{"text": "// Copyright (c) 2005 - 2009 Marc de Kamps, Dave Harrison\r\n// All rights reserved.\r\n//\r\n// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\r\n//\r\n//    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\r\n//    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation\r\n//      and/or other materials provided with the distribution.\r\n//    * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software\r\n//      without specific prior written permission.\r\n//\r\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\r\n// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY\r\n// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\r\n// USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\r\n// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n//\r\n//      If you use this software in work leading to a scientific publication, you should cite\r\n//      the 'currently valid reference', which can be found at http://miind.sourceforge.net\r\n#ifndef _CODE_LIBS_NUMTOOLSLIB_INTERPOLATION_INCLUDE_GUARD\r\n#define _CODE_LIBS_NUMTOOLSLIB_INTERPOLATION_INCLUDE_GUARD\r\n// Date:   9-02-2009\r\n// Author: Dave Harrison\r\n\r\n#include <valarray>\r\n#include <utility>\r\n#include <gsl/gsl_interp.h>\r\n\r\nnamespace NumtoolsLib\r\n{\r\n    //! Define types of interpolation\r\n    enum InterpType\r\n    {\r\n        INTERP_LINEAR,\r\n        INTERP_CSPLINE,\r\n        INTERP_AKIMA\r\n    };\r\n\r\n    class Interpolator\r\n    {\r\n        public:\r\n            /*!\r\n             Interpolator object to wrap GSL interpolation functions\r\n             interp_type Type of Interpolation to use: INTERP_LINEAR/_CSPLINE/_AKIMA\r\n             xs Array of x values\r\n             ys array of y values\r\n             Throws NumtoolsException on GSL error\r\n             */\r\n            Interpolator(const InterpType interp_type, const std::valarray<double>& xs,\r\n                    const std::valarray<double>& ys);\r\n\r\n            ~Interpolator();\r\n\r\n            /*!\r\n             Retrieve an interpolated y value for position x\r\n             Throws NumtoolsLibException on error\r\n             */\r\n            double InterpValue(const double x);\r\n\r\n        private:\r\n            //! The accelerator object\r\n            gsl_interp_accel*\t\t_acc;\r\n            //! The interpolation object\r\n            gsl_interp*\t\t\t\t_interp;\r\n            //! The x values\r\n            std::valarray<double>& _x;\r\n            //! The y values\r\n            std::valarray<double>& _y;\r\n            //! The size of the x & y arrays\r\n            const size_t\t\t\t_size;\r\n    };\r\n}\r\n\r\n#endif // include guard\r\n", "meta": {"hexsha": "c388f43e4053a9028b085b3ccc9b323439dad246", "size": 3357, "ext": "h", "lang": "C", "max_stars_repo_path": "libs/NumtoolsLib/Interpolation.h", "max_stars_repo_name": "dekamps/miind", "max_stars_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2015-09-15T17:28:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T20:26:47.000Z", "max_issues_repo_path": "libs/NumtoolsLib/Interpolation.h", "max_issues_repo_name": "dekamps/miind", "max_issues_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41.0, "max_issues_repo_issues_event_min_datetime": "2015-08-25T07:50:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T16:20:37.000Z", "max_forks_repo_path": "libs/NumtoolsLib/Interpolation.h", "max_forks_repo_name": "dekamps/miind", "max_forks_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-14T20:52:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T12:18:18.000Z", "avg_line_length": 44.76, "max_line_length": 163, "alphanum_fraction": 0.6690497468, "num_tokens": 679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.09401018850073228, "lm_q1q2_score": 0.04700509425036614}}
{"text": "// Copyright 2012 Jesse Windle - jesse.windle@gmail.com\r\n\r\n// This program is free software: you can redistribute it and/or\r\n// modify it under the terms of the GNU General Public License as\r\n// published by the Free Software Foundation, either version 3 of the\r\n// License, or (at your option) any later version.\r\n\r\n// This program is distributed in the hope that it will be useful, but\r\n// WITHOUT ANY WARRANTY; without even the implied warranty of\r\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n// General Public License for more details.\r\n\r\n// You should have received a copy of the GNU General Public License\r\n// along with this program.  If not, see\r\n// <http://www.gnu.org/licenses/>.\r\n\r\n/*********************************************************************\r\n\r\n  This class wraps GSL's random number generator and random\r\n  distribution functions into a class.  We use the Mersenne Twister\r\n  for random number generation since it has a large period, which is\r\n  what we want for MCMC simulation.\r\n\r\n  When compiling include -lgsl -lcblas -llapack .\r\n\r\n*********************************************************************/\r\n\r\n#ifndef __BASICRNG__\r\n#define __BASICRNG__\r\n\r\n#include <stdio.h>\r\n#include <gsl/gsl_rng.h>\r\n#include <gsl/gsl_randist.h>\r\n#include <gsl/gsl_cdf.h>\r\n#include <gsl/gsl_sf.h>\r\n\r\n#include <iostream>\r\n#include <fstream>\r\n#include <ctime>\r\n#include <string>\r\n#include <cmath>\r\n\r\nusing std::string;\r\nusing std::ofstream;\r\nusing std::ifstream;\r\n\r\n//////////////////////////////////////////////////////////////////////\r\n\t\t\t      // RNG //\r\n//////////////////////////////////////////////////////////////////////\r\n\r\nclass BasicRNG {\r\n\r\n protected:\r\n\r\n  gsl_rng * r;\r\n\r\n public:\r\n\r\n  // Constructors and destructors.\r\n  BasicRNG(unsigned long seed);\r\n\r\n  virtual ~BasicRNG()\r\n    { gsl_rng_free (r); }\r\n\r\n  // Assignment=\r\n  BasicRNG& operator=(const BasicRNG& rng);\r\n\r\n  // Read / Write / Set\r\n  bool read (const string& filename);\r\n  bool write(const string& filename);\r\n  void set(unsigned long seed);\r\n\r\n  // Get rng -- be careful.  Needed for other random variates.\r\n  gsl_rng* getrng() { return r; }\r\n\r\n  // Random variates.\r\n  double unif  ();                             // Uniform\r\n  double expon_mean(double mean);     // Exponential\r\n  double expon_rate(double rate);                  // Exponential\r\n  double chisq (double df);                    // Chisq\r\n  double norm  (double sd);                    // Normal\r\n  double norm  (double mean , double sd);      // Normal\r\n  double gamma_scale (double shape, double scale); // Gamma_Scale\r\n  double gamma_rate  (double shape, double rate);  // Gamma_Rate\r\n  double igamma(double shape, double scale);   // Inv-Gamma\r\n  double flat  (double a=0  , double b=1  );   // Flat\r\n  double beta  (double a=1.0, double b=1.0);   // Beta\r\n\r\n  int bern  (double p);                     // Bernoulli\r\n\r\n  // CDF\r\n  static double p_norm (double x, int use_log=0);\r\n  static double p_gamma_rate(double x, double shape, double rate, int use_log=0);\r\n\r\n  // Density\r\n  static double d_beta(double x, double a, double b);\r\n\r\n  // Utility\r\n  static double Gamma (double x, int use_log=0);\r\n\r\n}; // BasicRNG\r\n\r\n#endif\r\n\r\n////////////////////////////////////////////////////////////////////////////////\r\n\t\t\t\t // APPENDIX //\r\n////////////////////////////////////////////////////////////////////////////////\r\n\r\n// If you make everything inline within the same translation unit then that\r\n// function will not be callable from anohter translation unit.  You can see\r\n// that the function is missing by using the nm command.\r\n", "meta": {"hexsha": "7f4e4d2325ee598eba308e62c0838fc9f64856cb", "size": 3611, "ext": "h", "lang": "C", "max_stars_repo_path": "src/polyagamma/GRNG.h", "max_stars_repo_name": "TeoGiane/SPMIX", "max_stars_repo_head_hexsha": "d63dff8af7523fc1e8e11d2c2906daa16aaff4dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-22T09:35:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-22T09:35:09.000Z", "max_issues_repo_path": "src/polyagamma/GRNG.h", "max_issues_repo_name": "TeoGiane/SPMIX", "max_issues_repo_head_hexsha": "d63dff8af7523fc1e8e11d2c2906daa16aaff4dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/polyagamma/GRNG.h", "max_forks_repo_name": "TeoGiane/SPMIX", "max_forks_repo_head_hexsha": "d63dff8af7523fc1e8e11d2c2906daa16aaff4dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-18T21:31:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-18T21:31:01.000Z", "avg_line_length": 32.2410714286, "max_line_length": 82, "alphanum_fraction": 0.5768485184, "num_tokens": 791, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926344647597, "lm_q2_score": 0.10230471199815194, "lm_q1q2_score": 0.04597498404300801}}
{"text": "/**\n *\n * @file core_ssetvar.c\n *\n *  PLASMA core_blas kernel\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Mark Gates\n * @date 2010-11-15\n * @generated s Tue Jan  7 11:44:49 2014\n *\n **/\n#include <lapacke.h>\n#include \"common.h\"\n\n/***************************************************************************//**\n *\n * @ingroup CORE_float\n *\n * CORE_ssetvar sets a single variable, x := alpha.\n *\n *******************************************************************************\n *\n * @param[in] alpha\n *         Scalar to set x to, passed by pointer so it can depend on runtime value.\n *\n * @param[out] x\n *         On exit, x = alpha.\n *\n ******************************************************************************/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_ssetvar = PCORE_ssetvar\n#define CORE_ssetvar PCORE_ssetvar\n#endif\nvoid CORE_ssetvar(const float *alpha, float *x)\n{\n    *x = *alpha;\n}\n", "meta": {"hexsha": "6e87f5ee11b541a6c41848582a5cfb829f6da1fb", "size": 1014, "ext": "c", "lang": "C", "max_stars_repo_path": "core_blas/core_ssetvar.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "core_blas/core_ssetvar.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "core_blas/core_ssetvar.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7317073171, "max_line_length": 83, "alphanum_fraction": 0.5019723866, "num_tokens": 246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657966593214324, "lm_q2_score": 0.09534946811246837, "lm_q1q2_score": 0.04544161765984772}}
{"text": "/**\n *\n * @file core_dsetvar.c\n *\n *  PLASMA core_blas kernel\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Mark Gates\n * @date 2010-11-15\n * @generated d Tue Jan  7 11:44:49 2014\n *\n **/\n#include <lapacke.h>\n#include \"common.h\"\n\n/***************************************************************************//**\n *\n * @ingroup CORE_double\n *\n * CORE_dsetvar sets a single variable, x := alpha.\n *\n *******************************************************************************\n *\n * @param[in] alpha\n *         Scalar to set x to, passed by pointer so it can depend on runtime value.\n *\n * @param[out] x\n *         On exit, x = alpha.\n *\n ******************************************************************************/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_dsetvar = PCORE_dsetvar\n#define CORE_dsetvar PCORE_dsetvar\n#endif\nvoid CORE_dsetvar(const double *alpha, double *x)\n{\n    *x = *alpha;\n}\n", "meta": {"hexsha": "23c0d85255e074a71fd5777c201097e780952ed6", "size": 1017, "ext": "c", "lang": "C", "max_stars_repo_path": "core_blas/core_dsetvar.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "core_blas/core_dsetvar.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "core_blas/core_dsetvar.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8048780488, "max_line_length": 83, "alphanum_fraction": 0.5034414946, "num_tokens": 246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.09138211049075856, "lm_q1q2_score": 0.0446203671797267}}
{"text": "\n/*\n* -----------------------------------------------------------------\n*  Utilities Library --- util_lib.h\n*  Version: 1.6180\n*  Date: Feb 19, 2010\n* ----------------------------------------------------------------- \n*  Programmer: Americo Barbosa da Cunha Junior\n*              americo.cunhajr@gmail.com\n* -----------------------------------------------------------------\n*  Copyright (c) 2010 by Americo Barbosa da Cunha Junior\n*\n*  This program is free software: you can redistribute it and/or\n*  modify it under the terms of the GNU General Public License as\n*  published by the Free Software Foundation, either version 3 of\n*  the License, or (at your option) any later version.\n*\n*  This program is distributed in the hope that it will be useful,\n*  but WITHOUT ANY WARRANTY; without even the implied warranty of\n*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n*  GNU General Public License for more details.\n*\n*  A copy of the GNU General Public License is available in\n*  LICENSE.txt or http://www.gnu.org/licenses/.\n* -----------------------------------------------------------------\n*  This is the header file for a library with miscelaneous\n*  functions witch have a lot of applications.\n* -----------------------------------------------------------------\n*/\n\n\n\n\n#ifndef __UTIL_LIB_H__\n#define __UTIL_LIB_H__\n\n#include <time.h>\n\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_rng.h>\n\n\n\n\n/*\n*------------------------------------------------------------\n* function prototypes\n*------------------------------------------------------------\n*/\n\nint gsl_fprint_vector(FILE* file,\n                      gsl_vector *v);\n\nint gsl_print_vector(gsl_vector *v);\n\nint gsl_print_matrix_line(unsigned int i,\n                          gsl_matrix *M);\n\nint gsl_print_matrix_column(unsigned int j,\n                            gsl_matrix *M);\n\nint gsl_print_matrix(gsl_matrix *M);\n\nint gsl_rand_vector(gsl_rng *r,\n                    gsl_vector *v);\n\nint gsl_rand_matrix(gsl_rng *r,\n                    gsl_matrix *M);\n\nint gsl_diagonal_matrix(gsl_vector *v,\n                        gsl_matrix *D);\n\nvoid util_time_used(clock_t cpu_start,\n                    clock_t cpu_end,\n\t\t\t        time_t wall_start,\n                    time_t wall_end);\n\n#endif /* __UTIL_LIB_H__ */\n", "meta": {"hexsha": "9526673c0218e5502bac4668447091d250fdb1df", "size": 2310, "ext": "h", "lang": "C", "max_stars_repo_path": "CRFlowLib-1.0/include/util_lib.h", "max_stars_repo_name": "americocunhajr/CRFlowLib", "max_stars_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-29T12:56:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-29T12:56:14.000Z", "max_issues_repo_path": "CRFlowLib-1.0/include/util_lib.h", "max_issues_repo_name": "americocunhajr/CRFlowLib", "max_issues_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CRFlowLib-1.0/include/util_lib.h", "max_forks_repo_name": "americocunhajr/CRFlowLib", "max_forks_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-15T03:57:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-30T01:44:13.000Z", "avg_line_length": 28.875, "max_line_length": 68, "alphanum_fraction": 0.5350649351, "num_tokens": 469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.09138210492306811, "lm_q1q2_score": 0.0439071529706709}}
{"text": "/**\n *\n * @file qwrapper_zlacpy.c\n *\n *  PLASMA core_blas quark wrapper\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Julien Langou\n * @author Henricus Bouwmeester\n * @author Mathieu Faverge\n * @date 2010-11-15\n * @precisions normal z -> c d s\n *\n **/\n#include <lapacke.h>\n#include \"common.h\"\n\n/***************************************************************************//**\n *\n **/\nvoid QUARK_CORE_zlacpy(Quark *quark, Quark_Task_Flags *task_flags,\n                       PLASMA_enum uplo, int m, int n, int nb,\n                       const PLASMA_Complex64_t *A, int lda,\n                       PLASMA_Complex64_t *B, int ldb)\n{\n    DAG_CORE_LACPY;\n    QUARK_Insert_Task(quark, CORE_zlacpy_quark, task_flags,\n        sizeof(PLASMA_enum),                &uplo,  VALUE,\n        sizeof(int),                        &m,     VALUE,\n        sizeof(int),                        &n,     VALUE,\n        sizeof(PLASMA_Complex64_t)*nb*nb,    A,             INPUT,\n        sizeof(int),                        &lda,   VALUE,\n        sizeof(PLASMA_Complex64_t)*nb*nb,    B,             OUTPUT,\n        sizeof(int),                        &ldb,   VALUE,\n        0);\n}\n\n/***************************************************************************//**\n *\n **/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_zlacpy_quark = PCORE_zlacpy_quark\n#define CORE_zlacpy_quark PCORE_zlacpy_quark\n#endif\nvoid CORE_zlacpy_quark(Quark *quark)\n{\n    PLASMA_enum uplo;\n    int M;\n    int N;\n    const PLASMA_Complex64_t *A;\n    int LDA;\n    PLASMA_Complex64_t *B;\n    int LDB;\n\n    quark_unpack_args_7(quark, uplo, M, N, A, LDA, B, LDB);\n    LAPACKE_zlacpy_work(\n        LAPACK_COL_MAJOR,\n        lapack_const(uplo),\n        M, N, A, LDA, B, LDB);\n}\n\n/***************************************************************************//**\n *\n **/\nvoid QUARK_CORE_zlacpy_f1(Quark *quark, Quark_Task_Flags *task_flags,\n                          PLASMA_enum uplo, int m, int n, int nb,\n                          const PLASMA_Complex64_t *A, int lda,\n                          PLASMA_Complex64_t *B, int ldb,\n                          PLASMA_Complex64_t *fake1, int szefake1, int flag1)\n{\n    DAG_CORE_LACPY;\n    if ( fake1 == B ) {\n        QUARK_Insert_Task(quark, CORE_zlacpy_quark, task_flags,\n            sizeof(PLASMA_enum),                &uplo,  VALUE,\n            sizeof(int),                        &m,     VALUE,\n            sizeof(int),                        &n,     VALUE,\n            sizeof(PLASMA_Complex64_t)*nb*nb,    A,             INPUT,\n            sizeof(int),                        &lda,   VALUE,\n            sizeof(PLASMA_Complex64_t)*nb*nb,    B,             OUTPUT | flag1,\n            sizeof(int),                        &ldb,   VALUE,\n            0);\n    }\n    else {\n        QUARK_Insert_Task(quark, CORE_zlacpy_f1_quark, task_flags,\n            sizeof(PLASMA_enum),                &uplo,  VALUE,\n            sizeof(int),                        &m,     VALUE,\n            sizeof(int),                        &n,     VALUE,\n            sizeof(PLASMA_Complex64_t)*nb*nb,    A,             INPUT,\n            sizeof(int),                        &lda,   VALUE,\n            sizeof(PLASMA_Complex64_t)*nb*nb,    B,             OUTPUT,\n            sizeof(int),                        &ldb,   VALUE,\n            sizeof(PLASMA_Complex64_t)*szefake1, fake1,         flag1,\n            0);\n    }\n}\n\n/***************************************************************************//**\n *\n **/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_zlacpy_f1_quark = PCORE_zlacpy_f1_quark\n#define CORE_zlacpy_f1_quark PCORE_zlacpy_f1_quark\n#endif\nvoid CORE_zlacpy_f1_quark(Quark *quark)\n{\n    PLASMA_enum uplo;\n    int M;\n    int N;\n    const PLASMA_Complex64_t *A;\n    int LDA;\n    PLASMA_Complex64_t *B;\n    int LDB;\n    void *fake1;\n\n    quark_unpack_args_8(quark, uplo, M, N, A, LDA, B, LDB, fake1);\n    LAPACKE_zlacpy_work(\n        LAPACK_COL_MAJOR,\n        lapack_const(uplo),\n        M, N, A, LDA, B, LDB);\n}\n\n", "meta": {"hexsha": "affaaa47ba0e0b0a1359b09d07bb7604cb433f54", "size": 4095, "ext": "c", "lang": "C", "max_stars_repo_path": "core_blas-qwrapper/qwrapper_zlacpy.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "core_blas-qwrapper/qwrapper_zlacpy.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "core_blas-qwrapper/qwrapper_zlacpy.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0241935484, "max_line_length": 80, "alphanum_fraction": 0.4874236874, "num_tokens": 1110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.08632346894694785, "lm_q1q2_score": 0.04215031651113024}}
{"text": "/**\n *\n * @file core_zsetvar.c\n *\n *  PLASMA core_blas kernel\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Mark Gates\n * @date 2010-11-15\n * @precisions normal z -> c d s\n *\n **/\n#include <lapacke.h>\n#include \"common.h\"\n\n/***************************************************************************//**\n *\n * @ingroup CORE_PLASMA_Complex64_t\n *\n * CORE_zsetvar sets a single variable, x := alpha.\n *\n *******************************************************************************\n *\n * @param[in] alpha\n *         Scalar to set x to, passed by pointer so it can depend on runtime value.\n *\n * @param[out] x\n *         On exit, x = alpha.\n *\n ******************************************************************************/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_zsetvar = PCORE_zsetvar\n#define CORE_zsetvar PCORE_zsetvar\n#endif\nvoid CORE_zsetvar(const PLASMA_Complex64_t *alpha, PLASMA_Complex64_t *x)\n{\n    *x = *alpha;\n}\n", "meta": {"hexsha": "471291394850fa47c1df598e28b5d84818a4ae3d", "size": 1045, "ext": "c", "lang": "C", "max_stars_repo_path": "core_blas/core_zsetvar.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "core_blas/core_zsetvar.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "core_blas/core_zsetvar.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.487804878, "max_line_length": 83, "alphanum_fraction": 0.5177033493, "num_tokens": 256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250462027098473, "lm_q2_score": 0.09670579134361237, "lm_q1q2_score": 0.04085864364963803}}
{"text": "/**\n *\n * @file core_csetvar.c\n *\n *  PLASMA core_blas kernel\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Mark Gates\n * @date 2010-11-15\n * @generated c Tue Jan  7 11:44:49 2014\n *\n **/\n#include <lapacke.h>\n#include \"common.h\"\n\n/***************************************************************************//**\n *\n * @ingroup CORE_PLASMA_Complex32_t\n *\n * CORE_csetvar sets a single variable, x := alpha.\n *\n *******************************************************************************\n *\n * @param[in] alpha\n *         Scalar to set x to, passed by pointer so it can depend on runtime value.\n *\n * @param[out] x\n *         On exit, x = alpha.\n *\n ******************************************************************************/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_csetvar = PCORE_csetvar\n#define CORE_csetvar PCORE_csetvar\n#endif\nvoid CORE_csetvar(const PLASMA_Complex32_t *alpha, PLASMA_Complex32_t *x)\n{\n    *x = *alpha;\n}\n", "meta": {"hexsha": "be849ee98ba23a66a78388726fdeaf20138636e8", "size": 1053, "ext": "c", "lang": "C", "max_stars_repo_path": "core_blas/core_csetvar.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "core_blas/core_csetvar.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "core_blas/core_csetvar.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6829268293, "max_line_length": 83, "alphanum_fraction": 0.5204178538, "num_tokens": 264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.414898860266261, "lm_q2_score": 0.09670578548608504, "lm_q1q2_score": 0.04012312017933021}}
{"text": "/*\n *  specialfunctionsmodule.h\n *\n *  This file is part of NEST.\n *\n *  Copyright (C) 2004 The NEST Initiative\n *\n *  NEST is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 2 of the License, or\n *  (at your option) any later version.\n *\n *  NEST is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with NEST.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#ifndef SPECIALFUNCTIONSMODULE_H\n#define SPECIALFUNCTIONSMODULE_H\n/*\n    SLI Module implementing functions from the GNU Science Library.\n    The GSL is available from sources.redhat.com/gsl.\n*/\n\n/*\n    NOTE: Special functions are available only if the GSL is installed.\n          If no GSL is available, calling special functions will result\n          in a SLI error message.  HEP 2002-09-19.\n*/\n\n// Generated includes:\n#include \"config.h\"\n\n// Includes from sli:\n#include \"slifunction.h\"\n#include \"slimodule.h\"\n\n#ifdef HAVE_GSL\n// External include:\n#include <gsl/gsl_integration.h>\n#endif\n\n// NOTE: all gsl headers are included in specialfunctionsmodule.cc\n\nclass SpecialFunctionsModule : public SLIModule\n{\n\n  // Part 1: Methods pertaining to the module ----------------------\n\npublic:\n  SpecialFunctionsModule( void ){};\n  // ~SpecialFunctionsModule(void);\n\n  // The Module is registered by a call to this Function:\n  void init( SLIInterpreter* );\n\n  // This function will return the name of our module:\n  const std::string name( void ) const;\n\n\n  // Part 2: Classes for the implemented functions -----------------\n\n\npublic:\n  /**\n   * Classes which implement the GSL Funktions.\n   * These must be public, since we want to export\n   * objects of these.\n   */\n  class GammaIncFunction : public SLIFunction\n  {\n  public:\n    GammaIncFunction()\n    {\n    }\n    void execute( SLIInterpreter* ) const;\n  };\n  class LambertW0Function : public SLIFunction\n  {\n  public:\n    LambertW0Function()\n    {\n    }\n    void execute( SLIInterpreter* ) const;\n  };\n  class LambertWm1Function : public SLIFunction\n  {\n  public:\n    LambertWm1Function()\n    {\n    }\n    void execute( SLIInterpreter* ) const;\n  };\n\n  class ErfFunction : public SLIFunction\n  {\n  public:\n    ErfFunction()\n    {\n    }\n    void execute( SLIInterpreter* ) const;\n  };\n\n  class ErfcFunction : public SLIFunction\n  {\n  public:\n    ErfcFunction()\n    {\n    }\n    void execute( SLIInterpreter* ) const;\n  };\n\n  class GaussDiskConvFunction : public SLIFunction\n  {\n  public:\n    void execute( SLIInterpreter* ) const;\n\n    // need constructor and destructor to set up integration workspace\n    GaussDiskConvFunction( void );\n    ~GaussDiskConvFunction( void );\n\n  private:\n    // quadrature parameters, see GSL Reference\n    static const int MAX_QUAD_SIZE;\n    static const double QUAD_ERR_LIM;\n    static const double QUAD_ERR_SCALE;\n\n// integration workspace\n#ifdef HAVE_GSL\n    gsl_integration_workspace* w_;\n\n    /**\n     * Integrand function.\n     * @note This function must be static with C linkage so that it can\n     *       be passed to the GSL. Alternatively, one could define it\n     *       outside the class.\n     */\n    static double f_( double, void* );\n    static gsl_function F_; // GSL wrapper struct for it\n#endif\n  };\n\n  // Part 3: One instatiation of each new function class -----------\n\npublic:\n  const GammaIncFunction gammaincfunction;\n  const LambertW0Function lambertw0function;\n  const LambertWm1Function lambertwm1function;\n  const ErfFunction erffunction;\n  const ErfcFunction erfcfunction;\n  const GaussDiskConvFunction gaussdiskconvfunction;\n\n  // Part 3b: Internal variables\nprivate:\n};\n\n\n// Part 4: Documentation for all functions -------------------------\n\n/* BeginDocumentation\n\nName: Gammainc - incomplete gamma function\n\nSynopsis: x a Gammainc -> result\n\nDescription: Computes the incomplete Gamma function\n             int(t^(a-1)*exp(-t), t=0..x) / Gamma(a)\n\nParameters:  x      (double): upper limit of integration\n             a      (double): order of Gamma function\n\nExamples: 2.2 1.5 Gammainc -> 0.778615\n\nAuthor: H E Plesser\n\nFirstVersion: 2001-07-26\n\nRemarks: This is the incomplete Gamma function P(a,x) defined as no. 6.5.1\n         in Abramowitz&Stegun.  Requires the GSL.\n\nReferences: http://sources.redhat.com/gsl/ref\n*/\n\n/* BeginDocumentation\n\nName: Erf - error function\n\nSynopsis: x Erf -> result\n\nDescription: Computes the error function\n             erf(x) = 2/sqrt(pi) int_0^x dt exp(-t^2)\n\nParameters:  x (double): error function argument\n\nExamples: 0.5 erf -> 0.5205\n\nAuthor: H E Plesser\n\nFirstVersion: 2001-07-30\n\nRemarks: Requires the GSL.\n\nReferences: http://sources.redhat.com/gsl/ref\n\nSeeAlso: Erfc\n*/\n\n/* BeginDocumentation\n\nName: Erfc - complementary error function\n\nSynopsis: x Erfc -> result\n\nDescription: Computes the error function\n             erfc(x) = 1 - erf(x) = 2/sqrt(pi) int_x^inf dt exp(-t^2)\n\nParameters:  x (double): error function argument\n\nExamples: 0.5 erfc -> 0.4795\n\nAuthor: H E Plesser\n\nFirstVersion: 2001-07-30\n\nRemarks: Requires the GSL.\n\nReferences: http://sources.redhat.com/gsl/ref\n\nSeeAlso: Erf\n*/\n\n/* BeginDocumentation\n\nName:GaussDiskConv - Convolution of a Gaussian with an excentric disk\n\nSynopsis:R r0 GaussDiskConv -> result\n\nDescription:Computes the convolution of an excentric normalized Gaussian\nwith a disk\n\n       C[R, r0] = IInt[ disk(rvec; R) * Gauss(rvec - r_0vec) d^2rvec ]\n                = 2 Int[ r Exp[-r0^2-r^2] I_0[2 r r_0] dr, r=0..R]\n\nParameters:R   radius of the disk, centered at origin\nr0  distance of Gaussian center from origin\n\nExamples:SLI ] 3.2 2.3 GaussDiskConv =\n0.873191\n\nAuthor:H E Plesser\n\nFirstVersion: 2002-07-12\n\nRemarks:This integral is needed to compute the response of a DOG model to\n excentric light spots, see [1].  For technicalities, see [2].  Requires GSL.\n\nReferences: [1] G. T. Einevoll and P. Heggelund, Vis Neurosci 17:871-885 (2000).\n [2] Hans E. Plesser, Convolution of an Excentric Gaussian with a Disk,\n     Technical Report, arken.nlh.no/~itfhep, 2002\n\n*/\n\n#endif\n", "meta": {"hexsha": "d1bc798c4aaa9d2f2a616a101dcd5ea63a0c6cd8", "size": 6323, "ext": "h", "lang": "C", "max_stars_repo_path": "NEST-14.0-FPGA/sli/specialfunctionsmodule.h", "max_stars_repo_name": "OpenHEC/SNN-simulator-on-PYNQcluster", "max_stars_repo_head_hexsha": "14f86a76edf4e8763b58f84960876e95d4efc43a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 45.0, "max_stars_repo_stars_event_min_datetime": "2019-12-09T06:45:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T12:16:41.000Z", "max_issues_repo_path": "NEST-14.0-FPGA/sli/specialfunctionsmodule.h", "max_issues_repo_name": "zlchai/SNN-simulator-on-PYNQcluster", "max_issues_repo_head_hexsha": "14f86a76edf4e8763b58f84960876e95d4efc43a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-05-23T05:34:21.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-08T02:33:46.000Z", "max_forks_repo_path": "NEST-14.0-FPGA/sli/specialfunctionsmodule.h", "max_forks_repo_name": "OpenHEC/SNN-simulator-on-PYNQcluster", "max_forks_repo_head_hexsha": "14f86a76edf4e8763b58f84960876e95d4efc43a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-09T06:45:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-25T09:32:56.000Z", "avg_line_length": 23.5055762082, "max_line_length": 80, "alphanum_fraction": 0.6925510043, "num_tokens": 1682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.08389037953940537, "lm_q1q2_score": 0.03965359625569376}}
{"text": "/******************************************************************************\n * gsl_sprng.h: rewrite of gsl-sprng.h to use sprng streams                   *\n * Author: Yan Y. Liu <yanliu@illinois.edu>                                   *\n * Date: 2014/08/17                                                           *\n * Copyright and license of this source file are specified in LICENSE.TXT     *\n * under the root directory of this software package.                         *\n ******************************************************************************/\n\n/* \n * gsl-sprng.h: rewrite of gsl-sprng.h to use sprng streams\n * \n * This header file is based on  Darren Wilkinson's version for simple interface,\n * which does not use streams. We also refer to IceCube's C++ extension based on\n * sprng 4.0.\n * \n * Darren Wilkinson  http://www.staff.ncl.ac.uk/d.j.wilkinson/\n * IceCube project: http://icecube.wisc.edu/\n * \n * To use, just add the line:\n * #include \"gsl-sprng.h\"\n * immediately after the line:\n * #include <gsl/gsl_rng.h>\n * near the start of your code. \n * Make sure you alloc the rng on each processor. If you wish to\n * set a seed, you should set it to be the same on each processor.\n */\n\n#ifndef GSL_SPRNG_H\n#define GSL_SPRNG_H\n\n#define USE_MPI\n#include \"sprng.h\"\n\n/***************************/\n/* gsl definition of sprng */\n/***************************/\n\ntypedef struct\n{\n    int streamnum;\n    int nstreams;\n    int seed;\n    int *stream;\n} gsl_sprng_state_t;\n\n/* seed is gsl_rng_default_seed\n * either 0 by default or GSL_RNG_SEED environment variable\n */\nvoid sprng_set(void * vstate, unsigned long int seed);\n/* the get() function to get integer random number */\nunsigned long sprng_get(void * vstate);\n/* the get() function to get double random number */\ndouble sprng_get_double(void * vstate);\n\n/***************************/\n/*      gsl_sprng API      */\n/***************************/\n/* replace all gsl_rng_* func with corresponding one below */\n\n/* initialize gsl_rng */\ngsl_rng *gsl_sprng_alloc (int streamnum, int nstreams, int seed, int * stream);\n/* finalize gsl_rng */\nvoid gsl_sprng_free (gsl_rng * r);\n/* print out gsl_rng stream info for debug purpose */\nvoid gsl_sprng_print (gsl_rng * r);\n/* load gsl_rng from a file */\nint gsl_sprng_fread (char * fpath, gsl_rng * r);\n/* store gsl_rng to a file */\nint gsl_sprng_fwrite (char * fpath, const gsl_rng * r);\n#endif\n\n", "meta": {"hexsha": "9f3a5b0d7fc314c7afb78d2d4cce8d69fb0576b4", "size": 2402, "ext": "h", "lang": "C", "max_stars_repo_path": "pgap/gsl-sprng.h", "max_stars_repo_name": "ElsevierSoftwareX/SOFTX_2018_242", "max_stars_repo_head_hexsha": "9a7d7c02b2f1d7b6bfd1b08fbb2150c30ddd1046", "max_stars_repo_licenses": ["NCSA", "BSD-3-Clause"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2015-07-16T01:05:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-28T15:38:19.000Z", "max_issues_repo_path": "pgap/gsl-sprng.h", "max_issues_repo_name": "ElsevierSoftwareX/SOFTX-D-15-00005", "max_issues_repo_head_hexsha": "bb0c21ca479db5ac3ecf789ab280d5e45c3c7805", "max_issues_repo_licenses": ["NCSA", "BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-07-25T02:25:20.000Z", "max_issues_repo_issues_event_max_datetime": "2016-07-25T17:38:26.000Z", "max_forks_repo_path": "pgap/gsl-sprng.h", "max_forks_repo_name": "ElsevierSoftwareX/SOFTX-D-15-00005", "max_forks_repo_head_hexsha": "bb0c21ca479db5ac3ecf789ab280d5e45c3c7805", "max_forks_repo_licenses": ["NCSA", "BSD-3-Clause"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2015-10-28T15:28:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-17T14:29:16.000Z", "avg_line_length": 33.3611111111, "max_line_length": 81, "alphanum_fraction": 0.5840965862, "num_tokens": 560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.0803574677210091, "lm_q1q2_score": 0.03923721717618976}}
{"text": "/* Siconos-Numerics, Copyright INRIA 2005-2018.\n * Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n * Siconos is a free software; you can redistribute it and/or modify\n * it under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n * Siconos is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with Siconos; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\n * Contact: Vincent ACARY, siconos-team@lists.gforge.inria.fr\n */\n\n#ifndef SiconosBlas_H\n#define SiconosBlas_H\n#include \"SiconosConfig.h\"\n\n#if defined(__cplusplus)\nextern \"C\"\n{\n#endif\n\n// tells include-what-you-use to keep this file\n// and not to suggest cblas.h or alike.\n// IWYU pragma: begin_exports\n#if defined(HAS_MKL_CBLAS)\n#include <mkl_cblas.h>\n#elif defined(HAS_MATLAB_BLAS)\n#include <blas.h>\n#define cblas_daxpy daxpy\n#define cblas_dcopy dcopy\n#define cblas_ddot ddot\n#define cblas_dgemm dgemm\n#define cblas_dgemv dgemv\n#define cblas_dnrm2 dnrm2\n#define cblas_dscal dscal\n#else\n#include <cblas.h>\n#endif\n// IWYU pragma: end_exports\n\n#ifdef __cplusplus\n}\n#undef restrict\n#define restrict __restrict\n#endif\n\n\nstatic inline double* NMD_row_rmajor(double* restrict mat, unsigned ncols, unsigned rindx)\n{\n  return &mat[rindx*ncols];\n}\n\nstatic inline void NMD_copycol_rmajor(int nrows, double* col, double* restrict mat, int ncols, unsigned cindx)\n{\n  cblas_dcopy(nrows, col, 1, &mat[cindx], ncols);\n}\n\nstatic inline void NMD_dense_gemv(int nrows, int ncols, double alpha, double* restrict mat, double* restrict y, double beta, double* restrict x)\n{\n  cblas_dgemv(CblasColMajor, CblasTrans, ncols, nrows, alpha, mat, ncols, y, 1, beta, x, 1);\n}\n\n#endif // SiconosBlas_H\n\n\n", "meta": {"hexsha": "06878852c3ac21672d9a191ce8bed3f8d4f19ec9", "size": 2152, "ext": "h", "lang": "C", "max_stars_repo_path": "externals/blas_lapack/SiconosBlas.h", "max_stars_repo_name": "fperignon/sandbox", "max_stars_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "externals/blas_lapack/SiconosBlas.h", "max_issues_repo_name": "fperignon/sandbox", "max_issues_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "externals/blas_lapack/SiconosBlas.h", "max_forks_repo_name": "fperignon/sandbox", "max_forks_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4794520548, "max_line_length": 144, "alphanum_fraction": 0.7597583643, "num_tokens": 594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769844, "lm_q2_score": 0.08035747047400407, "lm_q1q2_score": 0.03892355832048338}}
{"text": "#include <petsc.h>\n\n#undef __FUNCT__\n#define __FUNCT__ \"main\"\nint main(int argc,char **args)\n{\n\n  PetscErrorCode ierr;\n\n  PetscInitialize(&argc,&args,(char*)0,(char*)0);\n\n  ierr = PetscPrintf(PETSC_COMM_WORLD,\" === Hello from Petsc! ===\\n\");CHKERRQ(ierr);\n\n  ierr = PetscFinalize();\n  \n  return 0;\n}\n", "meta": {"hexsha": "3c59dc23a738a7c19c234989acabf10c3956e40f", "size": 300, "ext": "c", "lang": "C", "max_stars_repo_path": "with_makefile/hellopetsc.c", "max_stars_repo_name": "lukaspospisil/hello_petsc", "max_stars_repo_head_hexsha": "64f4e067d173b1ad7d54bd1fa1a6ec2ba5c47eac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "with_makefile/hellopetsc.c", "max_issues_repo_name": "lukaspospisil/hello_petsc", "max_issues_repo_head_hexsha": "64f4e067d173b1ad7d54bd1fa1a6ec2ba5c47eac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "with_makefile/hellopetsc.c", "max_forks_repo_name": "lukaspospisil/hello_petsc", "max_forks_repo_head_hexsha": "64f4e067d173b1ad7d54bd1fa1a6ec2ba5c47eac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.6666666667, "max_line_length": 84, "alphanum_fraction": 0.6666666667, "num_tokens": 86, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3738758227716966, "lm_q2_score": 0.10374862132405092, "lm_q1q2_score": 0.03878910115895873}}
{"text": "/* bcls.c\n   $Revision: 282 $ $Date: 2006-12-17 17:38:00 -0800 (Sun, 17 Dec 2006) $\n\n   ---------------------------------------------------------------------\n   This file is part of BCLS (Bound-Constrained Least Squares).\n\n   Copyright (C) 2006 Michael P. Friedlander, Department of Computer\n   Science, University of British Columbia, Canada. All rights\n   reserved. E-mail: <mpf@cs.ubc.ca>.\n\n   BCLS is free software; you can redistribute it and/or modify it\n   under the terms of the GNU Lesser General Public License as\n   published by the Free Software Foundation; either version 2.1 of the\n   License, or (at your option) any later version.\n\n   BCLS is distributed in the hope that it will be useful, but WITHOUT\n   ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n   or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General\n   Public License for more details.\n\n   You should have received a copy of the GNU Lesser General Public\n   License along with BCLS; if not, write to the Free Software\n   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301\n   USA\n   ---------------------------------------------------------------------\n*/\n/*!\n  \\file\n  BCLS user-callable library routines.\n*/\n\n#include <cblas.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <float.h>\n#include <math.h>\n#include <assert.h>\n#include <setjmp.h>\n\n#include \"bcls.h\"\n#include \"bclib.h\"\n#include \"bcsolver.h\"\n#include \"bcversion.h\"\n\n/*!\n\n  \\brief Malloc wrapper.  Private to this file.\n\n  Pointer to the newly allocated memory,\n  or NULL if malloc returned an eror.\n  \n  \\param[in]  len   Number of elements needed\n  \\param[in]  size  Memory needed for each element.\n  \\param[in]  who   Short character description of the memory needed.\n  \n  \\return Pointer to the newly allocated memory.\n\n*/\nstatic void *\nxmalloc (int len, size_t size, char * who)\n{\n    register void *value = malloc(len * size);\n    if (value == NULL)\n\tfprintf( stderr, \"Not enough memory to allocate %s.\\n\", who );\n    return value;\n}\n\n/*!\n\n  \\brief Create a BCLS problem instance.\n\n  This routine create a BCLS problem.  It *must* be called before any\n  other BCLS routine.  It will create and initialize a new BCLS\n  problem with enough space to accomodate the specified problem.  The\n  problem is then initialized using bcls_init_prob.\n\n  In order to re-initialize the BCLS problem instance, but not\n  deallocate memory that's already sufficient for an equal or smaller\n  size problem, use bcls_init_prob.\n\n  \\param[in] mmax  Maximum number of rows    in any A.\n  \\param[in] nmax  Maximum number of columns in any A.\n\n  \\return Return a pointer to a new BCLS problem.  If the return is\n  NULL, then the initialization failed.\n\n*/\nBCLS *\nbcls_create_prob( int mmax, int nmax )\n{\n    int mnmax = imax( nmax, mmax );\n\n    assert( mmax > 0 && nmax > 0 );\n    \n    // Allocate the problem.\n    BCLS *ls = (BCLS *)xmalloc(1, sizeof(BCLS), \"ls\" );\n\n    // Check if the problem has been successfully allocated.\n    if (ls == NULL) {\n\tfprintf( stderr, \"XXX Could not allocate a BCLS problem.\\n\");\n\treturn ls;\n    }\n\n    // -----------------------------------------------------------------\n    // Allocate workspace vectors large enough to accomdate the problem.\n    // -----------------------------------------------------------------\n\n    // Record the maximum alloted workspace.\n    ls->mmax = mmax;\n    ls->nmax = nmax;\n\n    // Residual: r(m+n).\n    ls->r = (double *)xmalloc( mmax+nmax, sizeof(double), \"r\" );\n    if (ls->r == NULL) goto error;\n\n    // Gradient: g(n).\n    ls->g = (double *)xmalloc( nmax, sizeof(double), \"g\" );\n    if (ls->g == NULL) goto error;\n\n    // Search direction, full space: dx(n).\n    ls->dx = (double *)xmalloc( nmax, sizeof(double), \"dx\" );\n    if (ls->dx == NULL) goto error;\n\n    // Search direction, subspace: dxFree(n).\n    ls->dxFree = (double *)xmalloc( nmax, sizeof(double), \"dxFree\" );\n    if (ls->dxFree == NULL) goto error;\n\n    // Step to each breakpoint: aBreak(n).\n    ls->aBreak = (double *)xmalloc( nmax, sizeof(double), \"aBreak\" );\n    if (ls->aBreak == NULL) goto error;\n\n    // Indices of each breakpoint: iBreak(n).\n    ls->iBreak = (int *)xmalloc( nmax, sizeof(int), \"iBreak\" );\n    if (ls->iBreak == NULL) goto error;\n\n    // Variable indices: ix(n).\n    ls->ix = (int *)xmalloc( nmax, sizeof(int), \"ix\" );\n    if (ls->ix == NULL) goto error;\n\n    // Workspace: wrk_v( max(n, m) ).\n    ls->wrk_u = (double *)xmalloc( mnmax, sizeof(double), \"wrk_u\" );\n    if (ls->wrk_u == NULL) goto error;\n\n    // Workspace: wrk_v( max(n, m) ).\n    ls->wrk_v = (double *)xmalloc( mnmax, sizeof(double), \"wrk_v\" );\n    if (ls->wrk_v == NULL) goto error;\n\n    // Workspace: wrk_w( max(n, m) ).\n    ls->wrk_w = (double *)xmalloc( mnmax, sizeof(double), \"wrk_w\" );\n    if (ls->wrk_w == NULL) goto error;\n\n    // -----------------------------------------------------------------\n    // Initialize this new problem instance.\n    // -----------------------------------------------------------------\n    bcls_init_prob( ls );\n\n    // -----------------------------------------------------------------\n    // Exits.\n    // -----------------------------------------------------------------\n\n    // Successfull exit.\n    return ls;\n\n error:\n    // Unsuccessful exit.\n    bcls_free_prob( ls );\n    return ls;\n}\n\n/*!\n\n  \\brief Initialize a BCLS problem.\n  \n  Initialize a BCLS problem.  You can call this routine to \"reset\" a\n  BCLS problem, i.e., reset all parameter values.  Note that it is\n  automatically called by bcls_create_prob.\n\n  \\param[in,out] ls  BCLS problem context.\n\n*/\nvoid\nbcls_init_prob( BCLS *ls )\n{\n    // Some quick error checking.\n    assert( ls->mmax > 0 && ls->nmax > 0 );\n\n    // Check if the problem has been successfully allocated.\n    if (ls == NULL) {\n\tfprintf( stderr, \"XXX The BCLS problem is NULL.\\n\");\n\treturn;\n    }\n    \n    // Initialize the problem structure.\n    ls->print_info    =  NULL;\n    ls->print_hook    =  NULL;\n    ls->fault_info    =  NULL;\n    ls->fault_hook    =  NULL;\n    ls->Aprod         =  NULL;\n    ls->Usolve        =  NULL;\n    ls->CallBack      =  NULL;\n    ls->UsrWrk        =  NULL;\n    ls->anorm         =  NULL;\n    ls->print_level   =  1;\n    ls->proj_search   =  BCLS_PROJ_SEARCH_EXACT;\n    ls->newton_step   =  BCLS_NEWTON_STEP_LSQR;\n    ls->minor_file    =  NULL;\n    ls->itnMaj        =  0;\n    ls->itnMajLim     =  5  * (ls->nmax);\n    ls->itnMin        =  0;\n    ls->itnMinLim     =  10 * (ls->nmax);\n    ls->nAprodT       =  0;\n    ls->nAprodF       =  0;\n    ls->nAprod1       =  0;\n    ls->nUsolve       =  0;\n    ls->m             =  0;\n    ls->n             =  0;\n    ls->unconstrained =  0;\n    ls->damp          =  0.0;\n    ls->damp_min      =  1.0e-4;\n    ls->exit          =  BCLS_EXIT_UNDEF;\n    ls->soln_rNorm    = -1.0;\n    ls->soln_dInf     =  0.0;\n    ls->soln_jInf     = -1;\n    ls->soln_stat     =  BCLS_SOLN_UNDEF;\n    ls->optTol        =  1.0e-6;\n    ls->conlim        =  1.0 / ( 10.0 * sqrt( DBL_EPSILON ) );\n    ls->mu            =  1.0e-2;\n    ls->backtrack     =  1.0e-1;\n    ls->backtrack_limit = 10;\n\n    // Initialize timers.\n    bcls_timer( &(ls->stopwatch[BCLS_TIMER_TOTAL] ),  BCLS_TIMER_INIT );\n    ls->stopwatch[BCLS_TIMER_TOTAL].name = \"Total time\";\n\n    bcls_timer( &(ls->stopwatch[BCLS_TIMER_APROD] ),  BCLS_TIMER_INIT );\n    ls->stopwatch[BCLS_TIMER_APROD].name = \"Total time for Aprod\";\n\n    bcls_timer( &(ls->stopwatch[BCLS_TIMER_USOLVE] ),  BCLS_TIMER_INIT );\n    ls->stopwatch[BCLS_TIMER_USOLVE].name = \"Total time for Usolve\";\n\n    bcls_timer( &(ls->stopwatch[BCLS_TIMER_LSQR] ),  BCLS_TIMER_INIT );\n    ls->stopwatch[BCLS_TIMER_LSQR].name = \"Total time for LSQR\";\n\n    // Initialize constants.\n    ls->eps         = DBL_EPSILON;\n    ls->eps2        = pow( DBL_EPSILON, 0.50 );\n    ls->eps3        = pow( DBL_EPSILON, 0.75 );\n    ls->epsx        = ls->eps3;\n    ls->epsfixed    = DBL_EPSILON;\n    ls->BigNum      = BCLS_INFINITY;\n\n    return;\n}\n\n/*!\n\n  \\brief Free and reinitialize all resources in an existing BCLS problem.\n\n  \\return\n  - 0: no errors\n  - 1: the BCLS problem is NULL (ie, does not exist).\n\n*/\nint\nbcls_free_prob( BCLS *ls )\n{\n    // Report an error if it's already NULL.\n    if (ls == NULL) return 1;\n\n    // Deallocate the workspace.\n    assert( ls->r       != NULL ); free( ls->r       );\n    assert( ls->g       != NULL ); free( ls->g       );\n    assert( ls->dx      != NULL ); free( ls->dx      );\n    assert( ls->dxFree  != NULL ); free( ls->dxFree  );\n    assert( ls->aBreak  != NULL ); free( ls->aBreak  );\n    assert( ls->iBreak  != NULL ); free( ls->iBreak  );\n    assert( ls->ix      != NULL ); free( ls->ix      );\n    assert( ls->wrk_u   != NULL ); free( ls->wrk_u   );\n    assert( ls->wrk_v   != NULL ); free( ls->wrk_v   );\n    assert( ls->wrk_w   != NULL ); free( ls->wrk_w   );\n    \n    // Deallocate the BCLS problem.\n    free( ls );\n    \n    return 0;\n}\n\n/*!\n\n  \n  \\brief Install a print-hook routine.\n\n  This routine installs a user-defined print-hook routine.\n  \n  The parameter info is a transit pointer passed to the hook routine.\n  \n  The parameter hook is an entry point to the user-defined print-hook\n  routine. This routine is called by the routine \"print\" every time an\n  informative message should be output. The routine \"print\" passes to\n  the hook routine the transit pointer info and the character string\n  msg, which contains the message. If the hook routine returns zero,\n  the routine print prints the message in an usual way. Otherwise, if\n  the hook routine returns non-zero, the message is not printed.\n  \n  In order to uninstall the hook routine the parameter hook should be\n  specified as NULL (in this case the parameter info is ignored).\n\n  \\param[in,out] ls    BCLS problem context.\n  \\param[in]     info  Transit pointer passed to the hook routine.\n  \\param[in]     hook  Pointer to the print-hook routine.\n\n*/\nvoid\nbcls_set_print_hook( BCLS *ls,\n\t\t     void *info,\n\t\t     int (*hook)(void *info, char *msg))\n{\n    ls->print_info = info;\n    ls->print_hook = hook;\n    return;\n}\n\n/*!\n\n  \\brief Install a fault-hook routine.\n\n  This routine installs a user-defined fault-hook routine.\n\n  The parameter info is a transit pointer passed to the hook routine.\n\n  The parameter \"hook\" is an entry point to the user-defined\n  fault-hook routine. This routine is called by the routine\n  \"bcls_fault\" every time an error message should be output. The\n  routine \"bcls_fault\" passes to the hook routine the transit pointer\n  info and the character string msg, which contains the message. If\n  the hook routine returns zero, the routine print prints the message\n  in an usual way. Otherwise, if the hook routine returns non-zero,\n  the message is not printed.\n\n  In order to uninstall the hook routine the parameter hook should be\n  specified as NULL (in this case the parameter info is ignored).\n\n  \\param[in,out] ls    BCLS problem context.\n  \\param[in]     info  Transit pointer passed to the hook routine.\n  \\param[in]     hook  Pointer to the fault-hook routine.\n\n*/\nvoid\nbcls_set_fault_hook( BCLS *ls,\n\t\t     void *info,\n\t\t     int (*hook)(void *info, char *msg))\n{\n    ls->fault_info = info;\n    ls->fault_hook = hook;\n    return;\n}\n\n/*!\n\n  \\brief Give BCLS access to set of column weights.\n\n  Define a set of column weights.  BCLS will use these to scale the\n  steepest-descent steps.\n\n  \\param[in,out] ls     BCLS problem context.\n  \\param[in]     anorm  Array of columns norms of A.\n\n*/\nvoid\nbcls_set_anorm( BCLS *ls,\n                double anorm[] )\n{\n    ls->anorm = anorm;\n    return;\n}\n\n/*!\n\n  \\brief Install a user-defined preconditioning routine.\n \n  Replace each subproblem\n  \\f[\n  \\def\\minimize{\\displaystyle\\mathop{\\hbox{minimize}}}\n  \\minimize_x \\| Ax - b \\|\n  \\f]\n  with\n  \\f[\n  \\def\\minimize{\\displaystyle\\mathop{\\hbox{minimize}}}\n  \\minimize_y \\| AU^{-1}y - b \\|\n  \\quad\\mbox{with}\\quad\n  Ux = y.\n  \\f]\n\n  \\param[in,out]  ls     BCLS problem context.\n  \\param[in]      Usolve Pointer to the user's preconditioning routine.\n\n*/\nvoid\nbcls_set_usolve( BCLS *ls,\n                 int (*Usolve)( int mode, int m, int n, int nix,\n                                int ix[], double v[], double w[],\n                                void *UsrWrk ) )\n{\n    assert( Usolve != NULL );\n    ls->Usolve = Usolve;\n    return;\n}\n\n\n/*!\n\n  \\brief Compute the column norms of A.\n\n  Compute the columns norms of A.  Each column of A is generated by\n  multiplying A by a unit vector.  The two-norm squared of each\n  column is stored in aprod.\n  \n  This routine must be called *after* bcls_create_prob.  (As with any\n  other BCLS routine.)\n\n  \\param[in]      ls      BCLS problem context.\n  \\param[in]      m       Number of rows in A.\n  \\param[in]      n       Number of columns in A.\n  \\param[in]      Aprod   User's matrix-product routine.\n  \\param[in,out]  UsrWrk  Pointer to user's workspace (could be NULL).\n  \\param[out]     anorm   Vector of column norms of A.\n  \n  \\return Returns any error codes returned by the user's aprod\n  routine.\n\n*/\nint\nbcls_compute_anorm( BCLS *ls, int n, int m,\n                    int (*Aprod)\n                    ( int mode, int m, int n, int nix,\n                      int ix[], double x[], double y[], void *UsrWrk ),\n                    void *UsrWrk,\n                    double anorm[] )\n{    \n    // Make sure that the problem instance has been created.\n    assert( ls    != NULL );\n    assert( anorm != NULL );\n\n    int j;\n    int err;\n    const int mode = 1;         // Always:  aj = A*ej.\n    const int nix  = 1;         // Only one column is ever needed.\n    int    *ix = ls->ix;\n    double *e  = ls->wrk_u;\n    double *aj = ls->wrk_v;\n\n    bcls_dload( n, 1.0, e, 1 );\n    \n    for (j = 0; j < n; j++) {\n\n        // Multiply A times the jth unit vector.\n        ix[0] = j;\n        \n        // aj <- A * ej.\n        err = Aprod( mode, m, n, nix, ix, e, aj, UsrWrk );\n\n        // Exit if Aprod returned an error.\n        if (err) break;\n\n        // Compute the norm of aj and store it in anorm.\n        anorm[j] = cblas_dnrm2( m, aj, 1 );\n\n        // Make sure that the column norm is too small.\n        anorm[j] = fmax( BCLS_MIN_COLUMN_NORM, anorm[j] );\n    }\n\n    return err;\n}\n\n/*!\n\n  \\brief Load the problem into the BCLS data structure.\n\n  The routiens loads the complete problem description into a BCLS\n  problem instance.  No work is really being done: only the various\n  structure elements are being set to point to the right places.\n\n  \\param[in,out]  ls      BCLS problem context.\n  \\param[in]      m       Number of rows in A.  Note: m <= mmax.\n  \\param[in]      n       Number of columns in A.  Note: n <= nmax.\n  \\param[in]      Aprod   Hook to user's matrix-vector product routine.\n  \\param[in,out]  UsrWrk  Transit pointer passed directly to Aprod/Usolve.\n  \\param[in]      damp    Regularization parameter.\n  \\param[in,out]  x       The starting point.\n  \\param[in]      b       The RHS vector.\n  \\param[in]      c       Defines a linear term (set to NULL if one doesn't exist).\n  \\param[in]      bl      Lower bounds on x.\n  \\param[in]      bu      Upper bounds on x.\n\n*/\nvoid\nbcls_set_problem_data( BCLS *ls, int m, int n,\n\t\t       int (*Aprod)( int mode, int m, int n, int nix,\n\t\t\t\t     int ix[], double x[], double y[],\n\t\t\t\t     void *UsrWrk ),\n\t\t       void *UsrWrk, double damp,\n\t\t       double x[], double b[], double c[],\n\t\t       double bl[], double bu[] )\n{\n    assert( m <= ls->mmax );\n    assert( n <= ls->nmax );\n\n    assert( Aprod  != NULL ); ls->Aprod  = Aprod;\n    assert( m      >= 0    ); ls->m      = m;\n    assert( n      >= 0    ); ls->n      = n;\n                              ls->UsrWrk = UsrWrk;\n    assert( damp   >= 0.0  ); ls->damp   = damp;\n    assert( x      != NULL ); ls->x      = x;\n    assert( b      != NULL ); ls->b      = b;\n                              ls->c      = c;\n    assert( bl     != NULL ); ls->bl     = bl;\n    assert( bu     != NULL ); ls->bu     = bu;\n\n    return;\n}\n\n/*!\n\n  \\brief Return an exit message.\n\n  \\param[in] flag  The code of the error.\n\n  \\return Error messsage.\n\n*/\nchar *\nbcls_exit_msg( int flag )\n{\n    char *msg;\n\n    if      (flag==BCLS_EXIT_CNVGD)  msg=\"Optimal solution found\";\n    else if (flag==BCLS_EXIT_MAJOR)  msg=\"Too many major iterations\";\n    else if (flag==BCLS_EXIT_MINOR)  msg=\"Too many minor iterations\";\n    else if (flag==BCLS_EXIT_UNBND)  msg=\"Found direction of infinite descent\";\n    else if (flag==BCLS_EXIT_INFEA)  msg=\"Bounds are inconsistent\";\n    else if (flag==BCLS_EXIT_APROD)  msg=\"Aprod requested immediate exit\";\n    else if (flag==BCLS_EXIT_USOLVE) msg=\"Usolve requested immediate exit\";\n    else if (flag==BCLS_EXIT_CALLBK) msg=\"CallBack requested immediate exit\";\n    else                             msg=\"Undefined exit\";\n\n    return msg;\n}\n\n/*!\n\n  \\brief Solve the current problem instance.\n\n  \\return\n   -  #BCLS_EXIT_CNVGD (0) - Successful exit.  Found an optimal solution.\n   -  #BCLS_EXIT_MAJOR     - Too many major iterations.\n   -  #BCLS_EXIT_MINOR     - Too many inner iterations.\n   -  #BCLS_EXIT_UNBND     - Found direction of infinite descent.\n   -  #BCLS_EXIT_INFEA     - Bounds are inconsistent.\n   -  #BCLS_EXIT_APROD     - Aprod  requested immediate exit.\n   -  #BCLS_EXIT_USOLVE    - Usolve requested immediate exit.\n\n*/\nint\nbcls_solve_prob( BCLS *ls )\n{\n    int err;\n    int jpInf;\n    const int preconditioning = ls->Usolve != NULL;\n    double pInf, timeTot;\n    double bNorm;  // Norm of the RHS (or 1.0, which ever is bigger).\n    BCLS_timer watch;\n\n    // Print the banner.\n    //PRINT1(\" ----------------------------------------------------\\n\");\n    //PRINT1(\" BCLS -- Bound-Constrained Least Squares, Version %s\\n\",\n    //      bcls_version_info() );\n    //PRINT1(\" Compiled on %s\\n\",  bcls_compilation_info() );\n    //PRINT1(\" ----------------------------------------------------\\n\");\n\n    // -----------------------------------------------------------------\n    // Print parameters and diagnostic information.\n    // -----------------------------------------------------------------\n    bcls_print_params( ls );\n\n    // Examine the bounds and print a summary about them.\n    // Also check if the problem is feasible!\n    err = bcls_examine_bnds( ls, ls->n, ls->bl, ls->bu );\n    if (err) {\n\tls->exit = err;\n        goto direct_exit;\n    }\n\n    // Set the return for longjmp.  First call to setjmp returns 0.\n    err = setjmp(ls->jmp_env);\n    if (err) {\n        ls->exit = err;\n        goto direct_exit;\n    }\n\n    // Compute and print some statistics about the column scales.\n    bcls_examine_column_scales( ls, ls->anorm );\n\n    // Print a log header.\n    //    PRINT1(\"\\n %5s  %5s    %9s  %9s  %11s  %9s %7s %7s %7s\\n\",\n    //\t   \"Major\",\"Minor\",\"Residual\",\"xNorm\",\"Optimal\",\n    //\t   ls->newton_step == BCLS_NEWTON_STEP_LSQR\n    //\t   ? \"LSQR\" : \"CGLS\",\n    //\t   \"nSteps\", \"Free\", \"OptFac\");\n\n    // -----------------------------------------------------------------\n    // Call the BCLS solver.\n    // -----------------------------------------------------------------\n    bcls_timer( &(ls->stopwatch[BCLS_TIMER_TOTAL]), BCLS_TIMER_START );\n\n    bcls_solver( ls, ls->m, ls->n, &bNorm,\n\t\t ls->x, ls->b, ls->c, ls->bl, ls->bu, ls->r, ls->g,\n\t\t ls->dx, ls->dxFree, ls->ix,\n\t\t ls->aBreak, ls->iBreak, ls->anorm );\n\n    bcls_timer( &(ls->stopwatch[BCLS_TIMER_TOTAL]), BCLS_TIMER_STOP );\n\n\n    // =================================================================\n    // Exits.\n    // =================================================================\n direct_exit:\n    // -----------------------------------------------------------------\n    // Check feasibility and print a solution summary (iterations, etc.)\n    // -----------------------------------------------------------------\n    bcls_primal_inf( ls->n, ls->x, ls->bl, ls->bu, &pInf, &jpInf );\n\n    //PRINT1(\"\\n\");\n    //    PRINT1(\" BCLS Exit %4d -- %s\\n\",ls->exit, bcls_exit_msg(ls->exit));\n    //PRINT1(\"\\n\");\n    //PRINT1(\" No. of iterations      %8d %7s\", ls->itnMin, \"\");\n    //PRINT1(\" Objective value       %17.9e\\n\", ls->soln_obj  );\n    //PRINT1(\" No. of major iterations%8d %7s\", ls->itnMaj, \"\");\n    //PRINT1(\" Optimality           (%7d) %8.1e\\n\",\n    //\t   ls->soln_jInf,ls->soln_dInf);\n    //PRINT1(\" No. of calls to Aprod  %8d\", ls->nAprodT);\n\n    //if (ls->proj_search == BCLS_PROJ_SEARCH_EXACT)\n    //   PRINT1(\" (%5d)\", ls->nAprod1 );\n    //else\n    //  PRINT1(\"  %5s \", \"\");\n    // PRINT1(\" Norm of RHS            %16.1e\\n\", bNorm);\n    // if (pInf > ls->eps)\n    //  PRINT1(\" Feasibility          (%7d) %7.1e\\n\", jpInf, pInf);\n    //if (preconditioning)\n    //  PRINT1(\" No. of calls to Usolve %8d\\n\", ls->nUsolve);\n    //PRINT1(\"\\n\");\n\n    // -----------------------------------------------------------------\n    // Print timing statistics.\n    // -----------------------------------------------------------------\n    //timeTot = fmax(ls->eps,ls->stopwatch[BCLS_TIMER_TOTAL].total);\n\n    //watch   = ls->stopwatch[BCLS_TIMER_TOTAL];\n    //timeTot = fmax(1e-6, watch.total); // Safeguard against timeTot = 0.\n\n    //PRINT1(\" %-25s %5.1f (%4.2f) secs\\n\",\n    //\t   watch.name, watch.total, 1.0 );\n\n    //watch = ls->stopwatch[BCLS_TIMER_LSQR];\n    //PRINT1(\" %-25s %5.1f (%4.2f) secs\\n\",\n    //\t   watch.name, watch.total, watch.total / timeTot );\n\n    //    watch = ls->stopwatch[BCLS_TIMER_APROD];\n    //PRINT1(\" %-25s %5.1f (%4.2f) secs\\n\",\n    //\t   watch.name, watch.total, watch.total / timeTot );\n\n    // Only print time for Usolve is user provided this routine.\n    //if (preconditioning) {\n      //  watch = ls->stopwatch[BCLS_TIMER_USOLVE];\n      //PRINT1(\" %-25s %5.1f (%4.2f) secs\\n\",\n      //       watch.name, watch.total, watch.total / timeTot );\n    //}\n\n    return (ls->exit + err);\n}\n", "meta": {"hexsha": "6c5670b51069f1e2f0f17e9110bf58bf0f353ac1", "size": 21731, "ext": "c", "lang": "C", "max_stars_repo_path": "bcls-0.1/src/bcls.c", "max_stars_repo_name": "echristakopoulou/glslim", "max_stars_repo_head_hexsha": "ad8e783e83b881042aaf97b985e5cba9aa1e9b9a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-12-16T01:56:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T04:45:41.000Z", "max_issues_repo_path": "bcls-0.1/src/bcls.c", "max_issues_repo_name": "echristakopoulou/glslim", "max_issues_repo_head_hexsha": "ad8e783e83b881042aaf97b985e5cba9aa1e9b9a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bcls-0.1/src/bcls.c", "max_forks_repo_name": "echristakopoulou/glslim", "max_forks_repo_head_hexsha": "ad8e783e83b881042aaf97b985e5cba9aa1e9b9a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-03-05T07:46:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-24T13:00:19.000Z", "avg_line_length": 31.9104258443, "max_line_length": 83, "alphanum_fraction": 0.564171, "num_tokens": 6134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.07696084363512665, "lm_q1q2_score": 0.03817979963826262}}
{"text": "/* bst/gsl_bst.h\n * \n * Copyright (C) 2018, 2019 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_BST_H__\n#define __GSL_BST_H__\n\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_bst_avl.h>\n#include <gsl/gsl_bst_rb.h>\n#include <gsl/gsl_bst_types.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\n/* type of binary search tree */\ntypedef struct\n{\n  const char *name;\n  const size_t node_size;\n  int    (*init)(const gsl_bst_allocator * allocator,\n                 gsl_bst_cmp_function * compare, void * params, void * vtable);\n  size_t (*nodes) (const void * vtable);\n  void * (*insert) (void * item, void * vtable);\n  void * (*find) (const void *item, const void * vtable);\n  void * (*remove) (const void *item, void * vtable);\n  int    (*empty) (void * vtable);\n  int    (*trav_init) (void * vtrav, const void * vtable);\n  void * (*trav_first) (void * vtrav, const void * vtable);\n  void * (*trav_last) (void * vtrav, const void * vtable);\n  void * (*trav_find) (const void * item, void * vtrav, const void * vtable);\n  void * (*trav_insert) (void * item, void * vtrav, void * vtable);\n  void * (*trav_copy) (void * vtrav, const void * vsrc);\n  void * (*trav_next) (void * vtrav);\n  void * (*trav_prev) (void * vtrav);\n  void * (*trav_cur) (const void * vtrav);\n  void * (*trav_replace) (void * vtrav, void * new_item);\n} gsl_bst_type;\n\ntypedef struct\n{\n  const gsl_bst_type * type;    /* binary search tree type */\n  union\n    {\n      gsl_bst_avl_table avl_table;\n      gsl_bst_rb_table rb_table;\n    } table;\n} gsl_bst_workspace;\n\ntypedef struct\n{\n  const gsl_bst_type * type;    /* binary search tree type */\n  union\n    {\n      gsl_bst_avl_traverser avl_trav;\n      gsl_bst_rb_traverser rb_trav;\n    } trav_data;\n} gsl_bst_trav;\n\n/* tree types */\nGSL_VAR const gsl_bst_type * gsl_bst_avl;\nGSL_VAR const gsl_bst_type * gsl_bst_rb;\n\n/*\n * Prototypes\n */\n\ngsl_bst_workspace * gsl_bst_alloc(const gsl_bst_type * T, const gsl_bst_allocator * allocator,\n                                  gsl_bst_cmp_function * compare, void * params);\nvoid gsl_bst_free(gsl_bst_workspace * w);\nint gsl_bst_empty(gsl_bst_workspace * w);\nvoid * gsl_bst_insert(void * item, gsl_bst_workspace * w);\nvoid * gsl_bst_find(const void * item, const gsl_bst_workspace * w);\nvoid * gsl_bst_remove(const void * item, gsl_bst_workspace * w);\nsize_t gsl_bst_nodes(const gsl_bst_workspace * w);\nsize_t gsl_bst_node_size(const gsl_bst_workspace * w);\nconst char * gsl_bst_name(const gsl_bst_workspace * w);\n\nint gsl_bst_trav_init(gsl_bst_trav * trav, const gsl_bst_workspace * w);\nvoid * gsl_bst_trav_first(gsl_bst_trav * trav, const gsl_bst_workspace * w);\nvoid * gsl_bst_trav_last (gsl_bst_trav * trav, const gsl_bst_workspace * w);\nvoid * gsl_bst_trav_find (const void * item, gsl_bst_trav * trav, const gsl_bst_workspace * w);\nvoid * gsl_bst_trav_insert (void * item, gsl_bst_trav * trav, gsl_bst_workspace * w);\nvoid * gsl_bst_trav_copy(gsl_bst_trav * dest, const gsl_bst_trav * src);\nvoid * gsl_bst_trav_next(gsl_bst_trav * trav);\nvoid * gsl_bst_trav_prev(gsl_bst_trav * trav);\nvoid * gsl_bst_trav_cur(const gsl_bst_trav * trav);\nvoid * gsl_bst_trav_replace (gsl_bst_trav * trav, void * new_item);\n\n__END_DECLS\n\n#endif /* __GSL_BST_H__ */\n", "meta": {"hexsha": "c5988a6e802fcc41e2d13b4c8467ae61dd2d381c", "size": 4083, "ext": "h", "lang": "C", "max_stars_repo_path": "gsl-2.6/gsl/gsl_bst.h", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gsl-2.6/gsl/gsl_bst.h", "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gsl-2.6/gsl/gsl_bst.h", "max_forks_repo_name": "ielomariala/Hex-Game", "max_forks_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8974358974, "max_line_length": 95, "alphanum_fraction": 0.7119764879, "num_tokens": 1211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356686808225123, "lm_q2_score": 0.0913820937876881, "lm_q1q2_score": 0.03687878538869584}}
{"text": "\n/*\n* -----------------------------------------------------------------\n*  util_lib.h\n*  Utilities Library\n*  Version: 2.0\n*  Last Update: Nov 3, 2019\n*\n*  Programmer: Americo Barbosa da Cunha Junior\n*              americo.cunhajr@gmail.com\n* -----------------------------------------------------------------\n*  Copyright (c) 2010-2019, Americo Barbosa da Cunha Junior\n*  All rights reserved.\n* -----------------------------------------------------------------\n*  This is the header file for UTIL_LIB module, a computational\n*  library with routines for miscelaneous applications.\n* -----------------------------------------------------------------\n*/\n\n\n\n\n#ifndef __UTIL_LIB_H__\n#define __UTIL_LIB_H__\n\n#include <time.h>\n\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_rng.h>\n\n\n\n\n/*\n*------------------------------------------------------------\n* function prototypes\n*------------------------------------------------------------\n*/\n\nint gsl_fprint_vector(FILE* file,\n                      gsl_vector *v);\n\nint gsl_print_vector(gsl_vector *v);\n\nint gsl_print_matrix_line(unsigned int i,\n                          gsl_matrix *M);\n\nint gsl_print_matrix_column(unsigned int j,\n                            gsl_matrix *M);\n\nint gsl_print_matrix(gsl_matrix *M);\n\nint gsl_rand_vector(gsl_rng *r,\n                    gsl_vector *v);\n\nint gsl_rand_matrix(gsl_rng *r,\n                    gsl_matrix *M);\n\nint gsl_diagonal_matrix(gsl_vector *v,\n                        gsl_matrix *D);\n\nvoid util_time_used(clock_t cpu_start,\n                    clock_t cpu_end,\n                    time_t wall_start,\n                    time_t wall_end);\n\n#endif /* __UTIL_LIB_H__ */\n", "meta": {"hexsha": "d4fc765db5925431057c673b7dba6702ac72bab8", "size": 1683, "ext": "h", "lang": "C", "max_stars_repo_path": "CRFlowLib-2.0/include/util_lib.h", "max_stars_repo_name": "americocunhajr/CRFlowLib", "max_stars_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-29T12:56:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-29T12:56:14.000Z", "max_issues_repo_path": "CRFlowLib-2.0/include/util_lib.h", "max_issues_repo_name": "americocunhajr/CRFlowLib", "max_issues_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CRFlowLib-2.0/include/util_lib.h", "max_forks_repo_name": "americocunhajr/CRFlowLib", "max_forks_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-15T03:57:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-30T01:44:13.000Z", "avg_line_length": 24.3913043478, "max_line_length": 67, "alphanum_fraction": 0.4806892454, "num_tokens": 336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.07369626512851495, "lm_q1q2_score": 0.03684813256425747}}
{"text": "#ifndef GSLUtility_h\n#define GSLUtility_h\n/** This is free and unencumbered software released into the public domain.\nThe authors of ISIS do not claim copyright on the contents of this file.\nFor more details about the LICENSE terms and the AUTHORS, you will\nfind files of those names at the top level of this repository. **/\n\n/* SPDX-License-Identifier: CC0-1.0 */\n\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n#include <algorithm>\n\n#include <QString>\n\n#include <tnt/tnt_array1d.h>\n#include <tnt/tnt_array1d_utils.h>\n#include <tnt/tnt_array2d.h>\n#include <tnt/tnt_array2d_utils.h>\n\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n\n//  Some GSL optimization on by default, off if DEBUG or SAFE_GSL is defined\n#ifndef DEBUG\n#ifndef SAFE_GSL\n#define GSL_RANGE_CHECK_OFF 1\n#endif\n#endif\n\n#include \"IException.h\"\n\nnamespace Isis {\n  namespace GSL {\n\n    /**\n     * @brief GSLUtility Provides top level interface to the GNU GSL\n     *\n     * Provides GSL setup and interface utilities.  This object is provided for\n     * convenience of GSL vector and matrix manipulation as well as better\n     * management of GSL error handling.\n     *\n     * Without setting up GSL error handling, the GSL will abort when certain\n     * errors occur.  This singleton object, an object where there is never more\n     * than one instance, an error handler is established that captures GSL errors\n     * and formats them into ISIS exceptions.\n     *\n     * There are many convenience methods provided for manipulation of GSL vectors\n     * and matrixs.  Motivation for this is to address element access and\n     * efficient parameter and copy mechanisms (provided by the TNT library).\n     *\n     * There are some compile options on by default that help optimize the GSL.\n     * When the compile time DEBUG macro is set, range checking is turned on.\n     * Inline functions are also turned on by default unless the DEBUG macro is\n     * set. In addition, an additional compile time macro called SAFE_GSL is\n     * provided to emulate the DEBUG behavior, but does not invoke additional\n     * DEBUG behavior/side effects.\n     *\n     * See http://www.gnu.org/software/gsl/ for additional details on the GNU\n     * Scientific Library.\n     *\n     * @ingroup Utility\n     * @author 2008-05-06 Kris Becker\n     * @internal\n     *   @history 2009-08-20 Kris Becker Completed documentation\n     */\n    class GSLUtility {\n      public:\n        typedef TNT::Array1D<double> GSLVector;\n        typedef TNT::Array2D<double> GSLMatrix;\n\n        static GSLUtility *getInstance();\n\n        /** Tests if status is success */\n        inline bool success(int status) const {\n          return (status == GSL_SUCCESS);\n        }\n\n        /**\n         * @brief Returns GSL specific error text\n         *\n         * @param gsl_errno GSL error number\n         * @return QString Textual context of GSL error\n         */\n        inline QString status(int gsl_errno) const {\n          return (QString(gsl_strerror(gsl_errno)));\n        }\n\n        void check(int gsl_status, const char *src = __FILE__, int line = __LINE__)\n        const;\n\n\n        size_t Rows(const gsl_matrix *m) const;\n        size_t Columns(const gsl_matrix *m) const;\n\n        size_t Rows(const GSLMatrix &m) const;\n        size_t Columns(const GSLMatrix &m) const;\n\n        size_t size(const gsl_vector *v) const;\n        size_t size(const gsl_matrix *m) const;\n\n        gsl_vector *vector(size_t n, bool zero = false) const;\n        gsl_matrix *matrix(size_t n1, size_t n2, bool zero = false) const;\n        gsl_matrix *identity(size_t n1, size_t n2) const;\n        void setIdentity(gsl_matrix *m) const;\n\n        void free(gsl_vector *v) const;\n        void free(gsl_matrix *m) const;\n\n        GSLVector gslToGSL(const gsl_vector *v) const;\n        GSLMatrix gslToGSL(const gsl_matrix *m) const;\n        gsl_vector *GSLTogsl(const GSLVector &v, gsl_vector *gv = 0) const;\n        gsl_matrix *GSLTogsl(const GSLMatrix &m, gsl_matrix *gm = 0) const;\n\n\n      private:\n        //  Private Constructor/Destructor makes this a singleton\n        GSLUtility();\n        ~GSLUtility() { }\n\n        static GSLUtility *_instance;  //!< Singleton self-reference pointer\n\n        static void handler(const char *reason, const char *file, int line,\n                            int gsl_errno);\n\n\n    };\n\n  } // namespace GSL\n}     // namespace Isis\n#endif\n\n", "meta": {"hexsha": "3a69856878857e8e3873db45682b483242dfffd0", "size": 4406, "ext": "h", "lang": "C", "max_stars_repo_path": "isis/src/base/objs/GSLUtility/GSLUtility.h", "max_stars_repo_name": "kdl222/ISIS3", "max_stars_repo_head_hexsha": "aab0e63088046690e6c031881825596c1c2cc380", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 134.0, "max_stars_repo_stars_event_min_datetime": "2018-01-18T00:16:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T03:53:33.000Z", "max_issues_repo_path": "isis/src/base/objs/GSLUtility/GSLUtility.h", "max_issues_repo_name": "kdl222/ISIS3", "max_issues_repo_head_hexsha": "aab0e63088046690e6c031881825596c1c2cc380", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 3825.0, "max_issues_repo_issues_event_min_datetime": "2017-12-11T21:27:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:45:20.000Z", "max_forks_repo_path": "isis/src/base/objs/GSLUtility/GSLUtility.h", "max_forks_repo_name": "jlaura/isis3", "max_forks_repo_head_hexsha": "2c40e08caed09968ea01d5a767a676172ad20080", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 164.0, "max_forks_repo_forks_event_min_datetime": "2017-11-30T21:15:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T10:22:29.000Z", "avg_line_length": 32.637037037, "max_line_length": 83, "alphanum_fraction": 0.6706763504, "num_tokens": 1022, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.08151976211114502, "lm_q1q2_score": 0.03663438065606796}}
{"text": "#ifndef ARRAY_H\n#define ARRAY_H\n\n#include <cstdarg>\n#include <cstdio>\n#include <cstdlib>\n#include <cassert>\n#include <iostream>\n#include <algorithm>\n#include <charm++.h>\n#if CMK_HAS_CBLAS\n#include <cblas.h>\n#endif\n\nnamespace CharjArray {\n  class Range {\n  public:\n    int size, start, stop;\n    Range() {}\n    Range(int size_) : size(size_), start(0), stop(size) {}\n    Range(int start_, int stop_) :\n    size(stop_ - start_), start(start_), stop(stop_) {\n      assert(stop >= start);\n    }\n    void pup(PUP::er& p) { \n        p | size;\n        p | start;\n        p | stop;\n    }\n  };\n\n  template<int dims>\n  class Domain {\n  public:\n    Range ranges[dims];\n    \n    Domain() {}\n\n    Domain(Range ranges_[]) {\n      for (int i = 0; i < dims; i++) \n\tranges[i] = ranges_[i];      \n    }\n\n    Domain(Range range) {\n      ranges[0] = range;\n    }\n\n    Domain(Range range1, Range range2) {\n      // TODO: fix Charj generator so it uses the array\n      ranges[0] = range1;\n      ranges[1] = range2;\n    }\n\n    int size() const {\n      int total = 0;\n\n      for (int i = 0; i < dims; i++)\n\tif (total == 0)\n\t  total = ranges[i].size;\n\telse\n\t  total *= ranges[i].size;\n\n      return total;\n    }\n\n    void pup(PUP::er& p) { \n        for (int i=0; i<dims; ++i) p | ranges[i];\n    }\n  };\n\n  template<int dims>\n  class RowMajor {\n  public:\n    static int access(const int i, const Domain<dims> &d) {\n      return i - d.ranges[0].start;\n    }\n    static int access(const int i, const int j, const Domain<dims> &d) {\n      return (i - d.ranges[0].start) * d.ranges[1].size + j -\n        d.ranges[1].start;\n    }\n    // Generic access method, not used right now.\n    // static int access(const int *i, const Domain<dims> &d) {\n    //   int off = i[0];\n    //   int dimoff = 1;\n    //   for (int j = ndims-1; j > 0; --j) {\n    //     dimoff *= d.ranges[j].size;\n    //     off += dimoff * (i[j] - d.ranges[j].start);\n    //   }\n    //   return off;\n    // }\n  };\n\n  template<int dims>\n  class ColMajor {\n  public:\n    static int access(const int i, const Domain<dims> &d) {\n      return i - d.ranges[0].start;\n    }\n    static int access(const int i, const int j, const Domain<dims> &d) {\n      return (j - d.ranges[1].start) * d.ranges[1].size + i -\n        d.ranges[0].start;\n    }\n  };\n\n  template<class type, int dims = 1, class atype = RowMajor<dims> >\n  class Array {\n  private:\n    Domain<dims> domain;\n    type *block;\n    int ref_cout;\n    bool did_init;\n    Array* ref_parent;\n\n  public:\n    Array(Domain<dims> domain_) : ref_parent(0), did_init(false) {\n      init(domain_);\n    }\n\n    Array(type **block_) : did_init(false) {\n      block = *block_;\n    }\n\n    Array(type& block_) : did_init(false) {\n      block = &block_;\n    }\n\n    Array() : ref_parent(0), did_init(false) {\n\n    }\n\n    Array(Array* parent, Domain<dims> domain_)\n        : ref_parent(parent), did_init(false) {\n      domain = domain_;\n      block = parent->block;\n    }\n\n    void init(Domain<dims> &domain_) {\n      domain = domain_;\n      //if (atype == ROW_MAJOR)\n      block = new type[domain.size()];\n      //printf(\"Array: allocating memory, size=%d, base pointer=%p\\n\",\n      //       domain.size(), block);\n      did_init = true;\n    }\n\n    type* raw() { return block; }\n\n    ~Array() {\n      if (did_init) delete[] block;\n    }\n\n    /*type* operator[] (const Domain<dims> &domain) {\n      return block[domain.ranges[0].size];\n      }*/\n\n    type& operator[] (const int i) {\n      return block[atype::access(i, domain)];\n    }\n\n    const type& operator[] (const int i) const {\n      return block[atype::access(i, domain)];\n    }\n\n    type& access(const int i) {\n      return this->operator[](i);\n    }\n\n    type& access(const int i, const int j) {\n      //printf(\"Array: accessing, index (%d,%d), offset=%d, base pointer=%p\\n\",\n      //i, j, atype::access(i, j, domain), block);\n      return block[atype::access(i, j, domain)];\n    }\n\n    type& access(const int i, const Range r) {\n      Domain<1> d(r);\n      //printf(\"Array: accessing subrange, size = %d, range (%d,%d), base pointer=%p\\n\",\n      //d.size(), r.start, r.stop, block);\n      type* buf = new type[d.size()];\n      for (int j = 0; j < d.size(); j++) {\n        //printf(\"Array: copying element (%d,%d), base pointer=%p\\n\", i, j, block);\n        buf[j] = block[atype::access(i, j, domain)];\n      }\n      return *buf;\n    }\n\n    const type& access(const int i, const int j) const {\n      return block[atype::access(i, j, domain)];\n    }\n\n    Array<type, dims, atype>* operator[] (const Domain<dims> &domain) {\n      return new Array<type, dims, atype>(this, domain);\n    }\n\n    int size() const {\n      return domain.size();\n    }\n\n    int size(int dim) const {\n      return domain.ranges[dim].size;\n    }\n\n    void pup(PUP::er& p) { \n        p | domain;\n        if (p.isUnpacking()) {\n            block = new type[domain.size()];\n        }\n        PUParray(p, block, domain.size());\n    }\n\n    void fill(const type &t) {\n      for (int i = 0; i < domain.size(); ++i)\n\tblock[i] = t;\n    }\n\n    /// Do these arrays have the same shape and contents?\n    bool operator==(const Array &rhs) const\n    {\n      for (int i = 0; i < dims; ++i)\n\tif (this->size(i) != rhs.size(i))\n\t  return false;\n\n      for (int i = 0; i < this->size(); ++i)\n\tif (this->block[i] != rhs.block[i])\n\t  return false;\n\n      return true;\n    }\n    bool operator!=(const Array &rhs) const\n    {\n      return !(*this == rhs);\n    }\n  };\n\n  /**\n     A local Matrix class for various sorts of linear-algebra work.\n\n     Indexed from 0, to reflect the C-heritage of Charj.\n   */\n  template <typename V, class atype = RowMajor<2> >\n  class Matrix : public Array<V, 2, atype>\n  {\n  public:\n    Matrix() { }\n    /// A square matrix\n    Matrix(unsigned int n) : Array<V,2,atype>(Domain<2>(n,n)) { }\n\n    /// A identity matrix\n    static Matrix* ident(int n)\n    {\n      Matrix *ret = new Matrix(n);\n      ret->fill(0);\n\n      for (int i = 0; i < n; ++i)\n\tret->access(i,i) = 1;\n\n      return ret;\n    }\n  };\n\n  template <typename T, class atype = RowMajor<1> >\n  class Vector : public Array<T, 1, atype>\n  {\n  public:\n    Vector() { }\n    Vector(unsigned int n) : Array<T, 1, atype>(Range(n)) { }\n  };\n\n  /// Compute the inner (dot) product v1^T * v2\n  // To compute v1^H * v2, call as dot(v1.C(), v2)\n  template<typename T, class atype1, class atype2>\n  T dot(const Vector<T, atype1> *pv1, const Vector<T, atype2> *pv2)\n  {\n    const Vector<T, atype1> &v1 = *pv1, &v2 = *pv2;\n    assert(v1.size() == v2.size());\n    // XXX: This default initialization worries me some, since it\n    // won't necessarily be an additive identity for all T. - Phil\n    T ret = T();\n    int size = v1.size();\n    for (int i = 0; i < size; ++i)\n      ret += v1[i] * v2[i];\n    return ret;\n  }\n#if CMK_HAS_CBLAS\n  template <>\n  float dot<float, RowMajor<1>, RowMajor<1> >(const Vector<float, RowMajor<1> > *pv1,\n\t\t\t\t\t      const Vector<float, RowMajor<1> > *pv2)\n  {\n    const Vector<float, RowMajor<1> > &v1 = *pv1, &v2 = *pv2;\n    assert(v1.size() == v2.size());\n    return cblas_sdot(v1.size(), &(v1[0]), 1, &(v2[0]), 1);\n  }\n  template <>\n  double dot<double, RowMajor<1>, RowMajor<1> >(const Vector<double, RowMajor<1> > *pv1,\n\t\t\t\t\t\tconst Vector<double, RowMajor<1> > *pv2)\n  {\n    const Vector<double, RowMajor<1> > &v1 = *pv1, &v2 = *pv2;\n    assert(v1.size() == v2.size());\n    return cblas_ddot(v1.size(), &(v1[0]), 1, &(v2[0]), 1);\n  }\n#endif\n\n  /// Computer the 1-norm of the given vector\n  template<typename T, class atype>\n    T norm1(const Vector<T, atype> *pv)\n  {\n    const Vector<T, atype> &v = *pv;\n    // XXX: See comment about additive identity in dot(), above\n    T ret = T();\n    int size = v.size();\n    for (int i = 0; i < size; ++i)\n      ret += v[i];\n    return ret;\n  }\n\n  /// Compute the Euclidean (2) norm of the given vector\n  template<typename T, class atype>\n    T norm2(const Vector<T, atype> *pv)\n  {\n    const Vector<T, atype> &v = *pv;\n    // XXX: See comment about additive identity in dot(), above\n    T ret = T();\n    int size = v.size();\n    for (int i = 0; i < size; ++i)\n      ret += v[i] * v[i];\n    return sqrt(ret);\n  }\n#if CMK_HAS_CBLAS\n  template<>\n    float norm2<float, RowMajor<1> >(const Vector<float, RowMajor<1> > *pv)\n  {\n    const Vector<float, RowMajor<1> > &v = *pv;\n    return cblas_snrm2(v.size(), &(v[0]), 1);\n  }\n  template<>\n    double norm2<double, RowMajor<1> >(const Vector<double, RowMajor<1> > *pv)\n  {\n    const Vector<double, RowMajor<1> > &v = *pv;\n    return cblas_dnrm2(v.size(), &(v[0]), 1);\n  }\n#endif\n\n  /// Compute the infinity (max) norm of the given vector\n  // Will fail on zero-length vectors\n  template<typename T, class atype>\n    T normI(const Vector<T, atype> *pv)\n  {\n    const Vector<T, atype> &v = *pv;\n    T ret = v[0];\n    int size = v.size();\n    for (int i = 1; i < size; ++i)\n      ret = max(ret, v[i]);\n    return ret;\n  }\n\n  /// Scale a vector by some constant\n  template<typename T, typename U, class atype>\n    void scale(const T &t, Vector<U, atype> *pv)\n  {\n    const Vector<T, atype> &v = *pv;\n    int size = v.size();\n    for (int i = 0; i < size; ++i)\n      v[i] = t * v[i];\n  }\n#if CMK_HAS_CBLAS\n  template<>\n    void scale<float, float, RowMajor<1> >(const float &t,\n\t\t\t\t\t   Vector<float, RowMajor<1> > *pv)\n  {\n    Vector<float, RowMajor<1> > &v = *pv;\n    cblas_sscal(v.size(), t, &(v[0]), 1);\n  }\n  template<>\n    void scale<double, double, RowMajor<1> >(const double &t,\n\t\t\t\t\t     Vector<double, RowMajor<1> > *pv)\n  {\n    Vector<double, RowMajor<1> > &v = *pv;\n    cblas_dscal(v.size(), t, &(v[0]), 1);\n  }\n#endif\n\n  /// Add one vector to a scaled version of another\n  template<typename T, typename U, class atype>\n    void axpy(const T &a, const Vector<U, atype> *px, Vector<U, atype> *py)\n  {\n    Vector<T, atype> &x = *px;\n    const Vector<T, atype> &y = *py;\n    int size = x.size();\n    assert(size == y.size());\n    for (int i = 0; i < size; ++i)\n      x[i] = a * x[i] + y[i];\n  }\n#if CMK_HAS_CBLAS\n  template<>\n    void axpy<float, float, RowMajor<1> >(const float &a,\n\t\t\t\t\t  const Vector<float, RowMajor<1> > *px,\n\t\t\t\t\t  Vector<float, RowMajor<1> > *py)\n  {\n    const Vector<float, RowMajor<1> > &x = *px;\n    Vector<float, RowMajor<1> > &y = *py;\n    int size = x.size();\n    assert(size == y.size());\n    cblas_saxpy(size, a, &(x[0]), 1, &(y[0]), 1);\n  }\n  template<>\n    void axpy<double, double, RowMajor<1> >(const double &a,\n\t\t\t\t\t  const Vector<double, RowMajor<1> > *px,\n\t\t\t\t\t  Vector<double, RowMajor<1> > *py)\n  {\n    const Vector<double, RowMajor<1> > &x = *px;\n    Vector<double, RowMajor<1> > &y = *py;\n    int size = x.size();\n    assert(size == y.size());\n    cblas_daxpy(size, a, &(x[0]), 1, &(y[0]), 1);\n  }\n#endif\n}\n\n#endif\n", "meta": {"hexsha": "f3b248ce11b4b67b29cab17b3abfa0aadd09e74f", "size": 10729, "ext": "h", "lang": "C", "max_stars_repo_path": "NAMD_2.12_Source/charm-6.7.1/src/langs/charj/src/charj/libs/Array.h", "max_stars_repo_name": "scottkwarren/config-db", "max_stars_repo_head_hexsha": "fb5c3da2465e5cff0ad30950493b11d452bd686b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-17T20:07:23.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-17T20:07:23.000Z", "max_issues_repo_path": "NAMD_2.12_Source/charm-6.7.1/src/langs/charj/src/charj/libs/Array.h", "max_issues_repo_name": "scottkwarren/config-db", "max_issues_repo_head_hexsha": "fb5c3da2465e5cff0ad30950493b11d452bd686b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NAMD_2.12_Source/charm-6.7.1/src/langs/charj/src/charj/libs/Array.h", "max_forks_repo_name": "scottkwarren/config-db", "max_forks_repo_head_hexsha": "fb5c3da2465e5cff0ad30950493b11d452bd686b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6062052506, "max_line_length": 88, "alphanum_fraction": 0.5543853108, "num_tokens": 3371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.07807816407233609, "lm_q1q2_score": 0.0366023114612971}}
{"text": "#ifndef AMICI_VECTOR_H\n#define AMICI_VECTOR_H\n\n#include <vector>\n#include <type_traits>\n\n#include <amici/exception.h>\n\n#include <nvector/nvector_serial.h>\n\n#include <gsl/gsl-lite.hpp>\n\nnamespace amici {\n\n/** Since const N_Vector is not what we want */\nusing const_N_Vector =\n    std::add_const_t<typename std::remove_pointer_t<N_Vector>> *;\n\ninline const realtype* N_VGetArrayPointerConst(const_N_Vector x) {\n    return N_VGetArrayPointer(const_cast<N_Vector>(x));\n}\n\n/** AmiVector class provides a generic interface to the NVector_Serial struct */\nclass AmiVector {\n  public:\n    /**\n     * @brief Default constructor\n     */\n    AmiVector() = default;\n\n    /** Creates an std::vector<realtype> and attaches the\n     * data pointer to a newly created N_Vector_Serial.\n     * Using N_VMake_Serial ensures that the N_Vector\n     * module does not try to deallocate the data vector\n     * when calling N_VDestroy_Serial\n     * @brief empty constructor\n     * @param length number of elements in vector\n     */\n    explicit AmiVector(const long int length)\n        : vec_(static_cast<decltype(vec_)::size_type>(length), 0.0),\n          nvec_(N_VMake_Serial(length, vec_.data())) {}\n\n    /** Moves data from std::vector and constructs an nvec that points to the\n     * data\n     * @brief constructor from std::vector,\n     * @param rvec vector from which the data will be moved\n     */\n    explicit AmiVector(std::vector<realtype> rvec)\n        : vec_(std::move(rvec)),\n          nvec_(N_VMake_Serial(static_cast<long int>(vec_.size()), vec_.data())) {}\n\n    /** Copy data from gsl::span and constructs a vector\n     * @brief constructor from gsl::span,\n     * @param rvec vector from which the data will be copied\n     */\n    explicit AmiVector(gsl::span<realtype> rvec)\n        : AmiVector(std::vector<realtype>(rvec.begin(), rvec.end())) {}\n\n    /**\n     * @brief copy constructor\n     * @param vold vector from which the data will be copied\n     */\n    AmiVector(const AmiVector &vold) : vec_(vold.vec_) {\n        nvec_ =\n            N_VMake_Serial(static_cast<long int>(vold.vec_.size()), vec_.data());\n    }\n\n    /**\n     * @brief move constructor\n     * @param other vector from which the data will be moved\n     */\n    AmiVector(AmiVector&& other) noexcept : nvec_(nullptr) {\n        vec_ = std::move(other.vec_);\n        synchroniseNVector();\n    }\n\n    /**\n     * @brief destructor\n     */\n    ~AmiVector();\n\n    /**\n     * @brief copy assignment operator\n     * @param other right hand side\n     * @return left hand side\n     */\n    AmiVector &operator=(AmiVector const &other);\n\n    /**\n     * @brief operator *= (element-wise multiplication)\n     * @param multiplier multiplier\n     * @return result\n     */\n    AmiVector &operator*=(AmiVector const& multiplier) {\n        N_VProd(getNVector(),\n               const_cast<N_Vector>(multiplier.getNVector()),\n               getNVector());\n        return *this;\n    }\n\n    /**\n     * @brief operator /= (element-wise division)\n     * @param divisor divisor\n     * @return result\n     */\n    AmiVector &operator/=(AmiVector const& divisor) {\n        N_VDiv(getNVector(),\n               const_cast<N_Vector>(divisor.getNVector()),\n               getNVector());\n        return *this;\n    }\n\n    /**\n     * @brief Returns an iterator that points to the first element of the\n     * vector.\n     * @return iterator that points to the first element\n     */\n    auto begin() { return vec_.begin(); }\n\n    /**\n     * @brief Returns an iterator that points to one element after the last\n     * element of the vector.\n     * @return iterator that points to one element after the last element\n     */\n    auto end() { return vec_.end(); }\n\n    /**\n     * @brief data accessor\n     * @return pointer to data array\n     */\n    realtype *data();\n\n    /**\n     * @brief const data accessor\n     * @return const pointer to data array\n     */\n    const realtype *data() const;\n\n    /**\n     * @brief N_Vector accessor\n     * @return N_Vector\n     */\n    N_Vector getNVector();\n\n    /**\n     * @brief N_Vector accessor\n     * @return N_Vector\n     */\n    const_N_Vector getNVector() const;\n\n    /**\n     * @brief Vector accessor\n     * @return Vector\n     */\n    std::vector<realtype> const &getVector() const;\n\n    /**\n     * @brief returns the length of the vector\n     * @return length\n     */\n    int getLength() const;\n\n    /**\n     * @brief fills vector with zero values\n     */\n    void zero();\n\n    /**\n     * @brief changes the sign of data elements\n     */\n    void minus();\n\n    /**\n     * @brief sets all data elements to a specific value\n     * @param val value for data elements\n     */\n    void set(realtype val);\n\n    /**\n     * @brief accessor to data elements of the vector\n     * @param pos index of element\n     * @return element\n     */\n    realtype &operator[](int pos);\n    /**\n     * @brief accessor to data elements of the vector\n     * @param pos index of element\n     * @return element\n     */\n    realtype &at(int pos);\n\n    /**\n     * @brief accessor to data elements of the vector\n     * @param pos index of element\n     * @return element\n     */\n    const realtype &at(int pos) const;\n\n    /**\n     * @brief copies data from another AmiVector\n     * @param other data source\n     */\n    void copy(const AmiVector &other);\n\n    /**\n     * @brief Take absolute value (in-place)\n     */\n    void abs() {\n        N_VAbs(getNVector(), getNVector());\n    };\n\n  private:\n    /** main data storage */\n    std::vector<realtype> vec_;\n\n    /** N_Vector, will be synchronized such that it points to data in vec */\n    N_Vector nvec_ {nullptr};\n\n    /**\n     * @brief reconstructs nvec such that data pointer points to vec data array\n     */\n    void synchroniseNVector();\n};\n\n/**\n * @brief AmiVectorArray class.\n *\n * Provides a generic interface to arrays of NVector_Serial structs\n */\nclass AmiVectorArray {\n  public:\n    /**\n     * @brief Default constructor\n     */\n    AmiVectorArray() = default;\n\n    /**\n     * Creates an std::vector<realype> and attaches the\n     * data pointer to a newly created N_VectorArray\n     * using CloneVectorArrayEmpty ensures that the N_Vector\n     * module does not try to deallocate the data vector\n     * when calling N_VDestroyVectorArray_Serial\n     * @brief empty constructor\n     * @param length_inner length of vectors\n     * @param length_outer number of vectors\n     */\n    AmiVectorArray(long int length_inner, long int length_outer);\n\n    /**\n     * @brief copy constructor\n     * @param vaold object to copy from\n     */\n    AmiVectorArray(const AmiVectorArray &vaold);\n\n    ~AmiVectorArray() = default;\n\n    /**\n     * @brief copy assignment operator\n     * @param other right hand side\n     * @return left hand side\n     */\n    AmiVectorArray &operator=(AmiVectorArray const &other);\n\n    /**\n     * @brief accessor to data of AmiVector elements\n     * @param pos index of AmiVector\n     * @return pointer to data array\n     */\n    realtype *data(int pos);\n\n    /**\n     * @brief const accessor to data of AmiVector elements\n     * @param pos index of AmiVector\n     * @return const pointer to data array\n     */\n    const realtype *data(int pos) const;\n\n    /**\n     * @brief accessor to elements of AmiVector elements\n     * @param ipos inner index in AmiVector\n     * @param jpos outer index in AmiVectorArray\n     * @return element\n     */\n    realtype &at(int ipos, int jpos);\n\n    /**\n     * @brief const accessor to elements of AmiVector elements\n     * @param ipos inner index in AmiVector\n     * @param jpos outer index in AmiVectorArray\n     * @return element\n     */\n    const realtype &at(int ipos, int jpos) const;\n\n    /**\n     * @brief accessor to NVectorArray\n     * @return N_VectorArray\n     */\n    N_Vector *getNVectorArray();\n\n    /**\n     * @brief accessor to NVector element\n     * @param pos index of corresponding AmiVector\n     * @return N_Vector\n     */\n    N_Vector getNVector(int pos);\n\n    /**\n     * @brief const accessor to NVector element\n     * @param pos index of corresponding AmiVector\n     * @return N_Vector\n     */\n    const_N_Vector getNVector(int pos) const;\n\n    /**\n     * @brief accessor to AmiVector elements\n     * @param pos index of AmiVector\n     * @return AmiVector\n     */\n    AmiVector &operator[](int pos);\n\n    /**\n     * @brief const accessor to AmiVector elements\n     * @param pos index of AmiVector\n     * @return const AmiVector\n     */\n    const AmiVector &operator[](int pos) const;\n\n    /**\n     * @brief length of AmiVectorArray\n     * @return length\n     */\n    int getLength() const;\n\n    /**\n     * @brief set every AmiVector in AmiVectorArray to zero\n     */\n    void zero();\n\n    /**\n     * @brief flattens the AmiVectorArray to a vector in row-major format\n     * @param vec vector into which the AmiVectorArray will be flattened. Must\n     * have length equal to number of elements.\n     */\n    void flatten_to_vector(std::vector<realtype> &vec) const;\n\n    /**\n     * @brief copies data from another AmiVectorArray\n     * @param other data source\n     */\n    void copy(const AmiVectorArray &other);\n\n  private:\n    /** main data storage */\n    std::vector<AmiVector> vec_array_;\n\n    /**\n     * N_Vector array, will be synchronized such that it points to\n     * respective elements in the vec_array\n     */\n    std::vector<N_Vector> nvec_array_;\n};\n\n/**\n * @brief Computes z = a*x + b*y\n * @param a coefficient for x\n * @param x a vector\n * @param b coefficient for y\n * @param y another vector with same size as x\n * @param z result vector of same size as x and y\n */\ninline void linearSum(realtype a, AmiVector const& x, realtype b,\n               AmiVector const& y, AmiVector& z) {\n    N_VLinearSum(a, const_cast<N_Vector>(x.getNVector()),\n                 b, const_cast<N_Vector>(y.getNVector()),\n                 z.getNVector());\n}\n\n/**\n * @brief Compute dot product of x and y\n * @param x vector\n * @param y vector\n * @return dot product of x and y\n */\ninline realtype dotProd(AmiVector const& x, AmiVector const& y) {\n    return N_VDotProd(const_cast<N_Vector>(x.getNVector()),\n                      const_cast<N_Vector>(y.getNVector()));\n}\n\n} // namespace amici\n\n\nnamespace gsl {\n/**\n * @brief Create span from N_Vector\n * @param nv\n * @return\n */\ninline span<realtype> make_span(N_Vector nv)\n{\n    return span<realtype>(N_VGetArrayPointer(nv), N_VGetLength_Serial(nv));\n}\n} // namespace gsl\n\n#endif /* AMICI_VECTOR_H */\n", "meta": {"hexsha": "102a75e7f84146d69642b1bd5d87e58a8821bd85", "size": 10410, "ext": "h", "lang": "C", "max_stars_repo_path": "include/amici/vector.h", "max_stars_repo_name": "kristianmeyerr/AMICI", "max_stars_repo_head_hexsha": "15f14c24b781daf5ceb3606d79edbbf57155a043", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/amici/vector.h", "max_issues_repo_name": "kristianmeyerr/AMICI", "max_issues_repo_head_hexsha": "15f14c24b781daf5ceb3606d79edbbf57155a043", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/amici/vector.h", "max_forks_repo_name": "kristianmeyerr/AMICI", "max_forks_repo_head_hexsha": "15f14c24b781daf5ceb3606d79edbbf57155a043", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7037037037, "max_line_length": 83, "alphanum_fraction": 0.6228626321, "num_tokens": 2627, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713670203584295, "lm_q2_score": 0.07921031595778612, "lm_q1q2_score": 0.03620994260415945}}
{"text": "#ifndef UTIL_GSL_CONVERTER_H\n#define UTIL_GSL_CONVERTER_H\n\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n\nnamespace gsl {\n\ninline\ngsl_vector* convert_vec(const arma::vec & vector) {\n\n  gsl_vector * gsl_vec = gsl_vector_alloc(vector.n_elem);\n\n#pragma omp parallel for\n  for(arma::uword i=0; i<vector.n_elem; i++) {\n    gsl_vector_set(gsl_vec, i, vector(i));\n  }\n\n  return gsl_vec;\n}\n\ninline\narma::vec convert_vec(const gsl_vector * gsl_vec) {\n\n  arma::vec arma_vec(gsl_vec->size);\n\n#pragma omp parallel for\n  for(arma::uword i=0; i<arma_vec.n_elem; i++) {\n    arma_vec(i) = gsl_vector_get(gsl_vec, i);\n  }\n\n  return arma_vec;\n}\n\ninline\ngsl_matrix* convert_mat(const arma::mat & mat) {\n\n  gsl_matrix * gsl_mat = gsl_matrix_alloc(mat.n_rows, mat.n_cols);\n\n#pragma omp parallel for\n  for(arma::uword i=0; i<mat.n_rows; i++) {\n    for(arma::uword j=0; j<mat.n_cols; j++) {\n     gsl_matrix_set(gsl_mat, i, j, mat(i,j));\n    }\n  }\n\n  return gsl_mat;\n}\n\ninline\narma::mat convert_mat(const gsl_matrix * gsl_mat) {\n\n  arma::mat arma_mat(gsl_mat->size1, gsl_mat->size2);\n\n#pragma omp parallel for\n  for(arma::uword i=0; i<arma_mat.n_rows; i++) {\n    for(arma::uword j=0; j<arma_mat.n_cols; j++) {\n      arma_mat(i,j) = gsl_matrix_get(gsl_mat, i, j);\n    }\n  }\n\n  return arma_mat;\n}\n\n\n}\n\n#endif //UTIL_GSL_CONVERTER_H\n", "meta": {"hexsha": "f937109a9a9a76a517626e9e4637fe6f2f44059d", "size": 1316, "ext": "h", "lang": "C", "max_stars_repo_path": "include/quartz_internal/util/gsl_converter.h", "max_stars_repo_name": "Walter-Feng/Quartz", "max_stars_repo_head_hexsha": "f9af8cf41ec9882e109271ede3b7ad7c2a49af2b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-06-18T09:34:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-01T01:27:32.000Z", "max_issues_repo_path": "include/quartz_internal/util/gsl_converter.h", "max_issues_repo_name": "Walter-Feng/Quartz", "max_issues_repo_head_hexsha": "f9af8cf41ec9882e109271ede3b7ad7c2a49af2b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-02-27T04:46:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-17T05:26:46.000Z", "max_forks_repo_path": "include/quartz_internal/util/gsl_converter.h", "max_forks_repo_name": "Walter-Feng/Quartz", "max_forks_repo_head_hexsha": "f9af8cf41ec9882e109271ede3b7ad7c2a49af2b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.0724637681, "max_line_length": 66, "alphanum_fraction": 0.679331307, "num_tokens": 412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.0780781581729546, "lm_q1q2_score": 0.0359953410155331}}
{"text": "/**\n *\n * @file qwrapper_dlaswp.c\n *\n *  PLASMA core_blas quark wrapper\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Mathieu Faverge\n * @date 2010-11-15\n * @generated d Tue Jan  7 11:44:58 2014\n *\n **/\n#include <lapacke.h>\n#include \"common.h\"\n\n/***************************************************************************//**\n *\n **/\nvoid QUARK_CORE_dlaswp(Quark *quark, Quark_Task_Flags *task_flags,\n                       int n, double *A, int lda,\n                       int i1,  int i2, const int *ipiv, int inc)\n{\n    DAG_CORE_LASWP;\n    QUARK_Insert_Task(\n        quark, CORE_dlaswp_quark, task_flags,\n        sizeof(int),                      &n,    VALUE,\n        sizeof(double)*lda*n,  A,        INOUT | LOCALITY,\n        sizeof(int),                      &lda,  VALUE,\n        sizeof(int),                      &i1,   VALUE,\n        sizeof(int),                      &i2,   VALUE,\n        sizeof(int)*n,                     ipiv,     INPUT,\n        sizeof(int),                      &inc,  VALUE,\n        0);\n}\n\n/***************************************************************************//**\n *\n **/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_dlaswp_quark = PCORE_dlaswp_quark\n#define CORE_dlaswp_quark PCORE_dlaswp_quark\n#endif\nvoid CORE_dlaswp_quark(Quark *quark)\n{\n    int n, lda, i1, i2, inc;\n    int *ipiv;\n    double *A;\n\n    quark_unpack_args_7(quark, n, A, lda, i1, i2, ipiv, inc);\n    LAPACKE_dlaswp_work(LAPACK_COL_MAJOR, n, A, lda, i1, i2, ipiv, inc );\n}\n\n/***************************************************************************//**\n *\n **/\nvoid QUARK_CORE_dlaswp_f2(Quark *quark, Quark_Task_Flags *task_flags,\n                          int n, double *A, int lda,\n                          int i1,  int i2, const int *ipiv, int inc,\n                          double *fake1, int szefake1, int flag1,\n                          double *fake2, int szefake2, int flag2)\n{\n    DAG_CORE_LASWP;\n    QUARK_Insert_Task(\n        quark, CORE_dlaswp_f2_quark, task_flags,\n        sizeof(int),                        &n,     VALUE,\n        sizeof(double)*lda*n,    A,         INOUT | LOCALITY,\n        sizeof(int),                        &lda,   VALUE,\n        sizeof(int),                        &i1,    VALUE,\n        sizeof(int),                        &i2,    VALUE,\n        sizeof(int)*n,                       ipiv,      INPUT,\n        sizeof(int),                        &inc,   VALUE,\n        sizeof(double)*szefake1, fake1,     flag1,\n        sizeof(double)*szefake2, fake2,     flag2,\n        0);\n}\n\n/***************************************************************************//**\n *\n **/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_dlaswp_f2_quark = PCORE_dlaswp_f2_quark\n#define CORE_dlaswp_f2_quark PCORE_dlaswp_f2_quark\n#endif\nvoid CORE_dlaswp_f2_quark(Quark* quark)\n{\n    int n, lda, i1, i2, inc;\n    int *ipiv;\n    double *A;\n    void *fake1, *fake2;\n\n    quark_unpack_args_9(quark, n, A, lda, i1, i2, ipiv, inc, fake1, fake2);\n    LAPACKE_dlaswp_work(LAPACK_COL_MAJOR, n, A, lda, i1, i2, ipiv, inc );\n}\n\n\n/***************************************************************************//**\n *\n **/\nvoid QUARK_CORE_dlaswp_ontile(Quark *quark, Quark_Task_Flags *task_flags,\n                              PLASMA_desc descA, double *Aij,\n                              int i1,  int i2, const int *ipiv, int inc, double *fakepanel)\n{\n    DAG_CORE_LASWP;\n    if (fakepanel == Aij) {\n        QUARK_Insert_Task(\n            quark, CORE_dlaswp_ontile_quark, task_flags,\n            sizeof(PLASMA_desc),              &descA,     VALUE,\n            sizeof(double)*1,      Aij,           INOUT | LOCALITY,\n            sizeof(int),                      &i1,        VALUE,\n            sizeof(int),                      &i2,        VALUE,\n            sizeof(int)*(i2-i1+1)*abs(inc),   ipiv,           INPUT,\n            sizeof(int),                      &inc,       VALUE,\n            sizeof(double)*1,      fakepanel,     SCRATCH,\n            0);\n    } else {\n        QUARK_Insert_Task(\n            quark, CORE_dlaswp_ontile_quark, task_flags,\n            sizeof(PLASMA_desc),              &descA,     VALUE,\n            sizeof(double)*1,      Aij,           INOUT | LOCALITY,\n            sizeof(int),                      &i1,        VALUE,\n            sizeof(int),                      &i2,        VALUE,\n            sizeof(int)*(i2-i1+1)*abs(inc),   ipiv,           INPUT,\n            sizeof(int),                      &inc,       VALUE,\n            sizeof(double)*1,      fakepanel,     INOUT,\n            0);\n    }\n}\n\n/***************************************************************************//**\n *\n **/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_dlaswp_ontile_quark = PCORE_dlaswp_ontile_quark\n#define CORE_dlaswp_ontile_quark PCORE_dlaswp_ontile_quark\n#endif\nvoid CORE_dlaswp_ontile_quark(Quark *quark)\n{\n    int i1, i2, inc;\n    int *ipiv;\n    double *A, *fake;\n    PLASMA_desc descA;\n\n    quark_unpack_args_7(quark, descA, A, i1, i2, ipiv, inc, fake);\n    CORE_dlaswp_ontile(descA, i1, i2, ipiv, inc);\n}\n\n/***************************************************************************//**\n *\n **/\nvoid QUARK_CORE_dlaswp_ontile_f2(Quark *quark, Quark_Task_Flags *task_flags,\n                                 PLASMA_desc descA, double *Aij,\n                                 int i1,  int i2, const int *ipiv, int inc,\n                                 double *fake1, int szefake1, int flag1,\n                                 double *fake2, int szefake2, int flag2)\n{\n    DAG_CORE_LASWP;\n    QUARK_Insert_Task(\n        quark, CORE_dlaswp_ontile_f2_quark, task_flags,\n        sizeof(PLASMA_desc),                &descA, VALUE,\n        sizeof(double)*1,        Aij,       INOUT | LOCALITY,\n        sizeof(int),                        &i1,    VALUE,\n        sizeof(int),                        &i2,    VALUE,\n        sizeof(int)*(i2-i1+1)*abs(inc),      ipiv,      INPUT,\n        sizeof(int),                        &inc,   VALUE,\n        sizeof(double)*szefake1, fake1, flag1,\n        sizeof(double)*szefake2, fake2, flag2,\n        0);\n}\n\n/***************************************************************************//**\n *\n **/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_dlaswp_ontile_f2_quark = PCORE_dlaswp_ontile_f2_quark\n#define CORE_dlaswp_ontile_f2_quark PCORE_dlaswp_ontile_f2_quark\n#endif\nvoid CORE_dlaswp_ontile_f2_quark(Quark *quark)\n{\n    int i1, i2, inc;\n    int *ipiv;\n    double *A;\n    PLASMA_desc descA;\n    void *fake1, *fake2;\n\n    quark_unpack_args_8(quark, descA, A, i1, i2, ipiv, inc, fake1, fake2);\n    CORE_dlaswp_ontile(descA, i1, i2, ipiv, inc);\n}\n\n/***************************************************************************//**\n *\n **/\nvoid QUARK_CORE_dswptr_ontile(Quark *quark, Quark_Task_Flags *task_flags,\n                              PLASMA_desc descA, double *Aij,\n                              int i1,  int i2, const int *ipiv, int inc,\n                              const double *Akk, int ldak)\n{\n    DAG_CORE_TRSM;\n    QUARK_Insert_Task(\n        quark, CORE_dswptr_ontile_quark, task_flags,\n        sizeof(PLASMA_desc),              &descA, VALUE,\n        sizeof(double)*1,      Aij,       INOUT | LOCALITY,\n        sizeof(int),                      &i1,    VALUE,\n        sizeof(int),                      &i2,    VALUE,\n        sizeof(int)*(i2-i1+1)*abs(inc),    ipiv,      INPUT,\n        sizeof(int),                      &inc,   VALUE,\n        sizeof(double)*ldak,   Akk,       INPUT,\n        sizeof(int),                      &ldak,  VALUE,\n        0);\n}\n\n/***************************************************************************//**\n *\n **/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_dswptr_ontile_quark = PCORE_dswptr_ontile_quark\n#define CORE_dswptr_ontile_quark PCORE_dswptr_ontile_quark\n#endif\nvoid CORE_dswptr_ontile_quark(Quark *quark)\n{\n    int i1, i2, inc, ldak;\n    int *ipiv;\n    double *A, *Akk;\n    PLASMA_desc descA;\n\n    quark_unpack_args_8(quark, descA, A, i1, i2, ipiv, inc, Akk, ldak);\n    CORE_dswptr_ontile(descA, i1, i2, ipiv, inc, Akk, ldak);\n}\n\n/***************************************************************************//**\n *\n **/\nvoid QUARK_CORE_dlaswpc_ontile(Quark *quark, Quark_Task_Flags *task_flags,\n                              PLASMA_desc descA, double *Aij,\n                              int i1,  int i2, const int *ipiv, int inc, double *fakepanel)\n{\n    DAG_CORE_LASWP;\n    if (fakepanel == Aij) {\n        QUARK_Insert_Task(\n            quark, CORE_dlaswpc_ontile_quark, task_flags,\n            sizeof(PLASMA_desc),              &descA,     VALUE,\n            sizeof(double)*1,      Aij,           INOUT | LOCALITY,\n            sizeof(int),                      &i1,        VALUE,\n            sizeof(int),                      &i2,        VALUE,\n            sizeof(int)*(i2-i1+1)*abs(inc),   ipiv,           INPUT,\n            sizeof(int),                      &inc,       VALUE,\n            sizeof(double)*1,      fakepanel,     SCRATCH,\n            0);\n    } else {\n        QUARK_Insert_Task(\n            quark, CORE_dlaswpc_ontile_quark, task_flags,\n            sizeof(PLASMA_desc),              &descA,     VALUE,\n            sizeof(double)*1,      Aij,           INOUT | LOCALITY,\n            sizeof(int),                      &i1,        VALUE,\n            sizeof(int),                      &i2,        VALUE,\n            sizeof(int)*(i2-i1+1)*abs(inc),   ipiv,           INPUT,\n            sizeof(int),                      &inc,       VALUE,\n            sizeof(double)*1,      fakepanel,     INOUT,\n            0);\n    }\n}\n\n/***************************************************************************//**\n *\n **/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_dlaswpc_ontile_quark = PCORE_dlaswpc_ontile_quark\n#define CORE_dlaswpc_ontile_quark PCORE_dlaswpc_ontile_quark\n#endif\nvoid CORE_dlaswpc_ontile_quark(Quark *quark)\n{\n    int i1, i2, inc;\n    int *ipiv;\n    double *A, *fake;\n    PLASMA_desc descA;\n\n    quark_unpack_args_7(quark, descA, A, i1, i2, ipiv, inc, fake);\n    CORE_dlaswpc_ontile(descA, i1, i2, ipiv, inc);\n}\n\n", "meta": {"hexsha": "49601903e8698a9abc3ed92390070f78495f7aac", "size": 10169, "ext": "c", "lang": "C", "max_stars_repo_path": "core_blas-qwrapper/qwrapper_dlaswp.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "core_blas-qwrapper/qwrapper_dlaswp.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "core_blas-qwrapper/qwrapper_dlaswp.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0602836879, "max_line_length": 91, "alphanum_fraction": 0.4758579998, "num_tokens": 2745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326183324442865, "lm_q2_score": 0.07921032302219255, "lm_q1q2_score": 0.03590301622492237}}
{"text": "//====---- Sudoku/Board_Iterators.h                                   ----====//\n//\n// Location aware iterator implementation for Board\n//====--------------------------------------------------------------------====//\n//\n// The iterator can return a Location object.\n// included by Board.h\n//\n//====--------------------------------------------------------------------====//\n#pragma once\n\n#include \"Sudoku/Location.h\"\n#include <gsl/gsl>\n\n#include <iterator>\n#include <limits>\n#include <type_traits>\n\n#include \"Board.fwd.h\" // Forward declarations\n\n#include <cassert>\n\n\nnamespace Sudoku\n{\ntemplate<typename T, int N, bool is_const = false, bool is_reverse = false>\nclass Board_iterator;\n\n//====--- Aliases --------------------------------------------------------====//\ntemplate<typename T, int N>\nusing const_Board_iterator = Board_iterator<T, N, true, false>;\ntemplate<typename T, int N>\nusing reverse_Board_iterator = Board_iterator<T, N, false, true>;\ntemplate<typename T, int N>\nusing const_reverse_Board_iterator = Board_iterator<T, N, true, true>;\n\n//====--------------------------------------------------------------------====//\ntemplate<typename T, int N, bool is_const, bool is_reverse>\nclass Board_iterator\n{\n\tusing owner_type =\n\t\tstd::conditional_t<is_const, Board<T, N> const, Board<T, N>>;\n\tusing Location = ::Sudoku::Location<N>;\n\npublic:\n\t// member types\n\tusing difference_type = std::ptrdiff_t;\n\tstatic_assert(\n\t\tfull_size<N> < std::numeric_limits<difference_type>::max(),\n\t\t\"Use std::ptrdiff_t for Board_iterator::difference_type.\");\n\tusing value_type        = T;\n\tusing pointer           = std::conditional_t<is_const, T const*, T*>;\n\tusing reference         = std::conditional_t<is_const, T const&, T&>;\n\tusing iterator_category = std::random_access_iterator_tag;\n\n\t// Constructors\n\tconstexpr Board_iterator() noexcept\n\t{ // defaults to [r]begin()\n\t\tif constexpr (is_reverse)\n\t\t\telem_ = full_size<N> - 1;\n\t}\n\texplicit constexpr Board_iterator(gsl::not_null<owner_type*> owner) noexcept\n\t\t: board_(owner)\n\t{ // defaults to [r]begin()\n\t\tif constexpr (is_reverse)\n\t\t\telem_ = (full_size<N> - 1);\n\t}\n\texplicit constexpr Board_iterator(\n\t\tgsl::not_null<owner_type*> owner, Location loc) noexcept\n\t\t: board_(owner), elem_(loc.element())\n\t{\n\t}\n\t// Assignment\n\tconstexpr Board_iterator& operator=(Location const loc) noexcept\n\t{\n\t\tassert(is_valid(loc));\n\t\telem_ = loc.element();\n\t\treturn (*this);\n\t}\n\n\t// [[implicit]] Type Conversion to const_(reverse_)iterator\n\t// NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions)\n\tconstexpr operator Board_iterator<T, N, true, is_reverse>() const noexcept\n\t{\n\t\tstatic_assert(!is_const);\n\t\treturn Board_iterator<T, N, true, is_reverse>(\n\t\t\tgsl::not_null<owner_type*>{board_}, Location{elem_});\n\t}\n\n\t//====----------------------------------------------------------------====//\n\t[[nodiscard]] constexpr Location location() const noexcept\n\t{\n\t\treturn Location{gsl::narrow_cast<int>(elem_)};\n\t}\n\t// Allows for conversion to Location\n\texplicit constexpr operator Location() const noexcept { return location(); }\n\n\t//====----------------------------------------------------------------====//\n\t[[nodiscard]] constexpr reference operator*() const noexcept\n\t{ // Only valid in a dereferenceable location:\n\t\tassert(board_ != nullptr && is_valid(Location{elem_}));\n\t\treturn board_->operator[](location());\n\t}\n\t[[nodiscard]] constexpr pointer operator->() const noexcept\n\t{ // member access; equivalent to (*p).member\n\t\treturn std::pointer_traits<pointer>::pointer_to(**this);\n\t}\n\n\t//====----------------------------------------------------------------====//\n\tconstexpr Board_iterator& operator++() noexcept;\n\tconstexpr Board_iterator operator++(int) noexcept;\n\tconstexpr Board_iterator& operator--() noexcept;\n\tconstexpr Board_iterator operator--(int) noexcept;\n\tconstexpr Board_iterator& operator+=(const difference_type offset) noexcept;\n\tconstexpr Board_iterator& operator-=(const difference_type offset) noexcept;\n\n\t[[nodiscard]] friend constexpr difference_type operator-(\n\t\tBoard_iterator const left, Board_iterator const right) noexcept\n\t{ // difference\n\t\tassert(is_same_Board(left, right));\n\t\tif constexpr (is_reverse)\n\t\t\treturn right.elem_ - left.elem_;\n\t\telse\n\t\t\treturn left.elem_ - right.elem_;\n\t}\n\n\t[[nodiscard]] constexpr reference\n\t\toperator[](const difference_type offset) const noexcept\n\t{\n\t\treturn (*(*this + offset));\n\t}\n\n\t//====----------------------------------------------------------------====//\n\t[[nodiscard]] friend constexpr bool operator==(\n\t\tBoard_iterator const left, Board_iterator const right) noexcept\n\t{\n\t\tassert(is_same_Board(left, right));\n\t\treturn is_same_Board(left, right) && left.elem_ == right.elem_;\n\t}\n\t[[nodiscard]] friend constexpr bool operator<(\n\t\tBoard_iterator const left, Board_iterator const right) noexcept\n\t{\n\t\tassert(is_same_Board(left, right));\n\t\tif constexpr (is_reverse)\n\t\t\treturn left.elem_ > right.elem_;\n\t\telse\n\t\t\treturn left.elem_ < right.elem_;\n\t}\n\nprivate:\n\towner_type* board_{nullptr};\n\tgsl::index elem_{0};\n\n\tfriend constexpr bool\n\t\tis_same_Board(Board_iterator const A, Board_iterator const B) noexcept\n\t{ // compare address of:\n\t\treturn A.board_ == B.board_;\n\t}\n};\n\n\n//====--------------------------------------------------------------------====//\ntemplate<typename T, int N, bool C, bool is_reverse>\nconstexpr Board_iterator<T, N, C, is_reverse>&\n\tBoard_iterator<T, N, C, is_reverse>::operator++() noexcept\n{ // pre-increment\n\tassert(board_ != nullptr);\n\tif constexpr (is_reverse)\n\t{\n\t\tassert(elem_ >= 0);\n\t\t--elem_;\n\t}\n\telse\n\t{\n\t\tassert(elem_ < full_size<N>);\n\t\t++elem_;\n\t}\n\treturn (*this);\n}\ntemplate<typename T, int N, bool C, bool R>\nconstexpr Board_iterator<T, N, C, R> // NOLINTNEXTLINE(readability/casting)\n\tBoard_iterator<T, N, C, R>::operator++(int) noexcept\n{ // post-increment\n\tconst Board_iterator pre{*this};\n\toperator++();\n\treturn pre;\n}\ntemplate<typename T, int N, bool C, bool is_reverse>\nconstexpr Board_iterator<T, N, C, is_reverse>&\n\tBoard_iterator<T, N, C, is_reverse>::operator--() noexcept\n{ // pre-decrement\n\tassert(board_ != nullptr);\n\tif constexpr (is_reverse)\n\t{\n\t\tassert(elem_ < full_size<N> - 1);\n\t\t++elem_;\n\t}\n\telse\n\t{\n\t\tassert(elem_ > 0);\n\t\t--elem_;\n\t}\n\treturn (*this);\n}\ntemplate<typename T, int N, bool C, bool R>\nconstexpr Board_iterator<T, N, C, R> // NOLINTNEXTLINE(readability/casting)\n\tBoard_iterator<T, N, C, R>::operator--(int) noexcept\n{ // post-decrement\n\tconst Board_iterator pre{*this};\n\toperator--();\n\treturn pre;\n}\ntemplate<typename T, int N, bool C, bool is_reverse>\nconstexpr Board_iterator<T, N, C, is_reverse>&\n\tBoard_iterator<T, N, C, is_reverse>::operator+=(\n\t\tconst difference_type offset) noexcept\n{\n\tassert(offset == 0 || board_ != nullptr);\n\tif constexpr (is_reverse)\n\t{\n\t\telem_ -= offset;\n\t\tassert(elem_ >= -1);\n\t\tassert(elem_ < full_size<N>);\n\t}\n\telse\n\t{\n\t\telem_ += offset;\n\t\tassert(elem_ >= 0);\n\t\tassert(elem_ <= full_size<N>);\n\t}\n\treturn (*this);\n}\ntemplate<typename T, int N, bool C, bool is_reverse>\nconstexpr Board_iterator<T, N, C, is_reverse>&\n\tBoard_iterator<T, N, C, is_reverse>::operator-=(\n\t\tconst difference_type offset) noexcept\n{\n\treturn operator+=(-offset);\n}\n\n//====--------------------------------------------------------------------====//\n// Free functions (non-friend)\n//====--------------------------------------------------------------------====//\ntemplate<typename T, int N, bool is_const, bool is_reverse>\n[[nodiscard]] constexpr auto operator+(\n\tBoard_iterator<T, N, is_const, is_reverse> left,\n\ttypename Board_iterator<T, N, is_const, is_reverse>::difference_type const\n\t\toffset) noexcept\n{ // itr + offset\n\treturn (left += offset);\n}\ntemplate<typename T, int N, bool is_const, bool is_reverse>\n[[nodiscard]] inline constexpr auto operator+(\n\ttypename Board_iterator<T, N, is_const, is_reverse>::difference_type const\n\t\toffset,\n\tBoard_iterator<T, N, is_const, is_reverse> itr) noexcept\n{ // offset + itr\n\treturn (itr += offset);\n}\ntemplate<typename T, int N, bool is_const, bool is_reverse>\n[[nodiscard]] constexpr auto operator-(\n\tBoard_iterator<T, N, is_const, is_reverse> left,\n\ttypename Board_iterator<T, N, is_const, is_reverse>::difference_type const\n\t\toffset) noexcept\n{ // itr - offset\n\treturn (left += -offset);\n}\n\ntemplate<typename T, int N, bool is_const, bool is_reverse>\n[[nodiscard]] inline constexpr bool operator!=(\n\tBoard_iterator<T, N, is_const, is_reverse> const left,\n\tBoard_iterator<T, N, is_const, is_reverse> const right) noexcept\n{\n\treturn !(left == right);\n}\ntemplate<typename T, int N, bool is_const, bool is_reverse>\n[[nodiscard]] inline constexpr bool operator>(\n\tBoard_iterator<T, N, is_const, is_reverse> const left,\n\tBoard_iterator<T, N, is_const, is_reverse> const right) noexcept\n{\n\treturn (right < left);\n}\ntemplate<typename T, int N, bool is_const, bool is_reverse>\n[[nodiscard]] inline constexpr bool operator<=(\n\tBoard_iterator<T, N, is_const, is_reverse> const left,\n\tBoard_iterator<T, N, is_const, is_reverse> const right) noexcept\n{\n\treturn !(right < left);\n}\ntemplate<typename T, int N, bool is_const, bool is_reverse>\n[[nodiscard]] inline constexpr bool operator>=(\n\tBoard_iterator<T, N, is_const, is_reverse> const left,\n\tBoard_iterator<T, N, is_const, is_reverse> const right) noexcept\n{\n\treturn !(left < right);\n}\n\n} // namespace Sudoku\n", "meta": {"hexsha": "8817c9109e85278538fd20c32d3baadd29aeb341", "size": 9283, "ext": "h", "lang": "C", "max_stars_repo_path": "Sudoku/Sudoku/Board/Iterators.h", "max_stars_repo_name": "Farwaykorse/fwkSudoku", "max_stars_repo_head_hexsha": "05652d80fae2780f1327467225580e2c67dfa692", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-03-17T18:27:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-18T19:26:28.000Z", "max_issues_repo_path": "Sudoku/Sudoku/Board/Iterators.h", "max_issues_repo_name": "Farwaykorse/fwkSudoku", "max_issues_repo_head_hexsha": "05652d80fae2780f1327467225580e2c67dfa692", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 38.0, "max_issues_repo_issues_event_min_datetime": "2018-12-28T18:15:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-17T01:22:35.000Z", "max_forks_repo_path": "Sudoku/Sudoku/Board/Iterators.h", "max_forks_repo_name": "Farwaykorse/fwkSudoku", "max_forks_repo_head_hexsha": "05652d80fae2780f1327467225580e2c67dfa692", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-04-20T16:26:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-20T16:26:42.000Z", "avg_line_length": 31.0468227425, "max_line_length": 80, "alphanum_fraction": 0.6507594528, "num_tokens": 2207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.07263671137954406, "lm_q1q2_score": 0.03575092755878729}}
{"text": "// Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at\n// the Lawrence Livermore National Laboratory. LLNL-CODE-734707. All Rights\n// reserved. See files LICENSE and NOTICE for details.\n//\n// This file is part of CEED, a collection of benchmarks, miniapps, software\n// libraries and APIs for efficient high-order finite element and spectral\n// element discretizations for exascale applications. For more information and\n// source code availability see http://github.com/ceed.\n//\n// The CEED research is supported by the Exascale Computing Project 17-SC-20-SC,\n// a collaborative effort of two U.S. Department of Energy organizations (Office\n// of Science and the National Nuclear Security Administration) responsible for\n// the planning and preparation of a capable exascale ecosystem, including\n// software, applications, hardware, advanced system engineering and early\n// testbed platforms, in support of the nation's exascale computing imperative.\n\n//                        libCEED + PETSc Example: CEED BPs\n//\n// This example demonstrates a simple usage of libCEED with PETSc to solve the\n// CEED BP benchmark problems, see http://ceed.exascaleproject.org/bps.\n//\n// The code uses higher level communication protocols in DMPlex.\n//\n// Build with:\n//\n//     make bps [PETSC_DIR=</path/to/petsc>] [CEED_DIR=</path/to/libceed>]\n//\n// Sample runs:\n//\n//     ./bps -problem bp1 -degree 3\n//     ./bps -problem bp2 -degree 3\n//     ./bps -problem bp3 -degree 3\n//     ./bps -problem bp4 -degree 3\n//     ./bps -problem bp5 -degree 3 -ceed /cpu/self\n//     ./bps -problem bp6 -degree 3 -ceed /gpu/cuda\n//\n//TESTARGS -ceed {ceed_resource} -test -problem bp5 -degree 3 -ksp_max_it_clip 15,15\n\n/// @file\n/// CEED BPs example using PETSc with DMPlex\n/// See bpsraw.c for a \"raw\" implementation using a structured grid.\nconst char help[] = \"Solve CEED BPs using PETSc with DMPlex\\n\";\n\n#include <stdbool.h>\n#include <string.h>\n#include <ceed.h>\n#include <petsc.h>\n#include <petscdmplex.h>\n#include <petscksp.h>\n#include <petscsys.h>\n\n#include \"bps.h\"\n#include \"include/bpsproblemdata.h\"\n#include \"include/petscmacros.h\"\n#include \"include/petscutils.h\"\n#include \"include/matops.h\"\n#include \"include/structs.h\"\n#include \"include/libceedsetup.h\"\n\n#if PETSC_VERSION_LT(3,12,0)\n#ifdef PETSC_HAVE_CUDA\n#include <petsccuda.h>\n// Note: With PETSc prior to version 3.12.0, providing the source path to\n//       include 'cublas_v2.h' will be needed to use 'petsccuda.h'.\n#endif\n#endif\n\n// -----------------------------------------------------------------------------\n// Utilities\n// -----------------------------------------------------------------------------\n\n// Utility function, compute three factors of an integer\nstatic void Split3(PetscInt size, PetscInt m[3], bool reverse) {\n  for (PetscInt d=0, size_left=size; d<3; d++) {\n    PetscInt try = (PetscInt)PetscCeilReal(PetscPowReal(size_left, 1./(3 - d)));\n    while (try * (size_left / try) != size_left) try++;\n    m[reverse ? 2-d : d] = try;\n    size_left /= try;\n  }\n}\n\nstatic int Max3(const PetscInt a[3]) {\n  return PetscMax(a[0], PetscMax(a[1], a[2]));\n}\n\nstatic int Min3(const PetscInt a[3]) {\n  return PetscMin(a[0], PetscMin(a[1], a[2]));\n}\n\n// -----------------------------------------------------------------------------\n// Parameter structure for running problems\n// -----------------------------------------------------------------------------\ntypedef struct RunParams_ *RunParams;\nstruct RunParams_ {\n  MPI_Comm comm;\n  PetscBool test_mode, read_mesh, user_l_nodes, write_solution;\n  char *filename, *hostname;\n  PetscInt local_nodes, degree, q_extra, dim, num_comp_u, *mesh_elem;\n  PetscInt ksp_max_it_clip[2];\n  PetscMPIInt ranks_per_node;\n  BPType bp_choice;\n  PetscLogStage solve_stage;\n};\n\n// -----------------------------------------------------------------------------\n// Main body of program, called in a loop for performance benchmarking purposes\n// -----------------------------------------------------------------------------\nstatic PetscErrorCode RunWithDM(RunParams rp, DM dm,\n                                const char *ceed_resource) {\n  PetscErrorCode ierr;\n  double my_rt_start, my_rt, rt_min, rt_max;\n  PetscInt xl_size, l_size, g_size;\n  PetscScalar *r;\n  Vec X, X_loc, rhs, rhs_loc;\n  Mat mat_O;\n  KSP ksp;\n  UserO user_O;\n  Ceed ceed;\n  CeedData ceed_data;\n  CeedQFunction qf_error;\n  CeedOperator op_error;\n  CeedVector rhs_ceed, target;\n  VecType vec_type;\n  PetscMemType mem_type;\n\n  PetscFunctionBeginUser;\n  // Set up libCEED\n  CeedInit(ceed_resource, &ceed);\n  CeedMemType mem_type_backend;\n  CeedGetPreferredMemType(ceed, &mem_type_backend);\n\n  ierr = DMGetVecType(dm, &vec_type); CHKERRQ(ierr);\n  if (!vec_type) { // Not yet set by user -dm_vec_type\n    switch (mem_type_backend) {\n    case CEED_MEM_HOST: vec_type = VECSTANDARD; break;\n    case CEED_MEM_DEVICE: {\n      const char *resolved;\n      CeedGetResource(ceed, &resolved);\n      if (strstr(resolved, \"/gpu/cuda\")) vec_type = VECCUDA;\n      else if (strstr(resolved, \"/gpu/hip/occa\"))\n        vec_type = VECSTANDARD; // https://github.com/CEED/libCEED/issues/678\n      else if (strstr(resolved, \"/gpu/hip\")) vec_type = VECHIP;\n      else vec_type = VECSTANDARD;\n    }\n    }\n    ierr = DMSetVecType(dm, vec_type); CHKERRQ(ierr);\n  }\n\n  // Create global and local solution vectors\n  ierr = DMCreateGlobalVector(dm, &X); CHKERRQ(ierr);\n  ierr = VecGetLocalSize(X, &l_size); CHKERRQ(ierr);\n  ierr = VecGetSize(X, &g_size); CHKERRQ(ierr);\n  ierr = DMCreateLocalVector(dm, &X_loc); CHKERRQ(ierr);\n  ierr = VecGetSize(X_loc, &xl_size); CHKERRQ(ierr);\n  ierr = VecDuplicate(X, &rhs); CHKERRQ(ierr);\n\n  // Operator\n  ierr = PetscMalloc1(1, &user_O); CHKERRQ(ierr);\n  ierr = MatCreateShell(rp->comm, l_size, l_size, g_size, g_size,\n                        user_O, &mat_O); CHKERRQ(ierr);\n  ierr = MatShellSetOperation(mat_O, MATOP_MULT,\n                              (void(*)(void))MatMult_Ceed); CHKERRQ(ierr);\n  ierr = MatShellSetOperation(mat_O, MATOP_GET_DIAGONAL,\n                              (void(*)(void))MatGetDiag); CHKERRQ(ierr);\n  ierr = MatShellSetVecType(mat_O, vec_type); CHKERRQ(ierr);\n\n  // Print summary\n  if (!rp->test_mode) {\n    PetscInt P = rp->degree + 1, Q = P + rp->q_extra;\n\n    const char *used_resource;\n    CeedGetResource(ceed, &used_resource);\n\n    VecType vec_type;\n    ierr = VecGetType(X, &vec_type); CHKERRQ(ierr);\n\n    PetscInt c_start, c_end;\n    ierr = DMPlexGetHeightStratum(dm, 0, &c_start, &c_end); CHKERRQ(ierr);\n    PetscMPIInt comm_size;\n    ierr = MPI_Comm_size(rp->comm, &comm_size); CHKERRQ(ierr);\n    ierr = PetscPrintf(rp->comm,\n                       \"\\n-- CEED Benchmark Problem %d -- libCEED + PETSc --\\n\"\n                       \"  MPI:\\n\"\n                       \"    Hostname                           : %s\\n\"\n                       \"    Total ranks                        : %d\\n\"\n                       \"    Ranks per compute node             : %d\\n\"\n                       \"  PETSc:\\n\"\n                       \"    PETSc Vec Type                     : %s\\n\"\n                       \"  libCEED:\\n\"\n                       \"    libCEED Backend                    : %s\\n\"\n                       \"    libCEED Backend MemType            : %s\\n\"\n                       \"  Mesh:\\n\"\n                       \"    Number of 1D Basis Nodes (P)       : %d\\n\"\n                       \"    Number of 1D Quadrature Points (Q) : %d\\n\"\n                       \"    Global nodes                       : %D\\n\"\n                       \"    Local Elements                     : %D\\n\"\n                       \"    Owned nodes                        : %D\\n\"\n                       \"    DoF per node                       : %D\\n\",\n                       rp->bp_choice+1, rp->hostname, comm_size,\n                       rp->ranks_per_node, vec_type, used_resource,\n                       CeedMemTypes[mem_type_backend],\n                       P, Q, g_size/rp->num_comp_u, c_end - c_start, l_size/rp->num_comp_u,\n                       rp->num_comp_u);\n    CHKERRQ(ierr);\n  }\n\n  // Create RHS vector\n  ierr = VecDuplicate(X_loc, &rhs_loc); CHKERRQ(ierr);\n  ierr = VecZeroEntries(rhs_loc); CHKERRQ(ierr);\n  ierr = VecGetArrayAndMemType(rhs_loc, &r, &mem_type); CHKERRQ(ierr);\n  CeedVectorCreate(ceed, xl_size, &rhs_ceed);\n  CeedVectorSetArray(rhs_ceed, MemTypeP2C(mem_type), CEED_USE_POINTER, r);\n\n  ierr = PetscMalloc1(1, &ceed_data); CHKERRQ(ierr);\n  ierr = SetupLibceedByDegree(dm, ceed, rp->degree, rp->dim, rp->q_extra,\n                              rp->dim, rp->num_comp_u, g_size, xl_size, bp_options[rp->bp_choice],\n                              ceed_data, true, rhs_ceed, &target); CHKERRQ(ierr);\n\n  // Gather RHS\n  CeedVectorTakeArray(rhs_ceed, MemTypeP2C(mem_type), NULL);\n  ierr = VecRestoreArrayAndMemType(rhs_loc, &r); CHKERRQ(ierr);\n  ierr = VecZeroEntries(rhs); CHKERRQ(ierr);\n  ierr = DMLocalToGlobal(dm, rhs_loc, ADD_VALUES, rhs); CHKERRQ(ierr);\n  CeedVectorDestroy(&rhs_ceed);\n\n  // Create the error QFunction\n  CeedQFunctionCreateInterior(ceed, 1, bp_options[rp->bp_choice].error,\n                              bp_options[rp->bp_choice].error_loc, &qf_error);\n  CeedQFunctionAddInput(qf_error, \"u\", rp->num_comp_u, CEED_EVAL_INTERP);\n  CeedQFunctionAddInput(qf_error, \"true_soln\", rp->num_comp_u, CEED_EVAL_NONE);\n  CeedQFunctionAddOutput(qf_error, \"error\", rp->num_comp_u, CEED_EVAL_NONE);\n\n  // Create the error operator\n  CeedOperatorCreate(ceed, qf_error, CEED_QFUNCTION_NONE, CEED_QFUNCTION_NONE,\n                     &op_error);\n  CeedOperatorSetField(op_error, \"u\", ceed_data->elem_restr_u,\n                       ceed_data->basis_u, CEED_VECTOR_ACTIVE);\n  CeedOperatorSetField(op_error, \"true_soln\", ceed_data->elem_restr_u_i,\n                       CEED_BASIS_COLLOCATED, target);\n  CeedOperatorSetField(op_error, \"error\", ceed_data->elem_restr_u_i,\n                       CEED_BASIS_COLLOCATED, CEED_VECTOR_ACTIVE);\n\n  // Set up Mat\n  user_O->comm = rp->comm;\n  user_O->dm = dm;\n  user_O->X_loc = X_loc;\n  ierr = VecDuplicate(X_loc, &user_O->Y_loc); CHKERRQ(ierr);\n  user_O->x_ceed = ceed_data->x_ceed;\n  user_O->y_ceed = ceed_data->y_ceed;\n  user_O->op = ceed_data->op_apply;\n  user_O->ceed = ceed;\n\n  ierr = KSPCreate(rp->comm, &ksp); CHKERRQ(ierr);\n  {\n    PC pc;\n    ierr = KSPGetPC(ksp, &pc); CHKERRQ(ierr);\n    if (rp->bp_choice == CEED_BP1 || rp->bp_choice == CEED_BP2) {\n      ierr = PCSetType(pc, PCJACOBI); CHKERRQ(ierr);\n      ierr = PCJacobiSetType(pc, PC_JACOBI_ROWSUM); CHKERRQ(ierr);\n    } else {\n      ierr = PCSetType(pc, PCNONE); CHKERRQ(ierr);\n    }\n    ierr = KSPSetType(ksp, KSPCG); CHKERRQ(ierr);\n    ierr = KSPSetNormType(ksp, KSP_NORM_NATURAL); CHKERRQ(ierr);\n    ierr = KSPSetTolerances(ksp, 1e-10, PETSC_DEFAULT, PETSC_DEFAULT,\n                            PETSC_DEFAULT); CHKERRQ(ierr);\n  }\n  ierr = KSPSetOperators(ksp, mat_O, mat_O); CHKERRQ(ierr);\n\n  // First run's performance log is not considered for benchmarking purposes\n  ierr = KSPSetTolerances(ksp, 1e-10, PETSC_DEFAULT, PETSC_DEFAULT, 1);\n  CHKERRQ(ierr);\n  my_rt_start = MPI_Wtime();\n  ierr = KSPSolve(ksp, rhs, X); CHKERRQ(ierr);\n  my_rt = MPI_Wtime() - my_rt_start;\n  ierr = MPI_Allreduce(MPI_IN_PLACE, &my_rt, 1, MPI_DOUBLE, MPI_MIN, rp->comm);\n  CHKERRQ(ierr);\n  // Set maxits based on first iteration timing\n  if (my_rt > 0.02) {\n    ierr = KSPSetTolerances(ksp, 1e-10, PETSC_DEFAULT, PETSC_DEFAULT,\n                            rp->ksp_max_it_clip[0]);\n    CHKERRQ(ierr);\n  } else {\n    ierr = KSPSetTolerances(ksp, 1e-10, PETSC_DEFAULT, PETSC_DEFAULT,\n                            rp->ksp_max_it_clip[1]);\n    CHKERRQ(ierr);\n  }\n  ierr = KSPSetFromOptions(ksp); CHKERRQ(ierr);\n\n  // Timed solve\n  ierr = VecZeroEntries(X); CHKERRQ(ierr);\n  ierr = PetscBarrier((PetscObject)ksp); CHKERRQ(ierr);\n\n  // -- Performance logging\n  ierr = PetscLogStagePush(rp->solve_stage); CHKERRQ(ierr);\n\n  // -- Solve\n  my_rt_start = MPI_Wtime();\n  ierr = KSPSolve(ksp, rhs, X); CHKERRQ(ierr);\n  my_rt = MPI_Wtime() - my_rt_start;\n\n  // -- Performance logging\n  ierr = PetscLogStagePop();\n\n  // Output results\n  {\n    KSPType ksp_type;\n    KSPConvergedReason reason;\n    PetscReal rnorm;\n    PetscInt its;\n    ierr = KSPGetType(ksp, &ksp_type); CHKERRQ(ierr);\n    ierr = KSPGetConvergedReason(ksp, &reason); CHKERRQ(ierr);\n    ierr = KSPGetIterationNumber(ksp, &its); CHKERRQ(ierr);\n    ierr = KSPGetResidualNorm(ksp, &rnorm); CHKERRQ(ierr);\n    if (!rp->test_mode || reason < 0 || rnorm > 1e-8) {\n      ierr = PetscPrintf(rp->comm,\n                         \"  KSP:\\n\"\n                         \"    KSP Type                           : %s\\n\"\n                         \"    KSP Convergence                    : %s\\n\"\n                         \"    Total KSP Iterations               : %D\\n\"\n                         \"    Final rnorm                        : %e\\n\",\n                         ksp_type, KSPConvergedReasons[reason], its,\n                         (double)rnorm); CHKERRQ(ierr);\n    }\n    if (!rp->test_mode) {\n      ierr = PetscPrintf(rp->comm,\"  Performance:\\n\"); CHKERRQ(ierr);\n    }\n    {\n      PetscReal max_error;\n      ierr = ComputeErrorMax(user_O, op_error, X, target, &max_error);\n      CHKERRQ(ierr);\n      PetscReal tol = 5e-2;\n      if (!rp->test_mode || max_error > tol) {\n        ierr = MPI_Allreduce(&my_rt, &rt_min, 1, MPI_DOUBLE, MPI_MIN, rp->comm);\n        CHKERRQ(ierr);\n        ierr = MPI_Allreduce(&my_rt, &rt_max, 1, MPI_DOUBLE, MPI_MAX, rp->comm);\n        CHKERRQ(ierr);\n        ierr = PetscPrintf(rp->comm,\n                           \"    Pointwise Error (max)              : %e\\n\"\n                           \"    CG Solve Time                      : %g (%g) sec\\n\",\n                           (double)max_error, rt_max, rt_min); CHKERRQ(ierr);\n      }\n    }\n    if (!rp->test_mode) {\n      ierr = PetscPrintf(rp->comm,\n                         \"    DoFs/Sec in CG                     : %g (%g) million\\n\",\n                         1e-6*g_size*its/rt_max,\n                         1e-6*g_size*its/rt_min); CHKERRQ(ierr);\n    }\n  }\n\n  if (rp->write_solution) {\n    PetscViewer vtk_viewer_soln;\n\n    ierr = PetscViewerCreate(rp->comm, &vtk_viewer_soln); CHKERRQ(ierr);\n    ierr = PetscViewerSetType(vtk_viewer_soln, PETSCVIEWERVTK); CHKERRQ(ierr);\n    ierr = PetscViewerFileSetName(vtk_viewer_soln, \"solution.vtu\"); CHKERRQ(ierr);\n    ierr = VecView(X, vtk_viewer_soln); CHKERRQ(ierr);\n    ierr = PetscViewerDestroy(&vtk_viewer_soln); CHKERRQ(ierr);\n  }\n\n  // Cleanup\n  ierr = VecDestroy(&X); CHKERRQ(ierr);\n  ierr = VecDestroy(&X_loc); CHKERRQ(ierr);\n  ierr = VecDestroy(&user_O->Y_loc); CHKERRQ(ierr);\n  ierr = MatDestroy(&mat_O); CHKERRQ(ierr);\n  ierr = PetscFree(user_O); CHKERRQ(ierr);\n  ierr = CeedDataDestroy(0, ceed_data); CHKERRQ(ierr);\n\n  ierr = VecDestroy(&rhs); CHKERRQ(ierr);\n  ierr = VecDestroy(&rhs_loc); CHKERRQ(ierr);\n  ierr = KSPDestroy(&ksp); CHKERRQ(ierr);\n  CeedVectorDestroy(&target);\n  CeedQFunctionDestroy(&qf_error);\n  CeedOperatorDestroy(&op_error);\n  CeedDestroy(&ceed);\n  PetscFunctionReturn(0);\n}\n\nstatic PetscErrorCode Run(RunParams rp, PetscInt num_resources,\n                          char *const *ceed_resources, PetscInt num_bp_choices,\n                          const BPType *bp_choices) {\n  PetscInt ierr;\n  DM dm;\n\n  PetscFunctionBeginUser;\n  // Setup DM\n  if (rp->read_mesh) {\n    ierr = DMPlexCreateFromFile(PETSC_COMM_WORLD, rp->filename, PETSC_TRUE, &dm);\n    CHKERRQ(ierr);\n  } else {\n    if (rp->user_l_nodes) {\n      // Find a nicely composite number of elements no less than global nodes\n      PetscMPIInt size;\n      ierr = MPI_Comm_size(rp->comm, &size); CHKERRQ(ierr);\n      for (PetscInt g_elem =\n             PetscMax(1, size * rp->local_nodes / PetscPowInt(rp->degree, rp->dim));\n           ;\n           g_elem++) {\n        Split3(g_elem, rp->mesh_elem, true);\n        if (Max3(rp->mesh_elem) / Min3(rp->mesh_elem) <= 2) break;\n      }\n    }\n    ierr = DMPlexCreateBoxMesh(PETSC_COMM_WORLD, rp->dim, PETSC_FALSE,\n                               rp->mesh_elem,\n                               NULL, NULL, NULL, PETSC_TRUE, &dm); CHKERRQ(ierr);\n  }\n\n  {\n    DM dm_dist = NULL;\n    PetscPartitioner part;\n\n    ierr = DMPlexGetPartitioner(dm, &part); CHKERRQ(ierr);\n    ierr = PetscPartitionerSetFromOptions(part); CHKERRQ(ierr);\n    ierr = DMPlexDistribute(dm, 0, NULL, &dm_dist); CHKERRQ(ierr);\n    if (dm_dist) {\n      ierr = DMDestroy(&dm); CHKERRQ(ierr);\n      dm  = dm_dist;\n    }\n  }\n  // Disable default VECSTANDARD *after* distribution (which creates a Vec)\n  ierr = DMSetVecType(dm, NULL); CHKERRQ(ierr);\n\n  for (PetscInt b = 0; b < num_bp_choices; b++) {\n    DM dm_deg;\n    VecType vec_type;\n    PetscInt q_extra = rp->q_extra;\n    rp->bp_choice = bp_choices[b];\n    rp->num_comp_u = bp_options[rp->bp_choice].num_comp_u;\n    rp->q_extra = q_extra < 0 ? bp_options[rp->bp_choice].q_extra : q_extra;\n    ierr = DMClone(dm, &dm_deg); CHKERRQ(ierr);\n    ierr = DMGetVecType(dm, &vec_type); CHKERRQ(ierr);\n    ierr = DMSetVecType(dm_deg, vec_type); CHKERRQ(ierr);\n    // Create DM\n    PetscInt dim;\n    ierr = DMGetDimension(dm_deg, &dim); CHKERRQ(ierr);\n    ierr = SetupDMByDegree(dm_deg, rp->degree, rp->num_comp_u, dim,\n                           bp_options[rp->bp_choice].enforce_bc,\n                           bp_options[rp->bp_choice].bc_func); CHKERRQ(ierr);\n    for (PetscInt r = 0; r < num_resources; r++) {\n      ierr = RunWithDM(rp, dm_deg, ceed_resources[r]); CHKERRQ(ierr);\n    }\n    ierr = DMDestroy(&dm_deg); CHKERRQ(ierr);\n    rp->q_extra = q_extra;\n  }\n\n  ierr = DMDestroy(&dm); CHKERRQ(ierr);\n  PetscFunctionReturn(0);\n}\n\nint main(int argc, char **argv) {\n  PetscInt ierr, comm_size;\n  RunParams rp;\n  MPI_Comm comm;\n  char filename[PETSC_MAX_PATH_LEN];\n  char *ceed_resources[30];\n  PetscInt num_ceed_resources = 30;\n  char hostname[PETSC_MAX_PATH_LEN];\n\n  PetscInt dim = 3, mesh_elem[3] = {3, 3, 3};\n  PetscInt num_degrees = 30, degree[30] = {}, num_local_nodes = 2,\n                                          local_nodes[2] = {};\n  PetscMPIInt ranks_per_node;\n  PetscBool degree_set;\n  BPType bp_choices[10];\n  PetscInt num_bp_choices = 10;\n\n  // Initialize PETSc\n  ierr = PetscInitialize(&argc, &argv, NULL, help);\n  if (ierr) return ierr;\n  comm = PETSC_COMM_WORLD;\n  ierr = MPI_Comm_size(comm, &comm_size);\n  if (ierr != MPI_SUCCESS) return ierr;\n  #if defined(PETSC_HAVE_MPI_PROCESS_SHARED_MEMORY)\n  {\n    MPI_Comm splitcomm;\n    ierr = MPI_Comm_split_type(comm, MPI_COMM_TYPE_SHARED, 0, MPI_INFO_NULL,\n                               &splitcomm);\n    CHKERRQ(ierr);\n    ierr = MPI_Comm_size(splitcomm, &ranks_per_node); CHKERRQ(ierr);\n    ierr = MPI_Comm_free(&splitcomm); CHKERRQ(ierr);\n  }\n  #else\n  ranks_per_node = -1; // Unknown\n  #endif\n\n  // Setup all parameters needed in Run()\n  ierr = PetscMalloc1(1, &rp); CHKERRQ(ierr);\n  rp->comm = comm;\n\n  // Read command line options\n  ierr = PetscOptionsBegin(comm, NULL, \"CEED BPs in PETSc\", NULL);\n  CHKERRQ(ierr);\n  {\n    PetscBool set;\n    ierr = PetscOptionsEnumArray(\"-problem\", \"CEED benchmark problem to solve\",\n                                 NULL,\n                                 bp_types, (PetscEnum *)bp_choices, &num_bp_choices, &set);\n    CHKERRQ(ierr);\n    if (!set) {\n      bp_choices[0] = CEED_BP1;\n      num_bp_choices = 1;\n    }\n  }\n  rp->test_mode = PETSC_FALSE;\n  ierr = PetscOptionsBool(\"-test\",\n                          \"Testing mode (do not print unless error is large)\",\n                          NULL, rp->test_mode, &rp->test_mode, NULL); CHKERRQ(ierr);\n  rp->write_solution = PETSC_FALSE;\n  ierr = PetscOptionsBool(\"-write_solution\", \"Write solution for visualization\",\n                          NULL, rp->write_solution, &rp->write_solution, NULL);\n  CHKERRQ(ierr);\n  degree[0] = rp->test_mode ? 3 : 2;\n  ierr = PetscOptionsIntArray(\"-degree\",\n                              \"Polynomial degree of tensor product basis\", NULL,\n                              degree, &num_degrees, &degree_set); CHKERRQ(ierr);\n  if (!degree_set)\n    num_degrees = 1;\n  rp->q_extra = PETSC_DECIDE;\n  ierr = PetscOptionsInt(\"-q_extra\",\n                         \"Number of extra quadrature points (-1 for auto)\", NULL,\n                         rp->q_extra, &rp->q_extra, NULL); CHKERRQ(ierr);\n  {\n    PetscBool set;\n    ierr = PetscOptionsStringArray(\"-ceed\",\n                                   \"CEED resource specifier (comma-separated list)\", NULL,\n                                   ceed_resources, &num_ceed_resources, &set); CHKERRQ(ierr);\n    if (!set) {\n      ierr = PetscStrallocpy( \"/cpu/self\", &ceed_resources[0]); CHKERRQ(ierr);\n      num_ceed_resources = 1;\n    }\n  }\n  ierr = PetscGetHostName(hostname, sizeof hostname); CHKERRQ(ierr);\n  ierr = PetscOptionsString(\"-hostname\", \"Hostname for output\", NULL, hostname,\n                            hostname, sizeof(hostname), NULL); CHKERRQ(ierr);\n  rp->read_mesh = PETSC_FALSE;\n  ierr = PetscOptionsString(\"-mesh\", \"Read mesh from file\", NULL, filename,\n                            filename, sizeof(filename), &rp->read_mesh);\n  CHKERRQ(ierr);\n  rp->filename = filename;\n  if (!rp->read_mesh) {\n    PetscInt tmp = dim;\n    ierr = PetscOptionsIntArray(\"-cells\", \"Number of cells per dimension\", NULL,\n                                mesh_elem, &tmp, NULL); CHKERRQ(ierr);\n  }\n  local_nodes[0] = 1000;\n  ierr = PetscOptionsIntArray(\"-local_nodes\",\n                              \"Target number of locally owned nodes per \"\n                              \"process (single value or min,max)\",\n                              NULL, local_nodes, &num_local_nodes, &rp->user_l_nodes);\n  CHKERRQ(ierr);\n  if (num_local_nodes < 2)\n    local_nodes[1] = 2 * local_nodes[0];\n  {\n    PetscInt two = 2;\n    rp->ksp_max_it_clip[0] = 5;\n    rp->ksp_max_it_clip[1] = 20;\n    ierr = PetscOptionsIntArray(\"-ksp_max_it_clip\",\n                                \"Min and max number of iterations to use during benchmarking\",\n                                NULL, rp->ksp_max_it_clip, &two, NULL); CHKERRQ(ierr);\n  }\n  if (!degree_set) {\n    PetscInt max_degree = 8;\n    ierr = PetscOptionsInt(\"-max_degree\",\n                           \"Range of degrees [1, max_degree] to run with\",\n                           NULL, max_degree, &max_degree, NULL);\n    CHKERRQ(ierr);\n    for (PetscInt i = 0; i < max_degree; i++)\n      degree[i] = i + 1;\n    num_degrees = max_degree;\n  }\n  {\n    PetscBool flg;\n    PetscInt p = ranks_per_node;\n    ierr = PetscOptionsInt(\"-p\", \"Number of MPI ranks per node\", NULL,\n                           p, &p, &flg);\n    CHKERRQ(ierr);\n    if (flg) ranks_per_node = p;\n  }\n\n  ierr = PetscOptionsEnd();\n  CHKERRQ(ierr);\n\n  // Register PETSc logging stage\n  ierr = PetscLogStageRegister(\"Solve Stage\", &rp->solve_stage);\n  CHKERRQ(ierr);\n\n  rp->hostname = hostname;\n  rp->dim = dim;\n  rp->mesh_elem = mesh_elem;\n  rp->ranks_per_node = ranks_per_node;\n\n  for (PetscInt d = 0; d < num_degrees; d++) {\n    PetscInt deg = degree[d];\n    for (PetscInt n = local_nodes[0]; n < local_nodes[1]; n *= 2) {\n      rp->degree = deg;\n      rp->local_nodes = n;\n      ierr = Run(rp, num_ceed_resources, ceed_resources,\n                 num_bp_choices, bp_choices); CHKERRQ(ierr);\n    }\n  }\n  // Clear memory\n  ierr = PetscFree(rp); CHKERRQ(ierr);\n  for (PetscInt i=0; i<num_ceed_resources; i++) {\n    ierr = PetscFree(ceed_resources[i]); CHKERRQ(ierr);\n  }\n  return PetscFinalize();\n}\n", "meta": {"hexsha": "ed7ecd797d4ac1cf574915e74d4dbb4d25ce9748", "size": 23369, "ext": "c", "lang": "C", "max_stars_repo_path": "examples/petsc/bps.c", "max_stars_repo_name": "AdelekeBankole/libCEED", "max_stars_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 123.0, "max_stars_repo_stars_event_min_datetime": "2018-01-29T02:04:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T18:13:48.000Z", "max_issues_repo_path": "examples/petsc/bps.c", "max_issues_repo_name": "AdelekeBankole/libCEED", "max_issues_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 781.0, "max_issues_repo_issues_event_min_datetime": "2017-12-22T17:20:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T21:34:34.000Z", "max_forks_repo_path": "examples/petsc/bps.c", "max_forks_repo_name": "AdelekeBankole/libCEED", "max_forks_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2017-12-27T22:35:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:02:07.000Z", "avg_line_length": 38.3727422003, "max_line_length": 98, "alphanum_fraction": 0.5986563396, "num_tokens": 6299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091957, "lm_q2_score": 0.06954175173725284, "lm_q1q2_score": 0.03449923392744973}}
{"text": "/*\n Copyright (C) 2002 M. Marques, A. Castro, A. Rubio, G. Bertsch, D. Strubbe\n\n This program is free software; you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2, or (at your option)\n any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n 02110-1301, USA.\n\n*/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <strings.h>\n#include <ctype.h>\n#include <math.h>\n#include <gsl/gsl_complex_math.h>\n\n#include \"symbols.h\"\n#include \"gsl_userdef.h\"\n\n/* The symbol table: a chain of `struct symrec'.  */\nsymrec *sym_table = (symrec *)0;\n\nvoid str_tolower(char *in)\n{\n  for(; *in; in++)\n    *in = (char)tolower(*in);\n}\n\nvoid sym_mark_table_used ()\n{\n  symrec *ptr;\n\n  for (ptr = sym_table; ptr != (symrec *) 0;\n       ptr = (symrec *)ptr->next)\n  {\n    ptr->used = 1;\n  }\n}\n\nsymrec *putsym (const char *sym_name, symrec_type sym_type)  \n{\n  symrec *ptr;\n  ptr = (symrec *)malloc(sizeof(symrec));\n\n  /* names are always lowercase */\n  ptr->name = strdup(sym_name);\n  str_tolower(ptr->name);\n  \n  ptr->def  = 0;\n  ptr->used = 0;\n  ptr->type = sym_type;\n  GSL_SET_COMPLEX(&ptr->value.c, 0, 0); /* set value to 0 even if fctn.  */\n  ptr->next = (struct symrec *)sym_table;\n  sym_table = ptr;\n  return ptr;\n}\n\nsymrec *getsym (const char *sym_name)\n{\n  symrec *ptr;\n  for (ptr = sym_table; ptr != (symrec *) 0;\n       ptr = (symrec *)ptr->next)\n    if (strcasecmp(ptr->name,sym_name) == 0){\n      ptr->used = 1;\n      return ptr;\n    }\n  return (symrec *) 0;\n}\n\nint rmsym (const char *sym_name)\n{\n  symrec *ptr, *prev;\n  for (prev = (symrec *) 0, ptr = sym_table; ptr != (symrec *) 0;\n       prev = ptr, ptr = ptr->next)\n    if (strcasecmp(ptr->name,sym_name) == 0){\n      if(prev == (symrec *) 0)\n\tsym_table = ptr->next;\n      else\n\tprev->next = ptr->next;\n      free(ptr->name);\n      free(ptr);\n      \n      return 1;\n    }\n  \n  return 0;\n}\n\nstruct init_fntc{\n  char *fname;\n  int  nargs;\n  gsl_complex (*fnctptr)();\n};\n\nvoid sym_notdef (symrec *sym)\n{\n  fprintf(stderr, \"Parser error: symbol '%s' used before being defined.\\n\", sym->name);\n  exit(1);\n}\n\nvoid sym_redef (symrec *sym)\n{\n  fprintf(stderr, \"Parser warning: redefining symbol, previous value \");\n  sym_print(stderr, sym);\n  fprintf(stderr, \"\\n\");\n}\n\nvoid sym_wrong_arg (symrec *sym)\n{\n  if(sym->type == S_BLOCK) {\n    fprintf(stderr, \"Parser error: block name '%s' used in variable context.\\n\", sym->name);\n  } else if(sym->type == S_STR) {\n    fprintf(stderr, \"Parser error: string variable '%s' used in expression context.\\n\", sym->name);\n  } else {\n    fprintf(stderr, \"Parser error: function '%s' requires %d argument(s).\\n\", sym->name, sym->nargs);\n  }\n  exit(1);\n}\n\nstatic struct init_fntc arith_fncts[] = {\n  {\"sqrt\",   1, (gsl_complex (*)()) &gsl_complex_sqrt},\n  {\"exp\",    1, (gsl_complex (*)()) &gsl_complex_exp},\n  {\"ln\",     1, (gsl_complex (*)()) &gsl_complex_log},\n  {\"log\",    1, (gsl_complex (*)()) &gsl_complex_log},\n  {\"log10\",  1, (gsl_complex (*)()) &gsl_complex_log10},\n  {\"logb\",   2, (gsl_complex (*)()) &gsl_complex_log_b}, /* takes two arguments logb(z, b) = log_b(z) */\n\n  {\"arg\",    1, (gsl_complex (*)()) &gsl_complex_carg},\n  {\"abs\",    1, (gsl_complex (*)()) &gsl_complex_cabs},\n  {\"abs2\",   1, (gsl_complex (*)()) &gsl_complex_cabs2},\n  {\"logabs\", 1, (gsl_complex (*)()) &gsl_complex_clogabs},\n\n  {\"conjg\",  1, (gsl_complex (*)()) &gsl_complex_conjugate},\n  {\"inv\",    1, (gsl_complex (*)()) &gsl_complex_inverse},\n\n  {\"sin\",    1, (gsl_complex (*)()) &gsl_complex_sin},\n  {\"cos\",    1, (gsl_complex (*)()) &gsl_complex_cos},\n  {\"tan\",    1, (gsl_complex (*)()) &gsl_complex_tan},\n  {\"sec\",    1, (gsl_complex (*)()) &gsl_complex_sec},\n  {\"csc\",    1, (gsl_complex (*)()) &gsl_complex_csc},\n  {\"cot\",    1, (gsl_complex (*)()) &gsl_complex_cot},\n\n  {\"asin\",   1, (gsl_complex (*)()) &gsl_complex_arcsin},\n  {\"acos\",   1, (gsl_complex (*)()) &gsl_complex_arccos},\n  {\"atan\",   1, (gsl_complex (*)()) &gsl_complex_arctan},\n  {\"atan2\",  2, (gsl_complex (*)()) &gsl_complex_arctan2}, /* takes two arguments atan2(y,x) = atan(y/x) */\n  {\"asec\",   1, (gsl_complex (*)()) &gsl_complex_arcsec},\n  {\"acsc\",   1, (gsl_complex (*)()) &gsl_complex_arccsc},\n  {\"acot\",   1, (gsl_complex (*)()) &gsl_complex_arccot},\n\n  {\"sinh\",   1, (gsl_complex (*)()) &gsl_complex_sinh},\n  {\"cosh\",   1, (gsl_complex (*)()) &gsl_complex_cosh},\n  {\"tanh\",   1, (gsl_complex (*)()) &gsl_complex_tanh},\n  {\"sech\",   1, (gsl_complex (*)()) &gsl_complex_sech},\n  {\"csch\",   1, (gsl_complex (*)()) &gsl_complex_csch},\n  {\"coth\",   1, (gsl_complex (*)()) &gsl_complex_coth},\n\n  {\"asinh\",  1, (gsl_complex (*)()) &gsl_complex_arcsinh},\n  {\"acosh\",  1, (gsl_complex (*)()) &gsl_complex_arccosh},\n  {\"atanh\",  1, (gsl_complex (*)()) &gsl_complex_arctanh},\n  {\"asech\",  1, (gsl_complex (*)()) &gsl_complex_arcsech},\n  {\"acsch\",  1, (gsl_complex (*)()) &gsl_complex_arccsch},\n  {\"acoth\",  1, (gsl_complex (*)()) &gsl_complex_arccoth},\t\n \n/* user-defined step function. this is not available in GSL, \n   but we use GSL namespacing and macros here. */\n  {\"step\",   1, (gsl_complex (*)()) &gsl_complex_step_real},\n\n/* Minimum and maximum of two arguments (comparing real parts) */  \n  {\"min\",    2, (gsl_complex (*)()) &gsl_complex_min_real},\n  {\"max\",    2, (gsl_complex (*)()) &gsl_complex_max_real},\n\n  {\"erf\",    1, (gsl_complex (*)()) &gsl_complex_erf},\n\n  {\"realpart\", 1, (gsl_complex (*)()) &gsl_complex_realpart},\n  {\"imagpart\", 1, (gsl_complex (*)()) &gsl_complex_imagpart},\n  {\"round\",   1, (gsl_complex (*)()) &gsl_complex_round},\n  {\"floor\",   1, (gsl_complex (*)()) &gsl_complex_floor},\n  {\"ceiling\", 1, (gsl_complex (*)()) &gsl_complex_ceiling},\n\n  {\"rand\",    0, (gsl_complex (*)()) &gsl_complex_rand},\n\n  {0, 0, 0}\n};\n\nstruct init_cnst{\n\tchar *fname;\n\tdouble re;\n\tdouble im;\n};\n\nstatic struct init_cnst arith_cnts[] = {\n\t{\"pi\",    M_PI, 0}, \n\t{\"e\",      M_E, 0},\n\t{\"i\",        0, 1},\n\t{\"true\",     1, 0}, \n\t{\"yes\",      1, 0},\n\t{\"false\",    0, 0}, \n\t{\"no\",       0, 0},\n\t{0,          0, 0}\n};\n\nchar *reserved_symbols[] = {\n  \"x\", \"y\", \"z\", \"r\", \"w\", \"t\", 0\n};\n\nvoid sym_init_table ()  /* puts arithmetic functions in table. */\n{\n  int i;\n  symrec *ptr;\n  for (i = 0; arith_fncts[i].fname != 0; i++){\n    ptr = putsym (arith_fncts[i].fname, S_FNCT);\n    ptr->def = 1;\n    ptr->used = 1;\n    ptr->nargs = arith_fncts[i].nargs;\n    ptr->value.fnctptr = arith_fncts[i].fnctptr;\n  }\n\n  /* now the constants */\n  for (i = 0; arith_cnts[i].fname != 0; i++){\n    ptr = putsym(arith_cnts[i].fname, S_CMPLX);\n    ptr->def = 1;\n    ptr->used = 1;\n    GSL_SET_COMPLEX(&ptr->value.c, arith_cnts[i].re, arith_cnts[i].im);\n  }\n}\n\nvoid sym_end_table()\n{\n  symrec *ptr, *ptr2;\n\n  for (ptr = sym_table; ptr != NULL;){\n    free(ptr->name);\n    switch(ptr->type){\n    case S_STR:\n      free(ptr->value.str);\n      break;\n    case S_BLOCK:\n      if(ptr->value.block->n > 0){\n\tfree(ptr->value.block->lines);\n      }\n      free(ptr->value.block);\n      break;\n    case S_CMPLX:\n    case S_FNCT:\n      break;\n    }\n    ptr2 = ptr->next;\n    free(ptr);\n    ptr = ptr2;\n  }\n  \n  sym_table = NULL;\n}\n\n/* this function is defined in src/basic/varinfo_low.c */\nint varinfo_variable_exists(const char * var_name);\n\nvoid sym_output_table(int only_unused, int mpiv_node)\n{\n  FILE *f;\n  symrec *ptr;\n  int any_unused = 0;\n\n  if(mpiv_node != 0) {\n    return;\n  }\n  \n  if(only_unused) {\n    f = stderr;\n  } else {\n    f = stdout;\n  }\n  \n  for(ptr = sym_table; ptr != NULL; ptr = ptr->next){\n    if(only_unused && ptr->used == 1) continue;\n    if(only_unused && varinfo_variable_exists(ptr->name)) continue;\n    if(any_unused == 0) {\n      fprintf(f, \"\\nParser warning: possible mistakes in input file.\\n\");\n      fprintf(f, \"List of variable assignments not used by parser:\\n\");\n      any_unused = 1;\n    }\n\n    sym_print(f, ptr);\n  }\n  if(any_unused == 1) {\n    fprintf(f, \"\\n\");\n  }\n}\n\nvoid sym_print(FILE *f, const symrec *ptr)\n{\n  fprintf(f, \"%s\", ptr->name);\n  switch(ptr->type){\n  case S_CMPLX:\n    if(fabs(GSL_IMAG(ptr->value.c)) < 1.0e-14){\n      fprintf(f, \" = %f\\n\", GSL_REAL(ptr->value.c));\n    } else {\n      fprintf(f, \" = (%f,%f)\\n\", GSL_REAL(ptr->value.c), GSL_IMAG(ptr->value.c));\n    }\n    break;\n  case S_STR:\n    fprintf(f, \" = \\\"%s\\\"\\n\", ptr->value.str);\n    break;\n  case S_BLOCK:\n    fprintf(f, \"%s\\n\", \" <= BLOCK\");\n    break;\n  case S_FNCT:\n    fprintf(f, \"%s\\n\", \" <= FUNCTION\");\n    break;\n  }\n}\n", "meta": {"hexsha": "12d95987f26290c4f1860e03cd305fc8c96eea31", "size": 8862, "ext": "c", "lang": "C", "max_stars_repo_path": "liboct_parser/symbols.c", "max_stars_repo_name": "shunsuke-sato/octopus", "max_stars_repo_head_hexsha": "dcf68a185cdb13708395546b1557ca46aed969f6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-11-17T09:03:11.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-17T06:31:08.000Z", "max_issues_repo_path": "liboct_parser/symbols.c", "max_issues_repo_name": "shunsuke-sato/octopus", "max_issues_repo_head_hexsha": "dcf68a185cdb13708395546b1557ca46aed969f6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-08-11T19:14:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-11T19:14:06.000Z", "max_forks_repo_path": "liboct_parser/symbols.c", "max_forks_repo_name": "shunsuke-sato/octopus", "max_forks_repo_head_hexsha": "dcf68a185cdb13708395546b1557ca46aed969f6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-11-22T20:30:46.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-29T23:24:51.000Z", "avg_line_length": 27.2676923077, "max_line_length": 107, "alphanum_fraction": 0.5971563981, "num_tokens": 2937, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.06853749065376102, "lm_q1q2_score": 0.03426874532688051}}
{"text": "/*\n * GSLIntegrator.h\n *\n *  Created on: 6 cze 2020\n *      Author: tomhof\n */\n\n#ifndef SRC_GSLINTEGRATOR_H_\n#define SRC_GSLINTEGRATOR_H_\n\n#include <stdlib.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_monte.h>\n#include <gsl/gsl_monte_plain.h>\n#include <gsl/gsl_monte_miser.h>\n#include <gsl/gsl_monte_vegas.h>\n\nclass GSLIntegrator {\nprivate:\n\tsize_t calls = 50000;\npublic:\n\tGSLIntegrator();\n\tvirtual ~GSLIntegrator();\n    double integrate(double (*f)(double * x_array, size_t dim, void * params), double a1, double b1, double a2, double b2, double* int_err);\n    void display_results(char *title, double result, double error);\n\n\tsize_t getCalls() const {\n\t\treturn calls;\n\t}\n\n\tvoid setCalls(size_t calls = 50000) {\n\t\tthis->calls = calls;\n\t}\n};\n\n#endif /* SRC_GSLINTEGRATOR_H_ */\n", "meta": {"hexsha": "d24de5aad7309fdd6125da094391f6c7d8a70393", "size": 779, "ext": "h", "lang": "C", "max_stars_repo_path": "NakaoMethod/src/GSLIntegrator.h", "max_stars_repo_name": "tomaszhof/interval_arithmetic", "max_stars_repo_head_hexsha": "0d1e7c842803f8ca211bf2a9d7239f7541452492", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NakaoMethod/src/GSLIntegrator.h", "max_issues_repo_name": "tomaszhof/interval_arithmetic", "max_issues_repo_head_hexsha": "0d1e7c842803f8ca211bf2a9d7239f7541452492", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NakaoMethod/src/GSLIntegrator.h", "max_forks_repo_name": "tomaszhof/interval_arithmetic", "max_forks_repo_head_hexsha": "0d1e7c842803f8ca211bf2a9d7239f7541452492", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.0540540541, "max_line_length": 140, "alphanum_fraction": 0.7098844673, "num_tokens": 236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.07263671137954406, "lm_q1q2_score": 0.034051409443686065}}
{"text": "\\documentclass{report}\n\\usepackage[T1]{fontenc}\n\\usepackage{bera}\n\n\\usepackage[pdftex,usenames,dvipsnames]{color}\n\\usepackage{listings}\n\\definecolor{mycode}{rgb}{0.9,0.9,1}\n\\lstset{language=c++,tabsize=1,basicstyle=\\scriptsize,backgroundcolor=\\color{mycode}}\n\n\\usepackage{hyperref}\n\\usepackage{fancyhdr}\n\\pagestyle{fancy}\n\\usepackage{verbatim}\n\\begin{document}\n\n%\\title{The Powell Class for Minimization of Functions}\n%\\author{G.A.}\n%\\maketitle\n\n\\begin{comment}\n@o Minimizer.h -t\n@{\n/*\n@i license.txt\n*/\n@}\n\\end{comment}\n\n\\section{A class to minimize a function without using Derivatives}\nThis requires the GNU Scientific Library, libraries and devel. headers.\n\nExplain usage here. FIXME.\n\nThis is the structure of this file:\n\n@o Minimizer.h -t\n@{\n#ifndef MINIMIZER_H\n#define MINIMIZER_H\n\n#include <iostream>\n#include <vector>\n#include <stdexcept>\nextern \"C\" {\n#include <gsl/gsl_multimin.h>\n}\n\nnamespace PsimagLite {\n\t@<MockVector@>\n\t@<MyFunction@>\n\t@<theClassHere@>\n} // namespace PsimagLite\n#endif // MINIMIZER_H\n\n@}\n\nAnd this is the class here:\n\n@d theClassHere\n@{\ntemplate<typename RealType,typename FunctionType>\nclass Minimizer {\n\t@<privateTypedefsAndConstants@>\npublic:\n\t@<constructor@>\n\t@<destructor@>\n\t@<publicFunctions@>\nprivate:\n\t@<privateFunctions@>\n\t@<privateData@>\n}; // class Minimizer\n@}\n\n\n@d privateTypedefsAndConstants\n@{\ntypedef typename FunctionType::FieldType FieldType;\ntypedef typename Vector<FieldType>::Type VectorType;\ntypedef Minimizer<RealType,FunctionType> ThisType;\n\n@}\n\n@d privateData\n@{\nFunctionType& function_;\nSizeType maxIter_;\nconst gsl_multimin_fminimizer_type *gslT_;\ngsl_multimin_fminimizer *gslS_;\n@}\n\n@d constructor\n@{\nMinimizer(FunctionType& function,SizeType maxIter)\n\t\t: function_(function),\n\t\t  maxIter_(maxIter),\n\t\t  gslT_(gsl_multimin_fminimizer_nmsimplex2),\n\t\t  gslS_(gsl_multimin_fminimizer_alloc(gslT_,function_.size()))\n{\n}\n@}\n\n@d publicFunctions\n@{\n@<simplex@>\n@}\n\n@d destructor\n@{\n~Minimizer()\n{\n\tgsl_multimin_fminimizer_free (gslS_);\n}\n@}\n\n\n@d simplex\n@{\nint simplex(VectorType& minVector,RealType delta=1e-3,RealType tolerance=1e-3)\n{\n\tgsl_vector *x;\n\t/* Starting point,  */\n\tx = gsl_vector_alloc (function_.size());\n\tfor (SizeType i=0;i<minVector.size();i++)\n\t\tgsl_vector_set (x, i, minVector[i]);\n\n\tgsl_vector *xs;\n\txs = gsl_vector_alloc (function_.size());\n\tfor (SizeType i=0;i<minVector.size();i++)\n\t\tgsl_vector_set (xs, i, delta);\n\n\tgsl_multimin_function func;\n\tfunc.f= myFunction<FunctionType>;\n\tfunc.n = function_.size();\n\tfunc.params = &function_;\n\tgsl_multimin_fminimizer_set (gslS_, &func, x, xs);\n\n\tfor (SizeType iter=0;iter<maxIter_;iter++) {\n\t\tint status = gsl_multimin_fminimizer_iterate (gslS_);\n\n\t\tif (status) throw RuntimeError(\"Minimizer::simplex(...): Error encountered\\n\");\n\n\t\tRealType size = gsl_multimin_fminimizer_size(gslS_);\n\t\tstatus = gsl_multimin_test_size(size, tolerance);\n\n\t\tif (status == GSL_SUCCESS) {\n\t\t\tfound(minVector,gslS_->x,iter);\n\t\t\tgsl_vector_free (x);\n\t\t\tgsl_vector_free (xs);\n\t\t\treturn iter;\n\t\t}\n\t}\n\tgsl_vector_free (x);\n\tgsl_vector_free (xs);\n\treturn -1;\n}\n@}\n\n@d privateFunctions\n@{\n@<found@>\n@}\n\n@d found\n@{\nvoid found(VectorType& minVector,gsl_vector* x,SizeType iter)\n{\n\tfor (SizeType i=0;i<minVector.size();i++)\n\t\tminVector[i] = gsl_vector_get(x,i);\n}\n@}\n\n@d MockVector\n@{\ntemplate<typename FieldType>\nclass MockVector {\npublic:\n\tMockVector(const gsl_vector *v) : v_(v)\n\t{\n\t}\n\tconst FieldType& operator[](SizeType i) const\n\t{\n\t\treturn v_->data[i];\n\t}\n\tSizeType size() const { return v_->size; }\nprivate:\n\tconst gsl_vector *v_;\n}; // class MockVector\n@}\n\n@d MyFunction\n@{\ntemplate<typename FunctionType>\ntypename FunctionType::FieldType myFunction(const gsl_vector *v, void *params)\n{\n\tMockVector<typename FunctionType::FieldType> mv(v);\n\tFunctionType* ft = (FunctionType *)params;\n\treturn ft->operator()(mv);\n}\n@}\n\n\\end{document}\n\n", "meta": {"hexsha": "0a18f2b0f305ccb7346011801c4693be7b9f96ab", "size": 3834, "ext": "w", "lang": "C", "max_stars_repo_path": "src/Minimizer.w", "max_stars_repo_name": "g1257/PsimagLite", "max_stars_repo_head_hexsha": "1cdeb4530c66cd41bd0c59af9ad2ecb1069ca010", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2015-08-19T16:06:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-05T02:37:47.000Z", "max_issues_repo_path": "src/Minimizer.w", "max_issues_repo_name": "npatel37/PsimagLiteORNL", "max_issues_repo_head_hexsha": "ffa0ffad75c5db218a9edea1a9581fed98c2648f", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2016-02-02T20:28:21.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-08T22:56:12.000Z", "max_forks_repo_path": "src/Minimizer.w", "max_forks_repo_name": "npatel37/PsimagLiteORNL", "max_forks_repo_head_hexsha": "ffa0ffad75c5db218a9edea1a9581fed98c2648f", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-04-29T17:28:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-22T03:33:19.000Z", "avg_line_length": 18.8866995074, "max_line_length": 85, "alphanum_fraction": 0.7282211789, "num_tokens": 1136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.07477005115479887, "lm_q1q2_score": 0.03389041156262909}}
{"text": "/* Siconos-Numerics, Copyright INRIA 2005-2018.\n * Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n * Siconos is a free software; you can redistribute it and/or modify\n * it under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n * Siconos is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with Siconos; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\n * Contact: Vincent ACARY, siconos-team@lists.gforge.inria.fr\n */\n\n#ifndef SiconosLAPACKE_H\n#define SiconosLAPACKE_H\n\n#include \"SiconosBlas.h\"\n#include <stdlib.h>\n#include <assert.h>\n#include <stdio.h>\n\n// -------- Headers and routines naming conventions for the different Lapack implementations --------\n\n// --- Intel MKL Header --- \n#if defined(HAS_MKL_LAPACKE) \n#include <mkl_lapacke.h>\n#else \n// Standard lapacke header\n#include <lapacke.h>\n#endif \n\n// Name of the routines\n#define LAPACK_NAME(N) LAPACKE_##N\n\n#define LA_TRANS 'T'\n#define LA_NOTRANS 'N'\n#define LA_UP 'U'\n#define LA_LO 'L'\n#define LA_NONUNIT 'N'\n#define LA_UNIT 'U'\n\n#define INTEGER(X) X\n#define INTEGERP(X) X\n#define CHAR(X) X\n\n#ifndef lapack_int\n#define lapack_int int\n#endif\n\n// --- DGESVD ---\n#if defined(HAS_LAPACK_DGESVD)\n#define WRAP_DGESVD(F,A1,A2,A3,A4,A5,A6,A7,A8,A9,A10,A11,A12,INFO)      \\\n  INFO = F(CblasColMajor,A1,A2,A3,A4,A5,A6,A7,A8,A9,A10,A11,A12)\n#else\n#define WRAP_DGESVD(F,A1,A2,A3,A4,A5,A6,A7,A8,A9,A10,A11,A12,INFO)      \\\n  fprintf(stderr, \"Your lapack version misses dgesvd function.\\n\");\n#endif\n  \n// --- DGETRS ---\n#define WRAP_DGETRS(F,A1,A2,A3,A4,A5,A6,A7,A8,INFO)   \\\n  INFO = F(CblasColMajor,A1,A2,A3,A4,A5,A6,A7,A8)\n     \n// --- DGESV ---\n#define WRAP_DGESV(F,A1,A2,A3,A4,A5,A6,A7,INFO)   \\\n  INFO = F(CblasColMajor,A1,A2,A3,A4,A5,A6,A7)\n     \n// --- DGELS ---\n#if defined(HAS_LAPACK_DGELS)\n#define WRAP_DGELS(F,A1,A2,A3,A4,A5,A6,A7,A8,INFO)    \\\n  INFO = F(CblasColMajor,A1,A2,A3,A4,A5,A6,A7,A8)\n#else\n#define WRAP_DGELS(F,A1,A2,A3,A4,A5,A6,A7,A8,INFO)                      \\\n  fprintf(stderr, \"Your lapack version misses dgels function.\\n\");\n#endif\n\n// --- DGETRI ---\n#define WRAP_DGETRI(F,A1,A2,A3,A4,INFO)         \\\n  INFO = F(CblasColMajor,A1,A2,A3,A4)\n\n// --- DPOTRF ---\n#define WRAP_DPOTRF(F,A1,A2,A3,A4,INFO)  \\\n  INFO = F(CblasColMajor,A1,A2,A3,A4)\n\n// --- DGETRF ---\n#define WRAP_DGETRF(F,A1,A2,A3,A4,A5,INFO)  \\\n  INFO = F(CblasColMajor,A1,A2,A3,A4,A5)\n \n// --- DTRTRS ---\n#if defined(HAS_LAPACK_DTRTRS)\n#define WRAP_DTRTRS(F,A1,A2,A3,A4,A5,A6,A7,A8,A9,INFO)  \\\n  INFO = F(CblasColMajor,A1,A2,A3,A4,A5,A6,A7,A8,A9)\n#else\n#define WRAP_DTRTRS(F,A1,A2,A3,A4,A5,A6,A7,A8,A9,INFO)                \\\n  fprintf(stderr, \"Your lapack version misses dtrtrs function.\\n\");\n#endif\n\n#endif // SICONOSLAPACKE_H\n", "meta": {"hexsha": "9e9b01811c894308dfa7e8791f0df251ec220c8c", "size": 3187, "ext": "h", "lang": "C", "max_stars_repo_path": "externals/blas_lapack/SiconosLapacke.h", "max_stars_repo_name": "ljktest/siconos", "max_stars_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "externals/blas_lapack/SiconosLapacke.h", "max_issues_repo_name": "ljktest/siconos", "max_issues_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "externals/blas_lapack/SiconosLapacke.h", "max_forks_repo_name": "ljktest/siconos", "max_forks_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-07T19:35:16.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-07T19:35:16.000Z", "avg_line_length": 30.6442307692, "max_line_length": 101, "alphanum_fraction": 0.6921870097, "num_tokens": 1072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814648038985, "lm_q2_score": 0.07807816407233607, "lm_q1q2_score": 0.03388447601331153}}
{"text": "//====---- Sudoku/Board_Section_iterator.h                            ----====//\n//\n// Location aware iterator implementation for Sections\n//====--------------------------------------------------------------------====//\n//\n// The iterator can return a Location object.\n// Included by Board_Section.h\n//\n//====--------------------------------------------------------------------====//\n#pragma once\n\n#include \"Sudoku/Location.h\"\n#include \"Sudoku/Location_Utilities.h\"\n#include \"Sudoku/traits.h\"\n#include <gsl/gsl> // index\n\n#include <iterator>\n#include <type_traits>\n\n#include \"Board.fwd.h\" // Forward declarations\n\n#include <cassert>\n\n\nnamespace Sudoku::Board_Section\n{\ntemplate<typename T, int N, Section S, bool is_const, bool is_reverse>\nclass Section_iterator;\n\n//====--- Aliases --------------------------------------------------------====//\ntemplate<typename T, int N>\nusing Row_iterator = Section_iterator<T, N, Section::row, false, false>;\ntemplate<typename T, int N>\nusing Col_iterator = Section_iterator<T, N, Section::col, false, false>;\ntemplate<typename T, int N>\nusing Block_iterator = Section_iterator<T, N, Section::block, false, false>;\ntemplate<typename T, int N>\nusing const_Row_iterator = Section_iterator<T, N, Section::row, true, false>;\ntemplate<typename T, int N>\nusing const_Col_iterator = Section_iterator<T, N, Section::col, true, false>;\ntemplate<typename T, int N>\nusing const_Block_iterator =\n\tSection_iterator<T, N, Section::block, true, false>;\ntemplate<typename T, int N>\nusing reverse_Row_iterator = Section_iterator<T, N, Section::row, false, true>;\ntemplate<typename T, int N>\nusing reverse_Col_iterator = Section_iterator<T, N, Section::col, false, true>;\ntemplate<typename T, int N>\nusing reverse_Block_iterator =\n\tSection_iterator<T, N, Section::block, false, true>;\ntemplate<typename T, int N>\nusing const_reverse_Row_iterator =\n\tSection_iterator<T, N, Section::row, true, true>;\ntemplate<typename T, int N>\nusing const_reverse_Col_iterator =\n\tSection_iterator<T, N, Section::col, true, true>;\ntemplate<typename T, int N>\nusing const_reverse_Block_iterator =\n\tSection_iterator<T, N, Section::block, true, true>;\n\n//====--------------------------------------------------------------------====//\ntemplate<typename T, int N, Section S, bool is_const, bool is_reverse>\nclass Section_iterator\n{\n\tusing owner_type =\n\t\tstd::conditional_t<is_const, Board<T, N> const, Board<T, N>>;\n\tusing Location       = ::Sudoku::Location<N>;\n\tusing Location_Block = ::Sudoku::Location_Block<N>;\n\npublic:\n\t// member types\n\tusing difference_type   = std::ptrdiff_t;\n\tusing value_type        = T;\n\tusing pointer           = std::conditional_t<is_const, T const*, T*>;\n\tusing reference         = std::conditional_t<is_const, T const&, T&>;\n\tusing iterator_category = std::random_access_iterator_tag;\n\n\t// Constructors\n\tconstexpr Section_iterator() noexcept\n\t{ // defaults to [r]begin()\n\t\tif constexpr (is_reverse)\n\t\t\telem_ = elem_size<N> - 1;\n\t}\n\ttemplate<\n\t\ttypename idT,\n\t\ttypename elT,\n\t\ttypename = std::enable_if_t<is_int_v<idT> && is_int_v<elT>>>\n\tconstexpr Section_iterator(owner_type* owner, idT id, elT elem) noexcept\n\t\t: board_(owner), id_(id), elem_(elem)\n\t{\n\t\tassert(is_valid_size<N>(id));\n\t}\n\t// [[implicit]] Type Conversion to const_(reverse_)iterator\n\t// NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions)\n\tconstexpr operator Section_iterator<T, N, S, true, is_reverse>()\n\t\tconst noexcept // (guide format)\n\t{\n\t\treturn Section_iterator<T, N, S, true, is_reverse>(board_, id_, elem_);\n\t}\n\n\t//====----------------------------------------------------------------====//\n\t[[nodiscard]] constexpr Location location() const noexcept\n\t{\n\t\tassert(is_valid_size<N>(elem_));\n\t\tusing ::Sudoku::Board_Section::Section;\n\t\tswitch (S)\n\t\t{\n\t\tcase Section::row: return Location(id_, elem_); break;\n\t\tcase Section::col: return Location(elem_, id_); break;\n\t\tcase Section::block: return Location_Block(id_, elem_); break;\n\t\t}\n\t}\n\t// Allows for conversion to Location\n\texplicit constexpr operator Location() const noexcept { return location(); }\n\n\t//====----------------------------------------------------------------====//\n\t[[nodiscard]] constexpr reference operator*() const noexcept\n\t{ // Only valid in a dereferenceable location:\n\t\tassert(board_ != nullptr && is_valid_size<N>(elem_));\n\t\treturn board_->operator[](location());\n\t}\n\t[[nodiscard]] constexpr pointer operator->() const noexcept\n\t{ // member access; equivalent to (*p).member\n\t\treturn std::pointer_traits<pointer>::pointer_to(**this);\n\t}\n\n\t//====----------------------------------------------------------------====//\n\tconstexpr Section_iterator& operator++() noexcept;\n\tconstexpr Section_iterator operator++(int) noexcept;\n\tconstexpr Section_iterator& operator--() noexcept;\n\tconstexpr Section_iterator operator--(int) noexcept;\n\tconstexpr Section_iterator&\n\t\toperator+=(const difference_type offset) noexcept;\n\tconstexpr Section_iterator&\n\t\toperator-=(const difference_type offset) noexcept;\n\n\t[[nodiscard]] friend constexpr difference_type operator-(\n\t\tSection_iterator const& left, Section_iterator const& right) noexcept\n\t{ // difference\n\t\tassert(is_same_Section(left, right));\n\t\tif constexpr (is_reverse)\n\t\t\treturn right.elem_ - left.elem_;\n\t\telse\n\t\t\treturn left.elem_ - right.elem_;\n\t}\n\n\t[[nodiscard]] constexpr reference\n\t\toperator[](const difference_type offset) const noexcept\n\t{\n\t\treturn (*(*this + offset));\n\t}\n\n\t//====----------------------------------------------------------------====//\n\t[[nodiscard]] friend constexpr bool operator==(\n\t\tSection_iterator const& left, Section_iterator const& right) noexcept\n\t{\n\t\tassert(is_same_Section(left, right));\n\t\treturn is_same_Section(left, right) && left.elem_ == right.elem_;\n\t}\n\t[[nodiscard]] friend constexpr bool operator<(\n\t\tSection_iterator const& left, Section_iterator const& right) noexcept\n\t{\n\t\tassert(is_same_Section(left, right));\n\t\tif constexpr (is_reverse)\n\t\t\treturn left.elem_ > right.elem_;\n\t\telse\n\t\t\treturn left.elem_ < right.elem_;\n\t}\n\nprivate:\n\towner_type* board_{nullptr};\n\tgsl::index id_{0};\n\tgsl::index elem_{0};\n\n\tfriend constexpr bool is_same_Section(\n\t\tSection_iterator const& A, Section_iterator const& B) noexcept\n\t{ // compare address of:\n\t\treturn A.board_ == B.board_ && A.id_ == B.id_;\n\t}\n};\n\n\n//====--------------------------------------------------------------------====//\ntemplate<typename T, int N, Section S, bool C, bool is_reverse>\nconstexpr Section_iterator<T, N, S, C, is_reverse>&\n\tSection_iterator<T, N, S, C, is_reverse>::operator++() noexcept\n{ // pre-increment\n\tassert(board_ != nullptr);\n\tif constexpr (is_reverse)\n\t{\n\t\tassert(elem_ >= 0);\n\t\t--elem_;\n\t}\n\telse\n\t{\n\t\tassert(elem_ < elem_size<N>);\n\t\t++elem_;\n\t}\n\treturn (*this);\n}\ntemplate<typename T, int N, Section S, bool C, bool R>\nconstexpr Section_iterator<T, N, S, C, R> // NOLINTNEXTLINE(readability/casting)\n\tSection_iterator<T, N, S, C, R>::operator++(int) noexcept\n{ // post-increment\n\tconst Section_iterator pre{*this};\n\toperator++();\n\treturn pre;\n}\ntemplate<typename T, int N, Section S, bool C, bool is_reverse>\nconstexpr Section_iterator<T, N, S, C, is_reverse>&\n\tSection_iterator<T, N, S, C, is_reverse>::operator--() noexcept\n{ // pre-decrement\n\tassert(board_ != nullptr);\n\tif constexpr (is_reverse)\n\t{\n\t\tassert(elem_ < elem_size<N> - 1);\n\t\t++elem_;\n\t}\n\telse\n\t{\n\t\tassert(elem_ > 0);\n\t\t--elem_;\n\t}\n\treturn (*this);\n}\ntemplate<typename T, int N, Section S, bool C, bool R>\nconstexpr Section_iterator<T, N, S, C, R> // NOLINTNEXTLINE(readability/casting)\n\tSection_iterator<T, N, S, C, R>::operator--(int) noexcept\n{ // post-decrement\n\tconst Section_iterator pre{*this};\n\toperator--();\n\treturn pre;\n}\ntemplate<typename T, int N, Section S, bool C, bool is_reverse>\nconstexpr Section_iterator<T, N, S, C, is_reverse>&\n\tSection_iterator<T, N, S, C, is_reverse>::operator+=(\n\t\tconst difference_type offset) noexcept\n{\n\tassert(offset == 0 || board_ != nullptr);\n\tif constexpr (is_reverse)\n\t{\n\t\telem_ -= offset;\n\t\tassert(elem_ >= -1);\n\t\tassert(elem_ < elem_size<N>);\n\t}\n\telse\n\t{\n\t\telem_ += offset;\n\t\tassert(elem_ >= 0);\n\t\tassert(elem_ <= elem_size<N>);\n\t}\n\treturn (*this);\n}\ntemplate<typename T, int N, Section S, bool C, bool is_reverse>\nconstexpr Section_iterator<T, N, S, C, is_reverse>&\n\tSection_iterator<T, N, S, C, is_reverse>::operator-=(\n\t\tconst difference_type offset) noexcept\n{\n\treturn operator+=(-offset);\n}\n\n//====--------------------------------------------------------------------====//\n// Free functions (non-friend)\n//====--------------------------------------------------------------------====//\ntemplate<typename T, int N, Section S, bool is_const, bool is_reverse>\n[[nodiscard]] constexpr auto operator+(\n\tSection_iterator<T, N, S, is_const, is_reverse> left,\n\ttypename Section_iterator<T, N, S, is_const, is_reverse>::\n\t\tdifference_type const offset) noexcept\n{ // itr + offset\n\treturn (left += offset);\n}\ntemplate<typename T, int N, Section S, bool is_const, bool is_reverse>\n[[nodiscard]] inline constexpr auto operator+(\n\ttypename Section_iterator<T, N, S, is_const, is_reverse>::\n\t\tdifference_type const offset,\n\tSection_iterator<T, N, S, is_const, is_reverse> itr) noexcept\n{ // offset + itr\n\treturn (itr += offset);\n}\ntemplate<typename T, int N, Section S, bool is_const, bool is_reverse>\n[[nodiscard]] constexpr auto operator-(\n\tSection_iterator<T, N, S, is_const, is_reverse> left,\n\ttypename Section_iterator<T, N, S, is_const, is_reverse>::\n\t\tdifference_type const offset) noexcept\n{ // itr - offset\n\treturn (left += -offset);\n}\n\ntemplate<typename T, int N, Section S, bool is_const, bool is_reverse>\n[[nodiscard]] inline constexpr bool operator!=(\n\tSection_iterator<T, N, S, is_const, is_reverse> const& left,\n\tSection_iterator<T, N, S, is_const, is_reverse> const& right) noexcept\n{\n\treturn !(left == right);\n}\ntemplate<typename T, int N, Section S, bool is_const, bool is_reverse>\n[[nodiscard]] inline constexpr bool operator>(\n\tSection_iterator<T, N, S, is_const, is_reverse> const& left,\n\tSection_iterator<T, N, S, is_const, is_reverse> const& right) noexcept\n{\n\treturn (right < left);\n}\ntemplate<typename T, int N, Section S, bool is_const, bool is_reverse>\n[[nodiscard]] inline constexpr bool operator<=(\n\tSection_iterator<T, N, S, is_const, is_reverse> const& left,\n\tSection_iterator<T, N, S, is_const, is_reverse> const& right) noexcept\n{\n\treturn !(right < left);\n}\ntemplate<typename T, int N, Section S, bool is_const, bool is_reverse>\n[[nodiscard]] inline constexpr bool operator>=(\n\tSection_iterator<T, N, S, is_const, is_reverse> const& left,\n\tSection_iterator<T, N, S, is_const, is_reverse> const& right) noexcept\n{\n\treturn !(left < right);\n}\n\n} // namespace Sudoku::Board_Section\n", "meta": {"hexsha": "49e5751c315592f8e627c945f299640ee22e6579", "size": 10676, "ext": "h", "lang": "C", "max_stars_repo_path": "Sudoku/Sudoku/Board/Section_iterator.h", "max_stars_repo_name": "Farwaykorse/fwkSudoku", "max_stars_repo_head_hexsha": "05652d80fae2780f1327467225580e2c67dfa692", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-03-17T18:27:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-18T19:26:28.000Z", "max_issues_repo_path": "Sudoku/Sudoku/Board/Section_iterator.h", "max_issues_repo_name": "Farwaykorse/fwkSudoku", "max_issues_repo_head_hexsha": "05652d80fae2780f1327467225580e2c67dfa692", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 38.0, "max_issues_repo_issues_event_min_datetime": "2018-12-28T18:15:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-17T01:22:35.000Z", "max_forks_repo_path": "Sudoku/Sudoku/Board/Section_iterator.h", "max_forks_repo_name": "Farwaykorse/fwkSudoku", "max_forks_repo_head_hexsha": "05652d80fae2780f1327467225580e2c67dfa692", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-04-20T16:26:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-20T16:26:42.000Z", "avg_line_length": 33.3625, "max_line_length": 80, "alphanum_fraction": 0.661952042, "num_tokens": 2601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.06754668456987209, "lm_q1q2_score": 0.033773342284936045}}
{"text": "/*\n *  Copyright 2008-2009 NVIDIA Corporation\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n */\n\n/*! \\file defs.h\n *  \\brief Lapack utility definitions for interface routines\n */\n\n#pragma once\n\n#include <lapacke.h>\n\nnamespace cusp\n{\nnamespace lapack\n{\n\nstruct lapack_format {};\n\nstruct upper   : public lapack_format {};\nstruct lower   : public lapack_format {};\nstruct unit    : public lapack_format {};\nstruct nonunit : public lapack_format {};\nstruct evals   : public lapack_format {};\nstruct evecs   : public lapack_format {};\nstruct gen_op1 : public lapack_format {};\nstruct gen_op2 : public lapack_format {};\nstruct gen_op3 : public lapack_format {};\n\ntemplate< typename LayoutFormat >\nstruct Orientation {static const lapack_int type;};\ntemplate<>\nconst lapack_int Orientation<cusp::row_major>::type    = LAPACK_ROW_MAJOR;\ntemplate<>\nconst lapack_int Orientation<cusp::column_major>::type = LAPACK_COL_MAJOR;\n\ntemplate< typename TriangularFormat >\nstruct UpperOrLower {static const char type;};\ntemplate<>\nconst char UpperOrLower<upper>::type = 'U';\ntemplate<>\nconst char UpperOrLower<lower>::type = 'L';\n\ntemplate< typename DiagonalFormat >\nstruct UnitOrNonunit {static const char type;};\ntemplate<>\nconst char UnitOrNonunit<unit>::type    = 'U';\ntemplate<>\nconst char UnitOrNonunit<nonunit>::type = 'N';\n\ntemplate< typename JobType >\nstruct EvalsOrEvecs {static const char type;};\ntemplate<>\nconst char EvalsOrEvecs<evals>::type = 'N';\ntemplate<>\nconst char EvalsOrEvecs<evecs>::type = 'V';\n\ntemplate< typename OpType >\nstruct GenEigOp {static const char type;};\ntemplate<>\nconst char GenEigOp<gen_op1>::type = 1;\ntemplate<>\nconst char GenEigOp<gen_op2>::type = 2;\ntemplate<>\nconst char GenEigOp<gen_op3>::type = 3;\n\n} // end namespace lapack\n} // end namespace cusp\n\n", "meta": {"hexsha": "e9d5ecaecd35b82cf7fc18a7097c04c797fbf4bf", "size": 2298, "ext": "h", "lang": "C", "max_stars_repo_path": "cusp/lapack/detail/defs.h", "max_stars_repo_name": "Raman-sh/cusplibrary", "max_stars_repo_head_hexsha": "99dcde05991ef59cbc4546aeced6eb3bd49c90c9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 270.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:40:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T00:58:21.000Z", "max_issues_repo_path": "cusp/lapack/detail/defs.h", "max_issues_repo_name": "njh19/cusplibrary", "max_issues_repo_head_hexsha": "4f72f152804dee592fec86719049af2b5469295a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 41.0, "max_issues_repo_issues_event_min_datetime": "2015-01-08T18:07:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-27T02:37:38.000Z", "max_forks_repo_path": "cusp/lapack/detail/defs.h", "max_forks_repo_name": "njh19/cusplibrary", "max_forks_repo_head_hexsha": "4f72f152804dee592fec86719049af2b5469295a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 106.0, "max_forks_repo_forks_event_min_datetime": "2015-02-27T19:30:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T13:55:53.000Z", "avg_line_length": 28.0243902439, "max_line_length": 76, "alphanum_fraction": 0.7389033943, "num_tokens": 567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.07159120637748637, "lm_q1q2_score": 0.03356128649863057}}
{"text": "/* Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n *\n * Copyright 2021 INRIA.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n*/\n\n#ifndef SiconosLAPACKE_H\n#define SiconosLAPACKE_H\n\n// IWYU pragma: private, include \"SiconosLapack.h\"\n//#include \"SiconosBlas.h\"\n#include <stdlib.h>\n#include <assert.h>\n#include <stdio.h>\n\n// -------- Headers and routines naming conventions for the different Lapack implementations --------\n\n// --- Intel MKL Header ---\n#if defined(HAS_MKL_LAPACKE)\n#include <mkl_lapacke.h>\n#else\n// Standard lapacke header\n#include <lapacke.h>\n#endif\n\n// Name of the routines\n#define LAPACK_NAME(N) LAPACKE_##N\n\n#define LA_TRANS 'T'\n#define LA_NOTRANS 'N'\n#define LA_UP 'U'\n#define LA_LO 'L'\n#define LA_NONUNIT 'N'\n#define LA_UNIT 'U'\n\n#define INTEGER(X) X\n#define INTEGERP(X) X\n#define CHAR(X) X\n\n#ifndef lapack_int\n#define lapack_int int\n#endif\n\n// --- DGESVD ---\n#if defined(HAS_LAPACK_dgesvd)\n#define WRAP_DGESVD(F,A1,A2,A3,A4,A5,A6,A7,A8,A9,A10,A11,A12,INFO)      \\\n  INFO = F(CblasColMajor,A1,A2,A3,A4,A5,A6,A7,A8,A9,A10,A11,A12)\n#else\n#define WRAP_DGESVD(F,A1,A2,A3,A4,A5,A6,A7,A8,A9,A10,A11,A12,INFO)      \\\n  fprintf(stderr, \"Your lapack version misses dgesvd function.\\n\");\n#endif\n\n// --- DGETRS ---\n#define WRAP_DGETRS(F,A1,A2,A3,A4,A5,A6,A7,A8,INFO)   \\\n  INFO = F(CblasColMajor,A1,A2,A3,A4,A5,A6,A7,A8)\n\n// --- DPOTRS ---\n#define WRAP_DPOTRS(F,A1,A2,A3,A4,A5,A6,A7,INFO) \\\n  INFO = F(CblasColMajor,A1,A2,A3,A4,A5,A6,A7)\n\n// --- DSYTRS ---\n#define WRAP_DSYTRS(F,A1,A2,A3,A4,A5,A6,A7,A8,INFO) \\\n  INFO = F(CblasColMajor,A1,A2,A3,A4,A5,A6,A7,A8)\n\n\n// --- DGESV ---\n#define WRAP_DGESV(F,A1,A2,A3,A4,A5,A6,A7,INFO)   \\\n  INFO = F(CblasColMajor,A1,A2,A3,A4,A5,A6,A7)\n\n// --- DPOSV ---\n#define WRAP_DPOSV(F,A1,A2,A3,A4,A5,A6,A7,INFO) \\\n  INFO = F(CblasColMajor,A1,A2,A3,A4,A5,A6,A7)\n\n// --- DGELS ---\n#if defined(HAS_LAPACK_dgels)\n#define WRAP_DGELS(F,A1,A2,A3,A4,A5,A6,A7,A8,INFO)    \\\n  INFO = F(CblasColMajor,A1,A2,A3,A4,A5,A6,A7,A8)\n#else\n#define WRAP_DGELS(F,A1,A2,A3,A4,A5,A6,A7,A8,INFO)                      \\\n  fprintf(stderr, \"Your lapack version misses dgels function.\\n\");\n#endif\n\n// --- DGETRI ---\n#define WRAP_DGETRI(F,A1,A2,A3,A4,INFO)         \\\n  INFO = F(CblasColMajor,A1,A2,A3,A4)\n\n\n// --- DGETRF ---\n#define WRAP_DGETRF(F,A1,A2,A3,A4,A5,INFO)  \\\n  INFO = F(CblasColMajor,A1,A2,A3,A4,A5)\n\n// --- DPOTRF ---\n#define WRAP_DPOTRF(F,A1,A2,A3,A4,INFO)  \\\n  INFO = F(CblasColMajor,A1,A2,A3,A4)\n\n// --- DSYTRF ---\n#define WRAP_DSYTRF(F,A1,A2,A3,A4,A5,INFO)      \\\n  INFO = F(CblasColMajor,A1,A2,A3,A4,A5)\n\n// --- DTRTRS ---\n#if defined(HAS_LAPACK_dtrtrs)\n#define WRAP_DTRTRS(F,A1,A2,A3,A4,A5,A6,A7,A8,A9,INFO)  \\\n  INFO = F(CblasColMajor,A1,A2,A3,A4,A5,A6,A7,A8,A9)\n#else\n#define WRAP_DTRTRS(F,A1,A2,A3,A4,A5,A6,A7,A8,A9,INFO)                \\\n  fprintf(stderr, \"Your lapack version misses dtrtrs function.\\n\");\n#endif\n\n#endif // SICONOSLAPACKE_H\n", "meta": {"hexsha": "c9ba4945071b904f4c81d2718fa898331637da37", "size": 3439, "ext": "h", "lang": "C", "max_stars_repo_path": "externals/blas_lapack/SiconosLapacke.h", "max_stars_repo_name": "BuildJet/siconos", "max_stars_repo_head_hexsha": "5e9c95806f0a01d62ab564ffb1d9d50c2dc32ef0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2015-06-16T15:55:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T06:01:59.000Z", "max_issues_repo_path": "externals/blas_lapack/SiconosLapacke.h", "max_issues_repo_name": "BuildJet/siconos", "max_issues_repo_head_hexsha": "5e9c95806f0a01d62ab564ffb1d9d50c2dc32ef0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 381.0, "max_issues_repo_issues_event_min_datetime": "2015-09-22T15:31:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T09:05:23.000Z", "max_forks_repo_path": "externals/blas_lapack/SiconosLapacke.h", "max_forks_repo_name": "BuildJet/siconos", "max_forks_repo_head_hexsha": "5e9c95806f0a01d62ab564ffb1d9d50c2dc32ef0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2015-08-06T22:57:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T20:30:20.000Z", "avg_line_length": 28.1885245902, "max_line_length": 101, "alphanum_fraction": 0.679558011, "num_tokens": 1223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326183324442865, "lm_q2_score": 0.073696275300812, "lm_q1q2_score": 0.033403708846132155}}
{"text": "/// @file\n///\n/// @brief test of gsl pointer wrappers\n///\n/// @copyright (c) 2007 CSIRO\n/// Australia Telescope National Facility (ATNF)\n/// Commonwealth Scientific and Industrial Research Organisation (CSIRO)\n/// PO Box 76, Epping NSW 1710, Australia\n/// atnf-enquiries@csiro.au\n///\n/// This file is part of the ASKAP software distribution.\n///\n/// The ASKAP software distribution is free software: you can redistribute it\n/// and/or modify it under the terms of the GNU General Public License as\n/// published by the Free Software Foundation; either version 2 of the License,\n/// or (at your option) any later version.\n///\n/// This program is distributed in the hope that it will be useful,\n/// but WITHOUT ANY WARRANTY; without even the implied warranty of\n/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n/// GNU General Public License for more details.\n///\n/// You should have received a copy of the GNU General Public License\n/// along with this program; if not, write to the Free Software\n/// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA\n///\n/// @author Max Voronkov <maxim.voronkov@csiro.au>\n\n// unit test include\n#include <cppunit/extensions/HelperMacros.h>\n\n// own includes\n#include \"utils/SharedGSLTypes.h\"\n\n// gsl includes\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_vector.h>\n\n\nnamespace askap {\n\nnamespace utility {\n\n/// @brief helper specialisation to allow testing of the destructor call\n/// @details It is not used anywhere outside this test suit \ntemplate<> struct CustomGSLDeleter<bool> {\n    /// @brief this method just sets the passed object to true\n    /// @param[in] obj pointer to a boolean variable\n    void operator()(bool *obj) const { *obj = true; }\n};\n\n\nclass SharedGSLTypesTest : public CppUnit::TestFixture \n{\n   CPPUNIT_TEST_SUITE(SharedGSLTypesTest);\n   CPPUNIT_TEST(testVector);\n   CPPUNIT_TEST(testMatrix);\n   CPPUNIT_TEST_EXCEPTION(testNullPointer,AskapError);     \n   CPPUNIT_TEST(testDestruction); \n   CPPUNIT_TEST_SUITE_END();\npublic:\n   void testVector() {\n      const size_t nElements = 10;\n      SharedGSLVector vec = createGSLVector(nElements);\n      for (size_t el = 0; el < nElements; ++el) {\n           gsl_vector_set(vec.get(), el, double(el));\n      }\n      // check the content (can't really check that the destructor is\n      // called)\n      for (size_t el = 0; el < nElements; ++el) {\n          CPPUNIT_ASSERT_DOUBLES_EQUAL(double(el), gsl_vector_get(vec.get(), el), 1e-6);\n      }\n      // destructor should be called on leaving this method      \n   }\n\n   void testMatrix() {\n      const size_t nRow = 10;\n      const size_t nCol = 12;\n      SharedGSLMatrix matr = createGSLMatrix(nRow, nCol);\n      for (size_t row = 0; row < nRow; ++row) {\n           for (size_t col = 0; col < nCol; ++col) {\n                gsl_matrix_set(matr.get(), row, col, double(row*col));\n           }\n      }\n      \n      // check the content (can't really check that the destructor is\n      // called)\n      for (size_t row = 0; row < nRow; ++row) {\n           for (size_t col = 0; col < nCol; ++col) {\n                CPPUNIT_ASSERT_DOUBLES_EQUAL(double(row*col), gsl_matrix_get(matr.get(), row,col), 1e-6);\n           }\n      }\n      // destructor should be called on leaving this method      \n   }\n   \n   void testNullPointer() {\n      gsl_vector *nullVec = NULL;\n      // the following should throw an exception\n      createGSLObject(nullVec);\n   }\n   \n   void testDestruction() {\n      bool destructorCalledBuf = false;\n      {\n        const boost::shared_ptr<bool> destructorCalledPtr = createGSLObject(&destructorCalledBuf);\n        CPPUNIT_ASSERT(destructorCalledPtr);\n        CPPUNIT_ASSERT_EQUAL(false, *destructorCalledPtr);\n        CPPUNIT_ASSERT_EQUAL(false, destructorCalledBuf);        \n      }\n      CPPUNIT_ASSERT_EQUAL(true, destructorCalledBuf);      \n   }\n};\n\n} // namespace utility\n\n} // namespace askap\n\n", "meta": {"hexsha": "b5fc6ce95e9dfc8aa10eb7b570c8e1bdbab45412", "size": 3905, "ext": "h", "lang": "C", "max_stars_repo_path": "Code/Base/scimath/current/tests/utils/SharedGSLTypesTest.h", "max_stars_repo_name": "rtobar/askapsoft", "max_stars_repo_head_hexsha": "6bae06071d7d24f41abe3f2b7f9ee06cb0a9445e", "max_stars_repo_licenses": ["BSL-1.0", "Apache-2.0", "OpenSSL"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-18T08:37:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-18T08:37:43.000Z", "max_issues_repo_path": "Code/Base/scimath/current/tests/utils/SharedGSLTypesTest.h", "max_issues_repo_name": "ATNF/askapsoft", "max_issues_repo_head_hexsha": "d839c052d5c62ad8a511e58cd4b6548491a6006f", "max_issues_repo_licenses": ["BSL-1.0", "Apache-2.0", "OpenSSL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/Base/scimath/current/tests/utils/SharedGSLTypesTest.h", "max_forks_repo_name": "ATNF/askapsoft", "max_forks_repo_head_hexsha": "d839c052d5c62ad8a511e58cd4b6548491a6006f", "max_forks_repo_licenses": ["BSL-1.0", "Apache-2.0", "OpenSSL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.093220339, "max_line_length": 105, "alphanum_fraction": 0.666837388, "num_tokens": 960, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.399811640739795, "lm_q2_score": 0.08269734606617778, "lm_q1q2_score": 0.03306336161554517}}
{"text": "/**\n * ex_gnuplot.h\n *\n * utility functions for plotting with gnuplot (v 4.6)\n *\n *  - minimizes boilerplate needed to use\n *  - popen -> process piping available, less temp files\n *  - idea based on myexamples/gnuplot (syntax) and gnuplot_i by N. Devillard (pipes), except a bit simpler\n *\n * Aaro Salosensaari 2016\n *\n * Original gnuplot_i was written by N. Devillard 1998 (version 2.10 2003) and is in public domain.\n */\n\n#ifndef EX_GNUPLOT\n#define EX_GNUPLOT\n\n#include <stdarg.h>\n#include <stdio.h>\n#include <gsl/gsl_vector.h>\n#include \"ex_util.h\"\n\n#define GP_MAX_TMP_FILES 32\n\ntypedef struct {\n    /* Pipe to gnuplot process */\n    FILE *gnucmd ;\n\n    /* Number of currently active plots */\n    int nplots ;\n\n    /* Pointer to table of names of temporary files */\n    char *tmp_filename_tbl[GP_MAX_TMP_FILES] ;\n\n    /* Number of temporary files */\n    int ntmp ;\n} gnuplot_ctrl ;\n\n\n/**\n * Public interface function declarations\n */\n\ngnuplot_ctrl *gnuplot_init(void);\n\nvoid gnuplot_close(gnuplot_ctrl *handle);\n\n/*\n * gnuplot_cmd\n *\n * This sends a string to an active gnuplot session, to be executed.\n * There is strictly no way to know if the command has been\n * successfully executed or not.\n * The command syntax is the same as printf.\n */\nvoid gnuplot_cmd(gnuplot_ctrl *handle, char const *cmd, ...);\n\n/*\n * ex_plot_xf can plot a variable number n of x, f(x) plots.\n *\n * n: number of plots\n * xlow:\n * xhigh:\n * xstep: (self-evident)\n * f1: function to plot\n * title1: title\n * style1: gnuplot style spef\n * (repeat fi, titlei, stylei until i=n)\n */\nvoid ex_plot_xf(gnuplot_ctrl *handle, const int n, double xlow, double xhigh, double xstep, db_fx f1, const char *title1, const char *style1, ...);\n\n\n/*\n * ex_plot_xys can plot a variable number n of x, y plots.\n *\n * n: number of plots\n * xdata: x points\n * ydata: y points\n * title1: title\n * style1: gnuplot style spef\n * (repeat xdatai, ydatai, titlei, stylei until i=n)\n */\nvoid ex_plot_xys(gnuplot_ctrl *handle, const int n, gsl_vector *xdata1, gsl_vector *ydata1, const char *title1, const char *style1, ...);\n\n\n\n\nvoid gnuplot_xy(gnuplot_ctrl *handle, gsl_vector *xdata, gsl_vector *ydata, const char *title1, const char *style1);\n\n\n#endif /* ifndef EX_GNUPLOT */\n\n", "meta": {"hexsha": "53374b58aa4e13606c7ec735ff962844b18d9143", "size": 2232, "ext": "h", "lang": "C", "max_stars_repo_path": "ex_gnuplot.h", "max_stars_repo_name": "aa-m-sa/ex_gnuplot_util", "max_stars_repo_head_hexsha": "17319213c85f65850c7b017bb4f3030d978ba936", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-15T03:41:21.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-15T03:41:21.000Z", "max_issues_repo_path": "ex_gnuplot.h", "max_issues_repo_name": "aa-m-sa/ex_gnuplot_util", "max_issues_repo_head_hexsha": "17319213c85f65850c7b017bb4f3030d978ba936", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ex_gnuplot.h", "max_forks_repo_name": "aa-m-sa/ex_gnuplot_util", "max_forks_repo_head_hexsha": "17319213c85f65850c7b017bb4f3030d978ba936", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0, "max_line_length": 147, "alphanum_fraction": 0.6975806452, "num_tokens": 663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.0850990380460446, "lm_q1q2_score": 0.032755653227822874}}
{"text": "/*! Implementation of the class `Solver`.\n * \\file solver.h\n */\n\n#if !defined(SOLVER_H)\n#define SOLVER_H\n\n#include <petsc.h>\n\n\n/**\n * \\class Solver\n * \\brief Super class for an iterative solver.\n */\nclass Solver\n{\npublic:\n  virtual ~Solver(){ }\n  virtual PetscErrorCode create(const Mat &A) = 0;\n  virtual PetscErrorCode solve(Vec &x, Vec &b) = 0;\n  virtual PetscErrorCode getIters(PetscInt &iters) = 0;\n\n}; // Solver\n\n#endif\n", "meta": {"hexsha": "b4923e3087b94ff8be745453b4deda864dc9ab1f", "size": 426, "ext": "h", "lang": "C", "max_stars_repo_path": "src/utilities/solvers/solver.h", "max_stars_repo_name": "hietwll/PetIBM", "max_stars_repo_head_hexsha": "53cb87f2bf28a182119b4db7e86c4d62246e2952", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-07-12T13:37:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-12T13:37:47.000Z", "max_issues_repo_path": "src/utilities/solvers/solver.h", "max_issues_repo_name": "hietwll/PetIBM", "max_issues_repo_head_hexsha": "53cb87f2bf28a182119b4db7e86c4d62246e2952", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utilities/solvers/solver.h", "max_forks_repo_name": "hietwll/PetIBM", "max_forks_repo_head_hexsha": "53cb87f2bf28a182119b4db7e86c4d62246e2952", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-01-10T08:53:34.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-25T13:27:55.000Z", "avg_line_length": 16.3846153846, "max_line_length": 55, "alphanum_fraction": 0.6737089202, "num_tokens": 119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.45713671682749474, "lm_q2_score": 0.07159119548287624, "lm_q1q2_score": 0.03272696405679741}}
{"text": "/* $Id$ */\n/*--------------------------------------------------------------------*/\n/*;  Copyright (C) 2008                                               */\n/*;  Associated Universities, Inc. Washington DC, USA.                */\n/*;                                                                   */\n/*;  This program is free software; you can redistribute it and/or    */\n/*;  modify it under the terms of the GNU General Public License as   */\n/*;  published by the Free Software Foundation; either version 2 of   */\n/*;  the License, or (at your option) any later version.              */\n/*;                                                                   */\n/*;  This program is distributed in the hope that it will be useful,  */\n/*;  but WITHOUT ANY WARRANTY; without even the implied warranty of   */\n/*;  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the    */\n/*;  GNU General Public License for more details.                     */\n/*;                                                                   */\n/*;  You should have received a copy of the GNU General Public        */\n/*;  License along with this program; if not, write to the Free       */\n/*;  Software Foundation, Inc., 675 Massachusetts Ave, Cambridge,     */\n/*;  MA 02139, USA.                                                   */\n/*;                                                                   */\n/*; Correspondence about this software should be addressed as follows:*/\n/*;         Internet email: bcotton@nrao.edu.                         */\n/*;         Postal address: William Cotton                            */\n/*;                         National Radio Astronomy Observatory      */\n/*;                         520 Edgemont Road                         */\n/*;                         Charlottesville, VA 22903-2475 USA        */\n/*--------------------------------------------------------------------*/\n\n#include \"ObitUtil.h\"\n#include <gsl/gsl_multifit.h>\n\n/*----------------Obit: Merx mollis mortibus nuper ------------------*/\n/**\n * \\file ObitUtil.c\n * ObitUtil utility function definitions.\n *\n */\n\n\n/*----------------------Private functions---------------------------*/\n/** Private: qsort ofloat comparison */\nstatic int compare_gfloat  (const void* arg1,  const void* arg2);\n\n\n/*----------------------Public functions---------------------------*/\n/**\n * Get mean values of an array.\n * \\param array array of values may be magic value blanked\n * \\param n     dimension of array\n * \\return      Mean value, possibly blanked\n */\nofloat meanValue (ofloat *array, olong incs, olong n)\n{\n  olong i, count;\n  ofloat sum, fblank =ObitMagicF() ;\n\n  if (n<=0) return fblank;\n  sum = 0.0;\n  count = 0;\n    for (i=0; i<n; i++) {\n      if (array[i*incs]!=fblank) { \n\tsum += array[i*incs];\n\tcount++;\n      }\n    }\n    if (count>0) sum /= count;\n    else sum = fblank;\n\n  return sum;\n} /* end meanValue */\n\n/**\n * Get median value of an array.\n * Does sort then returns value array[ngood/2]\n * \\param array   array of values, on return will be in ascending order\n * \\param n       dimension of array\n * \\param inc     stride in array\n * \\return        Median value, possibly blanked\n */\nofloat medianValue (ofloat *array, olong incs, olong n)\n{\n  olong i, ngood;\n  ofloat out, fblank = ObitMagicF();\n  gboolean blanked;\n\n  if (n<=0) return fblank;\n\n  /* Count good (non blank) points */\n  ngood = 0;\n  for (i=0; i<n; i++) if (array[i*incs]!=fblank) ngood++;\n  if (ngood<1) return fblank;  /* Any good data? */\n  blanked = ngood<n;   /* Anything blanked? */\n\n  /* set blanked values to 2.0e20 for sort */\n  for (i=0; i<n; i++) if (array[i*incs]==fblank) array[i*incs] = 2.0e20;\n\n  /* Sort to ascending order */\n  qsort ((void*)array, n, MAX(1,incs)*sizeof(ofloat), compare_gfloat);\n\n  /* Set median */\n  out = array[(ngood/2)*incs];\n\n  /* reset blanked values */\n  if (blanked) {\n    for (i=0; i<n; i++) if (array[i*incs]>1.0e20) array[i*incs] = fblank;\n  }\n\n  return out;\n} /* end medianValue */\n\n/**\n * Return average of navg values around median (with magic value blanking)\n * Does sort then returns average of center of array\n * If there are fewer than navg valid data then the median is returned.\n * \\param array array of values, on return will be in ascending order\n * \\param incs  increment in data array, >1 => weights\n * \\param navg  width of averaging about median\n * \\param doWt  If True value after data is a weight\n * \\param n     dimension of array\n * \\return      Median/average, possibly blanked\n */\nofloat medianAvg (ofloat *array, olong incs, olong navg, gboolean doWt, olong n)\n{\n  olong i, cnt, wid, ngood, ind, hi, lo;\n  ofloat temp, wt, out=0.0, fblank = ObitMagicF();\n  ofloat center;\n  gboolean blanked;\n\n  if (n<=0) return fblank;\n\n  /* Count good (non blank) points */\n  ngood = 0;\n  for (i=0; i<n; i++) if (array[i*incs]!=fblank) ngood++;\n  if (ngood<1) return fblank;  /* Any good data? */\n  blanked = ngood<n;   /* Anything blanked? */\n\n  /* set blanked values to 2.0e20 for sort */\n  for (i=0; i<n; i++) if (array[i*incs]==fblank) array[i*incs] = 2.0e20;\n\n  /* Sort to ascending order */\n  qsort ((void*)array, n, MAX(1,incs)*sizeof(ofloat), compare_gfloat);\n\n  /* How many good values? */\n  cnt = 0;\n  for (i=0; i<n; i++) if (array[i*incs]<1.0e20) cnt++;\n  wid = MIN (MAX (1, navg/2), ngood/2);  /* width of averaging */\n  ngood = cnt;\n\n  ind = (ngood-1)/2;  /* center good value */\n  out = array[ind*incs];\n\n  /* average central values */\n  if (ngood>navg) {\n    center = (ngood-1)/2.0;\n    lo = MAX (1, (olong)(center - wid + 0.6));\n    hi = MIN (ngood, (olong)(center + wid));\n    /* Weighted? */\n    if (doWt) {\n      temp = 0.0; wt = 0.0;\n      for (i=lo; i<=hi; i++) {\n\tif (array[i*incs]<1.0e20) {\n\t  wt += array[i*incs+1];\n\t  temp += array[i*incs]*array[i*incs+1];\n\t}\n      }\n      if (wt>0.0) out = temp/wt;\n    } else { /* unweighted */\n      temp = 0.0; cnt = 0;\n      for (i=lo; i<=hi; i++) {\n\tif (array[i]<1.0e20) {\n\t  cnt++;\n\t  temp += array[i];\n\t}\n\tif (cnt>0) out = temp/cnt;\n      }\n    } /* end if weighting */\n  }\n\n  /* reset blanked values */\n  if (blanked) {\n    for (i=0; i<n; i++) if (array[i*incs]>1.0e20) array[i*incs] = fblank;\n  }\n\n  return out;\n} /* end medianAvg */\n\n/**\n * Return the running median of an array\n * \\param n       Number of points\n * \\param wind    Width of median window in cells\n * \\param array   Array of values, fblank blanking supported\n * \\param alpha   0 -> 1 = pure boxcar -> pure MWF (Alpha of the \n *                data samples in a window are discarded and \n *                the rest averaged). \n * \\param rms     RMS of array, median average sigma from each wind of data\n * \\param out     array of size of array to be with median values\n * \\param work    work array of size of array\n */\nvoid RunningMedian (olong n, olong wind, ofloat *array, ofloat alpha, \n\t\t    ofloat *RMS, ofloat *out, ofloat *work)\n{\n  ofloat *lwork=NULL;\n  ofloat level, sigma, sigmaSum, sigmaCnt;\n  ofloat fblank = ObitMagicF();\n  olong i, j, k, op, ind, half, RMScnt=0;\n\n  /* Create array */\n  lwork = g_malloc0(wind*sizeof(ofloat));\n\n  half = wind/2;\n  ind  = 0;\n  op   = 0;\n  k    = 0;\n  sigmaSum = 0.0;\n  sigmaCnt = 1;\n\n  /* First half wind filled with median of first wind points */\n  for (j=ind; j<ind+wind; j++) lwork[k++] = array[j];\n  ind++;\n  level = MedianLevel (wind, lwork, alpha);\n  sigma = MedianSigma (wind, lwork, level);\n  if (sigma!=fblank) {\n    sigmaSum = sigma;\n    sigmaSum += sigma;\n    work[RMScnt++] = sigma;\n  }\n  for (k=0; k<half; k++) out[op++] = level;\n\n  /* Loop over middle of array */\n  for (i=half; i<n-half; i++) {\n    k = 0;\n    for (j=ind; j<ind+wind; j++) lwork[k++] = array[j];\n    ind++;\n    level = MedianLevel (wind, lwork, alpha);\n    sigma = MedianSigma (wind, lwork, level);\n    if (sigma!=fblank) {\n      sigmaSum += sigma;\n      sigmaCnt++;\n      work[RMScnt++] = sigma;\n    }\n    out[op++] = level;\n  } /* end loop over array */\n\n  /* Fill in bit at end */\n  while (op<n) {\n    out[op++] = level;\n  }\n\n  /* median Average sigmas */\n  *RMS = MedianLevel (RMScnt, work, alpha);\n\n  /* Cleanup */\n  if (lwork) g_free(lwork);\n\n} /* end RunningMedian */\n\n/**\n * Determine alpha median value of a ofloat array\n * \\param n       Number of points\n * \\param value   Array of values\n * \\param alpha   0 -> 1 = pure boxcar -> pure MWF (ALPHA of the \n *                data samples are discarded and the rest averaged). \n * \\return alpha median value\n */\nofloat MedianLevel (olong n, ofloat *value, ofloat alpha)\n{\n  ofloat out=0.0;\n  ofloat fblank = ObitMagicF();\n  ofloat beta, sum;\n  olong i, i1, i2, count;\n\n  if (n<=0) return out;\n\n  /* Sort to ascending order */\n  qsort ((void*)value, n, sizeof(ofloat), compare_gfloat);\n\n  out = value[n/2];\n\n  beta = MAX (0.05, MIN (0.95, alpha)) / 2.0; /*  Average around median factor */\n\n  /* Average around the center */\n  i1 = MAX (0, (n/2)-(olong)(beta*n+0.5));\n  i2 = MIN (n, (n/2)+(olong)(beta*n+0.5));\n\n  if (i2>i1) {\n    sum = 0.0;\n    count = 0;\n    for (i=i1; i<i2; i++) {\n      if (value[i]!=fblank) {\n\tsum += value[i];\n\tcount++;\n      }\n    }\n    if (count>0) out = sum / count;\n  }\n   \n  return out;\n} /* end MedianLevel */\n\n/**\n * Determine robust RMS value of a ofloat array about mean\n * Use center 90% of points, excluding at least one point from each end\n * \\param n       Number of points, needs at least 4\n * \\param value   Array of values assumed sorted\n * \\param mean    Mean value of value\n * \\return RMS value, fblank if cannot determine\n */\nofloat MedianSigma (olong n, ofloat *value, ofloat mean)\n{\n  ofloat fblank = ObitMagicF();\n  ofloat out;\n  ofloat sum;\n  olong i, i1, i2, count;\n\n  out = fblank;\n  if (n<=4) return out;\n  if (mean==fblank) return out;\n\n  /* Get RMS around the center 90% */\n  i1 = MAX (1,   (n/2)-(olong)(0.45*n+0.5));\n  i2 = MIN (n-1, (n/2)+(olong)(0.45*n+0.5));\n\n  if (i2>i1) {\n    sum = 0.0;\n    count = 0;\n    for (i=i1; i<i2; i++) {\n      if (value[i]!=fblank) {\n\tsum += (value[i]-mean)*(value[i]-mean);\n\tcount++;\n      }\n    }\n    if (count>1) out = sqrt(sum / (count-1));\n  }\n   \n  return out;\n} /* end MedianSigma */\n\n/**\n * Fit polynomial y = f(poly, x) with magic value blanking\n * Use gsl package.\n * \\param poly   [out] polynomial coef in order of increasing power of x\n * \\param order  order of the polynomial\n * \\param x      values at which y is sampled\n * \\param y      values to be fitted\n * \\param wt     weights for values\n * \\param n      number of (x,y) value pairs\n */\nvoid  FitPoly (ofloat *poly, olong order, ofloat *x, ofloat *y, ofloat *wt, \n\t       olong n)\n{\n  olong i, j, k, good, p=order+1;\n  ofloat fgood=0.0;\n  double xi, chisq;\n  gsl_matrix *X, *cov;\n  gsl_vector *yy, *w, *c;\n  gsl_multifit_linear_workspace *work;\n  ofloat fblank = ObitMagicF();\n\n  /* Only use good data */\n  good = 0;\n  for (i=0; i<n; i++) if (y[i]!=fblank) {good++; fgood = y[i];}\n\n  /* If only one good datum - use it */\n  if (good==1) {\n    poly[0] = fgood;\n    poly[1] = 0.0;\n  }\n\n  if (good<(order+1)) {  /* Not enough good data */\n    poly[0] = fblank;\n    return;\n  }\n\n  /* If only one and order=0 use it */\n  if ((good==1) && (order==0)) {\n    poly[0] = y[0];\n    return;\n  }\n\n  /* allocate arrays */\n  X    = gsl_matrix_alloc(good, p);\n  yy   = gsl_vector_alloc(good);\n  w    = gsl_vector_alloc(good);\n  c    = gsl_vector_alloc(p);\n  cov  = gsl_matrix_alloc(p, p);\n  work = gsl_multifit_linear_alloc (good, p);\n\n  /* set data */\n  k = 0;\n  for (i=0; i<n; i++) {\n    if (y[i]!=fblank) {\n      gsl_vector_set(yy, k, (double)y[i]);\n      gsl_vector_set(w, k, (double)wt[i]);\n      xi = 1.0;\n      for (j=0; j<p; j++) {\n\tgsl_matrix_set(X, k, j, xi);\n\txi *= x[i];\n      }\n      k++;  /* good ones */\n    }\n  }\n\n  /* Fit */\n  gsl_multifit_wlinear (X, w, yy, c, cov, &chisq, work);\n\n  /* get results */\n  for (j=0; j<p; j++) poly[j] = (ofloat)gsl_vector_get(c, j);\n\n  /* Deallocate arrays */\n  gsl_matrix_free(X);\n  gsl_vector_free(yy);\n  gsl_vector_free(w);\n  gsl_vector_free(c);\n  gsl_matrix_free(cov);\n  gsl_multifit_linear_free (work);\n} /* end FitPoly */\n\n/**\n * Evaluate polynomial y = f(poly, x)\n * \\param order  order of the polynomial\n * \\param poly   polynomial coef in order of increasing power of x\n * \\param x      value at which polynomial is to be evaluated\n * \\return evaluated polynomial\n */\nofloat  EvalPoly (olong order, ofloat *poly, ofloat x)\n{\n  olong i;\n  ofloat sum = 0.0, aarg = 1.0;\n\n  for (i=0; i<=order; i++) {\n    sum  += poly[i]*aarg;\n    aarg *= x;\n  }\n  return sum;\n} /* end EvalPoly  */\n\n\n\n/*----------------------Private functions---------------------------*/\n/**\n * ofloat comparison of two arguments\n * \\param arg1 first value to compare\n * \\param arg2 second value to compare\n * \\return negative if arg1 is less than arg2, zero if equal\n *  and positive if arg1 is greater than arg2.\n */\nstatic int compare_gfloat  (const void* arg1,  const void* arg2)\n{\n  int out = 0;\n  ofloat larg1, larg2;\n\n  larg1 = *(ofloat*)arg1;\n  larg2 = *(ofloat*)arg2;\n  if (larg1<larg2) out = -1;\n  else if (larg1>larg2) out = 1;\n  return out;\n} /* end compare_gfloat */\n", "meta": {"hexsha": "acdd3182ad1a7a5d6e06944296e4766319b03a1b", "size": 13077, "ext": "c", "lang": "C", "max_stars_repo_path": "ObitSystem/Obit/src/ObitUtil.c", "max_stars_repo_name": "sarrvesh/Obit", "max_stars_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-08-26T06:53:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-20T01:08:59.000Z", "max_issues_repo_path": "ObitSystem/Obit/src/ObitUtil.c", "max_issues_repo_name": "sarrvesh/Obit", "max_issues_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ObitSystem/Obit/src/ObitUtil.c", "max_forks_repo_name": "sarrvesh/Obit", "max_forks_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-08-29T15:12:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:16:08.000Z", "avg_line_length": 28.5524017467, "max_line_length": 81, "alphanum_fraction": 0.5589967118, "num_tokens": 3994, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.06954174450582809, "lm_q1q2_score": 0.03260051798356929}}
{"text": "#ifndef AMICI_VECTOR_H\n#define AMICI_VECTOR_H\n\n#include <vector>\n#include <type_traits>\n\n#include <amici/exception.h>\n\n#include <nvector/nvector_serial.h>\n\n#include <gsl/gsl-lite.hpp>\n\nnamespace amici {\n\n/** Since const N_Vector is not what we want */\nusing const_N_Vector =\n    std::add_const<typename std::remove_pointer<N_Vector>::type *>::type;\n\n/** AmiVector class provides a generic interface to the NVector_Serial struct */\nclass AmiVector {\n  public:\n    /**\n     * @brief Default constructor\n     */\n    AmiVector() = default;\n\n    /** Creates an std::vector<realtype> and attaches the\n     * data pointer to a newly created N_Vector_Serial.\n     * Using N_VMake_Serial ensures that the N_Vector\n     * module does not try to deallocate the data vector\n     * when calling N_VDestroy_Serial\n     * @brief empty constructor\n     * @param length number of elements in vector\n     */\n    explicit AmiVector(const long int length)\n        : vec_(static_cast<decltype(vec_)::size_type>(length), 0.0),\n          nvec_(N_VMake_Serial(length, vec_.data())) {}\n\n    /** Moves data from std::vector and constructs an nvec that points to the\n     * data\n     * @brief constructor from std::vector,\n     * @param rvec vector from which the data will be moved\n     */\n    explicit AmiVector(std::vector<realtype> rvec)\n        : vec_(std::move(rvec)),\n          nvec_(N_VMake_Serial(static_cast<long int>(vec_.size()), vec_.data())) {}\n\n    /** Copy data from gsl::span and constructs a vector\n     * @brief constructor from gsl::span,\n     * @param rvec vector from which the data will be copied\n     */\n    explicit AmiVector(gsl::span<realtype> rvec)\n        : AmiVector(std::vector<realtype>(rvec.begin(), rvec.end())) {}\n\n    /**\n     * @brief copy constructor\n     * @param vold vector from which the data will be copied\n     */\n    AmiVector(const AmiVector &vold) : vec_(vold.vec_) {\n        nvec_ =\n            N_VMake_Serial(static_cast<long int>(vold.vec_.size()), vec_.data());\n    }\n\n    /**\n     * @brief move constructor\n     * @param other vector from which the data will be moved\n     */\n    AmiVector(AmiVector&& other) noexcept : nvec_(nullptr) {\n        vec_ = std::move(other.vec_);\n        synchroniseNVector();\n    }\n\n    /**\n     * @brief destructor\n     */\n    ~AmiVector();\n\n    /**\n     * @brief copy assignment operator\n     * @param other right hand side\n     * @return left hand side\n     */\n    AmiVector &operator=(AmiVector const &other);\n\n    /**\n     * @brief data accessor\n     * @return pointer to data array\n     */\n    realtype *data();\n\n    /**\n     * @brief const data accessor\n     * @return const pointer to data array\n     */\n    const realtype *data() const;\n\n    /**\n     * @brief N_Vector accessor\n     * @return N_Vector\n     */\n    N_Vector getNVector();\n\n    /**\n     * @brief N_Vector accessor\n     * @return N_Vector\n     */\n    const_N_Vector getNVector() const;\n\n    /**\n     * @brief Vector accessor\n     * @return Vector\n     */\n    std::vector<realtype> const &getVector() const;\n\n    /**\n     * @brief returns the length of the vector\n     * @return length\n     */\n    int getLength() const;\n\n    /**\n     * @brief resets the Vector by filling with zero values\n     */\n    void reset();\n\n    /**\n     * @brief changes the sign of data elements\n     */\n    void minus();\n\n    /**\n     * @brief sets all data elements to a specific value\n     * @param val value for data elements\n     */\n    void set(realtype val);\n\n    /**\n     * @brief accessor to data elements of the vector\n     * @param pos index of element\n     * @return element\n     */\n    realtype &operator[](int pos);\n    /**\n     * @brief accessor to data elements of the vector\n     * @param pos index of element\n     * @return element\n     */\n    realtype &at(int pos);\n\n    /**\n     * @brief accessor to data elements of the vector\n     * @param pos index of element\n     * @return element\n     */\n    const realtype &at(int pos) const;\n\n    /**\n     * @brief copies data from another AmiVector\n     * @param other data source\n     */\n    void copy(const AmiVector &other);\n\n  private:\n    /** main data storage */\n    std::vector<realtype> vec_;\n\n    /** N_Vector, will be synchronised such that it points to data in vec */\n    N_Vector nvec_ {nullptr};\n\n    /**\n     * @brief reconstructs nvec such that data pointer points to vec data array\n     */\n    void synchroniseNVector();\n};\n\n/**\n * @brief AmiVectorArray class.\n *\n * Provides a generic interface to arrays of NVector_Serial structs\n */\nclass AmiVectorArray {\n  public:\n    /**\n     * @brief Default constructor\n     */\n    AmiVectorArray() = default;\n\n    /**\n     * Creates an std::vector<realype> and attaches the\n     * data pointer to a newly created N_VectorArray\n     * using CloneVectorArrayEmpty ensures that the N_Vector\n     * module does not try to deallocate the data vector\n     * when calling N_VDestroyVectorArray_Serial\n     * @brief empty constructor\n     * @param length_inner length of vectors\n     * @param length_outer number of vectors\n     */\n    AmiVectorArray(long int length_inner, long int length_outer);\n\n    /**\n     * @brief copy constructor\n     * @param vaold object to copy from\n     */\n    AmiVectorArray(const AmiVectorArray &vaold);\n\n    ~AmiVectorArray() = default;\n\n    /**\n     * @brief copy assignment operator\n     * @param other right hand side\n     * @return left hand side\n     */\n    AmiVectorArray &operator=(AmiVectorArray const &other);\n\n    /**\n     * @brief accessor to data of AmiVector elements\n     * @param pos index of AmiVector\n     * @return pointer to data array\n     */\n    realtype *data(int pos);\n\n    /**\n     * @brief const accessor to data of AmiVector elements\n     * @param pos index of AmiVector\n     * @return const pointer to data array\n     */\n    const realtype *data(int pos) const;\n\n    /**\n     * @brief accessor to elements of AmiVector elements\n     * @param ipos inner index in AmiVector\n     * @param jpos outer index in AmiVectorArray\n     * @return element\n     */\n    realtype &at(int ipos, int jpos);\n\n    /**\n     * @brief const accessor to elements of AmiVector elements\n     * @param ipos inner index in AmiVector\n     * @param jpos outer index in AmiVectorArray\n     * @return element\n     */\n    const realtype &at(int ipos, int jpos) const;\n\n    /**\n     * @brief accessor to NVectorArray\n     * @return N_VectorArray\n     */\n    N_Vector *getNVectorArray();\n\n    /**\n     * @brief accessor to NVector element\n     * @param pos index of corresponding AmiVector\n     * @return N_Vector\n     */\n    N_Vector getNVector(int pos);\n\n    /**\n     * @brief const accessor to NVector element\n     * @param pos index of corresponding AmiVector\n     * @return N_Vector\n     */\n    const_N_Vector getNVector(int pos) const;\n\n    /**\n     * @brief accessor to AmiVector elements\n     * @param pos index of AmiVector\n     * @return AmiVector\n     */\n    AmiVector &operator[](int pos);\n\n    /**\n     * @brief const accessor to AmiVector elements\n     * @param pos index of AmiVector\n     * @return const AmiVector\n     */\n    const AmiVector &operator[](int pos) const;\n\n    /**\n     * @brief length of AmiVectorArray\n     * @return length\n     */\n    int getLength() const;\n\n    /**\n     * @brief resets every AmiVector in AmiVectorArray\n     */\n    void reset();\n\n    /**\n     * @brief flattens the AmiVectorArray to a vector in row-major format\n     * @param vec vector into which the AmiVectorArray will be flattened. Must\n     * have length equal to number of elements.\n     */\n    void flatten_to_vector(std::vector<realtype> &vec) const;\n\n    /**\n     * @brief copies data from another AmiVectorArray\n     * @param other data source\n     */\n    void copy(const AmiVectorArray &other);\n\n  private:\n    /** main data storage */\n    std::vector<AmiVector> vec_array_;\n\n    /**\n     * N_Vector array, will be synchronised such that it points to\n     * respective elements in the vec_array\n     */\n    std::vector<N_Vector> nvec_array_;\n};\n\n} // namespace amici\n\n\nnamespace gsl {\n/**\n * @brief Create span from N_Vector\n * @param nv\n * @return\n */\ninline span<realtype> make_span(N_Vector nv)\n{\n    return span<realtype>(N_VGetArrayPointer(nv), N_VGetLength_Serial(nv));\n}\n} // namespace gsl\n\n#endif /* AMICI_VECTOR_H */\n", "meta": {"hexsha": "b49a143d60733b22edcdf7f7471c941438d7e314", "size": 8278, "ext": "h", "lang": "C", "max_stars_repo_path": "include/amici/vector.h", "max_stars_repo_name": "lcontento/AMICI", "max_stars_repo_head_hexsha": "7a1dc5ed1299273b3670239f5d614eec835f1299", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/amici/vector.h", "max_issues_repo_name": "lcontento/AMICI", "max_issues_repo_head_hexsha": "7a1dc5ed1299273b3670239f5d614eec835f1299", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/amici/vector.h", "max_forks_repo_name": "lcontento/AMICI", "max_forks_repo_head_hexsha": "7a1dc5ed1299273b3670239f5d614eec835f1299", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0848484848, "max_line_length": 83, "alphanum_fraction": 0.6279294516, "num_tokens": 2096, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39606818053136394, "lm_q2_score": 0.08151975653257584, "lm_q1q2_score": 0.03228738164721708}}
{"text": "/******************************************************************************\n * Copyright (C) 2016-2019, Cris Cecka.  All rights reserved.\n * Copyright (C) 2016-2019, NVIDIA CORPORATION.  All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in the\n *       documentation and/or other materials provided with the distribution.\n *     * Neither the name of the NVIDIA CORPORATION nor the\n *       names of its contributors may be used to endorse or promote products\n *       derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n ******************************************************************************/\n\n#pragma once\n\n#include <blam/detail/config.h>\n\n#if !defined(__MKL_CBLAS_H__)\n#include <cblas.h>\nusing CBLAS_LAYOUT = CBLAS_ORDER;\n#endif\n\n\nnamespace blam\n{\n\ninline CBLAS_LAYOUT\ncblas_type(Layout order)\n{\n  switch (order) {\n    case Layout::ColMajor: return CblasColMajor;\n    case Layout::RowMajor: return CblasRowMajor;\n    default:\n      assert(false && \"Invalid Layout Parameter\");\n      return CblasColMajor;\n  }\n}\n\ninline CBLAS_TRANSPOSE\ncblas_type(Op trans)\n{\n  switch (trans) {\n    case Op::NoTrans:   return CblasNoTrans;\n    case Op::Trans:     return CblasTrans;\n    case Op::ConjTrans: return CblasConjTrans;\n    default:\n      assert(false && \"Invalid Op Parameter\");\n      return CblasNoTrans;\n  }\n}\n\ninline CBLAS_UPLO\ncblas_type(Uplo uplo)\n{\n  switch (uplo) {\n    case Uplo::Upper: return CblasUpper;\n    case Uplo::Lower: return CblasLower;\n    default:\n      assert(false && \"Invalid Uplo Parameter\");\n      return CblasUpper;\n  }\n}\n\ninline CBLAS_SIDE\ncblas_type(Side side)\n{\n  switch (side) {\n    case Side::Left:  return CblasLeft;\n    case Side::Right: return CblasRight;\n    default:\n      assert(false && \"Invalid Side Parameter\");\n      return CblasLeft;\n  }\n}\n\ninline CBLAS_DIAG\ncblas_type(Diag diag)\n{\n  switch (diag) {\n    case Diag::Unit:    return CblasUnit;\n    case Diag::NonUnit: return CblasNonUnit;\n    default:\n      assert(false && \"Invalid Diag Parameter\");\n      return CblasUnit;\n  }\n}\n\n} // end namespace blam\n", "meta": {"hexsha": "a341738addc2e116f6c900445375aa9f07ae434d", "size": 3255, "ext": "h", "lang": "C", "max_stars_repo_path": "blam/system/cblas/config.h", "max_stars_repo_name": "ccecka/BLAM", "max_stars_repo_head_hexsha": "4198e8a22aa7650cc97a1b6d96b30bdcac8ce232", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-02-09T20:48:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-19T04:51:47.000Z", "max_issues_repo_path": "blam/system/cblas/config.h", "max_issues_repo_name": "ccecka/BLAM", "max_issues_repo_head_hexsha": "4198e8a22aa7650cc97a1b6d96b30bdcac8ce232", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "blam/system/cblas/config.h", "max_forks_repo_name": "ccecka/BLAM", "max_forks_repo_head_hexsha": "4198e8a22aa7650cc97a1b6d96b30bdcac8ce232", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-08-04T04:38:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T07:50:20.000Z", "avg_line_length": 31.6019417476, "max_line_length": 82, "alphanum_fraction": 0.6844854071, "num_tokens": 743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782348444346736, "lm_q2_score": 0.07369626309405569, "lm_q1q2_score": 0.03226595469830197}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef vbitset_deeaeda9_1fc9_43e4_9026_c5eeb93c6ebb_h\r\n#define vbitset_deeaeda9_1fc9_43e4_9026_c5eeb93c6ebb_h\r\n\r\n#include <intrin.h>\r\n#include <gslib/config.h>\r\n#include <gslib/std.h>\r\n\r\n__gslib_begin__\r\n\r\ninline int bit_count(uint n)\r\n{\r\n    uint t = n - ((n >> 1) & 033333333333) - ((n >> 2) & 011111111111);\r\n    return ((t + (t >> 3)) & 030707070707) % 63;\r\n}\r\n\r\ninline uint bitelim_first_nonzero(uint n) { return n & (n - 1); }\r\ninline uint bitmask_first_nonzero(uint n) { return n ^ (n - 1); }\r\n\r\ninline int bitscan_forward(uint n)\r\n{\r\n    uint p;\r\n    return _BitScanForward((unsigned long*)&p, n) ? (int)p : -1;\r\n}\r\n\r\ninline int bitscan_reverse(uint n)\r\n{\r\n    uint p;\r\n    return _BitScanReverse((unsigned long*)&p, n) ? (int)p : -1;\r\n}\r\n\r\nclass vbitset\r\n{\r\npublic:\r\n    typedef vector<uint> container;\r\n    static const uint knot_size = sizeof(uint) * 8;\r\n\r\nprotected:\r\n    container           _container;\r\n    int                 _size;\r\n\r\npublic:\r\n    vbitset() { _size = 0; }\r\n    int knot_count() const { return (int)_container.size(); }\r\n    uint knot_at(int i) const\r\n    {\r\n        assert(i < knot_count());\r\n        return _container.at(i);\r\n    }\r\n    void set_knot(int p, uint k)\r\n    {\r\n        if(p >= knot_count()) {\r\n            assert(!\"unexpected.\");\r\n            return;\r\n        }\r\n        _container.at(p) = k;\r\n    }\r\n    uint& ref_knot_at(int i)\r\n    {\r\n        assert(i < knot_count());\r\n        return _container.at(i);\r\n    }\r\n    int capacity() const { return knot_size * knot_count(); }\r\n    int size() const { return _size; }\r\n    int length() const { return _size; }\r\n    void set(int pos) { reset(pos, true); }\r\n    void reset(int pos, bool b = false)\r\n    {\r\n        int cc = cycle_count(pos);\r\n        int cidx = cycle_index(pos);\r\n        ensure_container_capacity(pos, cc, cidx);\r\n        uint& n = _container.at(cc);\r\n        uint mask = (1 << cidx);\r\n        b ? (n |= mask) : (n &= ~mask);\r\n    }\r\n    void reset(bool b)\r\n    {\r\n        int cc = cycle_count(_size);\r\n        int cidx = cycle_index(_size);\r\n        int m = b ? -1 : 0;\r\n        memset(&_container.front(), m, cc * sizeof(uint));\r\n        uint mask = (1 << (cidx + 1)) - 1;\r\n        uint& n = _container.at(cc);\r\n        b ? (n |= mask) : (n &= ~mask);\r\n    }\r\n    bool test(int pos)\r\n    {\r\n        if(pos >= _size)\r\n            return false;\r\n        int cc = cycle_count(pos);\r\n        int cidx = cycle_index(pos);\r\n        uint n = knot_at(cc);\r\n        uint mask = (1 << cidx);\r\n        return (n & mask) != 0;\r\n    }\r\n    void resize(int s)\r\n    {\r\n        if(s == 0) {\r\n            _container.clear();\r\n            _size = 0;\r\n            return;\r\n        }\r\n        if(s == _size)\r\n            return;\r\n        else if(s < _size) {\r\n            ensure_container_capacity(s - 1);\r\n            return;\r\n        }\r\n        else {\r\n            int cc = cycle_count(s - 1);\r\n            _container.resize(cc + 1);\r\n            _size = s;\r\n        }\r\n    }\r\n    void rotate_left(int bias)\r\n    {\r\n        if(!bias)\r\n            return;\r\n        if(bias < 0)\r\n            return rotate_right(-bias);\r\n        bias %= _size;\r\n        if(!bias)\r\n            return;\r\n        int cc = cycle_count(bias);\r\n        int cm = cycle_index(bias);\r\n        rotate_left(cc, cm);\r\n    }\r\n    void rotate_right(int bias)\r\n    {\r\n        if(!bias)\r\n            return;\r\n        if(bias < 0)\r\n            return rotate_left(-bias);\r\n        bias %= _size;\r\n        if(!bias)\r\n            return;\r\n        int cc = cycle_count(bias);\r\n        int cm = cycle_index(bias);\r\n        rotate_right(cc, cm);\r\n    }\r\n    // todo: following\r\n    void rotate_left(int cc, int cm)\r\n    {\r\n        assert(cc >= 0 && cm >= 0);\r\n        if(!cm) {\r\n            uint* ptr = new uint[cc];\r\n            int crst = (int)_container.size() - cc;\r\n            memcpy_s(ptr, sizeof(uint) * cc, &_container.front(), _container.capacity());\r\n            memcpy_s(&_container.front(), sizeof(uint) * crst, &_container.at(cc), sizeof(uint) * crst);\r\n            memcpy_s(&_container.front(), sizeof(uint) * cc, ptr, sizeof(uint) * cc);\r\n            delete [] ptr;\r\n        }\r\n        else {\r\n\r\n        }\r\n    }\r\n    void rotate_right(int cc, int cm)\r\n    {\r\n        assert(cc >= 0 && cm >= 0);\r\n    }\r\n    void shift_left(int bias);\r\n    void shift_right(int bias);\r\n    void shift_left_1(int bias);\r\n    void shift_right_1(int bias);\r\n\r\npublic:\r\n    static int cycle_count(int p) { return p / knot_size; }\r\n    static int cycle_index(int p) { return p % knot_size; }\r\n\r\nprotected:\r\n    void ensure_container_capacity(int pos)\r\n    {\r\n        if(pos < _size)\r\n            return;\r\n        int cc = cycle_count(pos);\r\n        int cidx = cycle_index(pos);\r\n        ensure_container_capacity(pos, cc, cidx);\r\n    }\r\n    void ensure_container_capacity(int pos, int cc, int cidx)\r\n    {\r\n        assert(cc * knot_size + cidx == pos);\r\n        if(pos < _size)\r\n            return;\r\n        int kc = knot_count();\r\n        assert(kc <= cc);\r\n        if(kc == cc) {\r\n            _container.push_back(0);\r\n            _size = pos + 1;\r\n        }\r\n        else {\r\n            cc ++;\r\n            _container.resize(cc);\r\n            int delta = cc - kc;\r\n            memset(&_container.at(kc), 0, delta * sizeof(uint));\r\n            _size = pos + 1;\r\n        }\r\n    }\r\n};\r\n\r\n__gslib_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "410ddc67f22a6345038063dd7f5a11cde013ce32", "size": 6624, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gslib/vbitset.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/gslib/vbitset.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gslib/vbitset.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 28.9257641921, "max_line_length": 105, "alphanum_fraction": 0.54272343, "num_tokens": 1657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.457136702035843, "lm_q2_score": 0.07055959814175729, "lm_q1q2_score": 0.03225538199149732}}
{"text": "#include <petsc.h>\n#include \"um.h\"\n\nPetscErrorCode UMInitialize(UM *mesh) {\n    mesh->N = 0;\n    mesh->K = 0;\n    mesh->P = 0;\n    mesh->loc = NULL;\n    mesh->e = NULL;\n    mesh->bf = NULL;\n    mesh->ns = NULL;\n    return 0;\n}\n\nPetscErrorCode UMDestroy(UM *mesh) {\n    PetscErrorCode ierr;\n    ierr = VecDestroy(&(mesh->loc)); CHKERRQ(ierr);\n    ierr = ISDestroy(&(mesh->e)); CHKERRQ(ierr);\n    ierr = ISDestroy(&(mesh->bf)); CHKERRQ(ierr);\n    ierr = ISDestroy(&(mesh->ns)); CHKERRQ(ierr);\n    return 0;\n}\n\nPetscErrorCode UMViewASCII(UM *mesh, PetscViewer viewer) {\n    PetscErrorCode ierr;\n    PetscInt        n, k;\n    const Node      *aloc;\n    const PetscInt  *ae, *abf, *ans;\n\n    ierr = PetscViewerASCIIPushSynchronized(viewer); CHKERRQ(ierr);\n    if (mesh->loc && (mesh->N > 0)) {\n        ierr = PetscViewerASCIISynchronizedPrintf(viewer,\"%d nodes at (x,y) coordinates:\\n\",mesh->N); CHKERRQ(ierr);\n        ierr = VecGetArrayRead(mesh->loc,(const PetscReal **)&aloc); CHKERRQ(ierr);\n        for (n = 0; n < mesh->N; n++) {\n            ierr = PetscViewerASCIISynchronizedPrintf(viewer,\"    %3d : (%g,%g)\\n\",\n                               n,aloc[n].x,aloc[n].y); CHKERRQ(ierr);\n        }\n        ierr = VecRestoreArrayRead(mesh->loc,(const PetscReal **)&aloc); CHKERRQ(ierr);\n    } else {\n        ierr = PetscViewerASCIISynchronizedPrintf(viewer,\"node coordinates empty or unallocated\\n\"); CHKERRQ(ierr);\n    }\n    if (mesh->e && (mesh->K > 0)) {\n        ierr = PetscViewerASCIISynchronizedPrintf(viewer,\"%d elements:\\n\",mesh->K); CHKERRQ(ierr);\n        ierr = ISGetIndices(mesh->e,&ae); CHKERRQ(ierr);\n        for (k = 0; k < mesh->K; k++) {\n            ierr = PetscPrintf(PETSC_COMM_WORLD,\"    %3d : %3d %3d %3d\\n\",\n                               k,ae[3*k+0],ae[3*k+1],ae[3*k+2]); CHKERRQ(ierr);\n        }\n        ierr = ISRestoreIndices(mesh->e,&ae); CHKERRQ(ierr);\n    } else {\n        ierr = PetscViewerASCIISynchronizedPrintf(viewer,\"element index triples empty or unallocated\\n\"); CHKERRQ(ierr);\n    }\n    if (mesh->bf && (mesh->N > 0)) {\n        ierr = PetscViewerASCIISynchronizedPrintf(viewer,\"%d boundary flags at nodes (0 = interior, 1 = boundary, 2 = Dirichlet):\\n\",mesh->N); CHKERRQ(ierr);\n        ierr = ISGetIndices(mesh->bf,&abf); CHKERRQ(ierr);\n        for (n = 0; n < mesh->N; n++) {\n            ierr = PetscViewerASCIISynchronizedPrintf(viewer,\"    %3d : %1d\\n\",\n                               n,abf[n]); CHKERRQ(ierr);\n        }\n        ierr = ISRestoreIndices(mesh->bf,&abf); CHKERRQ(ierr);\n    } else {\n        ierr = PetscViewerASCIISynchronizedPrintf(viewer,\"boundary flags empty or unallocated\\n\"); CHKERRQ(ierr);\n    }\n    if (mesh->ns && (mesh->P > 0)) {\n        ierr = PetscViewerASCIISynchronizedPrintf(viewer,\"%d Neumann boundary segments:\\n\",mesh->P); CHKERRQ(ierr);\n        ierr = ISGetIndices(mesh->ns,&ans); CHKERRQ(ierr);\n        for (n = 0; n < mesh->P; n++) {\n            ierr = PetscViewerASCIISynchronizedPrintf(viewer,\"    %3d : %3d %3d\\n\",\n                               n,ans[2*n+0],ans[2*n+1]); CHKERRQ(ierr);\n        }\n        ierr = ISRestoreIndices(mesh->ns,&ans); CHKERRQ(ierr);\n    } else {\n        ierr = PetscViewerASCIISynchronizedPrintf(viewer,\"Neumann boundary segments empty or unallocated\\n\"); CHKERRQ(ierr);\n    }\n    ierr = PetscViewerASCIIPopSynchronized(viewer); CHKERRQ(ierr);\n    return 0;\n}\n\n\nPetscErrorCode UMViewSolutionBinary(UM *mesh, char *filename, Vec u) {\n    PetscErrorCode ierr;\n    PetscInt       Nu;\n    PetscViewer viewer;\n    ierr = VecGetSize(u,&Nu); CHKERRQ(ierr);\n    if (Nu != mesh->N) {\n        SETERRQ2(PETSC_COMM_SELF,1,\n           \"incompatible sizes of u (=%d) and number of nodes (=%d)\\n\",Nu,mesh->N);\n    }\n    ierr = PetscViewerBinaryOpen(PETSC_COMM_WORLD,filename,FILE_MODE_WRITE,&viewer); CHKERRQ(ierr);\n    ierr = VecView(u,viewer); CHKERRQ(ierr);\n    ierr = PetscViewerDestroy(&viewer); CHKERRQ(ierr);\n    return 0;\n}\n\n\nPetscErrorCode UMReadNodes(UM *mesh, char *filename) {\n    PetscErrorCode ierr;\n    PetscInt       twoN;\n    PetscViewer viewer;\n    if (mesh->N > 0) {\n        SETERRQ(PETSC_COMM_SELF,1,\"nodes already created?\\n\");\n    }\n    ierr = VecCreate(PETSC_COMM_WORLD,&mesh->loc); CHKERRQ(ierr);\n    ierr = VecSetFromOptions(mesh->loc); CHKERRQ(ierr);\n    ierr = PetscViewerBinaryOpen(PETSC_COMM_WORLD,filename,FILE_MODE_READ,&viewer); CHKERRQ(ierr);\n    ierr = VecLoad(mesh->loc,viewer); CHKERRQ(ierr);\n    ierr = PetscViewerDestroy(&viewer); CHKERRQ(ierr);\n    ierr = VecGetSize(mesh->loc,&twoN); CHKERRQ(ierr);\n    if (twoN % 2 != 0) {\n        SETERRQ1(PETSC_COMM_SELF,2,\"node locations loaded from %s are not N pairs\\n\",filename);\n    }\n    mesh->N = twoN / 2;\n    return 0;\n}\n\n\nPetscErrorCode UMCheckElements(UM *mesh) {\n    PetscErrorCode ierr;\n    const PetscInt  *ae;\n    PetscInt        k, m;\n    if ((mesh->K == 0) || (mesh->e == NULL)) {\n        SETERRQ(PETSC_COMM_SELF,1,\n                \"number of elements unknown; call UMReadElements() first\\n\");\n    }\n    if (mesh->N == 0) {\n        SETERRQ(PETSC_COMM_SELF,2,\n                \"node size unknown so element check impossible; call UMReadNodes() first\\n\");\n    }\n    ierr = ISGetIndices(mesh->e,&ae); CHKERRQ(ierr);\n    for (k = 0; k < mesh->K; k++) {\n        for (m = 0; m < 3; m++) {\n            if ((ae[3*k+m] < 0) || (ae[3*k+m] >= mesh->N)) {\n                SETERRQ3(PETSC_COMM_SELF,3,\n                   \"index e[%d]=%d invalid: not between 0 and N-1=%d\\n\",\n                   3*k+m,ae[3*k+m],mesh->N-1);\n            }\n        }\n        // FIXME: could add check for distinct indices\n    }\n    ierr = ISRestoreIndices(mesh->e,&ae); CHKERRQ(ierr);\n    return 0;\n}\n\nPetscErrorCode UMCheckBoundaryData(UM *mesh) {\n    PetscErrorCode ierr;\n    const PetscInt  *ans, *abf;\n    PetscInt        n, m;\n    if (mesh->N == 0) {\n        SETERRQ(PETSC_COMM_SELF,2,\n                \"node size unknown so boundary flag check impossible; call UMReadNodes() first\\n\");\n    }\n    if (mesh->bf == NULL) {\n        SETERRQ(PETSC_COMM_SELF,1,\n                \"boundary flags at nodes not allocated; call UMReadNodes() first\\n\");\n    }\n    if ((mesh->P > 0) && (mesh->ns == NULL)) {\n        SETERRQ(PETSC_COMM_SELF,3,\n                \"inconsistent data for Neumann boundary segments\\n\");\n    }\n    ierr = ISGetIndices(mesh->bf,&abf); CHKERRQ(ierr);\n    for (n = 0; n < mesh->N; n++) {\n        switch (abf[n]) {\n            case 0 :\n            case 1 :\n            case 2 :\n                break;\n            default :\n                SETERRQ2(PETSC_COMM_SELF,5,\n                   \"boundary flag bf[%d]=%d invalid: not in {0,1,2}\\n\",\n                   n,abf[n]);\n        }\n    }\n    ierr = ISRestoreIndices(mesh->bf,&abf); CHKERRQ(ierr);\n    if (mesh->P > 0) {\n        ierr = ISGetIndices(mesh->ns,&ans); CHKERRQ(ierr);\n        for (n = 0; n < mesh->P; n++) {\n            for (m = 0; m < 2; m++) {\n                if ((ans[2*n+m] < 0) || (ans[2*n+m] >= mesh->N)) {\n                    SETERRQ3(PETSC_COMM_SELF,6,\n                       \"index ns[%d]=%d invalid: not between 0 and N-1=%d\\n\",\n                       2*n+m,ans[3*n+m],mesh->N-1);\n                }\n            }\n        }\n        ierr = ISRestoreIndices(mesh->ns,&ans); CHKERRQ(ierr);\n    }\n    return 0;\n}\n\nPetscErrorCode UMReadISs(UM *mesh, char *filename) {\n    PetscErrorCode ierr;\n    PetscViewer  viewer;\n    PetscInt     n_bf;\n    if ((!mesh->loc) || (mesh->N == 0)) {\n        SETERRQ(PETSC_COMM_SELF,2,\n                \"node coordinates not created ... do that first ... stopping\\n\");\n    }\n    if ((mesh->K > 0) || (mesh->P > 0) || (mesh->e != NULL) || (mesh->bf != NULL) || (mesh->ns != NULL)) {\n        SETERRQ(PETSC_COMM_SELF,1,\n                \"elements, boundary flags, Neumann boundary segments already created? ... stopping\\n\");\n    }\n    ierr = PetscViewerBinaryOpen(PETSC_COMM_WORLD,filename,FILE_MODE_READ,&viewer); CHKERRQ(ierr);\n    // create and load e\n    ierr = ISCreate(PETSC_COMM_WORLD,&(mesh->e)); CHKERRQ(ierr);\n    ierr = ISLoad(mesh->e,viewer); CHKERRQ(ierr);\n    ierr = ISGetSize(mesh->e,&(mesh->K)); CHKERRQ(ierr);\n    if (mesh->K % 3 != 0) {\n        SETERRQ1(PETSC_COMM_SELF,3,\n                 \"IS e loaded from %s is wrong size for list of element triples\\n\",filename);\n    }\n    mesh->K /= 3;\n    // create and load bf\n    ierr = ISCreate(PETSC_COMM_WORLD,&(mesh->bf)); CHKERRQ(ierr);\n    ierr = ISLoad(mesh->bf,viewer); CHKERRQ(ierr);\n    ierr = ISGetSize(mesh->bf,&n_bf); CHKERRQ(ierr);\n    if (n_bf != mesh->N) {\n        SETERRQ1(PETSC_COMM_SELF,4,\n                 \"IS bf loaded from %s is wrong size for list of boundary flags\\n\",filename);\n    }\n    // FIXME  seems there is no way to tell if file is empty at this point\n    // create and load ns last ... may *start with a negative value* in which case set P = 0\n    const PetscInt *ans;\n    ierr = ISCreate(PETSC_COMM_WORLD,&(mesh->ns)); CHKERRQ(ierr);\n    ierr = ISLoad(mesh->ns,viewer); CHKERRQ(ierr);\n    ierr = ISGetIndices(mesh->ns,&ans); CHKERRQ(ierr);\n    if (ans[0] < 0) {\n        ISDestroy(&(mesh->ns));\n        mesh->ns = NULL;\n        mesh->P = 0;\n    } else {\n        ierr = ISGetSize(mesh->ns,&(mesh->P)); CHKERRQ(ierr);\n        if (mesh->P % 2 != 0) {\n            SETERRQ1(PETSC_COMM_SELF,4,\n                     \"IS s loaded from %s is wrong size for list of Neumann boundary segment pairs\\n\",filename);\n        }\n        mesh->P /= 2;\n    }\n    ierr = PetscViewerDestroy(&viewer); CHKERRQ(ierr);\n\n    // check that mesh is complete now\n    ierr = UMCheckElements(mesh); CHKERRQ(ierr);\n    ierr = UMCheckBoundaryData(mesh); CHKERRQ(ierr);\n    return 0;\n}\n\n\nPetscErrorCode UMStats(UM *mesh, PetscReal *maxh, PetscReal *meanh,\n                       PetscReal *maxa, PetscReal *meana) {\n    PetscErrorCode ierr;\n    const PetscInt *ae;\n    const Node     *aloc;\n    PetscInt       k;\n    PetscReal      x[3], y[3], ax, ay, bx, by, cx, cy, h, a,\n                   Maxh = 0.0, Maxa = 0.0, Sumh = 0.0, Suma = 0.0;\n    if ((mesh->K == 0) || (mesh->e == NULL)) {\n        SETERRQ(PETSC_COMM_SELF,1,\n                \"number of elements unknown; call UMReadElements() first\\n\");\n    }\n    if (mesh->N == 0) {\n        SETERRQ(PETSC_COMM_SELF,2,\n                \"node size unknown so element check impossible; call UMReadNodes() first\\n\");\n    }\n    ierr = UMGetNodeCoordArrayRead(mesh,&aloc); CHKERRQ(ierr);\n    ierr = ISGetIndices(mesh->e,&ae); CHKERRQ(ierr);\n    for (k = 0; k < mesh->K; k++) {\n        x[0] = aloc[ae[3*k]].x;\n        y[0] = aloc[ae[3*k]].y;\n        x[1] = aloc[ae[3*k+1]].x;\n        y[1] = aloc[ae[3*k+1]].y;\n        x[2] = aloc[ae[3*k+2]].x;\n        y[2] = aloc[ae[3*k+2]].y;\n        ax = x[1] - x[0];\n        ay = y[1] - y[0];\n        bx = x[2] - x[0];\n        by = y[2] - y[0];\n        cx = x[1] - x[2];\n        cy = y[1] - y[2];\n        h = PetscMax(ax*ax+ay*ay, PetscMax(bx*bx+by*by, cx*cx+cy*cy));\n        h = sqrt(h);\n        a = 0.5 * PetscAbs(ax*by-ay*bx);\n        Maxh = PetscMax(Maxh,h);\n        Sumh += h;\n        Maxa = PetscMax(Maxa,a);\n        Suma += a;\n    }\n    ierr = ISRestoreIndices(mesh->e,&ae); CHKERRQ(ierr);\n    ierr = UMRestoreNodeCoordArrayRead(mesh,&aloc); CHKERRQ(ierr);\n    if (maxh)  *maxh = Maxh;\n    if (maxa)  *maxa = Maxa;\n    if (meanh)  *meanh = Sumh / mesh->K;\n    if (meana)  *meana = Suma / mesh->K;\n    return 0;\n}\n\nPetscErrorCode UMGetNodeCoordArrayRead(UM *mesh, const Node **xy) {\n    PetscErrorCode ierr;\n    if ((!mesh->loc) || (mesh->N == 0)) {\n        SETERRQ(PETSC_COMM_SELF,1,\"node coordinates not created ... stopping\\n\");\n    }\n    ierr = VecGetArrayRead(mesh->loc,(const PetscReal **)xy); CHKERRQ(ierr);\n    return 0;\n}\n\n\nPetscErrorCode UMRestoreNodeCoordArrayRead(UM *mesh, const Node **xy) {\n    PetscErrorCode ierr;\n    if ((!mesh->loc) || (mesh->N == 0)) {\n        SETERRQ(PETSC_COMM_SELF,1,\"node coordinates not created ... stopping\\n\");\n    }\n    ierr = VecRestoreArrayRead(mesh->loc,(const PetscReal **)xy); CHKERRQ(ierr);\n    return 0;\n}\n\n", "meta": {"hexsha": "2727b71c06be474ef85a2ad1603069a066e67925", "size": 11942, "ext": "c", "lang": "C", "max_stars_repo_path": "c/ch10/um.c", "max_stars_repo_name": "thw1021/p4pdes", "max_stars_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 115.0, "max_stars_repo_stars_event_min_datetime": "2015-03-13T04:35:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T23:12:02.000Z", "max_issues_repo_path": "c/ch10/um.c", "max_issues_repo_name": "thw1021/p4pdes", "max_issues_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52.0, "max_issues_repo_issues_event_min_datetime": "2015-09-24T17:42:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-29T12:36:20.000Z", "max_forks_repo_path": "c/ch10/um.c", "max_forks_repo_name": "thw1021/p4pdes", "max_forks_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 46.0, "max_forks_repo_forks_event_min_datetime": "2016-07-23T09:26:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T07:43:17.000Z", "avg_line_length": 38.0318471338, "max_line_length": 157, "alphanum_fraction": 0.5624685982, "num_tokens": 3590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906414693485, "lm_q2_score": 0.06853749588586537, "lm_q1q2_score": 0.03212973666103766}}
{"text": "#include <errno.h>\n#include <getopt.h>\n#include <gsl/gsl_spmatrix.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <sys/stat.h>\n\nstatic int verbose = 0;\nstatic int help = 0;\n\nint test (size_t m,\n\t  size_t n,\n\t  size_t r,\n\t  size_t c,\n\t  size_t nnz,\n\t  const size_t *ind,\n\t  const size_t *ptr,\n\t  const double *data,\n          int trials,\n          int verbose);\n\nstatic void usage () {\n  fprintf(stderr,\"usage: spmv [options] <input>\\n\"\n  \"  <input>                    MatrixMarket file (multiply this matrix)\\n\"\n  \"  -r, --block_r <arg>        Row block size\\n\"\n  \"  -c, --block_c <arg>        Column block size\\n\"\n  \"  -t, --trials <arg>         Number of trials to run\\n\"\n  \"  -v, --verbose              Verbose mode\\n\"\n  \"  -q, --quiet                Quiet mode\\n\"\n  \"  -h, --help                 Display help message\\n\");\n}\n\nint main (int argc, char **argv) {\n\n  size_t b_r = 1;\n  size_t b_c = 1;\n  int trials = 1;\n\n  /* Beware. Option parsing below. */\n  long longarg;\n  double doublearg;\n  while (1) {\n    static char *options = \"r:c:t:vqh\";\n    static struct option long_options[] = {\n        {\"block_r\",  required_argument, 0, 'r'},\n        {\"block_c\",  required_argument, 0, 'c'},\n        {\"trials\",   required_argument, 0, 't'},\n        {\"verbose\",   no_argument, &verbose, 1},\n        {\"quiet\",     no_argument, &verbose, 0},\n        {\"help\",      no_argument, &help,    1},\n        {0, 0, 0, 0}\n      };\n\n    /* getopt_long stores the option index here. */\n    int option_index = 0;\n\n    int c = getopt_long (argc, argv, options,\n                     long_options, &option_index);\n\n    /* Detect the end of the options. */\n    if (c == -1)\n      break;\n\n    if (c == 0 && long_options[option_index].flag == 0)\n      c = long_options[option_index].val;\n\n    switch (c) {\n      case 0:\n        /* If this option set a flag, do nothing else now. */\n        break;\n\n      case 'r':\n        errno = 0;\n        longarg = strtol(optarg, 0, 10);\n        if (errno != 0 || longarg < 1) {\n          printf(\"option -r takes an integer column block size >= 1\\n\");\n          usage();\n          return 1;\n        }\n        b_r = longarg;\n        break;\n\n      case 'c':\n        errno = 0;\n        longarg = strtol(optarg, 0, 10);\n        if (errno != 0 || longarg < 1) {\n          printf(\"option -c takes an integer column block size >= 1\\n\");\n          usage();\n          return 1;\n        }\n        b_c = longarg;\n        break;\n\n      case 't':\n        errno = 0;\n        longarg = strtol(optarg, 0, 10);\n        if (errno != 0 || longarg < 1) {\n          printf(\"option -t takes an integer number of trials >= 1\\n\");\n          usage();\n          return 1;\n        }\n        trials = longarg;\n        break;\n\n      case 'v':\n        verbose = 1;\n        break;\n\n      case 'q':\n        verbose = 0;\n        break;\n\n      case 'h':\n        help = 1;\n        break;\n\n      case '?':\n        usage();\n        return 1;\n\n      default:\n        abort();\n    }\n  }\n\n  if (help) {\n    printf(\"Run a fill estimation algorithm!\\n\");\n    usage();\n    return 0;\n  }\n\n  if (argc - optind > 1) {\n    printf(\"<input> cannot be more than one file\\n\");\n    usage();\n    return 1;\n  }\n\n  if (argc - optind < 1) {\n    printf(\"<input> not specified\\n\");\n    usage();\n    return 1;\n  }\n\n  struct stat statthing;\n  if (stat(argv[optind], &statthing) < 0 || !S_ISREG(statthing.st_mode)){\n    printf(\"<input> must be filename of MatrixMarket matrix\\n\");\n    usage();\n    return 1;\n  }\n\n  FILE *f = fopen(argv[optind], \"r\");\n  gsl_spmatrix *triples = gsl_spmatrix_fscanf(f);\n  fclose(f);\n  if (triples == 0) {\n    printf(\"<input> must be filename of MatrixMarket matrix\\n\");\n    usage();\n    return 1;\n  }\n\n  int ret = test(triples->size1, triples->size2, b_r, b_c, triples->nz, triples->i, triples->p, triples->data, trials, verbose);\n\n  gsl_spmatrix_free(triples);\n\n  return ret;\n\n}\n", "meta": {"hexsha": "7ec682ea41217f7f86855e68a50b53c68235c3a5", "size": 3865, "ext": "c", "lang": "C", "max_stars_repo_path": "src/run_spmv.c", "max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/run_spmv.c", "max_issues_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_issues_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/run_spmv.c", "max_forks_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_forks_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1437125749, "max_line_length": 128, "alphanum_fraction": 0.5197930142, "num_tokens": 1114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.0656048374590693, "lm_q1q2_score": 0.032033752782345715}}
{"text": "/**\n *\n * @file qwrapper_zlaswp.c\n *\n *  PLASMA core_blas quark wrapper\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Mathieu Faverge\n * @date 2010-11-15\n * @precisions normal z -> c d s\n *\n **/\n#include <lapacke.h>\n#include \"common.h\"\n\n/***************************************************************************//**\n *\n **/\nvoid QUARK_CORE_zlaswp(Quark *quark, Quark_Task_Flags *task_flags,\n                       int n, PLASMA_Complex64_t *A, int lda,\n                       int i1,  int i2, const int *ipiv, int inc)\n{\n    DAG_CORE_LASWP;\n    QUARK_Insert_Task(\n        quark, CORE_zlaswp_quark, task_flags,\n        sizeof(int),                      &n,    VALUE,\n        sizeof(PLASMA_Complex64_t)*lda*n,  A,        INOUT | LOCALITY,\n        sizeof(int),                      &lda,  VALUE,\n        sizeof(int),                      &i1,   VALUE,\n        sizeof(int),                      &i2,   VALUE,\n        sizeof(int)*n,                     ipiv,     INPUT,\n        sizeof(int),                      &inc,  VALUE,\n        0);\n}\n\n/***************************************************************************//**\n *\n **/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_zlaswp_quark = PCORE_zlaswp_quark\n#define CORE_zlaswp_quark PCORE_zlaswp_quark\n#endif\nvoid CORE_zlaswp_quark(Quark *quark)\n{\n    int n, lda, i1, i2, inc;\n    int *ipiv;\n    PLASMA_Complex64_t *A;\n\n    quark_unpack_args_7(quark, n, A, lda, i1, i2, ipiv, inc);\n    LAPACKE_zlaswp_work(LAPACK_COL_MAJOR, n, A, lda, i1, i2, ipiv, inc );\n}\n\n/***************************************************************************//**\n *\n **/\nvoid QUARK_CORE_zlaswp_f2(Quark *quark, Quark_Task_Flags *task_flags,\n                          int n, PLASMA_Complex64_t *A, int lda,\n                          int i1,  int i2, const int *ipiv, int inc,\n                          PLASMA_Complex64_t *fake1, int szefake1, int flag1,\n                          PLASMA_Complex64_t *fake2, int szefake2, int flag2)\n{\n    DAG_CORE_LASWP;\n    QUARK_Insert_Task(\n        quark, CORE_zlaswp_f2_quark, task_flags,\n        sizeof(int),                        &n,     VALUE,\n        sizeof(PLASMA_Complex64_t)*lda*n,    A,         INOUT | LOCALITY,\n        sizeof(int),                        &lda,   VALUE,\n        sizeof(int),                        &i1,    VALUE,\n        sizeof(int),                        &i2,    VALUE,\n        sizeof(int)*n,                       ipiv,      INPUT,\n        sizeof(int),                        &inc,   VALUE,\n        sizeof(PLASMA_Complex64_t)*szefake1, fake1,     flag1,\n        sizeof(PLASMA_Complex64_t)*szefake2, fake2,     flag2,\n        0);\n}\n\n/***************************************************************************//**\n *\n **/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_zlaswp_f2_quark = PCORE_zlaswp_f2_quark\n#define CORE_zlaswp_f2_quark PCORE_zlaswp_f2_quark\n#endif\nvoid CORE_zlaswp_f2_quark(Quark* quark)\n{\n    int n, lda, i1, i2, inc;\n    int *ipiv;\n    PLASMA_Complex64_t *A;\n    void *fake1, *fake2;\n\n    quark_unpack_args_9(quark, n, A, lda, i1, i2, ipiv, inc, fake1, fake2);\n    LAPACKE_zlaswp_work(LAPACK_COL_MAJOR, n, A, lda, i1, i2, ipiv, inc );\n}\n\n\n/***************************************************************************//**\n *\n **/\nvoid QUARK_CORE_zlaswp_ontile(Quark *quark, Quark_Task_Flags *task_flags,\n                              PLASMA_desc descA, PLASMA_Complex64_t *Aij,\n                              int i1,  int i2, const int *ipiv, int inc, PLASMA_Complex64_t *fakepanel)\n{\n    DAG_CORE_LASWP;\n    if (fakepanel == Aij) {\n        QUARK_Insert_Task(\n            quark, CORE_zlaswp_ontile_quark, task_flags,\n            sizeof(PLASMA_desc),              &descA,     VALUE,\n            sizeof(PLASMA_Complex64_t)*1,      Aij,           INOUT | LOCALITY,\n            sizeof(int),                      &i1,        VALUE,\n            sizeof(int),                      &i2,        VALUE,\n            sizeof(int)*(i2-i1+1)*abs(inc),   ipiv,           INPUT,\n            sizeof(int),                      &inc,       VALUE,\n            sizeof(PLASMA_Complex64_t)*1,      fakepanel,     SCRATCH,\n            0);\n    } else {\n        QUARK_Insert_Task(\n            quark, CORE_zlaswp_ontile_quark, task_flags,\n            sizeof(PLASMA_desc),              &descA,     VALUE,\n            sizeof(PLASMA_Complex64_t)*1,      Aij,           INOUT | LOCALITY,\n            sizeof(int),                      &i1,        VALUE,\n            sizeof(int),                      &i2,        VALUE,\n            sizeof(int)*(i2-i1+1)*abs(inc),   ipiv,           INPUT,\n            sizeof(int),                      &inc,       VALUE,\n            sizeof(PLASMA_Complex64_t)*1,      fakepanel,     INOUT,\n            0);\n    }\n}\n\n/***************************************************************************//**\n *\n **/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_zlaswp_ontile_quark = PCORE_zlaswp_ontile_quark\n#define CORE_zlaswp_ontile_quark PCORE_zlaswp_ontile_quark\n#endif\nvoid CORE_zlaswp_ontile_quark(Quark *quark)\n{\n    int i1, i2, inc;\n    int *ipiv;\n    PLASMA_Complex64_t *A, *fake;\n    PLASMA_desc descA;\n\n    quark_unpack_args_7(quark, descA, A, i1, i2, ipiv, inc, fake);\n    CORE_zlaswp_ontile(descA, i1, i2, ipiv, inc);\n}\n\n/***************************************************************************//**\n *\n **/\nvoid QUARK_CORE_zlaswp_ontile_f2(Quark *quark, Quark_Task_Flags *task_flags,\n                                 PLASMA_desc descA, PLASMA_Complex64_t *Aij,\n                                 int i1,  int i2, const int *ipiv, int inc,\n                                 PLASMA_Complex64_t *fake1, int szefake1, int flag1,\n                                 PLASMA_Complex64_t *fake2, int szefake2, int flag2)\n{\n    DAG_CORE_LASWP;\n    QUARK_Insert_Task(\n        quark, CORE_zlaswp_ontile_f2_quark, task_flags,\n        sizeof(PLASMA_desc),                &descA, VALUE,\n        sizeof(PLASMA_Complex64_t)*1,        Aij,       INOUT | LOCALITY,\n        sizeof(int),                        &i1,    VALUE,\n        sizeof(int),                        &i2,    VALUE,\n        sizeof(int)*(i2-i1+1)*abs(inc),      ipiv,      INPUT,\n        sizeof(int),                        &inc,   VALUE,\n        sizeof(PLASMA_Complex64_t)*szefake1, fake1, flag1,\n        sizeof(PLASMA_Complex64_t)*szefake2, fake2, flag2,\n        0);\n}\n\n/***************************************************************************//**\n *\n **/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_zlaswp_ontile_f2_quark = PCORE_zlaswp_ontile_f2_quark\n#define CORE_zlaswp_ontile_f2_quark PCORE_zlaswp_ontile_f2_quark\n#endif\nvoid CORE_zlaswp_ontile_f2_quark(Quark *quark)\n{\n    int i1, i2, inc;\n    int *ipiv;\n    PLASMA_Complex64_t *A;\n    PLASMA_desc descA;\n    void *fake1, *fake2;\n\n    quark_unpack_args_8(quark, descA, A, i1, i2, ipiv, inc, fake1, fake2);\n    CORE_zlaswp_ontile(descA, i1, i2, ipiv, inc);\n}\n\n/***************************************************************************//**\n *\n **/\nvoid QUARK_CORE_zswptr_ontile(Quark *quark, Quark_Task_Flags *task_flags,\n                              PLASMA_desc descA, PLASMA_Complex64_t *Aij,\n                              int i1,  int i2, const int *ipiv, int inc,\n                              const PLASMA_Complex64_t *Akk, int ldak)\n{\n    DAG_CORE_TRSM;\n    QUARK_Insert_Task(\n        quark, CORE_zswptr_ontile_quark, task_flags,\n        sizeof(PLASMA_desc),              &descA, VALUE,\n        sizeof(PLASMA_Complex64_t)*1,      Aij,       INOUT | LOCALITY,\n        sizeof(int),                      &i1,    VALUE,\n        sizeof(int),                      &i2,    VALUE,\n        sizeof(int)*(i2-i1+1)*abs(inc),    ipiv,      INPUT,\n        sizeof(int),                      &inc,   VALUE,\n        sizeof(PLASMA_Complex64_t)*ldak,   Akk,       INPUT,\n        sizeof(int),                      &ldak,  VALUE,\n        0);\n}\n\n/***************************************************************************//**\n *\n **/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_zswptr_ontile_quark = PCORE_zswptr_ontile_quark\n#define CORE_zswptr_ontile_quark PCORE_zswptr_ontile_quark\n#endif\nvoid CORE_zswptr_ontile_quark(Quark *quark)\n{\n    int i1, i2, inc, ldak;\n    int *ipiv;\n    PLASMA_Complex64_t *A, *Akk;\n    PLASMA_desc descA;\n\n    quark_unpack_args_8(quark, descA, A, i1, i2, ipiv, inc, Akk, ldak);\n    CORE_zswptr_ontile(descA, i1, i2, ipiv, inc, Akk, ldak);\n}\n\n/***************************************************************************//**\n *\n **/\nvoid QUARK_CORE_zlaswpc_ontile(Quark *quark, Quark_Task_Flags *task_flags,\n                              PLASMA_desc descA, PLASMA_Complex64_t *Aij,\n                              int i1,  int i2, const int *ipiv, int inc, PLASMA_Complex64_t *fakepanel)\n{\n    DAG_CORE_LASWP;\n    if (fakepanel == Aij) {\n        QUARK_Insert_Task(\n            quark, CORE_zlaswpc_ontile_quark, task_flags,\n            sizeof(PLASMA_desc),              &descA,     VALUE,\n            sizeof(PLASMA_Complex64_t)*1,      Aij,           INOUT | LOCALITY,\n            sizeof(int),                      &i1,        VALUE,\n            sizeof(int),                      &i2,        VALUE,\n            sizeof(int)*(i2-i1+1)*abs(inc),   ipiv,           INPUT,\n            sizeof(int),                      &inc,       VALUE,\n            sizeof(PLASMA_Complex64_t)*1,      fakepanel,     SCRATCH,\n            0);\n    } else {\n        QUARK_Insert_Task(\n            quark, CORE_zlaswpc_ontile_quark, task_flags,\n            sizeof(PLASMA_desc),              &descA,     VALUE,\n            sizeof(PLASMA_Complex64_t)*1,      Aij,           INOUT | LOCALITY,\n            sizeof(int),                      &i1,        VALUE,\n            sizeof(int),                      &i2,        VALUE,\n            sizeof(int)*(i2-i1+1)*abs(inc),   ipiv,           INPUT,\n            sizeof(int),                      &inc,       VALUE,\n            sizeof(PLASMA_Complex64_t)*1,      fakepanel,     INOUT,\n            0);\n    }\n}\n\n/***************************************************************************//**\n *\n **/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_zlaswpc_ontile_quark = PCORE_zlaswpc_ontile_quark\n#define CORE_zlaswpc_ontile_quark PCORE_zlaswpc_ontile_quark\n#endif\nvoid CORE_zlaswpc_ontile_quark(Quark *quark)\n{\n    int i1, i2, inc;\n    int *ipiv;\n    PLASMA_Complex64_t *A, *fake;\n    PLASMA_desc descA;\n\n    quark_unpack_args_7(quark, descA, A, i1, i2, ipiv, inc, fake);\n    CORE_zlaswpc_ontile(descA, i1, i2, ipiv, inc);\n}\n\n", "meta": {"hexsha": "7c1e764c97faa21f4bec8c7ff286a764b172d5db", "size": 10593, "ext": "c", "lang": "C", "max_stars_repo_path": "core_blas-qwrapper/qwrapper_zlaswp.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "core_blas-qwrapper/qwrapper_zlaswp.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "core_blas-qwrapper/qwrapper_zlaswp.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5638297872, "max_line_length": 103, "alphanum_fraction": 0.4969319362, "num_tokens": 2970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.06656918248903144, "lm_q1q2_score": 0.031985072801059715}}
{"text": "/* roots/gsl_roots.h\r\n * \r\n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Reid Priedhorsky, Brian Gough\r\n * \r\n * This program is free software; you can redistribute it and/or modify\r\n * it under the terms of the GNU General Public License as published by\r\n * the Free Software Foundation; either version 3 of the License, or (at\r\n * your option) any later version.\r\n * \r\n * This program is distributed in the hope that it will be useful, but\r\n * WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n * General Public License for more details.\r\n * \r\n * You should have received a copy of the GNU General Public License\r\n * along with this program; if not, write to the Free Software\r\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r\n */\r\n\r\n#ifndef __GSL_ROOTS_H__\r\n#define __GSL_ROOTS_H__\r\n\r\n#if !defined( GSL_FUN )\r\n#  if !defined( GSL_DLL )\r\n#    define GSL_FUN extern\r\n#  elif defined( BUILD_GSL_DLL )\r\n#    define GSL_FUN extern __declspec(dllexport)\r\n#  else\r\n#    define GSL_FUN extern __declspec(dllimport)\r\n#  endif\r\n#endif\r\n\r\n#include <stdlib.h>\r\n#include <gsl/gsl_types.h>\r\n#include <gsl/gsl_math.h>\r\n\r\n#undef __BEGIN_DECLS\r\n#undef __END_DECLS\r\n#ifdef __cplusplus\r\n# define __BEGIN_DECLS extern \"C\" {\r\n# define __END_DECLS }\r\n#else\r\n# define __BEGIN_DECLS /* empty */\r\n# define __END_DECLS /* empty */\r\n#endif\r\n\r\n__BEGIN_DECLS\r\n\r\ntypedef struct\r\n  {\r\n    const char *name;\r\n    size_t size;\r\n    int (*set) (void *state, gsl_function * f, double * root, double x_lower, double x_upper);\r\n    int (*iterate) (void *state, gsl_function * f, double * root, double * x_lower, double * x_upper);\r\n  }\r\ngsl_root_fsolver_type;\r\n\r\ntypedef struct\r\n  {\r\n    const gsl_root_fsolver_type * type;\r\n    gsl_function * function ;\r\n    double root ;\r\n    double x_lower;\r\n    double x_upper;\r\n    void *state;\r\n  }\r\ngsl_root_fsolver;\r\n\r\ntypedef struct\r\n  {\r\n    const char *name;\r\n    size_t size;\r\n    int (*set) (void *state, gsl_function_fdf * f, double * root);\r\n    int (*iterate) (void *state, gsl_function_fdf * f, double * root);\r\n  }\r\ngsl_root_fdfsolver_type;\r\n\r\ntypedef struct\r\n  {\r\n    const gsl_root_fdfsolver_type * type;\r\n    gsl_function_fdf * fdf ;\r\n    double root ;\r\n    void *state;\r\n  }\r\ngsl_root_fdfsolver;\r\n\r\nGSL_FUN gsl_root_fsolver *\r\ngsl_root_fsolver_alloc (const gsl_root_fsolver_type * T);\r\nGSL_FUN void gsl_root_fsolver_free (gsl_root_fsolver * s);\r\n\r\nGSL_FUN int gsl_root_fsolver_set (gsl_root_fsolver * s,\r\n                          gsl_function * f, \r\n                          double x_lower, double x_upper);\r\n\r\nGSL_FUN int gsl_root_fsolver_iterate (gsl_root_fsolver * s);\r\n\r\nGSL_FUN const char * gsl_root_fsolver_name (const gsl_root_fsolver * s);\r\nGSL_FUN double gsl_root_fsolver_root (const gsl_root_fsolver * s);\r\nGSL_FUN double gsl_root_fsolver_x_lower (const gsl_root_fsolver * s);\r\nGSL_FUN double gsl_root_fsolver_x_upper (const gsl_root_fsolver * s);\r\n\r\n\r\nGSL_FUN gsl_root_fdfsolver *\r\ngsl_root_fdfsolver_alloc (const gsl_root_fdfsolver_type * T);\r\n\r\nGSL_FUN int\r\ngsl_root_fdfsolver_set (gsl_root_fdfsolver * s, \r\n                         gsl_function_fdf * fdf, double root);\r\n\r\nGSL_FUN int\r\ngsl_root_fdfsolver_iterate (gsl_root_fdfsolver * s);\r\n\r\nGSL_FUN void\r\ngsl_root_fdfsolver_free (gsl_root_fdfsolver * s);\r\n\r\nGSL_FUN const char * gsl_root_fdfsolver_name (const gsl_root_fdfsolver * s);\r\nGSL_FUN double gsl_root_fdfsolver_root (const gsl_root_fdfsolver * s);\r\n\r\nGSL_FUN int\r\ngsl_root_test_interval (double x_lower, double x_upper, double epsabs, double epsrel);\r\n\r\nGSL_FUN int\r\ngsl_root_test_residual (double f, double epsabs);\r\n\r\nGSL_FUN int\r\ngsl_root_test_delta (double x1, double x0, double epsabs, double epsrel);\r\n\r\nGSL_VAR const gsl_root_fsolver_type  * gsl_root_fsolver_bisection;\r\nGSL_VAR const gsl_root_fsolver_type  * gsl_root_fsolver_brent;\r\nGSL_VAR const gsl_root_fsolver_type  * gsl_root_fsolver_falsepos;\r\nGSL_VAR const gsl_root_fdfsolver_type  * gsl_root_fdfsolver_newton;\r\nGSL_VAR const gsl_root_fdfsolver_type  * gsl_root_fdfsolver_secant;\r\nGSL_VAR const gsl_root_fdfsolver_type  * gsl_root_fdfsolver_steffenson;\r\n\r\n__END_DECLS\r\n\r\n#endif /* __GSL_ROOTS_H__ */\r\n", "meta": {"hexsha": "b8e516b40d7360fa312d18b166833e53dd81a94d", "size": 4234, "ext": "h", "lang": "C", "max_stars_repo_path": "deps/include/gsl/gsl_roots.h", "max_stars_repo_name": "berkus/music-cs", "max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z", "max_issues_repo_path": "deps/include/gsl/gsl_roots.h", "max_issues_repo_name": "berkus/music-cs", "max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z", "max_forks_repo_path": "deps/include/gsl/gsl_roots.h", "max_forks_repo_name": "berkus/music-cs", "max_forks_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 30.6811594203, "max_line_length": 103, "alphanum_fraction": 0.7246102976, "num_tokens": 1137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.06465349421353082, "lm_q1q2_score": 0.03156922767232243}}
{"text": "#include <stdio.h>\n#include <gsl/gsl_rng.h>\n\ngsl_rng * r;  /* global generator */\n\nint\nmain (void)\n{\n  const gsl_rng_type * T;\n\n  gsl_rng_env_setup();\n\n  T = gsl_rng_default;\n  r = gsl_rng_alloc (T);\n  \n  printf (\"generator type: %s\\n\", gsl_rng_name (r));\n  printf (\"seed = %lu\\n\", gsl_rng_default_seed);\n  printf (\"first value = %lu\\n\", gsl_rng_get (r));\n\n  gsl_rng_free (r);\n  return 0;\n}\n", "meta": {"hexsha": "633026414999fe73b803c3fff7ab3b9b667cfe42", "size": 391, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/rng.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/rng.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/rng.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 17.0, "max_line_length": 52, "alphanum_fraction": 0.6368286445, "num_tokens": 122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.06465348745509981, "lm_q1q2_score": 0.031569224372292794}}
{"text": "/**\n *\n * @file qwrapper_dlaset2.c\n *\n *  PLASMA core_blas quark wrapper\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Hatem Ltaief\n * @date 2010-11-15\n * @generated d Tue Jan  7 11:44:59 2014\n *\n **/\n#include <lapacke.h>\n#include \"common.h\"\n\n/***************************************************************************//**\n *\n **/\nvoid QUARK_CORE_dlaset2(Quark *quark, Quark_Task_Flags *task_flags,\n                       PLASMA_enum uplo, int M, int N,\n                       double alpha, double *A, int LDA)\n{\n    DAG_CORE_LASET;\n    QUARK_Insert_Task(quark, CORE_dlaset2_quark, task_flags,\n        sizeof(PLASMA_enum),                &uplo,  VALUE,\n        sizeof(int),                        &M,     VALUE,\n        sizeof(int),                        &N,     VALUE,\n        sizeof(double),         &alpha, VALUE,\n        sizeof(double)*M*N,     A,      OUTPUT,\n        sizeof(int),                        &LDA,   VALUE,\n        0);\n}\n\n/***************************************************************************//**\n *\n **/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_dlaset2_quark = PCORE_dlaset2_quark\n#define CORE_dlaset2_quark PCORE_dlaset2_quark\n#endif\nvoid CORE_dlaset2_quark(Quark *quark)\n{\n    PLASMA_enum uplo;\n    int M;\n    int N;\n    double alpha;\n    double *A;\n    int LDA;\n\n    quark_unpack_args_6(quark, uplo, M, N, alpha, A, LDA);\n    CORE_dlaset2(uplo, M, N, alpha, A, LDA);\n}\n", "meta": {"hexsha": "e168d5899b17226a649ebabb251435bf422d7343", "size": 1518, "ext": "c", "lang": "C", "max_stars_repo_path": "core_blas-qwrapper/qwrapper_dlaset2.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "core_blas-qwrapper/qwrapper_dlaset2.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "core_blas-qwrapper/qwrapper_dlaset2.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6, "max_line_length": 80, "alphanum_fraction": 0.5204216074, "num_tokens": 414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.06465348520228963, "lm_q1q2_score": 0.03156922327228298}}
{"text": "/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*\n**                                                                                  **\n** This file forms part of the Underworld geophysics modelling application.         **\n**                                                                                  **\n** For full license and copyright information, please refer to the LICENSE.md file  **\n** located at the project root, or contact the authors.                             **\n**                                                                                  **\n**~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/\n#include <petsc.h>\n#include <petscvec.h>\n#include <petscmat.h>\n#include <petscksp.h>\n\n#include \"common-driver-utils.h\"\n\n\n/*\n\nwrites out \n\nfile1\n  1) its, residual, time\n  2) a summary of results\nfile2\n  1) solver configuration\n\n*/\nPetscErrorCode BSSCR_solver_output( KSP ksp, PetscInt monitor_index, const char res_file[], const char solver_conf[] )\n{\n\tPetscViewer v;\n\tMPI_Comm comm;\n\tPetscInt i,nargs;\n\tchar **args;\n\t\n\t\n\tPetscObjectGetComm( (PetscObject)ksp, &comm );\n\tPetscViewerASCIIOpen( comm, res_file, &v );\n\t\n\tBSSCR_GeneratePetscHeader_for_viewer( v );\n        PetscViewerASCIIPrintf( v, \"\\n\");\n\tBSSCR_KSPLogSolve( v, monitor_index, ksp );\n\tBSSCR_BSSCR_KSPLogSolveSummary( v, monitor_index, ksp );\n\t\n\tStg_PetscViewerDestroy(&v );\n\t\n\t//////////////////////////////////////////////////////////\n\t\n\tPetscObjectGetComm( (PetscObject)ksp, &comm );\n\tPetscViewerASCIIOpen( comm, solver_conf, &v );\n\n\t\t\n\tBSSCR_GeneratePetscHeader_for_viewer( v );\n\tPetscViewerASCIIPrintf( v, \"\\n\\nSolver configuration: \\n\");\n\n\tPetscViewerASCIIPrintf( v, \"\\n1) Command line arguments supplied: \\n\");\n\tPetscViewerASCIIPushTab(v);\n        PetscGetArgs( &nargs, &args );\n        for( i=0; i<nargs; i++ ) {\n                PetscViewerASCIIPrintf( v, \"[%d]: %s \\n\", i, args[i] );\n        }\n\tPetscViewerASCIIPopTab(v);\n\n\tPetscViewerASCIIPrintf( v, \"\\n2) Petsc KSPView(): \\n\");\n\tKSPView( ksp, v );\n\t\n\tStg_PetscViewerDestroy(&v );\n\t\n\t\n\tPetscFunctionReturn(0);\n}\n\n\n\n#undef __FUNCT__\n#define __FUNCT__ \"BSSCR_KSPLogConvergenceRate\"\nPetscErrorCode BSSCR_KSPLogConvergenceRate(PetscViewer v,PetscInt monitor_index, KSP ksp)\n{\n\tPetscInt i;\n\tPetscReal *rlog;\n\tPetscLogDouble *log;\n\tPetscInt nits;\n\tPetscReal rho;\n\t\n\t\n\tBSSCR_KSPLogGetResidualTimeHistory(ksp,monitor_index, &nits,&rlog,&log);\n\tPetscViewerASCIIPrintf( v, \"#-----------------------------------------------------------------------------------------------------------------------\\n\");\n\tPetscViewerASCIIPrintf( v, \"# it         |r|              |r_0|               |r|/|r_0|          -log10(r/r0)        rho     |rn|/|r0|^{1/n}        \\n\" );\n\tPetscViewerASCIIPrintf( v, \"#-----------------------------------------------------------------------------------------------------------------------\\n\");\n\trho = 0.0;\n\ti = 0;\n\tPetscViewerASCIIPrintf( v, \"%1.4d %14.12e %14.12e %14.12e %14.12e %14.12e %14.12e\\n\", i, rlog[i],rlog[0],rlog[i]/rlog[0],-log10(rlog[i]/rlog[0]), rho, 0.0 );\n\tfor( i=1; i<nits; i++ ) {\n\t\trho = (-log10(rlog[i]/rlog[0]))-(-log10(rlog[i-1]/rlog[0]));\n\t\tPetscViewerASCIIPrintf( v, \"%1.4d %14.12e %14.12e %14.12e %14.12e %14.12e %14.12e \\n\", \n\t\t\t\ti, rlog[i],rlog[0],rlog[i]/rlog[0],-log10(rlog[i]/rlog[0]), rho, pow(rlog[i]/rlog[0], 1.0/(double)i) );\n\t}\n\t\n\t\n\tPetscFunctionReturn(0);\n}\n", "meta": {"hexsha": "5eada56943e4fd292aa7cad9eedb43b8e855649c", "size": 3421, "ext": "c", "lang": "C", "max_stars_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/solver_output.c", "max_stars_repo_name": "longgangfan/underworld2", "max_stars_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 116.0, "max_stars_repo_stars_event_min_datetime": "2015-09-28T10:30:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T04:12:38.000Z", "max_issues_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/solver_output.c", "max_issues_repo_name": "longgangfan/underworld2", "max_issues_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 561.0, "max_issues_repo_issues_event_min_datetime": "2015-09-29T06:05:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T23:37:29.000Z", "max_forks_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/solver_output.c", "max_forks_repo_name": "longgangfan/underworld2", "max_forks_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 68.0, "max_forks_repo_forks_event_min_datetime": "2015-12-14T21:57:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-25T04:54:26.000Z", "avg_line_length": 33.8712871287, "max_line_length": 158, "alphanum_fraction": 0.5159310143, "num_tokens": 1172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014734858584286, "lm_q2_score": 0.07159119597808575, "lm_q1q2_score": 0.03079476313206304}}
{"text": "/**\n *\n * @file qwrapper_slaswp.c\n *\n *  PLASMA core_blas quark wrapper\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Mathieu Faverge\n * @date 2010-11-15\n * @generated s Tue Jan  7 11:44:58 2014\n *\n **/\n#include <lapacke.h>\n#include \"common.h\"\n\n/***************************************************************************//**\n *\n **/\nvoid QUARK_CORE_slaswp(Quark *quark, Quark_Task_Flags *task_flags,\n                       int n, float *A, int lda,\n                       int i1,  int i2, const int *ipiv, int inc)\n{\n    DAG_CORE_LASWP;\n    QUARK_Insert_Task(\n        quark, CORE_slaswp_quark, task_flags,\n        sizeof(int),                      &n,    VALUE,\n        sizeof(float)*lda*n,  A,        INOUT | LOCALITY,\n        sizeof(int),                      &lda,  VALUE,\n        sizeof(int),                      &i1,   VALUE,\n        sizeof(int),                      &i2,   VALUE,\n        sizeof(int)*n,                     ipiv,     INPUT,\n        sizeof(int),                      &inc,  VALUE,\n        0);\n}\n\n/***************************************************************************//**\n *\n **/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_slaswp_quark = PCORE_slaswp_quark\n#define CORE_slaswp_quark PCORE_slaswp_quark\n#endif\nvoid CORE_slaswp_quark(Quark *quark)\n{\n    int n, lda, i1, i2, inc;\n    int *ipiv;\n    float *A;\n\n    quark_unpack_args_7(quark, n, A, lda, i1, i2, ipiv, inc);\n    LAPACKE_slaswp_work(LAPACK_COL_MAJOR, n, A, lda, i1, i2, ipiv, inc );\n}\n\n/***************************************************************************//**\n *\n **/\nvoid QUARK_CORE_slaswp_f2(Quark *quark, Quark_Task_Flags *task_flags,\n                          int n, float *A, int lda,\n                          int i1,  int i2, const int *ipiv, int inc,\n                          float *fake1, int szefake1, int flag1,\n                          float *fake2, int szefake2, int flag2)\n{\n    DAG_CORE_LASWP;\n    QUARK_Insert_Task(\n        quark, CORE_slaswp_f2_quark, task_flags,\n        sizeof(int),                        &n,     VALUE,\n        sizeof(float)*lda*n,    A,         INOUT | LOCALITY,\n        sizeof(int),                        &lda,   VALUE,\n        sizeof(int),                        &i1,    VALUE,\n        sizeof(int),                        &i2,    VALUE,\n        sizeof(int)*n,                       ipiv,      INPUT,\n        sizeof(int),                        &inc,   VALUE,\n        sizeof(float)*szefake1, fake1,     flag1,\n        sizeof(float)*szefake2, fake2,     flag2,\n        0);\n}\n\n/***************************************************************************//**\n *\n **/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_slaswp_f2_quark = PCORE_slaswp_f2_quark\n#define CORE_slaswp_f2_quark PCORE_slaswp_f2_quark\n#endif\nvoid CORE_slaswp_f2_quark(Quark* quark)\n{\n    int n, lda, i1, i2, inc;\n    int *ipiv;\n    float *A;\n    void *fake1, *fake2;\n\n    quark_unpack_args_9(quark, n, A, lda, i1, i2, ipiv, inc, fake1, fake2);\n    LAPACKE_slaswp_work(LAPACK_COL_MAJOR, n, A, lda, i1, i2, ipiv, inc );\n}\n\n\n/***************************************************************************//**\n *\n **/\nvoid QUARK_CORE_slaswp_ontile(Quark *quark, Quark_Task_Flags *task_flags,\n                              PLASMA_desc descA, float *Aij,\n                              int i1,  int i2, const int *ipiv, int inc, float *fakepanel)\n{\n    DAG_CORE_LASWP;\n    if (fakepanel == Aij) {\n        QUARK_Insert_Task(\n            quark, CORE_slaswp_ontile_quark, task_flags,\n            sizeof(PLASMA_desc),              &descA,     VALUE,\n            sizeof(float)*1,      Aij,           INOUT | LOCALITY,\n            sizeof(int),                      &i1,        VALUE,\n            sizeof(int),                      &i2,        VALUE,\n            sizeof(int)*(i2-i1+1)*abs(inc),   ipiv,           INPUT,\n            sizeof(int),                      &inc,       VALUE,\n            sizeof(float)*1,      fakepanel,     SCRATCH,\n            0);\n    } else {\n        QUARK_Insert_Task(\n            quark, CORE_slaswp_ontile_quark, task_flags,\n            sizeof(PLASMA_desc),              &descA,     VALUE,\n            sizeof(float)*1,      Aij,           INOUT | LOCALITY,\n            sizeof(int),                      &i1,        VALUE,\n            sizeof(int),                      &i2,        VALUE,\n            sizeof(int)*(i2-i1+1)*abs(inc),   ipiv,           INPUT,\n            sizeof(int),                      &inc,       VALUE,\n            sizeof(float)*1,      fakepanel,     INOUT,\n            0);\n    }\n}\n\n/***************************************************************************//**\n *\n **/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_slaswp_ontile_quark = PCORE_slaswp_ontile_quark\n#define CORE_slaswp_ontile_quark PCORE_slaswp_ontile_quark\n#endif\nvoid CORE_slaswp_ontile_quark(Quark *quark)\n{\n    int i1, i2, inc;\n    int *ipiv;\n    float *A, *fake;\n    PLASMA_desc descA;\n\n    quark_unpack_args_7(quark, descA, A, i1, i2, ipiv, inc, fake);\n    CORE_slaswp_ontile(descA, i1, i2, ipiv, inc);\n}\n\n/***************************************************************************//**\n *\n **/\nvoid QUARK_CORE_slaswp_ontile_f2(Quark *quark, Quark_Task_Flags *task_flags,\n                                 PLASMA_desc descA, float *Aij,\n                                 int i1,  int i2, const int *ipiv, int inc,\n                                 float *fake1, int szefake1, int flag1,\n                                 float *fake2, int szefake2, int flag2)\n{\n    DAG_CORE_LASWP;\n    QUARK_Insert_Task(\n        quark, CORE_slaswp_ontile_f2_quark, task_flags,\n        sizeof(PLASMA_desc),                &descA, VALUE,\n        sizeof(float)*1,        Aij,       INOUT | LOCALITY,\n        sizeof(int),                        &i1,    VALUE,\n        sizeof(int),                        &i2,    VALUE,\n        sizeof(int)*(i2-i1+1)*abs(inc),      ipiv,      INPUT,\n        sizeof(int),                        &inc,   VALUE,\n        sizeof(float)*szefake1, fake1, flag1,\n        sizeof(float)*szefake2, fake2, flag2,\n        0);\n}\n\n/***************************************************************************//**\n *\n **/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_slaswp_ontile_f2_quark = PCORE_slaswp_ontile_f2_quark\n#define CORE_slaswp_ontile_f2_quark PCORE_slaswp_ontile_f2_quark\n#endif\nvoid CORE_slaswp_ontile_f2_quark(Quark *quark)\n{\n    int i1, i2, inc;\n    int *ipiv;\n    float *A;\n    PLASMA_desc descA;\n    void *fake1, *fake2;\n\n    quark_unpack_args_8(quark, descA, A, i1, i2, ipiv, inc, fake1, fake2);\n    CORE_slaswp_ontile(descA, i1, i2, ipiv, inc);\n}\n\n/***************************************************************************//**\n *\n **/\nvoid QUARK_CORE_sswptr_ontile(Quark *quark, Quark_Task_Flags *task_flags,\n                              PLASMA_desc descA, float *Aij,\n                              int i1,  int i2, const int *ipiv, int inc,\n                              const float *Akk, int ldak)\n{\n    DAG_CORE_TRSM;\n    QUARK_Insert_Task(\n        quark, CORE_sswptr_ontile_quark, task_flags,\n        sizeof(PLASMA_desc),              &descA, VALUE,\n        sizeof(float)*1,      Aij,       INOUT | LOCALITY,\n        sizeof(int),                      &i1,    VALUE,\n        sizeof(int),                      &i2,    VALUE,\n        sizeof(int)*(i2-i1+1)*abs(inc),    ipiv,      INPUT,\n        sizeof(int),                      &inc,   VALUE,\n        sizeof(float)*ldak,   Akk,       INPUT,\n        sizeof(int),                      &ldak,  VALUE,\n        0);\n}\n\n/***************************************************************************//**\n *\n **/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_sswptr_ontile_quark = PCORE_sswptr_ontile_quark\n#define CORE_sswptr_ontile_quark PCORE_sswptr_ontile_quark\n#endif\nvoid CORE_sswptr_ontile_quark(Quark *quark)\n{\n    int i1, i2, inc, ldak;\n    int *ipiv;\n    float *A, *Akk;\n    PLASMA_desc descA;\n\n    quark_unpack_args_8(quark, descA, A, i1, i2, ipiv, inc, Akk, ldak);\n    CORE_sswptr_ontile(descA, i1, i2, ipiv, inc, Akk, ldak);\n}\n\n/***************************************************************************//**\n *\n **/\nvoid QUARK_CORE_slaswpc_ontile(Quark *quark, Quark_Task_Flags *task_flags,\n                              PLASMA_desc descA, float *Aij,\n                              int i1,  int i2, const int *ipiv, int inc, float *fakepanel)\n{\n    DAG_CORE_LASWP;\n    if (fakepanel == Aij) {\n        QUARK_Insert_Task(\n            quark, CORE_slaswpc_ontile_quark, task_flags,\n            sizeof(PLASMA_desc),              &descA,     VALUE,\n            sizeof(float)*1,      Aij,           INOUT | LOCALITY,\n            sizeof(int),                      &i1,        VALUE,\n            sizeof(int),                      &i2,        VALUE,\n            sizeof(int)*(i2-i1+1)*abs(inc),   ipiv,           INPUT,\n            sizeof(int),                      &inc,       VALUE,\n            sizeof(float)*1,      fakepanel,     SCRATCH,\n            0);\n    } else {\n        QUARK_Insert_Task(\n            quark, CORE_slaswpc_ontile_quark, task_flags,\n            sizeof(PLASMA_desc),              &descA,     VALUE,\n            sizeof(float)*1,      Aij,           INOUT | LOCALITY,\n            sizeof(int),                      &i1,        VALUE,\n            sizeof(int),                      &i2,        VALUE,\n            sizeof(int)*(i2-i1+1)*abs(inc),   ipiv,           INPUT,\n            sizeof(int),                      &inc,       VALUE,\n            sizeof(float)*1,      fakepanel,     INOUT,\n            0);\n    }\n}\n\n/***************************************************************************//**\n *\n **/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_slaswpc_ontile_quark = PCORE_slaswpc_ontile_quark\n#define CORE_slaswpc_ontile_quark PCORE_slaswpc_ontile_quark\n#endif\nvoid CORE_slaswpc_ontile_quark(Quark *quark)\n{\n    int i1, i2, inc;\n    int *ipiv;\n    float *A, *fake;\n    PLASMA_desc descA;\n\n    quark_unpack_args_7(quark, descA, A, i1, i2, ipiv, inc, fake);\n    CORE_slaswpc_ontile(descA, i1, i2, ipiv, inc);\n}\n\n", "meta": {"hexsha": "ccc69716a8e765ede97ecaa30375037557d5b05f", "size": 10133, "ext": "c", "lang": "C", "max_stars_repo_path": "core_blas-qwrapper/qwrapper_slaswp.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "core_blas-qwrapper/qwrapper_slaswp.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "core_blas-qwrapper/qwrapper_slaswp.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.9326241135, "max_line_length": 90, "alphanum_fraction": 0.4739958551, "num_tokens": 2745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4111108548019597, "lm_q2_score": 0.0736962636026705, "lm_q1q2_score": 0.030297333925404416}}
{"text": "/* histogram/test2d_trap.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <gsl/gsl_histogram2d.h>\n#include <gsl/gsl_test.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_ieee_utils.h>\n\n#define N 107\n#define M 239\n\nstatic void my_error_handler (const char *reason, const char *file,\n                              int line, int err);\nstatic int status = 0;\n\nvoid\ntest2d_trap (void)\n{\n  gsl_histogram2d *h;\n  double result, lower, upper;\n  size_t i, j;\n\n  gsl_set_error_handler (&my_error_handler);\n\n  gsl_ieee_env_setup ();\n\n  status = 0;\n  h = gsl_histogram2d_calloc (0, 10);\n  gsl_test (!status, \"gsl_histogram_calloc traps zero-width histogram\");\n  gsl_test (h != 0,\n            \"gsl_histogram2d_calloc returns NULL for zero-width histogram\");\n\n\n  status = 0;\n  h = gsl_histogram2d_calloc (10, 0);\n  gsl_test (!status, \"gsl_histogram_calloc traps zero-length histogram\");\n  gsl_test (h != 0,\n            \"gsl_histogram2d_calloc returns NULL for zero-length histogram\");\n\n\n  status = 0;\n  h = gsl_histogram2d_calloc_uniform (0, 10, 0.0, 1.0, 0.0, 1.0);\n  gsl_test (!status,\n            \"gsl_histogram2d_calloc_uniform traps zero-width histogram\");\n  gsl_test (h != 0,\n    \"gsl_histogram2d_calloc_uniform returns NULL for zero-width histogram\");\n\n  status = 0;\n  h = gsl_histogram2d_calloc_uniform (10, 0, 0.0, 1.0, 0.0, 1.0);\n  gsl_test (!status,\n            \"gsl_histogram2d_calloc_uniform traps zero-length histogram\");\n  gsl_test (h != 0,\n   \"gsl_histogram2d_calloc_uniform returns NULL for zero-length histogram\");\n\n  status = 0;\n  h = gsl_histogram2d_calloc_uniform (10, 10, 0.0, 1.0, 1.0, 1.0);\n  gsl_test (!status,\n            \"gsl_histogram2d_calloc_uniform traps equal endpoints\");\n  gsl_test (h != 0,\n         \"gsl_histogram2d_calloc_uniform returns NULL for equal endpoints\");\n\n  status = 0;\n  h = gsl_histogram2d_calloc_uniform (10, 10, 1.0, 1.0, 0.0, 1.0);\n  gsl_test (!status,\n            \"gsl_histogram2d_calloc_uniform traps equal endpoints\");\n  gsl_test (h != 0,\n         \"gsl_histogram2d_calloc_uniform returns NULL for equal endpoints\");\n\n  status = 0;\n  h = gsl_histogram2d_calloc_uniform (10, 10, 0.0, 1.0, 2.0, 1.0);\n  gsl_test (!status,\n            \"gsl_histogram2d_calloc_uniform traps invalid range\");\n  gsl_test (h != 0,\n            \"gsl_histogram2d_calloc_uniform returns NULL for invalid range\");\n\n  status = 0;\n  h = gsl_histogram2d_calloc_uniform (10, 10, 2.0, 1.0, 0.0, 1.0);\n  gsl_test (!status,\n            \"gsl_histogram2d_calloc_uniform traps invalid range\");\n  gsl_test (h != 0,\n            \"gsl_histogram2d_calloc_uniform returns NULL for invalid range\");\n\n  h = gsl_histogram2d_calloc_uniform (N, M, 0.0, 1.0, 0.0, 1.0);\n\n  status = gsl_histogram2d_accumulate (h, 1.0, 0.0, 10.0);\n  gsl_test (status != GSL_EDOM, \"gsl_histogram2d_accumulate traps x at xmax\");\n\n  status = gsl_histogram2d_accumulate (h, 2.0, 0.0, 100.0);\n  gsl_test (status != GSL_EDOM, \"gsl_histogram2d_accumulate traps x above xmax\");\n\n  status = gsl_histogram2d_accumulate (h, -1.0, 0.0, 1000.0);\n  gsl_test (status != GSL_EDOM, \"gsl_histogram2d_accumulate traps x below xmin\");\n\n  status = gsl_histogram2d_accumulate (h, 0.0, 1.0, 10.0);\n  gsl_test (status != GSL_EDOM, \"gsl_histogram2d_accumulate traps y at ymax\");\n\n  status = gsl_histogram2d_accumulate (h, 0.0, 2.0, 100.0);\n  gsl_test (status != GSL_EDOM, \"gsl_histogram2d_accumulate traps y above ymax\");\n\n  status = gsl_histogram2d_accumulate (h, 0.0, -1.0, 1000.0);\n  gsl_test (status != GSL_EDOM, \"gsl_histogram2d_accumulate traps y below ymin\");\n\n\n  status = gsl_histogram2d_increment (h, 1.0, 0.0);\n  gsl_test (status != GSL_EDOM, \"gsl_histogram2d_increment traps x at xmax\");\n\n  status = gsl_histogram2d_increment (h, 2.0, 0.0);\n  gsl_test (status != GSL_EDOM, \"gsl_histogram2d_increment traps x above xmax\");\n\n  status = gsl_histogram2d_increment (h, -1.0, 0.0);\n  gsl_test (status != GSL_EDOM, \"gsl_histogram2d_increment traps x below xmin\");\n\n\n  status = gsl_histogram2d_increment (h, 0.0, 1.0);\n  gsl_test (status != GSL_EDOM, \"gsl_histogram2d_increment traps y at ymax\");\n\n  status = gsl_histogram2d_increment (h, 0.0, 2.0);\n  gsl_test (status != GSL_EDOM, \"gsl_histogram2d_increment traps y above ymax\");\n\n  status = gsl_histogram2d_increment (h, 0.0, -1.0);\n  gsl_test (status != GSL_EDOM, \"gsl_histogram2d_increment traps y below ymin\");\n\n\n  result = gsl_histogram2d_get (h, N, 0);\n  gsl_test (result != 0, \"gsl_histogram2d_get traps x index at nx\");\n\n  result = gsl_histogram2d_get (h, N + 1, 0);\n  gsl_test (result != 0, \"gsl_histogram2d_get traps x index above nx\");\n\n  result = gsl_histogram2d_get (h, 0, M);\n  gsl_test (result != 0, \"gsl_histogram2d_get traps y index at ny\");\n\n  result = gsl_histogram2d_get (h, 0, M + 1);\n  gsl_test (result != 0, \"gsl_histogram2d_get traps y index above ny\");\n\n\n  status = gsl_histogram2d_get_xrange (h, N, &lower, &upper);\n  gsl_test (status != GSL_EDOM, \"gsl_histogram2d_get_xrange traps index at nx\");\n\n  status = gsl_histogram2d_get_xrange (h, N + 1, &lower, &upper);\n  gsl_test (status != GSL_EDOM, \"gsl_histogram2d_get_xrange traps index above nx\");\n\n  status = gsl_histogram2d_get_yrange (h, M, &lower, &upper);\n  gsl_test (status != GSL_EDOM, \"gsl_histogram2d_get_yrange traps index at ny\");\n\n  status = gsl_histogram2d_get_yrange (h, M + 1, &lower, &upper);\n  gsl_test (status != GSL_EDOM, \"gsl_histogram2d_get_yrange traps index above ny\");\n\n  status = 0;\n  gsl_histogram2d_find (h, -0.01, 0.0, &i, &j);\n  gsl_test (status != GSL_EDOM, \"gsl_histogram2d_find traps x below xmin\");\n\n  status = 0;\n  gsl_histogram2d_find (h, 1.0, 0.0, &i, &j);\n  gsl_test (status != GSL_EDOM, \"gsl_histogram2d_find traps x at xmax\");\n\n  status = 0;\n  gsl_histogram2d_find (h, 1.1, 0.0, &i, &j);\n  gsl_test (status != GSL_EDOM, \"gsl_histogram2d_find traps x above xmax\");\n\n\n  status = 0;\n  gsl_histogram2d_find (h, 0.0, -0.01, &i, &j);\n  gsl_test (status != GSL_EDOM, \"gsl_histogram2d_find traps y below ymin\");\n\n  status = 0;\n  gsl_histogram2d_find (h, 0.0, 1.0, &i, &j);\n  gsl_test (status != GSL_EDOM, \"gsl_histogram2d_find traps y at ymax\");\n\n  status = 0;\n  gsl_histogram2d_find (h, 0.0, 1.1, &i, &j);\n  gsl_test (status != GSL_EDOM, \"gsl_histogram2d_find traps y above ymax\");\n\n  gsl_histogram2d_free (h);\n}\n\n\nstatic void\nmy_error_handler (const char *reason, const char *file, int line, int err)\n{\n  if (0)\n    printf (\"(caught [%s:%d: %s (%d)])\\n\", file, line, reason, err);\n  status = 1;\n}\n", "meta": {"hexsha": "0e2929c17d818ad200bd536cf01d55d6cfe033a8", "size": 7223, "ext": "c", "lang": "C", "max_stars_repo_path": "tests/libs/gsl/tests/histogram/test2d_trap.c", "max_stars_repo_name": "utdsimmons/ohpc", "max_stars_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 692.0, "max_stars_repo_stars_event_min_datetime": "2015-11-12T13:56:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:45:59.000Z", "max_issues_repo_path": "tests/libs/gsl/tests/histogram/test2d_trap.c", "max_issues_repo_name": "utdsimmons/ohpc", "max_issues_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1096.0, "max_issues_repo_issues_event_min_datetime": "2015-11-12T09:08:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:48:41.000Z", "max_forks_repo_path": "tests/libs/gsl/tests/histogram/test2d_trap.c", "max_forks_repo_name": "utdsimmons/ohpc", "max_forks_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 224.0, "max_forks_repo_forks_event_min_datetime": "2015-11-12T21:17:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T00:57:48.000Z", "avg_line_length": 35.4068627451, "max_line_length": 83, "alphanum_fraction": 0.6962480964, "num_tokens": 2335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.06560483974270367, "lm_q1q2_score": 0.030244931925481874}}
{"text": "/* #define _XOPEN_SOURCE 500 */\n#ifndef _FILE_OFFSET_BITS\n#define _FILE_OFFSET_BITS 64\n#endif\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <inttypes.h>\n#include <limits.h>\n\n#ifndef SIZE_MAX\n#define SIZE_MAX (~(size_t)0)\n#endif\n\n#ifdef _OPENMP\n#include <omp.h>\n#endif\n\n/* for open/close and other file io*/\n#include <unistd.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n\n/*for sendfile (in-kernel file to file copy, supposedly very fast) */\n#ifdef USE_SENDFILE\n#include <sys/sendfile.h>\n#endif\n\n#if defined(USE_MMAP)\n#include <sys/mman.h>\n#elif defined(USE_SENDFILE)\n#include <sys/sendfile.h>\n#else\n#endif\n\n\n#ifdef USE_WRITEV\n#ifndef USE_MMAP\n#error USE_MMAP must be enabled with USE_WRITEV\n#endif\n#include <sys/uio.h>\n#endif\n\n#include <gsl/gsl_rng.h>\n\n#include \"macros.h\"\n#include \"utils.h\"\n#include \"progressbar.h\"\n#include \"gadget_utils.h\"\n\n\n/* Copied straight from https://fossies.org/dox/gsl-2.2.1/shuffle_8c_source.html*/\n/* Adapted to generate array indices. The returned random indices are in increasing order */\nint gsl_ran_arr_index (const gsl_rng * r, size_t * dest, const size_t k, const size_t n)\n{\n  /* Choose k out of n items, return an array x[] of the k items.\n      These items will preserve the relative order of the original\n      input -- you can use shuffle() to randomize the output if you\n      wish */\n \n  if (k > n) {\n\tfprintf(stderr,\"k=%zu is greater than n=%zu. Cannot sample more than n items\\n\",\n\t\t\tk, n);\n\treturn EXIT_FAILURE;\n  }\n  if(k == n) {\n\tfor(size_t i=0;i<n;i++) {\n\t  dest[i] = i;\n\t}\n  } else {\n\tsize_t j=0;\n\tfor (size_t i = 0; i < n && j < k; i++) {\n\t  if ((n - i) * gsl_rng_uniform (r) < k - j) {\n\t\tdest[j] = i;\n\t\tj++ ;\n\t  }\n\t}\n  }\n \n  return EXIT_SUCCESS;\n}\n \n\nint write_random_subsample_of_field(int in_fd, int out_fd, off_t in_offset, off_t out_offset, const int dest_npart, const size_t itemsize, size_t *random_indices\n#ifdef USE_MMAP\n\t\t\t\t\t\t\t\t\t,char *in_memblock\n#endif\n)\n{\n#ifdef USE_MMAP\n  in_memblock += in_offset;//These are here so that I don't lose the original pointer from mmap\n#endif\n\n#ifndef USE_MMAP\n  size_t buf[itemsize];\n#endif\n\n  int interrupted=0;\n  \n#ifndef _OPENMP  \n  init_my_progressbar(dest_npart,&interrupted);\n#endif\n  \n#ifdef USE_WRITEV\n  //vector writes. Loop has to be re-written in units of IOV_MAX\n  for(int i=0;i<dest_npart;i+=IOV_MAX) {\n#ifndef _OPENMP        \n      my_progressbar(i,&interrupted);//progress-bar will be jumpy\n#endif      \n      const int nleft = ((dest_npart - i) > IOV_MAX) ? IOV_MAX:(dest_npart - i);\n      struct iovec iov[IOV_MAX];\n      for(int j=0;j<nleft;j++){\n          const size_t ind = random_indices[j];\n          const size_t offset_in_field = ind * itemsize;\n          iov[j].iov_base = in_memblock + offset_in_field;\n          iov[j].iov_len = itemsize;\n      }\n      random_indices += nleft;\n      \n      ssize_t bytes_written = writev(out_fd, iov, nleft);\n      XRETURN(bytes_written == nleft*itemsize, EXIT_FAILURE, \"Expected to write bytes = %zu but wrote %zd instead\\n\",nleft*itemsize, bytes_written);\n  }\n#else  //Not using WRITEV -> 3 options here i) MMAP + write ii) sendfile iii) pread + write\n  for(int i=0;i<dest_npart;i++) {\n#ifndef _OPENMP        \n\tmy_progressbar(i,&interrupted);\n#endif    \n\tconst size_t ind = random_indices[i];\n\tsize_t offset_in_field = ind * itemsize;\n#if defined(USE_MMAP)\n\tssize_t bytes_written = write(out_fd, in_memblock + offset_in_field, itemsize);\n#elif defined(USE_SENDFILE)\n\toff_t input_offset = in_offset + offset_in_field;\n\tssize_t bytes_written = sendfile(out_fd, in_fd, &input_offset, itemsize);\n#else\n\tssize_t bytes_read = pread(in_fd, &buf, itemsize, in_offset + offset_in_field);\n\tXRETURN(bytes_read == itemsize, EXIT_FAILURE, \"Expected to read bytes = %zu but read %zd instead\\n\",itemsize, bytes_read);\n\tssize_t bytes_written = write(out_fd, &buf, itemsize);\n#endif//default case (pread + write)\n\n\tXRETURN(bytes_written == itemsize, EXIT_FAILURE, \"Expected to write bytes = %zu but wrote %zd instead\\n\",itemsize, bytes_written);\n\tout_offset += itemsize;\n  }\n#endif //end of WRITEV\n\n#ifndef _OPENMP    \n  finish_myprogressbar(&interrupted);\n#endif\n  \n  return EXIT_SUCCESS;\n}\n\n\nint subsample_single_gadgetfile(const int dest_npart, const char *inputfile, const char *outputfile, const size_t id_bytes, const gsl_rng *rng, const double fraction, const int64_t nparttotal)\n{\n  if(dest_npart <= 0) {\n\tfprintf(stderr,\"Error: Desired number of particles =%d in the subsampled file must be > 0\\n\",dest_npart);\n\treturn EXIT_FAILURE;\n  }\n  struct timespec tstart, t0, t1;\n  current_utc_time(&tstart);\n\n  int in_fd=-1;\n  int out_fd=-1;\n  int status = EXIT_FAILURE;\n  in_fd = open(inputfile, O_RDONLY);\n  if(in_fd < 0) {\n\tfprintf(stderr,\"Error (in function %s, line # %d) while opening input file = `%s'\\n\",__FUNCTION__,__LINE__,inputfile);\n\tperror(NULL);\n\treturn EXIT_FAILURE;\n  }\n\n#ifdef USE_MMAP\n  struct stat sb;\n  if(fstat(in_fd, &sb) < 0) {\n\tperror(NULL);\n\treturn EXIT_FAILURE;\n  }\n  char *in_memblock = mmap(NULL, sb.st_size, PROT_READ, MAP_SHARED, in_fd, 0);\n#endif\n\n\n  //Check that that the output file does not exist.\n  {\n\tFILE *fp = fopen(outputfile,\"r\");\n\tif(fp != NULL) {\n\t  fclose(fp);\n\t  fprintf(stderr,\"Warning: Output file = `%s' should not exist. \"\n\t\t\t  \"Aborting so as to avoid accidentally over-writing regular fles\\n\",outputfile);\n\t  return EXIT_FAILURE;\n\t}\n  }\n\n  out_fd = open(outputfile, O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR);//set the mode since the file is being created\n  if(out_fd < 0) {\n\tfprintf(stderr,\"Error (in function %s, line # %d) while opening output file = `%s'\\n\",__FUNCTION__,__LINE__, outputfile);\n\tperror(NULL);\n\treturn EXIT_FAILURE;\n  }\n\n  /* Reserve disk-space for dest_npart particles, written as a fortran binary */\n  const size_t pos_vel_itemsize = sizeof(float)*3;\n  const off_t header_disk_size = 4 + sizeof(struct io_header) + 4;  //header\n  const off_t pos_disk_size = 4 + pos_vel_itemsize*dest_npart + 4; //all 3 positions for each particle\n  const off_t vel_disk_size = 4 + pos_vel_itemsize*dest_npart + 4; //all 3 velocities for each particle\n  const off_t id_disk_size = \t4 + id_bytes*dest_npart + 4;//all particle IDs\n  \n  /* These are all of the fields to be written */\n  const off_t outputfile_size = header_disk_size + pos_disk_size + vel_disk_size + id_disk_size;\n\n  status = posix_fallocate(out_fd, 0, outputfile_size);\n  if(status < 0) {\n  \tfprintf(stderr,\"Error: Could not reserve disk space for %d particles (output file: `%s', expected file-size on disk = %zu bytes)\\n\",\n  \t\t\tdest_npart, outputfile, (size_t) outputfile_size);\n  \tperror(NULL);\n  \treturn status;\n  }\n\n\n  struct io_header hdr;\n  int dummy1=0,dummy2=0;\n  const off_t pos_start_offset = header_disk_size + 4;\n  const off_t vel_start_offset = header_disk_size + pos_disk_size + 4;\n  const off_t id_start_offset = header_disk_size + pos_disk_size + vel_disk_size + 4;\n\n  read(in_fd, &dummy1, 4);\n  read(in_fd, &hdr, sizeof(struct io_header));\n  read(in_fd, &dummy2, 4);\n  if(dummy1 != 256 || dummy2 != 256) {\n\tfprintf(stderr,\"Error: Padding bytes for header = %d (front) and %d (end) should be exactly 256\\n\",dummy1, dummy2);\n\treturn EXIT_FAILURE;\n  }\n#ifdef USE_MMAP\n  if(fraction == 1.0) {\n\tXRETURN(dest_npart == hdr.npart[1],EXIT_FAILURE,\n\t\t\t\"for fraction = 1.0, input npart = %d must equal subsampled npart = %d\\n\",hdr.npart[1], dest_npart);\n\t/* XRETURN(sb.st_size == outputfile_size, EXIT_FAILURE, */\n\t/* \t\t\"for fraction = 1.0, input (=%zu bytes) and output file sizes (=%zu bytes) must be the same\",sb.st_size, outputfile_size); */\n  }\n#endif\n\n\n  for(int type=0;type<6;type++) {\n\tif(type==1) {\n\t  continue;\n\t}\n\n\t/* There should only be dark-matter particles */\n\tif(hdr.npart[type] > 0) {\n\t  fprintf(stderr,\"Error: Input file `%s' contains %d particles of type=%d. This code only works for dark-matter only simulations\\n\",\n\t\t\t  inputfile, hdr.npart[type], type);\n\t  return EXIT_FAILURE;\n\t}\n  }\n\n  /* The number of subsampled particles wanted can at most be the numbers present in the file*/\n  if(dest_npart > hdr.npart[1]) {\n\tfprintf(stderr,\"Error: Number of subsampled particles = %d exceeds the number of particles in the file = %d\\n\",\n\t\t\tdest_npart,  hdr.npart[1]);\n\treturn EXIT_FAILURE;\n  }\n\n  struct io_header out_hdr = hdr;\n  out_hdr.npart[1] = dest_npart;\n  out_hdr.npartTotal[1] = nparttotal;\n  out_hdr.npartTotalHighWord[1] = (nparttotal >> 32);\n  out_hdr.mass[1] /= fraction;\n\n  write(out_fd, &dummy1, sizeof(dummy1));\n  write(out_fd, &out_hdr, sizeof(struct io_header));\n  write(out_fd, &dummy2, sizeof(dummy2));\n  \n\n  //create an array of random indices\n  size_t *random_indices = calloc(dest_npart, sizeof(*random_indices));\n  status = gsl_ran_arr_index(rng, random_indices, (size_t) dest_npart, (size_t) hdr.npart[1]);\n\n  //write positions\n  current_utc_time(&t0);\n  int posvel_disk_size=pos_vel_itemsize*dest_npart;\n  write(out_fd, &posvel_disk_size, sizeof(posvel_disk_size));\n  status = write_random_subsample_of_field(in_fd, out_fd, pos_start_offset, -1,dest_npart, pos_vel_itemsize, random_indices\n#ifdef USE_MMAP\n\t\t\t\t\t\t\t\t\t\t\t   ,in_memblock\n#endif\n\t\t\t\t\t\t\t\t\t\t\t   );\n  if(status != EXIT_SUCCESS) {\n\treturn status;\n  }\n  write(out_fd, &posvel_disk_size, sizeof(posvel_disk_size));\n  current_utc_time(&t1);\n  double pos_time = REALTIME_ELAPSED_NS(t0,t1)*1e-9;\n\n  //write velocities\n  write(out_fd, &posvel_disk_size, sizeof(posvel_disk_size));\n  status = write_random_subsample_of_field(in_fd, out_fd, vel_start_offset, -1,dest_npart, pos_vel_itemsize, random_indices\n#ifdef USE_MMAP\n\t\t\t\t\t\t\t\t\t\t\t   ,in_memblock\n#endif\n\t\t\t\t\t\t\t\t\t\t\t   );\n  if(status != EXIT_SUCCESS) {\n\treturn status;\n  }\n  write(out_fd, &posvel_disk_size, sizeof(posvel_disk_size));\n  current_utc_time(&t0);\n  double vel_time = REALTIME_ELAPSED_NS(t1, t0)*1e-9;\n\n\n  //write ids\n  int id_size = id_bytes * dest_npart;\n  write(out_fd, &id_size, sizeof(id_size)); \n  status = write_random_subsample_of_field(in_fd, out_fd, vel_start_offset, -1,dest_npart, id_bytes, random_indices\n#ifdef USE_MMAP\n                                           ,in_memblock\n#endif\n                                           );\n  if(status != EXIT_SUCCESS) {\n\treturn status;\n  }\n  write(out_fd, &id_size, sizeof(id_size));\n  current_utc_time(&t1);\n  double id_time = REALTIME_ELAPSED_NS(t0,t1)*1e-9;\n\n  free(random_indices);\n\n  //close the input file -> we are only reading, unlikely to be error\n  close(in_fd);\n\n#ifdef USE_MMAP\n  munmap(in_memblock, sb.st_size);\n#endif\n\n  //check for error code here since disk quota might be hit\n  status = close(out_fd);\n  if(status != EXIT_SUCCESS){\n\tfprintf(stderr,\"Error while closing output file = `%s'\\n\",outputfile);\n\tperror(NULL);\n\treturn status;\n  }\n  current_utc_time(&t1);\n  /* fprintf(stderr,\"Done with file. Total time taken = %8.4lf seconds (pos_time = %6.3e vel_time = %6.3e id_time = %6.3e seconds)\\n\",REALTIME_ELAPSED_NS(tstart,t1)*1e-9, */\n  /*   \t  pos_time,vel_time,id_time); */\n\n  return EXIT_SUCCESS;\n}\n\n\n\n\nint main(int argc,char **argv) \n{\n  const char argnames[][100]={\"fraction\",\"input file\",\"output file\"};\n  int nargs=sizeof(argnames)/(sizeof(char)*100);\n  char input_filename[MAXLEN];\n  char output_filename[MAXLEN];\n  struct timespec tstart,t0,t1;\n  int64_t nparticles_written=0,nparticles_withmass=0;\n  const gsl_rng_type * rng_type = gsl_rng_ranlxd1;\n  gsl_rng * all_procs_rng = gsl_rng_alloc(rng_type);\n  unsigned long seed = 42;\n  int64_t TotNumPart;\n  current_utc_time(&tstart);\n\n  if (argc != 4 )  {\n\tfprintf(stderr,\"ERROR: %s usage - <fraction>  <gadget snapshot name>  <output filename>\\n\",argv[0]);\n\tfprintf(stderr,\"Each file will be subsampled to get (roughly) that fraction for each particle-type\\n\");\n    fprintf(stderr,\"\\nFound: %d parameters\\n \",argc-1);\n\tint i;\n    for(i=1;i<argc;i++) {\n      if(i <= nargs)\n\t\tfprintf(stderr,\"\\t\\t %s = `%s' \\n\",argnames[i-1],argv[i]);\n      else\n\t\tfprintf(stderr,\"\\t\\t <> = `%s' \\n\",argv[i]);\n    }\n    if(i <= nargs) {\n      fprintf(stderr,\"\\nMissing required parameters: \\n\");\n      for(i=argc;i<=nargs;i++)\n\t\tfprintf(stderr,\"\\t\\t %20s = `?'\\n\",argnames[i-1]);\n    }\n\tfprintf(stderr,\"\\n\\n\");\n    exit(EXIT_FAILURE);\n  }\n\n  double fraction = atof(argv[1]);\n  XRETURN(fraction > 0 && fraction <= 1.0, EXIT_FAILURE, \"Subsample fraction = %lf needs to be in (0,1]\", fraction);\n  strncpy(input_filename,argv[2],MAXLEN);\n  strncpy(output_filename,argv[3],MAXLEN);\n  XRETURN(strncmp(input_filename,output_filename,MAXLEN) != 0, EXIT_FAILURE, \"Input filename = `%s' and output filename = `%s' are the same\",input_filename, output_filename);\n  const int nfiles = get_gadget_nfiles(input_filename);\n  struct io_header header = get_gadget_header(input_filename);\n  TotNumPart = get_Numpart(&header);\n  XRETURN(header.npartTotal[0] == 0 && header.npartTotalHighWord[0]  == 0, EXIT_FAILURE, \"Subsampling will not work with gas particles\");\n\n  fprintf(stderr,\"Running `%s' on %d files with the following parameters \\n\",argv[0],nfiles);\n  fprintf(stderr,\"\\n\\t\\t ---------------------------------------------\\n\");\n  for(int i=1;i<=nargs;i++) {\n\tfprintf(stderr,\"\\t\\t %-25s = %s \\n\",argnames[i-1],argv[i]);\n  }\n#ifdef _OPENMP\n#pragma omp parallel\n  {\n      int nthreads = omp_get_num_threads();\n      int tid = omp_get_thread_num();\n      if(tid == 0)\n          fprintf(stderr,\"\\t\\t %-25s = %d \\n\",\"nthreads\", nthreads);\n  }\n#endif\n  fprintf(stderr,\"\\t\\t ---------------------------------------------\\n\\n\");\n\n  if(SIZE_MAX != 0xFFFFFFFFFFFFFFFF) {\n      fprintf(stderr,\"Error: SIZE_MAX=%zu should be (2^64-1)\\n\", SIZE_MAX);\n      return EXIT_FAILURE;\n  }\n  \n  size_t id_bytes;\n  int interrupted=0;\n  size_t seedtable[nfiles];\n  int64_t nparttotal=0;\n  fprintf(stderr,\"Checking all input files ...\\n\");\n  init_my_progressbar(nfiles, &interrupted);\n  for(int ifile=0;ifile<nfiles;ifile++) {\n      seedtable[ifile] = SIZE_MAX * gsl_rng_uniform(all_procs_rng);\n      char inputfile[MAXLEN];\n      my_snprintf(inputfile,MAXLEN,\"%s.%d\",input_filename, ifile);\n      if(ifile == 0) {\n          id_bytes = get_gadget_id_bytes(inputfile);\n          fprintf(stderr,\"Gadget ID bytes = %zu\\n\",id_bytes);\n          interrupted=1;\n      }\n      struct io_header hdr = get_gadget_header(inputfile);\n      const int dest_npart = fraction * hdr.npart[1];\n      XRETURN((int) (dest_npart*3*sizeof(float))  < INT_MAX, EXIT_FAILURE, \n              \"Padding bytes will overflow, please reduce the value of fraction (currently, fraction = %lf)\\n\",fraction);\n      my_progressbar(ifile,&interrupted);\n      nparttotal += dest_npart;\n  }\n  finish_myprogressbar(&interrupted);\n  fprintf(stderr,\"Checking all input files .....done\\n\\n\");  \n\n  \n  int numdone=0, errorflag=0, savestatus=0;\n  \n  init_my_progressbar(nfiles, &interrupted);\n#ifdef _OPENMP\n#pragma omp parallel shared(numdone, savestatus)\n  {\n      int nthreads = omp_get_num_threads();\n      int tid = omp_get_thread_num();\n#pragma omp for schedule(dynamic)\n#endif      \n      for(int ifile=0;ifile<nfiles;ifile++) {\n          if(errorflag == 0) {\n              //Setup the rng\n              gsl_rng * rng = gsl_rng_alloc(rng_type);\n              gsl_rng_set(rng, seedtable[ifile]);\n\n#ifdef _OPENMP\n#pragma omp atomic\n              numdone++;\n\n              if(tid == 0) \n#endif              \n                  my_progressbar(numdone,&interrupted);\n              \n              char inputfile[MAXLEN],outputfile[MAXLEN];\n              my_snprintf(inputfile,MAXLEN,\"%s.%d\",input_filename,ifile);\n              my_snprintf(outputfile, MAXLEN,\"%s.%d\",output_filename,ifile);\n              struct io_header hdr = get_gadget_header(inputfile);\n              const int dest_npart = fraction * hdr.npart[1];\n              int status = subsample_single_gadgetfile(dest_npart, inputfile, outputfile, id_bytes, rng, fraction, nparttotal);\n              if(status != EXIT_SUCCESS) {\n                  savestatus = status;\n                  errorflag = 1;\n              }\n              gsl_rng_free(rng);\n              \n              /* #ifdef _OPENMP           */\n              /* #pragma omp critical(info) */\n              /*               { */\n              /* #endif */\n              /*                   fprintf(stderr,\"Wrote %d subsampled particles out of %d particles (%d/%d files).\\n\", */\n              /*                           dest_npart, hdr.npart[1], ifile+1,nfiles); */\n              \n              /*                   interrupted=1; */\n              /* #ifdef _OPENMP */\n              /*               }//critical region */\n              /* #endif */\n              \n          }//errorflag == 0 condition\n      }//for loop over nfiles\n      \n#ifdef _OPENMP      \n  }//omp parallel region\n#endif  \n\n  gsl_rng_free(all_procs_rng);\n  finish_myprogressbar(&interrupted);\n\n  if(errorflag != 0) {\n      return savestatus;\n  }\n  \n  current_utc_time(&t1);\n  fprintf(stderr,\"subsample_Gadget> Done. Wrote %\"PRId64\" particles to file `%s'. Time taken = %6.2lf mins\\n\",\n\t\t  nparttotal,output_filename,REALTIME_ELAPSED_NS(tstart, t1)*1e-9/60.0);\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "c1970769ffb1e49c496bab2d42a0c5b165a423bc", "size": 17009, "ext": "c", "lang": "C", "max_stars_repo_path": "main.c", "max_stars_repo_name": "manodeep/subsampleGadget", "max_stars_repo_head_hexsha": "7255a48ba531110bdb55ad34d8749aca7fec3ced", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.c", "max_issues_repo_name": "manodeep/subsampleGadget", "max_issues_repo_head_hexsha": "7255a48ba531110bdb55ad34d8749aca7fec3ced", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.c", "max_forks_repo_name": "manodeep/subsampleGadget", "max_forks_repo_head_hexsha": "7255a48ba531110bdb55ad34d8749aca7fec3ced", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.220703125, "max_line_length": 192, "alphanum_fraction": 0.6632371098, "num_tokens": 4673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713673161914675, "lm_q2_score": 0.0656048392859768, "lm_q1q2_score": 0.02999038180959083}}
{"text": "/*\nGENETIC - A simple genetic algorithm.\n\nCopyright 2014, Javier Burguete Tolosa.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\n\tlist of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice,\n\tthis list of conditions and the following disclaimer in the documentation\n\tand/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``AS IS'' AND ANY EXPRESS\nOR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\nEVENT SHALL Javier Burguete Tolosa OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\nINDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\nBUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\nADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n/**\n * \\file entity.c\n * \\brief Source file to define the entity functions.\n * \\author Javier Burguete Tolosa.\n * \\copyright Copyright 2014 Javier Burguete Tolosa. All rights reserved.\n */\n#define _GNU_SOURCE\n#include <gsl/gsl_rng.h>\n#include <glib.h>\n#include \"entity.h\"\n\n/**\n * Function to create an entity.\n */\nvoid\nentity_new (Entity * entity,    ///< Entity struct.\n            unsigned int genome_nbytes,\n            ///< Number of bytes of the entity genome. \n            unsigned int id)    ///< Identifier number.\n{\n  entity->id = id;\n  // Aligning in 4 bytes\n  entity->nbytes = ((genome_nbytes + 3) / 4) * 4;\n  entity->genome = (char *) g_slice_alloc (entity->nbytes);\n}\n\n/**\n * Function to init randomly the genome of an entity.\n */\nvoid\nentity_init (Entity * entity,   ///< Entity struct.\n             gsl_rng * rng)     ///< GSL random numbers generator.\n{\n  unsigned int i;\n  for (i = 0; i < entity->nbytes; ++i)\n    entity->genome[i] = (char) gsl_rng_uniform_int (rng, 256);\n}\n\n/**\n * Function to free the memory used by an entity.\n */\nvoid\nentity_free (Entity * entity)   ///< Entity struct.\n{\n  g_slice_free1 (entity->nbytes, entity->genome);\n}\n", "meta": {"hexsha": "c13ba5d9ab51c5da03764e72d8ba14c4922c8ea3", "size": 2476, "ext": "c", "lang": "C", "max_stars_repo_path": "3.0.0/entity.c", "max_stars_repo_name": "jburguete/genetic", "max_stars_repo_head_hexsha": "e7b5473412eeb4bdd9d1f724ab555d7329b7156d", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-04-07T07:31:25.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-02T02:31:16.000Z", "max_issues_repo_path": "3.0.0/entity.c", "max_issues_repo_name": "jburguete/genetic", "max_issues_repo_head_hexsha": "e7b5473412eeb4bdd9d1f724ab555d7329b7156d", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3.0.0/entity.c", "max_forks_repo_name": "jburguete/genetic", "max_forks_repo_head_hexsha": "e7b5473412eeb4bdd9d1f724ab555d7329b7156d", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-05-22T08:54:08.000Z", "max_forks_repo_forks_event_max_datetime": "2017-05-22T08:54:08.000Z", "avg_line_length": 33.4594594595, "max_line_length": 79, "alphanum_fraction": 0.7277867528, "num_tokens": 571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926197162523, "lm_q2_score": 0.06656919452604806, "lm_q1q2_score": 0.02991570472046154}}
{"text": "/**\n *\n * @file qwrapper_dlacpy.c\n *\n *  PLASMA core_blas quark wrapper\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Julien Langou\n * @author Henricus Bouwmeester\n * @author Mathieu Faverge\n * @date 2010-11-15\n * @generated d Tue Jan  7 11:44:56 2014\n *\n **/\n#include <lapacke.h>\n#include \"common.h\"\n\n/***************************************************************************//**\n *\n **/\nvoid QUARK_CORE_dlacpy(Quark *quark, Quark_Task_Flags *task_flags,\n                       PLASMA_enum uplo, int m, int n, int nb,\n                       const double *A, int lda,\n                       double *B, int ldb)\n{\n    DAG_CORE_LACPY;\n    QUARK_Insert_Task(quark, CORE_dlacpy_quark, task_flags,\n        sizeof(PLASMA_enum),                &uplo,  VALUE,\n        sizeof(int),                        &m,     VALUE,\n        sizeof(int),                        &n,     VALUE,\n        sizeof(double)*nb*nb,    A,             INPUT,\n        sizeof(int),                        &lda,   VALUE,\n        sizeof(double)*nb*nb,    B,             OUTPUT,\n        sizeof(int),                        &ldb,   VALUE,\n        0);\n}\n\n/***************************************************************************//**\n *\n **/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_dlacpy_quark = PCORE_dlacpy_quark\n#define CORE_dlacpy_quark PCORE_dlacpy_quark\n#endif\nvoid CORE_dlacpy_quark(Quark *quark)\n{\n    PLASMA_enum uplo;\n    int M;\n    int N;\n    const double *A;\n    int LDA;\n    double *B;\n    int LDB;\n\n    quark_unpack_args_7(quark, uplo, M, N, A, LDA, B, LDB);\n    LAPACKE_dlacpy_work(\n        LAPACK_COL_MAJOR,\n        lapack_const(uplo),\n        M, N, A, LDA, B, LDB);\n}\n\n/***************************************************************************//**\n *\n **/\nvoid QUARK_CORE_dlacpy_f1(Quark *quark, Quark_Task_Flags *task_flags,\n                          PLASMA_enum uplo, int m, int n, int nb,\n                          const double *A, int lda,\n                          double *B, int ldb,\n                          double *fake1, int szefake1, int flag1)\n{\n    DAG_CORE_LACPY;\n    if ( fake1 == B ) {\n        QUARK_Insert_Task(quark, CORE_dlacpy_quark, task_flags,\n            sizeof(PLASMA_enum),                &uplo,  VALUE,\n            sizeof(int),                        &m,     VALUE,\n            sizeof(int),                        &n,     VALUE,\n            sizeof(double)*nb*nb,    A,             INPUT,\n            sizeof(int),                        &lda,   VALUE,\n            sizeof(double)*nb*nb,    B,             OUTPUT | flag1,\n            sizeof(int),                        &ldb,   VALUE,\n            0);\n    }\n    else {\n        QUARK_Insert_Task(quark, CORE_dlacpy_f1_quark, task_flags,\n            sizeof(PLASMA_enum),                &uplo,  VALUE,\n            sizeof(int),                        &m,     VALUE,\n            sizeof(int),                        &n,     VALUE,\n            sizeof(double)*nb*nb,    A,             INPUT,\n            sizeof(int),                        &lda,   VALUE,\n            sizeof(double)*nb*nb,    B,             OUTPUT,\n            sizeof(int),                        &ldb,   VALUE,\n            sizeof(double)*szefake1, fake1,         flag1,\n            0);\n    }\n}\n\n/***************************************************************************//**\n *\n **/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_dlacpy_f1_quark = PCORE_dlacpy_f1_quark\n#define CORE_dlacpy_f1_quark PCORE_dlacpy_f1_quark\n#endif\nvoid CORE_dlacpy_f1_quark(Quark *quark)\n{\n    PLASMA_enum uplo;\n    int M;\n    int N;\n    const double *A;\n    int LDA;\n    double *B;\n    int LDB;\n    void *fake1;\n\n    quark_unpack_args_8(quark, uplo, M, N, A, LDA, B, LDB, fake1);\n    LAPACKE_dlacpy_work(\n        LAPACK_COL_MAJOR,\n        lapack_const(uplo),\n        M, N, A, LDA, B, LDB);\n}\n\n", "meta": {"hexsha": "5bcbbef2e38a62b00643d16958e1ed6a1f6e4a41", "size": 3911, "ext": "c", "lang": "C", "max_stars_repo_path": "core_blas-qwrapper/qwrapper_dlacpy.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "core_blas-qwrapper/qwrapper_dlacpy.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "core_blas-qwrapper/qwrapper_dlacpy.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5403225806, "max_line_length": 80, "alphanum_fraction": 0.4630529276, "num_tokens": 1015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926492132671, "lm_q2_score": 0.06656918202606929, "lm_q1q2_score": 0.029915701066655483}}
{"text": "// Copyright 2018 Jeremy Mason\n//\n// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or\n// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or\n// http://opensource.org/licenses/MIT>, at your option. This file may not be\n// copied, modified, or distributed except according to those terms.\n\n//! \\file matrix.c\n//! Contains functions to manipulate matrices. Intended as a relatively less\n//! painful wrapper around Level 2 and 3 CBLAS. Column-major order is likely\n//! slightly faster than row-major order because of the underlying FORTRAN \n//! routines.\n\n#include <cblas.h>      // daxpy\n#include <math.h>       // exp\n#include <stdbool.h>    // bool\n#include <stddef.h>     // size_t\n#include <stdio.h>      // EOF\n#include <stdlib.h>     // abort\n#include <string.h>     // memcpy\n#include \"sb_structs.h\" // sb_mat\n#include \"sb_matrix.h\"\n#include \"sb_utility.h\" // SB_CHK_ERR\n#include \"sb_vector.h\"  // sb_vec_is_finite\n#include \"safety.h\"\n\n/// Constructs a matrix with the required capacity.\n///\n/// # Parameters\n/// - `n_rows`: number of rows of the matrix\n/// - `n_cols`: number of columns of the matrix\n///\n/// # Returns\n/// A `sb_mat` pointer to the allocated matrix, or `NULL` if the allocation\n/// fails\n/// \n/// # Examples\n/// ```\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   sb_mat * A = sb_mat_malloc(3, 3);\n///\n///   // Fill the matrix with some values and print\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.};\n///   sb_mat_subcpy(A, 0, a, 9);\n///   sb_mat_print(A, \"A: \", \"%g\");\n///\n///   SB_MAT_FREE_ALL(A);\n/// }\n/// ```\nsb_mat * sb_mat_malloc(size_t n_rows, size_t n_cols) {\n  sb_mat * out = malloc(sizeof(sb_mat));\n  SB_CHK_ERR(!out, return NULL, \"sb_mat_malloc: failed to allocate matrix\");\n\n  size_t n_elem = n_rows * n_cols;\n\n  double * data = malloc(n_elem * sizeof(double));\n  SB_CHK_ERR(!data, free(out); return NULL,\n      \"sb_mat_malloc: failed to allocate data\");\n\n  out->n_rows = n_rows;\n  out->n_cols = n_cols;\n  out->n_elem = n_elem;\n  out->data   = data;\n\n  return out;\n}\n\n/// Constructs a matrix with the required capacity and initializes all elements\n/// to zero. Requires support for the IEC 60559 standard.\n///\n/// # Parameters\n/// - `n_rows`: number of rows of the matrix\n/// - `n_cols`: number of columns of the matrix\n///\n/// # Returns\n/// A `sb_mat` pointer to the allocated matrix, or `NULL` if the allocation\n/// fails\n/// \n/// # Examples\n/// ```\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   sb_mat * A = sb_mat_calloc(3, 3);\n///\n///   // Initialized to zeros\n///   sb_mat_print(A, \"A before: \", \"%g\");\n///\n///   // Fill the matrix with some values and print\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.};\n///   sb_mat_subcpy(A, 0, a, 9);\n///   sb_mat_print(A, \"A after: \", \"%g\");\n///\n///   SB_MAT_FREE_ALL(A);\n/// }\n/// ```\nsb_mat * sb_mat_calloc(size_t n_rows, size_t n_cols) {\n  sb_mat * out = malloc(sizeof(sb_mat));\n  SB_CHK_ERR(!out, return NULL, \"sb_mat_calloc: failed to allocate matrix\");\n\n  size_t n_elem = n_rows * n_cols;\n\n  double * data = calloc(n_elem, sizeof(double));\n  SB_CHK_ERR(!data, free(out); return NULL,\n      \"sb_mat_calloc: failed to allocate data\");\n\n  out->n_rows = n_rows;\n  out->n_cols = n_cols;\n  out->n_elem = n_elem;\n  out->data   = data;\n\n  return out;\n}\n\n/// Constructs a matrix with the required capacity and initializes elements to\n/// the first `n_rows * n_cols` elements of array `a`. The array must contain\n/// at least `n_rows * n_cols` elements.\n///\n/// # Parameters\n/// - `a`: array to be copied into the matrix\n/// - `n_rows`: number of rows of the matrix\n/// - `n_cols`: number of columns of the matrix\n///\n/// # Returns\n/// A `sb_mat` pointer to the allocated matrix, or `NULL` if the allocation\n/// fails\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `a` is not `NULL`\n/// \n/// # Examples\n/// ```\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.};\n/// \n///   // Construct a matrix from the array\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n///   sb_mat_print(A, \"A: \", \"%g\");\n///\n///   SB_MAT_FREE_ALL(A);\n/// }\n/// ```\nsb_mat * sb_mat_of_arr(const double * a, size_t n_rows, size_t n_cols) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!a, abort(), \"sb_mat_of_arr: a cannot be NULL\");\n#endif\n  sb_mat * out = malloc(sizeof(sb_mat));\n  SB_CHK_ERR(!out, return NULL, \"sb_mat_of_arr: failed to allocate matrix\");\n\n  size_t n_elem = n_rows * n_cols;\n\n  double * data = malloc(n_elem * sizeof(double));\n  SB_CHK_ERR(!data, free(out); return NULL,\n      \"sb_mat_of_arr: failed to allocate data\");\n\n  out->n_rows = n_rows;\n  out->n_cols = n_cols;\n  out->n_elem = n_elem;\n  out->data   = memcpy(data, a, n_elem * sizeof(double));\n\n  return out;\n}\n\n/// Constructs a matrix as a deep copy of an existing matrix. The state of the\n/// existing matrix must be valid.\n///\n/// # Parameters\n/// - `A`: pointer to the matrix to be copied\n///\n/// # Returns\n/// A `sb_mat` pointer to the allocated matrix, or `NULL` if the allocation\n/// fails\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `A` is not `NULL`\n///\n/// # Examples\n/// ```\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.};\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n/// \n///   // `A` and `B` contain the same elements\n///   sb_mat_c * B = sb_mat_clone(A);\n///   sb_mat_print(B, \"B before: \", \"%g\");\n///\n///   // Fill `B` with some values and print\n///   sb_mat_subcpy(B, 0, a + 1, 3);\n///   sb_mat_print(B, \"B after: \", \"%g\");\n///\n///   // `A` is unchanged\n///   sb_mat_print(A, \"A after: \", \"%g\");\n///\n///   SB_MAT_FREE_ALL(A, B);\n/// }\n/// ```\nsb_mat * sb_mat_clone(const sb_mat * A) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_clone: A cannot be NULL\");\n#endif\n  sb_mat * out = malloc(sizeof(sb_mat));\n  SB_CHK_ERR(!out, return NULL, \"sb_mat_clone: failed to allocate matrix\");\n\n  size_t n_elem = A->n_elem;\n\n  double * data = malloc(n_elem * sizeof(double));\n  SB_CHK_ERR(!data, free(out); return NULL,\n      \"sb_mat_clone: failed to allocate data\");\n\n  *out = *A;\n  out->data = memcpy(data, A->data, n_elem * sizeof(double));\n\n  return out;\n}\n\n/// Deconstructs a matrix.\n///\n/// # Parameters\n/// - `A`: pointer to the matrix\n///\n/// # Returns\n/// No return value\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `A` is not `NULL`\n///\n/// # Examples\n/// ```\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.};\n/// \n///   // Allocates a pointer to mat\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n///   sb_mat_print(A, \"A: \", \"%g\");\n///\n///   sb_mat_free(A);\n///   // Pointer to `A` is now invalid\n/// }\n/// ```\nvoid sb_mat_free(sb_mat * A) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_free: A cannot be NULL\");\n#endif\n  free(A->data);\n  free(A);\n}\n\n/// Sets all elements of `A` to zero. Requires support for the IEC 60559\n/// standard.\n///\n/// # Parameters\n/// - `A`: pointer to the matrix\n///\n/// # Returns\n/// A copy of `A`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `A` is not `NULL`\n///\n/// # Examples\n/// ```\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.};\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n///   \n///   // Set all elements to zero\n///   sb_mat_print(A, \"A before: \", \"%g\");\n///   sb_mat_set_zero(A);\n///   sb_mat_print(A, \"A after: \", \"%g\");\n///\n///   SB_MAT_FREE_ALL(A);\n/// }\n/// ```\nsb_mat * sb_mat_set_zero(sb_mat * A) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_set_zero: A cannot be NULL\");\n#endif\n  return memset(A->data, 0, A->n_elem * sizeof(double));\n}\n\n/// Sets all elements of `A` to `x`.\n///\n/// # Parameters\n/// - `A`: pointer to the matrix\n/// - `x`: value for the elements\n///\n/// # Returns\n/// A copy of `A`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `A` is not `NULL`\n///\n/// # Examples\n/// ```\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.};\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n///   \n///   // Set all elements to 8.\n///   sb_mat_print(A, \"A before: \", \"%g\");\n///   sb_mat_set_all(A, 8.);\n///   sb_mat_print(A, \"A after: \", \"%g\");\n///\n///   SB_MAT_FREE_ALL(A);\n/// }\n/// ```\nsb_mat * sb_mat_set_all(sb_mat * A, double x) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_set_all: A cannot be NULL\");\n#endif\n  double * data = A->data;\n  for (size_t a = 0; a < A->n_elem; ++a) {\n    data[a] = x;\n  }\n  return A;\n}\n\n/// Sets all elements of `A` to zero, except for elements on the main diagonal\n/// which are set to one. `A` must be a square matrix. Requires support for the\n/// IEC 60559 standard.\n///\n/// # Parameters\n/// - `A`: pointer to the matrix\n///\n/// # Returns\n/// A copy of `A`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `A` is not `NULL`\n/// - `SAFE_LENGTH`: `A` is a square matrix\n///\n/// # Examples\n/// ```\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.};\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n///   \n///   // Set `A` to the identity\n///   sb_mat_print(A, \"A before: \", \"%g\");\n///   sb_mat_set_ident(A);\n///   sb_mat_print(A, \"A after: \", \"%g\");\n///\n///   SB_MAT_FREE_ALL(A);\n/// }\n/// ```\nsb_mat * sb_mat_set_ident(sb_mat * A) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_set_ident: A cannot be NULL\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(A->n_rows != A->n_cols, abort(),\n      \"sb_mat_set_ident: A must be square\");\n#endif\n  double * data = A->data;\n  size_t n_elem = A->n_elem;\n\n  memset(data, 0, n_elem * sizeof(double));\n  for (size_t a = 0; a < n_elem; a += A->n_rows + 1) {\n    data[a] = 1.;\n  }\n\n  return A;\n}\n\n/// Copies the `i`th row of the matrix `A` into the row vector `v`. `v` and `A`\n/// must not overlap in memory.\n///\n/// # Parameters\n/// - `v`: pointer to the vector\n/// - `A`: pointer to the matrix\n/// - `i`: index of the row to be copied\n///\n/// # Returns\n/// A copy of `v`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` and `A` are not `NULL`\n/// - `SAFE_LAYOUT`: `v` is a row vector\n/// - `SAFE_LENGTH`: `v` and `A` have the same number of columns and `i` is a\n///                  valid row index\n///\n/// # Examples\n/// ```\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.};\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n///   sb_vec * v = sb_vec_malloc(3, 'r');\n/// \n///   // Set v to the first row\n///   sb_mat_print(A, \"A: \", \"%g\");\n///   sb_mat_get_row(v, A, 1);\n///   sb_vec_print(v, \"v: \", \"%g\");\n///\n///   SB_MAT_FREE_ALL(A);\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\nsb_vec * sb_mat_get_row(sb_vec * restrict v, const sb_mat * restrict A, size_t i) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_mat_get_row: v cannot be NULL\");\n  SB_CHK_ERR(!A, abort(), \"sb_mat_get_row: A cannot be NULL\");\n#endif\n#ifdef SAFE_LAYOUT\n  SB_CHK_ERR(v->layout != 'r', abort(), \"sb_mat_get_row: v must be a row vector\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(v->n_elem != A->n_cols, abort(),\n      \"sb_mat_get_row: v and A must have same number of columns\");\n  SB_CHK_ERR(i >= A->n_rows, abort(),\n      \"sb_mat_get_row: invalid row index\");\n#endif\n  cblas_dcopy(A->n_cols, A->data + i, A->n_rows, v->data, 1);\n  return v;\n}\n\n/// Copies the `i`th column of the matrix `A` into the column vector `v`. `v`\n/// and `A` must not overlap in memory.\n///\n/// # Parameters\n/// - `v`: pointer to the vector\n/// - `A`: pointer to the matrix\n/// - `j`: index of the column to be copied\n///\n/// # Returns\n/// A copy of `v`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` and `A` are not `NULL`\n/// - `SAFE_LAYOUT`: `v` is a column vector\n/// - `SAFE_LENGTH`: `v` and `A` have the same number of rows and `j` is a\n///                  valid row index\n///\n/// # Examples\n/// ```\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.};\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n///   sb_vec * v = sb_vec_malloc(3, 'c');\n/// \n///   // Set v to the first column\n///   sb_mat_print(A, \"A: \", \"%g\");\n///   sb_mat_get_col(v, A, 1);\n///   sb_vec_print(v, \"v: \", \"%g\");\n///\n///   SB_MAT_FREE_ALL(A);\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\nsb_vec * sb_mat_get_col(sb_vec * restrict v, const sb_mat * restrict A, size_t j) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_mat_get_col: v cannot be NULL\");\n  SB_CHK_ERR(!A, abort(), \"sb_mat_get_col: A cannot be NULL\");\n#endif\n#ifdef SAFE_LAYOUT\n  SB_CHK_ERR(v->layout != 'c', abort(), \"sb_mat_get_col: v must be a column vector\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(v->n_elem != A->n_rows, abort(),\n      \"sb_mat_get_col: v and A must have same number of rows\");\n  SB_CHK_ERR(j >= A->n_cols, abort(),\n      \"sb_mat_get_col: invalid column index\");\n#endif\n  size_t n_rows = A->n_rows;\n  memcpy(v->data, A->data + j * n_rows, n_rows * sizeof(double));\n  return v;\n}\n\n/// Copies the diagonal of the matrix `A` into the vector `v`. `A` must be a\n/// square matrix, and `v` and `A` must not overlap in memory.\n///\n/// # Parameters\n/// - `v`: pointer to the vector\n/// - `A`: pointer to the matrix\n///\n/// # Returns\n/// A copy of `v`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` and `A` are not `NULL`\n/// - `SAFE_LENGTH`: `A` is square, and the number of elements in `v` is the\n///                  same as the number of rows in `A`\n///\n/// # Examples\n/// ```\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.};\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n///   sb_vec * v = sb_vec_malloc(3, 'c');\n/// \n///   // Set v to the main diagonal\n///   sb_mat_print(A, \"A: \", \"%g\");\n///   sb_mat_get_diag(v, A);\n///   sb_vec_print(v, \"v: \", \"%g\");\n///\n///   SB_MAT_FREE_ALL(A);\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\nsb_vec * sb_mat_get_diag(sb_vec * restrict v, const sb_mat * restrict A) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_mat_get_diag: v cannot be NULL\");\n  SB_CHK_ERR(!A, abort(), \"sb_mat_get_diag: A cannot be NULL\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(A->n_rows != A->n_cols, abort(),\n      \"sb_mat_get_diag: A must be square\");\n  SB_CHK_ERR(v->n_elem != A->n_rows, abort(),\n      \"sb_mat_get_diag: number of elements in v should equal number of rows of A\");\n#endif\n  size_t n_rows = A->n_rows;\n  cblas_dcopy(n_rows, A->data, n_rows + 1, v->data, 1);\n  return v;\n}\n\n/// Copies the row vector `v` into the `i`th row of the matrix `A`. `v` and `A`\n/// must not overlap in memory.\n///\n/// # Parameters\n/// - `A`: pointer to the matrix\n/// - `i`: index of the row to be written\n/// - `v`: pointer to the vector\n///\n/// # Returns\n/// A copy of `A`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` and `A` are not `NULL`\n/// - `SAFE_LAYOUT`: `v` is a row vector\n/// - `SAFE_LENGTH`: `v` and `A` have the same number of columns and `i` is a\n///                  valid row index\n///\n/// # Examples\n/// ```\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.};\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n///   sb_vec * v = sb_vec_of_arr(a + 2, 3, 'r');\n/// \n///   // Set the first row to v\n///   sb_mat_print(A, \"A before: \", \"%g\");\n///   sb_vec_print(v, \"v: \", \"%g\");\n///   sb_mat_set_row(A, 1, v);\n///   sb_mat_print(A, \"A after: \", \"%g\");\n///\n///   SB_MAT_FREE_ALL(A);\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\nsb_mat * sb_mat_set_row(sb_mat * restrict A, size_t i, const sb_vec * restrict v) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_set_row: A cannot be NULL\");\n  SB_CHK_ERR(!v, abort(), \"sb_mat_set_row: v cannot be NULL\");\n#endif\n#ifdef SAFE_LAYOUT\n  SB_CHK_ERR(v->layout != 'r', abort(), \"sb_mat_set_row: v must be a row vector\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(v->n_elem != A->n_cols, abort(),\n      \"sb_mat_set_row: v and A must have same number of columns\");\n  SB_CHK_ERR(i >= A->n_rows, abort(),\n      \"sb_mat_set_row: invalid row index\");\n#endif\n  cblas_dcopy(A->n_cols, v->data, 1, A->data + i, A->n_rows);\n  return A;\n}\n\n/// Copies the column vector `v` into the `i`th column of the matrix `A`. `v`\n/// and `A` must not overlap in memory.\n///\n/// # Parameters\n/// - `A`: pointer to the matrix\n/// - `j`: index of the column to be written\n/// - `v`: pointer to the vector\n///\n/// # Returns\n/// A copy of `v`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` and `A` are not `NULL`\n/// - `SAFE_LAYOUT`: `v` is a column vector\n/// - `SAFE_LENGTH`: `v` and `A` have the same number of rows and `j` is a\n///                  valid row index\n///\n/// # Examples\n/// ```\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.};\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n///   sb_vec * v = sb_vec_of_arr(a + 2, 3, 'c');\n/// \n///   // Set the first column to v\n///   sb_mat_print(A, \"A before: \", \"%g\");\n///   sb_vec_print(v, \"v: \", \"%g\");\n///   sb_mat_set_col(A, 1, v);\n///   sb_mat_print(A, \"A after: \", \"%g\");\n///\n///   SB_MAT_FREE_ALL(A);\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\nsb_mat * sb_mat_set_col(sb_mat * restrict A, size_t j, const sb_vec * restrict v) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_set_col: A cannot be NULL\");\n  SB_CHK_ERR(!v, abort(), \"sb_mat_set_col: v cannot be NULL\");\n#endif\n#ifdef SAFE_LAYOUT\n  SB_CHK_ERR(v->layout != 'c', abort(), \"sb_mat_set_col: v must be a column vector\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(v->n_elem != A->n_rows, abort(),\n      \"sb_mat_set_col: v and A must have same number of rows\");\n  SB_CHK_ERR(j >= A->n_cols, abort(),\n      \"sb_mat_set_col: invalid column index\");\n#endif\n  size_t n_rows = A->n_rows;\n  memcpy(A->data + j * n_rows, v->data, n_rows * sizeof(double));\n  return A;\n}\n\n/// Copies the vector `v` into the diagonal of the matrix `A`. `A` must be a\n/// square matrix, and `v` and `A` must not overlap in memory.\n///\n/// # Parameters\n/// - `v`: pointer to the vector\n/// - `A`: pointer to the matrix\n///\n/// # Returns\n/// A copy of `v`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` and `A` are not `NULL`\n/// - `SAFE_LENGTH`: `A` is square, and the number of elements in `v` is the\n///                  same as the number of rows in `A`\n///\n/// # Examples\n/// ```\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.};\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n///   sb_vec * v = sb_vec_of_arr(a + 2, 3, 'c');\n/// \n///   // Set the main diagonal to v\n///   sb_mat_print(A, \"A before: \", \"%g\");\n///   sb_vec_print(v, \"v: \", \"%g\");\n///   sb_mat_set_diag(A, v);\n///   sb_mat_print(A, \"A after: \", \"%g\");\n///\n///   SB_MAT_FREE_ALL(A);\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\nsb_mat * sb_mat_set_diag(sb_mat * restrict A, const sb_vec * restrict v) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_get_diag: A cannot be NULL\");\n  SB_CHK_ERR(!v, abort(), \"sb_mat_get_diag: v cannot be NULL\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(A->n_rows != A->n_cols, abort(),\n      \"sb_mat_get_diag: A must be square\");\n  SB_CHK_ERR(v->n_elem != A->n_rows, abort(),\n      \"sb_mat_get_diag: number of elements in v should equal number of rows of A\");\n#endif\n  size_t n_rows = A->n_rows;\n  cblas_dcopy(n_rows, v->data, 1, A->data, n_rows + 1);\n  return A;\n}\n\n/// Copies contents of the `src` matrix into the `dest` matrix. `src` and `dest`\n/// must have the same number of rows and columns and not overlap in memory.\n///\n/// # Parameters\n/// - `dest`: pointer to destination matrix\n/// - `src`: const pointer to source matrix\n///\n/// # Returns\n/// A copy of `dest`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `src` and `dest` are not `NULL`\n/// - `SAFE_LENGTH`: `src` and `dest` have same number of rows and columns\n///\n/// # Examples\n/// ```\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2., 8.};\n///   sb_mat * A = sb_mat_of_arr(a,     3, 3);\n///   sb_mat * B = sb_mat_of_arr(a + 1, 3, 3);\n///\n///   // Overwrite elements of `A` and print\n///   sb_mat_print(A, \"A before: \", \"%g\");\n///   sb_mat_print(B, \"B before: \", \"%g\");\n///   sb_mat_memcpy(A, B);\n///   sb_mat_print(A, \"A after: \", \"%g\");\n///   sb_mat_print(B, \"B after: \", \"%g\");\n///\n///   SB_MAT_FREE_ALL(A, B);\n/// }\n/// ```\nsb_mat * sb_mat_memcpy(sb_mat * restrict dest, const sb_mat * restrict src) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!dest, abort(), \"sb_mat_memcpy: dest cannot be NULL\");\n  SB_CHK_ERR(!src, abort(), \"sb_mat_memcpy: src cannot be NULL\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(dest->n_rows != src->n_rows, abort(),\n      \"sb_mat_memcpy: dest and src must have same number of rows\");\n  SB_CHK_ERR(dest->n_cols != src->n_cols, abort(),\n      \"sb_mat_memcpy: dest and src must have same number of columns\");\n#endif\n  memcpy(dest->data, src->data, src->n_elem * sizeof(double));\n  return dest;\n}\n\n/// Copies `n` elements of array `a` into the memory of matrix `A` starting at\n/// index `i`. `A` must have enough capacity, `a` must contain at least `n`\n/// elements, and `A` and `a` must not overlap in memory.\n///\n/// # Parameters\n/// - `A`: pointer to destination matrix\n/// - `i`: index of `A` where the copy will start\n/// - `a`: pointer to elements that will be copied\n/// - `n`: number of elements to copy\n///\n/// # Returns\n/// A copy of `A`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `A` and `a` are not `NULL`\n/// - `SAFE_LENGTH`: `A` has enough capacity\n///\n/// # Examples\n/// ```\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.};\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n///\n///   // Overwrite elements of `A` and print\n///   sb_mat_print(A, \"A before: \", \"%g\");\n///   sb_mat_subcpy(A, 0, a + 1, 3);\n///   sb_mat_print(A, \"A after: \", \"%g\");\n///\n///   SB_MAT_FREE_ALL(A);\n/// }\n/// ```\nsb_mat * sb_mat_subcpy(\n    sb_mat * restrict A,\n    size_t i,\n    const double * restrict a,\n    size_t n) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_subcpy: A cannot be NULL\");\n  SB_CHK_ERR(!a, abort(), \"sb_mat_subcpy: a cannot be NULL\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(A->n_elem - i < n, abort(),\n      \"sb_mat_subcpy: A does not have enough capacity\");\n#endif\n  memcpy(A->data + i, a, n * sizeof(double));\n  return A;\n}\n\n/// Swaps the contents of `A` and `B` by exchanging data pointers. Matrices must\n/// have the same number of rows and columns and not overlap in memory.\n///\n/// # Parameters\n/// - `A`: pointer to the first matrix\n/// - `B`: pointer to the second matrix\n///\n/// # Returns\n/// No return value\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `A` and `B` are not `NULL`\n/// - `SAFE_LENGTH`: `A` and `B` have the same numbers of rows and columns\n///\n/// # Examples\n/// ```\n/// #include \"matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2., 8.};\n///   sb_mat * A = sb_mat_of_arr(a,     3, 3);\n///   sb_mat * B = sb_mat_of_arr(a + 1, 3, 3);\n/// \n///   // Print matrices before and after\n///   sb_mat_print(A, \"A before: \", \"%g\");\n///   sb_mat_print(B, \"B before: \", \"%g\");\n///\n///   sb_mat_swap(A, B);\n///\n///   sb_mat_print(A, \"A after: \", \"%g\");\n///   sb_mat_print(B, \"B after: \", \"%g\");\n///\n///   SB_MAT_FREE_ALL(A, B);\n/// }\n/// ```\nvoid sb_mat_swap(sb_mat * restrict A, sb_mat * restrict B) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_swap: A cannot be NULL\");\n  SB_CHK_ERR(!B, abort(), \"sb_mat_swap: B cannot be NULL\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(A->n_rows != B->n_rows, abort(),\n      \"sb_mat_swap: A and B must have same number of rows\");\n  SB_CHK_ERR(A->n_cols != B->n_cols, abort(),\n      \"sb_mat_swap: A and B must have same number of columns\");\n#endif\n  double * scratch;\n  SB_SWAP(A->data, B->data, scratch);\n}\n\n/// Swaps the `i`th and `j`th rows of the matrix `A`.\n///\n/// # Parameters\n/// - `A`: pointer to the matrix\n///\n/// # Returns\n/// A copy of `A`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `A` is not `NULL`\n/// - `SAFE_LENGTH`: `i` and `j` are valid row indices\n///\n/// # Examples\n/// ```\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.};\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n/// \n///   // Print matrix before and after\n///   sb_mat_print(A, \"A before: \", \"%g\");\n///   sb_mat_swap_row(A, 0, 1);\n///   sb_mat_print(A, \"A after: \", \"%g\");\n///\n///   SB_MAT_FREE_ALL(A);\n/// }\n/// ```\nsb_mat * sb_mat_swap_row(sb_mat * A, size_t i, size_t j) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_swap_row: A cannot be NULL\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(i >= A->n_rows, abort(),\n      \"sb_mat_swap_row: i must be a valid row index\");\n  SB_CHK_ERR(j >= A->n_rows, abort(),\n      \"sb_mat_swap_row: j must be a valid row index\");\n#endif\n  double * data = A->data;\n  size_t n_rows = A->n_rows;\n  cblas_dswap(A->n_cols, data + i, n_rows, data + j, n_rows);\n  return A;\n}\n\n/// Swaps the `i`th and `j`th columns of the matrix `A`.\n///\n/// # Parameters\n/// - `A`: pointer to the matrix\n///\n/// # Returns\n/// A copy of `A`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `A` is not `NULL`\n/// - `SAFE_LENGTH`: `i` and `j` are valid column indices\n///\n/// # Examples\n/// ```\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.};\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n/// \n///   // Print matrix before and after\n///   sb_mat_print(A, \"A before: \", \"%g\");\n///   sb_mat_swap_col(A, 0, 1);\n///   sb_mat_print(A, \"A after: \", \"%g\");\n///\n///   SB_MAT_FREE_ALL(A);\n/// }\n/// ```\nsb_mat * sb_mat_swap_col(sb_mat * A, size_t i, size_t j) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_swap_row: A cannot be NULL\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(i >= A->n_cols, abort(),\n      \"sb_mat_swap_row: i must be a valid column index\");\n  SB_CHK_ERR(j >= A->n_cols, abort(),\n      \"sb_mat_swap_row: j must be a valid column index\");\n#endif\n  double * data = A->data;\n  size_t n_rows = A->n_rows;\n  cblas_dswap(n_rows, data + i * n_rows, 1, data + j * n_rows, 1);\n  return A;\n}\n\n/// Writes the matrix `A` to `stream` in a binary format. The data is written\n/// in the native binary format of the architecture, and may not be portable.\n///\n/// # Parameters\n/// - `stream`: an open I/O stream\n/// - `A`: pointer to the matrix\n///\n/// # Returns\n/// `0` on success, or `1` if the write fails\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `A` is not `NULL`\n///\n/// # Examples\n/// ```\n/// #include <stdio.h>\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.};\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n///   \n///   // Write the matrix to file\n///   FILE * f = fopen(\"matrix.bin\", \"wb\");\n///   sb_mat_fwrite(f, A);\n///   fclose(f);\n///   \n///   // Read the matrix from file\n///   FILE * g = fopen(\"matrix.bin\", \"rb\");\n///   sb_mat * B = sb_mat_fread(g);\n///   fclose(g);\n///   \n///   // Matrices have the same contents\n///   sb_mat_print(A, \"A: \", \"%g\");\n///   sb_mat_print(B, \"B: \", \"%g\");\n///   \n///   SB_MAT_FREE_ALL(A, B);\n/// }\n/// ```\nint sb_mat_fwrite(FILE * stream, const sb_mat * A) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_fwrite: A cannot be NULL\");\n#endif\n  size_t n_write;\n\n  n_write = fwrite(&(A->n_rows), sizeof(size_t), 1, stream);\n  SB_CHK_ERR(n_write != 1, return 1, \"sb_mat_fwrite: fwrite failed\");\n\n  n_write = fwrite(&(A->n_cols), sizeof(size_t), 1, stream);\n  SB_CHK_ERR(n_write != 1, return 1, \"sb_mat_fwrite: fwrite failed\");\n\n  size_t n_elem = A->n_elem; \n  n_write = fwrite(A->data, sizeof(double), n_elem, stream);\n  SB_CHK_ERR(n_write != n_elem, return 1, \"sb_mat_fwrite: fwrite failed\");\n\n  return 0;\n}\n\n/// Writes the matrix `A` to `stream`. The number of elements and elements are\n/// written in a human readable format.\n///\n/// # Parameters\n/// - `stream`: an open I/O stream\n/// - `A`: pointer to the matrix\n/// - `format`: a format specifier for the elements\n///\n/// # Returns\n/// `0` on success, or `1` if the write fails\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `A` is not `NULL`\n///\n/// # Examples\n/// ```\n/// #include <stdio.h>\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.};\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n///   \n///   // Write the matrix to file\n///   FILE * f = fopen(\"matrix.txt\", \"w\");\n///   sb_mat_fprintf(f, A, \"%lg\");\n///   fclose(f);\n///   \n///   // Read the matrix from file\n///   FILE * g = fopen(\"matrix.txt\", \"r\");\n///   sb_mat * B = sb_mat_fscanf(g);\n///   fclose(g);\n///   \n///   // Matrices have the same contents\n///   sb_mat_print(A, \"A: \", \"%g\");\n///   sb_mat_print(B, \"B: \", \"%g\");\n///   \n///   SB_MAT_FREE_ALL(A, B);\n/// }\n/// ```\nint sb_mat_fprintf(FILE * stream, const sb_mat * A, const char * format) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_fprintf: A cannot be NULL\");\n#endif\n  int status;\n\n  status = fprintf(stream, \"%zu %zu\", A->n_rows, A->n_cols);\n  SB_CHK_ERR(status < 0, return 1, \"sb_mat_fprintf: fprintf failed\");\n\n  double * data = A->data;\n  for (size_t a = 0; a < A->n_elem; ++a) {\n    status = putc(' ', stream);\n    SB_CHK_ERR(status == EOF, return 1, \"sb_mat_fprintf: putc failed\");\n    status = fprintf(stream, format, data[a]);\n    SB_CHK_ERR(status < 0, return 1, \"sb_mat_fprintf: fprintf failed\");\n  }\n  status = putc('\\n', stream);\n  SB_CHK_ERR(status == EOF, return 1, \"sb_mat_fprintf: putc failed\");\n\n  return 0;\n}\n\n/// Prints the matrix `A` to stdout. Output is slightly easier to read than for\n/// `sb_mat_fprintf()`. Mainly indended for debugging.\n///\n/// # Parameters\n/// - `A`: pointer to the matrix\n/// - `str`: a string to describe the matrix\n/// - `format`: a format specifier for the elements\n///\n/// # Returns\n/// `0` on success, or `1` if the print fails\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `A` is not `NULL`\n///\n/// # Examples\n/// ```\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4.};\n///   sb_mat * A = sb_mat_of_arr(a, 2, 4);\n///   sb_mat * B = sb_mat_of_arr(a, 4, 2);\n///\n///   // Prints the contents of `A` and `B` to stdout\n///   sb_mat_print(A, \"A: \", \"%g\");\n///   sb_mat_print(B, \"B: \", \"%g\");\n///\n///   SB_MAT_FREE_ALL(A, B);\n/// }\n/// ```\nint sb_mat_print(const sb_mat * A, const char * str, const char * format) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_print: A cannot be NULL\");\n#endif\n  int status;\n\n  status = printf(\"%s\\n\", str);\n  SB_CHK_ERR(status < 0, return 1, \"sb_mat_print: printf failed\");\n\n  size_t n_elem = A->n_elem;\n  double * data = A->data;\n\n  char   buffer[128];\n  char * dec;\n  bool   dec_mark[n_elem];\n  bool   any_mark = false;\n\n  unsigned char length;\n  unsigned char len_head[n_elem];\n  unsigned char max_head = 0;\n  unsigned char len_tail[n_elem];\n  unsigned char max_tail = 0;\n  for (size_t a = 0; a < n_elem; ++a) {\n    status = snprintf(buffer, 128, format, data[a]);\n    SB_CHK_ERR(status < 0, return 1, \"sb_mat_print: snprintf failed\");\n    dec = strchr(buffer, '.');\n    if (dec) {\n      dec_mark[a] = true;\n      any_mark    = true;\n      length = (unsigned char)(dec - buffer);\n      len_head[a] = length;\n      if (length > max_head) { max_head = length; }\n      length = strlen(buffer) - length - 1;\n      if (length > max_tail) { max_tail = length; }\n      len_tail[a] = length;\n    } else {\n      dec_mark[a] = false;\n      length = strlen(buffer);\n      len_head[a] = length;\n      if (length > max_head) { max_head = length; }\n      len_tail[a] = 0;\n    }\n  }\n\n  size_t n_rows = A->n_rows;\n  size_t n_cols = A->n_cols;\n  size_t index;\n  for (size_t r = 0; r < n_rows; ++r) {\n    for (size_t c = 0; c < n_cols; ++c) {\n      index = c * n_rows + r;\n      for (unsigned char s = 0; s < max_head - len_head[index]; ++s) {\n        status = putchar(' ');\n        SB_CHK_ERR(status == EOF, return 1, \"sb_mat_print: putchar failed\");\n      }\n      status = printf(format, data[index]);\n      SB_CHK_ERR(status < 0, return 1, \"sb_mat_print: printf failed\");\n      if (any_mark && !dec_mark[index]) {\n        status = putchar(' ');\n        SB_CHK_ERR(status == EOF, return 1, \"sb_mat_print: putchar failed\");\n      }\n      for (unsigned char s = 0; s < max_tail - len_tail[index] + 1; ++s) {\n        status = putchar(' ');\n        SB_CHK_ERR(status == EOF, return 1, \"sb_mat_print: putchar failed\");\n      }\n    }\n    status = putchar('\\n');\n    SB_CHK_ERR(status == EOF, return 1, \"sb_mat_print: putchar failed\");\n  }\n\n  return 0;\n}\n\n/// Reads binary data from `stream` into the matrix returned by the function.\n/// The data must be written in the native binary format of the architecture, \n/// preferably by `sb_mat_fwrite()`.\n///\n/// # Parameters\n/// - `stream`: an open I/O stream\n///\n/// # Returns\n/// A `sb_mat` pointer to the matrix read from `stream`, or `NULL` if the read\n/// or memory allocation fails\n/// \n/// # Examples\n/// ```\n/// #include <stdio.h>\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.};\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n///   \n///   // Write the matrix to file\n///   FILE * f = fopen(\"matrix.bin\", \"wb\");\n///   sb_mat_fwrite(f, A);\n///   fclose(f);\n///   \n///   // Read the matrix from file\n///   FILE * g = fopen(\"matrix.bin\", \"rb\");\n///   sb_mat * B = sb_mat_fread(g);\n///   fclose(g);\n///   \n///   // Matrices have the same contents\n///   sb_mat_print(A, \"A: \", \"%g\");\n///   sb_mat_print(B, \"B: \", \"%g\");\n///   \n///   SB_MAT_FREE_ALL(A, B);\n/// }\n/// ```\nsb_mat * sb_mat_fread(FILE * stream) {\n  size_t n_read;\n\n  size_t n_rows;\n  n_read = fread(&n_rows, sizeof(size_t), 1, stream);\n  SB_CHK_ERR(n_read != 1, return NULL, \"sb_mat_fread: fread failed\");\n\n  size_t n_cols;\n  n_read = fread(&n_cols, sizeof(size_t), 1, stream);\n  SB_CHK_ERR(n_read != 1, return NULL, \"sb_mat_fread: fread failed\");\n\n  sb_mat * out = sb_mat_malloc(n_rows, n_cols);\n  SB_CHK_ERR(!out, return NULL, \"sb_mat_fread: sb_mat_malloc failed\");\n\n  size_t n_elem = out->n_elem;\n  n_read = fread(out->data, sizeof(double), n_elem, stream);\n  SB_CHK_ERR(n_read != n_elem, sb_mat_free(out); return NULL,\n      \"sb_mat_fread: fread failed\");\n\n  return out;\n}\n\n/// Reads formatted data from `stream` into the matrix returned by the function.\n///\n/// # Parameters\n/// - `stream`: an open I/O stream\n///\n/// # Returns\n/// A `sb_mat` pointer to the matrix read from `stream`, or `NULL` if the scan\n/// or memory allocation fails\n/// \n/// # Examples\n/// ```\n/// #include <stdio.h>\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.};\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n///   \n///   // Write the matrix to file\n///   FILE * f = fopen(\"matrix.txt\", \"w\");\n///   sb_mat_fprintf(f, A, \"%lg\");\n///   fclose(f);\n///   \n///   // Read the matrix from file\n///   FILE * g = fopen(\"matrix.txt\", \"r\");\n///   sb_mat * B = sb_mat_fscanf(g);\n///   fclose(g);\n///   \n///   // Matrices have the same contents\n///   sb_mat_print(A, \"A: \", \"%g\");\n///   sb_mat_print(B, \"B: \", \"%g\");\n///   \n///   SB_MAT_FREE_ALL(A, B);\n/// }\n/// ```\nsb_mat * sb_mat_fscanf(FILE * stream) {\n  int n_scan;\n\n  size_t n_rows;\n  size_t n_cols;\n  n_scan = fscanf(stream, \"%zu %zu\", &n_rows, &n_cols);\n  SB_CHK_ERR(n_scan != 2, return NULL, \"sb_mat_fscanf: fscanf failed\");\n\n  sb_mat * out = sb_mat_malloc(n_rows, n_cols);\n  SB_CHK_ERR(!out, return NULL, \"sb_mat_fscanf: sb_mat_malloc failed\");\n\n  double * data = out->data;\n  for (size_t a = 0; a < out->n_elem; ++a) {\n    n_scan = fscanf(stream, \"%lg\", data + a);\n    SB_CHK_ERR(n_scan != 1, sb_mat_free(out); return NULL,\n        \"sb_mat_fscanf: fscanf failed\");\n  }\n\n  return out;\n}\n\n/// Takes the absolute value of every element of the matrix.\n///\n/// # Parameters\n/// - `A`: pointer to the matrix\n///\n/// # Returns\n/// A copy of `A`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `A` is not `NULL`\n/// - `SAFE_FINITE`: elements of `A` are finite\n///\n/// # Examples\n/// ```\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   double a[] = {1., -4., 2., 8., 5., -7., -1., 4., 2.};\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n/// \n///   // Take absolute value\n///   sb_mat_print(A, \"A before: \", \"%g\");\n///   sb_mat_abs(A);\n///   sb_mat_print(A, \"A after: \", \"%g\");\n///\n///   SB_MAT_FREE_ALL(A);\n/// }\n/// ```\nsb_mat * sb_mat_abs(sb_mat * A) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_abs: A cannot be NULL\");\n#endif\n  double * data = A->data;\n  for (size_t a = 0; a < A->n_elem; ++a) {\n    data[a] = fabs(data[a]);\n  }\n#ifdef SAFE_FINITE\n  SB_CHK_ERR(!sb_mat_is_finite(A), abort(), \"sb_mat_abs: element not finite\");\n#endif\n  return A;\n}\n\n/// Takes the exponent base `e` of every element of the matrix.\n///\n/// # Parameters\n/// - `A`: pointer to the matrix\n///\n/// # Returns\n/// A copy of `A`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `A` is not `NULL`\n/// - `SAFE_FINITE`: elements of `A` are finite\n///\n/// # Examples\n/// ```\n/// #include <math.h>\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///  double a[] = {log(1.), log(4.), log(2.),\n///                log(8.), log(5.), log(7.),\n///                log(1.), log(4.), log(2.)};\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n/// \n///   // Take exponent base e\n///   sb_mat_print(A, \"A before: \", \"%g\");\n///   sb_mat_exp(A);\n///   sb_mat_print(A, \"A after: \", \"%g\");\n///\n///   SB_MAT_FREE_ALL(A);\n/// }\n/// ```\nsb_mat * sb_mat_exp(sb_mat * A) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_exp: A cannot be NULL\");\n#endif\n  double * data = A->data;\n  for (size_t a = 0; a < A->n_elem; ++a) {\n    data[a] = exp(data[a]);\n  }\n#ifdef SAFE_FINITE\n  SB_CHK_ERR(!sb_mat_is_finite(A), abort(), \"sb_mat_exp: element not finite\");\n#endif\n  return A;\n}\n\n/// Takes the logarithm base `e` of every element of the matrix.\n///\n/// # Parameters\n/// - `A`: pointer to the matrix\n///\n/// # Returns\n/// A copy of `A`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `A` is not `NULL`\n/// - `SAFE_FINITE`: elements of `A` are finite\n///\n/// # Examples\n/// ```\n/// #include <math.h>\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   double a[] = {exp(1.), exp(4.), exp(2.),\n///                 exp(8.), exp(5.), exp(7.),\n///                 exp(1.), exp(4.), exp(2.)};\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n/// \n///   // Take exponent base e\n///   sb_mat_print(A, \"A before: \", \"%g\");\n///   sb_mat_log(A);\n///   sb_mat_print(A, \"A after: \", \"%g\");\n///\n///   SB_MAT_FREE_ALL(A);\n/// }\n/// ```\nsb_mat * sb_mat_log(sb_mat * A) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_log: A cannot be NULL\");\n#endif\n  double * data = A->data;\n  for (size_t a = 0; a < A->n_elem; ++a) {\n    data[a] = log(data[a]);\n  }\n#ifdef SAFE_FINITE\n  SB_CHK_ERR(!sb_mat_is_finite(A), abort(), \"sb_mat_log: element not finite\");\n#endif\n  return A;\n}\n\n/// Exponentiates every element of the matrix `A` by `x`.\n///\n/// # Parameters\n/// - `A`: pointer to the matrix\n/// - `x`: scalar exponent of the elements\n///\n/// # Returns\n/// A copy of `A`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `A` is not `NULL`\n/// - `SAFE_FINITE`: elements of `A` are finite\n///\n/// # Examples\n/// ```\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.};\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n/// \n///   // Exponentiate every element by -1.\n///   sb_mat_print(A, \"A before: \", \"%g\");\n///   sb_mat_pow(A, -1.);\n///   sb_mat_print(A, \"A after: \", \"%g\");\n///\n///   SB_MAT_FREE_ALL(A);\n/// }\n/// ```\nsb_mat * sb_mat_pow(sb_mat * A, double x) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_pow: A cannot be NULL\");\n#endif\n  double * data = A->data;\n  for (size_t a = 0; a < A->n_elem; ++a) {\n    data[a] = pow(data[a], x);\n  }\n#ifdef SAFE_FINITE\n  SB_CHK_ERR(!sb_mat_is_finite(A), abort(), \"sb_mat_pow: element not finite\");\n#endif\n  return A;\n}\n\n/// Takes the square root of every element of the matrix `A`.\n///\n/// # Parameters\n/// - `A`: pointer to the matrix\n/// - `x`: scalar exponent of the elements\n///\n/// # Returns\n/// A copy of `A`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `A` is not `NULL`\n/// - `SAFE_FINITE`: elements of `A` are finite\n///\n/// # Examples\n/// ```\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 16., 4., 64., 25., 49., 1., 16., 4.};\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n/// \n///   // Take the square root of every element\n///   sb_mat_print(A, \"A before: \", \"%g\");\n///   sb_mat_sqrt(A);\n///   sb_mat_print(A, \"A after: \", \"%g\");\n///\n///   SB_MAT_FREE_ALL(A);\n/// }\n/// ```\nsb_mat * sb_mat_sqrt(sb_mat * A) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_sqrt: A cannot be NULL\");\n#endif\n  double * data = A->data;\n  for (size_t a = 0; a < A->n_elem; ++a) {\n    data[a] = sqrt(data[a]);\n  }\n#ifdef SAFE_FINITE\n  SB_CHK_ERR(!sb_mat_is_finite(A), abort(), \"sb_mat_sqrt: element not finite\");\n#endif\n  return A;\n}\n\n/// Scalar addition of `x` to every element of the matrix `A`.\n///\n/// # Parameters\n/// - `A`: pointer to the matrix\n/// - `x`: scalar added to the elements\n///\n/// # Returns\n/// A copy of `A`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `A` is not `NULL`\n/// - `SAFE_FINITE`: elements of `A` are finite\n///\n/// # Examples\n/// ```\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.};\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n/// \n///   // Add 2. to every element\n///   sb_mat_print(A, \"A before: \", \"%g\");\n///   sb_mat_sadd(A, 2.);\n///   sb_mat_print(A, \"A after: \", \"%g\");\n///\n///   SB_MAT_FREE_ALL(A);\n/// }\n/// ```\nsb_mat * sb_mat_sadd(sb_mat * A, double x) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_sadd: A cannot be NULL\");\n#endif\n  double * data = A->data;\n  for (size_t a = 0; a < A->n_elem; ++a) {\n    data[a] += x;\n  }\n#ifdef SAFE_FINITE\n  SB_CHK_ERR(!sb_mat_is_finite(A), abort(), \"sb_mat_sadd: element not finite\");\n#endif\n  return A;\n}\n\n/// Scalar multiplication of `x` with every element of the matrix `A`.\n///\n/// # Parameters\n/// - `A`: pointer to the matrix\n/// - `x`: scalar mutiplier for the elements\n///\n/// # Returns\n/// A copy of `A`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `A` is not `NULL`\n/// - `SAFE_FINITE`: elements of `A` are finite\n///\n/// # Examples\n/// ```\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.};\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n/// \n///   // Multiply every element by -1.\n///   sb_mat_print(A, \"A before: \", \"%g\");\n///   sb_mat_smul(A, -1.);\n///   sb_mat_print(A, \"A after: \", \"%g\");\n///\n///   SB_MAT_FREE_ALL(A);\n/// }\n/// ```\nsb_mat * sb_mat_smul(sb_mat * A, double x) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_smul: A cannot be NULL\");\n#endif\n  cblas_dscal(A->n_elem, x, A->data, 1);\n#ifdef SAFE_FINITE\n  SB_CHK_ERR(!sb_mat_is_finite(A), abort(), \"sb_mat_smul: elements not finite\");\n#endif\n  return A;\n}\n\n/// Adds to every row or column of the matrix `A` the corresponding element of\n/// the vector `v`. `A` and `v` must not overlap in memory.\n///\n/// # Parameters\n/// - `A`: pointer to the matrix\n/// - `v`: pointer to the vector\n/// - `dir`: one of 'r' or 'c'\n///\n/// # Returns\n/// A copy of `A`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `A` and `v` are not `NULL`\n/// - `SAFE_LAYOUT`: the layout of `v` is compatible with `dir`\n/// - `SAFE_LENGTH`: `A` and `v` have compatible dimensions\n/// - `SAFE_FINITE`: elements of `A` are finite\n///\n/// # Examples\n/// ```\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.};\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n///   sb_vec * v = sb_vec_of_arr(a, 3, 'r');\n/// \n///   // Add v to every column of A\n///   sb_vec_print(v, \"v: \", \"%g\");\n///   sb_mat_print(A, \"A before: \", \"%g\");\n///   sb_mat_vadd(A, v, 'c');\n///   sb_mat_print(A, \"A after: \", \"%g\");\n///\n///   SB_MAT_FREE_ALL(A);\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\nsb_mat * sb_mat_vadd(sb_mat * restrict A, const sb_vec * restrict v, char dir) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_vadd: A cannot be NULL\");\n  SB_CHK_ERR(!v, abort(), \"sb_mat_vadd: v cannot be NULL\");\n#endif\n  size_t n_rows = A->n_rows;\n  size_t n_cols = A->n_cols;\n  double * A_data = A->data;\n  double * v_data = v->data;\n  switch (dir) {\n    case 'c':\n#ifdef SAFE_LAYOUT\n      SB_CHK_ERR(v->layout != 'r', abort(), \"sb_mat_vadd: v must be a row vector\");\n#endif\n#ifdef SAFE_LENGTH\n      SB_CHK_ERR(A->n_cols != v->n_elem, abort(),\n          \"sb_mat_vadd: A and v must have same number of columns\");\n#endif\n      for (size_t a = 0; a < n_rows; ++a) {\n        cblas_daxpy(n_cols, 1., v_data, 1, A_data + a, n_rows);\n      }\n      break;\n    case 'r':\n#ifdef SAFE_LAYOUT\n      SB_CHK_ERR(v->layout != 'c', abort(), \"sb_mat_radd: v must be a column vector\");\n#endif\n#ifdef SAFE_LENGTH\n      SB_CHK_ERR(A->n_rows != v->n_elem, abort(),\n          \"sb_mat_radd: A and v must have same number of rows\");\n#endif\n      for (size_t a = 0; a < n_cols; ++a) {\n        cblas_daxpy(n_rows, 1., v_data, 1, A_data + a * n_rows, 1);\n      }\n      break;\n    default:\n      SB_CHK_ERR(true, abort(), \"sb_mat_vadd: dir must 'c' or 'r'\");\n      break;\n  }\n#ifdef SAFE_FINITE\n  SB_CHK_ERR(!sb_mat_is_finite(A), abort(), \"sb_mat_vadd: elements not finite\");\n#endif\n  return A;\n}\n\n/// Subtracts from every row or column of the matrix `A` the corresponding\n/// element of the vector `v`. `A` and `v` must not overlap in memory.\n///\n/// # Parameters\n/// - `A`: pointer to the matrix\n/// - `v`: pointer to the vector\n/// - `dir`: one of 'r' or 'c'\n///\n/// # Returns\n/// A copy of `A`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `A` and `v` are not `NULL`\n/// - `SAFE_LAYOUT`: the layout of `v` is compatible with `dir`\n/// - `SAFE_LENGTH`: `A` and `v` have compatible dimensions\n/// - `SAFE_FINITE`: elements of `A` are finite\n///\n/// # Examples\n/// ```\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.};\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n///   sb_vec * v = sb_vec_of_arr(a, 3, 'r');\n/// \n///   // Subtracts v from every column of A\n///   sb_vec_print(v, \"v: \", \"%g\");\n///   sb_mat_print(A, \"A before: \", \"%g\");\n///   sb_mat_vsub(A, v, 'c');\n///   sb_mat_print(A, \"A after: \", \"%g\");\n///\n///   SB_MAT_FREE_ALL(A);\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\nsb_mat * sb_mat_vsub(sb_mat * restrict A, const sb_vec * restrict v, char dir) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_vsub: A cannot be NULL\");\n  SB_CHK_ERR(!v, abort(), \"sb_mat_vsub: v cannot be NULL\");\n#endif\n  size_t n_rows = A->n_rows;\n  size_t n_cols = A->n_cols;\n  double * A_data = A->data;\n  double * v_data = v->data;\n  switch (dir) {\n    case 'c':\n#ifdef SAFE_LAYOUT\n      SB_CHK_ERR(v->layout != 'r', abort(), \"sb_mat_vsub: v must be a row vector\");\n#endif\n#ifdef SAFE_LENGTH\n      SB_CHK_ERR(A->n_cols != v->n_elem, abort(),\n          \"sb_mat_vsub: A and v must have same number of columns\");\n#endif\n      for (size_t a = 0; a < n_rows; ++a) {\n        cblas_daxpy(n_cols, -1., v_data, 1, A_data + a, n_rows);\n      }\n      break;\n    case 'r':\n#ifdef SAFE_LAYOUT\n      SB_CHK_ERR(v->layout != 'c', abort(), \"sb_mat_rsub: v must be a column vector\");\n#endif\n#ifdef SAFE_LENGTH\n      SB_CHK_ERR(A->n_rows != v->n_elem, abort(),\n          \"sb_mat_rsub: A and v must have same number of rows\");\n#endif\n      for (size_t a = 0; a < n_cols; ++a) {\n        cblas_daxpy(n_rows, -1., v_data, 1, A_data + a * n_rows, 1);\n      }\n      break;\n    default:\n      SB_CHK_ERR(true, abort(), \"sb_mat_vsub: dir must 'c' or 'r'\");\n      break;\n  }\n#ifdef SAFE_FINITE\n  SB_CHK_ERR(!sb_mat_is_finite(A), abort(), \"sb_mat_vsub: elements not finite\");\n#endif\n  return A;\n}\n\n/// Multiplies every row or column of the matrix `A` by the corresonding\n/// element of the vector `v`. `A` and `v` must not overlap in memory.\n///\n/// # Parameters\n/// - `A`: pointer to the matrix\n/// - `v`: pointer to the vector\n/// - `dir`: one of 'r' or 'c'\n///\n/// # Returns\n/// A copy of `A`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `A` and `v` are not `NULL`\n/// - `SAFE_LAYOUT`: the layout of `v` is compatible with `dir`\n/// - `SAFE_LENGTH`: `A` and `v` have compatible dimensions\n/// - `SAFE_FINITE`: elements of `A` are finite\n///\n/// # Examples\n/// ```\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.};\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n///   sb_vec * v = sb_vec_of_arr(a, 3, 'r');\n/// \n///   // Multiplies every column of A by corresponding element of v\n///   sb_vec_print(v, \"v: \", \"%g\");\n///   sb_mat_print(A, \"A before: \", \"%g\");\n///   sb_mat_vmul(A, v, 'c');\n///   sb_mat_print(A, \"A after: \", \"%g\");\n///\n///   SB_MAT_FREE_ALL(A);\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\nsb_mat * sb_mat_vmul(sb_mat * restrict A, const sb_vec * restrict v, char dir) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_vmul: A cannot be NULL\");\n  SB_CHK_ERR(!v, abort(), \"sb_mat_vmul: v cannot be NULL\");\n#endif\n  size_t n_rows = A->n_rows;\n  size_t n_cols = A->n_cols;\n  double * A_data = A->data;\n  double * v_data = v->data;\n  switch (dir) {\n    case 'c':\n#ifdef SAFE_LAYOUT\n      SB_CHK_ERR(v->layout != 'r', abort(), \"sb_mat_vmul: v must be a row vector\");\n#endif\n#ifdef SAFE_LENGTH\n      SB_CHK_ERR(A->n_cols != v->n_elem, abort(),\n          \"sb_mat_vmul: A and v must have same number of columns\");\n#endif\n      for (size_t a = 0; a < n_cols; ++a) {\n        cblas_dscal(n_rows, v_data[a], A_data + a * n_rows, 1);\n      }\n      break;\n    case 'r':\n#ifdef SAFE_LAYOUT\n      SB_CHK_ERR(v->layout != 'c', abort(), \"sb_mat_vmul: v must be a column vector\");\n#endif\n#ifdef SAFE_LENGTH\n      SB_CHK_ERR(A->n_rows != v->n_elem, abort(),\n          \"sb_mat_vmul: A and v must have same number of rows\");\n#endif\n      for (size_t a = 0; a < n_rows; ++a) {\n        cblas_dscal(n_cols, v_data[a], A_data + a, n_rows);\n      }\n      break;\n    default:\n      SB_CHK_ERR(true, abort(), \"sb_mat_vmul: dir must 'c' or 'r'\");\n      break;\n  }\n#ifdef SAFE_FINITE\n  SB_CHK_ERR(!sb_mat_is_finite(A), abort(), \"sb_mat_vmul: elements not finite\");\n#endif\n  return A;\n}\n\n/// Divides every column or row of the matrix `A` by the corresonding element\n/// of the vector `v`. `A` and `v` must not overlap in memory.\n///\n/// # Parameters\n/// - `A`: pointer to the matrix\n/// - `v`: pointer to the vector\n/// - `dir`: one of 'r' or 'c'\n///\n/// # Returns\n/// A copy of `A`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `A` and `v` are not `NULL`\n/// - `SAFE_LAYOUT`: the layout of `v` is compatible with `dir`\n/// - `SAFE_LENGTH`: `A` and `v` have compatible dimensions\n/// - `SAFE_FINITE`: elements of `A` are finite\n///\n/// # Examples\n/// ```\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.};\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n///   sb_vec * v = sb_vec_of_arr(a, 3, 'r');\n/// \n///   // Divides every column of A by corresponding element of v\n///   sb_vec_print(v, \"v: \", \"%g\");\n///   sb_mat_print(A, \"A before: \", \"%g\");\n///   sb_mat_vdiv(A, v, 'c');\n///   sb_mat_print(A, \"A after: \", \"%g\");\n///\n///   SB_MAT_FREE_ALL(A);\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\nsb_mat * sb_mat_vdiv(sb_mat * restrict A, const sb_vec * restrict v, char dir) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_vdiv: A cannot be NULL\");\n  SB_CHK_ERR(!v, abort(), \"sb_mat_vdiv: v cannot be NULL\");\n#endif\n  size_t n_rows = A->n_rows;\n  size_t n_cols = A->n_cols;\n  double * A_data = A->data;\n  double * v_data = v->data;\n  switch (dir) {\n    case 'c':\n#ifdef SAFE_LAYOUT\n      SB_CHK_ERR(v->layout != 'r', abort(), \"sb_mat_vdiv: v must be a row vector\");\n#endif\n#ifdef SAFE_LENGTH\n      SB_CHK_ERR(A->n_cols != v->n_elem, abort(),\n          \"sb_mat_vdiv: A and v must have same number of columns\");\n#endif\n      for (size_t a = 0; a < n_cols; ++a) {\n        cblas_dscal(n_rows, 1. / v_data[a], A_data + a * n_rows, 1);\n      }\n      break;\n    case 'r':\n#ifdef SAFE_LAYOUT\n      SB_CHK_ERR(v->layout != 'c', abort(), \"sb_mat_rdiv: v must be a column vector\");\n#endif\n#ifdef SAFE_LENGTH\n      SB_CHK_ERR(A->n_rows != v->n_elem, abort(),\n          \"sb_mat_rdiv: A and v must have same number of rows\");\n#endif\n      for (size_t a = 0; a < n_rows; ++a) {\n        cblas_dscal(n_cols, 1. / v_data[a], A_data + a, n_rows);\n      }\n      break;\n    default:\n      SB_CHK_ERR(true, abort(), \"sb_mat_vdiv: dir must 'c' or 'r'\");\n      break;\n  }\n#ifdef SAFE_FINITE\n  SB_CHK_ERR(!sb_mat_is_finite(A), abort(), \"sb_mat_vdiv: elements not finite\");\n#endif\n  return A;\n}\n\n/// Pointwise addition of elements of the matrix `B` to elements of the matrix\n/// `A`. `A` and `B` must not overlap in memory.\n///\n/// # Parameters\n/// - `A`: pointer to the first matrix\n/// - `B`: pointer to the second matrix\n///\n/// # Returns\n/// A copy of `A`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `A` and `B` are not `NULL`\n/// - `SAFE_LENGTH`: `A` and `B` have the same number of rows and columns\n/// - `SAFE_FINITE`: elements of `A` are finite\n///\n/// # Examples\n/// ```\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2., 8.};\n///   sb_mat * A = sb_mat_of_arr(a,     3, 3);\n///   sb_mat * B = sb_mat_of_arr(a + 1, 3, 3);\n/// \n///   // Add B to A\n///   sb_mat_print(A, \"A: \", \"%g\");\n///   sb_mat_print(B, \"B: \", \"%g\");\n///   sb_mat_padd(A, B);\n///   sb_mat_print(A, \"A after: \", \"%g\");\n///\n///   SB_MAT_FREE_ALL(A, B);\n/// }\n/// ```\nsb_mat * sb_mat_padd(sb_mat * restrict A, const sb_mat * restrict B) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_padd: A cannot be NULL\");\n  SB_CHK_ERR(!B, abort(), \"sb_mat_padd: B cannot be NULL\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(A->n_rows != B->n_rows, abort(),\n      \"sb_mat_padd: A and B must have same number of rows\");\n  SB_CHK_ERR(A->n_cols != B->n_cols, abort(),\n      \"sb_mat_padd: A and B must have same number of columns\");\n#endif\n  cblas_daxpy(A->n_elem, 1., B->data, 1, A->data, 1);\n#ifdef SAFE_FINITE\n  SB_CHK_ERR(!sb_mat_is_finite(A), abort(), \"sb_mat_padd: elements not finite\");\n#endif\n  return A;\n}\n\n/// Pointwise subtraction of elements of the matrix `B` from elements of the\n/// matrix `A`. `A` and `B` must not overlap in memory.\n///\n/// # Parameters\n/// - `A`: pointer to the first matrix\n/// - `B`: pointer to the second matrix\n///\n/// # Returns\n/// A copy of `A`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `A` and `B` are not `NULL`\n/// - `SAFE_LENGTH`: `A` and `B` have the same number of rows and columns\n/// - `SAFE_FINITE`: elements of `A` are finite\n///\n/// # Examples\n/// ```\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2., 8.};\n///   sb_mat * A = sb_mat_of_arr(a,     3, 3);\n///   sb_mat * B = sb_mat_of_arr(a + 1, 3, 3);\n/// \n///   // Subtract B from A\n///   sb_mat_print(A, \"A: \", \"%g\");\n///   sb_mat_print(B, \"B: \", \"%g\");\n///   sb_mat_psub(A, B);\n///   sb_mat_print(A, \"A after: \", \"%g\");\n///\n///   SB_MAT_FREE_ALL(A, B);\n/// }\n/// ```\nsb_mat * sb_mat_psub(sb_mat * restrict A, const sb_mat * restrict B) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_psub: A cannot be NULL\");\n  SB_CHK_ERR(!B, abort(), \"sb_mat_psub: B cannot be NULL\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(A->n_rows != B->n_rows, abort(),\n      \"sb_mat_psub: A and B must have same number of rows\");\n  SB_CHK_ERR(A->n_cols != B->n_cols, abort(),\n      \"sb_mat_psub: A and B must have same number of columns\");\n#endif\n  cblas_daxpy(A->n_elem, -1., B->data, 1, A->data, 1);\n#ifdef SAFE_FINITE\n  SB_CHK_ERR(!sb_mat_is_finite(A), abort(), \"sb_mat_psub: elements not finite\");\n#endif\n  return A;\n}\n\n/// Pointwise multiplication of elements of the matrix `A` with elements of the\n/// matrix `B`. `A` and `B` must not overlap in memory.\n///\n/// # Parameters\n/// - `A`: pointer to the first matrix\n/// - `B`: pointer to the second matrix\n///\n/// # Returns\n/// A copy of `A`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `A` and `B` are not `NULL`\n/// - `SAFE_LENGTH`: `A` and `B` have the same number of rows and columns\n/// - `SAFE_FINITE`: elements of `A` are finite\n///\n/// # Examples\n/// ```\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2., 8.};\n///   sb_mat * A = sb_mat_of_arr(a,     3, 3);\n///   sb_mat * B = sb_mat_of_arr(a + 1, 3, 3);\n/// \n///   // Multiply elements of A by elements of B\n///   sb_mat_print(A, \"A: \", \"%g\");\n///   sb_mat_print(B, \"B: \", \"%g\");\n///   sb_mat_pmul(A, B);\n///   sb_mat_print(A, \"A after: \", \"%g\");\n///\n///   SB_MAT_FREE_ALL(A, B);\n/// }\n/// ```\nsb_mat * sb_mat_pmul(sb_mat * restrict A, const sb_mat * restrict B) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_pmul: A cannot be NULL\");\n  SB_CHK_ERR(!B, abort(), \"sb_mat_pmul: B cannot be NULL\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(A->n_rows != B->n_rows, abort(),\n      \"sb_mat_pmul: A and B must have same number of rows\");\n  SB_CHK_ERR(A->n_cols != B->n_cols, abort(),\n      \"sb_mat_pmul: A and B must have same number of columns\");\n#endif\n  double * A_data = A->data;\n  double * B_data = B->data;\n  for (size_t a = 0; a < A->n_elem; ++a) {\n    A_data[a] *= B_data[a];\n  }\n#ifdef SAFE_FINITE\n  SB_CHK_ERR(!sb_mat_is_finite(A), abort(), \"sb_mat_pmul: element not finite\");\n#endif\n  return A;\n}\n\n/// Pointwise division of elements of the matrix `A` by elements of the matrix\n/// `B`. `A` and `B` must not overlap in memory.\n///\n/// # Parameters\n/// - `A`: pointer to the first matrix\n/// - `B`: pointer to the second matrix\n///\n/// # Returns\n/// A copy of `A`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `A` and `B` are not `NULL`\n/// - `SAFE_LENGTH`: `A` and `B` have the same number of rows and columns\n/// - `SAFE_FINITE`: elements of `A` are finite\n///\n/// # Examples\n/// ```\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2., 8.};\n///   sb_mat * A = sb_mat_of_arr(a,     3, 3);\n///   sb_mat * B = sb_mat_of_arr(a + 1, 3, 3);\n/// \n///   // Divide elements of A by elements of B\n///   sb_mat_print(A, \"A: \", \"%g\");\n///   sb_mat_print(B, \"B: \", \"%g\");\n///   sb_mat_pdiv(A, B);\n///   sb_mat_print(A, \"A after: \", \"%g\");\n///\n///   SB_MAT_FREE_ALL(A, B);\n/// }\n/// ```\nsb_mat * sb_mat_pdiv(sb_mat * restrict A, const sb_mat * restrict B) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_pdiv: A cannot be NULL\");\n  SB_CHK_ERR(!B, abort(), \"sb_mat_pdiv: B cannot be NULL\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(A->n_rows != B->n_rows, abort(),\n      \"sb_mat_pdiv: A and B must have same number of rows\");\n  SB_CHK_ERR(A->n_cols != B->n_cols, abort(),\n      \"sb_mat_pdiv: A and B must have same number of columns\");\n#endif\n  double * A_data = A->data;\n  double * B_data = B->data;\n  for (size_t a = 0; a < A->n_elem; ++a) {\n    A_data[a] /= B_data[a];\n  }\n#ifdef SAFE_FINITE\n  SB_CHK_ERR(!sb_mat_is_finite(A), abort(), \"sb_mat_pdiv: element not finite\");\n#endif\n  return A;\n}\n\n/// Matrix-vector multiplication of `op(A)` and `w`, where `op` can be nothing\n/// or a transpose. The result is stored in the vector `v`, and any previous\n/// values in `v` are overwritten. `v`, `A` and `w` must not overlap in memory.\n///\n/// # Parameters\n/// - `v`: pointer to the resulting vector\n/// - `A`: pointer to the left matrix\n/// - `w`: pointer to the right vector\n/// - `op`: 'n' or 't'\n///\n/// # Returns\n/// A copy of `v`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v`, `A` and `w` are not `NULL`\n/// - `SAFE_LAYOUT`: `v` and `w` must be column vectors\n/// - `SAFE_LENGTH`: `v`, `A` and `w` have compatible dimensions\n/// - `SAFE_FINITE`: elements of `v` are finite\n///\n/// # Examples\n/// ```\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n/// #Include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.};\n///   sb_vec * v = sb_vec_malloc(3, 'c');\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n///   sb_vec * w = sb_vec_of_arr(a + 1, 3, 'c');\n/// \n///   // Multiply A by w and store in v\n///   sb_mat_print(A, \"A: \", \"%g\");\n///   sb_vec_print(w, \"w: \", \"%g\");\n///   sb_mat_mv_mul(v, A, w, 'n');\n///   sb_vec_print(v, \"v: \", \"%g\");\n///\n///   SB_MAT_FREE_ALL(A);\n///   SB_VEC_FREE_ALL(v, w);\n/// }\n/// ```\nsb_vec * sb_mat_mv_mul(\n    sb_vec * restrict v,\n    const sb_mat * restrict A,\n    const sb_vec * restrict w,\n    char op) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_mat_mv_mul: v cannot be NULL\");\n  SB_CHK_ERR(!A, abort(), \"sb_mat_mv_mul: A cannot be NULL\");\n  SB_CHK_ERR(!w, abort(), \"sb_mat_mv_mul: w cannot be NULL\");\n#endif\n#ifdef SAFE_LAYOUT\n  SB_CHK_ERR(v->layout != 'c', abort(), \"sb_mat_mv_mul: v must be a column vector\");\n  SB_CHK_ERR(w->layout != 'c', abort(), \"sb_mat_mv_mul: w must be a column vector\");\n#endif\n  switch (op) {\n    case 'n':\n#ifdef SAFE_LENGTH\n      SB_CHK_ERR(v->n_elem != A->n_rows, abort(),\n          \"sb_mat_mv_mul: v and A must have same number of rows\");\n      SB_CHK_ERR(A->n_cols != w->n_elem, abort(),\n          \"sb_mat_mv_mul: A and w must have compatible inner dimensions\");\n#endif\n      cblas_dgemv(CblasColMajor, CblasNoTrans, A->n_rows, A->n_cols,\n          1., A->data, A->n_rows, w->data, 1, 0., v->data, 1);\n      break;\n    case 't':\n#ifdef SAFE_LENGTH\n      SB_CHK_ERR(v->n_elem != A->n_cols, abort(),\n          \"sb_mat_mv_mul: v and A^T must have same number of rows\");\n      SB_CHK_ERR(A->n_rows != w->n_elem, abort(),\n          \"sb_mat_mv_mul: A^T and w must have compatible inner dimensions\");\n#endif\n      cblas_dgemv(CblasColMajor, CblasTrans, A->n_rows, A->n_cols,\n          1., A->data, A->n_rows, w->data, 1, 0., v->data, 1);\n      break;\n    default:\n      SB_CHK_ERR(true, abort(), \"sb_mat_mv_mul: op must 'n' or 't'\");\n      break;\n  }\n#ifdef SAFE_FINITE\n  SB_CHK_ERR(!sb_vec_is_finite(v), abort(), \"sb_mat_mv_mul: elements not finite\");\n#endif\n  return v;\n}\n\n/// Vector-matrix multiplication of `w` and `op(A)`, where `op` can be nothing\n/// or a transpose. The result is stored in the vector `v`, and any previous\n/// values in `v` are overwritten. `v`, `w` and `A` must not overlap in memory.\n///\n/// # Parameters\n/// - `v`: pointer to the resulting vector\n/// - `w`: pointer to the left vector\n/// - `A`: pointer to the right matrix\n/// - `op`: 'n' or 't'\n///\n/// # Returns\n/// A copy of `v`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v`, `w` and `A` are not `NULL`\n/// - `SAFE_LAYOUT`: `v` and `w` must be row vectors\n/// - `SAFE_LENGTH`: `v`, `w` and `A` have compatible dimensions\n/// - `SAFE_FINITE`: elements of `v` are finite\n///\n/// # Examples\n/// ```\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.};\n///   sb_vec * v = sb_vec_malloc(3, 'r');\n///   sb_vec * w = sb_vec_of_arr(a + 1, 3, 'r');\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n/// \n///   // Multiply w by A and store in v\n///   sb_vec_print(w, \"w: \", \"%g\");\n///   sb_mat_print(A, \"A: \", \"%g\");\n///   sb_mat_vm_mul(v, w, A, 'n');\n///   sb_vec_print(v, \"v: \", \"%g\");\n///\n///   SB_MAT_FREE_ALL(A);\n///   SB_VEC_FREE_ALL(v, w);\n/// }\n/// ```\nsb_vec * sb_mat_vm_mul(\n    sb_vec * restrict v,\n    const sb_vec * restrict w,\n    const sb_mat * restrict A,\n    char op) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_mat_vm_mul: v cannot be NULL\");\n  SB_CHK_ERR(!w, abort(), \"sb_mat_vm_mul: w cannot be NULL\");\n  SB_CHK_ERR(!A, abort(), \"sb_mat_vm_mul: A cannot be NULL\");\n#endif\n#ifdef SAFE_LAYOUT\n  SB_CHK_ERR(v->layout != 'r', abort(), \"sb_mat_vm_mul: v must be a row vector\");\n  SB_CHK_ERR(w->layout != 'r', abort(), \"sb_mat_vm_mul: w must be a row vector\");\n#endif\n  switch (op) {\n    case 'n':\n#ifdef SAFE_LENGTH\n      SB_CHK_ERR(v->n_elem != A->n_cols, abort(),\n          \"sb_mat_vm_mul: v and A must have same number of columns\");\n      SB_CHK_ERR(A->n_rows != w->n_elem, abort(),\n          \"sb_mat_vm_mul: A and w must have compatible inner dimensions\");\n#endif\n      cblas_dgemv(CblasColMajor, CblasTrans, A->n_rows, A->n_cols,\n          1., A->data, A->n_rows, w->data, 1, 0., v->data, 1);\n      break;\n    case 't':\n#ifdef SAFE_LENGTH\n      SB_CHK_ERR(v->n_elem != A->n_rows, abort(),\n          \"sb_mat_vm_mul: v and A^T must have same number of columns\");\n      SB_CHK_ERR(A->n_cols != w->n_elem, abort(),\n          \"sb_mat_vm_mul: A^T and w must have compatible inner dimensions\");\n#endif\n      cblas_dgemv(CblasColMajor, CblasNoTrans, A->n_rows, A->n_cols,\n          1., A->data, A->n_rows, w->data, 1, 0., v->data, 1);\n      break;\n    default:\n      SB_CHK_ERR(true, abort(), \"sb_mat_vm_mul: op must 'n' or 't'\");\n      break;\n  }\n#ifdef SAFE_FINITE\n  SB_CHK_ERR(!sb_vec_is_finite(v), abort(), \"sb_mat_vm_mul: elements not finite\");\n#endif\n  return v;\n}\n\n/// Matrix multiplication of `op(B)` and `op(C)`, where `op` can be nothing or\n/// a transpose. The result is stored in `A`, and any previous values in `A`\n/// are overwritten. `A` must not overlap `B` or `C` in memory.\n///\n/// # Parameters\n/// - `A`: pointer to the resulting matrix\n/// - `B`: pointer to the left matrix\n/// - `C`: pointer to the right matrix\n/// - `ops`: one of \"nn\", \"nt\", \"tn\", or \"tt\"\n///\n/// # Returns\n/// A copy of `A`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `A`, `B` and `C` are not `NULL`\n/// - `SAFE_LENGTH`: `A`, `B` and `C` have compatible dimensions\n/// - `SAFE_FINITE`: elements of `A` are finite\n///\n/// # Examples\n/// ```\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2., 8.};\n///   sb_mat * A = sb_mat_malloc(3, 3);\n///   sb_mat * B = sb_mat_of_arr(a,     3, 3);\n///   sb_mat * C = sb_mat_of_arr(a + 1, 3, 3);\n/// \n///   // Multiply B by C and store in A\n///   sb_mat_print(B, \"B: \", \"%g\");\n///   sb_mat_print(C, \"C: \", \"%g\");\n///   sb_mat_mm_mul(A, B, C, \"nn\");\n///   sb_mat_print(A, \"A: \", \"%g\");\n///\n///   SB_MAT_FREE_ALL(A, B, C);\n/// }\n/// ```\nsb_mat * sb_mat_mm_mul(\n    sb_mat * restrict A,\n    const sb_mat * restrict B,\n    const sb_mat * restrict C,\n    const char * restrict ops) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_mm_mul: A cannot be NULL\");\n  SB_CHK_ERR(!B, abort(), \"sb_mat_mm_mul: B cannot be NULL\");\n  SB_CHK_ERR(!C, abort(), \"sb_mat_mm_mul: C cannot be NULL\");\n#endif\n  switch ((*ops << 8) + *(ops + 1)) {\n    case 0x6E6E: // \"nn\"\n#ifdef SAFE_LENGTH\n      SB_CHK_ERR(A->n_rows != B->n_rows, abort(),\n          \"sb_mat_mm_mul: A and B must have same number of rows\");\n      SB_CHK_ERR(A->n_cols != C->n_cols, abort(),\n          \"sb_mat_mm_mul: A and C must have same number of columns\");\n      SB_CHK_ERR(B->n_cols != C->n_rows, abort(),\n          \"sb_mat_mm_mul: B and C must have compatible inner dimensions\");\n#endif\n      cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, A->n_rows, A->n_cols, B->n_cols,\n          1., B->data, B->n_rows, C->data, C->n_rows, 0., A->data, A->n_rows);\n      break;\n    case 0x6E74: // \"nt\"\n#ifdef SAFE_LENGTH\n      SB_CHK_ERR(A->n_rows != B->n_rows, abort(),\n          \"sb_mat_mm_mul: A and B must have same number of rows\");\n      SB_CHK_ERR(A->n_cols != C->n_rows, abort(),\n          \"sb_mat_mm_mul: A and C^T must have same number of columns\");\n      SB_CHK_ERR(B->n_cols != C->n_cols, abort(),\n          \"sb_mat_mm_mul: B and C^T must have compatible inner dimensions\");\n#endif\n      cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans, A->n_rows, A->n_cols, B->n_cols,\n          1., B->data, B->n_rows, C->data, C->n_rows, 0., A->data, A->n_rows);\n      break;\n    case 0x746E: // \"tn\"\n#ifdef SAFE_LENGTH\n      SB_CHK_ERR(A->n_rows != B->n_cols, abort(),\n          \"sb_mat_mm_mul: A and B^T must have same number of rows\");\n      SB_CHK_ERR(A->n_cols != C->n_cols, abort(),\n          \"sb_mat_mm_mul: A and C must have same number of columns\");\n      SB_CHK_ERR(B->n_rows != C->n_rows, abort(),\n          \"sb_mat_mm_mul: B^T and C must have compatible inner dimensions\");\n#endif\n      cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans, A->n_rows, A->n_cols, B->n_rows,\n          1., B->data, B->n_rows, C->data, C->n_rows, 0., A->data, A->n_rows);\n      break;\n    case 0x7474: // \"tt\"\n#ifdef SAFE_LENGTH\n      SB_CHK_ERR(A->n_rows != B->n_cols, abort(),\n          \"sb_mat_mm_mul: A and B^T must have same number of rows\");\n      SB_CHK_ERR(A->n_cols != C->n_rows, abort(),\n          \"sb_mat_mm_mul: A and C^T must have same number of columns\");\n      SB_CHK_ERR(B->n_rows != C->n_cols, abort(),\n          \"sb_mat_mm_mul: B^T and C^T must have compatible inner dimensions\");\n#endif\n      cblas_dgemm(CblasColMajor, CblasTrans, CblasTrans, A->n_rows, A->n_cols, B->n_rows,\n          1., B->data, B->n_rows, C->data, C->n_rows, 0., A->data, A->n_rows);\n      break;\n    default:\n      SB_CHK_ERR(true, abort(),\n          \"sb_mat_mm_mul: ops must be one of \\\"nn\\\", \\\"nt\\\", \\\"tn\\\", or \\\"tt\\\"\");\n      break;\n  }\n#ifdef SAFE_FINITE\n  SB_CHK_ERR(!sb_mat_is_finite(A), abort(), \"sb_mat_mm_mul: elements not finite\");\n#endif\n  return A;\n}\n\n/// Sums over the rows or columns of the matrix `A`. The result is stored in\n/// `v`, and any previous values in `v` are overwritten. `v` and `A` must not\n/// overlap in memory.\n///\n/// # Parameters\n/// - `v`: pointer to the resulting vector\n/// - `A`: pointer to the matrix to be summed\n/// - `dir`: one of 'r' or 'c'\n///\n/// # Returns\n/// A copy of `v`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` and `A` are not `NULL`\n/// - `SAFE_LAYOUT`: the layout of `v` is consistent with `dir`\n/// - `SAFE_LENGTH`: `v` and `A` have compatible dimensions\n/// - `SAFE_FINITE`: elements of `v` are finite\n///\n/// # Examples\n/// ```\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.};\n///   sb_vec * v = sb_vec_malloc(3, 'c');\n///   sb_vec * w = sb_vec_malloc(3, 'r');\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n/// \n///   sb_mat_print(A, \"A: \", \"%g\");\n///   // Sum over the rows of A\n///   sb_mat_sum(v, A, 'r');\n///   sb_vec_print(v, \"v: \", \"%g\");\n///   // Sum over the cols of A\n///   sb_mat_sum(w, A, 'c');\n///   sb_vec_print(w, \"w: \", \"%g\");\n///\n///   SB_MAT_FREE_ALL(A);\n///   SB_VEC_FREE_ALL(v, w);\n/// }\n/// ```\nsb_vec * sb_mat_sum(sb_vec * restrict v, const sb_mat * restrict A, const char dir) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_mat_sum: v cannot be NULL\");\n  SB_CHK_ERR(!A, abort(), \"sb_mat_sum: A cannot be NULL\");\n#endif\n  size_t n_rows = A->n_rows;\n  size_t n_cols = A->n_cols;\n  double * A_data = A->data;\n  double * v_data = v->data;\n  switch (dir) {\n    case 'c':\n#ifdef SAFE_LAYOUT\n      SB_CHK_ERR(v->layout != 'r', abort(),\n          \"sb_mat_sum: v must be a row vector\");\n#endif\n#ifdef SAFE_LENGTH\n      SB_CHK_ERR(v->n_elem != A->n_cols, abort(),\n          \"sb_mat_sum: v and A must have same number of columns\");\n#endif\n      sb_vec_set_zero(v);\n      for (size_t a = 0; a < n_rows; ++a) {\n        cblas_daxpy(n_cols, 1., A_data + a, n_rows, v_data, 1);\n      }\n      break;\n    case 'r':\n#ifdef SAFE_LAYOUT\n      SB_CHK_ERR(v->layout != 'c', abort(),\n          \"sb_mat_sum: v must be a column vector\");\n#endif\n#ifdef SAFE_LENGTH\n      SB_CHK_ERR(v->n_elem != A->n_rows, abort(),\n          \"sb_mat_sum: v and A must have same number of rows\");\n#endif\n      sb_vec_set_zero(v);\n      for (size_t a = 0; a < n_cols; ++a) {\n        cblas_daxpy(n_rows, 1., A_data + a * n_rows, 1, v_data, 1);\n      }\n      break;\n    default:\n      SB_CHK_ERR(true, abort(), \"sb_mat_sum: dir must 'c' or 'r'\");\n      break;\n  }\n#ifdef SAFE_FINITE\n  SB_CHK_ERR(!sb_vec_is_finite(v), abort(), \"sb_mat_sum: elements not finite\");\n#endif\n  return v;\n}\n\n/// Converts the column vector `*v` into a matrix with the indicated number of\n/// rows and columns. The number of elements is preserved. NOTE: `*v` is freed\n/// before the function returns and is set to `NULL`. The returned matrix\n/// should be freed as usual.\n///\n/// # Parameters\n/// - `v`: pointer to pointer to the vector\n/// - `n_rows`: number of rows of the returned matrix\n/// - `n_cols`: number of columns of the returned matrix\n///\n/// # Returns\n/// A pointer to a matrix containing the elements of `*v` in column-major order\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `*v` is not `NULL`\n/// - `SAFE_LAYOUT`: `*v` is a column vector\n/// - `SAFE_LENGTH`: the number of elements in `*v` is `n_rows * n_cols`\n///\n/// # Examples\n/// ```\n/// #include <assert.h>\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.};\n///   sb_vec * v = sb_vec_of_arr(a, 9, 'c');\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n/// \n///   // A is equal to B\n///   sb_mat * B = sb_vec_to_mat(&v, 3, 3);\n///   assert(sb_mat_is_equal(A, B));\n///\n///   SB_MAT_FREE_ALL(A, B);\n///   //SB_VEC_FREE_ALL(v); // <-- double free\n/// }\n/// ```\nsb_mat * sb_vec_to_mat(sb_vec ** v, size_t n_rows, size_t n_cols) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!(*v), abort(), \"sb_vec_to_mat: *v cannot be NULL\");\n#endif\n#ifdef SAFE_LAYOUT\n  SB_CHK_ERR((*v)->layout != 'c', abort(),\n      \"sb_vec_to_mat: *v must be a column vector\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR((*v)->n_elem != n_rows * n_cols, abort(),\n      \"sb_vec_to_mat: number of elements must be preserved\");\n#endif\n  sb_mat * out = malloc(sizeof(sb_mat));\n  SB_CHK_ERR(!out, return NULL, \"sb_vec_to_mat: failed to allocate matrix\");\n\n  out->n_rows = n_rows;\n  out->n_cols = n_cols;\n  out->n_elem = (*v)->n_elem;\n  out->data   = (*v)->data;\n\n  free(*v);\n  *v = NULL;\n  return out;\n}\n\n/// Converts the matrix `A` into a column vector. The number of elements is\n/// preserved. NOTE: `*A` is freed before the function returns and is set to\n/// `NULL`, but the returned vector should be freed as usual.\n///\n/// # Parameters\n/// - `A`: pointer to pointer to the matrix\n///\n/// # Returns\n/// A pointer to a vector containing the elements of `*A` in column-major order\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `*A` is not `NULL`\n///\n/// # Examples\n/// ```\n/// #include <assert.h>\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.};\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n///   sb_vec * v = sb_vec_of_arr(a, 9, 'c');\n/// \n///   // v is equal to w\n///   sb_vec * w = sb_mat_to_sb_vec(&A);\n///   assert(sb_vec_is_equal(v, w));\n///\n///   SB_VEC_FREE_ALL(v, w);\n///   //SB_MAT_FREE_ALL(A); // <-- double free\n/// }\n/// ```\nsb_vec * sb_mat_to_vec(sb_mat ** A) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!(*A), abort(), \"sb_mat_to_vec: *A cannot be NULL\");\n#endif\n  sb_vec * out = malloc(sizeof(sb_vec));\n  SB_CHK_ERR(!out, return NULL, \"sb_mat_to_vec: failed to allocate vector\");\n\n  out->n_elem = (*A)->n_elem;\n  out->data   = (*A)->data;\n  out->layout = 'c';\n\n  free(*A);\n  *A = NULL;\n  return out;\n}\n\n/// Reshapes the matrix `A` to have the indicated number of rows and columns\n/// with the elements in column-major order. The number of elements must be\n/// preserved.\n///\n/// # Parameters\n/// - `A`: pointer to the matrix\n/// - `n_rows`: number of rows in the returned matrix\n/// - `n_cols`: number of columns in the returned matrix\n///\n/// # Returns\n/// A copy of `A`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `A` is not `NULL`\n/// - `SAFE_LENGTH`: the number of elements in `A` is `n_rows * n_cols`\n///\n/// # Examples\n/// ```\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4.};\n///   sb_mat * A = sb_mat_of_arr(a, 4, 2);\n///   sb_mat * B = sb_mat_of_arr(a, 2, 4);\n/// \n///   // A is reshaped to equal B\n///   sb_mat_reshape(A, 2, 4);\n///   assert(sb_mat_is_equal(A, B));\n///\n///   SB_MAT_FREE_ALL(A, B);\n/// }\n/// ```\nsb_mat * sb_mat_reshape(sb_mat * A, size_t n_rows, size_t n_cols) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_reshape: A cannot be NULL\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(A->n_elem != n_rows * n_cols, abort(),\n      \"sb_mat_reshape: number of elements must be preserved\");\n#endif\n  A->n_rows = n_rows;\n  A->n_cols = n_cols;\n  return A;\n}\n\n/// Transposes the matrix `A` using a memory allocation for scratch space. NOTE:\n/// Since the matrix multiplication functions allow the matrix to be transposed\n/// at lower cost, this function is usually unnecesary.\n///\n/// # Parameters\n/// - `A`: pointer to the matrix\n///\n/// # Returns\n/// A copy of `A`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `A` is not `NULL`\n///\n/// # Examples\n/// ```\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4.};\n///   sb_mat * A = sb_mat_of_arr(a, 4, 2);\n/// \n///   // A is transposed\n///   sb_mat_print(A, \"A before: \", \"%g\");\n///   sb_mat_trans(A);\n///   sb_mat_print(A, \"A after: \", \"%g\");\n///\n///   SB_MAT_FREE_ALL(A);\n/// }\n/// ```\nsb_mat * sb_mat_trans(sb_mat * A) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_trans: A cannot be NULL\");\n#endif\n  size_t n_elem = A->n_elem;\n  double * T_data = malloc(n_elem * sizeof(double));\n  SB_CHK_ERR(!T_data, return A, \"sb_mat_trans: failed to allocate memory\");\n\n  size_t n_rows = A->n_rows;\n  size_t n_cols = A->n_cols;\n  double * A_data = A->data;\n  for (size_t a = 0; a < n_rows; ++a) {\n    cblas_dcopy(n_cols, A_data + a, n_rows, T_data + a * n_cols, 1);\n  }\n\n  A->n_rows = n_cols;\n  A->n_cols = n_rows;\n  A->data = T_data;\n  free(A_data);\n\n  return A;\n}\n\n/// Checks the matrices `A` and `B` for equality of elements. Matrices must\n/// have the same number of rows and columns.\n///\n/// # Parameters\n/// - `A`: pointer to the first matrix\n/// - `B`: pointer to the second matrix\n///\n/// # Returns\n/// `1` if `A` and `B` are equal, and `0` otherwise\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `A` and `B` are not `NULL`\n/// - `SAFE_LENGTH`: `A` and `B` have the same number of rows and columns\n/// - `SAFE_FINITE`: elements of `A` and `B` are finite\n///\n/// # Examples\n/// ```\n/// #include <assert.h>\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2., 8.};\n///   sb_mat * A = sb_mat_of_arr(a,     3, 3);\n///   sb_mat * B = sb_mat_of_arr(a + 1, 3, 3);\n/// \n///   // A and B are equal after sb_mat_memcpy\n///   assert(!sb_mat_is_equal(A, B));\n///   sb_mat_memcpy(B, A);\n///   assert(sb_mat_is_equal(A, B));\n///\n///   SB_MAT_FREE_ALL(A, B);\n/// }\n/// ```\nint sb_mat_is_equal(const sb_mat * restrict A, const sb_mat * restrict B) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_is_equal: A cannot be NULL\");\n  SB_CHK_ERR(!B, abort(), \"sb_mat_is_equal: B cannot be NULL\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(A->n_rows != B->n_rows, abort(),\n      \"sb_mat_is_equal: A and B must have same number of rows\");\n  SB_CHK_ERR(A->n_cols != B->n_cols, abort(),\n      \"sb_mat_is_equal: A and B must have same number of columns\");\n#endif\n  double * A_data = A->data;\n  double * B_data = B->data;\n  for (size_t a = 0; a < A->n_elem; ++a) {\n#ifdef SAFE_FINITE\n    SB_CHK_ERR(!isfinite(A_data[a]), abort(), \"sb_mat_is_equal: A is not finite\");\n    SB_CHK_ERR(!isfinite(B_data[a]), abort(), \"sb_mat_is_equal: B is not finite\");\n#endif\n    if (A_data[a] != B_data[a]) {\n      return 0;\n    }\n  }\n  return 1;\n}\n\n/// Checks if all elements of the matrix `A` are zero.\n///\n/// # Parameters\n/// - `A`: pointer to the matrix\n///\n/// # Returns\n/// `1` if all elements of `A` are zero, and `0` otherwise\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `A` is not `NULL`\n///\n/// # Examples\n/// ```\n/// #include <assert.h>\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.};\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n/// \n///   // A is zero after sb_mat_set_zero\n///   assert(!sb_mat_is_zero(A));\n///   sb_mat_set_zero(A);\n///   assert(sb_mat_is_zero(A));\n///\n///   SB_MAT_FREE_ALL(A);\n/// }\n/// ```\nint sb_mat_is_zero(const sb_mat * A) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_is_zero: A cannot be NULL\");\n#endif\n  double * data = A->data;\n  for (size_t a = 0; a < A->n_elem; ++a) {\n    if (data[a] != 0.) {\n      return 0;\n    }\n  }\n  return 1;\n}\n\n/// Checks if all elements of the matrix `A` are positive.\n///\n/// # Parameters\n/// - `A`: pointer to the matrix\n///\n/// # Returns\n/// `1` if all elements of `A` are positive, and `0` otherwise\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `A` is not `NULL`\n/// - `SAFE_FINITE`: elements of `A` are finite\n///\n/// # Examples\n/// ```\n/// #include <assert.h>\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   double a[] = {1., -4., 2., -8., 5., 7., 1., 4., -2.};\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n/// \n///   // A is positive after sb_mat_abs\n///   assert(!sb_mat_is_pos(A));\n///   sb_mat_abs(A);\n///   assert(sb_mat_is_pos(A));\n///\n///   SB_MAT_FREE_ALL(A);\n/// }\n/// ```\nint sb_mat_is_pos(const sb_mat * A) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_is_pos: A cannot be NULL\");\n#endif\n  double * data = A->data;\n  for (size_t a = 0; a < A->n_elem; ++a) {\n#ifdef SAFE_FINITE\n    SB_CHK_ERR(!isfinite(data[a]), abort(), \"sb_mat_is_pos: A is not finite\");\n#endif\n    if (data[a] <= 0.) {\n      return 0;\n    }\n  }\n  return 1;\n}\n\n/// Checks if all elements of the matrix `A` are negative.\n///\n/// # Parameters\n/// - `A`: pointer to the matrix\n///\n/// # Returns\n/// `1` if all elements of `A` are negative, and `0` otherwise\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `A` is not `NULL`\n/// - `SAFE_FINITE`: elements of `A` are finite\n///\n/// # Examples\n/// ```\n/// #include <assert.h>\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   double a[] = {1., -4., 2., -8., 5., 7., 1., 4., -2.};\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n/// \n///   // A is negative after\n///   assert(!sb_mat_is_neg(A));\n///   sb_mat_smul(sb_mat_abs(A), -1.);\n///   assert(sb_mat_is_neg(A));\n///\n///   SB_MAT_FREE_ALL(A);\n/// }\n/// ```\nint sb_mat_is_neg(const sb_mat * A) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_is_neg: A cannot be NULL\");\n#endif\n  double * data = A->data;\n  for (size_t a = 0; a < A->n_elem; ++a) {\n#ifdef SAFE_FINITE\n    SB_CHK_ERR(!isfinite(data[a]), abort(), \"sb_mat_is_neg: A is not finite\");\n#endif\n    if (data[a] >= 0.) {\n      return 0;\n    }\n  }\n  return 1;\n}\n\n/// Checks if all elements of the matrix `A` are nonnegative.\n///\n/// # Parameters\n/// - `A`: pointer to the matrix\n///\n/// # Returns\n/// `1` if all elements of `A` are nonnegative, and `0` otherwise\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `A` is not `NULL`\n/// - `SAFE_FINITE`: elements of `A` are finite\n///\n/// # Examples\n/// ```\n/// #include <assert.h>\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   double a[] = {0., -4., 2., -8., 5., 7., 1., 4., -2.};\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n/// \n///   // A is nonnegative after\n///   assert(!sb_mat_is_nonneg(A));\n///   sb_mat_abs(A);\n///   assert( sb_mat_is_nonneg(A));\n///\n///   SB_MAT_FREE_ALL(A);\n/// }\n/// ```\nint sb_mat_is_nonneg(const sb_mat * A) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_is_nonneg: A cannot be NULL\");\n#endif\n  double * data = A->data;\n  for (size_t a = 0; a < A->n_elem; ++a) {\n#ifdef SAFE_FINITE\n    SB_CHK_ERR(!isfinite(data[a]), abort(), \"sb_mat_is_nonneg: A is not finite\");\n#endif\n    if (data[a] < 0.) {\n      return 0;\n    }\n  }\n  return 1;\n}\n\n/// Checks if all elements of the matrix `A` are not infinite or `NaN`.\n///\n/// # Parameters\n/// - `A`: pointer to the matrix\n///\n/// # Returns\n/// `1` if all elements of `A` are not infinite or `NaN`, and `0` otherwise\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `A` is not `NULL`\n///\n/// # Examples\n/// ```\n/// #include <assert.h>\n/// #include <math.h>\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   double a[] = {1., INFINITY, 2., 8., 5., 7., 1., 4., 2.};\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n/// \n///   assert(!sb_mat_is_finite(A));\n///   sb_mat_set(A, 1, 0, NAN);\n///   assert(!sb_mat_is_finite(A));\n///   sb_mat_set(A, 1, 0, 4.);\n///   assert( sb_mat_is_finite(A));\n///\n///   SB_MAT_FREE_ALL(A);\n/// }\n/// ```\nint sb_mat_is_finite(const sb_mat * A) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_is_finite: A cannot be NULL\");\n#endif\n  double * data = A->data;\n  for (size_t a = 0; a < A->n_elem; ++a) {\n    if (!isfinite(data[a])) {\n      return 0;\n    }\n  }\n  return 1;\n}\n\n/// Finds the value of the maximum element of `A`.\n///\n/// # Parameters\n/// - `A`: pointer to the matrix\n///\n/// # Returns\n/// Value of the maximum element\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `A` is not `NULL`\n/// - `SAFE_LENGTH`: number of elements is nonzero\n/// - `SAFE_FINITE`: elements of `A` are finite\n///\n/// # Examples\n/// ```\n/// #include <assert.h>\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.};\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n/// \n///   // maximum value of A is 8.\n///   assert(sb_mat_max(A) == 8.);\n///\n///   SB_MAT_FREE_ALL(A);\n/// }\n/// ```\ndouble sb_mat_max(const sb_mat * A) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_max: A cannot be NULL\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(A->n_elem == 0, abort(), \"sb_mat_max: n_elem must be nonzero\");\n#endif\n  double * data = A->data;\n  double max_val = -INFINITY;\n  for (size_t a = 0; a < A->n_elem; ++a) {\n#ifdef SAFE_FINITE\n    SB_CHK_ERR(!isfinite(data[a]), abort(), \"sb_mat_max: A is not finite\");\n#endif\n    if (data[a] > max_val) {\n      max_val = data[a];\n    }\n  }\n  return max_val;\n}\n\n/// Finds the value of the minimum element of `A`.\n///\n/// # Parameters\n/// - `A`: pointer to the matrix\n///\n/// # Returns\n/// Value of the minimum element\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `A` is not `NULL`\n/// - `SAFE_LENGTH`: number of elements is nonzero\n/// - `SAFE_FINITE`: elements of `A` are finite\n///\n/// # Examples\n/// ```\n/// #include <assert.h>\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.};\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n/// \n///   // value of min is 1\n///   assert(sb_mat_min(A) == 1.);\n///\n///   SB_MAT_FREE_ALL(A);\n/// }\n/// ```\ndouble sb_mat_min(const sb_mat * A) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_min: A cannot be NULL\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(A->n_elem == 0, abort(), \"sb_mat_min: n_elem must be nonzero\");\n#endif\n  double * data = A->data;\n  double min_val = INFINITY;\n  for (size_t a = 0; a < A->n_elem; ++a) {\n#ifdef SAFE_FINITE\n    SB_CHK_ERR(!isfinite(data[a]), abort(), \"sb_mat_min: A is not finite\");\n#endif\n    if (data[a] < min_val) {\n      min_val = data[a];\n    }\n  }\n  return min_val;\n}\n\n/// Finds the maximum absolute value of the elements of `A`.\n///\n/// # Parameters\n/// - `A`: pointer to the matrix\n///\n/// # Returns\n/// Maximum absolute value of the elements\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `A` is not `NULL`\n/// - `SAFE_LENGTH`: number of elements is nonzero\n/// - `SAFE_FINITE`: elements of `A` are finite\n///\n/// # Examples\n/// ```\n/// #include <assert.h>\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   double a[] = {1., -4., 2., -8., 5., -7., 1., -4., 2.};\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n/// \n///   // maximum absolute value of A is 8.\n///   assert(sb_mat_abs_max(A) == 8.);\n///\n///   SB_MAT_FREE_ALL(A);\n/// }\n/// ```\ndouble sb_mat_abs_max(const sb_mat * A) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_abs_max: A cannot be NULL\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(A->n_elem == 0, abort(), \"sb_mat_abs_max: n_elem must be nonzero\");\n#endif\n  double * data = A->data;\n  size_t index = cblas_idamax(A->n_elem, data, 1);\n#ifdef SAFE_FINITE\n  SB_CHK_ERR(!isfinite(data[index]), abort(), \"sb_mat_abs_max: A is not finite\");\n#endif\n  return fabs(data[index]);\n}\n\n/// Finds the index of the maximum element of `A`.\n///\n/// # Parameters\n/// - `A`: pointer to the matrix\n///\n/// # Returns\n/// Index of the maximum element\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `A` is not `NULL`\n/// - `SAFE_LENGTH`: number of elements is nonzero\n/// - `SAFE_FINITE`: elements of `A` are finite\n///\n/// # Examples\n/// ```\n/// #include <assert.h>\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.};\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n/// \n///   // index of max is 3\n///   assert(sb_mat_max_index(A) == 3);\n///\n///   SB_MAT_FREE_ALL(A);\n/// }\n/// ```\nsize_t sb_mat_max_index(const sb_mat * A) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_max_index: A cannot be NULL\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(A->n_elem == 0, abort(), \"sb_mat_max_index: n_elem must be nonzero\");\n#endif\n  double * data = A->data;\n  double max_val = -INFINITY;\n  size_t max_ind = 0;\n  for (size_t a = 0; a < A->n_elem; ++a) {\n#ifdef SAFE_FINITE\n    SB_CHK_ERR(!isfinite(data[a]), abort(), \"sb_mat_max_index: A is not finite\");\n#endif\n    if (data[a] > max_val) {\n      max_val = data[a];\n      max_ind = a;\n    }\n  }\n  return max_ind;\n}\n\n/// Finds the index of the minimum element of `A`.\n///\n/// # Parameters\n/// - `A`: pointer to the matrix\n///\n/// # Returns\n/// Index of the minimum element\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `A` is not `NULL`\n/// - `SAFE_LENGTH`: number of elements is nonzero\n/// - `SAFE_FINITE`: elements of `A` are finite\n///\n/// # Examples\n/// ```\n/// #include <assert.h>\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.};\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n/// \n///   // index of min is 0\n///   assert(sb_mat_min_index(A) == 0);\n///\n///   SB_MAT_FREE_ALL(A);\n/// }\n/// ```\nsize_t sb_mat_min_index(const sb_mat * A) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_min_index: A cannot be NULL\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(A->n_elem == 0, abort(), \"sb_mat_min_index: n_elem must be nonzero\");\n#endif\n  double * data = A->data;\n  double min_val = INFINITY;\n  size_t min_ind = 0;\n  for (size_t a = 0; a < A->n_elem; ++a) {\n#ifdef SAFE_FINITE\n    SB_CHK_ERR(!isfinite(data[a]), abort(), \"sb_mat_min_index: A is not finite\");\n#endif\n    if (data[a] < min_val) {\n      min_val = data[a];\n      min_ind = a;\n    }\n  }\n  return min_ind;\n}\n\n/// Finds the index of the maximum absolute value of the elements of `A`.\n///\n/// # Parameters\n/// - `A`: pointer to the matrix\n///\n/// # Returns\n/// Index of the maximum absolute value of the elements\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `A` is not `NULL`\n/// - `SAFE_LENGTH`: number of elements is nonzero\n///\n/// # Examples\n/// ```\n/// #include <assert.h>\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n///\n/// int main(void) {\n///   double a[] = {1., -4., 2., -8., 5., -7., 1., -4., 2.};\n///   sb_mat * A = sb_mat_of_arr(a, 3, 3);\n/// \n///   // index of the maximum absolute value of A is 3\n///   assert(sb_mat_abs_max_index(A) == 3);\n///\n///   SB_MAT_FREE_ALL(A);\n/// }\n/// ```\nsize_t sb_mat_abs_max_index(const sb_mat * A) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!A, abort(), \"sb_mat_abs_max_index: A cannot be NULL\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(A->n_elem == 0, abort(),\n      \"sb_mat_abs_max_index: n_elem must be nonzero\");\n#endif\n  return cblas_idamax(A->n_elem, A->data, 1);\n}\n\nextern inline double   sb_mat_get(const sb_mat * A, size_t i, size_t j);\nextern inline void     sb_mat_set(sb_mat * A, size_t i, size_t j, double x);\nextern inline double * sb_mat_ptr(sb_mat * A, size_t i, size_t j);\n", "meta": {"hexsha": "1cb90c990c4d891ea09b4bab9cb254341b483955", "size": 98588, "ext": "c", "lang": "C", "max_stars_repo_path": "src/matrix.c", "max_stars_repo_name": "harharkh/sb_desc", "max_stars_repo_head_hexsha": "e2fa146692aa4417e77366ce5ba85d9fdecc2a9c", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2019-07-08T22:34:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T20:06:47.000Z", "max_issues_repo_path": "src/matrix.c", "max_issues_repo_name": "harharkh/sb_desc", "max_issues_repo_head_hexsha": "e2fa146692aa4417e77366ce5ba85d9fdecc2a9c", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-07-10T06:53:41.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-10T06:53:41.000Z", "max_forks_repo_path": "src/matrix.c", "max_forks_repo_name": "harharkh/sb_desc", "max_forks_repo_head_hexsha": "e2fa146692aa4417e77366ce5ba85d9fdecc2a9c", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9199178645, "max_line_length": 93, "alphanum_fraction": 0.5914005761, "num_tokens": 31109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4035668537353745, "lm_q2_score": 0.07369627174050788, "lm_q1q2_score": 0.029741372518343957}}
{"text": "/// \\file linalg.h\n/// \\brief Wrapper for including CBLAS and LAPACKE\n\n#ifndef LINALG_H\n#define LINALG_H\n\n#define LAPACK_DISABLE_NAN_CHECK \n\n#ifdef USE_MKL\n\n#include <mkl_cblas.h>\n#include <mkl_lapacke.h>\n\n#else\n\n// generic include\n#include <cblas.h>\n#include <lapacke.h>\n\n#endif\n\n\n#endif\n", "meta": {"hexsha": "c905c047ff1e4dfb86b30e0c496adf52029e0499", "size": 289, "ext": "h", "lang": "C", "max_stars_repo_path": "include/linalg.h", "max_stars_repo_name": "cmendl/tensor_networks", "max_stars_repo_head_hexsha": "da47a4699b1efcd6d5854760564f1b8b3c4b094b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2018-12-28T19:11:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T19:31:31.000Z", "max_issues_repo_path": "include/linalg.h", "max_issues_repo_name": "cmendl/tensor_networks", "max_issues_repo_head_hexsha": "da47a4699b1efcd6d5854760564f1b8b3c4b094b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-02-18T00:16:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-18T00:16:55.000Z", "max_forks_repo_path": "include/linalg.h", "max_forks_repo_name": "cmendl/tensor_networks", "max_forks_repo_head_hexsha": "da47a4699b1efcd6d5854760564f1b8b3c4b094b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-04-08T13:10:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-17T19:31:47.000Z", "avg_line_length": 12.0416666667, "max_line_length": 50, "alphanum_fraction": 0.7335640138, "num_tokens": 87, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.06656919360012363, "lm_q1q2_score": 0.02965854187262238}}
{"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\r\n * Copyright 2018 - Matteo Ragni, Matteo Cocetti - University of Trento\r\n *\r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n *\r\n * The above copyright notice and this permission notice shall be included in\r\n * all copies or substantial portions of the Software.\r\n *\r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\r\n\r\n#ifndef LIBNEWTON_H_\r\n#define LIBNEWTON_H_\r\n\r\n#include <lapacke.h>\r\n#include <cblas.h>\r\n\r\n/**\r\n * @brief Jacobian Callback for the Newton algorithm\r\n * \r\n * The callback receivs the current input, the current control, and the list of\r\n * parameter vectors. It should store the first argument the Jacobian matrix (stored as an array).\r\n * To select the ordering in the matrix, you must select the correct ordering in newton_options \r\n * structure, at the ordering input.\r\n * @param df output vector (vectorized Jacobian matrix)\r\n * @param t current time for evaluation\r\n * @param x current point for evaluation\r\n * @param u current control for evaluation\r\n * @param p array of parameter vectors\r\n * @param data user space input (simply use it as a pointer casted to void)\r\n */\r\ntypedef void (*newton_jacobian)(\r\n    double *df,\r\n    const double t,\r\n    const double *x,\r\n    const double *u,\r\n    const double **p,\r\n    void *data);\r\n\r\n/**\r\n * @brief Vector Field Callback for the Newton algorithm\r\n * \r\n * The callback receivs the current input, the current control, and the list of\r\n * parameter vectors. It should store the first argument the function output vector.\r\n * @param df output vector (vectorized Jacobian matrix)\r\n * @param t current time for evaluation\r\n * @param x current point for evaluation\r\n * @param u current control for evaluation\r\n * @param p array of parameter vectors\r\n * @param data user space input (simply use it as a pointer casted to void)\r\n */\r\ntypedef void (*newton_function)(\r\n    double *f,\r\n    const double t,\r\n    const double *x,\r\n    const double *u,\r\n    const double **p,\r\n    void *data);\r\n\r\n/**\r\n * @brief Options for the Newton Algorithm\r\n * \r\n * This structure contains all the options for the Newton algorithm, alongside the callbacks.\r\n * The structure will be modified by the algorithm with some debug information, such as number\r\n * of iterations, tolerances and ordering for the jacobian matrix.\r\n */\r\ntypedef struct newton_options {\r\n  lapack_int ordering; /**< Should be LAPACK_ROW_MAJOR or LAPACK_COL_MAJOR */\r\n  lapack_int f_size;   /**< Vector field size */\r\n  lapack_int x_size;   /**< Variable vector size */\r\n  double f_tol;        /**< Stopping tolerance for the zero. \r\n                              At the end will contain the 2 norm of the \r\n                              vector field in the solution */\r\n  double x_tol;        /**< Stopping tolerance for the x vector step.\r\n                              At the end will contain the 2 norm of the last update step */\r\n  lapack_int max_iter; /**< Maximum number of iteration,\r\n                              At the end will contain the number of step executed  */\r\n  newton_function f;   /**< Pointer to vector field callback */\r\n  newton_jacobian df;  /**<  Pointer to Jacobian callback */\r\n} newton_options;\r\n\r\n/**\r\n * @brief Error code returned by the algorithm\r\n */\r\ntypedef enum newton_ret {\r\n  NEWTON_F_TOL = 0,         /**< (0) The solver reached the required tolerance limit for the vector field */\r\n  NEWTON_X_TOL,             /**< (1) The last step for solution update was less than the minimum */\r\n  NEWTON_MAX_ITER,          /**< (2) Maximum number of iterations reached */\r\n  NEWTON_SINGULAR_JACOBIAN, /**< (3 LAPACKE) The jacobian is singular */\r\n  NEWTON_ILLEGAL_JACOBIAN,  /**< (4 LAPACKE) Illegal jacobian */\r\n  NEWTON_MALLOC_ERROR,      /**< (5) Cannot allocate memory */\r\n  NEWTON_GENERIC_ERROR      /**< (6) Generic error in the execution of the algorithm */\r\n} newton_ret;\r\n\r\n/**\r\n * @brief Boolean implementation\r\n */\r\ntypedef enum newton_bool {\r\n  NEWTON_FALSE = 0, /**< False */\r\n  NEWTON_TRUE       /**< True */\r\n} newton_bool;\r\n\r\n/**\r\n * @brief Executes the Newton algorithm for root finding\r\n * \r\n * Executes the Newton algorithm for root finding. The step Performed is:\r\n * \\f{\r\n *   x_{k+1} - x_{k} = -\\nabla F^{-1}(x_k, u, p) F(x_k, u, p)\r\n * \\f}\r\n * and the solution is found by using DGELS defined in LAPACK library.\r\n * The stopping conditions are:\r\n *  * Number of iterations bigger than maximum allowed (specified in newton_options)\r\n *  * \\f$ |x_{k+1} - x_k| \\leq x_{tol}\\f$\r\n *  * \\f$ |f(x_k, u, p)| \\leq y_{tol}\\f$\r\n * and the function and jacobian are evaluated through callbacks. On exit, the values \r\n * inside the option structure are update for debuggin purposes (this is why Newton \r\n * options is not a const pointer). It returns a status enum.\r\n * @param opt option structure\r\n * @param x root position and initial condition. Will be modified\r\n * @param u control action input. It can be NULL.\r\n * @param p parameter array of vectors. It can be NULL.\r\n * @param data space for user data. Will be passed to callbacks. It can be NULL\r\n * @return a status exit code as described in newton_ret enum.\r\n */\r\nnewton_ret newton_solve(\r\n    newton_options *opt,\r\n    const double t,\r\n    double *x,\r\n    const double *u,\r\n    const double **p,\r\n    void *data);\r\n\r\n#endif\r\n", "meta": {"hexsha": "a098d32ea181b719f94091ce4350af5e06308d8e", "size": 6251, "ext": "h", "lang": "C", "max_stars_repo_path": "libnewton.h", "max_stars_repo_name": "MatteoRagni/libeuler", "max_stars_repo_head_hexsha": "7dd73c1b383b6c32086da4880a82326ebf47b71b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-03-05T07:42:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-22T02:16:51.000Z", "max_issues_repo_path": "libnewton.h", "max_issues_repo_name": "MatteoRagni/libeuler", "max_issues_repo_head_hexsha": "7dd73c1b383b6c32086da4880a82326ebf47b71b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libnewton.h", "max_forks_repo_name": "MatteoRagni/libeuler", "max_forks_repo_head_hexsha": "7dd73c1b383b6c32086da4880a82326ebf47b71b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.1103448276, "max_line_length": 109, "alphanum_fraction": 0.6667733163, "num_tokens": 1488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.06656918804457732, "lm_q1q2_score": 0.029401813368302124}}
{"text": "// Copyright 2019 John McFarlane\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#ifndef WSS_BOARD_H\n#define WSS_BOARD_H\n\n#include \"coord.h\"\n#include \"grid.h\"\n#include \"load_buffer.h\"\n\n#include <ssize.h>\n#include <wss_assert.h>\n\n#include <fmt/printf.h>\n#include <gsl/string_span>\n\n#include <array>\n#include <optional>\n#include <unordered_map>\n\ntemplate<typename T>\nclass board {\npublic:\n    board(board&&) = default;\n\n    explicit board(int init_edge)\n            :edge{init_edge}, cells{std::make_unique<T[]>(edge*edge)} { }\n\n    int size() const\n    {\n        return edge;\n    }\n\n    T const& cell(coord c) const\n    {\n        WSS_ASSERT(c[0]>=0);\n        WSS_ASSERT(c[0]<edge);\n        WSS_ASSERT(c[1]>=0);\n        WSS_ASSERT(c[1]<edge);\n\n        return cells.get()[c[0]+c[1]*edge];\n    }\n\n    T& cell(coord c)\n    {\n        WSS_ASSERT(c[0]>=0);\n        WSS_ASSERT(c[0]<edge);\n        WSS_ASSERT(c[1]>=0);\n        WSS_ASSERT(c[1]<edge);\n\n        return cells.get()[c[0]+c[1]*edge];\n    }\n\nprivate:\n    int edge;\n    std::unique_ptr<T[]> cells;\n};\n\ntemplate<typename CellType, typename TextToCell>\nstd::optional<board<CellType>> make_board(\n        std::vector<std::vector<char>> const& lines,\n        TextToCell const& mapping)\n{\n    auto edge{ssize(lines)};\n    board<CellType> result{int(edge)};\n\n    for (auto row_index{0}; row_index!=edge; ++row_index) {\n        auto const& line{lines[row_index]};\n        auto const num_fields{ssize(line)};\n        if (num_fields!=edge) {\n            fmt::print(stderr,\n                    \"error: input row #{} has {} fields, expected {}.\\n\",\n                    row_index+1, num_fields, edge);\n            return std::nullopt;\n        }\n\n        for (auto column_index{0}; column_index!=edge; ++column_index) {\n            auto const field{line[column_index]};\n            auto const cell_found{mapping(field)};\n            if (!cell_found) {\n                fmt::print(\n                        stderr,\n                        \"Unrecognised field, '{}', in row #{}, column #{}.\\n\",\n\t\t\t\t\t\t(char)field,\n                        row_index+1, column_index+1);\n                return std::nullopt;\n            }\n\n            result.cell(coord{column_index,row_index}) = *cell_found;\n        }\n    }\n\n    return result;\n}\n\ntemplate<typename CellType, typename TextToCell>\nstd::optional<board<CellType>> load_board(\n        gsl::cstring_span<> filename,\n        TextToCell const& mapping)\n{\n    auto const buffer{load_buffer(filename)};\n    if (!buffer) {\n        return std::nullopt;\n    }\n    \n    auto const fields{parse_grid(*buffer)};\n    \n    return make_board<CellType>(fields, mapping);\n}\n\ntemplate<typename T>\nvoid transpose(board<T>& b)\n{\n    auto const edge = ssize(b);\n    for (auto row = 0; row != edge; ++row)\n    {\n        for (auto column = 0; column != row; ++ column)\n        {\n            std::swap(b.cell(coord{column, row}), b.cell(coord{row, column}));\n        }\n    }\n}\n\n#endif //WSS_BOARD_H\n", "meta": {"hexsha": "7afc8b4a451028fa9ff7fde956dd358ff051df7d", "size": 3463, "ext": "h", "lang": "C", "max_stars_repo_path": "src/play/board.h", "max_stars_repo_name": "johnmcfarlane/wss", "max_stars_repo_head_hexsha": "2772e303f79360056dd9f879198e6af207397dcc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-02-04T09:40:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T17:23:02.000Z", "max_issues_repo_path": "src/play/board.h", "max_issues_repo_name": "johnmcfarlane/wss", "max_issues_repo_head_hexsha": "2772e303f79360056dd9f879198e6af207397dcc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 21.0, "max_issues_repo_issues_event_min_datetime": "2019-10-28T22:07:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-18T23:55:35.000Z", "max_forks_repo_path": "src/play/board.h", "max_forks_repo_name": "johnmcfarlane/wss", "max_forks_repo_head_hexsha": "2772e303f79360056dd9f879198e6af207397dcc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-23T18:04:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T18:04:41.000Z", "avg_line_length": 25.4632352941, "max_line_length": 78, "alphanum_fraction": 0.5925498123, "num_tokens": 856, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.059210246175955, "lm_q1q2_score": 0.029373837769345382}}
{"text": "/*******************************************************************************\n*\n*       This file is part of the General Hidden Markov Model Library,\n*       GHMM version __VERSION__, see http://ghmm.org\n*\n*       Filename: ghmm/ghmm/randvar.c\n*       Authors:  Bernhard Knab, Benjamin Rich, Janne Grunau\n*\n*       Copyright (C) 1998-2004 Alexander Schliep\n*       Copyright (C) 1998-2001 ZAIK/ZPR, Universitaet zu Koeln\n*       Copyright (C) 2002-2004 Max-Planck-Institut fuer Molekulare Genetik,\n*                               Berlin\n*\n*       Contact: schliep@ghmm.org\n*\n*       This library is free software; you can redistribute it and/or\n*       modify it under the terms of the GNU Library General Public\n*       License as published by the Free Software Foundation; either\n*       version 2 of the License, or (at your option) any later version.\n*\n*       This library is distributed in the hope that it will be useful,\n*       but WITHOUT ANY WARRANTY; without even the implied warranty of\n*       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n*       Library General Public License for more details.\n*\n*       You should have received a copy of the GNU Library General Public\n*       License along with this library; if not, write to the Free\n*       Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n*\n*\n*       This file is version $Revision: 2310 $\n*                       from $Date: 2013-06-14 10:36:57 -0400 (Fri, 14 Jun 2013) $\n*             last change by $Author: ejb177 $.\n*\n*******************************************************************************/\n\n#ifdef HAVE_CONFIG_H\n#  include \"../config.h\"\n#endif\n\n#include <math.h>\n#include <float.h>\n#include <string.h>\n#ifdef HAVE_LIBPTHREAD\n# include <pthread.h>\n#endif /* HAVE_LIBPTHREAD */\n\n#include \"ghmm.h\"\n#include \"mes.h\"\n#include \"mprintf.h\"\n#include \"randvar.h\"\n#include \"rng.h\"\n\n#ifdef DO_WITH_GSL\n\n# include <gsl/gsl_math.h>\n# include <gsl/gsl_sf_erf.h>\n# include <gsl/gsl_randist.h>\n\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_blas.h>\n\n#endif /* DO_WITH_GSL */\n\n\n#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)\n#else\nstatic double ighmm_erf (double x);\nstatic double ighmm_erfc (double x);\n#endif /* check for ISO C99 */\n\n/* A list of already calculated values of the density function of a \n   N(0,1)-distribution, with x in [0.00, 19.99] */\n#define PDFLEN 2000\n#define X_STEP_PDF 0.01         /* step size */\n#define X_FAKT_PDF 100          /* equivalent to step size */\nstatic double pdf_stdnormal[PDFLEN];\nstatic int pdf_stdnormal_exists = 0;\n\n/* A list of already calulated values PHI of the Gauss distribution is\n   read in, x in [-9.999, 0] */\n#define X_STEP_PHI 0.001        /* step size */\n#define X_FAKT_PHI 1000         /* equivalent to step size */\nstatic double x_PHI_1 = -1.0;\n\n#ifndef M_SQRT1_2\n#define M_SQRT1_2  0.70710678118654752440084436210\n#endif\n\n\n/*============================================================================*/\n/* needed by ighmm_gtail_pmue_interpol */\n\ndouble ighmm_rand_get_xfaktphi ()\n{\n  return X_FAKT_PHI;\n}\n\ndouble ighmm_rand_get_xstepphi ()\n{\n  return X_STEP_PHI;\n}\n\ndouble ighmm_rand_get_philen ()\n{\n#ifdef DO_WITH_GSL\n  return 0 /*PHI_len*/;\n#else\n  return ighmm_rand_get_xPHIless1 () / X_STEP_PHI;\n#endif\n}\n\n\n/*============================================================================*/\ndouble ighmm_rand_get_PHI (double x)\n{\n#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)\n  return (erf (x * M_SQRT1_2) + 1.0) / 2.0;\n#else\n  return (ighmm_erf (x * M_SQRT1_2) + 1.0) / 2.0;\n#endif\n}                               /* randvar_get_PHI */\n\n\n/*============================================================================*/\n/* When is PHI[x,0,1] == 1? */\ndouble ighmm_rand_get_xPHIless1 ()\n{\n# define CUR_PROC \"ighmm_rand_get_xPHIless1\"\n\n  if (x_PHI_1 == -1) {\n    double low, up, half;\n    low = 0;\n    up = 100;\n    while (up - low > 0.001) {\n      half = (low + up) / 2.0;\n      if (ighmm_rand_get_PHI (half) < 1.0)\n        low = half;\n      else\n        up = half;\n    }\n    x_PHI_1 = low;\n  }\n  return (x_PHI_1);\n\n# undef CUR_PROC\n}\n\n/*============================================================================*/\ndouble ighmm_rand_get_1overa (double x, double mean, double u)\n{\n  /* Calulates 1/a(x, mean, u), with a = the integral from x til \\infty over\n     the Gauss density function */\n# define CUR_PROC \"ighmm_rand_get_1overa\"\n\n  double erfc_value;\n\n  if (u <= 0.0) {\n    GHMM_LOG(LCONVERTED, \"u <= 0.0 not allowed\\n\");\n    goto STOP;\n  }\n\n#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)\n  erfc_value = erfc ((x - mean) / sqrt (u * 2));\n#else\n  erfc_value = ighmm_erfc ((x - mean) / sqrt (u * 2));\n#endif\n\n  if (erfc_value <= DBL_MIN) {\n    ighmm_mes (MES_WIN, \"a ~= 0.0 critical! (mue = %.2f, u =%.2f)\\n\", mean, u);\n    return (erfc_value);\n  }\n  else\n    return (2.0 / erfc_value);\n\nSTOP:\n  return (-1.0);\n# undef CUR_PROC\n}                               /* ighmm_rand_get_1overa */\n\n\n/*============================================================================*/\n/* REMARK:\n   The calulation of this density function was testet, by calculating the \n   following integral sum for arbitrary mue and u:\n     for (x = 0, x < ..., x += step(=0.01/0.001/0.0001)) \n       isum += step * ighmm_rand_normal_density_pos(x, mue, u);\n   In each case, the sum \"converged\" evidently towards 1!\n   (BK, 14.6.99)\n   CHANGE:\n   Truncate at -EPS_NDT (const.h), so that x = 0 doesn't lead to a problem.\n   (BK, 15.3.2000)\n*/\ndouble ighmm_rand_normal_density_pos (double x, double mean, double u)\n{\n# define CUR_PROC \"ighmm_rand_normal_density_pos\"\n  return ighmm_rand_normal_density_trunc (x, mean, u, -GHMM_EPS_NDT);\n# undef CUR_PROC\n}                               /* double ighmm_rand_normal_density_pos */\n\n\n/*============================================================================*/\ndouble ighmm_rand_normal_density_trunc(double x, double mean, double u,\n                                       double a)\n{\n# define CUR_PROC \"ighmm_rand_normal_density_trunc\"\n#ifndef DO_WITH_GSL\n  double c;\n#endif /* DO_WITH_GSL */\n\n  if (u <= 0.0) {\n    GHMM_LOG(LERROR, \"u <= 0.0 not allowed\");\n    goto STOP;\n  }\n  if (x < a)\n    return 0.0;\n\n#ifdef DO_WITH_GSL\n  /* move mean to the right position */\n  return gsl_ran_gaussian_tail_pdf(x - mean, a - mean, sqrt(u));\n#else\n  if ((c = ighmm_rand_get_1overa(a, mean, u)) == -1) {\n    GHMM_LOG_QUEUED(LERROR);\n    goto STOP;\n  };\n  return c * ighmm_rand_normal_density(x, mean, u);\n#endif /* DO_WITH_GSL */\n\nSTOP:\n  return -1.0;\n# undef CUR_PROC\n}                               /* double ighmm_rand_normal_density_trunc */\n\n\n/*============================================================================*/\ndouble ighmm_rand_normal_density (double x, double mean, double u)\n{\n# define CUR_PROC \"ighmm_rand_normal_density\"\n#ifndef DO_WITH_GSL\n  double expo;\n#endif\n  if (u <= 0.0) {\n    GHMM_LOG(LCONVERTED, \"u <= 0.0 not allowed\\n\");\n    goto STOP;\n  }\n  /* The denominator is possibly < EPS??? Check that ? */\n#ifdef DO_WITH_GSL\n  /* double gsl_ran_gaussian_pdf (double x, double sigma) */\n  return gsl_ran_gaussian_pdf (x - mean, sqrt (u));\n#else\n  expo = exp (-1 * m_sqr (mean - x) / (2 * u));\n  return (1 / (sqrt (2 * PI * u)) * expo);\n#endif\n\nSTOP:\n  return (-1.0);\n# undef CUR_PROC\n}                               /* double ighmm_rand_normal_density */\n\n\n/*============================================================================*/\n/* covariance matrix is linearized */\ndouble ighmm_rand_binormal_density(const double *x, double *mean, double *cov)\n{\n# define CUR_PROC \"ighmm_rand_binormal_density\"\n  double rho;\n#ifndef DO_WITH_GSL\n  double numerator,part1,part2,part3;\n#endif\n  if (cov[0] <= 0.0 || cov[2 + 1] <= 0.0) {\n    GHMM_LOG(LCONVERTED, \"variance <= 0.0 not allowed\\n\");\n    goto STOP;\n  }\n  rho = cov[1] / ( sqrt (cov[0]) * sqrt (cov[2 + 1]) );\n  /* The denominator is possibly < EPS??? Check that ? */\n#ifdef DO_WITH_GSL\n  /* double gsl_ran_bivariate_gaussian_pdf (double x, double y, double sigma_x,\n                                            double sigma_y, double rho) */\n  return gsl_ran_bivariate_gaussian_pdf (x[0], x[1], sqrt (cov[0]),\n                                         sqrt (cov[2 + 1]), rho);\n#else\n  part1 = (x[0] - mean[0]) / sqrt (cov[0]);\n  part2 = (x[1] - mean[1]) / sqrt (cov[2 + 1]);\n  part3 = m_sqr (part1) - 2 * part1 * part2 + m_sqr (part2);\n  numerator = exp ( -1 * (part3) / ( 2 * (1 - m_sqr(rho)) ) );\n  return (numerator / ( 2 * PI * sqrt(1 - m_sqr(rho)) ));\n#endif\n\nSTOP:\n  return (-1.0);\n# undef CUR_PROC\n}                               /* double ighmm_rand_binormal_density */\n\n/*============================================================================*/\n/* matrices are linearized */\ndouble ighmm_rand_multivariate_normal_density(int length, const double *x, double *mean, double *sigmainv, double det)\n{\n# define CUR_PROC \"ighmm_rand_multivariate_normal_density\"\n  /* multivariate normal density function    */\n  /*\n   *       length     dimension of the random vetor\n   *       x          point at which to evaluate the pdf\n   *       mean       vector of means of size n\n   *       sigmainv   inverse variance matrix of dimension n x n\n   *       det        determinant of covariance matrix\n   */\n\n#ifdef DO_WITH_GSL\n  int i, j;\n  double ax,ay;\n  gsl_vector *ym, *xm, *gmean;\n  gsl_matrix *inv = gsl_matrix_alloc(length, length);\n\n\n  for (i=0; i<length; ++i) {\n    for (j=0; j<length; ++j) {\n      gsl_matrix_set(inv, i, j, sigmainv[i*length+j]);\n    }\n  }\n\n  xm = gsl_vector_alloc(length);\n  gmean = gsl_vector_alloc(length);\n  /*gsl_vector_memcpy(xm, x);*/\n  for (i=0; i<length; ++i) {\n    gsl_vector_set(xm, i, x[i]);\n    gsl_vector_set(gmean, i, mean[i]);\n  }\n\n  gsl_vector_sub(xm, gmean);\n  ym = gsl_vector_alloc(length);\n  gsl_blas_dsymv(CblasUpper, 1.0, inv, xm, 0.0, ym);\n  gsl_matrix_free(inv);\n  gsl_blas_ddot(xm, ym, &ay);\n  gsl_vector_free(xm);\n  gsl_vector_free(ym);\n  ay = exp(-0.5*ay) / sqrt(pow((2*M_PI), length) * det);\n\n  return ay;\n#else\n  /* do without GSL */\n  int i, j;\n  double ay, tempv;\n\n  ay = 0;\n  for (i=0; i<length; ++i) {\n    tempv = 0;\n    for (j=0; j<length; ++j) {\n      tempv += (x[j]-mean[j])*sigmainv[j*length+i];\n    }\n    ay += tempv*(x[i]-mean[i]);\n  }\n  ay = exp(-0.5*ay) / sqrt(pow((2*PI), length) * det);\n\n  return ay;\n#endif\n# undef CUR_PROC\n}                               /* double ighmm_rand_multivariate_normal_density */\n\n/*============================================================================*/\ndouble ighmm_rand_uniform_density (double x, double max, double min)\n{\n# define CUR_PROC \"ighmm_rand_uniform_density\"\n  double prob;\n  if (max <= min) {\n    GHMM_LOG(LCONVERTED, \"max <= min not allowed \\n\");\n    goto STOP;\n  }\n  prob = 1.0/(max-min);\n\n  if ( (x <= max) && (x>=min) ){\n    return prob;\n  }else{\n    return 0.0;\n  }\nSTOP:\n  return (-1.0);\n# undef CUR_PROC\n}                               /* double ighmm_rand_uniform_density */\n\n\n/*============================================================================*/\n/* special ghmm_cmodel pdf need it: smo->density==normal_approx: */\n/* generates a table of of aequidistant samples of gaussian pdf */\n\nstatic int randvar_init_pdf_stdnormal ()\n{\n# define CUR_PROC \"randvar_init_pdf_stdnormal\"\n  int i;\n  double x = 0.00;\n  for (i = 0; i < PDFLEN; i++) {\n    pdf_stdnormal[i] = 1 / (sqrt (2 * PI)) * exp (-1 * x * x / 2);\n    x += (double) X_STEP_PDF;\n  }\n  pdf_stdnormal_exists = 1;\n  /* printf(\"pdf_stdnormal_exists = %d\\n\", pdf_stdnormal_exists); */\n  return (0);\n# undef CUR_PROC\n}                               /* randvar_init_pdf_stdnormal */\n\n\ndouble ighmm_rand_normal_density_approx (double x, double mean, double u)\n{\n# define CUR_PROC \"ighmm_rand_normal_density_approx\"\n#ifdef HAVE_LIBPTHREAD\n  static pthread_mutex_t lock;\n#endif /* HAVE_LIBPTHREAD */\n  int i;\n  double y, z, pdf_x;\n  if (u <= 0.0) {\n    GHMM_LOG(LCONVERTED, \"u <= 0.0 not allowed\\n\");\n    goto STOP;\n  }\n  if (!pdf_stdnormal_exists) {\n#ifdef HAVE_LIBPTHREAD\n    pthread_mutex_lock (&lock); /* Put on a lock, because the clustering is parallel   */\n#endif /* HAVE_LIBPTHREAD */\n    randvar_init_pdf_stdnormal ();\n#ifdef HAVE_LIBPTHREAD\n    pthread_mutex_unlock (&lock);       /* Take the lock off */\n#endif /* HAVE_LIBPTHREAD */\n  }\n  y = 1 / sqrt (u);\n  z = fabs ((x - mean) * y);\n  i = (int) (z * X_FAKT_PDF);\n  /* linear interpolation: */\n  if (i >= PDFLEN - 1) {\n    i = PDFLEN - 1;\n    pdf_x = y * pdf_stdnormal[i];\n  }\n  else\n    pdf_x = y * (pdf_stdnormal[i] +\n                 (z - i * X_STEP_PDF) *\n                 (pdf_stdnormal[i + 1] - pdf_stdnormal[i]) / X_STEP_PDF);\n  return (pdf_x);\nSTOP:\n  return (-1.0);\n# undef CUR_PROC\n}                               /* double ighmm_rand_normal_density_approx */\ndouble ighmm_rand_dirichlet(int seed, int len, double *alpha, double *theta){\n  if (seed != 0) {\n    GHMM_RNG_SET(RNG, seed);\n  }\n#ifdef DO_WITH_GSL\n   gsl_ran_dirichlet(RNG, len, alpha, theta);\n#else\n  printf(\"not implemted without gsl. Compile with gsl to use dirichlet\");\n#endif\n}\n\n/*============================================================================*/\ndouble ighmm_rand_std_normal (int seed)\n{\n# define CUR_PROC \"ighmm_rand_std_normal\"\n  if (seed != 0) {\n    GHMM_RNG_SET (RNG, seed);\n  }\n\n#ifdef DO_WITH_GSL\n    return (gsl_ran_gaussian (RNG, 1.0));\n#else\n    /* Use the polar Box-Mueller transform */\n    /*\n       double x, y, r2;\n\n       do {\n       x = 2.0 * GHMM_RNG_UNIFORM(RNG) - 1.0;\n       y = 2.0 * GHMM_RNG_UNIFORM(RNG) - 1.0;\n       r2 = (x * x) + (y * y);\n       } while (r2 >= 1.0);\n\n       return x * sqrt((-2.0 * log(r2)) / r2);\n     */\n\n    double r2, theta;\n\n    r2 = -2.0 * log (GHMM_RNG_UNIFORM (RNG));   /* r2 ~ chi-square(2) */\n    theta = 2.0 * PI * GHMM_RNG_UNIFORM (RNG);  /* theta ~ uniform(0, 2 \\pi) */\n    return sqrt (r2) * cos (theta);\n#endif\n\n# undef CUR_PROC\n}                               /* ighmm_rand_std_normal */\n\n\n/*============================================================================*/\ndouble ighmm_rand_normal(double mue, double u, int seed)\n{\n# define CUR_PROC \"ighmm_rand_normal\"\n  if (seed != 0) {\n    GHMM_RNG_SET(RNG, seed);\n  }\n\n#ifdef DO_WITH_GSL\n    return gsl_ran_gaussian(RNG, sqrt (u)) + mue;\n#else\n    double x;\n    x = sqrt(u) * ighmm_rand_std_normal(seed) + mue;\n    return x;\n#endif\n\n# undef CUR_PROC\n}                               /* ighmm_rand_normal */\n\n/*============================================================================*/\nint ighmm_rand_multivariate_normal (int dim, double *x, double *mue, double *sigmacd, int seed)\n{\n# define CUR_PROC \"ighmm_rand_multivariate_normal\"\n  /* generate random vector of multivariate normal\n   *\n   *     dim     number of dimensions\n   *     x       space to store resulting vector in\n   *     mue     vector of means\n   *     sigmacd linearized cholesky decomposition of cov matrix\n   *     seed    RNG seed\n   *\n   *     see Barr & Slezak, A Comparison of Multivariate Normal Generators */\n  int i, j;\n#ifdef DO_WITH_GSL\n  gsl_vector *y = gsl_vector_alloc(dim);\n  gsl_vector *xgsl = gsl_vector_alloc(dim);\n  gsl_matrix *cd = gsl_matrix_alloc(dim, dim);\n#endif\n  if (seed != 0) {\n    GHMM_RNG_SET (RNG, seed);\n    /* do something here */\n    return 0;\n  }\n  else {\n#ifdef DO_WITH_GSL\n    /* cholesky decomposition matrix */\n    for (i=0;i<dim;i++) {\n      for (j=0;j<dim;j++) {\n        gsl_matrix_set(cd, i, j, sigmacd[i*dim+j]);\n      }\n    }\n    /* generate a random vector N(O,I) */\n    for (i=0;i<dim;i++) {\n      gsl_vector_set(y, i, ighmm_rand_std_normal(seed));\n    }\n    /* multiply cd with y */\n    gsl_blas_dgemv(CblasNoTrans, 1.0, cd, y, 0.0, xgsl);\n    for (i=0;i<dim;i++) {\n      x[i] = gsl_vector_get(xgsl, i) + mue[i];\n    }\n    gsl_vector_free(y);\n    gsl_vector_free(xgsl);\n    gsl_matrix_free(cd);\n#else\n    /* multivariate random numbers without gsl */\n    double randuni;\n    for (i=0;i<dim;i++) {\n      randuni = ighmm_rand_std_normal(seed);\n      for (j=0;j<dim;j++) {\n        if (i==0)\n          x[j] = mue[j];\n        x[j] += randuni * sigmacd[j*dim+i];\n      }\n    }\n#endif\n    return 0;\n  }\n# undef CUR_PROC\n}                               /* ighmm_rand_multivariate_normal */\n\n\n/*============================================================================*/\n#ifndef DO_WITH_GSL\n# define C0 2.515517\n# define C1 0.802853\n# define C2 0.010328\n# define D1 1.432788\n# define D2 0.189269\n# define D3 0.001308\n#endif\n\ndouble ighmm_rand_normal_right (double a, double mue, double u, int seed)\n{\n# define CUR_PROC \"ighmm_rand_normal_right\"\n  double x = -1;\n  double sigma;\n#ifdef DO_WITH_GSL\n  double s;\n#else\n  double U, Us, Us1, Feps, t, T;\n#endif\n\n  if (u <= 0.0) {\n    GHMM_LOG(LCONVERTED, \"u <= 0.0 not allowed\\n\");\n    goto STOP;\n  }\n  sigma = sqrt(u);\n\n  if (seed != 0) {\n    GHMM_RNG_SET (RNG, seed);\n  }\n\n#ifdef DO_WITH_GSL\n  /* move boundary to lower values in order to achieve maximum at mue\n     gsl_ran_gaussian_tail(generator, lower_boundary, sigma)\n   */\n  return mue + gsl_ran_gaussian_tail(RNG, a - mue, sqrt (u));\n\n#else /* DO_WITH_GSL */\n\n  /* Inverse transformation with restricted sampling by Fishman */\n  U = GHMM_RNG_UNIFORM(RNG);\n  Feps = ighmm_rand_get_PHI((a-mue) / sigma);\n\n  Us = Feps + (1-Feps) * U;\n  Us1 = 1-Us;\n  t = m_min (Us, Us1);\n\n  t = sqrt (-log (t * t));\n\n  T =\n    sigma * (t - (C0 + t * (C1 + t * C2))\n                 / (1 + t * (D1 + t * (D2 + t * D3))));\n\n  if (Us < Us1)\n    x = mue - T;\n  else\n    x = mue + T;\n#endif /* DO_WITH_GSL */\n\nSTOP:\n  return x;\n# undef CUR_PROC\n}                               /* randvar_normal_pos */\n\n\n\n/*============================================================================*/\ndouble ighmm_rand_uniform_int (int seed, int K)\n{\n# define CUR_PROC \"ighmm_rand_uniform_int\"\n  if (seed != 0) {\n    GHMM_RNG_SET (RNG, seed);\n  }\n\n#ifdef DO_WITH_GSL\n    /* more direct solution than old version ! */\n    return (double) gsl_rng_uniform_int (RNG, K);\n#else\n    return (double) ((int) (((double) K) * GHMM_RNG_UNIFORM (RNG)));\n#endif\n\n# undef CUR_PROC\n}                               /* ighmm_rand_uniform_int */\n\n/*===========================================================================*/\ndouble ighmm_rand_uniform_cont (int seed, double max, double min)\n{\n# define CUR_PROC \"ighmm_rand_uniform_cont\"\n  if (max <= min) {\n    GHMM_LOG(LCONVERTED, \"max <= min not allowed\\n\");\n    goto STOP;\n  }\n  if (seed != 0) {\n    GHMM_RNG_SET (RNG, seed);\n  }\n\n#ifdef DO_WITH_GSL\n    return (double)(((double)gsl_rng_uniform (RNG)*(max-min)) + min);\n#else\n    return (double)((GHMM_RNG_UNIFORM (RNG))*(max-min) + min );\n#endif\n\nSTOP:\n  return (-1.0);\n# undef CUR_PROC\n}                               /* ighmm_rand_uniform_cont */\n\n/*============================================================================*/\n/* cumalative distribution function of N(mean, u) */\ndouble ighmm_rand_normal_cdf (double x, double mean, double u)\n{\n# define CUR_PROC \"ighmm_rand_normal_cdf\"\n  if (u <= 0.0) {\n    GHMM_LOG(LCONVERTED, \"u <= 0.0 not allowed\\n\");\n    goto STOP;\n  }\n#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)\n  /* PHI(x)=erf(x/sqrt(2))/2+0.5 */\n  return (erf ((x - mean) / sqrt (u * 2.0)) + 1.0) / 2.0;\n#else\n  return (ighmm_erf ((x - mean) / sqrt (u * 2.0)) + 1.0) / 2.0;\n#endif /* Check for ISO C99 */\nSTOP:\n  return (-1.0);\n# undef CUR_PROC\n}                               /* double ighmm_rand_normal_cdf */\n\n/*============================================================================*/\n/* cumalative distribution function of a-truncated N(mean, u) */\ndouble ighmm_rand_normal_right_cdf (double x, double mean, double u, double a)\n{\n# define CUR_PROC \"ighmm_rand_normal_right_cdf\"\n\n  if (x <= a)\n    return (0.0);\n  if (u <= a) {\n    GHMM_LOG(LCONVERTED, \"u <= a not allowed\\n\");\n    goto STOP;\n  }\n#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)\n  /*\n     Function: int erfc (double x, gsl_sf_result * result) \n     These routines compute the complementary error function\n     erfc(x) = 1 - erf(x) = 2/\\sqrt(\\pi) \\int_x^\\infty \\exp(-t^2). \n   */\n  return 1.0 + (erf ((x - mean) / sqrt (u * 2)) -\n                1.0) / erfc ((a - mean) / sqrt (u * 2));\n#else\n  return 1.0 + (ighmm_erf ((x - mean) / sqrt (u * 2)) -\n                1.0) / ighmm_erfc ((a - mean) / sqrt (u * 2));\n#endif /* Check for ISO C99 */\nSTOP:\n  return (-1.0);\n# undef CUR_PROC\n}                               /* double ighmm_rand_normal_cdf */\n\n/*============================================================================*/\n/* cumalative distribution function of a uniform distribution in the range [min,max] */\ndouble ighmm_rand_uniform_cdf (double x, double max, double min)\n{\n# define CUR_PROC \"ighmm_rand_uniform_cdf\"\n  if (max <= min) {\n    GHMM_LOG(LCONVERTED, \"max <= min not allowed\\n\");\n    goto STOP;\n  }  \n  if (x < min) {\n    return 0.0;\n  }\n  if (x >= max) {\n    return 1.0;\n  }\n  return (x-min)/(max-min);\nSTOP:\n  return (-1.0);\n# undef CUR_PROC\n}                               /* ighmm_rand_uniform_cdf */\n\n\n\n#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)\n#else\n\n/* THIS WILL BE OBSOLETE WHEN WE USE ISO C99 */ \n\n/*===========================================================================\n *\n * The following functions for the error function and the complementory\n * error function are taken from\n * http://www.mathematik.uni-bielefeld.de/~sillke/ALGORITHMS/special-functions/erf.c\n * and have following different copyright.\n\n * ====================================================\n * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.\n *\n * Developed at SunPro, a Sun Microsystems, Inc. business.\n * Permission to use, copy, modify, and distribute this\n * software is freely granted, provided that this notice\n * is preserved.\n * ====================================================\n */\n\n/*\n * ====================================================\n * \n * Reference:\n *\n * W. J. Cody,\n *   Rational Chebychev approximations for the\n *   error function.\n *   Mathematics of Computations 23 (1969) 631-637\n *\n * W. J. Cody,\n *   Performance evaluations of programs for the \n *   error and complementary error function.\n *   Transactions of the ACM on Mathematical Software, \n *   16:1 (March 1990) 38-46\n *   \n * W. J. Cody,\n *   SPECFUN - A portable special function package,\n *   In: New Computing environments; \n *   Microcomputers in Large-Scale Scientific Computing,\n *   A. Wouk, SIAM, 1987, 1-12\n *\n * W. J. Cody,\n *   http://www.netlib.org/specfun/erf.\n *\n * For calculations with complex arguments see:   \n * \n * Walter Gautschi\n *   \"Efficient computation of the complex error function\"\n *   SIAM J. Numer. Anal.\n *   7:1 (1970), 187-198\n * \n * J.A.C. Weideman\n *   \"Computation of the complex error function\"\n *   SIAM J. Numer. Anal.\n *   31:5 (1994), 1497-1518 \n *\n * ====================================================\n */\n\n\n/* double erf(double x)\n * double erfc(double x)\n *\t\t\t     x\n *\t\t      2      |\\\n *     erf(x)  =  ---------  | exp(-t*t)dt\n *\t \t   sqrt(pi) \\|\n *\t\t\t     0\n *\n *     erfc(x) =  1-erf(x)\n *  Note that\n *\t\terf(-x) = -erf(x)\n *\t\terfc(-x) = 2 - erfc(x)\n *\n * Method:\n *\t1. For |x| in [0, 0.84375]\n *\t    erf(x)  = x + x*R(x^2)\n *          erfc(x) = 1 - erf(x)           if x in [-.84375,0.25]\n *                  = 0.5 + ((0.5-x)-x*R)  if x in [0.25,0.84375]\n *\t   where R = P/Q where P is an odd poly of degree 8 and\n *\t   Q is an odd poly of degree 10.\n *\t\t\t\t\t\t -57.90\n *\t\t\t| R - (erf(x)-x)/x | <= 2\n *\n *\n *\t   Remark. The formula is derived by noting\n *          erf(x) = (2/sqrt(pi))*(x - x^3/3 + x^5/10 - x^7/42 + ....)\n *\t   and that\n *          2/sqrt(pi) = 1.128379167095512573896158903121545171688\n *\t   is close to one. The interval is chosen because the fix\n *\t   point of erf(x) is near 0.6174 (i.e., erf(x)=x when x is\n *\t   near 0.6174), and by some experiment, 0.84375 is chosen to\n * \t   guarantee the error is less than one ulp for erf.\n *\n *      2. For |x| in [0.84375,1.25], let s = |x| - 1, and\n *         c = 0.84506291151 rounded to single (24 bits)\n *         \terf(x)  = sign(x) * (c  + P1(s)/Q1(s))\n *         \terfc(x) = (1-c)  - P1(s)/Q1(s) if x > 0\n *\t\t\t  1+(c+P1(s)/Q1(s))    if x < 0\n *         \t|P1/Q1 - (erf(|x|)-c)| <= 2**-59.06\n *\t   Remark: here we use the taylor series expansion at x=1.\n *\t\terf(1+s) = erf(1) + s*Poly(s)\n *\t\t\t = 0.845.. + P1(s)/Q1(s)\n *\t   That is, we use rational approximation to approximate\n *\t\t\terf(1+s) - (c = (single)0.84506291151)\n *\t   Note that |P1/Q1|< 0.078 for x in [0.84375,1.25]\n *\t   where\n *\t\tP1(s) = degree 6 poly in s\n *\t\tQ1(s) = degree 6 poly in s\n *\n *      3. For x in [1.25,1/0.35(~2.857143)],\n *         \terfc(x) = (1/x)*exp(-x*x-0.5625+R1/S1)\n *         \terf(x)  = 1 - erfc(x)\n *\t   where\n *\t\tR1(z) = degree 7 poly in z, (z=1/x^2)\n *\t\tS1(z) = degree 8 poly in z\n *\n *      4. For x in [1/0.35,28]\n *         \terfc(x) = (1/x)*exp(-x*x-0.5625+R2/S2) if x > 0\n *\t\t\t= 2.0 - (1/x)*exp(-x*x-0.5625+R2/S2) if -6<x<0\n *\t\t\t= 2.0 - tiny\t\t(if x <= -6)\n *         \terf(x)  = sign(x)*(1.0 - erfc(x)) if x < 6, else\n *         \terf(x)  = sign(x)*(1.0 - tiny)\n *\t   where\n *\t\tR2(z) = degree 6 poly in z, (z=1/x^2)\n *\t\tS2(z) = degree 7 poly in z\n *\n *      Note1:\n *\t   To compute exp(-x*x-0.5625+R/S), let s be a single\n *\t   precision number and s := x; then\n *\t\t-x*x = -s*s + (s-x)*(s+x)\n *\t        exp(-x*x-0.5626+R/S) =\n *\t\t\texp(-s*s-0.5625)*exp((s-x)*(s+x)+R/S);\n *      Note2:\n *\t   Here 4 and 5 make use of the asymptotic series\n *\t\t\t  exp(-x*x)\n *\t\terfc(x) ~ ---------- * ( 1 + Poly(1/x^2) )\n *\t\t\t  x*sqrt(pi)\n *\t   We use rational approximation to approximate\n *      \tg(s)=f(1/x^2) = log(erfc(x)*x) - x*x + 0.5625\n *\t   Here is the error bound for R1/S1 and R2/S2\n *      \t|R1/S1 - f(x)|  < 2**(-62.57)\n *      \t|R2/S2 - f(x)|  < 2**(-61.52)\n *\n *      5. For inf > x >= 28\n *         \terf(x)  = sign(x) *(1 - tiny)  (raise inexact)\n *         \terfc(x) = tiny*tiny (raise underflow) if x > 0\n *\t\t\t= 2 - tiny if x<0\n *\n *      7. Special case:\n *         \terf(0)  = 0, erf(inf)  = 1, erf(-inf) = -1,\n *         \terfc(0) = 1, erfc(inf) = 0, erfc(-inf) = 2,\n *\t   \terfc/erf(NaN) is NaN\n */\n\n\nstatic const double\n\ntiny =  1e-300,\nhalf =  5.00000000000000000000e-01, /* 0x3FE00000, 0x00000000 */\none  =  1.00000000000000000000e+00, /* 0x3FF00000, 0x00000000 */\ntwo  =  2.00000000000000000000e+00, /* 0x40000000, 0x00000000 */\n\nerx  =  8.45062911510467529297e-01, /* 0x3FEB0AC1, 0x60000000 */\n/*\n * Coefficients for approximation to  erf on [0,0.84375]\n */\nefx  =  1.28379167095512586316e-01, /* 0x3FC06EBA, 0x8214DB69 */\nefx8 =  1.02703333676410069053e+00, /* 0x3FF06EBA, 0x8214DB69 */\npp0  =  1.28379167095512558561e-01, /* 0x3FC06EBA, 0x8214DB68 */\npp1  = -3.25042107247001499370e-01, /* 0xBFD4CD7D, 0x691CB913 */\npp2  = -2.84817495755985104766e-02, /* 0xBF9D2A51, 0xDBD7194F */\npp3  = -5.77027029648944159157e-03, /* 0xBF77A291, 0x236668E4 */\npp4  = -2.37630166566501626084e-05, /* 0xBEF8EAD6, 0x120016AC */\nqq1  =  3.97917223959155352819e-01, /* 0x3FD97779, 0xCDDADC09 */\nqq2  =  6.50222499887672944485e-02, /* 0x3FB0A54C, 0x5536CEBA */\nqq3  =  5.08130628187576562776e-03, /* 0x3F74D022, 0xC4D36B0F */\nqq4  =  1.32494738004321644526e-04, /* 0x3F215DC9, 0x221C1A10 */\nqq5  = -3.96022827877536812320e-06, /* 0xBED09C43, 0x42A26120 */\n/*\n * Coefficients for approximation to  erf  in [0.84375,1.25]\n */\npa0  = -2.36211856075265944077e-03, /* 0xBF6359B8, 0xBEF77538 */\npa1  =  4.14856118683748331666e-01, /* 0x3FDA8D00, 0xAD92B34D */\npa2  = -3.72207876035701323847e-01, /* 0xBFD7D240, 0xFBB8C3F1 */\npa3  =  3.18346619901161753674e-01, /* 0x3FD45FCA, 0x805120E4 */\npa4  = -1.10894694282396677476e-01, /* 0xBFBC6398, 0x3D3E28EC */\npa5  =  3.54783043256182359371e-02, /* 0x3FA22A36, 0x599795EB */\npa6  = -2.16637559486879084300e-03, /* 0xBF61BF38, 0x0A96073F */\nqa1  =  1.06420880400844228286e-01, /* 0x3FBB3E66, 0x18EEE323 */\nqa2  =  5.40397917702171048937e-01, /* 0x3FE14AF0, 0x92EB6F33 */\nqa3  =  7.18286544141962662868e-02, /* 0x3FB2635C, 0xD99FE9A7 */\nqa4  =  1.26171219808761642112e-01, /* 0x3FC02660, 0xE763351F */\nqa5  =  1.36370839120290507362e-02, /* 0x3F8BEDC2, 0x6B51DD1C */\nqa6  =  1.19844998467991074170e-02, /* 0x3F888B54, 0x5735151D */\n/*\n * Coefficients for approximation to  erfc in [1.25,1/0.35]\n */\nra0  = -9.86494403484714822705e-03, /* 0xBF843412, 0x600D6435 */\nra1  = -6.93858572707181764372e-01, /* 0xBFE63416, 0xE4BA7360 */\nra2  = -1.05586262253232909814e+01, /* 0xC0251E04, 0x41B0E726 */\nra3  = -6.23753324503260060396e+01, /* 0xC04F300A, 0xE4CBA38D */\nra4  = -1.62396669462573470355e+02, /* 0xC0644CB1, 0x84282266 */\nra5  = -1.84605092906711035994e+02, /* 0xC067135C, 0xEBCCABB2 */\nra6  = -8.12874355063065934246e+01, /* 0xC0545265, 0x57E4D2F2 */\nra7  = -9.81432934416914548592e+00, /* 0xC023A0EF, 0xC69AC25C */\nsa1  =  1.96512716674392571292e+01, /* 0x4033A6B9, 0xBD707687 */\nsa2  =  1.37657754143519042600e+02, /* 0x4061350C, 0x526AE721 */\nsa3  =  4.34565877475229228821e+02, /* 0x407B290D, 0xD58A1A71 */\nsa4  =  6.45387271733267880336e+02, /* 0x40842B19, 0x21EC2868 */\nsa5  =  4.29008140027567833386e+02, /* 0x407AD021, 0x57700314 */\nsa6  =  1.08635005541779435134e+02, /* 0x405B28A3, 0xEE48AE2C */\nsa7  =  6.57024977031928170135e+00, /* 0x401A47EF, 0x8E484A93 */\nsa8  = -6.04244152148580987438e-02, /* 0xBFAEEFF2, 0xEE749A62 */\n/*\n * Coefficients for approximation to  erfc in [1/.35,28]\n */\nrb0  = -9.86494292470009928597e-03, /* 0xBF843412, 0x39E86F4A */\nrb1  = -7.99283237680523006574e-01, /* 0xBFE993BA, 0x70C285DE */\nrb2  = -1.77579549177547519889e+01, /* 0xC031C209, 0x555F995A */\nrb3  = -1.60636384855821916062e+02, /* 0xC064145D, 0x43C5ED98 */\nrb4  = -6.37566443368389627722e+02, /* 0xC083EC88, 0x1375F228 */\nrb5  = -1.02509513161107724954e+03, /* 0xC0900461, 0x6A2E5992 */\nrb6  = -4.83519191608651397019e+02, /* 0xC07E384E, 0x9BDC383F */\nsb1  =  3.03380607434824582924e+01, /* 0x403E568B, 0x261D5190 */\nsb2  =  3.25792512996573918826e+02, /* 0x40745CAE, 0x221B9F0A */\nsb3  =  1.53672958608443695994e+03, /* 0x409802EB, 0x189D5118 */\nsb4  =  3.19985821950859553908e+03, /* 0x40A8FFB7, 0x688C246A */\nsb5  =  2.55305040643316442583e+03, /* 0x40A3F219, 0xCEDF3BE6 */\nsb6  =  4.74528541206955367215e+02, /* 0x407DA874, 0xE79FE763 */\nsb7  = -2.24409524465858183362e+01; /* 0xC03670E2, 0x42712D62 */\n\nstatic double ighmm_erf (double x) {\n  double R,S,P,Q,s,y,z,r;\n  double ax = fabs(x);\n#ifdef HAVE_IEEE754\n  if (!isfinite(x)) {\n    if (isnan(x)) return x;     /* erf(nan)=nan */\n    return (x==ax) ? 1 : -1;\t/* erf(+-inf)=+-1 */\n  }\n#endif\n  if (ax < 0.84375) {\t\t/* |x|<0.84375 */\n    if (ax < 3.7252903e-9) { \t/* |x|<2**-28 */\n      if (ax < tiny)\n\treturn 0.125*(8.0*x+efx8*x);  /*avoid underflow */\n      return x + efx*x;\n    }\n    z = x*x;\n    r = pp0+z*(pp1+z*(pp2+z*(pp3+z*pp4)));\n    s = one+z*(qq1+z*(qq2+z*(qq3+z*(qq4+z*qq5))));\n    y = r/s;\n    return x + x*y;\n  }\n  if (ax < 1.25) {\t\t\t/* 0.84375 <= |x| < 1.25 */\n    s = ax-one;\n    P = pa0+s*(pa1+s*(pa2+s*(pa3+s*(pa4+s*(pa5+s*pa6)))));\n    Q = one+s*(qa1+s*(qa2+s*(qa3+s*(qa4+s*(qa5+s*qa6)))));\n    if (x>=0) return erx + P/Q;\n    else return -erx - P/Q;\n  }\n  if (ax >= 6.0) {\t\t/* inf>|x|>=6 */\n    if (x>=0) return one-tiny;\n    else return tiny-one;\n  }\n  s = one/(x*x);\n  if (ax < 2.857142857) {\t/* |x| < 1/0.35 */\n    R=ra0+s*(ra1+s*(ra2+s*(ra3+s*(ra4+s*(ra5+s*(ra6+s*ra7))))));\n    S=one+s*(sa1+s*(sa2+s*(sa3+s*(sa4+s*(sa5+s*(sa6+s*(sa7+s*sa8)))))));\n  }\n  else {\t\t/* |x| >= 1/0.35 */\n    R=rb0+s*(rb1+s*(rb2+s*(rb3+s*(rb4+s*(rb5+s*rb6)))));\n    S=one+s*(sb1+s*(sb2+s*(sb3+s*(sb4+s*(sb5+s*(sb6+s*sb7))))));\n  }\n  z  = (double)(float) ax;\n  r  = exp(-z*z-0.5625)*exp((z-ax)*(z+ax)+R/S);\n  if (x>=0) return one-r/ax;\n  else return  r/ax-one;\n}\n\nstatic double ighmm_erfc (double x) {\n  double R,S,P,Q,s,y,z,r;\n  double ax = fabs(x);\n#ifdef HAVE_IEEE754\n  if (!isfinite(x)) {\n    if (isnan(x)) return x;     /* erfc(nan)=nan */\n    return (x==ax) ? 0 : 2;\t/* erfc(+-inf)=0,2 */\n  }\n#endif\n  if (ax < 0.84375) {\t\t/* |x|<0.84375 */\n    if (ax < 13.8777878e-18)  \t/* |x|<2**-56 */\n      return one-x;\n    z = x*x;\n    r = pp0+z*(pp1+z*(pp2+z*(pp3+z*pp4)));\n    s = one+z*(qq1+z*(qq2+z*(qq3+z*(qq4+z*qq5))));\n    y = r/s;\n    if (ax < 0.25) {  \t\t/* x<1/4 */\n      return one-(x+x*y);\n    }\n    else {\n      r = x*y;\n      r += (x-half);\n      return half - r ;\n    }\n  }\n  if (ax < 1.25) {\t\t\t/* 0.84375 <= |x| < 1.25 */\n    s = fabs(x)-one;\n    P = pa0+s*(pa1+s*(pa2+s*(pa3+s*(pa4+s*(pa5+s*pa6)))));\n    Q = one+s*(qa1+s*(qa2+s*(qa3+s*(qa4+s*(qa5+s*qa6)))));\n    if (x>=0) {\n      z  = one-erx; return z - P/Q;\n    }\n    else {\n      z = erx+P/Q; return one+z;\n    }\n  }\n  if (ax < 28.0) {\t\t/* |x|<28 */\n    s = one/(x*x);\n    if (ax < 2.857142857) {\t/* |x| < 1/.35 ~ 2.857143*/\n      R=ra0+s*(ra1+s*(ra2+s*(ra3+s*(ra4+s*(ra5+s*(ra6+s*ra7))))));\n      S=one+s*(sa1+s*(sa2+s*(sa3+s*(sa4+s*(sa5+s*(sa6+s*(sa7+s*sa8)))))));\n    }\n    else {\t\t\t/* |x| >= 1/.35 ~ 2.857143 */\n      if (x < -6.0) return two-tiny;/* x < -6 */\n      R=rb0+s*(rb1+s*(rb2+s*(rb3+s*(rb4+s*(rb5+s*rb6)))));\n      S=one+s*(sb1+s*(sb2+s*(sb3+s*(sb4+s*(sb5+s*(sb6+s*sb7))))));\n    }\n    z  = (double)(float) ax;\n    r  = exp(-z*z-0.5625)*exp((z-ax)*(z+ax)+R/S);\n    if (x>0) return r/ax;\n    else return two-r/ax;\n  }\n  else {\n    if(x>0) return tiny*tiny;\n    else return two-tiny;\n  }\n}\n#endif /* check for ISO C99 */\n", "meta": {"hexsha": "e56b71e01e7135d101c35b16089a28c183c38051", "size": 33412, "ext": "c", "lang": "C", "max_stars_repo_path": "Trash/sandbox/hmm/ghmm-0.9-rc3/ghmm/randvar.c", "max_stars_repo_name": "ruslankuzmin/julia", "max_stars_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2017-03-13T17:32:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-27T16:51:22.000Z", "max_issues_repo_path": "Trash/sandbox/hmm/ghmm-0.9-rc3/ghmm/randvar.c", "max_issues_repo_name": "ruslankuzmin/julia", "max_issues_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-29T19:54:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-29T19:54:52.000Z", "max_forks_repo_path": "Trash/sandbox/hmm/ghmm-0.9-rc3/ghmm/randvar.c", "max_forks_repo_name": "ruslankuzmin/julia", "max_forks_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2016-10-18T03:31:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-29T13:23:10.000Z", "avg_line_length": 30.7944700461, "max_line_length": 118, "alphanum_fraction": 0.5614150605, "num_tokens": 11645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047869292635403, "lm_q2_score": 0.06097517531917227, "lm_q1q2_score": 0.029297272538311176}}
{"text": "/**\n *\n * @file qwrapper_slaset2.c\n *\n *  PLASMA core_blas quark wrapper\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Hatem Ltaief\n * @date 2010-11-15\n * @generated s Tue Jan  7 11:44:59 2014\n *\n **/\n#include <lapacke.h>\n#include \"common.h\"\n\n/***************************************************************************//**\n *\n **/\nvoid QUARK_CORE_slaset2(Quark *quark, Quark_Task_Flags *task_flags,\n                       PLASMA_enum uplo, int M, int N,\n                       float alpha, float *A, int LDA)\n{\n    DAG_CORE_LASET;\n    QUARK_Insert_Task(quark, CORE_slaset2_quark, task_flags,\n        sizeof(PLASMA_enum),                &uplo,  VALUE,\n        sizeof(int),                        &M,     VALUE,\n        sizeof(int),                        &N,     VALUE,\n        sizeof(float),         &alpha, VALUE,\n        sizeof(float)*M*N,     A,      OUTPUT,\n        sizeof(int),                        &LDA,   VALUE,\n        0);\n}\n\n/***************************************************************************//**\n *\n **/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_slaset2_quark = PCORE_slaset2_quark\n#define CORE_slaset2_quark PCORE_slaset2_quark\n#endif\nvoid CORE_slaset2_quark(Quark *quark)\n{\n    PLASMA_enum uplo;\n    int M;\n    int N;\n    float alpha;\n    float *A;\n    int LDA;\n\n    quark_unpack_args_6(quark, uplo, M, N, alpha, A, LDA);\n    CORE_slaset2(uplo, M, N, alpha, A, LDA);\n}\n", "meta": {"hexsha": "34816924cbba9f63cdd77c07c0d2a9ff9c9f6aad", "size": 1512, "ext": "c", "lang": "C", "max_stars_repo_path": "core_blas-qwrapper/qwrapper_slaset2.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "core_blas-qwrapper/qwrapper_slaset2.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "core_blas-qwrapper/qwrapper_slaset2.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4909090909, "max_line_length": 80, "alphanum_fraction": 0.5185185185, "num_tokens": 414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.061875986156129166, "lm_q1q2_score": 0.029247756255596905}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n//\n// File eigen_mm.h\n//\n// MIT License\n\n// Copyright (c) 2020 EigenMM\n\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n//\n// Description: EigenMM library definitions\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef eigen_mm_H\n#define eigen_mm_H\n\n#include <petsc.h>\n#include <slepceps.h>\n\n#include <algorithm>\n#include <vector>\n#include <map>\n#include <string>\n#include <fstream>\n#include <iterator>\n#include <iostream>\n#include \"mpi.h\"\n#include \"tinyxml.h\"\n\n#define PI 3.141592653589793238462\n\nclass SolverOptions\n{\nprivate:\n    // communicator options\n    PetscInt _nodesperevaluator = 1;\n    PetscInt _subproblemsperevaluator = 1;\n    PetscInt _totalsubproblems = 1;\n    PetscInt _nevaluators = 1;\n    PetscInt _nevals = -1;\n    PetscInt _taskspernode = 28;\n\n    // eigenvalue partitioning options\n    PetscInt _nk = 7;\n    PetscInt _nb = 4;\n    PetscInt _p = 0;\n    PetscInt _nv = 10;\n    PetscInt _splitmaxiters = 10;\n    PetscInt _raditers = 10;\n    PetscReal _splittol = 0.9;\n    PetscReal _radtol = 1e-3;\n    PetscReal _L = 0.01;\n    PetscReal _R = -1.0;\n\n    // save and print options\n    bool _terse = false;\n    bool _details = false;\n    bool _debug = false;\n    bool _save_operators = false;\n    bool _save_correctness = false;\n    bool _save_eigenvalues = false;\n    bool _save_eigenbasis = false;\n    char _operators_filename[2048];\n    char _correctness_filename[2048];\n    char _eigenvalues_filename[2048];\n    char _eigenbasis_filename[2048];\n\npublic:\n    SolverOptions() {}\n\n    // set communicator options\n    void set_nodesperevaluator(PetscInt v) { _nodesperevaluator = v; }\n    void set_subproblemsperevaluator(PetscInt v) { _subproblemsperevaluator = v; }\n    void set_totalsubproblems(PetscInt v) { _totalsubproblems = v; }\n    void set_nevaluators(PetscInt v) { _nevaluators = v; }\n    void set_nevals(PetscInt v) { _nevals = v; }\n    void set_taskspernode(PetscInt v) { _taskspernode = v; }\n\n    // set eigenvalue partitioning options\n    void set_nk(PetscInt v) { _nk = v; }\n    void set_nb(PetscInt v) { _nb = v; }\n    void set_p(PetscInt v) { _p = v; }\n    void set_nv(PetscInt v) { _nv = v; }\n    void set_splitmaxiters(PetscInt v) { _splitmaxiters = v; }\n    void set_raditers(PetscInt v) { _raditers = v; }\n    void set_splittol(PetscReal v) { _splittol = v; }\n    void set_radtol(PetscReal v) { _radtol = v; }\n    void set_L(PetscReal v) { _L = v; }\n    void set_R(PetscReal v) { _R = v; }\n\n    // set save and print options\n    void set_terse(bool v) { _terse = v; }\n    void set_details(bool v) { _details = v; }\n    void set_debug(bool v) { _debug = v; }\n    void set_save_operators(bool v, const char* filename)\n    {\n        _save_operators = v;\n        sprintf(_operators_filename, \"%s\", filename);\n    }\n    void set_save_correctness(bool v, const char* filename)\n    {\n        _save_correctness = v;\n        sprintf(_correctness_filename, \"%s\", filename);\n    }\n    void set_save_eigenvalues(bool v, const char* filename) \n    {\n        _save_eigenvalues = v;\n        sprintf(_eigenvalues_filename, \"%s\", filename);\n    }\n    void set_save_eigenbasis(bool v, const char* filename)\n    {\n        _save_eigenbasis = v;\n         sprintf(_eigenbasis_filename, \"%s\", filename);\n    }\n    \n    // get communicator options\n    PetscInt nodesperevaluator() { return _nodesperevaluator; }\n    PetscInt subproblemsperevaluator() { return _subproblemsperevaluator; }\n    PetscInt totalsubproblems() { return _totalsubproblems; }\n    PetscInt nevaluators() { return _nevaluators; }\n    PetscInt nevals() { return _nevals; }\n    PetscInt taskspernode() { return _taskspernode; }\n\n    // get eigenvalue partitioning options\n    PetscInt nk() { return _nk; }\n    PetscInt nb() { return _nb; }\n    PetscInt p() { return _p; }\n    PetscInt nv() { return _nv; }\n    PetscInt splitmaxiters() { return _splitmaxiters; }\n    PetscInt raditers() { return _raditers; }\n    PetscReal splittol() { return _splittol; }\n    PetscReal radtol() { return _radtol; }\n    PetscReal L() { return _L; }\n    PetscReal R() { return _R; }\n\n    // get save and print options\n    bool terse() { return _terse; }\n    bool details() { return _details; }\n    bool debug() { return _debug; }\n    bool save_operators() { return _save_operators; }\n    bool save_correctness() { return _save_correctness; }\n    bool save_eigenvalues() { return _save_eigenvalues; }\n    bool save_eigenbasis() { return _save_eigenbasis; }\n    char* operators_filename() { return _operators_filename; }\n    char* correctness_filename() { return _correctness_filename; }\n    char* eigenvalues_filename() { return _eigenvalues_filename; }\n    char* eigenbasis_filename() { return _eigenbasis_filename; }\n};\n\nstruct NodeInfo\n{\n    // world\n    PetscInt worldrank, worldsize;\n\n    // evaluator\n    PetscInt rank, size, id;\n    MPI_Comm comm;\n\n    // additional properties\n    PetscInt nevaluators;\n    \n    const char* procname;\n    PetscInt procid;\n\n    // Results\n    PetscInt neval;\n    PetscInt neval0;\n};\n\nclass eigen_mm\n{\nprivate:\n\n    EPS eps;\n    SolverOptions opts;\n    NodeInfo node;\n    Mat K, M, V;\n    Mat K_global, M_global;\n    Vec lambda;\n    std::vector<PetscReal> intervals;\n    std::vector<PetscReal> residuals;\n\n    void findUpperBound();\n    void rescaleInterval();\n    void formSubproblems();\n    PetscReal count_subintervals(PetscInt n, PetscReal Nhat, PetscInt Nbar,\n        std::vector<PetscReal> x, std::vector<PetscInt> &RA, std::vector<PetscInt> &A);\n    void merge_approximations(PetscReal Nhat, PetscInt Nbar,\n        std::vector<PetscReal> &x, std::vector<PetscInt> &RA,\n        std::vector<PetscReal> y, std::vector<PetscInt> RB,\n        std::vector<PetscInt> &A);\n    PetscInt solveSubproblems();\n    void formEigenbasis(PetscInt neval);\n\n    PetscInt solveSubProblem(PetscReal *intervals, int job);\n    void splitSubProblem(PetscReal a, PetscReal b, PetscReal *c, \n        PetscInt *out_ec_left, PetscInt *out_ec_right);\n    void global_refine(PetscInt n,\n                       std::vector<PetscReal>  x, \n                       std::vector<PetscReal> &y,\n                       std::vector<PetscInt>   C, \n                       PetscReal Nhat);\n    void balance_intervals(PetscReal   a, PetscReal   b, PetscReal   *c, \n                           PetscInt reva, PetscInt revb, PetscInt *revc,\n                           PetscInt  *Cl, PetscInt  *Cr);\n    PetscInt computeDev_approximate(PetscReal a, PetscReal U, PetscBool rl);\n    PetscInt computeDev_exact(PetscReal a, PetscBool rl);\n    PetscReal computeRadius(Mat &A);\n    void countInterval(PetscReal a, PetscReal b, PetscInt *count);\n\npublic:\n\n    eigen_mm();\n    ~eigen_mm();\n\n    int init(Mat &K_in, Mat &M_in, SolverOptions &opt);\n    int solve(Mat *V_out, Vec *lambda_out);\n\n    void exactEigenvalues_square_neumann(int Ne, \n        std::vector<PetscReal> &lambda, \n        std::vector<PetscReal> &eta1, \n        std::vector<PetscReal> &eta2);\n    void exactEigenvalues_cube_neumann(int Ne, \n        std::vector<PetscReal> &lambda, \n        std::vector<PetscReal> &eta1, \n        std::vector<PetscReal> &eta2,\n        std::vector<PetscReal> &eta3);\n\n};\n\n#endif //eigen_mm_H", "meta": {"hexsha": "6005989cc5c776e95e59735732d1212b782e0fef", "size": 8285, "ext": "h", "lang": "C", "max_stars_repo_path": "include/eigenmm/eigen_mm.h", "max_stars_repo_name": "paralab/EigenMM", "max_stars_repo_head_hexsha": "5c94233524ae2758ebf47c3b3fdb6570a6cc4e59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/eigenmm/eigen_mm.h", "max_issues_repo_name": "paralab/EigenMM", "max_issues_repo_head_hexsha": "5c94233524ae2758ebf47c3b3fdb6570a6cc4e59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/eigenmm/eigen_mm.h", "max_forks_repo_name": "paralab/EigenMM", "max_forks_repo_head_hexsha": "5c94233524ae2758ebf47c3b3fdb6570a6cc4e59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4072580645, "max_line_length": 87, "alphanum_fraction": 0.6613156307, "num_tokens": 2279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.06187598615612917, "lm_q1q2_score": 0.02900688232324858}}
{"text": "/*!\n *  Copyright (c) 2014 by Contributors\n * \\file base.h\n * \\brief definitions of base types, operators, macros functions\n *\n * \\author Bing Xu, Tianqi Chen\n */\n#ifndef MSHADOW_BASE_H_\n#define MSHADOW_BASE_H_\n#ifdef _MSC_VER\n#define _CRT_SECURE_NO_WARNINGS\n#define _CRT_SECURE_NO_DEPRECATE\n#define NOMINMAX\n#endif\n#include <cmath>\n#include <cstdio>\n#include <cfloat>\n#include <climits>\n#include <algorithm>\n// macro defintiions\n/*!\n * \\brief if this macro is define to be 1,\n * mshadow should compile without any of other libs \n */\n#ifndef MSHADOW_STAND_ALONE\n#define MSHADOW_STAND_ALONE 0\n#endif\n/*! \\brief whether do padding during allocation */\n#ifndef MSHADOW_ALLOC_PAD\n#define MSHADOW_ALLOC_PAD true\n#endif\n/*!\n * \\brief \n *  x dimension of data must be bigger pad_size * ratio to be alloced padded memory,\n *  otherwise use tide allocation \n *  for example, if pad_ratio=2, GPU memory alignement size is 32,\n *  then we will only allocate padded memory if x dimension > 64\n *  set it to 0 then we will always allocate padded memory\n */\n#ifndef MSHADOW_MIN_PAD_RATIO\n  #define MSHADOW_MIN_PAD_RATIO 2\n#endif\n\n#if MSHADOW_STAND_ALONE\n  #define MSHADOW_USE_CBLAS 0\n  #define MSHADOW_USE_MKL   0\n  #define MSHADOW_USE_CUDA  0\n#endif\n\n/*!\n * \\brief force user to use GPU stream during computation\n *  error will be shot when default stream NULL is used\n */\n#ifndef MSHADOW_FORCE_STREAM\n#define MSHADOW_FORCE_STREAM 0\n#endif\n\n/*! \\brief use CBLAS for CBLAS */\n#ifndef MSHADOW_USE_CBLAS\n  #define MSHADOW_USE_CBLAS 0\n#endif\n/*! \\brief use MKL for BLAS */\n#ifndef MSHADOW_USE_MKL\n  #define MSHADOW_USE_MKL   1\n#endif\n/*!\n * \\brief use CUDA support, must ensure that the cuda include path is correct,\n * or directly compile using nvcc\n */\n#ifndef MSHADOW_USE_CUDA\n  #define MSHADOW_USE_CUDA   1\n#endif\n\n/*!\n * \\brief seems CUDAARCH is deprecated in future NVCC\n * set this to 1 if you want to use CUDA version smaller than 2.0\n */\n#ifndef MSHADOW_OLD_CUDA\n#define MSHADOW_OLD_CUDA 0\n#endif\n\n/*! \\brief whether use SSE */\n#ifndef MSHADOW_USE_SSE\n  #define MSHADOW_USE_SSE 1\n#endif\n/*! \\brief whether use NVML to get dynamic info */\n#ifndef MSHADOW_USE_NVML\n  #define MSHADOW_USE_NVML 0\n#endif\n// SSE is conflict with cudacc\n#ifdef __CUDACC__\n  #undef MSHADOW_USE_SSE\n  #define MSHADOW_USE_SSE 0\n#endif\n\n#if MSHADOW_USE_CBLAS\nextern \"C\" {\n    #include <cblas.h>\n}\n#elif MSHADOW_USE_MKL\n  #include <mkl.h>\n  #include <mkl_cblas.h>\n  #include <mkl_vsl.h>\n  #include <mkl_vsl_functions.h>\n#endif\n\n#if MSHADOW_USE_CUDA\n  #include <cublas.h>\n  #include <curand.h>\n#endif\n\n#if MSHADOW_USE_NVML\n  #include <nvml.h>\n#endif\n// --------------------------------\n// MSHADOW_XINLINE is used for inlining template code for both CUDA and CPU code\n#ifdef MSHADOW_XINLINE\n  #error \"MSHADOW_XINLINE must not be defined\"\n#endif\n#ifdef _MSC_VER\n#define MSHADOW_FORCE_INLINE __forceinline\n#pragma warning( disable : 4068 )\n#else\n#define MSHADOW_FORCE_INLINE inline __attribute__((always_inline)) \n#endif\n#ifdef __CUDACC__\n  #define MSHADOW_XINLINE MSHADOW_FORCE_INLINE __device__ __host__\n#else\n  #define MSHADOW_XINLINE MSHADOW_FORCE_INLINE\n#endif\n/*! \\brief cpu force inline */\n#define MSHADOW_CINLINE MSHADOW_FORCE_INLINE\n\n#if defined(__GXX_EXPERIMENTAL_CXX0X) ||\\\n    defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L\n  #define MSHADOW_CONSTEXPR constexpr\n#else\n  #define MSHADOW_CONSTEXPR const\n#endif\n\n/*!\n * \\brief default data type for tensor string\n *  in code release, change it to default_real_t\n *  during development, change it to empty string so that missing\n *  template arguments can be detected\n */\n#ifndef MSHADOW_DEFAULT_DTYPE\n#define MSHADOW_DEFAULT_DTYPE = default_real_t\n//#define MSHADOW_DEFAULT_DTYPE\n#endif\n\n/*! \\brief namespace for mshadow */\nnamespace mshadow {\n/*! \\brief buffer size for each random number generator */\nconst unsigned kRandBufferSize = 1000000;\n/*! \\brief pi  */\nconst float kPi = 3.1415926f;\n/*! \\brief type that will be used for index */\ntypedef unsigned index_t;\n/*! \\brief float point type that will be used in default by mshadow */\ntypedef float default_real_t;\n\n/*! \\brief namespace for operators */\nnamespace op {\n// binary operator\n/*! \\brief mul operator */\nstruct mul{\n  /*! \\brief map a, b to result using defined operation */\n  template<typename DType>\n  MSHADOW_XINLINE static DType Map(DType a, DType b) {\n    return a * b;\n  }\n};\n/*! \\brief plus operator */\nstruct plus {\n  /*! \\brief map a, b to result using defined operation */\n  template<typename DType>\n  MSHADOW_XINLINE static DType Map(DType a, DType b) {\n    return a + b;\n  }\n};\n/*! \\brief minus operator */\nstruct minus {\n  /*! \\brief map a, b to result using defined operation */\n  template<typename DType>\n  MSHADOW_XINLINE static DType Map(DType a, DType b) {\n    return a - b;\n  }\n};\n/*! \\brief divide operator */\nstruct div {\n  /*! \\brief map a, b to result using defined operation */\n  template<typename DType>\n  MSHADOW_XINLINE static DType Map(DType a, DType b) {\n    return a / b;\n  }\n};\n/*! \\brief get rhs */\nstruct right {\n  /*! \\brief map a, b to result using defined operation */\n  template<typename DType>\n  MSHADOW_XINLINE static DType Map(DType a, DType b) {\n    return b;\n  }\n};\n// unary operator/ function: example\n// these operators can be defined by user,\n// in the same style as binary and unary operator\n// to use, simply write F<op::identity>( src )\n/*! \\brief identity function that maps a real number to it self */\nstruct identity{\n  /*! \\brief map a to result using defined operation */\n  template<typename DType>\n  MSHADOW_XINLINE static DType Map(DType a) {\n    return a;\n  }\n};\n}  // namespace op\n/*! \\brief namespace for savers */\nnamespace sv {\n/*! \\brief save to saver: = */\nstruct saveto {\n  /*! \\brief save b to a using save method */\n  template<typename DType>\n  MSHADOW_XINLINE static void Save(DType &a, DType b) {\n    a = b;\n  }\n  /*! \\brief helper constant to use BLAS, alpha */\n  inline static default_real_t AlphaBLAS(void) { return 1.0f; }\n  /*! \\brief helper constant to use BLAS, beta */\n  inline static default_real_t BetaBLAS(void) { return 0.0f; }\n  /*! \\brief corresponding binary operator type */\n  typedef op::right OPType;\n};\n/*! \\brief save to saver: += */\nstruct plusto {\n  /*! \\brief save b to a using save method */\n  template<typename DType>\n  MSHADOW_XINLINE static void Save(DType &a, DType b) {\n    a += b;\n  }\n  /*! \\brief helper constant to use BLAS, alpha */\n  inline static default_real_t AlphaBLAS(void) { return 1.0f; }\n  /*! \\brief helper constant to use BLAS, beta */\n  inline static default_real_t BetaBLAS(void) { return 1.0f; }\n  /*! \\brief corresponding binary operator type */\n  typedef op::plus OPType;\n};\n/*! \\brief minus to saver: -= */\nstruct minusto {\n  /*! \\brief save b to a using save method */\n  template<typename DType>\n  MSHADOW_XINLINE static void Save(DType &a, DType b) {\n    a -= b;\n  }\n  /*! \\brief helper constant to use BLAS, alpha */\n  inline static default_real_t AlphaBLAS(void) { return -1.0f; }\n  /*! \\brief helper constant to use BLAS, beta */\n  inline static default_real_t BetaBLAS(void) { return 1.0f; }\n  /*! \\brief corresponding binary operator type */\n  typedef op::minus OPType;\n};\n/*! \\brief multiply to saver: *= */\nstruct multo {\n  /*! \\brief save b to a using save method */\n  template<typename DType>\n  MSHADOW_XINLINE static void Save(DType &a, DType b) {\n    a *= b;\n  }\n  /*! \\brief corresponding binary operator type */\n  typedef op::mul OPType;\n};\n/*! \\brief divide to saver: /= */\nstruct divto {\n  /*! \\brief save b to a using save method */\n  template<typename DType>\n  MSHADOW_XINLINE static void Save(DType& a, DType b) {\n    a /= b;\n  }\n  /*! \\brief corresponding binary operator type */\n  typedef op::div OPType;\n};\n}  // namespace sv\n/*! \\brief namespace for potential reducer operations */\nnamespace red {\nnamespace limits {\n/*!\n * \\brief minimum value of certain types \n * \\tparam DType data type\n */\ntemplate<typename DType>\nMSHADOW_XINLINE DType MinValue(void);\n/*! \\brief minimum value of float */\ntemplate<>\nMSHADOW_XINLINE float MinValue<float>(void) {\n  return -FLT_MAX;\n}\n/*! \\brief minimum value of double */\ntemplate<>\nMSHADOW_XINLINE double MinValue<double>(void) {\n  return -DBL_MAX;\n}\n/*! \\brief minimum value of int */\ntemplate<>\nMSHADOW_XINLINE int MinValue<int>(void) {\n  return INT_MIN;\n}\n}  // namespace limits\n\n/*! \\brief sum reducer */\nstruct sum {\n  /*! \\brief do reduction into dst */\n  template<typename DType>\n  MSHADOW_XINLINE static void Reduce(volatile DType& dst,  volatile DType src) {\n    dst += src;\n  }\n  /*! \n   *\\brief calculate gradient of redres with respect to redsrc,\n   * redres: reduced result, redsrc: one of reduction element   \n   */\n  template<typename DType>\n  MSHADOW_XINLINE static DType PartialGrad(DType redres, DType redsrc) {\n    return 1;\n  }\n  /*!\n   *\\brief set the initial value during reduction\n   */  \n  template<typename DType>\n  MSHADOW_XINLINE static void SetInitValue(DType &initv) {\n    initv = 0;\n  }\n};\n/*! \\brief maximum reducer */\nstruct maximum {\n  /*! \\brief do reduction into dst */\n  template<typename DType>\n  MSHADOW_XINLINE static void Reduce(volatile DType& dst,  volatile DType src) {\n    using namespace std;\n    dst = max(dst, src);\n  }\n  /*!\n   * \\brief calculate gradient of redres with respect to redsrc,\n   * redres: reduced result, redsrc: one of reduction element\n   */\n  template<typename DType>\n  MSHADOW_XINLINE static DType PartialGrad(DType redres, DType redsrc) {\n    return redres == redsrc ? 1: 0;\n  }\n  /*!\n   *\\brief set the initial value during reduction\n   */  \n  template<typename DType>\n  MSHADOW_XINLINE static void SetInitValue(DType &initv) {\n    initv = limits::MinValue<DType>();\n  }\n};\n}  // namespace red\n}  // namespace mshadow\n#endif  // MSHADOW_BASE_H_\n", "meta": {"hexsha": "6336dfa023bcc15baed7ff45e0bf33ba6755d466", "size": 9789, "ext": "h", "lang": "C", "max_stars_repo_path": "mshadow/base.h", "max_stars_repo_name": "Kingnus/mshadow", "max_stars_repo_head_hexsha": "5491dfbb8e491ff9315e7b8b03db2d97dcee5575", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-04-21T05:41:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-17T16:42:46.000Z", "max_issues_repo_path": "mshadow/base.h", "max_issues_repo_name": "Kingnus/mshadow", "max_issues_repo_head_hexsha": "5491dfbb8e491ff9315e7b8b03db2d97dcee5575", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mshadow/base.h", "max_forks_repo_name": "Kingnus/mshadow", "max_forks_repo_head_hexsha": "5491dfbb8e491ff9315e7b8b03db2d97dcee5575", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1916666667, "max_line_length": 84, "alphanum_fraction": 0.707120237, "num_tokens": 2685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167299096624174, "lm_q2_score": 0.06560484156961124, "lm_q1q2_score": 0.02897588659791663}}
{"text": "/* -----------------------------------------------------------------------------\n * Copyright 2021 Jonathan Haigh\n * SPDX-License-Identifier: MIT\n * ---------------------------------------------------------------------------*/\n\n#ifndef SQ_INCLUDE_GUARD_parser_Parser_inl_h_\n#define SQ_INCLUDE_GUARD_parser_Parser_inl_h_\n\n#include <charconv>\n\n#include \"core/ASSERT.h\"\n#include \"core/errors.h\"\n\n#include <gsl/gsl>\n\nnamespace sq::parser {\n\ntemplate <std::integral Int> std::optional<Int> Parser::parse_integer() {\n  const auto opt_token = accept_token(TokenKind::Integer);\n  if (!opt_token) {\n    return std::nullopt;\n  }\n  const auto &token = opt_token.value();\n  const auto str_view = token.view();\n  ASSERT(!str_view.empty());\n  const auto *begin = str_view.data();\n  // We can't really avoid using pointer arithmetic when using\n  // std::from_chars - it requires a const char* to indicate the end of the\n  // string, but we can only reasonably make one using pointer arithmetic.\n  // In particular, std::string, std::string_view, std::span etc. only\n  // provide iterator versions of end(), but we need a pointer.\n  // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)\n  const auto *end = begin + str_view.size();\n  Int value = 0;\n  const auto [ptr, ec] = std::from_chars(begin, end, value, 10);\n  if (ec == std::errc::result_out_of_range) {\n    auto ss = std::ostringstream{};\n    ss << \"integer \" << str_view << \" does not fit in required type; \"\n       << \"must be in the closed interval [\" << std::numeric_limits<Int>::min()\n       << \", \" << std::numeric_limits<Int>::max() << \"]\";\n    throw OutOfRangeError{token, ss.str()};\n  }\n  ASSERT(ec == std::errc{});\n  ASSERT(ptr == end);\n  return value;\n}\n\n} // namespace sq::parser\n\n#endif // SQ_INCLUDE_GUARD_parser_Parser_inl_h_\n", "meta": {"hexsha": "4d6fed98e4d1171e46dcabf6e4bbec25c769d909", "size": 1795, "ext": "h", "lang": "C", "max_stars_repo_path": "src/parser/include/parser/Parser.inl.h", "max_stars_repo_name": "jonathanhaigh/sq", "max_stars_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-12T16:21:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-12T16:21:41.000Z", "max_issues_repo_path": "src/parser/include/parser/Parser.inl.h", "max_issues_repo_name": "jonathanhaigh/sq", "max_issues_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 44.0, "max_issues_repo_issues_event_min_datetime": "2021-02-08T19:17:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-05T18:51:38.000Z", "max_forks_repo_path": "src/parser/include/parser/Parser.inl.h", "max_forks_repo_name": "jonathanhaigh/sq", "max_forks_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1960784314, "max_line_length": 80, "alphanum_fraction": 0.6267409471, "num_tokens": 435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473339755163, "lm_q2_score": 0.06656918434088001, "lm_q1q2_score": 0.028634557169154223}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef type_3f1a28e2_0da6_44b6_84db_29542f5a65c0_h\r\n#define type_3f1a28e2_0da6_44b6_84db_29542f5a65c0_h\r\n\r\n#include <utility>\r\n#include <gslib/basetype.h>\r\n#include <gslib/math.h>\r\n\r\n__gslib_begin__\r\n\r\ntemplate<class _ty, class _protopt>\r\nstruct point_t:\r\n    public _protopt\r\n{\r\n    typedef _ty type;\r\n    typedef _protopt proto;\r\n    typedef point_t<_ty, _protopt> myref;\r\n\r\npublic:\r\n    point_t() { this->x = 0; this->y = 0; }\r\n    point_t(const proto& p): proto(p) {}\r\n    point_t(type a, type b) { this->x = a; this->y = b; }\r\n    void offset(type u, type v) { this->x += u; this->y += v; }\r\n    void offset(const proto& p) { this->x += p.x; this->y += p.y; }\r\n    void set_point(type a, type b) { this->x = a; this->y = b; }\r\n    bool operator == (const myref& that) const { return this->x == that.x && this->y == that.y; }\r\n    bool operator != (const myref& that) const { return this->x != that.x || this->y != that.y; }\r\n};\r\n\r\nstruct vec2i { int x, y; };\r\ntypedef point_t<int, vec2i> point;\r\ntypedef point_t<float, vec2> pointf;\r\n\r\ntemplate<class _ty, class _ptcls>\r\nstruct rect_t\r\n{\r\n    typedef _ty type;\r\n    typedef rect_t<_ty, _ptcls> myref;\r\n    typedef _ptcls point;\r\n\r\npublic:\r\n    type    left, top, right, bottom;\r\n\r\npublic:\r\n    rect_t()\r\n    {\r\n        left = 0;\r\n        top = 0;\r\n        right = 0;\r\n        bottom = 0;\r\n    }\r\n    rect_t(type l, type t, type w, type h) { set_rect(l, t, w, h); }\r\n    type width() const { return right - left; }\r\n    type height() const { return bottom - top; }\r\n    void set_rect(type l, type t, type w, type h)\r\n    {\r\n        left = l;\r\n        top = t;\r\n        right = l + w;\r\n        bottom = t + h;\r\n    }\r\n    void set_ltrb(type l, type t, type r, type b)\r\n    {\r\n        left = l;\r\n        top = t;\r\n        right = r;\r\n        bottom = b;\r\n    }\r\n    void set_by_pts(const point& p1, const point& p2)\r\n    {\r\n        left = gs_min(p1.x, p2.x);\r\n        top = gs_min(p1.y, p2.y);\r\n        right = gs_max(p1.x, p2.x);\r\n        bottom = gs_max(p1.y, p2.y);\r\n    }\r\n    bool in_rect(const point& pt) const { return pt.x >= left && pt.x < right && pt.y >= top && pt.y < bottom; }\r\n    void offset(type x, type y) { left += x; right += x; top += y; bottom += y; }\r\n    void deflate(type u, type v);\r\n    void move_to(const point& pt) { move_to(pt.x, pt.y); }\r\n    void move_to(type x, type y);\r\n    bool operator == (const myref& that) const { return left == that.left && right == that.right && top == that.top && bottom == that.bottom; }\r\n    bool operator != (const myref& that) const { return left != that.left || right != that.right || top != that.top || bottom != that.bottom; }\r\n    type area() const { return width() * height(); }\r\n    point center() const\r\n    {\r\n        point c;\r\n        c.x = (left + right) / 2;\r\n        c.y = (top + bottom) / 2;\r\n        return c;\r\n    }\r\n    point top_left() const { return point(left, top); }\r\n    point top_right() const { return point(right, top); }\r\n    point bottom_left() const { return point(left, bottom); }\r\n    point bottom_right() const { return point(right, bottom); }\r\n};\r\n\r\ntypedef rect_t<int, point> rect;\r\ntypedef rect_t<float, pointf> rectf;\r\n\r\ninline rectf to_rectf(const rect& rc)\r\n{\r\n    return std::move(rectf((float)rc.left, (float)rc.top, (float)rc.width(), (float)rc.height()));\r\n}\r\n\r\ninline rect to_aligned_rect(const rectf& rc)\r\n{\r\n    return std::move(rect(round(rc.left), round(rc.top), round(rc.width()), round(rc.height())));\r\n}\r\n\r\ngs_export extern bool intersect_rect(rect& rc, const rect& rc1, const rect& rc2);\r\ngs_export extern bool is_rect_intersected(const rect& rc1, const rect& rc2);\r\ngs_export extern void union_rect(rect& rc, const rect& rc1, const rect& rc2);\r\ngs_export extern bool substract_rect(rect& rc, const rect& rc1, const rect& rc2);\r\ngs_export extern bool intersect_rect(rectf& rc, const rectf& rc1, const rectf& rc2);\r\ngs_export extern bool is_rect_intersected(const rectf& rc1, const rectf& rc2);\r\ngs_export extern bool is_rect_contained(const rect& rc1, const rect& rc2);\r\ngs_export extern bool is_rect_contained(const rectf& rc1, const rectf& rc2);\r\ngs_export extern void union_rect(rectf& rc, const rectf& rc1, const rectf& rc2);\r\ngs_export extern bool substract_rect(rectf& rc, const rectf& rc1, const rectf& rc2);\r\ngs_export extern bool is_line_rect_overlapped(const point& p1, const point& p2, const rect& rc);\r\ngs_export extern bool is_line_rect_overlapped(const pointf& p1, const pointf& p2, const rectf& rc);\r\n\r\n__gslib_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "46174f5fa068275d52a85c8ffc77be91f6045a3c", "size": 5773, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gslib/type.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/gslib/type.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gslib/type.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 37.9802631579, "max_line_length": 144, "alphanum_fraction": 0.6429932444, "num_tokens": 1601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416729909662417, "lm_q2_score": 0.06465348520228963, "lm_q1q2_score": 0.028555698185686908}}
{"text": "#pragma once\n\n#include <complex>\n#include <cstddef>\n#include <cstdint>\n#include <iosfwd>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include <gsl/gsl>\n\n#include \"chainerx/error.h\"\n#include \"chainerx/float16.h\"\n\nnamespace chainerx {\n\n// NOTE: The dtype list is not fixed yet!!!\nenum class Dtype {\n    kBool = 1,\n    kInt8,\n    kInt16,\n    kInt32,\n    kInt64,\n    kUInt8,\n    kFloat16,\n    kFloat32,\n    kFloat64,\n};\n\ninline bool IsValidDtype(Dtype dtype) {\n    using Underlying = std::underlying_type_t<Dtype>;\n    auto value = static_cast<Underlying>(dtype);\n    return 1 <= value && value <= static_cast<Underlying>(Dtype::kFloat64);\n}\n\nstd::ostream& operator<<(std::ostream& os, Dtype dtype);\n\n}  // namespace chainerx\n\nnamespace std {\n\ntemplate <>\nstruct hash<::chainerx::Dtype> {\n    size_t operator()(::chainerx::Dtype dtype) const {\n        using T = std::underlying_type_t<::chainerx::Dtype>;\n        return hash<T>()(static_cast<T>(dtype));\n    }\n};\n\n}  // namespace std\n\nnamespace chainerx {\n\n// Kind of dtypes.\nenum class DtypeKind {\n    kBool = 0,\n    kInt,\n    kUInt,\n    kFloat,\n};\n\n// Gets the single character identifier compatible to NumPy's dtype kind\ninline char GetDtypeKindChar(DtypeKind kind) {\n    switch (kind) {\n        case DtypeKind::kBool:\n            return 'b';\n        case DtypeKind::kInt:\n            return 'i';\n        case DtypeKind::kUInt:\n            return 'u';\n        case DtypeKind::kFloat:\n            return 'f';\n        default:\n            throw DtypeError{\"invalid dtype kind\"};\n    }\n}\n\ntemplate <typename T>\nconstexpr bool IsFloatingPointV = std::is_floating_point<T>::value || std::is_same<std::remove_const_t<T>, Float16>::value;\n\n// Tag type used for dynamic dispatching with dtype value.\n//\n// This class template is used to resolve mapping from runtime dtype values to compile-time primitive types.\ntemplate <typename T>\nstruct PrimitiveType;\n\n#define CHAINERX_DEFINE_PRIMITIVE_TYPE(name, code, dtype, kind, t, dst) \\\n    template <>                                                         \\\n    struct PrimitiveType<t> {                                           \\\n        using type = t;                                                 \\\n        using device_storage_type = dst;                                \\\n        static constexpr char kCharCode = code;                         \\\n        static constexpr Dtype kDtype = dtype;                          \\\n        static constexpr int64_t kElementSize = sizeof(type);           \\\n        static constexpr DtypeKind kKind = kind;                        \\\n        static const char* GetName() { return name; }                   \\\n    }\n\n// TODO(niboshi): Char codes are mapped according to current development environment. They should be remapped depending on the executing\n// environment, as in NumPy.\nCHAINERX_DEFINE_PRIMITIVE_TYPE(\"bool\", '?', Dtype::kBool, DtypeKind::kBool, bool, bool);\nCHAINERX_DEFINE_PRIMITIVE_TYPE(\"int8\", 'b', Dtype::kInt8, DtypeKind::kInt, int8_t, int8_t);\nCHAINERX_DEFINE_PRIMITIVE_TYPE(\"int16\", 'h', Dtype::kInt16, DtypeKind::kInt, int16_t, int16_t);\nCHAINERX_DEFINE_PRIMITIVE_TYPE(\"int32\", 'i', Dtype::kInt32, DtypeKind::kInt, int32_t, int32_t);\nCHAINERX_DEFINE_PRIMITIVE_TYPE(\"int64\", 'l', Dtype::kInt64, DtypeKind::kInt, int64_t, int64_t);\nCHAINERX_DEFINE_PRIMITIVE_TYPE(\"uint8\", 'B', Dtype::kUInt8, DtypeKind::kUInt, uint8_t, uint8_t);\nCHAINERX_DEFINE_PRIMITIVE_TYPE(\"float16\", 'e', Dtype::kFloat16, DtypeKind::kFloat, chainerx::Float16, uint16_t);\nCHAINERX_DEFINE_PRIMITIVE_TYPE(\"float32\", 'f', Dtype::kFloat32, DtypeKind::kFloat, float, float);\nCHAINERX_DEFINE_PRIMITIVE_TYPE(\"float64\", 'd', Dtype::kFloat64, DtypeKind::kFloat, double, double);\n\n#undef CHAINERX_DEFINE_PRIMITIVE_TYPE\n\nnamespace dtype_detail {\ntemplate <typename To, typename From>\nusing WithConstnessOf = std::conditional_t<std::is_const<From>::value, std::add_const_t<To>, std::remove_const_t<To>>;\n}\n\ntemplate <typename T>\nusing TypeToDeviceStorageType = dtype_detail::WithConstnessOf<typename PrimitiveType<std::remove_const_t<T>>::device_storage_type, T>;\n\n// Dtype mapped from primitive type.\ntemplate <typename T>\nconstexpr Dtype TypeToDtype = PrimitiveType<std::remove_const_t<T>>::kDtype;\n\n// Invokes a function by passing PrimitiveType<T> corresponding to given dtype value.\n//\n// For example,\n//     VisitDtype(Dtype::kInt32, f, args...);\n// is equivalent to\n//     f(PrimtiveType<int>, args...);\n// Note that the dtype argument can be a runtime value. This function can be used for dynamic dispatching based on dtype values.\n//\n// Note (beam2d): This function should be constexpr, but GCC 5.x does not allow it because of the throw statement, so currently not marked\n// as constexpr.\ntemplate <typename F, typename... Args>\nauto VisitDtype(Dtype dtype, F&& f, Args&&... args) {\n    switch (dtype) {\n        case Dtype::kBool:\n            return std::forward<F>(f)(PrimitiveType<bool>{}, std::forward<Args>(args)...);\n        case Dtype::kInt8:\n            return std::forward<F>(f)(PrimitiveType<int8_t>{}, std::forward<Args>(args)...);\n        case Dtype::kInt16:\n            return std::forward<F>(f)(PrimitiveType<int16_t>{}, std::forward<Args>(args)...);\n        case Dtype::kInt32:\n            return std::forward<F>(f)(PrimitiveType<int32_t>{}, std::forward<Args>(args)...);\n        case Dtype::kInt64:\n            return std::forward<F>(f)(PrimitiveType<int64_t>{}, std::forward<Args>(args)...);\n        case Dtype::kUInt8:\n            return std::forward<F>(f)(PrimitiveType<uint8_t>{}, std::forward<Args>(args)...);\n        case Dtype::kFloat16:\n            return std::forward<F>(f)(PrimitiveType<chainerx::Float16>{}, std::forward<Args>(args)...);\n        case Dtype::kFloat32:\n            return std::forward<F>(f)(PrimitiveType<float>{}, std::forward<Args>(args)...);\n        case Dtype::kFloat64:\n            return std::forward<F>(f)(PrimitiveType<double>{}, std::forward<Args>(args)...);\n        default:\n            throw DtypeError{\"invalid dtype: \", static_cast<std::underlying_type_t<Dtype>>(dtype)};\n    }\n}\n\n// Invokes a function by passing PrimitiveType<T> corresponding to given numeric dtype value.\n// See VisitDtype for more detail.\ntemplate <typename F, typename... Args>\nauto VisitNumericDtype(Dtype dtype, F&& f, Args&&... args) {\n    switch (dtype) {\n        case Dtype::kInt8:\n            return std::forward<F>(f)(PrimitiveType<int8_t>{}, std::forward<Args>(args)...);\n        case Dtype::kInt16:\n            return std::forward<F>(f)(PrimitiveType<int16_t>{}, std::forward<Args>(args)...);\n        case Dtype::kInt32:\n            return std::forward<F>(f)(PrimitiveType<int32_t>{}, std::forward<Args>(args)...);\n        case Dtype::kInt64:\n            return std::forward<F>(f)(PrimitiveType<int64_t>{}, std::forward<Args>(args)...);\n        case Dtype::kUInt8:\n            return std::forward<F>(f)(PrimitiveType<uint8_t>{}, std::forward<Args>(args)...);\n        case Dtype::kFloat16:\n            return std::forward<F>(f)(PrimitiveType<chainerx::Float16>{}, std::forward<Args>(args)...);\n        case Dtype::kFloat32:\n            return std::forward<F>(f)(PrimitiveType<float>{}, std::forward<Args>(args)...);\n        case Dtype::kFloat64:\n            return std::forward<F>(f)(PrimitiveType<double>{}, std::forward<Args>(args)...);\n        default:\n            throw DtypeError{\"invalid dtype\"};\n    }\n}\n\n// Invokes a function by passing PrimitiveType<T> corresponding to given floating-point dtype value.\n// See VisitDtype for more detail.\ntemplate <typename F, typename... Args>\nauto VisitFloatingPointDtype(Dtype dtype, F&& f, Args&&... args) {\n    switch (dtype) {\n        case Dtype::kFloat16:\n            return std::forward<F>(f)(PrimitiveType<chainerx::Float16>{}, std::forward<Args>(args)...);\n        case Dtype::kFloat32:\n            return std::forward<F>(f)(PrimitiveType<float>{}, std::forward<Args>(args)...);\n        case Dtype::kFloat64:\n            return std::forward<F>(f)(PrimitiveType<double>{}, std::forward<Args>(args)...);\n        default:\n            throw DtypeError{\"invalid dtype\"};\n    }\n}\n\n// Gets the single character identifier compatible to NumPy's char code\ninline char GetCharCode(Dtype dtype) {\n    return VisitDtype(dtype, [](auto pt) { return decltype(pt)::kCharCode; });\n}\n\n// Gets the element size of the dtype in bytes.\ninline int64_t GetItemSize(Dtype dtype) {\n    return VisitDtype(dtype, [](auto pt) { return decltype(pt)::kElementSize; });\n}\n\n// Gets the kind of dtype.\ninline DtypeKind GetKind(Dtype dtype) {\n    return VisitDtype(dtype, [](auto pt) { return decltype(pt)::kKind; });\n}\n\nDtype PromoteTypes(Dtype dt1, Dtype dt2);\n\n// const char* representation of dtype compatible to NumPy's dtype name.\ninline const char* GetDtypeName(Dtype dtype) {\n    return VisitDtype(dtype, [](auto pt) { return decltype(pt)::GetName(); });\n}\n\n// Gets the dtype of given name.\nDtype GetDtype(const std::string& name);\n\n// Returns a vector of all possible dtype values.\nstd::vector<Dtype> GetAllDtypes();\n\n// Throws an exception if two dtypes mismatch.\nvoid CheckEqual(Dtype lhs, Dtype rhs);\n\n}  // namespace chainerx\n", "meta": {"hexsha": "2c1fcf71c6e1b287a30ab9d5cd3360b02a9f0593", "size": 9121, "ext": "h", "lang": "C", "max_stars_repo_path": "chainerx_cc/chainerx/dtype.h", "max_stars_repo_name": "hikjik/chainer", "max_stars_repo_head_hexsha": "324a1bc1ea3edd63d225e4a87ed0a36af7fd712f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-09T07:39:07.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-09T07:39:07.000Z", "max_issues_repo_path": "chainerx_cc/chainerx/dtype.h", "max_issues_repo_name": "hitsgub/chainer", "max_issues_repo_head_hexsha": "20d4d70f5cdacc1f24f243443f5bebc2055c8f8e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chainerx_cc/chainerx/dtype.h", "max_forks_repo_name": "hitsgub/chainer", "max_forks_repo_head_hexsha": "20d4d70f5cdacc1f24f243443f5bebc2055c8f8e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.6483050847, "max_line_length": 138, "alphanum_fraction": 0.6477359939, "num_tokens": 2312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936415888237616, "lm_q2_score": 0.07921032084852896, "lm_q1q2_score": 0.02846535032653475}}
{"text": "/*\r\nThis file is a part of NNTL project (https://github.com/Arech/nntl)\r\n\r\nCopyright (c) 2015-2021, Arech (aradvert@gmail.com; https://github.com/Arech)\r\nAll rights reserved.\r\n\r\nRedistribution and use in source and binary forms, with or without\r\nmodification, are permitted provided that the following conditions are met:\r\n\r\n* Redistributions of source code must retain the above copyright notice, this\r\n  list of conditions and the following disclaimer.\r\n\r\n* Redistributions in binary form must reproduce the above copyright notice,\r\n  this list of conditions and the following disclaimer in the documentation\r\n  and/or other materials provided with the distribution.\r\n\r\n* Neither the name of NNTL nor the names of its\r\n  contributors may be used to endorse or promote products derived from\r\n  this software without specific prior written permission.\r\n\r\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\r\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\r\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\r\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\r\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\r\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\r\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n*/\r\n#pragma once\r\n\r\n#include <cblas.h>\r\n//TODO: function definitions (like dgemm()) conflicts with similar function definitions in ACML. It builds successfully, but\r\n//links to wrong library and access violation happens in run-time.\r\n\r\n#include <complex>\r\n#define lapack_complex_float ::std::complex<float>\r\n#define lapack_complex_double ::std::complex<double>\r\n#include <lapacke.h>\r\n\r\n//#include \"../../../utils/denormal_floats.h\"\r\n\r\n#pragma comment(lib,\"libopenblas.dll.a\")\r\n\r\n//what else to do to use OpenBLAS:\r\n// -in the Solution's VC++ Directories property page set parameter Library Directories to point to a folder with the libopenblas.dll.a file\r\n// -copy correct libopenblas.dll and another dlls that the libopenblas.dll require to the debug/release solution's folder\r\n// -if you're going to use any calling convetion except for __cdecl, then most likely, you'll have to update function declarations\r\n//\t\twithin the cblas.h and other blas's .h files included to contain the __cdecl keyword (it's absent for some reason).\r\n//\t\tCheck the b_OpenBLAS:: methods to find out which function definitions should be changed.\r\n\r\n\r\n//http://www.christophlassner.de/using-blas-from-c-with-row-major-data.html\r\n\r\n// BTW: lda,ldb,ldc is a \"major stride\". The stride represents the distance in memory between elements in adjacent rows\r\n// (if row-major) or in adjacent columns (if column-major). This means that the stride is usually equal to the number\r\n// of rows/columns in the matrix.\r\n// Matrix A = [1 2 3]\r\n//            [4 5 6]\r\n// Row-major stores values as {1,2,3,4,5,6} Stride here is 3\r\n// Col-major stores values as {1,4,2,5,3,6} Stride here is 2\r\n// (https://www.physicsforums.com/threads/understanding-blas-dgemm-in-c.543110/)\r\n\r\n\r\n\r\nnamespace nntl {\r\nnamespace math {\r\n\r\n\t// wrapper around BLAS API. Should at least isolate from double/float differences\r\n\t// Also, we are going to use ColMajor ordering in all math libraries (most of them use it by default)\r\n\t// EXPECTING data to be in COL-MAJOR mode!\r\n\t// \r\n\t// NB: Leading dimension is the number of elements in major dimension. We're using Col-Major ordering,\r\n\t// therefore it is the number of ROWs of a matrix\r\n\tstruct b_OpenBLAS {\r\n\tprivate:\r\n\t\ttypedef utils::_scoped_restore_FPU _restoreFPU;\r\n\tpublic:\r\n\t\t//TODO: beware that sz_t type used as substitution of blasint can overflow blasint and silencing conversion warnings here can make it difficult to debug!\r\n\t\t//TODO: May be there should be some preliminary check for this condition.\r\n\r\n\t\t//////////////////////////////////////////////////////////////////////////\r\n\t\t//////////////////////////////////////////////////////////////////////////\r\n\t\t// LEVEL 1\r\n\t\t// AXPY y=a*x+y\r\n\t\ttemplate<typename sz_t, typename fl_t>\r\n\t\tstatic typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t<fl_t>, double>::value > axpy(\r\n\t\t\tconst sz_t n, const fl_t alpha, const fl_t *x, const sz_t incx, fl_t *y, const sz_t incy)\r\n\t\t{\r\n\t\t\t_restoreFPU r;\r\n\t\t\tcblas_daxpy(static_cast<blasint>(n), alpha, x, static_cast<blasint>(incx), y, static_cast<blasint>(incy));\r\n\t\t}\r\n\t\ttemplate<typename sz_t, typename fl_t>\r\n\t\tstatic typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t<fl_t>, float>::value > axpy(\r\n\t\t\tconst sz_t n, const fl_t alpha, const fl_t *x, const sz_t incx, fl_t *y, const sz_t incy)\r\n\t\t{\r\n\t\t\t_restoreFPU r;\r\n\t\t\tcblas_saxpy(static_cast<blasint>(n), alpha, x, static_cast<blasint>(incx), y, static_cast<blasint>(incy));\r\n\t\t}\r\n\r\n\t\t//////////////////////////////////////////////////////////////////////////\r\n\t\t// cblas_?dot\r\n\t\t// Computes a vector - vector dot product.\r\n\t\t//\tInput Parameters\r\n\t\t// n - Specifies the number of elements in vectors x and y.\r\n\t\t// x - Array, size at least(1 + (n - 1)*abs(incx)).\r\n\t\t// incx - Specifies the increment for the elements of x.\r\n\t\t// y - Array, size at least(1 + (n - 1)*abs(incy)).\r\n\t\t// incy - Specifies the increment for the elements of y.\r\n\t\t// Return Values - The result of the dot product of x and y, if n is positive.Otherwise, returns 0.\r\n\t\t//https://software.intel.com/en-us/mkl-developer-reference-c-cblas-dot\r\n\t\ttemplate<typename sz_t, typename fl_t>\r\n\t\tstatic typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t<fl_t>, double>::value, double >\r\n\t\t\tdot(const sz_t n, const fl_t *x, const sz_t incx, const fl_t *y, const sz_t incy)\r\n\t\t{\r\n\t\t\t_restoreFPU r;\r\n\t\t\treturn cblas_ddot(static_cast<blasint>(n), x, static_cast<blasint>(incx), y, static_cast<blasint>(incy));\r\n\t\t}\r\n\t\ttemplate<typename sz_t, typename fl_t>\r\n\t\tstatic typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t<fl_t>, float>::value, float >\r\n\t\t\tdot(const sz_t n, const fl_t *x, const sz_t incx, const fl_t *y, const sz_t incy)\r\n\t\t{\r\n\t\t\t_restoreFPU r;\r\n\t\t\treturn cblas_sdot(static_cast<blasint>(n), x, static_cast<blasint>(incx), y, static_cast<blasint>(incy));\r\n\t\t}\r\n\r\n\r\n\t\t//////////////////////////////////////////////////////////////////////////\r\n\t\t//////////////////////////////////////////////////////////////////////////\r\n\t\t// LEVEL 2\r\n\r\n\t\t\r\n\t\t//////////////////////////////////////////////////////////////////////////\r\n\t\t//////////////////////////////////////////////////////////////////////////\r\n\t\t// LEVEL 3\r\n\t\t// \r\n\t\t//////////////////////////////////////////////////////////////////////////\r\n\t\t// General matrix multiplication\r\n\t\t// GEMM C := alpha*op(A)*op(B) + beta*C\r\n\t\t// https://software.intel.com/en-us/node/520775\r\n\t\t// where:\r\n\t\t// op(X) is one of op(X) = X, or op(X) = XT, or op(X) = XH,\r\n\t\t// alpha and beta are scalars,\r\n\t\t// A, B and C are matrices :\r\n\t\t// op(A) is an m - by - k matrix,\r\n\t\t// op(B) is a k - by - n matrix,\r\n\t\t// C is an m - by - n matrix.\r\n\t\t// \r\n\t\t// M - Specifies the number of rows of the matrix op(A) and of the matrix C. The value of m must be at least zero.\r\n\t\t// N - Specifies the number of columns of the matrix op(B) and the number of columns of the matrix C. The value of n must be at least zero.\r\n\t\t// K - Specifies the number of columns of the matrix op(A) and the number of rows of the matrix op(B). The value of k must be at least zero.\r\n\t\t// A - {transa=CblasNoTrans : Array, size lda*k. Before entry, the leading m-by-k part of the array a must contain the matrix A.\r\n\t\t//\t\ttransa=CblasTrans : Array, size lda*m. Before entry, the leading k-by-m part of the array a must contain the matrix A.}\r\n\t\t// lda - Specifies the leading dimension of A as declared in the calling (sub)program.\r\n\t\t//\t\t{transa=CblasNoTrans, lda must be at least max(1, m).\r\n\t\t//\t\ttransa=CblasTrans, lda must be at least max(1, k)}\r\n\t\t// B - {transb=CblasNoTrans : Array, size ldb by n. Before entry, the leading k-by-n part of the array b must contain the matrix B.\r\n\t\t//\t\ttransb=CblasTrans : Array, size ldb by k. Before entry the leading n-by-k part of the array b must contain the matrix B.}\r\n\t\t// ldb - Specifies the leading dimension of B as declared in the calling (sub)program.\r\n\t\t//\t\t{transb = CblasNoTrans : ldb must be at least max(1, k).\r\n\t\t//\t\ttransb=CblasTrans : ldb must be at least max(1, n).}\r\n\t\t// C - Array, size ldc by n. Before entry, the leading m-by-n part of the array c must contain the matrix C, except when beta is\r\n\t\t//\t\tequal to zero, in which case c need not be set on entry.\r\n\t\t// ldc - Specifies the leading dimension of c as declared in the calling (sub)program. ldc must be at least max(1, m).\r\n\t\ttemplate<typename sz_t, typename fl_t>\r\n\t\tstatic typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t<fl_t>, double>::value >\r\n\t\t\tgemm( //const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB,\r\n\t\t\tconst bool bTransposeA, const bool bTransposeB,\r\n\t\t\tconst sz_t M, const sz_t N, const sz_t K, const fl_t alpha, const fl_t *A, const sz_t lda,\r\n\t\t\tconst fl_t *B, const sz_t ldb, const fl_t beta, fl_t *C, const sz_t ldc)\r\n\t\t{\r\n\t\t\t_restoreFPU r;\r\n\t\t\tcblas_dgemm(CblasColMajor, bTransposeA ? CblasTrans : CblasNoTrans, bTransposeB ? CblasTrans : CblasNoTrans,\r\n\t\t\t\tstatic_cast<blasint>(M), static_cast<blasint>(N), static_cast<blasint>(K),\r\n\t\t\t\talpha, A, static_cast<blasint>(lda), B, static_cast<blasint>(ldb), beta, C, static_cast<blasint>(ldc));\r\n\t\t\t//global_denormalized_floats_mode();\r\n\t\t}\r\n\t\ttemplate<typename sz_t, typename fl_t>\r\n\t\tstatic typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t<fl_t>, float>::value >\r\n\t\t\tgemm( //const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB,\r\n\t\t\tconst bool bTransposeA, const bool bTransposeB,\r\n\t\t\tconst sz_t M, const sz_t N, const sz_t K, const fl_t alpha, const fl_t *A, const sz_t lda,\r\n\t\t\tconst fl_t *B, const sz_t ldb, const fl_t beta, fl_t *C, const sz_t ldc)\r\n\t\t{\r\n\t\t\t_restoreFPU r;\r\n\t\t\tcblas_sgemm(CblasColMajor, bTransposeA ? CblasTrans: CblasNoTrans, bTransposeB ? CblasTrans : CblasNoTrans,\r\n\t\t\t\tstatic_cast<blasint>(M), static_cast<blasint>(N), static_cast<blasint>(K),\r\n\t\t\t\talpha, A, static_cast<blasint>(lda), B, static_cast<blasint>(ldb), beta, C, static_cast<blasint>(ldc));\r\n\t\t\t//global_denormalized_floats_mode();\r\n\t\t}\r\n\r\n\t\t//////////////////////////////////////////////////////////////////////////\r\n\t\t// cblas_?syrk, https://software.intel.com/en-us/node/520780\r\n\t\t// Performs a symmetric rank-k update.\r\n\t\t// The ?syrk routines perform a rank-k matrix-matrix operation for a symmetric matrix C using a general matrix A.\r\n\t\t// The operation is defined as:\r\n\t\t// C := alpha*A*A' + beta*C,\r\n\t\t//\t\tor\r\n\t\t// C : = alpha*A'*A + beta*C,\r\n\t\t// where :\r\n\t\t//\t\talpha and beta are scalars,\r\n\t\t//\t\tC is an n-by-n symmetric matrix,\r\n\t\t//\t\tA is an n-by-k matrix in the first case and a k-by-n matrix in the second case.\r\n\t\ttemplate<typename sz_t, typename fl_t>\r\n\t\tstatic typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t<fl_t>, double>::value >\r\n\t\t\tsyrk( const bool bCLowerTriangl, const bool bFirstATransposed, const sz_t N, const sz_t K, const fl_t alpha\r\n\t\t\t\t, const fl_t *A, const sz_t lda, const fl_t beta, fl_t *C, const sz_t ldc)\r\n\t\t{\r\n\t\t\t_restoreFPU r;\r\n\t\t\tcblas_dsyrk(CblasColMajor, bCLowerTriangl ? CblasLower : CblasUpper, bFirstATransposed ? CblasTrans : CblasNoTrans\r\n\t\t\t\t, static_cast<blasint>(N), static_cast<blasint>(K), alpha, A, static_cast<blasint>(lda), beta, C, static_cast<blasint>(ldc));\r\n\t\t\t//global_denormalized_floats_mode();\r\n\t\t}\r\n\t\ttemplate<typename sz_t, typename fl_t>\r\n\t\tstatic typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t<fl_t>, float>::value >\r\n\t\t\tsyrk(const bool bCLowerTriangl, const bool bFirstATransposed, const sz_t N, const sz_t K, const fl_t alpha\r\n\t\t\t\t, const fl_t *A, const sz_t lda, const fl_t beta, fl_t *C, const sz_t ldc)\r\n\t\t{\r\n\t\t\t_restoreFPU r;\r\n\t\t\tcblas_ssyrk(CblasColMajor, bCLowerTriangl ? CblasLower : CblasUpper, bFirstATransposed ? CblasTrans : CblasNoTrans\r\n\t\t\t\t, static_cast<blasint>(N), static_cast<blasint>(K), alpha, A, static_cast<blasint>(lda), beta, C, static_cast<blasint>(ldc));\r\n\t\t\t//global_denormalized_floats_mode();\r\n\t\t}\r\n\r\n\t\t//////////////////////////////////////////////////////////////////////////\r\n\t\t// cblas_?symm, https://software.intel.com/en-us/node/520779\r\n\t\t// Computes a matrix - matrix product where one input matrix is symmetric.\r\n\t\t// The ?symm routines compute a scalar-matrix-matrix product with one symmetric matrix and add the\r\n\t\t// result to a scalar-matrix product. The operation is defined as\r\n\t\t// C: = alpha*A*B + beta*C,\r\n\t\t//\t\tor\r\n\t\t// C : = alpha*B*A + beta*C,\r\n\t\t// where :\r\n\t\t//\t\talpha and beta are scalars,\r\n\t\t//\t\tA is a symmetric matrix,\r\n\t\t//\t\tB and C are m - by - n matrices.\r\n\t\ttemplate<typename sz_t, typename fl_t>\r\n\t\tstatic typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t<fl_t>, double>::value >\r\n\t\t\tsymm(const bool bSymmAatLeft, const bool bALowerTriangl, const sz_t M, const sz_t N, const fl_t alpha\r\n\t\t\t\t, const fl_t *A, const sz_t lda, const fl_t *B, const sz_t ldb, const fl_t beta, fl_t *C, const sz_t ldc)\r\n\t\t{\r\n\t\t\t_restoreFPU r;\r\n\t\t\tcblas_dsymm(CblasColMajor, bSymmAatLeft ? CblasLeft : CblasRight, bALowerTriangl ? CblasLower : CblasUpper\r\n\t\t\t\t, static_cast<blasint>(M), static_cast<blasint>(N), alpha, A, static_cast<blasint>(lda)\r\n\t\t\t\t, B, static_cast<blasint>(ldb), beta, C, static_cast<blasint>(ldc));\r\n\t\t\t//global_denormalized_floats_mode();\r\n\t\t}\r\n\t\ttemplate<typename sz_t, typename fl_t>\r\n\t\tstatic typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t<fl_t>, float>::value >\r\n\t\t\tsymm(const bool bSymmAatLeft, const bool bALowerTriangl, const sz_t M, const sz_t N, const fl_t alpha\r\n\t\t\t\t, const fl_t *A, const sz_t lda, const fl_t *B, const sz_t ldb, const fl_t beta, fl_t *C, const sz_t ldc)\r\n\t\t{\r\n\t\t\t_restoreFPU r;\r\n\t\t\tcblas_ssymm(CblasColMajor, bSymmAatLeft ? CblasLeft : CblasRight, bALowerTriangl ? CblasLower : CblasUpper\r\n\t\t\t\t, static_cast<blasint>(M), static_cast<blasint>(N), alpha, A, static_cast<blasint>(lda)\r\n\t\t\t\t, B, static_cast<blasint>(ldb), beta, C, static_cast<blasint>(ldc));\r\n\t\t\t//global_denormalized_floats_mode();\r\n\t\t}\r\n\r\n\r\n\t\t//////////////////////////////////////////////////////////////////////////\r\n\t\t//////////////////////////////////////////////////////////////////////////\r\n\t\t// LAPACKE\r\n\r\n\t\t// ?gesvd\r\n\t\t// https://software.intel.com/en-us/node/521150\r\n\t\ttemplate<typename sz_t, typename fl_t>\r\n\t\tstatic typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t<fl_t>, double>::value, int>\r\n\t\t\tgesvd(/*int matrix_layout,*/ const char jobu, const char jobvt,\r\n\t\t\t\tconst sz_t m, const sz_t n, fl_t* A,\r\n\t\t\t\tconst sz_t lda, fl_t* S, fl_t* U, const sz_t ldu,\r\n\t\t\t\tfl_t* Vt, const sz_t ldvt, fl_t* superb)\r\n\t\t{\r\n\t\t\t_restoreFPU r;\r\n\t\t\treturn static_cast<int>(LAPACKE_dgesvd(LAPACK_COL_MAJOR, jobu, jobvt, static_cast<lapack_int>(m), static_cast<lapack_int>(n)\r\n\t\t\t\t, A, static_cast<lapack_int>(lda), S, U, static_cast<lapack_int>(ldu), Vt, static_cast<lapack_int>(ldvt), superb));\r\n\t\t}\r\n\t\ttemplate<typename sz_t, typename fl_t>\r\n\t\tstatic typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t<fl_t>, float>::value, int>\r\n\t\t\tgesvd(/*int matrix_layout,*/ const char jobu, const char jobvt,\r\n\t\t\t\tconst sz_t m, const sz_t n, fl_t* A,\r\n\t\t\t\tconst sz_t lda, fl_t* S, fl_t* U, const sz_t ldu,\r\n\t\t\t\tfl_t* Vt, const sz_t ldvt, fl_t* superb)\r\n\t\t{\r\n\t\t\t_restoreFPU r;\r\n\t\t\treturn static_cast<int>(LAPACKE_sgesvd(LAPACK_COL_MAJOR, jobu, jobvt, static_cast<lapack_int>(m), static_cast<lapack_int>(n)\r\n\t\t\t\t, A, static_cast<lapack_int>(lda), S, U, static_cast<lapack_int>(ldu), Vt, static_cast<lapack_int>(ldvt), superb));\r\n\t\t}\r\n\r\n\r\n\t\t//////////////////////////////////////////////////////////////////////////\r\n\t\t//////////////////////////////////////////////////////////////////////////\r\n\t\t// Extensions\r\n\r\n\t\t// The omatcopy routine performs scaling and out-of-place transposition/copying of matrices. A transposition \r\n\t\t// operation can be a normal matrix copy, a transposition, a conjugate transposition, or just a conjugation.\r\n\t\t// The operation is defined as follows:\r\n\t\t// B : = alpha*op(A)\r\n\t\t// \r\n\t\t// Parameters\r\n\t\t// rows - The number of rows in the source matrix.\r\n\t\t// cols - The number of columns in the source matrix.\r\n\t\t// alpha - This parameter scales the input matrix by alpha.\r\n\t\t// pA - Array.\r\n\t\t// lda - Distance between the first elements in adjacent columns(in the case of the column - major order)\r\n\t\t//\t\tor rows(in the case of the row - major order) in the source matrix; measured in the number of elements.\r\n\t\t//\t\tThis parameter must be at least max(1, rows) if ordering = 'C' or 'c', and max(1, cols) otherwise.\r\n\t\t// b - Array.\r\n\t\t// ldb - Distance between the first elements in adjacent columns(in the case of the column - major order)\r\n\t\t//\t\tor rows(in the case of the row - major order) in the destination matrix; measured in the number of elements.\r\n\t\t//\t\tTo determine the minimum value of ldb on output, consider the following guideline :\r\n\t\t//\t\tIf ordering = 'C' or 'c', then\r\n\t\t//\t\t\tIf trans = 'T' or 't' or 'C' or 'c', this parameter must be at least max(1, cols)\r\n\t\t//\t\t\tIf trans = 'N' or 'n' or 'R' or 'r', this parameter must be at least max(1, rows)\r\n\t\t//\t\tIf ordering = 'R' or 'r', then\r\n\t\t//\t\t\tIf trans = 'T' or 't' or 'C' or 'c', this parameter must be at least max(1, rows)\r\n\t\t//\t\t\tIf trans = 'N' or 'n' or 'R' or 'r', this parameter must be at least max(1, cols)\r\n\t\t//\r\n\t\t// #warning current OpenBLAS implementation is slower, than it can be. See TEST(TestPerfDecisions, mTranspose) in test_perf_decisions.cpp\r\n\t\t//and https://github.com/xianyi/OpenBLAS/issues/1243\r\n\t\t// https://github.com/xianyi/OpenBLAS/issues/2532\r\n\t\t// https://stackoverflow.com/questions/16737298/what-is-the-fastest-way-to-transpose-a-matrix-in-c/16743203#16743203\r\n\t\ttemplate<typename sz_t, typename fl_t>\r\n\t\tstatic typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t<fl_t>, double>::value >\r\n\t\t\tomatcopy(const bool bTranspose, const sz_t rows, const sz_t cols, const fl_t alpha,\r\n\t\t\t\tconst fl_t* pA, const sz_t lda, fl_t* pB, const sz_t ldb)\r\n\t\t{\r\n\t\t\t_restoreFPU r;\r\n\t\t\tcblas_domatcopy(CblasColMajor, bTranspose ? CblasTrans : CblasNoTrans,\r\n\t\t\t\tstatic_cast<blasint>(rows), static_cast<blasint>(cols), alpha,\r\n\t\t\t\tpA, static_cast<blasint>(lda), pB, static_cast<blasint>(ldb));\r\n\t\t}\r\n\t\ttemplate<typename sz_t, typename fl_t>\r\n\t\tstatic typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t<fl_t>, float>::value >\r\n\t\t\tomatcopy(const bool bTranspose, const sz_t rows, const sz_t cols, const fl_t alpha,\r\n\t\t\t\tconst fl_t* pA, const sz_t lda, fl_t* pB, const sz_t ldb)\r\n\t\t{\r\n\t\t\t_restoreFPU r;\r\n\t\t\tcblas_somatcopy(CblasColMajor, bTranspose ? CblasTrans : CblasNoTrans,\r\n\t\t\t\tstatic_cast<blasint>(rows), static_cast<blasint>(cols), alpha,\r\n\t\t\t\tpA, static_cast<blasint>(lda), pB, static_cast<blasint>(ldb));\r\n\t\t}\r\n\r\n\t\ttemplate<typename sz_t, typename fl_t>\r\n\t\tstatic typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t<fl_t>, double>::value >\r\n\t\t\timatcopy(const bool bTranspose, const sz_t rows, const sz_t cols, const fl_t alpha,\r\n\t\t\t\tfl_t* pA, const sz_t lda, const sz_t ldb)\r\n\t\t{\r\n\t\t\t_restoreFPU r;\r\n\t\t\tcblas_dimatcopy(CblasColMajor, bTranspose ? CblasTrans : CblasNoTrans,\r\n\t\t\t\tstatic_cast<blasint>(rows), static_cast<blasint>(cols), alpha,\r\n\t\t\t\tpA, static_cast<blasint>(lda), static_cast<blasint>(ldb));\r\n\t\t}\r\n\t\ttemplate<typename sz_t, typename fl_t>\r\n\t\tstatic typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t<fl_t>, float>::value >\r\n\t\t\timatcopy(const bool bTranspose, const sz_t rows, const sz_t cols, const fl_t alpha,\r\n\t\t\t\tfl_t* pA, const sz_t lda, const sz_t ldb)\r\n\t\t{\r\n\t\t\t_restoreFPU r;\r\n\t\t\tcblas_simatcopy(CblasColMajor, bTranspose ? CblasTrans : CblasNoTrans,\r\n\t\t\t\tstatic_cast<blasint>(rows), static_cast<blasint>(cols), alpha,\r\n\t\t\t\tpA, static_cast<blasint>(lda), static_cast<blasint>(ldb));\r\n\t\t}\r\n\t};\r\n\r\n}\r\n}\r\n\r\n", "meta": {"hexsha": "7ee5d5aaa1f71f31b636368f557dda80c62f1e4a", "size": 20309, "ext": "h", "lang": "C", "max_stars_repo_path": "nntl/interface/math/bindings/b_open_blas.h", "max_stars_repo_name": "Arech/nntl", "max_stars_repo_head_hexsha": "fdcd7f33216c6414547acea3c4c172734ef9412a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2015-12-22T19:55:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-28T13:10:19.000Z", "max_issues_repo_path": "nntl/interface/math/bindings/b_open_blas.h", "max_issues_repo_name": "Arech/nntl", "max_issues_repo_head_hexsha": "fdcd7f33216c6414547acea3c4c172734ef9412a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nntl/interface/math/bindings/b_open_blas.h", "max_forks_repo_name": "Arech/nntl", "max_forks_repo_head_hexsha": "fdcd7f33216c6414547acea3c4c172734ef9412a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-10-15T11:12:33.000Z", "max_forks_repo_forks_event_max_datetime": "2017-10-15T11:12:33.000Z", "avg_line_length": 54.7412398922, "max_line_length": 156, "alphanum_fraction": 0.6642867694, "num_tokens": 5755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40733341443526055, "lm_q2_score": 0.06954175077306284, "lm_q1q2_score": 0.028326678788197605}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <argp.h>\n#include <string.h>\n#include <assert.h>\n#include <stdint.h>\n#include \"utils.h\"\n\n#ifdef USE_MKL\n#pragma message \"Using the MKL for BLAS.\"\n#include <mkl.h>\n#else\n#pragma message \"Not using the MKL for BLAS.\"\n#include <cblas.h>\n#endif\n\n#define MAX_LINES 2000\n#define NB_RUNS 1\n#define MAX_NAME_SIZE 256\n\n#define MAX_OFFSET 1000000\n#define WRITE_MEMORY_SIZE 100000000\n\nFILE* active_file = NULL;\nchar* basename = \"calibration\";\nchar* dir_name  = \".\";\n\nstatic double *matrix_A;\nstatic double *matrix_B;\nstatic double *matrix_C;\n\nunsigned long long base_time;\n\ntypedef struct {\n  char* sizefile;\n  int loop;\n  char* resultfile;\n} my_args;\n\nstatic char doc[] = \"Runs BLAS benchmarks to compute values used for SMPI calibration\";\n\n\nstatic struct argp_option options[] = {\n  {\"sizeFile\", 's', \"SIZEFILE\", 0, \"filename of the size list\"},\n  {\"resultfile\", 'o', \"RESULTFILE\", 0, \"filename of the results\"},\n  {\"loop\", 'l', \"NB_LOOPS\", 0, \"number of (non-recorded) loops to run before and after the execution\"},\n  { 0 }\n};\n\nstatic int parse_options (int key, char *arg, struct argp_state *state)\n{\n  my_args *arguments = state->input;\n  switch (key){\n  case 'l':\n    arguments->loop = atoi(arg);\n    break;\n  case 's':\n    arguments->sizefile = arg;\n    break;\n  case 'o':\n    arguments->resultfile = arg;\n    break;\n\n  default: return ARGP_ERR_UNKNOWN;\n  }\n  return 0;\n}\n\nstruct argp argp = { options, parse_options, NULL, doc };\nmy_args arguments;\n\n/*\n * Return 0b000...01...1, with n ones at the end.\n */\nuint64_t __get_mask(unsigned n) {\n    if(n == 0)\n        return 0;\n    assert(n >= 0 && n < 64);\n    uint64_t mask = 1;\n    return (mask << n) - 1;\n}\n\n/*\n * Return 0b000...01...10...0.\n * The bits at positions [start, stop] are equal to 1, the others to 0 (start is the lower order).\n */\nuint64_t get_mask(unsigned start, unsigned stop) {\n    assert(0 <= start && start <= stop && stop < 64);\n    uint64_t ones = __get_mask(stop);\n    uint64_t zeroes = ~__get_mask(start);\n    return ones & zeroes;\n}\n\n/*\n * Apply the given mask to a double.\n */\ndouble apply_mask(double x, uint64_t mask) {\n    uint64_t *tmp = (uint64_t*)&x;\n    (*tmp) |= mask;\n    return *((double*)tmp);\n}\n\nvoid __print_bits(uint64_t n, unsigned i) {\n    if(i == 64)\n        return;\n    __print_bits(n / 2, i+1);\n    if(n % 2)\n        printf(\"1\");\n    else\n        printf(\"0\");\n}\n\nvoid print_bits(uint64_t n) {\n    printf(\"0b\");\n    __print_bits(n, 0);\n    printf(\"\\n\");\n}\n\nvoid print_bits_f(double x) {\n    uint64_t *tmp = (uint64_t*)&x;\n    print_bits(*tmp);\n}\n\ndouble *allocate_matrix(size_t size1, size_t size2) {\n    size_t alloc_size = (size1*size2 + MAX_OFFSET) * sizeof(double);\n    double *result = (double*) malloc(alloc_size);\n    if(!result) {\n      perror(\"malloc\");\n      exit(errno);\n    }\n#ifdef MASK_SIZE\n    uint64_t mask = get_mask(0, MASK_SIZE);\n#pragma message \"Using a mask for the values of the matrix.\"\n#else\n    // Note that this particular mask does not do anything: apply_mask(x, get_mask(0, 0)) == x\n    // One need to change the stop and/or start indices to really apply a mask.\n    uint64_t mask = get_mask(0, 0);\n#endif\n    printf(\"Using the mask: \");\n    print_bits(mask);\n    double x = 3.1415926535897932384626433;\n    assert(x == apply_mask(x, get_mask(0, 0)));\n    assert(x != apply_mask(x, get_mask(0, 1)));\n    for(int i = 0; i < size1*size2; i++) {\n        result[i] = apply_mask((double)rand()/(double)(RAND_MAX), mask);\n    }\n    return result;\n}\n\nvoid write_memory(void) {\n    static char *buff = NULL;\n    if(!buff) {\n        buff = malloc(WRITE_MEMORY_SIZE);\n        if(!buff) {\n            perror(\"malloc\");\n            exit(errno);\n        }\n    }\n    memset(buff, rand()%256, WRITE_MEMORY_SIZE);\n}\n\nFILE *open_file(const char* filename){\n    FILE *file = fopen(filename, \"w\");\n    if(!file) {\n        perror(\"open_file\");\n        exit(errno);\n    }\n    return file;\n}\n\nvoid get_dgemm(FILE *file, int *sizes, int nb_it, unsigned long long base_time, int write_file) {\n  unsigned long long start_time, total_time;\n  double alpha = 1., beta=1.;\n  for(int i=0; i<nb_it; i++) {\n    start_time=get_time();\n    size_t offset = rand() % MAX_OFFSET;\n    cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans, sizes[0], sizes[1], sizes[2], alpha, matrix_A+offset, sizes[3],\n            matrix_B+offset, sizes[4], beta, matrix_C+offset, sizes[5]);\n    total_time=get_time()-start_time;\n    if(write_file)\n      print_in_file(file, \"dgemm\", sizes, 6, start_time-base_time, total_time);\n  }\n}\n\nstatic const char *names[] = {\"dgemm\", NULL};\nstatic const void (*functions[])(FILE*, int*, int, unsigned long long, int) = {get_dgemm};\n\nvoid test_op(FILE *result_file, experiment_t *exp, int nb_runs, unsigned long long base_time, int write_file) {\n  functions[exp->op_id](result_file, exp->sizes, nb_runs, base_time, write_file);\n}\n\n\nint get_max_size(experiment_t *exp, int nb_exp, int idx) {\n  int max = -1;\n  for(int i = 0; i < nb_exp; i++) {\n    int size = exp[i].sizes[idx];\n    if(max < size)\n      max = size;\n  }\n  return max;\n}\n\nint main(int argc, char** argv){\n\n  srand(42);\n  bzero (&arguments, sizeof(my_args));\n\n  if (argp_parse (&argp, argc, argv, 0, 0, &arguments) == ARGP_KEY_ERROR){\n    fprintf(stderr,\"error during the parsing of parameters\\n\");\n    return 1;\n  }\n\n  int nb_loops = arguments.loop;\n\n  if(arguments.sizefile==NULL){\n    fprintf(stderr, \"Please provide a name for a file containing a list of sizes\\n\");\n    return -1;\n  }\n  if(arguments.resultfile==NULL){\n    fprintf(stderr, \"Please provide a name for a result file\\n\");\n    return -1;\n  }\n\n  FILE *result_file = NULL;\n  if(arguments.resultfile)\n    result_file = open_file(arguments.resultfile);\n\n  int nb_exp, largest_size;\n\n  experiment_t *experiments = parse_experiment_file(names, arguments.sizefile, &nb_exp, &largest_size, -1, 300000, 6);\n\n  printf(\"nb_exp=%d, largest_size=%d\\n\", nb_exp, largest_size);\n\n  size_t max_size = (size_t)largest_size*(size_t)largest_size;\n  int max_M = get_max_size(experiments, nb_exp, 0);\n  int max_N = get_max_size(experiments, nb_exp, 1);\n  int max_K = get_max_size(experiments, nb_exp, 2);\n  printf(\"max(M)=%d | max(N)=%d | max(K)=%d\\n\", max_M, max_N, max_K);\n  printf(\"Alloc size: was %.2e bytes\\n\", (double)(max_size)*sizeof(double)*3);\n  double alloc_size = (double)max_M*(double)max_K;\n  alloc_size += (double)max_K*(double)max_N;\n  alloc_size += (double)max_M*(double)max_N;\n  printf(\"Alloc size: now %.2e bytes\\n\", alloc_size*sizeof(double));\n\n  matrix_A = allocate_matrix(max_M, max_K);\n  matrix_B = allocate_matrix(max_K, max_N);\n  matrix_C = allocate_matrix(max_M, max_N);\n\n  //Init time\n  base_time=get_time();\n  for(int i = 0; i < nb_loops; i++) {\n    for(int j = 0; j < nb_exp; j++) {\n      test_op(result_file, &experiments[j], NB_RUNS, base_time, 0);\n    }\n  }\n  for(int j = 0; j < nb_exp; j++) {\n    test_op(result_file, &experiments[j], NB_RUNS, base_time, 1);\n  }\n  for(int i = 0; i < nb_loops; i++) {\n    for(int j = 0; j < nb_exp; j++) {\n      test_op(result_file, &experiments[j], NB_RUNS, base_time, 0);\n    }\n  }\n\n  fflush(result_file);\n  fclose(result_file);\n  free(experiments);\n  free(matrix_A);\n  free(matrix_B);\n  free(matrix_C);\n  return 0;\n}\n", "meta": {"hexsha": "7c43bbec5ea4df22297fa0a846a0fe0a1fd60af6", "size": 7244, "ext": "c", "lang": "C", "max_stars_repo_path": "src/calibration/calibrate_blas.c", "max_stars_repo_name": "Ezibenroc/platform-calibration", "max_stars_repo_head_hexsha": "899f044658246fb86f24e4efc96489df546ad3d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-11-06T16:12:26.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-06T16:12:26.000Z", "max_issues_repo_path": "src/calibration/calibrate_blas.c", "max_issues_repo_name": "Ezibenroc/platform-calibration", "max_issues_repo_head_hexsha": "899f044658246fb86f24e4efc96489df546ad3d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2022-01-13T10:44:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T07:50:51.000Z", "max_forks_repo_path": "src/calibration/calibrate_blas.c", "max_forks_repo_name": "Ezibenroc/platform-calibration", "max_forks_repo_head_hexsha": "899f044658246fb86f24e4efc96489df546ad3d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-11-07T15:52:04.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-07T15:52:04.000Z", "avg_line_length": 26.5347985348, "max_line_length": 120, "alphanum_fraction": 0.646051905, "num_tokens": 2136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769843, "lm_q2_score": 0.05834583610886592, "lm_q1q2_score": 0.02826156101162359}}
{"text": "/* roots/utility.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Reid Priedhorsky, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* utility.c -- various root finding utility routines */\n\n/* config headers */\n#include <config.h>\n\n/* standard headers */\n#include <stddef.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n#include <float.h>\n\n/* gsl headers */\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_roots.h>\n\n/* roots headers */\n#include \"roots.h\"\n\n\n/* Validate arguments common to gsl_root_bisection and gsl_root_falsepos.\n   Return GSL_SUCCESS if all arguments are okay, complain appropriately (i.e.\n   call GSL_ERROR and return GSL_FAILURE) otherwise. */\nint\n_gsl_root_validate_bfp_args (double *root, double (*f) (double),\n                             double *lower_bound,\n                             double *upper_bound, double epsrel,\n                             double epsabs, unsigned int max_iterations,\n                             double max_deltay)\n{\n  /* Is the maximum delta-y too small? */\n  if (max_deltay < GSL_ROOT_MIN_MAX_DELTAY)\n    GSL_ERROR (\"maximum delta-y negative, zero, or too small\", GSL_EBADTOL);\n\n  /* Did the user give a lower bound that not less than the upper bound? */\n  if (*lower_bound >= *upper_bound)\n    GSL_ERROR (\"lower bound larger than upper_bound\", GSL_EINVAL);\n\n  /* The rest of the arguments are common. */\n  return _gsl_root_validate_args (root, f, lower_bound, upper_bound,\n                                  epsrel, epsabs, max_iterations);\n}\n\n/* Validate arguments commond to gsl_root_secant and gsl_root_newtons. Return\n   GSL_SUCCESS if all arguments are okay, complain appropriately (i.e. call\n   GSL_ERROR and return GSL_FAILURE) otherwise. */\nint\n_gsl_root_validate_sn_args (double *root, double (*f) (double),\n                            double *guess1,\n                            double *guess2, double epsrel,\n                            double epsabs, unsigned int max_iterations,\n                            double max_step_size)\n{\n  /* Is the maximum step size ridiculous? */\n  if (max_step_size <= 0.0)\n    GSL_ERROR (\"maximum step size <= 0\", GSL_EBADTOL);\n\n  /* The rest of the arguments are common. */\n  return _gsl_root_validate_args (root, f, guess1, guess2, epsrel,\n                                  epsabs, max_iterations);\n}\n\n/* Validate the arguments common to all four low level functions. Return\n   GSL_SUCCESS if all of the following arguments hold true, call GSL_ERROR and\n   return GSL_FAILURE otherwise.\n\n   * No pointer arguments are null.\n   * The maximum number of iterations is non-zero.\n   * Relative and absolute error are non-negative.\n   * The relative error is not too small. */\nint\n_gsl_root_validate_args (double *root, double (*f) (double), double *where1,\n                         double *where2, double epsrel,\n                         double epsabs, unsigned int max_iterations)\n{\n  /* Are any pointers null? */\n  if ((root == NULL) || (f == NULL) || (where1 == NULL)\n      || (where2 == NULL))\n    GSL_ERROR (\"pointer argument null\", GSL_EINVAL);\n  /* Did the user tell us to do no iterations? */\n  if (max_iterations == 0)\n    GSL_ERROR (\"maximum iterations 0\", GSL_EINVAL);\n  /* Did the user try to pawn a negative tolerance off on us? */\n  if (epsrel < 0.0 || epsabs < 0.0)\n    GSL_ERROR (\"relative or absolute tolerance negative\", GSL_EBADTOL);\n  /* Is the relative error too small? */\n  if (epsrel < GSL_DBL_EPSILON * GSL_ROOT_EPSILON_BUFFER)\n    GSL_ERROR (\"relative tolerance too small\", GSL_EBADTOL);\n\n  /* All is well. */\n  return GSL_SUCCESS;\n}\n\n/* Verify that the supplied interval is guaranteed by the Intermediate Value\n   Theorem to contain a root and complain appropriately if it is not. (It\n   might actually be a discontinuity, but we check for that elsewhere.) Return\n   GSL_SUCCESS if all is well, otherwise, call GSL_ERROR and return\n   GSL_FAILURE. */\nint\n_gsl_root_ivt_guar (double (*f) (double), double lower_bound,\n                    double upper_bound)\n{\n  double fl, fu;\n\n  _BARF_FPCALL (f, lower_bound, fl);\n  _BARF_FPCALL (f, upper_bound, fu);\n\n  if (fl * fu > 0.0)\n    {\n      GSL_ERROR (\"interval not guaranteed to contain a root\", GSL_EINVAL);\n    }\n  else\n    {\n      return GSL_SUCCESS;\n    }\n}\n\n/* Check if the user has the root but doesn't know it. If lower_bound or\n   upper_bound is a root of f, or the interval [upper_bound, lower_bound] is\n   within tolerance, return 1 and set *root appropriately. Otherwise, return\n   0. On error, call GSL_ERROR and return GSL_FAILURE. Only worry about\n   max_deltay if it is greater than 0 (which implies that you should validate\n   arguments _before_ calling this function). */\nint\n_gsl_root_silly_user (double *root, double (*f) (double), double lower_bound,\n                      double upper_bound, double epsrel,\n                      double epsabs, double max_deltay)\n{\n  double fl, fu;\n\n  /* Is lower_bound the root? */\n  _BARF_FPCALL (f, lower_bound, fl);\n  if (fl == 0.0)\n    {\n      *root = lower_bound;\n      return 1;\n    }\n\n  /* Is upper_bound the root? */\n  _BARF_FPCALL (f, upper_bound, fu);\n  if (fu == 0.0)\n    {\n      *root = upper_bound;\n      return 1;\n    }\n\n  /* Are lower_bound and upper_bound within tolerance? */\n  _BARF_TOLS (lower_bound, upper_bound, 2 * epsrel, 2 * epsabs);\n  if (max_deltay > 0.0)\n    _BARF_DELTAY (fl, fu, max_deltay);\n  if (_WITHIN_TOL (lower_bound, upper_bound, 2 * epsrel,\n                   2 * epsabs))\n    {\n      *root = (lower_bound + upper_bound) / 2.0;\n      return 1;\n    }\n\n  /* No? Bummer. */\n  return 0;\n}\n", "meta": {"hexsha": "57442a3e3d7d91cda9b174b57b72cb71e9ecf085", "size": 6257, "ext": "c", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/roots/utility.c", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/roots/utility.c", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/roots/utility.c", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 34.7611111111, "max_line_length": 81, "alphanum_fraction": 0.659421448, "num_tokens": 1583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.05749328485634488, "lm_q1q2_score": 0.028073016336366673}}
{"text": "/* ieee-utils/make_rep.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <gsl/gsl_ieee_utils.h>\n\n#include \"endian.c\"\n#include \"standardize.c\"\n\nstatic void sprint_nybble(int i, char *s) ;\nstatic void sprint_byte(int i, char *s) ;\nstatic int determine_ieee_type (int non_zero, int exponent, int max_exponent);\n\n\n/* For the IEEE float format the bits are found from the following\n   masks,\n   \n   sign      = 0x80000000  \n   exponent  = 0x7f800000 \n   mantisssa = 0x007fffff  \n\n   For the IEEE double format the masks are,\n\n   sign      = 0x8000000000000000  \n   exponent  = 0x7ff0000000000000 \n   mantissa  = 0x000fffffffffffff\n\n   */\n\nvoid \ngsl_ieee_float_to_rep (const float * x, gsl_ieee_float_rep * r)\n{\n  int e, non_zero;\n\n  union { \n    float f;\n    struct  { \n      unsigned char byte[4] ;\n    } ieee ;\n  } u;\n  \n  u.f = *x ; \n\n  if (little_endian_p())\n    make_float_bigendian(&(u.f)) ;\n  \n  /* note that r->sign is signed, u.ieee.byte is unsigned */\n\n  if (u.ieee.byte[3]>>7)\n    {\n      r->sign = 1 ;\n    }\n  else\n    {\n      r->sign = 0 ;\n    }\n\n  e = (u.ieee.byte[3] & 0x7f) << 1 | (u.ieee.byte[2] & 0x80)>>7 ; \n  \n  r->exponent = e - 127 ;\n\n  sprint_byte((u.ieee.byte[2] & 0x7f) << 1,r->mantissa) ;\n  sprint_byte(u.ieee.byte[1],r->mantissa + 7) ;\n  sprint_byte(u.ieee.byte[0],r->mantissa + 15) ;\n\n  r->mantissa[23] = '\\0' ;\n\n  non_zero = u.ieee.byte[0] || u.ieee.byte[1] || (u.ieee.byte[2] & 0x7f);\n\n  r->type = determine_ieee_type (non_zero, e, 255) ;\n}\n\nvoid \ngsl_ieee_double_to_rep (const double * x, gsl_ieee_double_rep * r)\n{\n\n  int e, non_zero;\n\n  union \n  { \n    double d;\n    struct  { \n      unsigned char byte[8];\n    } ieee ;\n  } u;\n\n  u.d= *x ; \n  \n  if (little_endian_p())\n    make_double_bigendian(&(u.d)) ;\n  \n  /* note that r->sign is signed, u.ieee.byte is unsigned */\n\n  if (u.ieee.byte[7]>>7)\n    {\n      r->sign = 1 ;\n    }\n  else\n    {\n      r->sign = 0 ;\n    }\n\n\n  e =(u.ieee.byte[7] & 0x7f)<<4 ^ (u.ieee.byte[6] & 0xf0)>>4 ;\n  \n  r->exponent = e - 1023 ;\n\n  sprint_nybble(u.ieee.byte[6],r->mantissa) ;\n  sprint_byte(u.ieee.byte[5],r->mantissa + 4) ;\n  sprint_byte(u.ieee.byte[4],r->mantissa + 12) ;\n  sprint_byte(u.ieee.byte[3],r->mantissa + 20) ; \n  sprint_byte(u.ieee.byte[2],r->mantissa + 28) ;\n  sprint_byte(u.ieee.byte[1],r->mantissa + 36) ;\n  sprint_byte(u.ieee.byte[0],r->mantissa + 44) ;\n\n  r->mantissa[52] = '\\0' ;\n\n  non_zero = (u.ieee.byte[0] || u.ieee.byte[1] || u.ieee.byte[2]\n              || u.ieee.byte[3] || u.ieee.byte[4] || u.ieee.byte[5] \n              || (u.ieee.byte[6] & 0x0f)) ;\n\n  r->type = determine_ieee_type (non_zero, e, 2047) ;\n}\n\n/* A table of character representations of nybbles */\n\nstatic char nybble[16][5]={ /* include space for the \\0 */\n  \"0000\", \"0001\", \"0010\", \"0011\",\n  \"0100\", \"0101\", \"0110\", \"0111\",\n  \"1000\", \"1001\", \"1010\", \"1011\",\n  \"1100\", \"1101\", \"1110\", \"1111\"\n}  ;\n          \nstatic void\nsprint_nybble(int i, char *s)\n{\n  char *c ;\n  c=nybble[i & 0x0f ];\n  *s=c[0] ;  *(s+1)=c[1] ;  *(s+2)=c[2] ;  *(s+3)=c[3] ;\n} \n\nstatic void\nsprint_byte(int i, char *s)\n{\n  char *c ;\n  c=nybble[(i & 0xf0)>>4];\n  *s=c[0] ;  *(s+1)=c[1] ;  *(s+2)=c[2] ;  *(s+3)=c[3] ;\n  c=nybble[i & 0x0f];\n  *(s+4)=c[0] ;  *(s+5)=c[1] ;  *(s+6)=c[2] ;  *(s+7)=c[3] ;\n} \n\nstatic int \ndetermine_ieee_type (int non_zero, int exponent, int max_exponent)\n{\n  if (exponent == max_exponent)\n    {\n      if (non_zero)\n        {\n          return GSL_IEEE_TYPE_NAN ;\n        }\n      else\n        {\n          return GSL_IEEE_TYPE_INF ;\n        }\n    }\n  else if (exponent == 0)\n    {\n      if (non_zero)\n        {\n          return GSL_IEEE_TYPE_DENORMAL ;\n        }\n      else\n        {\n          return GSL_IEEE_TYPE_ZERO ;\n        }\n    }\n  else\n    {\n      return GSL_IEEE_TYPE_NORMAL ;\n    }\n}\n", "meta": {"hexsha": "59bf861243bec0fb5f8608cc489f9910ebfe60ca", "size": 4513, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/ieee-utils/make_rep.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/ieee-utils/make_rep.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/ieee-utils/make_rep.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 22.7929292929, "max_line_length": 81, "alphanum_fraction": 0.585198316, "num_tokens": 1590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.05749328001157759, "lm_q1q2_score": 0.028073013970747247}}
{"text": "/*\nBallistic: a software to benchmark ballistic models.\n\nAUTHORS: Javier Burguete Tolosa.\n\nCopyright 2018, AUTHORS.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n  1. Redistributions of source code must retain the above copyright notice,\n    this list of conditions and the following disclaimer.\n\n  2. Redistributions in binary form must reproduce the above copyright notice,\n    this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY AUTHORS ``AS IS'' AND ANY EXPRESS OR IMPLIED\nWARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT\nSHALL AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\nBUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING\nIN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY\nOF SUCH DAMAGE.\n*/\n\n/**\n * \\file ballistic.c\n * \\brief Source file with the main function.\n * \\author Javier Burguete Tolosa.\n * \\copyright Copyright 2018.\n */\n#define _GNU_SOURCE\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <time.h>\n#include <gsl/gsl_rng.h>\n#include <libxml/parser.h>\n#include <glib.h>\n#include \"config.h\"\n#include \"utils.h\"\n#include \"equation.h\"\n#include \"method.h\"\n#include \"runge-kutta.h\"\n#include \"multi-steps.h\"\n\n#define DEBUG_BALLISTIC 0       ///< macro to debug the ballistic functions.\n\nlong double convergence_factor;\n///< convergence factor.\nunsigned int ntrajectories;\n///< number of projectil trajectories to calculate.\nunsigned int convergence;\n///< number of convergence steps.\n\n/**\n * Function to read the basic input data.\n *\n * \\return 1 on success, 0 on error.\n */\nstatic inline int\nconvergence_read_xml (xmlNode * node)      ///< XML node.\n{\n\tconst char *message[] = {\n\t\t\"Bad trajectories number\",\n\t\t\"Bad convergence steps\",\n\t\t\"Bad convergence factor\"\n\t};\n\tint e, error_code;\n\n#if DEBUG_BALLISTIC\n  fprintf (stderr, \"convergence_read_xml: start\\n\");\n#endif\n  ntrajectories = xml_node_get_uint (node, XML_TRAJECTORIES, &error_code);\n  if (error_code || !ntrajectories)\n\t  {\n\t\t\te = 0;\n      goto fail;\n\t\t}\n  convergence = xml_node_get_uint (node, XML_CONVERGENCE, &error_code);\n  if (error_code || !convergence)\n\t  {\n\t\t\te = 1;\n      goto fail;\n\t\t}\n  convergence_factor = xml_node_get_float (node, XML_FACTOR, &error_code);\n  if (error_code || convergence_factor <= 0.)\n\t  {\n\t\t\te = 2;\n      goto fail;\n\t\t}\n#if DEBUG_BALLISTIC\n  fprintf (stderr, \"convergence_read_xml: success\\n\");\n  fprintf (stderr, \"convergence_read_xml: end\\n\");\n#endif\n  return 1;\n\nfail:\n\terror_add (message[e]);\n#if DEBUG_BALLISTIC\n  fprintf (stderr, \"convergence_read_xml: error\\n\");\n  fprintf (stderr, \"convergence_read_xml: end\\n\");\n#endif\n  return 0;\n}\n\n/**\n * Function to open a numerical method on a XML node.\n *\n * \\return 0 on error, 1 on Runge-Kutta method, 2 on multi-steps method.\n */\nstatic inline int\nmethod_open_xml (MultiSteps * ms,\n\t\t             RungeKutta * rk,\n\t\t\t\t\t\t\t\t xmlNode * node)\n{\n\tchar *message[] = {\n    \"No numerical method XML node\",\n    \"Bad Runge-Kutta data\",\n    \"Bad multi-steps data\",\n    \"Unknown numerical method\"\n\t};\n\tint e, m;\n\n#if DEBUG_BALLISTIC\n  fprintf (stderr, \"method_open_xml: start\\n\");\n#endif\n  if (!node)\n    {\n      e = 0;\n      goto fail;\n    }\n  if (!xmlStrcmp (node->name, XML_RUNGE_KUTTA))\n    {\n      if (!runge_kutta_read_xml (rk, node))\n        {\n          e = 1;\n          goto fail;\n        }\n      runge_kutta_init_variables (rk);\n\t\t\tm = 1;\n    }\n  else if (!xmlStrcmp (node->name, XML_MULTI_STEPS))\n    {\n      if (!multi_steps_read_xml (ms, node))\n        {\n          e = 2;\n          goto fail;\n        }\n      multi_steps_init_variables (ms);\n\t\t\tm = 2;\n    }\n  else\n    {\n      e = 3;\n      goto fail;\n    }\n#if DEBUG_BALLISTIC\n  fprintf (stderr, \"method_open_xml: success\\n\");\n  fprintf (stderr, \"method_open_xml: end\\n\");\n#endif\n\treturn m;\n\nfail:\n\terror_add (message[e]);\n#if DEBUG_BALLISTIC\n  fprintf (stderr, \"method_open_xml: error\\n\");\n  fprintf (stderr, \"method_open_xml: end\\n\");\n#endif\n\treturn 0;\n}\n\n/**\n * Function to show the error message.\n */\nstatic void\nshow_error ()\n{\n  printf (\"ERROR!\\n%s\", error_message);\n  g_free (error_message);\n\terror_message = NULL;\n}\n\n/**\n * Function to print the solution values.\n */\nstatic void\nprint_solution (char *label,    ///< label.\n                long double *r0,        ///< position vector.\n                long double *r1)        ///< velocity vector.\n{\n  printf (\"%s\\n\", label);\n  printf (\"x = %.19Le\\n\", r0[0]);\n  printf (\"y = %.19Le\\n\", r0[1]);\n  printf (\"z = %.19Le\\n\", r0[2]);\n  printf (\"vx = %.19Le\\n\", r1[0]);\n  printf (\"vy = %.19Le\\n\", r1[1]);\n  printf (\"vz = %.19Le\\n\", r1[2]);\n}\n\n/**\n * Function to print the numerical errors.\n */\nstatic void\nprint_error (char *label,       ///< label.\n             long double *r1,   ///< numerical solution vector.\n             long double *r2)   ///< analytical solution vector.\n{\n  printf (\"%s = %.19Le\\n\", label, distance (r1, r2));\n}\n\n/**\n * Function to perform a convergence analysis of a method.\n *\n * \\return 0 on success, error code on error.\n */\nstatic inline int\nconvergence_run (xmlNode * node,   ///< XML node.\n                 char *output)  ///< results file name.\n{\n\tconst char *message[] = {\n\t\tNULL,\n\t\t\"Bad convergence data\",\n\t\t\"No equation XML node\",\n\t\t\"Unknown numerical method\",\n\t\t\"Bad numerical method data\"\n\t};\n  MultiSteps ms[1];\n  RungeKutta rk[1];\n  Equation eq[1];\n  Method *m;\n  gsl_rng *rng;\n  FILE *file;\n  long double sr0[3], sr1[3];\n  long double t, l0r0, l2r0, l0r1, l2r1, e;\n\tint er, me;\n  unsigned int i, j;\n#if DEBUG_BALLISTIC\n  fprintf (stderr, \"convergence_run: start\\n\");\n#endif\n\ter = 0;\n  if (!convergence_read_xml (node))\n\t  {\n      er = 1;\n\t\t\tgoto fail;\n\t\t}\n#if DEBUG_BALLISTIC\n  fprintf (stderr, \"convergence_run: initing equation\\n\");\n#endif\n\tnode = node->children;\n\tif (!node)\n\t  {\n\t\t\ter = 2;\n\t\t\tgoto fail;\n\t\t}\n  if (!equation_read_xml (eq, node, 0))\n\t  {\n\t\t\ter = 3;\n      goto fail;\n\t\t}\n#if DEBUG_BALLISTIC\n  fprintf (stderr, \"convergence_run: initing method\\n\");\n#endif\n\tnode = node->next;\n\tme = method_open_xml (ms, rk, node);\n\tswitch (me)\n\t  {\n\t\tcase 1:\n      m = RUNGE_KUTTA_METHOD (rk);\n\t\t\tbreak;\n\t\tcase 2:\n      m = MULTI_STEPS_METHOD (ms);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\ter = 4;\n\t\t\tgoto fail;\n\t\t}\n  rng = gsl_rng_alloc (gsl_rng_taus2);\n  file = fopen (output, \"w\");\n  for (j = 0; j < convergence; ++j)\n    {\n      gsl_rng_set (rng, 0l);\n      nevaluations = 0l;\n      l0r0 = l2r0 = l0r1 = l2r1 = 0.L;\n      for (i = 0; i < ntrajectories; ++i)\n        {\n#if DEBUG_BALLISTIC\n          fprintf (stderr, \"convergence_run: initing equation data\\n\");\n#endif\n          equation_init (eq, rng);\n#if DEBUG_BALLISTIC\n          fprintf (stderr, \"convergence_run: initing variables\\n\");\n#endif\n          equation_solution (eq, r0, r1, 0.);\n          equation_acceleration (eq, r0, r1, r2, 0.L);\n#if DEBUG_BALLISTIC\n          fprintf (stderr, \"convergence_run: running\\n\");\n#endif\n          if (me == 1)\n            t = runge_kutta_run (rk, eq);\n          else\n            t = multi_steps_run (ms, eq);\n#if DEBUG_BALLISTIC\n          fprintf (stderr, \"convergence_run: solutions\\n\");\n          print_solution (\"Numerical solution\", r0, r1);\n          printf (\"Time = %.19Le\\n\", t);\n#endif\n          switch (eq->land_type)\n            {\n            case 0:\n              equation_solution (eq, sr0, sr1, eq->tf);\n              break;\n            default:\n              t = equation_solve (eq, sr0, sr1);\n            }\n#if DEBUG_BALLISTIC\n          print_solution (\"Analytical solution\", sr0, sr1);\n          printf (\"Time = %.19Le\\n\", t);\n          print_error (\"Position error\", r0, sr0);\n          print_error (\"Velocity error\", r1, sr1);\n#endif\n          e = distance (r0, sr0);\n          l0r0 = fmaxl (l0r0, e);\n          l2r0 += e * e;\n          e = distance (r1, sr1);\n          l0r1 = fmaxl (l0r1, e);\n          l2r1 += e * e;\n\n        }\n#if DEBUG_BALLISTIC\n      fprintf (stderr, \"convergence_run: saving results\\n\");\n#endif\n      l2r0 = sqrtl (l2r0 / ntrajectories);\n      l2r1 = sqrtl (l2r1 / ntrajectories);\n      fprintf (file, \"%lu %.19Le %.19Le %.19Le %.19Le %.19Le %.19Le\\n\",\n               nevaluations, l0r0, l2r0, l0r1, l2r1, kt, m->emt);\n      switch (eq->size_type)\n        {\n        case 0:\n          dt *= convergence_factor;\n          break;\n        default:\n          kt *= convergence_factor;\n        }\n      m->emt *= convergence_factor;\n      if (me == 2)\n        RUNGE_KUTTA_METHOD (MULTI_STEPS_RUNGE_KUTTA (ms))->emt\n          *= convergence_factor;\n    }\n  fclose (file);\n  printf (\"Time = %.19Le\\n\", t);\n#if DEBUG_BALLISTIC\n  fprintf (stderr, \"convergence_run: deleting method\\n\");\n#endif\n  if (me == 1)\n    runge_kutta_delete (rk);\n  else\n    multi_steps_delete (ms);\n  gsl_rng_free (rng);\nfail:\n\tif (er)\n\t  {\n\t\t\terror_add (message[er]);\n\t\t  show_error ();\n\t\t}\n#if DEBUG_BALLISTIC\n  fprintf (stderr, \"convergence_run: end\\n\");\n#endif\n  return 0;\n}\n\n/**\n * Function to calculate a ballistic trajectory.\n *\n * \\return 0 on success, error code on error.\n */\nstatic inline int\nballistic_run (xmlNode * node)    ///< XML node.\n{\n  const char *message[] = {\n    NULL,\n    \"Unable to open the XML root element\",\n    \"Bad XML file\",\n    \"No equation XML node\",\n    \"Bad equation data\",\n  };\n  MultiSteps ms[1];\n  RungeKutta rk[1];\n  Equation eq[1];\n  long double sr0[3], sr1[3];\n  long double t;\n  int e, m;\n#if DEBUG_BALLISTIC\n  fprintf (stderr, \"ballistic_run: start\\n\");\n#endif\n  e = 0;\n  node = node->children;\n  if (!node)\n    {\n      e = 3;\n      goto end;\n    }\n  if (!equation_read_xml (eq, node, 1))\n    {\n      e = 4;\n      goto end;\n    }\n  node = node->next;\n  if (!node)\n    {\n      e = 5;\n      goto end;\n    }\n  if (!xmlStrcmp (node->name, XML_RUNGE_KUTTA))\n    {\n      if (!runge_kutta_read_xml (rk, node))\n        {\n          e = 6;\n          goto end;\n        }\n      runge_kutta_init_variables (rk);\n\t\t\tm = 1;\n    }\n  else if (!xmlStrcmp (node->name, XML_MULTI_STEPS))\n    {\n      if (!multi_steps_read_xml (ms, node))\n        {\n          e = 7;\n          goto end;\n        }\n      multi_steps_init_variables (ms);\n\t\t\tm = 2;\n    }\n  else\n    {\n      e = 8;\n      goto end;\n    }\n  nevaluations = 0l;\n#if DEBUG_BALLISTIC\n  fprintf (stderr, \"ballistic_run: initing variables\\n\");\n#endif\n  equation_solution (eq, r0, r1, 0.);\n  equation_acceleration (eq, r0, r1, r2, 0.L);\n#if DEBUG_BALLISTIC\n  fprintf (stderr, \"ballistic_run: running\\n\");\n#endif\n  switch (m)\n\t  {\n\t\tcase 1:\n\t\t\tt = runge_kutta_run (rk, eq);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tt = multi_steps_run (ms, eq);\n\t\t}\n#if DEBUG_BALLISTIC\n  fprintf (stderr, \"ballistic_run: solutions\\n\");\n#endif\n  print_solution (\"Numerical solution\", r0, r1);\n  printf (\"Time = %.19Le\\n\", t);\n  switch (eq->land_type)\n    {\n    case 0:\n      equation_solution (eq, sr0, sr1, eq->tf);\n      break;\n    default:\n      t = equation_solve (eq, sr0, sr1);\n    }\n  print_solution (\"Analytical solution\", sr0, sr1);\n  printf (\"Time = %.19Le\\n\", t);\n  print_error (\"Position error\", r0, sr0);\n  print_error (\"Velocity error\", r1, sr1);\n  printf (\"Time = %.19Le\\n\", t);\n#if DEBUG_BALLISTIC\n  fprintf (stderr, \"ballistic_run: deleting method\\n\");\n#endif\n  switch (m)\n\t  {\n\t\tcase 1:\n      runge_kutta_delete (rk);\n\t\t\tbreak;\n\t\tdefault:\n      multi_steps_delete (ms);\n\t\t}\nend:\n#if DEBUG_BALLISTIC\n  fprintf (stderr, \"ballistic_run: end\\n\");\n#endif\n\tif (e)\n    error_add (message[e]);\n  return e;\n}\n\n/**\n * Main function\n *\n * \\return 0 on success, error code otherwise.\n */\nint\nmain (int argn,                 ///< number of arguments.\n      char **argc)              ///< array of argument chars.\n{\n\tconst char *message[] = {\n\t\tNULL,\n    \"The syntax is:\\n./ballistic input_file output_file\\n\",\n\t\t\"Unable to open the input file\",\n\t\t\"Bad XML root element\",\n\t  \"Bad ballistic run\",\n\t  \"Bad convergence run\",\n\t\t\"Unknown model\"\n\t};\n  xmlDoc *doc;\n\txmlNode *node;\n  int e;\n#if DEBUG_BALLISTIC\n  fprintf (stderr, \"main: start\\n\");\n#endif\n\te = 0;\n\tif (argn != 3)\n\t  {\n\t\t\te = 1;\n\t\t\tgoto end;\n\t\t}\n  xmlKeepBlanksDefault (0);\n  doc = xmlParseFile (argc[1]);\n  if (!doc)\n\t  {\n\t\t\te = 2;\n\t\t\tgoto end;\n\t\t}\n  node = xmlDocGetRootElement (doc);\n  if (!node)\n    {\n      e = 3;\n      goto end;\n    }\n  if (!xmlStrcmp (node->name, XML_BALLISTIC))\n\t  {\n      e = ballistic_run (node);\n\t\t\tif (e)\n\t\t\t  {\n\t\t\t\t\te = 4;\n\t\t\t\t\tgoto end;\n\t\t\t\t}\n\t\t}\n\telse if (!xmlStrcmp (node->name, XML_CONVERGENCE))\n\t  {\n      e = convergence_run (node, argc[2]);\n\t\t\tif (e)\n\t\t\t  {\n\t\t\t\t\te = 5;\n\t\t\t\t\tgoto end;\n\t\t\t\t}\n\t\t}\n\telse\n\t  e = 6;\n  xmlFreeDoc (doc);\nend:\n  if (e)\n    {\n\t\t\terror_add (message[e]);\n      show_error ();\n    }\n  return e;\n}\n", "meta": {"hexsha": "933ad38b0999bfb458443fd8c650729191ff491e", "size": 13110, "ext": "c", "lang": "C", "max_stars_repo_path": "1.1.0/ballistic.c", "max_stars_repo_name": "jburguete/ballistic", "max_stars_repo_head_hexsha": "e557bce6e63bb667f1e698cff6e68013bb4e5e6f", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-08-02T14:03:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-02T14:03:09.000Z", "max_issues_repo_path": "1.1.0/ballistic.c", "max_issues_repo_name": "jburguete/ballistic", "max_issues_repo_head_hexsha": "e557bce6e63bb667f1e698cff6e68013bb4e5e6f", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "1.1.0/ballistic.c", "max_forks_repo_name": "jburguete/ballistic", "max_forks_repo_head_hexsha": "e557bce6e63bb667f1e698cff6e68013bb4e5e6f", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-06-24T07:19:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-24T07:19:47.000Z", "avg_line_length": 22.9597197898, "max_line_length": 80, "alphanum_fraction": 0.6070175439, "num_tokens": 3809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490155654565424, "lm_q2_score": 0.06008665143635008, "lm_q1q2_score": 0.027934377780375323}}
{"text": "/*\n * BSD 3-Clause License\n *\n * Copyright (c) 2021, Shahriar Rezghi <shahriar25.ss@gmail.com>\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n *    list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n *    this list of conditions and the following disclaimer in the documentation\n *    and/or other materials provided with the distribution.\n *\n * 3. Neither the name of the copyright holder nor the names of its\n *    contributors may be used to endorse or promote products derived from\n *    this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#pragma once\n\n#include <complex>\n\n#define lapack_complex_float std::complex<float>\n#define lapack_complex_double std::complex<double>\n\n#include <blasw/config.h>\n\n#ifdef BLASW_CBLAS_MKL\n#include <mkl_cblas.h>\n#else\n#include <cblas.h>\n#endif\n\n#ifdef BLASW_LAPACKE_FOUND\n#ifdef BLASW_LAPACKE_MKL\n#include <mkl_lapacke.h>\n#else\n#include <lapacke.h>\n#endif\n#endif\n\n#include <cstdlib>\n#include <iostream>\n#include <memory>\n#include <stdexcept>\n#include <string>\n#include <type_traits>\n\n#define CHECK(expr) \\\n    if (!static_cast<bool>(expr)) throw std::runtime_error(std::string(\"Expression \\\"\") + #expr + \"\\\" has failed!\");\n\nnamespace Blasw\n{\nusing Size = int;\nusing Index = CBLAS_INDEX;\n\nenum class Major\n{\n    Row = CblasRowMajor,\n    Col = CblasColMajor,\n};\nenum class State\n{\n    None = CblasNoTrans,\n    Trans = CblasTrans,\n    ConjTrans = CblasConjTrans,\n};\nenum class Triangular\n{\n    Upper = CblasUpper,\n    Lower = CblasLower,\n};\nenum class Diagonal\n{\n    Unit = CblasUnit,\n    NonUnit = CblasNonUnit,\n};\n\ntemplate <typename T>\nstruct From\n{\n    using Type = T;\n};\ntemplate <typename T>\nstruct From<std::complex<T>>\n{\n    using Type = T;\n};\ntemplate <typename T>\nstruct To\n{\n    using Type = std::complex<T>;\n};\ntemplate <typename T>\nstruct To<std::complex<T>>\n{\n    using Type = std::complex<T>;\n};\n\nnamespace Impl\n{\ninline CBLAS_ORDER blcvt(Major major) { return CBLAS_ORDER(major); }\ninline CBLAS_TRANSPOSE blcvt(State state) { return CBLAS_TRANSPOSE(state); }\ninline CBLAS_UPLO blcvt(Triangular tri) { return CBLAS_UPLO(tri); }\ninline CBLAS_DIAG blcvt(Diagonal diag) { return CBLAS_DIAG(diag); }\n}  // namespace Impl\n\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n\n#define STATE(name)               \\\n    name<T> &trans()              \\\n    {                             \\\n        state = State::Trans;     \\\n        return *this;             \\\n    }                             \\\n    name<T> &adjoint()            \\\n    {                             \\\n        state = State::ConjTrans; \\\n        return *this;             \\\n    }\n\ntemplate <typename T>\nstruct Vector\n{\n    T *data;\n    Size size, stride;\n\n    Vector() {}\n    Vector(T *data, Size size, Size stride) : data(data), size(size) { this->stride = (stride == 0 ? 1 : stride); }\n};\n\ntemplate <typename T>\nVector<T> vec(T *data, Size size, Size stride = 0)\n{\n    return Vector<T>(data, size, stride);\n}\n\ntemplate <typename T>\nstruct General\n{\n    using Type = T;\n\n    T *data;\n    Size rows, cols, stride;\n    Major major;\n    State state;\n    STATE(General);\n\n    General() : data(nullptr), rows(0), cols(0), stride(0), major{Major::Row}, state(State::None) {}\n    General(T *data, Size rows, Size cols, Size stride, Major major, State state)\n        : data(data), rows(rows), cols(cols), major{major}, state(state)\n    {\n        this->stride = (stride == 0 ? (major == Major::Row ? cols : rows) : stride);\n    }\n\n    bool _trans() const { return state == State::Trans || state == State::ConjTrans; }\n    Size _rows() const { return _trans() ? cols : rows; }\n    Size _cols() const { return _trans() ? rows : cols; }\n};\n\n#define GENERAL(name, major)                                                    \\\n    template <typename T>                                                       \\\n    General<T> name(T *data, Size rows, Size cols, Size stride = 0)             \\\n    {                                                                           \\\n        return General<T>(data, rows, cols, stride, Major::major, State::None); \\\n    }\nGENERAL(rmat, Row) GENERAL(cmat, Col);\n\ntemplate <typename T>\nstruct BGeneral\n{\n    using Type = T;\n\n    T *data;\n    Size rows, cols, stride;\n    Major major;\n    State state;\n    Size sub, super;\n    STATE(BGeneral);\n\n    BGeneral() : data(nullptr), rows(0), cols(0), stride(0), major{Major::Row}, state(State::None), sub(0), super(0) {}\n    BGeneral(T *data, Size rows, Size cols, Size stride, Major major, State state, Size sub, Size super)\n        : data(data), rows(rows), cols(cols), major{major}, state(state), sub(sub), super(super)\n    {\n        this->stride = (stride == 0 ? (major == Major::Row ? cols : rows) : stride);\n    }\n\n    bool _trans() const { return state == State::Trans || state == State::ConjTrans; }\n    Size _rows() const { return _trans() ? cols : rows; }\n    Size _cols() const { return _trans() ? rows : cols; }\n};\n\n#define BGENERAL(name, major, str)                                                           \\\n    template <typename T>                                                                    \\\n    BGeneral<T> name(T *data, Size rows, Size cols, Size sub, Size super, Size stride = 0)   \\\n    {                                                                                        \\\n        return BGeneral<T>(data, rows, cols, stride, Major::major, State::None, sub, super); \\\n    }\nBGENERAL(rbmat, Row, cols) BGENERAL(cbmat, Col, rows);\n\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n\ntemplate <typename T>\nstruct Triangle\n{\n    using Type = T;\n\n    T *data;\n    Size size, stride;\n    Major major;\n    State state;\n    Triangular tri;\n    Diagonal diag;\n    STATE(Triangle);\n\n    Triangle()\n        : data(nullptr),\n          size(0),\n          stride(0),\n          major{Major::Row},\n          state(State::None),\n          tri(Triangular::Upper),\n          diag(Diagonal::NonUnit)\n    {\n    }\n    Triangle(T *data, Size size, Size stride, Major major, State state, Triangular tri, Diagonal diag)\n        : data(data), size(size), major{major}, state(state), tri(tri), diag(diag)\n    {\n        this->stride = (stride == 0 ? size : stride);\n    }\n    Triangle<T> &unit()\n    {\n        diag = Diagonal::Unit;\n        return *this;\n    }\n};\n\n#define TRIANGLE(name, major, tri)                                                          \\\n    template <typename T>                                                                   \\\n    Triangle<T> name(T *data, Size size, Size stride = 0)                                   \\\n    {                                                                                       \\\n        return Triangle<T>(data, size, stride, Major::major, State::None, Triangular::tri); \\\n    }\nTRIANGLE(rupper, Row, Upper) TRIANGLE(cupper, Col, Upper);\nTRIANGLE(rlower, Row, Lower) TRIANGLE(clower, Col, Lower);\n\ntemplate <typename T>\nstruct BTriangle\n{\n    using Type = T;\n\n    T *data;\n    Size size, stride;\n    Major major;\n    State state;\n    Triangular tri;\n    Diagonal diag;\n    Size super;\n    STATE(BTriangle);\n\n    BTriangle()\n        : data(nullptr),\n          size(0),\n          stride(0),\n          major{Major::Row},\n          state(State::None),\n          tri(Triangular::Upper),\n          diag(Diagonal::NonUnit),\n          super(0)\n    {\n    }\n    BTriangle(T *data, Size size, Size stride, Major major, State state, Triangular tri, Diagonal diag, Size super)\n        : data(data), size(size), major{major}, state(state), tri(tri), diag(diag), super(super)\n    {\n        this->stride = (stride == 0 ? size : stride);\n    }\n\n    BTriangle<T> &unit()\n    {\n        diag = Diagonal::Unit;\n        return *this;\n    }\n};\n\n#define BTRIANGLE(name, major, tri)                                                                 \\\n    template <typename T>                                                                           \\\n    BTriangle<T> name(T *data, Size size, Size super, Size stride = 0)                              \\\n    {                                                                                               \\\n        return BTriangle<T>(data, size, stride, Major::major, State::None, Triangular::tri, super); \\\n    }\nBTRIANGLE(rbupper, Row, Upper) BTRIANGLE(cbupper, Col, Upper);\nBTRIANGLE(rblower, Row, Lower) BTRIANGLE(cblower, Col, Lower);\n\ntemplate <typename T>\nstruct PTriangle\n{\n    using Type = T;\n\n    T *data;\n    Size size;\n    Major major;\n    State state;\n    Triangular tri;\n    Diagonal diag;\n    STATE(PTriangle);\n\n    PTriangle()\n        : data(nullptr), size(0), major{Major::Row}, state(State::None), tri(Triangular::Upper), diag(Diagonal::NonUnit)\n    {\n    }\n    PTriangle(T *data, Size size, Major major, State state, Triangular tri, Diagonal diag)\n        : data(data), size(size), major{major}, state(state), tri(tri), diag(diag)\n    {\n    }\n\n    PTriangle<T> &unit()\n    {\n        diag = Diagonal::Unit;\n        return *this;\n    }\n};\n\n#define PTRIANGLE(name, major, tri)                                                  \\\n    template <typename T>                                                            \\\n    PTriangle<T> name(T *data, Size size)                                            \\\n    {                                                                                \\\n        return PTriangle<T>(data, size, Major::major, State::None, Triangular::tri); \\\n    }\nPTRIANGLE(rpupper, Row, Upper) PTRIANGLE(cpupper, Col, Upper);\nPTRIANGLE(rplower, Row, Lower) PTRIANGLE(cplower, Col, Lower);\n\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n\ntemplate <typename T>\nstruct Symmetric\n{\n    using Type = T;\n\n    T *data;\n    Size size, stride;\n    Major major;\n    Triangular tri;\n\n    Symmetric() : data(nullptr), size(0), stride(0), major{Major::Row}, tri(Triangular::Upper) {}\n    Symmetric(T *data, Size size, Size stride, Major major, Triangular tri)\n        : data(data), size(size), major{major}, tri(tri)\n    {\n        this->stride = (stride == 0 ? size : stride);\n    }\n};\n\n#define SYMMETRIC(name, major, tri)                                             \\\n    template <typename T>                                                       \\\n    Symmetric<T> name(T *data, Size size, Size stride = 0)                      \\\n    {                                                                           \\\n        return Symmetric<T>(data, size, stride, Major::major, Triangular::tri); \\\n    }\nSYMMETRIC(rusym, Row, Upper) SYMMETRIC(cusym, Col, Upper);\nSYMMETRIC(rlsym, Row, Lower) SYMMETRIC(clsym, Col, Lower);\n\ntemplate <typename T>\nstruct BSymmetric\n{\n    using Type = T;\n\n    T *data;\n    Size size, stride;\n    Major major;\n    Triangular tri;\n    Size super;\n\n    BSymmetric() : data(nullptr), size(0), stride(0), major{Major::Row}, tri(Triangular::Upper), super(0) {}\n    BSymmetric(T *data, Size size, Size stride, Major major, Triangular tri, Size super)\n        : data(data), size(size), major{major}, tri(tri), super(super)\n    {\n        this->stride = (stride == 0 ? size : stride);\n    }\n};\n\n#define BSYMMETRIC(name, major, tri)                                                    \\\n    template <typename T>                                                               \\\n    BSymmetric<T> name(T *data, Size size, Size super, Size stride = 0)                 \\\n    {                                                                                   \\\n        return BSymmetric<T>(data, size, stride, Major::major, Triangular::tri, super); \\\n    }\nBSYMMETRIC(rbusym, Row, Upper) BSYMMETRIC(cbusym, Col, Upper);\nBSYMMETRIC(rblsym, Row, Lower) BSYMMETRIC(cblsym, Col, Lower);\n\ntemplate <typename T>\nstruct PSymmetric\n{\n    using Type = T;\n\n    T *data;\n    Size size;\n    Major major;\n    Triangular tri;\n\n    PSymmetric() : data(nullptr), size(0), major{Major::Row}, tri(Triangular::Upper) {}\n    PSymmetric(T *data, Size size, Major major, Triangular tri) : data(data), size(size), major{major}, tri(tri) {}\n};\n\n#define PSYMMETRIC(name, major, tri)                                     \\\n    template <typename T>                                                \\\n    PSymmetric<T> name(T *data, Size size)                               \\\n    {                                                                    \\\n        return PSymmetric<T>(data, size, Major::major, Triangular::tri); \\\n    }\nPSYMMETRIC(rpusym, Row, Upper) PSYMMETRIC(cpusym, Col, Upper);\nPSYMMETRIC(rplsym, Row, Lower) PSYMMETRIC(cplsym, Col, Lower);\n\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n\ntemplate <typename T>\nstruct Hermitian\n{\n    using Type = T;\n\n    T *data;\n    Size size, stride;\n    Major major;\n    Triangular tri;\n\n    Hermitian() : data(nullptr), size(0), stride(0), major{Major::Row}, tri(Triangular::Upper) {}\n    Hermitian(T *data, Size size, Size stride, Major major, Triangular tri)\n        : data(data), major{major}, size(size), tri(tri)\n    {\n        this->stride = (stride == 0 ? size : stride);\n    }\n};\n\n#define HERMITIAN(name, major, tri)                                             \\\n    template <typename T>                                                       \\\n    Hermitian<T> name(T *data, Size size, Size stride = 0)                      \\\n    {                                                                           \\\n        return Hermitian<T>(data, size, stride, Major::major, Triangular::tri); \\\n    }\nHERMITIAN(ruherm, Row, Upper) HERMITIAN(cuherm, Col, Upper);\nHERMITIAN(rlherm, Row, Lower) HERMITIAN(clherm, Col, Lower);\n\ntemplate <typename T>\nstruct BHermitian\n{\n    using Type = T;\n\n    T *data;\n    Size size, stride;\n    Major major;\n    Triangular tri;\n    Size super;\n\n    BHermitian() : data(nullptr), size(0), stride(0), major{Major::Row}, tri(Triangular::Upper), super(0) {}\n    BHermitian(T *data, Size size, Size stride, Major major, Triangular tri, Size super)\n        : data(data), size(size), major{major}, tri(tri), super(super)\n    {\n        this->stride = (stride == 0 ? size : stride);\n    }\n};\n\n#define BHERMITIAN(name, major, tri)                                                    \\\n    template <typename T>                                                               \\\n    BHermitian<T> name(T *data, Size size, Size super, Size stride = 0)                 \\\n    {                                                                                   \\\n        return BHermitian<T>(data, size, stride, Major::major, Triangular::tri, super); \\\n    }\nBHERMITIAN(rbuherm, Row, Upper) BHERMITIAN(cbuherm, Col, Upper);\nBHERMITIAN(rblherm, Row, Lower) BHERMITIAN(cblherm, Col, Lower);\n\ntemplate <typename T>\nstruct PHermitian\n{\n    using Type = T;\n\n    T *data;\n    Size size;\n    Major major;\n    Triangular tri;\n\n    PHermitian() : data(nullptr), size(0), major{Major::Row}, tri(Triangular::Upper) {}\n    PHermitian(T *data, Size size, Major major, Triangular tri) : data(data), size(size), major{major}, tri(tri) {}\n};\n\n#define PHERMITIAN(name, major, tri)                                     \\\n    template <typename T>                                                \\\n    PHermitian<T> name(T *data, Size size)                               \\\n    {                                                                    \\\n        return PHermitian<T>(data, size, Major::major, Triangular::tri); \\\n    }\nPHERMITIAN(rpusym, Row, Upper) PHERMITIAN(cpusym, Col, Upper);\nPHERMITIAN(rplsym, Row, Lower) PHERMITIAN(cplsym, Col, Lower);\n\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n\ntemplate <typename T>\nstruct Posdef\n{\n    using Type = T;\n\n    T *data;\n    Size size, stride;\n    Major major;\n    Triangular tri;\n\n    Posdef() : data(nullptr), size(0), stride(0), major{Major::Row}, tri(Triangular::Upper) {}\n    Posdef(T *data, Size size, Size stride, Major major, Triangular tri)\n        : data(data), size(size), major{major}, tri(tri)\n    {\n        this->stride = (stride == 0 ? size : stride);\n    }\n};\n\n#define POSDEF(name, major, tri)                                             \\\n    template <typename T>                                                    \\\n    Posdef<T> name(T *data, Size size, Size stride = 0)                      \\\n    {                                                                        \\\n        return Posdef<T>(data, size, stride, Major::major, Triangular::tri); \\\n    }\nPOSDEF(rupod, Row, Upper) POSDEF(cupod, Col, Upper);\nPOSDEF(rlpod, Row, Lower) POSDEF(clpod, Col, Lower);\n\n////////////////////////////////////////////////////////////////////////////////\n/// BLAS LEVEL 1 ///////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n\n#define REPEAT0(func, name1, name2) \\\n    func(cblas_##name1, float, );   \\\n    func(cblas_##name2, double, );\n\n#define REPEAT1(func, name1, name2)                      \\\n    func(cblas_##name1, std::complex<float>, (void *)&); \\\n    func(cblas_##name2, std::complex<double>, (void *)&);\n\n#define REPEAT(func, name1, name2, name3, name4) \\\n    REPEAT0(func, name1, name2)                  \\\n    REPEAT1(func, name3, name4)\n\n#define ROTG(F, T, R) \\\n    inline void givens(T &a, T &b, T &c, T &s) { F(&a, &b, &c, &s); }\n\n#define ROTMG(F, T, R) \\\n    inline void givens(T &d1, T &d2, T &b1, T &b2, T P[5]) { F(&d1, &d2, &b1, b2, P); }\n\nREPEAT0(ROTG, srotg, drotg)\nREPEAT0(ROTMG, srotmg, drotmg)\n\n#define ROT(F, T, R)                                                               \\\n    inline void rotate(Vector<T> X, Vector<T> Y, From<T>::Type c, From<T>::Type s) \\\n    {                                                                              \\\n        CHECK(X.size == Y.size);                                                   \\\n        return F(X.size, X.data, X.stride, Y.data, Y.stride, c, s);                \\\n    }\n\nREPEAT0(ROT, srot, drot)\n\n#define ROTM(F, T, R)                                                \\\n    inline void rotate(Vector<T> X, Vector<T> Y, From<T>::Type P[5]) \\\n    {                                                                \\\n        CHECK(X.size == Y.size);                                     \\\n        return F(X.size, X.data, X.stride, Y.data, Y.stride, P);     \\\n    }\n\nREPEAT0(ROTM, srotm, drotm)\n\n#define SWAP(F, T, R)                                         \\\n    inline void swap(Vector<T> X, Vector<T> Y)                \\\n    {                                                         \\\n        CHECK(X.size == Y.size);                              \\\n        return F(X.size, X.data, X.stride, Y.data, Y.stride); \\\n    }\n\nREPEAT(SWAP, sswap, dswap, cswap, zswap)\n\n#define SCAL(F, T, R) \\\n    inline void scale(Vector<T> X, T alpha) { return F(X.size, R alpha, X.data, X.stride); }\n\nREPEAT(SCAL, sscal, dscal, cscal, zscal)\n\n#define SSCAL(F, T, R) \\\n    inline void scale(Vector<T> X, From<T>::Type alpha) { return F(X.size, alpha, X.data, X.stride); }\n\nREPEAT1(SSCAL, csscal, zdscal)\n\n#define COPY(F, T, R)                                         \\\n    inline void copy(Vector<T> X, Vector<T> Y)                \\\n    {                                                         \\\n        CHECK(X.size == Y.size);                              \\\n        return F(X.size, X.data, X.stride, Y.data, Y.stride); \\\n    }\n\nREPEAT(COPY, scopy, dcopy, ccopy, zcopy)\n\n#define AXPY(F, T, R)                                                  \\\n    inline void axpy(Vector<T> X, Vector<T> Y, T alpha)                \\\n    {                                                                  \\\n        CHECK(X.size == Y.size);                                       \\\n        return F(X.size, R alpha, X.data, X.stride, Y.data, Y.stride); \\\n    }\n\nREPEAT(AXPY, saxpy, daxpy, caxpy, zaxpy)\n\n#define DOT(F, T, R)                                          \\\n    inline T dot(Vector<T> X, Vector<T> Y)                    \\\n    {                                                         \\\n        CHECK(X.size == Y.size);                              \\\n        return F(X.size, X.data, X.stride, Y.data, Y.stride); \\\n    }\n\nREPEAT0(DOT, sdot, ddot)\n\n#define DOTU(F, T, R)                                                       \\\n    inline T dot(Vector<T> X, Vector<T> Y, bool conj = true)                \\\n    {                                                                       \\\n        CHECK(X.size == Y.size);                                            \\\n        T result;                                                           \\\n        if (conj)                                                           \\\n            F##c_sub(X.size, X.data, X.stride, Y.data, Y.stride, R result); \\\n        else                                                                \\\n            F##u_sub(X.size, X.data, X.stride, Y.data, Y.stride, R result); \\\n        return result;                                                      \\\n    }\n\nREPEAT1(DOTU, cdot, zdot)\n\ninline float exdot(Vector<float> X, Vector<float> Y, float beta)\n{\n    CHECK(X.size == Y.size);\n    return cblas_sdsdot(X.size, beta, X.data, X.stride, Y.data, Y.stride);\n}\ninline float exdot(Vector<float> X, Vector<float> Y)\n{\n    CHECK(X.size == Y.size);\n    return cblas_dsdot(X.size, X.data, X.stride, Y.data, Y.stride);\n}\n\n#define NRM2(F, T, R) \\\n    inline From<T>::Type norm2(Vector<T> X) { return F(X.size, X.data, X.stride); }\n\nREPEAT(NRM2, snrm2, dnrm2, scnrm2, dznrm2)\n\n#define ASUM(F, T, R) \\\n    inline From<T>::Type asum(Vector<T> X) { return F(X.size, X.data, X.stride); }\n\nREPEAT(ASUM, sasum, dasum, scasum, dzasum)\n\n#define IAMAX(F, T, R) \\\n    inline Index iamax(Vector<T> X) { return F(X.size, X.data, X.stride); }\n\nREPEAT(IAMAX, isamax, idamax, icamax, izamax)\n\n////////////////////////////////////////////////////////////////////////////////\n/// BLAS LEVEL 2 ///////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n\n#define GEMV(F, T, R)                                                                                              \\\n    inline void dot(General<T> A, Vector<T> X, Vector<T> Y, T alpha, T beta)                                       \\\n    {                                                                                                              \\\n        CHECK(A._cols() == X.size) CHECK(A._rows() == Y.size);                                                     \\\n        F(Impl::blcvt(A.major), Impl::blcvt(A.state), A.rows, A.cols, R alpha, A.data, A.stride, X.data, X.stride, \\\n          R beta, Y.data, Y.stride);                                                                               \\\n    }\n\nREPEAT(GEMV, sgemv, dgemv, cgemv, zgemv)\n\n#define GBMV(F, T, R)                                                                                            \\\n    inline void dot(BGeneral<T> A, Vector<T> X, Vector<T> Y, T alpha, T beta)                                    \\\n    {                                                                                                            \\\n        CHECK(A._cols() == X.size) CHECK(A._rows() == Y.size);                                                   \\\n        F(Impl::blcvt(A.major), Impl::blcvt(A.state), A.rows, A.cols, A.sub, A.super, R alpha, A.data, A.stride, \\\n          X.data, X.stride, R beta, Y.data, Y.stride);                                                           \\\n    }\n\nREPEAT(GBMV, sgbmv, dgbmv, cgbmv, zgbmv)\n\n#define SYMV(F, T, R)                                                                                            \\\n    inline void dot(Symmetric<T> A, Vector<T> X, Vector<T> Y, T alpha, T beta)                                   \\\n    {                                                                                                            \\\n        CHECK(A.size == X.size) CHECK(A.size == Y.size);                                                         \\\n        F(Impl::blcvt(A.major), Impl::blcvt(A.tri), A.size, R alpha, A.data, A.stride, X.data, X.stride, R beta, \\\n          Y.data, Y.stride);                                                                                     \\\n    }\n\n#define HEMV(F, T, R)                                                                                            \\\n    inline void dot(Hermitian<T> A, Vector<T> X, Vector<T> Y, T alpha, T beta)                                   \\\n    {                                                                                                            \\\n        CHECK(A.size == X.size) CHECK(A.size == Y.size);                                                         \\\n        F(Impl::blcvt(A.major), Impl::blcvt(A.tri), A.size, R alpha, A.data, A.stride, X.data, X.stride, R beta, \\\n          Y.data, Y.stride);                                                                                     \\\n    }\n\nREPEAT0(SYMV, ssymv, dsymv)\nREPEAT1(HEMV, chemv, zhemv)\n\n#define SBMV(F, T, R)                                                                                             \\\n    inline void dot(BSymmetric<T> A, Vector<T> X, Vector<T> Y, T alpha, T beta)                                   \\\n    {                                                                                                             \\\n        CHECK(A.size == X.size) CHECK(A.size == Y.size);                                                          \\\n        F(Impl::blcvt(A.major), Impl::blcvt(A.tri), A.size, A.super, R alpha, A.data, A.stride, X.data, X.stride, \\\n          R beta, Y.data, Y.stride);                                                                              \\\n    }\n\n#define HBMV(F, T, R)                                                                                             \\\n    inline void dot(BHermitian<T> A, Vector<T> X, Vector<T> Y, T alpha, T beta)                                   \\\n    {                                                                                                             \\\n        CHECK(A.size == X.size) CHECK(A.size == Y.size);                                                          \\\n        F(Impl::blcvt(A.major), Impl::blcvt(A.tri), A.size, A.super, R alpha, A.data, A.stride, X.data, X.stride, \\\n          R beta, Y.data, Y.stride);                                                                              \\\n    }\n\nREPEAT0(SBMV, ssbmv, dsbmv)\nREPEAT1(HBMV, chbmv, zhbmv)\n\n#define SPMV(F, T, R)                                                                                          \\\n    inline void dot(PSymmetric<T> A, Vector<T> X, Vector<T> Y, T alpha, T beta)                                \\\n    {                                                                                                          \\\n        CHECK(A.size == X.size) CHECK(A.size == Y.size);                                                       \\\n        F(Impl::blcvt(A.major), Impl::blcvt(A.tri), A.size, R alpha, A.data, X.data, X.stride, R beta, Y.data, \\\n          Y.stride);                                                                                           \\\n    }\n\n#define HPMV(F, T, R)                                                                                          \\\n    inline void dot(PHermitian<T> A, Vector<T> X, Vector<T> Y, T alpha, T beta)                                \\\n    {                                                                                                          \\\n        CHECK(A.size == X.size) CHECK(A.size == Y.size);                                                       \\\n        F(Impl::blcvt(A.major), Impl::blcvt(A.tri), A.size, R alpha, A.data, X.data, X.stride, R beta, Y.data, \\\n          Y.stride);                                                                                           \\\n    }\n\nREPEAT0(SPMV, sspmv, dspmv)\nREPEAT1(HPMV, chpmv, zhpmv)\n\n#define TRMV(F, T, R)                                                                                          \\\n    inline void dot(Triangle<T> A, Vector<T> X)                                                                \\\n    {                                                                                                          \\\n        CHECK(A.size == X.size);                                                                               \\\n        F(Impl::blcvt(A.major), Impl::blcvt(A.tri), Impl::blcvt(A.state), Impl::blcvt(A.diag), A.size, A.data, \\\n          A.stride, X.data, X.stride);                                                                         \\\n    }\n\nREPEAT(TRMV, strmv, dtrmv, ctrmv, ztrmv)\n\n#define TBMV(F, T, R)                                                                                           \\\n    inline void dot(BTriangle<T> A, Vector<T> X)                                                                \\\n    {                                                                                                           \\\n        CHECK(A.size == X.size);                                                                                \\\n        F(Impl::blcvt(A.major), Impl::blcvt(A.tri), Impl::blcvt(A.state), Impl::blcvt(A.diag), A.size, A.super, \\\n          A.data, A.stride, X.data, X.stride);                                                                  \\\n    }\n\nREPEAT(TBMV, stbmv, dtbmv, ctbmv, ztbmv)\n\n#define TPMV(F, T, R)                                                                                                  \\\n    inline void dot(PTriangle<T> A, Vector<T> X)                                                                       \\\n    {                                                                                                                  \\\n        CHECK(A.size == X.size);                                                                                       \\\n        F(Impl::blcvt(A.major), Impl::blcvt(A.tri), Impl::blcvt(A.state), Impl::blcvt(A.diag), A.size, A.data, X.data, \\\n          X.stride);                                                                                                   \\\n    }\n\nREPEAT(TPMV, stpmv, dtpmv, ctpmv, ztpmv)\n\n#define TRSV(F, T, R)                                                                                          \\\n    inline void solve(Triangle<T> A, Vector<T> X)                                                              \\\n    {                                                                                                          \\\n        CHECK(A.size == X.size);                                                                               \\\n        F(Impl::blcvt(A.major), Impl::blcvt(A.tri), Impl::blcvt(A.state), Impl::blcvt(A.diag), A.size, A.data, \\\n          A.stride, X.data, X.stride);                                                                         \\\n    }\n\nREPEAT(TRSV, strsv, dtrsv, ctrsv, ztrsv)\n\n#define TBSV(F, T, R)                                                                                           \\\n    inline void solve(BTriangle<T> A, Vector<T> X)                                                              \\\n    {                                                                                                           \\\n        CHECK(A.size == X.size);                                                                                \\\n        F(Impl::blcvt(A.major), Impl::blcvt(A.tri), Impl::blcvt(A.state), Impl::blcvt(A.diag), A.size, A.super, \\\n          A.data, A.stride, X.data, X.stride);                                                                  \\\n    }\n\nREPEAT(TBSV, stbsv, dtbsv, ctbsv, ztbsv)\n\n#define TPSV(F, T, R)                                                                                                  \\\n    inline void solve(PTriangle<T> A, Vector<T> X)                                                                     \\\n    {                                                                                                                  \\\n        CHECK(A.size == X.size);                                                                                       \\\n        F(Impl::blcvt(A.major), Impl::blcvt(A.tri), Impl::blcvt(A.state), Impl::blcvt(A.diag), A.size, A.data, X.data, \\\n          X.stride);                                                                                                   \\\n    }\n\nREPEAT(TPSV, stpsv, dtpsv, ctpsv, ztpsv)\n\n#define GER(F, T, R)                                                                                            \\\n    inline void update(Vector<T> X, Vector<T> Y, General<T> A, T alpha)                                         \\\n    {                                                                                                           \\\n        CHECK(X.size == A.rows) CHECK(Y.size == A.cols) CHECK(A.state == State::None);                          \\\n        F(Impl::blcvt(A.major), X.size, Y.size, R alpha, X.data, X.stride, Y.data, Y.stride, A.data, A.stride); \\\n    }\n\nREPEAT0(GER, sger, dger)\n\n#define GERU(F, T, R)                                                                                                  \\\n    inline void update(Vector<T> X, Vector<T> Y, General<T> A, T alpha, bool conj = true)                              \\\n    {                                                                                                                  \\\n        CHECK(X.size == A.rows) CHECK(Y.size == A.cols) CHECK(A.state == State::None);                                 \\\n        if (conj)                                                                                                      \\\n            F##c(Impl::blcvt(A.major), X.size, Y.size, R alpha, X.data, X.stride, Y.data, Y.stride, A.data, A.stride); \\\n        else                                                                                                           \\\n            F##u(Impl::blcvt(A.major), X.size, Y.size, R alpha, X.data, X.stride, Y.data, Y.stride, A.data, A.stride); \\\n    }\n\nREPEAT1(GERU, cger, zger)\n\n#define SYR(F, T, R)                                                                                      \\\n    inline void update(Vector<T> X, Symmetric<T> A, T alpha)                                              \\\n    {                                                                                                     \\\n        CHECK(A.size == X.size);                                                                          \\\n        F(Impl::blcvt(A.major), Impl::blcvt(A.tri), A.size, R alpha, X.data, X.stride, A.data, A.stride); \\\n    }\n\n#define HER(F, T, R)                                                                                    \\\n    inline void update(Vector<T> X, Hermitian<T> A, From<T>::Type alpha)                                \\\n    {                                                                                                   \\\n        CHECK(A.size == X.size);                                                                        \\\n        F(Impl::blcvt(A.major), Impl::blcvt(A.tri), A.size, alpha, X.data, X.stride, A.data, A.stride); \\\n    }\n\nREPEAT0(SYR, ssyr, dsyr)\nREPEAT1(HER, cher, zher)\n\n#define SPR(F, T, R)                                                                            \\\n    inline void update(Vector<T> X, PSymmetric<T> A, T alpha)                                   \\\n    {                                                                                           \\\n        CHECK(A.size == X.size);                                                                \\\n        F(Impl::blcvt(A.major), Impl::blcvt(A.tri), A.size, R alpha, X.data, X.stride, A.data); \\\n    }\n\n#define HPR(F, T, R)                                                                          \\\n    inline void update(Vector<T> X, PHermitian<T> A, From<T>::Type alpha)                     \\\n    {                                                                                         \\\n        CHECK(A.size == X.size);                                                              \\\n        F(Impl::blcvt(A.major), Impl::blcvt(A.tri), A.size, alpha, X.data, X.stride, A.data); \\\n    }\n\nREPEAT0(SPR, sspr, dspr)\nREPEAT1(HPR, chpr, zhpr)\n\n#define SYR2(F, T, R)                                                                                            \\\n    inline void update(Vector<T> X, Vector<T> Y, Symmetric<T> A, T alpha)                                        \\\n    {                                                                                                            \\\n        CHECK(A.size == X.size) CHECK(X.size == Y.size);                                                         \\\n        F(Impl::blcvt(A.major), Impl::blcvt(A.tri), A.size, R alpha, X.data, X.stride, Y.data, Y.stride, A.data, \\\n          A.stride);                                                                                             \\\n    }\n\n#define HER2(F, T, R)                                                                                            \\\n    inline void update(Vector<T> X, Vector<T> Y, Hermitian<T> A, T alpha)                                        \\\n    {                                                                                                            \\\n        CHECK(A.size == X.size) CHECK(X.size == Y.size);                                                         \\\n        F(Impl::blcvt(A.major), Impl::blcvt(A.tri), A.size, R alpha, X.data, X.stride, Y.data, Y.stride, A.data, \\\n          A.stride);                                                                                             \\\n    }\n\nREPEAT0(SYR2, ssyr2, dsyr2)\nREPEAT1(HER2, cher2, zher2)\n\n#define SPR2(F, T, R)                                                                                             \\\n    inline void update(Vector<T> X, Vector<T> Y, PSymmetric<T> A, T alpha)                                        \\\n    {                                                                                                             \\\n        CHECK(A.size == X.size) CHECK(X.size == Y.size);                                                          \\\n        F(Impl::blcvt(A.major), Impl::blcvt(A.tri), A.size, R alpha, X.data, X.stride, Y.data, Y.stride, A.data); \\\n    }\n\n#define HPR2(F, T, R)                                                                                             \\\n    inline void update(Vector<T> X, Vector<T> Y, PHermitian<T> A, T alpha)                                        \\\n    {                                                                                                             \\\n        CHECK(A.size == X.size) CHECK(X.size == Y.size);                                                          \\\n        F(Impl::blcvt(A.major), Impl::blcvt(A.tri), A.size, R alpha, X.data, X.stride, Y.data, Y.stride, A.data); \\\n    }\n\nREPEAT0(SPR2, sspr2, dspr2)\nREPEAT1(HPR2, chpr2, zhpr2)\n\n////////////////////////////////////////////////////////////////////////////////\n/// BLAS LEVEL 3 ///////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n\n#define GEMM(F, T, R)                                                                                           \\\n    inline void dot(General<T> A, General<T> B, General<T> C, T alpha, T beta)                                  \\\n    {                                                                                                           \\\n        CHECK(A.major == B.major) CHECK(A.major == C.major) CHECK(C.state == State::None);                      \\\n        CHECK(A._cols() == B._rows()) CHECK(A._rows() == C.rows) CHECK(B._cols() == C.cols);                    \\\n        F(Impl::blcvt(A.major), Impl::blcvt(A.state), Impl::blcvt(B.state), C.rows, C.cols, A._cols(), R alpha, \\\n          A.data, A.stride, B.data, B.stride, R beta, C.data, C.stride);                                        \\\n    }\n\nREPEAT(GEMM, sgemm, dgemm, cgemm, zgemm)\n\n#define SYMM(F, T, R)                                                                                              \\\n    inline void dot(Symmetric<T> A, General<T> B, General<T> C, T alpha, T beta)                                   \\\n    {                                                                                                              \\\n        CHECK(A.major == B.major) CHECK(A.major == C.major);                                                       \\\n        CHECK(B.state == State::None) CHECK(C.state == State::None);                                               \\\n        CHECK(A.size == B.rows) CHECK(A.size == C.rows) CHECK(B.cols == C.cols);                                   \\\n        F(Impl::blcvt(A.major), CblasLeft, Impl::blcvt(A.tri), C.rows, C.cols, R alpha, A.data, A.stride, B.data,  \\\n          B.stride, R beta, C.data, C.stride);                                                                     \\\n    }                                                                                                              \\\n    inline void dot(General<T> B, Symmetric<T> A, General<T> C, T alpha, T beta)                                   \\\n    {                                                                                                              \\\n        CHECK(A.major == B.major) CHECK(A.major == C.major);                                                       \\\n        CHECK(B.state == State::None) CHECK(C.state == State::None);                                               \\\n        CHECK(A.size == B.cols) CHECK(A.size == C.cols) CHECK(B.rows == C.rows);                                   \\\n        F(Impl::blcvt(A.major), CblasRight, Impl::blcvt(A.tri), C.rows, C.cols, R alpha, A.data, A.stride, B.data, \\\n          B.stride, R beta, C.data, C.stride);                                                                     \\\n    }\n\nREPEAT(SYMM, ssymm, dsymm, csymm, zsymm)\n\n#define HEMM(F, T, R)                                                                                              \\\n    inline void dot(Hermitian<T> A, General<T> B, General<T> C, T alpha, T beta)                                   \\\n    {                                                                                                              \\\n        CHECK(A.major == B.major) CHECK(A.major == C.major);                                                       \\\n        CHECK(B.state == State::None) CHECK(C.state == State::None);                                               \\\n        CHECK(A.size == B.rows) CHECK(A.size == C.rows) CHECK(B.cols == C.cols);                                   \\\n        F(Impl::blcvt(A.major), CblasLeft, Impl::blcvt(A.tri), C.rows, C.cols, R alpha, A.data, A.stride, B.data,  \\\n          B.stride, R beta, C.data, C.stride);                                                                     \\\n    }                                                                                                              \\\n    inline void dot(General<T> B, Hermitian<T> A, General<T> C, T alpha, T beta)                                   \\\n    {                                                                                                              \\\n        CHECK(A.major == B.major) CHECK(A.major == C.major);                                                       \\\n        CHECK(B.state == State::None) CHECK(C.state == State::None);                                               \\\n        CHECK(A.size == B.cols) CHECK(A.size == C.cols) CHECK(B.rows == C.rows);                                   \\\n        F(Impl::blcvt(A.major), CblasRight, Impl::blcvt(A.tri), C.rows, C.cols, R alpha, A.data, A.stride, B.data, \\\n          B.stride, R beta, C.data, C.stride);                                                                     \\\n    }\n\nREPEAT1(HEMM, chemm, zhemm)\n\n#define TRMM(F, T, R)                                                                                              \\\n    inline void dot(Triangle<T> A, General<T> B, T alpha)                                                          \\\n    {                                                                                                              \\\n        CHECK(A.major == B.major) CHECK(A.size == B.rows) CHECK(B.state == State::None);                           \\\n        F(Impl::blcvt(A.major), CblasLeft, Impl::blcvt(A.tri), Impl::blcvt(A.state), Impl::blcvt(A.diag), B.rows,  \\\n          B.cols, R alpha, A.data, A.stride, B.data, B.stride);                                                    \\\n    }                                                                                                              \\\n    inline void dot(General<T> B, Triangle<T> A, T alpha)                                                          \\\n    {                                                                                                              \\\n        CHECK(A.major == B.major) CHECK(A.size == B.cols) CHECK(B.state == State::None);                           \\\n        F(Impl::blcvt(A.major), CblasRight, Impl::blcvt(A.tri), Impl::blcvt(A.state), Impl::blcvt(A.diag), B.rows, \\\n          B.cols, R alpha, A.data, A.stride, B.data, B.stride);                                                    \\\n    }\n\nREPEAT(TRMM, strmm, dtrmm, ctrmm, ztrmm)\n\n#define TRSM(F, T, R)                                                                                              \\\n    inline void solve(Triangle<T> A, General<T> B, T alpha)                                                        \\\n    {                                                                                                              \\\n        CHECK(A.major == B.major) CHECK(A.size == B.rows) CHECK(B.state == State::None);                           \\\n        F(Impl::blcvt(A.major), CblasLeft, Impl::blcvt(A.tri), Impl::blcvt(A.state), Impl::blcvt(A.diag), B.rows,  \\\n          B.cols, R alpha, A.data, A.stride, B.data, B.stride);                                                    \\\n    }                                                                                                              \\\n    inline void solve(General<T> B, Triangle<T> A, T alpha)                                                        \\\n    {                                                                                                              \\\n        CHECK(A.major == B.major) CHECK(A.size == B.cols) CHECK(B.state == State::None);                           \\\n        F(Impl::blcvt(A.major), CblasRight, Impl::blcvt(A.tri), Impl::blcvt(A.state), Impl::blcvt(A.diag), B.rows, \\\n          B.cols, R alpha, A.data, A.stride, B.data, B.stride);                                                    \\\n    }\n\nREPEAT(TRSM, strsm, dtrsm, ctrsm, ztrsm)\n\n#define SYRK(F, T, R)                                                                                            \\\n    inline void update(General<T> A, Symmetric<T> C, T alpha, T beta)                                            \\\n    {                                                                                                            \\\n        CHECK(A.major == C.major) CHECK(A._rows() == C.size);                                                    \\\n        F(Impl::blcvt(A.major), Impl::blcvt(C.tri), Impl::blcvt(A.state), A._rows(), A._cols(), R alpha, A.data, \\\n          A.stride, R beta, C.data, C.stride);                                                                   \\\n    }\n\nREPEAT(SYRK, ssyrk, dsyrk, csyrk, zsyrk)\n\n#define HERK(F, T, R)                                                                                          \\\n    inline void update(General<T> A, Hermitian<T> C, From<T>::Type alpha, From<T>::Type beta)                  \\\n    {                                                                                                          \\\n        CHECK(A.major == C.major) CHECK(A._rows() == C.size);                                                  \\\n        F(Impl::blcvt(A.major), Impl::blcvt(C.tri), Impl::blcvt(A.state), A._rows(), A._cols(), alpha, A.data, \\\n          A.stride, beta, C.data, C.stride);                                                                   \\\n    }\n\nREPEAT1(HERK, cherk, zherk)\n\n#define SYR2K(F, T, R)                                                                                           \\\n    inline void update(General<T> A, General<T> B, Symmetric<T> C, T alpha, T beta)                              \\\n    {                                                                                                            \\\n        CHECK(A.major == B.major) CHECK(A.major == C.major) CHECK(A.state == B.state);                           \\\n        CHECK(A._rows() == C.size) CHECK(A._rows() == B._rows()) CHECK(A._cols() == B._cols());                  \\\n        F(Impl::blcvt(A.major), Impl::blcvt(C.tri), Impl::blcvt(A.state), A._rows(), B._cols(), R alpha, A.data, \\\n          A.stride, B.data, B.stride, R beta, C.data, C.stride);                                                 \\\n    }\n\nREPEAT(SYR2K, ssyr2k, dsyr2k, csyr2k, zsyr2k)\n\n#define HER2K(F, T, R)                                                                                           \\\n    inline void update(General<T> A, General<T> B, Hermitian<T> C, T alpha, From<T>::Type beta)                  \\\n    {                                                                                                            \\\n        CHECK(A.major == B.major) CHECK(A.major == C.major) CHECK(A.state == B.state);                           \\\n        CHECK(A._rows() == C.size) CHECK(A._rows() == B._rows()) CHECK(A._cols() == B._cols());                  \\\n        F(Impl::blcvt(A.major), Impl::blcvt(C.tri), Impl::blcvt(A.state), A._rows(), B._cols(), R alpha, A.data, \\\n          A.stride, B.data, B.stride, beta, C.data, C.stride);                                                   \\\n    }\n\nREPEAT1(HER2K, cher2k, zher2k)\n\n////////////////////////////////////////////////////////////////////////////////\n/// LAPACK /////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n\n#ifdef BLASW_LAPACKE_FOUND\n\n#undef REPEAT0\n#undef REPEAT1\n#undef REPEAT\n\n#define REPEAT0(func, name1, name2) \\\n    func(LAPACKE_##name1, float, ); \\\n    func(LAPACKE_##name2, double, );\n\n#define REPEAT1(func, name1, name2)                        \\\n    func(LAPACKE_##name1, std::complex<float>, (void *)&); \\\n    func(LAPACKE_##name2, std::complex<double>, (void *)&);\n\n#define REPEAT(func, name1, name2, name3, name4) \\\n    REPEAT0(func, name1, name2)                  \\\n    REPEAT1(func, name3, name4)\n\nnamespace Impl\n{\ninline int lpcvt(Major major) { return major == Major::Row ? LAPACK_ROW_MAJOR : LAPACK_ROW_MAJOR; }\n\ninline char lpcvt(State state)\n{\n    if (state == State::None)\n        return 'N';\n    else if (state == State::Trans)\n        return 'T';\n    else if (state == State::ConjTrans)\n        return 'C';\n    else\n        return '\\0';\n}\n\ninline char lpcvt(Triangular tri) { return tri == Triangular::Upper ? 'U' : 'L'; }\n\ntemplate <typename T>\nstd::unique_ptr<T> alloc(Size size)\n{\n#ifdef _WIN32\n    auto P = malloc(size * sizeof(T));\n#else\n    auto P = aligned_alloc(64, size * sizeof(T));\n#endif\n    return std::unique_ptr<T>((T *)P);\n}\n}  // namespace Impl\n\n#define GETRI(F, T, R)                                                                                    \\\n    inline bool inverse(General<T> A)                                                                     \\\n    {                                                                                                     \\\n        CHECK(A.rows == A.cols) CHECK(A.state == State::None);                                            \\\n        auto P = Impl::alloc<int>(A.rows);                                                                \\\n        if (F##getrf(Impl::lpcvt(A.major), A.rows, A.cols, A.data, A.stride, P.get()) != 0) return false; \\\n        return F##getri(Impl::lpcvt(A.major), A.rows, A.data, A.stride, P.get()) == 0;                    \\\n    }\n\nREPEAT(GETRI, s, d, c, z)\n\n#define SYTRI(F, T, R)                                                                                                \\\n    inline bool inverse(Symmetric<T> A)                                                                               \\\n    {                                                                                                                 \\\n        auto P = Impl::alloc<int>(A.size);                                                                            \\\n        if (F##sytrf(Impl::lpcvt(A.major), Impl::lpcvt(A.tri), A.size, A.data, A.stride, P.get()) != 0) return false; \\\n        return F##sytri(Impl::lpcvt(A.major), Impl::lpcvt(A.tri), A.size, A.data, A.stride, P.get()) == 0;            \\\n    }\n\nREPEAT(SYTRI, s, d, c, z)\n\n#define GEDTR(F, T, R)                                                                                 \\\n    inline T determinant(General<T> A)                                                                 \\\n    {                                                                                                  \\\n        CHECK(A.rows == A.cols) CHECK(A.state == State::None);                                         \\\n        auto _P = Impl::alloc<int>(A.rows);                                                            \\\n        if (F##getrf(Impl::lpcvt(A.major), A.rows, A.cols, A.data, A.stride, _P.get()) != 0) return 0; \\\n                                                                                                       \\\n        T det = 1;                                                                                     \\\n        auto P = _P.get();                                                                             \\\n        for (Size i = 0; i < A.rows; ++i) det *= A.data[i * A.stride + i] * T(P[i] == i ? 1 : -1);     \\\n        return det;                                                                                    \\\n    }\n\nREPEAT(GEDTR, s, d, c, z)\n\n#define SYDTR(F, T, R)                                                                                             \\\n    inline T determinant(Symmetric<T> A)                                                                           \\\n    {                                                                                                              \\\n        auto _P = Impl::alloc<int>(A.size);                                                                        \\\n        if (F##sytrf(Impl::lpcvt(A.major), Impl::lpcvt(A.tri), A.size, A.data, A.stride, _P.get()) != 0) return 0; \\\n                                                                                                                   \\\n        T det = 1;                                                                                                 \\\n        auto P = _P.get();                                                                                         \\\n        for (Size i = 0; i < A.size; ++i) det *= A.data[i * A.stride + i] * T(P[i] == i ? 1 : -1);                 \\\n        return det;                                                                                                \\\n    }\n\nREPEAT(SYDTR, s, d, c, z)\n\n#define HEDTR(F, T, R)                                                                                             \\\n    inline T determinant(Hermitian<T> A)                                                                           \\\n    {                                                                                                              \\\n        auto _P = Impl::alloc<int>(A.size);                                                                        \\\n        if (F##hetrf(Impl::lpcvt(A.major), Impl::lpcvt(A.tri), A.size, A.data, A.stride, _P.get()) != 0) return 0; \\\n                                                                                                                   \\\n        T det = 1;                                                                                                 \\\n        auto P = _P.get();                                                                                         \\\n        for (Size i = 0; i < A.size; ++i) det *= A.data[i * A.stride + i] * T(P[i] == i ? 1 : -1);                 \\\n        return det;                                                                                                \\\n    }\n\nREPEAT1(HEDTR, c, z)\n\n#define GETRF(F, T, R)                                                                                \\\n    inline bool lufact(General<T> A, Vector<int> P)                                                   \\\n    {                                                                                                 \\\n        CHECK(A.state == State::None) CHECK(std::min(A.rows, A.cols) == P.size) CHECK(P.stride == 1); \\\n        return F(Impl::lpcvt(A.major), A.rows, A.cols, A.data, A.stride, P.data) == 0;                \\\n    }\n\nREPEAT(GETRF, sgetrf, dgetrf, cgetrf, zgetrf)\n\n#define SYTRF(F, T, R)                                                                             \\\n    inline bool lufact(Symmetric<T> A, Vector<int> P)                                              \\\n    {                                                                                              \\\n        CHECK(A.size == P.size) CHECK(P.stride == 1);                                              \\\n        return F(Impl::lpcvt(A.major), Impl::lpcvt(A.tri), A.size, A.data, A.stride, P.data) == 0; \\\n    }\n\nREPEAT(SYTRF, ssytrf, dsytrf, csytrf, zsytrf)\n\n#define HETRF(F, T, R)                                                                             \\\n    inline bool lufact(Hermitian<T> A, Vector<int> P)                                              \\\n    {                                                                                              \\\n        CHECK(A.size == P.size) CHECK(P.stride == 1);                                              \\\n        return F(Impl::lpcvt(A.major), Impl::lpcvt(A.tri), A.size, A.data, A.stride, P.data) == 0; \\\n    }\n\nREPEAT1(HETRF, chetrf, zhetrf)\n\n#define POTRF(F, T, R)                                                                     \\\n    inline bool cholesky(Posdef<T> A)                                                      \\\n    {                                                                                      \\\n        return F(Impl::lpcvt(A.major), Impl::lpcvt(A.tri), A.size, A.data, A.stride) == 0; \\\n    }\n\nREPEAT(POTRF, spotrf, dpotrf, cpotrf, zpotrf)\n\n#define GEQRF(F, TYPE, R)                                                                             \\\n    inline bool qrfact(General<TYPE> A, Vector<TYPE> T)                                               \\\n    {                                                                                                 \\\n        CHECK(A.state == State::None) CHECK(std::min(A.rows, A.cols) == T.size) CHECK(T.stride == 1); \\\n        return F(Impl::lpcvt(A.major), A.rows, A.cols, A.data, A.stride, T.data) == 0;                \\\n    }\n\nREPEAT(GEQRF, sgeqrf, dgeqrf, cgeqrf, zgeqrf)\n\n#define GEEV(F, T, REF)                                                                                           \\\n    inline bool eigen(General<T> A, Vector<std::complex<T>> E, General<T> L, General<T> R)                        \\\n    {                                                                                                             \\\n        CHECK(A.major == L.major) CHECK(A.major == R.major);                                                      \\\n        CHECK(A.state == State::None) CHECK(L.state == State::None) CHECK(R.state == State::None);                \\\n        CHECK(A.rows == A.cols) CHECK(L.rows == L.cols) CHECK(R.rows == R.cols);                                  \\\n        CHECK(A.rows == E.size) CHECK(E.stride == 1);                                                             \\\n                                                                                                                  \\\n        if (L.data == nullptr) L.stride = A.rows;                                                                 \\\n        if (R.data == nullptr) R.stride = A.rows;                                                                 \\\n        auto _WR = Impl::alloc<T>(A.rows), _WI = Impl::alloc<T>(A.rows);                                          \\\n        if (F(Impl::lpcvt(A.major), L.data == nullptr ? 'N' : 'V', R.data == nullptr ? 'N' : 'V', A.rows, A.data, \\\n              A.stride, _WR.get(), _WI.get(), L.data, L.stride, R.data, R.stride) != 0)                           \\\n            return false;                                                                                         \\\n                                                                                                                  \\\n        auto WR = _WR.get(), WI = _WI.get();                                                                      \\\n        for (Size i = 0; i < A.rows; ++i) E.data[i].real(WR[i]), E.data[i].imag(WI[i]);                           \\\n        return true;                                                                                              \\\n    }\n\n#define GEEVC(F, T, REF)                                                                                             \\\n    inline bool eigen(General<T> A, Vector<T> E, General<T> L, General<T> R)                                         \\\n    {                                                                                                                \\\n        CHECK(A.major == L.major) CHECK(A.major == R.major);                                                         \\\n        CHECK(A.state == State::None) CHECK(L.state == State::None) CHECK(R.state == State::None);                   \\\n        CHECK(A.rows == A.cols) CHECK(L.rows == L.cols) CHECK(R.rows == R.cols);                                     \\\n        CHECK(A.rows == E.size) CHECK(E.stride == 1);                                                                \\\n                                                                                                                     \\\n        if (L.data == nullptr) L.stride = A.rows;                                                                    \\\n        if (R.data == nullptr) R.stride = A.rows;                                                                    \\\n        return F(Impl::lpcvt(A.major), L.data == nullptr ? 'N' : 'V', R.data == nullptr ? 'N' : 'V', A.rows, A.data, \\\n                 A.stride, E.data, L.data, L.stride, R.data, R.stride) == 0;                                         \\\n    }\n\nREPEAT0(GEEV, sgeev, dgeev)\nREPEAT1(GEEVC, cgeev, zgeev)\n\n#define SYEV(F, T, R)                                                                                        \\\n    inline bool eigen(Symmetric<T> A, Vector<T> E, bool vectors, bool divcon)                                \\\n    {                                                                                                        \\\n        CHECK(A.size == E.size) CHECK(E.stride == 1);                                                        \\\n        auto V = vectors ? 'V' : 'N';                                                                        \\\n                                                                                                             \\\n        if (divcon)                                                                                          \\\n            return F##d(Impl::lpcvt(A.major), V, Impl::lpcvt(A.tri), A.size, A.data, A.stride, E.data) == 0; \\\n        else                                                                                                 \\\n            return F(Impl::lpcvt(A.major), V, Impl::lpcvt(A.tri), A.size, A.data, A.stride, E.data) == 0;    \\\n    }\n\n#define HEEV(F, T, R)                                                                                        \\\n    inline bool eigen(Hermitian<T> A, Vector<From<T>::Type> E, bool vectors, bool divcon)                    \\\n    {                                                                                                        \\\n        CHECK(A.size == E.size) CHECK(E.stride == 1);                                                        \\\n        auto V = vectors ? 'V' : 'N';                                                                        \\\n                                                                                                             \\\n        if (divcon)                                                                                          \\\n            return F##d(Impl::lpcvt(A.major), V, Impl::lpcvt(A.tri), A.size, A.data, A.stride, E.data) == 0; \\\n        else                                                                                                 \\\n            return F(Impl::lpcvt(A.major), V, Impl::lpcvt(A.tri), A.size, A.data, A.stride, E.data) == 0;    \\\n    }\n\nREPEAT0(SYEV, ssyev, dsyev)\nREPEAT1(HEEV, cheev, zheev)\n\n#define GEES(F, T, R)                                                                                             \\\n    inline bool schur(General<T> A, Vector<std::complex<T>> E, General<T> V)                                      \\\n    {                                                                                                             \\\n        CHECK(A.major == V.major) CHECK(A.state == State::None) CHECK(V.state == State::None);                    \\\n        CHECK(A.rows == A.cols) CHECK(A.rows == E.size) CHECK(E.stride == 1) CHECK(V.rows == V.cols);             \\\n                                                                                                                  \\\n        int sdim = 0;                                                                                             \\\n        if (V.data == nullptr) V.stride = A.rows;                                                                 \\\n        auto _WR = Impl::alloc<T>(A.rows), _WI = Impl::alloc<T>(A.rows);                                          \\\n        if (F(Impl::lpcvt(A.major), V.data == nullptr ? 'N' : 'V', 'N', nullptr, A.rows, A.data, A.stride, &sdim, \\\n              _WR.get(), _WI.get(), V.data, V.stride) != 0)                                                       \\\n            return false;                                                                                         \\\n                                                                                                                  \\\n        auto WR = _WR.get(), WI = _WI.get();                                                                      \\\n        for (Size i = 0; i < A.rows; ++i) E.data[i].real(WR[i]), E.data[i].imag(WI[i]);                           \\\n        return true;                                                                                              \\\n    }\n\n#define GEESC(F, T, R)                                                                                               \\\n    inline bool schur(General<T> A, Vector<T> E, General<T> V)                                                       \\\n    {                                                                                                                \\\n        CHECK(A.major == V.major) CHECK(A.state == State::None) CHECK(V.state == State::None);                       \\\n        CHECK(A.rows == A.cols) CHECK(A.rows == E.size) CHECK(E.stride == 1) CHECK(V.rows == V.cols);                \\\n                                                                                                                     \\\n        int sdim = 0;                                                                                                \\\n        if (V.data == nullptr) V.stride = A.rows;                                                                    \\\n        return F(Impl::lpcvt(A.major), V.data == nullptr ? 'N' : 'V', 'N', nullptr, A.rows, A.data, A.stride, &sdim, \\\n                 E.data, V.data, V.stride) == 0;                                                                     \\\n    }\n\nREPEAT0(GEES, sgees, dgees)\nREPEAT1(GEESC, cgees, zgees)\n\n#define GESV(F, T, R)                                                                                     \\\n    inline bool solve(General<T> A, General<T> B)                                                         \\\n    {                                                                                                     \\\n        CHECK(A.major == B.major) CHECK(A.state == State::None) CHECK(B.state == State::None);            \\\n        CHECK(A.rows == A.cols) CHECK(A.rows == B.rows);                                                  \\\n        auto P = Impl::alloc<int>(A.rows);                                                                \\\n        return F(Impl::lpcvt(A.major), A.rows, B.cols, A.data, A.stride, P.get(), B.data, B.stride) == 0; \\\n    }\n\nREPEAT(GESV, sgesv, dgesv, cgesv, zgesv)\n\n#define SYSV(F, T, R)                                                                                         \\\n    inline bool solve(Symmetric<T> A, General<T> B)                                                           \\\n    {                                                                                                         \\\n        CHECK(A.major == B.major) CHECK(B.state == State::None) CHECK(A.size == B.rows);                      \\\n        auto P = Impl::alloc<int>(A.size);                                                                    \\\n        return F(Impl::lpcvt(A.major), Impl::lpcvt(A.tri), A.size, B.cols, A.data, A.stride, P.get(), B.data, \\\n                 B.stride) == 0;                                                                              \\\n    }\n\nREPEAT(SYSV, ssysv, dsysv, csysv, zsysv)\n\n#define HESV(F, T, R)                                                                                         \\\n    inline bool solve(Hermitian<T> A, General<T> B)                                                           \\\n    {                                                                                                         \\\n        CHECK(A.major == B.major) CHECK(B.state == State::None) CHECK(A.size == B.rows);                      \\\n        auto P = Impl::alloc<int>(A.size);                                                                    \\\n        return F(Impl::lpcvt(A.major), Impl::lpcvt(A.tri), A.size, B.cols, A.data, A.stride, P.get(), B.data, \\\n                 B.stride) == 0;                                                                              \\\n    }\n\nREPEAT1(HESV, chesv, zhesv)\n\n#define GELS(F, T, R)                                                                                                \\\n    inline bool lsquares(General<T> A, General<T> B)                                                                 \\\n    {                                                                                                                \\\n        CHECK(A.major == B.major) CHECK(B.state == State::None) CHECK(A._rows() == B.rows);                          \\\n        return F(Impl::lpcvt(A.major), Impl::lpcvt(A.state), A._rows(), A._cols(), B.cols, A.data, A.stride, B.data, \\\n                 B.stride) == 0;                                                                                     \\\n    }\n\nREPEAT(GELS, sgels, dgels, cgels, zgels)\n\n#define GESVD(F, T, R)                                                                                                \\\n    inline bool svd(General<T> A, Vector<From<T>::Type> S, General<T> U, General<T> VT)                               \\\n    {                                                                                                                 \\\n        CHECK(A.major == U.major) CHECK(A.major == VT.major);                                                         \\\n        CHECK(A.state == State::None) CHECK(U.state == State::None) CHECK(VT.state == State::None);                   \\\n        CHECK(std::min(A.rows, A.cols) == S.size) CHECK(S.stride == 1);                                               \\\n                                                                                                                      \\\n        if (U.data != nullptr) CHECK(A.rows == U.rows) CHECK(U.rows == U.cols);                                       \\\n        if (VT.data != nullptr) CHECK(A.cols == VT.rows) CHECK(VT.rows == VT.cols);                                   \\\n                                                                                                                      \\\n        if (U.data == nullptr) U.stride = A.rows;                                                                     \\\n        if (VT.data == nullptr) VT.stride = A.cols;                                                                   \\\n        auto SB = Impl::alloc<From<T>::Type>(std::min(A.rows, A.cols));                                               \\\n        return F(Impl::lpcvt(A.major), U.data == nullptr ? 'N' : 'A', VT.data == nullptr ? 'N' : 'A', A.rows, A.cols, \\\n                 A.data, A.stride, S.data, U.data, U.stride, VT.data, VT.stride, SB.get()) == 0;                      \\\n    }\n\nREPEAT(GESVD, sgesvd, dgesvd, cgesvd, zgesvd)\n\n#define GERK(F, T, R)                                                                              \\\n    inline Size rank(General<T> A, From<T>::Type epsilon)                                          \\\n    {                                                                                              \\\n        CHECK(A.state == State::None);                                                             \\\n        auto SB = Impl::alloc<From<T>::Type>(std::min(A.rows, A.cols));                            \\\n        auto _S = Impl::alloc<From<T>::Type>(std::min(A.rows, A.cols));                            \\\n        if (F(Impl::lpcvt(A.major), 'N', 'N', A.rows, A.cols, A.data, A.stride, _S.get(), nullptr, \\\n              std::max(A.rows, A.cols), nullptr, std::max(A.rows, A.cols), SB.get()) != 0)         \\\n            return 0;                                                                              \\\n                                                                                                   \\\n        Size rank = 0;                                                                             \\\n        auto S = _S.get();                                                                         \\\n        for (Size i = 0; i < std::min(A.rows, A.cols); ++i)                                        \\\n            if (std::abs(S[i]) >= std::abs(epsilon)) ++rank;                                       \\\n        return rank;                                                                               \\\n    }\n\nREPEAT(GERK, sgesvd, dgesvd, cgesvd, zgesvd)\n\n#undef GETRI\n#undef SYTRI\n#undef GEDTR\n#undef SYDTR\n#undef HEDTR\n#undef GETRF\n#undef SYTRF\n#undef HETRF\n#undef POTRF\n#undef GEQRF\n#undef GEEV\n#undef GEEVC\n#undef SYEV\n#undef HEEV\n#undef GEES\n#undef GEESC\n#undef GESV\n#undef SYSV\n#undef HESV\n#undef GELS\n#undef GESVD\n#undef GERK\n\n#endif\n}  // namespace Blasw\n\n#undef CHECK\n#undef REPEAT0\n#undef REPEAT1\n#undef REPEAT\n#undef STATE\n#undef GENERAL\n#undef BGENERAL\n#undef TRIANGLE\n#undef BTRIANGLE\n#undef PTRIANGLE\n#undef SYMMETRIC\n#undef BSYMMETRIC\n#undef PSYMMETRIC\n#undef HERMITIAN\n#undef BHERMITIAN\n#undef PHERMITIAN\n#undef POSDEF\n#undef ROTG\n#undef ROTMG\n#undef ROT\n#undef ROTM\n#undef SWAP\n#undef SCAL\n#undef SSCAL\n#undef COPY\n#undef AXPY\n#undef DOT\n#undef DOTU\n#undef NRM2\n#undef ASUM\n#undef IAMAX\n#undef GEMV\n#undef GBMV\n#undef SYMV\n#undef HEMV\n#undef SBMV\n#undef HBMV\n#undef SPMV\n#undef HPMV\n#undef TRMV\n#undef TBMV\n#undef TPMV\n#undef TRSV\n#undef TBSV\n#undef TPSV\n#undef GER\n#undef GERU\n#undef SYR\n#undef HER\n#undef SPR\n#undef HPR\n#undef SYR2\n#undef HER2\n#undef SPR2\n#undef HPR2\n#undef GEMM\n#undef SYMM\n#undef HEMM\n#undef TRMM\n#undef TRSM\n#undef SYRK\n#undef HERK\n#undef SYR2K\n#undef HER2K\n", "meta": {"hexsha": "e1e5027c51786dded286ceff030f471f7a545c3e", "size": 77638, "ext": "h", "lang": "C", "max_stars_repo_path": "src/blasw/blasw.h", "max_stars_repo_name": "Mathific/Blasw", "max_stars_repo_head_hexsha": "4295cfe1a2712dbe87fd251bfbb49ca22f13fe98", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-09T17:22:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-09T17:22:50.000Z", "max_issues_repo_path": "src/blasw/blasw.h", "max_issues_repo_name": "Mathific/Blasw", "max_issues_repo_head_hexsha": "4295cfe1a2712dbe87fd251bfbb49ca22f13fe98", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/blasw/blasw.h", "max_forks_repo_name": "Mathific/Blasw", "max_forks_repo_head_hexsha": "4295cfe1a2712dbe87fd251bfbb49ca22f13fe98", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.0676691729, "max_line_length": 120, "alphanum_fraction": 0.3453592313, "num_tokens": 15410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046493573919, "lm_q2_score": 0.0656048392859768, "lm_q1q2_score": 0.027718349618669674}}
{"text": "/**\n * @file matrix.i\n * @brief Wrapper for GSL matrix objects.\n * @author John McDonough, Kenichi Kumatani\n */\n\n#ifndef GSLMATRIX_H\n#define GSLMATRIX_H\n\n#include <gsl/gsl_matrix.h>\n\n#define GSL_MATRIX_NROWS(x) ((x)->size2)\n#define GSL_MATRIX_NCOLS(x) ((x)->size2)\n\ngsl_matrix_float* gsl_matrix_float_resize(gsl_matrix_float* m, size_t size1, size_t size2);\n\nvoid gsl_matrix_float_set_cosine(gsl_matrix_float* m, size_t i, size_t j, int type);\n\ngsl_matrix_float* gsl_matrix_float_load(gsl_matrix_float* m, const char* filename, bool old = false);\n\ngsl_vector_float* gsl_vector_float_load(gsl_vector_float* m, const char* filename, bool old = false);\n\n#endif\n", "meta": {"hexsha": "1fafaf1d67dc9a5867daff2a853536be54a8634f", "size": 658, "ext": "h", "lang": "C", "max_stars_repo_path": "btk20_src/matrix/gslmatrix.h", "max_stars_repo_name": "musiclvme/distant_speech_recognition", "max_stars_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 136.0, "max_stars_repo_stars_event_min_datetime": "2018-12-06T06:35:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T15:07:42.000Z", "max_issues_repo_path": "btk20_src/matrix/gslmatrix.h", "max_issues_repo_name": "musiclvme/distant_speech_recognition", "max_issues_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2018-12-03T04:33:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-28T22:01:37.000Z", "max_forks_repo_path": "btk20_src/matrix/gslmatrix.h", "max_forks_repo_name": "musiclvme/distant_speech_recognition", "max_forks_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 68.0, "max_forks_repo_forks_event_min_datetime": "2019-01-08T06:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-17T09:33:10.000Z", "avg_line_length": 27.4166666667, "max_line_length": 101, "alphanum_fraction": 0.7705167173, "num_tokens": 181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.05582314506158596, "lm_q1q2_score": 0.02747548969793353}}
{"text": "/* err/test_results.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#include <config.h>\n#include <math.h>\n#include <string.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n#ifdef HAVE_VPRINTF\n#ifdef STDC_HEADERS\n#include <stdarg.h>\n#else\n#include <varargs.h>\n#endif\n#endif\n\n#include <gsl/gsl_test.h>\n\nstatic unsigned int tests = 0;\nstatic unsigned int passed = 0;\nstatic unsigned int failed = 0;\n\nstatic unsigned int verbose = 1;\n\nvoid\ngsl_test (int status, const char *test_description,...)\n{\n\n  tests++;\n\n  if (status == 0)\n    {\n      passed++;\n      if (verbose)\n\tprintf (\"PASS: \");\n    }\n  else\n    {\n      failed++;\n      if (verbose)\n\tprintf (\"FAIL: \");\n    }\n\n  if (verbose)\n    {\n\n#ifdef HAVE_VPRINTF\n      va_list ap;\n\n#ifdef STDC_HEADERS\n      va_start (ap, test_description);\n#else\n      va_start (ap);\n#endif\n      vprintf (test_description, ap);\n      va_end (ap);\n#endif\n\n      printf(\"\\n\");\n      fflush (stdout);\n    }\n}\n\n\nvoid\ngsl_test_rel (double result, double expected, double relative_error,\n\t      const char *test_description,...)\n{\n  int status ;\n\n  if (expected != 0 ) \n    {\n      status = (fabs(result-expected)/fabs(expected) > relative_error) ;\n    }\n  else\n    {\n      status = (fabs(result) > relative_error) ;\n    }\n\n  tests++;\n\n  if (status == 0)\n    {\n      passed++;\n      if (verbose)\n\tprintf (\"PASS: \");\n    }\n  else\n    {\n      failed++;\n      if (verbose)\n\tprintf (\"FAIL: \");\n      \n    }\n\n  if (verbose)\n    {\n\n#ifdef HAVE_VPRINTF\n      va_list ap;\n\n#ifdef STDC_HEADERS\n      va_start (ap, test_description);\n#else\n      va_start (ap);\n#endif\n      vprintf (test_description, ap);\n      va_end (ap);\n#endif\n      if (status == 0)\n\t{\n\t  if (strlen(test_description) < 45)\n\t    {\n\t      printf(\" (%g observed vs %g expected)\", result, expected) ;\n\t    }\n\t  else\n\t    {\n\t      printf(\" (%g obs vs %g exp)\", result, expected) ;\n\t    }\n\t}\n      else \n\t{\n\t  printf(\" (%.18g observed vs %.18g expected)\", result, expected) ;\n\t}\n\n      printf (\"\\n\") ;\n      fflush (stdout);\n    }\n}\n\nvoid\ngsl_test_abs (double result, double expected, double absolute_error,\n\t      const char *test_description,...)\n{\n  int status ;\n\n  status = fabs(result-expected) > absolute_error ;\n\n  tests++;\n\n  if (status == 0)\n    {\n      passed++;\n      if (verbose)\n\tprintf (\"PASS: \");\n    }\n  else\n    {\n      failed++;\n      if (verbose)\n\tprintf (\"FAIL: \");\n      \n    }\n\n  if (verbose)\n    {\n\n#ifdef HAVE_VPRINTF\n      va_list ap;\n\n#ifdef STDC_HEADERS\n      va_start (ap, test_description);\n#else\n      va_start (ap);\n#endif\n      vprintf (test_description, ap);\n      va_end (ap);\n#endif\n      if (status == 0)\n\t{\n\t  if (strlen(test_description) < 45)\n\t    {\n\t      printf(\" (%g observed vs %g expected)\", result, expected) ;\n\t    }\n\t  else\n\t    {\n\t      printf(\" (%g obs vs %g exp)\", result, expected) ;\n\t    }\n\t}\n      else \n\t{\n\t  printf(\" (%.18g observed vs %.18g expected)\", result, expected) ;\n\t}\n\n      printf (\"\\n\") ;\n      fflush (stdout);\n    }\n}\n\n\nvoid\ngsl_test_factor (double result, double expected, double factor,\n                 const char *test_description,...)\n{\n  int status;\n  \n  if (result == expected) \n    {\n      status = 0;\n    }\n  else if (expected == 0.0) \n    {\n      status = (result > expected || result < expected);\n    }\n  else\n    {\n      double u = result / expected; \n      status = (u > factor || u < 1.0 / factor) ;\n    }\n\n  tests++;\n\n  if (status == 0)\n    {\n      passed++;\n      if (verbose)\n\tprintf (\"PASS: \");\n    }\n  else\n    {\n      failed++;\n      if (verbose)\n\tprintf (\"FAIL: \");\n      \n    }\n\n  if (verbose)\n    {\n\n#ifdef HAVE_VPRINTF\n      va_list ap;\n\n#ifdef STDC_HEADERS\n      va_start (ap, test_description);\n#else\n      va_start (ap);\n#endif\n      vprintf (test_description, ap);\n      va_end (ap);\n#endif\n      if (status == 0)\n\t{\n\t  if (strlen(test_description) < 45)\n\t    {\n\t      printf(\" (%g observed vs %g expected)\", result, expected) ;\n\t    }\n\t  else\n\t    {\n\t      printf(\" (%g obs vs %g exp)\", result, expected) ;\n\t    }\n\t}\n      else \n\t{\n\t  printf(\" (%.18g observed vs %.18g expected)\", result, expected) ;\n\t}\n\n      printf (\"\\n\") ;\n      fflush (stdout);\n    }\n}\n\nvoid\ngsl_test_int (int result, int expected, const char *test_description,...)\n{\n  int status = (result != expected) ;\n\n  tests++;\n\n  if (status == 0)\n    {\n      passed++;\n      if (verbose)\n\tprintf (\"PASS: \");\n    }\n  else\n    {\n      failed++;\n      if (verbose)\n\tprintf (\"FAIL: \");\n    }\n\n  if (verbose)\n    {\n\n#ifdef HAVE_VPRINTF\n      va_list ap;\n\n#ifdef STDC_HEADERS\n      va_start (ap, test_description);\n#else\n      va_start (ap);\n#endif\n      vprintf (test_description, ap);\n      va_end (ap);\n#endif\n      if (status == 0)\n\t{\n\t  printf(\" (%d observed vs %d expected)\", result, expected) ;\n\t}\n      else \n\t{\n\t  printf(\" (%d observed vs %d expected)\", result, expected) ;\n\t}\n\n      printf (\"\\n\");\n      fflush (stdout);\n    }\n}\n\nvoid\ngsl_test_str (const char * result, const char * expected, \n\t      const char *test_description,...)\n{\n  int status = strcmp(result,expected) ;\n\n  tests++;\n\n  if (status == 0)\n    {\n      passed++;\n      if (verbose)\n\tprintf (\"PASS: \");\n    }\n  else\n    {\n      failed++;\n      if (verbose)\n\tprintf (\"FAIL: \");\n    }\n\n  if (verbose)\n    {\n\n#ifdef HAVE_VPRINTF\n      va_list ap;\n\n#ifdef STDC_HEADERS\n      va_start (ap, test_description);\n#else\n      va_start (ap);\n#endif\n      vprintf (test_description, ap);\n      va_end (ap);\n#endif\n      if (status)\n\t{\n\t  printf(\" (%s observed vs %s expected)\", result, expected) ;\n\t}\n\n      printf (\"\\n\");\n      fflush (stdout);\n    }\n}\n\n\n\n\nvoid\ngsl_test_verbose (int v)\n{\n  verbose = v;\n}\n\nint\ngsl_test_summary (void)\n{\n\n  if (verbose && 0)\t\t/* FIXME: turned it off, this annoys me */\n    printf (\"%d tests, passed %d, failed %d.\\n\", tests, passed, failed);\n\n  if (failed != 0)\n    {\n\n      if (verbose && 0)\t\t/* FIXME: turned it off, this annoys me */\n\t{\n\t  printf (\"%d TEST%s FAILED.\\n\", failed, failed == 1 ? \"\" : \"S\");\n\t}\n      return EXIT_FAILURE;\n    }\n\n  if (tests != passed + failed)\n    {\n      if (verbose)\n\tprintf (\"TEST RESULTS DO NOT ADD UP %d != %d + %d\\n\",\n\t\ttests, passed, failed);\n      return EXIT_FAILURE;\n    }\n\n  if (passed == tests)\n    {\n      if (verbose && 0)\t\t/* FIXME: turned it off, this annoys me */\n\tprintf (\"All tests passed successfully\\n\");\n      return EXIT_SUCCESS;\n    }\n\n  return EXIT_FAILURE;\n}\n", "meta": {"hexsha": "3d4c1293673140a8dd50e6675b2b464615995260", "size": 7088, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/test/results.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/test/results.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/test/results.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 17.0795180723, "max_line_length": 73, "alphanum_fraction": 0.5664503386, "num_tokens": 1918, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38491215859561856, "lm_q2_score": 0.0705595986303734, "lm_q1q2_score": 0.027159247418457474}}
{"text": "/* Copyright (C) 2010-2021 Barcelona Supercomputing Center and University of\n * Illinois at Urbana-Champaign\n * SPDX-License-Identifier: MIT\n */\n\n/** \\file\n * \\brief Wrapper routines for GSL random number functions.\n */\n\n/* clang-format off */\n\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_randist.h>\n#include <gsl/gsl_rng.h>\n#include <stdio.h>\n#include <time.h>\n\n/** \\brief Private internal-use variable to store the random number\n * generator.\n */\nstatic gsl_rng *camp_rand_gsl_rng = NULL;\n\n/** \\brief Result code indicating successful completion.\n */\n#define CAMP_RAND_GSL_SUCCESS      0\n/** \\brief Result code indicating initialization failure.\n */\n#define CAMP_RAND_GSL_INIT_FAIL    1\n/** \\brief Result code indicating the generator was not initialized\n * when it should have been.\n */\n#define CAMP_RAND_GSL_NOT_INIT     2\n/** \\brief Result code indicating the generator was already\n * initialized when an initialization was attempted.\n */\n#define CAMP_RAND_GSL_ALREADY_INIT 3\n\n/** \\brief Initialize the random number generator with the given seed.\n *\n * This must be called before any other GSL random number functions\n * are called.\n *\n * \\param seed The random seed to use.\n * \\return CAMP_RAND_GSL_SUCCESS on success, otherwise an error code.\n * \\sa camp_rand_finalize_gsl() to cleanup the generator.\n */\nint camp_srand_gsl(int seed)\n{\n        if (camp_rand_gsl_rng) {\n                return CAMP_RAND_GSL_ALREADY_INIT;\n        }\n        gsl_set_error_handler_off(); // turn off automatic error handling\n        camp_rand_gsl_rng = gsl_rng_alloc(gsl_rng_mt19937);\n        if (camp_rand_gsl_rng == NULL) {\n                return CAMP_RAND_GSL_INIT_FAIL;\n        }\n        gsl_rng_set(camp_rand_gsl_rng, seed);\n        return CAMP_RAND_GSL_SUCCESS;\n}\n\n/** \\brief Cleanup and deallocate the random number generator.\n *\n * This must be called after camp_srand_gsl().\n *\n * \\return CAMP_RAND_GSL_SUCCESS on success, otherwise an error code.\n */\nint camp_rand_finalize_gsl()\n{\n        if (!camp_rand_gsl_rng) {\n                return CAMP_RAND_GSL_NOT_INIT;\n        }\n        gsl_rng_free(camp_rand_gsl_rng);\n        camp_rand_gsl_rng = NULL;\n        return CAMP_RAND_GSL_SUCCESS;\n}\n\n/** \\brief Generate a uniform random number in \\f$[0,1)\\f$.\n *\n * \\param harvest A pointer to the generated random number.\n * \\return CAMP_RAND_GSL_SUCCESS on success, otherwise an error code.\n */\nint camp_rand_gsl(double *harvest)\n{\n        if (!camp_rand_gsl_rng) {\n                return CAMP_RAND_GSL_NOT_INIT;\n        }\n        *harvest = gsl_rng_uniform(camp_rand_gsl_rng);\n        return CAMP_RAND_GSL_SUCCESS;\n}\n\n/** \\brief Generate a uniform random integer in \\f$[1,n]\\f$.\n *\n * \\param n The upper limit of the random integer.\n * \\param harvest A pointer to the generated random number.\n * \\return CAMP_RAND_GSL_SUCCESS on success, otherwise an error code.\n */\nint camp_rand_int_gsl(int n, int *harvest)\n{\n        if (!camp_rand_gsl_rng) {\n                return CAMP_RAND_GSL_NOT_INIT;\n        }\n        *harvest = gsl_rng_uniform_int(camp_rand_gsl_rng, n) + 1;\n        return CAMP_RAND_GSL_SUCCESS;\n}\n\n/** \\brief Generate a normally-distributed random number.\n *\n * \\param mean The mean of the distribution.\n * \\param stddev The standard deviation of the distribution.\n * \\param harvest A pointer to the generated random number.\n * \\return CAMP_RAND_GSL_SUCCESS on success, otherwise an error code.\n */\nint camp_rand_normal_gsl(double mean, double stddev, double *harvest)\n{\n        if (!camp_rand_gsl_rng) {\n                return CAMP_RAND_GSL_NOT_INIT;\n        }\n        *harvest = gsl_ran_gaussian(camp_rand_gsl_rng, stddev) + mean;\n        return CAMP_RAND_GSL_SUCCESS;\n}\n\n/** \\brief Generate a Poisson-distributed random integer.\n *\n * \\param mean The mean of the distribution.\n * \\param harvest A pointer to the generated random number.\n * \\return CAMP_RAND_GSL_SUCCESS on success, otherwise an error code.\n */\nint camp_rand_poisson_gsl(double mean, int *harvest)\n{\n        if (!camp_rand_gsl_rng) {\n                return CAMP_RAND_GSL_NOT_INIT;\n        }\n        *harvest = gsl_ran_poisson(camp_rand_gsl_rng, mean);\n        return CAMP_RAND_GSL_SUCCESS;\n}\n\n/** \\brief Generate a Binomial-distributed random integer.\n *\n * \\param n The sample size for the distribution.\n * \\param p The sample probability for the distribution.\n * \\param harvest A pointer to the generated random number.\n * \\return CAMP_RAND_GSL_SUCCESS on success, otherwise an error code.\n */\nint camp_rand_binomial_gsl(int n, double p, int *harvest)\n{\n        unsigned int u;\n\n        if (!camp_rand_gsl_rng) {\n                return CAMP_RAND_GSL_NOT_INIT;\n        }\n        u = n;\n        *harvest = gsl_ran_binomial(camp_rand_gsl_rng, p, u);\n        return CAMP_RAND_GSL_SUCCESS;\n}\n\n/* clang-format on */\n", "meta": {"hexsha": "72fbff71413533f863891d19914b6865dbd13edd", "size": 4783, "ext": "c", "lang": "C", "max_stars_repo_path": "src/rand_gsl.c", "max_stars_repo_name": "open-atmos/camp", "max_stars_repo_head_hexsha": "4c77145ac43ae3dcfce71f49a9709bb62f80b8c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-08-05T21:35:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T05:32:29.000Z", "max_issues_repo_path": "src/rand_gsl.c", "max_issues_repo_name": "open-atmos/camp", "max_issues_repo_head_hexsha": "4c77145ac43ae3dcfce71f49a9709bb62f80b8c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2021-10-06T18:14:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-22T11:42:07.000Z", "max_forks_repo_path": "src/rand_gsl.c", "max_forks_repo_name": "open-atmos/camp", "max_forks_repo_head_hexsha": "4c77145ac43ae3dcfce71f49a9709bb62f80b8c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4649681529, "max_line_length": 76, "alphanum_fraction": 0.697470207, "num_tokens": 1193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926344647597, "lm_q2_score": 0.06008665269869255, "lm_q1q2_score": 0.02700249915243451}}
{"text": "/* Useful general-purpose functions.\n *\n * Krzysztof Chalupka, 2017.\n */\n\n#include <stdio.h>\n#include <gsl/gsl_blas.h>\n#include \"utils.h\"\n\nvoid crit_err(char *msg){\n  fprintf(stderr, \"%s, exiting.\\n\", msg);\n  exit(1);\n}\n\nint get_nlines(char *fname){\n  /* Check how many lines there are in a file. */\n  int nlines = 0;\n  FILE *f = fopen(fname, \"r\");\n  while(!feof(f))\n    if (fgetc(f) == '\\n')\n      nlines++;\n  fclose(f);\n  printf(\"%d lines read from %s.\\n\\n\", nlines, fname);\n  return nlines;\n}\n\nvoid print_intarray(int *arr, int n){\n  int i;\n  printf(\"[\");\n  for(i = 0; i < n; i++)\n    printf(\"%d \", arr[i]);\n  printf(\"]\");\n}\n\nvoid print_gsl_vector(gsl_vector *vec){\n  int i;\n  for (i = 0; i < vec->size; i++)\n    printf(\"%.4f \", vec->data[i]);\n}\n\ngsl_vector *vector_sub(gsl_vector *v1, gsl_vector *v2){\n  /* Create a new vector equal to v1 - v2. */\n  gsl_vector *res = gsl_vector_calloc(v1->size);\n  gsl_vector_add(res, v1);\n  gsl_vector_sub(res, v2);\n  return res;\n}\n\ndouble vector_dist(gsl_vector *v1, gsl_vector *v2){\n  /* Compute the Euclidean distance between vectors. */\n  double dist;\n  gsl_vector *tmp =  vector_sub(v1, v2);\n  dist = gsl_blas_dnrm2(tmp);\n  free(tmp);\n  return dist;\n}\n\ngsl_vector **load_vectors_from_file(char *fname, int nvecs)\n{\n  int vec_id;\n  FILE *f;\n  gsl_vector **vecs;\n  double vals[2] = {0., 0.};\n  \n  /* Allocate the vector array. */\n  vecs = (gsl_vector **) calloc(nvecs, sizeof(gsl_vector *));\n      \n  /* Load the vectors from a file into an array. */\n  f = fopen(fname, \"r\");\n  vec_id = 0;\n  while(fscanf(f,\"%lf %lf\", &vals[0], &vals[1]) != EOF){\n    vecs[vec_id] = gsl_vector_alloc(2);\n    gsl_vector_set(vecs[vec_id], 0, vals[0]);\n    gsl_vector_set(vecs[vec_id], 1, vals[1]);\n    vec_id++;\n  }\n\n  /* Clean up. */\n  fclose(f);\n  printf(\"Data: \\n\");\n  for (vec_id = 0; vec_id < nvecs; vec_id++)\n    printf(\"[%f, %f]\\n\", \n\t   vecs[vec_id]->data[0], \n\t   vecs[vec_id]->data[1]);\n  printf(\"\\n\");\n  return vecs;\n}\n", "meta": {"hexsha": "bb945d4f6eb92ecf4f1551ee80e85031105b5479", "size": 1953, "ext": "c", "lang": "C", "max_stars_repo_path": "skiena/utils/utils.c", "max_stars_repo_name": "kjchalup/algorithm_design", "max_stars_repo_head_hexsha": "99176322b83d120f0ceb83dbba254a6e15f95264", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "skiena/utils/utils.c", "max_issues_repo_name": "kjchalup/algorithm_design", "max_issues_repo_head_hexsha": "99176322b83d120f0ceb83dbba254a6e15f95264", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "skiena/utils/utils.c", "max_forks_repo_name": "kjchalup/algorithm_design", "max_forks_repo_head_hexsha": "99176322b83d120f0ceb83dbba254a6e15f95264", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.1931818182, "max_line_length": 61, "alphanum_fraction": 0.6036866359, "num_tokens": 646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.05665242132616554, "lm_q1q2_score": 0.026999391187536328}}
{"text": "/* ode-initval2/driver.c\n * \n * Copyright (C) 2009, 2010 Tuomo Keskitalo\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Driver routine for odeiv2. This is a wrapper for low level GSL\n   functions that allows a simple interface to step, control and\n   evolve layers.\n */\n\n#include <config.h>\n#include <math.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_odeiv2.h>\n#include <gsl/gsl_machine.h>\n\nstatic gsl_odeiv2_driver *\ndriver_alloc (const gsl_odeiv2_system * sys, const double hstart,\n              const gsl_odeiv2_step_type * T)\n{\n  /* Allocates and initializes an ODE driver system. Step and evolve\n     objects are allocated here, but control object is allocated in\n     another function.\n   */\n\n  gsl_odeiv2_driver *state =\n    (gsl_odeiv2_driver *) malloc (sizeof (gsl_odeiv2_driver));\n\n  if (state == NULL)\n    {\n      GSL_ERROR_NULL (\"failed to allocate space for driver state\",\n                      GSL_ENOMEM);\n    }\n\n  if (sys == NULL)\n    {\n      GSL_ERROR_NULL (\"gsl_odeiv2_system must be defined\", GSL_EINVAL);\n    }\n\n  {\n    const size_t dim = sys->dimension;\n\n    if (dim == 0)\n      {\n        GSL_ERROR_NULL\n          (\"gsl_odeiv2_system dimension must be a positive integer\",\n           GSL_EINVAL);\n      }\n\n    state->sys = sys;\n\n    state->s = gsl_odeiv2_step_alloc (T, dim);\n\n    if (state->s == NULL)\n      {\n        free (state);\n        GSL_ERROR_NULL (\"failed to allocate step object\", GSL_ENOMEM);\n      }\n\n    state->e = gsl_odeiv2_evolve_alloc (dim);\n  }\n\n  if (state->e == NULL)\n    {\n      gsl_odeiv2_step_free (state->s);\n      free (state);\n      GSL_ERROR_NULL (\"failed to allocate evolve object\", GSL_ENOMEM);\n    }\n\n  if (hstart > 0.0 || hstart < 0.0)\n    {\n      state->h = hstart;\n    }\n  else\n    {\n      GSL_ERROR_NULL (\"invalid hstart\", GSL_EINVAL);\n    }\n\n  state->h = hstart;\n  state->hmin = 0.0;\n  state->hmax = GSL_DBL_MAX;\n  state->nmax = 0;\n  state->n = 0;\n  state->c = NULL;\n\n  return state;\n}\n\nint\ngsl_odeiv2_driver_set_hmin (gsl_odeiv2_driver * d, const double hmin)\n{\n  /* Sets minimum allowed step size fabs(hmin) for driver. It is\n     required that hmin <= fabs(h) <= hmax. */\n\n  if ((fabs (hmin) > fabs (d->h)) || (fabs (hmin) > d->hmax))\n    {\n      GSL_ERROR_NULL (\"hmin <= fabs(h) <= hmax required\", GSL_EINVAL);\n    }\n\n  d->hmin = fabs (hmin);\n\n  return GSL_SUCCESS;\n}\n\nint\ngsl_odeiv2_driver_set_hmax (gsl_odeiv2_driver * d, const double hmax)\n{\n  /* Sets maximum allowed step size fabs(hmax) for driver. It is\n     required that hmin <= fabs(h) <= hmax. */\n\n  if ((fabs (hmax) < fabs (d->h)) || (fabs (hmax) < d->hmin))\n    {\n      GSL_ERROR_NULL (\"hmin <= fabs(h) <= hmax required\", GSL_EINVAL);\n    }\n\n  if (hmax > 0.0 || hmax < 0.0)\n    {\n      d->hmax = fabs (hmax);\n    }\n  else\n    {\n      GSL_ERROR_NULL (\"invalid hmax\", GSL_EINVAL);\n    }\n\n  return GSL_SUCCESS;\n}\n\nint\ngsl_odeiv2_driver_set_nmax (gsl_odeiv2_driver * d,\n                            const unsigned long int nmax)\n{\n  /* Sets maximum number of allowed steps (nmax) for driver */\n\n  d->nmax = nmax;\n\n  return GSL_SUCCESS;\n}\n\ngsl_odeiv2_driver *\ngsl_odeiv2_driver_alloc_y_new (const gsl_odeiv2_system * sys,\n                               const gsl_odeiv2_step_type * T,\n                               const double hstart,\n                               const double epsabs, const double epsrel)\n{\n  /* Initializes an ODE driver system with control object of type y_new. */\n\n  gsl_odeiv2_driver *state = driver_alloc (sys, hstart, T);\n\n  if (state == NULL)\n    {\n      GSL_ERROR_NULL (\"failed to allocate driver object\", GSL_ENOMEM);\n    }\n\n  if (epsabs >= 0.0 && epsrel >= 0.0)\n    {\n      state->c = gsl_odeiv2_control_y_new (epsabs, epsrel);\n\n      if (state->c == NULL)\n        {\n          gsl_odeiv2_driver_free (state);\n          GSL_ERROR_NULL (\"failed to allocate control object\", GSL_ENOMEM);\n        }\n    }\n  else\n    {\n      gsl_odeiv2_driver_free (state);\n      GSL_ERROR_NULL (\"epsabs and epsrel must be positive\", GSL_EINVAL);\n    }\n\n  /* Distribute pointer to driver object */\n\n  gsl_odeiv2_step_set_driver (state->s, state);\n  gsl_odeiv2_evolve_set_driver (state->e, state);\n  gsl_odeiv2_control_set_driver (state->c, state);\n\n  return state;\n}\n\ngsl_odeiv2_driver *\ngsl_odeiv2_driver_alloc_yp_new (const gsl_odeiv2_system * sys,\n                                const gsl_odeiv2_step_type * T,\n                                const double hstart,\n                                const double epsabs, const double epsrel)\n{\n  /* Initializes an ODE driver system with control object of type yp_new. */\n\n  gsl_odeiv2_driver *state = driver_alloc (sys, hstart, T);\n\n  if (state == NULL)\n    {\n      GSL_ERROR_NULL (\"failed to allocate driver object\", GSL_ENOMEM);\n    }\n\n  if (epsabs >= 0.0 && epsrel >= 0.0)\n    {\n      state->c = gsl_odeiv2_control_yp_new (epsabs, epsrel);\n\n      if (state->c == NULL)\n        {\n          gsl_odeiv2_driver_free (state);\n          GSL_ERROR_NULL (\"failed to allocate control object\", GSL_ENOMEM);\n        }\n    }\n  else\n    {\n      gsl_odeiv2_driver_free (state);\n      GSL_ERROR_NULL (\"epsabs and epsrel must be positive\", GSL_EINVAL);\n    }\n\n  /* Distribute pointer to driver object */\n\n  gsl_odeiv2_step_set_driver (state->s, state);\n  gsl_odeiv2_evolve_set_driver (state->e, state);\n  gsl_odeiv2_control_set_driver (state->c, state);\n\n  return state;\n}\n\ngsl_odeiv2_driver *\ngsl_odeiv2_driver_alloc_standard_new (const gsl_odeiv2_system * sys,\n                                      const gsl_odeiv2_step_type * T,\n                                      const double hstart,\n                                      const double epsabs,\n                                      const double epsrel, const double a_y,\n                                      const double a_dydt)\n{\n  /* Initializes an ODE driver system with control object of type\n     standard_new. \n   */\n\n  gsl_odeiv2_driver *state = driver_alloc (sys, hstart, T);\n\n  if (state == NULL)\n    {\n      GSL_ERROR_NULL (\"failed to allocate driver object\", GSL_ENOMEM);\n    }\n\n  if (epsabs >= 0.0 && epsrel >= 0.0)\n    {\n      state->c =\n        gsl_odeiv2_control_standard_new (epsabs, epsrel, a_y, a_dydt);\n\n      if (state->c == NULL)\n        {\n          gsl_odeiv2_driver_free (state);\n          GSL_ERROR_NULL (\"failed to allocate control object\", GSL_ENOMEM);\n        }\n    }\n  else\n    {\n      gsl_odeiv2_driver_free (state);\n      GSL_ERROR_NULL (\"epsabs and epsrel must be positive\", GSL_EINVAL);\n    }\n\n  /* Distribute pointer to driver object */\n\n  gsl_odeiv2_step_set_driver (state->s, state);\n  gsl_odeiv2_evolve_set_driver (state->e, state);\n  gsl_odeiv2_control_set_driver (state->c, state);\n\n  return state;\n}\n\ngsl_odeiv2_driver *\ngsl_odeiv2_driver_alloc_scaled_new (const gsl_odeiv2_system * sys,\n                                    const gsl_odeiv2_step_type * T,\n                                    const double hstart,\n                                    const double epsabs, const double epsrel,\n                                    const double a_y, const double a_dydt,\n                                    const double scale_abs[])\n{\n  /* Initializes an ODE driver system with control object of type\n     scaled_new. \n   */\n\n  gsl_odeiv2_driver *state = driver_alloc (sys, hstart, T);\n\n  if (state == NULL)\n    {\n      GSL_ERROR_NULL (\"failed to allocate driver object\", GSL_ENOMEM);\n    }\n\n  if (epsabs >= 0.0 && epsrel >= 0.0)\n    {\n      state->c = gsl_odeiv2_control_scaled_new (epsabs, epsrel, a_y, a_dydt,\n                                                scale_abs, sys->dimension);\n\n      if (state->c == NULL)\n        {\n          gsl_odeiv2_driver_free (state);\n          GSL_ERROR_NULL (\"failed to allocate control object\", GSL_ENOMEM);\n        }\n    }\n  else\n    {\n      gsl_odeiv2_driver_free (state);\n      GSL_ERROR_NULL (\"epsabs and epsrel must be positive\", GSL_EINVAL);\n    }\n\n  /* Distribute pointer to driver object */\n\n  gsl_odeiv2_step_set_driver (state->s, state);\n  gsl_odeiv2_evolve_set_driver (state->e, state);\n  gsl_odeiv2_control_set_driver (state->c, state);\n\n  return state;\n}\n\nint\ngsl_odeiv2_driver_apply (gsl_odeiv2_driver * d, double *t,\n                         const double t1, double y[])\n{\n  /* Main driver function that evolves the system from t to t1. In\n     beginning vector y contains the values of dependent variables at\n     t. This function returns values at t=t1 in y. In case of\n     unrecoverable error, y and t contains the values after the last\n     successful step.\n   */\n\n  int sign = 0;\n  d->n = 0;\n\n  /* Determine integration direction sign */\n\n  if (d->h > 0.0)\n    {\n      sign = 1;\n    }\n  else\n    {\n      sign = -1;\n    }\n\n  /* Check that t, t1 and step direction are sensible */\n\n  if (sign * (t1 - *t) < 0.0)\n    {\n      GSL_ERROR_NULL\n        (\"integration limits and/or step direction not consistent\",\n         GSL_EINVAL);\n    }\n\n  /* Evolution loop */\n\n  while (sign * (t1 - *t) > 0.0)\n    {\n      int s = gsl_odeiv2_evolve_apply (d->e, d->c, d->s, d->sys,\n                                       t, t1, &(d->h), y);\n\n      if (s != GSL_SUCCESS)\n        {\n          return s;\n        }\n\n      /* Check for maximum allowed steps */\n\n      if ((d->nmax > 0) && (d->n > d->nmax))\n        {\n          return GSL_EMAXITER;\n        }\n\n      /* Set step size if maximum size is exceeded */\n\n      if (fabs (d->h) > d->hmax)\n        {\n          d->h = sign * d->hmax;\n        }\n\n      /* Check for too small step size */\n\n      if (fabs (d->h) < d->hmin)\n        {\n          return GSL_ENOPROG;\n        }\n\n      d->n++;\n    }\n\n  return GSL_SUCCESS;\n}\n\nint\ngsl_odeiv2_driver_apply_fixed_step (gsl_odeiv2_driver * d, double *t,\n                                    const double h, const unsigned long int n,\n                                    double y[])\n{\n  /* Alternative driver function that evolves the system from t using\n   * n steps of size h. In the beginning vector y contains the values\n   * of dependent variables at t. This function returns values at t =\n   * t + n * h in y. In case of an unrecoverable error, y and t\n   * contains the values after the last successful step.\n   */\n\n  unsigned long int i;\n  d->n = 0;\n\n  /* Evolution loop */\n\n  for (i = 0; i < n; i++)\n    {\n      int s = gsl_odeiv2_evolve_apply_fixed_step (d->e, d->c, d->s, d->sys,\n                                                  t, h, y);\n\n      if (s != GSL_SUCCESS)\n        {\n          return s;\n        }\n\n      d->n++;\n    }\n\n  return GSL_SUCCESS;\n}\n\nint\ngsl_odeiv2_driver_reset (gsl_odeiv2_driver * d)\n{\n  /* Reset the driver. Resets evolve and step objects. */\n\n  {\n    int s = gsl_odeiv2_evolve_reset (d->e);\n\n    if (s != GSL_SUCCESS)\n      {\n        return s;\n      }\n  }\n\n  {\n    int s = gsl_odeiv2_step_reset (d->s);\n\n    if (s != GSL_SUCCESS)\n      {\n        return s;\n      }\n  }\n\n  return GSL_SUCCESS;\n}\n\nint\ngsl_odeiv2_driver_reset_hstart (gsl_odeiv2_driver * d, const double hstart)\n{\n  /* Resets current driver and sets initial step size to hstart */\n\n  gsl_odeiv2_driver_reset (d);\n\n  if ((d->hmin > fabs (hstart)) || (fabs (hstart) > d->hmax))\n    {\n      GSL_ERROR_NULL (\"hmin <= fabs(h) <= hmax required\", GSL_EINVAL);\n    }\n\n  if (hstart > 0.0 || hstart < 0.0)\n    {\n      d->h = hstart;\n    }\n  else\n    {\n      GSL_ERROR_NULL (\"invalid hstart\", GSL_EINVAL);\n    }\n\n  return GSL_SUCCESS;\n}\n\nvoid\ngsl_odeiv2_driver_free (gsl_odeiv2_driver * state)\n{\n  if (state->c != NULL)\n    {\n      gsl_odeiv2_control_free (state->c);\n    }\n\n  gsl_odeiv2_evolve_free (state->e);\n  gsl_odeiv2_step_free (state->s);\n  free (state);\n}\n", "meta": {"hexsha": "d0db988a592d6b17cff7dc141bb4e54db752df1f", "size": 12220, "ext": "c", "lang": "C", "max_stars_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/ode-initval2/driver.c", "max_stars_repo_name": "ruslankuzmin/julia", "max_stars_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/ode-initval2/driver.c", "max_issues_repo_name": "ruslankuzmin/julia", "max_issues_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/ode-initval2/driver.c", "max_forks_repo_name": "ruslankuzmin/julia", "max_forks_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 24.8879837067, "max_line_length": 81, "alphanum_fraction": 0.5928805237, "num_tokens": 3373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.05500529216624421, "lm_q1q2_score": 0.026858170818173103}}
{"text": "#include <pygsl/solver.h>\n#include <gsl/gsl_roots.h>\n\n\nconst char  * filename = __FILE__;\nPyObject *module = NULL;\n\nstatic const char root_f_type_name[] = \"F-RootSolver\";\nstatic const char root_fdf_type_name[] = \"FdF-RootSolver\";\nstatic const char root_f_root_doc[] = \"Get the value of F\";\nstatic const char root_set_f_doc[] = \"\";\nstatic const char root_set_fdf_doc[] = \"\";\nstatic const char root_fdf_root_doc[] = \"\";\nstatic const char root_x_lower_doc  [] = \"Get the lower bound of x\";\nstatic const char root_x_upper_doc  [] = \"Get the upper bound of x\"; \n\nstatic PyObject* \nPyGSL_root_f_root(PyGSL_solver *self, PyObject *args) \n{\n     return PyGSL_solver_ret_double(self, args, (double_m_t) gsl_root_fsolver_root);\n}\n\nstatic PyObject* \nPyGSL_root_fdf_root(PyGSL_solver *self, PyObject *args) \n{\n     return PyGSL_solver_ret_double(self, args, (double_m_t) gsl_root_fdfsolver_root);\n}\n\nstatic PyObject* \nPyGSL_root_x_lower(PyGSL_solver *self, PyObject *args) \n{\n     return PyGSL_solver_ret_double(self, args, (double_m_t) gsl_root_fsolver_x_lower);\n}\n\nstatic PyObject* \nPyGSL_root_x_upper(PyGSL_solver *self, PyObject *args) \n{\n     return PyGSL_solver_ret_double(self, args, (double_m_t) gsl_root_fsolver_x_upper);\n}\n\nstatic PyObject*\nPyGSL_root_solver_test_interval(PyGSL_solver * self, PyObject *args)\n{\n     double epsabs, epsrel;\n     gsl_root_fsolver *s = (gsl_root_fsolver *) self->solver;\n     if(!PyArg_ParseTuple(args, \"dd\", &epsabs, &epsrel))\n\t  return NULL;\n     return PyInt_FromLong(gsl_root_test_interval(s->x_lower, s->x_upper, epsabs, epsrel));\n}\n\nstatic PyObject* \nPyGSL_root_set_f(PyGSL_solver *self, PyObject *args, PyObject *kw) \n{\n     return PyGSL_solver_set_f(self, args, kw, (void *)gsl_root_fsolver_set, 0); \n}\n\nstatic PyObject* \nPyGSL_root_set_fdf(PyGSL_solver *self, PyObject *args, PyObject *kw) \n{\n     return PyGSL_solver_set_f(self, args, kw,  (void *)gsl_root_fdfsolver_set, 1); \n}\n\nstatic PyMethodDef PyGSL_root_fmethods[] = {     \n     {\"root\",      (PyCFunction)PyGSL_root_f_root,     METH_NOARGS, (char *)root_f_root_doc}, \n     {\"x_lower\",   (PyCFunction)PyGSL_root_x_lower,    METH_NOARGS, (char *)root_x_lower_doc}, \n     {\"x_upper\",   (PyCFunction)PyGSL_root_x_upper,    METH_NOARGS, (char *)root_x_upper_doc}, \n     {\"set\",       (PyCFunction)PyGSL_root_set_f,      METH_VARARGS|METH_KEYWORDS, (char *)root_set_f_doc}, \n     {\"test_interval\",(PyCFunction)PyGSL_root_solver_test_interval, METH_VARARGS, NULL},      \n     {NULL, NULL, 0, NULL}           /* sentinel */\n};\nstatic PyMethodDef PyGSL_root_fdfmethods[] = {     \n     {\"root\",      (PyCFunction)PyGSL_root_fdf_root,     METH_NOARGS, (char *)root_fdf_root_doc}, \n     {\"set\",       (PyCFunction)PyGSL_root_set_fdf,      METH_VARARGS|METH_KEYWORDS, (char *)root_set_fdf_doc}, \n     {NULL, NULL, 0, NULL}           /* sentinel */\n};\n\n\nconst struct _SolverStatic \nroot_solver_f = {{(void_m_t) gsl_root_fsolver_free,   \n\t\t  /* gsl_multimin_fminimizer_restart */  (void_m_t) NULL,\n\t\t  (name_m_t) gsl_root_fsolver_name,   \n\t\t  (int_m_t) gsl_root_fsolver_iterate},\n\t\t 1, PyGSL_root_fmethods, root_f_type_name},\nroot_solver_fdf = {{(void_m_t) gsl_root_fdfsolver_free,   \n\t\t    /* gsl_multimin_fminimizer_restart */  (void_m_t) NULL,\n\t\t    (name_m_t) gsl_root_fdfsolver_name,   \n\t\t     (int_m_t) gsl_root_fdfsolver_iterate},\n\t\t   3, PyGSL_root_fdfmethods, root_fdf_type_name};\n\nstatic PyObject* \nPyGSL_root_f_init(PyObject *self, PyObject *args, \n\t\t const gsl_root_fsolver_type * type) \n{\n\n     PyObject *tmp=NULL;\n     solver_alloc_struct s = {type, (void_an_t) gsl_root_fsolver_alloc,\n\t\t\t      &root_solver_f};\n     FUNC_MESS_BEGIN();     \n     tmp = PyGSL_solver_dn_init(self, args, &s, 0);\n     FUNC_MESS_END();     \n     return tmp;\n}\n\nstatic PyObject* \nPyGSL_root_fdf_init(PyObject *self, PyObject *args, \n\t\t const gsl_root_fdfsolver_type * type) \n{\n\n     PyObject *tmp=NULL;\n     solver_alloc_struct s = {type, (void_an_t) gsl_root_fdfsolver_alloc,\n\t\t\t      &root_solver_fdf};\n     FUNC_MESS_BEGIN();     \n     tmp = PyGSL_solver_dn_init(self, args, &s, 0);\n     FUNC_MESS_END();     \n     return tmp;\n}\n\n#define AROOT_F(name)                                                  \\\nstatic PyObject* PyGSL_root_init_ ## name (PyObject *self, PyObject *args)\\\n{                                                                             \\\n     PyObject *tmp = NULL;                                                    \\\n     FUNC_MESS_BEGIN();                                                       \\\n     tmp = PyGSL_root_f_init(self, args,  gsl_root_fsolver_ ## name); \\\n     if (tmp == NULL){                                                        \\\n\t  PyGSL_add_traceback(module, __FILE__, __FUNCTION__, __LINE__); \\\n     }                                                                        \\\n     FUNC_MESS_END();                                                         \\\n     return tmp;                                                              \\\n}\n#define AROOT_FDF(name)                                                  \\\nstatic PyObject* PyGSL_root_init_ ## name (PyObject *self, PyObject *args)\\\n{                                                                             \\\n     PyObject *tmp = NULL;                                                    \\\n     FUNC_MESS_BEGIN();                                                       \\\n     tmp = PyGSL_root_fdf_init(self, args,  gsl_root_fdfsolver_ ## name); \\\n     if (tmp == NULL){                                                        \\\n\t  PyGSL_add_traceback(module, __FILE__, __FUNCTION__, __LINE__); \\\n     }                                                                        \\\n     FUNC_MESS_END();                                                         \\\n     return tmp;                                                              \\\n}\nAROOT_F(bisection)\nAROOT_F(falsepos)\nAROOT_F(brent)\nAROOT_FDF(newton)\nAROOT_FDF(secant)\nAROOT_FDF(steffenson)\n\n\nstatic PyObject*\nPyGSL_root_test_delta(PyObject * self, PyObject *args)\n{\n     double x_lower, x_upper, epsabs, epsrel;\n     if(!PyArg_ParseTuple(args, \"dddd\", &x_lower, &x_upper, &epsabs, &epsrel))\n\t  return NULL;\n     return PyInt_FromLong(gsl_root_test_delta(x_lower, x_upper, epsabs, epsrel));\n}\n\nstatic PyObject*\nPyGSL_root_test_interval(PyObject * self, PyObject *args)\n{\n     double x_lower, x_upper, epsabs, epsrel;\n     if(!PyArg_ParseTuple(args, \"dddd\", &x_lower, &x_upper, &epsabs, &epsrel))\n\t  return NULL;\n     return PyInt_FromLong(gsl_root_test_interval(x_lower, x_upper, epsabs, epsrel));\n}\n\nstatic const char PyGSL_roots_module_doc [] = \"XXX Missing \";\nstatic PyMethodDef mMethods[] = {\n     /* solver */\n     {\"bisection\",  PyGSL_root_init_bisection, METH_NOARGS, NULL},\n     {\"falsepos\",  PyGSL_root_init_falsepos, METH_NOARGS, NULL},\n     {\"brent\",  PyGSL_root_init_brent, METH_NOARGS, NULL},\n     {\"newton\",  PyGSL_root_init_newton, METH_NOARGS, NULL},\n     {\"secant\",  PyGSL_root_init_secant, METH_NOARGS, NULL},\n     {\"steffenson\",  PyGSL_root_init_steffenson, METH_NOARGS, NULL},\n     /* functions */\n     {\"test_delta\",  PyGSL_root_test_delta, METH_VARARGS, NULL},\n     {\"test_interval\",  PyGSL_root_test_interval, METH_VARARGS, NULL},\n     {NULL, NULL, 0, NULL}\n};\n\nvoid\ninitroots(void)\n{\n     PyObject* m, *dict, *item;\n     FUNC_MESS_BEGIN();\n\n     m=Py_InitModule(\"roots\", mMethods);\n     module = m;\n     assert(m);\n     dict = PyModule_GetDict(m);\n     if(!dict)\n\t  goto fail;\n\n     init_pygsl()\n     import_pygsl_solver();\n     assert(PyGSL_API);\n\n\n     if (!(item = PyString_FromString((char*)PyGSL_roots_module_doc))){\n\t  PyErr_SetString(PyExc_ImportError, \n\t\t\t  \"I could not generate module doc string!\");\n\t  goto fail;\n     }\n\n     if (PyDict_SetItemString(dict, \"__doc__\", item) != 0){\n\t  PyErr_SetString(PyExc_ImportError, \n\t\t\t  \"I could not init doc string!\");\n\t  goto fail;\n     }\n     \n     FUNC_MESS_END();\n\n fail:\n     FUNC_MESS(\"FAIL\");\n     return;\n}\n", "meta": {"hexsha": "5f29e10765bf97c63bf5c7096aefd9ca23eaa7f8", "size": 7922, "ext": "c", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/testing/src/solvers/roots.c", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/testing/src/solvers/roots.c", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/testing/src/solvers/roots.c", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 36.1735159817, "max_line_length": 112, "alphanum_fraction": 0.6100732138, "num_tokens": 2076, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.488283380402856, "lm_q2_score": 0.055005289068012136, "lm_q1q2_score": 0.026858168486165228}}
{"text": "/* \n * File:   rng.h\n * Author: fedro\n *\n * Created on November 3, 2014, 5:33 PM\n */\n\n#ifndef RNG_H\n#define\tRNG_H\n\n#include <gsl/gsl_rng.h>\n\nclass RNG\n{\npublic:\n    RNG(const gsl_rng_type* rng_type, const int seed=0)\n    {\n        rng_ = gsl_rng_alloc(rng_type);\n        gsl_rng_set(rng_, seed);\n    }\n    RNG(const int seed=0)\n    {\n        rng_ = gsl_rng_alloc(gsl_rng_default);\n        gsl_rng_set(rng_, seed);\n    }\n    virtual ~RNG()\n    {\n        gsl_rng_free(rng_);\n    }\n    gsl_rng* get() { return rng_; }\nprivate:\n    gsl_rng* rng_;\n};\n\n#endif\t/* RNG_H */\n\n", "meta": {"hexsha": "68141b1b2f7752db1eb20e034e82fb0c1f2b67c5", "size": 567, "ext": "h", "lang": "C", "max_stars_repo_path": "simulation/neurophys/rng.h", "max_stars_repo_name": "ModelDBRepository/228604", "max_stars_repo_head_hexsha": "8f641f73bcac2700b476663fe656fcad7d63470d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "simulation/neurophys/rng.h", "max_issues_repo_name": "ModelDBRepository/228604", "max_issues_repo_head_hexsha": "8f641f73bcac2700b476663fe656fcad7d63470d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simulation/neurophys/rng.h", "max_forks_repo_name": "ModelDBRepository/228604", "max_forks_repo_head_hexsha": "8f641f73bcac2700b476663fe656fcad7d63470d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.3243243243, "max_line_length": 55, "alphanum_fraction": 0.5749559083, "num_tokens": 170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35220178204788966, "lm_q2_score": 0.07585818054355695, "lm_q1q2_score": 0.026717386370351308}}
{"text": "/***************************************************************************/\n/*                                                                         */\n/* LU_decomp.h - LU Decomposition class for mruby                          */\n/* Copyright (C) 2015 Paolo Bosetti                                        */\n/* paolo[dot]bosetti[at]unitn.it                                           */\n/* Department of Industrial Engineering, University of Trento              */\n/*                                                                         */\n/* This library is free software.  You can redistribute it and/or          */\n/* modify it under the terms of the GNU GENERAL PUBLIC LICENSE 2.0.        */\n/*                                                                         */\n/* This library is distributed in the hope that it will be useful,         */\n/* but WITHOUT ANY WARRANTY; without even the implied warranty of          */\n/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the           */\n/* Artistic License 2.0 for more details.                                  */\n/*                                                                         */\n/* See the file LICENSE                                                    */\n/*                                                                         */\n/***************************************************************************/\n\n#ifndef LU_DECOMP_H\n#define LU_DECOMP_H\n\n#include <stdlib.h>\n#include <string.h>\n#include <errno.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <sys/param.h>\n#include <time.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_permutation.h>\n\n#include \"mruby.h\"\n#include \"mruby/variable.h\"\n#include \"mruby/string.h\"\n#include \"mruby/data.h\"\n#include \"mruby/class.h\"\n#include \"mruby/value.h\"\n#include \"mruby/array.h\"\n#include \"mruby/numeric.h\"\n#include \"mruby/compile.h\"\n\n#define E_LU_DECOMP_ERROR (mrb_class_get(mrb, \"LUDecompError\"))\n\n/***********************************************\\\n LU Decomposition\n\\***********************************************/\n\ntypedef struct {\n  gsl_matrix *mat;\n  gsl_permutation *p;\n  int sgn;\n  size_t size;\n} lu_decomp_data_s;\n\n\n// Garbage collector handler, for play_data struct\n// if play_data contains other dynamic data, free it too!\n// Check it with GC.start\nvoid lu_decomp_destructor(mrb_state *mrb, void *p_);\n\n// Utility function for getting the struct out of the wrapping IV @data\nvoid mrb_lu_decomp_get_data(mrb_state *mrb, mrb_value self, lu_decomp_data_s **data);\n\nvoid mrb_gsl_lu_decomp_init(mrb_state *mrb);\n\n#endif // LU_DECOMP_H", "meta": {"hexsha": "5c7aa3d0a2820eda163b0f2570902b36faf582b2", "size": 2653, "ext": "h", "lang": "C", "max_stars_repo_path": "src/LU_decomp.h", "max_stars_repo_name": "UniTN-Mechatronics/mruby-gsl", "max_stars_repo_head_hexsha": "0961ef3b88bb8ed9e9223b2678ece281acaa0f4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/LU_decomp.h", "max_issues_repo_name": "UniTN-Mechatronics/mruby-gsl", "max_issues_repo_head_hexsha": "0961ef3b88bb8ed9e9223b2678ece281acaa0f4b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/LU_decomp.h", "max_forks_repo_name": "UniTN-Mechatronics/mruby-gsl", "max_forks_repo_head_hexsha": "0961ef3b88bb8ed9e9223b2678ece281acaa0f4b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9, "max_line_length": 85, "alphanum_fraction": 0.4915190351, "num_tokens": 508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378235137849365, "lm_q2_score": 0.060975176172371096, "lm_q1q2_score": 0.02669636588544305}}
{"text": "/* Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n *\n * Copyright 2021 INRIA.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n*/\n\n#ifndef SiconosBlas_H\n#define SiconosBlas_H\n#include \"SiconosConfig.h\"\n\n#if defined(__cplusplus)\nextern \"C\"\n{\n#endif\n\n// tells include-what-you-use to keep this file\n// and not to suggest cblas.h or alike.\n// IWYU pragma: begin_exports\n#if defined(HAS_MKL_CBLAS)\n#include <mkl_cblas.h>\n#elif defined(HAS_MATLAB_BLAS)\n#include <blas.h>\n#define cblas_daxpy daxpy\n#define cblas_dcopy dcopy\n#define cblas_ddot ddot\n#define cblas_dgemm dgemm\n#define cblas_dgemv dgemv\n#define cblas_dnrm2 dnrm2\n#define cblas_dscal dscal\n#else\n#include <cblas.h>\n#endif\n// IWYU pragma: end_exports\n\n#ifdef __cplusplus\n}\n#undef restrict\n#define restrict __restrict\n#endif\n\n\nstatic inline double* NMD_row_rmajor(double* restrict mat, unsigned ncols, unsigned rindx)\n{\n  return &mat[rindx*ncols];\n}\n\nstatic inline void NMD_copycol_rmajor(int nrows, double* col, double* restrict mat, int ncols, unsigned cindx)\n{\n  cblas_dcopy(nrows, col, 1, &mat[cindx], ncols);\n}\n\nstatic inline void NMD_dense_gemv(int nrows, int ncols, double alpha, double* restrict mat, double* restrict y, double beta, double* restrict x)\n{\n  cblas_dgemv(CblasColMajor, CblasTrans, ncols, nrows, alpha, mat, ncols, y, 1, beta, x, 1);\n}\n\n#endif // SiconosBlas_H\n\n\n", "meta": {"hexsha": "8edac9622ae8fa8ac1d34c59e1224345264bcfbe", "size": 1901, "ext": "h", "lang": "C", "max_stars_repo_path": "externals/blas_lapack/SiconosBlas.h", "max_stars_repo_name": "BuildJet/siconos", "max_stars_repo_head_hexsha": "5e9c95806f0a01d62ab564ffb1d9d50c2dc32ef0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2015-06-16T15:55:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T06:01:59.000Z", "max_issues_repo_path": "externals/blas_lapack/SiconosBlas.h", "max_issues_repo_name": "BuildJet/siconos", "max_issues_repo_head_hexsha": "5e9c95806f0a01d62ab564ffb1d9d50c2dc32ef0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 381.0, "max_issues_repo_issues_event_min_datetime": "2015-09-22T15:31:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T09:05:23.000Z", "max_forks_repo_path": "externals/blas_lapack/SiconosBlas.h", "max_forks_repo_name": "BuildJet/siconos", "max_forks_repo_head_hexsha": "5e9c95806f0a01d62ab564ffb1d9d50c2dc32ef0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2015-08-06T22:57:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T20:30:20.000Z", "avg_line_length": 26.4027777778, "max_line_length": 144, "alphanum_fraction": 0.7564439769, "num_tokens": 516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438009916360314, "lm_q2_score": 0.05500529100440717, "lm_q1q2_score": 0.02664346831123759}}
{"text": "#ifndef PVIZUTIL_H\n#define PVIZUTIL_H\n\n#include <math.h>\n#include <string>\n\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_vector.h>\n\n#include <H5Cpp.h>\n\nusing namespace std;\nusing namespace H5;\n\nclass PvizUtil\n{\npublic:\n\tstatic void split(const int n, const int nsplit, int* counts, int* offsets)\n\t{\n\t\tif (nsplit == 0)\n\t\t\tthrow \"Cannot split by zero\";\n\t\t\n\t\t// i = 0\n\t\toffsets[0] = 0;\t\n\t\tcounts[0] = ceil(n/(double)nsplit);\n\t\t\n\t\t// i > 0\n\t\tfor (int i = 1; i < nsplit; i++)\n\t\t{\n\t\t\toffsets[i] = offsets[i-1] + counts[i-1];\n\t\t\tcounts[i] = ceil((n - offsets[i])/(double)(nsplit - i));\n\t\t}\n\t};\n\t\n\tstatic bool H5CheckDataset(const std::string &filename, \n\t\t\t\t\t\t\t   const std::string &datasetname)\n\t{\n\t\tbool rtn = true;\n\t\ttry {\n\t\t\tH5::H5File file(filename, H5F_ACC_RDONLY );\n\t\t\tH5::DataSet dataset = file.openDataSet(datasetname);\n\t\t}\n\t\tcatch (H5::FileIException e) \n\t\t{\n\t\t\trtn = false;\n\t\t}\n\t\t\n\t\treturn rtn;\n\t};\n\t\n\tstatic void H5GetDatasetDim(const std::string &filename, \n\t\t\t\t\t\t\t\tconst std::string &datasetname,\n\t\t\t\t\t\t\t\tconst int &rank, \n\t\t\t\t\t\t\t\thsize_t *dim)\n\t{\n\t\tH5::H5File file( filename, H5F_ACC_RDONLY );\n\t\tH5::DataSet dataset = file.openDataSet(datasetname);\n\t\t\n\t\t/*\n\t\t * Get dataspace of the dataset.\n\t\t */\n\t\tH5::DataSpace dataspace = dataset.getSpace();\n\t\t\n\t\t/*\n\t\t * Get the number of dimensions in the dataspace.\n\t\t */\n\t\tif (rank != dataspace.getSimpleExtentNdims())\n\t\t{\n\t\t\tthrow std::invalid_argument(\"Rank mismatch!!\");\n\t\t}\n\t\t\n\t\tdataspace.getSimpleExtentDims(dim, NULL);\n\t};\n\t\n\tstatic void H5ReadByOffset(const std::string &filename, \n\t\t\t\t\t\t\t   const std::string &datasetname, \n\t\t\t\t\t\t\t   const H5::DataType &mem_type,\n\t\t\t\t\t\t\t   const size_t &rowOffset, \n\t\t\t\t\t\t\t   const size_t &size,\n\t\t\t\t\t\t\t   void *m)\n\t{\n\t\tH5::H5File file(filename, H5F_ACC_RDONLY);\n\t\tH5::DataSet dataset = file.openDataSet(datasetname);\n\t\tH5::DataSpace dataspace = dataset.getSpace();\n\t\t\n\t\tcheckDataset(dataset, mem_type, rowOffset, size, m);\n\t\t\n\t\thsize_t      offset[1];   // hyperslab offset in the file\n\t\thsize_t      count[1];    // size of the hyperslab in the file\n\t\toffset[0] = rowOffset;\n\t\tcount[0]  = size;\n\t\t\n\t\tdataspace.selectHyperslab(H5S_SELECT_SET, count, offset);\n\t\t\n\t\tH5::DataSpace memspace(1, count);\n\t\t\n\t\tdataset.read(m, mem_type, memspace, dataspace);\n\t};\n\t\n\tstatic void H5ReadByRow(const std::string &filename, \n\t\t\t\t\t\t\tconst std::string &datasetname, \n\t\t\t\t\t\t\tconst H5::DataType &mem_type,\n\t\t\t\t\t\t\tconst size_t &rowOffset, \n\t\t\t\t\t\t\tconst size_t &size1,\n\t\t\t\t\t\t\tconst size_t &size2,\n\t\t\t\t\t\t\tvoid *m)\n\t{\n\t\tH5::H5File file(filename, H5F_ACC_RDONLY);\n\t\tH5::DataSet dataset = file.openDataSet(datasetname);\n\t\tH5::DataSpace dataspace = dataset.getSpace();\n\t\t\n\t\tcheckDataset(dataset, mem_type, rowOffset, size1, size2, m);\n\t\t\n\t\thsize_t      offset[2];   // hyperslab offset in the file\n\t\thsize_t      count[2];    // size of the hyperslab in the file\n\t\toffset[0] = rowOffset;\n\t\toffset[1] = 0;\n\t\tcount[0]  = size1;\n\t\tcount[1]  = size2;\n\t\t\n\t\tdataspace.selectHyperslab(H5S_SELECT_SET, count, offset);\n\t\t\n\t\tH5::DataSpace memspace(2, count);\n\t\t\n\t\tdataset.read(m, mem_type, memspace, dataspace);\n\t};\n\t\n\tstatic void H5WriteByRow(const std::string &filename, \n\t\t\t\t\t\t\t const std::string &datasetname, \n\t\t\t\t\t\t\t const H5::DataType &mem_type,\n\t\t\t\t\t\t\t const size_t &rowOffset, \n\t\t\t\t\t\t\t const size_t &size1,\n\t\t\t\t\t\t\t const size_t &size2,\n\t\t\t\t\t\t\t const gsl_matrix *m)\n\t{\n\t\tH5::H5File file(filename, H5F_ACC_RDWR);\n\t\tH5::DataSet dataset = file.openDataSet(datasetname);\n\t\tH5::DataSpace dataspace = dataset.getSpace();\n\t\t\n\t\tcheckDataset(dataset, mem_type, rowOffset, size1, size2, m);\n\t\t\n\t\thsize_t      offset[2];   // hyperslab offset in the file\n\t\thsize_t      count[2];    // size of the hyperslab in the file\n\t\toffset[0] = rowOffset;\n\t\toffset[1] = 0;\n\t\tcount[0]  = size1;\n\t\tcount[1]  = size2;\n\t\t\n\t\tdataspace.selectHyperslab(H5S_SELECT_SET, count, offset);\n\t\t\n\t\tH5::DataSpace memspace(2, count);\n\t\t\n\t\tdataset.write(m, mem_type, memspace, dataspace);\n\t};\n\t\nprotected:\n\tstatic void checkDataset(const H5::DataSet& dataset, \n\t\t\t\t\t\t\t const H5::DataType &mem_type,\n\t\t\t\t\t\t\t const size_t rowOffset, \n\t\t\t\t\t\t\t const size_t &size1,\n\t\t\t\t\t\t\t const size_t &size2,\n\t\t\t\t\t\t\t const void *m)\n\t{\n\t\t// Check datatype\n\t\t/*\n\t\tH5T_class_t class_t = dataset.getTypeClass();\n\t\t\n\t\tif ((class_t != H5T_FLOAT) && (class_t != H5T_INTEGER))\n\t\t{\n\t\t\tthrow std::runtime_error(\"Type mismatch!!\");\n\t\t}\t\t\t\n\t\t*/\n\t\t\n\t\tH5::DataType dtype = dataset.getDataType();\n\t\tif (!(dtype == mem_type))\n\t\t{\n\t\t\tthrow std::runtime_error(\"Data type mismatch!!\");\n\t\t}\n\t\t\n\t\tH5::DataSpace dataspace = dataset.getSpace();\n\t\t\n\t\t// Check rank\n\t\tif (dataspace.getSimpleExtentNdims() != 2)\n\t\t{\n\t\t\tthrow std::runtime_error(\"Rank mismatch!!\");\n\t\t}\n\t\t\n\t\t// Check dimension\n\t\thsize_t dims_out[2];\n\t\tdataspace.getSimpleExtentDims(dims_out, NULL);\n\t\tif (dims_out[0] < size1)\n\t\t{\n\t\t\tthrow std::runtime_error(\"Dimension mismatch!!\");\n\t\t}\n\t\t\n\t\tif (dims_out[1] != size2)\n\t\t{\n\t\t\tthrow std::runtime_error(\"Dimension mismatch!!\");\n\t\t}\n\t\t\n\t\t// Check parameter\n\t\tif (dims_out[0] <= rowOffset)\n\t\t{\n\t\t\tthrow std::runtime_error(\"Offset is out of range!!\");\n\t\t}\n\t\t\n\t\tif (dims_out[0] < rowOffset + size1)\n\t\t{\n\t\t\tthrow std::runtime_error(\"Count is out of range!!\");\n\t\t}\n\t};\n\t\n\tstatic void checkDataset(const H5::DataSet& dataset, \n\t\t\t\t\t\t\t const H5::DataType &mem_type,\n\t\t\t\t\t\t\t const size_t rowOffset, \n\t\t\t\t\t\t\t const size_t &size,\n\t\t\t\t\t\t\t const void *m)\n\t{\n\t\t// Check datatype\n\t\t/*\n\t\t H5T_class_t class_t = dataset.getTypeClass();\n\t\t \n\t\t if ((class_t != H5T_FLOAT) && (class_t != H5T_INTEGER))\n\t\t {\n\t\t throw std::runtime_error(\"Type mismatch!!\");\n\t\t }\t\t\t\n\t\t */\n\t\t\n\t\tH5::DataType dtype = dataset.getDataType();\n\t\tif (!(dtype == mem_type))\n\t\t{\n\t\t\tthrow std::runtime_error(\"Data type mismatch!!\");\n\t\t}\n\t\t\n\t\tH5::DataSpace dataspace = dataset.getSpace();\n\t\t\n\t\t// Check rank\n\t\tif (dataspace.getSimpleExtentNdims() != 1)\n\t\t{\n\t\t\tthrow std::runtime_error(\"Rank mismatch!!\");\n\t\t}\n\t\t\n\t\t// Check dimension\n\t\thsize_t dims_out[1];\n\t\tdataspace.getSimpleExtentDims(dims_out, NULL);\n\t\tif (dims_out[0] < size)\n\t\t{\n\t\t\tthrow std::runtime_error(\"Dimension mismatch!!\");\n\t\t}\n\t\t\n\t\t// Check parameter\n\t\tif (dims_out[0] <= rowOffset)\n\t\t{\n\t\t\tthrow std::runtime_error(\"Offset is out of range!!\");\n\t\t}\n\t\t\n\t\tif (dims_out[0] < rowOffset + size)\n\t\t{\n\t\t\tthrow std::runtime_error(\"Count is out of range!!\");\n\t\t}\n\t};\n};\n\n#endif //PVIZUTIL_H\n", "meta": {"hexsha": "8776988e2406eb27474256e2f9b9f594d22597f7", "size": 6289, "ext": "h", "lang": "C", "max_stars_repo_path": "pvizmodel/src/pvizutil.h", "max_stars_repo_name": "jychoi-hpc/pviz3", "max_stars_repo_head_hexsha": "d55c84a45df0a5bf30ecb832b370e03f0c7ab4c1", "max_stars_repo_licenses": ["xpp"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pvizmodel/src/pvizutil.h", "max_issues_repo_name": "jychoi-hpc/pviz3", "max_issues_repo_head_hexsha": "d55c84a45df0a5bf30ecb832b370e03f0c7ab4c1", "max_issues_repo_licenses": ["xpp"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pvizmodel/src/pvizutil.h", "max_forks_repo_name": "jychoi-hpc/pviz3", "max_forks_repo_head_hexsha": "d55c84a45df0a5bf30ecb832b370e03f0c7ab4c1", "max_forks_repo_licenses": ["xpp"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7320754717, "max_line_length": 76, "alphanum_fraction": 0.6346000954, "num_tokens": 1922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.05921024659098507, "lm_q1q2_score": 0.026608648702830834}}
{"text": "//  This random generator is a C++ wrapper for the GNU Scientific Library\n//  Copyright (C) 2001 Torbjorn Vik\n\n//  This program is free software; you can redistribute it and/or modify\n//  it under the terms of the GNU General Public License as published by\n//  the Free Software Foundation; either version 2 of the License, or\n//  (at your option) any later version.\n\n//  This program is distributed in the hope that it will be useful,\n//  but WITHOUT ANY WARRANTY; without even the implied warranty of\n//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n//  GNU General Public License for more details.\n\n//  You should have received a copy of the GNU General Public License\n//  along with this program; if not, write to the Free Software\n//  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n#ifndef __min_fminimizer_h\n#define __min_fminimizer_h \n\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_min.h>\n\nnamespace gsl{\n\n//! Derive this class provide a user defined function for minimisation\nstruct min_f\n{\n\t//! This operator must be overridden\n\tvirtual double operator()(const double& x)=0;\n\t\n\t//! This is the function gsl calls to optimize f\n\tstatic double f(double x, void *p)\n\t{\n\t\treturn (*(min_f *)p)(x);\n\t}\n};\n\n//! Class for minimizing one dimensional functions. \n/*!\n  Usage: \n       - Create with optional minimize type\n\t   - Set with function object and inital bounds\n\t   - Loop the  iterate function until convergence or maxIterations (extra facility)\n\n\t   - Recover minimum and bounds\n */\nclass min_fminimizer \n{\n public:\n\t//! choose between gsl_min_fminimizer_goldensection and gsl_min_fminimizer_brent\n\tmin_fminimizer(const gsl_min_fminimizer_type* type=gsl_min_fminimizer_brent) : s(NULL), maxIterations(100), isSet(false)\n\t{\n\t\ts=gsl_min_fminimizer_alloc(type);\n\t\tnIterations=0;\n\t\tif (!s)\n\t\t{\n\t\t\t//error\n\t\t\t//cout << \"ERROR Couldn't allocate memory for minimizer\" << endl;\n\t\t\t//throw ? \n\t\t\texit(-1);\n\t\t}\n\t}\n\t~min_fminimizer(){if (s) gsl_min_fminimizer_free(s);}\n\t//! returns GSL_FAILURE if the interval does not contain a minimum\n\tint set(min_f& function, double minimum, double x_lower, double x_upper)\n\t{\n\t\tisSet=false;\n\t\tf.function = &function.f;\n\t\tf.params = &function;\n\t\tint status=\tgsl_min_fminimizer_set(s, &f, minimum, x_lower, x_upper);\n\t\tif (!status)\n\t\t{\n\t\t\tisSet=true;\n\t\t\tnIterations=0;\n\t\t}\n\t\treturn status;\n\t}\n\tint set_with_values(min_f& function, \n\t\t\t\t\t\tdouble minimum, double f_minimum, \n\t\t\t\t\t\tdouble x_lower,double f_lower, \n\t\t\t\t\t\tdouble x_upper, double f_upper)\n\t{\n\t\tisSet=false;\n\t\tf.function = &function.f;\n\t\tf.params = &function;\n\t\tint status=\tgsl_min_fminimizer_set_with_values(s, &f, minimum, f_minimum, x_lower, f_lower, x_upper, f_upper);\n\t\tif (!status)\n\t\t{\n\t\t\tisSet=true;\n\t\t\tnIterations=0;\n\t\t}\n\t\treturn status;\n\t}\n\tint iterate()\n\t{\n\t\tassert_set();\n\t\tint status=gsl_min_fminimizer_iterate(s);\n\t\tnIterations++;\n\t\tif (status==GSL_FAILURE)\n\t\t\tisConverged=true;\n\t\treturn status;\n\t}\n\tdouble minimum(){assert_set();return gsl_min_fminimizer_minimum(s);}\n\tdouble x_upper(){assert_set();return gsl_min_fminimizer_x_upper(s);}\n\tdouble x_lower(){assert_set();return gsl_min_fminimizer_x_lower(s);}\n\tvoid SetMaxIterations(int n){maxIterations=n;}\n\tint GetNIterations(){return nIterations;}\n\tbool is_converged(){if (nIterations>=maxIterations) return true; if (isConverged) return true; return false;}\n\t//string name() const;\n\t\n private:\n\tvoid assert_set(){if (!isSet)exit(-1);} // Old problem of error handling: TODO\n\t\n\tbool isSet;\n\tbool isConverged;\n\tint nIterations;\n\tint maxIterations;\n\tgsl_min_fminimizer* s;\n\tgsl_function f;\n};\n};\t // namespace gsl\n\n#endif //__min_fminimizer_h\n", "meta": {"hexsha": "a4e4ad37a17b6e87cc9f963534a8b0185229654c", "size": 3627, "ext": "h", "lang": "C", "max_stars_repo_path": "src/gslwrap/min_fminimizer.h", "max_stars_repo_name": "entn-at/GlottDNN", "max_stars_repo_head_hexsha": "b7db669d7f34da92ab34742d75a8ba3c70763a65", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-11-27T01:35:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T01:17:11.000Z", "max_issues_repo_path": "src/gslwrap/min_fminimizer.h", "max_issues_repo_name": "entn-at/GlottDNN", "max_issues_repo_head_hexsha": "b7db669d7f34da92ab34742d75a8ba3c70763a65", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gslwrap/min_fminimizer.h", "max_forks_repo_name": "entn-at/GlottDNN", "max_forks_repo_head_hexsha": "b7db669d7f34da92ab34742d75a8ba3c70763a65", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-11-27T01:35:33.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-27T01:35:33.000Z", "avg_line_length": 29.25, "max_line_length": 121, "alphanum_fraction": 0.723462917, "num_tokens": 969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.055823143490797325, "lm_q1q2_score": 0.0266041742461217}}
{"text": "#ifndef TESTING_COMMON\n#define TESTING_COMMON\n\n#define MIN(a, b) ((a) < (b) ? (a) : (b))\n#define MAX(a, b) ((a) > (b) ? (a) : (b))\n\n// header ------------------------------------------\n#include \"testing_setting.h\"\n#undef _IEEE_\n\n#define __STDC_WANT_IEC_60559_TYPES_EXT__\n#include <cstdio>\n#include <cstdlib>\n#include <cmath> \n\n#include <string.h>\n#include <stdint.h>\n#include <float.h>\n#define __STDC_FORMAT_MACROS\n#include <inttypes.h>\n#include <sys/time.h>\n#include <unistd.h>\n#include <getopt.h>\n#include <ctype.h>\n#include <sys/utsname.h>\n\n#if defined (MKL)\n//#include <mkl.h>\n#include <mkl_cblas.h>\n#include <mkl_trans.h>\n//#include <mkl_spblas.h> // conflict with Bebop SMC\n#else\n#include <cblas.h>\n#endif\n\n#if defined (ARM)\n#define __float128 long double\n#endif\n\n#if defined (CUBLAS) \n#include <cublas_v2.h>\n#elif defined (CUOZBLAS)\n#include <cuozblas.h>\n#elif defined (OZBLAS)\n#include <ozblas.h>\n#endif\n\n#if defined (CUDA)\n#include <cuda.h>\n#include <cuda_runtime_api.h>\n#include <cublas_v2.h>\n#include <cusparse_v2.h>\n#endif\n\n#if defined (CSRMV) || defined (CG)\nextern \"C\" {\n#include <bebop/smc/sparse_matrix.h>\n#include <bebop/smc/sparse_matrix_ops.h>\n#include <bebop/smc/csr_matrix.h>\n}\n#endif\n\n#if !defined (MPLAPACK)\n#define mpreal double\n#endif\n\n// ===========================================================\n// common for FP_TYPE\n#if defined (PREC_Q_D) || defined (PREC_Q_S)\n#define PREC_Q\n#elif defined (PREC_D_D) || defined (PREC_D_S)\n#define PREC_D\n#elif defined (PREC_S_S) || defined (PREC_S_D)\n#define PREC_S\n#elif defined (PREC_32F_PDT_32F)\n#define PREC_S\n#elif defined (PREC_32F_TC_32F)\n#define PREC_S\n#elif defined (PREC_32F_TC_32TF)\n#define PREC_S\n#elif defined (PREC_16F_TC_32F)\n#define PREC_H\n#elif defined (PREC_16F_PDT_32F)\n#define PREC_H\n#elif defined (PREC_16F_TC_16F)\n#define PREC_H\n#elif defined (PREC_16F_PDT_16F)\n#define PREC_H\n#elif defined (PREC_64F_PDT_64F)\n#define PREC_D\n#elif defined (PREC_64F_TC_64F)\n#define PREC_D\n#endif\n// ===========================================================\n\t\n#if defined (MPLAPACK)\n#if defined (PREC_Q)\n#define MPFR_WANT_FLOAT128\n#define _Float128 __float128 // this is needed if MPFR is >= 4.1.0\n#endif\n#include <mplapack/mpblas_mpfr.h>\n#include <mpfr.h> // this is after above\n#endif\n#undef _Float128\n\n// +++++++++++++++++++++\n// FP_TYPE == binary128\n// +++++++++++++++++++++\n#if defined (PREC_Q)\n#define FP_TYPE\t__float128\n#if defined (ARM)\n#define FABS fabs\n#define FP_MAX LDBL_MAX\n#define FP_MIN LDBL_MIN\n#define F_PI 3.1415926535897932384626433832795029L;\n#else\n#include <quadmath.h>\n#define FABS fabsq\n#define FP_MAX FLT128_MAX\n#define FP_MIN FLT128_MIN\n#define F_PI M_PIq\n#endif\n#if defined (MPLAPACK)\n#include <mplapack/mpblas__Float128.h>\n#endif\n\n// +++++++++++++++++++++\n// FP_TYPE == double-double\n// +++++++++++++++++++++\n#elif defined (PREC_DD)\n#define FP_TYPE dd_real\n#define FABS fabs\n#if defined (MPLAPACK)\n#include <qd/dd_real.h>\n#include <mplapack/mpblas_dd.h>\n#endif\n#define FP_MAX DBL_MAX\n#define FP_MIN DBL_MIN\n#define F_PI dd_real::_pi\n\n// +++++++++++++++++++++\n// FP_TYPE == binary64\n// +++++++++++++++++++++\n#elif defined (PREC_D)\n#define FP_TYPE\tdouble\n#define FABS fabs\n#define FP_MAX DBL_MAX\n#define FP_MIN DBL_MIN\n#define F_PI M_PI\n\n// +++++++++++++++++++++\n// FP_TYPE == binary32\n// +++++++++++++++++++++\n#elif defined (PREC_S)\n#define FP_TYPE\tfloat\n#define FABS fabs\n#define FP_MAX FLT_MAX\n#define FP_MIN FLT_MIN\n#define F_PI M_PI\n\n// +++++++++++++++++++++\n// FP_TYPE == binary16\n// +++++++++++++++++++++\n#elif defined (PREC_H)\n#include \"half-2.1.0/half.hpp\"\nusing half_float::half;\n#define FP_TYPE\thalf\n#define FABS fabs\n#define FP_MAX 65504.\n#define FP_MIN (2.e-14)-1\n#define F_PI M_PI\n\n#endif\n\n// ===========================================================\n// reference BLAS\n#if defined (MPLAPACK)\n#define refRdot\t\t\t\t\t\t\t\t\t\t\t\tRdot\n#define refRgemv(tran,m,n,al,A,lda,X,ix,bt,Y,iy)\t\t\tRgemv(&tran,m,n,al,A,lda,X,ix,bt,Y,iy)\n#define refRgemm(tranA,tranB,m,n,k,al,A,lda,B,ldb,bt,C,ldc) Rgemm(&tranA,&tranB,m,n,k,al,A,lda,B,ldb,bt,C,ldc)\n#else\n#define refRdot\tcblas_ddot\n#define refRgemv(tran,m,n,al,A,lda,X,ix,bt,Y,iy)\t\t\tcblas_dgemv(CblasColMajor,ToCblasOp(tran),m,n,al,A,lda,X,ix,bt,Y,iy)\n#define refRgemm(tranA,tranB,m,n,k,al,A,lda,B,ldb,bt,C,ldc) cblas_dgemm(CblasColMajor,ToCblasOp(tranA),ToCblasOp(tranB),m,n,k,al,A,lda,B,ldb,bt,C,ldc)\n#endif\n\n// ===========================================================\n// argment transformation\n#if defined (OZBLAS) \n#define trgRdot(ha,n,x,ix,y,iy)\t\t\t\t\t\t\t\trdot(&ha,n,x,ix,y,iy)\n#define trgRnrm2(ha,n,x,ix)\t\t\t\t\t\t\t\t\trnrm2(&ha,n,x,ix)\n#define trgRaxpy(ha,n,a,x,ix,y,iy)\t\t\t\t\t\t\traxpy(&ha,n,a,x,ix,y,iy)\n#define\ttrgRgemv(ha,ta,m,n,al,a,la,x,ix,bt,y,iy)\t\t\trgemv(&ha,ta,m,n,al,a,la,x,ix,bt,y,iy)\n#define trgRgemm(ha,ta,tb,m,n,k,al,A,lda,B,ldb,bt,C,ldc)\trgemm(&ha,ta,tb,m,n,k,al,A,lda,B,ldb,bt,C,ldc)\n#define\ttrgRcsrmv(ha,ta,m,n,nnz,al,da,a,ci,rp,x,bt,y)\t\trcsrmv(&ha,ta,m,n,nnz,al,da,a,ci,rp,x,bt,y)\n#define\ttrgRcg(ha,ta,n,nnz,da,a,ci,rp,b,x,itr,tol)\t\t\trcg(&ha,ta,n,nnz,da,a,ci,rp,b,x,itr,tol)\t\n#elif defined (CUOZBLAS)\n#define trgRdot(ha,n,x,ix,y,iy,r)\t\t\t\t\t\t\trdot(&ha,n,x,ix,y,iy,r)\n#define trgRnrm2(ha,n,x,ix,r)\t\t\t\t\t\t\t\trnrm2(&ha,n,x,ix,r)\n#define trgRaxpy(ha,n,a,x,ix,y,iy)\t\t\t\t\t\t\traxpy(&ha,n,a,x,ix,y,iy)\n#define\ttrgRgemv(ha,ta,m,n,al,a,la,x,ix,bt,y,iy)\t\t\trgemv(&ha,ta,m,n,al,a,la,x,ix,bt,y,iy)\n#define trgRgemm(ha,ta,tb,m,n,k,al,A,lda,B,ldb,bt,C,ldc)\trgemm(&ha,ta,tb,m,n,k,al,A,lda,B,ldb,bt,C,ldc)\n#define\ttrgRcsrmv(ha,ta,m,n,nnz,al,da,a,ci,rp,x,bt,y)\t\trcsrmv(&ha,ta,m,n,nnz,al,da,a,ci,rp,x,bt,y)\n#define\ttrgRcg(ha,ta,n,nnz,da,a,ci,rp,b,x,itr,tol)\t\t\trcg(&ha,ta,n,nnz,da,a,ci,rp,b,x,itr,tol)\t\n#elif defined (CUBLAS) && defined (GEMMEX)\n#define trgRgemm(ha,ta,tb,m,n,k,al,A,lda,B,ldb,bt,C,ldc)\tcublasGemmEx(ha,ToCublasOp(ta),ToCublasOp(tb),m,n,k,&al,A,DATA_TYPE_A,lda,B,DATA_TYPE_B,ldb,&bt,C,DATA_TYPE_C,ldc,COMP_TYPE,ALGO_TYPE)\n#elif defined (CUBLAS)\n#define trgRdot(ha,n,x,ix,y,iy,r)\t\t\t\t\t\t\trdot(ha,n,x,ix,y,iy,r)\n#define trgRnrm2(ha,n,x,ix)\t\t\t\t\t\t\t\t\trnrm2(ha,n,x,ix)\n#define trgRaxpy(ha,n,a,x,ix,y,iy)\t\t\t\t\t\t\traxpy(ha,n,a,x,ix,y,iy)\n#define\ttrgRgemv(ha,ta,m,n,al,a,la,x,ix,bt,y,iy)\t\t\trgemv(ha,ToCublasOp(ta),m,n,&al,a,la,x,ix,&bt,y,iy)\n#define trgRgemm(ha,ta,tb,m,n,k,al,A,lda,B,ldb,bt,C,ldc)\trgemm(ha,ToCublasOp(ta),ToCublasOp(tb),m,n,k,&al,A,lda,B,ldb,&bt,C,ldc)\n#define\ttrgRcsrmv(ha,ta,m,n,nnz,al,da,a,ci,rp,x,bt,y)\t\trcsrmv(ha,ToCusparseOp(ta),m,n,nnz,al,da,a,ci,rp,x,bt,y)\n//#define\ttrgRcg(ha,ta,n,nnz,da,a,ci,rp,b,x,itr,tol)\t\t\trcg(&ha,ta,n,nnz,da,a,ci,rp,b,x,itr,tol)\t\n#elif defined (MPBLAS)\n#define trgRdot(ha,n,x,ix,y,iy)\t\t\t\t\t\t\t\trdot(n,x,ix,y,iy)\n#define trgRnrm2(ha,n,x,ix)\t\t\t\t\t\t\t\t\trnrm2(n,x,ix)\n#define trgRaxpy(ha,n,a,x,ix,y,iy)\t\t\t\t\t\t\traxpy(ha,n,a,x,ix,y,iy)\n#define\ttrgRgemv(ha,ta,m,n,al,a,la,x,ix,bt,y,iy)\t\t\trgemv(&ta,m,n,al,a,la,x,ix,bt,y,iy)\n#define trgRgemm(ha,ta,tb,m,n,k,al,A,lda,B,ldb,bt,C,ldc)\trgemm(&ta,&tb,m,n,k,al,A,lda,B,ldb,bt,C,ldc)\n//#define\ttrgRcg(ha,ta,n,nnz,da,a,ci,rp,b,x,itr,tol)\t\t\trcg(&ha,ta,n,nnz,da,a,ci,rp,b,x,itr,tol)\t\n#endif\n\n// ===========================================================\n#if defined (CUOZBLAS)\n#define ozblasHandle_t\t\tcuozblasHandle_t\n#define ozblasCreate \t\tcuozblasCreate\n#define ozblasDestroy\t\tcuozblasDestroy\n#endif\n\n// ================================================\n#if defined (PREC_Q_D)\n#if defined (CUOZBLAS)\n#define rcg\t\t\t\tcuozblasRcg<__float128,double>\n#define rdot\t\t\tcuozblasRdot<__float128,double>\n#define rnrm2\t\t\tcuozblasRnrm2<__float128,double>\n#define raxpy\t\t\tcuozblasRaxpy<__float128>\n#define rgemv\t\t\tcuozblasRgemv<__float128,double>\n#define rgemm\t\t\tcuozblasRgemm<__float128,double>\n#define rcsrmv\t\t\tcuozblasRcsrmv<__float128,double>\n#define rcsrmvSplitA\tcuozblasRcsrmvSplitA<__float128,double>\n#elif defined (OZBLAS)\n#define rcg\t\t\t\tozblasRcg<__float128,double>\n#define rdot\t\t\tozblasRdot<__float128,double>\n#define rnrm2\t\t\tozblasRnrm2<__float128,double>\n#define rgemv\t\t\tozblasRgemv<__float128,double>\n#define rgemm\t\t\tozblasRgemm<__float128,double>\n#define rcsrmv\t\t\tozblasRcsrmv<__float128,double>\n#define rcsrmvSplitA\tozblasRcsrmvSplitA<__float128,double>\n#elif defined (MPBLAS)\n#define\trdot\t\t\tRdot\n#define\trgemv\t\t\tRgemv\n#define\trgemm\t\t\tRgemm\n#endif\n\n// ================================================\n#elif defined (PREC_Q_S)\n#if defined (CUOZBLAS)\n#define rcg\t\t\t\tcuozblasRcg<__float128,float>\n#define rdot\t\t\tcuozblasRdot<__float128,float>\n#define rnrm2\t\t\tcuozblasRnrm2<__float128,float>\n#define raxpy\t\t\tcuozblasRaxpy<__float128>\n#define rgemv\t\t\tcuozblasRgemv<__float128,float>\n#define rgemm\t\t\tcuozblasRgemm<__float128,float>\n#define rcsrmv\t\t\tcuozblasRcsrmv<__float128,float>\n#define rcsrmvSplitA\tcuozblasRcsrmvSplitA<__float128,float>\n#elif defined (OZBLAS)\n#define rcg\t\t\t\tozblasRcg<__float128,float>\n#define rdot\t\t\tozblasRdot<__float128,float>\n#define rnrm2\t\t\tozblasRnrm2<__float128,float>\n#define rgemv\t\t\tozblasRgemv<__float128,float>\n#define rgemm\t\t\tozblasRgemm<__float128,float>\n#define rcsrmv\t\t\tozblasRcsrmv<__float128,float>\n#define rcsrmvSplitA\tozblasRcsrmvSplitA<__float128,float>\n#endif\n\n// ================================================\n#elif defined (PREC_D_S)\n#if defined (CUOZBLAS)\n#define rcg\t\t\t\tcuozblasRcg<double,float>\n#define rdot\t\t\tcuozblasRdot<double,float>\n#define rnrm2\t\t\tcuozblasRnrm2<double,float>\n#define raxpy\t\t\tcuozblasRaxpy<double>\n#define rgemv\t\t\tcuozblasRgemv<double,float>\n#define rgemm\t\t\tcuozblasRgemm<double,float>\n#define rcsrmv\t\t\tcuozblasRcsrmv<double,float>\n#define rcsrmvSplitA\tcuozblasRcsrmvSplitA<double,float>\n#elif defined (OZBLAS)\n#define rcg\t\t\t\tozblasRcg<double,float>\n#define rdot\t\t\tozblasRdot<double,float>\n#define rnrm2\t\t\tozblasRnrm2<double,float>\n#define rgemv\t\t\tozblasRgemv<double,float>\n#define rgemm\t\t\tozblasRgemm<double,float>\n#define rcsrmv\t\t\tozblasRcsrmv<double,float>\n#define rcsrmvSplitA\tozblasRcsrmvSplitA<double,float>\n#endif\n\n// ================================================\n#elif defined (PREC_D_D)\n#if defined (CUOZBLAS)\n#define rcg\t\t\t\tcuozblasRcg<double,double>\n#define rdot\t\t\tcuozblasRdot<double,double>\n#define rnrm2\t\t\tcuozblasRnrm2<double,double>\n#define raxpy\t\t\tcuozblasRaxpy<double>\n#define rgemv\t\t\tcuozblasRgemv<double,double>\n//#define rgemm\t\t\tcuozblasDgemm\n#define rgemm\t\t\tcuozblasRgemm<double,double>\n#define rcsrmv\t\t\tcuozblasRcsrmv<double,double>\n#define rcsrmvSplitA\tcuozblasRcsrmvSplitA<double,double>\n#elif defined (OZBLAS)\n#define rcg\t\t\t\tozblasRcg<double,double>\n#define rdot\t\t\tozblasRdot<double,double>\n#define rnrm2\t\t\tozblasRnrm2<double,double>\n#define rgemv\t\t\tozblasRgemv<double,double>\n//#define rgemv\t\t\tozblasDgemv\n#define rgemm\t\t\tozblasRgemm<double,double>\n#define rcsrmv\t\t\tozblasRcsrmv<double,double>\n#define rcsrmvSplitA\tozblasRcsrmvSplitA<double,double>\n#elif defined (CUBLAS)\n//#define rcg\t\t\tcublasDcg\n#define rdot\t\t\tcublasDdot\n#define rnrm2\t\t\tcublasDnrm2\n#define rgemv\t\t\tcublasDgemv\n#define rgemm\t\t\tcublasDgemm\n//#define rcsrmv\t\tcublasDcsrmv\n#endif\n\n// ================================================\n#elif defined (PREC_S_S)\n#if defined (CUOZBLAS)\n#define rcg\t\t\t\tcuozblasRcg<float,float>\n#define rdot\t\t\tcuozblasRdot<float,float>\n#define rnrm2\t\t\tcuozblasRnrm2<float,float>\n#define raxpy\t\t\tcuozblasRaxpy<float>\n#define rgemv\t\t\tcuozblasRgemv<float,float>\n#define rgemm\t\t\tcuozblasRgemm<float,float>\n#define rcsrmv\t\t\tcuozblasRcsrmv<float,float>\n#define rcsrmvSplitA\tcuozblasRcsrmvSplitA<float,float>\n#elif defined (OZBLAS)\n#define rcg\t\t\t\tozblasRcg<float,float>\n#define rdot\t\t\tozblasRdot<float,float>\n#define rnrm2\t\t\tozblasRnrm2<float,float>\n#define rgemv\t\t\tozblasRgemv<float,float>\n#define rgemm\t\t\tozblasRgemm<float,float>\n#define rcsrmv\t\t\tozblasRcsrmv<float,float>\n#define rcsrmvSplitA\tozblasRcsrmvSplitA<float,float>\n#elif defined (CUBLAS)\n//#define rcg\t\t\tcublasScg\n#define rdot\t\t\tcublasSdot\n#define rnrm2\t\t\tcublasSnrm2\n#define rgemv\t\t\tcublasSgemv\n#define rgemm\t\t\tcublasSgemm\n//#define rcsrmv\t\tcublasScsrmv\n#endif\n\n// ================================================\n#elif defined (PREC_S_D)\n#if defined (CUOZBLAS)\n#define rcg\t\t\t\tcuozblasRcg<float,double>\n#define rdot\t\t\tcuozblasRdot<float,double>\n#define rnrm2\t\t\tcuozblasRnrm2<float,double>\n#define raxpy\t\t\tcuozblasRaxpy<float>\n#define rgemv\t\t\tcuozblasRgemv<float,double>\n#define rgemm\t\t\tcuozblasRgemm<float,double>\n#define rcsrmv\t\t\tcuozblasRcsrmv<float,double>\n#define rcsrmvSplitA\tcuozblasRcsrmvSplitA<float,double>\n#elif defined (OZBLAS)\n#define rcg\t\t\t\tozblasRcg<float,double>\n#define rdot\t\t\tozblasRdot<float,double>\n#define rnrm2\t\t\tozblasRnrm2<float,double>\n#define rgemv\t\t\tozblasRgemv<float,double>\n#define rgemm\t\t\tozblasRgemm<float,double>\n#define rcsrmv\t\t\tozblasRcsrmv<float,double>\n#define rcsrmvSplitA\tozblasRcsrmvSplitA<float,double>\n#endif\n\n// ================================================\n#elif defined (PREC_DD)\n#if defined (MPBLAS)\n#define\trdot\t\t\tRdot\n#define\trgemv\t\t\tRgemv\n#define\trgemm\t\t\tRgemm\n#endif\n\n#endif\n\n// ================================================\n// GemmEx\n#if defined (CUBLAS) && defined (GEMMEX)\n#define rgemm\t\t\tcublasGemmEx\n// ----------------------------\n#if defined (PREC_32F_PDT_32F)\n#define DATA_TYPE_A CUDA_R_32F \n#define DATA_TYPE_B CUDA_R_32F \n#define DATA_TYPE_C CUDA_R_32F \n#define COMP_TYPE CUBLAS_COMPUTE_32F_PEDANTIC \n#define ALGO_TYPE CUBLAS_GEMM_DEFAULT\n// ----------------------------\n#elif defined (PREC_32F_TC_32F)\n#define DATA_TYPE_A CUDA_R_32F \n#define DATA_TYPE_B CUDA_R_32F \n#define DATA_TYPE_C CUDA_R_32F \n#define COMP_TYPE CUBLAS_COMPUTE_32F\n#define ALGO_TYPE CUBLAS_GEMM_DEFAULT\n// ----------------------------\n#elif defined (PREC_32F_TC_32TF)\n#define DATA_TYPE_A CUDA_R_32F \n#define DATA_TYPE_B CUDA_R_32F \n#define DATA_TYPE_C CUDA_R_32F \n#define COMP_TYPE CUBLAS_COMPUTE_32F_FAST_TF32\n#define ALGO_TYPE CUBLAS_GEMM_DEFAULT\n// ----------------------------\n#elif defined (PREC_16F_TC_32F)\n#define DATA_TYPE_A CUDA_R_16F \n#define DATA_TYPE_B CUDA_R_16F \n#define DATA_TYPE_C CUDA_R_16F \n#define COMP_TYPE CUBLAS_COMPUTE_32F\n#define ALGO_TYPE CUBLAS_GEMM_DEFAULT\n// ----------------------------\n#elif defined (PREC_16F_PDT_32F)\n#define DATA_TYPE_A CUDA_R_16F \n#define DATA_TYPE_B CUDA_R_16F \n#define DATA_TYPE_C CUDA_R_16F \n#define COMP_TYPE CUBLAS_COMPUTE_32F_PEDANTIC\n#define ALGO_TYPE CUBLAS_GEMM_DEFAULT\n// ----------------------------\n#elif defined (PREC_16F_TC_16F)\n#define DATA_TYPE_A CUDA_R_16F \n#define DATA_TYPE_B CUDA_R_16F \n#define DATA_TYPE_C CUDA_R_16F \n#define COMP_TYPE CUBLAS_COMPUTE_16F\n#define ALGO_TYPE CUBLAS_GEMM_DEFAULT\n// ----------------------------\n#elif defined (PREC_16F_PDT_16F)\n#define DATA_TYPE_A CUDA_R_16F \n#define DATA_TYPE_B CUDA_R_16F \n#define DATA_TYPE_C CUDA_R_16F \n#define COMP_TYPE CUBLAS_COMPUTE_16F_PEDANTIC\n#define ALGO_TYPE CUBLAS_GEMM_DEFAULT\n// ----------------------------\n#elif defined (PREC_64F_PDT_64F)\n#define DATA_TYPE_A CUDA_R_64F \n#define DATA_TYPE_B CUDA_R_64F \n#define DATA_TYPE_C CUDA_R_64F \n#define COMP_TYPE CUBLAS_COMPUTE_64F_PEDANTIC \n#define ALGO_TYPE CUBLAS_GEMM_DEFAULT\n// ----------------------------\n#elif defined (PREC_64F_TC_64F)\n#define DATA_TYPE_A CUDA_R_64F \n#define DATA_TYPE_B CUDA_R_64F \n#define DATA_TYPE_C CUDA_R_64F \n#define COMP_TYPE CUBLAS_COMPUTE_64F\n#define ALGO_TYPE CUBLAS_GEMM_DEFAULT\n// ----------------------------\n#endif\n#endif\n\n\n#endif\n", "meta": {"hexsha": "08f9672e01f356d3d0179f8a5aa6b20b499434f6", "size": 15132, "ext": "h", "lang": "C", "max_stars_repo_path": "testing/testing_common.h", "max_stars_repo_name": "wsmoses/Riken-blas", "max_stars_repo_head_hexsha": "97c20aa5d8e186790aa505f6be4d1f48eee352e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "testing/testing_common.h", "max_issues_repo_name": "wsmoses/Riken-blas", "max_issues_repo_head_hexsha": "97c20aa5d8e186790aa505f6be4d1f48eee352e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "testing/testing_common.h", "max_forks_repo_name": "wsmoses/Riken-blas", "max_forks_repo_head_hexsha": "97c20aa5d8e186790aa505f6be4d1f48eee352e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8956521739, "max_line_length": 191, "alphanum_fraction": 0.6920433518, "num_tokens": 5254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.05749328324142241, "lm_q1q2_score": 0.026505368272051306}}
{"text": "/* monte/gsl_monte_miser.h\r\n * \r\n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Michael Booth\r\n * Copyright (C) 2009 Brian Gough\r\n * \r\n * This program is free software; you can redistribute it and/or modify\r\n * it under the terms of the GNU General Public License as published by\r\n * the Free Software Foundation; either version 3 of the License, or (at\r\n * your option) any later version.\r\n * \r\n * This program is distributed in the hope that it will be useful, but\r\n * WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n * General Public License for more details.\r\n * \r\n * You should have received a copy of the GNU General Public License\r\n * along with this program; if not, write to the Free Software\r\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r\n */\r\n\r\n/* Author: MJB */\r\n\r\n#ifndef __GSL_MONTE_MISER_H__\r\n#define __GSL_MONTE_MISER_H__\r\n\r\n#if !defined( GSL_FUN )\r\n#  if !defined( GSL_DLL )\r\n#    define GSL_FUN extern\r\n#  elif defined( BUILD_GSL_DLL )\r\n#    define GSL_FUN extern __declspec(dllexport)\r\n#  else\r\n#    define GSL_FUN extern __declspec(dllimport)\r\n#  endif\r\n#endif\r\n\r\n#include <gsl/gsl_rng.h>\r\n#include <gsl/gsl_monte.h>\r\n#include <gsl/gsl_monte_plain.h>\r\n\r\n#undef __BEGIN_DECLS\r\n#undef __END_DECLS\r\n#ifdef __cplusplus\r\n# define __BEGIN_DECLS extern \"C\" {\r\n# define __END_DECLS }\r\n#else\r\n# define __BEGIN_DECLS /* empty */\r\n# define __END_DECLS /* empty */\r\n#endif\r\n\r\n__BEGIN_DECLS\r\n\r\ntypedef struct {\r\n  size_t min_calls;\r\n  size_t min_calls_per_bisection;\r\n  double dither;\r\n  double estimate_frac;\r\n  double alpha;\r\n  size_t dim;\r\n  int estimate_style;\r\n  int depth;\r\n  int verbose;\r\n  double * x;\r\n  double * xmid;\r\n  double * sigma_l;\r\n  double * sigma_r;\r\n  double * fmax_l;\r\n  double * fmax_r;\r\n  double * fmin_l;\r\n  double * fmin_r;\r\n  double * fsum_l;\r\n  double * fsum_r;\r\n  double * fsum2_l;\r\n  double * fsum2_r;\r\n  size_t * hits_l;\r\n  size_t * hits_r;\r\n} gsl_monte_miser_state; \r\n\r\nGSL_FUN int gsl_monte_miser_integrate(gsl_monte_function * f, \r\n                              const double xl[], const double xh[], \r\n                              size_t dim, size_t calls, \r\n                              gsl_rng *r, \r\n                              gsl_monte_miser_state* state,\r\n                              double *result, double *abserr);\r\n\r\nGSL_FUN gsl_monte_miser_state* gsl_monte_miser_alloc(size_t dim);\r\n\r\nGSL_FUN int gsl_monte_miser_init(gsl_monte_miser_state* state);\r\n\r\nGSL_FUN void gsl_monte_miser_free(gsl_monte_miser_state* state);\r\n\r\ntypedef struct {\r\n  double estimate_frac;\r\n  size_t min_calls;\r\n  size_t min_calls_per_bisection;\r\n  double alpha;\r\n  double dither;\r\n} gsl_monte_miser_params;\r\n\r\nGSL_FUN void gsl_monte_miser_params_get (const gsl_monte_miser_state * state,\r\n\t\t\t\t gsl_monte_miser_params * params);\r\n\r\nGSL_FUN void gsl_monte_miser_params_set (gsl_monte_miser_state * state,\r\n\t\t\t\t const gsl_monte_miser_params * params);\r\n\r\n__END_DECLS\r\n\r\n#endif /* __GSL_MONTE_MISER_H__ */\r\n", "meta": {"hexsha": "2377fc8ca1cb01a658179b5a635b387b4f72baeb", "size": 3050, "ext": "h", "lang": "C", "max_stars_repo_path": "vendor/gsl/gsl/gsl_monte_miser.h", "max_stars_repo_name": "mgreter/astrometrylib", "max_stars_repo_head_hexsha": "ef4d4539a537ab49329b77648aac893d2b4ad318", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z", "max_issues_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_monte_miser.h", "max_issues_repo_name": "zzpwahaha/VimbaCamJILA", "max_issues_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z", "max_forks_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_monte_miser.h", "max_forks_repo_name": "zzpwahaha/VimbaCamJILA", "max_forks_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 28.2407407407, "max_line_length": 82, "alphanum_fraction": 0.6855737705, "num_tokens": 803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.057493282433961186, "lm_q1q2_score": 0.026505367899798134}}
{"text": "/* sort/test.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Thomas Walter, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#include <config.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_test.h>\n#include <gsl/gsl_heapsort.h>\n#include <gsl/gsl_sort.h>\n#include <gsl/gsl_sort_vector.h>\n#include <gsl/gsl_ieee_utils.h>\n\nsize_t urand (size_t);\n\n#include \"test_heapsort.c\"\n\n#define BASE_LONG_DOUBLE\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_LONG_DOUBLE\n\n#define BASE_DOUBLE\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_DOUBLE\n\n#define BASE_FLOAT\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_FLOAT\n\n#define BASE_ULONG\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_ULONG\n\n#define BASE_LONG\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_LONG\n\n#define BASE_UINT\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_UINT\n\n#define BASE_INT\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_INT\n\n#define BASE_USHORT\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_USHORT\n\n#define BASE_SHORT\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_SHORT\n\n#define BASE_UCHAR\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_UCHAR\n\n#define BASE_CHAR\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_CHAR\n\nint\nmain (void)\n{\n  size_t i, s;\n\n  gsl_ieee_env_setup ();\n\n  /* Test for lengths of 1 ... 31, then 32, 64, 128, 256, ... */\n\n  for (i = 1; i < 1024; i = (i < 32) ? i + 1 : 2 * i)\n    test_heapsort (i);\n\n  for (i = 1; i < 1024; i = (i < 32) ? i + 1 : 2 * i)\n    {\n      for (s = 1; s < 4; s++)\n\t{\n\t  test_sort_vector (i, s);\n\t  test_sort_vector_float (i, s);\n\t  test_sort_vector_long_double (i, s);\n\t  test_sort_vector_ulong (i, s);\n\t  test_sort_vector_long (i, s);\n\t  test_sort_vector_uint (i, s);\n\t  test_sort_vector_int (i, s);\n\t  test_sort_vector_ushort (i, s);\n\t  test_sort_vector_short (i, s);\n\t  test_sort_vector_uchar (i, s);\n\t  test_sort_vector_char (i, s);\n\t}\n    }\n\n  exit (gsl_test_summary ());\n}\n\nsize_t \nurand (size_t N)\n{\n  static unsigned long int x = 1;\n  x = (1103515245 * x + 12345) & 0x7fffffffUL;\n  return (size_t) ((x / 2147483648.0) * N);\n}\n", "meta": {"hexsha": "69a568535fd0f0bf729479590a8d340e32eaf81b", "size": 3269, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/sort/test.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/sort/test.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/sort/test.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 23.1843971631, "max_line_length": 72, "alphanum_fraction": 0.7118384827, "num_tokens": 934, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.057493275570541236, "lm_q1q2_score": 0.02650536473564637}}
{"text": "/* ode-initval/evolve.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Author:  G. Jungman\n */\n#include <config.h>\n#include <string.h>\n#include <stdlib.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_odeiv.h>\n\n#include \"odeiv_util.h\"\n\ngsl_odeiv_evolve *\ngsl_odeiv_evolve_alloc (size_t dim)\n{\n  gsl_odeiv_evolve *e =\n    (gsl_odeiv_evolve *) malloc (sizeof (gsl_odeiv_evolve));\n\n  if (e == 0)\n    {\n      GSL_ERROR_NULL (\"failed to allocate space for evolve struct\",\n                      GSL_ENOMEM);\n    }\n\n  e->y0 = (double *) malloc (dim * sizeof (double));\n\n  if (e->y0 == 0)\n    {\n      free (e);\n      GSL_ERROR_NULL (\"failed to allocate space for y0\", GSL_ENOMEM);\n    }\n\n  e->yerr = (double *) malloc (dim * sizeof (double));\n\n  if (e->yerr == 0)\n    {\n      free (e->y0);\n      free (e);\n      GSL_ERROR_NULL (\"failed to allocate space for yerr\", GSL_ENOMEM);\n    }\n\n  e->dydt_in = (double *) malloc (dim * sizeof (double));\n\n  if (e->dydt_in == 0)\n    {\n      free (e->yerr);\n      free (e->y0);\n      free (e);\n      GSL_ERROR_NULL (\"failed to allocate space for dydt_in\", GSL_ENOMEM);\n    }\n\n  e->dydt_out = (double *) malloc (dim * sizeof (double));\n\n  if (e->dydt_out == 0)\n    {\n      free (e->dydt_in);\n      free (e->yerr);\n      free (e->y0);\n      free (e);\n      GSL_ERROR_NULL (\"failed to allocate space for dydt_out\", GSL_ENOMEM);\n    }\n\n  e->dimension = dim;\n  e->count = 0;\n  e->failed_steps = 0;\n  e->last_step = 0.0;\n\n  return e;\n}\n\nint\ngsl_odeiv_evolve_reset (gsl_odeiv_evolve * e)\n{\n  e->count = 0;\n  e->failed_steps = 0;\n  e->last_step = 0.0;\n  return GSL_SUCCESS;\n}\n\nvoid\ngsl_odeiv_evolve_free (gsl_odeiv_evolve * e)\n{\n  RETURN_IF_NULL (e);\n  free (e->dydt_out);\n  free (e->dydt_in);\n  free (e->yerr);\n  free (e->y0);\n  free (e);\n}\n\n/* Evolution framework method.\n *\n * Uses an adaptive step control object\n */\nint\ngsl_odeiv_evolve_apply (gsl_odeiv_evolve * e,\n                        gsl_odeiv_control * con,\n                        gsl_odeiv_step * step,\n                        const gsl_odeiv_system * dydt,\n                        double *t, double t1, double *h, double y[])\n{\n  const double t0 = *t;\n  double h0 = *h;\n  int step_status;\n  int final_step = 0;\n  double dt = t1 - t0;  /* remaining time, possibly less than h */\n\n  if (e->dimension != step->dimension)\n    {\n      GSL_ERROR (\"step dimension must match evolution size\", GSL_EINVAL);\n    }\n\n  if ((dt < 0.0 && h0 > 0.0) || (dt > 0.0 && h0 < 0.0))\n    {\n      GSL_ERROR (\"step direction must match interval direction\", GSL_EINVAL);\n    }\n\n  /* No need to copy if we cannot control the step size. */\n\n  if (con != NULL)\n    {\n      DBL_MEMCPY (e->y0, y, e->dimension);\n    }\n\n  /* Calculate initial dydt once if the method can benefit. */\n\n  if (step->type->can_use_dydt_in)\n    {\n      int status = GSL_ODEIV_FN_EVAL (dydt, t0, y, e->dydt_in);\n\n      if (status) \n        {\n          return status;\n        }\n    }\n\ntry_step:\n    \n  if ((dt >= 0.0 && h0 > dt) || (dt < 0.0 && h0 < dt))\n    {\n      h0 = dt;\n      final_step = 1;\n    }\n  else\n    {\n      final_step = 0;\n    }\n\n  if (step->type->can_use_dydt_in)\n    {\n      step_status =\n        gsl_odeiv_step_apply (step, t0, h0, y, e->yerr, e->dydt_in,\n                              e->dydt_out, dydt);\n    }\n  else\n    {\n      step_status =\n        gsl_odeiv_step_apply (step, t0, h0, y, e->yerr, NULL, e->dydt_out,\n                              dydt);\n    }\n\n  /* Check for stepper internal failure */\n\n  if (step_status != GSL_SUCCESS) \n    {\n      *h = h0;  /* notify user of step-size which caused the failure */\n      *t = t0;  /* restore original t value */\n      return step_status;\n    }\n\n  e->count++;\n  e->last_step = h0;\n\n  if (final_step)\n    {\n      *t = t1;\n    }\n  else\n    {\n      *t = t0 + h0;\n    }\n\n  if (con != NULL)\n    {\n      /* Check error and attempt to adjust the step. */\n\n      double h_old = h0;\n\n      const int hadjust_status \n        = gsl_odeiv_control_hadjust (con, step, y, e->yerr, e->dydt_out, &h0);\n\n      if (hadjust_status == GSL_ODEIV_HADJ_DEC)\n        {\n          /* Check that the reported status is correct (i.e. an actual\n             decrease in h0 occured) and the suggested h0 will change\n             the time by at least 1 ulp */\n\n          double t_curr = GSL_COERCE_DBL(*t);\n          double t_next = GSL_COERCE_DBL((*t) + h0);\n\n          if (fabs(h0) < fabs(h_old) && t_next != t_curr) \n            {\n              /* Step was decreased. Undo step, and try again with new h0. */\n              DBL_MEMCPY (y, e->y0, dydt->dimension);\n              e->failed_steps++;\n              goto try_step;\n            }\n          else\n            {\n              h0 = h_old; /* keep current step size */\n            }\n        }\n    }\n\n  *h = h0;  /* suggest step size for next time-step */\n\n  return step_status;\n}\n", "meta": {"hexsha": "d61842a3dfc6dfb2e862336051ccc8dc116df9ed", "size": 5585, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/ode-initval/evolve.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/ode-initval/evolve.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/ode-initval/evolve.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 23.5654008439, "max_line_length": 81, "alphanum_fraction": 0.5692032229, "num_tokens": 1673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356683938849797, "lm_q2_score": 0.06560483837252304, "lm_q1q2_score": 0.026475937270592373}}
{"text": "/* \n *\n * A cross-platform way of providing access to gsl_ieee_env_setup \n * from Fortran on any system MITgcm runs on currently.\n */\n\n#ifdef USE_GSL_IEEE\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_ieee_utils.h>\n\nvoid fgsl_ieee_env_setup ()\n{\n  gsl_ieee_env_setup ();\n}\n\nvoid fgsl_ieee_env_setup_ ()\n{\n  gsl_ieee_env_setup ();\n}\n\nvoid fgsl_ieee_env_setup__ ()\n{\n  gsl_ieee_env_setup ();\n}\n\nvoid FGSL_IEEE_ENV_SETUP ()\n{\n  gsl_ieee_env_setup ();\n}\n#endif\n", "meta": {"hexsha": "0e3157ddfd5da21dfca2158d055587a62f1b2169", "size": 455, "ext": "c", "lang": "C", "max_stars_repo_path": "eesupp/src/gsl_ieee_env.c", "max_stars_repo_name": "ElizabethYankovsky/MITgcm", "max_stars_repo_head_hexsha": "9e3cbd9dd7b61dbea201517a5c776fc7748f82af", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 247.0, "max_stars_repo_stars_event_min_datetime": "2018-02-07T08:33:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:55:55.000Z", "max_issues_repo_path": "eesupp/src/gsl_ieee_env.c", "max_issues_repo_name": "ElizabethYankovsky/MITgcm", "max_issues_repo_head_hexsha": "9e3cbd9dd7b61dbea201517a5c776fc7748f82af", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 580.0, "max_issues_repo_issues_event_min_datetime": "2018-01-31T21:38:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:43:30.000Z", "max_forks_repo_path": "eesupp/src/gsl_ieee_env.c", "max_forks_repo_name": "ElizabethYankovsky/MITgcm", "max_forks_repo_head_hexsha": "9e3cbd9dd7b61dbea201517a5c776fc7748f82af", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 209.0, "max_forks_repo_forks_event_min_datetime": "2018-01-31T20:58:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T06:24:43.000Z", "avg_line_length": 14.6774193548, "max_line_length": 66, "alphanum_fraction": 0.7252747253, "num_tokens": 132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.06278921473524327, "lm_q1q2_score": 0.026289650150516895}}
{"text": "/**\n * Copyright (c) 2019-2020 The University of Tennessee and The University\n *                         of Tennessee Research Foundation.  All rights\n *                         reserved.\n * Imported from:\n *\n * @file core_blas.h\n *\n *  PLASMA auxiliary routines\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.8.0\n * @author Jakub Kurzak\n * @author Hatem Ltaief\n * @date 2010-11-15\n *\n **/\n#ifndef _PLASMA_CORE_BLAS_H_\n#define _PLASMA_CORE_BLAS_H_\n\n\n#include \"cores/dplasma_plasmatypes.h\"\n#include \"cores/descriptor.h\"\n#include <cblas.h>\n#include <lapacke.h>\n\n#include \"cores/core_zblas.h\"\n#include \"cores/core_dblas.h\"\n#include \"cores/core_cblas.h\"\n#include \"cores/core_sblas.h\"\n#include \"cores/core_zcblas.h\"\n#include \"cores/core_dsblas.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n  /*\n   * Coreblas Error\n   */\n#define coreblas_error(k, str) fprintf(stderr, \"%s: Parameter %d / %s\\n\", __func__, k, str);\n\n/* CBLAS requires for scalar arguments to be passed by address rather than by value */\n#ifndef CBLAS_SADDR\n#define CBLAS_SADDR( _val_ ) &(_val_)\n#endif\n\n /** ****************************************************************************\n  *  External interface of the GKK algorithm for InPlace Layout Translation\n  **/\nint  GKK_minloc(int n, int *T);\nvoid GKK_BalanceLoad(int thrdnbr, int *Tp, int *leaders, int nleaders, int L);\nint  GKK_getLeaderNbr(int me, int ne, int *nleaders, int **leaders);\n\nvoid CORE_pivot_update(int m, int n, int *ipiv, int *indices,\n                       int offset, int init);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* _PLASMA_CORE_BLAS_H_ */\n", "meta": {"hexsha": "b52b461867611b12b580f506c5223640aa14e01c", "size": 1675, "ext": "h", "lang": "C", "max_stars_repo_path": "src/cores/core_blas.h", "max_stars_repo_name": "therault/dplasma", "max_stars_repo_head_hexsha": "fa687f0ceec07f03249217b93e8a707aa9fd8ef3", "max_stars_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-17T19:36:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T19:36:41.000Z", "max_issues_repo_path": "src/cores/core_blas.h", "max_issues_repo_name": "therault/dplasma", "max_issues_repo_head_hexsha": "fa687f0ceec07f03249217b93e8a707aa9fd8ef3", "max_issues_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2022-03-02T21:42:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T15:22:21.000Z", "max_forks_repo_path": "src/cores/core_blas.h", "max_forks_repo_name": "therault/dplasma", "max_forks_repo_head_hexsha": "fa687f0ceec07f03249217b93e8a707aa9fd8ef3", "max_forks_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2022-02-28T21:24:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T01:53:32.000Z", "avg_line_length": 26.171875, "max_line_length": 92, "alphanum_fraction": 0.6555223881, "num_tokens": 453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438006939036565, "lm_q2_score": 0.0541987305870374, "lm_q1q2_score": 0.02625278488261891}}
{"text": "#include <pygsl/solver.h>\n#include <gsl/gsl_multifit_nlin.h>\n\nconst char  * filename = __FILE__;\nPyObject *module = NULL;\nstatic const char multifit_f_type_name[] = \"F-MultiFitSolver\";\nstatic const char multifit_fdf_type_name[] = \"FdF-MultiFitSolver\";\n\n\nstatic int \nPyGSL_multifit_function_wrap(const gsl_vector *x, void *params, gsl_vector *f)\n{\n     PyGSL_solver *self = (PyGSL_solver *) params;\n     return PyGSL_function_wrap_Op_On(x, f, self->cbs[0], self->args, x->size, f->size,\n\t\t\t\t      __FUNCTION__);\n}\n\n\nstatic int \nPyGSL_multifit_function_wrap_df(const gsl_vector *x, void *params, gsl_matrix *df)\n{\n     PyGSL_solver *self = (PyGSL_solver *) params; \n     /* size 1 or size 2 from matrix ? */\n     return PyGSL_function_wrap_Op_Opn(x, df, self->cbs[1], self->args, df->size1, x->size, \n\t\t\t\t       __FUNCTION__);\n}\n\nstatic int \nPyGSL_multifit_function_wrap_fdf(const gsl_vector *x, void *params, gsl_vector *f, gsl_matrix *df)\n{\n     PyGSL_solver *self = (PyGSL_solver *) params;\n     /* size 1 or size 2 from matrix ? */\n     return PyGSL_function_wrap_Op_On_Opn(x, f, df, self->cbs[2], self->args, f->size, x->size, \n\t\t\t\t\t  __FUNCTION__);\n}\n\nstatic PyObject *\nPyGSL_multifit_fdfsolver_set(PyGSL_solver *self, PyObject *pyargs, PyObject *kw)\n{\n\n     gsl_multifit_function_fdf * c_sys;\n     struct pygsl_solver_n_set info = {1, NULL, (set_m_t)gsl_multifit_fdfsolver_set};\n     PyObject * tmp;\n\n     FUNC_MESS_BEGIN();\n     if(self->c_sys == NULL){\t  \n\t  if((c_sys = calloc(1, sizeof(gsl_multifit_function_fdf))) == NULL){\n\t       PyGSL_ERROR_NULL(\"Could not allocate the memory for the c_sys\", GSL_ENOMEM);\n\t  }\t  \n\t  c_sys->n=self->problem_dimensions[1];\n\t  c_sys->p=self->problem_dimensions[0];\n\t  c_sys->f  = PyGSL_multifit_function_wrap;\n\t  c_sys->df = PyGSL_multifit_function_wrap_df;\n\t  c_sys->fdf = PyGSL_multifit_function_wrap_fdf;\n\t  c_sys->params=(void*)self;\n\t  info.c_sys = c_sys;\t  \n     }else{\n\t  info.c_sys = self->c_sys;\n     }\n     tmp =  PyGSL_solver_n_set(self, pyargs, kw, &info);     \n     if(tmp == NULL){\n\t  PyGSL_add_traceback(module, __FILE__, __FUNCTION__, __LINE__ - 2);\n     }\n     FUNC_MESS_END();\n     return tmp;\n}\n\nstatic PyObject*  \nPyGSL_multifit_fdfsolver_position(PyGSL_solver *self, PyObject *args)\n{ \n     return PyGSL_solver_ret_vec(self, args, (ret_vec)gsl_multifit_fdfsolver_position); \n}\nstatic gsl_multifit_fdfsolver *\nPyGSL_get_multifit_solver(PyGSL_solver *self)\n{\n     FUNC_MESS_BEGIN();\n     assert(PyGSL_solver_check(self));     \n     FUNC_MESS_END();\n     return (gsl_multifit_fdfsolver *) (self->solver);\n}\n\nstatic PyObject*  \nPyGSL_multifit_fdfsolver_x(PyGSL_solver *self, PyObject *args)\n{\n     return (PyObject *) PyGSL_copy_gslvector_to_pyarray(PyGSL_get_multifit_solver(self)->x);\n}\n\nstatic PyObject*  \nPyGSL_multifit_fdfsolver_dx(PyGSL_solver *self, PyObject *args)\n{\n     return (PyObject *) PyGSL_copy_gslvector_to_pyarray(PyGSL_get_multifit_solver(self)->dx);\n}\n\nstatic PyObject*  \nPyGSL_multifit_fdfsolver_f(PyGSL_solver *self, PyObject *args)\n{\n     return (PyObject *) PyGSL_copy_gslvector_to_pyarray(PyGSL_get_multifit_solver(self)->f);\n}\n\nstatic PyObject*  \nPyGSL_multifit_fdfsolver_J(PyGSL_solver *self, PyObject *args)\n{\n     return (PyObject *) PyGSL_copy_gslmatrix_to_pyarray(PyGSL_get_multifit_solver(self)->J);\n}\n\nstatic PyObject*  \nPyGSL_multifit_fdfsolver_test_delta(PyGSL_solver *self, PyObject *args)\n{\n     int flag;\n     double epsabs, epsrel;     \n     gsl_multifit_fdfsolver *s = self->solver;     \n     if(!PyArg_ParseTuple(args, \"dd\", &epsabs, &epsrel))\n\t  return NULL;\n     flag = gsl_multifit_test_delta(s->dx, s->x, epsabs, epsrel);\n     return PyGSL_ERROR_FLAG_TO_PYINT(flag);\n}\n\nstatic PyObject*  \nPyGSL_multifit_fdfsolver_test_gradient(PyGSL_solver *self, PyObject *args)\n{\n     int flag;\n     double epsabs;     \n     gsl_vector *g = NULL;\n     gsl_multifit_fdfsolver *s = self->solver;     \n\n     if(!PyArg_ParseTuple(args, \"d\", &epsabs))\n\t  return NULL;\n     flag = gsl_multifit_gradient(s->J, s->f, g);\n     if(PyGSL_ERROR_FLAG(flag) != GSL_SUCCESS)\n\t  return NULL;\n     flag = gsl_multifit_test_gradient(g, epsabs);\n     return PyGSL_ERROR_FLAG_TO_PYINT(flag);\n}\n\nstatic PyMethodDef PyGSL_multifit_fmethods[] = {     \n     {NULL, NULL, 0, NULL}\n};\n\nstatic PyMethodDef PyGSL_multifit_fdfmethods[] = {     \n     {\"J\",    (PyCFunction)PyGSL_multifit_fdfsolver_J,   METH_NOARGS, NULL},\n     {\"dx\",   (PyCFunction)PyGSL_multifit_fdfsolver_dx,   METH_NOARGS, NULL},\n     {\"x\",    (PyCFunction)PyGSL_multifit_fdfsolver_x,   METH_NOARGS, NULL},\n     {\"position\",    (PyCFunction)PyGSL_multifit_fdfsolver_position,   METH_NOARGS, NULL},\n     {\"f\",    (PyCFunction)PyGSL_multifit_fdfsolver_f,    METH_NOARGS, NULL},\n     {\"set\",  (PyCFunction)PyGSL_multifit_fdfsolver_set,  METH_VARARGS|METH_KEYWORDS, NULL},\n     {\"test_delta\",  (PyCFunction)PyGSL_multifit_fdfsolver_test_delta,  METH_VARARGS, NULL},\n     {\"test_gradient\",  (PyCFunction)PyGSL_multifit_fdfsolver_test_gradient,  METH_VARARGS, NULL},\n     {NULL, NULL, 0, NULL}\n};\n\n\n\nconst struct _SolverStatic\nmultifit_solver_f   = {{ (void_m_t) gsl_multifit_fsolver_free,   \n\t\t\t /* gsl_multifit_fsolver_restart */  (void_m_t) NULL,\n\t\t\t (name_m_t) gsl_multifit_fsolver_name,   \n\t\t\t (int_m_t) gsl_multifit_fsolver_iterate},\n\t\t       1, PyGSL_multifit_fmethods, multifit_f_type_name},\nmultifit_solver_fdf = {{(void_m_t) gsl_multifit_fdfsolver_free, \n\t\t     /* gsl_multifit_fdfsolver_restart (void_m_t) */ NULL,\n\t\t     (name_m_t) gsl_multifit_fdfsolver_name, \n\t\t     (int_m_t)  gsl_multifit_fdfsolver_iterate},\n\t\t       3, PyGSL_multifit_fdfmethods, multifit_fdf_type_name};\n\nstatic PyObject* \nPyGSL_multifit_f_init(PyObject *self, PyObject *args, \n\t\t      const gsl_multifit_fsolver_type * type) \n{\n\n     PyObject *tmp=NULL;\n     solver_alloc_struct s = {type, (void_an_t) gsl_multifit_fsolver_alloc,\n\t\t\t      &multifit_solver_f};\n     FUNC_MESS_BEGIN();     \n     tmp = PyGSL_solver_dn_init(self, args, &s, 2);\n     FUNC_MESS_END();     \n     return tmp;\n}\n\nstatic PyObject* \nPyGSL_multifit_fdf_init(PyObject *self, PyObject *args, \n\t\t      const gsl_multifit_fdfsolver_type * type) \n{\n\n     PyObject *tmp=NULL;\n     solver_alloc_struct s = {type, (void_an_t) gsl_multifit_fdfsolver_alloc,\n\t\t\t      &multifit_solver_fdf};\n     FUNC_MESS_BEGIN();     \n     tmp = PyGSL_solver_dn_init(self, args, &s, 2);\n     FUNC_MESS_END();     \n     return tmp;\n}\n\n#define AMFIT_FDF(name)                                                  \\\nstatic PyObject* PyGSL_multifit_init_ ## name (PyObject *self, PyObject *args)\\\n{                                                                             \\\n     PyObject *tmp = NULL;                                                    \\\n     FUNC_MESS_BEGIN();                                                       \\\n     tmp = PyGSL_multifit_fdf_init(self, args,  gsl_multifit_fdfsolver_ ## name); \\\n     if (tmp == NULL){                                                        \\\n\t  PyGSL_add_traceback(module, __FILE__, __FUNCTION__, __LINE__); \\\n     }                                                                        \\\n     FUNC_MESS_END();                                                         \\\n     return tmp;                                                              \\\n}\n\nAMFIT_FDF(lmsder)\nAMFIT_FDF(lmder)\n\nPyObject * \nPyGSL_multifit_gradient(PyObject *self, PyObject *args)\n{\n  PyArrayObject *J_a = NULL, *f_a = NULL, *g_a = NULL;\n  PyObject *J_o = NULL, *f_o = NULL;\n  gsl_vector_view f;\n  gsl_vector_view g;\n  gsl_matrix_view J;\n\n  PyGSL_array_index_t stride_recalc, dimension;\n  int flag;\n\n  if(!PyArg_ParseTuple(args, \"OO:gsl_multifit_gradient\", &J_o, &f_o)){\n       return NULL;\n  }\n\n  J_a = PyGSL_matrix_check(J_o, -1, -1, PyGSL_DARRAY_CINPUT(1), NULL, NULL, NULL);\n  if(J_a == NULL) goto fail;\n\n  dimension = J_a->dimensions[0];\n  /* Numpy calculates strides in bytes, gsl in basis type */\n  f_a = PyGSL_vector_check(f_o, dimension, PyGSL_DARRAY_INPUT(2), &stride_recalc, NULL);\n  if(f_a == NULL) goto fail;\n\n  dimension = J_a->dimensions[1];\n  g_a = (PyArrayObject *) PyGSL_New_Array(1, &dimension, PyArray_DOUBLE);\n  if(g_a == NULL) goto fail;\n\n  J = gsl_matrix_view_array((double *) J_a->data, J_a->dimensions[0], J_a->dimensions[1]);\n  f = gsl_vector_view_array_with_stride((double *) f_a->data, stride_recalc, f_a->dimensions[0]);\n  g = gsl_vector_view_array((double *) g_a->data, dimension);\n  flag = gsl_multifit_gradient(&J.matrix, &f.vector, &g.vector);\n  \n  Py_DECREF(J_a);\n  Py_DECREF(f_a);\n  \n  if((PyGSL_ERROR_FLAG(flag)) != GSL_SUCCESS)\n       goto fail;\n\n  return (PyObject * )g_a;\n\n  fail :\n    Py_XDECREF(J_a);\n    Py_XDECREF(f_a);\n    Py_XDECREF(g_a);\n    return NULL;\n}\n\nPyObject * \nPyGSL_multifit_covar(PyObject *self, PyObject *args)\n{\n  PyArrayObject *J_a = NULL, *C_a = NULL;\n  PyObject *J_o = NULL;\n  gsl_matrix_view J, C;\n  PyGSL_array_index_t dimensions[2];\n  int flag;\n  double epsrel;\n\n\n  if(!PyArg_ParseTuple(args, \"Od:gsl_multifit_covar\", &J_o, &epsrel)){\n    return NULL;\n  }\n\n  J_a = PyGSL_matrix_check(J_o, -1, -1, PyGSL_DARRAY_CINPUT(1), NULL, NULL, NULL);\n  if(J_a == NULL) goto fail;\n\n  dimensions[0] = J_a->dimensions[1];\n  dimensions[1] = J_a->dimensions[1];\n  C_a = (PyArrayObject *) PyGSL_New_Array(2, dimensions, PyArray_DOUBLE);\n  if(C_a == NULL) goto fail;\n\n  J = gsl_matrix_view_array((double *) J_a->data, J_a->dimensions[0], J_a->dimensions[1]);\n  C = gsl_matrix_view_array((double *) C_a->data, C_a->dimensions[0], C_a->dimensions[1]);\n  \n  flag = gsl_multifit_covar(&J.matrix, epsrel, &C.matrix);\n  \n  Py_DECREF(J_a);\n  if((PyGSL_ERROR_FLAG(flag)) != GSL_SUCCESS)\n       goto fail;\n  return (PyObject * )C_a;\n\n  fail :\n    Py_XDECREF(J_a);\n    Py_XDECREF(C_a);\n    return NULL;\n}\n\nstatic PyObject *\nPyGSL_multifit_test_delta(PyObject * self, PyObject * args)\n{\n     return PyGSL_solver_vvdd_i(self, args, gsl_multifit_test_delta);     \n}\n\nstatic PyObject *\nPyGSL_multifit_test_gradient(PyObject * self, PyObject * args)\n{\n     return PyGSL_solver_vd_i(self, args, gsl_multifit_test_gradient);     \n}\n\nstatic PyMethodDef mMethods[] = {\n     /* multifit solvers */\n     {\"lmder\",          PyGSL_multifit_init_lmder,  METH_VARARGS, NULL},\n     {\"lmsder\",          PyGSL_multifit_init_lmsder,  METH_VARARGS, NULL},\n     /* multifit funcs */\n     {\"fit_test_delta\",    PyGSL_multifit_test_delta,     METH_VARARGS, NULL},\n     {\"fit_test_gradient\", PyGSL_multifit_test_gradient,  METH_VARARGS, NULL},\n     {\"gradient\",          PyGSL_multifit_gradient,  METH_VARARGS, NULL},\n     {\"covar\",             PyGSL_multifit_covar,  METH_VARARGS, NULL},\n     {NULL, NULL, 0, NULL}\n};\n\nstatic const char PyGSL_multifit_nlin_module_doc[] = \"XXX Missing \\n\";\nvoid\ninitmultifit_nlin(void)\n{\n     PyObject* m, *dict, *item;\n     FUNC_MESS_BEGIN();\n\n     m=Py_InitModule(\"multifit_nlin\", mMethods);\n     module = m;\n     assert(m);\n     dict = PyModule_GetDict(m);\n     if(!dict)\n\t  goto fail;\n\n     init_pygsl()\n     import_pygsl_solver();\n     assert(PyGSL_API);\n\n\n     if (!(item = PyString_FromString((char*)PyGSL_multifit_nlin_module_doc))){\n\t  PyErr_SetString(PyExc_ImportError, \n\t\t\t  \"I could not generate module doc string!\");\n\t  goto fail;\n     }\n     if (PyDict_SetItemString(dict, \"__doc__\", item) != 0){\n\t  PyErr_SetString(PyExc_ImportError, \n\t\t\t  \"I could not init doc string!\");\n\t  goto fail;\n     }\n     \n     FUNC_MESS_END();\n     return;\n\n fail:\n     FUNC_MESS(\"FAIL\");\n     return;\n}\n", "meta": {"hexsha": "02357debe69250b124a0864727338f025b823d56", "size": 11430, "ext": "c", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/testing/src/solvers/multifit_nlin.c", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/testing/src/solvers/multifit_nlin.c", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/testing/src/solvers/multifit_nlin.c", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 32.0168067227, "max_line_length": 98, "alphanum_fraction": 0.663079615, "num_tokens": 3369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657966593214324, "lm_q2_score": 0.055005286357059216, "lm_q1q2_score": 0.026214400996549158}}
{"text": "\n// Copyright (C) 2021 Intel Corporation\n// SPDX-License-Identifier: Apache-2.0\n\n#ifndef _HEBench_ClearText_EltAdd_H_7e5fa8c2415240ea93eff148ed73539b\n#define _HEBench_ClearText_EltAdd_H_7e5fa8c2415240ea93eff148ed73539b\n\n#include <gsl/gsl>\n\n#include \"hebench/api_bridge/cpp/hebench.hpp\"\n\n#include \"clear_benchmark.h\"\n\ntemplate <class T>\nclass EltAdd_Benchmark : public ClearTextBenchmark\n{\nprivate:\n    HEBERROR_DECLARE_CLASS_NAME(EltAdd_Benchmark)\n\npublic:\n    EltAdd_Benchmark(hebench::cpp::BaseEngine &engine,\n                     const hebench::APIBridge::BenchmarkDescriptor &bench_desc,\n                     const hebench::APIBridge::WorkloadParams &bench_params);\n    ~EltAdd_Benchmark() override;\n\n    hebench::APIBridge::Handle encode(const hebench::APIBridge::DataPackCollection *p_parameters) override;\n    void decode(hebench::APIBridge::Handle encoded_data, hebench::APIBridge::DataPackCollection *p_native) override;\n\n    hebench::APIBridge::Handle load(const hebench::APIBridge::Handle *p_local_data, std::uint64_t count) override;\n    void store(hebench::APIBridge::Handle remote_data,\n               hebench::APIBridge::Handle *p_local_data, std::uint64_t count) override;\n\n    hebench::APIBridge::Handle operate(hebench::APIBridge::Handle h_remote_packed,\n                                       const hebench::APIBridge::ParameterIndexer *p_param_indexers) override;\n\nprotected:\n    std::uint64_t m_vector_size;\n\nprivate:\n    static void eltAdd(gsl::span<T> &result,\n                       const gsl::span<const T> &M0, const gsl::span<const T> &M1,\n                       std::size_t element_count);\n};\n\n#include \"inl/bench_eltadd.inl\"\n\n#endif // defined _HEBench_ClearText_EltAdd_H_7e5fa8c2415240ea93eff148ed73539b\n", "meta": {"hexsha": "07934aa3a428c0d3c7790bb28a6c541f49aa16c8", "size": 1734, "ext": "h", "lang": "C", "max_stars_repo_path": "benchmarks/Vector/EltwiseAdd/include/bench_eltadd.h", "max_stars_repo_name": "hebench/backend-cpu-cleartext", "max_stars_repo_head_hexsha": "83e4398d9271f3e077bb4dfc0a8fb04ce36e23f6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-28T17:57:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T17:57:32.000Z", "max_issues_repo_path": "benchmarks/Vector/EltwiseAdd/include/bench_eltadd.h", "max_issues_repo_name": "hebench/backend-cpu-cleartext", "max_issues_repo_head_hexsha": "83e4398d9271f3e077bb4dfc0a8fb04ce36e23f6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-12-06T19:37:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-16T23:37:53.000Z", "max_forks_repo_path": "benchmarks/Vector/EltwiseAdd/include/bench_eltadd.h", "max_forks_repo_name": "hebench/backend-cpu-cleartext", "max_forks_repo_head_hexsha": "83e4398d9271f3e077bb4dfc0a8fb04ce36e23f6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-05T18:01:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-05T18:01:48.000Z", "avg_line_length": 36.125, "max_line_length": 116, "alphanum_fraction": 0.7312572088, "num_tokens": 464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.0534033311180551, "lm_q1q2_score": 0.026075959838431646}}
{"text": "/* spoper.c\n * \n * Copyright (C) 2012 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <stdlib.h>\n#include <math.h>\n\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_spmatrix.h>\n#include <gsl/gsl_spblas.h>\n\nint\ngsl_spmatrix_scale(gsl_spmatrix *m, const double x)\n{\n  size_t i;\n\n  for (i = 0; i < m->nz; ++i)\n    m->data[i] *= x;\n\n  return GSL_SUCCESS;\n} /* gsl_spmatrix_scale() */\n\nint\ngsl_spmatrix_minmax(const gsl_spmatrix *m, double *min_out, double *max_out)\n{\n  double min, max;\n  size_t n;\n\n  if (m->nz == 0)\n    {\n      GSL_ERROR(\"matrix is empty\", GSL_EINVAL);\n    }\n\n  min = m->data[0];\n  max = m->data[0];\n\n  for (n = 1; n < m->nz; ++n)\n    {\n      double x = m->data[n];\n\n      if (x < min)\n        min = x;\n\n      if (x > max)\n        max = x;\n    }\n\n  *min_out = min;\n  *max_out = max;\n\n  return GSL_SUCCESS;\n} /* gsl_spmatrix_minmax() */\n\n/*\ngsl_spmatrix_add()\n  Add two sparse matrices\n\nInputs: c - (output) a + b\n        a - (input) sparse matrix\n        b - (input) sparse matrix\n\nReturn: success or error\n*/\n\nint\ngsl_spmatrix_add(gsl_spmatrix *c, const gsl_spmatrix *a,\n                 const gsl_spmatrix *b)\n{\n  const size_t M = a->size1;\n  const size_t N = a->size2;\n\n  if (b->size1 != M || b->size2 != N || c->size1 != M || c->size2 != N)\n    {\n      GSL_ERROR(\"matrices must have same dimensions\", GSL_EBADLEN);\n    }\n  else if (a->sptype != b->sptype || a->sptype != c->sptype)\n    {\n      GSL_ERROR(\"matrices must have same sparse storage format\",\n                GSL_EINVAL);\n    }\n  else if (GSL_SPMATRIX_ISTRIPLET(a))\n    {\n      GSL_ERROR(\"triplet format not yet supported\", GSL_EINVAL);\n    }\n  else\n    {\n      int status = GSL_SUCCESS;\n      size_t *w = (size_t *) a->work;\n      double *x = (double *) b->work;\n      size_t *Cp, *Ci;\n      double *Cd;\n      size_t j, p;\n      size_t nz = 0; /* number of non-zeros in c */\n      size_t inner_size, outer_size;\n\n      if (GSL_SPMATRIX_ISCCS(a))\n        {\n          inner_size = M;\n          outer_size = N;\n        }\n      else if (GSL_SPMATRIX_ISCRS(a))\n        {\n          inner_size = N;\n          outer_size = M;\n        }\n      else\n        {\n          GSL_ERROR(\"unknown sparse matrix type\", GSL_EINVAL);\n        }\n\n      if (c->nzmax < a->nz + b->nz)\n        {\n          status = gsl_spmatrix_realloc(a->nz + b->nz, c);\n          if (status)\n            return status;\n        }\n\n      /* initialize w = 0 */\n      for (j = 0; j < inner_size; ++j)\n        w[j] = 0;\n\n      Ci = c->i;\n      Cp = c->p;\n      Cd = c->data;\n\n      for (j = 0; j < outer_size; ++j)\n        {\n          Cp[j] = nz;\n\n          /* CCS: x += A(:,j); CRS: x += A(j,:) */\n          nz = gsl_spblas_scatter(a, j, 1.0, w, x, j + 1, c, nz);\n\n          /* CCS: x += B(:,j); CRS: x += B(j,:) */\n          nz = gsl_spblas_scatter(b, j, 1.0, w, x, j + 1, c, nz);\n\n          for (p = Cp[j]; p < nz; ++p)\n            Cd[p] = x[Ci[p]];\n        }\n\n      /* finalize last column of c */\n      Cp[j] = nz;\n      c->nz = nz;\n\n      return status;\n    }\n} /* gsl_spmatrix_add() */\n\n/*\ngsl_spmatrix_d2sp()\n  Convert a dense gsl_matrix to sparse (triplet) format\n\nInputs: S - (output) sparse matrix in triplet format\n        A - (input) dense matrix to convert\n*/\n\nint\ngsl_spmatrix_d2sp(gsl_spmatrix *S, const gsl_matrix *A)\n{\n  int s = GSL_SUCCESS;\n  size_t i, j;\n\n  gsl_spmatrix_set_zero(S);\n  S->size1 = A->size1;\n  S->size2 = A->size2;\n\n  for (i = 0; i < A->size1; ++i)\n    {\n      for (j = 0; j < A->size2; ++j)\n        {\n          double x = gsl_matrix_get(A, i, j);\n\n          if (x != 0.0)\n            gsl_spmatrix_set(S, i, j, x);\n        }\n    }\n\n  return s;\n} /* gsl_spmatrix_d2sp() */\n\n/*\ngsl_spmatrix_sp2d()\n  Convert a sparse matrix to dense format\n*/\n\nint\ngsl_spmatrix_sp2d(gsl_matrix *A, const gsl_spmatrix *S)\n{\n  if (A->size1 != S->size1 || A->size2 != S->size2)\n    {\n      GSL_ERROR(\"matrix sizes do not match\", GSL_EBADLEN);\n    }\n  else\n    {\n      gsl_matrix_set_zero(A);\n\n      if (GSL_SPMATRIX_ISTRIPLET(S))\n        {\n          size_t n;\n\n          for (n = 0; n < S->nz; ++n)\n            {\n              size_t i = S->i[n];\n              size_t j = S->p[n];\n              double x = S->data[n];\n\n              gsl_matrix_set(A, i, j, x);\n            }\n        }\n      else\n        {\n          GSL_ERROR(\"non-triplet formats not yet supported\", GSL_EINVAL);\n        }\n\n      return GSL_SUCCESS;\n    }\n} /* gsl_spmatrix_sp2d() */\n", "meta": {"hexsha": "07268c18b5547dc3c8fb8e964010f63d1117f2e6", "size": 5172, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.4/spmatrix/spoper.c", "max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-13T05:01:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-13T05:01:59.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/spmatrix/spoper.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/spmatrix/spoper.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0085106383, "max_line_length": 81, "alphanum_fraction": 0.5442768755, "num_tokens": 1610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.054198729441259676, "lm_q1q2_score": 0.02604133387381263}}
{"text": "/* ieee-utils/env.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#include <config.h>\n#include <stdlib.h>\n#include <gsl/gsl_ieee_utils.h>\n#include <gsl/gsl_errno.h>\n\nvoid\ngsl_ieee_env_setup (void)\n{\n  const char * p = getenv(\"GSL_IEEE_MODE\") ;\n\n  int precision = 0, rounding = 0, exception_mask = 0 ;\n\n  int comma = 0 ;\n\n  if (p == 0)  /* GSL_IEEE_MODE environment variable is not set */\n    return ;\n\n  if (*p == '\\0') /* GSL_IEEE_MODE environment variable is empty */\n    return ;\n\n  gsl_ieee_read_mode_string (p, &precision, &rounding, &exception_mask) ;\n\n  gsl_ieee_set_mode (precision, rounding, exception_mask) ;\n  \n  fprintf(stderr, \"GSL_IEEE_MODE=\\\"\") ;\n\n  /* Print string with a preceeding comma if the list has already begun */\n\n#define PRINTC(x) do {if(comma) fprintf(stderr,\",\"); fprintf(stderr,x); comma++ ;} while(0)\n  \n  switch (precision) \n    {\n    case GSL_IEEE_SINGLE_PRECISION:\n      PRINTC(\"single-precision\") ;\n      break ;\n    case GSL_IEEE_DOUBLE_PRECISION:\n      PRINTC(\"double-precision\") ;\n      break ;\n    case GSL_IEEE_EXTENDED_PRECISION:\n      PRINTC(\"extended-precision\") ;\n      break ;\n    }\n\n  switch (rounding) \n    {\n    case GSL_IEEE_ROUND_TO_NEAREST:\n      PRINTC(\"round-to-nearest\") ;\n      break ;\n    case GSL_IEEE_ROUND_DOWN:\n      PRINTC(\"round-down\") ;\n      break ;\n    case GSL_IEEE_ROUND_UP:\n      PRINTC(\"round-up\") ;\n      break ;\n    case GSL_IEEE_ROUND_TO_ZERO:\n      PRINTC(\"round-to-zero\") ;\n      break ;\n    }\n\n  if ((exception_mask & GSL_IEEE_MASK_ALL) == GSL_IEEE_MASK_ALL)\n    {\n      PRINTC(\"mask-all\") ;\n    }\n  else if ((exception_mask & GSL_IEEE_MASK_ALL) == 0)\n    {\n      PRINTC(\"trap-common\") ;\n    }\n  else \n    {\n      if (exception_mask & GSL_IEEE_MASK_INVALID)\n\tPRINTC(\"mask-invalid\") ;\n      \n      if (exception_mask & GSL_IEEE_MASK_DENORMALIZED)\n\tPRINTC(\"mask-denormalized\") ;\n      \n      if (exception_mask & GSL_IEEE_MASK_DIVISION_BY_ZERO)\n\tPRINTC(\"mask-division-by-zero\") ;\n      \n      if (exception_mask & GSL_IEEE_MASK_OVERFLOW)\n\tPRINTC(\"mask-overflow\") ;\n      \n      if (exception_mask & GSL_IEEE_MASK_UNDERFLOW)\n\tPRINTC(\"mask-underflow\") ;\n    }\n\n  if (exception_mask & GSL_IEEE_TRAP_INEXACT)\n    PRINTC(\"trap-inexact\") ;\n  \n  fprintf(stderr,\"\\\"\\n\") ;\n}\n\n\n\n\n\n", "meta": {"hexsha": "28eeb4997fe4baeb40857fda8dce4ac5127cd27f", "size": 2967, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/ieee-utils/env.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/ieee-utils/env.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/ieee-utils/env.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 25.8, "max_line_length": 91, "alphanum_fraction": 0.6643073812, "num_tokens": 802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.055005285969780236, "lm_q1q2_score": 0.02600008980469684}}
{"text": "/* This library is used by compare_hashes_* tests.\n */\n\n#ifndef COMPARISON_STATS_H\n#define COMPARISON_STATS_H\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdint.h>\n#include <gsl/gsl_sf_log.h>\n#include <gsl/gsl_math.h>\n\nstruct comparison_stats {\n\tuint64_t *ones_count;\n\tuint64_t tot_count;\n\tuint hash_width;\n\tuint64_t (*calc_hash)(void *hash_info, unsigned char *str, unsigned length);\n\tvoid *hash_info;\n};\n\ntypedef enum {\n\treport_type_short,\n\treport_type_long } report_type;\n\nvoid basic_init_comparison_stats(struct comparison_stats *cs, uint width);\nvoid process_comparison_stats(struct comparison_stats *cs, unsigned char *str, unsigned sz);\nvoid report_comparison_stats(struct comparison_stats *cs, const char *name, report_type rtyp);\nvoid free_comparison_stats(struct comparison_stats *cs);\n\n#endif\n\n", "meta": {"hexsha": "611d35da6d543826bf1115c74fe0d197adddcdc3", "size": 831, "ext": "h", "lang": "C", "max_stars_repo_path": "tests/entropy_tests/comparison_stats.h", "max_stars_repo_name": "jonkanderson/BitBalancedTableHash", "max_stars_repo_head_hexsha": "dc103a67d0826f09b07196217f00a454441d5011", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/entropy_tests/comparison_stats.h", "max_issues_repo_name": "jonkanderson/BitBalancedTableHash", "max_issues_repo_head_hexsha": "dc103a67d0826f09b07196217f00a454441d5011", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/entropy_tests/comparison_stats.h", "max_forks_repo_name": "jonkanderson/BitBalancedTableHash", "max_forks_repo_head_hexsha": "dc103a67d0826f09b07196217f00a454441d5011", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1818181818, "max_line_length": 94, "alphanum_fraction": 0.7870036101, "num_tokens": 190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.057493273551888456, "lm_q1q2_score": 0.02561495143347583}}
{"text": "/* ******************************************************************************\n *\n *\n * This program and the accompanying materials are made available under the\n * terms of the Apache License, Version 2.0 which is available at\n * https://www.apache.org/licenses/LICENSE-2.0.\n *\n *  See the NOTICE file distributed with this work for additional\n *  information regarding copyright ownership.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations\n * under the License.\n *\n * SPDX-License-Identifier: Apache-2.0\n ******************************************************************************/\n\n//\n// Created by agibsonccc on 2/6/16.\n//\n\n#ifndef NATIVEOPERATIONS_CBLAS_ENUM_CONVERSION_H_H\n#define NATIVEOPERATIONS_CBLAS_ENUM_CONVERSION_H_H\n#include <cblas.h>\n\n/*\nenum CBLAS_ORDER {CblasRowMajor=101, CblasColMajor=102 };\nenum CBLAS_TRANSPOSE {CblasNoTrans=111, CblasTrans=112, CblasConjTrans=113,\n    AtlasConj=114};\nenum CBLAS_UPLO  {CblasUpper=121, CblasLower=122};\nenum CBLAS_DIAG  {CblasNonUnit=131, CblasUnit=132};\nenum CBLAS_SIDE  {CblasLeft=141, CblasRight=142};\n*/\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n/**\n * Converts a character\n * to its proper enum\n * for row (c) or column (f) ordering\n * default is row major\n */\nCBLAS_ORDER convertOrder(int from);\n/**\n * Converts a character to its proper enum\n * t -> transpose\n * n -> no transpose\n * c -> conj\n */\nCBLAS_TRANSPOSE convertTranspose(int from);\n/**\n * Upper or lower\n * U/u -> upper\n * L/l -> lower\n *\n * Default is upper\n */\nCBLAS_UPLO convertUplo(int from);\n\n/**\n * For diagonals:\n * u/U -> unit\n * n/N -> non unit\n *\n * Default: unit\n */\nCBLAS_DIAG convertDiag(int from);\n/**\n * Side of a matrix, left or right\n * l /L -> left\n * r/R -> right\n * default: left\n */\nCBLAS_SIDE convertSide(int from);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif  // NATIVEOPERATIONS_CBLAS_ENUM_CONVERSION_H_H\n", "meta": {"hexsha": "4e20d282281a725dc513d53e88061fba1053137a", "size": 2096, "ext": "h", "lang": "C", "max_stars_repo_path": "libnd4j/include/cblas_enum_conversion.h", "max_stars_repo_name": "steljord2/deeplearning4j", "max_stars_repo_head_hexsha": "4653c97a713cc59e41d4313ddbafc5ff527f8714", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2206.0, "max_stars_repo_stars_event_min_datetime": "2019-06-12T18:57:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T08:14:27.000Z", "max_issues_repo_path": "libnd4j/include/cblas_enum_conversion.h", "max_issues_repo_name": "steljord2/deeplearning4j", "max_issues_repo_head_hexsha": "4653c97a713cc59e41d4313ddbafc5ff527f8714", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1685.0, "max_issues_repo_issues_event_min_datetime": "2019-06-12T17:41:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T21:45:15.000Z", "max_forks_repo_path": "libnd4j/include/cblas_enum_conversion.h", "max_forks_repo_name": "steljord2/deeplearning4j", "max_forks_repo_head_hexsha": "4653c97a713cc59e41d4313ddbafc5ff527f8714", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 572.0, "max_forks_repo_forks_event_min_datetime": "2019-06-12T22:13:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T16:46:46.000Z", "avg_line_length": 25.2530120482, "max_line_length": 81, "alphanum_fraction": 0.6688931298, "num_tokens": 534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39606816627404173, "lm_q2_score": 0.06465348880678597, "lm_q1q2_score": 0.025607188754923}}
{"text": "/* Copyright (c) 2011-2012, J\u00e9r\u00e9my Fix. All rights reserved. */\n\n/* Redistribution and use in source and binary forms, with or without */\n/* modification, are permitted provided that the following conditions are met: */\n\n/* * Redistributions of source code must retain the above copyright notice, */\n/* this list of conditions and the following disclaimer. */\n/* * Redistributions in binary form must reproduce the above copyright notice, */\n/* this list of conditions and the following disclaimer in the documentation */\n/* and/or other materials provided with the distribution. */\n/* * None of the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. */\n\n/* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS \"AS IS\" AND */\n/* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */\n/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */\n/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE */\n/* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL */\n/* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR */\n/* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER */\n/* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, */\n/* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE */\n/* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */\n\n#ifndef UKF_SAMPLES_H\n#define UKF_SAMPLES_H\n\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_sort_vector_double.h>\n#include <gsl/gsl_permute_vector.h>\n#include <gsl/gsl_randist.h>\n\n#include <time.h>\n\n#include <iostream>\n\nnamespace ukf\n{\n    namespace samples\n    {\n        /**\n          * @short Generate 1D samples according to a uniform distribution :\n          * @brief In fact, gsl_ran_choose would do the job!!\n          */\n        class RandomSample_1D\n        {\n        public:\n            static void generateSample(gsl_vector * samples, unsigned int nb_samples, double min, double max, double delta)\n            {\n                if(samples->size != nb_samples)\n                {\n                    std::cerr << \"[ERROR] RandomSample_1D : samples should be allocated to the size of the requested number of samples\" << std::endl;\n                    return;\n                }\n\n\n                for(unsigned int i = 0 ; i < nb_samples ; i++)\n                    gsl_vector_set(samples, i, min + floor((max - min)*rand()/double(RAND_MAX)/delta)    * delta  );\n            }\n        };\n\n        /**\n          * @short Generate 2D samples according to a uniform distribution\n          * and put them alternativaly at the odd/even positions\n          */\n        class RandomSample_2D\n        {\n        public:\n            static void generateSample(gsl_vector * samples, unsigned int nb_samples, double minx, double maxx, double deltax, double miny, double maxy, double deltay)\n            {\n                if(samples->size != 2*nb_samples)\n                {\n                    std::cerr << \"[ERROR] RandomSample_2D : samples should be allocated to the size of the 2 times the requested number of samples\" << std::endl;\n                    return;\n                }\n\t\tgsl_vector_view vec_view = gsl_vector_subvector_with_stride (samples, 0, 2, nb_samples);\n                RandomSample_1D::generateSample(&vec_view.vector, nb_samples, minx, maxx, deltax);\n\t\tvec_view = gsl_vector_subvector_with_stride (samples, 1, 2, nb_samples);\n                RandomSample_1D::generateSample(&vec_view.vector, nb_samples, miny, maxy, deltay);\n            }\n        };\n\n        /**\n          * @short Generate 3D samples according to a uniform distribution\n          * and put them alternativaly at the odd/even positions\n          */\n        class RandomSample_3D\n        {\n        public:\n            static void generateSample(gsl_vector * samples, unsigned int nb_samples, double minx, double maxx, double deltax, double miny, double maxy, double deltay, double minz, double maxz, double deltaz)\n            {\n                if(samples->size != 3*nb_samples)\n                {\n                    std::cerr << \"[ERROR] RandomSample_2D : samples should be allocated to the size of the 2 times the requested number of samples\" << std::endl;\n                    return;\n                }\n\t\tgsl_vector_view vec_view = gsl_vector_subvector_with_stride (samples, 0, 3, nb_samples);\n                RandomSample_1D::generateSample(&vec_view.vector, nb_samples, minx, maxx, deltax);\n\t\tvec_view = gsl_vector_subvector_with_stride (samples, 1, 3, nb_samples);\n                RandomSample_1D::generateSample(&vec_view.vector, nb_samples, miny, maxy, deltay);\n\t\tvec_view = gsl_vector_subvector_with_stride (samples, 2, 3, nb_samples);\n                RandomSample_1D::generateSample(&vec_view.vector, nb_samples, minz, maxz, deltaz);\n            }\n        };\n\n        /**\n          * @short Extract the indexes of the nb_samples highest values of a vector\n          * Be carefull, this function is extracting the indexes as, the way it is used, it doesn't not to which sample a vector index corresponds\n          */\n        class MaximumIndexes_1D\n        {\n        public:\n            static void generateSample(gsl_vector * v, gsl_vector * indexes_samples, unsigned int nb_samples)\n            {\n                if(indexes_samples->size != nb_samples)\n                {\n                    std::cerr << \"[ERROR] MaximumIndexes_1D : samples should be allocated to the size of the requested number of samples\" << std::endl;\n                    return;\n                }\n                if(nb_samples > v->size)\n                {\n                    std::cerr << \"[ERROR] MaximumIndexes_1D : the vector v must hold at least nb_samples elements\" << std::endl;\n                    return;\n                }\n\n                gsl_permutation * p = gsl_permutation_alloc(v->size);\n                gsl_sort_vector_index(p,v);\n                for(unsigned int i = 0 ; i < nb_samples ; i++)\n                    gsl_vector_set(indexes_samples, i, gsl_permutation_get(p, p->size - i - 1));\n                gsl_permutation_free(p);\n            }\n        };\n\n        /**\n          * @short Extract the indexes of the nb_samples highest values of a matrix\n          * Be carefull, this function is extracting the indexes as, the way it is used, it doesn't not to which sample a vector index corresponds\n          */\n        class MaximumIndexes_2D\n        {\n        public:\n            static void generateSample(gsl_matrix * m, gsl_vector * indexes_samples, unsigned int nb_samples)\n            {\n\n                if(indexes_samples->size != 2*nb_samples)\n                {\n                    std::cerr << \"[ERROR] MaximumIndexes_2D : samples should be allocated to the size of 2 times the requested number of samples\" << std::endl;\n                    return;\n                }\n                if(nb_samples > m->size1 * m->size2 )\n                {\n                    std::cerr << \"[ERROR] MaximumIndexes_2D : the vector v must hold at least nb_samples elements\" << std::endl;\n                    return;\n                }\n\n                gsl_permutation * p = gsl_permutation_alloc(m->size1 * m->size2);\n                // We cast the matrix in a vector ordered in row-major and get the permutation to order the data by increasing value\n\t\tgsl_vector_view vec_view = gsl_vector_view_array(m->data,m->size1 * m->size2);\n                gsl_sort_vector_index(p,&vec_view.vector);\n\n                // The indexes stored in p are in row-major order\n                // we then convert the nb_samples first indexes into matrix indexes and copy them in indexes_samples\n                int k,l;\n                for(unsigned int i = 0 ; i < nb_samples ; i++)\n                {\n                    // Line\n                    k = gsl_permutation_get(p,p->size - i - 1) / m->size2;\n                    // Column\n                    l = gsl_permutation_get(p,p->size - i - 1) % m->size2;\n                    gsl_vector_set(indexes_samples, 2 * i, k);\n                    gsl_vector_set(indexes_samples, 2 * i + 1, l);\n                }\n\n                gsl_permutation_free(p);\n            }\n        };\n\n        /**\n          * @short Generate 1D samples according to a discrete vectorial distribution\n          */\n        class DistributionSample_1D\n        {\n        public:\n            static void generateSample(gsl_vector * v, gsl_vector * indexes_samples, unsigned int nb_samples)\n            {\n                if(indexes_samples->size != nb_samples)\n                {\n                    std::cerr << \"[ERROR] RandomSample_1D : samples should be allocated to the size of the requested number of samples\" << std::endl;\n                    return;\n                }\n\n                // Generating nb_samples samples from an array of weights for each index is easily done in the gsl with gsl_ran_discrete_* methods\n                // the weights v do not need to add up to one\n                gsl_rng * r = gsl_rng_alloc(gsl_rng_default);\n                // Init the random seed\n                gsl_rng_set(r, time(NULL));\n                gsl_ran_discrete_t * ran_pre = gsl_ran_discrete_preproc(v->size, v->data);\n\n                for(unsigned int i = 0 ; i < nb_samples ; i++)\n                    gsl_vector_set(indexes_samples, i , gsl_ran_discrete(r, ran_pre));\n\n                gsl_ran_discrete_free(ran_pre);\n                gsl_rng_free(r);\n            }\n        };\n\n        /**\n          * @short Generate 2D samples according to a discrete matricial distribution\n          */\n        class DistributionSample_2D\n        {\n        public:\n            static void generateSample(gsl_matrix * m, gsl_vector * indexes_samples, unsigned int nb_samples)\n            {\n                if(indexes_samples->size != 2*nb_samples)\n                {\n                    std::cerr << \"[ERROR] RandomSample_1D : samples should be allocated to the size of the requested number of samples\" << std::endl;\n                    return;\n                }\n\n                // To generate 2D samples according to a matrix of weights\n                // we simply cast the matrix into a vector, ask DistributionSample_1D to do the job\n                // and then convert the linear row-major indexes back into 2D indexes\n\n                gsl_vector * samples_tmp = gsl_vector_alloc(nb_samples);\n\t\tgsl_vector_view vec_view = gsl_vector_view_array(m->data,m->size1 * m->size2);\n                DistributionSample_1D::generateSample(&vec_view.vector, samples_tmp, nb_samples);\n\n                int k,l;\n                for(unsigned int i = 0 ; i < nb_samples ; i++)\n                {\n                    k = int(gsl_vector_get(samples_tmp,i)) / m->size2;\n                    l = int(gsl_vector_get(samples_tmp,i)) % m->size2;\n                    gsl_vector_set(indexes_samples, 2*i, k);\n                    gsl_vector_set(indexes_samples, 2*i+1, l);\n                }\n\n                gsl_vector_free(samples_tmp);\n            }\n        };\n    }\n}\n\n\n#endif // UKF_SAMPLES_H\n", "meta": {"hexsha": "e5afd0e7f5115350ab7e0f81e0677ec4f24e3f47", "size": 11226, "ext": "h", "lang": "C", "max_stars_repo_path": "src/ukf_samples.h", "max_stars_repo_name": "bahia14/C-Kalman-filtering", "max_stars_repo_head_hexsha": "7c01a11359bdd2e2b89ae8a8de88db215d8e061a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 101.0, "max_stars_repo_stars_event_min_datetime": "2015-01-07T05:30:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T15:24:07.000Z", "max_issues_repo_path": "src/ukf_samples.h", "max_issues_repo_name": "bahia14/C-Kalman-filtering", "max_issues_repo_head_hexsha": "7c01a11359bdd2e2b89ae8a8de88db215d8e061a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-10-16T10:29:05.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-17T21:45:18.000Z", "max_forks_repo_path": "src/ukf_samples.h", "max_forks_repo_name": "bahia14/C-Kalman-filtering", "max_forks_repo_head_hexsha": "7c01a11359bdd2e2b89ae8a8de88db215d8e061a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 52.0, "max_forks_repo_forks_event_min_datetime": "2015-03-10T01:02:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T02:47:35.000Z", "avg_line_length": 45.6341463415, "max_line_length": 208, "alphanum_fraction": 0.5905932656, "num_tokens": 2424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.053403334319473035, "lm_q1q2_score": 0.02545094243561129}}
{"text": "/**\n * @file      MeshAdaptors.h\n *\n * @brief     This file contains mesh <-> Eigen matrix adaptors\n *\n * @author    Stefan Reinhold\n * @copyright Copyright (C) 2018 Stefan Reinhold  -- All Rights Reserved.\n *            You may use, distribute and modify this code under the terms of\n *            the AFL 3.0 license; see LICENSE for full license details.\n */\n\n#pragma once\n\n#include \"Mesh.h\"\n\n#include <Eigen/Core>\n#include <gsl/gsl>\n\nnamespace CortidQCT {\nnamespace Internal {\nnamespace Adaptor {\n\ntemplate <class T>\ninline Eigen::Map<Eigen::Matrix<T, 3, Eigen::Dynamic> const>\nvertexMap(Mesh<T> const &mesh) {\n  return mesh.withUnsafeVertexPointer([&mesh](auto const *ptr) {\n    return Eigen::Map<Eigen::Matrix<T, 3, Eigen::Dynamic> const>{\n        ptr, 3, gsl::narrow_cast<Eigen::Index>(mesh.vertexCount())};\n  });\n}\n\ntemplate <class T>\ninline Eigen::Map<Eigen::Matrix<T, 3, Eigen::Dynamic>>\nvertexMap(Mesh<T> &mesh) {\n  return mesh.withUnsafeVertexPointer([&mesh](auto *ptr) {\n    return Eigen::Map<Eigen::Matrix<T, 3, Eigen::Dynamic>>{\n        ptr, 3, gsl::narrow_cast<Eigen::Index>(mesh.vertexCount())};\n  });\n}\n\ntemplate <class T>\ninline Eigen::Map<Eigen::Matrix<T, 3, Eigen::Dynamic> const>\nvertexNormalMap(Mesh<T> const &mesh) {\n  return mesh.withUnsafeVertexNormalPointer([&mesh](auto const *ptr) {\n    return Eigen::Map<Eigen::Matrix<T, 3, Eigen::Dynamic> const>{\n        ptr, 3, gsl::narrow_cast<Eigen::Index>(mesh.vertexCount())};\n  });\n}\n\ntemplate <class T>\ninline Eigen::Map<Eigen::Matrix<T, 3, Eigen::Dynamic>>\nvertexNormalMap(Mesh<T> &mesh) {\n  return mesh.withUnsafeVertexNormalPointer([&mesh](auto *ptr) {\n    return Eigen::Map<Eigen::Matrix<T, 3, Eigen::Dynamic>>{\n        ptr, 3, gsl::narrow_cast<Eigen::Index>(mesh.vertexCount())};\n  });\n}\n\ntemplate <class T>\ninline Eigen::Map<\n    Eigen::Matrix<typename Mesh<T>::Index, 3, Eigen::Dynamic> const>\nindexMap(Mesh<T> const &mesh) {\n  using S = typename Mesh<T>::Index;\n  return mesh.withUnsafeIndexPointer([&mesh](auto const *ptr) {\n    return Eigen::Map<Eigen::Matrix<S, 3, Eigen::Dynamic> const>{\n        ptr, 3, gsl::narrow_cast<Eigen::Index>(mesh.triangleCount())};\n  });\n}\n\ntemplate <class T>\ninline Eigen::Map<Eigen::Matrix<typename Mesh<T>::Index, 3, Eigen::Dynamic>>\nindexMap(Mesh<T> &mesh) {\n  using S = typename Mesh<T>::Index;\n  return mesh.withUnsafeIndexPointer([&mesh](auto *ptr) {\n    return Eigen::Map<Eigen::Matrix<S, 3, Eigen::Dynamic>>{\n        ptr, 3, gsl::narrow_cast<Eigen::Index>(mesh.triangleCount())};\n  });\n}\n\ntemplate <class T>\ninline Eigen::Map<\n    Eigen::Matrix<typename Mesh<T>::Label, Eigen::Dynamic, 1> const>\nlabelMap(Mesh<T> const &mesh) {\n  using S = typename Mesh<T>::Label;\n  return mesh.withUnsafeLabelPointer([&mesh](auto const *ptr) {\n    return Eigen::Map<Eigen::Matrix<S, Eigen::Dynamic, 1> const>{\n        ptr, gsl::narrow_cast<Eigen::Index>(mesh.vertexCount())};\n  });\n}\n\ntemplate <class T>\ninline Eigen::Map<Eigen::Matrix<typename Mesh<T>::Label, Eigen::Dynamic, 1>>\nlabelMap(Mesh<T> &mesh) {\n  using S = typename Mesh<T>::Label;\n  return mesh.withUnsafeLabelPointer([&mesh](auto *ptr) {\n    return Eigen::Map<Eigen::Matrix<S, Eigen::Dynamic, 1>>{\n        ptr, gsl::narrow_cast<Eigen::Index>(mesh.vertexCount())};\n  });\n}\n\n} // namespace Adaptor\n} // namespace Internal\n} // namespace CortidQCT\n", "meta": {"hexsha": "88404ba1bc3b6faae517d0bc40ff7f4a037e649a", "size": 3314, "ext": "h", "lang": "C", "max_stars_repo_path": "lib/MeshAdaptors.h", "max_stars_repo_name": "ithron/CortidQCT", "max_stars_repo_head_hexsha": "5b74c18a3cb7e16541b0cef16ec794c33ef9fa59", "max_stars_repo_licenses": ["AFL-3.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-21T17:30:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-21T17:30:23.000Z", "max_issues_repo_path": "lib/MeshAdaptors.h", "max_issues_repo_name": "ithron/CortidQCT", "max_issues_repo_head_hexsha": "5b74c18a3cb7e16541b0cef16ec794c33ef9fa59", "max_issues_repo_licenses": ["AFL-3.0"], "max_issues_count": 28.0, "max_issues_repo_issues_event_min_datetime": "2018-10-23T10:51:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-22T08:11:33.000Z", "max_forks_repo_path": "lib/MeshAdaptors.h", "max_forks_repo_name": "ithron/CortidQCT", "max_forks_repo_head_hexsha": "5b74c18a3cb7e16541b0cef16ec794c33ef9fa59", "max_forks_repo_licenses": ["AFL-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8653846154, "max_line_length": 77, "alphanum_fraction": 0.6707905854, "num_tokens": 937, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.05419873287859292, "lm_q1q2_score": 0.025407857948503972}}
{"text": "#ifndef __KILLDUPTRKS_H__\n#define __KILLDUPTRKS_H__\n\n#include <cstddef>\n#include <vector>\n#include <algorithm>\n#include <functional>\n#include <utility>\n#include <iostream>\n\n#include \"L1Trigger/TrackFindingTMTT/interface/Settings.h\"\n#include \"L1Trigger/TrackFindingTMTT/interface/Stub.h\"\n#include \"L1Trigger/TrackFindingTMTT/interface/TP.h\"\n#include \"FWCore/Utilities/interface/Exception.h\"\n#include <gsl/gsl_fit.h>\n\nusing namespace std;\n\n/**\n*  Kill duplicate reconstructed tracks.\n*  e.g. Those sharing many hits in common.\n*  \n*  Currently this is intended to run only on tracks found within a single (eta,phi) sector.\n*  It includes a naive algorithms from Ian (dupTrkAlg = 1) & more sophisticated ones from Ivan (dupTrkAlg > 1).\n*  The class is implemented inside L1Trigger/TrackFindingTMTT/interface/KillDupTrks.icc\n*  \n*  The template class \"T\" can be any class inheriting from L1trackBase.\n* \n*  -------------------------------------------------------------------------------------------\n*   GENERAL INFO ABOUT THE FILTER ALGORITHMS DEFINED IN THE CLASS.\n*   Some of these algorithms are designed to work on r-phi L1track2D tracks, and some on r-z \n*   L1track2D tracks. Others work on L1tracks3D.\n*  -------------------------------------------------------------------------------------------\n*/\n\nnamespace TMTT {\n\nclass L1trackBase;\nclass L1track2D;\nclass L1track3D;\nclass L1fittedTrack;\n\ntemplate <class T> class KillDupTrks {\n\npublic:\n\n  KillDupTrks()\n\t{\n    // Check that classed used as template \"T\" inherits from class L1trackBase.\n    static_assert(std::is_base_of<L1trackBase, T>::value, \"KillDupTrks ERROR: You instantiated this with a template class not inheriting from L1trackBase!\");\n  }\n\n  ~KillDupTrks() {}\n\n  /**\n  *  Make available cfg parameters & specify which algorithm is to be used for duplicate track removal.\n  */\n  void init(const Settings* settings, unsigned int dupTrkAlg);\n\n  /**\n  *  Eliminate duplicate tracks from the input collection, and so return a reduced list of tracks.\n  */\n  vector<T> filter(const vector<T>& vecTracks) const;\n\nprivate:\n\n  /**\n  *  Implementing \"inverse\" OSU algorithm, check for stubs in common,\n  *  keep largest candidates if common stubs in N or more layers (default 5 at present), both if equal\n  *  Implementing \"inverse\" OSU algorithm, check for stubs in common,\n  *  keep largest candidates if common stubs in N or more layers (default 5 at present), both if equal\n  */\n  vector<T> filterAlg8(const vector<T>& vecTracks) const;\n\n  /** Implementing \"inverse\" OSU algorithm, check for layers in common, reverse order as per Luis's suggestion\n   * Comparison window of up to 6\n   * Modified version of Algo23, looking for layers in common as in Algo8\n   * Check if N or more common layers (default 5 at present)\n   * Then keep candidate with most stubs, use |q/pT| as tie-break, finally drop \"latest\" if still equal\n   */\nvector<T> filterAlg25(const vector<T>& vecTracks) const;\n\n  /**\n  *  Prints out a consistently formatted formatted report of killed duplicate track\n  */\n  void printKill(unsigned alg, unsigned dup, unsigned cand, T dupTrack, T candTrack) const;\n\n  /**\n  * Counts candidate layers with stubs in common\n  */\n  unsigned int layerMatches(std::vector< std::pair<unsigned int, unsigned int> >* iStubs,\n\t\t\t    std::vector< std::pair<unsigned int, unsigned int> >* jStubs) const;\nprivate:\n\n  const Settings *settings_; // Configuration parameters.\n\n  unsigned int dupTrkAlg_; // Specifies choice of algorithm for duplicate track removal.\n  unsigned int dupTrkMinCommonHitsLayers_;  // Min no of matched stubs & layers to keep smaller cand\n};\n\n}\n//=== Include file which implements all the functions in the above class.\n#include \"L1Trigger/TrackFindingTMTT/interface/KillDupTrks.icc\"\n\n#endif\n\n", "meta": {"hexsha": "fef3f2802a4161c120eb81bc87374ecf05c55356", "size": 3773, "ext": "h", "lang": "C", "max_stars_repo_path": "L1Trigger/TrackFindingTMTT/interface/KillDupTrks.h", "max_stars_repo_name": "djcranshaw/cmssw", "max_stars_repo_head_hexsha": "d66d1b15005a5f253dcbd3704591620e39fe4290", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-08-24T19:10:26.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-19T11:45:32.000Z", "max_issues_repo_path": "L1Trigger/TrackFindingTMTT/interface/KillDupTrks.h", "max_issues_repo_name": "djcranshaw/cmssw", "max_issues_repo_head_hexsha": "d66d1b15005a5f253dcbd3704591620e39fe4290", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-08-23T13:40:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-05T21:16:03.000Z", "max_forks_repo_path": "L1Trigger/TrackFindingTMTT/interface/KillDupTrks.h", "max_forks_repo_name": "djcranshaw/cmssw", "max_forks_repo_head_hexsha": "d66d1b15005a5f253dcbd3704591620e39fe4290", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-08-21T16:37:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-09T13:33:17.000Z", "avg_line_length": 35.261682243, "max_line_length": 157, "alphanum_fraction": 0.7052743175, "num_tokens": 939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936414516010196, "lm_q2_score": 0.07055960156206997, "lm_q1q2_score": 0.02535659089819067}}
{"text": "/* ieee-utils/fp-sunos4.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <sys/ieeefp.h>\n#include <floatingpoint.h>\n#include <signal.h>\n#include <gsl/gsl_ieee_utils.h>\n#include <gsl/gsl_errno.h>\n\nint\ngsl_ieee_set_mode (int precision, int rounding, int exception_mask)\n{\n  char * out ;\n\n  switch (precision)\n    {\n    case GSL_IEEE_SINGLE_PRECISION:\n      ieee_flags (\"set\", \"precision\", \"single\", out) ;\n      break ;\n    case GSL_IEEE_DOUBLE_PRECISION:\n      ieee_flags (\"set\", \"precision\", \"double\", out) ;\n      break ;\n    case GSL_IEEE_EXTENDED_PRECISION:\n      ieee_flags (\"set\", \"precision\", \"extended\", out) ;\n      break ;\n    default:\n      ieee_flags (\"set\", \"precision\", \"extended\", out) ;\n    }\n\n  switch (rounding)\n    {\n    case GSL_IEEE_ROUND_TO_NEAREST:\n      ieee_flags (\"set\", \"direction\", \"nearest\", out) ;\n      break ;\n    case GSL_IEEE_ROUND_DOWN:\n      ieee_flags (\"set\", \"direction\", \"negative\", out) ;\n      break ;\n    case GSL_IEEE_ROUND_UP:\n      ieee_flags (\"set\", \"direction\", \"positive\", out) ;\n      break ;\n    case GSL_IEEE_ROUND_TO_ZERO:\n      ieee_flags (\"set\", \"direction\", \"tozero\", out) ;\n      break ;\n    default:\n      ieee_flags (\"set\", \"direction\", \"nearest\", out) ;\n    }\n\n  if (exception_mask & GSL_IEEE_MASK_INVALID)\n    {\n      ieee_handler (\"set\", \"invalid\", SIGFPE_IGNORE) ;\n    }\n  else \n    {\n      ieee_handler (\"set\", \"invalid\", SIGFPE_ABORT) ;\n    }\n\n  if (exception_mask & GSL_IEEE_MASK_DENORMALIZED)\n    {\n      ieee_handler (\"set\", \"denormalized\", SIGFPE_IGNORE) ;\n    }\n  else\n    {\n      GSL_ERROR (\"sunos4 does not support the denormalized operand exception. \"\n                 \"Use 'mask-denormalized' to work around this.\",\n                 GSL_EUNSUP) ;\n    }\n\n\n  if (exception_mask & GSL_IEEE_MASK_DIVISION_BY_ZERO)\n    {\n      ieee_handler (\"set\", \"division\", SIGFPE_IGNORE) ;\n    } \n  else\n    {\n      ieee_handler (\"set\", \"division\", SIGFPE_ABORT) ;\n    }\n  \n  if (exception_mask & GSL_IEEE_MASK_OVERFLOW)\n    {\n      ieee_handler (\"set\", \"overflow\", SIGFPE_IGNORE) ;\n    }\n  else \n    {\n      ieee_handler (\"set\", \"overflow\", SIGFPE_ABORT) ;\n    }\n\n  if (exception_mask & GSL_IEEE_MASK_UNDERFLOW)\n    {\n      ieee_handler (\"set\", \"underflow\", SIGFPE_IGNORE) ;\n    }\n  else\n    {\n      ieee_handler (\"set\", \"underflow\", SIGFPE_ABORT) ;\n    }\n\n  if (exception_mask & GSL_IEEE_TRAP_INEXACT)\n    {\n      ieee_handler (\"set\", \"inexact\", SIGFPE_ABORT) ;\n    }\n  else\n    {\n      ieee_handler (\"set\", \"inexact\", SIGFPE_IGNORE) ;\n    }\n\n  return GSL_SUCCESS ;\n}\n", "meta": {"hexsha": "307b5380554462f308ac1567878f89b218126634", "size": 3276, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/ieee-utils/fp-sunos4.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/ieee-utils/fp-sunos4.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/ieee-utils/fp-sunos4.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 26.6341463415, "max_line_length": 81, "alphanum_fraction": 0.6404151404, "num_tokens": 881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.052618957247549634, "lm_q1q2_score": 0.025282287018561982}}
{"text": "#include <gsl/gsl_test.h>\n#include <gsl/gsl_ieee_utils.h>\n#include <gsl/gsl_math.h>\n#include \"gsl_cblas.h\"\n\n#include \"tests.h\"\n\nvoid\ntest_tpmv (void) {\nconst double flteps = 1e-4, dbleps = 1e-6;\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 131;\n   int N = 2;\n   float A[] = { -0.587f, 0.14f, 0.841f };\n   float X[] = { -0.213f, 0.885f };\n   int incX = -1;\n   float x_expected[] = { -0.179133f, -0.549315f };\n   cblas_stpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"stpmv(case 974)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 132;\n   int N = 2;\n   float A[] = { -0.587f, 0.14f, 0.841f };\n   float X[] = { -0.213f, 0.885f };\n   int incX = -1;\n   float x_expected[] = { -0.213f, 0.85518f };\n   cblas_stpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"stpmv(case 975)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 131;\n   int N = 2;\n   float A[] = { -0.587f, 0.14f, 0.841f };\n   float X[] = { -0.213f, 0.885f };\n   int incX = -1;\n   float x_expected[] = { -0.055233f, -0.519495f };\n   cblas_stpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"stpmv(case 976)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 132;\n   int N = 2;\n   float A[] = { -0.587f, 0.14f, 0.841f };\n   float X[] = { -0.213f, 0.885f };\n   int incX = -1;\n   float x_expected[] = { -0.0891f, 0.885f };\n   cblas_stpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"stpmv(case 977)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 131;\n   int N = 2;\n   float A[] = { -0.587f, 0.14f, 0.841f };\n   float X[] = { -0.213f, 0.885f };\n   int incX = -1;\n   float x_expected[] = { -0.179133f, -0.549315f };\n   cblas_stpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"stpmv(case 978)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 132;\n   int N = 2;\n   float A[] = { -0.587f, 0.14f, 0.841f };\n   float X[] = { -0.213f, 0.885f };\n   int incX = -1;\n   float x_expected[] = { -0.213f, 0.85518f };\n   cblas_stpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"stpmv(case 979)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 131;\n   int N = 2;\n   float A[] = { -0.587f, 0.14f, 0.841f };\n   float X[] = { -0.213f, 0.885f };\n   int incX = -1;\n   float x_expected[] = { -0.055233f, -0.519495f };\n   cblas_stpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"stpmv(case 980)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 132;\n   int N = 2;\n   float A[] = { -0.587f, 0.14f, 0.841f };\n   float X[] = { -0.213f, 0.885f };\n   int incX = -1;\n   float x_expected[] = { -0.0891f, 0.885f };\n   cblas_stpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"stpmv(case 981)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 131;\n   int N = 2;\n   float A[] = { -0.765f, 0.968f, -0.956f };\n   float X[] = { 0.243f, -0.274f };\n   int incX = -1;\n   float x_expected[] = { -0.49754f, 0.20961f };\n   cblas_stpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"stpmv(case 982)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 132;\n   int N = 2;\n   float A[] = { -0.765f, 0.968f, -0.956f };\n   float X[] = { 0.243f, -0.274f };\n   int incX = -1;\n   float x_expected[] = { -0.022232f, -0.274f };\n   cblas_stpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"stpmv(case 983)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 131;\n   int N = 2;\n   float A[] = { -0.765f, 0.968f, -0.956f };\n   float X[] = { 0.243f, -0.274f };\n   int incX = -1;\n   float x_expected[] = { -0.232308f, 0.444834f };\n   cblas_stpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"stpmv(case 984)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 132;\n   int N = 2;\n   float A[] = { -0.765f, 0.968f, -0.956f };\n   float X[] = { 0.243f, -0.274f };\n   int incX = -1;\n   float x_expected[] = { 0.243f, -0.038776f };\n   cblas_stpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"stpmv(case 985)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 131;\n   int N = 2;\n   float A[] = { -0.765f, 0.968f, -0.956f };\n   float X[] = { 0.243f, -0.274f };\n   int incX = -1;\n   float x_expected[] = { -0.49754f, 0.20961f };\n   cblas_stpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"stpmv(case 986)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 132;\n   int N = 2;\n   float A[] = { -0.765f, 0.968f, -0.956f };\n   float X[] = { 0.243f, -0.274f };\n   int incX = -1;\n   float x_expected[] = { -0.022232f, -0.274f };\n   cblas_stpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"stpmv(case 987)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 131;\n   int N = 2;\n   float A[] = { -0.765f, 0.968f, -0.956f };\n   float X[] = { 0.243f, -0.274f };\n   int incX = -1;\n   float x_expected[] = { -0.232308f, 0.444834f };\n   cblas_stpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"stpmv(case 988)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 132;\n   int N = 2;\n   float A[] = { -0.765f, 0.968f, -0.956f };\n   float X[] = { 0.243f, -0.274f };\n   int incX = -1;\n   float x_expected[] = { 0.243f, -0.038776f };\n   cblas_stpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"stpmv(case 989)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 131;\n   int N = 2;\n   double A[] = { 0.393, -0.221, 0.356 };\n   double X[] = { -0.062, -0.221 };\n   int incX = -1;\n   double x_expected[] = { -0.022072, -0.073151 };\n   cblas_dtpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtpmv(case 990)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 132;\n   int N = 2;\n   double A[] = { 0.393, -0.221, 0.356 };\n   double X[] = { -0.062, -0.221 };\n   int incX = -1;\n   double x_expected[] = { -0.062, -0.207298 };\n   cblas_dtpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtpmv(case 991)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 131;\n   int N = 2;\n   double A[] = { 0.393, -0.221, 0.356 };\n   double X[] = { -0.062, -0.221 };\n   int incX = -1;\n   double x_expected[] = { 0.026769, -0.086853 };\n   cblas_dtpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtpmv(case 992)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 132;\n   int N = 2;\n   double A[] = { 0.393, -0.221, 0.356 };\n   double X[] = { -0.062, -0.221 };\n   int incX = -1;\n   double x_expected[] = { -0.013159, -0.221 };\n   cblas_dtpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtpmv(case 993)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 131;\n   int N = 2;\n   double A[] = { 0.393, -0.221, 0.356 };\n   double X[] = { -0.062, -0.221 };\n   int incX = -1;\n   double x_expected[] = { -0.022072, -0.073151 };\n   cblas_dtpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtpmv(case 994)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 132;\n   int N = 2;\n   double A[] = { 0.393, -0.221, 0.356 };\n   double X[] = { -0.062, -0.221 };\n   int incX = -1;\n   double x_expected[] = { -0.062, -0.207298 };\n   cblas_dtpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtpmv(case 995)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 131;\n   int N = 2;\n   double A[] = { 0.393, -0.221, 0.356 };\n   double X[] = { -0.062, -0.221 };\n   int incX = -1;\n   double x_expected[] = { 0.026769, -0.086853 };\n   cblas_dtpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtpmv(case 996)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 132;\n   int N = 2;\n   double A[] = { 0.393, -0.221, 0.356 };\n   double X[] = { -0.062, -0.221 };\n   int incX = -1;\n   double x_expected[] = { -0.013159, -0.221 };\n   cblas_dtpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtpmv(case 997)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 131;\n   int N = 2;\n   double A[] = { 0.694, 0.501, 0.019 };\n   double X[] = { -0.928, 0.365 };\n   int incX = -1;\n   double x_expected[] = { 0.165233, 0.25331 };\n   cblas_dtpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtpmv(case 998)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 132;\n   int N = 2;\n   double A[] = { 0.694, 0.501, 0.019 };\n   double X[] = { -0.928, 0.365 };\n   int incX = -1;\n   double x_expected[] = { -0.745135, 0.365 };\n   cblas_dtpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtpmv(case 999)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 131;\n   int N = 2;\n   double A[] = { 0.694, 0.501, 0.019 };\n   double X[] = { -0.928, 0.365 };\n   int incX = -1;\n   double x_expected[] = { -0.017632, -0.211618 };\n   cblas_dtpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtpmv(case 1000)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 132;\n   int N = 2;\n   double A[] = { 0.694, 0.501, 0.019 };\n   double X[] = { -0.928, 0.365 };\n   int incX = -1;\n   double x_expected[] = { -0.928, -0.099928 };\n   cblas_dtpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtpmv(case 1001)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 131;\n   int N = 2;\n   double A[] = { 0.694, 0.501, 0.019 };\n   double X[] = { -0.928, 0.365 };\n   int incX = -1;\n   double x_expected[] = { 0.165233, 0.25331 };\n   cblas_dtpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtpmv(case 1002)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 132;\n   int N = 2;\n   double A[] = { 0.694, 0.501, 0.019 };\n   double X[] = { -0.928, 0.365 };\n   int incX = -1;\n   double x_expected[] = { -0.745135, 0.365 };\n   cblas_dtpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtpmv(case 1003)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 131;\n   int N = 2;\n   double A[] = { 0.694, 0.501, 0.019 };\n   double X[] = { -0.928, 0.365 };\n   int incX = -1;\n   double x_expected[] = { -0.017632, -0.211618 };\n   cblas_dtpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtpmv(case 1004)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 132;\n   int N = 2;\n   double A[] = { 0.694, 0.501, 0.019 };\n   double X[] = { -0.928, 0.365 };\n   int incX = -1;\n   double x_expected[] = { -0.928, -0.099928 };\n   cblas_dtpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtpmv(case 1005)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 131;\n   int N = 2;\n   float A[] = { 0.362f, -0.849f, -0.612f, -0.718f, 0.503f, -0.923f };\n   float X[] = { 0.904f, 0.461f, -0.367f, 0.153f };\n   int incX = -1;\n   float x_expected[] = { 0.880215f, -0.602509f, -0.225207f, -0.564235f };\n   cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctpmv(case 1006) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctpmv(case 1006) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 132;\n   int N = 2;\n   float A[] = { 0.362f, -0.849f, -0.612f, -0.718f, 0.503f, -0.923f };\n   float X[] = { 0.904f, 0.461f, -0.367f, 0.153f };\n   int incX = -1;\n   float x_expected[] = { 0.904f, 0.461f, -0.58925f, -0.778204f };\n   cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctpmv(case 1007) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctpmv(case 1007) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 131;\n   int N = 2;\n   float A[] = { 0.362f, -0.849f, -0.612f, -0.718f, 0.503f, -0.923f };\n   float X[] = { 0.904f, 0.461f, -0.367f, 0.153f };\n   int incX = -1;\n   float x_expected[] = { 1.21467f, -0.432639f, -0.002957f, 0.366969f };\n   cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctpmv(case 1008) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctpmv(case 1008) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 132;\n   int N = 2;\n   float A[] = { 0.362f, -0.849f, -0.612f, -0.718f, 0.503f, -0.923f };\n   float X[] = { 0.904f, 0.461f, -0.367f, 0.153f };\n   int incX = -1;\n   float x_expected[] = { 1.23846f, 0.63087f, -0.367f, 0.153f };\n   cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctpmv(case 1009) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctpmv(case 1009) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 131;\n   int N = 2;\n   float A[] = { 0.362f, -0.849f, -0.612f, -0.718f, 0.503f, -0.923f };\n   float X[] = { 0.904f, 0.461f, -0.367f, 0.153f };\n   int incX = -1;\n   float x_expected[] = { 0.880215f, -0.602509f, -0.225207f, -0.564235f };\n   cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctpmv(case 1010) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctpmv(case 1010) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 132;\n   int N = 2;\n   float A[] = { 0.362f, -0.849f, -0.612f, -0.718f, 0.503f, -0.923f };\n   float X[] = { 0.904f, 0.461f, -0.367f, 0.153f };\n   int incX = -1;\n   float x_expected[] = { 0.904f, 0.461f, -0.58925f, -0.778204f };\n   cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctpmv(case 1011) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctpmv(case 1011) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 131;\n   int N = 2;\n   float A[] = { 0.362f, -0.849f, -0.612f, -0.718f, 0.503f, -0.923f };\n   float X[] = { 0.904f, 0.461f, -0.367f, 0.153f };\n   int incX = -1;\n   float x_expected[] = { 1.21467f, -0.432639f, -0.002957f, 0.366969f };\n   cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctpmv(case 1012) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctpmv(case 1012) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 132;\n   int N = 2;\n   float A[] = { 0.362f, -0.849f, -0.612f, -0.718f, 0.503f, -0.923f };\n   float X[] = { 0.904f, 0.461f, -0.367f, 0.153f };\n   int incX = -1;\n   float x_expected[] = { 1.23846f, 0.63087f, -0.367f, 0.153f };\n   cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctpmv(case 1013) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctpmv(case 1013) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 131;\n   int N = 2;\n   float A[] = { -0.876f, -0.697f, -0.519f, -0.223f, 0.526f, -0.077f };\n   float X[] = { 0.338f, -0.807f, 0.444f, -0.748f };\n   int incX = -1;\n   float x_expected[] = { -0.281591f, -0.161308f, -0.9103f, 0.34578f };\n   cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctpmv(case 1014) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctpmv(case 1014) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 132;\n   int N = 2;\n   float A[] = { -0.876f, -0.697f, -0.519f, -0.223f, 0.526f, -0.077f };\n   float X[] = { 0.338f, -0.807f, 0.444f, -0.748f };\n   int incX = -1;\n   float x_expected[] = { -0.05924f, -0.5178f, 0.444f, -0.748f };\n   cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctpmv(case 1015) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctpmv(case 1015) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 131;\n   int N = 2;\n   float A[] = { -0.876f, -0.697f, -0.519f, -0.223f, 0.526f, -0.077f };\n   float X[] = { 0.338f, -0.807f, 0.444f, -0.748f };\n   int incX = -1;\n   float x_expected[] = { 0.115649f, -0.450508f, -1.26568f, 0.689239f };\n   cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctpmv(case 1016) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctpmv(case 1016) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 132;\n   int N = 2;\n   float A[] = { -0.876f, -0.697f, -0.519f, -0.223f, 0.526f, -0.077f };\n   float X[] = { 0.338f, -0.807f, 0.444f, -0.748f };\n   int incX = -1;\n   float x_expected[] = { 0.338f, -0.807f, 0.088617f, -0.404541f };\n   cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctpmv(case 1017) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctpmv(case 1017) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 131;\n   int N = 2;\n   float A[] = { -0.876f, -0.697f, -0.519f, -0.223f, 0.526f, -0.077f };\n   float X[] = { 0.338f, -0.807f, 0.444f, -0.748f };\n   int incX = -1;\n   float x_expected[] = { -0.281591f, -0.161308f, -0.9103f, 0.34578f };\n   cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctpmv(case 1018) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctpmv(case 1018) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 132;\n   int N = 2;\n   float A[] = { -0.876f, -0.697f, -0.519f, -0.223f, 0.526f, -0.077f };\n   float X[] = { 0.338f, -0.807f, 0.444f, -0.748f };\n   int incX = -1;\n   float x_expected[] = { -0.05924f, -0.5178f, 0.444f, -0.748f };\n   cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctpmv(case 1019) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctpmv(case 1019) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 131;\n   int N = 2;\n   float A[] = { -0.876f, -0.697f, -0.519f, -0.223f, 0.526f, -0.077f };\n   float X[] = { 0.338f, -0.807f, 0.444f, -0.748f };\n   int incX = -1;\n   float x_expected[] = { 0.115649f, -0.450508f, -1.26568f, 0.689239f };\n   cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctpmv(case 1020) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctpmv(case 1020) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 132;\n   int N = 2;\n   float A[] = { -0.876f, -0.697f, -0.519f, -0.223f, 0.526f, -0.077f };\n   float X[] = { 0.338f, -0.807f, 0.444f, -0.748f };\n   int incX = -1;\n   float x_expected[] = { 0.338f, -0.807f, 0.088617f, -0.404541f };\n   cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctpmv(case 1021) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctpmv(case 1021) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 113;\n   int uplo = 121;\n   int diag = 131;\n   int N = 2;\n   float A[] = { 0.869f, -0.091f, -0.859f, 0.008f, -0.921f, -0.321f };\n   float X[] = { -0.122f, -0.364f, 0.602f, -0.96f };\n   int incX = -1;\n   float x_expected[] = { -0.295592f, 1.11591f, 0.610498f, -0.779458f };\n   cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctpmv(case 1022) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctpmv(case 1022) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 113;\n   int uplo = 121;\n   int diag = 132;\n   int N = 2;\n   float A[] = { 0.869f, -0.091f, -0.859f, 0.008f, -0.921f, -0.321f };\n   float X[] = { -0.122f, -0.364f, 0.602f, -0.96f };\n   int incX = -1;\n   float x_expected[] = { -0.646798f, 0.455824f, 0.602f, -0.96f };\n   cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctpmv(case 1023) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctpmv(case 1023) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 113;\n   int uplo = 122;\n   int diag = 131;\n   int N = 2;\n   float A[] = { 0.869f, -0.091f, -0.859f, 0.008f, -0.921f, -0.321f };\n   float X[] = { -0.122f, -0.364f, 0.602f, -0.96f };\n   int incX = -1;\n   float x_expected[] = { 0.229206f, 0.296082f, 0.712384f, -0.465806f };\n   cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctpmv(case 1024) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctpmv(case 1024) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 113;\n   int uplo = 122;\n   int diag = 132;\n   int N = 2;\n   float A[] = { 0.869f, -0.091f, -0.859f, 0.008f, -0.921f, -0.321f };\n   float X[] = { -0.122f, -0.364f, 0.602f, -0.96f };\n   int incX = -1;\n   float x_expected[] = { -0.122f, -0.364f, 0.703886f, -0.646348f };\n   cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctpmv(case 1025) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctpmv(case 1025) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 113;\n   int uplo = 121;\n   int diag = 131;\n   int N = 2;\n   float A[] = { 0.869f, -0.091f, -0.859f, 0.008f, -0.921f, -0.321f };\n   float X[] = { -0.122f, -0.364f, 0.602f, -0.96f };\n   int incX = -1;\n   float x_expected[] = { -0.295592f, 1.11591f, 0.610498f, -0.779458f };\n   cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctpmv(case 1026) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctpmv(case 1026) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 113;\n   int uplo = 121;\n   int diag = 132;\n   int N = 2;\n   float A[] = { 0.869f, -0.091f, -0.859f, 0.008f, -0.921f, -0.321f };\n   float X[] = { -0.122f, -0.364f, 0.602f, -0.96f };\n   int incX = -1;\n   float x_expected[] = { -0.646798f, 0.455824f, 0.602f, -0.96f };\n   cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctpmv(case 1027) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctpmv(case 1027) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 113;\n   int uplo = 122;\n   int diag = 131;\n   int N = 2;\n   float A[] = { 0.869f, -0.091f, -0.859f, 0.008f, -0.921f, -0.321f };\n   float X[] = { -0.122f, -0.364f, 0.602f, -0.96f };\n   int incX = -1;\n   float x_expected[] = { 0.229206f, 0.296082f, 0.712384f, -0.465806f };\n   cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctpmv(case 1028) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctpmv(case 1028) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 113;\n   int uplo = 122;\n   int diag = 132;\n   int N = 2;\n   float A[] = { 0.869f, -0.091f, -0.859f, 0.008f, -0.921f, -0.321f };\n   float X[] = { -0.122f, -0.364f, 0.602f, -0.96f };\n   int incX = -1;\n   float x_expected[] = { -0.122f, -0.364f, 0.703886f, -0.646348f };\n   cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctpmv(case 1029) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctpmv(case 1029) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 131;\n   int N = 2;\n   double A[] = { 0.254, 0.263, -0.271, -0.595, -0.182, -0.672 };\n   double X[] = { -0.042, -0.705, -0.255, -0.854 };\n   int incX = -1;\n   double x_expected[] = { -0.466116, 0.156534, -0.248261, -0.067936 };\n   cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztpmv(case 1030) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztpmv(case 1030) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 132;\n   int N = 2;\n   double A[] = { 0.254, 0.263, -0.271, -0.595, -0.182, -0.672 };\n   double X[] = { -0.042, -0.705, -0.255, -0.854 };\n   int incX = -1;\n   double x_expected[] = { -0.042, -0.705, -0.663093, -0.637955 };\n   cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztpmv(case 1031) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztpmv(case 1031) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 131;\n   int N = 2;\n   double A[] = { 0.254, 0.263, -0.271, -0.595, -0.182, -0.672 };\n   double X[] = { -0.042, -0.705, -0.255, -0.854 };\n   int incX = -1;\n   double x_expected[] = { -0.905141, 0.539693, 0.159832, -0.283981 };\n   cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztpmv(case 1032) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztpmv(case 1032) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 132;\n   int N = 2;\n   double A[] = { 0.254, 0.263, -0.271, -0.595, -0.182, -0.672 };\n   double X[] = { -0.042, -0.705, -0.255, -0.854 };\n   int incX = -1;\n   double x_expected[] = { -0.481025, -0.321841, -0.255, -0.854 };\n   cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztpmv(case 1033) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztpmv(case 1033) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 131;\n   int N = 2;\n   double A[] = { 0.254, 0.263, -0.271, -0.595, -0.182, -0.672 };\n   double X[] = { -0.042, -0.705, -0.255, -0.854 };\n   int incX = -1;\n   double x_expected[] = { -0.466116, 0.156534, -0.248261, -0.067936 };\n   cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztpmv(case 1034) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztpmv(case 1034) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 132;\n   int N = 2;\n   double A[] = { 0.254, 0.263, -0.271, -0.595, -0.182, -0.672 };\n   double X[] = { -0.042, -0.705, -0.255, -0.854 };\n   int incX = -1;\n   double x_expected[] = { -0.042, -0.705, -0.663093, -0.637955 };\n   cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztpmv(case 1035) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztpmv(case 1035) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 131;\n   int N = 2;\n   double A[] = { 0.254, 0.263, -0.271, -0.595, -0.182, -0.672 };\n   double X[] = { -0.042, -0.705, -0.255, -0.854 };\n   int incX = -1;\n   double x_expected[] = { -0.905141, 0.539693, 0.159832, -0.283981 };\n   cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztpmv(case 1036) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztpmv(case 1036) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 132;\n   int N = 2;\n   double A[] = { 0.254, 0.263, -0.271, -0.595, -0.182, -0.672 };\n   double X[] = { -0.042, -0.705, -0.255, -0.854 };\n   int incX = -1;\n   double x_expected[] = { -0.481025, -0.321841, -0.255, -0.854 };\n   cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztpmv(case 1037) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztpmv(case 1037) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 131;\n   int N = 2;\n   double A[] = { 0.421, -0.407, -0.595, -0.387, 0.884, -0.498 };\n   double X[] = { -0.008, 0.904, -0.689, -0.679 };\n   int incX = -1;\n   double x_expected[] = { 0.590302, 1.473768, -0.566422, -0.005436 };\n   cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztpmv(case 1038) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztpmv(case 1038) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 132;\n   int N = 2;\n   double A[] = { 0.421, -0.407, -0.595, -0.387, 0.884, -0.498 };\n   double X[] = { -0.008, 0.904, -0.689, -0.679 };\n   int incX = -1;\n   double x_expected[] = { 0.139182, 1.574648, -0.689, -0.679 };\n   cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztpmv(case 1039) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztpmv(case 1039) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 131;\n   int N = 2;\n   double A[] = { 0.421, -0.407, -0.595, -0.387, 0.884, -0.498 };\n   double X[] = { -0.008, 0.904, -0.689, -0.679 };\n   int incX = -1;\n   double x_expected[] = { 0.44312, 0.80312, -0.211814, -0.54022 };\n   cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztpmv(case 1040) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztpmv(case 1040) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 132;\n   int N = 2;\n   double A[] = { 0.421, -0.407, -0.595, -0.387, 0.884, -0.498 };\n   double X[] = { -0.008, 0.904, -0.689, -0.679 };\n   int incX = -1;\n   double x_expected[] = { -0.008, 0.904, -0.334392, -1.213784 };\n   cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztpmv(case 1041) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztpmv(case 1041) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 131;\n   int N = 2;\n   double A[] = { 0.421, -0.407, -0.595, -0.387, 0.884, -0.498 };\n   double X[] = { -0.008, 0.904, -0.689, -0.679 };\n   int incX = -1;\n   double x_expected[] = { 0.590302, 1.473768, -0.566422, -0.005436 };\n   cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztpmv(case 1042) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztpmv(case 1042) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 132;\n   int N = 2;\n   double A[] = { 0.421, -0.407, -0.595, -0.387, 0.884, -0.498 };\n   double X[] = { -0.008, 0.904, -0.689, -0.679 };\n   int incX = -1;\n   double x_expected[] = { 0.139182, 1.574648, -0.689, -0.679 };\n   cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztpmv(case 1043) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztpmv(case 1043) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 131;\n   int N = 2;\n   double A[] = { 0.421, -0.407, -0.595, -0.387, 0.884, -0.498 };\n   double X[] = { -0.008, 0.904, -0.689, -0.679 };\n   int incX = -1;\n   double x_expected[] = { 0.44312, 0.80312, -0.211814, -0.54022 };\n   cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztpmv(case 1044) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztpmv(case 1044) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 132;\n   int N = 2;\n   double A[] = { 0.421, -0.407, -0.595, -0.387, 0.884, -0.498 };\n   double X[] = { -0.008, 0.904, -0.689, -0.679 };\n   int incX = -1;\n   double x_expected[] = { -0.008, 0.904, -0.334392, -1.213784 };\n   cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztpmv(case 1045) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztpmv(case 1045) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 113;\n   int uplo = 121;\n   int diag = 131;\n   int N = 2;\n   double A[] = { -0.743, -0.078, 0.77, 0.505, 0.157, -0.986 };\n   double X[] = { -0.641, 0.565, -0.406, -0.948 };\n   int incX = -1;\n   double x_expected[] = { -1.449087, -1.068251, 0.375602, 0.672696 };\n   cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztpmv(case 1046) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztpmv(case 1046) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 113;\n   int uplo = 121;\n   int diag = 132;\n   int N = 2;\n   double A[] = { -0.743, -0.078, 0.77, 0.505, 0.157, -0.986 };\n   double X[] = { -0.641, 0.565, -0.406, -0.948 };\n   int incX = -1;\n   double x_expected[] = { -1.43236, 0.04007, -0.406, -0.948 };\n   cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztpmv(case 1047) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztpmv(case 1047) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 113;\n   int uplo = 122;\n   int diag = 131;\n   int N = 2;\n   double A[] = { -0.743, -0.078, 0.77, 0.505, 0.157, -0.986 };\n   double X[] = { -0.641, 0.565, -0.406, -0.948 };\n   int incX = -1;\n   double x_expected[] = { -0.657727, -0.543321, 0.167357, 1.431451 };\n   cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztpmv(case 1048) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztpmv(case 1048) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 113;\n   int uplo = 122;\n   int diag = 132;\n   int N = 2;\n   double A[] = { -0.743, -0.078, 0.77, 0.505, 0.157, -0.986 };\n   double X[] = { -0.641, 0.565, -0.406, -0.948 };\n   int incX = -1;\n   double x_expected[] = { -0.641, 0.565, -0.614245, -0.189245 };\n   cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztpmv(case 1049) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztpmv(case 1049) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 113;\n   int uplo = 121;\n   int diag = 131;\n   int N = 2;\n   double A[] = { -0.743, -0.078, 0.77, 0.505, 0.157, -0.986 };\n   double X[] = { -0.641, 0.565, -0.406, -0.948 };\n   int incX = -1;\n   double x_expected[] = { -1.449087, -1.068251, 0.375602, 0.672696 };\n   cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztpmv(case 1050) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztpmv(case 1050) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 113;\n   int uplo = 121;\n   int diag = 132;\n   int N = 2;\n   double A[] = { -0.743, -0.078, 0.77, 0.505, 0.157, -0.986 };\n   double X[] = { -0.641, 0.565, -0.406, -0.948 };\n   int incX = -1;\n   double x_expected[] = { -1.43236, 0.04007, -0.406, -0.948 };\n   cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztpmv(case 1051) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztpmv(case 1051) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 113;\n   int uplo = 122;\n   int diag = 131;\n   int N = 2;\n   double A[] = { -0.743, -0.078, 0.77, 0.505, 0.157, -0.986 };\n   double X[] = { -0.641, 0.565, -0.406, -0.948 };\n   int incX = -1;\n   double x_expected[] = { -0.657727, -0.543321, 0.167357, 1.431451 };\n   cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztpmv(case 1052) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztpmv(case 1052) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 113;\n   int uplo = 122;\n   int diag = 132;\n   int N = 2;\n   double A[] = { -0.743, -0.078, 0.77, 0.505, 0.157, -0.986 };\n   double X[] = { -0.641, 0.565, -0.406, -0.948 };\n   int incX = -1;\n   double x_expected[] = { -0.641, 0.565, -0.614245, -0.189245 };\n   cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztpmv(case 1053) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztpmv(case 1053) imag\");\n     };\n   };\n  };\n\n\n}\n", "meta": {"hexsha": "43a4926951ee2cc7a406f6c76563f4e1b7cf8638", "size": 42533, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/cblas/test_tpmv.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/cblas/test_tpmv.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/cblas/test_tpmv.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 25.6222891566, "max_line_length": 82, "alphanum_fraction": 0.5048550537, "num_tokens": 18369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.05261895074782334, "lm_q1q2_score": 0.025282283895582087}}
{"text": "/**\n *\n * @file qwrapper_dgemm.c\n *\n *  PLASMA core_blas quark wrapper\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Hatem Ltaief\n * @author Mathieu Faverge\n * @author Jakub Kurzak\n * @date 2010-11-15\n * @generated d Tue Jan  7 11:44:56 2014\n *\n **/\n#include <cblas.h>\n#include \"common.h\"\n\n/***************************************************************************//**\n *\n **/\nvoid QUARK_CORE_dgemm(Quark *quark, Quark_Task_Flags *task_flags,\n                      PLASMA_enum transA, int transB,\n                      int m, int n, int k, int nb,\n                      double alpha, const double *A, int lda,\n                                                const double *B, int ldb,\n                      double beta, double *C, int ldc)\n{\n    DAG_CORE_GEMM;\n    QUARK_Insert_Task(quark, CORE_dgemm_quark, task_flags,\n        sizeof(PLASMA_enum),                &transA,    VALUE,\n        sizeof(PLASMA_enum),                &transB,    VALUE,\n        sizeof(int),                        &m,         VALUE,\n        sizeof(int),                        &n,         VALUE,\n        sizeof(int),                        &k,         VALUE,\n        sizeof(double),         &alpha,     VALUE,\n        sizeof(double)*nb*nb,    A,                 INPUT,\n        sizeof(int),                        &lda,       VALUE,\n        sizeof(double)*nb*nb,    B,                 INPUT,\n        sizeof(int),                        &ldb,       VALUE,\n        sizeof(double),         &beta,      VALUE,\n        sizeof(double)*nb*nb,    C,                 INOUT,\n        sizeof(int),                        &ldc,       VALUE,\n        0);\n}\n\n/***************************************************************************//**\n *\n **/\nvoid QUARK_CORE_dgemm2( Quark *quark, Quark_Task_Flags *task_flags,\n                        PLASMA_enum transA, int transB,\n                        int m, int n, int k, int nb,\n                        double alpha, const double *A, int lda,\n                        const double *B, int ldb,\n                        double beta, double *C, int ldc)\n{\n    DAG_CORE_GEMM;\n    QUARK_Insert_Task(quark, CORE_dgemm_quark, task_flags,\n        sizeof(PLASMA_enum),                &transA,    VALUE,\n        sizeof(PLASMA_enum),                &transB,    VALUE,\n        sizeof(int),                        &m,         VALUE,\n        sizeof(int),                        &n,         VALUE,\n        sizeof(int),                        &k,         VALUE,\n        sizeof(double),         &alpha,     VALUE,\n        sizeof(double)*nb*nb,    A,                 INPUT,\n        sizeof(int),                        &lda,       VALUE,\n        sizeof(double)*nb*nb,    B,                 INPUT,\n        sizeof(int),                        &ldb,       VALUE,\n        sizeof(double),         &beta,      VALUE,\n        sizeof(double)*nb*nb,    C,                 INOUT | LOCALITY | GATHERV,\n        sizeof(int),                        &ldc,       VALUE,\n        0);\n}\n\n/***************************************************************************//**\n *\n **/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_dgemm_quark = PCORE_dgemm_quark\n#define CORE_dgemm_quark PCORE_dgemm_quark\n#endif\nvoid CORE_dgemm_quark(Quark *quark)\n{\n    PLASMA_enum transA;\n    PLASMA_enum transB;\n    int m;\n    int n;\n    int k;\n    double alpha;\n    double *A;\n    int lda;\n    double *B;\n    int ldb;\n    double beta;\n    double *C;\n    int ldc;\n\n    quark_unpack_args_13(quark, transA, transB, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc);\n    cblas_dgemm(\n        CblasColMajor,\n        (CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB,\n        m, n, k,\n        (alpha), A, lda,\n        B, ldb,\n        (beta), C, ldc);\n}\n\n/***************************************************************************//**\n *\n **/\nvoid QUARK_CORE_dgemm_f2(Quark *quark, Quark_Task_Flags *task_flags,\n                         PLASMA_enum transA, int transB,\n                         int m, int n, int k, int nb,\n                         double alpha, const double *A, int lda,\n                                                   const double *B, int ldb,\n                         double beta, double *C, int ldc,\n                         double *fake1, int szefake1, int flag1,\n                         double *fake2, int szefake2, int flag2)\n{\n    DAG_CORE_GEMM;\n    QUARK_Insert_Task(quark, CORE_dgemm_f2_quark, task_flags,\n        sizeof(PLASMA_enum),                &transA,    VALUE,\n        sizeof(PLASMA_enum),                &transB,    VALUE,\n        sizeof(int),                        &m,         VALUE,\n        sizeof(int),                        &n,         VALUE,\n        sizeof(int),                        &k,         VALUE,\n        sizeof(double),         &alpha,     VALUE,\n        sizeof(double)*nb*nb,    A,                 INPUT,\n        sizeof(int),                        &lda,       VALUE,\n        sizeof(double)*nb*nb,    B,                 INPUT,\n        sizeof(int),                        &ldb,       VALUE,\n        sizeof(double),         &beta,      VALUE,\n        sizeof(double)*nb*nb,    C,                 INOUT | LOCALITY,\n        sizeof(int),                        &ldc,       VALUE,\n        sizeof(double)*szefake1, fake1,             flag1,\n        sizeof(double)*szefake2, fake2,             flag2,\n        0);\n}\n\n/***************************************************************************//**\n *\n **/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_dgemm_f2_quark = PCORE_dgemm_f2_quark\n#define CORE_dgemm_f2_quark PCORE_dgemm_f2_quark\n#endif\nvoid CORE_dgemm_f2_quark(Quark* quark)\n{\n    PLASMA_enum transA;\n    PLASMA_enum transB;\n    int M;\n    int N;\n    int K;\n    double alpha;\n    double *A;\n    int LDA;\n    double *B;\n    int LDB;\n    double beta;\n    double *C;\n    int LDC;\n    void *fake1, *fake2;\n\n    quark_unpack_args_15(quark, transA, transB, M, N, K, alpha,\n                         A, LDA, B, LDB, beta, C, LDC, fake1, fake2);\n    cblas_dgemm(\n        CblasColMajor,\n        (CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB,\n        M, N, K,\n        (alpha), A, LDA,\n        B, LDB,\n        (beta), C, LDC);\n}\n\n/***************************************************************************//**\n *\n **/\nvoid QUARK_CORE_dgemm_p2(Quark *quark, Quark_Task_Flags *task_flags,\n                         PLASMA_enum transA, int transB,\n                         int m, int n, int k, int nb,\n                         double alpha, const double *A, int lda,\n                         const double **B, int ldb,\n                         double beta, double *C, int ldc)\n{\n    DAG_CORE_GEMM;\n    QUARK_Insert_Task(quark, CORE_dgemm_p2_quark, task_flags,\n        sizeof(PLASMA_enum),                &transA,    VALUE,\n        sizeof(PLASMA_enum),                &transB,    VALUE,\n        sizeof(int),                        &m,         VALUE,\n        sizeof(int),                        &n,         VALUE,\n        sizeof(int),                        &k,         VALUE,\n        sizeof(double),         &alpha,     VALUE,\n        sizeof(double)*lda*nb,   A,                 INPUT,\n        sizeof(int),                        &lda,       VALUE,\n        sizeof(double*),         B,                 INPUT,\n        sizeof(int),                        &ldb,       VALUE,\n        sizeof(double),         &beta,      VALUE,\n        sizeof(double)*ldc*nb,    C,                 INOUT | LOCALITY,\n        sizeof(int),                        &ldc,       VALUE,\n        0);\n}\n\n/***************************************************************************//**\n *\n **/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_dgemm_p2_quark = PCORE_dgemm_p2_quark\n#define CORE_dgemm_p2_quark PCORE_dgemm_p2_quark\n#endif\nvoid CORE_dgemm_p2_quark(Quark* quark)\n{\n    PLASMA_enum transA;\n    PLASMA_enum transB;\n    int M;\n    int N;\n    int K;\n    double alpha;\n    double *A;\n    int LDA;\n    double **B;\n    int LDB;\n    double beta;\n    double *C;\n    int LDC;\n\n    quark_unpack_args_13(quark, transA, transB, M, N, K, alpha,\n                         A, LDA, B, LDB, beta, C, LDC);\n    cblas_dgemm(\n        CblasColMajor,\n        (CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB,\n        M, N, K,\n        (alpha), A, LDA,\n        *B, LDB,\n        (beta), C, LDC);\n}\n\n/***************************************************************************//**\n *\n **/\nvoid QUARK_CORE_dgemm_p3(Quark *quark, Quark_Task_Flags *task_flags,\n                           PLASMA_enum transA, int transB,\n                           int m, int n, int k, int nb,\n                           double alpha, const double *A, int lda,\n                           const double *B, int ldb,\n                           double beta, double **C, int ldc)\n{\n    DAG_CORE_GEMM;\n    QUARK_Insert_Task(quark, CORE_dgemm_p3_quark, task_flags,\n        sizeof(PLASMA_enum),                &transA,    VALUE,\n        sizeof(PLASMA_enum),                &transB,    VALUE,\n        sizeof(int),                        &m,         VALUE,\n        sizeof(int),                        &n,         VALUE,\n        sizeof(int),                        &k,         VALUE,\n        sizeof(double),         &alpha,     VALUE,\n        sizeof(double)*lda*nb,   A,                 INPUT,\n        sizeof(int),                        &lda,       VALUE,\n        sizeof(double)*ldb*nb,   B,                 INPUT,\n        sizeof(int),                        &ldb,       VALUE,\n        sizeof(double),         &beta,      VALUE,\n        sizeof(double*),         C,                 INOUT | LOCALITY,\n        sizeof(int),                        &ldc,       VALUE,\n        0);\n}\n\n/***************************************************************************//**\n *\n **/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_dgemm_p3_quark = PCORE_dgemm_p3_quark\n#define CORE_dgemm_p3_quark PCORE_dgemm_p3_quark\n#endif\nvoid CORE_dgemm_p3_quark(Quark* quark)\n{\n    PLASMA_enum transA;\n    PLASMA_enum transB;\n    int M;\n    int N;\n    int K;\n    double alpha;\n    double *A;\n    int LDA;\n    double *B;\n    int LDB;\n    double beta;\n    double **C;\n    int LDC;\n\n    quark_unpack_args_13(quark, transA, transB, M, N, K, alpha,\n                         A, LDA, B, LDB, beta, C, LDC);\n    cblas_dgemm(\n        CblasColMajor,\n        (CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB,\n        M, N, K,\n        (alpha), A, LDA,\n        B, LDB,\n        (beta), *C, LDC);\n}\n\n/***************************************************************************//**\n *\n **/\nvoid QUARK_CORE_dgemm_p2f1(Quark *quark, Quark_Task_Flags *task_flags,\n                           PLASMA_enum transA, int transB,\n                           int m, int n, int k, int nb,\n                           double alpha, const double *A, int lda,\n                           const double **B, int ldb,\n                           double beta, double *C, int ldc,\n                           double *fake1, int szefake1, int flag1)\n{\n    DAG_CORE_GEMM;\n    QUARK_Insert_Task(quark, CORE_dgemm_p2f1_quark, task_flags,\n        sizeof(PLASMA_enum),                &transA,    VALUE,\n        sizeof(PLASMA_enum),                &transB,    VALUE,\n        sizeof(int),                        &m,         VALUE,\n        sizeof(int),                        &n,         VALUE,\n        sizeof(int),                        &k,         VALUE,\n        sizeof(double),         &alpha,     VALUE,\n        sizeof(double)*lda*nb,   A,                 INPUT,\n        sizeof(int),                        &lda,       VALUE,\n        sizeof(double*),         B,                 INPUT,\n        sizeof(int),                        &ldb,       VALUE,\n        sizeof(double),         &beta,      VALUE,\n        sizeof(double)*ldc*nb,    C,                 INOUT | LOCALITY,\n        sizeof(int),                        &ldc,       VALUE,\n        sizeof(double)*szefake1, fake1,             flag1,\n        0);\n}\n\n/***************************************************************************//**\n *\n **/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_dgemm_p2f1_quark = PCORE_dgemm_p2f1_quark\n#define CORE_dgemm_p2f1_quark PCORE_dgemm_p2f1_quark\n#endif\nvoid CORE_dgemm_p2f1_quark(Quark* quark)\n{\n    PLASMA_enum transA;\n    PLASMA_enum transB;\n    int M;\n    int N;\n    int K;\n    double alpha;\n    double *A;\n    int LDA;\n    double **B;\n    int LDB;\n    double beta;\n    double *C;\n    int LDC;\n    void *fake1;\n\n    quark_unpack_args_14(quark, transA, transB, M, N, K, alpha,\n                         A, LDA, B, LDB, beta, C, LDC, fake1);\n    cblas_dgemm(\n        CblasColMajor,\n        (CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB,\n        M, N, K,\n        (alpha), A, LDA,\n        *B, LDB,\n        (beta), C, LDC);\n}\n", "meta": {"hexsha": "fd4c4d16c15a6e8843376fd64af46314b1026d90", "size": 12760, "ext": "c", "lang": "C", "max_stars_repo_path": "core_blas-qwrapper/qwrapper_dgemm.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "core_blas-qwrapper/qwrapper_dgemm.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "core_blas-qwrapper/qwrapper_dgemm.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0549450549, "max_line_length": 94, "alphanum_fraction": 0.4370689655, "num_tokens": 3203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.050330635802546424, "lm_q1q2_score": 0.025165317901273212}}
{"text": "#ifndef DERIVATIVE_H\n#define DERIVATIVE_H\n\n\n#include <memory>\n\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_interp.h>\n#include <gsl/gsl_deriv.h>\n\n#include \"constants.h\"\n\n\nvoid deriv_discrete(gsl_vector *df, gsl_vector *f, double step);\n\n\n#endif // DERIVATIVE_H\n", "meta": {"hexsha": "51b8c2aa734e228866242aaae8599086584ed8a0", "size": 288, "ext": "h", "lang": "C", "max_stars_repo_path": "inc/derivative.h", "max_stars_repo_name": "ichi-rika/glottal-inverse", "max_stars_repo_head_hexsha": "c922ed540278e3c8eec528c2cf66b89e6d310575", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-01-24T17:01:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-26T16:22:08.000Z", "max_issues_repo_path": "inc/derivative.h", "max_issues_repo_name": "ichi-rika/glottal-inverse", "max_issues_repo_head_hexsha": "c922ed540278e3c8eec528c2cf66b89e6d310575", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inc/derivative.h", "max_forks_repo_name": "ichi-rika/glottal-inverse", "max_forks_repo_head_hexsha": "c922ed540278e3c8eec528c2cf66b89e6d310575", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-04-27T00:23:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-27T14:41:25.000Z", "avg_line_length": 15.1578947368, "max_line_length": 64, "alphanum_fraction": 0.7465277778, "num_tokens": 82, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.45326184801538616, "lm_q2_score": 0.05500528829345415, "lm_q1q2_score": 0.024931798622510114}}
{"text": "#include <stdio.h>\n#include <gsl/gsl_vector.h>\n\nint\nmain (void)\n{\n  int i; \n  gsl_vector * v = gsl_vector_alloc (10);\n\n  {  \n     FILE * f = fopen (\"test.dat\", \"r\");\n     gsl_vector_fscanf (f, v);\n     fclose (f);\n  }\n\n  for (i = 0; i < 10; i++)\n    {\n      printf (\"%g\\n\", gsl_vector_get(v, i));\n    }\n\n  gsl_vector_free (v);\n  return 0;\n}\n", "meta": {"hexsha": "203986b27e445f9bdaee4b51c252c3a3ca3aebc3", "size": 341, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/vectorr.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/vectorr.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/vectorr.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 14.2083333333, "max_line_length": 44, "alphanum_fraction": 0.5219941349, "num_tokens": 116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.05582314584698031, "lm_q1q2_score": 0.024870860213651393}}
{"text": "#pragma once\n\n#include <utility>\n#include <iostream>\n#include <initializer_list>\n#include <exception>\n\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_linalg.h>\n\n#include \"utils/fcmp.h\"\n\nnamespace gsl_wrapper\n{\n\n  class Vector\n  {\n  public:\n    // Constructors and destructor\n    Vector(size_t vec_size);\n    Vector(gsl_vector *gsl_vec_ptr);\n\n    Vector(const Vector &copy_from);\n    Vector(Vector &&move_from);\n\n    Vector(std::initializer_list<double> args);\n\n    ~Vector();\n\n    // Member functions\n    auto get_gsl_vector() const -> gsl_vector *;\n    auto size() const -> size_t;\n    auto begin() const -> double *;\n    auto end() const -> double *;\n\n    // Operators\n    auto operator=(const Vector &copy_from) -> Vector &;\n    auto operator=(Vector &&move_from) -> Vector &;\n\n    auto operator==(const Vector &comparasion_vector) -> bool;\n    auto operator!=(const Vector &comparasion_vector) -> bool;\n\n    auto operator[](const size_t index) -> double &;\n    auto operator[](const size_t index) const -> const double &;\n\n    auto operator+(const Vector &add_to) const -> Vector;\n    auto operator-(const Vector &sub) const -> Vector;\n    auto operator*(const double number) const -> Vector;\n\n    // Friend declarations\n    friend auto operator<<(std::ostream &stream, const Vector &to_print) -> std::ostream &;\n    friend auto operator*(const double number, const Vector &vec) -> Vector;\n\n  private:\n    gsl_vector *m_vector_ptr;\n    size_t m_vector_size;\n  };\n\n  inline Vector::Vector(size_t vec_size)\n      : m_vector_ptr{gsl_vector_calloc(vec_size)},\n        m_vector_size{vec_size}\n  {\n  }\n\n  inline Vector::Vector(gsl_vector *gsl_vec_ptr)\n      : m_vector_ptr{gsl_vec_ptr},\n        m_vector_size{gsl_vec_ptr->size}\n  {\n  }\n\n  inline Vector::Vector(const Vector &copy_from)\n      : m_vector_ptr{gsl_vector_calloc(copy_from.m_vector_size)},\n        m_vector_size{copy_from.m_vector_size}\n  {\n    gsl_vector_memcpy(m_vector_ptr, copy_from.m_vector_ptr);\n  }\n\n  inline Vector::Vector(Vector &&move_from)\n      : m_vector_ptr{std::exchange(move_from.m_vector_ptr, nullptr)},\n        m_vector_size{std::exchange(move_from.m_vector_size, 0)}\n  {\n  }\n\n  inline Vector::Vector(std::initializer_list<double> args)\n      : m_vector_ptr{gsl_vector_calloc(args.size())},\n        m_vector_size{args.size()}\n  {\n    size_t i = 0;\n    for (auto &&el : args)\n    {\n      gsl_vector_set(m_vector_ptr, i++, el);\n    }\n  }\n\n  inline Vector::~Vector()\n  {\n    gsl_vector_free(m_vector_ptr);\n  }\n\n  inline auto Vector::get_gsl_vector() const -> gsl_vector *\n  {\n    return m_vector_ptr;\n  }\n\n  inline auto Vector::size() const -> size_t\n  {\n    return m_vector_size;\n  }\n\n  inline auto Vector::begin() const -> double *\n  {\n    return m_vector_ptr->data;\n  }\n\n  inline auto Vector::end() const -> double *\n  {\n    return m_vector_ptr->data + m_vector_size;\n  }\n\n  inline auto Vector::operator=(const Vector &copy_from) -> Vector &\n  {\n    // Prevent self copy\n    if (m_vector_ptr == copy_from.m_vector_ptr)\n      return *this;\n\n    gsl_vector_free(m_vector_ptr);\n    m_vector_ptr = gsl_vector_calloc(copy_from.m_vector_size);\n    gsl_vector_memcpy(m_vector_ptr, copy_from.m_vector_ptr);\n    m_vector_size = copy_from.m_vector_size;\n\n    return *this;\n  }\n\n  inline auto Vector::operator=(Vector &&move_from) -> Vector &\n  {\n    // Prevent self move\n    if (m_vector_ptr == move_from.m_vector_ptr)\n      return *this;\n\n    gsl_vector_free(m_vector_ptr);\n    m_vector_ptr = std::exchange(move_from.m_vector_ptr, nullptr);\n    m_vector_size = std::exchange(move_from.m_vector_size, 0);\n\n    return *this;\n  }\n\n  inline auto Vector::operator==(const Vector &comparasion_vector) -> bool\n  {\n    if (m_vector_size != comparasion_vector.m_vector_size)\n      return false;\n\n    for (size_t i = 0; i < m_vector_size; i++)\n    {\n      bool test = ::gsl_wrapper::utils::equal((*this)[i], comparasion_vector[i]);\n      if (!test)\n        return false;\n    }\n    return true;\n  }\n\n  inline auto Vector::operator!=(const Vector &comparasion_vector) -> bool\n  {\n    return !(*this == comparasion_vector);\n  }\n\n  inline auto Vector::operator[](const size_t index) -> double &\n  {\n    if (index >= m_vector_size)\n      throw std::range_error{\"Accesing vector elements out of bounds\"};\n    return *gsl_vector_ptr(m_vector_ptr, index);\n  }\n\n  inline auto Vector::operator[](const size_t index) const -> const double &\n  {\n    return *gsl_vector_const_ptr(m_vector_ptr, index);\n  }\n\n  inline auto operator<<(std::ostream &stream, const Vector &to_print) -> std::ostream &\n  {\n    for (size_t i = 0; i < to_print.m_vector_size - 1; i++)\n    {\n      stream << to_print[i] << \" \";\n    }\n    stream << to_print[to_print.m_vector_size - 1];\n\n    return stream;\n  }\n\n  inline auto Vector::operator+(const Vector &add_to) const -> Vector\n  {\n    if (m_vector_size != add_to.m_vector_size)\n      throw std::range_error{\"Adding vector of diffrent sizes\"};\n\n    Vector result(m_vector_size);\n\n    for (size_t i = 0; i < m_vector_size; i++)\n    {\n      result[i] = (*this)[i] + add_to[i];\n    }\n\n    return result;\n  }\n\n  inline auto Vector::operator-(const Vector &sub) const -> Vector\n  {\n    if (m_vector_size != sub.m_vector_size)\n      throw std::range_error{\"Subtracting vector of diffrent sizes\"};\n\n    Vector result(m_vector_size);\n\n    for (size_t i = 0; i < m_vector_size; i++)\n    {\n      result[i] = (*this)[i] - sub[i];\n    }\n\n    return result;\n  }\n\n  inline auto Vector::operator*(const double number) const -> Vector\n  {\n    Vector result = *this;\n    for (auto &&el : result)\n    {\n      el *= number;\n    }\n\n    return result;\n  }\n\n  inline auto operator*(const double number, const Vector &vec) -> Vector\n  {\n    Vector result = vec;\n    for (auto &&el : result)\n    {\n      el *= number;\n    }\n\n    return result;\n  }\n\n}", "meta": {"hexsha": "e92f30dccbbd32f476cb4f319443eea03fe4ac64", "size": 5796, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gsl_wrapper/vector.h", "max_stars_repo_name": "Szynkaa/gsl_cpp_wrapper", "max_stars_repo_head_hexsha": "0c9c4edfe751474edbf1a9a23075762cc3362cc1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/gsl_wrapper/vector.h", "max_issues_repo_name": "Szynkaa/gsl_cpp_wrapper", "max_issues_repo_head_hexsha": "0c9c4edfe751474edbf1a9a23075762cc3362cc1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gsl_wrapper/vector.h", "max_forks_repo_name": "Szynkaa/gsl_cpp_wrapper", "max_forks_repo_head_hexsha": "0c9c4edfe751474edbf1a9a23075762cc3362cc1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0497925311, "max_line_length": 91, "alphanum_fraction": 0.6518288475, "num_tokens": 1498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334000459303, "lm_q2_score": 0.06097517617237108, "lm_q1q2_score": 0.02483722582869151}}
{"text": "// Copyright (c) Microsoft Corporation.\r\n// Licensed under the MIT license.\r\n\r\n// clang-format off\r\n\r\n#pragma once\r\n\r\n\r\n#pragma warning(push)\r\n\r\n// C\r\n#include <climits>\r\n#include <cwchar>\r\n#include <cwctype>\r\n\r\n// STL\r\n\r\n// Block minwindef.h min/max macros to prevent <algorithm> conflict\r\n#define NOMINMAX\r\n\r\n#include <algorithm>\r\n#include <atomic>\r\n#include <deque>\r\n#include <list>\r\n#include <memory>\r\n#include <map>\r\n#include <mutex>\r\n#include <shared_mutex>\r\n#include <new>\r\n#include <optional>\r\n#include <queue>\r\n#include <stdexcept>\r\n#include <string>\r\n#include <string_view>\r\n#include <thread>\r\n#include <tuple>\r\n#include <utility>\r\n#include <vector>\r\n#include <unordered_map>\r\n#include <iterator>\r\n#include <math.h>\r\n#include <sstream>\r\n#include <fstream>\r\n#include <iomanip>\r\n#include <filesystem>\r\n#include <functional>\r\n#include <set>\r\n#include <unordered_set>\r\n\r\n// WIL\r\n#include <wil/Common.h>\r\n#include <wil/Result.h>\r\n#include <wil/resource.h>\r\n#include <wil/wistd_memory.h>\r\n#include <wil/stl.h>\r\n#include <wil/com.h>\r\n#include <wil/filesystem.h>\r\n#include <wil/win32_helpers.h>\r\n\r\n// GSL\r\n// Block GSL Multi Span include because it both has C++17 deprecated iterators\r\n// and uses the C-namespaced \"max\" which conflicts with Windows definitions.\r\n#ifndef BLOCK_GSL\r\n#define GSL_MULTI_SPAN_H\r\n#include <gsl/gsl>\r\n#endif\r\n\r\n// CppCoreCheck\r\n#include <CppCoreCheck/Warnings.h>\r\n\r\n// IntSafe\r\n#define ENABLE_INTSAFE_SIGNED_FUNCTIONS\r\n#include <intsafe.h>\r\n\r\n// SAL\r\n#include <sal.h>\r\n\r\n// WRL\r\n#include <wrl.h>\r\n\r\n// TIL - Terminal Implementation Library\r\n#include \"til.h\"\r\n\r\n#pragma warning(pop)\r\n\r\n// clang-format on\r\n", "meta": {"hexsha": "3033cc1055c276390bd326665cc9b920dbf507d5", "size": 1635, "ext": "h", "lang": "C", "max_stars_repo_path": "src/inc/LibraryIncludes.h", "max_stars_repo_name": "Vereis/terminal", "max_stars_repo_head_hexsha": "6d6fb7f69058b78af0c77e376bed7228ad9eb41f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-08T06:55:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T12:56:42.000Z", "max_issues_repo_path": "src/inc/LibraryIncludes.h", "max_issues_repo_name": "Vereis/terminal", "max_issues_repo_head_hexsha": "6d6fb7f69058b78af0c77e376bed7228ad9eb41f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/inc/LibraryIncludes.h", "max_forks_repo_name": "Vereis/terminal", "max_forks_repo_head_hexsha": "6d6fb7f69058b78af0c77e376bed7228ad9eb41f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.7931034483, "max_line_length": 79, "alphanum_fraction": 0.6941896024, "num_tokens": 375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.05340333243628599, "lm_q1q2_score": 0.024827293166204804}}
{"text": "/*\n * Copyright 2020 Makani Technologies LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#ifndef SIM_MATH_ODE_SOLVER_H_\n#define SIM_MATH_ODE_SOLVER_H_\n\n#include <stdint.h>\n\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_odeiv2.h>\n\n#include <vector>\n\nnamespace sim {\n\n// Enumeration for return codes.\nenum class OdeSolverStatus { kSuccess, kError, kOutOfPhysics };\n\n// Interface representing a system of ordinary differential equations.\nclass OdeSystem {\n public:\n  virtual ~OdeSystem() {}\n\n  // Get the number of states for the ODE.\n  virtual int32_t num_states() const = 0;\n\n  // Calculate the state derivative for a given time and state.\n  virtual void CalcDerivatives(double t, const std::vector<double> &x,\n                               std::vector<double> *dx) const = 0;\n};\n\n// Interface for ODE solvers.\nclass OdeSolver {\n public:\n  virtual ~OdeSolver() {}\n\n  // Integrate the ODE with initial condition x0 at time t0 until time tf.\n  //\n  // Args:\n  //   t0: Initial time.\n  //   tf: Final time (>= t0).\n  //   x0: Initial state.\n  //   t_int: Null pointer or output time at which the integrator terminated.\n  //   x: Terminal state.  It should be safe to reuse x0 as x.\n  //\n  // Returns:\n  //   kSuccess on success (indicating *t_int = tf) and kError otherwise.\n  virtual OdeSolverStatus Integrate(double t0, double tf,\n                                    const std::vector<double> &x0,\n                                    double *t_int, std::vector<double> *x) = 0;\n};\n\n}  // namespace sim\n\n#endif  // SIM_MATH_ODE_SOLVER_H_\n", "meta": {"hexsha": "dde812e030b103635de3508d0c75c29b5f22c1ac", "size": 2055, "ext": "h", "lang": "C", "max_stars_repo_path": "sim/math/ode_solver.h", "max_stars_repo_name": "leozz37/makani", "max_stars_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1178.0, "max_stars_repo_stars_event_min_datetime": "2020-09-10T17:15:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:59:35.000Z", "max_issues_repo_path": "sim/math/ode_solver.h", "max_issues_repo_name": "leozz37/makani", "max_issues_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-22T05:22:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-22T05:22:35.000Z", "max_forks_repo_path": "sim/math/ode_solver.h", "max_forks_repo_name": "leozz37/makani", "max_forks_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 107.0, "max_forks_repo_forks_event_min_datetime": "2020-09-10T17:29:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T09:00:14.000Z", "avg_line_length": 29.7826086957, "max_line_length": 79, "alphanum_fraction": 0.6773722628, "num_tokens": 509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.049589020526013265, "lm_q1q2_score": 0.024794510263006633}}
{"text": "#ifndef QDM_THETA_H\n#define QDM_THETA_H 1\n\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_vector.h>\n\nint\nqdm_theta_optimize(\n    gsl_vector *result,\n    gsl_vector *emperical_quantiles,\n    gsl_matrix *ix\n);\n\nvoid\nqdm_theta_matrix_constrain(\n    gsl_matrix *theta,\n    double min\n);\n\n#endif /* QDM_THETA_H */\n", "meta": {"hexsha": "6c23626d3c35daa28ee23cbf5d6694894fea18cf", "size": 308, "ext": "h", "lang": "C", "max_stars_repo_path": "include/qdm/theta.h", "max_stars_repo_name": "calebcase/qdm", "max_stars_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/qdm/theta.h", "max_issues_repo_name": "calebcase/qdm", "max_issues_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-03-06T18:09:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-22T20:22:53.000Z", "max_forks_repo_path": "include/qdm/theta.h", "max_forks_repo_name": "calebcase/qdm", "max_forks_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.6666666667, "max_line_length": 36, "alphanum_fraction": 0.7305194805, "num_tokens": 93, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.05033063081688277, "lm_q1q2_score": 0.024772139351413154}}
{"text": "/* spcompress.c\n * \n * Copyright (C) 2012-2014, 2016 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <stdlib.h>\n#include <math.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_spmatrix.h>\n\n/*\ngsl_spmatrix_ccs()\n  Create a sparse matrix in compressed column format\n\nInputs: T - sparse matrix in triplet format\n\nReturn: pointer to new matrix (should be freed when finished with it)\n*/\n\ngsl_spmatrix *\ngsl_spmatrix_ccs(const gsl_spmatrix *T)\n{\n  if (!GSL_SPMATRIX_ISTRIPLET(T))\n    {\n      GSL_ERROR_NULL(\"matrix must be in triplet format\", GSL_EINVAL);\n    }\n  else\n    {\n      const size_t *Tj; /* column indices of triplet matrix */\n      size_t *Cp;       /* column pointers of compressed column matrix */\n      size_t *w;        /* copy of column pointers */\n      gsl_spmatrix *m;\n      size_t n;\n\n      m = gsl_spmatrix_alloc_nzmax(T->size1, T->size2, T->nz,\n                                   GSL_SPMATRIX_CCS);\n      if (!m)\n        return NULL;\n\n      Tj = T->p;\n      Cp = m->p;\n\n      /* initialize column pointers to 0 */\n      for (n = 0; n < m->size2 + 1; ++n)\n        Cp[n] = 0;\n\n      /*\n       * compute the number of elements in each column:\n       * Cp[j] = # non-zero elements in column j\n       */\n      for (n = 0; n < T->nz; ++n)\n        Cp[Tj[n]]++;\n\n      /* compute column pointers: p[j] = p[j-1] + nnz[j-1] */\n      gsl_spmatrix_cumsum(m->size2, Cp);\n\n      /* make a copy of the column pointers */\n      w = (size_t *) m->work;\n      for (n = 0; n < m->size2; ++n)\n        w[n] = Cp[n];\n\n      /* transfer data from triplet format to CCS */\n      for (n = 0; n < T->nz; ++n)\n        {\n          size_t k = w[Tj[n]]++;\n          m->i[k] = T->i[n];\n          m->data[k] = T->data[n];\n        }\n\n      m->nz = T->nz;\n\n      return m;\n    }\n}\n\ngsl_spmatrix *\ngsl_spmatrix_compcol(const gsl_spmatrix *T)\n{\n  return gsl_spmatrix_ccs(T);\n}\n\n/*\ngsl_spmatrix_crs()\n  Create a sparse matrix in compressed row format\n\nInputs: T - sparse matrix in triplet format\n\nReturn: pointer to new matrix (should be freed when finished with it)\n*/\n\ngsl_spmatrix *\ngsl_spmatrix_crs(const gsl_spmatrix *T)\n{\n  if (!GSL_SPMATRIX_ISTRIPLET(T))\n    {\n      GSL_ERROR_NULL(\"matrix must be in triplet format\", GSL_EINVAL);\n    }\n  else\n    {\n      const size_t *Ti; /* row indices of triplet matrix */\n      size_t *Cp;       /* row pointers of compressed row matrix */\n      size_t *w;        /* copy of column pointers */\n      gsl_spmatrix *m;\n      size_t n;\n\n      m = gsl_spmatrix_alloc_nzmax(T->size1, T->size2, T->nz,\n                                   GSL_SPMATRIX_CRS);\n      if (!m)\n        return NULL;\n\n      Ti = T->i;\n      Cp = m->p;\n\n      /* initialize row pointers to 0 */\n      for (n = 0; n < m->size1 + 1; ++n)\n        Cp[n] = 0;\n\n      /*\n       * compute the number of elements in each row:\n       * Cp[i] = # non-zero elements in row i\n       */\n      for (n = 0; n < T->nz; ++n)\n        Cp[Ti[n]]++;\n\n      /* compute row pointers: p[i] = p[i-1] + nnz[i-1] */\n      gsl_spmatrix_cumsum(m->size1, Cp);\n\n      /* make a copy of the row pointers */\n      w = (size_t *) m->work;\n      for (n = 0; n < m->size1; ++n)\n        w[n] = Cp[n];\n\n      /* transfer data from triplet format to CRS */\n      for (n = 0; n < T->nz; ++n)\n        {\n          size_t k = w[Ti[n]]++;\n          m->i[k] = T->p[n];\n          m->data[k] = T->data[n];\n        }\n\n      m->nz = T->nz;\n\n      return m;\n    }\n}\n\n/*\ngsl_spmatrix_cumsum()\n\nCompute the cumulative sum:\n\np[j] = Sum_{k=0...j-1} c[k]\n\n0 <= j < n + 1\n\nAlternatively,\np[0] = 0\np[j] = p[j - 1] + c[j - 1]\n\nInputs: n - length of input array\n        c - (input/output) array of size n + 1\n            on input, contains the n values c[k]\n            on output, contains the n + 1 values p[j]\n\nReturn: success or error\n*/\n\nvoid\ngsl_spmatrix_cumsum(const size_t n, size_t *c)\n{\n  size_t sum = 0;\n  size_t k;\n\n  for (k = 0; k < n; ++k)\n    {\n      size_t ck = c[k];\n      c[k] = sum;\n      sum += ck;\n    }\n\n  c[n] = sum;\n} /* gsl_spmatrix_cumsum() */\n", "meta": {"hexsha": "d680fa550b80e4fc1f290dbbc1ab670bcf337923", "size": 4752, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.4/spmatrix/spcompress.c", "max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-13T05:01:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-13T05:01:59.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/spmatrix/spcompress.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/spmatrix/spcompress.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8793969849, "max_line_length": 81, "alphanum_fraction": 0.5637626263, "num_tokens": 1434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3775406547908327, "lm_q2_score": 0.06560483152162024, "lm_q1q2_score": 0.024768491050114767}}
{"text": "/*\n  10 Sept 08: Process_Error_Code is now static and thus private to\n              this library.\n*/\n\n#include <cblas.h>\n#include \"lbl.h\"\n#include \"ma57.h\"\n\n#ifdef __cplusplus\nextern \"C\" {   /* To prevent C++ compilers from mangling symbols */\n#endif\n\n  /* ================================================================= */\n\n#ifdef  __FUNCT__\n#undef  __FUNCT__\n#endif\n#define __FUNCT__ \"Process_Error_Code\"\nstatic int Process_Error_Code( Ma57_Data *ma57, int nerror ) {\n\n    LOGMSG( \" [%3d]\", nerror );\n    /* Take appropriate action according to error code */\n    /* Inflation factors are from the MA57 spec sheet  */\n    switch( nerror ) {\n\n    case 0:\n      break;\n\n      /* Warnings */\n    case 1:\n      LOGMSG( \" Found and ignored %d indices out of range.\\n\", ma57->info[2] );\n      break;\n\n    case 2:\n      LOGMSG( \" Found and summed %d duplicate entries.\\n\", ma57->info[3] );\n      break;\n\n    case 3:\n      LOGMSG( \" Found duplicate and out-of-range indices.\\n\" );\n      break;\n\n    case 4:\n      LOGMSG( \" Matrix has rank %d, deficient.\\n\", ma57->info[24] );\n      break;\n\n    case 5:\n      LOGMSG( \" Found %d pivot sign changes in definite matrix.\\n\",\n              ma57->info[25] );\n      break;\n\n    case 8:\n      LOGMSG( \" Infinity norm of solution found to be zero.\\n\" );\n      break;\n\n    case 10:\n      LOGMSG( \" Insufficient real space. Increased LFACT to %d.\\n\",\n              ma57->lfact );\n      break;\n\n    case 11:\n      LOGMSG( \" Insufficient integer space. Increased LIFACT to %d.\\n\",\n              ma57->lifact );\n      break;\n\n      /* Errors */\n    case -1:\n      LOGMSG( \" Value of n is out of range: %d.\\n\", ma57->info[1] );\n      break;\n\n    case -2:\n      LOGMSG( \" Value of nz is out of range: %d.\\n\", ma57->info[1] );\n      break;\n\n    case -3:\n      LOGMSG( \" Adjusted size of array FACT to %d.\\n\", ma57->lfact );\n      break;\n\n    case -4:\n      LOGMSG( \" Adjusting size of array IFACT to %d.\\n\", ma57->lifact );\n      break;\n\n    case -5:\n      LOGMSG( \" Small pivot encountered at pivot step %d. Threshold = %lf.\\n\",\n              ma57->info[1], ma57->cntl[1] );\n\n    case -6:\n      LOGMSG( \" Change in pivot sign detected at pivot step %d.\\n\",\n              ma57->info[1] );\n      break;\n\n    case -7:\n      LOGMSG( \" Erroneous sizing of array FACT or IFACT.\\n\" );\n      break;\n\n    case -8:\n      LOGMSG( \" Iterative refinement failed to converge.\\n\" );\n      break;\n\n    case -9:\n      LOGMSG( \" Error in user-supplied permutation array in component %d.\\n\",\n              ma57->info[1] );\n      break;\n\n    case -10:\n      LOGMSG( \" Unknown pivoting strategy: %d\\n.\", ma57->info[1] );\n      break;\n\n    case -11:\n      LOGMSG( \" Size of RHS must be %d. Received %d.\\n\",\n              ma57->n, ma57->info[1] );\n      break;\n\n    case -12:\n      LOGMSG( \" Invalid value of JOB (%d).\\n\", ma57->info[1] );\n      break;\n\n    case -13:\n      LOGMSG( \" Invalid number of iterative refinement steps (%d).\\n\",\n              ma57->info[1] );\n      break;\n\n    case -14:\n      LOGMSG( \" Failed to estimate condition number.\\n\" );\n      break;\n\n    case -15:\n      LOGMSG( \" LKEEP has value %d, less than minimum allowed.\\n\",\n              ma57->info[1] );\n      break;\n\n    case -16:\n      LOGMSG( \" Invalid number of RHS (%d).\\n\", ma57->info[1] );\n      break;\n\n    case -17:\n      LOGMSG( \" Increasing size of LWORK to %d.\\n\", ma57->lwork );\n      break;\n\n    case -18:\n      LOGMSG( \" MeTiS library not available or not found.\\n\" );\n      break;\n\n    default:\n      LOGMSG( \" Unrecognized flag from Factorize().\" );\n      nerror = -30;\n    }    \n    return nerror;\n  }\n\n  /* ================================================================= */\n\n#ifdef  __FUNCT__\n#undef  __FUNCT__\n#endif\n#define __FUNCT__ \"MA57_Initialize\"\n  Ma57_Data *Ma57_Initialize( int nz, int n, FILE *logfile ) {\n\n    /* Call initialize subroutine MA57ID and set defaults */\n    Ma57_Data *ma57 = (Ma57_Data *)LBL_Calloc( 1, sizeof(Ma57_Data) );\n    ma57->logfile   = logfile;\n\n    LOGMSG( \" MA57 :: Initializing...\" );\n\n    ma57->n         = n;\n    ma57->nz        = nz;\n    ma57->fetched   = 0;\n    ma57->irn       = (int *)LBL_Calloc( nz, sizeof(int) );\n    ma57->jcn       = (int *)LBL_Calloc( nz, sizeof(int) );\n    ma57->lkeep     = 5*n + nz + imax(n,nz) + 42 + n; // Add n to suggested val.\n    ma57->keep      = (int *)LBL_Calloc( ma57->lkeep, sizeof(int) );\n    ma57->iwork     = (int *)LBL_Calloc( 5*n, sizeof(int) );\n    ma57->work      = NULL; // Will be initialized in Ma57_Solve()\n\n    LOGMSG( \" Calling ma57id...\" );\n    MA57ID( ma57->cntl, ma57->icntl ); // Initialize all parameters\n\n    // Ensure some default parameters are appropriate\n    ma57->icntl[0] = -1;  // Stream for error messages.\n    ma57->icntl[1] = -1;  // Stream for warning messages.\n    ma57->icntl[2] = -1;  // Stream for monitoring printing.\n    ma57->icntl[3] = -1;  // Stream for printing of statistics.\n    ma57->icntl[4] =  0;  // Verbosity: 0=none, 1=errors, 2=1+warnings,\n                          //            3=2+monitor, 4=3+input,output\n    ma57->icntl[5] =  5;  // Pivot selection strategy:\n                          //  0: AMD using MC47\n                          //  1: User-supplied pivot sequence\n                          //  2: AMD with dense row strategy\n                          //  3: MD as in MA27\n                          //  4: MeTiS\n                          //  5: Automatic (4 with fallback on 2)\n    ma57->icntl[6] =  1;  // Numerical pivoting strategy\n                          //  1: Do pivoting using value in cntl(1)\n                          //  2: No pivoting; exit on sign change or zero\n                          //  3: No pivoting; exit if pivot modulus < cntl(2)\n                          //  4: No pivoting; alter pivots to have same sign\n    ma57->icntl[7] =  1;  // Memory will be re-allocated if necessary\n    ma57->icntl[15] = 0;  // No need to scale system before factorizing    \n    ma57->fetched = 0;\n\n    LOGMSG( \" done\\n\");\n    return ma57;\n  }\n\n  /* ================================================================= */\n\n#ifdef  __FUNCT__\n#undef  __FUNCT__\n#endif\n#define __FUNCT__ \"Ma57_Analyze\"\n  int Ma57_Analyze( Ma57_Data *ma57 ) {\n\n    int finished = 0, error;\n    LOGMSG( \" MA57 :: Analyzing...\" );\n\n    /* Unpack data structure and call MA57AD */\n    while( !finished ) {\n      LOGMSG( \"\\n         Calling ma57ad... \" );\n\n      MA57AD( &(ma57->n), &(ma57->nz), ma57->irn, ma57->jcn,\n              &(ma57->lkeep), ma57->keep, ma57->iwork, ma57->icntl,\n              ma57->info, ma57->rinfo );\n\n      error = ma57->info[0];\n\n      if( !error )\n        finished = 1;\n      else {\n        error = Process_Error_Code( ma57, error );\n        if( error != -3 && error != -4 && error != -8 && error != -14 )\n          return error;\n      }\n    }\n\n    // Allocate data for Factorize()\n    ma57->lfact = ceil( LFACT_GROW * ma57->info[8] );\n    ma57->fact = (double *)LBL_Calloc( ma57->lfact, sizeof(double) );\n    ma57->lifact = ceil( LIFACT_GROW * ma57->info[9] );\n    ma57->ifact = (int *)LBL_Calloc( ma57->lifact, sizeof(int) );\n    LBL_Free( ma57->iwork );\n    ma57->iwork = (int *)LBL_Calloc( ma57->n, sizeof(int) );\n    ma57->work = NULL;\n\n    LOGMSG( \" done\\n\");\n    return 0;\n  }\n\n  /* ================================================================= */\n\n#ifdef  __FUNCT__\n#undef  __FUNCT__\n#endif\n#define __FUNCT__ \"Ma57_Factorize\"\n  int Ma57_Factorize( Ma57_Data *ma57, double A[] ) {\n\n    // To ensure consistency with the MA27 interface, the user must pass\n    // the array A, *including* its zero-th element. Internally, A+1 is\n    // passed to MA57.\n\n    double *newFact;\n    int    *newIfact;\n    int     newSize, one = 1, zero = 0;\n    int     finished = 0, error;\n    LOGMSG( \" MA57 :: Factorizing...\\n\" );\n        \n    /* Unpack data structure and call MA57BD */\n    while( !finished ) {\n      LOGMSG( \"         Calling ma57bd... \" );\n\n      MA57BD( &(ma57->n), &(ma57->nz), A, ma57->fact, &(ma57->lfact),\n              ma57->ifact, &(ma57->lifact), &(ma57->lkeep), ma57->keep,\n              ma57->iwork, ma57->icntl, ma57->cntl, ma57->info, ma57->rinfo );\n\n      error = ma57->info[0];\n\n      if( !error ) {\n\n        finished = 1;\n\n      } else {\n\n        error = Process_Error_Code( ma57, error );\n\n        if( error == -3 || error == 10 ) {\n\n          /* Resize real workspace */\n          newSize = (error == 10) ? ma57->lfact : ma57->info[16];\n          newSize = ceil( LFACT_GROW * newSize );\n          LOGMSG(\"         Resizing real workspace for factors to %d\", newSize);\n          newFact = (double *)LBL_Calloc( newSize, sizeof(double) );\n          MA57ED( &(ma57->n), &zero, ma57->keep, ma57->fact, &(ma57->lfact),\n                  newFact, &newSize, ma57->ifact, &(ma57->lifact), NULL,\n                  &zero, ma57->info );\n          LBL_Free( ma57->fact );\n          ma57->fact = newFact; newFact = NULL;\n          ma57->lfact = newSize;\n\n        } else if( error == -4 || error == 11 ) {\n\n          /* Resize integer workspace */\n          newSize = (error == 11) ? ma57->lifact : ma57->info[17];\n          newSize = ceil( LIFACT_GROW * newSize );\n          LOGMSG(\"         Resizing int workspace for factors to %d\", newSize);\n          newIfact = (int *)LBL_Calloc( newSize, sizeof(int) );\n          MA57ED( &(ma57->n), &one, ma57->keep, ma57->fact, &(ma57->lfact),\n                  NULL, &zero, ma57->ifact, &(ma57->lifact), newIfact,\n                  &newSize, ma57->info );\n          LBL_Free( ma57->ifact );\n          ma57->ifact = newIfact; newIfact = NULL;\n          ma57->lifact = newSize;\n\n        } else {\n          finished = 1;\n          if( error < 0 ) return error;\n        }\n      }\n    }\n\n    LOGMSG(\"\\n\");\n    LOGMSG(\"         %-23s: %6i   %-28s: %6i\\n\",\n           \"No. of 2x2 pivots\"            , ma57->info[21],\n           \"Pivot step for modification\"  , ma57->info[26]);\n    LOGMSG(\"         %-28s: %6i   %-28s: %6i\\n\",\n           \"No. of negative e-vals\"       , ma57->info[23],\n           \"No. of entries in factor\"     , ma57->info[13]);\n    LOGMSG(\"         %-28s: %6i   %-28s: %6i\\n\",\n           \"Rank of factorization\"        , ma57->info[24],\n           \"No. of pivot sign changes\"    , ma57->info[25]);\n    LOGMSG(\"         done\\n\");\n    return 0;\n  }\n\n  /* ================================================================= */\n\n#ifdef  __FUNCT__\n#undef  __FUNCT__\n#endif\n#define __FUNCT__ \"Ma57_Solve\"\n  int Ma57_Solve( Ma57_Data *ma57, double x[] ) {\n\n    int one = 1, finished = 0, error;\n\n    LOGMSG( \" MA57 :: Solving...\" );\n\n    ma57->job = 1;\n    ma57->lrhs = ma57->n;\n    ma57->nrhs = 1;\n    ma57->lwork = ma57->n * ma57->nrhs;\n    if( !ma57->work ) {\n      LOGMSG(\"\\n         Sizing work array to size %d \", ma57->lwork);\n      ma57->work = (double *)LBL_Calloc( ma57->lwork, sizeof(double) );\n    }\n\n    while( !finished ) {\n      LOGMSG( \"\\n         Calling ma57cd... \" );\n\n      /* Unpack data structure and call MA57CD */\n      MA57CD( &(ma57->job), &(ma57->n), ma57->fact, &(ma57->lfact),\n              ma57->ifact, &(ma57->lifact), &ma57->nrhs, x, &(ma57->lrhs),\n              ma57->work, &(ma57->lwork), ma57->iwork, ma57->icntl,\n              ma57->info );\n\n      error = ma57->info[0];\n      if( error == -17 ) {\n        LBL_Free( ma57->work );\n        ma57->lwork = ceil( 1.2 * ma57->lwork );\n        LOGMSG(\"\\n         Resizing work array to size %d \", ma57->lwork);\n        ma57->work = (double *)LBL_Calloc( ma57->lwork, sizeof(double) );\n      } else\n        finished = 1;\n      if( error ) error = Process_Error_Code( ma57, error );\n    }\n\n    LOGMSG( \" done\\n\" );\n    return error;\n  }\n\n  /* ================================================================= */\n\n#ifdef  __FUNCT__\n#undef  __FUNCT__\n#endif\n#define __FUNCT__ \"Ma57_Refine\"\n  int Ma57_Refine( Ma57_Data *ma57, double x[], double rhs[],\n                   double A[], int maxitref, int job ) {\n    \n    int error;\n\n    LOGMSG( \" MA57 :: Performing iterative refinement...\" );\n\n    ma57->job = job;\n    /* For values of 'job' that demand the presence of the residual,\n     * it should be placed by the user in ma57->residual prior to calling\n     * this function.\n     */\n\n    /* Allocate work space */\n    ma57->icntl[8] = imax( 1, maxitref );  // Number of refinement iterations\n    ma57->icntl[9] = 1; // Return estimates of condition number\n    LBL_Free( ma57->iwork );\n    ma57->iwork = (int *)LBL_Calloc( ma57->n, sizeof(int) );\n\n    LBL_Free( ma57->work );\n    ma57->lwork = ma57->n;\n    if( ma57->icntl[8] > 1 ) {\n      ma57->lwork += 2 * ma57->n;\n      if( ma57->icntl[9] > 0 )\n        ma57->lwork += 2 * ma57->n;\n    }\n    ma57->work = (double *)LBL_Calloc( ma57->lwork, sizeof(double) );\n    ma57->residual = (double *)LBL_Calloc( ma57->n, sizeof(double) );\n\n    /* Perform iterative refinement */\n    MA57DD( &(ma57->job), &(ma57->n), &(ma57->nz), A, ma57->irn,\n            ma57->jcn, ma57->fact, &(ma57->lfact), ma57->ifact,\n            &(ma57->lifact), rhs, x, ma57->residual, ma57->work,\n            ma57->iwork, ma57->icntl, ma57->cntl, ma57->info,\n            ma57->rinfo );\n\n    error = ma57->info[0];\n    if( error ) error = Process_Error_Code(ma57, ma57->info[0]);\n    LOGMSG( \" done\\n\" );\n    return error;\n  }\n\n  /* ================================================================= */\n\n#ifdef  __FUNCT__\n#undef  __FUNCT__\n#endif\n#define __FUNCT__ \"Ma57_Finalize\"\n  void Ma57_Finalize( Ma57_Data *ma57 ) {\n\n    /* Free allocated memory */\n    LOGMSG( \" MA57 :: Deallocating data arrays...\" );\n    LBL_Free( ma57->irn );\n    LBL_Free( ma57->jcn );\n    LBL_Free( ma57->keep );\n    LBL_Free( ma57->iwork );\n    LBL_Free( ma57->fact );\n    LBL_Free( ma57->ifact );\n    LBL_Free( ma57->work );\n    if( ma57->residual ) LBL_Free(ma57->residual);\n    LOGMSG( \" done.\\n\" );\n    free(ma57);\n    return;\n  }\n\n  /* ================================================================= */\n    /* Currently, this routine doesn't do error checking on the\n       allowable parameter values. */\n\n#ifdef  __FUNCT__\n#undef  __FUNCT__\n#endif\n#define __FUNCT__ \"Ma57_set_int_parm\"\n  void Ma57_set_int_parm( Ma57_Data *ma57, int parm, int val ) {\n\n      switch (parm) {\n      case MA57_I_PIV_SELECTION:\n          ma57->icntl[MA57_I_PIV_SELECTION] = val;\n          LOGMSG(\" Set %-20s = %10d\\n\",\"I_PIV_SELECTION\",val);\n          break;\n      case MA57_I_PIV_NUMERICAL:\n          ma57->icntl[MA57_I_PIV_NUMERICAL] = val;\n          LOGMSG(\" Set %-20s = %10d\\n\",\"I_PIV_NUMERICAL\",val);\n          break;\n      case MA57_I_SCALING:\n          ma57->icntl[MA57_I_SCALING] = val;\n          LOGMSG(\" Set %-20s = %10d\\n\",\"I_SCALING\",val);\n          break;                 \n      }\n      return;\n  }\n\n  /* ================================================================= */\n    /* Currently, this routine doesn't do error checking on the\n       allowable parameter values. */\n\n#ifdef  __FUNCT__\n#undef  __FUNCT__\n#endif\n#define __FUNCT__ \"Ma57_set_real_parm\"\n  void Ma57_set_real_parm( Ma57_Data *ma57, int parm, double val ) {\n\n      switch (parm) {\n      case MA57_D_PIV_THRESH:\n          ma57->cntl[MA57_D_PIV_THRESH] = val;\n          LOGMSG(\" Set %-20s = %10.2e\\n\",\"D_PIV_THRESH\",val);\n          break;\n      case MA57_D_PIV_NONZERO:\n          ma57->cntl[MA57_D_PIV_NONZERO] = val;\n          LOGMSG(\" Set %-20s = %10.2e\\n\",\"D_PIV_NONZERO\",val);\n          break;\n      }\n      return;\n  }\n\n  /* ================================================================= */\n\n#ifdef  __FUNCT__\n#undef  __FUNCT__\n#endif\n#define __FUNCT__ \"Ma57_get_int_parm\"\n  int Ma57_get_int_parm( Ma57_Data *ma57, int parm ) {\n\n      switch (parm) {\n      case MA57_I_PIV_SELECTION:\n          return ma57->icntl[MA57_I_PIV_SELECTION];\n      case MA57_I_PIV_NUMERICAL:\n          return ma57->icntl[MA57_I_PIV_NUMERICAL];\n      case MA57_I_SCALING:\n          return ma57->icntl[MA57_I_SCALING];\n      }\n      return 0;\n  }\n\n  /* ================================================================= */\n\n#ifdef  __FUNCT__\n#undef  __FUNCT__\n#endif\n#define __FUNCT__ \"Ma57_get_real_parm\"\n  double Ma57_get_real_parm( Ma57_Data *ma57, int parm ) {\n\n      switch (parm) {\n      case MA57_D_PIV_THRESH:\n          return ma57->cntl[MA57_D_PIV_THRESH];\n      case MA57_D_PIV_NONZERO:\n          return ma57->cntl[MA57_D_PIV_NONZERO];\n      }\n      return 0.0;\n  }\n\n  /* ================================================================= */\n\n#ifdef __cplusplus\n}              /* Closing brace for  extern \"C\"  block */\n#endif\n", "meta": {"hexsha": "6b1014f9d0dfdf905abb48eb14cf57ae7170a05c", "size": 16468, "ext": "c", "lang": "C", "max_stars_repo_path": "externals/lbl/src/ma57_lib.c", "max_stars_repo_name": "fperignon/sandbox", "max_stars_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2015-06-16T15:55:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T06:01:59.000Z", "max_issues_repo_path": "externals/lbl/src/ma57_lib.c", "max_issues_repo_name": "fperignon/sandbox", "max_issues_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 381.0, "max_issues_repo_issues_event_min_datetime": "2015-09-22T15:31:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T09:05:23.000Z", "max_forks_repo_path": "externals/lbl/src/ma57_lib.c", "max_forks_repo_name": "fperignon/sandbox", "max_forks_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2015-08-06T22:57:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T20:30:20.000Z", "avg_line_length": 30.4962962963, "max_line_length": 80, "alphanum_fraction": 0.5205853777, "num_tokens": 4861, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38861802670584894, "lm_q2_score": 0.06371499291856339, "lm_q1q2_score": 0.024760794819589243}}
{"text": "/* multimin/fdfminimizer.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Fabrice Rossi\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#include <config.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_multimin.h>\n\ngsl_multimin_fdfminimizer *\ngsl_multimin_fdfminimizer_alloc (const gsl_multimin_fdfminimizer_type * T,\n\t\t\t\t size_t n)\n{\n  int status;\n\n  gsl_multimin_fdfminimizer *s =\n    (gsl_multimin_fdfminimizer *) malloc (sizeof (gsl_multimin_fdfminimizer));\n\n  if (s == 0)\n    {\n      GSL_ERROR_VAL (\"failed to allocate space for minimizer struct\",\n\t\t     GSL_ENOMEM, 0);\n    }\n\n  s->type = T;\n\n  s->x = gsl_vector_calloc (n);\n\n  if (s->x == 0) \n    {\n      free (s);\n      GSL_ERROR_VAL (\"failed to allocate space for x\", GSL_ENOMEM, 0);\n    }\n\n  s->gradient = gsl_vector_calloc (n);\n\n  if (s->gradient == 0) \n    {\n      gsl_vector_free (s->x);\n      free (s);\n      GSL_ERROR_VAL (\"failed to allocate space for gradient\", GSL_ENOMEM, 0);\n    }\n\n  s->dx = gsl_vector_calloc (n);\n\n  if (s->dx == 0) \n    {\n      gsl_vector_free (s->x);\n      gsl_vector_free (s->gradient);\n      free (s);\n      GSL_ERROR_VAL (\"failed to allocate space for dx\", GSL_ENOMEM, 0);\n    }\n\n  s->state = malloc (T->size);\n\n  if (s->state == 0)\n    {\n      gsl_vector_free (s->x);\n      gsl_vector_free (s->gradient);\n      gsl_vector_free (s->dx);\n      free (s);\n      GSL_ERROR_VAL (\"failed to allocate space for minimizer state\",\n\t\t     GSL_ENOMEM, 0);\n    }\n\n  status = (T->alloc) (s->state, n);\n\n  if (status != GSL_SUCCESS)\n    {\n      free (s->state);\n      gsl_vector_free (s->x);\n      gsl_vector_free (s->gradient);\n      gsl_vector_free (s->dx);\n      free (s);\n\n      GSL_ERROR_VAL (\"failed to initialize minimizer state\", GSL_ENOMEM, 0);\n    }\n\n  return s;\n}\n\nint\ngsl_multimin_fdfminimizer_set (gsl_multimin_fdfminimizer * s,\n                               gsl_multimin_function_fdf * fdf,\n                               const gsl_vector * x,\n                               double step_size, double tol)\n{\n  if (s->x->size != fdf->n)\n    {\n      GSL_ERROR (\"function incompatible with solver size\", GSL_EBADLEN);\n    }\n  \n  if (x->size != fdf->n) \n    {\n      GSL_ERROR (\"vector length not compatible with function\", GSL_EBADLEN);\n    }  \n    \n  s->fdf = fdf;\n\n  gsl_vector_memcpy (s->x,x);\n  gsl_vector_set_zero (s->dx);\n  \n  return (s->type->set) (s->state, s->fdf, s->x, &(s->f), s->gradient, step_size, tol);\n}\n\nvoid\ngsl_multimin_fdfminimizer_free (gsl_multimin_fdfminimizer * s)\n{\n  (s->type->free) (s->state);\n  free (s->state);\n  gsl_vector_free (s->dx);\n  gsl_vector_free (s->gradient);\n  gsl_vector_free (s->x);\n  free (s);\n}\n\nint\ngsl_multimin_fdfminimizer_iterate (gsl_multimin_fdfminimizer * s)\n{\n  return (s->type->iterate) (s->state, s->fdf, s->x, &(s->f), s->gradient, s->dx);\n}\n\nint\ngsl_multimin_fdfminimizer_restart (gsl_multimin_fdfminimizer * s)\n{\n  return (s->type->restart) (s->state);\n}\n\nconst char * \ngsl_multimin_fdfminimizer_name (const gsl_multimin_fdfminimizer * s)\n{\n  return s->type->name;\n}\n\n\ngsl_vector * \ngsl_multimin_fdfminimizer_x (gsl_multimin_fdfminimizer * s)\n{\n  return s->x;\n}\n\ngsl_vector * \ngsl_multimin_fdfminimizer_dx (gsl_multimin_fdfminimizer * s)\n{\n  return s->dx;\n}\n\ngsl_vector * \ngsl_multimin_fdfminimizer_gradient (gsl_multimin_fdfminimizer * s)\n{\n  return s->gradient;\n}\n\ndouble \ngsl_multimin_fdfminimizer_minimum (gsl_multimin_fdfminimizer * s)\n{\n  return s->f;\n}\n\n", "meta": {"hexsha": "4029c375e9caa3353d8f3304163ed6b707161b24", "size": 4071, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/multimin/fdfminimizer.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/multimin/fdfminimizer.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/multimin/fdfminimizer.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 23.3965517241, "max_line_length": 87, "alphanum_fraction": 0.6502087939, "num_tokens": 1219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.053403330929736405, "lm_q1q2_score": 0.024619831629776864}}
{"text": "#ifndef CWANNIER_ECACHE_H\n#define CWANNIER_ECACHE_H\n\n#include <stdlib.h>\n#include <stdbool.h>\n#include <gsl/gsl_vector.h>\n#include \"input.h\"\n\ntypedef struct {\n    int na;\n    int nb;\n    int nc;\n    int num_bands;\n    int G_order[3];\n    int G_neg[3];\n    InputFn Efn;\n    bool use_cache;\n    gsl_vector **energies;\n} EnergyCache;\n\n#include \"submesh.h\"\n\nEnergyCache* init_EnergyCache(int na, int nb, int nc, int num_bands, int G_order[3], int G_neg[3], InputFn Efn, bool use_cache);\n\nvoid free_EnergyCache(EnergyCache *Ecache);\n\nvoid energy_from_cache(EnergyCache *Ecache, int i, int j, int k, gsl_vector *energies);\n\nvoid verify_sort(gsl_vector *energies);\n\n#endif // CWANNIER_ECACHE_H\n", "meta": {"hexsha": "73492c0d38337da7d2e6ec29fb04531a3b7ba52b", "size": 687, "ext": "h", "lang": "C", "max_stars_repo_path": "ecache.h", "max_stars_repo_name": "tflovorn/ctetra", "max_stars_repo_head_hexsha": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ecache.h", "max_issues_repo_name": "tflovorn/ctetra", "max_issues_repo_head_hexsha": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-11-19T22:44:14.000Z", "max_issues_repo_issues_event_max_datetime": "2016-11-30T15:23:35.000Z", "max_forks_repo_path": "ecache.h", "max_forks_repo_name": "tflovorn/ctetra", "max_forks_repo_head_hexsha": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.46875, "max_line_length": 128, "alphanum_fraction": 0.7176128093, "num_tokens": 202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123158, "lm_q2_score": 0.053403330929736405, "lm_q1q2_score": 0.024619831629776857}}
{"text": "/* trav.c\n * \n * Copyright (C) 2018 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <stdlib.h>\n#include <math.h>\n\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_bst.h>\n#include <gsl/gsl_errno.h>\n\nint\ngsl_bst_trav_init(gsl_bst_trav * trav, const gsl_bst_workspace * w)\n{\n  int status = (w->type->trav_init)((void *) &trav->trav_data, (const void *) &w->table);\n  trav->type = w->type;\n  return status;\n}\n\n/*\ngsl_bst_trav_first()\n  Initialize traverser to least-valued item in tree and return\na pointer to it. Return NULL if tree has no nodes.\n*/\n\nvoid *\ngsl_bst_trav_first(gsl_bst_trav * trav, const gsl_bst_workspace * w)\n{\n  trav->type = w->type;\n  return (w->type->trav_first)((void *) &trav->trav_data, (const void *) &w->table);\n}\n\n/*\ngsl_bst_trav_last()\n  Initializes |trav| for |tree| and selects and returns a pointer\nto its greatest-valued item. Returns NULL if |tree| contains no nodes.\n*/\n\nvoid *\ngsl_bst_trav_last (gsl_bst_trav * trav, const gsl_bst_workspace * w)\n{\n  trav->type = w->type;\n  return (w->type->trav_last)((void * ) &trav->trav_data, (const void *) &w->table);\n}\n\n/*\ngsl_bst_trav_find()\n  Searches for |item| in tree. If found, initializes |trav| to\nthe item found and returns the item as well.  If there is no matching\nitem, initializes |trav| to the null item and returns |NULL|.\n*/\n\nvoid *\ngsl_bst_trav_find (const void * item, gsl_bst_trav * trav, const gsl_bst_workspace * w)\n{\n  trav->type = w->type;\n  return (w->type->trav_find)(item, (void * ) &trav->trav_data, (const void *) &w->table);\n}\n\n/*\ngsl_bst_trav_insert()\n  Attempts to insert |item| into tree.  If |item| is inserted\nsuccessfully, it is returned and |trav| is initialized to its location.\nIf a duplicate is found, it is returned and |trav| is initialized to\nits location.  No replacement of the item occurs.\nIf a memory allocation failure occurs, |NULL| is returned and |trav|\nis initialized to the null item.\n*/\n\nvoid *\ngsl_bst_trav_insert (void * item, gsl_bst_trav * trav, gsl_bst_workspace * w)\n{\n  trav->type = w->type;\n  return (w->type->trav_insert)(item, (void * ) &trav->trav_data, (void *) &w->table);\n}\n\n/*\ngsl_bst_trav_copy()\n  Copy traverser 'src' into 'dest'\n*/\n\nvoid *\ngsl_bst_trav_copy(gsl_bst_trav * dest, const gsl_bst_trav * src)\n{\n  dest->type = src->type;\n  return (src->type->trav_copy)((void * ) &dest->trav_data, (const void *) &src->trav_data);\n}\n\n/*\ngsl_bst_trav_next()\n  Update traverser to point to next sequential node, and\nreturn a pointer to its data\n*/\n\nvoid *\ngsl_bst_trav_next(gsl_bst_trav * trav)\n{\n  return (trav->type->trav_next)((void *) &trav->trav_data);\n}\n\n/*\ngsl_bst_trav_prev()\n  Update traverser to point to previous sequential node, and\nreturn a pointer to its data\n*/\n\nvoid *\ngsl_bst_trav_prev(gsl_bst_trav * trav)\n{\n  return (trav->type->trav_prev)((void *) &trav->trav_data);\n}\n\n/*\ngsl_bst_trav_cur()\n  Return a pointer to data of current traverser node\n*/\n\nvoid *\ngsl_bst_trav_cur(const gsl_bst_trav * trav)\n{\n  return (trav->type->trav_cur)((const void *) &trav->trav_data);\n}\n\n/*\ngsl_bst_trav_replace()\n  Replace current item in trav with new_item and returns the item\nreplaced. The new item must not change the ordering of the tree.\n*/\n\nvoid *\ngsl_bst_trav_replace (gsl_bst_trav * trav, void * new_item)\n{\n  return (trav->type->trav_replace)((void * ) &trav->trav_data, new_item);\n}\n", "meta": {"hexsha": "6442c264a635a18b3f1bd8ebd3dd01ba0f1e2123", "size": 4053, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/bst/trav.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "gsl-2.6/bst/trav.c", "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "test/lib/gsl-2.6/bst/trav.c", "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 26.8410596026, "max_line_length": 92, "alphanum_fraction": 0.7125585986, "num_tokens": 1217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38491214448393357, "lm_q2_score": 0.06371500136344281, "lm_q1q2_score": 0.024524677810599523}}
{"text": "\n// Copyright (C) 2021 Intel Corporation\n// SPDX-License-Identifier: Apache-2.0\n\n#ifndef _HEBench_ClearText_EltMult_H_7e5fa8c2415240ea93eff148ed73539b\n#define _HEBench_ClearText_EltMult_H_7e5fa8c2415240ea93eff148ed73539b\n\n#include <gsl/gsl>\n\n#include \"hebench/api_bridge/cpp/hebench.hpp\"\n\n#include \"clear_benchmark.h\"\n\ntemplate <class T>\nclass EltMult_Benchmark : public ClearTextBenchmark\n{\nprivate:\n    HEBERROR_DECLARE_CLASS_NAME(EltMult_Benchmark)\n\npublic:\n    EltMult_Benchmark(hebench::cpp::BaseEngine &engine,\n                      const hebench::APIBridge::BenchmarkDescriptor &bench_desc,\n                      const hebench::APIBridge::WorkloadParams &bench_params);\n    ~EltMult_Benchmark() override;\n\n    hebench::APIBridge::Handle encode(const hebench::APIBridge::DataPackCollection *p_parameters) override;\n    void decode(hebench::APIBridge::Handle encoded_data, hebench::APIBridge::DataPackCollection *p_native) override;\n\n    hebench::APIBridge::Handle load(const hebench::APIBridge::Handle *p_local_data, std::uint64_t count) override;\n    void store(hebench::APIBridge::Handle remote_data,\n               hebench::APIBridge::Handle *p_local_data, std::uint64_t count) override;\n\n    hebench::APIBridge::Handle operate(hebench::APIBridge::Handle h_remote_packed,\n                                       const hebench::APIBridge::ParameterIndexer *p_param_indexers) override;\n\nprotected:\n    std::uint64_t m_vector_size;\n\nprivate:\n    static void eltMult(gsl::span<T> &result,\n                        const gsl::span<const T> &V0, const gsl::span<const T> &V1,\n                        std::size_t element_count);\n};\n\n#include \"inl/bench_eltmult.inl\"\n\n#endif // defined _HEBench_ClearText_EltMult_H_7e5fa8c2415240ea93eff148ed73539b\n", "meta": {"hexsha": "a290ca217f158c4c63f547e80bb806d7537ed47a", "size": 1747, "ext": "h", "lang": "C", "max_stars_repo_path": "benchmarks/Vector/EltwiseMult/include/bench_eltmult.h", "max_stars_repo_name": "hebench/backend-cpu-cleartext", "max_stars_repo_head_hexsha": "83e4398d9271f3e077bb4dfc0a8fb04ce36e23f6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-28T17:57:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T17:57:32.000Z", "max_issues_repo_path": "benchmarks/Vector/EltwiseMult/include/bench_eltmult.h", "max_issues_repo_name": "hebench/backend-cpu-cleartext", "max_issues_repo_head_hexsha": "83e4398d9271f3e077bb4dfc0a8fb04ce36e23f6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-12-06T19:37:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-16T23:37:53.000Z", "max_forks_repo_path": "benchmarks/Vector/EltwiseMult/include/bench_eltmult.h", "max_forks_repo_name": "hebench/backend-cpu-cleartext", "max_forks_repo_head_hexsha": "83e4398d9271f3e077bb4dfc0a8fb04ce36e23f6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-05T18:01:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-05T18:01:48.000Z", "avg_line_length": 36.3958333333, "max_line_length": 116, "alphanum_fraction": 0.7309673726, "num_tokens": 464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.049589025617623086, "lm_q1q2_score": 0.024407130070948684}}
{"text": "/** @file */\n#ifndef __CCL_CORE_H_INCLUDED__\n#define __CCL_CORE_H_INCLUDED__\n\n#include <stdbool.h>\n#include <stdio.h>\n#include <gsl/gsl_spline.h>\n#include <gsl/gsl_interp2d.h>\n#include <gsl/gsl_spline2d.h>\n#include <gsl/gsl_const_mksa.h>\n\n#include \"ccl_utils.h\"\n#include \"ccl_f1d.h\"\n#include \"ccl_f2d.h\"\n\nCCL_BEGIN_DECLS\n\n/**\n * Struct to hold physical constants.\n */\ntypedef struct ccl_physical_constants {\n  /**\n   * Lightspeed / H0 in units of Mpc/h (from CODATA 2014)\n   */\n  double CLIGHT_HMPC;\n\n  /**\n   * Newton's gravitational constant in units of m^3/Kg/s^2\n   */\n  double GNEWT;\n\n  /**\n   * Solar mass in units of kg (from GSL)\n   */\n  double SOLAR_MASS;\n\n  /**\n   * Mpc to meters (from PDG 2013)\n   */\n  double MPC_TO_METER;\n\n  /**\n   * pc to meters (from PDG 2013)\n   */\n  double PC_TO_METER;\n\n  /**\n   * Rho critical in units of M_sun/h / (Mpc/h)^3\n   */\n  double RHO_CRITICAL;\n\n  /**\n   * Boltzmann constant in units of J/K\n  */\n  double KBOLTZ;\n\n  /**\n   * Stefan-Boltzmann constant in units of kg/s^3 / K^4\n   */\n  double STBOLTZ;\n\n  /**\n   * Planck's constant in units kg m^2 / s\n   */\n  double HPLANCK;\n\n  /**\n   * The speed of light in m/s\n   */\n  double CLIGHT;\n\n  /**\n   * Electron volt to Joules convestion\n   */\n  double EV_IN_J;\n\n  /**\n   * Temperature of the CMB in K\n   */\n  double T_CMB;\n\n  /**\n   * T_ncdm, as taken from CLASS, explanatory.ini\n   */\n  double TNCDM;\n\n  /**\n   * neutrino mass splitting differences\n   * See Lesgourgues and Pastor, 2012 for these values.\n   * Adv. High Energy Phys. 2012 (2012) 608515,\n   * arXiv:1212.6154, page 13\n  */\n  double DELTAM12_sq;\n  double DELTAM13_sq_pos;\n  double DELTAM13_sq_neg;\n} ccl_physical_constants;\n\nextern ccl_physical_constants ccl_constants;\n\n/**\n * Struct that contains all the parameters needed to create certain splines.\n * This includes splines for the scale factor, masses, and power spectra.\n */\ntypedef struct ccl_spline_params {\n  // scale factor splines\n  int A_SPLINE_NA;\n  double A_SPLINE_MIN;\n  double A_SPLINE_MINLOG_PK;\n  double A_SPLINE_MIN_PK;\n  double A_SPLINE_MINLOG_SM;\n  double A_SPLINE_MIN_SM;\n  double A_SPLINE_MAX;\n  double A_SPLINE_MINLOG;\n  int A_SPLINE_NLOG;\n\n  //Mass splines\n  double LOGM_SPLINE_DELTA;\n  int LOGM_SPLINE_NM;\n  double LOGM_SPLINE_MIN;\n  double LOGM_SPLINE_MAX;\n\n  //PS a and k spline\n  int A_SPLINE_NA_SM;\n  int A_SPLINE_NLOG_SM;\n  int A_SPLINE_NA_PK;\n  int A_SPLINE_NLOG_PK;\n\n  //k-splines and integrals\n  double K_MAX_SPLINE;\n  double K_MAX;\n  double K_MIN;\n  double DLOGK_INTEGRATION;\n  int N_K;\n  int N_K_3DCOR;\n\n  //Correlation function parameters\n  double ELL_MIN_CORR;\n  double ELL_MAX_CORR;\n  int N_ELL_CORR;\n\n  // interpolation types\n  const gsl_interp_type* A_SPLINE_TYPE;\n  const gsl_interp_type* K_SPLINE_TYPE;\n  const gsl_interp_type* M_SPLINE_TYPE;\n  const gsl_interp_type* D_SPLINE_TYPE;\n  const gsl_interp2d_type* PNL_SPLINE_TYPE;\n  const gsl_interp2d_type* PLIN_SPLINE_TYPE;\n  const gsl_interp_type* CORR_SPLINE_TYPE;\n} ccl_spline_params;\n\nextern const ccl_spline_params default_spline_params;\n\n/**\n * Struct that contains parameters that control the accuracy of various GSL\n * routines.\n */\ntypedef struct ccl_gsl_params {\n  // General parameters\n  size_t N_ITERATION;\n\n  // Integration\n  int INTEGRATION_GAUSS_KRONROD_POINTS;\n  double INTEGRATION_EPSREL;\n  // Limber integration\n  int INTEGRATION_LIMBER_GAUSS_KRONROD_POINTS;\n  double INTEGRATION_LIMBER_EPSREL;\n  // Distance integrals\n  double INTEGRATION_DISTANCE_EPSREL;\n  // sigma_R integral\n  double INTEGRATION_SIGMAR_EPSREL;\n  // k_NL integral\n  double INTEGRATION_KNL_EPSREL;\n\n  // Root finding\n  double ROOT_EPSREL;\n  int ROOT_N_ITERATION;\n\n  // ODE\n  double ODE_GROWTH_EPSREL;\n\n  // growth\n  double EPS_SCALEFAC_GROWTH;\n\n  // halo model\n  double HM_MMIN;\n  double HM_MMAX;\n  double HM_EPSABS;\n  double HM_EPSREL;\n  size_t HM_LIMIT;\n  int HM_INT_METHOD;\n\n} ccl_gsl_params;\n\nextern const ccl_gsl_params default_gsl_params;\n\n/**\n * Struct containing the parameters defining a cosmology\n */\ntypedef struct ccl_parameters {\n\n  // Densities: CDM, baryons, total matter, neutrinos, curvature\n  double Omega_c; /**< Density of CDM relative to the critical density*/\n  double Omega_b; /**< Density of baryons relative to the critical density*/\n  double Omega_m; /**< Density of all matter relative to the critical density*/\n  double Omega_k; /**< Density of curvature relative to the critical density*/\n  double sqrtk; /**< Square root of the magnitude of curvature, k */ //TODO check\n  int k_sign; /**<Sign of the curvature k */\n\n\n  // Dark Energy\n  double w0;\n  double wa;\n\n  // Hubble parameters\n  double H0;\n  double h;\n\n  // Neutrino properties\n\n  double Neff; // Effective number of relativistic neutrino species in the early universe.\n  int N_nu_mass; // Number of species of neutrinos which are nonrelativistic today\n  double N_nu_rel;  // Number of species of neutrinos which are relativistic  today\n  double *m_nu;  // total mass of massive neutrinos (This is a pointer so that it can hold multiple masses.)\n  double sum_nu_masses; // sum of the neutrino masses.\n  double Omega_nu_mass; // Omega_nu for MASSIVE neutrinos\n  double Omega_nu_rel; // Omega_nu for MASSLESS neutrinos\n\n  // Primordial power spectra\n  double A_s;\n  double n_s;\n\n  // Radiation parameters\n  double Omega_g;\n  double T_CMB;\n\n  // BCM baryonic model parameters\n  double bcm_log10Mc;\n  double bcm_etab;\n  double bcm_ks;\n\n  // mu / Sigma quasistatica parameterisation of modified gravity params\n  double mu_0;\n  double sigma_0;\n\n  // Derived parameters\n  double sigma8;\n  double Omega_l;\n  double z_star;\n\n  //Modified growth rate\n  bool has_mgrowth;\n  int nz_mgrowth;\n  double *z_mgrowth;\n  double *df_mgrowth;\n} ccl_parameters;\n\n\n/**\n * Struct containing references to gsl splines for distance and acceleration calculations\n */\ntypedef struct ccl_data {\n  // These are all functions of the scale factor a.\n\n  // Distances are defined in Mpc\n  double growth0;\n  gsl_spline * chi;\n  gsl_spline * growth;\n  gsl_spline * fgrowth;\n  gsl_spline * E;\n  gsl_spline * achi;\n\n  // Function of Halo mass M\n  gsl_spline2d * logsigma;\n\n  // real-space splines for RSD\n  ccl_f1d_t* rsd_splines[3];\n  double rsd_splines_scalefactor;\n} ccl_data;\n\n/**\n * Sturct containing references to instances of the above structs, and boolean flags of precomputed values.\n */\ntypedef struct ccl_cosmology {\n  ccl_parameters    params;\n  ccl_configuration config;\n  ccl_data          data;\n  ccl_spline_params spline_params;\n  ccl_gsl_params    gsl_params;\n\n  bool computed_distances;\n  bool computed_growth;\n  bool computed_sigma;\n\n  int status;\n  //this is optional - less tedious than tracking all numerical values for status in error handler function\n  char status_message[500];\n\n  // other flags?\n} ccl_cosmology;\n\n// Initialization and life cycle of objects\nccl_cosmology * ccl_cosmology_create(ccl_parameters params, ccl_configuration config);\n\n/* Internal function to set the status message safely. */\nvoid ccl_cosmology_set_status_message(ccl_cosmology * cosmo, const char * status_message, ...);\n\n// User-facing creation routines\n/**\n * Create a cosmology\n * @param Omega_c Omega_c\n * @param Omega_b Omega_b\n * @param Omega_k Omega_k\n * @param Neff Number of relativistic neutrino species in the early universe\n * @param mnu neutrino mass, either sum or list of length 3\n * @param mnu_type determines neutrino mass convention (ccl_mnu_list, ccl_mnu_sum, ccl_mnu_sum_inverted, ccl_mnu_sum_equal)\n * @param w0 Dark energy EoS parameter\n * @param wa Dark energy EoS parameter\n * @param h Hubble constant in units of 100 km/s/Mpc\n * @param norm_pk the normalization of the power spectrum, either A_s or sigma8\n * @param n_s the power-law index of the power spectrum\n * @param bcm_log10Mc log10 cluster mass, one of the parameters of the BCM model\n * @param bcm_etab ejection radius parameter, one of the parameters of the BCM model\n * @param bcm_ks wavenumber for the stellar profile, one of the parameters of the BCM model\n * @param nz_mgrowth the number of redshifts where the modified growth is provided\n * @param zarr_mgrowth the array of redshifts where the modified growth is provided\n * @param dfarr_mgrowth the modified growth function vector provided\n * @param status Status flag. 0 if there are no errors, nonzero otherwise.\n * For specific cases see documentation for ccl_error.c\n * @return void\n */\nccl_parameters ccl_parameters_create(double Omega_c, double Omega_b, double Omega_k,\n\t\t\t\t     double Neff, double* mnu, int n_mnu,\n\t\t\t\t     double w0, double wa, double h, double norm_pk,\n\t\t\t\t     double n_s, double bcm_log10Mc, double bcm_etab, double bcm_ks,\n\t\t\t\t     double mu_0, double sigma_0, int nz_mgrowth, double *zarr_mgrowth,\n\t\t\t\t     double *dfarr_mgrowth, int *status);\n\n\n/**\n * Free a parameters struct\n * @param params ccl_parameters struct\n * @return void\n */\nvoid ccl_parameters_free(ccl_parameters * params);\n\n\n/**\n * Write a cosmology parameters object to a file in yaml format, .\n * @param params Cosmological parameters\n * @param filename Name of file to create and write\n * @param status Status flag. 0 if there are no errors, nonzero otherwise.\n * @return void\n */\nvoid ccl_parameters_write_yaml(ccl_parameters * params, const char * filename, int * status);\n\n/**\n * Read a cosmology parameters object from a file in yaml format, .\n * @param filename Name of existing file to read from\n * @param status Status flag. 0 if there are no errors, nonzero otherwise.\n * @return cosmo Cosmological parameters\n */\nccl_parameters ccl_parameters_read_yaml(const char * filename, int *status);\n\n/**\n * Free a cosmology struct\n * @param cosmo Cosmological parameters\n * @return void\n */\nvoid ccl_cosmology_free(ccl_cosmology * cosmo);\n\nint ccl_get_pk_spline_na(ccl_cosmology *cosmo);\nint ccl_get_pk_spline_nk(ccl_cosmology *cosmo);\nvoid ccl_get_pk_spline_a_array(ccl_cosmology *cosmo,int ndout,double* doutput,int *status);\nvoid ccl_get_pk_spline_lk_array(ccl_cosmology *cosmo,int ndout,double* doutput,int *status);\n\nCCL_END_DECLS\n\n#endif\n", "meta": {"hexsha": "4e536aa6c74b6e01dd605f1cefd1f240a04cd9ae", "size": 10021, "ext": "h", "lang": "C", "max_stars_repo_path": "include/ccl_core.h", "max_stars_repo_name": "borisbolliet/CCL", "max_stars_repo_head_hexsha": "6ddd35e49f9d2968cef3d3bc1bac8b55dbb4cf91", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/ccl_core.h", "max_issues_repo_name": "borisbolliet/CCL", "max_issues_repo_head_hexsha": "6ddd35e49f9d2968cef3d3bc1bac8b55dbb4cf91", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ccl_core.h", "max_forks_repo_name": "borisbolliet/CCL", "max_forks_repo_head_hexsha": "6ddd35e49f9d2968cef3d3bc1bac8b55dbb4cf91", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4406332454, "max_line_length": 123, "alphanum_fraction": 0.7386488374, "num_tokens": 2783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.05033063669284357, "lm_q1q2_score": 0.024379158042993853}}
{"text": "/*\n    Copyright (C) 2008 Wei Dong <wdong@princeton.edu>. All Rights Reserved.\n\n    This file is part of LSHKIT.\n\n    LSHKIT is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    LSHKIT is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with LSHKIT.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n/**\n *  \\file fitdata.cpp\n *  \\brief Gather statistics from dataset for MPLSH tuning.\n *\n *  This program gahters statistical data from a small sample dataset\n *  for automatic MPLSH parameter tuning.  It carries out the following\n *  steps:\n *  -# Sample N points from the dataset. Only those N points will be used for future computation.\n *  -# Sample P pairs of points from the sample, calculate the distance for each pair.\n *  -# Sample Q points from the sample as queries points.\n *  -# Divide the sample into F folds.\n *  -# For i = 1 to F, take i folds and run K-NN search, so the query points\n *     will be searched against sample datasets of N/F, 2N/F, ..., N/F points.\n *\n *  The statistical data is printed to standard output after the progress display.\n *\n\\verbatim\nAllowed options:\n  -h [ --help ]          produce help message.\n  -N [ -- ] arg (=0)     number of points to use\n  -P [ -- ] arg (=50000) number of pairs to sample\n  -Q [ -- ] arg (=1000)  number of queries to sample\n  -K [ -- ] arg (=100)   search for K nearest neighbors\n  -F [ -- ] arg (=10)    divide the sample to F folds\n  -D [ --data ] arg      data file\n\\endverbatim\n */\n\n#ifndef _MPLSH_FITDATA_H_\n#define _MPLSH_FITDATA_H_\n\n#include \"logging.h\"\n\n#include <cstdlib>\n#include <sstream>\n#include <gsl/gsl_multifit.h>\n\nnamespace lshkit {\n\ninline\nbool is_good_value (double v) {\n    return ((v > -std::numeric_limits<double>::max()) &&\n            (v < std::numeric_limits<double>::max()));\n}\n\ninline\nstd::string FitData(const FloatMatrix& data,\n                    unsigned N,            // number of points to use\n                    unsigned P,            // number of pairs to sample\n                    unsigned Q,            // number of queries to sample\n                    unsigned K,            // search for K neighbors neighbors\n                    unsigned F             // divide the sample to F folds\n                   )\n{\n    LOG(LIB_INFO) << \"started running FitData\" << std::endl;\n\n    std::vector<unsigned> idx(data.getSize());\n    for (size_t i = 0; i < idx.size(); ++i) idx[i] = i;\n    std::random_shuffle(idx.begin(), idx.end());\n\n    if (N > 0 && N < static_cast<unsigned>(data.getSize())) idx.resize(N);\n\n    metric::l2sqr<float> l2sqr(data.getDim());\n\n    DefaultRng rng;\n    boost::variate_generator<DefaultRng &, UniformUnsigned> gen(rng,\n             UniformUnsigned(0, idx.size()-1));\n\n    double gM = 0.0;\n    double gG = 0.0;\n    {\n        // sample P pairs of points\n        for (unsigned k = 0; k < P; ++k)\n        {\n            double dist, logdist;\n            for (;;)\n            {\n                unsigned i = gen();\n                unsigned j = gen();\n                if (i == j) continue;\n                dist = l2sqr(data[idx[i]], data[idx[j]]);\n                logdist = log(dist);\n                if (is_good_value(logdist)) break;\n            }\n            gM += dist;\n            gG += logdist;\n        }\n        gM /= P;\n        gG /= P;\n        gG = exp(gG);\n    }\n\n    if (Q > idx.size()) Q = idx.size();\n    if (K > idx.size() - Q) K = idx.size() - Q;\n    /* sample query */\n    std::vector<unsigned> qry(Q);\n\n    SampleQueries(&qry, idx.size(), rng);\n\n    /* do the queries */\n    std::vector<Topk<unsigned> > topks(Q);\n    for (unsigned i = 0; i < Q; ++i) topks[i].reset(K);\n\n    /* ... */\n    gsl_matrix *X = gsl_matrix_alloc(F * K, 3);\n    gsl_vector *yM = gsl_vector_alloc(F * K);\n    gsl_vector *yG = gsl_vector_alloc(F * K);\n    gsl_vector *pM = gsl_vector_alloc(3);\n    gsl_vector *pG = gsl_vector_alloc(3);\n    gsl_matrix *cov = gsl_matrix_alloc(3,3);\n\n    std::vector<double> M(K);\n    std::vector<double> G(K);\n\n    unsigned m = 0;\n    for (unsigned l = 0; l < F; l++)\n    {\n        // Scan\n        for (unsigned i = l; i< idx.size(); i += F)\n        {\n            for (unsigned j = 0; j < Q; j++)\n            {\n                unsigned id = qry[j];\n                if (i != id)\n                {\n                    float d = l2sqr(data[idx[id]], data[idx[i]]);\n                    if (is_good_value(log(double(d))))\n                      topks[j] << Topk<unsigned>::Element(i, d);\n                }\n            }\n        }\n\n        fill(M.begin(), M.end(), 0.0);\n        fill(G.begin(), G.end(), 0.0);\n\n        for (unsigned i = 0; i < Q; i++)\n        {\n            for (unsigned k = 0; k < K; k++)\n            {\n                M[k] += topks[i][k].dist;\n                G[k] += log(topks[i][k].dist);\n            }\n        }\n\n        for (unsigned k = 0; k < K; k++)\n        {\n            M[k] = log(M[k]/Q);\n            G[k] /= Q;\n            gsl_matrix_set(X, m, 0, 1.0);\n            gsl_matrix_set(X, m, 1, log(double(data.getSize() * (l + 1)) / double(F)));\n            gsl_matrix_set(X, m, 2, log(double(k + 1)));\n            gsl_vector_set(yM, m, M[k]);\n            gsl_vector_set(yG, m, G[k]);\n            ++m;\n        }\n\n        //++progress;\n    }\n\n    gsl_multifit_linear_workspace *work = gsl_multifit_linear_alloc(F * K, 3);\n\n    double chisq;\n\n    gsl_multifit_linear(X, yM, pM, cov, &chisq, work);\n    gsl_multifit_linear(X, yG, pG, cov, &chisq, work);\n\n    std::stringstream ss;\n    ss << gM << \" \" << gG << std::endl;\n    ss << gsl_vector_get(pM, 0) << \" \"\n       << gsl_vector_get(pM, 1) << \" \"\n       << gsl_vector_get(pM, 2) << std::endl;\n    ss << gsl_vector_get(pG, 0) << \" \"\n       << gsl_vector_get(pG, 1) << \" \"\n       << gsl_vector_get(pG, 2) << std::endl;\n\n    gsl_matrix_free(X);\n    gsl_matrix_free(cov);\n    gsl_vector_free(pM);\n    gsl_vector_free(pG);\n    gsl_vector_free(yM);\n    gsl_vector_free(yG);\n\n    LOG(LIB_INFO) << ss.str(); \n    LOG(LIB_INFO) << \"finished FitData\";\n\n    return ss.str();\n}\n\n}     // namespace lshkit\n\n#endif\n", "meta": {"hexsha": "c4db8a575d054e5d400daf0d9c8b6fb317973e66", "size": 6465, "ext": "h", "lang": "C", "max_stars_repo_path": "algorithms/NMSLIB/code/lshkit/include/lshkit/multiprobelsh-fitdata.h", "max_stars_repo_name": "sourabhpoddar404/nns_benchmark", "max_stars_repo_head_hexsha": "44cdd81ab984c87c2246a0464a7ac93321c58815", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 150.0, "max_stars_repo_stars_event_min_datetime": "2016-06-03T16:39:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-24T05:32:56.000Z", "max_issues_repo_path": "algorithms/NMSLIB/code/lshkit/include/lshkit/multiprobelsh-fitdata.h", "max_issues_repo_name": "sourabhpoddar404/nns_benchmark", "max_issues_repo_head_hexsha": "44cdd81ab984c87c2246a0464a7ac93321c58815", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2016-06-03T13:43:21.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-28T07:42:02.000Z", "max_forks_repo_path": "algorithms/NMSLIB/code/lshkit/include/lshkit/multiprobelsh-fitdata.h", "max_forks_repo_name": "sourabhpoddar404/nns_benchmark", "max_forks_repo_head_hexsha": "44cdd81ab984c87c2246a0464a7ac93321c58815", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 42.0, "max_forks_repo_forks_event_min_datetime": "2016-05-18T05:53:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-27T19:57:52.000Z", "avg_line_length": 30.6398104265, "max_line_length": 97, "alphanum_fraction": 0.5415313225, "num_tokens": 1765, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769843, "lm_q2_score": 0.0503306329535957, "lm_q1q2_score": 0.02437915623177665}}
{"text": "#include <stdio.h>\n#include <gsl/gsl_vector.h>\n\nint\nmain (void)\n{\n  int i; \n  gsl_vector * v = gsl_vector_alloc (100);\n  \n  for (i = 0; i < 100; i++)\n    {\n      gsl_vector_set (v, i, 1.23 + i);\n    }\n\n  {  \n     FILE * f = fopen (\"test.dat\", \"w\");\n     gsl_vector_fprintf (f, v, \"%.5g\");\n     fclose (f);\n  }\n\n  gsl_vector_free (v);\n  return 0;\n}\n", "meta": {"hexsha": "f25468b895b8be25038a7054e7006e20436c6336", "size": 348, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/vectorw.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/vectorw.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/vectorw.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 14.5, "max_line_length": 42, "alphanum_fraction": 0.5143678161, "num_tokens": 124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.05419873364244478, "lm_q1q2_score": 0.024356511696232055}}
{"text": "/*\n * Copyright (c) 2016 Kengo Tateishi (@tkengo)\n * Licensed under MIT license.\n *   http://www.opensource.org/licenses/mit-license.php\n *\n * MxRuby is really inspired by numpy.\n *\n * This file is implementation of extended array functions for ruby. The MX class is defined on ruby\n * interpreter by compiling it.\n */\n#include <ruby.h>\n/* #include <cblas.h> */\n#include \"mx.h\"\n\n/*\n * MX class object in C. This is initialized in Init_mxruby function.\n */\nVALUE rb_cMx;\nVALUE rb_eDataTypeError;\n\nMX *mxx_initialize(VALUE shape, DTYPE dtype)\n{\n    MX *mx = MX_ALLOC(MX);\n    mxx_setup(mx, dtype);\n    mxx_initialize_shape(mx, shape);\n\n    if (mx->size > 0) {\n        mx->elptr = MX_ALLOC_N(char, DTYPE_SIZES[mx->dtype] * mx->size);\n    }\n\n    return mx;\n}\n\nvoid mxx_setup(MX *mx, DTYPE dtype)\n{\n    mx->dim = 0;\n    mx->size = 0;\n    mx->dtype = dtype;\n    mx->shape = NULL;\n    mx->elptr = NULL;\n}\n\nvoid mxx_initialize_shape(MX *mx, VALUE shape)\n{\n    char shape_is_array = TYPE(shape) == T_ARRAY;\n\n    mx->size = 1;\n    mx->dim = shape_is_array ? RARRAY_LEN(shape) : 1;\n    mx->shape = MX_ALLOC_N(size_t, mx->dim);\n\n    for (int i = 0; i < mx->dim; i++) {\n        mx->shape[i] = FIX2INT(shape_is_array ? RARRAY_AREF(shape, i) : shape);\n        mx->size *= mx->shape[i];\n    }\n}\n\nvoid mxx_free(MX *mx)\n{\n    if (mx->shape != NULL) {\n        MX_FREE(mx->shape);\n    }\n    if (mx->elptr != NULL) {\n        MX_FREE(mx->elptr);\n    }\n\n    MX_FREE(mx);\n}\n\nstatic VALUE mx_alloc(VALUE klass)\n{\n    MX *mx = MX_ALLOC(MX);\n    mxx_setup(mx, DTYPE_FLOAT64);\n\n    return Data_Wrap_Struct(klass, 0, mxx_free, mx);\n}\n\nstatic VALUE mx_initialize(VALUE self, VALUE shape, VALUE initial_value, VALUE opt)\n{\n    MX *mx;\n    Data_Get_Struct(self, MX, mx);\n\n    if (!NIL_P(opt)) {\n        VALUE rb_dtype = rb_hash_aref(opt, ID2SYM(rb_intern(\"dtype\")));\n        if (!NIL_P(rb_dtype)) {\n            mx->dtype = mxx_dtype_from_symbol(rb_dtype);\n        }\n    }\n\n    mxx_initialize_shape(mx, shape);\n\n    if (mx->size > 0) {\n        mx->elptr = MX_ALLOC_N(char, DTYPE_SIZES[mx->dtype] * mx->size);\n\n        if (TYPE(initial_value) == T_ARRAY) {\n            for (int i = 0; i < mx->size; i++) {\n                VALUE v = RARRAY_AREF(initial_value, i);\n                mxx_rb_to_c(mx->elptr + i * DTYPE_SIZES[mx->dtype], mx->dtype, v);\n            }\n        } else if (!NIL_P(initial_value)) {\n            for (int i = 0; i < mx->size; i++) {\n                mxx_rb_to_c(mx->elptr + i * DTYPE_SIZES[mx->dtype], mx->dtype, initial_value);\n            }\n        }\n    }\n\n    return self;\n}\n\nstatic VALUE mx_shape(VALUE self)\n{\n    MX *mx = MX_DATA_PTR(self);\n    VALUE *shape = MX_ALLOC_N(VALUE, mx->dim);\n    for (int i = 0; i < mx->dim; i++) {\n        shape[i] = INT2FIX(mx->shape[i]);\n    }\n\n    return rb_ary_new4(mx->dim, shape);\n}\n\nstatic VALUE mx_dim(VALUE self)\n{\n    return INT2FIX(MX_DATA_DIM(self));\n}\n\nstatic VALUE mx_size(VALUE self)\n{\n    return INT2FIX(MX_DATA_SIZE(self));\n}\n\nstatic VALUE mx_dtype(VALUE self)\n{\n    return ID2SYM(rb_intern(DTYPE_NAMES[MX_DATA_PTR(self)->dtype]));\n}\n\nstatic VALUE mx_dot(VALUE self, VALUE target)\n{\n    int N = 2;\n    MX *mx = MX_DATA_PTR(self);\n    void *c = MX_ALLOC_N(char, mx->shape[0] * mx->shape[1] * DTYPE_SIZES[mx->dtype]);\n\n    /* cblas_sgemm( */\n    /*         CblasRowMajor, CblasNoTrans, CblasNoTrans, */\n    /*         N, N, N, */\n    /*         1, mx->elptr, N, */\n    /*         MX_DATA_ELPTR(target), N, */\n    /*         0, c, N */\n    /*         ); */\n\n    MX_FREE(mx->elptr);\n    mx->elptr = c;\n    return self;\n}\n\nstatic VALUE mx_astype(int argc, VALUE *argv, VALUE self)\n{\n    VALUE rb_new_dtype, rb_opt;\n    rb_scan_args(argc, argv, \"1:\", &rb_new_dtype, &rb_opt);\n\n    DTYPE new_dtype = mxx_dtype_from_symbol(rb_new_dtype);\n    MX *dest = MX_ALLOC(MX);\n    mxx_copy_cast(MX_DATA_PTR(self), dest, new_dtype);\n\n    return Data_Wrap_Struct(CLASS_OF(self), 0, mxx_free, dest);\n}\n\nstatic void mxs_to_a(VALUE *ary, size_t shape_index, size_t array_index, MX *mx)\n{\n    if (shape_index == mx->dim - 1) {\n        for (int i = 0; i < mx->shape[shape_index]; i++) {\n            void *p = (char *)mx->elptr + (i + array_index) * DTYPE_SIZES[mx->dtype];\n            ary[i] = mxx_c_to_rb(p, mx->dtype);\n        }\n    } else {\n        size_t skip = 1;\n        for (int i = shape_index + 1; i < mx->dim; i++) {\n            skip *= mx->shape[i];\n        }\n\n        for (int i = 0; i < mx->shape[shape_index]; i++) {\n            VALUE *v = MX_ALLOC_N(VALUE, mx->shape[shape_index + 1]);\n            mxs_to_a(v, shape_index + 1, skip * i + array_index, mx);\n            ary[i] = rb_ary_new4(mx->shape[shape_index + 1], v);\n        }\n    }\n}\n\nstatic VALUE mx_to_a(VALUE self)\n{\n    MX *mx = MX_DATA_PTR(self);\n    VALUE *ary = MX_ALLOC_N(VALUE, mx->shape[0]);\n    mxs_to_a(ary, 0, 0, mx);\n    return rb_ary_new4(mx->shape[0], ary);\n}\n\nstatic VALUE mx_flatten(VALUE self)\n{\n    MX *mx = MX_DATA_PTR(self);\n    VALUE *el = MX_ALLOC_N(VALUE, mx->size);\n    size_t dsize = DTYPE_SIZES[mx->dtype];\n    for (int i = 0; i < mx->size; i++) {\n        el[i] = mxx_c_to_rb((char *)mx->elptr + i * dsize, mx->dtype);\n    }\n    return rb_ary_new4(mx->size, el);\n}\n\nstatic VALUE mx_first(VALUE self)\n{\n    MX *mx = MX_DATA_PTR(self);\n    if (mx->size > 0) {\n        return mxx_c_to_rb(mx->elptr, mx->dtype);\n    }\n    return Qnil;\n}\n\nstatic VALUE mx_second(VALUE self)\n{\n    MX *mx = MX_DATA_PTR(self);\n    if (mx->size > 1) {\n        return mxx_c_to_rb(mx->elptr + DTYPE_SIZES[mx->dtype], mx->dtype);\n    }\n    return Qnil;\n}\n\nstatic VALUE mx_last(VALUE self)\n{\n    MX *mx = MX_DATA_PTR(self);\n    if (mx->size > 0) {\n        return mxx_c_to_rb(mx->elptr + (mx->size - 1) * DTYPE_SIZES[mx->dtype], mx->dtype);\n    }\n    return Qnil;\n}\n\nstatic VALUE mx_reshape(VALUE self, VALUE shape)\n{\n    MX *mx = MX_DATA_PTR(self);\n\n    MX *reshaped_mx = MX_ALLOC(MX);\n    mxx_initialize_shape(reshaped_mx, shape);\n\n    if (mx->size != reshaped_mx->size) {\n        rb_raise(rb_eArgError, \"Cannot do reshape operation between shape size of [ %ld ] and [ %ld ]. Total size of new array must be unchanged.\", mx->size, reshaped_mx->size);\n    }\n\n    reshaped_mx->dtype = mx->dtype;\n    reshaped_mx->elptr = MX_ALLOC_N(char, reshaped_mx->size * DTYPE_SIZES[reshaped_mx->dtype]);\n\n    mxx_copy_elptr(mx, reshaped_mx);\n    return Data_Wrap_Struct(CLASS_OF(self), 0, mxx_free, reshaped_mx);\n}\n\nstatic VALUE mx_sum(int argc, VALUE *argv, VALUE self)\n{\n    MX *mx = MX_DATA_PTR(self);\n\n    if (DTYPE_IS_INT(mx->dtype)) {\n        long sum = (long)mxx_sum(mx);\n        return INT2FIX(sum);\n    } else {\n        return rb_float_new(mxx_sum(mx));\n    }\n}\n\nstatic VALUE mx_is_empty(VALUE self)\n{\n    MX *mx = MX_DATA_PTR(self);\n    return mx->size == 0 ? Qtrue : Qfalse;\n}\n\nstatic VALUE mx_set(int argc, VALUE *argv, VALUE self)\n{\n    return self;\n}\n\n/**\n * Slice the `src` matrix, then the sliced matrix will be stored into the dest matrix.\n * @params src   Source matrix to be sliced\n * @params dest  Destination matrix\n * @params src_pos   Copy start position in the source matrix\n * @params count Copy element count\n * @params depth ?\n * @params idx\n * @params idx_len\n */\nstatic void _mxs_slice(MX *src, MX *dest, VALUE idx, size_t idx_len, int depth, size_t size,\n        size_t src_pos, size_t *dest_pos)\n{\n    if (depth == idx_len) {\n        mxx_copy_by_size(\n            MX_DATA_POS(src,  src_pos),\n            MX_DATA_POS(dest, *dest_pos),\n            size,\n            dest->dtype\n        );\n\n        *dest_pos += size;\n    } else {\n        size_t skip = 1;\n        for (int i = depth + 1; i < src->dim; i++) {\n            skip *= src->shape[i];\n        }\n\n        long beg, len;\n        VALUE v = RARRAY_AREF(idx, depth);\n        if (FIXNUM_P(v)) {\n            _mxs_slice(src, dest, idx, idx_len, depth + 1, skip, src_pos + FIX2INT(v) * skip, dest_pos);\n        } else if (rb_range_beg_len(v, &beg, &len, src->shape[depth], 0) == Qtrue) {\n            for (long i = 0; i < len; i++) {\n                _mxs_slice(src, dest, idx, idx_len, depth + 1, skip, src_pos + (beg + i) * skip, dest_pos);\n            }\n        }\n    }\n}\n\nstatic MX *mxs_slice(MX *src, VALUE idx, size_t idx_len)\n{\n    /**\n     * mx = [ [ [1,1], [2,2], [3,3], [4,4] ],\n     *        [ [0,0], [0,0], [0,0], [0,0] ],\n     *        [ [5,5], [6,6], [7,7], [8,8] ] ], shape = [3, 4, 2]\n     *\n     * mx[0]    =   [ [1,1], [2,2], [3,3], [4,4] ],   shape = [4, 2]\n     * mx[0..1] = [ [ [1,1], [2,2], [3,3], [4,4] ],\n     *              [ [0,0], [0,0], [0,0], [0,0] ] ], shape = [2, 4, 2]\n     *\n     * mx[0, 0..1] = [ [1,1], [2,2] ],   shape = [2, 2]\n     *\n     * mx[0..1, 0]    = [ [1,1],\n     *                    [0,0] ], shape = [2, 2]\n     * mx[0..1, 0..1] = [ [ [1,1], [2,2] ],\n     *                    [ [0,0], [0,0] ] ], shape = [2, 2, 2]\n     *\n     * mx[0..1, 0..1, 0] = [ [ 1, 2 ],\n     *                       [ 0, 0 ] ], shape = [2, 2]\n     *\n     * mx = [ [1, 2, 3],\n     *        [4, 5, 6],\n     *        [7, 8, 9] ], shape = [3, 3]\n     *\n     * mx[0]         =   [1, 2, 3],   shape = [3]\n     * mx[0..1]      = [ [1, 2, 3]\n     *                   [4, 5, 6] ], shape = [2, 3]\n     * mx[0..1, 0]   = [ 1\n     *                   4 ],         shape = [2, 1]\n     * mx[0..1, [0]] = [ [1]\n       *                 [4] ],       shape = [2, 1]\n     *\n     * mx[0, 0]    =     1,  shape = nil\n     * mx[0, 0..1] = [1, 2], shape = [2]\n     *\n     * mx[[0]]    = [ [1, 2, 3] ], shape = [1, 3]\n     * mx[0..0]   = [ [1, 2, 3]\n     *                [4, 5, 6] ], shape = [2, 3]\n     * mx[[0, 1]] = [ [1, 2, 3]\n     *                [4, 5, 6] ], shape = [2, 3]\n     *\n     * \u5f15\u6570\u304cFIXNUM\u3060\u3063\u305f\u3089dim\u304c1\u500b\u6e1b\u308b\n     * \u5f15\u6570\u304crange\u307e\u305f\u306farray\u3060\u3063\u305f\u3089\u6b21\u5143\u306f\u6e1b\u3089\u305a\u306bshape\u304c\u305d\u306e\u9577\u3055\u306b\u306a\u308b\n     */\n    long beg, len;\n    size_t new_dim = 0;\n    size_t *tmp = MX_ALLOC_N(size_t, src->dim);\n    for (int i = 0; i < src->dim; i++) {\n        if (i < idx_len) {\n            VALUE v = RARRAY_AREF(idx, i);\n            if (rb_range_beg_len(v, &beg, &len, src->shape[i], 0) == Qtrue) {\n                tmp[new_dim++] = len;\n            }\n        } else {\n            tmp[new_dim++] = src->shape[i];\n        }\n    }\n\n    VALUE *new_shape = MX_ALLOC_N(VALUE, new_dim);\n    for (int i = 0; i < new_dim; i++) {\n        new_shape[i] = INT2FIX(tmp[i]);\n    }\n\n    MX *new_mx = MX_ALLOC(MX);\n    mxx_initialize_shape(new_mx, rb_ary_new4(new_dim, new_shape));\n    new_mx->dtype = src->dtype;\n    new_mx->elptr = MX_ALLOC_N(char, new_mx->size * DTYPE_SIZES[new_mx->dtype]);\n    MX_FREE(tmp);\n\n    size_t dest_pos = 0;\n    _mxs_slice(src, new_mx, idx, idx_len, 0, 0, 0, &dest_pos);\n}\n\nstatic VALUE mx_get(int argc, VALUE *argv, VALUE self)\n{\n    VALUE idx;\n    rb_scan_args(argc, argv, \"0*\", &idx);\n    MX *mx = MX_DATA_PTR(self);\n\n    size_t idx_len = RARRAY_LEN(idx);\n    if (idx_len > mx->dim) {\n        return Qnil;\n    }\n\n    MX *new_mx = mxs_slice(mx, idx, idx_len);\n    return Data_Wrap_Struct(CLASS_OF(self), 0, mxx_free, new_mx);\n\n    return self;\n}\n\nstatic VALUE mx_ewadd(VALUE self, VALUE other)\n{\n    MX *mx = MX_DATA_PTR(self);\n    MX *new_mx = MX_ALLOC(MX);\n\n    if (IS_MX(other)) {\n        MX *other_mx = MX_DATA_PTR(other);\n        if (!mxx_is_same_shape(mx, other_mx)) {\n            rb_raise(rb_eDataTypeError, \"Cannot do addition operation between different shapes\");\n        }\n        mxx_ewadd_array(mx, other_mx, new_mx);\n    } else {\n        if (TYPE(other) == T_FLOAT) {\n            mxx_ewadd_dblscalar(mx, NUM2DBL(other), new_mx);\n        } else {\n            mxx_ewadd_intscalar(mx, FIX2INT(other), new_mx);\n        }\n    }\n\n    return Data_Wrap_Struct(CLASS_OF(self), 0, mxx_free, new_mx);\n}\n\nstatic VALUE mx_ewsub(VALUE self, VALUE other)\n{\n    MX *mx = MX_DATA_PTR(self);\n    MX *new_mx = MX_ALLOC(MX);\n\n    if (IS_MX(other)) {\n        MX *other_mx = MX_DATA_PTR(other);\n        if (!mxx_is_same_shape(mx, other_mx)) {\n            rb_raise(rb_eDataTypeError, \"Cannot do subtraction operation between different shapes\");\n        }\n        mxx_ewsub_array(mx, other_mx, new_mx);\n    } else {\n        if (TYPE(other) == T_FLOAT) {\n            mxx_ewsub_dblscalar(mx, NUM2DBL(other), new_mx);\n        } else {\n            mxx_ewsub_intscalar(mx, FIX2INT(other), new_mx);\n        }\n    }\n\n    return Data_Wrap_Struct(CLASS_OF(self), 0, mxx_free, new_mx);\n}\n\nstatic VALUE mx_ewmul(VALUE self, VALUE other)\n{\n    MX *mx = MX_DATA_PTR(self);\n    MX *new_mx = MX_ALLOC(MX);\n\n    if (IS_MX(other)) {\n        MX *other_mx = MX_DATA_PTR(other);\n        if (!mxx_is_same_shape(mx, other_mx)) {\n            rb_raise(rb_eDataTypeError, \"Cannot do multiplication operation between different shapes\");\n        }\n        mxx_ewmul_array(mx, other_mx, new_mx);\n    } else {\n        if (TYPE(other) == T_FLOAT) {\n            mxx_ewmul_dblscalar(mx, NUM2DBL(other), new_mx);\n        } else {\n            mxx_ewmul_intscalar(mx, FIX2INT(other), new_mx);\n        }\n    }\n\n    return Data_Wrap_Struct(CLASS_OF(self), 0, mxx_free, new_mx);\n}\n\nstatic VALUE mx_ewpow(VALUE self, VALUE other)\n{\n    MX *mx = MX_DATA_PTR(self);\n    MX *new_mx = MX_ALLOC(MX);\n\n    if (IS_MX(other)) {\n        MX *other_mx = MX_DATA_PTR(other);\n        if (!mxx_is_same_shape(mx, other_mx)) {\n            rb_raise(rb_eDataTypeError, \"Cannot do power operation between different shapes\");\n        }\n\n        if (DTYPE_IS_INT(other_mx->dtype)) {\n            mxx_ewintpow_array(mx, other_mx, new_mx);\n        } else {\n            mxx_ewpow_array(mx, other_mx, new_mx);\n        }\n    } else {\n        if (TYPE(other) == T_FIXNUM) {\n            mxx_ewpow_intscalar(mx, FIX2INT(other), new_mx);\n        } else {\n            mxx_ewpow_dblscalar(mx, NUM2DBL(other), new_mx);\n        }\n    }\n\n    return Data_Wrap_Struct(CLASS_OF(self), 0, mxx_free, new_mx);\n}\n\nstatic VALUE mx_sing_eye(int argc, VALUE *argv, VALUE klass)\n{\n    int row, col, dim = 2;\n    VALUE rb_row, rb_col, rb_opt;\n    rb_scan_args(argc, argv, \"11:\", &rb_row, &rb_col, &rb_opt);\n    DTYPE dtype = mxx_dtype_from_opt(rb_opt, DTYPE_FLOAT64);\n\n    VALUE *shape = MX_ALLOC_N(VALUE, dim);\n    shape[0] = rb_row;\n    if (NIL_P(rb_col)) {\n        shape[1] = rb_row;\n    } else {\n        shape[1] = rb_col;\n    }\n    int count = MX_MIN(FIX2INT(shape[0]), FIX2INT(shape[1]));\n    if (count < 0) {\n        MX_FREE(shape);\n        rb_raise(rb_eArgError, \"Negative dimensions are not allowed\");\n    }\n\n    MX *mx = mxx_initialize(rb_ary_new4(dim, shape), dtype);\n\n    memset(mx->elptr, 0x00, mx->size * DTYPE_SIZES[mx->dtype]);\n    mxx_eye(mx, count);\n    MX_FREE(shape);\n    return Data_Wrap_Struct(klass, 0, mxx_free, mx);;\n}\n\nstatic VALUE mx_sing_arange(int argc, VALUE *argv, VALUE klass)\n{\n    double start, stop, step;\n    int start_type, stop_type, step_type;\n    VALUE rb_start, rb_stop, rb_step, rb_opt;\n    DTYPE dtype;\n\n    rb_scan_args(argc, argv, \"12:\", &rb_start, &rb_stop, &rb_step, &rb_opt);\n\n    if (NIL_P(rb_stop)) {\n        start      = 0;\n        stop       = NUM2DBL(rb_start);\n        start_type = T_FIXNUM;\n        stop_type  = TYPE(rb_start);\n    } else {\n        start      = NUM2DBL(rb_start);\n        stop       = NUM2DBL(rb_stop);\n        start_type = TYPE(rb_start);\n        stop_type  = TYPE(rb_stop);\n    }\n\n    step      = NIL_P(rb_step) ? 1 : NUM2DBL(rb_step);\n    step_type = NIL_P(rb_step) ? T_FIXNUM : TYPE(rb_step);\n\n    if (step == 0) {\n        rb_raise(rb_eArgError, \"Cannot specify 0 to the step argument\");\n    } else if (step > 0 && start > stop) {\n        rb_raise(rb_eArgError, \"Confuse arguments order. start > stop.\");\n    } else if (step < 0 && start < stop) {\n        rb_raise(rb_eArgError, \"Confuse arguments order. start < stop.\");\n    } else if (start == stop) {\n        MX *mx = mxx_initialize(INT2FIX(0), DTYPE_INT64);\n        return Data_Wrap_Struct(klass, 0, mxx_free, mx);\n    }\n\n    // T_FIXNUM => FIXNUM_P\n    if (step_type == T_FIXNUM && start_type == T_FIXNUM && stop_type == T_FIXNUM) {\n        dtype = DTYPE_INT64;\n    } else {\n        dtype = DTYPE_FLOAT64;\n    }\n\n    size_t shape = (size_t)fabs(ceil((stop - start) / step));\n    MX *mx = mxx_initialize(INT2FIX(shape), mxx_dtype_from_opt(rb_opt, dtype));\n    mxx_linspace(mx, start, step);\n\n    return Data_Wrap_Struct(klass, 0, mxx_free, mx);\n}\n\nstatic VALUE mx_sing_linspace(int argc, VALUE *argv, VALUE klass)\n{\n    VALUE rb_start, rb_stop, rb_num, rb_opt;\n    rb_scan_args(argc, argv, \"21:\", &rb_start, &rb_stop, &rb_num, &rb_opt);\n\n    if (NIL_P(rb_num)) {\n        rb_num = INT2FIX(100);\n    }\n\n    if (FIX2INT(rb_num) < 0) {\n        rb_raise(rb_eArgError, \"Cannot specify negative number to the shape argument\");\n    }\n\n    DTYPE dtype = mxx_dtype_from_opt(rb_opt, DTYPE_FLOAT64);\n    MX *mx = mxx_initialize(rb_num, dtype);\n    double start = NUM2DBL(rb_start);\n    double stop  = NUM2DBL(rb_stop);\n    double step  = (stop - start) * (1.0 / (double)(mx->size - 1));\n    mxx_linspace(mx, start, step);\n\n    return Data_Wrap_Struct(klass, 0, mxx_free, mx);\n}\n\nvoid Init_mxruby()\n{\n    rb_cMx = rb_define_class(\"MX\", rb_cObject);\n    rb_eDataTypeError = rb_define_class(\"DataTypeError\", rb_eStandardError);\n\n    rb_define_alloc_func(rb_cMx, mx_alloc);\n\n    rb_define_protected_method(rb_cMx, \"__set__\", mx_initialize, 3);\n\n    rb_define_method(rb_cMx, \"shape\", mx_shape, 0);\n    rb_define_method(rb_cMx, \"dim\", mx_dim, 0);\n    rb_define_method(rb_cMx, \"size\", mx_size, 0);\n    rb_define_method(rb_cMx, \"dtype\", mx_dtype, 0);\n    rb_define_method(rb_cMx, \"dot\", mx_dot, 1);\n    rb_define_method(rb_cMx, \"astype\", mx_astype, -1);\n    rb_define_method(rb_cMx, \"to_a\", mx_to_a, 0);\n    rb_define_method(rb_cMx, \"flatten\", mx_flatten, 0);\n    rb_define_method(rb_cMx, \"first\", mx_first, 0);\n    rb_define_method(rb_cMx, \"second\", mx_second, 0);\n    rb_define_method(rb_cMx, \"last\", mx_last, 0);\n    rb_define_method(rb_cMx, \"reshape\", mx_reshape, 1);\n    rb_define_method(rb_cMx, \"sum\", mx_sum, -1);\n\n    rb_define_method(rb_cMx, \"empty?\", mx_is_empty, 0);\n\n    rb_define_method(rb_cMx, \"[]=\", mx_set, -1);\n    rb_define_method(rb_cMx, \"[]\", mx_get, -1);\n    rb_define_method(rb_cMx, \"+\", mx_ewadd, 1);\n    rb_define_method(rb_cMx, \"-\", mx_ewsub, 1);\n    rb_define_method(rb_cMx, \"*\", mx_ewmul, 1);\n    rb_define_method(rb_cMx, \"**\", mx_ewpow, 1);\n\n    rb_define_singleton_method(rb_cMx, \"eye\", mx_sing_eye, -1);\n    rb_define_singleton_method(rb_cMx, \"arange\", mx_sing_arange, -1);\n    rb_define_singleton_method(rb_cMx, \"linspace\", mx_sing_linspace, -1);\n\n    Init_random();\n}\n", "meta": {"hexsha": "ffc988be040af9ed7884c299ab6e731a1091ab26", "size": 18427, "ext": "c", "lang": "C", "max_stars_repo_path": "ext/mxruby/mx.c", "max_stars_repo_name": "tkengo/mxruby", "max_stars_repo_head_hexsha": "f828c829dc556fbad34047272875d7af1406bff5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ext/mxruby/mx.c", "max_issues_repo_name": "tkengo/mxruby", "max_issues_repo_head_hexsha": "f828c829dc556fbad34047272875d7af1406bff5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ext/mxruby/mx.c", "max_forks_repo_name": "tkengo/mxruby", "max_forks_repo_head_hexsha": "f828c829dc556fbad34047272875d7af1406bff5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9732704403, "max_line_length": 177, "alphanum_fraction": 0.5708471265, "num_tokens": 5889, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879061178313897, "lm_q2_score": 0.051845464452267745, "lm_q1q2_score": 0.02430466699875958}}
{"text": "#ifndef SOURCE_UTILS_H_\n#define SOURCE_UTILS_H_\n\n// *** source/utils.h ***\n// Author: Kevin Wolz, date: 08/2018\n//\n// Various utilities used in the code.\n\n#include <fstream>\n#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <vector>\n#include <string>\n#include <unistd.h>\n#include <algorithm>\n#include <stdlib.h>\n#include <sys/stat.h>\n#include <time.h>\n\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_cblas.h>\n#include <gsl/gsl_eigen.h>\n#include <gsl/gsl_integration.h>\n#include <gsl/gsl_sort_vector.h>\n#include <gsl/gsl_permutation.h>\n#include <gsl/gsl_histogram.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_roots.h>\n#include <gsl/gsl_cdf.h>\n\n\nstd::string Timestamp();\n\ndouble get_signum(double x);\n\nvoid PrintGslVector(gsl_vector* vector);\n\nvoid PrintGslVector(gsl_vector* vector, std::string label);\n\nvoid PrintGslMatrix(gsl_matrix* matrix);\n\nvoid PrintGslMatrix(gsl_matrix* matrix, std::string label);\n\nbool file_exists(const std::string& filename);\n\nvoid AppendTwoGslVectors(gsl_vector* vector1, gsl_vector* vector2, \n                         gsl_vector* new_vector);\n\nvoid ConcatenateTwoGslMatrices(gsl_matrix* mmatrix1, gsl_matrix* matrix2,\n                               gsl_matrix* new_matrix, bool vertical_axis);\n\nvoid BlockDiagFromTwoGslMatrices(gsl_matrix* matrix1, gsl_matrix* matrix2,\n                                 gsl_matrix* new_matrix, unsigned int dimnew1,\n                                 unsigned int dimnew2);\n\nvoid SubtractTwoDoubleVectors(const std::vector<double> &vector1,\n                              const std::vector<double> &vector2,\n                              std::vector<double> &difference);\n\ndouble GslVec1MatVec2(gsl_vector* vector1, gsl_matrix* matrix,\n                      gsl_vector* vector2, int dim);\n\nvoid InvertGslMatrix(gsl_matrix* tobeinverted, unsigned int dim, \n                     gsl_matrix* inverted);\n\ndouble DeterminantGslMatrix(gsl_matrix* square_matrix, unsigned int dim);\n\ndouble Vec1MatVec2(std::vector<double> vector1, gsl_matrix* matrix,\n                   std::vector<double> vector2, int dim);\n\ndouble TraceGslMatrix(gsl_matrix* square_matrix, int dim);\n\nvoid MultiplyFourGslMatrices(gsl_matrix* matrix1, gsl_matrix* matrix2,\n                             gsl_matrix* matrix3, gsl_matrix* matrix4,\n                             int dim, gsl_matrix* resulting_matrix);\n\nvoid MultiplyThreeGslMatrices(gsl_matrix* matrix1, gsl_matrix* matrix2,\n                              gsl_matrix* matrix3, int dim, \n                              gsl_matrix* resulting_matrix);\n\n#endif // SOURCE_UTILS_H_\n", "meta": {"hexsha": "fbdd3642a4708ea56c46ca728debcbeef8727ca1", "size": 2682, "ext": "h", "lang": "C", "max_stars_repo_path": "source/utils.h", "max_stars_repo_name": "kevguitar/Robustness", "max_stars_repo_head_hexsha": "ab83a09a82fcc7f8ee10027b3ccb24194731b4ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/utils.h", "max_issues_repo_name": "kevguitar/Robustness", "max_issues_repo_head_hexsha": "ab83a09a82fcc7f8ee10027b3ccb24194731b4ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/utils.h", "max_forks_repo_name": "kevguitar/Robustness", "max_forks_repo_head_hexsha": "ab83a09a82fcc7f8ee10027b3ccb24194731b4ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8275862069, "max_line_length": 78, "alphanum_fraction": 0.6759880686, "num_tokens": 643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.05261895706184315, "lm_q1q2_score": 0.02425822211542397}}
{"text": "/* ode-initval/gsl_odeiv.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Author:  G. Jungman\n */\n#ifndef __GSL_ODEIV_H__\n#define __GSL_ODEIV_H__\n\n#if !defined( GSL_FUN )\n#  if !defined( GSL_DLL )\n#    define GSL_FUN extern\n#  elif defined( BUILD_GSL_DLL )\n#    define GSL_FUN extern __declspec(dllexport)\n#  else\n#    define GSL_FUN extern __declspec(dllimport)\n#  endif\n#endif\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\n\n/* Description of a system of ODEs.\n *\n * y' = f(t,y) = dydt(t, y)\n *\n * The system is specified by giving the right-hand-side\n * of the equation and possibly a jacobian function.\n *\n * Some methods require the jacobian function, which calculates\n * the matrix dfdy and the vector dfdt. The matrix dfdy conforms\n * to the GSL standard, being a continuous range of floating point\n * values, in row-order.\n *\n * As with GSL function objects, user-supplied parameter\n * data is also present. \n */\n\ntypedef struct  \n{\n  int (* function) (double t, const double y[], double dydt[], void * params);\n  int (* jacobian) (double t, const double y[], double * dfdy, double dfdt[], void * params);\n  size_t dimension;\n  void * params;\n}\ngsl_odeiv_system;\n\n#define GSL_ODEIV_FN_EVAL(S,t,y,f)  (*((S)->function))(t,y,f,(S)->params)\n#define GSL_ODEIV_JA_EVAL(S,t,y,dfdy,dfdt)  (*((S)->jacobian))(t,y,dfdy,dfdt,(S)->params)\n\n\n/* General stepper object.\n *\n * Opaque object for stepping an ODE system from t to t+h.\n * In general the object has some state which facilitates\n * iterating the stepping operation.\n */\n\ntypedef struct \n{\n  const char * name;\n  int can_use_dydt_in;\n  int gives_exact_dydt_out;\n  void * (*alloc) (size_t dim);\n  int  (*apply)  (void * state, size_t dim, double t, double h, double y[], double yerr[], const double dydt_in[], double dydt_out[], const gsl_odeiv_system * dydt);\n  int  (*reset) (void * state, size_t dim);\n  unsigned int  (*order) (void * state);\n  void (*free)  (void * state);\n}\ngsl_odeiv_step_type;\n\ntypedef struct {\n  const gsl_odeiv_step_type * type;\n  size_t dimension;\n  void * state;\n}\ngsl_odeiv_step;\n\n\n/* Available stepper types.\n *\n * rk2    : embedded 2nd(3rd) Runge-Kutta\n * rk4    : 4th order (classical) Runge-Kutta\n * rkck   : embedded 4th(5th) Runge-Kutta, Cash-Karp\n * rk8pd  : embedded 8th(9th) Runge-Kutta, Prince-Dormand\n * rk2imp : implicit 2nd order Runge-Kutta at Gaussian points\n * rk4imp : implicit 4th order Runge-Kutta at Gaussian points\n * gear1  : M=1 implicit Gear method\n * gear2  : M=2 implicit Gear method\n */\n\nGSL_VAR const gsl_odeiv_step_type *gsl_odeiv_step_rk2;\nGSL_VAR const gsl_odeiv_step_type *gsl_odeiv_step_rk4;\nGSL_VAR const gsl_odeiv_step_type *gsl_odeiv_step_rkf45;\nGSL_VAR const gsl_odeiv_step_type *gsl_odeiv_step_rkck;\nGSL_VAR const gsl_odeiv_step_type *gsl_odeiv_step_rk8pd;\nGSL_VAR const gsl_odeiv_step_type *gsl_odeiv_step_rk2imp;\nGSL_VAR const gsl_odeiv_step_type *gsl_odeiv_step_rk2simp;\nGSL_VAR const gsl_odeiv_step_type *gsl_odeiv_step_rk4imp;\nGSL_VAR const gsl_odeiv_step_type *gsl_odeiv_step_bsimp;\nGSL_VAR const gsl_odeiv_step_type *gsl_odeiv_step_gear1;\nGSL_VAR const gsl_odeiv_step_type *gsl_odeiv_step_gear2;\n\n\n/* Constructor for specialized stepper objects.\n */\nGSL_FUN gsl_odeiv_step * gsl_odeiv_step_alloc(const gsl_odeiv_step_type * T, size_t dim);\nGSL_FUN int  gsl_odeiv_step_reset(gsl_odeiv_step * s);\nGSL_FUN void gsl_odeiv_step_free(gsl_odeiv_step * s);\n\n/* General stepper object methods.\n */\nGSL_FUN const char * gsl_odeiv_step_name(const gsl_odeiv_step * s);\nGSL_FUN unsigned int gsl_odeiv_step_order(const gsl_odeiv_step * s);\n\nGSL_FUN int  gsl_odeiv_step_apply(gsl_odeiv_step * s, double t, double h, double y[], double yerr[], const double dydt_in[], double dydt_out[], const gsl_odeiv_system * dydt);\n\n/* General step size control object.\n *\n * The hadjust() method controls the adjustment of\n * step size given the result of a step and the error.\n * Valid hadjust() methods must return one of the codes below.\n *\n * The general data can be used by specializations\n * to store state and control their heuristics.\n */\n\ntypedef struct \n{\n  const char * name;\n  void * (*alloc) (void);\n  int  (*init) (void * state, double eps_abs, double eps_rel, double a_y, double a_dydt);\n  int  (*hadjust) (void * state, size_t dim, unsigned int ord, const double y[], const double yerr[], const double yp[], double * h);\n  void (*free) (void * state);\n}\ngsl_odeiv_control_type;\n\ntypedef struct \n{\n  const gsl_odeiv_control_type * type;\n  void * state;\n}\ngsl_odeiv_control;\n\n/* Possible return values for an hadjust() evolution method.\n */\n#define GSL_ODEIV_HADJ_INC   1  /* step was increased */\n#define GSL_ODEIV_HADJ_NIL   0  /* step unchanged     */\n#define GSL_ODEIV_HADJ_DEC (-1) /* step decreased     */\n\nGSL_FUN gsl_odeiv_control * gsl_odeiv_control_alloc(const gsl_odeiv_control_type * T);\nGSL_FUN int gsl_odeiv_control_init(gsl_odeiv_control * c, double eps_abs, double eps_rel, double a_y, double a_dydt);\nGSL_FUN void gsl_odeiv_control_free(gsl_odeiv_control * c);\nGSL_FUN int gsl_odeiv_control_hadjust (gsl_odeiv_control * c, gsl_odeiv_step * s, const double y[], const double yerr[], const double dydt[], double * h);\nGSL_FUN const char * gsl_odeiv_control_name(const gsl_odeiv_control * c);\n\n/* Available control object constructors.\n *\n * The standard control object is a four parameter heuristic\n * defined as follows:\n *    D0 = eps_abs + eps_rel * (a_y |y| + a_dydt h |y'|)\n *    D1 = |yerr|\n *    q  = consistency order of method (q=4 for 4(5) embedded RK)\n *    S  = safety factor (0.9 say)\n *\n *                      /  (D0/D1)^(1/(q+1))  D0 >= D1\n *    h_NEW = S h_OLD * |\n *                      \\  (D0/D1)^(1/q)      D0 < D1\n *\n * This encompasses all the standard error scaling methods.\n *\n * The y method is the standard method with a_y=1, a_dydt=0.\n * The yp method is the standard method with a_y=0, a_dydt=1.\n */\n\nGSL_FUN gsl_odeiv_control * gsl_odeiv_control_standard_new(double eps_abs, double eps_rel, double a_y, double a_dydt);\nGSL_FUN gsl_odeiv_control * gsl_odeiv_control_y_new(double eps_abs, double eps_rel);\nGSL_FUN gsl_odeiv_control * gsl_odeiv_control_yp_new(double eps_abs, double eps_rel);\n\n/* This controller computes errors using different absolute errors for\n * each component\n *\n *    D0 = eps_abs * scale_abs[i] + eps_rel * (a_y |y| + a_dydt h |y'|)\n */\nGSL_FUN gsl_odeiv_control * gsl_odeiv_control_scaled_new(double eps_abs, double eps_rel, double a_y, double a_dydt, const double scale_abs[], size_t dim);\n\n/* General evolution object.\n */\ntypedef struct {\n  size_t dimension;\n  double * y0;\n  double * yerr;\n  double * dydt_in;\n  double * dydt_out;\n  double last_step;\n  unsigned long int count;\n  unsigned long int failed_steps;\n}\ngsl_odeiv_evolve;\n\n/* Evolution object methods.\n */\nGSL_FUN gsl_odeiv_evolve * gsl_odeiv_evolve_alloc(size_t dim);\nGSL_FUN int gsl_odeiv_evolve_apply(gsl_odeiv_evolve * e, gsl_odeiv_control * con, gsl_odeiv_step * step, const gsl_odeiv_system * dydt, double * t, double t1, double * h, double y[]);\nGSL_FUN int gsl_odeiv_evolve_reset(gsl_odeiv_evolve * e);\nGSL_FUN void gsl_odeiv_evolve_free(gsl_odeiv_evolve * e);\n\n\n__END_DECLS\n\n#endif /* __GSL_ODEIV_H__ */\n", "meta": {"hexsha": "0019c74d4f6f15e947cf6d45a9befb41486ef374", "size": 8145, "ext": "h", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_odeiv.h", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-28T08:20:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-28T08:20:20.000Z", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_odeiv.h", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_odeiv.h", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-14T12:45:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-14T12:45:35.000Z", "avg_line_length": 33.7966804979, "max_line_length": 183, "alphanum_fraction": 0.7321055862, "num_tokens": 2400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.051845468297913956, "lm_q1q2_score": 0.024103039680289397}}
{"text": "#ifndef LIBTENSOR_CBLAS_H_H\n#define LIBTENSOR_CBLAS_H_H\n\nextern \"C\" {  // Fixes older cblas.h versions without extern \"C\"\n#include <cblas.h>\n}\n\n#endif  // LIBTENSOR_CBLAS_H_H\n", "meta": {"hexsha": "fb35afa43e81e52174112196f329a627e67f152c", "size": 175, "ext": "h", "lang": "C", "max_stars_repo_path": "libtensor/linalg/cblas_h.h", "max_stars_repo_name": "maxscheurer/libtensor", "max_stars_repo_head_hexsha": "288ed0596b24356d187d2fa40c05b0dacd00b413", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libtensor/linalg/cblas_h.h", "max_issues_repo_name": "maxscheurer/libtensor", "max_issues_repo_head_hexsha": "288ed0596b24356d187d2fa40c05b0dacd00b413", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2020-12-04T20:26:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-03T08:07:09.000Z", "max_forks_repo_path": "libtensor/linalg/cblas_h.h", "max_forks_repo_name": "maxscheurer/libtensor", "max_forks_repo_head_hexsha": "288ed0596b24356d187d2fa40c05b0dacd00b413", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-06-17T12:35:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-23T16:27:39.000Z", "avg_line_length": 19.4444444444, "max_line_length": 64, "alphanum_fraction": 0.7542857143, "num_tokens": 57, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.399811640739795, "lm_q2_score": 0.06008665438181589, "lm_q1q2_score": 0.024023343874958806}}
{"text": "/*\n * author: Achim Gaedke\n * created: January 2002\n * file: pygsl/src/multiminmodule.c\n * $Id: multiminmodule.c,v 1.5 2004/03/08 08:42:16 schnizer Exp $\n */\n#include <setjmp.h>\n#include <pygsl/block_helpers.h>\n#include <pygsl/error_helpers.h>\n#include <pygsl/function_helpers.h>\n\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_multimin.h>\n#include \"multiminmodule_doc.h\"\n/* \n * I have two different types to minimize and I am too lazy to implement the same\n * twice. Therefore I use unions and add a flag to the minimizer for the type\n */\n\nunion pygsl_multimin_minimizer_type{\n     const gsl_multimin_fminimizer_type   *f; \n     const gsl_multimin_fdfminimizer_type *fdf; \n};\n\nunion pygsl_multimin_minimizer{\n     gsl_multimin_fminimizer   *f; \n     gsl_multimin_fdfminimizer *fdf; \n};\n\nunion pygsl_multimin_func{\n     gsl_multimin_function     *f; \n     gsl_multimin_function_fdf *fdf; \n};\n\nstruct pygsl_solver_types{\n     const char * f_minimizer;\n     const char * fdf_minimizer;\n};\nstatic struct pygsl_solver_types my_solvers = {\"F-Minimizer\", \"Fdf-Minimizer\"};\n\n/* \n *  type: \n *\t == 0 -> f \n *\t != 0 -> fdf\n */\ntypedef struct {\n     PyObject_HEAD\n     PyObject* py_f;\n     PyObject* py_df;\n     PyObject* py_fdf;\n     PyObject* trailing_params;\n     union pygsl_multimin_func      func;\n     union pygsl_multimin_minimizer min;\n     size_t n;\n     const char *mytype;\n     int isset; /* Used as a flag if the jmp_buf is set */\n     jmp_buf buffer;\n} PyGSL_multimin;\n\n#define PyGSL_multimin_check(op)  ((op)->ob_type == &PyGSL_multimin_pytype)\n#define PyGSL_multimin_isf(op)    ((op)->mytype  == my_solvers.f_minimizer)\n\n\nstatic void\nPyGSL_multimin_dealloc(PyGSL_multimin* self);\nstatic PyObject*\nPyGSL_multimin_getattr(PyGSL_multimin * obj, char *name);\n\n\n\nPyTypeObject PyGSL_multimin_pytype = {\n  PyObject_HEAD_INIT(NULL)\t /* fix up the type slot in initcrng */\n  0,\t\t\t\t /* ob_size */\n  \"PyGSL_multimin\",\t\t /* tp_name */\n  sizeof(PyGSL_multimin),\t /* tp_basicsize */\n  0,\t\t\t\t /* tp_itemsize */\n\n  /* standard methods */\n  (destructor)  PyGSL_multimin_dealloc, /* tp_dealloc  ref-count==0  */\n  (printfunc)   0,\t\t /* tp_print    \"print x\"     */\n  (getattrfunc) PyGSL_multimin_getattr,/* tp_getattr  \"x.attr\"      */\n  (setattrfunc) 0,\t\t /* tp_setattr  \"x.attr=v\"    */\n  (cmpfunc)     0,\t\t   /* tp_compare  \"x > y\"       */\n  (reprfunc)    0,                 /* tp_repr     `x`, print x  */\n\n  /* type categories */\n  0,\t\t\t\t/* tp_as_number   +,-,*,/,%,&,>>,pow...*/\n  0,\t\t\t\t/* tp_as_sequence +,[i],[i:j],len, ...*/\n  0,\t\t\t\t/* tp_as_mapping  [key], len, ...*/\n\n  /* more methods */\n  (hashfunc)     0,\t\t/* tp_hash    \"dict[x]\" */\n  (ternaryfunc)  0,      /* tp_call    \"x()\"     */\n  (reprfunc)     0,             /* tp_str     \"str(x)\"  */\n  (getattrofunc) 0,\t\t/* tp_getattro */\n  (setattrofunc) 0,\t\t/* tp_setattro */\n  0,\t\t\t\t/* tp_as_buffer */\n  0L,\t\t\t\t/* tp_flags */\n  (char *) PyGSL_multimin_type_doc\t\t/* tp_doc */\n};\n\n\n/* Reference to this module */\nPyObject *module = NULL;\nstatic const char filename[] = __FILE__;\n\n/* The Callbacks */\ndouble \nPyGSL_multimin_function_f(const gsl_vector* x, void* params) \n{\n     double result;\n     int flag;\n     int i;\n\n     FUNC_MESS_BEGIN();     \n     PyGSL_multimin *min_o;     \n     min_o = (PyGSL_multimin *) params;\n     assert(PyGSL_multimin_check(min_o));     \n     for(i = 0; i<x->size; i++){\n\t  DEBUG_MESS(2, \"Got a x[%d] of %f\", i, gsl_vector_get(x, i));\n     }\n     flag = PyGSL_function_wrap_On_O(x, min_o->py_f, min_o->trailing_params, &result,\n\t\t\t\t     NULL, x->size, __FUNCTION__);\n     if (flag!= GSL_SUCCESS){\n\t  result = gsl_nan();\n\t  if(min_o->isset == 1) longjmp(min_o->buffer,flag);\t  \n     }  \n     DEBUG_MESS(2, \"Got a result of %f\", result);\n     FUNC_MESS_END();\n     return result;\n}\n\nvoid \nPyGSL_multimin_function_df(const gsl_vector* x, void* params, gsl_vector *df)\n{\n     int flag, i;\n     PyGSL_multimin *min_o;     \n     min_o = (PyGSL_multimin *) params;\n\n     FUNC_MESS_BEGIN();\n     assert(PyGSL_multimin_check(min_o));     \n     for(i = 0; i<x->size; i++){\n\t  DEBUG_MESS(2, \"Got a x[%d] of %f\", i, gsl_vector_get(x, i));\n     }\n     flag = PyGSL_function_wrap_Op_On(x, df, min_o->py_df, min_o->trailing_params,\n\t\t\t\t      x->size, x->size, __FUNCTION__);\n     for(i = 0; i<df->size; i++){\n\t  DEBUG_MESS(2, \"Got df x[%d] of %f\", i, gsl_vector_get(df, i));\n     }\n     if(flag!=GSL_SUCCESS){\n\t  if(min_o->isset == 1) longjmp(min_o->buffer,flag);\t  \n     }\n     FUNC_MESS_END();\n} \nvoid \nPyGSL_multimin_function_fdf(const gsl_vector* x, void* params, double *f, gsl_vector *df)\n{\n     int flag, i;\n     PyGSL_multimin *min_o;     \n\n     FUNC_MESS_BEGIN();\n     min_o = (PyGSL_multimin *) params;\n     assert(PyGSL_multimin_check(min_o));     \n     for(i = 0; i<x->size; i++){\n\t  DEBUG_MESS(2, \"Got a x[%d] of %f\", i, gsl_vector_get(x, i));\n     }\n     flag = PyGSL_function_wrap_On_O(x, min_o->py_fdf, min_o->trailing_params, f,\n\t\t\t\t     df, x->size, __FUNCTION__);\n     DEBUG_MESS(2, \"Got a result of %f\", *f);\n     for(i = 0; i<df->size; i++){\n\t  DEBUG_MESS(2, \"Got df x[%d] of %f\", i, gsl_vector_get(df, i));\n     }\n     if (flag!= GSL_SUCCESS){\n\t  *f = gsl_nan();\n\t  if(min_o->isset == 1) longjmp(min_o->buffer,flag);  \n     }  \n     FUNC_MESS_END();\n     return;\n}\n\nstatic PyObject* \nPyGSL_multimin_set_f(PyGSL_multimin *self, PyObject *args, PyObject *kw) \n{\n\n     PyObject* func = NULL, * params = NULL, * x = NULL, * steps = NULL;\n     PyArrayObject * xa = NULL, * stepsa = NULL;\n     int n=0, flag=GSL_EFAILED;\n     int stride_recalc;\n     gsl_vector_view gsl_x;\n     gsl_vector_view gsl_steps;\n     static const char *kwlist[] = {\"f\", \"x0\", \"args\", \"steps\", NULL};\n\n     FUNC_MESS_BEGIN();\n     assert(PyGSL_multimin_check(self));     \n     if (self->min.f == NULL) {\n\t  gsl_error(\"Got a NULL Pointer of min.f\",  filename, __LINE__ - 3, GSL_EFAULT);\n\t  return NULL;\n     }\n\n     assert(args);\n     /* arguments PyFunction, Parameters, start Vector, step Vector */\n     if (0==PyArg_ParseTupleAndKeywords(args,kw,\"OOOO\", (char **) kwlist, &func,&x,&params,&steps))\n\t  return NULL;\n\n     if(!PyCallable_Check(func)){\n\t  gsl_error(\"First argument must be callable\",  filename, __LINE__ - 3, GSL_EBADFUNC);\n\t  return NULL;\t  \n     }\n     n=self->n;\n     xa  = PyGSL_PyArray_PREPARE_gsl_vector_view(x, PyArray_DOUBLE, 0, n, 4, NULL);\n     if (xa == NULL){\n\t  PyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__ - 1);\n\t  goto fail;\n     }\n     if(PyGSL_STRIDE_RECALC(xa->strides[0],sizeof(double), &stride_recalc) != GSL_SUCCESS)\n\t  goto fail;\n\n     gsl_x = gsl_vector_view_array_with_stride((double *)(xa->data), stride_recalc, xa->dimensions[0]);\n     stepsa =  PyGSL_PyArray_PREPARE_gsl_vector_view(steps, PyArray_DOUBLE, 0, n, 5, NULL);\n     if (stepsa == NULL){\n\t  PyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__ - 1);\n\t  goto fail;\n     }\n     if(PyGSL_STRIDE_RECALC(stepsa->strides[0],sizeof(double), &stride_recalc) != GSL_SUCCESS)\n\t  goto fail;\n\n     gsl_steps = gsl_vector_view_array_with_stride((double *)(stepsa->data), stride_recalc, stepsa->dimensions[0]);\n\n     if (self->func.f != NULL) {\n\t  /* free the previous function and params */\n\t  Py_XDECREF(self->trailing_params);\n\t  Py_XDECREF(self->py_f);\n     } else {\n\t  /* allocate function space */\n\t  self->func.f=calloc(1, sizeof(gsl_multimin_function));\n\t  if (self->func.f==NULL) {\n\t       gsl_error(\"Could not allocate the object for the minimizer function\", \n\t\t\t filename, __LINE__ - 3, GSL_ENOMEM);\n\t       goto fail;\n\t  }\n     }\n     /* add new function  and parameters */\n     self->trailing_params=params;\n     Py_INCREF(params);\n     self->py_f=func;\n     Py_INCREF(func);\n     \n     /* initialize the function struct */\n     self->func.f->n=n;\n     self->func.f->f=PyGSL_multimin_function_f;\n     self->func.f->params=(void*)self;\n     \n     if((flag = setjmp(self->buffer)) == 0){\n\t  self->isset = 1;\n\t  flag = gsl_multimin_fminimizer_set(self->min.f,self->func.f, &gsl_x.vector, &gsl_steps.vector);\n\t  if(PyGSL_ERROR_FLAG(flag) != GSL_SUCCESS){\n\t       goto fail;\n\t  }\n     } else {\n\t  goto fail;\n     }\n     Py_DECREF(xa);\n     Py_DECREF(stepsa);\n\n     Py_INCREF(Py_None);\n     self->isset = 0;\n     FUNC_MESS_END();\n     return Py_None;\n\n     \n fail:\n     FUNC_MESS(\"Fail\");\n     PyGSL_ERROR_FLAG(flag);\n     self->isset = 0;\n     Py_XDECREF(xa);\n     Py_XDECREF(stepsa);\n     return NULL;\n     \n}\nstatic PyObject* \nPyGSL_multimin_set_fdf(PyGSL_multimin *self, PyObject *args, PyObject *kw) \n{\n\n     PyObject * f = NULL, * df = NULL, * fdf = NULL, * params = NULL,\n\t      * x = NULL;\n     PyArrayObject * xa = NULL;\n     int n=0, flag=GSL_EFAILED;\n     int stride_recalc=-1;\n     double step=0.01, tol=1e-4;\n     gsl_vector_view gsl_x;\n     static const char *kwlist[] = {\"f\", \"df\", \"fdf\",  \"x0\", \"args\", \"step\", \"tol\", NULL};\n\n     FUNC_MESS_BEGIN();\n     assert(PyGSL_multimin_check(self));     \n     if (self->min.fdf == NULL) {\n\t  gsl_error(\"Got a NULL Pointer of min.fdf\", filename, __LINE__ - 3, GSL_EFAULT);\n\t       return NULL;\n\t  }\t  \n\n     /* arguments PyFunction, Parameters, start Vector, step Vector */\n     if (0==PyArg_ParseTupleAndKeywords(args, kw, \"OOOO|Odd\", (char **)kwlist, \n\t\t\t\t\t&f, &df, &fdf, &x, &params, &step, &tol))\n\t  return NULL;\n\n     n=self->n;\n     xa  = PyGSL_PyArray_PREPARE_gsl_vector_view(x, PyArray_DOUBLE, 0, n, 4, NULL);\n     if (xa == NULL){\n\t  PyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__ - 1);\n\t  goto fail;\n     }\n     if(params == NULL){\n          /* Reference counter increased later, when the parameters are set */\n\t  params = Py_None; \n     }\n     if(PyGSL_STRIDE_RECALC(xa->strides[0],sizeof(double), &stride_recalc) != GSL_SUCCESS)\n\t  goto fail;\n     gsl_x = gsl_vector_view_array_with_stride((double *)(xa->data), stride_recalc, xa->dimensions[0]);\n\n     if (self->func.fdf != NULL) {\n\t  /* free the previous function and params */\n\t  Py_XDECREF(self->trailing_params);\n\t  Py_XDECREF(self->py_f);\n\t  Py_XDECREF(self->py_df);\n\t  Py_XDECREF(self->py_fdf);\n     } else {\n\t  /* allocate function space */\n\t  self->func.fdf=malloc(sizeof(gsl_multimin_function_fdf));\n\t  if (self->func.fdf==NULL) {\n\t       gsl_error(\"Could not allocate the object for the minimizer function\", \n\t\t\t filename, __LINE__ - 3, GSL_ENOMEM);\n\t       goto fail;\n\t  }\n     }\n     /* add new function  and parameters */\n     self->trailing_params=params;     Py_INCREF(params);\n     self->py_f=f;                     Py_INCREF(f);\n     self->py_df=df;                   Py_INCREF(df);\n     self->py_fdf=fdf;                 Py_INCREF(fdf);\n     \n     /* initialize the function struct */\n     self->func.fdf->n=n;\n     self->func.fdf->f  =PyGSL_multimin_function_f;\n     self->func.fdf->df =PyGSL_multimin_function_df;  \n     self->func.fdf->fdf=PyGSL_multimin_function_fdf;\n     self->func.fdf->params=(void*)self;\n\n     if((flag = setjmp(self->buffer)) == 0){\n\t  self->isset = 1;\t  \n\t  flag = gsl_multimin_fdfminimizer_set(self->min.fdf,self->func.fdf, &gsl_x.vector, step, tol);\n\t  if(PyGSL_ERROR_FLAG(flag) != GSL_SUCCESS){\n\t       goto fail;\n\t  }\n     }else{\n\t  goto fail;\n     }\n     self->isset = 0;\n     Py_DECREF(xa);\n\n     Py_INCREF(Py_None);\n     FUNC_MESS_END();\n     return Py_None;\n\n fail:\n     PyGSL_ERROR_FLAG(flag);\n     self->isset = 0;\n     Py_XDECREF(xa);\n     return NULL;\n     \n}\n/*\nstatic PyObject* \nPyGSL_multimin_set(PyGSL_multimin *self, PyObject *args) \n{\n\n     if(PyGSL_multimin_isf(self)){       \n\t  return PyGSL_multimin_set_f(self, args);\n     }else {\n\t  return PyGSL_multimin_set_fdf(self, args);\n     }  \n}\n*/\nstatic PyObject* \nPyGSL_multimin_iterate(PyGSL_multimin *self, PyObject *args) \n{\n     int result, flag;\n\n     FUNC_MESS_BEGIN();\n     assert(PyGSL_multimin_check(self));     \n     if ( self->min.f ==NULL || self->func.f ==NULL) {\n\t  gsl_error(\"Got a NULL Pointer of min.f\", filename, __LINE__ - 3, GSL_EFAULT);\n\t  return NULL;\n     }\n\n     if((flag = setjmp(self->buffer)) == 0){\n\t  self->isset = 1;\t      \n\t  if(PyGSL_multimin_isf(self)){       \n\t       result = gsl_multimin_fminimizer_iterate(self->min.f);\n\t  } else {\n\t       result = gsl_multimin_fdfminimizer_iterate(self->min.fdf);\n\t  }\n     } else {\n\t  PyGSL_ERROR_FLAG(flag);\n\t  self->isset = 0;\n\t  return NULL;\n     }\n     self->isset = 0;\n     FUNC_MESS_END();\n     return PyGSL_error_flag_to_pyint(result);\n}\n\n\nstatic PyObject* \nPyGSL_multimin_x(PyGSL_multimin *self, PyObject *args) \n{\n     gsl_vector* result;\n     \n     FUNC_MESS_BEGIN();\n     assert(PyGSL_multimin_check(self));     \n     if (self->min.f==NULL || self->func.f==NULL) {\n\t  gsl_error(\"Got a NULL Pointer for min.f\", filename, __LINE__ - 3, GSL_EFAULT);\n\t  return NULL;\n     }\n     if(PyGSL_multimin_isf(self)){       \n\t  result=gsl_multimin_fminimizer_x(self->min.f);\n     } else {\n\t  result=gsl_multimin_fdfminimizer_x(self->min.fdf);\n     }\n     if (result==NULL) {\n\t  gsl_error(\"How could that happen?\",  filename, __LINE__ - 3, GSL_ESANITY);\n\t  return NULL;\n     }\n     FUNC_MESS_END();\n     return (PyObject *) PyGSL_copy_gslvector_to_pyarray(result);\n}\n\nstatic PyObject* \nPyGSL_multimin_minimum(PyGSL_multimin *self, PyObject *args) \n{\n     double min;\n\n     FUNC_MESS_BEGIN();\n     assert(PyGSL_multimin_check(self));     \n     if (self->min.f == NULL || self->func.f ==NULL) {\n\t  gsl_error(\"Got a NULL Pointer of min.f\", filename, __LINE__ - 3, GSL_EFAULT);\n\t  return NULL;\n     }\n     if(PyGSL_multimin_isf(self)){       \n\t  min = gsl_multimin_fminimizer_minimum(self->min.f);\n     } else {\n\t  min = gsl_multimin_fdfminimizer_minimum(self->min.fdf);\n     }\n     FUNC_MESS_END();\n     return PyFloat_FromDouble(min);\n}\n\nstatic PyObject* \nPyGSL_multimin_name(PyGSL_multimin *self, PyObject *args) \n{\n     const char * name;\n     FUNC_MESS_BEGIN();\n     assert(PyGSL_multimin_check(self));     \n     if(PyGSL_multimin_isf(self)){       \n\t  name = gsl_multimin_fminimizer_name(self->min.f);\n     } else {\n\t  name = gsl_multimin_fdfminimizer_name(self->min.fdf);\n     }\n     FUNC_MESS_END();\n     return PyString_FromString(name);\n}\n\nstatic PyObject* \nPyGSL_multimin_size(PyGSL_multimin *self, PyObject *args) \n{\n     double size;\n     FUNC_MESS_BEGIN();\n     assert(PyGSL_multimin_check(self));     \n     if ( self->min.f ==NULL || self->func.f ==NULL) {\n\t  PyErr_SetString(PyExc_RuntimeError,\"no function specified!\");\n\t  return NULL;\n     }\n     if(PyGSL_multimin_isf(self)){       \n\t  size = gsl_multimin_fminimizer_size(self->min.f);\n     } else {\n\t  gsl_error(\"Can not calculate size for a FDF\", filename, __LINE__, GSL_ESANITY);\n\t  return NULL;\n     }\n     FUNC_MESS_END();\n     return PyFloat_FromDouble(size);\n}\n\nstatic PyObject* \nPyGSL_multimin_test_size_method(PyGSL_multimin *self, PyObject *args) \n{\n     int flag=GSL_EFAILED;\n     double epsabs;\n\n     FUNC_MESS_BEGIN();\n     assert(PyGSL_multimin_check(self));     \n     if ( self->min.f ==NULL || self->func.f ==NULL) {\n\t  PyErr_SetString(PyExc_RuntimeError,\"no function specified!\");\n\t  return NULL;\n     }\n\n     if(PyGSL_multimin_isf(self)){\n\t  if (0==PyArg_ParseTuple(args,\"d\", &epsabs))\n\t       return NULL;            \n\t  flag = gsl_multimin_test_size(gsl_multimin_fminimizer_size(self->min.f), epsabs);\n     } else {\n\t  gsl_error(\"Can not calculate size for a FDF\", filename, __LINE__, GSL_ESANITY);\n\t  return NULL;\n     }\n\n     FUNC_MESS_END();\n     return PyGSL_ERROR_FLAG_TO_PYINT(flag);\n}\n\nstatic PyObject* \nPyGSL_multimin_restart(PyGSL_multimin *self, PyObject *args) \n{\n     int flag;\n\n     FUNC_MESS_BEGIN();\n     assert(PyGSL_multimin_check(self));     \n     if(PyGSL_multimin_isf(self)){       \n\t  gsl_error(\"Can not restart for a F type solver\", filename, __LINE__, GSL_ESANITY);\n\t  return NULL;\n     }\n     flag = gsl_multimin_fdfminimizer_restart(self->min.fdf);\n\n     if(PyGSL_ERROR_FLAG(flag) != GSL_SUCCESS){\n\t  return NULL;\n     }\n     FUNC_MESS_END();\n     Py_INCREF(Py_None);\n     return Py_None;\n}\nstatic PyObject* \nPyGSL_multimin_vec_fdf(PyGSL_multimin *self, PyObject *args, \n\t\t       gsl_vector *(*func)(gsl_multimin_fdfminimizer * s))\n{\n     gsl_vector *result;\n     FUNC_MESS_BEGIN();\n     assert(PyGSL_multimin_check(self));     \n     if(PyGSL_multimin_isf(self)){       \n\t  gsl_error(\"Can not retrieve this information for a F type solver!\", filename, __LINE__, GSL_ESANITY);\n\t  return NULL;\n     } else {\n\t  result=func(self->min.fdf);\n     }\n     FUNC_MESS_END();\n     return (PyObject *) PyGSL_copy_gslvector_to_pyarray(result);\n} \n\nstatic PyObject* \nPyGSL_multimin_istype(PyGSL_multimin *self, PyObject *args)\n{\n     static const char *f = \"F-Minimizer\",  *fdf = \"Fdf-Minimizer\";\n     const char *p;\n\n     FUNC_MESS_BEGIN();\n     assert(PyGSL_multimin_check(self));     \n     if(PyGSL_multimin_isf(self)){ \n\t  p = f;\n     } else {\n\t  p = fdf;\n     }\n     FUNC_MESS_END();\n     return PyString_FromString(p);\n}\n\nstatic PyObject* \nPyGSL_multimin_dx(PyGSL_multimin *self, PyObject *args)\n{\n     return PyGSL_multimin_vec_fdf(self, args, gsl_multimin_fdfminimizer_dx);\n}\n\nstatic PyObject* \nPyGSL_multimin_gradient(PyGSL_multimin *self, PyObject *args)\n{\n     return PyGSL_multimin_vec_fdf(self, args, gsl_multimin_fdfminimizer_gradient);\n}\n\nstatic PyObject*\nPyGSL_multimin_test_gradient_method(PyGSL_multimin * self, PyObject *args)\n{\n\n     double epsabs;\n     int flag;\n     FUNC_MESS_BEGIN();\n\n     assert(PyGSL_multimin_check(self));     \n     if (0==PyArg_ParseTuple(args,\"d\", &epsabs))\n\t  return NULL;     \n\n     if(PyGSL_multimin_isf(self)){       \n\t  gsl_error(\"Can not retrieve this information for a F type solver!\", filename, __LINE__, GSL_ESANITY);\n\t  return NULL;\n     }\n     flag = gsl_multimin_test_gradient(gsl_multimin_fdfminimizer_gradient(self->min.fdf), epsabs);\n     FUNC_MESS_END();\n     return PyGSL_ERROR_FLAG_TO_PYINT(flag);\n     \n}\n\n#define PyGSL_MULTIMIN_COMMON_METHODS  \\\n  {\"iterate\",     (PyCFunction)PyGSL_multimin_iterate,METH_NOARGS,(char *)multimin_iterate_doc,}, \\\n  {\"x\",           (PyCFunction)PyGSL_multimin_x,      METH_NOARGS,(char *)multimin_x_doc,      }, \\\n  {\"minimum\",     (PyCFunction)PyGSL_multimin_minimum,METH_NOARGS,(char *)multimin_minimum_doc,}, \\\n  {\"name\",        (PyCFunction)PyGSL_multimin_name,   METH_NOARGS,(char *)multimin_name_doc,   }, \\\n  {\"type\",        (PyCFunction)PyGSL_multimin_istype, METH_NOARGS,(char *)multimin_istype_doc, },\n\nstatic PyMethodDef PyGSL_multimin_fmethods[] = {\n     PyGSL_MULTIMIN_COMMON_METHODS\n     {\"set\",      (PyCFunction)PyGSL_multimin_set_f,           METH_VARARGS|METH_KEYWORDS, (char *)multimin_set_f_doc    },     \n     {\"size\",     (PyCFunction)PyGSL_multimin_size,            METH_NOARGS,  (char *)multimin_size_doc     },\n     {\"test_size\",(PyCFunction)PyGSL_multimin_test_size_method,METH_VARARGS, (char *)multimin_test_size_doc},\n     {NULL, NULL, 0, NULL}           /* sentinel */\n};\n\nstatic PyMethodDef PyGSL_multimin_fdfmethods[] = {\n     PyGSL_MULTIMIN_COMMON_METHODS\n     {\"set\",      (PyCFunction)PyGSL_multimin_set_fdf,                 METH_VARARGS|METH_KEYWORDS, (char *)multimin_set_fdf_doc      },     \n     {\"restart\",  (PyCFunction)PyGSL_multimin_restart,                 METH_NOARGS,  (char *)multimin_restart_doc      },     \n     {\"dx\",       (PyCFunction)PyGSL_multimin_dx,                      METH_NOARGS,  (char *)multimin_dx_doc           },     \n     {\"gradient\", (PyCFunction)PyGSL_multimin_gradient,                METH_NOARGS,  (char *)multimin_gradient_doc     },     \n     {\"test_gradient\",(PyCFunction)PyGSL_multimin_test_gradient_method,METH_VARARGS, (char *)multimin_test_gradient_doc},     \n     {NULL, NULL, 0, NULL}           /* sentinel */\n};\n\nstatic PyObject* \nPyGSL_multimin_init(PyObject *self, PyObject *args, \n\t\t    union pygsl_multimin_minimizer_type type, int t) \n{\n\n     PyGSL_multimin *min_o=NULL;\n     size_t n;\n     /* static const char functionname [] = __FUNCTION__; */\n\n     FUNC_MESS_BEGIN();     \n     min_o =  (PyGSL_multimin *) PyObject_NEW(PyGSL_multimin, &PyGSL_multimin_pytype);\n     if(min_o == NULL){\n\t  return NULL;\n     }\n\n     if (0==PyArg_ParseTuple(args,\"l\", &n))\n\t  return NULL;\n\n\n     if (n<=0) {\n\t  PyErr_SetString(PyExc_RuntimeError, \"dimension must be >0\");\n\t  return NULL;\n     }\n     min_o->n=n;\n     min_o->min.f=NULL;\n     min_o->min.fdf=NULL;\n     min_o->func.f=NULL;\n     min_o->func.fdf=NULL;\n     min_o->py_f=NULL;\n     min_o->py_df=NULL;\n     min_o->py_fdf=NULL;\n     min_o->trailing_params=NULL;\n     min_o->mytype=NULL;\n\n     if(t == 0){\n\t  min_o->min.f = gsl_multimin_fminimizer_alloc(type.f,n);\n\t  if (min_o->min.f == NULL) {\n\t\tgsl_error(\"Could not allocate the object for the minimizer\", \n\t\t\t  filename, __LINE__ - 3, GSL_ENOMEM);\n\t       goto fail;\n\t  }\n\t  min_o->mytype = my_solvers.f_minimizer;\n\t  assert(PyGSL_multimin_isf(min_o));\n     } else {\n\t  min_o->min.fdf = gsl_multimin_fdfminimizer_alloc(type.fdf,n);\n\t  if (min_o->min.fdf == NULL) {\n\t\tgsl_error(\"Could not allocate the object for the fdfminimizer\", \n\t\t\t  filename, __LINE__ - 3, GSL_ENOMEM);\n\t       goto fail;\n\t  }\n\t  min_o->mytype = my_solvers.fdf_minimizer;\n\t  assert(!PyGSL_multimin_isf(min_o));\n     }\n     FUNC_MESS_END();\n     return (PyObject *) min_o;\n fail:\n     Py_XDECREF(min_o);\n     return NULL;\n}\n\n#define AMINIMIZER(name)                                                      \\\nstatic PyObject* PyGSL_multimin_init_ ## name (PyObject *self, PyObject *args)\\\n{                                                                             \\\n     PyObject *tmp = NULL;                                                    \\\n     union pygsl_multimin_minimizer_type type;                                \\\n     FUNC_MESS_BEGIN();                                                       \\\n     type.f  = gsl_multimin_fminimizer_ ## name;                              \\\n     tmp = PyGSL_multimin_init(self, args, type, 0);                          \\\n     if (tmp == NULL){                                                        \\\n\t  PyGSL_add_traceback(module, (char *) filename, __FUNCTION__, __LINE__);      \\\n     }                                                                        \\\n     FUNC_MESS_END();                                                         \\\n     return tmp;                                                              \\\n}\n#define AMINIMIZER_FDF(name)                                                  \\\nstatic PyObject* PyGSL_multimin_init_ ## name (PyObject *self, PyObject *args)\\\n{                                                                             \\\n     PyObject *tmp = NULL;                                                    \\\n     union pygsl_multimin_minimizer_type type;                                \\\n     FUNC_MESS_BEGIN();                                                       \\\n     type.fdf  = gsl_multimin_fdfminimizer_ ## name;                          \\\n     tmp = PyGSL_multimin_init(self, args,  type, 1);                         \\\n     if (tmp == NULL){                                                        \\\n\t  PyGSL_add_traceback(module, (char *) filename, __FUNCTION__, __LINE__);      \\\n     }                                                                        \\\n     FUNC_MESS_END();                                                         \\\n     return tmp;                                                              \\\n}\n\nAMINIMIZER(nmsimplex)\nAMINIMIZER_FDF(steepest_descent)\nAMINIMIZER_FDF(vector_bfgs)\nAMINIMIZER_FDF(conjugate_pr)\nAMINIMIZER_FDF(conjugate_fr)\n\n\n\nstatic void\nPyGSL_multimin_dealloc(PyGSL_multimin *self)\n{\n     FUNC_MESS_BEGIN();\n     assert(PyGSL_multimin_check(self));     \n     if(PyGSL_multimin_isf(self)){\n\t  if (self->min.f  != NULL)   gsl_multimin_fminimizer_free(self->min.f);\n\t  if (self->func.f != NULL)  free(self->func.f); \n     }else{\n\t  if (self->min.fdf  != NULL)   gsl_multimin_fdfminimizer_free(self->min.fdf);\n\t  if (self->func.fdf != NULL)  free(self->func.fdf); \n     }\n\n     Py_XDECREF(self->trailing_params);     \n     Py_XDECREF(self->py_f);     \n     Py_XDECREF(self->py_df);     \n     Py_XDECREF(self->py_fdf);     \n     PyMem_Free(self);\n     FUNC_MESS_END();\n}\n\n\nstatic PyObject*\nPyGSL_multimin_getattr(PyGSL_multimin *self, char *name)\n{\n\n     PyObject *tmp = NULL;\n\n\n     FUNC_MESS_BEGIN();\n     assert(PyGSL_multimin_check(self));     \n     if(PyGSL_multimin_isf(self)){\n\t  tmp = Py_FindMethod(PyGSL_multimin_fmethods, (PyObject *) self, name);\n     } else {\n\t  tmp = Py_FindMethod(PyGSL_multimin_fdfmethods, (PyObject *) self, name);\n     }\n     FUNC_MESS_END();\n     return tmp;\n}\n\n\n\n\nstatic PyObject*\nPyGSL_multimin_test_size(PyObject * self, PyObject *args)\n{\n     double size, epsabs;\n     int flag = GSL_EFAILED;\n     FUNC_MESS_BEGIN();\n     if (0==PyArg_ParseTuple(args,\"dd\", &size, &epsabs))\n\t  return NULL;     \n     flag = gsl_multimin_test_size(size, epsabs);\n     FUNC_MESS_END();\n     return PyGSL_ERROR_FLAG_TO_PYINT(flag);\n     \n}\n\nstatic PyObject*\nPyGSL_multimin_test_gradient(PyObject * self, PyObject *args)\n{\n     PyObject *g=NULL;\n     PyArrayObject *ga=NULL;\n     gsl_vector_view gradient;\n\n     double epsabs;\n     int flag = GSL_EFAILED, stride_recalc=-1;\n\n     FUNC_MESS_BEGIN();\n     if (0==PyArg_ParseTuple(args,\"Od\", &g, &epsabs))\n\t  return NULL;     \n\n     ga  = PyGSL_PyArray_PREPARE_gsl_vector_view(g, PyArray_DOUBLE, 0, -1, 1, NULL);\n     if (ga == NULL){\n\t  PyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__ - 1);\n\t  return NULL;\n     }\n     if((PyGSL_STRIDE_RECALC(ga->strides[0],sizeof(double), &stride_recalc)) != GSL_SUCCESS){\n\t  Py_XDECREF(ga);\n\t  return NULL;\n     }\n     gradient = gsl_vector_view_array_with_stride((double *)(ga->data), stride_recalc, ga->dimensions[0]);\n\n     flag = gsl_multimin_test_gradient(&gradient.vector, epsabs);\n     FUNC_MESS_END();\n     return PyGSL_ERROR_FLAG_TO_PYINT(flag);\n     \n}\n\n\n\n\nstatic PyMethodDef multiminMethods[] = {\n     {\"nmsimplex\",        PyGSL_multimin_init_nmsimplex,        METH_VARARGS, (char *)nmsimplex_doc       },\n     {\"steepest_descent\", PyGSL_multimin_init_steepest_descent, METH_VARARGS, (char *)steepest_descent_doc},\n     {\"vector_bfgs\",      PyGSL_multimin_init_vector_bfgs,      METH_VARARGS, (char *)vector_bfgs_doc     },\n     {\"conjugate_pr\",     PyGSL_multimin_init_conjugate_pr,     METH_VARARGS, (char *)conjugate_pr_doc    },\n     {\"conjugate_fr\",     PyGSL_multimin_init_conjugate_fr,     METH_VARARGS, (char *)conjugate_fr_doc    },\n     {\"test_size\",        PyGSL_multimin_test_size,             METH_VARARGS, (char *)test_size_doc       },\n     {\"test_gradient\",    PyGSL_multimin_test_gradient,         METH_VARARGS, (char *)test_gradient_doc   },\n     {NULL, NULL, 0, NULL}        /* Sentinel */\n};\n\n\n\nvoid\ninitmultimin(void)\n{\n  PyObject* m, *dict, *item;\n  m=Py_InitModule(\"multimin\", multiminMethods);\n  import_array();\n  init_pygsl();\n  /* init multimin type */\n  PyGSL_multimin_pytype.ob_type  = &PyType_Type;\n\n\n  module = m;\n\n  Py_INCREF((PyObject*)&PyGSL_multimin_pytype);\n\n  dict = PyModule_GetDict(m);\n  if(!dict)\n       goto fail;\n  \n  if (!(item = PyString_FromString((char*)PyGSL_multimin_module_doc))){\n       PyErr_SetString(PyExc_ImportError, \n\t\t       \"I could not generate module doc string!\");\n       goto fail;\n  }\n  if (PyDict_SetItemString(dict, \"__doc__\", item) != 0){\n       PyErr_SetString(PyExc_ImportError, \n\t\t       \"I could not init doc string!\");\n       goto fail;\n  }\n\n fail:\n  return;\n}\n", "meta": {"hexsha": "96e6562364d3b6e3cd22b2de8d2fb6f5605f115c", "size": 27317, "ext": "c", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/testing/src/multiminmodule.c", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/testing/src/multiminmodule.c", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/testing/src/multiminmodule.c", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 31.6168981481, "max_line_length": 140, "alphanum_fraction": 0.6160266501, "num_tokens": 7747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.051082739846285856, "lm_q1q2_score": 0.023947109622325737}}
{"text": "/* gsl_spmatrix.h\n * \n * Copyright (C) 2012-2014 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_SPMATRIX_H__\n#define __GSL_SPMATRIX_H__\n\n#include <stdlib.h>\n\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\n/*\n * Binary tree data structure for storing sparse matrix elements\n * in triplet format. This is used for efficiently detecting\n * duplicates and element retrieval via gsl_spmatrix_get\n */\ntypedef struct\n{\n  void *tree;       /* tree structure */\n  void *node_array; /* preallocated array of tree nodes */\n  size_t n;         /* number of tree nodes in use (<= nzmax) */\n} gsl_spmatrix_tree;\n\n/*\n * Triplet format:\n *\n * If data[n] = A_{ij}, then:\n *   i = A->i[n]\n *   j = A->p[n]\n *\n * Compressed column format (CCS):\n *\n * If data[n] = A_{ij}, then:\n *   i = A->i[n]\n *   A->p[j] <= n < A->p[j+1]\n * so that column j is stored in\n * [ data[p[j]], data[p[j] + 1], ..., data[p[j+1] - 1] ]\n *\n * Compressed row format (CRS):\n *\n * If data[n] = A_{ij}, then:\n *   j = A->i[n]\n *   A->p[i] <= n < A->p[i+1]\n * so that row i is stored in\n * [ data[p[i]], data[p[i] + 1], ..., data[p[i+1] - 1] ]\n */\n\ntypedef struct\n{\n  size_t size1;  /* number of rows */\n  size_t size2;  /* number of columns */\n\n  /* i (size nzmax) contains:\n   *\n   * Triplet/CCS: row indices\n   * CRS: column indices\n   */\n  size_t *i;\n\n  double *data;  /* matrix elements of size nzmax */\n\n  /*\n   * p contains the column indices (triplet) or column pointers (compcol)\n   *\n   * triplet: p[n] = column number of element data[n]\n   * CCS:     p[j] = index in data of first non-zero element in column j\n   * CRS:     p[i] = index in data of first non-zero element in row i\n   */\n  size_t *p;\n\n  size_t nzmax;  /* maximum number of matrix elements */\n  size_t nz;     /* number of non-zero values in matrix */\n\n  gsl_spmatrix_tree *tree_data; /* binary tree for sorting triplet data */\n\n  /*\n   * workspace of size MAX(size1,size2)*MAX(sizeof(double),sizeof(size_t))\n   * used in various routines\n   */\n  void *work;\n\n  size_t sptype; /* sparse storage type */\n} gsl_spmatrix;\n\n#define GSL_SPMATRIX_TRIPLET      (0)\n#define GSL_SPMATRIX_CCS          (1)\n#define GSL_SPMATRIX_CRS          (2)\n\n#define GSL_SPMATRIX_ISTRIPLET(m) ((m)->sptype == GSL_SPMATRIX_TRIPLET)\n#define GSL_SPMATRIX_ISCCS(m)     ((m)->sptype == GSL_SPMATRIX_CCS)\n#define GSL_SPMATRIX_ISCRS(m)     ((m)->sptype == GSL_SPMATRIX_CRS)\n\n/*\n * Prototypes\n */\n\ngsl_spmatrix *gsl_spmatrix_alloc(const size_t n1, const size_t n2);\ngsl_spmatrix *gsl_spmatrix_alloc_nzmax(const size_t n1, const size_t n2,\n                                       const size_t nzmax, const size_t flags);\nvoid gsl_spmatrix_free(gsl_spmatrix *m);\nint gsl_spmatrix_realloc(const size_t nzmax, gsl_spmatrix *m);\nint gsl_spmatrix_set_zero(gsl_spmatrix *m);\nsize_t gsl_spmatrix_nnz(const gsl_spmatrix *m);\nint gsl_spmatrix_compare_idx(const size_t ia, const size_t ja,\n                             const size_t ib, const size_t jb);\nint gsl_spmatrix_tree_rebuild(gsl_spmatrix * m);\n\n/* spcopy.c */\nint gsl_spmatrix_memcpy(gsl_spmatrix *dest, const gsl_spmatrix *src);\n\n/* spgetset.c */\ndouble gsl_spmatrix_get(const gsl_spmatrix *m, const size_t i,\n                        const size_t j);\nint gsl_spmatrix_set(gsl_spmatrix *m, const size_t i, const size_t j,\n                     const double x);\ndouble *gsl_spmatrix_ptr(gsl_spmatrix *m, const size_t i, const size_t j);\n\n/* spcompress.c */\ngsl_spmatrix *gsl_spmatrix_compcol(const gsl_spmatrix *T);\ngsl_spmatrix *gsl_spmatrix_ccs(const gsl_spmatrix *T);\ngsl_spmatrix *gsl_spmatrix_crs(const gsl_spmatrix *T);\nvoid gsl_spmatrix_cumsum(const size_t n, size_t *c);\n\n/* spio.c */\nint gsl_spmatrix_fprintf(FILE *stream, const gsl_spmatrix *m,\n                         const char *format);\ngsl_spmatrix * gsl_spmatrix_fscanf(FILE *stream);\nint gsl_spmatrix_fwrite(FILE *stream, const gsl_spmatrix *m);\nint gsl_spmatrix_fread(FILE *stream, gsl_spmatrix *m);\n\n/* spoper.c */\nint gsl_spmatrix_scale(gsl_spmatrix *m, const double x);\nint gsl_spmatrix_minmax(const gsl_spmatrix *m, double *min_out,\n                        double *max_out);\nint gsl_spmatrix_add(gsl_spmatrix *c, const gsl_spmatrix *a,\n                     const gsl_spmatrix *b);\nint gsl_spmatrix_d2sp(gsl_spmatrix *S, const gsl_matrix *A);\nint gsl_spmatrix_sp2d(gsl_matrix *A, const gsl_spmatrix *S);\n\n/* spprop.c */\nint gsl_spmatrix_equal(const gsl_spmatrix *a, const gsl_spmatrix *b);\n\n/* spswap.c */\nint gsl_spmatrix_transpose(gsl_spmatrix * m);\nint gsl_spmatrix_transpose2(gsl_spmatrix * m);\nint gsl_spmatrix_transpose_memcpy(gsl_spmatrix *dest, const gsl_spmatrix *src);\n\n__END_DECLS\n\n#endif /* __GSL_SPMATRIX_H__ */\n", "meta": {"hexsha": "8e68256f9dfc068ce62af680b6410897483a7d2b", "size": 5599, "ext": "h", "lang": "C", "max_stars_repo_path": "3rdparty/wingsl/include/gsl/gsl_spmatrix.h", "max_stars_repo_name": "Tjoppen/fmigo", "max_stars_repo_head_hexsha": "0ad5e82b49a973cf710f85daa9dffc45261b36ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-12-18T16:35:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-14T07:38:05.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/spmatrix/gsl_spmatrix.h", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/spmatrix/gsl_spmatrix.h", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-12-20T16:50:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-13T05:31:07.000Z", "avg_line_length": 31.1055555556, "max_line_length": 81, "alphanum_fraction": 0.6858367566, "num_tokens": 1650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938443711712, "lm_q2_score": 0.048136775554611266, "lm_q1q2_score": 0.02388035804051932}}
{"text": "/* gsl_histogram_calloc_range.c\n * Copyright (C) 2000  Simone Piccardi\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU General Public License as\n * published by the Free Software Foundation; either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this library; if not, write to the Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n/***************************************************************\n *\n * File gsl_histogram_calloc_range.c: \n * Routine to create a variable binning histogram providing \n * an input range vector. Need GSL library and header.\n * Do range check and allocate the histogram data. \n *\n * Author: S. Piccardi\n * Jan. 2000\n *\n ***************************************************************/\n#include <config.h>\n#include <stdlib.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_histogram.h>\n\ngsl_histogram *\ngsl_histogram_calloc_range (size_t n, double *range)\n{\n  size_t i;\n  gsl_histogram *h;\n\n  /* check arguments */\n\n  if (n == 0)\n    {\n      GSL_ERROR_VAL (\"histogram length n must be positive integer\",\n                        GSL_EDOM, 0);\n    }\n\n  /* check ranges */\n\n  for (i = 0; i < n; i++)\n    {\n      if (range[i] >= range[i + 1])\n        {\n          GSL_ERROR_VAL (\"histogram bin extremes  must be \"\n                            \"in increasing order\", GSL_EDOM, 0);\n        }\n    }\n\n  /* Allocate histogram  */\n\n  h = (gsl_histogram *) malloc (sizeof (gsl_histogram));\n\n  if (h == 0)\n    {\n      GSL_ERROR_VAL (\"failed to allocate space for histogram struct\",\n                        GSL_ENOMEM, 0);\n    }\n\n  h->range = (double *) malloc ((n + 1) * sizeof (double));\n\n  if (h->range == 0)\n    {\n      /* exception in constructor, avoid memory leak */\n      free (h);\n      GSL_ERROR_VAL (\"failed to allocate space for histogram ranges\",\n                        GSL_ENOMEM, 0);\n    }\n\n  h->bin = (double *) malloc (n * sizeof (double));\n\n  if (h->bin == 0)\n    {\n      /* exception in constructor, avoid memory leak */\n      free (h->range);\n      free (h);\n      GSL_ERROR_VAL (\"failed to allocate space for histogram bins\",\n                        GSL_ENOMEM, 0);\n    }\n\n  /* initialize ranges */\n\n  for (i = 0; i <= n; i++)\n    {\n      h->range[i] = range[i];\n    }\n\n  /* clear contents */\n\n  for (i = 0; i < n; i++)\n    {\n      h->bin[i] = 0;\n    }\n\n  h->n = n;\n\n  return h;\n}\n", "meta": {"hexsha": "6549b73d35d742f98fea7c56b44417b428e7eb90", "size": 2779, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/histogram/calloc_range.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/histogram/calloc_range.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/histogram/calloc_range.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 25.7314814815, "max_line_length": 74, "alphanum_fraction": 0.5750269881, "num_tokens": 691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.061875989183534374, "lm_q1q2_score": 0.02381681968869889}}
{"text": "/* Siconos-Numerics, Copyright INRIA 2005-2011.\n * Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n * Siconos is a free software; you can redistribute it and/or modify\n * it under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n * Siconos is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with Siconos; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\n * Contact: Vincent ACARY, siconos-team@lists.gforge.inria.fr\n */\n\n#ifndef SiconosBlas_H\n#define SiconosBlas_H\n\n#include \"SiconosConfig.h\"\n\n#if defined(__cplusplus)\n#include <algorithm>\nusing std::min;\nusing std::max;\n#else\n#define min(a,b) ((a)>(b)?(b):(a))\n#define max(a,b) ((a) >= (b) ? (a) : (b))\n#endif\n\n#if defined(__cplusplus) \nextern \"C\"\n{\n#endif\n\n#if defined(HAS_MKL_CBLAS) \n#include <mkl_cblas.h>\n#elif defined(HAS_ATLAS_CBLAS)\n#include <cblas.h>\n#elif defined(HAS_ACCELERATE)\n#include <Accelerate.h>\n#else\n#include <cblas.h>\n#endif \n\n#ifdef __cplusplus\n}\n#endif\n\n\n#include \"matrix_la.h\"\n\n#endif // SiconosBlas_H\n\n\n", "meta": {"hexsha": "e7538814ec35fc21ea4a89f8f6deeadde4601684", "size": 1501, "ext": "h", "lang": "C", "max_stars_repo_path": "externals/blas_lapack/SiconosBlas.h", "max_stars_repo_name": "siconos/siconos-deb", "max_stars_repo_head_hexsha": "2739a23f23d797dbfecec79d409e914e13c45c67", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "externals/blas_lapack/SiconosBlas.h", "max_issues_repo_name": "siconos/siconos-deb", "max_issues_repo_head_hexsha": "2739a23f23d797dbfecec79d409e914e13c45c67", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "externals/blas_lapack/SiconosBlas.h", "max_forks_repo_name": "siconos/siconos-deb", "max_forks_repo_head_hexsha": "2739a23f23d797dbfecec79d409e914e13c45c67", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4406779661, "max_line_length": 78, "alphanum_fraction": 0.7335109927, "num_tokens": 407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552954976388515, "lm_q2_score": 0.053403328669912084, "lm_q1q2_score": 0.02379276097819871}}
{"text": "/*\n * Partition.h\n * Provides class prototype that simplifies partition vectors.\n *\n   Copyright 2017 Dariusz Kuchta\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n   \n   http://www.apache.org/licenses/LICENSE-2.0\n   \n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\n#pragma once\n\n#include <vector>\n#include <gsl.h>\n\nnamespace spectre::unsupervised\n{\n/// <summary>\n/// Class storing simplified representation of partition vectors.\n/// </summary>\nclass Partition\n{\npublic:\n\n    /// <summary>\n    /// Default constructor. Deleted so no dataless instance can be created.\n    /// </summary>\n    Partition() = delete;\n\n    /// <summary>\n    /// Constructor taking partition data and computing its simplified version.\n    /// </summary>\n    /// <param name=\"partition\">Input partition data.</param>\n    explicit Partition(gsl::span<unsigned int> partition);\n\n    /// <summary>\n    /// Getter for simplified partition data.\n    /// </summary>\n    /// <returns>Stored simplified partition.</returns>\n    const std::vector<unsigned int>& Get() const;\n\n    /// <summary>\n    /// Method for comparing specified partitions.\n    /// </summary>\n    /// <param name=\"lhs\">The first partition.</param>\n    /// <param name=\"rhs\">The second partition.</param>\n    /// <param name=\"tolerance\">The tolerance rate of mismatch.</param>\n    static bool Compare(const Partition &lhs, const Partition &rhs, double tolerance = 0);\n\n    /// <summary>\n    /// Equality operator. Compares with tolerance = 0.\n    /// </summary>\n    /// <param name=\"other\">The second partition.</param>\n    bool operator==(const Partition &other) const;\n\n    /// <summary>\n    /// Inequality operator. Compares with tolerance = 0.\n    /// </summary>\n    /// <param name=\"other\">The second partition.</param>\n    bool operator!=(const Partition &other) const;\n\nprivate:\n    std::vector<unsigned int> m_Partition;\n};\n}\n", "meta": {"hexsha": "4598561dd7c51e3f905a4a252652fa066602f804", "size": 2279, "ext": "h", "lang": "C", "max_stars_repo_path": "src/Spectre.libClustering/Partition.h", "max_stars_repo_name": "spectre-team/native-algorithms", "max_stars_repo_head_hexsha": "e5e4a65b52d44bc6c0efe68743eae83a08871664", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Spectre.libClustering/Partition.h", "max_issues_repo_name": "spectre-team/native-algorithms", "max_issues_repo_head_hexsha": "e5e4a65b52d44bc6c0efe68743eae83a08871664", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 36.0, "max_issues_repo_issues_event_min_datetime": "2017-12-31T16:44:51.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-03T21:18:46.000Z", "max_forks_repo_path": "src/Spectre.libClustering/Partition.h", "max_forks_repo_name": "spectre-team/native-algorithms", "max_forks_repo_head_hexsha": "e5e4a65b52d44bc6c0efe68743eae83a08871664", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3866666667, "max_line_length": 90, "alphanum_fraction": 0.6779289162, "num_tokens": 506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3775406547908327, "lm_q2_score": 0.0627892042126289, "lm_q1q2_score": 0.023705477272231226}}
{"text": "#pragma once\n\n#include <memory_resource>\n#include <vector>\n\n#include <gsl-lite/gsl-lite.hpp>\n\n#include <thrust/sort.h>\n#include <cuda/define_specifiers.hpp>\n\n#include <thrustshift/memory-resource.h>\n\nnamespace thrustshift {\n\n//! Col indices must be ordered\ntemplate <typename DataType, typename IndexType>\nclass CSR {\n   public:\n\tusing value_type = DataType;\n\tusing index_type = IndexType;\n\n   private:\n\tbool cols_are_sorted() {\n\t\tfor (size_t row_id = 0; row_id < this->num_rows(); ++row_id) {\n\t\t\tif (!std::is_sorted(col_indices_.begin() + row_ptrs_[row_id],\n\t\t\t                    col_indices_.begin() + row_ptrs_[row_id + 1])) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n   public:\n\tCSR() : row_ptrs_(1, 0, &pmr::default_resource), num_cols_(0) {\n\t}\n\n\ttemplate <class DataRange,\n\t          class ColIndRange,\n\t          class RowPtrsRange,\n\t          class MemoryResource>\n\tCSR(DataRange&& values,\n\t    ColIndRange&& col_indices,\n\t    RowPtrsRange&& row_ptrs,\n\t    size_t num_cols,\n\t    MemoryResource& memory_resource)\n\t    : values_(values.begin(), values.end(), &memory_resource),\n\t      col_indices_(col_indices.begin(),\n\t                   col_indices.end(),\n\t                   &memory_resource),\n\t      row_ptrs_(row_ptrs.begin(), row_ptrs.end(), &memory_resource),\n\t      num_cols_(num_cols) {\n\t\tgsl_Expects(values.size() == col_indices.size());\n\t\tgsl_Expects(row_ptrs.size() > 0);\n\t\tgsl_Expects(row_ptrs[0] == 0);\n\t\tgsl_ExpectsAudit(cols_are_sorted());\n\t}\n\n\ttemplate <class DataRange, class ColIndRange, class RowPtrsRange>\n\tCSR(DataRange&& values,\n\t    ColIndRange&& col_indices,\n\t    RowPtrsRange&& row_ptrs,\n\t    size_t num_cols)\n\t    : CSR(std::forward<DataRange>(values),\n\t          std::forward<ColIndRange>(col_indices),\n\t          std::forward<RowPtrsRange>(row_ptrs),\n\t          num_cols,\n\t          pmr::default_resource) {\n\t}\n\n\t// The copy constructor is declared explicitly to ensure\n\t// managed memory is used per default.\n\tCSR(const CSR& other)\n\t    : CSR(other.values(),\n\t          other.col_indices(),\n\t          other.row_ptrs(),\n\t          other.num_cols()) {\n\t}\n\n\tCSR(CSR&& other) = default;\n\n\tCSR& operator=(const CSR& other) = default;\n\n\tgsl_lite::span<DataType> values() {\n\t\treturn gsl_lite::make_span(values_);\n\t}\n\n\tgsl_lite::span<const DataType> values() const {\n\t\treturn gsl_lite::make_span(values_);\n\t}\n\n\tgsl_lite::span<IndexType> col_indices() {\n\t\treturn gsl_lite::make_span(col_indices_);\n\t}\n\n\tgsl_lite::span<const IndexType> col_indices() const {\n\t\treturn gsl_lite::make_span(col_indices_);\n\t}\n\n\tgsl_lite::span<IndexType> row_ptrs() {\n\t\treturn gsl_lite::make_span(row_ptrs_);\n\t}\n\n\tgsl_lite::span<const IndexType> row_ptrs() const {\n\t\treturn gsl_lite::make_span(row_ptrs_);\n\t}\n\n\tsize_t num_rows() const {\n\t\treturn row_ptrs_.size() - 1;\n\t}\n\n\tsize_t num_cols() const {\n\t\treturn num_cols_;\n\t}\n\n\tvoid sort_column_indices() {\n\t\tfor (size_t row_id = 0; row_id < num_rows(); ++row_id) {\n\t\t\tconst auto nns_start = row_ptrs_[row_id];\n\t\t\tconst auto nns_end = row_ptrs_[row_id + 1];\n\t\t\tthrust::sort_by_key(thrust::host,\n\t\t\t                    col_indices_.begin() + nns_start,\n\t\t\t                    col_indices_.begin() + nns_end,\n\t\t\t                    values_.begin() + nns_start);\n\t\t}\n\t}\n\n\t/*! \\brief Add additional elements to each row of the matrix.\n\t *\n\t *  A row might already have the maximum number of element. Therefore\n\t *  not every row might be extended by exactly `num_max_additional_elements_per_row`.\n\t *\n\t */\n\tvoid extend_rows(int num_max_additional_elements_per_row,\n\t                 DataType value = 0) {\n\t\tif (num_max_additional_elements_per_row == 0) {\n\t\t\treturn;\n\t\t}\n\t\tgsl_Expects(num_max_additional_elements_per_row >= 0);\n\t\tstd::vector<DataType> tmp_values(values_.begin(), values_.end());\n\t\tstd::vector<IndexType> tmp_col_indices(col_indices_.begin(),\n\t\t                                       col_indices_.end());\n\t\tsize_t num_additional_elements = 0;\n\t\tconst int nc = gsl_lite::narrow<int>(num_cols());\n\t\tauto get_num_additional_elements_per_row = [&](size_t row_id) {\n\t\t\tconst int num_elements_curr_row =\n\t\t\t    row_ptrs_[row_id + 1] - row_ptrs_[row_id];\n\t\t\treturn std::max(std::min(num_max_additional_elements_per_row,\n\t\t\t                         nc - num_elements_curr_row),\n\t\t\t                0);\n\t\t};\n\t\tfor (size_t row_id = 0; row_id < num_rows(); ++row_id) {\n\t\t\tnum_additional_elements +=\n\t\t\t    get_num_additional_elements_per_row(row_id);\n\t\t}\n\n\t\tconst size_t new_nnz = values_.size() + num_additional_elements;\n\t\tvalues_.resize(new_nnz);\n\t\tcol_indices_.resize(new_nnz);\n\t\tint nns_offset = 0;\n\t\tfor (size_t row_id = 0; row_id < num_rows(); ++row_id) {\n\t\t\tconst int num_additional_elements_curr_row =\n\t\t\t    get_num_additional_elements_per_row(row_id);\n\t\t\tint nns_id = row_ptrs_[row_id];\n\t\t\tconst int nns_end = row_ptrs_[row_id + 1];\n\t\t\tconst int nnz_curr_row = nns_end - nns_id;\n\t\t\tint curr_col_id = 0;\n\t\t\tint num_added_elements = 0;\n\t\t\tfor (int new_nns_id = nns_offset;\n\t\t\t     new_nns_id < nns_offset + num_additional_elements_curr_row +\n\t\t\t                      row_ptrs_[row_id + 1] - row_ptrs_[row_id];\n\t\t\t     ++new_nns_id) {\n\t\t\t\tconst int other_col_id = nns_id == nns_end\n\t\t\t\t                             ? std::numeric_limits<int>::max()\n\t\t\t\t                             : tmp_col_indices[nns_id];\n\t\t\t\tif (curr_col_id < other_col_id &&\n\t\t\t\t    num_added_elements < num_additional_elements_curr_row) {\n\t\t\t\t\tvalues_[new_nns_id] = value;\n\t\t\t\t\tcol_indices_[new_nns_id] = curr_col_id;\n\t\t\t\t\t++curr_col_id;\n\t\t\t\t\t++num_added_elements;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tvalues_[new_nns_id] = tmp_values[nns_id];\n\t\t\t\t\tcol_indices_[new_nns_id] = other_col_id;\n\t\t\t\t\tcurr_col_id = other_col_id + 1;\n\t\t\t\t\t++nns_id;\n\t\t\t\t}\n\t\t\t}\n\t\t\trow_ptrs_[row_id] = nns_offset;\n\t\t\tnns_offset += nnz_curr_row + num_additional_elements_curr_row;\n\t\t}\n\t\trow_ptrs_.back() = values_.size();\n\t\tgsl_ExpectsAudit(std::is_sorted(row_ptrs_.begin(), row_ptrs_.end()));\n\t\tgsl_ExpectsAudit(cols_are_sorted());\n\t}\n\n   private:\n\tstd::pmr::vector<DataType> values_;\n\tstd::pmr::vector<IndexType> col_indices_;\n\tstd::pmr::vector<IndexType> row_ptrs_;\n\tsize_t num_cols_;\n};\n\ntemplate <typename DataType, typename IndexType>\nbool operator==(const CSR<DataType, IndexType>& a,\n                const CSR<DataType, IndexType>& b) {\n\treturn equal(a.values(), b.values()) &&\n\t       equal(a.col_indices(), b.col_indices()) &&\n\t       equal(a.row_ptrs(), b.row_ptrs()) &&\n\t       a.num_rows() == b.num_rows() && a.num_cols() == b.num_cols();\n}\n\n\ntemplate <typename DataType, typename IndexType>\nclass CSR_view {\n\n   public:\n\tusing value_type = DataType;\n\tusing index_type = IndexType;\n\n\ttemplate <typename OtherDataType, typename OtherIndexType>\n\tCSR_view(CSR<OtherDataType, OtherIndexType>& owner)\n\t    : values_(owner.values()),\n\t      col_indices_(owner.col_indices()),\n\t      row_ptrs_(owner.row_ptrs()),\n\t      num_cols_(owner.num_cols()) {\n\t}\n\n\ttemplate <typename OtherDataType, typename OtherIndexType>\n\tCSR_view(const CSR<OtherDataType, OtherIndexType>& owner)\n\t    : values_(owner.values()),\n\t      col_indices_(owner.col_indices()),\n\t      row_ptrs_(owner.row_ptrs()),\n\t      num_cols_(owner.num_cols()) {\n\t}\n\n\ttemplate <class DataRange,\n\t          class ColIndRange,\n\t          class RowPtrsRange>\n\tCSR_view(DataRange&& values,\n\t    ColIndRange&& col_indices,\n\t    RowPtrsRange&& row_ptrs,\n\t    size_t num_cols)\n\t    : values_(values),\n\t      col_indices_(col_indices),\n\t      row_ptrs_(row_ptrs),\n\t      num_cols_(num_cols) {\n\t\tgsl_Expects(values.size() == col_indices.size());\n\t\tgsl_Expects(row_ptrs.size() > 0);\n\t\tgsl_ExpectsAudit(row_ptrs[0] == 0);\n\t\tgsl_ExpectsAudit(row_ptrs.back() == values.size());\n\t\tgsl_ExpectsAudit(std::is_sorted(row_ptrs.begin(), row_ptrs.end()));\n\t}\n\n\tCSR_view(const CSR_view& other) = default;\n\tCSR_view(CSR_view&& other) = default;\n\n\tCUDA_FHD gsl_lite::span<DataType> values() {\n\t\treturn values_;\n\t}\n\n\tCUDA_FHD gsl_lite::span<const DataType> values() const {\n\t\treturn values_;\n\t}\n\n\tCUDA_FHD gsl_lite::span<IndexType> col_indices() {\n\t\treturn col_indices_;\n\t}\n\n\tCUDA_FHD gsl_lite::span<const IndexType> col_indices() const {\n\t\treturn col_indices_;\n\t}\n\n\tCUDA_FHD gsl_lite::span<IndexType> row_ptrs() {\n\t\treturn row_ptrs_;\n\t}\n\n\tCUDA_FHD gsl_lite::span<const IndexType> row_ptrs() const {\n\t\treturn row_ptrs_;\n\t}\n\n\tCUDA_FHD size_t num_rows() const {\n\t\treturn row_ptrs_.size() - 1;\n\t}\n\n\tCUDA_FHD size_t num_cols() const {\n\t\treturn num_cols_;\n\t}\n\n\tCUDA_FHD auto max_row_nnz() const {\n\t\tusing I = typename std::remove_const<IndexType>::type;\n\t\tI mnnz = 0;\n\t\tfor (size_t row_id = 1; row_id < row_ptrs_.size(); ++row_id) {\n\t\t\tmnnz = std::max(row_ptrs_[row_id] - row_ptrs_[row_id - 1], mnnz);\n\t\t}\n\t\treturn mnnz;\n\t}\n\n   private:\n\tgsl_lite::span<DataType> values_;\n\tgsl_lite::span<IndexType> col_indices_;\n\tgsl_lite::span<IndexType> row_ptrs_;\n\tsize_t num_cols_;\n};\n\n} // namespace thrustshift\n", "meta": {"hexsha": "d064a6bb6693c859824ce85278b722782f1ea793", "size": 8829, "ext": "h", "lang": "C", "max_stars_repo_path": "include/thrustshift/CSR.h", "max_stars_repo_name": "codecircuit/thrustshift", "max_stars_repo_head_hexsha": "533ed68f6aa201f54b9622dcaa203fdf6844b466", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-16T13:01:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T13:01:46.000Z", "max_issues_repo_path": "include/thrustshift/CSR.h", "max_issues_repo_name": "codecircuit/thrustshift", "max_issues_repo_head_hexsha": "533ed68f6aa201f54b9622dcaa203fdf6844b466", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-23T14:12:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-17T11:40:04.000Z", "max_forks_repo_path": "include/thrustshift/CSR.h", "max_forks_repo_name": "codecircuit/thrustshift", "max_forks_repo_head_hexsha": "533ed68f6aa201f54b9622dcaa203fdf6844b466", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8529411765, "max_line_length": 86, "alphanum_fraction": 0.6658738249, "num_tokens": 2337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.048136769751103675, "lm_q1q2_score": 0.0236923469634169}}
{"text": "static char help[] = \"This code implements the distribution federate of the T-D power flow use-case. A global convergence for the federation is implemented in this use-case. The The distribution federate obtains the upstream distribution substation voltage from transmission federate, solves power flow, and sends the updated injection into transmission. This code does not use HELICS iterative API\\n\\n\";\n\n#include <petsc.h>\n#include <ValueFederate.h>\n#include <opendss.h>\n#include <complex.h>\n\ntypedef struct {\n  helics_federate vfed;\n  helics_publication pub;\n  helics_subscription sub;\n  helics_time_t currenttime;\n  helics_iteration_status currenttimeiter;\n  char       pub_topic[PETSC_MAX_PATH_LEN];\n} UserData;\n\nhelics_status CreateDistributionFederate(helics_federate *distfed,char* pub_topic)\n{\n  helics_federate_info_t fedinfo;\n  helics_status   status;\n  const char*    fedinitstring=\"--federates=1\";\n  helics_federate vfed;\n  char            fedname[PETSC_MAX_PATH_LEN];\n  PetscErrorCode ierr;\n  \n  /* Create Federate Info object that describes the federate properties */\n  fedinfo = helicsFederateInfoCreate();\n\n  ierr = PetscStrcpy(fedname,\"Distribution Federate \");CHKERRQ(ierr);\n  ierr = PetscStrcat(fedname,pub_topic);CHKERRQ(ierr);\n  /* Set Federate name */\n  status = helicsFederateInfoSetFederateName(fedinfo,fedname);\n\n  /* Set core type from string */\n  status = helicsFederateInfoSetCoreTypeFromString(fedinfo,\"zmq\");\n\n  /* Federate init string */\n  status = helicsFederateInfoSetCoreInitString(fedinfo,fedinitstring);\n\n  /* Set the message interval (timedelta) for federate. Note that\n     HELICS minimum message time interval is 1 ns and by default\n     it uses a time delta of 1 second. What is provided to the\n     setTimedelta routine is a multiplier for the default timedelta.\n  */\n  /* Set one second message interval */\n  status = helicsFederateInfoSetTimeDelta(fedinfo,1.0);\n\n  status = helicsFederateInfoSetLoggingLevel(fedinfo,1);\n\n  status = helicsFederateInfoSetMaxIterations(fedinfo,100);\n  /* Create value federate */\n  vfed = helicsCreateValueFederate(fedinfo);\n\n  *distfed = vfed;\n\n  return status;\n}\n\nint main(int argc,char **argv)\n{\n  PetscErrorCode ierr;\n  const char*    helicsversion;\n  UserData       user;\n  helics_status   status;\n  PetscBool      flg;\n  char           netfile[PETSC_MAX_PATH_LEN],dcommand[PETSC_MAX_PATH_LEN];\n  char           sub_topic[PETSC_MAX_PATH_LEN];\n  double complex *Stotal;\n  PetscInt      iter=0;\n  PetscScalar   Vm,Va;\n  PetscScalar   Pg,Qg,Pgprv,Qgprv;\n  PetscInt      pflowT_conv=0,pflowD_conv=0,global_conv=0;\n  char          pubstr[PETSC_MAX_PATH_LEN],substr[PETSC_MAX_PATH_LEN];\n  PetscInt      strlen;\n  PetscReal     tol=1E-6,mis;\n\n  \n  PetscInitialize(&argc,&argv,NULL,help);\n  \n  helicsversion = helicsGetVersion();\n\n  printf(\"D FED: Helics version = %s\\n\",helicsversion);\n\n  /* Get network data file from command line */\n  ierr = PetscOptionsGetString(NULL,NULL,\"-netfile\",netfile,PETSC_MAX_PATH_LEN,&flg);CHKERRQ(ierr);\n\n  ierr = PetscSNPrintf(dcommand,PETSC_MAX_PATH_LEN-1,\"Redirect \");CHKERRQ(ierr);\n  ierr = PetscStrcat(dcommand,netfile);CHKERRQ(ierr);\n\n  /* Load the D file */\n  ierr = OpenDSSRunCommand(dcommand);CHKERRQ(ierr);\n\n\n  flg = PETSC_FALSE;\n  /* Get the distribution topic for publication stream */\n  ierr = PetscOptionsGetString(NULL,NULL,\"-dtopic\",user.pub_topic,PETSC_MAX_PATH_LEN,&flg);CHKERRQ(ierr);\n  if(!flg) {\n    SETERRQ(PETSC_COMM_SELF,0,\"Need to specify the publication name, option -dtopic <topic_name>.\\n This is same as the distribution feeder file name without the extension\");\n  }\n\n    /* Create distribution federate */\n  status = CreateDistributionFederate(&user.vfed,user.pub_topic);\n  printf(\"Created D FEDERATE %s\\n\",user.pub_topic);\n\n  /* Register the publication */\n  user.pub = helicsFederateRegisterGlobalPublication(user.vfed,user.pub_topic,\"string\",\"\");\n  printf(\"D FEDERATE %s: Publication registered\\n\",user.pub_topic);\n\n  /* Subscribe to transmission federate's publication */\n  ierr = PetscStrcpy(sub_topic,\"Trans/\");\n  ierr = PetscStrcat(sub_topic,user.pub_topic);\n  user.sub = helicsFederateRegisterSubscription(user.vfed,sub_topic,\"string\",\"\");\n  printf(\"D FEDERATE %s: Subscription registered\\n\",user.pub_topic);\n\n  status = helicsFederateEnterInitializationMode(user.vfed);\n  printf(\"D FEDERATE %s: Entered initialization mode\\n\",user.pub_topic);\n\n  user.currenttime = 0.0;\n  user.currenttimeiter = iterating;\n\n  PetscInt solve;\n  /* Solve power flow */\n  //  printf(\"D FEDERATE %s running power flow\\n\",user.pub_topic);\n  ierr = OpenDSSSolutionGetSolve(&solve);CHKERRQ(ierr);\n\n  /* Send power injection to transmission */\n  /* Get the net injection at the boundary bus */\n  ierr = OpenDSSCircuitGetTotalPower(&Stotal);CHKERRQ(ierr);\n  Pgprv = -creal(Stotal[0])/1000.0; /* Conversion to MW */\n  Qgprv = -cimag(Stotal[0])/1000.0;\n\n  ierr = PetscSNPrintf(pubstr,PETSC_MAX_PATH_LEN-1,\"%18.16f,%18.16f,%d\",Pgprv,Qgprv,pflowD_conv);CHKERRQ(ierr);\n  status = helicsPublicationPublishString(user.pub,pubstr);\n  //  printf(\"D FEDERATE %s sent Pg = %4.3f, Qg = %4.3f, conv = %d from T FEDERATE\\n\",user.pub_topic,Pgprv,Qgprv,pflowD_conv);\n\n  status = helicsFederateEnterExecutionMode(user.vfed);\n  printf(\"D FEDERATE %s: Entered execution mode\\n\",user.pub_topic);\n    \n  while(user.currenttimeiter == iterating) {\n    iter++;\n\n    status = helicsSubscriptionGetString(user.sub,substr,PETSC_MAX_PATH_LEN-1,&strlen);\n    sscanf(substr,\"%lf,%lf,%d\",&Vm,&Va,&pflowT_conv);\n    //    printf(\"D FEDERATE %s received Vm = %4.3f, Va = %4.3f, conv = %d from T FEDERATE\\n\",user.pub_topic,Vm,Va,pflowT_conv);\n\n    global_conv = pflowT_conv & pflowD_conv;\n\n    if(global_conv) {\n      helicsFederateRequestTimeIterative(user.vfed,user.currenttime,no_iteration,&user.currenttime,&user.currenttimeiter);\n    } else {\n      /* Set source bus voltage */\n      ierr = OpenDSSVsourcesSetPU(Vm);CHKERRQ(ierr);\n      ierr = OpenDSSVsourcesSetAngleDeg(Va);CHKERRQ(ierr);\n\n      /* 2. Solve power flow */\n      //      printf(\"D FEDERATE %s running power flow\\n\",user.pub_topic);\n      ierr = OpenDSSSolutionGetSolve(&solve);CHKERRQ(ierr);\n\n      /* Send power injection to transmission */    \n      /* Get the net injection at the boundary bus */\n      ierr = OpenDSSCircuitGetTotalPower(&Stotal);CHKERRQ(ierr);\n      Pg = -creal(Stotal[0])/1000.0; /* Conversion to MW */\n      Qg = -cimag(Stotal[0])/1000.0;\n\n      mis = PetscSqrtScalar((Pg-Pgprv)/100*(Pg-Pgprv)/100 + (Qg-Qgprv)/100*(Qg-Qgprv)/100); /* Divide by 100 for conversion to pu */\n      if(mis < tol) {\n\tpflowD_conv = 1;\n      } else {\n\tpflowD_conv = 0;\n\tPgprv = Pg;\n\tQgprv = Qg;\n      }\n      ierr = PetscSNPrintf(pubstr,PETSC_MAX_PATH_LEN-1,\"%18.16f,%18.16f,%d\",Pg,Qg,pflowD_conv);CHKERRQ(ierr);\n      status = helicsPublicationPublishString(user.pub,pubstr);\n      //      printf(\"D FEDERATE %s sent Pg = %4.3f, Qg = %4.3f, conv = %d to T FEDERATE\\n\",user.pub_topic,Pg,Qg,pflowD_conv);\n    \n      fflush(NULL);\n\n      /*3. Publish Pg, Qg, and convergence status to transmission */\n      status = helicsFederateRequestTimeIterative(user.vfed,user.currenttime,force_iteration,&user.currenttime,&user.currenttimeiter);\n\n      printf(\"Iteration %d: D Federate %s mis = %g,converged = %d\\n\",iter,user.pub_topic,mis,pflowD_conv);\n\n    }\n    \n  }\n  \n  status = helicsFederateEnterExecutionModeComplete(user.vfed);\n  status = helicsFederateFinalize(user.vfed);\n\n  PetscFinalize();\n  return 0;\n}\n  \n", "meta": {"hexsha": "344b5a684604c3a31851f9b020ec6e6b8e39284c", "size": 7463, "ext": "c", "lang": "C", "max_stars_repo_path": "ANL-TD-Iterative-Pflow/pflow-helics-dist.c", "max_stars_repo_name": "GMLC-TDC/Use-Cases", "max_stars_repo_head_hexsha": "14d687fe04af731c1ee466e05acfd5813095660a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-04T07:27:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-04T07:27:34.000Z", "max_issues_repo_path": "ANL-TD-Iterative-Pflow/pflow-helics-dist.c", "max_issues_repo_name": "GMLC-TDC/Use-Cases", "max_issues_repo_head_hexsha": "14d687fe04af731c1ee466e05acfd5813095660a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ANL-TD-Iterative-Pflow/pflow-helics-dist.c", "max_forks_repo_name": "GMLC-TDC/Use-Cases", "max_forks_repo_head_hexsha": "14d687fe04af731c1ee466e05acfd5813095660a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-01T21:49:40.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-23T19:30:36.000Z", "avg_line_length": 38.2717948718, "max_line_length": 404, "alphanum_fraction": 0.7171378802, "num_tokens": 2117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769844, "lm_q2_score": 0.048857780007109594, "lm_q1q2_score": 0.02366573559743011}}
{"text": "#include <pygsl/solver.h>\n#include <gsl/gsl_min.h>\n\nstatic const char min_f_type_name[] = \"F-Minimizer\";\nstatic const char min_x_minimum_doc[]= \"\"; \t\nstatic const char min_x_lower_doc[]= \"\"; \t\nstatic const char min_x_upper_doc[]= \"\"; \t\nstatic const char min_f_minimum_doc[]= \"\"; \t\nstatic const char min_f_lower_doc[]= \"\"; \t\nstatic const char min_f_upper_doc[]= \"\"; \t\nstatic const char min_test_delta_doc[]= \"\"; \nstatic const char min_set_f_doc[]= \"\";\n \nstatic const char min_init_brent_doc[]= \"\"; \nstatic const char min_init_goldensection_doc[]= \"\"; \n\nconst char  * filename = __FILE__;\nPyObject *module = NULL;\n\nstatic PyObject* \nPyGSL_min_f_minimum(PyGSL_solver *self, PyObject *args) \n{\n     return PyGSL_solver_ret_double(self, args, (double_m_t) gsl_min_fminimizer_f_minimum);\n}\n\nstatic PyObject* \nPyGSL_min_f_lower(PyGSL_solver *self, PyObject *args) \n{\n     return PyGSL_solver_ret_double(self, args, (double_m_t) gsl_min_fminimizer_f_lower);\n}\n\nstatic PyObject* \nPyGSL_min_f_upper(PyGSL_solver *self, PyObject *args) \n{\n     return PyGSL_solver_ret_double(self, args, (double_m_t) gsl_min_fminimizer_f_upper);\n}\n\nstatic PyObject* \nPyGSL_min_x_minimum(PyGSL_solver *self, PyObject *args) \n{\n     return PyGSL_solver_ret_double(self, args, (double_m_t) gsl_min_fminimizer_x_minimum);\n}\n\nstatic PyObject* \nPyGSL_min_x_lower(PyGSL_solver *self, PyObject *args) \n{\n     return PyGSL_solver_ret_double(self, args, (double_m_t) gsl_min_fminimizer_x_lower);\n}\n\nstatic PyObject* \nPyGSL_min_x_upper(PyGSL_solver *self, PyObject *args) \n{\n     return PyGSL_solver_ret_double(self, args, (double_m_t) gsl_min_fminimizer_x_upper);\n}\n\nstatic PyObject*\nPyGSL_min_solver_test_interval(PyGSL_solver * self, PyObject *args)\n{\n     double epsabs, epsrel;\n     gsl_min_fminimizer *s = (gsl_min_fminimizer *) self->solver;\n     if(!PyArg_ParseTuple(args, \"dd\", &epsabs, &epsrel))\n\t  return NULL;\n     return PyInt_FromLong(gsl_min_test_interval(s->x_lower, s->x_upper, epsabs, epsrel));\n}\n\n\nstatic PyObject* \nPyGSL_min_set_f(PyGSL_solver *self, PyObject *args, PyObject *kw) \n{\n     return PyGSL_solver_set_f(self, args, kw,  (void *)gsl_min_fminimizer_set, 0); \n}\n\nstatic PyMethodDef PyGSL_min_fmethods[] = {     \n     {\"x_minimum\", (PyCFunction)PyGSL_min_x_minimum,  METH_NOARGS, (char *)min_x_minimum_doc}, \n     {\"x_lower\",   (PyCFunction)PyGSL_min_x_lower,    METH_NOARGS, (char *)min_x_lower_doc}, \n     {\"x_upper\",   (PyCFunction)PyGSL_min_x_upper,    METH_NOARGS, (char *)min_x_upper_doc}, \n     {\"f_minimum\", (PyCFunction)PyGSL_min_f_minimum,  METH_NOARGS, (char *)min_f_minimum_doc}, \n     {\"f_lower\",   (PyCFunction)PyGSL_min_f_lower,    METH_NOARGS, (char *)min_f_lower_doc}, \n     {\"f_upper\",   (PyCFunction)PyGSL_min_f_upper,    METH_NOARGS, (char *)min_f_upper_doc}, \n     {\"set\",       (PyCFunction)PyGSL_min_set_f,    METH_VARARGS|METH_KEYWORDS, (char *)min_set_f_doc}, \n     {\"test_interval\",(PyCFunction)PyGSL_min_solver_test_interval, METH_VARARGS, NULL},      \n     {NULL, NULL, 0, NULL}           /* sentinel */\n};\n\n\n\nconst struct _SolverStatic\nmin_solver_f = {{(void_m_t) gsl_min_fminimizer_free,   \n\t\t /* gsl_multimin_fminimizer_restart */  (void_m_t) NULL,\n\t\t (name_m_t) gsl_min_fminimizer_name,   \n\t\t (int_m_t) gsl_min_fminimizer_iterate},\n\t\t1, PyGSL_min_fmethods, min_f_type_name};\n\nstatic PyObject* \nPyGSL_min_f_init(PyObject *self, PyObject *args, \n\t\t const gsl_min_fminimizer_type * type) \n{\n\n     PyObject *tmp=NULL;\n     solver_alloc_struct s = {type, (void_an_t) gsl_min_fminimizer_alloc,\n\t\t\t      &min_solver_f};\n     FUNC_MESS_BEGIN();     \n     tmp = PyGSL_solver_dn_init(self, args, &s, 0);\n     FUNC_MESS_END();     \n     return tmp;\n}\n\n#define AMIN_F(name)                                                  \\\nstatic PyObject* PyGSL_min_init_ ## name (PyObject *self, PyObject *args)\\\n{                                                                             \\\n     PyObject *tmp = NULL;                                                    \\\n     FUNC_MESS_BEGIN();                                                       \\\n     tmp = PyGSL_min_f_init(self, args,  gsl_min_fminimizer_ ## name); \\\n     if (tmp == NULL){                                                        \\\n\t  PyGSL_add_traceback(module, __FILE__, __FUNCTION__, __LINE__); \\\n     }                                                                        \\\n     FUNC_MESS_END();                                                         \\\n     return tmp;                                                              \\\n}\nAMIN_F(brent)\nAMIN_F(goldensection)\n\nstatic PyObject*\nPyGSL_min_test_interval(PyObject * self, PyObject *args)\n{\n     double x_lower, x_upper, epsabs, epsrel;\n     if(!PyArg_ParseTuple(args, \"dddd\", &x_lower, &x_upper, &epsabs, &epsrel))\n\t  return NULL;\n     return PyInt_FromLong(gsl_min_test_interval(x_lower, x_upper, epsabs, epsrel));\n}\n\nstatic const char PyGSL_minimize_module_doc [] = \"XXX Missing \";\nstatic PyMethodDef mMethods[] = {\n     /* solvers */\n     {\"brent\",        PyGSL_min_init_brent, METH_NOARGS, (char *)min_init_brent_doc}, \n     {\"goldensection\",PyGSL_min_init_goldensection, METH_NOARGS, (char *)min_init_goldensection_doc}, \n     /* min methods */\n     {\"test_interval\",   PyGSL_min_test_interval, METH_VARARGS, (char *)min_test_delta_doc},\n     {NULL, NULL, 0, NULL}\n};\n\nvoid\ninitminimize(void)\n{\n     PyObject* m, *dict, *item;\n     FUNC_MESS_BEGIN();\n\n     m=Py_InitModule(\"minimize\", mMethods);\n     import_pygsl_solver();\n     assert(PyGSL_API);\n\n     module = m;\n     assert(m);\n     dict = PyModule_GetDict(m);\n     if(!dict)\n\t  goto fail;\n\n     if (!(item = PyString_FromString((char*)PyGSL_minimize_module_doc))){\n\t  PyErr_SetString(PyExc_ImportError, \n\t\t\t  \"I could not generate module doc string!\");\n\t  goto fail;\n     }\n\n     if (PyDict_SetItemString(dict, \"__doc__\", item) != 0){\n\t  PyErr_SetString(PyExc_ImportError, \n\t\t\t  \"I could not init doc string!\");\n\t  goto fail;\n     }\n     \n     FUNC_MESS_END();\n\n fail:\n     FUNC_MESS(\"FAIL\");\n     return;\n}\n", "meta": {"hexsha": "20c27d35c82a8c722eb47264317c33b41875587a", "size": 6003, "ext": "c", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/testing/src/solvers/minimize.c", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/testing/src/solvers/minimize.c", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/testing/src/solvers/minimize.c", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 34.1079545455, "max_line_length": 104, "alphanum_fraction": 0.6491754123, "num_tokens": 1617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926197162523, "lm_q2_score": 0.05261894963358463, "lm_q1q2_score": 0.02364656762255413}}
{"text": "/* Copyright 2016 by\n\n  Laboratoire d'Informatique de Paris 6 - \u00c9quipe PEQUAN\n  Sorbonne Universit\u00e9s\n  UPMC Univ Paris 06\n  UMR 7606, LIP6\n  4, place Jussieu\n  F-75252 Paris Cedex 05\n  France\n\n  Laboratoire d'Informatique de Paris 6, equipe PEQUAN,\n  UPMC Universite Paris 06 - CNRS - UMR 7606 - LIP6, Paris, France\n\n  Contributors:\n  Anastasia Volkova anastasia.volkova@lip6.fr\n\n\n  This software is a mathematical library whose purpose is to provide\n  functions to compute the Worst-Case Peak Gain measure of Linear\n  Time-Invariant Digital Filters.\n\n  This software is governed by the CeCILL-C license under French law and\n  abiding by the rules of distribution of free software.  You can  use,\n  modify and/ or redistribute the software under the terms of the CeCILL-C\n  license as circulated by CEA, CNRS and INRIA at the following URL\n  \"http://www.cecill.info\".\n\n  As a counterpart to the access to the source code and  rights to copy,\n  modify and redistribute granted by the license, users are provided only\n  with a limited warranty  and the software's author,  the holder of the\n  economic rights,  and the successive licensors  have only  limited\n  liability.\n\n  In this respect, the user's attention is drawn to the risks associated\n  with loading,  using,  modifying and/or developing or reproducing the\n  software by the user in light of its specific status of free software,\n  that may mean  that it is complicated to manipulate,  and  that  also\n  therefore means  that it is reserved for developers  and  experienced\n  professionals having in-depth computer knowledge. Users are therefore\n  encouraged to load and test the software's suitability as regards their\n  requirements in conditions enabling the security of their systems and/or\n  data to be ensured and,  more generally, to use and operate it in the\n  same conditions as regards security.\n\n  The fact that you are presently reading this means that you have had\n  knowledge of the CeCILL-C license and that you accept its terms.\n\n  This program is distributed WITHOUT ANY WARRANTY; without even the\n  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n\n */\n\n#ifndef SRC_LIB_CLAPACK_FUNCTIONS_CONFIG_H_\n#define SRC_LIB_CLAPACK_FUNCTIONS_CONFIG_H_\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#include <stdlib.h>\n#include \"config.h\"\n#include \"aux_funcs.h\"\n\n\n#include <f2c.h>\n\n#ifdef CLAPACK_HEADER\n\t#include <clapack.h>\n#endif\n\n#ifdef LAPACK_HEADER\n\t#include <lapack.h>\n#endif\n\n#ifdef LAPACKE_HEADER\n\t#include <lapacke.h>\n#endif\n\n#ifdef BLAS_HEADER\n\t#include <blas.h>\n#endif\n\n#ifdef CBLAS_HEADER\n\t#include <cblas.h>\n#endif\n\n#ifdef BLASWRAP_HEADER\n\t#include <blaswrap.h>\n#endif\n \n#include <complex.h>\ntypedef struct complexdouble\n{\n\tdouble r;\n\tdouble i;\n}complexdouble;\n\n#define doublereal double\n#define lapack_int int\n#define integer long int \n#define lapacke_complex double _Complex\n\n\n\n\nvoid my_zgetrf(int *m, int *n, complexdouble *A,\n \tint *lda, int *ipiv, int *info);\n\nvoid my_zgetri(int *n, complexdouble *A, int *lda,\n\t\tint *ipiv, complexdouble *work, int *lwork, int *info);\nvoid my_dgeevx(int* n, double *A, int* lda, double *wr, double *wi, double *vl,  \n\t       int* ldvl, double *vr, int* ldvr, int *ilo, int *ihi,  \n\t       double *scale, double *abnrm, double *rconde, double *rcondv,  \n\t       double *work, int *lwork, long int *iwork, int *info);\n\n\n#ifdef __cplusplus\n}\n#endif\n\n\n#endif /* SRC_LIB_CLAPACK_FUNCTIONS_CONFIG_H_ */\n", "meta": {"hexsha": "7e9796212ffbed357d1aeb8637e7dba8eea1e2fb", "size": 3438, "ext": "h", "lang": "C", "max_stars_repo_path": "WCPG/clapack_functions_config.h", "max_stars_repo_name": "remi-garcia/WCPG", "max_stars_repo_head_hexsha": "b90253a4a6a650300454f5656a7e8410e0493175", "max_stars_repo_licenses": ["CECILL-B"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "WCPG/clapack_functions_config.h", "max_issues_repo_name": "remi-garcia/WCPG", "max_issues_repo_head_hexsha": "b90253a4a6a650300454f5656a7e8410e0493175", "max_issues_repo_licenses": ["CECILL-B"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-08-16T00:47:20.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-16T00:47:56.000Z", "max_forks_repo_path": "WCPG/clapack_functions_config.h", "max_forks_repo_name": "remi-garcia/WCPG", "max_forks_repo_head_hexsha": "b90253a4a6a650300454f5656a7e8410e0493175", "max_forks_repo_licenses": ["CECILL-B"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-07-09T22:20:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-20T10:25:37.000Z", "avg_line_length": 27.7258064516, "max_line_length": 81, "alphanum_fraction": 0.7510180337, "num_tokens": 903, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657966593214324, "lm_q2_score": 0.0495890264954869, "lm_q1q2_score": 0.02363312168111935}}
{"text": "/**\n * @file lapacke.h\n * @brief Header file to automatically handle Intel MKL or LAPACKE includes.\n * \n * `npypacke` can be linked with a reference LAPACKE implementation, OpenBLAS,\n * or Intel MKL, but Intel MKL uses a different header file, `mkl.h`, while\n * OpenBLAS uses the LAPACKE header `lapacke.h`. This file includes the correct\n * header file given an appropriate preprocessor macro is defined and defines\n * some types appropriately so that the user can simply write in terms of the\n * Intel MKL interface, whether or not Intel MKL is actually linked.\n */\n\n#ifndef NPY_LPK_LAPACKE_H\n#define NPY_LPK_LAPACKE_H\n// if linking with Netlib LAPACKE\n#if defined(LAPACKE_INCLUDE)\n#include <lapacke.h>\n// define MKL_INT used in extension modules as in mkl.h\n#ifndef MKL_INT\n#define MKL_INT int\n#endif /* MKL_INT */\n// else if linking with OpenBLAS CBLAS\n#elif defined(OPENBLAS_INCLUDE)\n#include <complex.h>\n#include <lapacke.h>\n// OpenBLAS has blasint typedef, so define MKL_INT using blasint. for LAPACKE\n// routines, should cast to lapack_int (same size as blasint in OpenBLAS)\n#ifndef MKL_INT\n#define MKL_INT blasint\n#endif /* MKL_INT */\n// else if linking with Intel MKL LAPACKE implementation\n#elif defined(MKL_INCLUDE)\n#include <mkl.h>\n// else error, no LAPACKE includes specified\n#else\n// silence error squiggles in VS Code (__INTELLISENSE__ always defined)\n#ifndef __INTELLISENSE__\n#error \"no LAPACKE includes specified. try -D(LAPACKE|OPENBLAS|MKL)_INCLUDE\"\n#endif /* __INTELLISENSE__ */\n#endif\n\n// silence error squiggles in VS Code. use mkl.h since it also define MKL types\n#ifdef __INTELLISENSE__\n#include <mkl.h>\n#endif /* __INTELLISENSE__ */\n\n#endif /* NPY_LPK_LAPACKE_H */", "meta": {"hexsha": "cb8f60e00f70ced77061e06ef2f767df3d3f2a78", "size": 1690, "ext": "h", "lang": "C", "max_stars_repo_path": "npypacke/include/npypacke/lapacke.h", "max_stars_repo_name": "phetdam/npy_openblas_demo", "max_stars_repo_head_hexsha": "ff5f9932b19f82162bc0d9d46b341d42805f942b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-16T00:59:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-16T00:59:11.000Z", "max_issues_repo_path": "npypacke/include/npypacke/lapacke.h", "max_issues_repo_name": "phetdam/numpy-lapacke-demo", "max_issues_repo_head_hexsha": "ff5f9932b19f82162bc0d9d46b341d42805f942b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "npypacke/include/npypacke/lapacke.h", "max_forks_repo_name": "phetdam/numpy-lapacke-demo", "max_forks_repo_head_hexsha": "ff5f9932b19f82162bc0d9d46b341d42805f942b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.9574468085, "max_line_length": 79, "alphanum_fraction": 0.7668639053, "num_tokens": 475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.053403324150263734, "lm_q1q2_score": 0.023586806689929272}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdarg.h>\n#include <math.h>\n#include <string.h>\n\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_odeiv.h>\n#include <gsl/gsl_spline.h>\n#include <gsl/gsl_integration.h>\n\n#include \"ccl.h\"\n#include \"ccl_params.h\"\n\n//\n// Macros for replacing relative paths\n#define EXPAND_STR(s) STRING(s)\n#define STRING(s) #s\n\n\nconst ccl_configuration default_config = {ccl_boltzmann_class, ccl_halofit, ccl_nobaryons, ccl_tinker10, ccl_duffy2008, ccl_emu_strict};\n\nconst ccl_gsl_params default_gsl_params = {GSL_EPSREL,                          // EPSREL\n                                           GSL_N_ITERATION,                     // N_ITERATION\n                                           GSL_INTEGRATION_GAUSS_KRONROD_POINTS,// INTEGRATION_GAUSS_KRONROD_POINTS\n                                           GSL_EPSREL,                          // INTEGRATION_EPSREL\n                                           GSL_INTEGRATION_GAUSS_KRONROD_POINTS,// INTEGRATION_LIMBER_GAUSS_KRONROD_POINTS\n                                           GSL_EPSREL,                          // INTEGRATION_LIMBER_EPSREL\n                                           GSL_EPSREL_DIST,                     // INTEGRATION_DISTANCE_EPSREL\n                                           GSL_EPSREL_DNDZ,                     // INTEGRATION_DNDZ_EPSREL\n                                           GSL_EPSREL_SIGMAR,                   // INTEGRATION_SIGMAR_EPSREL\n                                           GSL_EPSREL_NU,                       // INTEGRATION_NU_EPSREL\n                                           GSL_EPSABS_NU,                       // INTEGRATION_NU_EPSABS\n                                           GSL_EPSREL,                          // ROOT_EPSREL\n                                           GSL_N_ITERATION,                     // ROOT_N_ITERATION\n                                           GSL_EPSREL_GROWTH                    // ODE_GROWTH_EPSREL\n                                          };\n\n/* ------- ROUTINE: ccl_cosmology_read_config ------\n   INPUTS: none, but will look for ini file in include/ dir\n   TASK: fill out global variables of splines with user defined input.\n   The variables are defined in ccl_params.h.\n\n   The following are the relevant global variables:\n*/\n\nccl_spline_params * ccl_splines=NULL; // Global variable\nccl_gsl_params * ccl_gsl=NULL; // Global variable\n\nvoid ccl_cosmology_read_config(void)\n{\n\n  int CONFIG_LINE_BUFFER_SIZE=100;\n  int MAX_CONFIG_VAR_LEN=100;\n  FILE *fconfig;\n  char buf[CONFIG_LINE_BUFFER_SIZE];\n  char var_name[MAX_CONFIG_VAR_LEN];\n  char* rtn;\n  double var_dbl;\n\n  // Get parameter .ini filename from environment variable or default location\n  const char* param_file;\n  const char* param_file_env = getenv(\"CCL_PARAM_FILE\");\n  if (param_file_env != NULL) {\n    param_file = param_file_env;\n  }\n  else {\n    // Use default ini file\n    param_file = EXPAND_STR(__CCL_DATA_DIR__) \"/ccl_params.ini\";\n  }\n  if ((fconfig=fopen(param_file, \"r\")) == NULL) {\n    ccl_raise_exception(CCL_ERROR_MISSING_CONFIG_FILE, \"ccl_core.c: Failed to open config file: %s\", param_file);\n    return;\n  }\n\n  if(ccl_splines == NULL) {\n    ccl_splines = malloc(sizeof(ccl_spline_params));\n  }\n  if(ccl_gsl == NULL) {\n    ccl_gsl = malloc(sizeof(ccl_gsl_params));\n    memcpy(ccl_gsl, &default_gsl_params, sizeof(ccl_gsl_params));\n  }\n\n  /* Exit gracefully if we couldn't allocate memory */\n  if(ccl_splines==NULL || ccl_gsl==NULL) {\n    ccl_raise_exception(CCL_ERROR_MEMORY, \"ccl_core.c: Failed to allocate memory for config file data.\");\n    return;\n  }\n\n#define MATCH(s, action) if (0 == strcmp(var_name, s)) { action ; continue;} do{} while(0)\n\n  int lineno = 0;\n  while(! feof(fconfig)) {\n    rtn = fgets(buf, CONFIG_LINE_BUFFER_SIZE, fconfig);\n    lineno ++;\n\n    if (buf[0]==';' || buf[0]=='[' || buf[0]=='\\n') {\n      continue;\n    }\n    else {\n      sscanf(buf, \"%99[^=]=%le\\n\",var_name, &var_dbl);\n\n      // Spline parameters\n      MATCH(\"A_SPLINE_NA\", ccl_splines->A_SPLINE_NA=(int) var_dbl);\n      MATCH(\"A_SPLINE_NLOG\", ccl_splines->A_SPLINE_NLOG=(int) var_dbl);\n      MATCH(\"A_SPLINE_MINLOG\", ccl_splines->A_SPLINE_MINLOG=var_dbl);\n      MATCH(\"A_SPLINE_MIN\", ccl_splines->A_SPLINE_MIN=var_dbl);\n      MATCH(\"A_SPLINE_MINLOG_PK\", ccl_splines->A_SPLINE_MINLOG_PK=var_dbl);\n      MATCH(\"A_SPLINE_MIN_PK\", ccl_splines->A_SPLINE_MIN_PK=var_dbl);\n      MATCH(\"A_SPLINE_MAX\", ccl_splines->A_SPLINE_MAX=var_dbl);\n      MATCH(\"LOGM_SPLINE_DELTA\", ccl_splines->LOGM_SPLINE_DELTA=var_dbl);\n      MATCH(\"LOGM_SPLINE_NM\", ccl_splines->LOGM_SPLINE_NM=(int) var_dbl);\n      MATCH(\"LOGM_SPLINE_MIN\", ccl_splines->LOGM_SPLINE_MIN=var_dbl);\n      MATCH(\"LOGM_SPLINE_MAX\", ccl_splines->LOGM_SPLINE_MAX=var_dbl);\n      MATCH(\"A_SPLINE_NA_PK\", ccl_splines->A_SPLINE_NA_PK=(int) var_dbl);\n      MATCH(\"A_SPLINE_NLOG_PK\", ccl_splines->A_SPLINE_NLOG_PK=(int) var_dbl);\n      MATCH(\"K_MAX_SPLINE\", ccl_splines->K_MAX_SPLINE=var_dbl);\n      MATCH(\"K_MAX\", ccl_splines->K_MAX=var_dbl);\n      MATCH(\"K_MIN\", ccl_splines->K_MIN=var_dbl);\n      MATCH(\"N_K\", ccl_splines->N_K=(int) var_dbl);\n\n      // 3dcorr parameters\n      MATCH(\"N_K_3DCOR\", ccl_splines->N_K_3DCOR=(int) var_dbl);\n\n      // GSL parameters\n      MATCH(\"GSL_EPSREL\", ccl_gsl->EPSREL=var_dbl);\n      MATCH(\"GSL_N_ITERATION\", ccl_gsl->N_ITERATION=(size_t) var_dbl);\n      MATCH(\"GSL_INTEGRATION_GAUSS_KRONROD_POINTS\", ccl_gsl->INTEGRATION_GAUSS_KRONROD_POINTS=(int) var_dbl);\n      MATCH(\"GSL_INTEGRATION_EPSREL\", ccl_gsl->INTEGRATION_EPSREL=var_dbl);\n      MATCH(\"GSL_INTEGRATION_DISTANCE_EPSREL\", ccl_gsl->INTEGRATION_DISTANCE_EPSREL=var_dbl);\n      MATCH(\"GSL_INTEGRATION_DNDZ_EPSREL\", ccl_gsl->INTEGRATION_DNDZ_EPSREL=var_dbl);\n      MATCH(\"GSL_INTEGRATION_SIGMAR_EPSREL\", ccl_gsl->INTEGRATION_SIGMAR_EPSREL=var_dbl);\n      MATCH(\"GSL_INTEGRATION_NU_EPSREL\", ccl_gsl->INTEGRATION_NU_EPSREL=var_dbl);\n      MATCH(\"GSL_INTEGRATION_NU_EPSABS\", ccl_gsl->INTEGRATION_NU_EPSABS=var_dbl);\n      MATCH(\"GSL_INTEGRATION_LIMBER_GAUSS_KRONROD_POINTS\", ccl_gsl->INTEGRATION_LIMBER_GAUSS_KRONROD_POINTS=(int) var_dbl);\n      MATCH(\"GSL_INTEGRATION_LIMBER_EPSREL\", ccl_gsl->INTEGRATION_LIMBER_EPSREL=var_dbl);\n      MATCH(\"GSL_ROOT_EPSREL\", ccl_gsl->ROOT_EPSREL=var_dbl);\n      MATCH(\"GSL_ROOT_N_ITERATION\", ccl_gsl->ROOT_N_ITERATION=(int) var_dbl);\n      MATCH(\"GSL_ODE_GROWTH_EPSREL\", ccl_gsl->ODE_GROWTH_EPSREL=var_dbl);\n\n      ccl_raise_exception(CCL_ERROR_MISSING_CONFIG_FILE, \"ccl_core.c: Failed to parse config file at line %d: %s\", lineno, buf);\n    }\n  }\n#undef MATCH\n\n  fclose(fconfig);\n}\n\n\n/* ------- ROUTINE: ccl_cosmology_create ------\nINPUTS: ccl_parameters params\n        ccl_configuration config\nTASK: creates the ccl_cosmology struct and passes some values to it\nDEFINITIONS:\nchi: comoving distance [Mpc]\ngrowth: growth function (density)\nfgrowth: logarithmic derivative of the growth (density) (dlnD/da?)\nE: E(a)=H(a)/H0\naccelerator: interpolation accelerator for functions of a\naccelerator_achi: interpolation accelerator for functions of chi\ngrowth0: growth at z=0, defined to be 1\nsigma: ?\np_lin: linear matter power spectrum at z=0?\np_lnl: nonlinear matter power spectrum at z=0?\ncomputed_distances, computed_growth,\ncomputed_power, computed_sigma: store status of the computations\n*/\nccl_cosmology * ccl_cosmology_create(ccl_parameters params, ccl_configuration config)\n{\n  ccl_cosmology * cosmo = malloc(sizeof(ccl_cosmology));\n  cosmo->params = params;\n  cosmo->config = config;\n\n  cosmo->data.chi = NULL;\n  cosmo->data.growth = NULL;\n  cosmo->data.fgrowth = NULL;\n  cosmo->data.E = NULL;\n  cosmo->data.accelerator=NULL;\n  cosmo->data.accelerator_achi=NULL;\n  cosmo->data.accelerator_m=NULL;\n  cosmo->data.accelerator_d=NULL;\n  cosmo->data.accelerator_k=NULL;\n  cosmo->data.growth0 = 1.;\n  cosmo->data.achi=NULL;\n\n  cosmo->data.logsigma = NULL;\n  cosmo->data.dlnsigma_dlogm = NULL;\n\n  // hmf parameter for interpolation\n  cosmo->data.alphahmf = NULL;\n  cosmo->data.betahmf = NULL;\n  cosmo->data.gammahmf = NULL;\n  cosmo->data.phihmf = NULL;\n  cosmo->data.etahmf = NULL;\n\n  cosmo->data.p_lin = NULL;\n  cosmo->data.p_nl = NULL;\n  //cosmo->data.nu_pspace_int = NULL;\n  cosmo->computed_distances = false;\n  cosmo->computed_growth = false;\n  cosmo->computed_power = false;\n  cosmo->computed_sigma = false;\n  cosmo->computed_hmfparams = false;\n  cosmo->status = 0;\n  ccl_cosmology_set_status_message(cosmo, \"\");\n\n  return cosmo;\n}\n\n/* ------ ROUTINE: ccl_parameters_fill_initial -------\nINPUT: ccl_parameters: params\nTASK: fill parameters not set by ccl_parameters_create with some initial values\nDEFINITIONS:\nOmega_g = (Omega_g*h^2)/h^2 is the radiation parameter; \"g\" is for photons, as in CLASS\nT_CMB: CMB temperature in Kelvin\nOmega_l: Lambda\nA_s: amplitude of the primordial PS, enforced here to initially set to NaN\nsigma8: variance in 8 Mpc/h spheres for normalization of matter PS, enforced here to initially set to NaN\nz_star: recombination redshift\n */\nvoid ccl_parameters_fill_initial(ccl_parameters * params, int *status)\n{\n  // Fixed radiation parameters\n  // Omega_g * h**2 is known from T_CMB\n  params->T_CMB =  TCMB;\n  // kg / m^3\n  double rho_g = 4. * STBOLTZ / pow(CLIGHT, 3) * pow(params->T_CMB, 4);\n  // kg / m^3\n  double rho_crit = RHO_CRITICAL * SOLAR_MASS/pow(MPC_TO_METER, 3) * pow(params->h, 2);\n  params->Omega_g = rho_g/rho_crit;\n\n  // Get the N_nu_rel from Neff and N_nu_mass\n  params->N_nu_rel = params->Neff - params->N_nu_mass * pow(TNCDM, 4) / pow(4./11.,4./3.);\n\n  // Temperature of the relativistic neutrinos in K\n  double T_nu= (params->T_CMB) * pow(4./11.,1./3.);\n  // in kg / m^3\n  double rho_nu_rel = params->N_nu_rel* 7.0/8.0 * 4. * STBOLTZ / pow(CLIGHT, 3) * pow(T_nu, 4);\n  params-> Omega_n_rel = rho_nu_rel/rho_crit;\n\n  // If non-relativistic neutrinos are present, calculate the phase_space integral.\n  if((params->N_nu_mass)>0) {\n    // Pass NULL for the accelerator here because we don't have our cosmology object defined yet.\n    params->Omega_n_mass = ccl_Omeganuh2(1.0, params->N_nu_mass, params->mnu, params->T_CMB, NULL, status) / ((params->h)*(params->h));\n    ccl_check_status_nocosmo(status);\n  }\n  else{\n    params->Omega_n_mass = 0.;\n  }\n\n  params->Omega_m = params->Omega_b + params-> Omega_c;\n  params->Omega_l = 1.0 - params->Omega_m - params->Omega_g - params->Omega_n_rel -params->Omega_n_mass- params->Omega_k;\n  // Initially undetermined parameters - set to nan to trigger\n  // problems if they are mistakenly used.\n  if (isfinite(params->A_s)) {params->sigma8 = NAN;}\n  if (isfinite(params->sigma8)) {params->A_s = NAN;}\n  params->z_star = NAN;\n\n  if(fabs(params->Omega_k)<1E-6)\n    params->k_sign=0;\n  else if(params->Omega_k>0)\n    params->k_sign=-1;\n  else\n    params->k_sign=1;\n  params->sqrtk=sqrt(fabs(params->Omega_k))*params->h/CLIGHT_HMPC;\n}\n\n\n/* ------ ROUTINE: ccl_parameters_create -------\nINPUT: numbers for the basic cosmological parameters needed by CCL\nTASK: fill params with some initial values provided by the user\nDEFINITIONS:\nOmega_c: cold dark matter\nOmega_b: baryons\nOmega_m: matter\nOmega_k: curvature\nlittle omega_x means Omega_x*h^2\nNeff : Effective number of neutrino speces\nmnu : Pointer to either sum of neutrino masses or list of three masses.\nmnu_type : how the neutrino mass(es) should be treated\nw0: Dark energy eq of state parameter\nwa: Dark energy eq of state parameter, time variation\nH0: Hubble's constant in km/s/Mpc.\nh: Hubble's constant divided by (100 km/s/Mpc).\nA_s: amplitude of the primordial PS\nn_s: index of the primordial PS\n\n */\nccl_parameters ccl_parameters_create(\n                     double Omega_c, double Omega_b, double Omega_k,\n\t\t\t\t     double Neff, double* mnu, ccl_mnu_convention mnu_type,\n\t\t\t\t     double w0, double wa, double h, double norm_pk,\n\t\t\t\t     double n_s, double bcm_log10Mc, double bcm_etab,\n\t\t\t\t     double bcm_ks, int nz_mgrowth, double *zarr_mgrowth,\n\t\t\t\t     double *dfarr_mgrowth, int *status)\n{\n  #ifndef USE_GSL_ERROR\n    gsl_set_error_handler_off ();\n  #endif\n\n  ccl_parameters params;\n  // Initialize params\n  params.mnu = NULL;\n  params.z_mgrowth=NULL;\n  params.df_mgrowth=NULL;\n  params.sigma8 = NAN;\n  params.A_s = NAN;\n  params.Omega_c = Omega_c;\n  params.Omega_b = Omega_b;\n  params.Omega_k = Omega_k;\n  params.Neff = Neff;\n\n  // Set the sum of neutrino masses\n  params.sum_nu_masses = *mnu;\n  double mnusum = *mnu;\n  double *mnu_in = NULL;\n\n  /* Check whether ccl_splines and ccl_gsl exist. If either is not set yet, load\n     parameters from the config file. */\n  if(ccl_splines==NULL || ccl_gsl==NULL) {\n    ccl_cosmology_read_config();\n  }\n\n  // Decide how to split sum of neutrino masses between 3 neutrinos. We use\n  // a Newton's rule numerical solution (thanks M. Jarvis).\n\n  if (mnu_type==ccl_mnu_sum){\n\t  // Normal hierarchy\n\n\t  mnu_in = malloc(3*sizeof(double));\n\n\t  // Check if the sum is zero\n\t  if (*mnu<1e-15){\n\t\t  mnu_in[0] = 0.;\n\t\t  mnu_in[1] = 0.;\n\t\t  mnu_in[2] = 0.;\n\t  } else{\n\n\t      mnu_in[0] = 0.; // This is a starting guess.\n\n\t      double sum_check;\n\t      // Check that sum is consistent\n\t      mnu_in[1] = sqrt(DELTAM12_sq);\n\t      mnu_in[2] = sqrt(DELTAM13_sq_pos);\n\t      sum_check = mnu_in[0] + mnu_in[1] + mnu_in[2];\n\t      if (ccl_mnu_sum < sum_check){\n\t\t      *status = CCL_ERROR_MNU_UNPHYSICAL;\n          }\n\n          double dsdm1;\n          // This is the Newton's method\n          while (fabs(*mnu - sum_check) > 1e-15){\n\n              dsdm1 = 1. + mnu_in[0] / mnu_in[1] + mnu_in[0] / mnu_in[2];\n              mnu_in[0] = mnu_in[0] - (sum_check - *mnu) / dsdm1;\n              mnu_in[1] = sqrt(mnu_in[0]*mnu_in[0] + DELTAM12_sq);\n              mnu_in[2] = sqrt(mnu_in[0]*mnu_in[0] + DELTAM13_sq_pos);\n              sum_check = mnu_in[0] + mnu_in[1] + mnu_in[2];\n          }\n\t  }\n\n  } else if (mnu_type==ccl_mnu_sum_inverted){\n\t  // Inverted hierarchy\n\n\t  mnu_in = malloc(3*sizeof(double));\n\n\t  \t  // Check if the sum is zero\n\t  if (*mnu<1e-15){\n\t\t  mnu_in[0] = 0.;\n\t\t  mnu_in[1] = 0.;\n\t\t  mnu_in[2] = 0.;\n\t  } else{\n\n\t      mnu_in[0] = 0.; // This is a starting guess.\n\n\t      double sum_check;\n\t      // Check that sum is consistent\n\t      mnu_in[1] = sqrt(-1.* DELTAM13_sq_neg - DELTAM12_sq);\n\t      mnu_in[2] = sqrt(-1.* DELTAM13_sq_neg);\n\t      sum_check = mnu_in[0] + mnu_in[1] + mnu_in[2];\n\t      if (ccl_mnu_sum < sum_check){\n\t\t      *status = CCL_ERROR_MNU_UNPHYSICAL;\n          }\n\n\n          double dsdm1;\n          // This is the Newton's method\n          while (fabs(*mnu- sum_check) > 1e-15){\n              dsdm1 = 1. + (mnu_in[0] / mnu_in[1]) + (mnu_in[0] / mnu_in[2]);\n              mnu_in[0] = mnu_in[0] - (sum_check - *mnu) / dsdm1;\n              mnu_in[1] = sqrt(mnu_in[0]*mnu_in[0] + DELTAM12_sq);\n              mnu_in[2] = sqrt(mnu_in[0]*mnu_in[0] + DELTAM13_sq_neg);\n              sum_check = mnu_in[0] + mnu_in[1] + mnu_in[2];\n          }\n\n      }\n\n  } else if (mnu_type==ccl_mnu_sum_equal){\n\t    // Split the sum of masses equally\n\t    mnu_in = malloc(3*sizeof(double));\n\t    mnu_in[0] = params.sum_nu_masses / 3.;\n\t    mnu_in[1] = params.sum_nu_masses / 3.;\n\t    mnu_in[2] = params.sum_nu_masses / 3.;\n  } else if (mnu_type == ccl_mnu_list){\n      // A list of neutrino masses was already passed in\n\t  params.sum_nu_masses = mnu[0] + mnu[1] + mnu[2];\n\t  mnu_in = malloc(3*sizeof(double));\n\t  for(int i=0; i<3; i++) mnu_in[i] = mnu[i];\n  } else {\n\t  *status = CCL_ERROR_NOT_IMPLEMENTED;\n  }\n  // Check for errors in the neutrino set up (e.g. unphysical mnu)\n  ccl_check_status_nocosmo(status);\n\n  // Check which of the neutrino species are non-relativistic today\n  int N_nu_mass = 0;\n  for(int i = 0; i<3; i=i+1){\n  \tif (mnu_in[i] > 0.00017){ // Limit taken from Lesgourges et al. 2012\n  \t\tN_nu_mass = N_nu_mass + 1;\n  \t}\n  }\n  params.N_nu_mass = N_nu_mass;\n\n  // Fill the array of massive neutrinos\n  if (N_nu_mass>0){\n  \tparams.mnu = malloc(params.N_nu_mass*sizeof(double));\n  \tint relativistic[3] = {0, 0, 0};\n\tfor (int i = 0; i < N_nu_mass; i = i + 1){\n\t\tfor (int j = 0; j<3; j = j +1){\n\t\t\tif ((mnu_in[j]>0.00017) && (relativistic[j]==0)){\n\t\t\t\trelativistic[j]=1;\n\t\t\t\tparams.mnu[i] = mnu_in[j];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} // end loop over neutrinos\n\t} // end loop over massive neutrinos\n  } else{\n\t  params.mnu = malloc(sizeof(double));\n\t  params.mnu[0] = 0.;\n  }\n  // Free mnu_in\n  if (mnu_in != NULL) free(mnu_in);\n\n  // Dark Energy\n  params.w0 = w0;\n  params.wa = wa;\n\n  // Hubble parameters\n  params.h = h;\n  params.H0 = h*100;\n\n  // Primordial power spectra\n  if(norm_pk<1E-5)\n    params.A_s=norm_pk;\n  else\n    params.sigma8=norm_pk;\n  params.n_s = n_s;\n\n  //Baryonic params\n  if(bcm_log10Mc<0)\n    params.bcm_log10Mc=log10(1.2e14);\n  else\n    params.bcm_log10Mc=bcm_log10Mc;\n  if(bcm_etab<0)\n    params.bcm_etab=0.5;\n  else\n    params.bcm_etab=bcm_etab;\n  if(bcm_ks<0)\n    params.bcm_ks=55.0;\n  else\n    params.bcm_ks=bcm_ks;\n\n  // Set remaining standard and easily derived parameters\n  ccl_parameters_fill_initial(&params, status);\n\n  //Trigger modified growth function if nz>0\n  if(nz_mgrowth>0) {\n    params.has_mgrowth=true;\n    params.nz_mgrowth=nz_mgrowth;\n    params.z_mgrowth=malloc(params.nz_mgrowth*sizeof(double));\n    params.df_mgrowth=malloc(params.nz_mgrowth*sizeof(double));\n    memcpy(params.z_mgrowth,zarr_mgrowth,params.nz_mgrowth*sizeof(double));\n    memcpy(params.df_mgrowth,dfarr_mgrowth,params.nz_mgrowth*sizeof(double));\n  }\n  else {\n    params.has_mgrowth=false;\n    params.nz_mgrowth=0;\n    params.z_mgrowth=NULL;\n    params.df_mgrowth=NULL;\n  }\n\n  return params;\n}\n\n\n/* ------- ROUTINE: ccl_parameters_create_flat_lcdm --------\nINPUT: some cosmological parameters needed to create a flat LCDM model\nTASK: call ccl_parameters_create to produce an LCDM model\n*/\nccl_parameters ccl_parameters_create_flat_lcdm(double Omega_c, double Omega_b, double h,\n                                               double norm_pk, double n_s, int *status)\n{\n  double Omega_k = 0.0;\n  double Neff = 3.046;\n  double w0 = -1.0;\n  double wa = 0.0;\n  double *mnu;\n  double mnuval = 0.;  // a pointer to the variable is not kept past the lifetime of this function\n  mnu = &mnuval;\n  ccl_mnu_convention mnu_type = ccl_mnu_sum;\n\n  ccl_parameters params = ccl_parameters_create(Omega_c, Omega_b, Omega_k, Neff,\n        mnu, mnu_type, w0, wa, h, norm_pk, n_s, -1, -1, -1, -1, NULL, NULL, status);\n\n  return params;\n\n}\n\n\n/**\n * Write a cosmology parameters object to a file in yaml format.\n * @param cosmo Cosmological parameters\n * @param f FILE* pointer opened for reading\n * @return void\n */\nvoid ccl_parameters_write_yaml(ccl_parameters * params, const char * filename, int *status)\n{\n\n  FILE * f = fopen(filename, \"w\");\n\n  if (!f){\n    *status = CCL_ERROR_FILE_WRITE;\n    return;\n  }\n\n#define WRITE_DOUBLE(name) fprintf(f, #name \": %le\\n\",params->name)\n#define WRITE_INT(name) fprintf(f, #name \": %d\\n\",params->name)\n\n  // Densities: CDM, baryons, total matter, curvature\n  WRITE_DOUBLE(Omega_c);\n  WRITE_DOUBLE(Omega_b);\n  WRITE_DOUBLE(Omega_m);\n  WRITE_DOUBLE(Omega_k);\n  WRITE_INT(k_sign);\n\n  // Dark Energy\n  WRITE_DOUBLE(w0);\n  WRITE_DOUBLE(wa);\n\n  // Hubble parameters\n  WRITE_DOUBLE(H0);\n  WRITE_DOUBLE(h);\n\n  // Neutrino properties\n  WRITE_DOUBLE(Neff);\n  WRITE_INT(N_nu_mass);\n  WRITE_DOUBLE(N_nu_rel);\n\n  if (params->N_nu_mass>0){\n    fprintf(f, \"mnu: [\");\n    for (int i=0; i<params->N_nu_mass; i++){\n      fprintf(f, \"%le, \", params->mnu[i]);\n    }\n    fprintf(f, \"]\\n\");\n  }\n\n  WRITE_DOUBLE(sum_nu_masses);\n  WRITE_DOUBLE(Omega_n_mass);\n  WRITE_DOUBLE(Omega_n_rel);\n\n  // Primordial power spectra\n  WRITE_DOUBLE(A_s);\n  WRITE_DOUBLE(n_s);\n\n  // Radiation parameters\n  WRITE_DOUBLE(Omega_g);\n  WRITE_DOUBLE(T_CMB);\n\n  // BCM baryonic model parameters\n  WRITE_DOUBLE(bcm_log10Mc);\n  WRITE_DOUBLE(bcm_etab);\n  WRITE_DOUBLE(bcm_ks);\n\n  // Derived parameters\n  WRITE_DOUBLE(sigma8);\n  WRITE_DOUBLE(Omega_l);\n  WRITE_DOUBLE(z_star);\n\n  WRITE_INT(has_mgrowth);\n  WRITE_INT(nz_mgrowth);\n\n  if (params->has_mgrowth){\n    fprintf(f, \"z_mgrowth: [\");\n    for (int i=0; i<params->nz_mgrowth; i++){\n      fprintf(f, \"%le, \", params->z_mgrowth[i]);\n    }\n    fprintf(f, \"]\\n\");\n\n    fprintf(f, \"df_mgrowth: [\");\n    for (int i=0; i<params->nz_mgrowth; i++){\n      fprintf(f, \"%le, \", params->df_mgrowth[i]);\n    }\n    fprintf(f, \"]\\n\");\n  }\n\n#undef WRITE_DOUBLE\n#undef WRITE_INT\n\n  fclose(f);\n\n}\n\n/**\n * Write a cosmology parameters object to a file in yaml format.\n * @param cosmo Cosmological parameters\n * @param f FILE* pointer opened for reading\n * @return void\n */\nccl_parameters ccl_parameters_read_yaml(const char * filename, int *status)\n{\n\n  FILE * f = fopen(filename, \"r\");\n\n  if (!f){\n    *status = CCL_ERROR_FILE_READ;\n    ccl_parameters bad_params;\n\n    ccl_raise_exception(CCL_ERROR_FILE_READ, \"ccl_core.c: Failed to read parameters from file.\");\n\n    return bad_params;\n  }\n\n#define READ_DOUBLE(name) double name; *status |= (0==fscanf(f, #name \": %le\\n\",&name));\n#define READ_INT(name) int name; *status |= (0==fscanf(f, #name \": %d\\n\",&name))\n\n  // Densities: CDM, baryons, total matter, curvature\n  READ_DOUBLE(Omega_c);\n  READ_DOUBLE(Omega_b);\n  READ_DOUBLE(Omega_m);\n  READ_DOUBLE(Omega_k);\n  READ_INT(k_sign);\n\n  // Dark Energy\n  READ_DOUBLE(w0);\n  READ_DOUBLE(wa);\n\n  // Hubble parameters\n  READ_DOUBLE(H0);\n  READ_DOUBLE(h);\n\n  // Neutrino properties\n  READ_DOUBLE(Neff);\n  READ_INT(N_nu_mass);\n  READ_DOUBLE(N_nu_rel);\n\n  double mnu[3] = {0.0, 0.0, 0.0};\n  if (N_nu_mass>0){\n    *status |= (0==fscanf(f, \"mnu: [\"));\n    for (int i=0; i<N_nu_mass; i++){\n      *status |= (0==fscanf(f, \"%le, \", mnu+i));\n    }\n    *status |= (0==fscanf(f, \"]\\n\"));\n  }\n\n  READ_DOUBLE(sum_nu_masses);\n  READ_DOUBLE(Omega_n_mass);\n  READ_DOUBLE(Omega_n_rel);\n\n  // Primordial power spectra\n  READ_DOUBLE(A_s);\n  READ_DOUBLE(n_s);\n\n  // Radiation parameters\n  READ_DOUBLE(Omega_g);\n  READ_DOUBLE(T_CMB);\n\n  // BCM baryonic model parameters\n  READ_DOUBLE(bcm_log10Mc);\n  READ_DOUBLE(bcm_etab);\n  READ_DOUBLE(bcm_ks);\n\n  // Derived parameters\n  READ_DOUBLE(sigma8);\n  READ_DOUBLE(Omega_l);\n  READ_DOUBLE(z_star);\n\n  READ_INT(has_mgrowth);\n  READ_INT(nz_mgrowth);\n\n  double *z_mgrowth;\n  double *df_mgrowth;\n\n\n  if (has_mgrowth){\n    z_mgrowth = malloc(nz_mgrowth*sizeof(double));\n    df_mgrowth = malloc(nz_mgrowth*sizeof(double));\n    *status |= (0==fscanf(f, \"z_mgrowth: [\"));\n    for (int i=0; i<nz_mgrowth; i++){\n      *status |= (0==fscanf(f, \"%le, \", z_mgrowth+i));\n    }\n    *status |= (0==fscanf(f, \"]\\n\"));\n\n    *status |= (0==fscanf(f, \"df_mgrowth: [\"));\n    for (int i=0; i<nz_mgrowth; i++){\n      *status |= (0==fscanf(f, \"%le, \", df_mgrowth+i));\n    }\n    *status |= (0==fscanf(f, \"]\\n\"));\n  }\n  else{\n    z_mgrowth = NULL;\n    df_mgrowth = NULL;\n  }\n\n#undef READ_DOUBLE\n#undef READ_INT\n\n  fclose(f);\n\n\n  if (status){\n    char msg[256];\n    snprintf(msg, 256, \"ccl_core.c: Structure of YAML file incorrect: %s\", filename);\n    ccl_raise_exception(*status, msg);\n  }\n\n  double norm_pk;\n\n  if (isnan(A_s)){\n    norm_pk = sigma8;\n  }\n  else{\n   norm_pk = A_s;\n  }\n\n  ccl_parameters params = ccl_parameters_create(\n    Omega_c, Omega_b, Omega_k,\n    Neff, mnu, ccl_mnu_list,\n    w0, wa, h, norm_pk,\n    n_s, bcm_log10Mc, bcm_etab,\n    bcm_ks, nz_mgrowth, z_mgrowth,\n    df_mgrowth, status);\n\n  if(z_mgrowth) free(z_mgrowth);\n  if (df_mgrowth) free(df_mgrowth);\n\n  return params;\n\n}\n\n\n\n/* ------- ROUTINE: ccl_data_free --------\nINPUT: ccl_data\nTASK: free the input data\n*/\nvoid ccl_data_free(ccl_data * data)\n{\n  //We cannot assume that all of these have been allocated\n  //TODO: it would actually make more sense to do this within ccl_cosmology_free,\n  //where we could make use of the flags \"computed_distances\" etc. to figure out\n  //what to free up\n  gsl_spline_free(data->chi);\n  gsl_spline_free(data->growth);\n  gsl_spline_free(data->fgrowth);\n  gsl_interp_accel_free(data->accelerator);\n  gsl_interp_accel_free(data->accelerator_achi);\n  gsl_spline_free(data->E);\n  gsl_spline_free(data->achi);\n  gsl_spline_free(data->logsigma);\n  gsl_spline_free(data->dlnsigma_dlogm);\n  gsl_spline2d_free(data->p_lin);\n  gsl_spline2d_free(data->p_nl);\n  gsl_spline_free(data->alphahmf);\n  gsl_spline_free(data->betahmf);\n  gsl_spline_free(data->gammahmf);\n  gsl_spline_free(data->phihmf);\n  gsl_spline_free(data->etahmf);\n  gsl_interp_accel_free(data->accelerator_d);\n  gsl_interp_accel_free(data->accelerator_m);\n  gsl_interp_accel_free(data->accelerator_k);\n}\n\n/* ------- ROUTINE: ccl_cosmology_set_status_message --------\nINPUT: ccl_cosmology struct, status_string\nTASK: set the status message safely.\n*/\nvoid ccl_cosmology_set_status_message(ccl_cosmology * cosmo, const char * message, ...)\n{\n  const int trunc = 480; /* must be < 500 - 4 */\n  va_list va;\n  va_start(va, message);\n  vsnprintf(cosmo->status_message, trunc, message, va);\n  va_end(va);\n\n  /* if truncation happens, message[trunc - 1] is not NULL, ... will show up. */\n  strcpy(&cosmo->status_message[trunc], \"...\");\n}\n\n/* ------- ROUTINE: ccl_parameters_free --------\nINPUT: ccl_parameters struct\nTASK: free allocated quantities in the parameters struct\n*/\nvoid ccl_parameters_free(ccl_parameters * params)\n{\n  if (params->mnu != NULL){\n    free(params->mnu);\n    params->mnu = NULL;\n  }\n  if (params->z_mgrowth != NULL){\n    free(params->z_mgrowth);\n    params->z_mgrowth = NULL;\n  }\n  if (params->df_mgrowth != NULL){\n    free(params->df_mgrowth);\n    params->df_mgrowth = NULL;\n  }\n}\n\n\n/* ------- ROUTINE: ccl_cosmology_free --------\nINPUT: ccl_cosmology struct\nTASK: free the input data and the cosmology struct\n*/\nvoid ccl_cosmology_free(ccl_cosmology * cosmo)\n{\n  ccl_data_free(&cosmo->data);\n  free(cosmo);\n}\n", "meta": {"hexsha": "65ea1938aef1bf4adab4b63bc82476e12ec1552b", "size": 25591, "ext": "c", "lang": "C", "max_stars_repo_path": "src/ccl_core.c", "max_stars_repo_name": "Russell-Jones-OxPhys/CCL", "max_stars_repo_head_hexsha": "1cdc4ecb8ae6fb23806540b39799cc3317473e71", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ccl_core.c", "max_issues_repo_name": "Russell-Jones-OxPhys/CCL", "max_issues_repo_head_hexsha": "1cdc4ecb8ae6fb23806540b39799cc3317473e71", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ccl_core.c", "max_forks_repo_name": "Russell-Jones-OxPhys/CCL", "max_forks_repo_head_hexsha": "1cdc4ecb8ae6fb23806540b39799cc3317473e71", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8697225573, "max_line_length": 136, "alphanum_fraction": 0.6606228752, "num_tokens": 7845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295203152604, "lm_q2_score": 0.05261895520477843, "lm_q1q2_score": 0.02344329787187511}}
{"text": "/*\n * Author : Pierre Schnizer\n * Date   : December 2004\n *\n */\n\n/*\n#ifdef DEBUG\n#undef DEBUG\n#endif\n\n#define DEBUG 10\n*/\n\n#include <gsl/gsl_fft.h>\n\n#include <gsl/gsl_fft_complex.h>\n#include <gsl/gsl_fft_real.h>\n#include <gsl/gsl_fft_halfcomplex.h>\n\n#include <gsl/gsl_fft_complex_float.h>\n#include <gsl/gsl_fft_real_float.h>\n#include <gsl/gsl_fft_halfcomplex_float.h>\n\n#include <pygsl/error_helpers.h>\n#include <pygsl/block_helpers.h>\n\nenum pygsl_fft_space_type{\n\tCOMPLEX_WORKSPACE = 0,\n\tREAL_WORKSPACE,\n\tCOMPLEX_WAVETABLE,\n\tREAL_WAVETABLE,\n\tHALFCOMPLEX_WAVETABLE,\n\tCOMPLEX_WORKSPACE_FLOAT,\n\tREAL_WORKSPACE_FLOAT,\n\tCOMPLEX_WAVETABLE_FLOAT,\n\tREAL_WAVETABLE_FLOAT,\n\tHALFCOMPLEX_WAVETABLE_FLOAT\n};\n\nenum pygsl_fft_mode{\n\tMODE_DOUBLE = 0,\n\tMODE_FLOAT\n};\n\nunion pygsl_fft_space_t{\n\tgsl_fft_complex_workspace     *cws;\n\tgsl_fft_complex_wavetable     *cwt;\n\tgsl_fft_real_workspace        *rws;\n\tgsl_fft_real_wavetable        *rwt;\n\tgsl_fft_halfcomplex_wavetable *hcwt;\n\tgsl_fft_complex_workspace_float     *cwsf;\n\tgsl_fft_complex_wavetable_float     *cwtf;\n\tgsl_fft_real_workspace_float        *rwsf;\n\tgsl_fft_real_wavetable_float        *rwtf;\n\tgsl_fft_halfcomplex_wavetable_float *hcwtf;\n\tvoid                          *v;\n};\n\ntypedef struct {\n\tPyObject_HEAD\n\tunion pygsl_fft_space_t space;\n\tint type;\n} PyGSL_fft_space;\n\nstatic PyObject *module = NULL;\nstatic const char filename[] = __FILE__;\n\nstatic const char  PyGSL_fft_space_type_doc[] = \"\\\nA catch all of the various space types of the fft module. Call the method\\n\\\n'get_type' to find what object is wrapped underneath!\\n\\\n\";\nstatic void\nPyGSL_fft_space_dealloc(PyGSL_fft_space * self);\n\nstatic PyObject*\nPyGSL_fft_space_getattr(PyGSL_fft_space * self, char * name);\n\n#define PyGSL_fft_space_check(op) ((op)->ob_type == &PyGSL_fft_space_pytype)\n#define PyGSL_complex_fft_work_space_check(op) \\\n         (PyGSL_fft_space_check(op) && ((PyGSL_fft_space *)op)->type == COMPLEX_WORKSPACE)\n#define PyGSL_complex_fft_wave_table_check(op) \\\n         (PyGSL_fft_space_check(op) && ((PyGSL_fft_space *)op)->type == COMPLEX_WAVETABLE)\n#define PyGSL_halfcomplex_fft_wave_table_check(op) \\\n         (PyGSL_fft_space_check(op) && ((PyGSL_fft_space *)op)->type == HALFCOMPLEX_WAVETABLE)\n#define PyGSL_real_fft_work_space_check(op) \\\n         (PyGSL_fft_space_check(op) && ((PyGSL_fft_space *)op)->type == REAL_WORKSPACE)\n#define PyGSL_real_fft_wave_table_check(op) \\\n         (PyGSL_fft_space_check(op) && ((PyGSL_fft_space *)op)->type == REAL_WAVETABLE)\n\n#define PyGSL_complex_fft_work_space_float_check(op) \\\n         (PyGSL_fft_space_check(op) && ((PyGSL_fft_space *)op)->type == COMPLEX_WORKSPACE_FLOAT)\n#define PyGSL_complex_fft_wave_table_float_check(op) \\\n         (PyGSL_fft_space_check(op) && ((PyGSL_fft_space *)op)->type == COMPLEX_WAVETABLE_FLOAT)\n#define PyGSL_halfcomplex_fft_wave_table_float_check(op) \\\n         (PyGSL_fft_space_check(op) && ((PyGSL_fft_space *)op)->type == HALFCOMPLEX_WAVETABLE_FLOAT)\n#define PyGSL_real_fft_work_space_float_check(op) \\\n         (PyGSL_fft_space_check(op) && ((PyGSL_fft_space *)op)->type == REAL_WORKSPACE_FLOAT)\n#define PyGSL_real_fft_wave_table_float_check(op) \\\n         (PyGSL_fft_space_check(op) && ((PyGSL_fft_space *)op)->type == REAL_WAVETABLE_FLOAT)\n\n#define PyGSL_FFT_MODE_SWITCH(mode, double_element, float_element) \\\n        (mode == MODE_DOUBLE) ? double_element : float_element\n\n\n\nPyTypeObject PyGSL_fft_space_pytype = {\n  PyObject_HEAD_INIT(NULL)\t /* fix up the type slot in initcrng */\n  0,\t\t\t\t /* ob_size */\n  \"PyGSL_fft_space\",\t\t /* tp_name */\n  sizeof(PyGSL_fft_space),\t /* tp_basicsize */\n  0,\t\t\t\t /* tp_itemsize */\n\n  /* standard methods */\n  (destructor)  PyGSL_fft_space_dealloc, /* tp_dealloc  ref-count==0  */\n  (printfunc)   0,\t\t         /* tp_print    \"print x\"     */\n  (getattrfunc) PyGSL_fft_space_getattr,  /* tp_getattr  \"x.attr\"      */\n  (setattrfunc) 0,\t\t /* tp_setattr  \"x.attr=v\"    */\n  (cmpfunc)     0,\t\t   /* tp_compare  \"x > y\"       */\n  (reprfunc)    0,                 /* tp_repr     `x`, print x  */\n\n  /* type categories */\n  0,\t\t\t\t/* tp_as_number   +,-,*,/,%,&,>>,pow...*/\n  0,\t\t\t\t/* tp_as_sequence +,[i],[i:j],len, ...*/\n  0,\t\t\t\t/* tp_as_mapping  [key], len, ...*/\n\n  /* more methods */\n  (hashfunc)     0,\t\t/* tp_hash    \"dict[x]\" */\n  (ternaryfunc)  0,      /* tp_call    \"x()\"     */\n  (reprfunc)     0,             /* tp_str     \"str(x)\"  */\n  (getattrofunc) 0,\t\t/* tp_getattro */\n  (setattrofunc) 0,\t\t/* tp_setattro */\n  0,\t\t\t\t/* tp_as_buffer */\n  0L,\t\t\t\t/* tp_flags */\n  (char *) PyGSL_fft_space_type_doc\t\t/* tp_doc */\n};\n\nstatic PyObject *\nPyGSL_fft_space_get_factors(PyGSL_fft_space *self, PyGSL_fft_space *args)\n{\n\n       int nf, i;                                                           \n       long *data=NULL;\n       size_t *cp_data=NULL;\n       PyArrayObject * a_array = NULL;\t\t\t\t\t    \n\t\t\t\t\t\t\t\t\t    \n       assert(PyGSL_fft_space_check(self));\n\n       DEBUG_MESS(2, \"Type = %d\", self->type);\n       switch(self->type){\n       case COMPLEX_WAVETABLE:           nf = self->space.cwt ->nf;  cp_data = self->space.cwt ->factor;  break;\n       case REAL_WAVETABLE:\t         nf = self->space.rwt ->nf;  cp_data = self->space.rwt ->factor;  break;\n       case HALFCOMPLEX_WAVETABLE:       nf = self->space.hcwt->nf;  cp_data = self->space.hcwt->factor;  break;\t       \n       case COMPLEX_WAVETABLE_FLOAT:     nf = self->space.cwtf ->nf; cp_data = self->space.cwtf ->factor; break;\n       case REAL_WAVETABLE_FLOAT:        nf = self->space.rwtf ->nf; cp_data = self->space.rwtf ->factor; break;\n       case HALFCOMPLEX_WAVETABLE_FLOAT: nf = self->space.hcwtf->nf; cp_data = self->space.hcwtf->factor; break;\t       \n       default: gsl_error(\"Got unknown switch\", filename, __LINE__, GSL_ESANITY); return NULL; break;\n       }\n\n       assert(nf < 64);\n       a_array = (PyArrayObject *) PyGSL_New_Array(1, &nf, PyArray_LONG);\n       if(a_array == NULL)\n\t       return NULL;\n       data = (long *) a_array->data;\n\n       \n       for(i=0; i<nf; i++){\n\t    data[i] = (long) cp_data[i];\n       }\n       return (PyObject *) a_array;\n\n}\nstatic const char PyGSL_fft_space_get_factors_doc[] = \" Get the factors ...\";\nstatic const char PyGSL_fft_space_get_type_doc[] = \" Get the type of this space\";\n\nstatic PyObject *\nPyGSL_fft_space_get_type(PyGSL_fft_space *self, PyObject *notused)\n{\n\tchar *p = NULL;\n\n\tswitch(self->type){\n\tcase COMPLEX_WORKSPACE:           p = \"COMPLEX_WORKSPACE\";           break;\n\tcase REAL_WORKSPACE:\t          p = \"REAL_WORKSPACE\";\t             break;\n\tcase COMPLEX_WAVETABLE:           p = \"COMPLEX_WAVETABLE\";\t     break;\n\tcase REAL_WAVETABLE:\t          p = \"REAL_WAVETABLE\";\t             break;\n\tcase HALFCOMPLEX_WAVETABLE:       p = \"HALFCOMPLEX_WAVETABLE\";       break;\n\tcase COMPLEX_WORKSPACE_FLOAT:     p = \"COMPLEX_WORKSPACE_FLOAT\";     break;\n\tcase REAL_WORKSPACE_FLOAT:\t  p = \"REAL_WORKSPACE_FLOAT\";\t     break;\n\tcase COMPLEX_WAVETABLE_FLOAT:     p = \"COMPLEX_WAVETABLE_FLOAT\";     break;\n\tcase REAL_WAVETABLE_FLOAT:\t  p = \"REAL_WAVETABLE_FLOAT\";\t     break;\n\tcase HALFCOMPLEX_WAVETABLE_FLOAT: p = \"HALFCOMPLEX_WAVETABLE_FLOAT\"; break;\n\tdefault: gsl_error(\"Got unknown switch\", filename, __LINE__, GSL_ESANITY); return NULL;\n\t}\n\treturn PyString_FromString(p);\n}\n\nstatic PyMethodDef PyGSL_fft_wavetable_methods[] = {\n\t{\"get_factors\",  (PyCFunction)PyGSL_fft_space_get_factors, METH_NOARGS,  (char *)PyGSL_fft_space_get_factors_doc},\n\t{\"get_type\",     (PyCFunction)PyGSL_fft_space_get_type, METH_NOARGS,  (char *)PyGSL_fft_space_get_type_doc},\n\t{NULL, NULL, 0, NULL}           /* sentinel */\n};\n\nstatic PyMethodDef PyGSL_fft_space_methods[] = {\n\t{\"get_type\",     (PyCFunction)PyGSL_fft_space_get_type, METH_NOARGS,  (char *)PyGSL_fft_space_get_type_doc},\n\t{NULL, NULL, 0, NULL}           /* sentinel */\n};\n\nstatic PyObject*\nPyGSL_fft_space_getattr(PyGSL_fft_space *self, char *name)\n{\n     PyObject *tmp = NULL;\n     FUNC_MESS_BEGIN();\n     assert(PyGSL_fft_space_check(self));     \n     switch(self->type){\n     case  COMPLEX_WORKSPACE:\n     case  REAL_WORKSPACE:    \n     case  COMPLEX_WORKSPACE_FLOAT:\n     case  REAL_WORKSPACE_FLOAT:\n\t     tmp = Py_FindMethod(PyGSL_fft_space_methods, (PyObject *) self, name);\n     default:\n\t     tmp = Py_FindMethod(PyGSL_fft_wavetable_methods, (PyObject *) self, name);\n     }\n     FUNC_MESS_END();\n     return tmp;\n}\n\nstatic void\nPyGSL_fft_space_dealloc(PyGSL_fft_space * self)\n{\n     FUNC_MESS_BEGIN();\n     assert(PyGSL_fft_space_check(self));     \n     switch(self->type){\n     case COMPLEX_WORKSPACE:           gsl_fft_complex_workspace_free(self->space.cws);       break;\n     case COMPLEX_WAVETABLE:           gsl_fft_complex_wavetable_free(self->space.cwt);       break;\n     case REAL_WORKSPACE:              gsl_fft_real_workspace_free(self->space.rws);          break;\n     case REAL_WAVETABLE:\t       gsl_fft_real_wavetable_free(self->space.rwt);          break;\n     case HALFCOMPLEX_WAVETABLE:       gsl_fft_halfcomplex_wavetable_free(self->space.hcwt);  break;\n     case COMPLEX_WORKSPACE_FLOAT:     gsl_fft_complex_workspace_float_free(self->space.cwsf);      break;\n     case COMPLEX_WAVETABLE_FLOAT:     gsl_fft_complex_wavetable_float_free(self->space.cwtf);      break;\n     case REAL_WORKSPACE_FLOAT:        gsl_fft_real_workspace_float_free(self->space.rwsf);         break;\n     case REAL_WAVETABLE_FLOAT:\t       gsl_fft_real_wavetable_float_free(self->space.rwtf);         break;\n     case HALFCOMPLEX_WAVETABLE_FLOAT: gsl_fft_halfcomplex_wavetable_float_free(self->space.hcwtf); break;\n     default: gsl_error(\"Got unknown switch\", filename, __LINE__, GSL_ESANITY); break;\n     }\n     FUNC_MESS_END();\n}\n\nstatic PyObject* \nPyGSL_fft_space_init(PyObject *self, PyObject *args, int type)\n{\n\tPyGSL_fft_space *o=NULL;\n\tsize_t n;\n\to =  (PyGSL_fft_space *) PyObject_NEW(PyGSL_fft_space, &PyGSL_fft_space_pytype);\n\tif(o == NULL){\n\t\treturn NULL;\n\t}\n\n\tif (0==PyArg_ParseTuple(args,\"l\", &n))\n\t\treturn NULL;\n\n\n\tif (n<=0) {\n\t\tPyErr_SetString(PyExc_RuntimeError, \"dimension must be >0\");\n\t\treturn NULL;\n\t}\n\to->type = type;\n\tswitch(type){\n\tcase COMPLEX_WORKSPACE:           o->space.cws  = gsl_fft_complex_workspace_alloc(n);            break;\n\tcase COMPLEX_WAVETABLE:           o->space.cwt  = gsl_fft_complex_wavetable_alloc(n);            break;\n\tcase REAL_WORKSPACE:              o->space.rws  = gsl_fft_real_workspace_alloc(n);               break;\n\tcase REAL_WAVETABLE:\t          o->space.rwt  = gsl_fft_real_wavetable_alloc(n);               break;\n\tcase HALFCOMPLEX_WAVETABLE:       o->space.hcwt = gsl_fft_halfcomplex_wavetable_alloc(n);        break;\n\tcase COMPLEX_WORKSPACE_FLOAT:     o->space.cwsf  = gsl_fft_complex_workspace_float_alloc(n);     break;\n\tcase COMPLEX_WAVETABLE_FLOAT:     o->space.cwtf  = gsl_fft_complex_wavetable_float_alloc(n);     break;\n\tcase REAL_WORKSPACE_FLOAT:        o->space.rwsf  = gsl_fft_real_workspace_float_alloc(n);        break;\n\tcase REAL_WAVETABLE_FLOAT:\t  o->space.rwtf  = gsl_fft_real_wavetable_float_alloc(n);        break;\n\tcase HALFCOMPLEX_WAVETABLE_FLOAT: o->space.hcwtf = gsl_fft_halfcomplex_wavetable_float_alloc(n); break;\n\tdefault: gsl_error(\"Got unknown switch\", filename, __LINE__, GSL_ESANITY); return NULL; break;\n\t}\n\treturn (PyObject *) o;\n}\n\n\n\n#define PyGSL_SPACE_ALLOC(TYPE)                               \\\nstatic PyObject *                                             \\\nPyGSL_fft_space_init_ ## TYPE (PyObject *self, PyObject *args)\\\n{                                                             \\\n     return PyGSL_fft_space_init(self, args, TYPE);           \\\n}                                                             \nPyGSL_SPACE_ALLOC(COMPLEX_WORKSPACE)\nPyGSL_SPACE_ALLOC(COMPLEX_WAVETABLE)\nPyGSL_SPACE_ALLOC(REAL_WORKSPACE)      \nPyGSL_SPACE_ALLOC(REAL_WAVETABLE)\nPyGSL_SPACE_ALLOC(HALFCOMPLEX_WAVETABLE)\n\nPyGSL_SPACE_ALLOC(COMPLEX_WORKSPACE_FLOAT)\nPyGSL_SPACE_ALLOC(COMPLEX_WAVETABLE_FLOAT)\nPyGSL_SPACE_ALLOC(REAL_WORKSPACE_FLOAT)      \nPyGSL_SPACE_ALLOC(REAL_WAVETABLE_FLOAT)\nPyGSL_SPACE_ALLOC(HALFCOMPLEX_WAVETABLE_FLOAT)\n\n\n/*\ntypedef int (complex_transform)(gsl_complex_packed_array\n          DATA, size_t STRIDE, size_t N, const\n          gsl_fft_complex_wavetable * WAVETABLE,\n          gsl_fft_complex_workspace * WORK);\n*/\ntypedef int transform(void * data, size_t stride, size_t N, const void *, void *);\ntypedef int transform_r2(void * data, size_t stride, size_t N);\n\n\ntypedef void * pygsl_fft_helpn_t(int);\ntypedef void * pygsl_fft_help_t(void *);\n\nstruct _pygsl_fft_help_s {\n\tpygsl_fft_helpn_t  * space_alloc;\n\tpygsl_fft_help_t   * space_free;\n\tpygsl_fft_helpn_t  * table_alloc;\n\tpygsl_fft_help_t   * table_free;\n\tenum pygsl_fft_space_type space_type;\n\tenum pygsl_fft_space_type table_type;\n\tvoid * space;\n\tvoid * table;\n\tint free_space;\n\tint free_table;\n};\n\ntypedef struct _pygsl_fft_help_s pygsl_fft_help_s;\n\nstatic const  \npygsl_fft_help_s complex_helpers = {(pygsl_fft_helpn_t *) gsl_fft_complex_workspace_alloc, \n\t\t\t\t    (pygsl_fft_help_t *)  gsl_fft_complex_workspace_free, \n\t\t\t\t    (pygsl_fft_helpn_t *) gsl_fft_complex_wavetable_alloc, \n\t\t\t\t    (pygsl_fft_help_t *)  gsl_fft_complex_wavetable_free,\n                                    COMPLEX_WORKSPACE, COMPLEX_WAVETABLE};\n\nstatic const  \npygsl_fft_help_s halfcomplex_helpers = {(pygsl_fft_helpn_t *) gsl_fft_real_workspace_alloc, \n\t\t\t\t\t(pygsl_fft_help_t *)  gsl_fft_real_workspace_free, \n\t\t\t\t\t(pygsl_fft_helpn_t *) gsl_fft_halfcomplex_wavetable_alloc, \n\t\t\t\t\t(pygsl_fft_help_t *)  gsl_fft_halfcomplex_wavetable_free, \n\t\t\t\t\tREAL_WORKSPACE, HALFCOMPLEX_WAVETABLE};\nstatic const \npygsl_fft_help_s real_helpers = {(pygsl_fft_helpn_t *) gsl_fft_real_workspace_alloc, \n\t\t\t\t (pygsl_fft_help_t *)  gsl_fft_real_workspace_free, \n\t\t\t\t (pygsl_fft_helpn_t *) gsl_fft_real_wavetable_alloc, \n\t\t\t\t (pygsl_fft_help_t *)  gsl_fft_real_wavetable_free, \n\t\t\t\t REAL_WORKSPACE, REAL_WAVETABLE};\nstatic const \npygsl_fft_help_s complex_helpers_float = {(pygsl_fft_helpn_t *) gsl_fft_complex_workspace_float_alloc, \n\t\t\t\t    (pygsl_fft_help_t *)  gsl_fft_complex_workspace_float_free, \n\t\t\t\t    (pygsl_fft_helpn_t *) gsl_fft_complex_wavetable_float_alloc, \n\t\t\t\t    (pygsl_fft_help_t *)  gsl_fft_complex_wavetable_float_free,\n                                    COMPLEX_WORKSPACE, COMPLEX_WAVETABLE};\n\nstatic const \npygsl_fft_help_s halfcomplex_helpers_float = {(pygsl_fft_helpn_t *) gsl_fft_real_workspace_float_alloc, \n\t\t\t\t\t(pygsl_fft_help_t *)  gsl_fft_real_workspace_float_free, \n\t\t\t\t\t(pygsl_fft_helpn_t *) gsl_fft_halfcomplex_wavetable_float_alloc, \n\t\t\t\t\t(pygsl_fft_help_t *)  gsl_fft_halfcomplex_wavetable_float_free, \n\t\t\t\t\tREAL_WORKSPACE, HALFCOMPLEX_WAVETABLE};\nstatic const \npygsl_fft_help_s real_helpers_float = {(pygsl_fft_helpn_t *) gsl_fft_real_workspace_float_alloc, \n\t\t\t\t (pygsl_fft_help_t *)  gsl_fft_real_workspace_float_free, \n\t\t\t\t (pygsl_fft_helpn_t *) gsl_fft_real_wavetable_float_alloc, \n\t\t\t\t (pygsl_fft_help_t *)  gsl_fft_real_wavetable_float_free, \n\t\t\t\t REAL_WORKSPACE, REAL_WAVETABLE};\n\nstatic int \nPyGSL_fft_helpers_alloc(PyObject *s_o, PyObject *t_o, pygsl_fft_help_s * h, int n)\n{\n\th->free_space = 0;\n\th->free_table = 0;\n\th->table = NULL;\n\th->space = NULL;\n\n\tif(s_o){\n\t\tif(PyGSL_fft_space_check(s_o) && ((PyGSL_fft_space * )s_o)->type == h->space_type){\n\t\t\th->space = ((PyGSL_fft_space * )s_o) ->space.v;\n\t\t} else {\n\t\t\tPyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__ - 4);\n\t\t\tGSL_ERROR(\"Need a pygsl  fft space of proper type!\", GSL_EINVAL);\n\t\t}\n\t}\n\n\tif(t_o){\n\t\tif(PyGSL_fft_space_check(t_o) && ((PyGSL_fft_space * )t_o)->type == h->table_type){\n\t\t\th->table = ((PyGSL_fft_space * )t_o) ->space.v;\n\t\t} else {\n\t\t\tPyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__ - 4);\n\t\t\tGSL_ERROR(\"Need a pygsl fft wave table of proper type!\", GSL_EINVAL);\n\t\t}\n\t}\n\t/* Check for the approbriate type and initialise it!*/\n\tif(h->space == NULL || h->table == NULL){\n\t\t/* Store if I need to free these arrays */\n\t\th->free_space = (h->space == NULL) ? 1 : 0;\n\t\th->free_table = (h->table == NULL) ? 1 : 0;\n\t\tif(!h->space) h->space = h->space_alloc(n);\n\t\tif(!h->table) h->table = h->table_alloc(n);\n\t\tif(!h->space || !h->table)  \n\t\t\treturn GSL_ENOMEM;\n\t}\n\treturn GSL_SUCCESS;\n\n}\n\nstatic void\nPyGSL_fft_helpers_free(pygsl_fft_help_s * h)\n{\n\tif(h->table && h->free_table){ \n\t\th->table_free(h->table); \n\t\th->table = NULL;\n\t}\n\tif(h->space && h->free_space){\n\t\th->space_free(h->space);  \n\t\th->space = NULL;\n\t}\n}\n/* \n * Copies real data to complex in the special way that it will be passed to the\n * transform with an offset of one! \n */\nstatic int\nPyGSL_copy_real_to_complex(PyArrayObject *dst, PyArrayObject *src, enum pygsl_fft_mode mode)\n{\n\tint i, n, n_check, n_2;\n\n\tn = src->dimensions[0];\n\tn_check = dst->dimensions[0];\n\t\n\tfor(i = 0; i < n; ++i){\n\n\t\tdouble *srcd=NULL, *dstd=NULL;\t\t\t\n\t\tfloat  *srcf=NULL, *dstf=NULL;\t\t\t\n\t\tif(mode == MODE_DOUBLE){\n\t\t\tsrcd = (double *)(src->data + src->strides[0] *  (i));\n\t\t\tn_2 = (i+1)/2;\n\t\t\tdstd = (double *)(dst->data + dst->strides[0] *  (n_2));\n\t\t\tif(n_2 >= n_check)\n\t\t\t\tGSL_ERROR(\"Complex array too small!\", GSL_ESANITY);\n\t\t\tdstd[(i+1)%2] = *srcd;\n\t\t\tDEBUG_MESS(5, \"R -> C [%d] srcd %e\\t dstd %e + %ej\", i, *srcd, dstd[0], dstd[1]);\n\t\t}else if(mode == MODE_FLOAT){\n\t\t\tsrcf = (float *)(src->data + src->strides[0] *  (i));\n\t\t\tn_2 = (i+1)/2;\n\t\t\tdstf = (float *)(dst->data + dst->strides[0] *  (n_2));\n\t\t\tif(n_2 >= n_check)\n\t\t\t\tGSL_ERROR(\"Complex array too small!\", GSL_ESANITY);\n\t\t\tdstf[(i+1)%2] = *srcd;\t\t\t\n\t\t}\n\t}\n\t/* XXX Sometimes the last value must be set to zero ... */\n\treturn GSL_SUCCESS;\n\t\n}\n\n/* Assumes special halfcomplex arrangement to be made and used ! */\nstatic int\nPyGSL_copy_halfcomplex_to_real(PyArrayObject *dst, PyArrayObject *src, double eps, enum pygsl_fft_mode mode\n\t )\n{\n\tint n, n_check, i, n_2;\n\tdouble *srcd=NULL, *dstd=NULL;\n\tfloat *srcf=NULL, *dstf=NULL;\n\n\tn_check = src->dimensions[0];\n\tn = dst->dimensions[0];\n\n\t/* The first element is a bit special */\n\tif(mode == MODE_DOUBLE){\n\t\tsrcd = (double *)(src->data);\t\n\t\tdstd = (double *)(dst->data);\n\t} else {\n\t\tsrcf = (float *)(src->data);\t\n\t\tdstf = (float *)(dst->data);\n\t}\n\t/* Should be zero ... */\n\tif(gsl_fcmp(PyGSL_FFT_MODE_SWITCH(mode, srcd[1], srcf[1]), 0,  eps) != 0)\n\t\tGSL_ERROR(\"The complex part of the nyquist freqency was not\" \n\t\t\t  \"zero as it ought to be!\", GSL_EINVAL);\n\t*dstd = *srcd;\n\n\tfor(i = 1; i < n; ++i){\n\t\tn_2 = (i+1)/2;\n\t\tif(n_2 >= n_check){\n\t\t\tGSL_ERROR(\"Sizes of the complex array too small!\", GSL_ESANITY);\n\t\t}\n\t\tif(mode == MODE_DOUBLE){\n\t\t\tsrcd = (double *)(src->data + src->strides[0] * n_2);\n\t\t\tdstd = (double *)(dst->data + dst->strides[0] * i);\n\t\t\t*dstd = srcd[(i+1)%2];\n\t\t\tDEBUG_MESS(5, \"C -> R [%d] srcd %e + %ej\\t dstd %e\", i, srcd[0], srcd[1], *dstd);\n\t\t} else {\n\t\t\tsrcf = (float *)(src->data + src->strides[0] * n_2);\n\t\t\tdstf = (float *)(dst->data + dst->strides[0] * i);\n\t\t\t*dstf = srcf[(i+1)%2];\n\t\t\tDEBUG_MESS(5, \"C -> R [%d] srcf %e + %ej\\t dstf %e\", i, srcf[0], srcf[1], *dstf);\n\t\t}\n\t}\n\treturn GSL_SUCCESS;\n}\n\nstatic int\nPyGSL_copy_complex_to_complex(PyArrayObject *dst, PyArrayObject *src,  enum pygsl_fft_mode mode)\n{\n\tint n, n_check, i;\n\n\tFUNC_MESS_BEGIN();\n\tn = dst->dimensions[0];\n\tn_check = src->dimensions[0];\n\tif(n_check != n){\n\t\tGSL_ERROR(\"Sizes of the arrays did not match!\", GSL_ESANITY);\n\t}\n\tfor(i = 0; i < n; i ++){\n\t\tdouble *srcd=NULL, *dstd=NULL;\n\t\tfloat  *srcf=NULL, *dstf=NULL;\n\t\tif(mode == MODE_DOUBLE){\n\t\t\tsrcd = (double *)(src->data + src->strides[0] * i);\n\t\t\tdstd = (double *)(dst->data + dst->strides[0] * i);\n\t\t\tdstd[0] = srcd[0];\n\t\t\tdstd[1] = srcd[1];\n\t\t} else {\n\t\t\tsrcf = (float *)(src->data + src->strides[0] * i);\n\t\t\tdstf = (float *)(dst->data + dst->strides[0] * i);\n\t\t\tdstf[0] = srcf[0];\n\t\t\tdstf[1] = srcf[1];\n\t\t}\n\t}\n\tFUNC_MESS_END();\n\treturn GSL_SUCCESS;\n}\n\n#if 0\n/*\n * Copy a complex array to a real one or to the other ...\n */\nstatic int\nPyGSL_copy_complex_real(PyArrayObject *dst, PyArrayObject *src)\n{\n\tint in_type, out_type;\n\tint flag = GSL_FAILURE, line = -1;\n\n\n\tFUNC_MESS_BEGIN();\n\tin_type  = src->descr->type_num;\n\tout_type = dst->descr->type_num;\n\n\tif(in_type ==  PyArray_CDOUBLE){\n\t\tDEBUG_MESS(2, \"Src is a complex array!\", NULL);\t\t\n\t} else if (in_type ==  PyArray_DOUBLE){\n\t\tDEBUG_MESS(2, \"Src is a real array!\", NULL);\n\t}\n\tif(out_type ==  PyArray_CDOUBLE){\n\t\tDEBUG_MESS(2, \"Dst is a complex array!\", NULL);\n\t} else if (out_type ==  PyArray_DOUBLE){\n\t\tDEBUG_MESS(2, \"Dst is a real array!\", NULL);\n\t}\n\n\tif(out_type == PyArray_CDOUBLE && in_type == PyArray_CDOUBLE){\n\t\tif(PyGSL_copy_complex_to_complex(dst, src) != GSL_SUCCESS){\n\t\t\tline = __LINE__ - 1;\n\t\t\tgoto fail;\t\t\t\n\t\t}\n\t} else \tif(out_type == PyArray_DOUBLE && in_type == PyArray_CDOUBLE){\n\t\tif(PyGSL_copy_halfcomplex_to_real(dst, src) != GSL_SUCCESS){\n\t\t\tline = __LINE__ - 1;\n\t\t\tgoto fail;\n\t\t}\n\t} else if(out_type == PyArray_CDOUBLE && in_type == PyArray_DOUBLE){\n\t\tif(PyGSL_copy_real_to_complex(dst, src) != GSL_SUCCESS){\n\t\t\tline = __LINE__ - 1;\n\t\t\tgoto fail;\n\t\t}\n\t} else{\n\t\tflag = GSL_ESANITY;\n\t\tline = __LINE__;\n\t\tgoto fail;\n\t}\n\tFUNC_MESS_END();\n\treturn GSL_SUCCESS;\n  fail:\n\tFUNC_MESS(\"Fail\");\n\tgsl_error(\"Not specifed error\", filename, line, flag);\n\tPyGSL_add_traceback(module, filename, __FUNCTION__, line);\n\treturn flag;\n}\n#endif \n\n/*\n * Only shift the last one. Assumes that it was passed to the GSL function with\n * an offset of one. Further assumes an contingous array.\n */\nstatic int\nPyGSL_fft_halfcomplex_unpack(PyArrayObject *a, int n_orig,  enum pygsl_fft_mode mode)\n{\n\tdouble *d;\n\tfloat *f;\n\tFUNC_MESS_BEGIN();\n\tif(mode == MODE_DOUBLE){\n\t\td = (double *) a->data;\n\t\td[0] = d[1];\n\t\td[1] = 0.0;\n\t\t/* Set the last imaginary to zero for even length as it ought to be */\n\t\tif(n_orig%2)\n\t\t\td[n_orig] = 0.0; \n\t}else{\n\t\tf = (float *) a->data;\n\t\tf[0] = f[1];\n\t\tf[1] = 0.0;\n\t\t/* Set the last imaginary to zero for even length as it ought to be */\n\t\tif(n_orig%2)\n\t\t\tf[n_orig] = 0.0; \n\n\t}\n\tFUNC_MESS_END();\n\treturn GSL_SUCCESS;\n}\n\n/*\n * I only need to reorder the imaginary data?\n * I have to do it inplace thus I can not use the gsl function ...\n */\nstatic PyObject *\nPyGSL_fft_halfcomplex_radix2_unpack(PyObject *self, PyObject *args)\n{\n\n\tPyObject *a_o=NULL;\n\tPyArrayObject *a=NULL, *r=NULL;\n\tint i, n, rn;\n        double *data, *real, *imag;\n\n\tFUNC_MESS_BEGIN();\n\tif(!PyArg_ParseTuple(args, \"O\",&a_o))\n\t\treturn NULL;\n\n\ta = PyGSL_PyArray_PREPARE_gsl_vector_view(a_o, PyArray_DOUBLE, 0, -1, 1, NULL);\n\tif(a == NULL)\n\t\tgoto fail;\n\tn = a->dimensions[0];\n\tif(n%2 != 0){\n\t\tgsl_error(\"The length of the vector must be a multiple of two!\",\n\t\t\t  __FILE__, __LINE__, GSL_EDOM);\t\tgoto fail;\n\t}\n\trn = n / 2 + 1;\n\tif((r = (PyArrayObject *) PyGSL_New_Array(1, &rn, PyArray_CDOUBLE)) == NULL)\n\t\tgoto fail;\n\tassert(r->dimensions[0] == rn);\n\t/* first one special */\n\tdata = (double *) r->data;\n\tdata[0] = a->data[0];\n\tdata[1] = 0.0;\n\n\tfor(i = 1; i < rn - 1; ++i){\n\t\tdata    = (double *)(r->data + r->strides[0] * i);\n\t\treal    = (double *)(a->data + a->strides[0] * i);\n\t\timag    = (double *)(a->data + a->strides[0] * (n-i));\n\t\tassert(i>0 && i < n);\n\t\tdata[0] = *real;\n\t\tdata[1] = *imag;\n\t\tDEBUG_MESS(6, \"n = %d, i = %d, n - i = %d, rn = %d\", n, i, n - i, rn);\n\t\tDEBUG_MESS(6, \"real = %e, %p, imag = %e, %p\", *real, real, *imag, imag);\n\t\tDEBUG_MESS(5, \"Data[%d] = %e + %e j\", i, data[0], data[1]);\n\t}\n\tdata    =   (double *)(r->data + r->strides[0] * (rn-1));\n\tdata[0] = *((double *)(a->data + a->strides[0] * (n/2)));\n\tdata[1] = 0.0;\n\n\t/* data[n_orig] = 0.0; */\n\tPy_DECREF(a);\n        FUNC_MESS_END();\n\treturn (PyObject *) r;\n  fail:\n\tPy_XDECREF(a);\n\tPy_XDECREF(r);\n\treturn NULL;\n}\nstatic PyObject *\nPyGSL_fft_halfcomplex_radix2_unpack_float(PyObject *self, PyObject *args)\n{\n\n\tPyObject *a_o=NULL;\n\tPyArrayObject *a=NULL, *r=NULL;\n\tint i, n, rn;\n        float *data, *real, *imag;\n\n\tFUNC_MESS_BEGIN();\n\tif(!PyArg_ParseTuple(args, \"O\",&a_o))\n\t\treturn NULL;\n\n\ta = PyGSL_PyArray_PREPARE_gsl_vector_view(a_o, PyArray_FLOAT, 0, -1, 1, NULL);\n\tif(a == NULL)\n\t\tgoto fail;\n\tn = a->dimensions[0];\n\tif(n%2 != 0){\n\t\tgsl_error(\"The length of the vector must be a multiple of two!\",\n\t\t\t  __FILE__, __LINE__, GSL_EDOM);\t\tgoto fail;\n\t}\n\trn = n / 2 + 1;\n\tif((r = (PyArrayObject *) PyGSL_New_Array(1, &rn, PyArray_CFLOAT)) == NULL)\n\t\tgoto fail;\n\tassert(r->dimensions[0] == rn);\n\t/* first one special */\n\tdata = (float *) r->data;\n\tdata[0] = a->data[0];\n\tdata[1] = 0.0;\n\n\tfor(i = 1; i < rn - 1; ++i){\n\t\tdata    = (float *)(r->data + r->strides[0] * i);\n\t\treal    = (float *)(a->data + a->strides[0] * i);\n\t\timag    = (float *)(a->data + a->strides[0] * (n-i));\n\t\tassert(i>0 && i < n);\n\t\tdata[0] = *real;\n\t\tdata[1] = *imag;\n\t\tDEBUG_MESS(6, \"n = %d, i = %d, n - i = %d, rn = %d\", n, i, n - i, rn);\n\t\tDEBUG_MESS(6, \"real = %e, %p, imag = %e, %p\", *real, real, *imag, imag);\n\t\tDEBUG_MESS(5, \"Data[%d] = %e + %e j\", i, data[0], data[1]);\n\t}\n\tdata    =   (float *)(r->data + r->strides[0] * (rn-1));\n\tdata[0] = *((float *)(a->data + a->strides[0] * (n/2)));\n\tdata[1] = 0.0;\n\n\t/* data[n_orig] = 0.0; */\n\tPy_DECREF(a);\n        FUNC_MESS_END();\n\treturn (PyObject *) r;\n  fail:\n\tPy_XDECREF(a);\n\tPy_XDECREF(r);\n\treturn NULL;\n}\n\n# if 0\n        /*\n         * All the arithmetic here will be only possible if the array is\n         * continguous.\n         */\n        if(a->strides[0] == sizeof(double) *2)\n                ;\n        else\n                GSL_ERROR(\"Can only unpack continuous halfcomplex arrays!\", GSL_ESANITY);\n\n        n = a->dimensions[0] - 1;\n\n\tif(n * 2 < n_orig)\n\t\tGSL_ERROR(\"Original size too big!!\", GSL_ESANITY);\n\tif(n_orig %2 == 0)\n\t\t;\n\telse\n\t\tGSL_ERROR(\"Got non even length for radix2!?!\", GSL_ESANITY);\n\n        DEBUG_MESS(2, \"Unpacking a half complex array of size %d, storage size = %d\", \n                   n_orig, a->dimensions[0]);\n\n\n\tdata = (double *) a->data;\n\tdata[0] = data[1];\n\tdata[1] = 0.0;\n\n\t/* Take the shift into account \t++data; */\n\n\t/*\n\t * now data starts were the real array would start withot the shift\n\t * trick\n\t */\n\tfor(i = 1; i < n_orig+1; i++)\n\t\tDEBUG_MESS(5, \"Putting data[%d]= %e\", i, data[i]);\n\n\t/* For two destinct arrays ....\n\tfor(i=1; i< n; ++i){\n\t\tnewdata[i*2] = data[i+1];\n\t\tnewdata[i*2+1] = data[n_orig-i+1];\n\t}\n\t*/\n\n\tfor(i = n_orig/2 - 1; i > 0; --i){\n\t\t/* move the real data backward */\n\t\ttmp1 = data[i+1];\n\t\ttmp2 = data[n_orig-i+1];\n\t\tDEBUG_MESS(5, \"Putting %e + %ej from %d,%d -> %d %d\", tmp1,\n\t\t\t   tmp2, i+1, n_orig-i+1, i*2, i*2+1);\n\n\t\t/* get the imaginary data from the end */\n\t\tif(i >= n)\n\t\t\tGSL_ERROR(\"Out of range for unpack!\", GSL_ESANITY);\n\t\ttmp3 = data[i*2];\n\t\ttmp4 = data[i*2+1];\n\t\tdata[i*2] = tmp1;\n\t\tdata[i*2+1] = tmp2;\t\t\n\t}\n#endif \n\n\n/*\n * A catch all of the various type handling routines. Perhaps too much in one function!\n */\nstatic PyArrayObject *\nPyGSL_Shadow_array(PyObject *shadow, PyObject *master,  enum pygsl_fft_mode mode)\n{\n\tPyArrayObject * ret = NULL, *s=NULL, *m=NULL;\n\tint line = -1;\n\t\n\t/* Check if I got a return array */\n\tif(!PyArray_Check(master)){\n\t\tline = __LINE__ - 1;\n\t\tgoto fail;\n\t}\n\tm = (PyArrayObject *) master;\n\tif(shadow == NULL){\n\t\tFUNC_MESS(\"Generating an output array\");\n\t\tret =  (PyArrayObject *) PyGSL_Copy_Array(m);\n\t\tif(ret == NULL){\n\t\t\tline = __LINE__ -2;\n\t\t\tgoto fail;\n\t\t}\n\t} else {\t\t\n\t\tif (shadow ==  master) {\n\t\t\tPy_INCREF(shadow);\n\t\t\tret = m;\n\t\t}else{\t\n\t\t\tFUNC_MESS(\"Copying input to output array\");\n\t\t\t/* Check if it is an array of the approbriate size */\n\t\t\ts = (PyArrayObject *) shadow;\n\t\t\tif((PyArray_Check(s)) && (s->nd == 1 ) \n\t\t\t   && (s->descr->type_num == m->descr->type_num) \n\t\t\t   && (s->dimensions[0] == m->dimensions[0])){\n\t\t\t\tPy_INCREF(s);\n\t\t\t\tret = (PyArrayObject *) s;\n\t\t\t} else {\n\t\t\t\tgsl_error(\"The return array must be of approbriate size and type!\", \n\t\t\t\t\t  filename, __LINE__, GSL_EINVAL);\n\t\t\t\tline = __LINE__ -7;\n\t\t\t\tgoto fail;\n\t\t\t}\n\t\t\tif(PyGSL_ERROR_FLAG(PyGSL_copy_complex_to_complex(s, m, mode) != GSL_SUCCESS)){\n\t\t\t\tline = __LINE__ -1;\n\t\t\t\tgoto fail;\t\t\t\n\t\t\t}\n\t\t}\n\t}\n\treturn ret;\n  fail:\n\tPyGSL_add_traceback(module, filename, __FUNCTION__, line);\n\treturn NULL;\n}\n\nstatic int\nPyGSL_guess_halfcomplex_length(PyArrayObject *a, int length, double eps,  enum pygsl_fft_mode mode)\n{\n\tint n, call_n = -1;\n\tvoid *v;\n\n\tn = a->dimensions[0];\n\tif(length == -1){\n\t\t/* length was not given, try to guess */\n\t\tv = (a->data + a->strides[0] * (n - 1));\n\t\tif(gsl_fcmp(PyGSL_FFT_MODE_SWITCH(mode, ((double *)v)[1], ((float *)v)[1]), 0,  eps) == 0){\n\t\t\tcall_n = n*2-2;\n\t\t}else{\n\t\t\t/* \n\t\t\t * The last element was close to zero, thus I assume\n\t\t\t *  that I got  original data of even length.\n\t\t\t */\n\t\t\tcall_n = n*2-1;\n\t\t}\t\t\t\n\t}else if(length < -1){\n\t\tgsl_error(\"The given length must be a positive number!\",\n\t\t\t  __FILE__, __LINE__, GSL_EINVAL);\n\t\treturn length;\n\t}else{\n\t\tcall_n = length;\n\t}\n\tDEBUG_MESS(5, \"Using a length of %d\", call_n);\n\treturn call_n;\n\n}\n\nstatic PyObject *\nPyGSL_fft_halfcomplex(PyObject *self, PyObject *args, transform * transform,  enum pygsl_fft_mode mode)\n{\n\tPyObject *data = NULL, *s_o= NULL, *t_o = NULL;\n\tPyArrayObject *a = NULL, *r=NULL;\n\t\n\tint strides=0;\n\tint flag, call_n, return_n, length=-1;\n\tint line = -1;\n\tdouble eps=1e-6;\n\n\tFUNC_MESS_BEGIN();\n\n\tif(! PyArg_ParseTuple(args, \"O|iOOd\",&data, &length, &s_o, &t_o, &eps)){\n\t\treturn NULL;\n\t}\n\t\n\ta = PyGSL_PyArray_PREPARE_gsl_vector_view(data, PyGSL_FFT_MODE_SWITCH(mode, PyArray_CDOUBLE, PyArray_CFLOAT), 0, -1, 1, NULL);\n\tif(a == NULL)\n\t\treturn NULL;\n\tcall_n = PyGSL_guess_halfcomplex_length(a, length, eps, mode);\n\tif(call_n < 0)\n\t\tgoto fail;\n\treturn_n = call_n;\n\n\tPyGSL_fft_helpers_alloc(s_o, t_o,  PyGSL_FFT_MODE_SWITCH(mode,  halfcomplex_helpers, halfcomplex_helpers_float));\n\t\n\n\tr = (PyArrayObject *) PyGSL_New_Array(1, &return_n, PyArray_DOUBLE);\t\t\t\n\tif(r == NULL){\n\t\tline = __LINE__ - 2;\n\t\tgoto fail;\n\t}\n\tif(PyGSL_ERROR_FLAG(PyGSL_copy_halfcomplex_to_real(r, a, eps, mode) != GSL_SUCCESS)){\n\t\tline = __LINE__ - 1;\n\t\tgoto fail;\t\t\t\n\t}\n\n\tflag = PyGSL_STRIDE_RECALC(r->strides[0], sizeof(double), &strides);\n\tif(flag != GSL_SUCCESS){\n\t\tline = __LINE__ - 2;\n\t\tgoto fail;\n\t}\n\n\tflag = transform((double *)(r->data), strides, call_n, table, space);\n\tif(PyGSL_ERROR_FLAG(flag) != GSL_SUCCESS){\n\t\tline = __LINE__ - 2;\n\t\tgoto fail;\n\t}\n\tPyGSL_fft_helpers_free(PyGSL_FFT_MODE_SWITCH(mode,  halfcomplex_helpers, halfcomplex_helpers_float));\n\tPy_DECREF(a);\n\tFUNC_MESS_END();\n\treturn (PyObject *) r;\n\n  fail:\n\tFUNC_MESS(\"Fail\");\n\tPyGSL_add_traceback(module, filename, __FUNCTION__, line);\n\tPyGSL_fft_helpers_free(PyGSL_FFT_MODE_SWITCH(mode,  halfcomplex_helpers, halfcomplex_helpers_float));\n\tPy_XDECREF(a);\n\tPy_XDECREF(r);\n\treturn NULL;\n}\n\nstatic PyObject *\nPyGSL_fft_halfcomplex_radix2(PyObject *self, PyObject *args, transform_r2 * transform,  enum pygsl_fft_mode mode)\n{\n\tPyObject *data = NULL;\n\tPyArrayObject *a = NULL, *r=NULL;\n\t\n\tint strides=0;\n\tint flag, call_n, return_n;\n\tint line = -1;\n\n\tFUNC_MESS_BEGIN();\n\n\tif(! PyArg_ParseTuple(args, \"O\", &data)){\n\t\treturn NULL;\n\t}\n\t\n\ta = PyGSL_PyArray_PREPARE_gsl_vector_view(data, PyArray_CDOUBLE, 0, -1, 1, NULL);\n\tif(a == NULL)\n\t\treturn NULL;\n\tcall_n = a->dimensions[0];\n\treturn_n = call_n;\n\n\tr = (PyArrayObject *) PyGSL_Copy_Array(a);\n\tif(r == NULL){\n\t\tline = __LINE__ - 2;\n\t\tgoto fail;\n\t}\n\tflag = PyGSL_STRIDE_RECALC(r->strides[0], sizeof(double), &strides);\n\tif(flag != GSL_SUCCESS){\n\t\tline = __LINE__ - 2;\n\t\tgoto fail;\n\t}\n\n\tflag = transform((double *)(r->data), strides, call_n);\n\tif(PyGSL_ERROR_FLAG(flag) != GSL_SUCCESS){\n\t\tline = __LINE__ - 2;\n\t\tgoto fail;\n\t}\n\tPy_DECREF(a);\n\tFUNC_MESS_END();\n\treturn (PyObject *) r;\n\n  fail:\n\tFUNC_MESS(\"Fail\");\n\tPyGSL_add_traceback(module, filename, __FUNCTION__, line);\n\tPy_XDECREF(a);\n\tPy_XDECREF(r);\n\treturn NULL;\n}\n\nstatic PyObject *\nPyGSL_fft_real(PyObject *self, PyObject *args, transform * transform,  enum pygsl_fft_mode mode)\n{\n\tPyObject *data = NULL, *s_o= NULL, *t_o = NULL;\n\tPyArrayObject *a = NULL, *r=NULL;\n\t\n\tgsl_fft_real_workspace  *space=NULL;\n\tgsl_fft_real_wavetable  *table=NULL;\n\tint strides=0, n=0, line=-1;\n\tint free_space = 0, free_table=0, flag, call_n, return_n;\n\n\n\tFUNC_MESS_BEGIN();\n\n\tif(! PyArg_ParseTuple(args, \"O|OO\", &data, &s_o, &t_o)){\n\t\treturn NULL;\n\t}\n\t\n\ta = PyGSL_PyArray_PREPARE_gsl_vector_view(data, PyArray_DOUBLE, 0, -1, 1, NULL);\n\tif(a == NULL)\n\t\treturn NULL;\n\tn = a->dimensions[0];\n\tcall_n = n;\n\treturn_n = n/2 + 1;\n\n\tif(s_o){\n\t\tflag = PyGSL_real_fft_work_space_check(s_o);\n\t\tif(flag){\n\t\t\tspace = ((PyGSL_fft_space * )s_o) ->space.rws;\n\t\t} else {\n\t\t\tline = __LINE__ -5;\n\t\t\tgsl_error(\"Need a pygsl fft space!\", filename, __LINE__ - 5, GSL_EINVAL);\n\t\t\tgoto fail;\n\t\t}\n\t}\n\n\tif(t_o){\n\t\tflag = PyGSL_real_fft_wave_table_check(t_o);\n\t\tif(flag){\n\t\t\ttable = ((PyGSL_fft_space * )t_o) ->space.rwt;\n\t\t} else {\n\t\t\tline = __LINE__ -5;\n\t\t\tgsl_error(\"Need a pygsl fft table!\", filename, __LINE__ - 5, GSL_EINVAL);\n\t\t\tgoto fail;\n\t\t}\n\t}\n\n\t/* Check for the approbriate type and initialise it!*/\n\tif(space == NULL || table == NULL){\n\t\t/* Store if I need to free these arrays */\n\t\tfree_space = (space == NULL) ? 1 : 0;\n\t\tfree_table = (table == NULL) ? 1 : 0;\n\t\tif(!space) space = gsl_fft_real_workspace_alloc(call_n);\n\t\tif(!table) table = gsl_fft_real_wavetable_alloc(call_n);\n\t\tif(!space || !table)\n\t\t\tgoto fail;\n\n\t}\n\t\n\t/* Check if I got a return array */\n\tr = (PyArrayObject *) PyGSL_New_Array(1, &return_n, PyArray_CDOUBLE);\t\t\t\n\tif(r == NULL){\n\t\tline = __LINE__ -2;\n\t\tgoto fail;\n\t}\n\tif(PyGSL_copy_real_to_complex(r, a, MODE_DOUBLE) != GSL_SUCCESS){\n\t\tline = __LINE__ -1;\n\t\tgoto fail;\t\t\t\n\t}\n\tflag = PyGSL_STRIDE_RECALC(r->strides[0], sizeof(double) * 2, &strides);\n\tif(flag != GSL_SUCCESS){\n\t\tline = __LINE__ -2;\n\t\tgoto fail;\n\t}\n\n\tFUNC_MESS(\"Transforming ...\");\n\tflag = transform(((double *) r->data)+1, strides, call_n, table, space);\n\tFUNC_MESS(\" ... Done\");\n\tif(PyGSL_ERROR_FLAG(flag) != GSL_SUCCESS){\n\t\tline = __LINE__ -2;\n\t\tgoto fail;\n\t}\n\t\n         /* Rearange half complex data */\n\tif(PyGSL_fft_halfcomplex_unpack(r, call_n, mode) != GSL_SUCCESS){\n\t\tline = __LINE__ -1;\n\t\tgoto fail;\n\t}\n\n\tif(free_space == 1 && space != NULL) gsl_fft_real_workspace_free(space);\n\tif(free_table == 1 && table != NULL) gsl_fft_real_wavetable_free(table);\n\tPy_DECREF(a);\n\tFUNC_MESS_END();\n\treturn (PyObject *) r;\n\n  fail:\n\tFUNC_MESS(\"Fail\");\n\tPyGSL_add_traceback(module, filename, __FUNCTION__, line);\n\tif(free_space == 1 && space != NULL) gsl_fft_real_workspace_free(space);\n\tif(free_table == 1 && table != NULL) gsl_fft_real_wavetable_free(table);\n\tPy_XDECREF(a);\n\tPy_XDECREF(r);\n\treturn NULL;\n}\n\nstatic PyObject *\nPyGSL_fft_real_radix2(PyObject *self, PyObject *args, transform_r2 * transform,  enum pygsl_fft_mode mode)\n{\n\tPyObject *data = NULL;\n\tPyArrayObject *a = NULL, *r=NULL;\n\t\n\tint strides=0, n=0, line=-1;\n\tint  flag, call_n, return_n;\n\n\n\tFUNC_MESS_BEGIN();\n\n\tif(! PyArg_ParseTuple(args, \"O\", &data)){\n\t\treturn NULL;\n\t}\n\t\n\ta = PyGSL_PyArray_PREPARE_gsl_vector_view(data, PyArray_DOUBLE, 0, -1, 1, NULL);\n\tif(a == NULL)\n\t\treturn NULL;\n\tn = a->dimensions[0];\n\tcall_n = n;\n\treturn_n = n;\n\n\t\n\t\n\t/* Check if I got a return array */\n\tr = (PyArrayObject *) PyGSL_Copy_Array(a);\n\tif(r == NULL)\n\t\tgoto fail;\n\n\tflag = PyGSL_STRIDE_RECALC(r->strides[0], sizeof(double), &strides);\n\tif(flag != GSL_SUCCESS){\n\t\tline = __LINE__ -2;\n\t\tgoto fail;\n\t}\n\tflag = transform(((double *)r->data), strides, call_n);\n\tif(PyGSL_ERROR_FLAG(flag) != GSL_SUCCESS){\n\t\tline = __LINE__ -2;\n\t\tgoto fail;\n\t}\n\t/* No rearange handled in a separate function ... */\n\tPy_DECREF(a);\n\tFUNC_MESS_END();\n\treturn (PyObject *) r;\n\n  fail:\n\tFUNC_MESS(\"Fail\");\n\tPyGSL_add_traceback(module, filename, __FUNCTION__, line);\n\tPy_XDECREF(a);\n\tPy_XDECREF(r);\n\treturn NULL;\n}\n\nstatic PyObject *\nPyGSL_complex_fft_(PyObject *self, PyObject *args, transform * transform,  enum pygsl_fft_mode mode)\n{\n\tPyObject *data = NULL, *s_o= NULL, *t_o = NULL, *ret=NULL;\n\tPyArrayObject *a = NULL, *r=NULL;\n\t\n\tgsl_fft_complex_workspace  *space=NULL;\n\tgsl_fft_complex_wavetable  *table=NULL;\n\tint strides=0, n=0;\n\tint free_space = 0, free_table=0, flag, call_n;\n\n\n\tFUNC_MESS_BEGIN();\n\tif(!PyArg_ParseTuple(args, \"O|OOO\", &data, &s_o, &t_o, &ret)){\n\t\treturn NULL;\n\t}\n\t\n\ta = PyGSL_PyArray_PREPARE_gsl_vector_view(data, PyArray_CDOUBLE, 0, -1, 1, NULL);\n\tif(a == NULL)\n\t\tgoto fail;\n\n\tn = a->dimensions[0];\n\tcall_n = n;\n\n\tr = PyGSL_Shadow_array((PyObject *) ret, (PyObject *) a, mode);\n\tif(r == NULL)\n\t\tgoto fail;\n\t/* \n\t *  Return n is used to allocate an array, while call_n is the length passed on.\n\t *  This is necessary as the halfcomplex transform needs space to store the nyquist \n\t *  frequency.\n\t *\n\t *  The following assert is protecting against surprises of missing space.\n\t */\n\t/*\n\tif(call_n > return_n){\n\t\tfprintf(stderr, \"In %s at Line %d call_n = %d, return_n = %d\",\n\t\t\tfilename, __LINE__, call_n, return_n);\n\t\tgsl_error(\"call_n larger than return_n!\", filename, __LINE__ - 2, GSL_ESANITY); goto fail;\n\t}\n\t*/\n\tif(s_o){\t\t\n\t\tflag = PyGSL_complex_fft_work_space_check(s_o);\n\t\tif(flag){\n\t\t\tspace = ((PyGSL_fft_space *) s_o)->space.cws;\n\t\t} else {\n\t\t\tgsl_error(\"Need a pygsl complex fft space!\", filename, __LINE__, GSL_EINVAL);\n\t\t\tPyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__ - 5);\n\t\t\tgoto fail;\n\t\t}\n\t}\n\t\n\tif(t_o){\n\t\tflag = PyGSL_complex_fft_wave_table_check(t_o);\n\t\tif(flag){\n\t\t\ttable = ((PyGSL_fft_space *) t_o) ->space.cwt;\n\t\t} else {\n\t\t\tgsl_error(\"Need a pygsl complex fft wave table!\", filename, __LINE__, GSL_EINVAL);\n\t\t\tPyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__ - 5);\n\t\t\tgoto fail;\n\t\t}\n\t}\n\t\n        /*\n\t * Check, if I have to init the the tables\n\t */\n\tif(space == NULL || table == NULL){\n\t\t/* Store if I need to free these arrays */\n\t\tfree_space = (space == NULL) ? 1 : 0;\n\t\tfree_table = (table == NULL) ? 1 : 0;\n\t\tif(!space) space = gsl_fft_complex_workspace_alloc(call_n);\n\t\tif(!table) table = gsl_fft_complex_wavetable_alloc(call_n);\n\t\tif(!space || !table)\n\t\t\tgoto fail;\n\t}\n\t\n\n\tflag = PyGSL_STRIDE_RECALC(r->strides[0], sizeof(double) * 2, &strides);\n\tif(flag != GSL_SUCCESS){\n\t\tgoto fail;\n\t}\n\n\tDEBUG_MESS(2, \"Array is at %p data at %p strides = %d length = %d\", (void *) r, (void *) r->data, \n\t\t   r->strides[0], r->dimensions[0]);\n\tDEBUG_MESS(2, \"Starting a transform with an array of a size of %d and a stride of %d\", call_n, strides);\n\n\tflag = transform((double *) r->data, strides, call_n, table, space);\n\tif(PyGSL_ERROR_FLAG(flag) != GSL_SUCCESS){\n\t\tgoto fail;\n\t}\n\tif(free_space == 1 && space != NULL) gsl_fft_complex_workspace_free(space);\n\tif(free_table == 1 && table != NULL) gsl_fft_complex_wavetable_free(table);\n\tPy_DECREF(a);\n\tFUNC_MESS_END();\n\treturn (PyObject *) r;\n\n  fail:\n\tFUNC_MESS(\"Fail\");\n\tPy_XDECREF(a);\n\tPy_XDECREF(r);\n\tif(free_space == 1 && space != NULL) gsl_fft_complex_workspace_free(space);\n\tif(free_table == 1 && table != NULL) gsl_fft_complex_wavetable_free(table);\n\treturn NULL;\n}\n\nstatic PyObject *\nPyGSL_complex_fft_radix2(PyObject *self, PyObject *args, transform_r2 * transform,  enum pygsl_fft_mode mode)\n{\n\tPyObject *data = NULL, *ret=NULL;\n\tPyArrayObject *a = NULL, *r=NULL;\n\t\n\tint strides=0, n=0, flag;\n\n\n\tFUNC_MESS_BEGIN();\n\tif(!PyArg_ParseTuple(args, \"O|O\", &data,  &ret)){\n\t\treturn NULL;\n\t}\n\t\n\ta = PyGSL_PyArray_PREPARE_gsl_vector_view(data, PyArray_CDOUBLE, 0, -1, 1, NULL);\n\tif(a == NULL)\n\t\tgoto fail;\n\tn = a->dimensions[0];\n\tr = PyGSL_Shadow_array((PyObject *) ret, (PyObject *) a, mode);\n\tif(r == NULL)\n\t\tgoto fail;\n\tflag = PyGSL_STRIDE_RECALC(r->strides[0], sizeof(double) * 2, &strides);\n\tif(flag != GSL_SUCCESS){\n\t\tgoto fail;\n\t}\n\n\tDEBUG_MESS(2, \"Array is at %p data at %p strides = %d length = %d\", (void *) r, (void *) r->data, \n\t\t   r->strides[0], r->dimensions[0]);\n\tDEBUG_MESS(2, \"Starting a transform with an array of a size of %d and a stride of %d\", n, strides);\n\tflag = transform((double *) r->data, strides, n);\n\tif(PyGSL_ERROR_FLAG(flag) != GSL_SUCCESS){\n\t\tgoto fail;\n\t}\n\tPy_DECREF(a);\n\tFUNC_MESS_END();\n\treturn (PyObject *) r;\n\n  fail:\n\tFUNC_MESS(\"Fail\");\n\tPy_XDECREF(a);\n\tPy_XDECREF(r);\n\treturn NULL;\n}\n\n/*\n int gsl_fft_real_transform (double DATA[], size_t STRIDE,\n          size_t N, const gsl_fft_real_wavetable * WAVETABLE,\n          gsl_fft_real_workspace * WORK)\n int gsl_fft_halfcomplex_transform (double DATA[], size_t\n          STRIDE, size_t N, const gsl_fft_halfcomplex_wavetable *\n          WAVETABLE, gsl_fft_real_workspace * WORK)\n*/\n\n#define PyGSL_COMPLEX(direction) \\\n        static PyObject * \\\n\tPyGSL_complex_fft_ ## direction(PyObject *self, PyObject *args){\\\n        PyObject *r;\\\n        FUNC_MESS_BEGIN();\\\n\tr = PyGSL_complex_fft_(self, args, (transform * )gsl_fft_complex_ ## direction, MODE_DOUBLE); \\\n        FUNC_MESS_END();\\\n\treturn r;\\\n        }\n\nPyGSL_COMPLEX(forward)\nPyGSL_COMPLEX(backward)\nPyGSL_COMPLEX(inverse)\n\n#define PyGSL_COMPLEX_RADIX2(direction) \\\n        static PyObject * \\\n\tPyGSL_complex_fft_radix2_ ## direction(PyObject *self, PyObject *args){\\\n        PyObject *r;\\\n        FUNC_MESS_BEGIN();\\\n\tr = PyGSL_complex_fft_radix2(self, args, (transform_r2 * )gsl_fft_complex_radix2_ ## direction, MODE_DOUBLE); \\\n        FUNC_MESS_END();\\\n\treturn r;\\\n        }\n\nPyGSL_COMPLEX_RADIX2(forward)\nPyGSL_COMPLEX_RADIX2(backward)\nPyGSL_COMPLEX_RADIX2(inverse)\n\nPyGSL_COMPLEX_RADIX2(dif_forward)\nPyGSL_COMPLEX_RADIX2(dif_backward)\nPyGSL_COMPLEX_RADIX2(dif_inverse)\n\n#define PyGSL_REAL_RADIX2(direction) \\\n        static PyObject * \\\n\tPyGSL_real_fft_radix2_ ## direction(PyObject *self, PyObject *args){\\\n        PyObject *r;\\\n        FUNC_MESS_BEGIN();\\\n\tr = PyGSL_fft_real_radix2(self, args, (transform_r2 * )gsl_fft_real_radix2_ ## direction, MODE_DOUBLE); \\\n        FUNC_MESS_END();\\\n\treturn r;\\\n        }\n\nPyGSL_REAL_RADIX2(transform)\n\n#define PyGSL_REAL(direction) \\\n        static PyObject * \\\n\tPyGSL_real_fft_ ## direction(PyObject *self, PyObject *args){\\\n        PyObject *r;\\\n        FUNC_MESS_BEGIN();\\\n\tr = PyGSL_fft_real(self, args, (transform * )gsl_fft_real_ ## direction, MODE_DOUBLE); \\\n        FUNC_MESS_END();\\\n\treturn r;\\\n        }\n\nPyGSL_REAL(transform)\n\n#define PyGSL_HALFCOMPLEX(direction) \\\n        static PyObject * \\\n\tPyGSL_halfcomplex_fft_ ## direction(PyObject *self, PyObject *args){\\\n\treturn PyGSL_fft_halfcomplex(self, args, (transform * )gsl_fft_halfcomplex_ ## direction, MODE_DOUBLE); \\\n        }\n\nPyGSL_HALFCOMPLEX(transform)\nPyGSL_HALFCOMPLEX(inverse)\n\n#define PyGSL_HALFCOMPLEX_RADIX2(direction) \\\n        static PyObject * \\\n\tPyGSL_halfcomplex_fft_radix2_ ## direction(PyObject *self, PyObject *args){\\\n\treturn PyGSL_fft_halfcomplex_radix2(self, args, (transform_r2 * )gsl_fft_halfcomplex_radix2_ ## direction, MODE_DOUBLE); \\\n        }\n\nPyGSL_HALFCOMPLEX_RADIX2(transform)\nPyGSL_HALFCOMPLEX_RADIX2(inverse)\n\nstatic const char fft_module_doc[] = \"\\\nWrapper for the FFT Module of the GSL Library\\n\\\n\\n\\\n\";\nstatic const char cws_doc[] = \"\\\nComplex Workspace\\n\\\n\\n\\\nNeeded as working space for mixed radix routines.\\n\\\n\\n\\\nInput:\\n\\\n    n ... Length of the data to transform\\n\\\n\";\nstatic const char cwt_doc[] = \"\\\nComplex Wavetable\\n\\\n\\n\\\n   Stores the precomputed trigonometric functions\\n\\\nInput:\\n\\\n    n ... Length of the data to transform\\n\\\n\";\nstatic const char rws_doc[] = \"\\\nReal Workspace\\n\\\n\\n\\\nNeeded as working space for mixed radix routines.\\n\\\n\\n\\\nInput:\\n\\\n    n ... Length of the data to transform\\n\\\n\";\nstatic const char rwt_doc[] = \"\\\nReal Wavetable\\n\\\n\\n\\\n   Stores the precomputed trigonometric functions\\n\\\nInput:\\n\\\n    n ... Length of the data to transform\\n\\\n\";\n\nstatic const char hcwt_doc[] = \"\\\nHalf Complex Wavetable\\n\\\n\\n\\\n   Stores the precomputed trigonometric functions\\n\\\nInput:\\n\\\n    n ... Length of the data to transform\\n\\\n\";\n#define TRANSFORM_INPUT \"\\\nInput:\\n\\\n      data ... an array of complex numbers\\n\\\n\\n\\\nOptional Input:\\n\\\n      If these objects are not provided, they will be generated by the\\n\\\n      function automatically.\\n\\\n\\n\\\n      space  ... a workspace of approbriate type and size\\n\\\n      table  ... a wavetable of approbriate type and size\\n\\\n      output ... array to store the output into. GSL computes the FFT\\n\\\n                 in place. So if this array is provided, the wrapper\\n\\\n                 will use this array as output array. If the input and\\n\\\n                 output array are identical no internal copy will be\\n\\\n                 made. \\n\\\n                 This works only for the complex transform types!\\n\"\n\n#define TRANSFORM_INPUT_RADIX2 \"\\\nInput:\\n\\\n      data ... an array of complex numbers\\n\\\n\\n\\\nOptional Input:\\n\\\n      If these objects are not provided, they will be generated by the\\n\\\n      function automatically.\\n\\\n\\n\\\n      output ... array to store the output into. GSL computes the FFT\\n\\\n                 in place. So if this array is provided, the wrapper\\n\\\n                 will use this array as output array. If the input and\\n\\\n                 output array are identical no internal copy will be\\n\\\n                 made. \\n\\\n                 This works only for the complex transform types!\\n\"\n\n#define TRANSFORM_INPUT_REAL \"\\\nInput:\\n\\\n      data ... an array of real numbers\\n\\\n\\n\\\nOptional Input:\\n\\\n      If these objects are not provided, they will be generated by the\\n\\\n      function automatically.\\n\\\n\\n\\\n      space  ... a workspace of approbriate type and size\\n\\\n      table  ... a wavetable of approbriate type and size\\n\\\n      output ... array to store the output into. GSL computes the FFT\\n\\\n                 in place. So if this array is provided, the wrapper\\n\\\n                 will use this array as output array. If the input and\\n\\\n                 output array are identical no internal copy will be\\n\\\n                 made. \\n\\\n                 This works only for the complex transform types!\\n\"\n\n#define TRANSFORM_INPUT_REAL_RADIX2 \"\\\nInput:\\n\\\n      data ... an array of real numbers\\n\\\n\\n\\\nOutput:\\n\\\n      the transformed data in its special storage. Halfcomplex data\\n\\\n      in an real array. Use halfcomplex_radix2_unpack to transform it\\n\\\n      into an approbriate complex array.\\n\\\n\"\n\n#define TRANSFORM_INPUT_HALFCOMPLEX \"\\\nInput:\\n\\\n      data ... an array of complex numbers\\n\\\n\\n\\\nOptional Input:\\n\\\n      If these objects are not provided, they will be generated by the\\n\\\n      function automatically.\\n\\\n\\n\\\n      n      ... length of the real array. From the complex input I can not\\n\\\n                 compute the original length if it was odd or even. Thus I \\n\\\n                 allow to give the input here. If not given the routine will guess\\n\\\n                 the input length. If the last imaginary part is zero it will\\n\\\n                 assume an real output array of even length\\n\\\n      space  ... a workspace of approbriate type and size\\n\\\n      table  ... a wavetable of approbriate type and size\\n\\\n      eps    ... epsilon to use in the comparisons (default 1e-8)\\n\\\n\"\n\n#define TRANSFORM_INPUT_HALFCOMPLEX_RADIX2 \"\\\nInput:\\n\\\n      data ... an array of real data containing the complex data\\n\\\n               as required by this transform. See the GSL Reference Document\\n\\\n\\n\\\n\"\n\nstatic const char cf_doc[] = \"\\\nComplex forward transform\\n\\\n\" TRANSFORM_INPUT;\n\nstatic const char cb_doc[] = \"\\\nComplex backward transform\\n\\\n\\n\\\nThe output is not scaled!\\n\\\n\" TRANSFORM_INPUT;\n\nstatic const char ci_doc[] = \"\\\nComplex inverse transform\\n\\\n\\n\\\nThe output is to scale.\\n\\\n\" TRANSFORM_INPUT;\n\nstatic const char cf_doc_r2[] = \"\\\nComplex forward radix2 transform\\n\\\n\" TRANSFORM_INPUT_RADIX2;\n\nstatic const char cb_doc_r2[] = \"\\\nComplex backward radix2 transform\\n\\\n\\n\\\nThe output is not scaled!\\n\\\n\" TRANSFORM_INPUT_RADIX2;\n\nstatic const char ci_doc_r2[] = \"\\\nComplex inverse radix2 transform\\n\\\n\\n\\\nThe output is to scale.\\n\\\n\" TRANSFORM_INPUT_RADIX2;\n\nstatic const char cf_doc_r2_dif[] = \"\\\nComplex forward radix2 decimation-in-frequency transform\\n\\\n\" TRANSFORM_INPUT_RADIX2;\n\nstatic const char cb_doc_r2_dif[] = \"\\\nComplex backward radix2 decimation-in-frequency transform\\n\\\n\\n\\\nThe output is not scaled!\\n\\\n\" TRANSFORM_INPUT_RADIX2;\n\nstatic const char ci_doc_r2_dif[] = \"\\\nComplex inverse radix2 decimation-in-frequency transform\\n\\\n\\n\\\nThe output is to scale.\\n\\\n\" TRANSFORM_INPUT_RADIX2;\n\nstatic const char rt_doc[] = \"\\\nReal transform\\n\\\n\" TRANSFORM_INPUT_REAL;\n\nstatic const char hc_doc[] = \"\\\nHalf complex transform\\n\\\n\\n\\\nThe output is not scaled!\\n\\\n\" TRANSFORM_INPUT_HALFCOMPLEX;\n\nstatic const char hi_doc[] = \"\\\nHalf complex inverse\\n\\\n\" TRANSFORM_INPUT_HALFCOMPLEX;\n\nstatic const char rt_doc_r2[] = \"\\\nReal radix2 transform\\n\\\n\" TRANSFORM_INPUT_REAL_RADIX2;\n\nstatic const char hc_doc_r2[] = \"\\\nHalf complex  radix2 transform\\n\\\n\\n\\\nThe output is not scaled!\\n\\\n\" TRANSFORM_INPUT_HALFCOMPLEX_RADIX2;\n\nstatic const char hi_doc_r2[] = \"\\\nHalf complex  radix2 inverse\\n\\\n\" TRANSFORM_INPUT_HALFCOMPLEX_RADIX2;\n\nstatic const char un_doc_r2[] = \"\\\nUnpack the frequency data from the output of a real radix 2 transform to an approbriate complex array.\\n\\\n\";\n\nstatic PyMethodDef fftMethods[] = {\n\t{\"complex_workspace\",     PyGSL_fft_space_init_COMPLEX_WORKSPACE,      METH_VARARGS, (char*)cws_doc},\n\t{\"complex_wavetable\",     PyGSL_fft_space_init_COMPLEX_WAVETABLE,      METH_VARARGS, (char*)cwt_doc},\n\t{\"real_workspace\",        PyGSL_fft_space_init_REAL_WORKSPACE,         METH_VARARGS, (char*)rws_doc},\n\t{\"real_wavetable\",        PyGSL_fft_space_init_REAL_WAVETABLE,         METH_VARARGS, (char*)rwt_doc},\n\t{\"halfcomplex_wavetable\", PyGSL_fft_space_init_HALFCOMPLEX_WAVETABLE,  METH_VARARGS, (char*)hcwt_doc},\n\t{\"complex_workspace_float\",     PyGSL_fft_space_init_COMPLEX_WORKSPACE_FLOAT,      METH_VARARGS, (char*)cws_doc},\n\t{\"complex_wavetable_float\",     PyGSL_fft_space_init_COMPLEX_WAVETABLE_FLOAT,      METH_VARARGS, (char*)cwt_doc},\n\t{\"real_workspace_float\",        PyGSL_fft_space_init_REAL_WORKSPACE_FLOAT,         METH_VARARGS, (char*)rws_doc},\n\t{\"real_wavetable_float\",        PyGSL_fft_space_init_REAL_WAVETABLE_FLOAT,         METH_VARARGS, (char*)rwt_doc},\n\t{\"halfcomplex_wavetable_float\", PyGSL_fft_space_init_HALFCOMPLEX_WAVETABLE_FLOAT,  METH_VARARGS, (char*)hcwt_doc},\n\t{\"complex_forward\",             PyGSL_complex_fft_forward,             METH_VARARGS, (char*)cf_doc},\t\n\t{\"complex_backward\",            PyGSL_complex_fft_backward,            METH_VARARGS, (char*)cb_doc},\t\n\t{\"complex_inverse\",             PyGSL_complex_fft_inverse,             METH_VARARGS, (char*)ci_doc},\t\n\t{\"complex_radix2_forward\",      PyGSL_complex_fft_radix2_forward,      METH_VARARGS, (char*)cf_doc_r2},\t\n\t{\"complex_radix2_backward\",     PyGSL_complex_fft_radix2_backward,     METH_VARARGS, (char*)cb_doc_r2},\t\n\t{\"complex_radix2_inverse\",      PyGSL_complex_fft_radix2_inverse,      METH_VARARGS, (char*)ci_doc_r2},\t\n\t{\"complex_radix2_dif_forward\",  PyGSL_complex_fft_radix2_dif_forward,  METH_VARARGS, (char*)cf_doc_r2_dif},\t\n\t{\"complex_radix2_dif_backward\", PyGSL_complex_fft_radix2_dif_backward, METH_VARARGS, (char*)cb_doc_r2_dif},\t\n\t{\"complex_radix2_dif_inverse\",  PyGSL_complex_fft_radix2_dif_inverse,  METH_VARARGS, (char*)ci_doc_r2_dif},\t\n\t{\"real_transform\",              PyGSL_real_fft_transform,              METH_VARARGS, (char*)rt_doc},\t\n\t{\"halfcomplex_transform\",       PyGSL_halfcomplex_fft_transform,       METH_VARARGS, (char*)hc_doc},\n\t{\"halfcomplex_inverse\",         PyGSL_halfcomplex_fft_inverse,         METH_VARARGS, (char*)hi_doc},\n\t{\"real_radix2_transform\",       PyGSL_real_fft_radix2_transform,       METH_VARARGS, (char*)rt_doc_r2},\t\n\t{\"halfcomplex_radix2_transform\",PyGSL_halfcomplex_fft_radix2_transform,METH_VARARGS, (char*)hc_doc_r2},\n\t{\"halfcomplex_radix2_inverse\",  PyGSL_halfcomplex_fft_radix2_inverse,  METH_VARARGS, (char*)hi_doc_r2},\n\t{\"halfcomplex_radix2_unpack\",   PyGSL_fft_halfcomplex_radix2_unpack,   METH_VARARGS, (char*)un_doc_r2},\n\t{NULL, NULL} /* Sentinel */\n};\n\nDL_EXPORT(void) initfft(void)\n{\n     \tPyObject *m = NULL, *dict = NULL, *item = NULL;\n\t\n\tPyGSL_fft_space_pytype.ob_type = &PyType_Type;\n\n\tm = Py_InitModule(\"fft\", fftMethods);\n\tmodule = m;\n\timport_array();\n\tinit_pygsl();\n\tif (m == NULL)\n\t\treturn;\n\n\tdict = PyModule_GetDict(m);\n\tif (dict == NULL)\n\t\treturn;\n\t\n\tif (!(item = PyString_FromString(fft_module_doc))){\n\t\tPyErr_SetString(PyExc_ImportError, \n\t\t\t\t\"I could not generate module doc string!\");\n\t\treturn;\n\t}\n\tif (PyDict_SetItemString(dict, \"__doc__\", item) != 0){\n\t\tPyErr_SetString(PyExc_ImportError, \n\t\t\t\t\"I could not init doc string!\");\n\t\treturn;\n\t}\n\n\treturn;\n}\n\n\n/*\n * Local Variables:\n * mode: C\n * c-file-style: \"python\"\n * End:\n */\n", "meta": {"hexsha": "889c3bcfae77f9c58a877c8b7f1bd013f207bbfd", "size": 52160, "ext": "c", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/testing/src/fftfloatmodule.c", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/testing/src/fftfloatmodule.c", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/testing/src/fftfloatmodule.c", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 31.4785757393, "max_line_length": 127, "alphanum_fraction": 0.6679639571, "num_tokens": 15738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207955, "lm_q2_score": 0.04742587536541707, "lm_q1q2_score": 0.02334245318103143}}
{"text": "#pragma once\n\n#include <vector>\n\n#include <gsl-lite/gsl-lite.hpp>\n\n#include <Eigen/Sparse>\n\n#include <thrustshift/CSR.h>\n#include <thrustshift/container-conversion.h>\n#include <thrustshift/managed-vector.h>\n#include <thrustshift/memory-resource.h>\n\nnamespace thrustshift {\n\nnamespace eigen {\n\n//! Return a CSR matrix with the default memory resource of the CSR class\ntemplate <class EigenSparseMatrix>\nauto sparse_mtx2csr(EigenSparseMatrix&& m_) {\n\n\tusing DataType =\n\t    typename std::remove_reference<EigenSparseMatrix>::type::value_type;\n\tusing StorageIndex =\n\t    typename std::remove_reference<EigenSparseMatrix>::type::StorageIndex;\n\t// Create copy because we might modify the container with `makeCompressed`\n\tEigen::SparseMatrix<DataType, Eigen::RowMajor, StorageIndex> m = m_;\n\tm.makeCompressed();\n\tauto m_data = m.data();\n\tauto nnz = m.nonZeros();\n\tauto rows = m.rows();\n\n\tconst DataType* A = &m_data.value(0);\n\tconst StorageIndex* IA = m.outerIndexPtr();\n\tconst StorageIndex* JA = &m_data.index(0);\n\n\tmanaged_vector<DataType> seq_A(A, A + nnz);\n\tmanaged_vector<StorageIndex> seq_JA(JA, JA + nnz);\n\tmanaged_vector<StorageIndex> seq_IA(IA, IA + rows + 1);\n\n\treturn CSR<DataType, StorageIndex>(\n\t    seq_A, seq_JA, seq_IA, gsl_lite::narrow<size_t>(m.cols()));\n}\n\n// Forward declaration to avoid co-dependent headers\ntemplate <class EigenSparseMatrix, class COO_C>\nEigenSparseMatrix coo2sparse_mtx(COO_C&& coo);\n\ntemplate <class EigenSparseMatrix, class CSR_C>\nEigenSparseMatrix csr2sparse_mtx(CSR_C&& csr) {\n\n\tusing DataType =\n\t    typename std::remove_reference<EigenSparseMatrix>::type::value_type;\n\tusing StorageIndex =\n\t    typename std::remove_reference<EigenSparseMatrix>::type::StorageIndex;\n\n\treturn coo2sparse_mtx<EigenSparseMatrix>(\n\t    csr2coo<thrustshift::COO<DataType, StorageIndex>>(\n\t        std::forward<CSR_C>(csr), pmr::default_resource));\n}\n\n} // namespace eigen\n\n} // namespace thrustshift\n", "meta": {"hexsha": "96442b2d1c523fd07c51478c7c55b6af55e89a22", "size": 1918, "ext": "h", "lang": "C", "max_stars_repo_path": "include/thrustshift/eigen3-interface/CSR.h", "max_stars_repo_name": "pauleonix/thrustshift", "max_stars_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-16T13:01:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T13:01:46.000Z", "max_issues_repo_path": "include/thrustshift/eigen3-interface/CSR.h", "max_issues_repo_name": "pauleonix/thrustshift", "max_issues_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-23T14:12:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-17T11:40:04.000Z", "max_forks_repo_path": "include/thrustshift/eigen3-interface/CSR.h", "max_forks_repo_name": "pauleonix/thrustshift", "max_forks_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5076923077, "max_line_length": 75, "alphanum_fraction": 0.7502606882, "num_tokens": 480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.05184546115599978, "lm_q1q2_score": 0.0232989683739351}}
{"text": "/*\n * C version of Diffusive Nested Sampling (DNest4) by Brendon J. Brewer\n *\n * Yan-Rong Li, liyanrong@mail.ihep.ac.cn\n * Jun 30, 2016\n *\n */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n#include <unistd.h>\n#include <math.h>\n#include <float.h>\n#include <mpi.h>\n#include <sys/stat.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n\n#include \"dnest.h\"\n#include \"dnestvars.h\"\n\n/*\n * dnest\n * call this function to do sampling\n * ========================================================\n * arguments:\n * argc:        number of command-line options (mandatory)\n * argv:        command-line options  (mandatory)\n * fptrset:     function set pointers required  (mandatory)\n * num_params:  number of parameters (mandatory)\n * param_range: parameter ranges  (mandatory)\n * prior_type:  prior types  (optional)\n * prior_info:  prior informations  (optional)\n * sample_dir:  output directory for sampling  (mandatory)\n * optfile:     option files  (optional)\n * opts:        options struct. if optfile is empty, use this struct (optional)\n * args:        any other arguments transferred to cdnest.  (optional)\n *              useful when referring to external variables or calling external functions (optional)\n * ========================================================\n * optional arguments can be set to \"NULL\"\n */\ndouble dnest(int argc, char** argv, DNestFptrSet *fptrset, int num_params, \n             double *param_range, int *prior_type, double *prior_info,\n             char *sample_dir, char *optfile, DNestOptions *opts, void *args)\n{\n  int optid;\n\n  MPI_Comm_rank(MPI_COMM_WORLD, &dnest_thistask);\n  MPI_Comm_size(MPI_COMM_WORLD, &dnest_totaltask);\n  \n  if(dnest_thistask == dnest_root)\n  {\n    printf(\"#=======================================================\\n\");\n    printf(\"# Starting CDNest.\\n\");\n    printf(\"# Use %d cores.\\n\", dnest_totaltask);\n  }\n\n  dnest_check_fptrset(fptrset);\n  \n  // cope with argv\n  if(dnest_thistask == dnest_root )\n  {\n    dnest_post_temp = 1.0;\n    dnest_flag_restart = 0;\n    dnest_flag_postprc = 0;\n    dnest_flag_sample_info = 0;\n    dnest_flag_limits = 0;\n\n    strcpy(file_save_restart, \"restart_dnest.txt\");\n    strcpy(dnest_sample_postfix, \"\\0\");\n    strcpy(dnest_sample_tag, \"\\0\");\n\n    opterr = 0;\n    optind = 0;\n    while( (optid = getopt(argc, argv, \"r:s:pt:clx:g:\")) != -1)\n    {\n      switch(optid)\n      {\n        case 'r':\n          dnest_flag_restart = 1;\n          strcpy(file_restart, optarg);\n          printf(\"# Dnest restarts.\\n\");\n          break;\n        case 's':\n          strcpy(file_save_restart, optarg);\n          printf(\"# Dnest sets restart file %s.\\n\", file_save_restart);\n          break;\n        case 'p':\n          dnest_flag_postprc = 1;\n          dnest_post_temp = 1.0;\n          printf(\"# Dnest does postprocess.\\n\");\n          break;\n        case 't':\n          dnest_post_temp = atof(optarg);\n          printf(\"# Dnest sets a temperature %f.\\n\", dnest_post_temp);\n          if(dnest_post_temp == 0.0)\n          {\n            printf(\"# Dnest incorrect option -t %s.\\n\", optarg);\n            exit(0);\n          }\n          if(dnest_post_temp < 1.0)\n          {\n            printf(\"# Dnest temperature should >= 1.0\\n\");\n            exit(0);\n          }\n          break;\n        case 'c':\n          dnest_flag_sample_info = 1;\n          printf(\"# Dnest recalculates sample information.\\n\");\n          break;\n        case 'l':\n          dnest_flag_limits = 1;\n          printf(\"# Dnest level-dependent sampling.\\n\");\n          break;\n        case 'x':\n          strcpy(dnest_sample_postfix, optarg);\n          printf(\"# Dnest sets sample postfix %s.\\n\", dnest_sample_postfix);\n          break;\n        case 'g':\n          strcpy(dnest_sample_tag, optarg);\n          printf(\"# Dnest sets sample tag %s.\\n\", dnest_sample_tag);\n          break;\n        case '?':\n          printf(\"# Dnest incorrect option -%c %s.\\n\", optopt, optarg);\n          exit(0);\n          break;\n        default:\n          break;\n      }\n    }\n  }\n  \n  MPI_Bcast(&dnest_flag_restart, 1, MPI_INT, dnest_root, MPI_COMM_WORLD);\n  MPI_Bcast(&dnest_flag_postprc, 1, MPI_INT, dnest_root, MPI_COMM_WORLD);\n  MPI_Bcast(&dnest_flag_sample_info, 1, MPI_INT,dnest_root, MPI_COMM_WORLD);\n  MPI_Bcast(&dnest_post_temp, 1, MPI_DOUBLE, dnest_root, MPI_COMM_WORLD);\n  MPI_Bcast(&dnest_flag_limits, 1, MPI_INT, dnest_root, MPI_COMM_WORLD);\n\n  setup(argc, argv, fptrset, num_params, param_range, prior_type, prior_info, sample_dir, optfile, opts, args);\n\n  if(dnest_flag_postprc == 1)\n  {\n    dnest_postprocess(dnest_post_temp, optfile, opts);\n    MPI_Barrier(MPI_COMM_WORLD);\n    finalise();\n    return post_logz;\n  }\n\n  if(dnest_flag_sample_info == 1)\n  {\n    dnest_postprocess(dnest_post_temp, optfile, opts);\n    finalise();\n    return post_logz;\n  }\n\n  if(dnest_flag_restart==1)\n    dnest_restart();\n\n  initialize_output_file();\n  dnest_run();\n  close_output_file();\n\n  dnest_postprocess(dnest_post_temp, optfile, opts);\n\n  finalise();\n  \n  return post_logz;\n}\n\n// postprocess, calculate evidence, generate posterior sample.\nvoid dnest_postprocess(double temperature,char *optfile, DNestOptions *opts)\n{\n  if(dnest_thistask == dnest_root)\n  {\n    options_load(optfile, opts);\n    postprocess(temperature);\n  }\n  MPI_Bcast(&post_logz, 1, MPI_DOUBLE, dnest_root, MPI_COMM_WORLD);\n}\n\nvoid dnest_run()\n{\n  int i, j, k, size_all_above_incr;\n  Level *pl, *levels_orig;\n  int *buf_size_above, *buf_displs;\n  double *plimits;\n  \n  // used to gather levels' information\n  if(dnest_thistask == dnest_root)\n  {\n    buf_size_above = malloc(dnest_totaltask * sizeof(int));  \n    buf_displs = malloc(dnest_totaltask * sizeof(int));\n  }\n\n  if(dnest_thistask == dnest_root)\n  {\n    printf(\"#=======================================================\\n\");\n    printf(\"# Starting diffusive nested sampling.\\n\");\n  }\n  MPI_Barrier(MPI_COMM_WORLD);\n\n  while(true)\n  {\n    //check for termination\n    if(options.max_num_saves !=0 &&\n        count_saves != 0 && (count_saves%options.max_num_saves == 0))\n      break;\n\n    dnest_mcmc_run();\n    MPI_Barrier(MPI_COMM_WORLD);\n    \n    //gather levels\n    MPI_Gather(levels, size_levels*sizeof(Level), MPI_BYTE, \n             copies_of_levels, size_levels*sizeof(Level), MPI_BYTE, dnest_root, MPI_COMM_WORLD);\n\n    //gather limits\n    if(dnest_flag_limits == 1)\n    {\n      MPI_Gather(limits, size_levels*particle_offset_double*2, MPI_DOUBLE, \n               copies_of_limits, size_levels*particle_offset_double*2, MPI_DOUBLE, dnest_root, MPI_COMM_WORLD );\n    }\n    \n    //gather size_above \n    MPI_Gather(&size_above, 1, MPI_INT, buf_size_above, 1, MPI_INT, dnest_root, MPI_COMM_WORLD);\n\n    // task 0 responsible for updating levels\n    if(dnest_thistask == dnest_root)\n    {\n      size_all_above_incr = 0;\n      for(i = 0; i<dnest_totaltask; i++)\n      {\n        size_all_above_incr += buf_size_above[i];\n\n        buf_size_above[i] *= sizeof(LikelihoodType);\n      }\n\n      // store new points following the end of all_above array.\n      buf_displs[0] = size_all_above * sizeof(LikelihoodType);\n      for(i=1; i<dnest_totaltask; i++)\n      {\n        buf_displs[i] = buf_displs[i-1] + buf_size_above[i-1];\n      }\n      \n      //update size_all_above\n      size_all_above += size_all_above_incr; \n\n      if(size_all_above > options.new_level_interval*2)\n      {\n        printf(\"# Error, all above overflow.\\n\");\n        exit(0);\n      }\n    }\n    \n\n    // gather above into all_above, stored in task 0, note that its size is different among tasks\n    MPI_Gatherv(above, size_above * sizeof(LikelihoodType), MPI_BYTE, \n                all_above, buf_size_above, buf_displs, MPI_BYTE, dnest_root, MPI_COMM_WORLD);\n\n    // reset size_above for each task\n    size_above = 0;\n\n    count_mcmc_steps += options.thread_steps * dnest_totaltask;\n\n    if(dnest_thistask == dnest_root)\n    {\n      //backup levels_combine\n      levels_orig = malloc(size_levels_combine * sizeof(Level));\n      memcpy(levels_orig, levels_combine, size_levels_combine*sizeof(Level));\n\n      //scan over all copies of levels\n      pl = copies_of_levels;\n      for(i=0; i< dnest_totaltask; i++)\n      {\n        for(j=0; j<size_levels_combine; j++)\n        {\n          levels_combine[j].accepts += (pl[j].accepts - levels_orig[j].accepts);\n          levels_combine[j].tries += (pl[j].tries - levels_orig[j].tries);\n          levels_combine[j].visits += (pl[j].visits - levels_orig[j].visits);\n          levels_combine[j].exceeds += (pl[j].exceeds - levels_orig[j].exceeds);\n          //printf(\"%d %d\\n\", thistask, (pl[j].accepts - levels_orig[j].accepts) );;\n        }\n        pl += size_levels_combine;\n      }\n\n      free(levels_orig);\n\n      // scan over all copies of limits\n      if(dnest_flag_limits == 1)\n      {\n        plimits = copies_of_limits;\n        for(i=0; i< dnest_totaltask; i++)\n        {\n          for(j=0; j < size_levels; j++)\n          {\n            for(k=0; k<particle_offset_double; k++)\n            {\n              limits[j * particle_offset_double *2 + k*2 ] = fmin(limits[j * particle_offset_double *2 + k*2 ],\n                plimits[j * particle_offset_double *2 + k*2]);\n              limits[j * particle_offset_double *2 + k*2 +1 ] = fmax(limits[j * particle_offset_double *2 + k*2 +1 ],\n                plimits[j * particle_offset_double *2 + k*2 + 1]);\n            }\n          \n          }\n          plimits += size_levels * particle_offset_double * 2;\n        }\n\n        // limits of smaller levels should be larger than those of higher levels\n        for(j=size_levels-2; j >= 0; j--)\n          for(k=0; k<particle_offset_double; k++)\n          {\n            limits[ j * particle_offset_double *2 + k*2 ] = fmin( limits[ j * particle_offset_double *2 + k*2 ],\n                    limits[ (j+1) * particle_offset_double *2 + k*2 ] );\n\n            limits[ j * particle_offset_double *2 + k*2 + 1] = fmax( limits[ j * particle_offset_double *2 + k*2 +1 ],\n                    limits[ (j+1) * particle_offset_double *2 + k*2 + 1 ] );\n          }\n      }\n\n      do_bookkeeping();\n\n      size_levels = size_levels_combine;\n      memcpy(levels, levels_combine, size_levels * sizeof(Level));\n    }\n\n    //broadcast levels\n    MPI_Bcast(&size_levels, 1, MPI_INT, dnest_root, MPI_COMM_WORLD);\n    //MPI_Bcast(&count_saves, 1, MPI_INT, root, MPI_COMM_WORLD);\n    MPI_Bcast(levels, size_levels * sizeof(Level), MPI_BYTE, dnest_root,  MPI_COMM_WORLD); \n\n    if(dnest_flag_limits == 1)\n      MPI_Bcast(limits, size_levels * particle_offset_double *2, MPI_DOUBLE, dnest_root, MPI_COMM_WORLD);\n\n    if(count_mcmc_steps >= (count_saves + 1)*options.save_interval)\n    {\n      save_particle();\n\n      if(dnest_thistask == dnest_root )\n      {\n        // save levels, limits, sync samples when running a number of steps\n        if( count_saves % num_saves == 0 )\n        {\n          save_levels();\n          if(dnest_flag_limits == 1)\n            save_limits();\n          fflush(fsample_info);\n          fsync(fileno(fsample_info));\n          fflush(fsample);\n          fsync(fileno(fsample));\n          printf(\"# Save levels, limits, and sync samples at N= %d.\\n\", count_saves);\n        }\n      }\n\n      if( count_saves % num_saves_restart == 0 )\n      {\n        dnest_save_restart();\n      }\n    }\n  }\n  \n  //dnest_save_restart();\n\n  if(dnest_thistask == dnest_root)\n  {\n    //save levels\n    save_levels();\n    if(dnest_flag_limits == 1)\n      save_limits();\n\n    /* output state of sampler */\n    FILE *fp;\n    fp = fopen(options.sampler_state_file, \"w\");\n    fprintf(fp, \"%d %d\\n\", size_levels, count_saves);\n    fclose(fp);\n\n    free(buf_size_above);\n    free(buf_displs);\n  }\n}\n\nvoid do_bookkeeping()\n{\n  int i;\n  //bool created_level = false;\n\n  if(!enough_levels(levels_combine, size_levels_combine) && size_all_above >= options.new_level_interval)\n  {\n    // in descending order \n    qsort(all_above, size_all_above, sizeof(LikelihoodType), dnest_cmp);\n    int index = (int)( (1.0/compression) * size_all_above);\n\n    Level level_tmp = {all_above[index], 0.0, 0, 0, 0, 0};\n    levels_combine[size_levels_combine] = level_tmp;\n    size_levels_combine++;\n    \n    printf(\"# Creating level %d with log likelihood = %e.\\n\", \n               size_levels_combine-1, levels_combine[size_levels_combine-1].log_likelihood.value);\n\n    // clear out the last index records\n    for(i=index; i<size_all_above; i++)\n    {\n      all_above[i].value = 0.0;\n      all_above[i].tiebreaker = 0.0;\n    }\n    size_all_above = index;\n\n    if(enough_levels(levels_combine, size_levels_combine))\n    {\n      renormalise_visits();\n      options.max_num_levels = size_levels_combine;\n      printf(\"# Done creating levles.\\n\");\n    }\n    else\n    {\n      kill_lagging_particles();\n    }\n\n    //created_level = true;\n  }\n  \n  recalculate_log_X();\n\n/*  if(created_level)\n    save_levels();\n\n  if(count_mcmc_steps >= (count_saves + 1)*options.save_interval)\n  {\n\n    //save_particle();\n\n    if(!created_level)\n      save_levels();\n  }*/\n\n}\n\nvoid recalculate_log_X()\n{\n  int i;\n\n  levels_combine[0].log_X = 0.0;\n  for(i=1; i<size_levels_combine; i++)\n  {\n    levels_combine[i].log_X = levels_combine[i-1].log_X \n    + log( (double)( (levels_combine[i-1].exceeds + 1.0/compression * regularisation)\n                    /(levels_combine[i-1].visits + regularisation)  ) );\n  }\n}\n\nvoid renormalise_visits()\n{\n  size_t i;\n\n  for(i=0; i<size_levels_combine; i++)\n  {\n    if(levels_combine[i].tries >= regularisation)\n    {\n      levels_combine[i].accepts = ((double)(levels_combine[i].accepts+1) / (double)(levels_combine[i].tries+1)) * regularisation;\n      levels_combine[i].tries = regularisation;\n    }\n\n    if(levels_combine[i].visits >= regularisation)\n    {\n      levels_combine[i].exceeds = ( (double) (levels_combine[i].exceeds+1) / (double)(levels_combine[i].visits + 1) ) * regularisation;\n      levels_combine[i].visits = regularisation;\n    }\n  }\n}\n\nvoid kill_lagging_particles()\n{\n  static unsigned int deletions = 0;\n\n  bool *good;\n  good = (bool *)malloc(options.num_particles * sizeof(bool));\n\n  double max_log_push = -DBL_MAX;\n\n  double kill_probability = 0.0;\n  unsigned int num_bad = 0;\n  size_t i;\n\n  for(i=0; i<options.num_particles; i++)good[i] = true;\n\n  for(i=0; i<options.num_particles; i++)\n  {\n    if( log_push(level_assignments[i]) > max_log_push)\n      max_log_push = log_push(level_assignments[i]);\n\n    kill_probability = pow(1.0 - 1.0/(1.0 + exp(-log_push(level_assignments[i]) - 4.0)), 3);\n    if(gsl_rng_uniform(dnest_gsl_r) <= kill_probability)\n    {\n      good[i] = false;\n      ++num_bad;\n    }\n  }\n\n  if(num_bad < options.num_particles)\n  {\n    for(i=0; i< options.num_particles; i++)\n    {\n      if(!good[i])\n      {\n        int i_copy;\n        do\n        {\n          i_copy = gsl_rng_uniform_int(dnest_gsl_r, options.num_particles);\n        }while(!good[i_copy] || gsl_rng_uniform(dnest_gsl_r) >= exp(log_push(level_assignments[i_copy]) - max_log_push));\n\n        memcpy(particles+i*particle_offset_size, particles + i_copy*particle_offset_size, dnest_size_of_modeltype);\n        log_likelihoods[i] = log_likelihoods[i_copy];\n        level_assignments[i] = level_assignments[i_copy];\n         \n        kill_action(i, i_copy);\n\n        deletions++;\n\n        printf(\"# Replacing lagging particle.\\n\");\n        printf(\"# This has happened %d times.\\n\", deletions);\n      }\n    }\n  }\n  else\n    printf(\"# Warning: all particles lagging!.\\n\");\n\n  free(good);\n}\n\n/* save levels */\nvoid save_levels()\n{\n  if(!save_to_disk)\n    return;\n  \n  int i;\n  FILE *fp;\n\n  fp = fopen(options.levels_file, \"w\");\n  fprintf(fp, \"# log_X, log_likelihood, tiebreaker, accepts, tries, exceeds, visits\\n\");\n  for(i=0; i<size_levels_combine; i++)\n  {\n    fprintf(fp, \"%14.12g %14.12g %f %llu %llu %llu %llu\\n\", levels_combine[i].log_X, levels_combine[i].log_likelihood.value, \n      levels_combine[i].log_likelihood.tiebreaker, levels_combine[i].accepts,\n      levels_combine[i].tries, levels[i].exceeds, levels_combine[i].visits);\n  }\n  fclose(fp);\n\n  /* update state of sampler */\n  fp = fopen(options.sampler_state_file, \"w\");\n  fprintf(fp, \"%d %d\\n\", size_levels, count_saves);\n  fclose(fp);\n}\n\nvoid save_limits()\n{\n  int i, j;\n  FILE *fp;\n\n  fp = fopen(options.limits_file, \"w\");\n  for(i=0; i<size_levels_combine; i++)\n  {\n    fprintf(fp, \"%d  \", i);\n    for(j=0; j<particle_offset_double; j++)\n      fprintf(fp, \"%f  %f  \", limits[i*2*particle_offset_double+j*2], limits[i*2*particle_offset_double+j*2+1]);\n\n    fprintf(fp, \"\\n\");\n  }\n  fclose(fp);\n}\n\n/* save particle */\nvoid save_particle()\n{\n  count_saves++;\n\n  if(!save_to_disk)\n    return;\n  \n  int whichparticle, whichtask;\n  void *particle_message;\n  \n  if(dnest_thistask == dnest_root)\n  {\n    if(count_saves%1 == 0)\n      printf(\"#[%.1f%%] Saving particle to disk. N= %d.\\n\", 100.0*count_saves/options.max_num_saves, count_saves);\n\n    whichtask = gsl_rng_uniform_int(dnest_gsl_r,dnest_totaltask);\n  }\n\n  MPI_Bcast(&whichtask, 1, MPI_INT, dnest_root, MPI_COMM_WORLD);\n\n  if(whichtask != dnest_root)\n  {\n    if(dnest_thistask == whichtask)\n    {\n      int size_message = dnest_size_of_modeltype + 2*sizeof(int) + 2*sizeof(double);\n      particle_message = (void *)malloc(size_message);\n      whichparticle = gsl_rng_uniform_int(dnest_gsl_r,options.num_particles);\n      memcpy(particle_message, particles + whichparticle * particle_offset_size, dnest_size_of_modeltype);\n      memcpy(particle_message + dnest_size_of_modeltype, &log_likelihoods[whichparticle].value, 2*sizeof(double));\n      memcpy(particle_message + dnest_size_of_modeltype + 2*sizeof(double), &level_assignments[whichparticle], sizeof(int));\n      memcpy(particle_message + dnest_size_of_modeltype + 2*sizeof(double) + sizeof(int), &whichparticle, sizeof(int));\n\n      MPI_Send(particle_message, size_message, MPI_BYTE, dnest_root, 1, MPI_COMM_WORLD);\n\n      //printf(\"%f %f\\n\", log_likelihoods[whichparticle].value, log_likelihoods[whichparticle].tiebreaker);\n\n      free(particle_message);\n    }\n    if(dnest_thistask == dnest_root)\n    {\n      MPI_Status status;\n      int size_message = dnest_size_of_modeltype + 2*sizeof(int) + 2*sizeof(double);\n      int whichlevel;\n      LikelihoodType logl;\n\n      particle_message = (void *)malloc(size_message);\n\n      MPI_Recv(particle_message, size_message, MPI_BYTE, whichtask, 1, MPI_COMM_WORLD, &status);\n\n      memcpy(&logl, particle_message + dnest_size_of_modeltype, 2*sizeof(double) );\n      memcpy(&whichlevel, particle_message + dnest_size_of_modeltype + 2*sizeof(double), sizeof(int) );\n      memcpy(&whichparticle, particle_message + dnest_size_of_modeltype + 2*sizeof(double) + sizeof(int), sizeof(int) );\n      \n      //printf(\"%f %f\\n\", logl.value, logl.tiebreaker);\n\n      print_particle(fsample, particle_message);\n\n      fprintf(fsample_info, \"%d %e %f %d\\n\", whichlevel, \n        logl.value,\n        logl.tiebreaker,\n        whichtask * options.num_particles + whichparticle);\n\n      free(particle_message);\n    }\n  }\n  else\n  {\n    if(dnest_thistask == dnest_root)\n    {\n      whichparticle =  gsl_rng_uniform_int(dnest_gsl_r,options.num_particles);\n\n      print_particle(fsample, particles + whichparticle * particle_offset_size);\n\n      fprintf(fsample_info, \"%d %e %f %d\\n\", level_assignments[whichparticle], \n        log_likelihoods[whichparticle].value,\n        log_likelihoods[whichparticle].tiebreaker,\n        whichtask * options.num_particles + whichparticle);\n    }\n  }\n}\n\nvoid dnest_mcmc_run()\n{\n  unsigned int which;\n  unsigned int i;\n  \n  for(i = 0; i<options.thread_steps; i++)\n  {\n\n    /* randomly select out one particle to update */\n    which = gsl_rng_uniform_int(dnest_gsl_r, options.num_particles);\n\n    dnest_which_particle_update = which;\n\n    //if(count_mcmc_steps >= 10000)printf(\"FFFF\\n\");\n    //printf(\"%d\\n\", which);\n    //printf(\"%f %f %f\\n\", particles[which].param[0], particles[which].param[1], particles[which].param[2]);\n    //printf(\"level:%d\\n\", level_assignments[which]);\n    //printf(\"%e\\n\", log_likelihoods[which].value);\n\n    if(gsl_rng_uniform(dnest_gsl_r) <= 0.5)\n    {\n      update_particle(which);\n      update_level_assignment(which);\n    }\n    else\n    {\n      update_level_assignment(which);\n      update_particle(which);\n    }\n        \n    if( !enough_levels(levels, size_levels)  && levels[size_levels-1].log_likelihood.value <= log_likelihoods[which].value)\n    {\n      above[size_above] = log_likelihoods[which];\n      size_above++;\n    }\n  }\n}\n\n\nvoid update_particle(unsigned int which)\n{\n  void *particle = particles+ which*particle_offset_size;\n  LikelihoodType *logl = &(log_likelihoods[which]);\n  \n  Level *level = &(levels[level_assignments[which]]);\n\n  void *proposal = (void *)malloc(dnest_size_of_modeltype);\n  LikelihoodType logl_proposal;\n  double log_H;\n\n  memcpy(proposal, particle, dnest_size_of_modeltype);\n  dnest_which_level_update = level_assignments[which];\n  \n  log_H = perturb(proposal);\n  \n  logl_proposal.value = log_likelihoods_cal(proposal);\n  logl_proposal.tiebreaker =  (*logl).tiebreaker + gsl_rng_uniform(dnest_gsl_r);\n  dnest_wrap(&logl_proposal.tiebreaker, 0.0, 1.0);\n  \n  if(log_H > 0.0)\n    log_H = 0.0;\n\n  dnest_perturb_accept[which] = 0;\n  if( gsl_rng_uniform(dnest_gsl_r) <= exp(log_H) && level->log_likelihood.value <= logl_proposal.value)\n  {\n    memcpy(particle, proposal, dnest_size_of_modeltype);\n    memcpy(logl, &logl_proposal, sizeof(LikelihoodType));\n    level->accepts++;\n\n    dnest_perturb_accept[which] = 1;\n    accept_action();\n    account_unaccepts[which] = 0; /* reset the number of unaccepted perturb */\n  }\n  else \n  {\n    account_unaccepts[which] += 1; /* number of unaccepted perturb */\n  }\n  level->tries++;\n  \n  unsigned int current_level = level_assignments[which];\n  for(; current_level < size_levels-1; ++current_level)\n  {\n    levels[current_level].visits++;\n    if(levels[current_level+1].log_likelihood.value <= log_likelihoods[which].value)\n      levels[current_level].exceeds++;\n    else\n      break; // exit the loop if it does not satify higher levels\n  }\n  free(proposal);\n}\n\nvoid update_level_assignment(unsigned int which)\n{\n  int i;\n\n  int proposal = level_assignments[which] \n                 + (int)( pow(10.0, 2*gsl_rng_uniform(dnest_gsl_r))*gsl_ran_ugaussian(dnest_gsl_r));\n\n  if(proposal == level_assignments[which])\n    proposal =  ((gsl_rng_uniform(dnest_gsl_r) < 0.5)?(proposal-1):(proposal+1));\n\n  proposal=mod_int(proposal, size_levels);\n\n  double log_A = -levels[proposal].log_X + levels[level_assignments[which]].log_X;\n\n  log_A += log_push(proposal) - log_push(level_assignments[which]);\n\n  // enforce uniform exploration if levels are enough\n  if(enough_levels(levels, size_levels))\n    log_A += options.beta*log( (double)(levels[level_assignments[which]].tries +1)/ (levels[proposal].tries +1) );\n\n  if(log_A > 0.0)\n    log_A = 0.0;\n\n  if( gsl_rng_uniform(dnest_gsl_r) <= exp(log_A) && levels[proposal].log_likelihood.value <= log_likelihoods[which].value)\n  {\n    level_assignments[which] = proposal;\n\n// update the limits of the level\n    if(dnest_flag_limits == 1)\n    {\n      double *particle = (double *) (particles+ which*particle_offset_size);\n      for(i=0; i<particle_offset_double; i++)\n      {\n        limits[proposal * 2 * particle_offset_double +  i*2] = \n            fmin(limits[proposal * 2* particle_offset_double +  i*2], particle[i]);\n        limits[proposal * 2 * particle_offset_double +  i*2+1] = \n            fmax(limits[proposal * 2 * particle_offset_double +  i*2+1], particle[i]);\n      }\n    }\n\n  }\n\n}\n\ndouble log_push(unsigned int which_level)\n{\n  if(which_level > size_levels)\n  {\n    printf(\"level overflow %d %d.\\n\", which_level, size_levels);\n    exit(0);\n  }\n  if(enough_levels(levels, size_levels))\n    return 0.0;\n\n  int i = which_level - (size_levels - 1);\n  return ((double)i)/options.lam;\n}\n\nbool enough_levels(Level *l, int size_l)\n{\n  int i;\n\n  if(options.max_num_levels == 0)\n  {\n    if(size_l >= LEVEL_NUM_MAX)\n      return true;\n\n    if(size_l < 10)\n      return false;\n\n    int num_levels_to_check = 20;\n    if(size_l > 80)\n      num_levels_to_check = (int)(sqrt(20) * sqrt(0.25*size_l));\n\n    int k = size_l - 1, kc = 0;\n    double tot = 0.0;\n    double max = -DBL_MAX;\n    double diff;\n\n    for(i= 0; i<num_levels_to_check; i++)\n    {\n      diff = l[k].log_likelihood.value - l[k-1].log_likelihood.value;\n      tot += diff;\n      if(diff > max)\n        max = diff;\n\n      k--;\n      kc++;\n      if( k < 1 )\n        break;\n    }\n    if(tot/kc < options.max_ptol && max < options.max_ptol*1.1)\n      return true;\n    else\n      return false;\n  }\n  return (size_l >= options.max_num_levels);\n}\n\nvoid initialize_output_file()\n{\n  if(dnest_thistask != dnest_root)\n    return;\n\n  if(dnest_flag_restart !=1)\n    fsample = fopen(options.sample_file, \"w\");\n  else\n    fsample = fopen(options.sample_file, \"a\");\n  \n  if(fsample==NULL)\n  {\n    fprintf(stderr, \"# Cannot open file sample.txt.\\n\");\n    exit(0);\n  }\n  if(dnest_flag_restart != 1)\n    fprintf(fsample, \"# \\n\");\n\n  if(dnest_flag_restart != 1)\n    fsample_info = fopen(options.sample_info_file, \"w\");\n  else\n    fsample_info = fopen(options.sample_info_file, \"a\");\n\n  if(fsample_info==NULL)\n  {\n    fprintf(stderr, \"# Cannot open file %s.\\n\", options.sample_info_file);\n    exit(0);\n  }\n  if(dnest_flag_restart != 1)\n    fprintf(fsample_info, \"# level assignment, log likelihood, tiebreaker, ID.\\n\");\n}\n\nvoid close_output_file()\n{\n  if(dnest_thistask != dnest_root )\n    return;\n\n  fclose(fsample);\n  fclose(fsample_info);\n}\n\nvoid setup(int argc, char** argv, DNestFptrSet *fptrset, int num_params, \n           double *param_range, int *prior_type, double *prior_info,\n           char *sample_dir, char *optfile, DNestOptions *opts, void *args)\n{\n  int i, j;\n\n  // root task.\n  dnest_root = 0;\n\n  if(dnest_thistask == dnest_root)\n  {\n    dnest_check_directory(sample_dir);\n  }\n  MPI_Barrier(MPI_COMM_WORLD);\n\n  // setup function pointers\n  from_prior = fptrset->from_prior;\n  log_likelihoods_cal = fptrset->log_likelihoods_cal;\n  log_likelihoods_cal_initial = fptrset->log_likelihoods_cal_initial;\n  log_likelihoods_cal_restart = fptrset->log_likelihoods_cal_restart;\n  perturb = fptrset->perturb;\n  print_particle = fptrset->print_particle;\n  read_particle = fptrset->read_particle;\n  restart_action = fptrset->restart_action;\n  accept_action = fptrset->accept_action;\n  kill_action = fptrset->kill_action;\n  strcpy(options_file, optfile);\n  strcpy(dnest_sample_dir, sample_dir);\n\n  // random number generator\n  dnest_gsl_T = (gsl_rng_type *) gsl_rng_default;\n  dnest_gsl_r = gsl_rng_alloc (dnest_gsl_T);\n#ifndef Debug\n  gsl_rng_set(dnest_gsl_r, time(NULL) + dnest_thistask);\n#else\n  gsl_rng_set(dnest_gsl_r, 9999 + dnest_thistask);\n  printf(\"# debugging, task %d dnest random seed %d\\n\", dnest_thistask, 9999 + dnest_thistask);\n#endif  \n  \n  dnest_num_params = num_params;\n  dnest_size_of_modeltype = dnest_num_params * sizeof(double);\n\n  if(param_range != NULL)\n  {\n    dnest_param_range = malloc(num_params*2*sizeof(double));\n    memcpy(dnest_param_range, param_range, num_params*2*sizeof(double));\n  }\n  if(prior_type != NULL)\n  {\n    dnest_prior_type = malloc(num_params*sizeof(int));\n    memcpy(dnest_prior_type, prior_type, num_params*sizeof(int));\n  }\n  if(prior_info != NULL)\n  {\n    dnest_prior_info = malloc(num_params*2*sizeof(double));\n    memcpy(dnest_prior_info, prior_info, num_params*2*sizeof(double));\n  }\n  if(args != NULL)\n  {\n    dnest_args = args;\n  }\n\n  // read options\n  if(dnest_thistask == dnest_root)\n    options_load(optfile, opts);\n  MPI_Bcast(&options, sizeof(DNestOptions), MPI_BYTE, dnest_root, MPI_COMM_WORLD);\n\n  //dnest_post_temp = 1.0;\n  compression = exp(1.0);\n  regularisation = options.new_level_interval*sqrt(options.lam);\n  save_to_disk = true;\n\n  // particles\n  particle_offset_size = dnest_size_of_modeltype/sizeof(void);\n  particle_offset_double = dnest_size_of_modeltype/sizeof(double);\n  particles = (void *)malloc(options.num_particles*dnest_size_of_modeltype);\n  \n  // initialise sampler\n  if(dnest_thistask == dnest_root)\n    all_above = (LikelihoodType *)malloc(2*options.new_level_interval * sizeof(LikelihoodType));\n\n  above = (LikelihoodType *)malloc(2*options.new_level_interval * sizeof(LikelihoodType));\n\n  log_likelihoods = (LikelihoodType *)malloc(2*options.num_particles * sizeof(LikelihoodType));\n  level_assignments = (unsigned int*)malloc(options.num_particles * sizeof(unsigned int));\n\n  account_unaccepts = (unsigned int *)malloc(options.num_particles * sizeof(unsigned int));\n  for(i=0; i<options.num_particles; i++)\n  {\n    account_unaccepts[i] = 0;\n  }\n\n  if(options.max_num_levels != 0)\n  {\n    levels = (Level *)malloc(options.max_num_levels * sizeof(Level));\n    if(dnest_thistask == dnest_root)\n    {\n      levels_combine = (Level *)malloc(options.max_num_levels * sizeof(Level));\n      copies_of_levels = (Level *)malloc(dnest_totaltask * options.max_num_levels * sizeof(Level));\n    }\n\n    if(dnest_flag_limits == 1)\n    {\n      limits = malloc(options.max_num_levels * particle_offset_double * 2 * sizeof(double));\n      if(limits == NULL)\n      {\n        printf(\"Cannot allocate memory for limits.\\n\"\n               \"This usually happens when both the numbers of parameters and levels are extremely large.\\n\"\n               \"Please do not switch on '-l' option in argv passed to dnest.\\n\");\n        exit(EXIT_FAILURE);\n      }\n      for(i=0; i<options.max_num_levels; i++)\n      {\n        for(j=0; j<particle_offset_double; j++)\n        {\n          limits[i*2*particle_offset_double+ j*2] = DBL_MAX;\n          limits[i*2*particle_offset_double + j*2 + 1] = -DBL_MAX;\n        }\n      }\n\n      if(dnest_thistask == dnest_root)\n      {\n        copies_of_limits = malloc( dnest_totaltask * options.max_num_levels * particle_offset_double * 2 * sizeof(double));\n        if(copies_of_limits == NULL)\n        {\n          printf(\"Cannot allocate memory for limits.\\n\"\n                 \"This usually happens when both the numbers of parameters and levels are extremely large.\\n\"\n                 \"Please do not switch on '-l' option in argv passed to dnest.\\n\");\n          exit(EXIT_FAILURE);\n        }\n      }\n    }\n  }\n  else\n  {\n    levels = (Level *)malloc(LEVEL_NUM_MAX * sizeof(Level));\n    if(dnest_thistask == dnest_root)\n    {\n      levels_combine = (Level *)malloc(LEVEL_NUM_MAX * sizeof(Level));\n      copies_of_levels = (Level *)malloc(dnest_totaltask * LEVEL_NUM_MAX * sizeof(Level));\n    }\n\n    if(dnest_flag_limits == 1)\n    {\n      limits = malloc(LEVEL_NUM_MAX * particle_offset_double * 2 * sizeof(double));\n      if(limits == NULL)\n      {\n        printf(\"Cannot allocate memory for limits.\\n\"\n               \"This usually happens when both the numbers of parameters and levels are extremely large.\\n\"\n               \"Please do not switch on '-l' option in argv passed to dnest.\\n\");\n        exit(EXIT_FAILURE);\n      }\n      for(i=0; i<LEVEL_NUM_MAX; i++)\n      {\n        for(j=0; j<particle_offset_double; j++)\n        {\n          limits[i*2*particle_offset_double + j*2] = DBL_MAX;\n          limits[i*2*particle_offset_double + j*2 + 1] = -DBL_MAX;\n        }\n      }\n\n      if(dnest_thistask == dnest_root)\n      {\n        copies_of_limits = malloc(dnest_totaltask * LEVEL_NUM_MAX * particle_offset_double * 2 * sizeof(double));\n        if(copies_of_limits == NULL)\n        {\n          printf(\"Cannot allocate memory for limits.\\n\"\n                 \"This usually happens when both the numbers of parameters and levels are extremely large.\\n\"\n                 \"Please do not switch on '-l' option in argv passed to dnest.\\n\");\n          exit(EXIT_FAILURE);\n        }\n      }\n    }\n  }\n  \n  dnest_perturb_accept = malloc(options.num_particles * sizeof(int));\n  for(i=0; i<options.num_particles; i++)\n  {\n    dnest_perturb_accept[i] = 0;\n  }\n\n  count_mcmc_steps = 0;\n  count_saves = 0;\n  num_saves = (int)fmax(0.02*options.max_num_saves, 1.0);\n  num_saves_restart = (int)fmax(0.2 * options.max_num_saves, 1.0);\n\n// first level\n  size_levels = 0;\n  size_above = 0;\n  size_all_above = 0;\n  LikelihoodType like_tmp = {-DBL_MAX, gsl_rng_uniform(dnest_gsl_r)};\n  Level level_tmp = {like_tmp, 0.0, 0, 0, 0, 0};\n  levels[size_levels] = level_tmp;\n  size_levels++;\n\n  if(dnest_thistask == dnest_root)\n  {\n    size_levels_combine = 0;\n    levels_combine[size_levels_combine] = level_tmp;\n    size_levels_combine++;\n  }\n  \n  for(i=0; i<options.num_particles; i++)\n  {\n    dnest_which_particle_update = i;\n    dnest_which_level_update = 0;\n    from_prior(particles+i*particle_offset_size);\n    log_likelihoods[i].value = log_likelihoods_cal_initial(particles+i*particle_offset_size);\n    log_likelihoods[i].tiebreaker = dnest_rand();\n    level_assignments[i] = 0;\n  }\n\n  /*ModelType proposal;\n  printf(\"%f %f %f \\n\", particles[0].param[0], particles[0].param[1], particles[0].param[2] );\n  proposal = particles[0];\n  printf(\"%f %f %f \\n\", proposal.param[0], proposal.param[1], proposal.param[2] );*/\n}\n\nvoid finalise()\n{\n  free(particles);\n  free(above);\n  free(log_likelihoods);\n  free(level_assignments);\n  free(levels);\n\n  free(account_unaccepts);\n\n  if(dnest_flag_limits == 1)\n    free(limits);\n\n\n  if(dnest_thistask == dnest_root)\n  {\n    free(all_above);\n    free(levels_combine);\n    free(copies_of_levels);\n    if(dnest_flag_limits == 1)\n      free(copies_of_limits);\n  }\n  gsl_rng_free(dnest_gsl_r);\n\n  free(dnest_perturb_accept);\n\n  if(dnest_param_range != NULL)\n  {\n    free(dnest_param_range);\n  }\n  if(dnest_prior_type != NULL)\n  {\n    free(dnest_prior_type);\n  }\n  if(dnest_prior_info != NULL)\n  {\n    free(dnest_prior_info);\n  }\n\n  if(dnest_thistask == dnest_root)\n  {\n    printf(\"# Finalizing CDNest.\\n\");\n    printf(\"#=======================================================\\n\");\n  }\n}\n\nint dnest_search_pardict(DNestPARDICT *pardict, int num_pardict, char *tag)\n{\n  int i;\n  for(i=0; i<num_pardict; i++)\n  {\n    if(strcmp(pardict[i].tag, tag) == 0)\n    {\n      return i;\n    }\n  }\n\n  fprintf(stderr, \"# cdnest no match of tag %s.\\n\", tag);\n  return num_pardict+1;\n}\n\nvoid options_load(char *optfile, DNestOptions *opts)\n{\n  if(strlen(optfile) > 0)\n  {\n    DNestPARDICT *pardict;\n    int num_pardict;\n    pardict = malloc(10 * sizeof(DNestPARDICT));\n    enum TYPE {INT, DOUBLE, STRING};\n  \n    FILE *fp;\n    char str[BUF_MAX_LENGTH], buf1[BUF_MAX_LENGTH], buf2[BUF_MAX_LENGTH], buf3[BUF_MAX_LENGTH];\n  \n    int i, j, nt, idx;\n    nt = 0;\n    strcpy(pardict[nt].tag, \"NumberParticles\");\n    pardict[nt].addr = &options.num_particles;\n    pardict[nt].isset = 0;\n    pardict[nt++].id = INT;\n  \n    strcpy(pardict[nt].tag, \"NewLevelIntervalFactor\");\n    pardict[nt].addr = &options.new_level_interval_factor;\n    pardict[nt].isset = 0;\n    pardict[nt++].id = DOUBLE;\n  \n    strcpy(pardict[nt].tag, \"SaveIntervalFactor\");\n    pardict[nt].addr = &options.save_interval_factor;\n    pardict[nt].isset = 0;\n    pardict[nt++].id = DOUBLE;\n  \n    strcpy(pardict[nt].tag, \"ThreadStepsFactor\");\n    pardict[nt].addr = &options.thread_steps_factor;\n    pardict[nt].isset = 0;\n    pardict[nt++].id = DOUBLE;\n  \n    strcpy(pardict[nt].tag, \"MaxNumberLevels\");\n    pardict[nt].addr = &options.max_num_levels;\n    pardict[nt].isset = 0;\n    pardict[nt++].id = INT;\n  \n    strcpy(pardict[nt].tag, \"BacktrackingLength\");\n    pardict[nt].addr = &options.lam;\n    pardict[nt].isset = 0;\n    pardict[nt++].id = DOUBLE;\n   \n    strcpy(pardict[nt].tag, \"StrengthEqualPush\");\n    pardict[nt].addr = &options.beta;\n    pardict[nt].isset = 0;\n    pardict[nt++].id = DOUBLE;\n  \n    strcpy(pardict[nt].tag, \"MaxNumberSaves\");\n    pardict[nt].addr = &options.max_num_saves;\n    pardict[nt].isset = 0;\n    pardict[nt++].id = INT;\n  \n    strcpy(pardict[nt].tag, \"PTol\");\n    pardict[nt].addr = &options.max_ptol;\n    pardict[nt].isset = 0;\n    pardict[nt++].id = DOUBLE;\n    \n    num_pardict = nt;\n  \n    /* default values */\n    options.new_level_interval_factor = 2;\n    options.save_interval_factor = options.new_level_interval_factor;\n    options.thread_steps_factor = 10;\n    options.num_particles = 1;\n    options.max_num_levels = 0;\n    options.lam = 10.0;\n    options.beta = 100.0;\n    options.max_ptol = 0.1;\n    options.max_num_saves = 10000;\n     \n    fp = fopen(options_file, \"r\");\n    if(fp == NULL)\n    {\n      fprintf(stderr, \"# ERROR: Cannot open options file %s.\\n\", options_file);\n      exit(0);\n    }\n    \n    while(!feof(fp))\n    {\n      sprintf(str,\"empty\");\n      fgets(str, 200, fp);\n      if(sscanf(str, \"%s%s%s\", buf1, buf2, buf3)<2)\n        continue;\n      if(buf1[0]=='%' || buf1[0] == '#')\n        continue;\n      for(i=0, j=-1; i<nt; i++)\n        if(strcmp(buf1, pardict[i].tag) == 0 && pardict[i].isset == 0)\n        {\n          j = i;\n          pardict[i].isset = 1;\n          //printf(\"%s %s\\n\", buf1, buf2);\n          break;\n        }\n      if(j >=0)\n      {\n        switch(pardict[j].id)\n        {\n          case DOUBLE:\n            *((double *) pardict[j].addr) = atof(buf2);\n            break;\n          case STRING:\n            strcpy(pardict[j].addr, buf2);\n            break;\n          case INT:\n            *((unsigned int *)pardict[j].addr) = (unsigned int) atof(buf2);\n            break;\n        }\n      }\n      else\n      {\n        fprintf(stderr, \"# Error in file %s: Tag '%s' is not allowed or multiple defined.\\n\",\n                      options_file, buf1);\n        exit(0);\n      }\n    }\n    fclose(fp);\n  \n    /* check options */\n    idx = dnest_search_pardict(pardict, num_pardict, \"SaveIntervalFactor\");\n    if(pardict[idx].isset == 0)  /* if not set */\n    {\n      options.save_interval_factor = options.new_level_interval_factor;\n    }\n\n    free(pardict);\n  }\n  else \n  {\n    options.new_level_interval_factor = opts->new_level_interval_factor;\n    options.save_interval_factor = opts->save_interval_factor;\n    options.thread_steps_factor = opts->thread_steps_factor;\n    options.num_particles = opts->num_particles;\n    options.max_num_levels = opts->max_num_levels;\n    options.lam = opts->lam;\n    options.beta = opts->beta;\n    options.max_ptol = opts->max_ptol;\n    options.max_num_saves = opts->max_num_saves;\n  }\n  \n  options.thread_steps = dnest_num_params * options.thread_steps_factor * options.num_particles;\n  options.new_level_interval =  dnest_totaltask * options.thread_steps * options.new_level_interval_factor;\n  options.save_interval =  dnest_totaltask * options.thread_steps * options.save_interval_factor;\n  \n  //fgets(buf, BUF_MAX_LENGTH, fp);\n  //sscanf(buf, \"%s\", options.sample_file);\n  strcpy(options.sample_file, dnest_sample_dir);\n  strcat(options.sample_file,\"/sample\");\n  strcat(options.sample_file, dnest_sample_tag);\n  strcat(options.sample_file, \".txt\");\n  strcat(options.sample_file, dnest_sample_postfix);\n  \n  //fgets(buf, BUF_MAX_LENGTH, fp);\n  //sscanf(buf, \"%s\", options.sample_info_file);\n  strcpy(options.sample_info_file, dnest_sample_dir);\n  strcat(options.sample_info_file,\"/sample_info\");\n  strcat(options.sample_info_file, dnest_sample_tag);\n  strcat(options.sample_info_file, \".txt\");\n  strcat(options.sample_info_file, dnest_sample_postfix);\n  \n  //fgets(buf, BUF_MAX_LENGTH, fp);\n  //sscanf(buf, \"%s\", options.levels_file);\n  strcpy(options.levels_file, dnest_sample_dir);\n  strcat(options.levels_file,\"/levels\");\n  strcat(options.levels_file, dnest_sample_tag);\n  strcat(options.levels_file, \".txt\");\n  strcat(options.levels_file, dnest_sample_postfix);\n  \n  //fgets(buf, BUF_MAX_LENGTH, fp);\n  //sscanf(buf, \"%s\", options.sampler_state_file);\n  strcpy(options.sampler_state_file, dnest_sample_dir);\n  strcat(options.sampler_state_file,\"/sampler_state\");\n  strcat(options.sampler_state_file, dnest_sample_tag);\n  strcat(options.sampler_state_file, \".txt\");\n  strcat(options.sampler_state_file, dnest_sample_postfix);\n  \n  //fgets(buf, BUF_MAX_LENGTH, fp);\n  //sscanf(buf, \"%s\", options.posterior_sample_file);\n  strcpy(options.posterior_sample_file, dnest_sample_dir);\n  strcat(options.posterior_sample_file,\"/posterior_sample\");\n  strcat(options.posterior_sample_file, dnest_sample_tag);\n  strcat(options.posterior_sample_file, \".txt\");\n  strcat(options.posterior_sample_file, dnest_sample_postfix);\n\n  //fgets(buf, BUF_MAX_LENGTH, fp);\n  //sscanf(buf, \"%s\", options.posterior_sample_info_file);\n  strcpy(options.posterior_sample_info_file, dnest_sample_dir);\n  strcat(options.posterior_sample_info_file,\"/posterior_sample_info\");\n  strcat(options.posterior_sample_info_file, dnest_sample_tag);\n  strcat(options.posterior_sample_info_file, \".txt\");\n  strcat(options.posterior_sample_info_file, dnest_sample_postfix);\n\n  //fgets(buf, BUF_MAX_LENGTH, fp);\n  //sscanf(buf, \"%s\", options.limits_file);\n  strcpy(options.limits_file, dnest_sample_dir);\n  strcat(options.limits_file,\"/limits\");\n  strcat(options.limits_file, dnest_sample_tag);\n  strcat(options.limits_file, \".txt\");\n  strcat(options.limits_file, dnest_sample_postfix);\n\n  // check options.\n  \n  if(options.new_level_interval < dnest_totaltask * options.thread_steps)\n  {\n    printf(\"# incorrect options:\\n\");\n    printf(\"# new level interval should be equal to or larger than\"); \n    printf(\"  totaltask * thread step.\\n\");\n    exit(0);\n  }\n\n  char fname[STR_MAX_LENGTH];\n  strcpy(fname, dnest_sample_dir);\n  strcat(fname, \"/DNEST_OPTIONS\");\n  FILE *fp = fopen(fname, \"w\");\n  if(fp == NULL)\n  {\n    fprintf(stderr, \"# ERROR: Cannot write file %s.\\n\", fname);\n    exit(0);\n  }\n  fprintf(fp, \"NumberParticles          %d  # Number of particles\\n\", options.num_particles);\n  fprintf(fp, \"NewLevelIntervalFactor   %.2f  # New level interval factor\\n\", options.new_level_interval_factor);\n  fprintf(fp, \"SaveIntervalFactor       %.2f  # Save interval factor\\n\", options.save_interval_factor);\n  fprintf(fp, \"ThreadStepsFactor        %.2f  # ThreadSteps factor\\n\", options.thread_steps_factor);\n  fprintf(fp, \"MaxNumberLevels          %d  # Maximum number of levels\\n\", options.max_num_levels);\n  fprintf(fp, \"BacktrackingLength       %.1f  # Backtracking scale length\\n\", options.lam);\n  fprintf(fp, \"StrengthEqualPush        %.1f  # Strength of effect to force histogram to equal push\\n\", options.beta);\n  fprintf(fp, \"MaxNumberSaves           %d    # Maximum number of saves\\n\", options.max_num_saves);\n  fprintf(fp, \"PTol                     %.1e  # Likelihood tolerance in loge\\n\", options.max_ptol);\n  fprintf(fp, \"ThreadSteps              %d   #\\n\", options.thread_steps);\n  fprintf(fp, \"SaveInterval             %d   #\\n\", options.save_interval);\n  fprintf(fp, \"NewLevelInterval         %d  #\\n\", options.new_level_interval);\n  fprintf(fp, \"SampleFile               %s  #\\n\", options.sample_file);\n  fprintf(fp, \"SampleInfoFile           %s  #\\n\", options.sample_info_file);\n  fprintf(fp, \"SamplerStateFile         %s  #\\n\", options.sampler_state_file);\n  fprintf(fp, \"PosteriorSampleFile      %s  #\\n\", options.posterior_sample_file);\n  fprintf(fp, \"PosteriorSampleInfoFile  %s  #\\n\", options.posterior_sample_info_file);\n  fprintf(fp, \"LevelsFile               %s  #\\n\", options.levels_file);\n  if(dnest_flag_limits == 1)\n    fprintf(fp, \"LimitsFile               %s  #\\n\", options.limits_file);\n  fprintf(fp, \"NumberCores              %d   # Number of cores\\n\", dnest_totaltask);\n  fprintf(fp, \"NumberParameters         %d   # Number of parameters\\n\", dnest_num_params);\n  fclose(fp);\n}\n\n\ndouble mod(double y, double x)\n{\n  if(x > 0.0)\n  {\n    return (y/x - floor(y/x))*x;\n  }\n  else if(x == 0.0)\n  {\n    return 0.0;\n  }\n  else\n  {\n    printf(\"Warning in mod(double, double) %e\\n\", x);\n    exit(0);\n  }\n  \n}\n\ninline void dnest_wrap(double *x, double min, double max)\n{\n  *x = mod(*x - min, max - min) + min;\n}\n\ninline void wrap_limit(double *x, double min, double max)\n{\n\n  *x = fmax(fmin(*x, max), min);\n}\n\ninline int mod_int(int y, int x)\n{\n  if(y >= 0)\n    return y - (y/x)*x;\n  else\n    return (x-1) - mod_int(-y-1, x);\n}\n\ninline double dnest_randh()\n{\n  return pow(10.0, 1.5 - 3.0*fabs(gsl_ran_tdist(dnest_gsl_r, 2))) * gsl_ran_ugaussian(dnest_gsl_r);\n}\n\ninline double dnest_rand()\n{\n  return gsl_rng_uniform(dnest_gsl_r);\n}\n\ninline int dnest_rand_int(int size)\n{\n  return gsl_rng_uniform_int(dnest_gsl_r, size);\n}\n\ninline double dnest_randn()\n{\n  return gsl_ran_ugaussian(dnest_gsl_r);\n}\n\nint dnest_cmp(const void *pa, const void *pb)\n{\n  LikelihoodType *a = (LikelihoodType *)pa;\n  LikelihoodType *b = (LikelihoodType *)pb;\n\n  // in decesending order\n  if(a->value > b->value)\n    return false;\n  if( a->value == b->value && a->tiebreaker > b->tiebreaker)\n    return false;\n  \n  return true;\n}\n\n\ninline int dnest_get_size_levels()\n{\n  return size_levels;\n}\n\ninline int dnest_get_which_level_update()\n{\n  return dnest_which_level_update;\n}\n\ninline int dnest_get_which_particle_update()\n{\n  return dnest_which_particle_update;\n}\n\ninline unsigned int dnest_get_which_num_saves()\n{\n  return num_saves;\n}\nunsigned int dnest_get_count_saves()\n{\n  return count_saves;\n}\n\ninline unsigned long long int dnest_get_count_mcmc_steps()\n{\n  return count_mcmc_steps;\n}\n\ninline void dnest_get_posterior_sample_file(char *fname)\n{\n  strcpy(fname, options.posterior_sample_file);\n  return;\n}\n\ninline void dnest_get_limit(int ilevel, int jparam, double *limit1, double *limit2)\n{\n  *limit1 = limits[ilevel*dnest_num_params*2 + jparam * 2 + 0];\n  *limit2 = limits[ilevel*dnest_num_params*2 + jparam * 2 + 1];\n  return;\n}\n/* \n * version check\n * \n *  1: greater\n *  0: equal\n * -1: lower\n */\nint dnest_check_version(char *version_str)\n{\n  int major, minor, patch;\n\n  sscanf(version_str, \"%d.%d.%d\", &major, &minor, &patch);\n  \n  if(major > DNEST_MAJOR_VERSION)\n    return 1;\n  if(major < DNEST_MAJOR_VERSION)\n    return -1;\n\n  if(minor > DNEST_MINOR_VERSION)\n    return 1;\n  if(minor < DNEST_MINOR_VERSION)\n    return -1;\n\n  if(patch > DNEST_PATCH_VERSION)\n    return 1;\n  if(patch > DNEST_PATCH_VERSION)\n    return -1;\n\n  return 0;\n}\n\nvoid dnest_check_fptrset(DNestFptrSet *fptrset)\n{\n  if(fptrset->from_prior == NULL)\n  {\n    printf(\"\\\"from_prior\\\" function is not defined at task %d.\\\n      \\nSet to the default function in dnest.\\n\", dnest_thistask);\n    fptrset->from_prior = dnest_from_prior;\n  }\n\n  if(fptrset->print_particle == NULL)\n  {\n    printf(\"\\\"print_particle\\\" function is not defined at task %d. \\\n      \\nSet to be default function in dnest.\\n\", dnest_thistask);\n    fptrset->print_particle = dnest_print_particle;\n  }\n\n  if(fptrset->read_particle == NULL)\n  {\n    printf(\"\\\"read_particle\\\" function is not defined at task %d. \\\n      \\nSet to be default function in dnest.\\n\", dnest_thistask);\n    fptrset->read_particle = dnest_read_particle;\n  }\n\n  if(fptrset->log_likelihoods_cal == NULL)\n  {\n    printf(\"\\\"log_likelihoods_cal\\\" function is not defined at task %d.\\n\", dnest_thistask);\n    exit(0);\n  }\n\n  if(fptrset->log_likelihoods_cal_initial == NULL)\n  {\n    printf(\"\\\"log_likelihoods_cal_initial\\\" function is not defined at task %d. \\\n      \\nSet to the same as \\\"log_likelihoods_cal\\\" function.\\n\", dnest_thistask);\n    fptrset->log_likelihoods_cal_initial = fptrset->log_likelihoods_cal;\n  }\n\n  if(fptrset->log_likelihoods_cal_restart == NULL)\n  {\n    printf(\"\\\"log_likelihoods_cal_restart\\\" function is not defined at task %d. \\\n      \\nSet to the same as \\\"log_likelihoods_cal\\\" function.\\n\", dnest_thistask);\n    fptrset->log_likelihoods_cal_restart = fptrset->log_likelihoods_cal;\n  }\n\n  if(fptrset->perturb == NULL)\n  {\n    printf(\"\\\"perturb\\\" function is not defined at task %d.\\\n      \\nSet to the default function in dnest.\\n\", dnest_thistask);\n    fptrset->perturb = dnest_perturb;\n  }\n\n  if(fptrset->restart_action == NULL)\n  {\n    printf(\"\\\"restart_action\\\" function is not defined at task %d.\\\n      \\nSet to the default function in dnest.\\n\", dnest_thistask);\n    fptrset->restart_action = dnest_restart_action;\n  }\n\n  if(fptrset->accept_action == NULL)\n  {\n    printf(\"\\\"accept_action\\\" function is not defined at task %d.\\\n      \\nSet to the default function in dnest.\\n\", dnest_thistask);\n    fptrset->accept_action = dnest_accept_action;\n  }\n\n  if(fptrset->kill_action == NULL)\n  {\n    printf(\"\\\"kill_action\\\" function is not defined at task %d.\\\n      \\nSet to the default function in dnest.\\n\", dnest_thistask);\n    fptrset->kill_action = dnest_kill_action;\n  }\n\n  return;\n}\n\nDNestFptrSet * dnest_malloc_fptrset()\n{\n  DNestFptrSet * fptrset;\n  fptrset = (DNestFptrSet *)malloc(sizeof(DNestFptrSet));\n\n  fptrset->from_prior = NULL;\n  fptrset->log_likelihoods_cal = NULL;\n  fptrset->log_likelihoods_cal_initial = NULL;\n  fptrset->log_likelihoods_cal_restart = NULL;\n  fptrset->perturb = NULL;\n  fptrset->print_particle = NULL;\n  fptrset->read_particle = NULL;\n  fptrset->restart_action = NULL;\n  fptrset->accept_action = NULL;\n  fptrset->kill_action = NULL;\n  return fptrset;\n}\n\ninline void dnest_free_fptrset(DNestFptrSet * fptrset)\n{\n  free(fptrset);\n  return;\n}\n\nvoid dnest_check_directory(char *sample_dir)\n{\n  /* check if sample_dir exists\n   * if not, create it;\n   * if exists, check if it is a directory;\n   * if not, throw an error.*/\n  struct stat st;\n  int status;\n  status = stat(sample_dir, &st);\n  if(status != 0)\n  {\n    printf(\"================================\\n\"\n           \"Directory %s not exist! create it.\\n\", sample_dir);\n    status = mkdir(sample_dir, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);\n    if(status!=0)\n    {\n      printf(\"Cannot create %s\\n\"\n             \"================================\\n\", sample_dir);\n    }\n  }\n  else\n  {\n    if(!S_ISDIR(st.st_mode))\n    {\n      printf(\"================================\\n\"\n             \"%s is not a direcotry!\\n\"\n             \"================================\\n\", sample_dir);\n      exit(-1);\n    }\n  }\n  return;\n}\n\n/*!\n *  Save sampler state for later restart. \n */\nvoid dnest_save_restart()\n{\n  FILE *fp;\n  int i, j;\n  void *particles_all;\n  LikelihoodType *log_likelihoods_all;\n  unsigned int *level_assignments_all;\n  char str[200];\n\n  if(dnest_thistask == dnest_root)\n  {\n    sprintf(str, \"%s_%d\", file_save_restart, count_saves);\n    fp = fopen(str, \"wb\");\n    if(fp == NULL)\n    {\n      fprintf(stderr, \"# Error: Cannot open file %s. \\n\", file_save_restart);\n      exit(0);\n    }\n\n    particles_all = (void *)malloc( options.num_particles *  dnest_totaltask * dnest_size_of_modeltype );\n\n\n    log_likelihoods_all = (LikelihoodType *)malloc(dnest_totaltask * options.num_particles * sizeof(LikelihoodType));\n    level_assignments_all = (unsigned int*)malloc(dnest_totaltask * options.num_particles * sizeof(unsigned int));\n  }\n\n  MPI_Gather(particles, options.num_particles * dnest_size_of_modeltype, MPI_BYTE, \n    particles_all, options.num_particles * dnest_size_of_modeltype, MPI_BYTE, dnest_root, MPI_COMM_WORLD);\n\n  MPI_Gather(level_assignments, options.num_particles * sizeof(unsigned int), MPI_BYTE, \n    level_assignments_all, options.num_particles * sizeof(unsigned int), MPI_BYTE, dnest_root, MPI_COMM_WORLD);\n\n  MPI_Gather(log_likelihoods, options.num_particles * sizeof(LikelihoodType), MPI_BYTE, \n    log_likelihoods_all, options.num_particles * sizeof(LikelihoodType), MPI_BYTE, dnest_root, MPI_COMM_WORLD);\n\n\n  if(dnest_thistask == dnest_root )\n  {\n    printf(\"# Save restart data to file %s.\\n\", str);\n\n    //fprintf(fp, \"%d %d\\n\", count_saves, count_mcmc_steps);\n    //fprintf(fp, \"%d\\n\", size_levels_combine);\n\n    fwrite(&count_saves, sizeof(int), 1, fp);\n    fwrite(&count_mcmc_steps, sizeof(int), 1, fp);\n    fwrite(&size_levels_combine, sizeof(int), 1, fp);\n\n    for(i=0; i<size_levels_combine; i++)\n    {\n      //fprintf(fp, \"%14.12g %14.12g %f %llu %llu %llu %llu\\n\", levels_combine[i].log_X, levels_combine[i].log_likelihood.value, \n      //  levels_combine[i].log_likelihood.tiebreaker, levels_combine[i].accepts,\n      //  levels_combine[i].tries, levels[i].exceeds, levels_combine[i].visits);\n\n      fwrite(&levels_combine[i], sizeof(Level), 1, fp);\n    }\n\n    for(j=0; j<dnest_totaltask; j++)\n    {\n      for(i=0; i<options.num_particles; i++)\n      {\n        //fprintf(fp, \"%d %e %f\\n\", level_assignments_all[j*options.num_particles + i], \n        //  log_likelihoods_all[j*options.num_particles + i].value,\n        //  log_likelihoods_all[j*options.num_particles + i].tiebreaker);  \n\n        fwrite(&level_assignments_all[j*options.num_particles + i], sizeof(int), 1, fp);\n        fwrite(&log_likelihoods_all[j*options.num_particles + i], sizeof(LikelihoodType), 1, fp);    \n      }\n    }\n    \n    if(dnest_flag_limits == 1)\n    {\n      for(i=0; i<size_levels_combine; i++)\n      {\n        //fprintf(fp, \"%d  \", i);\n        for(j=0; j<particle_offset_double; j++)\n        {\n          //fprintf(fp, \"%f  %f  \", limits[i*2*particle_offset_double+j*2], limits[i*2*particle_offset_double+j*2+1]);\n          fwrite(&limits[i*2*particle_offset_double+j*2], sizeof(double), 2, fp);\n        }\n  \n          //fprintf(fp, \"\\n\");\n      }\n    }\n    \n    for(j=0; j<dnest_totaltask; j++)\n    {\n      for(i=0; i<options.num_particles; i++)\n      {\n        //print_particle(fp, particles_all + (j * options.num_particles + i) * particle_offset_size);\n        fwrite(particles_all + (j * options.num_particles + i) * particle_offset_size, dnest_size_of_modeltype, 1, fp);\n      } \n    }\n    \n    fclose(fp);\n    free(particles_all);\n    free(log_likelihoods_all);\n    free(level_assignments_all);\n  }\n\n  restart_action(0);\n}\n\nvoid dnest_restart()\n{\n  FILE *fp;\n  int i, j;\n  void *particles_all;\n  unsigned int *level_assignments_all;\n  LikelihoodType *log_likelihoods_all;\n  void *particle;\n\n  if(dnest_thistask == dnest_root)\n  {\n    fp = fopen(file_restart, \"rb\");\n    if(fp == NULL)\n    {\n      fprintf(stderr, \"# Error: Cannot open file %s. \\n\", file_restart);\n      exit(0);\n    }\n\n    printf(\"# Reading %s\\n\", file_restart);\n\n    particles_all = (void *)malloc( options.num_particles *  dnest_totaltask * dnest_size_of_modeltype );\n    log_likelihoods_all = (LikelihoodType *)malloc(dnest_totaltask * options.num_particles * sizeof(LikelihoodType));\n    level_assignments_all = (unsigned int*)malloc(dnest_totaltask * options.num_particles * sizeof(unsigned int));\n\n    fread(&count_saves, sizeof(int), 1, fp);\n    fread(&count_mcmc_steps, sizeof(int), 1, fp);\n    fread(&size_levels_combine, sizeof(int), 1, fp);\n    \n    /* consider that the newly input max_num_levels may be different from the saved size of levels */\n    if(options.max_num_levels != 0)\n    {\n      if(size_levels_combine > options.max_num_levels)\n      {\n        printf(\"# input max_num_levels %d smaller than the one in restart data %d.\\n\", options.max_num_levels, size_levels_combine);\n        size_levels = options.max_num_levels;\n      }\n      else\n      {\n        size_levels = size_levels_combine;\n      }\n        \n    }\n    else  /* not input max_num_levels, directly use the saved size of levels */\n    {\n      if(size_levels_combine > LEVEL_NUM_MAX)\n      {\n        printf(\"# the saved size of levels %d exceeds LEVEL_NUM_MAX %d. \\n\", size_levels_combine, LEVEL_NUM_MAX);\n        exit(EXIT_FAILURE);\n      }\n      else\n      {\n        size_levels = size_levels_combine;\n      }\n    }\n    // read levels\n    for(i=0; i<size_levels_combine; i++)\n    {     \n      if(i<size_levels) // not read all the levels\n        fread(&levels_combine[i], sizeof(Level), 1, fp);\n      else\n        fseek(fp, sizeof(Level), SEEK_CUR); /* offset the file point */\n    }\n    memcpy(levels, levels_combine, size_levels * sizeof(Level));\n\n    // read level assignment\n    for(j=0; j<dnest_totaltask; j++)\n    {\n      for(i=0; i<options.num_particles; i++)\n      {\n        fread(&level_assignments_all[j*options.num_particles + i], sizeof(int), 1, fp);\n        fread(&log_likelihoods_all[j*options.num_particles + i], sizeof(LikelihoodType), 1, fp); \n        \n        /* reset the level assignment that exceeds the present maximum level */\n        if(level_assignments_all[j*options.num_particles + i] > size_levels -1)\n        {\n          level_assignments_all[j*options.num_particles + i] = size_levels - 1;\n        }\n      }\n    }\n\n    // read limits\n    if(dnest_flag_limits == 1)\n    {\n      for(i=0; i<size_levels_combine; i++)\n      {\n        if(i < size_levels)\n        {\n          for(j=0; j<particle_offset_double; j++)\n          {\n            fread(&limits[i*2*particle_offset_double+j*2], sizeof(double), 2, fp);      \n          }\n        }\n        else \n        {\n          fseek(fp, sizeof(double) * 2 * particle_offset_double, SEEK_CUR); /* offset the file point */\n        }\n      }\n    }\n\n    // read particles\n    for(j=0; j<dnest_totaltask; j++)\n    {\n      for(i=0; i<options.num_particles; i++)\n      {\n        particle = (particles_all + (j * options.num_particles + i) * dnest_size_of_modeltype);\n        fread(particle, dnest_size_of_modeltype, 1, fp);\n      }\n    }\n\n    fclose(fp);\n  }\n\n  MPI_Bcast(&count_saves, 1, MPI_INT, dnest_root, MPI_COMM_WORLD);\n  MPI_Bcast(&count_mcmc_steps, 1, MPI_INT, dnest_root, MPI_COMM_WORLD);\n  MPI_Bcast(&size_levels, 1, MPI_INT, dnest_root, MPI_COMM_WORLD);\n  MPI_Bcast(levels, size_levels * sizeof(Level), MPI_BYTE, dnest_root,  MPI_COMM_WORLD); \n  \n  if(count_saves > options.max_num_saves)\n  {\n    if(dnest_thistask == dnest_root)\n    {\n      printf(\"# Number of samples already larger than the input number, exit!\\n\");\n    }\n    MPI_Barrier(MPI_COMM_WORLD);\n    exit(0);\n  }\n  size_levels_combine = size_levels; /* reset szie_levels_combine */\n  \n  num_saves = (int)fmax(0.02*(options.max_num_saves-count_saves), 1.0); /* reset num_saves */\n  num_saves_restart = (int)fmax(0.2 * (options.max_num_saves-count_saves), 1.0); /* reset num_saves_restart */\n\n  if(dnest_flag_limits == 1)\n    MPI_Bcast(limits, size_levels * particle_offset_double * 2, MPI_DOUBLE, dnest_root, MPI_COMM_WORLD);\n\n  MPI_Scatter(level_assignments_all, options.num_particles * sizeof(unsigned int), MPI_BYTE,\n      level_assignments, options.num_particles * sizeof(unsigned int), MPI_BYTE, dnest_root, MPI_COMM_WORLD);\n\n  MPI_Scatter(log_likelihoods_all, options.num_particles * sizeof(LikelihoodType), MPI_BYTE, \n      log_likelihoods, options.num_particles * sizeof(LikelihoodType), MPI_BYTE, dnest_root, MPI_COMM_WORLD);\n\n  MPI_Scatter(particles_all, options.num_particles * dnest_size_of_modeltype, MPI_BYTE, \n    particles, options.num_particles * dnest_size_of_modeltype, MPI_BYTE, dnest_root, MPI_COMM_WORLD);\n\n  \n  restart_action(1);\n\n  for(i=0; i<options.num_particles; i++)\n  {\n    dnest_which_particle_update = i;\n    dnest_which_level_update = level_assignments[i];\n    //printf(\"%d %d %f\\n\", thistask, i, log_likelihoods[i].value);\n    log_likelihoods[i].value = log_likelihoods_cal_restart(particles+i*particle_offset_size);\n    //printf(\"%d %d %f\\n\", thistask, i, log_likelihoods[i].value);\n    //due to randomness, the original level assignment may be incorrect. re-asign the level\n    while(log_likelihoods[i].value < levels[level_assignments[i]].log_likelihood.value)\n    {\n      printf(\"# level assignment decrease %d %f %f %d.\\n\", i, log_likelihoods[i].value, \n        levels[level_assignments[i]].log_likelihood.value, level_assignments[i]);\n      level_assignments[i]--;\n    }\n    \n  }\n\n  if(dnest_thistask == dnest_root)\n  {\n    free(particles_all);\n    free(log_likelihoods_all);\n    free(level_assignments_all);\n  }\n  return;\n}\n\nvoid dnest_from_prior(void *model)\n{\n  int i;\n  double *pm = (double *)model;\n\n  for(i=0; i<dnest_num_params; i++)\n  {\n    if(dnest_prior_type[i] == GAUSSIAN )\n    {\n      pm[i] = dnest_randn() * dnest_prior_info[i*2+1] + dnest_prior_info[i*2+0];\n      dnest_wrap(&pm[i], dnest_param_range[i*2+0], dnest_param_range[i*2+1]);\n    }\n    else if(dnest_prior_type[i] == LOG)\n    {\n      pm[i] = log(dnest_param_range[i*2+0]) + dnest_rand()*(log(dnest_param_range[i*2+1]) - log(dnest_param_range[i*2+0]));\n      pm[i] = exp(pm[i]);\n    }\n    else \n    {\n      pm[i] = dnest_param_range[i*2+0] + dnest_rand()*(dnest_param_range[i*2+1] - dnest_param_range[i*2+0]);\n    }\n  }\n}\n\ndouble dnest_perturb(void *model)\n{\n  double *pm = (double *)model;\n  double logH = 0.0, width;\n  int which;\n\n  which = dnest_rand_int(dnest_num_params);\n\n  width = ( dnest_param_range[which*2+1] - dnest_param_range[which*2+0] );\n\n  if(dnest_prior_type[which] == UNIFORM)\n  {\n    pm[which] += dnest_randh() * width;\n    dnest_wrap(&(pm[which]), dnest_param_range[which*2+0], dnest_param_range[which*2+1]);\n  }\n  else if(dnest_prior_type[which] == LOG)\n  {\n    logH -= (-log(pm[which]));\n    pm[which] += dnest_randh() * width;\n    dnest_wrap(&(pm[which]), dnest_param_range[which*2+0], dnest_param_range[which*2+1]);\n    logH += (-log(pm[which]));\n  }\n  else\n  {\n    logH -= (-0.5*pow((pm[which] - dnest_prior_info[which*2+0])/dnest_prior_info[which*2+1], 2.0) );\n    pm[which] += dnest_randh() * width;\n    dnest_wrap(&pm[which], dnest_param_range[which*2+0], dnest_param_range[which*2+1]);\n    logH += (-0.5*pow((pm[which] - dnest_prior_info[which*2+0])/dnest_prior_info[which*2+1], 2.0) );\n  }\n  \n  return logH;\n}\n\ninline void dnest_print_particle(FILE *fp, const void *model)\n{\n  int i;\n  double *pm = (double *)model;\n\n  for(i=0; i<dnest_num_params; i++)\n  {\n    fprintf(fp, \"%e \", pm[i] );\n  }\n  fprintf(fp, \"\\n\");\n  return;\n}\n\nvoid dnest_read_particle(FILE *fp, void *model)\n{\n  int j;\n  double *psample = (double *)model;\n\n  for(j=0; j < dnest_num_params; j++)\n  {\n    if(fscanf(fp, \"%lf\", psample+j) < 1)\n    {\n      printf(\"%f\\n\", *psample);\n      fprintf(stderr, \"#Error: Cannot read file %s.\\n\", options.sample_file);\n      exit(0);\n    }\n  }\n  return;\n}\n\ninline void dnest_restart_action(int iflag)\n{\n  return;\n}\n\ninline void dnest_accept_action()\n{\n  return;\n}\n\ninline void dnest_kill_action(int i, int i_copy)\n{\n  return;\n}", "meta": {"hexsha": "06c24b3da622218366a3b15222e9111a0c3f7eed", "size": 61608, "ext": "c", "lang": "C", "max_stars_repo_path": "src/dnest.c", "max_stars_repo_name": "LiyrAstroph/CDNest", "max_stars_repo_head_hexsha": "afb6b869ce1c4ebd76662b20310f1d9d3db4e26e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-09-11T03:34:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-16T12:14:05.000Z", "max_issues_repo_path": "src/dnest.c", "max_issues_repo_name": "LiyrAstroph/DNest_C", "max_issues_repo_head_hexsha": "afb6b869ce1c4ebd76662b20310f1d9d3db4e26e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-05-14T10:04:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-06T02:04:19.000Z", "max_forks_repo_path": "src/dnest.c", "max_forks_repo_name": "LiyrAstroph/DNest_C", "max_forks_repo_head_hexsha": "afb6b869ce1c4ebd76662b20310f1d9d3db4e26e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8777885548, "max_line_length": 135, "alphanum_fraction": 0.6487144527, "num_tokens": 16972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4765796510636759, "lm_q2_score": 0.048857781911394844, "lm_q1q2_score": 0.023284624655077732}}
{"text": "#include <gsl/gsl_test.h>\n#include <gsl/gsl_ieee_utils.h>\n#include <gsl/gsl_math.h>\n#include \"gsl_cblas.h\"\n\n#include \"tests.h\"\n\nvoid\ntest_tbmv (void) {\nconst double flteps = 1e-4, dbleps = 1e-6;\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 131;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   float A[] = { 0.439f, -0.484f, -0.952f, -0.508f, 0.381f, -0.889f, -0.192f, -0.279f, -0.155f };\n   float X[] = { -0.089f, -0.688f, -0.203f };\n   int incX = -1;\n   float x_expected[] = { 0.017088f, 0.315595f, 0.243875f };\n   cblas_stbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"stbmv(case 894)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 132;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   float A[] = { 0.439f, -0.484f, -0.952f, -0.508f, 0.381f, -0.889f, -0.192f, -0.279f, -0.155f };\n   float X[] = { -0.089f, -0.688f, -0.203f };\n   int incX = -1;\n   float x_expected[] = { -0.089f, -0.721909f, 0.129992f };\n   cblas_stbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"stbmv(case 895)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 131;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   float A[] = { 0.439f, -0.484f, -0.952f, -0.508f, 0.381f, -0.889f, -0.192f, -0.279f, -0.155f };\n   float X[] = { -0.089f, -0.688f, -0.203f };\n   int incX = -1;\n   float x_expected[] = { 0.156927f, -0.159004f, 0.098252f };\n   cblas_stbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"stbmv(case 896)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 132;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   float A[] = { 0.439f, -0.484f, -0.952f, -0.508f, 0.381f, -0.889f, -0.192f, -0.279f, -0.155f };\n   float X[] = { -0.089f, -0.688f, -0.203f };\n   int incX = -1;\n   float x_expected[] = { 0.043096f, -0.584876f, -0.203f };\n   cblas_stbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"stbmv(case 897)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 131;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   float A[] = { 0.439f, -0.484f, -0.952f, -0.508f, 0.381f, -0.889f, -0.192f, -0.279f, -0.155f };\n   float X[] = { -0.089f, -0.688f, -0.203f };\n   int incX = -1;\n   float x_expected[] = { 0.024831f, -0.24504f, 0.447756f };\n   cblas_stbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"stbmv(case 898)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 132;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   float A[] = { 0.439f, -0.484f, -0.952f, -0.508f, 0.381f, -0.889f, -0.192f, -0.279f, -0.155f };\n   float X[] = { -0.089f, -0.688f, -0.203f };\n   int incX = -1;\n   float x_expected[] = { -0.089f, -0.670912f, 0.146504f };\n   cblas_stbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"stbmv(case 899)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 131;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   float A[] = { 0.439f, -0.484f, -0.952f, -0.508f, 0.381f, -0.889f, -0.192f, -0.279f, -0.155f };\n   float X[] = { -0.089f, -0.688f, -0.203f };\n   int incX = -1;\n   float x_expected[] = { -0.24504f, 0.447756f, -0.089117f };\n   cblas_stbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"stbmv(case 900)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 132;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   float A[] = { 0.439f, -0.484f, -0.952f, -0.508f, 0.381f, -0.889f, -0.192f, -0.279f, -0.155f };\n   float X[] = { -0.089f, -0.688f, -0.203f };\n   int incX = -1;\n   float x_expected[] = { -0.351128f, -0.589748f, -0.203f };\n   cblas_stbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"stbmv(case 901)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 131;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   float A[] = { 0.94f, -0.091f, 0.984f, -0.276f, -0.342f, -0.484f, -0.665f, -0.2f, 0.349f };\n   float X[] = { 0.023f, -0.501f, -0.562f };\n   int incX = -1;\n   float x_expected[] = { 0.156047f, 0.189418f, -0.52828f };\n   cblas_stbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"stbmv(case 902)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 132;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   float A[] = { 0.94f, -0.091f, 0.984f, -0.276f, -0.342f, -0.484f, -0.665f, -0.2f, 0.349f };\n   float X[] = { 0.023f, -0.501f, -0.562f };\n   int incX = -1;\n   float x_expected[] = { 0.194342f, -0.449858f, -0.562f };\n   cblas_stbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"stbmv(case 903)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 131;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   float A[] = { 0.94f, -0.091f, 0.984f, -0.276f, -0.342f, -0.484f, -0.665f, -0.2f, 0.349f };\n   float X[] = { 0.023f, -0.501f, -0.562f };\n   int incX = -1;\n   float x_expected[] = { -0.0046f, 0.156047f, 0.189418f };\n   cblas_stbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"stbmv(case 904)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 132;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   float A[] = { 0.94f, -0.091f, 0.984f, -0.276f, -0.342f, -0.484f, -0.665f, -0.2f, 0.349f };\n   float X[] = { 0.023f, -0.501f, -0.562f };\n   int incX = -1;\n   float x_expected[] = { 0.023f, -0.516295f, -0.423724f };\n   cblas_stbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"stbmv(case 905)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 131;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   float A[] = { 0.94f, -0.091f, 0.984f, -0.276f, -0.342f, -0.484f, -0.665f, -0.2f, 0.349f };\n   float X[] = { 0.023f, -0.501f, -0.562f };\n   int incX = -1;\n   float x_expected[] = { 0.328565f, 0.326454f, 0.051142f };\n   cblas_stbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"stbmv(case 906)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 132;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   float A[] = { 0.94f, -0.091f, 0.984f, -0.276f, -0.342f, -0.484f, -0.665f, -0.2f, 0.349f };\n   float X[] = { 0.023f, -0.501f, -0.562f };\n   int incX = -1;\n   float x_expected[] = { 0.356165f, -0.345888f, -0.562f };\n   cblas_stbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"stbmv(case 907)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 131;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   float A[] = { 0.94f, -0.091f, 0.984f, -0.276f, -0.342f, -0.484f, -0.665f, -0.2f, 0.349f };\n   float X[] = { 0.023f, -0.501f, -0.562f };\n   int incX = -1;\n   float x_expected[] = { -0.015295f, 0.13041f, -0.482689f };\n   cblas_stbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"stbmv(case 908)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 132;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   float A[] = { 0.94f, -0.091f, 0.984f, -0.276f, -0.342f, -0.484f, -0.665f, -0.2f, 0.349f };\n   float X[] = { 0.023f, -0.501f, -0.562f };\n   int incX = -1;\n   float x_expected[] = { 0.023f, -0.508866f, -0.516409f };\n   cblas_stbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"stbmv(case 909)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 131;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   double A[] = { 0.566, 0.955, -0.086, -0.856, 0.177, 0.974, -0.652, -0.884, 0.77 };\n   double X[] = { -0.77, -0.818, 0.337 };\n   int incX = -1;\n   double x_expected[] = { 0.50204, 0.563918, -0.590448 };\n   cblas_dtbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtbmv(case 910)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 132;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   double A[] = { 0.566, 0.955, -0.086, -0.856, 0.177, 0.974, -0.652, -0.884, 0.77 };\n   double X[] = { -0.77, -0.818, 0.337 };\n   int incX = -1;\n   double x_expected[] = { -0.77, -0.95429, -0.44419 };\n   cblas_dtbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtbmv(case 911)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 131;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   double A[] = { 0.566, 0.955, -0.086, -0.856, 0.177, 0.974, -0.652, -0.884, 0.77 };\n   double X[] = { -0.77, -0.818, 0.337 };\n   int incX = -1;\n   double x_expected[] = { 1.214016, -0.433258, 0.321835 };\n   cblas_dtbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtbmv(case 912)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 132;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   double A[] = { 0.566, 0.955, -0.086, -0.856, 0.177, 0.974, -0.652, -0.884, 0.77 };\n   double X[] = { -0.77, -0.818, 0.337 };\n   int incX = -1;\n   double x_expected[] = { -0.236664, -1.106472, 0.337 };\n   cblas_dtbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtbmv(case 913)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 131;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   double A[] = { 0.566, 0.955, -0.086, -0.856, 0.177, 0.974, -0.652, -0.884, 0.77 };\n   double X[] = { -0.77, -0.818, 0.337 };\n   int incX = -1;\n   double x_expected[] = { 0.68068, 0.357254, 1.022043 };\n   cblas_dtbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtbmv(case 914)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 132;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   double A[] = { 0.566, 0.955, -0.086, -0.856, 0.177, 0.974, -0.652, -0.884, 0.77 };\n   double X[] = { -0.77, -0.818, 0.337 };\n   int incX = -1;\n   double x_expected[] = { -0.77, -0.31596, 1.037208 };\n   cblas_dtbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtbmv(case 915)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 131;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   double A[] = { 0.566, 0.955, -0.086, -0.856, 0.177, 0.974, -0.652, -0.884, 0.77 };\n   double X[] = { -0.77, -0.818, 0.337 };\n   int incX = -1;\n   double x_expected[] = { 0.357254, 1.022043, 0.190742 };\n   cblas_dtbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtbmv(case 916)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 132;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   double A[] = { 0.566, 0.955, -0.086, -0.856, 0.177, 0.974, -0.652, -0.884, 0.77 };\n   double X[] = { -0.77, -0.818, 0.337 };\n   int incX = -1;\n   double x_expected[] = { -0.914786, -0.496165, 0.337 };\n   cblas_dtbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtbmv(case 917)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 131;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   double A[] = { 0.188, 0.6, -0.743, -0.803, 0.449, -0.681, -0.464, -0.029, 0.553 };\n   double X[] = { -0.851, 0.481, 0.155 };\n   int incX = -1;\n   double x_expected[] = { 0.610833, -0.293243, 0.02914 };\n   cblas_dtbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtbmv(case 918)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 132;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   double A[] = { 0.188, 0.6, -0.743, -0.803, 0.449, -0.681, -0.464, -0.029, 0.553 };\n   double X[] = { -0.851, 0.481, 0.155 };\n   int incX = -1;\n   double x_expected[] = { -0.635031, 0.574, 0.155 };\n   cblas_dtbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtbmv(case 919)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 131;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   double A[] = { 0.188, 0.6, -0.743, -0.803, 0.449, -0.681, -0.464, -0.029, 0.553 };\n   double X[] = { -0.851, 0.481, 0.155 };\n   int incX = -1;\n   double x_expected[] = { 0.024679, 0.610833, -0.293243 };\n   cblas_dtbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtbmv(case 920)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 132;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   double A[] = { 0.188, 0.6, -0.743, -0.803, 0.449, -0.681, -0.464, -0.029, 0.553 };\n   double X[] = { -0.851, 0.481, 0.155 };\n   int incX = -1;\n   double x_expected[] = { -0.851, 0.875864, -0.231243 };\n   cblas_dtbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtbmv(case 921)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 131;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   double A[] = { 0.188, 0.6, -0.743, -0.803, 0.449, -0.681, -0.464, -0.029, 0.553 };\n   double X[] = { -0.851, 0.481, 0.155 };\n   int incX = -1;\n   double x_expected[] = { -0.198505, 0.091504, 0.093 };\n   cblas_dtbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtbmv(case 922)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 132;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   double A[] = { 0.188, 0.6, -0.743, -0.803, 0.449, -0.681, -0.464, -0.029, 0.553 };\n   double X[] = { -0.851, 0.481, 0.155 };\n   int incX = -1;\n   double x_expected[] = { -1.074184, 0.356535, 0.155 };\n   cblas_dtbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtbmv(case 923)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 131;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   double A[] = { 0.188, 0.6, -0.743, -0.803, 0.449, -0.681, -0.464, -0.029, 0.553 };\n   double X[] = { -0.851, 0.481, 0.155 };\n   int incX = -1;\n   double x_expected[] = { 0.394864, -0.768342, 0.31774 };\n   cblas_dtbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtbmv(case 924)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 132;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   double A[] = { 0.188, 0.6, -0.743, -0.803, 0.449, -0.681, -0.464, -0.029, 0.553 };\n   double X[] = { -0.851, 0.481, 0.155 };\n   int incX = -1;\n   double x_expected[] = { -0.851, 0.098901, 0.4436 };\n   cblas_dtbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtbmv(case 925)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 131;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   float A[] = { 0.824f, -0.45f, -0.987f, 0.758f, 0.42f, -0.357f, 0.147f, -0.191f, 0.88f, 0.63f, 0.155f, -0.573f, 0.224f, 0.146f, 0.501f, -0.889f, 0.456f, 0.796f };\n   float X[] = { -0.46f, 0.069f, 0.308f, -0.003f, -0.236f, 0.605f };\n   int incX = -1;\n   float x_expected[] = { -0.113114f, -0.051704f, -0.403567f, -0.288349f, -0.223936f, 0.841145f };\n   cblas_ctbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctbmv(case 926) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctbmv(case 926) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 132;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   float A[] = { 0.824f, -0.45f, -0.987f, 0.758f, 0.42f, -0.357f, 0.147f, -0.191f, 0.88f, 0.63f, 0.155f, -0.573f, 0.224f, 0.146f, 0.501f, -0.889f, 0.456f, 0.796f };\n   float X[] = { -0.46f, 0.069f, 0.308f, -0.003f, -0.236f, 0.605f };\n   int incX = -1;\n   float x_expected[] = { -0.46f, 0.069f, -0.14027f, -0.23208f, -0.537722f, 0.841425f };\n   cblas_ctbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctbmv(case 927) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctbmv(case 927) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 131;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   float A[] = { 0.824f, -0.45f, -0.987f, 0.758f, 0.42f, -0.357f, 0.147f, -0.191f, 0.88f, 0.63f, 0.155f, -0.573f, 0.224f, 0.146f, 0.501f, -0.889f, 0.456f, 0.796f };\n   float X[] = { -0.46f, 0.069f, 0.308f, -0.003f, -0.236f, 0.605f };\n   int incX = -1;\n   float x_expected[] = { -0.099689f, 0.487805f, 0.353793f, 0.325411f, -0.225658f, -0.776023f };\n   cblas_ctbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctbmv(case 928) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctbmv(case 928) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 132;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   float A[] = { 0.824f, -0.45f, -0.987f, 0.758f, 0.42f, -0.357f, 0.147f, -0.191f, 0.88f, 0.63f, 0.155f, -0.573f, 0.224f, 0.146f, 0.501f, -0.889f, 0.456f, 0.796f };\n   float X[] = { -0.46f, 0.069f, 0.308f, -0.003f, -0.236f, 0.605f };\n   int incX = -1;\n   float x_expected[] = { -0.39057f, 0.113296f, 0.388863f, 0.131011f, -0.236f, 0.605f };\n   cblas_ctbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctbmv(case 929) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctbmv(case 929) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 131;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   float A[] = { 0.824f, -0.45f, -0.987f, 0.758f, 0.42f, -0.357f, 0.147f, -0.191f, 0.88f, 0.63f, 0.155f, -0.573f, 0.224f, 0.146f, 0.501f, -0.889f, 0.456f, 0.796f };\n   float X[] = { -0.46f, 0.069f, 0.308f, -0.003f, -0.236f, 0.605f };\n   int incX = -1;\n   float x_expected[] = { -0.169119f, 0.443509f, 0.159816f, 0.139696f, -0.180955f, -0.835292f };\n   cblas_ctbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctbmv(case 930) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctbmv(case 930) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 132;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   float A[] = { 0.824f, -0.45f, -0.987f, 0.758f, 0.42f, -0.357f, 0.147f, -0.191f, 0.88f, 0.63f, 0.155f, -0.573f, 0.224f, 0.146f, 0.501f, -0.889f, 0.456f, 0.796f };\n   float X[] = { -0.46f, 0.069f, 0.308f, -0.003f, -0.236f, 0.605f };\n   int incX = -1;\n   float x_expected[] = { -0.46f, 0.069f, 0.194886f, -0.054704f, -0.191297f, 0.545731f };\n   cblas_ctbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctbmv(case 931) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctbmv(case 931) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 131;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   float A[] = { 0.824f, -0.45f, -0.987f, 0.758f, 0.42f, -0.357f, 0.147f, -0.191f, 0.88f, 0.63f, 0.155f, -0.573f, 0.224f, 0.146f, 0.501f, -0.889f, 0.456f, 0.796f };\n   float X[] = { -0.46f, 0.069f, 0.308f, -0.003f, -0.236f, 0.605f };\n   int incX = -1;\n   float x_expected[] = { 0.159816f, 0.139696f, -0.180955f, -0.835292f, 0.077786f, 0.60472f };\n   cblas_ctbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctbmv(case 932) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctbmv(case 932) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 132;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   float A[] = { 0.824f, -0.45f, -0.987f, 0.758f, 0.42f, -0.357f, 0.147f, -0.191f, 0.88f, 0.63f, 0.155f, -0.573f, 0.224f, 0.146f, 0.501f, -0.889f, 0.456f, 0.796f };\n   float X[] = { -0.46f, 0.069f, 0.308f, -0.003f, -0.236f, 0.605f };\n   int incX = -1;\n   float x_expected[] = { -0.18707f, 0.2604f, 0.082342f, -0.779023f, -0.236f, 0.605f };\n   cblas_ctbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctbmv(case 933) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctbmv(case 933) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 131;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   float A[] = { -0.814f, 0.043f, -0.755f, -0.094f, 0.876f, 0.257f, 0.406f, 0.491f, -0.27f, -0.787f, 0.545f, 0.732f, -0.512f, -0.085f, 0.234f, 0.001f, -0.225f, -0.002f };\n   float X[] = { 0.411f, -0.308f, -0.912f, 0.811f, -0.894f, -0.116f };\n   int incX = -1;\n   float x_expected[] = { 0.647885f, 0.621535f, -0.104407f, 0.05309f, 0.732704f, 0.055982f };\n   cblas_ctbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctbmv(case 934) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctbmv(case 934) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 132;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   float A[] = { -0.814f, 0.043f, -0.755f, -0.094f, 0.876f, 0.257f, 0.406f, 0.491f, -0.27f, -0.787f, 0.545f, 0.732f, -0.512f, -0.085f, 0.234f, 0.001f, -0.225f, -0.002f };\n   float X[] = { 0.411f, -0.308f, -0.912f, 0.811f, -0.894f, -0.116f };\n   int incX = -1;\n   float x_expected[] = { 1.2955f, 0.190774f, -0.247934f, 0.982616f, -0.894f, -0.116f };\n   cblas_ctbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctbmv(case 935) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctbmv(case 935) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 131;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   float A[] = { -0.814f, 0.043f, -0.755f, -0.094f, 0.876f, 0.257f, 0.406f, 0.491f, -0.27f, -0.787f, 0.545f, 0.732f, -0.512f, -0.085f, 0.234f, 0.001f, -0.225f, -0.002f };\n   float X[] = { 0.411f, -0.308f, -0.912f, 0.811f, -0.894f, -0.116f };\n   int incX = -1;\n   float x_expected[] = { 0.096482f, -0.071661f, 0.647885f, 0.621535f, -0.104407f, 0.05309f };\n   cblas_ctbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctbmv(case 936) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctbmv(case 936) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 132;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   float A[] = { -0.814f, 0.043f, -0.755f, -0.094f, 0.876f, 0.257f, 0.406f, 0.491f, -0.27f, -0.787f, 0.545f, 0.732f, -0.512f, -0.085f, 0.234f, 0.001f, -0.225f, -0.002f };\n   float X[] = { 0.411f, -0.308f, -0.912f, 0.811f, -0.894f, -0.116f };\n   int incX = -1;\n   float x_expected[] = { 0.411f, -0.308f, -1.14861f, 0.933761f, -1.66247f, -0.234526f };\n   cblas_ctbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctbmv(case 937) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctbmv(case 937) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 131;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   float A[] = { -0.814f, 0.043f, -0.755f, -0.094f, 0.876f, 0.257f, 0.406f, 0.491f, -0.27f, -0.787f, 0.545f, 0.732f, -0.512f, -0.085f, 0.234f, 0.001f, -0.225f, -0.002f };\n   float X[] = { 0.411f, -0.308f, -0.912f, 0.811f, -0.894f, -0.116f };\n   int incX = -1;\n   float x_expected[] = { 0.632361f, -0.409373f, 0.578489f, 0.012724f, 0.664066f, 0.171616f };\n   cblas_ctbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctbmv(case 938) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctbmv(case 938) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 132;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   float A[] = { -0.814f, 0.043f, -0.755f, -0.094f, 0.876f, 0.257f, 0.406f, 0.491f, -0.27f, -0.787f, 0.545f, 0.732f, -0.512f, -0.085f, 0.234f, 0.001f, -0.225f, -0.002f };\n   float X[] = { 0.411f, -0.308f, -0.912f, 0.811f, -0.894f, -0.116f };\n   int incX = -1;\n   float x_expected[] = { 0.946879f, -0.645712f, -1.21801f, 0.32495f, -0.894f, -0.116f };\n   cblas_ctbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctbmv(case 939) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctbmv(case 939) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 131;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   float A[] = { -0.814f, 0.043f, -0.755f, -0.094f, 0.876f, 0.257f, 0.406f, 0.491f, -0.27f, -0.787f, 0.545f, 0.732f, -0.512f, -0.085f, 0.234f, 0.001f, -0.225f, -0.002f };\n   float X[] = { 0.411f, -0.308f, -0.912f, 0.811f, -0.894f, -0.116f };\n   int incX = -1;\n   float x_expected[] = { -0.236612f, 0.122761f, -1.12184f, -0.358823f, 1.4975f, -0.470595f };\n   cblas_ctbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctbmv(case 940) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctbmv(case 940) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 132;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   float A[] = { -0.814f, 0.043f, -0.755f, -0.094f, 0.876f, 0.257f, 0.406f, 0.491f, -0.27f, -0.787f, 0.545f, 0.732f, -0.512f, -0.085f, 0.234f, 0.001f, -0.225f, -0.002f };\n   float X[] = { 0.411f, -0.308f, -0.912f, 0.811f, -0.894f, -0.116f };\n   int incX = -1;\n   float x_expected[] = { 0.411f, -0.308f, -1.26537f, 0.570703f, -0.129206f, -0.642577f };\n   cblas_ctbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctbmv(case 941) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctbmv(case 941) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 113;\n   int uplo = 121;\n   int diag = 131;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   float A[] = { -0.675f, 0.047f, 0.695f, 0.724f, -0.438f, 0.991f, -0.188f, -0.06f, -0.093f, 0.302f, 0.842f, -0.753f, 0.465f, -0.972f, -0.058f, 0.988f, 0.093f, 0.164f };\n   float X[] = { 0.065f, -0.082f, -0.746f, 0.775f, 0.694f, -0.954f };\n   int incX = -1;\n   float x_expected[] = { 0.413357f, 0.178267f, -0.114618f, -1.35595f, -0.513288f, 0.611332f };\n   cblas_ctbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctbmv(case 942) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctbmv(case 942) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 113;\n   int uplo = 121;\n   int diag = 132;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   float A[] = { -0.675f, 0.047f, 0.695f, 0.724f, -0.438f, 0.991f, -0.188f, -0.06f, -0.093f, 0.302f, 0.842f, -0.753f, 0.465f, -0.972f, -0.058f, 0.988f, 0.093f, 0.164f };\n   float X[] = { 0.065f, -0.082f, -0.746f, 0.775f, 0.694f, -0.954f };\n   int incX = -1;\n   float x_expected[] = { 0.368428f, 0.071217f, -0.954366f, -0.390486f, 0.694f, -0.954f };\n   cblas_ctbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctbmv(case 943) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctbmv(case 943) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 113;\n   int uplo = 122;\n   int diag = 131;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   float A[] = { -0.675f, 0.047f, 0.695f, 0.724f, -0.438f, 0.991f, -0.188f, -0.06f, -0.093f, 0.302f, 0.842f, -0.753f, 0.465f, -0.972f, -0.058f, 0.988f, 0.093f, 0.164f };\n   float X[] = { 0.065f, -0.082f, -0.746f, 0.775f, 0.694f, -0.954f };\n   int incX = -1;\n   float x_expected[] = { -0.084786f, -0.059464f, 0.413357f, 0.178267f, -0.114618f, -1.35595f };\n   cblas_ctbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctbmv(case 944) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctbmv(case 944) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 113;\n   int uplo = 122;\n   int diag = 132;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   float A[] = { -0.675f, 0.047f, 0.695f, 0.724f, -0.438f, 0.991f, -0.188f, -0.06f, -0.093f, 0.302f, 0.842f, -0.753f, 0.465f, -0.972f, -0.058f, 0.988f, 0.093f, 0.164f };\n   float X[] = { 0.065f, -0.082f, -0.746f, 0.775f, 0.694f, -0.954f };\n   int incX = -1;\n   float x_expected[] = { 0.065f, -0.082f, -0.636071f, 0.80005f, 0.787748f, -1.14446f };\n   cblas_ctbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctbmv(case 945) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctbmv(case 945) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 113;\n   int uplo = 121;\n   int diag = 131;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   float A[] = { -0.675f, 0.047f, 0.695f, 0.724f, -0.438f, 0.991f, -0.188f, -0.06f, -0.093f, 0.302f, 0.842f, -0.753f, 0.465f, -0.972f, -0.058f, 0.988f, 0.093f, 0.164f };\n   float X[] = { 0.065f, -0.082f, -0.746f, 0.775f, 0.694f, -0.954f };\n   int incX = -1;\n   float x_expected[] = { -1.18498f, -0.424201f, 0.230196f, 0.374209f, -0.208366f, -1.16549f };\n   cblas_ctbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctbmv(case 946) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctbmv(case 946) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 113;\n   int uplo = 121;\n   int diag = 132;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   float A[] = { -0.675f, 0.047f, 0.695f, 0.724f, -0.438f, 0.991f, -0.188f, -0.06f, -0.093f, 0.302f, 0.842f, -0.753f, 0.465f, -0.972f, -0.058f, 0.988f, 0.093f, 0.164f };\n   float X[] = { 0.065f, -0.082f, -0.746f, 0.775f, 0.694f, -0.954f };\n   int incX = -1;\n   float x_expected[] = { -1.03519f, -0.446737f, -0.819232f, 0.995992f, 0.694f, -0.954f };\n   cblas_ctbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctbmv(case 947) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctbmv(case 947) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 113;\n   int uplo = 122;\n   int diag = 131;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   float A[] = { -0.675f, 0.047f, 0.695f, 0.724f, -0.438f, 0.991f, -0.188f, -0.06f, -0.093f, 0.302f, 0.842f, -0.753f, 0.465f, -0.972f, -0.058f, 0.988f, 0.093f, 0.164f };\n   float X[] = { 0.065f, -0.082f, -0.746f, 0.775f, 0.694f, -0.954f };\n   int incX = -1;\n   float x_expected[] = { 0.109929f, 0.02505f, 0.062939f, -0.202464f, -0.470658f, 1.69006f };\n   cblas_ctbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctbmv(case 948) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctbmv(case 948) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 113;\n   int uplo = 122;\n   int diag = 132;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   float A[] = { -0.675f, 0.047f, 0.695f, 0.724f, -0.438f, 0.991f, -0.188f, -0.06f, -0.093f, 0.302f, 0.842f, -0.753f, 0.465f, -0.972f, -0.058f, 0.988f, 0.093f, 0.164f };\n   float X[] = { 0.065f, -0.082f, -0.746f, 0.775f, 0.694f, -0.954f };\n   int incX = -1;\n   float x_expected[] = { 0.065f, -0.082f, -0.776809f, 0.762996f, 0.73663f, 0.124729f };\n   cblas_ctbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctbmv(case 949) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctbmv(case 949) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 131;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   double A[] = { -0.212, 0.612, 0.189, -0.046, -0.124, 0.82, 0.753, 0.727, 0.331, 0.116, 0.504, -0.673, -0.888, -0.277, -0.361, -0.909, 0.982, -0.124 };\n   double X[] = { 0.064, 0.169, -0.81, -0.779, -0.641, -0.103 };\n   int incX = -1;\n   double x_expected[] = { -0.010019, -0.1678, -0.042017, -1.112094, 0.010004, -0.480427 };\n   cblas_ztbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztbmv(case 950) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztbmv(case 950) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 132;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   double A[] = { -0.212, 0.612, 0.189, -0.046, -0.124, 0.82, 0.753, 0.727, 0.331, 0.116, 0.504, -0.673, -0.888, -0.277, -0.361, -0.909, 0.982, -0.124 };\n   double X[] = { 0.064, 0.169, -0.81, -0.779, -0.641, -0.103 };\n   int incX = -1;\n   double x_expected[] = { 0.064, 0.169, -0.80842, -0.715637, -0.829924, -0.212971 };\n   cblas_ztbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztbmv(case 951) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztbmv(case 951) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 131;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   double A[] = { -0.212, 0.612, 0.189, -0.046, -0.124, 0.82, 0.753, 0.727, 0.331, 0.116, 0.504, -0.673, -0.888, -0.277, -0.361, -0.909, 0.982, -0.124 };\n   double X[] = { 0.064, 0.169, -0.81, -0.779, -0.641, -0.103 };\n   int incX = -1;\n   double x_expected[] = { 0.634014, 0.796937, -0.585538, -0.895375, -0.125887, 0.010019 };\n   cblas_ztbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztbmv(case 952) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztbmv(case 952) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 132;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   double A[] = { -0.212, 0.612, 0.189, -0.046, -0.124, 0.82, 0.753, 0.727, 0.331, 0.116, 0.504, -0.673, -0.888, -0.277, -0.361, -0.909, 0.982, -0.124 };\n   double X[] = { 0.064, 0.169, -0.81, -0.779, -0.641, -0.103 };\n   int incX = -1;\n   double x_expected[] = { 0.567497, 1.085122, -1.217792, -1.322566, -0.641, -0.103 };\n   cblas_ztbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztbmv(case 953) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztbmv(case 953) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 131;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   double A[] = { -0.212, 0.612, 0.189, -0.046, -0.124, 0.82, 0.753, 0.727, 0.331, 0.116, 0.504, -0.673, -0.888, -0.277, -0.361, -0.909, 0.982, -0.124 };\n   double X[] = { 0.064, 0.169, -0.81, -0.779, -0.641, -0.103 };\n   int incX = -1;\n   double x_expected[] = { 0.130517, -0.119185, -0.187765, -0.519609, -0.169484, -1.165438 };\n   cblas_ztbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztbmv(case 954) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztbmv(case 954) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 132;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   double A[] = { -0.212, 0.612, 0.189, -0.046, -0.124, 0.82, 0.753, 0.727, 0.331, 0.116, 0.504, -0.673, -0.888, -0.277, -0.361, -0.909, 0.982, -0.124 };\n   double X[] = { 0.064, 0.169, -0.81, -0.779, -0.641, -0.103 };\n   int incX = -1;\n   double x_expected[] = { 0.064, 0.169, -0.820019, -0.9468, -0.684597, -1.278457 };\n   cblas_ztbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztbmv(case 955) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztbmv(case 955) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 131;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   double A[] = { -0.212, 0.612, 0.189, -0.046, -0.124, 0.82, 0.753, 0.727, 0.331, 0.116, 0.504, -0.673, -0.888, -0.277, -0.361, -0.909, 0.982, -0.124 };\n   double X[] = { 0.064, 0.169, -0.81, -0.779, -0.641, -0.103 };\n   int incX = -1;\n   double x_expected[] = { -0.187765, -0.519609, -0.169484, -1.165438, 0.198928, -0.370456 };\n   cblas_ztbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztbmv(case 956) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztbmv(case 956) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 132;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   double A[] = { -0.212, 0.612, 0.189, -0.046, -0.124, 0.82, 0.753, 0.727, 0.331, 0.116, 0.504, -0.673, -0.888, -0.277, -0.361, -0.909, 0.982, -0.124 };\n   double X[] = { 0.064, 0.169, -0.81, -0.779, -0.641, -0.103 };\n   int incX = -1;\n   double x_expected[] = { -0.113746, -0.182809, -0.935887, -0.768981, -0.641, -0.103 };\n   cblas_ztbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztbmv(case 957) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztbmv(case 957) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 131;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   double A[] = { -0.374, -0.308, 0.792, 0.884, -0.794, -0.055, -0.281, 0.527, 0.246, 0.762, 0.853, 0.891, -0.231, 0.384, 0.373, -0.717, -0.957, -0.338 };\n   double X[] = { 0.884, 0.636, 0.921, 0.282, -0.649, 0.188 };\n   int incX = -1;\n   double x_expected[] = { -0.436746, 0.963714, -1.087615, -0.018695, 0.30063, 0.12958 };\n   cblas_ztbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztbmv(case 958) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztbmv(case 958) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 132;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   double A[] = { -0.374, -0.308, 0.792, 0.884, -0.794, -0.055, -0.281, 0.527, 0.246, 0.762, 0.853, 0.891, -0.231, 0.384, 0.373, -0.717, -0.957, -0.338 };\n   double X[] = { 0.884, 0.636, 0.921, 0.282, -0.649, 0.188 };\n   int incX = -1;\n   double x_expected[] = { 0.895682, 1.407174, 0.2408, -0.14282, -0.649, 0.188 };\n   cblas_ztbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztbmv(case 959) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztbmv(case 959) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 131;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   double A[] = { -0.374, -0.308, 0.792, 0.884, -0.794, -0.055, -0.281, 0.527, 0.246, 0.762, 0.853, 0.891, -0.231, 0.384, 0.373, -0.717, -0.957, -0.338 };\n   double X[] = { 0.884, 0.636, 0.921, 0.282, -0.649, 0.188 };\n   int incX = -1;\n   double x_expected[] = { 0.785744, -0.3966, -0.436746, 0.963714, -1.087615, -0.018695 };\n   cblas_ztbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztbmv(case 960) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztbmv(case 960) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 132;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   double A[] = { -0.374, -0.308, 0.792, 0.884, -0.794, -0.055, -0.281, 0.527, 0.246, 0.762, 0.853, 0.891, -0.231, 0.384, 0.373, -0.717, -0.957, -0.338 };\n   double X[] = { 0.884, 0.636, 0.921, 0.282, -0.649, 0.188 };\n   int incX = -1;\n   double x_expected[] = { 0.884, 0.636, 0.472572, 0.47454, -1.056415, 0.594125 };\n   cblas_ztbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztbmv(case 961) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztbmv(case 961) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 131;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   double A[] = { -0.374, -0.308, 0.792, 0.884, -0.794, -0.055, -0.281, 0.527, 0.246, 0.762, 0.853, 0.891, -0.231, 0.384, 0.373, -0.717, -0.957, -0.338 };\n   double X[] = { 0.884, 0.636, 0.921, 0.282, -0.649, 0.188 };\n   int incX = -1;\n   double x_expected[] = { 0.464705, -0.108078, 0.094975, 0.376323, -0.6802, -0.42482 };\n   cblas_ztbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztbmv(case 962) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztbmv(case 962) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 132;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   double A[] = { -0.374, -0.308, 0.792, 0.884, -0.794, -0.055, -0.281, 0.527, 0.246, 0.762, 0.853, 0.891, -0.231, 0.384, 0.373, -0.717, -0.957, -0.338 };\n   double X[] = { 0.884, 0.636, 0.921, 0.282, -0.649, 0.188 };\n   int incX = -1;\n   double x_expected[] = { 0.562961, 0.924522, 1.004293, -0.112851, -0.649, 0.188 };\n   cblas_ztbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztbmv(case 963) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztbmv(case 963) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 131;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   double A[] = { -0.374, -0.308, 0.792, 0.884, -0.794, -0.055, -0.281, 0.527, 0.246, 0.762, 0.853, 0.891, -0.231, 0.384, 0.373, -0.717, -0.957, -0.338 };\n   double X[] = { 0.884, 0.636, 0.921, 0.282, -0.649, 0.188 };\n   int incX = -1;\n   double x_expected[] = { -0.448428, 0.19254, -0.674583, 1.236189, 0.780774, 1.167088 };\n   cblas_ztbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztbmv(case 964) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztbmv(case 964) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 132;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   double A[] = { -0.374, -0.308, 0.792, 0.884, -0.794, -0.055, -0.281, 0.527, 0.246, 0.762, 0.853, 0.891, -0.231, 0.384, 0.373, -0.717, -0.957, -0.338 };\n   double X[] = { 0.884, 0.636, 0.921, 0.282, -0.649, 0.188 };\n   int incX = -1;\n   double x_expected[] = { 0.884, 0.636, 0.653832, 1.112064, -0.168856, 1.225508 };\n   cblas_ztbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztbmv(case 965) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztbmv(case 965) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 113;\n   int uplo = 121;\n   int diag = 131;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   double A[] = { 0.002, 0.95, -0.363, 0.084, -0.646, 0.816, -0.407, 0.099, -0.02, -0.906, -0.874, 0.191, -0.328, -0.968, 0.79, 0.826, -0.795, 0.277 };\n   double X[] = { -0.591, -0.084, 0.707, 0.945, 0.326, 0.428 };\n   int incX = -1;\n   double x_expected[] = { -0.59515, 0.077106, -0.27658, -0.637356, 0.407252, -0.308844 };\n   cblas_ztbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztbmv(case 966) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztbmv(case 966) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 113;\n   int uplo = 121;\n   int diag = 132;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   double A[] = { 0.002, 0.95, -0.363, 0.084, -0.646, 0.816, -0.407, 0.099, -0.02, -0.906, -0.874, 0.191, -0.328, -0.968, 0.79, 0.826, -0.795, 0.277 };\n   double X[] = { -0.591, -0.084, 0.707, 0.945, 0.326, 0.428 };\n   int incX = -1;\n   double x_expected[] = { -1.46131, 0.537642, 0.624614, 0.762252, 0.326, 0.428 };\n   cblas_ztbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztbmv(case 967) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztbmv(case 967) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 113;\n   int uplo = 122;\n   int diag = 131;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   double A[] = { 0.002, 0.95, -0.363, 0.084, -0.646, 0.816, -0.407, 0.099, -0.02, -0.906, -0.874, 0.191, -0.328, -0.968, 0.79, 0.826, -0.795, 0.277 };\n   double X[] = { -0.591, -0.084, 0.707, 0.945, 0.326, 0.428 };\n   int incX = -1;\n   double x_expected[] = { -0.536274, 0.421806, -0.59515, 0.077106, -0.27658, -0.637356 };\n   cblas_ztbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztbmv(case 968) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztbmv(case 968) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 113;\n   int uplo = 122;\n   int diag = 132;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   double A[] = { 0.002, 0.95, -0.363, 0.084, -0.646, 0.816, -0.407, 0.099, -0.02, -0.906, -0.874, 0.191, -0.328, -0.968, 0.79, 0.826, -0.795, 0.277 };\n   double X[] = { -0.591, -0.084, 0.707, 0.945, 0.326, 0.428 };\n   int incX = -1;\n   double x_expected[] = { -0.591, -0.084, 0.98216, 0.400464, 0.131806, -0.026608 };\n   cblas_ztbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztbmv(case 969) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztbmv(case 969) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 113;\n   int uplo = 121;\n   int diag = 131;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   double A[] = { 0.002, 0.95, -0.363, 0.084, -0.646, 0.816, -0.407, 0.099, -0.02, -0.906, -0.874, 0.191, -0.328, -0.968, 0.79, 0.826, -0.795, 0.277 };\n   double X[] = { -0.591, -0.084, 0.707, 0.945, 0.326, 0.428 };\n   int incX = -1;\n   double x_expected[] = { -1.68293, 0.796222, -0.96062, 0.415172, -0.082386, -0.182748 };\n   cblas_ztbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztbmv(case 970) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztbmv(case 970) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 113;\n   int uplo = 121;\n   int diag = 132;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   double A[] = { 0.002, 0.95, -0.363, 0.084, -0.646, 0.816, -0.407, 0.099, -0.02, -0.906, -0.874, 0.191, -0.328, -0.968, 0.79, 0.826, -0.795, 0.277 };\n   double X[] = { -0.591, -0.084, 0.707, 0.945, 0.326, 0.428 };\n   int incX = -1;\n   double x_expected[] = { -1.737656, 0.290416, 0.61669, 0.73853, 0.326, 0.428 };\n   cblas_ztbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztbmv(case 971) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztbmv(case 971) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 113;\n   int uplo = 122;\n   int diag = 131;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   double A[] = { 0.002, 0.95, -0.363, 0.084, -0.646, 0.816, -0.407, 0.099, -0.02, -0.906, -0.874, 0.191, -0.328, -0.968, 0.79, 0.826, -0.795, 0.277 };\n   double X[] = { -0.591, -0.084, 0.707, 0.945, 0.326, 0.428 };\n   int incX = -1;\n   double x_expected[] = { 0.27516, -0.544536, -0.10627, -0.988374, 0.229991, -0.711267 };\n   cblas_ztbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztbmv(case 972) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztbmv(case 972) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 113;\n   int uplo = 122;\n   int diag = 132;\n   int N = 3;\n   int K = 1;\n   int lda = 3;\n   double A[] = { 0.002, 0.95, -0.363, 0.084, -0.646, 0.816, -0.407, 0.099, -0.02, -0.906, -0.874, 0.191, -0.328, -0.968, 0.79, 0.826, -0.795, 0.277 };\n   double X[] = { -0.591, -0.084, 0.707, 0.945, 0.326, 0.428 };\n   int incX = -1;\n   double x_expected[] = { -0.591, -0.084, 0.794924, 0.411234, 0.148739, 0.025577 };\n   cblas_ztbmv(order, uplo, trans, diag, N, K, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztbmv(case 973) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztbmv(case 973) imag\");\n     };\n   };\n  };\n\n\n}\n", "meta": {"hexsha": "861a529cab46c73d74d514d14e737aa730bfde53", "size": 53789, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/cblas/test_tbmv.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/cblas/test_tbmv.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/cblas/test_tbmv.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 29.5543956044, "max_line_length": 170, "alphanum_fraction": 0.5108851252, "num_tokens": 25464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.05261895631901725, "lm_q1q2_score": 0.023240372592355993}}
{"text": "/* ieee-utils/fp-aix.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Tim Mooney\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <math.h>\n#include <fptrap.h>\n#include <float.h>\n#include <gsl/gsl_ieee_utils.h>\n#include <gsl/gsl_errno.h>\n\nint\ngsl_ieee_set_mode (int precision, int rounding, int exception_mask)\n{\n  fptrap_t   mode = 0 ;\n  fprnd_t    rnd  = 0 ;\n\n  switch (precision)\n    {\n\n    /* I'm not positive about AIX only supporting default precision rounding,\n     * but this is the best assumption until it's proven otherwise. */\n\n    case GSL_IEEE_SINGLE_PRECISION:\n      GSL_ERROR (\"AIX only supports default precision rounding\",\n                 GSL_EUNSUP) ;\n      break ;\n    case GSL_IEEE_DOUBLE_PRECISION:\n      GSL_ERROR (\"AIX only supports default precision rounding\",\n                 GSL_EUNSUP) ;\n      break ;\n    case GSL_IEEE_EXTENDED_PRECISION:\n      GSL_ERROR (\"AIX only supports default precision rounding\",\n                 GSL_EUNSUP) ;\n      break ;\n    }\n\n  switch (rounding)\n    {\n    case GSL_IEEE_ROUND_TO_NEAREST:\n      rnd = FP_RND_RN ;\n      fp_swap_rnd (rnd) ;\n      break ;\n    case GSL_IEEE_ROUND_DOWN:\n      rnd = FP_RND_RM ;\n      fp_swap_rnd (rnd) ;\n      break ;\n    case GSL_IEEE_ROUND_UP:\n      rnd = FP_RND_RP ;\n      fp_swap_rnd (rnd) ;\n      break ;\n    case GSL_IEEE_ROUND_TO_ZERO:\n      rnd = FP_RND_RZ ;\n      fp_swap_rnd (rnd) ;\n      break ;\n    default:\n      rnd = FP_RND_RN ;\n      fp_swap_rnd (rnd) ;\n    }\n\n  /* Turn on all the exceptions apart from 'inexact' */\n\n  mode = TRP_INVALID | TRP_DIV_BY_ZERO | TRP_OVERFLOW | TRP_UNDERFLOW ;\n\n  if (exception_mask & GSL_IEEE_MASK_INVALID)\n    mode &= ~ TRP_INVALID ;\n\n  if (exception_mask & GSL_IEEE_MASK_DENORMALIZED)\n    {\n      /* do nothing */\n    }\n  else \n    {\n      GSL_ERROR (\"AIX does not support the denormalized operand exception. \"\n                 \"Use 'mask-denormalized' to work around this.\",\n                 GSL_EUNSUP) ;\n    }\n\n  if (exception_mask & GSL_IEEE_MASK_DIVISION_BY_ZERO)\n    mode &= ~ TRP_DIV_BY_ZERO ;\n\n  if (exception_mask & GSL_IEEE_MASK_OVERFLOW)\n    mode &= ~ TRP_OVERFLOW ;\n\n  if (exception_mask & GSL_IEEE_MASK_UNDERFLOW)\n    mode &=  ~ TRP_UNDERFLOW ;\n\n  if (exception_mask & GSL_IEEE_TRAP_INEXACT)\n    {\n      mode |= TRP_INEXACT ;\n    }\n  else\n    {\n      mode &= ~ TRP_INEXACT ;\n    }\n\n  /* AIX appears to require two steps -- first enable floating point traps\n   * in general... */\n  fp_trap(FP_TRAP_SYNC);\n\n  /* next, enable the traps we're interested in */\n  fp_enable(mode);\n\n  return GSL_SUCCESS ;\n\n}\n", "meta": {"hexsha": "9933f8faf94aaa8843105f2e5dc37fd62af99881", "size": 3243, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/ieee-utils/fp-aix.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/ieee-utils/fp-aix.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/ieee-utils/fp-aix.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 26.8016528926, "max_line_length": 81, "alphanum_fraction": 0.6574159729, "num_tokens": 857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.05582313563685471, "lm_q1q2_score": 0.023160954544487494}}
{"text": "/*\n *  rand.h\n *  Random number generation\n *\n *  Created by OKAMOTO Kenji, SAKO Yasushi and RIKEN\n *  Copyright 2011-2015\n *  Cellular Informatics Laboratory, Advance Science Institute, RIKEN, Japan.\n *  All rights reserved.\n *\n *  Ver. 1.0.0\n *  Last modified on 2015.09.17\n */\n\n#ifndef DEF_RAND\n#define DEF_RAND\n\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n\nvoid initRan();\nvoid freeRan();\ndouble ranInRange( double, double );\ndouble enoise( double );\ndouble interval( double );\n\n#endif\n\n//\n", "meta": {"hexsha": "be253ea9c2ac08faf28eb6483fb0320b023dbc1c", "size": 504, "ext": "h", "lang": "C", "max_stars_repo_path": "C/rand.h", "max_stars_repo_name": "okamoto-kenji/varBayes-HMM", "max_stars_repo_head_hexsha": "77afe3c336c9e1ebeb115ca4f0b2bc25060556bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-03-31T06:59:00.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-01T06:35:57.000Z", "max_issues_repo_path": "C/rand.h", "max_issues_repo_name": "okamoto-kenji/varBayes-HMM", "max_issues_repo_head_hexsha": "77afe3c336c9e1ebeb115ca4f0b2bc25060556bd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "C/rand.h", "max_forks_repo_name": "okamoto-kenji/varBayes-HMM", "max_forks_repo_head_hexsha": "77afe3c336c9e1ebeb115ca4f0b2bc25060556bd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.3793103448, "max_line_length": 77, "alphanum_fraction": 0.6984126984, "num_tokens": 153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4532618332444286, "lm_q2_score": 0.05108274201321098, "lm_q1q2_score": 0.023153857292060202}}
{"text": "#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\n\n#include <Python.h>\n#include <numpy/arrayobject.h>\n\n\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n\n#include <math.h>\n\n// Forward function declaration.\nstatic PyObject *zsampler_sample_region(PyObject *self, PyObject *args);\nstatic PyObject *zsampler_sample_categorical(PyObject *self, PyObject *args);\n\n\n// Boilerplate: method list.\nstatic PyMethodDef methods[] = {\n  { \"sample_region\", zsampler_sample_region, METH_VARARGS, \"Doc string.\"},\n  { \"sample_bulk_categorical\", zsampler_sample_categorical, METH_VARARGS, \"Doc string.\"},\n  { NULL, NULL, 0, NULL } /* Sentinel */\n};\n\nstatic struct PyModuleDef sampler_module =\n{\n    PyModuleDef_HEAD_INIT,\n    \"zsampler\", /* name of module */\n    \"\",          /* module documentation, may be NULL */\n    -1,          /* size of per-interpreter state of the module, or -1 if the module keeps state in global variables. */\n    methods\n};\n\nPyMODINIT_FUNC PyInit_zsampler(void)\n{   \n    import_array(); // crucial command if NumPy API is used\n    return PyModule_Create(&sampler_module);\n}\n\n/*****************************************************************************\n * Helper methods                                                            *\n *****************************************************************************/\nvoid print_int_array(npy_int64* array, int length) {\n  for(int i = 0; i < length; i++) {\n    printf(\"%ld \", array[i]);\n  }\n  printf(\"\\n\");\n}\n\nvoid print_f_array(npy_float64* array, int length) {\n  for(int i = 0; i < length; i++) {\n    printf(\"%lf \", array[i]);\n  }\n  printf(\"\\n\");\n}\n\nstatic PyObject* zsampler_sample_categorical(PyObject *self, PyObject *args) {\n\n\n    PyArrayObject *py_Z, *py_prob;\n    if (!PyArg_ParseTuple(args, \"O!O!\",\n                            &PyArray_Type, &py_Z,\n                            &PyArray_Type, &py_prob)) {\n        return NULL;\n    }\n\n    npy_int64 C_N, C_K;\n    C_N = PyArray_SHAPE(py_prob)[0];\n    C_K = PyArray_SHAPE(py_prob)[1];\n\n    const gsl_rng_type * C_T;\n    gsl_rng * C_r;\n    gsl_rng_env_setup();\n    C_T = gsl_rng_taus;\n    C_r = gsl_rng_alloc (C_T);\n\n    double *_prob; // probabilities for sampling from multinomial\n    _prob = (double*)malloc(C_K * sizeof(double));\n\n    unsigned int *_new_sample;\n    _new_sample = (unsigned int*)malloc(C_K * sizeof(unsigned int));\n\n    PyArrayObject* out_Z = (PyArrayObject*)PyArray_NewCopy(py_Z, NPY_ANYORDER);\n    for (int i=0; i < C_N; i++) {\n\n        for (int k=0; k < C_K; k++) {\n            _prob[k] = (*(npy_float64*)PyArray_GETPTR2(py_prob, i, k));\n         }\n\n        gsl_ran_multinomial(C_r, (size_t)C_K, 1, _prob, _new_sample);\n\n        for (int k = 0; k < C_K; k++) {\n            npy_int64* Zk = (npy_int64*)PyArray_GETPTR2(out_Z, i, k);\n            Zk[0] = (npy_int64)_new_sample[k];\n         }\n    }\n\n    free(_prob);\n    free(_new_sample);\n    gsl_rng_free(C_r);\n    return (PyObject*)out_Z;  // no need to IncRef out_Z\n}\n\n\n//      Mixture weight priors is block-specific\nstatic PyObject* zsampler_sample_region(PyObject *self, PyObject *args) {\n\n  // Input variables\n  PyArrayObject *py_Z, *py_counts, *py_covariates, *py_beta, *py_alpha;\n  PyArrayObject *py_region_alloc, *py_region_label_counts;\n\n  /*  parse single numpy array argument */\n    if (!PyArg_ParseTuple(args, \"O!O!O!O!O!O!O!\",\n                            &PyArray_Type, &py_Z,\n                            &PyArray_Type, &py_counts,\n                            &PyArray_Type, &py_covariates,\n                            &PyArray_Type, &py_beta,\n                            &PyArray_Type, &py_alpha,\n                            &PyArray_Type, &py_region_alloc,\n                            &PyArray_Type, &py_region_label_counts)) {\n        return NULL;\n    }\n\n    Py_INCREF(py_region_alloc);\n    Py_INCREF(py_region_label_counts);\n\n    const gsl_rng_type * C_T;\n    gsl_rng * C_r;\n    gsl_rng_env_setup();\n    C_T = gsl_rng_taus;\n    C_r = gsl_rng_alloc (C_T);\n\n    // Temporary variables\n    npy_int64 C_N, C_K, C_J;\n    C_N = PyArray_SHAPE(py_Z)[0];\n    C_K = PyArray_SHAPE(py_Z)[1];\n    C_J = PyArray_SHAPE(py_beta)[0];\n\n    PyArrayObject* out_Z = (PyArrayObject*)PyArray_NewCopy(py_Z, NPY_ANYORDER);\n\n    npy_int64 *C_counts = (npy_int64 *) PyArray_DATA(py_counts);\n    npy_float64 *C_alpha = (npy_float64 *) PyArray_DATA(py_alpha);\n    npy_int64 *C_region_alloc = (npy_int64 *) PyArray_DATA(py_region_alloc);\n\n    npy_int64 C_labelsum;\n    npy_int64 *C_label_counts;\n    C_label_counts = (npy_int64*)malloc(C_K * sizeof(npy_int64));\n    double *_mu;\n    _mu = (double*)malloc(C_K * sizeof(double));\n    double *_logpoi;\n    _logpoi = (double*)malloc(C_K * sizeof(double));\n    double *_logcat;\n    _logcat =(double*)malloc(C_K * sizeof(double)); \n    double *_lik;\n    _lik =(double*)malloc(C_K * sizeof(double)); \n    double *_prob; // probabilities for sampling from multinomial\n    _prob = (double*)malloc(C_K * sizeof(double)); \n    unsigned int *_new_sample;\n    _new_sample = (unsigned int*)malloc(C_K * sizeof(unsigned int));\n\n    \n\n    npy_float64 C_alpha_sum = 0.0;\n    for(int k=0; k < C_K; k++) {\n      C_alpha_sum = C_alpha_sum + C_alpha[k];\n    }\n    \n    for (int i=0; i < C_N; i++) {\n\n      C_labelsum = 0;\n      for (int k = 0; k < C_K; k++) {\n        // subtract current cell counts from the region counts\n        npy_int64* accessor = (npy_int64*)PyArray_GETPTR2(py_region_label_counts, C_region_alloc[i], k);\n        accessor[0] = accessor[0] - (*(npy_int64*)PyArray_GETPTR2(out_Z, i, k));  // TODO: make this simpler\n\n        C_label_counts[k] = accessor[0];\n        C_labelsum = C_labelsum + C_label_counts[k];\n      }\n\n      // computation of likelihood and interim calculations\n      for (int k=0; k < C_K; k++) {\n        _mu[k] = 0;\n        for (int j=0; j < C_J; j++) {\n            _mu[k] = _mu[k] + ((*(npy_float64*)PyArray_GETPTR2(py_covariates, i, j)) * (*(npy_float64*)PyArray_GETPTR2(py_beta, j, k)));\n        }\n\n        _logpoi[k] = ((double)C_counts[i])*_mu[k] - exp(_mu[k]);\n        _logcat[k] = log(((double)C_label_counts[k] + C_alpha[k])  / ((double)C_labelsum + C_alpha_sum));\n\n        _lik[k] = (_logpoi[k] + _logcat[k]);\n      }\n\n      double maxval = _lik[0];\n      for (int k=0; k < C_K; k++) {\n        if(_lik[k] > maxval) {\n          maxval = _lik[k];\n        }\n      }\n\n      double sumexp = 0;\n      for (int k=0; k < C_K; k++) {\n        sumexp = sumexp + exp((double)_lik[k] - maxval);\n      }\n\n      double logsumexp = maxval + log(sumexp);\n\n      for (int k=0; k < C_K; k++) {\n        _prob[k] = exp((double)_lik[k] - logsumexp);\n      }\n\n      gsl_ran_multinomial(C_r, (size_t)C_K, 1, _prob, _new_sample);\n      for (int k = 0; k < C_K; k++) {\n        npy_int64* Zk = (npy_int64*)PyArray_GETPTR2(out_Z, i, k);\n        Zk[0] = (npy_int64)_new_sample[k];\n\n        // update the region label counts\n        npy_int64* accessor = (npy_int64*)PyArray_GETPTR2(py_region_label_counts, C_region_alloc[i], k);\n        accessor[0] = accessor[0] + Zk[0];\n      }\n    }\n\n    free(C_label_counts);\n    free(_mu);\n    free(_logpoi);\n    free(_logcat);\n    free(_lik);\n    free(_prob);\n    free(_new_sample);\n\n    gsl_rng_free(C_r);\n    Py_DECREF(py_region_alloc);\n    Py_DECREF(py_region_label_counts);\n    return (PyObject*)out_Z;  // no need to IncRef out_Z\n}\n", "meta": {"hexsha": "7390950efe690954cd7fbddd6a7a981d6a5ea640", "size": 7298, "ext": "c", "lang": "C", "max_stars_repo_path": "src/z_sampler/src/sampler.c", "max_stars_repo_name": "jp2011/spatial-poisson-mixtures", "max_stars_repo_head_hexsha": "9e535a636e710a9fa146cbbd4613ece70ec90791", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-06-18T10:57:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T12:13:04.000Z", "max_issues_repo_path": "src/z_sampler/src/sampler.c", "max_issues_repo_name": "jp2011/spatial-poisson-mixtures", "max_issues_repo_head_hexsha": "9e535a636e710a9fa146cbbd4613ece70ec90791", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/z_sampler/src/sampler.c", "max_forks_repo_name": "jp2011/spatial-poisson-mixtures", "max_forks_repo_head_hexsha": "9e535a636e710a9fa146cbbd4613ece70ec90791", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.188034188, "max_line_length": 136, "alphanum_fraction": 0.5907097835, "num_tokens": 2076, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326183324442865, "lm_q2_score": 0.05108274183263388, "lm_q1q2_score": 0.023153857210211497}}
{"text": "/**\n *\n * @file qwrapper_dlaset.c\n *\n *  PLASMA core_blas quark wrapper\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Hatem Ltaief\n * @date 2010-11-15\n * @generated d Tue Jan  7 11:44:58 2014\n *\n **/\n#include <lapacke.h>\n#include \"common.h\"\n\n/***************************************************************************//**\n *\n **/\nvoid QUARK_CORE_dlaset(Quark *quark, Quark_Task_Flags *task_flags,\n                       PLASMA_enum uplo, int M, int N,\n                       double alpha, double beta,\n                       double *A, int LDA)\n{\n    DAG_CORE_LASET;\n    QUARK_Insert_Task(quark, CORE_dlaset_quark, task_flags,\n        sizeof(PLASMA_enum),                &uplo,  VALUE,\n        sizeof(int),                        &M,     VALUE,\n        sizeof(int),                        &N,     VALUE,\n        sizeof(double),         &alpha, VALUE,\n        sizeof(double),         &beta,  VALUE,\n        sizeof(double)*LDA*N,    A,      OUTPUT,\n        sizeof(int),                        &LDA,   VALUE,\n        0);\n}\n\n/***************************************************************************//**\n *\n **/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_dlaset_quark = PCORE_dlaset_quark\n#define CORE_dlaset_quark PCORE_dlaset_quark\n#endif\nvoid CORE_dlaset_quark(Quark *quark)\n{\n    PLASMA_enum uplo;\n    int M;\n    int N;\n    double alpha;\n    double beta;\n    double *A;\n    int LDA;\n\n    quark_unpack_args_7(quark, uplo, M, N, alpha, beta, A, LDA);\n    LAPACKE_dlaset_work(\n        LAPACK_COL_MAJOR,\n        lapack_const(uplo),\n        M, N, alpha, beta, A, LDA);\n}\n", "meta": {"hexsha": "9b2ef499b7dbeb613e371bb70f93f0faccefec64", "size": 1687, "ext": "c", "lang": "C", "max_stars_repo_path": "core_blas-qwrapper/qwrapper_dlaset.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "core_blas-qwrapper/qwrapper_dlaset.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "core_blas-qwrapper/qwrapper_dlaset.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6557377049, "max_line_length": 80, "alphanum_fraction": 0.5145228216, "num_tokens": 444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.048857775332955176, "lm_q1q2_score": 0.02309426310432128}}
{"text": "/*\n * author: Achim Gaedke\n * created: May 2001\n * file: pygsl/src/constmodule.c\n * $Id: constmodule.c,v 1.11 2007/11/26 20:25:09 schnizer Exp $\n *\n *\n * Changes:\n *    7. October 2003 Added support for gsl-1.4 constants.\n */\n\n#include <Python.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_const_num.h>\n#include <pygsl/pygsl_features.h>\n\n#ifdef _PYGSL_GSL_HAS_CGS\n#include <gsl/gsl_const_cgs.h>\n#endif\n\n#ifdef _PYGSL_GSL_HAS_CGSM\n#include <gsl/gsl_const_cgsm.h>\n#endif\n\n#ifdef _PYGSL_GSL_HAS_MKS\n#include <gsl/gsl_const_mks.h>\n#endif\n\n#ifdef _PYGSL_GSL_HAS_MKSA\n#include <gsl/gsl_const_mksa.h>\n#endif\n\n\nstatic PyMethodDef constMethods[] = {\n  {NULL,     NULL}        /* Sentinel */\n};\n\ntypedef struct {\n  char* name;\n  double value;\n  char* doc;\n} constConstants;\n\nconstConstants m_array[]={\n#include \"const_m_array.c\"\n{NULL,0,NULL}\n};\n\n#ifdef _PYGSL_GSL_HAS_MKS\nconstConstants mks_array[]={\n#include \"const_mks_array.c\"\n  {NULL,0,NULL}\n};\n#endif\n\n#ifdef _PYGSL_GSL_HAS_CGS\nconstConstants cgs_array[]={\n#include \"const_cgs_array.c\"\n  {NULL,0,NULL}\n};\n#endif\n\n#ifdef _PYGSL_GSL_HAS_MKSA\nconstConstants mksa_array[]={\n#include \"const_mksa_array.c\"\n  {NULL,0,NULL}\n};\n#endif\n\n#ifdef _PYGSL_GSL_HAS_CGSM\nconstConstants cgsm_array[]={\n#include \"const_cgsm_array.c\"\n  {NULL,0,NULL}\n};\n#endif\n\nconstConstants num_array[]={\n#include \"const_num_array.c\"\n  {NULL,0,NULL}\n};\n\n\n\nstatic void\nadd_constants(constConstants* constants, PyObject* m)\n{\n  int i=0;\n  while (constants[i].name!=NULL) {\n    PyObject* floatObject=PyFloat_FromDouble(constants[i].value);\n    if (floatObject==NULL) break;\n    PyModule_AddObject(m,constants[i].name,floatObject);\n    /* Py_DECREF(floatObject); */\n    i++;\n  }\n}\n\nDL_EXPORT(void) initconst(void)\n{\n  PyObject* const_module = Py_InitModule(\"const\", constMethods);\n\n#ifdef _PYGSL_GSL_HAS_MKS\n  PyObject* mks_module   = PyImport_AddModule(\"pygsl.const.mks\");\n#endif\n#ifdef _PYGSL_GSL_HAS_CGS\n  PyObject* cgs_module   = PyImport_AddModule(\"pygsl.const.cgs\");\n#endif\n\n#ifdef _PYGSL_GSL_HAS_MKSA\n  PyObject* mksa_module   = PyImport_AddModule(\"pygsl.const.mksa\");\n#endif\n#ifdef _PYGSL_GSL_HAS_CGSM\n  PyObject* cgsm_module   = PyImport_AddModule(\"pygsl.const.cgsm\");\n#endif\n\n  PyObject* math_module  = PyImport_AddModule(\"pygsl.const.m\");\n  PyObject* num_module   = PyImport_AddModule(\"pygsl.const.num\");\n\n  /* distribute constants on modules */\n  add_constants(m_array  , const_module);\n  add_constants(num_array, const_module);\n\n#ifdef _PYGSL_GSL_HAS_MKS\n  add_constants(mks_array, const_module);\n  add_constants(mks_array, mks_module);\n#endif\n#ifdef _PYGSL_GSL_HAS_CGS\n  add_constants(cgs_array, cgs_module);\n#endif\n\n#ifdef _PYGSL_GSL_HAS_MKSA\n  add_constants(mksa_array, const_module);\n  add_constants(mksa_array, mksa_module);\n#endif\n#ifdef _PYGSL_GSL_HAS_CGSM\n  add_constants(cgsm_array, cgsm_module);\n#endif\n\n  add_constants(num_array, num_module);\n  add_constants(m_array  , math_module);\n\n  PyModule_AddObject(const_module, \"m\",   math_module);\n#ifdef _PYGSL_GSL_HAS_CGS\n  PyModule_AddObject(const_module, \"cgs\", cgs_module);\n#endif\n#ifdef _PYGSL_GSL_HAS_MKS\n  PyModule_AddObject(const_module, \"mks\", mks_module);\n#endif\n   \n#ifdef _PYGSL_GSL_HAS_CGSM\n  PyModule_AddObject(const_module, \"cgsm\", cgsm_module);\n#endif\n#ifdef _PYGSL_GSL_HAS_MKSA\n  PyModule_AddObject(const_module, \"mksa\", mksa_module);\n#endif\n\n  PyModule_AddObject(const_module, \"num\", num_module);\n  return;\n}\n\n", "meta": {"hexsha": "96be4cccd5c63eefcd0db3ad45eba60fc5209bb5", "size": 3404, "ext": "c", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/src/constmodule.c", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/src/constmodule.c", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/src/constmodule.c", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 21.275, "max_line_length": 67, "alphanum_fraction": 0.7479435958, "num_tokens": 1050, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.055005294102639324, "lm_q1q2_score": 0.023030546638975663}}
{"text": "///\n/// @file\n///\n/// @brief This file contains code that is used to validate the output of the\n/// example codes.\n///\n/// @author Mirko Myllykoski (mirkom@cs.umu.se), Ume\u00e5 University\n///\n/// @section LICENSE\n///\n/// Copyright (c) 2019-2020, Ume\u00e5 Universitet\n///\n/// Redistribution and use in source and binary forms, with or without\n/// modification, are permitted provided that the following conditions are met:\n///\n/// 1. Redistributions of source code must retain the above copyright notice,\n///    this list of conditions and the following disclaimer.\n///\n/// 2. Redistributions in binary form must reproduce the above copyright notice,\n///    this list of conditions and the following disclaimer in the documentation\n///    and/or other materials provided with the distribution.\n///\n/// 3. Neither the name of the copyright holder nor the names of its\n///    contributors may be used to endorse or promote products derived from this\n///    software without specific prior written permission.\n///\n/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n/// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n/// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n/// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n/// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n/// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n/// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n/// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n/// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n/// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n/// POSSIBILITY OF SUCH DAMAGE.\n///\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <cblas.h>\n\nstatic inline double squ(double x)\n{\n    return x*x;\n}\n\nvoid check_orthogonality(int n, size_t ldQ, double const *Q)\n{\n    size_t ldT = ((n/8)+1)*8;\n    double *T = malloc(n*ldT*sizeof(double));\n\n    cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans, n, n, n, 1.0,\n        Q, ldQ, Q, ldQ, 0.0, T, ldT);\n\n    double dot = 0.0;\n    for (int i = 0; i < n; i++)\n        for (int j = 0; j < n; j++)\n            dot += squ(T[i*ldT+j] - (i == j ? 1.0 : 0.0));\n\n    double norm = ((long long)1<<52) * sqrt(dot)/sqrt(n);\n\n    if (norm < 1000) {\n        printf(\"The matrix is orthogonal.\\n\");\n    }\n    else {\n        fprintf(stderr, \"Matrix is not orthogonal.\\n\");\n        exit(EXIT_FAILURE);\n    }\n\n    free(T);\n}\n\nvoid check_residual(\n    int n, size_t ldQ, size_t ldA, size_t ldZ, size_t ldC,\n    double const *Q, double const *A, double const *Z, double const *C)\n{\n    size_t ldT = ((n/8)+1)*8;\n    double *T = malloc(n*ldT*sizeof(double));\n\n    size_t ldY = ((n/8)+1)*8;\n    double *Y = malloc(n*ldT*sizeof(double));\n\n    cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, n, n, n, 1.0,\n        Q, ldQ, A, ldA, 0.0, T, ldT);\n    cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans, n, n, n, 1.0,\n        T, ldT, Z, ldZ, 0.0, Y, ldY);\n\n    double dot = 0.0, a_dot = 0.0;\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            dot += squ(Y[i*ldY+j] - C[i*ldC+j]);\n            a_dot += squ(C[i*ldC+j]);\n        }\n    }\n\n    double norm = ((long long)1<<52) * sqrt(dot)/sqrt(a_dot);\n\n    if (norm < 1000) {\n        printf(\"The residual is small enough.\\n\");\n    }\n    else {\n        fprintf(stderr, \"The residual is too large.\\n\");\n        exit(EXIT_FAILURE);\n    }\n\n    free(T);\n    free(Y);\n}\n", "meta": {"hexsha": "5871050866104b1a18a10b43297805aa3a858ef3", "size": 3607, "ext": "c", "lang": "C", "max_stars_repo_path": "examples/validate.c", "max_stars_repo_name": "NLAFET/StarNEig", "max_stars_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2019-04-28T17:13:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-24T12:30:19.000Z", "max_issues_repo_path": "examples/validate.c", "max_issues_repo_name": "NLAFET/StarNEig", "max_issues_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/validate.c", "max_forks_repo_name": "NLAFET/StarNEig", "max_forks_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-04-30T12:14:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-14T09:41:23.000Z", "avg_line_length": 32.2053571429, "max_line_length": 80, "alphanum_fraction": 0.6382034932, "num_tokens": 1019, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4186969093556867, "lm_q2_score": 0.05500528325882746, "lm_q1q2_score": 0.023030542098705153}}
{"text": "#include <lapacke.h>", "meta": {"hexsha": "aad224189374ebe2dd7810a13075555f395ee7dc", "size": 20, "ext": "h", "lang": "C", "max_stars_repo_path": "Sources/C/CLapack/lapacke.h", "max_stars_repo_name": "Max0u/NDArray", "max_stars_repo_head_hexsha": "49c5f1ec9958a73afde90842c57995d8de9f57b7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 66.0, "max_stars_repo_stars_event_min_datetime": "2019-08-02T01:36:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-22T04:55:11.000Z", "max_issues_repo_path": "Sources/C/CLapack/lapacke.h", "max_issues_repo_name": "Max0u/NDArray", "max_issues_repo_head_hexsha": "49c5f1ec9958a73afde90842c57995d8de9f57b7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2019-08-02T06:07:39.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-22T03:44:41.000Z", "max_forks_repo_path": "Sources/C/CLapack/lapacke.h", "max_forks_repo_name": "Max0u/NDArray", "max_forks_repo_head_hexsha": "49c5f1ec9958a73afde90842c57995d8de9f57b7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2019-08-03T05:29:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T07:25:21.000Z", "avg_line_length": 20.0, "max_line_length": 20, "alphanum_fraction": 0.75, "num_tokens": 7, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.04672495381409655, "lm_q1q2_score": 0.02299746790940046}}
{"text": "#ifndef __GEMM_DRIVER_H\n#define __GEMM_DRIVER_H\n\n#include \"util.h\"\n\n#include <stddef.h>\n#include <stdlib.h>\n#include <string.h>\n#include <tuple>\n#include <algorithm>\n#include <assert.h>\n#include <iostream>\n#include <sstream>\n#include <vector>\n// openblas\n#include <cblas.h>\n\n#ifndef CEIL\n#define CEIL(value, divider)  (   ((value)-1)/(divider)+1  )\n#endif\n\n#ifndef CEIL_WRAP\n#define CEIL_WRAP(value, divider)  ( CEIL((value), (divider)) * (divider)  )\n#endif\n\ntypedef enum {\n    LAYOUT_ROW_MAJOR = 0,\n    LAYOUT_COL_MAJOR\n}layout_t;\n\ntypedef enum {\n    TRANS_NO_TRANS = 0,\n    TRANS_TRANS,\n    TRANS_CONJ_TRANS,\n    TRANS_CONJ_NO_TRANS,\n}trans_t;\n\ntypedef enum {\n    IDENT_A_MATRIX = 0,\n    IDENT_B_MATRIX\n}identifier_t;\n\n// cblas helper function\nstatic inline CBLAS_ORDER to_blas_layout(layout_t layout){\n    if(layout == LAYOUT_ROW_MAJOR)\n        return CblasRowMajor;\n    //if(layout == LAYOUT_COL_MAJOR)\n    //TODO: validation\n    return CblasColMajor;\n}\n// cblas helper function\nstatic inline CBLAS_TRANSPOSE to_blas_transpose(trans_t trans){\n    switch(trans){\n        case  TRANS_NO_TRANS:\n            return CblasNoTrans;\n        case  TRANS_TRANS:\n            return CblasTrans;\n        case TRANS_CONJ_TRANS:\n            return CblasConjTrans;\n        case TRANS_CONJ_NO_TRANS:\n            return CblasConjNoTrans;\n        default:\n            return CblasConjNoTrans;\n    }\n}\nstatic inline const char * to_layout_str(layout_t layout){\n    if(layout == LAYOUT_ROW_MAJOR)\n        return \"CblasRowMajor\";\n    if(layout == LAYOUT_COL_MAJOR)\n        return \"CblasColMajor\";\n    return \"n/a major\";\n}\n\nstatic inline const char * to_trans_str(trans_t trans){\n    if(trans == TRANS_NO_TRANS)\n        return \"CblasNoTrans\";\n    if(trans == TRANS_TRANS)\n        return \"CblasTrans\";\n    if(trans == TRANS_CONJ_TRANS)\n        return \"CblasConjTrans\";\n    if(trans == TRANS_CONJ_NO_TRANS)\n        return \"CblasConjNoTrans\";\n    return \"n/a trans\";\n}\n\nclass gemm_context_t {\npublic:\n// matrix descriptors\n    layout_t    layout;\n    trans_t     trans_a;\n    trans_t     trans_b;\n    size_t      m;\n    size_t      n;\n    size_t      k;\n\n    size_t      lda;\n    size_t      ldb;\n    size_t      ldc;\n    double      alpha;\n    double      beta;\n\n//\n    size_t      alignment;  // used for alloc A/B/C, indeed not so useful\n\n// blocking parameters\n    size_t      mc;\n    size_t      nc;\n    size_t      kc;\n    size_t      mr;\n    size_t      nr;\n\n// hw parameters\n    //size_t      cpu_id;\n    size_t      l1_size;\n    size_t      l2_size;\n    size_t      l3_size;\n    size_t      tlb_entry_l1d;\n    size_t      cacheline_size;\n    size_t      page_size;\n    std::vector<int>    cpu_list;\n\n    double      frequency;  // MHz\n\n    bool        cur_use_tuned {false};  // use tuned param from db or default, only a flag\n\n    void serialize_layout_trans(std::ostream & os){\n        std::string al, bl, cl;\n        if(layout == LAYOUT_ROW_MAJOR){\n            cl = \"cr\";\n            if(trans_a == TRANS_NO_TRANS || trans_a == TRANS_CONJ_NO_TRANS){\n                al = \"ar\";\n            }else{\n                al = \"ac\";\n            }\n            if(trans_b == TRANS_NO_TRANS || trans_b == TRANS_CONJ_NO_TRANS){\n                bl = \"br\";\n            }else{\n                bl = \"bc\";\n            }\n        }else{\n            cl = \"cc\";\n            if(trans_a == TRANS_NO_TRANS || trans_a == TRANS_CONJ_NO_TRANS){\n                al = \"ac\";\n            }else{\n                al = \"ar\";\n            }\n            if(trans_b == TRANS_NO_TRANS || trans_b == TRANS_CONJ_NO_TRANS){\n                bl = \"bc\";\n            }else{\n                bl = \"br\";\n            }\n        }\n        os<<al<<\"-\"<<bl<<\"-\"<<cl;\n    }\n\n    void deserialize_layout_trans(const std::istream & is){\n        std::string al, bl, cl;\n        std::stringstream tmp;\n        tmp << is.rdbuf();\n        std::string s( tmp.str() );\n\n        al = s.substr(0, 2);\n        bl = s.substr(3, 2);\n        cl = s.substr(6, 2);\n\n        if(cl == \"cr\"){\n            layout = LAYOUT_ROW_MAJOR;\n            if(al == \"ar\"){\n                trans_a = TRANS_NO_TRANS;\n            }else{\n                trans_a = TRANS_TRANS;\n            }\n            if(bl == \"br\"){\n                trans_b = TRANS_NO_TRANS;\n            }else{\n                trans_b = TRANS_TRANS;\n            }\n        }else if(cl == \"cc\"){\n            layout = LAYOUT_COL_MAJOR;\n            if(al == \"ar\"){\n                trans_a = TRANS_TRANS;\n            }else{\n                trans_a = TRANS_NO_TRANS;\n            }\n            if(bl == \"br\"){\n                trans_b = TRANS_TRANS;\n            }else{\n                trans_b = TRANS_NO_TRANS;\n            }\n        }\n    }\n\n    // TODO: fix more param\n    void serialize(std::ostream & os){\n        serialize_layout_trans(os);\n        os<<\"-\"<<m<<\"-\"<<n<<\"-\"<<k;\n    }\n    void serialize(std::string & str){\n        std::ostringstream oss;\n        serialize(oss);\n        str = oss.str();\n    }\n    void deserialize(std::istream & is){\n        char _d;\n\n        deserialize_layout_trans(is);\n        is>>_d>>m>>_d>>n>>_d>>k;\n    }\n    void deserialize(std::string & str){\n        std::istringstream iss;\n        iss.str(str);\n        deserialize(iss);\n    }\n};\n\n// https://software.intel.com/en-us/mkl-developer-reference-c-cblas-gemm\n\nclass matrix_elem_t {\npublic:\n    size_t operator() (size_t row, size_t col, size_t ldim, layout_t layout, trans_t trans){\n        if(layout == LAYOUT_ROW_MAJOR){\n            if(trans == TRANS_NO_TRANS || trans == TRANS_CONJ_NO_TRANS){\n                assert(ldim>=col);\n                return row * ldim;\n            }\n            else{\n                assert(ldim>=row);\n                return col * ldim;\n            }\n        }else{\n            if(trans == TRANS_NO_TRANS || trans == TRANS_CONJ_NO_TRANS){\n                assert(ldim>=row);\n                return col * ldim;\n            }\n            else{\n                assert(ldim>=col);\n                return row * ldim;\n            }\n        }\n    }\n};\n\ntemplate<typename T>\nclass matrix_t{\npublic:\n    matrix_t(size_t row_, size_t col_, size_t ldim_,\n        layout_t layout_, trans_t trans_, size_t alignment_)\n    {\n        this->row = row_;\n        this->col = col_;\n        this->ldim = ldim_;\n        // TODO ldim should be multiple of alignment!\n        this->layout = layout_;\n        this->trans = trans_;\n        this->alignment = alignment_;\n\n        size_t elements = matrix_elem_t()(row_, col_, ldim_, layout_, trans_);\n        this->data = (T *) __aligned_malloc(sizeof(T)*elements, alignment_);\n        rand_vector(this->data, elements);\n    }\n    ~matrix_t(){\n        if(data)\n            __aligned_free(this->data);\n    }\n\n    size_t dtype_size() const {\n        return sizeof(T);\n    }\n    void __copy(const matrix_t<T> & rhs){\n        this->row = rhs.row;\n        this->col = rhs.col;\n        this->ldim = rhs.ldim;\n\n        this->layout = rhs.layout;\n        this->trans = rhs.trans;\n        this->alignment = rhs.alignment;\n        size_t elements = matrix_elem_t()(rhs.row, rhs.col, rhs.ldim, rhs.layout, rhs.trans);\n        this->data = (T *) __aligned_malloc(sizeof(T)*elements, alignment);\n        memcpy(this->data, rhs.data, sizeof(T)*elements);\n    }\n\n    matrix_t(const matrix_t<T> & rhs){\n        __copy(rhs);\n    }\n    matrix_t& operator =(const matrix_t<T> & rhs){\n        __copy(rhs);\n        return *this;\n    }\n\n    T           *data {nullptr};\n    size_t      row;\n    size_t      col;\n    size_t      ldim;   // leading dimension\n\n    layout_t    layout;\n    trans_t     trans;\n    size_t      alignment;\n};\n\n//typedef matrix_t<float> matrix_fp32_t;\n//typedef matrix_t<double> matrix_fp64_t;\n\n#endif\n", "meta": {"hexsha": "3e186976e50bd0c47e18e158500e2d0ea779fc61", "size": 7712, "ext": "h", "lang": "C", "max_stars_repo_path": "src/gemm_driver.h", "max_stars_repo_name": "carlushuang/gemm_opt", "max_stars_repo_head_hexsha": "810b23ddd3c3da53d98398537154ed1f36ce4c29", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 47.0, "max_stars_repo_stars_event_min_datetime": "2019-04-19T07:14:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T03:09:25.000Z", "max_issues_repo_path": "src/gemm_driver.h", "max_issues_repo_name": "carlushuang/gemm_opt", "max_issues_repo_head_hexsha": "810b23ddd3c3da53d98398537154ed1f36ce4c29", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-08-18T16:42:42.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-22T11:37:16.000Z", "max_forks_repo_path": "src/gemm_driver.h", "max_forks_repo_name": "carlushuang/gemm_opt", "max_forks_repo_head_hexsha": "810b23ddd3c3da53d98398537154ed1f36ce4c29", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2019-04-19T14:36:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-09T03:48:31.000Z", "avg_line_length": 25.3684210526, "max_line_length": 93, "alphanum_fraction": 0.5374740664, "num_tokens": 1903, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.04742587334586295, "lm_q1q2_score": 0.022972148528178683}}
{"text": "/* permutation/init.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <stdlib.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_permutation.h>\n\ngsl_permutation *\ngsl_permutation_alloc (const size_t n)\n{\n  gsl_permutation * p;\n\n  if (n == 0)\n    {\n      GSL_ERROR_VAL (\"permutation length n must be positive integer\",\n                        GSL_EDOM, 0);\n    }\n\n  p = (gsl_permutation *) malloc (sizeof (gsl_permutation));\n\n  if (p == 0)\n    {\n      GSL_ERROR_VAL (\"failed to allocate space for permutation struct\",\n                        GSL_ENOMEM, 0);\n    }\n\n  p->data = (size_t *) malloc (n * sizeof (size_t));\n\n  if (p->data == 0)\n    {\n      free (p);         /* exception in constructor, avoid memory leak */\n\n      GSL_ERROR_VAL (\"failed to allocate space for permutation data\",\n                        GSL_ENOMEM, 0);\n    }\n\n  p->size = n;\n\n  return p;\n}\n\ngsl_permutation *\ngsl_permutation_calloc (const size_t n)\n{\n  size_t i;\n\n  gsl_permutation * p =  gsl_permutation_alloc (n);\n\n  if (p == 0)\n    return 0;\n\n  /* initialize permutation to identity */\n\n  for (i = 0; i < n; i++)\n    {\n      p->data[i] = i;\n    }\n\n  return p;\n}\n\nvoid\ngsl_permutation_init (gsl_permutation * p)\n{\n  const size_t n = p->size ;\n  size_t i;\n\n  /* initialize permutation to identity */\n\n  for (i = 0; i < n; i++)\n    {\n      p->data[i] = i;\n    }\n}\n\nvoid\ngsl_permutation_free (gsl_permutation * p)\n{\n  free (p->data);\n  free (p);\n}\n", "meta": {"hexsha": "570794facdf34b9ca3c44389e068e9124593957e", "size": 2192, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/permutation/init.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/permutation/init.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/permutation/init.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 22.1414141414, "max_line_length": 81, "alphanum_fraction": 0.6350364964, "num_tokens": 605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014734858584286, "lm_q2_score": 0.053403330741417704, "lm_q1q2_score": 0.02297130112407366}}
{"text": "// Copyright (c) 2005 - 2011 Marc de Kamps\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n//\n//    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n//    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation \n//      and/or other materials provided with the distribution.\n//    * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software \n//      without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED \n// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY \n// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \n// USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING \n// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n//      If you use this software in work leading to a scientific publication, you should cite\n//      the 'currently valid reference', which can be found at http://miind.sourceforge.net\n#ifndef _CODE_LIBS_NUMTOOLSLIB_RANDOMGENERATOR_INCLUDE_GUARD\n#define _CODE_LIBS_NUMTOOLSLIB_RANDOMGENERATOR_INCLUDE_GUARD\n\n#include <vector>\n#include <iostream>\n#include <gsl/gsl_rng.h>\n#include \"ChangeSeedException.h\"\n\nusing std::vector;\n\nnamespace NumtoolsLib\n{\n\n\t//! Global default seed for RandomGenerator\n\n\tconst long GLOBAL_SEED = 9875987L;\n\n\n\t//! This class contains a specific uniform random generator that can be used to generate other distributions\n\t//! GaussianDistribution and UniformDistribution, for example, use this random generator, which gsl_rng_mt19937\n\t//! of the Gnu Scietific Library. This class can be used to modify the seed and to keep track of the number\n\t//! of draws made by the generator. Distributions use one copy of this class.\n\n\tclass RandomGenerator \n\t{\n\n\tpublic:\n\n\t\tRandomGenerator(long lseed = GLOBAL_SEED);\n\t\t~RandomGenerator();\n\n\t\tdouble\tNextSampleValue();\n\n\tprivate:\n\t \n\n\t\tRandomGenerator(const RandomGenerator&);\n\t\tRandomGenerator& operator=(const RandomGenerator&);\n\n\t\tdouble\tRan2(long*);\n\t\n\t\t// new, uniformly distributed value\n\n\t\tvoid    AddOne         (){ std::cout << \"zopa\" << std::endl; ++_number_of_draws; }\n\n\n\t\tlong\t\t\t_initial_seed;    // initial seed value\n\t\tunsigned long\t_number_of_draws; // number of calls to NextSampleValue\n\n\t\tgsl_rng*\t\t_p_generator;\n\n\t\n\t}; // end of RandomGenerator\n\n\n\t//! Global Random Generator\n\textern RandomGenerator GLOBAL_RANDOM_GENERATOR;\n\n\tinline double RandomGenerator::NextSampleValue()\n\t{\n\t\tAddOne();\n\t\treturn gsl_rng_uniform(_p_generator);\n\t}\n\n\n\n\n} // end of Numtools\n\n\n#endif // include guard\n", "meta": {"hexsha": "a3362dadded7ff6e219c55ac08b0877bf467d49f", "size": 3322, "ext": "h", "lang": "C", "max_stars_repo_path": "libs/NumtoolsLib/RandomGenerator.h", "max_stars_repo_name": "dekamps/miind", "max_stars_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2015-09-15T17:28:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T20:26:47.000Z", "max_issues_repo_path": "libs/NumtoolsLib/RandomGenerator.h", "max_issues_repo_name": "dekamps/miind", "max_issues_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41.0, "max_issues_repo_issues_event_min_datetime": "2015-08-25T07:50:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T16:20:37.000Z", "max_forks_repo_path": "libs/NumtoolsLib/RandomGenerator.h", "max_forks_repo_name": "dekamps/miind", "max_forks_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-14T20:52:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T12:18:18.000Z", "avg_line_length": 36.5054945055, "max_line_length": 163, "alphanum_fraction": 0.7621914509, "num_tokens": 716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.04813676770280704, "lm_q1q2_score": 0.022941003955137006}}
{"text": "#ifndef libceed_petsc_examples_setup_h\n#define libceed_petsc_examples_setup_h\n\n#include <ceed.h>\n#include <petsc.h>\n\n#include \"structs.h\"\n\nPetscErrorCode CeedDataDestroy(CeedInt i, CeedData data);\nPetscErrorCode SetupLibceedByDegree(DM dm, Ceed ceed, CeedInt degree,\n                                    CeedInt topo_dim, CeedInt q_extra,\n                                    PetscInt num_comp_x, PetscInt num_comp_u,\n                                    PetscInt g_size, PetscInt xl_size,\n                                    BPData bp_data, CeedData data,\n                                    PetscBool setup_rhs, CeedVector rhs_ceed,\n                                    CeedVector *target);\nPetscErrorCode CeedLevelTransferSetup(Ceed ceed, CeedInt num_levels,\n                                      CeedInt num_comp_u, CeedData *data, CeedInt *leveldegrees,\n                                      CeedQFunction qf_restrict, CeedQFunction qf_prolong);\n\n#endif // libceed_petsc_examples_setup_h\n", "meta": {"hexsha": "4ba8ac4f3c28642a9a7c1cef75c8584c6b6be07e", "size": 989, "ext": "h", "lang": "C", "max_stars_repo_path": "examples/petsc/include/libceedsetup.h", "max_stars_repo_name": "wence-/libCEED", "max_stars_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/petsc/include/libceedsetup.h", "max_issues_repo_name": "wence-/libCEED", "max_issues_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/petsc/include/libceedsetup.h", "max_forks_repo_name": "wence-/libCEED", "max_forks_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.9545454545, "max_line_length": 96, "alphanum_fraction": 0.5884732053, "num_tokens": 214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167941228965, "lm_q2_score": 0.04958902017486778, "lm_q1q2_score": 0.022861371104713177}}
{"text": "#ifndef GSL_INTERFACE_H\n#define GSL_INTERFACE_H\n\n\n#include <gsl/gsl_odeiv2.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_matrix.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/*****************************\n * Structure definitions\n *****************************\n */\n\n/**\n * Encapsulation of the integrator;\n*/\ntypedef struct cgsl_integrator{\n\n  const gsl_odeiv2_step_type * step_type; /* time step allocation */\n  gsl_odeiv2_step      * step;\t\t  /* time step control */\n  gsl_odeiv2_control   * control;\t  /* definition of the system */\n  gsl_odeiv2_system      system;\t  /* definition of the driver */\n  gsl_odeiv2_evolve    * evolution;\t  /* emove forward in time*/\n  gsl_odeiv2_driver    * driver;\t  /* high level interface */\n\n} cgsl_integrator;\n\n\n//see <gsl/gsl_odeiv2.h> for an explanation of these\ntypedef int (* ode_function_ptr ) (double t, const double y[], double dydt[], void * params);\ntypedef int (* ode_jacobian_ptr ) (double t, const double y[], double * dfdy, double dfdt[], void * params);\n\n/** Pre/post step callbacks\n *      t: Start of the current time step (communicationPoint)\n *     dt: Length of the current time step (communicationStepSize)\n *      n: Size of system\n *      y: For pre, the values of the variables before stepping. For post, after.\n * params: Opaque pointer\n */\ntypedef int (* pre_post_step_ptr ) (double t, double dt, int n, const double y[], void * params);\n\nenum cgsl_callback_actions{\n  CGSL_RESTART = 1                     // multistep integrators need a reset when\n                                // used with the epce filter.\n};\n  \n/**\n *\n *  This is intended to contain everything needed to integrate only one\n *  little bit at a time *and* to be able to backtrack when needed, and to\n *  have multiple instances of the model.\n *\n *  Here we use this for inheritance by aggregation so that each model is\n *  declared as\n *  typedef struct my_model{\n *     cgs_model   m;\n *         .\n *         .\n *     extra stuff\n *         .\n *         .\n *  }  my_model ;\n*/\n\ntypedef struct cgsl_model{\n  int n_variables;\n  double *x;  \t        /** state variables */\n  double *x_backup;     /** for get/set FMU state */\n  void * parameters;\n\n  /** Definition of the dynamical system: this assumes an *explicit* ODE */\n  ode_function_ptr function;\n  /** Jacobian */\n  ode_jacobian_ptr jacobian;\n\n  /** Pre/post step functions */\n  pre_post_step_ptr pre_step;\n  pre_post_step_ptr post_step;\n\n  /** Get/set FMU state\n   * Used to copy/retreive internal state to/from temporary storage inside the model\n   * params: Opaque pointer\n   */\n  void (* get_state) (struct cgsl_model *model);\n  void (* set_state) (struct cgsl_model *model);\n\n  /** Destructor */\n  void (* free) (struct cgsl_model * model);\n\n  /** Needed by ModelExchange to store content from parameters */\n  void* (*get_model_parameters)(const struct cgsl_model *model);\n} cgsl_model;\n\n/**\n * Useful function for allocating the most common type of model\n */\ncgsl_model* cgsl_model_default_alloc(\n        int n_variables,            /** Number of variables */\n        const double *x0,           /** Initial values. If NULL, initialize model->x to all zeroes instead */\n        void *parameters,           /** User pointer */\n        ode_function_ptr function,  /** ODE function */\n        ode_jacobian_ptr jacobian,  /** Jacobian */\n        pre_post_step_ptr pre_step, /** Pre-step function */\n        pre_post_step_ptr post_step,/** Post-step function */\n        size_t sz                   /** If sz > sizeof(cgsl_model) then allocate sz bytes instead.\n                                        Useful for the my_model case described earlier in this file */\n);\n\n\n/** Default destructor. Frees model->x and the model itself */\nvoid cgsl_model_default_free(cgsl_model *model);\n\n/**\n * Finally we can put everything in a bag.  The spefic model only has to\n * fill in these fields.\n */\ntypedef struct cgsl_simulation {\n\n  cgsl_model * model;         /** this contains the state variables */\n  cgsl_integrator i;\n  double t;\t\t      /** current time */\n  double t1;\t\t      /** stop time */\n  double h;\t\t      /** first stepsize and current value */\n\n  int   fixed_step;\t      /** whether or not we move at fixed step */\n  FILE * file;\n  int store_data;\t      /** whether or not we save the data in an array */\n  double * data;              /** store variables as integration proceeds */\n  int buffer_size;            /** size of data storage */\n  int n;\t\t      /** number of time steps taken */\n  int save;\t\t      /** persistence to file */\n  int print;\t\t      /** verbose on stderr */\n\n  int iterations;             /** Number of iterations done by last call to cgsl_step_to() */\n} cgsl_simulation;\n\n/*****************************\n * Enum  definitions\n *****************************\n */\n\n/**\n * List of available time integration methods in the gsl_odeiv2 library\n */\nenum cgsl_integrator_ids\n{\n  rk2,\t\t/* 0 */\n  rk4,\t\t/* 1 */\n  rkf45,\t/* 2 */\n  rkck,\t\t/* 3 */\n  rk8pd,\t/* 4 */\n  rk1imp,\t/* 5 */\n  rk2imp,\t/* 6 */\n  rk4imp,\t/* 7 */\n  bsimp,\t/* 8 */\n  msadams,\t/* 9 */\n  msbdf\t\t/*10 */\n};\n  \n/* this will flag integrators which need restart */\n  extern int restart_integrator;\n  \n  \n/**************\n * Function declarations.\n **************\n */\n\n/**\n * Essentially the constructor for the cgsl_simulation object.\n * The dynamical model is defined by a function, its Jacobian, an\n * opaque parameter struct, and a set of initial values.\n * All variables are assumed to be continuous.\n *\n *  \\TODO: fix semantics for saving.  Use a filename\n *   instead of descriptor?  Open and close file automatically?\n */\ncgsl_simulation cgsl_init_simulation_tolerance(\n  cgsl_model * model, /** the model we work on */\n        enum cgsl_integrator_ids integrator, /** Integrator ID   */\n        double h,                    /** Initial time-step: must be non-zero, even  with variable step*/\n        int fixed_step,\t\t     /** Boolean */\n        int save,\t\t     /** Boolean */\n        int print,\t\t     /** Boolean  */\n  FILE *f,\t\t             /** File descriptor if 'save' is enabled  */\n  double reltol, double abstol\n  );\n\n  \ncgsl_simulation cgsl_init_simulation(\n  cgsl_model * model, /** the model we work on */\n        enum cgsl_integrator_ids integrator, /** Integrator ID   */\n        double h,                    /** Initial time-step: must be non-zero, even  with variable step*/\n        int fixed_step,\t\t     /** Boolean */\n        int save,\t\t     /** Boolean */\n        int print,\t\t     /** Boolean  */\n        FILE *f\t\t             /** File descriptor if 'save' is enabled  */\n  );\n\n/**\n *  Memory deallocation.\n */\nvoid  cgsl_free_simulation( cgsl_simulation sim );\n\n/**  Step from current time to next communication point. */\nint cgsl_step_to(void * _s,  double comm_point, double comm_step ) ;\n\n/** Accessor */\nconst gsl_odeiv2_step_type * cgsl_get_integrator( int  i ) ;\n\n/**  Commit to file. */\nvoid cgsl_save_data( struct cgsl_simulation * sim );\n\n\n/** Mutators for fixed step*/\n/** \\TODO: make this a toggle */\nvoid cgsl_simulation_set_fixed_step( cgsl_simulation * s, double h );\nvoid cgsl_simulation_set_variable_step( cgsl_simulation * s );\n\n/** Get/set FMU state */\nvoid cgsl_simulation_get( cgsl_simulation *s );\nvoid cgsl_simulation_set( cgsl_simulation *s );\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n", "meta": {"hexsha": "d1f70786672ec2e4e7c5cde9358372d6a32c5b66", "size": 7298, "ext": "h", "lang": "C", "max_stars_repo_path": "tools/cgsl/include/gsl-interface.h", "max_stars_repo_name": "Tjoppen/fmigo", "max_stars_repo_head_hexsha": "0ad5e82b49a973cf710f85daa9dffc45261b36ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-12-18T16:35:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-14T07:38:05.000Z", "max_issues_repo_path": "tools/cgsl/include/gsl-interface.h", "max_issues_repo_name": "Tjoppen/fmigo", "max_issues_repo_head_hexsha": "0ad5e82b49a973cf710f85daa9dffc45261b36ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tools/cgsl/include/gsl-interface.h", "max_forks_repo_name": "Tjoppen/fmigo", "max_forks_repo_head_hexsha": "0ad5e82b49a973cf710f85daa9dffc45261b36ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-20T15:50:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T15:50:01.000Z", "avg_line_length": 31.321888412, "max_line_length": 109, "alphanum_fraction": 0.6245546725, "num_tokens": 1769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.04603390059969197, "lm_q1q2_score": 0.022837134033984848}}
{"text": "/*\nGENETIC - A simple genetic algorithm.\n\nCopyright 2014, Javier Burguete Tolosa.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\n\tlist of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice,\n\tthis list of conditions and the following disclaimer in the documentation\n\tand/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``AS IS'' AND ANY EXPRESS\nOR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\nEVENT SHALL Javier Burguete Tolosa OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\nINDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\nBUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\nADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n/**\n * \\file reproduction.c\n * \\brief Source file to define the reproduction functions.\n * \\author Javier Burguete Tolosa.\n * \\copyright Copyright 2014 Javier Burguete Tolosa. All rights reserved.\n */\n#define _GNU_SOURCE\n#include <string.h>\n#include <glib.h>\n#include <gsl/gsl_rng.h>\n//#include \"config.h\"\n#include \"bits.h\"\n#include \"entity.h\"\n#include \"reproduction.h\"\n\nvoid (*reproduction) (Entity *, Entity *, Entity *, unsigned int, gsl_rng *);\n  ///< Pointer to the function to apply the reproduction operation.\n\n/**\n * Function to mate two genotypes by single-point reproduction of each genome.\n */\nstatic void\nreproduction_singlepoints (Entity * father,     ///< Father.\n                           Entity * mother,     ///< Mother.\n                           Entity * son,        ///< Son.\n                           unsigned int nbits,  ///< Genome nbits.\n                           gsl_rng * rng)\n                           ///< GSL random numbers generator.\n{\n  int i;\n  i = gsl_rng_uniform_int (rng, nbits);\n  bit_copy (son->genome, mother->genome, 0, 0, i);\n  bit_copy (son->genome, father->genome, i, i, nbits - i);\n}\n\n/**\n * Function to mate two genotypes by double-point reproduction of each genome.\n */\nstatic void\nreproduction_doublepoints (Entity * father,     ///< Father.\n                           Entity * mother,     ///< Mother.\n                           Entity * son,        ///< Son.\n                           unsigned int nbits,  ///< Genome nbits.\n                           gsl_rng * rng)\n                           ///< GSL random numbers generator.\n{\n  unsigned int i, j, k;\n  i = gsl_rng_uniform_int (rng, nbits);\n  j = gsl_rng_uniform_int (rng, nbits);\n  if (i > j)\n    k = i, i = j, j = k;\n  bit_copy (son->genome, mother->genome, 0, 0, i);\n  bit_copy (son->genome, father->genome, i, i, j - i);\n  bit_copy (son->genome, mother->genome, j, j, nbits - j);\n}\n\n/**\n * Function to mate two genotypes by random mixing both genomes.\n */\nstatic void\nreproduction_mixing (Entity * father,   ///< Father.\n                     Entity * mother,   ///< Mother.\n                     Entity * son,      ///< Son.\n                     unsigned int nbits,        ///< Genome nbits.\n                     gsl_rng * rng)     ///< GSL random numbers generator.\n{\n  unsigned int i;\n  for (i = 0; i < nbits; i++)\n    {\n      if (gsl_rng_uniform_int (rng, 2))\n        {\n          bit_get (father->genome, i) ?\n            bit_set (son->genome, i) : bit_clear (son->genome, i);\n        }\n      else\n        {\n          bit_get (mother->genome, i) ?\n            bit_set (son->genome, i) : bit_clear (son->genome, i);\n        }\n    }\n}\n\n/**\n * Function to select the reproduction operations.\n */\nvoid\nreproduction_init (unsigned int type)   ///< Type of reproduction operations.\n{\n  switch (type)\n    {\n    case REPRODUCTION_TYPE_SINGLEPOINTS:\n      reproduction = &reproduction_singlepoints;\n      break;\n    case REPRODUCTION_TYPE_DOUBLEPOINTS:\n      reproduction = &reproduction_doublepoints;\n      break;\n    default:\n      reproduction = &reproduction_mixing;\n    }\n}\n", "meta": {"hexsha": "31219bddcc38257c8071ecbf403712d18a715a8f", "size": 4397, "ext": "c", "lang": "C", "max_stars_repo_path": "3.0.0/reproduction.c", "max_stars_repo_name": "jburguete/genetic", "max_stars_repo_head_hexsha": "e7b5473412eeb4bdd9d1f724ab555d7329b7156d", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-04-07T07:31:25.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-02T02:31:16.000Z", "max_issues_repo_path": "3.0.0/reproduction.c", "max_issues_repo_name": "jburguete/genetic", "max_issues_repo_head_hexsha": "e7b5473412eeb4bdd9d1f724ab555d7329b7156d", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3.0.0/reproduction.c", "max_forks_repo_name": "jburguete/genetic", "max_forks_repo_head_hexsha": "e7b5473412eeb4bdd9d1f724ab555d7329b7156d", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-05-22T08:54:08.000Z", "max_forks_repo_forks_event_max_datetime": "2017-05-22T08:54:08.000Z", "avg_line_length": 34.3515625, "max_line_length": 79, "alphanum_fraction": 0.6356606777, "num_tokens": 995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250463481418826, "lm_q2_score": 0.05340333224796729, "lm_q1q2_score": 0.022563155389288183}}
{"text": "// A rectangular block of data of type uint8_t.  A transparent block\n// cache is used for each instance of this class if necessary, so the\n// image can be much bigger than will fit in memory, and pixels can\n// still be accessed and written efficiently, provided subsequent\n// accesses are spatially correlated.  A variety of useful methods are\n// implemented (filtering, subsetting, interpolating, etc.)\n//\n// Don't try to access the same instance concurrently.  Split your\n// images up into separate instances if you must parallelize things.\n//\n// For many methods, arguments of type ssize_t are used, but are not\n// allowed to be negative.  This is to help prevent people from\n// shooting themselves in the foor by accidently passing negative\n// values which don't yield warnings and can't be caught with\n// assertions.\n\n\n#ifndef UINT8_IMAGE_H\n#define UINT8_IMAGE_H\n\n#ifndef solaris\n#  include <stdint.h>\n#endif\n#include \"asf_meta.h\"\n#include <stdio.h>\n#include <sys/types.h>\n\n#include <glib.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_histogram.h>\n\n// sometimes we don't have these - choose conservative values\n#ifndef SSIZE_MAX\n#define SSIZE_MAX 32767\n#endif\n\n#ifndef UINT8_MAX\n#define UINT8_MAX 255\n#endif\n\n// Instance structure.  Everything here is private and need not be\n// used or understood by client code, except for the size_x and size_y\n// fields.\ntypedef struct {\n  size_t size_x, size_y;\t// Image dimensions.\n  size_t cache_space;\t\t// Memory cache space in bytes.\n  size_t cache_area;\t\t// Memory cache area in pixels.\n  size_t tile_size;\t\t// Tile size in pixels on a side.\n  size_t cache_size_in_tiles;\t// Number of tiles in cache.\n  size_t tile_count_x;\t\t// Number of tiles in image in x direction.\n  size_t tile_count_y;\t\t// Number of tiles in image in y direction.\n  size_t tile_count;\t\t// Total number of tiles in image.\n  size_t tile_area;             // Area of a tile, in pixels.\n  uint8_t *cache;\t\t// Memory cache.\n  uint8_t **tile_addresses;\t// Addresss of individual tiles in the cache.\n  GQueue *tile_queue;\t\t// Queue of tile offsets kept in load order.\n  FILE *tile_file;              // File with tiles stored contiguously.\n  GString *tile_file_name;  // Filename of the tile file\n} UInt8Image;\n\n///////////////////////////////////////////////////////////////////////////////\n//\n// Creating New Instances\n//\n///////////////////////////////////////////////////////////////////////////////\n\n// Thaw out a previously frozen instance (produced with\n// uint8_image_freeze) using data pointed to by file_pointer.  Frozen\n// instances aren't portable between platforms.  After thawing\n// file_pointer points to the data immediately following the data from\n// the thawed instance (or to the end of the file).\nUInt8Image *\nuint8_image_thaw (FILE *file_pointer);\n\n// Create a new image filled with zero pixel values.\nUInt8Image *\nuint8_image_new (ssize_t size_x, ssize_t size_y);\n\n// Create a new image with pixels initialized to value.\nUInt8Image *\nuint8_image_new_with_value (ssize_t size_x, ssize_t size_y, uint8_t value);\n\n// Create a new image from memory.  This pixels are assumed to be\n// layed out in memory in the usual way, i.e. contiguous rows of\n// pixels in the x direction are contiguous in memory.\nUInt8Image *\nuint8_image_new_from_memory (ssize_t size_x, ssize_t size_y, uint8_t *buffer);\n\n// Create a new independent copy of model.\nUInt8Image *\nuint8_image_copy (UInt8Image *model);\n\n// Form reduced resolution version of the model.  The scale_factor\n// must be positive and odd.  The new image will be round ((double)\n// model->size_x / scale_factor) pixels by round ((double)\n// model->size_y / scale_factor) pixels.  Scaling is performed by\n// averaging blocks of pixels together, using odd pixel reflection\n// around the image edges (see the description of the apply_kernel\n// method).  The average for a block of pixels is first computed as a\n// double precision floating point number, then rounded with the C99\n// round() function.  The upper and leftmost blocks of pixels averaged\n// together are always centered at the 0 index in the direction in\n// question, so reflection is always used for these edges.  Whether\n// reflection is used for the right and lower edges depends on the\n// relationship between the model dimensions and the scale factor.\nUInt8Image *\nuint8_image_new_from_model_scaled (UInt8Image *model, ssize_t scale_factor);\n\n// Create a new image by copying the portion of model with upper left\n// corner at model coordinates (x, y), width size_x, and height\n// size_y.\nUInt8Image *\nuint8_image_new_subimage (UInt8Image *model, ssize_t x, ssize_t y,\n\t\t\t  ssize_t size_x, ssize_t size_y);\n\n// Create a new image from data at byte offset in file.  The pixel\n// layout in the file is assumed to be the same as for the\n// uint8_image_new_from_memory method.  The byte order of individual\n// pixels in the file should be byte_order.\nUInt8Image *\nuint8_image_new_from_file (ssize_t size_x, ssize_t size_y, const char *file,\n\t\t\t   off_t offset);\n\n// The method is like new_from_file, but takes a file pointer instead\n// of a file name, and the offset argument is with respect to the\n// current position in the file_pointer stream.\nUInt8Image *\nuint8_image_new_from_file_pointer (ssize_t size_x, ssize_t size_y,\n\t\t\t\t   FILE *file_pointer, off_t offset);\n\n// Form a low quality reduced resolution version of the\n// original_size_x by original_size_y image in file.  The new image\n// will be size_x by size_y pixels.  This method is like new_from_file\n// method, but gets its data by sampling in each dimension using\n// bilinear interpolation, and rounding the interpolated values using\n// the C99 round() routine.  This is a decent way of forming quick\n// thumbnails of images, or of scaling images down just slightly (by a\n// factor of say 1.5 or less), but not much else.\nUInt8Image *\nuint8_image_new_from_file_scaled (ssize_t size_x, ssize_t size_y,\n\t\t\t\t  ssize_t original_size_x,\n\t\t\t\t  ssize_t original_size_y,\n\t\t\t\t  const char *file, off_t offset);\n\n// The function that does it all, generating an instance of UInt8Image\n// from a file and the metadata\nUInt8Image *\nuint8_image_new_from_metadata(meta_parameters *meta, const char *file);\n\n// For multi-band imagery the previous function needs to be more specific.\nUInt8Image *\nuint8_image_band_new_from_metadata(meta_parameters *meta,\n\t\t\t\t   int band, const char *file);\n\n///////////////////////////////////////////////////////////////////////////////\n//\n// Getting and Setting Image Pixels and Regions\n//\n///////////////////////////////////////////////////////////////////////////////\n\n// Get pixel at 0-indexed position x, y.  A cache is used so pixel\n// access does not usually involve the hard disk, provided subsequent\n// pixel lookups are spatially close together.  You can probably get\n// away with trating this function just as if everything was in\n// memory.  For details, see the cache control methods below.\n//\n// The x and y arguments should always be positive, ssize_t is used\n// only so people can't as easily shoot themselves in the foot by\n// accidently supplying negative arguments which get promoted in some\n// strange way.\nuint8_t\nuint8_image_get_pixel (UInt8Image *self, ssize_t x, ssize_t y);\n\n// Set pixel at 0-indexed position x, y to value.  A cache is used to\n// make this fast, as for the uint8_image_get_pixel method.\nvoid\nuint8_image_set_pixel (UInt8Image *self, ssize_t x, ssize_t y, uint8_t value);\n\n// Get rectangular image region of size_x, size_y having upper left\n// corner at x, y and copy it into already allocated buffer.  There is\n// not necessarily any caching help for this method, i.e. it may\n// always involve disk access and always be slow.\nvoid\nuint8_image_get_region (UInt8Image *self, ssize_t x, ssize_t y,\n\t\t\tssize_t size_x, ssize_t size_y, uint8_t *buffer);\n\n// This method is analogous to uint8_image_get_region.\nvoid\nuint8_image_set_region (UInt8Image *self, size_t x, size_t y, size_t size_x,\n\t\t\tsize_t size_y, uint8_t *buffer);\n\n// Get a full row of pixels, copying the data into already allocated\n// buffer.  This method will be fast on the average for calls with\n// sequential row numbers.\nvoid\nuint8_image_get_row (UInt8Image *self, size_t row, uint8_t *buffer);\n\n// Get a pixel, performing odd reflection at image edges if the pixel\n// indicies fall outside the image.  See the description of the\n// apply_kernel method for an explanation of reflection.\nuint8_t\nuint8_image_get_pixel_with_reflection (UInt8Image *self, ssize_t x, ssize_t y);\n\n///////////////////////////////////////////////////////////////////////////////\n//\n// Image Analysis and Statistics\n//\n///////////////////////////////////////////////////////////////////////////////\n\n// Default mask value when figuring image stats\n#define UINT8_IMAGE_DEFAULT_MASK (0.0)\n\n// Finds the minimum and maximum pixel values in the image, and the\n// mean and standard deviation of all pixels.  This function considers\n// every pixel in the image when mask is NAN, otherwise it discounts\n// all values within .00000000001 of the mask\nvoid\nuint8_image_statistics (UInt8Image *self, uint8_t *min, uint8_t *max,\n\t\t\tdouble *mean, double *standard_deviation,\n\t\t\tgboolean use_mask_value, uint8_t mask_value);\n\n// Does the same thing as uint8_image_statistics() except that the\n// statistics are calculated for a particular band selection within\n// a UInt8Image which contains multiple bands or channels in sequential\n// order.  Returns 1 on error, otherwise 0\nint\nuint8_image_band_statistics (UInt8Image *self, meta_stats *stats,\n                             int line_count, int band_no,\n                             gboolean use_mask_value, uint8_t mask_value);\n\n// This method works like the statistics method, except values in the\n// interval [interval_start, interval_end] are not considered at all\n// for the purposes of determining any of the outputs.\nvoid\nuint8_image_statistics_with_mask_interval (UInt8Image *self, uint8_t *min,\n\t\t\t\t\t   uint8_t *max, double *mean,\n\t\t\t\t\t   double *standard_deviation,\n\t\t\t\t\t   uint8_t interval_start,\n\t\t\t\t\t   uint8_t interval_end);\n\n// Compute an efficient estimate of the mean and standard deviation of\n// the pixels in the image, by sampling every stride th pixel in each\n// dimension, beginning with pixel (0, 0). If the mask is a non-NAN\n// value, this function will discount all values within .00000000001\n// of the mask\nvoid\nuint8_image_approximate_statistics (UInt8Image *self, size_t stride,\n                                    double *mean, double *standard_deviation,\n\t\t\t\t    gboolean use_mask_value,\n\t\t\t\t    uint8_t mask_value);\n\n// This method is a logical combination of the\n// statistics_with_mask_interval and approximate_statistics methods.\nvoid\nuint8_image_approximate_statistics_with_mask_interval\n  (UInt8Image *self, size_t stride, double *mean, double *standard_deviation,\n   uint8_t interval_start, uint8_t interval_end);\n\n// Creates a gsl_histogram with bin_count bins evenly spaced over the\n// interval [min, max].  This function considers every pixel in the\n// image.\ngsl_histogram *\nuint8_image_gsl_histogram (UInt8Image *self, double min, double max,\n                           size_t bin_count);\n\n///////////////////////////////////////////////////////////////////////////////\n//\n// Kernels, Interpolation, and Sampling\n//\n///////////////////////////////////////////////////////////////////////////////\n\n// Apply kernel centerd at pixel x, y and return the value.  The\n// kernel matrix must be have equal odd dimensions.  The values in the\n// kernel are multiplied by the pixels, and the sum of the products\n// returned.  When part of the kernel would fall outside the image\n// extents, the values used for the out-of-image pixels are the mirror\n// images of the corresponding in-image pixels, with the edge pixels\n// not duplicated, i.e. reflection about the middle of the edge pixels\n// is used.\ndouble\nuint8_image_apply_kernel (UInt8Image *self, ssize_t x, ssize_t y,\n\t\t\t  gsl_matrix *kern);\n\n// Type used to specify whether disk files should be in big or little\n// endian byte order.\n\n// Sample method types.  These dictate how nearby pixels are\n// considered when we want to find the approximate value for a point\n// which falls between pixel indicies.\ntypedef enum {\n  // Nearest pixel.\n  UINT8_IMAGE_SAMPLE_METHOD_NEAREST_NEIGHBOR,\n  // Linearly weited average of four nearest pixels\n  UINT8_IMAGE_SAMPLE_METHOD_BILINEAR,\n  // Bicubic spline interpolation (which consideres the nearest 16 pixels).\n  UINT8_IMAGE_SAMPLE_METHOD_BICUBIC\n} uint8_image_sample_method_t;\n\ndouble\nuint8_image_sample (UInt8Image *self, double x, double y,\n\t\t    uint8_image_sample_method_t sample_method);\n\n///////////////////////////////////////////////////////////////////////////////\n//\n// Comparing Images\n//\n///////////////////////////////////////////////////////////////////////////////\n\n// Return true iff self and other have identical sizes and pixels.\ngboolean\nuint8_image_equals (UInt8Image *self, UInt8Image *other);\n\n///////////////////////////////////////////////////////////////////////////////\n//\n// Manipulating Images\n//\n///////////////////////////////////////////////////////////////////////////////\n\n// Flip an image about a horizontal line through the center of the image\nvoid uint8_image_flip_y(UInt8Image *self);\n\n// Flip an image about a vertical line through the center of the image\nvoid uint8_image_flip_x(UInt8Image *self);\n\n///////////////////////////////////////////////////////////////////////////////\n//\n// Storing Images in Files\n//\n///////////////////////////////////////////////////////////////////////////////\n\n// Store instance self at position pointed to by file_pointer, for\n// later retrieval using uint8_image_thaw.  The serialized version of\n// self is not portable between platforms.\nvoid\nuint8_image_freeze (UInt8Image *self, FILE *file_pointer);\n\n// Store image pixels in file.  The image is stored in the usual\n// order, i.e. contiguous rows of pixels in the x direction are stored\n// contiguously in memory.  Individual pixels are stored in byte order\n// byte_order.  Returns 0 on success, nonzero on error.\nint\nuint8_image_store (UInt8Image *self, const char *file);\n\nint\nuint8_image_store_ext(UInt8Image *self, const char *file, int append_flag);\n\nint\nuint8_image_band_store(UInt8Image *self, const char *file,\n\t\t       meta_parameters *meta, int append_flag);\n\n///////////////////////////////////////////////////////////////////////////////\n//\n// Exporting Images in Various Image File Formats\n//\n///////////////////////////////////////////////////////////////////////////////\n\n// Export image to fila as a gray scaled jpeg image, with largest\n// dimension no larger than max_dimension.  The max_dimension argument\n// must be less than or equal to the largest dimension of the image.\n// The image may be scaled st its largest dimension is considerably\n// less than max_dimension.  Scaling is performed by averaging blocks\n// of pixels together, using odd pixel reflection around the image\n// edges (see the description of the apply_kernel method), and\n// rounding pixel averages with the C99 round() routine.  If\n// use_mask_value is true, then in determining the image statistics\n// (mean and standard deviation), values equal to mask are not\n// considered.  This routine slurps the whole image into memory, so\n// beware.  Returns 0 on success, nonzero on error.\nint\nuint8_image_export_as_jpeg (UInt8Image *self, const char *file,\n\t\t\t    size_t max_dimension, gboolean use_mask_value,\n\t\t\t    uint8_t mask_value);\n\n///////////////////////////////////////////////////////////////////////////////\n//\n// Controlling Image Data Caching\n//\n// It probably isn't necessary to use these methods.  They are\n// provided largely to make it clear how the cache works.  The major\n// tunable parameter is the size of the in-memory cache to use.\n//\n// When a new image is created, the following steps are performed:\n//\n//      1. The image is divided up into square tiles st two full rows\n//         or columns of tiles will fit in the memory cache.\n//\n//      2. A copy of the image is created on disk with the memory\n//         layout rearranged st individual tiles are contiguous in\n//         memory.  This allows tiles to be quickly retrieved later.\n//\n// When a pixel is accessed (read or set), the following happens:\n//\n//      1. If the pixel is in a tile already loaded into the cache,\n//         it is simply fetched or set.\n//\n//      2. Otherwise, the tile containing the pixel is loaded,\n//         possibly displacing an already loaded tile, and then the\n//         pixel is fetched or set.  The tile displaced is the one\n//         loaded longest ago (there is no most-recently-accessed\n//         heuristic, as this would make pixel access too slow).\n//\n// Thus, using a larger memory cache will result in larger tiles being\n// used, and fewer tile loads being needed.  In general, the default\n// behavior is pretty good, but if you know will be performing lots of\n// widely (but not too widely) scattered accesses, you might want to\n// make it bigger.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n// Get the image memory cache size setting, in bytes.  Note that this\n// is the memory cache used per image, not the class-wide cache usage.\n// If you will have a lot of objects instantiated simultaneously, you\n// may find it necessary to use a smaller cache for each image.\nsize_t\nuint8_image_get_cache_size (UInt8Image *self);\n\n// Set the image memory cache to size bytes.  Changing the cache size\n// requires the tiling to be recomputed, the on-disk tile cache to be\n// regenerated, and the in memory cache to be flushed, so its slow.\nvoid\nuint8_image_set_cache_size (UInt8Image *self, size_t size);\n\n///////////////////////////////////////////////////////////////////////////////\n//\n// Freeing Instances\n//\n///////////////////////////////////////////////////////////////////////////////\n\n// Destroy self.\nvoid\nuint8_image_free (UInt8Image *self);\n\n#endif // #ifndef UINT8_IMAGE_H\n", "meta": {"hexsha": "4bf7817108e59c08f3972f62e4eb8b6f3ddd2710", "size": 18031, "ext": "h", "lang": "C", "max_stars_repo_path": "src/libasf_raster/uint8_image.h", "max_stars_repo_name": "glshort/MapReady", "max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z", "max_issues_repo_path": "src/libasf_raster/uint8_image.h", "max_issues_repo_name": "glshort/MapReady", "max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libasf_raster/uint8_image.h", "max_forks_repo_name": "glshort/MapReady", "max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z", "avg_line_length": 41.5460829493, "max_line_length": 79, "alphanum_fraction": 0.6859852476, "num_tokens": 3969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.04672496028540144, "lm_q1q2_score": 0.022450347149770643}}
{"text": "#ifndef UTILS_H\n#define UTILS_H\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#include <stdio.h> // for printf\n#include <stdlib.h> // for posix_memalign\n#include <string.h> // for memset\n#include <math.h> // for sqrt\n#include <float.h> //for FLT_MAX\n#include <time.h> // for clock_gettime\n#include <cblas.h>\n\n#define STACK_SIZE_TOTAL 0x8000000 // 128Mbytes\n\ntypedef struct\n    {\n    int index;\n    float score;\n    }score_index_struct;\n\ntypedef struct\n    {\n    float x;\n    float y;\n    float w;\n    float h;\n    }box_struct;\n\ntypedef struct\n    {\n    void *stack_starting_address;\n    char *stack_current_address;\n    unsigned int stack_current_alloc_size;\n    }stack_struct;\n\n\nvoid init_stack\n    (\n    void\n    );\n\nvoid free_stack\n    (\n    void\n    );\n\nvoid *alloc_from_stack\n    (\n    unsigned int len\n    );\n\nvoid partial_free_from_stack\n    (\n    unsigned int len\n    );\n\nunsigned int get_stack_current_alloc_size\n    (\n    void\n    );\n\nvoid reset_stack_ptr_to_assigned_position\n    (\n    unsigned int assigned_size\n    );\n\ndouble what_time_is_it_now\n    (\n    void\n    );\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif // UTILS_H\n", "meta": {"hexsha": "d90691875b3f02204a9234eea6fd89c637da8631", "size": 1124, "ext": "h", "lang": "C", "max_stars_repo_path": "utils.h", "max_stars_repo_name": "lincolnhard/mobilenetssd-C-scratch", "max_stars_repo_head_hexsha": "2d8e671431e1f53ef0e30b5185805c45edf38cfc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-05-18T06:14:31.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-14T01:54:18.000Z", "max_issues_repo_path": "utils.h", "max_issues_repo_name": "lincolnhard/mobilenetssd-C-scratch", "max_issues_repo_head_hexsha": "2d8e671431e1f53ef0e30b5185805c45edf38cfc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils.h", "max_forks_repo_name": "lincolnhard/mobilenetssd-C-scratch", "max_forks_repo_head_hexsha": "2d8e671431e1f53ef0e30b5185805c45edf38cfc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-23T05:43:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-23T05:43:42.000Z", "avg_line_length": 14.05, "max_line_length": 47, "alphanum_fraction": 0.6583629893, "num_tokens": 291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681662740417, "lm_q2_score": 0.0566524280952398, "lm_q1q2_score": 0.022438223310653628}}
{"text": "/*\n * Copyright 2020 Makani Technologies LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#ifndef LIB_JSON_LOAD_JSON_ARRAY_LOADER_H_\n#define LIB_JSON_LOAD_JSON_ARRAY_LOADER_H_\n\n#include <glog/logging.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_vector.h>\n#include <jansson.h>\n#include <stdint.h>\n\n#include <array>\n#include <string>\n#include <vector>\n\n#include \"common/c_math/vec3.h\"\n#include \"lib/json_load/json_load_or_die.h\"\n\n// TODO: Put this under the lib namespace.\nnamespace json_load {\n\n// Utility class for loading JSON arrays into various vector and array\n// structures such as Vec3, gsl_vector, and gsl_matrix.\nclass JsonArrayLoader {\n public:\n  JsonArrayLoader(int32_t num_rows, int32_t num_cols, json_t *root)\n      : root_(CHECK_NOTNULL(root)),\n        num_rows_(num_rows),\n        num_cols_(num_cols),\n        matrix_buffer_(num_rows),\n        buffer_(0) {\n    CHECK_LT(0, num_rows);\n    CHECK_LT(0, num_cols);\n  }\n\n  virtual ~JsonArrayLoader() {}\n\n  template <int32_t rank>\n  void LoadVector(const std::string &field_name,\n                  const std::array<int32_t, rank> &dims, gsl_vector *dest) {\n    CHECK_NOTNULL(dest);\n    int32_t size = 1;\n    for (int32_t i = 0; i < rank; ++i) size *= dims[i];\n    CHECK_EQ(size, dest->size);\n\n    LoadBuffer(field_name, size, &buffer_);\n    CopyVector(buffer_, dest);\n  }\n\n  void LoadVector(const std::string &field_name, gsl_vector *dest) {\n    LoadVector<1>(field_name, {{static_cast<int32_t>(dest->size)}}, dest);\n  }\n\n  void LoadVec3(const std::string &field_name, Vec3 *dest) {\n    LoadBuffer(field_name, 3, &buffer_);\n    dest->x = buffer_[0];\n    dest->y = buffer_[1];\n    dest->z = buffer_[2];\n  }\n\n  void LoadMatrix(const std::string &field_name, gsl_matrix *dest) {\n    CHECK_NOTNULL(dest);\n\n    json_t *field = json_load::LoadFieldOrDie(root_, field_name);\n    CHECK(json_is_array(field));\n\n    LoadMatrixFromField(field, dest);\n  }\n\n protected:\n  void LoadMatrixFromField(json_t *field, gsl_matrix *dest) {\n    for (int32_t i = 0; i < num_rows_; ++i) {\n      json_t *slice = json_array_get(field, i);\n      CHECK(json_is_array(slice));\n      CHECK_EQ(num_cols_, json_array_size(slice));\n      json_load::LoadArray1D_DoubleOrDie(slice, num_cols_, &matrix_buffer_[i]);\n\n      for (int32_t j = 0; j < num_cols_; ++j) {\n        gsl_matrix_set(dest, i, j, matrix_buffer_[i][j]);\n      }\n    }\n  }\n\n  json_t *root_;\n\n private:\n  void LoadBuffer(const std::string &field_name, int32_t size,\n                  std::vector<double> *buffer) {\n    CHECK_NOTNULL(buffer);\n    json_t *array = json_load::LoadFieldOrDie(root_, field_name);\n    CHECK(json_is_array(array));\n    CHECK_EQ(size, json_array_size(array));\n    json_load::LoadArray1D_DoubleOrDie(array, size, buffer);\n  }\n\n  void CopyVector(const std::vector<double> &buffer, gsl_vector *dest) {\n    CHECK_NOTNULL(dest);\n    CHECK_EQ(buffer.size(), dest->size);\n    for (uint32_t i = 0U; i < buffer.size(); ++i) {\n      gsl_vector_set(dest, i, buffer[i]);\n    }\n  }\n\n  const int32_t num_rows_;\n  const int32_t num_cols_;\n\n  std::vector<std::vector<double>> matrix_buffer_;\n  std::vector<double> buffer_;\n\n  DISALLOW_COPY_AND_ASSIGN(JsonArrayLoader);\n};\n\n}  // namespace json_load\n\n#endif  // LIB_JSON_LOAD_JSON_ARRAY_LOADER_H_\n", "meta": {"hexsha": "75f0c5d5cbb6dd4106482c84956bebec6eaf2a99", "size": 3766, "ext": "h", "lang": "C", "max_stars_repo_path": "lib/json_load/json_array_loader.h", "max_stars_repo_name": "leozz37/makani", "max_stars_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1178.0, "max_stars_repo_stars_event_min_datetime": "2020-09-10T17:15:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:59:35.000Z", "max_issues_repo_path": "lib/json_load/json_array_loader.h", "max_issues_repo_name": "leozz37/makani", "max_issues_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-22T05:22:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-22T05:22:35.000Z", "max_forks_repo_path": "lib/json_load/json_array_loader.h", "max_forks_repo_name": "leozz37/makani", "max_forks_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 107.0, "max_forks_repo_forks_event_min_datetime": "2020-09-10T17:29:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T09:00:14.000Z", "avg_line_length": 28.9692307692, "max_line_length": 79, "alphanum_fraction": 0.6893255443, "num_tokens": 991, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658975016245987, "lm_q2_score": 0.06097517489257286, "lm_q1q2_score": 0.02235287412998058}}
{"text": "#ifndef CWANNIER_DOS_UTIL\n#define CWANNIER_DOS_UTIL\n\n#include <stdlib.h>\n#include <stdio.h>\n#include \"bstrlib/bstrlib.h\"\n#include <gsl/gsl_matrix.h>\n\ngsl_matrix* parse_R_from_bs(char *b1, char *b2, char *b3);\nint set_R_row(gsl_matrix *R, char *b, int row);\ndouble* linspace(double a, double b, int num);\n\n#endif //CWANNIER_DOS_UTIL\n", "meta": {"hexsha": "58a4e3c3d94a6d69f326453fb6e61a138eb42522", "size": 332, "ext": "h", "lang": "C", "max_stars_repo_path": "dos_util.h", "max_stars_repo_name": "tflovorn/cwannier", "max_stars_repo_head_hexsha": "96b9719b098d3e2e7d6f4fa5b2c938aa460c5fb8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dos_util.h", "max_issues_repo_name": "tflovorn/cwannier", "max_issues_repo_head_hexsha": "96b9719b098d3e2e7d6f4fa5b2c938aa460c5fb8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dos_util.h", "max_forks_repo_name": "tflovorn/cwannier", "max_forks_repo_head_hexsha": "96b9719b098d3e2e7d6f4fa5b2c938aa460c5fb8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7142857143, "max_line_length": 58, "alphanum_fraction": 0.75, "num_tokens": 106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3886180267058489, "lm_q2_score": 0.0574932828376918, "lm_q1q2_score": 0.022342926125225034}}
{"text": "\n#ifndef LIB_INCLUDE_TICK_ARRAY_VECTOR_OPERATIONS_H_\n#define LIB_INCLUDE_TICK_ARRAY_VECTOR_OPERATIONS_H_\n\n// License: BSD 3 clause\n\n#include <atomic>\n#include <vector>\n#include <numeric>\n#include <algorithm>\n#include <type_traits>\n\n#include \"promote.h\"\n#include \"tick/base/defs.h\"\n\n#if defined(TICK_USE_MKL)\n\n#include \"mkl.h\"\n\n#elif defined(TICK_USE_CBLAS)\n\n#if defined(__APPLE__)\n#include <Accelerate/Accelerate.h>\n// TODO(svp) Disabling this feature until we find\n//  a good way to determine if ATLAS is actually available\n#else\nextern \"C\" {\n#include <cblas.h>\n}\n#endif  // defined(__APPLE__)\n\n#else\n\n#include \"tick/array/vector/ops_unoptimized.h\"\nnamespace tick {\ntemplate <typename T>\nusing vector_operations = detail::vector_operations_unoptimized<T>;\n  }\n\n#endif\n\n#if defined(TICK_USE_MKL) || defined(TICK_USE_CBLAS)\n#include \"tick/array/vector/ops_blas.h\"\nnamespace tick {\ntemplate <typename T>\nusing vector_operations = detail::vector_operations_cblas<T>;\n  }\n#endif\n\n#include \"tick/array/vector/ops_unoptimized_impl.h\"\n\n#endif  // LIB_INCLUDE_TICK_ARRAY_VECTOR_OPERATIONS_H_\n\n", "meta": {"hexsha": "bb288e98d09b991dacd20587d2b805bfeb4df702", "size": 1085, "ext": "h", "lang": "C", "max_stars_repo_path": "lib/include/tick/array/vector_operations.h", "max_stars_repo_name": "sumau/tick", "max_stars_repo_head_hexsha": "1b56924a35463e12f7775bc0aec182364f26f2c6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 411.0, "max_stars_repo_stars_event_min_datetime": "2017-03-30T15:22:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T01:58:34.000Z", "max_issues_repo_path": "lib/include/tick/array/vector_operations.h", "max_issues_repo_name": "saurabhdash/tick", "max_issues_repo_head_hexsha": "bbc561804eb1fdcb4c71b9e3e2d83a66e7b13a48", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 345.0, "max_issues_repo_issues_event_min_datetime": "2017-04-13T14:53:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T00:46:22.000Z", "max_forks_repo_path": "lib/include/tick/array/vector_operations.h", "max_forks_repo_name": "saurabhdash/tick", "max_forks_repo_head_hexsha": "bbc561804eb1fdcb4c71b9e3e2d83a66e7b13a48", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 102.0, "max_forks_repo_forks_event_min_datetime": "2017-04-25T11:47:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T11:45:49.000Z", "avg_line_length": 20.0925925926, "max_line_length": 67, "alphanum_fraction": 0.7751152074, "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.04742587704837889, "lm_q1q2_score": 0.02223280661980873}}
{"text": "//  This random generator is a C++ wrapper for the GNU Scientific Library\n//  Copyright (C) 2001 Torbjorn Vik\n\n//  This program is free software; you can redistribute it and/or modify\n//  it under the terms of the GNU General Public License as published by\n//  the Free Software Foundation; either version 2 of the License, or\n//  (at your option) any later version.\n\n//  This program is distributed in the hope that it will be useful,\n//  but WITHOUT ANY WARRANTY; without even the implied warranty of\n//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n//  GNU General Public License for more details.\n\n//  You should have received a copy of the GNU General Public License\n//  along with this program; if not, write to the Free Software\n//  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n#ifndef __multimin_fdfminimizer_h\n#define __multimin_fdfminimizer_h \n\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_multimin.h>\n#include <gslwrap/vector_double.h>\n\nnamespace gsl{\n\n//! Create an instance of this class with a user defined function\n/*!\n  A template class with the function operator()(const vector& x) \n  and derivative(const vector&, vector&), as well as a reference to an object of this class must be fournished\n\n  User is responsible for deleting this reference !\n\n */\ntemplate <class fdf_function>\nclass multimin_fdf\n{\n public:\n\tfdf_function* fct;\n\n\t//! These operators can be overridden\n\tvirtual double operator()(const vector& x)\n\t\t{\n\t\t\treturn (*fct)(x);\n\t\t}\n\tvirtual void derivative(const vector& x, vector& g)\n\t\t{\n\t\t\t(*fct).derivative(x, g);\n\t\t}\n\t\n\t//! This operator can be overridden to gain performance in calculating the value and its derivative in a scoop\n\tvirtual double fval_and_derivative(const vector&x, vector& g )\n\t{\n\t\tderivative(x, g);\n\t\treturn (*this)(x);\n\t}\n\n\n\t//! This is the function gsl calls to calculate the value of f at x\n\tstatic double f(const gsl_vector* x, void *p)\n\t{\n\t\tvector_view x_view(*x);\n\t\treturn (*(multimin_fdf *)p)(x_view);\n\t}\n\n\t//! This is the function gsl calls to calculate the value of g=f' at x\n\tstatic void df(const gsl_vector* x, void *p, gsl_vector* g)\n\t{\n\t\tvector_view x_view(*x);\n\t\tvector_view g_view(*g);\n\t\t(*(multimin_fdf *)p).derivative(x_view, g_view);\n\t}\n\n\t//! This is the function gsl calls to calculate the value of g=f' at x\n\tstatic void fdf(const gsl_vector* x, void *p, double* f, gsl_vector* g)\n\t{\n\t\tvector_view x_view(*x);\n\t\tvector_view g_view(*g);\n\t\t*f=(*(multimin_fdf *)p).fval_and_derivative(x_view, g_view);\n\t}\n\n\t//! Constructor (User is responsible for deleting the fdf_function object)\n\tmultimin_fdf(fdf_function* _fct):fct(_fct){assert (fct!=NULL);}\n};\n\n//! Class for multiminimizing one dimensional functions. \n/*!\n  Usage: \n       - Create with optional multiminimize type\n\t   - Set with function object and inital bounds\n\t   - Loop the  iterate function until convergence or maxIterations (extra facility)\n\n\t   - Recover multiminimum and bounds\n */\nclass multimin_fdfminimizer \n{\n public:\n//! \n/*! Choose between : \n  - gsl_multimin_fdfminimizer_conjugate_fr\n  - gsl_multimin_fdfminimizer_conjugate_pr\n  - gsl_multimin_fdfminimizer_vector_bfgs\n  - gsl_multimin_fdfminimizer_steepest_descent\n  \n */\n\tmultimin_fdfminimizer(uint _dim, \n\t\t\t\t\t\t  const gsl_multimin_fdfminimizer_type* type=gsl_multimin_fdfminimizer_conjugate_fr) : \n\t\tdim(_dim), isSet(false), maxIterations(100), s(NULL)\n\t{\n\t\ts=gsl_multimin_fdfminimizer_alloc(type, dim);\n\t\tnIterations=0;\n\t\tif (!s)\n\t\t{\n\t\t\t//error\n\t\t\t//cout << \"ERROR Couldn't allocate memory for multiminimizer\" << endl;\n\t\t\t//throw ? \n\t\t\texit(-1);\n\t\t}\n\t}\n\t~multimin_fdfminimizer(){if (s) gsl_multimin_fdfminimizer_free(s);}\n\t//! returns GSL_FAILURE if the interval does not contain a multiminimum\n\ttemplate <class  fdf_function>\n\tint set(multimin_fdf<fdf_function>& function, const vector& initial_x, double step_size, double tol)\n\t{\n\t\tisSet=false;\n\t\tf.f   = &function.f;\n\t\tf.df  = &function.df;\n\t\tf.fdf = &function.fdf;\n\t\tf.n   = dim;\n\t\tf.params = &function;\n\t\tint status=\tgsl_multimin_fdfminimizer_set(s, &f, initial_x.gslobj(), step_size, tol);\n\t\tif (!status)\n\t\t{\n\t\t\tisSet=true;\n\t\t\tnIterations=0;\n\t\t}\n\t\treturn status;\n\t}\n\tint iterate()\n\t{\n\t\tassert_set();\n\t\tint status=gsl_multimin_fdfminimizer_iterate(s);\n\t\tnIterations++;\n\t\tif (status==GSL_FAILURE)\n\t\t\tisConverged=true;\n\t\treturn status;\n\t}\n\tint restart(){return gsl_multimin_fdfminimizer_restart(s);}\n  \tdouble minimum(){assert_set();return gsl_multimin_fdfminimizer_minimum(s);} \n\tvector x_value(){assert_set();return vector_view(*gsl_multimin_fdfminimizer_x(s));}  \n\tvector gradient(){assert_set();return vector_view(*gsl_multimin_fdfminimizer_gradient(s));}  \n\n\n\tvoid SetMaxIterations(int n){maxIterations=n;}\n\tint GetNIterations(){return nIterations;}\n\tbool is_converged(){if (nIterations>=maxIterations) return true; if (isConverged) return true; return false;}\n\t//string name() const;\n\t\n private:\n\tvoid assert_set(){if (!isSet)exit(-1);} // Old problem of error handling: TODO\n\t\n\tuint dim;\n\tbool isSet;\n\tbool isConverged;\n\tint nIterations;\n\tint maxIterations;\n\tgsl_multimin_fdfminimizer* s;\n\tgsl_multimin_function_fdf f;\n};\n};\t // namespace gsl\n\n#endif //__multimin_fdfminimizer_h\n", "meta": {"hexsha": "3a4718d5697bbc4eb119c9024f99e7faf7e71dc3", "size": 5169, "ext": "h", "lang": "C", "max_stars_repo_path": "src/gslwrap/multimin_fdfminimizer.h", "max_stars_repo_name": "entn-at/GlottDNN", "max_stars_repo_head_hexsha": "b7db669d7f34da92ab34742d75a8ba3c70763a65", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-11-27T01:35:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T01:17:11.000Z", "max_issues_repo_path": "src/gslwrap/multimin_fdfminimizer.h", "max_issues_repo_name": "entn-at/GlottDNN", "max_issues_repo_head_hexsha": "b7db669d7f34da92ab34742d75a8ba3c70763a65", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gslwrap/multimin_fdfminimizer.h", "max_forks_repo_name": "entn-at/GlottDNN", "max_forks_repo_head_hexsha": "b7db669d7f34da92ab34742d75a8ba3c70763a65", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-11-27T01:35:33.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-27T01:35:33.000Z", "avg_line_length": 30.0523255814, "max_line_length": 111, "alphanum_fraction": 0.7274134262, "num_tokens": 1423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046493573919, "lm_q2_score": 0.05261895149064917, "lm_q1q2_score": 0.022231751649110343}}
{"text": "/* spgetset.c\n * \n * Copyright (C) 2012 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <stdlib.h>\n#include <math.h>\n\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_spmatrix.h>\n\n#include \"avl.c\"\n\nstatic void *tree_find(const gsl_spmatrix *m, const size_t i, const size_t j);\n\ndouble\ngsl_spmatrix_get(const gsl_spmatrix *m, const size_t i, const size_t j)\n{\n  if (i >= m->size1)\n    {\n      GSL_ERROR_VAL(\"first index out of range\", GSL_EINVAL, 0.0);\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_VAL(\"second index out of range\", GSL_EINVAL, 0.0);\n    }\n  else if (m->nz == 0)\n    {\n      /* no non-zero elements added to matrix */\n      return (0.0);\n    }\n  else\n    {\n      if (GSL_SPMATRIX_ISTRIPLET(m))\n        {\n          /* traverse binary tree to search for (i,j) element */\n          void *ptr = tree_find(m, i, j);\n          double x = ptr ? *(double *) ptr : 0.0;\n\n          return x;\n        }\n      else if (GSL_SPMATRIX_ISCCS(m))\n        {\n          const size_t *mi = m->i;\n          const size_t *mp = m->p;\n          size_t p;\n\n          /* loop over column j and search for row index i */\n          for (p = mp[j]; p < mp[j + 1]; ++p)\n            {\n              if (mi[p] == i)\n                return m->data[p];\n            }\n        }\n      else if (GSL_SPMATRIX_ISCRS(m))\n        {\n          const size_t *mj = m->i;\n          const size_t *mp = m->p;\n          size_t p;\n\n          /* loop over row i and search for column index j */\n          for (p = mp[i]; p < mp[i + 1]; ++p)\n            {\n              if (mj[p] == j)\n                return m->data[p];\n            }\n        }\n      else\n        {\n          GSL_ERROR_VAL(\"unknown sparse matrix type\", GSL_EINVAL, 0.0);\n        }\n\n      /* element not found; return 0 */\n      return 0.0;\n    }\n} /* gsl_spmatrix_get() */\n\n/*\ngsl_spmatrix_set()\n  Add an element to a matrix in triplet form\n\nInputs: m - spmatrix\n        i - row index\n        j - column index\n        x - matrix value\n*/\n\nint\ngsl_spmatrix_set(gsl_spmatrix *m, const size_t i, const size_t j,\n                 const double x)\n{\n  if (!GSL_SPMATRIX_ISTRIPLET(m))\n    {\n      GSL_ERROR(\"matrix not in triplet representation\", GSL_EINVAL);\n    }\n  else if (x == 0.0)\n    {\n      /* traverse binary tree to search for (i,j) element */\n      void *ptr = tree_find(m, i, j);\n\n      /*\n       * just set the data element to 0; it would be easy to\n       * delete the node from the tree with avl_delete(), but\n       * we'd also have to delete it from the data arrays which\n       * is less simple\n       */\n      if (ptr != NULL)\n        *(double *) ptr = 0.0;\n\n      return GSL_SUCCESS;\n    }\n  else\n    {\n      int s = GSL_SUCCESS;\n      void *ptr;\n\n      /* check if matrix needs to be realloced */\n      if (m->nz >= m->nzmax)\n        {\n          s = gsl_spmatrix_realloc(2 * m->nzmax, m);\n          if (s)\n            return s;\n        }\n\n      /* store the triplet (i, j, x) */\n      m->i[m->nz] = i;\n      m->p[m->nz] = j;\n      m->data[m->nz] = x;\n\n      ptr = avl_insert(m->tree_data->tree, &m->data[m->nz]);\n      if (ptr != NULL)\n        {\n          /* found duplicate entry (i,j), replace with new x */\n          *((double *) ptr) = x;\n        }\n      else\n        {\n          /* no duplicate (i,j) found, update indices as needed */\n\n          /* increase matrix dimensions if needed */\n          m->size1 = GSL_MAX(m->size1, i + 1);\n          m->size2 = GSL_MAX(m->size2, j + 1);\n\n          ++(m->nz);\n        }\n\n      return s;\n    }\n} /* gsl_spmatrix_set() */\n\ndouble *\ngsl_spmatrix_ptr(gsl_spmatrix *m, const size_t i, const size_t j)\n{\n  if (i >= m->size1)\n    {\n      GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL);\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL);\n    }\n  else\n    {\n      if (GSL_SPMATRIX_ISTRIPLET(m))\n        {\n          /* traverse binary tree to search for (i,j) element */\n          void *ptr = tree_find(m, i, j);\n          return (double *) ptr;\n        }\n      else if (GSL_SPMATRIX_ISCCS(m))\n        {\n          const size_t *mi = m->i;\n          const size_t *mp = m->p;\n          size_t p;\n\n          /* loop over column j and search for row index i */\n          for (p = mp[j]; p < mp[j + 1]; ++p)\n            {\n              if (mi[p] == i)\n                return &(m->data[p]);\n            }\n        }\n      else if (GSL_SPMATRIX_ISCRS(m))\n        {\n          const size_t *mj = m->i;\n          const size_t *mp = m->p;\n          size_t p;\n\n          /* loop over row i and search for column index j */\n          for (p = mp[i]; p < mp[i + 1]; ++p)\n            {\n              if (mj[p] == j)\n                return &(m->data[p]);\n            }\n        }\n      else\n        {\n          GSL_ERROR_NULL(\"unknown sparse matrix type\", GSL_EINVAL);\n        }\n\n      /* element not found; return 0 */\n      return NULL;\n    }\n} /* gsl_spmatrix_ptr() */\n\n/*\ntree_find()\n  Find node in tree corresponding to matrix entry (i,j). Adapted\nfrom avl_find()\n\nInputs: m - spmatrix\n        i - row index\n        j - column index\n\nReturn: pointer to tree node data if found, NULL if not found\n*/\n\nstatic void *\ntree_find(const gsl_spmatrix *m, const size_t i, const size_t j)\n{\n  const struct avl_table *tree = (struct avl_table *) m->tree_data->tree;\n  const struct avl_node *p;\n\n  for (p = tree->avl_root; p != NULL; )\n    {\n      size_t n = (double *) p->avl_data - m->data;\n      size_t pi = m->i[n];\n      size_t pj = m->p[n];\n      int cmp = gsl_spmatrix_compare_idx(i, j, pi, pj);\n\n      if (cmp < 0)\n        p = p->avl_link[0];\n      else if (cmp > 0)\n        p = p->avl_link[1];\n      else /* |cmp == 0| */\n        return p->avl_data;\n    }\n\n  return NULL;\n} /* tree_find() */\n", "meta": {"hexsha": "2c5d2ea6d35a29f43cd83064aa298775524a7672", "size": 6472, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.4/spmatrix/spgetset.c", "max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-13T05:01:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-13T05:01:59.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/spmatrix/spgetset.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/spmatrix/spgetset.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1828793774, "max_line_length": 81, "alphanum_fraction": 0.5265760198, "num_tokens": 1835, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.0503306315291204, "lm_q1q2_score": 0.022229681304465378}}
{"text": "/**\n * author: Jochen K\"upper\n * created: Jan 2002\n * file: pygsl/src/statistics/longmodule.c\n * $Id: shortmodule.c,v 1.7 2004/03/24 08:40:45 schnizer Exp $\n *\n * \"\n */\n\n\n#include <Python.h>\n#include <pygsl/error_helpers.h>\n#include <pygsl/block_helpers.h>\n#include <gsl/gsl_statistics.h>\n\n\n/* include real functions for different data-types */\n\n#define STATMOD_APPEND_PY_TYPE(X) X ## Int\n#define STATMOD_APPEND_PYC_TYPE(X) X ## SHORT\n#define STATMOD_FUNC_EXT(X, Y) X ## _short ## Y\n#define STATMOD_PY_AS_C PyInt_AsLong\n#define STATMOD_C_TYPE short int\n#include \"functions.c\"\n\n\n\n\n/* initialization */\n\nPyGSL_STATISTICS_INIT(short, \"short\")\n\n\n/*\n * Local Variables:\n * mode: c\n * c-file-style: \"Stroustrup\"\n * End:\n */\n", "meta": {"hexsha": "7b61f83a2b6fa4ca06881d14397179fb83bc01ea", "size": 718, "ext": "c", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/src/statistics/shortmodule.c", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/src/statistics/shortmodule.c", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/src/statistics/shortmodule.c", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 17.95, "max_line_length": 62, "alphanum_fraction": 0.7033426184, "num_tokens": 210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.46101679412289653, "lm_q2_score": 0.04813676684935012, "lm_q1q2_score": 0.022191857932328717}}
{"text": "#include <stdio.h>\n#include <stdarg.h>\n#include <string.h>\n#include <math.h>\n#include <gbpLib.h>\n#include <gbpRNG.h>\n#include <gbpMCMC.h>\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_fit.h>\n#include <gsl/gsl_interp.h>\n\nvoid init_MCMC_arrays(MCMC_info *MCMC) {\n    int           i_DS;\n    MCMC_DS_info *current_DS;\n    MCMC_DS_info *next_DS;\n\n    if(MCMC->n_M == NULL) {\n        SID_log(\"Initializing MCMC target arrays for %d dataset(s)...\", SID_LOG_OPEN, MCMC->n_DS);\n\n        // Initialize chain arrays\n        MCMC->n_M       = (int *)SID_malloc(sizeof(int) * MCMC->n_DS);\n        MCMC->M_new     = (double **)SID_malloc(sizeof(double *) * MCMC->n_DS);\n        MCMC->M_last    = (double **)SID_malloc(sizeof(double *) * MCMC->n_DS);\n        MCMC->n_M_total = 0;\n        i_DS            = 0;\n        current_DS      = MCMC->DS;\n        while(current_DS != NULL) {\n            next_DS            = current_DS->next;\n            MCMC->n_M[i_DS]    = current_DS->n_M;\n            MCMC->M_new[i_DS]  = (double *)SID_malloc(sizeof(double) * MCMC->n_M[i_DS]);\n            MCMC->M_last[i_DS] = (double *)SID_malloc(sizeof(double) * MCMC->n_M[i_DS]);\n            MCMC->n_M_total += MCMC->n_M[i_DS];\n            current_DS = next_DS;\n            i_DS++;\n        }\n\n        // Initialize results arrays\n        MCMC->P_min   = (double *)SID_malloc(sizeof(double) * MCMC->n_P);\n        MCMC->P_max   = (double *)SID_malloc(sizeof(double) * MCMC->n_P);\n        MCMC->P_avg   = (double *)SID_malloc(sizeof(double) * MCMC->n_P);\n        MCMC->dP_avg  = (double *)SID_malloc(sizeof(double) * MCMC->n_P);\n        MCMC->P_best  = (double *)SID_malloc(sizeof(double) * MCMC->n_P);\n        MCMC->P_peak  = (double *)SID_malloc(sizeof(double) * MCMC->n_P);\n        MCMC->P_lo_68 = (double *)SID_malloc(sizeof(double) * MCMC->n_P);\n        MCMC->P_hi_68 = (double *)SID_malloc(sizeof(double) * MCMC->n_P);\n        MCMC->P_lo_95 = (double *)SID_malloc(sizeof(double) * MCMC->n_P);\n        MCMC->P_hi_95 = (double *)SID_malloc(sizeof(double) * MCMC->n_P);\n\n        MCMC->ln_likelihood_DS      = (double *)SID_malloc(sizeof(double) * MCMC->n_DS);\n        MCMC->ln_likelihood_DS_best = (double *)SID_malloc(sizeof(double) * MCMC->n_DS);\n        MCMC->ln_likelihood_DS_peak = (double *)SID_malloc(sizeof(double) * MCMC->n_DS);\n        MCMC->n_DoF_DS              = (int *)SID_malloc(sizeof(int) * MCMC->n_DS);\n        MCMC->n_DoF_DS_best         = (int *)SID_malloc(sizeof(int) * MCMC->n_DS);\n        MCMC->n_DoF_DS_peak         = (int *)SID_malloc(sizeof(int) * MCMC->n_DS);\n\n        // If MCMC_MODE_MINIMIZE_IO is on, we need to allocate buffers to store the chain\n        if(SID_CHECK_BITFIELD_SWITCH(MCMC->mode, MCMC_MODE_MINIMIZE_IO)) {\n            MCMC->flag_success_buffer      = (char *)SID_malloc(sizeof(char) * MCMC->n_iterations * MCMC->n_avg);\n            MCMC->ln_likelihood_new_buffer = (double *)SID_malloc(sizeof(double) * MCMC->n_iterations * MCMC->n_avg);\n            MCMC->P_new_buffer             = (double *)SID_malloc(sizeof(double) * MCMC->n_iterations * MCMC->n_avg * MCMC->n_P);\n            MCMC->M_new_buffer             = (double *)SID_malloc(sizeof(double) * MCMC->n_iterations * MCMC->n_avg * MCMC->n_M_total);\n        }\n\n        SID_log(\"Done.\", SID_LOG_CLOSE);\n    }\n}\n", "meta": {"hexsha": "c945b627eecb1d325e7e6bd95be4da6b1371a3fe", "size": 3277, "ext": "c", "lang": "C", "max_stars_repo_path": "src/gbpMath/gbpMCMC/init_MCMC_arrays.c", "max_stars_repo_name": "gbpoole/gbpCode", "max_stars_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-10-20T11:39:53.000Z", "max_stars_repo_stars_event_max_datetime": "2015-10-20T11:39:53.000Z", "max_issues_repo_path": "src/gbpMath/gbpMCMC/init_MCMC_arrays.c", "max_issues_repo_name": "gbpoole/gbpCode", "max_issues_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-07-30T11:10:49.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-18T00:40:46.000Z", "max_forks_repo_path": "src/gbpMath/gbpMCMC/init_MCMC_arrays.c", "max_forks_repo_name": "gbpoole/gbpCode", "max_forks_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-01-23T00:50:40.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-01T08:14:24.000Z", "avg_line_length": 48.9104477612, "max_line_length": 135, "alphanum_fraction": 0.5978028685, "num_tokens": 1022, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.04535257974786072, "lm_q1q2_score": 0.022144911624710543}}
{"text": "\n#ifndef KGS_GSLSVD_H\n#define KGS_GSLSVD_H\n\n#include \"math/SVD.h\"\n#include <gsl/gsl_matrix.h>\n\nclass SVDGSL: public SVD {\n public:\n  SVDGSL(gsl_matrix* M): SVD(M){}\n\n protected:\n\n  void UpdateFromMatrix() override;\n};\n\n\n#endif //KGS_GSLSVD_H\n", "meta": {"hexsha": "39b3f414bcec1e054b83c30c400cc3038af9a46b", "size": 242, "ext": "h", "lang": "C", "max_stars_repo_path": "src/math/SVDGSL.h", "max_stars_repo_name": "XiyuChenFAU/kgs_vibration_entropy", "max_stars_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-23T18:26:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-23T18:26:14.000Z", "max_issues_repo_path": "src/math/SVDGSL.h", "max_issues_repo_name": "XiyuChenFAU/kgs_vibration_entropy", "max_issues_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2017-01-26T19:54:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-06T16:06:30.000Z", "max_forks_repo_path": "src/math/SVDGSL.h", "max_forks_repo_name": "XiyuChenFAU/kgs_vibration_entropy", "max_forks_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 12.7368421053, "max_line_length": 35, "alphanum_fraction": 0.7148760331, "num_tokens": 84, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.047425878226452195, "lm_q1q2_score": 0.022048365311240593}}
{"text": "#ifndef TOOLS_H\n#define TOOLS_H\n\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n#include <math.h>\n\nusing namespace std;\n\n//required for TRACE / DEBUG\nextern int indentLevel;\nextern string BLANKLINE;\n\n//how many blanks to indent\n#define INDENTATION 2\n                                                                                           \n#define INDENT BLANKLINE.substr(0,(indentLevel)*INDENTATION)\n#define INDENT_INC BLANKLINE.substr(0,(indentLevel++)*INDENTATION)\n#define INDENT_DEC BLANKLINE.substr(0,(--indentLevel)*INDENTATION)\n\n#define MAX(x,y) ((x) > (y) ? (x) : (y))\n#define ABS(x) ((x)>0 ? (x) : -(x)) \n\n\n#ifdef STDOUT\n#define OUTPUT(x) cout << INDENT << (x) <<\"\\n\";\n#define OUTPUT1(x,arg1) cout << INDENT << (x) <<arg1<<\"\\n\";\n#define OUTPUT2(x,arg1,arg2) cout << INDENT << (x) <<arg1<<\" / \" <<arg2<<\"\\n\";\n\n#else\n#define OUTPUT(x) \"\"\n#define OUTPUT1(x,arg1) \"\"\n#define OUTPUT2(x,arg1,arg2) \"\"\n\n#endif //STDOUT\n\n\n#ifdef TRACE\n#define TRACE_IN(x) cout << INDENT_INC << \"***TRACE_IN: \"<< (x) <<\"()\\n\";\n#define TRACE_IN1(x,arg1) cout << INDENT_INC << \"***TRACE_IN: \"<< (x) <<\"(\"<<arg1<<\")\\n\";\n#define TRACE_OUT(x,ok) cout << INDENT_DEC << \"***TRACE_OUT: \"<< (x) <<\"() = \" << ok << \"\\n\";\n\n#else\n#define TRACE_IN(x) \"\"\n#define TRACE_IN1(x,arg1) \"\"\n#define TRACE_OUT(x,ok) \"\"\n\n#endif //TRACE\n\n#ifdef TRACEV\n#define TRACEV_IN(x) cout << INDENT_INC << \"***TRACE_IN: \"<< (x) <<\"()\\n\";\n#define TRACEV_IN1(x,arg1) cout << INDENT_INC << \"***TRACE_IN: \"<< (x) <<\"(\"<<arg1<<\")\\n\";\n#define TRACEV_OUT(x,ok) cout << INDENT_DEC << \"***TRACE_OUT: \"<< (x) <<\"() = \" << ok << \"\\n\";\n\n#else\n#define TRACEV_IN(x) \"\"\n#define TRACEV_IN1(x,arg1) \"\"\n#define TRACEV_OUT(x,ok) \"\"\n\n#endif //TRACEV\n\n\n#ifdef DBUG\n#define DEBUG(x) cout << INDENT << \"***DEBUG: \"<< (x) <<\"\\n\";\n#define DEBUG1(x,arg1) cout << INDENT << \"***DEBUG: \"<< (x) <<arg1<<\"\\n\";\n#define DEBUG2(x,arg1,arg2) cout << INDENT << \"***DEBUG: \"<< (x) <<arg1<<\" / \" <<arg2<<\"\\n\";\n\n#else\n#define DEBUG(x) \"\"\n#define DEBUG1(x,arg1) \"\"\n#define DEBUG2(x,arg1,arg2) \"\"\n\n#endif //DBUG\n\n//verbose debug information\n//mainly exact positions (quite big with dim=30)\n#ifdef DBUGV\n#define DEBUGV(x) cout << \"***DEBUG: \"<< (x) <<\"\\n\";\n#define DEBUGV1(x,arg1) cout << \"***DEBUG: \"<< (x) <<arg1<<\"\\n\";\n#define DEBUGV2(x,arg1,arg2) cout << \"***DEBUG: \"<< (x) <<arg1<<\" / \" <<arg2<<\"\\n\";\n\n#else\n#define DEBUGV(x) \"\"\n#define DEBUGV1(x,arg1) \"\"\n#define DEBUGV2(x,arg1,arg2) \"\"\n\n#endif //DBUGV\n\n///Little helper function calculating the maximum height\n/**of a regularly built pyramid of \n  *@param minDegree minimum degree*/\nint getMaxHeight(int minDegree, int swarmsize);\n\n//fix the seed for the global RNG\nvoid fixSeed(unsigned seed);\n\n///Free the RNG ressources\nvoid freeRng();\n///Return gaussian distributed double from [0;1)\ndouble randDoubleGaussian(double sigma);\n///Return double from [0;1)\ndouble randDouble();\n///Wrapper to GSL Function call\n/**Returns double from range [min,max)*/\ndouble randDoubleRange(double min, double max);\n///Wrapper to GSL Function call\n/**Returns int from range [min,max]*/\nint randIntRange(int min, int max);\n\nstring printVec(const vector<double>&);\n\ndouble euclideanDistance(const vector<double>& v1, const vector<double>& v2);\n\n\n\n///Generate a reproducable sequence\n/**The seed is passed and thus the sequence is repeatable*/\nclass SequenceGenerator {\npublic:\n\t///Pass the seed\n\tSequenceGenerator(unsigned seed_in);\n\t///Destructor\n\t~SequenceGenerator();\n\t///Return exponentially distributed random variable, with mean mu\n\tdouble nextDoubleExponential(double mu);\n\n\t///Wrapper to GSL Function call\n\t/**Returns double from range [min,max)*/\n\tdouble nextDoubleRange(double min, double max);\n\t///Wrapper to GSL Function call\n\t/**Returns int from range [min,max]*/\n\tint nextIntRange(int min, int max);\nprivate:\n\t///The random number generator\n\tgsl_rng*  randGen;\n\n\t///The random seed defining the sequence\n\tunsigned seed;\n\t\n\n};\n\n#endif //ifndef TOOLS_H\n", "meta": {"hexsha": "b31fe39815d4ce2d492bffff84e5389fdc513642", "size": 3976, "ext": "h", "lang": "C", "max_stars_repo_path": "HPSO/tools.h", "max_stars_repo_name": "andrejadd/ABC-bee-opt", "max_stars_repo_head_hexsha": "746b2f8eb8eeab27e0af515aa129ad8a00b035e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HPSO/tools.h", "max_issues_repo_name": "andrejadd/ABC-bee-opt", "max_issues_repo_head_hexsha": "746b2f8eb8eeab27e0af515aa129ad8a00b035e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HPSO/tools.h", "max_forks_repo_name": "andrejadd/ABC-bee-opt", "max_forks_repo_head_hexsha": "746b2f8eb8eeab27e0af515aa129ad8a00b035e5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8648648649, "max_line_length": 94, "alphanum_fraction": 0.6458752515, "num_tokens": 1098, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378235137849365, "lm_q2_score": 0.05033063793925957, "lm_q1q2_score": 0.02203593675360406}}
{"text": "#ifndef __GSL_MANAGED_H__\n#define __GSL_MANAGED_H__\n\n#include \"cuda.h\"\n#include <gsl/gsl_matrix_double.h>\n#include <gsl/gsl_vector_double.h>\n\ngsl_matrix *gsl_matrix_alloc_managed(const size_t n1, const size_t n2);\ngsl_matrix *gsl_matrix_calloc_managed(const size_t n1, const size_t n2);\nvoid gsl_matrix_free_managed(gsl_matrix *m);\n__host__ __device__ double *gsl_matrix_ptr_managed(gsl_matrix * m, const size_t i, const size_t j);\n\ngsl_vector *gsl_vector_alloc_managed(const size_t n, bool readmostly);\ngsl_vector *gsl_vector_calloc_managed(const size_t n, bool readmostly);\n__host__ __device__ double gsl_vector_get_managed(gsl_vector *vec, const size_t i);\nvoid gsl_vector_free_managed(gsl_vector *m);\n\n#endif /* __GSL_MANAGED_H__ */\n", "meta": {"hexsha": "c49cba6d6401042760ab8fbe1fd591e0815d8ed6", "size": 737, "ext": "h", "lang": "C", "max_stars_repo_path": "gsl_managed.h", "max_stars_repo_name": "artis-mcrt/artis", "max_stars_repo_head_hexsha": "eeb4ba06353a34be949d9662ab300a78f852ebdb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-04-12T12:09:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T21:56:21.000Z", "max_issues_repo_path": "gsl_managed.h", "max_issues_repo_name": "artis-mcrt/artis", "max_issues_repo_head_hexsha": "eeb4ba06353a34be949d9662ab300a78f852ebdb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-11-17T09:37:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-17T15:03:17.000Z", "max_forks_repo_path": "gsl_managed.h", "max_forks_repo_name": "artis-mcrt/artis", "max_forks_repo_head_hexsha": "eeb4ba06353a34be949d9662ab300a78f852ebdb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.7894736842, "max_line_length": 99, "alphanum_fraction": 0.8222523745, "num_tokens": 204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35577489351363034, "lm_q2_score": 0.061875989616020845, "lm_q1q2_score": 0.02201392361669031}}
{"text": "#include <petsc.h>\n#include \"plexview.h\"\n\nPetscErrorCode PlexViewFromOptions(DM plex) {\n    PetscErrorCode ierr;\n    PetscBool  cell_cones = PETSC_FALSE,\n               closures_coords = PETSC_FALSE,\n               coords = PETSC_FALSE,\n               points = PETSC_FALSE,\n               use_height = PETSC_FALSE,\n               vertex_supports = PETSC_FALSE;\n\n    ierr = PetscOptionsBegin(PETSC_COMM_WORLD, \"plex_view_\", \"view options for tiny\", \"\");CHKERRQ(ierr);\n    ierr = PetscOptionsBool(\"-cell_cones\", \"print cones of each cell\",\n                            \"tiny.c\", cell_cones, &cell_cones, NULL);CHKERRQ(ierr);\n    ierr = PetscOptionsBool(\"-closures_coords\", \"print vertex and edge (centers) coordinates for each cell\",\n                            \"tiny.c\", closures_coords, &closures_coords, NULL);CHKERRQ(ierr);\n    ierr = PetscOptionsBool(\"-coords\", \"print section and local vec for vertex coordinates\",\n                            \"tiny.c\", coords, &coords, NULL);CHKERRQ(ierr);\n    ierr = PetscOptionsBool(\"-points\", \"print point index ranges for vertices,edges,cells\",\n                            \"tiny.c\", points, &points, NULL);CHKERRQ(ierr);\n    ierr = PetscOptionsBool(\"-use_height\", \"use Height instead of Depth when printing points\",\n                            \"tiny.c\", use_height, &use_height, NULL);CHKERRQ(ierr);\n    ierr = PetscOptionsBool(\"-vertex_supports\", \"print supports of each vertex\",\n                            \"tiny.c\", vertex_supports, &vertex_supports, NULL);CHKERRQ(ierr);\n    ierr = PetscOptionsEnd();\n\n    if (points) {\n        ierr = PlexViewPointRanges(plex,use_height); CHKERRQ(ierr);\n    }\n    if (cell_cones) {\n        ierr = PlexViewFans(plex,2,2,1); CHKERRQ(ierr);\n    }\n    if (vertex_supports) {\n        ierr = PlexViewFans(plex,2,0,1); CHKERRQ(ierr);\n    }\n    if (coords) {\n        ierr = PlexViewCoords(plex); CHKERRQ(ierr);\n    }\n    if (closures_coords) {\n        ierr = PlexViewClosuresCoords(plex); CHKERRQ(ierr);\n    }\n    return 0;\n}\n\nstatic const char* stratanames[4][10] =\n                       {{\"vertex\",\"\",    \"\",    \"\"},       // dim=0 names\n                        {\"vertex\",\"cell\",\"\",    \"\"},       // dim=1 names\n                        {\"vertex\",\"edge\",\"cell\",\"\"},       // dim=2 names\n                        {\"vertex\",\"edge\",\"face\",\"cell\"}};  // dim=3 names\n\nPetscErrorCode PlexViewPointRanges(DM plex, PetscBool use_height) {\n    PetscErrorCode ierr;\n    int         dim, m, start, end;\n    const char  *plexname;\n    MPI_Comm    comm;\n    PetscMPIInt rank,size;\n\n    ierr = PetscObjectGetComm((PetscObject)plex,&comm); CHKERRQ(ierr);\n    ierr = MPI_Comm_size(comm,&size);CHKERRQ(ierr);\n    ierr = MPI_Comm_rank(comm,&rank); CHKERRQ(ierr);\n    ierr = DMGetDimension(plex,&dim); CHKERRQ(ierr);\n    ierr = PetscObjectGetName((PetscObject)plex,&plexname); CHKERRQ(ierr);\n    ierr = PetscPrintf(comm,\"point ranges for DMPlex %s in %dD:\\n\",plexname,dim); CHKERRQ(ierr);\n    if (size > 1) {\n        ierr = PetscSynchronizedPrintf(comm,\"  [rank %d]\",rank); CHKERRQ(ierr);\n    }\n    ierr = DMPlexGetChart(plex,&start,&end); CHKERRQ(ierr);\n    if (end < 1) { // nothing on this rank\n        ierr = PetscSynchronizedPrintf(comm,\"\\n\"); CHKERRQ(ierr);\n        ierr = PetscSynchronizedFlush(comm,PETSC_STDOUT); CHKERRQ(ierr);\n        return 0;\n    }\n    ierr = PetscSynchronizedPrintf(comm,\n        \"  chart points %d,...,%d\\n\",start,end-1); CHKERRQ(ierr);\n    for (m = 0; m < dim + 1; m++) {\n        if (use_height) {\n            ierr = DMPlexGetHeightStratum(plex,m,&start,&end); CHKERRQ(ierr);\n            ierr = PetscSynchronizedPrintf(comm,\n                \"    height %d of size %d: %d,...,%d (%s)\\n\",\n                m,end-start,start,end-1,dim < 4 ? stratanames[dim][2-m] : \"\"); CHKERRQ(ierr);\n        } else {\n            ierr = DMPlexGetDepthStratum(plex,m,&start,&end); CHKERRQ(ierr);\n            ierr = PetscSynchronizedPrintf(comm,\n                \"    depth=dim %d of size %d: %d,...,%d (%s)\\n\",\n                m,end-start,start,end-1,dim < 4 ? stratanames[dim][m] : \"\"); CHKERRQ(ierr);\n        }\n    }\n    ierr = PetscSynchronizedFlush(comm,PETSC_STDOUT); CHKERRQ(ierr);\n    return 0;\n}\n\nPetscErrorCode PlexViewFans(DM plex, int dim, int basestrata, int targetstrata) {\n    PetscErrorCode ierr;\n    const char  *plexname;\n    const int   *targets;\n    int         j, m, start, end, cssize;\n    MPI_Comm    comm;\n    PetscMPIInt rank,size;\n\n    ierr = PetscObjectGetComm((PetscObject)plex,&comm); CHKERRQ(ierr);\n    ierr = MPI_Comm_size(comm,&size);CHKERRQ(ierr);\n    ierr = MPI_Comm_rank(comm,&rank); CHKERRQ(ierr);\n    ierr = PetscObjectGetName((PetscObject)plex,&plexname); CHKERRQ(ierr);\n    ierr = PetscPrintf(comm,\"fans (cones or supports) for DMPlex %s:\\n\",plexname); CHKERRQ(ierr);\n    if (size > 1) {\n        ierr = PetscSynchronizedPrintf(comm,\"  [rank %d]\",rank); CHKERRQ(ierr);\n    }\n    ierr = PetscSynchronizedPrintf(comm,\n        \"  %s (= %s indices) of each %s\\n\",\n        (basestrata > targetstrata) ? \"cones\" : \"supports\",\n        stratanames[dim][targetstrata],stratanames[dim][basestrata]); CHKERRQ(ierr);\n    ierr = DMPlexGetDepthStratum(plex, basestrata, &start, &end); CHKERRQ(ierr);\n    for (m = start; m < end; m++) {\n        if (basestrata > targetstrata) {\n            ierr = DMPlexGetConeSize(plex,m,&cssize); CHKERRQ(ierr);\n            ierr = DMPlexGetCone(plex,m,&targets); CHKERRQ(ierr);\n        } else {\n            ierr = DMPlexGetSupportSize(plex,m,&cssize); CHKERRQ(ierr);\n            ierr = DMPlexGetSupport(plex,m,&targets); CHKERRQ(ierr);\n        }\n        ierr = PetscSynchronizedPrintf(comm,\n            \"    %s %d: \",stratanames[dim][basestrata],m); CHKERRQ(ierr);\n        for (j = 0; j < cssize-1; j++) {\n            ierr = PetscSynchronizedPrintf(comm,\n                \"%d,\",targets[j]); CHKERRQ(ierr);\n        }\n        ierr = PetscSynchronizedPrintf(comm,\n            \"%d\\n\",targets[cssize-1]); CHKERRQ(ierr);\n    }\n    ierr = PetscSynchronizedFlush(comm,PETSC_STDOUT); CHKERRQ(ierr);\n    return 0;\n}\n\nPetscErrorCode PlexViewCoords(DM plex) {\n    PetscErrorCode ierr;\n    PetscSection coordSection;\n    Vec          coordVec;\n    const char   *plexname;\n\n    ierr = PetscObjectGetName((PetscObject)plex,&plexname); CHKERRQ(ierr);\n    ierr = PetscPrintf(PETSC_COMM_WORLD,\"coordinate PetscSection and Vec for DMPlex %s:\\n\",plexname); CHKERRQ(ierr);\n    ierr = DMGetCoordinateSection(plex, &coordSection); CHKERRQ(ierr);\n    if (coordSection) {\n        ierr = PetscSectionView(coordSection,PETSC_VIEWER_STDOUT_WORLD); CHKERRQ(ierr);\n    } else {\n        ierr = PetscPrintf(PETSC_COMM_WORLD,\n            \"[PlexViewCoords():  vertex coordinates PetscSection has not been set]\\n\"); CHKERRQ(ierr);\n    }\n    ierr = DMGetCoordinatesLocal(plex,&coordVec); CHKERRQ(ierr);\n    if (coordVec) {\n        ierr = VecViewLocalStdout(coordVec,PETSC_COMM_WORLD); CHKERRQ(ierr);\n    } else {\n        ierr = PetscPrintf(PETSC_COMM_WORLD,\n            \"[PlexViewCoords():  vertex coordinates Vec not been set]\\n\"); CHKERRQ(ierr);\n    }\n    return 0;\n}\n\nPetscErrorCode PlexViewClosuresCoords(DM plex) {\n    PetscErrorCode ierr;\n    DM          cdm;\n    Vec         coords;\n    double      *acoords;\n    int         numpts, *pts = NULL,\n                j, p, vertexstart, vertexend, edgeend, cellstart, cellend;\n    MPI_Comm    comm;\n    PetscMPIInt rank,size;\n    const char  *plexname;\n\n    ierr = PetscObjectGetComm((PetscObject)plex,&comm); CHKERRQ(ierr);\n    ierr = MPI_Comm_size(comm,&size);CHKERRQ(ierr);\n    ierr = MPI_Comm_rank(comm,&rank); CHKERRQ(ierr);\n    ierr = PetscObjectGetName((PetscObject)plex,&plexname); CHKERRQ(ierr);\n    ierr = PetscPrintf(comm,\n        \"closure points and coordinates for each cell in DMPlex %s:\\n\",plexname); CHKERRQ(ierr);\n    if (size > 1) {\n        ierr = PetscSynchronizedPrintf(comm,\"  [rank %d]\",rank); CHKERRQ(ierr);\n    }\n    ierr = DMPlexGetHeightStratum(plex, 0, &cellstart, &cellend); CHKERRQ(ierr);\n    if (cellend < 1) { // nothing on this rank\n        ierr = PetscSynchronizedPrintf(comm,\"\\n\"); CHKERRQ(ierr);\n        ierr = PetscSynchronizedFlush(comm,PETSC_STDOUT); CHKERRQ(ierr);\n        return 0;\n    }\n    ierr = DMGetCoordinateDM(plex, &cdm); CHKERRQ(ierr);\n    ierr = DMGetCoordinatesLocal(plex,&coords); CHKERRQ(ierr);\n    ierr = DMPlexGetDepthStratum(plex, 0, &vertexstart, &vertexend); CHKERRQ(ierr);\n    ierr = DMPlexGetDepthStratum(plex, 1, NULL, &edgeend); CHKERRQ(ierr);\n    ierr = VecGetArray(coords, &acoords); CHKERRQ(ierr);\n    for (j = cellstart; j < cellend; j++) {\n        ierr = DMPlexGetTransitiveClosure(plex, j, PETSC_TRUE, &numpts, &pts);\n        ierr = PetscSynchronizedPrintf(comm,\"  cell %d\\n\",j); CHKERRQ(ierr);\n        for (p = 0; p < numpts*2; p += 2) {   // omit orientations\n            if ((pts[p] >= vertexstart) && (pts[p] < edgeend)) { // omit cells in closure\n                if (pts[p] < vertexend) { // get location from coords\n                    int voff;\n                    voff = pts[p] - vertexstart;\n                    ierr = PetscSynchronizedPrintf(comm,\n                        \"    vertex %3d at (%g,%g)\\n\",\n                        pts[p],acoords[2*voff+0],acoords[2*voff+1]); CHKERRQ(ierr);\n                } else { // assume it is an edge ... compute center\n                    const int *vertices;\n                    int       voff[2];\n                    double    x,y;\n                    ierr = DMPlexGetCone(plex, pts[p], &vertices); CHKERRQ(ierr);\n                    voff[0] = vertices[0] - vertexstart;\n                    voff[1] = vertices[1] - vertexstart;\n                    x = 0.5 * (acoords[2*voff[0]+0] + acoords[2*voff[1]+0]);\n                    y = 0.5 * (acoords[2*voff[0]+1] + acoords[2*voff[1]+1]);\n                    ierr = PetscSynchronizedPrintf(comm,\n                        \"    edge   %3d at (%g,%g)\\n\",pts[p],x,y); CHKERRQ(ierr);\n                }\n            }\n        }\n        ierr = DMPlexRestoreTransitiveClosure(plex, j, PETSC_TRUE, &numpts, &pts); CHKERRQ(ierr);\n    }\n    ierr = VecRestoreArray(coords, &acoords); CHKERRQ(ierr);\n    ierr = PetscSynchronizedFlush(comm,PETSC_STDOUT); CHKERRQ(ierr);\n    return 0;\n}\n\nPetscErrorCode VecViewLocalStdout(Vec v, MPI_Comm gcomm) {\n    PetscErrorCode ierr;\n    int         m,locsize;\n    PetscMPIInt rank,size;\n    double      *av;\n    const char  *vecname;\n    ierr = MPI_Comm_size(gcomm,&size);CHKERRQ(ierr);\n    ierr = MPI_Comm_rank(gcomm,&rank); CHKERRQ(ierr);\n    ierr = PetscObjectGetName((PetscObject)v,&vecname); CHKERRQ(ierr);\n    ierr = PetscPrintf(gcomm,\"local Vec: %s %d MPI processes\\n\",\n                       vecname,size); CHKERRQ(ierr);\n    if (size > 1) {\n        ierr = PetscSynchronizedPrintf(gcomm,\"[rank %d]:\\n\",rank); CHKERRQ(ierr);\n    }\n    ierr = VecGetLocalSize(v,&locsize); CHKERRQ(ierr);\n    ierr = VecGetArray(v, &av); CHKERRQ(ierr);\n    for (m = 0; m < locsize; m++) {\n        ierr = PetscSynchronizedPrintf(gcomm,\"%g\\n\",av[m]); CHKERRQ(ierr);\n    }\n    ierr = VecRestoreArray(v, &av); CHKERRQ(ierr);\n    ierr = PetscSynchronizedFlush(gcomm,PETSC_STDOUT); CHKERRQ(ierr);\n    return 0;\n}\n\n", "meta": {"hexsha": "2274c7980a115fd26c4162b952bb8df199493467", "size": 11110, "ext": "c", "lang": "C", "max_stars_repo_path": "c/junk/plex/plexview.c", "max_stars_repo_name": "thw1021/p4pdes", "max_stars_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 115.0, "max_stars_repo_stars_event_min_datetime": "2015-03-13T04:35:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T23:12:02.000Z", "max_issues_repo_path": "c/junk/plex/plexview.c", "max_issues_repo_name": "thw1021/p4pdes", "max_issues_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52.0, "max_issues_repo_issues_event_min_datetime": "2015-09-24T17:42:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-29T12:36:20.000Z", "max_forks_repo_path": "c/junk/plex/plexview.c", "max_forks_repo_name": "thw1021/p4pdes", "max_forks_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 46.0, "max_forks_repo_forks_event_min_datetime": "2016-07-23T09:26:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T07:43:17.000Z", "avg_line_length": 44.979757085, "max_line_length": 116, "alphanum_fraction": 0.5949594959, "num_tokens": 3003, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.044018649235890495, "lm_q1q2_score": 0.022009324617945247}}
{"text": "#include <gsl/gsl_test.h>\n#include <gsl/gsl_ieee_utils.h>\n#include <gsl/gsl_math.h>\n#include \"gsl_cblas.h\"\n\n#include \"tests.h\"\n\nvoid\ntest_symv (void) {\nconst double flteps = 1e-4, dbleps = 1e-6;\n  {\n   int order = 101;\n   int uplo = 121;\n   float alpha = 1.0f;\n   float beta = -1.0f;\n   int N = 1;\n   int lda = 1;\n   float A[] = { -0.428f };\n   float X[] = { -0.34f };\n   int incX = -1;\n   float Y[] = { -0.888f };\n   int incY = -1;\n   float y_expected[] = { 1.03352f };\n   cblas_ssymv(order, uplo, N, alpha, A, lda, X, incX, beta, Y, incY);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(Y[i], y_expected[i], flteps, \"ssymv(case 1054)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int uplo = 121;\n   float alpha = 1.0f;\n   float beta = -1.0f;\n   int N = 1;\n   int lda = 1;\n   float A[] = { -0.428f };\n   float X[] = { -0.34f };\n   int incX = -1;\n   float Y[] = { -0.888f };\n   int incY = -1;\n   float y_expected[] = { 1.03352f };\n   cblas_ssymv(order, uplo, N, alpha, A, lda, X, incX, beta, Y, incY);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(Y[i], y_expected[i], flteps, \"ssymv(case 1055)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int uplo = 122;\n   float alpha = 1.0f;\n   float beta = -1.0f;\n   int N = 1;\n   int lda = 1;\n   float A[] = { -0.428f };\n   float X[] = { -0.34f };\n   int incX = -1;\n   float Y[] = { -0.888f };\n   int incY = -1;\n   float y_expected[] = { 1.03352f };\n   cblas_ssymv(order, uplo, N, alpha, A, lda, X, incX, beta, Y, incY);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(Y[i], y_expected[i], flteps, \"ssymv(case 1056)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int uplo = 122;\n   float alpha = 1.0f;\n   float beta = -1.0f;\n   int N = 1;\n   int lda = 1;\n   float A[] = { -0.428f };\n   float X[] = { -0.34f };\n   int incX = -1;\n   float Y[] = { -0.888f };\n   int incY = -1;\n   float y_expected[] = { 1.03352f };\n   cblas_ssymv(order, uplo, N, alpha, A, lda, X, incX, beta, Y, incY);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(Y[i], y_expected[i], flteps, \"ssymv(case 1057)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int uplo = 121;\n   float alpha = 1.0f;\n   float beta = -1.0f;\n   int N = 1;\n   int lda = 1;\n   float A[] = { -0.428f };\n   float X[] = { -0.34f };\n   int incX = -1;\n   float Y[] = { -0.888f };\n   int incY = -1;\n   float y_expected[] = { 1.03352f };\n   cblas_ssymv(order, uplo, N, alpha, A, lda, X, incX, beta, Y, incY);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(Y[i], y_expected[i], flteps, \"ssymv(case 1058)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int uplo = 121;\n   float alpha = 1.0f;\n   float beta = -1.0f;\n   int N = 1;\n   int lda = 1;\n   float A[] = { -0.428f };\n   float X[] = { -0.34f };\n   int incX = -1;\n   float Y[] = { -0.888f };\n   int incY = -1;\n   float y_expected[] = { 1.03352f };\n   cblas_ssymv(order, uplo, N, alpha, A, lda, X, incX, beta, Y, incY);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(Y[i], y_expected[i], flteps, \"ssymv(case 1059)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int uplo = 122;\n   float alpha = 1.0f;\n   float beta = -1.0f;\n   int N = 1;\n   int lda = 1;\n   float A[] = { -0.428f };\n   float X[] = { -0.34f };\n   int incX = -1;\n   float Y[] = { -0.888f };\n   int incY = -1;\n   float y_expected[] = { 1.03352f };\n   cblas_ssymv(order, uplo, N, alpha, A, lda, X, incX, beta, Y, incY);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(Y[i], y_expected[i], flteps, \"ssymv(case 1060)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int uplo = 122;\n   float alpha = 1.0f;\n   float beta = -1.0f;\n   int N = 1;\n   int lda = 1;\n   float A[] = { -0.428f };\n   float X[] = { -0.34f };\n   int incX = -1;\n   float Y[] = { -0.888f };\n   int incY = -1;\n   float y_expected[] = { 1.03352f };\n   cblas_ssymv(order, uplo, N, alpha, A, lda, X, incX, beta, Y, incY);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(Y[i], y_expected[i], flteps, \"ssymv(case 1061)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int uplo = 121;\n   double alpha = 0;\n   double beta = -0.3;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.544 };\n   double X[] = { -0.601 };\n   int incX = -1;\n   double Y[] = { -0.852 };\n   int incY = -1;\n   double y_expected[] = { 0.2556 };\n   cblas_dsymv(order, uplo, N, alpha, A, lda, X, incX, beta, Y, incY);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(Y[i], y_expected[i], dbleps, \"dsymv(case 1062)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int uplo = 121;\n   double alpha = 0;\n   double beta = -0.3;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.544 };\n   double X[] = { -0.601 };\n   int incX = -1;\n   double Y[] = { -0.852 };\n   int incY = -1;\n   double y_expected[] = { 0.2556 };\n   cblas_dsymv(order, uplo, N, alpha, A, lda, X, incX, beta, Y, incY);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(Y[i], y_expected[i], dbleps, \"dsymv(case 1063)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int uplo = 122;\n   double alpha = 0;\n   double beta = -0.3;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.544 };\n   double X[] = { -0.601 };\n   int incX = -1;\n   double Y[] = { -0.852 };\n   int incY = -1;\n   double y_expected[] = { 0.2556 };\n   cblas_dsymv(order, uplo, N, alpha, A, lda, X, incX, beta, Y, incY);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(Y[i], y_expected[i], dbleps, \"dsymv(case 1064)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int uplo = 122;\n   double alpha = 0;\n   double beta = -0.3;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.544 };\n   double X[] = { -0.601 };\n   int incX = -1;\n   double Y[] = { -0.852 };\n   int incY = -1;\n   double y_expected[] = { 0.2556 };\n   cblas_dsymv(order, uplo, N, alpha, A, lda, X, incX, beta, Y, incY);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(Y[i], y_expected[i], dbleps, \"dsymv(case 1065)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int uplo = 121;\n   double alpha = 0;\n   double beta = -0.3;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.544 };\n   double X[] = { -0.601 };\n   int incX = -1;\n   double Y[] = { -0.852 };\n   int incY = -1;\n   double y_expected[] = { 0.2556 };\n   cblas_dsymv(order, uplo, N, alpha, A, lda, X, incX, beta, Y, incY);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(Y[i], y_expected[i], dbleps, \"dsymv(case 1066)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int uplo = 121;\n   double alpha = 0;\n   double beta = -0.3;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.544 };\n   double X[] = { -0.601 };\n   int incX = -1;\n   double Y[] = { -0.852 };\n   int incY = -1;\n   double y_expected[] = { 0.2556 };\n   cblas_dsymv(order, uplo, N, alpha, A, lda, X, incX, beta, Y, incY);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(Y[i], y_expected[i], dbleps, \"dsymv(case 1067)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int uplo = 122;\n   double alpha = 0;\n   double beta = -0.3;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.544 };\n   double X[] = { -0.601 };\n   int incX = -1;\n   double Y[] = { -0.852 };\n   int incY = -1;\n   double y_expected[] = { 0.2556 };\n   cblas_dsymv(order, uplo, N, alpha, A, lda, X, incX, beta, Y, incY);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(Y[i], y_expected[i], dbleps, \"dsymv(case 1068)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int uplo = 122;\n   double alpha = 0;\n   double beta = -0.3;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.544 };\n   double X[] = { -0.601 };\n   int incX = -1;\n   double Y[] = { -0.852 };\n   int incY = -1;\n   double y_expected[] = { 0.2556 };\n   cblas_dsymv(order, uplo, N, alpha, A, lda, X, incX, beta, Y, incY);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(Y[i], y_expected[i], dbleps, \"dsymv(case 1069)\");\n     }\n   };\n  };\n\n\n}\n", "meta": {"hexsha": "c997598bc4c20db3fe51572a8c85b3fab6a95314", "size": 7933, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/cblas/test_symv.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/cblas/test_symv.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/cblas/test_symv.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 20.8763157895, "max_line_length": 70, "alphanum_fraction": 0.4763645531, "num_tokens": 3210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713670203584295, "lm_q2_score": 0.048136766678658745, "lm_q1q2_score": 0.022005082766150916}}
{"text": "#include <cblas.h>", "meta": {"hexsha": "f6e0a41cc7aaf9e4a8f3bc6165bfe31080a32a79", "size": 18, "ext": "h", "lang": "C", "max_stars_repo_path": "Sources/C/CBlas/cblas.h", "max_stars_repo_name": "Max0u/NDArray", "max_stars_repo_head_hexsha": "49c5f1ec9958a73afde90842c57995d8de9f57b7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 66.0, "max_stars_repo_stars_event_min_datetime": "2019-08-02T01:36:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-22T04:55:11.000Z", "max_issues_repo_path": "Sources/C/CBlas/cblas.h", "max_issues_repo_name": "Max0u/NDArray", "max_issues_repo_head_hexsha": "49c5f1ec9958a73afde90842c57995d8de9f57b7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2019-08-02T06:07:39.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-22T03:44:41.000Z", "max_forks_repo_path": "Sources/C/CBlas/cblas.h", "max_forks_repo_name": "Max0u/NDArray", "max_forks_repo_head_hexsha": "49c5f1ec9958a73afde90842c57995d8de9f57b7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2019-08-03T05:29:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T07:25:21.000Z", "avg_line_length": 18.0, "max_line_length": 18, "alphanum_fraction": 0.7222222222, "num_tokens": 6, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926344647597, "lm_q2_score": 0.048857782084511685, "lm_q1q2_score": 0.021956327405063845}}
{"text": "/* avl.c\n * \n * Copyright (C) 1998-2002, 2004 Free Software Foundation, Inc.\n * Copyright (C) 2018 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* This code is originally from GNU libavl, with some modifications */\n\n#include <config.h>\n#include <stdlib.h>\n#include <stddef.h>\n#include <string.h>\n\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_bst.h>\n#include <gsl/gsl_errno.h>\n\ntypedef struct gsl_bst_avl_node avl_node;\ntypedef gsl_bst_avl_table avl_table;\ntypedef gsl_bst_avl_traverser avl_traverser;\n\n#ifndef AVL_MAX_HEIGHT\n#define AVL_MAX_HEIGHT GSL_BST_AVL_MAX_HEIGHT\n#endif\n\n/* Function types. */\ntypedef void avl_item_func (void *avl_item, void *avl_param);\ntypedef void *avl_copy_func (void *avl_item, void *avl_param);\n\n/* tree functions */\nstatic int avl_init(const gsl_bst_allocator * allocator,\n                    gsl_bst_cmp_function * compare, void * params, void * vtable);\nstatic size_t avl_nodes (const void * vtable);\nstatic int avl_empty (void * vtable);\nstatic void ** avl_probe (void * item, avl_table * table);\nstatic void * avl_insert (void * item, void * vtable);\nstatic void * avl_find (const void *item, const void * vtable);\nstatic void * avl_remove (const void *item, void * vtable);\n\n/* traverser functions */\nstatic int avl_t_init (void * vtrav, const void * vtable);\nstatic void * avl_t_first (void * vtrav, const void * vtable);\nstatic void * avl_t_last (void * vtrav, const void * vtable);\nstatic void * avl_t_find (const void * item, void * vtrav, const void * vtable);\nstatic void * avl_t_insert (void * item, void * vtrav, void * vtable);\nstatic void * avl_t_copy (void * vtrav, const void * vsrc);\nstatic void * avl_t_next (void * vtrav);\nstatic void * avl_t_prev (void * vtrav);\nstatic void * avl_t_cur (const void * vtrav);\nstatic void * avl_t_replace (void * vtrav, void * new_item);\nstatic void avl_trav_refresh (avl_traverser * trav);\n\n#if 0\nstatic avl_table * avl_copy (const avl_table *, avl_copy_func *,\n                             avl_item_func *);\nstatic void *avl_replace (avl_table *, void *);\n#endif\n\nstatic int\navl_init(const gsl_bst_allocator * allocator,\n         gsl_bst_cmp_function * compare, void * params, void * vtable)\n{\n  avl_table * table = (avl_table *) vtable;\n\n  table->avl_alloc = allocator;\n  table->avl_compare = compare;\n  table->avl_param = params;\n\n  table->avl_root = NULL;\n  table->avl_count = 0;\n  table->avl_generation = 0;\n\n  return GSL_SUCCESS;\n}\n\nstatic size_t\navl_nodes (const void * vtable)\n{\n  const avl_table * table = (const avl_table *) vtable;\n  return table->avl_count;\n}\n\n/* empty tree (delete all nodes) but do not free the tree itself */\nstatic int\navl_empty (void * vtable)\n{\n  avl_table * table = (avl_table *) vtable;\n  avl_node *p, *q;\n\n  for (p = table->avl_root; p != NULL; p = q)\n    {\n      if (p->avl_link[0] == NULL)\n        {\n          q = p->avl_link[1];\n          table->avl_alloc->free (p, table->avl_param);\n        }\n      else\n        {\n          q = p->avl_link[0];\n          p->avl_link[0] = q->avl_link[1];\n          q->avl_link[1] = p;\n        }\n    }\n\n  table->avl_root = NULL;\n  table->avl_count = 0;\n  table->avl_generation = 0;\n\n  return GSL_SUCCESS;\n}\n\n/*\navl_probe()\n  Inserts |item| into |tree| and returns a pointer to |item|'s address.\nIf a duplicate item is found in the tree, returns a pointer to the existing\nitem without inserting |item|.\nReturns |NULL| in case of memory allocation failure.\n*/\n\nstatic void **\navl_probe (void * item, avl_table * table)\n{\n  avl_node *y, *z; /* top node to update balance factor, and parent */\n  avl_node *p, *q; /* iterator, and parent */\n  avl_node *n;     /* newly inserted node */\n  avl_node *w;     /* new root of rebalanced subtree */\n  int dir;         /* direction to descend */\n\n  unsigned char da[AVL_MAX_HEIGHT]; /* cached comparison results */\n  int k = 0;                        /* number of cached results */\n\n  z = (avl_node *) &table->avl_root;\n  y = table->avl_root;\n  dir = 0;\n  for (q = z, p = y; p != NULL; q = p, p = p->avl_link[dir])\n    {\n      int cmp = table->avl_compare (item, p->avl_data, table->avl_param);\n\n      if (cmp == 0)\n        return &p->avl_data;\n\n      if (p->avl_balance != 0)\n        z = q, y = p, k = 0;\n\n      da[k++] = dir = cmp > 0;\n    }\n\n  /* allocate a new node */\n  n = q->avl_link[dir] = table->avl_alloc->alloc (sizeof *n, table->avl_param);\n  if (n == NULL)\n    return NULL;\n\n  table->avl_count++;\n\n  n->avl_data = item;\n  n->avl_link[0] = n->avl_link[1] = NULL;\n  n->avl_balance = 0;\n\n  if (y == NULL)\n    return &n->avl_data;\n\n  for (p = y, k = 0; p != n; p = p->avl_link[da[k]], k++)\n    if (da[k] == 0)\n      p->avl_balance--;\n    else\n      p->avl_balance++;\n\n  if (y->avl_balance == -2)\n    {\n      avl_node *x = y->avl_link[0];\n      if (x->avl_balance == -1)\n        {\n          w = x;\n          y->avl_link[0] = x->avl_link[1];\n          x->avl_link[1] = y;\n          x->avl_balance = y->avl_balance = 0;\n        }\n      else\n        {\n          w = x->avl_link[1];\n          x->avl_link[1] = w->avl_link[0];\n          w->avl_link[0] = x;\n          y->avl_link[0] = w->avl_link[1];\n          w->avl_link[1] = y;\n          if (w->avl_balance == -1)\n            x->avl_balance = 0, y->avl_balance = +1;\n          else if (w->avl_balance == 0)\n            x->avl_balance = y->avl_balance = 0;\n          else /* |w->avl_balance == +1| */\n            x->avl_balance = -1, y->avl_balance = 0;\n          w->avl_balance = 0;\n        }\n    }\n  else if (y->avl_balance == +2)\n    {\n      avl_node *x = y->avl_link[1];\n      if (x->avl_balance == +1)\n        {\n          w = x;\n          y->avl_link[1] = x->avl_link[0];\n          x->avl_link[0] = y;\n          x->avl_balance = y->avl_balance = 0;\n        }\n      else\n        {\n          w = x->avl_link[0];\n          x->avl_link[0] = w->avl_link[1];\n          w->avl_link[1] = x;\n          y->avl_link[1] = w->avl_link[0];\n          w->avl_link[0] = y;\n          if (w->avl_balance == +1)\n            x->avl_balance = 0, y->avl_balance = -1;\n          else if (w->avl_balance == 0)\n            x->avl_balance = y->avl_balance = 0;\n          else /* |w->avl_balance == -1| */\n            x->avl_balance = +1, y->avl_balance = 0;\n          w->avl_balance = 0;\n        }\n    }\n  else\n    return &n->avl_data;\n\n  z->avl_link[y != z->avl_link[0]] = w;\n  table->avl_generation++;\n\n  return &n->avl_data;\n}\n\n/*\navl_insert()\n  Inserts |item| into |table|. Returns NULL if item successfully inserted,\nor if a memory allocation error occurred. Otherwise, return duplicate\nitem.\n*/\n\nstatic void *\navl_insert (void * item, void * vtable)\n{\n  void **p = avl_probe (item, vtable);\n  return p == NULL || *p == item ? NULL : *p;\n}\n\n/*\navl_find()\n  Search for |item| in |table| and return a pointer to item if found.\nReturn NULL if not found.\n*/\n\nstatic void *\navl_find (const void * item, const void * vtable)\n{\n  const avl_table * table = (const avl_table *) vtable;\n  avl_node *p;\n\n  for (p = table->avl_root; p != NULL; )\n    {\n      int cmp = table->avl_compare (item, p->avl_data, table->avl_param);\n\n      if (cmp < 0)\n        p = p->avl_link[0];\n      else if (cmp > 0)\n        p = p->avl_link[1];\n      else /* |cmp == 0| */\n        return p->avl_data;\n    }\n\n  return NULL;\n}\n\n/*\navl_remove()\n  Deletes from |table| and returns an item matching |item|.\nReturns a null pointer if no matching item found.\n*/\n\nstatic void *\navl_remove (const void * item, void * vtable)\n{\n  avl_table * table = (avl_table *) vtable;\n\n  /* stack of nodes */\n  avl_node *pa[AVL_MAX_HEIGHT];      /* nodes */\n  unsigned char da[AVL_MAX_HEIGHT];  /* |link[]| indexes */\n  int k;                             /* stack pointer */\n\n  avl_node *p;                       /* traverses tree to find node to delete */\n  int cmp;                           /* result of comparison between |item| and |p| */\n\n  k = 0;\n  p = (avl_node *) &table->avl_root;\n  for (cmp = -1; cmp != 0;\n       cmp = table->avl_compare (item, p->avl_data, table->avl_param))\n    {\n      int dir = cmp > 0;\n\n      pa[k] = p;\n      da[k++] = dir;\n\n      p = p->avl_link[dir];\n      if (p == NULL)\n        return NULL;\n    }\n\n  item = p->avl_data;\n\n  if (p->avl_link[1] == NULL)\n    pa[k - 1]->avl_link[da[k - 1]] = p->avl_link[0];\n  else\n    {\n      avl_node *r = p->avl_link[1];\n      if (r->avl_link[0] == NULL)\n        {\n          r->avl_link[0] = p->avl_link[0];\n          r->avl_balance = p->avl_balance;\n          pa[k - 1]->avl_link[da[k - 1]] = r;\n          da[k] = 1;\n          pa[k++] = r;\n        }\n      else\n        {\n          avl_node *s;\n          int j = k++;\n\n          for (;;)\n            {\n              da[k] = 0;\n              pa[k++] = r;\n              s = r->avl_link[0];\n              if (s->avl_link[0] == NULL)\n                break;\n\n              r = s;\n            }\n\n          s->avl_link[0] = p->avl_link[0];\n          r->avl_link[0] = s->avl_link[1];\n          s->avl_link[1] = p->avl_link[1];\n          s->avl_balance = p->avl_balance;\n\n          pa[j - 1]->avl_link[da[j - 1]] = s;\n          da[j] = 1;\n          pa[j] = s;\n        }\n    }\n\n  table->avl_alloc->free (p, table->avl_param);\n\n  while (--k > 0)\n    {\n      avl_node *y = pa[k];\n\n      if (da[k] == 0)\n        {\n          y->avl_balance++;\n          if (y->avl_balance == +1)\n            break;\n          else if (y->avl_balance == +2)\n            {\n              avl_node *x = y->avl_link[1];\n              if (x->avl_balance == -1)\n                {\n                  avl_node *w;\n                  w = x->avl_link[0];\n                  x->avl_link[0] = w->avl_link[1];\n                  w->avl_link[1] = x;\n                  y->avl_link[1] = w->avl_link[0];\n                  w->avl_link[0] = y;\n                  if (w->avl_balance == +1)\n                    x->avl_balance = 0, y->avl_balance = -1;\n                  else if (w->avl_balance == 0)\n                    x->avl_balance = y->avl_balance = 0;\n                  else /* |w->avl_balance == -1| */\n                    x->avl_balance = +1, y->avl_balance = 0;\n                  w->avl_balance = 0;\n                  pa[k - 1]->avl_link[da[k - 1]] = w;\n                }\n              else\n                {\n                  y->avl_link[1] = x->avl_link[0];\n                  x->avl_link[0] = y;\n                  pa[k - 1]->avl_link[da[k - 1]] = x;\n                  if (x->avl_balance == 0)\n                    {\n                      x->avl_balance = -1;\n                      y->avl_balance = +1;\n                      break;\n                    }\n                  else\n                    x->avl_balance = y->avl_balance = 0;\n                }\n            }\n        }\n      else\n        {\n          y->avl_balance--;\n          if (y->avl_balance == -1)\n            break;\n          else if (y->avl_balance == -2)\n            {\n              avl_node *x = y->avl_link[0];\n              if (x->avl_balance == +1)\n                {\n                  avl_node *w;\n                  w = x->avl_link[1];\n                  x->avl_link[1] = w->avl_link[0];\n                  w->avl_link[0] = x;\n                  y->avl_link[0] = w->avl_link[1];\n                  w->avl_link[1] = y;\n                  if (w->avl_balance == -1)\n                    x->avl_balance = 0, y->avl_balance = +1;\n                  else if (w->avl_balance == 0)\n                    x->avl_balance = y->avl_balance = 0;\n                  else /* |w->avl_balance == +1| */\n                    x->avl_balance = -1, y->avl_balance = 0;\n                  w->avl_balance = 0;\n                  pa[k - 1]->avl_link[da[k - 1]] = w;\n                }\n              else\n                {\n                  y->avl_link[0] = x->avl_link[1];\n                  x->avl_link[1] = y;\n                  pa[k - 1]->avl_link[da[k - 1]] = x;\n                  if (x->avl_balance == 0)\n                    {\n                      x->avl_balance = +1;\n                      y->avl_balance = -1;\n                      break;\n                    }\n                  else\n                    x->avl_balance = y->avl_balance = 0;\n                }\n            }\n        }\n    }\n\n  table->avl_count--;\n  table->avl_generation++;\n\n  return (void *) item;\n}\n\n#if 0\n/* Inserts |item| into |table|, replacing any duplicate item.\n   Returns |NULL| if |item| was inserted without replacing a duplicate,\n   or if a memory allocation error occurred.\n   Otherwise, returns the item that was replaced. */\nstatic void *\navl_replace (avl_table *table, void *item)\n{\n  void **p = avl_probe (table, item);\n  if (p == NULL || *p == item)\n    return NULL;\n  else\n    {\n      void *r = *p;\n      *p = item;\n      return r;\n    }\n}\n\n\n/* Destroys |new| with |avl_destroy (new, destroy)|,\n   first setting right links of nodes in |stack| within |new|\n   to null pointers to avoid touching uninitialized data. */\nstatic void\ncopy_error_recovery (avl_node **stack, int height,\n                     avl_table *new, avl_item_func *destroy)\n{\n  for (; height > 2; height -= 2)\n    stack[height - 1]->avl_link[1] = NULL;\n  avl_destroy (new, destroy);\n}\n\n/* Copies |org| to a newly created tree, which is returned.\n   If |copy != NULL|, each data item in |org| is first passed to |copy|,\n   and the return values are inserted into the tree,\n   with |NULL| return values taken as indications of failure.\n   On failure, destroys the partially created new tree,\n   applying |destroy|, if non-null, to each item in the new tree so far,\n   and returns |NULL|.\n   If |allocator != NULL|, it is used for allocation in the new tree.\n   Otherwise, the same allocator used for |org| is used. */\nstatic avl_table *\navl_copy (const avl_table *org, avl_copy_func *copy,\n          avl_item_func *destroy, struct libavl_allocator *allocator)\n{\n  avl_node *stack[2 * (AVL_MAX_HEIGHT + 1)];\n  int height = 0;\n\n  avl_table *new;\n  const avl_node *x;\n  avl_node *y;\n\n  new = avl_alloc (org->avl_compare, org->avl_param,\n                   allocator != NULL ? allocator : org->avl_alloc);\n  if (new == NULL)\n    return NULL;\n  new->avl_count = org->avl_count;\n  if (new->avl_count == 0)\n    return new;\n\n  x = (const avl_node *) &org->avl_root;\n  y = (avl_node *) &new->avl_root;\n  for (;;)\n    {\n      while (x->avl_link[0] != NULL)\n        {\n          y->avl_link[0] =\n            new->allocator->alloc (sizeof *y->avl_link[0],\n                                   new->avl_param);\n          if (y->avl_link[0] == NULL)\n            {\n              if (y != (avl_node *) &new->avl_root)\n                {\n                  y->avl_data = NULL;\n                  y->avl_link[1] = NULL;\n                }\n\n              copy_error_recovery (stack, height, new, destroy);\n              return NULL;\n            }\n\n          stack[height++] = (avl_node *) x;\n          stack[height++] = y;\n          x = x->avl_link[0];\n          y = y->avl_link[0];\n        }\n      y->avl_link[0] = NULL;\n\n      for (;;)\n        {\n          y->avl_balance = x->avl_balance;\n          if (copy == NULL)\n            y->avl_data = x->avl_data;\n          else\n            {\n              y->avl_data = copy (x->avl_data, org->avl_param);\n              if (y->avl_data == NULL)\n                {\n                  y->avl_link[1] = NULL;\n                  copy_error_recovery (stack, height, new, destroy);\n                  return NULL;\n                }\n            }\n\n          if (x->avl_link[1] != NULL)\n            {\n              y->avl_link[1] =\n                new->allocator->alloc (sizeof *y->avl_link[1],\n                                       new->avl_param);\n              if (y->avl_link[1] == NULL)\n                {\n                  copy_error_recovery (stack, height, new, destroy);\n                  return NULL;\n                }\n\n              x = x->avl_link[1];\n              y = y->avl_link[1];\n              break;\n            }\n          else\n            y->avl_link[1] = NULL;\n\n          if (height <= 2)\n            return new;\n\n          y = stack[--height];\n          x = stack[--height];\n        }\n    }\n}\n\n#endif\n\n/*\navl_t_init()\n  Initializes |trav| for use with |tree| and selects the null node.\n*/\n\nstatic int\navl_t_init (void * vtrav, const void * vtable)\n{\n  avl_traverser * trav = (avl_traverser *) vtrav;\n  const avl_table * table = (const avl_table *) vtable;\n\n  trav->avl_table = table;\n  trav->avl_node = NULL;\n  trav->avl_height = 0;\n  trav->avl_generation = table->avl_generation;\n\n  return GSL_SUCCESS;\n}\n\n/*\navl_t_first()\n  Initializes |trav| for |tree| and selects and returns a pointer to its least-valued item.\n  Returns |NULL| if |tree| contains no nodes.\n*/\n\nstatic void *\navl_t_first (void * vtrav, const void * vtable)\n{\n  const avl_table * table = (const avl_table *) vtable;\n  avl_traverser * trav = (avl_traverser *) vtrav;\n  avl_node *x;\n\n  trav->avl_table = table;\n  trav->avl_height = 0;\n  trav->avl_generation = table->avl_generation;\n\n  x = table->avl_root;\n  if (x != NULL)\n    {\n      while (x->avl_link[0] != NULL)\n        {\n          if (trav->avl_height >= AVL_MAX_HEIGHT)\n            {\n              GSL_ERROR_NULL(\"traverser height exceeds maximum\", GSL_ETABLE);\n            }\n\n          trav->avl_stack[trav->avl_height++] = x;\n          x = x->avl_link[0];\n        }\n    }\n\n  trav->avl_node = x;\n\n  return x != NULL ? x->avl_data : NULL;\n}\n\n/*\navl_t_last()\n  Initializes |trav| for |tree| and selects and returns a pointer to its greatest-valued item.\n  Returns |NULL| if |tree| contains no nodes.\n*/\n\nstatic void *\navl_t_last (void * vtrav, const void * vtable)\n{\n  const avl_table * table = (const avl_table *) vtable;\n  avl_traverser * trav = (avl_traverser *) vtrav;\n  avl_node *x;\n\n  trav->avl_table = table;\n  trav->avl_height = 0;\n  trav->avl_generation = table->avl_generation;\n\n  x = table->avl_root;\n  if (x != NULL)\n    {\n      while (x->avl_link[1] != NULL)\n        {\n          if (trav->avl_height >= AVL_MAX_HEIGHT)\n            {\n              GSL_ERROR_NULL(\"traverser height exceeds maximum\", GSL_ETABLE);\n            }\n\n          trav->avl_stack[trav->avl_height++] = x;\n          x = x->avl_link[1];\n        }\n    }\n\n  trav->avl_node = x;\n\n  return x != NULL ? x->avl_data : NULL;\n}\n\n/*\navl_t_find()\n  Searches for |item| in |table|. If found, initializes |trav| to\nthe item found and returns the item as well.  If there is no matching\nitem, initializes |trav| to the null item and returns |NULL|.\n*/\n\nstatic void *\navl_t_find (const void * item, void * vtrav, const void * vtable)\n{\n  const avl_table * table = (const avl_table *) vtable;\n  avl_traverser * trav = (avl_traverser *) vtrav;\n  avl_node *p, *q;\n\n  trav->avl_table = table;\n  trav->avl_height = 0;\n  trav->avl_generation = table->avl_generation;\n\n  for (p = table->avl_root; p != NULL; p = q)\n    {\n      int cmp = table->avl_compare (item, p->avl_data, table->avl_param);\n\n      if (cmp < 0)\n        q = p->avl_link[0];\n      else if (cmp > 0)\n        q = p->avl_link[1];\n      else /* |cmp == 0| */\n        {\n          trav->avl_node = p;\n          return p->avl_data;\n        }\n\n      if (trav->avl_height >= AVL_MAX_HEIGHT)\n        {\n          GSL_ERROR_NULL(\"traverser height exceeds maximum\", GSL_ETABLE);\n        }\n\n      trav->avl_stack[trav->avl_height++] = p;\n    }\n\n  trav->avl_height = 0;\n  trav->avl_node = NULL;\n\n  return NULL;\n}\n\n/*\navl_t_insert()\n  Attempts to insert |item| into |table|.  If |item| is inserted\nsuccessfully, it is returned and |trav| is initialized to its location.\nIf a duplicate is found, it is returned and |trav| is initialized to\nits location.  No replacement of the item occurs.\nIf a memory allocation failure occurs, |NULL| is returned and |trav|\nis initialized to the null item.\n*/\n\nstatic void *\navl_t_insert (void * item, void * vtrav, void * vtable)\n{\n  avl_table * table = (avl_table *) vtable;\n  avl_traverser * trav = (avl_traverser *) vtrav;\n  void **p;\n\n  p = avl_probe (item, table);\n  if (p != NULL)\n    {\n      trav->avl_table = table;\n      trav->avl_node = ((avl_node *) ((char *) p - offsetof (avl_node, avl_data)));\n      trav->avl_generation = table->avl_generation - 1;\n      return *p;\n    }\n  else\n    {\n      avl_t_init (vtrav, vtable);\n      return NULL;\n    }\n}\n\n/*\navl_t_copy()\n  Initializes |trav| to have the same current node as |src|.\n*/\n\nstatic void *\navl_t_copy (void * vtrav, const void * vsrc)\n{\n  const avl_traverser * src = (const avl_traverser *) vsrc;\n  avl_traverser * trav = (avl_traverser *) vtrav;\n\n  if (trav != src)\n    {\n      trav->avl_table = src->avl_table;\n      trav->avl_node = src->avl_node;\n      trav->avl_generation = src->avl_generation;\n      if (trav->avl_generation == trav->avl_table->avl_generation)\n        {\n          trav->avl_height = src->avl_height;\n          memcpy (trav->avl_stack, (const void *) src->avl_stack,\n                  sizeof *trav->avl_stack * trav->avl_height);\n        }\n    }\n\n  return trav->avl_node != NULL ? trav->avl_node->avl_data : NULL;\n}\n\n/*\navl_t_next()\n  Returns the next data item in in-order within the tree\nbeing traversed with |trav|, or if there are no more data items returns NULL.\n*/\n\nstatic void *\navl_t_next (void * vtrav)\n{\n  avl_traverser * trav = (avl_traverser *) vtrav;\n  avl_node *x;\n\n  if (trav->avl_generation != trav->avl_table->avl_generation)\n    avl_trav_refresh (trav);\n\n  x = trav->avl_node;\n  if (x == NULL)\n    {\n      return avl_t_first (vtrav, trav->avl_table);\n    }\n  else if (x->avl_link[1] != NULL)\n    {\n      if (trav->avl_height >= AVL_MAX_HEIGHT)\n        {\n          GSL_ERROR_NULL(\"traverser height exceeds maximum\", GSL_ETABLE);\n        }\n\n      trav->avl_stack[trav->avl_height++] = x;\n      x = x->avl_link[1];\n\n      while (x->avl_link[0] != NULL)\n        {\n          if (trav->avl_height >= AVL_MAX_HEIGHT)\n            {\n              GSL_ERROR_NULL(\"traverser height exceeds maximum\", GSL_ETABLE);\n            }\n\n          trav->avl_stack[trav->avl_height++] = x;\n          x = x->avl_link[0];\n        }\n    }\n  else\n    {\n      avl_node *y;\n\n      do\n        {\n          if (trav->avl_height == 0)\n            {\n              trav->avl_node = NULL;\n              return NULL;\n            }\n\n          y = x;\n          x = trav->avl_stack[--trav->avl_height];\n        }\n      while (y == x->avl_link[1]);\n    }\n\n  trav->avl_node = x;\n\n  return x->avl_data;\n}\n\n/*\navl_t_prev()\n  Returns the previous data item in inorder within the tree being\ntraversed with |trav|, or if there are no more data items returns NULL.\n*/\n\nstatic void *\navl_t_prev (void * vtrav)\n{\n  avl_traverser * trav = (avl_traverser *) vtrav;\n  avl_node *x;\n\n  if (trav->avl_generation != trav->avl_table->avl_generation)\n    avl_trav_refresh (trav);\n\n  x = trav->avl_node;\n  if (x == NULL)\n    {\n      return avl_t_last (vtrav, trav->avl_table);\n    }\n  else if (x->avl_link[0] != NULL)\n    {\n      if (trav->avl_height >= AVL_MAX_HEIGHT)\n        {\n          GSL_ERROR_NULL(\"traverser height exceeds maximum\", GSL_ETABLE);\n        }\n\n      trav->avl_stack[trav->avl_height++] = x;\n      x = x->avl_link[0];\n\n      while (x->avl_link[1] != NULL)\n        {\n          if (trav->avl_height >= AVL_MAX_HEIGHT)\n            {\n              GSL_ERROR_NULL(\"traverser height exceeds maximum\", GSL_ETABLE);\n            }\n\n          trav->avl_stack[trav->avl_height++] = x;\n          x = x->avl_link[1];\n        }\n    }\n  else\n    {\n      avl_node *y;\n\n      do\n        {\n          if (trav->avl_height == 0)\n            {\n              trav->avl_node = NULL;\n              return NULL;\n            }\n\n          y = x;\n          x = trav->avl_stack[--trav->avl_height];\n        }\n      while (y == x->avl_link[0]);\n    }\n\n  trav->avl_node = x;\n\n  return x->avl_data;\n}\n\nstatic void *\navl_t_cur (const void * vtrav)\n{\n  const avl_traverser * trav = (const avl_traverser *) vtrav;\n  return trav->avl_node != NULL ? trav->avl_node->avl_data : NULL;\n}\n\n/*\navl_t_replace()\n  Replaces the current item in |trav| by |new| and returns the item replaced.\n|trav| must not have the null item selected. The new item must not upset the\nordering of the tree.\n*/\n\nstatic void *\navl_t_replace (void * vtrav, void * new_item)\n{\n  avl_traverser * trav = (avl_traverser *) vtrav;\n  void *old;\n\n  old = trav->avl_node->avl_data;\n  trav->avl_node->avl_data = new_item;\n\n  return old;\n}\n\n/*\navl_trav_refresh()\n  Refreshes the stack of parent pointers in |trav| and updates its generation number\n*/\n\nstatic void\navl_trav_refresh (avl_traverser * trav)\n{\n  trav->avl_generation = trav->avl_table->avl_generation;\n\n  if (trav->avl_node != NULL)\n    {\n      gsl_bst_cmp_function *cmp = trav->avl_table->avl_compare;\n      void *param = trav->avl_table->avl_param;\n      avl_node *node = trav->avl_node;\n      avl_node *i;\n\n      trav->avl_height = 0;\n      for (i = trav->avl_table->avl_root; i != node; )\n        {\n          if (trav->avl_height >= AVL_MAX_HEIGHT)\n            {\n              GSL_ERROR_VOID(\"traverser height exceeds maximum\", GSL_ETABLE);\n            }\n\n          trav->avl_stack[trav->avl_height++] = i;\n          i = i->avl_link[cmp (node->avl_data, i->avl_data, param) > 0];\n        }\n    }\n}\n\nstatic const gsl_bst_type avl_tree_type =\n{\n  \"AVL\",\n  sizeof(avl_node),\n  avl_init,\n  avl_nodes,\n  avl_insert,\n  avl_find,\n  avl_remove,\n  avl_empty,\n\n  avl_t_init,\n  avl_t_first,\n  avl_t_last,\n  avl_t_find,\n  avl_t_insert,\n  avl_t_copy,\n  avl_t_next,\n  avl_t_prev,\n  avl_t_cur,\n  avl_t_replace\n};\n\nconst gsl_bst_type * gsl_bst_avl = &avl_tree_type;\n", "meta": {"hexsha": "7423860b389b11f11245e61972df9cd15ce48ece", "size": 26047, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/bst/avl.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "gsl-2.6/bst/avl.c", "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "test/lib/gsl-2.6/bst/avl.c", "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 26.1516064257, "max_line_length": 94, "alphanum_fraction": 0.5442469382, "num_tokens": 7404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3345894279828469, "lm_q2_score": 0.06560483060816658, "lm_q1q2_score": 0.021950682746098023}}
{"text": "#pragma once\n\n#include <cuda/runtime_api.hpp>\n#include <gsl/gsl-lite.hpp>\n\nnamespace thrustshift {\n\nnamespace kernel {\n\ntemplate <typename A, class RangeX, class RangeY, class RangeD>\n__global__ void axmy(A a, RangeX x, RangeY y, RangeD d) {\n\tconst auto gtid = threadIdx.x + blockIdx.x * blockDim.x;\n\tgsl_Expects(x.size() == y.size());\n\tgsl_Expects(y.size() == d.size());\n\tif (gtid < x.size()) {\n\t\td[gtid] = a * x[gtid] * y[gtid];\n\t}\n}\n\n} // namespace kernel\n\nnamespace async {\n\ntemplate <typename A, class RangeX, class RangeY, class RangeD>\nvoid axmy(cuda::stream_t& stream, A a, RangeX&& x, RangeY&& y, RangeD&& d) {\n\n\tgsl_Expects(x.size() == y.size());\n\tgsl_Expects(y.size() == d.size());\n\tconstexpr cuda::grid::block_dimension_t block_dim = 256;\n\tconst cuda::grid::dimension_t grid_dim =\n\t    (x.size() + block_dim - 1) / block_dim;\n\n\tusing RangeXD = typename std::remove_reference<RangeX>::type;\n\tusing RangeYD = typename std::remove_reference<RangeY>::type;\n\tusing RangeDD = typename std::remove_reference<RangeD>::type;\n\n\tcuda::enqueue_launch(kernel::axmy<A, RangeXD, RangeYD, RangeDD>,\n\t                     stream,\n\t                     cuda::make_launch_config(grid_dim, block_dim),\n\t                     a,\n\t                     x,\n\t                     y,\n\t                     d);\n}\n\n} // namespace async\n\n} // namespace thrustshift\n", "meta": {"hexsha": "34321762a37f48f72a145705cd7e376670e6acef", "size": 1347, "ext": "h", "lang": "C", "max_stars_repo_path": "include/thrustshift/axmy.h", "max_stars_repo_name": "pauleonix/thrustshift", "max_stars_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-16T13:01:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T13:01:46.000Z", "max_issues_repo_path": "include/thrustshift/axmy.h", "max_issues_repo_name": "pauleonix/thrustshift", "max_issues_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-23T14:12:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-17T11:40:04.000Z", "max_forks_repo_path": "include/thrustshift/axmy.h", "max_forks_repo_name": "pauleonix/thrustshift", "max_forks_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4897959184, "max_line_length": 76, "alphanum_fraction": 0.6258351893, "num_tokens": 360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.461016779312316, "lm_q2_score": 0.047425873682455294, "lm_q1q2_score": 0.021864123541158267}}
{"text": "//===--- Sudoku/Solver_set_option.h                                     ---===//\n//\n// Helper functions\n//===----------------------------------------------------------------------===//\n#pragma once\n\n#include \"Board.h\"\n#include \"Location.h\"\n#include \"Location_Utilities.h\" // is_same_*\n#include \"Options.h\"\n#include \"Size.h\"\n#include \"Solvers_find.h\"\n#include \"Solvers_remove_option.h\"\n#include \"Value.h\"\n#include \"exceptions.h\"\n#include \"traits.h\"\n\n#include <gsl/gsl>\n\n#include <vector>\n\n#include <algorithm>   // find_if\n#include <iterator>    // next\n#include <stdexcept>   // logic_error\n#include <type_traits> // is_base_of\n\n#include \"Solver.fwd.h\" // Forward declaration - single_option\n\n#include <cassert>\n\n\nnamespace Sudoku\n{\n//===----------------------------------------------------------------------===//\ntemplate<int N, typename Options = Options<elem_size<N>>>\nint set_Value(Board<Options, N>&, Location<N>, Value);\ntemplate<int N, typename Options = Options<elem_size<N>>, typename ItrT>\nint set_Value(Board<Options, N>&, ItrT begin, ItrT end);\n\ntemplate<int N, typename Options = Options<elem_size<N>>, typename SectionT>\nint set_unique(Board<Options, N>&, SectionT, Value);\ntemplate<int N, typename Options = Options<elem_size<N>>, typename SectionT>\nint set_uniques(Board<Options, N>&, SectionT, Options worker);\n\ntemplate<int N, typename Options = Options<elem_size<N>>, typename SectionT>\nint set_section_locals(\n\tBoard<Options, N>&, SectionT, int rep_count, Options values);\ntemplate<int N, typename Options = Options<elem_size<N>>>\nint set_section_locals(\n\tBoard<Options, N>&,\n\tBoard_Section::Block<Options, N>,\n\tint rep_count,\n\tOptions values);\n\n//===----------------------------------------------------------------------===//\n\n\n// IF a possible option, Make [value] the answer for [loc]\ntemplate<int N, typename Options>\ninline int set_Value(\n\tBoard<Options, N>& board, // NOLINT(runtime/references)\n\tconst Location<N> loc,\n\tconst Value value)\n{\n\tassert(is_valid(loc));\n\tassert(is_valid<N>(value));\n\n\tint changes{0};\n\tauto& elem = board.at(loc);\n\tif (not elem.test(value)) // value is option nor answer\n\t\tthrow error::invalid_Board();\n\n\tif (not is_answer(elem))\n\t{\n\t\tchanges = gsl::narrow_cast<int>(elem.count_all());\n\t\telem.set_nocheck(value);\n\t}\n\treturn changes;\n}\n\n// set board_ using a transferable container of values\ntemplate<int N, typename Options, typename ItrT>\nint set_Value(\n\tBoard<Options, N>& board, // NOLINT(runtime/references)\n\tconst ItrT begin,\n\tconst ItrT end)\n{\n\t{\n\t\tstatic_assert(traits::is_forward<ItrT>);\n\t\tassert(end - begin == full_size<N>);\n\t}\n\tint changes{0};\n\tint n{0};\n\tfor (auto itr = begin; itr != end; ++itr)\n\t{\n\t\tconst Location<N> loc(n++); // start at 0!\n\n\t\t// handle different input types\n\t\tValue value{};\n\t\tif constexpr (traits::iterator_to<ItrT, Value>)\n\t\t{\n\t\t\tvalue = *itr;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tvalue = to_Value<N>(*itr);\n\t\t}\n\n\t\tif (value != Value{0})\n\t\t{\n\t\t\tif (not is_valid<N>(value))\n\t\t\t{\n\t\t\t\tthrow std::domain_error{\"Invalid Value\"};\n\t\t\t}\n\n\t\t\tif (is_option(board.at(loc), value))\n\t\t\t{ // update options on board\n\t\t\t\tchanges += single_option(board, loc, value);\n\t\t\t}\n\t\t\tassert(is_answer(board.at(loc), value));\n\t\t}\n\t}\n\tassert(n == full_size<N>);\n\treturn changes;\n}\n\n// Set unique values in section as answer\ntemplate<int N, typename Options, typename SectionT>\ninline int set_uniques(\n\tBoard<Options, N>& board, // NOLINT(runtime/references)\n\tconst SectionT section,\n\tconst Options worker)\n{\n\t{\n\t\tstatic_assert(Board_Section::traits::is_Section_v<SectionT>);\n\t\tstatic_assert(std::is_same_v<typename SectionT::value_type, Options>);\n\t}\n\tint changes{0};\n\n\tif (worker.count_all() > 0)\n\t{\n\t\tfor (Value val{1}; val < Value{worker.size()}; ++val)\n\t\t{\n\t\t\tif (worker[val])\n\t\t\t{\n\t\t\t\tchanges += set_unique(board, section, val);\n\t\t\t}\n\t\t}\n\t}\n\treturn changes;\n}\n\n// Set unique value in section as answer\ntemplate<int N, typename Options, typename SectionT>\ninline int set_unique(\n\tBoard<Options, N>& board, // NOLINT(runtime/references)\n\tconst SectionT section,\n\tconst Value value)\n{\n\t{\n\t\tstatic_assert(Board_Section::traits::is_Section_v<SectionT>);\n\t\tstatic_assert(std::is_same_v<typename SectionT::value_type, Options>);\n\t\tstatic_assert(traits::is_input<typename SectionT::iterator>);\n\t\tassert(is_valid<N>(value));\n\t}\n\tconst auto end       = section.cend();\n\tconst auto condition = [value](const Options& O) {\n\t\treturn O.test(value);\n\t};\n\n\tconst auto itr = std::find_if(section.cbegin(), end, condition);\n\n\tif (itr == end)\n\t{ // option not available in section\n\t\tthrow error::invalid_Board();\n\t}\n\tassert(&(*itr) == &board[itr.location()]); // section must be part of board\n\tassert(std::find_if(std::next(itr), end, condition) == end); // unique\n\n\treturn single_option(board, itr.location(), value);\n}\n\n// for [row/col] per value: if all in same block, remove from rest block\ntemplate<int N, typename Options, typename SectionT>\ninline int set_section_locals(\n\tBoard<Options, N>& board, // NOLINT(runtime/references)\n\tconst SectionT section,\n\tconst int rep_count,\n\tconst Options values)\n{\n\t{\n\t\tstatic_assert(Board_Section::traits::is_Section_v<SectionT>);\n\t\tstatic_assert(std::is_same_v<typename SectionT::value_type, Options>);\n\t\tassert(rep_count > 1);  // should have been caught by caller\n\t\t\t\t\t\t\t\t// use the set_uniques specialization\n\t\tassert(rep_count <= N); // won't fit in single block-row/col\n\t\tassert(values.count_all() > 0);\n\t}\n\tint changes{0};\n\tstd::vector<Location<N>> locations{};\n\n\t// start at 1, to skip the answer-bit\n\tfor (Value value{1}; value < Value{values.size()}; ++value)\n\t{\n\t\tif (values[value])\n\t\t{\n\t\t\tlocations = list_where_option<N>(section, value, rep_count);\n\t\t\tif (locations.size() != gsl::narrow_cast<size_t>(rep_count))\n\t\t\t{\n\t\t\t\tassert(changes > 0); // changed by earlier value in values\n\t\t\t}\n\t\t\telse if (is_same_block<N>(locations.cbegin(), locations.cend()))\n\t\t\t{ // remove from rest of block\n\t\t\t\tchanges += remove_option_section(\n\t\t\t\t\tboard, board.block(locations[0]), locations, value);\n\t\t\t}\n\t\t}\n\t}\n\treturn changes;\n}\n\n// per value in [block]: if all in same row/col, remove from rest row/col\ntemplate<int N, typename Options>\ninline int set_section_locals(\n\tBoard<Options, N>& board, // NOLINT(runtime/references)\n\tconst Board_Section::Block<Options, N> block,\n\tconst int rep_count,\n\tconst Options values)\n{\n\t{\n\t\tassert(rep_count > 1);  // should have been caught by caller\n\t\t\t\t\t\t\t\t// use the set_uniques specialization\n\t\tassert(rep_count <= N); // won't fit in single block-row/col\n\t\tassert(values.count_all() > 0);\n\t}\n\tint changes{0};\n\tstd::vector<Location<N>> locations{};\n\n\t// start at 1, to skip the answer-bit\n\tfor (Value value{1}; value < Value{values.size()}; ++value)\n\t{\n\t\tif (values[value])\n\t\t{\n\t\t\tlocations = list_where_option<N>(block, value, rep_count);\n\t\t\tif (locations.size() != gsl::narrow_cast<size_t>(rep_count))\n\t\t\t{\n\t\t\t\tassert(changes > 0); // changed by earlier value in values\n\t\t\t}\n\t\t\telse if (is_same_row<N>(locations.cbegin(), locations.cend()))\n\t\t\t{ // remove from rest of row\n\t\t\t\tchanges += remove_option_outside_block(\n\t\t\t\t\tboard, board.row(locations[0]), locations[0], value);\n\t\t\t}\n\t\t\telse if (is_same_col<N>(locations.cbegin(), locations.cend()))\n\t\t\t{ // remove from rest of col\n\t\t\t\tchanges += remove_option_outside_block(\n\t\t\t\t\tboard, board.col(locations[0]), locations[0], value);\n\t\t\t}\n\t\t}\n\t}\n\treturn changes;\n}\n\n\n} // namespace Sudoku\n", "meta": {"hexsha": "ea1e0c04f7e6ad66b45e0634626b5d5bb721dc90", "size": 7350, "ext": "h", "lang": "C", "max_stars_repo_path": "Sudoku/Sudoku/Solvers_set_option.h", "max_stars_repo_name": "FeodorFitsner/fwkSudoku", "max_stars_repo_head_hexsha": "760aa5731efe089dc08e51898a37d42f3db5bb10", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Sudoku/Sudoku/Solvers_set_option.h", "max_issues_repo_name": "FeodorFitsner/fwkSudoku", "max_issues_repo_head_hexsha": "760aa5731efe089dc08e51898a37d42f3db5bb10", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sudoku/Sudoku/Solvers_set_option.h", "max_forks_repo_name": "FeodorFitsner/fwkSudoku", "max_forks_repo_head_hexsha": "760aa5731efe089dc08e51898a37d42f3db5bb10", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6315789474, "max_line_length": 80, "alphanum_fraction": 0.6644897959, "num_tokens": 1903, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.044018649392654464, "lm_q1q2_score": 0.021837380345339715}}
{"text": "/* Copyright (c) 2020 Stijn Hinterding, Utrecht University\r\n * This sofware is licensed under the MIT license (see the LICENSE file)\t\r\n*/\r\n\r\n#ifndef FAKECOMMUNICATOR_H\r\n#define FAKECOMMUNICATOR_H\r\n\r\n#include <phast_gui/interfaces/itimetaggercommunicator.h>\r\n\r\n#include <gsl/gsl_rng.h>\r\n#include <chrono>\r\n#include <mutex>\r\n\r\nclass FakeCommunicator : public ITimeTaggerCommunicator\r\n{\r\nprivate:\r\n    gsl_rng* r;\r\n    double timeunit_seconds;\r\n    double decayrate_inv_seconds;\r\n    double pulse_period_seconds;\r\n    double detection_probability;\r\n\r\n    std::chrono::time_point<std::chrono::high_resolution_clock> prev_time;\r\n    bool first_run;\r\n\r\n    int64_t last_largest_time;\r\n    int64_t last_pulse_time;\r\n    int64_t pulse_period_timeunits;\r\n    int64_t last_pulse_published;\r\n    uint64_t sync_counter;\r\n    uint64_t sync_divider;\r\n\r\n    int64_t chan1_induced_delay;\r\n    int64_t chan2_induced_delay;\r\n\r\n    std::string descriptor;\r\n\r\n    bool chan0_enabled;\r\n    bool chan1_enabled;\r\n    bool chan2_enabled;\r\n\r\n    bool is_running;\r\n\r\n    double sim_speedup_factor;\r\n    std::mutex m;\r\n\r\n    std::map<chan_id,timestamp> first_times;\r\n    std::map<chan_id,timestamp> last_times;\r\n    std::map<chan_id,uint64_t> n_events;\r\n\r\n    int64_t n_emitters;\r\nprivate:\r\n    void gen_pulses(std::vector<int64_t> *timestamps,\r\n                    std::vector<uint8_t> *channel_IDs, int64_t duration);\r\n\r\npublic:\r\n    FakeCommunicator(const FakeCommunicator&) = delete;\r\n    FakeCommunicator& operator=(const FakeCommunicator&) = delete;\r\n    ~FakeCommunicator() override;\r\n\r\n    FakeCommunicator(double timeunit_seconds,\r\n                     double decayrate_inv_seconds,\r\n                     double pulse_period_seconds,\r\n                     double detection_probability,\r\n                     uint64_t sync_divider=128,\r\n                     int64_t chan1_induced_delay=0,\r\n                     int64_t chan2_induced_delay=0,\r\n                     int64_t n_emitters=1,\r\n                     double sim_speedup_factor=1);\r\n\r\n    void SetSimSpeedupFactor(double value)\r\n    {\r\n        std::lock_guard<std::mutex> l(this->m);\r\n        if (value <= 0.001)\r\n            value = 0.001;\r\n\r\n        this->sim_speedup_factor = value;\r\n    }\r\n\r\n    double GetSimSpeedupFactor() const\r\n    {\r\n        return this->sim_speedup_factor;\r\n    }\r\n\r\n    void SetDecayRate(double value)\r\n    {\r\n        std::lock_guard<std::mutex> l(this->m);\r\n        this->decayrate_inv_seconds = value;\r\n    }\r\n\r\n    int64_t GetNumEmitters() const\r\n    {\r\n        return this->n_emitters;\r\n    }\r\n\r\n    double GetDecayRate() const\r\n    {\r\n        return this->decayrate_inv_seconds;\r\n    }\r\n\r\n    void SetNumEmitters(int64_t value)\r\n    {\r\n        std::lock_guard<std::mutex> l(this->m);\r\n\r\n        if (value == 0)\r\n            value = 1;\r\n\r\n        this->n_emitters = value;\r\n    }\r\n    void SetPulsePeriod(double value)\r\n    {\r\n        std::lock_guard<std::mutex> l(this->m);\r\n        this->pulse_period_seconds = value;\r\n        this->pulse_period_timeunits = this->pulse_period_seconds/this->timeunit_seconds;\r\n    }\r\n\r\n    double GetPulsePeriod() const\r\n    {\r\n        return this->pulse_period_seconds;\r\n    }\r\n\r\n    void SetDetectionProbability(double value)\r\n    {\r\n        std::lock_guard<std::mutex> l(this->m);\r\n        if (value > 1.0)\r\n            value = 1.0;\r\n\r\n        if (value < 0.0)\r\n            value = 0.0;\r\n\r\n        this->detection_probability = value;\r\n    }\r\n\r\n    double GetDetectionProbability() const\r\n    {\r\n        return this->detection_probability;\r\n    }\r\n\r\n    void SetSyncDivider(uint64_t value)\r\n    {\r\n        std::lock_guard<std::mutex> l(this->m);\r\n        this->sync_divider = value;\r\n    }\r\n\r\n    virtual uint64_t ReceiveData(std::vector<int64_t>* timestamps,\r\n                             std::vector<uint8_t>* channel_IDs) override;\r\n\r\n    virtual uint64_t GetSyncDivider(chan_id channel_id) override\r\n    {\r\n        if (channel_id == 0)\r\n            return this->sync_divider;\r\n\r\n        return 1;\r\n    }\r\n\r\n    virtual void DisableChan(uint64_t ID);\r\n\r\n    virtual bool ConnectedToDevice() override\r\n    {\r\n        return true;\r\n    }\r\n\r\n    virtual const std::string& DeviceDescriptor() const override\r\n    {\r\n        return this->descriptor;\r\n    }\r\n\r\n    virtual bool TryToConnect(int64_t) override\r\n    {\r\n        return true;\r\n    }\r\n\r\n    virtual bool DataLossSinceLastCall() override\r\n    {\r\n        return false;\r\n    }\r\n\r\n    virtual double TimeUnit() const override\r\n    {\r\n        return this->timeunit_seconds;\r\n    }\r\n\r\n    virtual bool AnyDeviceAvailable() const override\r\n    {\r\n        return true;\r\n    }\r\n\r\n    virtual bool Disconnect() override\r\n    {\r\n        return true;\r\n    }\r\n\r\n    virtual uint64_t GetNumDevicesConnected() override\r\n    {\r\n        return 1;\r\n    }\r\n\r\n    virtual bool IsRealDevice() const\r\n    {\r\n        return false;\r\n    }\r\n};\r\n\r\n#endif // FAKECOMMUNICATOR_H\r\n", "meta": {"hexsha": "ecc53fb11044489c180e147f8cb55d4c39b69173", "size": 4917, "ext": "h", "lang": "C", "max_stars_repo_path": "fake_timetag_device_plugin/fakecommunicator.h", "max_stars_repo_name": "stijnhinterding/phast", "max_stars_repo_head_hexsha": "dad4702eb6401c1eba03ad70eff3659292636d30", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fake_timetag_device_plugin/fakecommunicator.h", "max_issues_repo_name": "stijnhinterding/phast", "max_issues_repo_head_hexsha": "dad4702eb6401c1eba03ad70eff3659292636d30", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fake_timetag_device_plugin/fakecommunicator.h", "max_forks_repo_name": "stijnhinterding/phast", "max_forks_repo_head_hexsha": "dad4702eb6401c1eba03ad70eff3659292636d30", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9853658537, "max_line_length": 90, "alphanum_fraction": 0.6040268456, "num_tokens": 1144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326184801538616, "lm_q2_score": 0.04813676770280703, "lm_q1q2_score": 0.02181856028646167}}
{"text": "// Precompiled headers go in here\n#pragma once\n\n// Standard Library Header\n#include <format>\n#include <fstream>\n#include <memory>\n#include <stdexcept>\n#include <random>\n#include <algorithm>\n#include <utility>\n#include <mutex>\n#include <shared_mutex>\n#include <execution>\n#include <optional>\n#include <iostream>\n\n// Data structures\n#include <string>\n#include <vector>\n#include <array>\n\n// GSL: Guidelines Support Library\n//#include <gsl/gsl>\n\n// Extern libs\n#include \"fmt/core.h\"\n#include \"nlohmann/json.hpp\"\n\n// My\n#include \"Enums.h\"\n#include \"RandomNumbers.h\"\n#include \"Statistics.h\"\n#include \"Disease/Disease.h\"\n#include \"Disease/Infection.h\"\n#include \"Person/Person.h\"\n#include \"Places/Places.h\"\n#include \"Places/Community.h\"\n#include \"Simulation/MeasureTime.h\"\n", "meta": {"hexsha": "90ee10abfdc30d8bc4122e129e2e4f659c823e5c", "size": 765, "ext": "h", "lang": "C", "max_stars_repo_path": "src/DiseaseSpreadSimulator/pch.h", "max_stars_repo_name": "Neithari/DiseaseSpreadSimulator", "max_stars_repo_head_hexsha": "8653f260660322e140fa390ce64dbd1b0346125a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/DiseaseSpreadSimulator/pch.h", "max_issues_repo_name": "Neithari/DiseaseSpreadSimulator", "max_issues_repo_head_hexsha": "8653f260660322e140fa390ce64dbd1b0346125a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2022-03-24T01:19:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T01:01:01.000Z", "max_forks_repo_path": "src/DiseaseSpreadSimulator/pch.h", "max_forks_repo_name": "Neithari/DiseaseSpreadSimulator", "max_forks_repo_head_hexsha": "8653f260660322e140fa390ce64dbd1b0346125a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.125, "max_line_length": 35, "alphanum_fraction": 0.737254902, "num_tokens": 180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681520167196, "lm_q2_score": 0.05500528248426954, "lm_q1q2_score": 0.02178584058470227}}
{"text": "\n#ifndef __SIMQ_H\n#define __SIMQ_H\n\n#include \"Queue.h\"\n#include \"statistics.h\"\n#include \"input.h\"\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n#include <errno.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n\n/* Defining non-queue function prototypes */\nCustomer* createCustomer(gsl_rng **);\ngsl_rng * randomGenerator();\nvoid validateArgs(int, char **);\n#endif\n", "meta": {"hexsha": "91ce5489edf0000f9d9125252f3e8b1d7d2dbf8c", "size": 384, "ext": "h", "lang": "C", "max_stars_repo_path": "simQ.h", "max_stars_repo_name": "b4ba/Postoffice_Queue_Simulation", "max_stars_repo_head_hexsha": "9f1dfaa6b97049ddeb508e692865f7ed442062e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "simQ.h", "max_issues_repo_name": "b4ba/Postoffice_Queue_Simulation", "max_issues_repo_head_hexsha": "9f1dfaa6b97049ddeb508e692865f7ed442062e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simQ.h", "max_forks_repo_name": "b4ba/Postoffice_Queue_Simulation", "max_forks_repo_head_hexsha": "9f1dfaa6b97049ddeb508e692865f7ed442062e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.2857142857, "max_line_length": 44, "alphanum_fraction": 0.7265625, "num_tokens": 102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.42632159254749036, "lm_q2_score": 0.05108273587359002, "lm_q1q2_score": 0.021777673309311713}}
{"text": "#ifndef __LINALG_LIB_WRAPPER_H__\n#define __LINALG_LIB_WRAPPER_H__\n\n// Wrapper for linear algebra library (BLAS, LAPACK)\n\n#if !defined(USE_MKL) && !defined(USE_OPENBLAS)\n#define USE_OPENBLAS\n#endif\n\n#ifdef USE_MKL\n#include <mkl.h>\n#define BLAS_SET_NUM_THREADS mkl_set_num_threads\n#endif\n\n#ifdef USE_OPENBLAS\n#include <cblas.h>\n#include <lapacke.h>\n#define BLAS_SET_NUM_THREADS openblas_set_num_threads\n#endif\n\n#endif\n\n", "meta": {"hexsha": "492bded893f0c67323fb1f4c0b15f9967dd946fa", "size": 417, "ext": "h", "lang": "C", "max_stars_repo_path": "src/linalg_lib_wrapper.h", "max_stars_repo_name": "scalable-matrix/H2Pack", "max_stars_repo_head_hexsha": "421e722712e69e35d2bacf5a23672cf7289317b6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2020-10-26T03:17:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T05:13:03.000Z", "max_issues_repo_path": "src/linalg_lib_wrapper.h", "max_issues_repo_name": "scalable-matrix/H2Pack", "max_issues_repo_head_hexsha": "421e722712e69e35d2bacf5a23672cf7289317b6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-12-13T18:18:02.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-29T23:53:06.000Z", "max_forks_repo_path": "src/linalg_lib_wrapper.h", "max_forks_repo_name": "scalable-matrix/H2Pack", "max_forks_repo_head_hexsha": "421e722712e69e35d2bacf5a23672cf7289317b6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-24T06:06:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-05T23:38:37.000Z", "avg_line_length": 18.1304347826, "max_line_length": 53, "alphanum_fraction": 0.8057553957, "num_tokens": 116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.5, "lm_q2_score": 0.043365795982107, "lm_q1q2_score": 0.0216828979910535}}
{"text": "/* multiset/gsl_multiset.h\n * based on combination/gsl_combination.h by Szymon Jaroszewicz\n * based on permutation/gsl_permutation.h by Brian Gough\n *\n * Copyright (C) 2009 Rhys Ulerich\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_MULTISET_H__\n#define __GSL_MULTISET_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_inline.h>\n#include <gsl/gsl_check_range.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\nstruct gsl_multiset_struct\n{\n  size_t n;\n  size_t k;\n  size_t *data;\n};\n\ntypedef struct gsl_multiset_struct gsl_multiset;\n\ngsl_multiset *gsl_multiset_alloc (const size_t n, const size_t k);\ngsl_multiset *gsl_multiset_calloc (const size_t n, const size_t k);\nvoid gsl_multiset_init_first (gsl_multiset * c);\nvoid gsl_multiset_init_last (gsl_multiset * c);\nvoid gsl_multiset_free (gsl_multiset * c);\nint gsl_multiset_memcpy (gsl_multiset * dest, const gsl_multiset * src);\n\nint gsl_multiset_fread (FILE * stream, gsl_multiset * c);\nint gsl_multiset_fwrite (FILE * stream, const gsl_multiset * c);\nint gsl_multiset_fscanf (FILE * stream, gsl_multiset * c);\nint gsl_multiset_fprintf (FILE * stream, const gsl_multiset * c, const char *format);\n\nsize_t gsl_multiset_n (const gsl_multiset * c);\nsize_t gsl_multiset_k (const gsl_multiset * c);\nsize_t * gsl_multiset_data (const gsl_multiset * c);\n\nint gsl_multiset_valid (gsl_multiset * c);\nint gsl_multiset_next (gsl_multiset * c);\nint gsl_multiset_prev (gsl_multiset * c);\n\nINLINE_DECL size_t gsl_multiset_get (const gsl_multiset * c, const size_t i);\n\n#ifdef HAVE_INLINE\n\nINLINE_FUN\nsize_t\ngsl_multiset_get (const gsl_multiset * c, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= c->k)) /* size_t is unsigned, can't be negative */\n    {\n      GSL_ERROR_VAL (\"index out of range\", GSL_EINVAL, 0);\n    }\n#endif\n  return c->data[i];\n}\n\n#endif /* HAVE_INLINE */\n\n__END_DECLS\n\n#endif /* __GSL_MULTISET_H__ */\n", "meta": {"hexsha": "65e93f68e16d5ccee55426008ee6dd13b3949e59", "size": 2784, "ext": "h", "lang": "C", "max_stars_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_multiset.h", "max_stars_repo_name": "snipekill/FPGen", "max_stars_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-07-06T02:44:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T21:02:18.000Z", "max_issues_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_multiset.h", "max_issues_repo_name": "snipekill/FPGen", "max_issues_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_multiset.h", "max_forks_repo_name": "snipekill/FPGen", "max_forks_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-06-27T11:11:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T19:22:30.000Z", "avg_line_length": 29.6170212766, "max_line_length": 85, "alphanum_fraction": 0.7564655172, "num_tokens": 756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473485858429, "lm_q2_score": 0.050330627433754126, "lm_q1q2_score": 0.021649585943291225}}
{"text": "/******************************************************************************\n\n  (c) 2017 - 2019 Scientific Computation Research Center,\n      Rensselaer Polytechnic Institute. All rights reserved.\n\n  This work is open source software, licensed under the terms of the\n  BSD license as described in the LICENSE file in the top-level directory.\n\n*******************************************************************************/\n#ifndef MSI_PETSC_VERSION_H_\n#define MSI_PETSC_VERSION_H_\n#include <petscversion.h>\n#include <petsc.h>\n#include <utility>\n\ntemplate <typename ... Args>\nauto PetscSetPCBackend(Args&&... args) -> decltype(\n#if PETSC_VERSION_GT(3,9,5)\n  PCFactorSetMatSolverType(std::forward<Args>(args)...)\n#else\n  PCFactorSetMatSolverPackage(std::forward<Args>(args)...)\n#endif\n  )\n{\n#if PETSC_VERSION_GT(3,9,5)\n  return PCFactorSetMatSolverType(std::forward<Args>(args)...);\n#else\n  return PCFactorSetMatSolverPackage(std::forward<Args>(args)...);\n#endif\n}\n#endif\n", "meta": {"hexsha": "272b1cb5f1527c54e0250d54b15509ac7f9aff34", "size": 974, "ext": "h", "lang": "C", "max_stars_repo_path": "include/msi_petsc_version.h", "max_stars_repo_name": "SCOREC/msi", "max_stars_repo_head_hexsha": "0eb22b50c313f63b336a98988c2777b7b2d65197", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-10T11:50:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-10T11:50:23.000Z", "max_issues_repo_path": "include/msi_petsc_version.h", "max_issues_repo_name": "SCOREC/msi", "max_issues_repo_head_hexsha": "0eb22b50c313f63b336a98988c2777b7b2d65197", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 20.0, "max_issues_repo_issues_event_min_datetime": "2018-04-18T19:33:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-21T16:38:35.000Z", "max_forks_repo_path": "include/msi_petsc_version.h", "max_forks_repo_name": "SCOREC/msi", "max_forks_repo_head_hexsha": "0eb22b50c313f63b336a98988c2777b7b2d65197", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-01-09T19:00:36.000Z", "max_forks_repo_forks_event_max_datetime": "2018-04-19T18:31:27.000Z", "avg_line_length": 30.4375, "max_line_length": 80, "alphanum_fraction": 0.6273100616, "num_tokens": 222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769843, "lm_q2_score": 0.04468087361190478, "lm_q1q2_score": 0.02164252532570372}}
{"text": "/* blas/gsl_cblas.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* This is a copy of the CBLAS standard header.\n * We carry this around so we do not have to\n * break our model for flexible BLAS functionality.\n */\n\n#ifndef __GSL_CBLAS_H__\n#define __GSL_CBLAS_H__\n#include <stddef.h>\n#include <gsl/gsl_types.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n#define __BEGIN_DECLS extern \"C\" {\n#define __END_DECLS }\n#else\n#define __BEGIN_DECLS           /* empty */\n#define __END_DECLS             /* empty */\n#endif\n\n__BEGIN_DECLS\n\n/*\n * Enumerated and derived types\n */\n#define CBLAS_INDEX size_t  /* this may vary between platforms */\n\nenum CBLAS_ORDER {CblasRowMajor=101, CblasColMajor=102};\nenum CBLAS_TRANSPOSE {CblasNoTrans=111, CblasTrans=112, CblasConjTrans=113};\nenum CBLAS_UPLO {CblasUpper=121, CblasLower=122};\nenum CBLAS_DIAG {CblasNonUnit=131, CblasUnit=132};\nenum CBLAS_SIDE {CblasLeft=141, CblasRight=142};\n\n/*\n * ===========================================================================\n * Prototypes for level 1 BLAS functions (complex are recast as routines)\n * ===========================================================================\n */\nGSL_EXPORT float  cblas_sdsdot(const int N, const float alpha, const float *X,\n                               const int incX, const float *Y, const int incY);\nGSL_EXPORT double cblas_dsdot(const int N, const float *X, const int incX, const float *Y,\n                              const int incY);\nGSL_EXPORT float  cblas_sdot(const int N, const float  *X, const int incX,\n                             const float  *Y, const int incY);\nGSL_EXPORT double cblas_ddot(const int N, const double *X, const int incX,\n                             const double *Y, const int incY);\n\n/*\n * Functions having prefixes Z and C only\n */\nGSL_EXPORT void   cblas_cdotu_sub(const int N, const void *X, const int incX,\n                                  const void *Y, const int incY, void *dotu);\nGSL_EXPORT void   cblas_cdotc_sub(const int N, const void *X, const int incX,\n                                  const void *Y, const int incY, void *dotc);\n\nGSL_EXPORT void   cblas_zdotu_sub(const int N, const void *X, const int incX,\n                                  const void *Y, const int incY, void *dotu);\nGSL_EXPORT void   cblas_zdotc_sub(const int N, const void *X, const int incX,\n                                  const void *Y, const int incY, void *dotc);\n\n\n/*\n * Functions having prefixes S D SC DZ\n */\nGSL_EXPORT float  cblas_snrm2(const int N, const float *X, const int incX);\nGSL_EXPORT float  cblas_sasum(const int N, const float *X, const int incX);\n\nGSL_EXPORT double cblas_dnrm2(const int N, const double *X, const int incX);\nGSL_EXPORT double cblas_dasum(const int N, const double *X, const int incX);\n\nGSL_EXPORT float  cblas_scnrm2(const int N, const void *X, const int incX);\nGSL_EXPORT float  cblas_scasum(const int N, const void *X, const int incX);\n\nGSL_EXPORT double cblas_dznrm2(const int N, const void *X, const int incX);\nGSL_EXPORT double cblas_dzasum(const int N, const void *X, const int incX);\n\n\n/*\n * Functions having standard 4 prefixes (S D C Z)\n */\nGSL_EXPORT CBLAS_INDEX cblas_isamax(const int N, const float  *X, const int incX);\nGSL_EXPORT CBLAS_INDEX cblas_idamax(const int N, const double *X, const int incX);\nGSL_EXPORT CBLAS_INDEX cblas_icamax(const int N, const void   *X, const int incX);\nGSL_EXPORT CBLAS_INDEX cblas_izamax(const int N, const void   *X, const int incX);\n\n/*\n * ===========================================================================\n * Prototypes for level 1 BLAS routines\n * ===========================================================================\n */\n\n/* \n * Routines with standard 4 prefixes (s, d, c, z)\n */\nGSL_EXPORT void cblas_sswap(const int N, float *X, const int incX, \n                            float *Y, const int incY);\nGSL_EXPORT void cblas_scopy(const int N, const float *X, const int incX, \n                            float *Y, const int incY);\nGSL_EXPORT void cblas_saxpy(const int N, const float alpha, const float *X,\n                            const int incX, float *Y, const int incY);\n\nGSL_EXPORT void cblas_dswap(const int N, double *X, const int incX, \n                            double *Y, const int incY);\nGSL_EXPORT void cblas_dcopy(const int N, const double *X, const int incX, \n                            double *Y, const int incY);\nGSL_EXPORT void cblas_daxpy(const int N, const double alpha, const double *X,\n                            const int incX, double *Y, const int incY);\n\nGSL_EXPORT void cblas_cswap(const int N, void *X, const int incX, \n                            void *Y, const int incY);\nGSL_EXPORT void cblas_ccopy(const int N, const void *X, const int incX, \n                            void *Y, const int incY);\nGSL_EXPORT void cblas_caxpy(const int N, const void *alpha, const void *X,\n                            const int incX, void *Y, const int incY);\n\nGSL_EXPORT void cblas_zswap(const int N, void *X, const int incX, \n                            void *Y, const int incY);\nGSL_EXPORT void cblas_zcopy(const int N, const void *X, const int incX, \n                            void *Y, const int incY);\nGSL_EXPORT void cblas_zaxpy(const int N, const void *alpha, const void *X,\n                            const int incX, void *Y, const int incY);\n\n\n/* \n * Routines with S and D prefix only\n */\nGSL_EXPORT void cblas_srotg(float *a, float *b, float *c, float *s);\nGSL_EXPORT void cblas_srotmg(float *d1, float *d2, float *b1, const float b2, float *P);\nGSL_EXPORT void cblas_srot(const int N, float *X, const int incX,\n                           float *Y, const int incY, const float c, const float s);\nGSL_EXPORT void cblas_srotm(const int N, float *X, const int incX,\n                           float *Y, const int incY, const float *P);\n\nGSL_EXPORT void cblas_drotg(double *a, double *b, double *c, double *s);\nGSL_EXPORT void cblas_drotmg(double *d1, double *d2, double *b1, const double b2, double *P);\nGSL_EXPORT void cblas_drot(const int N, double *X, const int incX,\n                           double *Y, const int incY, const double c, const double  s);\nGSL_EXPORT void cblas_drotm(const int N, double *X, const int incX,\n                            double *Y, const int incY, const double *P);\n\n\n/* \n * Routines with S D C Z CS and ZD prefixes\n */\nGSL_EXPORT void cblas_sscal(const int N, const float alpha, float *X, const int incX);\nGSL_EXPORT void cblas_dscal(const int N, const double alpha, double *X, const int incX);\nGSL_EXPORT void cblas_cscal(const int N, const void *alpha, void *X, const int incX);\nGSL_EXPORT void cblas_zscal(const int N, const void *alpha, void *X, const int incX);\nGSL_EXPORT void cblas_csscal(const int N, const float alpha, void *X, const int incX);\nGSL_EXPORT void cblas_zdscal(const int N, const double alpha, void *X, const int incX);\n\n/*\n * ===========================================================================\n * Prototypes for level 2 BLAS\n * ===========================================================================\n */\n\n/* \n * Routines with standard 4 prefixes (S, D, C, Z)\n */\nGSL_EXPORT void cblas_sgemv(const enum CBLAS_ORDER order,\n                            const enum CBLAS_TRANSPOSE TransA, const int M, const int N,\n                            const float alpha, const float *A, const int lda,\n                            const float *X, const int incX, const float beta,\n                            float *Y, const int incY);\nGSL_EXPORT void cblas_sgbmv(const enum CBLAS_ORDER order,\n                            const enum CBLAS_TRANSPOSE TransA, const int M, const int N,\n                            const int KL, const int KU, const float alpha,\n                            const float *A, const int lda, const float *X,\n                            const int incX, const float beta, float *Y, const int incY);\nGSL_EXPORT void cblas_strmv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                            const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag,\n                            const int N, const float *A, const int lda, \n                            float *X, const int incX);\nGSL_EXPORT void cblas_stbmv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                            const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag,\n                            const int N, const int K, const float *A, const int lda, \n                            float *X, const int incX);\nGSL_EXPORT void cblas_stpmv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                            const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag,\n                            const int N, const float *Ap, float *X, const int incX);\nGSL_EXPORT void cblas_strsv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                            const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag,\n                            const int N, const float *A, const int lda, float *X,\n                            const int incX);\nGSL_EXPORT void cblas_stbsv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                            const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag,\n                            const int N, const int K, const float *A, const int lda,\n                            float *X, const int incX);\nGSL_EXPORT void cblas_stpsv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                            const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag,\n                            const int N, const float *Ap, float *X, const int incX);\n\nGSL_EXPORT void cblas_dgemv(const enum CBLAS_ORDER order,\n                            const enum CBLAS_TRANSPOSE TransA, const int M, const int N,\n                            const double alpha, const double *A, const int lda,\n                            const double *X, const int incX, const double beta,\n                            double *Y, const int incY);\nGSL_EXPORT void cblas_dgbmv(const enum CBLAS_ORDER order,\n                            const enum CBLAS_TRANSPOSE TransA, const int M, const int N,\n                            const int KL, const int KU, const double alpha,\n                            const double *A, const int lda, const double *X,\n                            const int incX, const double beta, double *Y, const int incY);\nGSL_EXPORT void cblas_dtrmv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                            const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag,\n                            const int N, const double *A, const int lda, \n                            double *X, const int incX);\nGSL_EXPORT void cblas_dtbmv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                            const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag,\n                            const int N, const int K, const double *A, const int lda, \n                            double *X, const int incX);\nGSL_EXPORT void cblas_dtpmv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                            const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag,\n                            const int N, const double *Ap, double *X, const int incX);\nGSL_EXPORT void cblas_dtrsv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                            const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag,\n                            const int N, const double *A, const int lda, double *X,\n                            const int incX);\nGSL_EXPORT void cblas_dtbsv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                            const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag,\n                            const int N, const int K, const double *A, const int lda,\n                            double *X, const int incX);\nGSL_EXPORT void cblas_dtpsv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                            const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag,\n                            const int N, const double *Ap, double *X, const int incX);\n\nGSL_EXPORT void cblas_cgemv(const enum CBLAS_ORDER order,\n                            const enum CBLAS_TRANSPOSE TransA, const int M, const int N,\n                            const void *alpha, const void *A, const int lda,\n                            const void *X, const int incX, const void *beta,\n                            void *Y, const int incY);\nGSL_EXPORT void cblas_cgbmv(const enum CBLAS_ORDER order,\n                            const enum CBLAS_TRANSPOSE TransA, const int M, const int N,\n                            const int KL, const int KU, const void *alpha,\n                            const void *A, const int lda, const void *X,\n                            const int incX, const void *beta, void *Y, const int incY);\nGSL_EXPORT void cblas_ctrmv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                            const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag,\n                            const int N, const void *A, const int lda, \n                            void *X, const int incX);\nGSL_EXPORT void cblas_ctbmv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                            const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag,\n                            const int N, const int K, const void *A, const int lda, \n                            void *X, const int incX);\nGSL_EXPORT void cblas_ctpmv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                            const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag,\n                            const int N, const void *Ap, void *X, const int incX);\nGSL_EXPORT void cblas_ctrsv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                            const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag,\n                            const int N, const void *A, const int lda, void *X,\n                            const int incX);\nGSL_EXPORT void cblas_ctbsv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                            const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag,\n                            const int N, const int K, const void *A, const int lda,\n                            void *X, const int incX);\nGSL_EXPORT void cblas_ctpsv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                            const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag,\n                            const int N, const void *Ap, void *X, const int incX);\n\nGSL_EXPORT void cblas_zgemv(const enum CBLAS_ORDER order,\n                            const enum CBLAS_TRANSPOSE TransA, const int M, const int N,\n                            const void *alpha, const void *A, const int lda,\n                            const void *X, const int incX, const void *beta,\n                            void *Y, const int incY);\nGSL_EXPORT void cblas_zgbmv(const enum CBLAS_ORDER order,\n                            const enum CBLAS_TRANSPOSE TransA, const int M, const int N,\n                            const int KL, const int KU, const void *alpha,\n                            const void *A, const int lda, const void *X,\n                            const int incX, const void *beta, void *Y, const int incY);\nGSL_EXPORT void cblas_ztrmv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                            const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag,\n                            const int N, const void *A, const int lda, \n                            void *X, const int incX);\nGSL_EXPORT void cblas_ztbmv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                            const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag,\n                            const int N, const int K, const void *A, const int lda, \n                            void *X, const int incX);\nGSL_EXPORT void cblas_ztpmv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                            const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag,\n                            const int N, const void *Ap, void *X, const int incX);\nGSL_EXPORT void cblas_ztrsv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                            const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag,\n                            const int N, const void *A, const int lda, void *X,\n                            const int incX);\nGSL_EXPORT void cblas_ztbsv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                            const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag,\n                            const int N, const int K, const void *A, const int lda,\n                            void *X, const int incX);\nGSL_EXPORT void cblas_ztpsv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                            const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag,\n                            const int N, const void *Ap, void *X, const int incX);\n\n\n/* \n * Routines with S and D prefixes only\n */\nGSL_EXPORT void cblas_ssymv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                            const int N, const float alpha, const float *A,\n                            const int lda, const float *X, const int incX,\n                            const float beta, float *Y, const int incY);\nGSL_EXPORT void cblas_ssbmv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                            const int N, const int K, const float alpha, const float *A,\n                            const int lda, const float *X, const int incX,\n                            const float beta, float *Y, const int incY);\nGSL_EXPORT void cblas_sspmv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                            const int N, const float alpha, const float *Ap,\n                            const float *X, const int incX,\n                            const float beta, float *Y, const int incY);\nGSL_EXPORT void cblas_sger(const enum CBLAS_ORDER order, const int M, const int N,\n                           const float alpha, const float *X, const int incX,\n                           const float *Y, const int incY, float *A, const int lda);\nGSL_EXPORT void cblas_ssyr(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                           const int N, const float alpha, const float *X,\n                           const int incX, float *A, const int lda);\nGSL_EXPORT void cblas_sspr(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                           const int N, const float alpha, const float *X,\n                           const int incX, float *Ap);\nGSL_EXPORT void cblas_ssyr2(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                            const int N, const float alpha, const float *X,\n                            const int incX, const float *Y, const int incY, float *A,\n                            const int lda);\nGSL_EXPORT void cblas_sspr2(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                            const int N, const float alpha, const float *X,\n                            const int incX, const float *Y, const int incY, float *A);\n\nGSL_EXPORT void cblas_dsymv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                            const int N, const double alpha, const double *A,\n                            const int lda, const double *X, const int incX,\n                            const double beta, double *Y, const int incY);\nGSL_EXPORT void cblas_dsbmv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                            const int N, const int K, const double alpha, const double *A,\n                            const int lda, const double *X, const int incX,\n                            const double beta, double *Y, const int incY);\nGSL_EXPORT void cblas_dspmv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                            const int N, const double alpha, const double *Ap,\n                            const double *X, const int incX,\n                            const double beta, double *Y, const int incY);\nGSL_EXPORT void cblas_dger(const enum CBLAS_ORDER order, const int M, const int N,\n                           const double alpha, const double *X, const int incX,\n                           const double *Y, const int incY, double *A, const int lda);\nGSL_EXPORT void cblas_dsyr(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                           const int N, const double alpha, const double *X,\n                           const int incX, double *A, const int lda);\nGSL_EXPORT void cblas_dspr(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                           const int N, const double alpha, const double *X,\n                           const int incX, double *Ap);\nGSL_EXPORT void cblas_dsyr2(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                            const int N, const double alpha, const double *X,\n                            const int incX, const double *Y, const int incY, double *A,\n                            const int lda);\nGSL_EXPORT void cblas_dspr2(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                            const int N, const double alpha, const double *X,\n                            const int incX, const double *Y, const int incY, double *A);\n\n\n/* \n * Routines with C and Z prefixes only\n */\nGSL_EXPORT void cblas_chemv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                            const int N, const void *alpha, const void *A,\n                            const int lda, const void *X, const int incX,\n                            const void *beta, void *Y, const int incY);\nGSL_EXPORT void cblas_chbmv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                            const int N, const int K, const void *alpha, const void *A,\n                            const int lda, const void *X, const int incX,\n                            const void *beta, void *Y, const int incY);\nGSL_EXPORT void cblas_chpmv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                            const int N, const void *alpha, const void *Ap,\n                            const void *X, const int incX,\n                            const void *beta, void *Y, const int incY);\nGSL_EXPORT void cblas_cgeru(const enum CBLAS_ORDER order, const int M, const int N,\n                            const void *alpha, const void *X, const int incX,\n                            const void *Y, const int incY, void *A, const int lda);\nGSL_EXPORT void cblas_cgerc(const enum CBLAS_ORDER order, const int M, const int N,\n                            const void *alpha, const void *X, const int incX,\n                            const void *Y, const int incY, void *A, const int lda);\nGSL_EXPORT void cblas_cher(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                           const int N, const float alpha, const void *X, const int incX,\n                           void *A, const int lda);\nGSL_EXPORT void cblas_chpr(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                           const int N, const float alpha, const void *X,\n                           const int incX, void *A);\nGSL_EXPORT void cblas_cher2(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const int N,\n                            const void *alpha, const void *X, const int incX,\n                            const void *Y, const int incY, void *A, const int lda);\nGSL_EXPORT void cblas_chpr2(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const int N,\n                            const void *alpha, const void *X, const int incX,\n                            const void *Y, const int incY, void *Ap);\n\nGSL_EXPORT void cblas_zhemv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                            const int N, const void *alpha, const void *A,\n                            const int lda, const void *X, const int incX,\n                            const void *beta, void *Y, const int incY);\nGSL_EXPORT void cblas_zhbmv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                            const int N, const int K, const void *alpha, const void *A,\n                            const int lda, const void *X, const int incX,\n                            const void *beta, void *Y, const int incY);\nGSL_EXPORT void cblas_zhpmv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                            const int N, const void *alpha, const void *Ap,\n                            const void *X, const int incX,\n                            const void *beta, void *Y, const int incY);\nGSL_EXPORT void cblas_zgeru(const enum CBLAS_ORDER order, const int M, const int N,\n                            const void *alpha, const void *X, const int incX,\n                            const void *Y, const int incY, void *A, const int lda);\nGSL_EXPORT void cblas_zgerc(const enum CBLAS_ORDER order, const int M, const int N,\n                            const void *alpha, const void *X, const int incX,\n                            const void *Y, const int incY, void *A, const int lda);\nGSL_EXPORT void cblas_zher(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                           const int N, const double alpha, const void *X, const int incX,\n                           void *A, const int lda);\nGSL_EXPORT void cblas_zhpr(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n                           const int N, const double alpha, const void *X,\n                           const int incX, void *A);\nGSL_EXPORT void cblas_zher2(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const int N,\n                            const void *alpha, const void *X, const int incX,\n                            const void *Y, const int incY, void *A, const int lda);\nGSL_EXPORT void cblas_zhpr2(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const int N,\n                            const void *alpha, const void *X, const int incX,\n                            const void *Y, const int incY, void *Ap);\n\n/*\n * ===========================================================================\n * Prototypes for level 3 BLAS\n * ===========================================================================\n */\n\n/* \n * Routines with standard 4 prefixes (S, D, C, Z)\n */\nGSL_EXPORT void cblas_sgemm(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA,\n                            const enum CBLAS_TRANSPOSE TransB, const int M, const int N,\n                            const int K, const float alpha, const float *A,\n                            const int lda, const float *B, const int ldb,\n                            const float beta, float *C, const int ldc);\nGSL_EXPORT void cblas_ssymm(const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side,\n                            const enum CBLAS_UPLO Uplo, const int M, const int N,\n                            const float alpha, const float *A, const int lda,\n                            const float *B, const int ldb, const float beta,\n                            float *C, const int ldc);\nGSL_EXPORT void cblas_ssyrk(const enum CBLAS_ORDER Order, const enum CBLAS_UPLO Uplo,\n                            const enum CBLAS_TRANSPOSE Trans, const int N, const int K,\n                            const float alpha, const float *A, const int lda,\n                            const float beta, float *C, const int ldc);\nGSL_EXPORT void cblas_ssyr2k(const enum CBLAS_ORDER Order, const enum CBLAS_UPLO Uplo,\n                             const enum CBLAS_TRANSPOSE Trans, const int N, const int K,\n                             const float alpha, const float *A, const int lda,\n                             const float *B, const int ldb, const float beta,\n                             float *C, const int ldc);\nGSL_EXPORT void cblas_strmm(const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side,\n                            const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA,\n                            const enum CBLAS_DIAG Diag, const int M, const int N,\n                            const float alpha, const float *A, const int lda,\n                            float *B, const int ldb);\nGSL_EXPORT void cblas_strsm(const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side,\n                            const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA,\n                            const enum CBLAS_DIAG Diag, const int M, const int N,\n                            const float alpha, const float *A, const int lda,\n                            float *B, const int ldb);\n\nGSL_EXPORT void cblas_dgemm(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA,\n                            const enum CBLAS_TRANSPOSE TransB, const int M, const int N,\n                            const int K, const double alpha, const double *A,\n                            const int lda, const double *B, const int ldb,\n                            const double beta, double *C, const int ldc);\nGSL_EXPORT void cblas_dsymm(const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side,\n                            const enum CBLAS_UPLO Uplo, const int M, const int N,\n                            const double alpha, const double *A, const int lda,\n                            const double *B, const int ldb, const double beta,\n                            double *C, const int ldc);\nGSL_EXPORT void cblas_dsyrk(const enum CBLAS_ORDER Order, const enum CBLAS_UPLO Uplo,\n                            const enum CBLAS_TRANSPOSE Trans, const int N, const int K,\n                            const double alpha, const double *A, const int lda,\n                            const double beta, double *C, const int ldc);\nGSL_EXPORT void cblas_dsyr2k(const enum CBLAS_ORDER Order, const enum CBLAS_UPLO Uplo,\n                             const enum CBLAS_TRANSPOSE Trans, const int N, const int K,\n                             const double alpha, const double *A, const int lda,\n                             const double *B, const int ldb, const double beta,\n                             double *C, const int ldc);\nGSL_EXPORT void cblas_dtrmm(const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side,\n                            const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA,\n                            const enum CBLAS_DIAG Diag, const int M, const int N,\n                            const double alpha, const double *A, const int lda,\n                            double *B, const int ldb);\nGSL_EXPORT void cblas_dtrsm(const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side,\n                            const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA,\n                            const enum CBLAS_DIAG Diag, const int M, const int N,\n                            const double alpha, const double *A, const int lda,\n                            double *B, const int ldb);\n\nGSL_EXPORT void cblas_cgemm(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA,\n                            const enum CBLAS_TRANSPOSE TransB, const int M, const int N,\n                            const int K, const void *alpha, const void *A,\n                            const int lda, const void *B, const int ldb,\n                            const void *beta, void *C, const int ldc);\nGSL_EXPORT void cblas_csymm(const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side,\n                            const enum CBLAS_UPLO Uplo, const int M, const int N,\n                            const void *alpha, const void *A, const int lda,\n                            const void *B, const int ldb, const void *beta,\n                            void *C, const int ldc);\nGSL_EXPORT void cblas_csyrk(const enum CBLAS_ORDER Order, const enum CBLAS_UPLO Uplo,\n                            const enum CBLAS_TRANSPOSE Trans, const int N, const int K,\n                            const void *alpha, const void *A, const int lda,\n                            const void *beta, void *C, const int ldc);\nGSL_EXPORT void cblas_csyr2k(const enum CBLAS_ORDER Order, const enum CBLAS_UPLO Uplo,\n                             const enum CBLAS_TRANSPOSE Trans, const int N, const int K,\n                             const void *alpha, const void *A, const int lda,\n                             const void *B, const int ldb, const void *beta,\n                             void *C, const int ldc);\nGSL_EXPORT void cblas_ctrmm(const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side,\n                            const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA,\n                            const enum CBLAS_DIAG Diag, const int M, const int N,\n                            const void *alpha, const void *A, const int lda,\n                            void *B, const int ldb);\nGSL_EXPORT void cblas_ctrsm(const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side,\n                            const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA,\n                            const enum CBLAS_DIAG Diag, const int M, const int N,\n                            const void *alpha, const void *A, const int lda,\n                            void *B, const int ldb);\n\nGSL_EXPORT void cblas_zgemm(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA,\n                            const enum CBLAS_TRANSPOSE TransB, const int M, const int N,\n                            const int K, const void *alpha, const void *A,\n                            const int lda, const void *B, const int ldb,\n                            const void *beta, void *C, const int ldc);\nGSL_EXPORT void cblas_zsymm(const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side,\n                            const enum CBLAS_UPLO Uplo, const int M, const int N,\n                            const void *alpha, const void *A, const int lda,\n                            const void *B, const int ldb, const void *beta,\n                            void *C, const int ldc);\nGSL_EXPORT void cblas_zsyrk(const enum CBLAS_ORDER Order, const enum CBLAS_UPLO Uplo,\n                            const enum CBLAS_TRANSPOSE Trans, const int N, const int K,\n                            const void *alpha, const void *A, const int lda,\n                            const void *beta, void *C, const int ldc);\nGSL_EXPORT void cblas_zsyr2k(const enum CBLAS_ORDER Order, const enum CBLAS_UPLO Uplo,\n                             const enum CBLAS_TRANSPOSE Trans, const int N, const int K,\n                             const void *alpha, const void *A, const int lda,\n                             const void *B, const int ldb, const void *beta,\n                             void *C, const int ldc);\nGSL_EXPORT void cblas_ztrmm(const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side,\n                            const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA,\n                            const enum CBLAS_DIAG Diag, const int M, const int N,\n                            const void *alpha, const void *A, const int lda,\n                            void *B, const int ldb);\nGSL_EXPORT void cblas_ztrsm(const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side,\n                            const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA,\n                            const enum CBLAS_DIAG Diag, const int M, const int N,\n                            const void *alpha, const void *A, const int lda,\n                            void *B, const int ldb);\n\n\n/* \n * Routines with prefixes C and Z only\n */\nGSL_EXPORT void cblas_chemm(const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side,\n                            const enum CBLAS_UPLO Uplo, const int M, const int N,\n                            const void *alpha, const void *A, const int lda,\n                            const void *B, const int ldb, const void *beta,\n                            void *C, const int ldc);\nGSL_EXPORT void cblas_cherk(const enum CBLAS_ORDER Order, const enum CBLAS_UPLO Uplo,\n                            const enum CBLAS_TRANSPOSE Trans, const int N, const int K,\n                            const float alpha, const void *A, const int lda,\n                            const float beta, void *C, const int ldc);\nGSL_EXPORT void cblas_cher2k(const enum CBLAS_ORDER Order, const enum CBLAS_UPLO Uplo,\n                             const enum CBLAS_TRANSPOSE Trans, const int N, const int K,\n                             const void *alpha, const void *A, const int lda,\n                             const void *B, const int ldb, const float beta,\n                             void *C, const int ldc);\n\nGSL_EXPORT void cblas_zhemm(const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side,\n                            const enum CBLAS_UPLO Uplo, const int M, const int N,\n                            const void *alpha, const void *A, const int lda,\n                            const void *B, const int ldb, const void *beta,\n                            void *C, const int ldc);\nGSL_EXPORT void cblas_zherk(const enum CBLAS_ORDER Order, const enum CBLAS_UPLO Uplo,\n                            const enum CBLAS_TRANSPOSE Trans, const int N, const int K,\n                            const double alpha, const void *A, const int lda,\n                            const double beta, void *C, const int ldc);\nGSL_EXPORT void cblas_zher2k(const enum CBLAS_ORDER Order, const enum CBLAS_UPLO Uplo,\n                             const enum CBLAS_TRANSPOSE Trans, const int N, const int K,\n                             const void *alpha, const void *A, const int lda,\n                             const void *B, const int ldb, const double beta,\n                             void *C, const int ldc);\n\nGSL_EXPORT void cblas_xerbla(int p, const char *rout, const char *form, ...);\n\n__END_DECLS\n\n#endif /* __GSL_CBLAS_H__ */\n", "meta": {"hexsha": "98671151a507122355452ce1024518710c4d6581", "size": 38772, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/gsl/include/gsl/gsl_cblas.h", "max_stars_repo_name": "dynaryu/vaws", "max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/gsl/include/gsl/gsl_cblas.h", "max_issues_repo_name": "dynaryu/vaws", "max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/gsl/include/gsl/gsl_cblas.h", "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 63.7697368421, "max_line_length": 98, "alphanum_fraction": 0.57758176, "num_tokens": 9140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.0495890189458586, "lm_q1q2_score": 0.021520715080311992}}
{"text": "/* multiset/init.c\n * based on combination/init.c by Szymon Jaroszewicz\n * based on permutation/init.c by Brian Gough\n *\n * Copyright (C) 2001 Szymon Jaroszewicz\n * Copyright (C) 2009 Brian Gough\n * Copyright (C) 2009 Rhys Ulerich\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <stdlib.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_multiset.h>\n\ngsl_multiset *\ngsl_multiset_alloc (const size_t n, const size_t k)\n{\n  gsl_multiset * c;\n\n  if (n == 0)\n    {\n      GSL_ERROR_VAL (\"multiset parameter n must be positive integer\",\n                        GSL_EDOM, 0);\n    }\n  if (k > n)\n    {\n      GSL_ERROR_VAL (\"multiset length k must be an integer less than or equal to n\",\n                        GSL_EDOM, 0);\n    }\n  c = (gsl_multiset *) malloc (sizeof (gsl_multiset));\n\n  if (c == 0)\n    {\n      GSL_ERROR_VAL (\"failed to allocate space for multiset struct\",\n                        GSL_ENOMEM, 0);\n    }\n\n  if (k > 0)\n    {\n      c->data = (size_t *) malloc (k * sizeof (size_t));\n\n      if (c->data == 0)\n        {\n          free (c);             /* exception in constructor, avoid memory leak */\n\n          GSL_ERROR_VAL (\"failed to allocate space for multiset data\",\n                         GSL_ENOMEM, 0);\n        }\n    }\n  else\n    {\n      c->data = 0;\n    }\n\n  c->n = n;\n  c->k = k;\n\n  return c;\n}\n\ngsl_multiset *\ngsl_multiset_calloc (const size_t n, const size_t k)\n{\n  size_t i;\n\n  gsl_multiset * c =  gsl_multiset_alloc (n, k);\n\n  if (c == 0)\n    return 0;\n\n  /* initialize multiset to repeated first element */\n\n  for (i = 0; i < k; i++)\n    {\n      c->data[i] = 0;\n    }\n\n  return c;\n}\n\nvoid\ngsl_multiset_init_first (gsl_multiset * c)\n{\n  const size_t k = c->k ;\n  size_t i;\n\n  /* initialize multiset to repeated first element */\n\n  for (i = 0; i < k; i++)\n    {\n      c->data[i] = 0;\n    }\n}\n\nvoid\ngsl_multiset_init_last (gsl_multiset * c)\n{\n  const size_t k = c->k ;\n  size_t i;\n  size_t n = c->n;\n\n  /* initialize multiset to repeated last element */\n\n  for (i = 0; i < k; i++)\n    {\n      c->data[i] = n - 1;\n    }\n}\n\nvoid\ngsl_multiset_free (gsl_multiset * c)\n{\n  RETURN_IF_NULL (c);\n  if (c->k > 0) free (c->data);\n  free (c);\n}\n", "meta": {"hexsha": "b71b7369c7c0cf76174882b6535dbe8ac898c834", "size": 2860, "ext": "c", "lang": "C", "max_stars_repo_path": "folding_libs/gsl-1.14/multiset/init.c", "max_stars_repo_name": "parasol-ppl/PPL_utils", "max_stars_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "folding_libs/gsl-1.14/multiset/init.c", "max_issues_repo_name": "parasol-ppl/PPL_utils", "max_issues_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "folding_libs/gsl-1.14/multiset/init.c", "max_forks_repo_name": "parasol-ppl/PPL_utils", "max_forks_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.8320610687, "max_line_length": 84, "alphanum_fraction": 0.606993007, "num_tokens": 836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.04336579613665143, "lm_q1q2_score": 0.021513503873486616}}
{"text": "/**\r\n * @file xdegnome.c\r\n * @author Daniel R. Tabin\r\n * @brief Unit tests for Degnome\r\n */\r\n\r\n#include \"degnome.h\"\r\n#include <stdio.h>\r\n#include <string.h>\r\n#include <gsl/gsl_rng.h>\r\n#include <gsl/gsl_randist.h>\r\n#include <time.h>\r\n#include <unistd.h>\r\n#include <limits.h>\r\n\r\nunsigned long rngseed=0;\r\n\r\nint main(int argc, char **argv) {\r\n\tint verbose = 0;\r\n\tint seeded =0;\r\n\r\n\tif (argc == 2) {\r\n\t\tif (strncmp(argv[1], \"-v\", 2) != 0) {\r\n\t\t\tfprintf(stderr, \"usage: xdegnome [-v] [-s] [0000000000]\\n\");\r\n\t\t\texit(EXIT_FAILURE);\r\n\t\t}\r\n\t\tverbose = 1;\r\n\t}\r\n\telse if (argc == 3) {\r\n\t\tif (strncmp(argv[1], \"-s\", 2) != 0) {\r\n\t\t\tfprintf(stderr, \"usage: xdegnome [-v] [-s] [0000000000]\\n\");\r\n\t\t\texit(EXIT_FAILURE);\r\n\t\t}\r\n\t\trngseed = (unsigned long) atoi(argv[2]);\r\n\t}\r\n\telse if (argc == 4) {\r\n\t\tif (strncmp(argv[1], \"-v\", 2) != 0) {\r\n\t\t\tfprintf(stderr, \"usage: xdegnome [-v] [-s] [0000000000]\\n\");\r\n\t\t\texit(EXIT_FAILURE);\r\n\t\t}\r\n\t\telse if (strncmp(argv[2], \"-s\", 2) != 0) {\t\t\r\n\t\t\tfprintf(stderr, \"usage: xdegnome [-v] [-s]  [0000000000]\\n\");\r\n\t\t\texit(EXIT_FAILURE);\r\n\t\t}\r\n\t\tverbose = 1;\r\n\t\tseeded = 1;\r\n\t\trngseed = (unsigned long) atoi(argv[3]);\r\n\t\t\r\n\t}\r\n\telse if (argc != 1) {\r\n\t\tfprintf(stderr, \"usage: xdegnome [-v] [-s] [seed]\\n\");\r\n\t\texit(EXIT_FAILURE);\r\n\t}\r\n\r\n\tchrom_size = 15;\r\n\r\n\tif (verbose) {\r\n\t\tprintf(\"Chromosome is length %u\\n\", chrom_size);\r\n\t}\r\n\r\n\tDegnome* bom_mom = Degnome_new(); // good parent\r\n\tDegnome* bad_dad = Degnome_new();\t// bad parent\r\n\tDegnome* tst_bby = Degnome_new(); // their child\r\n\t\r\n\t// ============ change this to seed rn\r\n\tif (seeded == 0) {\r\n\t\ttime_t currtime = time(NULL);                  // time\r\n\t\tunsigned long pid = (unsigned long) getpid();  // process id\r\n\t\trngseed = currtime ^ pid;\t\t\t\t\t   // random seed\t\r\n\t}\r\n\tgsl_rng* rng = gsl_rng_alloc(gsl_rng_taus);    // rand generator\r\n\t\r\n\tgsl_rng_set(rng, rngseed);\r\n\trngseed = (rngseed == ULONG_MAX ? 0 : rngseed + 1);\r\n\t\r\n\t// ============ change this to seed rn\r\n\t\r\n\t\r\n\t\r\n\tfor (int i = 0; i < chrom_size; i++) {\r\n\t\tbom_mom->dna_array[i] = 2*i;\r\n\t\tbad_dad->dna_array[i] = 1*i;\r\n\r\n\t\tbom_mom->hat_size += bom_mom->dna_array[i];\r\n\t\tbad_dad->hat_size += bad_dad->dna_array[i];\r\n\t}\r\n\r\n\tif (verbose) {\r\n\t\tprintf(\"pre-mating values:\\n\");\r\n\t\tfor (int i = 0; i < chrom_size; i++) {\r\n\t\t\tprintf(\"Mom: %lf\\t Dad: %f\\n\", bom_mom->dna_array[i], bad_dad->dna_array[i]);\r\n\t\t}\r\n\t\tprintf(\"Mom hat_size: %lf\\t Dad hat_size: %f\\n\", bom_mom->hat_size, bad_dad->hat_size);\r\n\t}\r\n\r\n\tDegnome_mate(tst_bby, bom_mom, bad_dad, rng, 0, 0,2);\r\n\r\n\r\n\tif (verbose) {\r\n\t\tprintf(\"post-mating values:\\n\");\r\n\t\tfor (int i = 0; i < chrom_size; i++) {\r\n\t\t\tprintf(\"Mom: %lf\\t Dad: %f\\t Kid: %f\\n\", bom_mom->dna_array[i], bad_dad->dna_array[i], tst_bby->dna_array[i]);\r\n\t\t}\r\n\t\tprintf(\"Mom hat_size: %lf\\t Dad hat_size: %f\\t Kid hat_size: %f\\n\", bom_mom->hat_size, bad_dad->hat_size, tst_bby->hat_size);\r\n\t}\r\n\r\n\tDegnome_free(bom_mom);\r\n\tDegnome_free(bad_dad);\r\n\tDegnome_free(tst_bby);\r\n\r\n\tgsl_rng_free(rng);\r\n\r\n\tprintf(\"All tests for xdegnome completed\\n\");\r\n}", "meta": {"hexsha": "caa82546821f49ea03e577501d5cb3a2da7b6e2a", "size": 2996, "ext": "c", "lang": "C", "max_stars_repo_path": "src/xdegnome.c", "max_stars_repo_name": "masalemi/PopGenSim", "max_stars_repo_head_hexsha": "86bbd44f9ad6b588253b6115c7064e91c2d0d76f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-08-14T20:45:40.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-01T18:53:36.000Z", "max_issues_repo_path": "src/xdegnome.c", "max_issues_repo_name": "masalemi/PopGenSim", "max_issues_repo_head_hexsha": "86bbd44f9ad6b588253b6115c7064e91c2d0d76f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2019-09-17T20:12:17.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T23:56:03.000Z", "max_forks_repo_path": "src/xdegnome.c", "max_forks_repo_name": "masalemi/PopGenSim", "max_forks_repo_head_hexsha": "86bbd44f9ad6b588253b6115c7064e91c2d0d76f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-27T23:28:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-27T23:28:50.000Z", "avg_line_length": 26.2807017544, "max_line_length": 128, "alphanum_fraction": 0.5847797063, "num_tokens": 1025, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.04742587637519415, "lm_q1q2_score": 0.021496340369569742}}
{"text": "///  @file rainbow-gen-userpk.c\n///  @brief A command-line tool for generating the user public keys.\n\n#include <rainbow_keypair.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <api.h>\n#include <utils.h>\n#include <string.h>\n#include <blas.h>\n\nint main(int argc, char **argv) {\n\n    printf(\"%s\\n\", CRYPTO_ALGNAME);\n\n    printf(\"msk size: %lu\\n\", CRYPTO_MASTER_SECRET_KEY_BYTES);\n    printf(\"mpk size: %lu\\n\", CRYPTO_MASTER_PUBLIC_KEY_BYTES);\n    printf(\"hash size: %d\\n\", _HASH_LEN);\n    printf(\"signature size: %d\\n\\n\", CRYPTO_BYTES);\n\n    if (4 != argc) {\n        printf(\"Usage:\\n\\n\\trainbow-gen-userpk mpk_file_name identity upk_file_name\\n\\n\");\n        return -1;\n    }\n\n\n    //malloc upk\n\n    uint8_t *_mpk = malloc(CRYPTO_MASTER_PUBLIC_KEY_BYTES);\n    FILE *fp;\n    unsigned r;\n\n    fp = fopen( argv[1] , \"r\");\n    if( NULL == fp ) {\n        printf(\"fail to open master key file.\\n\");\n        return -1;\n    }\n    r = byte_fget(fp, _mpk, CRYPTO_MASTER_PUBLIC_KEY_BYTES);\n    fclose(fp);\n    if (CRYPTO_MASTER_PUBLIC_KEY_BYTES != r) {\n        printf(\"fail to load key file.\\n\");\n        return -1;\n    }\n\n    unsigned char * _identity = malloc((_ID+1)/2);\n    r = 0;\n\n    generate_identity_hash(_identity, (unsigned char *) argv[2], strlen(argv[2]));\n    if( NULL == _identity ) {\n        printf(\"fail to create identity hash.\\n\");\n        return -1;\n    }\n    printf(\"identity hash: \");\n    for(unsigned i = 0; i<_ID; i++){\n        printf(\"%hhu \",gf16v_get_ele(_identity,i));\n    }\n    printf(\"\\n\\n\");\n\n    uint8_t *_upk = malloc(sizeof(upk_t));\n\n    //calculate usk with mpk and ID\n\n    int re = calculate_upk((upk_t *) _upk, (mpk_t *) _mpk, _identity);\n    if (0 != re) {\n        printf(\"%s generate user-public-key fails.\\n\", CRYPTO_ALGNAME);\n        return -1;\n    }\n\n    //write upk to disk\n    fp = fopen(argv[3], \"w+\");\n    if (NULL == fp) {\n        printf(\"fail to open user public key file.\\n\");\n        return -1;\n    }\n    byte_fdump(fp, CRYPTO_ALGNAME \" user-public-key\", _upk, sizeof(upk_t)); //pk speichern und beschriften\n    fclose(fp);\n\n    //free upk and rest\n\n    free(_mpk);\n    free(_identity);\n    free(_upk);\n\n    return 0;\n}", "meta": {"hexsha": "c7b6f43178044fbfc1129ebafd72007f35bc3672", "size": 2155, "ext": "c", "lang": "C", "max_stars_repo_path": "Reference_Implementation/rainbow-gen-userpk.c", "max_stars_repo_name": "mnmuser/ibs-rainbow", "max_stars_repo_head_hexsha": "f219cb091f15073c6e7f40fefbe1086f4314aae0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-21T15:43:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-21T15:43:47.000Z", "max_issues_repo_path": "Reference_Implementation/rainbow-gen-userpk.c", "max_issues_repo_name": "mnmuser/ibs-rainbow", "max_issues_repo_head_hexsha": "f219cb091f15073c6e7f40fefbe1086f4314aae0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Reference_Implementation/rainbow-gen-userpk.c", "max_forks_repo_name": "mnmuser/ibs-rainbow", "max_forks_repo_head_hexsha": "f219cb091f15073c6e7f40fefbe1086f4314aae0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-18T14:16:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-18T14:16:30.000Z", "avg_line_length": 25.3529411765, "max_line_length": 106, "alphanum_fraction": 0.5967517401, "num_tokens": 630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.488283380402856, "lm_q2_score": 0.04401864516002745, "lm_q1q2_score": 0.02149357285949202}}
{"text": "/*!\n *  Copyright (c) 2014 by Contributors\n * \\file base.h\n * \\brief definitions of base types, operators, macros functions\n *\n * \\author Bing Xu, Tianqi Chen\n */\n#ifndef MSHADOW_BASE_H_\n#define MSHADOW_BASE_H_\n#ifdef _MSC_VER\n#ifndef _CRT_SECURE_NO_WARNINGS\n#define _CRT_SECURE_NO_WARNINGS\n#endif\n#ifndef _CRT_SECURE_NO_DEPRECATE\n#define _CRT_SECURE_NO_DEPRECATE\n#endif\n#define NOMINMAX\n#endif\n#include <cmath>\n#include <cstdio>\n#include <cfloat>\n#include <climits>\n#include <algorithm>\n#include <functional>\n#include <sstream>\n#include <string>\n\n#ifdef _MSC_VER\n//! \\cond Doxygen_Suppress\ntypedef signed char int8_t;\ntypedef __int16 int16_t;\ntypedef __int32 int32_t;\ntypedef __int64 int64_t;\ntypedef unsigned char uint8_t;\ntypedef unsigned __int16 uint16_t;\ntypedef unsigned __int32 uint32_t;\ntypedef unsigned __int64 uint64_t;\n//! \\endcond\n#else\n#include <inttypes.h>\n#endif\n// macro defintiions\n/*!\n * \\brief if this macro is define to be 1,\n * mshadow should compile without any of other libs\n */\n#ifndef MSHADOW_STAND_ALONE\n#define MSHADOW_STAND_ALONE 0\n#endif\n/*! \\brief whether do padding during allocation */\n#ifndef MSHADOW_ALLOC_PAD\n#define MSHADOW_ALLOC_PAD true\n#endif\n/*!\n * \\brief\n *  x dimension of data must be bigger pad_size * ratio to be alloced padded memory,\n *  otherwise use tide allocation\n *  for example, if pad_ratio=2, GPU memory alignement size is 32,\n *  then we will only allocate padded memory if x dimension > 64\n *  set it to 0 then we will always allocate padded memory\n */\n#ifndef MSHADOW_MIN_PAD_RATIO\n  #define MSHADOW_MIN_PAD_RATIO 2\n#endif\n\n#if MSHADOW_STAND_ALONE\n  #define MSHADOW_USE_CBLAS 0\n  #define MSHADOW_USE_MKL   0\n  #define MSHADOW_USE_CUDA  0\n#endif\n\n/*!\n * \\brief force user to use GPU stream during computation\n *  error will be shot when default stream NULL is used\n */\n#ifndef MSHADOW_FORCE_STREAM\n#define MSHADOW_FORCE_STREAM 1\n#endif\n\n/*! \\brief use CBLAS for CBLAS */\n#ifndef MSHADOW_USE_CBLAS\n  #define MSHADOW_USE_CBLAS 0\n#endif\n/*! \\brief use MKL for BLAS */\n#ifndef MSHADOW_USE_MKL\n  #define MSHADOW_USE_MKL   1\n#endif\n\n/*!\n * \\brief use CUDA support, must ensure that the cuda include path is correct,\n * or directly compile using nvcc\n */\n#ifndef MSHADOW_USE_CUDA\n  #define MSHADOW_USE_CUDA   1\n#endif\n\n/*!\n * \\brief use CUDNN support, must ensure that the cudnn include path is correct\n */\n#ifndef MSHADOW_USE_CUDNN\n  #define MSHADOW_USE_CUDNN 0\n#endif\n\n/*!\n * \\brief seems CUDAARCH is deprecated in future NVCC\n * set this to 1 if you want to use CUDA version smaller than 2.0\n */\n#ifndef MSHADOW_OLD_CUDA\n#define MSHADOW_OLD_CUDA 0\n#endif\n\n/*!\n * \\brief macro to decide existence of c++11 compiler\n */\n#ifndef MSHADOW_IN_CXX11\n#define MSHADOW_IN_CXX11 (defined(__GXX_EXPERIMENTAL_CXX0X__) ||\\\n                          __cplusplus >= 201103L || defined(_MSC_VER))\n#endif\n\n/*! \\brief whether use SSE */\n#ifndef MSHADOW_USE_SSE\n  #define MSHADOW_USE_SSE 1\n#endif\n/*! \\brief whether use NVML to get dynamic info */\n#ifndef MSHADOW_USE_NVML\n  #define MSHADOW_USE_NVML 0\n#endif\n// SSE is conflict with cudacc\n#ifdef __CUDACC__\n  #undef MSHADOW_USE_SSE\n  #define MSHADOW_USE_SSE 0\n#endif\n\n#if MSHADOW_USE_CBLAS\nextern \"C\" {\n    #include <cblas.h>\n}\n#elif MSHADOW_USE_MKL\n  #include <mkl_blas.h>\n  #include <mkl_cblas.h>\n  #include <mkl_vsl.h>\n  #include <mkl_vsl_functions.h>\n#endif\n\n#if MSHADOW_USE_CUDA\n  #include <cuda.h>\n  #include <cublas_v2.h>\n  #include <curand.h>\n#endif\n\n#if MSHADOW_USE_CUDNN == 1\n  #include <cudnn.h>\n#endif\n\n#if MSHADOW_USE_NVML\n  #include <nvml.h>\n#endif\n\n// --------------------------------\n// MSHADOW_XINLINE is used for inlining template code for both CUDA and CPU code\n#ifdef MSHADOW_XINLINE\n  #error \"MSHADOW_XINLINE must not be defined\"\n#endif\n#ifdef _MSC_VER\n#define MSHADOW_FORCE_INLINE __forceinline\n#pragma warning(disable : 4068)\n#else\n#define MSHADOW_FORCE_INLINE inline __attribute__((always_inline))\n#endif\n#ifdef __CUDACC__\n  #define MSHADOW_XINLINE MSHADOW_FORCE_INLINE __device__ __host__\n#else\n  #define MSHADOW_XINLINE MSHADOW_FORCE_INLINE\n#endif\n/*! \\brief cpu force inline */\n#define MSHADOW_CINLINE MSHADOW_FORCE_INLINE\n\n#if defined(__GXX_EXPERIMENTAL_CXX0X) ||\\\n    defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L\n  #define MSHADOW_CONSTEXPR constexpr\n#else\n  #define MSHADOW_CONSTEXPR const\n#endif\n\n/*!\n * \\brief default data type for tensor string\n *  in code release, change it to default_real_t\n *  during development, change it to empty string so that missing\n *  template arguments can be detected\n */\n#ifndef MSHADOW_DEFAULT_DTYPE\n#define MSHADOW_DEFAULT_DTYPE = default_real_t\n#endif\n\n/*!\n * \\brief DMLC marco for logging\n */\n#ifndef MSHADOW_USE_GLOG\n#define MSHADOW_USE_GLOG DMLC_USE_GLOG\n#endif  // MSHADOW_USE_GLOG\n\n#if DMLC_USE_CXX11\n#define MSHADOW_THROW_EXCEPTION noexcept(false)\n#define MSHADOW_NO_EXCEPTION  noexcept(true)\n#else\n#define MSHADOW_THROW_EXCEPTION\n#define MSHADOW_NO_EXCEPTION\n#endif\n\n/*!\n * \\brief Protected cuda call in mshadow\n * \\param func Expression to call.\n * It checks for CUDA errors after invocation of the expression.\n */\n#define MSHADOW_CUDA_CALL(func)                                    \\\n  {                                                                \\\n    cudaError_t e = (func);                                        \\\n    if (e == cudaErrorCudartUnloading) {                           \\\n      throw dmlc::Error(cudaGetErrorString(e));                    \\\n    }                                                              \\\n    CHECK(e == cudaSuccess)                                        \\\n        << \"CUDA: \" << cudaGetErrorString(e);                      \\\n  }\n\n/*!\n * \\brief Run function and catch error, log unknown error.\n * \\param func Expression to call.\n */\n#define MSHADOW_CATCH_ERROR(func)                                     \\\n  {                                                                   \\\n    try {                                                             \\\n      (func);                                                         \\\n    } catch (const dmlc::Error &e) {                                    \\\n      std::string what = e.what();                                      \\\n      if (what.find(\"driver shutting down\") == std::string::npos) {     \\\n        LOG(ERROR) << \"Ignore CUDA Error \" << what;                     \\\n      }                                                                 \\\n    }                                                                   \\\n  }\n\n#include \"./half.h\"\n#include \"./half2.h\"\n#include \"./logging.h\"\n/*! \\brief namespace for mshadow */\nnamespace mshadow {\n/*! \\brief buffer size for each random number generator */\nconst unsigned kRandBufferSize = 1000000;\n/*! \\brief pi  */\nconst float kPi = 3.1415926f;\n/*! \\brief type that will be used for index */\ntypedef unsigned index_t;\n\n#ifdef _WIN32\n  /*! \\brief openmp index for windows */\n  typedef int64_t openmp_index_t;\n#else\n  /*! \\brief openmp index for linux */\n  typedef index_t openmp_index_t;\n#endif\n\n/*! \\brief float point type that will be used in default by mshadow */\ntypedef float default_real_t;\n\n/*! \\brief data type flag */\nenum TypeFlag {\n  kFloat32 = 0,\n  kFloat64 = 1,\n  kFloat16 = 2,\n  kUint8 = 3,\n  kInt32 = 4,\n  kInt8  = 5\n};\n\ntemplate<typename DType>\nstruct DataType;\n\ntemplate<>\nstruct DataType<float> {\n  static const int kFlag = kFloat32;\n  static const int kLanes = 1;\n#if MSHADOW_USE_CUDA\n#if (CUDA_VERSION >= 8000)\n  static const cudaDataType_t kCudaFlag = CUDA_R_32F;\n#endif\n#if MSHADOW_USE_CUDNN\n  static const cudnnDataType_t kCudnnFlag = CUDNN_DATA_FLOAT;\n  typedef float ScaleType;\n#endif\n#endif\n};\ntemplate<>\nstruct DataType<double> {\n  static const int kFlag = kFloat64;\n  static const int kLanes = 1;\n#if MSHADOW_USE_CUDA\n#if (CUDA_VERSION >= 8000)\n  static const cudaDataType_t kCudaFlag = CUDA_R_64F;\n#endif\n#if MSHADOW_USE_CUDNN\n  static const cudnnDataType_t kCudnnFlag = CUDNN_DATA_DOUBLE;\n  typedef double ScaleType;\n#endif\n#endif\n};\ntemplate<>\nstruct DataType<half::half_t> {\n  static const int kFlag = kFloat16;\n  static const int kLanes = 1;\n#if MSHADOW_USE_CUDA\n#if (CUDA_VERSION >= 8000)\n  static const cudaDataType_t kCudaFlag = CUDA_R_16F;\n#endif\n#if MSHADOW_USE_CUDNN\n  static const cudnnDataType_t kCudnnFlag = CUDNN_DATA_HALF;\n  typedef float ScaleType;\n#endif\n#endif\n};\ntemplate<>\nstruct DataType<half::half2_t> {\n  static const int kFlag = kFloat16;\n  static const int kLanes = 2;\n};\ntemplate<>\nstruct DataType<uint8_t> {\n  static const int kFlag = kUint8;\n  static const int kLanes = 1;\n#if MSHADOW_USE_CUDA\n#if (CUDA_VERSION >= 8000)\n  static const cudaDataType_t kCudaFlag = CUDA_R_8U;\n#endif\n#if (MSHADOW_USE_CUDNN == 1 && CUDNN_MAJOR >= 6)\n  // no uint8 in cudnn for now\n  static const cudnnDataType_t kCudnnFlag = CUDNN_DATA_INT8;\n  typedef uint8_t ScaleType;\n#endif\n#endif\n};\ntemplate<>\nstruct DataType<int8_t> {\n  static const int kFlag = kInt8;\n  static const int kLanes = 1;\n#if MSHADOW_USE_CUDA\n#if (CUDA_VERSION >= 8000)\n  static const cudaDataType_t kCudaFlag = CUDA_R_8I;\n#endif\n#if (MSHADOW_USE_CUDNN == 1 && CUDNN_MAJOR >= 6)\n  static const cudnnDataType_t kCudnnFlag = CUDNN_DATA_INT8;\n  typedef int8_t ScaleType;\n#endif\n#endif\n};\ntemplate<>\nstruct DataType<int32_t> {\n  static const int kFlag = kInt32;\n  static const int kLanes = 1;\n#if MSHADOW_USE_CUDA\n#if (CUDA_VERSION >= 8000)\n  static const cudaDataType_t kCudaFlag = CUDA_R_32I;\n#endif\n#if (MSHADOW_USE_CUDNN == 1 && CUDNN_MAJOR >= 6)\n  static const cudnnDataType_t kCudnnFlag = CUDNN_DATA_INT32;\n  typedef int32_t ScaleType;\n#endif\n#endif\n};\n\n/*! \\brief type enum value for default real type */\nconst int default_type_flag = DataType<default_real_t>::kFlag;\n\n/*! layout flag */\nenum LayoutFlag {\n  kNCHW = 0,\n  kNHWC,\n  kCHWN,\n\n  kNCW = 1 << 3,\n  kNWC,\n  kCWN,\n\n  kNCDHW = 1 << 5,\n  kNDHWC,\n  kCDHWN\n};\n\ntemplate<int layout>\nstruct LayoutType;\n\ntemplate<>\nstruct LayoutType<kNCHW> {\n  static const index_t kNdim = 4;\n#if (MSHADOW_USE_CUDA && MSHADOW_USE_CUDNN == 1 && CUDNN_MAJOR >= 4)\n  static const cudnnTensorFormat_t kCudnnFlag = CUDNN_TENSOR_NCHW;\n#else\n  static const int kCudnnFlag = -1;\n#endif\n};\n\ntemplate<>\nstruct LayoutType<kNHWC> {\n  static const index_t kNdim = 4;\n#if (MSHADOW_USE_CUDA && MSHADOW_USE_CUDNN == 1 && CUDNN_MAJOR >= 4)\n  static const cudnnTensorFormat_t kCudnnFlag = CUDNN_TENSOR_NHWC;\n#else\n  static const int kCudnnFlag = -1;\n#endif\n};\n\n/*! \\brief default layout for 4d tensor */\nconst int default_layout = kNCHW;\n\ntemplate<>\nstruct LayoutType<kNCDHW> {\n  static const index_t kNdim = 5;\n#if (MSHADOW_USE_CUDA && MSHADOW_USE_CUDNN == 1 && CUDNN_MAJOR >= 4)\n  static const cudnnTensorFormat_t kCudnnFlag = CUDNN_TENSOR_NCHW;\n#else\n  static const int kCudnnFlag = -1;\n#endif\n};\n\ntemplate<>\nstruct LayoutType<kNDHWC> {\n  static const index_t kNdim = 5;\n#if (MSHADOW_USE_CUDA && MSHADOW_USE_CUDNN == 1 && CUDNN_MAJOR >= 4)\n  static const cudnnTensorFormat_t kCudnnFlag = CUDNN_TENSOR_NHWC;\n#else\n  static const int kCudnnFlag = -1;\n#endif\n};\n\n/*! \\brief default layout for 5d tensor */\nconst int default_layout_5d = kNCDHW;\n\n/*! \\brief namespace for operators */\nnamespace op {\n// binary operator\n/*! \\brief mul operator */\nstruct mul{\n  /*! \\brief map a, b to result using defined operation */\n  template<typename DType>\n  MSHADOW_XINLINE static DType Map(DType a, DType b) {\n    return a * b;\n  }\n};\n/*! \\brief plus operator */\nstruct plus {\n  /*! \\brief map a, b to result using defined operation */\n  template<typename DType>\n  MSHADOW_XINLINE static DType Map(DType a, DType b) {\n    return a + b;\n  }\n};\n/*! \\brief minus operator */\nstruct minus {\n  /*! \\brief map a, b to result using defined operation */\n  template<typename DType>\n  MSHADOW_XINLINE static DType Map(DType a, DType b) {\n    return a - b;\n  }\n};\n/*! \\brief divide operator */\nstruct div {\n  /*! \\brief map a, b to result using defined operation */\n  template<typename DType>\n  MSHADOW_XINLINE static DType Map(DType a, DType b) {\n    return a / b;\n  }\n};\n/*! \\brief get rhs */\nstruct right {\n  /*! \\brief map a, b to result using defined operation */\n  template<typename DType>\n  MSHADOW_XINLINE static DType Map(DType a, DType b) {\n    return b;\n  }\n};\n// unary operator/ function: example\n// these operators can be defined by user,\n// in the same style as binary and unary operator\n// to use, simply write F<op::identity>( src )\n/*! \\brief identity function that maps a real number to it self */\nstruct identity{\n  /*! \\brief map a to result using defined operation */\n  template<typename DType>\n  MSHADOW_XINLINE static DType Map(DType a) {\n    return a;\n  }\n};\n}  // namespace op\n/*! \\brief namespace for savers */\nnamespace sv {\n/*! \\brief save to saver: = */\nstruct saveto {\n  /*! \\brief save b to a using save method */\n  template<typename DType>\n  MSHADOW_XINLINE static void Save(DType &a, DType b) { // NOLINT(*)\n    a = b;\n  }\n  /*! \\brief helper constant to use BLAS, alpha */\n  inline static default_real_t AlphaBLAS(void) { return 1.0f; }\n  /*! \\brief helper constant to use BLAS, beta */\n  inline static default_real_t BetaBLAS(void) { return 0.0f; }\n  /*! \\brief corresponding binary operator type */\n  typedef op::right OPType;\n};\n/*! \\brief save to saver: += */\nstruct plusto {\n  /*! \\brief save b to a using save method */\n  template<typename DType>\n  MSHADOW_XINLINE static void Save(DType &a, DType b) { // NOLINT(*)\n    a += b;\n  }\n  /*! \\brief helper constant to use BLAS, alpha */\n  inline static default_real_t AlphaBLAS(void) { return 1.0f; }\n  /*! \\brief helper constant to use BLAS, beta */\n  inline static default_real_t BetaBLAS(void) { return 1.0f; }\n  /*! \\brief corresponding binary operator type */\n  typedef op::plus OPType;\n};\n/*! \\brief minus to saver: -= */\nstruct minusto {\n  /*! \\brief save b to a using save method */\n  template<typename DType>\n  MSHADOW_XINLINE static void Save(DType &a, DType b) { // NOLINT(*)\n    a -= b;\n  }\n  /*! \\brief helper constant to use BLAS, alpha */\n  inline static default_real_t AlphaBLAS(void) { return -1.0f; }\n  /*! \\brief helper constant to use BLAS, beta */\n  inline static default_real_t BetaBLAS(void) { return 1.0f; }\n  /*! \\brief corresponding binary operator type */\n  typedef op::minus OPType;\n};\n/*! \\brief multiply to saver: *= */\nstruct multo {\n  /*! \\brief save b to a using save method */\n  template<typename DType>\n  MSHADOW_XINLINE static void Save(DType &a, DType b) { // NOLINT(*)\n    a *= b;\n  }\n  /*! \\brief corresponding binary operator type */\n  typedef op::mul OPType;\n};\n/*! \\brief divide to saver: /= */\nstruct divto {\n  /*! \\brief save b to a using save method */\n  template<typename DType>\n  MSHADOW_XINLINE static void Save(DType& a, DType b) { // NOLINT(*)\n    a /= b;\n  }\n  /*! \\brief corresponding binary operator type */\n  typedef op::div OPType;\n};\n}  // namespace sv\n/*! \\brief namespace for potential reducer operations */\nnamespace red {\nnamespace limits {\n/*!\n * \\brief minimum value of certain types\n * \\tparam DType data type\n */\ntemplate<typename DType>\nMSHADOW_XINLINE DType MinValue(void);\n/*! \\brief minimum value of float */\ntemplate<>\nMSHADOW_XINLINE float MinValue<float>(void) {\n  return -FLT_MAX;\n}\n/*! \\brief minimum value of double */\ntemplate<>\nMSHADOW_XINLINE double MinValue<double>(void) {\n  return -DBL_MAX;\n}\n/*! \\brief minimum value of half */\ntemplate<>\nMSHADOW_XINLINE half::half_t MinValue<half::half_t>(void) {\n  return MSHADOW_HALF_MIN;\n}\n/*! \\brief minimum value of uint8_t */\ntemplate<>\nMSHADOW_XINLINE uint8_t MinValue<uint8_t>(void) {\n  return 0;\n}\n/*! \\brief minimum value of int8_t */\ntemplate<>\nMSHADOW_XINLINE int8_t MinValue<int8_t>(void) {\n  return SCHAR_MIN;\n}\n/*! \\brief minimum value of int32_t */\ntemplate<>\nMSHADOW_XINLINE int MinValue<int32_t>(void) {\n  return INT_MIN;\n}\n\n/*!\n * \\brief maximum value of certain types\n * \\tparam DType data type\n */\ntemplate<typename DType>\nMSHADOW_XINLINE DType MaxValue(void);\n/*! \\brief maximum value of float */\ntemplate<>\nMSHADOW_XINLINE float MaxValue<float>(void) {\n  return FLT_MAX;\n}\n/*! \\brief maximum value of double */\ntemplate<>\nMSHADOW_XINLINE double MaxValue<double>(void) {\n  return DBL_MAX;\n}\n/*! \\brief maximum value of uint8_t */\ntemplate<>\nMSHADOW_XINLINE uint8_t MaxValue<uint8_t>(void) {\n  return UCHAR_MAX;\n}\n/*! \\brief maximum value of int8_t */\ntemplate<>\nMSHADOW_XINLINE int8_t MaxValue<int8_t>(void) {\n  return SCHAR_MAX;\n}\n/*! \\brief maximum value of int32_t */\ntemplate<>\nMSHADOW_XINLINE int MaxValue<int32_t>(void) {\n  return INT_MAX;\n}\n}  // namespace limits\n\n/*! \\brief sum reducer */\nstruct sum {\n  /*! \\brief do reduction into dst */\n  template<typename DType>\n  MSHADOW_XINLINE static void Reduce(volatile DType& dst,  volatile DType src) { // NOLINT(*)\n    dst += src;\n  }\n  /*!\n   *\\brief calculate gradient of redres with respect to redsrc,\n   * redres: reduced result, redsrc: one of reduction element\n   */\n  template<typename DType>\n  MSHADOW_XINLINE static DType PartialGrad(DType redres, DType redsrc) {\n    return 1;\n  }\n  /*!\n   *\\brief set the initial value during reduction\n   */\n  template<typename DType>\n  MSHADOW_XINLINE static void SetInitValue(DType &initv) { // NOLINT(*)\n    initv = 0;\n  }\n};\n/*! \\brief maximum reducer */\nstruct maximum {\n  /*! \\brief do reduction into dst */\n  template<typename DType>\n  MSHADOW_XINLINE static void Reduce(volatile DType& dst,  volatile DType src) { // NOLINT(*)\n    using namespace std;\n#ifdef __CUDACC__\n    dst = ::max(dst, src);\n#else\n    dst = max(dst, src);\n#endif  // __CUDACC__\n  }\n  /*!\n   * \\brief calculate gradient of redres with respect to redsrc,\n   * redres: reduced result, redsrc: one of reduction element\n   */\n  template<typename DType>\n  MSHADOW_XINLINE static DType PartialGrad(DType redres, DType redsrc) {\n    return redres == redsrc ? 1: 0;\n  }\n  /*!\n   *\\brief set the initial value during reduction\n   */\n  template<typename DType>\n  MSHADOW_XINLINE static void SetInitValue(DType &initv) { // NOLINT(*)\n    initv = limits::MinValue<DType>();\n  }\n};\n/*! \\brief minimum reducer */\nstruct minimum {\n  /*! \\brief do reduction into dst */\n  template<typename DType>\n  MSHADOW_XINLINE static void Reduce(volatile DType& dst,  volatile DType src) { // NOLINT(*)\n    using namespace std;\n#ifdef __CUDACC__\n    dst = ::min(dst, src);\n#else\n    dst = min(dst, src);\n#endif  // __CUDACC__\n  }\n  /*!\n   * \\brief calculate gradient of redres with respect to redsrc,\n   * redres: reduced result, redsrc: one of reduction element\n   */\n  template<typename DType>\n  MSHADOW_XINLINE static DType PartialGrad(DType redres, DType redsrc) {\n    return redres == redsrc ? 1: 0;\n  }\n  /*!\n   *\\brief set the initial value during reduction\n   */\n  template<typename DType>\n  MSHADOW_XINLINE static void SetInitValue(DType &initv) { // NOLINT(*)\n    initv = -limits::MinValue<DType>();\n  }\n};\n}  // namespace red\n\n#define MSHADOW_TYPE_SWITCH(type, DType, ...)       \\\n  switch (type) {                                   \\\n  case mshadow::kFloat32:                           \\\n    {                                               \\\n      typedef float DType;                          \\\n      {__VA_ARGS__}                                 \\\n    }                                               \\\n    break;                                          \\\n  case mshadow::kFloat64:                           \\\n    {                                               \\\n      typedef double DType;                         \\\n      {__VA_ARGS__}                                 \\\n    }                                               \\\n    break;                                          \\\n  case mshadow::kFloat16:                           \\\n    {                                               \\\n      typedef mshadow::half::half_t DType;          \\\n      {__VA_ARGS__}                                 \\\n    }                                               \\\n    break;                                          \\\n  case mshadow::kUint8:                             \\\n    {                                               \\\n      typedef uint8_t DType;                        \\\n      {__VA_ARGS__}                                 \\\n    }                                               \\\n    break;                                          \\\n  case mshadow::kInt8:                              \\\n    {                                               \\\n      typedef int8_t DType;                         \\\n      {__VA_ARGS__}                                 \\\n    }                                               \\\n    break;                                          \\\n  case mshadow::kInt32:                             \\\n    {                                               \\\n      typedef int32_t DType;                        \\\n      {__VA_ARGS__}                                 \\\n    }                                               \\\n    break;                                          \\\n  default:                                          \\\n    LOG(FATAL) << \"Unknown type enum \" << type;     \\\n  }\n\n#define MSHADOW_TYPE_SWITCH_WITH_HALF2(type, DType, ...)  \\\n  switch (type) {                                         \\\n  case mshadow::kFloat32:                                 \\\n    {                                                     \\\n      typedef float DType;                                \\\n      {__VA_ARGS__}                                       \\\n    }                                                     \\\n    break;                                                \\\n  case mshadow::kFloat64:                                 \\\n    {                                                     \\\n      typedef double DType;                               \\\n      {__VA_ARGS__}                                       \\\n    }                                                     \\\n    break;                                                \\\n  case mshadow::kFloat16:                                 \\\n    {                                                     \\\n      typedef mshadow::half::half2_t DType;               \\\n      {__VA_ARGS__}                                       \\\n    }                                                     \\\n    break;                                                \\\n  case mshadow::kUint8:                                   \\\n    {                                                     \\\n      typedef uint8_t DType;                              \\\n      {__VA_ARGS__}                                       \\\n    }                                                     \\\n    break;                                                \\\n  case mshadow::kInt32:                                   \\\n    {                                                     \\\n      typedef int32_t DType;                              \\\n      {__VA_ARGS__}                                       \\\n    }                                                     \\\n    break;                                                \\\n  default:                                                \\\n    LOG(FATAL) << \"Unknown type enum \" << type;           \\\n  }\n\n#define MSHADOW_REAL_TYPE_SWITCH(type, DType, ...)  \\\n  switch (type) {                                   \\\n  case mshadow::kFloat32:                           \\\n    {                                               \\\n      typedef float DType;                          \\\n      {__VA_ARGS__}                                 \\\n    }                                               \\\n    break;                                          \\\n  case mshadow::kFloat64:                           \\\n    {                                               \\\n      typedef double DType;                         \\\n      {__VA_ARGS__}                                 \\\n    }                                               \\\n    break;                                          \\\n  case mshadow::kFloat16:                           \\\n    {                                               \\\n      typedef mshadow::half::half_t DType;          \\\n      {__VA_ARGS__}                                 \\\n    }                                               \\\n    break;                                          \\\n  case mshadow::kUint8:                             \\\n    LOG(FATAL) << \"This operation only support \"    \\\n                  \"floating point types not uint8\"; \\\n    break;                                          \\\n  case mshadow::kInt8:                              \\\n    LOG(FATAL) << \"This operation only support \"    \\\n                  \"floating point types not int8\";  \\\n    break;                                          \\\n  case mshadow::kInt32:                             \\\n    LOG(FATAL) << \"This operation only support \"    \\\n                  \"floating point types, not int32\";\\\n    break;                                          \\\n  default:                                          \\\n    LOG(FATAL) << \"Unknown type enum \" << type;     \\\n  }\n\n#define MSHADOW_REAL_TYPE_SWITCH_EX(type$, DType$, DLargeType$, ...)  \\\n  switch (type$) {                                  \\\n  case mshadow::kFloat32:                           \\\n    {                                               \\\n      typedef float DType$;                         \\\n      typedef float DLargeType$;                    \\\n      {__VA_ARGS__}                                 \\\n    }                                               \\\n    break;                                          \\\n  case mshadow::kFloat64:                           \\\n    {                                               \\\n      typedef double DType$;                        \\\n      typedef double DLargeType$;                   \\\n      {__VA_ARGS__}                                 \\\n    }                                               \\\n    break;                                          \\\n  case mshadow::kFloat16:                           \\\n    {                                               \\\n      typedef mshadow::half::half_t DType$;         \\\n      typedef float DLargeType$;                    \\\n      {__VA_ARGS__}                                 \\\n    }                                               \\\n    break;                                          \\\n  case mshadow::kUint8:                             \\\n    LOG(FATAL) << \"This operation only support \"    \\\n                  \"floating point types not uint8\"; \\\n    break;                                          \\\n  case mshadow::kInt8:                              \\\n    LOG(FATAL) << \"This operation only support \"    \\\n                  \"floating point types not int8\";  \\\n    break;                                          \\\n  case mshadow::kInt32:                             \\\n    LOG(FATAL) << \"This operation only support \"    \\\n                  \"floating point types, not int32\";\\\n    break;                                          \\\n  default:                                          \\\n    LOG(FATAL) << \"Unknown type enum \" << type$;    \\\n  }\n\n#define MSHADOW_LAYOUT_SWITCH(layout, Layout, ...)  \\\n  switch (layout) {                                 \\\n  case mshadow::kNCHW:                              \\\n    {                                               \\\n      const int Layout = kNCHW;                     \\\n      {__VA_ARGS__}                                 \\\n    }                                               \\\n    break;                                          \\\n  case mshadow::kNHWC:                              \\\n    {                                               \\\n      const int Layout = kNHWC;                     \\\n      {__VA_ARGS__}                                 \\\n    }                                               \\\n    break;                                          \\\n  case mshadow::kNCDHW:                             \\\n    {                                               \\\n      const int Layout = kNCDHW;                    \\\n      {__VA_ARGS__}                                 \\\n    }                                               \\\n    break;                                          \\\n  case mshadow::kNDHWC:                             \\\n    {                                               \\\n      const int Layout = kNDHWC;                    \\\n      {__VA_ARGS__}                                 \\\n    }                                               \\\n    break;                                          \\\n  default:                                          \\\n    LOG(FATAL) << \"Unknown layout enum \" << layout; \\\n  }\n\n/*! \\brief get data type size from type enum */\ninline size_t mshadow_sizeof(int type) {\n  int size = 0;\n  MSHADOW_TYPE_SWITCH(type, DType, size = sizeof(DType););\n  return size;\n}\n\n}  // namespace mshadow\n#endif  // MSHADOW_BASE_H_\n", "meta": {"hexsha": "d633b42900fc929a620ae474c78fcd1807cbbf35", "size": 28646, "ext": "h", "lang": "C", "max_stars_repo_path": "mshadow/mshadow/base.h", "max_stars_repo_name": "withinnoitatpmet/mxnetsource", "max_stars_repo_head_hexsha": "fab56d8efec12bd2af2b3ab8a8a26c733a83ffa7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mshadow/mshadow/base.h", "max_issues_repo_name": "withinnoitatpmet/mxnetsource", "max_issues_repo_head_hexsha": "fab56d8efec12bd2af2b3ab8a8a26c733a83ffa7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mshadow/mshadow/base.h", "max_forks_repo_name": "withinnoitatpmet/mxnetsource", "max_forks_repo_head_hexsha": "fab56d8efec12bd2af2b3ab8a8a26c733a83ffa7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7583148559, "max_line_length": 93, "alphanum_fraction": 0.527368568, "num_tokens": 6738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.341582499438317, "lm_q2_score": 0.06278920684328233, "lm_q1q2_score": 0.021447694211277856}}
{"text": "#ifndef neo_hookean_h\n#define neo_hookean_h\n\n#include <petsc.h>\n#include \"../include/structs.h\"\n\n#ifndef PHYSICS_STRUCT_NH\n#define PHYSICS_STRUCT_NH\ntypedef struct Physics_NH_ *Physics_NH;\nstruct Physics_NH_ {\n  CeedScalar   nu;      // Poisson's ratio\n  CeedScalar   E;       // Young's Modulus\n};\n#endif // PHYSICS_STRUCT_NH\n\n// Create context object\nPetscErrorCode PhysicsContext_NH(MPI_Comm comm, Ceed ceed, Units *units,\n                                 CeedQFunctionContext *ctx);\nPetscErrorCode PhysicsSmootherContext_NH(MPI_Comm comm, Ceed ceed,\n    CeedQFunctionContext ctx, CeedQFunctionContext *ctx_smoother);\n\n// Process physics options\nPetscErrorCode ProcessPhysics_NH(MPI_Comm comm, Physics_NH phys, Units units);\n\n#endif // neo_hookean_h\n", "meta": {"hexsha": "668a964359d5000f90061e059242885b771ce407", "size": 753, "ext": "h", "lang": "C", "max_stars_repo_path": "examples/solids/problems/neo-hookean.h", "max_stars_repo_name": "AdelekeBankole/libCEED", "max_stars_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 123.0, "max_stars_repo_stars_event_min_datetime": "2018-01-29T02:04:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T18:13:48.000Z", "max_issues_repo_path": "examples/solids/problems/neo-hookean.h", "max_issues_repo_name": "AdelekeBankole/libCEED", "max_issues_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 781.0, "max_issues_repo_issues_event_min_datetime": "2017-12-22T17:20:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T21:34:34.000Z", "max_forks_repo_path": "examples/solids/problems/neo-hookean.h", "max_forks_repo_name": "AdelekeBankole/libCEED", "max_forks_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2017-12-27T22:35:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:02:07.000Z", "avg_line_length": 28.9615384615, "max_line_length": 78, "alphanum_fraction": 0.7490039841, "num_tokens": 200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.04535257829625851, "lm_q1q2_score": 0.021437414382775858}}
{"text": "/* histogram/get.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_histogram.h>\n\n#include \"find.c\"\n\ndouble\ngsl_histogram_get (const gsl_histogram * h, size_t i)\n{\n  const size_t n = h->n;\n\n  if (i >= n)\n    {\n      GSL_ERROR_VAL (\"index lies outside valid range of 0 .. n - 1\",\n                        GSL_EDOM, 0);\n    }\n\n  return h->bin[i];\n}\n\nint\ngsl_histogram_get_range (const gsl_histogram * h, size_t i,\n                         double *lower, double *upper)\n{\n  const size_t n = h->n;\n\n  if (i >= n)\n    {\n      GSL_ERROR (\"index lies outside valid range of 0 .. n - 1\", GSL_EDOM);\n    }\n\n  *lower = h->range[i];\n  *upper = h->range[i + 1];\n\n  return GSL_SUCCESS;\n}\n\nint\ngsl_histogram_find (const gsl_histogram * h,\n                    const double x, size_t * i)\n{\n  int status = find (h->n, h->range, x, i);\n\n  if (status)\n    {\n      GSL_ERROR (\"x not found in range of h\", GSL_EDOM);\n    }\n\n  return GSL_SUCCESS;\n}\n", "meta": {"hexsha": "6e832a55d24a57bd16afff3a08cc83895e61d40b", "size": 1734, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/histogram/get.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/histogram/get.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/histogram/get.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 24.7714285714, "max_line_length": 81, "alphanum_fraction": 0.6470588235, "num_tokens": 475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.04336580200934005, "lm_q1q2_score": 0.02134413324501421}}
{"text": "/**\n * author: Jochen K\"upper\n * created: Jan 2002\n * file: pygsl/src/statistics/longmodule.c\n * $Id: longmodule.c,v 1.10 2004/03/24 08:40:45 schnizer Exp $\n *\n * optional usage of Numeric module, available at http://numpy.sourceforge.net\n *\"\n */\n\n\n#include <Python.h>\n#include <pygsl/error_helpers.h>\n#include <pygsl/block_helpers.h>\n#include <gsl/gsl_statistics.h>\n\n\n/* include real functions for different data-types */\n\n#define STATMOD_APPEND_PY_TYPE(X) X ## Int\n#define STATMOD_APPEND_PYC_TYPE(X) X ## LONG\n#define STATMOD_FUNC_EXT(X, Y) X ## _long ## Y\n#define STATMOD_PY_AS_C PyInt_AsLong\n#define STATMOD_C_TYPE long int\n#include \"functions.c\"\n\n\n\n/* initialization */\nPyGSL_STATISTICS_INIT(long, \"long\")\n\n\n/*\n * Local Variables:\n * mode: c\n * c-file-style: \"Stroustrup\"\n * End:\n */\n", "meta": {"hexsha": "8c2a3ed02e2eea51367675fb23fcaa930b2a1d72", "size": 789, "ext": "c", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/src/statistics/longmodule.c", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/src/statistics/longmodule.c", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/src/statistics/longmodule.c", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 20.2307692308, "max_line_length": 78, "alphanum_fraction": 0.7122940431, "num_tokens": 224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.04401865425233781, "lm_q1q2_score": 0.021321759456506825}}
{"text": "/* ******************************************************************************\n *\n *\n * This program and the accompanying materials are made available under the\n * terms of the Apache License, Version 2.0 which is available at\n * https://www.apache.org/licenses/LICENSE-2.0.\n *\n *  See the NOTICE file distributed with this work for additional\n *  information regarding copyright ownership.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations\n * under the License.\n *\n * SPDX-License-Identifier: Apache-2.0\n ******************************************************************************/\n\n//\n// Created by agibsonccc on 1/26/16.\n//\n\n#ifndef NATIVEOPERATIONS_CBLAS_H\n#define NATIVEOPERATIONS_CBLAS_H\n\n#ifndef __STANDALONE_BUILD__\n#include \"config.h\"\n#endif\n\n#ifdef __MKL_CBLAS_H__\n// CBLAS from MKL is already included\n#define CBLAS_H\n#endif\n\n#ifdef HAVE_OPENBLAS\n// include CBLAS from OpenBLAS\n#ifdef __GNUC__\n#include_next <cblas.h>\n#else\n#include <cblas.h>\n#endif\n#define CBLAS_H\n#endif\n\n#ifndef CBLAS_H\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n#ifndef CBLAS_ENUM_DEFINED_H\n#define CBLAS_ENUM_DEFINED_H\nenum CBLAS_ORDER { CblasRowMajor = 101, CblasColMajor = 102 };\nenum CBLAS_TRANSPOSE { CblasNoTrans = 111, CblasTrans = 112, CblasConjTrans = 113, AtlasConj = 114 };\nenum CBLAS_UPLO { CblasUpper = 121, CblasLower = 122 };\nenum CBLAS_DIAG { CblasNonUnit = 131, CblasUnit = 132 };\nenum CBLAS_SIDE { CblasLeft = 141, CblasRight = 142 };\n#endif\n\n#ifndef CBLAS_ENUM_ONLY\n#define CBLAS_H\n#define CBLAS_INDEX int\n\nint cblas_errprn(int ierr, int info, char *form, ...);\nvoid cblas_xerbla(int p, char *rout, char *form, ...);\n\n#ifdef __MKL\nvoid MKL_Set_Num_Threads(int num);\nint MKL_Domain_Set_Num_Threads(int num, int domain);\nint MKL_Set_Num_Threads_Local(int num);\n#elif __OPENBLAS\nvoid openblas_set_num_threads(int num);\n#else\n// do nothing\n#endif\n\n/*\n * ===========================================================================\n * Prototypes for level 1 BLAS functions (complex are recast as routines)\n * ===========================================================================\n */\nfloat cblas_sdsdot(int N, float alpha, float *X, int incX, float *Y, int incY);\ndouble cblas_dsdot(int N, float *X, int incX, float *Y, int incY);\nfloat cblas_sdot(int N, float *X, int incX, float *Y, int incY);\ndouble cblas_ddot(int N, double *X, int incX, double *Y, int incY);\n/*\n * Functions having prefixes Z and C only\n */\nvoid cblas_cdotu_sub(int N, void *X, int incX, void *Y, int incY, void *dotu);\nvoid cblas_cdotc_sub(int N, void *X, int incX, void *Y, int incY, void *dotc);\n\nvoid cblas_zdotu_sub(int N, void *X, int incX, void *Y, int incY, void *dotu);\nvoid cblas_zdotc_sub(int N, void *X, int incX, void *Y, int incY, void *dotc);\n\n/*\n * Functions having prefixes S D SC DZ\n */\nfloat cblas_snrm2(int N, float *X, int incX);\nfloat cblas_sasum(int N, float *X, int incX);\n\ndouble cblas_dnrm2(int N, double *X, int incX);\ndouble cblas_dasum(int N, double *X, int incX);\n\nfloat cblas_scnrm2(int N, void *X, int incX);\nfloat cblas_scasum(int N, void *X, int incX);\n\ndouble cblas_dznrm2(int N, void *X, int incX);\ndouble cblas_dzasum(int N, void *X, int incX);\n\n/*\n * Functions having standard 4 prefixes (S D C Z)\n */\nCBLAS_INDEX cblas_isamax(int N, float *X, int incX);\nCBLAS_INDEX cblas_idamax(int N, double *X, int incX);\nCBLAS_INDEX cblas_icamax(int N, void *X, int incX);\nCBLAS_INDEX cblas_izamax(int N, void *X, int incX);\n\n/*\n * ===========================================================================\n * Prototypes for level 1 BLAS routines\n * ===========================================================================\n */\n\n/*\n * Routines with standard 4 prefixes (s, d, c, z)\n */\nvoid cblas_sswap(int N, float *X, int incX, float *Y, int incY);\nvoid cblas_scopy(int N, float *X, int incX, float *Y, int incY);\nvoid cblas_saxpy(int N, float alpha, float *X, int incX, float *Y, int incY);\nvoid catlas_saxpby(int N, float alpha, float *X, int incX, float beta, float *Y, int incY);\nvoid catlas_sset(int N, float alpha, float *X, int incX);\n\nvoid cblas_dswap(int N, double *X, int incX, double *Y, int incY);\nvoid cblas_dcopy(int N, double *X, int incX, double *Y, int incY);\nvoid cblas_daxpy(int N, double alpha, double *X, int incX, double *Y, int incY);\nvoid catlas_daxpby(int N, double alpha, double *X, int incX, double beta, double *Y, int incY);\nvoid catlas_dset(int N, double alpha, double *X, int incX);\n\nvoid cblas_cswap(int N, void *X, int incX, void *Y, int incY);\nvoid cblas_ccopy(int N, void *X, int incX, void *Y, int incY);\nvoid cblas_caxpy(int N, void *alpha, void *X, int incX, void *Y, int incY);\nvoid catlas_caxpby(int N, void *alpha, void *X, int incX, void *beta, void *Y, int incY);\nvoid catlas_cset(int N, void *alpha, void *X, int incX);\n\nvoid cblas_zswap(int N, void *X, int incX, void *Y, int incY);\nvoid cblas_zcopy(int N, void *X, int incX, void *Y, int incY);\nvoid cblas_zaxpy(int N, void *alpha, void *X, int incX, void *Y, int incY);\nvoid catlas_zaxpby(int N, void *alpha, void *X, int incX, void *beta, void *Y, int incY);\nvoid catlas_zset(int N, void *alpha, void *X, int incX);\n\n/*\n * Routines with S and D prefix only\n */\nvoid cblas_srotg(float *a, float *b, float *c, float *s);\nvoid cblas_srotmg(float *d1, float *d2, float *b1, float b2, float *P);\nvoid cblas_srot(int N, float *X, int incX, float *Y, int incY, float c, float s);\nvoid cblas_srotm(int N, float *X, int incX, float *Y, int incY, float *P);\n\nvoid cblas_drotg(double *a, double *b, double *c, double *s);\nvoid cblas_drotmg(double *d1, double *d2, double *b1, double b2, double *P);\nvoid cblas_drot(int N, double *X, int incX, double *Y, int incY, double c, double s);\nvoid cblas_drotm(int N, double *X, int incX, double *Y, int incY, double *P);\n\n/*\n * Routines with S D C Z CS and ZD prefixes\n */\nvoid cblas_sscal(int N, float alpha, float *X, int incX);\nvoid cblas_dscal(int N, double alpha, double *X, int incX);\nvoid cblas_cscal(int N, void *alpha, void *X, int incX);\nvoid cblas_zscal(int N, void *alpha, void *X, int incX);\nvoid cblas_csscal(int N, float alpha, void *X, int incX);\nvoid cblas_zdscal(int N, double alpha, void *X, int incX);\n\n/*\n * Extra reference routines provided by ATLAS, but not mandated by the standard\n */\nvoid cblas_crotg(void *a, void *b, void *c, void *s);\nvoid cblas_zrotg(void *a, void *b, void *c, void *s);\nvoid cblas_csrot(int N, void *X, int incX, void *Y, int incY, float c, float s);\nvoid cblas_zdrot(int N, void *X, int incX, void *Y, int incY, double c, double s);\n\n/*\n * ===========================================================================\n * Prototypes for level 2 BLAS\n * ===========================================================================\n */\n\n/*\n * Routines with standard 4 prefixes (S, D, C, Z)\n */\nvoid cblas_sgemv(enum CBLAS_ORDER Order, enum CBLAS_TRANSPOSE TransA, int M, int N, float alpha, float *A, int lda,\n                 float *X, int incX, float beta, float *Y, int incY);\nvoid cblas_sgbmv(enum CBLAS_ORDER Order, enum CBLAS_TRANSPOSE TransA, int M, int N, int KL, int KU, float alpha,\n                 float *A, int lda, float *X, int incX, float beta, float *Y, int incY);\nvoid cblas_strmv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,\n                 float *A, int lda, float *X, int incX);\nvoid cblas_stbmv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,\n                 int K, float *A, int lda, float *X, int incX);\nvoid cblas_stpmv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,\n                 float *Ap, float *X, int incX);\nvoid cblas_strsv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,\n                 float *A, int lda, float *X, int incX);\nvoid cblas_stbsv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,\n                 int K, float *A, int lda, float *X, int incX);\nvoid cblas_stpsv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,\n                 float *Ap, float *X, int incX);\n\nvoid cblas_dgemv(enum CBLAS_ORDER Order, enum CBLAS_TRANSPOSE TransA, int M, int N, double alpha, double *A, int lda,\n                 double *X, int incX, double beta, double *Y, int incY);\nvoid cblas_dgbmv(enum CBLAS_ORDER Order, enum CBLAS_TRANSPOSE TransA, int M, int N, int KL, int KU, double alpha,\n                 double *A, int lda, double *X, int incX, double beta, double *Y, int incY);\nvoid cblas_dtrmv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,\n                 double *A, int lda, double *X, int incX);\nvoid cblas_dtbmv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,\n                 int K, double *A, int lda, double *X, int incX);\nvoid cblas_dtpmv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,\n                 double *Ap, double *X, int incX);\nvoid cblas_dtrsv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,\n                 double *A, int lda, double *X, int incX);\nvoid cblas_dtbsv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,\n                 int K, double *A, int lda, double *X, int incX);\nvoid cblas_dtpsv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,\n                 double *Ap, double *X, int incX);\n\nvoid cblas_cgemv(enum CBLAS_ORDER Order, enum CBLAS_TRANSPOSE TransA, int M, int N, void *alpha, void *A, int lda,\n                 void *X, int incX, void *beta, void *Y, int incY);\nvoid cblas_cgbmv(enum CBLAS_ORDER Order, enum CBLAS_TRANSPOSE TransA, int M, int N, int KL, int KU, void *alpha,\n                 void *A, int lda, void *X, int incX, void *beta, void *Y, int incY);\nvoid cblas_ctrmv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,\n                 void *A, int lda, void *X, int incX);\nvoid cblas_ctbmv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,\n                 int K, void *A, int lda, void *X, int incX);\nvoid cblas_ctpmv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,\n                 void *Ap, void *X, int incX);\nvoid cblas_ctrsv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,\n                 void *A, int lda, void *X, int incX);\nvoid cblas_ctbsv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,\n                 int K, void *A, int lda, void *X, int incX);\nvoid cblas_ctpsv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,\n                 void *Ap, void *X, int incX);\n\nvoid cblas_zgemv(enum CBLAS_ORDER Order, enum CBLAS_TRANSPOSE TransA, int M, int N, void *alpha, void *A, int lda,\n                 void *X, int incX, void *beta, void *Y, int incY);\nvoid cblas_zgbmv(enum CBLAS_ORDER Order, enum CBLAS_TRANSPOSE TransA, int M, int N, int KL, int KU, void *alpha,\n                 void *A, int lda, void *X, int incX, void *beta, void *Y, int incY);\nvoid cblas_ztrmv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,\n                 void *A, int lda, void *X, int incX);\nvoid cblas_ztbmv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,\n                 int K, void *A, int lda, void *X, int incX);\nvoid cblas_ztpmv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,\n                 void *Ap, void *X, int incX);\nvoid cblas_ztrsv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,\n                 void *A, int lda, void *X, int incX);\nvoid cblas_ztbsv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,\n                 int K, void *A, int lda, void *X, int incX);\nvoid cblas_ztpsv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,\n                 void *Ap, void *X, int incX);\n\n/*\n * Routines with S and D prefixes only\n */\nvoid cblas_ssymv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, float alpha, float *A, int lda, float *X,\n                 int incX, float beta, float *Y, int incY);\nvoid cblas_ssbmv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, int K, float alpha, float *A, int lda, float *X,\n                 int incX, float beta, float *Y, int incY);\nvoid cblas_sspmv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, float alpha, float *Ap, float *X, int incX,\n                 float beta, float *Y, int incY);\nvoid cblas_sger(enum CBLAS_ORDER Order, int M, int N, float alpha, float *X, int incX, float *Y, int incY, float *A,\n                int lda);\nvoid cblas_ssyr(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, float alpha, float *X, int incX, float *A,\n                int lda);\nvoid cblas_sspr(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, float alpha, float *X, int incX, float *Ap);\nvoid cblas_ssyr2(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, float alpha, float *X, int incX, float *Y,\n                 int incY, float *A, int lda);\nvoid cblas_sspr2(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, float alpha, float *X, int incX, float *Y,\n                 int incY, float *A);\n\nvoid cblas_dsymv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, double alpha, double *A, int lda, double *X,\n                 int incX, double beta, double *Y, int incY);\nvoid cblas_dsbmv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, int K, double alpha, double *A, int lda,\n                 double *X, int incX, double beta, double *Y, int incY);\nvoid cblas_dspmv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, double alpha, double *Ap, double *X, int incX,\n                 double beta, double *Y, int incY);\nvoid cblas_dger(enum CBLAS_ORDER Order, int M, int N, double alpha, double *X, int incX, double *Y, int incY, double *A,\n                int lda);\nvoid cblas_dsyr(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, double alpha, double *X, int incX, double *A,\n                int lda);\nvoid cblas_dspr(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, double alpha, double *X, int incX, double *Ap);\nvoid cblas_dsyr2(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, double alpha, double *X, int incX, double *Y,\n                 int incY, double *A, int lda);\nvoid cblas_dspr2(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, double alpha, double *X, int incX, double *Y,\n                 int incY, double *A);\n\n/*\n * Routines with C and Z prefixes only\n */\nvoid cblas_chemv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, void *alpha, void *A, int lda, void *X, int incX,\n                 void *beta, void *Y, int incY);\nvoid cblas_chbmv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, int K, void *alpha, void *A, int lda, void *X,\n                 int incX, void *beta, void *Y, int incY);\nvoid cblas_chpmv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, void *alpha, void *Ap, void *X, int incX,\n                 void *beta, void *Y, int incY);\nvoid cblas_cgeru(enum CBLAS_ORDER Order, int M, int N, void *alpha, void *X, int incX, void *Y, int incY, void *A,\n                 int lda);\nvoid cblas_cgerc(enum CBLAS_ORDER Order, int M, int N, void *alpha, void *X, int incX, void *Y, int incY, void *A,\n                 int lda);\nvoid cblas_cher(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, float alpha, void *X, int incX, void *A, int lda);\nvoid cblas_chpr(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, float alpha, void *X, int incX, void *A);\nvoid cblas_cher2(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, void *alpha, void *X, int incX, void *Y, int incY,\n                 void *A, int lda);\nvoid cblas_chpr2(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, void *alpha, void *X, int incX, void *Y, int incY,\n                 void *Ap);\n\nvoid cblas_zhemv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, void *alpha, void *A, int lda, void *X, int incX,\n                 void *beta, void *Y, int incY);\nvoid cblas_zhbmv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, int K, void *alpha, void *A, int lda, void *X,\n                 int incX, void *beta, void *Y, int incY);\nvoid cblas_zhpmv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, void *alpha, void *Ap, void *X, int incX,\n                 void *beta, void *Y, int incY);\nvoid cblas_zgeru(enum CBLAS_ORDER Order, int M, int N, void *alpha, void *X, int incX, void *Y, int incY, void *A,\n                 int lda);\nvoid cblas_zgerc(enum CBLAS_ORDER Order, int M, int N, void *alpha, void *X, int incX, void *Y, int incY, void *A,\n                 int lda);\nvoid cblas_zher(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, double alpha, void *X, int incX, void *A, int lda);\nvoid cblas_zhpr(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, double alpha, void *X, int incX, void *A);\nvoid cblas_zher2(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, void *alpha, void *X, int incX, void *Y, int incY,\n                 void *A, int lda);\nvoid cblas_zhpr2(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, void *alpha, void *X, int incX, void *Y, int incY,\n                 void *Ap);\n\n/*\n * ===========================================================================\n * Prototypes for level 3 BLAS\n * ===========================================================================\n */\n\n/*\n * Routines with standard 4 prefixes (S, D, C, Z)\n */\nvoid cblas_sgemm(enum CBLAS_ORDER Order, enum CBLAS_TRANSPOSE TransA, enum CBLAS_TRANSPOSE TransB, int M, int N, int K,\n                 float alpha, float *A, int lda, float *B, int ldb, float beta, float *C, int ldc);\nvoid cblas_ssymm(enum CBLAS_ORDER Order, enum CBLAS_SIDE Side, enum CBLAS_UPLO Uplo, int M, int N, float alpha,\n                 float *A, int lda, float *B, int ldb, float beta, float *C, int ldc);\nvoid cblas_ssyrk(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE Trans, int N, int K, float alpha,\n                 float *A, int lda, float beta, float *C, int ldc);\nvoid cblas_ssyr2k(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE Trans, int N, int K, float alpha,\n                  float *A, int lda, float *B, int ldb, float beta, float *C, int ldc);\nvoid cblas_strmm(enum CBLAS_ORDER Order, enum CBLAS_SIDE Side, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA,\n                 enum CBLAS_DIAG Diag, int M, int N, float alpha, float *A, int lda, float *B, int ldb);\nvoid cblas_strsm(enum CBLAS_ORDER Order, enum CBLAS_SIDE Side, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA,\n                 enum CBLAS_DIAG Diag, int M, int N, float alpha, float *A, int lda, float *B, int ldb);\n\nvoid cblas_dgemm(enum CBLAS_ORDER Order, enum CBLAS_TRANSPOSE TransA, enum CBLAS_TRANSPOSE TransB, int M, int N, int K,\n                 double alpha, double *A, int lda, double *B, int ldb, double beta, double *C, int ldc);\nvoid cblas_dsymm(enum CBLAS_ORDER Order, enum CBLAS_SIDE Side, enum CBLAS_UPLO Uplo, int M, int N, double alpha,\n                 double *A, int lda, double *B, int ldb, double beta, double *C, int ldc);\nvoid cblas_dsyrk(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE Trans, int N, int K, double alpha,\n                 double *A, int lda, double beta, double *C, int ldc);\nvoid cblas_dsyr2k(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE Trans, int N, int K, double alpha,\n                  double *A, int lda, double *B, int ldb, double beta, double *C, int ldc);\nvoid cblas_dtrmm(enum CBLAS_ORDER Order, enum CBLAS_SIDE Side, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA,\n                 enum CBLAS_DIAG Diag, int M, int N, double alpha, double *A, int lda, double *B, int ldb);\nvoid cblas_dtrsm(enum CBLAS_ORDER Order, enum CBLAS_SIDE Side, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA,\n                 enum CBLAS_DIAG Diag, int M, int N, double alpha, double *A, int lda, double *B, int ldb);\n\nvoid cblas_cgemm(enum CBLAS_ORDER Order, enum CBLAS_TRANSPOSE TransA, enum CBLAS_TRANSPOSE TransB, int M, int N, int K,\n                 void *alpha, void *A, int lda, void *B, int ldb, void *beta, void *C, int ldc);\nvoid cblas_csymm(enum CBLAS_ORDER Order, enum CBLAS_SIDE Side, enum CBLAS_UPLO Uplo, int M, int N, void *alpha, void *A,\n                 int lda, void *B, int ldb, void *beta, void *C, int ldc);\nvoid cblas_csyrk(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE Trans, int N, int K, void *alpha,\n                 void *A, int lda, void *beta, void *C, int ldc);\nvoid cblas_csyr2k(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE Trans, int N, int K, void *alpha,\n                  void *A, int lda, void *B, int ldb, void *beta, void *C, int ldc);\nvoid cblas_ctrmm(enum CBLAS_ORDER Order, enum CBLAS_SIDE Side, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA,\n                 enum CBLAS_DIAG Diag, int M, int N, void *alpha, void *A, int lda, void *B, int ldb);\nvoid cblas_ctrsm(enum CBLAS_ORDER Order, enum CBLAS_SIDE Side, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA,\n                 enum CBLAS_DIAG Diag, int M, int N, void *alpha, void *A, int lda, void *B, int ldb);\n\nvoid cblas_zgemm(enum CBLAS_ORDER Order, enum CBLAS_TRANSPOSE TransA, enum CBLAS_TRANSPOSE TransB, int M, int N, int K,\n                 void *alpha, void *A, int lda, void *B, int ldb, void *beta, void *C, int ldc);\nvoid cblas_zsymm(enum CBLAS_ORDER Order, enum CBLAS_SIDE Side, enum CBLAS_UPLO Uplo, int M, int N, void *alpha, void *A,\n                 int lda, void *B, int ldb, void *beta, void *C, int ldc);\nvoid cblas_zsyrk(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE Trans, int N, int K, void *alpha,\n                 void *A, int lda, void *beta, void *C, int ldc);\nvoid cblas_zsyr2k(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE Trans, int N, int K, void *alpha,\n                  void *A, int lda, void *B, int ldb, void *beta, void *C, int ldc);\nvoid cblas_ztrmm(enum CBLAS_ORDER Order, enum CBLAS_SIDE Side, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA,\n                 enum CBLAS_DIAG Diag, int M, int N, void *alpha, void *A, int lda, void *B, int ldb);\nvoid cblas_ztrsm(enum CBLAS_ORDER Order, enum CBLAS_SIDE Side, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA,\n                 enum CBLAS_DIAG Diag, int M, int N, void *alpha, void *A, int lda, void *B, int ldb);\n\n/*\n * Routines with prefixes C and Z only\n */\nvoid cblas_chemm(enum CBLAS_ORDER Order, enum CBLAS_SIDE Side, enum CBLAS_UPLO Uplo, int M, int N, void *alpha, void *A,\n                 int lda, void *B, int ldb, void *beta, void *C, int ldc);\nvoid cblas_cherk(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE Trans, int N, int K, float alpha,\n                 void *A, int lda, float beta, void *C, int ldc);\nvoid cblas_cher2k(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE Trans, int N, int K, void *alpha,\n                  void *A, int lda, void *B, int ldb, float beta, void *C, int ldc);\nvoid cblas_zhemm(enum CBLAS_ORDER Order, enum CBLAS_SIDE Side, enum CBLAS_UPLO Uplo, int M, int N, void *alpha, void *A,\n                 int lda, void *B, int ldb, void *beta, void *C, int ldc);\nvoid cblas_zherk(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE Trans, int N, int K, double alpha,\n                 void *A, int lda, double beta, void *C, int ldc);\nvoid cblas_zher2k(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE Trans, int N, int K, void *alpha,\n                  void *A, int lda, void *B, int ldb, double beta, void *C, int ldc);\n\nint cblas_errprn(int ierr, int info, char *form, ...);\n#ifdef __cplusplus\n}\n#endif\n#endif /* end #ifdef CBLAS_ENUM_ONLY */\n#endif\n#endif  // NATIVEOPERATIONS_CBLAS_H\n", "meta": {"hexsha": "a98027c5fc5a25ed00e3f750fa685ef5bf79c778", "size": 24691, "ext": "h", "lang": "C", "max_stars_repo_path": "libnd4j/include/cblas.h", "max_stars_repo_name": "steljord2/deeplearning4j", "max_stars_repo_head_hexsha": "4653c97a713cc59e41d4313ddbafc5ff527f8714", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2206.0, "max_stars_repo_stars_event_min_datetime": "2019-06-12T18:57:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T08:14:27.000Z", "max_issues_repo_path": "libnd4j/include/cblas.h", "max_issues_repo_name": "steljord2/deeplearning4j", "max_issues_repo_head_hexsha": "4653c97a713cc59e41d4313ddbafc5ff527f8714", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1685.0, "max_issues_repo_issues_event_min_datetime": "2019-06-12T17:41:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T21:45:15.000Z", "max_forks_repo_path": "libnd4j/include/cblas.h", "max_forks_repo_name": "steljord2/deeplearning4j", "max_forks_repo_head_hexsha": "4653c97a713cc59e41d4313ddbafc5ff527f8714", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 572.0, "max_forks_repo_forks_event_min_datetime": "2019-06-12T22:13:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T16:46:46.000Z", "avg_line_length": 59.6400966184, "max_line_length": 120, "alphanum_fraction": 0.6667206674, "num_tokens": 7796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.04468086868252906, "lm_q1q2_score": 0.021293992805941627}}
{"text": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_linalg.h>\n\n#include \"norm.h\"\n#include \"constants.h\"\n\nint readFileVector( gsl_vector *vector, char *filePath, char *fileName )                //read file vals into vector\n{\n\tchar tmpFilepath[120] = \"\\0\";\n\tchar tmpReading[20];\n\tchar *tmp2;\n\tdouble reading;                                 //WARNING this is similar to global var $readings, consider renaming\n\t\n\tstrcat( tmpFilepath, filePath );                //TODO replace this and the first instance of strcat into strcpy, that should work\n\tstrcat( tmpFilepath, fileName );        //combines the filepath and name into one searchable /path/file\n\tFILE *file = fopen( tmpFilepath, \"rt\");\n\tprintf(\"%s\\n\", tmpFilepath);                    //TODO DELETE THIS\n\tif ( file == NULL ) {                   //check if file exists\n\t\tfprintf( stderr, \"Error, unable to locate the Mu data file\\n\");\n\t\texit(100);\n\t}\n\t\n\tfor ( int i = 0; i < skip; i++)         //move past header of read files\n\t{\n\t\tfgets( tmpReading, 19, file );\n\t}\n\t\n\tfor ( int i = 0; i < readings; i++ )\n\t{\n\t\tfgets( tmpReading, 19, file );\n\t\t\n\t\ttmp2 = strrchr( tmpReading, '\\t' );\n\t\ttmp2 = tmp2 + 1;\n\t\treading = atof(tmp2);\n\t\tgsl_vector_set( vector, i, reading);\n\t}\n\tfclose(file);\n\treturn 0;\n}\n\nint readFileMatrix( gsl_matrix *matrix, char *filePath, int argc, char *argv[] )\n{\n\tchar *tmp2;\n\tdouble reading;\n\tfor ( int j = 2; j < argc; j++ )\n\t{\n\t\tgsl_vector_view column;\n\t\tchar tmpFilepath[120] = \"\\0\";                           //TODO replace this and the first instance of strcat into strcpy, that should work\n\t\tchar tmpReading[20];\n\t\tstrcat( tmpFilepath, filePath );\n\t\tstrcat( tmpFilepath, argv[j] );         //combines the filepath and name into one searchable /path/file\n\t\tFILE *file = fopen( tmpFilepath, \"rt\");\n\t\tprintf(\"%s\\n\", tmpFilepath);                            //TODO DELETE THIS\n\t\tif ( file == NULL ) {                   //check if file exists\n\t\t\tfprintf( stderr, \"Error, unable to locate a reference data file\\n\");\n\t\t\texit(100);\n\t\t}\n\t\tfor ( int i = 0; i < skip; i++)         //move past header of read files\n\t\t{\n\t\t\tfgets( tmpReading, 20, file);\n\t\t}\n\t\tfor ( int i = 0; i < readings; i++ ) //fill the ith element of the jth column\n\t\t{\n\t\t\tfgets( tmpReading, 19, file );\n\t\t\t\n\t\t\ttmp2 = strrchr( tmpReading, '\\t' );\n\t\t\ttmp2 = tmp2 + 1;\n\t\t\treading = atof(tmp2);\n\t\t\tgsl_matrix_set( matrix, i, j-2, reading );\n\t\t}\n\t\tfclose(file);\n\t\tcolumn = gsl_matrix_column( matrix, j-2 );                              //NORMALISE EACH REFERENCE VECOTR.\n\t\tnormalizeVector( &column.vector );\n\t}\n\t\n\treturn 0;\n}\n\n", "meta": {"hexsha": "146256f83aa9091fa81125af48d17b08a629a1a6", "size": 2664, "ext": "c", "lang": "C", "max_stars_repo_path": "src/utils.c", "max_stars_repo_name": "jakeinater/spectralILU", "max_stars_repo_head_hexsha": "825dbd5c5495b0ce0a0d14a5bed865b9bfdda98d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils.c", "max_issues_repo_name": "jakeinater/spectralILU", "max_issues_repo_head_hexsha": "825dbd5c5495b0ce0a0d14a5bed865b9bfdda98d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils.c", "max_forks_repo_name": "jakeinater/spectralILU", "max_forks_repo_head_hexsha": "825dbd5c5495b0ce0a0d14a5bed865b9bfdda98d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3411764706, "max_line_length": 140, "alphanum_fraction": 0.6028528529, "num_tokens": 748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.0488577737749038, "lm_q1q2_score": 0.02120336822989025}}
{"text": "#pragma once\n\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_linalg.h>\n\n#include \"../vector.h\"\n\nnamespace gsl_wrapper::bits\n{\n  class MatrixRow\n  {\n  public:\n    // Consructor\n    MatrixRow(gsl_vector_view view);\n\n    // Operators\n    operator ::gsl_wrapper::Vector() const;\n\n    auto operator[](const size_t index) -> double &;\n    auto operator[](const size_t index) const -> const double &;\n\n  private:\n    gsl_vector_view m_view;\n  };\n\n  inline MatrixRow::MatrixRow(gsl_vector_view view)\n      : m_view{view}\n  {\n  }\n\n  inline MatrixRow::operator ::gsl_wrapper::Vector() const\n  {\n    auto space = gsl_vector_calloc(m_view.vector.size);\n    gsl_vector_memcpy(space, &m_view.vector);\n    return ::gsl_wrapper::Vector(space);\n  }\n\n  inline auto MatrixRow::operator[](const size_t index) -> double &\n  {\n    return *gsl_vector_ptr(&m_view.vector, index);\n  }\n\n  inline auto MatrixRow::operator[](const size_t index) const -> const double &\n  {\n    return *gsl_vector_const_ptr(&m_view.vector, index);\n  }\n\n}", "meta": {"hexsha": "25badfaec83094536c0d3a968cd0a52e0f0d1cc4", "size": 1005, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gsl_wrapper/bits/matrix-view.h", "max_stars_repo_name": "Szynkaa/gsl_cpp_wrapper", "max_stars_repo_head_hexsha": "0c9c4edfe751474edbf1a9a23075762cc3362cc1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-09T14:35:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T14:35:36.000Z", "max_issues_repo_path": "include/gsl_wrapper/bits/matrix-view.h", "max_issues_repo_name": "Szynkaa/gsl_cpp_wrapper", "max_issues_repo_head_hexsha": "0c9c4edfe751474edbf1a9a23075762cc3362cc1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gsl_wrapper/bits/matrix-view.h", "max_forks_repo_name": "Szynkaa/gsl_cpp_wrapper", "max_forks_repo_head_hexsha": "0c9c4edfe751474edbf1a9a23075762cc3362cc1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-10T09:06:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T09:06:07.000Z", "avg_line_length": 20.9375, "max_line_length": 79, "alphanum_fraction": 0.6776119403, "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215925474903, "lm_q2_score": 0.049589019121431335, "lm_q1q2_score": 0.021140869604716554}}
{"text": "/*\nMIT License\n\nCopyright (c) 2021 Shunji Uno <shunji_uno@iscpc.jp>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n#pragma once\n#include <stdint.h>\n#include <math.h>\n#include <float.h>\n\n#ifdef MKL\n#include <mkl.h>\n#ifdef MKL_SBLAS\n#include <mkl_spblas.h>\n#endif /* MKL_SBLAS */\n#else\n#include <cblas.h>\n#endif /* MKL */\n\n#ifdef SXAT\n#include <sblas.h>\n#endif\n\n#define DNRM2(N,X) cblas_dnrm2(N,X,1)\n#define DDOT(N,X,Y) cblas_ddot(N,X,1,Y,1)\n\n#define MATRIX_TYPE_INDEX0     (0)\n#define MATRIX_TYPE_INDEX1     (1)\n#define MATRIX_TYPE_ASYMMETRIC (0<<4)\n#define MATRIX_TYPE_SYMMETRIC  (1<<4)\n#define MATRIX_TYPE_LOWER      (1<<5)\n#define MATRIX_TYPE_UPPER      (0)\n#define MATRIX_TYPE_UNIT       (1<<6)\n#define MATRIX_TYPE_NON_UNIT   (0)\n#define MATRIX_TYPE_CSC        (0<<8)\n#define MATRIX_TYPE_CSR        (1<<8)\n#define MATRIX_TYPE_ELLPACK    (2<<8)\n#define MATRIX_TYPE_JAD        (3<<8)\n#define MATRIX_TYPE_DCSC       (8<<8)\n#define MATRIX_TYPE_DCSR       (9<<8)\n#define MATRIX_TYPE_MASK       (0xf<<8)\n\n#define MATRIX_INDEX_TYPE(A)    (((A)->flags)&0xf)\n#define MATRIX_IS_SYMMETRIC(A)  (((A)->flags)&MATRIX_TYPE_SYMMETRIC)\n#define MATRIX_IS_LOWER(A)      (((A)->flags)&MATRIX_TYPE_LOWER)\n#define MATRIX_IS_UNIT(A)       (((A)->flags)&MATRIX_TYPE_UNIT)\n#define MATRIX_IS_CSC(A)        ((((A)->flags)&MATRIX_TYPE_MASK) == MATRIX_TYPE_CSC)\n#define MATRIX_IS_CSR(A)        ((((A)->flags)&MATRIX_TYPE_MASK) == MATRIX_TYPE_CSR)\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\ntypedef struct ellpack_info {\n    int32_t nw;\n    double* COEF;\n    int32_t* ICOL;\n} ellpack_info_t;\n\ntypedef struct jad_info {\n    int32_t* perm;\n    int32_t* ptr;\n    int32_t* index;\n    double* value;\n    int32_t maxnzr;\n} jad_info_t;\n\ntypedef struct Matrix {\n    int NROWS;\n    int NNZ;\n    uint32_t flags;\n    int* pointers;\n    int* indice;\n    double* values;\n    ellpack_info_t _ellpack;\n    jad_info_t _jad;\n    void* info;\n#ifdef MKL\n    sparse_matrix_t hdl;\n#endif\n#ifdef SXAT\n    sblas_handle_t hdl;\n#endif\n#ifdef SSL2\n    double *w;\n    int *iw;\n#endif\n    int optimized;\n} Matrix_t;\n\n/*\n * Generic Matrix operations\n */\nvoid Matrix_init_generic(Matrix_t *A);\nvoid Matrix_free_generic(Matrix_t *A);\nint Matrix_optimize_generic(Matrix_t *A);\nint Matrix_MV_generic(const Matrix_t *A, const double alpha, const double* x, const double beta, const double* y, double* z);\n\n/*\n * Architecture dependent Matrix operations (prototype for override)\n */\nvoid Matrix_init(Matrix_t *A);\nvoid Matrix_free(Matrix_t *A);\nint Matrix_optimize(Matrix_t *A);\nint Matrix_MV(const Matrix_t *A, const double alpha, const double* x, const double beta, const double* y, double* z);\n\n/*\n * Architecture independent functions\n */\nvoid Matrix_setMatrixCSR(Matrix_t *A, const int nrows, const int nnz, const int *aptr,\n    const int *aind, const double *aval, const uint32_t flags);\nMatrix_t* Matrix_duplicate(const Matrix_t* A);\nint Matrix_convert_index(Matrix_t* A, int base);\nint Matrix_transpose(Matrix_t* A);\nint Matrix_extract_symmetric(Matrix_t* A);\nint Matrix_create_ellpack(Matrix_t* A);\nint Matrix_create_jad(Matrix_t* A);\n\n#ifdef __cplusplus\n}\n#endif\n", "meta": {"hexsha": "558a06721bfc626aa6b1dea75c21d0d139b3081f", "size": 4090, "ext": "h", "lang": "C", "max_stars_repo_path": "openmp/libsolver/src/common/Matrix.h", "max_stars_repo_name": "ISCPC/vesolver", "max_stars_repo_head_hexsha": "b7792f8922d8610c5e15ce99cfa7380835ce1692", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "openmp/libsolver/src/common/Matrix.h", "max_issues_repo_name": "ISCPC/vesolver", "max_issues_repo_head_hexsha": "b7792f8922d8610c5e15ce99cfa7380835ce1692", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "openmp/libsolver/src/common/Matrix.h", "max_forks_repo_name": "ISCPC/vesolver", "max_forks_repo_head_hexsha": "b7792f8922d8610c5e15ce99cfa7380835ce1692", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0070921986, "max_line_length": 125, "alphanum_fraction": 0.7300733496, "num_tokens": 1070, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713670203584295, "lm_q2_score": 0.04603389978171546, "lm_q1q2_score": 0.021043785128061914}}
{"text": "/*\n#\n# * The source code in this file is developed independently by NEC Corporation.\n#\n# # NLCPy License #\n# \n#     Copyright (c) 2020-2021 NEC Corporation\n#     All rights reserved.\n#     \n#     Redistribution and use in source and binary forms, with or without\n#     modification, are permitted provided that the following conditions are met:\n#     * Redistributions of source code must retain the above copyright notice,\n#       this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above copyright notice,\n#       this list of conditions and the following disclaimer in the documentation\n#       and/or other materials provided with the distribution.\n#     * Neither NEC Corporation nor the names of its contributors may be\n#       used to endorse or promote products derived from this software\n#       without specific prior written permission.\n#     \n#     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n#     ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n#     WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n#     DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n#     FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n#     (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n#     LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n#     ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n#     (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n#     SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n*/\n\n\n#include <cblas.h>\n#include \"nlcpy.h\"\n\n\nuint64_t wrapper_cblas_sdot(ve_arguments *args, int32_t *psw)\n{\n#ifdef _OPENMP\n#pragma omp single\n#endif /* _OPENMP */\n{\n    ve_array *x = &(args->binary.x);\n    ve_array *y = &(args->binary.y);\n    ve_array *z = &(args->binary.z);\n\n    float *px = (float *)x->ve_adr;\n    if (px == NULL) {\n        px = (float *)nlcpy__get_scalar(x);\n        if (px == NULL) {\n            return NLCPY_ERROR_MEMORY;\n        }\n    }\n    float *py = (float *)y->ve_adr;\n    if (py == NULL) {\n        py = (float *)nlcpy__get_scalar(y);\n        if (py == NULL) {\n            return NLCPY_ERROR_MEMORY;\n        }\n    }\n    float *pz = (float *)z->ve_adr;\n    if (pz == NULL) {\n       return (uint64_t)NLCPY_ERROR_MEMORY; \n    }\n    assert(x->ndim <= 1);\n    assert(y->ndim <= 1);\n    assert(z->ndim <= 1);\n    assert(x->size == y->size);\n\n    *pz = cblas_sdot(x->size, px, x->strides[0] / x->itemsize, \n                            py, y->strides[0] / y->itemsize);\n} /* omp single */\n    retrieve_fpe_flags(psw);\n    return (uint64_t)NLCPY_ERROR_OK;\n}\n\nuint64_t wrapper_cblas_ddot(ve_arguments *args, int32_t *psw)\n{\n#ifdef _OPENMP\n#pragma omp single\n#endif /* _OPENMP */\n{\n    ve_array *x = &(args->binary.x);\n    ve_array *y = &(args->binary.y);\n    ve_array *z = &(args->binary.z);\n\n    double *px = (double *)x->ve_adr;\n    if (px == NULL) {\n        px = (double *)nlcpy__get_scalar(x);\n        if (px == NULL) {\n            return NLCPY_ERROR_MEMORY;\n        }\n    }\n    double *py = (double *)y->ve_adr;\n    if (py == NULL) {\n        py = (double *)nlcpy__get_scalar(y);\n        if (py == NULL) {\n            return NLCPY_ERROR_MEMORY;\n        }\n    }\n    double *pz = (double *)z->ve_adr;\n    if (pz == NULL) {\n       return (uint64_t)NLCPY_ERROR_MEMORY; \n    }\n    assert(x->ndim <= 1);\n    assert(y->ndim <= 1);\n    assert(z->ndim <= 1);\n    assert(x->size == y->size);\n\n    *pz = cblas_ddot(x->size, px, x->strides[0] / x->itemsize, \n                            py, y->strides[0] / y->itemsize);\n} /* omp single */\n    retrieve_fpe_flags(psw);\n    return (uint64_t)NLCPY_ERROR_OK;\n}\n\nuint64_t wrapper_cblas_cdotu_sub(ve_arguments *args, int32_t *psw)\n{\n#ifdef _OPENMP\n#pragma omp single\n#endif /* _OPENMP */\n{\n    ve_array *x = &(args->binary.x);\n    ve_array *y = &(args->binary.y);\n    ve_array *z = &(args->binary.z);\n\n    float _Complex *px = (float _Complex *)x->ve_adr;\n    if (px == NULL) {\n        px = (float _Complex *)nlcpy__get_scalar(x);\n        if (px == NULL) {\n            return NLCPY_ERROR_MEMORY;\n        }\n    }\n    float _Complex *py = (float _Complex *)y->ve_adr;\n    if (py == NULL) {\n        py = (float _Complex *)nlcpy__get_scalar(y);\n        if (py == NULL) {\n            return NLCPY_ERROR_MEMORY;\n        }\n    }\n    float _Complex *pz = (float _Complex *)z->ve_adr;\n    if (pz == NULL) {\n       return (uint64_t)NLCPY_ERROR_MEMORY; \n    }\n    assert(x->ndim <= 1);\n    assert(y->ndim <= 1);\n    assert(z->ndim <= 1);\n    assert(x->size == y->size);\n\n\n    cblas_cdotu_sub(x->size, px, x->strides[0] / x->itemsize, \n                        py, y->strides[0] / y->itemsize, pz);\n} /* omp single */\n    retrieve_fpe_flags(psw);\n    return (uint64_t)NLCPY_ERROR_OK;\n}\n\nuint64_t wrapper_cblas_zdotu_sub(ve_arguments *args, int32_t *psw)\n{\n#ifdef _OPENMP\n#pragma omp single\n#endif /* _OPENMP */\n{\n    ve_array *x = &(args->binary.x);\n    ve_array *y = &(args->binary.y);\n    ve_array *z = &(args->binary.z);\n\n    double _Complex *px = (double _Complex *)x->ve_adr;\n    if (px == NULL) {\n        px = (double _Complex *)nlcpy__get_scalar(x);\n        if (px == NULL) {\n            return NLCPY_ERROR_MEMORY;\n        }\n    }\n    double _Complex *py = (double _Complex *)y->ve_adr;\n    if (py == NULL) {\n        py = (double _Complex *)nlcpy__get_scalar(y);\n        if (py == NULL) {\n            return NLCPY_ERROR_MEMORY;\n        }\n    }\n    double _Complex *pz = (double _Complex *)z->ve_adr;\n    if (pz == NULL) {\n       return (uint64_t)NLCPY_ERROR_MEMORY; \n    }\n    assert(x->ndim <= 1);\n    assert(y->ndim <= 1);\n    assert(z->ndim <= 1);\n    assert(x->size == y->size);\n\n\n    cblas_zdotu_sub(x->size, px, x->strides[0] / x->itemsize, \n                        py, y->strides[0] / y->itemsize, pz);\n} /* omp single */\n    retrieve_fpe_flags(psw);\n    return (uint64_t)NLCPY_ERROR_OK;\n}\n\n\n\n\nuint64_t wrapper_cblas_sgemm(ve_arguments *args, int32_t *psw)\n{\n    const int32_t order = args->gemm.order;\n    const int32_t transA = args->gemm.transA;\n    const int32_t transB = args->gemm.transB;\n    const int32_t m = args->gemm.m;\n    const int32_t n = args->gemm.n;\n    const int32_t k = args->gemm.k;\n    const float alpha = *((float *)nlcpy__get_scalar(&(args->gemm.alpha)));\n    float* const a = (float *)args->gemm.a.ve_adr;\n    const int32_t lda = args->gemm.lda;\n    float* const b = (float *)args->gemm.b.ve_adr;\n    const int32_t ldb = args->gemm.ldb;\n    const float beta = *((float *)nlcpy__get_scalar(&(args->gemm.beta)));\n    float* const c = (float *)args->gemm.c.ve_adr;\n    const int32_t ldc = args->gemm.ldc;\n\n    if (a == NULL || b == NULL || c == NULL) {\n        return NLCPY_ERROR_MEMORY;\n    }\n\n\n#ifdef _OPENMP\n    const int32_t nt = omp_get_num_threads();\n    const int32_t it = omp_get_thread_num();\n#else\n    const int32_t nt = 1;\n    const int32_t it = 0;\n#endif /* _OPENMP */\n\n    const int32_t m_s = m * it / nt;\n    const int32_t m_e = m * (it + 1) / nt;\n    const int32_t m_d = m_e - m_s;\n    const int32_t n_s = n * it / nt;\n    const int32_t n_e = n * (it + 1) / nt;\n    const int32_t n_d = n_e - n_s;\n    \n    int32_t mode = 1;\n    if ( n > nt ) { \n        mode = 2;\n    }\n    int32_t iar, iac, ibr, ibc, icr, icc;\n    if (transA == CblasNoTrans ) {\n        iar = 1;\n        iac = lda;\n    } else {\n        iar = lda;\n        iac = 1;\n    }\n    if (transB == CblasNoTrans ) {\n        ibr = 1;\n        ibc = ldb;\n    } else {\n        ibr = ldb;\n        ibc = 1;\n    }\n    if (order == CblasColMajor ) {\n        icr = 1;\n        icc = ldc;\n    } else {\n        icr = ldc;\n        icc = 1;\n    }\n\n    if (order == CblasColMajor) {\n        if ( mode == 1 ) { \n            // split 'm'\n            cblas_sgemm(order, transA, transB, m_d, n, k, alpha, a + m_s * iar, lda, b, ldb, beta, c + m_s * icr, ldc);  \n        } else {\n            // split 'n'\n            cblas_sgemm(order, transA, transB, m, n_d, k, alpha, a, lda, b + n_s * ibc, ldb, beta, c + n_s * icc, ldc);  \n        }\n    } else {\n        if ( mode == 1 ) { \n            // split 'm'\n            cblas_sgemm(order, transA, transB, m_d, n, k, alpha, a + m_s * iac, lda, b, ldb, beta, c + m_s * icr, ldc);  \n        } else {\n            // split 'n'\n            cblas_sgemm(order, transA, transB, m, n_d, k, alpha, a, lda, b + n_s * ibr, ldb, beta, c + n_s * icc, ldc);  \n        }\n    }\n\n    retrieve_fpe_flags(psw);\n    return (uint64_t)NLCPY_ERROR_OK;\n}\n\nuint64_t wrapper_cblas_dgemm(ve_arguments *args, int32_t *psw)\n{\n    const int32_t order = args->gemm.order;\n    const int32_t transA = args->gemm.transA;\n    const int32_t transB = args->gemm.transB;\n    const int32_t m = args->gemm.m;\n    const int32_t n = args->gemm.n;\n    const int32_t k = args->gemm.k;\n    const double alpha = *((double *)nlcpy__get_scalar(&(args->gemm.alpha)));\n    double* const a = (double *)args->gemm.a.ve_adr;\n    const int32_t lda = args->gemm.lda;\n    double* const b = (double *)args->gemm.b.ve_adr;\n    const int32_t ldb = args->gemm.ldb;\n    const double beta = *((double *)nlcpy__get_scalar(&(args->gemm.beta)));\n    double* const c = (double *)args->gemm.c.ve_adr;\n    const int32_t ldc = args->gemm.ldc;\n\n    if (a == NULL || b == NULL || c == NULL) {\n        return NLCPY_ERROR_MEMORY;\n    }\n\n\n#ifdef _OPENMP\n    const int32_t nt = omp_get_num_threads();\n    const int32_t it = omp_get_thread_num();\n#else\n    const int32_t nt = 1;\n    const int32_t it = 0;\n#endif /* _OPENMP */\n\n    const int32_t m_s = m * it / nt;\n    const int32_t m_e = m * (it + 1) / nt;\n    const int32_t m_d = m_e - m_s;\n    const int32_t n_s = n * it / nt;\n    const int32_t n_e = n * (it + 1) / nt;\n    const int32_t n_d = n_e - n_s;\n    \n    int32_t mode = 1;\n    if ( n > nt ) { \n        mode = 2;\n    }\n    int32_t iar, iac, ibr, ibc, icr, icc;\n    if (transA == CblasNoTrans ) {\n        iar = 1;\n        iac = lda;\n    } else {\n        iar = lda;\n        iac = 1;\n    }\n    if (transB == CblasNoTrans ) {\n        ibr = 1;\n        ibc = ldb;\n    } else {\n        ibr = ldb;\n        ibc = 1;\n    }\n    if (order == CblasColMajor ) {\n        icr = 1;\n        icc = ldc;\n    } else {\n        icr = ldc;\n        icc = 1;\n    }\n\n    if (order == CblasColMajor) {\n        if ( mode == 1 ) { \n            // split 'm'\n            cblas_dgemm(order, transA, transB, m_d, n, k, alpha, a + m_s * iar, lda, b, ldb, beta, c + m_s * icr, ldc);  \n        } else {\n            // split 'n'\n            cblas_dgemm(order, transA, transB, m, n_d, k, alpha, a, lda, b + n_s * ibc, ldb, beta, c + n_s * icc, ldc);  \n        }\n    } else {\n        if ( mode == 1 ) { \n            // split 'm'\n            cblas_dgemm(order, transA, transB, m_d, n, k, alpha, a + m_s * iac, lda, b, ldb, beta, c + m_s * icr, ldc);  \n        } else {\n            // split 'n'\n            cblas_dgemm(order, transA, transB, m, n_d, k, alpha, a, lda, b + n_s * ibr, ldb, beta, c + n_s * icc, ldc);  \n        }\n    }\n\n    retrieve_fpe_flags(psw);\n    return (uint64_t)NLCPY_ERROR_OK;\n}\n\nuint64_t wrapper_cblas_cgemm(ve_arguments *args, int32_t *psw)\n{\n    const int32_t order = args->gemm.order;\n    const int32_t transA = args->gemm.transA;\n    const int32_t transB = args->gemm.transB;\n    const int32_t m = args->gemm.m;\n    const int32_t n = args->gemm.n;\n    const int32_t k = args->gemm.k;\n    const void *alpha = (void *)nlcpy__get_scalar(&(args->gemm.alpha));\n    if (alpha == NULL) return (uint64_t)NLCPY_ERROR_MEMORY;\n    float  _Complex* const a = (float  _Complex *)args->gemm.a.ve_adr;\n    const int32_t lda = args->gemm.lda;\n    float  _Complex* const b = (float  _Complex *)args->gemm.b.ve_adr;\n    const int32_t ldb = args->gemm.ldb;\n    const void *beta = (void *)nlcpy__get_scalar(&(args->gemm.beta));\n    if (beta == NULL) return (uint64_t)NLCPY_ERROR_MEMORY;\n    float  _Complex* const c = (float  _Complex *)args->gemm.c.ve_adr;\n    const int32_t ldc = args->gemm.ldc;\n\n    if (a == NULL || b == NULL || c == NULL) {\n        return NLCPY_ERROR_MEMORY;\n    }\n\n\n#ifdef _OPENMP\n    const int32_t nt = omp_get_num_threads();\n    const int32_t it = omp_get_thread_num();\n#else\n    const int32_t nt = 1;\n    const int32_t it = 0;\n#endif /* _OPENMP */\n\n    const int32_t m_s = m * it / nt;\n    const int32_t m_e = m * (it + 1) / nt;\n    const int32_t m_d = m_e - m_s;\n    const int32_t n_s = n * it / nt;\n    const int32_t n_e = n * (it + 1) / nt;\n    const int32_t n_d = n_e - n_s;\n    \n    int32_t mode = 1;\n    if ( n > nt ) { \n        mode = 2;\n    }\n    int32_t iar, iac, ibr, ibc, icr, icc;\n    if (transA == CblasNoTrans ) {\n        iar = 1;\n        iac = lda;\n    } else {\n        iar = lda;\n        iac = 1;\n    }\n    if (transB == CblasNoTrans ) {\n        ibr = 1;\n        ibc = ldb;\n    } else {\n        ibr = ldb;\n        ibc = 1;\n    }\n    if (order == CblasColMajor ) {\n        icr = 1;\n        icc = ldc;\n    } else {\n        icr = ldc;\n        icc = 1;\n    }\n\n    if (order == CblasColMajor) {\n        if ( mode == 1 ) { \n            // split 'm'\n            cblas_cgemm(order, transA, transB, m_d, n, k, alpha, a + m_s * iar, lda, b, ldb, beta, c + m_s * icr, ldc);  \n        } else {\n            // split 'n'\n            cblas_cgemm(order, transA, transB, m, n_d, k, alpha, a, lda, b + n_s * ibc, ldb, beta, c + n_s * icc, ldc);  \n        }\n    } else {\n        if ( mode == 1 ) { \n            // split 'm'\n            cblas_cgemm(order, transA, transB, m_d, n, k, alpha, a + m_s * iac, lda, b, ldb, beta, c + m_s * icr, ldc);  \n        } else {\n            // split 'n'\n            cblas_cgemm(order, transA, transB, m, n_d, k, alpha, a, lda, b + n_s * ibr, ldb, beta, c + n_s * icc, ldc);  \n        }\n    }\n\n    retrieve_fpe_flags(psw);\n    return (uint64_t)NLCPY_ERROR_OK;\n}\n\nuint64_t wrapper_cblas_zgemm(ve_arguments *args, int32_t *psw)\n{\n    const int32_t order = args->gemm.order;\n    const int32_t transA = args->gemm.transA;\n    const int32_t transB = args->gemm.transB;\n    const int32_t m = args->gemm.m;\n    const int32_t n = args->gemm.n;\n    const int32_t k = args->gemm.k;\n    const void *alpha = (void *)nlcpy__get_scalar(&(args->gemm.alpha));\n    if (alpha == NULL) return (uint64_t)NLCPY_ERROR_MEMORY;\n    double _Complex* const a = (double _Complex *)args->gemm.a.ve_adr;\n    const int32_t lda = args->gemm.lda;\n    double _Complex* const b = (double _Complex *)args->gemm.b.ve_adr;\n    const int32_t ldb = args->gemm.ldb;\n    const void *beta = (void *)nlcpy__get_scalar(&(args->gemm.beta));\n    if (beta == NULL) return (uint64_t)NLCPY_ERROR_MEMORY;\n    double _Complex* const c = (double _Complex *)args->gemm.c.ve_adr;\n    const int32_t ldc = args->gemm.ldc;\n\n    if (a == NULL || b == NULL || c == NULL) {\n        return NLCPY_ERROR_MEMORY;\n    }\n\n\n#ifdef _OPENMP\n    const int32_t nt = omp_get_num_threads();\n    const int32_t it = omp_get_thread_num();\n#else\n    const int32_t nt = 1;\n    const int32_t it = 0;\n#endif /* _OPENMP */\n\n    const int32_t m_s = m * it / nt;\n    const int32_t m_e = m * (it + 1) / nt;\n    const int32_t m_d = m_e - m_s;\n    const int32_t n_s = n * it / nt;\n    const int32_t n_e = n * (it + 1) / nt;\n    const int32_t n_d = n_e - n_s;\n    \n    int32_t mode = 1;\n    if ( n > nt ) { \n        mode = 2;\n    }\n    int32_t iar, iac, ibr, ibc, icr, icc;\n    if (transA == CblasNoTrans ) {\n        iar = 1;\n        iac = lda;\n    } else {\n        iar = lda;\n        iac = 1;\n    }\n    if (transB == CblasNoTrans ) {\n        ibr = 1;\n        ibc = ldb;\n    } else {\n        ibr = ldb;\n        ibc = 1;\n    }\n    if (order == CblasColMajor ) {\n        icr = 1;\n        icc = ldc;\n    } else {\n        icr = ldc;\n        icc = 1;\n    }\n\n    if (order == CblasColMajor) {\n        if ( mode == 1 ) { \n            // split 'm'\n            cblas_zgemm(order, transA, transB, m_d, n, k, alpha, a + m_s * iar, lda, b, ldb, beta, c + m_s * icr, ldc);  \n        } else {\n            // split 'n'\n            cblas_zgemm(order, transA, transB, m, n_d, k, alpha, a, lda, b + n_s * ibc, ldb, beta, c + n_s * icc, ldc);  \n        }\n    } else {\n        if ( mode == 1 ) { \n            // split 'm'\n            cblas_zgemm(order, transA, transB, m_d, n, k, alpha, a + m_s * iac, lda, b, ldb, beta, c + m_s * icr, ldc);  \n        } else {\n            // split 'n'\n            cblas_zgemm(order, transA, transB, m, n_d, k, alpha, a, lda, b + n_s * ibr, ldb, beta, c + n_s * icc, ldc);  \n        }\n    }\n\n    retrieve_fpe_flags(psw);\n    return (uint64_t)NLCPY_ERROR_OK;\n}\n\n\n", "meta": {"hexsha": "8b952d2151ef859cfef0e26b4663f0a39c98ef23", "size": 16648, "ext": "c", "lang": "C", "max_stars_repo_path": "nlcpy/ve_kernel/cblas_wrapper.c", "max_stars_repo_name": "SX-Aurora/nlcpy", "max_stars_repo_head_hexsha": "0a53eec8778073bc48b12687b7ce37ab2bf2b7e0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2020-07-31T02:21:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T03:12:11.000Z", "max_issues_repo_path": "nlcpy/ve_kernel/cblas_wrapper.c", "max_issues_repo_name": "SX-Aurora/nlcpy", "max_issues_repo_head_hexsha": "0a53eec8778073bc48b12687b7ce37ab2bf2b7e0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nlcpy/ve_kernel/cblas_wrapper.c", "max_forks_repo_name": "SX-Aurora/nlcpy", "max_forks_repo_head_hexsha": "0a53eec8778073bc48b12687b7ce37ab2bf2b7e0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1048824593, "max_line_length": 121, "alphanum_fraction": 0.555622297, "num_tokens": 5413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207955, "lm_q2_score": 0.04272219419471941, "lm_q1q2_score": 0.02102735711460074}}
{"text": "/**\n * Author : Pierre Schnizer\n * Date: January 2003\n */\n#ifndef PyGSL_FUNCTION_HELPERS_H\n#define  PyGSL_FUNCTION_HELPERS_H 1\n/*   ------------------------------------------------------------------------- \n     See gsl_functions_reference.txt for a compilation of the different \n     callbacks found in GSL.\n\n     Todo: \n           Perhaps split the file in general helpers and \n\t   special helpers ????\n\t   Make all helpers reporting error via \n           PyGSL_set_error_string_for_callback\n\n\t   List all functions in these file in a header\n   ------------------------------------------------------------------------- */\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_roots.h>\n#include <gsl/gsl_min.h>\n#include <gsl/gsl_multiroots.h>\n#include <gsl/gsl_multimin.h>\n#include <gsl/gsl_multifit_nlin.h>\n#include <gsl/gsl_monte.h>\n#include <pygsl/utils.h>\n#include <pygsl/intern.h>\n#include <pygsl/error_helpers.h>\n#include <pygsl/general_helpers.h>\n#include <pygsl/block_helpers.h>\n#include <pygsl/function_helpers.h>\n#include <math.h>\n#include <setjmp.h>\n\n/* -------------------------------------------------------------------------\n   Helper Structs\n\n   *_func_name : a descriptive message for the internal function used \n                 when reporting an error to the user.\n   buffer_is_set : It depends on the user that she/he uses the\n                   *BUFFER in the function interfaces. So this variable is\n                  set to zero when the struct is generated. I hope this \n\t\t  will stop the wrapper trying to jump to NIRVANA.\n   ------------------------------------------------------------------------- */\n/* \n *  11 December 2003\n *  I return the flag that GSL returned using the flag argument to longjmp.\n *  This flag must be different from zero to be useful. GSL uses \n *  0 (== GSL_SUCCESS) to indicate it. I check for that here to see if it is \n *  always like that.\n */\n#if GSL_SUCCESS != 0\n#error \"The function helpers use longjmp. GSL_SUCCESS must be zero. Pygsl Design error\"\n#endif\ntypedef struct {\n     PyObject *function;\n     PyObject *arguments;\n     const char * c_func_name;\n     jmp_buf buffer;\n     int buffer_is_set;\n} callback_function_params;\n\ntypedef struct {\n     PyObject *f;\n     PyObject *df;\n     PyObject *fdf;\n     PyObject *arguments;\n     const char * c_f_func_name;\n     const char * c_df_func_name;\n     const char * c_fdf_func_name;\n     jmp_buf buffer;\n     int buffer_is_set;\n} callback_function_params_fdf;\n\n\n\n\n/* -------------------------------------------------------------------------\n   Copy PyArray to gsl vector, gslarray and vice versa\n   Are these functions ever needed by pure vector or matrix conversion?\n   If so these functions should go into gsl_block_helpers.i\n   ------------------------------------------------------------------------- */\n\n\n/* 1. A_n O -> A_p  */\nint\nPyGSL_function_wrap_Op_On(const gsl_vector * x, gsl_vector *f, PyObject *callback, \n\t\t\t  PyObject * arguments, int n, int p, const char *c_func_name);\n/* 2. A_n O -> A_n_p */\nint\nPyGSL_function_wrap_Op_Opn(const gsl_vector * x, gsl_matrix *f, PyObject *callback,\n\t\t\t   PyObject *arguments, int n, int p, const char * c_func_name);\n\n/* 3   dO -> d      gsl_function     */\n/* 3.1 dO -> d d    gsl_function_fdf */\nPyGSL_API_EXTERN int \nPyGSL_function_wrap_helper(double x, double * result, double *result2,\n\t\t\t   PyObject *callback, PyObject *arguments,\n\t\t\t   const char *c_func_name);\n\n/*\n * Pass a NULL pointer for result 2, if not needed.\n */\n/* 4. A_n O   ->  d (A_n) */\n int\nPyGSL_function_wrap_On_O(const gsl_vector * x, PyObject *callback,\n\t\t\tPyObject *arguments, double *result1,\n\t\t\t gsl_vector *result2, int n, const char * c_func_name);\n\n/* 5. A_n O -> A_n A_n_p */\n int\nPyGSL_function_wrap_Op_On_Opn(const gsl_vector * x, gsl_vector *f1, \n\t\t\t      gsl_matrix *f2, PyObject *callback, \n\t\t\t      PyObject *arguments, int n, int p, \n\t\t\t      const char * c_func_name);\n\n\n/* -------------------------------------------------------------------------\n      Register Python Call backs\n      \n      Generic Helper Functions\n   ------------------------------------------------------------------------ */\n/* Callbacks using one function */\ncallback_function_params *\nPyGSL_convert_to_generic_function(PyObject *object, int *size, int *size2, const char * c_func_name);\n/* Callbacks using 3  functions */\ncallback_function_params_fdf *\nPyGSL_convert_to_generic_function_fdf(PyObject *object, int *size, int *size2, \n\t\t\t\t      const char * c_f_func_name, const char * c_df_func_name, const char * c_fdf_func_name);\nvoid \nPyGSL_params_free(callback_function_params *p);\nvoid \nPyGSL_params_free_fdf(callback_function_params_fdf *p);\n\n\ndouble \nPyGSL_function_wrap(double x, void * params);\ndouble \nPyGSL_function_wrap_f(double x, void * params);\ndouble \nPyGSL_function_wrap_df(double x, void * params);\nvoid\nPyGSL_function_wrap_fdf(double x,  void * params, double *f, double * fdf);\ngsl_function *  \nPyGSL_convert_to_gsl_function(PyObject * object);\ngsl_function_fdf *  \nPyGSL_convert_to_gsl_function_fdf(PyObject * object);\n\n\n/* Specialised functions ... should they go to callbacks? */\n\n\nint \nPyGSL_multiroot_function_wrap(const gsl_vector *x, void *params, gsl_vector *f);\nint \nPyGSL_multiroot_function_wrap_f(const gsl_vector *x, void *params, gsl_vector *f);\nint \nPyGSL_multiroot_function_wrap_df(const gsl_vector *x, void *params, gsl_matrix *J);\nint \nPyGSL_multiroot_function_wrap_fdf(const gsl_vector *x, void *params, gsl_vector *f, gsl_matrix *J);\ngsl_multiroot_function *  \nPyGSL_convert_to_gsl_multiroot_function(PyObject * object);\ngsl_multiroot_function_fdf *  \nPyGSL_convert_to_gsl_multiroot_function_fdf(PyObject * object);\n\n\ndouble\nPyGSL_multimin_function_wrap(const gsl_vector *x, void *params);\ndouble\nPyGSL_multimin_function_wrap_f(const gsl_vector *x, void *params);\nvoid\nPyGSL_multimin_function_wrap_df(const gsl_vector *x, void *params, gsl_vector *g);\nvoid\nPyGSL_multimin_function_wrap_fdf(const gsl_vector *x, void *params, double *f, gsl_vector *g);\ngsl_multimin_function *  \nPyGSL_convert_to_gsl_multimin_function(PyObject * object);\ngsl_multimin_function_fdf *  \nPyGSL_convert_to_gsl_multimin_function_fdf(PyObject * object);\n\n\nint \nPyGSL_multifit_function_wrap(const gsl_vector *x, void *params, gsl_vector *f);\nint \nPyGSL_multifit_function_wrap_f(const gsl_vector *x, void *params, gsl_vector *f);\nint \nPyGSL_multifit_function_wrap_df(const gsl_vector *x, void *params, gsl_matrix *df);\nint \nPyGSL_multifit_function_wrap_fdf(const gsl_vector *x, void *params, gsl_vector *f, gsl_matrix *df);\ngsl_multifit_function *  \nPyGSL_convert_to_gsl_multifit_function(PyObject * object);\ngsl_multifit_function_fdf *  \nPyGSL_convert_to_gsl_multifit_function_fdf(PyObject * object);\ngsl_monte_function *\nPyGSL_convert_to_gsl_monte_function(PyObject * object);\n\n\n/* gsl_function */\nextern char * pygsl_gsl_function;\nextern char * pygsl_gsl_f_function;\nextern char * pygsl_gsl_df_function;\nextern char * pygsl_gsl_fdf_function;\n/* gsl_multifit */\nextern char * pygsl_multifit_function;\nextern char * pygsl_multifit_f_function;\nextern char * pygsl_multifit_df_function;\nextern char * pygsl_multifit_fdf_function;\n \nextern char * pygsl_multimin_function;\nextern char * pygsl_multimin_f_function;\nextern char * pygsl_multimin_df_function;\nextern char * pygsl_multimin_fdf_function;\n/* gsl_multiroot */\nextern char * pygsl_multiroot_function;\nextern char * pygsl_multiroot_f_function;\nextern char * pygsl_multiroot_df_function;\nextern char * pygsl_multiroot_fdf_function;\n\n/* monte */\nextern char * pygsl_monte_function;\n#ifndef _PyGSL_API_MODULE\n#define PyGSL_function_wrap_helper \\\n(*(int (*) (double, double *, double *, PyObject *, PyObject *, const char *)) PyGSL_API[PyGSL_function_wrap_helper_NUM])\n#endif  /* _PyGSL_API_MODULE */\n#endif  /* PyGSL_FUNCTION_HELPERS_H */\n\n\n\n\n", "meta": {"hexsha": "83a4972bd4a6bcf506fc1a2780b509f315697c9a", "size": 7851, "ext": "h", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/Include/pygsl/function_helpers.h", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/Include/pygsl/function_helpers.h", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/Include/pygsl/function_helpers.h", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 34.1347826087, "max_line_length": 121, "alphanum_fraction": 0.6929053624, "num_tokens": 1951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3923368301671084, "lm_q2_score": 0.053403330929736405, "lm_q1q2_score": 0.02095209357733788}}
{"text": "#ifndef MATHLAB_H\n#define MATHLAB_H\n\n#define USE_MKL 0\n#define USE_OPENBLAS 1\n\n#if USE_MKL\n#include <mkl.h>\n\n#elif USE_OPENBLAS\n#include <cblas.h>\n\n#endif\n\n#endif", "meta": {"hexsha": "82bd28ae1a1a865ce6c691b925d0f195bea00b48", "size": 162, "ext": "h", "lang": "C", "max_stars_repo_path": "github_winograd/include/mathlib.h", "max_stars_repo_name": "tsyj0404/winograd_convolution", "max_stars_repo_head_hexsha": "0872ae3ad5398ab1acf1cc53bcf027d65ea04cfb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2017-10-18T06:08:50.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-06T10:47:32.000Z", "max_issues_repo_path": "github_winograd/include/mathlib.h", "max_issues_repo_name": "TaoHuUMD/Winograd_Convolution", "max_issues_repo_head_hexsha": "0872ae3ad5398ab1acf1cc53bcf027d65ea04cfb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "github_winograd/include/mathlib.h", "max_forks_repo_name": "TaoHuUMD/Winograd_Convolution", "max_forks_repo_head_hexsha": "0872ae3ad5398ab1acf1cc53bcf027d65ea04cfb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-10-18T06:09:03.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-29T23:56:17.000Z", "avg_line_length": 10.8, "max_line_length": 22, "alphanum_fraction": 0.7530864198, "num_tokens": 53, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.44167300566462553, "lm_q2_score": 0.04742587536541707, "lm_q1q2_score": 0.020946728918919678}}
{"text": "////////////////////////////////////////////////////////////\n//\n// Copyright (c) 2018 Jan Filipowicz, Filip Turobos\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n//\n////////////////////////////////////////////////////////////\n\n#ifndef GENETIC_ALGORITHM_LIBRARY_ELITIST_SELECTION_H\n#define GENETIC_ALGORITHM_LIBRARY_ELITIST_SELECTION_H\n\n#include <algorithm>\n#include <cstddef>\n#include <functional>\n#include <vector>\n#include <gsl/gsl_assert>\n\ntemplate<class Compare = std::less<>>\nclass elitist_selection {\npublic:\n\texplicit elitist_selection(const Compare& comp = Compare()) noexcept(noexcept(Compare(comp)));\n\ttemplate<class Specimen>\n\tvoid operator()(std::vector<Specimen>& specimens, std::size_t n) const;\nprivate:\n\tCompare comparator;\n};\n\ntemplate<class Compare>\ninline elitist_selection<Compare>::elitist_selection(const Compare& comp) noexcept(noexcept(Compare(comp)))\n\t: comparator(comp) {}\n\ntemplate<class Compare>\ntemplate<class Specimen>\ninline void elitist_selection<Compare>::operator()(std::vector<Specimen>& specimens, std::size_t n) const {\n\tExpects(specimens.size() >= n);\n\tstd::nth_element(specimens.begin(), specimens.begin() + n, specimens.end(), [this](const Specimen& lhs, const Specimen& rhs) {\n\t\treturn comparator(rhs.rating(), lhs.rating());\n\t});\n\tspecimens.resize(n);\n}\n\n#endif\n", "meta": {"hexsha": "f95afb251a262e0a3e47726e9abfacc93c3f815d", "size": 2333, "ext": "h", "lang": "C", "max_stars_repo_path": "Genetic-Algorithm-Library/elitist_selection.h", "max_stars_repo_name": "SirEmentaler/Eugenics-Wars", "max_stars_repo_head_hexsha": "8a093d42ca935556e7d6ccaee5a57b8dd0c6b3e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Genetic-Algorithm-Library/elitist_selection.h", "max_issues_repo_name": "SirEmentaler/Eugenics-Wars", "max_issues_repo_head_hexsha": "8a093d42ca935556e7d6ccaee5a57b8dd0c6b3e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Genetic-Algorithm-Library/elitist_selection.h", "max_forks_repo_name": "SirEmentaler/Eugenics-Wars", "max_forks_repo_head_hexsha": "8a093d42ca935556e7d6ccaee5a57b8dd0c6b3e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.5423728814, "max_line_length": 127, "alphanum_fraction": 0.7243891985, "num_tokens": 492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.042087729417519974, "lm_q1q2_score": 0.020879462860473357}}
{"text": "/* rng/gsl_rng.h\r\n * \r\n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2004, 2007 James Theiler, Brian Gough\r\n * \r\n * This program is free software; you can redistribute it and/or modify\r\n * it under the terms of the GNU General Public License as published by\r\n * the Free Software Foundation; either version 3 of the License, or (at\r\n * your option) any later version.\r\n * \r\n * This program is distributed in the hope that it will be useful, but\r\n * WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n * General Public License for more details.\r\n * \r\n * You should have received a copy of the GNU General Public License\r\n * along with this program; if not, write to the Free Software\r\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r\n */\r\n\r\n#ifndef __GSL_RNG_H__\r\n#define __GSL_RNG_H__\r\n\r\n#if !defined( GSL_FUN )\r\n#  if !defined( GSL_DLL )\r\n#    define GSL_FUN extern\r\n#  elif defined( BUILD_GSL_DLL )\r\n#    define GSL_FUN extern __declspec(dllexport)\r\n#  else\r\n#    define GSL_FUN extern __declspec(dllimport)\r\n#  endif\r\n#endif\r\n#include <stdlib.h>\r\n#include <gsl/gsl_types.h>\r\n#include <gsl/gsl_errno.h>\r\n#include <gsl/gsl_inline.h>\r\n\r\n#undef __BEGIN_DECLS\r\n#undef __END_DECLS\r\n#ifdef __cplusplus\r\n# define __BEGIN_DECLS extern \"C\" {\r\n# define __END_DECLS }\r\n#else\r\n# define __BEGIN_DECLS /* empty */\r\n# define __END_DECLS /* empty */\r\n#endif\r\n\r\n__BEGIN_DECLS\r\n\r\ntypedef struct\r\n  {\r\n    const char *name;\r\n    unsigned long int max;\r\n    unsigned long int min;\r\n    size_t size;\r\n    void (*set) (void *state, unsigned long int seed);\r\n    unsigned long int (*get) (void *state);\r\n    double (*get_double) (void *state);\r\n  }\r\ngsl_rng_type;\r\n\r\ntypedef struct\r\n  {\r\n    const gsl_rng_type * type;\r\n    void *state;\r\n  }\r\ngsl_rng;\r\n\r\n\r\n/* These structs also need to appear in default.c so you can select\r\n   them via the environment variable GSL_RNG_TYPE */\r\n\r\nGSL_VAR const gsl_rng_type *gsl_rng_borosh13;\r\nGSL_VAR const gsl_rng_type *gsl_rng_coveyou;\r\nGSL_VAR const gsl_rng_type *gsl_rng_cmrg;\r\nGSL_VAR const gsl_rng_type *gsl_rng_fishman18;\r\nGSL_VAR const gsl_rng_type *gsl_rng_fishman20;\r\nGSL_VAR const gsl_rng_type *gsl_rng_fishman2x;\r\nGSL_VAR const gsl_rng_type *gsl_rng_gfsr4;\r\nGSL_VAR const gsl_rng_type *gsl_rng_knuthran;\r\nGSL_VAR const gsl_rng_type *gsl_rng_knuthran2;\r\nGSL_VAR const gsl_rng_type *gsl_rng_knuthran2002;\r\nGSL_VAR const gsl_rng_type *gsl_rng_lecuyer21;\r\nGSL_VAR const gsl_rng_type *gsl_rng_minstd;\r\nGSL_VAR const gsl_rng_type *gsl_rng_mrg;\r\nGSL_VAR const gsl_rng_type *gsl_rng_mt19937;\r\nGSL_VAR const gsl_rng_type *gsl_rng_mt19937_1999;\r\nGSL_VAR const gsl_rng_type *gsl_rng_mt19937_1998;\r\nGSL_VAR const gsl_rng_type *gsl_rng_r250;\r\nGSL_VAR const gsl_rng_type *gsl_rng_ran0;\r\nGSL_VAR const gsl_rng_type *gsl_rng_ran1;\r\nGSL_VAR const gsl_rng_type *gsl_rng_ran2;\r\nGSL_VAR const gsl_rng_type *gsl_rng_ran3;\r\nGSL_VAR const gsl_rng_type *gsl_rng_rand;\r\nGSL_VAR const gsl_rng_type *gsl_rng_rand48;\r\nGSL_VAR const gsl_rng_type *gsl_rng_random128_bsd;\r\nGSL_VAR const gsl_rng_type *gsl_rng_random128_glibc2;\r\nGSL_VAR const gsl_rng_type *gsl_rng_random128_libc5;\r\nGSL_VAR const gsl_rng_type *gsl_rng_random256_bsd;\r\nGSL_VAR const gsl_rng_type *gsl_rng_random256_glibc2;\r\nGSL_VAR const gsl_rng_type *gsl_rng_random256_libc5;\r\nGSL_VAR const gsl_rng_type *gsl_rng_random32_bsd;\r\nGSL_VAR const gsl_rng_type *gsl_rng_random32_glibc2;\r\nGSL_VAR const gsl_rng_type *gsl_rng_random32_libc5;\r\nGSL_VAR const gsl_rng_type *gsl_rng_random64_bsd;\r\nGSL_VAR const gsl_rng_type *gsl_rng_random64_glibc2;\r\nGSL_VAR const gsl_rng_type *gsl_rng_random64_libc5;\r\nGSL_VAR const gsl_rng_type *gsl_rng_random8_bsd;\r\nGSL_VAR const gsl_rng_type *gsl_rng_random8_glibc2;\r\nGSL_VAR const gsl_rng_type *gsl_rng_random8_libc5;\r\nGSL_VAR const gsl_rng_type *gsl_rng_random_bsd;\r\nGSL_VAR const gsl_rng_type *gsl_rng_random_glibc2;\r\nGSL_VAR const gsl_rng_type *gsl_rng_random_libc5;\r\nGSL_VAR const gsl_rng_type *gsl_rng_randu;\r\nGSL_VAR const gsl_rng_type *gsl_rng_ranf;\r\nGSL_VAR const gsl_rng_type *gsl_rng_ranlux;\r\nGSL_VAR const gsl_rng_type *gsl_rng_ranlux389;\r\nGSL_VAR const gsl_rng_type *gsl_rng_ranlxd1;\r\nGSL_VAR const gsl_rng_type *gsl_rng_ranlxd2;\r\nGSL_VAR const gsl_rng_type *gsl_rng_ranlxs0;\r\nGSL_VAR const gsl_rng_type *gsl_rng_ranlxs1;\r\nGSL_VAR const gsl_rng_type *gsl_rng_ranlxs2;\r\nGSL_VAR const gsl_rng_type *gsl_rng_ranmar;\r\nGSL_VAR const gsl_rng_type *gsl_rng_slatec;\r\nGSL_VAR const gsl_rng_type *gsl_rng_taus;\r\nGSL_VAR const gsl_rng_type *gsl_rng_taus2;\r\nGSL_VAR const gsl_rng_type *gsl_rng_taus113;\r\nGSL_VAR const gsl_rng_type *gsl_rng_transputer;\r\nGSL_VAR const gsl_rng_type *gsl_rng_tt800;\r\nGSL_VAR const gsl_rng_type *gsl_rng_uni;\r\nGSL_VAR const gsl_rng_type *gsl_rng_uni32;\r\nGSL_VAR const gsl_rng_type *gsl_rng_vax;\r\nGSL_VAR const gsl_rng_type *gsl_rng_waterman14;\r\nGSL_VAR const gsl_rng_type *gsl_rng_zuf;\r\n\r\nGSL_FUN const gsl_rng_type ** gsl_rng_types_setup(void);\r\n\r\nGSL_VAR const gsl_rng_type *gsl_rng_default;\r\nGSL_VAR unsigned long int gsl_rng_default_seed;\r\n\r\nGSL_FUN gsl_rng *gsl_rng_alloc (const gsl_rng_type * T);\r\nGSL_FUN int gsl_rng_memcpy (gsl_rng * dest, const gsl_rng * src);\r\nGSL_FUN gsl_rng *gsl_rng_clone (const gsl_rng * r);\r\n\r\nGSL_FUN void gsl_rng_free (gsl_rng * r);\r\n\r\nGSL_FUN void gsl_rng_set (const gsl_rng * r, unsigned long int seed);\r\nGSL_FUN unsigned long int gsl_rng_max (const gsl_rng * r);\r\nGSL_FUN unsigned long int gsl_rng_min (const gsl_rng * r);\r\nGSL_FUN const char *gsl_rng_name (const gsl_rng * r);\r\n\r\nGSL_FUN int gsl_rng_fread (FILE * stream, gsl_rng * r);\r\nGSL_FUN int gsl_rng_fwrite (FILE * stream, const gsl_rng * r);\r\n\r\nGSL_FUN size_t gsl_rng_size (const gsl_rng * r);\r\nGSL_FUN void * gsl_rng_state (const gsl_rng * r);\r\n\r\nGSL_FUN void gsl_rng_print_state (const gsl_rng * r);\r\n\r\nGSL_FUN const gsl_rng_type * gsl_rng_env_setup (void);\r\n\r\nGSL_FUN INLINE_DECL unsigned long int gsl_rng_get (const gsl_rng * r);\r\nGSL_FUN INLINE_DECL double gsl_rng_uniform (const gsl_rng * r);\r\nGSL_FUN INLINE_DECL double gsl_rng_uniform_pos (const gsl_rng * r);\r\nGSL_FUN INLINE_DECL unsigned long int gsl_rng_uniform_int (const gsl_rng * r, unsigned long int n);\r\n\r\n#ifdef HAVE_INLINE\r\n\r\nINLINE_FUN unsigned long int\r\ngsl_rng_get (const gsl_rng * r)\r\n{\r\n  return (r->type->get) (r->state);\r\n}\r\n\r\nINLINE_FUN double\r\ngsl_rng_uniform (const gsl_rng * r)\r\n{\r\n  return (r->type->get_double) (r->state);\r\n}\r\n\r\nINLINE_FUN double\r\ngsl_rng_uniform_pos (const gsl_rng * r)\r\n{\r\n  double x ;\r\n  do\r\n    {\r\n      x = (r->type->get_double) (r->state) ;\r\n    }\r\n  while (x == 0) ;\r\n\r\n  return x ;\r\n}\r\n\r\n/* Note: to avoid integer overflow in (range+1) we work with scale =\r\n   range/n = (max-min)/n rather than scale=(max-min+1)/n, this reduces\r\n   efficiency slightly but avoids having to check for the out of range\r\n   value.  Note that range is typically O(2^32) so the addition of 1\r\n   is negligible in most usage. */\r\n\r\nINLINE_FUN unsigned long int\r\ngsl_rng_uniform_int (const gsl_rng * r, unsigned long int n)\r\n{\r\n  unsigned long int offset = r->type->min;\r\n  unsigned long int range = r->type->max - offset;\r\n  unsigned long int scale;\r\n  unsigned long int k;\r\n\r\n  if (n > range || n == 0) \r\n    {\r\n      GSL_ERROR_VAL (\"invalid n, either 0 or exceeds maximum value of generator\",\r\n                     GSL_EINVAL, 0) ;\r\n    }\r\n\r\n  scale = range / n;\r\n\r\n  do\r\n    {\r\n      k = (((r->type->get) (r->state)) - offset) / scale;\r\n    }\r\n  while (k >= n);\r\n\r\n  return k;\r\n}\r\n#endif /* HAVE_INLINE */\r\n\r\n__END_DECLS\r\n\r\n#endif /* __GSL_RNG_H__ */\r\n", "meta": {"hexsha": "bc343e18d87f3aa079d9d4841d6e2b9e7424e4e2", "size": 7569, "ext": "h", "lang": "C", "max_stars_repo_path": "deps/include/gsl/gsl_rng.h", "max_stars_repo_name": "berkus/music-cs", "max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z", "max_issues_repo_path": "deps/include/gsl/gsl_rng.h", "max_issues_repo_name": "berkus/music-cs", "max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z", "max_forks_repo_path": "deps/include/gsl/gsl_rng.h", "max_forks_repo_name": "berkus/music-cs", "max_forks_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 33.1973684211, "max_line_length": 100, "alphanum_fraction": 0.7505615009, "num_tokens": 2212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37754065479083276, "lm_q2_score": 0.05500528519522229, "lm_q1q2_score": 0.020766731389560724}}
{"text": "// Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at\n// the Lawrence Livermore National Laboratory. LLNL-CODE-734707. All Rights\n// reserved. See files LICENSE and NOTICE for details.\n//\n// This file is part of CEED, a collection of benchmarks, miniapps, software\n// libraries and APIs for efficient high-order finite element and spectral\n// element discretizations for exascale applications. For more information and\n// source code availability see http://github.com/ceed.\n//\n// The CEED research is supported by the Exascale Computing Project 17-SC-20-SC,\n// a collaborative effort of two U.S. Department of Energy organizations (Office\n// of Science and the National Nuclear Security Administration) responsible for\n// the planning and preparation of a capable exascale ecosystem, including\n// software, applications, hardware, advanced system engineering and early\n// testbed platforms, in support of the nation's exascale computing imperative.\n\n#ifndef setuparea_h\n#define setuparea_h\n\n#include <ceed.h>\n#include <petsc.h>\n#include <petscdmplex.h>\n#include <petscfe.h>\n#include <stdbool.h>\n#include <string.h>\n#include \"qfunctions/area/areacube.h\"\n#include \"qfunctions/area/areasphere.h\"\n\n#if PETSC_VERSION_LT(3,14,0)\n#  define DMPlexGetClosureIndices(a,b,c,d,e,f,g,h,i) DMPlexGetClosureIndices(a,b,c,d,f,g,i)\n#  define DMPlexRestoreClosureIndices(a,b,c,d,e,f,g,h,i) DMPlexRestoreClosureIndices(a,b,c,d,f,g,i)\n#endif\n\n#if PETSC_VERSION_LT(3,14,0)\n#  define DMPlexCreateSphereMesh(a,b,c,d,e) DMPlexCreateSphereMesh(a,b,c,e)\n#endif\n\n// -----------------------------------------------------------------------------\n// PETSc Operator Structs\n// -----------------------------------------------------------------------------\n\n// Data for PETSc\ntypedef struct User_ *User;\nstruct User_ {\n  MPI_Comm comm;\n  DM dm;\n  Vec Xloc, Yloc, diag;\n  CeedVector xceed, yceed;\n  CeedOperator op;\n  Ceed ceed;\n};\n\n// -----------------------------------------------------------------------------\n// libCEED Data Struct\n// -----------------------------------------------------------------------------\n\n// libCEED data struct for level\ntypedef struct CeedData_ *CeedData;\nstruct CeedData_ {\n  Ceed ceed;\n  CeedBasis basisx, basisu;\n  CeedElemRestriction Erestrictx, Erestrictu, Erestrictqdi;\n  CeedQFunction qf_apply;\n  CeedOperator op_apply, op_restrict, op_interp;\n  CeedVector qdata, uceed, vceed;\n};\n\n// -----------------------------------------------------------------------------\n// Problem Option Data\n// -----------------------------------------------------------------------------\n\n// Problem options\ntypedef enum {\n  CUBE = 0, SPHERE = 1\n} problemType;\nstatic const char *const problemTypes[] = {\"cube\", \"sphere\",\n                                           \"problemType\", \"AREA\", NULL\n                                          };\n\n// Problem specific data\ntypedef struct {\n  CeedInt ncompu, ncompx, qdatasize, qextra, topodim;\n  CeedQFunctionUser setupgeo, apply;\n  const char *setupgeofname, *applyfname;\n  CeedEvalMode inmode, outmode;\n  CeedQuadMode qmode;\n} problemData;\n\nstatic problemData problemOptions[6] = {\n  [CUBE] = {\n    .ncompx = 3,\n    .ncompu = 1,\n    .topodim = 2,\n    .qdatasize = 1,\n    .qextra = 1,\n    .setupgeo = SetupMassGeoCube,\n    .apply = Mass,\n    .setupgeofname = SetupMassGeoCube_loc,\n    .applyfname = Mass_loc,\n    .inmode = CEED_EVAL_INTERP,\n    .outmode = CEED_EVAL_INTERP,\n    .qmode = CEED_GAUSS\n  },\n  [SPHERE] = {\n    .ncompx = 3,\n    .ncompu = 1,\n    .topodim = 2,\n    .qdatasize = 1,\n    .qextra = 1,\n    .setupgeo = SetupMassGeoSphere,\n    .apply = Mass,\n    .setupgeofname = SetupMassGeoSphere_loc,\n    .applyfname = Mass_loc,\n    .inmode = CEED_EVAL_INTERP,\n    .outmode = CEED_EVAL_INTERP,\n    .qmode = CEED_GAUSS\n  }\n};\n\n// -----------------------------------------------------------------------------\n// PETSc sphere auxiliary functions\n// -----------------------------------------------------------------------------\n\n// Utility function taken from petsc/src/dm/impls/plex/examples/tutorials/ex7.c\nstatic PetscErrorCode ProjectToUnitSphere(DM dm) {\n  Vec            coordinates;\n  PetscScalar   *coords;\n  PetscInt       Nv, v, dim, d;\n  PetscErrorCode ierr;\n\n  PetscFunctionBeginUser;\n  ierr = DMGetCoordinatesLocal(dm, &coordinates); CHKERRQ(ierr);\n  ierr = VecGetLocalSize(coordinates, &Nv); CHKERRQ(ierr);\n  ierr = VecGetBlockSize(coordinates, &dim); CHKERRQ(ierr);\n  Nv  /= dim;\n  ierr = VecGetArray(coordinates, &coords); CHKERRQ(ierr);\n  for (v = 0; v < Nv; ++v) {\n    PetscReal r = 0.0;\n\n    for (d = 0; d < dim; ++d) r += PetscSqr(PetscRealPart(coords[v*dim+d]));\n    r = PetscSqrtReal(r);\n    for (d = 0; d < dim; ++d) coords[v*dim+d] /= r;\n  }\n  ierr = VecRestoreArray(coordinates, &coords); CHKERRQ(ierr);\n  PetscFunctionReturn(0);\n}\n\n// -----------------------------------------------------------------------------\n// PETSc Finite Element space setup\n// -----------------------------------------------------------------------------\n\n// Create FE by degree\nstatic int PetscFECreateByDegree(DM dm, PetscInt dim, PetscInt Nc,\n                                 PetscBool isSimplex, const char prefix[],\n                                 PetscInt order, PetscFE *fem) {\n  PetscQuadrature q, fq;\n  DM              K;\n  PetscSpace      P;\n  PetscDualSpace  Q;\n  PetscInt        quadPointsPerEdge;\n  PetscBool       tensor = isSimplex ? PETSC_FALSE : PETSC_TRUE;\n  PetscErrorCode  ierr;\n\n  PetscFunctionBeginUser;\n  /* Create space */\n  ierr = PetscSpaceCreate(PetscObjectComm((PetscObject) dm), &P); CHKERRQ(ierr);\n  ierr = PetscObjectSetOptionsPrefix((PetscObject) P, prefix); CHKERRQ(ierr);\n  ierr = PetscSpacePolynomialSetTensor(P, tensor); CHKERRQ(ierr);\n  ierr = PetscSpaceSetFromOptions(P); CHKERRQ(ierr);\n  ierr = PetscSpaceSetNumComponents(P, Nc); CHKERRQ(ierr);\n  ierr = PetscSpaceSetNumVariables(P, dim); CHKERRQ(ierr);\n  ierr = PetscSpaceSetDegree(P, order, order); CHKERRQ(ierr);\n  ierr = PetscSpaceSetUp(P); CHKERRQ(ierr);\n  ierr = PetscSpacePolynomialGetTensor(P, &tensor); CHKERRQ(ierr);\n  /* Create dual space */\n  ierr = PetscDualSpaceCreate(PetscObjectComm((PetscObject) dm), &Q);\n  CHKERRQ(ierr);\n  ierr = PetscDualSpaceSetType(Q,PETSCDUALSPACELAGRANGE); CHKERRQ(ierr);\n  ierr = PetscObjectSetOptionsPrefix((PetscObject) Q, prefix); CHKERRQ(ierr);\n  ierr = PetscDualSpaceCreateReferenceCell(Q, dim, isSimplex, &K); CHKERRQ(ierr);\n  ierr = PetscDualSpaceSetDM(Q, K); CHKERRQ(ierr);\n  ierr = DMDestroy(&K); CHKERRQ(ierr);\n  ierr = PetscDualSpaceSetNumComponents(Q, Nc); CHKERRQ(ierr);\n  ierr = PetscDualSpaceSetOrder(Q, order); CHKERRQ(ierr);\n  ierr = PetscDualSpaceLagrangeSetTensor(Q, tensor); CHKERRQ(ierr);\n  ierr = PetscDualSpaceSetFromOptions(Q); CHKERRQ(ierr);\n  ierr = PetscDualSpaceSetUp(Q); CHKERRQ(ierr);\n  /* Create element */\n  ierr = PetscFECreate(PetscObjectComm((PetscObject) dm), fem); CHKERRQ(ierr);\n  ierr = PetscObjectSetOptionsPrefix((PetscObject) *fem, prefix); CHKERRQ(ierr);\n  ierr = PetscFESetFromOptions(*fem); CHKERRQ(ierr);\n  ierr = PetscFESetBasisSpace(*fem, P); CHKERRQ(ierr);\n  ierr = PetscFESetDualSpace(*fem, Q); CHKERRQ(ierr);\n  ierr = PetscFESetNumComponents(*fem, Nc); CHKERRQ(ierr);\n  ierr = PetscFESetUp(*fem); CHKERRQ(ierr);\n  ierr = PetscSpaceDestroy(&P); CHKERRQ(ierr);\n  ierr = PetscDualSpaceDestroy(&Q); CHKERRQ(ierr);\n  /* Create quadrature */\n  quadPointsPerEdge = PetscMax(order + 1,1);\n  if (isSimplex) {\n    ierr = PetscDTStroudConicalQuadrature(dim,   1, quadPointsPerEdge, -1.0, 1.0,\n                                          &q); CHKERRQ(ierr);\n    ierr = PetscDTStroudConicalQuadrature(dim-1, 1, quadPointsPerEdge, -1.0, 1.0,\n                                          &fq); CHKERRQ(ierr);\n  } else {\n    ierr = PetscDTGaussTensorQuadrature(dim,   1, quadPointsPerEdge, -1.0, 1.0,\n                                        &q); CHKERRQ(ierr);\n    ierr = PetscDTGaussTensorQuadrature(dim-1, 1, quadPointsPerEdge, -1.0, 1.0,\n                                        &fq); CHKERRQ(ierr);\n  }\n  ierr = PetscFESetQuadrature(*fem, q); CHKERRQ(ierr);\n  ierr = PetscFESetFaceQuadrature(*fem, fq); CHKERRQ(ierr);\n  ierr = PetscQuadratureDestroy(&q); CHKERRQ(ierr);\n  ierr = PetscQuadratureDestroy(&fq); CHKERRQ(ierr);\n\n  PetscFunctionReturn(0);\n}\n\n// -----------------------------------------------------------------------------\n// PETSc Setup for Level\n// -----------------------------------------------------------------------------\n\n// This function sets up a DM for a given degree\nstatic int SetupDMByDegree(DM dm, PetscInt degree, PetscInt ncompu,\n                           PetscInt dim) {\n  PetscInt ierr;\n  PetscFE fe;\n\n  PetscFunctionBeginUser;\n\n  // Setup FE\n  ierr = PetscFECreateByDegree(dm, dim, ncompu, PETSC_FALSE, NULL, degree, &fe);\n  CHKERRQ(ierr);\n  ierr = DMAddField(dm, NULL, (PetscObject)fe); CHKERRQ(ierr);\n\n  // Setup DM\n  ierr = DMCreateDS(dm); CHKERRQ(ierr);\n  ierr = DMPlexSetClosurePermutationTensor(dm, PETSC_DETERMINE, NULL);\n  CHKERRQ(ierr);\n  ierr = PetscFEDestroy(&fe); CHKERRQ(ierr);\n\n  PetscFunctionReturn(0);\n}\n\n// -----------------------------------------------------------------------------\n// libCEED Setup for Level\n// -----------------------------------------------------------------------------\n\n// Destroy libCEED operator objects\nstatic PetscErrorCode CeedDataDestroy(CeedData data) {\n  PetscInt ierr;\n\n  CeedVectorDestroy(&data->qdata);\n  CeedVectorDestroy(&data->uceed);\n  CeedVectorDestroy(&data->vceed);\n  CeedBasisDestroy(&data->basisx);\n  CeedBasisDestroy(&data->basisu);\n  CeedElemRestrictionDestroy(&data->Erestrictu);\n  CeedElemRestrictionDestroy(&data->Erestrictx);\n  CeedElemRestrictionDestroy(&data->Erestrictqdi);\n  CeedQFunctionDestroy(&data->qf_apply);\n  CeedOperatorDestroy(&data->op_apply);\n  ierr = PetscFree(data); CHKERRQ(ierr);\n\n  PetscFunctionReturn(0);\n}\n\n// Auxiliary function to define CEED restrictions from DMPlex data\nstatic int CreateRestrictionPlex(Ceed ceed, CeedInt P, CeedInt ncomp,\n                                 CeedElemRestriction *Erestrict, DM dm) {\n  PetscInt ierr;\n  PetscInt c, cStart, cEnd, nelem, nnodes, *erestrict, eoffset;\n  PetscSection section;\n  Vec Uloc;\n\n  PetscFunctionBegin;\n\n  // Get Nelem\n  ierr = DMGetSection(dm, &section); CHKERRQ(ierr);\n  ierr = DMPlexGetHeightStratum(dm, 0, &cStart,& cEnd); CHKERRQ(ierr);\n  nelem = cEnd - cStart;\n\n  // Get indices\n  ierr = PetscMalloc1(nelem*P*P, &erestrict); CHKERRQ(ierr);\n  for (c=cStart, eoffset = 0; c<cEnd; c++) {\n    PetscInt numindices, *indices, i;\n    ierr = DMPlexGetClosureIndices(dm, section, section, c, PETSC_TRUE,\n                                   &numindices, &indices, NULL, NULL);\n    CHKERRQ(ierr);\n    for (i=0; i<numindices; i+=ncomp) {\n      for (PetscInt j=0; j<ncomp; j++) {\n        if (indices[i+j] != indices[i] + (PetscInt)(copysign(j, indices[i])))\n          SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP,\n                   \"Cell %D closure indices not interlaced\", c);\n      }\n      // NO BC on closed surfaces\n      PetscInt loc = indices[i];\n      erestrict[eoffset++] = loc;\n    }\n    ierr = DMPlexRestoreClosureIndices(dm, section, section, c, PETSC_TRUE,\n                                       &numindices, &indices, NULL, NULL);\n    CHKERRQ(ierr);\n  }\n\n  // Setup CEED restriction\n  ierr = DMGetLocalVector(dm, &Uloc); CHKERRQ(ierr);\n  ierr = VecGetLocalSize(Uloc, &nnodes); CHKERRQ(ierr);\n\n  ierr = DMRestoreLocalVector(dm, &Uloc); CHKERRQ(ierr);\n  CeedElemRestrictionCreate(ceed, nelem, P*P, ncomp, 1, nnodes,\n                            CEED_MEM_HOST, CEED_COPY_VALUES, erestrict,\n                            Erestrict);\n  ierr = PetscFree(erestrict); CHKERRQ(ierr);\n\n  PetscFunctionReturn(0);\n}\n\n// Set up libCEED for a given degree\nstatic int SetupLibceedByDegree(DM dm, Ceed ceed, CeedInt degree,\n                                CeedInt topodim, CeedInt qextra,\n                                PetscInt ncompx, PetscInt ncompu,\n                                PetscInt xlsize, problemType problemChoice,\n                                CeedData data) {\n  int ierr;\n  DM dmcoord;\n  Vec coords;\n  const PetscScalar *coordArray;\n  CeedBasis basisx, basisu;\n  CeedElemRestriction Erestrictx, Erestrictu, Erestrictqdi;\n  CeedQFunction qf_setupgeo, qf_apply;\n  CeedOperator op_setupgeo, op_apply;\n  CeedVector xcoord, qdata, uceed, vceed;\n  CeedInt P, Q, cStart, cEnd, nelem,\n          qdatasize = problemOptions[problemChoice].qdatasize;\n\n  // CEED bases\n  P = degree + 1;\n  Q = P + qextra;\n  CeedBasisCreateTensorH1Lagrange(ceed, topodim, ncompu, P, Q,\n                                  problemOptions[problemChoice].qmode, &basisu);\n  CeedBasisCreateTensorH1Lagrange(ceed, topodim, ncompx, 2, Q,\n                                  problemOptions[problemChoice].qmode, &basisx);\n\n  // CEED restrictions\n  ierr = DMGetCoordinateDM(dm, &dmcoord); CHKERRQ(ierr);\n  ierr = DMPlexSetClosurePermutationTensor(dmcoord, PETSC_DETERMINE, NULL);\n  CHKERRQ(ierr);\n\n  ierr = CreateRestrictionPlex(ceed, 2, ncompx, &Erestrictx, dmcoord);\n  CHKERRQ(ierr);\n  ierr = CreateRestrictionPlex(ceed, P, ncompu, &Erestrictu, dm); CHKERRQ(ierr);\n\n  ierr = DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd); CHKERRQ(ierr);\n  nelem = cEnd - cStart;\n\n  CeedElemRestrictionCreateStrided(ceed, nelem, Q*Q, qdatasize,\n                                   qdatasize*nelem*Q*Q,\n                                   CEED_STRIDES_BACKEND, &Erestrictqdi);\n\n  // Element coordinates\n  ierr = DMGetCoordinatesLocal(dm, &coords); CHKERRQ(ierr);\n  ierr = VecGetArrayRead(coords, &coordArray); CHKERRQ(ierr);\n\n  CeedElemRestrictionCreateVector(Erestrictx, &xcoord, NULL);\n  CeedVectorSetArray(xcoord, CEED_MEM_HOST, CEED_COPY_VALUES,\n                     (PetscScalar *)coordArray);\n  ierr = VecRestoreArrayRead(coords, &coordArray);\n\n  // Create the vectors that will be needed in setup and apply\n  CeedInt nqpts;\n  CeedBasisGetNumQuadraturePoints(basisu, &nqpts);\n  CeedVectorCreate(ceed, qdatasize*nelem*nqpts, &qdata);\n  CeedVectorCreate(ceed, xlsize, &uceed);\n  CeedVectorCreate(ceed, xlsize, &vceed);\n\n  // Create the Q-function that builds the operator (i.e. computes its\n  // quadrature data) and set its context data\n  CeedQFunctionCreateInterior(ceed, 1, problemOptions[problemChoice].setupgeo,\n                              problemOptions[problemChoice].setupgeofname,\n                              &qf_setupgeo);\n  CeedQFunctionAddInput(qf_setupgeo, \"x\", ncompx, CEED_EVAL_INTERP);\n  CeedQFunctionAddInput(qf_setupgeo, \"dx\", ncompx*topodim, CEED_EVAL_GRAD);\n  CeedQFunctionAddInput(qf_setupgeo, \"weight\", 1, CEED_EVAL_WEIGHT);\n  CeedQFunctionAddOutput(qf_setupgeo, \"qdata\", qdatasize, CEED_EVAL_NONE);\n\n  // Set up the mass operator\n  CeedQFunctionCreateInterior(ceed, 1, problemOptions[problemChoice].apply,\n                              problemOptions[problemChoice].applyfname,\n                              &qf_apply);\n  CeedQFunctionAddInput(qf_apply, \"u\", ncompu,\n                        problemOptions[problemChoice].inmode);\n  CeedQFunctionAddInput(qf_apply, \"qdata\", qdatasize, CEED_EVAL_NONE);\n  CeedQFunctionAddOutput(qf_apply, \"v\", ncompu,\n                         problemOptions[problemChoice].outmode);\n\n  // Create the operator that builds the quadrature data for the operator\n  CeedOperatorCreate(ceed, qf_setupgeo, NULL, NULL, &op_setupgeo);\n  CeedOperatorSetField(op_setupgeo, \"x\", Erestrictx, basisx,\n                       CEED_VECTOR_ACTIVE);\n  CeedOperatorSetField(op_setupgeo, \"dx\", Erestrictx, basisx,\n                       CEED_VECTOR_ACTIVE);\n  CeedOperatorSetField(op_setupgeo, \"weight\", CEED_ELEMRESTRICTION_NONE, basisx,\n                       CEED_VECTOR_NONE);\n  CeedOperatorSetField(op_setupgeo, \"qdata\", Erestrictqdi,\n                       CEED_BASIS_COLLOCATED, CEED_VECTOR_ACTIVE);\n\n  // Create the mass or diff operator\n  CeedOperatorCreate(ceed, qf_apply, NULL, NULL, &op_apply);\n  CeedOperatorSetField(op_apply, \"u\", Erestrictu, basisu, CEED_VECTOR_ACTIVE);\n  CeedOperatorSetField(op_apply, \"qdata\", Erestrictqdi, CEED_BASIS_COLLOCATED,\n                       qdata);\n  CeedOperatorSetField(op_apply, \"v\", Erestrictu, basisu, CEED_VECTOR_ACTIVE);\n\n  // Setup qdata\n  CeedOperatorApply(op_setupgeo, xcoord, qdata, CEED_REQUEST_IMMEDIATE);\n\n  // Cleanup\n  CeedQFunctionDestroy(&qf_setupgeo);\n  CeedOperatorDestroy(&op_setupgeo);\n  CeedVectorDestroy(&xcoord);\n\n  // Save libCEED data\n  data->basisx = basisx;\n  data->basisu = basisu;\n  data->Erestrictx = Erestrictx;\n  data->Erestrictu = Erestrictu;\n  data->Erestrictqdi = Erestrictqdi;\n  data->qf_apply = qf_apply;\n  data->op_apply = op_apply;\n  data->qdata = qdata;\n  data->uceed = uceed;\n  data->vceed = vceed;\n\n  PetscFunctionReturn(0);\n}\n\n#endif // setuparea_h\n", "meta": {"hexsha": "df2a7ecae0b48bf7a5c8a18d701d5ef12827b9c7", "size": 16724, "ext": "h", "lang": "C", "max_stars_repo_path": "examples/petsc/setuparea.h", "max_stars_repo_name": "barker29/libCEED", "max_stars_repo_head_hexsha": "3d576824e8d990e1f48c6609089904bee9170514", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/petsc/setuparea.h", "max_issues_repo_name": "barker29/libCEED", "max_issues_repo_head_hexsha": "3d576824e8d990e1f48c6609089904bee9170514", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/petsc/setuparea.h", "max_forks_repo_name": "barker29/libCEED", "max_forks_repo_head_hexsha": "3d576824e8d990e1f48c6609089904bee9170514", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-30T23:13:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-30T23:13:18.000Z", "avg_line_length": 38.1826484018, "max_line_length": 99, "alphanum_fraction": 0.6334608945, "num_tokens": 4525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3998116264369279, "lm_q2_score": 0.051845469213544056, "lm_q1q2_score": 0.020728421369652722}}
{"text": "/* Odeint solver */\n#include <pygsl/utils.h>\n#include <pygsl/block_helpers.h>\n#include <pygsl/error_helpers.h>\n#include <Python.h>\n#include <gsl/gsl_odeiv.h>\n#include <gsl/gsl_errno.h>\n\nchar odeiv_module_doc[] = \"XXX odeiv module doc missing!\\n\";\n\nstatic char this_file[] = __FILE__;\nstatic PyObject *module = NULL; /* set by initodeiv */ \n\n#if 0\nstatic void\t\t\t/* generic instance destruction */\ngeneric_dealloc (PyObject *self)\n{\n  DEBUG_MESS(1, \" *** generic_dealloc %p\\n\", (void *) self);\n  PyMem_Free(self);\n}\n#endif \n\ntypedef struct {\n     PyObject_HEAD\n     gsl_odeiv_step * step;\n     gsl_odeiv_system system;\n     PyObject *py_func;\n     PyObject *py_jac;\n     PyObject *arguments;\n     jmp_buf buffer;\n}\nPyGSL_odeiv_step;\n\ntypedef struct {\n     PyObject_HEAD\n     PyGSL_odeiv_step * step;\n     gsl_odeiv_control * control;\n} PyGSL_odeiv_control;\n\ntypedef struct {\n     PyObject_HEAD\n     PyGSL_odeiv_step * step;\n     PyGSL_odeiv_control * control;\n     gsl_odeiv_evolve * evolve;\n} PyGSL_odeiv_evolve;\n\n/*---------------------------------------------------------------------------\n * Declaration of the various Methods\n *---------------------------------------------------------------------------*/\n/*\n * stepper\n */\nstatic int \nPyGSL_odeiv_func(double t, const double y[], double f[], void *params);\nstatic int \nPyGSL_odeiv_jac(double t, const double y[], double *dfdy, double dfdt[], \n\t\tvoid *params);\nstatic PyObject *\nPyGSL_odeiv_step_apply(PyGSL_odeiv_step *self, PyObject *args);\nstatic PyObject *\nPyGSL_odeiv_step_reset(PyGSL_odeiv_step *self, PyObject *args);\nstatic PyObject *\nPyGSL_odeiv_step_name(PyGSL_odeiv_step *self, PyObject *args);\nstatic PyObject *\nPyGSL_odeiv_step_order(PyGSL_odeiv_step *self, PyObject *args);\nstatic void \nPyGSL_odeiv_step_free(PyGSL_odeiv_step * self);\n\n/*\n * control \n */\nstatic PyObject *\nPyGSL_odeiv_control_hadjust(PyGSL_odeiv_control *self, PyObject *args);\nstatic PyObject *\nPyGSL_odeiv_control_name(PyGSL_odeiv_control *self, PyObject *args);\nstatic void \nPyGSL_odeiv_control_free(PyGSL_odeiv_control * self);\n\n/*\n * evolve\n */\nstatic PyObject *\nPyGSL_odeiv_evolve_apply(PyGSL_odeiv_evolve *self, PyObject *args);\nstatic PyObject *\nPyGSL_odeiv_evolve_apply_array(PyGSL_odeiv_evolve *self, PyObject *args);\nstatic PyObject *\nPyGSL_odeiv_evolve_reset(PyGSL_odeiv_evolve *self, PyObject *args);\nstatic void \nPyGSL_odeiv_evolve_free(PyGSL_odeiv_evolve * self);\n/*---------------------------------------------------------------------------*/\n\n\n\nstatic char  PyGSL_odeiv_step_doc[] = \"XXX Documentation missing\\n\"; \nstatic char  PyGSL_odeiv_control_doc[] = \"XXX Documentation missing\\n\";\nstatic char  PyGSL_odeiv_evolve_doc[] = \"XXX Documentation missing\\n\"; \n       \nstatic char odeiv_step_apply_doc[] =  \"XXX Documentation missing\\n\"; \nstatic char odeiv_step_name_doc[] =  \"XXX Documentation missing\\n\"; \nstatic char odeiv_step_order_doc[] =  \"XXX Documentation missing\\n\"; \nstatic char odeiv_step_reset_doc[] =  \"XXX Documentation missing\\n\"; \n       \nstatic char odeiv_control_name_doc[] =  \"XXX Documentation missing\\n\"; \nstatic char odeiv_control_hadjust_doc[] =  \"XXX Documentation missing\\n\"; \n\n\nstatic char odeiv_evolve_apply_doc[] =  \"XXX Documentation missing\\n\"; \nstatic char odeiv_evolve_apply_array_doc[] =  \"XXX Documentation missing\\n\"; \nstatic char odeiv_evolve_reset_doc[] =  \"XXX Documentation missing\\n\";\n\nstatic char * odeiv_step_init_err_msg = \"odeiv_step.__init__\";\n\nstatic struct PyMethodDef PyGSL_odeiv_step_methods[] = {\n     {\"apply\", (PyCFunction) PyGSL_odeiv_step_apply, METH_VARARGS, odeiv_step_apply_doc},\n     {\"reset\", (PyCFunction) PyGSL_odeiv_step_reset, METH_VARARGS, odeiv_step_reset_doc},\n     {\"name\",  (PyCFunction) PyGSL_odeiv_step_name,  METH_VARARGS, odeiv_step_name_doc},\n     {\"order\", (PyCFunction) PyGSL_odeiv_step_order, METH_VARARGS, odeiv_step_order_doc},\n     {NULL, NULL}\n};\nstatic struct PyMethodDef PyGSL_odeiv_control_methods[] = {\n     {\"hadjust\", (PyCFunction) PyGSL_odeiv_control_hadjust, METH_VARARGS, odeiv_control_hadjust_doc},\n     {\"name\",  (PyCFunction) PyGSL_odeiv_control_name,  METH_VARARGS, odeiv_control_name_doc},\n     {NULL, NULL}\n};\n\nstatic struct PyMethodDef PyGSL_odeiv_evolve_methods[] = {\n     {\"apply\", (PyCFunction) PyGSL_odeiv_evolve_apply, METH_VARARGS, odeiv_evolve_apply_doc},\n     {\"reset\", (PyCFunction) PyGSL_odeiv_evolve_reset, METH_VARARGS, odeiv_evolve_reset_doc},\n     {\"apply_array\", (PyCFunction) PyGSL_odeiv_evolve_apply_array, METH_VARARGS, odeiv_evolve_apply_array_doc},\n     {NULL, NULL}\n};\n\n\n\n\n\n\n#define PyGSL_ODEIV_GENERIC_ALL                                                           \\\nstatic PyObject *\t\t\t\t\t\t\t\t\t  \\\nPyGSL_ODEIV_GENERIC_GETATTR(PyGSL_ODEIV_GENERIC *self, char *name)\t\t          \\\n{\t\t\t\t\t\t\t\t\t\t\t  \\\n     PyObject *tmp = NULL;\t\t\t\t\t\t\t\t  \\\n\t\t\t\t\t\t\t\t\t\t\t  \\\n     FUNC_MESS_BEGIN();\t\t\t\t\t\t\t\t\t  \\\n     tmp = Py_FindMethod(PyGSL_ODEIV_GENERIC_METHODS, (PyObject *) self, name);\t          \\\n     if(NULL == tmp){\t  \t\t\t\t\t\t\t\t  \\\n\t  PyGSL_add_traceback(module, __FILE__, \"odeiv.__attr__\", __LINE__ - 1);\t  \\\n\t  return NULL;\t\t\t\t\t\t\t\t\t  \\\n     }\t\t\t\t\t\t\t\t\t\t\t  \\\n     FUNC_MESS_END();\t\t\t\t\t\t\t\t\t  \\\n     return tmp;                                                                          \\\n}                                                                                         \\\nstatic PyTypeObject PyGSL_ODEIV_GENERIC_PYTYPE = {\t\t\t\t\t  \\\n  PyObject_HEAD_INIT(NULL)\t/* fix up the type slot in initcrng */\t\t\t  \\\n  0,\t\t\t\t/* ob_size */\t\t\t\t\t\t  \\\n  PyGSL_ODEIV_GENERIC_NAME,\t\t\t/* tp_name */\t\t\t          \\\n  sizeof(PyGSL_ODEIV_GENERIC),  /* tp_basicsize */\t\t\t\t\t  \\\n  0,\t\t\t\t/* tp_itemsize */\t\t\t\t\t  \\\n\t\t\t\t\t\t\t\t\t\t\t  \\\n  /* standard methods */\t\t\t\t\t\t\t\t  \\\n  (destructor)  PyGSL_ODEIV_GENERIC_DELETE,       /* tp_dealloc  ref-count==0  */\t  \\\n  (printfunc)   0,\t\t                      /* tp_print    \"print x\"     */\t  \\\n  (getattrfunc) PyGSL_ODEIV_GENERIC_GETATTR,       /* tp_getattr  \"x.attr\"      */\t  \\\n  (setattrfunc) 0,\t\t   /* tp_setattr  \"x.attr=v\"    */\t\t\t  \\\n  (cmpfunc)     0,\t\t   /* tp_compare  \"x > y\"       */\t\t\t  \\\n  (reprfunc)    0,                 /* tp_repr     `x`, print x  */\t\t\t  \\\n\t\t\t\t\t\t\t\t\t\t\t  \\\n  /* type categories */\t\t\t\t\t\t\t\t\t  \\\n  0,\t\t\t\t/* tp_as_number   +,-,*,/,%,&,>>,pow...*/\t\t  \\\n  0,\t\t\t\t/* tp_as_sequence +,[i],[i:j],len, ...*/\t\t  \\\n  0,\t\t\t\t/* tp_as_mapping  [key], len, ...*/\t\t\t  \\\n\t\t\t\t\t\t\t\t\t\t\t  \\\n  /* more methods */\t\t\t\t\t\t\t\t\t  \\\n  (hashfunc)     0,\t\t/* tp_hash    \"dict[x]\" */\t\t\t\t  \\\n  (ternaryfunc)  0,             /* tp_call    \"x()\"     */\t\t\t\t  \\\n  (reprfunc)     0,             /* tp_str     \"str(x)\"  */\t\t\t\t  \\\n  (getattrofunc) 0,\t\t/* tp_getattro */\t\t\t\t\t  \\\n  (setattrofunc) 0,\t\t/* tp_setattro */\t\t\t\t\t  \\\n  0,\t\t\t\t/* tp_as_buffer */\t\t\t\t\t  \\\n  0L,\t\t\t\t/* tp_flags */\t\t\t\t\t\t  \\\n  PyGSL_ODEIV_GENERIC_DOC       /* doc */                                                 \\\n};                                                                                        \n\n\n#define PyGSL_ODEIV_GENERIC            PyGSL_odeiv_step\n#define PyGSL_ODEIV_GENERIC_NAME      \"PyGSL_odeiv_step\"\n#define PyGSL_ODEIV_GENERIC_PYTYPE     PyGSL_odeiv_step_pytype\n#define PyGSL_ODEIV_GENERIC_DOC        PyGSL_odeiv_step_doc\n#define PyGSL_ODEIV_GENERIC_GETATTR    PyGSL_odeiv_step_getattr\n#define PyGSL_ODEIV_GENERIC_METHODS    PyGSL_odeiv_step_methods\n#define PyGSL_ODEIV_GENERIC_DELETE     PyGSL_odeiv_step_free\nPyGSL_ODEIV_GENERIC_ALL\n/**/;\n#undef PyGSL_ODEIV_GENERIC       \n#undef PyGSL_ODEIV_GENERIC_NAME  \n#undef PyGSL_ODEIV_GENERIC_PYTYPE\n#undef PyGSL_ODEIV_GENERIC_DOC   \n#undef PyGSL_ODEIV_GENERIC_GETATTR\n#undef PyGSL_ODEIV_GENERIC_METHODS\n#undef PyGSL_ODEIV_GENERIC_DELETE\n#define PyGSL_ODEIV_GENERIC            PyGSL_odeiv_control\n#define PyGSL_ODEIV_GENERIC_NAME      \"PyGSL_odeiv_control\"\n#define PyGSL_ODEIV_GENERIC_PYTYPE     PyGSL_odeiv_control_pytype\n#define PyGSL_ODEIV_GENERIC_DOC        PyGSL_odeiv_control_doc\n#define PyGSL_ODEIV_GENERIC_GETATTR    PyGSL_odeiv_control_getattr\n#define PyGSL_ODEIV_GENERIC_METHODS    PyGSL_odeiv_control_methods\n#define PyGSL_ODEIV_GENERIC_DELETE     PyGSL_odeiv_control_free\nPyGSL_ODEIV_GENERIC_ALL\n/**/;\n#undef PyGSL_ODEIV_GENERIC       \n#undef PyGSL_ODEIV_GENERIC_NAME  \n#undef PyGSL_ODEIV_GENERIC_PYTYPE\n#undef PyGSL_ODEIV_GENERIC_DOC   \n#undef PyGSL_ODEIV_GENERIC_GETATTR\n#undef PyGSL_ODEIV_GENERIC_METHODS\n#undef PyGSL_ODEIV_GENERIC_DELETE\n#define PyGSL_ODEIV_GENERIC            PyGSL_odeiv_evolve\n#define PyGSL_ODEIV_GENERIC_NAME      \"PyGSL_odeiv_evolve\"\n#define PyGSL_ODEIV_GENERIC_PYTYPE     PyGSL_odeiv_evolve_pytype\n#define PyGSL_ODEIV_GENERIC_DOC        PyGSL_odeiv_evolve_doc\n#define PyGSL_ODEIV_GENERIC_GETATTR    PyGSL_odeiv_evolve_getattr\n#define PyGSL_ODEIV_GENERIC_METHODS    PyGSL_odeiv_evolve_methods\n#define PyGSL_ODEIV_GENERIC_DELETE     PyGSL_odeiv_evolve_free\nPyGSL_ODEIV_GENERIC_ALL\n/**/;\n\n#define PyGSL_ODEIV_STEP_Check(v)    ((v)->ob_type == &PyGSL_odeiv_step_pytype)\n#define PyGSL_ODEIV_CONTROL_Check(v) ((v)->ob_type == &PyGSL_odeiv_control_pytype)\n#define PyGSL_ODEIV_EVOLVE_Check(v)  ((v)->ob_type == &PyGSL_odeiv_evolve_pytype)\n\n/*---------------------------------------------------------------------------\n  Wrapper functions to push call the approbriate Python Objects\n  ---------------------------------------------------------------------------*/\nstatic int \nPyGSL_odeiv_func(double t, const double y[], double f[], void *params)\n{\n    int dimension, flag = GSL_FAILURE;\n\n    PyObject *arglist = NULL, *result = NULL;\n    PyArrayObject *yo = NULL;\n    PyGSL_odeiv_step * step;\n    gsl_vector_view yv, fv;\n    PyGSL_error_info  info;\n\n    FUNC_MESS_BEGIN();\n\n    step = (PyGSL_odeiv_step *) params;\n    if(!PyGSL_ODEIV_STEP_Check(step)){\n\t  PyGSL_add_traceback(module, this_file, __FUNCTION__, \n\t\t\t      __LINE__ - 2);\n\t  gsl_error(\"Param not a step type!\", \n\t\t    this_file, __LINE__ -2, GSL_EFAULT);\n\t  goto fail;\n    }\n    dimension =  step->system.dimension;\n\n\n    /* Do I need to copy the array ??? */\n    yv = gsl_vector_view_array((double *) y, dimension);\n    yo = PyGSL_copy_gslvector_to_pyarray(&yv.vector);\n    if (yo == NULL) goto fail;\n\n    FUNC_MESS(\"\\t\\tBuild args\");\n    arglist = Py_BuildValue(\"(dOO)\", t, yo, step->arguments);\n    FUNC_MESS(\"\\t\\tEnd Build args\");\n\n    info.callback = step->py_func;\n    info.message  = \"odeiv_func\";\n    result  = PyEval_CallObject(step->py_func, arglist);\n\n\n    if((flag = PyGSL_CHECK_PYTHON_RETURN(result, 1, &info)) != GSL_SUCCESS){\n\t  goto fail;\n     }\n    info.argnum = 1;\n    fv = gsl_vector_view_array(f, dimension);\n    if((flag = PyGSL_copy_pyarray_to_gslvector(&fv.vector, result, dimension, \n\t\t\t\t\t       &info)) != GSL_SUCCESS){\n\t  goto fail;\n     }     \n     \n\n    Py_DECREF(arglist);    arglist = NULL;\n    Py_DECREF(yo);         yo = NULL;\n    Py_DECREF(result);     result = NULL;\n    FUNC_MESS_END();\n    return GSL_SUCCESS;\n\n fail:\n    FUNC_MESS(\"    IN Fail BEGIN\");\n    Py_XDECREF(yo);\n    Py_XDECREF(result);\n    Py_XDECREF(arglist);\n    FUNC_MESS(\"    IN Fail END\");\n    assert(flag != GSL_SUCCESS);\n    longjmp(step->buffer, flag);\n    return flag;\n}\n\nstatic int \nPyGSL_odeiv_jac(double t, const double y[], double *dfdy, double dfdt[], \n\t\tvoid *params)\n{\n    int dimension, flag = GSL_FAILURE;\n    PyGSL_odeiv_step *step = NULL;\n    PyGSL_error_info  info;\n    \n    PyObject *arglist = NULL, *result = NULL, *tmp=NULL;\n    PyArrayObject *yo = NULL;\n\n    gsl_vector_view yv, dfdtv;\n    gsl_matrix_view dfdyv;\n\n\n    FUNC_MESS_BEGIN();\n    \n    step = (PyGSL_odeiv_step *) params;\n    if(!PyGSL_ODEIV_STEP_Check(step)){\n\t  PyGSL_add_traceback(module, this_file, __FUNCTION__, \n\t\t\t      __LINE__ - 2);\n\t  gsl_error(\"Param not a step type!\", \n\t\t    this_file, __LINE__ -2, GSL_EFAULT);\n\t  goto fail;\n    }\n    dimension = step->system.dimension;\n\n\n\n    yv = gsl_vector_view_array((double *) y, dimension);\n    yo = PyGSL_copy_gslvector_to_pyarray(&yv.vector);\n    if (yo == NULL) goto fail;\n\n\n    arglist = Py_BuildValue(\"(dOO)\", t, yo, step->arguments);\n\n    assert(step->py_jac);\n    result  = PyEval_CallObject(step->py_jac, arglist);\n\n    info.callback = step->py_jac;\n    info.message  = \"odeiv_jac\";\n    if((flag = PyGSL_CHECK_PYTHON_RETURN(result, 2, &info)) != GSL_SUCCESS){\n\t  goto fail;\n     }\n\n    info.argnum = 1;\n    tmp = PyTuple_GET_ITEM(result, 0);\n    dfdyv = gsl_matrix_view_array((double *) dfdy, dimension, dimension);\n    if((flag = PyGSL_copy_pyarray_to_gslmatrix(&dfdyv.matrix, tmp, dimension, dimension, &info)) != GSL_SUCCESS){\n\t  goto fail;\n    }     \n    \n    info.argnum = 2;\n    tmp = PyTuple_GET_ITEM(result, 1);\n    dfdtv = gsl_vector_view_array((double *) dfdt, dimension);\n    if((flag = PyGSL_copy_pyarray_to_gslvector(&dfdtv.vector, tmp, dimension, &info)) != GSL_SUCCESS){\n\t  goto fail;\n    }     \n\n          \n    Py_DECREF(arglist);    arglist = NULL;\n    Py_DECREF(result);     result = NULL;\n    Py_DECREF(yo);         yo = NULL;\n    FUNC_MESS_END();\n    return GSL_SUCCESS;\n\n fail:\n    FUNC_MESS(\"IN Fail\");\n    assert(flag != GSL_SUCCESS);\n    longjmp(step->buffer, flag);\n    return flag;\n}\n\n\n/* Wrappers for the evaluation of the system */\nstatic PyObject *\nPyGSL_odeiv_step_apply(PyGSL_odeiv_step *self, PyObject *args)\n{\n    PyObject *result = NULL;\n    PyObject *y0_o = NULL, *dydt_in_o = NULL;\n    PyArrayObject *volatile y0 = NULL, * volatile yerr = NULL, \n\t *volatile dydt_in = NULL, *volatile dydt_out = NULL,\n\t *volatile yout = NULL;\n\n    double t=0, h=0, *volatile dydt_in_d;\n    int dimension, r, flag;\n\n\n    FUNC_MESS_BEGIN();\n    assert(PyGSL_ODEIV_STEP_Check(self));\n    if(! PyArg_ParseTuple(args, \"ddOOO\", &t, &h, &y0_o,  &dydt_in_o)){\n      return NULL;\n    }\n\n\n    dimension = self->system.dimension;\n    y0 = PyGSL_PyArray_PREPARE_gsl_vector_view(y0_o, PyArray_DOUBLE, 1, dimension, 1, NULL);\n    if(y0 == NULL) goto fail;\n\n\n    if (Py_None == dydt_in_o){\n\t dydt_in_d = NULL;\n    }else{\n\t dydt_in = PyGSL_PyArray_PREPARE_gsl_vector_view(dydt_in_o, PyArray_DOUBLE, 1, dimension, 2, NULL);\n\t if(dydt_in == NULL) goto fail;\n\t dydt_in_d = (double *) dydt_in->data;\n    }\n\n\n    dydt_out = (PyArrayObject *)  PyArray_FromDims(1, &dimension, PyArray_DOUBLE);\n    if (dydt_out == NULL) goto fail;\n\n    yerr = (PyArrayObject *) PyArray_FromDims(1, &dimension, PyArray_DOUBLE);\n    if(yerr == NULL) goto fail;\n\n\n    yout = (PyArrayObject *) PyArray_CopyFromObject((PyObject * ) y0, PyArray_DOUBLE, 1, 1);\n    if(yout == NULL) goto fail;\n\n\n    if((flag=setjmp(self->buffer)) == 0){\n\t  FUNC_MESS(\"\\t\\t Setting Jmp Buffer\");\n    } else {\n\t  FUNC_MESS(\"\\t\\t Returning from Jmp Buffer\");\n\t  goto fail;\n    }\n    \n    r = gsl_odeiv_step_apply(self->step, t, h, \n\t\t\t     (double *) yout->data, \n\t\t\t     (double *) yerr->data, \n\t\t\t     dydt_in_d, \n\t\t\t     (double *) dydt_out->data, \n\t\t\t     &(self->system));\n    if (GSL_SUCCESS != r){\n\tPyErr_SetString(PyExc_TypeError, \"Error While evaluating gsl_odeiv\");\n      goto fail;\n    }\n\n    FUNC_MESS(\"    Returnlist create \");\n    assert(yout != NULL);\n    assert(yerr != NULL);\n    assert(dydt_out != NULL);\n\n    result = Py_BuildValue(\"(OOO)\", yout, yerr, dydt_out);\n\n    FUNC_MESS(\"    Memory free \");\n    /* Deleting the arrays */    \n    Py_DECREF(y0);           y0 = NULL;\n    Py_DECREF(yout);         yout = NULL;\n    Py_DECREF(yerr);         yerr = NULL;\n    Py_DECREF(dydt_out);     dydt_out = NULL;\n    /* This array does not need to exist ... */\n    Py_XDECREF(dydt_in);\t dydt_in=NULL;\n    \n    FUNC_MESS_END();\n    return result;\n\n    fail:\n    FUNC_MESS(\"IN Fail\");\n    Py_XDECREF(y0);\n    Py_XDECREF(yout);\n    Py_XDECREF(yerr);\n    Py_XDECREF(dydt_in);\n    Py_XDECREF(dydt_out);\n    FUNC_MESS(\"IN Fail End\");   \n    return NULL;\n}\n\n\n\nstatic void \nPyGSL_odeiv_step_free(PyGSL_odeiv_step * self)\n{\n     assert(PyGSL_ODEIV_STEP_Check(self));\n     Py_DECREF(self->py_func);\n     Py_XDECREF(self->py_jac);\n     Py_DECREF(self->arguments);\n     gsl_odeiv_step_free(self->step);\n     PyMem_Free(self);\n}\n\nstatic PyObject *\nPyGSL_odeiv_step_reset(PyGSL_odeiv_step *self, PyObject *args)\n{\n     assert(PyGSL_ODEIV_STEP_Check(self));\n     gsl_odeiv_step_reset(self->step);\n     Py_INCREF(Py_None);\n     return Py_None;\n}\n\nstatic PyObject *\nPyGSL_odeiv_step_name(PyGSL_odeiv_step *self, PyObject *args)\n{\n     assert(PyGSL_ODEIV_STEP_Check(self));\n     return PyString_FromString(gsl_odeiv_step_name(self->step));\n}\n\nstatic PyObject *\nPyGSL_odeiv_step_order(PyGSL_odeiv_step *self, PyObject *args)\n{\n     assert(PyGSL_ODEIV_STEP_Check(self));\n     return PyInt_FromLong((long) gsl_odeiv_step_order(self->step));\n}\n\n\n/* --------------------------------------------------------------------------- */\n/* control_hadjust needs a few arrays */\n/*\nextern int \ngsl_odeiv_control_hadjust (gsl_odeiv_control * c, gsl_odeiv_step * s, \n\t\t\t   const double y0[],  const double yerr[], \n\t\t\t   const double dydt[], double * h);\n*/\nstatic PyObject *\nPyGSL_odeiv_control_hadjust(PyGSL_odeiv_control *self, PyObject *args)\n{\n  \n  PyObject *result = NULL;\n  PyObject *y0_o = NULL, *yerr_o = NULL, *dydt_o = NULL;\n  PyArrayObject *y0 = NULL, *yerr = NULL, *dydt = NULL;\n  double h = 0;\n  int r = 0;\n\n\n  size_t dimension = 0;\n\n  FUNC_MESS_BEGIN();\n  assert(PyGSL_ODEIV_CONTROL_Check(self));\n  if(!PyArg_ParseTuple(args, \"OOOd\",  &y0_o, &yerr_o, &dydt_o, &h)){\n    return NULL;\n  }\n\n  dimension = self->step->system.dimension;\n\n\n  y0 = PyGSL_PyArray_PREPARE_gsl_vector_view(y0_o, PyArray_DOUBLE, 1, dimension,  1, NULL);\n  if(y0 == NULL)   goto fail;\n  yerr = PyGSL_PyArray_PREPARE_gsl_vector_view(yerr_o, PyArray_DOUBLE, 1, dimension, 2, NULL);\n  if(yerr == NULL) goto fail;\n  dydt = PyGSL_PyArray_PREPARE_gsl_vector_view(yerr_o, PyArray_DOUBLE, 1, dimension, 3, NULL);\n  if(dydt == NULL) goto fail;\n  \n  FUNC_MESS(\"      Array Pointers End\");\n\n  r = gsl_odeiv_control_hadjust(self->control, self->step->step, \n\t\t\t\t(double *) y0->data,\n\t\t\t\t(double *) yerr->data,\n\t\t\t\t(double *) dydt->data, &h);\n\n  FUNC_MESS(\"      Function End\");\n  Py_DECREF(y0);       y0 = NULL;  \n  Py_DECREF(yerr);     yerr = NULL;\n  Py_DECREF(dydt);     dydt = NULL;\n\n  result = Py_BuildValue(\"di\",h,r);\n  FUNC_MESS_END();\n  return result;\n\n fail:\n  FUNC_MESS(\"IN Fail\");\n  Py_XDECREF(y0);\n  Py_XDECREF(yerr);\n  Py_XDECREF(dydt);\n  FUNC_MESS(\"IN Fail END\");\n  return NULL;\n}\n\n\nstatic void \nPyGSL_odeiv_control_free(PyGSL_odeiv_control * self)\n{\n     assert(PyGSL_ODEIV_CONTROL_Check(self));\n     Py_DECREF(self->step);\n     //gsl_odeiv_control_free(self->control);\n     PyMem_Free(self);\n}\n\nstatic PyObject *\nPyGSL_odeiv_control_name(PyGSL_odeiv_control *self, PyObject *args)\n{\n     assert(PyGSL_ODEIV_CONTROL_Check(self));\n     return PyString_FromString(gsl_odeiv_control_name(self->control));\n}\n\nstatic void \nPyGSL_odeiv_evolve_free(PyGSL_odeiv_evolve * self)\n{\n     assert(PyGSL_ODEIV_EVOLVE_Check(self));\n     Py_DECREF(self->step);\n     Py_DECREF(self->control);\n     gsl_odeiv_evolve_free(self->evolve);\n     PyMem_Free(self);\n}\n\nstatic PyObject *\nPyGSL_odeiv_evolve_apply(PyGSL_odeiv_evolve *self, PyObject *args)\n{\n    PyObject *result = NULL;\n    PyObject *y0_o = NULL;\n    PyArrayObject *volatile y0 = NULL, *volatile yout = NULL;\n\n    double t=0, h=0, t1 = 0, flag;\n\n    int dimension, r;\n\n    assert(PyGSL_ODEIV_EVOLVE_Check(self));\n    FUNC_MESS_BEGIN();\n\n    if(! PyArg_ParseTuple(args, \"dddO\",\n\t\t\t  &t, &t1, &h, &y0_o)){\n      return NULL;\n    }\n\n    dimension = self->step->system.dimension;\n\n\n\n    y0 = PyGSL_PyArray_PREPARE_gsl_vector_view(y0_o, PyArray_DOUBLE, 1, dimension, 1, NULL);\n    if(y0 == NULL) goto fail;\n\n\n    yout = (PyArrayObject *)  PyArray_CopyFromObject((PyObject * ) y0, PyArray_DOUBLE, 1, 1);\n    if(yout == NULL) goto fail;\n\n\n    if((flag=setjmp(self->step->buffer)) == 0){\n\t  FUNC_MESS(\"\\t\\t Setting Jmp Buffer\");\n     } else {\n\t  FUNC_MESS(\"\\t\\t Returning from Jmp Buffer\");\n\t  goto fail;\n     }\n\n    r = gsl_odeiv_evolve_apply(self->evolve, \n\t\t\t       self->control->control, \n\t\t\t       self->step->step, \n\t\t\t       &(self->step->system), &t, t1, &h,\n\t\t\t       (double * )yout->data); \n\n    if (GSL_SUCCESS != r){\n\t goto fail;\n    } \n\n\n    assert(yout != NULL);\n\n\n    result = Py_BuildValue(\"(ddO)\", t, h, yout);\n\n    /* Deleting the arrays */    \n    /* Do I need to do that??? Not transfered Py_DECREF(yout);     yout = NULL; */\n    Py_DECREF(y0);       y0=NULL;\n    FUNC_MESS_END();\n    return result;\n\n fail:\n    FUNC_MESS(\"IN Fail\");\n    PyGSL_add_traceback(module, this_file, odeiv_step_init_err_msg, __LINE__);\n    Py_XDECREF(y0);\n    Py_XDECREF(yout); \n    FUNC_MESS(\"IN Fail End\");   \n    return NULL;\n}\n\nstatic PyObject *\nPyGSL_odeiv_evolve_apply_array(PyGSL_odeiv_evolve *self, PyObject *args)\n{\n    PyObject *result = NULL;\n    PyObject *y0_o = NULL;\n    PyObject *t_o = NULL;\n    PyArrayObject *volatile y0 = NULL, *volatile yout = NULL, *volatile ta = NULL;\n\n    double t=0, h=0, t1 = 0, flag;\n    double *y0_data = NULL, *yout_data = NULL;\n    int dimension, r, dims[2];\n    int nlen=-1, i, j;\n\n    assert(PyGSL_ODEIV_EVOLVE_Check(self));\n    FUNC_MESS_BEGIN();\n\n    if(! PyArg_ParseTuple(args, \"OdO\", &t_o, &h, &y0_o)){\n      return NULL;\n    }\n\n    dimension = self->step->system.dimension;\n\n    ta = PyGSL_PyArray_PREPARE_gsl_vector_view(t_o, PyArray_DOUBLE, 1, -1, 1, NULL);\n    if(ta == NULL) goto fail;\n    nlen = ta->dimensions[0];\n\n    y0 = PyGSL_PyArray_PREPARE_gsl_vector_view(y0_o, PyArray_DOUBLE, 1, dimension, 1, NULL);\n    if(y0 == NULL) goto fail;\n\n    dims[0] = nlen;\n    dims[1] = dimension;\n    yout = (PyArrayObject *)  PyArray_FromDims(2, dims, PyArray_DOUBLE);\n    if(yout == NULL) goto fail;\n\n\n    if((flag=setjmp(self->step->buffer)) == 0){\n\t  FUNC_MESS(\"\\t\\t Setting Jmp Buffer\");\n     } else {\n\t  FUNC_MESS(\"\\t\\t Returning from Jmp Buffer\");\n\t  goto fail;\n     }\n\n    DEBUG_MESS(5, \"\\t\\t Yout Layout %p, shape=[%d,%d], strides=[%d,%d]\", \n\t       yout->data, yout->dimensions[0], yout->dimensions[1], yout->strides[0], yout->strides[1]);\n    r = GSL_CONTINUE;\n\n    yout_data = (double *)(yout->data);\n    /* Copy the start vector */\n    for(j=0; j<dimension; j++){\n\t yout_data[j] = *((double *)(y0->data + y0->strides[0] * j));\n    }\n    for(i=1; i<nlen; i++){\n\t y0_data   = (double *)(yout->data + yout->strides[0]*(i-1));\t \n\t yout_data = (double *)(yout->data + yout->strides[0]*(i)  );\t \n\t /* Copy the start vector */\n\t for(j=0; j<dimension; j++){\n\t      yout_data[j] = y0_data[j];\n\t }\n\t t =  *((double *) (ta->data + ta->strides[0]*(i-1)) );\t \n\t t1 = *((double *) (ta->data + ta->strides[0]*(i)  ) );\t \n\n\t while(t<t1){\n\t      r = gsl_odeiv_evolve_apply(self->evolve, \n\t\t\t\t\t self->control->control, \n\t\t\t\t\t self->step->step, \n\t\t\t\t\t &(self->step->system), &t, t1, &h,\n\t\t\t\t\t yout_data); \n\t      /* All GSL Errors are > 0. */\n\t      if (r != GSL_SUCCESS){\n\t\t   goto fail;\n\t      }\n\t }\n\t assert(r == GSL_SUCCESS);\n    }\n\n\n    result = (PyObject *) yout;\n\n    /* Deleting the arrays */    \n    Py_DECREF(y0); y0=NULL;\n    Py_DECREF(ta); \n    FUNC_MESS_END();\n    return result;\n\n fail:\n    FUNC_MESS(\"IN Fail\");\n    PyGSL_add_traceback(module, this_file, odeiv_step_init_err_msg, __LINE__);\n    Py_XDECREF(ta);  ta = NULL;\n    Py_XDECREF(y0);  y0=NULL;\n    Py_XDECREF(yout); \n    FUNC_MESS(\"IN Fail End\");   \n    return NULL;\n}\n\nstatic PyObject *\nPyGSL_odeiv_evolve_reset(PyGSL_odeiv_evolve *self, PyObject *args)\n{\n     assert(PyGSL_ODEIV_EVOLVE_Check(self));\n     gsl_odeiv_evolve_reset(self->evolve);\n     Py_INCREF(Py_None);\n     return Py_None;\n}\n\n\n\nstatic PyObject *\nPyGSL_odeiv_step_init(PyObject *self, PyObject *args, PyObject *kwdict, const gsl_odeiv_step_type * odeiv_type)\n{\n     \n     PyObject *func=NULL, *jac=NULL, *o_params=NULL;\n     PyGSL_odeiv_step *odeiv_step = NULL;\n\n     static char * kwlist[] = {\"dimension\", \"func\", \"jac\", \"args\", NULL}; \n     int dim, has_jacobian = 0;\n\n     FUNC_MESS_BEGIN();\n     assert(args);\n     if (0 == PyArg_ParseTupleAndKeywords(args, kwdict, \"iOOO:odeiv_step.__init__\", kwlist, \n\t\t\t\t\t  &dim, &func, &jac, &o_params)){\n\t  PyGSL_add_traceback(module, this_file, odeiv_step_init_err_msg, __LINE__ - 2);\n\t  return NULL;\n     }     \n     if (dim <= 0){\t  \n\t  PyGSL_add_traceback(module, this_file, odeiv_step_init_err_msg, __LINE__ - 1);\n\t  gsl_error(\"The dimension of the problem must be at least 1\", \n\t\t    this_file, __LINE__ -2, GSL_EDOM);\n\t  return NULL;\n     }\n     if(!PyCallable_Check(func)){\n\t  PyGSL_add_traceback(module, this_file, odeiv_step_init_err_msg, __LINE__ - 1);\n\t  gsl_error(\"The function object is not callable!\", \n\t\t    this_file, __LINE__ -2, GSL_EBADFUNC);\n\t  goto fail;\t  \n     }\n\n     if(jac == Py_None){\n\t  if(odeiv_type == gsl_odeiv_step_bsimp){\n\t       PyGSL_add_traceback(module, this_file, odeiv_step_init_err_msg, __LINE__ - 1);\n\t       gsl_error(\"The bsimp method needs a jacobian! You supplied None.\", \n\t\t\t this_file, __LINE__ -2, GSL_EBADFUNC);\n\t       goto fail;\n\t  }\n     }else{\n\t  if(!PyCallable_Check(jac)){\n\t       PyGSL_add_traceback(module, this_file, odeiv_step_init_err_msg, __LINE__ - 1);\n\t       gsl_error(\"The jacobian object must be None or callable!\", \n\t\t\t this_file, __LINE__ -2, GSL_EBADFUNC);\n\t       goto fail;\n\t  }\n\t  has_jacobian = 1;\n\n     }\n\n     odeiv_step =  (PyGSL_odeiv_step *) PyObject_NEW(PyGSL_odeiv_step, &PyGSL_odeiv_step_pytype);\n     if(odeiv_step == NULL){\n\t  PyErr_NoMemory();\n\t  goto fail;\n     }\n     odeiv_step->step=NULL;\n     odeiv_step->py_func=NULL;\n     odeiv_step->py_jac=NULL;\n     odeiv_step->arguments=NULL;\n\n     odeiv_step->system.dimension = dim;\n     if(has_jacobian)\n\t  odeiv_step->system.jacobian = PyGSL_odeiv_jac;\n     else\n\t  odeiv_step->system.jacobian = NULL;\n\n     odeiv_step->system.function = PyGSL_odeiv_func;\n     odeiv_step->system.params = (void *) odeiv_step;\n\n     odeiv_step->step =  gsl_odeiv_step_alloc(odeiv_type, dim);     \n     if(odeiv_step->step == NULL){\n\t  Py_DECREF(odeiv_step);\n\t  PyErr_NoMemory();\n\t  return NULL;\n     }\n\n     odeiv_step->py_func=func;\n     if(has_jacobian)\n\t  odeiv_step->py_jac=jac;\n\n     odeiv_step->arguments = o_params;\n     Py_INCREF(odeiv_step->py_func);\n     Py_INCREF(odeiv_step->arguments);\n\n     \n     Py_XINCREF(odeiv_step->py_jac);\n\n     FUNC_MESS_END();\n     return (PyObject *) odeiv_step;\n fail:\n     return NULL;\n}\n#define ADD_ODESTEPPER(mytype)                                                      \\\nstatic PyObject *                                                                   \\\nPyGSL_odeiv_step_init_ ## mytype (PyObject * self, PyObject * args, PyObject *kwdic)\\\n{                                                                                   \\\n     return PyGSL_odeiv_step_init(self, args, kwdic, gsl_odeiv_step_ ## mytype);    \\\n}   \nADD_ODESTEPPER(rk2)\nADD_ODESTEPPER(rk4)\nADD_ODESTEPPER(rkf45)\nADD_ODESTEPPER(rkck)\nADD_ODESTEPPER(rk8pd)\nADD_ODESTEPPER(rk2imp)\nADD_ODESTEPPER(rk4imp)\nADD_ODESTEPPER(bsimp)\nADD_ODESTEPPER(gear1)\nADD_ODESTEPPER(gear2)\n\n\nstatic PyObject *\nPyGSL_odeiv_control_init(PyObject *self, PyObject *args, void * type)\n{\n     int nargs = -1, tmp=0;\n     double eps_abs, eps_rel, a_y, a_dydt;\n     PyGSL_odeiv_step *step=NULL;\n     PyGSL_odeiv_control *a_con=NULL;\n\n     gsl_odeiv_control *(*evaluator_5)(double , double , double , double ) = NULL;\n     gsl_odeiv_control *(*evaluator_3)(double , double ) = NULL;\n\n     FUNC_MESS_BEGIN();\n     /* The arguments depend on the type of control */\n     if(type == (void *) gsl_odeiv_control_standard_new){\n\t  /* step, eps_abs, eps_rel, a_y, a_dydt */\n\t  nargs = 5;\n     }else if(type == (void *) gsl_odeiv_control_y_new || \n\t      type == (void *) gsl_odeiv_control_yp_new){\n\t  nargs = 3;\n     }else{\n\t  PyGSL_add_traceback(module, this_file, odeiv_step_init_err_msg, \n\t\t\t      __LINE__ - 2);\n\t  gsl_error(\"Unknown control type\", \n\t\t    this_file, __LINE__ -2, GSL_EFAULT);\n\t  goto fail;\n     }\n     assert(nargs > -1);\n\n\n     switch(nargs){\n     case 5:\n\t  tmp == PyArg_ParseTuple(args, \"O!dddd:odeiv_control.__init__\", \n\t\t\t\t  &PyGSL_odeiv_step_pytype, &step, &eps_abs, &eps_rel, &a_y, &a_dydt);\n\t  break;\n     case 3:\n\t  tmp == PyArg_ParseTuple(args, \"O!dd:odeiv_control.__init__\", \n\t\t\t\t  &PyGSL_odeiv_step_pytype, &step, &eps_abs, &eps_rel);\n\t  break;\n     default:\n\t  fprintf(stderr, \"nargs = %d\\n\", nargs);\n\t  gsl_error(\"Unknown number of arguments\", \n\t\t    this_file, __LINE__ -2, GSL_EFAULT);\n\t  goto fail; break;\n     }\n     \n     if(!step){\n\t  PyErr_SetString(PyExc_TypeError, \"The first argument must be a step object!\");\n\t  goto fail;\n     }\n\n\n     if(tmp){\t  \n\t  PyGSL_add_traceback(module, this_file, odeiv_step_init_err_msg, \n\t\t\t      __LINE__ - 2);\n\t  return NULL;\n     }\n\n     a_con =  PyObject_NEW(PyGSL_odeiv_control, &PyGSL_odeiv_control_pytype);\n     if (NULL == a_con){\n\t  PyErr_NoMemory();\n\t  goto fail;\n     }\n     a_con->control=NULL;\n     switch(nargs){\n     case 5:\n\t  evaluator_5 = type;\n\t  a_con->control = evaluator_5(eps_abs, eps_rel, a_y, a_dydt);\n\t  break;\n     case 3:\n\t  evaluator_3 = type;\n\t  a_con->control = evaluator_3(eps_abs, eps_rel);\n\t  break;\n     default:\n\t  goto fail;\n     }\n     if (NULL == a_con->control){\n\t  PyErr_NoMemory();\n\t  goto fail;\n     }\n     assert(step);\n     a_con->step =  step;\n     Py_INCREF(step);\n     FUNC_MESS_END();\n     return (PyObject *) a_con;\n\n fail:\n     FUNC_MESS(\"FAIL\");\n     Py_XDECREF(a_con);\n     return NULL;\n     \n}\n\n#define ADD_ODECONTROL(name)                                                  \\\nstatic PyObject *                                                             \\\nPyGSL_odeiv_control_init_ ## name (PyObject * self, PyObject * args)          \\\n{                                                                             \\\n     return PyGSL_odeiv_control_init(self, args, (void *) gsl_odeiv_control_ ## name);    \\\n}   \nADD_ODECONTROL(standard_new)\nADD_ODECONTROL(y_new)\nADD_ODECONTROL(yp_new)\n\nstatic PyObject *\nPyGSL_odeiv_evolve_init(PyObject *self, PyObject *args)\n{\n     PyGSL_odeiv_step *step = NULL;\n     PyGSL_odeiv_control *control = NULL;\n     PyGSL_odeiv_evolve *a_ev = NULL;\n\n\n     /* step, control */\n     FUNC_MESS_BEGIN();\n     if(0== PyArg_ParseTuple(args, \"O!O!:odeiv_evolve.__init__\", \n\t\t\t     &PyGSL_odeiv_step_pytype, &step,\n\t\t\t     &PyGSL_odeiv_control_pytype, &control)){\n\t  return NULL;\n     }\n\n     if(!step){\n\t  PyErr_SetString(PyExc_TypeError, \"The first argument must be a step object!\");\n\t  goto fail;\n     }\n\n     if(!control){\n\t  PyErr_SetString(PyExc_TypeError, \"The second argument must be a control object!\");\n\t  goto fail;\n     }\n\n     a_ev =  (PyGSL_odeiv_evolve *) PyObject_NEW(PyGSL_odeiv_evolve, &PyGSL_odeiv_evolve_pytype);\n     if(NULL == a_ev){\n\t  PyErr_NoMemory();\n\t  return NULL;\n     }\n     \n\n\n     a_ev->step = step;\n     a_ev->control = control;\n\n     a_ev->evolve = gsl_odeiv_evolve_alloc(step->system.dimension);\n     if(NULL == a_ev){\n\t  PyErr_NoMemory();\n\t  goto fail;\n     }\n     Py_INCREF(step);\n     Py_INCREF(control);\n     FUNC_MESS_END();\n     return (PyObject *) a_ev;\n fail:\n     FUNC_MESS(\"FAIL\");\n     Py_DECREF(a_ev);\n     return NULL;\n}\n\nstatic PyMethodDef PyGSL_odeiv_module_functions[] = {\n     {\"step_rk2\",    PyGSL_odeiv_step_init_rk2,    METH_VARARGS|METH_KEYWORDS, NULL},\n     {\"step_rk4\",    PyGSL_odeiv_step_init_rk4,    METH_VARARGS|METH_KEYWORDS, NULL},\n     {\"step_rkf45\",  PyGSL_odeiv_step_init_rkf45,  METH_VARARGS|METH_KEYWORDS, NULL},\n     {\"step_rkck\",   PyGSL_odeiv_step_init_rkck,   METH_VARARGS|METH_KEYWORDS, NULL},\n     {\"step_rk8pd\",  PyGSL_odeiv_step_init_rk8pd,  METH_VARARGS|METH_KEYWORDS, NULL},\n     {\"step_rk2imp\", PyGSL_odeiv_step_init_rk2imp, METH_VARARGS|METH_KEYWORDS, NULL},\n     {\"step_rk4imp\", PyGSL_odeiv_step_init_rk4imp, METH_VARARGS|METH_KEYWORDS, NULL},\n     {\"step_bsimp\",  PyGSL_odeiv_step_init_bsimp,  METH_VARARGS|METH_KEYWORDS, NULL},\n     {\"step_gear1\",  PyGSL_odeiv_step_init_gear1,  METH_VARARGS|METH_KEYWORDS, NULL},\n     {\"step_gear2\",  PyGSL_odeiv_step_init_gear2,  METH_VARARGS|METH_KEYWORDS, NULL},\n     {\"control_standard_new\", PyGSL_odeiv_control_init_standard_new, METH_VARARGS, NULL},\n     {\"control_y_new\",        PyGSL_odeiv_control_init_y_new,        METH_VARARGS, NULL},\n     {\"control_yp_new\",       PyGSL_odeiv_control_init_yp_new,       METH_VARARGS, NULL},\n     {\"evolve\", PyGSL_odeiv_evolve_init, METH_VARARGS, NULL},\n     {NULL, NULL, 0}        /* Sentinel */\n};\n\nvoid \ninitodeiv(void)\n{\n     PyObject *m=NULL, *item=NULL, *dict=NULL;\n\n     FUNC_MESS_BEGIN();\n     fprintf(stderr, \"Compiled at %s %s\\n\", __DATE__, __TIME__);\n     m = Py_InitModule(\"odeiv\", PyGSL_odeiv_module_functions);\n     assert(m);\n     module = m;\n     import_array();\n     init_pygsl();\n\n\n     PyGSL_odeiv_step_pytype.ob_type = &PyType_Type;\n     PyGSL_odeiv_control_pytype.ob_type = &PyType_Type;\n     PyGSL_odeiv_evolve_pytype.ob_type = &PyType_Type;\n\n     dict = PyModule_GetDict(m);\n     /* create_odeiv_step_types(dict); */\n     if(!dict)\n\t  goto fail;\n     \n     if (!(item = PyString_FromString(odeiv_module_doc))){\n\t  PyErr_SetString(PyExc_ImportError, \n\t\t\t  \"I could not generate module doc string!\");\n\t  goto fail;\n     }\n     if (PyDict_SetItemString(dict, \"__doc__\", item) != 0){\n\t  PyErr_SetString(PyExc_ImportError, \n\t\t\t  \"I could not init doc string!\");\n\t  goto fail;\n     }\n     \n     FUNC_MESS_END();\n     return;\n fail:\n     FUNC_MESS(\"Fail\");\n     fprintf(stderr, \"Import of module odeiv failed!\\n\");\n}\n\n", "meta": {"hexsha": "ed47c8b20ab5d53c115e6ee40b8583772e17d618", "size": 33224, "ext": "c", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/testing/src/solvers/old/odeiv_old2.c", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/testing/src/solvers/old/odeiv_old2.c", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/testing/src/solvers/old/odeiv_old2.c", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 30.5087235996, "max_line_length": 113, "alphanum_fraction": 0.6394473874, "num_tokens": 9809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.04401864531679141, "lm_q1q2_score": 0.020635528321297014}}
{"text": "/* permutation/gsl_permutation.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2004, 2007 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_PERMUTATION_H__\n#define __GSL_PERMUTATION_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_inline.h>\n#include <gsl/gsl_check_range.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\nstruct gsl_permutation_struct\n{\n  size_t size;\n  size_t *data;\n};\n\ntypedef struct gsl_permutation_struct gsl_permutation;\n\ngsl_permutation *gsl_permutation_alloc (const size_t n);\ngsl_permutation *gsl_permutation_calloc (const size_t n);\nvoid gsl_permutation_init (gsl_permutation * p);\nvoid gsl_permutation_free (gsl_permutation * p);\nint gsl_permutation_memcpy (gsl_permutation * dest, const gsl_permutation * src);\n\nint gsl_permutation_fread (FILE * stream, gsl_permutation * p);\nint gsl_permutation_fwrite (FILE * stream, const gsl_permutation * p);\nint gsl_permutation_fscanf (FILE * stream, gsl_permutation * p);\nint gsl_permutation_fprintf (FILE * stream, const gsl_permutation * p, const char *format);\n\nsize_t gsl_permutation_size (const gsl_permutation * p);\nsize_t * gsl_permutation_data (const gsl_permutation * p);\n\nint gsl_permutation_swap (gsl_permutation * p, const size_t i, const size_t j);\n\nint gsl_permutation_valid (const gsl_permutation * p);\nvoid gsl_permutation_reverse (gsl_permutation * p);\nint gsl_permutation_inverse (gsl_permutation * inv, const gsl_permutation * p);\nint gsl_permutation_next (gsl_permutation * p);\nint gsl_permutation_prev (gsl_permutation * p);\nint gsl_permutation_mul (gsl_permutation * p, const gsl_permutation * pa, const gsl_permutation * pb);\n\nint gsl_permutation_linear_to_canonical (gsl_permutation * q, const gsl_permutation * p);\nint gsl_permutation_canonical_to_linear (gsl_permutation * p, const gsl_permutation * q);\n\nsize_t gsl_permutation_inversions (const gsl_permutation * p);\nsize_t gsl_permutation_linear_cycles (const gsl_permutation * p);\nsize_t gsl_permutation_canonical_cycles (const gsl_permutation * q);\n\nINLINE_DECL size_t gsl_permutation_get (const gsl_permutation * p, const size_t i);\n\n#ifdef HAVE_INLINE\n\nINLINE_FUN\nsize_t\ngsl_permutation_get (const gsl_permutation * p, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= p->size))\n    {\n      GSL_ERROR_VAL (\"index out of range\", GSL_EINVAL, 0);\n    }\n#endif\n  return p->data[i];\n}\n\n#endif /* HAVE_INLINE */\n\n__END_DECLS\n\n#endif /* __GSL_PERMUTATION_H__ */\n", "meta": {"hexsha": "10ac0f58a2e1d962f1ef62e5a6c65f15aef9d683", "size": 3346, "ext": "h", "lang": "C", "max_stars_repo_path": "gsl-an/gsl/gsl_permutation.h", "max_stars_repo_name": "juandesant/astrometry.net", "max_stars_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_stars_repo_licenses": ["Net-SNMP", "Xnet"], "max_stars_count": 460.0, "max_stars_repo_stars_event_min_datetime": "2015-01-06T13:20:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T00:37:55.000Z", "max_issues_repo_path": "gsl-an/gsl/gsl_permutation.h", "max_issues_repo_name": "juandesant/astrometry.net", "max_issues_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_issues_repo_licenses": ["Net-SNMP", "Xnet"], "max_issues_count": 208.0, "max_issues_repo_issues_event_min_datetime": "2015-01-08T20:26:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T15:21:34.000Z", "max_forks_repo_path": "gsl-an/gsl/gsl_permutation.h", "max_forks_repo_name": "juandesant/astrometry.net", "max_forks_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_forks_repo_licenses": ["Net-SNMP", "Xnet"], "max_forks_count": 173.0, "max_forks_repo_forks_event_min_datetime": "2015-01-08T18:01:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T07:27:04.000Z", "avg_line_length": 33.1287128713, "max_line_length": 102, "alphanum_fraction": 0.7752540347, "num_tokens": 875, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.414898860266261, "lm_q2_score": 0.04958902719777796, "lm_q1q2_score": 0.020574430866070696}}
{"text": "#pragma once\n\n#include \"exp_curve_fitter.h\"\n#include \"optimizer_job.h\"\n#include \"random_utils.h\"\n#include \"schedule_params.h\"\n#include <gsl/gsl-lite.hpp>\n#include <vector>\n\nnamespace angonoka::stun {\n/**\n    How many iterations without improvement before\n    considering optimization complete.\n*/\nenum class MaxIdleIters : std::int_fast32_t;\n\n/**\n    Optimization algorithm based on stochastic tunneling.\n\n    This is the primary facade for doing stochastic tunneling\n    optimization.\n*/\nclass Optimizer {\npublic:\n    /**\n        Constructor.\n\n        @param params           Scheduling parameters\n        @param batch_size       Number of iterations per update\n        @param max_idle_iters   Stopping condition\n    */\n    Optimizer(\n        const ScheduleParams& params,\n        BatchSize batch_size,\n        MaxIdleIters max_idle_iters);\n\n    /**\n        Run stochastic tunneling optimization batch.\n\n        Does batch_size number of iterations and adjusts the estimated\n        progress accordingly.\n    */\n    void update() noexcept;\n\n    /**\n        Checks if the stopping condition has been met.\n\n        @return True when further improvements are unlikely\n    */\n    [[nodiscard]] bool has_converged() const noexcept;\n\n    /**\n        Estimated optimization progress from 0.0 to 1.0.\n\n        @return Progress from 0.0 to 1.0\n    */\n    [[nodiscard]] float estimated_progress() const noexcept;\n\n    /**\n        The best schedule so far.\n\n        @return A schedule.\n    */\n    [[nodiscard]] Schedule schedule() const;\n\n    /**\n        The best makespan so far.\n\n        @return Makespan.\n    */\n    [[nodiscard]] float normalized_makespan() const;\n\n    /**\n        Reset the optimization to initial state.\n    */\n    void reset();\n\n    /**\n        Get the current ScheduleParams object.\n\n        @return Schedule parameters.\n    */\n    [[nodiscard]] const ScheduleParams& params() const;\n\n    /**\n        Set the ScheduleParams object.\n\n        @param params ScheduleParams object\n    */\n    void params(const ScheduleParams& params);\n\nprivate:\n    struct Impl;\n\n    int16 batch_size;\n    int16 max_idle_iters;\n    int16 idle_iters{0};\n    int16 epochs{0};\n    float last_progress{0.F};\n    float last_makespan{0.F};\n    ExpCurveFitter exp_curve;\n\n    /**\n        An optimization job and a PRNG.\n\n        @var random_utils   Random number generator utilities\n        @var job            Optimization job\n    */\n    struct Job {\n        /**\n            Constructor.\n\n            @param params       Scheduling parameters\n            @param batch_size   Number of iterations per update\n        */\n        Job(const ScheduleParams& params, BatchSize batch_size);\n        RandomUtils random_utils;\n        OptimizerJob job;\n    };\n    std::vector<Job> jobs;\n};\n} // namespace angonoka::stun\n", "meta": {"hexsha": "5af8326b86d9cf57d283c530fba41dbb5bec1719", "size": 2797, "ext": "h", "lang": "C", "max_stars_repo_path": "src/stun/optimizer.h", "max_stars_repo_name": "coffee-lord/angonoka", "max_stars_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-10-23T18:05:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T21:53:24.000Z", "max_issues_repo_path": "src/stun/optimizer.h", "max_issues_repo_name": "coffee-lord/angonoka", "max_issues_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2022-02-12T19:52:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-12T19:55:52.000Z", "max_forks_repo_path": "src/stun/optimizer.h", "max_forks_repo_name": "coffee-lord/angonoka", "max_forks_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.7398373984, "max_line_length": 70, "alphanum_fraction": 0.6299606721, "num_tokens": 593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.04146226826976642, "lm_q1q2_score": 0.02056917544449902}}
{"text": "/* permutation/gsl_permutation.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2004, 2007 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_PERMUTATION_H__\n#define __GSL_PERMUTATION_H__\n\n#if !defined( GSL_FUN )\n#  if !defined( GSL_DLL )\n#    define GSL_FUN extern\n#  elif defined( BUILD_GSL_DLL )\n#    define GSL_FUN extern __declspec(dllexport)\n#  else\n#    define GSL_FUN extern __declspec(dllimport)\n#  endif\n#endif\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_inline.h>\n#include <gsl/gsl_check_range.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\nstruct gsl_permutation_struct\n{\n  size_t size;\n  size_t *data;\n};\n\ntypedef struct gsl_permutation_struct gsl_permutation;\n\nGSL_FUN gsl_permutation *gsl_permutation_alloc (const size_t n);\nGSL_FUN gsl_permutation *gsl_permutation_calloc (const size_t n);\nGSL_FUN void gsl_permutation_init (gsl_permutation * p);\nGSL_FUN void gsl_permutation_free (gsl_permutation * p);\nGSL_FUN int gsl_permutation_memcpy (gsl_permutation * dest, const gsl_permutation * src);\n\nGSL_FUN int gsl_permutation_fread (FILE * stream, gsl_permutation * p);\nGSL_FUN int gsl_permutation_fwrite (FILE * stream, const gsl_permutation * p);\nGSL_FUN int gsl_permutation_fscanf (FILE * stream, gsl_permutation * p);\nGSL_FUN int gsl_permutation_fprintf (FILE * stream, const gsl_permutation * p, const char *format);\n\nGSL_FUN size_t gsl_permutation_size (const gsl_permutation * p);\nGSL_FUN size_t * gsl_permutation_data (const gsl_permutation * p);\n\nGSL_FUN int gsl_permutation_swap (gsl_permutation * p, const size_t i, const size_t j);\n\nGSL_FUN int gsl_permutation_valid (const gsl_permutation * p);\nGSL_FUN void gsl_permutation_reverse (gsl_permutation * p);\nGSL_FUN int gsl_permutation_inverse (gsl_permutation * inv, const gsl_permutation * p);\nGSL_FUN int gsl_permutation_next (gsl_permutation * p);\nGSL_FUN int gsl_permutation_prev (gsl_permutation * p);\nGSL_FUN int gsl_permutation_mul (gsl_permutation * p, const gsl_permutation * pa, const gsl_permutation * pb);\n\nGSL_FUN int gsl_permutation_linear_to_canonical (gsl_permutation * q, const gsl_permutation * p);\nGSL_FUN int gsl_permutation_canonical_to_linear (gsl_permutation * p, const gsl_permutation * q);\n\nGSL_FUN size_t gsl_permutation_inversions (const gsl_permutation * p);\nGSL_FUN size_t gsl_permutation_linear_cycles (const gsl_permutation * p);\nGSL_FUN size_t gsl_permutation_canonical_cycles (const gsl_permutation * q);\n\nGSL_FUN INLINE_DECL size_t gsl_permutation_get (const gsl_permutation * p, const size_t i);\n\n#ifdef HAVE_INLINE\n\nINLINE_FUN\nsize_t\ngsl_permutation_get (const gsl_permutation * p, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= p->size))\n    {\n      GSL_ERROR_VAL (\"index out of range\", GSL_EINVAL, 0);\n    }\n#endif\n  return p->data[i];\n}\n\n#endif /* HAVE_INLINE */\n\n__END_DECLS\n\n#endif /* __GSL_PERMUTATION_H__ */\n", "meta": {"hexsha": "c6a6f1668ab8e38882835d2c4341086fbe416913", "size": 3771, "ext": "h", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_permutation.h", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-28T08:20:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-28T08:20:20.000Z", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_permutation.h", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_permutation.h", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-14T12:45:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-14T12:45:35.000Z", "avg_line_length": 33.972972973, "max_line_length": 110, "alphanum_fraction": 0.7761866879, "num_tokens": 1010, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3522017820478897, "lm_q2_score": 0.0583458352901723, "lm_q1q2_score": 0.020549507164271338}}
{"text": "#ifndef petscutils_h\n#define petscutils_h\n\n#include <ceed.h>\n#include <petsc.h>\n#include <petscdmplex.h>\n#include <petscfe.h>\n\nCeedMemType MemTypeP2C(PetscMemType mtype);\nPetscErrorCode ProjectToUnitSphere(DM dm);\nPetscErrorCode Kershaw(DM dm_orig, PetscScalar eps);\ntypedef PetscErrorCode (*BCFunction)(PetscInt dim, PetscReal time,\n                                     const PetscReal x[],\n                                     PetscInt num_comp_u, PetscScalar *u, void *ctx);\nPetscErrorCode SetupDMByDegree(DM dm, PetscInt degree, PetscInt num_comp_u,\n                               PetscInt topo_dim,\n                               bool enforce_bc,  BCFunction bc_func);\nPetscErrorCode CreateRestrictionFromPlex(Ceed ceed, DM dm, CeedInt P,\n    CeedInt topo_dim, CeedInt height, DMLabel domain_label, CeedInt value,\n    CeedElemRestriction *elem_restr);\n\n#endif // petscutils_h\n", "meta": {"hexsha": "a541f39a3700eba46257d0ca410865f2e8fc9ab4", "size": 881, "ext": "h", "lang": "C", "max_stars_repo_path": "examples/petsc/include/petscutils.h", "max_stars_repo_name": "LeilaGhaffari/libCEED", "max_stars_repo_head_hexsha": "4a63c7da274c5bcaedf5323dad2ae658837a33b1", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/petsc/include/petscutils.h", "max_issues_repo_name": "LeilaGhaffari/libCEED", "max_issues_repo_head_hexsha": "4a63c7da274c5bcaedf5323dad2ae658837a33b1", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/petsc/include/petscutils.h", "max_forks_repo_name": "LeilaGhaffari/libCEED", "max_forks_repo_head_hexsha": "4a63c7da274c5bcaedf5323dad2ae658837a33b1", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.3043478261, "max_line_length": 85, "alphanum_fraction": 0.6776390465, "num_tokens": 219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.04272219541354526, "lm_q1q2_score": 0.020527103975604585}}
{"text": "#pragma once\r\n#include <gsl/multi_span>\r\n#include <droidCrypto/Defines.h>\r\n#include <droidCrypto/MatrixView.h>\r\n#include <cstring>\r\n\r\nnamespace droidCrypto\r\n{\r\n    enum class AllocType\r\n    {\r\n        Uninitialized,\r\n        Zeroed\r\n    };\r\n\r\n    template<typename T>\r\n    class Matrix : public MatrixView<T>\r\n    {\r\n        uint64_t mCapacity = 0;\r\n    public:\r\n        Matrix()\r\n        {}\r\n\r\n        Matrix(uint64_t rows, uint64_t columns, AllocType t = AllocType::Zeroed)\r\n        {\r\n            resize(rows, columns, t);\r\n        }\r\n\r\n\r\n\r\n        Matrix(const MatrixView<T>& copy)\r\n            : MatrixView<T>(new T[copy.size()], copy.bounds()[0], copy.stride())\r\n            , mCapacity(copy.size())\r\n        {\r\n            memcpy(MatrixView<T>::mView.data(), copy.data(), copy.mView.size_bytes());\r\n        }\r\n\r\n        Matrix(Matrix<T>&& copy)\r\n            : MatrixView<T>(copy.data(), copy.bounds()[0], copy.stride())\r\n            , mCapacity(copy.mCapacity)\r\n        {\r\n            copy.mView = span<T>();\r\n            copy.mStride = 0;\r\n            copy.mCapacity = 0;\r\n        }\r\n\r\n\r\n        ~Matrix()\r\n        {\r\n            delete[] MatrixView<T>::mView.data();\r\n        }\r\n\r\n\r\n        const Matrix<T>& operator=(const Matrix<T>& copy)\r\n        {\r\n            resize(copy.rows(), copy.stride());\r\n            memcpy(MatrixView<T>::mView.data(), copy.data(), copy.mView.size_bytes());\r\n            return copy;\r\n        }\r\n\r\n\r\n        void resize(uint64_t rows, uint64_t columns, AllocType type = AllocType::Zeroed)\r\n        {\r\n            if (rows * columns > mCapacity)\r\n            {\r\n                mCapacity = rows * columns;\r\n                auto old = MatrixView<T>::mView;\r\n\r\n                if (type == AllocType::Zeroed)\r\n                    MatrixView<T>::mView = span<T>(new T[mCapacity](), mCapacity);\r\n                else\r\n                    MatrixView<T>::mView = span<T>(new T[mCapacity], mCapacity);\r\n\r\n\r\n                auto min = std::min<uint64_t>(old.size(), mCapacity) * sizeof(T);\r\n                memcpy(MatrixView<T>::mView.data(), old.data(), min);\r\n\r\n                delete[] old.data();\r\n\r\n            }\r\n            else\r\n            {\r\n                auto newSize = rows * columns;\r\n                if (newSize > MatrixView<T>::size() && type == AllocType::Zeroed)\r\n                {\r\n                    memset(MatrixView<T>::data() + MatrixView<T>::size(), 0, newSize - MatrixView<T>::size());\r\n                }\r\n\r\n                MatrixView<T>::mView = span<T>(MatrixView<T>::data(), newSize);\r\n            }\r\n\r\n            MatrixView<T>::mStride = columns;\r\n        }\r\n\r\n\r\n        // return the internal memory, stop managing its lifetime, and set the current container to null.\r\n        T* release()\r\n        {\r\n            auto ret = MatrixView<T>::mView.data();\r\n            MatrixView<T>::mView = {};\r\n            mCapacity = 0;\r\n            return ret;\r\n        }\r\n    };\r\n\r\n\r\n}\r\n", "meta": {"hexsha": "0efd2138dbfacef4f855457b95b9f50256a85cf5", "size": 2937, "ext": "h", "lang": "C", "max_stars_repo_path": "droidCrypto/Matrix.h", "max_stars_repo_name": "CROSSINGTUD/mobile_psi_cpp", "max_stars_repo_head_hexsha": "4c5f0f56142535ca0d3524c99781cfd0c07b9205", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-08-16T16:18:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T06:40:50.000Z", "max_issues_repo_path": "droidCrypto/Matrix.h", "max_issues_repo_name": "contact-discovery/mobile_psi_cpp", "max_issues_repo_head_hexsha": "6458cab5add75d592861d9a1ee253cc07b3ab829", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "droidCrypto/Matrix.h", "max_forks_repo_name": "contact-discovery/mobile_psi_cpp", "max_forks_repo_head_hexsha": "6458cab5add75d592861d9a1ee253cc07b3ab829", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-10-11T08:23:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-31T05:40:21.000Z", "avg_line_length": 27.4485981308, "max_line_length": 111, "alphanum_fraction": 0.4759959142, "num_tokens": 628, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29421497216298875, "lm_q2_score": 0.06954174161325838, "lm_q1q2_score": 0.02046022157291057}}
{"text": "/* spswap.c\n * \n * Copyright (C) 2014 Patrick Alken\n * Copyright (C) 2016 Alexis Tantet\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <stdlib.h>\n#include <math.h>\n\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_spmatrix.h>\n\n#include \"avl.c\"\n\n/*\ngsl_spmatrix_transpose()\n  Replace the sparse matrix src by its transpose,\nkeeping the matrix in the same storage format\n\nInputs: A - (input/output) sparse matrix to transpose.\n*/\n\nint\ngsl_spmatrix_transpose(gsl_spmatrix * m)\n{\n  if (GSL_SPMATRIX_ISTRIPLET(m))\n    {\n      size_t n;\n\n      /* swap row/column indices */\n      for (n = 0; n < m->nz; ++n)\n        {\n          size_t tmp = m->p[n];\n          m->p[n] = m->i[n];\n          m->i[n] = tmp;\n        }\n\n      /* need to rebuild AVL tree, or element searches won't\n       * work correctly with transposed indices */\n      gsl_spmatrix_tree_rebuild(m);\n    }\n  else\n    {\n      GSL_ERROR(\"unknown sparse matrix type\", GSL_EINVAL);\n    }\n  \n  /* swap dimensions */\n  if (m->size1 != m->size2)\n    {\n      size_t tmp = m->size1;\n      m->size1 = m->size2;\n      m->size2 = tmp;\n    }\n  \n  return GSL_SUCCESS;\n}\n\n/*\ngsl_spmatrix_transpose2()\n  Replace the sparse matrix src by its transpose either by\n  swapping its row and column indices if it is in triplet storage,\n  or by switching its major if it is in compressed storage.\n\nInputs: A - (input/output) sparse matrix to transpose.\n*/\n\nint\ngsl_spmatrix_transpose2(gsl_spmatrix * m)\n{\n  if (GSL_SPMATRIX_ISTRIPLET(m))\n    {\n      return gsl_spmatrix_transpose(m);\n    }\n  else if (GSL_SPMATRIX_ISCCS(m))\n    {\n      m->sptype = GSL_SPMATRIX_CRS;\n    }\n  else if (GSL_SPMATRIX_ISCRS(m))\n    {\n      m->sptype = GSL_SPMATRIX_CCS;\n    }\n  else\n    {\n      GSL_ERROR(\"unknown sparse matrix type\", GSL_EINVAL);\n    }\n  \n  /* swap dimensions */\n  if (m->size1 != m->size2)\n    {\n      size_t tmp = m->size1;\n      m->size1 = m->size2;\n      m->size2 = tmp;\n    }\n  \n  return GSL_SUCCESS;\n}\n\nint\ngsl_spmatrix_transpose_memcpy(gsl_spmatrix *dest, const gsl_spmatrix *src)\n{\n  const size_t M = src->size1;\n  const size_t N = src->size2;\n\n  if (M != dest->size2 || N != dest->size1)\n    {\n      GSL_ERROR(\"dimensions of dest must be transpose of src matrix\",\n                GSL_EBADLEN);\n    }\n  else if (dest->sptype != src->sptype)\n    {\n      GSL_ERROR(\"cannot copy matrices of different storage formats\",\n                GSL_EINVAL);\n    }\n  else\n    {\n      int s = GSL_SUCCESS;\n      const size_t nz = src->nz;\n\n      if (dest->nzmax < src->nz)\n        {\n          s = gsl_spmatrix_realloc(src->nz, dest);\n          if (s)\n            return s;\n        }\n\n      if (GSL_SPMATRIX_ISTRIPLET(src))\n        {\n          size_t n;\n          void *ptr;\n\n          for (n = 0; n < nz; ++n)\n            {\n              dest->i[n] = src->p[n];\n              dest->p[n] = src->i[n];\n              dest->data[n] = src->data[n];\n\n              /* copy binary tree data */\n              ptr = avl_insert(dest->tree_data->tree, &dest->data[n]);\n              if (ptr != NULL)\n                {\n                  GSL_ERROR(\"detected duplicate entry\", GSL_EINVAL);\n                }\n            }\n        }\n      else if (GSL_SPMATRIX_ISCCS(src))\n        {\n          size_t *Ai = src->i;\n          size_t *Ap = src->p;\n          double *Ad = src->data;\n          size_t *ATi = dest->i;\n          size_t *ATp = dest->p;\n          double *ATd = dest->data;\n          size_t *w = (size_t *) dest->work;\n          size_t p, j;\n\n          /* initialize to 0 */\n          for (p = 0; p < M + 1; ++p)\n            ATp[p] = 0;\n\n          /* compute row counts of A (= column counts for A^T) */\n          for (p = 0; p < nz; ++p)\n            ATp[Ai[p]]++;\n\n          /* compute row pointers for A (= column pointers for A^T) */\n          gsl_spmatrix_cumsum(M, ATp);\n\n          /* make copy of row pointers */\n          for (j = 0; j < M; ++j)\n            w[j] = ATp[j];\n\n          for (j = 0; j < N; ++j)\n            {\n              for (p = Ap[j]; p < Ap[j + 1]; ++p)\n                {\n                  size_t k = w[Ai[p]]++;\n                  ATi[k] = j;\n                  ATd[k] = Ad[p];\n                }\n            }\n        }\n      else if (GSL_SPMATRIX_ISCRS(src))\n        {\n          size_t *Aj = src->i;\n          size_t *Ap = src->p;\n          double *Ad = src->data;\n          size_t *ATj = dest->i;\n          size_t *ATp = dest->p;\n          double *ATd = dest->data;\n          size_t *w = (size_t *) dest->work;\n          size_t p, i;\n\n          /* initialize to 0 */\n          for (p = 0; p < N + 1; ++p)\n            ATp[p] = 0;\n\n          /* compute column counts of A (= row counts for A^T) */\n          for (p = 0; p < nz; ++p)\n            ATp[Aj[p]]++;\n\n          /* compute column pointers for A (= row pointers for A^T) */\n          gsl_spmatrix_cumsum(N, ATp);\n\n          /* make copy of column pointers */\n          for (i = 0; i < N; ++i)\n            w[i] = ATp[i];\n\n          for (i = 0; i < M; ++i)\n            {\n              for (p = Ap[i]; p < Ap[i + 1]; ++p)\n                {\n                  size_t k = w[Aj[p]]++;\n                  ATj[k] = i;\n                  ATd[k] = Ad[p];\n                }\n            }\n        }\n      else\n        {\n          GSL_ERROR(\"unknown sparse matrix type\", GSL_EINVAL);\n        }\n\n      dest->nz = nz;\n\n      return s;\n    }\n} /* gsl_spmatrix_transpose_memcpy() */\n", "meta": {"hexsha": "a54876f6cd87988203523ec58273684f50b9617e", "size": 6118, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.4/spmatrix/spswap.c", "max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-13T05:01:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-13T05:01:59.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/spmatrix/spswap.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/spmatrix/spswap.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0737704918, "max_line_length": 81, "alphanum_fraction": 0.5125858124, "num_tokens": 1732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.048857774813604704, "lm_q1q2_score": 0.0204565993124524}}
{"text": "#ifndef __STATS_H__\n#define __STATS_H__\n\n#include <stdint.h>\n#include <time.h>\n#include <sys/time.h>\n#include <sys/resource.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <assert.h>\n#include <inttypes.h>\n\n#include <gsl/gsl_rstat.h>\n\ntypedef uint64_t word;\n\n#define TIMER_STACK 8\nenum Timer{MutTimer, Gen0Timer, Gen1Timer, MiscTimer, MaxTimer};\n\ntypedef struct {\n  uint64_t allocated;\n  uint64_t nursery_n_collections;\n  uint64_t nursery_time_max;\n  uint64_t nursery_copied;\n\n  uint64_t gen1_collections;\n  uint64_t gen1_copied;\n\n  uint64_t max_heap;\n  uint64_t max_residency;\n\n  uint64_t start_time;\n  enum Timer active_timer[TIMER_STACK];\n  uint64_t n_timers;\n  uint64_t timers[MaxTimer];\n\n  gsl_rstat_quantile_workspace *latency_50;\n  gsl_rstat_quantile_workspace *latency_90;\n  gsl_rstat_quantile_workspace *latency_99;\n} Stats;\n\nvoid stats_init(Stats *s);\nvoid stats_pprint(Stats *s);\n\nstatic uint64_t clock_gettime_nsec(clockid_t clk_id) {\n  struct timespec t;\n  clock_gettime(clk_id,&t);\n  return (uint64_t)t.tv_sec*1e9 + t.tv_nsec;\n}\n\nstatic char *pp_time(uint64_t time) {\n  static int i=0;\n  static char buffer[10][128];\n  i = (i+1) % 10;\n  if(time < 1000000) {\n    snprintf(buffer[i], 128, \"%4.0f us\", ((double)time)/1000);\n  } else if(time < 10000000) {\n    snprintf(buffer[i], 128, \"%4.2f ms\", ((double)time)/1000000);\n  } else if(time < 100000000) {\n    snprintf(buffer[i], 128, \"%4.1f ms\", ((double)time)/1000000);\n  } else if(time < 1000000000) {\n    snprintf(buffer[i], 128, \"%4.0f ms\", ((double)time)/1000000);\n  } else {\n    snprintf(buffer[i], 128, \"%4.2f s\", ((double)time)/1000000000);\n  }\n  return buffer[i];\n}\n\nstatic char *pp_speed(uint64_t words, uint64_t time) {\n  static int i=0;\n  static char buffer[10][128];\n  uint64_t rate = words*8/1024 / (time/1e9);\n  i = (i+1) % 10;\n  if(rate < 1024) {\n    snprintf(buffer[i], 128, \"%4\" PRIu64 \" KB/s\", rate);\n  } if(rate < 1024*1024*10) { // Less than 10000 MB/s\n    snprintf(buffer[i], 128, \"%4\" PRIu64 \" MB/s\", rate/1024);\n  } else {\n    snprintf(buffer[i], 128, \"%4.1f GB/s\", (double)rate/1024/1024);\n  }\n  return buffer[i];\n}\n\nstatic char *pp_bytes(uint64_t words) {\n  static int i=0;\n  static char buffer[10][128];\n  uint64_t bytes = words * 8;\n  i = (i+1) % 10;\n  if(bytes < 1024) {\n    snprintf(buffer[i], 128, \"%4\" PRIu64 \" B\", bytes);\n  } else if(bytes < 1024*1024) {\n    snprintf(buffer[i], 128, \"%4\" PRIu64 \" KB\", bytes/1024);\n  } else if(bytes < (uint64_t)1024*1024*1024*10) {\n    snprintf(buffer[i], 128, \"%4\" PRIu64 \" MB\", bytes/1024/1024);\n  } else {\n    snprintf(buffer[i], 128, \"%4.1f GB\", ((double)bytes)/1024/1024/1024);\n  }\n  return buffer[i];\n}\n\n\n#define CLOCK_ID CLOCK_PROCESS_CPUTIME_ID\n\nstatic void stats_timer_begin(Stats *s, enum Timer t) {\n  uint64_t now = clock_gettime_nsec(CLOCK_ID);\n  assert(s->n_timers < TIMER_STACK);\n  s->active_timer[s->n_timers] = t;\n  if(s->n_timers > 0) {\n    s->timers[s->active_timer[s->n_timers-1]] += now - s->start_time;\n  }\n\n  s->n_timers++;\n  s->start_time = now;\n}\nstatic void stats_timer_end(Stats *s) {\n  uint64_t now = clock_gettime_nsec(CLOCK_ID);\n  uint64_t t = now - s->start_time;\n  assert(s->n_timers > 0);\n  if(s->active_timer[s->n_timers-1] == Gen0Timer) {\n    gsl_rstat_quantile_add((double)t, s->latency_50);\n    gsl_rstat_quantile_add((double)t, s->latency_90);\n    gsl_rstat_quantile_add((double)t, s->latency_99);\n    if(t > s->nursery_time_max) {\n      s->nursery_time_max = t;\n    }\n  }\n  s->timers[s->active_timer[s->n_timers-1]] += t;\n  s->start_time = now;\n  s->n_timers--;\n}\n\n#endif\n", "meta": {"hexsha": "e04d814d7f906a629701bf7fb91dde7a3c206d72", "size": 3539, "ext": "h", "lang": "C", "max_stars_repo_path": "experiments/gc/stats.h", "max_stars_repo_name": "Lemmih/lhc", "max_stars_repo_head_hexsha": "53bfa57b9b7275b7737dcf9dd620533d0261be66", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 193.0, "max_stars_repo_stars_event_min_datetime": "2015-01-07T01:25:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-07T13:52:13.000Z", "max_issues_repo_path": "experiments/gc/stats.h", "max_issues_repo_name": "lemmih/lhc", "max_issues_repo_head_hexsha": "53bfa57b9b7275b7737dcf9dd620533d0261be66", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2017-10-25T04:10:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-27T06:30:34.000Z", "max_forks_repo_path": "experiments/gc/stats.h", "max_forks_repo_name": "lemmih/lhc", "max_forks_repo_head_hexsha": "53bfa57b9b7275b7737dcf9dd620533d0261be66", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2015-05-12T13:25:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-13T21:01:38.000Z", "avg_line_length": 26.6090225564, "max_line_length": 73, "alphanum_fraction": 0.6674201752, "num_tokens": 1209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.05261895260488792, "lm_q1q2_score": 0.02025367388764587}}
{"text": "/* block/test.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <fcntl.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <gsl/gsl_block.h>\n#include <gsl/gsl_ieee_utils.h>\n#include <gsl/gsl_test.h>\n\nint status = 0;\n\n#ifndef DESC\n#define DESC \"\"\n#endif\n\n#define N 1027\n\n\n#define BASE_GSL_COMPLEX_LONG\n#include \"templates_on.h\"\n#include \"test_complex_source.c\"\n#if HAVE_PRINTF_LONGDOUBLE\n#include \"test_complex_io.c\"\n#endif\n#include \"templates_off.h\"\n#undef  BASE_GSL_COMPLEX_LONG\n\n\n#define BASE_GSL_COMPLEX\n#include \"templates_on.h\"\n#include \"test_complex_source.c\"\n#include \"test_complex_io.c\"\n#include \"templates_off.h\"\n#undef  BASE_GSL_COMPLEX\n\n#define BASE_GSL_COMPLEX_FLOAT\n#include \"templates_on.h\"\n#include \"test_complex_source.c\"\n#include \"test_complex_io.c\"\n#include \"templates_off.h\"\n#undef  BASE_GSL_COMPLEX_FLOAT\n\n#define BASE_LONG_DOUBLE\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#if HAVE_PRINTF_LONGDOUBLE\n#include \"test_io.c\"\n#endif\n#include \"templates_off.h\"\n#undef  BASE_LONG_DOUBLE\n\n#define BASE_DOUBLE\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"test_io.c\"\n#include \"templates_off.h\"\n#undef  BASE_DOUBLE\n\n#define BASE_FLOAT\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"test_io.c\"\n#include \"templates_off.h\"\n#undef  BASE_FLOAT\n\n#define BASE_ULONG\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"test_io.c\"\n#include \"templates_off.h\"\n#undef  BASE_ULONG\n\n#define BASE_LONG\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"test_io.c\"\n#include \"templates_off.h\"\n#undef  BASE_LONG\n\n#define BASE_UINT\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"test_io.c\"\n#include \"templates_off.h\"\n#undef  BASE_UINT\n\n#define BASE_INT\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"test_io.c\"\n#include \"templates_off.h\"\n#undef  BASE_INT\n\n#define BASE_USHORT\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"test_io.c\"\n#include \"templates_off.h\"\n#undef  BASE_USHORT\n\n#define BASE_SHORT\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"test_io.c\"\n#include \"templates_off.h\"\n#undef  BASE_SHORT\n\n#define BASE_UCHAR\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"test_io.c\"\n#include \"templates_off.h\"\n#undef  BASE_UCHAR\n\n#define BASE_CHAR\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"test_io.c\"\n#include \"templates_off.h\"\n#undef  BASE_CHAR\n\nvoid my_error_handler (const char *reason, const char *file,\n                       int line, int err);\n\nint\nmain (void)\n{\n  gsl_ieee_env_setup ();\n\n  test_func ();\n  test_float_func ();\n  test_long_double_func ();\n  test_ulong_func ();\n  test_long_func ();\n  test_uint_func ();\n  test_int_func ();\n  test_ushort_func ();\n  test_short_func ();\n  test_uchar_func ();\n  test_char_func ();\n  test_complex_func ();\n  test_complex_float_func ();\n  test_complex_long_double_func ();\n\n  test_text ();\n  test_float_text ();\n#if HAVE_PRINTF_LONGDOUBLE\n  test_long_double_text ();\n#endif\n  test_ulong_text ();\n  test_long_text ();\n  test_uint_text ();\n  test_int_text ();\n  test_ushort_text ();\n  test_short_text ();\n  test_uchar_text ();\n  test_char_text ();\n  test_complex_text ();\n  test_complex_float_text ();\n#if HAVE_PRINTF_LONGDOUBLE\n  test_complex_long_double_text ();\n#endif\n\n  test_binary ();\n  test_float_binary ();\n  test_long_double_binary ();\n  test_ulong_binary ();\n  test_long_binary ();\n  test_uint_binary ();\n  test_int_binary ();\n  test_ushort_binary ();\n  test_short_binary ();\n  test_uchar_binary ();\n  test_char_binary ();\n  test_complex_binary ();\n  test_complex_float_binary ();\n  test_complex_long_double_binary ();\n\n  gsl_set_error_handler (&my_error_handler);\n\n  test_alloc_zero_length ();\n  test_float_alloc_zero_length ();\n  test_long_double_alloc_zero_length ();\n  test_ulong_alloc_zero_length ();\n  test_long_alloc_zero_length ();\n  test_uint_alloc_zero_length ();\n  test_int_alloc_zero_length ();\n  test_ushort_alloc_zero_length ();\n  test_short_alloc_zero_length ();\n  test_uchar_alloc_zero_length ();\n  test_char_alloc_zero_length ();\n  test_complex_alloc_zero_length ();\n  test_complex_float_alloc_zero_length ();\n  test_complex_long_double_alloc_zero_length ();\n\n  test_calloc_zero_length ();\n  test_float_calloc_zero_length ();\n  test_long_double_calloc_zero_length ();\n  test_ulong_calloc_zero_length ();\n  test_long_calloc_zero_length ();\n  test_uint_calloc_zero_length ();\n  test_int_calloc_zero_length ();\n  test_ushort_calloc_zero_length ();\n  test_short_calloc_zero_length ();\n  test_uchar_calloc_zero_length ();\n  test_char_calloc_zero_length ();\n  test_complex_calloc_zero_length ();\n  test_complex_float_calloc_zero_length ();\n  test_complex_long_double_calloc_zero_length ();\n\n  exit (gsl_test_summary ());\n}\n\nvoid\nmy_error_handler (const char *reason, const char *file, int line, int err)\n{\n  if (0)\n    printf (\"(caught [%s:%d: %s (%d)])\\n\", file, line, reason, err);\n  status = 1;\n}\n", "meta": {"hexsha": "fc104175e41f676f3d678e99112151b656320081", "size": 5700, "ext": "c", "lang": "C", "max_stars_repo_path": "tests/libs/gsl/tests/block/test.c", "max_stars_repo_name": "utdsimmons/ohpc", "max_stars_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 692.0, "max_stars_repo_stars_event_min_datetime": "2015-11-12T13:56:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:45:59.000Z", "max_issues_repo_path": "tests/libs/gsl/tests/block/test.c", "max_issues_repo_name": "utdsimmons/ohpc", "max_issues_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1096.0, "max_issues_repo_issues_event_min_datetime": "2015-11-12T09:08:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:48:41.000Z", "max_forks_repo_path": "tests/libs/gsl/tests/block/test.c", "max_forks_repo_name": "utdsimmons/ohpc", "max_forks_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 224.0, "max_forks_repo_forks_event_min_datetime": "2015-11-12T21:17:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T00:57:48.000Z", "avg_line_length": 23.8493723849, "max_line_length": 81, "alphanum_fraction": 0.7533333333, "num_tokens": 1364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834617637482, "lm_q2_score": 0.042722193280600056, "lm_q1q2_score": 0.020194074214013976}}
{"text": "/*\nGENETIC - A simple genetic algorithm.\n\nCopyright 2014, Javier Burguete Tolosa.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\n\tlist of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice,\n\tthis list of conditions and the following disclaimer in the documentation\n\tand/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``AS IS'' AND ANY EXPRESS\nOR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\nEVENT SHALL Javier Burguete Tolosa OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\nINDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\nBUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\nADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n/**\n * \\file genetic.c\n * \\brief Source file to define genetic algorithm main function.\n * \\author Javier Burguete Tolosa.\n * \\copyright Copyright 2014 Javier Burguete Tolosa. All rights reserved.\n */\n#define _GNU_SOURCE\n#include <stdio.h>\n#include <string.h>\n#include <math.h>\n#include <gsl/gsl_rng.h>\n#include <glib.h>\n#if HAVE_MPI\n#include <mpi.h>\n#endif\n#include \"bits.h\"\n#include \"entity.h\"\n#include \"population.h\"\n#include \"reproduction.h\"\n#include \"selection.h\"\n#include \"evolution.h\"\n#include \"genetic.h\"\n\n#define DEBUG_GENETIC 0         ///< Macro to debug the genetic functions.\n\nstatic Population genetic_population[1];\n///< Population of the genetic algorithm.\nstatic double (*genetic_simulation) (Entity *);\n///< Pointer to the function to perform a simulation.\n\n/**\n * Function to get a variable encoded in the genome of an entity.\n *\n * \\return Variable value.\n */\ndouble\ngenetic_get_variable (Entity * entity,  ///< Entity struct.\n                      GeneticVariable * variable)       ///< Variable data.\n{\n  double x;\n#if DEBUG_GENETIC\n  fprintf (stderr, \"get variable: start\\n\");\n#endif\n  x = variable->minimum\n    + bit_get_value (entity->genome, variable->location, variable->nbits)\n    * (variable->maximum - variable->minimum)\n    / ((unsigned long long int) 1L << variable->nbits);\n#if DEBUG_GENETIC\n  fprintf (stderr, \"get variable: value=%lg\\n\", x);\n  fprintf (stderr, \"get variable: end\\n\");\n#endif\n  return x;\n}\n\n/**\n * Funtion to apply the evolution of a population.\n */\nstatic inline void\ngenetic_evolution (Population * population,     ///< Population\n                   gsl_rng * rng)       ///< GSL random numbers generator.\n{\n#if DEBUG_GENETIC\n  fprintf (stderr, \"genetic_evolution: start\\n\");\n#endif\n  evolution_mutation (population, rng);\n  evolution_reproduction (population, rng);\n  evolution_adaptation (population, rng);\n#if DEBUG_GENETIC\n  fprintf (stderr, \"genetic_evolution: end\\n\");\n#endif\n}\n\n/**\n * Funtion to perform the simulations on a thread.\n */\nstatic void\ngenetic_simulation_thread (GeneticThreadData * data)    ///< Thread data.\n{\n  unsigned int i;\n#if DEBUG_GENETIC\n  fprintf (stderr, \"genetic_simulation_thread: start\\n\");\n  fprintf (stderr, \"genetic_simulation_thread: nmin=%u nmax=%u\\n\",\n           data->nmin, data->nmax);\n#endif\n  for (i = data->nmin; i < data->nmax && !genetic_population->stop; ++i)\n    {\n      genetic_population->objective[i]\n        = genetic_simulation (genetic_population->entity + i);\n      if (genetic_population->objective[i] < genetic_population->threshold)\n        {\n          g_mutex_lock (mutex);\n          genetic_population->stop = 1;\n          g_mutex_unlock (mutex);\n          break;\n        }\n    }\n#if DEBUG_GENETIC\n  fprintf (stderr, \"genetic_simulation_thread: end\\n\");\n#endif\n}\n\n/**\n * Function to perform the simulations on a task.\n */\nstatic void\ngenetic_simulation_master (unsigned int nsurvival)\n                           ///< Number of survival entities already simulated.\n{\n  unsigned int j, nsimulate, nmin, nmax;\n  GThread *thread[nthreads];\n  GeneticThreadData thread_data[nthreads];\n  Population *population;\n#if HAVE_MPI\n  unsigned int i;\n  unsigned int n[ntasks + 1];\n  unsigned int stop[ntasks];\n  char *genome_array;\n  MPI_Status mpi_status;\n#endif\n\n#if DEBUG_GENETIC\n  fprintf (stderr, \"genetic_simulation_master: start\\n\");\n#endif\n\n  population = genetic_population;\n  nmax = population->nentities;\n  nsimulate = nmax - nsurvival;\n  nmin = nsurvival;\n#if DEBUG_GENETIC\n  fprintf (stderr, \"genetic_simulation_master: nmax=%u nmin=%u nsimulate=%u\\n\",\n           nmax, nmin, nsimulate);\n#endif\n\n#if HAVE_MPI\n  nmax = nmin + nsimulate / ntasks;\n\n  // Send genome information to the slaves\n#if DEBUG_GENETIC\n  fprintf (stderr, \"genetic_simulation_master: nmax=%u nmin=%u nsimulate=%u\\n\",\n           nmax, nmin, nsimulate);\n#endif\n\n  genome_array = (char *) g_malloc (nsimulate * population->genome_nbytes);\n  for (j = 0; j < nsimulate; ++j)\n    memcpy (genome_array + j * population->genome_nbytes,\n            population->entity[nmin + j].genome, population->genome_nbytes);\n  n[0] = 0;\n  for (i = 0; (int) ++i < ntasks;)\n    {\n      n[i] = i * nsimulate / ntasks;\n      j = (i + 1) * nsimulate / ntasks - n[i];\n#if DEBUG_GENETIC\n      fprintf (stderr,\n               \"genetic_simulation_master: send %u bytes on %u to task %u\\n\",\n               j * population->genome_nbytes, nsurvival + n[i], i);\n#endif\n      MPI_Send (genome_array + n[i] * population->genome_nbytes,\n                j * population->genome_nbytes, MPI_CHAR, i, 1, MPI_COMM_WORLD);\n    }\n  n[i] = nsimulate;\n\n#if DEBUG_GENETIC\n  for (j = 0; j <= ntasks; ++j)\n    fprintf (stderr, \"genetic_simulation_master: n[%u]=%u\\n\", j, n[j]);\n#endif\n  g_free (genome_array);\n\n  nsimulate = nmax - nmin;\n\n#endif\n\n#if DEBUG_GENETIC\n  fprintf (stderr, \"genetic_simulation_master: nsimulate=%u\\n\", nsimulate);\n  fprintf (stderr, \"genetic_simulation_master: performing simulations\\n\");\n#endif\n\n  thread_data[0].nmin = nmin;\n  for (j = 0; ++j < nthreads;)\n    thread_data[j - 1].nmax = thread_data[j].nmin\n      = nmin + j * nsimulate / nthreads;\n  thread_data[j - 1].nmax = nmax;\n  for (j = 0; j < nthreads; ++j)\n    thread[j] = g_thread_new\n      (NULL, (GThreadFunc) (void (*)(void)) genetic_simulation_thread,\n       thread_data + j);\n  for (j = 0; j < nthreads; ++j)\n    g_thread_join (thread[j]);\n\n#if HAVE_MPI\n  // Receive objective function resuts from the slaves\n  for (j = 0; (int) ++j < ntasks;)\n    {\n#if DEBUG_GENETIC\n      fprintf (stderr,\n               \"genetic_simulation_master: \"\n               \"receive %u reals from task %u on %u\\n\",\n               n[j + 1] - n[j], j, nsurvival + n[j]);\n#endif\n      MPI_Recv (population->objective + nsurvival + n[j], n[j + 1] - n[j],\n                MPI_DOUBLE, j, 1, MPI_COMM_WORLD, &mpi_status);\n#if DEBUG_GENETIC\n      fprintf (stderr,\n               \"genetic_simulation_master: receive one integer from task %u\\n\",\n               j);\n#endif\n      MPI_Recv (stop + j, j, MPI_UNSIGNED, j, 1, MPI_COMM_WORLD, &mpi_status);\n      if (stop[j])\n        genetic_population->stop = 1;\n    }\n  // Sending stop instruction to the slaves\n  for (j = 0; (int) ++j < ntasks;)\n    {\n#if DEBUG_GENETIC\n      fprintf (stderr,\n               \"genetic_simulation_master: sending one integer to task %u\\n\",\n               j);\n#endif\n      MPI_Send (&genetic_population->stop, 1, MPI_UNSIGNED, j, 1,\n                MPI_COMM_WORLD);\n    }\n#endif\n\n#if DEBUG_GENETIC\n  fprintf (stderr, \"genetic_simulation_master: end\\n\");\n#endif\n}\n\n#if HAVE_MPI\n\n/**\n * Function to perform the simulations on a task.\n */\nstatic void\ngenetic_simulation_slave (unsigned int nsurvival,\n                          ///< Number of survival entities already simulated.\n                          int rank)     ///< Number of task.\n{\n  unsigned int j, nsimulate, nmin, nmax, stop;\n  GThread *thread[nthreads];\n  GeneticThreadData thread_data[nthreads];\n  Population *population;\n  char *genome_array;\n  MPI_Status mpi_status;\n\n#if DEBUG_GENETIC\n  fprintf (stderr, \"genetic_simulation_slave: rank=%d start\\n\", rank);\n#endif\n\n  population = genetic_population;\n  nmax = population->nentities;\n  nsimulate = nmax - nsurvival;\n  nmin = nsurvival;\n  nmax = nmin + (rank + 1) * nsimulate / ntasks;\n  nmin += rank * nsimulate / ntasks;\n\n  // Receive genome information from the master\n  nsimulate = nmax - nmin;\n  genome_array = (char *) g_malloc (nsimulate * population->genome_nbytes);\n#if DEBUG_GENETIC\n  fprintf (stderr,\n           \"genetic_simulation_slave: rank=%d receive %u bytes from master\\n\",\n           rank, nsimulate * population->genome_nbytes);\n#endif\n  MPI_Recv (genome_array, nsimulate * population->genome_nbytes, MPI_CHAR, 0,\n            1, MPI_COMM_WORLD, &mpi_status);\n#if DEBUG_GENETIC\n  fprintf (stderr, \"genetic_simulation_slave: rank=%d nmin=%u nsimulate=%u\\n\",\n           rank, nmin, nsimulate);\n#endif\n  for (j = 0; j < nsimulate; ++j)\n    memcpy (population->entity[nmin + j].genome,\n            genome_array + j * population->genome_nbytes,\n            population->genome_nbytes);\n#if DEBUG_GENETIC\n  fprintf (stderr, \"genetic_simulation_slave: rank=%d freeing\\n\", rank);\n#endif\n  g_free (genome_array);\n\n#if DEBUG_GENETIC\n  fprintf (stderr, \"genetic_simulation_slave: rank=%d performing simulations\\n\",\n           rank);\n#endif\n  thread_data[0].nmin = nmin;\n  for (j = 0; ++j < nthreads;)\n    thread_data[j - 1].nmax = thread_data[j].nmin\n      = nmin + j * nsimulate / nthreads;\n  thread_data[j - 1].nmax = nmax;\n  for (j = 0; j < nthreads; ++j)\n    thread[j] = g_thread_new\n      (NULL, (GThreadFunc) (void (*)(void)) genetic_simulation_thread,\n       thread_data + j);\n  for (j = 0; j < nthreads; ++j)\n    g_thread_join (thread[j]);\n\n#if DEBUG_GENETIC\n  fprintf (stderr,\n           \"genetic_simulation_slave: rank=%d send %u reals on %u to master\\n\",\n           rank, nsimulate, nmin);\n#endif\n  // Send the objective function resuts to the master\n  MPI_Send (population->objective + nmin, nsimulate, MPI_DOUBLE, 0, 1,\n            MPI_COMM_WORLD);\n#if DEBUG_GENETIC\n  fprintf (stderr,\n           \"genetic_simulation_slave: rank=%d send one integer to master\\n\",\n           rank);\n#endif\n  // Send the stop variable from the master\n  MPI_Send (&genetic_population->stop, 1, MPI_UNSIGNED, 0, 1, MPI_COMM_WORLD);\n#if DEBUG_GENETIC\n  fprintf (stderr,\n           \"genetic_simulation_slave: \"\n           \"rank=%d receive one integer from master\\n\", rank);\n#endif\n  // Receive the stop variable from the master\n  MPI_Recv (&stop, 1, MPI_UNSIGNED, 0, 1, MPI_COMM_WORLD, &mpi_status);\n  if (stop)\n    genetic_population->stop = 1;\n\n#if DEBUG_GENETIC\n  fprintf (stderr, \"genetic_simulation_slave: rank=%d end\\n\", rank);\n#endif\n}\n\n#endif\n\n/**\n * Function to create the data of the genetic algorithm.\n *\n * \\return 1 on succes, 0 on error.\n */\nint\ngenetic_new (unsigned int nvariables,   ///< Number of variables.\n             GeneticVariable * variable,        ///< Array of variables data.\n             unsigned int nentities,\n             ///< Number of entities in each generation.\n             double mutation_ratio,     ///< Mutation ratio.\n             double reproduction_ratio, ///< Reproduction ratio.\n             double adaptation_ratio,   ///< Adaptation ratio.\n             double threshold)  ///< Threshold to finish the simulations.\n{\n  unsigned int i, genome_nbits, nprocesses;\n\n#if DEBUG_GENETIC\n  fprintf (stderr, \"genetic_new: start\\n\");\n#endif\n\n  // Checking variables number\n  if (!nvariables)\n    {\n      fprintf (stderr, \"ERROR: no variables\\n\");\n      return 0;\n    }\n\n  // Checking variable bits number\n  for (i = genome_nbits = 0; i < nvariables; ++i)\n    {\n      if (!variable[i].nbits || variable[i].nbits > 32)\n        {\n          fprintf (stderr, \"ERROR: bad bits number in variable %u\\n\", i + 1);\n          return 0;\n        }\n      variable[i].location = genome_nbits;\n      genome_nbits += variable[i].nbits;\n    }\n\n  // Checking processes number\n  nprocesses = ntasks * nthreads;\n  if (!nprocesses)\n    {\n      fprintf (stderr, \"ERROR: no processes\\n\");\n      return 0;\n    }\n\n  // Init the population\n#if DEBUG_GENETIC\n  fprintf (stderr, \"genetic_new: init the population\\n\");\n#endif\n  if (!population_new (genetic_population, variable, nvariables, genome_nbits,\n                       nentities, mutation_ratio, reproduction_ratio,\n                       adaptation_ratio, threshold))\n    return 0;\n\n#if DEBUG_GENETIC\n  fprintf (stderr, \"genetic_new: end\\n\");\n#endif\n  return 1;\n}\n\n/**\n * Function to perform the genetic algorithm.\n *\n * \\return 1 on succes, 0 on error.\n */\nint\ngenetic_algorithm (unsigned int nvariables,     ///< Number of variables.\n                   GeneticVariable * variable,  ///< Array of variables data.\n                   unsigned int nentities,\n                   ///< Number of entities in each generation.\n                   unsigned int ngenerations,   ///< Number of generations.\n                   double mutation_ratio,       ///< Mutation ratio.\n                   double reproduction_ratio,   ///< Reproduction ratio.\n                   double adaptation_ratio,     ///< Adaptation ratio.\n                   const gsl_rng_type * type_random,\n                   ///< Type of GSL random numbers generator algorithm.\n                   unsigned long random_seed,\n                   ///< Seed of the GSL random numbers generator.\n                   unsigned int type_reproduction,\n                   ///< Type of reproduction algorithm.\n                   unsigned int type_selection_mutation,\n                   ///< Type of mutation selection algorithm.\n                   unsigned int type_selection_reproduction,\n                   ///< Type of reproduction selection algorithm.\n                   unsigned int type_selection_adaptation,\n                   ///< Type of adaptation selection algorithm.\n                   double threshold,\n                   ///< Threshold to finish the simulations.\n                   double (*simulate_entity) (Entity *),\n///< Pointer to the function to perform a simulation of an entity.\n                   char **best_genome,  ///< Best genome.\n                   double **best_variables,     ///< Best array of variables.\n                   double *best_objective)\n                   ///< Best objective function value.\n{\n  unsigned int i;\n  double *bv;\n  gsl_rng *rng;\n  Entity *best_entity;\n#if HAVE_MPI\n  int rank;\n#endif\n\n#if DEBUG_GENETIC\n  fprintf (stderr, \"genetic_algorithm: start\\n\");\n#endif\n\n  // Init the data\n  if (!genetic_new (nvariables, variable, nentities,\n                    mutation_ratio, reproduction_ratio, adaptation_ratio,\n                    threshold))\n    return 0;\n\n  // Init the evaluation function\n  genetic_simulation = simulate_entity;\n\n  // Get the rank\n#if HAVE_MPI\n  MPI_Comm_rank (MPI_COMM_WORLD, &rank);\n#endif\n\n  // Variables to init only by master task\n#if HAVE_MPI\n  if (rank == 0)\n    {\n#endif\n      // Init the GSL random numbers generator\n      rng = gsl_rng_alloc (type_random);\n      if (random_seed)\n        gsl_rng_set (rng, random_seed);\n\n      // Init genomes\n      population_init_genomes (genetic_population, rng);\n\n      // Init selection, mutation and reproduction algorithms\n      reproduction_init (type_reproduction);\n      selection_init (type_selection_mutation, type_selection_reproduction,\n                      type_selection_adaptation);\n\n#if HAVE_MPI\n    }\n  if (rank == 0)\n    {\n#endif\n\n      // First simulation of all entities\n#if DEBUG_GENETIC\n      fprintf (stderr, \"genetic_algorithm: first simulation of all entities\\n\");\n#endif\n      genetic_simulation_master (0);\n\n      // Sorting by objective function results\n#if DEBUG_GENETIC\n      fprintf (stderr,\n               \"genetic_algorithm: sorting by objective function results\\n\");\n#endif\n      evolution_sort (genetic_population);\n\n      // Population generations\n#if DEBUG_GENETIC\n      fprintf (stderr, \"genetic_algorithm: ngenerations=%u\\n\", ngenerations);\n#endif\n      for (i = 1; i < ngenerations && !genetic_population->stop; ++i)\n        {\n          // Evolution\n#if DEBUG_GENETIC\n          fprintf (stderr, \"genetic_algorithm: evolution of the population\\n\");\n#endif\n          genetic_evolution (genetic_population, rng);\n\n          // Simulation of the new entities\n#if DEBUG_GENETIC\n          fprintf (stderr,\n                   \"genetic_algorithm: simulation of the new entities\\n\");\n#endif\n          genetic_simulation_master (genetic_population->nsurvival);\n\n          // Sorting by objective function results\n#if DEBUG_GENETIC\n          fprintf (stderr,\n                   \"genetic_algorithm: sorting by objective function results\\n\");\n#endif\n          evolution_sort (genetic_population);\n        }\n\n      // Saving the best\n#if DEBUG_GENETIC\n      fprintf (stderr, \"genetic_algorithm: saving the best\\n\");\n#endif\n      best_entity = genetic_population->entity;\n      *best_objective = genetic_population->objective[0];\n      *best_genome = (char *) g_malloc (genetic_population->genome_nbytes);\n      memcpy (*best_genome, best_entity->genome,\n              genetic_population->genome_nbytes);\n      *best_variables = bv = (double *) g_malloc (nvariables * sizeof (double));\n      for (i = 0; i < nvariables; ++i)\n        bv[i] = genetic_get_variable (best_entity, variable + i);\n      gsl_rng_free (rng);\n\n#if HAVE_MPI\n\n    }\n  else\n    {\n      // First simulation of all entities\n#if DEBUG_GENETIC\n      fprintf (stderr, \"genetic_algorithm: first simulation of all entities\\n\");\n#endif\n      genetic_simulation_slave (0, rank);\n\n      // Population generations\n      for (i = 1; i < ngenerations && !genetic_population->stop; ++i)\n        {\n          // Simulation of the new entities\n#if DEBUG_GENETIC\n          fprintf (stderr,\n                   \"genetic_algorithm: simulation of the new entities\\n\");\n#endif\n          genetic_simulation_slave (genetic_population->nsurvival, rank);\n        }\n    }\n\n#endif\n\n  // Freeing memory\n#if DEBUG_GENETIC\n  fprintf (stderr, \"genetic_algorithm: freeing memory\\n\");\n#endif\n  population_free (genetic_population);\n\n#if DEBUG_GENETIC\n  fprintf (stderr, \"genetic_algorithm: rank=%d\\n\", rank);\n  fprintf (stderr, \"genetic_algorithm: end\\n\");\n#endif\n  return 1;\n}\n\n/**\n * Function to perform the genetic algorithm with default random and evolution \n *   algorithms.\n *\n * \\return 1 on succes, 0 on error.\n */\nint\ngenetic_algorithm_default (unsigned int nvariables,\n                           ///< Number of variables.\n                           GeneticVariable * variable,\n                           ///< Array of variables data.\n                           unsigned int nentities,\n                           ///< Number of entities in each generation.\n                           unsigned int ngenerations,\n                           ///< Number of generations.\n                           double mutation_ratio,       ///< Mutation ratio.\n                           double reproduction_ratio,   ///< Reproduction ratio.\n                           double adaptation_ratio,     ///< Adaptation ratio.\n                           unsigned long random_seed,\n                           ///< Seed of the GSL random numbers generator.\n                           double threshold,\n                           ///< Threshold to finish the simulations.\n                           double (*simulate_entity) (Entity *),\n///< Pointer to the function to perform a simulation of an entity.\n                           char **best_genome,  ///< Best genome.\n                           double **best_variables,\n                           ///< Best array of variables.\n                           double *best_objective)\n                           ///< Best objective function value.\n{\n  return genetic_algorithm (nvariables,\n                            variable,\n                            nentities,\n                            ngenerations,\n                            mutation_ratio,\n                            reproduction_ratio,\n                            adaptation_ratio,\n                            gsl_rng_mt19937,\n                            random_seed,\n                            0,\n                            0,\n                            0,\n                            0,\n                            threshold,\n                            simulate_entity,\n                            best_genome, best_variables, best_objective);\n}\n", "meta": {"hexsha": "0b193490a0673f0e0b6c0440f509d17636bdc7d2", "size": 20724, "ext": "c", "lang": "C", "max_stars_repo_path": "3.0.0/genetic.c", "max_stars_repo_name": "jburguete/genetic", "max_stars_repo_head_hexsha": "e7b5473412eeb4bdd9d1f724ab555d7329b7156d", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-04-07T07:31:25.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-02T02:31:16.000Z", "max_issues_repo_path": "3.0.0/genetic.c", "max_issues_repo_name": "jburguete/genetic", "max_issues_repo_head_hexsha": "e7b5473412eeb4bdd9d1f724ab555d7329b7156d", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3.0.0/genetic.c", "max_forks_repo_name": "jburguete/genetic", "max_forks_repo_head_hexsha": "e7b5473412eeb4bdd9d1f724ab555d7329b7156d", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-05-22T08:54:08.000Z", "max_forks_repo_forks_event_max_datetime": "2017-05-22T08:54:08.000Z", "avg_line_length": 32.3307332293, "max_line_length": 81, "alphanum_fraction": 0.627388535, "num_tokens": 4851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4186969093556867, "lm_q2_score": 0.04813677453046283, "lm_q1q2_score": 0.020154718722256323}}
{"text": "#pragma once\n\n#include <queue>\n#include <vector>\n\n#include <gsl/gsl>\n\n#define EMPTY_NODE '\\0'\n\nclass minqueue_node {\n    public:\n    minqueue_node(char value, unsigned int score);\n    ~minqueue_node();\n\n    unsigned int score;\n    char value;\n\n    minqueue_node* left;\n    minqueue_node* right;\n};\n\nstruct cmp_minqueue_nodes {\n    bool operator()(\n        const gsl::not_null<minqueue_node*> left, const gsl::not_null<minqueue_node*> right);\n};\n\nclass minqueue {\n    std::priority_queue<\n        minqueue_node*, std::vector<minqueue_node*>, cmp_minqueue_nodes> nodes;\n\n    public:\n    minqueue();\n    ~minqueue();\n\n    void push(gsl::not_null<minqueue_node*> node);\n    minqueue_node* pop();\n\n    bool empty();\n    int size();\n};\n", "meta": {"hexsha": "68c6887c45360fe00ad679bd07f0128b94aefa21", "size": 730, "ext": "h", "lang": "C", "max_stars_repo_path": "src/minqueue.h", "max_stars_repo_name": "joshleeb/Huffman", "max_stars_repo_head_hexsha": "54660f62c6a7adf7dfb63388ed9e4f4e41306058", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/minqueue.h", "max_issues_repo_name": "joshleeb/Huffman", "max_issues_repo_head_hexsha": "54660f62c6a7adf7dfb63388ed9e4f4e41306058", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/minqueue.h", "max_forks_repo_name": "joshleeb/Huffman", "max_forks_repo_head_hexsha": "54660f62c6a7adf7dfb63388ed9e4f4e41306058", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.8048780488, "max_line_length": 93, "alphanum_fraction": 0.6589041096, "num_tokens": 184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38861802670584894, "lm_q2_score": 0.051845463719763736, "lm_q1q2_score": 0.020148081804424265}}
{"text": "#include <stdio.h>\n#include <gsl/gsl_ieee_utils.h>\n\nint main() {\n    //gsl_ieee_printf_double\n    double a = 1.1;\n    while (a > 0){\n        gsl_ieee_printf_double(&a);\n        printf(\"\\r\\n\");\n        a /= 2.0;\n    }\n\n    float b = 1.1;\n    while (b > 0){\n        gsl_ieee_printf_float(&b);\n        printf(\"\\r\\n\");\n        b /= 2.0;\n    }\n\n    return 0;\n}", "meta": {"hexsha": "5835e2acede52d0765f4bb3425797b0a40709dfa", "size": 355, "ext": "c", "lang": "C", "max_stars_repo_path": "lab_1/main.c", "max_stars_repo_name": "kamilok1965/CMfSaT", "max_stars_repo_head_hexsha": "0d63eea12291789800df29b23bda0772f6af6695", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-09T18:59:11.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-09T18:59:11.000Z", "max_issues_repo_path": "lab_1/main.c", "max_issues_repo_name": "kamilok1965/CMfSaT", "max_issues_repo_head_hexsha": "0d63eea12291789800df29b23bda0772f6af6695", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lab_1/main.c", "max_forks_repo_name": "kamilok1965/CMfSaT", "max_forks_repo_head_hexsha": "0d63eea12291789800df29b23bda0772f6af6695", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-12-13T10:05:17.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-13T10:05:17.000Z", "avg_line_length": 16.9047619048, "max_line_length": 35, "alphanum_fraction": 0.4845070423, "num_tokens": 119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.040845715909949315, "lm_q1q2_score": 0.020103776765899195}}
{"text": "#ifndef libceed_solids_examples_setup_dm_h\n#define libceed_solids_examples_setup_dm_h\n\n#include <ceed.h>\n#include <petsc.h>\n#include <petscdmplex.h>\n#include <petscfe.h>\n#include \"../include/structs.h\"\n\n// -----------------------------------------------------------------------------\n// Setup DM\n// -----------------------------------------------------------------------------\nPetscErrorCode CreateBCLabel(DM dm, const char name[]);\n\n// Read mesh and distribute DM in parallel\nPetscErrorCode CreateDistributedDM(MPI_Comm comm, AppCtx app_ctx, DM *dm);\n\n// Setup DM with FE space of appropriate degree\nPetscErrorCode SetupDMByDegree(DM dm, AppCtx app_ctx, PetscInt order,\n                               PetscBool boundary, PetscInt num_comp_u);\n\n#endif // libceed_solids_examples_setup_dm_h\n", "meta": {"hexsha": "afc9589eb9ea5ee9ea131c2d30ff62a9b9b26b76", "size": 790, "ext": "h", "lang": "C", "max_stars_repo_path": "examples/solids/include/setup-dm.h", "max_stars_repo_name": "wence-/libCEED", "max_stars_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/solids/include/setup-dm.h", "max_issues_repo_name": "wence-/libCEED", "max_issues_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/solids/include/setup-dm.h", "max_forks_repo_name": "wence-/libCEED", "max_forks_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.347826087, "max_line_length": 80, "alphanum_fraction": 0.6037974684, "num_tokens": 158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4301473339755163, "lm_q2_score": 0.04672495912388512, "lm_q1q2_score": 0.02009861659725416}}
{"text": "/**\n *\n * @file core_blas.h\n *\n *  PLASMA auxiliary routines\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Jakub Kurzak\n * @author Hatem Ltaief\n * @date 2010-11-15\n *\n **/\n#ifndef _PLASMA_CORE_BLAS_H_\n#define _PLASMA_CORE_BLAS_H_\n\n#ifdef USE_MKL\n#include <mkl_cblas.h>\n#else\n#include <cblas.h>\n#endif\n#include \"plasmatypes.h\"\n#include \"descriptor.h\"\n\n#include \"core_dblas.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n  /*\n   * Coreblas Error\n   */\n#define coreblas_error(k, str) fprintf(stderr, \"%s: Parameter %d / %s\\n\", __func__, k, str);\n\n /** ****************************************************************************\n  *  LAPACK Constants\n  **/\nextern char *plasma_lapack_constants[];\n#define lapack_const(plasma_const) plasma_lapack_constants[plasma_const][0]\n\n  /*\n   * CBlas enum\n   */\n#define CBLAS_TRANSPOSE int\n#define CBLAS_UPLO      int\n#define CBLAS_DIAG      int\n#define CBLAS_SIDE      int\n//#define CBLAS_TRANSPOSE enum CBLAS_TRANSPOSE\n//#define CBLAS_UPLO      enum CBLAS_UPLO\n//#define CBLAS_DIAG      enum CBLAS_DIAG\n//#define CBLAS_SIDE      enum CBLAS_SIDE\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* _PLASMA_CORE_BLAS_H_ */\n", "meta": {"hexsha": "c6a1e777d03c72e7886c06720669a74e157f8ca6", "size": 1257, "ext": "h", "lang": "C", "max_stars_repo_path": "examples/omp/benchmarks/kastors-1.1/plasma/include/core_blas.h", "max_stars_repo_name": "tianyi93/hpxMP_mirror", "max_stars_repo_head_hexsha": "668e8881a6f2f437a614ae92e205ae49f083691e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2018-07-16T14:39:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T11:25:09.000Z", "max_issues_repo_path": "examples/omp/benchmarks/kastors-1.1/plasma/include/core_blas.h", "max_issues_repo_name": "tianyi93/hpxMP_mirror", "max_issues_repo_head_hexsha": "668e8881a6f2f437a614ae92e205ae49f083691e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2018-06-18T14:59:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-16T20:43:57.000Z", "max_forks_repo_path": "examples/omp/benchmarks/kastors-1.1/plasma/include/core_blas.h", "max_forks_repo_name": "tianyi93/hpxMP_mirror", "max_forks_repo_head_hexsha": "668e8881a6f2f437a614ae92e205ae49f083691e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2018-06-22T18:44:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-21T11:17:28.000Z", "avg_line_length": 20.95, "max_line_length": 92, "alphanum_fraction": 0.6603023071, "num_tokens": 364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398147944527615, "lm_q2_score": 0.04603389978171546, "lm_q1q2_score": 0.01997785993190445}}
{"text": "#include <gsl/gsl_interp.h>\n#include <unistd.h>\n#include <stdio.h>\n\nint main(int argc, char const *argv[]) {\n  double x = 4096.0;\n  int iterations = 1500;\n  for(int i=0; i<iterations; i++){\n    printf(\"%lf\\n\",x);\n    gsl_ieee_printf_double(&x);\n    printf(\"---------\\n\");\n    x = x/2;\n  }\n  return 0;\n}\n", "meta": {"hexsha": "8fd6d00bea719bef080e6609fb82414bc4790e69", "size": 303, "ext": "c", "lang": "C", "max_stars_repo_path": "lab1/3_gsl/gsl_tryout.c", "max_stars_repo_name": "mprzewie/MOwNiT_2", "max_stars_repo_head_hexsha": "d2a492d210d3acfa1246de82c4a9b818956b4271", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lab1/3_gsl/gsl_tryout.c", "max_issues_repo_name": "mprzewie/MOwNiT_2", "max_issues_repo_head_hexsha": "d2a492d210d3acfa1246de82c4a9b818956b4271", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lab1/3_gsl/gsl_tryout.c", "max_forks_repo_name": "mprzewie/MOwNiT_2", "max_forks_repo_head_hexsha": "d2a492d210d3acfa1246de82c4a9b818956b4271", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-04-10T09:35:51.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-29T10:19:18.000Z", "avg_line_length": 18.9375, "max_line_length": 40, "alphanum_fraction": 0.5742574257, "num_tokens": 100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.04813676650796737, "lm_q1q2_score": 0.019971888864544218}}
{"text": "/*\n * utils.h\n *\n *  Created on: Dec 14, 2016\n *      Author: hazem\n */\n#include <cublas_v2.h>\n#include <curand.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include \"papi.h\"\n#include <cblas.h>\n#include <pthread.h>\n#include <sys/mman.h>\n#ifndef UTILS_H_\n#define UTILS_H_\n\nfloat convert_to_sec(long long time_usec);\nfloat calculate_average(float* array, int repeat);\nvoid GPU_fill_rand(float *A, int nr_rows_A, int nr_cols_A);\nvoid fill_2d_matrix(float* matrix, int n, int m, float value);\nvoid print_matrix(const float *A, int nr_rows_A, int nr_cols_A);\n#endif /* UTILS_H_ */\n", "meta": {"hexsha": "8e93fc443ccd38a850b57ef751c98a3055c50d34", "size": 573, "ext": "h", "lang": "C", "max_stars_repo_path": "utils.h", "max_stars_repo_name": "HazemAbdelhafez/Jetson-matrixmultiply", "max_stars_repo_head_hexsha": "809bd64b10241d5bd4c04256c1c3ee46eded3e5c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utils.h", "max_issues_repo_name": "HazemAbdelhafez/Jetson-matrixmultiply", "max_issues_repo_head_hexsha": "809bd64b10241d5bd4c04256c1c3ee46eded3e5c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils.h", "max_forks_repo_name": "HazemAbdelhafez/Jetson-matrixmultiply", "max_forks_repo_head_hexsha": "809bd64b10241d5bd4c04256c1c3ee46eded3e5c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.875, "max_line_length": 64, "alphanum_fraction": 0.7172774869, "num_tokens": 167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.37387583672470853, "lm_q2_score": 0.05340332641008787, "lm_q1q2_score": 0.019966213345454325}}
{"text": "/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @file pgp.c\n   @brief Interface to pgplot\n\n   Some usage of pgplot.Functionality goes like this: With filling the\n   struct pgp_gdsc the user defines a layout of a plot, which consists\n   of a number of viewgraphs with the same x-axis range. A default\n   struct of that type is delivered by the routine pgp_default. A\n   pgplot device is activated (and must be activated) by calling the\n   routine pgp_opendev(). Then, a box is drawn by calling the routine\n   pgp_openbox. With a call of that function an appropriate pgplot\n   viewport is defined to enable the user to plot his viewgraph in the\n   box by calling functions pgp_marker(), pgp_lines(), pgp_bars(), and\n   pgp_errby(). With pgp_legend(), a string can be plotted to a legend\n   line. The routine pgp_end() will terminate the plotting process\n   properly.\n\n   An example can be accessed with testpgp.c.\n\n   $Source: /Volumes/DATA_J_II/data/CVS/tirific/src/pgp.c,v $\n   $Date: 2011/05/25 22:25:26 $\n   $Revision: 1.14 $\n   $Author: jozsa $\n   $Log: pgp.c,v $\n   Revision 1.14  2011/05/25 22:25:26  jozsa\n   Left work\n\n   Revision 1.13  2011/05/10 00:30:16  jozsa\n   Left work\n\n   Revision 1.12  2009/05/26 07:56:41  jozsa\n   Left work\n\n   Revision 1.11  2007/08/22 15:58:43  gjozsa\n   Left work\n\n   Revision 1.10  2006/11/22 14:16:21  gjozsa\n   Bugfix concerning RASH and horizontal/vertical lines\n\n   Revision 1.9  2006/11/03 10:49:02  gjozsa\n   Introduced logarithmic scaling, hms dms\n\n   Revision 1.8  2006/10/05 12:39:58  gjozsa\n   nasty bugfix\n\n   Revision 1.7  2006/04/03 11:47:57  gjozsa\n   Left work\n\n   Revision 1.6  2006/02/08 16:13:17  gjozsa\n   Extended graphics routines\n\n   Revision 1.5  2005/10/12 14:51:25  gjozsa\n   First point gets thick in the polar plot\n\n   Revision 1.4  2005/10/12 09:53:09  gjozsa\n   Included polar plot facility\n\n   Revision 1.3  2005/06/24 12:00:29  gjozsa\n   Left work\n\n   Revision 1.2  2005/05/24 10:42:24  gjozsa\n   Left work\n\n   Revision 1.1  2005/05/17 12:58:15  gjozsa\n   Added to cvs control\n\n\n*/\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/* EXTERNAL INCLUDES */\n/* ------------------------------------------------------------ */\n#include <stdio.h>\n#include <cpgplot.h>\n#include <math.h>\n#include <string.h>\n#include <float.h>\n#include <stdlib.h>\n#include <gsl/gsl_interp.h>\n#include <gsl/gsl_spline.h>\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/* INTERNAL INCLUDES */\n/* ------------------------------------------------------------ */\n#include <pgp.h>\n#include <maths.h>\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @def _MEMORY_HERE_ON\n   @brief Controls the use of the memory_here module\n\n   If you don't want to use the memory_here facility comment this\n   define, otherways it will be included.\n\n*/\n/* ------------------------------------------------------------ */\n/* #define _MEMORY_HERE_ON */\n/* #include <memory_here.h> */\n\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/* PRIVATE SYMBOLIC CONSTANTS */\n/* ------------------------------------------------------------ */\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @define DEGTORAD\n   @brief Conversion factor from deg to rad\n*/\n/* ------------------------------------------------------------ */\n#define DEGTORAD 0.0174532925199433\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @define LOGFAULT\n   @brief If a logarithm is asked for for a negative number or 0 this should be redurned\n*/\n/* ------------------------------------------------------------ */\n#define LOGFAULT -40\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/* PRIVATE MACROS */\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/* (PRIVATE) GLOBAL VARIABLES */\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/* PRIVATE TYPEDEFS */\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/* PRIVATE STRUCTS */\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/* PRIVATE FUNCTION DECLARATIONS */\n/* ------------------------------------------------------------ */\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn int putalabel(char where, char *overfrac, char underfrac, float charheight, float xmin, float xmax)\n  @brief Puts a label at a viewgraph as a fraction\n\n  Requires an open viewgraph, and the character height set to the axis\n  numbering height. If both overfrac and underfrac are filled, then a fraction will be plotted. If one of both is an empty string (not NULL), then no fraction bar will be plotted.\n\n  @param where      (char)   t, b, l, r position of the label\n  @param overfrac   (char *) Text above the fraction bar\n  @param underfrac  (char *) Text below the fraction bar\n  @param charheight (float)  Character height relative to the actual character height, which should be set to the numbering height.\n  @param dist       (float)  Distance from the axis baseline in units of the initial height\n  @return (success) int putalabel: 1\\\\\n          (error)   0\n\n*/\n/* ------------------------------------------------------------ */\nint putalabel(char where, char *overfrac, char *underfrac, float charheight, float dist);\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn float pgp_logf10f(float x)\n  @brief Returns the logarithm on basis 10 and LOGFAULT if x <= 0\n\n  @param x (float) number to calculate the logarithm of\n  @return logarithm of the number or, if impossible, LOGFAULT\n\n*/\n/* ------------------------------------------------------------ */\nfloat pgp_logf10f(float x);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static int pgp_get_interparray(float *x, float *y, int npoints, int interptype, int nout, float **xout, float **yout)\n  @brief Returns an array of interpolated values.\n\n  Assumes an array of npoints x-y pairs as an input. Checks if x is strictly monotonically increasing. If *xout is not NULL, deallocates *xout. If *yout is not NULL, deallocates *yout. Allocates an array *xout of nout equally-spaced points with xout[0] = x[0] and xout[nout-1] = x[nout-1]. Allocates an array *yout of nout data points where the ith data point is an interpolation between x and y at the position xout[i]. interptype determines the interpolation type, which can be  PGP_I_LINEAR: linear; PGP_I_CSPLINE: cubic natural spline; PGP_I_AKIMA: Akima .\n\n  @param x          (float * ) input data points, abscissae, must be strictly increasing\n  @param y \t    (float * ) input data points, ordinate\n  @param npoints    (  int   ) input number of data points\n  @param interptype (  int   ) input interpolation type: PGP_I_LINEAR: linear; PGP_I_CSPLINE: cubic natural spline; PGP_I_AKIMA: Akima\n  @param nout\t    (  int   ) input number of output data points\n  @param xout \t    (float **) output data array x-values (equally spaced)\n  @param yout \t    (float **) output data array y-values\n\n  @return logarithm of the number or, if impossible, LOGFAULT\n\n*/\n/* ------------------------------------------------------------ */\n static int pgp_get_interparray(float *x, float *y, int npoints, int interptype, int nout, float **xout, float **yout);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/* FUNCTION CODE */\n/* ------------------------------------------------------------ */\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Opens the pgplot device as specified */\nint pgp_opendev(char *device_name)\n{\n  int val;\n\n  if (device_name)\n    if (device_name[0]) {\n      val = cpgbeg(0,device_name,1,1);\n\n      /* Has to be set 0 for use in gipsy */\n      cpgask(1);\n      return val;\n    }\n\n  return 0;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Returns a default pgp_gdsc struct */\npgp_gdsc *pgp_gdsc_default(int nplots, int legendcols, int legendrows, float charheight)\n{\n  pgp_gdsc *gdsc;\n  /* int i;  Control variable */\n  float chrhtx; /* Horizontal character width in x-map units, 1 is whole page */\n  float chrhty; /* Vertical character height in y-map units, 1 is whole page */\n  float chrhtxref; /* Reference charheight */\n  float scalexy; /* scale from x size of numbers to y size of numbers\n\t\t    (is the same physical size, but in terms of window\n\t\t    size they are different) */\n  float pltheight;\n\n  /* Allocate */\n  if (!(gdsc = (pgp_gdsc *) malloc(sizeof(pgp_gdsc))))\n    return NULL;\n\n  /* Find the reference */\n  cpgsch(1.0);\n  cpgqcs(0, &chrhtxref, &chrhty);\n\n  /* This is a scale */\n  scalexy = chrhty/chrhtxref;\n\n  /* Now, the character height in window units is like this */\n  chrhtx = chrhtxref*charheight;\n\n  /* Fill with default values */\n\n  /* Number of plots */\n  gdsc -> nplots = nplots;\n\n  /* Symbols and descriptors in charheight, but at most one\n     third??? of the plot height until the numbering is finished */\n\n  /* The height of the plot is 1.0 at the start */\n  pltheight = 1.0;\n  \n  /* The number is reduced by the axis description + 1 character */\n  pltheight = pltheight-12.3*chrhty;\n\n  /* Then, for each legend line, two characters */\n  pltheight = pltheight-2.0*legendrows*chrhty;\n\n  /* Then, each plot has only 1/nplots height */\n  pltheight = pltheight/nplots;\n\n  /* At the end, each plot has a margin of 4 heights at the top for the numbering */\n  pltheight = pltheight-4.0*chrhty;\n\n  /* We could express this as: */\n  /* (1.0-12.3*chrhty-2.0*legendrows*chrhty)/nplots-4.0*chrhty */\n\n\n  /* If this leaves room for 3 (???) numbers, then we apply the character height else we adjust the height */\n  if (chrhty*3 > pltheight)\n    chrhty = 1/(12.3+2*legendrows+7.0*nplots);\n\n  chrhtx= chrhty/scalexy;\n\n  gdsc -> numberheight = chrhtx/chrhtxref;\n  gdsc -> symbolheight = 1.0;\n  gdsc -> legendheight = 1.0;\n  gdsc -> axdescheight = 1.0;\n  \n  /* legend */\n  gdsc -> legendcols = legendcols;\n  gdsc -> legendrows = legendrows;\n\n  /* Horizontal and vertical borders are 2 characters */\n  gdsc -> verbord = 2.0;\n  gdsc -> horbord = 2.0;\n\n  /* Stop of the axis numbering is 2 characters, only for the top of the graph */\n  gdsc -> leftnum = 0.0;\n  gdsc -> rightnum = 0.0;\n  gdsc -> botnum = 0.0;\n  gdsc -> topnum = 1.0;\n\n  /* Margins */\n  gdsc -> leftmargin = 7.0;\n  gdsc -> rightmargin = 7.0;\n  gdsc -> bottommargin = 1.8;\n  gdsc -> topmargin = 2.5;\n\n  /* Linewidths */\n  gdsc -> graphlw = 1;\n  gdsc -> boxlw = 1;\n\n  /* reserve and return an initialised array for the axis labelling */\n/*   if (!(gdsc -> logarcsx = (int *) malloc(gdsc -> nplots*sizeof(int)))){ */\n/*     free(gdsc); */\n/*     return 0; */\n/*   } */\n/*   for (i = 0; i < gdsc -> nplots; ++i) */\n/*     gdsc -> logarcsx[i] = 0; */\n\n  /* reserve and return an initialised array for the axis labelling */\n/*   if (!(gdsc -> logarcsy = (int *) malloc(gdsc -> nplots*sizeof(int)))){ */\n/*     free(gdsc -> logarcsx); */\n/*     free(gdsc); */\n/*     return 0; */\n/*   } */\n/*   for (i = 0; i < gdsc -> nplots; ++i) */\n/*     gdsc -> logarcsy[i] = 0; */\n  gdsc -> logarcsx = 0;\n  gdsc -> logarcsy = 0;\n  gdsc -> interptype_lines = PGP_I_LINEAR;\n  gdsc -> interp_numlines = 500;\n\n  return gdsc;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Make a polar diagram on an open device */\nvoid pgp_polar(int ndots, float *xarray, float *yarray, int nlines, float *xlarray, float *ylarray, int nradii, float *radiis, float *lineangle, int linewidth, int circlewidth, int symbolwidth, int colour)\n{\n  int i;\n  float rmax = 0;\n  float twopointsx[2];\n  float twopointsy[2];\n  float xv1,yv1;\n  float *radii;\n  rmax = 0;\n\n  /* Allocte memory for radii */\n  if (!(radii = (float *) malloc(nradii*sizeof(float))))\n    return;\n\n  /* First find out about the extent of the graph */\n  for (i = 0; i < ndots; ++i) {\n    if (rmax < fabs(xarray[i]))\n      rmax = fabs(xarray[i]);\n    if (rmax < fabs(yarray[i]))\n      rmax = fabs(yarray[i]);\n  }\n\n  for (i = 0; i < nlines; ++i) {\n    if (rmax < fabs(xlarray[i]))\n      rmax = fabs(xlarray[i]);\n    if (rmax < fabs(ylarray[i]))\n      rmax = fabs(ylarray[i]);\n  }\n\n  /* We make a local copy of the radii */\n\n  for (i = 0; i < nradii; ++i) {\n    radii[i] = fabs(radiis[i]);\n    if (rmax < radii[i])\n      rmax = radii[i];\n  }\n\n  /* Now scale rmax a bit */\n  rmax = rmax*1.02;\n\n  /* Define a drawing area, must be quadratic */\n  cpgenv(-rmax, rmax, -rmax, rmax, 1, -2);\n\n  /* Check the linewidths */\n  if (linewidth < 1)\n    linewidth = 1;\n  if (linewidth > 201)\n    linewidth = 201;\n  if (circlewidth < 1)\n    circlewidth = 1;\n  if (circlewidth > 201)\n    circlewidth = 201;\n  if (symbolwidth < 1)\n    symbolwidth = 1;\n  if (symbolwidth > 201)\n    symbolwidth = 201;\n\n  /* Set the colour index foreground */\n  cpgsci(1);\n\n  /* Draw the circles */\n  if (nradii > 0) {\n    cpgslw(circlewidth);\n\n    /* Make the circles open */\n    cpgsfs(2);\n\n    /* Chose a dashed style */\n    cpgsls(4);\n    \n    for (i = 0; i < (nradii-1); ++i)\n      cpgcirc(0,0, radii[i]);\n\n    /* Draw the last circle, solid line with double width, solid */\n    cpgsls(1);\n\n    if (circlewidth > 100)\n      circlewidth = 201;\n    else\n      circlewidth = 2*circlewidth;\n\n    cpgslw(circlewidth);\n\n    cpgcirc(0,0, radii[nradii-1]);\n\n    /* Now do the Briggs style thingies */\n    twopointsx[0] = 0;\n    twopointsx[1] = 0;\n    twopointsy[0] = radii[nradii-1];\n    twopointsy[1] = radii[nradii-1]-0.05*radii[nradii-1];\n    cpgline(2, twopointsx, twopointsy);\n\n    twopointsx[0] = 0;\n    twopointsx[1] = 0;\n    twopointsy[0] = -radii[nradii-1];\n    twopointsy[1] = -radii[nradii-1]+0.05*radii[nradii-1];\n    cpgline(2, twopointsx, twopointsy);\n\n    twopointsy[0] = 0;\n    twopointsy[1] = 0;\n    twopointsx[0] = radii[nradii-1];\n    twopointsx[1] = radii[nradii-1]-0.05*radii[nradii-1];\n    cpgline(2, twopointsx, twopointsy);\n\n    twopointsy[0] = 0;\n    twopointsy[1] = 0;\n    twopointsx[0] = -radii[nradii-1];\n    twopointsx[1] = -radii[nradii-1]+0.05*radii[nradii-1];\n    cpgline(2, twopointsx, twopointsy);\n\n    /* Check whether to plot a point */\n    for (i = 0; i < (nradii); ++i) {\n      if (radii[i] == 0){\n\txv1 = yv1 = 0;\n\tcpgpt(1, &xv1, &yv1, -1);\n      }\n    }\n    }\n    /* Draw the reference thing */\n    if ((lineangle)) {\n      cpgslw(linewidth);\n      twopointsy[0] = 0;\n      twopointsy[1] = cos(DEGTORAD*(*lineangle))*radii[nradii-1];\n      twopointsx[0] = 0;\n      twopointsx[1] = -sin(DEGTORAD*(*lineangle))*radii[nradii-1];\n    cpgline(2, twopointsx, twopointsy);\n    }\n\n  /* Plot the points */\n\n  /* Set the linewidth */\n  cpgslw(symbolwidth);\n\n  /* Set the colour */\n  cpgsci(colour);\n\n /* Plot points, number of points, vectors for x and y, symbol */\n  if (ndots > 0)\n  cpgpt(ndots, xarray, yarray, -1);\n\n  /* Make a first dot */\n  symbolwidth *= 2;\n  if (symbolwidth > 201)\n    symbolwidth = 210;\n  cpgslw(symbolwidth);\n\n  cpgpt(1, xarray, yarray, -1);\n\n\n  /* Draw the lines */\n  /* Set the linewidth */\n  if (nlines > 1) {\n  cpgslw(linewidth);\n  cpgline(nlines, xlarray, ylarray);\n  }\n\n  /* Finished */\n  return;\n}\n\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Opens a box in an opened window with a few specifications */\nint pgp_openbox(pgp_gdsc *gdsc, int nplot, float xmin, float xmax, float ymin, float ymax, char *leftdeschi, char *leftdesclo, char *rightdeschi, char *rightdesclo, char *bottomdeschi, char *bottomdesclo, char *topdeschi, char *topdesclo, float lrzero, float lrscale, float btzero, float btscale, int logarcsx, int logarcsy)\n{\n  float plotheight;\n  float chrhtxref;    /* Horizontal character width in x-map units, 1 is whole page */\n  float chrhtyref;    /* Vertical character height in y-map units, 1 is whole page */\n  /* float scalexy; */    /* scale from x size of numbers to y size of numbers (or inverse scale of x to y size of area */\n  float dummy1, dummy2;\n\n  int slw; /* Standard linewidth */\n\n  float xlo; /* Box in window coordinates */\n  float xhi;\n  float ylo;\n  float yhi;\n\n  float xulo; /* Box in user coordinates */\n  float xuhi;\n  float yulo;\n  float yuhi;\n\n  float xlo2; /* Another box in window coordinates */\n  float xhi2;\n  float ylo2;\n  float yhi2;\n\n  float xulo2; /* Another box in user coordinates */\n  float xuhi2;\n  float yulo2;\n  float yuhi2;\n\n  float ax, ay, bx, by; /* linear coefficients from window to user coordinates */\n\n  void (* boxingx)(const char *xopt, float xtick, int nxsub, const char *yopt, float ytick, int nysub);\n  void (* boxingy)(const char *xopt, float xtick, int nxsub, const char *yopt, float ytick, int nysub);\n  char steringxt[8],steringxb[8],steringyl[8],steringyr[8],steribgxt[8],steribgxb[8],steribgyl[8],steribgyr[8];\n\n  /* First calculate the symbol height and width in map units \n\t\t    (is the same physical size, but in terms of window\n\t\t    size they are different) */\n\n  /* Check if there is anything to draw */\n  if (nplot > gdsc -> nplots || nplot < 1)\n    return 0;\n\n  /* Check the scaling */\n  if ((logarcsx < 0) || (logarcsx > 3))\n    return 0;\n\n  /* per default the function to draw the box is cpgbox */\n  boxingx = cpgbox;\n  boxingy = cpgbox;\n\n  /* Default numbering style */\n  sprintf(steringyr,\"MV\");\n  sprintf(steringyl,\"NV\");\n  sprintf(steringxt,\"M\");\n  sprintf(steringxb,\"N\");\n\n  sprintf(steribgyr,\"CTS\");\n  sprintf(steribgyl,\"BTS\");\n  sprintf(steribgxt,\"CTS\");\n  sprintf(steribgxb,\"BTS\");\n\n  /* Default scaling */\n  gdsc -> logarcsx = 0;\n  gdsc -> logarcsy = 0;\n\n  /* If a different scaling was requested, redefine labelling */\n  if (logarcsx == 1) {\n    gdsc -> logarcsx = 1;\n/*     if (xmin <= 0) */\n/*       return 0; */\n/*     if (xmax <= 0) */\n/*       return 0; */\n/*     if ((xmin*btscale+btzero) <= 0) */\n/*       return 0; */\n/*     if ((xmax*btscale+btzero) <= 0) */\n/*       return 0; */\n\n    /* Do a trick */\n    dummy1 = pgp_logf10f(xmin*btscale+btzero);\n    dummy2 = pgp_logf10f(xmax*btscale+btzero);\n\n    xmin = pgp_logf10f(xmin);\n    xmax = pgp_logf10f(xmax);\n\n    if (xmin == xmax) {\n      btzero = dummy1-xmin;\n      btscale = 0;\n    }\n    else {\n      btscale = (dummy2-dummy1)/(xmax-xmin);\n      btzero = dummy2-btscale*xmax;\n    }\n    sprintf(steringxt,\"ML2\");\n    sprintf(steringxb,\"NL2\");\n    sprintf(steribgxt,\"CTSL\");\n    sprintf(steribgxb,\"BTSL\");\n  }\n\n  if (logarcsy == 1) {\n    gdsc -> logarcsy = 1;\n/*     if (ymin <= 0) */\n/*       return 0; */\n/*     if (ymax <= 0) */\n/*       return 0; */\n/*     if ((ymin*btscale+btzero) <= 0) */\n/*       return 0; */\n/*     if ((ymax*btscale+btzero) <= 0) */\n/*       return 0; */\n\n    /* Do a trick */\n    dummy1 = pgp_logf10f(ymin*lrscale+lrzero);\n    dummy2 = pgp_logf10f(ymax*lrscale+lrzero);\n\n    ymin = pgp_logf10f(ymin);\n    ymax = pgp_logf10f(ymax);\n\n    if (ymin == ymax) {\n      lrzero = dummy1-ymin;\n      lrscale = 0;\n    }\n    else {\n      lrscale = (dummy2-dummy1)/(ymax-ymin);\n      lrzero = dummy2-lrscale*ymax;\n    }\n    sprintf(steringyr,\"MVL2\");\n    sprintf(steringyl,\"NVL2\");\n    sprintf(steribgyr,\"CTSL\");\n    sprintf(steribgyl,\"BTSL\");\n  }\n\n  /* hms */\n  if (logarcsx == 2) {\n    gdsc -> logarcsx = 2;\n    /* convert to seconds of time, input is interpreted as deg */\n    btzero = btzero/240.0;\n    btscale = btscale/240.0;\n    xmin = xmin*240.0;\n    xmax = xmax*240.0;\n    boxingx = cpgtbox;\n    sprintf(steringxt,\"M\");\n    sprintf(steringxb,\"NZH\");\n    sprintf(steribgxt,\"CTS\");\n    sprintf(steribgxb,\"BTSZXYH\");\n  }\n  if (logarcsy == 2) {\n    gdsc -> logarcsy = 2;\n\n    /* convert to seconds of time, input is interpreted as deg */\n    ymin = ymin*240.0;\n    ymax = ymax*240.0;\n\n    /* I'm really not sure why this is not the case */\n/*      lrzero = lrzero/240.0; */\n     lrscale = lrscale/240.0;\n    boxingy = cpgtbox;\n    sprintf(steringyr,\"MV\");\n    sprintf(steringyl,\"NVZXYH\");\n    sprintf(steribgyr,\"CTS\");\n    sprintf(steribgyl,\"BTSZXYH\");\n  }\n\n  /* dms */\n  if (logarcsx == 3) {\n    gdsc -> logarcsx = 3;\n\n    /* convert to seconds of time, input is interpreted as deg */\n    xmin = xmin*3600.0;\n    xmax = xmax*3600.0;\n\n    /* I'm really not sure why this is not the case */\n/*     btzero = btzero/3600.0; */\n    btscale = btscale/3600.0;\n    boxingx = cpgtbox;\n    sprintf(steringxt,\"M\");\n    sprintf(steringxb,\"NZD\");\n    sprintf(steribgxt,\"CTS\");\n    sprintf(steribgxb,\"BTSZYD\");\n  }\n  if (logarcsy == 3) {\n    gdsc -> logarcsy = 3;\n\n    /* convert to seconds of time, input is interpreted as deg */\n    ymin = ymin*3600.0;\n    ymax = ymax*3600.0;\n/*     lrzero = lrzero/3600.0; */\n    lrscale = lrscale/3600.0;\n    boxingy = cpgtbox;\n    sprintf(steringyr,\"MV\");\n    sprintf(steringyl,\"NVZYD\");\n    sprintf(steribgyr,\"CTS\");\n    sprintf(steribgyl,\"BTSZYD\");\n  }\n\n  /* Ensure that minimum and maximum are different */\n  if(xmin == xmax) {\n    if (xmin != 0.0) {\n      xmin = xmin*0.9;\n      xmax = xmax*1.1;\n    }\n    else {\n      xmin = -1.0;\n      xmax = 1.0;\n    }\n  }\n\n  if (logarcsx > 1) {\n    if ((xmin-xmax) < 1.0) {\n      xmin = xmin-1.0;\n      xmax = xmax+1.0;\n    }\n  }\n\n  if(ymin == ymax) {\n    if (ymin != 0.0) {\n      ymin = ymin*0.9;\n      ymax = ymax*1.1;\n    }\n    else {\n      ymin = -1.0;\n      ymax = 1.0;\n    }\n  }\n\n  if (logarcsy > 1) {\n    if ((ymin-ymax) < 1.0) {\n      ymin = ymin-1.0;\n      ymax = ymax+1.0;\n    }\n  }\n\n  /**********/\n  /* scales */\n  /**********/\n\n  /* Standard linewidth */\n  cpgqlw(&slw);\n\n  /* Find the reference */\n  cpgsch(gdsc -> numberheight);\n  cpgqcs(0, &chrhtxref, &chrhtyref);\n\n  /* The physical size in x is scalexy times the physical size in y */\n  /* scalexy = chrhtyref/chrhtxref; */\n\n  /* plot height */\n  plotheight = (1.0 - 2.0*(gdsc -> legendrows+1)*gdsc -> legendheight*chrhtyref - 6*gdsc -> axdescheight*chrhtyref-6*chrhtyref)/gdsc -> nplots;\n\n  /* Position of the plot, whole box */\n  xlo = gdsc -> leftmargin*chrhtxref+3*gdsc -> axdescheight*chrhtxref;\n\n  /* changed from 3*gdsc -> axdescheight to 4*gdsc -> axdescheight */\n  xhi = 1.0-4*gdsc -> axdescheight*chrhtxref-gdsc -> rightmargin*chrhtxref;\n  ylo = 1.0-4*gdsc -> axdescheight*chrhtyref-gdsc -> topmargin*chrhtyref-plotheight*(nplot);\n  yhi = 1.0-4*gdsc -> axdescheight*chrhtyref-gdsc -> topmargin*chrhtyref-plotheight*(nplot-1);\n\n  /* Check if the specification is wrong and return 0 if it is */\n  if (xlo >= xhi)\n    return 0;\n  if (ylo >= yhi)\n    return 0;\n\n\n  /* Define the linear dependencies of the window scaling and the user scaling */\n  ax = (xmax-xmin)/((xhi-gdsc -> horbord*gdsc -> symbolheight*chrhtxref) - (xlo+gdsc -> horbord*gdsc -> symbolheight*chrhtxref));\n  ay =  (ymax-ymin)/((yhi-gdsc -> verbord*gdsc -> symbolheight*chrhtyref) - (ylo+gdsc -> verbord*gdsc -> symbolheight*chrhtyref));\n  bx = xmin-ax*(xlo+gdsc -> horbord*gdsc -> symbolheight*chrhtxref);\n  by = ymin-ay*(ylo+gdsc -> verbord*gdsc -> symbolheight*chrhtyref);\n\n  /*************/\n  /* Numbering */\n  /*************/\n\n  /* Set the symbol size (again) */\n  cpgsch(gdsc -> numberheight);\n\n  /* Draw the numbers axis by axis */\n\n  /* First define the plot region */\n  xlo2 = gdsc -> leftmargin*chrhtxref+3*gdsc -> axdescheight*chrhtxref+gdsc -> leftnum*chrhtxref;\n  xhi2 = 1.0-gdsc -> rightmargin*chrhtxref-4*gdsc -> axdescheight*chrhtxref-gdsc -> rightnum*chrhtxref;\n  ylo2 = 1.0-4*gdsc -> axdescheight*chrhtyref-gdsc -> topmargin*chrhtyref-plotheight*(nplot)+gdsc -> botnum*chrhtyref;\n  yhi2 = 1.0-4*gdsc -> axdescheight*chrhtyref-gdsc -> topmargin*chrhtyref-plotheight*(nplot-1)-gdsc -> topnum*chrhtyref;\n\n  xulo2 = ax*xlo2+bx;\n  xuhi2 = ax*xhi2+bx;\n  yulo2 = ay*ylo2+by;\n  yuhi2 = ay*yhi2+by;\n\n  /* Top and bottom numbering */\n  if (nplot == 1) {\n    cpgsvp(xlo2, xhi2, ylo, yhi);\n    cpgswin(xulo2*btscale+btzero, xuhi2*btscale+btzero, yulo2*lrscale+lrzero, yuhi2*lrscale+lrzero);\n\n    if ((topdeschi) || topdesclo)\n      (*boxingx)(steringxt, 0.0, 0, \"\", 0.0, 0);\n  }\n\n  if (nplot == gdsc -> nplots) {\n    cpgsvp(xlo2, xhi2, ylo, yhi);\n\n    /* BUGFIX: changed from (...,yulo, yuhi) to (...,yulo2, yuhi2) */\n    cpgswin(xulo2, xuhi2, yulo2, yuhi2);\n\n    if ((bottomdeschi) || bottomdesclo)\n      (*boxingx)(steringxb, 0.0, 0, \"\", 0.0, 0);\n  }\n\n  /* Left and right numbering */\n  cpgsvp(xlo, xhi, ylo2, yhi2);\n  cpgswin(xulo2*btscale+btzero, xuhi2*btscale+btzero, yulo2*lrscale+lrzero, yuhi2*lrscale+lrzero);\n\n  if ((rightdeschi) || (rightdesclo))\n    (*boxingy)(\"\", 0.0, 0, steringyr, 0.0, 0);\n  cpgsvp(xlo, xhi, ylo2, yhi2);\n  cpgswin(xulo2, xuhi2, yulo2, yuhi2);\n\n  if ((leftdeschi) || (leftdesclo))\n    (*boxingy)(\"\", 0.0, 0, steringyl, 0.0, 0);\n\n  /***************/  \n  /* Box drawing */\n  /***************/  \n  \n  /* Set the line width */\n  cpgslw(gdsc -> boxlw);\n\n  /* Define an area of operation PGSVP (XMIN, XMAX, YMIN, YMAX), 0 to 1,  y from bottom to top */\n  cpgsvp(xlo, xhi, ylo, yhi);\n    \n  xulo = ax*xlo+bx;\n  xuhi = ax*xhi+bx;\n  yulo = ay*ylo+by;\n  yuhi = ay*yhi+by;\n\n  cpgswin(xulo, xuhi, yulo, yuhi);\n\n/* draw the box with the tickmarks of the lower and left panel */\n  (*boxingx)(steribgxb, 0.0, 0, \"\", 0.0, 0);\n  (*boxingy)(\"\", 0.0, 0, steribgyl, 0.0, 0);\n\n  /* Now change the user coordinates */\n  cpgswin(xulo*btscale+btzero, xuhi*btscale+btzero, yulo*lrscale+lrzero, yuhi*lrscale+lrzero);\n\n  /* draw the box with the tickmarks of the upper and right panel */\n  (*boxingx)(steribgxt, 0.0, 0, \"\", 0.0, 0);\n  (*boxingy)(\"\", 0.0, 0, steribgyr, 0.0, 0);\n\n  /* Reset the linewidth */\n  cpgslw(slw);\n\n  /*************/  \n  /* Labelling */\n  /*************/  \n\n  /* Set character height (again) to the number value */\n  cpgsch(gdsc -> numberheight);\n\n  /* Label top */\n  if (nplot == 1)\n    putalabel('t', topdeschi, topdesclo, gdsc -> axdescheight, gdsc -> topmargin);\n\n  /* Label bottom */\n  if (nplot == gdsc -> nplots)\n    putalabel('b', bottomdeschi, bottomdesclo, gdsc -> axdescheight, gdsc -> bottommargin);\n\n  /* Label left and right axis */\n  putalabel('l', leftdeschi, leftdesclo, gdsc -> axdescheight, gdsc -> leftmargin);\n  putalabel('r', rightdeschi, rightdesclo, gdsc -> axdescheight, gdsc -> rightmargin);\n\n  /* At the end we put the viewport and the window at the right values */\n  switch (logarcsx) {\n  case 2:\n    xmin = xmin/240.0;\n    xmax = xmax/240.0;\n    break;\n  case 3:\n    xmin = xmin/3600.0;\n    xmax = xmax/3600.0;\n    break;\n  }\n  switch (logarcsy) {\n  case 2:\n    ymin = ymin/240.0;\n    ymax = ymax/240.0;\n    break;\n  case 3:\n    ymin = ymin/3600.0;\n    ymax = ymax/3600.0;\n    break;\n  }\n\n  /* Redefine */\n  xlo = gdsc -> leftmargin*chrhtxref+3*gdsc -> axdescheight*chrhtxref;\n  xhi = 1.0-4*gdsc -> axdescheight*chrhtxref-gdsc -> rightmargin*chrhtxref;\n  ylo = 1.0-4*gdsc -> axdescheight*chrhtyref-gdsc -> topmargin*chrhtyref-plotheight*(nplot);\n  yhi = 1.0-4*gdsc -> axdescheight*chrhtyref-gdsc -> topmargin*chrhtyref-plotheight*(nplot-1);\n\n  ax = (xmax-xmin)/((xhi-gdsc -> horbord*gdsc -> symbolheight*chrhtxref) - (xlo+gdsc -> horbord*gdsc -> symbolheight*chrhtxref));\n  ay =  (ymax-ymin)/((yhi-gdsc -> verbord*gdsc -> symbolheight*chrhtyref) - (ylo+gdsc -> verbord*gdsc -> symbolheight*chrhtyref));\n  bx = xmin-ax*(xlo+gdsc -> horbord*gdsc -> symbolheight*chrhtxref);\n  by = ymin-ay*(ylo+gdsc -> verbord*gdsc -> symbolheight*chrhtyref);\n\n  xulo = ax*xlo+bx;\n  xuhi = ax*xhi+bx;\n  yulo = ay*ylo+by;\n  yuhi = ay*yhi+by;\n\n  /* Do the redefinition */\n  cpgsvp(xlo, xhi, ylo, yhi);\n  cpgswin(xulo, xuhi, yulo, yuhi);\n\n  return 1;\n}\n/* ------------------------------------------------------------ */\n\n   \n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Puts a label at a viewgraph as a fraction */\n\nint putalabel(char where, char *overfrac, char *underfrac, float charheight, float dist)\n{\n  float oheight;    /* Character height at call time */\n  int fraclength;\n  char *fracbar;\n  float ovpos; \n  float unpos; \n  float fracpos;\n\n  char format[3];\n\n  float frlen1;\n  float frlen2;\n  float xbox;\n  float ybox;\n  float chrhtxref;\n  float chrhtyref;\n\n  /* Check if there is anything to put */\n  if ((overfrac == NULL) && (underfrac == NULL))\n    return 1;\n\n  /***********/\n  /* scaling */\n  /***********/\n\n  /* Find the reference character height */\n  cpgqch(&oheight);\n\n  /* Set the character height to the required value */\n  cpgsch(oheight*charheight);\n\n  /* If the strings are empty we return a success */\n  if (!(*overfrac)) {\n    if (!(*underfrac))\n      return 1;\n    /* If only one of them is empty, we make the one not empty overfrac */\n    else {\n      fracbar = overfrac;\n      overfrac = underfrac;\n      underfrac = fracbar;\n    }\n  }\n\n  /* A format string is required */\n  switch (where) {\n  case 'l':\n    sprintf(format,\"L\");\n\n    /* Calculate the maximum possible distance from the edge of the graph */\n    ovpos = dist/charheight+2.0;\n    fracpos = dist/charheight+1.4;\n    unpos = dist/charheight;\n    break;\n  case 'r':\n    sprintf(format,\"R\");\n\n    /* Calculate the maximum possible distance from the edge of the graph */\n    ovpos = dist/charheight+1;\n    fracpos = dist/charheight+1.6;\n    unpos = dist/charheight+3;\n    break;\n\n  case 't':\n    sprintf(format,\"T\");\n    ovpos = dist/charheight+2.0;\n    fracpos = dist/charheight/charheight+1.4;\n    unpos = dist/charheight/charheight+0.0;\n    break;\n\n  case 'b':\n    sprintf(format,\"B\");\n    ovpos = dist/charheight+1.0;\n    fracpos = dist/charheight+1.6;\n    unpos = dist/charheight+3.0;\n    break;\n\n  default:\n    return 0;\n  }\n\n  /* To get the length of the fraction bar, first find a bounding box at an arbitrary position */\n  cpglen(2, overfrac, &xbox, &ybox);\n  frlen1 = ybox;\n  cpglen(2, underfrac, &xbox, &ybox);\n  frlen2 = ybox;\n  frlen1= (frlen1 > frlen2)?frlen1:frlen2;\n\n  /* Now frlen1 is the length of the string in world coordinates of the x axis, we get the character width of this axis in the same units */\n  cpgqcs(2, &chrhtxref, &chrhtyref);\n\n  /* Then, the length of the fraction bar is the uprounded fraction */\n  fraclength = ((int) (frlen1/chrhtyref))+3;\n\n  if (!(fracbar = (char *) malloc((fraclength+1)*sizeof(char))))\n    return 0;\n\n  fracbar[fraclength] = '\\0';\n\n  while (fraclength > 0) {\n    fracbar[fraclength-1] = '_';\n    --fraclength;\n  }\n\n\n  /************/\n  /* plotting */\n  /************/\n\n  /* If there is a fraction bar to plot do this */\n  if (*underfrac) {\n  /* First plot the character string above the fraction bar */\n  cpgmtxt(format, ovpos, 0.5, 0.5, overfrac);\n\n  /* Now draw the fraction bar */ \n  cpgmtxt(format, fracpos, 0.5, 0.5, fracbar);\n\n  /* At last put the argument below the fraction bar */\n  cpgmtxt(format, unpos, 0.5, 0.5, underfrac);\n  }\n\n  /* No fraction bar */\n  else {\n    cpgmtxt(format, unpos, 0.5, 0.5, overfrac);\n  }\n\n  /* Deallocate */\n  free(fracbar);\n\n  /* Set the character height to the original value */\n  cpgsch(oheight);\n\n  return 1;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Puts a string to the specified legend position */\nint pgp_legend(pgp_gdsc *gdsc, int nhor, int nver, char *string)\n{\n  float chrhtxref;    /* Horizontal character width in x-map units, 1 is whole page */\n  float chrhtyref;    /* Vertical character height in y-map units, 1 is whole page */\n  /* float charwidth; */\n  float posix;\n  float posiy;\n  float plotheight;\n  /* float boxwidth; */\n  float xlo; /* Box in window coordinates */\n  float xhi;\n  float ylo;\n  float yhi;\n  \n  /* First check if the intended legend position is available */\n  if (nver < 1 || nver > gdsc -> legendrows || nhor < 1 || nhor > gdsc -> legendcols) {\n    return 0;\n  }\n\n  /* Then open a box that nearly spans the whole surface at the bottom position of the graph */\n\n  /* Find the reference */\n  cpgsch(gdsc -> numberheight);\n  cpgqcs(0, &chrhtxref, &chrhtyref);\n\n  /* plot height */\n  plotheight = (1.0 - 2.0*(gdsc -> legendrows+1)*gdsc -> legendheight*chrhtyref - 6*gdsc -> axdescheight*chrhtyref-6*chrhtyref)/gdsc -> nplots;\n  ylo = 1.0-4*gdsc -> axdescheight*chrhtyref-gdsc -> topmargin*chrhtyref-plotheight*(gdsc -> nplots);\n  yhi = 1.0-4*gdsc -> axdescheight*chrhtyref-gdsc -> topmargin*chrhtyref-plotheight*(gdsc -> nplots-1);\n\n  /* At the left hand the box has the distance of one symbol to the border of the plotting surface */\n  cpgsch(gdsc -> numberheight*gdsc -> legendheight);\n  cpgqcs(0, &chrhtxref, &chrhtyref);\n\n  xlo = chrhtxref;\n  xhi = 1.0-chrhtxref;\n\n  /* Check if the specification is wrong and return 0 if it is */\n  if (xlo >= xhi)\n    return 0;\n  if (ylo >= yhi)\n    return 0;\n\n  /* Define the surface */\n  cpgsvp(xlo, xhi, ylo, yhi);\n\n  /* This is the length of a box element in units of the x-axis, spacing is one character between rows */\n  /* boxwidth = (1-(gdsc -> legendcols-1)*charwidth)/gdsc -> legendcols; */\n\n  /* This is the position of the string in x along the axis */\n  posix = (nhor-0.5)/gdsc -> legendcols;\n\n  /* Now in y */\n  posiy = gdsc -> bottommargin/gdsc -> legendheight+3*gdsc -> axdescheight/gdsc -> legendheight+2*nver;\n\n  /* Put it on the graph */\n  cpgmtxt(\"B\", posiy, posix, 0.5, string);\n  \n  /* Reset the character height */\n  cpgsch(gdsc -> numberheight);\n\n  return 1;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Puts markers on a predefined viewport */\nint pgp_marker(pgp_gdsc *gdsc, int npoints, float *xpos, float *ypos, int colour, int empty, int symbol, float sizer)\n{\n  int colourbef;\n  float chrhtxref, chrhtyref;\n  int intlw;\n  float *xposd = NULL;\n  float *yposd = NULL;\n  int i;\n\n  /* Allocate space if necessary */\n  if (gdsc -> logarcsx == 1) {\n    if (!(xposd = (float *) malloc(npoints*sizeof(float))))\n      return 1;\n    for (i=0; i < npoints; ++i) {\n\txposd[i] = pgp_logf10f(xpos[i]);\n    }\n    xpos = xposd;\n  }\n  if (gdsc -> logarcsy == 1) {\n    if (!(yposd = (float *) malloc(npoints*sizeof(float)))) {\n      if ((xposd))\n\tfree(xposd);\n      return 2;\n    }\n    for (i=0; i < npoints; ++i) {\n\typosd[i] = pgp_logf10f(ypos[i]);\n    }\n    ypos = yposd;\n  }\n\n  /* Set the character height */\n  if (symbol == -1)\n    cpgsch(gdsc -> numberheight*gdsc -> symbolheight*sizer);\n  else if (symbol == 3)\n    cpgsch(gdsc -> numberheight*gdsc -> symbolheight*2*sizer*1.2);\n  else \n    cpgsch(gdsc -> numberheight*gdsc -> symbolheight*2*sizer);\n\n  /* Inquire the character height in inches */\n  cpgqcs(1, &chrhtxref, &chrhtyref);\n\n  /* Set the linewidth as an equivalent */\n  if (symbol == -1) {\n    intlw = chrhtxref*200.0>201.0?201: (int) (chrhtxref*200.0);\n  }\n  else \n    intlw = 1;\n  cpgslw(intlw);\n\n  /* Store the colour index */\n  cpgqci(&colourbef);\n\n  /* Set the colour index */\n  cpgsci(colour);\n\n /* Plot points, number of points, vectors for x and y, symbol */\n  cpgpt(npoints, xpos, ypos, symbol);\n\n  /* If required, plot the same list on top of that with background colour and with a radius that is smaller */\n  if ((empty)) {\n    cpgslw(((intlw-4*gdsc -> graphlw) > 0)?(intlw-4*gdsc -> graphlw):0);\n    cpgsci(0);\n    cpgpt(npoints, xpos, ypos, symbol);\n  }\n\n  /* Reset the linewidth */\n  cpgslw(gdsc -> graphlw);\n\n  /* Reset the colour index */\n  cpgsci(colourbef);\n\n  /* Reset the character height */\n  cpgsch(gdsc -> numberheight);\n\n  /* Reset the linewidth */\n  cpgslw(gdsc -> boxlw);\n\n  /* Deallocate */\n\n  if (gdsc -> logarcsy == 1) {\n    free(yposd);\n  }\n\n  if (gdsc -> logarcsx == 1) {\n    free(xposd);\n  }\n\n  return 0;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Puts lines on a predefined viewport */\nint pgp_lines(pgp_gdsc *gdsc, int npoints, float *xpos, float *ypos, int colour)\n{\n  int i;\n  int colourbef;\n  float *xposd = NULL;\n  float *yposd = NULL;\n\n  if (gdsc -> interptype_lines != PGP_I_LINEAR) {\n    if (pgp_get_interparray(xpos, ypos, npoints, gdsc -> interptype_lines, gdsc -> interp_numlines+1, &xposd, &yposd))\n      goto error;\n    npoints = gdsc -> interp_numlines+1;\n    xpos = xposd;\n    ypos = yposd;\n  }\n\n  /* Allocate space if necessary */\n  if (gdsc -> logarcsx == 1) {\n    if (!xposd) {\n      if (!(xposd = (float *) malloc(npoints*sizeof(float))))\n\tgoto error;\n    }\n    for (i=0; i < npoints; ++i) {\n\txposd[i] = pgp_logf10f(xpos[i]);\n    }\n    xpos = xposd;\n  }\n  if (gdsc -> logarcsy == 1) {\n    if (!yposd) {\n      if (!(yposd = (float *) malloc(npoints*sizeof(float))))\n\tgoto error;\n    }\n    for (i=0; i < npoints; ++i) {\n\typosd[i] = pgp_logf10f(ypos[i]);\n    }\n    ypos = yposd;\n  }\n\n  /* Store the colour index */\n  cpgqci(&colourbef);\n\n  /* Set the colour index */\n  cpgsci(colour);\n\n  /* Set the linewidth */\n  cpgslw(gdsc -> graphlw);\n\n /* Plot lines, number of points, vectors for x and y, symbol */\n  cpgline(npoints, xpos, ypos);\n\n  /* Reset the linewidth */\n  cpgslw(gdsc -> graphlw);\n\n  /* Reset the colour index */\n  cpgsci(colourbef);\n\n  /* Reset the linewidth */\n  cpgslw(gdsc -> boxlw);\n\n  /* Deallocate */\n  if ((xposd))\n    free(xposd);\n  if ((yposd))\n    free(yposd);\n  return 0;\n\n error:\n  if ((xposd))\n    free(xposd);\n  if ((yposd))\n    free(yposd);\n  return 1;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Puts lines on a predefined viewport */\nint pgp_bars(pgp_gdsc *gdsc, int npoints, float *xpos, float *ypos, float width, int colour)\n{\n  int colourbef,i;\n  float *xposd = NULL;\n  float *yposd = NULL;\n\n  /* Allocate space if necessary */\n  if (gdsc -> logarcsx == 1) {\n    if (!(xposd = (float *) malloc(npoints*sizeof(float))))\n      return 1;\n    for (i=0; i < npoints; ++i) {\n      xposd[i] = pgp_logf10f(xpos[i]);\n    }\n    xpos = xposd;\n  }\n  if (gdsc -> logarcsy == 1) {\n    if (!(yposd = (float *) malloc(npoints*sizeof(float)))) {\n      if ((xposd))\n\tfree(xposd);\n      return 2;\n    }\n    for (i=0; i < npoints; ++i) {\n\typosd[i] = pgp_logf10f(ypos[i]);\n    }\n    ypos = yposd;\n  }\n\n  /* Store the colour index */\n  cpgqci(&colourbef);\n\n  /* Set the colour index */\n  cpgsci(colour);\n\n  /* Set the linewidth */\n  cpgslw(gdsc -> graphlw);\n\n /* Plot lines, number of points, vectors for x and y, symbol */\n  for (i = 0; i < npoints; ++i)\n  cpgerr1(5, xpos[i], ypos[i], width/2, 0.0);\n\n  /* Reset the linewidth */\n  cpgslw(gdsc -> graphlw);\n\n  /* Reset the colour index */\n  cpgsci(colourbef);\n\n  /* Reset the linewidth */\n  cpgslw(gdsc -> boxlw);\n\n\n  /* Deallocate */\n  if (gdsc -> logarcsy == 1) {\n    free(yposd);\n  }\n\n  if (gdsc -> logarcsx == 1) {\n    free(xposd);\n  }\n\n  return 0;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Puts lines on a predefined viewport */\nint pgp_errby(pgp_gdsc *gdsc, int npoints, float *xpos, float *ypos, float *err, int colour)\n{\n  int colourbef, i;\n  float *xposd = NULL;\n  float *yposdl = NULL;\n  float *yposdr = NULL;\n\n  /* Allocate space if necessary */\n  if (gdsc -> logarcsx == 1) {\n    if (!(xposd = (float *) malloc(npoints*sizeof(float))))\n      return 1;\n    for (i=0; i < npoints; ++i) {\n\txposd[i] = pgp_logf10f(xpos[i]);\n    }\n    xpos = xposd;\n  }\n\n  if (gdsc -> logarcsy == 1) {\n    if (!(yposdl = (float *) malloc(npoints*sizeof(float)))) {\n      if ((xposd))\n\tfree(xposd);\n      return 1;\n    }\n    if (!(yposdr = (float *) malloc(npoints*sizeof(float)))) {\n      if ((xposd))\n\tfree(xposd);\n      free(yposdl);\n      return 1;\n    }\n    for (i=0; i < npoints; ++i) {\n\typosdr[i] = pgp_logf10f(ypos[i]+err[i]);\n      }\n    for (i=0; i < npoints; ++i) {\n\typosdl[i] = pgp_logf10f(ypos[i]-err[i]);\n    }\n  }\n\n  /* Store the colour index */\n  cpgqci(&colourbef);\n\n  /* Set the colour index */\n  cpgsci(colour);\n\n  /* Set the linewidth */\n  cpgslw(gdsc -> graphlw);\n\n /* Plot lines, number of points, vectors for x and y, symbol */\n  if (gdsc -> logarcsy == 1) \n    cpgerry(npoints, xpos, yposdl, yposdr, 2.0);\n  else\n    cpgerrb(6, npoints, xpos, ypos, err, 2.0);\n\n  /* Reset the linewidth */\n  cpgslw(gdsc -> graphlw);\n\n  /* Reset the colour index */\n  cpgsci(colourbef);\n\n  /* Reset the linewidth */\n  cpgslw(gdsc -> boxlw);\n\n  /* Clean up */\n  if (gdsc -> logarcsx == 1)\n    free(xposd);\n  if (gdsc -> logarcsy == 1) {\n    free(yposdl);\n    free(yposdr);\n  }\n\n  return 0;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* End the plotting and close the device */\nvoid pgp_end()\n{\n  cpgclos();\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Returns the logarithm on basis 10 and LOGFAULT if x <= 0 */\nfloat pgp_logf10f(float x)\n{\n  if (x > 0)\n    return log10f(x);\n  else\n    return LOGFAULT;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Returns an array of interpolated values. */\n\nstatic int pgp_get_interparray(float *x, float *y, int npoints, int interptype, int noutpoints, float **xout, float **yout)\n{\n  int i, pgp_get_interparray = 0;\n  double *xdouble = NULL, *ydouble = NULL; /* input is float, but gsl requires double */\n  gsl_interp *gsl_interpv = NULL; /* gsl structs */\n  gsl_interp_accel *gsl_interp_accelv = NULL; /* gsl structs */\n  const gsl_interp_type * intytype = NULL; /* interpolation type, internal to gsl */\n  float dx;\n\n  /* At least two data points */\n  if (npoints < 2) {\n    pgp_get_interparray |= 1;\n    goto error;\n  }\n\n  /* Wipe the input, gone ... */\n  if (*xout) {\n    free(*xout);\n    *xout = NULL;\n  }  \n  if (*yout) {\n    free(*yout);\n    *yout = NULL;\n  }\n\n  /* Allocate arrays */\n  if (!(xdouble = (double *) malloc(npoints*sizeof(double)))) {\n    pgp_get_interparray |= 2;\n    goto error;\n  }\n  if (!(ydouble = (double *) malloc(npoints*sizeof(double)))) {\n    pgp_get_interparray |= 2;\n    goto error;\n  }\n  for (i = 0; i < npoints; ++i) {\n    xdouble[i] = x[i];\n    ydouble[i] = y[i];\n  }\n  if (!(*xout = (float *) malloc(noutpoints*sizeof(float)))) {\n    pgp_get_interparray |= 2;\n    goto error;\n  }\n  if (!(*yout = (float *) malloc(noutpoints*sizeof(float)))) {\n    pgp_get_interparray |= 2;\n    goto error;\n  }\n\n  switch(interptype) {\n    case PGP_I_LINEAR:\n      intytype = gsl_interp_linear;\n      break;\n\n    case PGP_I_CSPLINE:\n      if (npoints > 2)\n\tintytype = gsl_interp_cspline;\n      else {\n\tprintf(\"Must have at least 3 radii for spline, using linear\\n\");\n\tintytype = gsl_interp_linear;\n      }\n      break;\n    \n    case PGP_I_AKIMA:\n      if (npoints > 4) {\n\tintytype = gsl_interp_akima;\n      }\n      else {\n\tprintf(\"Must have at least 5 radii for Akima\\n\");\n\tif (npoints > 2) {\n\t  printf(\"Using natural cubic spline\\n\");\n\t  intytype = gsl_interp_cspline;\n\t}\n\telse {\n\t  printf(\"Using linear\\n\");\n\t  intytype = gsl_interp_linear;\n\t}\n      }\n      break;\n\n    /* No real default, but we set linear */\n    default:\n      intytype = gsl_interp_linear;\n      break;\n    }\n\n  /* Attempt to allocate all gsl structures */\n  if (!(gsl_interpv = gsl_interp_alloc(intytype, npoints))) {\n    pgp_get_interparray |= 2;\n    goto error;\n  }\n  if (!(gsl_interp_accelv = gsl_interp_accel_alloc())) {\n    pgp_get_interparray |= 2;\n    goto error;\n  }\n\n  gsl_interp_init(gsl_interpv, xdouble, ydouble, npoints);\n  \n  (*xout)[0] = x[0];\n  (*yout)[0] = y[0];\n\n  dx = (x[npoints-1]-x[0])/((float)(noutpoints-1));\n\n  /* Bugfix: rounding error could lead to failure of interpolation */\n  --noutpoints;\n\n  for (i = 1; i < noutpoints; ++i) {\n    (*xout)[i] = (*xout)[i-1]+dx;\n    (*yout)[i] = gsl_interp_eval(gsl_interpv, xdouble, ydouble, (*xout)[i], gsl_interp_accelv);\n  }\n  (*xout)[i] = x[npoints-1];\n  (*yout)[i] = y[npoints-1];\n  \n  /* last points should be identical regardless of rounding errors */\n    free(xdouble);\n    free(ydouble);\n    gsl_interp_free(gsl_interpv);\n    gsl_interp_accel_free(gsl_interp_accelv);\n\n  return pgp_get_interparray;\n\n error:\n  if (xdouble)\n    free(xdouble);\n  if (ydouble)\n    free(ydouble);\n  if (*xout) {\n    free(*xout);\n    *xout = NULL;\n  }  \n  if (*yout) {\n    free(*yout);\n    *yout = NULL;\n  }\n  if (gsl_interpv)\n    gsl_interp_free(gsl_interpv);\n  if (gsl_interp_accelv)\n    gsl_interp_accel_free(gsl_interp_accelv);\n\n  return pgp_get_interparray;  \n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ \n\n   $Log: pgp.c,v $\n   Revision 1.14  2011/05/25 22:25:26  jozsa\n   Left work\n\n   Revision 1.13  2011/05/10 00:30:16  jozsa\n   Left work\n\n   Revision 1.12  2009/05/26 07:56:41  jozsa\n   Left work\n\n   Revision 1.11  2007/08/22 15:58:43  gjozsa\n   Left work\n\n   Revision 1.10  2006/11/22 14:16:21  gjozsa\n   Bugfix concerning RASH and horizontal/vertical lines\n\n   Revision 1.9  2006/11/03 10:49:02  gjozsa\n   Introduced logarithmic scaling, hms dms\n\n   Revision 1.8  2006/10/05 12:39:58  gjozsa\n   nasty bugfix\n\n   Revision 1.7  2006/04/03 11:47:57  gjozsa\n   Left work\n\n   Revision 1.6  2006/02/08 16:13:17  gjozsa\n   Extended graphics routines\n\n   Revision 1.5  2005/10/12 14:51:25  gjozsa\n   First point gets thick in the polar plot\n\n   Revision 1.4  2005/10/12 09:53:09  gjozsa\n   Included polar plot facility\n\n   Revision 1.3  2005/06/24 12:00:29  gjozsa\n   Left work\n\n   Revision 1.2  2005/05/24 10:42:24  gjozsa\n   Left work\n\n   Revision 1.1  2005/05/17 12:58:15  gjozsa\n   Added to cvs control\n\n\n   ------------------------------------------------------------ */\n", "meta": {"hexsha": "feadd592f47730b0f5c5b58aeb93846ea908dde0", "size": 45965, "ext": "c", "lang": "C", "max_stars_repo_path": "src/pgp.c", "max_stars_repo_name": "kernsuite-debian/tirific", "max_stars_repo_head_hexsha": "05fddee80e715dfee5d0f4e2f994b2f17c5d2ca9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-07-01T12:07:09.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-04T08:22:01.000Z", "max_issues_repo_path": "src/pgp.c", "max_issues_repo_name": "gigjozsa/tirific", "max_issues_repo_head_hexsha": "462a58a8312ce437ac5e2c87060cde751774f1de", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-02-24T12:40:08.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-20T06:37:26.000Z", "max_forks_repo_path": "src/pgp.c", "max_forks_repo_name": "kernsuite-debian/tirific", "max_forks_repo_head_hexsha": "05fddee80e715dfee5d0f4e2f994b2f17c5d2ca9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-08-28T03:17:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T15:02:35.000Z", "avg_line_length": 26.9431418523, "max_line_length": 560, "alphanum_fraction": 0.5677798325, "num_tokens": 14790, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552954976388504, "lm_q2_score": 0.044680871226722915, "lm_q1q2_score": 0.019906648440699986}}
{"text": "/***************************************************************************/\n/*                                                                         */\n/* vector.c - Vector class for mruby                                       */\n/* Copyright (C) 2015 Paolo Bosetti                                        */\n/* paolo[dot]bosetti[at]unitn.it                                           */\n/* Department of Industrial Engineering, University of Trento              */\n/*                                                                         */\n/* This library is free software.  You can redistribute it and/or          */\n/* modify it under the terms of the GNU GENERAL PUBLIC LICENSE 2.0.        */\n/*                                                                         */\n/* This library is distributed in the hope that it will be useful,         */\n/* but WITHOUT ANY WARRANTY; without even the implied warranty of          */\n/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the           */\n/* Artistic License 2.0 for more details.                                  */\n/*                                                                         */\n/* See the file LICENSE                                                    */\n/*                                                                         */\n/***************************************************************************/\n\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_statistics_double.h>\n#include <gsl/gsl_sort_vector.h>\n#include <gsl/gsl_rng.h>\n#include \"vector.h\"\n\n#pragma mark -\n#pragma mark \u2022 Utilities\n\n// Garbage collector handler, for play_data struct\n// if play_data contains other dynamic data, free it too!\n// Check it with GC.start\nvoid vector_destructor(mrb_state *mrb, void *p_) {\n  gsl_vector *v = (gsl_vector *)p_;\n  gsl_vector_free(v);\n};\n\n// Creating data type and reference for GC, in a const struct\nconst struct mrb_data_type vector_data_type = {\"vector_data\",\n                                               vector_destructor};\n\n// Utility function for getting the struct out of the wrapping IV @data\nvoid mrb_vector_get_data(mrb_state *mrb, mrb_value self, gsl_vector **data) {\n  mrb_value data_value;\n  data_value = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, \"@data\"));\n\n  // Loading data from data_value into p_data:\n  Data_Get_Struct(mrb, data_value, &vector_data_type, *data);\n  if (!*data)\n    mrb_raise(mrb, E_RUNTIME_ERROR, \"Could not access @data\");\n}\n\n#pragma mark -\n#pragma mark \u2022 Init and accessing\n\n// Data Initializer C function (not exposed!)\nstatic void mrb_vector_init(mrb_state *mrb, mrb_value self, mrb_int n) {\n  mrb_value data_value; // this IV holds the data\n  gsl_vector *p_data;   // pointer to the C struct\n\n  data_value = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, \"@data\"));\n\n  // if @data already exists, free its content:\n  if (!mrb_nil_p(data_value)) {\n    Data_Get_Struct(mrb, data_value, &vector_data_type, p_data);\n    free(p_data);\n  }\n  // Allocate and zero-out the data struct:\n  p_data = gsl_vector_calloc(n);\n  if (!p_data)\n    mrb_raise(mrb, E_RUNTIME_ERROR, \"Could not allocate @data\");\n\n  // Wrap struct into @data:\n  mrb_iv_set(\n      mrb, self, mrb_intern_lit(mrb, \"@data\"), // set @data\n      mrb_obj_value(                           // with value hold in struct\n          Data_Wrap_Struct(mrb, mrb->object_class, &vector_data_type, p_data)));\n}\n\nstatic mrb_value mrb_vector_initialize(mrb_state *mrb, mrb_value self) {\n  mrb_int n;\n  mrb_get_args(mrb, \"i\", &n);\n\n  // Call strcut initializer:\n  mrb_vector_init(mrb, self, n);\n  mrb_iv_set(mrb, self, mrb_intern_lit(mrb, \"@length\"), mrb_fixnum_value(n));\n  mrb_iv_set(mrb, self, mrb_intern_lit(mrb, \"@format\"),\n             mrb_str_new_cstr(mrb, \"%10.3f\"));\n  return mrb_nil_value();\n}\n\nstatic mrb_value mrb_vector_rnd_fill(mrb_state *mrb, mrb_value self) {\n  gsl_vector *p_vec = NULL;\n  const gsl_rng_type *T;\n  gsl_rng *r;\n  mrb_int h;\n\n  mrb_vector_get_data(mrb, self, &p_vec);\n\n  gsl_rng_env_setup();\n  T = gsl_rng_default;\n  r = gsl_rng_alloc(T);\n\n  for (h = 0; h < p_vec->size; h++) {\n    gsl_vector_set(p_vec, h, gsl_rng_uniform(r));\n  }\n  return self;\n}\n\n\nstatic mrb_value mrb_vector_dup(mrb_state *mrb, mrb_value self) {\n  mrb_value other;\n  gsl_vector *p_vec = NULL, *p_vec_other = NULL;\n  mrb_value args[1];\n\n  // call utility for unwrapping @data into p_data:\n  mrb_vector_get_data(mrb, self, &p_vec);\n  args[0] = mrb_fixnum_value(p_vec->size);\n  other = mrb_obj_new(mrb, mrb_class_get(mrb, \"Vector\"), 1, args);\n  mrb_vector_get_data(mrb, other, &p_vec_other);\n  gsl_vector_memcpy(p_vec_other, p_vec);\n  return other;\n}\n\nstatic mrb_value mrb_vector_all(mrb_state *mrb, mrb_value self) {\n  mrb_float v;\n  gsl_vector *p_vec = NULL;\n\n  mrb_get_args(mrb, \"f\", &v);\n  // call utility for unwrapping @data into p_data:\n  mrb_vector_get_data(mrb, self, &p_vec);\n  gsl_vector_set_all(p_vec, v);\n  return self;\n}\n\nstatic mrb_value mrb_vector_zero(mrb_state *mrb, mrb_value self) {\n  gsl_vector *p_vec = NULL;\n\n  // call utility for unwrapping @data into p_data:\n  mrb_vector_get_data(mrb, self, &p_vec);\n  gsl_vector_set_zero(p_vec);\n  return self;\n}\n\nstatic mrb_value mrb_vector_basis(mrb_state *mrb, mrb_value self) {\n  mrb_int i;\n  gsl_vector *p_vec = NULL;\n\n  mrb_get_args(mrb, \"i\", &i);\n  // call utility for unwrapping @data into p_data:\n  mrb_vector_get_data(mrb, self, &p_vec);\n  gsl_vector_set_basis(p_vec, i);\n  return self;\n}\n\n\n#pragma mark -\n#pragma mark \u2022 Tests\n\nstatic mrb_value mrb_vector_equal(mrb_state *mrb, mrb_value self) {\n  mrb_value other;\n  gsl_vector *p_vec, *p_vec_other;\n  mrb_get_args(mrb, \"o\", &other);\n\n  // call utility for unwrapping @data into p_data:\n  mrb_vector_get_data(mrb, self, &p_vec);\n  mrb_vector_get_data(mrb, other, &p_vec_other);\n  if (1 == gsl_vector_equal(p_vec, p_vec_other))\n    return mrb_true_value();\n  else\n    return mrb_false_value();\n}\n\n\n#pragma mark -\n#pragma mark \u2022 Accessors\n\nstatic mrb_value mrb_vector_get_i(mrb_state *mrb, mrb_value self) {\n  mrb_int i = 0;\n  gsl_vector *p_vec = NULL;\n\n  mrb_get_args(mrb, \"i\", &i);\n  // call utility for unwrapping @data into p_data:\n  mrb_vector_get_data(mrb, self, &p_vec);\n  if (i >= p_vec->size) {\n    mrb_raise(mrb, E_VECTOR_ERROR, \"Vector index out of range!\");\n  }\n  return mrb_float_value(mrb, gsl_vector_get(p_vec, (size_t)i));\n}\n\nstatic mrb_value mrb_vector_set_i(mrb_state *mrb, mrb_value self) {\n  mrb_int i = 0;\n  mrb_float f;\n  gsl_vector *p_vec = NULL;\n\n  mrb_get_args(mrb, \"if\", &i, &f);\n\n  // call utility for unwrapping @data into p_data:\n  mrb_vector_get_data(mrb, self, &p_vec);\n  if (i >= p_vec->size) {\n    mrb_raise(mrb, E_VECTOR_ERROR, \"Vector index out of range!\");\n  }\n  gsl_vector_set(p_vec, (size_t)i, (double)f);\n  return mrb_float_value(mrb, f);\n}\n\nstatic mrb_value mrb_vector_to_a(mrb_state *mrb, mrb_value self) {\n  int i;\n  mrb_value ary = mrb_nil_value();\n  gsl_vector *p_vec = NULL;\n  mrb_float e;\n  mrb_vector_get_data(mrb, self, &p_vec);\n  ary = mrb_ary_new_capa(mrb, p_vec->size);\n  for (i = 0; i < p_vec->size; i++) {\n    e = *(p_vec->data + i * p_vec->stride);\n    mrb_ary_set(mrb, ary, i, mrb_float_value(mrb, e));\n  }\n  return ary;\n}\n\n#pragma mark -\n#pragma mark \u2022 Properties\n\nstatic mrb_value mrb_vector_max(mrb_state *mrb, mrb_value self) {\n  gsl_vector *p_vec = NULL;\n  mrb_vector_get_data(mrb, self, &p_vec);\n  return mrb_float_value(mrb, gsl_vector_max(p_vec));\n}\n\nstatic mrb_value mrb_vector_min(mrb_state *mrb, mrb_value self) {\n  gsl_vector *p_vec = NULL;\n  mrb_vector_get_data(mrb, self, &p_vec);\n  return mrb_float_value(mrb, gsl_vector_min(p_vec));\n}\n\nstatic mrb_value mrb_vector_max_index(mrb_state *mrb, mrb_value self) {\n  gsl_vector *p_vec = NULL;\n  mrb_vector_get_data(mrb, self, &p_vec);\n  return mrb_fixnum_value(gsl_vector_max_index(p_vec));\n}\n\nstatic mrb_value mrb_vector_min_index(mrb_state *mrb, mrb_value self) {\n  gsl_vector *p_vec = NULL;\n  mrb_vector_get_data(mrb, self, &p_vec);\n  return mrb_fixnum_value(gsl_vector_min_index(p_vec));\n}\n\n#pragma mark -\n#pragma mark \u2022 Operations\n\nstatic mrb_value mrb_vector_add(mrb_state *mrb, mrb_value self) {\n  mrb_value other;\n  gsl_vector *p_vec, *p_vec_other;\n  mrb_get_args(mrb, \"o\", &other);\n\n  // call utility for unwrapping @data into p_data:\n  mrb_vector_get_data(mrb, self, &p_vec);\n\n  if (mrb_obj_is_kind_of(mrb, other, mrb_class_get(mrb, \"Vector\"))) {\n    mrb_vector_get_data(mrb, other, &p_vec_other);\n    if (p_vec->size != p_vec_other->size) {\n      mrb_raise(mrb, E_VECTOR_ERROR, \"Vector indexes don't match!\");\n    }\n    gsl_vector_add(p_vec, p_vec_other);\n  } else if (mrb_obj_is_kind_of(mrb, other, mrb_class_get(mrb, \"Numeric\"))) {\n    gsl_vector_add_constant(p_vec, mrb_to_flo(mrb, other));\n  }\n  return self;\n}\n\nstatic mrb_value mrb_vector_sub(mrb_state *mrb, mrb_value self) {\n  mrb_value other;\n  gsl_vector *p_vec, *p_vec_other;\n  mrb_get_args(mrb, \"o\", &other);\n\n  // call utility for unwrapping @data into p_data:\n  mrb_vector_get_data(mrb, self, &p_vec);\n  mrb_vector_get_data(mrb, other, &p_vec_other);\n  if (p_vec->size != p_vec_other->size) {\n    mrb_raise(mrb, E_VECTOR_ERROR, \"Vector dimensions don't match!\");\n  }\n  gsl_vector_sub(p_vec, p_vec_other);\n  return self;\n}\n\nstatic mrb_value mrb_vector_mul(mrb_state *mrb, mrb_value self) {\n  mrb_value other;\n  gsl_vector *p_vec, *p_vec_other;\n  mrb_get_args(mrb, \"o\", &other);\n\n  // call utility for unwrapping @data into p_data:\n  mrb_vector_get_data(mrb, self, &p_vec);\n  if (mrb_obj_is_kind_of(mrb, other, mrb_class_get(mrb, \"Vector\"))) {\n    mrb_vector_get_data(mrb, other, &p_vec_other);\n    if (p_vec->size != p_vec_other->size) {\n      mrb_raise(mrb, E_VECTOR_ERROR, \"Vector indexes don't match!\");\n    }\n    gsl_vector_mul(p_vec, p_vec_other);\n  } else if (mrb_obj_is_kind_of(mrb, other, mrb_class_get(mrb, \"Numeric\"))) {\n    gsl_vector_scale(p_vec, mrb_to_flo(mrb, other));\n  }\n  return self;\n}\n\nstatic mrb_value mrb_vector_div(mrb_state *mrb, mrb_value self) {\n  mrb_value other;\n  gsl_vector *p_vec, *p_vec_other;\n  mrb_get_args(mrb, \"o\", &other);\n\n  // call utility for unwrapping @data into p_data:\n  mrb_vector_get_data(mrb, self, &p_vec);\n  mrb_vector_get_data(mrb, other, &p_vec_other);\n  if (p_vec->size != p_vec_other->size) {\n    mrb_raise(mrb, E_VECTOR_ERROR, \"Vector indexes don't match!\");\n  }\n  gsl_vector_div(p_vec, p_vec_other);\n  return self;\n}\n\nstatic mrb_value mrb_vector_prod(mrb_state *mrb, mrb_value self) {\n  mrb_value other;\n  gsl_vector *p_vec, *p_vec_other;\n  mrb_float res;\n  mrb_get_args(mrb, \"o\", &other);\n\n  // call utility for unwrapping @data into p_data:\n  mrb_vector_get_data(mrb, self, &p_vec);\n  mrb_vector_get_data(mrb, other, &p_vec_other);\n  if (!mrb_obj_is_kind_of(mrb, other, mrb_class_get(mrb, \"Vector\"))) {\n    mrb_raise(mrb, E_ARGUMENT_ERROR, \"Need a Vector!\");\n  }\n  if (p_vec->size != p_vec_other->size) {\n    mrb_raise(mrb, E_VECTOR_ERROR, \"Vector indexes don't match!\");\n  }\n  if (gsl_blas_ddot(p_vec, p_vec_other, &res)) {\n    mrb_raise(mrb, E_VECTOR_ERROR, \"Cannot multiply\");\n  }\n  return mrb_float_value(mrb, res);\n}\n\nstatic mrb_value mrb_vector_norm(mrb_state *mrb, mrb_value self) {\n  gsl_vector *p_vec;\n\n  // call utility for unwrapping @data into p_data:\n  mrb_vector_get_data(mrb, self, &p_vec);\n  return mrb_float_value(mrb, gsl_blas_dnrm2(p_vec));\n}\n\nstatic mrb_value mrb_vector_sum(mrb_state *mrb, mrb_value self) {\n  gsl_vector *p_vec;\n\n  // call utility for unwrapping @data into p_data:\n  mrb_vector_get_data(mrb, self, &p_vec);\n  return mrb_float_value(mrb, gsl_blas_dasum(p_vec));\n}\n\nstatic mrb_value mrb_vector_swap(mrb_state *mrb, mrb_value self) {\n  gsl_vector *p_vec;\n  mrb_int i, j;\n  mrb_get_args(mrb, \"ii\", &i, &j);\n\n  // call utility for unwrapping @data into p_data:\n  mrb_vector_get_data(mrb, self, &p_vec);\n  if (gsl_vector_swap_elements(p_vec, i, j)) {\n    mrb_raise(mrb, E_VECTOR_ERROR, \"Cannot swap\");\n  }\n  return self;\n}\n\nstatic mrb_value mrb_vector_reverse(mrb_state *mrb, mrb_value self) {\n  gsl_vector *p_vec;\n\n  // call utility for unwrapping @data into p_data:\n  mrb_vector_get_data(mrb, self, &p_vec);\n  if (gsl_vector_reverse(p_vec)) {\n    mrb_raise(mrb, E_VECTOR_ERROR, \"Cannot reverse\");\n  }\n  return self;\n}\n\n\n#pragma mark -\n#pragma mark \u2022 Statistics\n\nstatic mrb_value mrb_vector_mean(mrb_state *mrb, mrb_value self) {\n  gsl_vector *p_vec;\n  mrb_float result;\n  // call utility for unwrapping @data into p_data:\n  mrb_vector_get_data(mrb, self, &p_vec);\n  result = gsl_stats_mean(p_vec->data, p_vec->stride, p_vec->size);\n  return mrb_float_value(mrb, result);\n}\n\nstatic mrb_value mrb_vector_variance(mrb_state *mrb, mrb_value self) {\n  gsl_vector *p_vec;\n  mrb_float result;\n  mrb_float m;\n  // call utility for unwrapping @data into p_data:\n  mrb_vector_get_data(mrb, self, &p_vec);\n  if (mrb_get_args(mrb, \"|f\", &m) == 1) {\n    result = gsl_stats_variance_m(p_vec->data, p_vec->stride, p_vec->size, m);\n  } else {\n    result = gsl_stats_variance(p_vec->data, p_vec->stride, p_vec->size);\n  }\n  return mrb_float_value(mrb, result);\n}\n\nstatic mrb_value mrb_vector_sd(mrb_state *mrb, mrb_value self) {\n  gsl_vector *p_vec;\n  mrb_float result;\n  mrb_float m;\n  // call utility for unwrapping @data into p_data:\n  mrb_vector_get_data(mrb, self, &p_vec);\n  if (mrb_get_args(mrb, \"|f\", &m) == 1) {\n    result = gsl_stats_sd_m(p_vec->data, p_vec->stride, p_vec->size, m);\n  } else {\n    result = gsl_stats_sd(p_vec->data, p_vec->stride, p_vec->size);\n  }\n  return mrb_float_value(mrb, result);\n}\n\nstatic mrb_value mrb_vector_absdev(mrb_state *mrb, mrb_value self) {\n  gsl_vector *p_vec;\n  mrb_float result;\n  mrb_float m;\n  // call utility for unwrapping @data into p_data:\n  mrb_vector_get_data(mrb, self, &p_vec);\n  if (mrb_get_args(mrb, \"|f\", &m) == 1) {\n    result = gsl_stats_absdev_m(p_vec->data, p_vec->stride, p_vec->size, m);\n  } else {\n    result = gsl_stats_absdev(p_vec->data, p_vec->stride, p_vec->size);\n  }\n  return mrb_float_value(mrb, result);\n}\n\nstatic mrb_value mrb_vector_quantile(mrb_state *mrb, mrb_value self) {\n  gsl_vector *p_vec = NULL, *p_sort_vec = NULL;\n  mrb_float result;\n  mrb_float f;\n  mrb_int n;\n  // call utility for unwrapping @data into p_data:\n  mrb_vector_get_data(mrb, self, &p_vec);\n  n = mrb_get_args(mrb, \"|f\", &f);\n  if (f < 0 || f > 1) {\n    mrb_raise(mrb, E_VECTOR_ERROR, \"Quantile must be in [0,1]\");\n  }\n  p_sort_vec = gsl_vector_calloc(p_vec->size);\n  if (gsl_vector_memcpy(p_sort_vec, p_vec)) {\n    mrb_raise(mrb, E_VECTOR_ERROR, \"Cannot copy vector\");\n  }\n  gsl_sort_vector(p_sort_vec);\n  if (n == 1) {\n    result = gsl_stats_quantile_from_sorted_data(\n        p_sort_vec->data, p_sort_vec->stride, p_sort_vec->size, f);\n  } else {\n    result = gsl_stats_quantile_from_sorted_data(\n        p_sort_vec->data, p_sort_vec->stride, p_sort_vec->size, 0.5);\n  }\n  return mrb_float_value(mrb, result);\n}\n\n\n#pragma mark -\n#pragma mark \u2022 Gem setup\n\nvoid mrb_gsl_vector_init(mrb_state *mrb) {\n  struct RClass *gsl;\n\n  mrb_load_string(mrb, \"class VectorError < Exception; end\");\n\n  gsl = mrb_define_class(mrb, \"Vector\", mrb->object_class);\n  mrb_define_method(mrb, gsl, \"all\", mrb_vector_all, MRB_ARGS_REQ(1));\n  mrb_define_method(mrb, gsl, \"zero\", mrb_vector_zero, MRB_ARGS_NONE());\n  mrb_define_method(mrb, gsl, \"basis\", mrb_vector_basis, MRB_ARGS_REQ(1));\n\n  mrb_define_method(mrb, gsl, \"initialize\", mrb_vector_initialize,\n                    MRB_ARGS_NONE());\n  mrb_define_method(mrb, gsl, \"rnd_fill\", mrb_vector_rnd_fill,\n                    MRB_ARGS_NONE());\n  mrb_define_method(mrb, gsl, \"dup\", mrb_vector_dup, MRB_ARGS_NONE());\n  mrb_define_method(mrb, gsl, \"===\", mrb_vector_equal, MRB_ARGS_REQ(1));\n  mrb_define_method(mrb, gsl, \"[]\", mrb_vector_get_i, MRB_ARGS_REQ(1));\n  mrb_define_method(mrb, gsl, \"[]=\", mrb_vector_set_i, MRB_ARGS_REQ(2));\n  mrb_define_method(mrb, gsl, \"to_a\", mrb_vector_to_a, MRB_ARGS_NONE());\n  mrb_define_method(mrb, gsl, \"max\", mrb_vector_max, MRB_ARGS_NONE());\n  mrb_define_method(mrb, gsl, \"min\", mrb_vector_min, MRB_ARGS_NONE());\n  mrb_define_method(mrb, gsl, \"max_index\", mrb_vector_max_index,\n                    MRB_ARGS_NONE());\n  mrb_define_method(mrb, gsl, \"min_index\", mrb_vector_min_index,\n                    MRB_ARGS_NONE());\n  mrb_define_method(mrb, gsl, \"add!\", mrb_vector_add, MRB_ARGS_REQ(1));\n  mrb_define_method(mrb, gsl, \"sub!\", mrb_vector_sub, MRB_ARGS_REQ(1));\n  mrb_define_method(mrb, gsl, \"mul!\", mrb_vector_mul, MRB_ARGS_REQ(1));\n  mrb_define_method(mrb, gsl, \"div!\", mrb_vector_div, MRB_ARGS_REQ(1));\n  mrb_define_method(mrb, gsl, \"^\", mrb_vector_prod, MRB_ARGS_REQ(1));\n  mrb_define_method(mrb, gsl, \"norm\", mrb_vector_norm, MRB_ARGS_NONE());\n  mrb_define_method(mrb, gsl, \"sum\", mrb_vector_sum, MRB_ARGS_NONE());\n  mrb_define_method(mrb, gsl, \"swap!\", mrb_vector_swap, MRB_ARGS_REQ(2));\n  mrb_define_method(mrb, gsl, \"reverse!\", mrb_vector_reverse, MRB_ARGS_NONE());\n\n  mrb_define_method(mrb, gsl, \"mean\", mrb_vector_mean, MRB_ARGS_OPT(1));\n  mrb_define_method(mrb, gsl, \"variance\", mrb_vector_variance, MRB_ARGS_OPT(1));\n  mrb_define_method(mrb, gsl, \"sd\", mrb_vector_sd, MRB_ARGS_OPT(1));\n  mrb_define_method(mrb, gsl, \"absdev\", mrb_vector_absdev, MRB_ARGS_OPT(1));\n  mrb_define_method(mrb, gsl, \"quantile\", mrb_vector_quantile, MRB_ARGS_OPT(1));\n}\n", "meta": {"hexsha": "a2233a87b80c8b57a91ef0b046997146946f0a61", "size": 17232, "ext": "c", "lang": "C", "max_stars_repo_path": "src/vector.c", "max_stars_repo_name": "UniTN-Mechatronics/mruby-gsl", "max_stars_repo_head_hexsha": "0961ef3b88bb8ed9e9223b2678ece281acaa0f4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/vector.c", "max_issues_repo_name": "UniTN-Mechatronics/mruby-gsl", "max_issues_repo_head_hexsha": "0961ef3b88bb8ed9e9223b2678ece281acaa0f4b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/vector.c", "max_forks_repo_name": "UniTN-Mechatronics/mruby-gsl", "max_forks_repo_head_hexsha": "0961ef3b88bb8ed9e9223b2678ece281acaa0f4b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0553359684, "max_line_length": 80, "alphanum_fraction": 0.6771703807, "num_tokens": 4882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37754066879814546, "lm_q2_score": 0.05261894926217173, "lm_q1q2_score": 0.019865793295895995}}
{"text": "/* interpolation/spline2d.c\n * \n * Copyright 2012 David Zaslavsky\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <string.h>\n#include <stdlib.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_interp.h>\n#include <gsl/gsl_interp2d.h>\n#include <gsl/gsl_spline2d.h>\n\ngsl_spline2d *\ngsl_spline2d_alloc(const gsl_interp2d_type * T, size_t xsize, size_t ysize)\n{\n  double * array_mem;\n  gsl_spline2d * interp;\n\n  if (xsize < T->min_size || ysize < T->min_size)\n    {\n      GSL_ERROR_NULL(\"insufficient number of points for interpolation type\", GSL_EINVAL);\n    }\n\n  interp = calloc(1, sizeof(gsl_spline2d));\n  if (interp == NULL)\n    {\n      GSL_ERROR_NULL(\"failed to allocate space for gsl_spline2d struct\", GSL_ENOMEM);\n    }\n\n  interp->interp_object.type = T;\n  interp->interp_object.xsize = xsize;\n  interp->interp_object.ysize = ysize;\n  if (interp->interp_object.type->alloc == NULL)\n    {\n      interp->interp_object.state = NULL;\n    }\n  else\n    {\n      interp->interp_object.state = interp->interp_object.type->alloc(xsize, ysize);\n      if (interp->interp_object.state == NULL)\n        {\n          gsl_spline2d_free(interp);\n          GSL_ERROR_NULL(\"failed to allocate space for gsl_spline2d state\", GSL_ENOMEM);\n        }\n    }\n\n  /*\n   * Use one contiguous block of memory for all three data arrays.\n   * That way the code fails immediately if there isn't sufficient space for everything,\n   * rather than allocating one or two and then having to free them.\n   */\n  array_mem = (double *)calloc(xsize + ysize + xsize * ysize, sizeof(double));\n  if (array_mem == NULL)\n    {\n      gsl_spline2d_free(interp);\n      GSL_ERROR_NULL(\"failed to allocate space for data arrays\", GSL_ENOMEM);\n    }\n\n  interp->xarr = array_mem;\n  interp->yarr = array_mem + xsize;\n  interp->zarr = array_mem + xsize + ysize;\n\n  return interp;\n} /* gsl_spline2d_alloc() */\n\nint\ngsl_spline2d_init(gsl_spline2d * interp, const double xarr[],\n                  const double yarr[], const double zarr[],\n                  size_t xsize, size_t ysize)\n{\n  int status = gsl_interp2d_init(&(interp->interp_object), xarr, yarr, zarr, xsize, ysize);\n\n  memcpy(interp->xarr, xarr, xsize * sizeof(double));\n  memcpy(interp->yarr, yarr, ysize * sizeof(double));\n  memcpy(interp->zarr, zarr, xsize * ysize * sizeof(double));\n\n  return status;\n} /* gsl_spline2d_init() */\n\nvoid\ngsl_spline2d_free(gsl_spline2d * interp)\n{\n  RETURN_IF_NULL(interp);\n\n  if (interp->interp_object.type->free)\n    interp->interp_object.type->free(interp->interp_object.state);\n\n  /*\n   * interp->xarr points to the beginning of one contiguous block of memory\n   * that holds interp->xarr, interp->yarr, and interp->zarr. So it all gets\n   * freed with one call. cf. gsl_spline2d_alloc() implementation\n   */\n  if (interp->xarr)\n    free(interp->xarr);\n\n  free(interp);\n} /* gsl_spline2d_free() */\n\ndouble\ngsl_spline2d_eval(const gsl_spline2d * interp, const double x,\n                  const double y, gsl_interp_accel * xa, gsl_interp_accel * ya)\n{\n  return gsl_interp2d_eval(&(interp->interp_object), interp->xarr, interp->yarr,\n                           interp->zarr, x, y, xa, ya);\n}\n\nint\ngsl_spline2d_eval_e(const gsl_spline2d * interp, const double x,\n                    const double y, gsl_interp_accel * xa, gsl_interp_accel * ya,\n                    double * z)\n{\n  return gsl_interp2d_eval_e(&(interp->interp_object), interp->xarr, interp->yarr,\n                             interp->zarr, x, y, xa, ya, z);\n}\n\ndouble\ngsl_spline2d_eval_extrap(const gsl_spline2d * interp, const double x,\n                         const double y, gsl_interp_accel * xa, gsl_interp_accel * ya)\n{\n  return gsl_interp2d_eval_extrap(&(interp->interp_object), interp->xarr, interp->yarr,\n                                  interp->zarr, x, y, xa, ya);\n}\n\nint\ngsl_spline2d_eval_extrap_e(const gsl_spline2d * interp, const double x,\n                           const double y, gsl_interp_accel * xa, gsl_interp_accel * ya,\n                           double * z)\n{\n  return gsl_interp2d_eval_extrap_e(&(interp->interp_object), interp->xarr, interp->yarr,\n                                    interp->zarr, x, y, xa, ya, z);\n}\n\ndouble\ngsl_spline2d_eval_deriv_x(const gsl_spline2d * interp, const double x,\n                          const double y, gsl_interp_accel * xa, gsl_interp_accel * ya)\n{\n  return gsl_interp2d_eval_deriv_x(&(interp->interp_object), interp->xarr, interp->yarr,\n                                   interp->zarr, x, y, xa, ya);\n}\n\nint\ngsl_spline2d_eval_deriv_x_e(const gsl_spline2d * interp, const double x,\n                            const double y, gsl_interp_accel * xa, gsl_interp_accel * ya,\n                            double * z)\n{\n  return gsl_interp2d_eval_deriv_x_e(&(interp->interp_object), interp->xarr, interp->yarr,\n                                     interp->zarr, x, y, xa, ya, z);\n}\n\ndouble\ngsl_spline2d_eval_deriv_y(const gsl_spline2d * interp, const double x,\n                          const double y, gsl_interp_accel * xa, gsl_interp_accel * ya)\n{\n  return gsl_interp2d_eval_deriv_y(&(interp->interp_object), interp->xarr, interp->yarr,\n                                   interp->zarr, x, y, xa, ya);\n}\n\nint\ngsl_spline2d_eval_deriv_y_e(const gsl_spline2d * interp, const double x,\n                            const double y, gsl_interp_accel * xa, gsl_interp_accel * ya,\n                            double * z)\n{\n  return gsl_interp2d_eval_deriv_y_e(&(interp->interp_object), interp->xarr, interp->yarr,\n                                     interp->zarr, x, y, xa, ya, z);\n}\n\ndouble\ngsl_spline2d_eval_deriv_xx(const gsl_spline2d * interp, const double x,\n                           const double y, gsl_interp_accel * xa, gsl_interp_accel * ya)\n{\n  return gsl_interp2d_eval_deriv_xx(&(interp->interp_object), interp->xarr, interp->yarr,\n                                    interp->zarr, x, y, xa, ya);\n}\n\nint\ngsl_spline2d_eval_deriv_xx_e(const gsl_spline2d * interp, const double x,\n                             const double y, gsl_interp_accel * xa, gsl_interp_accel * ya,\n                             double * z)\n{\n  return gsl_interp2d_eval_deriv_xx_e(&(interp->interp_object), interp->xarr, interp->yarr,\n                                      interp->zarr, x, y, xa, ya, z);\n}\n\ndouble\ngsl_spline2d_eval_deriv_yy(const gsl_spline2d * interp, const double x,\n                           const double y, gsl_interp_accel * xa, gsl_interp_accel * ya)\n{\n  return gsl_interp2d_eval_deriv_yy(&(interp->interp_object), interp->xarr, interp->yarr,\n                                    interp->zarr, x, y, xa, ya);\n}\n\nint\ngsl_spline2d_eval_deriv_yy_e(const gsl_spline2d * interp, const double x,\n                             const double y, gsl_interp_accel * xa, gsl_interp_accel * ya,\n                             double * z)\n{\n  return gsl_interp2d_eval_deriv_yy_e(&(interp->interp_object), interp->xarr, interp->yarr,\n                                      interp->zarr, x, y, xa, ya, z);\n}\n\ndouble\ngsl_spline2d_eval_deriv_xy(const gsl_spline2d * interp, const double x,\n                           const double y, gsl_interp_accel * xa, gsl_interp_accel * ya)\n{\n  return gsl_interp2d_eval_deriv_xy(&(interp->interp_object), interp->xarr, interp->yarr,\n                                    interp->zarr, x, y, xa, ya);\n}\n\nint\ngsl_spline2d_eval_deriv_xy_e(const gsl_spline2d * interp, const double x,\n                             const double y, gsl_interp_accel * xa, gsl_interp_accel * ya,\n                             double * z)\n{\n  return gsl_interp2d_eval_deriv_xy_e(&(interp->interp_object), interp->xarr, interp->yarr,\n                                      interp->zarr, x, y, xa, ya, z);\n}\n\nsize_t\ngsl_spline2d_min_size(const gsl_spline2d * interp)\n{\n  return gsl_interp2d_min_size(&(interp->interp_object));\n}\n\nconst char *\ngsl_spline2d_name(const gsl_spline2d * interp)\n{\n  return gsl_interp2d_name(&(interp->interp_object));\n}\n\nint\ngsl_spline2d_set(const gsl_spline2d * interp, double zarr[],\n                 const size_t i, const size_t j, const double z)\n{\n  return gsl_interp2d_set(&(interp->interp_object), zarr, i, j, z);\n} /* gsl_spline2d_set() */\n\ndouble\ngsl_spline2d_get(const gsl_spline2d * interp, const double zarr[],\n                 const size_t i, const size_t j)\n{\n  return gsl_interp2d_get(&(interp->interp_object), zarr, i, j);\n} /* gsl_spline2d_get() */\n", "meta": {"hexsha": "9d8f2d0e5082858be95972518e0f2ea3fbd63b18", "size": 9079, "ext": "c", "lang": "C", "max_stars_repo_path": "thirdparty/gsl-2.7/interpolation/spline2d.c", "max_stars_repo_name": "igormcoelho/optstats", "max_stars_repo_head_hexsha": "6d95cf06fbb96b1cc047fa570690c6eb3d21ece4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thirdparty/gsl-2.7/interpolation/spline2d.c", "max_issues_repo_name": "igormcoelho/optstats", "max_issues_repo_head_hexsha": "6d95cf06fbb96b1cc047fa570690c6eb3d21ece4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thirdparty/gsl-2.7/interpolation/spline2d.c", "max_forks_repo_name": "igormcoelho/optstats", "max_forks_repo_head_hexsha": "6d95cf06fbb96b1cc047fa570690c6eb3d21ece4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0540540541, "max_line_length": 91, "alphanum_fraction": 0.6389470206, "num_tokens": 2376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782349911420193, "lm_q2_score": 0.045352577167234585, "lm_q1q2_score": 0.019856424029205507}}
{"text": "#ifndef setup_h\n#define setup_h\n\n#include <ceed.h>\n#include <petsc.h>\n#include <petscdmplex.h>\n#include <petscfe.h>\n#include <petscksp.h>\n#include <stdbool.h>\n#include <string.h>\n#include \"problems/problems.h\"\n#include \"include/cl-options.h\"\n#include \"include/matops.h\"\n#include \"include/misc.h\"\n#include \"include/structs.h\"\n#include \"include/setup-dm.h\"\n#include \"include/setup-libceed.h\"\n#include \"include/utils.h\"\n\n#endif // setup_h\n", "meta": {"hexsha": "0a669982c9f8056bbc547874abd1d230d724cc7b", "size": 436, "ext": "h", "lang": "C", "max_stars_repo_path": "examples/solids/elasticity.h", "max_stars_repo_name": "AdelekeBankole/libCEED", "max_stars_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 123.0, "max_stars_repo_stars_event_min_datetime": "2018-01-29T02:04:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T18:13:48.000Z", "max_issues_repo_path": "examples/solids/elasticity.h", "max_issues_repo_name": "AdelekeBankole/libCEED", "max_issues_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 781.0, "max_issues_repo_issues_event_min_datetime": "2017-12-22T17:20:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T21:34:34.000Z", "max_forks_repo_path": "examples/solids/elasticity.h", "max_forks_repo_name": "AdelekeBankole/libCEED", "max_forks_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2017-12-27T22:35:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:02:07.000Z", "avg_line_length": 20.7619047619, "max_line_length": 34, "alphanum_fraction": 0.7362385321, "num_tokens": 112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.38861802670584894, "lm_q2_score": 0.051082733706665134, "lm_q1q2_score": 0.01985167117182456}}
{"text": "#ifndef OPENMC_TALLIES_TALLY_H\n#define OPENMC_TALLIES_TALLY_H\n\n#include \"openmc/constants.h\"\n#include \"openmc/memory.h\" // for unique_ptr\n#include \"openmc/tallies/filter.h\"\n#include \"openmc/tallies/trigger.h\"\n#include \"openmc/vector.h\"\n\n#include <gsl/gsl>\n#include \"pugixml.hpp\"\n#include \"xtensor/xfixed.hpp\"\n#include \"xtensor/xtensor.hpp\"\n\n#include <string>\n#include <unordered_map>\n\nnamespace openmc {\n\n//==============================================================================\n//! A user-specified flux-weighted (or current) measurement.\n//==============================================================================\n\nclass Tally {\npublic:\n  //----------------------------------------------------------------------------\n  // Constructors, destructors, factory functions\n  explicit Tally(int32_t id);\n  explicit Tally(pugi::xml_node node);\n  ~Tally();\n  static Tally* create(int32_t id = -1);\n\n  //----------------------------------------------------------------------------\n  // Accessors\n\n  void set_id(int32_t id);\n\n  void set_active(bool active) { active_ = active; }\n\n  void set_writable(bool writable) { writable_ = writable; }\n\n  void set_scores(pugi::xml_node node);\n\n  void set_scores(const vector<std::string>& scores);\n\n  void set_nuclides(pugi::xml_node node);\n\n  void set_nuclides(const vector<std::string>& nuclides);\n\n  const vector<int32_t>& filters() const { return filters_; }\n\n  int32_t filters(int i) const {return filters_[i];}\n\n  void set_filters(gsl::span<Filter*> filters);\n\n  int32_t strides(int i) const {return strides_[i];}\n\n  int32_t n_filter_bins() const {return n_filter_bins_;}\n\n  bool writable() const { return writable_;}\n\n  //----------------------------------------------------------------------------\n  // Other methods.\n\n  void add_filter(Filter* filter) { set_filters({&filter, 1}); }\n\n  void init_triggers(pugi::xml_node node);\n\n  void init_results();\n\n  void reset();\n\n  void accumulate();\n\n  //! A string representing the i-th score on this tally\n  std::string score_name(int score_idx) const;\n\n  //! A string representing the i-th nuclide on this tally\n  std::string nuclide_name(int nuclide_idx) const;\n\n  //----------------------------------------------------------------------------\n  // Major public data members.\n\n  int id_ {C_NONE}; //!< User-defined identifier\n\n  std::string name_; //!< User-defined name\n\n  TallyType type_ {TallyType::VOLUME}; //!< e.g. volume, surface current\n\n  //! Event type that contributes to this tally\n  TallyEstimator estimator_ {TallyEstimator::TRACKLENGTH};\n\n  //! Whether this tally is currently being updated\n  bool active_ {false};\n\n  //! Number of realizations\n  int n_realizations_ {0};\n\n  vector<int> scores_; //!< Filter integrands (e.g. flux, fission)\n\n  //! Index of each nuclide to be tallied.  -1 indicates total material.\n  vector<int> nuclides_ {-1};\n\n  //! True if this tally has a bin for every nuclide in the problem\n  bool all_nuclides_ {false};\n\n  //! Results for each bin -- the first dimension of the array is for the\n  //! combination of filters (e.g. specific cell, specific energy group, etc.)\n  //! and the second dimension of the array is for scores (e.g. flux, total\n  //! reaction rate, fission reaction rate, etc.)\n  xt::xtensor<double, 3> results_;\n\n  //! True if this tally should be written to statepoint files\n  bool writable_ {true};\n\n  //----------------------------------------------------------------------------\n  // Miscellaneous public members.\n\n  // We need to have quick access to some filters.  The following gives indices\n  // for various filters that could be in the tally or C_NONE if they are not\n  // present.\n  int energyout_filter_ {C_NONE};\n  int delayedgroup_filter_ {C_NONE};\n\n  vector<Trigger> triggers_;\n\n  int deriv_ {C_NONE}; //!< Index of a TallyDerivative object for diff tallies.\n\nprivate:\n  //----------------------------------------------------------------------------\n  // Private data.\n\n  vector<int32_t> filters_; //!< Filter indices in global filters array\n\n  //! Index strides assigned to each filter to support 1D indexing.\n  vector<int32_t> strides_;\n\n  int32_t n_filter_bins_ {0};\n\n  gsl::index index_;\n};\n\n//==============================================================================\n// Global variable declarations\n//==============================================================================\n\nnamespace model {\n  extern std::unordered_map<int, int> tally_map;\n  extern vector<unique_ptr<Tally>> tallies;\n  extern vector<int> active_tallies;\n  extern vector<int> active_analog_tallies;\n  extern vector<int> active_tracklength_tallies;\n  extern vector<int> active_collision_tallies;\n  extern vector<int> active_meshsurf_tallies;\n  extern vector<int> active_surface_tallies;\n}\n\nnamespace simulation {\n  //! Global tallies (such as k-effective estimators)\n  extern xt::xtensor_fixed<double, xt::xshape<N_GLOBAL_TALLIES, 3>> global_tallies;\n\n  //! Number of realizations for global tallies\n  extern \"C\" int32_t n_realizations;\n}\n\nextern double global_tally_absorption;\nextern double global_tally_collision;\nextern double global_tally_tracklength;\nextern double global_tally_leakage;\n\n//==============================================================================\n// Non-member functions\n//==============================================================================\n\n//! Read tally specification from tallies.xml\nvoid read_tallies_xml();\n\n//! \\brief Accumulate the sum of the contributions from each history within the\n//! batch to a new random variable\nvoid accumulate_tallies();\n\n//! Determine which tallies should be active\nvoid setup_active_tallies();\n\n// Alias for the type returned by xt::adapt(...). N is the dimension of the\n// multidimensional array\ntemplate <std::size_t N>\nusing adaptor_type = xt::xtensor_adaptor<xt::xbuffer_adaptor<double*&, xt::no_ownership>, N>;\n\n#ifdef OPENMC_MPI\n//! Collect all tally results onto master process\nvoid reduce_tally_results();\n#endif\n\nvoid free_memory_tally();\n\n} // namespace openmc\n\n#endif // OPENMC_TALLIES_TALLY_H\n", "meta": {"hexsha": "aaaff0e700eef6c7edf83a8711ee80233da65765", "size": 6035, "ext": "h", "lang": "C", "max_stars_repo_path": "include/openmc/tallies/tally.h", "max_stars_repo_name": "drewejohnson/openmc", "max_stars_repo_head_hexsha": "ef128f56095ac197600684ba9241dedde2b10998", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-02-07T20:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-07T20:23:33.000Z", "max_issues_repo_path": "include/openmc/tallies/tally.h", "max_issues_repo_name": "drewejohnson/openmc", "max_issues_repo_head_hexsha": "ef128f56095ac197600684ba9241dedde2b10998", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-05-22T07:57:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-21T17:34:35.000Z", "max_forks_repo_path": "include/openmc/tallies/tally.h", "max_forks_repo_name": "drewejohnson/openmc", "max_forks_repo_head_hexsha": "ef128f56095ac197600684ba9241dedde2b10998", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.175, "max_line_length": 93, "alphanum_fraction": 0.6178956089, "num_tokens": 1329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3998116264369279, "lm_q2_score": 0.049589028075641806, "lm_q1q2_score": 0.019826269968348832}}
{"text": "/**\n * \\file DelayInterface.h\n */\n\n#ifndef ATK_DELAY_DELAYINTERFACE_H\n#define ATK_DELAY_DELAYINTERFACE_H\n\n#include <ATK/Delay/config.h>\n\n#include <gsl/gsl>\n\n#include <map>\n\nnamespace ATK\n{\n  /// Interface for a fixed filter\n  class ATK_DELAY_EXPORT DelayInterface\n  {\n  public:\n    virtual ~DelayInterface() = default;\n    /// Sets the delay of the filter\n  virtual void set_delay(gsl::index delay) = 0;\n    /// Returns the delay\n    virtual gsl::index get_delay() const = 0;\n  };\n\n  /// Interface for a universal filter\n  template<class DataType>\n  class ATK_DELAY_EXPORT UniversalDelayInterface\n  {\n  public:\n    virtual ~UniversalDelayInterface() = default;\n    \n    /// Sets the blend of the filter\n    virtual void set_blend(DataType blend) = 0;\n    /// Returns the blend\n    virtual DataType get_blend() const = 0;\n    /// Sets the feedback of the filter\n    virtual void set_feedback(DataType feedback) = 0;\n    /// Returns the feedback\n    virtual DataType get_feedback() const = 0;\n    /// Sets the feedforward of the filter\n    virtual void set_feedforward(DataType feedforward) = 0;\n    /// Returns the feedforward\n    virtual DataType get_feedforward() const = 0;\n  };\n}\n\n#endif\n", "meta": {"hexsha": "c5ed4a1af7d356bacdca115fd37f59289bc4f8aa", "size": 1191, "ext": "h", "lang": "C", "max_stars_repo_path": "ATK/Delay/DelayInterface.h", "max_stars_repo_name": "AudioTK/AudioTK", "max_stars_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2021-02-04T10:47:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T03:45:00.000Z", "max_issues_repo_path": "ATK/Delay/DelayInterface.h", "max_issues_repo_name": "AudioTK/AudioTK", "max_issues_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-02-01T15:45:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-13T19:39:05.000Z", "max_forks_repo_path": "ATK/Delay/DelayInterface.h", "max_forks_repo_name": "AudioTK/AudioTK", "max_forks_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-04-12T03:28:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-17T00:47:11.000Z", "avg_line_length": 23.82, "max_line_length": 59, "alphanum_fraction": 0.6943744752, "num_tokens": 284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.399811640739795, "lm_q2_score": 0.049589019472576816, "lm_q1q2_score": 0.019826267238008583}}
{"text": "/* matrix/test.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#include <config.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_test.h>\n#include <gsl/gsl_ieee_utils.h>\n\n#define M 53\n#define N 107\n\nint status = 0;\n\n#ifndef DESC\n#define DESC \"\"\n#endif\n\n#define BASE_GSL_COMPLEX_LONG\n#include \"templates_on.h\"\n#include \"test_complex_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_GSL_COMPLEX_LONG\n\n#define BASE_GSL_COMPLEX\n#include \"templates_on.h\"\n#include \"test_complex_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_GSL_COMPLEX\n\n#define BASE_GSL_COMPLEX_FLOAT\n#include \"templates_on.h\"\n#include \"test_complex_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_GSL_COMPLEX_FLOAT\n\n#define BASE_LONG_DOUBLE\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_LONG_DOUBLE\n\n#define BASE_DOUBLE\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_DOUBLE\n\n#define BASE_FLOAT\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_FLOAT\n\n#define BASE_ULONG\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_ULONG\n\n#define BASE_LONG\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_LONG\n\n#define BASE_UINT\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_UINT\n\n#define BASE_INT\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_INT\n\n#define BASE_USHORT\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_USHORT\n\n#define BASE_SHORT\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_SHORT\n\n#define BASE_UCHAR\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_UCHAR\n\n#define BASE_CHAR\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_CHAR\n\nvoid my_error_handler (const char *reason, const char *file,\n\t\t       int line, int err);\n\nint\nmain (void)\n{\n  gsl_ieee_env_setup ();\n\n  test_func ();\n  test_float_func ();\n  test_long_double_func ();\n  test_ulong_func ();\n  test_long_func ();\n  test_uint_func ();\n  test_int_func ();\n  test_ushort_func ();\n  test_short_func ();\n  test_uchar_func ();\n  test_char_func ();\n  test_complex_func ();\n  test_complex_float_func ();\n  test_complex_long_double_func ();\n\n  test_text ();\n  test_float_text ();\n#ifdef HAVE_PRINTF_LONGDOUBLE\n  test_long_double_text ();\n#endif\n  test_ulong_text ();\n  test_long_text ();\n  test_uint_text ();\n  test_int_text ();\n  test_ushort_text ();\n  test_short_text ();\n  test_uchar_text ();\n  test_char_text ();\n  test_complex_text ();\n  test_complex_float_text ();\n#ifdef HAVE_PRINTF_LONGDOUBLE\n  test_complex_long_double_text ();\n#endif\n\n  test_binary ();\n  test_float_binary ();\n  test_long_double_binary ();\n  test_ulong_binary ();\n  test_long_binary ();\n  test_uint_binary ();\n  test_int_binary ();\n  test_ushort_binary ();\n  test_short_binary ();\n  test_uchar_binary ();\n  test_char_binary ();\n  test_complex_binary ();\n  test_complex_float_binary ();\n  test_complex_long_double_binary ();\n\n  gsl_warnings_off = 1;\n\n  gsl_set_error_handler (&my_error_handler);\n\n  test_trap ();\n  test_float_trap ();\n  test_long_double_trap ();\n  test_ulong_trap ();\n  test_long_trap ();\n  test_uint_trap ();\n  test_int_trap ();\n  test_ushort_trap ();\n  test_short_trap ();\n  test_uchar_trap ();\n  test_char_trap ();\n  test_complex_trap ();\n  test_complex_float_trap ();\n  test_complex_long_double_trap ();\n\n  exit (gsl_test_summary ());\n}\n\nvoid\nmy_error_handler (const char *reason, const char *file, int line, int err)\n{\n  if (0)\n    printf (\"(caught [%s:%d: %s (%d)])\\n\", file, line, reason, err);\n  status = 1;\n}\n", "meta": {"hexsha": "cffc98911cb1ca5ccdffad54aecccd2239c1b5a5", "size": 4634, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/matrix/test.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/matrix/test.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/matrix/test.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 22.2788461538, "max_line_length": 74, "alphanum_fraction": 0.7388864912, "num_tokens": 1127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.0396388410863502, "lm_q1q2_score": 0.0198194205431751}}
{"text": "/* combination/init.c\n * based on permutation/init.c by Brian Gough\n * \n * Copyright (C) 2001 Szymon Jaroszewicz\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <stdlib.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_combination.h>\n\ngsl_combination *\ngsl_combination_alloc (const size_t n, const size_t k)\n{\n  gsl_combination * c;\n\n  if (n == 0)\n    {\n      GSL_ERROR_VAL (\"combination parameter n must be positive integer\",\n                        GSL_EDOM, 0);\n    }\n  if (k > n)\n    {\n      GSL_ERROR_VAL (\"combination length k must be an integer less than or equal to n\",\n                        GSL_EDOM, 0);\n    }\n  c = (gsl_combination *) malloc (sizeof (gsl_combination));\n\n  if (c == 0)\n    {\n      GSL_ERROR_VAL (\"failed to allocate space for combination struct\",\n                        GSL_ENOMEM, 0);\n    }\n\n  if (k > 0)\n    {\n      c->data = (size_t *) malloc (k * sizeof (size_t));\n\n      if (c->data == 0)\n        {\n          free (c);             /* exception in constructor, avoid memory leak */\n\n          GSL_ERROR_VAL (\"failed to allocate space for combination data\",\n                         GSL_ENOMEM, 0);\n        }\n    }\n  else\n    {\n      c->data = 0;\n    }\n\n  c->n = n;\n  c->k = k;\n\n  return c;\n}\n\ngsl_combination *\ngsl_combination_calloc (const size_t n, const size_t k)\n{\n  size_t i;\n\n  gsl_combination * c =  gsl_combination_alloc (n, k);\n\n  if (c == 0)\n    return 0;\n\n  /* initialize combination to identity */\n\n  for (i = 0; i < k; i++)\n    {\n      c->data[i] = i;\n    }\n\n  return c;\n}\n\nvoid\ngsl_combination_init_first (gsl_combination * c)\n{\n  const size_t k = c->k ;\n  size_t i;\n\n  /* initialize combination to identity */\n\n  for (i = 0; i < k; i++)\n    {\n      c->data[i] = i;\n    }\n}\n\nvoid\ngsl_combination_init_last (gsl_combination * c)\n{\n  const size_t k = c->k ;\n  size_t i;\n  size_t n = c->n;\n\n  /* initialize combination to identity */\n\n  for (i = 0; i < k; i++)\n    {\n      c->data[i] = n - k + i;\n    }\n}\n\nvoid\ngsl_combination_free (gsl_combination * c)\n{\n  if (c->k > 0) free (c->data);\n  free (c);\n}\n", "meta": {"hexsha": "6bac2d459b12d5c9c7ae908791f7b4f828e9b8c1", "size": 2755, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/combination/init.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/combination/init.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/combination/init.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 21.6929133858, "max_line_length": 87, "alphanum_fraction": 0.6054446461, "num_tokens": 777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37022539259558657, "lm_q2_score": 0.053403327163362595, "lm_q1q2_score": 0.019771267764966467}}
{"text": "#include \"readArray_MPI.h\"\n#include \"../include/paralleltt.h\"\n\n#include <mpi.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <lapacke.h>\n#include <time.h>\n#include <math.h>\n\nvoid* p_hilbert_init(int d, int* n){\n    p_hilbert* parameters = (p_hilbert*) malloc(sizeof(p_hilbert));\n    parameters->d = d;\n    parameters->n = (int*) malloc(d*sizeof(int));\n    for (int ii = 0; ii < d; ++ii){\n        parameters->n[ii] = n[ii];\n    }\n    parameters->n_stream = (int*) calloc(d, sizeof(int));\n    parameters->n_prod = (long*) malloc(d * sizeof(long));\n    return (void*) parameters;\n}\n\n\nvoid p_hilbert_free(void* parameters){\n    p_hilbert* p_casted = (p_hilbert*) parameters;\n    free(p_casted->n); p_casted->n = NULL;\n    free(p_casted->n_stream); p_casted->n_stream = NULL;\n    free(p_casted->n_prod); p_casted->n_prod = NULL;\n    free(p_casted);\n}\n\nvoid f_hilbert(double* restrict X, int* ind1, int* ind2, const void* parameters)\n{\n    p_hilbert* p_casted = (p_hilbert*) parameters;\n    int d = p_casted->d;\n    int* n = p_casted->n;\n    int* n_stream = p_casted->n_stream;\n    long* n_prod = p_casted->n_prod;\n\n\n    long N_stream = 1;\n    for (int ii = 0; ii < d; ++ii){\n        n_stream[ii] = ind2[ii] - ind1[ii];\n        N_stream = N_stream*n_stream[ii];\n    }\n\n    n_prod[0] = 1;\n    for (int ii = 1; ii < d; ++ii){\n        n_prod[ii] = (long) n_prod[ii-1] * n_stream[ii-1];\n    }\n\n    int bias = 1;\n    for (int jj = 0; jj < d; ++jj){\n        bias = bias + ind1[jj];\n    }\n\n    for (long ii = 0; ii < N_stream; ++ii){\n        int xinv = bias;\n\t\tlong tmp = ii;\n\t\tfor (int jj = d-1; jj >= 0; jj--){\n\t\t\txinv += tmp/n_prod[jj];\n\t\t\ttmp = tmp % n_prod[jj];\n\t\t}\n\n        X[ii] = (double) 1/xinv;\n    }\n}\n\nvoid* p_gaussian_bumps_init(int d, int* n, int M, double gamma, double* region, double* centers)\n{\n    p_gaussian_bumps* parameters = (p_gaussian_bumps*) malloc(sizeof(p_gaussian_bumps));\n    parameters->d = d;\n    parameters->n = (int*) calloc(d, sizeof(int));\n    for (int ii = 0; ii < d; ++ii){\n        parameters->n[ii] = n[ii];\n    }\n\n    parameters->M = M;\n    parameters->gamma = gamma;\n\n    parameters->region = (double*) calloc(2*d, sizeof(double));\n    for (int ii = 0; ii < 2*d; ++ii){\n        parameters->region[ii] = region[ii];\n    }\n    parameters->centers = (double*) calloc(d*M, sizeof(double));\n    for (int ii = 0; ii < d*M; ++ii){\n        parameters->centers[ii] = centers[ii];\n    }\n\n//    parameters->ten_ind_ii = (int*) calloc(d, sizeof(int));\n    parameters->x_ii = (double*) calloc(d, sizeof(double));\n    parameters->n_stream = (int*) calloc(d, sizeof(double));\n    parameters->n_prod = (long*) calloc(d, sizeof(long));\n\n    return (void*) parameters;\n}\n\nvoid* unit_random_p_gaussian_bumps_init(int d, int* n, int M, double gamma, int seed)\n{\n    p_gaussian_bumps* parameters = (p_gaussian_bumps*) malloc(sizeof(p_gaussian_bumps));\n    parameters->d = d;\n    parameters->n = (int*) calloc(d, sizeof(int));\n    for (int ii = 0; ii < d; ++ii){\n        parameters->n[ii] = n[ii];\n    }\n\n    parameters->M = M;\n    parameters->gamma = gamma;\n\n    parameters->region = (double*) calloc(2*d, sizeof(double));\n    for (int ii = 0; ii < d; ++ii){\n        parameters->region[2*ii] = -1.0;\n        parameters->region[2*ii+1] = 1.0;\n    }\n\n    parameters->centers = (double*) calloc(d*M, sizeof(double));\n    srand(seed);\n    int r1 = rand()%4096, r2 = rand()%4096, r3 = rand()%4096, r4 = rand()%4096;\n    int iseed[4] = {r1, r2, r3, r4+(r4%2 == 0?1:0)};\n    LAPACKE_dlarnv(2, iseed, d*M, parameters->centers);\n\n    parameters->x_ii = (double*) calloc(d, sizeof(double));\n    parameters->n_stream = (int*) calloc(d, sizeof(double));\n    parameters->n_prod = (long*) calloc(d, sizeof(long));\n\n    return (void*) parameters;\n}\n\nvoid p_gaussian_bumps_free(void* parameters)\n{\n    p_gaussian_bumps* p_casted = (p_gaussian_bumps*) parameters;\n\n    free(p_casted->n);          p_casted->n = NULL;\n    free(p_casted->region);     p_casted->region = NULL;\n    free(p_casted->centers);    p_casted->centers = NULL;\n    free(p_casted->x_ii);       p_casted->x_ii = NULL;\n    free(p_casted->n_stream);   p_casted->n_stream = NULL;\n    free(p_casted->n_prod);     p_casted->n_prod = NULL;\n    free(p_casted);\n}\n\nvoid f_gaussian_bumps(double* restrict X, int* ind1, int* ind2, const void* parameters)\n{\n    p_gaussian_bumps* p_casted = (p_gaussian_bumps*) parameters;\n    int d = p_casted->d;\n    int* n = p_casted->n;\n    int M = p_casted->M;\n    double gamma = p_casted->gamma;\n    double* region = p_casted->region;\n    double* centers = p_casted->centers;\n    double* x_ii = p_casted->x_ii;\n    int* n_stream = p_casted->n_stream;\n    long* n_prod = p_casted->n_prod;\n\n    long N_stream = 1;\n    for (int ii = 0; ii < d; ++ii){\n        n_stream[ii] = ind2[ii] - ind1[ii];\n        N_stream = N_stream*n_stream[ii];\n    }\n\n    n_prod[0] = 1;\n    for (int ii = 1; ii < d; ++ii){\n        n_prod[ii] = (long) n_prod[ii-1] * n_stream[ii-1];\n    }\n\n    for (long ii = 0; ii < N_stream; ++ii){\n        long tmp = ii;\n        for (int jj = d-1; jj >= 0; jj--){\n            int ind_jj = tmp/n_prod[jj];\n            x_ii[jj] = region[2*jj] + (ind_jj + ind1[jj]) * (region[2*jj + 1] - region[2*jj]) / (n[jj] - 1);\n\t\t\ttmp = tmp % n_prod[jj];\n\t\t}\n\n        X[ii] = 0;\n        for (int kk = 0; kk < M; ++kk){\n            double exponent = 0;\n            for (int jj = 0; jj < d; ++jj){\n                exponent += (x_ii[jj] - centers[kk*d + jj]) * (x_ii[jj] - centers[kk*d + jj]);\n            }\n            X[ii] += exp(-gamma * exponent);\n        }\n    }\n}\n\nvoid* p_arithmetic_init(int d, int* n)\n{\n    p_arithmetic* parameters = (p_arithmetic*) malloc(sizeof(p_arithmetic));\n    parameters->d = d;\n    parameters->n = (int*) malloc(d*sizeof(int));\n    for (int ii = 0; ii < d; ++ii){\n        parameters->n[ii] = n[ii];\n    }\n    return (void*) parameters;\n}\n\nvoid p_arithmetic_free(void* parameters)\n{\n    p_arithmetic* p_casted = (p_arithmetic*) parameters;\n    free(p_casted->n); p_casted->n = NULL;\n    free(p_casted);\n}\n\n\nvoid f_arithmetic(double* restrict X, int* ind1, int* ind2, const void* parameters)\n{\n    p_arithmetic* p_casted = (p_arithmetic*) parameters;\n    int d = p_casted->d;\n    int* n = p_casted->n;\n\n    int* n_stream = (int*) calloc(d, sizeof(int));\n    long N_stream = 1;\n    for (int ii = 0; ii < d; ++ii){\n        n_stream[ii] = ind2[ii] - ind1[ii];\n        N_stream = N_stream*n_stream[ii];\n    }\n\n    int* ind_ii = (int*) calloc(d, sizeof(int));\n    for (int ii = 0; ii < N_stream; ++ii){\n        to_tensor_ind(ind_ii, ii, n_stream, d);\n        for (int jj = 0; jj < d; ++jj){\n            ind_ii[jj] = ind_ii[jj] + ind1[jj];\n        }\n        X[ii] = 1 + to_vec_ind(ind_ii, n, d);\n//        X[ii] = X[ii] + (0.000000001 / X[ii]);\n    }\n\n    free(n_stream);\n    free(ind_ii);\n}\n\n\n\nvoid* p_tt_init(tensor_train* tt)\n{\n    p_tt* parameters = (p_tt*) malloc(sizeof(p_tt));\n    parameters->tt = tt;\n    return (void*) parameters;\n}\n\n// Doesn't actually free the tensor train. You gotta do that yourself\nvoid p_tt_free(void* parameters)\n{\n    p_tt* p_casted = (p_tt*) parameters;\n    p_casted->tt = NULL;\n    free(p_casted);\n}\n\nvoid f_tt(double* restrict X, int* ind1, int* ind2, const void* parameters)\n{\n    p_tt* p_casted = (p_tt*) parameters;\n    tensor_train* tt = p_casted->tt;\n    int d = tt->d;\n    int* n = tt->n;\n    int* r = tt->r;\n\n    matrix_tt** train_submats = (matrix_tt**) calloc(d, sizeof(matrix_tt*));\n    for (int ii = 0; ii < d; ++ii){\n        matrix_tt* train_mat_ii = matrix_tt_wrap(r[ii]*n[ii], r[ii+1], tt->trains[ii]);\n        train_submats[ii] = submatrix(train_mat_ii, ind1[ii]*r[ii], ind2[ii]*r[ii], 0, r[ii+1]);\n        free(train_mat_ii);\n    }\n\n    matrix_tt* mult = submatrix_copy(train_submats[d-1]);\n    matrix_tt_reshape(r[d-1], ind2[d-1] - ind1[d-1], mult);\n\n\n    for (int jj = d-2; jj >= 1; --jj){\n        matrix_tt* new_mult = matrix_tt_init(train_submats[jj]->m, mult->n);\n        matrix_tt_dgemm(train_submats[jj], mult, new_mult, 1.0, 0.0);\n        matrix_tt_reshape(r[jj], (new_mult->n) * (new_mult->m) / r[jj], new_mult);\n        matrix_tt_free(mult); mult = new_mult;\n    }\n\n    long X_m = 1;\n    for (int ii = 1; ii < d; ++ii){\n        X_m = X_m*(ind2[ii] - ind1[ii]);\n    }\n\n    matrix_tt* X_mat = matrix_tt_wrap(ind2[0] - ind1[0], X_m, X);\n    matrix_tt_dgemm(train_submats[0], mult, X_mat, 1.0, 0.0);\n\n    for (int ii = 0; ii < d; ++ii){\n        free(train_submats[ii]); train_submats[ii] = NULL;\n    }\n\n    free(train_submats); train_submats = NULL;\n    matrix_tt_free(mult);   mult = NULL;\n    free(X_mat);         X_mat = NULL;\n}\n\n\ndouble tt_error(tensor_train* tt, MPI_tensor* ten)\n{\n    MPI_Comm comm = ten->comm;\n    tt_broadcast(comm, tt);\n\n\n    void* parameters_tt = p_tt_init(tt);\n    MPI_tensor* ten_tt = MPI_tensor_init(ten->d, ten->n, ten->nps, ten->comm, &f_tt, parameters_tt);\n    int rank = ten_tt->rank;\n    int* schedule_rank = ten_tt->schedule[rank];\n\n    double true_norm_squared = 0;\n    double diff_norm_squared = 0;\n\n    flattening_info* fi = flattening_info_init(ten, 0, 1, 0);\n    for (int ii = 0; ii < ten->n_schedule; ++ii){\n        int block = schedule_rank[ii];\n\n        if (block != -1){\n            stream(ten, block);\n            stream(ten_tt, block);\n\n            flattening_info_update(fi, ten, block);\n            long N = fi->t_N;\n\n            for (int jj = 0; jj < N; ++jj){\n                ten_tt->X[jj] = ten_tt->X[jj] - ten->X[jj];\n            }\n\n            matrix_tt* mat_true = matrix_tt_wrap(N, 1, ten->X);\n            double tmp = frobenius_norm(mat_true);\n            true_norm_squared = true_norm_squared + tmp*tmp;\n\n            matrix_tt* mat_diff = matrix_tt_wrap(N, 1, ten_tt->X);\n            tmp = frobenius_norm(mat_diff);\n            diff_norm_squared = diff_norm_squared + tmp*tmp;\n//            printf(\"r%d ii%d true_norm_squared = %e, diff_norm_squared = %e\\n\", rank, ii, true_norm_squared, diff_norm_squared);\n\n            free(mat_true); mat_true = NULL;\n            free(mat_diff); mat_diff = NULL;\n        }\n    }\n    int head = 0;\n\n    double true_norm_reduced;\n    double diff_norm_reduced;\n    MPI_Reduce(&true_norm_squared, &true_norm_reduced, 1, MPI_DOUBLE, MPI_SUM, head, comm);\n    true_norm_reduced = sqrt(true_norm_reduced);\n\n    MPI_Reduce(&diff_norm_squared, &diff_norm_reduced, 1, MPI_DOUBLE, MPI_SUM, head, comm);\n    diff_norm_reduced = sqrt(diff_norm_reduced);\n\n    double rel_err = diff_norm_reduced/true_norm_reduced;\n\n\n\n    p_tt_free(parameters_tt); parameters_tt = NULL;\n    flattening_info_free(fi); fi = NULL;\n    MPI_tensor_free(ten_tt); ten_tt = NULL;\n\n    return rel_err;\n}", "meta": {"hexsha": "1d913068b63aaa2461d80cc31daa4883dcee991e", "size": 10623, "ext": "c", "lang": "C", "max_stars_repo_path": "test/readArray_MPI.c", "max_stars_repo_name": "SidShi/Parallel_TT_sketching", "max_stars_repo_head_hexsha": "e2c00c289d75d3ac1df32ed2b95af579a517fcbf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/readArray_MPI.c", "max_issues_repo_name": "SidShi/Parallel_TT_sketching", "max_issues_repo_head_hexsha": "e2c00c289d75d3ac1df32ed2b95af579a517fcbf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/readArray_MPI.c", "max_forks_repo_name": "SidShi/Parallel_TT_sketching", "max_forks_repo_head_hexsha": "e2c00c289d75d3ac1df32ed2b95af579a517fcbf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0934844193, "max_line_length": 130, "alphanum_fraction": 0.5875929587, "num_tokens": 3350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167300566462553, "lm_q2_score": 0.04468087345289264, "lm_q1q2_score": 0.01973433567365987}}
{"text": "/*\n * Copyright (c) 1997-1999 Massachusetts Institute of Technology\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n *\n */\n\n#include <stdlib.h>\n#include <fftw.h>\n\n#include \"mex.h\"\n\n/**************************************************************************/\n\n/* MEX programs need to use special memory allocation routines,\n   so we use the hooks provided by FFTW to ensure that MEX\n   allocation is used: */\n\nvoid *fftw_mex_malloc_hook(size_t n)\n{\n     void *buf;\n\n     buf = mxMalloc(n);\n\n     /* Call this routine so that we can retain allocations and\n\tdata between calls to the FFTW MEX: */\n     mexMakeMemoryPersistent(buf);\n\n     return buf;\n}\n\nvoid fftw_mex_free_hook(void *buf)\n{\n     mxFree(buf);\n}\n\nvoid install_fftw_hooks(void)\n{\n     fftw_malloc_hook = fftw_mex_malloc_hook;\n     fftw_free_hook = fftw_mex_free_hook;\n}\n\n/**************************************************************************/\n\n/* We retain various information between calls to the FFTW MEX in\n   order to maximize performance.  (Reusing plans, data, and\n   allocated blocks where possible.)  This information is referenced\n   by the following variables, which are initialized in the function\n   initialize_fftw_mex_data. */\n\n#define MAX_RANK 10\n\nint first_call = 1; /* 1 if this is the first call to the FFTW MEX,\n\t\t       and nothing has been initialized yet.  0 otherwise. */\n\n/* Keep track of the array dimensions that stored data (below) is for.\n   When these dimensions changed, we have to recompute the plans,\n   work arrays, etc. */\nint  cur_rank = 0,         /* rank of the array */\n     cur_dims[MAX_RANK],   /* dimensions */\n     cur_N;                /* product of the dimensions */\n\n/* Work arrays.  MATLAB stores complex numbers as separate real/imag.\n   arrays, so we have to translate into our format before the FFT.\n   In case allocation is slow, we retain these work arrays between\n   calls so that they can be reused. */\nfftw_complex *input_work = 0, *output_work = 0;\n\n/* The number of floating point operations required for the FFT.\n   (Starting with FFTW 1.3, an exact count is computed by the planner.)\n   This is used to update MATLAB's flops count. */\nint fftw_mex_flops = 0, ifftw_mex_flops = 0;\n\n/* Plans.  These are computed once and then reused as long as the\n   dimensions of the array don't changed.  At any point in time,\n   at most two plans are cached: a forward and backwards plan,\n   either for one- or multi-dimensional transforms. */\nfftw_plan p = 0, ip = 0;\nfftwnd_plan pnd = 0, ipnd = 0;\n\n/**************************************************************************/\n\nint compute_fftw_mex_flops(fftw_direction dir)\n{\n#ifdef FFTW_HAS_COUNT_PLAN_OPS /* this feature will be in FFTW 1.3 */\n     fftw_op_count ops;\n\n     if (dir == FFTW_FORWARD) {\n\t  if (cur_rank == 1)\n\t       fftw_count_plan_ops(p,&ops);\n\t  else\n\t       fftwnd_count_plan_ops(pnd,&ops);\n     }\n     else {\n\t  if (cur_rank == 1)\n\t       fftw_count_plan_ops(ip,&ops);\n\t  else\n\t       fftwnd_count_plan_ops(ipnd,&ops);\n     }\n\n     return (ops.fp_additions + ops.fp_multiplications);\n#else\n     return 0;\n#endif\n}\n\n/**************************************************************************/\n\n/* The following functions destroy and/or initialize the data that\n   FFTW-MEX caches between calls. */\n\nvoid destroy_fftw_mex_data(void) {\n     if (output_work != input_work)\n\t  fftw_free(output_work);\n     if (input_work)\n\t  fftw_free(input_work);\n     if (p)\n\t  fftw_destroy_plan(p);\n     if (pnd)\n\t  fftwnd_destroy_plan(pnd);\n     if (ip)\n\t  fftw_destroy_plan(ip);\n     if (ipnd)\n\t  fftwnd_destroy_plan(ipnd);\n\n     cur_rank = 0;\n     input_work = output_work = 0;\n     ip = p = 0;\n     ipnd = pnd = 0;\n}\n\n/* This function is called when MATLAB exits or the MEX file is\n   cleared, in which case we want to dispose of all data and\n   free any allocated blocks. */\n\nvoid fftw_mex_exit_function(void)\n{\n     if (!first_call) {\n\t  destroy_fftw_mex_data();\n\t  fftw_forget_wisdom();\n\t  first_call = 1;\n     }\n}\n\n#define MAGIC(x) #x\n#define STRINGIZE(x) MAGIC(x)\n\n/* Initialize the cached data each time the MEX file is called.  First,\n   we check if we have previously computed plans and data for these\n   array dimensions.  Only if the dimensions have changed since the\n   last call must we recompute the plans, etc. */\n\nvoid initialize_fftw_mex_data(int rank, const int *dims, fftw_direction dir)\n{\n     int new_plan = 0;\n\n     if (first_call) {\n\t  /* The following things need only be done once: */\n\t  install_fftw_hooks();\n\t  mexAtExit(fftw_mex_exit_function);\n\t  first_call = 0;\n     }\n\n     if (rank == 1) {\n\t  if (cur_rank != 1 || cur_dims[0] != dims[0]) {\n\t       destroy_fftw_mex_data();\n\n\t       cur_rank = 1;\n\t       cur_dims[0] = cur_N = dims[0];\n\t       \n\t       input_work = (fftw_complex*)fftw_malloc(sizeof(fftw_complex) * cur_N);\n\t       output_work = (fftw_complex*)fftw_malloc(sizeof(fftw_complex) * cur_N);\n\t       \n\t       new_plan = 1;\n\t  }\n\t  else if (dir == FFTW_FORWARD && !p ||\n\t\t   dir == FFTW_BACKWARD && !ip)\n\t       new_plan = 1;\n\n\t  if (new_plan) {\n\t       if (dir == FFTW_FORWARD) {\n\t\t    p = fftw_create_plan(cur_N,dir,\n\t\t\t\t\t FFTW_MEASURE | FFTW_USE_WISDOM);\n\n\t\t    fftw_mex_flops = compute_fftw_mex_flops(dir);\n\t       }\n\t       else {\n\t\t    ip = fftw_create_plan(cur_N,dir,\n\t\t\t\t\t  FFTW_MEASURE | FFTW_USE_WISDOM);\n\n\t\t    ifftw_mex_flops = compute_fftw_mex_flops(dir);\n\t       }\n\t  }\n     }\n     else {\n\t  int same_dims = 1, dim;\n\n\t  if (cur_rank == rank)\n\t       for (dim = 0; dim < rank && same_dims; ++dim)\n\t\t    same_dims = (cur_dims[dim] == dims[rank-1-dim]);\n\t  else\n\t       same_dims = 0;\n\n\t  if (!same_dims) {\n\t       if (rank > MAX_RANK)\n\t\t    mexErrMsgTxt(\"Sorry, dimensionality > \" STRINGIZE(MAX_RANK)\n\t\t\t\t \" is not supported.\");\n\n\t       destroy_fftw_mex_data();\n\n\t       cur_rank = rank;\n\n\t       cur_N = 1;\n\t       for (dim = 0; dim < rank; ++dim)\n\t\t    cur_N *= (cur_dims[dim] = dims[rank-1-dim]);\n\n\t       input_work = (fftw_complex*)fftw_malloc(sizeof(fftw_complex) * cur_N);\n\t       output_work = input_work;\n\n\t       new_plan = 1;\n\t  }\n          else if (dir == FFTW_FORWARD && !pnd ||\n                   dir == FFTW_BACKWARD && !ipnd)\n               new_plan = 1;\n\n\t  if (new_plan) {\n\t       if (dir == FFTW_FORWARD) {\n\t\t    pnd = fftwnd_create_plan(rank,cur_dims,dir,\n\t\t\t\t\t     FFTW_IN_PLACE | \n\t\t\t\t\t     FFTW_MEASURE | FFTW_USE_WISDOM);\n\t\t    \n\t\t    fftw_mex_flops = compute_fftw_mex_flops(dir);\n\t       }\n\t       else {\n\t\t    ipnd = fftwnd_create_plan(rank,cur_dims,dir,\n\t\t\t\t\t      FFTW_IN_PLACE | \n\t\t\t\t\t      FFTW_MEASURE | FFTW_USE_WISDOM);\n\t\t    \n\t\t    ifftw_mex_flops = compute_fftw_mex_flops(dir);\n\t       }\n\t  }\n\n     }\n}\n\n/**************************************************************************/\n\n/* MATLAB stores complex numbers as separate arrays for real and\n   imaginary parts.  The following functions take the data in\n   this format and pack it into a fftw_complex work array, or\n   unpack it, respectively. The globals input_work and output_work\n   are used as the arrays to pack to/unpack from.*/\n\nvoid pack_input_work(double *input_re, double *input_im)\n{\n     int i;\n\n     if (input_im)\n\t  for (i = 0; i < cur_N; ++i) {\n\t       c_re(input_work[i]) = input_re[i];\n\t       c_im(input_work[i]) = input_im[i];\n\t  }\n     else\n\t  for (i = 0; i < cur_N; ++i) {\n\t       c_re(input_work[i]) = input_re[i];\n\t       c_im(input_work[i]) = 0.0;\n\t  }\n}\n\nvoid unpack_output_work(double *output_re, double *output_im)\n{\n     int i;\n\n     for (i = 0; i < cur_N; ++i) {\n\t  output_re[i] = c_re(output_work[i]);\n\t  output_im[i] = c_im(output_work[i]);\n     }\n}\n\n/**************************************************************************/\n\n/* The following function is called by MATLAB when the FFTW\n   MEX is invoked from within the program.\n\n   The rhs parameters are the list of arrays on the right-hand-side\n   (rhs) of the MATLAB command--the arguments to FFTW.  The lhs\n   parameters are the list of arrays on the left-hand-side (lhs) of\n   the MATLAB command--these are what the output(s) of FFTW are\n   assigned to.\n\n   The syntax for the FFTW call in MATLAB is fftw(array,sign),\n   as described in fftw.m  */\n\nvoid mexFunction(int nlhs, mxArray *plhs[],\n\t\t int nrhs, const mxArray *prhs[])\n{\n     int rank;\n     const int *dims;\n     int m, n;  /* Array is m x n, C-ordered */\n     fftw_direction dir;\n\n     if (nrhs != 2)\n\t  mexErrMsgTxt(\"Two input arguments are expected.\");\n\n     if (!mxIsDouble(prhs[0]))\n\t  mexErrMsgTxt(\"First input must be a double precision matrix.\");\n     if (mxIsSparse(prhs[0]))\n\t  mexErrMsgTxt(\"Sorry, sparse matrices are not currently supported.\");\n\n     if (mxGetM(prhs[1]) * mxGetN(prhs[1]) != 1)\n\t  mexErrMsgTxt(\"Second input must be a scalar (+/- 1).\");\n\n     if (mxGetScalar(prhs[1]) > 0.0)\n\t  dir = FFTW_BACKWARD;\n     else\n\t  dir = FFTW_FORWARD;\n\n     if ((rank = mxGetNumberOfDimensions(prhs[0])) == 2) {\n\t  int dims2[2];\n\t  m = mxGetM(prhs[0]);\n\t  n = mxGetN(prhs[0]);\n\t  if (m == 1 || n == 1) {\n\t       dims2[0] = m * n;\n\t       initialize_fftw_mex_data(1,dims2,dir);\n\t  }\n\t  else {\n\t       dims2[0] = m;\n\t       dims2[1] = n;\n\t       initialize_fftw_mex_data(2,dims2,dir);\n\t  }\n     }\n     else\n\t  initialize_fftw_mex_data(rank,dims = mxGetDimensions(prhs[0]),dir);\n\n     pack_input_work(mxGetPr(prhs[0]),mxGetPi(prhs[0]));\n     \n     if (dir == FFTW_FORWARD) {\n\t  if (cur_rank == 1)\n\t       fftw(p,1, input_work,1,0, output_work,1,0);\n\t  else\n\t       fftwnd(pnd,1, input_work,1,0, 0,0,0);\n\t  \n\t  mexAddFlops(fftw_mex_flops);\n     }\n     else {\n\t  if (cur_rank == 1)\n\t       fftw(ip,1, input_work,1,0, output_work,1,0);\n\t  else\n\t       fftwnd(ipnd,1, input_work,1,0, 0,0,0);\n\t  \n\t  mexAddFlops(ifftw_mex_flops);\n     }\n\n     /* Create a matrix for the return argument. */\n     if (cur_rank <= 2)\n\t  plhs[0] = mxCreateDoubleMatrix(m, n, mxCOMPLEX);\n     else\n\t  plhs[0] = mxCreateNumericArray(rank,dims,\n\t\t\t\t\t mxDOUBLE_CLASS,mxCOMPLEX);\n\n     unpack_output_work(mxGetPr(plhs[0]),mxGetPi(plhs[0]));\n}\n", "meta": {"hexsha": "df86c33e40e5e25f118765a4a791922f9b3642c9", "size": 10647, "ext": "c", "lang": "C", "max_stars_repo_path": "original/lib/fftw-2.1.3/matlab/fftw.c", "max_stars_repo_name": "albertsgrc/ftdock-opt", "max_stars_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "original/lib/fftw-2.1.3/matlab/fftw.c", "max_issues_repo_name": "albertsgrc/ftdock-opt", "max_issues_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "original/lib/fftw-2.1.3/matlab/fftw.c", "max_forks_repo_name": "albertsgrc/ftdock-opt", "max_forks_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.392, "max_line_length": 79, "alphanum_fraction": 0.6144453837, "num_tokens": 2873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31405054499180746, "lm_q2_score": 0.06278921517368556, "lm_q1q2_score": 0.019718987244903816}}
{"text": "#include <gsl/gsl_test.h>\n#include <gsl/gsl_ieee_utils.h>\n#include <gsl/gsl_math.h>\n#include \"gsl_cblas.h\"\n\n#include \"tests.h\"\n\nvoid\ntest_trsm (void) {\nconst double flteps = 1e-4, dbleps = 1e-6;\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha = -0.3f;\n   float A[] = { 0.773f, 0.069f, 0.45f, 0.189f };\n   int lda = 2;\n   float B[] = { -0.037f, 0.788f, 0.015f, 0.028f, -0.804f, -0.357f };\n   int ldb = 3;\n   float B_expected[] = { 0.0183269f, -0.419738f, -0.0564036f, -0.0444444f, 1.27619f, 0.566667f };\n   cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strsm(case 1830)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha = -0.3f;\n   float A[] = { -0.13f, -0.832f, 0.426f, 0.195f };\n   int lda = 2;\n   float B[] = { 0.504f, 0.996f, 0.872f, -0.35f, 0.518f, -0.8f };\n   int ldb = 3;\n   float B_expected[] = { -0.06384f, -0.428093f, -0.06192f, 0.105f, -0.1554f, 0.24f };\n   cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strsm(case 1831)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha = -0.3f;\n   float A[] = { 0.755f, -0.053f, -0.132f, -0.515f };\n   int lda = 2;\n   float B[] = { -0.735f, 0.494f, 0.072f, -0.882f, -0.112f, 0.904f };\n   int ldb = 3;\n   float B_expected[] = { 0.292053f, -0.196291f, -0.0286093f, -0.588643f, -0.0149311f, 0.533935f };\n   cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strsm(case 1832)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha = -0.3f;\n   float A[] = { -0.88f, -0.555f, 0.642f, 0.751f };\n   int lda = 2;\n   float B[] = { -0.411f, 0.134f, 0.657f, 0.072f, -0.007f, -0.34f };\n   int ldb = 3;\n   float B_expected[] = { 0.1233f, -0.0402f, -0.1971f, -0.100759f, 0.0279084f, 0.228538f };\n   cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strsm(case 1833)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha = -0.3f;\n   float A[] = { -0.478f, 0.938f, -0.731f, 0.25f };\n   int lda = 2;\n   float B[] = { -0.859f, -0.409f, -0.154f, -0.54f, 0.146f, -0.106f };\n   int ldb = 2;\n   float B_expected[] = { -1.2897f, 0.4908f, -1.08763f, 0.648f, -0.102894f, 0.1272f };\n   cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strsm(case 1834)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha = -0.3f;\n   float A[] = { 0.953f, 0.249f, -0.451f, -0.781f };\n   int lda = 2;\n   float B[] = { -0.4f, -0.546f, 0.839f, 0.392f, -0.445f, -0.818f };\n   int ldb = 2;\n   float B_expected[] = { 0.193874f, 0.1638f, -0.304738f, -0.1176f, 0.244175f, 0.2454f };\n   cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strsm(case 1835)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha = -0.3f;\n   float A[] = { 0.831f, -0.997f, -0.366f, 0.307f };\n   int lda = 2;\n   float B[] = { 0.157f, -0.02f, 0.57f, 0.309f, -0.159f, 0.266f };\n   int ldb = 2;\n   float B_expected[] = { -0.0566787f, -0.164523f, -0.205776f, -0.970224f, 0.0574007f, -0.0735227f };\n   cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strsm(case 1836)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha = -0.3f;\n   float A[] = { -0.842f, 0.674f, 0.03f, 0.628f };\n   int lda = 2;\n   float B[] = { -0.426f, 0.806f, 0.299f, 0.626f, -0.471f, 0.208f };\n   int ldb = 2;\n   float B_expected[] = { 0.1278f, -0.327937f, -0.0897f, -0.127342f, 0.1413f, -0.157636f };\n   cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strsm(case 1837)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha = -0.3f;\n   float A[] = { -0.095f, 0.301f, 0.168f, 0.934f, 0.107f, 0.068f, 0.384f, -0.201f, 0.116f };\n   int lda = 3;\n   float B[] = { 0.534f, 0.773f, -0.304f, -0.402f, 0.642f, -0.102f };\n   int ldb = 3;\n   float B_expected[] = { 1.68632f, -6.91104f, 2.39525f, -1.26947f, 1.77114f, 1.06409f };\n   cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strsm(case 1838)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha = -0.3f;\n   float A[] = { -0.738f, -0.353f, -0.616f, 0.304f, 0.403f, 0.739f, 0.996f, 0.329f, 0.273f };\n   int lda = 3;\n   float B[] = { -0.436f, 0.074f, 0.273f, -0.609f, 0.858f, 0.993f };\n   int ldb = 3;\n   float B_expected[] = { 0.1308f, 0.0239724f, -0.0190428f, 0.1827f, -0.192907f, -0.0427986f };\n   cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strsm(case 1839)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha = -0.3f;\n   float A[] = { -0.956f, 0.878f, 0.156f, 0.217f, 0.082f, -0.869f, 0.595f, 0.845f, 0.064f };\n   int lda = 3;\n   float B[] = { -0.744f, 0.662f, -0.31f, 0.811f, 0.257f, 0.98f };\n   int ldb = 3;\n   float B_expected[] = { -3.27779f, -17.3962f, 1.45312f, 7.92713f, 46.3978f, -4.59375f };\n   cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strsm(case 1840)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha = -0.3f;\n   float A[] = { 0.313f, -0.316f, 0.836f, 0.359f, -0.415f, 0.154f, -0.948f, -0.596f, -0.799f };\n   int lda = 3;\n   float B[] = { 0.29f, -0.291f, 0.652f, 0.614f, 0.922f, -0.063f };\n   int ldb = 3;\n   float B_expected[] = { -0.261918f, -0.0292776f, -0.1956f, -0.0710273f, -0.265336f, 0.0189f };\n   cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strsm(case 1841)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha = -0.3f;\n   float A[] = { -0.634f, 0.561f, 0.883f, -0.136f, 0.203f, -0.531f, 0.733f, -0.332f, 0.705f };\n   int lda = 3;\n   float B[] = { 0.133f, -0.843f, -0.179f, 0.94f, -0.656f, 0.645f };\n   int ldb = 2;\n   float B_expected[] = { 0.0629338f, -0.398896f, 0.306695f, -1.6564f, 0.358145f, -0.639766f };\n   cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strsm(case 1842)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha = -0.3f;\n   float A[] = { 0.742f, -0.438f, 0.991f, 0.614f, 0.108f, -0.125f, 0.736f, -0.383f, 0.0f };\n   int lda = 3;\n   float B[] = { -0.792f, -0.033f, -0.723f, 0.885f, 0.336f, 0.584f };\n   int ldb = 2;\n   float B_expected[] = { 0.2376f, 0.0099f, 0.0710136f, -0.271579f, -0.248475f, -0.286501f };\n   cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strsm(case 1843)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha = -0.3f;\n   float A[] = { 0.761f, 0.466f, 0.907f, -0.85f, -0.342f, -0.058f, -0.379f, -0.416f, 0.599f };\n   int lda = 3;\n   float B[] = { -0.238f, 0.013f, 0.473f, -0.626f, 0.912f, -0.003f };\n   int ldb = 2;\n   float B_expected[] = { 0.336709f, 0.329497f, 0.492375f, -0.549378f, -0.456761f, 0.0015025f };\n   cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strsm(case 1844)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha = -0.3f;\n   float A[] = { 0.567f, -0.532f, -0.817f, 0.85f, -0.135f, 0.797f, 0.981f, -0.75f, 0.856f };\n   int lda = 3;\n   float B[] = { -0.705f, 0.326f, 0.184f, 0.079f, -0.173f, 0.125f };\n   int ldb = 2;\n   float B_expected[] = { 0.20253f, -0.125146f, -0.0965643f, 0.0061875f, 0.0519f, -0.0375f };\n   cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strsm(case 1845)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha = -0.3f;\n   float A[] = { -0.859f, 0.563f, -0.61f, 0.2f };\n   int lda = 2;\n   float B[] = { -0.241f, -0.357f, -0.683f, -0.718f, 0.69f, -0.486f };\n   int ldb = 3;\n   float B_expected[] = { -0.0841676f, -0.12468f, -0.238533f, 1.31393f, -0.684026f, 1.40047f };\n   cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strsm(case 1846)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha = -0.3f;\n   float A[] = { 0.157f, -0.741f, 0.844f, 0.206f };\n   int lda = 2;\n   float B[] = { 0.816f, -0.692f, 0.765f, -0.408f, 0.404f, 0.764f };\n   int ldb = 3;\n   float B_expected[] = { -0.2448f, 0.2076f, -0.2295f, -0.0589968f, 0.0326316f, -0.399259f };\n   cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strsm(case 1847)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha = -0.3f;\n   float A[] = { 0.187f, 0.354f, -0.931f, 0.18f };\n   int lda = 2;\n   float B[] = { -0.215f, -0.645f, 0.847f, 0.014f, 0.83f, 0.761f };\n   int ldb = 3;\n   float B_expected[] = { 0.228752f, -5.85232f, -7.67336f, -0.0233333f, -1.38333f, -1.26833f };\n   cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strsm(case 1848)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha = -0.3f;\n   float A[] = { -0.923f, 0.27f, -0.319f, -0.856f };\n   int lda = 2;\n   float B[] = { 0.391f, 0.01f, 0.429f, 0.685f, 0.332f, -0.643f };\n   int ldb = 3;\n   float B_expected[] = { -0.182855f, -0.0347724f, -0.0671649f, -0.2055f, -0.0996f, 0.1929f };\n   cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strsm(case 1849)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha = -0.3f;\n   float A[] = { 0.724f, 0.201f, 0.87f, -0.638f };\n   int lda = 2;\n   float B[] = { -0.533f, 0.183f, 0.569f, 0.85f, 0.642f, -0.051f };\n   int ldb = 2;\n   float B_expected[] = { 0.220856f, 0.387218f, -0.235773f, 0.0781772f, -0.266022f, -0.386739f };\n   cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strsm(case 1850)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha = -0.3f;\n   float A[] = { 0.291f, 0.244f, 0.931f, 0.857f };\n   int lda = 2;\n   float B[] = { 0.008f, -0.478f, -0.252f, -0.155f, 0.419f, -0.192f };\n   int ldb = 2;\n   float B_expected[] = { -0.0024f, 0.145634f, 0.0756f, -0.0238836f, -0.1257f, 0.174627f };\n   cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strsm(case 1851)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha = -0.3f;\n   float A[] = { -0.634f, -0.529f, -0.344f, 0.375f };\n   int lda = 2;\n   float B[] = { -0.295f, 0.551f, 0.832f, 0.744f, -0.326f, 0.111f };\n   int ldb = 2;\n   float B_expected[] = { 0.228207f, -0.4408f, 0.890317f, -0.5952f, -0.0801653f, -0.0888f };\n   cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strsm(case 1852)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha = -0.3f;\n   float A[] = { 0.641f, 0.989f, 0.998f, -0.005f };\n   int lda = 2;\n   float B[] = { -0.168f, 0.465f, 0.36f, 0.356f, -0.858f, 0.879f };\n   int ldb = 2;\n   float B_expected[] = { 0.188365f, -0.1395f, -0.0023748f, -0.1068f, 0.518199f, -0.2637f };\n   cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strsm(case 1853)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha = -0.3f;\n   float A[] = { -0.638f, 0.389f, 0.997f, 0.909f, -0.598f, -0.43f, -0.345f, -0.897f, 0.119f };\n   int lda = 3;\n   float B[] = { 0.64f, 0.779f, -0.129f, 0.016f, 0.599f, -0.668f };\n   int ldb = 3;\n   float B_expected[] = { 0.904844f, 0.156956f, 0.32521f, 2.08405f, -0.910426f, 1.68403f };\n   cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strsm(case 1854)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha = -0.3f;\n   float A[] = { 0.289f, 0.641f, -0.876f, -0.503f, -0.062f, -0.987f, 0.1f, -0.105f, 0.757f };\n   int lda = 3;\n   float B[] = { -0.285f, 0.285f, 0.219f, -0.986f, -0.0f, -0.605f };\n   int ldb = 3;\n   float B_expected[] = { 0.124319f, -0.150346f, -0.0657f, 0.339965f, 0.17914f, 0.1815f };\n   cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strsm(case 1855)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha = -0.3f;\n   float A[] = { 0.524f, 0.018f, 0.292f, -0.573f, 0.866f, 0.749f, 0.99f, 0.101f, 0.871f };\n   int lda = 3;\n   float B[] = { 0.522f, -0.269f, -0.142f, -0.266f, -0.505f, -0.55f };\n   int ldb = 3;\n   float B_expected[] = { -0.298855f, -0.104554f, 0.400719f, 0.15229f, 0.275707f, -0.0156298f };\n   cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strsm(case 1856)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha = -0.3f;\n   float A[] = { 0.283f, 0.62f, -0.387f, -0.739f, -0.599f, 0.114f, 0.552f, 0.083f, -0.976f };\n   int lda = 3;\n   float B[] = { 0.202f, 0.169f, 0.7f, 0.473f, 0.86f, -0.557f };\n   int ldb = 3;\n   float B_expected[] = { -0.0606f, -0.0954834f, -0.168624f, -0.1419f, -0.362864f, 0.275547f };\n   cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strsm(case 1857)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha = -0.3f;\n   float A[] = { -0.185f, 0.178f, -0.22f, -0.645f, -0.585f, -0.342f, -0.594f, -0.141f, 0.944f };\n   int lda = 3;\n   float B[] = { 0.22f, -0.895f, -0.301f, -0.683f, -0.009f, -0.451f };\n   int ldb = 2;\n   float B_expected[] = { 0.888147f, -0.569939f, -0.155048f, -0.384802f, 0.00286017f, 0.143326f };\n   cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strsm(case 1858)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha = -0.3f;\n   float A[] = { -0.145f, 0.746f, 0.541f, 0.584f, -0.394f, 0.371f, -0.172f, -0.601f, 0.542f };\n   int lda = 3;\n   float B[] = { 0.529f, 0.636f, 0.668f, 0.848f, -0.816f, -0.925f };\n   int ldb = 2;\n   float B_expected[] = { -0.0854817f, -0.0918985f, -0.0532752f, -0.0876225f, 0.2448f, 0.2775f };\n   cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strsm(case 1859)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha = -0.3f;\n   float A[] = { 0.416f, -0.526f, -0.486f, -0.716f, 0.361f, 0.365f, -0.492f, 0.544f, 0.721f };\n   int lda = 3;\n   float B[] = { 0.25f, 0.746f, 0.55f, 0.836f, -0.024f, 0.226f };\n   int ldb = 2;\n   float B_expected[] = { -0.180288f, -0.537981f, -0.719755f, -1.47861f, 0.25283f, 0.291864f };\n   cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strsm(case 1860)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha = -0.3f;\n   float A[] = { -0.735f, -0.606f, -0.124f, 0.641f, -0.074f, -0.053f, -0.734f, 0.907f, 0.558f };\n   int lda = 3;\n   float B[] = { 0.623f, 0.392f, -0.808f, -0.022f, -0.665f, -0.616f };\n   int ldb = 2;\n   float B_expected[] = { -0.1869f, -0.1176f, 0.129139f, -0.0646656f, 0.183169f, 0.16679f };\n   cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strsm(case 1861)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha = 0.1;\n   double A[] = { -0.584, -0.058, -0.964, -0.214 };\n   int lda = 2;\n   double B[] = { 0.073, -0.734, -0.058, -0.115, 0.513, 0.503 };\n   int ldb = 3;\n   double B_expected[] = { -0.0178370247087, 0.149492702599, 0.0332751888363, 0.053738317757, -0.239719626168, -0.235046728972 };\n   cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrsm(case 1862)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha = 0.1;\n   double A[] = { 0.251, -0.8, 0.365, 0.809 };\n   int lda = 2;\n   double B[] = { -0.632, -0.611, 0.9, 0.063, -0.652, -0.841 };\n   int ldb = 3;\n   double B_expected[] = { -0.05816, -0.11326, 0.02272, 0.0063, -0.0652, -0.0841 };\n   cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrsm(case 1863)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha = 0.1;\n   double A[] = { -0.833, 0.934, -0.608, 0.49 };\n   int lda = 2;\n   double B[] = { 0.336, -0.541, -0.729, -0.382, 0.741, 0.546 };\n   int ldb = 3;\n   double B_expected[] = { -0.0403361344538, 0.0649459783914, 0.0875150060024, -0.128008917853, 0.231810520126, 0.220018619693 };\n   cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrsm(case 1864)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha = 0.1;\n   double A[] = { 0.824, 0.907, 0.632, -0.348 };\n   int lda = 2;\n   double B[] = { 0.351, -0.301, 0.602, 0.873, 0.031, -0.2 };\n   int ldb = 3;\n   double B_expected[] = { 0.0351, -0.0301, 0.0602, 0.0651168, 0.0221232, -0.0580464 };\n   cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrsm(case 1865)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha = 0.1;\n   double A[] = { 0.427, 0.193, -0.959, -0.679 };\n   int lda = 2;\n   double B[] = { -0.646, 0.741, -0.339, 0.049, 0.734, -0.182 };\n   int ldb = 2;\n   double B_expected[] = { -0.3963857167, -0.10913107511, -0.0955986383061, -0.00721649484536, 0.232096380888, 0.0268041237113 };\n   cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrsm(case 1866)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha = 0.1;\n   double A[] = { 0.282, 0.766, -0.422, -0.518 };\n   int lda = 2;\n   double B[] = { 0.269, 0.211, -0.911, -0.685, -0.777, -0.919 };\n   int ldb = 2;\n   double B_expected[] = { 0.0358042, 0.0211, -0.120007, -0.0685, -0.1164818, -0.0919 };\n   cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrsm(case 1867)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha = 0.1;\n   double A[] = { -0.877, -0.818, 0.191, 0.468 };\n   int lda = 2;\n   double B[] = { 0.517, 0.669, 0.337, -0.579, 0.885, -0.677 };\n   int ldb = 2;\n   double B_expected[] = { -0.0589509692132, 0.039910485435, -0.0384264538198, -0.190882135095, -0.100912200684, -0.321038846495 };\n   cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrsm(case 1868)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha = 0.1;\n   double A[] = { 0.469, 0.115, 0.284, 0.139 };\n   int lda = 2;\n   double B[] = { 0.889, -0.002, -0.686, -0.256, 0.028, 0.371 };\n   int ldb = 2;\n   double B_expected[] = { 0.0889, -0.0104235, -0.0686, -0.017711, 0.0028, 0.036778 };\n   cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrsm(case 1869)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha = 0.1;\n   double A[] = { -0.218, -0.819, -0.523, 0.042, 0.545, -0.292, 0.283, 0.224, 0.247 };\n   int lda = 3;\n   double B[] = { 0.677, 0.153, -0.272, -0.226, 0.987, -0.216 };\n   int ldb = 3;\n   double B_expected[] = { -0.310550458716, -0.438607019611, -1.28619894589, 0.103669724771, 0.336890834105, 0.530329512606 };\n   cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrsm(case 1870)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha = 0.1;\n   double A[] = { 0.241, 0.561, 0.164, 0.486, 0.891, -0.508, -0.596, -0.074, 0.576 };\n   int lda = 3;\n   double B[] = { -0.325, 0.382, 0.368, 0.761, -0.349, 0.324 };\n   int ldb = 3;\n   double B_expected[] = { -0.0325, 0.0564325, 0.07079771, 0.0761, -0.0775921, -0.0194971868 };\n   cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrsm(case 1871)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha = 0.1;\n   double A[] = { 0.76, 0.58, -0.203, 0.053, 0.792, 0.355, -0.685, 0.449, -0.367 };\n   int lda = 3;\n   double B[] = { 0.861, -0.44, 0.842, -0.019, -0.382, -0.579 };\n   int ldb = 3;\n   double B_expected[] = { -0.0986936127734, 0.0745114634079, -0.229427792916, 0.149297547123, -0.137672708006, 0.157765667575 };\n   cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrsm(case 1872)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha = 0.1;\n   double A[] = { 0.802, 0.298, 0.159, 0.333, 0.515, 0.715, -0.32, -0.217, 0.301 };\n   int lda = 3;\n   double B[] = { -0.268, 0.1, -0.631, 0.472, 0.796, 0.278 };\n   int ldb = 3;\n   double B_expected[] = { -0.0457623309, -0.0036927, -0.0631, 0.0275803442, 0.0856326, 0.0278 };\n   cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrsm(case 1873)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha = 0.1;\n   double A[] = { -0.028, 0.186, -0.435, -0.747, 0.212, 0.257, 0.804, -0.595, 0.64 };\n   int lda = 3;\n   double B[] = { 0.729, -0.847, -0.577, 0.056, -0.493, 0.619 };\n   int ldb = 2;\n   double B_expected[] = { -2.60357142857, 3.025, -9.44607479784, 10.685259434, -5.58819230648, 6.23051463001 };\n   cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrsm(case 1874)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha = 0.1;\n   double A[] = { -0.74, -0.091, 0.484, 0.769, 0.91, 0.817, -0.26, 0.579, 0.393 };\n   int lda = 3;\n   double B[] = { 0.109, 0.969, -0.668, 0.544, 0.753, 0.796 };\n   int ldb = 2;\n   double B_expected[] = { 0.0109, 0.0969, -0.0751821, -0.0201161, 0.1216644359, 0.1164412219 };\n   cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrsm(case 1875)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha = 0.1;\n   double A[] = { 0.123, -0.328, -0.482, 0.083, -0.125, -0.712, -0.757, -0.009, 0.237 };\n   int lda = 3;\n   double B[] = { -0.18, 0.358, 0.839, -0.725, 0.73, -0.095 };\n   int ldb = 2;\n   double B_expected[] = { -5.40775366883, 2.28950005146, -2.42566413502, 0.808320675105, 0.308016877637, -0.0400843881857 };\n   cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrsm(case 1876)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha = 0.1;\n   double A[] = { 0.255, -0.069, -0.137, -0.45, -0.24, 0.221, -0.509, -0.484, -0.131 };\n   int lda = 3;\n   double B[] = { -0.563, 0.993, 0.508, 0.771, 0.745, 0.233 };\n   int ldb = 2;\n   double B_expected[] = { -0.0437243505, 0.1074566983, 0.0343355, 0.0719507, 0.0745, 0.0233 };\n   cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrsm(case 1877)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha = -1;\n   double A[] = { -0.772, 0.079, -0.227, 0.998 };\n   int lda = 2;\n   double B[] = { -0.095, 0.012, -0.988, -0.722, 0.738, 0.05 };\n   int ldb = 3;\n   double B_expected[] = { -0.123056994819, 0.0155440414508, -1.27979274611, 0.733187878347, -0.740709398071, 0.051206039021 };\n   cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrsm(case 1878)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha = -1;\n   double A[] = { -0.045, 0.059, -0.61, -0.328 };\n   int lda = 2;\n   double B[] = { 0.302, -0.099, 0.521, 0.487, -0.961, 0.903 };\n   int ldb = 3;\n   double B_expected[] = { -0.302, 0.099, -0.521, -0.469182, 0.955159, -0.872261 };\n   cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrsm(case 1879)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha = -1;\n   double A[] = { -0.319, 0.642, 0.511, 0.762 };\n   int lda = 2;\n   double B[] = { 0.883, 0.987, 0.436, -0.783, 0.175, -0.973 };\n   int ldb = 3;\n   double B_expected[] = { 4.41405227952, 2.72615785879, 3.41221747752, 1.02755905512, -0.229658792651, 1.27690288714 };\n   cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrsm(case 1880)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha = -1;\n   double A[] = { 0.676, 0.038, 0.543, 0.296 };\n   int lda = 2;\n   double B[] = { 0.804, -0.28, -0.318, 0.382, -0.165, -0.007 };\n   int ldb = 3;\n   double B_expected[] = { -0.596574, 0.190405, 0.314199, -0.382, 0.165, 0.007 };\n   cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrsm(case 1881)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha = -1;\n   double A[] = { -0.722, -0.355, -0.14, -0.146 };\n   int lda = 2;\n   double B[] = { -0.44, 0.751, -0.995, 0.625, 0.16, -0.127 };\n   int ldb = 2;\n   double B_expected[] = { -0.609418282548, 5.72820931203, -1.37811634349, 5.60230334307, 0.221606648199, -1.08236253937 };\n   cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrsm(case 1882)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha = -1;\n   double A[] = { 0.817, -0.619, 0.548, 0.064 };\n   int lda = 2;\n   double B[] = { -0.756, -0.169, 0.429, -0.789, 0.79, 0.479 };\n   int ldb = 2;\n   double B_expected[] = { 0.756, -0.245288, -0.429, 1.024092, -0.79, -0.04608 };\n   cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrsm(case 1883)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha = -1;\n   double A[] = { 0.496, -0.734, -0.679, -0.697 };\n   int lda = 2;\n   double B[] = { -0.483, -0.508, -0.819, 0.237, 0.852, -0.512 };\n   int ldb = 2;\n   double B_expected[] = { -0.104772180312, -0.728837876614, 2.1543973018, 0.340028694405, -2.80479705651, -0.734576757532 };\n   cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrsm(case 1884)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha = -1;\n   double A[] = { 0.049, 0.079, -0.8, -0.762 };\n   int lda = 2;\n   double B[] = { 0.426, 0.094, 0.794, -0.098, 0.442, -0.991 };\n   int ldb = 2;\n   double B_expected[] = { -0.418574, -0.094, -0.801742, 0.098, -0.520289, 0.991 };\n   cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrsm(case 1885)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha = -1;\n   double A[] = { -0.974, 0.848, -0.765, 0.528, -0.693, 0.252, -0.135, -0.507, 0.954 };\n   int lda = 3;\n   double B[] = { 0.395, 0.791, -0.787, 0.636, 0.271, -0.905 };\n   int ldb = 3;\n   double B_expected[] = { 1.01254427581, 1.4413950829, 0.824947589099, 0.548697105717, 0.736012415258, 0.948637316562 };\n   cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrsm(case 1886)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha = -1;\n   double A[] = { 0.919, -0.513, -0.38, 0.587, -0.862, 0.598, 0.714, 0.726, 0.491 };\n   int lda = 3;\n   double B[] = { -0.056, -0.802, -0.962, 0.656, -0.195, -0.679 };\n   int ldb = 3;\n   double B_expected[] = { 0.537869412, 0.226724, 0.962, -0.506244546, -0.211042, 0.679 };\n   cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrsm(case 1887)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha = -1;\n   double A[] = { -0.287, -0.009, -0.989, -0.062, 0.714, -0.293, -0.875, 0.371, 0.728 };\n   int lda = 3;\n   double B[] = { -0.14, -0.969, 0.702, -0.317, -0.739, -0.518 };\n   int ldb = 3;\n   double B_expected[] = { -0.487804878049, 1.31478445037, -2.22062403761, -1.10452961672, 0.939102470256, -1.09460224052 };\n   cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrsm(case 1888)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha = -1;\n   double A[] = { 0.236, 0.605, 0.338, -0.926, 0.362, 0.562, -0.554, 0.076, 0.85 };\n   int lda = 3;\n   double B[] = { 0.113, 0.604, 0.859, 0.216, -0.6, -0.048 };\n   int ldb = 3;\n   double B_expected[] = { -0.113, -0.708638, -0.867745512, -0.216, 0.399984, -0.102062784 };\n   cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrsm(case 1889)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha = -1;\n   double A[] = { -0.476, 0.428, -0.214, -0.889, -0.526, -0.704, 0.458, -0.479, 0.077 };\n   int lda = 3;\n   double B[] = { 0.124, -0.007, 0.452, 0.966, 0.42, 0.369 };\n   int ldb = 2;\n   double B_expected[] = { -15.8695808776, -16.2060574143, 5.8264777048, 6.20050861686, -5.45454545455, -4.79220779221 };\n   cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrsm(case 1890)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha = -1;\n   double A[] = { 0.748, 0.242, -0.964, 0.422, -0.78, -0.595, -0.926, -0.474, 0.947 };\n   int lda = 3;\n   double B[] = { 0.242, -0.553, -0.899, -0.714, -0.084, -0.609 };\n   int ldb = 2;\n   double B_expected[] = { -0.560396352, 0.693808948, 0.938816, 1.002666, 0.084, 0.609 };\n   cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrsm(case 1891)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha = -1;\n   double A[] = { 0.808, -0.074, 0.359, -0.172, -0.934, -0.67, 0.92, -0.617, -0.383 };\n   int lda = 3;\n   double B[] = { 0.079, 0.978, 0.82, 0.444, -0.597, -0.64 };\n   int ldb = 2;\n   double B_expected[] = { -0.0977722772277, -1.2103960396, 0.885690737168, 0.571273347892, -3.19977295412, -3.80492250994 };\n   cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrsm(case 1892)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha = -1;\n   double A[] = { 0.786, 0.922, -0.763, 0.498, -0.082, 0.538, 0.742, -0.391, -0.255 };\n   int lda = 3;\n   double B[] = { 0.911, 0.066, 0.895, 0.255, -0.547, -0.805 };\n   int ldb = 2;\n   double B_expected[] = { -0.911, -0.066, -0.055058, -0.194148, -0.118471796, 0.859093624 };\n   cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrsm(case 1893)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 1.0f};\n   float A[] = { -0.362f, -0.457f, -0.347f, -0.203f, -0.517f, 0.462f, 0.572f, 0.521f };\n   int lda = 2;\n   float B[] = { 0.118f, -0.593f, 0.773f, 0.053f, -0.419f, -0.096f, 0.846f, -0.311f, -0.364f, 0.161f, -0.496f, -0.393f };\n   int ldb = 3;\n   float B_expected[] = { -1.58885f, 0.58489f, -0.628497f, -0.878921f, 0.701485f, 1.08554f, 1.03347f, 0.537701f, -0.470639f, -0.207688f, -0.056162f, -0.815978f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1894) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1894) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 1.0f};\n   float A[] = { 0.845f, -0.654f, -0.43f, -0.834f, 0.206f, 0.414f, 0.761f, 0.961f };\n   int lda = 2;\n   float B[] = { 0.069f, 0.005f, -0.419f, 0.806f, 0.857f, 0.669f, 0.942f, 0.657f, 0.52f, 0.19f, -0.609f, -0.305f };\n   int ldb = 3;\n   float B_expected[] = { -1.07314f, -0.073878f, -1.32138f, -0.35386f, -0.029944f, 0.8495f, -0.657f, 0.942f, -0.19f, 0.52f, 0.305f, -0.609f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1895) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1895) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 1.0f};\n   float A[] = { -0.87f, 0.218f, 0.813f, 0.575f, -0.848f, 0.7f, -0.311f, 0.374f };\n   int lda = 2;\n   float B[] = { 0.117f, 0.758f, -0.189f, -0.768f, 0.857f, -0.269f, 0.796f, -0.592f, -0.499f, 0.977f, 0.643f, 0.282f };\n   int ldb = 3;\n   float B_expected[] = { 0.851499f, 0.0788813f, -0.881826f, -0.00372192f, -0.0586805f, -0.999761f, -1.37808f, -2.51525f, 2.45259f, 2.57925f, 1.0972f, 1.8459f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1896) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1896) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 1.0f};\n   float A[] = { -0.697f, -0.668f, 0.746f, -0.818f, 0.651f, 0.275f, -0.702f, -0.615f };\n   int lda = 2;\n   float B[] = { -0.876f, 0.842f, -0.848f, 0.901f, 0.75f, 0.361f, -0.702f, 0.039f, -0.41f, 0.541f, 0.489f, 0.025f };\n   int ldb = 3;\n   float B_expected[] = { -0.842f, -0.876f, -0.901f, -0.848f, -0.361f, 0.75f, 0.268242f, 0.099826f, -0.187649f, 0.389823f, 0.416261f, 0.100025f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1897) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1897) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 1.0f};\n   float A[] = { -0.394f, -0.65f, -0.082f, -0.632f, -0.53f, 0.483f, 0.149f, -0.192f };\n   int lda = 2;\n   float B[] = { -0.691f, 0.732f, 0.976f, 0.073f, 0.607f, 0.918f, -0.918f, 0.67f, 0.37f, -0.344f, -0.114f, -0.62f };\n   int ldb = 2;\n   float B_expected[] = { -1.39367f, -3.05481f, -3.35679f, 2.2248f, 4.33836f, -1.06673f, 1.29393f, -4.49373f, -1.89826f, 2.23995f, 1.93461f, 1.72783f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1898) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1898) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 1.0f};\n   float A[] = { 0.45f, 0.972f, -0.051f, 0.71f, -0.127f, -0.274f, 0.152f, 0.789f };\n   int lda = 2;\n   float B[] = { 0.683f, -0.915f, -0.773f, 0.088f, -0.28f, 0.17f, 0.818f, 0.293f, -0.551f, 0.365f, 0.899f, 0.257f };\n   int ldb = 2;\n   float B_expected[] = { 1.11563f, 0.560717f, -0.088f, -0.773f, -0.431343f, -0.256396f, -0.293f, 0.818f, -0.643965f, -0.507245f, -0.257f, 0.899f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1899) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1899) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 1.0f};\n   float A[] = { -0.993f, -0.028f, -0.547f, -0.251f, 0.781f, -0.315f, 0.865f, 0.229f };\n   int lda = 2;\n   float B[] = { 0.578f, 0.73f, -0.931f, 0.288f, 0.048f, 0.508f, -0.168f, 0.655f, 0.92f, -0.26f, 0.485f, 0.05f };\n   int ldb = 2;\n   float B_expected[] = { 0.718162f, -0.602325f, -0.0323644f, -1.24023f, 0.509813f, -0.0627138f, -0.410611f, 0.0227614f, -0.287729f, -0.918372f, -0.000635986f, -0.10338f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1900) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1900) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 1.0f};\n   float A[] = { 0.131f, -0.494f, 0.615f, -0.089f, -0.22f, -0.874f, 0.677f, 0.074f };\n   int lda = 2;\n   float B[] = { -0.276f, 0.539f, 0.647f, 0.986f, -0.34f, 0.983f, -0.819f, 0.144f, 0.361f, 0.561f, 0.178f, -0.433f };\n   int ldb = 2;\n   float B_expected[] = { -0.539f, -0.276f, -0.629951f, 0.768769f, -0.983f, -0.34f, 0.490805f, -0.697387f, -0.561f, 0.361f, 0.745886f, -0.093944f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1901) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1901) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 1.0f};\n   float A[] = { -0.123f, -0.726f, -0.011f, 0.245f, -0.205f, 0.77f, -0.81f, -0.973f, 0.354f, -0.835f, 0.552f, 0.396f, -0.524f, -0.204f, -0.814f, 0.284f, -0.976f, -0.835f };\n   int lda = 3;\n   float B[] = { -0.42f, 0.976f, -0.845f, 0.651f, -0.44f, -0.862f, 0.137f, 0.066f, -0.63f, 0.482f, -0.187f, 0.724f };\n   int ldb = 3;\n   float B_expected[] = { 0.783777f, -1.21156f, 0.66205f, -1.40548f, 0.886226f, 0.0391664f, -0.168468f, -0.119451f, 0.378144f, -0.774828f, 0.708857f, -0.807468f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1902) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1902) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 1.0f};\n   float A[] = { 0.921f, 0.167f, -0.41f, 0.578f, -0.372f, 0.106f, 0.551f, 0.668f, 0.295f, 0.855f, -0.167f, 0.976f, -0.782f, -0.777f, 0.278f, -0.98f, 0.038f, -0.832f };\n   int lda = 3;\n   float B[] = { 0.459f, 0.06f, 0.387f, 0.871f, -0.366f, 0.926f, 0.236f, -0.889f, 0.619f, 0.319f, -0.709f, 0.884f };\n   int ldb = 3;\n   float B_expected[] = { -0.06f, 0.459f, -0.630298f, 0.60987f, -0.409693f, 0.528127f, 0.889f, 0.236f, 0.181898f, 0.201918f, -0.300827f, -0.859254f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1903) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1903) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 1.0f};\n   float A[] = { -0.691f, -0.817f, 0.954f, -0.969f, -0.574f, -0.026f, 0.992f, 0.529f, 0.135f, -0.413f, -0.314f, -0.859f, -0.284f, -0.849f, 0.781f, 0.534f, -0.018f, 0.282f };\n   int lda = 3;\n   float B[] = { -0.028f, -0.429f, 0.066f, -0.854f, -0.316f, 0.514f, -0.465f, -0.857f, 0.286f, 0.415f, -0.486f, 0.538f };\n   int ldb = 3;\n   float B_expected[] = { 6.83575f, 2.7232f, 3.79999f, 5.15624f, -1.00015f, 1.88653f, 5.42614f, 2.69261f, 2.30584f, 3.85628f, -1.59513f, 2.00962f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1904) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1904) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 1.0f};\n   float A[] = { -0.839f, -0.318f, 0.175f, 0.72f, -0.683f, 0.395f, -0.279f, 0.151f, -0.71f, 0.445f, 0.533f, -0.38f, -0.749f, -0.833f, 0.871f, -0.426f, 0.195f, 0.889f };\n   int lda = 3;\n   float B[] = { 0.804f, -0.346f, 0.234f, 0.782f, 0.033f, 0.581f, 0.981f, -0.68f, 0.919f, -0.758f, 0.152f, -0.503f };\n   int ldb = 3;\n   float B_expected[] = { -0.20395f, 0.376748f, -0.290007f, -0.042249f, -0.581f, 0.033f, 1.15245f, 1.75457f, 0.255135f, 1.00089f, 0.503f, 0.152f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1905) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1905) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 1.0f};\n   float A[] = { -0.365f, -0.662f, 0.188f, -0.571f, 0.082f, 0.192f, -0.833f, -0.958f, 0.159f, -0.203f, 0.481f, 0.08f, -0.954f, 0.681f, -0.015f, 0.146f, -0.352f, -0.068f };\n   int lda = 3;\n   float B[] = { 0.779f, -0.691f, -0.516f, 0.148f, 0.721f, 0.217f, -0.976f, -0.963f, 0.532f, -0.366f, 0.176f, 0.4f };\n   int ldb = 2;\n   float B_expected[] = { -1.34375f, 0.302916f, 0.692272f, 0.158126f, -2.93098f, -5.71682f, 3.87247f, 3.8052f, 3.25028f, -6.53201f, -2.34332f, 2.30748f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1906) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1906) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 1.0f};\n   float A[] = { 0.779f, 0.065f, -0.616f, -0.245f, 0.823f, 0.689f, 0.06f, -0.164f, 0.768f, -0.727f, 0.897f, -0.556f, -0.875f, 0.862f, 0.863f, -0.085f, 0.171f, 0.063f };\n   int lda = 3;\n   float B[] = { -0.621f, 0.428f, 0.096f, 0.711f, 0.416f, -0.684f, 0.806f, 0.491f, 0.037f, -0.776f, -0.312f, 0.391f };\n   int ldb = 2;\n   float B_expected[] = { -0.428f, -0.621f, -0.711f, 0.096f, 0.811524f, 0.383068f, -0.464084f, 0.683636f, -0.866708f, -0.399047f, -0.587978f, -0.244543f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1907) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1907) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 1.0f};\n   float A[] = { -0.349f, 0.224f, -0.323f, 0.457f, 0.081f, 0.443f, 0.809f, 0.037f, -0.543f, 0.554f, 0.779f, 0.632f, -0.852f, -0.148f, -0.649f, -0.78f, 0.469f, -0.515f };\n   int lda = 3;\n   float B[] = { 0.162f, 0.754f, -0.978f, -0.097f, 0.986f, 0.943f, 0.676f, 0.718f, 0.204f, 0.264f, -0.124f, -0.73f };\n   int ldb = 2;\n   float B_expected[] = { 0.0811068f, 1.92921f, -3.74716f, 1.18561f, 1.80842f, -0.638944f, 0.528341f, 1.20828f, -0.471728f, -0.083028f, 0.837267f, 0.654994f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1908) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1908) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 1.0f};\n   float A[] = { -0.469f, -0.164f, -0.792f, -0.454f, 0.206f, 0.785f, 0.504f, -0.561f, 0.205f, 0.463f, -0.8f, 0.803f, 0.283f, 0.131f, 0.576f, -0.431f, 0.297f, -0.415f };\n   int lda = 3;\n   float B[] = { -0.364f, 0.853f, 0.056f, -0.78f, 0.05f, 0.223f, -0.166f, -0.097f, 0.24f, 0.721f, 0.023f, 0.508f };\n   int ldb = 2;\n   float B_expected[] = { -1.3696f, 0.527133f, 0.554099f, 0.524136f, -0.60708f, 0.820963f, -0.290931f, 0.260324f, -0.721f, 0.24f, -0.508f, 0.023f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1909) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1909) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {1.0f, 0.0f};\n   float A[] = { 0.917f, 0.367f, -0.115f, -0.321f, -0.811f, -0.563f, 0.78f, -0.742f };\n   int lda = 2;\n   float B[] = { 0.797f, 0.166f, 0.737f, -0.685f, 0.677f, -0.04f, -0.652f, 0.327f, 0.094f, -0.656f, 0.496f, -0.646f };\n   int ldb = 3;\n   float B_expected[] = { 0.811592f, -0.143789f, 0.435059f, -0.92112f, 0.621302f, -0.292277f, -0.710488f, 0.0561583f, 0.694329f, -0.137285f, 0.752465f, 0.100199f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1910) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1910) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {1.0f, 0.0f};\n   float A[] = { -0.384f, 0.783f, -0.086f, -0.649f, -0.574f, 0.216f, -0.809f, -0.608f };\n   int lda = 2;\n   float B[] = { 0.067f, -0.183f, -0.524f, 0.77f, 0.169f, 0.769f, -0.982f, -0.522f, -0.051f, -0.129f, 0.595f, 0.56f };\n   int ldb = 3;\n   float B_expected[] = { 0.067f, -0.183f, -0.524f, 0.77f, 0.169f, 0.769f, -0.857471f, -0.494255f, -0.595794f, -0.402856f, 0.110453f, 0.735815f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1911) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1911) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {1.0f, 0.0f};\n   float A[] = { 0.228f, -0.644f, 0.731f, 0.458f, 0.051f, -0.725f, 0.731f, 0.537f };\n   int lda = 2;\n   float B[] = { -0.588f, 0.01f, -0.009f, -0.374f, 0.422f, 0.758f, -0.428f, 0.263f, 0.659f, 0.171f, -0.239f, 0.968f };\n   int ldb = 3;\n   float B_expected[] = { -0.232749f, -1.39168f, -0.124158f, 0.287962f, -1.55821f, 0.0298572f, -0.208619f, 0.513035f, 0.697138f, -0.278198f, 0.419466f, 1.01607f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1912) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1912) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {1.0f, 0.0f};\n   float A[] = { -0.321f, 0.761f, 0.809f, -0.017f, -0.009f, -0.975f, 0.057f, 0.396f };\n   int lda = 2;\n   float B[] = { 0.377f, 0.776f, -0.686f, -0.561f, 0.29f, 0.601f, 0.755f, 0.518f, 0.313f, -0.394f, 0.945f, 0.395f };\n   int ldb = 3;\n   float B_expected[] = { -0.121255f, 1.51679f, -0.299033f, -0.259371f, -0.08662f, 1.52593f, 0.755f, 0.518f, 0.313f, -0.394f, 0.945f, 0.395f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1913) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1913) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {1.0f, 0.0f};\n   float A[] = { 0.186f, 0.818f, -0.142f, -0.376f, 0.332f, 0.746f, 0.413f, -0.151f };\n   int lda = 2;\n   float B[] = { -0.374f, -0.787f, 0.221f, -0.104f, 0.74f, -0.548f, 0.88f, -0.66f, 0.65f, 0.046f, -0.839f, -0.783f };\n   int ldb = 2;\n   float B_expected[] = { -1.01366f, 0.226724f, 1.10152f, 1.79962f, -0.441403f, -1.00501f, 0.588898f, 0.222456f, 0.225271f, -0.743398f, -2.5862f, -2.65075f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1914) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1914) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {1.0f, 0.0f};\n   float A[] = { -0.574f, 0.018f, -0.584f, -0.184f, 0.41f, 0.075f, 0.92f, 0.022f };\n   int lda = 2;\n   float B[] = { 0.524f, -0.234f, 0.198f, 0.079f, -0.449f, -0.433f, -0.14f, -0.201f, -0.242f, -0.368f, -0.298f, 0.693f };\n   int ldb = 2;\n   float B_expected[] = { 0.524f, -0.234f, -0.03439f, 0.13564f, -0.449f, -0.433f, 0.011615f, 0.010205f, -0.242f, -0.368f, -0.22638f, 0.86203f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1915) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1915) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {1.0f, 0.0f};\n   float A[] = { 0.422f, -0.38f, 0.919f, -0.229f, -0.849f, -0.19f, 0.02f, -0.181f };\n   int lda = 2;\n   float B[] = { 0.971f, -0.339f, 0.203f, 0.083f, 0.461f, -0.623f, 0.334f, 0.653f, 0.694f, 0.42f, 0.239f, -0.061f };\n   int ldb = 2;\n   float B_expected[] = { 3.06394f, -0.745692f, -0.330599f, 1.15808f, 8.0252f, -0.902398f, -3.36278f, 2.21688f, 0.70369f, -0.872941f, 0.477097f, 1.26772f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1916) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1916) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {1.0f, 0.0f};\n   float A[] = { 0.564f, 0.483f, -0.635f, 0.84f, 0.238f, 0.35f, 0.96f, 0.397f };\n   int lda = 2;\n   float B[] = { 0.963f, -0.513f, 0.989f, 0.404f, -0.352f, 0.924f, 0.052f, -0.059f, -0.771f, 0.341f, -0.566f, -0.844f };\n   int ldb = 2;\n   float B_expected[] = { 1.93037f, -1.08722f, 0.989f, 0.404f, -0.36854f, 0.842855f, 0.052f, -0.059f, -1.83937f, 0.2805f, -0.566f, -0.844f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1917) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1917) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {1.0f, 0.0f};\n   float A[] = { 0.182f, 0.699f, 0.303f, -0.273f, -0.363f, 0.02f, 0.991f, -0.206f, -0.347f, 0.269f, -0.384f, 0.797f, 0.392f, -0.966f, 0.347f, 0.87f, 0.016f, -0.097f };\n   int lda = 3;\n   float B[] = { 0.587f, 0.875f, -0.848f, 0.154f, -0.887f, -0.709f, 0.824f, -0.895f, 0.159f, 0.933f, -0.011f, -0.393f };\n   int ldb = 3;\n   float B_expected[] = { -14.9753f, 2.31554f, 0.613295f, 24.1527f, 5.64728f, -10.0758f, -3.79783f, -5.34545f, -5.38045f, 2.99977f, 3.92602f, -0.760993f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1918) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1918) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {1.0f, 0.0f};\n   float A[] = { 0.637f, -0.57f, 0.322f, -0.303f, 0.618f, 0.261f, 0.654f, -0.238f, 0.66f, -0.485f, 0.223f, -0.196f, -0.252f, 0.929f, -0.012f, 0.965f, 0.783f, 0.489f };\n   int lda = 3;\n   float B[] = { 0.894f, 0.93f, 0.648f, 0.914f, 0.7f, -0.138f, 0.63f, -0.173f, -0.671f, -0.327f, -0.922f, 0.816f };\n   int ldb = 3;\n   float B_expected[] = { -0.0695574f, 0.64143f, 0.518948f, 1.08197f, 0.7f, -0.138f, 1.8231f, -0.404044f, -0.62533f, -0.68968f, -0.922f, 0.816f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1919) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1919) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {1.0f, 0.0f};\n   float A[] = { 0.274f, 0.721f, -0.445f, 0.14f, 0.023f, -0.945f, 0.859f, -0.522f, -0.227f, 0.722f, 0.165f, 0.969f, -0.212f, -0.816f, 0.908f, -0.652f, -0.208f, -0.229f };\n   int lda = 3;\n   float B[] = { 0.011f, -0.818f, 0.067f, -0.191f, -0.911f, 0.84f, -0.162f, -0.951f, -0.502f, -0.21f, 0.492f, 0.767f };\n   int ldb = 3;\n   float B_expected[] = { -0.986296f, -0.390076f, -0.910328f, -1.26205f, -3.05033f, 0.930902f, -1.22716f, -0.241667f, -1.07925f, -0.600129f, -2.84941f, 5.27338f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1920) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1920) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {1.0f, 0.0f};\n   float A[] = { -0.186f, 0.118f, -0.545f, 0.784f, 0.057f, 0.39f, 0.77f, -0.518f, -0.97f, 0.271f, 0.488f, 0.637f, -0.482f, -0.993f, -0.797f, -0.945f, 0.257f, 0.3f };\n   int lda = 3;\n   float B[] = { -0.783f, 0.649f, 0.698f, 0.046f, -0.153f, 0.473f, -0.996f, -0.211f, 0.84f, 0.201f, -0.457f, 0.918f };\n   int ldb = 3;\n   float B_expected[] = { -0.783f, 0.649f, 0.964728f, -0.859324f, 0.406086f, 0.235086f, -0.996f, -0.211f, 1.71622f, -0.152458f, 0.78435f, 1.32759f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1921) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1921) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {1.0f, 0.0f};\n   float A[] = { -0.681f, -0.342f, -0.195f, -0.053f, 0.016f, -0.191f, 0.989f, -0.718f, -0.59f, 0.646f, -0.41f, -0.809f, -0.359f, -0.783f, -0.902f, 0.917f, -0.703f, 0.795f };\n   int lda = 3;\n   float B[] = { -0.27f, 0.037f, 0.349f, 0.36f, -0.293f, 0.128f, -0.481f, -0.834f, -0.815f, -0.6f, 0.728f, 0.122f };\n   int ldb = 2;\n   float B_expected[] = { -0.69977f, -2.39368f, 2.17354f, 1.74016f, 0.260417f, -1.25151f, 0.175881f, 1.93577f, 0.085191f, 0.949825f, -0.368302f, -0.590043f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1922) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1922) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {1.0f, 0.0f};\n   float A[] = { -0.132f, 0.33f, 0.357f, 0.32f, 0.833f, -0.111f, -0.192f, -0.643f, -0.622f, -0.663f, -0.58f, 0.423f, -0.874f, 0.86f, -0.281f, -0.992f, 0.055f, 0.137f };\n   int lda = 3;\n   float B[] = { 0.104f, -0.906f, -0.712f, 0.103f, -0.474f, -0.591f, 0.073f, -0.906f, -0.261f, -0.391f, 0.881f, -0.345f };\n   int ldb = 2;\n   float B_expected[] = { 0.126148f, -1.31009f, -0.0285057f, -0.554776f, -0.159469f, -0.959783f, 0.662801f, -0.128993f, -0.261f, -0.391f, 0.881f, -0.345f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1923) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1923) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {1.0f, 0.0f};\n   float A[] = { -0.353f, -0.581f, -0.648f, 0.894f, 0.825f, -0.23f, -0.529f, 0.213f, 0.568f, 0.296f, 0.372f, 0.442f, 0.515f, -0.409f, 0.222f, -0.246f, -0.524f, 0.318f };\n   int lda = 3;\n   float B[] = { -0.467f, 0.632f, 0.672f, 0.777f, -0.609f, 0.511f, -0.991f, 0.311f, -0.617f, -0.732f, -0.585f, 0.152f };\n   int ldb = 2;\n   float B_expected[] = { -0.437806f, -1.06979f, -1.49004f, 0.251317f, -2.40924f, 1.62379f, -1.09482f, 3.75003f, -1.80514f, -2.07012f, -4.8059f, -0.418185f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1924) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1924) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {1.0f, 0.0f};\n   float A[] = { -0.201f, -0.918f, -0.514f, -0.889f, -0.948f, 0.34f, 0.818f, 0.557f, 0.341f, 0.484f, 0.235f, 0.561f, 0.874f, -0.342f, -0.411f, -0.975f, -0.85f, -0.621f };\n   int lda = 3;\n   float B[] = { -0.389f, -0.252f, 0.322f, -0.763f, -0.839f, -0.744f, -0.946f, -0.312f, 0.051f, -0.686f, -0.626f, -0.043f };\n   int ldb = 2;\n   float B_expected[] = { -0.389f, -0.252f, 0.322f, -0.763f, -0.814918f, -1.21935f, -0.102185f, -0.417924f, -0.896001f, -0.04892f, -0.790606f, -0.720266f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1925) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1925) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int trans = 113;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {-0.3f, 0.1f};\n   float A[] = { 0.571f, 0.12f, 0.665f, 0.425f, -0.977f, -0.772f, -0.944f, -0.154f };\n   int lda = 2;\n   float B[] = { -0.357f, -0.213f, 0.57f, 0.134f, 0.089f, 0.046f, 0.027f, 0.825f, -0.127f, 0.658f, -0.332f, 0.247f };\n   int ldb = 3;\n   float B_expected[] = { 0.205417f, 0.092557f, -0.315204f, -0.0368205f, -0.0507703f, -0.0192512f, 0.238158f, 0.270895f, -0.257649f, 0.296502f, -0.140106f, 0.100105f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1926) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1926) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int trans = 113;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {-0.3f, 0.1f};\n   float A[] = { 0.051f, 0.966f, 0.04f, -0.765f, 0.276f, -0.798f, 0.766f, -0.37f };\n   int lda = 2;\n   float B[] = { 0.532f, 0.59f, 0.305f, 0.443f, 0.036f, 0.655f, -0.145f, -0.864f, -0.483f, -0.45f, -0.327f, -0.365f };\n   int ldb = 3;\n   float B_expected[] = { -0.2186f, -0.1238f, -0.1358f, -0.1024f, -0.0763f, -0.1929f, 0.043937f, 0.416881f, 0.116996f, 0.194683f, -0.0099165f, 0.142885f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1927) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1927) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int trans = 113;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {-0.3f, 0.1f};\n   float A[] = { -0.163f, -0.238f, -0.032f, 0.494f, 0.863f, 0.96f, 0.669f, 0.415f };\n   int lda = 2;\n   float B[] = { -0.724f, -0.682f, 0.034f, 0.352f, 0.42f, 0.253f, 0.186f, -0.061f, 0.278f, -0.764f, -0.484f, 0.051f };\n   int ldb = 3;\n   float B_expected[] = { -0.532386f, -1.09223f, -1.1606f, 1.43429f, 1.04476f, 0.724237f, -0.0783541f, 0.00655162f, -0.179639f, 0.27272f, 0.193877f, 0.0250509f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1928) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1928) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int trans = 113;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {-0.3f, 0.1f};\n   float A[] = { 0.533f, 0.575f, 0.808f, -0.631f, 0.185f, 0.296f, -0.757f, -0.279f };\n   int lda = 2;\n   float B[] = { -0.744f, -0.881f, -0.594f, 0.629f, -0.924f, 0.017f, -0.089f, -0.052f, 0.959f, -0.486f, 0.39f, -0.378f };\n   int ldb = 3;\n   float B_expected[] = { 0.303415f, 0.198103f, 0.0879903f, -0.363588f, 0.245042f, -0.149137f, 0.0319f, 0.0067f, -0.2391f, 0.2417f, -0.0792f, 0.1524f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1929) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1929) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int trans = 113;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {-0.3f, 0.1f};\n   float A[] = { -0.001f, -0.948f, -0.97f, -0.285f, -0.664f, -0.977f, -0.746f, 0.192f };\n   int lda = 2;\n   float B[] = { 0.997f, -0.852f, 0.87f, -0.955f, 0.007f, -0.071f, -0.263f, -0.077f, -0.856f, 0.228f, -0.81f, 0.476f };\n   int ldb = 2;\n   float B_expected[] = { 0.375027f, 0.225237f, -0.432345f, -0.0987217f, 0.0232012f, -0.00529874f, -0.112225f, 0.0682749f, -0.162707f, -0.246664f, 0.267117f, 0.237712f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1930) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1930) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int trans = 113;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {-0.3f, 0.1f};\n   float A[] = { 0.804f, 0.476f, -0.898f, -0.966f, 0.51f, -0.346f, 0.622f, -0.749f };\n   int lda = 2;\n   float B[] = { -0.964f, 0.453f, 0.799f, -0.949f, -0.055f, 0.803f, 0.99f, -0.162f, 0.913f, -0.081f, -0.057f, 0.014f };\n   int ldb = 2;\n   float B_expected[] = { 0.2439f, -0.2323f, -0.349565f, 0.398684f, -0.0638f, -0.2464f, -0.333516f, 0.295339f, -0.2658f, 0.1156f, 0.191256f, 0.0231108f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1931) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1931) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int trans = 113;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {-0.3f, 0.1f};\n   float A[] = { -0.144f, -0.611f, -0.054f, 0.618f, 0.213f, 0.49f, -0.465f, -0.488f };\n   int lda = 2;\n   float B[] = { -0.225f, -0.663f, 0.073f, -0.379f, -0.297f, 0.822f, -0.038f, -0.935f, -0.81f, 0.885f, -0.065f, 0.412f };\n   int ldb = 2;\n   float B_expected[] = { 0.287563f, -0.439427f, 0.113582f, -0.141015f, -0.375321f, -0.339988f, 0.189826f, -0.395838f, -0.655583f, 0.0702722f, -0.117522f, 0.15645f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1932) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1932) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int trans = 113;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {-0.3f, 0.1f};\n   float A[] = { -0.367f, 0.502f, -0.309f, 0.404f, 0.531f, -0.188f, 0.181f, 0.583f };\n   int lda = 2;\n   float B[] = { 0.861f, -0.648f, 0.906f, -0.402f, 0.455f, 0.412f, 0.34f, -0.248f, 0.107f, 0.507f, 0.088f, -0.593f };\n   int ldb = 2;\n   float B_expected[] = { -0.350389f, 0.252194f, -0.2316f, 0.2112f, -0.245348f, -0.0757932f, -0.0772f, 0.1084f, -0.148061f, -0.0704181f, 0.0329f, 0.1867f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1933) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1933) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int trans = 113;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {-0.3f, 0.1f};\n   float A[] = { -0.476f, 0.202f, -0.66f, 0.774f, -0.943f, -0.99f, -0.035f, 0.901f, -0.742f, -0.085f, -0.335f, -0.591f, 0.799f, 0.515f, 0.753f, 0.76f, -0.042f, -0.011f };\n   int lda = 3;\n   float B[] = { 0.025f, -0.976f, -0.44f, 0.741f, -0.126f, 0.527f, 0.743f, 0.216f, 0.661f, -0.071f, 0.564f, -0.093f };\n   int ldb = 3;\n   float B_expected[] = { -6.73789f, 0.501263f, -2.62173f, -2.22684f, -0.664138f, 3.89034f, 4.11106f, 5.79368f, -1.20958f, 3.39994f, 4.05469f, -0.945199f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1934) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1934) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int trans = 113;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {-0.3f, 0.1f};\n   float A[] = { -0.999f, 0.418f, 0.687f, 0.6f, 0.106f, -0.737f, -0.165f, 0.263f, 0.998f, -0.092f, 0.555f, -0.671f, -0.162f, -0.814f, 0.317f, 0.582f, 0.302f, -0.48f };\n   int lda = 3;\n   float B[] = { 0.699f, 0.128f, 0.296f, -0.021f, 0.654f, 0.14f, 0.008f, 0.94f, -0.963f, 0.333f, -0.481f, -0.917f };\n   int ldb = 3;\n   float B_expected[] = { -0.312717f, 0.0986958f, 0.0456624f, 0.163957f, -0.2102f, 0.0234f, 0.143952f, 0.0170999f, 0.276937f, -0.480541f, 0.236f, 0.227f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1935) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1935) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int trans = 113;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {-0.3f, 0.1f};\n   float A[] = { -0.932f, 0.532f, -0.763f, -0.029f, -0.524f, -0.938f, 0.007f, -0.445f, -0.659f, 0.709f, -0.581f, 0.825f, -0.904f, -0.453f, 0.119f, 0.964f, -0.649f, 0.48f };\n   int lda = 3;\n   float B[] = { -0.571f, 0.138f, 0.038f, -0.175f, 0.737f, 0.567f, -0.569f, 0.062f, 0.522f, -0.625f, 0.156f, 0.799f };\n   int ldb = 3;\n   float B_expected[] = { -0.0819591f, 0.15247f, -0.121808f, -0.00810757f, 0.287388f, -0.154159f, -0.0982488f, 0.13709f, -0.190946f, -0.223188f, 0.0729118f, 0.274542f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1936) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1936) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int trans = 113;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {-0.3f, 0.1f};\n   float A[] = { 0.527f, 0.272f, 0.431f, 0.642f, -0.239f, -0.254f, -0.231f, 0.766f, 0.85f, -0.09f, 0.679f, -0.898f, 0.192f, -0.651f, -0.869f, 0.859f, 0.68f, 0.03f };\n   int lda = 3;\n   float B[] = { 0.867f, 0.816f, -0.643f, 0.509f, -0.594f, -0.833f, -0.174f, 0.51f, 0.676f, 0.115f, 0.261f, -0.409f };\n   int ldb = 3;\n   float B_expected[] = { -0.3417f, -0.1581f, 0.184172f, -0.515263f, 0.82684f, 0.153742f, 0.0012f, -0.1704f, -0.0834964f, -0.0053432f, -0.216529f, 0.104369f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1937) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1937) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int trans = 113;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {-0.3f, 0.1f};\n   float A[] = { 0.606f, -0.757f, 0.503f, -0.649f, -0.269f, -0.484f, 0.626f, -0.107f, -0.867f, -0.047f, -0.779f, 0.675f, 0.249f, 0.645f, -0.755f, 0.242f, 0.941f, 0.189f };\n   int lda = 3;\n   float B[] = { -0.402f, 0.252f, -0.214f, 0.745f, 0.342f, -0.98f, -0.096f, 0.38f, -0.543f, 0.605f, 0.63f, -0.059f };\n   int ldb = 2;\n   float B_expected[] = { 0.349049f, -0.0955741f, -0.472341f, -0.259287f, -0.176304f, -0.239347f, 0.191174f, 0.170679f, 0.152979f, -0.219859f, -0.203592f, 0.0448683f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1938) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1938) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int trans = 113;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {-0.3f, 0.1f};\n   float A[] = { -0.797f, -0.288f, 0.943f, -0.821f, -0.565f, 0.73f, -0.146f, -0.967f, 0.473f, -0.095f, 0.877f, 0.178f, -0.159f, 0.021f, -0.988f, 0.296f, 0.279f, -0.513f };\n   int lda = 3;\n   float B[] = { -0.455f, 0.859f, -0.21f, 0.702f, -0.591f, -0.235f, 0.519f, 0.279f, -0.444f, 0.816f, -0.507f, 0.893f };\n   int ldb = 2;\n   float B_expected[] = { -0.136371f, -0.712172f, -0.311667f, -0.302476f, 0.337384f, -0.259056f, -0.027248f, -0.327988f, 0.0516f, -0.2892f, 0.0628f, -0.3186f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1939) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1939) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int trans = 113;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {-0.3f, 0.1f};\n   float A[] = { 0.791f, 0.19f, -0.549f, 0.994f, -0.822f, 0.679f, -0.586f, 0.042f, -0.159f, -0.86f, 0.065f, 0.943f, -0.545f, 0.403f, 0.199f, 0.76f, 0.159f, 0.715f };\n   int lda = 3;\n   float B[] = { -0.336f, 0.317f, 0.502f, 0.543f, 0.027f, 0.802f, 0.391f, 0.716f, -0.154f, 0.436f, 0.738f, -0.029f };\n   int ldb = 2;\n   float B_expected[] = { 0.119543f, -0.133991f, -0.212552f, -0.193533f, -0.239565f, -0.0842153f, -0.531028f, 0.229828f, 0.61223f, 0.265016f, 0.850081f, -0.810046f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1940) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1940) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int trans = 113;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {-0.3f, 0.1f};\n   float A[] = { -0.182f, -0.821f, -0.756f, -0.479f, -0.191f, -0.989f, -0.466f, 0.018f, 0.85f, 0.516f, -0.826f, 0.209f, -0.321f, -0.988f, -0.936f, -0.745f, -0.57f, -0.362f };\n   int lda = 3;\n   float B[] = { -0.501f, 0.915f, -0.928f, 0.722f, -0.542f, -0.828f, -0.875f, -0.981f, 0.425f, 0.347f, -0.929f, -0.596f };\n   int ldb = 2;\n   float B_expected[] = { 0.0588f, -0.3246f, 0.2062f, -0.3094f, 0.134369f, -0.0793628f, 0.368285f, -0.125876f, -0.344423f, -0.219222f, 0.402199f, -0.204129f };\n   cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrsm(case 1941) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrsm(case 1941) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {0, 0};\n   double A[] = { 0.976, -0.41, -0.313, -0.779, -0.164, 0.571, 0.056, -0.526 };\n   int lda = 2;\n   double B[] = { -0.177, 0.837, 0.391, -0.853, -0.633, 0.693, -0.392, -0.356, -0.708, 0.926, -0.093, -0.337 };\n   int ldb = 3;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1942) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1942) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {0, 0};\n   double A[] = { -0.383, 0.141, 0.889, -0.007, -0.148, -0.068, 0.481, 0.675 };\n   int lda = 2;\n   double B[] = { 0.469, 0.735, -0.47, -0.164, 0.994, -0.483, -0.354, 0.357, 0.51, 0.523, 0.934, -0.592 };\n   int ldb = 3;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1943) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1943) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {0, 0};\n   double A[] = { -0.089, -0.391, -0.317, -0.349, 0.618, -0.541, -0.84, 0.31 };\n   int lda = 2;\n   double B[] = { 0.931, -0.257, -0.048, 0.633, -0.32, -0.576, -0.682, 0.953, -0.412, 0.408, -0.809, 0.092 };\n   int ldb = 3;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1944) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1944) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {0, 0};\n   double A[] = { 0.599, -0.01, -0.045, 0.567, 0.827, -0.969, -0.729, 0.538 };\n   int lda = 2;\n   double B[] = { 0.971, -0.626, -0.77, -0.882, 0.434, 0.269, -0.456, 0.497, 0.289, 0.957, 0.447, -0.921 };\n   int ldb = 3;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1945) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1945) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {0, 0};\n   double A[] = { 0.441, -0.501, 0.607, -0.4, -0.976, -0.523, -0.136, -0.492 };\n   int lda = 2;\n   double B[] = { 0.639, 0.872, -0.436, 0.518, 0.164, -0.04, 0.489, 0.201, 0.723, -0.958, 0.934, -0.549 };\n   int ldb = 2;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1946) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1946) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {0, 0};\n   double A[] = { -0.603, -0.475, 0.598, -0.666, -0.733, 0.04, 0.491, -0.592 };\n   int lda = 2;\n   double B[] = { 0.71, -0.827, 0.947, -0.364, 0.235, 0.294, 0.298, -0.401, -0.193, -0.008, 0.122, -0.47 };\n   int ldb = 2;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1947) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1947) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {0, 0};\n   double A[] = { -0.73, -0.823, 0.636, -0.965, 0.886, -0.236, 0.501, -0.301 };\n   int lda = 2;\n   double B[] = { 0.259, 0.701, -0.033, 0.616, -0.646, -0.177, -0.886, 0.589, -0.736, -0.303, -0.995, 0.982 };\n   int ldb = 2;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1948) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1948) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {0, 0};\n   double A[] = { 0.829, -0.889, 0.382, 0.083, 0.006, -0.76, -0.338, -0.601 };\n   int lda = 2;\n   double B[] = { 0.006, 0.381, 0.241, 0.096, -0.672, 0.664, 0.952, -0.376, -0.803, 0.344, -0.09, -0.175 };\n   int ldb = 2;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1949) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1949) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {0, 0};\n   double A[] = { 0.879, -0.511, -0.814, -0.94, 0.91, 0.761, 0.223, 0.03, -0.689, -0.739, -0.814, 0.463, 0.389, 0.615, -0.175, 0.129, -0.904, 0.102 };\n   int lda = 3;\n   double B[] = { 0.383, 0.328, 0.589, -0.29, 0.912, 0.327, 0.629, 0.883, -0.578, -0.708, 0.168, -0.982 };\n   int ldb = 3;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1950) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1950) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {0, 0};\n   double A[] = { -0.91, -0.182, 0.333, 0.193, 0.14, 0.538, 0.161, -0.034, -0.614, -0.154, 0.881, 0.842, 0.183, -0.229, 0.099, 0.062, -0.121, 0.179 };\n   int lda = 3;\n   double B[] = { -0.138, 0.109, -0.87, -0.161, 0.917, 0.443, 0.798, 0.677, -0.574, 0.327, -0.626, 0.446 };\n   int ldb = 3;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1951) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1951) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {0, 0};\n   double A[] = { -0.491, -0.021, -0.833, 0.921, -0.71, 0.282, 0.638, 0.223, -0.434, 0.921, -0.949, 0.457, -0.665, -0.844, -0.633, -0.874, -0.73, 0.637 };\n   int lda = 3;\n   double B[] = { -0.047, 0.714, 0.678, 0.756, 0.003, 0.359, 0.507, -0.197, -0.726, 0.873, -0.118, -0.996 };\n   int ldb = 3;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1952) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1952) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {0, 0};\n   double A[] = { 0.372, 0.354, -0.537, 0.948, -0.348, 0.808, 0.573, -0.797, 0.818, 0.701, -0.749, -0.801, -0.959, -0.781, 0.727, -0.189, 0.244, 0.414 };\n   int lda = 3;\n   double B[] = { 0.852, -0.714, 0.455, 0.171, -0.128, 0.554, 0.342, -0.203, 0.669, 0.619, -0.76, 0.759 };\n   int ldb = 3;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1953) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1953) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {0, 0};\n   double A[] = { 0.1, -0.975, 0.885, -0.608, -0.303, 0.87, -0.763, 0.409, 0.501, 0.522, -0.176, 0.679, -0.681, -0.815, -0.878, 0.86, 0.348, -0.65 };\n   int lda = 3;\n   double B[] = { -0.245, 0.954, -0.465, -0.931, 0.327, 0.288, -0.067, 0.252, 0.124, -0.073, -0.731, 0.176 };\n   int ldb = 2;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1954) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1954) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {0, 0};\n   double A[] = { 0.572, 0.045, -0.465, 0.113, 0.996, -0.597, 0.712, 0.945, 0.053, -0.436, 0.36, 0.035, -0.489, -0.012, 0.23, 0.22, 0.068, -0.586 };\n   int lda = 3;\n   double B[] = { -0.543, -0.809, -0.641, -0.744, 0.507, -0.742, -0.279, -0.835, -0.097, -0.968, 0.984, -0.813 };\n   int ldb = 2;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1955) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1955) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {0, 0};\n   double A[] = { 0.837, 0.576, -0.396, 0.013, -0.567, 0.59, 0.513, 0.824, 0.045, 0.486, 0.386, 0.766, 0.222, 0.042, 0.091, -0.008, 0.43, 0.102 };\n   int lda = 3;\n   double B[] = { 0.16, -0.958, -0.125, 0.833, 0.344, 0.213, 0.2, -0.689, 0.81, 0.415, -0.198, 0.001 };\n   int ldb = 2;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1956) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1956) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {0, 0};\n   double A[] = { -0.351, 0.7, -0.495, 0.448, -0.229, 0.925, -0.269, 0.251, -0.783, -0.223, 0.582, 0.373, -0.095, -0.383, -0.087, -0.043, -0.315, -0.999 };\n   int lda = 3;\n   double B[] = { -0.067, -0.104, 0.92, -0.333, 0.367, 0.995, 0.86, 0.425, 0.12, -0.756, 0.441, -0.214 };\n   int ldb = 2;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1957) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1957) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { 0.572, -0.073, 0.878, -0.688, -0.615, -0.213, -0.643, 0.809 };\n   int lda = 2;\n   double B[] = { -0.973, -0.481, 0.071, -0.71, -0.669, 0.717, -0.09, -0.304, -0.427, 0.625, 0.539, -0.565 };\n   int ldb = 3;\n   double B_expected[] = { 0.574560994608, 0.155494672389, 0.0371747871512, 0.389534544514, 0.283820482207, -0.45678514825, 0.591891359193, 0.214411302729, -0.27258111691, 0.507180331171, 0.645135319443, -0.46315922005 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1958) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1958) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { -0.022, 0.475, 0.444, 0.252, -0.871, 0.867, -0.093, 0.264 };\n   int lda = 2;\n   double B[] = { 0.696, 0.259, 0.494, 0.162, -0.9, 0.143, 0.436, 0.487, -0.733, 0.138, -0.618, 0.572 };\n   int ldb = 3;\n   double B_expected[] = { -0.2347, -0.0081, -0.1644, 0.0008, 0.2557, -0.1329, -0.0773344, -0.0397592, 0.2792952, -0.0736264, -0.0188216, -0.2388288 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1959) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1959) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { 0.918, -0.459, 0.547, 0.887, 0.4, -0.497, 0.49, -0.313 };\n   int lda = 2;\n   double B[] = { 0.028, 0.482, -0.59, -0.533, -0.594, 0.544, -0.717, -0.524, 0.07, -0.839, 0.538, -0.548 };\n   int ldb = 3;\n   double B_expected[] = { -0.258092239243, -0.278373561582, 0.128448307703, -0.0949352940165, 0.35005709854, -0.355276452021, 0.308556833073, 0.371588344391, -0.148348709879, 0.433197660833, -0.356526626221, 0.217565644883 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1960) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1960) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { -0.86, -0.532, -0.396, -0.116, 0.766, -0.818, -0.335, 0.271 };\n   int lda = 2;\n   double B[] = { -0.029, -0.754, -0.566, -0.108, 0.904, -0.038, 0.07, -0.476, -0.48, 0.961, 0.864, -0.593 };\n   int ldb = 3;\n   double B_expected[] = { -0.058812, 0.130312, 0.419002, 0.272588, -0.330474, -0.264172, 0.0266, 0.1498, 0.0479, -0.3363, -0.1999, 0.2643 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1961) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1961) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { -0.043, 0.25, -0.831, 0.609, -0.896, 0.886, 0.653, 0.065 };\n   int lda = 2;\n   double B[] = { 0.548, 0.076, 0.429, 0.873, -0.559, -0.329, -0.326, -0.174, 0.633, 0.489, 0.317, -0.896 };\n   int ldb = 2;\n   double B_expected[] = { 0.239257797324, 0.64684765886, 0.889006221152, 0.139062311692, 0.0322336011438, -0.807944179397, -0.977615509726, -1.02501063893, -0.164440783851, 0.983483814822, 1.28991055447, 1.90436729944 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1962) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1962) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { -0.268, -0.062, -0.017, 0.326, 0.561, -0.203, -0.665, 0.338 };\n   int lda = 2;\n   double B[] = { -0.46, 0.954, 0.823, 0.945, -0.825, 0.882, -0.214, -0.095, -0.935, -0.245, 0.902, 0.904 };\n   int ldb = 2;\n   double B_expected[] = { 0.0426, -0.3322, -0.297862, -0.006188, 0.1593, -0.3471, 0.054794, 0.234161, 0.305, -0.02, -0.528045, -0.107865 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1963) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1963) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { -0.075, 0.178, -0.321, -0.056, -0.124, -0.483, 0.685, -0.052 };\n   int lda = 2;\n   double B[] = { -0.47, -0.363, 0.766, -0.961, -0.391, -0.691, 0.42, -0.339, 0.45, -0.975, 0.991, -0.198 };\n   int ldb = 2;\n   double B_expected[] = { 0.874038948948, -0.779868445448, -0.234271045009, 0.514916650598, 0.810533012472, -1.05664738101, -0.149515922946, 0.198430908039, 2.17245126703, 0.115946317124, -0.420252834642, 0.199484456348 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1964) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1964) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { -0.206, -0.461, -0.681, 0.358, 0.21, -0.318, 0.082, -0.097 };\n   int lda = 2;\n   double B[] = { 0.576, -0.249, 0.718, 0.424, 0.728, -0.464, 0.774, 0.541, -0.112, 0.803, 0.275, -0.638 };\n   int ldb = 2;\n   double B_expected[] = { -0.343295, 0.186865, -0.2578, -0.0554, -0.3973645, 0.2566785, -0.2863, -0.0849, 0.0189315, -0.0963345, -0.0187, 0.2189 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1965) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1965) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { -0.117, 0.983, -0.929, -0.69, -0.144, 0.28, 0.658, 0.304, -0.657, 0.543, -0.051, -0.98, -0.846, -0.484, 0.052, 0.691, 0.613, -0.178 };\n   int lda = 3;\n   double B[] = { -0.688, 0.453, -0.63, 0.067, 0.193, 0.359, -0.792, 0.307, -0.501, -0.616, -0.595, 0.817 };\n   int ldb = 3;\n   double B_expected[] = { -0.566587593051, 0.340892661842, -0.458137993587, -0.0857620879204, -0.102500656517, -0.173972458173, -1.32599192297, -0.284341349955, -0.284178293736, -0.823318590512, 0.278700120014, -0.415972885216 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1966) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1966) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { 0.773, -0.614, 0.782, -0.728, -0.727, -0.715, 0.858, -0.065, 0.922, 0.178, 0.588, 0.215, -0.92, -0.443, -0.583, -0.244, 0.996, -0.539 };\n   int lda = 3;\n   double B[] = { 0.159, 0.669, -0.692, 0.808, -0.146, 0.489, -0.385, -0.646, 0.704, -0.968, 0.551, -0.281 };\n   int ldb = 3;\n   double B_expected[] = { 0.0796383322, -0.0678193334, 0.0951193, -0.2156591, -0.0051, -0.1613, -0.2408434996, -0.0853028168, -0.0037554, 0.3083308, -0.1372, 0.1394 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1967) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1967) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { -0.864, -0.382, -0.715, 0.227, -0.973, -0.709, -0.247, -0.601, 0.467, -0.133, 0.988, 0.937, -0.272, -0.334, 0.719, 0.992, 0.203, -0.646 };\n   int lda = 3;\n   double B[] = { 0.285, -0.409, -0.347, -0.925, -0.616, 0.422, 0.631, -0.954, -0.053, -0.255, -0.749, -0.979 };\n   int ldb = 3;\n   double B_expected[] = { -0.0215414266825, -0.165475896999, 0.469240391843, 0.538308411392, 1.71185240759, 0.063655952267, -0.0586080545035, -0.378370049976, 0.536158413721, 0.02961076215, 0.67769157898, -0.0939027988826 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1968) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1968) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { -0.373, -0.335, -0.106, 0.542, -0.504, 0.574, -0.318, 0.043, -0.801, -0.331, 0.699, 0.776, -0.56, 0.131, 0.742, -0.692, -0.614, -0.874 };\n   int lda = 3;\n   double B[] = { -0.823, 0.929, -0.55, 0.172, -0.44, 0.067, 0.99, -0.013, 0.513, -0.438, -0.591, -0.302 };\n   int ldb = 3;\n   double B_expected[] = { 0.154, -0.361, 0.181249, -0.22802, 0.187552082, 0.008181148, -0.2957, 0.1029, -0.1997079, 0.2281373, 0.0457001502, -0.1796150434 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1969) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1969) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { -0.912, 0.523, 0.314, -0.205, -0.895, 0.033, 0.157, -0.936, -0.582, 0.104, -0.868, 0.851, -0.131, 0.836, 0.993, 0.319, -0.684, -0.035 };\n   int lda = 3;\n   double B[] = { 0.07, -0.556, 0.018, -0.245, -0.405, 0.77, 0.888, 0.01, -0.81, -0.42, 0.66, -0.387 };\n   int ldb = 2;\n   double B_expected[] = { -0.132542904863, 0.151203976135, 0.45996395874, -0.700981460432, -0.771115355304, 0.0234040392321, 1.04091400336, -0.314874142966, -0.418936175202, -0.0443526810935, 0.218699329114, -0.27741882532 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1970) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1970) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { -0.904, 0.983, -0.777, 0.503, 0.061, -0.442, 0.797, 0.415, -0.49, -0.466, 0.386, -0.147, -0.793, -0.381, -0.481, 0.33, 0.69, 0.35 };\n   int lda = 3;\n   double B[] = { 0.152, 0.832, 0.687, -0.287, -0.571, -0.187, -0.456, 0.631, 0.976, 0.833, -0.527, -0.188 };\n   int ldb = 2;\n   double B_expected[] = { -0.3155234788, -0.5211211034, -0.2870272698, 0.3910522396, -0.0411631, 0.0498567, 0.1600099, -0.2914973, -0.3761, -0.1523, 0.1769, 0.0037 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1971) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1971) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { 0.527, 0.434, 0.025, 0.505, 0.724, 0.961, -0.071, 0.675, -0.334, 0.259, 0.167, 0.898, 0.116, 0.723, 0.086, 0.042, -0.483, -0.862 };\n   int lda = 3;\n   double B[] = { -0.874, 0.252, 0.924, 0.251, 0.559, -0.619, -0.131, -0.286, 0.09, -0.111, 0.062, -0.973 };\n   int ldb = 2;\n   double B_expected[] = { 0.116195543731, -0.404988360492, -0.325886265381, 0.300824742268, 0.86553022636, 0.0931927221532, -0.0931167995431, -0.760087414797, 0.774460770553, -0.204189465459, -0.501996021978, -0.354684266966 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1972) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1972) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { 0.383, -0.184, 0.14, 0.131, -0.494, -0.025, -0.396, -0.183, 0.519, 0.806, -0.737, 0.764, -0.03, 0.622, -0.826, 0.605, 0.638, 0.935 };\n   int lda = 3;\n   double B[] = { 0.975, -0.816, -0.996, -0.038, -0.316, -0.31, -0.003, -0.974, 0.364, -0.217, 0.909, -0.656 };\n   int ldb = 2;\n   double B_expected[] = { -0.2109, 0.3423, 0.3026, -0.0882, 0.2001673, 0.0411059, 0.0443818, 0.2646074, -0.0213138923, 0.1426909311, 0.1794588402, 0.4128021586 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1973) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1973) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int trans = 113;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { -0.433, -0.405, -0.008, 0.13, 0.377, -0.664, 0.421, -0.779 };\n   int lda = 2;\n   double B[] = { 0.022, -0.326, -0.905, 0.323, -0.722, 0.282, -0.877, -0.793, -0.906, -0.999, -0.607, -0.979 };\n   int ldb = 3;\n   double B_expected[] = { 0.0831887207906, -0.153137570623, -0.510564586332, -0.0447544052299, -0.412732352054, -0.0239182507667, 0.35364638809, -0.274824473121, 0.341954849059, -0.294570686181, 0.328230337479, -0.181800438645 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1974) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1974) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int trans = 113;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { 0.007, 0.289, 0.434, 0.931, 0.776, -0.861, 0.83, -0.753 };\n   int lda = 2;\n   double B[] = { 0.775, -0.299, -0.45, 0.923, 0.251, 0.934, 0.388, -0.958, -0.732, 0.263, -0.5, 0.097 };\n   int ldb = 3;\n   double B_expected[] = { -0.2026, 0.1672, 0.0427, -0.3219, -0.1687, -0.2551, -0.0883348, 0.0650146, 0.4744571, 0.0273583, 0.4510139, -0.1254463 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1975) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1975) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int trans = 113;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { -0.768, -0.738, 0.236, 0.721, 0.691, -0.963, -0.36, -0.376 };\n   int lda = 2;\n   double B[] = { -0.822, 0.174, 0.799, 0.8, -0.985, -0.169, 0.652, -0.529, -0.51, -0.506, -0.542, -0.786 };\n   int ldb = 3;\n   double B_expected[] = { -0.212429545832, 0.508667487335, 0.591670151369, 0.238559438419, 0.40264717438, -0.154881488703, 0.500259801606, -0.0994508738781, -0.130621162022, -0.416426547, -0.0684577231932, -0.575944733113 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1976) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1976) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int trans = 113;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { -0.294, 0.843, 0.52, 0.53, 0.392, 0.293, 0.209, 0.497 };\n   int lda = 2;\n   double B[] = { 0.765, -0.547, 0.451, -0.581, 0.166, 0.834, -0.541, 0.278, -0.832, 0.66, -0.718, -0.664 };\n   int ldb = 3;\n   double B_expected[] = { -0.1872365, 0.3339085, -0.0667796, 0.3834252, -0.2809938, -0.2009734, 0.1345, -0.1375, 0.1836, -0.2812, 0.2818, 0.1274 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1977) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1977) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int trans = 113;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { 0.642, 0.513, 0.428, 0.273, -0.612, 0.531, -0.664, 0.801 };\n   int lda = 2;\n   double B[] = { 0.429, -0.049, -0.661, 0.36, -0.247, 0.523, -0.227, 0.459, -0.902, 0.328, 0.37, -0.225 };\n   int ldb = 2;\n   double B_expected[] = { -0.161443909893, -0.0392846195877, 0.158306491417, 0.236544282705, 0.158671944063, -0.1560767799, 0.00300493937503, 0.254905467713, 0.369328020399, 0.00134777953987, -0.306971508873, -0.0836654236493 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1978) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1978) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int trans = 113;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { 0.229, -0.461, -0.279, 0.674, -0.797, -0.286, 0.397, 0.329 };\n   int lda = 2;\n   double B[] = { 0.402, 0.728, 0.824, -0.691, -0.362, 0.437, 0.192, 0.788, -0.259, 0.599, 0.79, 0.076 };\n   int ldb = 2;\n   double B_expected[] = { -0.1934, -0.1782, -0.383205, 0.202987, 0.0649, -0.1673, -0.1325225, -0.3690995, 0.0178, -0.2056, -0.289215, -0.112754 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1979) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1979) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int trans = 113;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { -0.942, -0.832, 0.595, -0.092, 0.01, 0.001, 0.944, 0.256 };\n   int lda = 2;\n   double B[] = { 0.73, 0.488, -0.363, -0.01, -0.112, 0.169, -0.268, -0.13, -0.657, 0.573, 0.91, 0.632 };\n   int ldb = 2;\n   double B_expected[] = { 0.158268746344, 0.226988691038, 0.117355164571, -0.00345029435376, -0.0289643723553, 0.0722018494696, 0.0888981803586, 0.0370317099277, -0.233113998714, -0.101765761072, -0.305361921327, -0.187259165106 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1980) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1980) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int trans = 113;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { -0.508, 0.053, -0.516, 0.785, -0.451, -0.53, 0.551, 0.235 };\n   int lda = 2;\n   double B[] = { -0.09, 0.46, 0.948, 0.918, -0.337, 0.012, -0.786, -0.676, 0.906, -0.38, -0.566, 0.645 };\n   int ldb = 2;\n   double B_expected[] = { -0.0713482, -0.5355066, -0.3762, -0.1806, 0.1589574, 0.2649562, 0.3034, 0.1242, 0.0168633, 0.1582089, 0.1053, -0.2501 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1981) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1981) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int trans = 113;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { 0.499, -0.268, 0.234, 0.032, -0.158, 0.684, -0.878, 0.613, 0.968, 0.812, 0.013, 0.34, -0.485, -0.565, 0.316, 0.286, -0.459, 0.637 };\n   int lda = 3;\n   double B[] = { -0.964, 0.804, 0.197, 0.141, 0.942, 0.474, 0.741, -0.441, -0.738, -0.703, -0.27, 0.98 };\n   int ldb = 3;\n   double B_expected[] = { 0.561582612433, -0.70128258354, -0.0253749021391, 0.0631927226609, 0.295313488523, -0.305260767297, -0.0937671252683, 0.884164549696, 0.000683977216651, 0.260184505619, 0.344358828778, 0.221445372699 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1982) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1982) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int trans = 113;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { -0.453, 0.917, 0.131, 0.361, 0.087, 0.441, -0.439, 0.439, 0.777, 0.131, 0.535, 0.646, 0.508, 0.746, -0.347, -0.911, -0.874, -0.525 };\n   int lda = 3;\n   double B[] = { -0.739, -0.776, -0.049, 0.548, -0.39, -0.856, -0.757, 0.307, -0.533, -0.342, 0.431, 0.618 };\n   int ldb = 3;\n   double B_expected[] = { 0.2794424312, 0.1451980676, -0.2891898, -0.1549434, 0.2026, 0.2178, 0.2242026328, -0.0997909546, 0.3882643, 0.0019799, -0.1911, -0.1423 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1983) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1983) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int trans = 113;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { -0.835, -0.775, -0.384, -0.128, -0.41, -0.511, -0.282, -0.341, -0.856, -0.662, 0.721, -0.939, 0.175, -0.899, 0.832, -0.519, 0.652, -0.318 };\n   int lda = 3;\n   double B[] = { -0.654, 0.105, -0.39, 0.645, 0.867, 0.045, -0.842, -0.896, -0.249, 0.419, 0.575, 0.561 };\n   int ldb = 3;\n   double B_expected[] = { -0.177337134492, -0.0485464421929, -0.0947130836909, 0.143712701441, -0.0502556531648, 0.286334558029, -0.109929498786, -0.323108217437, -0.0362323282558, 0.21056630482, -0.514117706819, 0.0792536824901 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1984) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1984) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int trans = 113;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { -0.136, 0.272, 0.676, 0.673, -0.659, 0.668, 0.991, -0.569, -0.489, 0.581, -0.232, -0.249, -0.396, -0.832, 0.763, -0.092, 0.117, 0.108 };\n   int lda = 3;\n   double B[] = { 0.721, -0.141, -0.604, 0.318, 0.387, 0.73, -0.549, 0.302, 0.101, 0.721, -0.064, 0.673 };\n   int ldb = 3;\n   double B_expected[] = { -0.2022, 0.1144, 0.4148738, -0.1541186, -0.5047180206, 0.1126569022, 0.1345, -0.1455, -0.318479, -0.13854, 0.114359797, -0.242815912 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1985) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1985) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int trans = 113;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { -0.578, 0.601, -0.43, -0.187, -0.934, 0.635, 0.157, -0.561, -0.964, 0.025, 0.435, -0.674, -0.575, 0.275, 0.609, 0.228, -0.202, -0.267 };\n   int lda = 3;\n   double B[] = { 0.505, -0.347, 0.213, -0.392, -0.465, -0.918, -0.737, -0.974, -0.051, 0.97, 0.066, 0.604 };\n   int ldb = 2;\n   double B_expected[] = { -0.206165616299, -0.811510964363, -0.328765954464, -0.593889594613, -0.410790365608, 0.365230809488, -0.377900693873, 0.166778025696, -0.558066070138, 0.728199798382, -0.271362172482, 0.505674752215 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1986) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1986) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int trans = 113;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { -0.311, -0.737, -0.738, -0.214, -0.387, -0.043, -0.168, 0.563, 0.165, 0.007, -0.121, 0.408, -0.75, -0.641, -0.997, -0.347, 0.523, -0.922 };\n   int lda = 3;\n   double B[] = { 0.46, 0.376, -0.623, -0.092, 0.233, 0.981, -0.435, -0.493, 0.405, 0.855, -0.391, 0.572 };\n   int ldb = 2;\n   double B_expected[] = { -0.311417159, -0.418726217, 0.2053384662, -0.1587052684, -0.449331, -0.414523, 0.1666068, -0.1265226, -0.207, -0.216, 0.0601, -0.2107 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1987) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1987) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int trans = 113;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { -0.288, -0.421, 0.451, 0.234, 0.67, -0.483, 0.273, 0.131, 0.005, 0.091, -0.706, -0.191, 0.285, -0.434, 0.648, -0.556, -0.886, 0.798 };\n   int lda = 3;\n   double B[] = { 0.359, -0.682, -0.618, 0.479, 0.463, 0.468, -0.43, 0.058, -0.361, -0.058, -0.028, -0.729 };\n   int ldb = 2;\n   double B_expected[] = { 0.432870841901, -0.202296442916, -0.484714722217, 0.00498299287046, -1.27917612947, -3.59551100448, 2.13407463306, 3.62604336509, 2.50059207751, 0.44116664838, -3.08374361183, -0.156015309482 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1988) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1988) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int trans = 113;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { 0.288, 0.961, -0.571, -0.341, -0.443, 0.116, -0.928, 0.157, 0.035, 0.822, 0.733, -0.15, 0.851, -0.634, -0.769, -0.709, 0.346, -0.943 };\n   int lda = 3;\n   double B[] = { -0.708, 0.945, -0.144, 0.505, 0.827, -0.467, 0.883, 0.194, -0.607, -0.332, 0.716, -0.117 };\n   int ldb = 2;\n   double B_expected[] = { 0.1179, -0.3543, -0.0073, -0.1659, -0.2548954, -0.0197092, -0.3450402, -0.0621396, 0.4925104482, -0.0516973464, 0.0565040266, 0.1296638568 };\n   cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrsm(case 1989) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrsm(case 1989) imag\");\n     };\n   };\n  };\n\n\n}\n", "meta": {"hexsha": "e65ba01a0160e211505a1cb6963e7147d4fe5724", "size": 126971, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/cblas/test_trsm.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/cblas/test_trsm.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/cblas/test_trsm.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 32.1608409321, "max_line_length": 232, "alphanum_fraction": 0.528986934, "num_tokens": 60958, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398145016252104, "lm_q2_score": 0.045352584747824255, "lm_q1q2_score": 0.019682180497479405}}
{"text": "/* ndlinear.c\n * \n * Copyright (C) 2006, 2007 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <stdlib.h>\n\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_multifit.h>\n#include <gsl/gsl_blas.h>\n\n#include \"gsl_multifit_ndlinear.h\"\n\nstatic int ndlinear_construct_row(const gsl_vector *d, gsl_vector *x,\n                                  gsl_multifit_ndlinear_workspace *w);\n\n/*\ngsl_multifit_ndlinear_alloc()\n  Allocate a ndlinear workspace\n\nInputs: n_dim  - dimension of fit function\n        N      - number of terms in each sum; N[i] = N_i, 0 <= i < n_dim\n        u      - basis functions to call\n                 u[j] = u^{(j)}, 0 <= j < n_dim\n        params - parameters to pass to basis functions\n\nReturn: pointer to new workspace\n\nNotes: the supplied basis functions 'u[j]' must accept three\n       arguments:\n\nint uj(double x, double y[], void *params)\n\nand fill the y[] vector so that y[i] = u_{i}^{(j)}(x) (the ith\nbasis function for the jth parameter evaluated at x)\n*/\n\ngsl_multifit_ndlinear_workspace *\ngsl_multifit_ndlinear_alloc(size_t n_dim, size_t N[],\n                            int (**u)(double x, double y[], void *p),\n                            void *params)\n{\n  gsl_multifit_ndlinear_workspace *w;\n  size_t n_coeffs; /* total number of fit coefficients */\n  size_t i, idx;\n  size_t sum_N;\n\n  if (n_dim == 0)\n    {\n      GSL_ERROR_NULL(\"n_dim must be at least 1\", GSL_EINVAL);\n    }\n\n  w = calloc(1, sizeof(gsl_multifit_ndlinear_workspace));\n  if (!w)\n    {\n      GSL_ERROR_NULL(\"failed to allocate space for workspace\", GSL_ENOMEM);\n    }\n\n  w->N = calloc(n_dim, sizeof(size_t));\n  if (!w->N)\n    {\n      gsl_multifit_ndlinear_free(w);\n      GSL_ERROR_NULL(\"failed to allocate space for N vector\", GSL_ENOMEM);\n    }\n\n  n_coeffs = 1;\n  sum_N = 0;\n  for (i = 0; i < n_dim; ++i)\n    {\n      if (N[i] == 0)\n        {\n          gsl_multifit_ndlinear_free(w);\n          GSL_ERROR_NULL(\"one of the sums is empty\", GSL_EINVAL);\n        }\n\n      /* The total number of coefficients is: N_1 * N_2 * ... * N_n */\n      n_coeffs *= N[i];\n      w->N[i] = N[i];\n      sum_N += N[i];\n    }\n\n  w->n_dim = n_dim;\n  w->n_coeffs = n_coeffs;\n\n  w->work = gsl_vector_alloc(n_coeffs);\n  w->work2 = gsl_vector_alloc(sum_N);\n  if (!w->work || !w->work2)\n    {\n      gsl_multifit_ndlinear_free(w);\n      GSL_ERROR_NULL(\"failed to allocate space for basis vector\",\n                     GSL_ENOMEM);\n    }\n\n  w->v = calloc(n_dim, sizeof(gsl_vector_view));\n  if (!w->v)\n    {\n      gsl_multifit_ndlinear_free(w);\n      GSL_ERROR_NULL(\"failed to allocate space for basis vector\",\n                     GSL_ENOMEM);\n    }\n\n  w->u = calloc(n_dim, sizeof(int *));\n  if (!w->u)\n    {\n      gsl_multifit_ndlinear_free(w);\n      GSL_ERROR_NULL(\"failed to allocate space for basis functions\",\n                     GSL_ENOMEM);\n    }\n\n  idx = 0;\n  for (i = 0; i < n_dim; ++i)\n    {\n      w->v[i] = gsl_vector_subvector(w->work2, idx, N[i]);\n      idx += N[i];\n\n      w->u[i] = u[i];\n    }\n\n  w->params = params;\n\n  return (w);\n} /* gsl_multifit_ndlinear_alloc() */\n\n/*\ngsl_multifit_ndlinear_free()\n  Free workspace w\n*/\n\nvoid\ngsl_multifit_ndlinear_free(gsl_multifit_ndlinear_workspace *w)\n{\n  if (w->N)\n    free(w->N);\n\n  if (w->work)\n    gsl_vector_free(w->work);\n\n  if (w->work2)\n    gsl_vector_free(w->work2);\n\n  if (w->v)\n    free(w->v);\n\n  if (w->u)\n    free(w->u);\n\n  free(w);\n} /* gsl_multifit_ndlinear_free() */\n\n/*\ngsl_multifit_ndlinear_design()\n  This function constructs the coefficient design matrix 'X'\n\nInputs: vars  - independent variable vectors for matrix X\n                vars is a ndata-by-n_dim matrix where the ith row\n                specifies the n_dim independent variables for the\n                ith observation, so that\n                vars_{ij} = (x_i)_j, the jth element of the\n                ith input variable vector\n        X     - (output) design matrix (must be ndata-by-w->n_coeffs)\n        w     - workspace\n\nReturn: success or error\n*/\n\nint\ngsl_multifit_ndlinear_design(const gsl_matrix *vars, gsl_matrix *X,\n                             gsl_multifit_ndlinear_workspace *w)\n{\n  const size_t ndata = vars->size1;\n\n  if ((X->size1 != ndata) || (X->size2 != w->n_coeffs))\n    {\n      GSL_ERROR(\"X matrix has wrong dimensions\", GSL_EBADLEN);\n    }\n  else\n    {\n      size_t i; /* looping */\n      int s;\n\n      for (i = 0; i < ndata; ++i)\n        {\n          gsl_vector_const_view d = gsl_matrix_const_row(vars, i);\n          gsl_vector_view xv = gsl_matrix_row(X, i);\n\n          s = ndlinear_construct_row(&d.vector, &xv.vector, w);\n          if (s != GSL_SUCCESS)\n            return s;\n        }\n\n      return GSL_SUCCESS;\n    }\n} /* gsl_multifit_ndlinear_design() */\n\n/*\ngsl_multifit_ndlinear_est()\n  Compute the model function at a given data point with errors\n\nInputs: x     - data point (w->n_dim elements)\n        c     - coefficient vector\n        cov   - covariance matrix\n        y     - where to store fit function result\n        y_err - standard deviation of fit\n        w     - workspace\n\nReturn: success or error\n*/\n\nint\ngsl_multifit_ndlinear_est(const gsl_vector *x, const gsl_vector *c,\n                          const gsl_matrix *cov, double *y, double *y_err,\n                          gsl_multifit_ndlinear_workspace *w)\n{\n  if (c->size != w->n_coeffs)\n    {\n      GSL_ERROR(\"c vector has wrong size\", GSL_EBADLEN);\n    }\n  else\n    {\n      int s;\n\n      s = ndlinear_construct_row(x, w->work, w);\n      if (s != GSL_SUCCESS)\n        return s;\n\n      /*\n       * Now w->work contains the appropriate basis functions\n       * evaluated at the given point - compute the function value\n       */\n      s = gsl_multifit_linear_est(w->work, c, cov, y, y_err);\n\n      return s;\n    }\n} /* gsl_multifit_ndlinear_est() */\n\n/*\ngsl_multifit_ndlinear_calc()\n  Compute the model function at a given data point\n\nInputs: x - data point (w->n_dim elements)\n        c - coefficient vector\n        w - workspace\n\nReturn: model value\n*/\n\ndouble\ngsl_multifit_ndlinear_calc(const gsl_vector *x, const gsl_vector *c,\n                           gsl_multifit_ndlinear_workspace *w)\n{\n  if (c->size != w->n_coeffs)\n    {\n      GSL_ERROR_VAL(\"c vector has wrong size\", GSL_EBADLEN, 0.0);\n    }\n  else\n    {\n      double y;\n      int s;\n\n      s = ndlinear_construct_row(x, w->work, w);\n      if (s != GSL_SUCCESS)\n        {\n          GSL_ERROR_VAL(\"constructing matrix row failed\", s, 0.0);\n        }\n\n      gsl_blas_ddot(w->work, c, &y);\n\n      return y;\n    }\n} /* gsl_multifit_ndlinear_calc() */\n\n/*\ngsl_multifit_ndlinear_ncoeffs()\n  Return the total number of fit coefficients\n*/\n\nsize_t\ngsl_multifit_ndlinear_ncoeffs(gsl_multifit_ndlinear_workspace *w)\n{\n  return w->n_coeffs;\n} /* gsl_multifit_ndlinear_ncoeffs() */\n\n/******************************************\n *         INTERNAL ROUTINES              *\n ******************************************/\n\n/*\nndlinear_construct_row()\n\n  Compute a row of the design matrix X:\n\nX(:,j) = u_{r_0}^{(0)}(d_0) * u_{r_1)^{(1)}(d_1) * ... *\n         u_{r_{n-1}}^{(n-1)}(d_{n-1})\n\nwhere 'd' is the corresponding data vector for that row\n\nInputs: d - data vector of length w->n_dim\n        x - (output) where to store row of design matrix X\n        w - workspace\n\nReturn: success or error\n*/\n\nstatic int\nndlinear_construct_row(const gsl_vector *d, gsl_vector *x,\n                       gsl_multifit_ndlinear_workspace *w)\n{\n  size_t j;\n  int k, s;\n  size_t denom, rk;\n  double melement;\n\n  /* compute basis functions for this data point */\n  for (j = 0; j < w->n_dim; ++j)\n    {\n      s = w->u[j](gsl_vector_get(d, j), w->v[j].vector.data, w->params);\n\n      if (s != GSL_SUCCESS)\n        return s;\n    }\n\n  for (j = 0; j < w->n_coeffs; ++j)\n    {\n      /*\n       * The (:,j) element of the matrix X will be:\n       *\n       * X_{:,j} = u_{r_0}^{(0)}(d_0) *\n       *           u_{r_1)^{(1)}(d_1) *\n       *           ... *\n       *           u_{r_{n-1}}^{(n-1)}(d_{n-1})\n       *\n       * with the basis function indices r_k given by\n       *\n       * r_k = floor(j / Prod_{i=(k+1)..(n-1)} [ N_i ]) (mod N_k)\n       *\n       * In the case where N_i = N for all i,\n       *\n       * r_k = floor(j / N^{n - k - 1}) (mod N)\n       *\n       * n: dimension of fit function (w->n_dim)\n       * N_i: number of terms in sum i of fit function\n       */\n\n      /* calculate the r_k and the matrix element X_{:,j} */\n\n      denom = 1;\n      melement = 1.0;\n      for (k = (int)(w->n_dim - 1); k >= 0; --k)\n        {\n          rk = (j / denom) % w->N[k];\n          denom *= w->N[k];\n\n          melement *= gsl_vector_get(&(w->v[k]).vector, rk);\n        }\n\n      /* set the matrix element */\n      gsl_vector_set(x, j, melement);\n    }\n\n  return GSL_SUCCESS;\n} /* ndlinear_construct_row() */\n", "meta": {"hexsha": "82dcaf06878132a0964372d63d1720c47c9dca87", "size": 9487, "ext": "c", "lang": "C", "max_stars_repo_path": "src/BodyComponents/archive/ndlinear-1.0/src/ndlinear.c", "max_stars_repo_name": "rennhak/Keyposes", "max_stars_repo_head_hexsha": "e5ffe4c849b0894f27d58985b41ec8edd3432be1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-11-26T07:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-05T12:45:52.000Z", "max_issues_repo_path": "src/BodyComponents/archive/ndlinear-1.0/src/ndlinear.c", "max_issues_repo_name": "rennhak/Keyposes", "max_issues_repo_head_hexsha": "e5ffe4c849b0894f27d58985b41ec8edd3432be1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/BodyComponents/archive/ndlinear-1.0/src/ndlinear.c", "max_forks_repo_name": "rennhak/Keyposes", "max_forks_repo_head_hexsha": "e5ffe4c849b0894f27d58985b41ec8edd3432be1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0978835979, "max_line_length": 81, "alphanum_fraction": 0.5836407716, "num_tokens": 2673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.03963884321354336, "lm_q1q2_score": 0.01966458552560409}}
{"text": "/*\n *  vbHmmGaussDiffusion.c\n *  Model-specific core functions for VB-HMM-GAUSS-DIFFUSION.\n *\n *  Created by OKAMOTO Kenji, SAKO Yasushi and RIKEN\n *  Copyright 2011-2016\n *  Cellular Informatics Laboratory, Advance Science Institute, RIKEN, Japan.\n *  All rights reserved.\n *\n *  Ver. 1.0.0\n *  Last modified on 2016.02.08\n */\n\n#include \"vbHmmGaussDiffusion.h\"\n#include <gsl/gsl_sf_gamma.h>\n#include <gsl/gsl_sf_psi.h>\n#include <string.h>\n#include \"rand.h\"\n\n#ifdef _OPENMP\n#include \"omp.h\"\n#endif\n\n#define  MAX(a,b)  ((a)>(b)?(a):(b))\n#define  MIN(a,b)  ((a)<(b)?(a):(b))\n\nstatic int isGlobalAnalysis = 0;\n\nvoid setFunctions_gaussDiff(){\n    commonFunctions funcs;\n    funcs.newModelParameters  = newModelParameters_gaussDiff;\n    funcs.freeModelParameters = freeModelParameters_gaussDiff;\n    funcs.newModelStats       = newModelStats_gaussDiff;\n    funcs.freeModelStats      = freeModelStats_gaussDiff;\n    funcs.initializeVbHmm     = initializeVbHmm_gaussDiff;\n    funcs.pTilde_z1           = pTilde_z1_gaussDiff;\n    funcs.pTilde_zn_zn1       = pTilde_zn_zn1_gaussDiff;\n    funcs.pTilde_xn_zn        = pTilde_xn_zn_gaussDiff;\n    funcs.calcStatsVars       = calcStatsVars_gaussDiff;\n    funcs.maximization        = maximization_gaussDiff;\n    funcs.varLowerBound       = varLowerBound_gaussDiff;\n    funcs.reorderParameters   = reorderParameters_gaussDiff;\n    funcs.outputResults       = outputResults_gaussDiff;\n    setFunctions( funcs );\n}\n\nvoid setGFunctions_gaussDiff(){\n    gCommonFunctions funcs;\n    funcs.newModelParameters    = newModelParameters_gaussDiff;\n    funcs.freeModelParameters   = freeModelParameters_gaussDiff;\n    funcs.newModelStats         = newModelStats_gaussDiff;\n    funcs.freeModelStats        = freeModelStats_gaussDiff;\n    funcs.newModelStatsG        = newModelStatsG_gaussDiff;\n    funcs.freeModelStatsG       = freeModelStatsG_gaussDiff;\n    funcs.initializeVbHmmG      = initializeVbHmmG_gaussDiff;\n    funcs.pTilde_z1             = pTilde_z1_gaussDiff;\n    funcs.pTilde_zn_zn1         = pTilde_zn_zn1_gaussDiff;\n    funcs.pTilde_xn_zn          = pTilde_xn_zn_gaussDiff;\n    funcs.calcStatsVarsG        = calcStatsVarsG_gaussDiff;\n    funcs.maximizationG         = maximizationG_gaussDiff;\n    funcs.varLowerBoundG        = varLowerBoundG_gaussDiff;\n    funcs.reorderParametersG    = reorderParametersG_gaussDiff;\n    funcs.outputResultsG        = outputResultsG_gaussDiff;\n    setGFunctions( funcs );\n    isGlobalAnalysis = 1;\n}\n\n\nvoid outputResults_gaussDiff( xn, gv, iv, logFP )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\nFILE *logFP;\n{\n    outputGaussDiffResults( xn, gv, iv, logFP );\n}\n\nvoid outputResultsG_gaussDiff( xns, gv, ivs, logFP )\nxnDataBundle *xns;\nglobalVars *gv;\nindVarBundle *ivs;\nFILE *logFP;\n{\n    outputGaussDiffResultsG( xns, gv, ivs, logFP );\n}\n\n\nvoid *newModelParameters_gaussDiff( xn, sNo )\nxnDataSet *xn;\nint sNo;\n{\n    int i;\n    gaussDiffParameters *p = (gaussDiffParameters*)malloc( sizeof(gaussDiffParameters) );\n    \n    p->uPiArr = (double*)malloc( sNo * sizeof(double) );\n    p->sumUPi = 0.0;\n    p->uAMat = (double**)malloc( sNo * sizeof(double*) );\n    for( i = 0 ; i < sNo ; i++ ){\n        p->uAMat[i] = (double*)malloc( sNo * sizeof(double) );\n    }\n    p->sumUAArr = (double*)malloc( sNo * sizeof(double) );\n\n    p->avgPi = (double *)malloc( sNo * sizeof(double) );\n    p->avgLnPi = (double *)malloc( sNo * sizeof(double) );\n    p->avgA = (double **)malloc( sNo * sizeof(double*) );\n    p->avgLnA = (double **)malloc( sNo * sizeof(double*) );\n    for( i = 0 ; i < sNo ; i++ ){\n        p->avgA[i] = (double *)malloc( sNo * sizeof(double) );\n        p->avgLnA[i] = (double *)malloc( sNo * sizeof(double) );\n    }\n    p->avgDlt = (double *)malloc( sNo * sizeof(double) );\n    p->avgLnDlt = (double *)malloc( sNo * sizeof(double) );\n\n    p->uAArr = (double *)malloc( sNo * sizeof(double) );\n    p->uBArr = (double *)malloc( sNo * sizeof(double) );\n    p->aDlt = (double *)malloc( sNo * sizeof(double) );\n    p->bDlt = (double *)malloc( sNo * sizeof(double) );\n\n    return p;\n}\n\nvoid freeModelParameters_gaussDiff( p, xn, sNo )\nvoid **p;\nxnDataSet *xn;\nint sNo;\n{\n    gaussDiffParameters *gp = *p;\n    int i;\n\n    free( gp->uPiArr );\n    for( i = 0 ; i < sNo ; i++ ){\n        free( gp->uAMat[i] );\n    }\n    free( gp->uAMat );\n    free( gp->sumUAArr );\n\n    free( gp->avgPi );\n    free( gp->avgLnPi );\n    for( i = 0 ; i < sNo ; i++ ){\n        free( gp->avgA[i] );\n        free( gp->avgLnA[i] );\n    }\n    free( gp->avgA );\n    free( gp->avgLnA );\n    free( gp->avgDlt );\n    free( gp->avgLnDlt );\n\n    free( gp->uAArr );\n    free( gp->uBArr );\n    free( gp->aDlt );\n    free( gp->bDlt );\n\n    free( *p );\n    *p = NULL;\n}\n\n\nvoid *newModelStats_gaussDiff( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n    if( isGlobalAnalysis == 0 ){\n        int sNo = gv->sNo;\n        gaussDiffStats *s = (gaussDiffStats*)malloc( sizeof(gaussDiffStats) );\n        \n        int i;\n        s->Ni = (double *)malloc( sNo * sizeof(double) );\n        s->Ri = (double *)malloc( sNo * sizeof(double) );\n        s->Nij = (double **)malloc( sNo * sizeof(double*) );\n        for( i = 0 ; i < sNo ; i++ )\n        {   s->Nij[i] = (double *)malloc( sNo * sizeof(double) );   }\n        s->Nii = (double *)malloc( sNo * sizeof(double) );\n\n        return s;\n\n    } else {\n\n        return NULL;\n\n    }\n}\n\nvoid freeModelStats_gaussDiff( s, xn, gv, iv )\nvoid **s;\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n    if( isGlobalAnalysis == 0 ){\n        int sNo = gv->sNo;\n        gaussDiffStats *gs = *s;\n        int i;\n\n        free( gs->Ni );\n        free( gs->Ri );\n        for( i = 0 ; i < sNo ; i++ )\n        {   free( gs->Nij[i] );   }\n        free( gs->Nij );\n        free( gs->Nii );\n\n        free( gs );\n        *s = NULL;\n    }\n}\n\nvoid *newModelStatsG_gaussDiff( xns, gv, ivs)\nxnDataBundle *xns;\nglobalVars *gv;\nindVarBundle *ivs;\n{\n    int sNo = gv->sNo;\n    gaussDiffGlobalStats *gs = (gaussDiffGlobalStats*)malloc( sizeof(gaussDiffGlobalStats) );\n    \n    int i;\n    gs->NiR = (double *)malloc( sNo * sizeof(double) );\n    gs->RiR = (double *)malloc( sNo * sizeof(double) );\n    gs->NijR = (double **)malloc( sNo * sizeof(double*) );\n    for( i = 0 ; i < sNo ; i++ )\n    {   gs->NijR[i] = (double *)malloc( sNo * sizeof(double) );   }\n    gs->NiiR = (double *)malloc( sNo * sizeof(double) );\n    gs->z1iR = (double *)malloc( sNo * sizeof(double) );\n\n    return gs;\n}\n\nvoid freeModelStatsG_gaussDiff( gs, xns, gv, ivs )\nvoid **gs;\nxnDataBundle *xns;\nglobalVars *gv;\nindVarBundle *ivs;\n{\n    int sNo = gv->sNo;\n    gaussDiffGlobalStats *ggs = *gs;\n    int i;\n    free( ggs->NiR );\n    for( i = 0 ; i < sNo ; i++ )\n    {   free( ggs->NijR[i] );   }\n    free( ggs->NijR );\n    free( ggs->NiiR );\n    free( ggs->RiR );\n    free( ggs->z1iR );\n\n    free( *gs );\n    *gs = NULL;\n}\n\n\nvoid initializeVbHmm_gaussDiff( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n    int sNo = gv->sNo;\n    gaussDiffParameters *p = gv->params;\n    int i, j;\n    \n    // hyper parameter for p( pi(i) )\n    p->sumUPi = 0.0;\n    for( i = 0 ; i < sNo ; i++ ){\n        p->uPiArr[i] = 1.0;\n        p->sumUPi += p->uPiArr[i];\n    }\n    \n    // hyper parameter for p( A(i,j) )\n    for( i = 0 ; i < sNo ; i++ ){\n        p->sumUAArr[i] = 0.0;\n        for( j = 0 ; j < sNo ; j++ ){\n            if( j == i ){\n                p->uAMat[i][j] = 5.0;\n            } else {\n                p->uAMat[i][j] = 1.0;\n            }\n            p->sumUAArr[i] += p->uAMat[i][j];\n        }\n    }\n    \n    // hyper parameter for p( delta(k) )\n    for( i = 0 ; i < sNo ; i++ ){\n        p->uAArr[i] = 1.0;\n        p->uBArr[i] = 0.0005;\n    }\n    \n    initialize_indVars_gaussDiff( xn, gv, iv );\n    \n    calcStatsVars_gaussDiff( xn, gv, iv );\n    maximization_gaussDiff( xn, gv, iv );\n}\n\nvoid initializeVbHmmG_gaussDiff( xns, gv, ivs )\nxnDataBundle *xns;\nglobalVars *gv;\nindVarBundle *ivs;\n{\n    int sNo = gv->sNo, rNo = xns->R;\n    gaussDiffParameters *p = gv->params;\n    int i, j, r;\n\n    p->sumUPi = 0.0;\n    for( i = 0 ; i < sNo ; i++ ){\n        p->uPiArr[i] = 1.0;\n        p->sumUPi += p->uPiArr[i];\n    }\n    \n    for( i = 0 ; i < sNo ; i++ ){\n        p->sumUAArr[i] = 0.0;\n        for( j = 0 ; j < sNo ; j++ ){\n            if( j == i ){\n                p->uAMat[i][j] = 5.0;\n            } else {\n                p->uAMat[i][j] = 1.0;\n            }\n            p->sumUAArr[i] += p->uAMat[i][j];\n        }\n    }\n    \n    // hyper parameter for p( delta(k) )\n    for( i = 0 ; i < sNo ; i++ ){\n        p->uAArr[i] = 1.0;\n        p->uBArr[i] = 0.0005;\n    }\n    \n    for( r = 0 ; r < rNo ; r++ ){\n        initialize_indVars_gaussDiff( xns->xn[r], gv, ivs->indVars[r] );\n    }\n    \n    calcStatsVarsG_gaussDiff( xns, gv, ivs );\n    maximizationG_gaussDiff( xns, gv, ivs );\n}\n\n\nvoid initialize_indVars_gaussDiff( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n    size_t dLen = xn->N;\n    int sNo = gv->sNo;\n    double **gmMat = iv->gmMat;\n    \n    int i;\n    size_t n;\n    double sumPar;\n    for( n = 0 ; n < dLen ; n++ ){\n        sumPar = 0.0;\n        for( i = 0 ; i < sNo ; i++ ){\n            gmMat[n][i] = enoise(1.0) + 1.0;\n            sumPar += gmMat[n][i];\n        }\n        for( i = 0 ; i < sNo ; i++ ){\n            gmMat[n][i] /= sumPar;\n        }\n    }\n}\n\n\nxnDataSet *newXnDataSet_gaussDiff( filename )\nconst char *filename;\n{\n    xnDataSet *xn = (xnDataSet*)malloc( sizeof(xnDataSet) );\n    xn->name = (char*)malloc( strlen(filename) + 2 );\n    strncpy( xn->name, filename, strlen(filename)+1 );\n    xn->data = (gaussDiffData*)malloc( sizeof(gaussDiffData) );\n    gaussDiffData *d = (gaussDiffData*)xn->data;\n    d->v = NULL;\n    return xn;\n}\n\nvoid freeXnDataSet_gaussDiff( xn )\nxnDataSet **xn;\n{\n    gaussDiffData *d = (gaussDiffData*)(*xn)->data;\n    free( d->v );\n    free( (*xn)->data );\n    free( (*xn)->name );\n    free( *xn );\n    *xn = NULL;\n}\n\n\ndouble pTilde_z1_gaussDiff( i, params )\nint i;\nvoid *params;\n{\n    gaussDiffParameters *p = (gaussDiffParameters*)params;\n    return exp( p->avgLnPi[i] );\n}\n\ndouble pTilde_zn_zn1_gaussDiff( i, j, params )\nint i, j;\nvoid *params;\n{\n    gaussDiffParameters *p = (gaussDiffParameters*)params;\n    return exp( p->avgLnA[i][j] );\n}\n\ndouble pTilde_xn_zn_gaussDiff( xnWv, n, i, params )\nxnDataSet *xnWv;\nsize_t n;\nint i;\nvoid *params;\n{\n    gaussDiffParameters *p = (gaussDiffParameters*)params;\n    gaussDiffData *xn = (gaussDiffData*)xnWv->data;\n    double val;\n    val  = p->avgLnDlt[i] - log(2.0);\n    val -= log(xn->v[n]) + p->avgDlt[i] * pow( xn->v[n], 2.0) / 4.0;\n    return exp(val);\n}\n\n\nvoid calcStatsVars_gaussDiff( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n    gaussDiffData *d = (gaussDiffData*)xn->data;\n    gaussDiffStats *s = (gaussDiffStats*)iv->stats;\n    size_t dLen = xn->N;\n    int sNo = gv->sNo;\n    double **gmMat = iv->gmMat, ***xiMat = iv->xiMat;\n    double *Ni = s->Ni, *Ri = s->Ri, *Nii = s->Nii, **Nij = s->Nij;\n    size_t n;\n    int i, j;\n\n    for( i = 0 ; i < sNo ; i++ ){\n        Ni[i]   = 1e-10;\n        Ri[i]   = 1e-10;\n        Nii[i]  = 1e-10;\n        for( j = 0 ; j < sNo ; j++ ){\n            Nij[i][j] = 1e-10;\n        }\n        for( n = 0 ; n < dLen ; n++ ){\n            Ni[i] += gmMat[n][i];\n            Ri[i] += gmMat[n][i] * pow( d->v[n], 2.0 );\n            for( j = 0 ; j < sNo ; j++ ){\n                Nii[i]    += xiMat[n][i][j];\n                Nij[i][j] += xiMat[n][i][j];\n            }\n        }\n    }\n}\n\nvoid calcStatsVarsG_gaussDiff( xns, gv, ivs )\nxnDataBundle *xns;\nglobalVars *gv;\nindVarBundle *ivs;\n{\n    gaussDiffData *d;\n    gaussDiffGlobalStats *gs = (gaussDiffGlobalStats*)ivs->stats;\n    int sNo = gv->sNo, rNo = xns->R;\n    double **gmMat, ***xiMat;\n    double *NiR = gs->NiR, *RiR = gs->RiR, *NiiR = gs->NiiR;\n    double **NijR = gs->NijR, *z1iR = gs->z1iR;\n    size_t dLen, n;\n    int i, j, r;\n    \n    for( i = 0 ; i < sNo ; i++ ){\n        NiR[i]   = 1e-10;\n        RiR[i]  = 1e-10;\n        NiiR[i]  = 1e-10;\n        for( j = 0 ; j < sNo ; j++ ){\n            NijR[i][j] = 1e-10;\n        }\n        z1iR[i] = 1e-10;\n    }\n    for( r = 0 ; r < rNo ; r++ ){\n        d = (gaussDiffData*)xns->xn[r]->data;\n        dLen = xns->xn[r]->N;\n        gmMat = ivs->indVars[r]->gmMat;\n        xiMat = ivs->indVars[r]->xiMat;\n        for( i = 0 ; i < sNo ; i++ ){\n            z1iR[i] += gmMat[0][i];\n            for( n = 0 ; n < dLen ; n++ ){\n                NiR[i] += gmMat[n][i];\n                RiR[i] += gmMat[n][i] * pow( d->v[n], 2.0 );\n                for( j = 0 ; j < sNo ; j++ ){\n                    NiiR[i]    += xiMat[n][i][j];\n                    NijR[i][j] += xiMat[n][i][j];\n                }\n            }\n        }\n    }\n}\n\n\nvoid maximization_gaussDiff( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n    gaussDiffParameters *p = (gaussDiffParameters*)gv->params;\n    gaussDiffStats *s = (gaussDiffStats*)iv->stats;\n    int sNo = gv->sNo;\n    double **gmMat = iv->gmMat;\n    double *uPiArr = p->uPiArr, sumUPi = p->sumUPi;\n    double **uAMat = p->uAMat, *sumUAArr = p->sumUAArr;\n    double *uAArr = p->uAArr, *uBArr = p->uBArr, *aDlt = p->aDlt, *bDlt = p->bDlt;\n    double *avgPi = p->avgPi, *avgLnPi = p->avgLnPi, **avgA = p->avgA, **avgLnA = p->avgLnA;\n    double *avgDlt = p->avgDlt, *avgLnDlt = p->avgLnDlt;\n    double *Ni = s->Ni, *Ri = s->Ri, *Nii = s->Nii, **Nij = s->Nij;\n    int i, j;\n\n    for( i = 0 ; i < sNo ; i++ ){\n        avgPi[i] = ( uPiArr[i] + gmMat[0][i] ) / ( sumUPi + 1.0 );\n        avgLnPi[i] = gsl_sf_psi( uPiArr[i] + gmMat[0][i] ) - gsl_sf_psi( sumUPi + 1.0 );\n\n        for( j = 0 ; j < sNo ; j++ ){\n            avgA[i][j] = ( uAMat[i][j] + Nij[i][j] ) / ( sumUAArr[i] + Nii[i] );\n            avgLnA[i][j] = gsl_sf_psi( uAMat[i][j] + Nij[i][j] ) - gsl_sf_psi( sumUAArr[i] + Nii[i] );\n        }\n\n        aDlt[i] = uAArr[i] + Ni[i];\n        bDlt[i] = uBArr[i] + Ri[i] / 4.0;\n\n        avgDlt[i]   = aDlt[i] / bDlt[i];\n        avgLnDlt[i] = gsl_sf_psi( aDlt[i] ) - log( bDlt[i] );\n    }\n}\n\nvoid maximizationG_gaussDiff( xns, gv, ivs )\nxnDataBundle *xns;\nglobalVars *gv;\nindVarBundle *ivs;\n{\n    gaussDiffParameters *p = (gaussDiffParameters*)gv->params;\n    double *uPiArr = p->uPiArr, sumUPi = p->sumUPi;\n    double **uAMat = p->uAMat, *sumUAArr = p->sumUAArr;\n    double *uAArr = p->uAArr, *uBArr = p->uBArr, *aDlt = p->aDlt, *bDlt = p->bDlt;\n    double *avgPi = p->avgPi, *avgLnPi = p->avgLnPi, **avgA = p->avgA, **avgLnA = p->avgLnA;\n    double *avgDlt = p->avgDlt, *avgLnDlt = p->avgLnDlt;\n    gaussDiffGlobalStats *gs = (gaussDiffGlobalStats*)ivs->stats;\n    double *NiR = gs->NiR, *NiiR = gs->NiiR, **NijR = gs->NijR, *RiR = gs->RiR;\n    double *z1iR = gs->z1iR, dR = (double)(xns->R);\n    int sNo = gv->sNo;\n    int i, j;\n    \n    for( i = 0 ; i < sNo ; i++ ){\n        avgPi[i] = ( uPiArr[i] + z1iR[i] ) / ( sumUPi + dR );\n        avgLnPi[i] = gsl_sf_psi( uPiArr[i] + z1iR[i] ) - gsl_sf_psi( sumUPi + dR );\n        \n        for( j = 0 ; j < sNo ; j++ ){\n            avgA[i][j] = ( uAMat[i][j] + NijR[i][j] ) / ( sumUAArr[i] + NiiR[i] );\n            avgLnA[i][j] = gsl_sf_psi( uAMat[i][j] + NijR[i][j] ) - gsl_sf_psi( sumUAArr[i] + NiiR[i] );\n        }\n        \n        aDlt[i] = uAArr[i] + NiR[i];\n        bDlt[i] = uBArr[i] + RiR[i] / 4.0;\n        \n        avgDlt[i]   = aDlt[i] / bDlt[i];\n        avgLnDlt[i] = gsl_sf_psi( aDlt[i] ) - log( bDlt[i] );\n    }\n}\n\n\ndouble varLowerBound_gaussDiff( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n    gaussDiffParameters *p = (gaussDiffParameters*)gv->params;\n    gaussDiffStats *s = (gaussDiffStats*)iv->stats;\n    size_t dLen = xn->N;\n    int sNo = gv->sNo;\n    double **gmMat = iv->gmMat, *cn = iv->cn;\n    double *uPiArr = p->uPiArr, sumUPi = p->sumUPi;\n    double **uAMat = p->uAMat, *sumUAArr = p->sumUAArr;\n    double *uAArr = p->uAArr, *uBArr = p->uBArr;\n    double *avgLnPi = p->avgLnPi, **avgLnA = p->avgLnA;\n    double *avgDlt = p->avgDlt, *avgLnDlt = p->avgLnDlt;\n    double *Nii = s->Nii, **Nij = s->Nij;\n    double *aDlt = p->aDlt, *bDlt = p->bDlt;\n    size_t n;\n    int i, j;\n\n    double lnpPi = gsl_sf_lngamma(sumUPi);\n    double lnpA = 0.0;\n    double lnpDlt = 0.0;\n    double lnqPi = gsl_sf_lngamma(sumUPi + 1.0);\n    double lnqA = 0.0;\n    double lnqDlt = - sNo / 2.0;\n    for( i = 0 ; i < sNo ; i++ ){\n        lnpPi += (uPiArr[i]-1.0) * avgLnPi[i] - gsl_sf_lngamma(uPiArr[i]);\n\n        lnpDlt += - gsl_sf_lngamma(uAArr[i]) + uAArr[i] * log(uBArr[i]);\n        lnpDlt += (uAArr[i] - 1.0) * avgLnDlt[i] - uBArr[i] * avgDlt[i];\n        \n        lnqPi += (uPiArr[i]+gmMat[0][i]-1.0) * (gsl_sf_psi(uPiArr[i]+gmMat[0][i]) - gsl_sf_psi(sumUPi+1.0));\n        lnqPi -= gsl_sf_lngamma(uPiArr[i] + gmMat[0][i]);\n\n        lnpA += gsl_sf_lngamma(sumUAArr[i]);\n        lnqA += gsl_sf_lngamma(sumUAArr[i] + Nii[i]);\n        for( j = 0 ; j < sNo ; j++ ){\n            lnpA += (uAMat[i][j]-1.0)*avgLnA[i][j] - gsl_sf_lngamma(uAMat[i][j]);\n\n            lnqA += (uAMat[i][j] + Nij[i][j] - 1.0) * (gsl_sf_psi(uAMat[i][j]+Nij[i][j]) - gsl_sf_psi(sumUAArr[i]+Nii[i]));\n            lnqA -= gsl_sf_lngamma( uAMat[i][j] + Nij[i][j] );\n        }\n\n        lnqDlt += - gsl_sf_lngamma(aDlt[i]) + aDlt[i] * log(bDlt[i]);\n        lnqDlt += (aDlt[i] - 1.0) * avgLnDlt[i] - aDlt[i];\n    }\n\n    double lnpX = 0.0;\n    for( n = 0 ; n < dLen ; n++ ){\n        lnpX += log( cn[n] );\n    }\n\n    double val;\n    val  = lnpPi + lnpA + lnpDlt;\n    val -= lnqPi + lnqA + lnqDlt;\n    val += lnpX;\n    val += log(gsl_sf_fact(sNo));\n\n    return val;\n}\n\ndouble varLowerBoundG_gaussDiff( xns, gv, ivs )\nxnDataBundle *xns;\nglobalVars *gv;\nindVarBundle *ivs;\n{\n    gaussDiffParameters *p = (gaussDiffParameters*)gv->params;\n    int sNo = gv->sNo, rNo = xns->R;\n    double *uPiArr = p->uPiArr, sumUPi = p->sumUPi;\n    double **uAMat = p->uAMat, *sumUAArr = p->sumUAArr;\n    double *uAArr = p->uAArr, *uBArr = p->uBArr;\n    double *avgLnPi = p->avgLnPi, **avgLnA = p->avgLnA;\n    double *avgDlt = p->avgDlt, *avgLnDlt = p->avgLnDlt;\n    double *aDlt = p->aDlt, *bDlt = p->bDlt;\n    gaussDiffGlobalStats *gs = (gaussDiffGlobalStats*)ivs->stats;\n    double *NiiR = gs->NiiR, **NijR = gs->NijR, *z1iR = gs->z1iR, dR = (double)xns->R;\n    size_t n;\n    int i, j, r;\n\n    double lnpPi = gsl_sf_lngamma(sumUPi);\n    double lnpA = 0.0;\n    double lnpDlt = 0.0;\n    double lnqPi = gsl_sf_lngamma(sumUPi + dR);\n    double lnqA = 0.0;\n    double lnqDlt = - sNo / 2.0;\n    for( i = 0 ; i < sNo ; i++ ){\n        lnpPi += (uPiArr[i]-1.0) * avgLnPi[i] - gsl_sf_lngamma(uPiArr[i]);\n        \n        lnpDlt += - gsl_sf_lngamma(uAArr[i]) + uAArr[i] * log(uBArr[i]);\n        lnpDlt += (uAArr[i] - 1.0) * avgLnDlt[i] - uBArr[i] * avgDlt[i];\n        \n        lnqPi += (uPiArr[i]+z1iR[i]-1.0) * (gsl_sf_psi(uPiArr[i]+z1iR[i]) - gsl_sf_psi(sumUPi+dR));\n        lnqPi -= gsl_sf_lngamma(uPiArr[i] + z1iR[i]);\n        \n        lnpA += gsl_sf_lngamma(sumUAArr[i]);\n        lnqA += gsl_sf_lngamma(sumUAArr[i] + NiiR[i]);\n        for( j = 0 ; j < sNo ; j++ ){\n            lnpA += (uAMat[i][j]-1.0)*avgLnA[i][j] - gsl_sf_lngamma(uAMat[i][j]);\n            \n            lnqA += (uAMat[i][j] + NijR[i][j] - 1.0) * (gsl_sf_psi(uAMat[i][j]+NijR[i][j]) - gsl_sf_psi(sumUAArr[i]+NiiR[i]));\n            lnqA -= gsl_sf_lngamma( uAMat[i][j] + NijR[i][j] );\n        }\n        \n        lnqDlt += - gsl_sf_lngamma(aDlt[i]) + aDlt[i] * log(bDlt[i]);\n        lnqDlt += (aDlt[i] - 1.0) * avgLnDlt[i] - aDlt[i];\n    }\n    \n    double lnpX = 0.0;\n    for( r = 0 ; r < rNo ; r++ ){\n        size_t dLen = xns->xn[r]->N;\n        for( n = 0 ; n < dLen ; n++ ){\n            lnpX += log( ivs->indVars[r]->cn[n] );\n        }\n    }\n    \n    double val;\n    val  = lnpPi + lnpA + lnpDlt;\n    val -= lnqPi + lnqA + lnqDlt;\n    val += lnpX;\n    val += log(gsl_sf_fact(sNo));\n    \n    return val;\n}    \n\n\nvoid reorderParameters_gaussDiff( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n    gaussDiffParameters *p = (gaussDiffParameters*)gv->params;\n    gaussDiffStats *s = (gaussDiffStats*)iv->stats;\n    size_t dLen = xn->N;\n    int sNo = gv->sNo;\n    double **gmMat = iv->gmMat, ***xiMat = iv->xiMat;\n    double *avgPi = p->avgPi, *avgLnPi = p->avgLnPi, **avgA = p->avgA, **avgLnA = p->avgLnA;\n    double *avgDlt = p->avgDlt, *avgLnDlt = p->avgLnDlt;\n    double *Ni = s->Ni;\n    size_t n;\n    int i, j;\n\n    int *index = (int*)malloc( sNo * sizeof(int) );\n    double *store = (double*)malloc( sNo * sizeof(double) );\n    double **s2D = (double**)malloc( sNo * sizeof(double*) );\n    for( i = 0 ; i < sNo ; i++ )\n    {   s2D[i] = (double*)malloc( MAX(sNo,2) * sizeof(double) );   }\n\n    // index indicates order of avgDlt values (0=biggest avgDlt -- sNo=smallest avgDlt).\n    for( i = 0 ; i < sNo ; i++ ){\n        index[i] = sNo - 1;\n        for( j = 0 ; j < sNo ; j++ ){\n            if( j != i ){\n                if( avgDlt[i] < avgDlt[j] ){\n                    index[i]--;\n                } else if( avgDlt[i] == avgDlt[j] ){\n                    if( j > i )\n                    {   index[i]--;   }\n                }\n            }\n        }\n    }\n\n    for( i = 0 ; i < sNo ; i++ ){   store[index[i]] = avgPi[i];   }\n    for( i = 0 ; i < sNo ; i++ ){   avgPi[i] = store[i];   }\n\n    for( i = 0 ; i < sNo ; i++ ){   store[index[i]] = avgLnPi[i];   }\n    for( i = 0 ; i < sNo ; i++ ){   avgLnPi[i] = store[i];   }\n\n    for( i = 0 ; i < sNo ; i++ ){   store[index[i]] = avgDlt[i];   }\n    for( i = 0 ; i < sNo ; i++ ){   avgDlt[i] = store[i];   }\n\n    for( i = 0 ; i < sNo ; i++ ){   store[index[i]] = avgLnDlt[i];   }\n    for( i = 0 ; i < sNo ; i++ ){   avgLnDlt[i] = store[i];   }\n\n    for( j = 0 ; j < sNo ; j++ ){\n        for( i = 0 ; i < sNo ; i++ ){   s2D[index[i]][index[j]] = avgA[i][j];   }\n    }\n    for( j = 0 ; j < sNo ; j++ ){\n        for( i = 0 ; i < sNo ; i++ ){   avgA[i][j] = s2D[i][j];   }\n    }\n\n    for( j = 0 ; j < sNo ; j++ ){\n        for( i = 0 ; i < sNo ; i++ ){   s2D[index[i]][index[j]] = avgLnA[i][j];   }\n    }\n    for( j = 0 ; j < sNo ; j++ ){\n        for( i = 0 ; i < sNo ; i++ ){   avgLnA[i][j] = s2D[i][j];   }\n    }\n\n    for( i = 0 ; i < sNo ; i++ ){   store[index[i]] = Ni[i];   }\n    for( i = 0 ; i < sNo ; i++ ){   Ni[i] = store[i];   }\n\n    for( n = 0 ; n < dLen ; n++ ){\n        for( i = 0 ; i < sNo ; i++ ){   store[index[i]] = gmMat[n][i];   }\n        for( i = 0 ; i < sNo ; i++ ){   gmMat[n][i] = store[i];   }\n    }\n\n    for( n = 0 ; n < dLen ; n++ ){\n        for( j = 0 ; j < sNo ; j++ ){\n            for( i = 0 ; i < sNo ; i++ ){   s2D[index[i]][index[j]] = xiMat[n][i][j];   }\n        }\n        for( j = 0 ; j < sNo ; j++ ){\n            for( i = 0 ; i < sNo ; i++ ){   xiMat[n][i][j] = s2D[i][j];   }\n        }\n    }\n\n    for( i = 0 ; i < sNo ; i++ ){   free( s2D[i] );   }\n    free( s2D );\n    free( store );\n    free( index );\n}\n\nvoid reorderParametersG_gaussDiff( xns, gv, ivs )\nxnDataBundle *xns;\nglobalVars *gv;\nindVarBundle *ivs;\n{\n    gaussDiffParameters *p = (gaussDiffParameters*)gv->params;\n    size_t dLen;\n    int sNo = gv->sNo, rNo = xns->R;\n    double *avgPi = p->avgPi, *avgLnPi = p->avgLnPi, **avgA = p->avgA, **avgLnA = p->avgLnA;\n    double *avgDlt = p->avgDlt, *avgLnDlt = p->avgLnDlt;\n    size_t n;\n    int i, j, r;\n    \n    int *index = (int*)malloc( sNo * sizeof(int) );\n    double *store = (double*)malloc( sNo * sizeof(double) );\n    double **s2D = (double**)malloc( sNo * sizeof(double*) );\n    for( i = 0 ; i < sNo ; i++ )\n    {   s2D[i] = (double*)malloc( MAX(sNo,2) * sizeof(double) );   }\n    \n    // index indicates order of avgMu values (0=biggest avgMu -- sNo=smallest avgMu).\n    for( i = 0 ; i < sNo ; i++ ){\n        index[i] = sNo - 1;\n        for( j = 0 ; j < sNo ; j++ ){\n            if( j != i ){\n                if( avgDlt[i] < avgDlt[j] ){\n                    index[i]--;\n                } else if( avgDlt[i] == avgDlt[j] ){\n                    if( j > i )\n                    {   index[i]--;   }\n                }\n            }\n        }\n    }\n    \n    for( i = 0 ; i < sNo ; i++ ){   store[index[i]] = avgPi[i];   }\n    for( i = 0 ; i < sNo ; i++ ){   avgPi[i] = store[i];   }\n    \n    for( i = 0 ; i < sNo ; i++ ){   store[index[i]] = avgLnPi[i];   }\n    for( i = 0 ; i < sNo ; i++ ){   avgLnPi[i] = store[i];   }\n    \n    for( i = 0 ; i < sNo ; i++ ){   store[index[i]] = avgDlt[i];   }\n    for( i = 0 ; i < sNo ; i++ ){   avgDlt[i] = store[i];   }\n    \n    for( i = 0 ; i < sNo ; i++ ){   store[index[i]] = avgLnDlt[i];   }\n    for( i = 0 ; i < sNo ; i++ ){   avgLnDlt[i] = store[i];   }\n    \n    for( j = 0 ; j < sNo ; j++ ){\n        for( i = 0 ; i < sNo ; i++ ){   s2D[index[i]][index[j]] = avgA[i][j];   }\n    }\n    for( j = 0 ; j < sNo ; j++ ){\n        for( i = 0 ; i < sNo ; i++ ){   avgA[i][j] = s2D[i][j];   }\n    }\n    \n    for( j = 0 ; j < sNo ; j++ ){\n        for( i = 0 ; i < sNo ; i++ ){   s2D[index[i]][index[j]] = avgLnA[i][j];   }\n    }\n    for( j = 0 ; j < sNo ; j++ ){\n        for( i = 0 ; i < sNo ; i++ ){   avgLnA[i][j] = s2D[i][j];   }\n    }\n    \n    double *NiR = ((gaussDiffGlobalStats*)ivs->stats)->NiR;\n    for( i = 0 ; i < sNo ; i++ ){   store[index[i]] = NiR[i];   }\n    for( i = 0 ; i < sNo ; i++ ){   NiR[i] = store[i];   }\n    \n    for( r = 0 ; r < rNo ; r++ ){\n        double **gmMat = ivs->indVars[r]->gmMat;\n        dLen = xns->xn[r]->N;\n        for( n = 0 ; n < dLen ; n++ ){\n            for( i = 0 ; i < sNo ; i++ ){   store[index[i]] = gmMat[n][i];   }\n            for( i = 0 ; i < sNo ; i++ ){   gmMat[n][i] = store[i];   }\n        }\n    }\n    \n    for( r = 0 ; r < rNo ; r++ ){\n        double ***xiMat = ivs->indVars[r]->xiMat;\n        dLen = xns->xn[r]->N;\n        for( n = 0 ; n < dLen ; n++ ){\n            for( j = 0 ; j < sNo ; j++ ){\n                for( i = 0 ; i < sNo ; i++ ){   s2D[index[i]][index[j]] = xiMat[n][i][j];   }\n            }\n            for( j = 0 ; j < sNo ; j++ ){\n                for( i = 0 ; i < sNo ; i++ ){   xiMat[n][i][j] = s2D[i][j];   }\n            }\n        }\n    }\n    \n    for( i = 0 ; i < sNo ; i++ ){   free( s2D[i] );   }\n    free( s2D );\n    free( store );\n    free( index );\n}\n\n\nvoid outputGaussDiffResults( xn, gv, iv, logFP )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\nFILE *logFP;\n{\n    gaussDiffParameters *p = (gaussDiffParameters*)gv->params;\n    int sNo = gv->sNo;\n    int i, j;\n    fprintf(logFP, \"  results: K = %d \\n\", sNo);\n\n    fprintf(logFP, \"   delta: ( %g\", p->avgDlt[0]);\n    for( i = 1 ; i < sNo ; i++ ){\n        fprintf(logFP, \", %g\", p->avgDlt[i]);\n    }\n    fprintf(logFP, \" ) \\n\");\n\n    fprintf(logFP, \"   pi: ( %g\", p->avgPi[0]);\n    for( i = 1 ; i < sNo ; i++ ){\n        fprintf(logFP, \", %g\", p->avgPi[i]);\n    }\n    fprintf(logFP, \" ) \\n\");\n    \n    fprintf(logFP, \"   A_matrix: [\");\n    for( i = 0 ; i < sNo ; i++ ){\n            fprintf(logFP, \" ( %g\", p->avgA[i][0]);\n            for( j = 1 ; j < sNo ; j++ )\n            {   fprintf(logFP, \", %g\", p->avgA[i][j]);   }\n            fprintf(logFP, \")\");\n    }\n    fprintf(logFP, \" ] \\n\\n\");\n\n    char fn[256];\n    FILE *fp;\n    size_t n;\n\n    sprintf( fn, \"%s.param%03d\", xn->name, sNo );\n    if( (fp = fopen( fn, \"w\")) != NULL ){\n        fprintf(fp, \"delta, pi\");\n        for( i = 0 ; i < sNo ; i++ )\n        {   fprintf(fp, \", A%dx\", i);   }\n        fprintf(fp, \"\\n\");\n\n        for( i = 0 ; i < sNo ; i++ ){\n            fprintf(fp, \"%g, %g\", p->avgDlt[i], p->avgPi[i]);\n            for( j = 0 ; j < sNo ; j++ )\n            {   fprintf(fp, \", %g\", p->avgA[j][i]);   }\n            fprintf(fp, \"\\n\");\n        }\n        fclose(fp);\n    }\n\n    sprintf( fn, \"%s.Lq%03d\", xn->name, sNo );\n    if( (fp = fopen( fn, \"w\")) != NULL ){\n        for( n = 0 ; n < gv->iteration ; n++ ){\n            fprintf( fp, \"%24.20e\\n\", gv->LqArr[n] );\n        }\n        fclose(fp);\n    }\n\n    sprintf( fn, \"%s.maxS%03d\", xn->name, sNo );\n    if( (fp = fopen( fn, \"w\")) != NULL ){\n        for( n = 0 ; n < xn->N ; n++ ){\n            fprintf( fp, \"%d\\n\", iv->stateTraj[n] );\n        }\n        fclose(fp);\n    }\n\n}\n\nvoid outputGaussDiffResultsG( xns, gv, ivs, logFP )\nxnDataBundle *xns;\nglobalVars *gv;\nindVarBundle *ivs;\nFILE *logFP;\n{\n    int sNo = gv->sNo, rNo = xns->R;\n    gaussDiffParameters *p = (gaussDiffParameters*)gv->params;\n    int i, j, r;\n    \n    fprintf(logFP, \"  results: K = %d \\n\", sNo);\n    \n    fprintf(logFP, \"   delta: ( %g\", p->avgDlt[0]);\n    for( i = 1 ; i < sNo ; i++ )\n    {   fprintf(logFP, \", %g\", p->avgDlt[i]);   }\n    fprintf(logFP, \" ) \\n\");\n    \n    fprintf(logFP, \"   pi: ( %g\", p->avgPi[0]);\n    for( i = 1 ; i < sNo ; i++ ){\n        fprintf(logFP, \", %g\", p->avgPi[i]);\n    }\n    fprintf(logFP, \" ) \\n\");\n    \n    fprintf(logFP, \"   A_matrix: [\");\n    for( i = 0 ; i < sNo ; i++ ){\n        fprintf(logFP, \" ( %g\", p->avgA[i][0]);\n        for( j = 1 ; j < sNo ; j++ )\n        {   fprintf(logFP, \", %g\", p->avgA[i][j]);   }\n        fprintf(logFP, \")\");\n    }\n    fprintf(logFP, \" ] \\n\\n\");\n    \n    char fn[256];\n    FILE *fp;\n    size_t n;\n    \n    sprintf( fn, \"%s.param%03d\", xns->xn[0]->name, sNo );\n    if( (fp = fopen( fn, \"w\")) != NULL ){\n        fprintf(fp, \"delta, pi\");\n        for( i = 0 ; i < sNo ; i++ )\n        {   fprintf(fp, \", A%dx\", i);   }\n        fprintf(fp, \"\\n\");\n        \n        for( i = 0 ; i < sNo ; i++ ){\n            fprintf(fp, \"%g, %g\", p->avgDlt[i], p->avgPi[i]);\n            for( j = 0 ; j < sNo ; j++ )\n            {   fprintf(fp, \", %g\", p->avgA[j][i]);   }\n            fprintf(fp, \"\\n\");\n        }\n        fclose(fp);\n    }\n    \n    sprintf( fn, \"%s.Lq%03d\", xns->xn[0]->name, sNo );\n    if( (fp = fopen( fn, \"w\")) != NULL ){\n        for( n = 0 ; n < gv->iteration ; n++ ){\n            fprintf( fp, \"%24.20e\\n\", gv->LqArr[n] );\n        }\n        fclose(fp);\n    }\n    \n    sprintf( fn, \"%s.maxS%03d\", xns->xn[0]->name, sNo );\n    int flag = 0;\n    if( (fp = fopen( fn, \"w\")) != NULL ){\n        n = 0;\n        do{\n            flag = 1;\n            for( r = 0 ; r < rNo ; r++ ){\n                xnDataSet *xn = xns->xn[r];\n                indVars *iv = ivs->indVars[r];\n                \n                if( r > 0 ){\n                    fprintf( fp, \",\" );\n                }\n                if( n < xn->N ){\n                    fprintf( fp, \"%d\", iv->stateTraj[n] );\n                }\n                flag &= (n >= (xn->N - 1));\n            }\n            fprintf( fp, \"\\n\" );\n            n++;\n        }while( !flag );\n        fclose(fp);\n    }\n}\n\n//\n", "meta": {"hexsha": "c8a0fa0bcfd0940f04f183db8482dfbb62a79d0d", "size": 30318, "ext": "c", "lang": "C", "max_stars_repo_path": "C/vbHmmGaussDiffusion.c", "max_stars_repo_name": "okamoto-kenji/varBayes-HMM", "max_stars_repo_head_hexsha": "77afe3c336c9e1ebeb115ca4f0b2bc25060556bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-03-31T06:59:00.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-01T06:35:57.000Z", "max_issues_repo_path": "C/vbHmmGaussDiffusion.c", "max_issues_repo_name": "okamoto-kenji/varBayes-HMM", "max_issues_repo_head_hexsha": "77afe3c336c9e1ebeb115ca4f0b2bc25060556bd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "C/vbHmmGaussDiffusion.c", "max_forks_repo_name": "okamoto-kenji/varBayes-HMM", "max_forks_repo_head_hexsha": "77afe3c336c9e1ebeb115ca4f0b2bc25060556bd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8112094395, "max_line_length": 126, "alphanum_fraction": 0.4883567518, "num_tokens": 11323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.03963884250447896, "lm_q1q2_score": 0.01966458517384162}}
{"text": "#pragma once\n\n#include <type_traits>\n#include <utility>\n\n#include <cuda/define_specifiers.hpp>\n#include <cuda/runtime_api.hpp>\n\n#include <gsl-lite/gsl-lite.hpp>\n\nnamespace thrustshift {\n\nnamespace kernel {\n\ntemplate <typename SrcT, typename DstT, class F>\n__global__ void transform(gsl_lite::span<const SrcT> src,\n                          gsl_lite::span<DstT> dst,\n                          F f) {\n\n\tconst auto gtid = threadIdx.x + blockIdx.x * blockDim.x;\n\tif (gtid < src.size()) {\n\t\tdst[gtid] = f(src[gtid]);\n\t}\n}\n\n} // namespace kernel\n\nnamespace async {\n\ntemplate <class SrcRange, class DstRange, class UnaryFunctor>\nvoid transform(cuda::stream_t& stream,\n               SrcRange&& src,\n               DstRange&& dst,\n               UnaryFunctor f) {\n\tgsl_Expects(src.size() == dst.size());\n\n\tif (src.empty()) {\n\t\treturn;\n\t}\n\n\tusing src_value_type =\n\t    typename std::remove_reference<SrcRange>::type::value_type;\n\tusing dst_value_type =\n\t    typename std::remove_reference<DstRange>::type::value_type;\n\n\tconstexpr cuda::grid::block_dimension_t block_dim = 128;\n\tconst cuda::grid::dimension_t grid_dim =\n\t    (src.size() + block_dim - 1) / block_dim;\n\tauto c = cuda::make_launch_config(grid_dim, block_dim);\n\tauto k = kernel::transform<src_value_type, dst_value_type, decltype(f)>;\n\tcuda::enqueue_launch(k, stream, c, src, dst, f);\n}\n\n} // namespace async\n\nnamespace array {\n\nnamespace detail {\n\ntemplate <typename T,\n          std::size_t N,\n          template <typename, std::size_t>\n          class Arr,\n          class F,\n          std::size_t... I>\nCUDA_FHD auto transform_impl(const Arr<T, N>& arr,\n                             F&& f,\n                             std::index_sequence<I...>) {\n\treturn Arr<T, N>({f(arr[I])...});\n}\n\n} // namespace detail\n\ntemplate <typename T,\n          std::size_t N,\n          template <typename, std::size_t>\n          class Arr,\n          class F,\n          typename Indices = std::make_index_sequence<N>>\nCUDA_FHD auto transform(const Arr<T, N>& arr, F&& f) {\n\treturn detail::transform_impl(arr, std::forward<F>(f), Indices{});\n}\n\n} // namespace array\n\nnamespace tuple {\n\nnamespace detail {\n\ntemplate <typename Tuple, typename F, std::size_t... I>\nCUDA_FHD auto transform_impl(Tuple&& t, F&& f, std::index_sequence<I...>) {\n\tusing TupleT = typename std::remove_reference<Tuple>::type;\n\tusing std::get;\n\treturn TupleT(f(get<I>(t))...);\n}\n\n} // namespace detail\n\ntemplate <typename... Ts, template <typename...> class TupleT, typename F>\nCUDA_FHD auto transform(TupleT<Ts...> const& t, F&& f) {\n\tusing std::tuple_size;\n\tauto seq = std::make_index_sequence<tuple_size<TupleT<Ts...>>::value>{};\n\treturn detail::transform_impl(t, std::forward<F>(f), seq);\n}\n\n} // namespace tuple\n\n} // namespace thrustshift\n", "meta": {"hexsha": "bd0c8e69731f2359c238e5275e56f83c4d51ee2f", "size": 2752, "ext": "h", "lang": "C", "max_stars_repo_path": "include/thrustshift/transform.h", "max_stars_repo_name": "pauleonix/thrustshift", "max_stars_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-16T13:01:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T13:01:46.000Z", "max_issues_repo_path": "include/thrustshift/transform.h", "max_issues_repo_name": "pauleonix/thrustshift", "max_issues_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-23T14:12:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-17T11:40:04.000Z", "max_forks_repo_path": "include/thrustshift/transform.h", "max_forks_repo_name": "pauleonix/thrustshift", "max_forks_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.247706422, "max_line_length": 75, "alphanum_fraction": 0.6369912791, "num_tokens": 683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35220178204788966, "lm_q2_score": 0.055823143098100166, "lm_q1q2_score": 0.01966101047866523}}
{"text": "/* matrix/gsl_matrix_int.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_MATRIX_INT_H__\n#define __GSL_MATRIX_INT_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_inline.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_vector_int.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size1;\n  size_t size2;\n  size_t tda;\n  int * data;\n  gsl_block_int * block;\n  int owner;\n} gsl_matrix_int;\n\ntypedef struct\n{\n  gsl_matrix_int matrix;\n} _gsl_matrix_int_view;\n\ntypedef _gsl_matrix_int_view gsl_matrix_int_view;\n\ntypedef struct\n{\n  gsl_matrix_int matrix;\n} _gsl_matrix_int_const_view;\n\ntypedef const _gsl_matrix_int_const_view gsl_matrix_int_const_view;\n\n/* Allocation */\n\ngsl_matrix_int * \ngsl_matrix_int_alloc (const size_t n1, const size_t n2);\n\ngsl_matrix_int * \ngsl_matrix_int_calloc (const size_t n1, const size_t n2);\n\ngsl_matrix_int * \ngsl_matrix_int_alloc_from_block (gsl_block_int * b, \n                                   const size_t offset, \n                                   const size_t n1, \n                                   const size_t n2, \n                                   const size_t d2);\n\ngsl_matrix_int * \ngsl_matrix_int_alloc_from_matrix (gsl_matrix_int * m,\n                                    const size_t k1, \n                                    const size_t k2,\n                                    const size_t n1, \n                                    const size_t n2);\n\ngsl_vector_int * \ngsl_vector_int_alloc_row_from_matrix (gsl_matrix_int * m,\n                                        const size_t i);\n\ngsl_vector_int * \ngsl_vector_int_alloc_col_from_matrix (gsl_matrix_int * m,\n                                        const size_t j);\n\nvoid gsl_matrix_int_free (gsl_matrix_int * m);\n\n/* Views */\n\n_gsl_matrix_int_view \ngsl_matrix_int_submatrix (gsl_matrix_int * m, \n                            const size_t i, const size_t j, \n                            const size_t n1, const size_t n2);\n\n_gsl_vector_int_view \ngsl_matrix_int_row (gsl_matrix_int * m, const size_t i);\n\n_gsl_vector_int_view \ngsl_matrix_int_column (gsl_matrix_int * m, const size_t j);\n\n_gsl_vector_int_view \ngsl_matrix_int_diagonal (gsl_matrix_int * m);\n\n_gsl_vector_int_view \ngsl_matrix_int_subdiagonal (gsl_matrix_int * m, const size_t k);\n\n_gsl_vector_int_view \ngsl_matrix_int_superdiagonal (gsl_matrix_int * m, const size_t k);\n\n_gsl_vector_int_view\ngsl_matrix_int_subrow (gsl_matrix_int * m, const size_t i,\n                         const size_t offset, const size_t n);\n\n_gsl_vector_int_view\ngsl_matrix_int_subcolumn (gsl_matrix_int * m, const size_t j,\n                            const size_t offset, const size_t n);\n\n_gsl_matrix_int_view\ngsl_matrix_int_view_array (int * base,\n                             const size_t n1, \n                             const size_t n2);\n\n_gsl_matrix_int_view\ngsl_matrix_int_view_array_with_tda (int * base, \n                                      const size_t n1, \n                                      const size_t n2,\n                                      const size_t tda);\n\n\n_gsl_matrix_int_view\ngsl_matrix_int_view_vector (gsl_vector_int * v,\n                              const size_t n1, \n                              const size_t n2);\n\n_gsl_matrix_int_view\ngsl_matrix_int_view_vector_with_tda (gsl_vector_int * v,\n                                       const size_t n1, \n                                       const size_t n2,\n                                       const size_t tda);\n\n\n_gsl_matrix_int_const_view \ngsl_matrix_int_const_submatrix (const gsl_matrix_int * m, \n                                  const size_t i, const size_t j, \n                                  const size_t n1, const size_t n2);\n\n_gsl_vector_int_const_view \ngsl_matrix_int_const_row (const gsl_matrix_int * m, \n                            const size_t i);\n\n_gsl_vector_int_const_view \ngsl_matrix_int_const_column (const gsl_matrix_int * m, \n                               const size_t j);\n\n_gsl_vector_int_const_view\ngsl_matrix_int_const_diagonal (const gsl_matrix_int * m);\n\n_gsl_vector_int_const_view \ngsl_matrix_int_const_subdiagonal (const gsl_matrix_int * m, \n                                    const size_t k);\n\n_gsl_vector_int_const_view \ngsl_matrix_int_const_superdiagonal (const gsl_matrix_int * m, \n                                      const size_t k);\n\n_gsl_vector_int_const_view\ngsl_matrix_int_const_subrow (const gsl_matrix_int * m, const size_t i,\n                               const size_t offset, const size_t n);\n\n_gsl_vector_int_const_view\ngsl_matrix_int_const_subcolumn (const gsl_matrix_int * m, const size_t j,\n                                  const size_t offset, const size_t n);\n\n_gsl_matrix_int_const_view\ngsl_matrix_int_const_view_array (const int * base,\n                                   const size_t n1, \n                                   const size_t n2);\n\n_gsl_matrix_int_const_view\ngsl_matrix_int_const_view_array_with_tda (const int * base, \n                                            const size_t n1, \n                                            const size_t n2,\n                                            const size_t tda);\n\n_gsl_matrix_int_const_view\ngsl_matrix_int_const_view_vector (const gsl_vector_int * v,\n                                    const size_t n1, \n                                    const size_t n2);\n\n_gsl_matrix_int_const_view\ngsl_matrix_int_const_view_vector_with_tda (const gsl_vector_int * v,\n                                             const size_t n1, \n                                             const size_t n2,\n                                             const size_t tda);\n\n/* Operations */\n\nvoid gsl_matrix_int_set_zero (gsl_matrix_int * m);\nvoid gsl_matrix_int_set_identity (gsl_matrix_int * m);\nvoid gsl_matrix_int_set_all (gsl_matrix_int * m, int x);\n\nint gsl_matrix_int_fread (FILE * stream, gsl_matrix_int * m) ;\nint gsl_matrix_int_fwrite (FILE * stream, const gsl_matrix_int * m) ;\nint gsl_matrix_int_fscanf (FILE * stream, gsl_matrix_int * m);\nint gsl_matrix_int_fprintf (FILE * stream, const gsl_matrix_int * m, const char * format);\n \nint gsl_matrix_int_memcpy(gsl_matrix_int * dest, const gsl_matrix_int * src);\nint gsl_matrix_int_swap(gsl_matrix_int * m1, gsl_matrix_int * m2);\n\nint gsl_matrix_int_swap_rows(gsl_matrix_int * m, const size_t i, const size_t j);\nint gsl_matrix_int_swap_columns(gsl_matrix_int * m, const size_t i, const size_t j);\nint gsl_matrix_int_swap_rowcol(gsl_matrix_int * m, const size_t i, const size_t j);\nint gsl_matrix_int_transpose (gsl_matrix_int * m);\nint gsl_matrix_int_transpose_memcpy (gsl_matrix_int * dest, const gsl_matrix_int * src);\n\nint gsl_matrix_int_max (const gsl_matrix_int * m);\nint gsl_matrix_int_min (const gsl_matrix_int * m);\nvoid gsl_matrix_int_minmax (const gsl_matrix_int * m, int * min_out, int * max_out);\n\nvoid gsl_matrix_int_max_index (const gsl_matrix_int * m, size_t * imax, size_t *jmax);\nvoid gsl_matrix_int_min_index (const gsl_matrix_int * m, size_t * imin, size_t *jmin);\nvoid gsl_matrix_int_minmax_index (const gsl_matrix_int * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);\n\nint gsl_matrix_int_equal (const gsl_matrix_int * a, const gsl_matrix_int * b);\n\nint gsl_matrix_int_isnull (const gsl_matrix_int * m);\nint gsl_matrix_int_ispos (const gsl_matrix_int * m);\nint gsl_matrix_int_isneg (const gsl_matrix_int * m);\nint gsl_matrix_int_isnonneg (const gsl_matrix_int * m);\n\nint gsl_matrix_int_add (gsl_matrix_int * a, const gsl_matrix_int * b);\nint gsl_matrix_int_sub (gsl_matrix_int * a, const gsl_matrix_int * b);\nint gsl_matrix_int_mul_elements (gsl_matrix_int * a, const gsl_matrix_int * b);\nint gsl_matrix_int_div_elements (gsl_matrix_int * a, const gsl_matrix_int * b);\nint gsl_matrix_int_scale (gsl_matrix_int * a, const double x);\nint gsl_matrix_int_add_constant (gsl_matrix_int * a, const double x);\nint gsl_matrix_int_add_diagonal (gsl_matrix_int * a, const double x);\n\n/***********************************************************************/\n/* The functions below are obsolete                                    */\n/***********************************************************************/\nint gsl_matrix_int_get_row(gsl_vector_int * v, const gsl_matrix_int * m, const size_t i);\nint gsl_matrix_int_get_col(gsl_vector_int * v, const gsl_matrix_int * m, const size_t j);\nint gsl_matrix_int_set_row(gsl_matrix_int * m, const size_t i, const gsl_vector_int * v);\nint gsl_matrix_int_set_col(gsl_matrix_int * m, const size_t j, const gsl_vector_int * v);\n/***********************************************************************/\n\n/* inline functions if you are using GCC */\n\nINLINE_DECL int   gsl_matrix_int_get(const gsl_matrix_int * m, const size_t i, const size_t j);\nINLINE_DECL void    gsl_matrix_int_set(gsl_matrix_int * m, const size_t i, const size_t j, const int x);\nINLINE_DECL int * gsl_matrix_int_ptr(gsl_matrix_int * m, const size_t i, const size_t j);\nINLINE_DECL const int * gsl_matrix_int_const_ptr(const gsl_matrix_int * m, const size_t i, const size_t j);\n\n#ifdef HAVE_INLINE\nINLINE_FUN \nint\ngsl_matrix_int_get(const gsl_matrix_int * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_VAL(\"first index out of range\", GSL_EINVAL, 0) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_VAL(\"second index out of range\", GSL_EINVAL, 0) ;\n        }\n    }\n#endif\n  return m->data[i * m->tda + j] ;\n} \n\nINLINE_FUN \nvoid\ngsl_matrix_int_set(gsl_matrix_int * m, const size_t i, const size_t j, const int x)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_VOID(\"first index out of range\", GSL_EINVAL) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_VOID(\"second index out of range\", GSL_EINVAL) ;\n        }\n    }\n#endif\n  m->data[i * m->tda + j] = x ;\n}\n\nINLINE_FUN \nint *\ngsl_matrix_int_ptr(gsl_matrix_int * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n        }\n    }\n#endif\n  return (int *) (m->data + (i * m->tda + j)) ;\n} \n\nINLINE_FUN \nconst int *\ngsl_matrix_int_const_ptr(const gsl_matrix_int * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n        }\n    }\n#endif\n  return (const int *) (m->data + (i * m->tda + j)) ;\n} \n\n#endif\n\n__END_DECLS\n\n#endif /* __GSL_MATRIX_INT_H__ */\n", "meta": {"hexsha": "a9b04c1b3e2df956b4b0f019b163f962b5384755", "size": 11845, "ext": "h", "lang": "C", "max_stars_repo_path": "gsl-an/gsl/gsl_matrix_int.h", "max_stars_repo_name": "juandesant/astrometry.net", "max_stars_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_stars_repo_licenses": ["Net-SNMP", "Xnet"], "max_stars_count": 460.0, "max_stars_repo_stars_event_min_datetime": "2015-01-06T13:20:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T00:37:55.000Z", "max_issues_repo_path": "gsl-an/gsl/gsl_matrix_int.h", "max_issues_repo_name": "juandesant/astrometry.net", "max_issues_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_issues_repo_licenses": ["Net-SNMP", "Xnet"], "max_issues_count": 208.0, "max_issues_repo_issues_event_min_datetime": "2015-01-08T20:26:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T15:21:34.000Z", "max_forks_repo_path": "gsl-an/gsl/gsl_matrix_int.h", "max_forks_repo_name": "juandesant/astrometry.net", "max_forks_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_forks_repo_licenses": ["Net-SNMP", "Xnet"], "max_forks_count": 173.0, "max_forks_repo_forks_event_min_datetime": "2015-01-08T18:01:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T07:27:04.000Z", "avg_line_length": 33.7464387464, "max_line_length": 120, "alphanum_fraction": 0.6414520895, "num_tokens": 2900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618627863437, "lm_q2_score": 0.0433658004638956, "lm_q1q2_score": 0.019656063499486207}}
{"text": "/* ieee-utils/fp-x86linux.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#include <stdio.h>\n#include <fpu_control.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_ieee_utils.h>\n\n  /* Handle libc5, where _FPU_SETCW is not available, suggested by\n     OKUJI Yoshinori <okuji@gnu.org> and Evgeny Stambulchik\n     <fnevgeny@plasma-gate.weizmann.ac.il> */\n\n#ifndef _FPU_SETCW\n#include <i386/fpu_control.h>\n#define _FPU_SETCW(cw) __setfpucw(cw)\n#endif\n\nint\ngsl_ieee_set_mode (int precision, int rounding, int exception_mask)\n{\n  unsigned short mode = 0 ;\n\n  switch (precision)\n    {\n    case GSL_IEEE_SINGLE_PRECISION:\n      mode |= _FPU_SINGLE ;\n      break ;\n    case GSL_IEEE_DOUBLE_PRECISION:\n      mode |= _FPU_DOUBLE ;\n      break ;\n    case GSL_IEEE_EXTENDED_PRECISION:\n      mode |= _FPU_EXTENDED ;\n      break ;\n    default:\n      mode |= _FPU_EXTENDED ;\n    }\n\n  switch (rounding)\n    {\n    case GSL_IEEE_ROUND_TO_NEAREST:\n      mode |= _FPU_RC_NEAREST ;\n      break ;\n    case GSL_IEEE_ROUND_DOWN:\n      mode |= _FPU_RC_DOWN ;\n      break ;\n    case GSL_IEEE_ROUND_UP:\n      mode |= _FPU_RC_UP ;\n      break ;\n    case GSL_IEEE_ROUND_TO_ZERO:\n      mode |= _FPU_RC_ZERO ;\n      break ;\n    default:\n      mode |= _FPU_RC_NEAREST ;\n    }\n\n  if (exception_mask & GSL_IEEE_MASK_INVALID)\n    mode |= _FPU_MASK_IM ;\n\n  if (exception_mask & GSL_IEEE_MASK_DENORMALIZED)\n    mode |= _FPU_MASK_DM ;\n\n  if (exception_mask & GSL_IEEE_MASK_DIVISION_BY_ZERO)\n    mode |= _FPU_MASK_ZM ;\n\n  if (exception_mask & GSL_IEEE_MASK_OVERFLOW)\n    mode |= _FPU_MASK_OM ;\n\n  if (exception_mask & GSL_IEEE_MASK_UNDERFLOW)\n    mode |= _FPU_MASK_UM ;\n\n  if (exception_mask & GSL_IEEE_TRAP_INEXACT)\n    {\n      mode &= ~ _FPU_MASK_PM ;\n    }\n  else\n    {\n      mode |= _FPU_MASK_PM ;\n    }\n\n  _FPU_SETCW(mode) ;\n\n  return GSL_SUCCESS ;\n}\n", "meta": {"hexsha": "4e0c1d574e5da601368ca0b074393008ec91148b", "size": 2539, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/ieee-utils/fp-x86linux.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/ieee-utils/fp-x86linux.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/ieee-utils/fp-x86linux.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 25.39, "max_line_length": 72, "alphanum_fraction": 0.6857030327, "num_tokens": 718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.044018651900878066, "lm_q1q2_score": 0.01961160951446701}}
{"text": "/**\n * original author: Jochen K\"upper\n * author: Pierre Schnizer\n * created: Jan 2002\n * modified: May 2009\n * file: pygsl/src/statistics/longmodule.c\n * $Id: charmodule.c,v 1.9 2009/05/11 08:53:03 schnizer Exp $\n *\n *\n *\"\n */\n\n\n#include <Python.h>\n#include <pygsl/error_helpers.h>\n#include <pygsl/block_helpers.h>\n#include <gsl/gsl_statistics.h>\n\n\n/* include real functions for different data-types */\n\n#define STATMOD_APPEND_PY_TYPE(X) X ## Int\n\n#if (defined PyGSL_NUMARRAY) || (defined PyGSL_NUMERIC)\n#define STATMOD_APPEND_PYC_TYPE(X) X ## CHAR\n#else /* PyGSL_NUMARRAY */ \n#define STATMOD_APPEND_PYC_TYPE(X) X ## BYTE\n#endif /* PyGSL_NUMARRAY */\n\n#define STATMOD_FUNC_EXT(X, Y) X ## _char ## Y\n#define STATMOD_PY_AS_C PyInt_AsLong\n#define STATMOD_C_TYPE char\n#include \"functions.c\"\n\n\n\n\nPyGSL_STATISTICS_INIT(char, \"char\")\n\n\n/*\n * Local Variables:\n * mode: c\n * c-file-style: \"python\"\n * End:\n */\n", "meta": {"hexsha": "d52f8777c1837f23d006a296762460d82ca828ea", "size": 901, "ext": "c", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/src/statistics/charmodule.c", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/src/statistics/charmodule.c", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/src/statistics/charmodule.c", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 19.170212766, "max_line_length": 61, "alphanum_fraction": 0.7058823529, "num_tokens": 268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3775406547908327, "lm_q2_score": 0.051845462987259734, "lm_q1q2_score": 0.019573770044143922}}
{"text": "#ifndef CPP_MICROBENCH_BENCH_OUTPUT_H\n#define CPP_MICROBENCH_BENCH_OUTPUT_H\n\n#include <string>\n#include <chrono>\n#include <fstream>\n#include <iomanip>\n\n#include <fmt/os.h>\n#include <fmt/ostream.h>\n#include <fmt/chrono.h>\n\n#include <gsl/util>\n\n#include \"util/aligned_vector.hpp\"\n#include \"util/alloc_array.hpp\"\n#include \"util/trivial_aligned_array.hpp\"\n#include \"util/plain_array.hpp\"\n\ntemplate <typename array_type>\nauto generate_array(std::size_t max) {\n  using namespace std::chrono;\n  auto t1 = high_resolution_clock::now();\n  array_type v(max);\n  auto t2 = high_resolution_clock::now();\n  for (std::size_t i = 0; i < max; ++i) {\n    v[i] = 1.0F / gsl::narrow_cast<float>(i+1);\n  }\n  auto t3 = high_resolution_clock::now();\n  fmt::print(\"Create: {}\\n\", duration_cast<microseconds>(t2-t1));\n  fmt::print(\"Fill: {}\\n\", duration_cast<microseconds>(t3-t2));\n  return v;\n}\n\ntemplate <typename vector_type>\nauto generate_vector(std::size_t max) {\n  using namespace std::chrono;\n  auto t1 = high_resolution_clock::now();\n  vector_type v;\n  v.reserve(max);\n  auto t2 = high_resolution_clock::now();\n  for (std::size_t i = 0; i < max; ++i) {\n    v.push_back(1.0F / gsl::narrow_cast<float>(i+1));\n  }\n  auto t3 = high_resolution_clock::now();\n  fmt::print(\"Create: {}\\n\", duration_cast<microseconds>(t2-t1));\n  fmt::print(\"Fill: {}\\n\", duration_cast<microseconds>(t3-t2));\n  return v;\n}\n\nvoid fmt_output_vector(const auto & v) {\n  auto file_name = std::string(static_cast<const char *>(__func__)) + \".txt\";\n  auto file = fmt::output_file(file_name);\n  file.print(\"{}\\n\", v.size());\n\n  for (const auto & x : v) {\n    file.print(\"{:.18f}\\n\", x);\n  }\n}\n\nvoid stream_output_vector(const auto & v) {\n  auto file_name = std::string(static_cast<const char *>(__func__)) + \".txt\";\n  std::ofstream file{file_name};\n  file << v.size() << '\\n';\n\n  for (const auto & x : v) {\n    file << std::setprecision(18) << x << '\\n';\n  }\n}\n\ntemplate <typename array_type>\nauto bench_fmt_output_array(std::size_t n) {\n  using namespace std::chrono;\n\n  auto t1 = high_resolution_clock::now();\n  auto v = generate_array<array_type>(n);\n  auto t2 = high_resolution_clock::now();\n  fmt_output_vector(v);\n  auto t3 = high_resolution_clock::now();\n\n  return std::tuple {__func__, t2 - t1, t3 - t2};\n}\n\ntemplate <typename vector_type>\nauto bench_fmt_output_vector(std::size_t n) {\n  using namespace std::chrono;\n\n  auto t1 = high_resolution_clock::now();\n  auto v = generate_vector<vector_type>(n);\n  auto t2 = high_resolution_clock::now();\n  fmt_output_vector(v);\n  auto t3 = high_resolution_clock::now();\n\n  return std::tuple {__func__, t2 - t1, t3 - t2};\n}\n\ntemplate <typename vector_type>\nauto bench_stream_vector(std::size_t n) {\n  using namespace std::chrono;\n\n  auto t1 = high_resolution_clock::now();\n  auto v = generate_vector<vector_type>(n);\n  auto t2 = high_resolution_clock::now();\n  stream_output_vector(v);\n  auto t3 = high_resolution_clock::now();\n\n  return std::tuple {__func__, t2 - t1, t3 - t2};\n}\n\n\nvoid print_bench(auto t) {\n  using namespace std::chrono;\n  auto d1 = duration_cast<microseconds>(std::get<1>(t));\n  auto d2 = duration_cast<microseconds>(std::get<2>(t));\n  fmt::print(\"\\nVersion: {}\\n\", std::get<0>(t));\n  fmt::print(\"Generation {} us\\n\", d1.count());\n  fmt::print(\"Writing {} us\\n\", d2.count());\n}\n\n#endif//CPP_MICROBENCH_BENCH_OUTPUT_H\n", "meta": {"hexsha": "f8c1734452602881814a119e8b20bc9494329201", "size": 3337, "ext": "h", "lang": "C", "max_stars_repo_path": "gen-floats/bench_output.h", "max_stars_repo_name": "jdgarciauc3m/cpp-microbench", "max_stars_repo_head_hexsha": "c764d5fe5d376324e9c0074e88f79c288fc4afc8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gen-floats/bench_output.h", "max_issues_repo_name": "jdgarciauc3m/cpp-microbench", "max_issues_repo_head_hexsha": "c764d5fe5d376324e9c0074e88f79c288fc4afc8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gen-floats/bench_output.h", "max_forks_repo_name": "jdgarciauc3m/cpp-microbench", "max_forks_repo_head_hexsha": "c764d5fe5d376324e9c0074e88f79c288fc4afc8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5785123967, "max_line_length": 77, "alphanum_fraction": 0.6817500749, "num_tokens": 965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2814055953761018, "lm_q2_score": 0.0695417406490685, "lm_q1q2_score": 0.01956943493084158}}
{"text": "/* histogram/get2d.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#include <config.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_histogram2d.h>\n\n#include \"find.c\"\n\ndouble\ngsl_histogram2d_get (const gsl_histogram2d * h, const size_t i, const size_t j)\n{\n  const size_t nx = h->nx;\n  const size_t ny = h->ny;\n\n  if (i >= nx)\n    {\n      GSL_ERROR_VAL (\"index i lies outside valid range of 0 .. nx - 1\",\n\t\t\tGSL_EDOM, 0);\n    }\n\n  if (j >= ny)\n    {\n      GSL_ERROR_VAL (\"index j lies outside valid range of 0 .. ny - 1\",\n\t\t\tGSL_EDOM, 0);\n    }\n\n  return h->bin[i * ny + j];\n}\n\nint\ngsl_histogram2d_get_xrange (const gsl_histogram2d * h, const size_t i,\n\t\t\t    double *xlower, double *xupper)\n{\n  const size_t nx = h->nx;\n\n  if (i >= nx)\n    {\n      GSL_ERROR (\"index i lies outside valid range of 0 .. nx - 1\", GSL_EDOM);\n    }\n\n  *xlower = h->xrange[i];\n  *xupper = h->xrange[i + 1];\n\n  return GSL_SUCCESS;\n}\n\nint\ngsl_histogram2d_get_yrange (const gsl_histogram2d * h, const size_t j,\n\t\t\t    double *ylower, double *yupper)\n{\n  const size_t ny = h->ny;\n\n  if (j >= ny)\n    {\n      GSL_ERROR (\"index j lies outside valid range of 0 .. ny - 1\", GSL_EDOM);\n    }\n\n  *ylower = h->yrange[j];\n  *yupper = h->yrange[j + 1];\n\n  return GSL_SUCCESS;\n}\n\nint\ngsl_histogram2d_find (const gsl_histogram2d * h,\n\t\t      const double x, const double y,\n\t\t      size_t * i, size_t * j)\n{\n  int status = find (h->nx, h->xrange, x, i);\n\n  if (status)\n    {\n      GSL_ERROR (\"x not found in range of h\", GSL_EDOM);\n    }\n\n  status = find (h->ny, h->yrange, y, j);\n\n  if (status)\n    {\n      GSL_ERROR (\"y not found in range of h\", GSL_EDOM);\n    }\n\n  return GSL_SUCCESS;\n}\n", "meta": {"hexsha": "88a08e2917f93b3fd9e785c3b393c0e6306fbe80", "size": 2376, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/histogram/get2d.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/histogram/get2d.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/histogram/get2d.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 23.2941176471, "max_line_length": 79, "alphanum_fraction": 0.6435185185, "num_tokens": 721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39981165504266236, "lm_q2_score": 0.048857782950095914, "lm_q1q2_score": 0.019533911062993018}}
{"text": "/* $Id$      */\n/*--------------------------------------------------------------------*/\n/*;  Copyright (C) 2013-2020                                          */\n/*;  Associated Universities, Inc. Washington DC, USA.                */\n/*;                                                                   */\n/*;  This program is free software; you can redistribute it and/or    */\n/*;  modify it under the terms of the GNU General Public License as   */\n/*;  published by the Free Software Foundation; either version 2 of   */\n/*;  the License, or (at your option) any later version.              */\n/*;                                                                   */\n/*;  This program is distributed in the hope that it will be useful,  */\n/*;  but WITHOUT ANY WARRANTY; without even the implied warranty of   */\n/*;  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the    */\n/*;  GNU General Public License for more details.                     */\n/*;                                                                   */\n/*;  You should have received a copy of the GNU General Public        */\n/*;  License along with this program; if not, write to the Free       */\n/*;  Software Foundation, Inc., 675 Massachusetts Ave, Cambridge,     */\n/*;  MA 02139, USA.                                                   */\n/*;                                                                   */\n/*;Correspondence about this software should be addressed as follows: */\n/*;         Internet email: bcotton@nrao.edu.                         */\n/*;         Postal address: William Cotton                            */\n/*;                         National Radio Astronomy Observatory      */\n/*;                         520 Edgemont Road                         */\n/*;                         Charlottesville, VA 22903-2475 USA        */\n/*--------------------------------------------------------------------*/\n\n#include \"ObitRMFit.h\"\n#include \"ObitThread.h\"\n#include \"ObitSinCos.h\"\n#ifdef HAVE_GSL\n#include <gsl/gsl_blas.h>\n#endif /* HAVE_GSL */ \n#ifndef VELIGHT\n#define VELIGHT 2.997924562e8\n#endif /* VELIGHT */\n/*----------------Obit: Merx mollis mortibus nuper ------------------*/\n/**\n * \\file ObitRMFit.c\n * ObitRMFit class function definitions.\n * This class is derived from the Obit base class.\n */\n\n/** name of the class defined in this file */\nstatic gchar *myClassName = \"ObitRMFit\";\n\n/** Function to obtain parent ClassInfo */\nstatic ObitGetClassFP ObitParentGetClass = ObitGetClass;\n\n/**\n * ClassInfo structure ObitRMFitClassInfo.\n * This structure is used by class objects to access class functions.\n */\nstatic ObitRMFitClassInfo myClassInfo = {FALSE};\n\n/*--------------- File Global Variables  ----------------*/\n\n\n/*---------------Private function prototypes----------------*/\n/** Private: Initialize newly instantiated object. */\nvoid  ObitRMFitInit  (gpointer in);\n\n/** Private: Deallocate members. */\nvoid  ObitRMFitClear (gpointer in);\n\n/** Private: Set Class function pointers. */\nstatic void ObitRMFitClassInfoDefFn (gpointer inClass);\n\n/** Private: Do actual fitting */\nstatic void Fitter (ObitRMFit* in, ObitErr *err);\n\n/** Private: Write output image */\nstatic void WriteOutput (ObitRMFit* in, ObitImage *outImage, \n\t\t\t ObitErr *err);\n\n\n#ifdef HAVE_GSL\n/** Private: Solver function evaluation */\nstatic int RMFitFunc (const gsl_vector *x, void *params, \n\t\t      gsl_vector *f);\n\n/** Private: Solver Jacobian evaluation */\nstatic int RMFitJac (const gsl_vector *x, void *params, \n\t\t     gsl_matrix *J);\n\n/** Private: Solver function + Jacobian evaluation */\nstatic int RMFitFuncJac (const gsl_vector *x, void *params, \n\t\t\t gsl_vector *f, gsl_matrix *J);\n\n#endif /* HAVE_GSL */ \n\n/** Private: Threaded fitting */\nstatic gpointer ThreadNLRMFit (gpointer arg);\n\n/** Private: Threaded RM synthesis fitting */\nstatic gpointer ThreadRMSynFit (gpointer arg);\n\n/*---------------Private structures----------------*/\n/* FT threaded function argument */\ntypedef struct {\n  /** ObitRMFit object */\n  ObitRMFit *in;\n  /* Obit error stack object */\n  ObitErr      *err;\n  /** First (1-rel) value in y to process this thread */\n  olong        first;\n  /** Highest (1-rel) value in y to process this thread  */\n  olong        last;\n  /** thread number, >0 -> no threading   */\n  olong        ithread;\n  /** max number of terms to fit  */\n  olong        nterm;\n  /** number of frequencies  */\n  olong        nlamb2;\n  /** number of valid data points in x, q, u, w  */\n  olong        nvalid;\n  /** maximum iteration  */\n  olong        maxIter;\n  /** acceptable iteration delta, rel and abs. */\n  odouble minDelta;\n  /** Array of Lambda^2 (nlamb2) */\n  ofloat *lamb2;\n  /** Array of Q, U weights (1/RMS) per inFArrays (nlamb2) */\n  ofloat *Qweight, *Uweight;\n  /** Array of Q, U variance per inFArrays (nlamb2) */\n  ofloat *Qvar, *Uvar;\n  /** Array of Q, U pixel values being fitted (nlamb2) */\n  ofloat *Qobs, *Uobs;\n  /** Array of polarized intensity pixel values being fitted (nlamb2) */\n  ofloat *Pobs;\n  /** min Q/U SNR */\n  ofloat minQUSNR;\n  /** min fraction of valid samples */\n  ofloat minFrac;\n  /** Reference lambda^2 */\n  ofloat refLamb2;\n  /** Vector of guess/fitted coefficients, optional errors */\n  ofloat *coef;\n  /** Chi squared of fit */\n  ofloat ChiSq;\n  /** Do error analysis? */\n  gboolean doError;\n  /** work arrays */\n  double *x, *q, *u, *w;\n  ofloat *wrk1, *wrk2, *wrk3;\n#ifdef HAVE_GSL\n  /** Fitting solver  */\n  gsl_multifit_fdfsolver *solver;\n  /** Fitting solver function structure */\n  gsl_multifit_function_fdf *funcStruc;\n  /** Fitting work vector */\n  gsl_vector *work;\n  /** Covariance matrix */\n  gsl_matrix *covar;\n#endif /* HAVE_GSL */ \n} NLRMFitArg;\n\n/** Private: Actual fitting */\nstatic void NLRMFit (NLRMFitArg *arg);\n\n/** Private: coarse search */\nstatic olong RMcoarse (NLRMFitArg *arg);\n\n/*----------------------Public functions---------------------------*/\n/**\n * Constructor.\n * Initializes class if needed on first call.\n * \\param name An optional name for the object.\n * \\return the new object.\n */\nObitRMFit* newObitRMFit (gchar* name)\n{\n  ObitRMFit* out;\n  ofloat s, c;\n\n  /* Class initialization if needed */\n  if (!myClassInfo.initialized) ObitRMFitClassInit();\n\n  /* allocate/init structure */\n  out = g_malloc0(sizeof(ObitRMFit));\n\n  /* initialize values */\n  if (name!=NULL) out->name = g_strdup(name);\n  else out->name = g_strdup(\"Noname\");\n\n  /* set ClassInfo */\n  out->ClassInfo = (gpointer)&myClassInfo;\n\n  /* initialize other stuff */\n  ObitRMFitInit((gpointer)out);\n  ObitSinCosCalc(0.0, &s, &c);    /* Sine/cosine functions */\n\n  return out;\n} /* end newObitRMFit */\n\n/**\n * Returns ClassInfo pointer for the class.\n * \\return pointer to the class structure.\n */\ngconstpointer ObitRMFitGetClass (void)\n{\n  /* Class initialization if needed */\n  if (!myClassInfo.initialized) ObitRMFitClassInit();\n\n  return (gconstpointer)&myClassInfo;\n} /* end ObitRMFitGetClass */\n\n/**\n * Make a deep copy of an ObitRMFit.\n * \\param in  The object to copy\n * \\param out An existing object pointer for output or NULL if none exists.\n * \\param err Obit error stack object.\n * \\return pointer to the new object.\n */\nObitRMFit* ObitRMFitCopy  (ObitRMFit *in, ObitRMFit *out, ObitErr *err)\n{\n  const ObitClassInfo *ParentClass;\n  gboolean oldExist;\n  gchar *outName;\n  olong i, nOut;\n\n  /* error checks */\n  if (err->error) return out;\n  g_assert (ObitIsA(in, &myClassInfo));\n  if (out) g_assert (ObitIsA(out, &myClassInfo));\n\n  /* Create if it doesn't exist */\n  oldExist = out!=NULL;\n  if (!oldExist) {\n    /* derive object name */\n    outName = g_strconcat (\"Copy: \",in->name,NULL);\n    out = newObitRMFit(outName);\n    g_free(outName);\n  }\n\n  /* deep copy any base class members */\n  ParentClass = myClassInfo.ParentClass;\n  g_assert ((ParentClass!=NULL) && (ParentClass->ObitCopy!=NULL));\n  ParentClass->ObitCopy (in, out, err);\n\n  /*  copy this class */\n  out->nlamb2 = in->nlamb2;\n  out->nterm = in->nterm;\n\n  /* Arrays */\n  if (out->QRMS) g_free(out->QRMS);\n  out->QRMS = g_malloc0(out->nlamb2*sizeof(ofloat));\n  if (in->QRMS)\n    for (i=0; i<out->nlamb2; i++) out->QRMS[i] = in->QRMS[i];\n  if (out->URMS) g_free(out->URMS);\n  out->URMS = g_malloc0(out->nlamb2*sizeof(ofloat));\n  if (in->URMS)\n    for (i=0; i<out->nlamb2; i++) out->URMS[i] = in->URMS[i];\n    \n  /* reference this class members */\n  if (out->outDesc) out->outDesc = ObitImageDescUnref(out->outDesc);\n  if (in->outDesc)  out->outDesc = ObitImageDescRef(in->outDesc);\n  if (out->inQFArrays) {\n    for (i=0; i<in->nlamb2; i++) out->inQFArrays[i] = ObitFArrayUnref(out->inQFArrays[i]);\n  }\n  if (in->inQFArrays) {\n    for (i=0; i<in->nlamb2; i++) out->inQFArrays[i] = ObitFArrayRef(in->inQFArrays[i]);\n  }\n  if (out->inUFArrays) {\n    for (i=0; i<in->nlamb2; i++) out->inUFArrays[i] = ObitFArrayUnref(out->inUFArrays[i]);\n  }\n  if (in->inUFArrays) {\n    for (i=0; i<in->nlamb2; i++) out->inUFArrays[i] = ObitFArrayRef(in->inUFArrays[i]);\n  }\n\n\n  /* How many output planes */\n  if (in->doError) nOut = 1+in->nterm*2;\n  else nOut = in->nterm;\n  if (out->outFArrays) {\n    for (i=0; i<nOut; i++) out->outFArrays[i] = ObitFArrayUnref(out->outFArrays[i]);\n  }\n  if (in->outFArrays) {\n    for (i=0; i<nOut; i++) out->outFArrays[i] = ObitFArrayRef(in->outFArrays[i]);\n  }\n\n  return out;\n} /* end ObitRMFitCopy */\n\n/**\n * Make a copy of a object but do not copy the actual data\n * This is useful to create an RMFit similar to the input one.\n * \\param in  The object to copy\n * \\param out An existing object pointer for output, must be defined.\n * \\param err Obit error stack object.\n */\nvoid ObitRMFitClone  (ObitRMFit *in, ObitRMFit *out, ObitErr *err)\n{\n  const ObitClassInfo *ParentClass;\n  olong i, nOut;\n\n  /* error checks */\n  g_assert (ObitErrIsA(err));\n  if (err->error) return;\n  g_assert (ObitIsA(in, &myClassInfo));\n  g_assert (ObitIsA(out, &myClassInfo));\n\n  /* deep copy any base class members */\n  ParentClass = myClassInfo.ParentClass;\n  g_assert ((ParentClass!=NULL) && (ParentClass->ObitCopy!=NULL));\n  ParentClass->ObitCopy (in, out, err);\n\n  /*  copy this class */\n  out->nlamb2 = in->nlamb2;\n  out->nterm = in->nterm;\n  \n  /* Arrays */\n  if (out->QRMS) g_free(out->QRMS);\n  out->QRMS = g_malloc0(out->nlamb2*sizeof(ofloat));\n  if (in->QRMS)\n    for (i=0; i<out->nlamb2; i++) out->QRMS[i] = in->QRMS[i];\n  if (out->URMS) g_free(out->URMS);\n  out->URMS = g_malloc0(out->nlamb2*sizeof(ofloat));\n  if (in->URMS)\n    for (i=0; i<out->nlamb2; i++) out->URMS[i] = in->URMS[i];\n\n  /* reference this class members */\n  if (out->outDesc) out->outDesc = ObitImageDescUnref(out->outDesc);\n  if (in->outDesc)  out->outDesc = ObitImageDescRef(in->outDesc);\n  if (out->inQFArrays) {\n    for (i=0; i<in->nlamb2; i++) out->inQFArrays[i] = ObitFArrayUnref(out->inQFArrays[i]);\n  }\n  if (in->inQFArrays) {\n    for (i=0; i<in->nlamb2; i++) out->inQFArrays[i] = ObitFArrayRef(in->inQFArrays[i]);\n  }\n  if (out->inUFArrays) {\n    for (i=0; i<in->nlamb2; i++) out->inUFArrays[i] = ObitFArrayUnref(out->inUFArrays[i]);\n  }\n  if (in->inUFArrays) {\n    for (i=0; i<in->nlamb2; i++) out->inUFArrays[i] = ObitFArrayRef(in->inUFArrays[i]);\n  }\n\n  /* How many output planes */\n  if (in->doError) nOut = 1+in->nterm*2;\n  else nOut = in->nterm;\n  if (out->outFArrays) {\n    for (i=0; i<nOut; i++) out->outFArrays[i] = ObitFArrayUnref(out->outFArrays[i]);\n  }\n  if (in->outFArrays) {\n    for (i=0; i<nOut; i++) out->outFArrays[i] = ObitFArrayRef(in->outFArrays[i]);\n  }\n\n} /* end ObitRMFitClone */\n\n/**\n * Creates an ObitRMFit \n * \\param name   An optional name for the object.\n * \\param nterm  Number of coefficients of powers of log(nu)\n * \\return the new object.\n */\nObitRMFit* ObitRMFitCreate (gchar* name, olong nterm)\n{\n  ObitRMFit* out;\n\n  /* Create basic structure */\n  out = newObitRMFit (name);\n  out->nterm = nterm;\n\n  return out;\n} /* end ObitRMFitCreate */\n\n/**\n * Fit RM to an image cube pixels.\n * The third axis of the output image will be \"SPECRM  \" to indicate that the\n * planes are RM fit parameters.  The \"CRVAL\" on this axis will be the reference \n * Frequency for the fitting.\n * Item \"NTERM\" is added to the output image descriptor\n * \\param in       Spectral fitting object\n *                 Potential parameters on in->info:\n * \\li \"refLamb2\" OBIT_double scalar Reference frequency for fit [def ref for inQImage]\n * \\li \"minQUSNR\" OBIT_float  scalar min. SNR for Q and U pixels [def 3.0]\n * \\li \"minFrac\"  OBIT_float  scalar min. fraction of planes included [def 0.5]\n * \\li \"doError\"  OBIT_boolean scalar If true do error analysis [def False]\n * \\li \"doRMSyn\"  OBIT_boolean scalar If true do max RM synthesis [def False]\n * \\li \"maxRMSyn\" OBIT_float scalar max RM to search (rad/m^2) [def ambiguity]\n * \\li \"minRMSyn\" OBIT_float scalar min RM to search (rad/m^2)[def -ambiguity]\n * \\li \"delRMSyn\" OBIT_float scalar RM increment for search (rad/m^2)[def 1.0]\n * \\li \"maxChi2\"  OBIT_float scalar max Chi^2 for search [def 10.0]\n *\n * \\param inQImage Q Image cube to be fitted\n * \\param inUImage U Image cube to be fitted\n * \\param outImage Image cube with fitted spectra.\n *                 Should be defined but not created.\n *                 Planes 1->nterm are coefficients per pixel\n *                 if doError:\n *                 Planes nterm+1->2*nterm are uncertainties in coefficients\n *                 Plane 2*nterm+1 = Chi squared of fit\n *                 if do RMsyn, planes are 1=RM, 2=EVPA@0 lambda, 3=amp@0 lambda, 4=sum wt.\n * \\param err      Obit error stack object.\n */\nvoid ObitRMFitCube (ObitRMFit* in, ObitImage *inQImage, ObitImage *inUImage, \n\t\t    ObitImage *outImage, ObitErr *err)\n{\n  olong i, iplane, nOut, plane[5]={1,1,1,1,1}, noffset=0;\n  olong naxis[2];\n  ObitIOSize IOBy;\n  ObitInfoType type;\n  ObitIOCode retCode;\n  union ObitInfoListEquiv InfoReal; \n  gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};\n  odouble freq;\n  gchar *today=NULL, *SPECRM   = \"SPECRM  \", *MaxRMSyn   = \"MaxRMSyn\", keyword[9];\n  ObitHistory *inHist=NULL, *outHist=NULL;\n  gchar hiCard[73], *TF[2]={\"False\",\"True\"};\n  gchar *routine = \"ObitRMFitCube\";\n\n  /* error checks */\n  if (err->error) return;\n  g_assert (ObitIsA(in, &myClassInfo));\n  g_assert(ObitImageIsA(inQImage));\n  g_assert(ObitImageIsA(inUImage));\n  g_assert(ObitImageIsA(outImage));\n\n  /* Warn if no GSL implementation */\n#ifndef HAVE_GSL\n  Obit_log_error(err, OBIT_InfoWarn, \"NO GSL available - results will be approximate\");\n#endif\n\n  /* Control parameters */\n  /* Min Q/U pixel SNR for fit */\n  InfoReal.flt = 3.0; type = OBIT_float;\n  in->minQUSNR = 3.0;\n  ObitInfoListGetTest(in->info, \"minQUSNR\", &type, dim, &InfoReal);\n  if (type==OBIT_float) in->minQUSNR = InfoReal.flt;\n  else if (type==OBIT_double) in->minQUSNR = (ofloat)InfoReal.dbl;\n\n  /* Min fraction of planes in the fit */\n  InfoReal.flt = 0.5; type = OBIT_float;\n  in->minFrac  = 0.5;\n  ObitInfoListGetTest(in->info, \"minFrac\", &type, dim, &InfoReal);\n  if (type==OBIT_float) in->minFrac = InfoReal.flt;\n  else if (type==OBIT_double) in->minFrac = (ofloat)InfoReal.dbl;\n\n  /* Want Error analysis? */\n  InfoReal.itg = (olong)FALSE; type = OBIT_bool;\n  ObitInfoListGetTest(in->info, \"doError\", &type, dim, &InfoReal);\n  in->doError = InfoReal.itg;\n\n  /* Want max RM Synthesis? */\n  InfoReal.itg = (olong)FALSE; type = OBIT_bool;\n  ObitInfoListGetTest(in->info, \"doRMSyn\", &type, dim, &InfoReal);\n  in->doRMSyn = InfoReal.itg;\n  if (in->doRMSyn) Obit_log_error(err, OBIT_InfoErr, \"Using Max RM Synthesis\");\n\n  /*  Max RM for RM syn search */\n  InfoReal.flt = 0.0; type = OBIT_float;\n  in->maxRMSyn  = 0.0;\n  ObitInfoListGetTest(in->info, \"maxRMSyn\", &type, dim, &InfoReal);\n  if (type==OBIT_float)       in->maxRMSyn = InfoReal.flt;\n  else if (type==OBIT_double) in->maxRMSyn = (ofloat)InfoReal.dbl;\n\n  /*  Min RM for RM syn search */\n  InfoReal.flt = 1.0; type = OBIT_float;\n  in->minRMSyn = 1.0;\n  ObitInfoListGetTest(in->info, \"minRMSyn\", &type, dim, &InfoReal);\n  if (type==OBIT_float)       in->minRMSyn = InfoReal.flt;\n  else if (type==OBIT_double) in->minRMSyn = (ofloat)InfoReal.dbl;\n\n  /* Delta RM for RM syn search */\n  InfoReal.flt = 1.0; type = OBIT_float;\n  in->delRMSyn = 1.0;\n  ObitInfoListGetTest(in->info, \"delRMSyn\", &type, dim, &InfoReal);\n  if (type==OBIT_float)       in->delRMSyn = InfoReal.flt;\n  else if (type==OBIT_double) in->delRMSyn = (ofloat)InfoReal.dbl;\n\n  /* maxChi2 for RM syn search */\n  InfoReal.flt = 10.0; type = OBIT_float;\n  in->maxChi2  = 10.0;\n  ObitInfoListGetTest(in->info, \"maxChi2\", &type, dim, &InfoReal);\n  if (type==OBIT_float)       in->maxChi2 = InfoReal.flt;\n  else if (type==OBIT_double) in->maxChi2 = (ofloat)InfoReal.dbl;\n\n  /* Open input images to get info */\n  IOBy = OBIT_IO_byPlane;\n  dim[0] = 1;\n  ObitInfoListAlwaysPut (inQImage->info, \"IOBy\", OBIT_long, dim, &IOBy);\n  inQImage->extBuffer = TRUE;   /* Using inFArrays as I/O buffer */\n  retCode = ObitImageOpen (inQImage, OBIT_IO_ReadOnly, err);\n  if ((retCode!=OBIT_IO_OK) || (err->error)) \n    Obit_traceback_msg (err, routine, inQImage->name);\n  ObitInfoListAlwaysPut (inUImage->info, \"IOBy\", OBIT_long, dim, &IOBy);\n  inUImage->extBuffer = TRUE;   /* Using inFArrays as I/O buffer */\n  retCode = ObitImageOpen (inUImage, OBIT_IO_ReadOnly, err);\n  if ((retCode!=OBIT_IO_OK) || (err->error)) \n    Obit_traceback_msg (err, routine, inUImage->name);\n\n  /* Check compatability */\n  Obit_return_if_fail(((inQImage->myDesc->inaxes[0]==inUImage->myDesc->inaxes[0]) && \n\t\t       (inQImage->myDesc->inaxes[1]==inUImage->myDesc->inaxes[1]) &&\n\t\t       (inQImage->myDesc->inaxes[2]==inUImage->myDesc->inaxes[2])), err,\n\t\t      \"%s: Input images incompatable\", routine);\n\n  /* Get Reference frequency/lambda^2 , default from input Q ref. freq. */\n  InfoReal.dbl = VELIGHT/inQImage->myDesc->crval[inQImage->myDesc->jlocf]; \n  InfoReal.dbl *= InfoReal.dbl;\n  type = OBIT_double;\n  in->refLamb2 = InfoReal.dbl;\n  ObitInfoListGetTest(in->info, \"refLamb2\", &type, dim, &InfoReal);\n  if (type==OBIT_float) in->refLamb2 = InfoReal.flt;\n  else if (type==OBIT_double) in->refLamb2 = (ofloat)InfoReal.dbl;\n  in->refLamb2 = MAX (1.0e-10, in->refLamb2); /* Avoid zero divide */\n  \n  /* What plane does spectral data start on */\n  if (!strncmp(inQImage->myDesc->ctype[inQImage->myDesc->jlocf], \"SPECLNMF\", 8)) {\n    noffset = 2;  /* What plane does spectral data start on */\n    ObitInfoListGetTest (inQImage->myDesc->info, \"NTERM\", &type, dim, &noffset);\n  } else {   /* Normal spectral cube */\n    noffset = 0;\n  }\n\n  /* Determine number of frequency planes and initialize in */\n  in->nlamb2     = inQImage->myDesc->inaxes[inQImage->myDesc->jlocf]-noffset;\n  in->QRMS       = g_malloc0(in->nlamb2*sizeof(ofloat));\n  in->URMS       = g_malloc0(in->nlamb2*sizeof(ofloat));\n  in->inQFArrays = g_malloc0(in->nlamb2*sizeof(ObitFArray*));\n  in->inUFArrays = g_malloc0(in->nlamb2*sizeof(ObitFArray*));\n  in->lamb2      = g_malloc0(in->nlamb2*sizeof(odouble));\n\n  /* How many output planes? */\n  if (in->doError) nOut = 1+in->nterm*2;\n  else nOut = in->nterm;\n  /* always 4 for doRMSyn */\n  if (in->doRMSyn) nOut = 4;\n\n   /* Define term arrays */\n  in->outFArrays = g_malloc0((nOut)*sizeof(ObitFArray*));\n  for (i=0; i<nOut; i++) in->outFArrays[i] = NULL;\n\n /* Image size */\n  in->nx = inQImage->myDesc->inaxes[0];\n  in->ny = inQImage->myDesc->inaxes[1];\n  naxis[0] = (olong)in->nx;  naxis[1] = (olong)in->ny; \n  for (i=0; i<in->nlamb2; i++) in->inQFArrays[i] = ObitFArrayCreate (NULL, 2, naxis);\n  for (i=0; i<in->nlamb2; i++) in->inUFArrays[i] = ObitFArrayCreate (NULL, 2, naxis);\n  for (i=0; i<nOut; i++)       in->outFArrays[i] = ObitFArrayCreate (NULL, 2, naxis);\n\n  /* Output Image descriptor */\n  outImage->myDesc = ObitImageDescCopy (inQImage->myDesc, in->outDesc, err);\n  if (err->error) Obit_traceback_msg (err, routine, inQImage->name);\n\n  /* Change third axis to type \"SPECRM  \" and leave the reference frequency\n     as the \"CRVAL\" */\n  outImage->myDesc->inaxes[outImage->myDesc->jlocf] =  nOut;\n  outImage->myDesc->crval[outImage->myDesc->jlocf]  =  VELIGHT/sqrt(in->refLamb2);\n  outImage->myDesc->crpix[outImage->myDesc->jlocf]  =  1.0;\n  outImage->myDesc->cdelt[outImage->myDesc->jlocf]  =  1.0;\n  if (in->doRMSyn) strncpy (outImage->myDesc->ctype[outImage->myDesc->jlocf], MaxRMSyn, IMLEN_KEYWORD);\n  else             strncpy (outImage->myDesc->ctype[outImage->myDesc->jlocf], SPECRM ,  IMLEN_KEYWORD);\n  outImage->myDesc->bitpix = -32;  /* Float it */\n\n  /* Creation date today */\n  today = ObitToday();\n  strncpy (outImage->myDesc->date, today, IMLEN_VALUE);\n  if (today) g_free(today);\n\n  /* Copy of output descriptor to in */\n  in->outDesc = ObitImageDescCopy (outImage->myDesc, in->outDesc, err);\n\n  /* Loop reading planes */\n  for (iplane=0; iplane<in->nlamb2; iplane++) {\n    /* Lambda^2 Check for MFImage outputs */\n    if (!strncmp(inQImage->myDesc->ctype[inQImage->myDesc->jlocf], \"SPECLNMF\", 8)) {\n\tsprintf (keyword, \"FREQ%4.4d\",iplane+1);\n\tfreq = inQImage->myDesc->crval[inQImage->myDesc->jlocf] + \n\t  inQImage->myDesc->cdelt[inQImage->myDesc->jlocf] * \n\t  (inQImage->myDesc->plane - inQImage->myDesc->crpix[inQImage->myDesc->jlocf]);\n\tObitInfoListGetTest (inQImage->myDesc->info, keyword, &type, dim, &freq);\n       } else {   /* Normal spectral cube */\n\tfreq = inQImage->myDesc->crval[inQImage->myDesc->jlocf] + \n\t  inQImage->myDesc->cdelt[inQImage->myDesc->jlocf] * \n\t  (inQImage->myDesc->plane - inQImage->myDesc->crpix[inQImage->myDesc->jlocf]);\n      }\n    in->lamb2[iplane] = (VELIGHT/freq)*(VELIGHT/freq);\n\n    plane[0] = iplane+noffset+1;  /* Select correct plane */\n    retCode = ObitImageGetPlane (inQImage, in->inQFArrays[iplane]->array, plane, err);\n    retCode = ObitImageGetPlane (inUImage, in->inUFArrays[iplane]->array, plane, err);\n    /* if it didn't work bail out */\n    if ((retCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine, inQImage->name);\n\n    /* Plane RMSes */\n    in->QRMS[iplane] = ObitFArrayRMS(in->inQFArrays[iplane]);\n    in->URMS[iplane] = ObitFArrayRMS(in->inUFArrays[iplane]);\n\n    \n  } /* end loop reading planes */\n\n  /* Close inputs */\n  retCode = ObitImageClose (inQImage, err);\n  inQImage->extBuffer = FALSE;   /* May need I/O buffer later */\n  retCode = ObitImageClose (inUImage, err);\n  inUImage->extBuffer = FALSE;   /* May need I/O buffer later */\n  /* if it didn't work bail out */\n  if ((retCode!=OBIT_IO_OK) || (err->error)) \n    Obit_traceback_msg (err, routine, inQImage->name);\n\n  /* Do actual fitting */\n  Fitter (in, err);\n  if (err->error) Obit_traceback_msg (err, routine, inQImage->name);\n\n  /* Update output header to reference Frequency */\n  outImage->myDesc->crval[outImage->myDesc->jlocf] = VELIGHT/sqrt(in->refLamb2);\n  in->outDesc->crval[in->outDesc->jlocf] = VELIGHT/sqrt(in->refLamb2);\n\n  /* Write output */\n  WriteOutput(in, outImage, err);\n  if (err->error) Obit_traceback_msg (err, routine, inQImage->name);\n\n  /* History */\n  /* Copy any history */\n  inHist  = newObitDataHistory((ObitData*)inQImage, OBIT_IO_ReadOnly, err);\n  outHist = newObitDataHistory((ObitData*)outImage, OBIT_IO_WriteOnly, err);\n  outHist = ObitHistoryCopy (inHist, outHist, err);\n  /* Add parameters */\n  ObitHistoryOpen (outHist, OBIT_IO_ReadWrite, err);\n  ObitHistoryTimeStamp (outHist, \"ObitRMFitCube\", err);\n  g_snprintf ( hiCard, 72, \"RMCube  nterm = %d\",in->nterm);\n  ObitHistoryWriteRec (outHist, -1, hiCard, err);\n  g_snprintf ( hiCard, 72, \"RMCube  refLamb2 = %lf\",in->refLamb2);\n  ObitHistoryWriteRec (outHist, -1, hiCard, err);\n  g_snprintf ( hiCard, 72, \"RMCube  minQUSNR = %f\",in->minQUSNR);\n  ObitHistoryWriteRec (outHist, -1, hiCard, err);\n  g_snprintf ( hiCard, 72, \"RMCube  minFrac = %f\",in->minFrac);\n  ObitHistoryWriteRec (outHist, -1, hiCard, err);\n  g_snprintf ( hiCard, 72, \"RMCube  doRMSyn = %s\",TF[in->doRMSyn]);\n  ObitHistoryWriteRec (outHist, -1, hiCard, err);\n  if (in->doRMSyn) {\n    ObitHistoryWriteRec (outHist, -1, hiCard, err);\n    g_snprintf ( hiCard, 72, \"RMCube  maxRMSyn = %f\",in->maxRMSyn);\n    ObitHistoryWriteRec (outHist, -1, hiCard, err);\n    g_snprintf ( hiCard, 72, \"RMCube  minRMSyn = %f\",in->minRMSyn);\n    ObitHistoryWriteRec (outHist, -1, hiCard, err);\n    g_snprintf ( hiCard, 72, \"RMCube  delRMSyn = %f\",in->delRMSyn);\n    ObitHistoryWriteRec (outHist, -1, hiCard, err);\n    g_snprintf ( hiCard, 72, \"RMCube  maxChi2 = %f\", in->maxChi2);\n    ObitHistoryWriteRec (outHist, -1, hiCard, err);\n  } /* end doRMSyn */\n  ObitHistoryClose (outHist, err);\n  if (err->error) Obit_traceback_msg (err, routine, in->name);\n  inHist  = ObitHistoryUnref(inHist);\n  outHist = ObitHistoryUnref(outHist);\n\n} /* end ObitRMFitCube */\n\n/**\n * Fit RM to an array of images\n * The third axis of the output image will be \"SPECRM  \" to indicate that then\n * planes are spectral fit parameters.  The \"CRVAL\" on this axis will be the reference \n * Frequency for the fitting.\n * Item \"NTERM\" is added to the output image descriptor to give the maximum number \n * of terms fitted\n * \\param in       Spectral fitting object\n * \\li \"refLamb2\" OBIT_double scalar Reference frequency for fit [def average of inputs]\n * \\li \"minQUSNR\" OBIT_float scalar Max. min. SNR for Q and U pixels [def 3.0]\n * \\li \"doError\" OBIT_boolean scalar If true do error analysis [def False]\n * \\param nimage   Number of entries in imQArr\n * \\param imQArr   Array of Q images to be fitted\n * \\param imUArr   Array of U images to be fitted, same geometry as imQArr\n * \\param outImage Image cube with fitted parameters.\n *                 Should be defined but not created.\n *                 Planes 1->nterm are coefficients per pixel\n *                 if doError:\n *                 Planes nterm+1->2*nterm are uncertainties in coefficients\n *                 Plane 2*nterm+1 = Chi squared of fit\n * \\param err      Obit error stack object.\n */\nvoid ObitRMFitImArr (ObitRMFit* in, olong nimage, \n\t\t     ObitImage **imQArr, ObitImage **imUArr, \n\t\t     ObitImage *outImage, ObitErr *err)\n{\n  olong i, iplane, nOut;\n  olong naxis[2];\n  ObitIOSize IOBy;\n  ObitInfoType type;\n  ObitIOCode retCode;\n  union ObitInfoListEquiv InfoReal; \n  gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};\n  ofloat ipixel[2], opixel[2];\n  gboolean bad;\n  odouble avgLamb2, freq;\n  gchar *today=NULL, *SPECRM   = \"SPECRM  \";\n  gchar *routine = \"ObitRMFitCube\";\n\n  /* error checks */\n  if (err->error) return;\n  g_assert (ObitIsA(in, &myClassInfo));\n  g_assert(ObitImageIsA(outImage));\n\n  /* Warn if no GSL implementation */\n#ifndef HAVE_GSL\n  Obit_log_error(err, OBIT_InfoWarn, \"NO GSL available - results will be approximate\");\n#endif\n\n  /* Control parameters */\n  /* Min Q/U pixel SNR for fit */\n  InfoReal.flt = 3.0; type = OBIT_float;\n  in->minQUSNR = 3.0;\n  ObitInfoListGetTest(in->info, \"minQUSNR\", &type, dim, &InfoReal);\n  if (type==OBIT_float) in->minQUSNR = InfoReal.flt;\n  else if (type==OBIT_double) in->minQUSNR = (ofloat)InfoReal.dbl;\n\n  /* Min fraction of planes in the fit */\n  InfoReal.flt = 0.5; type = OBIT_float;\n  in->minFrac  = 0.5;\n  ObitInfoListGetTest(in->info, \"minFrac\", &type, dim, &InfoReal);\n  if (type==OBIT_float) in->minFrac = InfoReal.flt;\n  else if (type==OBIT_double) in->minFrac = (ofloat)InfoReal.dbl;\n\n  /* Want Error analysis? */\n  InfoReal.itg = (olong)FALSE; type = OBIT_bool;\n  ObitInfoListGetTest(in->info, \"doError\", &type, dim, &InfoReal);\n  in->doError = InfoReal.itg;\n\n  /* Determine number of lambda^2 planes and initialize in */\n  in->nlamb2 = nimage;\n  in->QRMS       = g_malloc0(in->nlamb2*sizeof(ofloat));\n  in->URMS       = g_malloc0(in->nlamb2*sizeof(ofloat));\n  in->inQFArrays = g_malloc0(in->nlamb2*sizeof(ObitFArray*));\n  in->inUFArrays = g_malloc0(in->nlamb2*sizeof(ObitFArray*));\n  in->lamb2      = g_malloc0(in->nlamb2*sizeof(odouble));\n\n  /* How many output planes? */\n  if (in->doError) nOut = 1+in->nterm*2;\n  else nOut = in->nterm;\n    \n  /* Define term arrays */\n  in->outFArrays = g_malloc0((nOut)*sizeof(ObitFArray*));\n  for (i=0; i<nOut; i++) in->outFArrays[i] = NULL;\n\n  /* Loop over images */\n  for (iplane = 0; iplane<nimage; iplane++) {\n    /* Open input image to get info */\n    IOBy = OBIT_IO_byPlane;\n    dim[0] = 1;\n    ObitInfoListAlwaysPut (imQArr[iplane]->info, \"IOBy\", OBIT_long, dim, &IOBy);\n    imQArr[iplane]->extBuffer = TRUE;   /* Using inFArrays as I/O buffer */\n    retCode = ObitImageOpen (imQArr[iplane], OBIT_IO_ReadOnly, err);\n    ObitInfoListAlwaysPut (imUArr[iplane]->info, \"IOBy\", OBIT_long, dim, &IOBy);\n    imUArr[iplane]->extBuffer = TRUE;   /* Using inFArrays as I/O buffer */\n    retCode = ObitImageOpen (imUArr[iplane], OBIT_IO_ReadOnly, err);\n    /* if it didn't work bail out */\n    if ((retCode!=OBIT_IO_OK) || (err->error)) \n      Obit_traceback_msg (err, routine, imQArr[iplane]->name);\n    \n    /* On first image initialize */\n    if (iplane==0) {\n      /* Image size */\n      in->nx = imQArr[iplane]->myDesc->inaxes[0];\n      in->ny = imQArr[iplane]->myDesc->inaxes[1];\n      naxis[0] = (olong)in->nx;  naxis[1] = (olong)in->ny; \n      for (i=0; i<in->nlamb2; i++) in->inQFArrays[i] = ObitFArrayCreate (NULL, 2, naxis);\n      for (i=0; i<in->nlamb2; i++) in->inUFArrays[i] = ObitFArrayCreate (NULL, 2, naxis);\n      for (i=0; i<nOut; i++)       in->outFArrays[i] = ObitFArrayCreate (NULL, 2, naxis);\n      \n      /* Output Image descriptor */\n      outImage->myDesc = ObitImageDescCopy (imQArr[iplane]->myDesc, in->outDesc, err);\n      if (err->error) Obit_traceback_msg (err, routine, imQArr[iplane]->name);\n\n      /* Change third axis to type \"SPECRM  \" and leave the reference frequency\n\t as the \"CRVAL\" */\n      outImage->myDesc->inaxes[outImage->myDesc->jlocf] =  nOut;\n      outImage->myDesc->crpix[outImage->myDesc->jlocf]  =  1.0;\n      outImage->myDesc->cdelt[outImage->myDesc->jlocf]  =  1.0;\n      strncpy (outImage->myDesc->ctype[outImage->myDesc->jlocf], SPECRM , IMLEN_KEYWORD);\n      outImage->myDesc->bitpix = -32;  /* Float it */\n\n      /* Creation date today */\n      today = ObitToday();\n      strncpy (outImage->myDesc->date, today, IMLEN_VALUE);\n      if (today) g_free(today);\n\n      /* Copy of output descriptor to in */\n      in->outDesc = ObitImageDescCopy (outImage->myDesc, in->outDesc, err);\n\n    } else { /* On subsequent images check for consistency */\n      /* Check size of planes */\n      Obit_return_if_fail(((imQArr[iplane]->myDesc->inaxes[0]==in->outDesc->inaxes[0]) && \n\t\t\t   (imQArr[iplane]->myDesc->inaxes[1]==in->outDesc->inaxes[1])), err,\n\t\t\t  \"%s: Image planes incompatible  %d!= %d or  %d!= %d\", \n\t\t\t  routine, imQArr[iplane]->myDesc->inaxes[0], in->outDesc->inaxes[0], \n\t\t\t  imQArr[iplane]->myDesc->inaxes[1], in->outDesc->inaxes[1]) ;\n      Obit_return_if_fail(((imUArr[iplane]->myDesc->inaxes[0]==in->outDesc->inaxes[0]) && \n\t\t\t   (imUArr[iplane]->myDesc->inaxes[1]==in->outDesc->inaxes[1])), err,\n\t\t\t  \"%s: Image planes incompatible  %d!= %d or  %d!= %d\", \n\t\t\t  routine, imUArr[iplane]->myDesc->inaxes[0], in->outDesc->inaxes[0], \n\t\t\t  imUArr[iplane]->myDesc->inaxes[1], in->outDesc->inaxes[1]) ;\n\n      /* Check alignment of pixels */\n      ipixel[0] = 1.0; ipixel[1] = 1.0;\n      bad = !ObitImageDescCvtPixel (imQArr[iplane]->myDesc, in->outDesc, ipixel, opixel, err);\n      if (err->error) Obit_traceback_msg (err, routine, imQArr[iplane]->name);\n      Obit_return_if_fail(!bad, err,\n\t\t\t  \"%s: Image planes incompatible\", routine);\n      Obit_return_if_fail(((fabs(ipixel[0]-opixel[0])<0.01) &&\n\t\t\t   (fabs(ipixel[1]-opixel[1])<0.01)), err,\n\t\t\t  \"%s: Image pixels not aligned %f!=%f or %f!=%f\", \n\t\t\t  routine, ipixel[0], opixel[0], ipixel[1], opixel[1]) ;\n     } /* end consistency check */\n    \n    /* Read planes */\n    retCode = ObitImageRead (imQArr[iplane], in->inQFArrays[iplane]->array, err);\n    retCode = ObitImageRead (imUArr[iplane], in->inUFArrays[iplane]->array, err);\n    /* if it didn't work bail out */\n    if ((retCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine, imQArr[iplane]->name);\n    \n    /* Plane RMSes */\n    in->QRMS[iplane] = ObitFArrayRMS(in->inQFArrays[iplane]);\n    in->URMS[iplane] = ObitFArrayRMS(in->inUFArrays[iplane]);\n\n    /* Lambda^2 */\n    freq = imQArr[iplane]->myDesc->crval[imQArr[iplane]->myDesc->jlocf] + \n      imQArr[iplane]->myDesc->cdelt[imQArr[iplane]->myDesc->jlocf] * \n      (imQArr[iplane]->myDesc->plane - imQArr[iplane]->myDesc->crpix[imQArr[iplane]->myDesc->jlocf]);\n    in->lamb2[iplane] = (VELIGHT/freq)*(VELIGHT/freq);\n\n    /* Close inputs */\n    retCode = ObitImageClose (imQArr[iplane], err);\n    imQArr[iplane]->extBuffer = FALSE;   /* May need I/O buffer later */\n    retCode = ObitImageClose (imUArr[iplane], err);\n    imUArr[iplane]->extBuffer = FALSE;   /* May need I/O buffer later */\n    /* if it didn't work bail out */\n    if ((retCode!=OBIT_IO_OK) || (err->error)) \n      Obit_traceback_msg (err, routine, imQArr[iplane]->name);\n  } /* end loop over input images */\n\n  /* Average Lambda^2 */\n  avgLamb2 = 0.0;\n  for (i=0; i<in->nlamb2; i++) avgLamb2 += in->lamb2[i];\n  avgLamb2 /= in->nlamb2;\n\n  /* Get Reference lambda^2 , default avg. input ref. freq. */\n  InfoReal.dbl = avgLamb2; type = OBIT_double;\n  in->refLamb2 = InfoReal.dbl;\n  ObitInfoListGetTest(in->info, \"refLamb2\", &type, dim, &InfoReal);\n  if (type==OBIT_float) in->refLamb2 = InfoReal.flt;\n  else if (type==OBIT_double) in->refLamb2 = (ofloat)InfoReal.dbl;\n  in->refLamb2 = MAX (1.0e-10, in->refLamb2); /* Avoid zero divide */\n  \n  /* Update output header to reference Frequency */\n  outImage->myDesc->crval[outImage->myDesc->jlocf] =VELIGHT/sqrt(in->refLamb2);\n  in->outDesc->crval[in->outDesc->jlocf] = VELIGHT/sqrt(in->refLamb2);\n\n  /* Do actual fitting */\n  Fitter (in, err);\n  if (err->error) Obit_traceback_msg (err, routine, imQArr[0]->name);\n\n  /* Write output */\n  WriteOutput(in, outImage, err);\n  if (err->error) Obit_traceback_msg (err, routine, outImage->name);\n\n} /* end ObitRMFitImArr */\n\n/**\n * Fit single RM to Q, Uflux measurements\n * \\param nlamb2    Number of entries in freq, flux, sigma\n * \\param nterm     Number of coefficients of powers of log(nu) to fit\n * \\param refLamb2  Reference lambda^2 (m^2)\n * \\param lamb2     Array of lambda^2 (m^2)\n * \\param qflux     Array of Q fluxes (Jy) same dim as lamb2\n * \\param qsigma    Array of Q errors (Jy) same dim as lamb2\n * \\param uflux     Array of U fluxes (Jy) same dim as lamb2\n * \\param usigma    Array of U errors (Jy) same dim as lamb2\n * \\param err      Obit error stack object.\n * \\return  Array of fitter parameters, errors for each and Chi Squares of fit\n *          Initial terms are in Jy, other in log.\n */\nofloat* ObitRMFitSingle (olong nlamb2, olong nterm, odouble refLamb2, odouble *lamb2, \n\t\t\t ofloat *qflux, ofloat *qsigma, ofloat *uflux, ofloat *usigma, \n\t\t\t ObitErr *err)\n{\n  ofloat *out = NULL;\n  ofloat fblank = ObitMagicF();\n  olong i, j;\n  NLRMFitArg *arg=NULL;\n  gchar *routine = \"ObitRMFitSingle\";\n  /* GSL implementation */\n#ifdef HAVE_GSL\n  const gsl_multifit_fdfsolver_type *T=NULL;\n#endif /* HAVE_GSL */ \n  /* Warn if no GSL implementation */\n#ifndef HAVE_GSL\n  Obit_log_error(err, OBIT_InfoWarn, \"NO GSL available - results will be approximate\");\n#endif\n  if (err->error) return out;\n\n\n  /* Warn if ref. lambda^2 <= 0, set to 1.0 */\n  if (refLamb2<=0.0) {\n    refLamb2 = 1.0;\n    Obit_log_error(err, OBIT_InfoWarn, \n\t\t   \"%s: Setting reference lambda^2 to 1\", routine);\n  }\n\n  /* Create function argument */\n  arg = g_malloc(sizeof(NLRMFitArg));\n  arg->in             = NULL;     /* Not needed here */\n  arg->nlamb2         = nlamb2;\n  arg->maxIter        = 100;     /* max. number of iterations */\n  arg->minDelta       = 1.0e-5;  /* Min step size */\n  arg->nterm          = nterm;\n  arg->doError        = TRUE;\n  arg->minQUSNR       = 3.0;      /* min pixel SNR */\n  arg->minFrac        = 0.5;      /* min fraction of samples */\n  arg->refLamb2       = refLamb2; /* Reference Frequency */\n  arg->Qweight        = g_malloc0(arg->nlamb2*sizeof(ofloat));\n  arg->Uweight        = g_malloc0(arg->nlamb2*sizeof(ofloat));\n  arg->Qvar           = g_malloc0(arg->nlamb2*sizeof(ofloat));\n  arg->Uvar           = g_malloc0(arg->nlamb2*sizeof(ofloat));\n  arg->Qobs           = g_malloc0(arg->nlamb2*sizeof(ofloat));\n  arg->Uobs           = g_malloc0(arg->nlamb2*sizeof(ofloat));\n  arg->Pobs           = g_malloc0(arg->nlamb2*sizeof(ofloat));\n  arg->lamb2          = g_malloc0(arg->nlamb2*sizeof(ofloat));\n  arg->x              = g_malloc0(arg->nlamb2*sizeof(double));\n  arg->w              = g_malloc0(arg->nlamb2*sizeof(double));\n  arg->q              = g_malloc0(arg->nlamb2*sizeof(double));\n  arg->u              = g_malloc0(arg->nlamb2*sizeof(double));\n  arg->wrk1           = g_malloc0(arg->nlamb2*sizeof(ofloat));\n  arg->wrk2           = g_malloc0(arg->nlamb2*sizeof(ofloat));\n  arg->wrk3           = g_malloc0(arg->nlamb2*sizeof(ofloat));\n  arg->coef           = g_malloc0(3*arg->nterm*sizeof(ofloat));\n  for (i=0; i<nlamb2; i++) {\n    arg->lamb2[i]   = lamb2[i];\n    arg->Qvar[i]    = qsigma[i]*qsigma[i];\n    arg->Uvar[i]    = usigma[i]*usigma[i];\n    arg->Qobs[i]    = qflux[i];\n    arg->Uobs[i]    = uflux[i];\n    if ((arg->Qobs[i]!=fblank) && (arg->Uobs[i]!=fblank)) {\n      arg->Pobs[i]    = sqrt (qflux[i]*qflux[i] + uflux[i]*uflux[i]);\n      arg->Qweight[i] = 1.0 / qsigma[i];\n      arg->Uweight[i] = 1.0 / usigma[i];\n   } else{ \n      arg->Pobs[i]    = 0.0;\n      arg->Qweight[i] = 0.0;\n      arg->Uweight[i] = 0.0;\n    }\n  }\n  /* GSL implementation */\n#ifdef HAVE_GSL\n  arg->solver = NULL;\n  arg->covar  = NULL;\n  arg->work = NULL;\n  /* Setup solver */\n  T = gsl_multifit_fdfsolver_lmder;\n  arg->solver = gsl_multifit_fdfsolver_alloc(T, 2*arg->nlamb2, 2);\n\n  /* Fitting function info */\n  arg->funcStruc = g_malloc0(sizeof(gsl_multifit_function_fdf));\n  arg->funcStruc->f      = &RMFitFunc;\n  arg->funcStruc->df     = &RMFitJac;\n  arg->funcStruc->fdf    = &RMFitFuncJac;\n  arg->funcStruc->n      = 2*arg->nlamb2;\n  arg->funcStruc->p      = 2;\n  arg->funcStruc->params = arg;\n\n  /* Set up work arrays */\n  arg->covar = gsl_matrix_alloc(2, 2);\n  arg->work  = gsl_vector_alloc(2);\n#endif /* HAVE_GSL */ \n\n  /* Do fit */  \n  NLRMFit(arg);\n  \n  /* get results parameters + errors */\n  out = g_malloc0((2*arg->nterm+1)*sizeof(ofloat));\n  for (j=0; j<nterm*2+1; j++) out[j] = arg->coef[j];\n  \n  /* Cleanup */\n  if (arg->Qweight)   g_free(arg->Qweight);\n  if (arg->Uweight)   g_free(arg->Uweight);\n  if (arg->Qvar)      g_free(arg->Qvar);\n  if (arg->Uvar)      g_free(arg->Uvar);\n  if (arg->Qobs)      g_free(arg->Qobs);\n  if (arg->Uobs)      g_free(arg->Uobs);\n  if (arg->Pobs)      g_free(arg->Pobs);\n  if (arg->lamb2)     g_free(arg->lamb2);\n  if (arg->x)         g_free(arg->x);\n  if (arg->w)         g_free(arg->w);\n  if (arg->q)         g_free(arg->q);\n  if (arg->u)         g_free(arg->u);\n  if (arg->wrk1)      g_free(arg->wrk1);\n  if (arg->wrk2)      g_free(arg->wrk2);\n  if (arg->wrk3)      g_free(arg->wrk3);\n  if (arg->coef)      g_free(arg->coef);\n#ifdef HAVE_GSL\n  if (arg->solver)   gsl_multifit_fdfsolver_free (arg->solver);\n  if (arg->work)     gsl_vector_free(arg->work);\n  if (arg->covar)    gsl_matrix_free(arg->covar);\n  if (arg->funcStruc) g_free(arg->funcStruc);\n#endif /* HAVE_GSL */\n  g_free(arg);\n\n  return out;\n} /* end ObitRMFitSingle */\n\n/**\n * Make single spectrum fitting argument array\n * \\param nlamb2   Number of entries in freq, flux, sigma\n * \\param nterm    Number of coefficients of powers of log(nu) to fit\n * \\param refLamb2 Reference lambda^2 (m^2)\n * \\param lamb2    Array of lambda^2 (m^2)\n * \\param out      Array for output results, should be g_freed when done\n * \\param err      Obit error stack object.\n * \\return  argument for single spectrum fitting, use ObitRMFitKillArg to dispose.\n */\ngpointer ObitRMFitMakeArg (olong nlamb2, olong nterm, odouble refLamb2, \n\t\t\t   odouble *lamb2, ofloat **out, ObitErr *err)\n{\n  olong i;\n  NLRMFitArg *arg=NULL;\n  gchar *routine = \"ObitRMFitMakeArg\";\n#ifdef HAVE_GSL\n  const gsl_multifit_fdfsolver_type *T=NULL;\n#endif /* HAVE_GSL */ \n\n  if (err->error) return out;\n\n  /* Warn if too many terms asked for */\n  if (nterm>2) {\n      Obit_log_error(err, OBIT_InfoWarn, \n\t\t    \"%s: Asked for %d terms, will limit to 2\", routine, nterm);\n  }\n\n  /* Warn if ref. lambda^2 <= 0, set to 1.0 */\n  if (refLamb2<=0.0) {\n    refLamb2 = 1.0;\n    Obit_log_error(err, OBIT_InfoWarn, \n\t\t   \"%s: Setting reference Lambda^2 to 1\", routine);\n  }\n\n  /* Create function argument */\n  arg = g_malloc(sizeof(NLRMFitArg));\n  arg->in             = NULL;     /* Not needed here */\n  arg->nlamb2         = nlamb2;\n  arg->maxIter        = 100;     /* max. number of iterations */\n  arg->minDelta       = 1.0e-5;  /* Min step size */\n  arg->nterm          = nterm;\n  arg->doError        = TRUE;\n  arg->minQUSNR       = 3.0;      /* min pixel SNR */\n  arg->minFrac        = 0.5;      /* min fraction of samples */\n  arg->refLamb2       = refLamb2; /* Reference Frequency */\n  arg->Qweight        = g_malloc0(arg->nlamb2*sizeof(ofloat));\n  arg->Uweight        = g_malloc0(arg->nlamb2*sizeof(ofloat));\n  arg->Qvar           = g_malloc0(arg->nlamb2*sizeof(ofloat));\n  arg->Uvar           = g_malloc0(arg->nlamb2*sizeof(ofloat));\n  arg->Qobs           = g_malloc0(arg->nlamb2*sizeof(ofloat));\n  arg->Uobs           = g_malloc0(arg->nlamb2*sizeof(ofloat));\n  arg->Pobs           = g_malloc0(arg->nlamb2*sizeof(ofloat));\n  arg->lamb2          = g_malloc0(arg->nlamb2*sizeof(ofloat));\n  arg->x              = g_malloc0(arg->nlamb2*sizeof(double));\n  arg->w              = g_malloc0(arg->nlamb2*sizeof(double));\n  arg->q              = g_malloc0(arg->nlamb2*sizeof(double));\n  arg->u              = g_malloc0(arg->nlamb2*sizeof(double));\n  arg->wrk1           = g_malloc0(arg->nlamb2*sizeof(ofloat));\n  arg->wrk2           = g_malloc0(arg->nlamb2*sizeof(ofloat));\n  arg->wrk3           = g_malloc0(arg->nlamb2*sizeof(ofloat));\n  arg->coef           = g_malloc0(3*arg->nterm*sizeof(ofloat));\n  for (i=0; i<nlamb2; i++) {\n    arg->lamb2[i]        = lamb2[i];\n  }\n  /* GSL implementation */\n#ifdef HAVE_GSL\n  arg->solver = NULL; arg->covar = NULL; arg->work = NULL;\n  /* Setup solver */\n  T = gsl_multifit_fdfsolver_lmder;\n  arg->solver = gsl_multifit_fdfsolver_alloc(T, 2*arg->nlamb2, 2);\n\n  /* Fitting function info */\n  arg->funcStruc = g_malloc0(sizeof(gsl_multifit_function_fdf));\n  arg->funcStruc->f      = &RMFitFunc;\n  arg->funcStruc->df     = &RMFitJac;\n  arg->funcStruc->fdf    = &RMFitFuncJac;\n  arg->funcStruc->n      = 2*arg->nlamb2;\n  arg->funcStruc->p      = 2;\n  arg->funcStruc->params = arg;\n\n  /* Set up work arrays */\n  arg->covar = gsl_matrix_alloc(2, 2);\n  arg->work  = gsl_vector_alloc(2);\n#endif /* HAVE_GSL */ \n\n  /* output array */\n  *out = (ofloat*)g_malloc0((2*arg->nterm+1)*sizeof(ofloat));\n\n  return (gpointer)arg;\n} /* end ObitRMFitMakeArg */\n\n/**\n * Fit single RM to measurements using precomputed argument\n * \\param aarg      pointer to argument for fitting\n * \\param Qflux     Array of Q values to be fitted\n * \\param Qsigma    Array of uncertainties of Qflux\n * \\param Uflux     Array of U values to be fitted\n * \\param Usigma    Array of uncertainties of Qflux\n * \\param out       Result array at least 2*nterms+1 in size.\n *                  in order, fitted parameters, error estimates, chi sq of fit.\n */\nvoid ObitRMFitSingleArg (gpointer aarg, \n\t\t\t ofloat *qflux, ofloat *qsigma, \n\t\t\t ofloat *uflux, ofloat *usigma,\n\t\t\t ofloat *out)\n{\n  olong i, j;\n  NLRMFitArg *arg=(NLRMFitArg*)aarg;\n  ofloat fblank = ObitMagicF();\n  gboolean allBad;\n\n  /* Save flux array, sigma, Check if all data blanked  */\n  allBad = TRUE;\n  for (i=0; i<arg->nlamb2; i++) {\n    if ((arg->Qobs[i]!=fblank) && \n\t(arg->Uobs[i]!=fblank) && \n\t((fabs(qflux[i])>arg->minQUSNR*qsigma[i]) ||\n\t (fabs(uflux[i])>arg->minQUSNR*usigma[i]))) allBad = FALSE;\n    arg->Qobs[i]    = qflux[i];\n    arg->Uobs[i]    = uflux[i];\n    arg->Qvar[i]    = qsigma[i];\n    arg->Uvar[i]    = usigma[i];\n    if ((arg->Qobs[i]!=fblank) && (arg->Uobs[i]!=fblank)) {\n      arg->Pobs[i]    = sqrt (qflux[i]*qflux[i] + uflux[i]*uflux[i]);\n      /* arg->Qweight[i] = arg->Pobs[i] / arg->Qvar[i];\n\t arg->Uweight[i] = arg->Pobs[i] / arg->Uvar[i]; */\n      arg->Qweight[i] = 1.0 / qsigma[i];\n      arg->Uweight[i] = 1.0 / usigma[i];\n   } else {\n      arg->Pobs[i]    = 0.0;\n      arg->Qweight[i] = 0.0;\n      arg->Uweight[i] = 0.0;\n    }\n  }\n  \n   /* Return fblanks/zeroes for no data */\n  if (allBad) {\n    out[0] = fblank;\n    for (j=1; j<=arg->nterm*2; j++) out[j] = 0.0;\n    return;\n  }\n\n  /* Fit */\n  NLRMFit(arg);\n  \n  /* get results parameters + errors */\n  for (j=0; j<arg->nterm*2; j++) out[j] = arg->coef[j];\n  /* Chi squared */\n  out[arg->nterm*2] = arg->ChiSq;\n  \n  return;\n} /* end ObitRMFitSingleArg */\n\n/**\n * Delete single fitting argument\n * \\param aarg      pointer to argument to kill\n */\nvoid ObitRMFitKillArg (gpointer aarg)\n{\n  NLRMFitArg *arg= (NLRMFitArg*)aarg;\n\n  if (arg==NULL) return;\n  if (arg->Qweight)   g_free(arg->Qweight);\n  if (arg->Uweight)   g_free(arg->Uweight);\n  if (arg->Qvar)      g_free(arg->Qvar);\n  if (arg->Uvar)      g_free(arg->Uvar);\n  if (arg->Qobs)      g_free(arg->Qobs);\n  if (arg->Uobs)      g_free(arg->Uobs);\n  if (arg->Pobs)      g_free(arg->Pobs);\n  if (arg->lamb2)     g_free(arg->lamb2);\n  if (arg->x)         g_free(arg->x);\n  if (arg->w)         g_free(arg->w);\n  if (arg->q)         g_free(arg->q);\n  if (arg->u)         g_free(arg->u);\n  if (arg->wrk1)      g_free(arg->wrk1);\n  if (arg->wrk2)      g_free(arg->wrk2);\n  if (arg->wrk3)      g_free(arg->wrk3);\n  if (arg->coef)      g_free(arg->coef);\n#ifdef HAVE_GSL\n  if (arg->solver)   gsl_multifit_fdfsolver_free (arg->solver);\n  if (arg->work)     gsl_vector_free(arg->work);\n  if (arg->covar)    gsl_matrix_free(arg->covar);\n  if (arg->funcStruc) g_free(arg->funcStruc);\n#endif /* HAVE_GSL */\n  g_free(arg);\n\n} /* end ObitRMFitKillArg */\n\n/**\n * Initialize global ClassInfo Structure.\n */\nvoid ObitRMFitClassInit (void)\n{\n  if (myClassInfo.initialized) return;  /* only once */\n  \n  /* Set name and parent for this class */\n  myClassInfo.ClassName   = g_strdup(myClassName);\n  myClassInfo.ParentClass = ObitParentGetClass();\n\n  /* Set function pointers */\n  ObitRMFitClassInfoDefFn ((gpointer)&myClassInfo);\n \n  myClassInfo.initialized = TRUE; /* Now initialized */\n \n} /* end ObitRMFitClassInit */\n\n/**\n * Initialize global ClassInfo Function pointers.\n */\nstatic void ObitRMFitClassInfoDefFn (gpointer inClass)\n{\n  ObitRMFitClassInfo *theClass = (ObitRMFitClassInfo*)inClass;\n  ObitClassInfo *ParentClass = (ObitClassInfo*)myClassInfo.ParentClass;\n\n  if (theClass->initialized) return;  /* only once */\n\n  /* Check type of inClass */\n  g_assert (ObitInfoIsA(inClass, (ObitClassInfo*)&myClassInfo));\n\n  /* Initialize (recursively) parent class first */\n  if ((ParentClass!=NULL) && \n      (ParentClass->ObitClassInfoDefFn!=NULL))\n    ParentClass->ObitClassInfoDefFn(theClass);\n\n  /* function pointers defined or overloaded this class */\n  theClass->ObitClassInit = (ObitClassInitFP)ObitRMFitClassInit;\n  theClass->newObit       = (newObitFP)newObitRMFit;\n  theClass->ObitClassInfoDefFn = (ObitClassInfoDefFnFP)ObitRMFitClassInfoDefFn;\n  theClass->ObitGetClass  = (ObitGetClassFP)ObitRMFitGetClass;\n  theClass->ObitCopy      = (ObitCopyFP)ObitRMFitCopy;\n  theClass->ObitClone     = NULL;\n  theClass->ObitClear     = (ObitClearFP)ObitRMFitClear;\n  theClass->ObitInit      = (ObitInitFP)ObitRMFitInit;\n  theClass->ObitRMFitCreate = (ObitRMFitCreateFP)ObitRMFitCreate;\n  theClass->ObitRMFitCube   = (ObitRMFitCubeFP)ObitRMFitCube;\n  theClass->ObitRMFitImArr  = (ObitRMFitImArrFP)ObitRMFitImArr;\n  theClass->ObitRMFitSingle = (ObitRMFitSingleFP)ObitRMFitSingle;\n} /* end ObitRMFitClassDefFn */\n\n/*---------------Private functions--------------------------*/\n\n/**\n * Creates empty member objects, initialize reference count.\n * Parent classes portions are (recursively) initialized first\n * \\param inn Pointer to the object to initialize.\n */\nvoid ObitRMFitInit  (gpointer inn)\n{\n  ObitClassInfo *ParentClass;\n  ObitRMFit *in = inn;\n\n  /* error checks */\n  g_assert (in != NULL);\n\n  /* recursively initialize parent class members */\n  ParentClass = (ObitClassInfo*)(myClassInfo.ParentClass);\n  if ((ParentClass!=NULL) && ( ParentClass->ObitInit!=NULL)) \n    ParentClass->ObitInit (inn);\n\n  /* set members in this class */\n  in->thread     = newObitThread();\n  in->info       = newObitInfoList(); \n  in->nterm      = 2;\n  in->nlamb2     = 0;\n  in->minQUSNR   = 3.0;\n  in->minFrac    = 0.5;\n  in->QRMS       = NULL;\n  in->URMS       = NULL;\n  in->outDesc    = NULL;\n  in->inQFArrays = NULL;\n  in->inUFArrays = NULL;\n  in->outFArrays = NULL;\n  in->lamb2      = NULL;\n\n} /* end ObitRMFitInit */\n\n/**\n * Deallocates member objects.\n * Does (recursive) deallocation of parent class members.\n * \\param  inn Pointer to the object to deallocate.\n *           Actually it should be an ObitRMFit* cast to an Obit*.\n */\nvoid ObitRMFitClear (gpointer inn)\n{\n  ObitClassInfo *ParentClass;\n  ObitRMFit *in = inn;\n  olong i, nOut;\n\n  /* error checks */\n  g_assert (ObitIsA(in, &myClassInfo));\n\n  /* delete this class members */\n  if (in->QRMS) g_free(in->QRMS);\n  if (in->URMS) g_free(in->URMS);\n  in->thread = ObitThreadUnref(in->thread);\n  in->info   = ObitInfoListUnref(in->info);\n  if (in->outDesc) in->outDesc = ObitImageDescUnref(in->outDesc);\n  if (in->inQFArrays) {\n    for (i=0; i<in->nlamb2; i++) in->inQFArrays[i] = ObitFArrayUnref(in->inQFArrays[i]);\n    g_free(in->inQFArrays);\n  }\n  if (in->inUFArrays) {\n    for (i=0; i<in->nlamb2; i++) in->inUFArrays[i] = ObitFArrayUnref(in->inUFArrays[i]);\n    g_free(in->inUFArrays);\n  }\n\n  /* How many output planes */\n  if (in->doError) nOut = 1+in->nterm*2;\n  else nOut = in->nterm;\n\n  if (in->outFArrays) {\n    for (i=0; i<nOut; i++) in->outFArrays[i] = ObitFArrayUnref(in->outFArrays[i]);\n    g_free(in->outFArrays);\n  }\n  if (in->lamb2)     g_free(in->lamb2);\n\n  /* unlink parent class members */\n  ParentClass = (ObitClassInfo*)(myClassInfo.ParentClass);\n  /* delete parent class members */\n  if ((ParentClass!=NULL) && ( ParentClass->ObitClear!=NULL)) \n    ParentClass->ObitClear (inn);\n  \n} /* end ObitRMFitClear */\n\n/**\n * Does RM fitting, input and output on input object\n * Work divided up amoung 1 or more threads\n * In each pixel an RM is fitted if the number of valid data points \n * exceeds in->nterm, otherwise the pixel is blanked.\n * If in->doRMSyn then the max value of an RM synthesis is used\n * The results are stored in outFArrays:\n * \\li first entry is the RM at the reference lambda^2\n * \\li second is the EVLA (rad) at 0 lambda^2\n * \\li third is the polarized amplitude at 0 lambda^2\n * \\li fouurth is the sum of the statistical weights\n * Otherwise, the results are stored in outFArrays:\n * \\li first entry is the RM at the reference lambda^2\n * \\li second is the EVLA (rad) at the reference lambda^2\n * \\li entries nterm+1->nterm*2 RMS uncertainties on coefficients\n * \\li entry 1+nterm*2 = the Chi squared of the fit\n *\n * \\param  in  RMFit to fit\n * \\param  err Obit error stack object.\n */\nstatic void Fitter (ObitRMFit* in, ObitErr *err)\n{\n  olong i, loy, hiy, nyPerThread, nThreads;\n  gboolean OK;\n  NLRMFitArg **threadArgs;\n  NLRMFitArg *args=NULL;\n  ObitThreadFunc func=(ObitThreadFunc)ThreadNLRMFit;\n  gchar *routine = \"Fitter\";\n  /* GSL implementation */\n#ifdef HAVE_GSL\n  const gsl_multifit_fdfsolver_type *T=NULL;\n#endif /* HAVE_GSL */ \n\n  /* error checks */\n  if (err->error) return;\n\n  /* Warn if too many terms asked for */\n  if (in->nterm>2) {\n      Obit_log_error(err, OBIT_InfoWarn, \n\t\t    \"%s: Asked for %d terms, will limit to 2\", routine, in->nterm);\n  }\n\n  /* How many threads to use? */\n  nThreads = MAX (1, ObitThreadNumProc(in->thread));\n\n  /* Initialize threadArg array  */\n  threadArgs = g_malloc0(nThreads*sizeof(NLRMFitArg*));\n  for (i=0; i<nThreads; i++) \n    threadArgs[i] = g_malloc0(sizeof(NLRMFitArg)); \n\n  /* Set up thread arguments */\n  for (i=0; i<nThreads; i++) {\n    args = (NLRMFitArg*)threadArgs[i];\n    args->in          = in;\n    args->err         = err;\n    args->nlamb2      = in->nlamb2;\n    args->maxIter     = 100;     /* max. number of iterations */\n    args->minDelta    = 1.0e-5;  /* Min step size */\n    args->nterm       = in->nterm;\n    args->doError     = in->doError;\n    args->minQUSNR    = in->minQUSNR;     /* min pixel SNR */\n    args->minFrac     = in->minFrac;      /* min fraction of samples  */\n    args->Qweight     = g_malloc0(args->nlamb2*sizeof(ofloat));\n    args->Uweight     = g_malloc0(args->nlamb2*sizeof(ofloat));\n    args->Qvar        = g_malloc0(args->nlamb2*sizeof(ofloat));\n    args->Uvar        = g_malloc0(args->nlamb2*sizeof(ofloat));\n    args->Qobs        = g_malloc0(args->nlamb2*sizeof(ofloat));\n    args->Uobs        = g_malloc0(args->nlamb2*sizeof(ofloat));\n    args->Pobs        = g_malloc0(args->nlamb2*sizeof(ofloat));\n    args->lamb2       = g_malloc0(args->nlamb2*sizeof(ofloat));\n    args->x           = g_malloc0(args->nlamb2*sizeof(double));\n    args->w           = g_malloc0(args->nlamb2*sizeof(double));\n    args->q           = g_malloc0(args->nlamb2*sizeof(double));\n    args->u           = g_malloc0(args->nlamb2*sizeof(double));\n    args->wrk1        = g_malloc0(args->nlamb2*sizeof(ofloat));\n    args->wrk2        = g_malloc0(args->nlamb2*sizeof(ofloat));\n    args->wrk3        = g_malloc0(args->nlamb2*sizeof(ofloat));\n    if (args->doError)\n      args->coef      = g_malloc0(3*args->nterm*sizeof(ofloat));\n    else\n      args->coef      = g_malloc0(args->nterm*sizeof(ofloat));\n   /* GSL implementation */\n#ifdef HAVE_GSL\n    args->solver = NULL; args->covar = NULL; args->work = NULL;\n  /* Setup solver */\n    T = gsl_multifit_fdfsolver_lmder;\n    args->solver = gsl_multifit_fdfsolver_alloc(T, 2*args->nlamb2, 2);\n    \n    /* Fitting function info */\n    args->funcStruc = g_malloc0(sizeof(gsl_multifit_function_fdf));\n    args->funcStruc->f      = &RMFitFunc;\n    args->funcStruc->df     = &RMFitJac;\n    args->funcStruc->fdf    = &RMFitFuncJac;\n    args->funcStruc->n      = 2*args->nlamb2;\n    args->funcStruc->p      = 2;\n    args->funcStruc->params = args;\n    \n    /* Set up work arrays */\n    args->covar = gsl_matrix_alloc(2, 2);\n    args->work  = gsl_vector_alloc(2);\n#endif /* HAVE_GSL */ \n  }\n  /* end initialize */\n  \n  /* Divide up work */\n  nyPerThread = in->ny/nThreads;\n  loy = 1;\n  hiy = nyPerThread;\n  hiy = MIN (hiy, in->ny);\n  \n  /* Set up thread arguments */\n  for (i=0; i<nThreads; i++) {\n    if (i==(nThreads-1)) hiy = in->ny;  /* Make sure do all */\n    args = (NLRMFitArg*)threadArgs[i];\n    args->first  = loy;\n    args->last   = hiy;\n    if (nThreads>1) args->ithread = i;\n    else args->ithread = -1;\n    /* Update which y */\n    loy += nyPerThread;\n    hiy += nyPerThread;\n    hiy = MIN (hiy, in->ny);\n  }\n  \n  /* Do operation possibly with threads */\n  if (in->doRMSyn) func = (ObitThreadFunc)ThreadRMSynFit;\n  else             func = (ObitThreadFunc)ThreadNLRMFit;\n  OK = ObitThreadIterator (in->thread, nThreads, func, (gpointer)threadArgs);\n  \n  /* Check for problems */\n  if (!OK) {\n    Obit_log_error(err, OBIT_Error,\"%s: Problem in threading\", routine);\n  }\n\n  /* Shut down any threading */\n  ObitThreadPoolFree (in->thread);\n  if (threadArgs) {\n    for (i=0; i<nThreads; i++) {\n      args = (NLRMFitArg*)threadArgs[i];\n      if (args->Qweight)   g_free(args->Qweight);\n      if (args->Uweight)   g_free(args->Uweight);\n      if (args->Qvar)      g_free(args->Qvar);\n      if (args->Uvar)      g_free(args->Uvar);\n      if (args->Qobs)      g_free(args->Qobs);\n      if (args->Uobs)      g_free(args->Uobs);\n      if (args->Pobs)      g_free(args->Pobs);\n      if (args->lamb2)     g_free(args->lamb2);\n      if (args->x)         g_free(args->x);\n      if (args->w)         g_free(args->w);\n      if (args->q)         g_free(args->q);\n      if (args->u)         g_free(args->u);\n      if (args->wrk1)      g_free(args->wrk1);\n      if (args->wrk2)      g_free(args->wrk2);\n      if (args->wrk3)      g_free(args->wrk3);\n      if (args->coef)      g_free(args->coef);\n#ifdef HAVE_GSL\n      if (args->solver)    gsl_multifit_fdfsolver_free (args->solver);\n      if (args->work)      gsl_vector_free(args->work);\n      if (args->covar)     gsl_matrix_free(args->covar);\n      if (args->funcStruc) g_free(args->funcStruc);\n#endif /* HAVE_GSL */\n      g_free(threadArgs[i]);\n    }\n    g_free(threadArgs);\n  }\n\n} /* end Fitter */\n\n/**\n * Write contents on in to outImage\n * \\param in       RM fitting object\n * \\param outImage Image cube with fitted spectra.\n *                 Should be defined but not created.\n *                 Planes 1->nterm are coefficients per pixel\n *                 Planes nterm+1->2*nterm are uncertainties in coefficients\n * \\param err      Obit error stack object.\n */\nstatic void WriteOutput (ObitRMFit* in, ObitImage *outImage, \n\t\t\t ObitErr *err)\n{\n  olong iplane, nOut;\n  ObitIOSize IOBy;\n  olong  i, blc[IM_MAXDIM], trc[IM_MAXDIM];\n  ObitIOCode retCode;\n  gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};\n  gchar *routine = \"WriteOutput\";\n\n  /* error checks */\n  if (err->error) return;\n  g_assert (ObitIsA(in, &myClassInfo));\n  g_assert(ObitImageIsA(outImage));\n\n  /* Open output- all, by plane */\n  dim[0] = IM_MAXDIM;\n  for (i=0; i<IM_MAXDIM; i++) blc[i] = 1;\n  for (i=0; i<IM_MAXDIM; i++) trc[i] = 0;\n  ObitInfoListPut (outImage->info, \"BLC\", OBIT_long, dim, blc, err); \n  ObitInfoListPut (outImage->info, \"TRC\", OBIT_long, dim, trc, err); \n  IOBy = OBIT_IO_byPlane;\n  dim[0] = 1;\n  ObitInfoListAlwaysPut (outImage->info, \"IOBy\", OBIT_long, dim, &IOBy);\n  outImage->extBuffer = TRUE;   /* Using outFArrays as I/O buffer */\n  retCode = ObitImageOpen (outImage, OBIT_IO_ReadWrite, err);\n  /* if it didn't work bail out */\n  if ((retCode!=OBIT_IO_OK) || (err->error)) \n    Obit_traceback_msg (err, routine, outImage->name);\n\n  /* save descriptive material */\n  ObitImageDescCopyDesc (in->outDesc, outImage->myDesc, err);\n  if (err->error) Obit_traceback_msg (err, routine, outImage->name);\n\n  /* How many output planes? */\n  if (in->doError) nOut = 1+in->nterm*2;\n  else nOut = in->nterm;\n  /* always 4 for doRMSyn */\n  if (in->doRMSyn) nOut = 4;\n\n  /* Loop writing planes */\n  for (iplane=0; iplane<nOut; iplane++) {\n    retCode = ObitImageWrite (outImage, in->outFArrays[iplane]->array, err);\n    /* if it didn't work bail out */\n    if ((retCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine, outImage->name);\n\n  } /* end loop writing planes */\n\n  /* Save nterms on output descriptor */\n  dim[0] = dim[1] = dim[2] = 1;\n  ObitInfoListAlwaysPut (outImage->myDesc->info, \"NTERM\", OBIT_long, dim, &in->nterm);\n  ObitInfoListAlwaysPut (((ObitImageDesc*)outImage->myIO->myDesc)->info, \"NTERM\", \n    OBIT_long, dim, &in->nterm);\n\n  /* Close output */\n  retCode = ObitImageClose (outImage, err);\n  outImage->extBuffer = FALSE;   /* May need I/O buffer later */\n  /* if it didn't work bail out */\n  if ((retCode!=OBIT_IO_OK) || (err->error)) \n    Obit_traceback_msg (err, routine, outImage->name);\n\n} /* end WriteOutput */\n\n/**\n * Thread function to fit a portion of the image set\n * \\param arg      NLRMFitArg structure\n */\nstatic gpointer ThreadNLRMFit (gpointer arg)\n{\n  NLRMFitArg *larg      = (NLRMFitArg*)arg;\n  ObitRMFit* in       = (ObitRMFit*)larg->in;\n  olong lo            = larg->first-1;  /* First in y range */\n  olong hi            = larg->last;     /* Highest in y range */\n  gboolean doError    = larg->doError;  /* Error analysis? */\n  ObitErr *err        = larg->err;\n\n  olong ix, iy, indx, i, nOut;\n  ofloat fblank = ObitMagicF();\n  /*gchar *routine = \"ThreadNLRMFit\";*/\n\n  /* error checks */\n  if (err->error) return NULL;\n  g_assert (ObitIsA(in, &myClassInfo));\n\n  /* Set up frequency info */\n  larg->refLamb2 = in->refLamb2;\n  for (i=0; i<in->nlamb2; i++) {\n    larg->lamb2[i] = in->lamb2[i];\n  }\n\n  /* How many output planes */\n  if (in->doError) nOut = 1+in->nterm*2;\n  else nOut = in->nterm;\n\n  /* Loop over pixels in Y */\n  indx = lo*in->nx  -1;  /* Offset in pixel arrays */\n  for (iy=lo; iy<hi; iy++) {\n    /* Loop over pixels in X */\n    for (ix=0; ix<in->nx; ix++) {\n      indx ++;\n\n      /* Collect values;  */\n      for (i=0; i<in->nlamb2; i++) {\n\tlarg->Qobs[i] = in->inQFArrays[i]->array[indx];\n\tlarg->Uobs[i] = in->inUFArrays[i]->array[indx];\n\t/* Data valid? */\n\tif ((larg->Qobs[i]!=fblank) && \n\t    (larg->Uobs[i]!=fblank) && \n\t    ((fabs(larg->Qobs[i])>in->minQUSNR*in->QRMS[i]) ||\n\t     (fabs(larg->Uobs[i])>in->minQUSNR*in->URMS[i]))) {\n\t  /* Statistical weight */\n\t  larg->Qvar[i] = (in->QRMS[i]*in->QRMS[i]);\n\t  larg->Uvar[i] = (in->URMS[i]*in->URMS[i]);\n\t  larg->Pobs[i]    = sqrt (larg->Qobs[i]*larg->Qobs[i] + larg->Uobs[i]*larg->Uobs[i]);\n\t  /* larg->Qweight[i] = larg->Pobs[i] / larg->Qvar[i];\n\t     larg->Uweight[i] = larg->Pobs[i] / larg->Uvar[i];*/\n\t  larg->Qweight[i] = 1.0 / in->QRMS[i];\n\t  larg->Uweight[i] = 1.0 / in->URMS[i];\n\t  /* End if datum valid */\n\t} else { /* invalid pixel */\n\t  larg->Qweight[i] = 0.0;\n\t  larg->Qvar[i]    = 0.0;\n\t  larg->Uweight[i] = 0.0;\n\t  larg->Uvar[i]    = 0.0;\n\t  larg->Pobs[i]    = 0.0;\n\t}\n\t/* DEBUG\n\tif ((ix==669) && (iy==449)) { \n\t  fprintf (stderr,\"%3d q=%g u=%g qs=%g us=%g wt=%f\\n\",\n\t\t   i, larg->Qobs[i], larg->Uobs[i], in->QRMS[i], in->URMS[i], larg->Qweight[i]);\n\t} */\n      } /* end loop over frequencies */\n      \n      /* Fit */\n      NLRMFit(larg);\n      /* DEBUG\n      if ((ix==669) && (iy==449)) { \n\t fprintf (stderr,\"ix=%4d iy=%4d\\n\",ix+1,iy+1);\n\t fprintf (stderr,\"RM=%f EVPA=%f chi2=%f\\n\",\n\t\t  larg->coef[0], larg->coef[1],larg->coef[4]);\n      } */\n      \n      /* Save to output */\n      if (doError) {\n\tfor (i=0; i<nOut; i++) \n\t  in->outFArrays[i]->array[indx]  = larg->coef[i];\n      } else { /* only values */\n \tfor (i=0; i<in->nterm; i++) \n\t  in->outFArrays[i]->array[indx] = larg->coef[i];\n      }\n\n    } /* end x loop */\n  } /* end y loop */\n\n  /* Indicate completion */\n  if (larg->ithread>=0)\n    ObitThreadPoolDone (in->thread, (gpointer)&larg->ithread);\n\n  return NULL;\n} /* end ThreadNLRMFit */\n\n/**\n * Fit RM and EVPA at the reference lambda^2\n * Only fits for up to 5 terms\n * \\param arg      NLRMFitArg structure\n *                 fitted parameters returned in arg->in->coef\n *                 RM, EVPA, sig RM, sig EVPA, chi2\n */\nstatic void NLRMFit (NLRMFitArg *arg)\n{\n  olong iter=0, i, nterm=2, nvalid;\n  ofloat sumwt, fblank = ObitMagicF();\n  double chi2;\n  int status;\n \n  /* Initialize output */\n  if (arg->doError) \n    for (i=0; i<2*nterm+1; i++) arg->coef[i] = 0.0;\n  else\n    for (i=0; i<nterm; i++) arg->coef[i]  = 0.0;\n  /* Blank */\n  arg->coef[0] =  arg->coef[1] = fblank;\n  \n  /* try to unwrap EVPA, get data to be fitted, returns number of valid data \n     and crude fits */\n  nvalid = RMcoarse (arg);\n\n  if (nvalid<=MAX(2,nterm)) return;  /* enough good data for fit? */\n  /* High enough fraction of valid pixels? */\n  if ((((ofloat)nvalid)/((ofloat)arg->nlamb2)) < arg->minFrac) return;\n\n  /* Do fit */\n#ifdef HAVE_GSL\n    /* order EVPA, RM */\n    gsl_vector_set(arg->work, 0, (double)arg->coef[1]);\n    gsl_vector_set(arg->work, 1, (double)arg->coef[0]);\n    arg->funcStruc->n      = arg->nlamb2*2;\n    arg->funcStruc->p      = nterm;\n    arg->funcStruc->params = arg;\n    gsl_multifit_fdfsolver_set (arg->solver, arg->funcStruc, arg->work);\n    iter = 0;\n    /* iteration loop */\n    do {\n      iter++;\n      status = gsl_multifit_fdfsolver_iterate(arg->solver);\n      /*if (status) break;???*/\n\n      status = gsl_multifit_test_delta (arg->solver->dx, arg->solver->x, \n\t\t\t\t\t(double)arg->minDelta, \n\t\t\t\t\t(double)arg->minDelta);\n      /* DEBUG\n      if (nvalid>nterm) {\n\tsumwt = (ofloat)gsl_blas_dnrm2(arg->solver->f);\n\tchi2 = (sumwt*sumwt)/(nvalid-nterm);\n      } else chi2 = -1.0;\n      for (i=0; i<nterm; i++) arg->coef[i] = (ofloat)gsl_vector_get(arg->solver->x, i);\n      fprintf (stderr,\"   iter=%d RM %f EVPA %f chi2 %g status %d\\n\",\n\t       iter, arg->coef[1], arg->coef[0], chi2, status); */\n      /* end DEBUG */\n    } while ((status==GSL_CONTINUE) && (iter<arg->maxIter));\n\n    /* If it didn't work - bail */\n    if ((status!=GSL_SUCCESS) && (status!=GSL_CONTINUE)) {\n      fprintf (stderr, \"Failed, status = %s\\n\", gsl_strerror(status));\n      return;\n    }\n    \n    /* normalized Chi squares */\n    if (nvalid>nterm) {\n      sumwt = (ofloat)gsl_blas_dnrm2(arg->solver->f);\n      chi2 = (sumwt*sumwt)/(nvalid-nterm);\n    } else chi2 = -1.0;\n\n    /* Get fitted values - switch order to RM, EVPA*/\n    arg->coef[0] = (ofloat)gsl_vector_get(arg->solver->x, 1);\n    arg->coef[1] = (ofloat)gsl_vector_get(arg->solver->x, 0);\n      \n    /* Errors wanted? */\n    if (arg->doError) {\n      gsl_matrix *J;\n\n      /* second argument removes degenerate col/row from Jacobean */\n      J = gsl_matrix_alloc(2*arg->nlamb2, 2);\n#ifdef HAVE_GSL_MULTIFIT_FDFSOLVER_JAC\n      gsl_multifit_fdfsolver_jac(arg->solver, J);\n#else\n      gsl_matrix_memcpy(J, arg->solver->J);\n#endif\n      gsl_multifit_covar (J, 1.0e-8, arg->covar);\n      gsl_matrix_free(J);\n      arg->coef[nterm+0] = sqrt(gsl_matrix_get(arg->covar, 1, 1));\n      arg->coef[nterm+1] = sqrt(gsl_matrix_get(arg->covar, 0, 0));\n      arg->coef[4] = chi2;\n    } /* end of get errors */\n      \n#endif /* HAVE_GSL */ \n} /* end NLRMFit */\n\n/**\n * Make crude estimate of RM, EVPA and populate argument arrays\n * \\param arg      NLRMFitArg structure\n *                 Data to be fitted in x,q,u,w\n *                 RM, EVPA in coef\n * \\return number of valid data\n */\nstatic olong RMcoarse (NLRMFitArg *arg)\n{\n  olong i, j, ntest, nvalid, numb;\n  ofloat minDL, maxDL, dRM, tRM, bestRM=0.0, fblank = ObitMagicF();\n  ofloat bestQ, bestU, sumrQ, sumrU, penFact;\n  double aarg, varaarg;\n  odouble amb, res, best, test;\n \n\n  /* get EVLA values count valid data*/\n  nvalid = 0;\n  numb   = 0;\n  for (i=0; i<arg->nlamb2; i++) {\n    if ((arg->Qobs[i]!=fblank) && (arg->Qweight[i]>0.0) &&\n\t(arg->Uobs[i]!=fblank) && (arg->Uweight[i]>0.0)) {\n      arg->x[numb] = arg->lamb2[i] - arg->refLamb2;\n      /* Weight */\n      aarg    = fabs(arg->Uobs[i]/arg->Qobs[i]);\n      varaarg = aarg*aarg*(arg->Qvar[i]/(arg->Qobs[i]*arg->Qobs[i]) + \n\t\t\t   arg->Uvar[i]/(arg->Uobs[i]*arg->Uobs[i]));\n      arg->w[numb] = (1.0+aarg*aarg)/varaarg;\n      /* arg->q[numb] = arg->Qobs[i] * arg->w[numb];\n\t arg->u[numb] = arg->Uobs[i] * arg->w[numb];*/\n      arg->q[numb] = arg->Qobs[i];\n      arg->u[numb] = arg->Uobs[i];\n      /* DEBUG\n      fprintf (stderr, \"%3d x=%8.5f q=%8.5f u=%8.5f w=%8.5g \\n \",\n\t       numb,arg->x[numb], arg->q[numb],arg->u[numb],arg->w[numb]);\n      arg->Qweight[i] = arg->Uweight[i] = 1.0/20.0e-6;\n      fprintf (stderr,\"%3d l2=%g q=%g u=%g p=%f qwt=%g uwt=%g\\n\",\n\t       i,arg->lamb2[i]-arg->refLamb2, arg->Qobs[i], arg->Uobs[i],arg->Pobs[i], \n\t       arg->Qweight[i], arg->Uweight[i]);*/\n     numb++;\n    }\n  }\n  nvalid = numb;\n  if (nvalid<=MAX(2,arg->nterm)) return nvalid;  /* enough good data for fit? */\n  /* High enough fraction of valid pixels? */\n  if ((((ofloat)nvalid)/((ofloat)arg->nlamb2)) < arg->minFrac) return nvalid;\n  arg->nvalid = nvalid;\n\n  /* max and min delta lamb2 - assume lamb2 ordered */\n  maxDL = fabs(arg->x[0]-arg->x[numb-1]);   /* range of actual delta lamb2 */\n  minDL  = 1.0e20; \n  for (i=1; i<numb; i++) minDL = MIN (minDL, fabs(arg->x[i]-arg->x[i-1]));\n  /* \n     ambiguity  = pi/min_dlamb2\n     resolution = pi/max_dlamb2 = RM which gives 1 turn over  lamb2 range\n   */\n  amb = G_PI / fabs(minDL);\n  res = G_PI / maxDL;\n  dRM = 0.05 * res;   /* test RM interval */\n\n  /* DEBUG\n  fprintf (stderr,\"amb = %f res= %f dRM=%f\\n\", amb, res, dRM); */\n  /* end DEBUG */\n  /* Test +/- half ambiguity every dRM */\n  ntest = 1 + 0.5*amb/dRM;\n  ntest =  MIN (ntest, 1001);   /* Some bounds */\n  /* Penalty to downweight solutions away from zero, \n     weight 0.25 at edge of search */\n  penFact = 0.25 / (0.5*ntest);\n  best = -1.0e20;\n  for (i=0; i<ntest; i++) {\n    tRM = (i-ntest/2) * dRM;\n    /* Loop over data samples - first phases to convert to ref Lamb2 */\n    for (j=0; j<numb; j++) arg->wrk1[j]= -2*tRM * arg->x[j];\n    /* sines/cosine */\n    ObitSinCosVec (numb, arg->wrk1, arg->wrk3, arg->wrk2);\n    /* DEBUG\n    if ((fabs(tRM-133.0)<0.95*dRM) || (fabs(tRM-133.)<0.95*dRM)) {\n      for (j=0; j<numb; j++) {\n\ttest = (arg->q[j]*arg->wrk2[j])*(arg->q[j]*arg->wrk2[j]) + \n\t  (arg->u[j]*arg->wrk3[j])*(arg->u[j]*arg->wrk3[j]);\n\tfprintf (stderr,\"   i=%d j=%d t phase=%f obs phase %lf q=%f u=%lf test=%f\\n\",\n\t\t i, j, arg->wrk1[j], 0.5*atan2(arg->u[j],arg->q[j]),\n\t\t (arg->q[j]*arg->wrk2[j] - arg->u[j]*arg->wrk3[j])*1000, \n\t\t (arg->q[j]*arg->wrk3[j] + arg->u[j]*arg->wrk2[j])*1000, \n\t\t test);\n      }\n    } */\n    /* end  DEBUG*/\n    /* Find best sum of weighted amplitudes^2 converted to ref lambda^2 */\n    test = 0.0; sumrQ = sumrU = 0.0;\n    for (j=0; j<numb; j++) {\n      sumrQ += arg->w[j]*(arg->q[j]*arg->wrk2[j] - arg->u[j]*arg->wrk3[j]); \n      sumrU += arg->w[j]*(arg->q[j]*arg->wrk3[j] + arg->u[j]*arg->wrk2[j]);\n    } \n    test = sumrQ*sumrQ + sumrU*sumrU;\n    /* Add penalty */\n    test *= (1.0 - penFact*abs(i-ntest/2));\n    /* DEBUG \n    fprintf (stderr,\" i=%d test=%g  tRM %f sum Q=%f sum U=%f pen %f\\n\",\n\t     i, test, tRM, sumrQ, sumrU,  penFact*abs(i-ntest/2));*/\n  /* end DEBUG */\n    if (test>best) {\n      best = test;\n      bestRM = tRM;\n      bestQ = sumrQ;\n      bestU = sumrU;\n    }\n  }\n\n  /* Save */\n  arg->coef[0] = bestRM;\n  arg->coef[1] = 0.5 * atan2(bestU, bestQ);\n  \n  /* DEBUG \n  fprintf (stderr,\"RM = %f EVPA= %f best=%f dRM=%f\\n\",\n\t   arg->coef[1],arg->coef[0], best, dRM); */\n  /* end DEBUG */\n\n  return nvalid;\n} /* end RMcoarse */\n\n#ifdef HAVE_GSL\n/**\n * Function evaluator for spectral fitting solver\n * Evaluates (model-observed) / sigma\n * \\param x       Vector of parameters to be fitted\n *                Flux,array_of spectral_terms\n * \\param param   Function parameter structure (NLRMFitArg)\n * \\param f       Vector of (model-obs)/sigma for data points\n *                in order q, u each datum\n * \\return completion code GSL_SUCCESS=OK\n */\nstatic int RMFitFunc (const gsl_vector *x, void *params, \n\t\t      gsl_vector *f)\n{\n  NLRMFitArg *args = (NLRMFitArg*)params;\n  ofloat fblank = ObitMagicF();\n  olong nlamb2  = args->nlamb2;\n  double func;\n  odouble RM, EVPA;\n  size_t i, j;\n  /* DEBUG\n  odouble sum=0.0; */\n\n  /* get model parameters */\n  EVPA = gsl_vector_get(x, 0);\n  RM   = gsl_vector_get(x, 1);\n  /* DEBUG\n  fprintf (stderr,\"FitFunc RM=%f EVPA=%f\\n\", RM,EVPA); */\n\n  /* First compute model phases */\n  for (j=0; j<nlamb2; j++) \n    args->wrk1[j] = 2*(EVPA + RM * (args->lamb2[j]-args->refLamb2));\n  /* then sine/cosine */\n  ObitSinCosVec (nlamb2, args->wrk1, args->wrk3, args->wrk2);\n  /* Loop over data - Residuals */\n  for (i=0; i<nlamb2; i++) {\n    /* Q model = args->Pobs[i] * args->wrk2[i]  */\n    if ((args->Qobs[i]!=fblank) && (args->Qweight[i]>0.0)) {\n      func = (args->Pobs[i] * args->wrk2[i] - args->Qobs[i]) * args->Qweight[i];\n      /*  sum += func*func;   DEBUG\n      fprintf (stderr,\"FitFunc q i=%3ld func=%lg obs=%g mod=%g wt=%g p=%f\\n\", \n\t       2*i, func, args->Uobs[i], args->Pobs[i]*args->wrk3[i],\n\t       args->Uweight[i],  args->Pobs[i]); */\n      gsl_vector_set(f, 2*i, func);  /* Save function residual */\n    } else {  /* Invalid data */\n      func = 0.0;\n      gsl_vector_set(f, 2*i, func);     /* Save function residual */\n    }\n    /* U model = args->Pobs[i] * args->wrk3[i]  */\n    if ((args->Uobs[i]!=fblank) && (args->Uweight[i]>0.0)) {\n      func = (args->Pobs[i] * args->wrk3[i] - args->Uobs[i]) * args->Uweight[i];\n      /* sum += func*func;   DEBUG\n      fprintf (stderr,\"FitFunc u i=%3ld func=%lg obs=%g mod=%g wt=%g phs=%f\\n\", \n\t       2*i+1, func, args->Uobs[i], args->Pobs[i]*args->wrk3[i],\n\t       args->Uweight[i], args->wrk1[i]*28.648); */\n      gsl_vector_set(f, 2*i+1, func);  /* Save function residual */\n    } else {  /* Invalid data */\n      func = 0.0;\n      gsl_vector_set(f, 2*i+1, func);     /* Save function residual */\n    }\n  } /* End loop over data */\n  /* DEBUG\n  fprintf (stderr,\"FitFunc RMS=%g\\n\", sqrt(sum)); */\n  \n  return GSL_SUCCESS;\n} /*  end RMFitFunc */\n\n/**\n * Jacobian evaluator for spectral fitting solver\n * Evaluates partial derivatives of model wrt each parameter\n * \\param x       Vector of parameters to be fitted\n *                Flux,array_of spectral_terms\n * \\param param   Function parameter structure (NLRMFitArg)\n * \\param J       Jacobian matrix J[data_point, parameter]\n *                in order q, u each datum\n * \\return completion code GSL_SUCCESS=OK\n */\nstatic int RMFitJac (const gsl_vector *x, void *params, \n\t\t     gsl_matrix *J)\n{\n  NLRMFitArg *args = (NLRMFitArg*)params;\n  ofloat fblank = ObitMagicF();\n  olong nlamb2  = args->nlamb2;\n  odouble RM, EVPA;\n  double jac;\n  size_t i, j;\n\n  /* get model parameters */\n  EVPA = gsl_vector_get(x, 0);\n  RM   = gsl_vector_get(x, 1);\n  /* DEBUG \n  fprintf (stderr,\"FitJac RM=%f EVPA=%f\\n\", RM,EVPA);*/\n\n  /* First compute model phases */\n  for (j=0; j<nlamb2; j++) \n    args->wrk1[j] = 2*(EVPA + RM * (args->lamb2[j]-args->refLamb2));\n  /* then sine/cosine */\n  ObitSinCosVec (nlamb2, args->wrk1, args->wrk3, args->wrk2);\n  /* Loop over data - gradients */\n  for (i=0; i<nlamb2; i++) {\n    j = 0;    /* EVPA */\n    /* d Q model/d EVPA = -args->Pobs[i] * args->wrk3[i]  */\n    if ((args->Qobs[i]!=fblank) && (args->Qweight[i]>0.0)) {\n      jac = -(args->Pobs[i] * args->wrk3[i]) * args->Qweight[i];\n      gsl_matrix_set(J, 2*i, j, jac);  /* Save function gradient */\n    } else {  /* Invalid data */\n      jac = 0.0;\n      gsl_matrix_set(J, 2*i, j, jac);     /* Save function gradient */\n    }\n    /* d U model/d EVPA = args->Pobs[i] * args->wrk2[i]  */\n    if ((args->Uobs[i]!=fblank) && (args->Uweight[i]>0.0)) {\n      jac = (args->Pobs[i] * args->wrk2[i]) * args->Uweight[i];\n      gsl_matrix_set(J, 2*i+1, j, jac);  /* Save function gradient */\n    } else {  /* Invalid data */\n      jac = 0.0;\n      gsl_matrix_set(J, 2*i+1, j, jac);     /* Save function gradient */\n    }\n    j = 1;   /* RM  */\n    /* d Q model/d RM = -2 args->Pobs[i] * args->wrk3[i] * (args->lamb2[i]-args->refLamb2)  */\n    if ((args->Qobs[i]!=fblank) && (args->Qweight[i]>0.0)) {\n      jac = -2*(args->Pobs[i] * args->wrk3[i]) * \n\t(args->lamb2[i]-args->refLamb2) * args->Qweight[i];\n      gsl_matrix_set(J, 2*i, j, jac);  /* Save function gradient */\n    } else {  /* Invalid data */\n      jac = 0.0;\n      gsl_matrix_set(J, 2*i, j, jac);     /* Save function gradient */\n    }\n    /* d U model/d RM = 2 args->Pobs[i] * args->wrk2[i] * (args->lamb2[i]-args->refLamb2) */\n    if ((args->Uobs[i]!=fblank) && (args->Uweight[i]>0.0)) {\n      jac = 2*(args->Pobs[i] * args->wrk2[i]) * \n\t(args->lamb2[i]-args->refLamb2) * args->Uweight[i];\n      gsl_matrix_set(J, 2*i+1, j, jac);  /* Save function gradient */\n    } else {  /* Invalid data */\n      jac = 0.0;\n      gsl_matrix_set(J, 2*i+1, j, jac);     /* Save function gradient */\n    }\n  } /* End loop over data */\n  \n  return GSL_SUCCESS;\n} /*  end RMFitJac */\n\n/**\n * Function and Jacobian evaluator for spectral fitting solver\n * Function = (model-observed) / sigma\n * Jacobian =  partial derivatives of model wrt each parameter\n * \\param x       Vector of parameters to be fitted\n *                Flux,array_of spectral_terms\n * \\param param   Function parameter structure (NLRMFitArg)\n * \\param f       Vector of (model-obs)/sigma for data points\n *                in order q, u each datum\n * \\param J       Jacobian matrix J[data_point, parameter]\n *                in order q, u each datum\n * \\return completion code GSL_SUCCESS=OK\n */\nstatic int RMFitFuncJac (const gsl_vector *x, void *params, \n\t\t\t gsl_vector *f, gsl_matrix *J)\n{\n  NLRMFitArg *args = (NLRMFitArg*)params;\n  ofloat fblank = ObitMagicF();\n  double func, jac;\n  olong nlamb2  = args->nlamb2;\n  odouble RM, EVPA;\n  size_t i, j;\n  /* DEBUG\n  odouble sum=0.0; */\n\n  /* get model parameters */\n  EVPA = gsl_vector_get(x, 0);\n  RM   = gsl_vector_get(x, 1);\n  /* DEBUG\n  fprintf (stderr,\"FuncJac RM=%f EVPA=%f\\n\", RM,EVPA); */\n\n  /* First compute model phases */\n  for (j=0; j<nlamb2; j++) \n    args->wrk1[j] = 2*(EVPA + RM * (args->lamb2[j]-args->refLamb2));\n  /* then sine/cosine */\n  ObitSinCosVec (nlamb2, args->wrk1, args->wrk3, args->wrk2);\n  /* Loop over data - gradients */\n  for (i=0; i<nlamb2; i++) {\n    if ((args->Qobs[i]!=fblank) && (args->Qweight[i]>0.0)) {\n      /* Q model   = args->Pobs[i] * args->wrk2[i]  */\n      func = (args->Pobs[i] * args->wrk2[i] - args->Qobs[i]) * args->Qweight[i];\n      /* sum += func*func;   DEBUG */\n      /* DEBUG\n      fprintf (stderr,\"FuncJac q i=%3ld func=%lg obs=%g mod=%g wt=%g p=%f\\n\", \n\t       2*i, func, args->Qobs[i], args->Pobs[i] * args->wrk2[i],\n\t       args->Qweight[i], args->Pobs[i]); */\n      gsl_vector_set(f, 2*i, func);  /* Save function residual */\n      j = 0;    /* EVPA */\n      /* d Q model/d EVPA = -args->Pobs[i] * args->wrk3[i]  */\n      jac = -(args->Pobs[i] * args->wrk3[i]) * args->Qweight[i];\n      /* DEBUG\n      fprintf (stderr,\"FuncJac q i=%3ld j=%3ld jac=%lf\\n\", 2*i, j, jac); */\n      gsl_matrix_set(J, 2*i, j, jac);  /* Save function residual */\n      j = 1;   /* RM  */\n      /* d Q model/d RM = -2 args->Pobs[i] * args->wrk3[i] * (args->lamb2[i]-args->refLamb2)  */\n      jac = -2*(args->Pobs[i] * args->wrk3[i]) * \n\t(args->lamb2[i]-args->refLamb2) * args->Qweight[i];\n      /* DEBUG \n      fprintf (stderr,\"FuncJac q i=%3ld j=%3ld jac=%lf\\n\", 2*i+1, j, jac);*/\n      gsl_matrix_set(J, 2*i, j, jac);  /* Save function gradient */\n    } else {  /* Invalid data */\n      func = 0.0;\n      gsl_vector_set(f, 2*i, func);\n      j = 0;    /* EVPA */\n      jac = 0.0;\n      gsl_matrix_set(J, 2*i, j, jac);\n      j = 1;   /* RM  */\n      gsl_matrix_set(J, 2*i, j, jac);\n    }\n    if ((args->Uobs[i]!=fblank) && (args->Uweight[i]>0.0)) {\n      /* U model   = 2 args->Pobs[i] * args->wrk3[i]  */\n      func = (args->Pobs[i] * args->wrk3[i] - args->Uobs[i]) * args->Uweight[i];\n      /* sum += func*func;   DEBUG */\n      /* DEBUG\n      fprintf (stderr,\"FuncJac u i=%3ld func=%lg obs=%g mod=%g wt=%g phs=%f\\n\", \n\t       2*i+1, func, args->Uobs[i], args->Pobs[i]*args->wrk3[i],\n\t       args->Uweight[i], args->wrk1[i]*28.648); */\n      gsl_vector_set(f, 2*i+1, func);  /* Save function residual */\n      j = 0;    /* EVPA */\n      /* d U model/d EVPA = args->Pobs[i] * args->wrk2[i]  */\n      jac = (args->Pobs[i] * args->wrk2[i]) * args->Uweight[i];\n      /* DEBUG\n      fprintf (stderr,\"FuncJac u i=%3ld j=%3ld jac=%lf\\n\", 2*i, j, jac); */\n      gsl_matrix_set(J, 2*i+1, j, jac);  /* Save function gradient */\n      j = 1;   /* RM  */\n      /* d U model/d RM = args->Pobs[i] * args->wrk2[i] * (args->lamb2[i]-args->refLamb2) */\n      jac = 2*(args->Pobs[i] * args->wrk2[i]) * \n\t(args->lamb2[i]-args->refLamb2) * args->Uweight[i];\n      /* DEBUG\n      fprintf (stderr,\"FuncJac u i=%3ld j=%3ld jac=%lf\\n\", 2*i+1, j, jac); */\n      gsl_matrix_set(J, 2*i+1, j, jac);  /* Save function gradient */      \n    } else {  /* Invalid data */\n      func = 0.0;\n      gsl_vector_set(f, 2*i+1, func);\n      j = 0;    /* EVPA */\n      jac = 0.0;\n      gsl_matrix_set(J, 2*i+1, j, jac);\n      j = 1;   /* RM  */\n      gsl_matrix_set(J, 2*i+1, j, jac);\n    }\n  } /* End loop over data */\n   /* DEBUG\n  fprintf (stderr,\"FuncJac RMS=%g\\n\", sqrt(sum)); */\n \n  return GSL_SUCCESS;\n} /*  end RMFitFuncJac */\n#endif /* HAVE_GSL */ \n\n/* RM Synthesis max routines */\n/**\n * Thread function to RM Synthesis Max fit a portion of the image set\n * \\param arg      NLRMFitArg structure\n * \\li             coef[0]=RM, coef[1]=amp, coef[2]=phase, coef[3]=RMS Q,U\n */\nstatic gpointer ThreadRMSynFit (gpointer arg)\n{\n  NLRMFitArg *larg    = (NLRMFitArg*)arg;\n  ObitRMFit* in       = (ObitRMFit*)larg->in;\n  olong lo            = larg->first-1;  /* First in y range */\n  olong hi            = larg->last;     /* Highest in y range */\n  ObitErr *err        = larg->err;\n\n  olong ix, iy, indx, i, besti;\n  ofloat fblank = ObitMagicF();\n  olong j, ntest, nvalid, numb;\n  ofloat minDL, maxDL, dRM, tRM, bestRM=0.0;\n  ofloat bestQ, bestU, sumrQ, sumrU, sumW=0.0, EVPA, amp;\n  double aarg, varaarg;\n  odouble amb, res, best, test;\n /*gchar *routine = \"ThreadRMSynFit\";*/\n\n  /* error checks */\n  if (err->error) return NULL;\n  g_assert (ObitIsA(in, &myClassInfo));\n\n  /* Set up frequency info if in given */\n  if (in) {\n    larg->refLamb2 = in->refLamb2;\n    for (i=0; i<in->nlamb2; i++) {\n      larg->lamb2[i] = in->lamb2[i];\n    }\n  }\n\n  /* Loop over pixels in Y */\n  indx = lo*in->nx  -1;  /* Offset in pixel arrays */\n  for (iy=lo; iy<hi; iy++) {\n    /* Loop over pixels in X */\n    for (ix=0; ix<in->nx; ix++) {\n      indx ++;\n\n      /* Collect values;  */\n      for (i=0; i<in->nlamb2; i++) {\n\tlarg->Qobs[i] = in->inQFArrays[i]->array[indx];\n\tlarg->Uobs[i] = in->inUFArrays[i]->array[indx];\n\t/* Data valid? */\n\tif ((larg->Qobs[i]!=fblank) && \n\t    (larg->Uobs[i]!=fblank) && \n\t    ((fabs(larg->Qobs[i])>in->minQUSNR*in->QRMS[i]) ||\n\t     (fabs(larg->Uobs[i])>in->minQUSNR*in->URMS[i]))) {\n\t  /* Statistical weight */\n\t  larg->Qvar[i] = (in->QRMS[i]*in->QRMS[i]);\n\t  larg->Uvar[i] = (in->URMS[i]*in->URMS[i]);\n\t  larg->Qweight[i] = 1.0 / in->QRMS[i];\n\t  larg->Uweight[i] = 1.0 / in->URMS[i];\n\t  /* End if datum valid */\n\t} else { /* invalid pixel */\n\t  larg->Qweight[i] = 0.0;\n\t  larg->Uweight[i] = 0.0;\n\t}\n\t/* DEBUG\n\tif ((ix==669) && (iy==449)) { \n\t  fprintf (stderr,\"%3d q=%g u=%g qs=%g us=%g wt=%f\\n\",\n\t\t   i, larg->Qobs[i], larg->Uobs[i], in->QRMS[i], in->URMS[i], larg->Qweight[i]);\n\t} */\n      } /* end loop over frequencies */\n      \n      /* Fit coef[0]=RM, coef[1]=amp, coef[2]=phase, coef[3]=RMS Q,U */\n      /* get  values count valid data*/\n      numb   = 0; sumW = 0.0;\n      for (i=0; i<larg->nlamb2; i++) {\n\tif ((larg->Qweight[i]>0.0) && (larg->Uweight[i]>0.0)) {\n\t  larg->x[numb] = larg->lamb2[i] - larg->refLamb2;\n\t  /* Weight of polarized amplitude */\n\t  aarg    = fabs(larg->Uobs[i]/larg->Qobs[i]);\n\t  varaarg = aarg*aarg*(larg->Qvar[i]/(larg->Qobs[i]*larg->Qobs[i]) + \n\t\t\t       larg->Uvar[i]/(larg->Uobs[i]*larg->Uobs[i]));\n\t  larg->w[numb] = (1.0+aarg*aarg)/varaarg;\n\t  larg->q[numb] = larg->Qobs[i];\n\t  larg->u[numb] = larg->Uobs[i];\n\t  sumW  += larg->w[numb];\n\t  /* DEBUG\n\t     fprintf (stderr, \"%3d x=%8.5f q=%8.5f u=%8.5f w=%8.5g \\n \",\n\t     numb,larg->x[numb], larg->q[numb],larg->u[numb],larg->w[numb]);\n\t     larg->Qweight[i] = larg->Uweight[i] = 1.0/20.0e-6;\n\t     fprintf (stderr,\"%3d l2=%g q=%g u=%g p=%f qwt=%g uwt=%g\\n\",\n\t     i,larg->lamb2[i]-larg->refLamb2, larg->Qobs[i], larg->Uobs[i],larg->Pobs[i], \n\t     larg->Qweight[i], larg->Uweight[i]);*/\n\t  numb++;\n\t}\n      }\n      nvalid = numb;\n      /* enough data? */\n      if ((nvalid<=2) || ((((ofloat)nvalid)/((ofloat)larg->nlamb2)) < larg->minFrac)) {\n\tbestRM = EVPA = fblank;  amp = 0.0; sumrQ = sumrU = 1000.0;\n\tgoto doneFit;\n      }\n      \n      /* max and min delta lamb2 - assume lamb2 ordered */\n      maxDL = fabs(larg->x[0]-larg->x[numb-1]);   /* range of actual delta lamb2 */\n      minDL  = 1.0e20; \n      for (i=1; i<numb; i++) minDL = MIN (minDL, fabs(larg->x[i]-larg->x[i-1]));\n      /* \n\t ambiguity  = pi/min_dlamb2\n\t resolution = pi/max_dlamb2 = RM which gives 1 turn over  lamb2 range\n      */\n      if (in->maxRMSyn>in->minRMSyn) {\n\tdRM = MAX (0.01,in->delRMSyn);\n\tntest = 1+(in->maxRMSyn - in->minRMSyn)/dRM;\n      } else {\n\tamb = G_PI / fabs(minDL);\n\tres = G_PI / maxDL;\n\tdRM = 0.05 * res;   /* test RM interval */\n\t/* Test +/- 0.05 ambiguity every dRM */\n\tntest = 1 + amb/(0.05*dRM);\n\tdRM *= 0.05;\n \tin->minRMSyn = -(ntest/2) * dRM;\n     }\n      ntest =  MIN (ntest, 10001);   /* Some bounds */\n     \n      /* DEBUG\n\t fprintf (stderr,\"amb = %f res= %f dRM=%f\\n\", amb, res, dRM); */\n      /* end DEBUG */\n      best = -1.0e20; besti = 0;\n      for (i=0; i<ntest; i++) {\n\ttRM = in->minRMSyn + i * dRM;\n\t/* Loop over data samples - first phases to convert to ref Lamb2 */\n\tfor (j=0; j<numb; j++) larg->wrk1[j]= -2*tRM * larg->x[j];\n\t/* sines/cosine */\n\tObitSinCosVec (numb, larg->wrk1, larg->wrk3, larg->wrk2);\n\t/* Find best sum of weighted amplitudes^2 converted to ref lambda^2 */\n\ttest = 0.0; sumrQ = sumrU = 0.0;\n\tfor (j=0; j<numb; j++) {\n\t  sumrQ += larg->w[j]*(larg->q[j]*larg->wrk2[j] - larg->u[j]*larg->wrk3[j]); \n\t  sumrU += larg->w[j]*(larg->q[j]*larg->wrk3[j] + larg->u[j]*larg->wrk2[j]);\n\t} \n\ttest = sumrQ*sumrQ + sumrU*sumrU;\n\t/* DEBUG \n\t   fprintf (stderr,\" i=%d test=%g  tRM %f sum Q=%f sum U=%f pen %f\\n\",\n\t   i, test, tRM, sumrQ, sumrU,  penFact*abs(i-ntest/2));*/\n\t/* end DEBUG */\n\tif (test>best) {\n\t  besti = i;\n\t  best = test;\n\t  bestRM = tRM;\n\t  bestQ = sumrQ;\n\t  bestU = sumrU;\n\t}\n      }\n      /* Get chi sq for fit */\n      EVPA = 0.5 * atan2(bestU, bestQ);\n      amp = sqrtf(bestU*bestU + bestQ*bestQ)/sumW;\n      tRM = bestRM;\n      /* Loop over data samples - first phases to convert to ref Lamb2 */\n      for (j=0; j<larg->nlamb2; j++) \n\tlarg->wrk1[j]= 2*tRM * (larg->lamb2[j]-larg->refLamb2) + 2.0*EVPA;\n      /* sines/cosine */\n      ObitSinCosVec (larg->nlamb2, larg->wrk1, larg->wrk3, larg->wrk2);\n      sumrQ = sumrU = 0.0; numb = 0;\n      for (j=0; j<larg->nlamb2; j++) {\n\tif ((larg->Qweight[j]>0.0) && (larg->Uweight[j]>0.0)) {\n\t  numb += 2;\n\t  sumrQ += (larg->Qobs[j]-amp*larg->wrk2[j])*(larg->Qobs[j]-amp*larg->wrk2[j])/larg->Qvar[j]; \n\t  sumrU += (larg->Uobs[j]-amp*larg->wrk3[j])*(larg->Uobs[j]-amp*larg->wrk3[j])/larg->Uvar[j];\n\t}\n      } \n      sumrQ /= numb; sumrU /= numb; \n      /* Save */\n    doneFit:\n      larg->coef[0] = bestRM;\n      larg->coef[1] = EVPA;\n      larg->coef[2] = amp;\n      larg->coef[3] = (sumrQ+sumrU);\n      /* Edit */\n      if ((larg->coef[3]>in->maxChi2) || (besti<=0) || (besti>=(ntest-1))) {\n\tlarg->coef[0] = larg->coef[1] = fblank;\n      }\n  \n      /* DEBUG\n      if ((ix==669) && (iy==449)) { \n\t fprintf (stderr,\"ix=%4d iy=%4d\\n\",ix+1,iy+1);\n\t fprintf (stderr,\"RM=%f EVPA=%f chi2=%f\\n\",\n\t\t  larg->coef[0], larg->coef[1],larg->coef[4]);\n      } */\n      \n      /* Save to output */\n      for (i=0; i<4; i++) \n\tin->outFArrays[i]->array[indx] = larg->coef[i];\n    } /* end x loop */\n  } /* end y loop */\n\n  /* Indicate completion */\n  if (larg->ithread>=0)\n    ObitThreadPoolDone (in->thread, (gpointer)&larg->ithread);\n\n  return NULL;\n} /* end ThreadRMSynFit */\n\n", "meta": {"hexsha": "5e486e4b687338e6754e2332f03e485084fa130d", "size": 86248, "ext": "c", "lang": "C", "max_stars_repo_path": "ObitSystem/Obit/src/ObitRMFit.c", "max_stars_repo_name": "kettenis/Obit", "max_stars_repo_head_hexsha": "3f835799918065b149a1e73a6a140cb5eed466c5", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ObitSystem/Obit/src/ObitRMFit.c", "max_issues_repo_name": "kettenis/Obit", "max_issues_repo_head_hexsha": "3f835799918065b149a1e73a6a140cb5eed466c5", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ObitSystem/Obit/src/ObitRMFit.c", "max_forks_repo_name": "kettenis/Obit", "max_forks_repo_head_hexsha": "3f835799918065b149a1e73a6a140cb5eed466c5", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-22T14:07:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-22T14:07:41.000Z", "avg_line_length": 37.0004290004, "max_line_length": 103, "alphanum_fraction": 0.6054401261, "num_tokens": 29408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4921881357207955, "lm_q2_score": 0.039638843213543364, "lm_q1q2_score": 0.019509768343402813}}
{"text": "//\r\n// Copyright (c) Microsoft. All rights reserved.\r\n// This code is licensed under the MIT License (MIT).\r\n// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF\r\n// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY\r\n// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR\r\n// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.\r\n//\r\n// Developed by Minigraph\r\n//\r\n// Author:  James Stanard \r\n//\r\n\r\n#pragma once\r\n\r\n#pragma warning(disable:4201) // nonstandard extension used : nameless struct/union\r\n#pragma warning(disable:4238) // nonstandard extension used : class rvalue used as lvalue\r\n#pragma warning(disable:4324) // structure was padded due to __declspec(align())\r\n\r\n#ifndef WIN32_LEAN_AND_MEAN\r\n    #define WIN32_LEAN_AND_MEAN\r\n#endif\r\n#ifndef NOMINMAX\r\n    #define NOMINMAX\r\n#endif\r\n#include <windows.h>\r\n\r\n#include <d3d12.h>\r\n\r\n#pragma comment(lib, \"d3d12.lib\")\r\n#pragma comment(lib, \"dxgi.lib\")\r\n\r\n#define MY_IID_PPV_ARGS IID_PPV_ARGS\r\n#define D3D12_GPU_VIRTUAL_ADDRESS_NULL      ((D3D12_GPU_VIRTUAL_ADDRESS)0)\r\n#define D3D12_GPU_VIRTUAL_ADDRESS_UNKNOWN   ((D3D12_GPU_VIRTUAL_ADDRESS)-1)\r\n\r\n\r\n#pragma region\r\n#include <d3dx12.h>\r\n#include <d3d12shader.h>\r\n#include <d3dcompiler.h>\r\n#pragma endregion\r\n\r\n\r\n#pragma region\r\n\r\n#pragma comment (lib, \"d3dcompiler.lib\")\r\n\r\n#pragma endregion\r\n\r\n#include <cstdint>\r\n#include <cstdio>\r\n#include <cstdarg>\r\n#include <vector>\r\n#include <memory>\r\n#include <string>\r\n#include <exception>\r\n#include <numeric>\r\n#include <wrl.h>\r\n#include <ppltasks.h>\r\n#include <gsl\\gsl>\r\n\r\n#include \"Utility.h\"\r\n#include \"VectorMath.h\"\r\n#include \"EngineTuning.h\"\r\n#include \"EngineProfiling.h\"\r\n\r\ntemplate< typename T >\r\nusing NotNull = gsl::not_null< T >;\r\n\r\n#define SHADER_ARGS(shader) (shader), \\\r\n\t\t\t\t\t\t\t\t sizeof(shader)\r\n\r\ntemplate<typename T, std::size_t N>\r\nstruct Array :public std::array<T, N>\r\n{\r\n    static inline std::function<T(T, T)> multiply = [](T priview, T current) {\r\n        return priview * current;\r\n    };\r\npublic:\r\n    T product()\r\n    {\r\n        return std::accumulate(begin(), end(), 1, multiply);\r\n    }\r\n    \r\n};\r\n\r\nusing U32 = uint32_t;\r\nusing U32x1 = U32;\r\nusing U32x2 = Array<U32, 2>;\r\nusing U32x3 = Array<U32, 3>;\r\nusing F32 = float;\r\nusing F32x2 = Array<F32, 2>;\r\nusing F32x3 = Array<F32, 3>;", "meta": {"hexsha": "aefc0ff0ef2aca0c5568b53b5f0b23b3546c4553", "size": 2245, "ext": "h", "lang": "C", "max_stars_repo_path": "MiniEngine/Core/pch.h", "max_stars_repo_name": "sienaiwun/DirectX-Graphics-Samples", "max_stars_repo_head_hexsha": "2222a913905ba17c587dfedf04425fc8acfa06d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MiniEngine/Core/pch.h", "max_issues_repo_name": "sienaiwun/DirectX-Graphics-Samples", "max_issues_repo_head_hexsha": "2222a913905ba17c587dfedf04425fc8acfa06d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MiniEngine/Core/pch.h", "max_forks_repo_name": "sienaiwun/DirectX-Graphics-Samples", "max_forks_repo_head_hexsha": "2222a913905ba17c587dfedf04425fc8acfa06d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8829787234, "max_line_length": 90, "alphanum_fraction": 0.6864142539, "num_tokens": 584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34864514886966624, "lm_q2_score": 0.05582313917112876, "lm_q1q2_score": 0.019462466666690284}}
{"text": "#include <cblas.h>\n#include <clapack.h>\n#ifdef NoChange\n   #define dgeqrf_ dgeqrf\n#elif defined(UpCase)\n   #define dgeqrf_ DGEQRF\n#endif\nmain(int nargs, char **args)\n{\n   extern void dgeqrf_(F77_INTEGER*,F77_INTEGER*,double*,F77_INTEGER*,\n                       double*,double*,F77_INTEGER*,F77_INTEGER*);\n   double A[1]={1.0}, b[1]={1.0}, c[1];\n   F77_INTEGER N=1, info;\n   dgeqrf_(&N, &N, A, &N, b, c, &N, &info);\n}\n", "meta": {"hexsha": "ffb3ac45c58c24f6288762ae76da681cfee05a52", "size": 418, "ext": "c", "lang": "C", "max_stars_repo_path": "lib/qr.c", "max_stars_repo_name": "kevleyski/math-atlas", "max_stars_repo_head_hexsha": "cc36aa7e0362c577739ac507378068882834825e", "max_stars_repo_licenses": ["BSD-3-Clause-Clear"], "max_stars_count": 135.0, "max_stars_repo_stars_event_min_datetime": "2015-01-08T20:35:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T02:26:28.000Z", "max_issues_repo_path": "lib/qr.c", "max_issues_repo_name": "kevleyski/math-atlas", "max_issues_repo_head_hexsha": "cc36aa7e0362c577739ac507378068882834825e", "max_issues_repo_licenses": ["BSD-3-Clause-Clear"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2015-01-13T15:19:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-05T20:00:27.000Z", "max_forks_repo_path": "lib/qr.c", "max_forks_repo_name": "kevleyski/math-atlas", "max_forks_repo_head_hexsha": "cc36aa7e0362c577739ac507378068882834825e", "max_forks_repo_licenses": ["BSD-3-Clause-Clear"], "max_forks_count": 47.0, "max_forks_repo_forks_event_min_datetime": "2015-01-27T06:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-11T20:59:04.000Z", "avg_line_length": 26.125, "max_line_length": 70, "alphanum_fraction": 0.6267942584, "num_tokens": 156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101676450173545, "lm_q2_score": 0.04208772881675952, "lm_q1q2_score": 0.01940314856432893}}
{"text": "#include <stdio.h>\n#include <gsl_rng.h>\n#include <gsl_randist.h>\n\nint main(int argv, char* argc[])\n{\n  // Regression test for https://github.com/conda-forge/ipopt-feedstock/issues/57\n  gsl_rng *r = gsl_rng_alloc(gsl_rng_mt19937);\n  \n  if (r == NULL) \n  {\n    return 1;\n  }\n  \n  gsl_rng_free(r);\n\n  return 0;\n}\n", "meta": {"hexsha": "a1ca035d596f65e4cda83659bb0fbd9937309588", "size": 310, "ext": "c", "lang": "C", "max_stars_repo_path": "recipe/test/regression_test.c", "max_stars_repo_name": "hmaarrfk/gsl-feedstock", "max_stars_repo_head_hexsha": "7ecbeb17ea5b98c7483c349c01eab5c6bdf1a25f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "recipe/test/regression_test.c", "max_issues_repo_name": "hmaarrfk/gsl-feedstock", "max_issues_repo_head_hexsha": "7ecbeb17ea5b98c7483c349c01eab5c6bdf1a25f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "recipe/test/regression_test.c", "max_forks_repo_name": "hmaarrfk/gsl-feedstock", "max_forks_repo_head_hexsha": "7ecbeb17ea5b98c7483c349c01eab5c6bdf1a25f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.3157894737, "max_line_length": 81, "alphanum_fraction": 0.6516129032, "num_tokens": 98, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36296920551961676, "lm_q2_score": 0.05340333055309902, "lm_q1q2_score": 0.019383764462959824}}
{"text": "/* err/test_errnos.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#include <config.h>\n\n#include <stdio.h>\n#include <stdlib.h>\n\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_test.h>\n\n#define CHECK(x) errors[n].number = x ; errors[n].name = #x ; n++ ;\n#define MAX_ERRS 64\n\nint verbose = 0 ;\n\nint\nmain (void)\n{\n  int i, j, n = 0 ;\n\n  struct { \n    int number; \n    const char * name; \n  } errors[MAX_ERRS] ;\n\n  CHECK(GSL_SUCCESS);\n  CHECK(GSL_FAILURE);\n  CHECK(GSL_CONTINUE);\n  CHECK(GSL_EDOM);\n  CHECK(GSL_ERANGE);\n  CHECK(GSL_EFAULT);\n  CHECK(GSL_EINVAL);\n  CHECK(GSL_EFAILED);\n  CHECK(GSL_EFACTOR);\n  CHECK(GSL_ESANITY);\n  CHECK(GSL_ENOMEM);\n  CHECK(GSL_EBADFUNC);\n  CHECK(GSL_ERUNAWAY);\n  CHECK(GSL_EMAXITER);\n  CHECK(GSL_EZERODIV);\n  CHECK(GSL_EBADTOL);\n  CHECK(GSL_ETOL);\n  CHECK(GSL_EUNDRFLW);\n  CHECK(GSL_EOVRFLW);\n  CHECK(GSL_ELOSS);\n  CHECK(GSL_EROUND);\n  CHECK(GSL_EBADLEN);\n  CHECK(GSL_ENOTSQR);\n  CHECK(GSL_ESING);\n  CHECK(GSL_EDIVERGE);\n  CHECK(GSL_EUNSUP);\n  CHECK(GSL_EUNIMPL);\n  CHECK(GSL_ECACHE);\n  CHECK(GSL_ETABLE);\n  CHECK(GSL_ENOPROG);\n  CHECK(GSL_ENOPROGJ);\n  CHECK(GSL_ETOLF);\n  CHECK(GSL_ETOLX);\n  CHECK(GSL_ETOLG);\n  CHECK(GSL_EOF);\n\n  for (i = 0 ; i < n ; i++) \n    {\n      if (verbose) printf (\"%s = %d\\n\", errors[i].name, errors[i].number) ;\n    }\n\n  for (i = 0; i < n; i++)\n    {\n      int status = 0;\n      for (j = 0; j < n; j++)\n\t{\n\t  if (j != i)\n\t      status |= (errors[i].number == errors[j].number);\n\t}\n\n      gsl_test (status, \"%s is distinct from other error values\",\n\t\terrors[i].name);\n    }\n\n  for (i = 0; i < n; i++)\n    {\n      int status = 0;\n      int e1 = errors[i].number ;\n      for (j = 0; j < n; j++)\n\t{\n\t  if (j != i)\n\t    {\n\t      int e2 = errors[j].number;\n\t      status |= (gsl_strerror(e1) == gsl_strerror(e2)) ;\n\t    }\n\t}\n      gsl_test (status, \"%s has a distinct error message\",\n\t\terrors[i].name);\n    }\n\n  \n  exit (gsl_test_summary ());\n}\n\n", "meta": {"hexsha": "9e2741d26daa70d287b2f504a89fb344b2986153", "size": 2636, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/err/test.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/err/test.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/err/test.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 22.5299145299, "max_line_length": 75, "alphanum_fraction": 0.6365705615, "num_tokens": 832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3522017820478897, "lm_q2_score": 0.05500529100440716, "lm_q1q2_score": 0.01937296151381496}}
{"text": "#ifndef MSHADOW_TENSOR_BASE_H\n#define MSHADOW_TENSOR_BASE_H\n/*!\n * \\file tensor_base.h\n * \\brief definitions of base types, macros functions\n *\n * \\author Bing Xu, Tianqi Chen\n */\n#include <cmath>\n#include <cstdio>\n#include <cfloat>\n#include <climits>\n#include <algorithm>\n// macro defintiions\n\n/*!\\brief if this macro is define to be 1, mshadow should compile without any of other libs */\n#ifndef MSHADOW_STAND_ALONE\n    #define MSHADOW_STAND_ALONE 0\n#endif\n\n/*! \\brief whether do padding during allocation */\n#ifndef MSHADOW_ALLOC_PAD\n    #define MSHADOW_ALLOC_PAD true\n#endif\n\n/*! \n * \\brief x dimension of data must be bigger pad_size * ratio to be alloced padded memory, otherwise use tide allocation \n *        for example, if pad_ratio=2, GPU memory alignement size is 32, then we will only allocate padded memory if x dimension > 64\n *        set it to 0 then we will always allocate padded memory\n */\n#ifndef MSHADOW_MIN_PAD_RATIO\n    #define MSHADOW_MIN_PAD_RATIO 2\n#endif\n\n#if MSHADOW_STAND_ALONE\n   #define MSHADOW_USE_CBLAS 0\n   #define MSHADOW_USE_MKL   0\n   #define MSHADOW_USE_CUDA  0\n#endif\n\n/*! \\brief use CBLAS for CBLAS */\n#ifndef MSHADOW_USE_CBLAS\n   #define MSHADOW_USE_CBLAS 0\n#endif\n/*! \\brief use MKL for BLAS */\n#ifndef MSHADOW_USE_MKL\n   #define MSHADOW_USE_MKL   1\n#endif\n/*! \\brief use CUDA support, must ensure that the cuda include path is correct, or directly compile using nvcc */\n#ifndef MSHADOW_USE_CUDA\n  #define MSHADOW_USE_CUDA   1\n#endif\n/*! \\brief use single precition float */\n#ifndef MSHADOW_SINGLE_PRECISION\n  #define MSHADOW_SINGLE_PRECISION 1\n#endif\n/*! \\brief whether use SSE */\n#ifndef MSHADOW_USE_SSE\n  #define MSHADOW_USE_SSE 1\n#endif\n/*! \\brief whether use NVML to get dynamic info */\n#ifndef MSHADOW_USE_NVML\n  #define MSHADOW_USE_NVML 0\n#endif\n// SSE is conflict with cudacc\n#ifdef __CUDACC__\n  #undef MSHADOW_USE_SSE\n  #define MSHADOW_USE_SSE 0\n#endif\n\n#if MSHADOW_USE_CBLAS\nextern \"C\"{\n    #include <cblas.h>\n}\n#elif MSHADOW_USE_MKL\n  #include <mkl.h>\n  #include <mkl_cblas.h>\n  #include <mkl_vsl.h>\n  #include <mkl_vsl_functions.h>\n#endif\n\n#if MSHADOW_USE_CUDA\n  #include <cublas.h>\n  #include <curand.h>\n#endif\n\n#if MSHADOW_USE_NVML\n  #include <nvml.h>\n#endif\n// --------------------------------\n// MSHADOW_XINLINE is used for inlining template code for both CUDA and CPU code.\n#ifdef MSHADOW_XINLINE\n  #error \"MSHADOW_XINLINE must not be defined\"\n#endif\n#ifdef __CUDACC__\n  #define MSHADOW_XINLINE inline __attribute__((always_inline)) __device__ __host__\n#else\n  #define MSHADOW_XINLINE inline __attribute__((always_inline))\n#endif\n/*! \\brief cpu force inline */\n#define MSHADOW_CINLINE inline __attribute__((always_inline))\n\n#if defined(__GXX_EXPERIMENTAL_CXX0X) || defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L\n  #define MSHADOW_CONSTEXPR constexpr\n#else\n  #define MSHADOW_CONSTEXPR const\n#endif\n\n/*! \\brief namespace for mshadow */\nnamespace mshadow {\n    /*! \\brief buffer size for each random number generator */\n    const unsigned kRandBufferSize = 1000000;\n    /*! \\brief pi  */\n    const float kPi = 3.1415926f;\n\n#if MSHADOW_SINGLE_PRECISION\n    /*! \\brief type that will be used for content */\n    typedef float real_t;\n#else\n    typedef double real_t;\n#endif\n    /*! \\brief type that will be used for index */\n    typedef unsigned index_t;\n}; // namespace mshadow\n\nnamespace mshadow {\n    /*! \\brief namespace for operators */\n    namespace op {\n        // binary operator\n        /*! \\brief mul operator */\n        struct mul{\n            /*! \\brief map a, b to result using defined operation */\n            MSHADOW_XINLINE static real_t Map(real_t a, real_t b) {\n                return a * b;\n            }\n        };\n        /*! \\brief plus operator */\n        struct plus {\n            /*! \\brief map a, b to result using defined operation */\n            MSHADOW_XINLINE static real_t Map(real_t a, real_t b) {\n                return a + b;\n            }\n        };\n        /*! \\brief minus operator */\n        struct minus {\n            /*! \\brief map a, b to result using defined operation */\n            MSHADOW_XINLINE static real_t Map(real_t a, real_t b) {\n                return a - b;\n            }\n        };\n        /*! \\brief divide operator */\n        struct div {\n            /*! \\brief map a, b to result using defined operation */\n            MSHADOW_XINLINE static real_t Map(real_t a, real_t b) {\n                return a / b;\n            }\n        };\n        /*! \\brief get rhs */\n        struct right {\n            /*! \\brief map a, b to result using defined operation */\n            MSHADOW_XINLINE static real_t Map(real_t a, real_t b) {\n                return b;\n            }\n        };\n    }; // namespace op\n\n    /*! \\brief namespace for savers */\n    namespace sv {\n        /*! \\brief save to saver: = */\n        struct saveto {\n            /*! \\brief save b to a using save method */\n            MSHADOW_XINLINE static void Save(real_t& a, real_t b) {\n                a  = b;\n            }\n            /*! \\brief helper constant to use BLAS, alpha */\n            MSHADOW_CONSTEXPR static real_t kAlphaBLAS = 1.0f;\n            /*! \\brief helper constant to use BLAS, beta */\n            MSHADOW_CONSTEXPR static real_t kBetaBLAS  = 0.0f;\n            /*! \\brief corresponding binary operator type */\n            typedef op::right OPType;\n        };\n        /*! \\brief save to saver: += */\n        struct plusto {\n            /*! \\brief save b to a using save method */\n            MSHADOW_XINLINE static void Save(real_t& a, real_t b) {\n                a += b;\n            }\n            /*! \\brief helper constant to use BLAS, alpha */\n            MSHADOW_CONSTEXPR static real_t kAlphaBLAS = 1.0f;\n            /*! \\brief helper constant to use BLAS, beta */\n            MSHADOW_CONSTEXPR static real_t kBetaBLAS  = 1.0f;\n            /*! \\brief corresponding binary operator type */\n            typedef op::plus OPType;\n        };\n        /*! \\brief minus to saver: -= */\n        struct minusto {\n            /*! \\brief save b to a using save method */\n            MSHADOW_XINLINE static void Save(real_t& a, real_t b) {\n                a -= b;\n            }\n            /*! \\brief helper constant to use BLAS, alpha */\n            MSHADOW_CONSTEXPR static real_t kAlphaBLAS = -1.0f;\n            /*! \\brief helper constant to use BLAS, beta */\n            MSHADOW_CONSTEXPR static real_t kBetaBLAS  = 1.0f;\n            /*! \\brief corresponding binary operator type */\n            typedef op::minus OPType;\n        };\n        /*! \\brief multiply to saver: *= */\n        struct multo {\n            /*! \\brief save b to a using save method */\n            MSHADOW_XINLINE static void Save(real_t& a, real_t b) {\n                a *= b;\n            }\n            /*! \\brief corresponding binary operator type */\n            typedef op::mul OPType;\n        };\n        /*! \\brief divide to saver: /= */\n        struct divto {\n            /*! \\brief save b to a using save method */\n            MSHADOW_XINLINE static void Save(real_t& a, real_t b) {\n                a /= b;\n            }\n            /*! \\brief corresponding binary operator type */\n            typedef op::div OPType;\n        };\n    }; // namespace sv\n\n\n    namespace op {\n        // unary operator/ function: example\n        // these operators can be defined by user, in the same style as binary and unary operator\n        // to use, simply write F<op::identity>( src )\n        /*! \\brief identity function that maps a real number to it self */\n        struct identity{\n            /*! \\brief map a to result using defined operation */\n            MSHADOW_XINLINE static real_t Map(real_t a) {\n                return a;\n            }\n        };\n    }; // namespace op\n\n    /*! \\brief namespace for potential reducer operations */\n    namespace red {\n        /*! \\brief sum reducer */\n        struct sum {\n            /*! \\brief do reduction into dst */\n            MSHADOW_XINLINE static void Reduce( volatile real_t& dst,  volatile real_t src ) {\n                dst += src;\n            }\n            /*! \\brief calculate gradient of redres with respect to redsrc,  redres: reduced result, redsrc: one of reduction element */\n            MSHADOW_XINLINE static real_t PartialGrad( real_t redres, real_t redsrc ) {\n                return 1.0f;\n            }\n            /*! \\brief an intial value of reducer */\n            MSHADOW_CONSTEXPR static real_t kInitV = 0.0f;\n        };\n        /*! \\brief maximum reducer */\n        struct maximum {\n            /*! \\brief do reduction into dst */\n            MSHADOW_XINLINE static void Reduce( volatile real_t& dst,  volatile real_t src ) {\n                using namespace std;\n                dst = max( dst, src );\n            }\n            /*! \\brief calculate gradient of redres with respect to redsrc,  redres: reduced result, redsrc: one of reduction element */\n            MSHADOW_XINLINE static real_t PartialGrad( real_t redres, real_t redsrc ) {\n                return redres == redsrc ? 1.0f: 0.0f;\n            }\n            /*! \\brief an intial value of reducer */\n#if MSHADOW_SINGLE_PRECISION\n            MSHADOW_CONSTEXPR static real_t kInitV = -FLT_MAX;\n#else\n            MSHADOW_CONSTEXPR static real_t kInitV = -DBL_MAX;\n#endif\n        };\n    };\n\n    /*! \\brief namespace for helper utils of the project */\n    namespace utils{\n        /*! \\brief send error message then exit */\n        inline void Error( const char *msg ){\n            fprintf( stderr, \"Error:%s\\n\",msg );\n            exit( -1 );\n        }\n        /*! \\brief assert a expression is true */\n        inline void Assert( bool exp ){\n            if( !exp ) Error( \"AssertError\" );\n        }\n        /*! \\brief assert a expression is true */\n        inline void Assert( bool exp, const char *msg ){\n            if( !exp ) Error( msg );\n        }\n        /*! \\brief warning */\n        inline void Warning( const char *msg ){\n            fprintf( stderr, \"warning:%s\\n\",msg );\n        }\n    }; // namespace utils\n}; // namespace mshadow\n#endif // TENSOR_BASE_H\n", "meta": {"hexsha": "b251cbadf4fc705161901ca45d2808bdc205f3fb", "size": 10059, "ext": "h", "lang": "C", "max_stars_repo_path": "include/mshadow/tensor_base.h", "max_stars_repo_name": "kaiping/RNNLM_PARAM_SHARING", "max_stars_repo_head_hexsha": "7d39f8813d057565224402e230afacb98c8c366b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-10-29T09:40:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T11:03:31.000Z", "max_issues_repo_path": "include/mshadow/tensor_base.h", "max_issues_repo_name": "kaiping/RNNLM_PARAM_SHARING", "max_issues_repo_head_hexsha": "7d39f8813d057565224402e230afacb98c8c366b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/mshadow/tensor_base.h", "max_forks_repo_name": "kaiping/RNNLM_PARAM_SHARING", "max_forks_repo_head_hexsha": "7d39f8813d057565224402e230afacb98c8c366b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6421404682, "max_line_length": 136, "alphanum_fraction": 0.5945919077, "num_tokens": 2468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263216071250873, "lm_q2_score": 0.0453525766833672, "lm_q1q2_score": 0.019334783378916868}}
{"text": "#ifndef IMAGE_H_YQCE0AWR\n#define IMAGE_H_YQCE0AWR\n\n#include <gsl/gsl>\n#include <opencv2/core/mat.hpp>\n#include <sens_loc/math/coordinate.h>\n#include <type_traits>\n\nnamespace sens_loc::math {\n\nnamespace detail {\ntemplate <typename Number>  // requires Number<Number>\ninline int get_opencv_type() {\n    static_assert(std::is_arithmetic_v<Number>);\n\n    if constexpr (std::is_same<Number, float>::value)\n        return CV_32F;  // NOLINT(bugprone-branch-clone)\n    else if constexpr (std::is_same<Number, double>::value)\n        return CV_64F;\n    else if constexpr (std::is_same<Number, uchar>::value)\n        return CV_8U;\n    else if constexpr (std::is_same<Number, schar>::value)\n        return CV_8S;\n    else if constexpr (std::is_same<Number, ushort>::value)\n        return CV_16U;\n    else if constexpr (std::is_same<Number, short>::value)\n        return CV_16S;\n    else\n        return -1;\n}\n}  // namespace detail\n\n/// This function encapsulates an \\c cv::Mat and ensures the common\n/// preconditions for this code base are enforced.\n///\n/// \\invariant the image has only 1 channel.\n/// \\invariant the underlying data types are consistent\n/// \\invariant access is only done in \\p pixel_coord<int>\n///\n/// \\tparam PixelType the underlying type of the \\c cv::Mat\n/// \\sa math::pixel_coord\ntemplate <typename PixelType = ushort>\nclass image {\n  public:\n    static_assert(std::is_arithmetic_v<PixelType>);\n\n    image() = default;\n\n    /// Construct the image from a \\c cv::Mat and uphold the class invariant.\n    explicit image(const cv::Mat& image) noexcept\n        : _data(image) {\n        Expects(image.type() == detail::get_opencv_type<PixelType>());\n        Expects(image.channels() == 1);\n        Expects(!image.empty());\n    }\n    image(const image<PixelType>& other) = default;\n\n    // NOLINTNEXTLINE(performance-noexcept-move-constructor)\n    image(image<PixelType>&& other) = default;\n    explicit image(cv::Mat&& other) noexcept\n        : _data(std::move(other)) {\n        Expects(_data.type() == detail::get_opencv_type<PixelType>());\n        Expects(_data.channels() == 1);\n        Expects(!_data.empty());\n    }\n\n    image<PixelType>& operator=(const image<PixelType>& other) = default;\n    image<PixelType>& operator=(const cv::Mat& other) noexcept {\n        Expects(other.type() == detail::get_opencv_type<PixelType>());\n        Expects(other.channels() == 1);\n        Expects(!other.empty());\n        _data = other;\n        return *this;\n    }\n\n    // NOLINTNEXTLINE(performance-noexcept-move-constructor)\n    image<PixelType>& operator=(image<PixelType>&& other) = default;\n    image<PixelType>& operator=(cv::Mat&& other) noexcept {\n        Expects(other.type() == detail::get_opencv_type<PixelType>());\n        Expects(other.channels() == 1);\n        Expects(!other.empty());\n        _data = std::move(other);\n        return *this;\n    }\n\n    ~image() = default;\n\n    /// Return the width of the image.\n    [[nodiscard]] int w() const noexcept { return _data.cols; }\n    /// Return the height of the image.\n    [[nodiscard]] int h() const noexcept { return _data.rows; }\n\n    /// Read-Access in the image for some pixel \\p p.\n    template <typename Number = int>\n    [[nodiscard]] PixelType at(const pixel_coord<Number>& p) const noexcept {\n        static_assert(std::is_arithmetic_v<Number>);\n\n        return _data.at<PixelType>(gsl::narrow_cast<int>(p.v()),\n                                   gsl::narrow_cast<int>(p.u()));\n    }\n    /// Write-Access in the image for some pixel \\p p.\n    template <typename Number = int>\n    [[nodiscard]] PixelType& at(const pixel_coord<Number>& p) noexcept {\n        static_assert(std::is_arithmetic_v<Number>);\n\n        return _data.at<PixelType>(gsl::narrow_cast<int>(p.v()),\n                                   gsl::narrow_cast<int>(p.u()));\n    }\n\n    /// Get access to the underlying data to use it for normal cv operations.\n    [[nodiscard]] const cv::Mat& data() const noexcept { return _data; }\n\n  private:\n    cv::Mat _data;\n};\n\ntemplate <typename TargetType, typename PixelType>\nimage<TargetType> convert(const image<PixelType>& img) noexcept {\n    static_assert(std::is_arithmetic_v<TargetType>);\n    static_assert(std::is_arithmetic_v<PixelType>);\n\n    if constexpr (std::is_same_v<TargetType, PixelType>)\n        return img; // NOLINT(bugprone-suspicious-semicolon)\n\n    cv::Mat tmp(img.h(), img.w(), detail::get_opencv_type<TargetType>());\n    img.data().convertTo(tmp, detail::get_opencv_type<TargetType>());\n    return math::image<TargetType>(std::move(tmp));\n}\n\n}  // namespace sens_loc::math\n\n#endif /* end of include guard: IMAGE_H_YQCE0AWR */\n", "meta": {"hexsha": "ef785e79326bd221f604649b3eed30aac836d7dd", "size": 4623, "ext": "h", "lang": "C", "max_stars_repo_path": "src/include/sens_loc/math/image.h", "max_stars_repo_name": "JonasToth/depth-conversions", "max_stars_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-09-30T07:09:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T09:14:35.000Z", "max_issues_repo_path": "src/include/sens_loc/math/image.h", "max_issues_repo_name": "JonasToth/depth-conversions", "max_issues_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/include/sens_loc/math/image.h", "max_forks_repo_name": "JonasToth/depth-conversions", "max_forks_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7593984962, "max_line_length": 77, "alphanum_fraction": 0.6519576033, "num_tokens": 1182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35577489351363034, "lm_q2_score": 0.05419872791355607, "lm_q1q2_score": 0.019282546652019637}}
{"text": "/*\n * C version of Diffusive Nested Sampling (DNest4) by Brendon J. Brewer\n *\n * Yan-Rong Li, liyanrong@mail.ihep.ac.cn\n * Jun 30, 2016\n *\n */\n\n#ifndef _MODEL1_H\n#define _MODEL1_H\n\n#include <stdbool.h>\n#include <gsl/gsl_rng.h>\n\n\n/* number of model parameters */\nextern int num_params;\n\nextern int which_level_update;\nextern double *limits;     // limits from dnest\nextern int thistask, totaltask;\n\nextern DNestFptrSet *fptrset_thismodel;\n\n/* functions */\nvoid from_prior_thismodel(void *model);\nvoid print_particle_thismodel(FILE *fp, const void *model);\ndouble log_likelihoods_cal_thismodel(const void *model);\ndouble perturb_thismodel(void *model);\nvoid restart_action_model1(int iflag);\n#endif\n", "meta": {"hexsha": "f8f7ddbb75b44112288b74b27b882b4b0c902ee2", "size": 697, "ext": "h", "lang": "C", "max_stars_repo_path": "src/model1.h", "max_stars_repo_name": "LiyrAstroph/CDNest", "max_stars_repo_head_hexsha": "afb6b869ce1c4ebd76662b20310f1d9d3db4e26e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-09-11T03:34:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-16T12:14:05.000Z", "max_issues_repo_path": "src/model1.h", "max_issues_repo_name": "LiyrAstroph/DNest_C", "max_issues_repo_head_hexsha": "afb6b869ce1c4ebd76662b20310f1d9d3db4e26e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-05-14T10:04:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-06T02:04:19.000Z", "max_forks_repo_path": "src/model1.h", "max_forks_repo_name": "LiyrAstroph/DNest_C", "max_forks_repo_head_hexsha": "afb6b869ce1c4ebd76662b20310f1d9d3db4e26e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.78125, "max_line_length": 71, "alphanum_fraction": 0.7589670014, "num_tokens": 184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4186969093556867, "lm_q2_score": 0.046033901581263824, "lm_q1q2_score": 0.019274252317659023}}
{"text": "\n/*\n* -----------------------------------------------------------------\n*  Utilities Library --- util_lib.c\n*  Version: 1.6180\n*  Date: Mar 12, 2010\n* ----------------------------------------------------------------- \n*  Programmer: Americo Barbosa da Cunha Junior\n*              americo.cunhajr@gmail.com\n* -----------------------------------------------------------------\n*  Copyright (c) 2010 by Americo Barbosa da Cunha Junior\n*\n*  This program is free software: you can redistribute it and/or\n*  modify it under the terms of the GNU General Public License as\n*  published by the Free Software Foundation, either version 3 of\n*  the License, or (at your option) any later version.\n*\n*  This program is distributed in the hope that it will be useful,\n*  but WITHOUT ANY WARRANTY; without even the implied warranty of\n*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n*  GNU General Public License for more details.\n*\n*  A copy of the GNU General Public License is available in\n*  LICENSE.txt or http://www.gnu.org/licenses/.\n* -----------------------------------------------------------------\n*  This is the implementation file of a library\n*  with miscelaneous functions.\n* -----------------------------------------------------------------\n*/\n\n\n\n\n#include <stdio.h>\n#include <gsl/gsl_errno.h>\n\n#include \"../include/util_lib.h\"\n\n\n\n\n/*\n*------------------------------------------------------------\n*   gsl_fprint_vector\n*\n*   This function prints a vector in a file.\n*\n*   Input:\n*   file - output file\n*   v    - GSL vector\n*\n*   Output:\n*\n*   Return:\n*   success or error\n*\n*   last update: Nov 6, 2008\n*------------------------------------------------------------\n*/\n\nint gsl_fprint_vector(FILE* file,gsl_vector *v)\n{\n    if( v == NULL )\n\treturn GSL_EINVAL;\n    \n    unsigned int i;\n    \n    for( i = 0; i < v->size; i++ )\n\tfprintf(file,\" %+.3e\", v->data[i]);\n\n    return GSL_SUCCESS;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*\n*------------------------------------------------------------\n*   gsl_print_vector\n*\n*   This function prints a vector on the screen\n*\n*   Input:\n*   v  - GSL vector\n*\n*   Output:\n*\n*   Return:\n*   success or error\n*\n*   last update: Dec 26, 2008\n*------------------------------------------------------------\n*/\n\nint gsl_print_vector(gsl_vector *v)\n{\n    if( v == NULL )\n\treturn GSL_EINVAL;\n    \n    unsigned int i;\n    \n    for( i = 0; i < v->size; i++ )\n\tprintf(\" %+.3e\", v->data[i]);\n\n    return GSL_SUCCESS;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*\n*------------------------------------------------------------\n*   gsl_print_matrix_line\n*\n*   This function prints a matrix line on the screen.\n*\n*   Input:\n*   i  - matrix line to be printed\n*   M  - GSL matrix\n*\n*   Output:\n*\n*   Return:\n*   success or error\n*\n*   last update: Dec 26, 2008\n*------------------------------------------------------------\n*/\n\nint gsl_print_matrix_line(unsigned int i,gsl_matrix *M)\n{\n    if( M == NULL )\n\treturn GSL_EINVAL;\n    \n    unsigned int j;\n    \n    printf(\"\\n\");\n    for( j = 0; j < M->size2; j++ )\n\tprintf(\" %+.3e \", M->data[i*M->tda+j]);\n    \n    return GSL_SUCCESS;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*\n*------------------------------------------------------------\n*   gsl_print_matrix_column\n*\n*   This function prints a matrix column on the screen\n*\n*   Input:\n*   M  - GSL matrix\n*   i  - matrix column to be printed\n*\n*   Output:\n*\n*   Return:\n*   success or error\n*\n*   last update: Dec 26, 2008\n*------------------------------------------------------------\n*/\n\nint gsl_print_matrix_column(unsigned int j,gsl_matrix *M)\n{\n    if( M == NULL )\n    \treturn GSL_EINVAL;\n    \n    unsigned int i;\n    \n    printf(\"\\n\");\n    for( i = 0; i < M->size1; i++ )\n\tprintf(\" %+.3e\\n\", M->data[i*M->tda+j]);\n    \n    return GSL_SUCCESS;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*\n*------------------------------------------------------------\n*   gsl_print_matrix\n*\n*   This function prints a matrix on the screen\n*\n*   Input:\n*   M  - GSL matrix\n*\n*   Outpur:\n*\n*   Return:\n*   success or error\n*\n*   last update: Dec 26, 2008\n*------------------------------------------------------------\n*/\n\nint gsl_print_matrix(gsl_matrix *M)\n{\n    if( M == NULL )\n    \treturn GSL_EINVAL;\n    \n    unsigned int i;\n    \n    for( i = 0; i < M->size1; i++ )\n\tgsl_print_matrix_line(i,M);\n    \n    return GSL_SUCCESS;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*\n*------------------------------------------------------------\n*   gsl_rand_vector\n*\n*   This function creates a random vector.\n*\n*   Input:\n*   seed - random number generator seed\n*\n*   Output:\n*   v  - GSL vector\n*\n*   Return:\n*   success or error\n*\n*   last update: Feb 19, 2010\n*------------------------------------------------------------\n*/\n\nint gsl_rand_vector(gsl_rng *r,gsl_vector *v)\n{\n    if( v == NULL )\n    \treturn GSL_EINVAL;\n    \n    unsigned int i;\n    \n    for( i = 0; i < v->size; i++ )\n\tv->data[i] = gsl_rng_uniform(r) + 1.0;\n    \n    return GSL_SUCCESS;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*\n*------------------------------------------------------------\n*   gsl_rand_matrix\n*\n*   This function creates a radom matrix.\n*\n*   Input:\n*   seed - random number generator seed\n*\n*   Output:\n*   M    - GSL matrix\n*\n*   Return:\n*   success or error\n*\n*   last update: Feb 27, 2009\n*------------------------------------------------------------\n*/\n\nint gsl_rand_matrix(gsl_rng *r,gsl_matrix *M)\n{\n    if( M == NULL )\n    \treturn GSL_EINVAL;\n    \n    unsigned int i, j;\n    \n    for( i = 0; i < M->size1; i++ )\n        for( j = 0; j < M->size2; j++ )\n            M->data[i*M->tda+j] = gsl_rng_uniform(r) + 1.0;\n    \n    return GSL_SUCCESS;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*\n*------------------------------------------------------------\n*   gsl_diagonal_matrix\n*\n*   This function creates a diagonal matrix with the elements\n*   of the vector v.\n*\n*   Input:\n*   v - GSL vector\n*\n*   Output:\n*   D  - GSL matrix\n*\n*   Return:\n*   success or error\n*\n*   last update: Feb 26, 2009\n*------------------------------------------------------------\n*/\n\nint gsl_diagonal_matrix(gsl_vector *v,gsl_matrix *D)\n{\n    if( v == NULL || D == NULL )\n    \treturn GSL_EINVAL;\n    \n    unsigned int i, j;\n    \n    for( i = 0; i < D->size1; i++ )\n        for( j = 0; j < D->size2; j++ )\n            if( i == j )\n                D->data[i*D->tda+j] = v->data[i];\n            else\n                D->data[i*D->tda+j] = 0.0;\n    \n    return GSL_SUCCESS;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*\n*------------------------------------------------------------\n*   util_time_used\n*\n*   This function computes the CPU time and Wall time\n*   used in a simulation.\n*\n*   Input:\n*   cpu_start  - cpu clock start flag\n*   cpu_end    - cpu clock end flag\n*   wall_start - wall clock start flag\n*   wall_end   - wall clock end flag\n*\n*   last update: Nov 10, 2009\n*------------------------------------------------------------\n*/\n\nvoid util_time_used(clock_t cpu_start,clock_t cpu_end,\n\t\t\t    time_t wall_start,time_t wall_end)\n{\n    double cpu_used;\n    double wall_used;\n    \n    cpu_used  = ((double) (cpu_end - cpu_start)) / CLOCKS_PER_SEC;\n    wall_used = difftime(wall_end,wall_start);\n    \n    printf(\"\\n\");\n    printf(\"\\n CPU  time (s): %+.6e\",cpu_used);\n    printf(\"\\n Wall time (s): %+.6e\",wall_used);\n    printf(\"\\n\");\n    \n    return;\n}\n/*------------------------------------------------------------*/\n", "meta": {"hexsha": "6e7f904658ce42c62e3e6a13e8132b2df8c93b5e", "size": 7635, "ext": "c", "lang": "C", "max_stars_repo_path": "CRFlowLib-2.0/src/util_lib.c", "max_stars_repo_name": "americocunhajr/CRFlowLib", "max_stars_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-29T12:56:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-29T12:56:14.000Z", "max_issues_repo_path": "CRFlowLib-1.0/src/util_lib.c", "max_issues_repo_name": "americocunhajr/CRFlowLib", "max_issues_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CRFlowLib-1.0/src/util_lib.c", "max_forks_repo_name": "americocunhajr/CRFlowLib", "max_forks_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-15T03:57:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-30T01:44:13.000Z", "avg_line_length": 20.6351351351, "max_line_length": 68, "alphanum_fraction": 0.4332678454, "num_tokens": 1824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39981164073979497, "lm_q2_score": 0.048136769580412284, "lm_q1q2_score": 0.019245640825858088}}
{"text": "/* Starting from version 7.8, MATLAB BLAS expects ptrdiff_t arguments for integers */\r\n#if MATLAB_VERSION >= 0x0708\r\n#include <stddef.h>\r\n#include <stdlib.h>\r\n#endif\r\n#include <string.h>\r\n\r\n/* Define MX_HAS_INTERLEAVED_COMPLEX for version <9.4 */\r\n#ifndef MX_HAS_INTERLEAVED_COMPLEX\r\n#define MX_HAS_INTERLEAVED_COMPLEX 0\r\n#endif\r\n\r\n/* Starting from version 7.6, MATLAB BLAS is seperated */\r\n#if MATLAB_VERSION >= 0x0705\r\n#include <blas.h>\r\n#endif\r\n#include <lapack.h>\r\n#include \"f2c.h\"\r\n\r\n// Conversion of optimal problems with coupling weighting terms to standard problems\r\n#define sb02mt FORTRAN_WRAPPER(sb02mt)\r\nextern void sb02mt(\r\n        const char *jobg,\r\n        const char *jobl,\r\n        const char *fact,\r\n        const char *uplo,\r\n        const ptrdiff_t *n,\r\n        const ptrdiff_t *m,\r\n        double *a,\r\n        const ptrdiff_t *lda,\r\n        double *b,\r\n        const ptrdiff_t *ldb,\r\n        double *q,\r\n        const ptrdiff_t *ldq,\r\n        double *r,\r\n        const ptrdiff_t *ldr,\r\n        double *l,\r\n        const ptrdiff_t *ldl,\r\n        ptrdiff_t *ipiv,\r\n        ptrdiff_t *oufact,\r\n        double *g,\r\n        const ptrdiff_t *ldg,\r\n        ptrdiff_t *iwork,\r\n        double *dwork,\r\n        const ptrdiff_t *ldwork,\r\n        ptrdiff_t *info\r\n        );\r\n\r\n// Conversion of optimal problems with coupling weighting terms to standard problems (more flexibility)\r\n#define sb02mx FORTRAN_WRAPPER(sb02mx)\r\nextern void sb02mx(\r\n        const char *jobg,\r\n        const char *jobl,\r\n        const char *fact,\r\n        const char *uplo,\r\n        const char *trans,\r\n        const char *flag,\r\n        const char *def,\r\n        const ptrdiff_t *n,\r\n        const ptrdiff_t *m,\r\n        double *a,\r\n        const ptrdiff_t *lda,\r\n        double *b,\r\n        const ptrdiff_t *ldb,\r\n        double *q,\r\n        const ptrdiff_t *ldq,\r\n        double *r,\r\n        const ptrdiff_t *ldr,\r\n        double *l,\r\n        const ptrdiff_t *ldl,\r\n        ptrdiff_t *ipiv,\r\n        ptrdiff_t *oufact,\r\n        double *g,\r\n        const ptrdiff_t *ldg,\r\n        ptrdiff_t *iwork,\r\n        double *dwork,\r\n        const ptrdiff_t *ldwork,\r\n        ptrdiff_t *info\r\n        );\r\n\r\n// Constructing the 2n-by-2n Hamiltonian or symplectic matrix for linear-quadratic optimization problems\r\n#define sb02mu FORTRAN_WRAPPER(sb02mu)\r\nextern void sb02mu(\r\n        const char *dico,\r\n        const char *hinv,\r\n        const char *uplo,\r\n        const ptrdiff_t *n,\r\n        double *a,\r\n        const ptrdiff_t *lda,\r\n        const double *g,\r\n        const ptrdiff_t *ldg,\r\n        const double *q,\r\n        const ptrdiff_t *ldq,\r\n        double *s,\r\n        const ptrdiff_t *lds,\r\n        ptrdiff_t *iwork,\r\n        double *dwork,\r\n        const ptrdiff_t *ldwork,\r\n        ptrdiff_t *info\r\n        );\r\n\r\n// Constructing the 2n-by-2n Hamiltonian or symplectic matrix for linear-quadratic optimization problems (improved)\r\n#define sb02ru FORTRAN_WRAPPER(sb02ru)\r\nextern void sb02ru(\r\n        const char *dico,\r\n        const char *hinv,\r\n        const char *trana,\r\n        const char *uplo,\r\n        const ptrdiff_t *n,\r\n        const double *a,\r\n        const ptrdiff_t *lda,\r\n        double *g,\r\n        const ptrdiff_t *ldg,\r\n        double *q,\r\n        const ptrdiff_t *ldq,\r\n        double *s,\r\n        const ptrdiff_t *lds,\r\n        ptrdiff_t *iwork,\r\n        double *dwork,\r\n        const ptrdiff_t *ldwork,\r\n        ptrdiff_t *info\r\n        );\r\n\r\n// Constructing the extended Hamiltonian or symplectic matrix pairs for linear-quadratic optimization problems, and compressing them to 2N-by-2N matrices\r\n#define sb02oy FORTRAN_WRAPPER(sb02oy)\r\nextern void sb02oy(\r\n        const char *type,\r\n        const char *dico,\r\n        const char *jobb,\r\n        const char *fact,\r\n        const char *uplo,\r\n        const char *jobl,\r\n        const char *jobe,\r\n        const ptrdiff_t *n,\r\n        const ptrdiff_t *m,        \r\n        const ptrdiff_t *p,        \r\n        const double *a,\r\n        const ptrdiff_t *lda,\r\n        const double *b,\r\n        const ptrdiff_t *ldb,        \r\n        const double *q,\r\n        const ptrdiff_t *ldq,\r\n        const double *r,\r\n        const ptrdiff_t *ldr,\r\n        const double *l,\r\n        const ptrdiff_t *ldl,\r\n        const double *e,\r\n        const ptrdiff_t *lde,\r\n        double *af,\r\n        const ptrdiff_t *ldaf,\r\n        double *bf,\r\n        const ptrdiff_t *ldbf,\r\n        double *tol,\r\n        ptrdiff_t *iwork,\r\n        double *dwork,\r\n        const ptrdiff_t *ldwork,\r\n        ptrdiff_t *info\r\n        );\r\n\r\n// Optimal state feedback matrix for an optimal control problem\r\n#define sb02nd FORTRAN_WRAPPER(sb02nd)\r\nextern void sb02nd(\r\n        const char *dico,\r\n        const char *fact,\r\n        const char *uplo,\r\n        const char *jobl,\r\n        const ptrdiff_t *n,\r\n        const ptrdiff_t *m,\r\n        const ptrdiff_t *p,\r\n        const double *a,\r\n        const ptrdiff_t *lda,\r\n        double *b,\r\n        const ptrdiff_t *ldb,\r\n        double *r,\r\n        const ptrdiff_t *ldr,\r\n        ptrdiff_t *ipiv,\r\n        const double *l,\r\n        const ptrdiff_t *ldl,\r\n        double *x,\r\n        const ptrdiff_t *ldx,\r\n        const double *rnorm,\r\n        double *f,\r\n        const ptrdiff_t *ldf,\r\n        ptrdiff_t *oufact,\r\n        ptrdiff_t *iwork,\r\n        double *dwork,\r\n        const ptrdiff_t *ldwork,\r\n        ptrdiff_t *info\r\n        );\r\n\r\n// Solution of continuous- or discrete-time algebraic Riccati equations for descriptor systems\r\n#define sg02nd FORTRAN_WRAPPER(sg02nd)\r\nextern void sg02nd(\r\n        const char *dico,\r\n        const char *jobe,\r\n        const char *job,\r\n        const char *jobx,\r\n        const char *fact,\r\n        const char *uplo,\r\n        const char *jobl,\r\n        const char *trans,\r\n        const ptrdiff_t *n,\r\n        const ptrdiff_t *m,        \r\n        const ptrdiff_t *p,\r\n        const double *a,\r\n        const ptrdiff_t *lda,\r\n        const double *e,\r\n        const ptrdiff_t *lde,\r\n        double *b,\r\n        const ptrdiff_t *ldb,\r\n        double *r,\r\n        const ptrdiff_t *ldr,\r\n        ptrdiff_t *ipiv,\r\n        const double *l,\r\n        const ptrdiff_t *ldl,\r\n        double *x,\r\n        const ptrdiff_t *ldx,\r\n        const double *rnorm,\r\n        double *k,\r\n        const ptrdiff_t *ldk,\r\n        double *h,\r\n        const ptrdiff_t *ldh,\r\n        double *xe,\r\n        const ptrdiff_t *ldxe,\r\n        ptrdiff_t *oufact,\r\n        ptrdiff_t *iwork,\r\n        double *dwork,\r\n        const ptrdiff_t *ldwork,\r\n        ptrdiff_t *info\r\n        );\r\n\r\n\r\n// Column interchanges in a complex matrix\r\n#define ma02gz FORTRAN_WRAPPER(ma02gz)\r\nextern void ma02gz(\r\n        const ptrdiff_t *n,\r\n        double *a,\r\n        const ptrdiff_t *lda,\r\n        const ptrdiff_t *k1,\r\n        const ptrdiff_t *k2,\r\n        const ptrdiff_t *ipiv,\r\n        const ptrdiff_t *incx\r\n        );\r\n\r\n\r\n// Solution of linear equations X op(A) = B\r\n#define mb02vd FORTRAN_WRAPPER(mb02vd)\r\nextern void mb02vd(\r\n        const char *trans,\r\n        const ptrdiff_t *m,\r\n        const ptrdiff_t *n,\r\n        double *a,\r\n        const ptrdiff_t *lda,\r\n        ptrdiff_t *ipiv,\r\n        double *b,\r\n        const ptrdiff_t *ldb,\r\n        ptrdiff_t *info\r\n        );\r\n\r\n// Periodic Hessenberg form of a product of p matrices using orthogonal similarity transformations\r\n#define mb03vd FORTRAN_WRAPPER(mb03vd)\r\nextern void mb03vd(\r\n        const ptrdiff_t *n,\r\n        const ptrdiff_t *p,\r\n        const ptrdiff_t *ilo,\r\n        const ptrdiff_t *ihi,\r\n        double *a,\r\n        const ptrdiff_t *lda1,\r\n        const ptrdiff_t *lda2,\r\n        double *tau,\r\n        const ptrdiff_t *ldtau,\r\n        double *dwork,\r\n        ptrdiff_t *info\r\n        );\r\n\r\n// Orthogonal matrices for reduction to periodic Hessenberg form of a product of matrices\r\n#define mb03vy FORTRAN_WRAPPER(mb03vy)\r\nextern void mb03vy(\r\n        const ptrdiff_t *n,\r\n        const ptrdiff_t *p,\r\n        const ptrdiff_t *ilo,\r\n        const ptrdiff_t *ihi,\r\n        double *a,\r\n        const ptrdiff_t *lda1,\r\n        const ptrdiff_t *lda2,\r\n        double *tau,\r\n        const ptrdiff_t *ldtau,\r\n        double *dwork,\r\n        const ptrdiff_t *ldwork,\r\n        ptrdiff_t *info\r\n        );\r\n\r\n// Schur decomposition and eigenvalues of a product of matrices in periodic Hessenberg form\r\n#define mb03wd FORTRAN_WRAPPER(mb03wd)\r\nextern void mb03wd(\r\n        const char *job,\r\n        const char *compz,\r\n        const ptrdiff_t *n,\r\n        const ptrdiff_t *p,\r\n        const ptrdiff_t *ilo,\r\n        const ptrdiff_t *ihi,\r\n        const ptrdiff_t *iloz,\r\n        const ptrdiff_t *ihiz,\r\n        double *h,\r\n        const ptrdiff_t *ldh1,\r\n        const ptrdiff_t *ldh2,\r\n        double *z,\r\n        const ptrdiff_t *ldz1,\r\n        const ptrdiff_t *ldz2,\r\n        double *wr,\r\n        double *wi,\r\n        double *dwork,\r\n        const ptrdiff_t *ldwork,\r\n        ptrdiff_t *info\r\n        );\r\n\r\n\r\n// Computes the general product of K complex scalars trying to avoid over- and underflow. \r\n#define zlapr1 FORTRAN_WRAPPER(zlapr1)\r\nextern int zlapr1(\r\n        doublereal *base, \r\n        integer *k, \r\n        integer *s, \r\n        doublecomplex *a, \r\n        integer *inca, \r\n        doublecomplex *alpha, \r\n        doublecomplex *beta, \r\n        integer *scal\r\n        );\r\n\r\n// Finding the eigenvalues of the complex generalized matrix product. \r\n#define zpgeqz FORTRAN_WRAPPER(zpgeqz)\r\nextern int zpgeqz(\r\n        char *job, \r\n        char *compq, \r\n        integer *k, \r\n        integer *n,\t\r\n        integer *ilo, \r\n        integer *ihi, \r\n        integer *s, \r\n        doublecomplex *a, \r\n        integer *lda1, \r\n        integer *lda2, \r\n        doublecomplex *alpha, \r\n        doublecomplex *beta,\r\n        integer *scal,\r\n        doublecomplex *q,\r\n        integer *ldq1,\r\n        integer *ldq2,\r\n        doublereal *dwork,\r\n        integer *ldwork,\r\n        doublecomplex *zwork,\r\n        integer *lzwork, \r\n        integer *info\r\n        );\r\n\r\n// Swaps adjacent diagonal 1-by-1 blocks in a complex generalized matrix product. \r\n#define zpgex2 FORTRAN_WRAPPER(zpgex2)\r\nextern int zpgex2(\r\n        logical *wantq, \r\n        integer *k, \r\n        integer *n, \r\n        integer *j, \r\n        integer *s, \r\n        doublecomplex *a, \r\n        integer *lda1, \r\n        integer *lda2, \r\n        doublecomplex *q, \r\n        integer *ldq1, \r\n        integer *ldq2, \r\n        doublecomplex *zwork,\r\n        integer *info\r\n        );\r\n\r\n// Swaps adjacent diagonal 1-by-1 blocks in a complex generalized matrix product. \r\n#define zpghrd FORTRAN_WRAPPER(zpghrd)\r\nextern int zpghrd(\r\n        char *compq, \r\n        integer *k, \r\n        integer *n, \r\n        integer *ilo, \r\n        integer *ihi, \r\n        integer *s, \r\n        doublecomplex *a, \r\n        integer *lda1, \r\n        integer *lda2, \r\n        doublecomplex *q, \r\n        integer *ldq1, \r\n        integer *ldq2, \r\n        doublereal *dwork, \r\n        integer *ldwork, \r\n        doublecomplex *zwork, \r\n        integer *lzwork, \r\n        integer *info\r\n        );\r\n\r\n// Reorders the periodic Schur decomposition of a complex generalized matrix product. \r\n#define zpgord FORTRAN_WRAPPER(zpgord)\r\nextern int zpgord(\r\n        logical *wantq, \r\n        integer *k, \r\n        integer *n, \r\n        integer *s, \r\n        logical *select, \r\n        doublecomplex *a, \r\n        integer *lda1, \r\n        integer *lda2, \r\n        doublecomplex *alpha,\r\n        doublecomplex *beta,\r\n        integer *scal, \r\n        doublecomplex *q, \r\n        integer *ldq1, \r\n        integer *ldq2, \r\n        integer *m,\r\n        doublecomplex *zwork,\r\n        integer *lzwork,\r\n        integer *info\r\n        );\r\n\r\n", "meta": {"hexsha": "ecf044e0dad5a907b905d22af3196620a6b91880", "size": 11689, "ext": "h", "lang": "C", "max_stars_repo_path": "dprex.h", "max_stars_repo_name": "iwoodsawyer/dpre", "max_stars_repo_head_hexsha": "515076c0b6b7c6643378427553b4c302dc29ed3b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-17T13:13:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T13:13:08.000Z", "max_issues_repo_path": "dprex.h", "max_issues_repo_name": "iwoodsawyer/dpre", "max_issues_repo_head_hexsha": "515076c0b6b7c6643378427553b4c302dc29ed3b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-25T15:47:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T21:11:59.000Z", "max_forks_repo_path": "dprex.h", "max_forks_repo_name": "iwoodsawyer/dpre", "max_forks_repo_head_hexsha": "515076c0b6b7c6643378427553b4c302dc29ed3b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.830952381, "max_line_length": 154, "alphanum_fraction": 0.5583026777, "num_tokens": 2993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.03846619422289417, "lm_q1q2_score": 0.019233097111447085}}
{"text": "/**\n *\n * @file qwrapper_cpotrf.c\n *\n *  PLASMA core_blas quark wrapper\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Hatem Ltaief\n * @author Mathieu Faverge\n * @author Jakub Kurzak\n * @date 2010-11-15\n * @generated c Tue Jan  7 11:44:56 2014\n *\n **/\n#include <lapacke.h>\n#include \"common.h\"\n\n/***************************************************************************//**\n *\n **/\nvoid QUARK_CORE_clauum(Quark *quark, Quark_Task_Flags *task_flags,\n                       PLASMA_enum uplo, int n, int nb,\n                       PLASMA_Complex32_t *A, int lda)\n{\n    DAG_CORE_LAUUM;\n    QUARK_Insert_Task(quark, CORE_clauum_quark, task_flags,\n        sizeof(PLASMA_enum),                &uplo,  VALUE,\n        sizeof(int),                        &n,     VALUE,\n        sizeof(PLASMA_Complex32_t)*nb*nb,    A,             INOUT,\n        sizeof(int),                        &lda,   VALUE,\n        0);\n}\n\n/***************************************************************************//**\n *\n **/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_clauum_quark = PCORE_clauum_quark\n#define CORE_clauum_quark PCORE_clauum_quark\n#endif\nvoid CORE_clauum_quark(Quark *quark)\n{\n    PLASMA_enum uplo;\n    int N;\n    PLASMA_Complex32_t *A;\n    int LDA;\n\n    quark_unpack_args_4(quark, uplo, N, A, LDA);\n    LAPACKE_clauum_work(LAPACK_COL_MAJOR, lapack_const(uplo), N, A, LDA);\n}\n", "meta": {"hexsha": "494b454edeb49adc857f24cd4bc80ff77efa54bc", "size": 1475, "ext": "c", "lang": "C", "max_stars_repo_path": "core_blas-qwrapper/qwrapper_clauum.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "core_blas-qwrapper/qwrapper_clauum.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "core_blas-qwrapper/qwrapper_clauum.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8301886792, "max_line_length": 80, "alphanum_fraction": 0.5538983051, "num_tokens": 424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.03846619270725236, "lm_q1q2_score": 0.01923309635362618}}
{"text": "//\n// C++ Interface: %{MODULE}\n//\n// Description:\n//\n//\n// Author: %{AUTHOR} <%{EMAIL}>, (C) %{YEAR}\n//\n// Copyright: See COPYING file that comes with this distribution\n//\n//\n\n#ifndef TNet_Vector_h\n#define TNet_Vector_h\n\n#include <cstddef>\n#include <cstdlib>\n#include <stdexcept>\n#include <iostream>\n\n#ifdef HAVE_ATLAS\nextern \"C\"{\n  #include <cblas.h>\n  #include <clapack.h>\n}\n#endif\n\n#include \"Common.h\"\n#include \"MathAux.h\"\n#include \"Types.h\"\n#include \"Error.h\"\n\nnamespace TNet\n{\n  template<typename _ElemT> class Vector;\n  template<typename _ElemT> class SubVector;\n  template<typename _ElemT> class Matrix;\n  template<typename _ElemT> class SpMatrix;\n\n  // we need to declare the friend functions here\n  template<typename _ElemT>\n    std::ostream & operator << (std::ostream & rOut, const Vector<_ElemT> & rV);\n\n  template<typename _ElemT>\n    std::istream & operator >> (std::istream & rIn, Vector<_ElemT> & rV);\n\n  template<typename _ElemT>\n    _ElemT\n    BlasDot(const Vector<_ElemT>& rA, const Vector<_ElemT>& rB);\n\n  /** **************************************************************************\n   ** **************************************************************************\n   *  @brief Provides a matrix abstraction class\n   *\n   *  This class provides a way to work with matrices in TNet.\n   *  It encapsulates basic operations and memory optimizations.\n   *\n   */\n  template<typename _ElemT>\n    class Vector\n    {\n    public:\n\n    /// defines a type of this\n    typedef Vector<_ElemT> ThisType;\n\n\n    Vector(): mpData(NULL)\n#ifdef STK_MEMALIGN_MANUAL\n    ,mpFreeData(NULL)\n#endif\n    , mDim(0)\n      {}\n\n      /**\n       * @brief Copy constructor\n       * @param rV\n       */\n      Vector(const Vector<_ElemT>& rV)\n  \t  { mpData=NULL; Init(rV.Dim()); Copy(rV); }\n\n\n      /* Type conversion constructor. */\n      template<typename _ElemU>\n      explicit Vector(const Vector<_ElemU>& rV)\n  \t  { mpData=NULL; Init(rV.Dim()); Copy(rV); }\n\n\n      Vector(const _ElemT* ppData, const size_t s)\n      { mpData=NULL; Init(s); Copy(ppData); }\n\n      explicit Vector(const size_t s, bool clear=true)\n      { mpData=NULL; Init(s,clear); }\n\n      ~Vector()\n      { Destroy(); }\n\n       Vector<_ElemT> &operator = (const Vector <_ElemT> &other)\n       { Init(other.Dim()); Copy(other); return *this; } // Needed for inclusion in std::vector\n\n      Vector<_ElemT>&\n      Init(size_t length, bool clear=true);\n\n      /**\n       * @brief Dealocates the window from memory and resets the dimensions to (0)\n       */\n      void\n      Destroy();\n\n      /**\n       * @brief Returns @c true if vector is initialized\n       */\n      bool\n      IsInitialized() const\n      { return mpData != NULL; }\n\n      /**\n       * @brief Sets all elements to 0\n       */\n      void\n      Zero();\n\n      void\n      Set(_ElemT f);\n\n      inline size_t\n      Dim() const\n      { return mDim; }\n\n      /**\n       * @brief Returns size of matrix in memory (in bytes)\n       */\n      inline size_t\n      MSize() const\n      {\n        return (mDim + (((16 / sizeof(_ElemT)) - mDim%(16 / sizeof(_ElemT)))\n                          % (16 / sizeof(_ElemT)))) * sizeof(_ElemT);\n      }\n\n      /**\n       *  @brief Gives access to the vector memory area\n       *  @return pointer to the first field\n       */\n      inline _ElemT*\n      pData()\n      { return mpData; }\n\n      /**\n       *  @brief Gives access to the vector memory area\n       *  @return pointer to the first field (const version)\n       */\n      inline const _ElemT*\n      pData() const\n      { return mpData; }\n\n      /**\n       *  @brief Gives access to a specified vector element (const).\n       */\n      inline _ElemT\n      operator [] (size_t i) const\n      {\n#ifdef PARANOID\n\t\tassert(i<mDim);\n#endif\n\t\treturn *(mpData + i);\n\t  }\n\n      /**\n       *  @brief Gives access to a specified vector element (non-const).\n       */\n      inline _ElemT &\n      operator [] (size_t i)\n      {\n#ifdef PARANOID\n\t\tassert(i<mDim);\n#endif\n\t\treturn *(mpData + i);\n\t  }\n\n      /**\n       *  @brief Gives access to a specified vector element (const).\n       */\n      inline _ElemT\n\t\toperator () (size_t i) const\n      {\n#ifdef PARANOID\n\t\tassert(i<mDim);\n#endif\n\t\treturn *(mpData + i);\n\t  }\n\n      /**\n       *  @brief Gives access to a specified vector element (non-const).\n       */\n      inline _ElemT &\n\t\toperator () (size_t i)\n      {\n#ifdef PARANOID\n\t\tassert(i<mDim);\n#endif\n\t\treturn *(mpData + i);\n\t  }\n\n      /**\n       * @brief Returns a matrix sub-range\n       * @param o Origin\n       * @param l Length\n       * See @c SubVector class for details\n       */\n      SubVector<_ElemT>\n      Range(const size_t o, const size_t l)\n      { return SubVector<_ElemT>(*this, o, l); }\n\n      /**\n       * @brief Returns a matrix sub-range\n       * @param o Origin\n       * @param l Length\n       * See @c SubVector class for details\n       */\n      const SubVector<_ElemT>\n      Range(const size_t o, const size_t l) const\n      { return SubVector<_ElemT>(*this, o, l); }\n\n\n\n      //########################################################################\n      //########################################################################\n\n      /// Copy data from another vector\n      Vector<_ElemT>&\n      Copy(const Vector<_ElemT>& rV);\n\n      /// Copy data from another vector of a different type.\n      template<typename _ElemU> Vector<_ElemT>&\n      Copy(const Vector<_ElemU>& rV);\n\n\n      /// Load data into the vector\n      Vector<_ElemT>&\n      Copy(const _ElemT* ppData);\n\n      Vector<_ElemT>&\n      CopyVectorizedMatrixRows(const Matrix<_ElemT> &rM);\n\n      Vector<_ElemT>&\n      RemoveElement(size_t i);\n\n      Vector<_ElemT>&\n      ApplyLog();\n\n      Vector<_ElemT>&\n      ApplyLog(const Vector<_ElemT>& rV);//ApplyLog to rV and put the result in (*this)\n\n      Vector<_ElemT>&\n      ApplyExp();\n\n      Vector<_ElemT>&\n      ApplySoftMax();\n\n      Vector<_ElemT>&\n      Invert();\n\n      Vector<_ElemT>&\n      DotMul(const Vector<_ElemT>& rV); // Multiplies each element (*this)(i) by rV(i).\n\n      Vector<_ElemT>&\n      BlasAxpy(const _ElemT alpha, const Vector<_ElemT>& rV);\n\n      Vector<_ElemT>&\n      BlasGemv(const _ElemT alpha, const Matrix<_ElemT>& rM, const MatrixTrasposeType trans, const Vector<_ElemT>& rV, const _ElemT beta = 0.0);\n\n\n      //########################################################################\n      //########################################################################\n\n      Vector<_ElemT>&\n      Add(const Vector<_ElemT>& rV)\n      { return BlasAxpy(1.0, rV); }\n\n      Vector<_ElemT>&\n      Subtract(const Vector<_ElemT>& rV)\n      { return BlasAxpy(-1.0, rV); }\n\n      Vector<_ElemT>&\n      AddScaled(_ElemT alpha, const Vector<_ElemT>& rV)\n      { return BlasAxpy(alpha, rV); }\n\n      Vector<_ElemT>&\n      Add(_ElemT c);\n\n      Vector<_ElemT>&\n      MultiplyElements(const Vector<_ElemT>& rV);\n\n      // @brief elementwise : rV.*rR+beta*this --> this\n      Vector<_ElemT>&\n      MultiplyElements(_ElemT alpha, const Vector<_ElemT>& rV, const Vector<_ElemT>& rR,_ElemT beta);\n\n      Vector<_ElemT>&\n      DivideElements(const Vector<_ElemT>& rV);\n\n      /// @brief elementwise : rV./rR+beta*this --> this\n      Vector<_ElemT>&\n      DivideElements(_ElemT alpha, const Vector<_ElemT>& rV, const Vector<_ElemT>& rR,_ElemT beta);\n\n      Vector<_ElemT>&\n      Subtract(_ElemT c);\n\n      Vector<_ElemT>&\n      Scale(_ElemT c);\n\n\n      //########################################################################\n      //########################################################################\n\n      /// Performs a row stack of the matrix rMa\n      Vector<_ElemT>&\n      MatrixRowStack(const Matrix<_ElemT>& rMa);\n\n      // Extracts a row of the matrix rMa.  .. could also do this with vector.Copy(rMa[row]).\n      Vector<_ElemT>&\n      Row(const Matrix<_ElemT>& rMa, size_t row);\n\n      // Extracts a column of the matrix rMa.\n      Vector<_ElemT>&\n      Col(const Matrix<_ElemT>& rMa, size_t col);\n\n      // Takes all elements to a power.\n      Vector<_ElemT>&\n      Power(_ElemT power);\n\n      _ElemT \n      Max() const;\n\n      _ElemT \n      Min() const;\n\n      /// Returns sum of the elements\n      _ElemT\n      Sum() const;\n\n      /// Returns sum of the elements\n      Vector<_ElemT>&\n      AddRowSum(const Matrix<_ElemT>& rM);\n\n      /// Returns sum of the elements\n      Vector<_ElemT>&\n      AddColSum(const Matrix<_ElemT>& rM);\n\n      /// Returns log(sum(exp())) without exp overflow\n      _ElemT\n      LogSumExp() const;\n\n      //########################################################################\n      //########################################################################\n\n      friend std::ostream &\n      operator << <> (std::ostream& rOut, const Vector<_ElemT>& rV);\n\n      friend _ElemT\n      BlasDot<>(const Vector<_ElemT>& rA, const Vector<_ElemT>& rB);\n\n      /**\n       * Computes v1^T * M * v2.  \n       * Not as efficient as it could be where v1==v2 (but no suitable blas\n       * routines available).\n       */\n      _ElemT\n      InnerProduct(const Vector<_ElemT> &v1, const Matrix<_ElemT> &M, const Vector<_ElemT> &v2) const;\n\n\n    //##########################################################################\n    //##########################################################################\n    //protected:\n    public:\n      /// data memory area\n      _ElemT*   mpData;\n#ifdef STK_MEMALIGN_MANUAL\n      /// data to be freed (in case of manual memalignment use, see common.h)\n      _ElemT*   mpFreeData;\n#endif\n      size_t  mDim;      ///< Number of elements\n    }; // class Vector\n\n\n\n\n  /**\n   * @brief Represents a non-allocating general vector which can be defined\n   * as a sub-vector of higher-level vector\n   */\n  template<typename _ElemT>\n    class SubVector : public Vector<_ElemT>\n    {\n    protected:\n      /// Constructor\n      SubVector(const Vector<_ElemT>& rT,\n                const size_t  origin,\n                const size_t  length)\n      {\n        assert(origin+length <= rT.mDim);\n        Vector<_ElemT>::mpData = rT.mpData+origin;\n        Vector<_ElemT>::mDim   = length;\n      }\n      //only Vector class can call this protected constructor\n      friend class Vector<_ElemT>; \n\n    public:\n      /// Constructor\n      SubVector(Vector<_ElemT>& rT,\n                const size_t  origin,\n                const size_t  length)\n      {\n        assert(origin+length <= rT.mDim);\n        Vector<_ElemT>::mpData = rT.mpData+origin;\n        Vector<_ElemT>::mDim   = length;\n      }\n\n\n      /**\n       * @brief Constructs a vector representation out of a standard array\n       *\n       * @param pData pointer to data array to associate with this vector\n       * @param length length of this vector\n       */\n      inline\n      SubVector(_ElemT *ppData,\n                size_t length)\n      {\n        Vector<_ElemT>::mpData = ppData;\n        Vector<_ElemT>::mDim   = length;\n      }\n\n\n      /**\n       * @brief Destructor\n       */\n      ~SubVector()\n      {\n        Vector<_ElemT>::mpData = NULL;\n      }\n    };\n\n\n    // Useful shortcuts\n    typedef Vector<BaseFloat> BfVector;\n    typedef SubVector<BaseFloat> BfSubVector;\n\n    //Adding two vectors of different types\n    template <typename _ElemT, typename _ElemU>\n    void Add(Vector<_ElemT>& rDst, const Vector<_ElemU>& rSrc)\n    {\n      assert(rDst.Dim() == rSrc.Dim());\n      const _ElemU* p_src = rSrc.pData();\n      _ElemT* p_dst = rDst.pData();\n\n      for(size_t i=0; i<rSrc.Dim(); i++) {\n        *p_dst++ += (_ElemT)*p_src++;\n      }\n    }\n   \n      \n    //Scales adding two vectors of different types\n    template <typename _ElemT, typename _ElemU>\n    void AddScaled(Vector<_ElemT>& rDst, const Vector<_ElemU>& rSrc, _ElemT scale)\n    {\n      assert(rDst.Dim() == rSrc.Dim());\n\n      Vector<_ElemT> tmp(rSrc);\n      rDst.BlasAxpy(scale, tmp); \n\n/*\n      const _ElemU* p_src = rSrc.pData();\n      _ElemT* p_dst = rDst.pData();\n\n      for(size_t i=0; i<rDst.Dim(); i++) {\n        *p_dst++ += *p_src++ * scale;\n      }\n*/\n    }\n\n\n} // namespace TNet\n\n//*****************************************************************************\n//*****************************************************************************\n// we need to include the implementation\n#include \"Vector.tcc\"\n\n/******************************************************************************\n ******************************************************************************\n * The following section contains specialized template definitions\n * whose implementation is in Vector.cc\n */\n\n\n#endif // #ifndef TNet_Vector_h\n", "meta": {"hexsha": "384c5d20eae10a3fc9a4a680f527ed357446683a", "size": 12556, "ext": "h", "lang": "C", "max_stars_repo_path": "src/KaldiLib/Vector.h", "max_stars_repo_name": "troylee/nnet-asr", "max_stars_repo_head_hexsha": "0381dcb95d9482c36a24d95af16155da9c12f43d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/KaldiLib/Vector.h", "max_issues_repo_name": "troylee/nnet-asr", "max_issues_repo_head_hexsha": "0381dcb95d9482c36a24d95af16155da9c12f43d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/KaldiLib/Vector.h", "max_forks_repo_name": "troylee/nnet-asr", "max_forks_repo_head_hexsha": "0381dcb95d9482c36a24d95af16155da9c12f43d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2635814889, "max_line_length": 144, "alphanum_fraction": 0.5259636827, "num_tokens": 3106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014734858584286, "lm_q2_score": 0.0446808737709169, "lm_q1q2_score": 0.019219359385058636}}
{"text": "\t#pragma once\n\n#include <DirectXMath.h>\n#include <d3d11.h>\n#include <gsl\\gsl>\n\nnamespace Library\n{\n\tclass Mesh;\n\n\ttemplate <typename T>\n\tstruct VertexDeclaration\n\t{\n\t\tstatic constexpr uint32_t VertexSize() { return gsl::narrow_cast<uint32_t>(sizeof(T)); }\n\t\tstatic constexpr uint32_t VertexBufferByteWidth(size_t vertexCount) { return gsl::narrow_cast<uint32_t>(sizeof(T) * vertexCount); }\n\t\tstatic void CreateVertexBuffer(gsl::not_null<ID3D11Device*> device, const gsl::span<const T>& vertices, gsl::not_null<ID3D11Buffer**> vertexBuffer);\n\t};\n\n\tclass VertexPosition : public VertexDeclaration<VertexPosition>\n\t{\n\tprivate:\n\t\tinline static const D3D11_INPUT_ELEMENT_DESC _InputElements[]\n\t\t{\n\t\t\t{ \"POSITION\", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },\n\t\t};\n\n\tpublic:\n\t\tVertexPosition() = default;\n\n\t\tVertexPosition(const DirectX::XMFLOAT4& position) :\n\t\t\tPosition(position) { }\n\n\t\tDirectX::XMFLOAT4 Position;\n\n\t\tinline static const gsl::span<const D3D11_INPUT_ELEMENT_DESC> InputElements { _InputElements };\n\n\t\tstatic void CreateVertexBuffer(gsl::not_null<ID3D11Device*> device, const Library::Mesh& mesh, gsl::not_null<ID3D11Buffer**> vertexBuffer);\n\t\tstatic void CreateVertexBuffer(gsl::not_null<ID3D11Device*> device, const gsl::span<const VertexPosition>& vertices, gsl::not_null<ID3D11Buffer**> vertexBuffer)\n\t\t{\n\t\t\tVertexDeclaration::CreateVertexBuffer(device, vertices, vertexBuffer);\n\t\t}\n\t};\n\n\tclass VertexPositionColor : public VertexDeclaration<VertexPositionColor>\n\t{\n\tprivate:\n\t\tinline static const D3D11_INPUT_ELEMENT_DESC _InputElements[]\n\t\t{\n\t\t\t{ \"POSITION\", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },\n\t\t\t{ \"COLOR\", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },\n\t\t};\n\n\tpublic:\n\t\tVertexPositionColor() = default;\n\n\t\tVertexPositionColor(const DirectX::XMFLOAT4& position, const DirectX::XMFLOAT4& color) :\n\t\t\tPosition(position), Color(color) { }\n\n\t\tDirectX::XMFLOAT4 Position;\n\t\tDirectX::XMFLOAT4 Color;\n\n\t\tinline static const gsl::span<const D3D11_INPUT_ELEMENT_DESC> InputElements{ _InputElements };\n\n\t\tstatic void CreateVertexBuffer(gsl::not_null<ID3D11Device*> device, const Library::Mesh& mesh, gsl::not_null<ID3D11Buffer**> vertexBuffer);\n\t\tstatic void CreateVertexBuffer(gsl::not_null<ID3D11Device*> device, const gsl::span<const VertexPositionColor>& vertices, gsl::not_null<ID3D11Buffer**> vertexBuffer)\n\t\t{\n\t\t\tVertexDeclaration::CreateVertexBuffer(device, vertices, vertexBuffer);\n\t\t}\n\t};\n\n\tclass VertexPositionTexture : public VertexDeclaration<VertexPositionTexture>\n\t{\n\tprivate:\n\t\tinline static const D3D11_INPUT_ELEMENT_DESC _InputElements[]\n\t\t{\n\t\t\t{ \"POSITION\", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },\n\t\t\t{ \"TEXCOORD\", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },\n\t\t};\n\tpublic:\n\t\tVertexPositionTexture() = default;\n\n\t\tVertexPositionTexture(const DirectX::XMFLOAT4& position, const DirectX::XMFLOAT2& textureCoordinates) :\n\t\t\tPosition(position), TextureCoordinates(textureCoordinates) { }\n\n\t\tDirectX::XMFLOAT4 Position;\n\t\tDirectX::XMFLOAT2 TextureCoordinates;\n\n\t\tinline static const gsl::span<const D3D11_INPUT_ELEMENT_DESC> InputElements{ _InputElements };\n\n\t\tstatic void CreateVertexBuffer(gsl::not_null<ID3D11Device*> device, const Library::Mesh& mesh, gsl::not_null<ID3D11Buffer**> vertexBuffer);\n\t\tstatic void CreateVertexBuffer(gsl::not_null<ID3D11Device*> device, const gsl::span<const VertexPositionTexture>& vertices, gsl::not_null<ID3D11Buffer**> vertexBuffer)\n\t\t{\n\t\t\tVertexDeclaration::CreateVertexBuffer(device, vertices, vertexBuffer);\n\t\t}\n\t};\n\t\t\n\tclass VertexPositionSize : public VertexDeclaration<VertexPositionSize>\n\t{\n\tprivate:\n\t\tinline static const D3D11_INPUT_ELEMENT_DESC _InputElements[]\n\t\t{\n\t\t\t{ \"POSITION\", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },\n\t\t\t{ \"SIZE\", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },\n\t\t};\n\n\tpublic:\n\t\tVertexPositionSize() = default;\n\n\t\tVertexPositionSize(const DirectX::XMFLOAT4& position, const DirectX::XMFLOAT2& size) :\n\t\t\tPosition(position), Size(size) { }\n\n\t\tDirectX::XMFLOAT4 Position;\n\t\tDirectX::XMFLOAT2 Size;\n\n\t\tinline static const gsl::span<const D3D11_INPUT_ELEMENT_DESC> InputElements{ _InputElements };\n\n\t\tstatic void CreateVertexBuffer(gsl::not_null<ID3D11Device*> device, const gsl::span<const VertexPositionSize>& vertices, gsl::not_null<ID3D11Buffer**> vertexBuffer)\n\t\t{\n\t\t\tVertexDeclaration::CreateVertexBuffer(device, vertices, vertexBuffer);\n\t\t}\n\t};\n\n\tclass VertexPositionNormal : public VertexDeclaration<VertexPositionNormal>\n\t{\n\tprivate:\n\t\tinline static const D3D11_INPUT_ELEMENT_DESC _InputElements[]\n\t\t{\n\t\t\t{ \"POSITION\", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },\n\t\t\t{ \"NORMAL\", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },\n\t\t};\n\n\tpublic:\n\t\tVertexPositionNormal() = default;\n\n\t\tVertexPositionNormal(const DirectX::XMFLOAT4& position, const DirectX::XMFLOAT3& normal) :\n\t\t\tPosition(position), Normal(normal) { }\n\n\t\tDirectX::XMFLOAT4 Position;\n\t\tDirectX::XMFLOAT3 Normal;\n\n\t\tinline static const gsl::span<const D3D11_INPUT_ELEMENT_DESC> InputElements{ _InputElements };\n\n\t\tstatic void CreateVertexBuffer(gsl::not_null<ID3D11Device*> device, const Library::Mesh& mesh, gsl::not_null<ID3D11Buffer**> vertexBuffer);\n\t\tstatic void CreateVertexBuffer(gsl::not_null<ID3D11Device*> device, const gsl::span<const VertexPositionNormal>& vertices, gsl::not_null<ID3D11Buffer**> vertexBuffer)\n\t\t{\n\t\t\tVertexDeclaration::CreateVertexBuffer(device, vertices, vertexBuffer);\n\t\t}\n\t};\n\n\tclass VertexPositionTextureNormal : public VertexDeclaration<VertexPositionTextureNormal>\n\t{\n\tprivate:\n\t\tinline static const D3D11_INPUT_ELEMENT_DESC _InputElements[]\n\t\t{\n\t\t\t{ \"POSITION\", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },\n\t\t\t{ \"TEXCOORD\", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },\n\t\t\t{ \"NORMAL\", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },\n\t\t};\n\n\tpublic:\n\t\tVertexPositionTextureNormal() = default;\n\n\t\tVertexPositionTextureNormal(const DirectX::XMFLOAT4& position, const DirectX::XMFLOAT2& textureCoordinates, const DirectX::XMFLOAT3& normal) :\n\t\t\tPosition(position), TextureCoordinates(textureCoordinates), Normal(normal) { }\n\n\t\tDirectX::XMFLOAT4 Position;\n\t\tDirectX::XMFLOAT2 TextureCoordinates;\n\t\tDirectX::XMFLOAT3 Normal;\n\t\t\n\t\tinline static const gsl::span<const D3D11_INPUT_ELEMENT_DESC> InputElements{ _InputElements };\n\n\t\tstatic void CreateVertexBuffer(gsl::not_null<ID3D11Device*> device, const Library::Mesh& mesh, gsl::not_null<ID3D11Buffer**> vertexBuffer);\n\t\tstatic void CreateVertexBuffer(gsl::not_null<ID3D11Device*> device, const gsl::span<const VertexPositionTextureNormal>& vertices, gsl::not_null<ID3D11Buffer**> vertexBuffer)\n\t\t{\n\t\t\tVertexDeclaration::CreateVertexBuffer(device, vertices, vertexBuffer);\n\t\t}\n\t};\n\n\tclass VertexPositionTextureNormalTangent : public VertexDeclaration<VertexPositionTextureNormalTangent>\n\t{\n\tprivate:\n\t\tinline static const D3D11_INPUT_ELEMENT_DESC _InputElements[]\n\t\t{\n\t\t\t{ \"POSITION\", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },\n\t\t\t{ \"TEXCOORD\", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },\n\t\t\t{ \"NORMAL\", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },\n\t\t\t{ \"TANGENT\", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },\n\t\t};\n\n\tpublic:\n\t\tVertexPositionTextureNormalTangent() = default;\n\n\t\tVertexPositionTextureNormalTangent(const DirectX::XMFLOAT4& position, const DirectX::XMFLOAT2& textureCoordinates, const DirectX::XMFLOAT3& normal, const DirectX::XMFLOAT3& tangent) :\n\t\t\tPosition(position), TextureCoordinates(textureCoordinates), Normal(normal), Tangent(tangent) { }\n\n\t\tDirectX::XMFLOAT4 Position;\n\t\tDirectX::XMFLOAT2 TextureCoordinates;\n\t\tDirectX::XMFLOAT3 Normal;\n\t\tDirectX::XMFLOAT3 Tangent;\n\n\t\tinline static const gsl::span<const D3D11_INPUT_ELEMENT_DESC> InputElements{ _InputElements };\n\n\t\tstatic void CreateVertexBuffer(gsl::not_null<ID3D11Device*> device, const Library::Mesh& mesh, gsl::not_null<ID3D11Buffer**> vertexBuffer);\t\t\n\t\tstatic void CreateVertexBuffer(gsl::not_null<ID3D11Device*> device, const gsl::span<const VertexPositionTextureNormalTangent>& vertices, gsl::not_null<ID3D11Buffer**> vertexBuffer)\n\t\t{\n\t\t\tVertexDeclaration::CreateVertexBuffer(device, vertices, vertexBuffer);\n\t\t}\n\t};\n\n\tclass VertexSkinnedPositionTextureNormal : public VertexDeclaration<VertexSkinnedPositionTextureNormal>\n\t{\n\tprivate:\n\t\tinline static const D3D11_INPUT_ELEMENT_DESC _InputElements[]\n\t\t{\n\t\t\t{ \"POSITION\", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },\n\t\t\t{ \"TEXCOORD\", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },\n\t\t\t{ \"NORMAL\", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },\n\t\t\t{ \"BONEINDICES\", 0, DXGI_FORMAT_R32G32B32A32_UINT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },\n\t\t\t{ \"BONEWEIGHTS\", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }\n\t\t};\n\n\tpublic:\n\t\tVertexSkinnedPositionTextureNormal() = default;\n\n\t\tVertexSkinnedPositionTextureNormal(const DirectX::XMFLOAT4& position, const DirectX::XMFLOAT2& textureCoordinates, const DirectX::XMFLOAT3& normal, const DirectX::XMUINT4& boneIndices, const DirectX::XMFLOAT4& boneWeights) :\n\t\t\tPosition(position), TextureCoordinates(textureCoordinates), Normal(normal), BoneIndices(boneIndices), BoneWeights(boneWeights) { }\n\n\t\tDirectX::XMFLOAT4 Position;\n\t\tDirectX::XMFLOAT2 TextureCoordinates;\n\t\tDirectX::XMFLOAT3 Normal;\n\t\tDirectX::XMUINT4 BoneIndices;\n\t\tDirectX::XMFLOAT4 BoneWeights;\n\t\n\t\tinline static const gsl::span<const D3D11_INPUT_ELEMENT_DESC> InputElements{ _InputElements };\n\n\t\tstatic void CreateVertexBuffer(gsl::not_null<ID3D11Device*> device, const Library::Mesh& mesh, gsl::not_null<ID3D11Buffer**> vertexBuffer);\n\t\tstatic void CreateVertexBuffer(gsl::not_null<ID3D11Device*> device, const gsl::span<const VertexSkinnedPositionTextureNormal>& vertices, gsl::not_null<ID3D11Buffer**> vertexBuffer)\n\t\t{\n\t\t\tVertexDeclaration::CreateVertexBuffer(device, vertices, vertexBuffer);\n\t\t}\n\t};\n}\n\n#include \"VertexDeclarations.inl\"", "meta": {"hexsha": "a035a08b94d9cd4d8f7d47c84e8fde9b538d0b2d", "size": 10838, "ext": "h", "lang": "C", "max_stars_repo_path": "source/Library.Shared/VertexDeclarations.h", "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/Library.Shared/VertexDeclarations.h", "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/Library.Shared/VertexDeclarations.h", "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.4180327869, "max_line_length": 226, "alphanum_fraction": 0.7873223842, "num_tokens": 3049, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3702254064929193, "lm_q2_score": 0.051845468847292006, "lm_q1q2_score": 0.01919450977880467}}
{"text": "\n/*\n* -----------------------------------------------------------------\n*  pmsr_lib.h\n*  Pairwise Mixing Stirred Reactor Library\n*  Version: 2.0\n*  Last Update: Oct 1, 2019\n*  \n*  This is the header file of a computational library with\n*  routines to implement a Pairwise Mixing Stirred Reactor\n*  (PMSR) model.\n* ----------------------------------------------------------------- \n*  Programmer: Americo Barbosa da Cunha Junior\n*              americo.cunhajr@gmail.com\n* -----------------------------------------------------------------\n*  Copyright (c) 2019 by Americo Barbosa da Cunha Junior\n* -----------------------------------------------------------------\n*/\n\n\n\n#ifndef __PMSR_LIB_H__\n#define __PMSR_LIB_H__\n\n\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_rng.h>\n\n\n\n\n/*\n* ------------------------------------------------------------\n*  Types: struct pmsr, pmsr_wrk\n* ------------------------------------------------------------\n* This structure contains fields of PMSR model.\n* \n* last update: Nov 5, 2009\n* ------------------------------------------------------------\n*/\n\ntypedef struct pmsr\n{\n    int *pmsr_idx;         /* particles index vector */\n    gsl_vector **pmsr_ps;  /* particle system        */\n} pmsr_wrk;\n/*------------------------------------------------------------*/\n\n\n\n\n\n/*\n*------------------------------------------------------------\n* function prototypes\n*------------------------------------------------------------\n*/\n\nvoid pmsr_title();\n\nint pmsr_input(unsigned long int *seed,\n               unsigned int *Np,\n               unsigned int *Ndt,\n\t       double *t0,\n               double *delta_t,\n               double *tau_res,\n               double *tau_mix,\n\t       double *tau_pair,\n               double *Tmax,\n               double *Tmin,\n               double *atol,\n               double *rtol);\n\npmsr_wrk *pmsr_alloc();\n\nint pmsr_init(int Np,\n              int Neq,\n              pmsr_wrk *pmsr);\n\nvoid pmsr_free(int Np,\n               void **pmsr_bl);\n\nvoid pmsr_set_all(int Np,\n                  gsl_vector *phi,\n                  pmsr_wrk *pmsr);\n\nint pmsr_Nexc(int Np,\n              double delta_t,\n              double tau_res);\n\nint pmsr_Npair(int Np,\n               double delta_t,\n               double tau_pair);\n\nvoid pmsr_meanvar(int Np,\n                  int k,\n                  gsl_vector **ps,\n                  double *mean,\n                  double *var);\n\nvoid pmsr_mixture(int Np,\n                  int Neq,\n                  double delta_t,\n                  double tau_mix,\n                  int *idx,\n                  gsl_vector **ps);\n\nvoid pmsr_iops(int Np,\n               int Nexc,\n               int Npair,\n               gsl_rng *r,\n               gsl_vector *phi,\n               pmsr_wrk *pmsr);\n\n\n#endif /* __PMSR_LIB_H__ */\n", "meta": {"hexsha": "33eb2f2593edf8c3658279953788aaa7c49d511f", "size": 2794, "ext": "h", "lang": "C", "max_stars_repo_path": "CRFlowLib-2.0/include/pmsr_lib.h", "max_stars_repo_name": "americocunhajr/CRFlowLib", "max_stars_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-29T12:56:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-29T12:56:14.000Z", "max_issues_repo_path": "CRFlowLib-2.0/include/pmsr_lib.h", "max_issues_repo_name": "americocunhajr/CRFlowLib", "max_issues_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CRFlowLib-2.0/include/pmsr_lib.h", "max_forks_repo_name": "americocunhajr/CRFlowLib", "max_forks_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-15T03:57:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-30T01:44:13.000Z", "avg_line_length": 23.8803418803, "max_line_length": 68, "alphanum_fraction": 0.4083750895, "num_tokens": 611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.04023794665187624, "lm_q1q2_score": 0.019176586574869984}}
{"text": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n#pragma once\n\n#include <iosfwd>\n#include <gsl\\gsl>\n#include <vector>\n\n#include \"Data\\Data.h\"\n#include \"Data\\TimeUnits.h\"\n\n#include <Plat/CameraDevice/CameraSettings.h>\n\nnamespace mage\n{\n    namespace binary_data\n    {\n        constexpr uint64_t LATEST_BINARY_VERSION = 3;\n        constexpr uint64_t LATEST_CALIBRATION_VERSION = 2;\n        \n        // portable strings for device information\n        struct DeviceInformation\n        {\n            std::string Id;\n            std::string DeviceName;\n            std::string DeviceManufacturer;\n            std::string DeviceHardwareVersion;\n            std::string DeviceFirmwareVersion;\n        };\n\n        struct HeaderData\n        {\n            uint64_t BinaryVersion;\n            uint64_t CalibrationVersion;\n            calibration::LinearFocalLengthModel Calibration;\n            mage::Size ImageSize;\n            mage::PixelFormat FormatOfPixels;\n\n            DeviceInformation DeviceInformation;\n\n            HeaderData(const uint64_t& b, const uint64_t& m, const calibration::LinearFocalLengthModel& c, const mage::Size& size, const mage::PixelFormat &fp, const mage::binary_data::DeviceInformation& deviceInfo)\n                : BinaryVersion{ b }, CalibrationVersion{ m }, Calibration{ c }, ImageSize{ size }, FormatOfPixels{ fp }, DeviceInformation{ deviceInfo }\n            {}\n\n            HeaderData()\n                : BinaryVersion{ LATEST_BINARY_VERSION },\n                CalibrationVersion{ LATEST_CALIBRATION_VERSION },\n                Calibration{},\n                ImageSize{},\n                FormatOfPixels{ mage::PixelFormat::GRAYSCALE8 },\n                DeviceInformation{ \"n/a\", \"n/a\", \"n/a\", \"n/a\" }\n            {}\n        };\n              \n        struct FileFrameData\n        {\n            uint64_t CorrelationId;\n            hundred_nanoseconds TimeStamp;\n            mira::CameraSettings CameraSettings;\n            std::vector<uint8_t> Pixels;\n\n            FileFrameData(const uint64_t& correlationId, const hundred_nanoseconds& t, const mira::CameraSettings& cameraSettings, std::vector<uint8_t> p)\n                : CorrelationId{ correlationId }, TimeStamp{ t }, CameraSettings{ cameraSettings }, Pixels{ std::move(p) }\n            {}\n            FileFrameData() = default;\n            FileFrameData(FileFrameData&&) = default;\n        };\n\n        void SerializeCaptureHeaderData(std::fstream& outputFile, const HeaderData& data);\n        void SerializeFrameData(std::fstream& outputFile, const FileFrameData& data);\n\n        bool DeSerializeHeaderData(std::istream& inputFile, HeaderData& data);\n        FileFrameData DeSerializeFrameData(std::istream& inputFile, HeaderData& headerData);\n    }\n}\n\n", "meta": {"hexsha": "b9d9d0897527e15906b137f6b5cd200046d49bc2", "size": 2760, "ext": "h", "lang": "C", "max_stars_repo_path": "Core/MAGESLAM/Source/Serialization/BinarySerializer.h", "max_stars_repo_name": "syntheticmagus/mageslam", "max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z", "max_issues_repo_path": "Core/MAGESLAM/Source/Serialization/BinarySerializer.h", "max_issues_repo_name": "syntheticmagus/mageslam", "max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z", "max_forks_repo_path": "Core/MAGESLAM/Source/Serialization/BinarySerializer.h", "max_forks_repo_name": "syntheticmagus/mageslam", "max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z", "avg_line_length": 35.3846153846, "max_line_length": 215, "alphanum_fraction": 0.6260869565, "num_tokens": 576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39233683016710835, "lm_q2_score": 0.04885777429425425, "lm_q1q2_score": 0.019168704295627743}}
{"text": "#include <gsl/gsl_test.h>\n#include <gsl/gsl_ieee_utils.h>\n#include <gsl/gsl_math.h>\n#include \"gsl_cblas.h\"\n\n#include \"tests.h\"\n\nvoid\ntest_gbmv (void) {\nconst double flteps = 1e-4, dbleps = 1e-6;\n  {\n   int order = 101;\n   int trans = 111;\n   int M = 3;\n   int N = 4;\n   int KL = 1;\n   int KU = 1;\n   int lda = 4;\n   float alpha = -1.0f;\n   float beta = -1.0f;\n   float A[] = { 0.423f, -0.143f, -0.182f, -0.076f, -0.855f, 0.599f, 0.389f, -0.473f, 0.493f, -0.902f, -0.889f, -0.256f, 0.112f, 0.128f, -0.277f, -0.777f };\n   float X[] = { 0.488f, 0.029f, -0.633f, 0.84f };\n   int incX = -1;\n   float Y[] = { 0.874f, 0.322f, -0.477f };\n   int incY = -1;\n   float y_expected[] = { -0.101941f, 0.764086f, 0.481914f };\n   cblas_sgbmv(order, trans, M, N, KU, KL, alpha, A,                                  lda, X, incX, beta, Y, incY);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(Y[i], y_expected[i], flteps, \"sgbmv(case 794)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int M = 3;\n   int N = 4;\n   int KL = 1;\n   int KU = 1;\n   int lda = 4;\n   float alpha = -1.0f;\n   float beta = -1.0f;\n   float A[] = { 0.423f, -0.143f, -0.182f, -0.076f, -0.855f, 0.599f, 0.389f, -0.473f, 0.493f, -0.902f, -0.889f, -0.256f, 0.112f, 0.128f, -0.277f, -0.777f };\n   float X[] = { 0.488f, 0.029f, -0.633f, 0.84f };\n   int incX = -1;\n   float Y[] = { 0.874f, 0.322f, -0.477f };\n   int incY = -1;\n   float y_expected[] = { -0.656261f, 0.19575f, 0.055905f };\n   cblas_sgbmv(order, trans, M, N, KU, KL, alpha, A,                                  lda, X, incX, beta, Y, incY);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(Y[i], y_expected[i], flteps, \"sgbmv(case 795)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int M = 3;\n   int N = 4;\n   int KL = 1;\n   int KU = 1;\n   int lda = 4;\n   float alpha = 0.0f;\n   float beta = 0.1f;\n   float A[] = { -0.066f, -0.153f, -0.619f, 0.174f, 0.777f, 0.543f, 0.614f, -0.446f, -0.138f, -0.767f, 0.725f, 0.222f, 0.165f, -0.063f, -0.047f, 0.267f };\n   float X[] = { -0.096f, -0.007f, -0.657f };\n   int incX = -1;\n   float Y[] = { -0.88f, 0.102f, -0.278f, 0.403f };\n   int incY = -1;\n   float y_expected[] = { -0.088f, 0.0102f, -0.0278f, 0.0403f };\n   cblas_sgbmv(order, trans, M, N, KU, KL, alpha, A,                                  lda, X, incX, beta, Y, incY);\n   {\n     int i;\n     for (i = 0; i < 4; i++) {\n       gsl_test_rel(Y[i], y_expected[i], flteps, \"sgbmv(case 796)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int M = 3;\n   int N = 4;\n   int KL = 1;\n   int KU = 1;\n   int lda = 4;\n   float alpha = 0.0f;\n   float beta = 0.1f;\n   float A[] = { -0.066f, -0.153f, -0.619f, 0.174f, 0.777f, 0.543f, 0.614f, -0.446f, -0.138f, -0.767f, 0.725f, 0.222f, 0.165f, -0.063f, -0.047f, 0.267f };\n   float X[] = { -0.096f, -0.007f, -0.657f };\n   int incX = -1;\n   float Y[] = { -0.88f, 0.102f, -0.278f, 0.403f };\n   int incY = -1;\n   float y_expected[] = { -0.088f, 0.0102f, -0.0278f, 0.0403f };\n   cblas_sgbmv(order, trans, M, N, KU, KL, alpha, A,                                  lda, X, incX, beta, Y, incY);\n   {\n     int i;\n     for (i = 0; i < 4; i++) {\n       gsl_test_rel(Y[i], y_expected[i], flteps, \"sgbmv(case 797)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int M = 3;\n   int N = 4;\n   int KL = 1;\n   int KU = 1;\n   int lda = 4;\n   double alpha = 0.1;\n   double beta = 0;\n   double A[] = { -0.688, 0.29, 0.442, -0.001, 0.313, -0.073, 0.991, -0.654, -0.12, 0.416, 0.571, 0.932, -0.179, -0.724, 0.492, -0.965 };\n   double X[] = { 0.187, -0.338, -0.976, -0.052 };\n   int incX = -1;\n   double Y[] = { -0.101, 0.8, 0.026 };\n   int incY = -1;\n   double y_expected[] = { 0.0083289, -0.0279986, -0.0446472 };\n   cblas_dgbmv(order, trans, M, N, KU, KL, alpha, A,                                  lda, X, incX, beta, Y, incY);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(Y[i], y_expected[i], dbleps, \"dgbmv(case 798)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int M = 3;\n   int N = 4;\n   int KL = 1;\n   int KU = 1;\n   int lda = 4;\n   double alpha = 0.1;\n   double beta = 0;\n   double A[] = { -0.688, 0.29, 0.442, -0.001, 0.313, -0.073, 0.991, -0.654, -0.12, 0.416, 0.571, 0.932, -0.179, -0.724, 0.492, -0.965 };\n   double X[] = { 0.187, -0.338, -0.976, -0.052 };\n   int incX = -1;\n   double Y[] = { -0.101, 0.8, 0.026 };\n   int incY = -1;\n   double y_expected[] = { -0.1141297, 0.0088824, -0.0320568 };\n   cblas_dgbmv(order, trans, M, N, KU, KL, alpha, A,                                  lda, X, incX, beta, Y, incY);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(Y[i], y_expected[i], dbleps, \"dgbmv(case 799)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int M = 3;\n   int N = 4;\n   int KL = 1;\n   int KU = 1;\n   int lda = 4;\n   double alpha = -0.3;\n   double beta = -0.3;\n   double A[] = { 0.746, 0.262, -0.449, -0.954, -0.093, 0.108, -0.496, 0.927, 0.177, 0.729, -0.92, -0.469, 0.87, -0.877, -0.308, -0.806 };\n   double X[] = { 0.662, -0.887, 0.261 };\n   int incX = -1;\n   double Y[] = { 0.771, 0.637, -0.177, -0.018 };\n   int incY = -1;\n   double y_expected[] = { -0.048588, -0.467865, 0.0818433, -0.0398619 };\n   cblas_dgbmv(order, trans, M, N, KU, KL, alpha, A,                                  lda, X, incX, beta, Y, incY);\n   {\n     int i;\n     for (i = 0; i < 4; i++) {\n       gsl_test_rel(Y[i], y_expected[i], dbleps, \"dgbmv(case 800)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int M = 3;\n   int N = 4;\n   int KL = 1;\n   int KU = 1;\n   int lda = 4;\n   double alpha = -0.3;\n   double beta = -0.3;\n   double A[] = { 0.746, 0.262, -0.449, -0.954, -0.093, 0.108, -0.496, 0.927, 0.177, 0.729, -0.92, -0.469, 0.87, -0.877, -0.308, -0.806 };\n   double X[] = { 0.662, -0.887, 0.261 };\n   int incX = -1;\n   double Y[] = { 0.771, 0.637, -0.177, -0.018 };\n   int incY = -1;\n   double y_expected[] = { -0.404082, -0.2887797, 0.1876263, -0.1345935 };\n   cblas_dgbmv(order, trans, M, N, KU, KL, alpha, A,                                  lda, X, incX, beta, Y, incY);\n   {\n     int i;\n     for (i = 0; i < 4; i++) {\n       gsl_test_rel(Y[i], y_expected[i], dbleps, \"dgbmv(case 801)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int M = 3;\n   int N = 4;\n   int KL = 1;\n   int KU = 1;\n   int lda = 4;\n   float alpha[2] = {0.0f, 1.0f};\n   float beta[2] = {0.0f, 0.1f};\n   float A[] = { -0.107f, 0.926f, -0.246f, -0.555f, -0.301f, 0.276f, 0.471f, -0.084f, -0.754f, 0.082f, -0.952f, -0.394f, 0.659f, 0.054f, 0.795f, 0.923f, 0.232f, -0.788f, 0.478f, 0.775f, -0.118f, 0.691f, -0.933f, 0.809f, 0.164f, -0.263f, -0.923f, -0.88f, 0.819f, -0.521f, -0.045f, 0.034f };\n   float X[] = { 0.407f, 0.895f, 0.301f, 0.769f, -0.269f, -0.465f, 0.455f, -0.628f };\n   int incX = -1;\n   float Y[] = { -0.116f, -0.744f, -0.936f, -0.064f, -0.232f, -0.665f };\n   int incY = -1;\n   float y_expected[] = { -0.806176f, -1.559f, -1.57611f, -0.155463f, 0.098816f, -0.274361f };\n   cblas_cgbmv(order, trans, M, N, KU, KL, alpha, A,                                  lda, X, incX, beta, Y, incY);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(Y[2*i], y_expected[2*i], flteps, \"cgbmv(case 802) real\");\n       gsl_test_rel(Y[2*i+1], y_expected[2*i+1], flteps, \"cgbmv(case 802) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int M = 3;\n   int N = 4;\n   int KL = 1;\n   int KU = 1;\n   int lda = 4;\n   float alpha[2] = {0.0f, 1.0f};\n   float beta[2] = {0.0f, 0.1f};\n   float A[] = { -0.107f, 0.926f, -0.246f, -0.555f, -0.301f, 0.276f, 0.471f, -0.084f, -0.754f, 0.082f, -0.952f, -0.394f, 0.659f, 0.054f, 0.795f, 0.923f, 0.232f, -0.788f, 0.478f, 0.775f, -0.118f, 0.691f, -0.933f, 0.809f, 0.164f, -0.263f, -0.923f, -0.88f, 0.819f, -0.521f, -0.045f, 0.034f };\n   float X[] = { 0.407f, 0.895f, 0.301f, 0.769f, -0.269f, -0.465f, 0.455f, -0.628f };\n   int incX = -1;\n   float Y[] = { -0.116f, -0.744f, -0.936f, -0.064f, -0.232f, -0.665f };\n   int incY = -1;\n   float y_expected[] = { -0.245235f, -0.313725f, -0.798094f, 0.691455f, -0.164015f, -0.242714f };\n   cblas_cgbmv(order, trans, M, N, KU, KL, alpha, A,                                  lda, X, incX, beta, Y, incY);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(Y[2*i], y_expected[2*i], flteps, \"cgbmv(case 803) real\");\n       gsl_test_rel(Y[2*i+1], y_expected[2*i+1], flteps, \"cgbmv(case 803) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int M = 3;\n   int N = 4;\n   int KL = 1;\n   int KU = 1;\n   int lda = 4;\n   float alpha[2] = {-1.0f, 0.0f};\n   float beta[2] = {0.0f, 0.1f};\n   float A[] = { -0.258f, 0.838f, -0.106f, -0.066f, 0.395f, 0.982f, -0.546f, 0.565f, 0.14f, -0.18f, 0.165f, -0.186f, 0.499f, -0.038f, -0.305f, -0.653f, -0.811f, -0.466f, -0.674f, -0.013f, -0.552f, -0.807f, -0.536f, 0.864f, -0.027f, -0.606f, 0.459f, 0.564f, -0.968f, 0.717f, -0.312f, -0.485f };\n   float X[] = { -0.399f, 0.459f, 0.398f, 0.358f, -0.161f, -0.359f };\n   int incX = -1;\n   float Y[] = { 0.572f, 0.293f, -0.813f, -0.096f, -0.611f, -0.717f, 0.736f, 0.259f };\n   int incY = -1;\n   float y_expected[] = { -0.619961f, -0.011425f, -0.477499f, 0.059361f, -0.886984f, 0.44008f, -0.139432f, 0.04644f };\n   cblas_cgbmv(order, trans, M, N, KU, KL, alpha, A,                                  lda, X, incX, beta, Y, incY);\n   {\n     int i;\n     for (i = 0; i < 4; i++) {\n       gsl_test_rel(Y[2*i], y_expected[2*i], flteps, \"cgbmv(case 804) real\");\n       gsl_test_rel(Y[2*i+1], y_expected[2*i+1], flteps, \"cgbmv(case 804) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int M = 3;\n   int N = 4;\n   int KL = 1;\n   int KU = 1;\n   int lda = 4;\n   float alpha[2] = {-1.0f, 0.0f};\n   float beta[2] = {0.0f, 0.1f};\n   float A[] = { -0.258f, 0.838f, -0.106f, -0.066f, 0.395f, 0.982f, -0.546f, 0.565f, 0.14f, -0.18f, 0.165f, -0.186f, 0.499f, -0.038f, -0.305f, -0.653f, -0.811f, -0.466f, -0.674f, -0.013f, -0.552f, -0.807f, -0.536f, 0.864f, -0.027f, -0.606f, 0.459f, 0.564f, -0.968f, 0.717f, -0.312f, -0.485f };\n   float X[] = { -0.399f, 0.459f, 0.398f, 0.358f, -0.161f, -0.359f };\n   int incX = -1;\n   float Y[] = { 0.572f, 0.293f, -0.813f, -0.096f, -0.611f, -0.717f, 0.736f, 0.259f };\n   int incY = -1;\n   float y_expected[] = { -0.318227f, -0.172201f, -0.109343f, 0.698685f, 0.208261f, -0.269065f, 0.175074f, -0.507326f };\n   cblas_cgbmv(order, trans, M, N, KU, KL, alpha, A,                                  lda, X, incX, beta, Y, incY);\n   {\n     int i;\n     for (i = 0; i < 4; i++) {\n       gsl_test_rel(Y[2*i], y_expected[2*i], flteps, \"cgbmv(case 805) real\");\n       gsl_test_rel(Y[2*i+1], y_expected[2*i+1], flteps, \"cgbmv(case 805) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 113;\n   int M = 3;\n   int N = 4;\n   int KL = 1;\n   int KU = 1;\n   int lda = 4;\n   float alpha[2] = {-1.0f, 0.0f};\n   float beta[2] = {0.0f, 0.1f};\n   float A[] = { -0.804f, 0.232f, -0.448f, -0.558f, -0.078f, -0.056f, -0.345f, -0.379f, 0.369f, -0.662f, -0.169f, -0.391f, -0.215f, 0.467f, 0.374f, 0.889f, -0.698f, 0.734f, 0.377f, -0.955f, 0.498f, 0.151f, -0.725f, -0.728f, -0.655f, -0.581f, 0.389f, 0.949f, -0.553f, -0.434f, 0.237f, 0.641f };\n   float X[] = { -0.262f, -0.823f, -0.357f, -0.994f, -0.347f, -0.375f };\n   int incX = -1;\n   float Y[] = { -0.683f, -0.87f, -0.708f, 0.071f, 0.575f, -0.575f, 0.845f, 0.032f };\n   int incY = -1;\n   float y_expected[] = { 0.341749f, 0.301992f, -0.306848f, 0.109252f, -0.018347f, -0.747479f, -0.894201f, 0.713246f };\n   cblas_cgbmv(order, trans, M, N, KU, KL, alpha, A,                                  lda, X, incX, beta, Y, incY);\n   {\n     int i;\n     for (i = 0; i < 4; i++) {\n       gsl_test_rel(Y[2*i], y_expected[2*i], flteps, \"cgbmv(case 806) real\");\n       gsl_test_rel(Y[2*i+1], y_expected[2*i+1], flteps, \"cgbmv(case 806) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 113;\n   int M = 3;\n   int N = 4;\n   int KL = 1;\n   int KU = 1;\n   int lda = 4;\n   float alpha[2] = {-1.0f, 0.0f};\n   float beta[2] = {0.0f, 0.1f};\n   float A[] = { -0.804f, 0.232f, -0.448f, -0.558f, -0.078f, -0.056f, -0.345f, -0.379f, 0.369f, -0.662f, -0.169f, -0.391f, -0.215f, 0.467f, 0.374f, 0.889f, -0.698f, 0.734f, 0.377f, -0.955f, 0.498f, 0.151f, -0.725f, -0.728f, -0.655f, -0.581f, 0.389f, 0.949f, -0.553f, -0.434f, 0.237f, 0.641f };\n   float X[] = { -0.262f, -0.823f, -0.357f, -0.994f, -0.347f, -0.375f };\n   int incX = -1;\n   float Y[] = { -0.683f, -0.87f, -0.708f, 0.071f, 0.575f, -0.575f, 0.845f, 0.032f };\n   int incY = -1;\n   float y_expected[] = { -0.562773f, -0.455143f, -0.213881f, -0.466169f, -0.183683f, 0.097891f, -0.451416f, 0.052586f };\n   cblas_cgbmv(order, trans, M, N, KU, KL, alpha, A,                                  lda, X, incX, beta, Y, incY);\n   {\n     int i;\n     for (i = 0; i < 4; i++) {\n       gsl_test_rel(Y[2*i], y_expected[2*i], flteps, \"cgbmv(case 807) real\");\n       gsl_test_rel(Y[2*i+1], y_expected[2*i+1], flteps, \"cgbmv(case 807) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int M = 3;\n   int N = 4;\n   int KL = 1;\n   int KU = 1;\n   int lda = 4;\n   double alpha[2] = {0, 0.1};\n   double beta[2] = {1, 0};\n   double A[] = { -0.919, -0.002, 0.105, -0.338, -0.358, -0.715, -0.157, 0.307, 0.334, 0.121, 0.366, 0.029, -0.006, -0.662, -0.314, 0.061, -0.322, -0.865, -0.586, 0.556, 0.507, 0.581, 0.855, -0.09, 0.836, -0.788, -0.209, -0.694, -0.695, 0.11, -0.234, 0.17 };\n   double X[] = { 0.356, -0.76, -0.96, 0.437, -0.849, 0.397, -0.382, -0.826 };\n   int incX = -1;\n   double Y[] = { 0.288, -0.832, 0.889, 0.576, -0.809, 0.4 };\n   int incY = -1;\n   double y_expected[] = { 0.3241775, -0.6761577, 0.8458527, 0.5705165, -0.8597295, 0.4268499 };\n   cblas_zgbmv(order, trans, M, N, KU, KL, alpha, A,                                  lda, X, incX, beta, Y, incY);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(Y[2*i], y_expected[2*i], dbleps, \"zgbmv(case 808) real\");\n       gsl_test_rel(Y[2*i+1], y_expected[2*i+1], dbleps, \"zgbmv(case 808) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int M = 3;\n   int N = 4;\n   int KL = 1;\n   int KU = 1;\n   int lda = 4;\n   double alpha[2] = {0, 0.1};\n   double beta[2] = {1, 0};\n   double A[] = { -0.919, -0.002, 0.105, -0.338, -0.358, -0.715, -0.157, 0.307, 0.334, 0.121, 0.366, 0.029, -0.006, -0.662, -0.314, 0.061, -0.322, -0.865, -0.586, 0.556, 0.507, 0.581, 0.855, -0.09, 0.836, -0.788, -0.209, -0.694, -0.695, 0.11, -0.234, 0.17 };\n   double X[] = { 0.356, -0.76, -0.96, 0.437, -0.849, 0.397, -0.382, -0.826 };\n   int incX = -1;\n   double Y[] = { 0.288, -0.832, 0.889, 0.576, -0.809, 0.4 };\n   int incY = -1;\n   double y_expected[] = { 0.4026074, -0.8033768, 0.7510795, 0.5671044, -0.8162255, 0.3349099 };\n   cblas_zgbmv(order, trans, M, N, KU, KL, alpha, A,                                  lda, X, incX, beta, Y, incY);\n   {\n     int i;\n     for (i = 0; i < 3; i++) {\n       gsl_test_rel(Y[2*i], y_expected[2*i], dbleps, \"zgbmv(case 809) real\");\n       gsl_test_rel(Y[2*i+1], y_expected[2*i+1], dbleps, \"zgbmv(case 809) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int M = 3;\n   int N = 4;\n   int KL = 1;\n   int KU = 1;\n   int lda = 4;\n   double alpha[2] = {1, 0};\n   double beta[2] = {1, 0};\n   double A[] = { 0.511, -0.707, -0.906, 0.345, -0.524, -0.933, 0.154, -0.529, -0.651, -0.851, 0.104, 0.532, -0.297, 0.477, 0.511, 0.469, -0.888, -0.789, 0.656, 0.288, -0.749, 0.961, 0.571, 0.539, 0.465, 0.647, 0.653, -0.994, -0.515, 0.297, 0.35, -0.707 };\n   double X[] = { -0.991, 0.658, -0.909, -0.99, -0.517, -0.071 };\n   int incX = -1;\n   double Y[] = { 0.451, 0.351, -0.113, -0.62, 0.983, 0.511, 0.142, -0.186 };\n   int incY = -1;\n   double y_expected[] = { 0.560921, -1.094193, -0.210397, -0.613323, 3.018979, 0.641612, 0.384166, 1.11801 };\n   cblas_zgbmv(order, trans, M, N, KU, KL, alpha, A,                                  lda, X, incX, beta, Y, incY);\n   {\n     int i;\n     for (i = 0; i < 4; i++) {\n       gsl_test_rel(Y[2*i], y_expected[2*i], dbleps, \"zgbmv(case 810) real\");\n       gsl_test_rel(Y[2*i+1], y_expected[2*i+1], dbleps, \"zgbmv(case 810) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int M = 3;\n   int N = 4;\n   int KL = 1;\n   int KU = 1;\n   int lda = 4;\n   double alpha[2] = {1, 0};\n   double beta[2] = {1, 0};\n   double A[] = { 0.511, -0.707, -0.906, 0.345, -0.524, -0.933, 0.154, -0.529, -0.651, -0.851, 0.104, 0.532, -0.297, 0.477, 0.511, 0.469, -0.888, -0.789, 0.656, 0.288, -0.749, 0.961, 0.571, 0.539, 0.465, 0.647, 0.653, -0.994, -0.515, 0.297, 0.35, -0.707 };\n   double X[] = { -0.991, 0.658, -0.909, -0.99, -0.517, -0.071 };\n   int incX = -1;\n   double Y[] = { 0.451, 0.351, -0.113, -0.62, 0.983, 0.511, 0.142, -0.186 };\n   int incY = -1;\n   double y_expected[] = { -0.435541, 0.015793, -0.926518, 1.122561, 1.671751, -0.257493, 0.187543, 1.066818 };\n   cblas_zgbmv(order, trans, M, N, KU, KL, alpha, A,                                  lda, X, incX, beta, Y, incY);\n   {\n     int i;\n     for (i = 0; i < 4; i++) {\n       gsl_test_rel(Y[2*i], y_expected[2*i], dbleps, \"zgbmv(case 811) real\");\n       gsl_test_rel(Y[2*i+1], y_expected[2*i+1], dbleps, \"zgbmv(case 811) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 113;\n   int M = 3;\n   int N = 4;\n   int KL = 1;\n   int KU = 1;\n   int lda = 4;\n   double alpha[2] = {0, 0.1};\n   double beta[2] = {-0.3, 0.1};\n   double A[] = { 0.534, 0.67, -0.621, 0.143, -0.794, 0.073, 0.414, -0.9, 0.155, -0.368, 0.122, -0.583, 0.03, 0.646, -0.768, -0.892, -0.741, -0.397, 0.626, 0.004, -0.515, 0.355, 0.196, -0.989, -0.982, 0.985, 0.445, 0.63, -0.849, -0.528, 0.146, -0.319 };\n   double X[] = { -0.199, -0.259, 0.386, -0.131, -0.867, 0.888 };\n   int incX = -1;\n   double Y[] = { 0.106, 0.874, 0.962, 0.636, -0.759, 0.415, -0.053, 0.315 };\n   int incY = -1;\n   double y_expected[] = { -0.139603, -0.250546, -0.3107376, -0.1144656, 0.2181809, -0.0877031, 0.0149724, -0.0224571 };\n   cblas_zgbmv(order, trans, M, N, KU, KL, alpha, A,                                  lda, X, incX, beta, Y, incY);\n   {\n     int i;\n     for (i = 0; i < 4; i++) {\n       gsl_test_rel(Y[2*i], y_expected[2*i], dbleps, \"zgbmv(case 812) real\");\n       gsl_test_rel(Y[2*i+1], y_expected[2*i+1], dbleps, \"zgbmv(case 812) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 113;\n   int M = 3;\n   int N = 4;\n   int KL = 1;\n   int KU = 1;\n   int lda = 4;\n   double alpha[2] = {0, 0.1};\n   double beta[2] = {-0.3, 0.1};\n   double A[] = { 0.534, 0.67, -0.621, 0.143, -0.794, 0.073, 0.414, -0.9, 0.155, -0.368, 0.122, -0.583, 0.03, 0.646, -0.768, -0.892, -0.741, -0.397, 0.626, 0.004, -0.515, 0.355, 0.196, -0.989, -0.982, 0.985, 0.445, 0.63, -0.849, -0.528, 0.146, -0.319 };\n   double X[] = { -0.199, -0.259, 0.386, -0.131, -0.867, 0.888 };\n   int incX = -1;\n   double Y[] = { 0.106, 0.874, 0.962, 0.636, -0.759, 0.415, -0.053, 0.315 };\n   int incY = -1;\n   double y_expected[] = { -0.1642353, -0.2575697, -0.3610975, -0.1305629, 0.1713576, -0.2514988, 0.0195631, -0.0648656 };\n   cblas_zgbmv(order, trans, M, N, KU, KL, alpha, A,                                  lda, X, incX, beta, Y, incY);\n   {\n     int i;\n     for (i = 0; i < 4; i++) {\n       gsl_test_rel(Y[2*i], y_expected[2*i], dbleps, \"zgbmv(case 813) real\");\n       gsl_test_rel(Y[2*i+1], y_expected[2*i+1], dbleps, \"zgbmv(case 813) imag\");\n     };\n   };\n  };\n\n\n}\n", "meta": {"hexsha": "9baf6c6834f1d8f245ed7a158dc0424efd372c85", "size": 19472, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/cblas/test_gbmv.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/cblas/test_gbmv.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/cblas/test_gbmv.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 35.7941176471, "max_line_length": 293, "alphanum_fraction": 0.4965078061, "num_tokens": 9566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.04084571766131308, "lm_q1q2_score": 0.019148089577445588}}
{"text": "// --------------------------------------------------------------------------\n//                   OpenMS -- Open-Source Mass Spectrometry\n// --------------------------------------------------------------------------\n// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,\n// ETH Zurich, and Freie Universitaet Berlin 2002-2013.\n//\n// This software is released under a three-clause BSD license:\n//  * Redistributions of source code must retain the above copyright\n//    notice, this list of conditions and the following disclaimer.\n//  * Redistributions in binary form must reproduce the above copyright\n//    notice, this list of conditions and the following disclaimer in the\n//    documentation and/or other materials provided with the distribution.\n//  * Neither the name of any author or any participating institution\n//    may be used to endorse or promote products derived from this software\n//    without specific prior written permission.\n// For a full list of authors, refer to the file AUTHORS.\n// --------------------------------------------------------------------------\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING\n// INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// --------------------------------------------------------------------------\n// $Maintainer: Clemens Groepl $\n// $Authors: $\n// --------------------------------------------------------------------------\n\n#ifndef OPENMS_TRANSFORMATIONS_FEATUREFINDER_LEVMARQFITTER1D_H\n#define OPENMS_TRANSFORMATIONS_FEATUREFINDER_LEVMARQFITTER1D_H\n\n#include <OpenMS/TRANSFORMATIONS/FEATUREFINDER/Fitter1D.h>\n\n#include <gsl/gsl_rng.h> // gsl random number generators\n#include <gsl/gsl_randist.h> // gsl random number distributions\n#include <gsl/gsl_vector.h> // gsl vector and matrix definitions\n#include <gsl/gsl_multifit_nlin.h> // gsl multidimensional fitting\n#include <gsl/gsl_blas.h> // gsl linear algebra stuff\n\n#include <OpenMS/DATASTRUCTURES/ListUtils.h>\n\nnamespace OpenMS\n{\n\n  /**\n    @brief Abstract class for 1D-model fitter using Levenberg-Marquardt algorithm for parameter optimization.\n      */\n  class OPENMS_DLLAPI LevMarqFitter1D :\n    public Fitter1D\n  {\n\npublic:\n\n    typedef std::vector<double> ContainerType;\n\n    /// Default constructor\n    LevMarqFitter1D() :\n      Fitter1D()\n    {\n      this->defaults_.setValue(\"max_iteration\", 500, \"Maximum number of iterations using by Levenberg-Marquardt algorithm.\", ListUtils::create<String>(\"advanced\"));\n      this->defaults_.setValue(\"deltaAbsError\", 0.0001, \"Absolute error used by the Levenberg-Marquardt algorithm.\", ListUtils::create<String>(\"advanced\"));\n      this->defaults_.setValue(\"deltaRelError\", 0.0001, \"Relative error used by the Levenberg-Marquardt algorithm.\", ListUtils::create<String>(\"advanced\"));\n    }\n\n    /// copy constructor\n    LevMarqFitter1D(const LevMarqFitter1D & source) :\n      Fitter1D(source),\n      max_iteration_(source.max_iteration_),\n      abs_error_(source.abs_error_),\n      rel_error_(source.rel_error_)\n    {\n    }\n\n    /// destructor\n    virtual ~LevMarqFitter1D()\n    {\n    }\n\n    /// assignment operator\n    virtual LevMarqFitter1D & operator=(const LevMarqFitter1D & source)\n    {\n      if (&source == this) return *this;\n\n      Fitter1D::operator=(source);\n      max_iteration_ = source.max_iteration_;\n      abs_error_ = source.abs_error_;\n      rel_error_ = source.rel_error_;\n\n      return *this;\n    }\n\nprotected:\n\n    /// GSL status\n    Int gsl_status_;\n    /// Parameter indicates symmetric peaks\n    bool symmetric_;\n    /// Maximum number of iterations\n    Int max_iteration_;\n    /** Test for the convergence of the sequence by comparing the last iteration step dx with the absolute error epsabs and relative error epsrel to the current position x */\n    /// Absolute error\n    CoordinateType abs_error_;\n    /// Relative error\n    CoordinateType rel_error_;\n\n    /** Display the intermediate state of the solution. The solver state contains\n        the vector s->x which is the current position, and the vector s->f with\n        corresponding function values */\n    virtual void printState_(Int iter, gsl_multifit_fdfsolver * s) = 0;\n\n    /// Return GSL status as string\n    const String getGslStatus_()\n    {\n      return gsl_strerror(gsl_status_);\n    }\n\n    /**\n        @brief Optimize start parameter\n\n        @exception Exception::UnableToFit is thrown if fitting cannot be performed\n    */\n    void optimize_(const RawDataArrayType & set, Int num_params, CoordinateType x_init[],\n                   Int (* residual)(const gsl_vector * x, void * params, gsl_vector * f),\n                   Int (* jacobian)(const gsl_vector * x, void * params, gsl_matrix * J),\n                   Int (* evaluate)(const gsl_vector * x, void * params, gsl_vector * f, gsl_matrix * J),\n                   void * advanced_params\n                   )\n    {\n\n      const gsl_multifit_fdfsolver_type * T;\n      gsl_multifit_fdfsolver * s;\n\n      Int status;\n      Int iter = 0;\n      const UInt n = (UInt)set.size();\n\n      // number of parameters to be optimized\n      UInt p = num_params;\n\n      // gsl always expects N>=p or default gsl error handler invoked,\n      // cause Jacobian be rectangular M x N with M>=N\n      if (n < p) throw Exception::UnableToFit(__FILE__, __LINE__, __PRETTY_FUNCTION__, \"UnableToFit-FinalSet\", \"Skipping feature, gsl always expects N>=p\");\n\n      // allocate space for a covariance matrix of size p by p\n      gsl_matrix * covar = gsl_matrix_alloc(p, p);\n      gsl_multifit_function_fdf f;\n\n      gsl_vector_view x = gsl_vector_view_array(x_init, p);\n\n      gsl_rng_env_setup();\n\n      // set up the function to be fit\n      f.f = (residual);     // the function of residuals\n      f.df = (jacobian);     // the gradient of this function\n      f.fdf = (evaluate);     // combined function and gradient\n      f.n = set.size();     // number of points in the data set\n      f.p = p;     // number of parameters in the fit function\n      f.params = advanced_params;     // // structure with the data and error bars\n\n      T = gsl_multifit_fdfsolver_lmsder;\n      s = gsl_multifit_fdfsolver_alloc(T, n, p);\n      gsl_multifit_fdfsolver_set(s, &f, &x.vector);\n\n#ifdef DEBUG_FEATUREFINDER\n      printState_(iter, s);\n#endif\n\n      // this is the loop for fitting\n      do\n      {\n        iter++;\n\n        // perform a single iteration of the fitting routine\n        status = gsl_multifit_fdfsolver_iterate(s);\n\n#ifdef DEBUG_FEATUREFINDER\n        // customized routine to print out current parameters\n        printState_(iter, s);\n#endif\n\n        /* check if solver is stuck */\n        if (status) break;\n\n        // test for convergence with an absolute and relative error\n        status = gsl_multifit_test_delta(s->dx, s->x, abs_error_, rel_error_);\n      }\n      while (status == GSL_CONTINUE && iter < max_iteration_);\n\n      // This function uses Jacobian matrix J to compute the covariance matrix of the best-fit parameters, covar.\n      // The parameter epsrel (0.0) is used to remove linear-dependent columns when J is rank deficient.\n      gsl_multifit_covar(s->J, 0.0, covar);\n\n#ifdef DEBUG_FEATUREFINDER\n      gsl_matrix_fprintf(stdout, covar, \"covar %g\");\n#endif\n\n#define FIT(i) gsl_vector_get(s->x, i)\n#define ERR(i) sqrt(gsl_matrix_get(covar, i, i))\n\n      // Set GSl status\n      gsl_status_ = status;\n\n#ifdef DEBUG_FEATUREFINDER\n      {\n        // chi-squared value\n        DoubleReal chi = gsl_blas_dnrm2(s->f);\n        DoubleReal dof = n - p;\n        DoubleReal c = GSL_MAX_DBL(1, chi / sqrt(dof));\n\n        printf(\"chisq/dof = %g\\n\", pow(chi, 2.0) / dof);\n\n        for (Size i = 0; i < p; ++i)\n        {\n          std::cout << i;\n          printf(\".Parameter = %.5f +/- %.5f\\n\", FIT(i), c * ERR(i));\n        }\n      }\n#endif\n\n      // set optimized parameters\n      for (Size i = 0; i < p; ++i)\n      {\n        x_init[i] = FIT(i);\n      }\n\n      gsl_multifit_fdfsolver_free(s);\n      gsl_matrix_free(covar);\n\n    }\n\n    void updateMembers_()\n    {\n      Fitter1D::updateMembers_();\n      max_iteration_ = this->param_.getValue(\"max_iteration\");\n      abs_error_ = this->param_.getValue(\"deltaAbsError\");\n      rel_error_ = this->param_.getValue(\"deltaRelError\");\n    }\n\n  };\n}\n\n#endif // OPENMS_TRANSFORMATIONS_FEATUREFINDER_LEVMARQFITTER1D_H\n", "meta": {"hexsha": "7950ea4a4a5b0d70ccb33f09735bd1731b9f7a9c", "size": 8984, "ext": "h", "lang": "C", "max_stars_repo_path": "include/OpenMS/TRANSFORMATIONS/FEATUREFINDER/LevMarqFitter1D.h", "max_stars_repo_name": "open-ms/all-svn-branches", "max_stars_repo_head_hexsha": "b182ba576e0cbfbe420b8edb0dd1c42bb6c973f3", "max_stars_repo_licenses": ["Zlib", "Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-05-23T03:43:10.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-23T03:43:10.000Z", "max_issues_repo_path": "src/openms/include/OpenMS/TRANSFORMATIONS/FEATUREFINDER/LevMarqFitter1D.h", "max_issues_repo_name": "kreinert/OpenMS", "max_issues_repo_head_hexsha": "45455356482ce5ab35e32e445609b291ec78a6d6", "max_issues_repo_licenses": ["Zlib", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/openms/include/OpenMS/TRANSFORMATIONS/FEATUREFINDER/LevMarqFitter1D.h", "max_forks_repo_name": "kreinert/OpenMS", "max_forks_repo_head_hexsha": "45455356482ce5ab35e32e445609b291ec78a6d6", "max_forks_repo_licenses": ["Zlib", "Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0803212851, "max_line_length": 174, "alphanum_fraction": 0.6468165628, "num_tokens": 2106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.04084571299100987, "lm_q1q2_score": 0.01914808738805122}}
{"text": "#include <gsl/gsl_test.h>\n#include <gsl/gsl_ieee_utils.h>\n#include <gsl/gsl_math.h>\n#include \"gsl_cblas.h\"\n\n#include \"tests.h\"\n\nvoid\ntest_hemm (void) {\nconst double flteps = 1e-4, dbleps = 1e-6;\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int M = 1;\n   int N = 2;\n   float alpha[2] = {0.0f, 0.1f};\n   float beta[2] = {0.0f, 0.1f};\n   float A[] = { -0.126f, 0.079f };\n   int lda = 1;\n   float B[] = { -0.954f, -0.059f, 0.296f, -0.988f };\n   int ldb = 2;\n   float C[] = { -0.859f, -0.731f, 0.737f, 0.593f };\n   int ldc = 2;\n   float C_expected[] = { 0.0723566f, -0.0738796f, -0.0717488f, 0.0699704f };\n   cblas_chemm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[2*i], C_expected[2*i], flteps, \"chemm(case 1550) real\");\n       gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, \"chemm(case 1550) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int M = 1;\n   int N = 2;\n   float alpha[2] = {0.0f, 0.1f};\n   float beta[2] = {0.0f, 0.1f};\n   float A[] = { 0.652f, 0.584f };\n   int lda = 1;\n   float B[] = { -0.983f, -0.734f, -0.422f, -0.825f };\n   int ldb = 1;\n   float C[] = { 0.387f, 0.341f, -0.734f, 0.632f };\n   int ldc = 1;\n   float C_expected[] = { 0.0137568f, -0.0253916f, -0.00941f, -0.100914f };\n   cblas_chemm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[2*i], C_expected[2*i], flteps, \"chemm(case 1551) real\");\n       gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, \"chemm(case 1551) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int M = 1;\n   int N = 2;\n   float alpha[2] = {0.0f, 1.0f};\n   float beta[2] = {-1.0f, 0.0f};\n   float A[] = { 0.78f, 0.885f, 0.507f, 0.765f, 0.911f, -0.461f, 0.707f, 0.508f };\n   int lda = 2;\n   float B[] = { -0.905f, 0.633f, 0.85f, -0.943f };\n   int ldb = 2;\n   float C[] = { 0.045f, -0.237f, 0.078f, -0.252f };\n   int ldc = 2;\n   float C_expected[] = { 0.589611f, -0.759345f, 0.960095f, -0.09013f };\n   cblas_chemm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[2*i], C_expected[2*i], flteps, \"chemm(case 1552) real\");\n       gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, \"chemm(case 1552) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int M = 1;\n   int N = 2;\n   float alpha[2] = {0.0f, 1.0f};\n   float beta[2] = {-1.0f, 0.0f};\n   float A[] = { 0.947f, 0.939f, -0.267f, -0.819f, -0.827f, -0.937f, 0.991f, 0.838f };\n   int lda = 2;\n   float B[] = { 0.871f, -0.988f, -0.232f, -0.434f };\n   int ldb = 1;\n   float C[] = { -0.261f, 0.927f, -0.351f, -0.203f };\n   int ldc = 1;\n   float C_expected[] = { 1.0551f, 0.496359f, 0.780145f, -1.67298f };\n   cblas_chemm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[2*i], C_expected[2*i], flteps, \"chemm(case 1553) real\");\n       gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, \"chemm(case 1553) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int M = 1;\n   int N = 2;\n   float alpha[2] = {-1.0f, 0.0f};\n   float beta[2] = {0.0f, 0.0f};\n   float A[] = { -0.593f, -0.9f };\n   int lda = 1;\n   float B[] = { -0.861f, 0.747f, -0.984f, 0.595f };\n   int ldb = 2;\n   float C[] = { -0.589f, -0.671f, -0.011f, -0.417f };\n   int ldc = 2;\n   float C_expected[] = { -0.510573f, 0.442971f, -0.583512f, 0.352835f };\n   cblas_chemm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[2*i], C_expected[2*i], flteps, \"chemm(case 1554) real\");\n       gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, \"chemm(case 1554) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int M = 1;\n   int N = 2;\n   float alpha[2] = {-1.0f, 0.0f};\n   float beta[2] = {0.0f, 0.0f};\n   float A[] = { -0.79f, 0.132f };\n   int lda = 1;\n   float B[] = { -0.243f, -0.12f, 0.633f, -0.556f };\n   int ldb = 1;\n   float C[] = { -0.658f, -0.74f, -0.47f, 0.481f };\n   int ldc = 1;\n   float C_expected[] = { -0.19197f, -0.0948f, 0.50007f, -0.43924f };\n   cblas_chemm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[2*i], C_expected[2*i], flteps, \"chemm(case 1555) real\");\n       gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, \"chemm(case 1555) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int M = 1;\n   int N = 2;\n   float alpha[2] = {-0.3f, 0.1f};\n   float beta[2] = {0.0f, 1.0f};\n   float A[] = { -0.114f, -0.515f, -0.513f, -0.527f, -0.995f, 0.986f, 0.229f, -0.076f };\n   int lda = 2;\n   float B[] = { 0.084f, 0.522f, 0.61f, 0.694f };\n   int ldb = 2;\n   float C[] = { 0.802f, 0.136f, -0.161f, -0.364f };\n   int ldc = 2;\n   float C_expected[] = { 0.269101f, 0.716492f, 0.237088f, 0.0290666f };\n   cblas_chemm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[2*i], C_expected[2*i], flteps, \"chemm(case 1556) real\");\n       gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, \"chemm(case 1556) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int M = 1;\n   int N = 2;\n   float alpha[2] = {-0.3f, 0.1f};\n   float beta[2] = {0.0f, 1.0f};\n   float A[] = { 0.798f, -0.324f, -0.693f, -0.893f, -0.223f, 0.749f, 0.102f, -0.357f };\n   int lda = 2;\n   float B[] = { -0.572f, -0.569f, -0.391f, -0.938f };\n   int ldb = 1;\n   float C[] = { 0.152f, -0.834f, -0.633f, -0.473f };\n   int ldc = 1;\n   float C_expected[] = { 1.08642f, -0.113853f, 0.234826f, -0.48289f };\n   cblas_chemm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[2*i], C_expected[2*i], flteps, \"chemm(case 1557) real\");\n       gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, \"chemm(case 1557) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int M = 1;\n   int N = 2;\n   double alpha[2] = {0, 0.1};\n   double beta[2] = {0, 0.1};\n   double A[] = { -0.359, 0.089 };\n   int lda = 1;\n   double B[] = { -0.451, -0.337, -0.901, -0.871 };\n   int ldb = 2;\n   double C[] = { 0.729, 0.631, 0.364, 0.246 };\n   int ldc = 2;\n   double C_expected[] = { -0.0751983, 0.0890909, -0.0558689, 0.0687459 };\n   cblas_zhemm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[2*i], C_expected[2*i], dbleps, \"zhemm(case 1558) real\");\n       gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, \"zhemm(case 1558) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int M = 1;\n   int N = 2;\n   double alpha[2] = {0, 0.1};\n   double beta[2] = {0, 0.1};\n   double A[] = { 0.044, -0.496 };\n   int lda = 1;\n   double B[] = { -0.674, 0.281, 0.366, 0.888 };\n   int ldb = 1;\n   double C[] = { -0.9, 0.919, 0.857, -0.049 };\n   int ldc = 1;\n   double C_expected[] = { -0.0931364, -0.0929656, 0.0009928, 0.0873104 };\n   cblas_zhemm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[2*i], C_expected[2*i], dbleps, \"zhemm(case 1559) real\");\n       gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, \"zhemm(case 1559) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int M = 1;\n   int N = 2;\n   double alpha[2] = {0, 0};\n   double beta[2] = {0, 0.1};\n   double A[] = { -0.314, 0.115, 0.114, 0.878, 0.961, -0.224, 0.973, 0.771 };\n   int lda = 2;\n   double B[] = { 0.5, -0.016, -0.5, 0.149 };\n   int ldb = 2;\n   double C[] = { -0.054, 0.064, 0.02, 0.245 };\n   int ldc = 2;\n   double C_expected[] = { -0.0064, -0.0054, -0.0245, 0.002 };\n   cblas_zhemm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[2*i], C_expected[2*i], dbleps, \"zhemm(case 1560) real\");\n       gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, \"zhemm(case 1560) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int M = 1;\n   int N = 2;\n   double alpha[2] = {0, 0};\n   double beta[2] = {0, 0.1};\n   double A[] = { 0.186, 0.578, 0.797, -0.957, -0.539, -0.969, -0.21, 0.354 };\n   int lda = 2;\n   double B[] = { 0.641, -0.968, 0.15, -0.569 };\n   int ldb = 1;\n   double C[] = { -0.556, -0.9, 0.197, 0.31 };\n   int ldc = 1;\n   double C_expected[] = { 0.09, -0.0556, -0.031, 0.0197 };\n   cblas_zhemm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[2*i], C_expected[2*i], dbleps, \"zhemm(case 1561) real\");\n       gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, \"zhemm(case 1561) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int M = 1;\n   int N = 2;\n   double alpha[2] = {1, 0};\n   double beta[2] = {1, 0};\n   double A[] = { 0.323, 0.641 };\n   int lda = 1;\n   double B[] = { -0.188, 0.091, -0.235, 0.523 };\n   int ldb = 2;\n   double C[] = { 0.919, 0.806, 0.823, -0.94 };\n   int ldc = 2;\n   double C_expected[] = { 0.858276, 0.835393, 0.747095, -0.771071 };\n   cblas_zhemm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[2*i], C_expected[2*i], dbleps, \"zhemm(case 1562) real\");\n       gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, \"zhemm(case 1562) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int M = 1;\n   int N = 2;\n   double alpha[2] = {1, 0};\n   double beta[2] = {1, 0};\n   double A[] = { -0.688, 0.915 };\n   int lda = 1;\n   double B[] = { 0.914, -0.204, 0.205, -0.476 };\n   int ldb = 1;\n   double C[] = { 0.27, -0.628, -0.079, 0.507 };\n   int ldc = 1;\n   double C_expected[] = { -0.358832, -0.487648, -0.22004, 0.834488 };\n   cblas_zhemm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[2*i], C_expected[2*i], dbleps, \"zhemm(case 1563) real\");\n       gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, \"zhemm(case 1563) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int M = 1;\n   int N = 2;\n   double alpha[2] = {0, 1};\n   double beta[2] = {0, 0.1};\n   double A[] = { 0.681, 0.574, -0.425, -0.64, 0.792, 0.661, -0.009, 0.005 };\n   int lda = 2;\n   double B[] = { -0.221, 0.554, -0.465, -0.95 };\n   int ldb = 2;\n   double C[] = { 0.331, -0.958, -0.826, -0.972 };\n   int ldc = 2;\n   double C_expected[] = { 0.778291, 0.142269, -0.496199, 0.112747 };\n   cblas_zhemm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[2*i], C_expected[2*i], dbleps, \"zhemm(case 1564) real\");\n       gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, \"zhemm(case 1564) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int M = 1;\n   int N = 2;\n   double alpha[2] = {0, 1};\n   double beta[2] = {0, 0.1};\n   double A[] = { 0.959, 0.34, -0.23, 0.064, 0.516, -0.275, 0.714, 0.899 };\n   int lda = 2;\n   double B[] = { -0.502, -0.987, -0.134, 0.215 };\n   int ldb = 1;\n   double C[] = { 0.929, 0.181, -0.16, -0.921 };\n   int ldc = 1;\n   double C_expected[] = { 0.986459, -0.371458, -0.320548, -0.059384 };\n   cblas_zhemm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[2*i], C_expected[2*i], dbleps, \"zhemm(case 1565) real\");\n       gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, \"zhemm(case 1565) imag\");\n     };\n   };\n  };\n\n\n}\n", "meta": {"hexsha": "ce1b888927ad6eb977a517f1df88552697b93cd5", "size": 12080, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/cblas/test_hemm.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/cblas/test_hemm.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/cblas/test_hemm.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 28.2242990654, "max_line_length": 88, "alphanum_fraction": 0.5070364238, "num_tokens": 5486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609384437117127, "lm_q2_score": 0.03846618829811288, "lm_q1q2_score": 0.01908283923111618}}
{"text": "\n#ifndef BIO_GSL_H_\n#define BIO_GSL_H_\n\n#include \"bio/defs.h\"\n#include \"bio/raii.h\"\n\n#include <gsl/gsl_integration.h>\n\nBIO_NS_START\n\nvoid\ngsl_init();\n\ntemplate <>\nRAII<gsl_integration_workspace *>::~RAII();\n\n#define BIO_GSL_EXP(x) ((x) < GSL_LOG_DBL_MIN ? 0.0 : gsl_sf_exp(x))\n\nBIO_NS_END\n\n\n#endif //BIO_GSL_H_\n\n", "meta": {"hexsha": "5c4d82136d375d8142b8785c1e77faa26b4ff2b4", "size": 312, "ext": "h", "lang": "C", "max_stars_repo_path": "C++/include/bio/gsl.h", "max_stars_repo_name": "JohnReid/biopsy", "max_stars_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "C++/include/bio/gsl.h", "max_issues_repo_name": "JohnReid/biopsy", "max_issues_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "C++/include/bio/gsl.h", "max_forks_repo_name": "JohnReid/biopsy", "max_forks_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 12.48, "max_line_length": 68, "alphanum_fraction": 0.7211538462, "num_tokens": 102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3960681662740417, "lm_q2_score": 0.04813676770280703, "lm_q1q2_score": 0.019065441314410295}}
{"text": "#pragma once\n\n#include <gsl.h>\n\n#include \"TMP_Helper.h\"\n#include \"HE_Assert.h\"\n#include \"HE_Math.h\"\n\n#include <type_traits>\n\nnamespace HE\n{\n\tstruct MemoryBlock\n\t{\n\t\tvoid* ptr;\n\t\tsize_t length;\n\n\t\tvoid* begin() const { return ptr; }\n\t\tvoid* end() const { return static_cast<char*>(ptr) + length; }\n\t};\n\tusing Blk = MemoryBlock;\n\t\n\n\t// Max alignment\n\tconstexpr size_t PlatformMaxAlignment = Math::Max(alignof(void*), alignof(size_t));\n\tstatic_assert(Math::IsPow2(PlatformMaxAlignment), \"PlatformMaxAlignment is not a power of 2, as should be\");\n\n\tnamespace Private\n\t{\n\t\ttemplate<class T>\n\t\tusing try_allocate = std::enable_if_t<std::is_same<Blk, decltype(std::declval<T>().allocate(std::declval<size_t>()))>::value>;\n\n\t\t// Custom aligned allocation's alignment parameter generally has to be a power of 2 and bigger than the allocator's default alignment,\n\t\t// in order to respect the allocator's semantics\n\t\ttemplate<class T>\n\t\tusing try_aligned_allocate = std::enable_if_t<std::is_same<Blk, decltype(std::declval<T>().allocate(std::declval<size_t>(), std::declval<size_t>()))>::value>;\n\n\t\ttemplate<class T>\n\t\tusing try_deallocate = decltype(std::declval<T>().deallocate(std::declval<Blk>()));\n\n\t\ttemplate<class T>\n\t\tusing try_deallocateAll = decltype(std::declval<T>().deallocateAll());\n\n\t\ttemplate<class T>\n\t\tusing try_owns = std::enable_if_t<std::is_same<bool, decltype(std::declval<T>().owns(std::declval<Blk>()))>::value>;\n\n\t\ttemplate<class T>\n\t\tusing try_it = std::enable_if_t<std::is_same<T, decltype(T::it)>::value>;\n\t}\n\n\t// Allocator\n\t// Must have (for allocator of type T): \n\t// - MemoryBlock T::allocate(size_t)\n\t// - void T::deallocate(MemoryBlock) noexcept\n\ttemplate<class T>\n\tusing is_allocator = and_ < has_op<T, Private::try_allocate>, has_op<T, Private::try_deallocate> > ;\n\ttemplate<class... T>\n\tconstexpr bool IsAllocator()\n\t{\n\t\treturn and_<is_allocator<T>...>::value;\n\t}\n\n\t// StatelessAllocator\n\t// - Allocator\n\t// - StateSize<T>::value == 0\n\t// - is_same<decltype(T::it), T> \n\ttemplate<class T>\n\tusing is_stateless_allocator = and_<is_allocator<T>, equal_<StateSize<T>, std::integral_constant<size_t, 0>>>;\n\ttemplate<class... T>\n\tconstexpr bool IsStatelessAllocator()\n\t{\n\t\treturn and_<is_stateless_allocator<T>...>::value;\n\t}\n\n\t// OwningAllocator\n\t// Must have (for allocator of type T)\n\t// - HE::is_allocator<T>()\n\t// - bool T::owns(MemoryBlock)\n\ttemplate<class T>\n\tusing is_owning_allocator = and_<is_allocator<T>, has_op<T, Private::try_owns>>;\n\ttemplate<class... T>\n\tconstexpr bool IsOwningAllocator()\n\t{\n\t\treturn and_<is_owning_allocator<T>...>::value;\n\t}\n\n\t// AlignedAllocator\n\t// Must have (for allocator of type T)\n\t// - HE::is_allocator<T>()\n\t// - bool T::allocate(size_t, size_t)\n\ttemplate<class T>\n\tusing is_aligned_allocator = and_<is_allocator<T>, has_op<T, Private::try_aligned_allocate>>;\n\ttemplate<class... T>\n\tconstexpr bool IsAlignedAllocator()\n\t{\n\t\treturn and_<is_aligned_allocator<T>...>::value;\n\t}\n\n\t// Generic allocator functions\n\ttemplate< class Type, class Allocator, class Enable = std::enable_if_t<is_allocator<Allocator>::value>>\n\tBlk allocate(Allocator&& a)\n\t{\n\t\treturn a.allocate(sizeof(Type));\n\t}\n\n\ttemplate<class Type, class Allocator, class Enable = std::enable_if_t<is_allocator<Allocator>::value>>\n\tBlk allocate(Allocator&& a, size_t count)\n\t{\n\t\treturn a.allocate(count*sizeof(Type), alignof(Type));\n\t}\n\n\tclass NullAllocator\n\t{\n\tpublic:\n\t\tstatic constexpr size_t alignment = 64 * 1024;\n\t\tstatic NullAllocator it;\n\n\t\tBlk allocate(size_t);\n\t\tBlk allocate(size_t, size_t);\n\t\tvoid deallocate(Blk) noexcept;\n\t\tvoid deallocateAll() noexcept;\n\t\tbool owns(Blk);\n\t};\n\t\n\t// Returns the beginning of the buffer is the buffer is big enough, even if it\n\t// was already allocated. This is because the allocator does no tracking. The client\n\t// is responsible for making sure memory doesn't get corrupted\n\t// Probably shouldn't be used as the main allocator of the Fallback allocator, but pairs\n\t// well with Segregator\n\ttemplate<size_t N>\n\tclass alignas(PlatformMaxAlignment) LightInlineAllocator\n\t{\n\tpublic:\n\t\tstatic constexpr size_t alignment = PlatformMaxAlignment;\n\n\t\tBlk allocate(size_t n)\n\t\t{\n\t\t\tif (n <= N)\n\t\t\t{\n\t\t\t\treturn{ m_buffer, n };\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn{ nullptr, 0 };\n\t\t\t}\n\t\t}\n\n\t\tBlk allocate(size_t n, size_t a)\n\t\t{\n\t\t\tEXPECTS(Math::IsPow2(alignment) && a >= alignment);\n\t\t\tauto const p = reinterpret_cast<char*>(Math::RoundUpToMultipleOf(reinterpret_cast<size_t>(&m_buffer[0]), a));\n\t\t\tBlk const b{ p, n };\n\t\t\tif (b.end() <= m_buffer + N)\n\t\t\t{\n\t\t\t\treturn b;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn{ nullptr, 0 };\n\t\t\t}\n\t\t}\n\n\t\tbool owns(Blk b)\n\t\t{\n\t\t\treturn b.begin() >= m_buffer && b.end() <= m_buffer + N;\n\t\t}\n\n\t\tvoid deallocate(Blk) noexcept {}\n\n\tprivate:\n\t\tchar m_buffer[N];\n\t};\n\n\tclass MallocAllocator\n\t{\n\tpublic:\n\t\tstatic constexpr size_t alignment = PlatformMaxAlignment;\n\t\tstatic MallocAllocator it;\n\n\t\tBlk allocate(size_t n);\n\t\tvoid deallocate(Blk) noexcept;\n\t};\n\n\tclass AlignedMallocAllocator\n\t{\n\tpublic:\n\t\tstatic constexpr size_t alignment = PlatformMaxAlignment;\n\t\tstatic AlignedMallocAllocator it;\n\n\t\tBlk allocate(size_t n);\n\t\tBlk allocate(size_t n, size_t alignment);\n\t\tvoid deallocate(Blk) noexcept;\n\t};\n\n\ttemplate< class Primary, class Fallback >\n\tclass FallbackAllocator;\n\n\tnamespace Private\n\t{\n\t\ttemplate < class Primary, class Fallback, class Enable = void>\n\t\tstruct FallbackAllocatorImpl {\t};\n\n\t\ttemplate< class Primary, class Fallback >\n\t\tusing FallbackStatelessCond = std::enable_if_t<\n\t\t\tand_<\n\t\t\tequal_<StateSize<Primary>, std::integral_constant<size_t, 0>>,\n\t\t\tequal_<StateSize<Fallback>, std::integral_constant<size_t, 0>>\n\t\t\t>::value\n\t\t>;\n\n\t\ttemplate < class Primary, class Fallback >\n\t\tstruct FallbackAllocatorImpl<Primary, Fallback, \n\t\t\tFallbackStatelessCond<Primary, Fallback> >\n\t\t{\n\t\t\tstatic FallbackAllocator<Primary, Fallback> it;\n\t\t};\n\t}\n\n\ttemplate< class Primary, class Fallback >\n\tclass FallbackAllocator :\n\t\tprivate Primary,\n\t\tprivate Fallback,\n\t\tprivate Private::FallbackAllocatorImpl<Primary, Fallback>\n\t{\n\tprotected:\n\t\tusing P = Primary;\n\t\tusing F = Fallback;\n\n\t\tstatic_assert(IsOwningAllocator<P>(), \"Primary allocator does not meet the HE::OwningAllocator concept\");\n\t\tstatic_assert(IsAllocator<F>(), \"Fallback allocator does not meet the HE::Allocator concept\");\n\n\tpublic:\n\t\tstatic constexpr size_t alignment = Math::Min(Primary::alignment, Fallback::alignment);\n\n\t\tBlk allocate(size_t n)\n\t\t{\n\t\t\tauto const blk = P::allocate(n);\n\t\t\tif (!blk.ptr) return F::allocate(n);\n\t\t\treturn blk;\n\t\t}\n\n\t\ttemplate<class Enable = std::enable_if_t<and_<is_aligned_allocator<Primary>, is_aligned_allocator<Fallback>>::value>>\n\t\tBlk allocate(size_t n, size_t alignment)\n\t\t{\n\t\t\tauto const blk = P::allocate(n, alignment);\n\t\t\tif (!blk.ptr) return F::allocate(n, alignment);\n\t\t\treturn blk;\n\t\t}\n\n\t\tvoid deallocate(Blk b) noexcept\n\t\t{\n\t\t\tif (P::owns(b))\n\t\t\t\tP::deallocate(b);\n\t\t\telse\n\t\t\t\tF::deallocate(b);\n\t\t}\n\n\t\ttemplate<class Enable = std::enable_if_t<and_<has_op<Primary, Private::try_deallocateAll>, has_op<Fallback, Private::try_deallocateAll>>::value>>\n\t\tvoid deallocateAll() noexcept\n\t\t{\n\t\t\tPrimary::deallocateAll();\n\t\t\tFallback::deallocateAll();\n\t\t}\n\t\t\n\n\t\ttemplate<class Enable = std::enable_if_t<is_owning_allocator<Fallback>::value>>\n\t\tbool owns(Blk b)\n\t\t{\n\t\t\treturn Primary::owns(b) || Fallback::owns(b);\n\t\t}\n\t};\n\n\ttemplate< class Primary, class Fallback >\n\tFallbackAllocator<Primary, Fallback> Private::FallbackAllocatorImpl<Primary, Fallback, Private::FallbackStatelessCond<Primary, Fallback>>::it;\n\n\tnamespace Allocator\n\t{\n\t\tconstexpr size_t unbounded = static_cast<size_t>(-1);\n\t}\n\n\t// An allocator that allocates nodes on a Parent allocator and internally keeps blocks\n\t// of memory on deallocation instead of actually deallocating them, but only\n\t// if they have a certain size\n\t// Important: Actual deallocations to the parent allocator are not guaranteed to be ordered as \n\t// deallocated in the Freelist allocator, and therefore should not be used with allocators\n\t// that require ordered deallocations, such as StackAllocator\n\n\t// minSize: Minimum size of the allocation to be considered in range\n\t// maxSize: Maxsimum size of the allocation to be considered in range\n\t// batchCount: Number of allocations on a fresh \"in range\" allocation. Basically fills up the Freelist with batchCount nodes on allocation\n\t// maxNodes: Max number of nodes the freelist can keep\n\ttemplate< class Parent,\n\t\tsize_t MinSize, \n\t\tsize_t MaxSize = MinSize,\n\t\tsize_t MaxNodes = Allocator::unbounded,\n\t\tclass Enable = std::enable_if_t<is_allocator<Parent>::value>\n\t\t>\n\tclass FreelistAllocator\n\t\t: private Parent\n\t{\n\t\tstatic_assert(MaxSize >= MinSize, \"FreelistAllocator's MaxSize should be higher or equal to MinSize\");\n\t\tstatic_assert(MaxSize >= sizeof(void*), \"FreelistAllocator's MaxSize and MinSize should be higher or equal than sizeof(void*)\");\n\n\tpublic:\n\t\tstatic constexpr size_t alignment = Parent::alignment;\n\n\t\tBlk allocate(size_t n)\n\t\t{\n\t\t\treturn allocateImpl(n);\n\t\t}\n\n\t\ttemplate<class Enable = std::enable_if_t<is_aligned_allocator<Parent>::value>>\n\t\tBlk allocate(size_t n, size_t alignment)\n\t\t{\n\t\t\treturn allocateImpl(n, alignment);\n\t\t}\n\n\t\tvoid deallocate(Blk b) noexcept\n\t\t{\n\t\t\tif ((MaxNodes == Allocator::unbounded || m_nNodesCount != MaxNodes) && inRange(b.length))\n\t\t\t{\n\t\t\t\tauto const next = m_pFreelistRoot;\n\t\t\t\tm_pFreelistRoot = static_cast<Node*>(b.ptr);\n\t\t\t\tm_pFreelistRoot->next = next;\n\t\t\t\t++m_nNodesCount;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tParent::deallocate(b);\n\t\t\t}\n\t\t}\n\n\t\t// Only O(1) if the Parent allocator supports deallocateAll\n\t\t// If the Freelist is unbounded and the Parent doesn't support deallocateAll,\n\t\t// the Freelist will do a best effort of deallocating all the nodes in its freelist\n\t\t// in O(n)\n\t\tvoid deallocateAll() noexcept\n\t\t{\n\t\t\tdeallocateAllImpl();\n\t\t}\n\n\t\tstatic constexpr bool has_fast_deallocateAll() { return has_op<Parent, Private::try_deallocateAll>::value; }\n\n\t\tbool owns(Blk b)\n\t\t{\n\t\t\treturn Parent::owns(b);\n\t\t}\n\n\tprivate:\n\t\tstruct Node\n\t\t{\n\t\t\tNode* next;\n\t\t};\n\t\tNode* m_pFreelistRoot{ nullptr };\n\t\tsize_t m_nNodesCount{ 0 };\n\n\t\tbool inRange(size_t n) const\n\t\t{\n\t\t\tif (MinSize == MaxSize) return n == MaxSize;\n\n\t\t\treturn (MinSize == 0 || n >= MinSize) && n <= MaxSize;\n\t\t}\n\n\t\ttemplate<class... Args>\n\t\tBlk allocateImpl(size_t n, Args... args)\n\t\t{\n\t\t\tif (!inRange(n)) return Parent::allocate(n, args...);\n\n\t\t\tif (!m_pFreelistRoot)\n\t\t\t{\n\t\t\t\tauto const b = Parent::allocate(MaxSize, args...);\n\t\t\t\treturn{ b.ptr, n };\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tBlk const result{ static_cast<void*>(m_pFreelistRoot), n };\n\t\t\t\tm_pFreelistRoot = m_pFreelistRoot->next;\n\t\t\t\t--m_nNodesCount;\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\n\t\tvoid deallocateAllImpl(std::enable_if_t<has_op<Parent, Private::try_deallocateAll>::value>* = nullptr) noexcept\n\t\t{\n\t\t\tParent::deallocateAll();\n\t\t\tm_pFreelistRoot = nullptr;\n\t\t}\n\n\t\t// In this case, we can only guarantee a complete deallocation if the freelist is unbounded\n\t\tvoid deallocateAllImpl(std::enable_if_t<\n\t\t\tand_<\n\t\t\tnot_<has_op<Parent, Private::try_deallocateAll>>,\n\t\t\thas_op<Parent, Private::try_deallocate>,\n\t\t\tequal_<std::integral_constant<size_t, MaxNodes>, std::integral_constant<size_t, Allocator::unbounded>>\n\t\t\t>::value>* = nullptr) noexcept\n\t\t{\n\t\t\tauto next = m_pFreelistRoot;\n\t\t\twhile (next)\n\t\t\t{\n\t\t\t\tBlk const b{ static_cast<void*>(next), MaxSize };\n\t\t\t\tnext = next->next;\n\t\t\t\tParent::deallocate(b);\n\t\t\t}\n\t\t\tm_pFreelistRoot = nullptr;\n\t\t}\n\t};\n\n\ttemplate<class Parent, class PrefixType, class SuffixType>\n\tclass AffixAllocator;\n\n\tnamespace Private\n\t{\n\t\ttemplate < class Parent, class PrefixType, class SuffixType, class Enable = void>\n\t\tstruct AffixParentImpl : protected Parent {\t};\n\n\t\ttemplate < class Parent, class PrefixType, class SuffixType>\n\t\tstruct AffixParentImpl<Parent, PrefixType, SuffixType, std::enable_if_t<StateSize<Parent>::value == 0>>\n\t\t\t: protected Parent\n\t\t{\n\t\t\tstatic AffixAllocator<Parent, PrefixType, SuffixType> it;\n\t\t};\n\n\t\ttemplate<class PrefixType>\n\t\tstruct PrefixImpl\n\t\t{\n\t\t\ttemplate<class Enable = std::enable_if_t<StateSize<PrefixType>::value != 0>>\n\t\t\tstatic PrefixType& Prefix(Blk& b)\n\t\t\t{\n\t\t\t\treturn reinterpret_cast<PrefixType*>(b.ptr)[-1];\n\t\t\t}\n\t\t};\n\n\t\ttemplate<>\n\t\tstruct PrefixImpl<void>{};\n\n\t\ttemplate<class PrefixType, class SuffixType>\n\t\tstruct SuffixImpl\n\t\t{\n\t\t\ttemplate<class Enable = std::enable_if_t<StateSize<SuffixType>::value != 0>>\n\t\t\tstatic SuffixType& Suffix(Blk& b)\n\t\t\t{\n\n\t\t\t\tauto const p = static_cast<char*>(b.ptr) + b.length;\n\t\t\t\treturn *reinterpret_cast<SuffixType*>(p);\n\t\t\t}\n\n\t\tprotected:\n\t\t\tstatic size_t totalAllocationSize(size_t s)\n\t\t\t{\n\t\t\t\tif (StateSize<SuffixType>::value == 0)\n\t\t\t\t{\n\t\t\t\t\treturn s + StateSize<PrefixType>::value;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\treturn Math::RoundUpToMultipleOf(s + StateSize<PrefixType>::value, alignof(SuffixType)) + StateSize<SuffixType>::value;\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\ttemplate<class PrefixType>\n\t\tstruct SuffixImpl<PrefixType, void>\n\t\t{\n\t\tprotected:\n\t\t\tstatic size_t totalAllocationSize(size_t s)\n\t\t\t{\n\t\t\t\treturn s + StateSize<PrefixType>::value;\n\t\t\t}\n\t\t};\n\t}\n\n\ttemplate<class Parent, class PrefixType, class SuffixType = void>\n\tclass AffixAllocator : public Private::AffixParentImpl<Parent, PrefixType, SuffixType>,\n\t\tpublic Private::PrefixImpl<PrefixType>,\n\t\tpublic Private::SuffixImpl<PrefixType, SuffixType>\n\t{\n\tpublic:\n\t\tstatic constexpr size_t alignment = StateSize<PrefixType>::value ? alignof(PrefixType) : Parent::alignment;\n\n\t\tBlk allocate(size_t n)\n\t\t{\n\t\t\tauto const result = Parent::allocate(totalAllocationSize(n));\n\t\t\tif (!result.ptr) return result;\n\n\t\t\treturn{ static_cast<char*>(result.ptr) + StateSize<PrefixType>::value, n };\n\t\t}\n\n\t\tbool owns(Blk b)\n\t\t{\n\t\t\treturn Parent::owns(actualAllocation(b));\n\t\t}\n\n\t\tvoid deallocate(Blk b)\n\t\t{\n\t\t\tParent::deallocate(actualAllocation(b));\n\t\t}\n\n\tprivate:\n\t\t// Takes a requested allocation, and returns the actual allocation that was request to the parent\n\t\tstatic Blk actualAllocation(Blk b)\n\t\t{\n\t\t\tif (!b.ptr) return{ nullptr, 0 };\n\t\t\treturn{ static_cast<char*>(b.ptr) - StateSize<PrefixType>::value, totalAllocationSize(b.length) };\n\t\t}\n\t};\n\n\ttemplate<class Parent, class PrefixType, class SuffixType>\n\tAffixAllocator<Parent, PrefixType, SuffixType> Private::AffixParentImpl<Parent, PrefixType, SuffixType, std::enable_if_t<StateSize<Parent>::value == 0>>::it;\n\t\n\ttemplate < size_t Threshold, class SmallAllocator, class LargeAllocator >\n\tclass SegregateAllocator;\n\n\tnamespace Private\n\t{\n\t\ttemplate < size_t Threshold, class SmallAllocator, class LargeAllocator, class Enable = void>\n\t\tstruct SegregateAllocatorImpl {\t};\n\n\t\ttemplate< class SmallAllocator, class LargeAllocator >\n\t\tusing SegregateAllocatorStatelessCond = std::enable_if_t<\n\t\t\tand_<\n\t\t\tequal_<StateSize<SmallAllocator>, std::integral_constant<size_t, 0>>,\n\t\t\tequal_<StateSize<LargeAllocator>, std::integral_constant<size_t, 0>>\n\t\t\t>::value\n\t\t>;\n\n\t\ttemplate < size_t Threshold, class SmallAllocator, class LargeAllocator >\n\t\tstruct SegregateAllocatorImpl<Threshold, SmallAllocator, LargeAllocator,\n\t\t\tSegregateAllocatorStatelessCond<SmallAllocator, LargeAllocator> >\n\t\t{\n\t\t\tstatic SegregateAllocator<Threshold, SmallAllocator, LargeAllocator> it;\n\t\t};\n\t}\n\n\t// Seggregator\n\ttemplate<size_t Threshold,\n\t\tclass SmallAllocator,\n\t\tclass LargeAllocator >\n\tclass SegregateAllocator\n\t\t: private SmallAllocator,\n\t\tprivate LargeAllocator\n\t{\n\tpublic:\n\t\tconstexpr static size_t alignment = Math::Min(SmallAllocator::alignment, LargeAllocator::alignment);\n\n\t\tBlk allocate(size_t n)\n\t\t{\n\t\t\treturn allocate_Impl(n);\n\t\t}\n\n\t\tBlk allocate(size_t n, size_t alignment_requirement)\n\t\t{\n\t\t\tEXPECTS(alignment_requirement >= alignment && Math::IsPow2(alignment_requirement));\n\t\t\treturn allocate_Impl(n, alignment_requirement);\n\t\t}\n\n\t\tbool owns(Blk b)\n\t\t{\n\t\t\treturn n <= Threshold ? SmallAllocator::owns(b) : LargeAllocator::owns(b);\n\t\t}\n\n\t\tvoid deallocate(Blk b)\n\t\t{\n\t\t\treturn n <= Threshold ? SmallAllocator::deallocate(b) : LargeAllocator::deallocate(b);\n\t\t}\n\n\t\tvoid deallocateAll()\n\t\t{\n\t\t\tSmallAllocator::deallocateAll();\n\t\t\tLargeAllocator::deallocateAll();\n\t\t}\n\n\tprivate:\n\t\ttemplate<class... Args>\n\t\tBlk allocate_Impl(size_t n, Args... args)\n\t\t{\n\t\t\treturn n <= Threshold ? SmallAllocator::allocate(n, args...) : LargeAllocator::allocate(n, args...);\n\t\t}\n\t};\n\n\ttemplate < size_t Threshold, class SmallAllocator, class LargeAllocator >\n\tSegregateAllocator<Threshold, SmallAllocator, LargeAllocator> Private::SegregateAllocatorImpl<Threshold, SmallAllocator, LargeAllocator, Private::SegregateAllocatorStatelessCond<SmallAllocator, LargeAllocator>>::it;\n}", "meta": {"hexsha": "e74ac1243123080de72845b6ccff2b976ed9c38e", "size": 16470, "ext": "h", "lang": "C", "max_stars_repo_path": "src/Source/SDK/HE_Allocator.h", "max_stars_repo_name": "KABoissonneault/Hazel_Engine", "max_stars_repo_head_hexsha": "e5ab97f6ccbc2c77bd92dd9dc84f2f64670e586d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Source/SDK/HE_Allocator.h", "max_issues_repo_name": "KABoissonneault/Hazel_Engine", "max_issues_repo_head_hexsha": "e5ab97f6ccbc2c77bd92dd9dc84f2f64670e586d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Source/SDK/HE_Allocator.h", "max_forks_repo_name": "KABoissonneault/Hazel_Engine", "max_forks_repo_head_hexsha": "e5ab97f6ccbc2c77bd92dd9dc84f2f64670e586d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2989690722, "max_line_length": 216, "alphanum_fraction": 0.7125075896, "num_tokens": 4457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.03963883782465424, "lm_q1q2_score": 0.019045616397345245}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef polygon_9cb4a5c6_8903_42fd_9232_eb81bfcd30a5_h\r\n#define polygon_9cb4a5c6_8903_42fd_9232_eb81bfcd30a5_h\r\n\r\n#include <gslib/std.h>\r\n#include <gslib/math.h>\r\n#include <ariel/config.h>\r\n\r\n__ariel_begin__\r\n\r\nclass polygon\r\n{\r\npublic:\r\n    typedef gs::vector<point3> vtstream;\r\n    typedef gs::vector<int> idstream;\r\n    typedef vtstream::iterator vtiter;\r\n    typedef vtstream::const_iterator const_vtiter;\r\n    typedef idstream::iterator iditer;\r\n    typedef idstream::const_iterator const_iditer;\r\n\r\npublic:\r\n    polygon();\r\n    int get_vertex_count() const { return (int)_vtstream.size(); }\r\n    int get_index_count() const { return (int)_idstream.size(); }\r\n    int get_face_count() const { return _faces; }\r\n    int query_face_count();\r\n    void write_vtstream(int start, int cnt, const point3* src);\r\n    void append_vtstream(int cnt, const point3* src) { write_vtstream(get_vertex_count(), cnt, src); }\r\n    void append_vtstream(const point3& src) { _vtstream.push_back(src); }\r\n    void write_idstream(int start, int cnt, const int* src);\r\n    void append_idstream(int cnt, const int* src) { write_idstream(get_index_count(), cnt, src); }\r\n    void append_idstream(int idx) { _idstream.push_back(idx); }\r\n    point3& get_vertex(int i) { return _vtstream.at(i); }\r\n    const point3& get_vertex(int i) const { return _vtstream.at(i); }\r\n    int& get_index(int i) { return _idstream.at(i); }\r\n    const int& get_index(int i) const { return _idstream.at(i); }\r\n\r\nprotected:\r\n    vtstream    _vtstream;\r\n    idstream    _idstream;\r\n    int         _faces;\r\n};\r\n\r\n__ariel_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "e8c89cc4c5187555153d8d32c6b0bc348d77d72f", "size": 2858, "ext": "h", "lang": "C", "max_stars_repo_path": "include/ariel/polygon.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/ariel/polygon.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ariel/polygon.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 39.1506849315, "max_line_length": 103, "alphanum_fraction": 0.7155353394, "num_tokens": 716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552953503957277, "lm_q2_score": 0.04272219815590353, "lm_q1q2_score": 0.019034001080268193}}
{"text": "#ifndef OPENMC_CELL_H\n#define OPENMC_CELL_H\n\n#include <cstdint>\n#include <functional> // for hash\n#include <limits>\n#include <memory> // for unique_ptr\n#include <string>\n#include <unordered_map>\n#include <vector>\n\n#include <gsl/gsl>\n#include \"hdf5.h\"\n#include \"pugixml.hpp\"\n#include \"dagmc.h\"\n\n#include \"openmc/constants.h\"\n#include \"openmc/neighbor_list.h\"\n#include \"openmc/position.h\"\n#include \"openmc/surface.h\"\n\nnamespace openmc {\n\n//==============================================================================\n// Constants\n//==============================================================================\n\nenum class Fill {\n  MATERIAL,\n  UNIVERSE,\n  LATTICE\n};\n\n// TODO: Convert to enum\nconstexpr int32_t OP_LEFT_PAREN   {std::numeric_limits<int32_t>::max()};\nconstexpr int32_t OP_RIGHT_PAREN  {std::numeric_limits<int32_t>::max() - 1};\nconstexpr int32_t OP_COMPLEMENT   {std::numeric_limits<int32_t>::max() - 2};\nconstexpr int32_t OP_INTERSECTION {std::numeric_limits<int32_t>::max() - 3};\nconstexpr int32_t OP_UNION        {std::numeric_limits<int32_t>::max() - 4};\n\n//==============================================================================\n// Global variables\n//==============================================================================\n\nclass Cell;\nclass ParentCell;\nclass CellInstance;\nclass Universe;\nclass UniversePartitioner;\n\nnamespace model {\n  extern std::unordered_map<int32_t, int32_t> cell_map;\n  extern std::vector<std::unique_ptr<Cell>> cells;\n\n  extern std::unordered_map<int32_t, int32_t> universe_map;\n  extern std::vector<std::unique_ptr<Universe>> universes;\n} // namespace model\n\n//==============================================================================\n//! A geometry primitive that fills all space and contains cells.\n//==============================================================================\n\nclass Universe\n{\npublic:\n  int32_t id_;                  //!< Unique ID\n  std::vector<int32_t> cells_;  //!< Cells within this universe\n\n  //! \\brief Write universe information to an HDF5 group.\n  //! \\param group_id An HDF5 group id.\n  void to_hdf5(hid_t group_id) const;\n\n  BoundingBox bounding_box() const;\n\n  std::unique_ptr<UniversePartitioner> partitioner_;\n};\n\n//==============================================================================\n//==============================================================================\n\nclass Cell {\npublic:\n  //----------------------------------------------------------------------------\n  // Constructors, destructors, factory functions\n\n  explicit Cell(pugi::xml_node cell_node);\n  Cell() {};\n  virtual ~Cell() = default;\n\n  //----------------------------------------------------------------------------\n  // Methods\n\n  //! \\brief Determine if a cell contains the particle at a given location.\n  //!\n  //! The bounds of the cell are detemined by a logical expression involving\n  //! surface half-spaces. At initialization, the expression was converted\n  //! to RPN notation.\n  //!\n  //! The function is split into two cases, one for simple cells (those\n  //! involving only the intersection of half-spaces) and one for complex cells.\n  //! Simple cells can be evaluated with short circuit evaluation, i.e., as soon\n  //! as we know that one half-space is not satisfied, we can exit. This\n  //! provides a performance benefit for the common case. In\n  //! contains_complex, we evaluate the RPN expression using a stack, similar to\n  //! how a RPN calculator would work.\n  //! \\param r The 3D Cartesian coordinate to check.\n  //! \\param u A direction used to \"break ties\" the coordinates are very\n  //!   close to a surface.\n  //! \\param on_surface The signed index of a surface that the coordinate is\n  //!   known to be on.  This index takes precedence over surface sense\n  //!   calculations.\n  virtual bool\n  contains(Position r, Direction u, int32_t on_surface) const = 0;\n\n  //! Find the oncoming boundary of this cell.\n  virtual std::pair<double, int32_t>\n  distance(Position r, Direction u, int32_t on_surface, Particle* p) const = 0;\n\n  //! Write all information needed to reconstruct the cell to an HDF5 group.\n  //! \\param group_id An HDF5 group id.\n  virtual void to_hdf5(hid_t group_id) const = 0;\n\n  //! Get the BoundingBox for this cell.\n  virtual BoundingBox bounding_box() const = 0;\n\n  //----------------------------------------------------------------------------\n  // Accessors\n\n  //! Get the temperature of a cell instance\n  //! \\param[in] instance Instance index. If -1 is given, the temperature for\n  //!   the first instance is returned.\n  //! \\return Temperature in [K]\n  double temperature(int32_t instance = -1) const;\n\n  //! Set the temperature of a cell instance\n  //! \\param[in] T Temperature in [K]\n  //! \\param[in] instance Instance index. If -1 is given, the temperature for\n  //!   all instances is set.\n  //! \\param[in] set_contained If this cell is not filled with a material,\n  //!   collect all contained cells with material fills and set their\n  //!   temperatures.\n  void set_temperature(double T, int32_t instance = -1, bool set_contained = false);\n\n  //! Get the name of a cell\n  //! \\return Cell name\n  const std::string& name() const { return name_; };\n\n  //! Set the temperature of a cell instance\n  //! \\param[in] name Cell name\n  void set_name(const std::string& name) { name_ = name; };\n\n  //! Get all cell instances contained by this cell\n  //! \\return Map with cell indexes as keys and instances as values\n  std::unordered_map<int32_t, std::vector<int32_t>>\n  get_contained_cells() const;\n\nprotected:\n  void\n  get_contained_cells_inner(std::unordered_map<int32_t, std::vector<int32_t>>& contained_cells,\n                            std::vector<ParentCell>& parent_cells) const;\n\npublic:\n  //----------------------------------------------------------------------------\n  // Data members\n\n  int32_t id_;                //!< Unique ID\n  std::string name_;          //!< User-defined name\n  Fill type_;                  //!< Material, universe, or lattice\n  int32_t universe_;          //!< Universe # this cell is in\n  int32_t fill_;              //!< Universe # filling this cell\n  int32_t n_instances_{0};    //!< Number of instances of this cell\n\n  //! \\brief Index corresponding to this cell in distribcell arrays\n  int distribcell_index_{C_NONE};\n\n  //! \\brief Material(s) within this cell.\n  //!\n  //! May be multiple materials for distribcell.\n  std::vector<int32_t> material_;\n\n  //! \\brief Temperature(s) within this cell.\n  //!\n  //! The stored values are actually sqrt(k_Boltzmann * T) for each temperature\n  //! T. The units are sqrt(eV).\n  std::vector<double> sqrtkT_;\n\n  //! Definition of spatial region as Boolean expression of half-spaces\n  std::vector<std::int32_t> region_;\n  //! Reverse Polish notation for region expression\n  std::vector<std::int32_t> rpn_;\n  bool simple_;  //!< Does the region contain only intersections?\n\n  //! \\brief Neighboring cells in the same universe.\n  NeighborList neighbors_;\n\n  Position translation_ {0, 0, 0}; //!< Translation vector for filled universe\n\n  //! \\brief Rotational tranfsormation of the filled universe.\n  //\n  //! The vector is empty if there is no rotation. Otherwise, the first 9 values\n  //! give the rotation matrix in row-major order. When the user specifies\n  //! rotation angles about the x-, y- and z- axes in degrees, these values are\n  //! also present at the end of the vector, making it of length 12.\n  std::vector<double> rotation_;\n\n  std::vector<int32_t> offset_;  //!< Distribcell offset table\n};\n\nstruct CellInstanceItem {\n  int32_t index {-1};        //! Index into global cells array\n  int     lattice_indx{-1};  //! Flat index value of the lattice cell\n};\n\n//==============================================================================\n\nclass CSGCell : public Cell\n{\npublic:\n  CSGCell();\n\n  explicit CSGCell(pugi::xml_node cell_node);\n\n  bool\n  contains(Position r, Direction u, int32_t on_surface) const;\n\n  std::pair<double, int32_t>\n  distance(Position r, Direction u, int32_t on_surface, Particle* p) const;\n\n  void to_hdf5(hid_t group_id) const;\n\n  BoundingBox bounding_box() const;\n\nprotected:\n  bool contains_simple(Position r, Direction u, int32_t on_surface) const;\n  bool contains_complex(Position r, Direction u, int32_t on_surface) const;\n  BoundingBox bounding_box_simple() const;\n  static BoundingBox bounding_box_complex(std::vector<int32_t> rpn);\n\n  //! Applies DeMorgan's laws to a section of the RPN\n  //! \\param start Starting point for token modification\n  //! \\param stop Stopping point for token modification\n  static void apply_demorgan(std::vector<int32_t>::iterator start,\n                             std::vector<int32_t>::iterator stop);\n\n  //! Removes complement operators from the RPN\n  //! \\param rpn The rpn to remove complement operators from.\n  static void remove_complement_ops(std::vector<int32_t>& rpn);\n\n  //! Returns the beginning position of a parenthesis block (immediately before\n  //! two surface tokens) in the RPN given a starting position at the end of\n  //! that block (immediately after two surface tokens)\n  //! \\param start Starting position of the search\n  //! \\param rpn The rpn being searched\n  static std::vector<int32_t>::iterator\n  find_left_parenthesis(std::vector<int32_t>::iterator start,\n                        const std::vector<int32_t>& rpn);\n\n};\n\n//==============================================================================\n\n#ifdef DAGMC\nclass DAGCell : public Cell\n{\npublic:\n  DAGCell();\n\n  bool contains(Position r, Direction u, int32_t on_surface) const;\n\n  std::pair<double, int32_t>\n  distance(Position r, Direction u, int32_t on_surface, Particle* p) const;\n\n  BoundingBox bounding_box() const;\n\n  void to_hdf5(hid_t group_id) const;\n\n  moab::DagMC* dagmc_ptr_; //!< Pointer to DagMC instance\n  int32_t dag_index_;      //!< DagMC index of cell\n};\n#endif\n\n//==============================================================================\n//! Speeds up geometry searches by grouping cells in a search tree.\n//\n//! Currently this object only works with universes that are divided up by a\n//! bunch of z-planes.  It could be generalized to other planes, cylinders,\n//! and spheres.\n//==============================================================================\n\nclass UniversePartitioner\n{\npublic:\n  explicit UniversePartitioner(const Universe& univ);\n\n  //! Return the list of cells that could contain the given coordinates.\n  const std::vector<int32_t>& get_cells(Position r, Direction u) const;\n\nprivate:\n  //! A sorted vector of indices to surfaces that partition the universe\n  std::vector<int32_t> surfs_;\n\n  //! Vectors listing the indices of the cells that lie within each partition\n  //\n  //! There are n+1 partitions with n surfaces.  `partitions_.front()` gives the\n  //! cells that lie on the negative side of `surfs_.front()`.\n  //! `partitions_.back()` gives the cells that lie on the positive side of\n  //! `surfs_.back()`.  Otherwise, `partitions_[i]` gives cells sandwiched\n  //! between `surfs_[i-1]` and `surfs_[i]`.\n  std::vector<std::vector<int32_t>> partitions_;\n};\n\n\n//==============================================================================\n//! Define a containing (parent) cell\n//==============================================================================\n\nstruct ParentCell {\n  gsl::index cell_index;\n  gsl::index lattice_index;\n};\n\n//==============================================================================\n//! Define an instance of a particular cell\n//==============================================================================\n\nstruct CellInstance {\n  //! Check for equality\n  bool operator==(const CellInstance& other) const\n  { return index_cell == other.index_cell && instance == other.instance; }\n\n  gsl::index index_cell;\n  gsl::index instance;\n};\n\nstruct CellInstanceHash {\n  std::size_t operator()(const CellInstance& k) const\n  {\n    return 4096*k.index_cell + k.instance;\n  }\n};\n\n//==============================================================================\n// Non-member functions\n//==============================================================================\n\nvoid read_cells(pugi::xml_node node);\n\n#ifdef DAGMC\nint32_t next_cell(DAGCell* cur_cell, DAGSurface* surf_xed);\n#endif\n\n} // namespace openmc\n#endif // OPENMC_CELL_H\n", "meta": {"hexsha": "5cd819c26ce2003401f2d5352c84e2e1d5cb9c8c", "size": 12288, "ext": "h", "lang": "C", "max_stars_repo_path": "include/openmc/cell.h", "max_stars_repo_name": "Hit-Weixg/openmc", "max_stars_repo_head_hexsha": "c5f66a3af5c1a57087e330f7b870e89a82267e4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-01-10T13:14:35.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-05T10:18:12.000Z", "max_issues_repo_path": "include/openmc/cell.h", "max_issues_repo_name": "sinkaa-ife/openmc", "max_issues_repo_head_hexsha": "fe12fb1e96253cf9f0e65fbdc021bf65bb8918bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-03-14T12:18:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-01T15:23:23.000Z", "max_forks_repo_path": "include/openmc/cell.h", "max_forks_repo_name": "sinkaa-ife/openmc", "max_forks_repo_head_hexsha": "fe12fb1e96253cf9f0e65fbdc021bf65bb8918bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-07-31T21:03:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-22T20:54:48.000Z", "avg_line_length": 34.7118644068, "max_line_length": 95, "alphanum_fraction": 0.6053059896, "num_tokens": 2689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782348444346736, "lm_q2_score": 0.0433657947457516, "lm_q1q2_score": 0.018986563361245174}}
{"text": "/* randist/gsl-randist.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 James Theiler, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <string.h>\n\n#include <gsl/gsl_randist.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_test.h>\n\nvoid error (const char * s);\n\n\nint\nmain (int argc, char *argv[])\n{\n  size_t i,j;\n  size_t n = 0;\n  double mu = 0, nu = 0, nu1 = 0, nu2 = 0, sigma = 0, a = 0, b = 0, c = 0;\n  double zeta = 0, sigmax = 0, sigmay = 0, rho = 0;\n  double p = 0;\n  double x = 0, y =0, z=0  ;\n  unsigned int N = 0, t = 0, n1 = 0, n2 = 0 ;\n  unsigned long int seed = 0 ;\n  const char * name ;\n  gsl_rng * r ;\n\n  if (argc < 4) \n    {\n      printf (\n\"Usage: gsl-randist seed n DIST param1 param2 ...\\n\"\n\"Generates n samples from the distribution DIST with parameters param1,\\n\"\n\"param2, etc. Valid distributions are,\\n\\n\");\n\n      printf(\n\"  beta\\n\"\n\"  binomial\\n\"\n\"  bivariate-gaussian\\n\"\n\"  cauchy\\n\"\n\"  chisq\\n\"\n\"  dir-2d\\n\"\n\"  dir-3d\\n\"\n\"  dir-nd\\n\"\n\"  erlang\\n\"\n\"  exponential\\n\"\n\"  exppow\\n\"\n\"  fdist\\n\"\n\"  flat\\n\"\n\"  gamma\\n\"\n\"  gaussian-tail\\n\"\n\"  gaussian\\n\"\n\"  geometric\\n\"\n\"  gumbel1\\n\"\n\"  gumbel2\\n\"\n\"  hypergeometric\\n\"\n\"  laplace\\n\"\n\"  landau\\n\"\n\"  levy\\n\"\n\"  levy-skew\\n\"\n\"  logarithmic\\n\"\n\"  logistic\\n\"\n\"  lognormal\\n\"\n\"  negative-binomial\\n\"\n\"  pareto\\n\"\n\"  pascal\\n\"\n\"  poisson\\n\"\n\"  rayleigh-tail\\n\"\n\"  rayleigh\\n\"\n\"  tdist\\n\"\n\"  ugaussian-tail\\n\"\n\"  ugaussian\\n\"\n\"  weibull\\n\") ;\n      exit (0);\n    }\n\n  argv++ ; seed = atol (argv[0]); argc-- ;\n  argv++ ; n = atol (argv[0]); argc-- ;\n  argv++ ; name = argv[0] ; argc-- ; argc-- ;\n\n  gsl_rng_env_setup() ;\n\n  if (gsl_rng_default_seed != 0) {\n    fprintf(stderr, \n            \"overriding GSL_RNG_SEED with command line value, seed = %ld\\n\", \n            seed) ;\n  }\n  \n  gsl_rng_default_seed = seed ;\n\n  r = gsl_rng_alloc(gsl_rng_default) ;\n\n\n#define NAME(x) !strcmp(name,(x))\n#define OUTPUT(x) for (i = 0; i < n; i++) { printf(\"%g\\n\", (x)) ; }\n#define OUTPUT1(a,x) for(i = 0; i < n; i++) { a ; printf(\"%g\\n\", x) ; }\n#define OUTPUT2(a,x,y) for(i = 0; i < n; i++) { a ; printf(\"%g %g\\n\", x, y) ; }\n#define OUTPUT3(a,x,y,z) for(i = 0; i < n; i++) { a ; printf(\"%g %g %g\\n\", x, y, z) ; }\n#define INT_OUTPUT(x) for (i = 0; i < n; i++) { printf(\"%d\\n\", (x)) ; }\n#define ARGS(x,y) if (argc != x) error(y) ;\n#define DBL_ARG(x) if (argc) { x=atof((++argv)[0]);argc--;} else {error( #x);};\n#define INT_ARG(x) if (argc) { x=atoi((++argv)[0]);argc--;} else {error( #x);};\n\n  if (NAME(\"bernoulli\"))\n    {\n      ARGS(1, \"p = probability of success\");\n      DBL_ARG(p)\n      INT_OUTPUT(gsl_ran_bernoulli (r, p));\n    }\n  else if (NAME(\"beta\"))\n    {\n      ARGS(2, \"a,b = shape parameters\");\n      DBL_ARG(a)\n      DBL_ARG(b)\n      OUTPUT(gsl_ran_beta (r, a, b));\n    }\n  else if (NAME(\"binomial\"))\n    {\n      ARGS(2, \"p = probability, N = number of trials\");\n      DBL_ARG(p)\n      INT_ARG(N)\n      INT_OUTPUT(gsl_ran_binomial (r, p, N));\n    }\n  else if (NAME(\"cauchy\"))\n    {\n      ARGS(1, \"a = scale parameter\");\n      DBL_ARG(a)\n      OUTPUT(gsl_ran_cauchy (r, a));\n    }\n  else if (NAME(\"chisq\"))\n    {\n      ARGS(1, \"nu = degrees of freedom\");\n      DBL_ARG(nu)\n      OUTPUT(gsl_ran_chisq (r, nu));\n    }\n  else if (NAME(\"erlang\"))\n    {\n      ARGS(2, \"a = scale parameter, b = order\");\n      DBL_ARG(a)\n      DBL_ARG(b)\n      OUTPUT(gsl_ran_erlang (r, a, b));\n    }\n  else if (NAME(\"exponential\"))\n    {\n      ARGS(1, \"mu = mean value\");\n      DBL_ARG(mu) ;\n      OUTPUT(gsl_ran_exponential (r, mu));\n    }\n  else if (NAME(\"exppow\"))\n    {\n      ARGS(2, \"a = scale parameter, b = power (1=exponential, 2=gaussian)\");\n      DBL_ARG(a) ;\n      DBL_ARG(b) ;\n      OUTPUT(gsl_ran_exppow (r, a, b));\n    }\n  else if (NAME(\"fdist\"))\n    {\n      ARGS(2, \"nu1, nu2 = degrees of freedom parameters\");\n      DBL_ARG(nu1) ;\n      DBL_ARG(nu2) ;\n      OUTPUT(gsl_ran_fdist (r, nu1, nu2));\n    }\n  else if (NAME(\"flat\"))\n    {\n      ARGS(2, \"a = lower limit, b = upper limit\");\n      DBL_ARG(a) ;\n      DBL_ARG(b) ;\n      OUTPUT(gsl_ran_flat (r, a, b));\n    }\n  else if (NAME(\"gamma\"))\n    {\n      ARGS(2, \"a = order, b = scale\");\n      DBL_ARG(a) ;\n      DBL_ARG(b) ;\n      OUTPUT(gsl_ran_gamma (r, a, b));\n    }\n  else if (NAME(\"gaussian\"))\n    {\n      ARGS(1, \"sigma = standard deviation\");\n      DBL_ARG(sigma) ;\n      OUTPUT(gsl_ran_gaussian (r, sigma));\n    }\n  else if (NAME(\"gaussian-tail\"))\n    {\n      ARGS(2, \"a = lower limit, sigma = standard deviation\");\n      DBL_ARG(a) ;\n      DBL_ARG(sigma) ;\n      OUTPUT(gsl_ran_gaussian_tail (r, a, sigma));\n    }\n  else if (NAME(\"ugaussian\"))\n    {\n      ARGS(0, \"unit gaussian, no parameters required\");\n      OUTPUT(gsl_ran_ugaussian (r));\n    }\n  else if (NAME(\"ugaussian-tail\"))\n    {\n      ARGS(1, \"a = lower limit\");\n      DBL_ARG(a) ;\n      OUTPUT(gsl_ran_ugaussian_tail (r, a));\n    }\n  else if (NAME(\"bivariate-gaussian\"))\n    {\n      ARGS(3, \"sigmax = x std.dev., sigmay = y std.dev., rho = correlation\");\n      DBL_ARG(sigmax) ;\n      DBL_ARG(sigmay) ;\n      DBL_ARG(rho) ;\n      OUTPUT2(gsl_ran_bivariate_gaussian (r, sigmax, sigmay, rho, &x, &y), \n              x, y);\n    }\n  else if (NAME(\"dir-2d\"))\n    {\n      OUTPUT2(gsl_ran_dir_2d (r, &x, &y), x, y);\n    }\n  else if (NAME(\"dir-3d\"))\n    {\n      OUTPUT3(gsl_ran_dir_3d (r, &x, &y, &z), x, y, z);\n    }\n  else if (NAME(\"dir-nd\"))\n    {\n      double *xarr;  \n      ARGS(1, \"n1 = number of dimensions of hypersphere\"); \n      INT_ARG(n1) ;\n      xarr = (double *)malloc(n1*sizeof(double));\n\n      for(i = 0; i < n; i++) { \n        gsl_ran_dir_nd (r, n1, xarr) ; \n        for (j = 0; j < n1; j++) { \n          if (j) putchar(' '); \n          printf(\"%g\", xarr[j]) ; \n        } \n        putchar('\\n'); \n      } ;\n\n      free(xarr);\n    }  \n  else if (NAME(\"geometric\"))\n    {\n      ARGS(1, \"p = bernoulli trial probability of success\");\n      DBL_ARG(p) ;\n      INT_OUTPUT(gsl_ran_geometric (r, p));\n    }\n  else if (NAME(\"gumbel1\"))\n    {\n      ARGS(2, \"a = order, b = scale parameter\");\n      DBL_ARG(a) ;\n      DBL_ARG(b) ;\n      OUTPUT(gsl_ran_gumbel1 (r, a, b));\n    }\n  else if (NAME(\"gumbel2\"))\n    {\n      ARGS(2, \"a = order, b = scale parameter\");\n      DBL_ARG(a) ;\n      DBL_ARG(b) ;\n      OUTPUT(gsl_ran_gumbel2 (r, a, b));\n    }\n  else if (NAME(\"hypergeometric\"))\n    {\n      ARGS(3, \"n1 = tagged population, n2 = untagged population, t = number of trials\");\n      INT_ARG(n1) ;\n      INT_ARG(n2) ;\n      INT_ARG(t) ;\n      INT_OUTPUT(gsl_ran_hypergeometric (r, n1, n2, t));\n    }\n  else if (NAME(\"laplace\"))\n    {\n      ARGS(1, \"a = scale parameter\");\n      DBL_ARG(a) ;\n      OUTPUT(gsl_ran_laplace (r, a));\n    }\n  else if (NAME(\"landau\"))\n    {\n      ARGS(0, \"no arguments required\");\n      OUTPUT(gsl_ran_landau (r));\n    }\n  else if (NAME(\"levy\"))\n    {\n      ARGS(2, \"c = scale, a = power (1=cauchy, 2=gaussian)\");\n      DBL_ARG(c) ;\n      DBL_ARG(a) ;\n      OUTPUT(gsl_ran_levy (r, c, a));\n    }\n  else if (NAME(\"levy-skew\"))\n    {\n      ARGS(3, \"c = scale, a = power (1=cauchy, 2=gaussian), b = skew\");\n      DBL_ARG(c) ;\n      DBL_ARG(a) ;\n      DBL_ARG(b) ;\n      OUTPUT(gsl_ran_levy_skew (r, c, a, b));\n    }\n  else if (NAME(\"logarithmic\"))\n    {\n      ARGS(1, \"p = probability\");\n      DBL_ARG(p) ;\n      INT_OUTPUT(gsl_ran_logarithmic (r, p));\n    }\n  else if (NAME(\"logistic\"))\n    {\n      ARGS(1, \"a = scale parameter\");\n      DBL_ARG(a) ;\n      OUTPUT(gsl_ran_logistic (r, a));\n    }\n  else if (NAME(\"lognormal\"))\n    {\n      ARGS(2, \"zeta = location parameter, sigma = scale parameter\");\n      DBL_ARG(zeta) ;\n      DBL_ARG(sigma) ;\n      OUTPUT(gsl_ran_lognormal (r, zeta, sigma));\n    }\n  else if (NAME(\"negative-binomial\"))\n    {\n      ARGS(2, \"p = probability, a = order\");\n      DBL_ARG(p) ;\n      DBL_ARG(a) ;\n      INT_OUTPUT(gsl_ran_negative_binomial (r, p, a));\n    }\n  else if (NAME(\"pareto\"))\n    {\n      ARGS(2, \"a = power, b = scale parameter\");\n      DBL_ARG(a) ;\n      DBL_ARG(b) ;\n      OUTPUT(gsl_ran_pareto (r, a, b));\n    }\n  else if (NAME(\"pascal\"))\n    {\n      ARGS(2, \"p = probability, n = order (integer)\");\n      DBL_ARG(p) ;\n      INT_ARG(N) ;\n      INT_OUTPUT(gsl_ran_pascal (r, p, N));\n    }\n  else if (NAME(\"poisson\"))\n    {\n      ARGS(1, \"mu = scale parameter\");\n      DBL_ARG(mu) ;\n      INT_OUTPUT(gsl_ran_poisson (r, mu));\n    }\n  else if (NAME(\"rayleigh\"))\n    {\n      ARGS(1, \"sigma = scale parameter\");\n      DBL_ARG(sigma) ;\n      OUTPUT(gsl_ran_rayleigh (r, sigma));\n    }\n  else if (NAME(\"rayleigh-tail\"))\n    {\n      ARGS(2, \"a = lower limit, sigma = scale parameter\");\n      DBL_ARG(a) ;\n      DBL_ARG(sigma) ;\n      OUTPUT(gsl_ran_rayleigh_tail (r, a, sigma));\n    }\n  else if (NAME(\"tdist\"))\n    {\n      ARGS(1, \"nu = degrees of freedom\");\n      DBL_ARG(nu) ;\n      OUTPUT(gsl_ran_tdist (r, nu));\n    }\n  else if (NAME(\"weibull\"))\n    {\n      ARGS(2, \"a = scale parameter, b = exponent\");\n      DBL_ARG(a) ;\n      DBL_ARG(b) ;\n      OUTPUT(gsl_ran_weibull (r, a, b));\n    }\n  else\n    {\n      fprintf(stderr,\"Error: unrecognized distribution: %s\\n\", name) ;\n    }\n\n  return 0 ;\n}\n\n\nvoid\nerror (const char * s)\n{\n  fprintf(stderr, \"Error: arguments should be %s\\n\",s) ;\n  exit (EXIT_FAILURE) ;\n}\n", "meta": {"hexsha": "aec5e7d0a18746d6a2a1236b7146e4bea48f57aa", "size": 9927, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/gsl-randist.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/gsl-randist.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/gsl-randist.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 25.1316455696, "max_line_length": 88, "alphanum_fraction": 0.5476981968, "num_tokens": 3357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.457136702035843, "lm_q2_score": 0.04146226812171165, "lm_q1q2_score": 0.01895392450808513}}
{"text": "/*\n * C version of Diffusive Nested Sampling (DNest4) by Brendon J. Brewer\n *\n * Yan-Rong Li, liyanrong@mail.ihep.ac.cn\n * Jun 30, 2016\n *\n */\n\n#ifndef _MODEL3_H\n#define _MODEL3_H\n\n#include <stdbool.h>\n#include <gsl/gsl_rng.h>\n\n/* number of model parameters */\nextern int num_params;\n\nextern int which_particle_update; // which particule to be updated\nextern int which_level_update;\nextern double *limits;\nextern int thistask, totaltask;\n\nextern DNestFptrSet *fptrset_thismodel3;\n\n/* functions */\nvoid from_prior_thismodel3(void *model);\nvoid print_particle_thismodel3(FILE *fp, const void *model);\ndouble log_likelihoods_cal_thismodel3(const void *model);\ndouble perturb_thismodel3(void *model);\nvoid restart_action_model3(int iflag);\n\n#endif\n", "meta": {"hexsha": "67f6a5a09c1d9b9f66fad0270a2f6f288759afec", "size": 744, "ext": "h", "lang": "C", "max_stars_repo_path": "src/model3.h", "max_stars_repo_name": "LiyrAstroph/CDNest", "max_stars_repo_head_hexsha": "afb6b869ce1c4ebd76662b20310f1d9d3db4e26e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-09-11T03:34:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-16T12:14:05.000Z", "max_issues_repo_path": "src/model3.h", "max_issues_repo_name": "LiyrAstroph/DNest_C", "max_issues_repo_head_hexsha": "afb6b869ce1c4ebd76662b20310f1d9d3db4e26e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-05-14T10:04:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-06T02:04:19.000Z", "max_forks_repo_path": "src/model3.h", "max_forks_repo_name": "LiyrAstroph/DNest_C", "max_forks_repo_head_hexsha": "afb6b869ce1c4ebd76662b20310f1d9d3db4e26e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5454545455, "max_line_length": 71, "alphanum_fraction": 0.7715053763, "num_tokens": 196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.43014736319616964, "lm_q2_score": 0.04401865080353022, "lm_q1q2_score": 0.01893450657459148}}
{"text": "#ifndef I3SPRNGRANDOMSERVICE_H\n#define I3SPRNGRANDOMSERVICE_H\n\n#include \"phys-services/I3RandomService.h\"\n\n#include <gsl/gsl_randist.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_test.h>\n\n#include <string>\n\n\n/**\n * copyright  (C) 2004\n * the icecube collaboration\n * $Id: I3SPRNGRandomService.h 127790 2015-01-14 04:03:06Z olivas $\n *\n * @brief SPRNG Implementation of the I3RandomService interface.\n * This implementation uses a combination of SPRNG and GSL to generate\n * statistically independent streams of pseudo-random number distributions.\n * See gsl-sprng.h for more details.\n *\n * NB : It's important that you use the same seed for different jobs.  Set\n * nstreams to the number of jobs and use a different streamnum for each job.\n * Otherwise you'll get correlations between the RNG streams.  I know this is\n * counterintuitive, but this is how SPRNG works.\n * \n * The code for this class is based on John Pretz's implementation of\n * I3GSLRandomService.\n *\n * @version $Revision: 127790 $\n * @date $Date: 2015-01-13 21:03:06 -0700 (Tue, 13 Jan 2015) $\n * @author juancarlos\n *\n * @todo Add ability to save state of rng after run is complete\n *  SPRNG has the functions:\n *\n *      int pack_sprng(char *bytes); // returns size of bytes\n *      void unpack_sprng(char bytes[MAX_PACKED_LENGTH]);\n *\n *  which can be used to save and retrieve the state of an rng\n */\n\nclass I3SPRNGRandomService : public I3RandomService{\n public:\n  /**\n   * default constructor\n   */\n  I3SPRNGRandomService();\n\n  /**\n   * constructors\n   */\n  I3SPRNGRandomService(int seed, int nstreams, int streamnum,\n\t\t       std::string instatefile=std::string(),\n\t\t       std::string outstatefile=std::string());\n\n  /**\n   * destructor\n   */\n  virtual ~I3SPRNGRandomService();\n\n  /**\n   * Binomial distribution\n   */\n  virtual int Binomial(int ntot, double prob);\n\n  // As with John Pretz's GSL implementation, I have left this out for now.\n  /* virtual double BreitWigner(double mean = 0, double gamma = 1)=0; */\n  \n  /**\n   * Exponential distribution\n   */\n  virtual double Exp(double tau);\n\n  /**\n   * Uniform int distribution with range [0,imax)\n   */\n  virtual unsigned int Integer(unsigned int imax);\n\n  /**\n   * int Poisson distribution\n   */\n  virtual int Poisson(double mean);\n\n  /**\n   * double Poisson distribution\n   */\n  virtual double PoissonD(double mean);\n\n  /**\n   * double uniform distribution with range (0,x1)\n   */\n  virtual double Uniform(double x1 = 1);\n\n  /**\n   * double  uniform distribution with range (x1,x2)\n   */\n  virtual double Uniform(double x1, double x2);\n\n  /**\n   * double Gaussian distribution given mean and StdD\n   */\n  virtual double Gaus(double mean, double stddev);\n   \n  virtual I3FrameObjectPtr GetState() const;\n  virtual void RestoreState(I3FrameObjectConstPtr state);\n\n private:\n\n  // private copy constructors and assignment\n  I3SPRNGRandomService(const I3SPRNGRandomService& );\n  I3SPRNGRandomService operator=(const I3SPRNGRandomService& );\n\n  gsl_rng* rng_;\n  std::string instatefile_;\n  std::string outstatefile_;\n  \n  int seed_;\n  int streamnum_;\n  int nstreams_;\n\n  SET_LOGGER(\"I3SPRNGRandomService\");\n\n};\n\nI3_POINTER_TYPEDEFS(I3SPRNGRandomService);\n\n#endif // I3SPRNGRANDOMSERVICE_H\n", "meta": {"hexsha": "9a0cb07bd168dceebc58864e933de1a5c829429e", "size": 3217, "ext": "h", "lang": "C", "max_stars_repo_path": "phys-services/public/phys-services/I3SPRNGRandomService.h", "max_stars_repo_name": "hschwane/offline_production", "max_stars_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-24T22:00:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-24T22:00:01.000Z", "max_issues_repo_path": "phys-services/public/phys-services/I3SPRNGRandomService.h", "max_issues_repo_name": "hschwane/offline_production", "max_issues_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "phys-services/public/phys-services/I3SPRNGRandomService.h", "max_forks_repo_name": "hschwane/offline_production", "max_forks_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-07-17T09:20:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-30T16:44:18.000Z", "avg_line_length": 24.7461538462, "max_line_length": 77, "alphanum_fraction": 0.70562636, "num_tokens": 865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.03963884051909871, "lm_q1q2_score": 0.01889106478316076}}
{"text": "/* ieee-utils/fp-os2.c\n * \n * Copyright (C) 2001 Henry Sobotka <sobotka@axess.com>\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <float.h>\n#include <gsl/gsl_ieee_utils.h>\n#include <gsl/gsl_errno.h>\n\nint\ngsl_ieee_set_mode (int precision, int rounding, int exception_mask)\n{\n  unsigned mode = 0;\n\n  switch (precision)\n    {\n    case GSL_IEEE_SINGLE_PRECISION:\n      _control87(PC_24, MCW_PC);    \n      break ;\n    case GSL_IEEE_DOUBLE_PRECISION:\n      _control87(PC_53, MCW_PC);\n      break ;\n    case GSL_IEEE_EXTENDED_PRECISION:\n      _control87(PC_64, MCW_PC);\n      break ;\n    }\n\n  switch (rounding)\n    {\n    case GSL_IEEE_ROUND_TO_NEAREST:\n      _control87(RC_NEAR, MCW_RC);\n      break ;\n    case GSL_IEEE_ROUND_DOWN:\n      _control87(RC_DOWN, MCW_RC);\n      break ;\n    case GSL_IEEE_ROUND_UP:\n      _control87(RC_UP, MCW_RC);\n      break ;\n    case GSL_IEEE_ROUND_TO_ZERO:\n      _control87(RC_CHOP, MCW_RC);\n      break ;\n    default:\n      _control87(RC_NEAR, MCW_RC);\n    }\n\n  /* Turn on all the exceptions apart from 'inexact' */\n\n  mode = EM_INVALID | EM_DENORMAL | EM_ZERODIVIDE | EM_OVERFLOW | EM_UNDERFLOW;\n\n  if (exception_mask & GSL_IEEE_MASK_INVALID)\n    mode &= ~ EM_INVALID;\n\n  if (exception_mask & GSL_IEEE_MASK_DENORMALIZED)\n    mode &= ~ EM_DENORMAL;\n\n  if (exception_mask & GSL_IEEE_MASK_DIVISION_BY_ZERO)\n    mode &= ~ EM_ZERODIVIDE;\n\n  if (exception_mask & GSL_IEEE_MASK_OVERFLOW)\n    mode &= ~ EM_OVERFLOW;\n\n  if (exception_mask & GSL_IEEE_MASK_UNDERFLOW)\n    mode &= ~ EM_UNDERFLOW;\n\n  if (exception_mask & GSL_IEEE_TRAP_INEXACT)\n    {\n      mode |= EM_INEXACT;\n    }\n  else\n    {\n      mode &= ~ EM_INEXACT;\n    }\n\n  _control87(mode, MCW_EM);\n\n  return GSL_SUCCESS ;\n}\n", "meta": {"hexsha": "8c41a50aff9ac15a22bd8b7c6775b2e27f120f0b", "size": 2391, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/ieee-utils/fp-os2emx.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/ieee-utils/fp-os2emx.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/ieee-utils/fp-os2emx.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 25.9891304348, "max_line_length": 81, "alphanum_fraction": 0.6896695943, "num_tokens": 657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40733340004593027, "lm_q2_score": 0.04603389732778596, "lm_q1q2_score": 0.018751143915892318}}
{"text": "/* gsl_histogram2d_calloc_range.c\n * Copyright (C) 2000  Simone Piccardi\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU General Public License as\n * published by the Free Software Foundation; either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this library; if not, write to the Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n/***************************************************************\n *\n * File gsl_histogram2d_calloc_range.c: \n * Routine to create a variable binning 2D histogram providing \n * the input range vectors. Need GSL library and header.\n * Do range check and allocate the histogram data. \n *\n * Author: S. Piccardi\n * Jan. 2000\n *\n ***************************************************************/\n#include <config.h>\n#include <stdlib.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_histogram2d.h>\n/*\n * Routine that create a 2D histogram using the given \n * values for X and Y ranges\n */\ngsl_histogram2d *\ngsl_histogram2d_calloc_range (size_t nx, size_t ny,\n                              double *xrange,\n                              double *yrange)\n{\n  size_t i, j;\n  gsl_histogram2d *h;\n\n  /* check arguments */\n\n  if (nx == 0)\n    {\n      GSL_ERROR_VAL (\"histogram length nx must be positive integer\",\n                        GSL_EDOM, 0);\n    }\n\n  if (ny == 0)\n    {\n      GSL_ERROR_VAL (\"histogram length ny must be positive integer\",\n                        GSL_EDOM, 0);\n    }\n\n  /* init ranges */\n\n  for (i = 0; i < nx; i++)\n    {\n      if (xrange[i] >= xrange[i + 1])\n        {\n          GSL_ERROR_VAL (\"histogram xrange not in increasing order\",\n                            GSL_EDOM, 0);\n        }\n    }\n\n  for (j = 0; j < ny; j++)\n    {\n      if (yrange[j] >= yrange[j + 1])\n        {\n          GSL_ERROR_VAL (\"histogram yrange not in increasing order\"\n                            ,GSL_EDOM, 0);\n        }\n    }\n\n  /* Allocate histogram  */\n\n  h = (gsl_histogram2d *) malloc (sizeof (gsl_histogram2d));\n\n  if (h == 0)\n    {\n      GSL_ERROR_VAL (\"failed to allocate space for histogram struct\",\n                        GSL_ENOMEM, 0);\n    }\n\n  h->xrange = (double *) malloc ((nx + 1) * sizeof (double));\n\n  if (h->xrange == 0)\n    {\n      /* exception in constructor, avoid memory leak */\n      free (h);\n\n      GSL_ERROR_VAL (\"failed to allocate space for histogram xrange\",\n                        GSL_ENOMEM, 0);\n    }\n\n  h->yrange = (double *) malloc ((ny + 1) * sizeof (double));\n\n  if (h->yrange == 0)\n    {\n      /* exception in constructor, avoid memory leak */\n      free (h);\n\n      GSL_ERROR_VAL (\"failed to allocate space for histogram yrange\",\n                        GSL_ENOMEM, 0);\n    }\n\n  h->bin = (double *) malloc (nx * ny * sizeof (double));\n\n  if (h->bin == 0)\n    {\n      /* exception in constructor, avoid memory leak */\n      free (h->xrange);\n      free (h->yrange);\n      free (h);\n\n      GSL_ERROR_VAL (\"failed to allocate space for histogram bins\",\n                        GSL_ENOMEM, 0);\n    }\n\n  /* init histogram */\n\n  /* init ranges */\n\n  for (i = 0; i <= nx; i++)\n    {\n      h->xrange[i] = xrange[i];\n    }\n\n  for (j = 0; j <= ny; j++)\n    {\n      h->yrange[j] = yrange[j];\n    }\n\n  /* clear contents */\n\n  for (i = 0; i < nx; i++)\n    {\n      for (j = 0; j < ny; j++)\n        {\n          h->bin[i * ny + j] = 0;\n        }\n    }\n\n  h->nx = nx;\n  h->ny = ny;\n\n  return h;\n}\n", "meta": {"hexsha": "6f14d8784e84ff2b4b8ee36e7a1410ea10df3118", "size": 3808, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/histogram/calloc_range2d.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/histogram/calloc_range2d.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/histogram/calloc_range2d.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 24.8888888889, "max_line_length": 74, "alphanum_fraction": 0.5430672269, "num_tokens": 989, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29421497216298875, "lm_q2_score": 0.06371499869663867, "lm_q1q2_score": 0.01874590656789641}}
{"text": "#ifndef DEINOS_CHESS_H\n#define DEINOS_CHESS_H\n#include <optional>\n#include <array>\n#include <vector>\n#include <string>\n#include <cassert>\n#include <iostream>\n#include <gsl/gsl_assert>\n#include <cstddef>\n\nnamespace chess {\n\tenum class Almnt : uint8_t;\n\tenum class AlRes : uint8_t;\n\tenum class GameResult : uint8_t;\n\tenum class Side : uint8_t;\n\tstruct Piece;\n\tclass Square;\n\tstruct MoveRecord;\n\tclass Move;\n\tclass Position;\n\t\n\t//Alignment (i.e. White or Black)\n\tenum class Almnt : uint8_t {White = 0, Black = 1};\n\tconstexpr Almnt operator!(const Almnt& a) {return (a == Almnt::White ? Almnt::Black : Almnt::White);}\n\tinline uint8_t as_index(Almnt a) {return static_cast<uint8_t>(a);}\n\t\n\t//Alignment Result (for cases where \"None\" is an option)\n\tenum class AlRes : uint8_t {White = 0, Black = 1, None = 2}; //Utility to avoid constant Empty checks\n\tinline bool operator==(AlRes ar, Almnt a) {return static_cast<uint8_t>(ar) == static_cast<uint8_t>(a);}\n\tinline bool operator==(Almnt a, AlRes ar) {return ar == a;}\n\tinline bool operator!=(AlRes ar, Almnt a) {return !(ar == a);}\n\tinline bool operator!=(Almnt a, AlRes ar) {return !(ar == a);}\n\n\t//Game Result\n\tenum class GameResult : uint8_t {White = 0, Black = 1, Draw = 2};\n\tinline float evaluate(GameResult gr) {\n\t\tswitch (gr) {\n\t\t\tcase GameResult::White: return 1.0f;\n\t\t\tcase GameResult::Black: return 0.0f;\n\t\t\tcase GameResult::Draw: return 0.5f;\n\t\t\tdefault: return 0.5f;\n\t\t}\n\t}\n\tinline GameResult victory(Almnt a) {return static_cast<GameResult>(a);}\n\tinline AlRes victor(GameResult gr) {return static_cast<AlRes>(gr);}\n\n\t//Side of Board\n\tenum class Side : uint8_t {Kingside = 0, Queenside = 1};\n\n\t//The contents of a square (i.e. a chess piece or empty)\n\tstruct Piece {\n\t\tenum class Type : uint8_t {Empty, Pawn, Knight, Bishop, Rook, Queen, King};\n\t\t\n\t\tconstexpr Piece() = default;\n\t\tconstexpr Piece(Almnt a, Type t) : data((static_cast<std::byte>(t) << 1) | static_cast<std::byte>(a)) {}\n\n\t\tinline AlRes almnt_res() const {return (type() == Type::Empty ? AlRes::None : static_cast<AlRes>(almnt()));}\n\t\tinline Almnt almnt() const {return static_cast<Almnt>(data & std::byte{0x01});}\n\t\tinline Type type() const {return static_cast<Type>(data >> 1);}\n\n\tprivate:\n\t\tconstexpr Piece(uint8_t d) : data(std::byte{d}) {}\n\t\tinline uint8_t raw() const {return static_cast<uint8_t>(data);}\n\t\tstd::byte data = std::byte{0};\n\t\tfriend class Position;\n\t};\n\t\n\tbool operator==(Piece, Piece);\n\tbool operator!=(Piece, Piece);\n\tstd::ostream& operator<<(std::ostream& os, Piece::Type t);\n\tstd::ostream& operator<<(std::ostream& os, Piece p); //White uppercase, black lowercase\n\n\t//A bounds checked index into a chess position\n\tclass Square{\n\tpublic:\n\t\tconstexpr Square() = default;\n\t\tconstexpr Square(const char* name){ //this must be a zstring TODO\n\t\t\tconstexpr std::array<char, 8> files {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'};\n\t\t\tconstexpr std::array<char, 8> ranks {'1', '2', '3', '4', '5', '6', '7', '8'};\n\t\t\tuint8_t file = 255;\n\t\t\tuint8_t rank = 255;\n\t\t\tfor (int i = 0; i < 8; i++) {\n\t\t\t\tif (files[i] == name[0]) file = i;\n\t\t\t\tif (ranks[i] == name[1]) rank = i;\n\t\t\t}\n\t\t\tassert(file != 255);\n\t\t\tassert(rank != 255);\n\t\t\tdata = (std::byte{rank} << 3) | std::byte{file};\n\t\t}\n\t\t\n\t\tstd::optional<Square> translate(int files, int ranks) const; //TODO consider changing type to int8_t\n\t\tinline uint8_t file() const {return std::to_integer<uint8_t>(data & std::byte{0b00000111});}\n\t\tinline uint8_t rank() const {return std::to_integer<uint8_t>((data & std::byte{0b00111000}) >> 3);}\n\t\texplicit operator std::string () const;\n\tprivate:\n\t\tconstexpr Square(uint8_t file, uint8_t rank) : data((std::byte{rank} << 3) | std::byte{file}) {\n\t\t\tassert(file < 8);\n\t\t\tassert(rank < 8);\n\t\t}\n\t\tconstexpr Square(std::byte d) : data(d) {} //construct from raw data\n\t\tstd::byte data = std::byte{0};\n\t\tfriend class MoveRecord;\n\t\tfriend bool operator==(Square, Square);\n\t};\n\tbool operator==(Square, Square);\n\tbool operator!=(Square, Square);\n\t\n\tconstexpr std::array<Square, 64> all_squares {\n\t\t\"a1\", \"b1\", \"c1\", \"d1\", \"e1\", \"f1\", \"g1\", \"h1\",\n\t\t\"a2\", \"b2\", \"c2\", \"d2\", \"e2\", \"f2\", \"g2\", \"h2\",\n\t\t\"a3\", \"b3\", \"c3\", \"d3\", \"e3\", \"f3\", \"g3\", \"h3\",\n\t\t\"a4\", \"b4\", \"c4\", \"d4\", \"e4\", \"f4\", \"g4\", \"h4\",\n\t\t\"a5\", \"b5\", \"c5\", \"d5\", \"e5\", \"f5\", \"g5\", \"h5\",\n\t\t\"a6\", \"b6\", \"c6\", \"d6\", \"e6\", \"f6\", \"g6\", \"h6\",\n\t\t\"a7\", \"b7\", \"c7\", \"d7\", \"e7\", \"f7\", \"g7\", \"h7\",\n\t\t\"a8\", \"b8\", \"c8\", \"d8\", \"e8\", \"f8\", \"g8\", \"h8\",\n\t\t};\n\n\t//stores information necessary to reconstruct a move from a position\n\tstruct MoveRecord {\n\tprivate:\n\t\t\n\t\tinline uint8_t promo_index() const {return static_cast<uint8_t>(data2) >> 6;}\t\t\n\tpublic:\n\t\tconstexpr static std::array<Piece::Type, 4> promo_types\n\t\t\t{Piece::Type::Knight, Piece::Type::Bishop, Piece::Type::Rook, Piece::Type::Queen};\n\t\t\n\t\tstatic_assert(sizeof(Square) == 1);\n\t\tconstexpr MoveRecord(Square t_initial, Square t_final)\n\t\t\t: data1(reinterpret_cast<std::byte&>(t_initial)), data2(reinterpret_cast<std::byte&>(t_final)) {}\n\t\tMoveRecord(Square t_initial, Square t_final, Piece::Type t_promo_type);\n\t\t\n\t\tinline Square initial() const {return Square(data1 & std::byte{0x3F});}\n\t\tinline Square final() const {return Square(data2 & std::byte{0x3F});}\n\t\tinline bool is_promo() const {return (data1 & std::byte{0b11000000}) != std::byte{0};}\n\t\tinline std::optional<Piece::Type> promo_type() const\n\t\t{\n\t\t\treturn is_promo() ? std::make_optional<Piece::Type>(promo_types[promo_index()]) : std::nullopt;\n\t\t};\n\t\tstd::string to_string() const;\n\tprivate:\n\t\tstd::byte data1 = std::byte{0}; //initial square and promotion existence flag\n\t\tstd::byte data2 = std::byte{0}; //final square and promotion type flag\n\t};\n\tbool operator==(const MoveRecord&, const MoveRecord&);\n\tinline bool operator!=(const MoveRecord& mr1, const MoveRecord& mr2) {return !(mr1 == mr2);}\n\tinline std::ostream& operator<<(std::ostream& os, const MoveRecord& mr) {os << mr.to_string(); return os;}\n\n\t//64 half-byte uints stored in 32B\n\tstruct HalfByteBoard {\n\tprivate:\n\t\tinline uint8_t get_front(int i) const {return data[i] >> 4;}\n\t\tinline uint8_t get_back(int i) const {return data[i] & 0x0F;}\n\t\tinline void set_front(int i, uint8_t val) {data[i] = (val << 4) | (data[i] & 0x0F);}\n\t\tinline void set_back(int i, uint8_t val) {data[i] = val | (data[i] & 0xF0);}\n\tpublic:\n\t\tinline uint8_t get(int i) const\n\t\t{\n\t\t\tassert(i >= 0);\n\t\t\tassert(i < 64);\n\t\t\tif (i % 2 == 0) return get_front(i / 2);\n\t\t\telse return get_back(i / 2);\n\t\t}\n\t\tinline uint8_t get(int file, int rank) const {return get(rank * 8 + file);}\n\t\tinline void set(int i, uint8_t val)\n\t\t{\n\t\t\tassert(i >= 0);\n\t\t\tassert(i < 64);\n\t\t\tassert(val <= 0x0F);\n\t\t\tif (i % 2 == 0) set_front(i / 2, val);\n\t\t\telse set_back(i / 2, val);\n\t\t}\n\t\tinline void set(int file, int rank, uint8_t val) {set(rank * 8 + file, val);}\n\tprivate:\n\t\tstd::array<uint8_t, 32> data = {0};\n\t\tfriend bool operator==(const HalfByteBoard&, const HalfByteBoard&);\n\t};\n\tinline bool operator==(const HalfByteBoard& hbb1, const HalfByteBoard& hbb2) {return hbb1.data == hbb2.data;}\n\tinline bool operator!=(const HalfByteBoard& hbb1, const HalfByteBoard& hbb2) {return !(hbb1 == hbb2);}\n\n\t//Equivalent to a chess position recorded in Forsyth-Edwards Notaion\n\tclass Position {\n\tpublic:\n\t\tconstexpr Position() = default;\n\t\tPosition(const std::string& fen); //construct from FEN representation\n\t\tPosition(const Position&, const Move&); //generate new position by applying a move\n\t\tstatic Position std_start();\n\n\t\t//inline Piece& operator[] (Square s) {return m_board[s.file()][s.rank()];}\n\t\t//inline Piece operator[] (Square s) const {return m_board[s.file()][s.rank()];}\n\t\tinline Piece at(Square s) const {return Piece(m_board.get(s.file(), s.rank()));}\n\t\t//inline Piece at(Square s) const {return m_board[s.file()][s.rank()];}\n\t\tinline Piece at(int index) const {return Piece(m_board.get(index));}\n\t\t//inline Piece at(int index) const {return m_board[index % 8][index / 8];}\n\t\tinline void set(Square s, Piece p) {m_board.set(s.file(), s.rank(), p.raw());}\n\t\t//inline void set(Square s, Piece p) {m_board[s.file()][s.rank()] = p;}\n\t\tinline void set(int index, Piece p) {m_board.set(index, p.raw());}\n\t\t//inline void set(int index, Piece p) {m_board[index % 8][index / 8] = p;}\n\t\tinline bool can_castle(Almnt a, Side s) const {return m_castle[(int) a][(int) s];} //TODO use as_index\n\t\tinline bool& mut_castle(Almnt a, Side s){return m_castle[(int) a][(int) s];}\n\t\tinline Almnt to_move() const {return m_to_move;}\n\t\tinline std::optional<Square> en_passant_target() const {return m_en_passant_target;}\n\t\tinline int hm_clock() const {return m_hm_clock;}\n\t\tinline int fm_count() const {return m_fm_count;}\n\n\t\tstd::string as_fen() const;\n\t\texplicit operator std::string() const;\n\t\tfriend std::ostream& operator<<(std::ostream& os, const Position& pos);\n\t\tfriend bool operator==(const Position&, const Position&);\n\n\tprivate:\n\t\tstatic_assert(sizeof(Piece) == 1);\n\t\tHalfByteBoard m_board;\n\t\t//std::array<std::array<Piece, 8>, 8> m_board = {Piece()};\n\t\tAlmnt m_to_move = Almnt::White;\n\t\tstd::array<std::array<bool, 2>, 2> m_castle = {{false}}; //\"permitted to castle\" flags indexed by enum values\n\t\t//std::optional<GameResult> m_result = std::nullopt;\n\t\tstd::optional<Square> m_en_passant_target = std::nullopt;\n\t\tshort m_hm_clock = 0;\n\t\tshort m_fm_count = 1;\n\t};\n\tbool operator==(const Position&, const Position&);\n\tbool operator!=(const Position&, const Position&);\n\tstd::ostream& operator<<(std::ostream& os, const Position& pos);\n\n\t\n\t//A wrapper for a position and move record, representing a single move\n\tclass Move { //TODO: test code\n\tpublic:\n\t\t//constexpr Move() = default; //default constructor\n\t\t//Move(Square initial, Square final, Piece moved, Piece captured); //normal move\n\t\t//Move(const Position& pos, const std::string& name); //N.B this constructor does not support castling, promotion or en passant\n\t\t//void set_castling(); //castling 1.must be a king moving 2.must not capture 3.can only set once\n\t\t//void set_promotion(Piece::Type); //pawn promotion\n\t\t//void set_en_passant(); //en_passant\n\t\tconstexpr Move(const Position& t_pos, const MoveRecord& t_record) : m_pos(t_pos), m_record(t_record) {\n\t\t\tif (moved().type() == Piece::Type::Empty) {std::cerr << *this << std::endl << t_pos << std::endl; throw std::exception();}\n\t\t\tif (captured().almnt_res() == moved().almnt()) {std::cerr << *this << \" capt: \" << captured() << \" mr: \" << m_record << std::endl << t_pos << std::endl; throw std::exception();}\n\t\t\tassert(moved().type() != Piece::Type::Empty);\n\t\t\tassert(captured().almnt_res() != moved().almnt());\n\t\t}\n\t\t//inline Square initial_square() const {return m_initial_square;}\n\t\tinline Square initial_sq() const {return m_record.initial();}\n\t\t//inline Square final_square() const {return m_final_square;}\n\t\tinline Square final_sq() const {return m_record.final();}\n\t\t//inline Piece moved_piece() const {return m_moved_piece;}\n\t\tinline Piece moved() const {return m_pos.at(initial_sq());}\n\t\t//inline Piece captured_piece() const {return m_captured_piece;}\n\t\tinline Piece captured() const {return m_pos.at(final_sq());} //returns empty piece if en passant\n\t\t//inline bool is_en_passant() const {return m_is_en_passant;}\n\t\tbool is_en_passant() const;\n\t\t//inline bool is_castling() const {return m_is_castling;}\n\t\tbool is_castling() const;\n\t\t//inline bool is_promotion() const {return m_promoted_to.type() != Piece::Type::Empty;}\n\t\tinline bool is_promotion() const {return m_record.is_promo();}\n\t\t//inline Piece promoted_to() const {return m_promoted_to;}\n\t\tinline std::optional<Piece::Type> promo_type() const {return m_record.promo_type();}\n\t\tinline const MoveRecord& record() const {return m_record;}\n\t\tinline Position apply() const {return Position(m_pos, *this);}\n\n\t\texplicit operator std::string() const;\n\t\tfriend std::ostream& operator<<(std::ostream& os, const Move& mv);\n\t\tstd::string to_xboard() const;\n\t\n\tprivate:\n\t\t//Square m_initial_square;\n\t\t//Square m_final_square;\n\t\t//Piece m_moved_piece;\n\t\t//Piece m_captured_piece;\n\t\t//Piece m_promoted_to;\n\t\t//bool m_is_castling = false;\n\t\t//bool m_is_en_passant = false;\n\t\tconst Position& m_pos;\n\t\tconst MoveRecord& m_record;\n\t\tfriend bool operator==(const Move&, const Move&);\n\t};\n\tbool operator==(const Move&, const Move&);\n\tbool operator!=(const Move&, const Move&);\n\tstd::ostream& operator<<(std::ostream& os, const Move& mv);\n\t//std::optional<Move> find_move(const std::string& t_name, const AnalysedPosition& apos);\n\n\t//std::optional<Move> move_from_fen(const std::string& fen, const Position& curr_pos, const std::vector<Move>& moves);\n}\n#endif", "meta": {"hexsha": "f185d03b60247466e765c3af8551e9fb7efcef0a", "size": 12506, "ext": "h", "lang": "C", "max_stars_repo_path": "deinos/chess.h", "max_stars_repo_name": "Ayals4/deinos", "max_stars_repo_head_hexsha": "940f60f4c4907c3484217c082db6b66b3c39a373", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-05T00:44:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-05T00:44:30.000Z", "max_issues_repo_path": "deinos/chess.h", "max_issues_repo_name": "Ayals4/deinos", "max_issues_repo_head_hexsha": "940f60f4c4907c3484217c082db6b66b3c39a373", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "deinos/chess.h", "max_forks_repo_name": "Ayals4/deinos", "max_forks_repo_head_hexsha": "940f60f4c4907c3484217c082db6b66b3c39a373", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.8807017544, "max_line_length": 180, "alphanum_fraction": 0.6731968655, "num_tokens": 3812, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.039638840660911584, "lm_q1q2_score": 0.018736625012803064}}
{"text": "#ifndef BN\n#define BN\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n#include <stdbool.h>\n#include <getopt.h>\n#include <assert.h>\n\n#include <gsl/gsl_randist.h>\n#include <gsl/gsl_sf_gamma.h>\n#include <gsl/gsl_multimin.h>\n#include <gsl/gsl_matrix.h>\n\n#include <omp.h>\n#include <math.h>\n\n#include \"matrix.h\"\n#include \"model.h\"\n#include \"data.h\"\n#include \"vector.h\"\n#include \"a-queue.h\"\n\nbool verbose = false;\nbool debug = false;\n\nint** GENOTYPE; // GENOTYPE[i] stores the binary expansion of i.\nint NUM_SAMPLES_READ; // total number of samples read in from dataset.\n\n// set initial parameter values (seeimingly arbitrary, but makes it easier to tweak them since they're all here)\nvoid initialize_MH_params(unsigned int* seed, int* number_samples, int* record_ith, int* burn_in, char* reg_scheme) {\n\t*seed = time(NULL); // random seed using time\n\t*number_samples = 100000;\n\t*record_ith = 1;\n\t*burn_in = 0;\n\tstrcpy(reg_scheme, \"bic\");\n}\n\n/*\n * Check file inputs to bn. If no .poset file supplied (f flag), prints error message and exits.\n * Flags: \n *  \n * \n * \n */\nvoid check_file_inputs(int argc, char** argv, char* filestem, char* output, int* number_samples, unsigned int* seed, char* reg_scheme) {\n\tint c = 0;\n\tbool input_flag = false;\n\tbool output_flag = false;\n\tbool help_flag = false;\n\tstatic struct option long_options[] =\n        {\n          {\"dataset\",     \t\trequired_argument, 0, 'd'},\n          {\"output\",  \t\t\t\trequired_argument, 0, 'o'},\n          {\"number_samples\",\trequired_argument, 0, 'n'},\n          {\"seed\", \t\t\t\t\t\trequired_argument, 0, 's'},\n          {\"reg\", \t\t\t\t\t\trequired_argument, 0, 'r'},\n          {\"help\", \t\t\t\t\t\tno_argument, \t\t\t 0, 'h'},\n          {NULL, 0, NULL,0,}\n        };\n\twhile ((c = getopt_long(argc, argv, \"d:o:n:s:r:hvt:e:\", long_options, NULL)) != -1 ) {\n\t\tswitch(c) {\n\t\t\tcase 'd': // get input filename, satisfy boolean check for provided input. \n\t\t\t\tstrcpy(filestem, optarg);\n\t\t\t\tinput_flag = true;\n\t\t\t\tbreak;\n\t\t\tcase 'o':\n\t\t\t\tstrcpy(output, optarg);\n\t\t\t\toutput_flag = true;\n\t\t\t\tbreak;\n\t\t\tcase 'n':\n\t\t\t\t*number_samples = atoi(optarg);\n\t\t\t\tbreak;\n\t\t\tcase 's':\n\t\t\t\t*seed = atoi(optarg);\n\t\t\t\tbreak;\t\t\t\n\t\t\tcase 'r':\n\t\t\t\tstrcpy(reg_scheme, optarg);\n\t\t\t\tbreak;\n\t\t\tcase 'h':\n\t\t\t\thelp_flag = true;\n\t\t\t\tbreak;\n\t\t\tcase 'v':\n\t\t\t\tverbose = true;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (help_flag) {\n\t\tprintf(\"Usage: ./cbn (-(option) (argument) )*\\n\");\n\t\tprintf(\"where dataset input option (-d or --dataset) is required.\\n\");\n\t\tprintf(\"Options include:\\n\");\n\t\tprintf(\"-d | --dataset \\tPath to input file with sample data. Please include file extension as well. ex: test1.txt\\n\");\n\t\tprintf(\"-o | --output \\tPath to output file to write results to. If not specified, then results not written to file.\\n\");\n\t\tprintf(\"-n | --number_samples \\tSet the number of iterations for Metropolis-Hastings to be run. Default value set to 500,000.\\n\");\n\t\tprintf(\"-s | --seed \\tSet the seed for random number generators in the program. Time used as default seed.\\n\");\n\t\tprintf(\"-r | --reg \\tSet the likelihood regularization scheme for the MCMC algorithm. Valid choices are bic, aic, and loglik.\\n\");\n\t\tprintf(\"-h | --help \\tPrint help information for program.\\n\");\n\t\texit(1);\n\t}\n\n\tif (!input_flag) {\n\t\tfprintf(stderr, \"Error: No input file specified. Please provide the filename (without filetype) of a file containing formatted sample data using the \\\"-d\\\" or \\\"--dataset\\\" options.\\n\");\n\t\texit(1);\n\t}\n\tif (!output_flag) {\n\t\tstrcpy(output, \"\");\n\t}\n\tif (strcmp(reg_scheme, \"bic\") &&  strcmp(reg_scheme, \"aic\") && strcmp(reg_scheme, \"loglik\")) {\n\t\tfprintf(stderr, \"Error: Invalid regularization scheme. Please choose from bic (default), aic, or loglik.\\n\");\n\t\texit(1);\n\t}\t\n}\n\n/* \n * Standard open_file helper. Throws error if error while opening file. \n */\nFILE* open_file(char* filename, char* option) {\n\tFILE* input = fopen(filename, option);\n\tif (input == NULL) {\n\t\tfprintf(stderr, \"Error: Could not read %s\\n\", filename);\n\t\texit(1);\n\t}\n\treturn input;\n}\n\n/* \n * Base 2 power function. Computes 2^n, for n >= 0\n */\nstatic inline int pow2(int n) {\n\tassert(n >= 0);\n\treturn 1 << n;\n}\n\n\n// Basic power function implementation. Only accepts integral power values. \ndouble power(double base, int power) {\n\tdouble result = 1.0;\n\tfor (int i = 0; i < power; i++) {\n\t\tresult *= base;\n\t}\n\treturn result;\n}\n\n\n/* \n * Generates a binary compression of pattern data, which is\n * used as a means of quickly determining whether two samples have \n * the same pattern. Presumably, this is faster (as opposed to\n * comparisons without such a compression scheme), since we compress \n * all samples once, and then compare the \"hash\" values. \n * Parallels index_of in TS code. \n */\nint binary_compression(int* pat_i, int num_events) {\n\tint index = 0;\n\tfor (int i = 0; i < num_events; i++) {\n\t\tif (pat_i[i] ==1)\n\t\t\tindex += pow2(num_events - 1 - i);\n\t}\n\treturn index;\n}\n\n// Used to generate binary expansions of genotypes, for easier access later on.\nvoid precompute_binary(const int n) {\n\tint m = pow2(n);\n\tGENOTYPE = get_int_matrix(m, n);\n\tfor (int i = 0; i < m; i++) {\n\t\tint count = 0;\n\t\tfor (int j = 0; j < n; j++) {\n\t\t\tif ( ((1 << j) & i) > 0) {\n\t\t\t\tGENOTYPE[i][n - 1 - j] = 1;\n\t\t\t\tcount++;\n\t\t\t} else {\n\t\t\t\tGENOTYPE[i][n - 1 - j] = 0;\n\t\t\t}\n\t\t}\n\t}\n}\n\nint count_edges(int** poset, int n) {\n\tint count = 0;\n\tfor (int i=0; i< n; i++) {\n\t\tfor (int j = 0; j< n; j++) {\n\t\t\tif (poset[i][j])\n\t\t\t\tcount++;\n\t\t}\n\t}\n\treturn count;\n}\n\n// TODO: reconsider the use of int* ptr vector here. We've changed the idea, and we're no longer looking\n// at the probability of combined events. Instead, using the current poset to determine how children\n// are valid or not in find_children_extended. \n\n/* \n * Helper function for process_patterns function. Reads pattern data\n * from .txt file. Only 0/1 expected, but places negative values where\n * any deviations occur. Exits if any error is encountered.\n */\nint** read_patterns(FILE *input, model* M, char* filename, int* num_samples, int* num_events) {\n\tsize_t temp = 0;\n\tint n;\n\tchar* line = NULL; \n\tint len = getline(&line, &temp, input);\n\tif (len != -1) {\n\t\tn = len / 2;\n\t\tfree(line);\n\t\tline = NULL;\n\t\trewind(input);\n\t} else {\n\t\tfprintf(stderr, \"Error reading sample data.\\n\");\n\t\texit(1);\n\t}\n\n\tM->n = n;\n\t*num_events = n;\n\n\tptr_vector* v = new_ptr_vector(); // vector takes ints, hopefully won't get mutilated?\n\twhile (getline(&line, &temp, input) != -1) {\n\t\tint line_index = 0;\n\t\tint* genotype = get_int_array(n);\n\t\tfor (int i = 0; i< n; i++) { // fill in each event with genotype.\n\t\t\tif (line[line_index] == '0') genotype[i] = 0;\n\t\t\tif (line[line_index] == '1') genotype[i] = 1;\n\t\t\tline_index += 2;\n\t\t}\n\t\tpush_back_ptr(v, genotype);\n\t\tfree(line);\n\t\tline = NULL;\n\t\ttemp = 0;\n\t}\n\tfree(line);\n\t*num_samples = v->size;\n\n\tif (debug) {\n\t\tprintf(\"Finished reading patterns.\\nPatterns matrix: \\n\");\n\t\tprint_int_matrix(v->elems, v->size, n);\n\t}\n\n\treturn free_ptr_vector(v, false);\n}\n\n\n// counts uniq patterns among samples.\n// It seems that pat_idx counts the number of unique samples\n// up to that last unique sample.\n// ----- variables -----\n// index stores the \"hashed\" patterns\n// count stores the number of samples with the same pattern \n// Removed pat_idx necessity, since the same information is stored in index. \n\n// Note: The binary compression places a limit on the number of loci that can be observed (32 for int, 64 for long int). \n// For a completely scalable implementation, should re-work this scheme, use a hashset for speed. \nvoid count_uniq_patterns(int* index, int* count, int num_samples, int num_events, int* N_u, int** pat) {\n\n\t//binary compression that \"hashes\" genotypes \n\tfor (int i = 0; i< num_samples; i++)\n\t\tindex[i] = binary_compression(pat[i], num_events);\n\n\t// count unique patterns. Runs in worst case O(n^2) time. can be optimized to O(nlgn) using sort -> iterate, or linear time using a hashtable/set.\n\tbool skips; // true if another sample has same pattern (\"index\" value)\n\tint num_unique = 0; // counts number of unique patterns\n\tfor (int i = 0; i < num_samples; i++) {\n\t\tskips = false;\n\t\tfor (int j = 0; j < i; j++) {\n\t\t\tif (index[i] == index[j]) { //samples have the same pattern\n\t\t\t\tcount[j]++; //increment the count at first index\n\t\t\t\tskips = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (!skips) { // unique pattern --> NOT previously observed\n\t\t\tcount[i]++;\n\t\t\tnum_unique++;\t\n\t\t}\n\t}\n\t*N_u = num_unique;\n\n\tif (verbose) {\n\t\tprintf(\"Number of samples processed = %d\\n\", num_samples);\n\t\tprintf(\"Number of gene loci considered = %d\\n\", num_events);\n\t\tprintf(\"Number of unique genotypes observed = %d\\n\", num_unique);\n\t}\n\tif (debug) {\n\t\tprintf(\"num_samples = %d\\n\", num_samples);\n\t\tprintf(\"count array: \\n\");\n\t\tprint_int_array(count, num_samples);\n\t\tprintf(\"index array: \\n\");\n\t\tprint_int_array(index, num_samples);\n\t}\n}\n\ndata* construct_data_set(int num_unique, int* count, int* index, int num_samples, int num_events, int** pat) {\n\tdata* D = calloc(num_unique, sizeof(data));\n\tif (D == NULL) {\n\t\tfprintf(stderr, \"Error: calloc failure - out of memory.\\n\");\n\t\texit(1);\n\t}\n\tint d_index = 0;\n\tfor (int i = 0; i < num_samples; i++) {\n\t\tif (count[i] > 0) {//if was not a repeat\n\t\t\tD[d_index].count = count[i];\n\t\t\tD[d_index].g = get_int_array(num_events);\n\t\t\tfor (int j = 0; j < num_events; j++) \n\t\t\t\tD[d_index].g[j] = pat[i][j];\n\t\t\td_index++;\n\t\t}\n\t}\n\n\tif (debug) {\n\t\tprint_data_array(D, num_unique, num_events);\n\t}\n\treturn D;\n}\n\n// N_u = number of unique genotypes in dataset\n// n  = number of events\nint process_patterns(char* filename, model* M, int* N_u, data** D) {\n\n\tFILE* input = open_file(filename, \"r\");\n\tint num_samples, num_events;\n\tint** pat = read_patterns(input, M, filename, &num_samples, &num_events);\n\tfclose(input);\n\n\t//Count unique patterns, construct data set.\n\tint* index = get_int_array(num_samples);\n\tint* count = get_int_array(num_samples);\n\tcount_uniq_patterns(index, count, num_samples, num_events, N_u, pat);\n\t*D = construct_data_set(*N_u, count, index, num_samples, num_events, pat);\n\n\tNUM_SAMPLES_READ = num_samples;\n\tfree_int_matrix(pat, num_samples);\n\tfree_int_array(index);\n\tfree_int_array(count);\n\n\treturn 0;\n}\n\n// Suppes condition\n// Confirm that the proposed modification (move) is supported by event probabilities in the data set, taking into account\n// current theta types. \nbool cumulative_probs_maintained(model* M, data* D, int* theta_types, int num_unique) {\n\tint n = M->n;\n\tfor (int i = 0; i< n; i++) { // loop through each event\n\t\tint num_parents = M->num_pa[i];\n\t\tint* parents = M->pa[i];\n\t\tint type = theta_types[i];\n\t\tint count_parents = 0;\n\t\tint count_child = 0;\n\t\tint count_parents_child = 0;\n\t\tfor (int j = 0; j< num_unique; j++) { // loop through all observed genotypes\n\t\t\tint* g = D[j].g;\n\t\t\tint found = 0;\n\t\t\t\n\t\t\t// get child present bool value\n\t\t\tbool child_present = false;\n\t\t\tif (g[i]) child_present = true;\n\n\t\t\t// get parent set satisfied bool value\n\t\t\tbool parents_present = true;\n\t\t\tswitch (type) { // 0 or 1 parents, conjunctive\n\t\t\t\tcase -1 ... 0:\n\t\t\t\t\tfor (int k = 0; k < num_parents; k++) {\n\t\t\t\t\t\tif (!g[parents[k]]) parents_present = false;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 1: // or\n\t\t\t\t\tfor (int k = 0; k < num_parents; k++) {\n\t\t\t\t\t\tif (g[parents[k]]) found++;\n\t\t\t\t\t}\n\t\t\t\t\tif (!found) parents_present = false;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2: // xor\n\t\t\t\t\tfor (int k = 0; k < num_parents; k++) {\n\t\t\t\t\t\tif (g[parents[k]]) found++;\n\t\t\t\t\t}\n\t\t\t\t\tif (found != 1) parents_present = false;\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (child_present && parents_present) {\n\t\t\t\tcount_parents_child += D[j].count;\n\t\t\t}\n\n\t\t\tif (child_present) {\n\t\t\t\tcount_child += D[j].count;\n\t\t\t}\n\n\t\t\tif (parents_present) {\n\t\t\t\tcount_parents += D[j].count;\n\t\t\t}\n\t\t} \n\t\t// check that the checks and additions are correct. \n\t\tif (num_parents > 0) {\n\t\t\tif (count_parents <= count_child || count_parents_child * NUM_SAMPLES_READ <= count_parents * count_child) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} \n\t}\n\treturn true;\n}\n\n// Initializes the parent fields in the model so that they can be used to find children more efficiently. \nvoid set_theta_types(model* M, int* theta_types, int* theta_types_p) {\n\tint num_events = M->n;\n\tint** poset = M->P;\n\tfree_parents(M);\n\tM->num_pa = get_int_array(num_events); // create an array that stores the sizes of parents. \n\tM->pa = (int**) malloc(num_events * sizeof(int*)); // create an array to hold arrays of integers\n\n\t// for all events, create a vector of all other events that relate to them, according to the current poset. \n\t// Then, determine theta type if an event has > 1 parent events. \n\tfor (int i = 0; i< num_events; i++) {\n\t\tvector* v = new_vector();\n\t\tfor (int j = 0; j< num_events; j++) {\n\t\t\tif (poset[j][i]) {\n\t\t\t\tpush_back(v, j);\n\t\t\t}\n\t\t}\n\t\tint num_parents = v->size;\n\t\tM->num_pa[i] = num_parents;\n\t\tM->pa[i] = free_vector(v, false);\n\n\t\tif (num_parents <= 1) { // if 1 parent at most, no need for special care. \n\t\t\ttheta_types_p[i] = -1;\n\t\t} else {\n\t\t\tif (theta_types[i] < 0) { // event goes from 0/1 parents to 2+ parents\n\t\t\t\ttheta_types_p[i] = rand() % 3; // randomly pick between 0, 1, and 2. \n\t\t\t} else { // carry over formula from previous iteration. \n\t\t\t\ttheta_types_p[i] = theta_types[i];  \n\t\t\t}\n\t\t}\n\t}\n}\n\n\n// imposes a total ordering on the events. Use Fisher-Yates shuffling algorithm to randomize ordering\nvoid new_total_ordering(model* M, int* theta_types, data* D, int num_unique) {\n\tint num_events = M->n;\n\t// initialize new array to use.\n\tint rand_arr[num_events];\n\tfor (int i = 0; i < num_events; i++) {\n\t\trand_arr[i] = i;\n\t}\n\n\t// establish total ordering\n\tfor (int i = num_events - 1; i >= 0; i--) {\n\t\tint randy = rand() % (i + 1);\n\t\tint temp = rand_arr[i];\n\t\trand_arr[i] = rand_arr[randy];\n\t\trand_arr[randy] = temp;\n\t}\n\n\tint** initial_poset = get_int_matrix(num_events, num_events);\n\t// mark in poset. \n\tfor (int i = 0; i < num_events - 1; i++) {\n\t\tinitial_poset[rand_arr[i]][rand_arr[i+1]] = 1;\n\t}\n\n\t// transitive closure & theta types\n\tint** T = get_int_matrix(num_events, num_events);\n\ttransitive_closure(initial_poset, T, num_events);\n\n\tfor (int i = 0; i < num_events; i++) {\n\t\tint num_parents = 0;\n\t\tfor (int j = 0; j < num_events; j++) {\n\t\t\tif (T[j][i]) num_parents++;\n\t\t}\n\t\tif (num_parents == 0) continue; // don't bother checking if there are no parents, since we're only going to remove excess edges.\n\t\tint reduce = num_parents - (rand() % (num_parents + 1));\n\t\tfor (int j = 0; j < reduce; j++) { // delete a random relation reduce number of times.\n\t\t\tint ith_event = rand() % num_parents;\n\t\t\tint counted = 0;\n\t\t\tfor (int k = 0; k < num_events; k++) {\n\t\t\t\tif (counted == ith_event && T[k][i]) {\n\t\t\t\t\tT[k][i] = 0; // delete event\n\t\t\t\t\tnum_parents--; // decrement number of parents.\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (T[k][i]) counted++;\n\t\t\t}\n\t\t}\n\t}\n\n\tfree_int_matrix(initial_poset, num_events);\n\tfree_int_matrix(M->P, num_events);\n\tM->P = T;\n\t\n\tint* theta_types_p = get_int_array(num_events);\n\tfor (int i = 0; i < num_events; i++) {\n\t\ttheta_types_p[i] = -1;\n\t}\n\tset_theta_types(M, theta_types_p, theta_types);\n\n\tmodel M_p;\n\tM_p.n = num_events;\n\tM_p.pa = M->pa;\n\tM_p.P = T;\n\tM_p.num_pa = get_int_array(num_events); // initializes each to 0.\n\t// do suppes checking for each events' parent set. \n\tfor (int i = 0; i < num_events; i++) {\n\t\t// determine suppes prob condition for this event and its parent set. \n\t\t// copy the parent set of this event into a new poset. \n\t\ttheta_types_p[i] = theta_types[i];\n\t\tM_p.num_pa[i] = M->num_pa[i];\n\t\tif (!cumulative_probs_maintained(&M_p, D, theta_types, num_unique)) {// reject entire parent set.\n\t\t\tfor (int j = 0; j < num_events; j++) { \n\t\t\t\tM->P[j][i] = 0;\n\t\t\t}\n\t\t\tM->num_pa[i] = 0; \n\t\t\ttheta_types[i] = -1;\n\t\t}\n\t\ttheta_types_p[i] = -1; // push to conjunctive so that it doesn't go to 'or' and 'xor' cases.\n\t\tM_p.num_pa[i] = 0; // set back to 0.\n\t}\n\tfree_int_array(M_p.num_pa);\n\tfree_int_array(theta_types_p);\n}\n\n\n// returns the total number of events associated with a given genotype. \n// ex. For n= 4, 0101 returns 2.\nint total_events(const int genotype, const int n) {\n\tint* binary = GENOTYPE[genotype];\n\tint num_events = 0;\n\tfor (int i=0; i< n; i++) \n\t\tnum_events += binary[i];\n\treturn num_events;\n}\n\n// Given two integers, returns the number of bitwise differences between the two. \n// If hamming distance > 1, returns index of last (largest) bit. \nint hamming_distance(unsigned int x, unsigned int y, const int num_events, int* diff_index) {\n\tunsigned int dist = 0;\n\tunsigned int diff = x ^ y;\n\tfor (int i= 0; i < num_events; i++) {\n\t\tif ( (1 << i) & diff ) {\n\t\t\tdist++;\n\t\t\tif (diff_index != NULL)\t*diff_index = num_events - 1 - i;\n\t\t}\n\t}\n\treturn dist;\n}\n\n\n// Checks that the parent conditions of the ith event are satisfied in provided genotype g. \n// Returns true if parent conditions (according to poset and theta_types) are fulfilled, false otherwise. \nbool check_parent_set(model* M, int* theta_types, int* g, int i) {\n\tint num_parents = M->num_pa[i];\n\tint type = theta_types[i]; // relationship between parents.\n\tbool compatible = false;\n\tint found = 0;\n\n\tswitch (type) { // will only go into one case for each, so this may be faster. \n\t\tcase -1 ... 0: // 0/1 parents, or and case if > 1 parents. loop through all parents, confirm that all are present.\n\t\t\tfor (int j = 0; j< num_parents; j++) {\n\t\t\t\tif (!g[M->pa[i][j]]) return false;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 1: // or. \n\t\t\tfor (int j = 0; j< num_parents; j++) {\n\t\t\t\tif (g[M->pa[i][j]]) {\n\t\t\t\t\tcompatible = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\t\t\t\t\t\n\t\t\t}\n\t\t\tif (!compatible) return false;\n\t\t\tbreak;\n\t\tcase 2: // xor. loop through all parents, confirm that only one present at a time.\n\t\t\tfor (int j = 0; j< num_parents; j++) {\n\t\t\t\tif (g[M->pa[i][j]]) { // another event observed that isn't the current\n\t\t\t\t\tfound++;\n\t\t\t\t} \n\t\t\t}\n\t\t\tif (found != 1) return false;\n\t\t\tbreak;\n\t}\n\treturn true;\n}\n\n\n// Theta types gives the relationship between \"parent events\", if an event has more than one direct parent.\n// If check_parent_set returns true for all events, then returns true. \nbool compatible_with_poset(int genotype, model* M, int* theta_types) {\n\tint num_events = M->n;\n\tint* g = GENOTYPE[genotype];\n\tfor (int i = 0; i< num_events; i++) { // for each event\n\t\tif (g[i]) { // if event is observed\n\t\t\tif (!check_parent_set(M, theta_types, g, i)) return false; \n\t\t}\n\t}\n\treturn true;\n}\n\n#endif\n", "meta": {"hexsha": "7738e22465a1e6d7d54fbf9d24252a99c133a95e", "size": 18167, "ext": "h", "lang": "C", "max_stars_repo_path": "HESBCN/h-esbcn.h", "max_stars_repo_name": "BIMIB-DISCo/PMCE", "max_stars_repo_head_hexsha": "836575a6a5ac7d3e0cb13eea9ac5e20b8e33c2a6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HESBCN/h-esbcn.h", "max_issues_repo_name": "BIMIB-DISCo/PMCE", "max_issues_repo_head_hexsha": "836575a6a5ac7d3e0cb13eea9ac5e20b8e33c2a6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HESBCN/h-esbcn.h", "max_forks_repo_name": "BIMIB-DISCo/PMCE", "max_forks_repo_head_hexsha": "836575a6a5ac7d3e0cb13eea9ac5e20b8e33c2a6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3795986622, "max_line_length": 188, "alphanum_fraction": 0.6456762261, "num_tokens": 5326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37754066879814546, "lm_q2_score": 0.049589020701586016, "lm_q1q2_score": 0.018721872040721864}}
{"text": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//------------------------------------------------------------------------------\n// Intrinsics.h\n//------------------------------------------------------------------------------\n\n#pragma once\n\n#include <arcana/analysis/introspector.h>\n\n#include <gsl/gsl>\n\n#include <array>\n\nnamespace mage\n{    \n    class Intrinsics\n    {\n    public:\n        Intrinsics() = default;\n        Intrinsics(gsl::span<const float, 4> intrinsicsCxCyFxFy, uint32_t imageWidth, uint32_t imageHeight);\n        Intrinsics(float cx, float cy, float fx, float fy, uint32_t imageWidth, uint32_t imageHeight);\n\n        // cx, cy, fx, fy\n        gsl::span<const float, 4> GetCoefficients() const { return m_coefficients; }\n        std::array<float, 4> GetNormalizedCoefficients() const;\n\n        float GetCx() const { return m_coefficients[0]; } //principle point pixels\n        float GetCy() const { return m_coefficients[1]; } //principle point pixels\n        float GetFx() const { return m_coefficients[2]; } //focal length pixels\n        float GetFy() const { return m_coefficients[3]; } //focal length pixels\n\n        void SetCx(float cx) { m_coefficients[0] = cx; }  //principle point pixels\n        void SetCy(float cy) { m_coefficients[1] = cy; }  //principle point pixels\n        void SetFx(float fx) { m_coefficients[2] = fx; }  //focal length pixels\n        void SetFy(float fy) { m_coefficients[3] = fy; }  //focal length pixels\n\n        uint32_t GetCalibrationWidth() const { return m_widthPixels; }\n        uint32_t GetCalibrationHeight() const { return m_heightPixels; }\n\n    private:\n        std::array<float, 4> m_coefficients{}; // cx, cy, fx, fy in pixels\n        uint32_t m_widthPixels{};  //widht/height calibration was performed for\n        uint32_t m_heightPixels{};\n    };\n\n    template<typename ArchiveT>\n    void introspect_object(mira::introspector<ArchiveT>& intro, const Intrinsics& intrin)\n    {\n        intro(\n            cereal::make_nvp(\"Coefficients\", intrin.GetCoefficients())\n        );\n    }\n}\n", "meta": {"hexsha": "40b9cfb2bda57a3c8f1b939eac85eb8ab4620f55", "size": 2074, "ext": "h", "lang": "C", "max_stars_repo_path": "Core/MAGESLAM/Source/Data/Intrinsics.h", "max_stars_repo_name": "syntheticmagus/mageslam", "max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z", "max_issues_repo_path": "Core/MAGESLAM/Source/Data/Intrinsics.h", "max_issues_repo_name": "syntheticmagus/mageslam", "max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z", "max_forks_repo_path": "Core/MAGESLAM/Source/Data/Intrinsics.h", "max_forks_repo_name": "syntheticmagus/mageslam", "max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z", "avg_line_length": 37.0357142857, "max_line_length": 108, "alphanum_fraction": 0.6080038573, "num_tokens": 511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.04023794060948605, "lm_q1q2_score": 0.01870668181817915}}
{"text": "/**\n *\n * @file qwrapper_sgemm.c\n *\n *  PLASMA core_blas quark wrapper\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Hatem Ltaief\n * @author Mathieu Faverge\n * @author Jakub Kurzak\n * @date 2010-11-15\n * @generated s Tue Jan  7 11:44:56 2014\n *\n **/\n#include <cblas.h>\n#include \"common.h\"\n\n/***************************************************************************//**\n *\n **/\nvoid QUARK_CORE_sgemm(Quark *quark, Quark_Task_Flags *task_flags,\n                      PLASMA_enum transA, int transB,\n                      int m, int n, int k, int nb,\n                      float alpha, const float *A, int lda,\n                                                const float *B, int ldb,\n                      float beta, float *C, int ldc)\n{\n    DAG_CORE_GEMM;\n    QUARK_Insert_Task(quark, CORE_sgemm_quark, task_flags,\n        sizeof(PLASMA_enum),                &transA,    VALUE,\n        sizeof(PLASMA_enum),                &transB,    VALUE,\n        sizeof(int),                        &m,         VALUE,\n        sizeof(int),                        &n,         VALUE,\n        sizeof(int),                        &k,         VALUE,\n        sizeof(float),         &alpha,     VALUE,\n        sizeof(float)*nb*nb,    A,                 INPUT,\n        sizeof(int),                        &lda,       VALUE,\n        sizeof(float)*nb*nb,    B,                 INPUT,\n        sizeof(int),                        &ldb,       VALUE,\n        sizeof(float),         &beta,      VALUE,\n        sizeof(float)*nb*nb,    C,                 INOUT,\n        sizeof(int),                        &ldc,       VALUE,\n        0);\n}\n\n/***************************************************************************//**\n *\n **/\nvoid QUARK_CORE_sgemm2( Quark *quark, Quark_Task_Flags *task_flags,\n                        PLASMA_enum transA, int transB,\n                        int m, int n, int k, int nb,\n                        float alpha, const float *A, int lda,\n                        const float *B, int ldb,\n                        float beta, float *C, int ldc)\n{\n    DAG_CORE_GEMM;\n    QUARK_Insert_Task(quark, CORE_sgemm_quark, task_flags,\n        sizeof(PLASMA_enum),                &transA,    VALUE,\n        sizeof(PLASMA_enum),                &transB,    VALUE,\n        sizeof(int),                        &m,         VALUE,\n        sizeof(int),                        &n,         VALUE,\n        sizeof(int),                        &k,         VALUE,\n        sizeof(float),         &alpha,     VALUE,\n        sizeof(float)*nb*nb,    A,                 INPUT,\n        sizeof(int),                        &lda,       VALUE,\n        sizeof(float)*nb*nb,    B,                 INPUT,\n        sizeof(int),                        &ldb,       VALUE,\n        sizeof(float),         &beta,      VALUE,\n        sizeof(float)*nb*nb,    C,                 INOUT | LOCALITY | GATHERV,\n        sizeof(int),                        &ldc,       VALUE,\n        0);\n}\n\n/***************************************************************************//**\n *\n **/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_sgemm_quark = PCORE_sgemm_quark\n#define CORE_sgemm_quark PCORE_sgemm_quark\n#endif\nvoid CORE_sgemm_quark(Quark *quark)\n{\n    PLASMA_enum transA;\n    PLASMA_enum transB;\n    int m;\n    int n;\n    int k;\n    float alpha;\n    float *A;\n    int lda;\n    float *B;\n    int ldb;\n    float beta;\n    float *C;\n    int ldc;\n\n    quark_unpack_args_13(quark, transA, transB, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc);\n    cblas_sgemm(\n        CblasColMajor,\n        (CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB,\n        m, n, k,\n        (alpha), A, lda,\n        B, ldb,\n        (beta), C, ldc);\n}\n\n/***************************************************************************//**\n *\n **/\nvoid QUARK_CORE_sgemm_f2(Quark *quark, Quark_Task_Flags *task_flags,\n                         PLASMA_enum transA, int transB,\n                         int m, int n, int k, int nb,\n                         float alpha, const float *A, int lda,\n                                                   const float *B, int ldb,\n                         float beta, float *C, int ldc,\n                         float *fake1, int szefake1, int flag1,\n                         float *fake2, int szefake2, int flag2)\n{\n    DAG_CORE_GEMM;\n    QUARK_Insert_Task(quark, CORE_sgemm_f2_quark, task_flags,\n        sizeof(PLASMA_enum),                &transA,    VALUE,\n        sizeof(PLASMA_enum),                &transB,    VALUE,\n        sizeof(int),                        &m,         VALUE,\n        sizeof(int),                        &n,         VALUE,\n        sizeof(int),                        &k,         VALUE,\n        sizeof(float),         &alpha,     VALUE,\n        sizeof(float)*nb*nb,    A,                 INPUT,\n        sizeof(int),                        &lda,       VALUE,\n        sizeof(float)*nb*nb,    B,                 INPUT,\n        sizeof(int),                        &ldb,       VALUE,\n        sizeof(float),         &beta,      VALUE,\n        sizeof(float)*nb*nb,    C,                 INOUT | LOCALITY,\n        sizeof(int),                        &ldc,       VALUE,\n        sizeof(float)*szefake1, fake1,             flag1,\n        sizeof(float)*szefake2, fake2,             flag2,\n        0);\n}\n\n/***************************************************************************//**\n *\n **/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_sgemm_f2_quark = PCORE_sgemm_f2_quark\n#define CORE_sgemm_f2_quark PCORE_sgemm_f2_quark\n#endif\nvoid CORE_sgemm_f2_quark(Quark* quark)\n{\n    PLASMA_enum transA;\n    PLASMA_enum transB;\n    int M;\n    int N;\n    int K;\n    float alpha;\n    float *A;\n    int LDA;\n    float *B;\n    int LDB;\n    float beta;\n    float *C;\n    int LDC;\n    void *fake1, *fake2;\n\n    quark_unpack_args_15(quark, transA, transB, M, N, K, alpha,\n                         A, LDA, B, LDB, beta, C, LDC, fake1, fake2);\n    cblas_sgemm(\n        CblasColMajor,\n        (CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB,\n        M, N, K,\n        (alpha), A, LDA,\n        B, LDB,\n        (beta), C, LDC);\n}\n\n/***************************************************************************//**\n *\n **/\nvoid QUARK_CORE_sgemm_p2(Quark *quark, Quark_Task_Flags *task_flags,\n                         PLASMA_enum transA, int transB,\n                         int m, int n, int k, int nb,\n                         float alpha, const float *A, int lda,\n                         const float **B, int ldb,\n                         float beta, float *C, int ldc)\n{\n    DAG_CORE_GEMM;\n    QUARK_Insert_Task(quark, CORE_sgemm_p2_quark, task_flags,\n        sizeof(PLASMA_enum),                &transA,    VALUE,\n        sizeof(PLASMA_enum),                &transB,    VALUE,\n        sizeof(int),                        &m,         VALUE,\n        sizeof(int),                        &n,         VALUE,\n        sizeof(int),                        &k,         VALUE,\n        sizeof(float),         &alpha,     VALUE,\n        sizeof(float)*lda*nb,   A,                 INPUT,\n        sizeof(int),                        &lda,       VALUE,\n        sizeof(float*),         B,                 INPUT,\n        sizeof(int),                        &ldb,       VALUE,\n        sizeof(float),         &beta,      VALUE,\n        sizeof(float)*ldc*nb,    C,                 INOUT | LOCALITY,\n        sizeof(int),                        &ldc,       VALUE,\n        0);\n}\n\n/***************************************************************************//**\n *\n **/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_sgemm_p2_quark = PCORE_sgemm_p2_quark\n#define CORE_sgemm_p2_quark PCORE_sgemm_p2_quark\n#endif\nvoid CORE_sgemm_p2_quark(Quark* quark)\n{\n    PLASMA_enum transA;\n    PLASMA_enum transB;\n    int M;\n    int N;\n    int K;\n    float alpha;\n    float *A;\n    int LDA;\n    float **B;\n    int LDB;\n    float beta;\n    float *C;\n    int LDC;\n\n    quark_unpack_args_13(quark, transA, transB, M, N, K, alpha,\n                         A, LDA, B, LDB, beta, C, LDC);\n    cblas_sgemm(\n        CblasColMajor,\n        (CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB,\n        M, N, K,\n        (alpha), A, LDA,\n        *B, LDB,\n        (beta), C, LDC);\n}\n\n/***************************************************************************//**\n *\n **/\nvoid QUARK_CORE_sgemm_p3(Quark *quark, Quark_Task_Flags *task_flags,\n                           PLASMA_enum transA, int transB,\n                           int m, int n, int k, int nb,\n                           float alpha, const float *A, int lda,\n                           const float *B, int ldb,\n                           float beta, float **C, int ldc)\n{\n    DAG_CORE_GEMM;\n    QUARK_Insert_Task(quark, CORE_sgemm_p3_quark, task_flags,\n        sizeof(PLASMA_enum),                &transA,    VALUE,\n        sizeof(PLASMA_enum),                &transB,    VALUE,\n        sizeof(int),                        &m,         VALUE,\n        sizeof(int),                        &n,         VALUE,\n        sizeof(int),                        &k,         VALUE,\n        sizeof(float),         &alpha,     VALUE,\n        sizeof(float)*lda*nb,   A,                 INPUT,\n        sizeof(int),                        &lda,       VALUE,\n        sizeof(float)*ldb*nb,   B,                 INPUT,\n        sizeof(int),                        &ldb,       VALUE,\n        sizeof(float),         &beta,      VALUE,\n        sizeof(float*),         C,                 INOUT | LOCALITY,\n        sizeof(int),                        &ldc,       VALUE,\n        0);\n}\n\n/***************************************************************************//**\n *\n **/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_sgemm_p3_quark = PCORE_sgemm_p3_quark\n#define CORE_sgemm_p3_quark PCORE_sgemm_p3_quark\n#endif\nvoid CORE_sgemm_p3_quark(Quark* quark)\n{\n    PLASMA_enum transA;\n    PLASMA_enum transB;\n    int M;\n    int N;\n    int K;\n    float alpha;\n    float *A;\n    int LDA;\n    float *B;\n    int LDB;\n    float beta;\n    float **C;\n    int LDC;\n\n    quark_unpack_args_13(quark, transA, transB, M, N, K, alpha,\n                         A, LDA, B, LDB, beta, C, LDC);\n    cblas_sgemm(\n        CblasColMajor,\n        (CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB,\n        M, N, K,\n        (alpha), A, LDA,\n        B, LDB,\n        (beta), *C, LDC);\n}\n\n/***************************************************************************//**\n *\n **/\nvoid QUARK_CORE_sgemm_p2f1(Quark *quark, Quark_Task_Flags *task_flags,\n                           PLASMA_enum transA, int transB,\n                           int m, int n, int k, int nb,\n                           float alpha, const float *A, int lda,\n                           const float **B, int ldb,\n                           float beta, float *C, int ldc,\n                           float *fake1, int szefake1, int flag1)\n{\n    DAG_CORE_GEMM;\n    QUARK_Insert_Task(quark, CORE_sgemm_p2f1_quark, task_flags,\n        sizeof(PLASMA_enum),                &transA,    VALUE,\n        sizeof(PLASMA_enum),                &transB,    VALUE,\n        sizeof(int),                        &m,         VALUE,\n        sizeof(int),                        &n,         VALUE,\n        sizeof(int),                        &k,         VALUE,\n        sizeof(float),         &alpha,     VALUE,\n        sizeof(float)*lda*nb,   A,                 INPUT,\n        sizeof(int),                        &lda,       VALUE,\n        sizeof(float*),         B,                 INPUT,\n        sizeof(int),                        &ldb,       VALUE,\n        sizeof(float),         &beta,      VALUE,\n        sizeof(float)*ldc*nb,    C,                 INOUT | LOCALITY,\n        sizeof(int),                        &ldc,       VALUE,\n        sizeof(float)*szefake1, fake1,             flag1,\n        0);\n}\n\n/***************************************************************************//**\n *\n **/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_sgemm_p2f1_quark = PCORE_sgemm_p2f1_quark\n#define CORE_sgemm_p2f1_quark PCORE_sgemm_p2f1_quark\n#endif\nvoid CORE_sgemm_p2f1_quark(Quark* quark)\n{\n    PLASMA_enum transA;\n    PLASMA_enum transB;\n    int M;\n    int N;\n    int K;\n    float alpha;\n    float *A;\n    int LDA;\n    float **B;\n    int LDB;\n    float beta;\n    float *C;\n    int LDC;\n    void *fake1;\n\n    quark_unpack_args_14(quark, transA, transB, M, N, K, alpha,\n                         A, LDA, B, LDB, beta, C, LDC, fake1);\n    cblas_sgemm(\n        CblasColMajor,\n        (CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB,\n        M, N, K,\n        (alpha), A, LDA,\n        *B, LDB,\n        (beta), C, LDC);\n}\n", "meta": {"hexsha": "f9fe5e9f635baf06f6d20d89d8a1544d321debeb", "size": 12669, "ext": "c", "lang": "C", "max_stars_repo_path": "core_blas-qwrapper/qwrapper_sgemm.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "core_blas-qwrapper/qwrapper_sgemm.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "core_blas-qwrapper/qwrapper_sgemm.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8049450549, "max_line_length": 94, "alphanum_fraction": 0.4330254953, "num_tokens": 3203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378235137849365, "lm_q2_score": 0.04272219328060005, "lm_q1q2_score": 0.018704780778711516}}
{"text": "/*\n * SpanDSP - a series of DSP components for telephony\n *\n * makecss.c - Create the composite source signal (CSS) for G.168 testing.\n *\n * Written by Steve Underwood <steveu@coppice.org>\n *\n * Copyright (C) 2003 Steve Underwood\n *\n * All rights reserved.\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License version 2, as\n * published by the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n/*! \\page makecss_page CSS construction for G.168 testing\n\\section makecss_page_sec_1 What does it do?\n???.\n\n\\section makecss_page_sec_2 How does it work?\n???.\n*/\n\n#if defined(HAVE_CONFIG_H)\n#include \"config.h\"\n#endif\n\n#include <stdlib.h>\n#include <unistd.h>\n#include <string.h>\n#include <time.h>\n#include <stdio.h>\n#include <fcntl.h>\n#include <sndfile.h>\n#if defined(HAVE_FFTW3_H)\n#include <fftw3.h>\n#else\n#include <fftw.h>\n#endif\n\n#include \"spandsp.h\"\n#include \"spandsp/g168models.h\"\n\n#if !defined(NULL)\n#define NULL (void *) 0\n#endif\n\n#define FAST_SAMPLE_RATE    44100.0\n\n#define C1_VOICED_SAMPLES   2144    /* 48.62ms at 44100 samples/second => 2144.142 */\n#define C1_NOISE_SAMPLES    8820    /* 200ms at 44100 samples/second => 8820.0 */\n#define C1_SILENCE_SAMPLES  4471    /* 101.38ms at 44100 samples/second => 4470.858 */\n\n#define C3_VOICED_SAMPLES   3206    /* 72.69ms at 44100 samples/second => 3205.629 */\n#define C3_NOISE_SAMPLES    8820    /* 200ms at 44100 samples/second => 8820.0 */\n#define C3_SILENCE_SAMPLES  5614    /* 127.31ms at 44100 samples/second => 5614.371 */\n\nstatic double scaling(double f, double start, double end, double start_gain, double end_gain)\n{\n    double scale;\n\n    scale = start_gain + (f - start)*(end_gain - start_gain)/(end - start);\n    return scale;\n}\n/*- End of function --------------------------------------------------------*/\n\nstatic double peak(const int16_t amp[], int len)\n{\n    int16_t peak;\n    int i;\n\n    peak = 0;\n    for (i = 0;  i < len;  i++)\n    {\n        if (abs(amp[i]) > peak)\n            peak = abs(amp[i]);\n    }\n    return peak/32767.0;\n}\n/*- End of function --------------------------------------------------------*/\n\nstatic double rms(const int16_t amp[], int len)\n{\n    double ms;\n    int i;\n\n    ms = 0.0;\n    for (i = 0;  i < len;  i++)\n        ms += amp[i]*amp[i];\n    return sqrt(ms/len)/32767.0;\n}\n/*- End of function --------------------------------------------------------*/\n\nstatic double rms_to_dbm0(double rms)\n{\n    return 20.0*log10(rms) + DBM0_MAX_POWER;\n}\n/*- End of function --------------------------------------------------------*/\n\nstatic double rms_to_db(double rms)\n{\n    return 20.0*log10(rms);\n}\n/*- End of function --------------------------------------------------------*/\n\nint main(int argc, char *argv[])\n{\n#if defined(HAVE_FFTW3_H)\n    double in[8192][2];\n    double out[8192][2];\n#else\n    fftw_complex in[8192];\n    fftw_complex out[8192];\n#endif\n    fftw_plan p;\n    int16_t voiced_sound[8192];\n    int16_t noise_sound[8830];\n    int16_t silence_sound[8192];\n    int i;\n    int voiced_length;\n    int randy;\n    double f;\n    double pk;\n    double ms;\n    double scale;\n    SNDFILE *filehandle;\n    SF_INFO info;\n    awgn_state_t *noise_source;\n\n    memset(&info, 0, sizeof(info));\n    info.frames = 0;\n    info.samplerate = FAST_SAMPLE_RATE;\n    info.channels = 1;\n    info.format = SF_FORMAT_WAV | SF_FORMAT_PCM_16;\n    info.sections = 1;\n    info.seekable = 1;\n    if ((filehandle = sf_open(\"sound_c1.wav\", SFM_WRITE, &info)) == NULL)\n    {\n        fprintf(stderr, \"    Failed to open result file\\n\");\n        exit(2);\n    }\n\n    printf(\"Generate C1\\n\");\n    /* The sequence is\n            48.62ms  of voiced sound from table C.1 of G.168\n            200.0ms  of pseudo-noise\n            101.38ms of silence\n       The above is then repeated phase inverted.\n\n       The voice comes straight from C.1, repeated enough times to\n       fill out the 48.62ms period - i.e. 16 copies of the sequence.\n\n       The pseudo noise section is random numbers filtered by the spectral\n       pattern in Figure C.2 */\n\n    /* The set of C1 voice samples is ready for use in the output file. */\n    voiced_length = sizeof(css_c1)/sizeof(css_c1[0]);\n    for (i = 0;  i < voiced_length;  i++)\n        voiced_sound[i] = css_c1[i];\n    pk = peak(voiced_sound, voiced_length);\n    ms = rms(voiced_sound, voiced_length);\n    printf(\"Voiced level = %.2fdB, crest factor = %.2fdB\\n\", rms_to_dbm0(ms), rms_to_db(pk/ms));\n\n#if defined(HAVE_FFTW3_H)\n    p = fftw_plan_dft_1d(8192, in, out, FFTW_BACKWARD, FFTW_ESTIMATE);\n#else\n    p = fftw_create_plan(8192, FFTW_BACKWARD, FFTW_ESTIMATE);\n#endif\n    for (i = 0;  i < 8192;  i++)\n    {\n#if defined(HAVE_FFTW3_H)\n        in[i][0] = 0.0;\n        in[i][1] = 0.0;\n#else\n        in[i].re = 0.0;\n        in[i].im = 0.0;\n#endif\n    }\n    for (i = 1;  i <= 3715;  i++)\n    {\n        f = FAST_SAMPLE_RATE*i/8192.0;\n\n#if 1\n        if (f < 50.0)\n            scale = -60.0;\n        else if (f < 100.0)\n            scale = scaling(f, 50.0, 100.0, -25.8, -12.8);\n        else if (f < 200.0)\n            scale = scaling(f, 100.0, 200.0, -12.8, 17.4);\n        else if (f < 215.0)\n            scale = scaling(f, 200.0, 215.0, 17.4, 17.8);\n        else if (f < 500.0)\n            scale = scaling(f, 215.0, 500.0, 17.8, 12.2);\n        else if (f < 1000.0)\n            scale = scaling(f, 500.0, 1000.0, 12.2, 7.2);\n        else if (f < 2850.0)\n            scale = scaling(f, 1000.0, 2850.0, 7.2, 0.0);\n        else if (f < 3600.0)\n            scale = scaling(f, 2850.0, 3600.0, 0.0, -2.0);\n        else if (f < 3660.0)\n            scale = scaling(f, 3600.0, 3660.0, -2.0, -20.0);\n        else if (f < 3680.0)\n            scale = scaling(f, 3600.0, 3680.0, -20.0, -30.0);\n        else\n            scale = -60.0;\n#else\n        scale = 0.0;\n#endif\n        randy = ((rand() >> 10) & 0x1)  ?  1.0  :  -1.0;\n#if defined(HAVE_FFTW3_H)\n        in[i][0] = randy*pow(10.0, scale/20.0)*35.0;\n        in[8192 - i][0] = -in[i][0];\n#else\n        in[i].re = randy*pow(10.0, scale/20.0)*35.0;\n        in[8192 - i].re = -in[i].re;\n#endif\n    }\n#if defined(HAVE_FFTW3_H)\n    fftw_execute(p);\n#else\n    fftw_one(p, in, out);\n#endif\n    for (i = 0;  i < 8192;  i++)\n    {\n#if defined(HAVE_FFTW3_H)\n        noise_sound[i] = out[i][1];\n#else\n        noise_sound[i] = out[i].im;\n#endif\n    }\n    pk = peak(noise_sound, 8192);\n    ms = rms(noise_sound, 8192);\n    printf(\"Filtered noise level = %.2fdB, crest factor = %.2fdB\\n\", rms_to_dbm0(ms), rms_to_db(pk/ms));\n\n    for (i = 0;  i < 8192;  i++)\n        silence_sound[i] = 0.0;\n\n    for (i = 0;  i < 16;  i++)\n        sf_writef_short(filehandle, voiced_sound, voiced_length);\n    printf(\"%d samples of voice\\n\", 16*voiced_length);\n    sf_writef_short(filehandle, noise_sound, 8192);\n    sf_writef_short(filehandle, noise_sound, C1_NOISE_SAMPLES - 8192);\n    printf(\"%d samples of noise\\n\", C1_NOISE_SAMPLES);\n    sf_writef_short(filehandle, silence_sound, C1_SILENCE_SAMPLES);\n    printf(\"%d samples of silence\\n\", C1_SILENCE_SAMPLES);\n\n    /* Now phase invert the C1 set of samples. */\n    voiced_length = sizeof(css_c1)/sizeof(css_c1[0]);\n    for (i = 0;  i < voiced_length;  i++)\n        voiced_sound[i] = -css_c1[i];\n    for (i = 0;  i < 8192;  i++)\n        noise_sound[i] = -noise_sound[i];\n\n    for (i = 0;  i < 16;  i++)\n        sf_writef_short(filehandle, voiced_sound, voiced_length);\n    printf(\"%d samples of voice\\n\", 16*voiced_length);\n    sf_writef_short(filehandle, noise_sound, 8192);\n    sf_writef_short(filehandle, noise_sound, C1_NOISE_SAMPLES - 8192);\n    printf(\"%d samples of noise\\n\", C1_NOISE_SAMPLES);\n    sf_writef_short(filehandle, silence_sound, C1_SILENCE_SAMPLES);\n    printf(\"%d samples of silence\\n\", C1_SILENCE_SAMPLES);\n\n    if (sf_close(filehandle))\n    {\n        fprintf(stderr, \"    Cannot close speech file '%s'\\n\", \"sound_c1.wav\");\n        exit(2);\n    }\n\n    memset(&info, 0, sizeof(info));\n    info.frames = 0;\n    info.samplerate = FAST_SAMPLE_RATE;\n    info.channels = 1;\n    info.format = SF_FORMAT_WAV | SF_FORMAT_PCM_16;\n    info.sections = 1;\n    info.seekable = 1;\n    if ((filehandle = sf_open(\"sound_c3.wav\", SFM_WRITE, &info)) == NULL)\n    {\n        fprintf(stderr, \"    Failed to open result file\\n\");\n        exit(2);\n    }\n\n    printf(\"Generate C3\\n\");\n    /* The sequence is\n            72.69ms  of voiced sound from table C.3 of G.168\n            200.0ms  of pseudo-noise\n            127.31ms of silence\n       The above is then repeated phase inverted.\n\n       The voice comes straight from C.3, repeated enough times to\n       fill out the 72.69ms period - i.e. 14 copies of the sequence.\n\n       The pseudo noise section is AWGN filtered by the spectral\n       pattern in Figure C.2. Since AWGN has the quality of being its\n       own Fourier transform, we can use an approach like the one above\n       for the C1 signal, using AWGN samples instead of randomly alternating\n       ones and zeros. */\n\n    /* Take the supplied set of C3 voice samples. */\n    voiced_length = (sizeof(css_c3)/sizeof(css_c3[0]));\n    for (i = 0;  i < voiced_length;  i++)\n        voiced_sound[i] = css_c3[i];\n    pk = peak(voiced_sound, voiced_length);\n    ms = rms(voiced_sound, voiced_length);\n    printf(\"Voiced level = %.2fdB, crest factor = %.2fdB\\n\", rms_to_dbm0(ms), rms_to_db(pk/ms));\n\n    noise_source = awgn_init_dbm0(NULL, 7162534, rms_to_dbm0(ms));\n    for (i = 0;  i < 8192;  i++)\n        noise_sound[i] = awgn(noise_source);\n    pk = peak(noise_sound, 8192);\n    ms = rms(noise_sound, 8192);\n    printf(\"Unfiltered noise level = %.2fdB, crest factor = %.2fdB\\n\", rms_to_dbm0(ms), rms_to_db(pk/ms));\n\n    /* Now filter them */\n#if defined(HAVE_FFTW3_H)\n    p = fftw_plan_dft_1d(8192, in, out, FFTW_BACKWARD, FFTW_ESTIMATE);\n#else\n    p = fftw_create_plan(8192, FFTW_BACKWARD, FFTW_ESTIMATE);\n#endif\n    for (i = 0;  i < 8192;  i++)\n    {\n#if defined(HAVE_FFTW3_H)\n        in[i][0] = 0.0;\n        in[i][1] = 0.0;\n#else\n        in[i].re = 0.0;\n        in[i].im = 0.0;\n#endif\n    }\n    for (i = 1;  i <= 3715;  i++)\n    {\n        f = FAST_SAMPLE_RATE*i/8192.0;\n\n#if 1\n        if (f < 50.0)\n            scale = -60.0;\n        else if (f < 100.0)\n            scale = scaling(f, 50.0, 100.0, -25.8, -12.8);\n        else if (f < 200.0)\n            scale = scaling(f, 100.0, 200.0, -12.8, 17.4);\n        else if (f < 215.0)\n            scale = scaling(f, 200.0, 215.0, 17.4, 17.8);\n        else if (f < 500.0)\n            scale = scaling(f, 215.0, 500.0, 17.8, 12.2);\n        else if (f < 1000.0)\n            scale = scaling(f, 500.0, 1000.0, 12.2, 7.2);\n        else if (f < 2850.0)\n            scale = scaling(f, 1000.0, 2850.0, 7.2, 0.0);\n        else if (f < 3600.0)\n            scale = scaling(f, 2850.0, 3600.0, 0.0, -2.0);\n        else if (f < 3660.0)\n            scale = scaling(f, 3600.0, 3660.0, -2.0, -20.0);\n        else if (f < 3680.0)\n            scale = scaling(f, 3600.0, 3680.0, -20.0, -30.0);\n        else\n            scale = -60.0;\n#else\n        scale = 0.0;\n#endif\n#if defined(HAVE_FFTW3_H)\n        in[i][0] = noise_sound[i]*pow(10.0, scale/20.0)*0.0106;\n        in[8192 - i][0] = -in[i][0];\n#else\n        in[i].re = noise_sound[i]*pow(10.0, scale/20.0)*0.0106;\n        in[8192 - i].re = -in[i].re;\n#endif\n    }\n#if defined(HAVE_FFTW3_H)\n    fftw_execute(p);\n#else\n    fftw_one(p, in, out);\n#endif\n    for (i = 0;  i < 8192;  i++)\n    {\n#if defined(HAVE_FFTW3_H)\n        noise_sound[i] = out[i][1];\n#else\n        noise_sound[i] = out[i].im;\n#endif\n    }\n    pk = peak(noise_sound, 8192);\n    ms = rms(noise_sound, 8192);\n    printf(\"Filtered noise level = %.2fdB, crest factor = %.2fdB\\n\", rms_to_dbm0(ms), rms_to_db(pk/ms));\n\n    for (i = 0;  i < 14;  i++)\n        sf_writef_short(filehandle, voiced_sound, voiced_length);\n    printf(\"%d samples of voice\\n\", 14*voiced_length);\n    sf_writef_short(filehandle, noise_sound, 8192);\n    sf_writef_short(filehandle, noise_sound, C3_NOISE_SAMPLES - 8192);\n    printf(\"%d samples of noise\\n\", C3_NOISE_SAMPLES);\n    sf_writef_short(filehandle, silence_sound, C3_SILENCE_SAMPLES);\n    printf(\"%d samples of silence\\n\", C3_SILENCE_SAMPLES);\n\n    /* Now phase invert the C3 set of samples. */\n    voiced_length = (sizeof(css_c3)/sizeof(css_c3[0]));\n    for (i = 0;  i < voiced_length;  i++)\n        voiced_sound[i] = -css_c3[i];\n    for (i = 0;  i < 8192;  i++)\n        noise_sound[i] = -noise_sound[i];\n\n    for (i = 0;  i < 14;  i++)\n        sf_writef_short(filehandle, voiced_sound, voiced_length);\n    printf(\"%d samples of voice\\n\", 14*voiced_length);\n    sf_writef_short(filehandle, noise_sound, 8192);\n    sf_writef_short(filehandle, noise_sound, C3_NOISE_SAMPLES - 8192);\n    printf(\"%d samples of noise\\n\", C3_NOISE_SAMPLES);\n    sf_writef_short(filehandle, silence_sound, C3_SILENCE_SAMPLES);\n    printf(\"%d samples of silence\\n\", C3_SILENCE_SAMPLES);\n\n    if (sf_close(filehandle))\n    {\n        fprintf(stderr, \"    Cannot close speech file '%s'\\n\", \"sound_c3.wav\");\n        exit(2);\n    }\n\n    fftw_destroy_plan(p);\n    return 0;\n}\n/*- End of function --------------------------------------------------------*/\n/*- End of file ------------------------------------------------------------*/\n", "meta": {"hexsha": "0cb065783d3b39dbe3a2ac7979391c6daf016f8e", "size": 13642, "ext": "c", "lang": "C", "max_stars_repo_path": "VideoServer/libs/spandsp/tests/make_g168_css.c", "max_stars_repo_name": "zengfanmao/mpds", "max_stars_repo_head_hexsha": "c2bba464eaddc9ec70604a8614d84c5334461e8e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "VideoServer/libs/spandsp/tests/make_g168_css.c", "max_issues_repo_name": "zengfanmao/mpds", "max_issues_repo_head_hexsha": "c2bba464eaddc9ec70604a8614d84c5334461e8e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "VideoServer/libs/spandsp/tests/make_g168_css.c", "max_forks_repo_name": "zengfanmao/mpds", "max_forks_repo_head_hexsha": "c2bba464eaddc9ec70604a8614d84c5334461e8e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7255813953, "max_line_length": 106, "alphanum_fraction": 0.5845183991, "num_tokens": 4373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713671682749474, "lm_q2_score": 0.04084571226127504, "lm_q1q2_score": 0.018672074799599817}}
{"text": "/* this manages and calls function to execute function\n* from beginning to end\n*/\n#include <stdio.h>\n#include <string.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_eigen.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_statistics.h>\n\n#include \"fileio.h\"\n#include \"data_process.h\"\n#include \"sensor_history.h\"\n#include \"sensor_validation.h\"\n\n#include \"externs.h\"\n\nvoid handle_files(char *, double*, double*);\nvoid sensor_validation(double*);\ndouble data_processing(double*);\n\nint sensor_number;\nint temperature_min = 30;\nint temperature_max = 60;\nint data_number;\nint group_number;\nfloat q_percent;\n\n/* path and names of the files used in the program\n* which include input file, output file and sensor history file */\nchar input_file_name[255] = \"../data/input_data/sample_input.csv\";\nchar history_file_name[255] = \"../data/sensor_history/sensor_history.csv\";\nchar output_file_name[255] = \"../data/output_data/output.csv\";\n\n\nint main() {\n\n    printf(\"\\nApplication is running....\\n\");\n    \n    /* user input for the number of sensors to process */\n    printf(\"Insert number of sensors:\");\n    scanf(\"%d\", &sensor_number);\n    \n    /* determining the time intervals for the sensors */\n    int time_interval;\n\n    printf(\"Insert collected time intervals:\");\n    scanf(\"%d\", &time_interval);\n\n    printf(\"Insert q percent(Should be 0~1):\");\n    scanf(\"%f\", &q_percent);\n\n    if ((q_percent<0) || (q_percent>1)) {\n        printf(\"Invalid q_percent! It will be regarded as 0.7 of default value.\\n\");\n        q_percent = 0.7;\n    }\n\n    double values[256];\n    double time_value[256];\n    double group_values[sensor_number];\n    \n    /* function performs reading of sensor data\n    * @input : file name\n    * @output : sensor time and associated values\n    */\n    handle_files(input_file_name, &time_value[0], &values[0]);\n\n    /* number of calculations to be performed based on the user input */\n    group_number = data_number / sensor_number;\n\n    for (int i = 0; i < group_number; i++) {\n        time_value[i] = time_value[i * sensor_number];\n    }\n\n    /* check whether the user input and actual file data matches */\n    if (group_number != time_interval) {\n        printf(\"ERROR: Time interval numbers, sensor numbers do not match with your input file!\\n\");\n        exit(0);\n    }\n\n    sensor_validation(&values[0]);\n\n    /* seperating multiple data computations in the output file*/\n    FILE *fpout = fopen(output_file_name, \"a\");\n    fprintf(fpout, \"--------------\\n\");\n    fclose(fpout);\n\n    FILE *fphis = fopen(history_file_name, \"a\");\n    fprintf(fphis, \"--------------\\n\");\n    fclose(fphis);\n\n    for (int i = 0 ; i < group_number; i++) {\n        for (int j = 0; j < sensor_number; j++) {\n            group_values[j]  = values[i*sensor_number + j];\n        }\n        printf(\"\\n---------------------Time interval %d---------------------\\n\\n\", i);\n        \n        double fused = data_processing(&group_values[0]);\n        float time_val_file = (float)time_value[i];\n        \n        write_data(time_val_file, fused, output_file_name);\n    }\n\n    \n\n    return 1;\n}\n\n/* function checks whether an attempt made to open a file is succuessful or not */\nvoid handle_files(char* input_file_name, double* time_value, double* values) {\n    printf(\"\\n\");\n    if (input_file_name != NULL) {\n        data_number = read_data(&time_value[0], &values[0], input_file_name);    \n\n        if ( data_number == -1 ) {\n            printf(\"ERROR: File open failed!\\n\");\n            exit(0);\n        } else if ( data_number == 0 ) {\n            printf(\"ERROR: Sensor numbers inserted and file are different!\\n\");\n            exit(0);\n        } else if ( data_number > 0) {\n            printf(\"Read data successfully!\\n\");\n        }    \n    } else {\n        printf(\"ERROR: Input file does not exist!\\n\");\n        exit(0);\n    }\n}\n\n/* function performs sensor validation for group values\n* @input : group Values\n*/\nvoid sensor_validation(double* group_values) {\n\n    int res = reading_validation(&group_values[0]);\n    if (res == 1) {\n        frozen_value_check(&group_values[0]);\n\n    }\n\n    if (res == 0) {\n        printf(\"ERROR: Temperature values are out of range! Check history file.\\n\");\n        frozen_value_check(&group_values[0]);\n    } \n\n}\n\n/* function performs sensor fusion algo using group Values\n* @input : group Values\n* @output : fused result\n*/\ndouble data_processing(double* group_values) {\n\n    printf(\"Sensor Values:\\n\");\n\n    for (int i = 0; i < sensor_number; i++) {\n        printf(\"x%d=%f, \", i, group_values[i]);\n    }\n    \n    /* Step 1: Calc the Support Degree Matrix */\n    gsl_matrix* D = gsl_matrix_alloc(sensor_number,sensor_number); \n    support_degree_generator(D, &group_values[0]);    //function in data_process.c to get D - Support Degree Matrix\n\n\n\n    /* Step 2: Calc eigenval & eigenvec */\n    gsl_matrix* T = gsl_matrix_alloc(sensor_number,sensor_number);\n    gsl_vector* evec = gsl_vector_alloc(sensor_number);\n    gsl_matrix* Temp = gsl_matrix_alloc(sensor_number,sensor_number);\n\n    gsl_matrix_memcpy(Temp, D);\n    eigenvec_calc(evec, T, Temp);    //function in data_process.c to get evec - eigen group_values & T - vectors\n\n\n\n    /* Step 3: Principal Comp Calc */\n    gsl_matrix* y = gsl_matrix_alloc(sensor_number,sensor_number);\n    principal_comp_calc(T, D, y);    //function in data_process.c to get T - Principal Components \n\n\n\n    /* Step 4: Calc the contri rate of the kth principal comp */\n    double alpha[sensor_number];\n    contri_rate_calc_kth(evec, &alpha[0]);    //function in data_process.c to get alpha\n\n\n\n    /* Step 5: Calc the contri rate of the m principal comp */\n    double phi[sensor_number];\n    major_contri_calc(&alpha[0], &phi[0]);    //function in data_process.c to get phi\n\n\n\n    /* Step 6: Compute the integrated support degree score */\n    gsl_vector* Z = gsl_vector_alloc(sensor_number);\n    integ_supp_score_calc(&alpha[0], y, Z);    //function in data_process.c to get z_i\n\n\n\n    /* Step 7-1: Eliminate incorrect data */\n    int sensor_correction[sensor_number];\n    elliminate_incorrect_data(Z, &sensor_correction[0]);    //function in data_process.c to elliminate incorrect datas\n\n\n\n    /* Step 7-2: Compute the weight coefficient for each sensor */\n    double omega[sensor_number];\n    weight_coeff_calc(Z, &sensor_correction[0], &omega[0]);     //function in data_process.c to get omega\n\n\n\n    /* Step 7-3: Compute the fused output */\n    double fused;\n    fused = fused_output(&omega[0], &group_values[0]);    //function in data_process.c to get fused output\n    printf(\"FINAL STEP: \\nThe fused output is %f\\n\", fused);\n\n\n\n    /* Free memory */\n    gsl_matrix_free(D);\n    gsl_matrix_free(Temp);\n    gsl_matrix_free(T);\n    gsl_vector_free(evec);\n    gsl_matrix_free(y);\n    gsl_vector_free(Z);\n\n    return fused;\n\n}\n", "meta": {"hexsha": "998861dcf45a18103bf8f05d19e68a57933d34fb", "size": 6779, "ext": "c", "lang": "C", "max_stars_repo_path": "src/main.c", "max_stars_repo_name": "karanbirsandhu/nu-sense", "max_stars_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/main.c", "max_issues_repo_name": "karanbirsandhu/nu-sense", "max_issues_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "src/main.c", "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4739130435, "max_line_length": 118, "alphanum_fraction": 0.6481781974, "num_tokens": 1661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473631961697, "lm_q2_score": 0.04336579830027346, "lm_q1q2_score": 0.01865368379175957}}
{"text": "#include \"jobqueue.h\"\r\n#include \"ance_degnome.h\"\r\n#include \"fitfunc.h\"\r\n#include \"flagparse.c\"\r\n#include <stdio.h>\r\n#include <string.h>\r\n#include <gsl/gsl_rng.h>\r\n#include <gsl/gsl_randist.h>\r\n#include <time.h>\r\n#include <pthread.h>\r\n#include <unistd.h>\r\n#include <limits.h>\r\n\r\ntypedef struct JobData JobData;\r\nstruct JobData {\r\n\tDegnome* child;\r\n\tDegnome* p1;\r\n\tDegnome* p2;\r\n};\r\n\r\nvoid usage(void);\r\nvoid help_menu(void);\r\nint jobfunc(void* p, void* tdat);\r\nvoid calculate_diversity(Degnome* generation, double** percent_decent, double* diversity);\r\n\r\nconst char* usageMsg =\r\n\t\"Usage: devosim [-bhrv] [-s | -u] [-c chromosome_length]\\n\"\r\n\t\"\\t\\t  [-e mutation_effect] [-g num_generations]\\n\"\r\n\t\"\\t\\t  [-m mutation_rate] [-o crossover_rate]\\n\"\r\n\t\"\\t\\t  [-p population_size] [-t num_threads]\\n\"\r\n\t\"\\t\\t  [--seed rngseed] [--target hat_height target]\\n\"\r\n\t\"\\t\\t  [--sqrt | --linear | --close | --ceiling | --log]\\n\";\r\n\r\nconst char* helpMsg =\r\n\t\"OPTIONS\\n\"\r\n\t\"\\t -b\\t Simulation will stop when all degnomes are identical.\\n\\n\"\r\n\t\"\\t -c chromosome_length\\n\"\r\n\t\"\\t\\t Set chromosome length for the current simulation.\\n\"\r\n\t\"\\t\\t Default chromosome length is 10.\\n\\n\"\r\n\t\"\\t -e mutation_effect\\n\"\r\n\t\"\\t\\t Set how much a mutation will effect a gene on average.\\n\"\r\n\t\"\\t\\t Default mutation effect is 2.\\n\\n\"\r\n\t\"\\t -g num_generations\\n\"\r\n\t\"\\t\\t Set how many generations this simulation will run for.\\n\"\r\n\t\"\\t\\t Default number of generations is 1000.\\n\\n\"\r\n\t\"\\t -h\\t Display this help menu.\\n\\n\"\r\n\t\"\\t -m mutation_rate\\n\"\r\n\t\"\\t\\t Set the mutation rate for the current simulation.\\n\"\r\n\t\"\\t\\t Default mutation rate is 1.\\n\\n\"\r\n\t\"\\t -o crossover_rate\\n\"\r\n\t\"\\t\\t Set the crossover rate for the current simulation.\\n\"\r\n\t\"\\t\\t Default crossover rate is 2.\\n\\n\"\r\n\t\"\\t -p population_size\\n\"\r\n\t\"\\t\\t Set the population size for the current simulation.\\n\"\r\n\t\"\\t\\t Default population size is 10.\\n\\n\"\r\n\t\"\\t -r\\t Only show percentages of descent from the original genomes.\\n\\n\"\r\n\t\"\\t -s\\t Degnome selection will occur.\\n\\n\"\r\n\t\"\\t -u\\t All degnomes contribute to two offspring.\\n\\n\"\r\n\t\"\\t -v\\t Output will be given for every generation.\\n\\n\"\r\n\t\"\\t -t num_threads\\n\"\r\n\t\"\\t\\t Select the number of threads to be used in the current run.\\n\"\r\n\t\"\\t\\t Default is 0 (which will result in 3/4 of cores being used).\\n\"\r\n\t\"\\t\\t Must be 1 if a seed is used in order to prevent race conditions.\\n\\n\"\r\n\t\"\\t --seed rngseed\\n\"\r\n\t\"\\t\\t Select the seed used by the RNG in the current run.\\n\"\r\n\t\"\\t\\t Default seed is 0 (which will result in a random seed).\\n\\n\"\r\n\t\"\\t --target hat_height target\\n\"\r\n\t\"\\t\\t Sets the ideal hat height for the current simulation\\n\"\r\n\t\"\\t\\t Used for fitness functions that have an \\\"ideal\\\" value.\\n\\n\"\r\n\t\"\\t --sqrt\\t\\t fitness will be sqrt(hat_height)\\n\\n\"\r\n\t\"\\t --linear\\t fitness will be hat_height\\n\\n\"\r\n\t\"\\t --close\\t fitness will be (target - abs(target - hat_height))\\n\\n\"\r\n\t\"\\t --ceiling\\t fitness will quickly level off after passing target\\n\\n\";\r\n\r\npthread_mutex_t seedLock = PTHREAD_MUTEX_INITIALIZER;\r\nunsigned long rngseed=0;\r\n\r\n//\tthere is no need for the line 'int chrom_size' as it is declared as a global variable in degnome.h\r\nint pop_size;\r\nint num_gens;\r\nint mutation_rate;\r\nint mutation_effect;\r\nint crossover_rate;\r\nint selective;\r\nint uniform;\r\nint verbose;\r\nint reduced;\r\nint break_at_zero_diversity;\r\n\r\nvoid usage(void) {\r\n\tfputs(usageMsg, stderr);\r\n\texit(EXIT_FAILURE);\r\n}\r\n\r\nvoid help_menu(void) {\r\n\tfputs(helpMsg, stderr);\r\n\texit(EXIT_FAILURE);\r\n}\r\n\r\nint num_threads = 0;\r\nJobQueue* jq;\r\n\r\nvoid *ThreadState_new(void *notused);\r\nvoid ThreadState_free(void *rng);\r\n\r\nvoid *ThreadState_new(void *notused) {\r\n\t// Lock seed, initialize random number generator, increment seed,\r\n\t// and unlock.\r\n\tgsl_rng *rng = gsl_rng_alloc(gsl_rng_taus);\r\n\r\n\tpthread_mutex_lock(&seedLock);\r\n\tgsl_rng_set(rng, rngseed);\r\n\trngseed = (rngseed == ULONG_MAX ? 0 : rngseed + 1);\r\n\tpthread_mutex_unlock(&seedLock);\r\n\r\n\treturn rng;\r\n}\r\n\r\nvoid ThreadState_free(void *rng) {\r\n\tgsl_rng_free((gsl_rng *) rng);\r\n}\r\n\r\nint jobfunc(void* p, void* tdat) {\r\n\tgsl_rng* rng = (gsl_rng*) tdat;\r\n\tJobData* data = (JobData*) p;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//get data out\r\n\tDegnome_mate(data->child, data->p1, data->p2, rng, mutation_rate, mutation_effect, crossover_rate);\t\t\t//mate\r\n\r\n\treturn 0;\t\t//exited without error\r\n}\r\n\r\nvoid calculate_diversity(Degnome* generation, double** percent_decent, double* diversity) {\r\n\t*diversity = 0;\r\n\tfor (int i = 0; i < pop_size; i++) {\t\t\t//calculate percent decent for each degnome\r\n\t\tfor (int j = 0; j < pop_size; j++) {\r\n\t\t\tpercent_decent[i][j] = 0;\r\n\t\t\tfor (int k = 0; k < chrom_size; k++) {\r\n\t\t\t\tif (generation[i].GOI_array[k] == j) {\r\n\t\t\t\t\tpercent_decent[i][j]++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tpercent_decent[i][j] /= chrom_size;\r\n\t\t}\r\n\t}\r\n\tfor (int j = 0; j < pop_size; j++) {\t\t\t//sum and average\r\n\t\tpercent_decent[pop_size][j] = 0;\r\n\t\tfor (int k = 0; k < pop_size; k++) {\r\n\t\t\tpercent_decent[pop_size][j] += percent_decent[k][j];\r\n\t\t}\r\n\t\tpercent_decent[pop_size][j] /= pop_size;\r\n\t}\r\n\r\n\tfor (int i = 0; i < pop_size; i++) {\t\t\t//calculate percent diversity for the entire generation\r\n\t\tfor (int j = 0; j < pop_size; j++) {\r\n\t\t\tif (i == j) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tfor (int k = 0; k < chrom_size; k++) {\r\n\t\t\t\tif (generation[i].GOI_array[k] != generation[j].GOI_array[k]) {\r\n\t\t\t\t\t(*diversity)++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t*diversity /= ((pop_size-1) * pop_size * chrom_size);\r\n}\r\n\r\nint main(int argc, char **argv) {\r\n\r\n\tint * flags = NULL;\r\n\r\n\tif (parse_flags(argc, argv, 3, &flags) == -1) {\r\n\t\tfree(flags);\r\n\t\tusage();\r\n\t}\r\n\r\n\tif (flags[2] == 1) {\r\n\t\tfree(flags);\r\n\t\thelp_menu();\r\n\t}\r\n\r\n\tbreak_at_zero_diversity = flags[1];\r\n\treduced = flags[3];\r\n\tverbose = flags[4];\r\n\tif (flags[5] == 1) {\r\n\t\tselective = 1;\r\n\t}\r\n\telse if (flags[5] == 2) {\r\n\t\tuniform = 1;\r\n\t}\r\n\tchrom_size = flags[6];\r\n\tmutation_effect = flags[7];\r\n\tnum_gens = flags[8];\r\n\tmutation_rate = flags[9];\r\n\tcrossover_rate = flags[10];\r\n\tpop_size = flags[11];\r\n\r\n\tnum_threads = flags[12];\r\n\r\n\tif(flags[13] == 0){\r\n\t\tset_function(\"linear\");\r\n\t}\r\n\telse if(flags[13] == 1){\r\n\t\tset_function(\"sqrt\");\r\n\t}\r\n\telse if(flags[13] == 2){\r\n\t\tset_function(\"close\");\r\n\t}\r\n\telse if(flags[13] == 3){\r\n\t\tset_function(\"ceiling\");\r\n\t}\r\n\telse if(flags[13] == 4){\r\n\t\tset_function(\"log\");\r\n\t}\r\n\r\n\ttarget_num = flags[14];\r\n\r\n\tif(flags[15] <= 0) {\r\n\t\ttime_t currtime = time(NULL);                  // time\r\n\t\tunsigned long pid = (unsigned long) getpid();  // process id\r\n\t\trngseed = currtime ^ pid;                      // random seed\r\n\t}\r\n\telse{\r\n\t\trngseed = flags[15];\r\n\t}\r\n\tgsl_rng* rng = gsl_rng_alloc(gsl_rng_taus);    // rand generator\r\n\tgsl_rng_set(rng, rngseed);\r\n\r\n\tfree(flags);\r\n\r\n\r\n\tif (num_threads <= 0) {\r\n\t\tif (num_threads < 0) {\r\n\t\t\t#ifdef DEBUG_MODE\r\n\t\t\t\tfprintf(stderr, \"Error invalid number of threads: %u\\n\", num_threads);\r\n\t\t\t#endif\r\n\t\t}\r\n\t\tnum_threads = (3*getNumCores()/4);\r\n\t}\r\n\t#ifdef DEBUG_MODE\r\n\t\tfprintf(stderr, \"Final number of threads: %u\\n\", num_threads);\r\n\t#endif\r\n\r\n\tDegnome* parents;\r\n\tDegnome* children;\r\n\tDegnome* temp;\r\n\r\n\tprintf(\"%u, %u, %u\\n\", chrom_size, pop_size, num_gens);\r\n\r\n\tparents = malloc(pop_size*sizeof(Degnome));\r\n\tchildren = malloc(pop_size*sizeof(Degnome));\r\n\r\n\tfor (int i = 0; i < pop_size; i++) {\r\n\t\tparents[i].dna_array = malloc(chrom_size*sizeof(double));\r\n\t\tparents[i].GOI_array = malloc(chrom_size*sizeof(int));\r\n\r\n\t\tchildren[i].dna_array = malloc(chrom_size*sizeof(double));\r\n\t\tchildren[i].GOI_array = malloc(chrom_size*sizeof(int));\r\n\r\n\t\tparents[i].hat_size = 0;\r\n\r\n\t\tfor (int j = 0; j < chrom_size; j++) {\r\n\t\t\tparents[i].dna_array[j] = 10;\t//children aren't initialized\r\n\t\t\tparents[i].hat_size += 10;\r\n\t\t\tparents[i].GOI_array[j] = (i);\t//track ancestries\r\n\t\t}\r\n\t}\r\n\r\n\tdouble* diversity;\r\n\tdouble** percent_decent;\r\n\r\n\tdiversity = malloc(sizeof(double));\r\n\t*diversity = 1;\r\n\tpercent_decent = malloc((pop_size+1)*sizeof(double*));\r\n\tfor (int i = 0; i < pop_size+1; i++) {\r\n\t\tpercent_decent[i] = malloc(pop_size*sizeof(double));\r\n\t\tif (i == pop_size) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tfor (int j = 0; j < pop_size; j++) {\r\n\t\t\tif (i == j) {\r\n\t\t\t\tpercent_decent[i][j] = 1;\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tpercent_decent[i][j] = 0;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tif (!reduced && !verbose) {\r\n\t\tprintf(\"\\nGeneration 0:\\n\\n\");\r\n\t\tfor (int i = 0; i < pop_size; i++) {\r\n\t\t\tprintf(\"Degnome %u allele values:\\n\", i);\r\n\t\t\tif (!reduced) {\r\n\t\t\t\tfor (int j = 0; j < chrom_size; j++) {\r\n\t\t\t\t\tprintf(\"%lf\\t\", parents[i].dna_array[j]);\r\n\t\t\t\t}\r\n\t\t\t\tprintf(\"\\n\");\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tprintf(\"%lf\\n\", parents[i].dna_array[0]);\r\n\t\t\t}\r\n\r\n\t\t\tprintf(\"Degnome %u ancestries:\\n\", i);\r\n\t\t\tif (!reduced) {\r\n\t\t\t\tfor (int j = 0; j < chrom_size; j++) {\r\n\t\t\t\t\tprintf(\"%u\\t\", parents[i].GOI_array[j]);\r\n\t\t\t\t}\r\n\t\t\t\tprintf(\"\\n\");\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tprintf(\"%u\\n\", parents[i].GOI_array[0]);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tprintf(\"\\n\\n\");\r\n\r\n\tint final_gen;\r\n\tint broke_early = 0;\r\n\r\n\tjq = JobQueue_new(num_threads, NULL, ThreadState_new, ThreadState_free);\r\n\r\n\tJobData* dat = malloc(pop_size*sizeof(JobData));\r\n\r\n\tfor (int i = 0; i < num_gens; i++) {\r\n\t\tif (break_at_zero_diversity) {\r\n\t\t\tcalculate_diversity(parents, percent_decent, diversity);\r\n\t\t\tif ((*diversity) <= 0) {\r\n\t\t\t\tfinal_gen = i;\r\n\t\t\t\tbroke_early = 1;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (!uniform) {\r\n\t\t\tdouble fit;\r\n\t\t\tif (selective) {\r\n\t\t\t\tfit = get_fitness(parents[0].hat_size);\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tfit = 100;\t\t\t//in runs withoutslection, everybody is equally fit\r\n\t\t\t}\r\n\r\n\t\t\tdouble total_hat_size = fit;\r\n\t\t\tdouble cum_hat_size[pop_size];\r\n\t\t\tcum_hat_size[0] = fit;\r\n\r\n\t\t\tfor (int j = 1; j < pop_size; j++) {\r\n\t\t\t\tif (selective) {\r\n\t\t\t\t\tfit = get_fitness(parents[j].hat_size);\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tfit = 100;\r\n\t\t\t\t}\r\n\r\n\t\t\t\ttotal_hat_size += fit;\r\n\t\t\t\tcum_hat_size[j] = (cum_hat_size[j-1] + fit);\r\n\t\t\t}\r\n\r\n\t\t\tfor (int j = 0; j < pop_size; j++) {\r\n\r\n\t\t\t\tpthread_mutex_lock(&seedLock);\r\n\t\t\t\tgsl_rng_set(rng, rngseed);\r\n\t\t\t\trngseed = (rngseed == ULONG_MAX ? 0 : rngseed + 1);\r\n\t\t\t\tpthread_mutex_unlock(&seedLock);\r\n\r\n\t\t\t\tint m, d;\r\n\r\n\t\t\t\tdouble win_m = gsl_rng_uniform(rng);\r\n\t\t\t\twin_m *= total_hat_size;\r\n\t\t\t\tdouble win_d = gsl_rng_uniform(rng);\r\n\t\t\t\twin_d *= total_hat_size;\r\n\r\n\t\t\t\t// printf(\"win_m:%lf, wind:%lf, max: %lf\\n\", win_m,win_d,total_hat_size);\r\n\r\n\t\t\t\tfor (m = 0; cum_hat_size[m] < win_m; m++) {\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tfor (d = 0; cum_hat_size[d] < win_d; d++) {\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// printf(\"m:%u, d:%u\\n\", m,d);\t\t\t\t\r\n\t\t\t\tdat[j].child = (children + j);\r\n\t\t\t\tdat[j].p1 = (parents + m);\r\n\t\t\t\tdat[j].p2 = (parents + d);\r\n\r\n\t\t\t\tJobQueue_addJob(jq, jobfunc, dat + j);\t\t\t}\r\n\t\t}\r\n\t\telse {\r\n\t\t\t// printf(\"uniform!!!\\n\");\r\n\r\n\t\t\tint moms[pop_size];\r\n\t\t\tint dads[pop_size];\r\n\t\t\tint mom_max = pop_size;\r\n\t\t\tint dad_max = pop_size;\r\n\r\n\t\t\tint m, d;\r\n\r\n\t\t\tfor (int j = 0; j < pop_size; j++) {\r\n\t\t\t\tmoms[j] = j;\r\n\t\t\t\tdads[j] = j;\r\n\t\t\t}\r\n\r\n\t\t\tfor (int j = 0; j < pop_size; j++) {\r\n\t\t\t\tpthread_mutex_lock(&seedLock);\r\n\t\t\t\tgsl_rng_set(rng, rngseed);\r\n\t\t\t\trngseed = (rngseed == ULONG_MAX ? 0 : rngseed + 1);\r\n\r\n\t\t\t\tpthread_mutex_unlock(&seedLock);\r\n\r\n\t\t\t\tint index_m = (int) gsl_rng_uniform_int (rng, mom_max);\r\n\t\t\t\tint index_d = (int) gsl_rng_uniform_int (rng, dad_max);\r\n\r\n\t\t\t\tm = moms[index_m];\r\n\t\t\t\td = dads[index_d];\r\n\r\n\t\t\t\t// printf(\"m:\\t%u\\nd:\\t%u\\n\", m, d);\r\n\r\n\t\t\t\t//reduce the pool of available degnomes\r\n\t\t\t\t//in order to make sure everybody get's two chances to mate\r\n\t\t\t\t//one as a dad and one as a mom\r\n\t\t\t\t\r\n\t\t\t\tint temp_m = moms[index_m];\r\n\t\t\t\tint temp_d = dads[index_d];\r\n\t\t\t\tmoms[index_m] = moms[mom_max-1];\r\n\t\t\t\tdads[index_d] = dads[dad_max-1];\r\n\t\t\t\tmoms[mom_max-1] = temp_m;\r\n\t\t\t\tdads[dad_max-1] = temp_d;\r\n\r\n\t\t\t\tmom_max--;\r\n\t\t\t\tdad_max--;\t\t\t\t\r\n\r\n\t\t\t\tdat[j].child = (children + j);\r\n\t\t\t\tdat[j].p1 = (parents + m);\r\n\t\t\t\tdat[j].p2 = (parents + d);\r\n\r\n\t\t\t\tJobQueue_addJob(jq, jobfunc, dat + j);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tJobQueue_waitOnJobs(jq);\r\n\r\n\t\ttemp = children;\r\n\t\tchildren = parents;\r\n\t\tparents = temp;\r\n\t\tif (verbose) {\r\n\t\t\tcalculate_diversity(parents, percent_decent, diversity);\r\n\t\t\tprintf(\"\\nGeneration %u:\\n\", i);\r\n\t\t\tif (!reduced) {\r\n\t\t\t\tfor (int k = 0; k < pop_size; k++) {\r\n\t\t\t\t\tprintf(\"\\n\\nDegnome %u allele values:\\n\", k);\r\n\r\n\t\t\t\t\tfor (int j = 0; j < chrom_size; j++) {\r\n\t\t\t\t\t\tprintf(\"%lf\\t\", parents[k].dna_array[j]);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (selective) {\r\n\t\t\t\t\t\tprintf(\"\\nTOTAL HAT SIZE: %lg\\n\\n\", parents[k].hat_size);\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse {\r\n\t\t\t\t\t\tprintf(\"\\n\");\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tprintf(\"\\n\\nDegnome %u ancestries:\\n\", k);\r\n\t\t\t\t\tfor (int j = 0; j < chrom_size; j++) {\r\n\t\t\t\t\t\tprintf(\"%u\\t\", parents[k].GOI_array[j]);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tprintf(\"\\n\");\r\n\r\n\t\t\t\t\tfor (int j = 0; j < pop_size; j++) {\r\n\t\t\t\t\t\tif (percent_decent[k][j] > 0) {\r\n\t\t\t\t\t\t\tprintf(\"%lf%% Degnome %u\\t\", (100*percent_decent[k][j]), j);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tprintf(\"\\nAverage population descent percentages:\\n\");\r\n\t\t\tfor (int j = 0; j < pop_size; j++) {\r\n\t\t\t\tif (percent_decent[pop_size][j] > 0) {\r\n\t\t\t\t\tprintf(\"%lf%% Degnome %u\\t\", (100*percent_decent[pop_size][j]), j);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tprintf(\"\\nPercent diversity: %lf\\n\", (100* (*diversity)));\r\n\t\tprintf(\"\\n\\n\");\r\n\t\t}\r\n\t}\r\n\r\n\tJobQueue_noMoreJobs(jq);\r\n\r\n\tif (verbose) {\r\n\t\tprintf(\"\\n\");\r\n\t}\r\n\r\n\tcalculate_diversity(parents, percent_decent, diversity);\r\n\t// printf(\"\\n\\n DIVERSITY%lf\\n\\n\\n\", *diversity);\r\n\tif (broke_early) {\r\n\t\tprintf(\"Generation %u:\\n\", final_gen);\r\n\t}\r\n\telse {\r\n\t\tprintf(\"Generation %u:\\n\", num_gens);\r\n\t}\r\n\tif (!reduced) {\r\n\t\tfor (int i = 0; i < pop_size; i++) {\r\n\t\t\tprintf(\"\\n\\nDegnome %u allele values:\\n\", i);\t\t\r\n\t\t\tif (!reduced) {\r\n\t\t\t\tfor (int j = 0; j < chrom_size; j++) {\r\n\t\t\t\t\tprintf(\"%lf\\t\", parents[i].dna_array[j]);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tprintf(\"\\n\\nDegnome %u ancestries:\\n\", i);\r\n\t\t\tif (!reduced) {\r\n\t\t\t\tfor (int j = 0; j < chrom_size; j++) {\r\n\t\t\t\t\tprintf(\"%u\\t\", parents[i].GOI_array[j]);\r\n\t\t\t\t}\r\n\t\t\t\tprintf(\"\\n\");\r\n\t\t\t}\r\n\r\n\t\t\tfor (int j = 0; j < pop_size; j++) {\r\n\t\t\t\tif (percent_decent[i][j] > 0) {\r\n\t\t\t\t\tprintf(\"%lf%% Degnome %u\\t\", (100*percent_decent[i][j]), j);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tprintf(\"\\n\");\r\n\r\n\t\t\tif (selective) {\r\n\t\t\t\tprintf(\"\\nTOTAL HAT SIZE: %lg\\n\\n\", parents[i].hat_size);\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tprintf(\"\\n\\n\");\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tprintf(\"Average population decent percentages:\\n\");\r\n\tfor (int j = 0; j < pop_size; j++) {\r\n\t\tif (percent_decent[pop_size][j] > 0) {\r\n\t\t\tprintf(\"%lf%% Degnome %u\\t\", (100*percent_decent[pop_size][j]), j);\r\n\t\t}\r\n\t}\r\n\tprintf(\"\\nPercent diversity: %lf\\n\", (100* (*diversity)));\r\n\tprintf(\"\\n\\n\\n\");\r\n\r\n\t//free everything\r\n\tJobQueue_free(jq);\r\n\tfree(dat);\r\n\r\n\tfor (int i = 0; i < pop_size; i++) {\r\n\t\tfree(parents[i].dna_array);\r\n\t\tfree(children[i].dna_array);\r\n\t\tfree(parents[i].GOI_array);\r\n\t\tfree(children[i].GOI_array);\r\n\t\tparents[i].hat_size = 0;\r\n\r\n\t\tfree(percent_decent[i]);\r\n\t}\r\n\tfree(percent_decent[pop_size]);\r\n\r\n\tfree(parents);\r\n\tfree(children);\r\n\r\n\tfree(percent_decent);\r\n\tfree(diversity);\r\n\r\n\tgsl_rng_free (rng);\r\n}\r\n", "meta": {"hexsha": "1866aa5e3a62c2d5f31f31d27da219d15160048e", "size": 14726, "ext": "c", "lang": "C", "max_stars_repo_path": "src/devosim.c", "max_stars_repo_name": "masalemi/PopGenSim", "max_stars_repo_head_hexsha": "86bbd44f9ad6b588253b6115c7064e91c2d0d76f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-08-14T20:45:40.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-01T18:53:36.000Z", "max_issues_repo_path": "src/devosim.c", "max_issues_repo_name": "masalemi/PopGenSim", "max_issues_repo_head_hexsha": "86bbd44f9ad6b588253b6115c7064e91c2d0d76f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2019-09-17T20:12:17.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T23:56:03.000Z", "max_forks_repo_path": "src/devosim.c", "max_forks_repo_name": "masalemi/PopGenSim", "max_forks_repo_head_hexsha": "86bbd44f9ad6b588253b6115c7064e91c2d0d76f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-27T23:28:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-27T23:28:50.000Z", "avg_line_length": 26.0637168142, "max_line_length": 110, "alphanum_fraction": 0.5907917968, "num_tokens": 4597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.037892427308664316, "lm_q1q2_score": 0.018650203154987253}}
{"text": "/***************************************************************************/\n/*                                                                         */\n/* matrix.c - Matrix class for mruby                                       */\n/* Copyright (C) 2015 Paolo Bosetti                                        */\n/* paolo[dot]bosetti[at]unitn.it                                           */\n/* Department of Industrial Engineering, University of Trento              */\n/*                                                                         */\n/* This library is free software.  You can redistribute it and/or          */\n/* modify it under the terms of the GNU GENERAL PUBLIC LICENSE 2.0.        */\n/*                                                                         */\n/* This library is distributed in the hope that it will be useful,         */\n/* but WITHOUT ANY WARRANTY; without even the implied warranty of          */\n/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the           */\n/* Artistic License 2.0 for more details.                                  */\n/*                                                                         */\n/* See the file LICENSE                                                    */\n/*                                                                         */\n/***************************************************************************/\n\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_rng.h>\n#include \"matrix.h\"\n#include \"vector.h\"\n\n#pragma mark -\n#pragma mark \u2022 Utilities\n\n// Garbage collector handler, for play_data struct\n// if play_data contains other dynamic data, free it too!\n// Check it with GC.start\nvoid matrix_destructor(mrb_state *mrb, void *p_) {\n  gsl_matrix *v = (gsl_matrix *)p_;\n  gsl_matrix_free(v);\n};\n\n// Creating data type and reference for GC, in a const struct\nconst struct mrb_data_type matrix_data_type = {\"matrix_data\",\n                                               matrix_destructor};\n\n// Utility function for getting the struct out of the wrapping IV @data\nvoid mrb_matrix_get_data(mrb_state *mrb, mrb_value self, gsl_matrix **data) {\n  mrb_value data_value;\n  data_value = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, \"@data\"));\n\n  // Loading data from data_value into p_data:\n  Data_Get_Struct(mrb, data_value, &matrix_data_type, *data);\n  if (!*data)\n    mrb_raise(mrb, E_RUNTIME_ERROR, \"Could not access @data\");\n}\n\n#pragma mark -\n#pragma mark \u2022 Initializations and setup\n\n// Data Initializer C function (not exposed!)\nstatic void mrb_matrix_init(mrb_state *mrb, mrb_value self, mrb_int n,\n                            mrb_int m) {\n  mrb_value data_value; // this IV holds the data\n  gsl_matrix *p_data;   // pointer to the C struct\n\n  data_value = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, \"@data\"));\n\n  // if @data already exists, free its content:\n  if (!mrb_nil_p(data_value)) {\n    Data_Get_Struct(mrb, data_value, &matrix_data_type, p_data);\n    free(p_data);\n  }\n  // Allocate and zero-out the data struct:\n  p_data = gsl_matrix_calloc(n, m);\n  if (!p_data)\n    mrb_raise(mrb, E_RUNTIME_ERROR, \"Could not allocate @data\");\n\n  // Wrap struct into @data:\n  mrb_iv_set(\n      mrb, self, mrb_intern_lit(mrb, \"@data\"), // set @data\n      mrb_obj_value(                           // with value hold in struct\n          Data_Wrap_Struct(mrb, mrb->object_class, &matrix_data_type, p_data)));\n}\n\nstatic mrb_value mrb_matrix_initialize(mrb_state *mrb, mrb_value self) {\n  mrb_int n, m;\n  mrb_get_args(mrb, \"ii\", &n, &m);\n\n  // Call strcut initializer:\n  mrb_matrix_init(mrb, self, n, m);\n  mrb_iv_set(mrb, self, mrb_intern_lit(mrb, \"@nrows\"), mrb_fixnum_value(n));\n  mrb_iv_set(mrb, self, mrb_intern_lit(mrb, \"@ncols\"), mrb_fixnum_value(m));\n  mrb_iv_set(mrb, self, mrb_intern_lit(mrb, \"@format\"),\n             mrb_str_new_cstr(mrb, \"%10.3f\"));\n  return mrb_nil_value();\n}\n\nstatic mrb_value mrb_matrix_dup(mrb_state *mrb, mrb_value self) {\n  mrb_value other;\n  gsl_matrix *p_mat = NULL, *p_mat_other = NULL;\n  mrb_value args[2];\n\n  // call utility for unwrapping @data into p_data:\n  mrb_matrix_get_data(mrb, self, &p_mat);\n  args[0] = mrb_fixnum_value(p_mat->size1);\n  args[1] = mrb_fixnum_value(p_mat->size2);\n  other = mrb_obj_new(mrb, mrb_class_get(mrb, \"Matrix\"), 2, args);\n  mrb_matrix_get_data(mrb, other, &p_mat_other);\n  gsl_matrix_memcpy(p_mat_other, p_mat);\n  return other;\n}\n\nstatic mrb_value mrb_matrix_rnd_fill(mrb_state *mrb, mrb_value self) {\n  gsl_matrix *p_mat = NULL;\n  const gsl_rng_type *T;\n  gsl_rng *r;\n  mrb_int h, k;\n\n  mrb_matrix_get_data(mrb, self, &p_mat);\n\n  gsl_rng_env_setup();\n  T = gsl_rng_default;\n  r = gsl_rng_alloc(T);\n\n  for (k = 0; k < p_mat->size2; k++) {\n    for (h = 0; h < p_mat->size1; h++) {\n      gsl_matrix_set(p_mat, h, k, gsl_rng_uniform(r));\n    }\n  }\n  return self;\n}\n\nstatic mrb_value mrb_matrix_all(mrb_state *mrb, mrb_value self) {\n  mrb_float v;\n  gsl_matrix *p_mat = NULL;\n\n  mrb_get_args(mrb, \"f\", &v);\n  // call utility for unwrapping @data into p_data:\n  mrb_matrix_get_data(mrb, self, &p_mat);\n  gsl_matrix_set_all(p_mat, v);\n  return self;\n}\n\nstatic mrb_value mrb_matrix_zero(mrb_state *mrb, mrb_value self) {\n  gsl_matrix *p_mat = NULL;\n\n  // call utility for unwrapping @data into p_data:\n  mrb_matrix_get_data(mrb, self, &p_mat);\n  gsl_matrix_set_zero(p_mat);\n  return self;\n}\n\nstatic mrb_value mrb_matrix_identity(mrb_state *mrb, mrb_value self) {\n  gsl_matrix *p_mat = NULL;\n\n  // call utility for unwrapping @data into p_data:\n  mrb_matrix_get_data(mrb, self, &p_mat);\n  gsl_matrix_set_identity(p_mat);\n  return self;\n}\n\n#pragma mark -\n#pragma mark \u2022 Tests\n\nstatic mrb_value mrb_matrix_equal(mrb_state *mrb, mrb_value self) {\n  mrb_value other;\n  gsl_matrix *p_mat, *p_mat_other;\n  mrb_get_args(mrb, \"o\", &other);\n\n  // call utility for unwrapping @data into p_data:\n  mrb_matrix_get_data(mrb, self, &p_mat);\n  mrb_matrix_get_data(mrb, other, &p_mat_other);\n  if (1 == gsl_matrix_equal(p_mat, p_mat_other))\n    return mrb_true_value();\n  else\n    return mrb_false_value();\n}\n\n#pragma mark -\n#pragma mark \u2022 Accessors\n\nstatic mrb_value mrb_matrix_get_row(mrb_state *mrb, mrb_value self) {\n  mrb_int i, n;\n  mrb_value result, args[1];\n  gsl_matrix *p_mat = NULL;\n  gsl_vector *p_vec = NULL;\n\n  n = mrb_get_args(mrb, \"|i\", &i);\n  // call utility for unwrapping @data into p_data:\n  mrb_matrix_get_data(mrb, self, &p_mat);\n\n  if (n == 1) {\n    if (i >= p_mat->size1) {\n      mrb_raise(mrb, E_MATRIX_ERROR, \"matrix index out of range!\");\n    }\n    args[0] = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, \"@ncols\"));\n    result = mrb_obj_new(mrb, mrb_class_get(mrb, \"Vector\"), 1, args);\n    mrb_vector_get_data(mrb, result, &p_vec);\n    gsl_matrix_get_row(p_vec, p_mat, i);\n  }\n  else {\n    result = mrb_ary_new_capa(mrb, p_mat->size1);\n    for (i = 0; i < p_mat->size1; i++) {\n      mrb_ary_push(mrb, result, mrb_funcall(mrb, self, \"get_row\", 1, mrb_fixnum_value(i)));\n    }\n  }\n  return result;\n}\n\nstatic mrb_value mrb_matrix_get_col(mrb_state *mrb, mrb_value self) {\n  mrb_int i;\n  mrb_value res, args[1];\n  gsl_matrix *p_mat = NULL;\n  gsl_vector *p_vec = NULL;\n\n  mrb_get_args(mrb, \"i\", &i);\n  // call utility for unwrapping @data into p_data:\n  mrb_matrix_get_data(mrb, self, &p_mat);\n  if (i >= p_mat->size2) {\n    mrb_raise(mrb, E_MATRIX_ERROR, \"matrix index out of range!\");\n  }\n  args[0] = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, \"@nrows\"));\n  res = mrb_obj_new(mrb, mrb_class_get(mrb, \"Vector\"), 1, args);\n  mrb_vector_get_data(mrb, res, &p_vec);\n  gsl_matrix_get_col(p_vec, p_mat, i);\n  return res;\n}\n\nstatic mrb_value mrb_matrix_get_ij(mrb_state *mrb, mrb_value self) {\n  mrb_value result;\n  mrb_int i, j;\n  gsl_matrix *p_mat = NULL;\n  mrb_int n;\n\n  n = mrb_get_args(mrb, \"|ii\", &i, &j);\n  // call utility for unwrapping @data into p_data:\n  mrb_matrix_get_data(mrb, self, &p_mat);\n  if (n == 2) {\n    if (i >= p_mat->size1 || j >= p_mat->size2) {\n      mrb_raise(mrb, E_MATRIX_ERROR, \"matrix index out of range!\");\n    }\n    result = mrb_float_value(mrb, gsl_matrix_get(p_mat, (size_t)i, (size_t)j));\n  } else {\n    result = mrb_matrix_get_row(mrb, self);\n  }\n  return result;\n}\n\nstatic mrb_value mrb_matrix_set_ij(mrb_state *mrb, mrb_value self) {\n  mrb_int i, j;\n  mrb_float f;\n  gsl_matrix *p_mat = NULL;\n\n  mrb_get_args(mrb, \"iif\", &i, &j, &f);\n\n  // call utility for unwrapping @data into p_data:\n  mrb_matrix_get_data(mrb, self, &p_mat);\n  if (i >= p_mat->size1 || j >= p_mat->size2) {\n    mrb_raise(mrb, E_MATRIX_ERROR, \"matrix index out of range!\");\n  }\n  gsl_matrix_set(p_mat, (size_t)i, (size_t)j, (double)f);\n  return mrb_float_value(mrb, f);\n}\n\nstatic mrb_value mrb_matrix_set_row(mrb_state *mrb, mrb_value self) {\n  mrb_int i;\n  mrb_value other;\n  gsl_matrix *p_mat = NULL;\n  gsl_vector *p_vec = NULL;\n\n  mrb_get_args(mrb, \"io\", &i, &other);\n  // call utility for unwrapping @data into p_data:\n  mrb_matrix_get_data(mrb, self, &p_mat);\n  if (i >= p_mat->size1) {\n    mrb_raise(mrb, E_MATRIX_ERROR, \"matrix row index out of range!\");\n  }\n  mrb_vector_get_data(mrb, other, &p_vec);\n  if (p_mat->size2 != p_vec->size) {\n    mrb_raise(mrb, E_MATRIX_ERROR, \"Size mismatch!\");\n  }\n  gsl_matrix_set_row(p_mat, i, p_vec);\n  return self;\n}\n\nstatic mrb_value mrb_matrix_set_col(mrb_state *mrb, mrb_value self) {\n  mrb_int i;\n  mrb_value other;\n  gsl_matrix *p_mat = NULL;\n  gsl_vector *p_vec = NULL;\n\n  mrb_get_args(mrb, \"io\", &i, &other);\n  // call utility for unwrapping @data into p_data:\n  mrb_matrix_get_data(mrb, self, &p_mat);\n  if (i >= p_mat->size2) {\n    mrb_raise(mrb, E_MATRIX_ERROR, \"matrix col index out of range!\");\n  }\n  mrb_vector_get_data(mrb, other, &p_vec);\n  if (p_mat->size1 != p_vec->size) {\n    mrb_raise(mrb, E_MATRIX_ERROR, \"Size mismatch!\");\n  }\n  gsl_matrix_set_col(p_mat, i, p_vec);\n  return self;\n}\n\n#pragma mark -\n#pragma mark \u2022 Properties\n\nstatic mrb_value mrb_matrix_max(mrb_state *mrb, mrb_value self) {\n  gsl_matrix *p_mat = NULL;\n  mrb_matrix_get_data(mrb, self, &p_mat);\n  return mrb_float_value(mrb, gsl_matrix_max(p_mat));\n}\n\nstatic mrb_value mrb_matrix_min(mrb_state *mrb, mrb_value self) {\n  gsl_matrix *p_mat = NULL;\n  mrb_matrix_get_data(mrb, self, &p_mat);\n  return mrb_float_value(mrb, gsl_matrix_min(p_mat));\n}\n\nstatic mrb_value mrb_matrix_max_index(mrb_state *mrb, mrb_value self) {\n  size_t i, j;\n  mrb_value res = mrb_ary_new_capa(mrb, 2);\n  gsl_matrix *p_mat = NULL;\n  mrb_matrix_get_data(mrb, self, &p_mat);\n  gsl_matrix_max_index(p_mat, &i, &j);\n  mrb_ary_push(mrb, res, mrb_fixnum_value(i));\n  mrb_ary_push(mrb, res, mrb_fixnum_value(j));\n  return res;\n}\n\nstatic mrb_value mrb_matrix_min_index(mrb_state *mrb, mrb_value self) {\n  size_t i, j;\n  mrb_value res = mrb_ary_new_capa(mrb, 2);\n  gsl_matrix *p_mat = NULL;\n  mrb_matrix_get_data(mrb, self, &p_mat);\n  gsl_matrix_min_index(p_mat, &i, &j);\n  mrb_ary_push(mrb, res, mrb_fixnum_value(i));\n  mrb_ary_push(mrb, res, mrb_fixnum_value(j));\n  return res;\n}\n\n#pragma mark -\n#pragma mark \u2022 Operations\n\nstatic mrb_value mrb_matrix_add(mrb_state *mrb, mrb_value self) {\n  mrb_value other;\n  gsl_matrix *p_mat, *p_mat_other;\n  mrb_get_args(mrb, \"o\", &other);\n\n  // call utility for unwrapping @data into p_data:\n  mrb_matrix_get_data(mrb, self, &p_mat);\n  if (mrb_obj_is_kind_of(mrb, other, mrb_class_get(mrb, \"Matrix\"))) {\n    mrb_matrix_get_data(mrb, other, &p_mat_other);\n    if (p_mat->size1 != p_mat_other->size1 ||\n        p_mat->size2 != p_mat_other->size2) {\n      mrb_raise(mrb, E_MATRIX_ERROR, \"matrix dimensions don't match!\");\n    }\n    gsl_matrix_add(p_mat, p_mat_other);\n  } else if (mrb_obj_is_kind_of(mrb, other, mrb_class_get(mrb, \"Numeric\"))) {\n    gsl_matrix_add_constant(p_mat, mrb_to_flo(mrb, other));\n  }\n  return self;\n}\n\nstatic mrb_value mrb_matrix_sub(mrb_state *mrb, mrb_value self) {\n  mrb_value other;\n  gsl_matrix *p_mat, *p_mat_other;\n  mrb_get_args(mrb, \"o\", &other);\n\n  // call utility for unwrapping @data into p_data:\n  mrb_matrix_get_data(mrb, self, &p_mat);\n  mrb_matrix_get_data(mrb, other, &p_mat_other);\n  if (p_mat->size1 != p_mat_other->size1 ||\n      p_mat->size2 != p_mat_other->size2) {\n    mrb_raise(mrb, E_MATRIX_ERROR, \"matrix dimensions don't match!\");\n  }\n  gsl_matrix_sub(p_mat, p_mat_other);\n  return self;\n}\n\nstatic mrb_value mrb_matrix_mul(mrb_state *mrb, mrb_value self) {\n  mrb_value other;\n  gsl_matrix *p_mat, *p_mat_other;\n  mrb_get_args(mrb, \"o\", &other);\n\n  // call utility for unwrapping @data into p_data:\n  mrb_matrix_get_data(mrb, self, &p_mat);\n  if (mrb_obj_is_kind_of(mrb, other, mrb_class_get(mrb, \"Matrix\"))) {\n    mrb_matrix_get_data(mrb, other, &p_mat_other);\n    if (p_mat->size1 != p_mat_other->size1 ||\n        p_mat->size2 != p_mat_other->size2) {\n      mrb_raise(mrb, E_MATRIX_ERROR, \"matrix dimensions don't match!\");\n    }\n    gsl_matrix_mul_elements(p_mat, p_mat_other);\n  } else if (mrb_obj_is_kind_of(mrb, other, mrb_class_get(mrb, \"Numeric\"))) {\n    gsl_matrix_scale(p_mat, mrb_to_flo(mrb, other));\n  }\n  return self;\n}\n\nstatic mrb_value mrb_matrix_prod(mrb_state *mrb, mrb_value self) {\n  mrb_value other, res;\n  gsl_matrix *p_mat, *p_mat_other, *p_mat_res;\n  gsl_vector *p_vec_other, *p_vec_res;\n  mrb_value args[2];\n  mrb_get_args(mrb, \"o\", &other);\n\n  // call utility for unwrapping @data into p_data:\n  mrb_matrix_get_data(mrb, self, &p_mat);\n\n  if (mrb_obj_is_kind_of(mrb, other, mrb_class_get(mrb, \"Matrix\"))) {\n    args[1] = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, \"@nrows\"));\n    args[0] = mrb_iv_get(mrb, other, mrb_intern_lit(mrb, \"@ncols\"));\n    res = mrb_obj_new(mrb, mrb_class_get(mrb, \"Matrix\"), 2, args);\n    mrb_matrix_get_data(mrb, other, &p_mat_other);\n    mrb_matrix_get_data(mrb, res, &p_mat_res);\n\n    if (p_mat->size2 != p_mat_other->size1) {\n      mrb_raise(mrb, E_MATRIX_ERROR, \"matrix dimensions don't match!\");\n    }\n    gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, p_mat, p_mat_other, 0.0,\n                   p_mat_res);\n  } else if (mrb_obj_is_kind_of(mrb, other, mrb_class_get(mrb, \"Vector\"))) {\n    args[0] = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, \"@nrows\"));\n    res = mrb_obj_new(mrb, mrb_class_get(mrb, \"Vector\"), 1, args);\n    mrb_vector_get_data(mrb, other, &p_vec_other);\n    mrb_vector_get_data(mrb, res, &p_vec_res);\n\n    if (p_mat->size2 != p_vec_other->size) {\n      mrb_raise(mrb, E_MATRIX_ERROR, \"matrix dimensions don't match!\");\n    }\n    gsl_blas_dgemv(CblasNoTrans, 1.0, p_mat, p_vec_other, 0.0, p_vec_res);\n  }\n  return res;\n}\n\nstatic mrb_value mrb_matrix_div(mrb_state *mrb, mrb_value self) {\n  mrb_value other;\n  gsl_matrix *p_mat, *p_mat_other;\n  mrb_get_args(mrb, \"o\", &other);\n\n  // call utility for unwrapping @data into p_data:\n  mrb_matrix_get_data(mrb, self, &p_mat);\n  mrb_matrix_get_data(mrb, other, &p_mat_other);\n  if (p_mat->size1 != p_mat_other->size1 ||\n      p_mat->size2 != p_mat_other->size2) {\n    mrb_raise(mrb, E_MATRIX_ERROR, \"matrix dimensions don't match!\");\n  }\n  gsl_matrix_div_elements(p_mat, p_mat_other);\n  return self;\n}\n\nstatic mrb_value mrb_matrix_transpose_self(mrb_state *mrb, mrb_value self) {\n  gsl_matrix *p_mat;\n  // call utility for unwrapping @data into p_data:\n  mrb_matrix_get_data(mrb, self, &p_mat);\n  if (p_mat->size1 != p_mat->size2) {\n    mrb_raise(mrb, E_MATRIX_ERROR, \"matrix must be square!\");\n  }\n  if (gsl_matrix_transpose(p_mat)) {\n    mrb_raise(mrb, E_MATRIX_ERROR, \"Cannot calculate transposed matrix\");\n  }\n  return self;\n}\n\nstatic mrb_value mrb_matrix_transpose(mrb_state *mrb, mrb_value self) {\n  mrb_value other;\n  gsl_matrix *p_mat, *p_mat_other;\n  mrb_value args[2];\n  // swap dimensions!\n  args[1] = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, \"@nrows\"));\n  args[0] = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, \"@ncols\"));\n  other = mrb_obj_new(mrb, mrb_class_get(mrb, \"Matrix\"), 2, args);\n  // call utility for unwrapping @data into p_data:\n  mrb_matrix_get_data(mrb, self, &p_mat);\n  mrb_matrix_get_data(mrb, other, &p_mat_other);\n  if (gsl_matrix_transpose_memcpy(p_mat_other, p_mat)) {\n    mrb_raise(mrb, E_MATRIX_ERROR, \"Cannot calculate transposed matrix\");\n  }\n  return other;\n}\n\nstatic mrb_value mrb_matrix_swap_rows(mrb_state *mrb, mrb_value self) {\n  gsl_matrix *p_mat;\n  mrb_int i, j;\n  mrb_get_args(mrb, \"ii\", &i, &j);\n\n  // call utility for unwrapping @data into p_data:\n  mrb_matrix_get_data(mrb, self, &p_mat);\n  if (gsl_matrix_swap_rows(p_mat, i, j)) {\n    mrb_raise(mrb, E_MATRIX_ERROR, \"Cannot swap rows\");\n  }\n  return self;\n}\n\nstatic mrb_value mrb_matrix_swap_cols(mrb_state *mrb, mrb_value self) {\n  gsl_matrix *p_mat;\n  mrb_int i, j;\n  mrb_get_args(mrb, \"ii\", &i, &j);\n\n  // call utility for unwrapping @data into p_data:\n  mrb_matrix_get_data(mrb, self, &p_mat);\n  if (gsl_matrix_swap_columns(p_mat, i, j)) {\n    mrb_raise(mrb, E_MATRIX_ERROR, \"Cannot swap cols\");\n  }\n  return self;\n}\n\n#pragma mark -\n#pragma mark \u2022 Gem setup\n\nvoid mrb_gsl_matrix_init(mrb_state *mrb) {\n  struct RClass *gsl;\n\n  mrb_load_string(mrb, \"class MatrixError < Exception; end\");\n\n  gsl = mrb_define_class(mrb, \"Matrix\", mrb->object_class);\n  mrb_define_method(mrb, gsl, \"initialize\", mrb_matrix_initialize,\n                    MRB_ARGS_NONE());\n  mrb_define_method(mrb, gsl, \"dup\", mrb_matrix_dup, MRB_ARGS_NONE());\n  mrb_define_method(mrb, gsl, \"all\", mrb_matrix_all, MRB_ARGS_REQ(1));\n  mrb_define_method(mrb, gsl, \"zero\", mrb_matrix_zero, MRB_ARGS_NONE());\n  mrb_define_method(mrb, gsl, \"identity\", mrb_matrix_identity, MRB_ARGS_NONE());\n  mrb_define_method(mrb, gsl, \"rnd_fill\", mrb_matrix_rnd_fill, MRB_ARGS_NONE());\n  mrb_define_method(mrb, gsl, \"===\", mrb_matrix_equal, MRB_ARGS_REQ(1));\n  mrb_define_method(mrb, gsl, \"[]\", mrb_matrix_get_ij, MRB_ARGS_OPT(2));\n  mrb_define_method(mrb, gsl, \"row\", mrb_matrix_get_row, MRB_ARGS_REQ(1));\n  mrb_define_method(mrb, gsl, \"col\", mrb_matrix_get_col, MRB_ARGS_REQ(1));\n  mrb_define_method(mrb, gsl, \"[]=\", mrb_matrix_set_ij, MRB_ARGS_REQ(3));\n  mrb_define_method(mrb, gsl, \"get_row\", mrb_matrix_get_row, MRB_ARGS_OPT(1));\n  mrb_define_method(mrb, gsl, \"get_col\", mrb_matrix_get_col, MRB_ARGS_OPT(1));\n  mrb_define_method(mrb, gsl, \"set_row\", mrb_matrix_set_row, MRB_ARGS_REQ(2));\n  mrb_define_method(mrb, gsl, \"set_col\", mrb_matrix_set_col, MRB_ARGS_REQ(2));\n\n  mrb_define_method(mrb, gsl, \"max\", mrb_matrix_max, MRB_ARGS_NONE());\n  mrb_define_method(mrb, gsl, \"max_index\", mrb_matrix_max_index,\n                    MRB_ARGS_NONE());\n  mrb_define_method(mrb, gsl, \"min\", mrb_matrix_min, MRB_ARGS_NONE());\n  mrb_define_method(mrb, gsl, \"min_index\", mrb_matrix_min_index,\n                    MRB_ARGS_NONE());\n\n  mrb_define_method(mrb, gsl, \"add!\", mrb_matrix_add, MRB_ARGS_REQ(1));\n  mrb_define_method(mrb, gsl, \"sub!\", mrb_matrix_sub, MRB_ARGS_REQ(1));\n  mrb_define_method(mrb, gsl, \"mul!\", mrb_matrix_mul, MRB_ARGS_REQ(1));\n  mrb_define_method(mrb, gsl, \"div!\", mrb_matrix_div, MRB_ARGS_REQ(1));\n  mrb_define_method(mrb, gsl, \"^\", mrb_matrix_prod, MRB_ARGS_REQ(1));\n  mrb_define_method(mrb, gsl, \"t!\", mrb_matrix_transpose_self, MRB_ARGS_NONE());\n  mrb_define_method(mrb, gsl, \"t\", mrb_matrix_transpose, MRB_ARGS_NONE());\n  mrb_define_method(mrb, gsl, \"swap_rows\", mrb_matrix_swap_rows,\n                    MRB_ARGS_REQ(2));\n  mrb_define_method(mrb, gsl, \"swap_cols\", mrb_matrix_swap_cols,\n                    MRB_ARGS_REQ(2));\n}\n", "meta": {"hexsha": "8a2d3fbeb800515f90ded14838d75c37f5a6bb11", "size": 19239, "ext": "c", "lang": "C", "max_stars_repo_path": "src/matrix.c", "max_stars_repo_name": "UniTN-Mechatronics/mruby-gsl", "max_stars_repo_head_hexsha": "0961ef3b88bb8ed9e9223b2678ece281acaa0f4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/matrix.c", "max_issues_repo_name": "UniTN-Mechatronics/mruby-gsl", "max_issues_repo_head_hexsha": "0961ef3b88bb8ed9e9223b2678ece281acaa0f4b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/matrix.c", "max_forks_repo_name": "UniTN-Mechatronics/mruby-gsl", "max_forks_repo_head_hexsha": "0961ef3b88bb8ed9e9223b2678ece281acaa0f4b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1076642336, "max_line_length": 91, "alphanum_fraction": 0.6700971984, "num_tokens": 5604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3486451217982255, "lm_q2_score": 0.05340333243628599, "lm_q1q2_score": 0.018618811341680055}}
{"text": "/* eigen/schur.h\n * \n * Copyright (C) 2006 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_SCHUR_H__\n#define __GSL_SCHUR_H__\n\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_complex.h>\n\n/*\n * Prototypes\n */\n\nvoid gsl_schur_standardize(gsl_matrix *T, size_t row, gsl_complex *eval1,\n                           gsl_complex *eval2, int update_t, gsl_matrix *Z);\n\n#endif /* __GSL_SCHUR_H__ */\n", "meta": {"hexsha": "17d87a0e81d2487dbcf0c95d6bf376ba9c4501eb", "size": 1096, "ext": "h", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/eigen/schur.h", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/eigen/schur.h", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/eigen/schur.h", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 32.2352941176, "max_line_length": 81, "alphanum_fraction": 0.7244525547, "num_tokens": 280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.04023794233588316, "lm_q1q2_score": 0.01855036658184354}}
{"text": "#pragma once\n#include <gsl/gsl_rng.h>\n#include <utility>\n\n// we are using GSL random number generation because i don't trust\n// random number generation to be consistent across various C++ stdlib\n// implementations, and for the kind of MC simulator we are writing here,\n// we want to be able to run it deterministically for testing purposes.\n\nclass Sampler {\nprivate:\n    gsl_rng *internal_rng_state;\npublic:\n    unsigned long int seed;\n    double generate() {\n        return gsl_rng_uniform_pos(internal_rng_state);\n    };\n\n    Sampler(unsigned long int n) :\n        seed (n) {\n        internal_rng_state = gsl_rng_alloc(gsl_rng_default);\n        gsl_rng_set(internal_rng_state, seed);\n        };\n\n    ~Sampler() {\n        gsl_rng_free(internal_rng_state);\n    };\n\n    // since we don't have access to gsl internal state, can't write\n    // copy constructor\n    Sampler(Sampler &other) = delete;\n\n    // move constructor\n    Sampler(Sampler &&other) :\n        internal_rng_state (std::exchange(other.internal_rng_state, nullptr)),\n        seed (other.seed)\n        {};\n\n    // since we don't have access to gsl internal state, can't write\n    // copy assignment operator\n    Sampler &operator=(Sampler &other) = delete;\n\n    // move assignment operator\n    Sampler &operator=(Sampler &&other) {\n        seed = other.seed;\n\n        // we move the existing internal_rng_state into other so\n        // it gets freed when other is dropped.\n        std::swap(internal_rng_state, other.internal_rng_state);\n        return *this;\n    };\n\n};\n", "meta": {"hexsha": "bf1cc6ed04d207257f223ecb78f722def38f37b9", "size": 1535, "ext": "h", "lang": "C", "max_stars_repo_path": "core/sampler.h", "max_stars_repo_name": "danielbarter/SMMC", "max_stars_repo_head_hexsha": "0966e4c7919da253e69f17e268bfb2d2a7e7f873", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-08T19:24:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T19:24:44.000Z", "max_issues_repo_path": "core/sampler.h", "max_issues_repo_name": "danielbarter/SMMC", "max_issues_repo_head_hexsha": "0966e4c7919da253e69f17e268bfb2d2a7e7f873", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "core/sampler.h", "max_forks_repo_name": "danielbarter/SMMC", "max_forks_repo_head_hexsha": "0966e4c7919da253e69f17e268bfb2d2a7e7f873", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-12-06T18:48:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T23:03:13.000Z", "avg_line_length": 28.4259259259, "max_line_length": 78, "alphanum_fraction": 0.667752443, "num_tokens": 335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2909808662149068, "lm_q2_score": 0.06371499425196533, "lm_q1q2_score": 0.018539844218314682}}
{"text": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n#pragma once\n\n#include <algorithm>\n#include <array>\n#include <vector>\n#include <gsl/gsl>\n#include <assert.h>\n#include <boost/optional.hpp>\n#include \"Data/Intrinsics.h\"\n#include \"TimeUnits.h\"\n#include \"MageSettings.h\"\n\nnamespace mage\n{\n    enum class TrackingState\n    {\n        INITIALIZING = 0,\n        TRACKING = 1,\n        RELOCALIZING = 2,\n        SKIPPED = 3\n    };\n\n    enum class FuserMode\n    {\n        Invalid = 0 ,\n        WaitForMageInit = 1,\n        WaitForGravityConverge = 2,\n        VisualTrackingLost = 3,\n        VisualTrackingReacquired = 4,\n        ScaleInit = 5,\n        Tracking = 6\n    };\n\n    enum class PixelFormat\n    {\n        GRAYSCALE8,\n        NV12\n    };\n\n    struct FrameId\n    {\n        std::uint64_t CorrelationId;    //this is the number used to match frames either from each stereo cameras, or from low-res to high-res in the mono case. Should be unique (and increasing) per camera.\n        CameraIdentity Camera;\n\n        FrameId()\n            : CorrelationId{ 0 }, Camera{ mage::CameraIdentity::MONO }\n        {}\n\n        FrameId(const std::uint64_t& id, CameraIdentity cam)\n            : CorrelationId{ id }, Camera{ cam }\n        {}\n\n        bool operator ==(const FrameId& other) const\n        {\n            return CorrelationId == other.CorrelationId && Camera == other.Camera;\n        }\n\n        bool operator !=(const FrameId& other) const\n        {\n            return !(*this == other);\n        }\n\n        bool operator <(const FrameId& other) const\n        {\n            if (CorrelationId < other.CorrelationId)\n                return true;\n\n            if (other.CorrelationId < CorrelationId)\n                return false;\n\n            return Camera < other.Camera;\n        }\n    };\n\n    struct Size\n    {\n        size_t Width;\n        size_t Height;\n    };\n\n    struct Rect\n    {\n        int X;\n        int Y;\n        size_t Width;\n        size_t Height;\n    };\n\n    struct Matrix\n    {\n        float M11, M12, M13, M14;\n        float M21, M22, M23, M24;\n        float M31, M32, M33, M34;\n        float M41, M42, M43, M44;\n    };\n\n    struct Position\n    {\n        float X;\n        float Y;\n        float Z;\n\n        std::array<float, 3> AsArray() const\n        {\n            return{ X, Y, Z };\n        }\n    };\n\n    struct ProjectedPoint\n    {\n        float X;\n        float Y;\n        float Depth;\n        int32_t Id;\n\n        ProjectedPoint(float x, float y, float depth, int32_t id)\n            : X{ x }, Y{ y }, Depth{ depth }, Id{ id }\n        {}\n\n        ProjectedPoint() = default;\n    };\n\n    struct AxisAlignedVolume\n    {\n        Position Min;\n        Position Max;\n    };\n    \n    struct Direction\n    {\n        float X;\n        float Y;\n        float Z;\n    };\n\n    enum class DataFormat\n    {\n        BINARY,\n        PNG,\n        LIVE,\n        BOB,\n        MIDDLEBURY,\n    };\n\n    namespace calibration\n    {\n        enum class DistortionType\n        {\n            None,\n            Poly3k,\n            Rational6k\n        };\n\n        class CameraModel\n        {\n        public:\n\n            CameraModel() = default;\n            CameraModel(const Intrinsics& intrinsics, DistortionType distType) : m_intrinsics(intrinsics), m_distortionType(distType) {}\n            const Intrinsics& GetIntrinsics() const { return m_intrinsics; }\n           \n            //not in opencv order\n            virtual gsl::span<const float> GetDistortionCoefficients() const = 0;\n            virtual DistortionType GetDistortionType() const { return m_distortionType; }\n\n        private:\n            Intrinsics m_intrinsics;\n            DistortionType m_distortionType;\n        };\n\n        class PinholeCameraModel : public CameraModel\n        {\n        public:\n            PinholeCameraModel() = delete;\n            PinholeCameraModel(const Intrinsics& intrinsics) : CameraModel(intrinsics, DistortionType::None) {}\n\n            gsl::span<const float> GetDistortionCoefficients() const { return {}; }\n        };\n\n        class Poly3KCameraModel : public CameraModel\n        {\n        public:\n            Poly3KCameraModel() = delete;\n            Poly3KCameraModel(const Intrinsics& intrinsics, std::vector<float> distortionCoefficients) :\n                CameraModel(intrinsics, DistortionType::Poly3k),\n                m_distortionCoefficients{ distortionCoefficients }\n            {\n                assert(m_distortionCoefficients.size()== 5 && \"incorrect number of distortion coefficients. want k1, k2, k3, p1, p2\");\n            }\n\n            //not in opencv order\n            gsl::span<const float> GetDistortionCoefficients() const { return m_distortionCoefficients; }\n          \n            float GetK1() const { return m_distortionCoefficients[0];}\n            float GetK2() const { return m_distortionCoefficients[1];}\n            float GetK3() const { return m_distortionCoefficients[2];}\n            float GetP1() const { return m_distortionCoefficients[3];}\n            float GetP2() const { return m_distortionCoefficients[4];}\n            \n            void SetK1(float k1) { m_distortionCoefficients[0] = k1; }\n            void SetK2(float k2) { m_distortionCoefficients[1] = k2; }\n            void SetK3(float k3) { m_distortionCoefficients[2] = k3; }\n            void SetP1(float p1) { m_distortionCoefficients[3] = p1; }\n            void SetP2(float p2) { m_distortionCoefficients[4] = p2; }\n\n        private:\n            // k1, k2, k3, p1, p2\n            std::vector<float> m_distortionCoefficients;\n        };\n\n        class Rational6KCameraModel : public CameraModel\n        {\n        public:\n            Rational6KCameraModel() = delete;\n            Rational6KCameraModel(const Intrinsics& intrinsics, std::vector<float> distortionCoefficients)\n                : CameraModel(intrinsics, DistortionType::Rational6k),\n                m_distortionCoefficients{ distortionCoefficients }\n            {\n                assert(m_distortionCoefficients.size() == 8 && \"incorrect number of distortion coefficients. want k1, k2, k3, k4, k5, k6, p1, p2\");\n            }\n\n            //not in opencv order\n            gsl::span<const float> GetDistortionCoefficients() const { return m_distortionCoefficients; }\n\n            float GetK1() const { return m_distortionCoefficients[0]; }\n            float GetK2() const { return m_distortionCoefficients[1]; }\n            float GetK3() const { return m_distortionCoefficients[2]; }\n            float GetK4() const { return m_distortionCoefficients[3]; }\n            float GetK5() const { return m_distortionCoefficients[4]; }\n            float GetK6() const { return m_distortionCoefficients[5]; }\n            float GetP1() const { return m_distortionCoefficients[6]; }\n            float GetP2() const { return m_distortionCoefficients[7]; }\n\n            void SetK1(float k1) { m_distortionCoefficients[0] = k1; }\n            void SetK2(float k2) { m_distortionCoefficients[1] = k2; }\n            void SetK3(float k3) { m_distortionCoefficients[2] = k3; }\n            void SetK4(float k4) { m_distortionCoefficients[3] = k4; }\n            void SetK5(float k5) { m_distortionCoefficients[4] = k5; }\n            void SetK6(float k6) { m_distortionCoefficients[5] = k6; }\n            void SetP1(float p1) { m_distortionCoefficients[6] = p1; }\n            void SetP2(float p2) { m_distortionCoefficients[7] = p2; }\n\n        private:\n            // k1, k2, k3, k4, k5, k6, p1, p2\n            std::vector<float> m_distortionCoefficients;\n        };\n\n        struct Line\n        {\n            float M;\n            float B;\n        };\n\n        struct Bounds\n        {\n            float Lower;\n            float Upper;\n        };\n        \n        class LinearFocalLengthModel\n        {\n        public:\n\n            LinearFocalLengthModel(Line fx, Line fy, float cx, float cy, Bounds focalbounds, Size calibrationSize,\n                const std::vector<float>& distortionPoly3k = {},\n                const std::vector<float>& distortionRational6k = {}) :\n                m_fx(fx), m_fy(fy), m_cx(cx), m_cy(cy), m_focalBounds(focalbounds), m_calibrationSize(calibrationSize)\n            {\n                assert(distortionPoly3k.empty() || distortionRational6k.empty() && \"can't pass two types currently. calibrations have different intrinsics depending on model\");\n                assert(cx >= 0 && cx <= 1 && \"cx and cy need to be a ratio\");\n                assert(cy >= 0 && cy <= 1 && \"cx and cy need to be a ratio\");\n\n                if (!distortionPoly3k.empty())\n                {\n                    assert(distortionPoly3k.size() == 5 && \"expecting k0, k1, k2, p0, p1, for poly3k distortion\");\n                    std::copy(distortionPoly3k.begin(), distortionPoly3k.end(), std::back_inserter(m_distortionPoly3k));\n                }\n\n                if (!distortionRational6k.empty())\n                {\n                    assert(distortionRational6k.size() == 8 && \"expecting k0, k1, k2, k3, k4, k5, p0, p1, for rational6k distortion\");\n                    std::copy(distortionRational6k.begin(), distortionRational6k.end(), std::back_inserter(m_distortionRational6k));\n                }\n            }\n\n            LinearFocalLengthModel()\n            {\n                m_fx = { 0,0 };\n                m_fy = { 0,0 };\n                m_cx = 0;\n                m_cy = 0;\n                m_focalBounds = { 0,0 };\n                m_calibrationSize = { 0, 0 };\n            }\n\n            Intrinsics CreateIntrinsics(boost::optional<uint32_t> lensPosition, size_t width, size_t height) const\n            {\n                assert(width / (float)height == m_calibrationSize.Width / (float)m_calibrationSize.Height && \"aspect not equal need to crop to modify resolution\");\n                assert(lensPosition || (m_fx.M == 0 && m_fy.M == 0));\n\n                float fx = m_fx.B;\n                float fy = m_fy.B;\n\n                if (lensPosition)\n                {\n                    fx += m_fx.M * lensPosition.value();\n                    fy += m_fy.M * lensPosition.value();\n                }\n\n                float FxInPixelCoordinates = fx * width;\n                float FyInPixelCoordinates = fy * height;\n                float CxInPixelCoordinates = m_cx * width;\n                float CyInPixelCoordinates = m_cy * height;\n\n                return Intrinsics(CxInPixelCoordinates, CyInPixelCoordinates,\n                    FxInPixelCoordinates, FyInPixelCoordinates,\n                    gsl::narrow<uint32_t>(width), gsl::narrow<uint32_t>(height));\n            }\n\n            std::shared_ptr<const PinholeCameraModel> CreatePinholeCameraModel(const boost::optional<uint32_t>& lensPosition, size_t width, size_t height) const\n            {\n                return std::make_shared<const PinholeCameraModel>(CreateIntrinsics(lensPosition, width, height));\n            }\n\n            std::shared_ptr<const Poly3KCameraModel> CreatePoly3kCameraModel(const boost::optional<uint32_t>& lensPosition, size_t width, size_t height) const\n            {\n                return std::make_shared<const Poly3KCameraModel>(CreateIntrinsics(lensPosition, width, height), m_distortionPoly3k);\n            }\n\n            std::shared_ptr<const Rational6KCameraModel> CreateRational6kCameraModel(const boost::optional<uint32_t>& lensPosition, size_t width, size_t height) const\n            {\n                return std::make_shared<const Rational6KCameraModel>(CreateIntrinsics(lensPosition, width, height), m_distortionRational6k);\n            }\n\n\n            std::shared_ptr<const CameraModel> GetCameraModel(const boost::optional<uint32_t>& lensPosition, size_t width, size_t height)\n            {\n                if (HasPoly3kModel())\n                {\n                    return CreatePoly3kCameraModel(lensPosition, width, height);\n                }\n                else if (HasRational6kModel())\n                {\n                    return CreateRational6kCameraModel(lensPosition, width, height);\n                }\n                else\n                {\n                    return CreatePinholeCameraModel(lensPosition, width, height);\n                }\n            }\n\n            Line GetFx() const { return m_fx; }\n            Line GetFy() const { return m_fy; }\n            float GetCx() const { return m_cx; }\n            float GetCy() const { return m_cy; }\n            Bounds GetFocalBounds() const { return m_focalBounds; }\n            Size GetCalibrationSize() const { return m_calibrationSize; }\n\n            bool HasPoly3kModel()\n            {\n                return m_distortionPoly3k.size() > 0;\n            }\n\n            bool HasRational6kModel()\n            {\n                return m_distortionRational6k.size() > 0;\n            }\n\n            std::vector<float> GetDistortionPoly3k() const { return m_distortionPoly3k; }\n            std::vector<float> GetDistortionRational6k() const { return m_distortionRational6k; }\n\n        private:\n            //F = m*focusValue + b\n            Line m_fx, m_fy;\n            float m_cx, m_cy;\n            Bounds m_focalBounds;\n            Size m_calibrationSize;\n\n            //distortion\n            std::vector<float> m_distortionPoly3k;\n            std::vector<float> m_distortionRational6k;\n        };\n    }\n\n    struct Depth\n    {\n        static constexpr float INVALID_DEPTH = -1.0f;\n\n        float NearPlaneDepth;\n        float FarPlaneDepth;\n        gsl::span<const ProjectedPoint> SparseDepth;\n\n        Depth(float nearDepth, float farDepth, gsl::span<const ProjectedPoint> sparse)\n            : NearPlaneDepth{ nearDepth }, FarPlaneDepth{ farDepth }, SparseDepth{ sparse }\n        {}\n\n        Depth()\n            : NearPlaneDepth{ INVALID_DEPTH }, FarPlaneDepth{ INVALID_DEPTH }\n        {}\n    };\n}\n", "meta": {"hexsha": "053351a45539cb43860250fab3ca3f816d813288", "size": 13725, "ext": "h", "lang": "C", "max_stars_repo_path": "Core/MAGESLAM/Source/Data/Data.h", "max_stars_repo_name": "syntheticmagus/mageslam", "max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z", "max_issues_repo_path": "Core/MAGESLAM/Source/Data/Data.h", "max_issues_repo_name": "syntheticmagus/mageslam", "max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z", "max_forks_repo_path": "Core/MAGESLAM/Source/Data/Data.h", "max_forks_repo_name": "syntheticmagus/mageslam", "max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z", "avg_line_length": 33.8888888889, "max_line_length": 206, "alphanum_fraction": 0.5629872495, "num_tokens": 3301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.0390482952423748, "lm_q1q2_score": 0.018457483951266826}}
{"text": "/*\n * C version of Diffusive Nested Sampling (DNest4) by Brendon J. Brewer\n *\n * Yan-Rong Li, liyanrong@mail.ihep.ac.cn\n * Jun 30, 2016\n *\n */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n#include <unistd.h>\n#include <math.h>\n#include <float.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n\n#include \"dnestvars.h\"\n\ndouble dnest(int argc, char** argv, DNestFptrSet *fptrset, int num_params, \n             char *sample_dir, int max_num_saves, double ptol, const void *arg)\n{\n  int opt;\n  \n  dnest_arg = arg;\n  \n  dnest_check_fptrset(fptrset);\n\n  // cope with argv\n  \n  dnest_post_temp = 1.0;\n  dnest_flag_restart = 0;\n  dnest_flag_postprc = 0;\n  dnest_flag_sample_info = 0;\n  dnest_flag_limits = 0;\n\n  strcpy(file_save_restart, \"restart_dnest.txt\");\n  strcpy(dnest_sample_postfix, \"\\0\");\n  strcpy(dnest_sample_tag, \"\\0\");\n    \n  opterr = 0;\n  optind = 0;\n  while( (opt = getopt(argc, argv, \"r:s:pt:clx:g:\")) != -1)\n  {\n    switch(opt)\n    {\n      case 'r':\n        dnest_flag_restart = 1;\n        strcpy(file_restart, optarg);\n        printf(\"# Dnest restarts.\\n\");\n        break;\n      case 's':\n        strcpy(file_save_restart, optarg);\n        //printf(\"# Dnest sets restart file %s.\\n\", file_save_restart);\n        break;\n      case 'p':\n        dnest_flag_postprc = 1;\n        dnest_post_temp = 1.0;\n        printf(\"# Dnest does postprocess.\\n\");\n        break;\n      case 't':\n        dnest_post_temp = atof(optarg);\n        printf(\"# Dnest sets a temperature %f.\\n\", dnest_post_temp);\n        if(dnest_post_temp == 0.0)\n        {\n          printf(\"# Dnest incorrect option -t %s.\\n\", optarg);\n          exit(0);\n        }\n        if(dnest_post_temp < 1.0)\n        {\n          printf(\"# Dnest temperature should >= 1.0\\n\");\n          exit(0);\n        }\n        break;\n      case 'c':\n        dnest_flag_sample_info = 1;\n        printf(\"# Dnest recalculates sample information.\\n\");\n        break;\n      case 'l':\n        dnest_flag_limits = 1;\n        printf(\"# Dnest level-dependent sampling.\\n\");\n        break;\n      case 'x':\n        strcpy(dnest_sample_postfix, optarg);\n        printf(\"# Dnest sets sample postfix %s.\\n\", dnest_sample_postfix);\n        break;\n      case 'g':\n        strcpy(dnest_sample_tag, optarg);\n        printf(\"# Dnest sets sample tag %s.\\n\", dnest_sample_tag);\n        break;\n      case '?':\n        printf(\"# Dnest incorrect option -%c %s.\\n\", optopt, optarg);\n        exit(0);\n        break;\n      default:\n        break;\n    }\n  }\n  \n  setup(argc, argv, fptrset, num_params, sample_dir, max_num_saves, ptol);\n\n  if(dnest_flag_postprc == 1)\n  {\n    dnest_postprocess(dnest_post_temp, max_num_saves, ptol);\n    finalise();\n    return post_logz;\n  }\n\n  if(dnest_flag_sample_info == 1)\n  {\n    dnest_postprocess(dnest_post_temp, max_num_saves, ptol);\n    finalise();\n    return post_logz;\n  }\n\n  if(dnest_flag_restart==1)\n    dnest_restart();\n\n  initialize_output_file();\n  dnest_run();\n  close_output_file();\n\n  dnest_postprocess(dnest_post_temp, max_num_saves, ptol);\n\n  finalise();\n  \n  return post_logz;\n}\n\n// postprocess, calculate evidence, generate posterior sample.\nvoid dnest_postprocess(double temperature, int max_num_saves, double ptol)\n{\n  options_load(max_num_saves, ptol);\n  postprocess(temperature);\n}\n\nvoid dnest_run()\n{\n  int i, j, k, size_all_above_incr;\n  Level *pl, *levels_orig;\n  int *buf_size_above, *buf_displs;\n  double *plimits;\n  \n  printf(\"# Start diffusive nested sampling.\\n\");\n\n  while(true)\n  {\n    //check for termination\n    if(options.max_num_saves !=0 &&\n        count_saves != 0 && (count_saves%options.max_num_saves == 0))\n      break;\n\n    dnest_mcmc_run();\n\n    count_mcmc_steps += options.thread_steps;\n    \n    if(dnest_flag_limits == 1)\n    {\n      // limits of smaller levels should be larger than those of higher levels\n      for(j=size_levels-2; j >= 0; j--)\n        for(k=0; k<particle_offset_double; k++)\n        {\n          limits[ j * particle_offset_double *2 + k*2 ] = fmin( limits[ j * particle_offset_double *2 + k*2 ],\n                  limits[ (j+1) * particle_offset_double *2 + k*2 ] );\n          limits[ j * particle_offset_double *2 + k*2 + 1] = fmax( limits[ j * particle_offset_double *2 + k*2 +1 ],\n                  limits[ (j+1) * particle_offset_double *2 + k*2 + 1 ] );\n        }\n    }\n\n    do_bookkeeping();\n\n    if(count_mcmc_steps >= (count_saves + 1)*options.save_interval)\n    {\n      save_particle();\n\n      // save levels, limits, sync samples when running a number of steps\n      if( count_saves % num_saves == 0 )\n      {\n        if(size_levels <= options.max_num_levels)\n        {\n          save_levels();\n\n          printf(\"# Save levels at N= %d.\\n\", count_saves);\n        }\n        if(dnest_flag_limits == 1)\n          save_limits();\n        fflush(fsample_info);\n        fsync(fileno(fsample_info));\n        fflush(fsample);\n        fsync(fileno(fsample));\n        printf(\"# Save limits, and sync samples at N= %d.\\n\", count_saves);\n      }\n\n      //if( count_saves % num_saves_restart == 0 )\n      //{\n      //  dnest_save_restart();\n      //}\n    }\n  }\n  \n  //dnest_save_restart();\n\n  //save levels\n  save_levels();\n  if(dnest_flag_limits == 1)\n    save_limits();\n\n  /* output state of sampler */\n  FILE *fp;\n  fp = fopen(options.sampler_state_file, \"w\");\n  fprintf(fp, \"%d %d\\n\", size_levels, count_saves);\n  fclose(fp);\n}\n\nvoid do_bookkeeping()\n{\n  int i;\n  //bool created_level = false;\n\n  if(!enough_levels(levels, size_levels) && size_above >= options.new_level_interval)\n  {\n    // in descending order \n    qsort(above, size_above, sizeof(LikelihoodType), dnest_cmp);\n    int index = (int)( (1.0/compression) * size_above);\n\n    Level level_tmp = {above[index], 0.0, 0, 0, 0, 0};\n    levels[size_levels] = level_tmp;\n    size_levels++;\n    \n    printf(\"# Creating level %d with log likelihood = %e.\\n\", \n               size_levels-1, levels[size_levels-1].log_likelihood.value);\n\n    // clear out the last index records\n    for(i=index; i<size_above; i++)\n    {\n      above[i].value = 0.0;\n      above[i].tiebreaker = 0.0;\n    }\n    size_above = index;\n\n    if(enough_levels(levels, size_levels))\n    {\n      renormalise_visits();\n      options.max_num_levels = size_levels;\n      printf(\"# Done creating levles.\\n\");\n    }\n    else\n    {\n      kill_lagging_particles();\n    }\n  }\n  recalculate_log_X();\n}\n\nvoid recalculate_log_X()\n{\n  int i;\n\n  levels[0].log_X = 0.0;\n  for(i=1; i<size_levels; i++)\n  {\n    levels[i].log_X = levels[i-1].log_X \n    + log( (double)( (levels[i-1].exceeds + 1.0/compression * regularisation)\n                    /(levels[i-1].visits + regularisation)  ) );\n  }\n}\n\nvoid renormalise_visits()\n{\n  size_t i;\n\n  for(i=0; i<size_levels; i++)\n  {\n    if(levels[i].tries >= regularisation)\n    {\n      levels[i].accepts = ((double)(levels[i].accepts+1) / (double)(levels[i].tries+1)) * regularisation;\n      levels[i].tries = regularisation;\n    }\n\n    if(levels[i].visits >= regularisation)\n    {\n      levels[i].exceeds = ( (double) (levels[i].exceeds+1) / (double)(levels[i].visits + 1) ) * regularisation;\n      levels[i].visits = regularisation;\n    }\n  }\n}\n\nvoid kill_lagging_particles()\n{\n  static unsigned int deletions = 0;\n\n  bool *good;\n  good = (bool *)malloc(options.num_particles * sizeof(bool));\n\n  double max_log_push = -DBL_MAX;\n\n  double kill_probability = 0.0;\n  unsigned int num_bad = 0;\n  size_t i;\n\n  for(i=0; i<options.num_particles; i++)good[i] = true;\n\n  for(i=0; i<options.num_particles; i++)\n  {\n    if( log_push(level_assignments[i]) > max_log_push)\n      max_log_push = log_push(level_assignments[i]);\n\n    kill_probability = pow(1.0 - 1.0/(1.0 + exp(-log_push(level_assignments[i]) - 4.0)), 3);\n    if(gsl_rng_uniform(dnest_gsl_r) <= kill_probability)\n    {\n      good[i] = false;\n      ++num_bad;\n    }\n  }\n\n  if(num_bad < options.num_particles)\n  {\n    for(i=0; i< options.num_particles; i++)\n    {\n      if(!good[i])\n      {\n        int i_copy;\n        do\n        {\n          i_copy = gsl_rng_uniform_int(dnest_gsl_r, options.num_particles);\n        }while(!good[i_copy] || gsl_rng_uniform(dnest_gsl_r) >= exp(log_push(level_assignments[i_copy]) - max_log_push));\n\n        memcpy(particles+i*particle_offset_size, particles + i_copy*particle_offset_size, dnest_size_of_modeltype);\n        log_likelihoods[i] = log_likelihoods[i_copy];\n        level_assignments[i] = level_assignments[i_copy];\n         \n        kill_action(i, i_copy);\n\n        deletions++;\n\n        printf(\"# Replacing lagging particle.\\n\");\n        printf(\"# This has happened %d times.\\n\", deletions);\n      }\n    }\n  }\n  else\n    printf(\"# Warning: all particles lagging!.\\n\");\n\n  free(good);\n}\n\n/* save levels */\nvoid save_levels()\n{\n  if(!save_to_disk)\n    return;\n  \n  int i;\n  FILE *fp;\n\n  fp = fopen(options.levels_file, \"w\");\n  fprintf(fp, \"# log_X, log_likelihood, tiebreaker, accepts, tries, exceeds, visits\\n\");\n  for(i=0; i<size_levels; i++)\n  {\n    fprintf(fp, \"%14.12g %14.12g %f %llu %llu %llu %llu\\n\", levels[i].log_X, levels[i].log_likelihood.value, \n      levels[i].log_likelihood.tiebreaker, levels[i].accepts,\n      levels[i].tries, levels[i].exceeds, levels[i].visits);\n  }\n  fclose(fp);\n\n  /* update state of sampler */\n  fp = fopen(options.sampler_state_file, \"w\");\n  fprintf(fp, \"%d %d\\n\", size_levels, count_saves);\n  fclose(fp);\n}\n\nvoid save_limits()\n{\n  int i, j;\n  FILE *fp;\n\n  fp = fopen(options.limits_file, \"w\");\n  for(i=0; i<size_levels; i++)\n  {\n    fprintf(fp, \"%d  \", i);\n    for(j=0; j<particle_offset_double; j++)\n      fprintf(fp, \"%f  %f  \", limits[i*2*particle_offset_double+j*2], limits[i*2*particle_offset_double+j*2+1]);\n\n    fprintf(fp, \"\\n\");\n  }\n  fclose(fp);\n}\n\n/* save particle */\nvoid save_particle()\n{\n  count_saves++;\n\n  if(!save_to_disk)\n    return;\n  \n  int whichparticle, whichtask;\n  void *particle_message;\n  \n  if(count_saves%10 == 0)\n    printf(\"#[%.1f%%] Saving sample N= %d.\\n\", 100.0*count_saves/options.max_num_saves, count_saves);\n    \n  whichparticle =  gsl_rng_uniform_int(dnest_gsl_r,options.num_particles);\n\n  print_particle(fsample, particles + whichparticle * particle_offset_size, dnest_arg);\n\n  fprintf(fsample_info, \"%d %e %f %d\\n\", level_assignments[whichparticle], \n        log_likelihoods[whichparticle].value,\n        log_likelihoods[whichparticle].tiebreaker,\n        whichparticle);\n}\n\nvoid dnest_mcmc_run()\n{\n  unsigned int which;\n  unsigned int i;\n  \n  for(i = 0; i<options.thread_steps; i++)\n  {\n\n    /* randomly select out one particle to update */\n    which = gsl_rng_uniform_int(dnest_gsl_r, options.num_particles);\n\n    dnest_which_particle_update = which;\n\n    //if(count_mcmc_steps >= 10000)printf(\"FFFF\\n\");\n    //printf(\"%d\\n\", which);\n    //printf(\"%f %f %f\\n\", particles[which].param[0], particles[which].param[1], particles[which].param[2]);\n    //printf(\"level:%d\\n\", level_assignments[which]);\n    //printf(\"%e\\n\", log_likelihoods[which].value);\n\n    if(gsl_rng_uniform(dnest_gsl_r) <= 0.5)\n    {\n      update_particle(which);\n      update_level_assignment(which);\n    }\n    else\n    {\n      update_level_assignment(which);\n      update_particle(which);\n    }\n        \n    if( !enough_levels(levels, size_levels)  && levels[size_levels-1].log_likelihood.value < log_likelihoods[which].value)\n    {\n      above[size_above] = log_likelihoods[which];\n      size_above++;\n    }\n  }\n}\n\n\nvoid update_particle(unsigned int which)\n{\n  void *particle = particles+ which*particle_offset_size;\n  LikelihoodType *logl = &(log_likelihoods[which]);\n  \n  Level *level = &(levels[level_assignments[which]]);\n\n  void *proposal = (void *)malloc(dnest_size_of_modeltype);\n  LikelihoodType logl_proposal;\n  double log_H;\n\n  memcpy(proposal, particle, dnest_size_of_modeltype);\n  dnest_which_level_update = level_assignments[which];\n  \n  log_H = perturb(proposal, dnest_arg);\n  \n  logl_proposal.value = log_likelihoods_cal(proposal, dnest_arg);\n  logl_proposal.tiebreaker =  (*logl).tiebreaker + gsl_rng_uniform(dnest_gsl_r);\n  dnest_wrap(&logl_proposal.tiebreaker, 0.0, 1.0);\n  \n  if(log_H > 0.0)\n    log_H = 0.0;\n\n  dnest_perturb_accept[which] = 0;\n  if( gsl_rng_uniform(dnest_gsl_r) <= exp(log_H) && level->log_likelihood.value < logl_proposal.value)\n  {\n    memcpy(particle, proposal, dnest_size_of_modeltype);\n    memcpy(logl, &logl_proposal, sizeof(LikelihoodType));\n    level->accepts++;\n\n    dnest_perturb_accept[which] = 1;\n    accept_action();\n    account_unaccepts[which] = 0; /* reset the number of unaccepted perturb */\n  }\n  else \n  {\n    account_unaccepts[which] += 1; /* number of unaccepted perturb */\n  }\n  level->tries++;\n  \n  unsigned int current_level = level_assignments[which];\n  for(; current_level < size_levels-1; ++current_level)\n  {\n    levels[current_level].visits++;\n    if(levels[current_level+1].log_likelihood.value < log_likelihoods[which].value)\n      levels[current_level].exceeds++;\n    else\n      break; // exit the loop if it does not satify higher levels\n  }\n  free(proposal);\n}\n\nvoid update_level_assignment(unsigned int which)\n{\n  int i;\n\n  int proposal = level_assignments[which] \n                 + (int)( pow(10.0, 2*gsl_rng_uniform(dnest_gsl_r))*gsl_ran_ugaussian(dnest_gsl_r));\n\n  if(proposal == level_assignments[which])\n    proposal =  ((gsl_rng_uniform(dnest_gsl_r) < 0.5)?(proposal-1):(proposal+1));\n\n  proposal=mod_int(proposal, size_levels);\n\n  double log_A = -levels[proposal].log_X + levels[level_assignments[which]].log_X;\n\n  log_A += log_push(proposal) - log_push(level_assignments[which]);\n\n  if(size_levels == options.max_num_levels)\n    log_A += options.beta*log( (double)(levels[level_assignments[which]].tries +1)/ (levels[proposal].tries +1) );\n\n  if(log_A > 0.0)\n    log_A = 0.0;\n\n  if( gsl_rng_uniform(dnest_gsl_r) <= exp(log_A) && levels[proposal].log_likelihood.value < log_likelihoods[which].value)\n  {\n    level_assignments[which] = proposal;\n\n// update the limits of the level\n    if(dnest_flag_limits == 1)\n    {\n      double *particle = (double *) (particles+ which*particle_offset_size);\n      for(i=0; i<particle_offset_double; i++)\n      {\n        limits[proposal * 2 * particle_offset_double +  i*2] = \n            fmin(limits[proposal * 2* particle_offset_double +  i*2], particle[i]);\n        limits[proposal * 2 * particle_offset_double +  i*2+1] = \n            fmax(limits[proposal * 2 * particle_offset_double +  i*2+1], particle[i]);\n      }\n    }\n\n  }\n\n}\n\ndouble log_push(unsigned int which_level)\n{\n  if(which_level > size_levels)\n  {\n    printf(\"level overflow %d %d.\\n\", which_level, size_levels);\n    exit(0);\n  }\n  if(enough_levels(levels, size_levels))\n    return 0.0;\n\n  int i = which_level - (size_levels - 1);\n  return ((double)i)/options.lambda;\n}\n\nbool enough_levels(Level *l, int size_l)\n{\n  int i;\n\n  if(options.max_num_levels == 0)\n  {\n    if(size_l >= LEVEL_NUM_MAX)\n      return true;\n\n    if(size_l < 10)\n      return false;\n\n    int num_levels_to_check = 20;\n    if(size_l > 80)\n      num_levels_to_check = (int)(sqrt(20) * sqrt(0.25*size_l));\n\n    int k = size_l - 1, kc = 0;\n    double tot = 0.0;\n    double max = -DBL_MAX;\n    double diff;\n\n    for(i= 0; i<num_levels_to_check; i++)\n    {\n      diff = l[k].log_likelihood.value - l[k-1].log_likelihood.value;\n      tot += diff;\n      if(diff > max)\n        max = diff;\n\n      k--;\n      kc++;\n      if( k < 1 )\n        break;\n    }\n    if(tot/kc < options.max_ptol && max < options.max_ptol*1.1)\n      return true;\n    else\n      return false;\n  }\n  return (size_l >= options.max_num_levels);\n}\n\nvoid initialize_output_file()\n{\n  if(dnest_flag_restart !=1)\n    fsample = fopen(options.sample_file, \"w\");\n  else\n    fsample = fopen(options.sample_file, \"a\");\n  \n  if(fsample==NULL)\n  {\n    fprintf(stderr, \"# Cannot open file sample.txt.\\n\");\n    exit(0);\n  }\n  if(dnest_flag_restart != 1)\n    fprintf(fsample, \"# \\n\");\n\n  if(dnest_flag_restart != 1)\n    fsample_info = fopen(options.sample_info_file, \"w\");\n  else\n    fsample_info = fopen(options.sample_info_file, \"a\");\n\n  if(fsample_info==NULL)\n  {\n    fprintf(stderr, \"# Cannot open file %s.\\n\", options.sample_info_file);\n    exit(0);\n  }\n  if(dnest_flag_restart != 1)\n    fprintf(fsample_info, \"# level assignment, log likelihood, tiebreaker, ID.\\n\");\n}\n\nvoid close_output_file()\n{\n  fclose(fsample);\n  fclose(fsample_info);\n}\n\nvoid setup(int argc, char** argv, DNestFptrSet *fptrset, int num_params, char *sample_dir, int max_num_saves, double ptol)\n{\n  int i, j;\n\n  // root task.\n  dnest_root = 0;\n\n  // setup function pointers\n  from_prior = fptrset->from_prior;\n  log_likelihoods_cal = fptrset->log_likelihoods_cal;\n  log_likelihoods_cal_initial = fptrset->log_likelihoods_cal_initial;\n  log_likelihoods_cal_restart = fptrset->log_likelihoods_cal_restart;\n  perturb = fptrset->perturb;\n  print_particle = fptrset->print_particle;\n  read_particle = fptrset->read_particle;\n  restart_action = fptrset->restart_action;\n  accept_action = fptrset->accept_action;\n  kill_action = fptrset->kill_action;\n  strcpy(dnest_sample_dir, sample_dir);\n\n  // random number generator\n  dnest_gsl_T = (gsl_rng_type *) gsl_rng_default;\n  dnest_gsl_r = gsl_rng_alloc (dnest_gsl_T);\n#ifndef Debug\n  gsl_rng_set(dnest_gsl_r, time(NULL));\n#else\n  gsl_rng_set(dnest_gsl_r, 9999);\n  printf(\"# debugging, dnest random seed %d\\n\", 9999);\n#endif  \n  \n  dnest_num_params = num_params;\n  dnest_size_of_modeltype = dnest_num_params * sizeof(double);\n\n  // read options\n  options_load(max_num_saves, ptol);\n\n  //dnest_post_temp = 1.0;\n  compression = exp(1.0);\n  regularisation = options.new_level_interval*sqrt(options.lambda);\n  save_to_disk = true;\n\n  // particles\n  particle_offset_size = dnest_size_of_modeltype/sizeof(void);\n  particle_offset_double = dnest_size_of_modeltype/sizeof(double);\n  particles = (void *)malloc(options.num_particles*dnest_size_of_modeltype);\n  \n  // initialise sampler\n  above = (LikelihoodType *)malloc(2*options.new_level_interval * sizeof(LikelihoodType));\n\n  log_likelihoods = (LikelihoodType *)malloc(2*options.num_particles * sizeof(LikelihoodType));\n  level_assignments = (unsigned int*)malloc(options.num_particles * sizeof(unsigned int));\n\n  account_unaccepts = (unsigned int *)malloc(options.num_particles * sizeof(unsigned int));\n  for(i=0; i<options.num_particles; i++)\n  {\n    account_unaccepts[i] = 0;\n  }\n\n  if(options.max_num_levels != 0)\n  {\n    levels = (Level *)malloc(options.max_num_levels * sizeof(Level));\n    if(dnest_flag_limits == 1)\n    {\n      limits = malloc(options.max_num_levels * particle_offset_double * 2 * sizeof(double));\n      for(i=0; i<options.max_num_levels; i++)\n      {\n        for(j=0; j<particle_offset_double; j++)\n        {\n          limits[i*2*particle_offset_double+ j*2] = DBL_MAX;\n          limits[i*2*particle_offset_double + j*2 + 1] = -DBL_MAX;\n        }\n      }\n    }\n  }\n  else\n  {\n    levels = (Level *)malloc(LEVEL_NUM_MAX * sizeof(Level));\n\n    if(dnest_flag_limits == 1)\n    {\n      limits = malloc(LEVEL_NUM_MAX * particle_offset_double * 2 * sizeof(double));\n      for(i=0; i<LEVEL_NUM_MAX; i++)\n      {\n        for(j=0; j<particle_offset_double; j++)\n        {\n          limits[i*2*particle_offset_double + j*2] = DBL_MAX;\n          limits[i*2*particle_offset_double + j*2 + 1] = -DBL_MAX;\n        }\n      }\n    }\n  }\n  \n  dnest_perturb_accept = malloc(options.num_particles * sizeof(int));\n  for(i=0; i<options.num_particles; i++)\n  {\n    dnest_perturb_accept[i] = 0;\n  }\n\n  count_mcmc_steps = 0;\n  count_saves = 0;\n  num_saves = (int)fmax(0.02*options.max_num_saves, 1.0);\n  num_saves_restart = (int)fmax(0.2 * options.max_num_saves, 1.0);\n\n// first level\n  size_levels = 0;\n  size_above = 0;\n  LikelihoodType like_tmp = {-DBL_MAX, gsl_rng_uniform(dnest_gsl_r)};\n  Level level_tmp = {like_tmp, 0.0, 0, 0, 0, 0};\n  levels[size_levels] = level_tmp;\n  size_levels++;\n  \n  for(i=0; i<options.num_particles; i++)\n  {\n    dnest_which_particle_update = i;\n    dnest_which_level_update = 0;\n    from_prior(particles+i*particle_offset_size, dnest_arg);\n    log_likelihoods[i].value = log_likelihoods_cal_initial(particles+i*particle_offset_size, dnest_arg);\n    log_likelihoods[i].tiebreaker = dnest_rand();\n    level_assignments[i] = 0;\n  }\n\n  /*ModelType proposal;\n  printf(\"%f %f %f \\n\", particles[0].param[0], particles[0].param[1], particles[0].param[2] );\n  proposal = particles[0];\n  printf(\"%f %f %f \\n\", proposal.param[0], proposal.param[1], proposal.param[2] );*/\n}\n\nvoid finalise()\n{\n  free(particles);\n  free(above);\n  free(log_likelihoods);\n  free(level_assignments);\n  free(levels);\n\n  free(account_unaccepts);\n\n  if(dnest_flag_limits == 1)\n    free(limits);\n\n  gsl_rng_free(dnest_gsl_r);\n\n  free(dnest_perturb_accept);\n\n  printf(\"# Finalizing dnest.\\n\");\n}\n\n\nvoid options_load(int max_num_saves, double ptol)\n{\n  //sscanf(buf, \"%d\", &options.num_particles);\n  options.num_particles = 2;\n\n  //fgets(buf, BUF_MAX_LENGTH, fp);\n  //sscanf(buf, \"%d\", &options.new_level_interval);\n  options.new_level_interval = options.num_particles * dnest_num_params*10;\n\n  //fgets(buf, BUF_MAX_LENGTH, fp);\n  //sscanf(buf, \"%d\", &options.save_interval);\n  options.save_interval = options.new_level_interval;\n\n  //fgets(buf, BUF_MAX_LENGTH, fp);\n  //sscanf(buf, \"%d\", &options.thread_steps);\n  options.thread_steps = options.new_level_interval;\n\n  //fgets(buf, BUF_MAX_LENGTH, fp);\n  //sscanf(buf, \"%d\", &options.max_num_levels);\n  options.max_num_levels = 0;\n\n  //fgets(buf, BUF_MAX_LENGTH, fp);\n  //sscanf(buf, \"%lf\", &options.lambda);\n  options.lambda = 10.0;\n\n  //fgets(buf, BUF_MAX_LENGTH, fp);\n  //sscanf(buf, \"%lf\", &options.beta);\n  options.beta = 100.0;\n\n  //fgets(buf, BUF_MAX_LENGTH, fp);\n  //sscanf(buf, \"%d\", &options.max_num_saves);\n  options.max_num_saves = max_num_saves;\n\n  options.max_ptol = ptol;\n\n  //fgets(buf, BUF_MAX_LENGTH, fp);\n  //sscanf(buf, \"%s\", options.sample_file);\n  strcpy(options.sample_file, dnest_sample_dir);\n  strcat(options.sample_file,\"/sample\");\n  strcat(options.sample_file, dnest_sample_tag);\n  strcat(options.sample_file, \".txt\");\n  strcat(options.sample_file, dnest_sample_postfix);\n  \n  //fgets(buf, BUF_MAX_LENGTH, fp);\n  //sscanf(buf, \"%s\", options.sample_info_file);\n  strcpy(options.sample_info_file, dnest_sample_dir);\n  strcat(options.sample_info_file,\"/sample_info\");\n  strcat(options.sample_info_file, dnest_sample_tag);\n  strcat(options.sample_info_file, \".txt\");\n  strcat(options.sample_info_file, dnest_sample_postfix);\n  \n  //fgets(buf, BUF_MAX_LENGTH, fp);\n  //sscanf(buf, \"%s\", options.levels_file);\n  strcpy(options.levels_file, dnest_sample_dir);\n  strcat(options.levels_file,\"/levels\");\n  strcat(options.levels_file, dnest_sample_tag);\n  strcat(options.levels_file, \".txt\");\n  strcat(options.levels_file, dnest_sample_postfix);\n  \n  //fgets(buf, BUF_MAX_LENGTH, fp);\n  //sscanf(buf, \"%s\", options.sampler_state_file);\n  strcpy(options.sampler_state_file, dnest_sample_dir);\n  strcat(options.sampler_state_file,\"/sampler_state\");\n  strcat(options.sampler_state_file, dnest_sample_tag);\n  strcat(options.sampler_state_file, \".txt\");\n  strcat(options.sampler_state_file, dnest_sample_postfix);\n  \n  //fgets(buf, BUF_MAX_LENGTH, fp);\n  //sscanf(buf, \"%s\", options.posterior_sample_file);\n  strcpy(options.posterior_sample_file, dnest_sample_dir);\n  strcat(options.posterior_sample_file,\"/posterior_sample\");\n  strcat(options.posterior_sample_file, dnest_sample_tag);\n  strcat(options.posterior_sample_file, \".txt\");\n  strcat(options.posterior_sample_file, dnest_sample_postfix);\n\n  //fgets(buf, BUF_MAX_LENGTH, fp);\n  //sscanf(buf, \"%s\", options.posterior_sample_info_file);\n  strcpy(options.posterior_sample_info_file, dnest_sample_dir);\n  strcat(options.posterior_sample_info_file,\"/posterior_sample_info\");\n  strcat(options.posterior_sample_info_file, dnest_sample_tag);\n  strcat(options.posterior_sample_info_file, \".txt\");\n  strcat(options.posterior_sample_info_file, dnest_sample_postfix);\n\n  //fgets(buf, BUF_MAX_LENGTH, fp);\n  //sscanf(buf, \"%s\", options.limits_file);\n  strcpy(options.limits_file, dnest_sample_dir);\n  strcat(options.limits_file,\"/limits\");\n  strcat(options.limits_file, dnest_sample_tag);\n  strcat(options.limits_file, \".txt\");\n  strcat(options.limits_file, dnest_sample_postfix);\n\n  // check options.\n  \n  if(options.new_level_interval < options.thread_steps)\n  {\n    printf(\"# incorrect options:\\n\");\n    printf(\"# new level interval should be equal to or larger than\"); \n    printf(\"  totaltask * thread step.\\n\");\n    exit(0);\n  }\n\n/*  strcpy(options.sample_file, \"sample.txt\");\n  strcpy(options.sample_info_file, \"sample_info.txt\");\n  strcpy(options.levels_file, \"levels.txt\");\n  strcpy(options.sampler_state_file, \"sampler_state.txt\");*/\n}\n\n\ndouble mod(double y, double x)\n{\n  if(x > 0.0)\n  {\n    return (y/x - floor(y/x))*x;\n  }\n  else if(x == 0.0)\n  {\n    return 0.0;\n  }\n  else\n  {\n    printf(\"Warning in mod(double, double) %e\\n\", x);\n    exit(0);\n  }\n  \n}\n\nvoid dnest_wrap(double *x, double min, double max)\n{\n  *x = mod(*x - min, max - min) + min;\n}\n\nvoid wrap_limit(double *x, double min, double max)\n{\n\n  *x = fmax(fmin(*x, max), min);\n}\n\nint mod_int(int y, int x)\n{\n  if(y >= 0)\n    return y - (y/x)*x;\n  else\n    return (x-1) - mod_int(-y-1, x);\n}\n\ndouble dnest_randh()\n{\n  return pow(10.0, 1.5 - 3.0*fabs(gsl_ran_tdist(dnest_gsl_r, 2))) * gsl_ran_ugaussian(dnest_gsl_r);\n}\n\ndouble dnest_rand()\n{\n  return gsl_rng_uniform(dnest_gsl_r);\n}\n\nint dnest_rand_int(int size)\n{\n  return gsl_rng_uniform_int(dnest_gsl_r, size);\n}\n\ndouble dnest_randn()\n{\n  return gsl_ran_ugaussian(dnest_gsl_r);\n}\n\nint dnest_cmp(const void *pa, const void *pb)\n{\n  LikelihoodType *a = (LikelihoodType *)pa;\n  LikelihoodType *b = (LikelihoodType *)pb;\n\n  // in decesending order\n  if(a->value > b->value)\n    return false;\n  if( a->value == b->value && a->tiebreaker > b->tiebreaker)\n    return false;\n  \n  return true;\n}\n\n\nint dnest_get_size_levels()\n{\n  return size_levels;\n}\n\nint dnest_get_which_level_update()\n{\n  return dnest_which_level_update;\n}\n\nint dnest_get_which_particle_update()\n{\n  return dnest_which_particle_update;\n}\n\nunsigned int dnest_get_which_num_saves()\n{\n  return num_saves;\n}\nunsigned int dnest_get_count_saves()\n{\n  return count_saves;\n}\n\nunsigned long long int dnest_get_count_mcmc_steps()\n{\n  return count_mcmc_steps;\n}\n\nvoid dnest_get_posterior_sample_file(char *fname)\n{\n  strcpy(fname, options.posterior_sample_file);\n  return;\n}\n/* \n * version check\n * \n *  1: greater\n *  0: equal\n * -1: lower\n */\nint dnest_check_version(char *version_str)\n{\n  int major, minor, patch;\n\n  sscanf(version_str, \"%d.%d.%d\", &major, &minor, &patch);\n  \n  if(major > DNEST_MAJOR_VERSION)\n    return 1;\n  if(major < DNEST_MAJOR_VERSION)\n    return -1;\n\n  if(minor > DNEST_MINOR_VERSION)\n    return 1;\n  if(minor < DNEST_MINOR_VERSION)\n    return -1;\n\n  if(patch > DNEST_PATCH_VERSION)\n    return 1;\n  if(patch > DNEST_PATCH_VERSION)\n    return -1;\n\n  return 0;\n}\n\nvoid dnest_check_fptrset(DNestFptrSet *fptrset)\n{\n  if(fptrset->from_prior == NULL)\n  {\n    printf(\"\\\"from_prior\\\" function is not defined.\\n\");\n    exit(0);\n  }\n\n  if(fptrset->print_particle == NULL)\n  {\n    //printf(\"\\\"print_particle\\\" function is not defined. \\\n    //  \\nSet to be default function in dnest.\\n\");\n    fptrset->print_particle = dnest_print_particle;\n  }\n\n  if(fptrset->read_particle == NULL)\n  {\n    //printf(\"\\\"read_particle\\\" function is not defined. \\\n    //  \\nSet to be default function in dnest.\\n\");\n    fptrset->read_particle = dnest_read_particle;\n  }\n\n  if(fptrset->log_likelihoods_cal == NULL)\n  {\n    printf(\"\\\"log_likelihoods_cal\\\" function is not defined.\\n\");\n    exit(0);\n  }\n\n  if(fptrset->log_likelihoods_cal_initial == NULL)\n  {\n    //printf(\"\\\"log_likelihoods_cal_initial\\\" function is not defined. \\\n    //  \\nSet to the same as \\\"log_likelihoods_cal\\\" function.\\n\");\n    fptrset->log_likelihoods_cal_initial = fptrset->log_likelihoods_cal;\n  }\n\n  if(fptrset->log_likelihoods_cal_restart == NULL)\n  {\n    //printf(\"\\\"log_likelihoods_cal_restart\\\" function is not defined. \\\n    //  \\nSet to the same as \\\"log_likelihoods_cal\\\" function.\\n\");\n    fptrset->log_likelihoods_cal_restart = fptrset->log_likelihoods_cal;\n  }\n\n  if(fptrset->perturb == NULL)\n  {\n    printf(\"\\\"perturb\\\" function is not defined.\\n\");\n    exit(0);\n  }\n\n  if(fptrset->restart_action == NULL)\n  {\n    //printf(\"\\\"restart_action\\\" function is not defined.\\\n    //  \\nSet to the default function in dnest.\\n\");\n    fptrset->restart_action = dnest_restart_action;\n  }\n\n  if(fptrset->accept_action == NULL)\n  {\n    //printf(\"\\\"accept_action\\\" function is not defined.\\\n    //  \\nSet to the default function in dnest.\\n\");\n    fptrset->accept_action = dnest_accept_action;\n  }\n\n  if(fptrset->kill_action == NULL)\n  {\n    //printf(\"\\\"kill_action\\\" function is not defined.\\\n    //  \\nSet to the default function in dnest.\\n\");\n    fptrset->kill_action = dnest_kill_action;\n  }\n\n  return;\n}\n\nDNestFptrSet * dnest_malloc_fptrset()\n{\n  DNestFptrSet * fptrset;\n  fptrset = (DNestFptrSet *)malloc(sizeof(DNestFptrSet));\n\n  fptrset->from_prior = NULL;\n  fptrset->log_likelihoods_cal = NULL;\n  fptrset->log_likelihoods_cal_initial = NULL;\n  fptrset->log_likelihoods_cal_restart = NULL;\n  fptrset->perturb = NULL;\n  fptrset->print_particle = NULL;\n  fptrset->read_particle = NULL;\n  fptrset->restart_action = NULL;\n  fptrset->accept_action = NULL;\n  fptrset->kill_action = NULL;\n  return fptrset;\n}\n\nvoid dnest_free_fptrset(DNestFptrSet * fptrset)\n{\n  free(fptrset);\n  return;\n}\n\n\n/*!\n *  Save sampler state for later restart. \n */\nvoid dnest_save_restart()\n{\n  FILE *fp;\n  int i, j;\n  void *particles_all;\n  LikelihoodType *log_likelihoods_all;\n  unsigned int *level_assignments_all;\n  char str[200];\n\n  \n  sprintf(str, \"%s_%d\", file_save_restart, count_saves);\n  fp = fopen(str, \"wb\");\n  if(fp == NULL)\n  {\n    fprintf(stderr, \"# Error: Cannot open file %s. \\n\", file_save_restart);\n    exit(0);\n  }\n\n  \n  printf(\"# Save restart data to file %s.\\n\", str);\n\n    //fprintf(fp, \"%d %d\\n\", count_saves, count_mcmc_steps);\n    //fprintf(fp, \"%d\\n\", size_levels_combine);\n\n  fwrite(&count_saves, sizeof(int), 1, fp);\n  fwrite(&count_mcmc_steps, sizeof(int), 1, fp);\n  fwrite(&size_levels, sizeof(int), 1, fp);\n\n  for(i=0; i<size_levels; i++)\n  {\n    //fprintf(fp, \"%14.12g %14.12g %f %llu %llu %llu %llu\\n\", levels_combine[i].log_X, levels_combine[i].log_likelihood.value, \n    //  levels_combine[i].log_likelihood.tiebreaker, levels_combine[i].accepts,\n    //  levels_combine[i].tries, levels[i].exceeds, levels_combine[i].visits);\n\n    fwrite(&levels[i], sizeof(Level), 1, fp);\n  }\n\n  for(i=0; i<options.num_particles; i++)\n  {\n    //fprintf(fp, \"%d %e %f\\n\", level_assignments_all[j*options.num_particles + i], \n    //  log_likelihoods_all[j*options.num_particles + i].value,\n    //  log_likelihoods_all[j*options.num_particles + i].tiebreaker);  \n    fwrite(&level_assignments[j*options.num_particles + i], sizeof(int), 1, fp);\n    fwrite(&log_likelihoods[j*options.num_particles + i], sizeof(LikelihoodType), 1, fp);    \n  }\n    \n    \n  if(dnest_flag_limits == 1)\n  {\n    for(i=0; i<size_levels; i++)\n    {\n      //fprintf(fp, \"%d  \", i);\n      for(j=0; j<particle_offset_double; j++)\n      {\n        //fprintf(fp, \"%f  %f  \", limits[i*2*particle_offset_double+j*2], limits[i*2*particle_offset_double+j*2+1]);\n        fwrite(&limits[i*2*particle_offset_double+j*2], sizeof(double), 2, fp);\n      }\n\n        //fprintf(fp, \"\\n\");\n    }\n  }\n    \n\n  for(i=0; i<options.num_particles; i++)\n  {\n    //print_particle(fp, particles_all + (j * options.num_particles + i) * particle_offset_size);\n    fwrite(particles + (j * options.num_particles + i) * particle_offset_size, dnest_size_of_modeltype, 1, fp);\n  } \n    \n  fclose(fp);\n\n  restart_action(0);\n}\n\nvoid dnest_restart()\n{\n  FILE *fp;\n  int i, j;\n  void *particles_all;\n  unsigned int *level_assignments_all;\n  LikelihoodType *log_likelihoods_all;\n  void *particle;\n\n  fp = fopen(file_restart, \"rb\");\n  if(fp == NULL)\n  {\n    fprintf(stderr, \"# Error: Cannot open file %s. \\n\", file_restart);\n    exit(0);\n  }\n\n  printf(\"# Reading %s\\n\", file_restart);\n\n  fread(&count_saves, sizeof(int), 1, fp);\n  fread(&count_mcmc_steps, sizeof(int), 1, fp);\n  fread(&size_levels, sizeof(int), 1, fp);\n    \n  /* consider that the newly input max_num_levels may be different from the save one */\n  if(options.max_num_levels != 0)\n  {\n    if(size_levels > options.max_num_levels)\n    {\n      printf(\"# input max_num_levels %d smaller than the one in restart data %d.\\n\", options.max_num_levels, size_levels);\n      size_levels = options.max_num_levels;\n    }   \n  }\n    // read levels\n  for(i=0; i<size_levels; i++)\n  {     \n    if(i<size_levels) // not read all the levels\n      fread(&levels[i], sizeof(Level), 1, fp);\n    else\n      fseek(fp, sizeof(Level), SEEK_CUR); /* offset the file point */\n  }\n    memcpy(levels, levels, size_levels * sizeof(Level));\n\n    // read level assignment\n  for(i=0; i<options.num_particles; i++)\n  {\n    fread(&level_assignments[j*options.num_particles + i], sizeof(int), 1, fp);\n    fread(&log_likelihoods[j*options.num_particles + i], sizeof(LikelihoodType), 1, fp); \n    \n    /* reset the level assignment that exceeds the present maximum level */\n    if(level_assignments[j*options.num_particles + i] > size_levels -1)\n    {\n      level_assignments[j*options.num_particles + i] = size_levels - 1;\n    }\n  }\n\n  // read limits\n  if(dnest_flag_limits == 1)\n  {\n    for(i=0; i<size_levels; i++)\n    {\n      if(i < size_levels)\n      {\n        for(j=0; j<particle_offset_double; j++)\n        {\n          fread(&limits[i*2*particle_offset_double+j*2], sizeof(double), 2, fp);      \n        }\n      }\n      else \n      {\n        fseek(fp, sizeof(double) * 2 * particle_offset_double, SEEK_CUR); /* offset the file point */\n      }\n    }\n  }\n\n  // read particles\n  for(i=0; i<options.num_particles; i++)\n  {\n    particle = (particles + (j * options.num_particles + i) * dnest_size_of_modeltype);\n    fread(particle, dnest_size_of_modeltype, 1, fp);\n  }\n\n  fclose(fp);\n\n  if(count_saves > options.max_num_saves)\n  {\n    printf(\"# Number of samples already larger than the input number, exit!\\n\");\n    exit(0);\n  }\n  \n  num_saves = (int)fmax(0.02*(options.max_num_saves-count_saves), 1.0); /* reset num_saves */\n  num_saves_restart = (int)fmax(0.2 * (options.max_num_saves-count_saves), 1.0); /* reset num_saves_restart */\n\n  restart_action(1);\n\n  for(i=0; i<options.num_particles; i++)\n  {\n    dnest_which_particle_update = i;\n    dnest_which_level_update = level_assignments[i];\n    //printf(\"%d %d %f\\n\", thistask, i, log_likelihoods[i].value);\n    log_likelihoods[i].value = log_likelihoods_cal_restart(particles+i*particle_offset_size, dnest_arg);\n    //printf(\"%d %d %f\\n\", thistask, i, log_likelihoods[i].value);\n    //due to randomness, the original level assignment may be incorrect. re-asign the level\n    while(log_likelihoods[i].value < levels[level_assignments[i]].log_likelihood.value)\n    {\n      printf(\"# level assignment decrease %d %f %f %d.\\n\", i, log_likelihoods[i].value, \n        levels[level_assignments[i]].log_likelihood.value, level_assignments[i]);\n      level_assignments[i]--;\n    }\n    \n  }\n  return;\n}\n\nvoid dnest_print_particle(FILE *fp, const void *model, const void *arg)\n{\n  int i;\n  double *pm = (double *)model;\n\n  for(i=0; i<dnest_num_params; i++)\n  {\n    fprintf(fp, \"%e \", pm[i] );\n  }\n  fprintf(fp, \"\\n\");\n  return;\n}\n\nvoid dnest_read_particle(FILE *fp, void *model)\n{\n  int j;\n  double *psample = (double *)model;\n\n  for(j=0; j < dnest_num_params; j++)\n  {\n    if(fscanf(fp, \"%lf\", psample+j) < 1)\n    {\n      printf(\"%f\\n\", *psample);\n      fprintf(stderr, \"#Error: Cannot read file %s.\\n\", options.sample_file);\n      exit(0);\n    }\n  }\n  return;\n}\n\nvoid dnest_restart_action(int iflag)\n{\n  return;\n}\n\nvoid dnest_accept_action()\n{\n  return;\n}\n\nvoid dnest_kill_action(int i, int i_copy)\n{\n  return;\n}\n\n\n\n", "meta": {"hexsha": "f82a64930ba2fa3f0e93806d8ebad0852a14698a", "size": 35886, "ext": "c", "lang": "C", "max_stars_repo_path": "src/pycali/cdnest/dnest.c", "max_stars_repo_name": "LiyrAstroph/PyCALI", "max_stars_repo_head_hexsha": "e232531b5c6f7817b6e3bd34dbb31463807ae2b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-01-14T01:32:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T09:23:59.000Z", "max_issues_repo_path": "src/pycali/cdnest/dnest.c", "max_issues_repo_name": "LiyrAstroph/pyCALI", "max_issues_repo_head_hexsha": "e232531b5c6f7817b6e3bd34dbb31463807ae2b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pycali/cdnest/dnest.c", "max_forks_repo_name": "LiyrAstroph/pyCALI", "max_forks_repo_head_hexsha": "e232531b5c6f7817b6e3bd34dbb31463807ae2b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-02-05T02:01:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-06T11:26:06.000Z", "avg_line_length": 26.3093841642, "max_line_length": 127, "alphanum_fraction": 0.6566070334, "num_tokens": 10224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.039048291607938254, "lm_q1q2_score": 0.018457482233328725}}
{"text": "#pragma once\n\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n\ngsl_rng *RandomNumberGenerator; /* Random number generator. */\nunsigned RandomSeed; /* Random seed. */\n\nunsigned GetRandomSeed()\n{\n  FILE *random_file;\n  unsigned seed;\n  int error;\n\n  seed = 0;\n  random_file = fopen(\"/dev/urandom\", \"rb\");\n  if (!random_file)\n    return 0;\n  do\n  {\n    error = fread(&seed, 1, sizeof(unsigned int), random_file);\n    if (error != sizeof(unsigned int))\n      return 0;\n  }\n  while (!seed);\n  fclose(random_file);\n  return seed;\n}\n\n/** InitialiseRandom.\n\n    - Initialises the random number generator. **/\n\nint InitialiseRandom(const gsl_rng_type *random_generator)\n{\n  RandomSeed = GetRandomSeed();\n  if (!RandomSeed)\n    return EXIT_FAILURE;\n  RandomNumberGenerator = gsl_rng_alloc(random_generator);\n  if (!RandomNumberGenerator)\n    return EXIT_FAILURE;\n  gsl_rng_set(RandomNumberGenerator, RandomSeed);\n  return EXIT_SUCCESS;\n}\n\n/** FinaliseRandom.\n\n    - Finalises the random number generator. **/\n\nint FinaliseRandom()\n{\n  /* Release random number generator memory. */\n\n  if (RandomNumberGenerator)\n  {\n    gsl_rng_free(RandomNumberGenerator);\n    return EXIT_SUCCESS; // EXIT_SUCCESS = 0\n  }\n  return EXIT_FAILURE; // EXIT_FAILURE = 1\n}\n\n/////////////\n", "meta": {"hexsha": "69b218ed8776e3eb9fa141350173bd85a0c9de8c", "size": 1261, "ext": "h", "lang": "C", "max_stars_repo_path": "src/lib/nrMath/random.h", "max_stars_repo_name": "eduardomgutierrez/RIAF_radproc", "max_stars_repo_head_hexsha": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-30T06:56:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-30T06:56:03.000Z", "max_issues_repo_path": "src/lib/nrMath/random.h", "max_issues_repo_name": "eduardomgutierrez/RIAF_radproc", "max_issues_repo_head_hexsha": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lib/nrMath/random.h", "max_forks_repo_name": "eduardomgutierrez/RIAF_radproc", "max_forks_repo_head_hexsha": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0158730159, "max_line_length": 63, "alphanum_fraction": 0.6907216495, "num_tokens": 310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38861801254413975, "lm_q2_score": 0.047425873009270605, "lm_q1q2_score": 0.018430548512033504}}
{"text": "#include <bindings.cmacros.h>\n#include <gsl/gsl_multifit_nlin.h>\n\nBC_INLINE3VOID(GSL_MULTIFIT_FN_EVAL,gsl_multifit_function*,gsl_vector*,gsl_vector*)\nBC_INLINE3(GSL_MULTIFIT_FN_EVAL_F,gsl_multifit_function_fdf*,gsl_vector*,gsl_vector*,int)\nBC_INLINE3(GSL_MULTIFIT_FN_EVAL_DF,gsl_multifit_function_fdf*,gsl_vector*,gsl_matrix*,int)\nBC_INLINE4(GSL_MULTIFIT_FN_EVAL_F_DF,gsl_multifit_function_fdf*,gsl_vector*,gsl_vector*,gsl_matrix*,int)\n", "meta": {"hexsha": "0dc44adb98ec172c7b297a15b165012aed58ad3c", "size": 436, "ext": "c", "lang": "C", "max_stars_repo_path": "bindings-gsl/src/Bindings/Gsl/NonlinearLeastSquaresFitting.c", "max_stars_repo_name": "flip111/bindings-dsl", "max_stars_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2015-04-29T00:31:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T09:29:03.000Z", "max_issues_repo_path": "bindings-gsl/src/Bindings/Gsl/NonlinearLeastSquaresFitting.c", "max_issues_repo_name": "flip111/bindings-dsl", "max_issues_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2015-01-04T06:32:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-07T09:49:12.000Z", "max_forks_repo_path": "bindings-gsl/src/Bindings/Gsl/NonlinearLeastSquaresFitting.c", "max_forks_repo_name": "flip111/bindings-dsl", "max_forks_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2015-01-03T20:43:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-10T19:31:38.000Z", "avg_line_length": 54.5, "max_line_length": 104, "alphanum_fraction": 0.871559633, "num_tokens": 141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.5, "lm_q2_score": 0.036769470165750315, "lm_q1q2_score": 0.018384735082875157}}
{"text": "/* multifit_nlinear/fdf.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough\n * Copyright (C) 2015, 2016 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <stdlib.h>\n#include <string.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_multifit_nlinear.h>\n\ngsl_multifit_nlinear_workspace *\ngsl_multifit_nlinear_alloc (const gsl_multifit_nlinear_type * T, \n                            const gsl_multifit_nlinear_parameters * params,\n                            const size_t n, const size_t p)\n{\n  gsl_multifit_nlinear_workspace * w;\n\n  if (n < p)\n    {\n      GSL_ERROR_VAL (\"insufficient data points, n < p\", GSL_EINVAL, 0);\n    }\n\n  w = calloc (1, sizeof (gsl_multifit_nlinear_workspace));\n  if (w == 0)\n    {\n      GSL_ERROR_VAL (\"failed to allocate space for multifit workspace\",\n                     GSL_ENOMEM, 0);\n    }\n\n  w->x = gsl_vector_calloc (p);\n  if (w->x == 0) \n    {\n      gsl_multifit_nlinear_free (w);\n      GSL_ERROR_VAL (\"failed to allocate space for x\", GSL_ENOMEM, 0);\n    }\n\n  w->f = gsl_vector_calloc (n);\n  if (w->f == 0) \n    {\n      gsl_multifit_nlinear_free (w);\n      GSL_ERROR_VAL (\"failed to allocate space for f\", GSL_ENOMEM, 0);\n    }\n\n  w->dx = gsl_vector_calloc (p);\n  if (w->dx == 0) \n    {\n      gsl_multifit_nlinear_free (w);\n      GSL_ERROR_VAL (\"failed to allocate space for dx\", GSL_ENOMEM, 0);\n    }\n\n  w->g = gsl_vector_alloc (p);\n  if (w->g == 0) \n    {\n      gsl_multifit_nlinear_free (w);\n      GSL_ERROR_VAL (\"failed to allocate space for g\", GSL_ENOMEM, 0);\n    }\n\n  w->J = gsl_matrix_alloc(n, p);\n  if (w->J == 0) \n    {\n      gsl_multifit_nlinear_free (w);\n      GSL_ERROR_VAL (\"failed to allocate space for Jacobian\", GSL_ENOMEM, 0);\n    }\n\n  w->sqrt_wts_work = gsl_vector_calloc (n);\n  if (w->sqrt_wts_work == 0)\n    {\n      gsl_multifit_nlinear_free (w);\n      GSL_ERROR_VAL (\"failed to allocate space for weights\", GSL_ENOMEM, 0);\n    }\n\n  w->state = (T->alloc)(params, n, p);\n  if (w->state == 0)\n    {\n      gsl_multifit_nlinear_free (w);\n      GSL_ERROR_VAL (\"failed to allocate space for multifit state\", GSL_ENOMEM, 0);\n    }\n\n  w->type = T;\n  w->fdf = NULL;\n  w->niter = 0;\n  w->params = *params;\n\n  return w;\n}\n\nvoid\ngsl_multifit_nlinear_free (gsl_multifit_nlinear_workspace * w)\n{\n  RETURN_IF_NULL (w);\n\n  if (w->state)\n    (w->type->free) (w->state);\n\n  if (w->dx)\n    gsl_vector_free (w->dx);\n\n  if (w->x)\n    gsl_vector_free (w->x);\n\n  if (w->f)\n    gsl_vector_free (w->f);\n\n  if (w->sqrt_wts_work)\n    gsl_vector_free (w->sqrt_wts_work);\n\n  if (w->g)\n    gsl_vector_free (w->g);\n\n  if (w->J)\n    gsl_matrix_free (w->J);\n\n  free (w);\n}\n\ngsl_multifit_nlinear_parameters\ngsl_multifit_nlinear_default_parameters(void)\n{\n  gsl_multifit_nlinear_parameters params;\n\n  params.trs = gsl_multifit_nlinear_trs_lm;\n  params.scale = gsl_multifit_nlinear_scale_more;\n  params.solver = gsl_multifit_nlinear_solver_qr;\n  params.fdtype = GSL_MULTIFIT_NLINEAR_FWDIFF;\n  params.factor_up = 3.0;\n  params.factor_down = 2.0;\n  params.avmax = 0.75;\n  params.h_df = GSL_SQRT_DBL_EPSILON;\n  params.h_fvv = 0.02;\n\n  return params;\n}\n\nint\ngsl_multifit_nlinear_init (const gsl_vector * x,\n                           gsl_multifit_nlinear_fdf * fdf,\n                           gsl_multifit_nlinear_workspace * w)\n{\n  return gsl_multifit_nlinear_winit(x, NULL, fdf, w);\n}\n\nint\ngsl_multifit_nlinear_winit (const gsl_vector * x,\n                            const gsl_vector * wts,\n                            gsl_multifit_nlinear_fdf * fdf, \n                            gsl_multifit_nlinear_workspace * w)\n{\n  const size_t n = w->f->size;\n\n  if (n != fdf->n)\n    {\n      GSL_ERROR (\"function size does not match workspace\", GSL_EBADLEN);\n    }\n  else if (w->x->size != x->size)\n    {\n      GSL_ERROR (\"vector length does not match workspace\", GSL_EBADLEN);\n    }\n  else if (wts != NULL && n != wts->size)\n    {\n      GSL_ERROR (\"weight vector length does not match workspace\", GSL_EBADLEN);\n    }\n  else\n    {\n      size_t i;\n\n      /* initialize counters for function and Jacobian evaluations */\n      fdf->nevalf = 0;\n      fdf->nevaldf = 0;\n      fdf->nevalfvv = 0;\n\n      w->fdf = fdf;\n      gsl_vector_memcpy(w->x, x);\n      w->niter = 0;\n\n      if (wts)\n        {\n          w->sqrt_wts = w->sqrt_wts_work;\n\n          for (i = 0; i < n; ++i)\n            {\n              double wi = gsl_vector_get(wts, i);\n              gsl_vector_set(w->sqrt_wts, i, sqrt(wi));\n            }\n        }\n      else\n        {\n          w->sqrt_wts = NULL;\n        }\n  \n      return (w->type->init) (w->state, w->sqrt_wts, w->fdf,\n                              w->x, w->f, w->J, w->g);\n    }\n}\n\nint\ngsl_multifit_nlinear_iterate (gsl_multifit_nlinear_workspace * w)\n{\n  int status =\n    (w->type->iterate) (w->state, w->sqrt_wts, w->fdf,\n                        w->x, w->f, w->J, w->g, w->dx);\n\n  w->niter++;\n\n  return status;\n}\n\ndouble\ngsl_multifit_nlinear_avratio (const gsl_multifit_nlinear_workspace * w)\n{\n  return (w->type->avratio) (w->state);\n}\n\n/*\ngsl_multifit_nlinear_driver()\n  Iterate the nonlinear least squares solver until completion\n\nInputs: maxiter  - maximum iterations to allow\n        xtol     - tolerance in step x\n        gtol     - tolerance in gradient\n        ftol     - tolerance in ||f||\n        callback - callback function to call each iteration\n        callback_params - parameters to pass to callback function\n        info     - (output) info flag on why iteration terminated\n                   1 = stopped due to small step size ||dx|\n                   2 = stopped due to small gradient\n                   3 = stopped due to small change in f\n                   GSL_ETOLX = ||dx|| has converged to within machine\n                               precision (and xtol is too small)\n                   GSL_ETOLG = ||g||_inf is smaller than machine\n                               precision (gtol is too small)\n                   GSL_ETOLF = change in ||f|| is smaller than machine\n                               precision (ftol is too small)\n        w        - workspace\n\nReturn:\nGSL_SUCCESS if converged\nGSL_MAXITER if maxiter exceeded without converging\nGSL_ENOPROG if no accepted step found on first iteration\n*/\n\nint\ngsl_multifit_nlinear_driver (const size_t maxiter,\n                             const double xtol,\n                             const double gtol,\n                             const double ftol,\n                             void (*callback)(const size_t iter, void *params,\n                                              const gsl_multifit_nlinear_workspace *w),\n                             void *callback_params,\n                             int *info,\n                             gsl_multifit_nlinear_workspace * w)\n{\n  int status;\n  size_t iter = 0;\n\n  /* call user callback function prior to any iterations\n   * with initial system state */\n  if (callback)\n    callback(iter, callback_params, w);\n\n  do\n    {\n      status = gsl_multifit_nlinear_iterate (w);\n\n      /*\n       * If the solver reports no progress on the first iteration,\n       * then it didn't find a single step to reduce the\n       * cost function and more iterations won't help so return.\n       *\n       * If we get a no progress flag on subsequent iterations,\n       * it means we did find a good step in a previous iteration,\n       * so continue iterating since the solver has now reset\n       * mu to its initial value.\n       */\n      if (status == GSL_ENOPROG && iter == 0)\n        {\n          *info = status;\n          return GSL_EMAXITER;\n        }\n\n      ++iter;\n\n      if (callback)\n        callback(iter, callback_params, w);\n\n      /* test for convergence */\n      status = gsl_multifit_nlinear_test(xtol, gtol, ftol, info, w);\n    }\n  while (status == GSL_CONTINUE && iter < maxiter);\n\n  /*\n   * the following error codes mean that the solution has converged\n   * to within machine precision, so record the error code in info\n   * and return success\n   */\n  if (status == GSL_ETOLF || status == GSL_ETOLX || status == GSL_ETOLG)\n    {\n      *info = status;\n      status = GSL_SUCCESS;\n    }\n\n  /* check if max iterations reached */\n  if (iter >= maxiter && status != GSL_SUCCESS)\n    status = GSL_EMAXITER;\n\n  return status;\n} /* gsl_multifit_nlinear_driver() */\n\ngsl_matrix *\ngsl_multifit_nlinear_jac (const gsl_multifit_nlinear_workspace * w)\n{\n  return w->J;\n}\n\nconst char *\ngsl_multifit_nlinear_name (const gsl_multifit_nlinear_workspace * w)\n{\n  return w->type->name;\n}\n\ngsl_vector *\ngsl_multifit_nlinear_position (const gsl_multifit_nlinear_workspace * w)\n{\n  return w->x;\n}\n\ngsl_vector *\ngsl_multifit_nlinear_residual (const gsl_multifit_nlinear_workspace * w)\n{\n  return w->f;\n}\n\nsize_t\ngsl_multifit_nlinear_niter (const gsl_multifit_nlinear_workspace * w)\n{\n  return w->niter;\n}\n\nint\ngsl_multifit_nlinear_rcond (double *rcond, const gsl_multifit_nlinear_workspace * w)\n{\n  int status = (w->type->rcond) (rcond, w->state);\n  return status;\n}\n\nconst char *\ngsl_multifit_nlinear_trs_name (const gsl_multifit_nlinear_workspace * w)\n{\n  return w->params.trs->name;\n}\n\n/*\ngsl_multifit_nlinear_eval_f()\n  Compute residual vector y with user callback function, and apply\nweighting transform if given:\n\ny~ = sqrt(W) y\n\nInputs: fdf  - callback function\n        x    - model parameters\n        swts - weight matrix sqrt(W) = sqrt(diag(w1,w2,...,wn))\n               set to NULL for unweighted fit\n        y    - (output) (weighted) residual vector\n               y_i = sqrt(w_i) f_i where f_i is unweighted residual\n*/\n\nint\ngsl_multifit_nlinear_eval_f(gsl_multifit_nlinear_fdf *fdf,\n                            const gsl_vector *x,\n                            const gsl_vector *swts,\n                            gsl_vector *y)\n{\n  int s = ((*((fdf)->f)) (x, fdf->params, y));\n\n  ++(fdf->nevalf);\n\n  /* y <- sqrt(W) y */\n  if (swts)\n    gsl_vector_mul(y, swts);\n\n  return s;\n}\n\n/*\ngsl_multifit_nlinear_eval_df()\n  Compute Jacobian matrix J with user callback function, and apply\nweighting transform if given:\n\nJ~ = sqrt(W) J\n\nInputs: x      - model parameters\n        f      - residual vector f(x)\n        swts   - weight matrix W = diag(w1,w2,...,wn)\n                 set to NULL for unweighted fit\n        h      - finite difference step size\n        fdtype - finite difference method\n        fdf    - callback function\n        df     - (output) (weighted) Jacobian matrix\n                 df = sqrt(W) df where df is unweighted Jacobian\n        work   - workspace for finite difference, size n\n*/\n\nint\ngsl_multifit_nlinear_eval_df(const gsl_vector *x,\n                             const gsl_vector *f,\n                             const gsl_vector *swts,\n                             const double h,\n                             const gsl_multifit_nlinear_fdtype fdtype,\n                             gsl_multifit_nlinear_fdf *fdf,\n                             gsl_matrix *df,\n                             gsl_vector *work)\n{\n  int status;\n\n  if (fdf->df)\n    {\n      /* call user-supplied function */\n      status = ((*((fdf)->df)) (x, fdf->params, df));\n      ++(fdf->nevaldf);\n\n      /* J <- sqrt(W) J */\n      if (swts)\n        {\n          const size_t n = swts->size;\n          size_t i;\n\n          for (i = 0; i < n; ++i)\n            {\n              double swi = gsl_vector_get(swts, i);\n              gsl_vector_view v = gsl_matrix_row(df, i);\n\n              gsl_vector_scale(&v.vector, swi);\n            }\n        }\n    }\n  else\n    {\n      /* use finite difference Jacobian approximation */\n      status = gsl_multifit_nlinear_df(h, fdtype, x, swts, fdf, f, df, work);\n    }\n\n  return status;\n}\n\n/*\ngsl_multifit_nlinear_eval_fvv()\n  Compute second direction derivative vector yvv with user\ncallback function, and apply weighting transform if given:\n\nyvv~ = sqrt(W) yvv\n\nInputs: h    - step size for finite difference, if needed\n        x    - model parameters, size p\n        v    - unscaled geodesic velocity vector, size p\n        f    - residual vector f(x), size n\n        J    - Jacobian matrix J(x), n-by-p\n        swts - weight matrix sqrt(W) = sqrt(diag(w1,w2,...,wn))\n               set to NULL for unweighted fit\n        fdf  - callback function\n        yvv  - (output) (weighted) second directional derivative vector\n               yvv_i = sqrt(w_i) fvv_i where f_i is unweighted\n        work - workspace, size p\n*/\n\nint\ngsl_multifit_nlinear_eval_fvv(const double h,\n                              const gsl_vector *x,\n                              const gsl_vector *v,\n                              const gsl_vector *f,\n                              const gsl_matrix *J,\n                              const gsl_vector *swts,\n                              gsl_multifit_nlinear_fdf *fdf,\n                              gsl_vector *yvv, gsl_vector *work)\n{\n  int status;\n  \n  if (fdf->fvv != NULL)\n    {\n      /* call user-supplied function */\n      status = ((*((fdf)->fvv)) (x, v, fdf->params, yvv));\n      ++(fdf->nevalfvv);\n\n      /* yvv <- sqrt(W) yvv */\n      if (swts)\n        gsl_vector_mul(yvv, swts);\n    }\n  else\n    {\n      /* use finite difference approximation */\n      status = gsl_multifit_nlinear_fdfvv(h, x, v, f, J,\n                                          swts, fdf, yvv, work);\n    }\n\n  return status;\n}\n", "meta": {"hexsha": "fc0c1134b1e440e6d66d3f4711014dee62400cef", "size": 13952, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/multifit_nlinear/fdf.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit_nlinear/fdf.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit_nlinear/fdf.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 27.25, "max_line_length": 87, "alphanum_fraction": 0.5884461009, "num_tokens": 3737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473485858429, "lm_q2_score": 0.042722201050615215, "lm_q1q2_score": 0.018376841507673446}}
{"text": "//\n// Created by pedram pakseresht on 2/18/21.\n//\n\nstatic char help[] = \"settling in quiescent fluid\";\n\n#include <petsc.h>\n#include \"incompressibleFlow.h\"\n#include \"mesh.h\"\n#include \"particleInertial.h\"\n#include \"particles.h\"\n#include \"particleInitializer.h\"\n#include \"petscviewer.h\"\n\n\nstatic PetscErrorCode uniform_u(PetscInt Dim, PetscReal time, const PetscReal *X, PetscInt Nf, PetscScalar *u, void *ctx) {\n    PetscInt d;\n    for (d = 0; d < Dim; ++d)\n        u[d] = 0.0;\n    return 0;\n\n}\n\nstatic PetscErrorCode uniform_u_t(PetscInt Dim, PetscReal time, const PetscReal *X, PetscInt Nf, PetscScalar *u, void *ctx) {\n    PetscInt d;\n    for (d = 0; d < Dim; ++d)\n        u[d] = 0.0;\n    return 0;\n}\n\nstatic PetscErrorCode uniform_p(PetscInt Dim, PetscReal time, const PetscReal *X, PetscInt Nf, PetscScalar *p, void *ctx) {\n    p[0] = 0.0;\n    return 0;\n}\n\nstatic PetscErrorCode uniform_T(PetscInt Dim, PetscReal time, const PetscReal *X, PetscInt Nf, PetscScalar *T, void *ctx) {\n    T[0] = 0.0;\n    return 0;\n}\nstatic PetscErrorCode uniform_T_t(PetscInt Dim, PetscReal time, const PetscReal *X, PetscInt Nf, PetscScalar *T, void *ctx) {\n    T[0] = 0.0;\n    return 0;\n}\n\nstatic PetscErrorCode SetInitialConditions(TS ts, Vec u) {\n\n    PetscErrorCode (*initFuncs[3])(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar u[], void *ctx) = {uniform_u,uniform_p,uniform_T};\n    // u here is the solution vector including velocity, temperature and pressure fields.\n    DM dm;\n    PetscReal t;\n    PetscErrorCode ierr;\n    PetscFunctionBegin;\n\n    ierr = TSGetDM(ts, &dm);\n    CHKERRQ(ierr);\n    ierr = TSGetTime(ts, &t);\n\n    CHKERRQ(ierr);\n\n    ierr = DMProjectFunction(dm, 0.0, initFuncs, NULL, INSERT_ALL_VALUES, u);\n    CHKERRQ(ierr);\n    // get the flow to apply the completeFlowInitialization method\n    ierr = IncompressibleFlow_CompleteFlowInitialization(dm, u);\n    CHKERRQ(ierr);\n\n    PetscFunctionReturn(0);\n}\n\nstatic PetscErrorCode MonitorFlowAndParticleError(TS ts, PetscInt step, PetscReal crtime, Vec u, void *ctx) {\n    // PetscErrorCode (*exactFuncs[3])(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx);\n    // void *ctxs[3];\n    DM dm;\n    PetscDS ds;\n    Vec v;\n    PetscReal ferrors[3];\n    PetscInt f;\n    PetscErrorCode ierr;\n    PetscInt num;\n\n    PetscFunctionBeginUser;\n    ierr = TSGetDM(ts, &dm);\n    CHKERRQ(ierr);\n    ierr = DMGetDS(dm, &ds);\n    CHKERRQ(ierr);\n\n    // get the particle data from the context\n    ParticleData particlesData = (ParticleData)ctx;\n    PetscInt particleCount;\n    ierr = DMSwarmGetSize(particlesData->dm, &particleCount);\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n    // compute the average particle location\n    const PetscReal *coords;\n    PetscInt dims;\n    PetscReal avg[3] = {0.0, 0.0, 0.0};\n    ierr = DMSwarmGetField(particlesData->dm, DMSwarmPICField_coor, &dims, NULL, (void **)&coords);\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n    for (PetscInt p = 0; p < particleCount; p++) {\n        for (PetscInt n = 0; n < dims; n++) {\n            avg[n] += coords[p * dims + n] / particleCount;  // PetscReal\n        }\n    }\n    ierr = DMSwarmRestoreField(particlesData->dm, DMSwarmPICField_coor, &dims, NULL, (void **)&coords);\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n    ierr = PetscPrintf(PETSC_COMM_WORLD,\n                       \"Timestep: %04d time = %-8.4g \\t L_2 Error: [%2.3g, %2.3g, %2.3g] ParticleCount: %d\\n\",\n                       (int)step,\n                       (double)crtime,\n                       (double)ferrors[0],\n                       (double)ferrors[1],\n                       (double)ferrors[2],\n                       particleCount,\n                       (double)avg[0],\n                       (double)avg[1]);\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n    ierr = PetscPrintf(PETSC_COMM_WORLD, \"Avg Particle Location: [%2.3g, %2.3g, %2.3g]\\n\", (double)avg[0], (double)avg[1], (double)avg[2]);\n\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n    ierr = VecViewFromOptions(u, NULL, \"-vec_view\");\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n    ierr = DMSetOutputSequenceNumber(particlesData->dm, step, crtime);\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n    if (step == 0) {\n        ierr = ParticleViewFromOptions(particlesData, \"-particle_init\");\n        CHKERRABORT(PETSC_COMM_WORLD, ierr);\n    } else {\n        ierr = ParticleViewFromOptions(particlesData, \"-particle_view\");\n        CHKERRABORT(PETSC_COMM_WORLD, ierr);\n    }\n\n    PetscFunctionReturn(0);\n}\n\nstatic PetscErrorCode ParticleInertialInitialize(ParticleData particles) {\n\n    PetscFunctionBeginUser;\n    PetscErrorCode  ierr;\n    Vec vel,diam,dens;\n    DM particleDm = particles->dm;\n\n    // input parameters required for particles\n    PetscScalar partVel = 0.0;\n    PetscScalar partDiam = 0.22;\n    PetscScalar partDens = 90.0;\n    PetscScalar fluidDens = 1.0;\n    PetscScalar fluidVisc = 1.0;\n    PetscScalar gravity[3] = {0.0,1.0,0.0};\n\n    ierr = DMSwarmCreateGlobalVectorFromField(particleDm,ParticleVelocity, &vel);CHKERRQ(ierr);\n    ierr = DMSwarmCreateGlobalVectorFromField(particleDm,ParticleDiameter, &diam);CHKERRQ(ierr);\n    ierr = DMSwarmCreateGlobalVectorFromField(particleDm,ParticleDensity, &dens);CHKERRQ(ierr);\n    // set particle velocity, diameter and density\n    ierr = VecSet(vel, partVel);CHKERRQ(ierr);\n    ierr = VecSet(diam, partDiam);CHKERRQ(ierr);\n    ierr = VecSet(dens, partDens);CHKERRQ(ierr);\n    ierr = DMSwarmDestroyGlobalVectorFromField(particleDm,ParticleVelocity, &vel);CHKERRQ(ierr);\n    ierr = DMSwarmDestroyGlobalVectorFromField(particleDm,ParticleDiameter, &diam);CHKERRQ(ierr);\n    ierr = DMSwarmDestroyGlobalVectorFromField(particleDm,ParticleDensity, &dens);CHKERRQ(ierr);\n\n    InertialParticleParameters *data;\n    PetscNew(&data);\n    particles->data =data;\n\n    // set fluid parameters\n    data->fluidDensity = fluidDens;\n    data->fluidViscosity = fluidVisc;\n    data->gravityField[0] = gravity[0];\n    data->gravityField[1] = gravity[1];\n    data->gravityField[2] = gravity[2];\n    PetscFunctionReturn(0);\n\n}\n\n\nint main( int argc, char *argv[] )\n{\n\n    DM dm;     // domain definition\n    TS ts;     // time-stepper\n    PetscErrorCode ierr;\n\n    PetscBag parameterBag; // constant flow parameters\n    Vec flowField;         // flow solution vector\n    FlowData flowData;\n\n\n    PetscReal t;\n    PetscInt Dim = 2;\n    PetscReal dt = 0.05;       // dt for time stepper\n    PetscInt max_steps = 10; // maximum time steps\n\n    PetscReal Re = 0.1;       // Reynolds number\n    PetscReal St = 1.0;       // Strouhal number\n    PetscReal Pe = 1.0;       // Peclet number\n    PetscReal Mu = 1.0;      // viscosity\n    PetscReal K_input = 1.0;  // thermal conductivity\n    PetscReal Cp = 1.0;    // heat capacity\n    // PetscInt Np=10;\n\n\n    // initialize Petsc ...\n    ierr = PetscInitialize(&argc, &argv, NULL, \"\");CHKERRQ(ierr);\n    ierr = PetscPrintf(PETSC_COMM_WORLD, \"Settling particle in a quiescent fluid \\n\");CHKERRQ(ierr);\n\n    // setup the ts\n    ierr = TSCreate(PETSC_COMM_WORLD, &ts);\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n    ierr = CreateMesh(PETSC_COMM_WORLD, &dm, PETSC_TRUE, Dim);\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n    ierr = TSSetDM(ts, dm);\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n    ierr = TSSetExactFinalTime(ts, TS_EXACTFINALTIME_MATCHSTEP);\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n\n    //output the mesh\n    ierr = DMViewFromOptions(dm, NULL, \"-dm_view\");\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n    // Setup the flow data\n    ierr = FlowCreate(&flowData);\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n    // setup problem\n    ierr = IncompressibleFlow_SetupDiscretization(flowData, dm);\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n    IncompressibleFlowParameters flowParameters;\n\n    // changing non-dimensional parameters manually here ...\n    flowParameters.strouhal = St;\n    flowParameters.reynolds = Re;\n    flowParameters.peclet = Pe;\n    flowParameters.mu = Mu;\n    flowParameters.k = K_input;\n    flowParameters.cp = Cp;\n\n    // print out the parameters\n    /*\n    ierr = PetscPrintf(PETSC_COMM_WORLD, \"*** non-dimensional parameters ***\\n\");CHKERRQ(ierr);\n    ierr = PetscPrintf(PETSC_COMM_WORLD, \"St=%g\\n\", flowParameters.strouhal);CHKERRQ(ierr);\n    ierr = PetscPrintf(PETSC_COMM_WORLD, \"Re=%g\\n\", flowParameters.reynolds);CHKERRQ(ierr);\n    ierr = PetscPrintf(PETSC_COMM_WORLD, \"Pe=%g\\n\", flowParameters.peclet);CHKERRQ(ierr);\n    ierr = PetscPrintf(PETSC_COMM_WORLD, \"Mu=%g\\n\", flowParameters.mu);CHKERRQ(ierr);\n    ierr = PetscPrintf(PETSC_COMM_WORLD, \"K=%g\\n\", flowParameters.k);CHKERRQ(ierr);\n    ierr = PetscPrintf(PETSC_COMM_WORLD, \"Cp=%g\\n\", flowParameters.cp);CHKERRQ(ierr);\n    */\n\n    // Start the problem setup\n    PetscScalar constants[TOTAL_INCOMPRESSIBLE_FLOW_PARAMETERS];\n    ierr = IncompressibleFlow_PackParameters(&flowParameters, constants);\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n    ierr = IncompressibleFlow_StartProblemSetup(flowData, TOTAL_INCOMPRESSIBLE_FLOW_PARAMETERS, constants);\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n\n    // Override problem with source terms, boundary, and set the exact solution\n    PetscDS prob;\n    ierr = DMGetDS(dm, &prob);\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n    // Setup Boundary Conditions\n    // Note: DM_BC_ESSENTIAL is a Dirichlet BC.\n    PetscInt id;\n    id = 3;\n    ierr = PetscDSAddBoundary(\n        prob, DM_BC_ESSENTIAL, \"top wall velocity\", \"marker\", VEL, 0, NULL, (void (*)(void))uniform_u, (void (*)(void))uniform_u_t, 1, &id, NULL);\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n    id = 1;\n    ierr = PetscDSAddBoundary(\n        prob, DM_BC_ESSENTIAL, \"bottom wall velocity\", \"marker\", VEL, 0, NULL, (void (*)(void))uniform_u, (void (*)(void))uniform_u_t, 1, &id, NULL);\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n    id = 2;\n    ierr = PetscDSAddBoundary(\n        prob, DM_BC_ESSENTIAL, \"right wall velocity\", \"marker\", VEL, 0, NULL, (void (*)(void))uniform_u, (void (*)(void))uniform_u_t, 1, &id, NULL);\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n    id = 4;\n    ierr = PetscDSAddBoundary(\n        prob, DM_BC_ESSENTIAL, \"left wall velocity\", \"marker\", VEL, 0, NULL, (void (*)(void))uniform_u, (void (*)(void))uniform_u_t, 1, &id, NULL);\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n    id = 3;\n    ierr = PetscDSAddBoundary(\n        prob, DM_BC_ESSENTIAL, \"top wall temp\", \"marker\", TEMP, 0, NULL, (void (*)(void))uniform_T, (void (*)(void))uniform_T_t, 1, &id, NULL);\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n    id = 1;\n    ierr = PetscDSAddBoundary(\n        prob, DM_BC_ESSENTIAL, \"bottom wall temp\", \"marker\", TEMP, 0, NULL, (void (*)(void))uniform_T, (void (*)(void))uniform_T_t, 1, &id, parameterBag);\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n    id = 2;\n    ierr = PetscDSAddBoundary(\n        prob, DM_BC_ESSENTIAL, \"right wall temp\", \"marker\", TEMP, 0, NULL, (void (*)(void))uniform_T, (void (*)(void))uniform_T_t, 1, &id, parameterBag);\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n    id = 4;\n    ierr = PetscDSAddBoundary(\n        prob, DM_BC_ESSENTIAL, \"left wall temp\", \"marker\", TEMP, 0, NULL, (void (*)(void))uniform_T, (void (*)(void))uniform_T_t, 1, &id, parameterBag);\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n\n    ierr = IncompressibleFlow_CompleteProblemSetup(flowData, ts);\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n    // Name the flow field\n    ierr = PetscObjectSetName(((PetscObject)flowData->flowField), \"Numerical Solution\");\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n\n    ierr = SetInitialConditions(ts, flowData->flowField);\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n\n    ierr = TSGetTime(ts, &t);\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n    //  *** added by Pedram for dt and number of time steps ***\n    ierr = TSSetTimeStep(ts,dt);\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n    ierr = TSSetMaxSteps(ts,max_steps);\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n    // ***********************************\n\n    ierr = DMSetOutputSequenceNumber(dm, 0, t);\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n    // checks for convergence ...\n    ierr = DMTSCheckFromOptions(ts, flowData->flowField);\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n\n    ParticleData particles;\n\n    // Setup the particle domain\n    ierr = ParticleInertialCreate(&particles, Dim);\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n    // link the flow to the particles\n    ierr = ParticleInitializeFlow(particles, flowData);\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n    // name the particle domain\n    ierr = PetscObjectSetOptionsPrefix((PetscObject)(particles->dm), \"particles_\");\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n    ierr = PetscObjectSetName((PetscObject)particles->dm, \"Particles\");\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n    // initialize the particles position\n    ierr = ParticleInitialize(dm, particles->dm);CHKERRABORT(PETSC_COMM_WORLD, ierr);\n    // initialize inertial particles velocity, diameter and density\n    ierr = ParticleInertialInitialize(particles);CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n    //ierr = ParticleInertialInitialize(particles->dm);CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n    // setup the flow monitor to also check particles\n    ierr = TSMonitorSet(ts, MonitorFlowAndParticleError, particles, NULL);\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n    ierr = TSSetFromOptions(ts);\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n\n    // Setup particle position integrator\n    TS particleTs;\n    ierr = TSCreate(PETSC_COMM_WORLD, &particleTs);\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n    ierr = PetscObjectSetOptionsPrefix((PetscObject)particleTs, \"particle_\");\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n    ierr = ParticleInertialSetupIntegrator(particles, particleTs, flowData);\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n    // ierr = VecView(particleVelocity,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr);\n\n\n    // Solve the one way coupled system\n    ierr = TSSolve(ts, flowData->flowField);\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n\n    // Cleanup\n    ierr = DMDestroy(&dm);\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n    ierr = TSDestroy(&ts);\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n    ierr = TSDestroy(&particleTs);\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n    ierr = FlowDestroy(&flowData);\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n    ierr = ParticleInertialDestroy(&particles);\n    CHKERRABORT(PETSC_COMM_WORLD, ierr);\n    ierr = PetscFinalize();\n    exit(ierr);\n\n}", "meta": {"hexsha": "c347bce39f98b175a932f3fcc78c144db2ad0083", "size": 14347, "ext": "c", "lang": "C", "max_stars_repo_path": "quiescentFluid.c", "max_stars_repo_name": "pakserep/ablateClient", "max_stars_repo_head_hexsha": "c7bb7cf4a4ec706170efd7c06bf8589e30ece47b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "quiescentFluid.c", "max_issues_repo_name": "pakserep/ablateClient", "max_issues_repo_head_hexsha": "c7bb7cf4a4ec706170efd7c06bf8589e30ece47b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "quiescentFluid.c", "max_forks_repo_name": "pakserep/ablateClient", "max_forks_repo_head_hexsha": "c7bb7cf4a4ec706170efd7c06bf8589e30ece47b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2297979798, "max_line_length": 161, "alphanum_fraction": 0.6783996654, "num_tokens": 4116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.03732689028911683, "lm_q1q2_score": 0.01837185254365508}}
{"text": "/* multiset/multiset.c\n * based on combination/combination.c by Szymon Jaroszewicz\n * based on permutation/permutation.c by Brian Gough\n *\n * Copyright (C) 2001 Szymon Jaroszewicz\n * Copyright (C) 2009 Rhys Ulerich\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_multiset.h>\n\nsize_t\ngsl_multiset_n (const gsl_multiset * c)\n{\n  return c->n ;\n}\n\nsize_t\ngsl_multiset_k (const gsl_multiset * c)\n{\n  return c->k ;\n}\n\nsize_t *\ngsl_multiset_data (const gsl_multiset * c)\n{\n  return c->data ;\n}\n\nint\ngsl_multiset_valid (gsl_multiset * c)\n{\n  const size_t n = c->n ;\n  const size_t k = c->k ;\n\n  size_t i, j ;\n\n  for (i = 0; i < k; i++)\n    {\n      const size_t ci = c->data[i];\n\n      if (ci >= n)\n        {\n          GSL_ERROR(\"multiset index outside range\", GSL_FAILURE) ;\n        }\n\n      for (j = 0; j < i; j++)\n        {\n          if (c->data[j] > ci)\n            {\n              GSL_ERROR(\"multiset indices not in increasing order\",\n                        GSL_FAILURE) ;\n            }\n        }\n    }\n\n  return GSL_SUCCESS;\n}\n\n\nint\ngsl_multiset_next (gsl_multiset * c)\n{\n  /* Replaces c with the next multiset (in the standard lexicographical\n   * ordering).  Returns GSL_FAILURE if there is no next multiset.\n   */\n  const size_t n = c->n;\n  const size_t k = c->k;\n  size_t *data = c->data;\n  size_t i;\n\n  if(k == 0)\n    {\n      return GSL_FAILURE;\n    }\n  i = k - 1;\n\n  while(i > 0 && data[i] == n-1)\n    {\n      --i;\n    }\n\n  if (i == 0 && data[0] == n-1)\n    {\n      return GSL_FAILURE;\n    }\n\n  ++data[i];\n\n  while(i < k-1)\n    {\n      data[i+1] = data[i];\n      ++i;\n    }\n\n  return GSL_SUCCESS;\n}\n\nint\ngsl_multiset_prev (gsl_multiset * c)\n{\n  /* Replaces c with the previous multiset (in the standard\n   * lexicographical ordering).  Returns GSL_FAILURE if there is no\n   * previous multiset.\n   */\n  const size_t n = c->n;\n  const size_t k = c->k;\n  size_t *data = c->data;\n  size_t i;\n\n  if(k == 0)\n    {\n      return GSL_FAILURE;\n    }\n  i = k - 1;\n\n  while(i > 0 && data[i-1] == data[i])\n    {\n      --i;\n    }\n\n  if(i == 0 && data[i] == 0)\n    {\n      return GSL_FAILURE;\n    }\n\n  data[i]--;\n\n  if (data[i] < n-1)\n    {\n      while (i < k-1) {\n        data[++i] = n - 1;\n      }\n    }\n\n  return GSL_SUCCESS;\n}\n\nint\ngsl_multiset_memcpy (gsl_multiset * dest, const gsl_multiset * src)\n{\n   const size_t src_n = src->n;\n   const size_t src_k = src->k;\n   const size_t dest_n = dest->n;\n   const size_t dest_k = dest->k;\n\n   if (src_n != dest_n || src_k != dest_k)\n     {\n       GSL_ERROR (\"multiset lengths are not equal\", GSL_EBADLEN);\n     }\n\n   {\n     size_t j;\n\n     for (j = 0; j < src_k; j++)\n       {\n         dest->data[j] = src->data[j];\n       }\n   }\n\n   return GSL_SUCCESS;\n}\n", "meta": {"hexsha": "c1a0f80b4cb0e20bfa2b787fc0ded3d4444269a2", "size": 3438, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/multiset/multiset.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multiset/multiset.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multiset/multiset.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 19.3146067416, "max_line_length": 81, "alphanum_fraction": 0.5872600349, "num_tokens": 1035, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4035668537353746, "lm_q2_score": 0.04535258555427004, "lm_q1q2_score": 0.01830280026090116}}
{"text": "/* ieee-utils/test.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#include <config.h>\n#include <stdlib.h>\n#include <math.h>\n#include <float.h>\n#include <string.h>\n#include <gsl/gsl_ieee_utils.h>\n#include <gsl/gsl_test.h>\n\n#if defined(HAVE_IRIX_IEEE_INTERFACE)\n/* don't test denormals on IRIX */\n#else\n#define TEST_DENORMAL 1\n#endif\n\nint\nmain (void)\n{\n  float zerof = 0.0f, minus_onef = -1.0f ;\n  double zero = 0.0, minus_one = -1.0 ;\n\n  /* Check for +ZERO (float) */\n\n  {\n    float f = 0.0f;\n    const char mantissa[] = \"00000000000000000000000\";\n    gsl_ieee_float_rep r;\n    gsl_ieee_float_to_rep (&f, &r);\n\n    gsl_test_int (r.sign, 0, \"float x = 0, sign is +\");\n    gsl_test_int (r.exponent, -127, \"float x = 0, exponent is -127\");\n    gsl_test_str (r.mantissa, mantissa, \"float x = 0, mantissa\");\n    gsl_test_int (r.type, GSL_IEEE_TYPE_ZERO, \"float x = 0, type is ZERO\");\n  }\n\n  /* Check for -ZERO (float) */\n\n  {\n    float f = minus_onef;\n    const char mantissa[] = \"00000000000000000000000\";\n    gsl_ieee_float_rep r;\n    \n    while (f < 0) {\n      f *= 0.1f;\n    }\n\n    gsl_ieee_float_to_rep (&f, &r);\n\n    gsl_test_int (r.sign, 1, \"float x = -1*0, sign is -\");\n    gsl_test_int (r.exponent, -127, \"float x = -1*0, exponent is -127\");\n    gsl_test_str (r.mantissa, mantissa, \"float x = -1*0, mantissa\");\n    gsl_test_int (r.type, GSL_IEEE_TYPE_ZERO, \"float x = -1*0, type is ZERO\");\n  }\n\n  /* Check for a positive NORMAL number (e.g. 2.1) (float) */\n\n  {\n    float f = 2.1f;\n    const char mantissa[] = \"00001100110011001100110\";\n\n    gsl_ieee_float_rep r;\n    gsl_ieee_float_to_rep (&f, &r);\n\n    gsl_test_int (r.sign, 0, \"float x = 2.1, sign is +\");\n    gsl_test_int (r.exponent, 1, \"float x = 2.1, exponent is 1\");\n    gsl_test_str (r.mantissa, mantissa, \"float x = 2.1, mantissa\");\n    gsl_test_int (r.type, GSL_IEEE_TYPE_NORMAL, \"float x = 2.1, type is NORMAL\");\n  }\n\n\n  /* Check for a negative NORMAL number (e.g. -1.3304...) (float) */\n\n  {\n    float f = -1.3303577090924210f ;\n    const char mantissa[] = \"01010100100100100101001\";\n\n    gsl_ieee_float_rep r;\n    gsl_ieee_float_to_rep (&f, &r);\n\n    gsl_test_int (r.sign, 1, \"float x = -1.3304..., sign is -\");\n    gsl_test_int (r.exponent, 0, \"float x = -1.3304..., exponent is 0\");\n    gsl_test_str (r.mantissa, mantissa, \"float x = -1.3304..., mantissa\");\n    gsl_test_int (r.type, GSL_IEEE_TYPE_NORMAL,\n\t\t  \"float x = -1.3304..., type is NORMAL\");\n  }\n\n  /* Check for a large positive NORMAL number (e.g. 3.37e31) (float) */\n\n  {\n    float f = 3.37e31f;\n    const char mantissa[] = \"10101001010110101001001\";\n    gsl_ieee_float_rep r;\n    gsl_ieee_float_to_rep (&f, &r);\n\n    gsl_test_int (r.sign, 0, \"float x = 3.37e31, sign is +\");\n    gsl_test_int (r.exponent, 104, \"float x = 3.37e31, exponent is 104\");\n    gsl_test_str (r.mantissa, mantissa, \"float x = 3.37e31, mantissa\");\n    gsl_test_int (r.type, GSL_IEEE_TYPE_NORMAL, \"float x = 3.37e31, type is NORMAL\");\n  }\n\n  /* Check for a small positive NORMAL number (e.g. 3.37e-31) (float) */\n\n  {\n    float f = 3.37e-31f;\n    const char mantissa[] = \"10110101011100110111011\";\n\n    gsl_ieee_float_rep r;\n    gsl_ieee_float_to_rep (&f, &r);\n\n    gsl_test_int (r.sign, 0, \"float x = 3.37e-31, sign is +\");\n    gsl_test_int (r.exponent, -102, \"float x = 3.37e-31, exponent is -102\");\n    gsl_test_str (r.mantissa, mantissa, \"float x = 3.37e-31, mantissa\");\n    gsl_test_int (r.type, GSL_IEEE_TYPE_NORMAL,\n\t\t  \"float x = 3.37e-31, type is NORMAL\");\n  }\n\n  /* Check for FLT_MIN (smallest possible number that is not denormal) */\n\n  {\n    float f = 1.17549435e-38f;\t/* FLT_MIN (float) */\n    const char mantissa[] = \"00000000000000000000000\";\n    gsl_ieee_float_rep r;\n    gsl_ieee_float_to_rep (&f, &r);\n\n    gsl_test_int (r.sign, 0, \"float x = FLT_MIN, sign is +\");\n    gsl_test_int (r.exponent, -126, \"float x = FLT_MIN, exponent is -126\");\n    gsl_test_str (r.mantissa, mantissa, \"float x = FLT_MIN, mantissa\");\n    gsl_test_int (r.type, GSL_IEEE_TYPE_NORMAL, \"float x = FLT_MIN, type is NORMAL\");\n  }\n\n  /* Check for FLT_MAX (largest possible number that is not Inf) */\n\n  {\n    float f = 3.40282347e+38f;\t/* FLT_MAX */\n    const char mantissa[] = \"11111111111111111111111\";\n\n    gsl_ieee_float_rep r;\n    gsl_ieee_float_to_rep (&f, &r);\n\n    gsl_test_int (r.sign, 0, \"float x = FLT_MAX, sign is +\");\n    gsl_test_int (r.exponent, 127, \"float x = FLT_MAX, exponent is 127\");\n    gsl_test_str (r.mantissa, mantissa, \"float x = FLT_MAX, mantissa\");\n    gsl_test_int (r.type, GSL_IEEE_TYPE_NORMAL, \"float x = FLT_MAX, type is NORMAL\");\n  }\n\n\n  /* Check for DENORMAL numbers (e.g. FLT_MIN/2^n) */\n\n#ifdef TEST_DENORMAL\n  {\n    float f = 1.17549435e-38f;\t/* FLT_MIN */\n    char mantissa[] = \"10000000000000000000000\";\n\n    int i;\n    gsl_ieee_float_rep r;\n\n    for (i = 0; i < 23; i++)\n      {\n\tfloat x = f / (float)pow (2.0, 1 + (float) i);\n\tmantissa[i] = '1';\n\tgsl_ieee_float_to_rep (&x, &r);\n\n\tgsl_test_int (r.sign, 0, \"float x = FLT_MIN/2^%d, sign is +\", i + 1);\n\tgsl_test_int (r.exponent, -127,\n\t\t      \"float x = FLT_MIN/2^%d, exponent is -127\", i + 1);\n\tgsl_test_str (r.mantissa, mantissa,\n\t\t      \"float x = FLT_MIN/2^%d, mantissa\", i + 1);\n\tgsl_test_int (r.type, GSL_IEEE_TYPE_DENORMAL,\n\t\t      \"float x = FLT_MIN/2^%d, type is DENORMAL\", i + 1);\n\tmantissa[i] = '0';\n      }\n  }\n#endif\n\n  /* Check for positive INFINITY (e.g. 2*FLT_MAX) */\n\n  {\n    float f = 3.40282347e+38f;\t/* FLT_MAX */\n    const char mantissa[] = \"00000000000000000000000\";\n\n    gsl_ieee_float_rep r;\n\n    float x;\n    x = 2 * f;\n    gsl_ieee_float_to_rep (&x, &r);\n\n    gsl_test_int (r.sign, 0, \"float x = 2*FLT_MAX, sign is +\");\n    gsl_test_int (r.exponent, 128, \"float x = 2*FLT_MAX, exponent is 128\");\n    gsl_test_str (r.mantissa, mantissa, \"float x = 2*FLT_MAX, mantissa\");\n    gsl_test_int (r.type, GSL_IEEE_TYPE_INF, \"float x = -2*FLT_MAX, type is INF\");\n  }\n\n  /* Check for negative INFINITY (e.g. -2*FLT_MAX) */\n\n  {\n    float f = 3.40282347e+38f;\t/* FLT_MAX */\n    const char mantissa[] = \"00000000000000000000000\";\n\n    gsl_ieee_float_rep r;\n\n    float x;\n    x = -2 * f;\n    gsl_ieee_float_to_rep (&x, &r);\n\n    gsl_test_int (r.sign, 1, \"float x = -2*FLT_MAX, sign is -\");\n    gsl_test_int (r.exponent, 128, \"float x = -2*FLT_MAX, exponent is 128\");\n    gsl_test_str (r.mantissa, mantissa, \"float x = -2*FLT_MAX, mantissa\");\n    gsl_test_int (r.type, GSL_IEEE_TYPE_INF, \"float x = -2*FLT_MAX, type is INF\");\n  }\n\n  /* Check for NAN (e.g. Inf - Inf) (float) */\n\n  {\n    gsl_ieee_float_rep r;\n    float x = 1.0f, y = 2.0f, z = zerof;\n\n    x = x / z;\n    y = y / z;\n    z = y - x;\n\n    gsl_ieee_float_to_rep (&z, &r);\n\n    /* We don't check the sign and we don't check the mantissa because\n       they could be anything for a NaN */\n\n    gsl_test_int (r.exponent, 128, \"float x = NaN, exponent is 128\");\n    gsl_test_int (r.type, GSL_IEEE_TYPE_NAN, \"float x = NaN, type is NAN\");\n  }\n\n\n  /* Check for +ZERO */\n\n  {\n    double d = 0.0;\n    const char mantissa[]\n      = \"0000000000000000000000000000000000000000000000000000\";\n    gsl_ieee_double_rep r;\n    gsl_ieee_double_to_rep (&d, &r);\n\n    gsl_test_int (r.sign, 0, \"double x = 0, sign is +\");\n    gsl_test_int (r.exponent, -1023, \"double x = 0, exponent is -1023\");\n    gsl_test_str (r.mantissa, mantissa, \"double x = 0, mantissa\");\n    gsl_test_int (r.type, GSL_IEEE_TYPE_ZERO, \"double x = 0, type is ZERO\");\n  }\n\n  /* Check for -ZERO */\n\n  {\n    double d =  minus_one;\n    const char mantissa[]\n      = \"0000000000000000000000000000000000000000000000000000\";\n    gsl_ieee_double_rep r;\n\n    while (d < 0) {\n      d *= 0.1;\n    }\n\n    gsl_ieee_double_to_rep (&d, &r);\n\n    gsl_test_int (r.sign, 1, \"double x = -1*0, sign is -\");\n    gsl_test_int (r.exponent, -1023, \"double x = -1*0, exponent is -1023\");\n    gsl_test_str (r.mantissa, mantissa, \"double x = -1*0, mantissa\");\n    gsl_test_int (r.type, GSL_IEEE_TYPE_ZERO, \"double x = -1*0, type is ZERO\");\n  }\n\n  /* Check for a positive NORMAL number (e.g. 2.1) */\n\n  {\n    double d = 2.1;\n    const char mantissa[]\n      = \"0000110011001100110011001100110011001100110011001101\";\n    gsl_ieee_double_rep r;\n    gsl_ieee_double_to_rep (&d, &r);\n\n    gsl_test_int (r.sign, 0, \"double x = 2.1, sign is +\");\n    gsl_test_int (r.exponent, 1, \"double x = 2.1, exponent is 1\");\n    gsl_test_str (r.mantissa, mantissa, \"double x = 2.1, mantissa\");\n    gsl_test_int (r.type, GSL_IEEE_TYPE_NORMAL, \"double x = 2.1, type is NORMAL\");\n  }\n\n\n  /* Check for a negative NORMAL number (e.g. -1.3304...) */\n\n  {\n    double d = -1.3303577090924210146738460025517269968986511230468750;\n    const char mantissa[]\n      = \"0101010010010010010100101010010010001000100011101110\";\n    gsl_ieee_double_rep r;\n    gsl_ieee_double_to_rep (&d, &r);\n\n    gsl_test_int (r.sign, 1, \"double x = -1.3304..., sign is -\");\n    gsl_test_int (r.exponent, 0, \"double x = -1.3304..., exponent is 0\");\n    gsl_test_str (r.mantissa, mantissa, \"double x = -1.3304..., mantissa\");\n    gsl_test_int (r.type, GSL_IEEE_TYPE_NORMAL,\n\t\t  \"double x = -1.3304..., type is NORMAL\");\n  }\n\n  /* Check for a large positive NORMAL number (e.g. 3.37e297) */\n\n  {\n    double d = 3.37e297;\n    const char mantissa[]\n      = \"0100100111001001100101111001100000100110011101000100\";\n    gsl_ieee_double_rep r;\n    gsl_ieee_double_to_rep (&d, &r);\n\n    gsl_test_int (r.sign, 0, \"double x = 3.37e297, sign is +\");\n    gsl_test_int (r.exponent, 988, \"double x = 3.37e297, exponent is 998\");\n    gsl_test_str (r.mantissa, mantissa, \"double x = 3.37e297, mantissa\");\n    gsl_test_int (r.type, GSL_IEEE_TYPE_NORMAL,\n\t\t  \"double x = 3.37e297, type is NORMAL\");\n  }\n\n  /* Check for a small positive NORMAL number (e.g. 3.37e-297) */\n\n  {\n    double d = 3.37e-297;\n    const char mantissa[]\n    = \"0001101000011011101011100001110010100001001100110111\";\n    gsl_ieee_double_rep r;\n    gsl_ieee_double_to_rep (&d, &r);\n\n    gsl_test_int (r.sign, 0, \"double x = 3.37e-297, sign is +\");\n    gsl_test_int (r.exponent, -985, \"double x = 3.37e-297, exponent is -985\");\n    gsl_test_str (r.mantissa, mantissa, \"double x = 3.37e-297, mantissa\");\n    gsl_test_int (r.type, GSL_IEEE_TYPE_NORMAL,\n\t\t  \"double x = 3.37e-297, type is NORMAL\");\n  }\n\n  /* Check for DBL_MIN (smallest possible number that is not denormal) */\n\n  {\n    double d = 2.2250738585072014e-308;\t\t/* DBL_MIN */\n    const char mantissa[]\n      = \"0000000000000000000000000000000000000000000000000000\";\n    gsl_ieee_double_rep r;\n    gsl_ieee_double_to_rep (&d, &r);\n\n    gsl_test_int (r.sign, 0, \"double x = DBL_MIN, sign is +\");\n    gsl_test_int (r.exponent, -1022, \"double x = DBL_MIN, exponent is -1022\");\n    gsl_test_str (r.mantissa, mantissa, \"double x = DBL_MIN, mantissa\");\n    gsl_test_int (r.type, GSL_IEEE_TYPE_NORMAL,\n\t\t  \"double x = DBL_MIN, type is NORMAL\");\n  }\n\n  /* Check for DBL_MAX (largest possible number that is not Inf) */\n\n  {\n    double d = 1.7976931348623157e+308;\t\t/* DBL_MAX */\n    const char mantissa[]\n    = \"1111111111111111111111111111111111111111111111111111\";\n    gsl_ieee_double_rep r;\n    gsl_ieee_double_to_rep (&d, &r);\n\n    gsl_test_int (r.sign, 0, \"double x = DBL_MAX, sign is +\");\n    gsl_test_int (r.exponent, 1023, \"double x = DBL_MAX, exponent is 1023\");\n    gsl_test_str (r.mantissa, mantissa, \"double x = DBL_MAX, mantissa\");\n    gsl_test_int (r.type, GSL_IEEE_TYPE_NORMAL,\n\t\t  \"double x = DBL_MAX, type is NORMAL\");\n  }\n\n  /* Check for DENORMAL numbers (e.g. DBL_MIN/2^n) */\n\n#ifdef TEST_DENORMAL\n  {\n    double d = 2.2250738585072014e-308;\t\t/* DBL_MIN */\n    char mantissa[]\n      = \"1000000000000000000000000000000000000000000000000000\";\n    int i;\n    gsl_ieee_double_rep r;\n\n    for (i = 0; i < 52; i++)\n      {\n\tdouble x = d / pow (2.0, 1 + (double) i);\n\tmantissa[i] = '1';\n\tgsl_ieee_double_to_rep (&x, &r);\n\n\tgsl_test_int (r.sign, 0, \"double x = DBL_MIN/2^%d, sign is +\", i + 1);\n\tgsl_test_int (r.exponent, -1023,\n\t\t      \"double x = DBL_MIN/2^%d, exponent\", i + 1);\n\tgsl_test_str (r.mantissa, mantissa,\n\t\t      \"double x = DBL_MIN/2^%d, mantissa\", i + 1);\n\tgsl_test_int (r.type, GSL_IEEE_TYPE_DENORMAL,\n\t\t      \"double x = DBL_MIN/2^%d, type is DENORMAL\", i + 1);\n\tmantissa[i] = '0';\n      }\n  }\n#endif\n\n  /* Check for positive INFINITY (e.g. 2*DBL_MAX) */\n\n  {\n    double d = 1.7976931348623157e+308;\t\t/* DBL_MAX */\n    const char mantissa[]\n      = \"0000000000000000000000000000000000000000000000000000\";\n    gsl_ieee_double_rep r;\n\n    double x;\n    x = 2.0 * d;\n    gsl_ieee_double_to_rep (&x, &r);\n\n    gsl_test_int (r.sign, 0, \"double x = 2*DBL_MAX, sign is +\");\n    gsl_test_int (r.exponent, 1024, \"double x = 2*DBL_MAX, exponent is 1024\");\n    gsl_test_str (r.mantissa, mantissa, \"double x = 2*DBL_MAX, mantissa\");\n    gsl_test_int (r.type, GSL_IEEE_TYPE_INF, \"double x = 2*DBL_MAX, type is INF\");\n  }\n\n  /* Check for negative INFINITY (e.g. -2*DBL_MAX) */\n\n  {\n    double d = 1.7976931348623157e+308;\t\t/* DBL_MAX */\n    const char mantissa[]\n      = \"0000000000000000000000000000000000000000000000000000\";\n    gsl_ieee_double_rep r;\n\n    double x;\n    x = -2.0 * d;\n    gsl_ieee_double_to_rep (&x, &r);\n\n    gsl_test_int (r.sign, 1, \"double x = -2*DBL_MAX, sign is -\");\n    gsl_test_int (r.exponent, 1024, \"double x = -2*DBL_MAX, exponent is 1024\");\n    gsl_test_str (r.mantissa, mantissa, \"double x = -2*DBL_MAX, mantissa\");\n    gsl_test_int (r.type, GSL_IEEE_TYPE_INF,\"double x = -2*DBL_MAX, type is INF\");\n  }\n\n  /* Check for NAN (e.g. Inf - Inf) */\n\n  {\n    gsl_ieee_double_rep r;\n    double x = 1.0, y = 2.0, z = zero;\n\n    x = x / z;\n    y = y / z;\n    z = y - x;\n\n    gsl_ieee_double_to_rep (&z, &r);\n\n    /* We don't check the sign and we don't check the mantissa because\n       they could be anything for a NaN */\n\n    gsl_test_int (r.exponent, 1024, \"double x = NaN, exponent is 1024\");\n    gsl_test_int (r.type, GSL_IEEE_TYPE_NAN, \"double x = NaN, type is NAN\");\n  }\n\n  exit (gsl_test_summary ());\n}\n", "meta": {"hexsha": "30136128adeaf18ec3c04d2d7bdbb1174151532f", "size": 14599, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/ieee-utils/test.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/ieee-utils/test.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/ieee-utils/test.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 31.3956989247, "max_line_length": 85, "alphanum_fraction": 0.6392218645, "num_tokens": 5043, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814648038986, "lm_q2_score": 0.04208773031866069, "lm_q1q2_score": 0.01826529485396382}}
{"text": "/* rng/benchmark.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#include <config.h>\n#include <time.h>\n#include <stdio.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_errno.h>\n\nvoid benchmark (const gsl_rng_type * T);\n\n#define N  1000000\nint isum;\ndouble dsum;\n\nint\nmain (void)\n{\n  benchmark(gsl_rng_ranlux);\n  benchmark(gsl_rng_ranlux389);\n  benchmark(gsl_rng_ranlxs0);\n  benchmark(gsl_rng_ranlxs1);\n  benchmark(gsl_rng_ranlxs2);\n  benchmark(gsl_rng_ranlxd1);\n  benchmark(gsl_rng_ranlxd2);\n\n  benchmark(gsl_rng_slatec);\n  benchmark(gsl_rng_gfsr4);\n  benchmark(gsl_rng_cmrg);\n  benchmark(gsl_rng_minstd);\n  benchmark(gsl_rng_mrg);\n  benchmark(gsl_rng_mt19937);\n  benchmark(gsl_rng_r250);\n  benchmark(gsl_rng_ran0);\n  benchmark(gsl_rng_ran1);\n  benchmark(gsl_rng_ran2);\n  benchmark(gsl_rng_ran3);\n  benchmark(gsl_rng_rand48);\n  benchmark(gsl_rng_rand);\n  benchmark(gsl_rng_random8_bsd);\n  benchmark(gsl_rng_random8_glibc2);\n  benchmark(gsl_rng_random8_libc5);\n  benchmark(gsl_rng_random128_bsd);\n  benchmark(gsl_rng_random128_glibc2);\n  benchmark(gsl_rng_random128_libc5);\n  benchmark(gsl_rng_random256_bsd);\n  benchmark(gsl_rng_random256_glibc2);\n  benchmark(gsl_rng_random256_libc5);\n  benchmark(gsl_rng_random32_bsd);\n  benchmark(gsl_rng_random32_glibc2);\n  benchmark(gsl_rng_random32_libc5);\n  benchmark(gsl_rng_random64_bsd);\n  benchmark(gsl_rng_random64_glibc2);\n  benchmark(gsl_rng_random64_libc5);\n  benchmark(gsl_rng_random_bsd);\n  benchmark(gsl_rng_random_glibc2);\n  benchmark(gsl_rng_random_libc5);\n  benchmark(gsl_rng_randu);\n  benchmark(gsl_rng_ranf);\n\n  benchmark(gsl_rng_ranmar);\n  benchmark(gsl_rng_taus);\n  benchmark(gsl_rng_transputer);\n  benchmark(gsl_rng_tt800);\n  benchmark(gsl_rng_uni32);\n  benchmark(gsl_rng_uni);\n  benchmark(gsl_rng_vax);\n  benchmark(gsl_rng_zuf);\n  return 0;\n}\n\nvoid\nbenchmark (const gsl_rng_type * T)\n{\n  int start, end;\n  int i = 0, d = 0 ;\n  double t1, t2;\n\n  gsl_rng *r = gsl_rng_alloc (T);\n\n  start = clock ();\n  do\n    {\n      int j;\n      for (j = 0; j < N; j++)\n\tisum += gsl_rng_get (r);\n\n      i += N;\n      end = clock ();\n    }\n  while (end < start + CLOCKS_PER_SEC/10);\n\n  t1 = (end - start) / (double) CLOCKS_PER_SEC;\n\n  start = clock ();\n  do\n    {\n      int j;\n      for (j = 0; j < N; j++)\n\tdsum += gsl_rng_uniform (r);\n\n      d += N;\n      end = clock ();\n    }\n  while (end < start + CLOCKS_PER_SEC/10);\n\n  t2 = (end - start) / (double) CLOCKS_PER_SEC;\n\n\n  printf (\"%6.0f k ints/sec, %6.0f k doubles/sec, %s\\n\",\n\t  i / t1 / 1000.0, d / t2 / 1000.0, gsl_rng_name (r));\n\n  gsl_rng_free (r);\n}\n", "meta": {"hexsha": "1b81ca4005d8cad7b24d3653aaae311ec296a32a", "size": 3287, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/rng/benchmark.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/rng/benchmark.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/rng/benchmark.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 25.0916030534, "max_line_length": 72, "alphanum_fraction": 0.7131122604, "num_tokens": 1002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814794452761, "lm_q2_score": 0.04208772806580895, "lm_q1q2_score": 0.018265294492490237}}
{"text": "#ifndef Photometry_h\n#define Photometry_h\n/**\n * @file\n * $Revision: 1.5 $\n * $Date: 2008/07/09 19:40:52 $\n *\n *   Unless noted otherwise, the portions of Isis written by the USGS are\n *   public domain. See individual third-party library and package descriptions\n *   for intellectual property information, user agreements, and related\n *   information.\n *\n *   Although Isis has been used by the USGS, no warranty, expressed or\n *   implied, is made by the USGS as to the accuracy and functioning of such\n *   software and related material nor shall the fact of distribution\n *   constitute any such warranty, and no responsibility is assumed by the\n *   USGS in connection therewith.\n *\n *   For additional information, launch\n *   $ISISROOT/doc//documents/Disclaimers/Disclaimers.html\n *   in a browser or see the Privacy &amp; Disclaimers page on the Isis website,\n *   http://isis.astrogeology.usgs.gov, and the USGS privacy and disclaimers on\n *   http://www.usgs.gov/privacy.html.\n */\n\n#include <string>\n#include <vector>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_min.h>\n#include <gsl/gsl_roots.h>\n\nnamespace Isis {\n  class Pvl;\n  class PhotoModel;\n  class AtmosModel;\n  class NormModel;\n  /**\n   * @author ????-??-?? Unknown\n   *\n   * @internal\n   *  @history 2007-08-02 Steven Lambright - Fixed memory leak\n   *  @history 2008-03-07 Janet Barrett - Added SetPhotomWl method to allow\n   *                      the application to set the p_normWavelength variable for\n   *                      use by MoonAlbedo normalization.\n   *  @history 2008-06-18 Steven Koechle - Fixed Documentation Errors\n   *  @history 2008-07-09 Steven Lambright - Fixed unit test\n   *  @history 2011-08-19 Sharmila Prasad - Implemented brentminimizer using GSL\n   *  @history 2011-09-15 Sharmila Prasad - Implemented brent's root solver using GSL\n   */\n  class Photometry {\n    public:\n      Photometry(Pvl &pvl);\n      Photometry() {};\n      virtual ~Photometry();\n\n      //! Calculate the surface brightness\n      void Compute(double pha, double inc, double ema, double dn,\n                   double &albedo, double &mult, double &base);\n      void Compute(double pha, double inc, double ema, double deminc,\n                   double demema, double dn, double &albedo,\n                   double &mult, double &base);\n\n      //! Set the wavelength\n      virtual void SetPhotomWl(double wl);\n\n      //! Double precision version of bracketing algorithm ported from Python.\n      //! Solution bracketing for 1-D minimization routine.\n      static void minbracket(double &xa, double &xb, double &xc, double &fa,\n          double &fb, double &fc, double Func(double par, void *params),\n          void *params);\n\n      //! Brent's method 1-D minimization routine using GSL's r8Brent minimization Algorithm\n      static int brentminimizer(double x_lower, double x_upper, gsl_function *Func, \n          double & x_minimum, double tolerance);\n      \n      //! GSL's the Brent-Dekker method (Brent's method) combines an interpolation strategy \n      //! with the bisection algorithm to estimate the root of the quadratic function.\n      static int brentsolver(double x_lo, double x_hi, gsl_function *Func, double tolerance, double &root);\n\n      PhotoModel *GetPhotoModel() const {\n        return p_phtPmodel;\n      }\n\n      AtmosModel *GetAtmosModel() const {\n        return p_phtAmodel;\n      }\n\n      NormModel *GetNormModel() const {\n        return p_phtNmodel;\n      }\n\n    protected:      \n      AtmosModel *p_phtAmodel;\n      PhotoModel *p_phtPmodel;\n      NormModel *p_phtNmodel;\n  };\n};\n\n#endif\n", "meta": {"hexsha": "2f781d0b521b4bc39c25d207a95bc232c6fd28f2", "size": 3610, "ext": "h", "lang": "C", "max_stars_repo_path": "isis/src/base/objs/Photometry/Photometry.h", "max_stars_repo_name": "ihumphrey-usgs/ISIS3_old", "max_stars_repo_head_hexsha": "284cc442b773f8369d44379ee29a9b46961d8108", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-13T15:31:33.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-13T15:31:33.000Z", "max_issues_repo_path": "isis/src/base/objs/Photometry/Photometry.h", "max_issues_repo_name": "ihumphrey-usgs/ISIS3_old", "max_issues_repo_head_hexsha": "284cc442b773f8369d44379ee29a9b46961d8108", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "isis/src/base/objs/Photometry/Photometry.h", "max_forks_repo_name": "ihumphrey-usgs/ISIS3_old", "max_forks_repo_head_hexsha": "284cc442b773f8369d44379ee29a9b46961d8108", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-12T06:05:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-12T06:05:03.000Z", "avg_line_length": 35.7425742574, "max_line_length": 107, "alphanum_fraction": 0.6720221607, "num_tokens": 919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091957, "lm_q2_score": 0.03676946924216766, "lm_q1q2_score": 0.018241106803960145}}
{"text": "/* ******************************************************************************\n *\n *\n * This program and the accompanying materials are made available under the\n * terms of the Apache License, Version 2.0 which is available at\n * https://www.apache.org/licenses/LICENSE-2.0.\n *\n *  See the NOTICE file distributed with this work for additional\n *  information regarding copyright ownership.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations\n * under the License.\n *\n * SPDX-License-Identifier: Apache-2.0\n ******************************************************************************/\n\n//\n// @author raver119@gmail.com\n//\n\n#ifndef LIBND4J_GEMM_H\n#define LIBND4J_GEMM_H\n\n#include <cblas.h>\n#include <math/templatemath.h>\n#include <system/op_boilerplate.h>\n\n\nnamespace sd {\n     namespace blas {\n         template <typename T>\n         static void * transpose(int orderSource, int orderTarget, int rows, int cols, void *source);\n\n         static inline int linearIndexC(int rows, int cols, int r, int c);\n         static inline int linearIndexF(int rows, int cols, int r, int c);\n\n         template <typename X, typename Y, typename Z>\n         class GEMM {\n         protected:\n         public:\n             static void op(int Order, int TransA, int TransB, int M, int N, int K, double alpha, void *A, int lda, void *B, int ldb, double beta, void *C, int ldc);\n         };\n\n         template <typename X, typename Y, typename Z>\n         class GEMV : public sd::blas::GEMM<X, Y, Z>{\n         public:\n             static void op(int TRANS, int M, int N, double alpha, void* vA, int lda, void* vX, int incx, double beta, void* vY, int incy );\n         };\n\n\n         int FORCEINLINE linearIndexC(int rows, int cols, int r, int c) {\n             return (r * cols + c);\n         }\n\n         int FORCEINLINE linearIndexF(int rows, int cols, int r, int c) {\n             return (c * rows + r);\n         }\n\n    }\n}\n\n#endif //LIBND4J_GEMM_H\n", "meta": {"hexsha": "8026fa21e68363921f55c30f651e420e8f445b74", "size": 2183, "ext": "h", "lang": "C", "max_stars_repo_path": "libnd4j/include/ops/gemm.h", "max_stars_repo_name": "Celebrate-future/deeplearning4j", "max_stars_repo_head_hexsha": "d93976922a9af838457a15e69ef1218c3d9adc45", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libnd4j/include/ops/gemm.h", "max_issues_repo_name": "Celebrate-future/deeplearning4j", "max_issues_repo_head_hexsha": "d93976922a9af838457a15e69ef1218c3d9adc45", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libnd4j/include/ops/gemm.h", "max_forks_repo_name": "Celebrate-future/deeplearning4j", "max_forks_repo_head_hexsha": "d93976922a9af838457a15e69ef1218c3d9adc45", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5846153846, "max_line_length": 165, "alphanum_fraction": 0.6010077874, "num_tokens": 507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.03676946594365837, "lm_q1q2_score": 0.018241105167590036}}
{"text": "/* -----------------------------------------------------------------------------\n * Copyright 2021 Jonathan Haigh\n * SPDX-License-Identifier: MIT\n * ---------------------------------------------------------------------------*/\n\n#ifndef SQ_INCLUDE_GUARD_core_narrow_inl_h_\n#define SQ_INCLUDE_GUARD_core_narrow_inl_h_\n\n#include \"core/errors.h\"\n\n#include <fmt/format.h>\n#include <fmt/ostream.h>\n#include <gsl/gsl>\n\nnamespace sq {\n\ntemplate <typename T, typename U, typename... FormatArgs>\nconstexpr T narrow(U value, FormatArgs &&...format_args) {\n  try {\n    return gsl::narrow<T>(value);\n  } catch (gsl::narrowing_error &e) {\n    throw NarrowingError{T{}, value, SQ_FWD(format_args)...};\n  }\n}\n\nconstexpr gsl::index to_index(auto value, auto &&...format_args) {\n  return narrow<gsl::index>(SQ_FWD(value), SQ_FWD(format_args)...);\n}\n\nconstexpr std::size_t to_size(auto value, auto &&...format_args) {\n  return narrow<std::size_t>(SQ_FWD(value), SQ_FWD(format_args)...);\n}\n\n} // namespace sq\n\n#endif // SQ_INCLUDE_GUARD_core_narrow_inl_h_\n", "meta": {"hexsha": "78ef23acfcca8cbbedfd91b776b617b3ed89efcd", "size": 1036, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/include/core/narrow.inl.h", "max_stars_repo_name": "jonathanhaigh/sq", "max_stars_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-12T16:21:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-12T16:21:41.000Z", "max_issues_repo_path": "src/core/include/core/narrow.inl.h", "max_issues_repo_name": "jonathanhaigh/sq", "max_issues_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 44.0, "max_issues_repo_issues_event_min_datetime": "2021-02-08T19:17:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-05T18:51:38.000Z", "max_forks_repo_path": "src/core/include/core/narrow.inl.h", "max_forks_repo_name": "jonathanhaigh/sq", "max_forks_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0, "max_line_length": 80, "alphanum_fraction": 0.61003861, "num_tokens": 237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3311197264277872, "lm_q2_score": 0.05500528713161718, "lm_q1q2_score": 0.018213335627102964}}
{"text": "#ifndef GBNET_GRAPHBASE\n#define GBNET_GRAPHBASE\n\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <utility>\n#include <map>\n#include <set>\n#include <stdio.h>\n\n\n#include <gsl/gsl_rng.h>\n\n\n#include \"RVNode.h\"\n#include \"XNode.h\"\n#include \"HNodeORNOR.h\"\n#include \"YDataNode.h\"\n#include \"SNode.h\"\n#include \"NodeDictionary.h\"\n\n\nnamespace gbn\n{\n    // used accross module. might want to find a better place for these typedefs\n    typedef std::vector<RVNode *> node_vector_t;\n    typedef std::pair<std::string, int> trg_de_pair_t;\n    typedef std::map<std::string, int> evidence_dict_t;\n\n    typedef std::set<std::string> prior_active_tf_set_t;\n\n    typedef std::pair<std::string, std::string> src_trg_pair_t;\n    typedef std::pair<src_trg_pair_t, int> network_edge_t;\n    typedef std::vector<network_edge_t> network_t;\n    \n    class GraphBase\n    {\n        private:\n        protected:\n            gsl_rng * rng;\n\n        public:\n            node_vector_t random_nodes;\n            node_vector_t norand_nodes; /* Used to keep track of node pointers for later destruction */\n\n            GraphBase (unsigned int);\n            virtual ~GraphBase ();\n\n            void sample (unsigned int);\n            void burn_stats();\n            void print_stats();\n    };\n}\n\n#endif", "meta": {"hexsha": "cdbb41a1f49d3a4b9ecb5ee8a41c6d3d4da63545", "size": 1277, "ext": "h", "lang": "C", "max_stars_repo_path": "libgbnet/include/GraphBase.h", "max_stars_repo_name": "umbibio/gbnet", "max_stars_repo_head_hexsha": "0e478d764cfa02eaed3e32d11d03c240c78e2ff6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libgbnet/include/GraphBase.h", "max_issues_repo_name": "umbibio/gbnet", "max_issues_repo_head_hexsha": "0e478d764cfa02eaed3e32d11d03c240c78e2ff6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libgbnet/include/GraphBase.h", "max_forks_repo_name": "umbibio/gbnet", "max_forks_repo_head_hexsha": "0e478d764cfa02eaed3e32d11d03c240c78e2ff6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-06-10T16:19:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-10T16:19:58.000Z", "avg_line_length": 22.4035087719, "max_line_length": 103, "alphanum_fraction": 0.6570086139, "num_tokens": 305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40733338565660004, "lm_q2_score": 0.044680874247953285, "lm_q1q2_score": 0.018200011781515604}}
{"text": "/**\n * author: Jochen K\"upper\n * created: Jan 2002\n * file: pygsl/src/statisticsmodule.c\n * $Id: floatmodule.c,v 1.8 2004/03/24 08:40:45 schnizer Exp $\n *\n * \"\n */\n\n\n#include <Python.h>\n#include <gsl/gsl_statistics.h>\n#include <pygsl/error_helpers.h>\n#include <pygsl/block_helpers.h>\n\n\n/* include real functions for default data-types (double in C) */\n\n#define STATMOD_WEIGHTED\n#define STATMOD_APPEND_PY_TYPE(X) X ## Float32\n#define STATMOD_APPEND_PYC_TYPE(X) X ## FLOAT\n#define STATMOD_FUNC_EXT(X, Y) X ## _float ## Y\n#define STATMOD_PY_AS_C PyFloat_AsDouble\n#define STATMOD_C_TYPE float\n#include \"functions.c\"\n\n\n\n/* initialization */\n\nPyGSL_STATISTICS_INIT(float, \"float\")\n\n\n/*\n * Local Variables:\n * mode: c\n * c-file-style: \"Stroustrup\"\n * End:\n */\n\n\n", "meta": {"hexsha": "3866d0671ed4692897ae5064981bf6222d6a115e", "size": 755, "ext": "c", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/src/statistics/floatmodule.c", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/src/statistics/floatmodule.c", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/src/statistics/floatmodule.c", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 17.9761904762, "max_line_length": 65, "alphanum_fraction": 0.7086092715, "num_tokens": 218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.039048297199379224, "lm_q1q2_score": 0.018153614727446483}}
{"text": "#pragma once\n\n#include <chrono>\n#include <fmt/printf.h>\n#include <gsl/gsl-lite.hpp>\n\nnamespace angonoka::cli {\n/**\n    Pretty-print values with as much info as possible.\n\n    @var value Value to be pretty-printed\n*/\ntemplate <typename T> struct verbose {\n    T value;\n};\ntemplate <typename T> verbose(T) -> verbose<T>;\n\nnamespace detail {\n    /**\n        Helper function to print verbose durations.\n\n        @param name Duration (s, m, d, etc)\n\n        @return Formatter function\n    */\n    template <typename T>\n    constexpr auto verbose_duration(gsl::czstring name)\n    {\n        return [=](auto& total, auto& ctx, bool& needs_space) {\n            const auto dur = std::chrono::floor<T>(total);\n            if (dur == dur.zero()) return;\n            total -= dur;\n            if (needs_space) fmt::format_to(ctx.out(), \" \");\n            needs_space = true;\n            const auto ticks = dur.count();\n            fmt::format_to(ctx.out(), \"{}{}\", ticks, name);\n        };\n    }\n} // namespace detail\n} // namespace angonoka::cli\n\nnamespace fmt {\nusing angonoka::cli::verbose;\n\n/**\n    User-defined formatter for std::chrono durations.\n*/\ntemplate <typename... Ts>\nstruct fmt::formatter<verbose<std::chrono::duration<Ts...>>> {\n    using value_type = verbose<std::chrono::duration<Ts...>>;\n    static constexpr auto parse(format_parse_context& ctx)\n    {\n        return ctx.end();\n    }\n\n    template <typename FormatContext>\n    constexpr auto format(const value_type& obj, FormatContext& ctx)\n    {\n        using angonoka::cli::detail::verbose_duration;\n        using namespace std::chrono;\n        if (obj.value == obj.value.zero())\n            return format_to(ctx.out(), \"0s\");\n        bool needs_space = false;\n        auto total = duration_cast<seconds>(obj.value);\n        [&](auto&&... fns) {\n            (fns(total, ctx, needs_space), ...);\n        }(verbose_duration<months>(\"mo\"),\n          verbose_duration<days>(\"d\"),\n          verbose_duration<hours>(\"h\"),\n          verbose_duration<minutes>(\"m\"),\n          verbose_duration<seconds>(\"s\"));\n        return ctx.out();\n    }\n};\n} // namespace fmt\n", "meta": {"hexsha": "6520e7a892d8c4d64d1a0186ab88c70c0b9893eb", "size": 2113, "ext": "h", "lang": "C", "max_stars_repo_path": "src/cli/verbose.h", "max_stars_repo_name": "coffee-lord/angonoka", "max_stars_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-10-23T18:05:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T21:53:24.000Z", "max_issues_repo_path": "src/cli/verbose.h", "max_issues_repo_name": "coffee-lord/angonoka", "max_issues_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2022-02-12T19:52:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-12T19:55:52.000Z", "max_forks_repo_path": "src/cli/verbose.h", "max_forks_repo_name": "coffee-lord/angonoka", "max_forks_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8026315789, "max_line_length": 68, "alphanum_fraction": 0.5939422622, "num_tokens": 483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234844434674, "lm_q2_score": 0.04146227256335484, "lm_q1q2_score": 0.018153156646632796}}
{"text": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//------------------------------------------------------------------------------\n// KeypointSpatialIndex.h\n//\n// Allows to construction, query, and removal of Keypoint entries based on pixel position.\n//------------------------------------------------------------------------------\n\n#pragma once\n\n#include \"Utils\\thread_memory.h\"\n\n#include <memory>\n#include <vector>\n#include <functional>\n#include <opencv2\\features2d\\features2d.hpp>\n\n#include <gsl/span>\n\nnamespace mage\n{\n    class KeypointSpatialIndex\n    {\n        struct Impl;\n\n    public:\n        KeypointSpatialIndex(gsl::span<const cv::KeyPoint> keypoints);\n\n        void Query(const cv::Point2f& center, int octave, float radius, temp::vector<size_t>& results) const;\n        void Remove(const cv::KeyPoint& keypoint, size_t value);\n\n        ~KeypointSpatialIndex();\n\n    private:\n        static constexpr float octaveSpacing = 100;\n        static constexpr float octaveQueryRange = 1;\n\n        std::unique_ptr<Impl> m_impl;\n    };\n}", "meta": {"hexsha": "5fb2dede7cf71e201f4ec63c60cb01954058623e", "size": 1067, "ext": "h", "lang": "C", "max_stars_repo_path": "Core/MAGESLAM/Source/Image/KeypointSpatialIndex.h", "max_stars_repo_name": "syntheticmagus/mageslam", "max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z", "max_issues_repo_path": "Core/MAGESLAM/Source/Image/KeypointSpatialIndex.h", "max_issues_repo_name": "syntheticmagus/mageslam", "max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z", "max_forks_repo_path": "Core/MAGESLAM/Source/Image/KeypointSpatialIndex.h", "max_forks_repo_name": "syntheticmagus/mageslam", "max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z", "avg_line_length": 26.0243902439, "max_line_length": 109, "alphanum_fraction": 0.5885660731, "num_tokens": 217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.036220058075706524, "lm_q1q2_score": 0.018110029037853262}}
{"text": "/**\n * \\file Utilities.h\n */\n\n#ifndef ATK_CORE_UTILITIES_H\n#define ATK_CORE_UTILITIES_H\n\n#include <ATK/Core/config.h>\n\n#include <gsl/gsl>\n\n#include <cstddef>\n\nnamespace ATK\n{\n  /// Class to convert arrays from different type to another type\n  template<typename DataType1, typename DataType2>\n  class ATK_CORE_EXPORT ConversionUtilities\n  {\n  public:\n    /*!\n     * @brief Method to convert an array to another, using double as the intermediate type\n     * @param input_array\n     * @param output_array\n     * @param size\n     * @param offset\n     * @param ports\n     */\n    static void convert_array(const DataType1* input_array, DataType2* output_array, gsl::index size, gsl::index offset = 0, gsl::index ports = 1);\n  };\n  \n  class ATK_CORE_EXPORT RuntimeError: public std::runtime_error\n  {\n  public:\n    explicit RuntimeError(const std::string& what_arg);\n    explicit RuntimeError(const char* what_arg);\n  };\n}\n\n#endif\n", "meta": {"hexsha": "4b2ae7d67052cf59a59f84ecbb25b76cc778a29a", "size": 924, "ext": "h", "lang": "C", "max_stars_repo_path": "ATK/Core/Utilities.h", "max_stars_repo_name": "AudioTK/AudioTK", "max_stars_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2021-02-04T10:47:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T03:45:00.000Z", "max_issues_repo_path": "ATK/Core/Utilities.h", "max_issues_repo_name": "AudioTK/AudioTK", "max_issues_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-02-01T15:45:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-13T19:39:05.000Z", "max_forks_repo_path": "ATK/Core/Utilities.h", "max_forks_repo_name": "AudioTK/AudioTK", "max_forks_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-04-12T03:28:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-17T00:47:11.000Z", "avg_line_length": 22.5365853659, "max_line_length": 147, "alphanum_fraction": 0.7012987013, "num_tokens": 222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32423539898095244, "lm_q2_score": 0.05582313642224892, "lm_q1q2_score": 0.018099836910236016}}
{"text": "/* siman/gsl_siman.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Mark Galassi\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_SIMAN_H__\n#define __GSL_SIMAN_H__\n#include <stdlib.h>\n#include <gsl/gsl_rng.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\n/* types for the function pointers passed to gsl_siman_solve */\n\ntypedef double (*gsl_siman_Efunc_t) (void *xp);\ntypedef void (*gsl_siman_step_t) (const gsl_rng *r, void *xp, double step_size);\ntypedef double (*gsl_siman_metric_t) (void *xp, void *yp);\ntypedef void (*gsl_siman_print_t) (void *xp);\ntypedef void (*gsl_siman_copy_t) (void *source, void *dest);\ntypedef void * (*gsl_siman_copy_construct_t) (void *xp);\ntypedef void (*gsl_siman_destroy_t) (void *xp);\n\n/* this structure contains all the information needed to structure the\n   search, beyond the energy function, the step function and the\n   initial guess. */\n\ntypedef struct {\n  int n_tries;          /* how many points to try for each step */\n  int iters_fixed_T;    /* how many iterations at each temperature? */\n  double step_size;     /* max step size in the random walk */\n  /* the following parameters are for the Boltzmann distribution */\n  double k, t_initial, mu_t, t_min;\n} gsl_siman_params_t;\n\n/* prototype for the workhorse function */\n\nvoid gsl_siman_solve(const gsl_rng * r, \n                     void *x0_p, gsl_siman_Efunc_t Ef,\n                     gsl_siman_step_t take_step,\n                     gsl_siman_metric_t distance,\n                     gsl_siman_print_t print_position,\n                     gsl_siman_copy_t copyfunc,\n                     gsl_siman_copy_construct_t copy_constructor,\n                     gsl_siman_destroy_t destructor,\n                     size_t element_size,\n                     gsl_siman_params_t params);\n\nvoid \ngsl_siman_solve_many (const gsl_rng * r, void *x0_p, gsl_siman_Efunc_t Ef,\n                      gsl_siman_step_t take_step,\n                      gsl_siman_metric_t distance,\n                      gsl_siman_print_t print_position,\n                      size_t element_size,\n                      gsl_siman_params_t params);\n\n__END_DECLS\n\n#endif /* __GSL_SIMAN_H__ */\n", "meta": {"hexsha": "d04333a690b71ec80bd8e56e9d508f56b34b65e6", "size": 3018, "ext": "h", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/siman/gsl_siman.h", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/siman/gsl_siman.h", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/siman/gsl_siman.h", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 36.3614457831, "max_line_length": 81, "alphanum_fraction": 0.6855533466, "num_tokens": 730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41111086923216805, "lm_q2_score": 0.04401864641413912, "lm_q1q2_score": 0.018096543989740192}}
{"text": "/*\n * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The OpenAirInterface Software Alliance licenses this file to You under\n * the OAI Public License, Version 1.1  (the \"License\"); you may not use this file\n * except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.openairinterface.org/?page_id=698\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *-------------------------------------------------------------------------------\n * For more information about the OpenAirInterface (OAI) Software Alliance:\n *      contact@openairinterface.org\n */\n\n#include <string.h>\n#include <math.h>\n#include <unistd.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include <cblas.h>\n#include <execinfo.h>\n\n//<<PAD>>//\n//#include <mpi.h>\n//#include \"UTIL/FIFO/pad_list.h\"\n#include \"discrete_event_generator.h\"\n#include \"threadpool.h\"\n#include <pthread.h>\n#include \"oaisim_functions.h\"\n//<<PAD>>//\n\n#include \"SIMULATION/RF/defs.h\"\n#include \"PHY/types.h\"\n#include \"PHY/defs.h\"\n#include \"PHY/vars.h\"\n#include \"MAC_INTERFACE/vars.h\"\n\n//#ifdef OPENAIR2\n#include \"LAYER2/MAC/defs.h\"\n#include \"LAYER2/MAC/vars.h\"\n#include \"RRC/LITE/vars.h\"\n#include \"PHY_INTERFACE/vars.h\"\n//#endif\n\n#include \"ARCH/CBMIMO1/DEVICE_DRIVER/vars.h\"\n\n#ifdef IFFT_FPGA\n//#include \"PHY/LTE_REFSIG/mod_table.h\"\n#endif //IFFT_FPGA\n\n#include \"SCHED/defs.h\"\n#include \"SCHED/vars.h\"\n\n#include \"oaisim.h\"\n#include \"oaisim_config.h\"\n#include \"UTIL/OCG/OCG_extern.h\"\n#include \"cor_SF_sim.h\"\n#include \"UTIL/OMG/omg_constants.h\"\n\n\n\n//#include \"UTIL/LOG/vcd_signal_dumper.h\"\n\n#define RF\n\n//#define DEBUG_SIM\n\n#define MCS_COUNT 24//added for PHY abstraction\n#define N_TRIALS 1\n\n\n/*\n  DCI0_5MHz_TDD0_t          UL_alloc_pdu;\n  DCI1A_5MHz_TDD_1_6_t      CCCH_alloc_pdu;\n  DCI2_5MHz_2A_L10PRB_TDD_t DLSCH_alloc_pdu1;\n  DCI2_5MHz_2A_M10PRB_TDD_t DLSCH_alloc_pdu2;\n */\n\n#define UL_RB_ALLOC computeRIV(lte_frame_parms->N_RB_UL,0,24)\n#define CCCH_RB_ALLOC computeRIV(lte_frame_parms->N_RB_UL,0,3)\n#define RA_RB_ALLOC computeRIV(lte_frame_parms->N_RB_UL,0,3)\n#define DLSCH_RB_ALLOC 0x1fff\n\n#define DECOR_DIST 100\n#define SF_VAR 10\n\n//constant for OAISIM soft realtime calibration\n#define SF_DEVIATION_OFFSET_NS 100000 //= 0.1ms : should be as a number of UE\n#define SLEEP_STEP_US       100 //  = 0.01ms could be adaptive, should be as a number of UE\n#define K 2                  // averaging coefficient\n#define TARGET_SF_TIME_NS 1000000       // 1ms = 1000000 ns\n\n//#ifdef OPENAIR2\n//uint16_t NODE_ID[1];\n//uint8_t NB_INST = 2;\n//#endif //OPENAIR2\nextern int otg_times;\nextern int for_times;\nextern int if_times;\nint for_main_times = 0;\n\nframe_t frame=0;\nchar stats_buffer[16384];\nchannel_desc_t *eNB2UE[NUMBER_OF_eNB_MAX][NUMBER_OF_UE_MAX];\nchannel_desc_t *UE2eNB[NUMBER_OF_UE_MAX][NUMBER_OF_eNB_MAX];\nSignal_buffers *signal_buffers_g;\n//Added for PHY abstraction\nnode_desc_t *enb_data[NUMBER_OF_eNB_MAX];\nnode_desc_t *ue_data[NUMBER_OF_UE_MAX];\n//double sinr_bler_map[MCS_COUNT][2][16];\n//double sinr_bler_map_up[MCS_COUNT][2][16];\n//extern double SINRpost_eff[301];\nextern int mcsPost;\nextern int  nrbPost;\nextern int frbPost;\nextern void kpi_gen();\n\nextern uint16_t Nid_cell;\nextern uint8_t target_dl_mcs;\nextern uint8_t rate_adaptation_flag;\nextern double snr_dB, sinr_dB;\nextern uint8_t set_seed;\nextern uint8_t cooperation_flag;          // for cooperative communication\nextern uint8_t abstraction_flag, ethernet_flag;\nextern uint8_t ue_connection_test;\nextern int map1,map2;\nextern double **ShaF;\n// pointers signal buffers (s = transmit, r,r0 = receive)\nextern double **s_re, **s_im, **r_re, **r_im, **r_re0, **r_im0;\nextern Node_list ue_node_list;\nextern Node_list enb_node_list;\nextern int pdcp_period, omg_period;\nextern LTE_DL_FRAME_PARMS *frame_parms;\n// time calibration for soft realtime mode\nextern struct timespec time_spec;\nextern unsigned long time_last, time_now;\nextern int td, td_avg, sleep_time_us;\n\nint eMBMS_active = 0;\n\nthreadpool_t * pool;\n\n#ifdef OPENAIR2\nextern int pfd[2];\n#endif\n\n// this should reflect the channel models in openair1/SIMULATION/TOOLS/defs.h\nmapping small_scale_names[] = {\n  {\"custom\", custom},\n  {\"SCM_A\", SCM_A},\n  {\"SCM_B\", SCM_B},\n  {\"SCM_C\", SCM_C},\n  {\"SCM_D\", SCM_D},\n  {\"EPA\", EPA},\n  {\"EVA\", EVA},\n  {\"ETU\", ETU},\n  {\"Rayleigh8\", Rayleigh8},\n  {\"Rayleigh1\", Rayleigh1},\n  {\"Rayleigh1_800\", Rayleigh1_800},\n  {\"Rayleigh1_corr\", Rayleigh1_corr},\n  {\"Rayleigh1_anticorr\", Rayleigh1_anticorr},\n  {\"Rice8\", Rice8},\n  {\"Rice1\", Rice1},\n  {\"Rice1_corr\", Rice1_corr},\n  {\"Rice1_anticorr\", Rice1_anticorr},\n  {\"AWGN\", AWGN},\n  {NULL, -1}\n};\n\n//static void *sigh(void *arg);\nvoid terminate(void);\n\nvoid\nhelp (void)\n{\n  printf\n  (\"Usage: oaisim -h -a -F -C tdd_config -V -R N_RB_DL -e -x transmission_mode -m target_dl_mcs -r(ate_adaptation) -n n_frames -s snr_dB -k ricean_factor -t max_delay -f forgetting factor -A channel_model -z cooperation_flag -u nb_local_ue -U UE mobility -b nb_local_enb -B eNB_mobility -M ethernet_flag -p nb_master -g multicast_group -l log_level -c ocg_enable -T traffic model -D multicast network device\\n\");\n\n  printf (\"-h provides this help message!\\n\");\n  printf (\"-a Activates PHY abstraction mode\\n\");\n  printf (\"-F Activates FDD transmission (TDD is default)\\n\");\n  printf (\"-C [0-6] Sets TDD configuration\\n\");\n  printf (\"-R [6,15,25,50,75,100] Sets N_RB_DL\\n\");\n  printf (\"-e Activates extended prefix mode\\n\");\n  printf (\"-m Gives a fixed DL mcs\\n\");\n  printf (\"-r Activates rate adaptation (DL for now)\\n\");\n  printf (\"-n Set the number of frames for the simulation\\n\");\n  printf (\"-s snr_dB set a fixed (average) SNR, this deactivates the openair channel model generator (OCM)\\n\");\n  printf (\"-S snir_dB set a fixed (average) SNIR, this deactivates the openair channel model generator (OCM)\\n\");\n  printf (\"-k Set the Ricean factor (linear)\\n\");\n  printf (\"-t Set the delay spread (microseconds)\\n\");\n  printf (\"-f Set the forgetting factor for time-variation\\n\");\n  printf (\"-A set the multipath channel simulation,  options are: SCM_A, SCM_B, SCM_C, SCM_D, EPA, EVA, ETU, Rayleigh8, Rayleigh1, Rayleigh1_corr,Rayleigh1_anticorr, Rice8,, Rice1, AWGN \\n\");\n  printf (\"-b Set the number of local eNB\\n\");\n  printf (\"-u Set the number of local UE\\n\");\n  printf (\"-M Set the machine ID for Ethernet-based emulation\\n\");\n  printf (\"-p Set the total number of machine in emulation - valid if M is set\\n\");\n  printf (\"-g Set multicast group ID (0,1,2,3) - valid if M is set\\n\");\n  printf (\"-l Set the global log level (8:trace, 7:debug, 6:info, 4:warn, 3:error) \\n\");\n  printf\n  (\"-c [1,2,3,4] Activate the config generator (OCG) to process the scenario descriptor, or give the scenario manually: -c template_1.xml \\n\");\n  printf (\"-x Set the transmission mode (1,2,5,6 supported for now)\\n\");\n  printf (\"-z Set the cooperation flag (0 for no cooperation, 1 for delay diversity and 2 for distributed alamouti\\n\");\n  printf (\"-T activate the traffic generator: 0 for NONE, 1 for CBR, 2 for M2M, 3 for FPS Gaming, 4 for mix\\n\");\n  printf (\"-B Set the mobility model for eNB, options are: STATIC, RWP, RWALK, \\n\");\n  printf (\"-U Set the mobility model for UE, options are: STATIC, RWP, RWALK \\n\");\n  printf (\"-E Random number generator seed\\n\");\n  printf (\"-P enable protocol analyzer : 0 for wireshark interface, 1: for pcap , 2 : for tshark \\n\");\n  printf (\"-I Enable CLI interface (to connect use telnet localhost 1352)\\n\");\n  printf (\"-V Enable VCD dump, file = openair_vcd_dump.vcd\\n\");\n  printf (\"-G Enable background traffic \\n\");\n  printf (\"-O [mme ipv4 address] Enable MME mode\\n\");\n  printf (\"-Z Reserved\\n\");\n}\n\n\n#ifdef OPENAIR2\nvoid omv_end (int pfd, Data_Flow_Unit omv_data);\nint omv_write (int pfd,  Node_list enb_node_list, Node_list ue_node_list, Data_Flow_Unit omv_data);\n#endif\n\n//<<<< PAD >>>>//\n#define PAD 1\n//#define PAD_FINE 1\n//#define PAD_SYNC 1\n#define JOB_REQUEST_TAG 246\n#define JOB_REPLY_TAG 369\n#define FRAME_END 888\n#define NO_JOBS_TAG 404\n#define JOB_DIST_DEBUG 33\n\n//Global Variables\nint worker_number;\nint frame_number = 1;\n//<<<< PAD >>>>//\n\n//<<<< DEG >>>>//\nextern End_Of_Sim_Event end_event; //Could later be a list of condition_events\nextern Event_List event_list;\n//<<<< DEG >>>>//\n\nextern Packet_OTG_List *otg_pdcp_buffer;\n\nvoid run(int argc, char *argv[]);\n\n#ifdef PAD\nvoid pad_init()\n{\n\n  int UE_id, i;\n\n  pool = threadpool_create(PAD);\n\n  if (pool == NULL) {\n    printf(\"ERROR threadpool allocation\\n\");\n    return;\n  }\n\n  signal_buffers_g = malloc(NB_UE_INST * sizeof(Signal_buffers));\n\n  if (abstraction_flag == 0) {\n    for (UE_id = 0; UE_id < NB_UE_INST; UE_id++) {\n      signal_buffers_g[UE_id].s_re = malloc(2*sizeof(double*));\n      signal_buffers_g[UE_id].s_im = malloc(2*sizeof(double*));\n      signal_buffers_g[UE_id].r_re = malloc(2*sizeof(double*));\n      signal_buffers_g[UE_id].r_im = malloc(2*sizeof(double*));\n      signal_buffers_g[UE_id].r_re0 = malloc(2*sizeof(double*));\n      signal_buffers_g[UE_id].r_im0 = malloc(2*sizeof(double*));\n\n\n      for (i=0; i<2; i++) {\n\n        signal_buffers_g[UE_id].s_re[i] = malloc(FRAME_LENGTH_COMPLEX_SAMPLES*sizeof(double));\n        bzero(signal_buffers_g[UE_id].s_re[i],FRAME_LENGTH_COMPLEX_SAMPLES*sizeof(double));\n        signal_buffers_g[UE_id].s_im[i] = malloc(FRAME_LENGTH_COMPLEX_SAMPLES*sizeof(double));\n        bzero(signal_buffers_g[UE_id].s_im[i],FRAME_LENGTH_COMPLEX_SAMPLES*sizeof(double));\n        signal_buffers_g[UE_id].r_re[i] = malloc(FRAME_LENGTH_COMPLEX_SAMPLES*sizeof(double));\n        bzero(signal_buffers_g[UE_id].r_re[i],FRAME_LENGTH_COMPLEX_SAMPLES*sizeof(double));\n        signal_buffers_g[UE_id].r_im[i] = malloc(FRAME_LENGTH_COMPLEX_SAMPLES*sizeof(double));\n        bzero(signal_buffers_g[UE_id].r_im[i],FRAME_LENGTH_COMPLEX_SAMPLES*sizeof(double));\n        signal_buffers_g[UE_id].r_re0[i] = malloc(FRAME_LENGTH_COMPLEX_SAMPLES*sizeof(double));\n        bzero(signal_buffers_g[UE_id].r_re0[i],FRAME_LENGTH_COMPLEX_SAMPLES*sizeof(double));\n        signal_buffers_g[UE_id].r_im0[i] = malloc(FRAME_LENGTH_COMPLEX_SAMPLES*sizeof(double));\n        bzero(signal_buffers_g[UE_id].r_im0[i],FRAME_LENGTH_COMPLEX_SAMPLES*sizeof(double));\n      }\n    }\n  }\n}\n\nvoid pad_finalize()\n{\n\n  int ret, i;\n  module_id_t UE_id;\n\n  ret = threadpool_destroy(pool);\n\n  if (ret)\n    printf(\"ERROR threadpool destroy = %d\\n\", ret);\n\n  if (abstraction_flag == 0) {\n\n    for (UE_id = 0; UE_id < NB_UE_INST; UE_id++) {\n      for (i = 0; i < 2; i++) {\n        free(signal_buffers_g[UE_id].s_re[i]);\n        free(signal_buffers_g[UE_id].s_im[i]);\n        free(signal_buffers_g[UE_id].r_re[i]);\n        free(signal_buffers_g[UE_id].r_im[i]);\n      }\n\n      free(signal_buffers_g[UE_id].s_re);\n      free(signal_buffers_g[UE_id].s_im);\n      free(signal_buffers_g[UE_id].r_re);\n      free(signal_buffers_g[UE_id].r_im);\n    }\n\n    //free node by node here same pattern as below\n  }\n\n  free(signal_buffers_g);\n}\n\nvoid pad_inject_job(int eNB_flag, int nid, int frame, int next_slot, int last_slot, enum Job_type type, int ctime)\n{\n\n  int ret;\n  Job_elt *job_elt;\n\n  job_elt = malloc(sizeof(Job_elt));\n  job_elt->next = NULL;\n  (job_elt->job).eNB_flag = eNB_flag;\n  (job_elt->job).nid = nid;\n  (job_elt->job).frame = frame;\n  (job_elt->job).next_slot = next_slot;\n  (job_elt->job).last_slot = last_slot;\n  (job_elt->job).type = type;\n  (job_elt->job).ctime = ctime;\n\n  ret = threadpool_add(pool, job_elt);\n\n  if (ret) {\n    printf(\"ERROR threadpool_add %d\\n\", ret);\n    return;\n  }\n}\n\nvoid pad_synchronize()\n{\n  pthread_mutex_lock(&(pool->sync_lock));\n\n  while(pool->active > 0) {\n    pthread_cond_wait(&(pool->sync_notify), &(pool->sync_lock));\n  }\n\n  pthread_mutex_unlock(&(pool->sync_lock));\n}\n\n#endif\n//<<PAD(DEG_MAIN)>>//\nint main (int argc, char *argv[])\n{\n\n  //Mobility *mobility_frame_10;\n  //Application_Config *application_frame_20;\n\n  //Here make modifications on the mobility and traffic new models\n  //mob_frame_10 -> ...\n  //application_frame_30 -> ...\n\n  //schedule(ET_OMG, 10, NULL, mobility_frame_10);\n  //schedule(ET_OTG, 15, NULL, application_frame_20);\n\n  //event_list_display(&event_list);\n\n  schedule_end_of_simulation(FRAME, 100);\n\n  run(argc, argv);\n\n  return 0;\n}\n//<<PAD>>//\n\n//<<PAD(RUN)>>//\nvoid run(int argc, char *argv[])\n{\n\n\n  int32_t i;\n  module_id_t UE_id, eNB_id;\n  Job_elt *job_elt;\n  int ret;\n\n  clock_t t;\n\n\n  Event_elt *user_defined_event;\n  Event event;\n\n  // Framing variables\n  int32_t slot, last_slot, next_slot;\n\n  FILE *SINRpost;\n  char SINRpost_fname[512];\n  sprintf(SINRpost_fname,\"postprocSINR.m\");\n  SINRpost = fopen(SINRpost_fname,\"w\");\n  // variables/flags which are set by user on command-line\n  double snr_direction,snr_step=1.0;//,sinr_direction;\n\n  lte_subframe_t direction;\n  char fname[64],vname[64];\n\n#ifdef XFORMS\n  // current status is that every UE has a DL scope for a SINGLE eNB (eNB_id=0)\n  // at eNB 0, an UL scope for every UE\n  FD_lte_phy_scope_ue  *form_ue[NUMBER_OF_UE_MAX];\n  FD_lte_phy_scope_enb *form_enb[NUMBER_OF_UE_MAX];\n  char title[255];\n#endif\n\n#ifdef PROC\n  int node_id;\n  int port,Process_Flag=0,wgt,Channel_Flag=0,temp;\n#endif\n\n  // uint8_t awgn_flag = 0;\n\n#ifdef PRINT_STATS\n  int len;\n  FILE *UE_stats[NUMBER_OF_UE_MAX], *UE_stats_th[NUMBER_OF_UE_MAX], *eNB_stats, *eNB_avg_thr, *eNB_l2_stats;\n  char UE_stats_filename[255];\n  char UE_stats_th_filename[255];\n  char eNB_stats_th_filename[255];\n#endif\n\n#ifdef SMBV\n  uint8_t config_smbv = 0;\n  char smbv_ip[16];\n  strcpy(smbv_ip,DEFAULT_SMBV_IP);\n#endif\n\n#ifdef OPENAIR2\n  Data_Flow_Unit omv_data;\n#endif\n\n\n  //time_t t0,t1;\n  //clock_t start, stop;\n\n  //double **s_re2[MAX_eNB+MAX_UE], **s_im2[MAX_eNB+MAX_UE], **r_re2[MAX_eNB+MAX_UE], **r_im2[MAX_eNB+MAX_UE], **r_re02, **r_im02;\n  //double **r_re0_d[MAX_UE][MAX_eNB], **r_im0_d[MAX_UE][MAX_eNB], **r_re0_u[MAX_eNB][MAX_UE],**r_im0_u[MAX_eNB][MAX_UE];\n  //default parameters\n\n  //{\n  /* INITIALIZATIONS */\n\n  target_dl_mcs = 0;\n  rate_adaptation_flag = 0;\n  oai_emulation.info.n_frames = 0xffff;//1024;          //10;\n  oai_emulation.info.n_frames_flag = 0;//fixme\n  snr_dB = 30;\n  cooperation_flag = 0;         // default value 0 for no cooperation, 1 for Delay diversity, 2 for Distributed Alamouti\n\n  //Default values if not changed by the user in get_simulation_options();\n  pdcp_period = 1;\n  omg_period = 10;\n\n  mRAL_init_default_values(); //Default values\n  eRAL_init_default_values(); //Default values\n\n  init_oai_emulation(); //Default values\n\n  get_simulation_options(argc, argv); //Command-line options\n\n  oaisim_config(); // config OMG and OCG, OPT, OTG, OLG\n\n  //To fix eventual conflict on the value of n_frames\n  if (oai_emulation.info.n_frames_flag) {\n    schedule_end_of_simulation(FRAME, oai_emulation.info.n_frames);\n  }\n\n  VCD_SIGNAL_DUMPER_INIT(); // Initialize VCD LOG module\n\n#ifdef OPENAIR2\n  init_omv();\n#endif\n\n  check_and_adjust_params(); //Before this call, NB_UE_INST and NB_eNB_INST are not set correctly\n\n  init_otg_pdcp_buffer();\n\n#ifdef PRINT_STATS\n\n  for (UE_id=0; UE_id<NB_UE_INST; UE_id++) {\n    sprintf(UE_stats_filename,\"UE_stats%d.txt\",UE_id);\n    UE_stats[UE_id] = fopen (UE_stats_filename, \"w\");\n  }\n\n  eNB_stats = fopen (\"eNB_stats.txt\", \"w\");\n  printf (\"UE_stats=%p, eNB_stats=%p\\n\", UE_stats, eNB_stats);\n\n  eNB_avg_thr = fopen (\"eNB_stats_th.txt\", \"w\");\n\n#endif\n\n  LOG_I(EMU,\"total number of UE %d (local %d, remote %d) mobility %s \\n\", NB_UE_INST,oai_emulation.info.nb_ue_local,oai_emulation.info.nb_ue_remote,\n        oai_emulation.topology_config.mobility.eNB_mobility.eNB_mobility_type.selected_option);\n  LOG_I(EMU,\"Total number of eNB %d (local %d, remote %d) mobility %s \\n\", NB_eNB_INST,oai_emulation.info.nb_enb_local,oai_emulation.info.nb_enb_remote,\n        oai_emulation.topology_config.mobility.UE_mobility.UE_mobility_type.selected_option);\n  LOG_I(OCM,\"Running with frame_type %d, Nid_cell %d, N_RB_DL %d, EP %d, mode %d, target dl_mcs %d, rate adaptation %d, nframes %d, abstraction %d, channel %s\\n\",\n        oai_emulation.info.frame_type, Nid_cell, oai_emulation.info.N_RB_DL, oai_emulation.info.extended_prefix_flag, oai_emulation.info.transmission_mode,target_dl_mcs,rate_adaptation_flag,\n        oai_emulation.info.n_frames,abstraction_flag,oai_emulation.environment_system_config.fading.small_scale.selected_option);\n\n  init_seed(set_seed);\n\n  init_openair1();\n\n  init_openair2();\n\n  init_ocm();\n\n#ifdef XFORMS\n  init_xforms();\n#endif\n\n  printf (\"before L2 init: Nid_cell %d\\n\", PHY_vars_eNB_g[0]->lte_frame_parms.Nid_cell);\n  printf (\"before L2 init: frame_type %d,tdd_config %d\\n\",\n          PHY_vars_eNB_g[0]->lte_frame_parms.frame_type,\n          PHY_vars_eNB_g[0]->lte_frame_parms.tdd_config);\n\n  init_time();\n\n#ifdef PAD\n  pad_init();\n#endif\n\n  if (ue_connection_test == 1) {\n    snr_direction = -snr_step;\n    snr_dB=20;\n    sinr_dB=-20;\n  }\n\n  frame = 0;\n  slot = 0;\n\n  LOG_I(EMU,\">>>>>>>>>>>>>>>>>>>>>>>>>>> OAIEMU initialization done <<<<<<<<<<<<<<<<<<<<<<<<<<\\n\\n\");\n\n  printf (\"after init: Nid_cell %d\\n\", PHY_vars_eNB_g[0]->lte_frame_parms.Nid_cell);\n  printf (\"after init: frame_type %d,tdd_config %d\\n\",\n          PHY_vars_eNB_g[0]->lte_frame_parms.frame_type,\n          PHY_vars_eNB_g[0]->lte_frame_parms.tdd_config);\n\n  t = clock();\n\n  while (!end_of_simulation()) {\n\n    last_slot = (slot - 1)%20;\n\n    if (last_slot <0)\n      last_slot+=20;\n\n    next_slot = (slot + 1)%20;\n\n    oai_emulation.info.time_ms = frame * 10 + (next_slot>>1);\n    oai_emulation.info.frame = frame;\n\n    if (slot == 0) { //Frame's Prologue\n\n      //Run the aperiodic user-defined events\n      while ((user_defined_event = event_list_get_head(&event_list)) != NULL) {\n\n        event = user_defined_event->event;\n\n        if (event.frame == frame) {\n          switch (event.type) {\n          case ET_OMG:\n            update_omg_model(event.key, event.value); //implement it with assigning the new values to that of oai_emulation & second thing is to ensure mob model is always read from oai_emulation\n            user_defined_event = event_list_remove_head(&event_list);\n            break;\n\n          case ET_OTG:\n            update_otg_model(event.key, event.value);\n            user_defined_event = event_list_remove_head(&event_list);\n            break;\n          }\n        } else {\n          break;\n        }\n      }\n\n      //Comment (handle cooperation flag) deleted here. Look at oaisim.c to see it\n      if (ue_connection_test==1) {\n        if ((frame%20) == 0) {\n          snr_dB += snr_direction;\n          sinr_dB -= snr_direction;\n        }\n\n        if (snr_dB == -20) {\n          snr_direction=snr_step;\n        } else if (snr_dB==20) {\n          snr_direction=-snr_step;\n        }\n      }\n\n      update_omg(); // frequency is defined in the omg_global params configurable by the user\n\n      update_omg_ocm();\n\n#ifdef OPENAIR2\n\n      // check if pipe is still open\n      if ((oai_emulation.info.omv_enabled == 1) ) {\n        omv_write(pfd[1], enb_node_list, ue_node_list, omv_data);\n      }\n\n#endif\n\n#ifdef DEBUG_OMG\n\n      if ((((int) oai_emulation.info.time_s) % 100) == 0) {\n        for (UE_id = oai_emulation.info.first_ue_local; UE_id < (oai_emulation.info.first_ue_local + oai_emulation.info.nb_ue_local); UE_id++) {\n          get_node_position (UE, UE_id);\n        }\n      }\n\n#endif\n      update_ocm();\n    }\n\n    direction = subframe_select(frame_parms,next_slot>>1);\n\n    if((next_slot %2) ==0)\n      clear_eNB_transport_info(oai_emulation.info.nb_enb_local);\n\n\n    for (eNB_id=oai_emulation.info.first_enb_local;\n         (eNB_id<(oai_emulation.info.first_enb_local+oai_emulation.info.nb_enb_local)) && (oai_emulation.info.cli_start_enb[eNB_id]==1);\n         eNB_id++) {\n      for_main_times += 1;\n      //printf (\"debug: Nid_cell %d\\n\", PHY_vars_eNB_g[eNB_id]->lte_frame_parms.Nid_cell);\n      //printf (\"debug: frame_type %d,tdd_config %d\\n\", PHY_vars_eNB_g[eNB_id]->lte_frame_parms.frame_type,PHY_vars_eNB_g[eNB_id]->lte_frame_parms.tdd_config);\n      LOG_D(EMU,\"PHY procedures eNB %d for frame %d, slot %d (subframe TX %d, RX %d) TDD %d/%d Nid_cell %d\\n\",\n            eNB_id, frame, slot, next_slot >> 1,last_slot>>1,\n            PHY_vars_eNB_g[eNB_id]->lte_frame_parms.frame_type,\n            PHY_vars_eNB_g[eNB_id]->lte_frame_parms.tdd_config,PHY_vars_eNB_g[eNB_id]->lte_frame_parms.Nid_cell);\n\n      //Appliation\n#ifdef PAD_FINE\n      pad_inject_job(1, eNB_id, frame, next_slot, last_slot, JT_OTG, oai_emulation.info.time_ms);\n#else\n      update_otg_eNB(eNB_id, oai_emulation.info.time_ms);\n#endif\n\n      //Access layer\n      if (frame % pdcp_period == 0) {\n#ifdef PAD_FINE\n        pad_inject_job(1, eNB_id, frame, next_slot, last_slot, JT_PDCP, oai_emulation.info.time_ms);\n#else\n        pdcp_run(frame, 1, 0, eNB_id);//PHY_vars_eNB_g[eNB_id]->Mod_id\n#endif\n      }\n\n      //Phy/Mac layer\n#ifdef PAD_FINE\n      pad_inject_job(1, eNB_id, frame, next_slot, last_slot, JT_PHY_MAC, oai_emulation.info.time_ms);\n#else\n      phy_procedures_eNB_lte (last_slot, next_slot, PHY_vars_eNB_g[eNB_id], abstraction_flag, no_relay, NULL);\n#endif\n\n\n#ifdef PRINT_STATS\n\n      if(last_slot==9 && frame%10==0)\n        if(eNB_avg_thr)\n          fprintf(eNB_avg_thr,\"%d %d\\n\",PHY_vars_eNB_g[eNB_id]->frame,(PHY_vars_eNB_g[eNB_id]->total_system_throughput)/((PHY_vars_eNB_g[eNB_id]->frame+1)*10));\n\n      if (eNB_stats) {\n        len = dump_eNB_stats(PHY_vars_eNB_g[eNB_id], stats_buffer, 0);\n        rewind (eNB_stats);\n        fwrite (stats_buffer, 1, len, eNB_stats);\n        fflush(eNB_stats);\n      }\n\n#ifdef OPENAIR2\n\n      if (eNB_l2_stats) {\n        len = dump_eNB_l2_stats (stats_buffer, 0);\n        rewind (eNB_l2_stats);\n        fwrite (stats_buffer, 1, len, eNB_l2_stats);\n        fflush(eNB_l2_stats);\n      }\n\n#endif\n#endif\n    }\n\n#ifdef PAD_SYNC\n\n    if ((direction == SF_DL) || ((direction == SF_S) && (next_slot%2==0)) )\n      pad_synchronize();\n\n#endif\n\n\n    // Call ETHERNET emulation here\n    //emu_transport (frame, last_slot, next_slot, direction, oai_emulation.info.frame_type, ethernet_flag);\n\n    if ((next_slot % 2) == 0)\n      clear_UE_transport_info (oai_emulation.info.nb_ue_local);\n\n    for (UE_id = oai_emulation.info.first_ue_local;\n         (UE_id < (oai_emulation.info.first_ue_local+oai_emulation.info.nb_ue_local)) && (oai_emulation.info.cli_start_ue[UE_id]==1);\n         UE_id++)\n      if (frame >= (UE_id * 20)) {    // activate UE only after 20*UE_id frames so that different UEs turn on separately\n\n        LOG_D(EMU,\"PHY procedures UE %d for frame %d, slot %d (subframe TX %d, RX %d)\\n\",\n              UE_id, frame, slot, next_slot >> 1,last_slot>>1);\n\n        if (PHY_vars_UE_g[UE_id]->UE_mode[0] != NOT_SYNCHED) {\n          if (frame>0) {\n            PHY_vars_UE_g[UE_id]->frame = frame;\n\n            //Application UE\n#ifdef PAD_FINE\n            pad_inject_job(0, UE_id, frame, next_slot, last_slot, JT_OTG, oai_emulation.info.time_ms);\n#else\n            update_otg_UE(UE_id + NB_eNB_INST, oai_emulation.info.time_ms);\n#endif\n\n            //Access layer UE\n            if (frame % pdcp_period == 0) {\n#ifdef PAD_FINE\n              pad_inject_job(0, UE_id, frame, next_slot, last_slot, JT_PDCP, oai_emulation.info.time_ms);\n#else\n              pdcp_run(frame, 0, UE_id, 0);\n#endif\n            }\n\n            //Phy/Mac layer UE\n#ifdef PAD_FINE\n            pad_inject_job(0, UE_id, frame, next_slot, last_slot, JT_PHY_MAC, oai_emulation.info.time_ms);\n#else\n            phy_procedures_UE_lte (last_slot, next_slot, PHY_vars_UE_g[UE_id], 0, abstraction_flag, normal_txrx, no_relay, NULL);\n            ue_data[UE_id]->tx_power_dBm = PHY_vars_UE_g[UE_id]->tx_power_dBm;\n#endif\n          }\n        } else {\n          if (abstraction_flag==1) {\n            LOG_E(EMU, \"sync not supported in abstraction mode (UE%d,mode%d)\\n\", UE_id, PHY_vars_UE_g[UE_id]->UE_mode[0]);\n            exit(-1);\n          }\n\n          if ((frame>0) && (last_slot == (LTE_SLOTS_PER_FRAME-2))) {\n#ifdef PAD_FINE\n            pad_inject_job(0, UE_id, frame, next_slot, last_slot, JT_INIT_SYNC, oai_emulation.info.time_ms);\n#else\n            initial_sync(PHY_vars_UE_g[UE_id],normal_txrx);\n#endif\n            /* LONG write output comment DELETED here */\n          }\n        }\n\n#ifdef PRINT_STATS\n\n        if(last_slot==2 && frame%10==0)\n          if (UE_stats_th[UE_id])\n            fprintf(UE_stats_th[UE_id],\"%d %d\\n\",frame, PHY_vars_UE_g[UE_id]->bitrate[0]/1000);\n\n        if (UE_stats[UE_id]) {\n          len = dump_ue_stats (PHY_vars_UE_g[UE_id], stats_buffer, 0, normal_txrx, 0);\n          rewind (UE_stats[UE_id]);\n          fwrite (stats_buffer, 1, len, UE_stats[UE_id]);\n          fflush(UE_stats[UE_id]);\n        }\n\n#endif\n      }\n\n#ifdef PAD_SYNC\n\n    if ((direction == SF_UL) || ((direction == SF_S) && (next_slot%2==1)) )\n      pad_synchronize();\n\n#endif\n\n    emu_transport (frame, last_slot, next_slot,direction, oai_emulation.info.frame_type, ethernet_flag);\n\n    if ((direction  == SF_DL)|| (frame_parms->frame_type==0)) {\n      for (UE_id=0; UE_id<NB_UE_INST; UE_id++) {\n\n#ifdef PAD\n        pad_inject_job(0, UE_id, frame, next_slot, last_slot, JT_DL, oai_emulation.info.time_ms);\n#else\n        do_DL_sig(r_re0,r_im0,r_re,r_im,s_re,s_im,eNB2UE,enb_data,ue_data,next_slot,abstraction_flag,frame_parms,UE_id);\n#endif\n      }\n    }\n\n    if ((direction  == SF_UL)|| (frame_parms->frame_type==0)) { //if ((subframe<2) || (subframe>4))\n      do_UL_sig(r_re0,r_im0,r_re,r_im,s_re,s_im,UE2eNB,enb_data,ue_data,next_slot,abstraction_flag,frame_parms,frame);\n\n      /*\n            int ccc;\n            fprintf(SINRpost,\"SINRdb For eNB New Subframe : \\n \");\n            for(ccc = 0 ; ccc<301; ccc++)\n            {\n              fprintf(SINRpost,\"_ %f \", SINRpost_eff[ccc]);\n            }\n            fprintf(SINRpost,\"SINRdb For eNB : %f \\n \", SINRpost_eff[ccc]);\n            */\n    }\n\n    if ((direction == SF_S)) {//it must be a special subframe\n      if (next_slot%2==0) {//DL part\n        for (UE_id=0; UE_id<NB_UE_INST; UE_id++) {\n#ifdef PAD\n          pad_inject_job(0, UE_id, frame, next_slot, last_slot, JT_DL, oai_emulation.info.time_ms);\n#else\n          do_DL_sig(r_re0,r_im0,r_re,r_im,s_re,s_im,eNB2UE,enb_data,ue_data,next_slot,abstraction_flag,frame_parms,UE_id);\n#endif\n        }\n\n        /*\n              for (aarx=0;aarx<UE2eNB[1][0]->nb_rx;aarx++)\n              for (aatx=0;aatx<UE2eNB[1][0]->nb_tx;aatx++)\n              for (k=0;k<UE2eNB[1][0]->channel_length;k++)\n              printf(\"SB(%d,%d,%d)->(%f,%f)\\n\",k,aarx,aatx,UE2eNB[1][0]->ch[aarx+(aatx*UE2eNB[1][0]->nb_rx)][k].r,UE2eNB[1][0]->ch[aarx+(aatx*UE2eNB[1][0]->nb_rx)][k].i);\n            */\n      } else { // UL part\n        /*#ifdef PAD\n        pthread_mutex_lock(&(pool->sync_lock));\n        while(pool->active != 0) {\n        pthread_cond_wait(&(pool->sync_notify), &(pool->sync_lock));\n        }\n        pthread_mutex_unlock(&(pool->sync_lock));\n        #endif*/\n        do_UL_sig(r_re0,r_im0,r_re,r_im,s_re,s_im,UE2eNB,enb_data,ue_data,next_slot,abstraction_flag,frame_parms,frame);\n        /*\n                int ccc;\n                fprintf(SINRpost,\"SINRdb For eNB New Subframe : \\n \");\n                for(ccc = 0 ; ccc<301; ccc++)\n                {\n                  fprintf(SINRpost,\"_ %f \", SINRpost_eff[ccc]);\n                }\n                fprintf(SINRpost,\"SINRdb For eNB : %f \\n \", SINRpost_eff[ccc]);\n                */\n      }\n    }\n\n    if ((last_slot == 1) && (frame == 0)\n        && (abstraction_flag == 0) && (oai_emulation.info.n_frames == 1)) {\n\n      write_output (\"dlchan0.m\", \"dlch0\",\n                    &(PHY_vars_UE_g[0]->lte_ue_common_vars.common_vars_rx_data_per_thread[subframe&0x1].dl_ch_estimates[0][0][0]),\n                    (6 * (PHY_vars_UE_g[0]->lte_frame_parms.ofdm_symbol_size)), 1, 1);\n      write_output (\"dlchan1.m\", \"dlch1\",\n                    &(PHY_vars_UE_g[0]->lte_ue_common_vars.common_vars_rx_data_per_thread[subframe&0x1].dl_ch_estimates[1][0][0]),\n                    (6 * (PHY_vars_UE_g[0]->lte_frame_parms.ofdm_symbol_size)), 1, 1);\n      write_output (\"dlchan2.m\", \"dlch2\",\n                    &(PHY_vars_UE_g[0]->lte_ue_common_vars.common_vars_rx_data_per_thread[subframe&0x1].dl_ch_estimates[2][0][0]),\n                    (6 * (PHY_vars_UE_g[0]->lte_frame_parms.ofdm_symbol_size)), 1, 1);\n      write_output (\"pbch_rxF_comp0.m\", \"pbch_comp0\",\n                    PHY_vars_UE_g[0]->lte_ue_pbch_vars[0]->rxdataF_comp[0], 6 * 12 * 4, 1, 1);\n      write_output (\"pbch_rxF_llr.m\", \"pbch_llr\",\n                    PHY_vars_UE_g[0]->lte_ue_pbch_vars[0]->llr, (frame_parms->Ncp == 0) ? 1920 : 1728, 1, 4);\n    }\n\n    if (next_slot %2 == 0) {\n      clock_gettime (CLOCK_REALTIME, &time_spec);\n      time_last = time_now;\n      time_now = (unsigned long) time_spec.tv_nsec;\n      td = (int) (time_now - time_last);\n\n      if (td>0) {\n        td_avg = (int)(((K*(long)td) + (((1<<3)-K)*((long)td_avg)))>>3); // in us\n        LOG_T(EMU,\"sleep frame %d, time_now %ldus,time_last %ldus,average time difference %ldns, CURRENT TIME DIFF %dus, avgerage difference from the target %dus\\n\",\n              frame, time_now,time_last,td_avg, td/1000,(td_avg-TARGET_SF_TIME_NS)/1000);\n      }\n\n      if (td_avg<(TARGET_SF_TIME_NS - SF_DEVIATION_OFFSET_NS)) {\n        sleep_time_us += SLEEP_STEP_US;\n        LOG_D(EMU,\"Faster than realtime increase the avg sleep time for %d us, frame %d\\n\",\n              sleep_time_us,frame);\n        // LOG_D(EMU,\"Faster than realtime increase the avg sleep time for %d us, frame %d, time_now %ldus,time_last %ldus,average time difference %ldns, CURRENT TIME DIFF %dus, avgerage difference from the target %dus\\n\",    sleep_time_us,frame, time_now,time_last,td_avg, td/1000,(td_avg-TARGET_SF_TIME_NS)/1000);\n      } else if (td_avg > (TARGET_SF_TIME_NS + SF_DEVIATION_OFFSET_NS)) {\n        sleep_time_us-= SLEEP_STEP_US;\n        LOG_D(EMU,\"Slower than realtime reduce the avg sleep time for %d us, frame %d, time_now\\n\",\n              sleep_time_us,frame);\n        //LOG_T(EMU,\"Slower than realtime reduce the avg sleep time for %d us, frame %d, time_now %ldus,time_last %ldus,average time difference %ldns, CURRENT TIME DIFF %dus, avgerage difference from the target %dus\\n\",     sleep_time_us,frame, time_now,time_last,td_avg, td/1000,(td_avg-TARGET_SF_TIME_NS)/1000);\n      }\n    } // end if next_slot%2\n\n    slot++;\n\n    if (slot == 20) { //Frame's Epilogue\n      frame++;\n      slot = 0;\n\n      // if n_frames not set by the user or is greater than max num frame then set adjust the frame counter\n      if ( (oai_emulation.info.n_frames_flag == 0) || (oai_emulation.info.n_frames >= 0xffff) ) {\n        frame %=(oai_emulation.info.n_frames-1);\n      }\n\n      oai_emulation.info.time_s += 0.01;\n\n      if ((frame>=1)&&(frame<=9)&&(abstraction_flag==0)) {\n        write_output(\"UEtxsig0.m\",\"txs0\", PHY_vars_UE_g[0]->lte_ue_common_vars.txdata[0],FRAME_LENGTH_COMPLEX_SAMPLES,1,1);\n        sprintf(fname,\"eNBtxsig%d.m\",frame);\n        sprintf(vname,\"txs%d\",frame);\n        write_output(fname,vname, PHY_vars_eNB_g[0]->lte_eNB_common_vars.txdata[0][0],FRAME_LENGTH_COMPLEX_SAMPLES,1,1);\n        write_output(\"eNBtxsigF0.m\",\"txsF0\",PHY_vars_eNB_g[0]->lte_eNB_common_vars.txdataF[0][0],PHY_vars_eNB_g[0]->lte_frame_parms.symbols_per_tti*PHY_vars_eNB_g[0]->lte_frame_parms.ofdm_symbol_size,1,1);\n\n        write_output(\"UErxsig0.m\",\"rxs0\", PHY_vars_UE_g[0]->lte_ue_common_vars.rxdata[0],FRAME_LENGTH_COMPLEX_SAMPLES,1,1);\n        write_output(\"eNBrxsig0.m\",\"rxs0\", PHY_vars_eNB_g[0]->lte_eNB_common_vars.rxdata[0][0],FRAME_LENGTH_COMPLEX_SAMPLES,1,1);\n      }\n\n#ifdef XFORMS\n      do_xforms();\n#endif\n\n      // calibrate at the end of each frame if there is some time  left\n      if((sleep_time_us > 0)&& (ethernet_flag ==0)) {\n        LOG_I(EMU,\"[TIMING] Adjust average frame duration, sleep for %d us\\n\",sleep_time_us);\n        usleep(sleep_time_us);\n        sleep_time_us=0; // reset the timer, could be done per n SF\n      }\n\n#ifdef SMBV\n\n      if ((frame == config_frames[0]) || (frame == config_frames[1]) || (frame == config_frames[2]) || (frame == config_frames[3])) {\n        smbv_frame_cnt++;\n      }\n\n#endif\n    }\n  }\n\n  t = clock() - t;\n  printf(\"rrc Duration of the simulation: %f seconds\\n\",((float)t)/CLOCKS_PER_SEC);\n\n  fclose(SINRpost);\n  LOG_I(EMU,\">>>>>>>>>>>>>>>>>>>>>>>>>>> OAIEMU Ending <<<<<<<<<<<<<<<<<<<<<<<<<<\\n\\n\");\n\n  free(otg_pdcp_buffer);\n\n#ifdef SMBV\n\n  if (config_smbv) {\n    smbv_send_config (smbv_fname,smbv_ip);\n  }\n\n#endif\n\n  //Perform KPI measurements\n  if (oai_emulation.info.otg_enabled==1)\n    kpi_gen();\n\n#ifdef PAD\n  pad_finalize();\n#endif\n\n  // relase all rx state\n  if (ethernet_flag == 1) {\n    emu_transport_release ();\n  }\n\n  if (abstraction_flag == 0) {\n    /*\n           #ifdef IFFT_FPGA\n           free(txdataF2[0]);\n           free(txdataF2[1]);\n           free(txdataF2);\n           free(txdata[0]);\n           free(txdata[1]);\n           free(txdata);\n           #endif\n         */\n\n    for (i = 0; i < 2; i++) {\n      free (s_re[i]);\n      free (s_im[i]);\n      free (r_re[i]);\n      free (r_im[i]);\n    }\n\n    free (s_re);\n    free (s_im);\n    free (r_re);\n    free (r_im);\n    lte_sync_time_free ();\n  }\n\n  //  pthread_join(sigth, NULL);\n\n  // added for PHY abstraction\n  if (oai_emulation.info.ocm_enabled == 1) {\n    for (eNB_id = 0; eNB_id < NUMBER_OF_eNB_MAX; eNB_id++)\n      free(enb_data[eNB_id]);\n\n    for (UE_id = 0; UE_id < NUMBER_OF_UE_MAX; UE_id++)\n      free(ue_data[UE_id]);\n  } //End of PHY abstraction changes\n\n#ifdef OPENAIR2\n  mac_top_cleanup();\n#endif\n\n#ifdef PRINT_STATS\n\n  for(UE_id=0; UE_id<NB_UE_INST; UE_id++) {\n    if (UE_stats[UE_id])\n      fclose (UE_stats[UE_id]);\n\n    if(UE_stats_th[UE_id])\n      fclose (UE_stats_th[UE_id]);\n  }\n\n  if (eNB_stats)\n    fclose (eNB_stats);\n\n  if (eNB_avg_thr)\n    fclose (eNB_avg_thr);\n\n  if (eNB_l2_stats)\n    fclose (eNB_l2_stats);\n\n#endif\n\n  // stop OMG\n  stop_mobility_generator(oai_emulation.info.omg_model_ue);//omg_param_list.mobility_type\n#ifdef OPENAIR2\n\n  if (oai_emulation.info.omv_enabled == 1)\n    omv_end(pfd[1],omv_data);\n\n#endif\n\n  if ((oai_emulation.info.ocm_enabled == 1) && (ethernet_flag == 0) && (ShaF != NULL))\n    destroyMat(ShaF,map1, map2);\n\n  if (opt_enabled == 1 )\n    terminate_opt();\n\n  if (oai_emulation.info.cli_enabled)\n    cli_server_cleanup();\n\n  //bring oai if down\n  terminate();\n  logClean();\n  VCD_SIGNAL_DUMPER_CLOSE();\n  //printf(\"FOR MAIN TIMES = %d &&&& OTG TIMES = %d <-> FOR TIMES = %d <-> IF TIMES = %d\\n\", for_main_times, otg_times, for_times, if_times);\n\n}\n//<<PAD>>//\n\nvoid terminate(void)\n{\n  int i;\n  char interfaceName[8];\n\n  for (i=0; i < NUMBER_OF_eNB_MAX+NUMBER_OF_UE_MAX; i++)\n    if (oai_emulation.info.oai_ifup[i]==1) {\n      sprintf(interfaceName, \"oai%d\", i);\n      bringInterfaceUp(interfaceName,0);\n    }\n}\n\n#ifdef OPENAIR2\nint omv_write (int pfd,  Node_list enb_node_list, Node_list ue_node_list, Data_Flow_Unit omv_data)\n{\n  int i,j;\n  omv_data.end=0;\n\n  //omv_data.total_num_nodes = NB_UE_INST + NB_eNB_INST;\n  for (i=0; i<NB_eNB_INST; i++) {\n    if (enb_node_list != NULL) {\n      omv_data.geo[i].x = (enb_node_list->node->X_pos < 0.0)? 0.0 : enb_node_list->node->X_pos;\n      omv_data.geo[i].y = (enb_node_list->node->Y_pos < 0.0)? 0.0 : enb_node_list->node->Y_pos;\n      omv_data.geo[i].z = 1.0;\n      omv_data.geo[i].mobility_type = oai_emulation.info.omg_model_enb;\n      omv_data.geo[i].node_type = 0; //eNB\n      enb_node_list = enb_node_list->next;\n      omv_data.geo[i].Neighbors=0;\n\n      for (j=NB_eNB_INST; j< NB_UE_INST + NB_eNB_INST ; j++) {\n        if (is_UE_active(i,j - NB_eNB_INST ) == 1) {\n          omv_data.geo[i].Neighbor[omv_data.geo[i].Neighbors]=  j;\n          omv_data.geo[i].Neighbors++;\n          LOG_D(OMG,\"[eNB %d][UE %d] is_UE_active(i,j) %d geo (x%d, y%d) num neighbors %d\\n\", i,j-NB_eNB_INST, is_UE_active(i,j-NB_eNB_INST),\n                omv_data.geo[i].x, omv_data.geo[i].y, omv_data.geo[i].Neighbors);\n        }\n      }\n    }\n  }\n\n  for (i=NB_eNB_INST; i<NB_UE_INST+NB_eNB_INST; i++) {\n    if (ue_node_list != NULL) {\n      omv_data.geo[i].x = (ue_node_list->node->X_pos < 0.0) ? 0.0 : ue_node_list->node->X_pos;\n      omv_data.geo[i].y = (ue_node_list->node->Y_pos < 0.0) ? 0.0 : ue_node_list->node->Y_pos;\n      omv_data.geo[i].z = 1.0;\n      omv_data.geo[i].mobility_type = oai_emulation.info.omg_model_ue;\n      omv_data.geo[i].node_type = 1; //UE\n      //trial\n      omv_data.geo[i].state = 1;\n      omv_data.geo[i].rnti = 88;\n      omv_data.geo[i].connected_eNB = 0;\n      omv_data.geo[i].RSRP = 66;\n      omv_data.geo[i].RSRQ = 55;\n      omv_data.geo[i].Pathloss = 44;\n      omv_data.geo[i].RSSI[0] = 33;\n      omv_data.geo[i].RSSI[1] = 22;\n      omv_data.geo[i].RSSI[2] = 11;\n\n      ue_node_list = ue_node_list->next;\n      omv_data.geo[i].Neighbors=0;\n\n      for (j=0; j< NB_eNB_INST ; j++) {\n        if (is_UE_active(j,i-NB_eNB_INST) == 1) {\n          omv_data.geo[i].Neighbor[ omv_data.geo[i].Neighbors]=j;\n          omv_data.geo[i].Neighbors++;\n          LOG_D(OMG,\"[UE %d][eNB %d] is_UE_active  %d geo (x%d, y%d) num neighbors %d\\n\", i-NB_eNB_INST,j, is_UE_active(j,i-NB_eNB_INST),\n                omv_data.geo[i].x, omv_data.geo[i].y, omv_data.geo[i].Neighbors);\n        }\n      }\n    }\n  }\n\n  if( write( pfd, &omv_data, sizeof(struct Data_Flow_Unit) ) == -1 )\n    perror( \"write omv failed\" );\n\n  return 1;\n}\n\nvoid omv_end (int pfd, Data_Flow_Unit omv_data)\n{\n  omv_data.end=1;\n\n  if( write( pfd, &omv_data, sizeof(struct Data_Flow_Unit) ) == -1 )\n    perror( \"write omv failed\" );\n}\n#endif\n", "meta": {"hexsha": "1f251de581cd666e5a00877a47bbc8e93696793d", "size": 37876, "ext": "c", "lang": "C", "max_stars_repo_path": "targets/SIMU/USER/oaisim_pad.c", "max_stars_repo_name": "danghoaison91/openairinterface", "max_stars_repo_head_hexsha": "ca28acccb2dfe85a0644d5fd6d379928d89f72a6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2019-09-09T19:57:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T02:03:51.000Z", "max_issues_repo_path": "targets/SIMU/USER/oaisim_pad.c", "max_issues_repo_name": "danghoaison91/openairinterface", "max_issues_repo_head_hexsha": "ca28acccb2dfe85a0644d5fd6d379928d89f72a6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "targets/SIMU/USER/oaisim_pad.c", "max_forks_repo_name": "danghoaison91/openairinterface", "max_forks_repo_head_hexsha": "ca28acccb2dfe85a0644d5fd6d379928d89f72a6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-06-11T17:18:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-16T04:05:07.000Z", "avg_line_length": 32.9356521739, "max_line_length": 412, "alphanum_fraction": 0.6617647059, "num_tokens": 11483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.040237940465619626, "lm_q1q2_score": 0.01808263407128096}}
{"text": "/* sum/gsl_sum.h\n *\n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Author:  G. Jungman */\n\n\n#ifndef __GSL_SUM_H__\n#define __GSL_SUM_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS          /* empty */\n# define __END_DECLS            /* empty */\n#endif\n\n__BEGIN_DECLS\n\n/*  Workspace for Levin U Transform with error estimation,\n *   \n *   size        = number of terms the workspace can handle\n *   sum_plain   = simple sum of series\n *   q_num       = backward diagonal of numerator; length = size\n *   q_den       = backward diagonal of denominator; length = size\n *   dq_num      = table of numerator derivatives; length = size**2\n *   dq_den      = table of denominator derivatives; length = size**2\n *   dsum        = derivative of sum wrt term i; length = size\n */\n\ntypedef struct\n{\n  size_t size;\n  size_t i;                     /* position in array */\n  size_t terms_used;            /* number of calls */\n  double sum_plain;\n  double *q_num;\n  double *q_den;\n  double *dq_num;\n  double *dq_den;\n  double *dsum;\n}\ngsl_sum_levin_u_workspace;\n\nGSL_EXPORT gsl_sum_levin_u_workspace *gsl_sum_levin_u_alloc (size_t n);\nGSL_EXPORT void gsl_sum_levin_u_free (gsl_sum_levin_u_workspace * w);\n\n/* Basic Levin-u acceleration method.\n *\n *   array       = array of series elements\n *   n           = size of array\n *   sum_accel   = result of summation acceleration\n *   err         = estimated error\n *\n * See [Fessler et al., ACM TOMS 9, 346 (1983) and TOMS-602]\n */\n\nGSL_EXPORT int gsl_sum_levin_u_accel (const double *array,\n                                      const size_t n,\n                                      gsl_sum_levin_u_workspace * w,\n                                      double *sum_accel, double *abserr);\n\n/* Basic Levin-u acceleration method with constraints on the terms\n * used,\n *\n *   array       = array of series elements\n *   n           = size of array\n *   min_terms   = minimum number of terms to sum\n *   max_terms   = maximum number of terms to sum\n *   sum_accel   = result of summation acceleration\n *   err         = estimated error\n *\n * See [Fessler et al., ACM TOMS 9, 346 (1983) and TOMS-602]\n */\n\nGSL_EXPORT int gsl_sum_levin_u_minmax (const double *array,\n                                       const size_t n,\n                                       const size_t min_terms,\n                                       const size_t max_terms,\n                                       gsl_sum_levin_u_workspace * w,\n                                       double *sum_accel, double *abserr);\n\n/* Basic Levin-u step w/o reference to the array of terms.\n * We only need to specify the value of the current term\n * to execute the step. See TOMS-745.\n *\n * sum = t0 + ... + t_{n-1} + term;  term = t_{n}\n *\n *   term   = value of the series term to be added\n *   n      = position of term in series (starting from 0)\n *   sum_accel = result of summation acceleration\n *   sum_plain = simple sum of series\n */\n\nGSL_EXPORT\nint\ngsl_sum_levin_u_step (const double term,\n                      const size_t n,\n                      const size_t nmax,\n                      gsl_sum_levin_u_workspace * w,\n                      double *sum_accel);\n\n/* The following functions perform the same calculation without\n   estimating the errors. They require O(N) storage instead of O(N^2).\n   This may be useful for summing many similar series where the size\n   of the error has already been estimated reliably and is not\n   expected to change.  */\n\ntypedef struct\n{\n  size_t size;\n  size_t i;                     /* position in array */\n  size_t terms_used;            /* number of calls */\n  double sum_plain;\n  double *q_num;\n  double *q_den;\n  double *dsum;\n}\ngsl_sum_levin_utrunc_workspace;\n\nGSL_EXPORT gsl_sum_levin_utrunc_workspace *gsl_sum_levin_utrunc_alloc (size_t n);\nGSL_EXPORT void gsl_sum_levin_utrunc_free (gsl_sum_levin_utrunc_workspace * w);\n\nGSL_EXPORT int gsl_sum_levin_utrunc_accel (const double *array,\n                                           const size_t n,\n                                           gsl_sum_levin_utrunc_workspace * w,\n                                           double *sum_accel, double *abserr_trunc);\n\nGSL_EXPORT int gsl_sum_levin_utrunc_minmax (const double *array,\n                                            const size_t n,\n                                            const size_t min_terms,\n                                            const size_t max_terms,\n                                            gsl_sum_levin_utrunc_workspace * w,\n                                            double *sum_accel, double *abserr_trunc);\n\nGSL_EXPORT int gsl_sum_levin_utrunc_step (const double term,\n                                          const size_t n,\n                                          gsl_sum_levin_utrunc_workspace * w,\n                                          double *sum_accel);\n\n__END_DECLS\n\n#endif /* __GSL_SUM_H__ */\n", "meta": {"hexsha": "187192a095f7a5396aa3ef346a1fd6069338405d", "size": 5795, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/gsl/include/gsl/gsl_sum.h", "max_stars_repo_name": "dynaryu/vaws", "max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/gsl/include/gsl/gsl_sum.h", "max_issues_repo_name": "dynaryu/vaws", "max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/gsl/include/gsl/gsl_sum.h", "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1212121212, "max_line_length": 85, "alphanum_fraction": 0.6041415013, "num_tokens": 1354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.03732688734412946, "lm_q1q2_score": 0.018080400837546928}}
{"text": "/**\n * author: Jochen K\"upper\n * created: Jan 2002\n * file: pygsl/src/statistics/longmodule.c\n * $Id: ucharmodule.c,v 1.5 2004/03/24 08:40:45 schnizer Exp $\n *\n *\"\n */\n\n\n#include <Python.h>\n#include <pygsl/error_helpers.h>\n#include <pygsl/block_helpers.h>\n#include <gsl/gsl_statistics.h>\n\n\n/* include real functions for different data-types */\n\n#define STATMOD_APPEND_PY_TYPE(X) X ## Int\n#define STATMOD_APPEND_PYC_TYPE(X) X ## UBYTE\n#define STATMOD_FUNC_EXT(X, Y) X ## _uchar ## Y\n#define STATMOD_PY_AS_C PyInt_AsLong\n#define STATMOD_C_TYPE unsigned char\n#include \"functions.c\"\n\n\n\n\n\n\nPyGSL_STATISTICS_INIT(uchar, \"uchar\")\n\n\n/*\n * Local Variables:\n * mode: c\n * c-file-style: \"Stroustrup\"\n * End:\n */\n", "meta": {"hexsha": "4cd6b7d0901dc5e46270ccb57402d67d63613adc", "size": 701, "ext": "c", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/src/statistics/ucharmodule.c", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/src/statistics/ucharmodule.c", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/src/statistics/ucharmodule.c", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 17.525, "max_line_length": 62, "alphanum_fraction": 0.7061340942, "num_tokens": 209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.43398145016252104, "lm_q2_score": 0.04146227611666973, "lm_q1q2_score": 0.017993858716151192}}
{"text": "#include <stdio.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/block/gsl_block.h>\n#include <gsl/vector/gsl_vector.h>\n\n\n#define BASE_DOUBLE\n#include <gsl/templates_on.h>\n#include <gsl/vector/file_source.c>\n#include <gsl/templates_off.h>\n#undef BASE_DOUBLE\n\n", "meta": {"hexsha": "faf6d1574f8be1a82dd328f0dd5a1a28bb8546dd", "size": 253, "ext": "c", "lang": "C", "max_stars_repo_path": "Cartwheel/cartwheel-3d/gsl/vector/file.c", "max_stars_repo_name": "MontyThibault/centre-of-mass-awareness", "max_stars_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Cartwheel/cartwheel-3d/gsl/vector/file.c", "max_issues_repo_name": "MontyThibault/centre-of-mass-awareness", "max_issues_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cartwheel/cartwheel-3d/gsl/vector/file.c", "max_forks_repo_name": "MontyThibault/centre-of-mass-awareness", "max_forks_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.4615384615, "max_line_length": 35, "alphanum_fraction": 0.7628458498, "num_tokens": 67, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326183324442865, "lm_q2_score": 0.03963883697377708, "lm_q1q2_score": 0.017966771914411237}}
{"text": "/**\n * author: Jochen K\"upper\n * created: Jan 2002\n * file: pygsl/src/statisticsmodule.c\n * $Id: doublemodule.c,v 1.9 2004/03/24 08:40:45 schnizer Exp $\n *\n * optional usage of Numeric module, available at http://numpy.sourceforge.net\n * \"\n */\n\n#include <pygsl/error_helpers.h>\n#include <pygsl/block_helpers.h>\n#include <Python.h>\n#include <gsl/gsl_statistics.h>\n\n\n/* include real functions for default data-types (double in C) */\n\n#define STATMOD_WEIGHTED\n#define STATMOD_APPEND_PY_TYPE(X) X ## Float\n#define STATMOD_APPEND_PYC_TYPE(X) X ## DOUBLE\n#define STATMOD_FUNC_EXT(X, Y) X ## Y\n#define STATMOD_PY_AS_C PyFloat_AsDouble\n#define STATMOD_C_TYPE double\n#define PyGSL_STATISTICS_IMPORT_API\n#include \"functions.c\"\n\n\n\nPyGSL_STATISTICS_INIT(double, \"double\")\n\n\n\n/*\n * Local Variables:\n * mode: c\n * c-file-style: \"Stroustrup\"\n * End:\n */\n\n\n", "meta": {"hexsha": "faedc77cd1986fef1ea8533260bc5a4739d7b886", "size": 841, "ext": "c", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/src/statistics/doublemodule.c", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/src/statistics/doublemodule.c", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/src/statistics/doublemodule.c", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 20.0238095238, "max_line_length": 78, "alphanum_fraction": 0.7288941736, "num_tokens": 236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618332444286, "lm_q2_score": 0.03963883640652564, "lm_q1q2_score": 0.017966771657297813}}
{"text": "/**\n *\n * @file core_sgeqp3_init.c\n *\n *  PLASMA core_blas kernel\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Mark Gates\n * @date 2010-11-15\n * @generated s Tue Jan  7 11:44:49 2014\n *\n **/\n#include <lapacke.h>\n#include \"common.h\"\n\n/***************************************************************************//**\n *\n * @ingroup CORE_float\n *\n *  CORE_sgeqp3_init initializes jpvt to [1, ..., n].\n *  Uses 1-based indexing for Fortran compatability.\n *\n *******************************************************************************\n *\n *  @param[in] n\n *          Size of vector.\n *\n *  @param[in,out] jpvt\n *          Vector of size n.\n *          On exit, jpvt[i] = i+1.\n **/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_sgeqp3_init = PCORE_sgeqp3_init\n#define CORE_sgeqp3_init PCORE_sgeqp3_init\n#endif\nvoid CORE_sgeqp3_init( int n, int *jpvt )\n{\n    int j;\n    for( j = 0; j < n; ++j ) {\n        jpvt[j] = j+1;\n    }\n}\n", "meta": {"hexsha": "3d08d15682ef93fc21af6026cb4ee0375a3b181d", "size": 1041, "ext": "c", "lang": "C", "max_stars_repo_path": "core_blas/core_sgeqp3_init.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "core_blas/core_sgeqp3_init.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "core_blas/core_sgeqp3_init.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1333333333, "max_line_length": 80, "alphanum_fraction": 0.5244956772, "num_tokens": 303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30735801686526387, "lm_q2_score": 0.0583458389742937, "lm_q1q2_score": 0.017933061359478933}}
{"text": "#include \"../include/paralleltt.h\"\n#include <math.h>\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <mpi.h>\n#include <cblas.h>\n#include <string.h>\n#include <lapacke.h>\n\n#define min(a,b) ((a)>(b)?(b):(a))\n#define abs(a) ((a)>(0)?(a):(-a))\n\n#ifndef HEAD\n#define HEAD (int) 0\n#endif\n\nmatrix_tt* matrix_tt_init(const int m, const int n)\n{\n    matrix_tt* A = (matrix_tt*) malloc(sizeof(matrix_tt));\n    A->m = m;\n    A->n = n;\n    A->transpose = 0;\n    A->offset = 0;\n    A->lda = m;\n    A->X_size = (long) m*n;\n    A->X = (double*) malloc(A->X_size*sizeof(double));\n\n    return A;\n}\n\nvoid matrix_tt_wrap_update(matrix_tt* A, int m, int n, double* X)\n{\n    A->m = m;\n    A->n = n;\n    A->transpose = 0;\n    A->offset = 0;\n    A->lda = m;\n    A->X_size = (long) m*n;\n    A->X = X;\n}\n\nmatrix_tt* matrix_tt_wrap(int m, int n, double* X)\n{\n    matrix_tt* A = (matrix_tt*) malloc(sizeof(matrix_tt));\n    A->m = m;\n    A->n = n;\n    A->transpose = 0;\n    A->offset = 0;\n    A->lda = m;\n    A->X_size = (long) m*n;\n    A->X = X;\n    return A;\n}\n\nmatrix_tt* matrix_tt_copy(const matrix_tt* A)\n{\n    matrix_tt* B = (matrix_tt*) malloc(sizeof(matrix_tt));\n    int m = A->m; int n = A->n; int X_size = A->X_size;\n    B->m = m;\n    B->n = n;\n    B->transpose = A->transpose;\n    B->offset = A->offset;\n    B->lda = A->lda;\n    B->X_size = X_size;\n    B->X = (double*) malloc(X_size * sizeof(double));\n    memcpy(B->X, A->X, X_size * sizeof(double));\n\n    return B;\n}\n\n// Copy from matrix A to matrix B\nvoid matrix_tt_copy_data(matrix_tt* B, const matrix_tt* A)\n{\n    int BT = (B->transpose == 0) ? 0 : 1;\n    int AT = (A->transpose == 0) ? 0 : 1;\n    if (BT == AT){\n        if ((B->m != A->m) || (B->n != A->n)){\n            printf(\"matrix_tt_copy_data: B (%d x %d) is not the same size as A (%d x %d)\\n\", B->n, B->m, A->n, A->m);\n            return;\n        }\n        for (int jj = 0; jj < B->n; ++jj){\n            memcpy((B->X) + (B->offset) + (B->lda)*jj, (A->X) + (A->offset) + jj*(A->lda), (B->m)*sizeof(double));\n        }\n    }\n    else{\n        if ((B->m != A->n) || (B->n != A->m)){\n            printf(\"matrix_tt_copy_data: B (%d x %d, transpose = %d) is not the same size as A (%d x %d, transpose = %d)\\n\",\n                    B->n, B->m, B->transpose, A->n, A->m, A->transpose);\n            return;\n        }\n        for (int jj = 0; jj < B->n; ++jj){\n            double* BX = (B->X) + (B->offset) + (B->lda)*jj;\n            double* AX = (A->X) + (A->offset) + jj;\n            for (int ii = 0; ii < B->m; ++ii){\n                BX[ii] = AX[ii*(A->lda)];\n            }\n        }\n    }\n}\n\nmatrix_tt* submatrix_copy(const matrix_tt* A)\n{\n    matrix_tt* B = (matrix_tt*) malloc(sizeof(matrix_tt));\n    int m = A->m; int n = A->n; int X_size = m*n;\n    B->m = m;\n    B->n = n;\n    B->transpose = A->transpose;\n    B->offset = 0;\n    B->lda = m;\n    B->X_size = X_size;\n    B->X = (double*) malloc(X_size * sizeof(double));\n    matrix_tt_copy_data(B, A);\n\n    return(B);\n}\n\n// NOTE: reshape and submatrix will not work well together.\nvoid matrix_tt_reshape(int m, int n, matrix_tt* A)\n{\n    long new_size = (long) m*n;\n    if (new_size > A->X_size){\n        printf(\"Reshape failed: m*n=%ld is too large for X_size=%ld\\n\", (long) new_size, A->X_size);\n    }\n    else{\n        A->m = m;\n        A->n = n;\n        A->offset = 0;\n        A->lda = m;\n    }\n}\n\n// In matlab notation, returns A[ii1:ii2-1, jj1:jj2-1]\nmatrix_tt* submatrix(const matrix_tt* A, int ii1, int ii2, int jj1, int jj2)\n{\n    int mA = A->m; int nA = A->n; int lda = A->lda;\n    if ((ii1 < 0) || (ii2 < ii1) || (mA < ii2) || (jj1 < 0) || (jj2 < jj1) || (nA < jj2)){\n        printf(\"Cannot take the A[%d:%d,%d:%d] of a %d by %d matrix (Matlab notation)\\n\", ii1, ii2-1, jj1, jj2-1, mA, nA);\n    }\n    matrix_tt* B = (matrix_tt*) malloc(sizeof(matrix_tt));\n\n    B->m = ii2 - ii1;\n    B->n = jj2 - jj1;\n    B->transpose = A->transpose;\n    B->offset = ii1 + jj1*lda;\n    B->lda = lda;\n    B->X_size = A->X_size;\n    B->X = A->X + A->offset;\n\n    return B;\n}\n\n// Updates the indices of the submatrix A\nvoid submatrix_update(matrix_tt* A, int ii1, int ii2, int jj1, int jj2)\n{\n    A->m = ii2 - ii1;\n    A->n = jj2 - jj1;\n    A->offset = ii1 + jj1*(A->lda);\n}\n\n\n// Get an element of the matrix\ndouble matrix_tt_element(const matrix_tt* A, int ii, int jj)\n{\n    return A->X[A->offset + ii + (A->lda)*jj];\n}\n\nvoid matrix_tt_free(matrix_tt* A)\n{\n    free(A->X); A->X = NULL;\n    free(A);\n    return;\n}\n\nvoid matrix_tt_print(const matrix_tt* A, int just_the_matrix)\n{\n    int m = A->m; int n = A->n; int T = A->transpose;\n    int offset = A->offset; int lda = A->lda;\n\n    if (!just_the_matrix){\n        printf(\"Size of matrix: m=%d, n=%d\\n\", m, n);\n        printf(\"Transpose=%d, offset=%d, lda=%d\\n\", T, offset, lda);\n        printf(\"X_size=%ld\\n\", A->X_size);\n        printf(\"X\");\n        if (T){ printf(\"^T\"); }\n        printf(\" is \\n\");\n    }\n\n    int mloop = T ? m : n;\n    int nloop = T ? n : m;\n    printf(\"[\");\n    for (int jj = 0; jj < nloop; ++jj){\n        for (int ii = 0; ii < mloop; ++ii){\n            if (!T){ printf(\"%f\",A->X[lda*ii + jj + offset]); }\n            else{    printf(\"%f\",A->X[lda*jj + ii + offset]); }\n            if (ii < mloop-1){ printf(\", \"); }\n        }\n\n        if (jj == nloop - 1){\n            printf(\"]\\n\");\n        }\n        else{\n            printf(\",\\n \");\n        }\n    }\n}\n\n\ndouble frobenius_norm(matrix_tt* A){\n    double norm = 0;\n    if (A->m == A->lda){\n        norm = cblas_dnrm2(A->m * A->n, A->offset + A->X, 1);\n    }\n    else{\n        for (int ii = 0; ii < A->n; ++ii){\n            double tmp = cblas_dnrm2(A->m, A->offset + (A->lda)*ii + A->X, 1);\n            norm = sqrt(norm*norm + tmp*tmp);\n        }\n    }\n    return norm;\n}\n\n\n\n// Performs the operation C = alpha*A*B + beta*C, where A and B are appropriately transposed\nint matrix_tt_dgemm(const matrix_tt* A, const matrix_tt* B, matrix_tt* C, const double alpha, const double beta)\n{\n    int mA = A->m; int nA = A->n;\n    int mB = B->m; int nB = B->n;\n    int m_check = C->m; int n_check = C->n; int k_check;\n\n    int m; int n; int k;\n    CBLAS_TRANSPOSE TransA;\n    CBLAS_TRANSPOSE TransB;\n    if (A->transpose == 0){\n        TransA = CblasNoTrans;\n        m = mA;\n        k = nA;\n    }\n    else{\n        TransA = CblasTrans;\n        m = nA;\n        k = mA;\n    }\n\n\n    if (B->transpose == 0){\n        TransB = CblasNoTrans;\n        k_check = mB;\n        n = nB;\n    }\n    else{\n        TransB = CblasTrans;\n        k_check = nB;\n        n = mB;\n    }\n\n    if ((m != m_check) || (n != n_check) || (k != k_check)){\n        printf(\"Dimensions of input arrays do not match:\\n\");\n        printf(\"A: m=%d, n=%d, tranpose=%d\\n\",mA,nA,A->transpose);\n        printf(\"B: m=%d, n=%d, tranpose=%d\\n\",mB,nB,B->transpose);\n        printf(\"C: m=%d, n=%d, tranpose=%d\\n\",m_check,n_check,C->transpose);\n        return 1;\n    }\n\n    C->transpose = 0;\n\n    cblas_dgemm(CblasColMajor, TransA, TransB,\n                m, n, k,\n                alpha,\n                A->X + A->offset, A->lda,\n                B->X + B->offset, B->lda,\n                beta,\n                C->X + C->offset, C->lda);\n\n    return 0;\n}\n\n// Solves the least squares problem Ax = b\n// At the end, it just copies the result into x. This probably isn't the most efficient way to do this\nvoid matrix_tt_dgels(matrix_tt* x, matrix_tt* A, const matrix_tt* b)\n{\n    if (x->transpose != 0){\n        printf(\"matrix_tt_least_squares: x cannot be transposed for dgels\\n\");\n        return;\n    }\n\n    if (b->transpose != 0){\n        printf(\"matrix_tt_least_squares: b cannot be transposed for dgels\\n\");\n        return;\n    }\n\n    int nrhs = x->n;\n    char TransA;\n    int m_check;\n    int n_check;\n\n\n    if (A->transpose == 0){\n        TransA = 'N';\n        m_check = A->m;\n        n_check = A->n;\n    }\n    else{\n        TransA = 'T';\n        m_check = A->n;\n        n_check = A->m;\n    }\n\n    if (n_check != x->m){\n        printf(\"right index of A (%d) does not match left index of x (%d)\\n\", n_check, x->m);\n    }\n    if (m_check != b->m){\n        printf(\"left index of A (%d) does not match left index of b (%d)\\n\", m_check, b->m);\n    }\n    if (x->n != b->n){\n        printf(\"right index of x (%d) does not match right index of b (%d)\\n\", x->n, b->n);\n    }\n\n    int m = A->m;\n    int n = A->n;\n\n    int info = LAPACKE_dgels(LAPACK_COL_MAJOR, TransA, m, n, nrhs, A->X + A->offset, A->lda, b->X + b->offset, b->lda);\n\n    matrix_tt* result = submatrix(b, 0, x->m, 0, x->n);\n    matrix_tt_copy_data(x, result);\n    free(result);\n}\n\n\n// Input:\n//   Q - the matrix you want to take the QR\n// Output:\n//   Q - the Q matrix of QR\n//   R - (input is NULL) ? nothing : the R matrix of QR\n\n// NOTE: Currently assumes R and Q are not transposed\nint matrix_tt_truncated_qr(matrix_tt* Q, matrix_tt* R, int r)\n{\n    int Qm = Q->m; int Qn = Q->n; double* QX = Q->X;\n    int Qtranspose = Q->transpose; long Qoffset = Q->offset; int Qlda = Q->lda;\n\n    lapack_int info;\n\n\n    if (Qtranspose == 0){\n        if (r > Qn)\n        {\n            printf(\"ERROR: (matrix_tt_truncated_qr) r = %d is too large for Q->n = %d \\n\", r, Qn);\n            return 1;\n        }\n        // The QR step\n        double* tau = (double*) malloc(sizeof(double)*min(Qm,Qn));\n        info = LAPACKE_dgeqrf(LAPACK_COL_MAJOR, Qm, Qn, QX + Qoffset, Qlda, tau);\n\n        if (R != NULL){\n            int Rm = R->m; int Rn = R->n; double* RX = R->X;\n            int Rtranspose = R->transpose; long Roffset = R->offset; int Rlda = R->lda;\n\n            if ((Rm != r) || (Rn != r)){\n                printf(\"ERROR: (matrix_tt_truncated_qr) R->m = %d or R->n = %d is not equal to r = %d\\n\", Rm, Rn, r);\n                return 1;\n            }\n            if (Rtranspose != 0){\n                printf(\"ERROR: (matrix_tt_truncated_qr) Only defined for R->transpose = 0\\n\");\n                return 1;\n            }\n\n            for (int jj = 0; jj < r; ++jj){\n                int r_col_length = (Qm < jj+1) ? (Qm) : jj+1;\n                memcpy(RX + Roffset + jj*Rlda, QX + Qoffset + jj*Qlda, r_col_length*sizeof(double));\n                memset(RX + Roffset + jj*Rlda + r_col_length, 0, (r-r_col_length)*sizeof(double));\n            }\n        }\n\n        if (r > Qm){\n            LAPACKE_dorgqr(LAPACK_COL_MAJOR, Qm, Qm, Qm, QX + Qoffset, Qlda, tau);\n            matrix_tt* Q_sub = submatrix(Q, 0, Qm, Qm, r);\n            matrix_tt_fill_zeros(Q_sub);\n            free(Q_sub);\n        }\n        else{\n            LAPACKE_dorgqr(LAPACK_COL_MAJOR, Qm, r, r, QX + Qoffset, Qlda, tau);\n        }\n\n        Q->n = r;\n\n        free(tau);       tau = NULL;\n    }\n    else{\n        if (r > Qm)\n        {\n            printf(\"ERROR: (matrix_tt_truncated_qr) r = %d is too large for Q->n = %d \\n\", r, Qn);\n            return 1;\n        }\n        // The LQ step\n        printf(\"Performing LQ\\n\");\n        double* tau = (double*) malloc(sizeof(double)*min(Qm,Qn));\n        info = LAPACKE_dgelqf(LAPACK_COL_MAJOR, Qm, Qn, QX + Qoffset, Qlda, tau);\n        printf(\"\\nRight after LQ, Q = \\n\");\n        matrix_tt_print(Q, 1);\n\n        if (R != NULL){\n            int Rm = R->m; int Rn = R->n; double* RX = R->X;\n            int Rtranspose = R->transpose; long Roffset = R->offset; int Rlda = R->lda;\n\n            if ((Rm != r) || (Rn != r)){\n                printf(\"ERROR: (matrix_tt_truncated_qr) R->m = %d or R->n = %d is not equal to r = %d\\n\", Rm, Rn, r);\n                return 1;\n            }\n            if (Rtranspose == 0){\n                printf(\"ERROR: (matrix_tt_truncated_qr) Only defined for R->transpose = Q->transpose\\n\");\n                return 1;\n            }\n\n            int ncols = (r > Qm) ? Qm : r;\n            for (int jj = 0; jj < r; ++jj){\n                if (jj < Qm){\n                    memcpy(RX + Roffset + jj*Rlda + jj, QX + Qoffset + jj*Qlda + jj, (Qm - jj)*sizeof(double));\n                    memset(RX + Roffset + jj*Rlda, 0, jj*sizeof(double));\n                }\n            }\n\n        }\n\n        if (r > Qn){\n            printf(\"Doing first dorglq\\n\");\n            LAPACKE_dorglq(LAPACK_COL_MAJOR, Qn, Qn, Qn, QX + Qoffset, Qlda, tau);\n            matrix_tt* Q_sub = submatrix(Q, Qn, r, 0, Qn);\n            matrix_tt_fill_zeros(Q_sub);\n            free(Q_sub);\n        }\n        else{\n            printf(\"Doing second dorglq\\n\");\n            LAPACKE_dorglq(LAPACK_COL_MAJOR, Qm, Qn, Qm, QX + Qoffset, Qlda, tau);\n        }\n\n        Q->m = r;\n\n        free(tau);       tau = NULL;\n    }\n\n    return 0;\n}/**/\n\nvoid matrix_tt_group_reduce(MPI_Comm comm, int rank, matrix_tt* A, matrix_tt* buf, int head, int* group_ranks, int nranks)\n{\n    int in_the_group = 0;\n    for (int ii = 0; ii < nranks; ++ii){\n        if (rank == group_ranks[ii]){\n            in_the_group = 1;\n        }\n    }\n\n    if (in_the_group){\n        int buf_assigned = 0;\n        if (!buf){\n            buf_assigned = 1;\n            buf = matrix_tt_init(A->m, A->n);\n        }\n\n        if ((buf->m < A->m) || (buf->n < A->n)){\n            printf(\"buf (%d x %d) must be larger than A (%d x %d)\\n\", buf->m, buf->n, A->m, A->n);\n        }\n\n        int send = -1;\n        int recv = -1;\n        while (nranks > 1){\n            int half_nranks = (nranks + 1) / 2;\n            for (int ii = 0; ii < half_nranks; ++ii){\n                if (ii + half_nranks >= nranks){\n                    recv = group_ranks[ii];\n                    send = -1;\n                }\n                else if (group_ranks[ii + half_nranks] == head){\n                    recv = head;\n                    send = group_ranks[ii];\n                }\n                else{\n                    recv = group_ranks[ii];\n                    send = group_ranks[ii + half_nranks];\n                }\n\n                if (rank == send){\n                    matrix_tt_send(comm, A, recv);\n                }\n                else if ((rank == recv) && (send != -1)){\n                    matrix_tt_recv(comm, buf, send);\n                    for (int jj = 0; jj < A->n; ++jj){\n//                        MPI_Recv(buf->X + buf->offset, A->m, MPI_DOUBLE, send, 0, comm, MPI_STATUS_IGNORE);\n                        long A_offset = A->offset + jj * (A->lda);\n                        long buf_offset = buf->offset +  jj * (buf->lda);\n                        for (int kk = 0; kk < A->m; ++kk){\n                            A->X[A_offset + kk] = A->X[A_offset + kk] + buf->X[buf_offset + kk];\n                        }\n                    }\n                }\n                group_ranks[ii] = recv;\n            }\n            nranks = half_nranks;\n        }\n\n        if (buf_assigned){\n            matrix_tt_free(buf);\n        }\n    }\n\n}\n\n\n// buf just has to be size A->lda x 1 or more\nvoid matrix_tt_reduce(MPI_Comm comm, int rank, matrix_tt* A, matrix_tt* buf, int head)\n{\n    if (buf == NULL){\n        matrix_tt* buf = matrix_tt_init(A->m, 1);\n        matrix_tt_reduce(comm, rank, A, buf, head);\n        matrix_tt_free(buf);\n    }\n    else{\n        int size;\n        MPI_Comm_size(comm, &size);\n\n        if ((head < 0) || (head >= size)){\n            printf(\"matrix_tt_reduce: head = %d is not a valid rank for size = %d\\n\", head, size);\n        }\n\n        if (buf->lda < A->m){\n            printf(\"buf->lda = %d must be larger than A->m = %d\\n\", buf->lda, A->m);\n        }\n\n        int* activated_ranks = (int*) calloc(size, sizeof(int));\n        for (int ii = 0; ii < size; ++ii){\n            activated_ranks[ii] = ii;\n        }\n        int send = -1;\n        int recv = -1;\n        while (size > 1){\n            int half_size = (size + 1) / 2;\n            for (int ii = 0; ii < half_size; ++ii){\n                if (ii + half_size >= size){\n                    recv = activated_ranks[ii];\n                    send = -1;\n                }\n                else if (activated_ranks[ii + half_size] == head){\n                    recv = head;\n                    send = activated_ranks[ii];\n                }\n                else{\n                    recv = activated_ranks[ii];\n                    send = activated_ranks[ii + half_size];\n                }\n\n                if (rank == send){\n                    for (int jj = 0; jj < A->n; ++jj){\n                        MPI_Send(A->X + A->offset + A->lda * jj, A->m, MPI_DOUBLE, recv, 0, comm);\n                    }\n                }\n                else if ((rank == recv) && (send != -1)){\n                    for (int jj = 0; jj < A->n; ++jj){\n                        MPI_Recv(buf->X + buf->offset, A->m, MPI_DOUBLE, send, 0, comm, MPI_STATUS_IGNORE);\n                        long A_offset = A->offset + jj * (A->lda);\n                        for (int kk = 0; kk < A->m; ++kk){\n                            A->X[A_offset + kk] = A->X[A_offset + kk] + buf->X[buf->offset + kk];\n                        }\n                    }\n                }\n                activated_ranks[ii] = recv;\n            }\n            size = half_size;\n        }\n        free(activated_ranks);\n    }\n}\n\nvoid matrix_tt_allreduce(MPI_Comm comm, matrix_tt* A)\n{\n    for (int jj = 0; jj < A->n; ++jj){\n        MPI_Allreduce(MPI_IN_PLACE, A->X + A->offset + jj*(A->lda), A->m, MPI_DOUBLE, MPI_SUM, comm);\n    }\n}\n\nvoid matrix_tt_broadcast(MPI_Comm comm, matrix_tt* buf)\n{\n    int count = buf->m * buf->n;\n    MPI_Bcast(buf->X, count, MPI_DOUBLE, HEAD, comm);\n}\n\nvoid matrix_tt_send(MPI_Comm comm, matrix_tt* buf, int dest){\n    MPI_Datatype buf_type;\n    MPI_Type_vector(buf->n, buf->m, buf->lda, MPI_DOUBLE, &buf_type);\n    MPI_Type_commit(&buf_type);\n    MPI_Send(buf->X + buf->offset, 1, buf_type, dest, 0, comm);\n    MPI_Type_free(&buf_type);\n}\n\nvoid matrix_tt_recv(MPI_Comm comm, matrix_tt* buf, int source){\n    MPI_Datatype buf_type;\n    MPI_Type_vector(buf->n, buf->m, buf->lda, MPI_DOUBLE, &buf_type);\n    MPI_Type_commit(&buf_type);\n    MPI_Recv(buf->X + buf->offset, 1, buf_type, source, 0, comm, MPI_STATUS_IGNORE);\n    MPI_Type_free(&buf_type);\n}\n\n// Column khatri-rao product C = A x B\nvoid khatri_rao(const matrix_tt* restrict A, const matrix_tt* restrict B, matrix_tt* restrict C){\n    int n = A->n;\n    int m_A = A->m;\n\n    int n_B = B->n;\n    int m_B = B->m;\n\n    int n_C = C->n;\n    int m_C = C->m;\n\n    if ((n != n_B) || (n != n_C) || (m_A*m_B != m_C)){\n        printf(\"khatri_rao: the sizes dont work!\\n\");\n        printf(\"A is %d x %d\\n\", m_A, n);\n        printf(\"B is %d x %d\\n\", m_B, n_B);\n        printf(\"C is %d x %d\\n\", m_C, n_C);\n    }\n\n    for (int kk = 0; kk < n; ++kk){\n        for (int ii = 0; ii < m_B; ++ii){\n            double Bii = B->X[kk*m_B + ii];\n            for (int jj = 0; jj < m_A; ++jj){\n                C->X[kk*m_C + ii*m_B + jj] = Bii * A->X[kk*m_A + jj];\n            }\n        }\n    }\n}\n\n// Recursively KR multiply the list of matrices A\nvoid list_khatri_rao(int d_kr, matrix_tt** A, matrix_tt* Omega){\n    if (d_kr == 1){\n        for (int ii = 0; ii < A[0]->X_size; ++ii){\n            Omega->X[ii] = A[0]->X[ii];\n        }\n        return;\n    }\n\n    if (d_kr == 2){\n        khatri_rao(A[0], A[1], Omega);\n    }\n    else{\n        int m_B = 1;\n        int n_B = Omega->n;\n        for (int ii = 0; ii < d_kr-1; ++ii){\n            m_B = m_B * A[ii]->m;\n        }\n\n        matrix_tt* B = matrix_tt_init(m_B, n_B);\n        list_khatri_rao(d_kr - 1, A, B);\n        khatri_rao(B, A[d_kr - 1], Omega);\n        matrix_tt_free(B); B = NULL;\n    }\n\n}\n\n\nvoid matrix_tt_dlarnv(matrix_tt* A){\n    int r1 = rand()%4096, r2 = rand()%4096, r3 = rand()%4096, r4 = rand()%4096;\n    int iseed[4] = {r1, r2, r3, r4+(r4%2 == 0?1:0)};\n    LAPACKE_dlarnv(3, iseed, (A->n) * (A->m), A->X);\n}\n\n\nvoid matrix_tt_fill_zeros(matrix_tt* A)\n{\n    for (int jj = 0; jj < A->n; ++jj){\n        memset(A->X + A->offset + jj*A->lda, 0, A->m * sizeof(double));\n    }\n}\n\n// Takes a matrix in row major and transforms it to column major\nvoid row_to_col_major(const matrix_tt* mat_row, matrix_tt* mat_col)\n{\n    int m = mat_col->m;\n    int n = mat_col->n;\n    if ((m != mat_row->n) || (n != mat_row->m)){\n        printf(\"The dimensions don't work out! mat_row should have the dimensions of mat_col transposed\\n\");\n        printf(\"mat_row->m = %d, mat_row->n = %d\\n\", mat_row->m, mat_row->n);\n        printf(\"mat_col->m = %d, mat_col->n = %d\\n\", mat_col->m, mat_col->n);\n    }\n\n    for (int ii = 0; ii < m; ++ii){\n        for (int jj = 0; jj < n; ++jj){\n            mat_col->X[jj * (mat_col->lda) + ii + mat_col->offset] = mat_row->X[ii * (mat_row->lda) + jj + mat_row->offset];\n        }\n    }\n}\n", "meta": {"hexsha": "da3056e2c74e7cf9beb79b1748d71c7e45554294", "size": 20410, "ext": "c", "lang": "C", "max_stars_repo_path": "src/matrix_tt.c", "max_stars_repo_name": "SidShi/Parallel_TT_sketching", "max_stars_repo_head_hexsha": "e2c00c289d75d3ac1df32ed2b95af579a517fcbf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/matrix_tt.c", "max_issues_repo_name": "SidShi/Parallel_TT_sketching", "max_issues_repo_head_hexsha": "e2c00c289d75d3ac1df32ed2b95af579a517fcbf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/matrix_tt.c", "max_forks_repo_name": "SidShi/Parallel_TT_sketching", "max_forks_repo_head_hexsha": "e2c00c289d75d3ac1df32ed2b95af579a517fcbf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5369030391, "max_line_length": 124, "alphanum_fraction": 0.4853993141, "num_tokens": 6462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.399811640739795, "lm_q2_score": 0.04468087440696542, "lm_q1q2_score": 0.01786393370633756}}
{"text": "/* wavelet/gsl_wavelet.h\n * \n * Copyright (C) 2004 Ivo Alxneit\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_WAVELET_H__\n#define __GSL_WAVELET_H__\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS          /* empty */\n# define __END_DECLS            /* empty */\n#endif\n\n__BEGIN_DECLS\n\n#ifndef GSL_DISABLE_DEPRECATED\ntypedef enum {\n  forward = 1, backward = -1,\n  gsl_wavelet_forward = 1, gsl_wavelet_backward = -1\n} \ngsl_wavelet_direction;\n#else\ntypedef enum {\n  gsl_wavelet_forward = 1, gsl_wavelet_backward = -1\n} \ngsl_wavelet_direction;\n#endif\n\ntypedef struct\n{\n  const char *name;\n  int (*init) (const double **h1, const double **g1,\n               const double **h2, const double **g2, size_t * nc,\n               size_t * offset, size_t member);\n}\ngsl_wavelet_type;\n\ntypedef struct\n{\n  const gsl_wavelet_type *type;\n  const double *h1;\n  const double *g1;\n  const double *h2;\n  const double *g2;\n  size_t nc;\n  size_t offset;\n}\ngsl_wavelet;\n\ntypedef struct\n{\n  double *scratch;\n  size_t n;\n}\ngsl_wavelet_workspace;\n\nGSL_VAR const gsl_wavelet_type *gsl_wavelet_daubechies;\nGSL_VAR const gsl_wavelet_type *gsl_wavelet_daubechies_centered;\nGSL_VAR const gsl_wavelet_type *gsl_wavelet_haar;\nGSL_VAR const gsl_wavelet_type *gsl_wavelet_haar_centered;\nGSL_VAR const gsl_wavelet_type *gsl_wavelet_bspline;\nGSL_VAR const gsl_wavelet_type *gsl_wavelet_bspline_centered;\n\ngsl_wavelet *gsl_wavelet_alloc (const gsl_wavelet_type * T, size_t k);\nvoid gsl_wavelet_free (gsl_wavelet * w);\nconst char *gsl_wavelet_name (const gsl_wavelet * w);\n\ngsl_wavelet_workspace *gsl_wavelet_workspace_alloc (size_t n);\nvoid gsl_wavelet_workspace_free (gsl_wavelet_workspace * work);\n\nint gsl_wavelet_transform (const gsl_wavelet * w, \n                           double *data, size_t stride, size_t n,\n                           gsl_wavelet_direction dir, \n                           gsl_wavelet_workspace * work);\n\nint gsl_wavelet_transform_forward (const gsl_wavelet * w, \n                                   double *data, size_t stride, size_t n, \n                                   gsl_wavelet_workspace * work);\n\nint gsl_wavelet_transform_inverse (const gsl_wavelet * w, \n                                    double *data, size_t stride, size_t n, \n                                    gsl_wavelet_workspace * work);\n\n__END_DECLS\n\n#endif /* __GSL_WAVELET_H__ */\n", "meta": {"hexsha": "fde012cd30107997ad6eecf7aca32493871d991c", "size": 3211, "ext": "h", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/wavelet/gsl_wavelet.h", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/wavelet/gsl_wavelet.h", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/wavelet/gsl_wavelet.h", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 29.4587155963, "max_line_length": 81, "alphanum_fraction": 0.7047648708, "num_tokens": 829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.036220058465835675, "lm_q1q2_score": 0.01782708305199788}}
{"text": "\ufeff// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n#pragma once\n\n#include <memory>\n#include <vector>\n#include <gsl/span>\n#include <map>\n\n#include <Eigen/Geometry>\n\nnamespace mage\n{\n    struct BundlerParameters\n    {\n        bool  ArePointsFixed{ false };        // True if map points should not be optimized\n    };\n\n    class BundlerLib\n    {\n    public:\n        BundlerLib(const BundlerParameters& bundlerParameters);\n        ~BundlerLib();\n\n        void AllocateCameras(size_t count);\n\n        void SetCameraPose(size_t idx,\n            Eigen::Map<const Eigen::Vector3f> position,\n            Eigen::Map<const Eigen::Matrix3f> orientation,\n            Eigen::Map<const Eigen::Vector4f> intrinsics, bool isFixed);\n\n        void FixCameraPose(size_t idx, bool value);\n\n        void AllocateMapPoints(size_t count);\n        void SetMapPoint(size_t idx, Eigen::Map<const Eigen::Vector3f> point);\n\n        void AllocateObservations(size_t count);\n        void SetObservation(size_t idx, Eigen::Map<const Eigen::Vector2f> position, size_t cameraIndex, size_t mapPointIndex, float informationMatrixScalar);\n\n        void AllocateFixedDistanceConstraints(size_t count);\n        void SetFixedDistanceConstraint(size_t idx, size_t cameraIndex1, size_t cameraIndex2, float distance = 1.0f, float weight = 1.0f);\n\n        void AllocateRelativeRotationConstraints(size_t count);\n        void SetRelativeRotationConstraint(size_t idx, size_t cameraIndex1, size_t cameraIndex2, const Eigen::Quaternionf& deltaRotation, float weight = 1.0f);\n\n        void AllocateRelativeTransformConstraints(size_t count);\n        void SetRelativeTransformConstraint(size_t idx, size_t cameraIndex1, size_t cameraIndex2, Eigen::Map<const Eigen::Vector3f> deltaPosition, const Eigen::Quaternionf& deltaRotation, float weight);\n\n        void SetCurrentLambda(float userLambda);\n        float GetCurrentLambda() const;\n\n        // Runs an iteration of the solver for each provided Huber width.\n        // Return the average square error.\n        float StepBundleAdjustment(gsl::span<const float> huberWidthPerIteration, float maxErrorSquare, std::vector<unsigned int>& outliers);\n\n        void GetPose(size_t idx, Eigen::Map<Eigen::Vector3f> position, Eigen::Map<Eigen::Matrix3f> orientation) const;\n        void GetPoint(size_t idx, Eigen::Map<Eigen::Vector3f> position) const;\n\n    private:\n        struct Impl;\n        const std::unique_ptr<Impl> m_impl;\n\n        // Description of the problem to optimize from the calling code.\n        BundlerParameters m_bundlerParameters;\n    };\n}\n", "meta": {"hexsha": "0dfcc2b51c6399aa2562f675eec1d0695d928764", "size": 2582, "ext": "h", "lang": "C", "max_stars_repo_path": "Dependencies/BundlerLib/Include/BundlerLib.h", "max_stars_repo_name": "syntheticmagus/mageslam", "max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z", "max_issues_repo_path": "Dependencies/BundlerLib/Include/BundlerLib.h", "max_issues_repo_name": "syntheticmagus/mageslam", "max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z", "max_forks_repo_path": "Dependencies/BundlerLib/Include/BundlerLib.h", "max_forks_repo_name": "syntheticmagus/mageslam", "max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z", "avg_line_length": 37.9705882353, "max_line_length": 202, "alphanum_fraction": 0.7091402014, "num_tokens": 584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.03622005833579263, "lm_q1q2_score": 0.017827082987992234}}
{"text": "/* -*- mode: C; c-basic-offset: 4 -*- */\n/* ex: set shiftwidth=4 tabstop=4 expandtab: */\n/*\n * Copyright (c) 2013, Georgia Tech Research Corporation\n * Copyright (c) 2015, Rice University\n * Copyright (c) 2018-2019, Colorado School of Mines\n * All rights reserved.\n *\n * Author(s): Neil T. Dantam <ntd@gatech.edu>\n * Georgia Tech Humanoid Robotics Lab\n * Under Direction of Prof. Mike Stilman <mstilman@cc.gatech.edu>\n *\n *\n * This file is provided under the following \"BSD-style\" License:\n *\n *\n *   Redistribution and use in source and binary forms, with or\n *   without modification, are permitted provided that the following\n *   conditions are met:\n *\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *\n *   * Redistributions in binary form must reproduce the above\n *     copyright notice, this list of conditions and the following\n *     disclaimer in the documentation and/or other materials provided\n *     with the distribution.\n *\n *   * Neither the name of the Rice University nor the names of its\n *     contributors may be used to endorse or promote products derived\n *     from this software without specific prior written permission.\n *\n *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND\n *   CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n *   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n *   MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n *   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n *   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n *   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n *   AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n *   LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n *   ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *   POSSIBILITY OF SUCH DAMAGE.\n *\n */\n\n#include <nlopt.h>\n#include \"amino.h\"\n#include \"amino/diffeq.h\"\n\n\n\n/* static double */\n/* s_nlobj_jpinv(unsigned n, const double *q, double *dq, void *vcx) */\n/* { */\n/*     struct kin_solve_cx *cx = (struct kin_solve_cx*)vcx; */\n/*     void *ptrtop = aa_mem_region_ptr(cx->reg); */\n\n/*     struct aa_dvec vq = AA_DVEC_INIT(n,(double*)q,1); */\n/*     aa_rx_fk_sub(cx->fk, cx->ssg, &vq); */\n/*     double *E_act = aa_rx_fk_ref(cx->fk, cx->frame); */\n\n\n/*     if( dq ) { */\n/*         struct aa_dvec v_dq = AA_DVEC_INIT(n,dq,1); */\n/*         s_ksol_jpinv(cx,q, &v_dq); */\n/*         aa_dvec_scal(-1,&v_dq); */\n/*     } */\n\n/*     double x = s_serr( E_act, cx->TF_ref->data ); */\n\n/*     aa_mem_region_pop(cx->reg, ptrtop); */\n/*     return x; */\n\n/* } */\n\nstatic double s_nlobj_dq_fd_helper( void *vcx, const struct aa_dvec *x)\n{\n    struct kin_solve_cx *cx = (struct kin_solve_cx*)vcx;\n    void *ptrtop = aa_mem_region_ptr(cx->reg);\n    assert(1 == x->inc);\n\n    aa_rx_fk_sub(cx->fk, cx->ssg, x);\n    double *E_act = aa_rx_fk_ref(cx->fk, cx->frame);\n\n    double S_act[8], S_ref[8], S_err[8], S_ln[8];\n    aa_tf_qutr2duqu(E_act, S_act);\n    aa_tf_qutr2duqu(cx->TF_ref->data, S_ref);\n    aa_tf_duqu_cmul(S_act,S_ref,S_err);\n    aa_tf_duqu_minimize(S_err);\n    aa_tf_duqu_ln(S_err, S_ln);\n    double result = aa_la_dot(8,S_ln,S_ln);\n\n    aa_mem_region_pop(cx->reg, ptrtop);\n    return result;\n}\n\nAA_API double\naa_rx_ik_opt_err_dqln_fd( void *vcx, const double *q, double *dq )\n{\n    struct kin_solve_cx *cx = (struct kin_solve_cx*)vcx;\n    size_t n = aa_rx_sg_sub_config_count(cx->ssg);\n\n    struct aa_dvec vq = AA_DVEC_INIT(n,(double*)q,1);\n    double x = s_nlobj_dq_fd_helper(vcx, &vq);\n\n    if( dq ) {\n        struct aa_dvec vdq = AA_DVEC_INIT(n,dq,1);\n        // TODO: make epsilon a parameter\n        double eps = 1e-6;\n        aa_de_grad_fd( s_nlobj_dq_fd_helper, vcx,\n                       &vq, eps, &vdq );\n    }\n\n    return x;\n}\n\nstatic void\nmv_block_helper (const double *A, const double *x, double *y)\n{\n    cblas_dgemv(CblasColMajor, CblasTrans, 8, 4,\n                1, A, 8, x, 1,\n                0, y, 1);\n    cblas_dgemv(CblasColMajor, CblasTrans, 4, 4,\n                1, A, 8, x+4, 1,\n                0, y+4, 1);\n}\n\nstatic void\nduqu_rmul_helper( const double *Sr, const double *x, double *y )\n{\n    double M[8*8];\n    aa_tf_duqu_matrix_r(Sr,M,8);\n    mv_block_helper(M, x, y);\n}\n\n\nAA_API double\naa_rx_ik_opt_err_dqln( void *vcx, double *q, double *dq ) {\n    struct kin_solve_cx *cx = (struct kin_solve_cx*)vcx;\n    void *ptrtop = aa_mem_region_ptr(cx->reg);\n\n    size_t n = aa_rx_sg_sub_config_count(cx->ssg);\n    struct aa_dvec vq = AA_DVEC_INIT(n,(double*)q,1);\n    aa_rx_fk_sub(cx->fk, cx->ssg, &vq );\n    double *E_act = aa_rx_fk_ref(cx->fk, cx->frame);\n\n\n    double S_act[8], S_ref[8], S_err[8], S_ln[8];\n    aa_tf_qutr2duqu(E_act, S_act);\n    aa_tf_qutr2duqu(cx->TF_ref->data, S_ref);\n    aa_tf_duqu_cmul(S_act,S_ref,S_err);\n    // Apply a negative factor in gradient when we have to minimze the\n    // error quaternion\n    int needs_min = (S_err[AA_TF_DUQU_REAL_W] < 0 );\n    if( needs_min ) {\n        for( size_t i = 0; i < 8; i ++ ) S_err[i] *= -1;\n    } else {\n    }\n    aa_tf_duqu_ln(S_err, S_ln);\n    double result = aa_la_dot(8,S_ln,S_ln);\n\n    if( dq ) {\n        if( needs_min ) {\n            for( size_t i = 0; i < 8; i ++ ) S_ln[i] *= -1;\n        }\n        struct aa_dvec v_dq = AA_DVEC_INIT(n,dq,1);\n\n        /*\n         * g_sumsq * J_ln*[S_ref]_r*J_conj*J_S\n         * -> J_ln^T g_sumsq * [S_ref]_r*J_conj*J_S\n         * -> [S_ref]_r^T (J_ln^T g_sumsq) *J_conj*J_S\n         * -> J_conj^T*[S_ref]_r^T (J_ln^T g_sumsq) * J_S\n         * -> J_S^T J_conj^T * [S_ref]_r^T * J_ln^T g_sumsq\n         */\n\n        double a[8], b[8], dJ[8*8];\n        struct aa_dmat vJ_8x8 = AA_DMAT_INIT(8,8,dJ,8);\n        struct aa_dmat *J_8x8 = &vJ_8x8;\n\n        {\n            struct aa_dmat *J_ln = J_8x8;\n            aa_tf_duqu_ln_jac(S_err,J_ln);\n            /*\n             *  struct aa_dvec v_S_ln = AA_DVEC_INIT(8,S_ln,1);\n             * //aa_dmat_gemv( CblasTrans, 2, J_8x8, &v_S_ln, 0, &va );\n             *\n             * Avoid multiplying by the zero block:\n             *\n             * J_ln = [J_r   0]     J_ln^T = [J_r^T J_d^T]\n             *        [J_d J_r]              [  0   J_r^T]\n             *\n             * J_ln^T * del(S_ln^T*S_ln)^T = 2*J_ln^T S_ln\n             *\n             * 2*J_ln^T S_ln = 2*[J_r^T  J_d^T] (S_ln_r)\n             *                   [   0   J_r^T] (S_ln_d)\n             *\n             */\n            mv_block_helper(dJ, S_ln, a);\n        }\n\n\n        /*\n         * dS/dphi = [S]_R V J\n         * g [S]_R V J\n         * -> [S]_R^T g V J\n         * -> V^T [S]_R^T g J\n         * -> J^T V [S]_R^T g\n         */\n\n        duqu_rmul_helper( S_ref, a, b );\n        aa_tf_duqu_conj1(b);\n\n        duqu_rmul_helper( S_act, b, a );  /* TODO: Pure result, some\n                                           * extra multiplies here. */\n        // a is now a pure dual quaternion\n        {\n            double c[6];\n            struct aa_dvec vc = AA_DVEC_INIT(6,c,1);\n            // Using Twist Jacobian\n            aa_tf_duqu2pure(a,c);\n            struct aa_dmat *Jtw = aa_rx_sg_sub_jac_twist_get(cx->ssg, cx->reg, cx->fk);\n            aa_dmat_gemv( CblasTrans, 1, Jtw, &vc, 0, &v_dq );\n\n            // Using Velocity Jacobian\n            /* aa_tf_cross_a(a+AA_TF_DUQU_DUAL_XYZ,E_act+AA_TF_QUTR_V,a); */\n            /* aa_tf_duqu2pure(a,c); */\n            /* struct aa_dmat *J_vel = aa_rx_sg_sub_get_jacobian(cx->ssg,cx->reg,cx->TF); */\n            /* aa_dmat_gemv( CblasTrans, 1, J_vel, &vc, 0, &v_dq ); */\n\n        }\n\n\n        /* { */\n        /*     struct aa_dvec *v_dq_fd = aa_dvec_alloc(cx->reg,n); */\n        /*     double eps = 1e-6; */\n        /*     aa_de_grad_fd( s_nlobj_dq_fd_helper, vcx, */\n        /*                    &vq, eps, v_dq_fd ); */\n\n\n        /*     printf(\"--\\n\"); */\n        /*     printf(\"needs min: %d\\n\", needs_min); */\n        /*     printf(\"ad: \"); */\n        /*     aa_dump_vec(stdout,v_dq_fd->data,n); */\n        /*     printf(\"an: \"); */\n        /*     aa_dump_vec(stdout,dq,n); */\n\n        /*     assert( aa_dvec_ssd(v_dq_fd, &v_dq) < 1e-3 ); */\n        /* } */\n    }\n\n    aa_mem_region_pop(cx->reg, ptrtop);\n    return result;\n}\n\nstatic double s_nlobj_qv_fd_trans_helper( void *vcx, const struct aa_dvec *x)\n{\n    struct kin_solve_cx *cx = (struct kin_solve_cx*)vcx;\n    assert(1 == x->inc);\n\n    aa_rx_fk_sub(cx->fk, cx->ssg, x);\n    double *E_act = aa_rx_fk_ref(cx->fk, cx->frame);\n    double *v_act = E_act + AA_TF_QUTR_V;\n\n    double *E_ref = cx->TF_ref->data;\n    double *v_ref = E_ref + AA_TF_QUTR_V;\n\n    double E_err[7];\n    double *v_err = E_err + AA_TF_QUTR_V;\n\n\n    for(size_t i = 0; i < 3; i ++ ) v_err[i] = v_act[i] - v_ref[i];\n\n    double result = aa_tf_vdot(v_err,v_err);\n\n    return result;\n}\n\nAA_API double\naa_rx_ik_opt_err_trans_fd( void *vcx, const double *q, double *dq )\n{\n    struct kin_solve_cx *cx = (struct kin_solve_cx*)vcx;\n    size_t n = aa_rx_sg_sub_config_count(cx->ssg);\n\n    struct aa_dvec vq = AA_DVEC_INIT(n,(double*)q,1);\n    double x = s_nlobj_qv_fd_trans_helper(vcx, &vq);\n\n    if( dq ) {\n        struct aa_dvec vdq = AA_DVEC_INIT(n,dq,1);\n        // TODO: make epsilon a parameter\n        double eps = 1e-6;\n        aa_de_grad_fd( s_nlobj_qv_fd_trans_helper, vcx,\n                       &vq, eps, &vdq );\n    }\n    /* fprintf(stdout, \"fd error: %2.2f\\n\", x);  */\n    return x;\n}\n\nstatic double s_nlobj_qv_fd_helper( void *vcx, const struct aa_dvec *x)\n{\n    struct kin_solve_cx *cx = (struct kin_solve_cx*)vcx;\n    void *ptrtop = aa_mem_region_ptr(cx->reg);\n    assert(1 == x->inc);\n\n    aa_rx_fk_sub(cx->fk, cx->ssg, x);\n    double *E_act = aa_rx_fk_ref(cx->fk, cx->frame);\n    double *v_act = E_act + AA_TF_QUTR_V;\n    double *q_act = E_act + AA_TF_QUTR_Q;\n\n    double *E_ref = cx->TF_ref->data;\n    double *v_ref = E_ref + AA_TF_QUTR_V;\n    double *q_ref = E_ref + AA_TF_QUTR_Q;\n\n    double E_err[7];\n    double *v_err = E_err + AA_TF_QUTR_V;\n    double *q_err = E_err + AA_TF_QUTR_Q;\n\n    aa_tf_qcmul(q_act,q_ref,q_err);\n\n    double q_ln[4];\n    aa_tf_qminimize(q_err);\n    aa_tf_duqu_ln(q_err, q_ln);\n\n    for(size_t i = 0; i < 3; i ++ ) v_err[i] = v_act[i] - v_ref[i];\n\n    double result = ( aa_tf_qdot(q_ln,q_ln)\n                      +\n                      aa_tf_vdot(v_err,v_err) );\n\n    aa_mem_region_pop(cx->reg, ptrtop);\n    return result;\n}\n\n\nAA_API double\naa_rx_ik_opt_err_qlnpv_fd( void *vcx, const double *q, double *dq )\n{\n    struct kin_solve_cx *cx = (struct kin_solve_cx*)vcx;\n    size_t n = aa_rx_sg_sub_config_count(cx->ssg);\n\n    struct aa_dvec vq = AA_DVEC_INIT(n,(double*)q,1);\n    double x = s_nlobj_qv_fd_helper(vcx, &vq);\n\n    if( dq ) {\n        struct aa_dvec vdq = AA_DVEC_INIT(n,dq,1);\n        // TODO: make epsilon a parameter\n        double eps = 1e-6;\n        aa_de_grad_fd( s_nlobj_qv_fd_helper, vcx,\n                       &vq, eps, &vdq );\n    }\n\n    return x;\n}\n\nAA_API double\naa_rx_ik_opt_err_trans( void *vcx, const double *q, double *dq )\n{\n    struct kin_solve_cx *cx = (struct kin_solve_cx*)vcx;\n    void *ptrtop = aa_mem_region_ptr(cx->reg);\n\n    size_t n = aa_rx_sg_sub_config_count(cx->ssg);\n    struct aa_dvec vq = AA_DVEC_INIT(n,(double*)q,1);\n    aa_rx_fk_sub(cx->fk, cx->ssg, &vq );\n\n    double *E_act = aa_rx_fk_ref(cx->fk, cx->frame);\n    double *v_act = E_act + AA_TF_QUTR_V;\n\n    double *E_ref = cx->TF_ref->data;\n    double *v_ref = E_ref + AA_TF_QUTR_V;\n\n    double E_err[7];\n    double *v_err = E_err + AA_TF_QUTR_V;\n\n    // Apply a negative factor in gradient when we have to minimze the\n    // error quaternion\n\n\n    for(size_t i = 0; i < 3; i ++ ) v_err[i] = v_act[i] - v_ref[i];\n\n    double result = aa_tf_vdot(v_err,v_err);\n\n    if( dq ) {\n\n        struct aa_dvec v_dq = AA_DVEC_INIT(n,dq,1);\n\n        struct aa_dmat *Jvel = aa_rx_sg_sub_jac_vel_get(cx->ssg, cx->reg, cx->fk);\n        struct aa_dmat Jr, Jv;\n        aa_dmat_view_block(&Jv, Jvel, AA_TF_DX_V, 0, 3, Jvel->cols);\n        aa_dmat_view_block(&Jr, Jvel, AA_TF_DX_W, 0, 3, Jvel->cols);\n\n        // Translational Part\n        struct aa_dvec v_v_err = AA_DVEC_INIT(3,v_err,1);\n        aa_dmat_gemv(CblasTrans, 2, &Jv, &v_v_err, 0, &v_dq);\n    }\n\n    aa_mem_region_pop(cx->reg, ptrtop);\n    /* printf(\"err: %f\\n\", result); */\n    return result;\n}\n\nstatic void\nq_rmul_helper( const double *q, const struct aa_dvec *x, struct aa_dvec *y )\n{\n    double dM[4*4];\n    struct aa_dmat M = AA_DMAT_INIT(4,4,dM,4);\n    aa_tf_qmat_r(q,&M);\n    aa_dmat_gemv(CblasTrans, 1, &M, x, 0, y);\n}\n\n\nAA_API double\naa_rx_ik_opt_err_qlnpv( void *vcx, const double *q, double *dq )\n{\n    struct kin_solve_cx *cx = (struct kin_solve_cx*)vcx;\n    void *ptrtop = aa_mem_region_ptr(cx->reg);\n\n    size_t n = aa_rx_sg_sub_config_count(cx->ssg);\n    struct aa_dvec vq = AA_DVEC_INIT(n,(double*)q,1);\n    aa_rx_fk_sub(cx->fk, cx->ssg, &vq );\n\n    double *E_act = aa_rx_fk_ref(cx->fk, cx->frame);\n    double *v_act = E_act + AA_TF_QUTR_V;\n    double *q_act = E_act + AA_TF_QUTR_Q;\n\n    double *E_ref = cx->TF_ref->data;\n    double *v_ref = E_ref + AA_TF_QUTR_V;\n    double *q_ref = E_ref + AA_TF_QUTR_Q;\n\n    double E_err[7];\n    double *v_err = E_err + AA_TF_QUTR_V;\n    double *q_err = E_err + AA_TF_QUTR_Q;\n\n    aa_tf_qcmul(q_act,q_ref,q_err);\n\n    // Apply a negative factor in gradient when we have to minimze the\n    // error quaternion\n    int needs_min = (E_err[AA_TF_QUAT_W] < 0 );\n    if( needs_min ) {\n        for( size_t i = 0; i < 4; i ++ ) E_err[i] *= -1;\n    }\n\n    double q_ln[4];\n    aa_tf_qln(E_err, q_ln);\n\n    for(size_t i = 0; i < 3; i ++ ) v_err[i] = v_act[i] - v_ref[i];\n\n    double result = ( aa_tf_qdot(q_ln,q_ln) +\n                      + aa_tf_vdot(v_err,v_err) );\n\n    if( dq ) {\n\n        struct aa_dvec v_dq = AA_DVEC_INIT(n,dq,1);\n\n        struct aa_dmat *Jvel = aa_rx_sg_sub_jac_vel_get(cx->ssg, cx->reg, cx->fk);\n        struct aa_dmat Jr, Jv;\n        aa_dmat_view_block(&Jv, Jvel, AA_TF_DX_V, 0, 3, Jvel->cols);\n        aa_dmat_view_block(&Jr, Jvel, AA_TF_DX_W, 0, 3, Jvel->cols);\n\n        // Translational Part\n        struct aa_dvec v_v_err = AA_DVEC_INIT(3,v_err,1);\n        aa_dmat_gemv(CblasTrans, 2, &Jv, &v_v_err, 0, &v_dq);\n\n        // Rotational Part\n        if( needs_min ) {\n            for( size_t i = 0; i < 4; i ++ ) q_ln[i] *= -1;\n        }\n\n        double a[4], b[4], dJ[4*4];\n        struct aa_dvec va = AA_DVEC_INIT(4,a,1);\n        struct aa_dvec vb = AA_DVEC_INIT(4,b,1);\n        struct aa_dvec vln = AA_DVEC_INIT(4,q_ln,1);\n        struct aa_dmat vJ_4x4 = AA_DMAT_INIT(4,4,dJ,4);\n        struct aa_dmat *J_4x4 = &vJ_4x4;\n\n        {\n            struct aa_dmat *J_ln = J_4x4;\n            aa_tf_qln_jac(q_err,J_ln);\n            aa_dmat_gemv(CblasTrans, 1, J_ln, &vln, 0, &va);\n        }\n\n        q_rmul_helper( q_ref, &va, &vb );\n        aa_tf_qconj1(b);\n\n        q_rmul_helper( q_act, &vb, &va ); /* TODO: Pure result, some\n                                           * extra multiplies here. */\n\n        // a is now a pure dual quaternion */\n        {\n            struct aa_dvec va3 = AA_DVEC_INIT(3,a,1);\n            aa_dmat_gemv( CblasTrans, 1, &Jr, &va3, 1, &v_dq );\n        }\n\n\n        /* { */\n        /*     struct aa_dvec *v_dq_fd = aa_dvec_alloc(cx->reg,n); */\n        /*     double eps = 1e-6; */\n        /*     aa_de_grad_fd( s_nlobj_qv_fd_helper, vcx, */\n        /*                    &vq, eps, v_dq_fd ); */\n\n\n        /*     printf(\"--\\n\"); */\n        /*     printf(\"needs min: %d\\n\", needs_min); */\n        /*     printf(\"ad: \"); */\n        /*     aa_dump_vec(stdout,v_dq_fd->data,n); */\n        /*     printf(\"an: \"); */\n        /*     aa_dump_vec(stdout,dq,n); */\n\n        /*     assert( aa_dvec_ssd(v_dq_fd, &v_dq) < 1e-3 ); */\n        /* } */\n    }\n\n    aa_mem_region_pop(cx->reg, ptrtop);\n    //printf(\"err: %f\\n\", result);\n    return result;\n}\n\n\n// TODO: weighted error\n\nAA_API double\naa_rx_ik_opt_err_jcenter( void *vcx, const double *q, double *dq )\n{\n    struct kin_solve_cx *cx = (struct kin_solve_cx*)vcx;\n    struct aa_mem_region *reg = cx->reg;\n    void *ptrtop = aa_mem_region_ptr(reg);\n\n    size_t n = aa_rx_sg_sub_config_count(cx->ssg);\n    struct aa_dvec *q_center = aa_dvec_alloc(reg,n);\n    aa_rx_sg_sub_center_configv(cx->ssg,q_center);\n\n    double result = 0;\n\n    if( dq ) { // error and gradient\n        for( size_t i = 0; i < n; i ++ ) {\n            double d = q[i] - AA_DVEC_REF(q_center,i);\n            result += (d*d);\n            dq[i] = d;\n        }\n        //printf(\"--\\n\");\n        //printf(\"q:  \"); aa_dump_vec(stdout,q,n);\n        //printf(\"qc: \"); aa_dump_vec(stdout,q_center->data,n);\n        //printf(\"dq: \"); aa_dump_vec(stdout,dq,n);\n    } else { // error only\n        for( size_t i = 0; i < n; i ++ ) {\n            double d = q[i] - AA_DVEC_REF(q_center,i);\n            result += (d*d);\n        }\n    }\n\n    aa_mem_region_pop(cx->reg, ptrtop);\n\n    return result / 2;\n}\n\nstruct err_cx {\n    void *cx;\n    aa_rx_ik_opt_fun *fun;\n};\n\nstatic double\ns_err_cx_dispatch(unsigned n, const double *q, double *dq, void *vcx)\n{\n    (void)n;\n    struct err_cx *cx = (struct err_cx *)vcx;\n    return cx->fun(cx->cx, q, dq);\n}\n\nstatic int\ns_ik_nlopt( struct kin_solve_cx *cx,\n            struct aa_dvec *q )\n{\n    struct aa_mem_region *reg = cx->reg;\n    void *ptrtop = aa_mem_region_ptr(reg);\n\n    const struct aa_rx_sg_sub *ssg = cx->ssg;\n    const struct aa_rx_sg *sg = cx->ssg->scenegraph;\n\n    if( 1 != cx->q_sub->inc || 1 != cx->q_all->inc ) {\n        return AA_RX_INVALID_PARAMETER;\n    }\n\n    size_t n_sub = cx->q_sub->len;\n    nlopt_algorithm alg = NLOPT_LD_SLSQP;\n    nlopt_opt opt = nlopt_create(alg, (unsigned)n_sub); /* algorithm and dimensionality */\n\n    struct err_cx ocx, eqctcx;\n    ocx.cx = cx;\n    ocx.fun = cx->ik_cx->opts->obj_fun;\n    nlopt_set_min_objective(opt, s_err_cx_dispatch, &ocx);\n\n    if( cx->ik_cx->opts->eqct_fun ) {\n        eqctcx.cx = cx;\n        eqctcx.fun = cx->ik_cx->opts->eqct_fun;\n        nlopt_add_equality_constraint(opt, s_err_cx_dispatch, &eqctcx,\n                                      cx->ik_cx->opts->eqct_tol);\n    }\n\n\n    //nlopt_set_xtol_rel(opt, 1e-4); // TODO: make a parameter\n    if( cx->opts->tol_obj_abs >= 0 )\n        nlopt_set_ftol_abs(opt, cx->opts->tol_obj_abs );\n    if( cx->opts->tol_obj_rel >= 0 )\n        nlopt_set_ftol_rel(opt, cx->opts->tol_obj_rel );\n    if( cx->opts->tol_dq >= 0 )\n        nlopt_set_xtol_rel(opt, cx->opts->tol_dq );\n\n    double *lb = AA_MEM_REGION_NEW_N(reg,double,n_sub);\n    double *ub = AA_MEM_REGION_NEW_N(reg,double,n_sub);\n    { // bounds\n        for( size_t i = 0; i < n_sub; i ++ ) {\n            aa_rx_config_id id = aa_rx_sg_sub_config(ssg,i);\n            if( aa_rx_sg_get_limit_pos(sg, id, lb+i, ub+i) )\n            {\n                lb[i] = -DBL_MAX;\n                ub[i] = DBL_MAX;\n            }\n        }\n    }\n\n\n    nlopt_set_lower_bounds(opt, lb);\n    nlopt_set_upper_bounds(opt, ub);\n    double minf;\n    nlopt_result ores = nlopt_optimize(opt, cx->q_sub->data, &minf);\n    if( cx->opts->debug ) {\n        /* fprintf(\"AMINO IK NLOPT RESULT: %s (%d)\", */\n        /*         nlopt_result_to_string(ores), ores); */\n\n        fprintf(stderr, \"AMINO IK NLOPT RESULT: %d\\n\", ores);\n    }\n    aa_dvec_copy( cx->q_sub, q );\n\n\n    aa_rx_fk_sub(cx->fk, cx->ssg, q);\n    double *E_act = aa_rx_fk_ref(cx->fk, cx->frame);\n    int result = s_check(cx->ik_cx, cx->TF_ref, E_act );\n    nlopt_destroy(opt);\n    aa_mem_region_pop(reg,ptrtop);\n\n    return result;\n\n}\n", "meta": {"hexsha": "a53d432597318d55f5b230e1ee0ee3c89596b329", "size": 19620, "ext": "c", "lang": "C", "max_stars_repo_path": "src/rx/ik_nlopt.c", "max_stars_repo_name": "dyalab/amino", "max_stars_repo_head_hexsha": "e3063ceeeed7d1a3d55fc0d3071c9aacb4466b22", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/rx/ik_nlopt.c", "max_issues_repo_name": "dyalab/amino", "max_issues_repo_head_hexsha": "e3063ceeeed7d1a3d55fc0d3071c9aacb4466b22", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/rx/ik_nlopt.c", "max_forks_repo_name": "dyalab/amino", "max_forks_repo_head_hexsha": "e3063ceeeed7d1a3d55fc0d3071c9aacb4466b22", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4186046512, "max_line_length": 92, "alphanum_fraction": 0.5811926606, "num_tokens": 6489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800991636032, "lm_q2_score": 0.036769466207539105, "lm_q1q2_score": 0.017810397687800548}}
{"text": "/**\n * \\author Sylvain Marsat, University of Maryland - NASA GSFC\n *\n * \\brief C header for the conversion between time scales.\n *\n */\n\n#ifndef _TIMECONVERSION_H\n#define _TIMECONVERSION_H\n\n#define _XOPEN_SOURCE 500\n\n#ifdef __GNUC__\n#define UNUSED __attribute__ ((unused))\n#else\n#define UNUSED\n#endif\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <complex.h>\n#include <time.h>\n#include <unistd.h>\n#include <getopt.h>\n#include <stdbool.h>\n#include <string.h>\n\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_bspline.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_min.h>\n#include <gsl/gsl_spline.h>\n\n#include \"constants.h\"\n\n/*************************/\n/****** Prototypes ******/\n\n/* Function computing the gmst angle from the gps time */\ndouble gmst_angle_from_gpstime(const double gpstime); /* gpstime in seconds */\n\n#if 0\n{ /* so that editors will match succeeding brace */\n#elif defined(__cplusplus)\n}\n#endif\n\n#endif /* _TIMECONVERSION_H */\n", "meta": {"hexsha": "2eaea088cb592422fdc8941c862c56200812094a", "size": 959, "ext": "h", "lang": "C", "max_stars_repo_path": "tools/timeconversion.h", "max_stars_repo_name": "titodalcanton/flare", "max_stars_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z", "max_issues_repo_path": "tools/timeconversion.h", "max_issues_repo_name": "titodalcanton/flare", "max_issues_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tools/timeconversion.h", "max_forks_repo_name": "titodalcanton/flare", "max_forks_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z", "avg_line_length": 19.18, "max_line_length": 78, "alphanum_fraction": 0.6986444213, "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4843800693903656, "lm_q2_score": 0.03676946805470429, "lm_q1q2_score": 0.017810397487784495}}
{"text": "#ifndef OPENMC_TALLIES_FILTER_ENERGY_H\n#define OPENMC_TALLIES_FILTER_ENERGY_H\n\n#include <gsl/gsl>\n\n#include \"openmc/tallies/filter.h\"\n#include \"openmc/vector.h\"\n\nnamespace openmc {\n\n//==============================================================================\n//! Bins the incident neutron energy.\n//==============================================================================\n\nclass EnergyFilter : public Filter {\npublic:\n  //----------------------------------------------------------------------------\n  // Constructors, destructors\n\n  ~EnergyFilter() = default;\n\n  //----------------------------------------------------------------------------\n  // Methods\n\n  std::string type() const override { return \"energy\"; }\n\n  void from_xml(pugi::xml_node node) override;\n\n  void get_all_bins(const Particle& p, TallyEstimator estimator,\n    FilterMatch& match) const override;\n\n  void to_statepoint(hid_t filter_group) const override;\n\n  std::string text_label(int bin) const override;\n\n  //----------------------------------------------------------------------------\n  // Accessors\n\n  const vector<double>& bins() const { return bins_; }\n  void set_bins(gsl::span<const double> bins);\n\n  bool matches_transport_groups() const { return matches_transport_groups_; }\n\nprotected:\n  //----------------------------------------------------------------------------\n  // Data members\n\n  vector<double> bins_;\n\n  //! True if transport group number can be used directly to get bin number\n  bool matches_transport_groups_ {false};\n};\n\n//==============================================================================\n//! Bins the outgoing neutron energy.\n//!\n//! Only scattering events use the get_all_bins functionality.  Nu-fission\n//! tallies manually iterate over the filter bins.\n//==============================================================================\n\nclass EnergyoutFilter : public EnergyFilter {\npublic:\n  //----------------------------------------------------------------------------\n  // Methods\n\n  std::string type() const override { return \"energyout\"; }\n\n  void get_all_bins(const Particle& p, TallyEstimator estimator,\n    FilterMatch& match) const override;\n\n  std::string text_label(int bin) const override;\n};\n\n} // namespace openmc\n#endif // OPENMC_TALLIES_FILTER_ENERGY_H\n", "meta": {"hexsha": "c820f28fb4b9632044ffbb187293867002049a44", "size": 2288, "ext": "h", "lang": "C", "max_stars_repo_path": "include/openmc/tallies/filter_energy.h", "max_stars_repo_name": "stu314159/openmc", "max_stars_repo_head_hexsha": "2efe223404680099f9a77214e743ab78e37cd08c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-09T17:55:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-09T17:55:14.000Z", "max_issues_repo_path": "include/openmc/tallies/filter_energy.h", "max_issues_repo_name": "huak95/openmc", "max_issues_repo_head_hexsha": "922f688978693761f82c4a3764ab05dd96cc8cff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/openmc/tallies/filter_energy.h", "max_forks_repo_name": "huak95/openmc", "max_forks_repo_head_hexsha": "922f688978693761f82c4a3764ab05dd96cc8cff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1052631579, "max_line_length": 80, "alphanum_fraction": 0.5074300699, "num_tokens": 399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3486451488696663, "lm_q2_score": 0.05108273858224624, "lm_q1q2_score": 0.017809748997677486}}
{"text": "/*\n * Copyright 2020 Makani Technologies LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#ifndef SIM_MATH_ODE_SOLVER_GSL_H_\n#define SIM_MATH_ODE_SOLVER_GSL_H_\n\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_odeiv2.h>\n#include <stdint.h>\n\n#include <vector>\n\n#include \"common/macros.h\"\n#include \"sim/math/ode_solver.h\"\n#include \"sim/sim_types.h\"\n\nnamespace sim {\n\n// Wrapper for the GSL ODE library.\nclass GslOdeSolver : public OdeSolver {\n public:\n  explicit GslOdeSolver(const OdeSystem &ode_system,\n                        const SimOdeSolverParams &params);\n  ~GslOdeSolver() {\n    if (ode_driver_ != nullptr) gsl_odeiv2_driver_free(ode_driver_);\n  }\n\n  OdeSolverStatus Integrate(double t0, double tf, const std::vector<double> &x0,\n                            double *t_int, std::vector<double> *x) override;\n\n private:\n  // Static callback function for the GSL ODE solver.\n  //\n  // Args:\n  //   t: Time at which derivative will be evaluated.\n  //   x: Array of length num_states() containing the state at which\n  //       the derivative will be evaluated.\n  //   dx: Array of length num_states() into which the derivative is stored.\n  //   context: Pointer to the OdeSolver class containing the OdeSystem.\n  //\n  // Returns:\n  //   GSL_SUCCESS if the derivative was calculated successfully,\n  //   GSL_FAILURE if the time step was too large, or\n  //   GSL_EBADFUNC if the integration should be aborted immediately.\n  static int32_t GslCallback(double t, const double x[], double dx[],\n                             void *context);\n\n  // Solver parameters.\n  const SimOdeSolverParams &params_;\n\n  // ODE to be solved.\n  const OdeSystem &ode_system_;\n\n  // Parameters for GSL.\n  gsl_odeiv2_system sys_;\n  gsl_odeiv2_driver *ode_driver_;\n\n  DISALLOW_COPY_AND_ASSIGN(GslOdeSolver);\n};\n\n}  // namespace sim\n\n#endif  // SIM_MATH_ODE_SOLVER_GSL_H_\n", "meta": {"hexsha": "0befb4297c5d76acb52df286780b26b54a1f4109", "size": 2362, "ext": "h", "lang": "C", "max_stars_repo_path": "sim/math/ode_solver_gsl.h", "max_stars_repo_name": "leozz37/makani", "max_stars_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1178.0, "max_stars_repo_stars_event_min_datetime": "2020-09-10T17:15:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:59:35.000Z", "max_issues_repo_path": "sim/math/ode_solver_gsl.h", "max_issues_repo_name": "leozz37/makani", "max_issues_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-22T05:22:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-22T05:22:35.000Z", "max_forks_repo_path": "sim/math/ode_solver_gsl.h", "max_forks_repo_name": "leozz37/makani", "max_forks_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 107.0, "max_forks_repo_forks_event_min_datetime": "2020-09-10T17:29:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T09:00:14.000Z", "avg_line_length": 30.6753246753, "max_line_length": 80, "alphanum_fraction": 0.7078746825, "num_tokens": 586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.03732688975366457, "lm_q1q2_score": 0.017789236094093764}}
{"text": "#ifndef BCT_TEST_H\n#define BCT_TEST_H\n\n#include <bct/bct.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_vector.h>\n#include <octave/oct.h>\n#include <vector>\n\nnamespace bct_test {\n\tMatrix from_gsl(const gsl_vector*, int = 0);\n\tMatrix from_gsl(const gsl_matrix*, int = 0, int = 0);\n\tNDArray from_gsl(const std::vector<gsl_matrix*>, int = 0);\n\tgsl_vector* to_gslv(const Matrix, int = 0);\n\tgsl_matrix* to_gslm(const Matrix, int = 0, int = 0);\n\tstd::vector<gsl_matrix*> to_gsl(const NDArray, int = 0);\n}\n\n#include \"bct_test.cpp\"\n\n#define MATRIX_TO_SCALAR_FUNCTION(function_name) \\\n\tDEFUN_DLD(function_name##_cpp, args, , \"Wrapper for C++ function.\") { \\\n\t\tif (args.length() == 0) { \\\n\t\t\treturn octave_value_list(); \\\n\t\t} \\\n\t\tMatrix m = args(0).matrix_value(); \\\n\t\tif (!error_state) { \\\n\t\t\tgsl_matrix* m_gsl = bct_test::to_gslm(m); \\\n\t\t\toctave_value ret = octave_value(bct::function_name(m_gsl)); \\\n\t\t\tgsl_matrix_free(m_gsl); \\\n\t\t\treturn ret; \\\n\t\t} else { \\\n\t\t\treturn octave_value_list(); \\\n\t\t} \\\n\t}\n\n#define MATRIX_TO_VECTOR_FUNCTION(function_name) \\\n\tDEFUN_DLD(function_name##_cpp, args, , \"Wrapper for C++ function.\") { \\\n\t\tif (args.length() == 0) { \\\n\t\t\treturn octave_value_list(); \\\n\t\t} \\\n\t\tMatrix m = args(0).matrix_value(); \\\n\t\tif (!error_state) { \\\n\t\t\tgsl_matrix* m_gsl = bct_test::to_gslm(m); \\\n\t\t\tgsl_vector* ret_gsl = bct::function_name(m_gsl); \\\n\t\t\toctave_value ret = bct_test::from_gsl(ret_gsl); \\\n\t\t\tgsl_matrix_free(m_gsl); \\\n\t\t\tgsl_vector_free(ret_gsl); \\\n\t\t\treturn ret; \\\n\t\t} else { \\\n\t\t\treturn octave_value_list(); \\\n\t\t} \\\n\t}\n\n#define MATRIX_TO_MATRIX_FUNCTION(function_name) \\\n\tDEFUN_DLD(function_name##_cpp, args, , \"Wrapper for C++ function.\") { \\\n\t\tif (args.length() == 0) { \\\n\t\t\treturn octave_value_list(); \\\n\t\t} \\\n\t\tMatrix m = args(0).matrix_value(); \\\n\t\tif (!error_state) { \\\n\t\t\tgsl_matrix* m_gsl = bct_test::to_gslm(m); \\\n\t\t\tgsl_matrix* ret_gsl = bct::function_name(m_gsl); \\\n\t\t\toctave_value ret = bct_test::from_gsl(ret_gsl); \\\n\t\t\tgsl_matrix_free(m_gsl); \\\n\t\t\tgsl_matrix_free(ret_gsl); \\\n\t\t\treturn ret; \\\n\t\t} else { \\\n\t\t\treturn octave_value_list(); \\\n\t\t} \\\n\t}\n\n#endif\n", "meta": {"hexsha": "d2ef78d7714381bb7ff5a828ee6cd436ec63152a", "size": 2089, "ext": "h", "lang": "C", "max_stars_repo_path": "test/bct_test.h", "max_stars_repo_name": "devuci/bct-cpp", "max_stars_repo_head_hexsha": "bbb33f476bffbb5669e051841f00c3241f4d6f69", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/bct_test.h", "max_issues_repo_name": "devuci/bct-cpp", "max_issues_repo_head_hexsha": "bbb33f476bffbb5669e051841f00c3241f4d6f69", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/bct_test.h", "max_forks_repo_name": "devuci/bct-cpp", "max_forks_repo_head_hexsha": "bbb33f476bffbb5669e051841f00c3241f4d6f69", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2297297297, "max_line_length": 72, "alphanum_fraction": 0.6620392532, "num_tokens": 671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.037326885737772805, "lm_q1q2_score": 0.017789234180201466}}
{"text": "#ifndef BATCH_EXTRACTOR_H_IVH3CLLQ\n#define BATCH_EXTRACTOR_H_IVH3CLLQ\n\n#include <algorithm>\n#include <gsl/gsl>\n#include <opencv2/core/types.hpp>\n#include <opencv2/features2d.hpp>\n#include <opencv2/xfeatures2d.hpp>\n#include <optional>\n#include <sens_loc/util/correctness_util.h>\n\nusing namespace std;\nusing namespace cv;\n\nnamespace sens_loc::apps {\n\n/// Helper class that visits a list of images and extracts features with the\n/// provided detectors.\n/// \\ingroup feature-extractor-driver\nclass batch_extractor {\n  public:\n    using filter_func = function<vector<KeyPoint>::iterator(vector<KeyPoint>&)>;\n\n    /// \\param detector,descriptor Algorithms used for detection and\n    /// description.\n    /// \\param input_pattern,output_pattern Formattable string for IO.\n    /// \\param keypoint_filter Callable that determines if a keypoint shall be\n    /// dropped from consideration. All keypoints with 'keypoint_filter(kp) ==\n    /// true' are removed.\n    batch_extractor(Ptr<Feature2D>      detector,\n                    Ptr<Feature2D>      descriptor,\n                    string_view         input_pattern,\n                    string_view         output_pattern,\n                    vector<filter_func> keypoint_filter)\n        : _detector{move(detector)}\n        , _descriptor{move(descriptor)}\n        , _input_pattern{input_pattern}\n        , _ouput_pattern{output_pattern}\n        , _keypoint_filter{move(keypoint_filter)} {\n        Expects(!_input_pattern.empty());\n        Expects(!_ouput_pattern.empty());\n        Expects(!_detector.empty());\n    }\n\n    /// Process a whole batch of files in the range [start, end].\n    [[nodiscard]] bool process_batch(int start, int end) const noexcept;\n\n  private:\n    /// Detect and describe one single index. Handles the IO as well.\n    [[nodiscard]] bool process_index(int idx) const noexcept;\n\n    /// Do IO and handle detection down to \\c compute_features.\n    bool process_detector(const math::image<uchar>& image,\n                          const string&             out_file,\n                          const string&             in_file) const noexcept;\n\n    /// Compute and filter keypoints and run the descriptor on them\n    /// afterwards.\n    [[nodiscard]] pair<vector<KeyPoint>, Mat>\n    compute_features(const math::image<uchar>& img) const noexcept;\n\n\n    mutable Ptr<Feature2D> _detector;\n    mutable Ptr<Feature2D> _descriptor;\n    string_view            _input_pattern;\n    string_view            _ouput_pattern;\n    vector<filter_func>    _keypoint_filter;\n};\n}  // namespace sens_loc::apps\n\n#endif /* end of include guard: BATCH_EXTRACTOR_H_IVH3CLLQ */\n", "meta": {"hexsha": "016faa725d9629c154719ab2cec092bab63979d3", "size": 2614, "ext": "h", "lang": "C", "max_stars_repo_path": "src/apps/feature_extractor/batch_extractor.h", "max_stars_repo_name": "JonasToth/depth-conversions", "max_stars_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-09-30T07:09:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T09:14:35.000Z", "max_issues_repo_path": "src/apps/feature_extractor/batch_extractor.h", "max_issues_repo_name": "JonasToth/depth-conversions", "max_issues_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/apps/feature_extractor/batch_extractor.h", "max_forks_repo_name": "JonasToth/depth-conversions", "max_forks_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3055555556, "max_line_length": 80, "alphanum_fraction": 0.6706197399, "num_tokens": 572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.046033897164190665, "lm_q1q2_score": 0.017719006076421493}}
{"text": "#ifndef UTIL_H_\n#define UTIL_H_\n\n#include <gsl/gsl_randist.h>\n#include <gsl/gsl_rng.h>\n#include <time.h>\n\n/*\n * constants\n */\n\n#define TYPE_REQ 1\n#define TYPE_REQ_FOLLOW 2\n#define TYPE_RES 0\n\n#define NB_MBUF 8191\n#define MBUF_SIZE (2048 + sizeof(struct rte_mbuf) + RTE_PKTMBUF_HEADROOM)\n#define MBUF_CACHE_SIZE 32\n#define MAX_BURST_SIZE 32\n#define MAX_LCORES 32\n#define NB_RXD 128  // RX descriptors\n#define NB_TXD 512  // TX descriptors\n#define RX_QUEUE_PER_LCORE 4\n\n#define IP_SRC \"10.1.0.12\"\n#define IP_DST \"10.1.0.1\"\n#define CLIENT_PORT 11234\n#define SERVICE_PORT 1234\n\nstatic const struct rte_eth_conf port_conf = {\n    .rxmode =\n        {\n            .max_rx_pkt_len = ETHER_MAX_LEN,\n            .split_hdr_size = 0,\n            .header_split = 0,    // Header Split disabled\n            .hw_ip_checksum = 0,  // IP checksum offload disabled\n            .hw_vlan_filter = 0,  // VLAN filtering disabled\n            .jumbo_frame = 0,     // Jumbo Frame Support disabled\n            .hw_strip_crc = 0,    // CRC stripped by hardware\n        },\n    .txmode =\n        {\n            .mq_mode = ETH_MQ_TX_NONE,\n        },\n};\n\n/*\n * custom types\n */\n\n/********* Misc *********/\n\n// Get current time in ns\nuint64_t get_cur_ns() {\n  struct timespec ts;\n  clock_gettime(CLOCK_REALTIME, &ts);\n  uint64_t t = ts.tv_sec * 1000 * 1000 * 1000 + ts.tv_nsec;\n  return t;\n}\n\n// For storing results\ntypedef struct LatencyResults_ {\n  uint64_t *sjrn_times;\n  uint64_t *sjrn_times_short;\n  uint64_t *sjrn_times_long;\n  uint64_t *work_ratios;\n  uint64_t *work_ratios_short;\n  uint64_t *work_ratios_long;\n  uint32_t (*queue_lengths)[3];\n  size_t count;\n  size_t count_short;\n  size_t count_long;\n} LatencyResults;\n\n/********* Distributions *********/\n\n// Exponential Distribution\ntypedef struct ExpDist_ {\n  gsl_rng *r;\n  double mu;\n  uint64_t cur_ns;\n} ExpDist;\n\nvoid init_exp_dist(ExpDist *exp_dist, double mu) {\n  gsl_rng_env_setup();\n  const gsl_rng_type *T = gsl_rng_default;\n  gsl_rng *r = gsl_rng_alloc(T);\n  uint64_t cur_ns = get_cur_ns();\n  ExpDist temp_exp_dist = {r, mu, cur_ns};\n  memcpy(exp_dist, &temp_exp_dist, sizeof(ExpDist));\n}\n\nuint64_t exp_dist_next_arrival_ns(ExpDist *exp_dist) {\n  exp_dist->cur_ns += gsl_ran_exponential(exp_dist->r, exp_dist->mu);\n  return exp_dist->cur_ns;\n}\n\nuint64_t exp_dist_work_ns(ExpDist *exp_dist) {\n  return gsl_ran_exponential(exp_dist->r, exp_dist->mu);\n}\n\nvoid free_exp_dist(const ExpDist *exp_dist) {\n  gsl_rng_free(exp_dist->r);\n  free((void *)exp_dist);\n}\n\n// Lognormal Distribution\ntypedef struct LognormalDist_ {\n  gsl_rng *r;\n  double mu;\n  double sigma;\n} LognormalDist;\n\nvoid init_lognormal_dist(LognormalDist *lognormal_dist, double mu,\n                         double sigma) {\n  gsl_rng_env_setup();\n  const gsl_rng_type *T = gsl_rng_default;\n  gsl_rng *r = gsl_rng_alloc(T);\n  LognormalDist temp_lognormal_dist = {r, mu, sigma};\n  memcpy(lognormal_dist, &temp_lognormal_dist, sizeof(LognormalDist));\n}\n\nuint64_t lognormal_dist_work_ns(LognormalDist *lognormal_dist) {\n  return gsl_ran_lognormal(lognormal_dist->r, lognormal_dist->mu,\n                           lognormal_dist->sigma);\n}\n\nvoid free_lognormal_dist(LognormalDist *lognormal_dist) {\n  gsl_rng_free(lognormal_dist->r);\n  free((void *)lognormal_dist);\n}\n\n// Bimodal Distribution\ntypedef struct BimodalDist_ {\n  gsl_rng *r;\n  uint64_t work_1;\n  uint64_t work_2;\n  double ratio;\n} BimodalDist;\n\nvoid init_bimodal_dist(BimodalDist *bimodal_dist, uint64_t work_1_ns,\n                       uint64_t work_2_ns, double ratio) {\n  gsl_rng_env_setup();\n  const gsl_rng_type *T = gsl_rng_default;\n  gsl_rng *r = gsl_rng_alloc(T);\n  BimodalDist temp_bimodal_dist = {r, work_1_ns, work_2_ns, ratio};\n  memcpy(bimodal_dist, &temp_bimodal_dist, sizeof(BimodalDist));\n}\n\nuint64_t bimodal_dist_work_ns(BimodalDist *bimodal_dist) {\n  double num = gsl_ran_flat(bimodal_dist->r, 0.0, 1.0);\n  if (num < bimodal_dist->ratio) {\n    return bimodal_dist->work_1;\n  } else {\n    return bimodal_dist->work_2;\n  }\n}\n\nvoid free_bimodal_dist(BimodalDist *bimodal_dist) {\n  gsl_rng_free(bimodal_dist->r);\n  free((void *)bimodal_dist);\n}\n\n// Trimodal Distribution\ntypedef struct TrimodalDist_ {\n  gsl_rng *r;\n  uint64_t work_1;\n  uint64_t work_2;\n  uint64_t work_3;\n  double ratio1;\n  double ratio2;\n} TrimodalDist;\n\nvoid init_trimodal_dist(TrimodalDist *trimodal_dist, uint64_t work_1_ns,\n                        uint64_t work_2_ns, uint64_t work_3_ns, double ratio1,\n                        double ratio2) {\n  gsl_rng_env_setup();\n  const gsl_rng_type *T = gsl_rng_default;\n  gsl_rng *r = gsl_rng_alloc(T);\n  TrimodalDist temp_trimodal_dist = {\n      r, work_1_ns, work_2_ns, work_3_ns, ratio1, ratio2,\n  };\n  memcpy(trimodal_dist, &temp_trimodal_dist, sizeof(TrimodalDist));\n}\n\nuint64_t trimodal_dist_work_ns(TrimodalDist *trimodal_dist) {\n  double num = gsl_ran_flat(trimodal_dist->r, 0.0, 1.0);\n  if (num < trimodal_dist->ratio1) {\n    return trimodal_dist->work_1;\n  } else if (num < trimodal_dist->ratio1 + trimodal_dist->ratio2) {\n    return trimodal_dist->work_2;\n  } else {\n    return trimodal_dist->work_3;\n  }\n}\n\nvoid free_trimodal_dist(TrimodalDist *trimodal_dist) {\n  gsl_rng_free(trimodal_dist->r);\n  free((void *)trimodal_dist);\n}\n\ntypedef struct Message_ {\n  uint8_t recir_flag;\n  uint8_t core_idx;\n  uint8_t type;\n  uint16_t seq_num;\n  uint32_t queue_length[3];\n  uint16_t client_id;\n  uint32_t req_id;\n  uint32_t pkts_length;\n  uint64_t run_ns;\n  uint64_t gen_ns;\n} __attribute__((__packed__)) Message;\n\nstruct mbuf_table {\n  uint32_t len;\n  struct rte_mbuf *m_table[MAX_BURST_SIZE];\n};\n\nstruct lcore_configuration {\n  uint32_t vid;                                // virtual core id\n  uint32_t port;                               // one port\n  uint32_t tx_queue_id;                        // one TX queue\n  uint32_t n_rx_queue;                         // number of RX queues\n  uint32_t rx_queue_list[RX_QUEUE_PER_LCORE];  // list of RX queues\n  struct mbuf_table tx_mbufs;                  // mbufs to hold TX queue\n} __rte_cache_aligned;\n\n/*\n * global variables\n */\n\nuint32_t enabled_port_mask = 1;\nuint32_t enabled_ports[RTE_MAX_ETHPORTS];\nuint32_t n_enabled_ports = 0;\nuint32_t n_rx_queues = 0;\nuint32_t n_lcores = 0;\n\nstruct rte_mempool *pktmbuf_pool = NULL;\nstruct ether_addr port_eth_addrs[RTE_MAX_ETHPORTS];\nstruct lcore_configuration lcore_conf[MAX_LCORES];\n\nuint8_t header_template[sizeof(struct ether_hdr) + sizeof(struct ipv4_hdr) +\n                        sizeof(struct udp_hdr)];\n\n/*\n * functions for generation\n */\n\n// send packets, drain TX queue\nstatic void send_pkt_burst(uint32_t lcore_id) {\n  struct lcore_configuration *lconf = &lcore_conf[lcore_id];\n  struct rte_mbuf **m_table = (struct rte_mbuf **)lconf->tx_mbufs.m_table;\n\n  uint32_t n = lconf->tx_mbufs.len;\n  uint32_t ret = rte_eth_tx_burst(lconf->port, lconf->tx_queue_id, m_table,\n                                  lconf->tx_mbufs.len);\n  if (unlikely(ret < n)) {\n    do {\n      rte_pktmbuf_free(m_table[ret]);\n    } while (++ret < n);\n  }\n  lconf->tx_mbufs.len = 0;\n}\n\n// put packet into TX queue\nstatic void enqueue_pkt(uint32_t lcore_id, struct rte_mbuf *mbuf) {\n  struct lcore_configuration *lconf = &lcore_conf[lcore_id];\n  lconf->tx_mbufs.m_table[lconf->tx_mbufs.len++] = mbuf;\n\n  // enough packets in TX queue\n  if (unlikely(lconf->tx_mbufs.len == MAX_BURST_SIZE)) {\n    send_pkt_burst(lcore_id);\n  }\n}\n\n/*\n * functions for initialization\n */\n\n// init header template\nstatic void init_header_template(void) {\n  memset(header_template, 0, sizeof(header_template));\n  struct ether_hdr *eth = (struct ether_hdr *)header_template;\n  struct ipv4_hdr *ip =\n      (struct ipv4_hdr *)((uint8_t *)eth + sizeof(struct ether_hdr));\n  struct udp_hdr *udp =\n      (struct udp_hdr *)((uint8_t *)ip + sizeof(struct ipv4_hdr));\n  uint32_t pkt_len = sizeof(header_template) + sizeof(Message);\n\n  // eth header\n  eth->ether_type = rte_cpu_to_be_16(ETHER_TYPE_IPv4);\n  struct ether_addr src_addr = {\n      .addr_bytes = {0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}};\n  struct ether_addr dst_addr = {\n      .addr_bytes = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55}};\n  ether_addr_copy(&src_addr, &eth->s_addr);\n  ether_addr_copy(&dst_addr, &eth->d_addr);\n\n  // ip header\n  char src_ip[] = IP_SRC;\n  char dst_ip[] = IP_DST;\n  int st1 = inet_pton(AF_INET, src_ip, &(ip->src_addr));\n  int st2 = inet_pton(AF_INET, dst_ip, &(ip->dst_addr));\n  if (st1 != 1 || st2 != 1) {\n    fprintf(stderr, \"inet_pton() failed.Error message: %s %s\", strerror(st1),\n            strerror(st2));\n    exit(EXIT_FAILURE);\n  }\n  ip->total_length = rte_cpu_to_be_16(pkt_len - sizeof(struct ether_hdr));\n  ip->version_ihl = 0x45;\n  ip->type_of_service = 0;\n  ip->packet_id = 0;\n  ip->fragment_offset = 0;\n  ip->time_to_live = 64;\n  ip->next_proto_id = IPPROTO_UDP;\n  uint32_t ip_cksum;\n  uint16_t *ptr16 = (uint16_t *)ip;\n  ip_cksum = 0;\n  ip_cksum += ptr16[0];\n  ip_cksum += ptr16[1];\n  ip_cksum += ptr16[2];\n  ip_cksum += ptr16[3];\n  ip_cksum += ptr16[4];\n  ip_cksum += ptr16[6];\n  ip_cksum += ptr16[7];\n  ip_cksum += ptr16[8];\n  ip_cksum += ptr16[9];\n  ip_cksum = ((ip_cksum & 0xffff0000) >> 16) + (ip_cksum & 0x0000ffff);\n  if (ip_cksum > 65535) {\n    ip_cksum -= 65535;\n  }\n  ip_cksum = (~ip_cksum) & 0x0000ffff;\n  if (ip_cksum == 0) {\n    ip_cksum = 0xffff;\n  }\n  ip->hdr_checksum = (uint16_t)ip_cksum;\n\n  // udp header\n  udp->src_port = htons(CLIENT_PORT);\n  udp->dst_port = htons(SERVICE_PORT);\n  udp->dgram_len = rte_cpu_to_be_16(pkt_len - sizeof(struct ether_hdr) -\n                                    sizeof(struct ipv4_hdr));\n  udp->dgram_cksum = 0;\n}\n\n// check link status\nstatic void check_link_status(void) {\n  const uint32_t check_interval_ms = 100;\n  const uint32_t check_iterations = 90;\n  uint32_t i, j;\n  struct rte_eth_link link;\n  for (i = 0; i < check_iterations; i++) {\n    uint8_t all_ports_up = 1;\n    for (j = 0; j < n_enabled_ports; j++) {\n      uint32_t portid = enabled_ports[j];\n      memset(&link, 0, sizeof(link));\n      rte_eth_link_get_nowait(portid, &link);\n      if (link.link_status) {\n        printf(\"\\tport %u link up - speed %u Mbps - %s\\n\", portid,\n               link.link_speed,\n               (link.link_duplex == ETH_LINK_FULL_DUPLEX) ? \"full-duplex\"\n                                                          : \"half-duplex\");\n      } else {\n        all_ports_up = 0;\n      }\n    }\n\n    if (all_ports_up == 1) {\n      printf(\"check link status finish: all ports are up\\n\");\n      break;\n    } else if (i == check_iterations - 1) {\n      printf(\"check link status finish: not all ports are up\\n\");\n    } else {\n      rte_delay_ms(check_interval_ms);\n    }\n  }\n}\n\n// initialize all status\nstatic void init(void) {\n  uint32_t i, j;\n\n  // create mbuf pool\n  printf(\"create mbuf pool\\n\");\n  pktmbuf_pool = rte_mempool_create(\n      \"mbuf_pool\", NB_MBUF, MBUF_SIZE, MBUF_CACHE_SIZE,\n      sizeof(struct rte_pktmbuf_pool_private), rte_pktmbuf_pool_init, NULL,\n      rte_pktmbuf_init, NULL, rte_socket_id(), 0);\n  if (pktmbuf_pool == NULL) {\n    rte_exit(EXIT_FAILURE, \"cannot init mbuf pool\\n\");\n  }\n\n  // determine available ports\n  printf(\"create enabled ports\\n\");\n  uint32_t n_total_ports = 0;\n  n_total_ports = rte_eth_dev_count();\n\n  if (n_total_ports == 0) {\n    rte_exit(EXIT_FAILURE, \"cannot detect ethernet ports\\n\");\n  }\n  if (n_total_ports > RTE_MAX_ETHPORTS) {\n    n_total_ports = RTE_MAX_ETHPORTS;\n  }\n\n  // get info for each enabled port\n  struct rte_eth_dev_info dev_info;\n  n_enabled_ports = 0;\n  printf(\"\\tports: \");\n  for (i = 0; i < n_total_ports; i++) {\n    if ((enabled_port_mask & (1 << i)) == 0) {\n      continue;\n    }\n    enabled_ports[n_enabled_ports++] = i;\n    rte_eth_dev_info_get(i, &dev_info);\n    printf(\"%u \", i);\n  }\n  printf(\"\\n\");\n\n  // find number of active lcores\n  printf(\"create enabled cores\\n\\tcores: \");\n  n_lcores = 0;\n  for (i = 0; i < MAX_LCORES; i++) {\n    if (rte_lcore_is_enabled(i)) {\n      n_lcores++;\n      printf(\"%u \", i);\n    }\n  }\n\n  // ensure numbers are correct\n  if (n_lcores % n_enabled_ports != 0) {\n    rte_exit(EXIT_FAILURE,\n             \"number of cores (%u) must be multiple of ports (%u)\\n\", n_lcores,\n             n_enabled_ports);\n  }\n\n  uint32_t rx_queues_per_lcore = RX_QUEUE_PER_LCORE;\n  uint32_t rx_queues_per_port =\n      rx_queues_per_lcore * n_lcores / n_enabled_ports;\n  uint32_t tx_queues_per_port = n_lcores / n_enabled_ports;\n\n  if (rx_queues_per_port < rx_queues_per_lcore) {\n    rte_exit(EXIT_FAILURE,\n             \"rx_queues_per_port (%u) must be >= rx_queues_per_lcore (%u)\\n\",\n             rx_queues_per_port, rx_queues_per_lcore);\n  }\n\n  // assign each lcore some RX queues and a port\n  printf(\"set up %d RX queues per port and %d TX queues per port\\n\",\n         rx_queues_per_port, tx_queues_per_port);\n  uint32_t portid_offset = 0;\n  uint32_t rx_queue_id = 0;\n  uint32_t tx_queue_id = 0;\n  uint32_t vid = 0;\n  for (i = 0; i < MAX_LCORES; i++) {\n    if (rte_lcore_is_enabled(i)) {\n      lcore_conf[i].vid = vid++;\n      lcore_conf[i].n_rx_queue = rx_queues_per_lcore;\n      for (j = 0; j < rx_queues_per_lcore; j++) {\n        lcore_conf[i].rx_queue_list[j] = rx_queue_id++;\n      }\n      lcore_conf[i].port = enabled_ports[portid_offset];\n      lcore_conf[i].tx_queue_id = tx_queue_id++;\n      if (rx_queue_id % rx_queues_per_port == 0) {\n        portid_offset++;\n        rx_queue_id = 0;\n        tx_queue_id = 0;\n      }\n    }\n  }\n\n  // initialize each port\n  for (portid_offset = 0; portid_offset < n_enabled_ports; portid_offset++) {\n    uint32_t portid = enabled_ports[portid_offset];\n\n    int32_t ret = rte_eth_dev_configure(portid, rx_queues_per_port,\n                                        tx_queues_per_port, &port_conf);\n    if (ret < 0) {\n      rte_exit(EXIT_FAILURE, \"cannot configure device: err=%d, port=%u\\n\", ret,\n               portid);\n    }\n    rte_eth_macaddr_get(portid, &port_eth_addrs[portid]);\n\n    // initialize RX queues\n    for (i = 0; i < rx_queues_per_port; i++) {\n      ret = rte_eth_rx_queue_setup(\n          portid, i, NB_RXD, rte_eth_dev_socket_id(portid), NULL, pktmbuf_pool);\n      if (ret < 0) {\n        rte_exit(EXIT_FAILURE, \"rte_eth_rx_queue_setup: err=%d, port=%u\\n\", ret,\n                 portid);\n      }\n    }\n\n    // initialize TX queues\n    for (i = 0; i < tx_queues_per_port; i++) {\n      ret = rte_eth_tx_queue_setup(portid, i, NB_TXD,\n                                   rte_eth_dev_socket_id(portid), NULL);\n      if (ret < 0) {\n        rte_exit(EXIT_FAILURE, \"rte_eth_tx_queue_setup: err=%d, port=%u\\n\", ret,\n                 portid);\n      }\n    }\n\n    // start device\n    ret = rte_eth_dev_start(portid);\n    if (ret < 0) {\n      rte_exit(EXIT_FAILURE, \"rte_eth_dev_start: err=%d, port=%u\\n\", ret,\n               portid);\n    }\n\n    rte_eth_promiscuous_enable(portid);\n\n    char mac_buf[ETHER_ADDR_FMT_SIZE];\n    ether_format_addr(mac_buf, ETHER_ADDR_FMT_SIZE, &port_eth_addrs[portid]);\n    printf(\"initiaze queues and start port %u, MAC address:%s\\n\", portid,\n           mac_buf);\n  }\n\n  if (!n_enabled_ports) {\n    rte_exit(EXIT_FAILURE,\n             \"all available ports are disabled. Please set portmask.\\n\");\n  }\n  check_link_status();\n  init_header_template();\n}\n\n/*\n * misc\n */\n\nstatic uint64_t timediff_in_us(uint64_t new_t, uint64_t old_t) {\n  return (new_t - old_t) * 1000000UL / rte_get_tsc_hz();\n}\n\n#endif  // UTIL_H_\n", "meta": {"hexsha": "c891bc64c58f0d295eb026e9d5175b461a9b7fd2", "size": 15326, "ext": "h", "lang": "C", "max_stars_repo_path": "client_code/r2p2-client/util.h", "max_stars_repo_name": "netx-repo/RackSched", "max_stars_repo_head_hexsha": "ba3a4c4dfc100701df4733462dc83dec0d6851fd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2020-10-30T18:20:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T13:14:01.000Z", "max_issues_repo_path": "client_code/r2p2-client/util.h", "max_issues_repo_name": "netx-repo/RackSched", "max_issues_repo_head_hexsha": "ba3a4c4dfc100701df4733462dc83dec0d6851fd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "client_code/r2p2-client/util.h", "max_forks_repo_name": "netx-repo/RackSched", "max_forks_repo_head_hexsha": "ba3a4c4dfc100701df4733462dc83dec0d6851fd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-10-19T16:28:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-27T03:07:26.000Z", "avg_line_length": 28.5932835821, "max_line_length": 80, "alphanum_fraction": 0.6599243116, "num_tokens": 4541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.03676946779082354, "lm_q1q2_score": 0.01766694527665999}}
{"text": "//====---- Sudoku/Board_Section.h                                     ----====//\n//\n// Internal in-between object for provide access to a section of Board.\n//====--------------------------------------------------------------------====//\n#pragma once\n\n#include \"Board_Section_iterator.h\"\n#include \"Board_Section_traits.h\" // Convenience include\n#include \"Location.h\"\n#include \"Location_Utilities.h\"\n#include \"exceptions.h\"\n#include \"traits.h\"\n\n#include <gsl/gsl> // index\n\n#include <type_traits>\n\n#include \"Board.fwd.h\" // Forward declarations\n\n#include <cassert>\n\n\nnamespace Sudoku::Board_Section\n{\ntemplate<typename T, int N, Section S, bool is_const>\nclass [[nodiscard]] Board_Section_\n{\n\tusing index          = gsl::index;\n\tusing Location       = ::Sudoku::Location<N>;\n\tusing Location_Block = ::Sudoku::Location_Block<N>;\n\tusing OwnerT =\n\t\tstd::conditional_t<is_const, Board<T, N> const&, Board<T, N>&>;\n\n\t// explicit friends for conversion\n\tfriend class Board_Section_<T, N, Section::row, true>;\n\tfriend class Board_Section_<T, N, Section::row, false>;\n\tfriend class Board_Section_<T, N, Section::col, true>;\n\tfriend class Board_Section_<T, N, Section::col, false>;\n\tfriend class Board_Section_<T, N, Section::block, true>;\n\tfriend class Board_Section_<T, N, Section::block, false>;\n\npublic:\n\tusing value_type             = T;\n\tusing pointer                = std::conditional_t<is_const, T const*, T*>;\n\tusing reference              = std::conditional_t<is_const, T const&, T&>;\n\tusing iterator               = Section_iterator<T, N, S, is_const, false>;\n\tusing const_iterator         = Section_iterator<T, N, S, true, false>;\n\tusing reverse_iterator       = Section_iterator<T, N, S, is_const, true>;\n\tusing const_reverse_iterator = Section_iterator<T, N, S, true, true>;\n\n\ttemplate<typename idT, typename = std::enable_if_t<is_int_v<idT>>>\n\tconstexpr Board_Section_(OwnerT board, idT id) noexcept\n\t\t: board_(board), id_(id)\n\t{\n\t\tassert(is_valid_size<N>(id));\n\t}\n\tconstexpr Board_Section_(OwnerT board, Location loc) noexcept\n\t\t: board_(board), id_(to_id(loc))\n\t{\n\t\tassert(is_valid<N>(loc));\n\t}\n\t// Conversion to other Section type (maintaining or gaining const)\n\ttemplate<\n\t\tSection Sx,\n\t\tbool B,\n\t\ttypename = std::enable_if_t<!B || B == is_const>>\n\tconstexpr Board_Section_(\n\t\tBoard_Section_<T, N, Sx, B> other, index pivot_elem) noexcept\n\t\t: board_(other.board_), id_(to_id(other.location(pivot_elem)))\n\t{\n\t}\n\t// [[implicit]] conversion to const\n\t// NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions)\n\tconstexpr operator Board_Section_<T, N, S, true>() const noexcept\n\t{\n\t\treturn Board_Section_<T, N, S, true>(board_, id_);\n\t}\n\n\t[[nodiscard]] static constexpr int size() noexcept { return elem_size<N>; }\n\t[[nodiscard]] constexpr index id() const noexcept { return id_; }\n\t[[nodiscard]] constexpr Location location(index elem) const noexcept;\n\n\t[[nodiscard]] constexpr reference front() noexcept { return (*this)[0]; }\n\t[[nodiscard]] constexpr reference back() noexcept\n\t{\n\t\treturn (*this)[static_cast<index>(size()) - 1];\n\t}\n\t[[nodiscard]] constexpr reference operator[](const index elem) noexcept\n\t{\n\t\treturn board_[location(elem)];\n\t}\n\t[[nodiscard]] constexpr T const& operator[](const index elem) const noexcept\n\t{\n\t\treturn board_[location(elem)];\n\t}\n\t// Checked access\n\t[[nodiscard]] constexpr reference at(const index elem);\n\n\tconstexpr iterator begin() noexcept { return iterator(&board_, id_, 0); }\n\tconstexpr iterator end() noexcept { return iterator(&board_, id_, size()); }\n\t[[nodiscard]] constexpr const_iterator cbegin() const noexcept\n\t{\n\t\treturn const_iterator(&board_, id_, 0);\n\t}\n\t[[nodiscard]] constexpr const_iterator cend() const noexcept\n\t{\n\t\treturn const_iterator(&board_, id_, size());\n\t}\n\t[[nodiscard]] constexpr const_iterator begin() const noexcept\n\t{\n\t\treturn cbegin();\n\t}\n\t[[nodiscard]] constexpr const_iterator end() const noexcept\n\t{\n\t\treturn cend();\n\t}\n\tconstexpr reverse_iterator rbegin() noexcept\n\t{\n\t\treturn reverse_iterator(&board_, id_, size() - 1);\n\t}\n\tconstexpr reverse_iterator rend() noexcept\n\t{\n\t\treturn reverse_iterator(&board_, id_, -1);\n\t}\n\t[[nodiscard]] constexpr const_reverse_iterator crbegin() const noexcept\n\t{\n\t\treturn const_reverse_iterator(&board_, id_, size() - 1);\n\t}\n\t[[nodiscard]] constexpr const_reverse_iterator crend() const noexcept\n\t{\n\t\treturn const_reverse_iterator(&board_, id_, -1);\n\t}\n\t[[nodiscard]] constexpr const_reverse_iterator rbegin() const noexcept\n\t{\n\t\treturn crbegin();\n\t}\n\t[[nodiscard]] constexpr const_reverse_iterator rend() const noexcept\n\t{\n\t\treturn crend();\n\t}\n\nprivate:\n\tOwnerT board_;\n\tconst gsl::index id_{};\n\n\t// Internal helper\n\tstatic constexpr gsl::index to_id(Location loc) noexcept;\n};\n\n//====--------------------------------------------------------------------====//\n// Member Functions\n\n// Checked access\ntemplate<typename T, int N, Section S, bool is_const>\n[[nodiscard]] inline constexpr\n\ttypename Board_Section_<T, N, S, is_const>::reference\n\tBoard_Section_<T, N, S, is_const>::at(const index elem)\n{\n\tif (!is_valid_size<N>(elem))\n\t{\n\t\tthrow error::invalid_Location{\"Board_Section::at(elem)\"};\n\t}\n\treturn board_.at(location(elem));\n}\n\ntemplate<typename T, int N, Section S, bool is_const>\n[[nodiscard]] constexpr Location<N>\n\tBoard_Section_<T, N, S, is_const>::location(index elem) const noexcept\n{\n\tassert(is_valid_size<N>(elem));\n\tswitch (S)\n\t{\n\tcase Section::row: return Location(id_, elem);\n\tcase Section::col: return Location(elem, id_);\n\tcase Section::block: return Location_Block(id_, elem);\n\t}\n}\n\n// Internal helper\ntemplate<typename T, int N, Section S, bool is_const>\ninline constexpr gsl::index\n\tBoard_Section_<T, N, S, is_const>::to_id(Location loc) noexcept\n{\n\tswitch (S)\n\t{\n\tcase Section::row: return loc.row();\n\tcase Section::col: return loc.col();\n\tcase Section::block: return loc.block();\n\t}\n}\n\n} // namespace Sudoku::Board_Section\n", "meta": {"hexsha": "18983960b85df3b63d0358500e8752a0e7a5638c", "size": 5874, "ext": "h", "lang": "C", "max_stars_repo_path": "Sudoku/Sudoku/Board_Section.h", "max_stars_repo_name": "FeodorFitsner/fwkSudoku", "max_stars_repo_head_hexsha": "760aa5731efe089dc08e51898a37d42f3db5bb10", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Sudoku/Sudoku/Board_Section.h", "max_issues_repo_name": "FeodorFitsner/fwkSudoku", "max_issues_repo_head_hexsha": "760aa5731efe089dc08e51898a37d42f3db5bb10", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sudoku/Sudoku/Board_Section.h", "max_forks_repo_name": "FeodorFitsner/fwkSudoku", "max_forks_repo_head_hexsha": "760aa5731efe089dc08e51898a37d42f3db5bb10", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4352331606, "max_line_length": 80, "alphanum_fraction": 0.6850527749, "num_tokens": 1453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073333856566001, "lm_q2_score": 0.04336579381848507, "lm_q1q2_score": 0.017664335617769585}}
{"text": "/***************************************************************************/\n/*                                                                         */\n/* matrix.h - Matrix class for mruby                                       */\n/* Copyright (C) 2015 Paolo Bosetti                                        */\n/* paolo[dot]bosetti[at]unitn.it                                           */\n/* Department of Industrial Engineering, University of Trento              */\n/*                                                                         */\n/* This library is free software.  You can redistribute it and/or          */\n/* modify it under the terms of the GNU GENERAL PUBLIC LICENSE 2.0.        */\n/*                                                                         */\n/* This library is distributed in the hope that it will be useful,         */\n/* but WITHOUT ANY WARRANTY; without even the implied warranty of          */\n/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the           */\n/* Artistic License 2.0 for more details.                                  */\n/*                                                                         */\n/* See the file LICENSE                                                    */\n/*                                                                         */\n/***************************************************************************/\n\n#ifndef MATRIX_H\n#define MATRIX_H\n\n#include <stdlib.h>\n#include <string.h>\n#include <errno.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <sys/param.h>\n#include <time.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n\n#include \"mruby.h\"\n#include \"mruby/variable.h\"\n#include \"mruby/string.h\"\n#include \"mruby/data.h\"\n#include \"mruby/class.h\"\n#include \"mruby/value.h\"\n#include \"mruby/array.h\"\n#include \"mruby/numeric.h\"\n#include \"mruby/compile.h\"\n\n#define E_MATRIX_ERROR (mrb_class_get(mrb, \"MatrixError\"))\n\n/***********************************************\\\n MATRICES\n\\***********************************************/\n\n// Garbage collector handler, for play_data struct\n// if play_data contains other dynamic data, free it too!\n// Check it with GC.start\nvoid matrix_destructor(mrb_state *mrb, void *p_);\n\n// Utility function for getting the struct out of the wrapping IV @data\nvoid mrb_matrix_get_data(mrb_state *mrb, mrb_value self, gsl_matrix **data);\n\nvoid mrb_gsl_matrix_init(mrb_state *mrb);\n\n#endif // MATRIX_H", "meta": {"hexsha": "d9d8cb637a964715723978128b623321e0c4c33c", "size": 2451, "ext": "h", "lang": "C", "max_stars_repo_path": "src/matrix.h", "max_stars_repo_name": "UniTN-Mechatronics/mruby-gsl", "max_stars_repo_head_hexsha": "0961ef3b88bb8ed9e9223b2678ece281acaa0f4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/matrix.h", "max_issues_repo_name": "UniTN-Mechatronics/mruby-gsl", "max_issues_repo_head_hexsha": "0961ef3b88bb8ed9e9223b2678ece281acaa0f4b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/matrix.h", "max_forks_repo_name": "UniTN-Mechatronics/mruby-gsl", "max_forks_repo_head_hexsha": "0961ef3b88bb8ed9e9223b2678ece281acaa0f4b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.85, "max_line_length": 77, "alphanum_fraction": 0.4638922889, "num_tokens": 428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3557749071749625, "lm_q2_score": 0.04958901736570397, "lm_q1q2_score": 0.017642528050180937}}
{"text": "#ifndef bcfunctions_h\n#define bcfunctions_h\n\n#include <petsc.h>\n\nPetscErrorCode BCsDiff(PetscInt dim, PetscReal time, const PetscReal x[],\n                       PetscInt num_comp_u, PetscScalar *u, void *ctx);\nPetscErrorCode BCsMass(PetscInt dim, PetscReal time, const PetscReal x[],\n                       PetscInt num_comp_u, PetscScalar *u, void *ctx);\n\n#endif // bcfunctions_h\n", "meta": {"hexsha": "b272a64db6da1b4d5e702712e7c1f67b380bfd06", "size": 382, "ext": "h", "lang": "C", "max_stars_repo_path": "examples/petsc/include/bcfunctions.h", "max_stars_repo_name": "AdelekeBankole/libCEED", "max_stars_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 123.0, "max_stars_repo_stars_event_min_datetime": "2018-01-29T02:04:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T18:13:48.000Z", "max_issues_repo_path": "examples/petsc/include/bcfunctions.h", "max_issues_repo_name": "AdelekeBankole/libCEED", "max_issues_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 781.0, "max_issues_repo_issues_event_min_datetime": "2017-12-22T17:20:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T21:34:34.000Z", "max_forks_repo_path": "examples/petsc/include/bcfunctions.h", "max_forks_repo_name": "AdelekeBankole/libCEED", "max_forks_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2017-12-27T22:35:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:02:07.000Z", "avg_line_length": 31.8333333333, "max_line_length": 73, "alphanum_fraction": 0.6884816754, "num_tokens": 96, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3451052709578724, "lm_q2_score": 0.051082737679360814, "lm_q1q2_score": 0.01762892202810573}}
{"text": "/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*\n**                                                                                  **\n** This file forms part of the Underworld geophysics modelling application.         **\n**                                                                                  **\n** For full license and copyright information, please refer to the LICENSE.md file  **\n** located at the project root, or contact the authors.                             **\n**                                                                                  **\n**~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/\n#include <petsc.h>\n#include <petscmat.h>\n\n#include \"common-driver-utils.h\"\n\n#include <StGermain/libStGermain/src/StGermain.h>\n#include <StgDomain/libStgDomain/src/StgDomain.h>\n#include <StgFEM/libStgFEM/src/StgFEM.h>\n#include <PICellerator/libPICellerator/src/PICellerator.h>\n#include <Underworld/libUnderworld/src/Underworld.h>\n#include \"Solvers/SLE/src/SLE.h\" /* to give the AugLagStokes_SLE type */\n#include \"Solvers/KSPSolvers/src/KSPSolvers.h\" /* for __KSP_COMMON */\n#include \"BSSCR.h\"\n#include \"writeMatVec.h\"\n\n#if( (PETSC_VERSION_MAJOR==2) && (PETSC_VERSION_MINOR==3) && (PETSC_VERSION_SUBMINOR==0) )\n#define FILE_OPTION PETSC_FILE_RDONLY\n#endif\n#if( (PETSC_VERSION_MAJOR==2) && (PETSC_VERSION_MINOR==3) && (PETSC_VERSION_SUBMINOR>=2) )\n#define FILE_OPTION FILE_MODE_READ\n#endif\n#if( PETSC_VERSION_MAJOR==3 )\n#define FILE_OPTION FILE_MODE_READ\n#endif\n\n\nPetscErrorCode BSSCR_FormSchurApproximation1( Mat A11, Mat A12, Mat A21, Mat A22, Mat *_Shat, PetscTruth sym );\nPetscErrorCode BSSCR_FormSchurApproximationDiag( Mat A11, Mat A12, Mat A21, Mat A22, Mat *_Shat, PetscTruth sym );\n\nPetscErrorCode BSSCR_BSSCR_StokesReadPCSchurMat_binary( MPI_Comm comm, Mat *S )\n{\n\tPetscViewer mat_view_file;\n\tchar\top_name[PETSC_MAX_PATH_LEN];\n\tPetscTruth flg;\n\n\tPetscOptionsGetString( PETSC_NULL,\"-stokes_Smat\",op_name,PETSC_MAX_PATH_LEN-1,&flg );\n\t*S = PETSC_NULL;\n\tif (flg) {\n\t\tif (!S)\tStg_SETERRQ(1,\"Memory space for Smat is NULL\");\n\n\t\tPetscViewerBinaryOpen( comm, op_name,  FILE_OPTION, &mat_view_file );\n\t\tStg_MatLoad( mat_view_file, MATAIJ, S );\n\t\tStg_PetscViewerDestroy(&mat_view_file );\n\t}\n\n\tPetscFunctionReturn(0);\n}\n\nPetscErrorCode BSSCR_BSSCR_StokesReadPCSchurMat_ascii( MPI_Comm comm, Mat *S )\n{\n\tchar\top_name[PETSC_MAX_PATH_LEN];\n\tPetscTruth flg;\n\n\tPetscOptionsGetString( PETSC_NULL,\"-stokes_Smat\",op_name,PETSC_MAX_PATH_LEN-1,&flg );\n\t*S = PETSC_NULL;\n\tif (flg) {\n\t\tif (!S)\tStg_SETERRQ(1,\"Memory space for Smat is NULL\");\n\t\tStg_SETERRQ(1,\"Currently Disabled\");\n\t\t//MatAIJLoad_MatrixMarket( comm, op_name, S );\n\t}\n\n\tPetscFunctionReturn(0);\n}\n\n\nPetscErrorCode BSSCR_StokesReadPCSchurMat( MPI_Comm comm, Mat *S )\n{\n\tchar\top_name[PETSC_MAX_PATH_LEN];\n\tPetscTruth flg;\n\n\n\tPetscOptionsGetString( PETSC_NULL,\"-stokes_ascii\",op_name,PETSC_MAX_PATH_LEN-1,&flg );\n\tif (flg==PETSC_TRUE) {\n\t\tBSSCR_BSSCR_StokesReadPCSchurMat_ascii( comm, S );\n\t}\n\telse {\n\t\tBSSCR_BSSCR_StokesReadPCSchurMat_binary( comm, S );\n\t}\n\n\tPetscFunctionReturn(0);\n}\n\n\n\n\nPetscErrorCode BSSCR_StokesCreatePCSchur( Mat K, Mat G, PC pc_S )\n{\n\tchar pc_type[PETSC_MAX_PATH_LEN];\n\tPetscTruth flg;\n\n\n\tPetscOptionsGetString( PETSC_NULL, \"-Q22_pc_type\", pc_type, PETSC_MAX_PATH_LEN-1, &flg );\n\tif( !flg ) {\n\t\tStg_SETERRQ( PETSC_ERR_SUP, \"OPTION: -Q22_pc_type must be set\" );\n\t}\n\n\n\t/* 1. define S pc to be \"none\" */\n\n\tif( strcmp(pc_type,\"none\")==0 ) { /* none */\n\t\tPetscPrintf(PETSC_COMM_WORLD,\"  Setting schur_pc to \\\"none\\\" \\n\" );\n\t\tPCSetType( pc_S, \"none\" );\n\t}\n\telse if( strcmp(pc_type,\"uw\")==0 ) { /* diag */\n\t\tMat S, Amat;\n\t\tMatStructure mstruct;\n\t\tMPI_Comm comm;\n\n\t\tPetscPrintf(PETSC_COMM_WORLD,\"  Setting schur_pc to \\\"uw\\\" \\n\" );\n\n\t\tPetscObjectGetComm( (PetscObject)pc_S, &comm );\n\t\tS = PETSC_NULL;\n\t\tBSSCR_StokesReadPCSchurMat( comm, &S );\n\t\tif (!S) {\tStg_SETERRQ(1,\"Must indicate location of file for SchurPC matrix with the stokes_Smat option\");\t}\n\n\t\tStg_PCGetOperators( pc_S, &Amat, &Amat, &mstruct );\n\t\tStg_PCSetOperators( pc_S, Amat, S, SAME_NONZERO_PATTERN );\n\n\t\tMatView( S, PETSC_VIEWER_STDOUT_WORLD );\n\t}\n\telse { /* not valid option */\n\t\tStg_SETERRQ( PETSC_ERR_SUP, \"OPTION: -seg_schur_pc_type is not valid\" );\n\t}\n\n\tPetscFunctionReturn(0);\n}\n\n\n\nPetscErrorCode BSSCR_BSSCR_StokesCreatePCSchur2(\n   Mat K, Mat G, Mat D, Mat C, Mat Smat, PC pc_S,\n   PetscTruth sym, KSP_BSSCR * bsscrp )\n{\n\tchar pc_type[PETSC_MAX_PATH_LEN];\n\tPetscTruth flg;\n\n\n\tPetscOptionsGetString( PETSC_NULL, \"-Q22_pc_type\", pc_type, PETSC_MAX_PATH_LEN-1, &flg );\n\tif( !flg ) {\n\t    strcpy(pc_type, \"uw\");\n\t    //Stg_SETERRQ( PETSC_ERR_SUP, \"OPTION: -Q22_pc_type must be set\" );\n\t}\n\n\n\t/* 1. define S pc to be \"none\" */\n\n\tif( strcmp(pc_type,\"none\")==0 ) { /* none */\n\t\t/* Mat Amat,Pmat; */\n\t\t/* MatStructure mstruct; */\n\n\t\tPetscPrintf(PETSC_COMM_WORLD,\"  Setting schur_pc to \\\"none\\\" \\n\" );\n\t\t/* PCGetOperators( pc_S, &Amat, &Pmat, &mstruct ); */\n\t\t/* PCSetOperators( pc_S, Amat, Amat, SAME_NONZERO_PATTERN ); */\n\t\tPCSetType( pc_S, \"none\" );\n\t}\n\telse if( strcmp(pc_type,\"uw\")==0 ) { /* diag */\n\t    Mat Amat,Pmat;\n\t\tMatStructure mstruct;\n\n\t\tPetscPrintf(PETSC_COMM_WORLD,\"  Setting schur_pc to \\\"uw\\\" \\n\" );\n\n\t\tif (!Smat) {\tStg_SETERRQ(1,\"Smat cannot be NULL if -Q22_pc_type = uw\");\t}\n\n\t\tStg_PCGetOperators( pc_S, &Amat, &Pmat, &mstruct );\n\t\tStg_PCSetOperators( pc_S, Amat, Smat, SAME_NONZERO_PATTERN );\n\t}\n\telse if( strcmp(pc_type,\"uwscale\")==0 ) { /* diag */\n\t    Mat Amat, Shat, Pmat;\n\t\tMatStructure mstruct;\n\n\t\tPetscPrintf(PETSC_COMM_WORLD,\"  Setting schur_pc to \\\"uwscale\\\" \\n\" );\n\n\t\tif (!Smat) {\tStg_SETERRQ(1,\"Smat cannot be NULL if -Q22_pc_type = uwscale\");\t}\n\n\t\tBSSCR_FormSchurApproximation1( K, G, D, C, &Shat, sym );\n\n\t\tStg_PCGetOperators( pc_S, &Amat, &Pmat, &mstruct );\n\t\tStg_PCSetOperators( pc_S, Amat, Shat, SAME_NONZERO_PATTERN );\n\n\t\tStg_MatDestroy(&Shat);\n\t}\n\telse if( strcmp(pc_type,\"gkgdiag\")==0 ) { /* diag */\n\t    Mat Amat, Shat, Pmat;\n\t\tMatStructure mstruct;\n\n\t\tPetscPrintf(PETSC_COMM_WORLD,\"  Setting schur_pc to \\\"gkgdiag\\\" \\n\" );\n\n\t\tif (!Smat) {\tStg_SETERRQ(1,\"Smat cannot be NULL if -Q22_pc_type = uwscale\");\t}\n\n\t\tBSSCR_FormSchurApproximationDiag( K, G, D, C, &Shat, sym );\n\n\t\tStg_PCGetOperators( pc_S, &Amat, &Pmat, &mstruct );\n\t\tStg_PCSetOperators( pc_S, Amat, Shat, SAME_NONZERO_PATTERN );\n\n\t\tStg_MatDestroy(&Shat);\n\t}\n\telse if( strcmp(pc_type,\"gtkg\")==0 ) { /* GtKG */\n\t    PetscPrintf(PETSC_COMM_WORLD,\"  Setting schur_pc to \\\"gtkg\\\" \\n\" );\n\n\t    /* Build the schur pc GtKG */\n\t    PCSetType( pc_S, \"gtkg\" );\n\t    //AugLagStokes_SLE * stokesSLE = (AugLagStokes_SLE*)bsscrp->st_sle;\n        StokesBlockKSPInterface* Solver = bsscrp->solver;\n\t    Mat M=0;\n\t    if (Solver->vmStiffMat){\n\t\tM = Solver->vmStiffMat->matrix;\n\t    }\n\t    BSSCR_PCGtKGSet_Operators( pc_S, K, G, M );\n\t    //BSSCR_PCGtKGAttachNullSpace( pc_S );\n\t}\n\telse { /* not valid option */\n\t\tStg_SETERRQ( PETSC_ERR_SUP, \"OPTION: -Q22_pc_type is not valid\" );\n\t}\n\n\tPetscFunctionReturn(0);\n}\n\n\n\n/*\n\nRecomended usage:\n\nStg_KSPSetOperators( ksp_S, S, Shat, SAME_NONZERO_PATTERN );\n\nKSPGetPC( ksp_S, &pc_S );\nPCSetType( pc_S, \"jacobi\" );\n\n\nNOTE: In pracise \"jacobi\" works better than keep the entire matrix and\nfactoring it using something like \"cholesky\"\n\n*/\nPetscErrorCode BSSCR_FormSchurApproximation1( Mat A11, Mat A12, Mat A21, Mat A22, Mat *_Shat, PetscTruth sym )\n{\n   Mat Shat, A21_cpy;\n   Vec diag;\n\n   MatGetVecs( A11, &diag, PETSC_NULL );\n   MatGetDiagonal( A11, diag );\n   VecReciprocal( diag );\n\n/*    if( sym ) { */\n/* #if( PETSC_VERSION_MAJOR <= 2 ) */\n/*       MatTranspose( A12, &A21_cpy ); */\n/* #else */\n/*       MatTranspose( A12, MAT_INITIAL_MATRIX, &A21_cpy ); */\n/* #endif */\n/*       MatDiagonalScale(A21_cpy, PETSC_NULL, diag ); */\n/*    } */\n/*    else { */\n      MatDuplicate( A21, MAT_COPY_VALUES, &A21_cpy );\n      MatDiagonalScale(A21_cpy, PETSC_NULL, diag );\n   /* } */\n\n   MatMatMult( A21_cpy, A12, MAT_INITIAL_MATRIX, 1.2, &Shat );  /* A21 diag(K)^{-1} A12 */\n\n   if( A22 != PETSC_NULL )\n      MatAXPY( Shat, -1.0, A22, DIFFERENT_NONZERO_PATTERN ); /* S <- -C + A21 diag(K)^{-1} A12 */\n\n   *(void**)_Shat = (void*)Shat;\n\n   Stg_MatDestroy(&A21_cpy);\n   Stg_VecDestroy(&diag);\n\n   PetscFunctionReturn(0);\n}\n\nPetscErrorCode BSSCR_FormSchurApproximationDiag( Mat A11, Mat A12, Mat A21, Mat A22, Mat *_Shat, PetscTruth sym )\n{\n   Mat Shat, A21_cpy;\n   Vec diag;\n\n   MatGetVecs( A11, &diag, PETSC_NULL );\n   MatGetDiagonal( A11, diag );\n   VecReciprocal( diag );\n\n/*    if( sym ) { */\n/* #if( PETSC_VERSION_MAJOR <= 2 ) */\n/*       MatTranspose( A12, &A21_cpy ); */\n/* #else */\n/*       MatTranspose( A12, MAT_INITIAL_MATRIX, &A21_cpy ); */\n/* #endif */\n/*       MatDiagonalScale(A21_cpy, PETSC_NULL, diag ); */\n/*    } */\n/*    else { */\n      MatDuplicate( A21, MAT_COPY_VALUES, &A21_cpy );\n      MatDiagonalScale(A21_cpy, PETSC_NULL, diag );\n   /* } */\n\n   MatMatMult( A21_cpy, A12, MAT_INITIAL_MATRIX, 1.2, &Shat );  /* A21 diag(K)^{-1} A12 */\n\n   if( A22 != PETSC_NULL )\n      MatAXPY( Shat, -1.0, A22, DIFFERENT_NONZERO_PATTERN ); /* S <- -C + A21 diag(K)^{-1} A12 */\n\n\n   Stg_MatDestroy(&A21_cpy);\n   Stg_VecDestroy(&diag);\n\n   MatGetVecs( Shat, &diag, PETSC_NULL );\n   MatGetDiagonal( Shat, diag );\n\n   MatZeroEntries( Shat );\n   MatDiagonalSet( Shat, diag, INSERT_VALUES );\n\n   *(void**)_Shat = (void*)Shat;\n\n   Stg_VecDestroy(&diag);\n\n   PetscFunctionReturn(0);\n}\n", "meta": {"hexsha": "082d973755bf70ac924f065f7c749f947976c5e0", "size": 9424, "ext": "c", "lang": "C", "max_stars_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/preconditioner.c", "max_stars_repo_name": "rbeucher/underworld2", "max_stars_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/preconditioner.c", "max_issues_repo_name": "rbeucher/underworld2", "max_issues_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/preconditioner.c", "max_forks_repo_name": "rbeucher/underworld2", "max_forks_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.45, "max_line_length": 114, "alphanum_fraction": 0.6495118846, "num_tokens": 3256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4111108836623764, "lm_q2_score": 0.04272219663237114, "lm_q1q2_score": 0.017563560009531902}}
{"text": "#ifndef PyGSL_COMPLEX_HELPERS_H\n#define PyGSL_COMPLEX_HELPERS_H 1\n#include <pygsl/utils.h>\n#include <pygsl/intern.h>\n#include <gsl/gsl_complex.h>\n#include <gsl/gsl_errno.h>\n\n/*\n *  These macros convert a PyObect to  a complex if numeric \n *  Input recieved. If complex, accessing the data, otherwise\n *  reverting to a function.\n */\n/* -------------------------------------------------------------------------\n   Helper Functions\n   ------------------------------------------------------------------------- */\nPyGSL_API_EXTERN int\nPyGSL_PyComplex_to_gsl_complex(PyObject * src, gsl_complex * mycomplex);\n\nPyGSL_API_EXTERN int\nPyGSL_PyComplex_to_gsl_complex_float(PyObject * src, \n\t\t\t\t     gsl_complex_float * mycomplex);\nPyGSL_API_EXTERN int \nPyGSL_PyComplex_to_gsl_complex_long_double(PyObject * src, \n\t\t\t\t\t   gsl_complex_long_double * mycomplex);\n\n#ifndef _PyGSL_API_MODULE\n#define PyGSL_PyComplex_to_gsl_complex \\\n(*(int (*) (PyObject *, gsl_complex *))              PyGSL_API[PyGSL_PyComplex_to_gsl_complex_NUM])\n#define PyGSL_PyComplex_to_gsl_complex_float \\\n(*(int (*) (PyObject *, gsl_complex_float *))        PyGSL_API[PyGSL_PyComplex_to_gsl_complex_float_NUM])\n#define PyGSL_PyComplex_to_gsl_complex_long_double \\\n(*(int (*) (PyObject *, gsl_complex_long_double *))  PyGSL_API[PyGSL_PyComplex_to_gsl_complex_long_double_NUM])\n#endif /* _PyGSL_API_MODULE */\n\n#define PyGSL_PyCOMPLEX_TO_gsl_complex(object, tmp)            \\\n(PyComplex_Check((object))) ? \t\t\t\t       \\\n     ((tmp)->dat[0] = ((PyComplexObject *)(object))->cval.real,\\\n      (tmp)->dat[1] = ((PyComplexObject *)(object))->cval.imag,\\\n      GSL_SUCCESS) \t\t\t\t\t       \\\n     : PyGSL_PyComplex_to_gsl_complex(object, tmp)         \n\n#define PyGSL_PyCOMPLEX_TO_gsl_complex_float(object, tmp )     \\\n(PyComplex_Check((object))) ?                                  \\\n     ((tmp)->dat[0] = ((PyComplexObject *)(object))->cval.real,\\\n      (tmp)->dat[1] = ((PyComplexObject *)(object))->cval.imag,\\\n      GSL_SUCCESS)                                             \\\n     : PyGSL_PyComplex_to_gsl_complex_float(object, tmp)      \n\n#define PyGSL_PyCOMPLEX_TO_gsl_complex_long_double(object, tmp ) \\\n(PyComplex_Check((object))) ?                                     \\\n     ((tmp)->dat[0] = ((PyComplexObject *)(object))->cval.real,  \\\n      (tmp)->dat[1] = ((PyComplexObject *)(object))->cval.imag,  \\\n      GSL_SUCCESS)                                               \\\n     : PyGSL_PyComplex_to_gsl_complex_long_double(object, tmp)\n\n#endif  /* PyGSL_COMPLEX_HELPERS_H */\n", "meta": {"hexsha": "1719003716c8f38ffc1546da07d53affdaadaa58", "size": 2526, "ext": "h", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/Include/pygsl/complex_helpers.h", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/Include/pygsl/complex_helpers.h", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/Include/pygsl/complex_helpers.h", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 44.3157894737, "max_line_length": 111, "alphanum_fraction": 0.6219319082, "num_tokens": 630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936414516010196, "lm_q2_score": 0.04885777896840857, "lm_q1q2_score": 0.017557733973403353}}
{"text": "// @file utils.h\n//\n//  \\date Created on: Sep 23, 2017\n//  \\author Gopalakrishna Hegde\n//\n//   Description:\n//\n//\n//\n\n#ifndef INC_UTILS_H_\n#define INC_UTILS_H_\n#include \"common_types.h\"\n#include <cblas.h>\n\nvoid PrintMat(char *name, const float *ptr, int H, int W, CBLAS_LAYOUT layout);\nvoid RandInitF32(float *p_data, int N);\nvoid SeqInitF32(float *p_data, int N);\nvoid PrintTensor(const float *data, TensorDim dim);\nint TensorSize(TensorDim dim);\nbool TensorCompare(const float *t1, const float *t2, TensorDim dim);\n#endif  // INC_UTILS_H_\n", "meta": {"hexsha": "7a2c7002d195dad371ffb732f11f089f377db257", "size": 541, "ext": "h", "lang": "C", "max_stars_repo_path": "inc/utils.h", "max_stars_repo_name": "gplhegde/convolution-flavors", "max_stars_repo_head_hexsha": "c5f612d35888e224aa610408a7fc9f08f232147c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 54.0, "max_stars_repo_stars_event_min_datetime": "2017-10-03T18:10:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T06:38:50.000Z", "max_issues_repo_path": "inc/utils.h", "max_issues_repo_name": "chayitw/convolution-flavors", "max_issues_repo_head_hexsha": "c5f612d35888e224aa610408a7fc9f08f232147c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-10-16T02:49:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-16T02:49:23.000Z", "max_forks_repo_path": "inc/utils.h", "max_forks_repo_name": "chayitw/convolution-flavors", "max_forks_repo_head_hexsha": "c5f612d35888e224aa610408a7fc9f08f232147c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2017-10-24T05:17:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T14:16:14.000Z", "avg_line_length": 23.5217391304, "max_line_length": 79, "alphanum_fraction": 0.7208872458, "num_tokens": 160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.2598256379609836, "lm_q2_score": 0.06754669724011828, "lm_q1q2_score": 0.017550363702571143}}
{"text": "/* vector/gsl_vector_double.h\n *\n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_VECTOR_DOUBLE_H__\n#define __GSL_VECTOR_DOUBLE_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/block/gsl_check_range.h>\n#include <gsl/block/gsl_block_double.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct\n{\n  size_t size;\t\t//the number of elements in this vector\n  size_t stride;\t//in the block pointer, this indicates the spacing between elements\n  double *data;\t\t//a pointer to the data in this vector\n  gsl_block *block;\t//a pointer to the block that the data belongs to\n  int owner;\t\t//if this is 1 it means that this vector is the owner of this block, otherwise it means it inherited it from somewhere else and it shouldn't be deallocated with the vector\n}\ngsl_vector;\n\ntypedef struct\n{\n  gsl_vector vector;\n} _gsl_vector_view;\n\ntypedef _gsl_vector_view gsl_vector_view;\n\ntypedef struct\n{\n  gsl_vector vector;\n} _gsl_vector_const_view;\n\ntypedef const _gsl_vector_const_view gsl_vector_const_view;\n\n\n/* Allocation */\n\nGSL_FUNC gsl_vector *gsl_vector_alloc (const size_t n);\nGSL_FUNC gsl_vector *gsl_vector_calloc (const size_t n);\n\nGSL_FUNC gsl_vector *gsl_vector_alloc_from_block (gsl_block * b,\n                                                     const size_t offset,\n                                                     const size_t n,\n                                                     const size_t stride);\n\nGSL_FUNC gsl_vector *gsl_vector_alloc_from_vector (gsl_vector * v,\n                                                      const size_t offset,\n                                                      const size_t n,\n                                                      const size_t stride);\n\nGSL_FUNC void gsl_vector_free (gsl_vector * v);\n\n/* Views */\n\nGSL_FUNC _gsl_vector_view\ngsl_vector_view_array (double *v, size_t n);\n\nGSL_FUNC _gsl_vector_view\ngsl_vector_view_array_with_stride (double *base,\n                                         size_t stride,\n                                         size_t n);\n\nGSL_FUNC _gsl_vector_const_view\ngsl_vector_const_view_array (const double *v, size_t n);\n\nGSL_FUNC _gsl_vector_const_view\ngsl_vector_const_view_array_with_stride (const double *base,\n                                               size_t stride,\n                                               size_t n);\n\nGSL_FUNC _gsl_vector_view\ngsl_vector_subvector (gsl_vector *v,\n                            size_t i,\n                            size_t n);\n\nGSL_FUNC _gsl_vector_view\ngsl_vector_subvector_with_stride (gsl_vector *v,\n                                        size_t i,\n                                        size_t stride,\n                                        size_t n);\n\nGSL_FUNC _gsl_vector_const_view\ngsl_vector_const_subvector (const gsl_vector *v,\n                                  size_t i,\n                                  size_t n);\n\nGSL_FUNC _gsl_vector_const_view\ngsl_vector_const_subvector_with_stride (const gsl_vector *v,\n                                              size_t i,\n                                              size_t stride,\n                                              size_t n);\n\n/* Operations */\n\nGSL_FUNC double gsl_vector_get (const gsl_vector * v, const size_t i);\nGSL_FUNC void gsl_vector_set (gsl_vector * v, const size_t i, double x);\n\nGSL_FUNC double *gsl_vector_ptr (gsl_vector * v, const size_t i);\nGSL_FUNC const double *gsl_vector_const_ptr (const gsl_vector * v, const size_t i);\n\nGSL_FUNC void gsl_vector_set_zero (gsl_vector * v);\nGSL_FUNC void gsl_vector_set_all (gsl_vector * v, double x);\nGSL_FUNC int gsl_vector_set_basis (gsl_vector * v, size_t i);\n\nGSL_FUNC int gsl_vector_fread (FILE * stream, gsl_vector * v);\nGSL_FUNC int gsl_vector_fwrite (FILE * stream, const gsl_vector * v);\nGSL_FUNC int gsl_vector_fscanf (FILE * stream, gsl_vector * v);\nGSL_FUNC int gsl_vector_fprintf (FILE * stream, const gsl_vector * v,\n                              const char *format);\n\nGSL_FUNC int gsl_vector_memcpy (gsl_vector * dest, const gsl_vector * src);\n\nGSL_FUNC int gsl_vector_reverse (gsl_vector * v);\n\nGSL_FUNC int gsl_vector_swap (gsl_vector * v, gsl_vector * w);\nGSL_FUNC int gsl_vector_swap_elements (gsl_vector * v, const size_t i, const size_t j);\n\nGSL_FUNC double gsl_vector_max (const gsl_vector * v);\nGSL_FUNC double gsl_vector_min (const gsl_vector * v);\nGSL_FUNC void gsl_vector_minmax (const gsl_vector * v, double * min_out, double * max_out);\n\nGSL_FUNC size_t gsl_vector_max_index (const gsl_vector * v);\nGSL_FUNC size_t gsl_vector_min_index (const gsl_vector * v);\nGSL_FUNC void gsl_vector_minmax_index (const gsl_vector * v, size_t * imin, size_t * imax);\n\nGSL_FUNC int gsl_vector_add (gsl_vector * a, const gsl_vector * b);\nGSL_FUNC int gsl_vector_sub (gsl_vector * a, const gsl_vector * b);\nGSL_FUNC int gsl_vector_mul (gsl_vector * a, const gsl_vector * b);\nGSL_FUNC int gsl_vector_div (gsl_vector * a, const gsl_vector * b);\nGSL_FUNC int gsl_vector_scale (gsl_vector * a, const double x);\nGSL_FUNC int gsl_vector_add_constant (gsl_vector * a, const double x);\n\nGSL_FUNC int gsl_vector_isnull (const gsl_vector * v);\nGSL_FUNC int gsl_vector_ispos (const gsl_vector * v);\nGSL_FUNC int gsl_vector_isneg (const gsl_vector * v);\n\n#ifdef HAVE_INLINE\n\nextern inline\ndouble\ngsl_vector_get (const gsl_vector * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_VAL (\"index out of range\", GSL_EINVAL, 0);\n    }\n#endif\n  return v->data[i * v->stride];\n}\n\nextern inline\nvoid\ngsl_vector_set (gsl_vector * v, const size_t i, double x)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_VOID (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  v->data[i * v->stride] = x;\n}\n\nextern inline\ndouble *\ngsl_vector_ptr (gsl_vector * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return (double *) (v->data + i * v->stride);\n}\n\nextern inline\nconst double *\ngsl_vector_const_ptr (const gsl_vector * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return (const double *) (v->data + i * v->stride);\n}\n\n\n#endif /* HAVE_INLINE */\n\n__END_DECLS\n\n#endif /* __GSL_VECTOR_DOUBLE_H__ */\n\n\n", "meta": {"hexsha": "436283bfa40c1e8487c1e2c9c9b65ae9e9ef13a5", "size": 7232, "ext": "h", "lang": "C", "max_stars_repo_path": "Cartwheel/cartwheel-3d/gsl/vector/gsl_vector_double.h", "max_stars_repo_name": "MontyThibault/centre-of-mass-awareness", "max_stars_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Cartwheel/cartwheel-3d/gsl/vector/gsl_vector_double.h", "max_issues_repo_name": "MontyThibault/centre-of-mass-awareness", "max_issues_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cartwheel/cartwheel-3d/gsl/vector/gsl_vector_double.h", "max_forks_repo_name": "MontyThibault/centre-of-mass-awareness", "max_forks_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7192982456, "max_line_length": 185, "alphanum_fraction": 0.6633019912, "num_tokens": 1763, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.03904829705959319, "lm_q1q2_score": 0.01754801708697311}}
{"text": "#ifndef setupdm_h\n#define setupdm_h\n\n#include <ceed.h>\n#include <petsc.h>\n#include <petscdmplex.h>\n#include <petscfe.h>\n#include \"../include/structs.h\"\n\n// -----------------------------------------------------------------------------\n// Setup DM\n// -----------------------------------------------------------------------------\nPetscErrorCode CreateBCLabel(DM dm, const char name[]);\n\n// Create FE by degree\nPetscErrorCode PetscFECreateByDegree(DM dm, PetscInt dim, PetscInt Nc,\n                                     PetscBool is_simplex, const char prefix[],\n                                     PetscInt order, PetscFE *fem);\n\n// Read mesh and distribute DM in parallel\nPetscErrorCode CreateDistributedDM(MPI_Comm comm, AppCtx app_ctx, DM *dm);\n\n// Setup DM with FE space of appropriate degree\nPetscErrorCode SetupDMByDegree(DM dm, AppCtx app_ctx, PetscInt order,\n                               PetscBool boundary, PetscInt num_comp_u);\n\n#endif // setupdm_h\n", "meta": {"hexsha": "57f610625e9893d079920aad66931f65ada33e12", "size": 958, "ext": "h", "lang": "C", "max_stars_repo_path": "examples/solids/include/setup-dm.h", "max_stars_repo_name": "AdelekeBankole/libCEED", "max_stars_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 123.0, "max_stars_repo_stars_event_min_datetime": "2018-01-29T02:04:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T18:13:48.000Z", "max_issues_repo_path": "examples/solids/include/setup-dm.h", "max_issues_repo_name": "AdelekeBankole/libCEED", "max_issues_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 781.0, "max_issues_repo_issues_event_min_datetime": "2017-12-22T17:20:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T21:34:34.000Z", "max_forks_repo_path": "examples/solids/include/setup-dm.h", "max_forks_repo_name": "AdelekeBankole/libCEED", "max_forks_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2017-12-27T22:35:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:02:07.000Z", "avg_line_length": 34.2142857143, "max_line_length": 80, "alphanum_fraction": 0.5584551148, "num_tokens": 192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.039638840660911584, "lm_q1q2_score": 0.017507405895765993}}
{"text": "#ifndef PyGSL_TRANSFORM_TYPES_H\n#define PyGSL_TRANSFORM_TYPES_H 1\n/*\n * All different transforms are handled by only two functions. \n *       PyGSL_transform_\n * and \n *       PyGSL_transform_2d_.\n * \n * This was done as similar functionallity is needed by all the transforms.\n * Copy the input data (transforms are often in place), check or allocate \n * help spaces. Call the function and make clean up. To allow that the \n * functions need to do quite some decisions to prepare all in proper order\n * and to do the clean up.\n * In this file various data types are defined. The first two are needed by the\n * python type which allows to allocate the proper help space and pass it to\n * the function. All the others are needed to store the information about the\n * transform.\n */\n\n/* ------------------------------------------------------------------------- */\n/*\n * One Python type is used to encapsulate all the different workspaces. This\n * enum allows the C Code to destinquish between the different types.\n */\n\nenum pygsl_transform_space_type{\n\tNOSPACE=0,\n\tCOMPLEX_WORKSPACE,\n\tREAL_WORKSPACE,\n\tCOMPLEX_WAVETABLE,\n\tREAL_WAVETABLE,\n\tHALFCOMPLEX_WAVETABLE,\n\tCOMPLEX_WORKSPACE_FLOAT,\n\tREAL_WORKSPACE_FLOAT,\n\tCOMPLEX_WAVETABLE_FLOAT,\n\tREAL_WAVETABLE_FLOAT,\n\tHALFCOMPLEX_WAVETABLE_FLOAT,\n\tWAVELET_WORKSPACE\n};\n\n#include <pygsl/pygsl_features.h>\n#include <gsl/gsl_fft.h>\n#include <gsl/gsl_fft_complex.h>\n#include <gsl/gsl_fft_real.h>\n#include <gsl/gsl_fft_halfcomplex.h>\n#include <gsl/gsl_fft_complex_float.h>\n#include <gsl/gsl_fft_real_float.h>\n#include <gsl/gsl_fft_halfcomplex_float.h>\n#include <gsl/gsl_blas.h>\n#ifdef  _PYGSL_GSL_HAS_WAVELET\n#define forward forward_wavelet\n#define backward backward_wavelet\n#include <gsl/gsl_wavelet.h>\n#include <gsl/gsl_wavelet2d.h>\n#undef forward\n#undef backward\n#else /* _PYGSL_GSL_HAS_WAVELET */\n#endif /* _PYGSL_GSL_HAS_WAVELET */\n\n/*\n * Here the corresponding union to address the pointer as the proper type.\n */\nunion pygsl_transform_space_t{\n\tgsl_fft_complex_workspace           *cws;\n\tgsl_fft_complex_wavetable           *cwt;\n\tgsl_fft_real_workspace              *rws;\n\tgsl_fft_real_wavetable              *rwt;\n\tgsl_fft_halfcomplex_wavetable       *hcwt;\n\tgsl_fft_complex_workspace_float     *cwsf;\n\tgsl_fft_complex_wavetable_float     *cwtf;\n\tgsl_fft_real_workspace_float        *rwsf;\n\tgsl_fft_real_wavetable_float        *rwtf;\n\tgsl_fft_halfcomplex_wavetable_float *hcwtf;\n#ifdef _PYGSL_GSL_HAS_WAVELET \n\tgsl_wavelet_workspace               *wws; \n#endif\n\tvoid                                *v;\n};\n\n/* ------------------------------------------------------------------------- */\n/*\n * From here all data types are defined needed to guide the transform \n * functions.\n */\n/*\n * Transformation in float or double mode \n */\nenum pygsl_transform_mode{\n\tMODE_DOUBLE = 1,\n\tMODE_FLOAT\n};\n\n/*\n * Input data in ... output data in ...\n */\nenum transform_mode{\n\tComplexComplex = 1,\n\tRealReal,\n\tRealHalfcomplex,\n\tHalfComplexReal\n\t\n};\n\n/*\n * Should be renamed. Originally the transform mode would only handle the FFT.\n * There one only needed to destinquish between the radix. Wavelets are also a \n * bit different. Others to come.\n */\nenum radix_mode{\n\tRADIX_TWO = 1,\n\tRADIX_FREE,\n\tWAVELET\n};\n\n/*\n * Does the basis type consist of only one machine type or two. e.g real\n * is SINGLE_TYPE, complex PACKED_TYPE (a real and an imaginary part).\n */\nenum pygsl_packed_type{\n\tSINGLE_TYPE=1,\n\tPACKED_TYPE=2\n};\n\n\n#define PyGSL_TRANSFORM_MODE_SWITCH(mode, double_element, float_element) \\\n        ((mode == MODE_DOUBLE) ? double_element : float_element)\n\ntypedef int transform(void * data, size_t stride, size_t N, const void *, void *);\ntypedef int transform_r2(void * data, size_t stride, size_t N);\n#ifdef  _PYGSL_GSL_HAS_WAVELET\ntypedef int wavelet(const gsl_wavelet * W, double *data, size_t stride, size_t N, void *);\ntypedef int wavelet2d(const gsl_wavelet * W, gsl_matrix *m, void *);\n#endif\ntypedef void * pygsl_transform_helpn_t(int);\ntypedef void * pygsl_transform_help_t(void *);\n\n/*\n * The different transform types.\n */\nunion transforms{\n\ttransform *free;\n\ttransform_r2 *radix2;\n#ifdef  _PYGSL_GSL_HAS_WAVELET\n\twavelet *wavelet;\n\twavelet2d *wavelet2d;\n#endif\n\tvoid *v;\n};\n\n/*\n * Functions to construct and destruct the helpers space and the helpers table.\n * The user can pass them as a proper python type. If not, the proper space\n * will be allocated using these functions.\n */\nstruct _pygsl_transform_func_rf_s {\n\tpygsl_transform_helpn_t  * space_alloc;\n\tpygsl_transform_help_t   * space_free;\n\tpygsl_transform_helpn_t  * table_alloc;\n\tpygsl_transform_help_t   * table_free;\n\tenum pygsl_transform_space_type space_type;\n\tenum pygsl_transform_space_type table_type;\n};\n\n/*\n * Not all transforms need additional workspace. The ones that need it will put\n * an instance somewhere and point the func to the approbriate initalisers.\n * free_space and free_table is used to store if the space and table have to be\n * freeded at the end of the transform.\n */\nstruct _pygsl_transform_help_rf_s{\n\tconst struct _pygsl_transform_func_rf_s *func;\n\tvoid * space;\n\tvoid * table;\n\tint free_space;\n\tint free_table;\n};\n\n/*\n * The info about which transform, what input and output\n * arrays and so forth. Used by _pygsl_transform_help_s to inform the transform\n * function about the various properties.\n */\nstruct _pygsl_transform_info_s {\n\t/* \n\t *  complex -> complex\n\t *  real    -> half_complex\n\t *  half_complex -> real\n\t *  real -> real\n\t */\n\tenum transform_mode mode;\n        /* float or double ? */\n\tenum pygsl_transform_mode datatype; \n\tenum PyArray_TYPES input_array_type;\n\tenum PyArray_TYPES output_array_type;\n        /* \n\t *  Do I need to add some additional offset to the data \n\t *  pointer before\n\t *  calling the function. A trick needed for the real to\n\t *  halfcomplex transform.\n\t */\n\tint data_offset; \n\t/* Type of the transform. Should be renamed */\n\tenum radix_mode radix2; \n\t/* one or two machine types make on basis type ? */\n\tenum pygsl_packed_type packed; \n};\n\n/*\n * Finally the struct which gathers all the information. The split up was made, as the \n * info struct is always needed, but not the helpers.\n */\nstruct _pygsl_transform_help_s{\n\tstruct _pygsl_transform_info_s *info;\n\tunion transforms  transform;\n\tstruct _pygsl_transform_help_rf_s *helpers;\n};\ntypedef  struct _pygsl_transform_help_s pygsl_transform_help_s;\n\n/* \n * The main function doing all the work. Its a function for the ffts and a \n *  method for the wavelets! \n */\nstatic PyObject *\nPyGSL_transform_(PyObject *self, PyObject *args, pygsl_transform_help_s *helps);\n\n/*\n * Currently only wavelets provide a 2 dimensional transform\n */\n#ifdef _PYGSL_GSL_HAS_WAVELET\nstatic PyObject *\nPyGSL_transform_2d_(PyObject *self, PyObject *args, pygsl_transform_help_s *helps);\n#endif \n\n#endif /* PyGSL_TRANSFORM_TYPES_H */\n/*\n * Local Variables:\n * mode: C\n * c-file-style: \"python\"\n * End:\n */\n", "meta": {"hexsha": "56be3626a51b3a0c5015704237413ce61eff325c", "size": 6909, "ext": "h", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/src/transform/transformtypes.h", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/src/transform/transformtypes.h", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/src/transform/transformtypes.h", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 28.6680497925, "max_line_length": 90, "alphanum_fraction": 0.7283253727, "num_tokens": 1763, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4035668537353746, "lm_q2_score": 0.043365803709329, "lm_q1q2_score": 0.01750100096267974}}
{"text": "/*\n * Copyright (c) 2011-2018 The University of Tennessee and The University\n *                         of Tennessee Research Foundation.  All rights\n *                         reserved.\n *\n * @precisions normal z -> s d c\n *\n */\n#include \"dplasma_cores.h\"\n#include \"dplasma_zcores.h\"\n\n#if defined(PARSEC_HAVE_STRING_H)\n#include <string.h>\n#endif  /* defined(PARSEC_HAVE_STRING_H) */\n#if defined(PARSEC_HAVE_STDARG_H)\n#include <stdarg.h>\n#endif  /* defined(PARSEC_HAVE_STDARG_H) */\n#include <stdio.h>\n#ifdef PARSEC_HAVE_LIMITS_H\n#include <limits.h>\n#endif\n#include <stdlib.h>\n\n#include <cblas.h>\n#include <core_blas.h>\n\n#define max(a, b) ((a) > (b) ? (a) : (b))\n#define min(a, b) ((a) < (b) ? (a) : (b))\n#if defined(ADD_)\n#define  DLARFG      zlarfg_\n#else\n#define  DLARFG      zlarfg\n#endif\nextern void DLARFG(int *N, parsec_complex64_t *ALPHA, parsec_complex64_t *X, int *INCX, parsec_complex64_t *TAU);\n\n//static void band_to_trd_vmpi1(int N, int NB, parsec_complex64_t *A, int LDA);\n//static void band_to_trd_vmpi2(int N, int NB, parsec_complex64_t *A, int LDA);\n//static void band_to_trd_v8seq(int N, int NB, parsec_complex64_t *A, int LDA, int INgrsiz, int INthgrsiz);\n//static int  TRD_seqgralgtype(int N, int NB, parsec_complex64_t *A, int LDA, parsec_complex64_t *C, parsec_complex64_t *S, int i, int j, int m, int grsiz, int BAND);\nint  blgchase_ztrdv1(int NT, int N, int NB, parsec_complex64_t *A, parsec_complex64_t *V, parsec_complex64_t *TAU, int sweep, int id, int blktile);\nint  blgchase_ztrdv2(int NT, int N, int NB, parsec_complex64_t *A1, parsec_complex64_t *A2, parsec_complex64_t *V1, parsec_complex64_t *TAU1, parsec_complex64_t *V2, parsec_complex64_t *TAU2, int sweep, int id, int blktile);\n\nint CORE_zlarfx2(int side, int N,\n                parsec_complex64_t V,\n                parsec_complex64_t TAU,\n                parsec_complex64_t *C1, int LDC1,\n                parsec_complex64_t *C2, int LDC2);\n\nint CORE_zlarfx2c(int uplo,\n                parsec_complex64_t V,\n                parsec_complex64_t TAU,\n                parsec_complex64_t *C1,\n                parsec_complex64_t *C2,\n                parsec_complex64_t *C3);\n\nstatic void CORE_zhbtelr(int N, int NB, parsec_complex64_t *A1, int LDA1, parsec_complex64_t *A2, int LDA2, parsec_complex64_t *V1, parsec_complex64_t *TAU1, int st, int ed);\nstatic void CORE_zhbtrce(int N, int NB, parsec_complex64_t *A1, int LDA1, parsec_complex64_t *A2, int LDA2, parsec_complex64_t *V1, parsec_complex64_t *TAU1, parsec_complex64_t *V2, parsec_complex64_t *TAU2, int st, int ed, int edglob);\nstatic void CORE_zhbtlrx(int N, int NB, parsec_complex64_t *A1, int LDA1, parsec_complex64_t *A2, int LDA2, parsec_complex64_t *V1, parsec_complex64_t *TAU1, int st, int ed);\n\nstatic void DLARFX_C(char side, int N, parsec_complex64_t V, parsec_complex64_t TAU, parsec_complex64_t *C, int LDC);\nstatic void TRD_type1bHL(int N, int NB, parsec_complex64_t *A, int LDA, parsec_complex64_t *V, parsec_complex64_t *TAU, int st, int ed);\nstatic void TRD_type2bHL(int N, int NB, parsec_complex64_t *A, int LDA, parsec_complex64_t *V, parsec_complex64_t *TAU, int st, int ed);\nstatic void TRD_type3bHL(int N, int NB, parsec_complex64_t *A, int LDA, parsec_complex64_t *V, parsec_complex64_t *TAU, int st, int ed);\n\n\nint CORE_zlarfx2(int side, int N,\n                parsec_complex64_t V,\n                parsec_complex64_t TAU,\n                parsec_complex64_t *C1, int LDC1,\n                parsec_complex64_t *C2, int LDC2)\n{\n    static parsec_complex64_t zzero = 0.0;\n    int    J;\n    parsec_complex64_t V2, T2, SUM;\n\n    /* Quick return */\n    /*\n    if (N == 0)\n        return PLASMA_SUCCESS;\n    */\n    if (TAU == zzero)\n        return 0;\n\n    /*\n     * Special code for 2 x 2 Householder where V1 = I\n    */\n    if(side==PlasmaLeft){\n        V2 = conj(V);\n        T2 = TAU*conj(V2);\n        for (J = 0; J < N ; J++){\n           SUM         = C1[J*LDC1]   + V2*C2[J*LDC2];\n           C1[J*LDC1]  = C1[J*LDC1]   - SUM*TAU;\n           C2[J*LDC2]  = C2[J*LDC2]   - SUM*T2;\n        }\n    }else if(side==PlasmaRight){\n        V2 = V;\n        T2 = TAU*conj(V2);\n        for (J = 0; J < N ; J++){\n           SUM     = C1[J]   + V2*C2[J];\n           C1[J]   = C1[J]   - SUM*TAU;\n           C2[J]   = C2[J]   - SUM*T2;\n        }\n    }\n\n    return 0;\n}\n\n/***************************************************************************//**\n *\n **/\nint CORE_zlarfx2c(int uplo,\n                parsec_complex64_t V,\n                parsec_complex64_t TAU,\n                parsec_complex64_t *C1,\n                parsec_complex64_t *C2,\n                parsec_complex64_t *C3)\n{\n    static parsec_complex64_t zzero = 0.0;\n    parsec_complex64_t T2, SUM, TEMP;\n\n    /* Quick return */\n    if (TAU == zzero)\n        return 0;\n\n   /*\n    *        Special code for a diagonal block  C1\n    *                                           C2  C3\n    */\n if(uplo==PlasmaLower){   //do the corner Left then Right (used for the lower case tridiag)\n      // L and R for the 2x2 corner\n      //            C(N-1, N-1)  C(N-1,N)        C1  TEMP\n      //            C(N  , N-1)  C(N  ,N)        C2  C3\n      // For Left : use conj(TAU) and V.\n      // For Right: nothing, keep TAU and V.\n      // Left 1 ==> C1\n      //            C2\n      TEMP    = conj(C2[0]); // copy C2 here before modifying it.\n      T2      = conj(TAU)*V;\n      SUM     = C1[0]   + conj(V)*C2[0];\n      C1[0]   = C1[0]   - SUM*conj(TAU);\n      C2[0]   = C2[0]   - SUM*T2;\n      // Left 2 ==> TEMP\n      //            C3\n      SUM     = TEMP    + conj(V)*C3[0];\n      TEMP    = TEMP    - SUM*conj(TAU);\n      C3[0]   = C3[0]   - SUM*T2;\n      // Right 1 ==>  C1 TEMP.  NB: no need to compute corner (2,2)=TEMP\n      T2      = TAU*conj(V);\n      SUM     = C1[0]   + V*TEMP;\n      C1[0]   = C1[0]   - SUM*TAU;\n      // Right 2 ==> C2 C3\n      SUM     = C2[0]   + V*C3[0];\n      C2[0]   = C2[0]   - SUM*TAU;\n      C3[0]   = C3[0]   - SUM*T2;\n }else if(uplo==PlasmaUpper){ // do the corner Right then Left (used for the upper case tridiag)\n      //            C(N-1, N-1)  C(N-1,N)        C1    C2\n      //            C(N  , N-1)  C(N  ,N)        TEMP  C3\n      // For Left : use TAU       and conj(V).\n      // For Right: use conj(TAU) and conj(V).\n      // Right 1 ==> C1 C2\n      V       = conj(V);\n      TEMP    = conj(C2[0]); // copy C2 here before modifying it.\n      T2      = conj(TAU)*conj(V);\n      SUM     = C1[0]   + V*C2[0];\n      C1[0]   = C1[0]   - SUM*conj(TAU);\n      C2[0]   = C2[0]   - SUM*T2;\n      // Right 2 ==> TEMP C3\n      SUM     = TEMP    + V*C3[0];\n      TEMP    = TEMP    - SUM*conj(TAU);\n      C3[0]   = C3[0]   - SUM*T2;\n      // Left 1 ==> C1\n      //            TEMP. NB: no need to compute corner (2,1)=TEMP\n      T2      = TAU*V;\n      SUM     = C1[0]   + conj(V)*TEMP;\n      C1[0]   = C1[0]   - SUM*TAU;\n      // Left 2 ==> C2\n      //            C3\n      SUM     = C2[0]   + conj(V)*C3[0];\n      C2[0]   = C2[0]   - SUM*TAU;\n      C3[0]   = C3[0]   - SUM*T2;\n }\n\n return 0;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n///////////////////////////////////////////////////////////\n//                  DLARFX en C\n///////////////////////////////////////////////////////////\nstatic void DLARFX_C(char side, int N, parsec_complex64_t V, parsec_complex64_t TAU, parsec_complex64_t *C, int LDC)\n{\n parsec_complex64_t T2, SUM, TEMP;\n int    J, pt;\n\n/*\n *        Special code for 2 x 2 Householder\n */\n\n\n T2 = TAU*V;\n if(side=='L'){\n     for (J = 0; J < N ; J++){\n        pt      = LDC*J;\n        SUM     = C[pt]   + V*C[pt+1];\n        C[pt]   = C[pt]   - SUM*TAU;\n        C[pt+1] = C[pt+1] - SUM*T2;\n     }\n }else if(side=='R'){\n     for (J = 0; J < N ; J++){\n        pt      = J+LDC;\n        SUM     = C[J]   + V*C[pt];\n        C[J]    = C[J]   - SUM*TAU;\n        C[pt]   = C[pt]  - SUM*T2;\n     }\n }else if(side=='B'){\n     TEMP    = C[ LDC * (N-2) +1];\n     for (J = 0; J < N-1 ; J++){\n        pt      = LDC*J;\n        SUM     = C[pt]   + V*C[pt+1];\n        C[pt]   = C[pt]   - SUM*TAU;\n        C[pt+1] = C[pt+1] - SUM*T2;\n     }\n     // L and R for the 2x2 corner\n     //            C(1, N-1)  C(1,N)        C(1, N-1)  TEMP\n     //            C(2, N-1)  C(2,N)        C(2, N-1)  C(2,N)\n     // Left 1 ==> C(1,N-1) C(2,N-1) deja fait dans la boucle\n     //pt      = LDC * (N-2);\n     //TEMP    = C[pt+1];\n     //SUM     = C[pt]   + V*C[pt+1];\n     //C[pt]   = C[pt]   - SUM*TAU;\n     //C[pt+1] = C[pt+1] - SUM*T2;\n     // Left 2 ==> TEMP C(2,N)\n     pt      = LDC * (N-1) +1;\n     SUM     = TEMP    + V*C[pt];\n     TEMP    = TEMP    - SUM*TAU;\n     C[pt]   = C[pt]   - SUM*T2;\n     // Right 1 ==>  C(1,N-1) TEMP.  NB: no need to compute corner (2,2)\n     J       = LDC * (N-2);\n     SUM     = C[J]   + V*TEMP;\n     C[J]    = C[J]   - SUM*TAU;\n     // Right 2 ==> C(2,N-1) C(2,N)\n     J      = LDC * (N-2) + 1;\n     pt     = LDC * (N-1) + 1;\n     SUM    = C[J]   + V*C[pt];\n     C[J]   = C[J]   - SUM*TAU;\n     C[pt]  = C[pt]  - SUM*T2;\n }\n}\n///////////////////////////////////////////////////////////\n\n///////////////////////////////////////////////////////////\n#define A1(m,n)   &(A1[((m)-(n)) + LDA1*(n)])\n#define A2(m,n)   &(A2[((m)-(n)) + LDA2*((n)-NB)])\n#define V1(m)     &(V1[m-st])\n#define TAU1(m)   &(TAU1[m-st])\n#define V2(m)     &(V2[m-st])\n#define TAU2(m)   &(TAU2[m-st])\n///////////////////////////////////////////////////////////\n//                  TYPE 1-BAND Householder\n///////////////////////////////////////////////////////////\nstatic void CORE_zhbtelr(int N, int NB, parsec_complex64_t *A1, int LDA1, parsec_complex64_t *A2, int LDA2, parsec_complex64_t *V1, parsec_complex64_t *TAU1, int st, int ed) {\n  int    J1, J2, KDM1, LDX;\n  int    len, len1, len2, t1ed, t2st;\n  int    i, IONE, ITWO;\n  IONE=1;\n  ITWO=2;\n  (void)N;\n\n  KDM1 = NB-1;\n  LDX = LDA2-1;\n  /* **********************************************************************************************\n   *   Annihiliate, then LEFT:\n   * ***********************************************************************************************/\n  for (i = ed; i >= st+1 ; i--){\n     /* generate Householder to annihilate a(i+k-1,i) within the band */\n     *V1(i)          = *A1(i, (st-1));\n     *A1(i, (st-1))  = 0.0;\n     DLARFG( &ITWO, A1((i-1),(st-1)), V1(i), &IONE, TAU1(i) );\n\n     J1   = st;\n     J2   = i-2;\n     t1ed = min(J2,KDM1);\n     t2st = max(J1, NB);\n     len1 = t1ed - J1 +1;\n     len2 = J2 - t2st +1;\n     // printf(\"Type 1L st %d   ed %d    i %d    J1 %d   J2 %d  t1ed %d  t2st %d len1 %d len2 %d \\n\", st, ed, i, J1,J2,t1ed,t2st,len1,len2);\n     /* apply reflector from the left (horizontal row) and from the right for only the diagonal 2x2.*/\n     if(len2>=0){\n        /* part of the left(if len2>0) and the corner are on tile T2 */\n        if(len2>0) CORE_zlarfx2(PlasmaLeft, len2 , *V1(i), conj(*TAU1(i)), A2((i-1), t2st), LDX, A2(i, t2st), LDX);\n        CORE_zlarfx2c(PlasmaLower, *V1(i), *TAU1(i), A2(i-1,i-1), A2(i,i-1), A2(i,i));\n        if(len1>0) CORE_zlarfx2(PlasmaLeft, len1 , *V1(i), conj(*TAU1(i)), A1(i-1, J1), LDX, A1(i, J1), LDX);\n     }else if(len2==-1){\n        /* the left is on tile T1, and only A(i,i) of the corner is on tile T2 */\n        CORE_zlarfx2c(PlasmaLower, *V1(i), *TAU1(i), A1(i-1,i-1), A1(i,i-1), A2(i,i));\n        if(len1>0) CORE_zlarfx2(PlasmaLeft, len1 , *V1(i), conj(*TAU1(i)), A1(i-1, J1), LDX, A1(i, J1), LDX);\n     }else{\n        /* the left and the corner are on tile T1, nothing on tile T2 */\n        CORE_zlarfx2c(PlasmaLower, *V1(i), *TAU1(i), A1(i-1,i-1), A1(i,i-1), A1(i,i)) ;\n        if(len1>0) CORE_zlarfx2(PlasmaLeft, len1 , *V1(i), conj(*TAU1(i)), A1((i-1), J1), LDX, A1(i, J1), LDX);\n     }\n  }\n  /* **********************************************************************************************\n   *   APPLY RIGHT ON THE REMAINING ELEMENT OF KERNEL 1\n   * ***********************************************************************************************/\n  for (i = ed; i >= st+1 ; i--){\n     J1    = i+1;\n     J2    = ed;\n     len   = J2-J1+1;\n     if(len>0){\n        if(i>NB)\n           /* both column (i-1) and i are on tile T2 */\n           CORE_zlarfx2(PlasmaRight, len, *V1(i), *TAU1(i), A2(J1, i-1), LDX, A2(J1, i), LDX);\n        else if(i==NB)\n           /* column (i-1) is on tile T1 while column i is on tile T2 */\n           CORE_zlarfx2(PlasmaRight, len, *V1(i), *TAU1(i), A1(J1, i-1), LDX, A2(J1, i), LDX);\n        else\n           /* both column (i-1) and i are on tile T1 */\n           CORE_zlarfx2(PlasmaRight, len, *V1(i), *TAU1(i), A1(J1, i-1), LDX, A1(J1, i), LDX);\n     }\n  }\n}\n///////////////////////////////////////////////////////////\n\n\n\n\n\n\n\n///////////////////////////////////////////////////////////\n//                  TYPE 2-BAND Householder\n///////////////////////////////////////////////////////////\nstatic void CORE_zhbtrce(int N, int NB, parsec_complex64_t *A1, int LDA1, parsec_complex64_t *A2, int LDA2, parsec_complex64_t *V1, parsec_complex64_t *TAU1, parsec_complex64_t *V2, parsec_complex64_t *TAU2, int st, int ed, int edglob) {\n  int    J1, J2, J3, KDM1, LDX, pt;\n  int    len, len1, len2, t1ed, t2st, iglob;\n  int    i, IONE, ITWO;\n  parsec_complex64_t V,T,SUM;\n  IONE=1;\n  ITWO=2;\n\n  iglob = edglob+1;\n  LDX   = LDA1-1;\n  KDM1  = NB-1;\n  /* **********************************************************************************************\n   *   Right:\n   * ***********************************************************************************************/\n  for (i = ed; i >= st+1 ; i--){\n     /* apply Householder from the right. and create newnnz outside the band if J3 < N */\n     iglob = iglob -1;\n     J1  = ed+1;\n     if((iglob+NB)>= N){\n        J2 = i +(N-iglob-1);\n        J3 = J2;\n     }else{\n        J2 = i + KDM1;\n        J3 = J2+1;\n     }\n     len   = J2-J1+1;\n     /* printf(\"Type 2R st %d   ed %d    i %d   J1 %d   J2 %d  len %d iglob %d  \\n\",st,ed,i,J1,J2,len,iglob);*/\n\n     if(len>0){\n        if(i>NB){\n           /* both column (i-1) and i are on tile T2 */\n           CORE_zlarfx2(PlasmaRight, len, *V1(i), *TAU1(i), A2(J1, i-1), LDX, A2(J1, i), LDX);\n           /* if nonzero element need to be created outside the band (if index < N) then create and eliminate it. */\n           if(J3>J2){\n              /* new nnz at TEMP=V2(i)  */\n              V          = *V1(i);\n              T          = *TAU1(i) * conj(V);\n              SUM        =  V * (*A2(J3, i));\n              *V2(i)     = -SUM * (*TAU1(i));\n              *A2(J3, i) = *A2(J3, i) - SUM * T;\n              /* generate Householder to annihilate a(j+kd,j-1) within the band */\n              DLARFG( &ITWO, A2(J2,i-1), V2(i), &IONE, TAU2(i) );\n           }\n        }else if(i==NB){\n           /* column (i-1) is on tile T1 while column i is on tile T2 */\n           CORE_zlarfx2(PlasmaRight, len, *V1(i), *TAU1(i), A1(J1, i-1), LDX, A2(J1, i), LDX);\n           /* if nonzero element need to be created outside the band (if index < N) then create and eliminate it. */\n           if(J3>J2){\n              /* new nnz at TEMP=V2(i)  */\n              V          = *V1(i);\n              T          = *TAU1(i) * conj(V);\n              SUM        =  V * (*A2(J3, i));\n              *V2(i)     = -SUM * (*TAU1(i));\n              *A2(J3, i) = *A2(J3, i) - SUM * T;\n              /* generate Householder to annihilate a(j+kd,j-1) within the band */\n              DLARFG( &ITWO, A1(J2, i-1), V2(i), &IONE, TAU2(i) );\n           }\n        }else{\n           /* both column (i-1) and i are on tile T1 */\n           CORE_zlarfx2(PlasmaRight, len, *V1(i), *TAU1(i), A1(J1, i-1), LDX, A1(J1, i), LDX);\n           /* if nonzero element need to be created outside the band (if index < N) then create and eliminate it. */\n           if(J3>J2){\n              /* new nnz at TEMP=V2(i)  */\n              V              = *V1(i);\n              T              = *TAU1(i) * conj(V);\n              SUM            =  V * (*A1(J3, i));\n              *V2(i)         = -SUM * (*TAU1(i));\n              *A1(J3, i)    = *A1(J3, i) - SUM * T;\n              /* generate Householder to annihilate a(j+kd,j-1) within the band */\n              DLARFG( &ITWO, A1(J2, i-1), V2(i), &IONE, TAU2(i) );\n           }\n        }\n     }\n  }\n              // if(id==1) return;\n\n  /* **********************************************************************************************\n   *   APPLY LEFT ON THE REMAINING ELEMENT OF KERNEL 1\n   * ***********************************************************************************************/\n  iglob = edglob+1;\n  for (i = ed; i >= st+1 ; i--){\n     iglob = iglob -1;\n     if((iglob+NB)< N){ /* mean that J3>J2 and so a nnz has been created and so a left is required. */\n        J1   = i;\n        J2   = ed;\n        t1ed = min(J2,KDM1);\n        t2st = max(J1, NB);\n        len1 = t1ed - J1 +1;\n        len2 = J2 - t2st +1;\n        pt   = i + KDM1; /* pt correspond to the J2 position of the corresponding right done above */\n        //printf(\"Type 2L st %d   ed %d    i %d    J1 %d   J2 %d  t1ed %d  t2st %d len1 %d len2 %d \\n\", st, ed, i, J1,J2,t1ed,t2st,len1,len2);\n\n        /* apply reflector from the left (horizontal row) and from the right for only the diagonal 2x2.*/\n        if(len2>0){\n           /* part of the left(if len2>0) and the corner are on tile T2 */\n           CORE_zlarfx2(PlasmaLeft, len2 , *V2(i), conj(*TAU2(i)), A2(pt, t2st), LDX, A2(pt+1, t2st), LDX);\n           if(len1>0) CORE_zlarfx2(PlasmaLeft, len1 , *V2(i), conj(*TAU2(i)), A1(pt, J1), LDX, A1(pt+1, J1), LDX);\n        }else if(len1>0){\n           /* the left and the corner are on tile T1, nothing on tile T2 */\n           CORE_zlarfx2(PlasmaLeft, len1 , *V2(i), conj(*TAU2(i)), A1(pt, J1), LDX, A1(pt+1, J1), LDX);\n        }\n     }\n  }\n}\n///////////////////////////////////////////////////////////\n\n\n///////////////////////////////////////////////////////////\n//                  TYPE 1-BAND Householder\n///////////////////////////////////////////////////////////\nstatic void CORE_zhbtlrx(int N, int NB, parsec_complex64_t *A1, int LDA1, parsec_complex64_t *A2, int LDA2, parsec_complex64_t *V1, parsec_complex64_t *TAU1, int st, int ed) {\n  int    J1, J2, KDM1, LDX;\n  int    len, len1, len2, t1ed, t2st;\n  int    i;\n\n  (void)N;\n  KDM1 = NB-1;\n  LDX = LDA2-1;\n  /* **********************************************************************************************\n   *   Annihiliate, then LEFT:\n   * ***********************************************************************************************/\n  for (i = ed; i >= st+1 ; i--){\n     J1   = st;\n     J2   = i-2;\n     t1ed = min(J2,KDM1);\n     t2st = max(J1, NB);\n     len1 = t1ed - J1 +1;\n     len2 = J2 - t2st +1;\n     //printf(\"Type 3L st %d   ed %d    i %d    J1 %d   J2 %d  t1ed %d  t2st %d len1 %d len2 %d \\n\", st, ed, i, J1,J2,t1ed,t2st,len1,len2);\n     /* apply reflector from the left (horizontal row) and from the right for only the diagonal 2x2.*/\n     if(len2>=0){\n        /* part of the left(if len2>0) and the corner are on tile T2 */\n        if(len2>0) CORE_zlarfx2(PlasmaLeft, len2 , *V1(i), conj(*TAU1(i)), A2((i-1), t2st), LDX, A2(i, t2st), LDX);\n        CORE_zlarfx2c(PlasmaLower, *V1(i), *TAU1(i), A2(i-1,i-1), A2(i,i-1), A2(i,i));\n        if(len1>0) CORE_zlarfx2(PlasmaLeft, len1 , *V1(i), conj(*TAU1(i)), A1(i-1, J1), LDX, A1(i, J1), LDX);\n     }else if(len2==-1){\n        /* the left is on tile T1, and only A(i,i) of the corner is on tile T2 */\n        CORE_zlarfx2c(PlasmaLower, *V1(i), *TAU1(i), A1(i-1,i-1), A1(i,i-1), A2(i,i));\n        if(len1>0) CORE_zlarfx2(PlasmaLeft, len1 , *V1(i), conj(*TAU1(i)), A1(i-1, J1), LDX, A1(i, J1), LDX);\n     }else{\n        /* the left and the corner are on tile T1, nothing on tile T2 */\n        CORE_zlarfx2c(PlasmaLower, *V1(i), *TAU1(i), A1(i-1,i-1), A1(i,i-1), A1(i,i)) ;\n        if(len1>0) CORE_zlarfx2(PlasmaLeft, len1 , *V1(i), conj(*TAU1(i)), A1((i-1), J1), LDX, A1(i, J1), LDX);\n     }\n  }\n  /* **********************************************************************************************\n   *   APPLY RIGHT ON THE REMAINING ELEMENT OF KERNEL 1\n   * ***********************************************************************************************/\n  for (i = ed; i >= st+1 ; i--){\n     J1    = i+1;\n     J2    = ed;\n     len   = J2-J1+1;\n     if(len>0){\n        if(i>NB)\n           /* both column (i-1) and i are on tile T2 */\n           CORE_zlarfx2(PlasmaRight, len, *V1(i), *TAU1(i), A2(J1, i-1), LDX, A2(J1, i), LDX);\n        else if(i==NB)\n           /* column (i-1) is on tile T1 while column i is on tile T2 */\n           CORE_zlarfx2(PlasmaRight, len, *V1(i), *TAU1(i), A1(J1, i-1), LDX, A2(J1, i), LDX);\n        else\n           /* both column (i-1) and i are on tile T1 */\n           CORE_zlarfx2(PlasmaRight, len, *V1(i), *TAU1(i), A1(J1, i-1), LDX, A1(J1, i), LDX);\n     }\n  }\n}\n///////////////////////////////////////////////////////////\n#undef A1\n#undef A2\n#undef V1\n#undef TAU1\n#undef V2\n#undef TAU2\n\n\n\n\n\n\n\n\n\n\n\n///////////////////////////////////////////////////////////\n//                  TYPE 1-BAND Householder\n///////////////////////////////////////////////////////////\n//// add -1 because of C\n#define A(m,n)   &(A[((m)-(n)) + LDA*((n)-1)])\n#define V(m)     &(V[m-1])\n#define TAU(m)   &(TAU[m-1])\nstatic void TRD_type1bHL(int N, int NB, parsec_complex64_t *A, int LDA, parsec_complex64_t *V, parsec_complex64_t *TAU, int st, int ed) {\n  int    J1, J2, len, LDX;\n  int    i, IONE, ITWO;\n  IONE=1;\n  ITWO=2;\n  (void)NB;\n\n  if(ed <= st){\n    printf(\"TRD_type 1bH: ERROR st and ed %d  %d \\n\",st,ed);\n    exit(-10);\n  }\n\n  LDX = LDA-1;\n  for (i = ed; i >= st+1 ; i--){\n     // generate Householder to annihilate a(i+k-1,i) within the band\n     *V(i)          = *A(i, (st-1));\n     *A(i, (st-1))  = 0.0;\n     DLARFG( &ITWO, A((i-1),(st-1)), V(i), &IONE, TAU(i) );\n\n     // apply reflector from the left (horizontal row) and from the right for only the diagonal 2x2.\n     J1  = st;\n     J2  = i;\n     len = J2-J1+1;\n     printf(\"voici J1 %d J2 %d len %d \\n\",J1,J2,len);\n     DLARFX_C('B', len , *V(i), *TAU(i), A((i-1),J1   ), LDX);\n  }\n\n  for (i = ed; i >= st+1 ; i--){\n     len = min(ed,N)-i;\n     if(len>0)DLARFX_C('R', len, *V(i), *TAU(i), A((i+1),(i-1)), LDX);\n  }\n\n\n}\n#undef A\n#undef V\n#undef TAU\n///////////////////////////////////////////////////////////\n\n\n\n///////////////////////////////////////////////////////////\n//                  TYPE 2-BAND Householder\n///////////////////////////////////////////////////////////\n//// add -1 because of C\n#define A(m,n)   &(A[((m)-(n)) + LDA*((n)-1)])\n#define V(m)     &(V[m-1])\n#define TAU(m)   &(TAU[m-1])\nstatic void TRD_type2bHL(int N, int NB, parsec_complex64_t *A, int LDA, parsec_complex64_t *V, parsec_complex64_t *TAU, int st, int ed) {\n  int    J1, J2, J3, KDM2, len, LDX;\n  int    i, IONE, ITWO;\n  IONE=1;\n  ITWO=2;\n\n\n  if(ed <= st){\n    printf(\"TRD_type 2H: ERROR st and ed %d  %d \\n\",st,ed);\n    exit(-10);;\n  }\n\n  LDX  = LDA -1;\n  KDM2 = NB-2;\n  for (i = ed; i >= st+1 ; i--){\n     // apply Householder from the right. and create newnnz outside the band if J3 < N\n     J1  = ed+1;\n     J2  = min((i+1+KDM2), N);\n     J3  = min((J2+1), N);\n     len = J2-J1+1;\n     DLARFX_C('R', len, *V(i), *TAU(i), A(J1,(i-1)), LDX);\n\n     // if nonzero element a(j+kd,j-1) has been created outside the band (if index < N) then eliminate it.\n     len    = J3-J2; // soit 1 soit 0\n     if(len>0){\n         //  new nnz at TEMP=V(J3)\n         *V(J3)     =            - *A(J3,(i)) * (*TAU(i)) * (*V(i));\n         *A(J3,(i)) = *A(J3,(i)) + *V(J3)  * (*V(i)); //ATTENTION THIS replacement IS VALID IN FLOAT CASE NOT IN COMPLEX\n         // generate Householder to annihilate a(j+kd,j-1) within the band\n         DLARFG( &ITWO, A(J2,(i-1)), V(J3), &IONE, TAU(J3) );\n     }\n  }\n               //if(id==1) return;\n\n\n  for (i = ed; i >= st+1 ; i--){\n     J2  = min((i+1+KDM2), N);\n     J3  = min((J2+1), N);\n     len    = J3-J2;\n     if(len>0){\n        len = min(ed,N)-i+1;\n        DLARFX_C('L', len , *V(J3), *TAU(J3), A(J2, i), LDX);\n     }\n  }\n\n}\n#undef A\n#undef V\n#undef TAU\n///////////////////////////////////////////////////////////\n\n\n\n///////////////////////////////////////////////////////////\n//                  TYPE 3-BAND Householder\n///////////////////////////////////////////////////////////\n//// add -1 because of C\n#define A(m,n)   &(A[((m)-(n)) + LDA*((n)-1)])\n#define V(m)     &(V[m-1])\n#define TAU(m)   &(TAU[m-1])\nstatic void TRD_type3bHL(int N, int NB, parsec_complex64_t *A, int LDA, parsec_complex64_t *V, parsec_complex64_t *TAU, int st, int ed) {\n  int    J1, J2, len, LDX;\n  int    i;\n  (void)NB;\n\n  if(ed <= st){\n    printf(\"TRD_type 3H: ERROR st and ed %d  %d \\n\",st,ed);\n    exit(-10);\n  }\n\n  LDX = LDA-1;\n  for (i = ed; i >= st+1 ; i--){\n     // apply rotation from the left. faire le DROT horizontal\n     J1  = st;\n     J2  = i;\n     len = J2-J1+1;\n     //len = NB+1;\n     DLARFX_C('B', len , *V(i), *TAU(i), A((i-1),J1   ), LDX);\n  }\n\n  for (i = ed; i >= st+1 ; i--){\n     len = min(ed,N)-i;\n     if(len>0)DLARFX_C('R', len, *V(i), *TAU(i), A((i+1),(i-1)), LDX);\n  }\n}\n#undef A\n#undef V\n#undef TAU\n///////////////////////////////////////////////////////////\n\n\n\n///////////////////////////////////////////////////////////\n//                  grouping sched wrapper call\n///////////////////////////////////////////////////////////\n#if 0\nint TRD_seqgralgtype(int N, int NB, parsec_complex64_t *A, int LDA, parsec_complex64_t *C, parsec_complex64_t *S, int i, int j, int m, int grsiz, int BAND) {\n  int    k,shift=3;\n  int    myid,colpt,stind,edind,blklastind,stepercol;\n  (void) BAND;\n\n\n\n  k   = shift/grsiz;\n  stepercol =  k*grsiz == shift ? k:k+1;\n\n\n   for (k = 1; k <=grsiz; k++){\n      myid = (i-j)*(stepercol*grsiz) +(m-1)*grsiz + k;\n      if(myid%2 ==0){\n           colpt      = (myid/2)*NB+1+j-1;\n           stind      = colpt-NB+1;\n           edind      = min(colpt,N);\n           blklastind = colpt;\n           if(stind>=edind){\n               printf(\"TRD_seqalg ERROR---------> st>=ed  %d  %d \\n\\n\",stind, edind);\n               return -10;\n           }\n      }else{\n           colpt      = ((myid+1)/2)*NB + 1 +j -1 ;\n           stind      = colpt-NB+1;\n           edind      = min(colpt,N);\n           if( (stind>=edind-1) && (edind==N) )\n               blklastind=N;\n           else\n               blklastind=0;\n           if(stind>=edind){\n               printf(\"TRD_seqalg ERROR---------> st>=ed  %d  %d \\n\\n\",stind, edind);\n               return -10;\n\n           }\n      }\n\n          if(myid == 1)\n              TRD_type1bHL(N, NB, A, LDA, C, S, stind, edind);\n          else if(myid%2 == 0)\n              TRD_type2bHL(N, NB, A, LDA, C, S, stind, edind);\n          else if(myid%2 == 1)\n              TRD_type3bHL(N, NB, A, LDA, C, S, stind, edind);\n          else{\n              printf(\"COUCOU ERROR myid/2 %d\\n\",myid);\n               return -10;\n          }\n\n      if(blklastind >= (N-1))  break;\n      //if(myid==2)return;\n  }   // END for k=1:grsiz\nreturn 0;\n}\n///////////////////////////////////////////////////////////\n#endif\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////\n//                  REDUCTION BAND TO TRIDIAG\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////\n#if 0\nstatic void band_to_trd_v8seq(int N, int NB, parsec_complex64_t *A, int LDA, int INgrsiz, int INthgrsiz) {\n  int myid, grsiz, shift, stt, st, ed, stind, edind, BAND;\n  int blklastind, colpt;\n  int stepercol,mylastid;\n  parsec_complex64_t *C, *S;\n  int i,j,m;\n  int thgrsiz, thgrnb, thgrid, thed;\n  int INFO;\n  INFO=-1;\n  BAND = 0;\n  C   = malloc(N*sizeof(parsec_complex64_t));\n  S   = malloc(N*sizeof(parsec_complex64_t));\n  memset(C,0,N*sizeof(parsec_complex64_t));\n  memset(S,0,N*sizeof(parsec_complex64_t));\n\n  grsiz   = INgrsiz;\n  thgrsiz = INthgrsiz;\n\n  shift   = 3;\n  if(grsiz==0)grsiz   = 6;\n  if(thgrsiz==0)thgrsiz = N;\n\n  if(LDA != (NB+1))\n  {\n      printf(\" ERROR LDA not equal NB+1 and this code is special for LDA=NB+1. LDA=%d NB+1=%d \\n\",LDA,NB+1);\n      return;\n  }\n  printf(\"  Version -8seq- grsiz %4d     thgrsiz %4d       N %5d      NB %5d    BAND %5d\\n\",grsiz,thgrsiz, N, NB, BAND);\n\n\n  i = shift/grsiz;\n  stepercol =  i*grsiz == shift ? i:i+1;\n\n  i       = (N-2)/thgrsiz;\n  thgrnb  = i*thgrsiz == (N-2) ? i:i+1;\n\n  for (thgrid = 1; thgrid<=thgrnb; thgrid++){\n     stt  = (thgrid-1)*thgrsiz+1;\n     thed = min( (stt + thgrsiz -1), (N-2));\n     for (i = stt; i <= N-2; i++){\n        ed=min(i,thed);\n        if(stt>ed)break;\n        for (m = 1; m <=stepercol; m++){\n            st=stt;\n            for (j = st; j <=ed; j++){\n                 myid     = (i-j)*(stepercol*grsiz) +(m-1)*grsiz + 1;\n                 mylastid = myid+grsiz-1;\n                 INFO = TRD_seqgralgtype(N, NB, A, LDA, C, S, i, j, m, grsiz, BAND);\n                 if(INFO!=0){\n                         printf(\"ERROR band_to_trd_v8seq INFO=%d\\n\",INFO);\n                         return;\n                 }\n                 if(mylastid%2 ==0){\n                     blklastind      = (mylastid/2)*NB+1+j-1;\n                 }else{\n                      colpt      = ((mylastid+1)/2)*NB + 1 +j -1 ;\n                      stind      = colpt-NB+1;\n                      edind      = min(colpt,N);\n                      if( (stind>=edind-1) && (edind==N) )\n                          blklastind=N;\n                      else\n                          blklastind=0;\n                 }\n                 if(blklastind >= (N-1))  stt=stt+1;\n           } // END for j=st:ed\n        } // END for m=1:stepercol\n     } // END for i=1:N-2\n  } // END for thgrid=1:thgrnb\n\n} // END FUNCTION\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////\n#endif\n\n\n\n\n\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////\nint blgchase_ztrdv1(int NT, int N, int NB, parsec_complex64_t *A, parsec_complex64_t *V, parsec_complex64_t *TAU, int sweep, int id, int blktile) {\n  int    /*edloc,*/ stloc, st, ed, KDM1, LDA;\n\n  (void)NT;\n  KDM1   = NB-1;\n  LDA    = NB+1;\n  /* generate the indiceslocal and global*/\n  stloc  = (sweep+1)%NB;\n  if(stloc==0) stloc=NB;\n  /*if(id==NT-1)\n     edloc = NB-1;\n  else\n     edloc = stloc + KDM1;\n  */\n\n  st = min(id*NB+stloc, N-1);\n  ed = min(st+KDM1, N-1);\n  /*\n   * i     = (N-1)%ed;\n   * edloc = i%NB+NB;\n   */\n\n  /* quick return in case of last tile */\n  if(st==ed)\n     return 0;\n\n  /* because the kernel have been writted for fortran, add 1 */\n   st = st +1;\n   ed = ed +1;\n  /* code for all tiles */\n  if(id==blktile){\n     TRD_type1bHL(N, NB, A, LDA, V, TAU, st, ed);\n     TRD_type2bHL(N, NB, A, LDA, V, TAU, st, ed);\n  }else{\n     TRD_type3bHL(N, NB, A, LDA, V, TAU, st, ed);\n     //if(id==6) return;\n     TRD_type2bHL(N, NB, A, LDA, V, TAU, st, ed);\n  }\n  return 0;\n}\n\n#if 0\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////\n//\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////\nstatic void band_to_trd_vmpi1(int N, int NB, parsec_complex64_t *A, int LDA) {\n  int NT;\n  parsec_complex64_t *V, *TAU;\n  int blktile, S, id, sweep;\n  V   = malloc(N*sizeof(parsec_complex64_t));\n  TAU = malloc(N*sizeof(parsec_complex64_t));\n  memset(V,0,N*sizeof(parsec_complex64_t));\n  memset(TAU,0,N*sizeof(parsec_complex64_t));\n\n\n  NT = N/NB;\n  if(NT*NB != N){\n      printf(\"ERROR NT*NB not equal N \\n\");\n      return;\n  }\n\n  //printf(\"voici NT, N NB %d %d %d\\n\",NT,N,NB);\n  for (blktile = 0; blktile<NT; blktile++){\n     for (S = 0; S<NB; S++){\n        sweep = blktile*NB + S ;\n        for (id = blktile; id<NT; id++){\n               blgchase_ztrdv1 (NT, N, NB, A, V, TAU, sweep , id, blktile);\n        }\n     }\n  }\n\n}\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////\n#endif\n\n\n\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////\nint blgchase_ztrdv2(int NT, int N, int NB, parsec_complex64_t *A1, parsec_complex64_t *A2, parsec_complex64_t *V1, parsec_complex64_t *TAU1, parsec_complex64_t *V2, parsec_complex64_t *TAU2, int sweep, int id, int blktile) {\n  int    edloc, stloc, st, ed, KDM1, LDA;\n\n  KDM1   = NB-1;\n  LDA    = NB+1;\n  /* generate the indiceslocal and global*/\n  stloc  = (sweep+1)%NB;\n  if(stloc==0) stloc=NB;\n  if(id==NT-1)\n     edloc = NB-1;\n  else\n     edloc = stloc + KDM1;\n\n  st = min(id*NB+stloc, N-1);\n  ed = min(st+KDM1, N-1);\n  /*\n   * i     = (N-1)%ed;\n   * edloc = i%NB+NB;\n   */\n\n  /* quick return in case of last tile */\n  if(st==ed)\n     return 0;\n\n\n  /* code for all tiles */\n  if(id==blktile){\n     CORE_zhbtelr(N, NB, A1, LDA, A2, LDA, V1, TAU1, stloc, edloc);\n     CORE_zhbtrce(N, NB, A1, LDA, A2, LDA, V1, TAU1, V2, TAU2, stloc, edloc, ed);\n  }else{\n     CORE_zhbtlrx(N, NB, A1, LDA, A2, LDA, V1, TAU1, stloc, edloc);\n     CORE_zhbtrce(N, NB, A1, LDA, A2, LDA, V1, TAU1, V2, TAU2, stloc, edloc, ed);\n  }\n  return 0;\n}\n\n#if 0\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////\n//\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////\nstatic void band_to_trd_vmpi2(int N, int NB, parsec_complex64_t *A, int LDA) {\n    int NT;\n    parsec_complex64_t *V, *TAU;\n    int blktile, S, id, sweep;\n    V   = malloc(N*sizeof(parsec_complex64_t));\n    TAU = malloc(N*sizeof(parsec_complex64_t));\n    memset(V,0,N*sizeof(parsec_complex64_t));\n    memset(TAU,0,N*sizeof(parsec_complex64_t));\n\n\n    NT = N/NB;\n    if(NT*NB != N){\n        printf(\"ERROR NT*NB not equal N \\n\");\n        return;\n    }\n\n    //printf(\"voici NT, N NB %d %d %d\\n\",NT,N,NB);\n    for (blktile = 0; blktile<NT; blktile++){\n        for (S = 0; S<NB; S++){\n            sweep = blktile*NB + S ;\n            for (id = blktile; id<NT; id++){\n                //printf(\"voici  blktile %d    S %d     id %d   sweep %d   \\n\",blktile, S, id, sweep);\n                blgchase_ztrdv2 (NT, N, NB,\n                                A+(id*NB*LDA), A+((id+1)*NB*LDA),\n                                V+(id*NB), TAU+(id*NB),\n                                V+((id+1)*NB), TAU+((id+1)*NB),\n                                sweep, id, blktile);\n            }\n            //if(sweep==0) return;\n        }\n    }\n\n}\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////\n#endif\n", "meta": {"hexsha": "8d54f6307f2d8a35c90f00f37127aefb294040bc", "size": 34523, "ext": "c", "lang": "C", "max_stars_repo_path": "dplasma/cores/core_ztrdv.c", "max_stars_repo_name": "NLAFET/ABFT", "max_stars_repo_head_hexsha": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8", "max_stars_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-08-13T10:13:00.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-13T10:13:00.000Z", "max_issues_repo_path": "dplasma/cores/core_ztrdv.c", "max_issues_repo_name": "NLAFET/ABFT", "max_issues_repo_head_hexsha": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8", "max_issues_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dplasma/cores/core_ztrdv.c", "max_forks_repo_name": "NLAFET/ABFT", "max_forks_repo_head_hexsha": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8", "max_forks_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5540679712, "max_line_length": 237, "alphanum_fraction": 0.4496422675, "num_tokens": 11798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.03732688600549891, "lm_q1q2_score": 0.017498494280524204}}
{"text": "#ifndef MATCH_H_COIEXYNJ\n#define MATCH_H_COIEXYNJ\n\n#include <gsl/gsl>\n#include <sens_loc/analysis/recognition_performance.h>\n#include <sens_loc/math/pointcloud.h>\n#include <utility>\n#include <vector>\n\nnamespace sens_loc::analysis {\n\n/// Create linear vectors that pair the keypoints from \\c kp0 to \\c kp1\n/// according to \\c matches.\n///\n/// \\pre \\c query is the query set in \\c matches.\n/// \\pre \\c train is the training set in \\c matches.\n/// \\param matches Set of matches in \\c query and \\c train\n/// \\param query Set of keypoints that were matched as the query set.\n/// \\param train Set of keypoints that were matched as the training set.\n/// \\returns \\c pair{QueriedKps, TrainedKps} were each vector contains only\n/// matched keypoints. All other keypoints are discarded in the result.\nstd::pair<math::imagepoints_t, math::imagepoints_t>\ngather_correspondences(gsl::span<const keypoint_correspondence> matches,\n                       const math::imagepoints_t&               query,\n                       const math::imagepoints_t&               train) noexcept;\n}  // namespace sens_loc::analysis\n\n#endif /* end of include guard: MATCH_H_COIEXYNJ */\n", "meta": {"hexsha": "a67092447ee0962195593c45ca6b79e409aa9a65", "size": 1156, "ext": "h", "lang": "C", "max_stars_repo_path": "src/include/sens_loc/analysis/match.h", "max_stars_repo_name": "JonasToth/depth-conversions", "max_stars_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-09-30T07:09:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T09:14:35.000Z", "max_issues_repo_path": "src/include/sens_loc/analysis/match.h", "max_issues_repo_name": "JonasToth/depth-conversions", "max_issues_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/include/sens_loc/analysis/match.h", "max_forks_repo_name": "JonasToth/depth-conversions", "max_forks_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.8620689655, "max_line_length": 80, "alphanum_fraction": 0.7067474048, "num_tokens": 283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3629692055196168, "lm_q2_score": 0.04813677367700579, "lm_q1q2_score": 0.017472166497820397}}
{"text": "// MIT License Copyright (c) 2020 Jarrett Wendt\n\n#pragma once\n\n#define _SILENCE_CLANG_COROUTINE_MESSAGE\n\n// Standard\n#include <algorithm>\n#include <cassert>\n#include <chrono>\n#include <cmath>\n#include <cstdint>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <exception>\n#include <filesystem>\n#include <fstream>\n#include <functional>\n#include <future>\n#include <initializer_list>\n#include <iostream>\n#include <new>\n#include <random>\n#include <sstream>\n#include <stdexcept>\n#include <string>\n#include <thread>\n#include <tuple>\n#include <utility>\n#include <vector>\n\n#ifdef _WIN32\n#include <experimental/coroutine>\n#else\n#include <coroutine>\n#endif\n\n// External\n#include <gsl/gsl>\n", "meta": {"hexsha": "68f6c451977ab0cf06d6b5c1517f62bc93f023d1", "size": 695, "ext": "h", "lang": "C", "max_stars_repo_path": "source/Library/pch.h", "max_stars_repo_name": "JarrettWendt/FIEAEngine", "max_stars_repo_head_hexsha": "0bf7e89cd66fec29550f7d7a1a11f5cf398c27e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-05-27T14:01:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T09:11:58.000Z", "max_issues_repo_path": "source/Library/pch.h", "max_issues_repo_name": "JarrettWendt/FIEAEngine", "max_issues_repo_head_hexsha": "0bf7e89cd66fec29550f7d7a1a11f5cf398c27e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/Library/pch.h", "max_forks_repo_name": "JarrettWendt/FIEAEngine", "max_forks_repo_head_hexsha": "0bf7e89cd66fec29550f7d7a1a11f5cf398c27e5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.9512195122, "max_line_length": 47, "alphanum_fraction": 0.7482014388, "num_tokens": 162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21733753118592733, "lm_q2_score": 0.08035747267640012, "lm_q1q2_score": 0.017464694723829412}}
{"text": "#ifndef S3D_DISPARITY_VIEWER_DEPTH_CONVERTER_H\n#define S3D_DISPARITY_VIEWER_DEPTH_CONVERTER_H\n\n#include <s3d/utilities/eigen.h>\n\n#include <vector>\n\n#include <gsl/gsl>\n\nnamespace s3d {\n\nstruct ViewerContext;\n\nclass ViewerDepthConverter {\n public:\n  using Point = Eigen::Vector2d;\n  using Pointf = Eigen::Vector2f;\n\n  explicit ViewerDepthConverter(gsl::not_null<ViewerContext*> context);\n\n  std::vector<float> computePerceivedDepth(const std::vector<float>& disparitiesPercent);\n\n  // horizontal position and depth in meters\n  std::vector<Pointf> computeDepthPositions(const std::vector<Point>& imagePoints,\n                                            const std::vector<float>& disparities);\n\n  float computePerceivedDepth(float disparityPercent);\n\n  // 0 in the middle of the image\n  float computeHorizontalPosition(float imageX);\n\n  std::vector<float> computeHorizontalPositions(const std::vector<Point>& imagePoints);\n\n  void setViewerContext(gsl::not_null<ViewerContext*> viewerContext);\n\n private:\n  ViewerContext* viewerContext_;\n};\n}  // namespace s3d\n\n#endif  // S3D_DISPARITY_VIEWER_DEPTH_CONVERTER_H\n", "meta": {"hexsha": "2459cef6d834706fe79e469e01f13bff13ff4d58", "size": 1108, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/s3d/include/s3d/disparity/viewer_depth_converter.h", "max_stars_repo_name": "hugbed/OpenS3D", "max_stars_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-16T16:38:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-20T03:23:15.000Z", "max_issues_repo_path": "src/core/s3d/include/s3d/disparity/viewer_depth_converter.h", "max_issues_repo_name": "hugbed/OpenS3D", "max_issues_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 40.0, "max_issues_repo_issues_event_min_datetime": "2017-04-12T17:24:44.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-21T18:41:23.000Z", "max_forks_repo_path": "src/core/s3d/include/s3d/disparity/viewer_depth_converter.h", "max_forks_repo_name": "hugbed/OpenS3D", "max_forks_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-07-13T21:51:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-18T16:22:03.000Z", "avg_line_length": 26.380952381, "max_line_length": 89, "alphanum_fraction": 0.7536101083, "num_tokens": 258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4148988313272769, "lm_q2_score": 0.04208773272170267, "lm_q1q2_score": 0.01746215111944923}}
{"text": "#ifndef OPENMC_TALLIES_FILTER_MU_H\n#define OPENMC_TALLIES_FILTER_MU_H\n\n#include <vector>\n\n#include <gsl/gsl>\n\n#include \"openmc/tallies/filter.h\"\n\nnamespace openmc {\n\n//==============================================================================\n//! Bins the incoming-outgoing direction cosine.  This is only used for scatter\n//! reactions.\n//==============================================================================\n\nclass MuFilter : public Filter\n{\npublic:\n  //----------------------------------------------------------------------------\n  // Constructors, destructors\n\n  ~MuFilter() = default;\n\n  //----------------------------------------------------------------------------\n  // Methods\n\n  std::string type() const override {return \"mu\";}\n\n  void from_xml(pugi::xml_node node) override;\n\n  void get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match)\n  const override;\n\n  void to_statepoint(hid_t filter_group) const override;\n\n  std::string text_label(int bin) const override;\n\n  //----------------------------------------------------------------------------\n  // Accessors\n\n  void set_bins(gsl::span<double> bins);\n\nprivate:\n  //----------------------------------------------------------------------------\n  // Data members\n\n  std::vector<double> bins_;\n};\n\n} // namespace openmc\n#endif // OPENMC_TALLIES_FILTER_MU_H\n", "meta": {"hexsha": "7f6f29e5f7e581ae6ef5d59c2feb92ccd694ec5b", "size": 1352, "ext": "h", "lang": "C", "max_stars_repo_path": "include/openmc/tallies/filter_mu.h", "max_stars_repo_name": "Hit-Weixg/openmc", "max_stars_repo_head_hexsha": "c5f66a3af5c1a57087e330f7b870e89a82267e4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-01-10T13:14:35.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-05T10:18:12.000Z", "max_issues_repo_path": "include/openmc/tallies/filter_mu.h", "max_issues_repo_name": "mehmeturkmen/openmc", "max_issues_repo_head_hexsha": "ffe0f0283a81d32759e4f877909bbb64d5ad0d3d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-03-14T12:18:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-01T15:23:23.000Z", "max_forks_repo_path": "include/openmc/tallies/filter_mu.h", "max_forks_repo_name": "mehmeturkmen/openmc", "max_forks_repo_head_hexsha": "ffe0f0283a81d32759e4f877909bbb64d5ad0d3d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-07-31T21:03:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-22T20:54:48.000Z", "avg_line_length": 25.5094339623, "max_line_length": 84, "alphanum_fraction": 0.4718934911, "num_tokens": 247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869689484852374, "lm_q2_score": 0.04146226826976642, "lm_q1q2_score": 0.017360122977927675}}
{"text": "/* bst.c\n * \n * Copyright (C) 2018 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <stdlib.h>\n#include <math.h>\n\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_bst.h>\n#include <gsl/gsl_errno.h>\n\nstatic void * bst_malloc(size_t size, void * params);\nstatic void bst_free(void * block, void * params);\n\nstatic const gsl_bst_allocator bst_default_allocator =\n{\n  bst_malloc,\n  bst_free\n};\n\n/*\ngsl_bst_alloc()\n  Allocate binary search tree\n\nInputs: T         - tree type\n        allocator - memory allocator\n        compare   - comparison function\n        params    - parameters to pass to allocator and compare\n*/\n\ngsl_bst_workspace *\ngsl_bst_alloc(const gsl_bst_type * T, const gsl_bst_allocator * allocator,\n              gsl_bst_cmp_function * compare, void * params)\n{\n  int status;\n  gsl_bst_workspace *w;\n\n  w = calloc(1, sizeof(gsl_bst_workspace));\n  if (w == NULL)\n    {\n      GSL_ERROR_NULL(\"failed to allocate bst workspace\", GSL_ENOMEM);\n    }\n\n  w->type = T;\n\n  status = (w->type->init)(allocator != NULL ? allocator : &bst_default_allocator, compare, params, (void *) &w->table);\n  if (status)\n    {\n      gsl_bst_free(w);\n      GSL_ERROR_NULL(\"failed to initialize bst\", GSL_EFAILED);\n    }\n\n  return w;\n}\n\nvoid\ngsl_bst_free(gsl_bst_workspace * w)\n{\n  /* free tree nodes */\n  gsl_bst_empty(w);\n\n  free(w);\n}\n\n/* delete all nodes from tree */\nint\ngsl_bst_empty(gsl_bst_workspace * w)\n{\n  return (w->type->empty)((void *) &w->table);\n}\n\n/*\ngsl_bst_insert()\n  Inserts |item| into tree\n  \nAVL: if duplicate found, returns pointer to item without inserting\nAVLmult: if duplicate found, increase multiplicity for that node\n\nIf no duplicate found, insert item and return pointer to item.\nReturns NULL if a memory allocation error occurred.\n*/\n\nvoid *\ngsl_bst_insert(void * item, gsl_bst_workspace * w)\n{\n  return (w->type->insert)(item, (void *) &w->table);\n}\n\nvoid *\ngsl_bst_find(const void * item, const gsl_bst_workspace * w)\n{\n  return (w->type->find)(item, (const void *) &w->table);\n}\n\nvoid *\ngsl_bst_remove(const void * item, gsl_bst_workspace * w)\n{\n  return (w->type->remove)(item, (void *) &w->table);\n}\n\n/* return number of nodes in tree */\nsize_t\ngsl_bst_nodes(const gsl_bst_workspace * w)\n{\n  return (w->type->nodes)((const void *) &w->table);\n}\n\n/* return size (in bytes) of each node in tree */\nsize_t\ngsl_bst_node_size(const gsl_bst_workspace * w)\n{\n  return w->type->node_size;\n}\n\nconst char *\ngsl_bst_name(const gsl_bst_workspace * w)\n{\n  return w->type->name;\n}\n\n/**********************************************\n * INTERNAL ROUTINES                          *\n **********************************************/\n\nstatic void *\nbst_malloc(size_t size, void * params)\n{\n  (void) params; /* avoid unused parameter warning */\n  return malloc(size);\n}\n\nstatic void\nbst_free(void * block, void * params)\n{\n  (void) params; /* avoid unused parameter warning */\n  free(block);\n}\n", "meta": {"hexsha": "b8802454fd41536e9a88d1170ddfcd364ed212d6", "size": 3611, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/bst/bst.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "gsl-2.6/bst/bst.c", "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "test/lib/gsl-2.6/bst/bst.c", "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 23.4480519481, "max_line_length": 120, "alphanum_fraction": 0.6712821933, "num_tokens": 933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.038466196289678546, "lm_q1q2_score": 0.017286425288457204}}
{"text": "/*\n    -- MAGMA (version 2.5.4) --\n       Univ. of Tennessee, Knoxville\n       Univ. of California, Berkeley\n       Univ. of Colorado, Denver\n       @date October 2020\n*/\n\n#ifndef MAGMA_TYPES_H\n#define MAGMA_TYPES_H\n\n#include <stdint.h>\n#include <assert.h>\n\n\n// for backwards compatability\n#ifdef HAVE_clAmdBlas\n#define HAVE_clBLAS\n#endif\n\n// each implementation of MAGMA defines HAVE_* appropriately.\n#if ! defined(HAVE_CUBLAS) && ! defined(HAVE_clBLAS) && ! defined(HAVE_MIC)\n#define HAVE_CUBLAS\n#endif\n\n\n// =============================================================================\n// C99 standard defines __func__. Some older compilers use __FUNCTION__.\n// Note __func__ in C99 is not a macro, so ifndef __func__ doesn't work.\n#if __STDC_VERSION__ < 199901L\n  #ifndef __func__\n    #if __GNUC__ >= 2 || _MSC_VER >= 1300\n      #define __func__ __FUNCTION__\n    #else\n      #define __func__ \"<unknown>\"\n    #endif\n  #endif\n#endif\n\n\n// =============================================================================\n// To use int64_t, link with mkl_intel_ilp64 or similar (instead of mkl_intel_lp64).\n// Similar to magma_int_t we declare magma_index_t used for row/column indices in sparse\n#if defined(MAGMA_ILP64) || defined(MKL_ILP64)\ntypedef long long int magma_int_t;  // MKL uses long long int, not int64_t\n#else\ntypedef int magma_int_t;\n#endif\n\ntypedef int magma_index_t;\ntypedef unsigned int magma_uindex_t;\n\n// Define new type that the precision generator will not change (matches PLASMA)\ntypedef double real_Double_t;\n\n\n// =============================================================================\n// define types specific to implementation (CUDA, OpenCL, MIC)\n// define macros to deal with complex numbers\n#if defined(HAVE_CUBLAS)\n    // include cublas_v2.h, unless cublas.h has already been included, e.g., via magma.h\n    #ifndef CUBLAS_H_\n    #include <cuda.h>    // for CUDA_VERSION\n    #include <cublas_v2.h>\n    #endif\n\n    #include <cusparse_v2.h>\n\n    #ifdef __cplusplus\n    extern \"C\" {\n    #endif\n\n    // opaque queue structure\n    struct magma_queue;\n    typedef struct magma_queue* magma_queue_t;\n    typedef cudaEvent_t    magma_event_t;\n    typedef magma_int_t    magma_device_t;\n\n    // Half precision in CUDA \n    #if defined(__cplusplus) && CUDA_VERSION >= 7500\n    #include <cuda_fp16.h>\n    typedef __half           magmaHalf;\n    #else\n    // use short for cuda older than 7.5 \n    // corresponding routines would not work anyway since there is no half precision\n    typedef short            magmaHalf;\n    #endif    // CUDA_VERSION >= 7500\n\n    typedef cuDoubleComplex magmaDoubleComplex;\n    typedef cuFloatComplex  magmaFloatComplex;\n\n    cudaStream_t     magma_queue_get_cuda_stream    ( magma_queue_t queue );\n    cublasHandle_t   magma_queue_get_cublas_handle  ( magma_queue_t queue );\n    cusparseHandle_t magma_queue_get_cusparse_handle( magma_queue_t queue );\n\n    /// @addtogroup magma_complex\n    /// @{\n\n    #define MAGMA_Z_MAKE(r,i)     make_cuDoubleComplex(r, i)    ///< @return complex number r + i*sqrt(-1).\n    #define MAGMA_Z_REAL(a)       (a).x                         ///< @return real component of a.\n    #define MAGMA_Z_IMAG(a)       (a).y                         ///< @return imaginary component of a.\n    #define MAGMA_Z_ADD(a, b)     cuCadd(a, b)                  ///< @return (a + b).\n    #define MAGMA_Z_SUB(a, b)     cuCsub(a, b)                  ///< @return (a - b).\n    #define MAGMA_Z_MUL(a, b)     cuCmul(a, b)                  ///< @return (a * b).\n    #define MAGMA_Z_DIV(a, b)     cuCdiv(a, b)                  ///< @return (a / b).\n    #define MAGMA_Z_ABS(a)        cuCabs(a)                     ///< @return absolute value, |a| = sqrt( real(a)^2 + imag(a)^2 ).\n    #define MAGMA_Z_ABS1(a)       (fabs((a).x) + fabs((a).y))   ///< @return 1-norm absolute value, | real(a) | + | imag(a) |.\n    #define MAGMA_Z_CONJ(a)       cuConj(a)                     ///< @return conjugate of a.\n\n    #define MAGMA_C_MAKE(r,i)     make_cuFloatComplex(r, i)\n    #define MAGMA_C_REAL(a)       (a).x\n    #define MAGMA_C_IMAG(a)       (a).y\n    #define MAGMA_C_ADD(a, b)     cuCaddf(a, b)\n    #define MAGMA_C_SUB(a, b)     cuCsubf(a, b)\n    #define MAGMA_C_MUL(a, b)     cuCmulf(a, b)\n    #define MAGMA_C_DIV(a, b)     cuCdivf(a, b)\n    #define MAGMA_C_ABS(a)        cuCabsf(a)\n    #define MAGMA_C_ABS1(a)       (fabsf((a).x) + fabsf((a).y))\n    #define MAGMA_C_CONJ(a)       cuConjf(a)\n\n    /// @}\n    // end group magma_complex\n\n    #ifdef __cplusplus\n    }\n    #endif\n#elif defined(HAVE_clBLAS)\n    #include <clBLAS.h>\n\n    #ifdef __cplusplus\n    extern \"C\" {\n    #endif\n\n    typedef cl_command_queue  magma_queue_t;\n    typedef cl_event          magma_event_t;\n    typedef cl_device_id      magma_device_t;\n\n    typedef short         magmaHalf;    // placeholder until FP16 is supported \n    typedef DoubleComplex magmaDoubleComplex;\n    typedef FloatComplex  magmaFloatComplex;\n\n    cl_command_queue magma_queue_get_cl_queue( magma_queue_t queue );\n\n    #define MAGMA_Z_MAKE(r,i)     doubleComplex(r,i)\n    #define MAGMA_Z_REAL(a)       (a).s[0]\n    #define MAGMA_Z_IMAG(a)       (a).s[1]\n    #define MAGMA_Z_ADD(a, b)     MAGMA_Z_MAKE((a).s[0] + (b).s[0], (a).s[1] + (b).s[1])\n    #define MAGMA_Z_SUB(a, b)     MAGMA_Z_MAKE((a).s[0] - (b).s[0], (a).s[1] - (b).s[1])\n    #define MAGMA_Z_MUL(a, b)     ((a) * (b))\n    #define MAGMA_Z_DIV(a, b)     ((a) / (b))\n    #define MAGMA_Z_ABS(a)        magma_cabs(a)\n    #define MAGMA_Z_ABS1(a)       (fabs((a).s[0]) + fabs((a).s[1]))\n    #define MAGMA_Z_CONJ(a)       MAGMA_Z_MAKE((a).s[0], -(a).s[1])\n\n    #define MAGMA_C_MAKE(r,i)     floatComplex(r,i)\n    #define MAGMA_C_REAL(a)       (a).s[0]\n    #define MAGMA_C_IMAG(a)       (a).s[1]\n    #define MAGMA_C_ADD(a, b)     MAGMA_C_MAKE((a).s[0] + (b).s[0], (a).s[1] + (b).s[1])\n    #define MAGMA_C_SUB(a, b)     MAGMA_C_MAKE((a).s[0] - (b).s[0], (a).s[1] - (b).s[1])\n    #define MAGMA_C_MUL(a, b)     ((a) * (b))\n    #define MAGMA_C_DIV(a, b)     ((a) / (b))\n    #define MAGMA_C_ABS(a)        magma_cabsf(a)\n    #define MAGMA_C_ABS1(a)       (fabsf((a).s[0]) + fabsf((a).s[1]))\n    #define MAGMA_C_CONJ(a)       MAGMA_C_MAKE((a).s[0], -(a).s[1])\n\n    #ifdef __cplusplus\n    }\n    #endif\n#elif defined(HAVE_MIC)\n    #include <complex>\n\n    #ifdef __cplusplus\n    extern \"C\" {\n    #endif\n\n    typedef int   magma_queue_t;\n    typedef int   magma_event_t;\n    typedef int   magma_device_t;\n\n    typedef short                 magmaHalf;    // placeholder until FP16 is supported \n    typedef std::complex<float>   magmaFloatComplex;\n    typedef std::complex<double>  magmaDoubleComplex;\n\n    #define MAGMA_Z_MAKE(r, i)    std::complex<double>(r,i)\n    #define MAGMA_Z_REAL(x)       (x).real()\n    #define MAGMA_Z_IMAG(x)       (x).imag()\n    #define MAGMA_Z_ADD(a, b)     ((a)+(b))\n    #define MAGMA_Z_SUB(a, b)     ((a)-(b))\n    #define MAGMA_Z_MUL(a, b)     ((a)*(b))\n    #define MAGMA_Z_DIV(a, b)     ((a)/(b))\n    #define MAGMA_Z_ABS(a)        abs(a)\n    #define MAGMA_Z_ABS1(a)       (fabs((a).real()) + fabs((a).imag()))\n    #define MAGMA_Z_CONJ(a)       conj(a)\n\n    #define MAGMA_C_MAKE(r, i)    std::complex<float> (r,i)\n    #define MAGMA_C_REAL(x)       (x).real()\n    #define MAGMA_C_IMAG(x)       (x).imag()\n    #define MAGMA_C_ADD(a, b)     ((a)+(b))\n    #define MAGMA_C_SUB(a, b)     ((a)-(b))\n    #define MAGMA_C_MUL(a, b)     ((a)*(b))\n    #define MAGMA_C_DIV(a, b)     ((a)/(b))\n    #define MAGMA_C_ABS(a)        abs(a)\n    #define MAGMA_C_ABS1(a)       (fabs((a).real()) + fabs((a).imag()))\n    #define MAGMA_C_CONJ(a)       conj(a)\n\n    #ifdef __cplusplus\n    }\n    #endif\n#else\n    #error \"One of HAVE_CUBLAS, HAVE_clBLAS, or HAVE_MIC must be defined. For example, add -DHAVE_CUBLAS to CFLAGS, or #define HAVE_CUBLAS before #include <magma.h>. In MAGMA, this happens in Makefile.\"\n#endif\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#define MAGMA_Z_EQUAL(a,b)        (MAGMA_Z_REAL(a)==MAGMA_Z_REAL(b) && MAGMA_Z_IMAG(a)==MAGMA_Z_IMAG(b))\n#define MAGMA_Z_NEGATE(a)         MAGMA_Z_MAKE( -MAGMA_Z_REAL(a), -MAGMA_Z_IMAG(a))\n\n#define MAGMA_C_EQUAL(a,b)        (MAGMA_C_REAL(a)==MAGMA_C_REAL(b) && MAGMA_C_IMAG(a)==MAGMA_C_IMAG(b))\n#define MAGMA_C_NEGATE(a)         MAGMA_C_MAKE( -MAGMA_C_REAL(a), -MAGMA_C_IMAG(a))\n\n#define MAGMA_D_MAKE(r,i)         (r)\n#define MAGMA_D_REAL(x)           (x)\n#define MAGMA_D_IMAG(x)           (0.0)\n#define MAGMA_D_ADD(a, b)         ((a) + (b))\n#define MAGMA_D_SUB(a, b)         ((a) - (b))\n#define MAGMA_D_MUL(a, b)         ((a) * (b))\n#define MAGMA_D_DIV(a, b)         ((a) / (b))\n#define MAGMA_D_ABS(a)            ((a)>0 ? (a) : -(a))\n#define MAGMA_D_ABS1(a)           ((a)>0 ? (a) : -(a))\n#define MAGMA_D_CONJ(a)           (a)\n#define MAGMA_D_EQUAL(a,b)        ((a) == (b))\n#define MAGMA_D_NEGATE(a)         (-a)\n\n#define MAGMA_S_MAKE(r,i)         (r)\n#define MAGMA_S_REAL(x)           (x)\n#define MAGMA_S_IMAG(x)           (0.0)\n#define MAGMA_S_ADD(a, b)         ((a) + (b))\n#define MAGMA_S_SUB(a, b)         ((a) - (b))\n#define MAGMA_S_MUL(a, b)         ((a) * (b))\n#define MAGMA_S_DIV(a, b)         ((a) / (b))\n#define MAGMA_S_ABS(a)            ((a)>0 ? (a) : -(a))\n#define MAGMA_S_ABS1(a)           ((a)>0 ? (a) : -(a))\n#define MAGMA_S_CONJ(a)           (a)\n#define MAGMA_S_EQUAL(a,b)        ((a) == (b))\n#define MAGMA_S_NEGATE(a)         (-a)\n\n#define MAGMA_Z_ZERO              MAGMA_Z_MAKE( 0.0, 0.0)\n#define MAGMA_Z_ONE               MAGMA_Z_MAKE( 1.0, 0.0)\n#define MAGMA_Z_HALF              MAGMA_Z_MAKE( 0.5, 0.0)\n#define MAGMA_Z_NEG_ONE           MAGMA_Z_MAKE(-1.0, 0.0)\n#define MAGMA_Z_NEG_HALF          MAGMA_Z_MAKE(-0.5, 0.0)\n\n#define MAGMA_C_ZERO              MAGMA_C_MAKE( 0.0, 0.0)\n#define MAGMA_C_ONE               MAGMA_C_MAKE( 1.0, 0.0)\n#define MAGMA_C_HALF              MAGMA_C_MAKE( 0.5, 0.0)\n#define MAGMA_C_NEG_ONE           MAGMA_C_MAKE(-1.0, 0.0)\n#define MAGMA_C_NEG_HALF          MAGMA_C_MAKE(-0.5, 0.0)\n\n#define MAGMA_D_ZERO              ( 0.0)\n#define MAGMA_D_ONE               ( 1.0)\n#define MAGMA_D_HALF              ( 0.5)\n#define MAGMA_D_NEG_ONE           (-1.0)\n#define MAGMA_D_NEG_HALF          (-0.5)\n\n#define MAGMA_S_ZERO              ( 0.0)\n#define MAGMA_S_ONE               ( 1.0)\n#define MAGMA_S_HALF              ( 0.5)\n#define MAGMA_S_NEG_ONE           (-1.0)\n#define MAGMA_S_NEG_HALF          (-0.5)\n\n#ifndef CBLAS_SADDR\n#define CBLAS_SADDR(a)  &(a)\n#endif\n\n// for MAGMA_[CZ]_ABS\ndouble magma_cabs ( magmaDoubleComplex x );\nfloat  magma_cabsf( magmaFloatComplex  x );\n\n#if defined(HAVE_clBLAS)\n    // OpenCL uses opaque memory references on GPU\n    typedef cl_mem magma_ptr;\n    typedef cl_mem magmaInt_ptr;\n    typedef cl_mem magmaIndex_ptr;\n    typedef cl_mem magmaFloat_ptr;\n    typedef cl_mem magmaDouble_ptr;\n    typedef cl_mem magmaFloatComplex_ptr;\n    typedef cl_mem magmaDoubleComplex_ptr;\n\n    typedef cl_mem magma_const_ptr;\n    typedef cl_mem magmaInt_const_ptr;\n    typedef cl_mem magmaIndex_const_ptr;\n    typedef cl_mem magmaFloat_const_ptr;\n    typedef cl_mem magmaDouble_const_ptr;\n    typedef cl_mem magmaFloatComplex_const_ptr;\n    typedef cl_mem magmaDoubleComplex_const_ptr;\n#else\n    // MIC and CUDA use regular pointers on GPU\n    typedef void               *magma_ptr;\n    typedef magma_int_t        *magmaInt_ptr;\n    typedef magma_index_t      *magmaIndex_ptr;\n    typedef magma_uindex_t     *magmaUIndex_ptr;\n    typedef float              *magmaFloat_ptr;\n    typedef double             *magmaDouble_ptr;\n    typedef magmaFloatComplex  *magmaFloatComplex_ptr;\n    typedef magmaDoubleComplex *magmaDoubleComplex_ptr;\n    typedef magmaHalf          *magmaHalf_ptr;\n\n    typedef void               const *magma_const_ptr;\n    typedef magma_int_t        const *magmaInt_const_ptr;\n    typedef magma_index_t      const *magmaIndex_const_ptr;\n    typedef magma_uindex_t     const *magmaUIndex_const_ptr;\n    typedef float              const *magmaFloat_const_ptr;\n    typedef double             const *magmaDouble_const_ptr;\n    typedef magmaFloatComplex  const *magmaFloatComplex_const_ptr;\n    typedef magmaDoubleComplex const *magmaDoubleComplex_const_ptr;\n    typedef magmaHalf          const *magmaHalf_const_ptr;\n#endif\n\n\n// =============================================================================\n// MAGMA constants\n\n// -----------------------------------------------------------------------------\n#define MAGMA_VERSION_MAJOR 2\n#define MAGMA_VERSION_MINOR 5\n#define MAGMA_VERSION_MICRO 4\n\n// stage is \"svn\", \"beta#\", \"rc#\" (release candidate), or blank (\"\") for final release\n#define MAGMA_VERSION_STAGE \"\"\n\n#define MagmaMaxGPUs 8\n#define MagmaMaxAccelerators 8\n#define MagmaMaxSubs 16\n\n// trsv template parameter\n#define MagmaBigTileSize 1000000\n\n\n// -----------------------------------------------------------------------------\n// Return codes\n// LAPACK argument errors are < 0 but > MAGMA_ERR.\n// MAGMA errors are < MAGMA_ERR.\n/// @addtogroup magma_error_codes\n/// @{\n\n#define MAGMA_SUCCESS               0       ///< operation was successful\n#define MAGMA_ERR                  -100     ///< unspecified error\n#define MAGMA_ERR_NOT_INITIALIZED  -101     ///< magma_init() was not called\n#define MAGMA_ERR_REINITIALIZED    -102     // unused\n#define MAGMA_ERR_NOT_SUPPORTED    -103     ///< not supported on this GPU\n#define MAGMA_ERR_ILLEGAL_VALUE    -104     // unused\n#define MAGMA_ERR_NOT_FOUND        -105     ///< file not found\n#define MAGMA_ERR_ALLOCATION       -106     // unused\n#define MAGMA_ERR_INTERNAL_LIMIT   -107     // unused\n#define MAGMA_ERR_UNALLOCATED      -108     // unused\n#define MAGMA_ERR_FILESYSTEM       -109     // unused\n#define MAGMA_ERR_UNEXPECTED       -110     // unused\n#define MAGMA_ERR_SEQUENCE_FLUSHED -111     // unused\n#define MAGMA_ERR_HOST_ALLOC       -112     ///< could not malloc CPU host memory\n#define MAGMA_ERR_DEVICE_ALLOC     -113     ///< could not malloc GPU device memory\n#define MAGMA_ERR_CUDASTREAM       -114     // unused\n#define MAGMA_ERR_INVALID_PTR      -115     ///< can't free invalid pointer\n#define MAGMA_ERR_UNKNOWN          -116     ///< unspecified error\n#define MAGMA_ERR_NOT_IMPLEMENTED  -117     ///< not implemented yet\n#define MAGMA_ERR_NAN              -118     ///< NaN (not-a-number) detected\n\n// some MAGMA-sparse errors\n#define MAGMA_SLOW_CONVERGENCE     -201\n#define MAGMA_DIVERGENCE           -202\n#define MAGMA_NONSPD               -203\n#define MAGMA_ERR_BADPRECOND       -204\n#define MAGMA_NOTCONVERGED         -205\n\n// When adding error codes, please add to interface_cuda/error.cpp\n\n// map cusparse errors to magma errors\n#define MAGMA_ERR_CUSPARSE                            -3000\n#define MAGMA_ERR_CUSPARSE_NOT_INITIALIZED            -3001\n#define MAGMA_ERR_CUSPARSE_ALLOC_FAILED               -3002\n#define MAGMA_ERR_CUSPARSE_INVALID_VALUE              -3003\n#define MAGMA_ERR_CUSPARSE_ARCH_MISMATCH              -3004\n#define MAGMA_ERR_CUSPARSE_MAPPING_ERROR              -3005\n#define MAGMA_ERR_CUSPARSE_EXECUTION_FAILED           -3006\n#define MAGMA_ERR_CUSPARSE_INTERNAL_ERROR             -3007\n#define MAGMA_ERR_CUSPARSE_MATRIX_TYPE_NOT_SUPPORTED  -3008\n#define MAGMA_ERR_CUSPARSE_ZERO_PIVOT                 -3009\n\n/// @}\n// end group magma_error_codes\n\n\n// -----------------------------------------------------------------------------\n// parameter constants\n// numbering is consistent with CBLAS and PLASMA; see plasma/include/plasma.h\n// also with lapack_cwrapper/include/lapack_enum.h\n// see http://www.netlib.org/lapack/lapwrapc/\ntypedef enum {\n    MagmaFalse         = 0,\n    MagmaTrue          = 1\n} magma_bool_t;\n\ntypedef enum {\n    MagmaRowMajor      = 101,\n    MagmaColMajor      = 102\n} magma_order_t;\n\n// Magma_ConjTrans is an alias for those rare occasions (zlarfb, zun*, zher*k)\n// where we want Magma_ConjTrans to convert to MagmaTrans in precision generation.\ntypedef enum {\n    MagmaNoTrans       = 111,\n    MagmaTrans         = 112,\n    MagmaConjTrans     = 113,\n    Magma_ConjTrans    = MagmaConjTrans\n} magma_trans_t;\n\ntypedef enum {\n    MagmaUpper         = 121,\n    MagmaLower         = 122,\n    MagmaFull          = 123,  /* lascl, laset */\n    MagmaHessenberg    = 124   /* lascl */\n} magma_uplo_t;\n\ntypedef magma_uplo_t magma_type_t;  /* lascl */\n\ntypedef enum {\n    MagmaNonUnit       = 131,\n    MagmaUnit          = 132\n} magma_diag_t;\n\ntypedef enum {\n    MagmaLeft          = 141,\n    MagmaRight         = 142,\n    MagmaBothSides     = 143   /* trevc */\n} magma_side_t;\n\ntypedef enum {\n    MagmaOneNorm       = 171,  /* lange, lanhe */\n    MagmaRealOneNorm   = 172,\n    MagmaTwoNorm       = 173,\n    MagmaFrobeniusNorm = 174,\n    MagmaInfNorm       = 175,\n    MagmaRealInfNorm   = 176,\n    MagmaMaxNorm       = 177,\n    MagmaRealMaxNorm   = 178\n} magma_norm_t;\n\ntypedef enum {\n    MagmaDistUniform   = 201,  /* latms */\n    MagmaDistSymmetric = 202,\n    MagmaDistNormal    = 203\n} magma_dist_t;\n\ntypedef enum {\n    MagmaHermGeev      = 241,  /* latms */\n    MagmaHermPoev      = 242,\n    MagmaNonsymPosv    = 243,\n    MagmaSymPosv       = 244\n} magma_sym_t;\n\ntypedef enum {\n    MagmaNoPacking     = 291,  /* latms */\n    MagmaPackSubdiag   = 292,\n    MagmaPackSupdiag   = 293,\n    MagmaPackColumn    = 294,\n    MagmaPackRow       = 295,\n    MagmaPackLowerBand = 296,\n    MagmaPackUpeprBand = 297,\n    MagmaPackAll       = 298\n} magma_pack_t;\n\ntypedef enum {\n    MagmaNoVec         = 301,  /* geev, syev, gesvd */\n    MagmaVec           = 302,  /* geev, syev */\n    MagmaIVec          = 303,  /* stedc */\n    MagmaAllVec        = 304,  /* gesvd, trevc */\n    MagmaSomeVec       = 305,  /* gesvd, trevc */\n    MagmaOverwriteVec  = 306,  /* gesvd */\n    MagmaBacktransVec  = 307   /* trevc */\n} magma_vec_t;\n\ntypedef enum {\n    MagmaRangeAll      = 311,  /* syevx, etc. */\n    MagmaRangeV        = 312,\n    MagmaRangeI        = 313\n} magma_range_t;\n\ntypedef enum {\n    MagmaQ             = 322,  /* unmbr, ungbr */\n    MagmaP             = 323\n} magma_vect_t;\n\ntypedef enum {\n    MagmaForward       = 391,  /* larfb */\n    MagmaBackward      = 392\n} magma_direct_t;\n\ntypedef enum {\n    MagmaColumnwise    = 401,  /* larfb */\n    MagmaRowwise       = 402\n} magma_storev_t;\n\ntypedef enum {\n    MagmaHybrid        = 701,\n    MagmaNative        = 702\n} magma_mode_t;\n// -----------------------------------------------------------------------------\n// sparse\ntypedef enum {\n    Magma_CSR          = 611,\n    Magma_ELLPACKT     = 612,\n    Magma_ELL          = 613,\n    Magma_DENSE        = 614,\n    Magma_BCSR         = 615,\n    Magma_CSC          = 616,\n    Magma_HYB          = 617,\n    Magma_COO          = 618,\n    Magma_ELLRT        = 619,\n    Magma_SPMVFUNCTION = 620,\n    Magma_SELLP        = 621,\n    Magma_ELLD         = 622,\n    Magma_CSRLIST      = 623,\n    Magma_CSRD         = 624,\n    Magma_CSRL         = 627,\n    Magma_CSRU         = 628,\n    Magma_CSRCOO       = 629,\n    Magma_CUCSR        = 630,\n    Magma_COOLIST      = 631,\n    Magma_CSR5         = 632\n} magma_storage_t;\n\n\ntypedef enum {\n    Magma_CG           = 431,\n    Magma_CGMERGE      = 432,\n    Magma_GMRES        = 433,\n    Magma_BICGSTAB     = 434,\n  Magma_BICGSTABMERGE  = 435,\n  Magma_BICGSTABMERGE2 = 436,\n    Magma_JACOBI       = 437,\n    Magma_GS           = 438,\n    Magma_ITERREF      = 439,\n    Magma_BCSRLU       = 440,\n    Magma_PCG          = 441,\n    Magma_PGMRES       = 442,\n    Magma_PBICGSTAB    = 443,\n    Magma_PASTIX       = 444,\n    Magma_ILU          = 445,\n    Magma_ICC          = 446,\n    Magma_PARILU       = 447,\n    Magma_PARIC        = 448,\n    Magma_BAITER       = 449,\n    Magma_LOBPCG       = 450,\n    Magma_NONE         = 451,\n    Magma_FUNCTION     = 452,\n    Magma_IDR          = 453,\n    Magma_PIDR         = 454,\n    Magma_CGS          = 455,\n    Magma_PCGS         = 456,\n    Magma_CGSMERGE     = 457,\n    Magma_PCGSMERGE    = 458,\n    Magma_TFQMR        = 459,\n    Magma_PTFQMR       = 460,\n    Magma_TFQMRMERGE   = 461,\n    Magma_PTFQMRMERGE  = 462,\n    Magma_QMR          = 463,\n    Magma_PQMR         = 464,\n    Magma_QMRMERGE     = 465,\n    Magma_PQMRMERGE    = 466,\n    Magma_BOMBARD      = 490,\n    Magma_BOMBARDMERGE = 491,\n    Magma_PCGMERGE     = 492,\n    Magma_BAITERO      = 493,\n    Magma_IDRMERGE     = 494,\n  Magma_PBICGSTABMERGE = 495,\n    Magma_PARICT       = 496,\n    Magma_CUSTOMIC     = 497,\n    Magma_CUSTOMILU    = 498,\n    Magma_PIDRMERGE    = 499,\n    Magma_BICG         = 500,\n    Magma_BICGMERGE    = 501,\n    Magma_PBICG        = 502,\n    Magma_PBICGMERGE   = 503,\n    Magma_LSQR         = 504,\n    Magma_PARILUT      = 505,\n    Magma_ISAI         = 506,\n    Magma_CUSOLVE      = 507,\n    Magma_VBJACOBI     = 508,\n    Magma_PARDISO      = 509,\n    Magma_SYNCFREESOLVE= 510,\n    Magma_ILUT         = 511\n} magma_solver_type;\n\ntypedef enum {\n    Magma_CGSO         = 561,\n    Magma_FUSED_CGSO   = 562,\n    Magma_MGSO         = 563\n} magma_ortho_t;\n\ntypedef enum {\n    Magma_CPU          = 571,\n    Magma_DEV          = 572\n} magma_location_t;\n\ntypedef enum {\n    Magma_GENERAL      = 581,\n    Magma_SYMMETRIC    = 582\n} magma_symmetry_t;\n\ntypedef enum {\n    Magma_ORDERED      = 591,\n    Magma_DIAGFIRST    = 592,\n    Magma_UNITY        = 593,\n    Magma_VALUE        = 594\n} magma_diagorder_t;\n\ntypedef enum {\n    Magma_DCOMPLEX     = 501,\n    Magma_FCOMPLEX     = 502,\n    Magma_DOUBLE       = 503,\n    Magma_FLOAT        = 504\n} magma_precision;\n\ntypedef enum {\n    Magma_NOSCALE      = 511,\n    Magma_UNITROW      = 512,\n    Magma_UNITDIAG     = 513,\n    Magma_UNITCOL      = 514,\n    Magma_UNITROWCOL   = 515, // to be deprecated\n    Magma_UNITDIAGCOL  = 516, // to be deprecated\n} magma_scale_t;\n\n\ntypedef enum {\n    Magma_SOLVE        = 801,\n    Magma_SETUPSOLVE   = 802,\n    Magma_APPLYSOLVE   = 803,\n    Magma_DESTROYSOLVE = 804,\n    Magma_INFOSOLVE    = 805,\n    Magma_GENERATEPREC = 806,\n    Magma_PRECONDLEFT  = 807,\n    Magma_PRECONDRIGHT = 808,\n    Magma_TRANSPOSE    = 809,\n    Magma_SPMV         = 810\n} magma_operation_t;\n\ntypedef enum {\n    Magma_PREC_SS           = 900,\n    Magma_PREC_SST          = 901,\n    Magma_PREC_HS           = 902,\n    Magma_PREC_HST          = 903,\n    Magma_PREC_SH           = 904,\n    Magma_PREC_SHT          = 905,\n    \n    Magma_PREC_XHS_H        = 910,\n    Magma_PREC_XHS_HTC      = 911,\n    Magma_PREC_XHS_161616   = 912,\n    Magma_PREC_XHS_161616TC = 913,\n    Magma_PREC_XHS_161632TC = 914,\n    Magma_PREC_XSH_S        = 915,\n    Magma_PREC_XSH_STC      = 916,\n    Magma_PREC_XSH_163232TC = 917,\n    Magma_PREC_XSH_323232TC = 918,\n\n    Magma_REFINE_IRSTRS   = 920,\n    Magma_REFINE_IRDTRS   = 921,\n    Magma_REFINE_IRGMSTRS = 922,\n    Magma_REFINE_IRGMDTRS = 923,\n    Magma_REFINE_GMSTRS   = 924,\n    Magma_REFINE_GMDTRS   = 925,\n    Magma_REFINE_GMGMSTRS = 926,\n    Magma_REFINE_GMGMDTRS = 927,\n\n    Magma_PREC_HD         = 930,\n} magma_refinement_t;\n\ntypedef enum {\n    Magma_MP_BASE_SS              = 950,\n    Magma_MP_BASE_DD              = 951,\n    Magma_MP_BASE_XHS             = 952,\n    Magma_MP_BASE_XSH             = 953,\n    Magma_MP_BASE_XHD             = 954,\n    Magma_MP_BASE_XDH             = 955,\n\n    Magma_MP_ENABLE_DFLT_MATH     = 960,\n    Magma_MP_ENABLE_TC_MATH       = 961,\n    Magma_MP_SGEMM                = 962,\n    Magma_MP_HGEMM                = 963,\n    Magma_MP_GEMEX_I32_O32_C32    = 964,\n    Magma_MP_GEMEX_I16_O32_C32    = 965,\n    Magma_MP_GEMEX_I16_O16_C32    = 966,\n    Magma_MP_GEMEX_I16_O16_C16    = 967,\n\n    Magma_MP_TC_SGEMM             = 968,\n    Magma_MP_TC_HGEMM             = 969,\n    Magma_MP_TC_GEMEX_I32_O32_C32 = 970,\n    Magma_MP_TC_GEMEX_I16_O32_C32 = 971,\n    Magma_MP_TC_GEMEX_I16_O16_C32 = 972,\n    Magma_MP_TC_GEMEX_I16_O16_C16 = 973,\n\n} magma_mp_type_t;\n\n// When adding constants, remember to do these steps as appropriate:\n// 1)  add magma_xxxx_const()  converter below and in control/constants.cpp\n// 2a) add to magma2lapack_constants[] in control/constants.cpp\n// 2b) update min & max here, which are used to check bounds for magma2lapack_constants[]\n// 2c) add lapack_xxxx_const() converter below and in control/constants.cpp\n#define Magma2lapack_Min  MagmaFalse     // 0\n#define Magma2lapack_Max  MagmaRowwise   // 402\n\n\n// -----------------------------------------------------------------------------\n// string constants for calling Fortran BLAS and LAPACK\n// todo: use translators instead? lapack_const_str( MagmaUpper )\n#define MagmaRowMajorStr      \"Row\"\n#define MagmaColMajorStr      \"Col\"\n\n#define MagmaNoTransStr       \"NoTrans\"\n#define MagmaTransStr         \"Trans\"\n#define MagmaConjTransStr     \"ConjTrans\"\n#define Magma_ConjTransStr    \"ConjTrans\"\n\n#define MagmaUpperStr         \"Upper\"\n#define MagmaLowerStr         \"Lower\"\n#define MagmaFullStr          \"Full\"\n\n#define MagmaNonUnitStr       \"NonUnit\"\n#define MagmaUnitStr          \"Unit\"\n\n#define MagmaLeftStr          \"Left\"\n#define MagmaRightStr         \"Right\"\n#define MagmaBothSidesStr     \"Both\"\n\n#define MagmaOneNormStr       \"1\"\n#define MagmaTwoNormStr       \"2\"\n#define MagmaFrobeniusNormStr \"Fro\"\n#define MagmaInfNormStr       \"Inf\"\n#define MagmaMaxNormStr       \"Max\"\n\n#define MagmaForwardStr       \"Forward\"\n#define MagmaBackwardStr      \"Backward\"\n\n#define MagmaColumnwiseStr    \"Columnwise\"\n#define MagmaRowwiseStr       \"Rowwise\"\n\n#define MagmaNoVecStr         \"NoVec\"\n#define MagmaVecStr           \"Vec\"\n#define MagmaIVecStr          \"IVec\"\n#define MagmaAllVecStr        \"All\"\n#define MagmaSomeVecStr       \"Some\"\n#define MagmaOverwriteVecStr  \"Overwrite\"\n\n\n// -----------------------------------------------------------------------------\n// Convert LAPACK character constants to MAGMA constants.\n// This is a one-to-many mapping, requiring multiple translators\n// (e.g., \"N\" can be NoTrans or NonUnit or NoVec).\nmagma_bool_t   magma_bool_const  ( char lapack_char );\nmagma_order_t  magma_order_const ( char lapack_char );\nmagma_trans_t  magma_trans_const ( char lapack_char );\nmagma_uplo_t   magma_uplo_const  ( char lapack_char );\nmagma_diag_t   magma_diag_const  ( char lapack_char );\nmagma_side_t   magma_side_const  ( char lapack_char );\nmagma_norm_t   magma_norm_const  ( char lapack_char );\nmagma_dist_t   magma_dist_const  ( char lapack_char );\nmagma_sym_t    magma_sym_const   ( char lapack_char );\nmagma_pack_t   magma_pack_const  ( char lapack_char );\nmagma_vec_t    magma_vec_const   ( char lapack_char );\nmagma_range_t  magma_range_const ( char lapack_char );\nmagma_vect_t   magma_vect_const  ( char lapack_char );\nmagma_direct_t magma_direct_const( char lapack_char );\nmagma_storev_t magma_storev_const( char lapack_char );\n\n\n// -----------------------------------------------------------------------------\n// Convert MAGMA constants to LAPACK(E) constants.\n// The generic lapack_const_str works for all cases, but the specific routines\n// (e.g., lapack_trans_const) do better error checking.\n\n// magma  defines lapack_const_str, which returns char* to call lapack (Fortran interface).\n// plasma defines lapack_const, which is roughly the same as MAGMA's lapacke_const\n// (returns a char instead of char*) to call lapacke (C interface).\n\nconst char* lapack_const_str   ( int            magma_const );\nconst char* lapack_bool_const  ( magma_bool_t   magma_const );\nconst char* lapack_order_const ( magma_order_t  magma_const );\nconst char* lapack_trans_const ( magma_trans_t  magma_const );\nconst char* lapack_uplo_const  ( magma_uplo_t   magma_const );\nconst char* lapack_diag_const  ( magma_diag_t   magma_const );\nconst char* lapack_side_const  ( magma_side_t   magma_const );\nconst char* lapack_norm_const  ( magma_norm_t   magma_const );\nconst char* lapack_dist_const  ( magma_dist_t   magma_const );\nconst char* lapack_sym_const   ( magma_sym_t    magma_const );\nconst char* lapack_pack_const  ( magma_pack_t   magma_const );\nconst char* lapack_vec_const   ( magma_vec_t    magma_const );\nconst char* lapack_range_const ( magma_range_t  magma_const );\nconst char* lapack_vect_const  ( magma_vect_t   magma_const );\nconst char* lapack_direct_const( magma_direct_t magma_const );\nconst char* lapack_storev_const( magma_storev_t magma_const );\n\nstatic inline char lapacke_const       ( int magma_const            ) { return *lapack_const_str   ( magma_const ); }\nstatic inline char lapacke_bool_const  ( magma_bool_t   magma_const ) { return *lapack_bool_const  ( magma_const ); }\nstatic inline char lapacke_order_const ( magma_order_t  magma_const ) { return *lapack_order_const ( magma_const ); }\nstatic inline char lapacke_trans_const ( magma_trans_t  magma_const ) { return *lapack_trans_const ( magma_const ); }\nstatic inline char lapacke_uplo_const  ( magma_uplo_t   magma_const ) { return *lapack_uplo_const  ( magma_const ); }\nstatic inline char lapacke_diag_const  ( magma_diag_t   magma_const ) { return *lapack_diag_const  ( magma_const ); }\nstatic inline char lapacke_side_const  ( magma_side_t   magma_const ) { return *lapack_side_const  ( magma_const ); }\nstatic inline char lapacke_norm_const  ( magma_norm_t   magma_const ) { return *lapack_norm_const  ( magma_const ); }\nstatic inline char lapacke_dist_const  ( magma_dist_t   magma_const ) { return *lapack_dist_const  ( magma_const ); }\nstatic inline char lapacke_sym_const   ( magma_sym_t    magma_const ) { return *lapack_sym_const   ( magma_const ); }\nstatic inline char lapacke_pack_const  ( magma_pack_t   magma_const ) { return *lapack_pack_const  ( magma_const ); }\nstatic inline char lapacke_vec_const   ( magma_vec_t    magma_const ) { return *lapack_vec_const   ( magma_const ); }\nstatic inline char lapacke_range_const ( magma_range_t  magma_const ) { return *lapack_range_const ( magma_const ); }\nstatic inline char lapacke_vect_const  ( magma_vect_t   magma_const ) { return *lapack_vect_const  ( magma_const ); }\nstatic inline char lapacke_direct_const( magma_direct_t magma_const ) { return *lapack_direct_const( magma_const ); }\nstatic inline char lapacke_storev_const( magma_storev_t magma_const ) { return *lapack_storev_const( magma_const ); }\n\n\n// -----------------------------------------------------------------------------\n// Convert MAGMA constants to clBLAS constants.\n#if defined(HAVE_clBLAS)\nclblasOrder          clblas_order_const( magma_order_t order );\nclblasTranspose      clblas_trans_const( magma_trans_t trans );\nclblasUplo           clblas_uplo_const ( magma_uplo_t  uplo  );\nclblasDiag           clblas_diag_const ( magma_diag_t  diag  );\nclblasSide           clblas_side_const ( magma_side_t  side  );\n#endif\n\n\n// -----------------------------------------------------------------------------\n// Convert MAGMA constants to CUBLAS constants.\n#if defined(CUBLAS_V2_H_)\ncublasOperation_t    cublas_trans_const ( magma_trans_t trans );\ncublasFillMode_t     cublas_uplo_const  ( magma_uplo_t  uplo  );\ncublasDiagType_t     cublas_diag_const  ( magma_diag_t  diag  );\ncublasSideMode_t     cublas_side_const  ( magma_side_t  side  );\n#endif\n\n\n// -----------------------------------------------------------------------------\n// Convert MAGMA constants to CBLAS constants.\n#if defined(HAVE_CBLAS)\n#include <cblas.h>\nenum CBLAS_ORDER     cblas_order_const  ( magma_order_t order );\nenum CBLAS_TRANSPOSE cblas_trans_const  ( magma_trans_t trans );\nenum CBLAS_UPLO      cblas_uplo_const   ( magma_uplo_t  uplo  );\nenum CBLAS_DIAG      cblas_diag_const   ( magma_diag_t  diag  );\nenum CBLAS_SIDE      cblas_side_const   ( magma_side_t  side  );\n#endif\n\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif // MAGMA_TYPES_H\n", "meta": {"hexsha": "aab2929f067d83f8557c782b41dc7137b526c33d", "size": 31435, "ext": "h", "lang": "C", "max_stars_repo_path": "include/magma_types.h", "max_stars_repo_name": "klast/magma", "max_stars_repo_head_hexsha": "cfb849621be6f697288e995831ec3c9e84530d9d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-12-04T13:31:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T11:41:23.000Z", "max_issues_repo_path": "include/magma_types.h", "max_issues_repo_name": "klast/magma", "max_issues_repo_head_hexsha": "cfb849621be6f697288e995831ec3c9e84530d9d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-27T20:00:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-28T06:19:59.000Z", "max_forks_repo_path": "include/magma_types.h", "max_forks_repo_name": "klast/magma", "max_forks_repo_head_hexsha": "cfb849621be6f697288e995831ec3c9e84530d9d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-04T13:23:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-27T00:50:27.000Z", "avg_line_length": 36.6375291375, "max_line_length": 202, "alphanum_fraction": 0.6217909973, "num_tokens": 9103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39233681595684605, "lm_q2_score": 0.04401865017647432, "lm_q1q2_score": 0.017270137052956193}}
{"text": "/***************************************************************************\n                          misc.h  -  description\n                             -------------------\n    copyright            : (C) 2005 by MOUSSA\n    email                : mmousa@liris.cnrs.fr\n ***************************************************************************/\n\n/***************************************************************************\n *                                                                         *\n *   This program is free software; you can redistribute it and/or modify  *\n *   it under the terms of the GNU General Public License as published by  *\n *   the Free Software Foundation; either version 2 of the License, or     *\n *   (at your option) any later version.                                   *\n *                                                                         *\n ***************************************************************************/\n\n#ifndef MISC_H\n#define MISC_H\n\n#include \"config.h\"\n\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_monte.h>\n#include <gsl/gsl_monte_plain.h>\n#include <gsl/gsl_sf.h>\n#include <gsl/gsl_complex.h>\n#include <gsl/gsl_complex_math.h>\n\n\n//////////////////////////////////////////////////////////////////////////////\ntemplate<class T> void Add_vectors(T *vec1, T *vec2, T *result, int size);\ntemplate<class T> void Add_vectors(T *vec1, T *vec2, T *result, int size){\n  for(int i=0; i<size; i++){\n    result[i] = vec1[i]+vec2[i];\n  }\n}\n//////////////////////////////////////////////////////////////////////////////\ntemplate<class T> void Mult_vector_const(T *vec, T c, T *result, int size);\ntemplate<class T> void Mult_vector_const(T *vec, T c, T *result, int size){\n  for(int i=0; i<size; i++){\n    result[i] = vec[i]*c;\n  }\n}\n//////////////////////////////////////////////////////////////////////////////\ntemplate<class T>void assign_value(T *vec, T c, int size);\ntemplate<class T>void assign_value(T *vec, T c, int size){\n  for(int i = 0; i<size; i++) vec[i] = c;\n}\n//////////////////////////////////////////////////////////////////////////////\ntemplate<class T>void copy_vectors(T *src, T *dest, int size);\ntemplate<class T>void copy_vectors(T *src, T *dest, int size){\n  for(int i = 0; i<size; i++){\n    dest[i] = src[i];\n  }\n}\n//////////////////////////////////////////////////////////////////////////////\ntemplate<class T> int is_overlaping(T *vec1, T *vec2, int size);\ntemplate<class T> int is_overlaping(T *vec1, T *vec2, int size){\n  for(int i = 0; i<size; i++){\n    if((fabs(vec1[i])>1e-6)&&(fabs(vec2[i])>1e-6)) return true;\n  }\n  return false;\n}\n//////////////////////////////////////////////////////////////////////////////\ntemplate<class T> void print_vector(T *vec, int size);\ntemplate<class T> void print_vector(T *vec, int size){\n  for(int i = 0; i<size; i++){\n    if(vec[i]>0.0) std::cout<<vec[i]<<std::endl;\n  }\n}\n//////////////////////////////////////////////////////////////////////////////\ntemplate<class T> bool AllOnes(T *vec, int size);\ntemplate<class T> bool AllOnes(T *vec, int size){\n  for(int i = 0; i < size; i++)\n    if(fabs(vec[i]) < 1e-6) return false;\n  return true;\n}\n//////////////////////////////////////////////////////////////////////////////\nint gettoken(char[30], FILE *);\nbool FileName(char[30], char *);\nvoid theta_phi_bounds(Triangle_3 tr, double *mintheta, double *maxtheta, double *minphi, double *maxphi);\nvoid SphericalHarmonic(int, int, double, double, gsl_complex *);\n#endif\n", "meta": {"hexsha": "d0402ae1e9f917a8e4dfafc5b200a445f464e48b", "size": 3480, "ext": "h", "lang": "C", "max_stars_repo_path": "Volume_11/Number_2/Mousa2006/misc.h", "max_stars_repo_name": "kyeonghopark/jgt-code", "max_stars_repo_head_hexsha": "08bbcc298e12582e32cb56a52e70344c57689d73", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 415.0, "max_stars_repo_stars_event_min_datetime": "2015-10-24T17:37:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T04:09:07.000Z", "max_issues_repo_path": "Volume_11/Number_2/Mousa2006/misc.h", "max_issues_repo_name": "kyeonghopark/jgt-code", "max_issues_repo_head_hexsha": "08bbcc298e12582e32cb56a52e70344c57689d73", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2016-01-15T13:23:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-27T01:49:50.000Z", "max_forks_repo_path": "Volume_11/Number_2/Mousa2006/misc.h", "max_forks_repo_name": "kyeonghopark/jgt-code", "max_forks_repo_head_hexsha": "08bbcc298e12582e32cb56a52e70344c57689d73", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 77.0, "max_forks_repo_forks_event_min_datetime": "2015-10-24T22:36:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T01:03:54.000Z", "avg_line_length": 41.4285714286, "max_line_length": 105, "alphanum_fraction": 0.4290229885, "num_tokens": 752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.03846619587632166, "lm_q1q2_score": 0.01713782636351872}}
{"text": "/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*\n**                                                                                  **\n** This file forms part of the Underworld geophysics modelling application.         **\n**                                                                                  **\n** For full license and copyright information, please refer to the LICENSE.md file  **\n** located at the project root, or contact the authors.                             **\n**                                                                                  **\n**~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/\n\n#ifndef __DRIVERS_common_utils_h__\n#define __DRIVERS_common_utils_h__\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <time.h>\n\n#include <petsc.h>\n#include <petscmat.h>\n#include <petscvec.h>\n#include <petscpc.h>\n#include <petscksp.h>\n#include <petscsnes.h>\n\n#include <petscversion.h>\n#if ( (PETSC_VERSION_MAJOR >= 3) && (PETSC_VERSION_MINOR >=3) )\n  #if (PETSC_VERSION_MINOR >=6)\n     #include \"petsc/private/vecimpl.h\"\n     #include \"petsc/private/matimpl.h\"\n     #include \"petsc/private/pcimpl.h\"\n     #include \"petsc/private/kspimpl.h\"\n     #include \"petsc/private/snesimpl.h\"\n  #else\n     #include \"petsc-private/vecimpl.h\"\n     #include \"petsc-private/matimpl.h\"\n     #include \"petsc-private/pcimpl.h\"\n     #include \"petsc-private/kspimpl.h\"\n     #include \"petsc-private/snesimpl.h\"\n  #endif\n#else\n  #include \"private/vecimpl.h\"\n  #include \"private/matimpl.h\"\n  #include \"private/pcimpl.h\"\n  #include \"private/kspimpl.h\"\n  #include \"private/snesimpl.h\"\n#endif\n\n#include \"../../../../StgDomain/Utils/src/PETScCompatibility.h\"\n\n#include \"pc_GtKG.h\"\n#include \"pc_ScaledGtKG.h\"\n#include \"stokes_block_scaling.h\"\n#include \"stokes_mvblock_scaling.h\"\n#include \"ksp_scale.h\"\n\n/* BSSCR_create_execute_script.c */\nint BSSCR_create_execute_script( void );\n\n\n/* create_petsc_header.c */\nPetscErrorCode BSSCR_GeneratePetscHeader_for_file( FILE *fd, MPI_Comm comm );\nPetscErrorCode BSSCR_GeneratePetscHeader_for_viewer( PetscViewer viewer );\n\n\n/* MatIdentityOperator.c */\n//PetscErrorCode MatCreateIdentityOperator( Mat A, Mat *_I );\n\n\n/* read_matrices.c */\n//PetscErrorCode StokesReadOperators( MPI_Comm comm, Mat *K, Mat *G, Mat *D, Mat *C, Vec *f, Vec *h );\n\n\n/* stokes_residual.c */\ndouble BSSCR_StokesMomentumResidual( Mat K, Mat G, Vec F, Vec u, Vec p );\ndouble BSSCR_StokesContinuityResidual( Mat G, Mat C, Vec H, Vec u, Vec p );\n\n\n/* preconditioner.c */\nPetscErrorCode BSSCR_StokesReadPCSchurMat( MPI_Comm comm, Mat *S );\nPetscErrorCode BSSCR_StokesCreatePCSchur( Mat K, Mat G, PC pc_S );\t\n\n/* nullspace */\n/*\nPetscErrorCode BSSCR_MatGtKinvG_ContainsConstantNullSpace(\n\t\tMat K, Mat G, Mat M,Vec t1, Vec ustar,  Vec r, Vec l,\n\t\tKSP ksp, PetscTruth *has_cnst_nullsp );\nPetscErrorCode BSSCR_VecRemoveConstNullspace(Vec v, Vec nsp_vec);\n*/\n/* PetscErrorCode BSSCR_MatContainsConstantNullSpace( Mat A, PetscTruth *has_cnst_nullsp ); */\n//PetscErrorCode BSSCR_MatContainsConstNullSpace(Mat A, Vec nsp_vec, PetscTruth *has);\n\n\n/* timed residuals */\n//PetscErrorCode KSPLogDestroyMonitor(KSP ksp);\nPetscErrorCode BSSCR_KSPLogSetMonitor(KSP ksp,PetscInt len,PetscInt *monitor_index);\nPetscErrorCode BSSCR_KSPLogGetTimeHistory(KSP ksp,PetscInt monitor_index,PetscInt *na,PetscLogDouble **log);\nPetscErrorCode BSSCR_KSPLogGetResidualHistory(KSP ksp,PetscInt monitor_index,PetscInt *na,PetscReal **rlog);\nPetscErrorCode BSSCR_KSPLogGetResidualTimeHistory(KSP ksp,PetscInt monitor_index,PetscInt *na,PetscReal **rlog,PetscLogDouble **tlog);\nPetscErrorCode BSSCR_KSPLogSolve(PetscViewer v,PetscInt monitor_index,KSP ksp);\nPetscErrorCode BSSCR_BSSCR_KSPLogSolveSummary(PetscViewer v,PetscInt monitor_index,KSP ksp);\n\n\n/* operator summary */\nPetscErrorCode BSSCR_MatInfoLog(PetscViewer v,Mat A,const char name[]);\nPetscErrorCode BSSCR_VecInfoLog(PetscViewer v,Vec x,const char name[]);\nPetscErrorCode BSSCR_StokesCreateOperatorSummary( Mat K, Mat G, Mat C, Vec f, Vec h, const char filename[] );\n\n\n/* standard output */\nPetscErrorCode BSSCR_solver_output( KSP ksp, PetscInt monitor_index, const char res_file[], const char solver_conf[] );\nPetscErrorCode BSSCR_KSPLogConvergenceRate(PetscViewer v,PetscInt monitor_index, KSP ksp);\n\n/* list available operations */\nPetscErrorCode BSSCR_MatListOperations( Mat A, PetscViewer v );\nPetscErrorCode BSSCR_VecListOperations( Vec x, PetscViewer v );\nPetscErrorCode BSSCR_KSPListOperations( KSP ksp, PetscViewer v );\nPetscErrorCode BSSCR_PCListOperations( PC pc, PetscViewer v );\nPetscErrorCode BSSCR_SNESListOperations( SNES snes, PetscViewer v );\n\n\n/* Register any petsc objects defined in drivers */\nPetscErrorCode BSSCR_PetscExtStokesSolversInitialize( void );\nPetscErrorCode BSSCR_PetscExtStokesSolversFinalize( void );\n\n/* stokes block */\n/*\nPetscErrorCode BSSCR_CreateStokesBlockOperators( MPI_Comm comm, \n\t\tMat K, Mat G, Mat D, Mat C,\n\t\tVec u, Vec p, Vec f, Vec h,\n\t\tMat *A, Vec *x, Vec *b );\n*/\n/* stokes output */\nPetscErrorCode BSSCR_stokes_output( PetscViewer v, Mat stokes_A, Vec stokes_b, Vec stokes_x, KSP ksp, PetscInt monitor_index );\n\n//PetscErrorCode BSSCR_NSPRemoveAll(Vec v, void *_data);\n//PetscErrorCode BSSCR_CheckNullspace(KSP ksp_S, Mat S, Vec h_hat, MatStokesBlockScaling BA, Vec * _nsp_vec);\n#endif\n", "meta": {"hexsha": "76a9784e7167998eea664caf494c34db6e5067fb", "size": 5433, "ext": "h", "lang": "C", "max_stars_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/common-driver-utils.h", "max_stars_repo_name": "longgangfan/underworld2", "max_stars_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 116.0, "max_stars_repo_stars_event_min_datetime": "2015-09-28T10:30:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T04:12:38.000Z", "max_issues_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/common-driver-utils.h", "max_issues_repo_name": "longgangfan/underworld2", "max_issues_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 561.0, "max_issues_repo_issues_event_min_datetime": "2015-09-29T06:05:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T23:37:29.000Z", "max_forks_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/common-driver-utils.h", "max_forks_repo_name": "longgangfan/underworld2", "max_forks_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 68.0, "max_forks_repo_forks_event_min_datetime": "2015-12-14T21:57:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-25T04:54:26.000Z", "avg_line_length": 38.5319148936, "max_line_length": 134, "alphanum_fraction": 0.7016381373, "num_tokens": 1646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.03846618940039771, "lm_q1q2_score": 0.017137823478303334}}
{"text": "#ifndef MOBULA_INC_CONTEXT_CPU_CTX_H_\n#define MOBULA_INC_CONTEXT_CPU_CTX_H_\n\n#define MOBULA_KERNEL void\n#define MOBULA_DEVICE\n\n#include <algorithm>\n#include <cmath>\n#include <cstring>\n#include <mutex>\n#include <thread>\n#include \"../ctypes.h\"\n#include \"./common.h\"\n\nnamespace mobula {\n\n#if USING_CBLAS\n#include <cblas.h>\ninline void blas_gemm(const int axis, const bool tA, const bool tB, const int M,\n                      const int N, const int K, const float alpha,\n                      const float *A, const int lda, const float *B,\n                      const int ldb, const float beta, float *C,\n                      const int ldc) {\n  cblas_sgemm(axis == 0 ? CblasRowMajor : CblasColMajor,\n              tA ? CblasTrans : CblasNoTrans, tB ? CblasTrans : CblasNoTrans, M,\n              N, K, alpha, A, lda, B, ldb, beta, C, ldc);\n}\n#endif\n\nusing std::abs;\nusing std::max;\nusing std::min;\n\n#if HOST_NUM_THREADS > 1 || USING_OPENMP\nconstexpr int NUM_MOBULA_ATOMIC_ADD_MUTEXES = HOST_NUM_THREADS * 8;\nstatic std::mutex MOBULA_ATOMIC_ADD_MUTEXES[NUM_MOBULA_ATOMIC_ADD_MUTEXES];\ninline MOBULA_DEVICE float atomic_add(const float val, float *address) {\n  uintptr_t id = (reinterpret_cast<uintptr_t>(address) / sizeof(float)) %\n                 NUM_MOBULA_ATOMIC_ADD_MUTEXES;\n  MOBULA_ATOMIC_ADD_MUTEXES[id].lock();\n  *address += val;\n  MOBULA_ATOMIC_ADD_MUTEXES[id].unlock();\n  return *address;\n}\n#else\n// no lock for single thread mode\ninline MOBULA_DEVICE float atomic_add(const float val, float *address) {\n  *address += val;\n  return *address;\n}\n#endif\n\ntemplate <typename T>\nT *new_array(size_t size) {\n  return new T[size];\n}\n\ntemplate <typename T>\nvoid del_array(T *p) {\n  delete[] p;\n}\n\ntemplate <typename T>\nT *MemcpyHostToDev(T *dst, const T *src, size_t size) {\n  if (dst == src) return dst;\n  return static_cast<T *>(memcpy(dst, src, size));\n}\n\ntemplate <typename T>\nT *MemcpyDevToHost(T *dst, const T *src, size_t size) {\n  if (dst == src) return dst;\n  return static_cast<T *>(memcpy(dst, src, size));\n}\n\ntemplate <typename T>\nT *MemcpyDevToDev(T *dst, const T *src, size_t size) {\n  if (dst == src) return dst;\n  return static_cast<T *>(memcpy(dst, src, size));\n}\n\n}  // namespace mobula\n\n#define KERNEL_RUN_BEGIN(device_id) \\\n  {                                 \\\n    UNUSED(device_id)\n#define KERNEL_RUN_END() }\n#define KERNEL_RUN_STREAM(a, strm) KERNEL_RUN(a)\n\n#if USING_OPENMP\n#include \"./openmp_ctx.h\"\n#else\n#include \"./naive_ctx.h\"\n#endif\n\n#endif  // MOBULA_INC_CONTEXT_CPU_CTX_H_\n", "meta": {"hexsha": "816b34cea4aa44e6358e4822ffb0d64524d57739", "size": 2503, "ext": "h", "lang": "C", "max_stars_repo_path": "mobula/inc/context/cpu_ctx.h", "max_stars_repo_name": "hustzxd/MobulaOP", "max_stars_repo_head_hexsha": "49e4062f6578b31918ddcc613e38e0fbb92bb015", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mobula/inc/context/cpu_ctx.h", "max_issues_repo_name": "hustzxd/MobulaOP", "max_issues_repo_head_hexsha": "49e4062f6578b31918ddcc613e38e0fbb92bb015", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mobula/inc/context/cpu_ctx.h", "max_forks_repo_name": "hustzxd/MobulaOP", "max_forks_repo_head_hexsha": "49e4062f6578b31918ddcc613e38e0fbb92bb015", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0729166667, "max_line_length": 80, "alphanum_fraction": 0.6767878546, "num_tokens": 674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3998116264369279, "lm_q2_score": 0.04272219632766466, "lm_q1q2_score": 0.017080830798721358}}
{"text": "#ifdef DFFTW\n#include <dfftw.h>\n#endif\n\n#ifdef SFFTW\n#include <sfftw.h>\n#endif\n\n#ifdef FFTW\n#include <fftw.h>\n#endif\n\nint\nmain()\n{\n#ifdef DOUBLE\n  /* Cause a compile-time error if fftw_real is not double */\n  int _array_ [1 - 2 * !((sizeof(fftw_real)) == sizeof(double))];\n#else\n  /* Cause a compile-time error if fftw_real is not float */\n  int _array_ [1 - 2 * !((sizeof(fftw_real)) == sizeof(float))]; \n#endif\n  return 0;\n}\n", "meta": {"hexsha": "e3367760fe24c771f7b5c505111e4d5b3c07dbf0", "size": 427, "ext": "c", "lang": "C", "max_stars_repo_path": "gromacs-4.6.5/cmake/TestFFTW2.c", "max_stars_repo_name": "farajilab/gifs_release", "max_stars_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-03-04T18:56:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:49:22.000Z", "max_issues_repo_path": "gromacs-4.6.5/cmake/TestFFTW2.c", "max_issues_repo_name": "farajilab/gifs_release", "max_issues_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gromacs-4.6.5/cmake/TestFFTW2.c", "max_forks_repo_name": "farajilab/gifs_release", "max_forks_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-08T00:11:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T00:11:00.000Z", "avg_line_length": 17.08, "max_line_length": 65, "alphanum_fraction": 0.6557377049, "num_tokens": 133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014734858584286, "lm_q2_score": 0.03963883995184723, "lm_q1q2_score": 0.017050541906305665}}
{"text": "//\n// Created by agibsonccc on 2/6/16.\n//\n\n#ifndef NATIVEOPERATIONS_CBLAS_ENUM_CONVERSION_H_H\n#define NATIVEOPERATIONS_CBLAS_ENUM_CONVERSION_H_H\n#include <cblas.h>\n\n/*\nenum CBLAS_ORDER {CblasRowMajor=101, CblasColMajor=102 };\nenum CBLAS_TRANSPOSE {CblasNoTrans=111, CblasTrans=112, CblasConjTrans=113,\n    AtlasConj=114};\nenum CBLAS_UPLO  {CblasUpper=121, CblasLower=122};\nenum CBLAS_DIAG  {CblasNonUnit=131, CblasUnit=132};\nenum CBLAS_SIDE  {CblasLeft=141, CblasRight=142};\n*/\n#include <dll.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n/**\n * Converts a character\n * to its proper enum\n * for row (c) or column (f) ordering\n * default is row major\n */\nCBLAS_ORDER convertOrder(int from);\n/**\n * Converts a character to its proper enum\n * t -> transpose\n * n -> no transpose\n * c -> conj\n */\nCBLAS_TRANSPOSE convertTranspose(int from);\n/**\n * Upper or lower\n * U/u -> upper\n * L/l -> lower\n *\n * Default is upper\n */\nCBLAS_UPLO convertUplo(int from);\n\n/**\n * For diagonals:\n * u/U -> unit\n * n/N -> non unit\n *\n * Default: unit\n */\nCBLAS_DIAG convertDiag(int from);\n/**\n * Side of a matrix, left or right\n * l /L -> left\n * r/R -> right\n * default: left\n */\nCBLAS_SIDE convertSide(int from);\n\n#ifdef __cplusplus\n}\n#endif\n\n\n#endif //NATIVEOPERATIONS_CBLAS_ENUM_CONVERSION_H_H\n", "meta": {"hexsha": "496baf71b87cee2f1b09f1f76b677a1e5c904e19", "size": 1273, "ext": "h", "lang": "C", "max_stars_repo_path": "libnd4j/include/cblas_enum_conversion.h", "max_stars_repo_name": "rexwong/deeplearning4j", "max_stars_repo_head_hexsha": "96a12b3b0ee7282f245c8a0af1c90b0ce2c2ed38", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 97.0, "max_stars_repo_stars_event_min_datetime": "2016-02-15T07:08:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-09T17:36:38.000Z", "max_issues_repo_path": "libnd4j/include/cblas_enum_conversion.h", "max_issues_repo_name": "rexwong/deeplearning4j", "max_issues_repo_head_hexsha": "96a12b3b0ee7282f245c8a0af1c90b0ce2c2ed38", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 331.0, "max_issues_repo_issues_event_min_datetime": "2016-03-07T21:26:26.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-08T07:16:15.000Z", "max_forks_repo_path": "libnd4j/include/cblas_enum_conversion.h", "max_forks_repo_name": "rexwong/deeplearning4j", "max_forks_repo_head_hexsha": "96a12b3b0ee7282f245c8a0af1c90b0ce2c2ed38", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 108.0, "max_forks_repo_forks_event_min_datetime": "2016-01-19T15:11:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-29T05:25:51.000Z", "avg_line_length": 19.0, "max_line_length": 75, "alphanum_fraction": 0.7038491752, "num_tokens": 394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3812195803163618, "lm_q2_score": 0.044680875043013955, "lm_q1q2_score": 0.017033224432065584}}
{"text": "/* -*- mode: C; c-basic-offset: 4 -*- */\n/* ex: set shiftwidth=4 tabstop=4 expandtab: */\n/*\n * Copyright (c) 2018-2019, Colorado School of Mines\n * All rights reserved.\n *\n * Author(s): Neil T. Dantam <ndantam@miens.edu>\n * Georgia Tech Humanoid Robotics Lab\n * Under Direction of Prof. Mike Stilman <mstilman@cc.gatech.edu>\n *\n *\n * This file is provided under the following \"BSD-style\" License:\n *\n *\n *   Redistribution and use in source and binary forms, with or\n *   without modification, are permitted provided that the following\n *   conditions are met:\n *\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *\n *   * Redistributions in binary form must reproduce the above\n *     copyright notice, this list of conditions and the following\n *     disclaimer in the documentation and/or other materials provided\n *     with the distribution.\n *\n *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND\n *   CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n *   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n *   MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n *   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n *   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n *   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n *   AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n *   LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n *   ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *   POSSIBILITY OF SUCH DAMAGE.\n *\n */\n\n#ifndef AMINO_MAT_H\n#define AMINO_MAT_H\n\n#include <cblas.h>\n\n/**\n * @file mat.h\n *\n * Block matrix descriptors and linear algebra operations.\n *\n */\n\ntypedef size_t aa_la_size;\n\n/**\n * Descriptor for a vector.\n */\nstruct aa_dvec {\n    aa_la_size len;   ///< Number of elements in vector\n    double *data; ///< Pointer to data\n    aa_la_size inc;   ///< Increment between successive vector elements\n};\n\n/**\n * Descriptor for a block matrix.\n */\nstruct aa_dmat {\n    aa_la_size rows;    ///< number of rows in matrix\n    aa_la_size cols;    ///< number of columns\n    double *data;   ///< Pointer to matrix data\n    aa_la_size ld;      ///< Leading dimension of matrix\n};\n\n\n#define AA_DVEC_REF(v,i) ((v)->data[(i) * (v)->inc])\n\n/**\n * Reference a matrix entry.\n *\n * @param M matrix\n * @param i row\n * @param j column\n */\n#define AA_DMAT_REF(M,i,j) (((M)->data)[(M)->ld*(j) + (i)])\n\n\n\ntypedef void\n(aa_la_err_fun)( const char *message );\n\nAA_API void\naa_la_err( const char *message );\n\nAA_API void\naa_la_set_err( aa_la_err_fun *fun );\n\n\n/**\n * BLAS arguments for a vector\n */\n#define AA_VEC_ARGS(X) (X->data), ((int)(X->inc))\n\n/**\n * BLAS arguments for a matrix\n */\n#define AA_MAT_ARGS(X) (X->data), ((int)(X->ld))\n\n/* Construction */\n\n/**\n * Fill in a vector descriptor.\n *\n * @param len  Number of elements in vector\n * @param data Pointer to vector data\n * @param inc  Increment between sucessive elements\n */\nstatic inline struct aa_dvec\nAA_DVEC_INIT( size_t len, double *data, size_t inc )\n{\n    struct aa_dvec vec;\n    vec.len = len;\n    vec.data = data;\n    vec.inc = inc;\n    return vec;\n}\n\n/**\n * Fill in a vector descriptor.\n *\n * @param vec  Pointer to descriptor\n * @param len  Number of elements in vector\n * @param data Pointer to vector data\n * @param inc  Increment between sucessive elements\n */\nAA_API void\naa_dvec_view( struct aa_dvec *vec, size_t len, double *data, size_t inc );\n\n/**\n * Fill in a matrix descriptor.\n *\n * @param mat   Pointer to descriptor\n * @param rows  Number of rows in matrix\n * @param cols  Number of colums in matrix\n * @param data  Pointer to vector data\n * @param ld    Leading dimension of matrix\n */\nAA_API void\naa_dmat_view( struct aa_dmat *mat, size_t rows, size_t cols, double *data, size_t ld );\n\n/**\n * View a block of a matrix.\n */\nAA_API void\naa_dmat_view_block( struct aa_dmat *dst,\n                    const struct aa_dmat *src,\n                    size_t row_start, size_t col_start,\n                    size_t rows, size_t cols );\n\n/**\n * View a slice of a vector.\n */\nAA_API void\naa_dvec_slice( const struct aa_dvec *src,\n               size_t start,\n               size_t stop,\n               size_t step,\n               struct aa_dvec *dst );\n\n\n/**\n * View a block of a matrix.\n */\nAA_API void\naa_dmat_block( const struct aa_dmat *src,\n               size_t row_start, size_t col_start,\n               size_t row_end, size_t col_end,\n               struct aa_dmat *dst );\n\n/**\n * View a row of a matrix as a vector.\n */\nAA_API void\naa_dmat_row_vec( const struct aa_dmat *src, size_t row, struct aa_dvec *dst );\n\n/**\n * View a column of a matrix as a vector.\n */\nAA_API void\naa_dmat_col_vec( const struct aa_dmat *src, size_t col, struct aa_dvec *dst );\n\n/**\n * View the diagonal of a matrix as a vector.\n */\nAA_API void\naa_dmat_diag_vec( const struct aa_dmat *src, struct aa_dvec *dst );\n\n\n/**\n * Fill in a matrix descriptor.\n *\n * @param rows  Number of rows in matrix\n * @param cols  Number of colums in matrix\n * @param data  Pointer to vector data\n * @param ld    Leading dimension of matrix\n */\nstatic inline struct aa_dmat\nAA_DMAT_INIT( size_t rows, size_t cols, double *data, size_t ld )\n{\n    struct aa_dmat mat;\n    mat.rows = rows;\n    mat.cols = cols;\n    mat.data = data;\n    mat.ld = ld;\n    return mat;\n}\n\n\n#define AA_MAT_DIAG(VEC,MAT)                                    \\\n    aa_dvec_view((VEC), (MAT)->cols, (MAT)->data, 1+(MAT)->ld);\n\n/**\n * Region-allocate a vector.\n *\n * When finished, pop the descriptor.\n */\nAA_API struct aa_dvec *\naa_dvec_alloc( struct aa_mem_region *reg, size_t len );\n\n\n/**\n * Duplicate vector out of region\n *\n * When finished, pop the descriptor.\n */\nAA_API struct aa_dvec *\naa_dvec_dup( struct aa_mem_region *reg, const struct aa_dvec *src);\n\n/**\n * Duplicate matrix out of region\n *\n * When finished, pop the descriptor.\n */\nAA_API struct aa_dmat *\naa_dmat_dup( struct aa_mem_region *reg, const struct aa_dmat *src);\n\n/**\n * Region-allocate a matrix.\n *\n * When finished, pop the descriptor.\n */\nAA_API struct aa_dmat *\naa_dmat_alloc( struct aa_mem_region *reg, size_t rows, size_t cols );\n\n/**\n * Heap-allocate a vector.\n *\n * The descriptor and data are contained in a single malloc()'ed block.\n * When finished, call free() on the descriptor.\n */\nAA_API struct aa_dvec *\naa_dvec_malloc( size_t len );\n\n/**\n * Heap-allocate a matrix.\n *\n * The descriptor and data are contained in a single malloc()'ed block.\n * When finished, call free() on the descriptor.\n */\nAA_API struct aa_dmat *\naa_dmat_malloc( size_t rows, size_t cols );\n\n/**\n * Zero a vector.\n */\nAA_API void\naa_dvec_zero( struct aa_dvec *vec );\n\n/**\n * Fill a vector.\n */\nAA_API void\naa_dvec_set( struct aa_dvec *vec, double alpha );\n\n/**\n * Fill a matrix diagonal and off-diagonal elements.\n *\n * @param[in] A        The matrix to fill\n * @param[in] alpha    off-diagonal entries of A\n * @param[in] beta     diagonal entries of A\n */\nAA_API void\naa_dmat_set( struct aa_dmat *A, double alpha, double beta );\n\n/**\n * Zero a matrix.\n */\nAA_API void\naa_dmat_zero( struct aa_dmat *mat );\n\n/* Level 1 BLAS */\n\n/**\n * Swap x and y\n *\n * \\f[ \\mathbf{x} \\leftrightarrow \\mathbf{y} \\f]\n */\nAA_API void\naa_dvec_swap( struct aa_dvec *x, struct aa_dvec *y );\n\n/**\n * Scale x by alpha.\n *\n * \\f[ \\mathbf{x} \\leftarrow \\alpha \\mathbf{x} \\f]\n */\nAA_API void\naa_dvec_scal( double alpha, struct aa_dvec *x );\n\n/**\n * Increment x by alpha.\n *\n * \\f[ \\mathbf{x} \\leftarrow \\alpha + \\mathbf{x} \\f]\n */\nAA_API void\naa_dvec_inc( double alpha, struct aa_dvec *x );\n\n/**\n * Copy x to y.\n *\n * \\f[ \\mathbf{y} \\leftarrow \\mathbf{x} \\f]\n */\nAA_API void\naa_dvec_copy( const struct aa_dvec *x, struct aa_dvec *y );\n\n\n/**\n * Alpha x plus y.\n *\n * \\f[ \\mathbf{y} \\leftarrow \\alpha \\mathbf{x} + \\mathbf{y} \\f]\n */\nAA_API void\naa_dvec_axpy( double a, const struct aa_dvec *x, struct aa_dvec *y );\n\n/**\n * Dot product\n *\n * \\f[ \\mathbf{x}^T \\mathbf{y} \\f]\n */\nAA_API double\naa_dvec_dot( const struct aa_dvec *x, struct aa_dvec *y );\n\n/**\n * Euclidean Norm\n *\n * \\f[ \\left\\Vert \\mathbf{x} \\right\\Vert_2  \\f]\n */\nAA_API double\naa_dvec_nrm2( const struct aa_dvec *x );\n\n/* Level 2 BLAS */\n\n/**\n * General Matrix-Vector multiply\n *\n * \\f[ \\mathbf{y} \\leftarrow \\alpha \\mathbf{A}^{\\rm op} \\mathbf{x} + \\beta \\mathbf{y}  \\f]\n */\nAA_API void\naa_dmat_gemv( CBLAS_TRANSPOSE trans,\n              double alpha, const struct aa_dmat *A,\n              const struct aa_dvec *x,\n              double beta, struct aa_dvec *y );\n\n\n\n/* Level 3 BLAS */\n\n/**\n * General Matrix-Matrix multiply\n *\n * \\f[ \\mathbf{y} \\leftarrow \\alpha \\mathbf{A}^{\\rm opA} \\mathbf{B}^\\rm{opB} + \\beta \\mathbf{C}  \\f]\n */\nAA_API void\naa_dmat_gemm( CBLAS_TRANSPOSE transA, CBLAS_TRANSPOSE transB,\n              double alpha, const struct aa_dmat *A,\n              const struct aa_dmat *B,\n              double beta, struct aa_dmat *C );\n\n\n\n\n/* LAPACK */\n\n/**\n * Copies all or part of a two-dimensional matrix A to another\n * matrix B.\n *\n *  @param[in] UPLO\n *          Specifies the part of the matrix A to be copied to B.\n *          - = 'U':      Upper triangular part\n *          - = 'L':      Lower triangular part\n *          - Otherwise:  All of the matrix A\n *\n *  @param[in] A\n *          dimension (LDA,N)\n *          The m by n matrix A.  If UPLO = 'U', only the upper triangle\n *          or trapezoid is accessed; if UPLO = 'L', only the lower\n *          triangle or trapezoid is accessed.\n *\n *  @param[out] B\n *          dimension (LDB,N)\n *          On exit, B = A in the locations specified by UPLO.\n *\n */\nAA_API void\naa_dmat_lacpy( const char uplo[1],\n               const struct aa_dmat *A,\n               struct aa_dmat *B );\n\n\n\n/* Matrix/Vector Functions */\n\n/**\n * sum-square-differences of two vectors\n */\nAA_API double\naa_dvec_ssd( const struct aa_dvec *x, const struct aa_dvec *y);\n\n\n/**\n * Y += alpha * X\n */\nAA_API void\naa_dmat_axpy( double alpha, const struct aa_dmat *X, struct aa_dmat *Y);\n\n/**\n * sum-square-differences of two matrices\n */\nAA_API double\naa_dmat_ssd( const struct aa_dmat *x, const struct aa_dmat *y);\n\n/**\n * Scale the matrix A by alpha\n */\nAA_API void\naa_dmat_scal( struct aa_dmat *A, double alpha );\n\n/**\n * Increment the matrix A by alpha\n */\nAA_API void\naa_dmat_inc( struct aa_dmat *A, double alpha );\n\n/**\n * Euclidean Norm\n */\nAA_API double\naa_dmat_nrm2( const struct aa_dmat *x );\n\n\n/**\n * Matrix transpose.\n */\nAA_API void\naa_dmat_trans( const struct aa_dmat *A, struct aa_dmat *At);\n\n\n/**\n * Matrix inverse, in-place.\n */\nAA_API int\naa_dmat_inv( struct aa_dmat *A);\n\n\n/**\n * Pseudo-inverse.\n *\n * Singular values less than tol are ignored.  If tol < 0, then a sane\n * default is used.\n */\nAA_API int\naa_dmat_pinv( const struct aa_dmat *A, double tol, struct aa_dmat *As);\n\n/**\n * Damped pseudo-inverse.\n */\nAA_API int\naa_dmat_dpinv( const struct aa_dmat *A, double k, struct aa_dmat *As);\n\n/**\n * Dead-zone damped pseudo-inverse.\n */\nAA_API int\naa_dmat_dzdpinv(  const struct aa_dmat *A, double s_min, struct aa_dmat *As);\n\n/**\n * Copy a matrix\n */\nAA_API void\naa_dmat_copy(  const struct aa_dmat *A, struct aa_dmat *B);\n\n\n#endif /* AMINO_MAT_H */\n", "meta": {"hexsha": "0008d427c393320d16ac649e2ffa32af8be611c7", "size": 11370, "ext": "h", "lang": "C", "max_stars_repo_path": "include/amino/mat.h", "max_stars_repo_name": "dyalab/amino", "max_stars_repo_head_hexsha": "e3063ceeeed7d1a3d55fc0d3071c9aacb4466b22", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2015-06-02T20:06:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T16:49:22.000Z", "max_issues_repo_path": "include/amino/mat.h", "max_issues_repo_name": "dyalab/amino", "max_issues_repo_head_hexsha": "e3063ceeeed7d1a3d55fc0d3071c9aacb4466b22", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 28.0, "max_issues_repo_issues_event_min_datetime": "2016-05-18T20:54:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-22T23:43:23.000Z", "max_forks_repo_path": "include/amino/mat.h", "max_forks_repo_name": "dyalab/amino", "max_forks_repo_head_hexsha": "e3063ceeeed7d1a3d55fc0d3071c9aacb4466b22", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2016-01-05T18:55:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T01:32:20.000Z", "avg_line_length": 22.5148514851, "max_line_length": 100, "alphanum_fraction": 0.6545294635, "num_tokens": 3161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926344647596, "lm_q2_score": 0.037892429753269334, "lm_q1q2_score": 0.017028578833092545}}
{"text": "/**\n * author: Jochen K\"upper\n * created: Jan 2002\n * file: pygsl/src/statistics/longmodule.c\n * $Id: intmodule.c,v 1.6 2004/03/24 08:40:45 schnizer Exp $\n *\n *\n *\"\n */\n\n\n#include <Python.h>\n#include <pygsl/error_helpers.h>\n#include <pygsl/block_helpers.h>\n#include <gsl/gsl_statistics.h>\n\n\n/* include real functions for different data-types */\n\n#define STATMOD_APPEND_PY_TYPE(X) X ## Int\n#define STATMOD_APPEND_PYC_TYPE(X) X ## INT\n#define STATMOD_FUNC_EXT(X, Y) X ## _int ## Y\n#define STATMOD_PY_AS_C PyInt_AsLong\n#define STATMOD_C_TYPE int\n#define PyGSL_STATISTICS_IMPORT_API\n#include \"functions.c\"\n\n\n/* initialization */\n\nPyGSL_STATISTICS_INIT(int, \"int\")\n\n\n/*\n * Local Variables:\n * mode: c\n * c-file-style: \"Stroustrup\"\n * End:\n */\n", "meta": {"hexsha": "fbc35429f21fb2822ca576bdb581fad6610b037d", "size": 738, "ext": "c", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/src/statistics/intmodule.c", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/src/statistics/intmodule.c", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/src/statistics/intmodule.c", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 18.45, "max_line_length": 60, "alphanum_fraction": 0.7086720867, "num_tokens": 218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.04084571167748719, "lm_q1q2_score": 0.016946838630737038}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n *\r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n *\r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n *\r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef clip_c55b09bc_5fbd_463f_8d45_b12013b57f42_h\r\n#define clip_c55b09bc_5fbd_463f_8d45_b12013b57f42_h\r\n\r\n#include <gslib/tree.h>\r\n#include <ariel/painterpath.h>\r\n\r\n__ariel_begin__\r\n\r\nenum clip_point_tag\r\n{\r\n    cpt_corner = 0x01,\r\n    cpt_interpolate = 0x02,\r\n};\r\n\r\nenum clip_fill_type\r\n{\r\n    cft_even_odd = 0,\r\n    cft_non_zero,\r\n    cft_positive,\r\n    cft_negative,\r\n};\r\n\r\nstruct clip_vec2_hash\r\n{\r\n    size_t operator()(const vec2& pt) const { return hash_bytes((const byte*)&pt, sizeof(pt)); }\r\n};\r\n\r\ntypedef _treenode_wrapper<painter_path> clip_result_wrapper;\r\ntypedef tree<painter_path, clip_result_wrapper> clip_result;\r\ntypedef typename clip_result::iterator clip_result_iter;\r\ntypedef typename clip_result::const_iterator clip_result_const_iter;\r\ntypedef unordered_map<vec2, uint, clip_vec2_hash> clip_point_attr;\r\n\r\nariel_export extern void clip_remap_points(painter_linestrips& output, clip_point_attr& attrmap, const painter_path& input, uint attr_selector, float step_len = -1.f);\r\nariel_export extern void clip_offset(painter_linestrips& lss, const painter_linestrips& input, float offset);\r\nariel_export extern void clip_stroker(painter_linestrips& lss, const painter_linestrips& input, float offset);\r\nariel_export extern void clip_simplify(painter_linestrips& lss, const painter_linestrip& input, clip_fill_type ft = cft_even_odd);\r\nariel_export extern void clip_simplify(painter_linestrips& lss, const painter_linestrips& input, clip_fill_type ft = cft_even_odd);\nariel_export extern void clip_simplify(clip_result& output, const painter_path& input);\r\nariel_export extern void clip_union(clip_result& output, const painter_path& subjects, const painter_path& clips);\r\nariel_export extern void clip_intersect(clip_result& output, const painter_path& subjects, const painter_path& clips);\r\nariel_export extern void clip_substract(clip_result& output, const painter_path& subjects, const painter_path& clips);\r\nariel_export extern void clip_exclude(clip_result& output, const painter_path& subjects, const painter_path& clips);\r\nariel_export extern void clip_convert(painter_path& path, const clip_result& result);\r\n\r\n__ariel_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "d26a62209c04ca1b5b5fd9d26d5a752bfbd1d99c", "size": 3425, "ext": "h", "lang": "C", "max_stars_repo_path": "include/ariel/clip.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/ariel/clip.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ariel/clip.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 45.0657894737, "max_line_length": 168, "alphanum_fraction": 0.7813138686, "num_tokens": 817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.03904829664023509, "lm_q1q2_score": 0.016946236974026373}}
{"text": "#ifndef __HCORE__\n#define __HCORE__\n\n#ifdef MKL\n  #include <mkl.h>\n  #include <mkl_lapack.h>\n  //#pragma message(\"MKL is used\")\n#else\n  #ifdef ARMPL\n    #include <armpl.h>\n  #else\n    #include <cblas.h>\n  #endif\n  #ifdef LAPACKE_UTILS\n    #include <lapacke_utils.h>\n  #endif\n  #include <lapacke.h>\n  //#pragma message(\"MKL is NOT used\")\n#endif\n\n#ifndef hcore_min\n#define hcore_min(a, b) ((a) < (b) ? (a) : (b))\n#endif\n#ifndef hcore_max\n#define hcore_max(a, b) ((a) < (b) ? (b) : (a))\n#endif\n\n\n\n#define HCORE_NoTrans         111\n#define HCORE_Trans           112\n#define HCORE_ConjTrans       113\n\n#define HCORE_Upper           121\n#define HCORE_Lower           122\n#define HCORE_UpperLower      123\n\n#define HCORE_NonUnit         131\n#define HCORE_Unit            132\n\n#define HCORE_Left            141\n#define HCORE_Right           142\n\ntypedef int  HCORE_enum;\n#endif\n", "meta": {"hexsha": "ea4033365ed26f9f3f6740bc8402c85f77855df9", "size": 870, "ext": "h", "lang": "C", "max_stars_repo_path": "src/include/hcore.h", "max_stars_repo_name": "ecrc/hcore", "max_stars_repo_head_hexsha": "0b1c6d659e56d10795fc1838c1e2959e2afad8ad", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-04T19:12:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-04T19:12:33.000Z", "max_issues_repo_path": "src/include/hcore.h", "max_issues_repo_name": "ecrc/hcore", "max_issues_repo_head_hexsha": "0b1c6d659e56d10795fc1838c1e2959e2afad8ad", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/include/hcore.h", "max_forks_repo_name": "ecrc/hcore", "max_forks_repo_head_hexsha": "0b1c6d659e56d10795fc1838c1e2959e2afad8ad", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-01T14:44:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-01T14:44:20.000Z", "avg_line_length": 18.9130434783, "max_line_length": 47, "alphanum_fraction": 0.6264367816, "num_tokens": 277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.039048295661732874, "lm_q1q2_score": 0.01694623654937455}}
{"text": "/* rng/gsl_rng.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2004, 2007 James Theiler, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_RNG_H__\n#define __GSL_RNG_H__\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_inline.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct\n  {\n    const char *name;\n    unsigned long int max;\n    unsigned long int min;\n    size_t size;\n    void (*set) (void *state, unsigned long int seed);\n    unsigned long int (*get) (void *state);\n    double (*get_double) (void *state);\n  }\ngsl_rng_type;\n\ntypedef struct\n  {\n    const gsl_rng_type * type;\n    void *state;\n  }\ngsl_rng;\n\n\n/* These structs also need to appear in default.c so you can select\n   them via the environment variable GSL_RNG_TYPE */\n\nGSL_VAR const gsl_rng_type *gsl_rng_borosh13;\nGSL_VAR const gsl_rng_type *gsl_rng_coveyou;\nGSL_VAR const gsl_rng_type *gsl_rng_cmrg;\nGSL_VAR const gsl_rng_type *gsl_rng_fishman18;\nGSL_VAR const gsl_rng_type *gsl_rng_fishman20;\nGSL_VAR const gsl_rng_type *gsl_rng_fishman2x;\nGSL_VAR const gsl_rng_type *gsl_rng_gfsr4;\nGSL_VAR const gsl_rng_type *gsl_rng_knuthran;\nGSL_VAR const gsl_rng_type *gsl_rng_knuthran2;\nGSL_VAR const gsl_rng_type *gsl_rng_knuthran2002;\nGSL_VAR const gsl_rng_type *gsl_rng_lecuyer21;\nGSL_VAR const gsl_rng_type *gsl_rng_minstd;\nGSL_VAR const gsl_rng_type *gsl_rng_mrg;\nGSL_VAR const gsl_rng_type *gsl_rng_mt19937;\nGSL_VAR const gsl_rng_type *gsl_rng_mt19937_1999;\nGSL_VAR const gsl_rng_type *gsl_rng_mt19937_1998;\nGSL_VAR const gsl_rng_type *gsl_rng_r250;\nGSL_VAR const gsl_rng_type *gsl_rng_ran0;\nGSL_VAR const gsl_rng_type *gsl_rng_ran1;\nGSL_VAR const gsl_rng_type *gsl_rng_ran2;\nGSL_VAR const gsl_rng_type *gsl_rng_ran3;\nGSL_VAR const gsl_rng_type *gsl_rng_rand;\nGSL_VAR const gsl_rng_type *gsl_rng_rand48;\nGSL_VAR const gsl_rng_type *gsl_rng_random128_bsd;\nGSL_VAR const gsl_rng_type *gsl_rng_random128_glibc2;\nGSL_VAR const gsl_rng_type *gsl_rng_random128_libc5;\nGSL_VAR const gsl_rng_type *gsl_rng_random256_bsd;\nGSL_VAR const gsl_rng_type *gsl_rng_random256_glibc2;\nGSL_VAR const gsl_rng_type *gsl_rng_random256_libc5;\nGSL_VAR const gsl_rng_type *gsl_rng_random32_bsd;\nGSL_VAR const gsl_rng_type *gsl_rng_random32_glibc2;\nGSL_VAR const gsl_rng_type *gsl_rng_random32_libc5;\nGSL_VAR const gsl_rng_type *gsl_rng_random64_bsd;\nGSL_VAR const gsl_rng_type *gsl_rng_random64_glibc2;\nGSL_VAR const gsl_rng_type *gsl_rng_random64_libc5;\nGSL_VAR const gsl_rng_type *gsl_rng_random8_bsd;\nGSL_VAR const gsl_rng_type *gsl_rng_random8_glibc2;\nGSL_VAR const gsl_rng_type *gsl_rng_random8_libc5;\nGSL_VAR const gsl_rng_type *gsl_rng_random_bsd;\nGSL_VAR const gsl_rng_type *gsl_rng_random_glibc2;\nGSL_VAR const gsl_rng_type *gsl_rng_random_libc5;\nGSL_VAR const gsl_rng_type *gsl_rng_randu;\nGSL_VAR const gsl_rng_type *gsl_rng_ranf;\nGSL_VAR const gsl_rng_type *gsl_rng_ranlux;\nGSL_VAR const gsl_rng_type *gsl_rng_ranlux389;\nGSL_VAR const gsl_rng_type *gsl_rng_ranlxd1;\nGSL_VAR const gsl_rng_type *gsl_rng_ranlxd2;\nGSL_VAR const gsl_rng_type *gsl_rng_ranlxs0;\nGSL_VAR const gsl_rng_type *gsl_rng_ranlxs1;\nGSL_VAR const gsl_rng_type *gsl_rng_ranlxs2;\nGSL_VAR const gsl_rng_type *gsl_rng_ranmar;\nGSL_VAR const gsl_rng_type *gsl_rng_slatec;\nGSL_VAR const gsl_rng_type *gsl_rng_taus;\nGSL_VAR const gsl_rng_type *gsl_rng_taus2;\nGSL_VAR const gsl_rng_type *gsl_rng_taus113;\nGSL_VAR const gsl_rng_type *gsl_rng_transputer;\nGSL_VAR const gsl_rng_type *gsl_rng_tt800;\nGSL_VAR const gsl_rng_type *gsl_rng_uni;\nGSL_VAR const gsl_rng_type *gsl_rng_uni32;\nGSL_VAR const gsl_rng_type *gsl_rng_vax;\nGSL_VAR const gsl_rng_type *gsl_rng_waterman14;\nGSL_VAR const gsl_rng_type *gsl_rng_zuf;\n\nconst gsl_rng_type ** gsl_rng_types_setup(void);\n\nGSL_VAR const gsl_rng_type *gsl_rng_default;\nGSL_VAR unsigned long int gsl_rng_default_seed;\n\ngsl_rng *gsl_rng_alloc (const gsl_rng_type * T);\nint gsl_rng_memcpy (gsl_rng * dest, const gsl_rng * src);\ngsl_rng *gsl_rng_clone (const gsl_rng * r);\n\nvoid gsl_rng_free (gsl_rng * r);\n\nvoid gsl_rng_set (const gsl_rng * r, unsigned long int seed);\nunsigned long int gsl_rng_max (const gsl_rng * r);\nunsigned long int gsl_rng_min (const gsl_rng * r);\nconst char *gsl_rng_name (const gsl_rng * r);\n\nint gsl_rng_fread (FILE * stream, gsl_rng * r);\nint gsl_rng_fwrite (FILE * stream, const gsl_rng * r);\n\nsize_t gsl_rng_size (const gsl_rng * r);\nvoid * gsl_rng_state (const gsl_rng * r);\n\nvoid gsl_rng_print_state (const gsl_rng * r);\n\nconst gsl_rng_type * gsl_rng_env_setup (void);\n\nINLINE_DECL unsigned long int gsl_rng_get (const gsl_rng * r);\nINLINE_DECL double gsl_rng_uniform (const gsl_rng * r);\nINLINE_DECL double gsl_rng_uniform_pos (const gsl_rng * r);\nINLINE_DECL unsigned long int gsl_rng_uniform_int (const gsl_rng * r, unsigned long int n);\n\n#ifdef HAVE_INLINE\n\nINLINE_FUN unsigned long int\ngsl_rng_get (const gsl_rng * r)\n{\n  return (r->type->get) (r->state);\n}\n\nINLINE_FUN double\ngsl_rng_uniform (const gsl_rng * r)\n{\n  return (r->type->get_double) (r->state);\n}\n\nINLINE_FUN double\ngsl_rng_uniform_pos (const gsl_rng * r)\n{\n  double x ;\n  do\n    {\n      x = (r->type->get_double) (r->state) ;\n    }\n  while (x == 0) ;\n\n  return x ;\n}\n\n/* Note: to avoid integer overflow in (range+1) we work with scale =\n   range/n = (max-min)/n rather than scale=(max-min+1)/n, this reduces\n   efficiency slightly but avoids having to check for the out of range\n   value.  Note that range is typically O(2^32) so the addition of 1\n   is negligible in most usage. */\n\nINLINE_FUN unsigned long int\ngsl_rng_uniform_int (const gsl_rng * r, unsigned long int n)\n{\n  unsigned long int offset = r->type->min;\n  unsigned long int range = r->type->max - offset;\n  unsigned long int scale;\n  unsigned long int k;\n\n  if (n > range || n == 0) \n    {\n      GSL_ERROR_VAL (\"invalid n, either 0 or exceeds maximum value of generator\",\n                     GSL_EINVAL, 0) ;\n    }\n\n  scale = range / n;\n\n  do\n    {\n      k = (((r->type->get) (r->state)) - offset) / scale;\n    }\n  while (k >= n);\n\n  return k;\n}\n#endif /* HAVE_INLINE */\n\n__END_DECLS\n\n#endif /* __GSL_RNG_H__ */\n", "meta": {"hexsha": "d80e763494ac2b774ba375b441838b0c9d1ddd4c", "size": 6957, "ext": "h", "lang": "C", "max_stars_repo_path": "gsl-2.6/gsl/gsl_rng.h", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gsl-2.6/gsl/gsl_rng.h", "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gsl-2.6/gsl/gsl_rng.h", "max_forks_repo_name": "ielomariala/Hex-Game", "max_forks_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-30T20:40:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-30T20:40:25.000Z", "avg_line_length": 31.9128440367, "max_line_length": 91, "alphanum_fraction": 0.7737530545, "num_tokens": 2091, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814648038985, "lm_q2_score": 0.039048293425156484, "lm_q1q2_score": 0.01694623557874185}}
{"text": "/**\n * This file is part of yasimSBML (http://www.labri.fr/perso/ghozlane/metaboflux/about/yasimSBML.php)\n * Copyright (C) 2010 Amine Ghozlane from LaBRI and University of Bordeaux 1\n *\n * yasimSBML is free software: you can redistribute it and/or modify\n * it under the terms of the Lesser GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * yasimSBML is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the Lesser GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n/**\n * \\file simulation.c\n * \\brief Simulate a petri net\n * \\author {Amine Ghozlane}\n * \\version 1.0\n * \\date 27 octobre 2009\n */\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <assert.h>\n#include <time.h>\n#include <unistd.h>\n#include <gsl/gsl_rng.h>\n#include <sbml/SBMLTypes.h>\n#include \"especes.h\"\n#include \"simulation.h\"\n\n/*TODO Verification des BoundaryConditions,Local parameter values, Global parameter values, Reaction, des equations */\n\n/**\n * \\fn void SBML_initEspeceAmounts(Model_t *mod, pEspeces molecules, int nbEspeces)\n * \\author Amine Ghozlane\n * \\brief  Alloc memory and initialize the struct Especes\n * \\param  mod Model of the SBML file\n * \\param  molecules Struct Especes\n * \\param  nbEspeces Number of molecules\n */\nvoid SBML_initEspeceAmounts(Model_t *mod, pEspeces molecules, int nbEspeces) {\n  int i;\n  Species_t *esp;\n\n  /* Initialisation des quantites des especes*/\n  for (i = 0; i < nbEspeces; i++) {\n      esp = Model_getSpecies(mod, i);\n      /*printf(\"espece: %s, compartiment : %s\\n\",Species_getId(esp),Species_getCompartment(esp));*/\n      Especes_save(molecules, i, Species_getInitialAmount(esp),\n          Species_getId(esp), Species_getCompartment(esp));\n  }\n}\n\n/**\n * \\fn void SBML_setReactions(Model_t *mod, pEspeces molecules, pScore result, double *reactions_ratio, int nbReactions, int nbEspeces)\n * \\author Amine Ghozlane\n * \\brief  Alloc memory and initialize the struct Especes\n * \\param  mod Model of the SBML file\n * \\param  molecules Struct Especes\n * \\param  result Struct Score\n * \\param  reactions_ratio List of computed reaction ratio\n * \\param  nbReactions Number of reaction\n * \\param  nbEspeces Number of molecules\n */\nvoid SBML_setReactions(Model_t *mod, pEspeces molecules, int nbReactions, int nbEspeces) {\n  int ref = 0, i, j;\n  SpeciesReference_t *reactif;\n  Species_t *especeId;\n  Reaction_t *react;\n  const char *kf;\n  const ASTNode_t *km;\n  KineticLaw_t *kl;\n\n  /*fprintf(stdout, \"Debut reaction\\n\");*/\n  /* Recherche les reactions ou apparaissent chaque espece */\n  for (i = 0; i < nbReactions; i++) {\n      react = Model_getReaction(mod, i);\n      for (j = 0; j < (int)Reaction_getNumReactants(react); j++) {\n          reactif = Reaction_getReactant(react, j);\n          especeId = Model_getSpeciesById(mod, SpeciesReference_getSpecies(\n              reactif));\n          ref = Especes_find(molecules, Species_getId(especeId), nbEspeces);\n          /*printf(\"Reactif :Quantite de ref %d :%f \\n\", ref,Especes_getQuantite(molecules, ref));*/\n\n          kl = Reaction_getKineticLaw(react);\n\n          if (KineticLaw_isSetFormula(kl)) {\n              kf = KineticLaw_getFormula(kl);\n              /*printf(\"c du kf %s\\n\", kf);*/\n              Especes_allocReactions(molecules, ref, react,\n                  SBML_evalExpression(kf));\n          } else {\n              km = KineticLaw_getMath(kl);\n              printf(\"C du kM... cas encore ignore\\n\");\n              exit(1);\n          }\n      }\n  }\n  /*fprintf(stdout, \"Fin reaction\\n\");*/\n}\n\n/**\n * \\fn double SBML_evalExpression(const char *formule)\n * \\author Amine Ghozlane\n * \\brief  Get the reaction ratio define in the sbml\n * \\param  formule Formule SBML\n * \\return Return double value of the constraint\n */\ndouble SBML_evalExpression(const char *formule) {\n  return atof(formule);\n}\n\n/**\n * \\fn int SBML_checkQuantite(Model_t *mod, Reaction_t *react, int nbEspeces, pEspeces molecules)\n * \\author Amine Ghozlane\n * \\brief  Determine the number of reaction for one molecule\n * \\param  mod Model of the SBML file\n * \\param  react Reaction id\n * \\param  nbEspeces Number of molecules\n * \\param  molecules Struct Especes\n * \\return Number of reaction for one molecule\n */\nint SBML_checkQuantite(Model_t *mod, Reaction_t *react, int nbEspeces, pEspeces molecules)\n{\n  double quantite = 0.0, minStep = 0.0, temp = 0.0;\n  int ref = 0, i;\n  SpeciesReference_t *reactif;\n  Species_t *especeId;\n\n  reactif = Reaction_getReactant(react, 0);\n  especeId = Model_getSpeciesById(mod, SpeciesReference_getSpecies(reactif));\n  ref = Especes_find(molecules, Species_getId(especeId), nbEspeces);\n\n  if ((quantite = Especes_getQuantite(molecules, ref)) <= 0.0) {\n      /*printf(\"je fais le return\\n\");*/\n      return END;\n  }\n  /*printf(\"quantite : %d\\n\",quantite);*/\n  minStep = quantite / SpeciesReference_getStoichiometry(reactif);\n  /*printf(\"quantite : %d, minStep init : %d\\n\",quantite,minStep);*/\n  /* Cas ou le nombre de pas est egal a 0 */\n  if(minStep==0.0) return END;\n\n  for (i = 1; i < (int)Reaction_getNumReactants(react); i++) {\n      reactif = Reaction_getReactant(react, i);\n      especeId = Model_getSpeciesById(mod, SpeciesReference_getSpecies(reactif));\n      ref = Especes_find(molecules, Species_getId(especeId), nbEspeces);\n      quantite= Especes_getQuantite(molecules, ref);\n      /* La quantite est egale a 0 */\n      if(quantite<=0.0) return END;\n      temp = floor(Especes_getQuantite(molecules, ref)/SpeciesReference_getStoichiometry(reactif));\n      /* Cas ou le nombre de pas est egal a 0 */\n      if(temp==0.0) return END;\n      /* Si le nouveau nombre est inferieur au precedent, on change la valeur de minStep */\n      if (minStep > temp) minStep = temp;\n  }\n\n  return (int)minStep;\n}\n\n/**\n * \\fn Reaction_t * SBML_reactChoice(pEspeces molecules, const gsl_rng * r, int ref)\n * \\author Amine Ghozlane\n * \\brief  Determine randomly the reaction to achieve for several nodes reactions\n * \\param  molecules Struct Especes\n * \\param  r Random number generator\n * \\param  ref Number reference of one molecule\n * \\return Id of the selected reaction\n */\nReaction_t * SBML_reactChoice(pEspeces molecules, const gsl_rng * r, int ref) {\n\n  pReaction temp = NULL;\n  pReaction Q = molecules[ref].system;\n  double value = gsl_rng_uniform(r) * 100.0;\n  double choice = 0.0;\n\n  /*printf(\"Choix de la reaction :\\n\");\n\t printf(\"value : %f\\n\", value);*/\n\n  /* Choix de la reaction a realiser */\n  if (value < Q->ratio)\n    temp = Q;\n  else {\n      do {\n          /*printf(\"reaction %s : ratio %f\\n\", Reaction_getId(Q->link), Q->ratio);*/\n          choice += Q->ratio;\n          /*printf(\"choice : %f\\n\", choice);*/\n          Q = Q->suivant;\n          temp = Q;\n          /*printf(\"ratio suivant : %f\\n\",Q->ratio );*/\n      } while (Q->suivant != NULL && value <= (choice + Q->suivant->ratio)\n          && value > choice);\n  }\n  if (temp == NULL) {\n      fprintf(stderr, \"on a un probleme de ratio\\n\");\n      exit(EXIT_FAILURE);\n  }\n\n  /*printf(\"Resultat :\\n\");\n\t printf(\"value : %f, choice :%f\\n\", value, (choice + Q->ratio));\n\t printf(\"reaction %s : ratio %f\\n\", Reaction_getId(temp->link), temp->ratio);*/\n  /*if (Q->suivant == NULL)\n\t printf(\"choice :%f\", choice);*/\n  /*printf(\"c bon\\n\");*/\n\n  return (temp->link);\n\n}\n\n/**\n * \\fn void SBML_reaction(Model_t *mod, pEspeces molecules, Reaction_t *react, int nbEspeces)\n * \\author Amine Ghozlane\n * \\brief  Simulation of a discrete transision\n * \\param  mod Model of the SBML file\n * \\param  molecules Struct Especes\n * \\param  react Reaction id\n * \\param  nbEspeces Number of molecules\n */\nvoid SBML_reaction(Model_t *mod, pEspeces molecules, Reaction_t *react, int nbEspeces)\n{\n  SpeciesReference_t *reactif;\n  Species_t *especeId;\n  int i, ref = 0;\n\n  /*boucle pour retirer des reactifs*/\n  for (i = 0; i < (int)Reaction_getNumReactants(react); i++) {\n      reactif = Reaction_getReactant(react, i);\n      especeId = Model_getSpeciesById(mod, SpeciesReference_getSpecies(reactif));\n      ref = Especes_find(molecules, Species_getId(especeId), nbEspeces);\n\n      /*printf(\"Reactif : %s\",Species_getId(especeId) );\n\t\t printf(\"ref : %d\\n\",ref);\n\t\t printf(\"Reactif :Quantite de ref %d :%d \\n\",ref,Espece_getQuantite(molecules,ref));*/\n      Especes_setQuantite(molecules, ref,(Especes_getQuantite(molecules, ref)- SpeciesReference_getStoichiometry(reactif)));\n      /*printf(\"Apres Reactif: Quantite de ref %d :%d \\n\",ref,Espece_getQuantite(molecules,ref));*/\n  }\n\n  /*boucle pour ajouter des produits */\n  for (i = 0; i < (int)Reaction_getNumProducts(react); i++) {\n      reactif = Reaction_getProduct(react, i);\n      especeId = Model_getSpeciesById(mod, SpeciesReference_getSpecies(reactif));\n      /*printf(\"Produit : %s\",Species_getId(especeId) );*/\n      ref = Especes_find(molecules, Species_getId(especeId), /*Species_getCompartment(especeId),*/ nbEspeces);\n      /*printf(\"Produit : ref : %d\\n\",ref);\n\t\t printf(\"Produit : Quantite de ref %d :%d \\n\",ref,Espece_getQuantite(molecules,ref));*/\n\n      Especes_setQuantite(molecules, ref,(Especes_getQuantite(molecules, ref)+ SpeciesReference_getStoichiometry(reactif)));\n      /*printf(\"Apres Produit : Quantite de ref %d :%d \\n\",ref,Espece_getQuantite(molecules,ref));*/\n  }\n}\n\n/**\n * \\fn void SBML_allocTest(pTestReaction T, int nbReactions)\n * \\author Amine Ghozlane\n * \\brief  Alloc memory and initialize the struct pTestReaction\n * \\param  T Empty struct TestReaction\n * \\param  nbReactions Number of reactions\n */\nvoid SBML_allocTest(pTestReaction T, int nbReactions)\n{\n  int i;\n\n  /* Initialisation des tableaux des reactions */\n  T->tabReactions= (Reaction_t **) malloc(nbReactions * sizeof(Reaction_t *));\n  T->minStepTab = (int*) malloc(nbReactions * sizeof(int));\n\n  if (T->tabReactions == NULL)\n    exit(EXIT_FAILURE);\n  if (T->minStepTab == NULL)\n    exit(EXIT_FAILURE);\n\n  for (i = 0; i < nbReactions; i++) {\n      T->tabReactions[i] = NULL;\n      T->minStepTab[i] = 0;\n  }\n}\n\n/**\n * \\fn void SBML_freeTest(pTestReaction T)\n * \\author Amine Ghozlane\n * \\brief  Free memory of the struct TestReaction\n * \\param T Struct TestReaction gives data on reaction\n */\nvoid SBML_freeTest(pTestReaction T)\n{\n  if (T->tabReactions != NULL)\n    free(T->tabReactions);\n  if (T->minStepTab != NULL)\n    free(T->minStepTab);\n}\n\n/**\n * \\fn int SBML_EstimationReaction(Model_t *mod, pTestReaction T, pEspeces molecules, int ref, int nbEspeces)\n * \\author Amine Ghozlane\n * \\brief  Alloc memory and initialize the struct Especes\n * \\param  mod Model of the SBML file\n * \\param  T Struct TestReaction gives data on reaction\n * \\param  molecules Struct Especes\n * \\param  ref Number reference of one molecule\n * \\param  nbEspeces Number of molecules\n * \\return Estimated number of feasible step by reaction\n */\nint SBML_EstimationReaction(Model_t *mod, pTestReaction T, pEspeces molecules, int ref, int nbEspeces)\n{\n  pReaction Q = molecules[ref].system;\n  int i = 0, min = 0, curr = 0;\n\n  /* Compte le nombre de reactions rattachees a une espece */\n  while (Q != NULL) {\n      T->tabReactions[i] = Q->link;\n      T->minStepTab[i] = SBML_checkQuantite(mod, Q->link, nbEspeces,\n          molecules);\n      if (i == 0)\n        min = T->minStepTab[i];\n      curr = T->minStepTab[i];\n      if (T->minStepTab[i] <= 0)\n        return END;\n      else if (curr < min)\n        min = curr;\n      Q = Q->suivant;\n      i++;\n  }\n\n  return min;\n}\n\n/**\n * \\fn int SBML_simulate(Model_t *mod, pEspeces molecules, const gsl_rng * r, pTestReaction T, char **banned, int nbBanned, int nbEspeces, int ref)\n * \\author Amine Ghozlane\n * \\brief  Simulate one step of petri net\n * \\param  mod Model of the SBML file\n * \\param  molecules Struct Especes\n * \\param  r Random number generator\n * \\param  T Struct TestReaction gives data on reaction\n * \\param  banned List of banned compound\n * \\param  nbBanned Number of banned compound\n * \\param  nbEspeces Number of molecules\n * \\param  ref Number reference of one molecule\n * \\return Condition of stop/pursue\n */\nint SBML_simulate(Model_t *mod, pEspeces molecules, const gsl_rng * r, pTestReaction T, int nbEspeces, int ref)\n{\n  Reaction_t *react = NULL;\n  int minStep = 0, valid = 0/*, i=0*/;\n  /*int nbReactions = Especes_getNbreactions(molecules, ref);*/\n  int nbReactions = molecules[ref].nbReactions;\n\n  /*printf(\"nbreactions : %d, ref : %d\\n\", nbReactions, ref);\n\t printf(\"molecules : %s\\n\", molecules[ref].id);*/\n\n  /* Probleme ATP, ADP, NADH, NAD+ */\n  if (!strcmp(molecules[ref].id, \"ADP\") || !strcmp(molecules[ref].id, \"ATP\")\n      || !strcmp(molecules[ref].id, \"NADH\") || !strcmp(molecules[ref].id,\n          \"NADplus\") || !strcmp(molecules[ref].id, \"NADPH\") || !strcmp(\n              molecules[ref].id, \"NADPplus\")|| !strcmp(molecules[ref].id, \"NADplus_g\")||\n              !strcmp(molecules[ref].id, \"NADH_g\")|| !strcmp(molecules[ref].id, \"ADP_g\")||\n              !strcmp(molecules[ref].id, \"ATP_g\")|| !strcmp(molecules[ref].id, \"ADP_c\")|| !strcmp(molecules[ref].id, \"ATP_c\")) {\n      /*printf(\"END : molecules : %s\\n\", molecules[ref].id);*/\n      return END;\n  }\n\n  /* Elimine les calculs sur ADP... */\n  /*for(j=0;j<BANNI;j++){\n\t if(!strcmp(tab[i],molecules[ref].id)){\n\t printf(\"test : tab: %s molecules : %s\\n\",tab[i],molecules[ref].id );\n\t return END;\n\t }\n\t }*/\n\n  /* Variation selon le cas. */\n  switch (nbReactions) {\n  /* Cas ou aucune reaction n'est possible */\n  case 0:\n    /*printf(\"Cas N\u00b01\\n\");*/\n    return END;\n    break;\n    /* Cas ou une seule reaction est possible */\n  case 1:\n    /*printf(\"Cas N\u00b02\\n\");*/\n    react = molecules[ref].system->link;\n    if ((minStep = SBML_checkQuantite(mod, react, nbEspeces, molecules))<= END)\n      return END;\n    /*printf(\"minstep = %d\\n\", minStep);*/\n\n    while (minStep > 0) {\n        SBML_reaction(mod, molecules, react, nbEspeces);\n        minStep--;\n    }\n    break;\n    /* Cas ou  plusieurs reactions sont possibles*/\n  default:\n    /*printf(\"Cas N\u00b03\\n\");*/\n    /* Allocation de la memoire au tableau des reactions */\n    SBML_allocTest(T, nbReactions);\n    valid = SBML_EstimationReaction(mod, T, molecules, ref, nbEspeces);\n    if (valid <= END) {\n        /*printf(\"on ne fait rien\\n\");*/\n        return END;\n    }\n    while (Especes_getQuantite(molecules, ref) > 0.0 && valid > END) {\n        react = SBML_reactChoice(molecules, r, ref);\n        /*printf(\"molecule : %s, reaction %s\\n\", molecules[ref].id, Reaction_getId(react));*/\n        /*printf(\"reaction : %s\\n\", Reaction_getId(react));*/\n        /*printf(\"valid : %d, i : %d\\n\", valid, i);*/\n        SBML_reaction(mod, molecules, react, nbEspeces);\n        /*if(i>=valid) valid=SBML_EstimationReaction(mod, T, molecules, ref, nbEspeces);*/\n        /*i++;*/\n        valid--;\n    }\n    /*printf(\"Fin de simulation\\n\");*/\n\n    /* Liberation de la memoire allouee au tableau des reactions */\n    SBML_freeTest(T);\n    break;\n  }\n  /*printf(\"On quitte la simulation\\n\");*/\n  return PURSUE;\n}\n\n/**\n * \\fn void SBML_compute_simulation(pScore result, Model_t *mod, double *reactions_ratio, gsl_rng * r, char **banned, int nbBanned)\n * \\author Amine Ghozlane\n * \\brief  Simulation of metabolic network\n * \\param  result Struct Score\n * \\param  mod Model of the SBML file\n * \\param  reactions_ratio List of computed reaction ratio\n * \\param  r Random number generator\n * \\param  banned List of banned compound\n * \\param  nbBanned Number of banned compound\n */\nvoid compute_simulation(Model_t *mod)\n{\n  int i, nbReactions = 0, nbEspeces = 0, temp = 1, tempo = 0;\n  pEspeces molecules;\n  const gsl_rng_type *T;\n  gsl_rng * r;\n  pTestReaction TR = NULL;\n\n  /* Verifications */\n  /*TODO numGlobalParameters=Model_getNumParameters(mod);\n\tcheckBoundaryConditions(mod);\n\tif(numGlobalParameters>0){\n\t    globalParVec=gsl_vector_alloc(numGlobalParameters);\n\t    setGlobalParVec();\n\t  }*/\n  /* Allocation memoire et initialisation des generateurs de nombre aleatoire */\n  gsl_rng_env_setup();\n  if (!getenv(\"GSL_RNG_SEED\"))\n    gsl_rng_default_seed = time(NULL);\n  T = gsl_rng_default;\n  r = gsl_rng_alloc(T);\n  gsl_rng_default_seed = gsl_rng_uniform(r);\n\n  /* Allocation memoire */\n  TR = (pTestReaction) malloc(1 * sizeof(TestReaction));\n  if (T == NULL)\n    exit(EXIT_FAILURE);\n\n  /* File information */\n  nbReactions = Model_getNumReactions(mod);\n  nbEspeces = Model_getNumSpecies(mod);\n  /*printf(\"Nom du model : %s\\n\",Model_getId(mod));*/\n  molecules = Especes_alloc(nbEspeces);\n  /* Initialisation de la quantite des especes */\n  SBML_initEspeceAmounts(mod, molecules, nbEspeces);\n  /* Initialisation des reactions et des ratios*/\n  SBML_setReactions(mod, molecules, nbReactions, nbEspeces);\n\n\n  /*TODO checkRatio(mod,molecules);*/\n\n  /* Test des donnees enregistrees */\n  printf(\"\\nEtat des especes :\\n\\n\");\n  Especes_print(molecules, nbEspeces);\n\n  printf(\"\\nDebut de simulation ...\\n\");\n  /* Simulation des reactions */\n  while (temp > END) {\n      temp = 0;\n      for (i = 0; i < nbEspeces; i++) {\n          tempo = SBML_simulate(mod, molecules, r, TR, nbEspeces, i);\n          /*if (tempo != END) {\n              Especes_print_2(molecules, nbEspeces);\n\t\t\t\t printf(\"\\n\");\n          }*/\n          temp += tempo;\n      }\n  }\n  printf(\"Fin de simulation...\\n\");\n  printf(\"\\nEtat des especes :\\n\");\n  Especes_print_2(molecules, nbEspeces);\n  /* Liberation de la memoire des generateurs aleatoire */\n  gsl_rng_free(r);\n\n  /* Liberation de la memoire de la structure Especes */\n  Especes_free(molecules, nbEspeces);\n  if (TR != NULL)\n    free(TR);\n}\n\n/**\n * \\fn void SBML_score_add(pScore result, pScore result_temp, FILE *debugFile)\n * \\author Amine Ghozlane\n * \\brief  Add scores\n * \\param  result Struct Score used for all the simulation\n * \\param  result_temp Struct Score used at each simulation step\n * \\param  debugFile File use for debug\n */\nvoid SBML_score_add(pScore result, pScore result_temp, int nbEspeces)\n{\n  /* Addition des scores */\n  int i;\n\n  /* Copie des resultats */\n  for(i=0;i<nbEspeces;i++){\n      if(result->name[i]==NULL){\n          result->name[i]=(char*)malloc(((int)strlen(result_temp->name[i])+1)*sizeof(char));\n          assert(result->name[i]!=NULL);\n          strcpy(result->name[i], result_temp->name[i]);\n      }\n      result->quantite[i]+=result_temp->quantite[i];\n  }\n}\n\n/**\n * \\fn void SBML_score_mean(pScore result, int n)\n * \\author Amine Ghozlane\n * \\brief  Mean quantities for score\n * \\param  result Struct Score\n * \\param  n Number of simulation step\n */\nvoid SBML_score_mean(pScore result, int nbEspeces, int n)\n{\n  /* Moyenne des resultats */\n  int i;\n  for(i=0;i<nbEspeces;i++){\n      result->quantite[i]/=n;\n  }\n}\n\n/**\n * \\fn pScore SBML_scoreAlloc(pListParameters a)\n * \\author Amine Ghozlane\n * \\brief  Allocation of the struct Score\n * \\param  a Global parameters : struct ListParameters\n * \\return Allocated struct Score\n */\npScore SBML_scoreAlloc(int nbEspeces)\n{\n  int i;\n  /* Allocation de la structure de score */\n  pScore result=NULL;\n  result=(pScore)malloc(1*sizeof(Score));\n  assert(result!=NULL);\n\n  result->name=NULL;\n  result->quantite=NULL;\n  result->name=(char**)malloc(nbEspeces*sizeof(char*));\n  assert(result->name!=NULL);\n  result->quantite=(double*)malloc(nbEspeces*sizeof(double));\n  assert(result->quantite!=NULL);\n  for(i=0;i<nbEspeces;i++){\n      result->name[i]=NULL;\n      result->quantite[i]=0.0;\n  }\n  return result;\n}\n\n/**\n * \\fn void SBML_scoreFree(pScore out)\n * \\author Amine Ghozlane\n * \\brief  Free the struct Score\n * \\param  out Struct score\n */\nvoid SBML_scoreFree(pScore out, int nbEspeces)\n{\n  int i;\n  /* Libere la memoire alloue a la structure de score */\n  for(i=0;i<nbEspeces;i++){\n      if(out->name[i]!=NULL) free(out->name[i]);\n  }\n  if(out->name!=NULL) free(out->name);\n  if(out->quantite!=NULL) free(out->quantite);\n  if(out!=NULL) free(out);\n}\n\n/* Affiche le score moyen */\n\n/**\n * \\fn void SBML_scoreFree(pScore out)\n * \\author Amine Ghozlane\n * \\brief  Free the struct Score\n * \\param  out Struct score\n * \\param  nbEspeces\n */\nvoid SBML_score_print(pScore result, int nbEspeces)\n{\n  int i;\n  /* Print head*/\n  /*for(i=0;i<nbEspeces;i++){\n      printf(\"%s;\",result->name[i]);\n  }\n  printf(\"\\n\");*/\n  /* Print Value */\n  for(i=0;i<nbEspeces;i++){\n      /*printf(\"Molecule: %s - Biomass: %.0f\\n\",result->name[i],result->quantite[i]);*/\n      printf(\"%.0f;\",result->quantite[i]);\n  }\n  printf(\"\\n\");\n}\n\n/**\n * \\fn void SBML_compute_simulation_mean(Model_t *mod, int nb_simulation)\n * \\author Amine Ghozlane\n * \\brief  X time simulation of metabolic network\n * \\param  mod Model of the SBML file\n * \\param  nb_simulation Number of simulation step\n */\nvoid SBML_compute_simulation_mean(Model_t *mod, int nb_simulation)\n{\n  /* Simulation du reseau metabolique  */\n  int i, j,nbReactions = 0, nbEspeces = 0, temp = 1, tempo=0, test=0;\n  pEspeces molecules=NULL;\n  pTestReaction TR=NULL;\n  const gsl_rng_type *T;\n  gsl_rng * r;\n  pScore result=NULL,result_temp=NULL;\n\n  /* Allocation memoire et initialisation des generateurs de nombre aleatoire */\n  gsl_rng_env_setup();\n  if (!getenv(\"GSL_RNG_SEED\"))\n    gsl_rng_default_seed = time(NULL)+(double)getpid();\n  T = gsl_rng_default;\n  r = gsl_rng_alloc(T);\n  /*gsl_rng_default_seed = time(NULL)+(double)getpid();*/\n\n  /* Allocation memoire */\n  TR=(pTestReaction)malloc(1*sizeof(TestReaction));\n  assert(TR!=NULL);\n\n  /* File information */\n  nbReactions = (int)Model_getNumReactions(mod);\n  nbEspeces = (int)Model_getNumSpecies(mod);\n  molecules = Especes_alloc(nbEspeces);\n\n  /* Initialisation de la structure de score temporaire */\n  result=SBML_scoreAlloc(nbEspeces);\n  result_temp=SBML_scoreAlloc(nbEspeces);\n\n  /* Initialisation de la quantite des especes */\n  SBML_initEspeceAmounts(mod, molecules, nbEspeces);\n  /* Initialisation des reactions et des ratios*/\n  SBML_setReactions(mod, molecules, nbReactions, nbEspeces);\n\n  /*printf(\"Start the simulation\\n\");*/\n  /* SIMULATION */\n  for(j=0;j<nb_simulation;j++){\n      /* Simulation des reactions */\n      while (temp > END) {\n          temp = 0;\n          for (i = 0; i < nbEspeces; i++) {\n              tempo = SBML_simulate(mod, molecules, r, TR, nbEspeces, i);\n              temp +=tempo;\n          }\n          test+=1;\n      }\n      temp=1;\n      tempo=0;\n      /*printf(\"Nombre de tour %d\\n\",test);*/\n      /*Score */\n      /* Enregistre le score des especes */\n      Especes_scoreSpecies(molecules, nbEspeces, result_temp->name, result_temp->quantite);\n      SBML_score_add(result,result_temp,nbEspeces);\n      SBML_initEspeceAmounts(mod, molecules, nbEspeces);\n  }\n  SBML_score_mean(result,nbEspeces,nb_simulation);\n\n  /*printf(\"End of the simulation...\\n\");\n  printf(\"Final state of the molecules :\\n\");*/\n  SBML_score_print(result, nbEspeces);\n\n  /* Liberation de la memoire des generateurs aleatoire */\n  gsl_rng_free(r);\n\n  /* Liberation de la memoire du score */\n  SBML_scoreFree(result, nbEspeces);\n  SBML_scoreFree(result_temp, nbEspeces);\n\n  /* Liberation de la memoire de la structure Especes */\n  Especes_free(molecules, nbEspeces);\n  if(TR!=NULL) free(TR);\n}\n", "meta": {"hexsha": "f36531ea27ecc2d93e36923141f6c1124b2e6149", "size": 23296, "ext": "c", "lang": "C", "max_stars_repo_path": "src/simulation.c", "max_stars_repo_name": "aghozlane/yasimSBML", "max_stars_repo_head_hexsha": "bd2067127afaaeccf3292b288797ce90ec9cddc0", "max_stars_repo_licenses": ["DOC"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/simulation.c", "max_issues_repo_name": "aghozlane/yasimSBML", "max_issues_repo_head_hexsha": "bd2067127afaaeccf3292b288797ce90ec9cddc0", "max_issues_repo_licenses": ["DOC"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/simulation.c", "max_forks_repo_name": "aghozlane/yasimSBML", "max_forks_repo_head_hexsha": "bd2067127afaaeccf3292b288797ce90ec9cddc0", "max_forks_repo_licenses": ["DOC"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3276108727, "max_line_length": 147, "alphanum_fraction": 0.6659512363, "num_tokens": 6829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.341582499438317, "lm_q2_score": 0.04958902631991414, "lm_q1q2_score": 0.016938743555068757}}
{"text": "#ifndef PROB_FUNCTIONS_H\n#define PROB_FUNCTIONS_H\n\n#include <gsl/gsl_vector.h>\n#include \"data.h\"\n\ndouble my_f (const gsl_vector *x, void *params);\nvoid my_df (const gsl_vector *x, void *params, gsl_vector *g);\nvoid my_fdf (const gsl_vector *x, void *params, double *f, gsl_vector *g);\nvoid gradientQ (Dataset *data, double *dQdAlpha, double *dQdBeta);\ndouble computeLikelihood (Dataset *data);\ndouble computeQ (Dataset *data);\ndouble logProbL (int l, int z, double alphaI, double betaJ);\ndouble prob(double alpha, double beta);\nvoid EStep (Dataset *data);\nvoid MStep (Dataset *data);\n\n#endif\n", "meta": {"hexsha": "e18245749b4f616187bd8d88160de0e650f5278a", "size": 592, "ext": "h", "lang": "C", "max_stars_repo_path": "EM/prob_functions.h", "max_stars_repo_name": "ShreyaR/WorkerPoolSelection", "max_stars_repo_head_hexsha": "03e0bfeda422975c118efe91fe31045f9c27f002", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "EM/prob_functions.h", "max_issues_repo_name": "ShreyaR/WorkerPoolSelection", "max_issues_repo_head_hexsha": "03e0bfeda422975c118efe91fe31045f9c27f002", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "EM/prob_functions.h", "max_forks_repo_name": "ShreyaR/WorkerPoolSelection", "max_forks_repo_head_hexsha": "03e0bfeda422975c118efe91fe31045f9c27f002", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-02-25T18:59:03.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-25T18:59:03.000Z", "avg_line_length": 31.1578947368, "max_line_length": 74, "alphanum_fraction": 0.75, "num_tokens": 167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.45326184801538616, "lm_q2_score": 0.03732688453300536, "lm_q1q2_score": 0.016918852664086943}}
{"text": "/**\n * @file   libhades.c\n * @author Michael Hartmann <michael.hartmann@physik.uni-augsburg.de>\n * @date   February, 2016\n * @brief  library to access low-level LAPACK functions\n */\n\n#include <cblas.h>\n#include <errno.h>\n#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <string.h>\n#include <strings.h>\n\n#include <libhades.h>\n#include <libhades/parse_npy_dict.h>\n\n\n/** \\defgroup misc miscellaneous functions\n *  @{\n */\n\n/** @brief malloc wrapper\n *\n * This function uses malloc to allocate size bytes of memory and returns a\n * pointer to the memory. If an error occures, an error message is printed to\n * stderr and the program is aborted.\n *\n * @param [in] size amount of memory to allocate\n * @retval ptr pointer to the allocated memory\n */\nvoid *libhades_malloc(size_t size)\n{\n    void *ptr = malloc(size);\n    if(ptr == NULL)\n    {   \n        const int err = errno;\n        fprintf(stderr, \"malloc can't allocate %zu bytes of memory: %s (%d)\\n\", size, strerror(err), err);\n        abort();\n    }   \n    return ptr;\n}\n\n/** @brief free wrapper\n *\n * This function frees the memory allocated by \\ref libhades_malloc or \\ref\n * libhades_realloc (or malloc and realloc). If the pointer given is NULL, an error is\n * printed to stderr and the program is aborted.\n *\n * @param [in] ptr pointer to the memory that should be freed\n */\nvoid libhades_free(void *ptr)\n{\n    if(ptr == NULL)\n    {\n        fprintf(stderr, \"Trying to free NULL pointer\\n\");\n        abort();\n    }\n\n    free(ptr);\n}\n\n/** @brief realloc wrapper\n *\n * This function changes the size of the memory block pointed to by ptr to size\n * bytes. If ptr is NULL, this function behaves like \\ref libhades_malloc. If\n * an error occures, an error is printed to stderr and the program is aboprted.\n *\n * @param [in] ptr pointer to the memory block\n * @param [in] size size of the memory block\n * @retval ptr_new pointer to the new memory block\n */\nvoid *libhades_realloc(void *ptr, size_t size)\n{\n    void *ptr_new = realloc(ptr, size);\n\n    if(ptr_new == NULL)\n    {\n        int err = errno;\n        fprintf(stderr, \"realloc can't allocate %zu bytes of memory: %s (%d)\\n\", size, strerror(err), err);\n        abort();\n    }\n\n    return ptr_new;\n}\n\nstatic void *(*malloc_cb)(size_t)          = &libhades_malloc;\nstatic void *(*realloc_cb)(void *, size_t) = &libhades_realloc;\nstatic void  (*free_cb)(void *)            = &libhades_free;\n\n\n/** macro to create functions argmin, argmax, argabsmin, argabsmax */\n#define ARGXXX(FUNCTION_NAME, FUNCTION, RELATION) \\\nsize_t FUNCTION_NAME(double list[], size_t size) \\\n{ \\\n    size_t index = 0; \\\n    for(size_t i = 0; i < size; i++) \\\n        if(FUNCTION(list[i]) RELATION FUNCTION(list[index])) \\\n            index = i; \\\n    return index; \\\n}\n\n/** @brief Return index of smallest element in list\n *\n * @param [in] list\n * @param [in] size elements in list\n *\n * @retval index\n */\nARGXXX(argmin, +, <)\n\n/** @brief Return index of largest element in list\n *\n * @param [in] list\n * @param [in] size elements in list\n *\n * @retval index\n */\nARGXXX(argmax, +, >)\n\n/** @brief Return index of element with smallest absolute value in list\n *\n * @param [in] list\n * @param [in] size elements in list\n *\n * @retval index\n */\nARGXXX(argabsmin, fabs, <)\n/** @brief Return index of element with largest absolute value in list\n *\n * @param [in] list\n * @param [in] size elements in list\n *\n * @retval index\n */\nARGXXX(argabsmax, fabs, >)\n\n/** @}*/\n\n\n\n/** \\defgroup create Creating, printing and freeing matrices\n *  @{\n */\n\nstatic inline void _swap_int(int *a, int *b);\nstatic inline void _swap_size_t(size_t *a, size_t *b);\n\nstatic inline void _swap_int(int *a, int *b)\n{\n    int c = *a;\n    *a = *b;\n    *b = c;\n}\n\nstatic inline void _swap_size_t(size_t *a, size_t *b)\n{\n    size_t c = *a;\n    *a = *b;\n    *b = c;\n}\n\n#define MATRIX_SWAP(FUNCTION_NAME, MATRIX_TYPE, TYPE) \\\nvoid FUNCTION_NAME(MATRIX_TYPE *A, MATRIX_TYPE *B) \\\n{ \\\n    /* swap pointers */ \\\n    TYPE *ptr = A->M; \\\n    A->M = B->M; \\\n    B->M = ptr; \\\n\\\n    /* swap rows */ \\\n    _swap_int(&A->rows, &B->rows); \\\n\\\n    /* swap columns */ \\\n    _swap_int(&A->columns, &B->columns); \\\n\\\n    /* swap min */ \\\n    _swap_int(&A->min, &B->min); \\\n\\\n    /* swap size */ \\\n    _swap_size_t(&A->size, &B->size); \\\n\\\n    /* swap type */ \\\n    _swap_int(&A->type, &B->type); \\\n\\\n    /* swap min */ \\\n    _swap_int(&A->min, &B->min); \\\n}\n\n/** @brief Swap matrices A and B\n *\n * This function swaps the matrices A and B. The former content of A will be\n * the content of B and vice versa. No data is copied or moved, but the\n * pointers are swapped.\n *\n * @param [in,out] A matrix A\n * @param [in,out] B matrix B\n */\nMATRIX_SWAP(matrix_swap, matrix_t, double);\n\n/** @brief Swap matrices A and B\n *\n * See \\ref matrix_swap.\n *\n * @param [in,out] A matrix A\n * @param [in,out] B matrix B\n */\nMATRIX_SWAP(matrix_complex_swap, matrix_complex_t, complex_t);\n\n/** macro to create a diagnal matrix out of a vector */\n#define MATRIX_DIAG(FUNCTION_NAME, MATRIX_TYPE, ZEROS) \\\nMATRIX_TYPE *FUNCTION_NAME(MATRIX_TYPE *v) \\\n{ \\\n    int dim = v->size; \\\n    MATRIX_TYPE *A = ZEROS(dim, dim, NULL); \\\n    if(A == NULL) \\\n        return NULL; \\\n\\\n    for(int i = 0; i < dim; i++) \\\n        matrix_set(A, i,i, v->M[i]); \\\n\\\n    return A; \\\n}\n\n/** @brief Construct a real diagonal matrix from a row or columns vector\n *\n * @param [in] v row or column vector\n *\n * @retval A A = diag(v) if successfull, NULL otherwise\n */\nMATRIX_DIAG(matrix_diag, matrix_t, matrix_zeros)\n\n/** @brief Construct a complex diagonal matrix from a row or columns vector\n *\n * @param [in] v row or column vector\n *\n * @retval A A = diag(v) if successfull, NULL otherwise\n */\nMATRIX_DIAG(matrix_complex_diag, matrix_complex_t, matrix_complex_zeros)\n\n\n/** @brief Set functions to allocate and free memory\n *\n * By default wrappers to malloc and free from <stdlib.h> are used to allocate\n * and free memory. If allocation of memory fails or a NULL pointer is freed,\n * the program will terminate.\n *\n * @param [in] _malloc_cb callback to a malloc-alike function\n * @param [in] _free_cb callback to a free-alike function\n */\nvoid matrix_set_alloc(void *(*_malloc_cb)(size_t), void  (*_free_cb)(void *))\n{\n    malloc_cb = _malloc_cb;\n    free_cb   = _free_cb;\n}\n\n\n/** macro for copying matrices. */\n#define MATRIX_COPY(FUNCTION_NAME, MTYPE, TYPE, ALLOC) \\\nMTYPE *FUNCTION_NAME(MTYPE *A, MTYPE *C) \\\n{ \\\n    if(C == NULL) { \\\n        C = ALLOC(A->rows, A->columns); \\\n        if(C == NULL) \\\n            return NULL; \\\n    } \\\n\\\n    C->rows    = A->rows; \\\n    C->columns = A->columns; \\\n    C->min     = A->min; \\\n    C->size    = A->size; \\\n    C->type    = A->type; \\\n    C->view    = 0; \\\n    memcpy(C->M, A->M, C->size*sizeof(TYPE)); \\\n    return C; \\\n}\n\n\n\n/** @brief Copy real matrix A\n *\n * Copy matrix A into C. If C is NULL, space for the matrix C will be\n * allocated.\n *\n * @param [in]     A real matrix\n * @param [in,out] C real matrix\n *\n * @retval C copy of A\n */\nMATRIX_COPY(matrix_copy, matrix_t, double, matrix_alloc)\n\n\n/** @brief Copy complex matrix A\n *\n * Copy matrix A into C. If C is NULL, space for the matrix C will be\n * allocated.\n *\n * @param [in]     A complex matrix\n * @param [in,out] C complex matrix\n *\n * @retval C copy of A\n */\nMATRIX_COPY(matrix_complex_copy, matrix_complex_t, complex_t, matrix_complex_alloc)\n\n\n/** @brief Copy a real matrix A to a complex matrix C\n *\n * Copy the matrix A to a complex matrix C. The matrix elements of A and C will\n * be identical. If C is NULL, memory for the matrix will be allocated.\n *\n * @param [in] A real matrix\n *\n * @retval C copy of A if successfull, NULL otherwise\n */\nmatrix_complex_t *matrix_tocomplex(matrix_t *A, matrix_complex_t *C)\n{\n    if(C == NULL)\n    {\n        C = matrix_complex_alloc(A->rows, A->columns);\n        if(C == NULL)\n            return NULL;\n    }\n\n    for(size_t i = 0; i < C->size; i++)\n        C->M[i] = A->M[i];\n\n    return C;\n}\n\n/** @brief Print real matrix M to stream\n *\n * Print the matrix A to the stream given by stream, e.g. stdout or stderr.\n * The format is given by the format string format, the separator of two\n * columns is sep, the separator between lines is given by sep_line. Both sep\n * and sep_line may be NULL.\n *\n * @param [in] stream output stream\n * @param [in] A real matrix\n * @param [in] format output format, e.g. \"%lf\" or \"%g\"\n * @param [in] sep separator between columns, e.g. \"\\t\"\n * @param [in] sep_line separator between lines, e.g. \"\\n\"\n */\nvoid matrix_fprintf(FILE *stream, matrix_t *A, const char *format, const char *sep, const char *sep_line)\n{\n    const int rows = A->rows, columns = A->columns;\n\n    for(int i = 0; i < rows; i++)\n    {\n        for(int j = 0; j < columns; j++)\n        {\n            fprintf(stream, format, matrix_get(A, i,j));\n            if(sep != NULL)\n                fputs(sep, stream);\n        }\n        if(sep_line != NULL)\n            fputs(sep_line, stream);\n    }\n}\n\n/** @brief Print complex matrix A to stream\n *\n * See matrix_fprintf.\n *\n * @param [in] stream output stream\n * @param [in] A complex matrix\n * @param [in] format output format, e.g. \"%+lf%+lfi\"\n * @param [in] sep separator between columns, e.g. \"\\t\"\n * @param [in] sep_line separator between lines, e.g. \"\\n\"\n */\nvoid matrix_complex_fprintf(FILE *stream, matrix_complex_t *A, const char *format, const char *sep, const char *sep_line)\n{\n    const int rows = A->rows, columns = A->columns;\n\n    for(int i = 0; i < rows; i++)\n    {\n        for(int j = 0; j < columns; j++)\n        {\n            const complex_t c = matrix_get(A, i,j);\n            fprintf(stream, format, CREAL(c), CIMAG(c));\n            if(sep != NULL)\n                fputs(sep, stream);\n        }\n        if(sep_line != NULL)\n            fputs(sep_line, stream);\n    }\n}\n\n/** macro for matrix allocations. */\n#define MATRIX_ALLOC(FUNCTION_NAME, MTYPE, TYPE) \\\nMTYPE *FUNCTION_NAME(int rows, int columns) \\\n{ \\\n    if(rows <= 0 || columns <= 0) \\\n        return NULL; \\\n\\\n    MTYPE *A = malloc_cb(sizeof(MTYPE)); \\\n    if(A == NULL) \\\n        return NULL; \\\n\\\n    const size_t size = (size_t)rows*(size_t)columns; \\\n\\\n    A->rows    = rows; \\\n    A->columns = columns; \\\n    A->min     = MIN(rows, columns); \\\n    A->size    = size; \\\n    A->type    = 0; \\\n    A->view    = 0; \\\n    A->M       = malloc_cb(size*sizeof(TYPE)); \\\n    if(A->M == NULL) \\\n    { \\\n        free_cb(A); \\\n        return NULL; \\\n    } \\\n\\\n    return A; \\\n}\n\n/** @brief Allocate memory for real matrix of m rows and n columns\n *\n * This function will allocate and return a matrix of m lines and n columns.\n * The function given by matrix_set_alloc will be used to allocate memory; by\n * default this is malloc from <stdlib.h>.\n *\n * The matrix elements will be undefined. To allocate a matrix initialized with\n * zeros, see matrix_zeros. To create a unity matrix, see matrix_eye.\n *\n * @param [in] rows rows of matrix M (rows > 0)\n * @param [in] columns columns of matrix M (columns > 0)\n *\n * @retval A real matrix if successful, NULL otherwise\n */\nMATRIX_ALLOC(matrix_alloc, matrix_t, double)\n\n/** @brief Allocate memory for complex matrix of m rows and n columns\n *\n * See matrix_alloc.\n *\n * @param [in] rows rows of matrix M (rows > 0)\n * @param [in] columns columns of matrix M (columns > 0)\n *\n * @retval A complex matrix if successful, otherwise NULL\n */\nMATRIX_ALLOC(matrix_complex_alloc, matrix_complex_t, complex_t)\n\n/** macro to create zero matrix */\n#define MATRIX_ZEROS(FUNCTION_NAME, MTYPE, TYPE, ALLOC, SETALL) \\\nMTYPE *FUNCTION_NAME(int rows, int columns, MTYPE *A) \\\n{ \\\n    if(A == NULL) \\\n    { \\\n        A = ALLOC(rows,columns); \\\n        if(A == NULL) \\\n            return NULL; \\\n    } \\\n\\\n    SETALL(A, 0); \\\n\\\n    return A; \\\n}\n\n/** @brief Generate a real zero matrix of m lines and n columns\n *\n * Set every element of matrix A to 0. If A is NULL, the matrix will be\n * created. In this case, you have to free the matrix yourself.\n *\n * @param [in] rows rows of matrix M\n * @param [in] columns columns of matrix M\n * @param [in,out] A: matrix\n *\n * @retval A real matrix 0 if successful, otherwise NULL\n */\nMATRIX_ZEROS(matrix_zeros, matrix_t, double, matrix_alloc, matrix_setall)\n\n/** @brief Generate a complex zero matrix of m lines and n columns\n *\n * See matrix_zeros.\n *\n * @param [in] rows rows of matrix M\n * @param [in] columns columns of matrix M\n * @param [in,out] A: matrix\n *\n * @retval A complex matrix 0 if successful, otherwise NULL\n */\nMATRIX_ZEROS(matrix_complex_zeros, matrix_complex_t, complex_t, matrix_complex_alloc, matrix_complex_setall)\n\n\n/** macro to create matrix x*Id */\n#define MATRIX_SETALL(FUNCTION_NAME, MATRIX_TYPE, TYPE) \\\nvoid FUNCTION_NAME(MATRIX_TYPE *A, TYPE x) \\\n{ \\\n    const size_t size = A->size; \\\n    TYPE *M = A->M; \\\n    for(size_t i = 0; i < size; i++) \\\n        *M++ = x; \\\n}\n\n/** @brief Set matrix elements of A to x\n *\n * @param [in,out] A real matrix\n * @param [in] x real number\n */\nMATRIX_SETALL(matrix_setall, matrix_t, double)\n\n/** @brief Set matrix elements of A to x\n *\n * @param [in,out] A complex matrix\n * @param [in] x complex number\n */\nMATRIX_SETALL(matrix_complex_setall, matrix_complex_t, complex_t)\n\n/** macro to create unity matrix */\n#define MATRIX_EYE(FUNCTION_NAME, MTYPE, TYPE, ALLOC, SETALL) \\\nMTYPE *FUNCTION_NAME(int dim, MTYPE *A) \\\n{ \\\n    if(A == NULL) \\\n    { \\\n        A = ALLOC(dim,dim); \\\n        if(A == NULL) \\\n            return NULL; \\\n    } \\\n \\\n    const int min = A->min; \\\n    TYPE *M = A->M; \\\n    SETALL(A,0); \\\n    for(int i = 0; i < min; i++) \\\n        *(M+i*(min+1)) = 1; \\\n \\\n    return A; \\\n}\n\n\n/** @brief Create real identity matrix\n *\n * If A == NULL, a identity matrix of dimension dim times dim is created and\n * returned.\n * If A != NULL, the matrix A is set to the identity matrix and the parameter\n * dim is ignored. More specific, for a general (e.g. not square) matrix A, the\n * matrix elements are set to A_ij = Delta_ij.\n *\n * @param [in]     dim dimension of identity matrix (ignored for A == NULL)\n * @param [in,out] A real matrix\n *\n * @retval A identity matrix if successful, NULL otherwise\n */\nMATRIX_EYE(matrix_eye, matrix_t, double, matrix_alloc, matrix_setall)\n\n/** @brief Create complex identity matrix\n *\n * See matrix_eye.\n *\n * @param [in]     dim dimension of identity matrix (ignored for A == NULL)\n * @param [in,out] A complex matrix\n *\n * @retval A identity matrix if successful, NULL otherwise\n */\nMATRIX_EYE(matrix_complex_eye, matrix_complex_t, complex_t, matrix_complex_alloc, matrix_complex_setall)\n\n\n/** macro to free matrices */\n#define MATRIX_FREE(FUNCTION_NAME, MTYPE) \\\nvoid FUNCTION_NAME(MTYPE *A) \\\n{ \\\n    if(A != NULL) \\\n    { \\\n        if(!A->view && A->M != NULL) \\\n        { \\\n            free_cb(A->M); \\\n            A->M = NULL; \\\n        } \\\n        free_cb(A); \\\n    } \\\n}\n\n/** @brief Free real matrix\n *\n * This function will free the memory allocated for matrix M. If M is NULL this\n * function will do nothing.\n *\n * @param [in,out] A matrix to free\n */\nMATRIX_FREE(matrix_free, matrix_t)\n\n/** @brief Free complex matrix\n *\n * See matrix_free.\n *\n * @param [in,out] A matrix to free\n */\nMATRIX_FREE(matrix_complex_free, matrix_complex_t)\n\n/** @}*/\n\n\n/** \\defgroup trdet trace and determinant\n *  @{\n */\n\n/** macro to calculate trace of matrix */\n#define MATRIX_TRACE(FUNCTION_NAME, MATRIX_TYPE, TYPE) \\\nTYPE FUNCTION_NAME(MATRIX_TYPE *A) \\\n{ \\\n    const int min = A->min; \\\n    const TYPE *M = A->M; \\\n    TYPE trace = 0; \\\n    for(int i = 0; i < min; i++) \\\n        trace += *(M+i*(1+min)); \\\n\\\n    return trace; \\\n}\n\n/** @brief Calculate Tr(A) of real matrix A\n *\n * @param [in] A complex matrix\n *\n * @retval x with x=Tr(A)\n */\nMATRIX_TRACE(matrix_trace, matrix_t, double)\n\n/** @brief Calculate Tr(A) of complex matrix A\n *\n * @param [in] A complex matrix\n *\n * @retval z with z=Tr(A)\n */\nMATRIX_TRACE(matrix_complex_trace, matrix_complex_t, complex_t)\n\n/** @brief Calculate Tr(A*B)\n *\n * This will calculate the trace of A*B: Tr(A*B). Matrix A and B must be square\n * matrices of dimension dim, dim.\n *\n * A and B must not point to the same matrix or the behaviour will be\n * undefined!\n *\n * @param [in] A real matrix\n * @param [in] B real matrix\n *\n * @retval x with x=Tr(A*B)\n */\ndouble matrix_trace_AB(matrix_t *A, matrix_t *B)\n{\n    const int dim = A->min;\n    double sum = 0;\n    double *M1 = A->M;\n    double *M2 = B->M;\n\n    for(int i = 0; i < dim; i++)\n        sum += cblas_ddot(dim, M1+i, dim, M2+i*dim, 1);\n\n    return sum;\n}\n\n/** @brief Calculate Tr(A*B) for A,B complex\n *\n * See matrix_trace_AB.\n *\n * @param [in] A complex matrix\n * @param [in] B complex matrix\n *\n * @retval z with z=Tr(A*B)\n */\ncomplex_t matrix_trace_complex_AB(matrix_complex_t *A, matrix_complex_t *B)\n{\n    const int dim = A->min;\n    complex_t sum = 0;\n\n    for(int i = 0; i < dim; i++)\n        for(int k = 0; k < dim; k++)\n            sum += matrix_get(A, i,k)*matrix_get(B, k,i);\n\n    return sum;\n}\n\n/** @brief Calculate Re(Tr(A*B)) for A,B complex\n *\n * See matrix_trace_AB.\n *\n * @param [in] A complex matrix\n * @param [in] B complex matrix\n *\n * @retval x with x=Re(Tr(A*B))\n */\ndouble matrix_trace_complex_AB_real(matrix_complex_t *A, matrix_complex_t *B)\n{\n    const int dim = A->rows;\n    double sum = 0;\n    const complex_t *M1 = A->M;\n    const complex_t *M2 = B->M;\n\n    for(int i = 0; i < dim; i++)\n        for(int k = 0; k < dim; k++)\n            sum += CREAL(M1[i*dim+k]*M2[k*dim+i]);\n\n    return sum;\n}\n\n/** @}*/\n\n\n/** \\defgroup kron Kronecker product\n *  @{\n */\n\n/** macro to create Kronecker product */\n#define MATRIX_KRON(FUNCTION_NAME, MTYPE, TYPE, ALLOC, SETALL) \\\nMTYPE *FUNCTION_NAME(MTYPE *A, MTYPE *B, MTYPE *C) \\\n{ \\\n    const int Am = A->rows, An = A->columns; \\\n    const int Bm = B->rows, Bn = B->columns; \\\n    if(C == NULL) \\\n    { \\\n        C = ALLOC(Am*Bm, An*Bn); \\\n        if(C == NULL) \\\n            return NULL; \\\n    } \\\n    SETALL(C, 0); \\\n\\\n    for(int m = 0; m < Am; m++) \\\n        for(int n = 0; n < An; n++) \\\n        { \\\n            const TYPE c = matrix_get(A,m,n); \\\n            if(c != 0) \\\n            { \\\n                for(int im = 0; im < Bm; im++) \\\n                    for(int in = 0; in < Bn; in++) \\\n                        matrix_set(C, m*Bm+im, n*Bn+in, c*matrix_get(B,im,in)); \\\n            } \\\n        } \\\n\\\n    return C; \\\n}\n\n\n/** @brief Calculate Kronecker product of real matrices A and B\n *\n * Matrix A has dimension Am,An, matrix B has dimension Bm,Bn.\n *\n * If C is not NULL, the Kronecker product will be stored in C. C must have\n * dimension Am+Bm,An+Bn. If C is NULL, memory for the matrix will be allocated\n * and the matrix will be returned. You have to free the memory for the\n * returned matrix yourself.\n *\n * @param [in] A real matrix\n * @param [in] B real matrix\n * @param [in,out] C Kronecker product\n *\n * @retval C Kronecker product of A and B, NULL if no memory could be allocated\n */\nMATRIX_KRON(matrix_kron, matrix_t, double, matrix_alloc, matrix_setall)\n\n\n/** @brief Calculate Kronecker product of complex matrices A and B\n *\n * See matrix_kron.\n *\n * @param [in] A complex matrix\n * @param [in] B complex matrix\n * @param [in,out] C Kronecker product\n *\n * @retval C Kronecker product of A and B\n */\nMATRIX_KRON(matrix_complex_kron, matrix_complex_t, complex_t, matrix_complex_alloc, matrix_complex_setall)\n\n/** @}*/\n\n\n/** \\defgroup addsubmult Add, subtract and multiply matrices\n *  @{\n */\n\n\n/** macro to multiply matrix with scalar factor */\n#define MATRIX_MULT_SCALAR(FUNCTION_NAME, MTYPE, TYPE) \\\nvoid FUNCTION_NAME(MTYPE *A, TYPE alpha) \\\n{ \\\n    const size_t size = A->size; \\\n    TYPE *M = A->M; \\\n    for(size_t i = 0; i < size; i++) \\\n        M[i] *= alpha; \\\n}\n\n/** @brief Multiply real matrix with a real scalar\n *\n * alpha*A -> A\n *\n * @param [in,out] A real matrix\n * @param [in] alpha real scalar\n * @retval A, A=alpha*A\n */\nMATRIX_MULT_SCALAR(matrix_mult_scalar, matrix_t, double)\n\n/** @brief Multiply complex matrix with a complex scalar\n *\n * alpha*A -> A\n *\n * @param [in,out] A complex matrix\n * @param [in] alpha complex scalar\n * @retval A, A=alpha*A\n */\nMATRIX_MULT_SCALAR(matrix_complex_mult_scalar, matrix_complex_t, complex_t)\n\n/** @brief Multiply real matrix with a complex scalar\n *\n * alpha*A -> C\n *\n * If C is NULL, memory for the matrix C will be allocated. If C is not NULL, C\n * must have the correct dimension.\n *\n * @param [in] A real matrix\n * @param [in] alpha complex scalar\n * @param [in,out] C complex matrix\n *\n * @retval C, C = alpha*A\n */\nmatrix_complex_t *matrix_mult_complex_scalar(matrix_t *A, complex_t alpha, matrix_complex_t *C)\n{\n    const int rows    = A->rows;\n    const int columns = A->columns;\n    const double *AM  = A->M;\n    complex_t *CM;\n    if(C == NULL)\n    {\n        C = matrix_complex_alloc(rows, columns);\n        if(C == NULL)\n            return NULL;\n    }\n    CM = C->M;\n\n    for(size_t i = 0; i < C->size; i++)\n        CM[i] = alpha*AM[i];\n\n    return C;\n}\n\n\n/* compute alpha*A*B */\n#define MATRIX_MULT(FUNCTION_NAME, MATRIX_TYPE, TYPE, ALLOC, BLAS_xGEMM, PTR) \\\nMATRIX_TYPE *FUNCTION_NAME(MATRIX_TYPE *A, MATRIX_TYPE *B, TYPE alpha, MATRIX_TYPE *C) \\\n{ \\\n    TYPE beta = 0; \\\n\\\n    if(A->columns != B->rows) \\\n        return NULL; \\\n\\\n    if(C == NULL) \\\n    { \\\n        C = ALLOC(A->rows, B->columns); \\\n        if(C == NULL) \\\n            return NULL; \\\n    } \\\n\\\n    /* xGEMM ( TRANSA, TRANSB, M, N, K, ALPHA, A, LDA, B, LDB, BETA, C, LDC) */ \\\n    BLAS_xGEMM(CblasColMajor, /* column order */ \\\n               CblasNoTrans,  /* don't transpose/conjugate A */ \\\n               CblasNoTrans,  /* don't transpose/conjugate B */ \\\n               A->rows,       /* M: rows of A and C */ \\\n               B->columns,    /* N: columns of B and C */ \\\n               A->columns,    /* K: columns of A and rows of B */ \\\n               PTR alpha,     /* alpha: scalar */ \\\n               A->M,          /* A: matrix A */ \\\n               A->rows,       /* LDA: leading dimension of A (columns) */ \\\n               B->M,          /* B: matrix B */ \\\n               A->columns,    /* LDB: leading dimension of B (columns) */ \\\n               PTR beta,      /* beta: scalar */ \\\n               C->M,          /* C: matrix C */ \\\n               C->rows        /* LDC: leading dimension of C (columns) */ \\\n    ); \\\n\\\n    return C; \\\n}\n\n/** @brief Multiply real matrices\n *\n * alpha*A*B -> C\n *\n * If C is NULL, memory for the matrix C will be allocated.\n *\n * @param [in] A real matrix\n * @param [in] B real matrix\n * @param [in] alpha real scalar\n * @param [in,out] C real matrix\n *\n * @retval C, C = alpha*A*B\n */\nMATRIX_MULT(matrix_mult, matrix_t, double, matrix_alloc, cblas_dgemm, +)\n\n/** @brief Multiply complex matrices\n *\n * alpha*A*B -> C\n *\n * If C is NULL, memory for the matrix C will be allocated.\n *\n * @param [in] A complex matrix\n * @param [in] B complex matrix\n * @param [in] alpha complex scalar\n * @param [in,out] C complex matrix\n *\n * @retval C, C = alpha*A*B\n */\nMATRIX_MULT(matrix_complex_mult, matrix_complex_t, complex_t, matrix_complex_alloc, cblas_zgemm, &)\n\n/** macro to add two matrices */\n#define MATRIX_ADD(FUNCTION_NAME, TYPE1, MTYPE1, TYPE2, MTYPE2) \\\nint FUNCTION_NAME(MTYPE1 *A, MTYPE2 *B, TYPE1 alpha, MTYPE1 *C) \\\n{ \\\n    const size_t size = A->size; \\\n    TYPE1 *M3; \\\n    TYPE1 *M1 = A->M; \\\n    TYPE2 *M2 = B->M; \\\n\\\n    if(C == NULL) \\\n        M3 = A->M; \\\n    else \\\n        M3 = C->M; \\\n\\\n    if(A->rows != B->rows || A->columns != B->columns) \\\n        return LIBHADES_ERROR_SHAPE; \\\n\\\n    for(size_t i = 0; i < size; i++) \\\n        M3[i] = M1[i] + (alpha*M2[i]); \\\n\\\n    return 0; \\\n}\n\n/** @brief Add real matrices A and B\n *\n * Calculate A+alpha*B -> C.\n *\n * The result will be stored in C. If C is NULL, the result is stored in A.\n *\n * @param [in,out] A real matrix\n * @param [in] B real matrix\n * @param [in] alpha real scalar\n * @param [in,out] C real matrix or NULL\n *\n * @retval 0 if successfull\n * @retval LIBHADES_ERROR_SHAPE if matrices have wrong shape\n */\nMATRIX_ADD(matrix_add, double, matrix_t, double, matrix_t)\n\n/** @brief Add complex matrices A and B\n *\n * Calculate A+alpha*B -> C.\n *\n * The result will be stored in C. If C is NULL, the result is stored in A.\n *\n * @param [in,out] A complex matrix\n * @param [in] B complex matrix\n * @param [in] alpha complex number\n * @param [in,out] C complex matrix or NULL\n *\n * @retval 0 if successfull\n * @retval LIBHADES_ERROR_SHAPE if matrices have wrong shape\n */\nMATRIX_ADD(matrix_complex_add, complex_t, matrix_complex_t, complex_t, matrix_complex_t)\n\n/** @brief Add complex matrix A and real matrix B\n *\n * Calculate A+alpha*B -> C.\n *\n * The result will be stored in C. If C is NULL, the result is stored in A.\n *\n * @param [in,out] A complex matrix\n * @param [in] B real matrix\n * @param [in] alpha complex scalar\n * @param [in,out] C complex matrix or NULL\n *\n * @retval 0 if successfull\n * @retval LIBHADES_ERROR_SHAPE if matrices have wrong shape\n */\nMATRIX_ADD(matrix_complex_add_real, complex_t, matrix_complex_t, double, matrix_t)\n\n/** @}*/\n\n\n/** \\defgroup transconj Transpose, conjugate\n *  @{\n */\n\n\n#define MATRIX_TRANSPOSE(FUNCTION_NAME, MTYPE, TYPE) \\\nvoid FUNCTION_NAME(MTYPE *A) \\\n{ \\\n    const int rows    = A->rows; \\\n    const int columns = A->columns; \\\n    for(int im = 0; im < rows; im++) \\\n        for(int in = im+1; in < columns; in++) \\\n        { \\\n            TYPE temp = matrix_get(A, im, in); \\\n            matrix_set(A, im, in, matrix_get(A, in, im)); \\\n            matrix_set(A, in, im, temp); \\\n        } \\\n\\\n    A->rows    = columns; \\\n    A->columns = rows; \\\n}\n\n/** @brief Transpose real matrix A\n *\n * The matrix will be transposed.\n *\n * @param [in,out] A real matrix\n *\n * @retval C with C=A^T\n */\nMATRIX_TRANSPOSE(matrix_transpose, matrix_t, double)\n\n/** @brief Transpose complex matrix A\n *\n * The matrix will be transposed.\n *\n * @param [in,out] A complex matrix\n *\n * @retval C with C=A^T\n */\nMATRIX_TRANSPOSE(matrix_complex_transpose, matrix_complex_t, complex_t)\n\n/** @}*/\n\n\n/** \\defgroup ev Eigenvalue problems\n *  @{\n */\n\n\n/** @brief Compute eigenvalues and optionally eigenvectors of symmetric matrix A\n *\n * This function computes all eigenvalues and, optionally, eigenvectors of a\n * real symmetric matrix A.\n *\n * See dsyev.\n *\n * @param [in] A real matrix\n * @param [in] JOBZ 'N': only eigenvalues, 'V' eigenvalues and eigenvectors\n * @param [in] UPLO 'U': upper triangle part of A is stored; 'L': lower triangle part of A is stored\n * @param [in] w real matrix of dimension (dim,1) (i.e. a vector); the eigenvalues will be stored in w\n *\n * @retval 0 on success\n */\nint eig_sym(matrix_t *A, char *JOBZ, char *UPLO, matrix_t *w)\n{\n    int info, lwork = -1, N = A->min;\n    double workopt;\n    double *work;\n\n    dsyev_(JOBZ, UPLO, &N, A->M, &N, w->M, &workopt, &lwork, &info);\n    if(info != 0)\n        return info;\n\n    lwork = workopt;\n    work = malloc_cb(lwork*sizeof(double));\n    if(work == NULL)\n        return LIBHADES_ERROR_OOM;\n\n    dsyev_(JOBZ, UPLO, &N, A->M, &N, w->M, work, &lwork, &info);\n\n    free_cb(work);\n\n    return info;\n}\n\n/** @brief Compute eigenvalues and optionally eigenvectors of Hermitian matrix A\n *\n * This function computes all eigenvalues and, optionally, eigenvectors of a\n * Hermitian symmetric matrix A.\n *\n * See zheev.\n *\n * @param [in] A complex matrix\n * @param [in] JOBZ 'N': only eigenvalues, 'V' eigenvalues and eigenvectors\n * @param [in] UPLO 'U': upper triangle part of A is stored; 'L': lower triangle part of A is stored\n * @param [in] w real matrix of dimension (dim,1) (i.e. a vector); the eigenvalues will be stored in w\n *\n * @retval 0 on success\n */\nint eig_herm(matrix_complex_t *A, char *JOBZ, char *UPLO, matrix_t *w)\n{\n    int info, lwork = -1, N = A->min;\n    complex_t workopt;\n    complex_t *work = NULL;\n    double *rwork;\n    \n    rwork = malloc_cb(MAX(1, 3*N-2)*sizeof(double));\n    if(rwork == NULL)\n        return LIBHADES_ERROR_OOM;\n\n    zheev_(JOBZ, UPLO, &N, A->M, &N, w->M, &workopt, &lwork, rwork, &info);\n    if(info != 0)\n    {\n        free_cb(rwork);\n        return info;\n    }\n\n    lwork = CREAL(workopt);\n    work = malloc_cb(lwork*sizeof(complex_t));\n    if(work == NULL)\n    {\n        free_cb(rwork);\n        return LIBHADES_ERROR_OOM;\n    }\n\n    zheev_(JOBZ, UPLO, &N, A->M, &N, w->M, work, &lwork, rwork, &info);\n\n    free_cb(rwork);\n    free_cb(work);\n\n    return info;\n}\n\n/** @brief Compute eigenvalues and optionally eigenvectors of matrix A\n *\n * Compute for an N-by-N complex nonsymmetric matrix A, the eigen- values and,\n * optionally, right eigenvectors\n *\n * See zgeev.\n *\n * @param [in] A real matrix\n * @param [in] w list containing the eigenvalues of A\n * @param [in] vr if vr != NULL, right eigenvectors are computed and will be stored in vr; vr must be a complex matrix of dimension (dim,dim)\n * @param [in] vl if vl != NULL, lefft eigenvectors are computed and will be stored in vl; vl must be a complex matrix of dimension (dim,dim)\n *\n * @retval 0 on success\n */\n\n/* Parameters */\nint eig_complex_generic(matrix_complex_t *A, matrix_complex_t *w, matrix_complex_t *vl, matrix_complex_t *vr)\n{\n    int N = A->min;\n    int lwork = -1;\n    char jobvr = 'N';\n    char jobvl = 'N';\n    int info;\n    complex_t *evr  = NULL;\n    complex_t *evl  = NULL;\n    complex_t *work = NULL;\n    double *rwork   = NULL;\n    complex_t wopt;\n\n    /* if vr is not NULL, calculate right eigenvectors */\n    if(vr != NULL)\n    {\n        jobvr = 'V';\n        evr   = vr->M;\n    }\n    /* if vl is not NULL, calculate left eigenvectors */\n    if(vl != NULL)\n    {\n        jobvl = 'V';\n        evl   = vl->M;\n    }\n\n    /* get the optimal size for workspace work */\n    zgeev_(&jobvl, &jobvr, &N, A->M, &N, w->M, evl, &N, evr, &N, &wopt, &lwork, rwork, &info);\n\n    if(info != 0)\n        return info;\n\n    lwork = CREAL(wopt);\n\n    rwork = malloc_cb(2*N*sizeof(double));\n    work  = malloc_cb(lwork*sizeof(complex_t));\n\n    if(rwork == NULL || work == NULL)\n    {\n        if(rwork != NULL)\n            free(rwork);\n        if(work != NULL)\n            free(work);\n\n        return LIBHADES_ERROR_OOM;\n    }\n\n    /* SUBROUTINE ZGEEV( JOBVL, JOBVR, N, A, LDA, W, VL, LDVL, VR, LDVR, WORK, LWORK, RWORK, INFO ) */\n    zgeev_(\n        &jobvl,     /* left eigenvectors of A are not computed */\n        &jobvr,     /* calculate/don't calculate right eigenvectors */\n        &N,         /* order of matrix A */\n        A->M,       /* matrix A */\n        &N,         /* LDA - leading dimension of A */\n        w->M,       /* eigenvalues */\n        evl,        /* left eigenvectors */\n        &N,         /* leading dimension of array vl */\n        evr,        /* eigenvectors */\n        &N,         /* leading dimension of the array VR */\n        work,       /* COMPLEX*16 array, dimension (LWORK) */\n        &lwork,     /* dimension of the array WORK; LWORK >= max(1,2*N) */\n        rwork,      /* (workspace) DOUBLE PRECISION array, dimension (2*N) */\n        &info       /* 0 == success */\n    );\n\n    free_cb(work);\n    free_cb(rwork);\n\n    return info;\n}\n\nint eig_complex_vr(matrix_complex_t *M, complex_t lambda, matrix_complex_t *vr)\n{\n    matrix_complex_t *A = NULL, *b = NULL;\n    const int rows    = M->rows;\n    const int columns = M->columns;\n\n    /* lapack */\n    char trans = 'N';\n    int info, lwork;\n    complex_t work_size, *work = NULL;\n    int m = rows+1, n = columns, nrhs = 1;\n    int lda = m, ldb = MAX(m,n);\n\n    if((A = matrix_complex_alloc(rows+1, columns)) == NULL)\n        return LIBHADES_ERROR_OOM;\n\n    if((b = matrix_complex_zeros(rows+1,1,NULL)) == NULL)\n    {\n        matrix_complex_free(A);\n        return LIBHADES_ERROR_OOM;\n    }\n    matrix_set(b, rows,0, 1);\n\n    for(int j = 0; j < columns; j++)\n    {\n        for(int i = 0; i < rows; i++)\n            matrix_set(A, i, j, matrix_get(M, i,j));\n\n        /* - lambda Id */\n        matrix_set(A, j,j, matrix_get(A,j,j)-lambda);\n\n        /* set nomalization condition */\n        matrix_set(A, rows,j, 1);\n    }\n\n    /* determine work size */\n    lwork = -1;\n    zgels_(&trans, &m, &n, &nrhs, A->M, &lda, b->M, &ldb, &work_size, &lwork, &info);\n    lwork = (int)CREAL(work_size);\n    if((work = malloc_cb(lwork*sizeof(complex_t))) == NULL)\n    {\n        matrix_complex_free(A);\n        matrix_complex_free(vr);\n        return LIBHADES_ERROR_OOM;\n    }\n\n    /* calculate eigenvector */\n    zgels_(\n        &trans, /* find least squares solution of overdetermined system */\n        &m,     /* number of rows of matrix A */\n        &n,     /* number of columns of matrix A */\n        &nrhs,  /* number of columns of matrix B */\n        A->M,   /* matrix A (will be overwritten) */\n        &lda,   /* leading dimension of A, LDA >= max(1,M) */\n        b->M,   /* on entry: right hand side vectors, on exit: solution */\n        &ldb,   /* leading dimension of B, LDB >= MAX(1,M,N) */\n        work,   /* workspace */\n        &lwork, /* dimension of work */\n        &info   /* status */\n    );\n\n    free_cb(work);\n    matrix_complex_free(A);\n\n    for(int i = 0; i < rows; i++)\n        matrix_set(vr, i,0, matrix_get(b, i,0));\n\n    matrix_complex_free(b);\n\n    return info;\n}\n\n/** @}*/\n\n\n\n\n/** \\defgroup exp Calculate matrix exponential\n *  @{\n */\n\n/** macro to calculate matrix norm */\n#define MATRIX_NORM(FUNCTION_NAME, MTYPE, LAPACK_FUNC) \\\nint FUNCTION_NAME(MTYPE *A, char norm_type, double *norm) \\\n{ \\\n    double *work = NULL; \\\n\\\n    if(norm_type == 'I') \\\n    { \\\n        work = malloc_cb(A->rows*sizeof(double)); \\\n        if(work == NULL) \\\n            return LIBHADES_ERROR_OOM; \\\n    } \\\n\\\n    *norm = LAPACK_FUNC(&norm_type, &A->rows, &A->columns, A->M, &A->rows, work); \\\n\\\n    if(work != NULL) \\\n        free_cb(work); \\\n\\\n    return 0; \\\n}\n\n/** @brief Compute matrix norm for real matrix\n *\n * See dlange.\n *\n * Returns\n *      max(abs(A(i,j))), norm_type = 'M' or 'm'\n *      norm1(A),         norm_type = '1', 'O' or 'o'\n *      normI(A),         norm_type = 'I' or 'i'\n *      normF(A),         norm_type = 'F', 'f', 'E' or 'e'\n *\n * @param [in]  A real matrix\n * @param [in]  norm_type type of norm, e.g. 'F' for Frobenius norm\n * @param [out] norm value of norm\n *\n * @retval ret 0 if successfull, <0 otherwise\n */\nMATRIX_NORM(matrix_norm, matrix_t, dlange_);\n\n/** @brief Compute matrix norm for complex matrix\n *\n * See matrix_norm.\n *\n * @param [in]  A complex matrix\n * @param [in]  norm_type type of norm, e.g. 'F' for Frobenius norm\n * @param [out] norm value of norm\n *\n * @retval ret 0 if successfull, <0 otherwise\n */\nMATRIX_NORM(matrix_complex_norm, matrix_complex_t, zlange_);\n\nmatrix_complex_t *matrix_complex_exp_taylor(matrix_complex_t *A, int order)\n{\n    const int rows = A->min;\n    matrix_complex_t *C = matrix_complex_alloc(rows,rows);\n\n    /* B = E+A/order */\n    matrix_complex_t *B = matrix_complex_copy(A,NULL);\n    matrix_complex_mult_scalar(B, 1./order);\n\n    for(int i = 0; i < rows; i++)\n        matrix_set(B, i,i, 1+matrix_get(B,i,i));\n\n    for(int k = order-1; k > 0; k--)\n    {\n        matrix_complex_mult(A, B, 1./order, C);\n\n        /* swap */\n        {\n            matrix_complex_t *temp;\n            temp = C;\n            C = B;\n            B = temp;\n        }\n\n        for(int i = 0; i < rows; i++)\n            matrix_set(B, i,i, 1+matrix_get(B,i,i));\n    }\n\n    matrix_complex_free(C);\n\n    return B;\n}\n\n/** @}*/\n\n\n\n/** \\defgroup LA LU decomposition, inverting\n *  @{\n */\n\n#define LU_DECOMPOSITION(FUNCTION_NAME, MATRIX_TYPE, XGETRF) \\\nint FUNCTION_NAME(MATRIX_TYPE *A, int ipiv[]) \\\n{ \\\n    int info; \\\n\\\n    XGETRF( \\\n        &A->rows,    /* M number of rows of A */ \\\n        &A->columns, /* N number of columns of A */ \\\n        A->M,        /* matrix A to be factored */ \\\n        &A->columns, /* LDA: leading dimension of A */ \\\n        ipiv,        /* pivot indices of dimension (min(M,N)) */ \\\n        &info \\\n    ); \\\n\\\n    return info; \\\n}\n\n/** @brief Compute LU decomposition of real matrix A\n *\n * See dgetrf.\n *\n * The factorization has the form\n *    A = P * L * U\n * where P is a permutation matrix, L is lower triangular with unit\n * diagonal elements (lower trapezoidal if rows > columns), and U is upper\n * triangular (upper trapezoidal if m < n).\n *\n * @param [in,out] A real matrix\n * @param [out] ipiv pivot indices; array of dimension MIN(rows,columns)\n *\n * @retval INFO\n */\nLU_DECOMPOSITION(matrix_lu_decomposition, matrix_t, dgetrf_)\n\n/** @brief Compute LU decomposition of complex matrix A\n *\n * See matrix_lu_decomposition.\n *\n * @param [in,out] A complex matrix\n * @param [out] ipiv pivot indices; array of dimension MIN(rows,columns)\n *\n * @retval INFO\n */\nLU_DECOMPOSITION(matrix_complex_lu_decomposition, matrix_complex_t, zgetrf_)\n\n#define MATRIX_INVERT(FUNCTION_NAME, TYPE, MATRIX_TYPE, LU_DECOMPOSITION, XGETRI) \\\nint FUNCTION_NAME(MATRIX_TYPE *A) \\\n{ \\\n    int info, lwork, dim = A->min; \\\n    int *ipiv = NULL; \\\n    TYPE *work = NULL; \\\n    TYPE workopt; \\\n\\\n    ipiv = malloc_cb(dim*sizeof(int)); \\\n    if(ipiv == NULL) \\\n        return LIBHADES_ERROR_OOM; \\\n\\\n    info = LU_DECOMPOSITION(A, ipiv); \\\n    if(info != 0) \\\n        goto out; \\\n\\\n    lwork = -1; \\\n    XGETRI(&dim, A->M, &dim, ipiv, &workopt, &lwork, &info); \\\n    if(info != 0) \\\n        goto out; \\\n\\\n    lwork = (int)workopt; \\\n    work = malloc_cb(lwork*sizeof(TYPE)); \\\n    if(work == NULL) \\\n    { \\\n        info = LIBHADES_ERROR_OOM; \\\n        goto out; \\\n    } \\\n\\\n    XGETRI( \\\n        &dim,   /* order of matrix A */ \\\n        A->M,   /* factors L and U from LU decomposition */ \\\n        &dim,   /* LDA: leading dimension of A */ \\\n        ipiv,   /* pivot indices */ \\\n        work,   /* workspace of dimension LWORK */ \\\n        &lwork, /* length of work */ \\\n        &info \\\n    ); \\\n\\\nout: \\\n    free_cb(ipiv); \\\n    if(work != NULL) \\\n        free_cb(work); \\\n\\\n    return info; \\\n}\n\n/** @brief Invert real matrix A\n *\n * The inverse of A is computed using the LU factorzation of A\n *\n * @param [in] A real matrix\n *\n * @retval INFO\n */\nMATRIX_INVERT(matrix_invert, double, matrix_t, matrix_lu_decomposition, dgetri_)\n\n/** @brief Invert complex matrix A\n *\n * See matrix_invert.\n *\n * @param [in] A complex matrix\n *\n * @retval INFO\n */\nMATRIX_INVERT(matrix_complex_invert, complex_t, matrix_complex_t, matrix_complex_lu_decomposition, zgetri_)\n\n#define MATRIX_SOLVE(FUNCTION_NAME, MATRIX_TYPE, LU_DECOMPOSITION, XGETRS) \\\nint FUNCTION_NAME(MATRIX_TYPE *A, MATRIX_TYPE *b) \\\n{ \\\n    int N = A->min; \\\n    char trans = 'N'; \\\n    int nrhs = b->columns; \\\n    int info = -1; \\\n    int *ipiv = malloc_cb(N*sizeof(int)); \\\n\\\n    if(ipiv == NULL) \\\n        return LIBHADES_ERROR_OOM; \\\n\\\n    LU_DECOMPOSITION(A, ipiv); \\\n    XGETRS(&trans, &N, &nrhs, A->M, &N, ipiv, b->M, &N, &info); \\\n\\\n    free_cb(ipiv); \\\n\\\n    return info; \\\n}\n\n/** @brief Solve system of linear equations\n *\n * Solve the system of linear equations:\n *      A*x = b\n *\n * @param [in,out] A matrix\n * @param [in,out] b vector/matrix\n *\n * @retval INFO\n */\n\n/** @}*/\nMATRIX_SOLVE(matrix_solve, matrix_t, matrix_lu_decomposition, dgetrs_);\n\n/** @brief Solve system of linear equations\n *\n * Solve the system of complex linear equations:\n *      A*x = b\n *\n * @param [in,out] A complex matrix\n * @param [in,out] b complex vector/matrix\n *\n * @retval INFO\n */\n\n/** @}*/\nMATRIX_SOLVE(matrix_complex_solve, matrix_complex_t, matrix_complex_lu_decomposition, zgetrs_);\n\n/*\nstatic void _cblas_zaxpy(const int N, const double alpha, const void *X, const int incX, void *Y, const int incY)\n{\n    complex_t beta = alpha;\n    cblas_zaxpy(N, &beta, X, incX, Y, incY);\n}\n*/\n\n/** @brief Calculate dot product of vectors x and y\n *\n * Calculate dot product of first column of x,y. If x and y have different\n * rows, the minimum is used.\n *\n * @param [in] x vector\n * @param [in] y vector\n * @retval x*y\n */\ndouble vector_dot(matrix_t *x, matrix_t *y)\n{\n    int incx = 1;\n    int incy = 1;\n    int N = MIN(x->rows, y->rows);\n    \n    return ddot_(&N, x->M, &incx, y->M, &incy);\n}\n\n/** @brief Calculate dot product of vectors x and y\n *\n * Calculate dot product of first column of x,y. If x and y have different\n * rows, the minimum is used.\n *\n * @param [in] x vector\n * @param [in] y vector\n * @retval x*y\n */\ncomplex_t vector_complex_dot(matrix_complex_t *x, matrix_complex_t *y)\n{\n    /*\n    int incx = 1;\n    int incy = 1;\n    int N = MIN(x->rows, y->rows);\n    complex_t z = 0;\n    \n    zdotc_(&z, &N, x->M, &incx, y->M, &incy);\n    return z;\n    */\n\n    int N = MIN(x->rows, y->rows);\n    complex_t z = 0;\n    for(int i = 0; i < N; i++)\n        z += matrix_get(x,i,0)*matrix_get(y,i,0);\n    return z;\n}\n\n#define MATRIX_GET_COLUMN(FUNCTION_NAME, TYPE, MATRIX_TYPE) \\\nMATRIX_TYPE *FUNCTION_NAME(MATRIX_TYPE *A, int i) \\\n{ \\\n    const int rows = A->rows; \\\n    MATRIX_TYPE *v = malloc_cb(sizeof(MATRIX_TYPE)); \\\n    if(v == NULL) \\\n        return NULL; \\\n\\\n    v->rows    = rows; \\\n    v->columns = 1; \\\n    v->min     = 1; \\\n    v->size    = rows; \\\n    v->type    = 0; \\\n    v->view    = 1; \\\n    v->M       = &A->M[i*rows]; \\\n\\\n    return v; \\\n}\n\n/** @brief Get i-th column of matrix A\n *\n * @param [in] A matrix\n * @param [in] i column number\n * @retval x*y\n */\nMATRIX_GET_COLUMN(matrix_get_column,         double,    matrix_t);\n\n/** @brief Get i-th column of matrix A\n *\n * @param [in] A matrix\n * @param [in] i column number\n * @retval x*y\n */\nMATRIX_GET_COLUMN(matrix_complex_get_column, complex_t, matrix_complex_t);\n\n\n/** \\defgroup sparse Functions for sparse matrices\n *  @{\n */\n\n#ifdef SUPPORT_SPARSE\n\n/** @brief Calculate eigenvalues of a sparse complex matrix\n *\n * @param [in] N     number of columns/rows of matrix\n * @param [in] nev   number of eigenvalues to compute\n * @param [in] which LM (largest magnitude), SM (smallest magnitude), LR (largest real part), SR (smallest real part), LI (largest imaginary part), SI (smallest imaginary part)\n * @param [in] Av callback function that implements the matrix-vector operation Av; the input vector is given as in, the vector Av must be written in out\n * @param [in,out] d on exit d contains the Rith approximations (must be of length nev+1)\n * @param [in] mxiter maximum number of Arnoldi update iterations allowed\n * @param [in] tol relative accuracy of the Ritz value\n * @param [in] data pointer that is given to callback function Av\n *\n * @retval 0 if successful\n */\nint sparse_complex_eig(int N, int nev, char *which, void (*Av)(int N, complex_t *in, complex_t *out, void *data), complex_t *d, int mxiter, double tol, void *data)\n{\n    int ret = LIBHADES_ERROR_OOM;\n    int info = 0;\n    int ido = 0;\n    char *bmat = \"I\";          /* standard eigenproblem */\n    int ncv = MIN(2*nev+2, N);\n\n    int ishift = 1;\n    int mode = 1;\n    int iparam[11] = { ishift, 0, mxiter, 1, 0, 0, mode, 0, 0, 0, 0 };\n\n    int ipntr[14];\n    int lworkl = ncv*(3*ncv + 5);\n    int rvec = 0;\n    char *howmny = \"P\";\n\n    complex_t *workd = NULL, *workl = NULL, *resid = NULL, *v = NULL, *workev = NULL;\n    int *select = NULL;\n    double *rwork = NULL;\n\n    /* allocate memory */\n    ret = LIBHADES_ERROR_OOM;\n\n    workd = malloc_cb(3*N*sizeof(complex_t));\n    if(workd == NULL)\n        goto out;\n    workl = malloc_cb(lworkl*sizeof(complex_t));\n    if(workl == NULL)\n        goto out;\n    rwork = malloc_cb(ncv*sizeof(double));\n    if(rwork == NULL)\n        goto out;\n    resid  = malloc_cb(N*sizeof(complex_t));\n    if(resid == NULL)\n        goto out;\n    v = malloc_cb(N*ncv*sizeof(complex_t));\n    if(v == NULL)\n        goto out;\n    select = malloc_cb(ncv*sizeof(int));\n    if(select == NULL)\n        goto out;\n    workev = malloc_cb((2*ncv)*sizeof(complex_t));\n    if(workev == NULL)\n        goto out;\n\n    /* loop */\n    while(1)\n    {\n        /* http://www.caam.rice.edu/software/ARPACK/UG/node138.html */\n        znaupd_(\n            &ido, bmat, &N, which, &nev, &tol, resid, &ncv, v, &N, iparam,\n            ipntr, workd, workl, &lworkl, rwork, &info, strlen(bmat),\n            strlen(which)\n        );\n\n        if(ido == 1 || ido == -1)\n            Av(N, &workd[ipntr[0]-1], &workd[ipntr[1]-1], data);\n        else if(ido == 99)\n            break;\n        else\n        {\n            ret = ido;\n            goto out;\n        }\n    }\n\n    if(info != 0)\n    {\n        ret = info;\n        goto out;\n    }\n\n    /* http://www.mathkeisan.com/usersguide/man/zneupd.html */\n    zneupd_(\n        &rvec, howmny, select, d, NULL, &N, NULL, workev, bmat, &N, which,\n        &nev, &tol, resid, &ncv, v, &N, iparam, ipntr, workd, workl, &lworkl,\n        rwork, &info, strlen(howmny), strlen(bmat), strlen(which)\n    );\n\n    ret = info;\n\nout:\n    if(resid != NULL)\n        free_cb(resid);\n    if(v != NULL)\n        free_cb(v);\n    if(workd != NULL)\n        free_cb(workd);\n    if(workl != NULL)\n        free_cb(workl);\n    if(rwork != NULL)\n        free_cb(rwork);\n    if(select != NULL)\n        free_cb(select);\n    if(workev != NULL)\n        free_cb(workev);\n\n    return ret;\n}\n\n#endif\n/** @}*/\n\n/** \\defgroup io Save/load matrices\n *  @{\n */\n\n#define MATRIX_LOAD_FROM_STREAM(FUNCTION_NAME, MATRIX_TYPE, TYPE, ALLOC, TRANSPOSE, IS_COMPLEX) \\\nMATRIX_TYPE *FUNCTION_NAME(FILE *stream, int *ret) \\\n{ \\\n    MATRIX_TYPE *M; \\\n    uint16_t len; \\\n    int rows, columns, fortran_order, is_complex; \\\n    char header[10] = { 0 }; \\\n    char dict[2048] = { 0 }; \\\n\\\n    if(ret != NULL) \\\n        *ret = 0; \\\n\\\n    /* read magic string, major and minor number */ \\\n    fread(header, 8, 1, stream); \\\n    if(memcmp(header, \"\\x93NUMPY\\x01\\x00\", 8) != 0) \\\n    { \\\n        if(ret != NULL) \\\n            *ret = LIBHADES_ERROR_HEADER; \\\n        return NULL; \\\n    } \\\n\\\n    /* read length of dict */ \\\n    fread(&len, sizeof(uint16_t), 1, stream); \\\n\\\n    if(len >= sizeof(dict)/sizeof(dict[0])) \\\n    { \\\n        if(ret != NULL) \\\n            *ret = LIBHADES_ERROR_INV_LENGTH; \\\n        return NULL; \\\n    } \\\n\\\n    fread(dict, sizeof(char), len, stream); \\\n\\\n    if(npy_dict_get_fortran_order(dict, &fortran_order) != 0) \\\n    { \\\n        if(ret != NULL) \\\n            *ret = LIBHADES_ERROR_ORDER; \\\n        return NULL; \\\n    } \\\n\\\n    if(npy_dict_get_shape(dict, &rows, &columns) != 0) \\\n    { \\\n        if(ret != NULL) \\\n            *ret = LIBHADES_ERROR_SHAPE; \\\n        return NULL; \\\n    } \\\n\\\n    if(npy_dict_get_descr(dict, &is_complex) != 0) \\\n    { \\\n        if(ret != NULL) \\\n            *ret = LIBHADES_ERROR_DESCR; \\\n        return NULL; \\\n    } \\\n\\\n    if(is_complex != IS_COMPLEX) \\\n    { \\\n        if(ret != NULL) \\\n            *ret = LIBHADES_ERROR_FORMAT; \\\n        return NULL; \\\n    } \\\n\\\n    M = ALLOC(rows,columns); \\\n    fread(M->M, sizeof(TYPE), rows*columns, stream); \\\n\\\n    if(!fortran_order) \\\n        TRANSPOSE(M); \\\n\\\n    M->min  = MIN(rows,columns); \\\n    M->size = (size_t)rows*(size_t)columns; \\\n    M->view = 0; \\\n    M->type = 0; \\\n\\\n    return M; \\\n}\n\n/** @brief Load real matrix from stream\n *\n * Load real matrix A from a stream. This function will also allocate memory\n * for the matrix.\n *\n * If error != NULL, error will be set to:\n *  0                         if successful\n *  LIBHADES_ERROR_HEADER     if magic or major/minor number is invalid\n *  LIBHADES_ERROR_INV_LENGTH if length of dictionary is invalid (too long)\n *  LIBHADES_ERROR_ORDER      if order is invalid (Fortran/C order)\n *  LIBHADES_ERROR_SHAPE      if shape is invalid (rows/columns)\n *  LIBHADES_ERROR_DESCR      if dtype is wrong/not supported\n *  LIBHADES_ERROR_FORMAT     if wrong format (real instead of complex)\n *  0 rows/columns wrong\n *\n * @param [in] stream file handle of a opened file\n * @param [out] error error code\n * @retval A matrix\n * @retval NULL if an error occured\n */\nMATRIX_LOAD_FROM_STREAM(matrix_load_from_stream, matrix_t, double, matrix_alloc, matrix_transpose, 0);\n\n/** @brief Load complex matrix from stream\n *\n * Load complex matrix A from a stream. This function will also allocate memory\n * for the matrix.\n *\n * If error != NULL, error will be set to:\n *  0                         if successful\n *  LIBHADES_ERROR_HEADER     if magic or major/minor number is invalid\n *  LIBHADES_ERROR_INV_LENGTH if length of dictionary is invalid (too long)\n *  LIBHADES_ERROR_ORDER      if order is invalid (Fortran/C order)\n *  LIBHADES_ERROR_SHAPE      if shape is invalid (rows/columns)\n *  LIBHADES_ERROR_DESCR      if dtype is wrong/not supported\n *  LIBHADES_ERROR_FORMAT     if wrong format (complex instead of real)\n *  0 rows/columns wrong\n *\n * @param [in] stream file handle of a opened file\n * @param [out] error error code\n * @retval A matrix\n * @retval NULL if an error occured\n */\nMATRIX_LOAD_FROM_STREAM(matrix_complex_load_from_stream, matrix_complex_t, complex_t, matrix_complex_alloc, matrix_complex_transpose, 1);\n\n\n#define MATRIX_LOAD(FUNCTION_NAME, MATRIX_TYPE, LOAD_FUNCTION) \\\nMATRIX_TYPE *FUNCTION_NAME(const char *filename, int *ret) \\\n{ \\\n    FILE *stream; \\\n    MATRIX_TYPE *M; \\\n\\\n    if((stream = fopen(filename, \"r\")) == NULL) \\\n    { \\\n        if(ret != NULL) \\\n            *ret = LIBHADES_ERROR_IO; \\\n        return NULL; \\\n    } \\\n\\\n    M = LOAD_FUNCTION(stream, ret); \\\n\\\n    fclose(stream); \\\n\\\n    return M; \\\n}\n\n/** @brief Load real matrix from file\n *\n * Load real matrix A from file given by filename. This function will also\n * allocate memory for the matrix. See \\ref matrix_load_from_stream for errors.\n *\n * @param [in] filename path to the file\n * @param [out] error error code\n * @retval A matrix\n * @retval NULL if an error occured\n */\nMATRIX_LOAD(matrix_load, matrix_t, matrix_load_from_stream);\n\n/** @brief Load complex matrix from file\n *\n * Load complex matrix A from file given by filename. This function will also\n * allocate memory for the matrix. See \\ref matrix_complex_load_from_stream for\n * errors.\n *\n * @param [in] filename path to the file\n * @param [out] error error code\n * @retval A matrix\n * @retval NULL if an error occured\n */\nMATRIX_LOAD(matrix_complex_load, matrix_complex_t, matrix_complex_load_from_stream);\n\n#define MATRIX_SAVE_TO_STREAM(FUNCTION_NAME, TYPE, MATRIX_TYPE, DTYPE) \\\nvoid FUNCTION_NAME(MATRIX_TYPE *M, FILE *stream) \\\n{ \\\n    char d_str[512] = { 0 }; \\\n    uint16_t len = 0; \\\n    const int rows = M->rows, columns = M->columns; \\\n\\\n    /* write magic string, major number and minor number */ \\\n    fwrite(\"\\x93NUMPY\\x01\\x00\", sizeof(char), 8, stream); \\\n\\\n    /* write length of header and header */ \\\n    snprintf(d_str, sizeof(d_str)/sizeof(d_str[0]), \"{'descr': '%s', 'fortran_order': True, 'shape': (%d, %d), }\", DTYPE, rows, columns); \\\n\\\n    len = strlen(d_str); \\\n\\\n    fwrite(&len,  sizeof(len),  1,   stream); \\\n    fwrite(d_str, sizeof(char), len, stream); \\\n\\\n    /* write matrix */ \\\n    fwrite(M->M, sizeof(TYPE), M->size, stream); \\\n}\n\n/** @brief Save real matrix A to stream\n *\n * Save real matrix A to a file handle given by stream. The datatype\n * corresponds to Numpy's npy file format.\n *\n * @param [in] A      matrix to be dumped to file\n * @param [in] stream file handle of opened file\n */\nMATRIX_SAVE_TO_STREAM(matrix_save_to_stream, double, matrix_t, \"<f8\");\n\n/** @brief Save complex matrix A to stream\n *\n * Save complex matrix A to a file handle given by stream. The datatype\n * corresponds to Numpy's npy file format.\n *\n * @param [in] A      matrix to be dumped to file\n * @param [in] stream file handle of opened file\n */\nMATRIX_SAVE_TO_STREAM(matrix_complex_save_to_stream, complex_t, matrix_complex_t, \"<c16\");\n\n\n#define MATRIX_SAVE(FUNCTION_NAME, MATRIX_TYPE, SAVE_FUNCTION) \\\nint FUNCTION_NAME(MATRIX_TYPE *M, const char *filename) \\\n{ \\\n    FILE *stream = fopen(filename, \"w\"); \\\n    if(stream == NULL) \\\n        return LIBHADES_ERROR_IO; \\\n\\\n    SAVE_FUNCTION(M, stream); \\\n\\\n    fclose(stream); \\\n\\\n    return 0; \\\n};\n\n/** @brief Save real matrix A to file\n *\n * Save real matrix A to file given by filename. The datatype corresponds to\n * Numpy's .npy file format.\n *\n * @param [in] A        matrix to be dumped to file\n * @param [in] filename path to the file\n * @retval 0 if successful\n * @retval LIBHADES_ERROR_IO if file could not be opened\n */\nMATRIX_SAVE(matrix_save, matrix_t, matrix_save_to_stream);\n\n/** @brief Save complex matrix A to file\n *\n * Save complex matrix A to file given by filename. The datatype corresponds to\n * Numpy's .npy file format.\n *\n * @param [in] A        matrix to be dumped to file\n * @param [in] filename path to the file\n * @retval 0 if successful\n * @retval LIBHADES_ERROR_IO if file could not be opened\n */\nMATRIX_SAVE(matrix_complex_save, matrix_complex_t, matrix_complex_save_to_stream);\n\n/** @}*/\n", "meta": {"hexsha": "7edbdeb1e6e70c973bd216748aaa683438aab435", "size": 52569, "ext": "c", "lang": "C", "max_stars_repo_path": "src/libhades.c", "max_stars_repo_name": "michael-hartmann/libhades", "max_stars_repo_head_hexsha": "81a2ab18dbf59975f8fbae0693a757b054b4501c", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-11-03T15:07:53.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-28T20:09:32.000Z", "max_issues_repo_path": "src/libhades.c", "max_issues_repo_name": "michael-hartmann/libhades", "max_issues_repo_head_hexsha": "81a2ab18dbf59975f8fbae0693a757b054b4501c", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libhades.c", "max_forks_repo_name": "michael-hartmann/libhades", "max_forks_repo_head_hexsha": "81a2ab18dbf59975f8fbae0693a757b054b4501c", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3503759398, "max_line_length": 176, "alphanum_fraction": 0.6059084251, "num_tokens": 15193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3073580041760868, "lm_q2_score": 0.05500528442066434, "lm_q1q2_score": 0.01690631443867339}}
{"text": "#ifndef TTT_BOARD_H\n#define TTT_BOARD_H\n\n#include <SDL_rect.h>\n\n#include <gsl/util>\n\n#include <array>\n#include <optional>\n\nnamespace ttt\n{\n\tclass Game;\n\n\tenum class CellState\n\t{\n\t\tempty, x, o\n\t};\n\n\tclass Board final\n\t{\n\tpublic:\n\t\tSDL_FPoint pos;\n\t\tSDL_FPoint cellSize;\n\t\tstatic constexpr int size{3};\n\n\t\tCellState preview{CellState::empty};\n\t\tSDL_Point previewCell{};\n\n\t\tBoard(const SDL_FPoint &pos, const SDL_FPoint &cellSize, const Game &game) noexcept;\n\n\t\tvoid update() noexcept;\n\t\tvoid render() const noexcept;\n\n\t\t[[nodiscard]] CellState getCellState(const SDL_Point &pos) const noexcept;\n\t\tvoid setCellState(const SDL_Point &pos, CellState state) noexcept;\n\t\tvoid clear() noexcept;\n\n\t\t[[nodiscard]] std::optional<SDL_Point> getCell(const SDL_Point &point) const noexcept;\n\t\t[[nodiscard]] bool isEmpty() const noexcept;\n\n\tprivate:\n\t\tconst Game &game;\n\t\tstd::array<CellState, 9> grid{};\n\n\t\tstatic constexpr float lineWidth{16.0f};\n\t\tfloat previewOffset{0.0f};\n\t\tbool shrinkPreview{false};\n\n\t\tconst SDL_Rect lineSrc{0, 0, 8, 576};\n\t\tconst SDL_Rect xSrc{8, 0, 48, 48};\n\t\tconst SDL_Rect oSrc{8, 48, 48, 48};\n\t};\n\n\tinline CellState Board::getCellState(const SDL_Point &pos) const noexcept\n\t{\n\t\treturn gsl::at(grid, pos.x + pos.y * size);\n\t}\n\n\tinline void Board::setCellState(const SDL_Point &pos, CellState state) noexcept \n\t{\n\t\tgsl::at(grid, pos.x + pos.y * size) = state;\n\t}\n}\n\n#endif", "meta": {"hexsha": "6de0dd317a3f7677d6d10e59b0022ff37fa424e5", "size": 1385, "ext": "h", "lang": "C", "max_stars_repo_path": "Source/Board.h", "max_stars_repo_name": "itsArtem/TicTacToe", "max_stars_repo_head_hexsha": "8c70a77e4603dd0ff22ec0621b978ec0685ec3cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Source/Board.h", "max_issues_repo_name": "itsArtem/TicTacToe", "max_issues_repo_head_hexsha": "8c70a77e4603dd0ff22ec0621b978ec0685ec3cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/Board.h", "max_forks_repo_name": "itsArtem/TicTacToe", "max_forks_repo_head_hexsha": "8c70a77e4603dd0ff22ec0621b978ec0685ec3cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.9848484848, "max_line_length": 88, "alphanum_fraction": 0.7075812274, "num_tokens": 401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632159254749036, "lm_q2_score": 0.03963884122816307, "lm_q1q2_score": 0.0168988939191276}}
{"text": "/* multilarge_nlinear/dummy.c\n * \n * Copyright (C) 2016 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* dummy linear solver */\n\n#include <config.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_multilarge_nlinear.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_permutation.h>\n\nstatic void *dummy_alloc (const size_t n, const size_t p);\nstatic int dummy_init(const void * vtrust_state, void * vstate);\nstatic int dummy_presolve(const double mu, const void * vtrust_state, void * vstate);\nstatic int dummy_solve(const gsl_vector * g, gsl_vector *x,\n                       const  void * vtrust_state, void *vstate);\nstatic int dummy_rcond(double * rcond, const gsl_matrix * JTJ, void * vstate);\nstatic int dummy_covar(const gsl_matrix * JTJ, gsl_matrix * covar, void * vstate);\n\nstatic void *\ndummy_alloc (const size_t n, const size_t p)\n{\n  (void) n;\n  (void) p;\n  return NULL;\n}\n\nstatic void\ndummy_free(void *vstate)\n{\n  (void) vstate;\n}\n\nstatic int\ndummy_init(const void * vtrust_state, void * vstate)\n{\n  (void) vtrust_state;\n  (void) vstate;\n  return GSL_SUCCESS;\n}\n\nstatic int\ndummy_presolve(const double mu, const void * vtrust_state, void * vstate)\n{\n  (void) mu;\n  (void) vtrust_state;\n  (void) vstate;\n  return GSL_SUCCESS;\n}\n\nstatic int\ndummy_solve(const gsl_vector * g, gsl_vector *x,\n            const void * vtrust_state, void *vstate)\n{\n  (void) g;\n  (void) x;\n  (void) vtrust_state;\n  (void) vstate;\n  return GSL_SUCCESS;\n}\n\nstatic int\ndummy_rcond(double * rcond, const gsl_matrix * JTJ, void * vstate)\n{\n  (void) vstate;\n  (void) rcond;\n  (void) JTJ;\n  *rcond = 0.0;\n  return GSL_SUCCESS;\n}\n\nstatic int\ndummy_covar(const gsl_matrix * JTJ, gsl_matrix * covar, void * vstate)\n{\n  (void) vstate;\n  (void) JTJ;\n  gsl_matrix_set_zero(covar);\n  return GSL_SUCCESS;\n}\n\nstatic const gsl_multilarge_nlinear_solver dummy_type =\n{\n  \"dummy\",\n  dummy_alloc,\n  dummy_init,\n  dummy_presolve,\n  dummy_solve,\n  dummy_rcond,\n  dummy_covar,\n  dummy_free\n};\n\nconst gsl_multilarge_nlinear_solver *gsl_multilarge_nlinear_solver_none = &dummy_type;\n", "meta": {"hexsha": "fb9ba844171d349544570dec066a42d35592e50b", "size": 2847, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/multilarge_nlinear/dummy.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multilarge_nlinear/dummy.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multilarge_nlinear/dummy.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 24.9736842105, "max_line_length": 86, "alphanum_fraction": 0.7207586934, "num_tokens": 799, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782349911420193, "lm_q2_score": 0.038466195876321656, "lm_q1q2_score": 0.016841404476183434}}
{"text": "#ifndef CWANNIER_PARSESCF_H\n#define CWANNIER_PARSESCF_H\n\n#include <stdbool.h>\n#include <stdio.h>\n#include <gsl/gsl_matrix.h>\n#include \"bstrlib/bstrlib.h\"\n\n#define CWANNIER_PARSESCF_OK 0\n#define CWANNIER_PARSESCF_ERR 1\n\nint ParseSCF(char *filePath, double *num_electrons, double *alat, gsl_matrix *R);\n\nvoid get_b_row(gsl_matrix *R, int row, bstring line);\n\n#endif // CWANNIER_PARSESCF_H\n", "meta": {"hexsha": "0b984561c9a19dec38aecc7396b5b3f199ccbd8a", "size": 387, "ext": "h", "lang": "C", "max_stars_repo_path": "ParseSCF.h", "max_stars_repo_name": "tflovorn/cwannier", "max_stars_repo_head_hexsha": "96b9719b098d3e2e7d6f4fa5b2c938aa460c5fb8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ParseSCF.h", "max_issues_repo_name": "tflovorn/cwannier", "max_issues_repo_head_hexsha": "96b9719b098d3e2e7d6f4fa5b2c938aa460c5fb8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ParseSCF.h", "max_forks_repo_name": "tflovorn/cwannier", "max_forks_repo_head_hexsha": "96b9719b098d3e2e7d6f4fa5b2c938aa460c5fb8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.7647058824, "max_line_length": 81, "alphanum_fraction": 0.7855297158, "num_tokens": 121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.036769466867240946, "lm_q1q2_score": 0.016808673363187875}}
{"text": "/* ****************************************************************** **\n**    OpenSees - Open System for Earthquake Engineering Simulation    **\n**          Pacific Earthquake Engineering Research Center            **\n**                                                                    **\n**                                                                    **\n** (C) Copyright 1999, The Regents of the University of California    **\n** All Rights Reserved.                                               **\n**                                                                    **\n** Commercial use of this program without express permission of the   **\n** University of California, Berkeley, is strictly prohibited.  See   **\n** file 'COPYRIGHT'  in main directory for information on usage and   **\n** redistribution,  and for a DISCLAIMER OF ALL WARRANTIES.           **\n**                                                                    **\n** Developed by:                                                      **\n**   Frank McKenna (fmckenna@ce.berkeley.edu)                         **\n**   Gregory L. Fenves (fenves@ce.berkeley.edu)                       **\n**   Filip C. Filippou (filippou@ce.berkeley.edu)                     **\n**                                                                    **\n** ****************************************************************** */\n                                                                        \n// $Revision: 1.1.1.1 $\n// $Date: 2000-09-15 08:23:29 $\n// $Source: /usr/local/cvs/OpenSees/SRC/system_of_eqn/linearSOE/petsc/ActorPetscSOE.h,v $\n                                                                        \n                                                                        \n// File: ~/system_of_eqn/linearSOE/petsc/ActorPetscSOE.h\n//\n// Written: fmk & om\n// Created: 7/98\n// Revision: A\n//\n// Description: This file contains the class definition for ActorPetscSOE\n// ActorPetscSOE is a subclass of LinearSOE. It uses the LAPACK storage\n// scheme to store the components of the A matrix, which is a full matrix.\n\n\n// What: \"@(#) ActorPetscSOE.h, revA\"\n\n#ifndef ActorPetscSOE_h\n#define ActorPetscSOE_h\n\n#include <LinearSOE.h>\n#include <Vector.h>\n\n// extern \"C\" {\n#include <petsc.h>\n// }\n\nclass PetscSolver;\nclass PetscSOE;\n\nclass ActorPetscSOE\n{\n  public:\n    ActorPetscSOE(PetscSolver &theSolver, int blockSize);     \n    \n    ~ActorPetscSOE();\n    int run(void);\n    \n  protected:\n    \n  private:\n    MPI_Comm theComm;\n    PetscSOE *theSOE;  // the local portion of the SOE\n    PetscSolver *theSolver; // created locally via data from process 0\n    int myRank;\t\t\t\t \n    int recvData[3];\t\t\t\t \n    void *recvBuffer;\n    int numProcessors;\n};\n\n\n#endif\n\n\n\n", "meta": {"hexsha": "afd80353db3d4510747670edec49ed1f5729e082", "size": 2730, "ext": "h", "lang": "C", "max_stars_repo_path": "OpenSees/SRC/system_of_eqn/linearSOE/petsc/ActorPetscSOE.h", "max_stars_repo_name": "kuanshi/ductile-fracture", "max_stars_repo_head_hexsha": "ccb350564df54f5c5ec3a079100effe261b46650", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-03-05T16:25:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-17T14:12:03.000Z", "max_issues_repo_path": "SRC/system_of_eqn/linearSOE/petsc/ActorPetscSOE.h", "max_issues_repo_name": "steva44/OpenSees", "max_issues_repo_head_hexsha": "417c3be117992a108c6bbbcf5c9b63806b9362ab", "max_issues_repo_licenses": ["TCL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SRC/system_of_eqn/linearSOE/petsc/ActorPetscSOE.h", "max_forks_repo_name": "steva44/OpenSees", "max_forks_repo_head_hexsha": "417c3be117992a108c6bbbcf5c9b63806b9362ab", "max_forks_repo_licenses": ["TCL"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-09-21T03:11:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-19T07:29:37.000Z", "avg_line_length": 35.4545454545, "max_line_length": 89, "alphanum_fraction": 0.4553113553, "num_tokens": 557, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.04336579397302949, "lm_q1q2_score": 0.01669202075540722}}
{"text": "/*\n * \n * \n * \n */\n\n#include <inttypes.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <assert.h>\n#include <cblas.h>\n#include <string.h> // memcpy\n#include <math.h>\n#include <stdarg.h>\n\n#include \"cgraph.h\"\n#include \"cg_operation.h\"\n#include \"cg_types.h\"\n#include \"cg_variables.h\"\n#include \"cg_errors.h\"\n#include \"cg_constants.h\"\n#include \"cg_enums.h\"\n#include \"cg_factory.h\"\n#include \"cg_math.h\"\n#include \"cg_ops.h\"\n\n\nvoid cg_assert(int cond, const char * rawcond, const char * fmt, ...)\n{\n\tif(cond)\n\t\treturn;\n\n\tchar temp[1024];\n\tva_list vl;\n\tva_start(vl, fmt);\n\tvsprintf(temp, fmt, vl);\n\tva_end(vl);\n\tfprintf(stdout, \"Fatal error, assertion failed: %s\\n\", rawcond);\n\tfprintf(stdout, temp);\n\tfprintf(stdout, \"\\n\");\n\n\texit(-1);\n}\n\n\n#define CHECK_RESULT(node) \\\nif(node->error != NULL){\\\n\treturn node;\\\n}\n\n/*\n * Works only with constant types\n */\nCGNode* copyNode(CGNode* node){\n\tCGNode* n = calloc(1, sizeof(CGNode));\n\tif(node->type != CGNT_CONSTANT){\n\t\tfprintf(stderr, \"Call to copyNode with a non-constant node.\\n... This should not happen, but who knows these days.\\n\");\n\t\tfprintf(stderr, \"copy node with nodetype = %d\\n\", node->type);\n\t\texit(-1);\n\t}\n\t\n\tn->type = CGNT_CONSTANT;\n\tn->constant = calloc(1, sizeof(CGPConstant));\n\tn->constant->type = node->constant->type;\n\tn->result = NULL;\n\tn->diff = NULL;\n\t\n\tswitch(node->constant->type){\n\t\tcase CGVT_DOUBLE: {\n\t\t\tCGDouble* d = calloc(1, sizeof(CGDouble));\n\t\t\td->value = ((CGDouble*)node->constant->value)->value;\n\t\t\t\n\t\t\tn->constant->value = d;\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\tcase CGVT_VECTOR: {\n\t\t\tCGVector* V = calloc(1, sizeof(CGVector));\n\t\t\tCGVector* src = (CGVector*)node->constant->value;\n\t\t\t\n\t\t\tV->len = src->len;\n\t\t\tif(src->data != NULL) {\n\t\t\t\tV->data = calloc(V->len, sizeof(cg_float));\n\t\t\t\tmemcpy(V->data, src->data, V->len * sizeof(cg_float));\n\t\t\t}\n\n#ifdef CG_USE_OPENCL\n\t        V->buf = NULL;\n\t        V->loc = CG_DATALOC_HOST_MEM;\n#endif\n\t\t\tn->constant->value = V;\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\tcase CGVT_MATRIX: {\n\t\t\tCGMatrix* M = calloc(1, sizeof(CGMatrix));\n\t\t\tCGMatrix* src = (CGMatrix*)node->constant->value;\n\t\t\t\n\t\t\tuint64_t size = src->cols * src->rows;\n\t\t\t\n\t\t\tM->rows = src->rows;\n\t\t\tM->cols = src->cols;\n\n\t\t\tif(src->data != NULL) {\n\t\t\t\tM->data = calloc(size, sizeof(cg_float));\n\t\t\t\tmemcpy(M->data, src->data, size*sizeof(cg_float));\n\t\t\t}\n\n#ifdef CG_USE_OPENCL\n\t\t\tM->buf = NULL;\n\t\t\tM->loc = CG_DATALOC_HOST_MEM;\n#endif\n\t\t\tn->constant->value = M;\n\t\t\tbreak;\n\t\t}\n\t}\n\t\n\treturn n;\n}\n\n// @Deprecated @NotUsed\nvoid* copyNodeValue(CGNode* node){\n\tif(node->type != CGNT_CONSTANT){\n\t\tfprintf(stderr, \"Call to copyNodeValue with a non-constant node.\\n... This should not happen, but who knows these days.\");\n\t\texit(-1);\n\t}\n\t\n\tswitch(node->constant->type){\n\t\tcase CGVT_DOUBLE: {\n\t\t\tCGDouble* d = calloc(1, sizeof(CGDouble));\n\t\t\td->value = ((CGDouble*)node->constant->value)->value;\n\t\t\t\n\t\t\treturn d;\n\t\t}\n\t\t\n\t\tcase CGVT_VECTOR: {\n\t\t\tCGVector* V = calloc(1, sizeof(CGVector));\n\t\t\tCGVector* src = (CGVector*)node->constant->value;\n\t\t\t\n\t\t\tV->len = src->len;\n\t\t\tV->data = calloc(V->len, sizeof(cg_float));\n\t\t\t\n\t\t\tmemcpy(V->data, src->data, V->len*sizeof(cg_float));\n\t\t\treturn V;\n\t\t}\n\t\t\n\t\tcase CGVT_MATRIX: {\n\t\t\tCGMatrix* M = calloc(1, sizeof(CGMatrix));\n\t\t\tCGMatrix* src = (CGMatrix*)node->constant->value;\n\t\t\t\n\t\t\tuint64_t size = src->cols * src->rows;\n\t\t\t\n\t\t\tM->rows = src->rows;\n\t\t\tM->cols = src->cols;\n\t\t\tM->data = calloc(size, sizeof(cg_float));\n\t\t\t\n\t\t\tmemcpy(M->data, src->data, size*sizeof(cg_float));\n\t\t\treturn M;\n\t\t}\n\t}\n}\n\n/*\n * @Deprecated\n */\nvoid* copyRNodeValue(CGResultNode* node){\n\tswitch(node->type){\n\t\tcase CGVT_DOUBLE: {\n\t\t\tCGDouble* d = calloc(1, sizeof(CGDouble));\n\t\t\td->value = ((CGDouble*)node->value)->value;\n\t\t\t\n\t\t\treturn d;\n\t\t}\n\t\t\n\t\tcase CGVT_VECTOR: {\n\t\t\tCGVector* V = calloc(1, sizeof(CGVector));\n\t\t\tCGVector* src = (CGVector*)node->value;\n\t\t\t\n\t\t\tV->len = src->len;\n\t\t\tV->data = calloc(V->len, sizeof(cg_float));\n\t\t\t\n\t\t\tmemcpy(V->data, src->data, V->len*sizeof(cg_float));\n\t\t\treturn V;\n\t\t}\n\t\t\n\t\tcase CGVT_MATRIX: {\n\t\t\tCGMatrix* M = calloc(1, sizeof(CGMatrix));\n\t\t\tCGMatrix* src = (CGMatrix*)node->value;\n\t\t\t\n\t\t\tuint64_t size = src->cols * src->rows;\n\t\t\t\n\t\t\tM->rows = src->rows;\n\t\t\tM->cols = src->cols;\n\t\t\tM->data = calloc(size, sizeof(cg_float));\n\t\t\t\n\t\t\tmemcpy(M->data, src->data, size*sizeof(cg_float));\n\t\t\treturn M;\n\t\t}\n\t}\n}\n\n\nCGResultNode* copyResultNode(CGResultNode* node){\n\tCGResultNode* res = calloc(1, sizeof(CGResultNode));\n\t\n\tswitch(node->type){\n\t\tcase CGVT_DOUBLE: {\n\t\t\tCGDouble* d = calloc(1, sizeof(CGDouble));\n\t\t\tCGDouble* d2 = (CGDouble*)node->value;\n\t\t\td->value = d2->value;\n\t\t\t\n\t\t\tres->value = d;\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\tcase CGVT_VECTOR: {\n\t\t\tCGVector* V = calloc(1, sizeof(CGVector));\n\t\t\tCGVector* src = (CGVector*)node->value;\n\t\t\t\n\t\t\tV->len = src->len;\n\t\t\tV->data = calloc(V->len, sizeof(cg_float));\n\n#ifdef CG_USE_OPENCL\n\t\t\tV->buf = src->buf;\n#endif\n\t\t\tmemcpy(V->data, src->data, V->len*sizeof(cg_float));\n\t\t\t\n\t\t\tres->value = V;\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\tcase CGVT_MATRIX: {\n\t\t\tCGMatrix* M = calloc(1, sizeof(CGMatrix));\n\t\t\tCGMatrix* src = (CGMatrix*)node->value;\n\t\t\t\n\t\t\tuint64_t size = src->cols * src->rows;\n\t\t\t\n\t\t\tM->rows = src->rows;\n\t\t\tM->cols = src->cols;\n\t\t\tM->data = calloc(size, sizeof(cg_float));\n#ifdef CG_USE_OPENCL\n            M->buf = src->buf;\n#endif\n\t\t\t\n\t\t\tmemcpy(M->data, src->data, size*sizeof(cg_float));\n\t\t\t\n\t\t\tres->value = M;\n\t\t\tbreak;\n\t\t}\n\t}\n\tres->type = node->type;\n\t\n\treturn res;\n}\n\nCGMatrix* vectorToMatrix(CGVector* v){\n\tCGMatrix* m = calloc(1, sizeof(CGMatrix));\n\tm->rows = v->len;\n\tm->cols = 1;\n\tm->data = v->data;\n\t\n\treturn m;\n}\n\n\n/*\n * Computational Graph traversing\n */\n\nCGResultNode* processUnaryOperation(CGraph* graph, CGUnaryOperationType type, CGNode* uhs, CGNode* parentNode){\n\tCGVarType uhsType = CGVT_DOUBLE;\n\tvoid* uhsValue = NULL;\n\tCGResultNode* newres = NULL;\n\t\n\tCGResultNode* lhsResult = computeCGNode(graph, uhs);\n\tCHECK_RESULT(lhsResult)\n\tuhsType = lhsResult->type;\n\tuhsValue = lhsResult->value;\n\t\n\tswitch(type){\n\t\tcase CGUOT_EXP:{\n\t\t\tif(uhsType == CGVT_DOUBLE){\n\t\t\t\tnewres = expD((CGDouble*)uhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif(uhsType == CGVT_VECTOR){\n\t\t\t\tnewres = expV((CGVector*)uhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif(uhsType == CGVT_MATRIX){\n\t\t\t\tnewres = expM((CGMatrix*)uhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\tcase CGUOT_LOG:{\n\t\t\tif(uhsType == CGVT_DOUBLE){\n\t\t\t\tnewres = logD((CGDouble*)uhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif(uhsType == CGVT_VECTOR){\n\t\t\t\tnewres = logV((CGVector*)uhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif(uhsType == CGVT_MATRIX){\n\t\t\t\tnewres = logM((CGMatrix*)uhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\n\t\tcase CGUOT_MINUS:{\n\t\t\tif(uhsType == CGVT_DOUBLE){\n\t\t\t\tCGDouble* rhs = calloc(1, sizeof(CGDouble));\n\t\t\t\trhs->value = -1;\n\t\t\t\t\n\t\t\t\tCGResultNode* res = mulDD((CGDouble*)uhsValue, rhs, graph, parentNode);\n\t\t\t\t\n\t\t\t\tfreeDoubleValue(rhs);\n\t\t\t\t\n\t\t\t\tparentNode->result = res;\n\t\t\t\treturn res;\n\t\t\t}\n\t\t\t\n\t\t\tif(uhsType == CGVT_VECTOR){\n\t\t\t\tCGDouble* lhs = calloc(1, sizeof(CGDouble));\n\t\t\t\tlhs->value = -1;\n\t\t\t\t\n\t\t\t\tCGResultNode* res = mulDV(lhs, (CGVector*)uhsValue, graph, parentNode);\n\t\t\t\n\t\t\t\tfree(lhs);\n\t\t\t\tparentNode->result = res;\n\t\t\t\treturn res;\n\t\t\t}\n\t\t\t\n\t\t\tif(uhsType == CGVT_MATRIX){\n\t\t\t\tCGDouble* lhs = calloc(1, sizeof(CGDouble));\n\t\t\t\tlhs->value = -1;\n\t\t\t\tCGResultNode* res = mulDM(lhs, (CGMatrix*)uhsValue, graph, parentNode);\n\t\t\t\t\n\t\t\t\tfree(lhs);\n\t\t\t\t\n\t\t\t\tparentNode->result = res;\n\t\t\t\treturn res;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\tcase CGUOT_SIN:{\n\t\t\tif(uhsType == CGVT_DOUBLE){\n\t\t\t\tnewres = sinD((CGDouble*)uhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif(uhsType == CGVT_VECTOR){\n\t\t\t\tnewres = sinV((CGVector*)uhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif(uhsType == CGVT_MATRIX){\n\t\t\t\tnewres = sinM((CGMatrix*)uhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\tcase CGUOT_COS:{\n\t\t\tif(uhsType == CGVT_DOUBLE){\n\t\t\t\tnewres = cosD((CGDouble*)uhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif(uhsType == CGVT_VECTOR){\n\t\t\t\tnewres = cosV((CGVector*)uhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif(uhsType == CGVT_MATRIX){\n\t\t\t\tnewres = cosM((CGMatrix*)uhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\tcase CGUOT_TAN:{\n\t\t\tif(uhsType == CGVT_DOUBLE){\n\t\t\t\tnewres = tanD((CGDouble*)uhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif(uhsType == CGVT_VECTOR){\n\t\t\t\tnewres = tanV((CGVector*)uhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif(uhsType == CGVT_MATRIX){\n\t\t\t\tnewres = tanM((CGMatrix*)uhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\tcase CGUOT_TANH:{\n\t\t\tif(uhsType == CGVT_DOUBLE){\n\t\t\t\tnewres = tanhD((CGDouble*)uhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif(uhsType == CGVT_VECTOR){\n\t\t\t\tnewres = tanhV((CGVector*)uhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif(uhsType == CGVT_MATRIX){\n\t\t\t\tnewres = tanhM((CGMatrix*)uhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\tcase CGUOT_INV:{\n\t\t\tchar msg[MAX_ERR_FMT_LEN];\n\t\t\tsnprintf(msg, MAX_ERR_FMT_LEN, \"Operation `%s` is not implemented/supported\", getUnaryOperationTypeString(type));\n\t\t\tnewres = returnResultError(graph, CGET_OPERATION_NOT_IMPLEMENTED, parentNode, msg);\n\t\t}\n\t\t\t\n\t\tcase CGUOT_TRANSPOSE:{\n\t\t\t\n\t\t\tif(uhsType == CGVT_DOUBLE){\n\t\t\t\tnewres = transposeD((CGDouble*)uhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif(uhsType == CGVT_VECTOR){\n\t\t\t\tnewres = transposeV((CGVector*)uhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\tif(uhsType == CGVT_MATRIX){\n\t\t\t\tnewres = transposeM((CGMatrix*)uhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tbreak;\n\t\t}\n\t\n\t\tcase CGUOT_RELU:{\n\t\t\tif(uhsType == CGVT_DOUBLE){\n\t\t\t\tnewres = reluD((CGDouble*)uhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\n\t\t\tif(uhsType == CGVT_VECTOR){\n\t\t\t\tnewres = reluV((CGVector*)uhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\n\n\t\t\tif(uhsType == CGVT_MATRIX){\n\t\t\t\tnewres = reluM((CGMatrix*)uhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n\n        case CGUOT_SOFTPLUS:{\n\t\t\tif(uhsType == CGVT_DOUBLE){\n\t\t\t\tnewres = softplusD((CGDouble*)uhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\n\t\t\tif(uhsType == CGVT_VECTOR){\n\t\t\t\tnewres = softplusV((CGVector*)uhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\n\n\t\t\tif(uhsType == CGVT_MATRIX){\n\t\t\t\tnewres = softplusM((CGMatrix*)uhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\n\t\t\tbreak;\n        }\n\t}\n\tchar msg[MAX_ERR_FMT_LEN];\n\tsnprintf(msg, MAX_ERR_FMT_LEN, \"Operation [%s %s] cannot be applied\", getVariableTypeString(uhsType), getUnaryOperationTypeString(type));\n\tnewres = returnResultError(graph, CGET_INCOMPATIBLE_ARGS_EXCEPTION, parentNode, msg);\n\treturn newres;\n}\n\nCGResultNode* processBinaryOperation(CGraph* graph, CGBinaryOperationType type, CGNode* lhs, CGNode* rhs, CGNode* parentNode){\n\tCGVarType lhsType = CGVT_DOUBLE;\n\tCGVarType rhsType = CGVT_DOUBLE;\n\tCGResultNode* newres = NULL;\n\tvoid* lhsValue = NULL;\n\tvoid* rhsValue = NULL;\n\t\n\tCGResultNode* lhsResult = computeCGNode(graph, lhs);\n\tCHECK_RESULT(lhsResult)\n\tlhsType = lhsResult->type;\n\tlhsValue = lhsResult->value;\n\t\t\n\tCGResultNode* rhsResult = computeCGNode(graph, rhs);\n\tCHECK_RESULT(rhsResult)\n\trhsType = rhsResult->type;\n\trhsValue = rhsResult->value;\n\t\n\tswitch(type){\n\t\tcase CGBOT_ADD:{\n\t\t\tif((lhsType == CGVT_DOUBLE) && (rhsType == CGVT_DOUBLE)){\n\t\t\t\tnewres = addDD((CGDouble*)lhsValue, (CGDouble*)rhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif((lhsType == CGVT_VECTOR) && (rhsType == CGVT_DOUBLE)){\n\t\t\t\tnewres = addVD((CGVector*)lhsValue, (CGDouble*)rhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\tif((lhsType == CGVT_DOUBLE) && (rhsType == CGVT_VECTOR)){\n\t\t\t\tnewres = addVD((CGVector*)rhsValue, (CGDouble*)lhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif((lhsType == CGVT_MATRIX) && (rhsType == CGVT_DOUBLE)){\n\t\t\t\tnewres = addMD((CGMatrix*)lhsValue, (CGDouble*)rhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif((lhsType == CGVT_DOUBLE) && (rhsType == CGVT_MATRIX)){\n\t\t\t\tnewres = addMD((CGMatrix*)rhsValue, (CGDouble*)lhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif((lhsType == CGVT_VECTOR) && (rhsType == CGVT_VECTOR)){\n\t\t\t\tnewres = addVV((CGVector*)lhsValue, (CGVector*)rhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif((lhsType == CGVT_MATRIX) && (rhsType == CGVT_VECTOR)){\n\t\t\t\tnewres = addMV((CGMatrix*)lhsValue, (CGVector*)rhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif((lhsType == CGVT_VECTOR) && (rhsType == CGVT_MATRIX)){\n\t\t\t\tnewres = addMV((CGMatrix*)rhsValue, (CGVector*)lhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif((lhsType == CGVT_MATRIX) && (rhsType == CGVT_MATRIX)){\n\t\t\t\tnewres = addMM((CGMatrix*)lhsValue, (CGMatrix*)rhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\tcase CGBOT_SUB:{\n\t\t\tif((lhsType == CGVT_DOUBLE) && (rhsType == CGVT_DOUBLE)){\n\t\t\t\tnewres = subDD((CGDouble*)lhsValue, (CGDouble*)rhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif((lhsType == CGVT_VECTOR) && (rhsType == CGVT_DOUBLE)){\n\t\t\t\tnewres = subVD((CGVector*)lhsValue, (CGDouble*)rhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif((lhsType == CGVT_DOUBLE) && (rhsType == CGVT_VECTOR)){\n\t\t\t\tnewres = subDV((CGDouble*)lhsValue, (CGVector*)rhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif((lhsType == CGVT_MATRIX) && (rhsType == CGVT_DOUBLE)){\n\t\t\t\tnewres = subMD((CGMatrix*)lhsValue, (CGDouble*)rhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif((lhsType == CGVT_DOUBLE) && (rhsType == CGVT_MATRIX)){\n\t\t\t\tnewres = subDM((CGDouble*)lhsValue, (CGMatrix*)rhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif((lhsType == CGVT_VECTOR) && (rhsType == CGVT_VECTOR)){\n\t\t\t\tnewres = subVV((CGVector*)lhsValue, (CGVector*)rhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif((lhsType == CGVT_MATRIX) && (rhsType == CGVT_MATRIX)){\n\t\t\t\tnewres = subMM((CGMatrix*)lhsValue, (CGMatrix*)rhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif((lhsType == CGVT_MATRIX) && (rhsType == CGVT_VECTOR)){\n\t\t\t\tnewres = subMV((CGMatrix*)lhsValue, (CGVector*)rhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif((lhsType == CGVT_VECTOR) && (rhsType == CGVT_MATRIX)){\n\t\t\t\tnewres = subVM((CGVector*)lhsValue, (CGMatrix*)rhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\tcase CGBOT_DIV:{\n\t\t\tif((lhsType == CGVT_DOUBLE) && (rhsType == CGVT_DOUBLE)){\n\t\t\t\tnewres = divDD((CGDouble*)lhsValue, (CGDouble*)rhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif((lhsType == CGVT_VECTOR) && (rhsType == CGVT_DOUBLE)){\n\t\t\t\tnewres = divVD((CGVector*)lhsValue, (CGDouble*)rhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif((lhsType == CGVT_DOUBLE) && (rhsType == CGVT_VECTOR)){\n\t\t\t\tnewres = divDV((CGDouble*)lhsValue, (CGVector*)rhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif((lhsType == CGVT_VECTOR) && (rhsType == CGVT_VECTOR)){\n\t\t\t\tnewres = divVV((CGVector*)lhsValue, (CGVector*)rhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif((lhsType == CGVT_MATRIX) && (rhsType == CGVT_DOUBLE)){\n\t\t\t\tnewres = divMD((CGMatrix*)lhsValue, (CGDouble*)rhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif((lhsType == CGVT_MATRIX) && (rhsType == CGVT_VECTOR)){\n\t\t\t\tnewres = divMV((CGMatrix*)lhsValue, (CGVector*)rhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif((lhsType == CGVT_DOUBLE) && (rhsType == CGVT_MATRIX)){\n\t\t\t\tnewres = divDM((CGDouble*)lhsValue, (CGMatrix*)rhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\tcase CGBOT_MULT:{\n\t\t\t// TODO: update\n\t\t\tif((lhsType == CGVT_MATRIX) && (rhsType == CGVT_MATRIX)){\n\t\t\t\tnewres = mulMM((CGMatrix*)lhsValue, (CGMatrix*)rhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\t// TODO: update\n\t\t\tif((lhsType == CGVT_MATRIX) && (rhsType == CGVT_VECTOR)){\n\t\t\t\tnewres = mulMV((CGMatrix*)lhsValue, (CGVector*)rhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\t// TODO: update\n\t\t\tif((lhsType == CGVT_VECTOR) && (rhsType == CGVT_MATRIX)){\n\t\t\t\tnewres = mulMV((CGMatrix*)rhsValue, (CGVector*)lhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif((lhsType == CGVT_DOUBLE) && (rhsType == CGVT_DOUBLE)){\n\t\t\t\tnewres = mulDD((CGDouble*)lhsValue, (CGDouble*)rhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif((lhsType == CGVT_DOUBLE) && (rhsType == CGVT_VECTOR)){\n\t\t\t\tnewres = mulDV((CGDouble*)lhsValue, (CGVector*)rhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif((lhsType == CGVT_VECTOR) && (rhsType == CGVT_DOUBLE)){\n\t\t\t\tnewres = mulDV((CGDouble*)rhsValue, (CGVector*)lhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif((lhsType == CGVT_DOUBLE) && (rhsType == CGVT_MATRIX)){\n\t\t\t\tnewres = mulDM((CGDouble*)lhsValue, (CGMatrix*)rhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif((lhsType == CGVT_MATRIX) && (rhsType == CGVT_DOUBLE)){\n\t\t\t\tnewres = mulDM((CGDouble*)rhsValue, (CGMatrix*)lhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif((lhsType == CGVT_VECTOR) && (rhsType == CGVT_VECTOR)){\n\t\t\t\tnewres = crossVV((CGVector*)rhsValue, (CGVector*)lhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\tcase CGBOT_POW:{\n\t\t\tif((lhsType == CGVT_DOUBLE) && (rhsType == CGVT_DOUBLE)){\n\t\t\t\tnewres = powDD((CGDouble*)lhsValue, (CGDouble*)rhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif((lhsType == CGVT_VECTOR) && (rhsType == CGVT_DOUBLE)){\n\t\t\t\tnewres = powVD((CGVector*)lhsValue, (CGDouble*)rhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif((lhsType == CGVT_MATRIX) && (rhsType == CGVT_DOUBLE)){\n\t\t\t\tnewres = powMD((CGMatrix*)lhsValue, (CGDouble*)rhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\tcase CGBOT_DOT: {\n\t\t\t/*\n\t\t\t * The following are the same as MUL\n\t\t\t */\n\t\t\tif((lhsType == CGVT_DOUBLE) && (rhsType == CGVT_DOUBLE)){\n\t\t\t\tnewres = mulDD((CGDouble*)lhsValue, (CGDouble*)rhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif((lhsType == CGVT_DOUBLE) && (rhsType == CGVT_VECTOR)){\n\t\t\t\tnewres = mulDV((CGDouble*)lhsValue, (CGVector*)rhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif((lhsType == CGVT_VECTOR) && (rhsType == CGVT_DOUBLE)){\n\t\t\t\tnewres = mulDV((CGDouble*)rhsValue, (CGVector*)lhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif((lhsType == CGVT_DOUBLE) && (rhsType == CGVT_MATRIX)){\n\t\t\t\tnewres = mulDM((CGDouble*)lhsValue, (CGMatrix*)rhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif((lhsType == CGVT_MATRIX) && (rhsType == CGVT_DOUBLE)){\n\t\t\t\tnewres = mulDM((CGDouble*)rhsValue, (CGMatrix*)lhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\t/* here starts dot specific impl */\n\t\t\t\n\t\t\t\n\t\t\tif((lhsType == CGVT_MATRIX) && (rhsType == CGVT_MATRIX)){\n\t\t\t\tnewres = dotMM((CGMatrix*)lhsValue, (CGMatrix*)rhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif((lhsType == CGVT_MATRIX) && (rhsType == CGVT_VECTOR)){\n\t\t\t\tnewres = dotMV((CGMatrix*)lhsValue, (CGVector*)rhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\tif((lhsType == CGVT_VECTOR) && (rhsType == CGVT_MATRIX)){\n\t\t\t\tnewres = dotVM((CGVector*)lhsValue, (CGMatrix*)rhsValue, graph, parentNode);\n\t\t\t\t//newres = dotMM(vectorToMatrix((CGVector*)lhsValue), (CGMatrix*)rhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t\n\t\t\t/*\n\t\t\tif((lhsType == CGVT_VECTOR) && (rhsType == CGVT_MATRIX)){\n\t\t\t\tnewres = mulMV((CGMatrix*)rhsValue, (CGVector*)lhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\t*/\n\t\t\t\n\t\t\tif((lhsType == CGVT_VECTOR) && (rhsType == CGVT_VECTOR)){\n\t\t\t\tnewres = dotVV((CGVector*)lhsValue, (CGVector*)rhsValue, graph, parentNode);\n\t\t\t\tparentNode->result = newres;\n\t\t\t\treturn newres;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\tcase CGBOT_TMULT:{\n\t\t\tchar msg[MAX_ERR_FMT_LEN];\n\t\t\tsnprintf(msg, MAX_ERR_FMT_LEN, \"Operation `%s` is not implemented/supported\", getBinaryOperationTypeString(type));\n\t\t\treturn returnResultError(graph, CGET_OPERATION_NOT_IMPLEMENTED, parentNode, msg);\n\t\t}\n\t}\n\t\n\tchar msg[MAX_ERR_FMT_LEN];\n\tsnprintf(msg, MAX_ERR_FMT_LEN, \"Operation [%s %s %s] cannot be applied\", getVariableTypeString(lhsType), getBinaryOperationTypeString(type), getVariableTypeString(rhsType));\n\treturn returnResultError(graph, CGET_INCOMPATIBLE_ARGS_EXCEPTION, parentNode, msg);\n}\n\nCGResultNode* computeRawNode(CGNode* node){\n\tCGraph* tmp_G = makeGraph(\"temp_g\");\n\t\n\ttmp_G->root = node;\n\tstoreNodesInGraph(tmp_G, node);\n\t\n\tCGResultNode* res = computeGraph(tmp_G);\n\tres = copyResultNode(res);\n\tfreeGraph(tmp_G);\n\tfree(tmp_G);\n\t\n\treturn res;\n}\n\n\nCGResultNode* computeCGNode(CGraph* graph, CGNode* node){\n\tCGResultNode* result = NULL;\n\t\n\tif(node->result != NULL){\n\t\treturn node->result;\n\t}\n\t\n\tswitch(node->type){\n\t\tcase CGNT_CONSTANT:{\n\t\t\tresult = constantNodeToResultNodeCopy(node);\n\t\t\tbreak;\n\t\t}\n\n\t\tcase CGNT_VARIABLE:{\n\t\t\tif(graph == NULL)\n\t\t\t{\n\t\t\t\tchar msg[MAX_ERR_FMT_LEN];\n\t\t\t\tsnprintf(msg, MAX_ERR_FMT_LEN, \"Cannot compute variable`%s` without the graph instance\", node->var->name);\n\t\t\t\treturn returnResultError(graph, CGET_NO_GRAPH_INSTANCE, node, msg);\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\tCGNode* constantNode = *map_get(&graph->vars, node->var->name);\n\t\t\tif(constantNode == NULL)\n\t\t\t{\n\t\t\t\tchar msg[MAX_ERR_FMT_LEN];\n\t\t\t\tsnprintf(msg, MAX_ERR_FMT_LEN, \"No variable `%s` was found in graph `%s`\", node->var->name, graph!=NULL?graph->name:\"[anonymous]\");\n\t\t\t\treturn returnResultError(graph, CGET_VARIABLE_DOES_NOT_EXIST, node, msg);\n\t\t\t}\n\t\t\t\n\t\t\tCGResultNode* rnode = computeCGNode(graph, constantNode);\n\t\t\tCHECK_RESULT(rnode)\n\t\t\tconstantNode->result = rnode;\n\t\t\tnode->result = copyResultNode(rnode);\n\t\t\t\n\t\t\tresult = node->result;\n\t\t\tbreak;\n\t\t}\n\t\tcase CGNT_BINARY_OPERATION:\n\t\t\tresult = processBinaryOperation(graph, node->bop->type, node->bop->lhs, node->bop->rhs, node);\n\t\t\tbreak;\n\t\tcase CGNT_UNARY_OPERATION:\n\t\t\tresult = processUnaryOperation(graph, node->uop->type, node->uop->uhs, node);\n\t\t\tbreak;\n\t\t\n\t\t/* \n\t\t * TODO: add this test to unittest\n\t\t */\n\t\tcase CGNT_AXIS_BOUND_OPERATION:\n\t\t{\n            //CGResultNode* res = computeCGNode(graph, node->axop->uhs);\n\n\t\t\tswitch(node->axop->type){\n\t\t\t\tcase CGABOT_SUM:{\n\t\t\t\t\tCGResultNode* newres = computeCGNode(graph, node->axop->uhs);\n\t\t\t\t\tCHECK_RESULT(newres)\n\n\t\t\t\t\tif(newres->type == CGVT_DOUBLE){\n\t\t\t\t\t\tresult = sumD((CGDouble*)newres->value, graph, node);\n\t\t\t\t\t}\n\n\t\t\t\t\tif(newres->type == CGVT_VECTOR){\n\t\t\t\t\t\tresult = sumV((CGVector*)newres->value, graph, node);\n\t\t\t\t\t}\n\n\t\t\t\t\tif(newres->type == CGVT_MATRIX){\n\t\t\t\t\t\tresult = sumM((CGMatrix*)newres->value, graph, node, node->axop->axis);\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tcase CGABOT_MAX:{\n\t\t\t\t\tresult = max(node, graph);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tcase CGABOT_MIN:{\n\t\t\t\t\tresult = min(node, graph);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tcase CGABOT_MEAN:{\n\t\t\t\t\tresult = mean(node, graph);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tcase CGABOT_SOFTMAX:{\n\t\t\t\t\tchar msg[MAX_ERR_FMT_LEN];\n\t\t\t\t\tsnprintf(msg, MAX_ERR_FMT_LEN, \"Operation [CGABOT_SOFTMAX] is not implemented/supported\");\n\t\t\t\t\treturn returnResultError(graph, CGET_OPERATION_NOT_IMPLEMENTED, node, msg);\n\t\t\t\t\t//CGResultNode* res = computeCGNode(graph, node->axop->uhs);\n\t\t\t\t\t//break;\n\t\t\t\t}\n\n\t\t\t\tcase CGABOT_ARGMAX:{\n\t\t\t\t    result = argmax(node, graph);\n                    break;\n\t\t\t\t}\n\n                case CGABOT_ARGMIN:{\n                    result = argmin(node, graph);\n                    break;\n                }\n\n\t\t\t\tdefault:\n\t\t\t\t    break;\n\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n\t\tcase CGNT_GRAPH:{\n\t\t\tresult = computeGraph(node->graph);\n\t\t\tbreak;\n\t\t\t/*\n\t\t\tchar msg[MAX_ERR_FMT_LEN];\n\t\t\tsnprintf(msg, MAX_ERR_FMT_LEN, \"Operation [GRAPH] is not implemented/supported\");\n\t\t\treturn returnResultError(graph, CGET_OPERATION_NOT_IMPLEMENTED, node, msg);\n\t\t\t*/\n\t\t}\n\t\t\n\t\tcase CGNT_CROSS_ENTROPY_LOSS_FUNC:\n\t\t{\n\t\t\tCGResultNode* X_res = computeCGNode(graph, node->crossEntropyLoss->x);\n\t\t\tCGNode* X = resultNodeToConstantNodeCopy(X_res);\n\t\t\n\t\t\tCGNode* X_val = softmax_node(X);\n\t\t\t\n\t\t\t\t\t\t\n\t\t\tCGResultNode* x_res = computeRawNode(X_val);\n\n\t\t\tCGResultNode* y_res = computeCGNode(graph, node->crossEntropyLoss->y);\n\t\t\t\n\t\t\tresult = crossEntropy(x_res, y_res, node->crossEntropyLoss->num_classes);\n\t\t\t\n\t\t\tfreeResultNode(x_res);\n\t\t\tfree(x_res);\n\t\t\tbreak;\n\t\t}\n\t}\n\t\n\tnode->result = reduceDim(result);\n\t\n\t\n\tif(node->diff == NULL)\n\t\tswitch(node->result->type){\n\t\t\tcase CGVT_DOUBLE:\n\t\t\t\tnode->diff = makeZeroDoubleConstantNode();\n\t\t\t\tbreak;\n\t\t\tcase CGVT_VECTOR:{\n\t\t\t\tCGVector* v = (CGVector*)node->result ->value;\n\t\t\t\tnode->diff = makeZeroVectorConstantNode(v->len);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t\tcase CGVT_MATRIX:{\n\t\t\t\tCGMatrix* v = (CGMatrix*)node->result ->value;\n\t\t\t\tnode->diff = makeZeroMatrixConstantNode(v->rows, v->cols);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\n\treturn node->result;\n}\n\nCGResultNode* reduceDim(CGResultNode* result){\n    //return result;\n\n\tswitch(result->type){\n\t\tcase CGVT_DOUBLE:{\n\t\t\treturn result;\n\t\t}\n\t\t\n\t\tcase CGVT_VECTOR:{\n\t\t\tCGVector* vec = (CGVector*)result->value;\n\t\t\tif (vec->len > 1)\n\t\t\t\treturn result;\n\n#ifdef CG_USE_OPENCL\n\t\t\tcopyDataToHost(result);\n#endif\n\t\t\t\n\t\t\tCGDouble* d = calloc(1, sizeof(CGDouble));\n\t\t\td->value = vec->data[0];\n\t\t\t\n\t\t\tfreeVectorValue(result->value);\n\t\t\tfree(result->value);\n\t\t\t\n\t\t\tresult->type = CGVT_DOUBLE;\n\t\t\tresult->value = d;\n\t\t\t\n\t\t\treturn result;\n\t\t}\n\t\t\n\t\tcase CGVT_MATRIX:{\n\t\t\tCGMatrix* mat = (CGMatrix*)result->value;\n\t\t\t\n\t\t\tif((mat->rows>1) &&(mat->cols>1))\n\t\t\t\treturn result;\n\t\t\t\n\t\t\tif((mat->rows == 1) && (mat->cols == 1)){\n                copyDataToHost(result);\n\n\t\t\t\tCGDouble* d = calloc(1, sizeof(CGDouble));\n\t\t\t\td->value = mat->data[0];\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tfreeMatrixValue(result->value);\n\t\t\t\tfree(result->value);\n\t\t\t\t\n\t\t\t\tresult->type = CGVT_DOUBLE;\n\t\t\t\tresult->value = d;\n\t\t\t\t\n\t\t\t\treturn result;\n\t\t\t}\n\t\t\t\n\t\t\tif(mat->rows == 1){\n\t\t\t\tCGVector* vec = calloc(1, sizeof(CGVector));\n\t\t\t\tvec->len = mat->cols;\n\t\t\t\tvec->data = mat->data;\n\t\t\t\t//TODO: Memory leak here\n#ifdef CG_USE_OPENCL\n\t\t\t\tvec->buf = mat->buf;\n#endif\n\t\t\t\t\n\t\t\t\t//freeMatrixValue(result->value);\n\t\t\t\tfree(result->value);\n\t\t\t\t\n\t\t\t\tresult->type = CGVT_VECTOR;\n\t\t\t\tresult->value = vec;\n\t\t\t\t\n\t\t\t\treturn result;\n\t\t\t}\n\t\t\t\n\t\t\treturn result;\n\t\t}\n\t}\n}\n\nCGResultNode* computeGraph(CGraph* graph){\n\tresetGraphResultNodes(graph, graph->root);\n\tCGResultNode* res = computeCGNode(graph, graph->root);\n\tcopyDataToHost(res);\n\n\treturn res;\n}\n\nCGResultNode* computeGraphNode(CGraph* graph, CGNode* node){\n\tstoreNodesInGraph(graph, node);\n\tresetGraphResultNodes(graph, node);\n\treturn computeCGNode(graph, node);\n}\n\n\nvoid storeNodesInGraph(CGraph* graph, CGNode* node){\n\tint idx = -1;\n\t\n\tvec_find(&graph->nodes, node, idx);\n\t\n\tif(idx != -1)\n\t\treturn;\n\t\n\tvec_push(&graph->nodes, node);\n\t\n\t\n\tswitch(node->type){\n\t\tcase CGNT_CONSTANT:\n\t\t\tbreak;\n\t\tcase CGNT_VARIABLE:\n\t\t\tbreak;\n\t\tcase CGNT_BINARY_OPERATION:\n\t\t\tstoreNodesInGraph(graph, node->bop->lhs);\n\t\t\tstoreNodesInGraph(graph, node->bop->rhs);\n\t\t\tbreak;\n\t\tcase CGNT_UNARY_OPERATION:\n\t\t\tstoreNodesInGraph(graph, node->uop->uhs);\n\t\t\tbreak;\n\t\tcase CGNT_AXIS_BOUND_OPERATION:\n\t\t\tstoreNodesInGraph(graph, node->axop->uhs);\n\t\t\tbreak;\n\t\tcase CGNT_GRAPH:\n\t\t\tstoreNodesInGraph(graph, node->graph->root);\n\t\t\tbreak;\n\t\tcase CGNT_CROSS_ENTROPY_LOSS_FUNC:\n\t\t\tstoreNodesInGraph(graph, node->crossEntropyLoss->x);\n\t\t\tstoreNodesInGraph(graph, node->crossEntropyLoss->y);\n\t\t\tbreak;\n\t}\n}\n\nvoid resetGraphResultNodes(CGraph* graph, CGNode* node){\n\tif(node->result != NULL){\n\t\tfreeResultNode(node->result);\n\t\tfree(node->result);\n\t\tnode->result = NULL;\n\t}\n\t\n\tif(node->diff != NULL){\n\t\tfreeNode(graph, node->diff);\n\t\tfree(node->diff);\n\t\tnode->diff = NULL;\n\t}\n\t\n\tswitch(node->type){\n\t\tcase CGNT_CONSTANT:\n\t\t\tbreak;\n\t\tcase CGNT_VARIABLE:{\n\t\t\tCGNode* var = graphGetVar(graph, node->var->name);\n\t\t\tif(var != NULL)\n\t\t\t\tresetGraphResultNodes(graph, var);\n\t\t\tbreak;\n\t\t}\n\t\tcase CGNT_BINARY_OPERATION:\n\t\t\tresetGraphResultNodes(graph, node->bop->lhs);\n\t\t\tresetGraphResultNodes(graph, node->bop->rhs);\n\t\t\tbreak;\n\t\tcase CGNT_UNARY_OPERATION:\n\t\t\tresetGraphResultNodes(graph, node->uop->uhs);\n\t\t\tbreak;\n\t\tcase CGNT_AXIS_BOUND_OPERATION:\n\t\t\tresetGraphResultNodes(graph, node->axop->uhs);\n\t\t\tbreak;\n\t\tcase CGNT_GRAPH:\n\t\t\tresetGraphResultNodes(graph, node->graph->root);\n\t\t\tbreak;\n\t\tcase CGNT_CROSS_ENTROPY_LOSS_FUNC:\n\t\t\tresetGraphResultNodes(graph, node->crossEntropyLoss->x);\n\t\t\tresetGraphResultNodes(graph, node->crossEntropyLoss->y);\n\t\t\tbreak;\n\t}\n}\n\n\nvoid graphSetVar_lua(CGraph* graph, const char* name, CGNode* value){\n\tCGNode** old = map_get(&graph->vars, name); \n\tif(old != NULL){\n\t\t//freeNode(graph, *old);\n\t\tmap_remove(&graph->vars, name);\n\t}\n\t\n\tint res = map_set(&graph->vars, name, value);\n}\n", "meta": {"hexsha": "3bce30b8ef797fe056ec696a66b1d0ccdb857bfd", "size": 31035, "ext": "c", "lang": "C", "max_stars_repo_path": "source/libcgraph/source/cgraph.c", "max_stars_repo_name": "Enehcruon/cgraph", "max_stars_repo_head_hexsha": "cc12d6e195d0d260584e1d4bc822bcc34d24a9af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-01-29T17:55:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-28T03:25:53.000Z", "max_issues_repo_path": "source/libcgraph/source/cgraph.c", "max_issues_repo_name": "Enehcruon/cgraph", "max_issues_repo_head_hexsha": "cc12d6e195d0d260584e1d4bc822bcc34d24a9af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-01-22T18:39:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-08T12:27:17.000Z", "max_forks_repo_path": "source/libcgraph/source/cgraph.c", "max_forks_repo_name": "praisethemoon/ccgraph", "max_forks_repo_head_hexsha": "ff5ff885dcddc19cfe1c6a21550a39c19684680f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-02-26T13:55:26.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-21T05:16:24.000Z", "avg_line_length": 25.293398533, "max_line_length": 174, "alphanum_fraction": 0.6425326245, "num_tokens": 9223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326186278634367, "lm_q2_score": 0.03676946686724094, "lm_q1q2_score": 0.016666197045906373}}
{"text": "// Copyright (c) 2022 SmartPolarBear.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n//\n// Created by cleve on 2/1/2022.\n//\n#pragma once\n\n#include \"types.h\"\n\n#include <utility>\n#include <cstdint>\n#include <string_view>\n#include <bit>\n\n#include <gsl/gsl>\n\nnamespace jpeg_lite::decoder::transform\n{\n[[nodiscard]] FORCE_INLINE gsl::index coordinate_to_zigzag(gsl::index x, gsl::index y);\n\n[[nodiscard]] FORCE_INLINE std::pair<gsl::index, gsl::index> zigzag_to_coordinate(gsl::index zigzag);\n\n[[nodiscard, maybe_unused]] int16_t binary_string_to_int16(std::string_view sv);\n\n[[nodiscard]] static inline FORCE_INLINE constexpr int16_t value_category(int16_t val)\n{\n\tif (val == 0x0000)\n\t\treturn 0;\n\treturn std::bit_width(static_cast<uint16_t>(val > 0 ? val : -val));\n}\n}", "meta": {"hexsha": "dc4796d2b834a558c022b460dd5a2cb2e4c01c9b", "size": 1793, "ext": "h", "lang": "C", "max_stars_repo_path": "include/decoder/transform.h", "max_stars_repo_name": "SmartPolarBear/jpeg-lite", "max_stars_repo_head_hexsha": "e450d01fe90d710381f53d16b5141a85dabd56d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/decoder/transform.h", "max_issues_repo_name": "SmartPolarBear/jpeg-lite", "max_issues_repo_head_hexsha": "e450d01fe90d710381f53d16b5141a85dabd56d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/decoder/transform.h", "max_forks_repo_name": "SmartPolarBear/jpeg-lite", "max_forks_repo_head_hexsha": "e450d01fe90d710381f53d16b5141a85dabd56d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5918367347, "max_line_length": 101, "alphanum_fraction": 0.753485778, "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632159254749036, "lm_q2_score": 0.03904828979072011, "lm_q1q2_score": 0.016647129089835705}}
{"text": "/*\n** Read design file\n**\n** G.Lohmann, MPI-KYB 2018\n*/\n#include <viaio/Vlib.h>\n#include <viaio/VImage.h>\n#include <viaio/mu.h>\n#include <viaio/option.h>\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_blas.h>\n\n\ntypedef struct TrialStruct {\n  int   id;\n  float onset;\n  float duration;\n  float height;\n} Trial;\n\n\nextern void printmat(gsl_matrix *R,char *str);\nextern void printvec(gsl_vector *x,char *str);\n\nint test_ascii(int val)\n{\n  if (val >= 'a' && val <= 'z') return 1;\n  if (val >= 'A' && val <= 'Z') return 1;\n  if (val >= '0' && val <= '9') return 1;\n  if (val ==  ' ') return 1;\n  if (val ==  '-') return 1;\n  if (val ==  '+') return 1;\n  if (val ==  '.') return 1;\n  if (val == '\\0') return 1;\n  if (val == '\\n') return 1;\n  if (val == '\\r') return 1;\n  if (val == '\\t') return 1;\n  if (val == '\\v') return 1;\n  return 0;\n}\n\n\nint line_empty(char *buf,int len)\n{\n  int i;\n  for (i=0; i<len; i++) {\n    if (buf[i] != ' ' && buf[i] != '\\0' && buf[i] != '\\n') return 0;\n  }\n  return 1;\n}\n\nint CheckBuffer(char *buf,int len)\n{\n  int j;\n  if(strlen(buf) < 1) return 0;\n  if (buf[0] == '%' || buf[0] == '#' || buf[0] == '/') return 0;  /* comment */\n  for (j=0; j<len; j++) {\n    if (buf[j] == '\\v') buf[j] = ' '; /* remove tabs */\n    if (buf[j] == '\\t') buf[j] = ' ';\n  }\n  if (line_empty(buf,len) > 0) return 0;\n  return 1;\n}\n\n\nint VistaFormat(char *buf,int len)\n{\n  if (strncmp(buf,\"V-data\",6) == 0) return 1;\n  return 0;\n}\n\n\n/* parse design file */\nTrial *ReadDesign(VString designfile,int *numtrials,int *nevents)\n{\n  FILE *fp=NULL;\n  int  i,j,id,len=4096;\n  float onset=0,duration=0,height=0;\n  char *buf = (char *)VCalloc(len,sizeof(char));\n\n  fp = fopen(designfile,\"r\");\n  if (!fp) VError(\" error opening design file %s\",designfile);\n  int ntrials=0;\n  while (!feof(fp)) {\n    for (j=0; j<len; j++) buf[j] = '\\0';\n    if (fgets(buf,len,fp) == NULL) break;\n    if (VistaFormat(buf,len) > 1) VError(\" Design file must be a text file\");\n    if (CheckBuffer(buf,len) < 1) continue;\n    if (! test_ascii((int)buf[0])) VError(\" File %s: line %d begins with an illegal character (%c)\",designfile,ntrials,buf[0]);\n    ntrials++;    \n  }\n  *numtrials = ntrials;\n\n  Trial *trial = (Trial *) VCalloc(ntrials+1,sizeof(Trial));\n\n  i = (*nevents) = 0;\n  rewind(fp);\n  while (!feof(fp)) {\n    for (j=0; j<len; j++) buf[j] = '\\0';\n    if (fgets(buf,len,fp) == NULL) break;\n    if (CheckBuffer(buf,len) < 1) continue;\n\n    int nch = sscanf(buf,\"%d %f %f %f\",&id,&onset,&duration,&height);\n    if (nch > 0 && nch != 4) VError(\" line %d: illegal input format\",i+1);\n    if (duration < 0.5 && duration >= -0.0001) duration = 0.5;\n    trial[i].id       = id;\n    trial[i].onset    = onset;\n    trial[i].duration = duration;\n    trial[i].height   = height;\n    i++;\n    if (id > (*nevents)) (*nevents) = id;\n  }\n  fclose(fp);\n  return trial;\n}\n\n\n\nTrial *CopyTrials(Trial *trial,int numtrials)\n{\n  int i;\n  Trial *newtrial = (Trial *) VCalloc(numtrials,sizeof(Trial));\n  for (i=0; i<numtrials; i++) {\n    newtrial[i].id       = trial[i].id;\n    newtrial[i].onset    = trial[i].onset;\n    newtrial[i].duration = trial[i].duration;\n    newtrial[i].height   = trial[i].height;\n  }\n  return newtrial;\n}\n\n\n\n\n/* concatenate trials from all runs */\nTrial *ConcatenateTrials(Trial **trial,int *numtrials,float *run_duration,int dlists,int sumtrials)\n{\n  int i,j;\n  Trial *alltrials = (Trial *) VCalloc(sumtrials,sizeof(Trial));\n  \n  int ii=0;\n  float add=0;\n  for (i=0; i<dlists; i++) {\n    for (j=0; j<numtrials[i]; j++) {\n      alltrials[ii].id       = trial[i][j].id;\n      alltrials[ii].onset    = trial[i][j].onset + add;\n      alltrials[ii].duration = trial[i][j].duration;\n      alltrials[ii].height   = trial[i][j].height;\n      ii++;\n    }\n    add += run_duration[i];\n  }\n  return alltrials;\n}\n\n\n\n/* check if trial labels are complete and positive */\nvoid CheckTrialLabels(Trial *trial,int numtrials)\n{\n  int i,j;\n  int maxlabel = -1;\n  for (i=0; i<numtrials; i++) {\n    j = trial[i].id;\n    if (j > maxlabel) maxlabel = j;\n    if (j < 1) VError(\" trial[%d] has illegal label %d\",i,j);\n  }\n\n  int *tmp = (int *) VCalloc(maxlabel+1,sizeof(int));\n  for (i=0; i<numtrials; i++) {\n    j = trial[i].id;\n    tmp[j]++;\n  }\n  for (i=1; i<=maxlabel; i++) {\n    if (tmp[i] < 1) VError(\" Label %d missing in design file\",i);\n    if (tmp[i] < 4) VWarning(\" Label %d has too few trials (%d) for random permutations\",i,tmp[i]);\n  }\n  VFree(tmp);\n}\n\n", "meta": {"hexsha": "ebce82618e3fdf8a8c6f287bf8cbd161e59a29d3", "size": 4531, "ext": "c", "lang": "C", "max_stars_repo_path": "src/stats/vlisa_precoloring/Design.c", "max_stars_repo_name": "zrajna/lipsia", "max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z", "max_issues_repo_path": "src/stats/vlisa_precoloring/Design.c", "max_issues_repo_name": "zrajna/lipsia", "max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z", "max_forks_repo_path": "src/stats/vlisa_precoloring/Design.c", "max_forks_repo_name": "zrajna/lipsia", "max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z", "avg_line_length": 24.1010638298, "max_line_length": 127, "alphanum_fraction": 0.5709556389, "num_tokens": 1554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552953503957277, "lm_q2_score": 0.037326883060511865, "lm_q1q2_score": 0.016630228854426356}}
{"text": "#include <gsl/gsl_test.h>\n#include <gsl/gsl_ieee_utils.h>\n#include <gsl/gsl_math.h>\n#include \"gsl_cblas.h\"\n\n#include \"tests.h\"\n\nvoid\ntest_trmm (void) {\nconst double flteps = 1e-4, dbleps = 1e-6;\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha = 1.0f;\n   float A[] = { 0.565f, 0.967f, -0.969f, 0.184f };\n   int lda = 2;\n   float B[] = { 0.842f, -0.918f, -0.748f, -0.859f, -0.463f, 0.292f };\n   int ldb = 3;\n   float B_expected[] = { -0.354923f, -0.966391f, -0.140256f, -0.158056f, -0.085192f, 0.053728f };\n   cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strmm(case 1670)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha = 1.0f;\n   float A[] = { -0.748f, 0.548f, 0.245f, 0.761f };\n   int lda = 2;\n   float B[] = { 0.349f, -0.552f, -0.682f, -0.71f, 0.475f, -0.59f };\n   int ldb = 3;\n   float B_expected[] = { -0.04008f, -0.2917f, -1.00532f, -0.71f, 0.475f, -0.59f };\n   cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strmm(case 1671)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha = 1.0f;\n   float A[] = { 0.788f, 0.617f, -0.998f, -0.97f };\n   int lda = 2;\n   float B[] = { -0.4f, 0.773f, 0.074f, -0.388f, 0.825f, -0.608f };\n   int ldb = 3;\n   float B_expected[] = { -0.3152f, 0.609124f, 0.058312f, 0.77556f, -1.5717f, 0.515908f };\n   cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strmm(case 1672)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha = 1.0f;\n   float A[] = { 0.01f, 0.387f, -0.953f, -0.374f };\n   int lda = 2;\n   float B[] = { 0.364f, 0.09f, 0.588f, -0.263f, 0.584f, 0.463f };\n   int ldb = 3;\n   float B_expected[] = { 0.364f, 0.09f, 0.588f, -0.609892f, 0.49823f, -0.097364f };\n   cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strmm(case 1673)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha = 1.0f;\n   float A[] = { -0.586f, -0.426f, 0.765f, -0.239f };\n   int lda = 2;\n   float B[] = { -0.673f, -0.724f, 0.217f, -0.672f, -0.378f, -0.005f };\n   int ldb = 2;\n   float B_expected[] = { -0.159482f, 0.173036f, -0.641242f, 0.160608f, 0.217683f, 0.001195f };\n   cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strmm(case 1674)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha = 1.0f;\n   float A[] = { -0.668f, 0.962f, 0.515f, 0.292f };\n   int lda = 2;\n   float B[] = { -0.145f, -0.337f, 0.718f, -0.866f, -0.454f, -0.439f };\n   int ldb = 2;\n   float B_expected[] = { -0.318555f, -0.337f, 0.27201f, -0.866f, -0.680085f, -0.439f };\n   cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strmm(case 1675)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha = 1.0f;\n   float A[] = { -0.125f, -0.676f, 0.181f, 0.741f };\n   int lda = 2;\n   float B[] = { 0.354f, -0.366f, 0.455f, 0.134f, -0.564f, -0.303f };\n   int ldb = 2;\n   float B_expected[] = { -0.04425f, -0.51051f, -0.056875f, -0.208286f, 0.0705f, 0.156741f };\n   cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strmm(case 1676)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha = 1.0f;\n   float A[] = { -0.162f, 0.542f, -0.839f, -0.935f };\n   int lda = 2;\n   float B[] = { 0.216f, 0.766f, -0.228f, -0.097f, 0.205f, 0.875f };\n   int ldb = 2;\n   float B_expected[] = { 0.216f, 0.883072f, -0.228f, -0.220576f, 0.205f, 0.98611f };\n   cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strmm(case 1677)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha = 1.0f;\n   float A[] = { -0.353f, -0.854f, -0.502f, 0.591f, -0.934f, -0.729f, 0.063f, 0.352f, 0.126f };\n   int lda = 3;\n   float B[] = { 0.2f, -0.626f, -0.694f, -0.889f, -0.251f, -0.42f };\n   int ldb = 3;\n   float B_expected[] = { -0.0706f, 0.413884f, 0.26851f, 0.313817f, 0.99364f, 0.576337f };\n   cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strmm(case 1678)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha = 1.0f;\n   float A[] = { -0.864f, -0.046f, -0.755f, 0.12f, 0.525f, 0.917f, 0.571f, -0.098f, -0.226f };\n   int lda = 3;\n   float B[] = { -0.905f, -0.296f, -0.927f, -0.813f, 0.624f, -0.366f };\n   int ldb = 3;\n   float B_expected[] = { -0.905f, -0.25437f, -0.515157f, -0.813f, 0.661398f, 0.820023f };\n   cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strmm(case 1679)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha = 1.0f;\n   float A[] = { -0.69f, -0.927f, -0.281f, -0.918f, -0.527f, -0.652f, -0.393f, -0.954f, 0.651f };\n   int lda = 3;\n   float B[] = { -0.587f, 0.788f, -0.629f, -0.444f, 0.515f, 0.081f };\n   int ldb = 3;\n   float B_expected[] = { -0.071157f, 0.18479f, -0.409479f, -0.198243f, -0.348679f, 0.052731f };\n   cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strmm(case 1680)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha = 1.0f;\n   float A[] = { -0.082f, -0.077f, 0.811f, 0.852f, 0.224f, 0.443f, -0.509f, 0.171f, 0.986f };\n   int lda = 3;\n   float B[] = { -0.982f, 0.388f, -0.493f, -0.497f, -0.605f, 0.433f };\n   int ldb = 3;\n   float B_expected[] = { -0.400487f, 0.303697f, -0.493f, -1.23286f, -0.530957f, 0.433f };\n   cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strmm(case 1681)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha = 1.0f;\n   float A[] = { 0.97f, -0.666f, 0.066f, -0.176f, 0.402f, 0.286f, -0.703f, 0.962f, 0.912f };\n   int lda = 3;\n   float B[] = { -0.644f, -0.97f, 0.814f, -0.777f, 0.812f, 0.254f };\n   int ldb = 2;\n   float B_expected[] = { -0.62468f, -0.9409f, 0.440572f, -0.141634f, 1.97634f, 0.166084f };\n   cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strmm(case 1682)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha = 1.0f;\n   float A[] = { 0.714f, 0.468f, 0.859f, -0.547f, 0.076f, 0.542f, 0.512f, -0.987f, -0.167f };\n   int lda = 3;\n   float B[] = { -0.238f, -0.336f, 0.402f, 0.945f, -0.242f, -0.062f };\n   int ldb = 2;\n   float B_expected[] = { -0.238f, -0.336f, 0.532186f, 1.12879f, -0.76063f, -1.16675f };\n   cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strmm(case 1683)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha = 1.0f;\n   float A[] = { -0.723f, 0.041f, 0.333f, -0.682f, 0.193f, 0.581f, 0.963f, -0.757f, 0.396f };\n   int lda = 3;\n   float B[] = { 0.047f, -0.701f, -0.25f, -0.779f, 0.435f, 0.612f };\n   int ldb = 2;\n   float B_expected[] = { 0.100624f, 0.67868f, 0.204485f, 0.205225f, 0.17226f, 0.242352f };\n   cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strmm(case 1684)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha = 1.0f;\n   float A[] = { -0.13f, 0.511f, -0.544f, 0.938f, -0.126f, -0.873f, 0.118f, -0.75f, 0.674f };\n   int lda = 3;\n   float B[] = { -0.927f, -0.558f, -0.289f, -0.66f, 0.83f, 0.363f };\n   int ldb = 2;\n   float B_expected[] = { -1.5262f, -1.09273f, -1.01359f, -0.976899f, 0.83f, 0.363f };\n   cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strmm(case 1685)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha = 0.1f;\n   float A[] = { -0.625f, -0.123f, -0.48f, -0.088f };\n   int lda = 2;\n   float B[] = { 0.376f, -0.46f, -0.813f, 0.419f, 0.792f, 0.226f };\n   int ldb = 3;\n   float B_expected[] = { -0.0235f, 0.02875f, 0.0508125f, -0.008312f, -0.0013116f, 0.0080111f };\n   cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strmm(case 1686)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha = 0.1f;\n   float A[] = { -0.038f, -0.105f, -0.946f, 0.474f };\n   int lda = 2;\n   float B[] = { -0.757f, 0.974f, -0.045f, -0.809f, 0.654f, 0.611f };\n   int ldb = 3;\n   float B_expected[] = { -0.0757f, 0.0974f, -0.0045f, -0.0729515f, 0.055173f, 0.0615725f };\n   cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strmm(case 1687)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha = 0.1f;\n   float A[] = { -0.328f, 0.713f, 0.781f, 0.084f };\n   int lda = 2;\n   float B[] = { -0.097f, 0.442f, -0.563f, 0.065f, -0.18f, 0.63f };\n   int ldb = 3;\n   float B_expected[] = { 0.0082581f, -0.0285556f, 0.0676694f, 5.46e-04f, -0.001512f, 0.005292f };\n   cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strmm(case 1688)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha = 0.1f;\n   float A[] = { 0.261f, -0.659f, -0.536f, 0.694f };\n   int lda = 2;\n   float B[] = { -0.498f, 0.692f, 0.125f, 0.706f, -0.118f, -0.907f };\n   int ldb = 3;\n   float B_expected[] = { -0.0876416f, 0.0755248f, 0.0611152f, 0.0706f, -0.0118f, -0.0907f };\n   cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strmm(case 1689)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha = 0.1f;\n   float A[] = { -0.669f, 0.416f, 0.761f, -0.359f };\n   int lda = 2;\n   float B[] = { -0.305f, -0.675f, -0.442f, 0.566f, 0.064f, 0.962f };\n   int ldb = 2;\n   float B_expected[] = { 0.0204045f, 0.001022f, 0.0295698f, -0.0539556f, -0.0042816f, -0.0296654f };\n   cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strmm(case 1690)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha = 0.1f;\n   float A[] = { 0.565f, 0.386f, 0.643f, -0.028f };\n   int lda = 2;\n   float B[] = { 0.863f, -0.241f, 0.766f, 0.656f, -0.977f, 0.274f };\n   int ldb = 2;\n   float B_expected[] = { 0.0863f, 0.0313909f, 0.0766f, 0.114854f, -0.0977f, -0.0354211f };\n   cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strmm(case 1691)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha = 0.1f;\n   float A[] = { 0.116f, 0.534f, 0.043f, 0.73f };\n   int lda = 2;\n   float B[] = { -0.758f, -0.63f, -0.043f, 0.666f, -0.088f, 0.382f };\n   int ldb = 2;\n   float B_expected[] = { -0.0424348f, -0.04599f, 0.0350656f, 0.048618f, 0.019378f, 0.027886f };\n   cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strmm(case 1692)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha = 0.1f;\n   float A[] = { 0.48f, -0.63f, -0.786f, -0.437f };\n   int lda = 2;\n   float B[] = { 0.945f, 0.528f, -0.855f, -0.587f, 0.062f, 0.372f };\n   int ldb = 2;\n   float B_expected[] = { 0.061236f, 0.0528f, -0.048519f, -0.0587f, -0.017236f, 0.0372f };\n   cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strmm(case 1693)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha = 0.1f;\n   float A[] = { -0.822f, -0.068f, 0.119f, -0.244f, -0.05f, 0.685f, 0.752f, -0.059f, -0.935f };\n   int lda = 3;\n   float B[] = { -0.431f, -0.753f, -0.319f, 0.164f, 0.979f, 0.885f };\n   int ldb = 3;\n   float B_expected[] = { 0.0367525f, -0.0180865f, 0.0298265f, -0.0096065f, 0.0557275f, -0.0827475f };\n   cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strmm(case 1694)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha = 0.1f;\n   float A[] = { 0.97f, -0.408f, 0.174f, -0.308f, 0.997f, -0.484f, 0.322f, -0.183f, 0.849f };\n   int lda = 3;\n   float B[] = { -0.571f, 0.696f, -0.256f, -0.178f, 0.098f, 0.004f };\n   int ldb = 3;\n   float B_expected[] = { -0.0899512f, 0.0819904f, -0.0256f, -0.0217288f, 0.0096064f, 4.0e-04f };\n   cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strmm(case 1695)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha = 0.1f;\n   float A[] = { -0.831f, 0.73f, 0.407f, 0.721f, 0.086f, -0.294f, 0.941f, -0.656f, -0.066f };\n   int lda = 3;\n   float B[] = { -0.051f, -0.343f, -0.98f, 0.722f, -0.372f, 0.466f };\n   int ldb = 3;\n   float B_expected[] = { 0.0042381f, -0.0066269f, 0.0241697f, -0.0599982f, 0.048857f, 0.0892678f };\n   cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strmm(case 1696)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha = 0.1f;\n   float A[] = { 0.472f, 0.137f, -0.341f, 0.386f, -0.578f, 0.863f, -0.415f, -0.547f, -0.023f };\n   int lda = 3;\n   float B[] = { 0.582f, 0.141f, -0.306f, -0.047f, -0.162f, -0.784f };\n   int ldb = 3;\n   float B_expected[] = { 0.0582f, 0.0365652f, -0.0624657f, -0.0047f, -0.0180142f, -0.0675881f };\n   cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strmm(case 1697)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha = 0.1f;\n   float A[] = { -0.775f, 0.762f, -0.038f, -0.8f, 0.626f, -0.701f, 0.639f, 0.239f, 0.34f };\n   int lda = 3;\n   float B[] = { 0.42f, 0.917f, 0.485f, 0.844f, -0.832f, 0.179f };\n   int ldb = 2;\n   float B_expected[] = { -0.124515f, -0.127149f, 0.0104762f, 0.0571125f, -0.028288f, 0.006086f };\n   cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strmm(case 1698)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha = 0.1f;\n   float A[] = { -0.675f, 0.283f, 0.785f, -0.0f, -0.592f, -0.661f, 0.149f, -0.129f, 0.149f };\n   int lda = 3;\n   float B[] = { 0.964f, -0.575f, -0.215f, 0.953f, 0.527f, -0.418f };\n   int ldb = 2;\n   float B_expected[] = { 0.104252f, -0.0637282f, -0.0282983f, 0.100692f, 0.0527f, -0.0418f };\n   cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strmm(case 1699)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha = 0.1f;\n   float A[] = { -0.225f, -0.943f, 0.839f, 0.759f, 0.752f, 0.807f, 0.288f, -0.276f, 0.434f };\n   int lda = 3;\n   float B[] = { -0.234f, 0.275f, 0.658f, -0.423f, -0.807f, -0.683f };\n   int ldb = 2;\n   float B_expected[] = { 0.005265f, -0.0061875f, 0.0715478f, -0.0577421f, -0.0015558f, -0.0407058f };\n   cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strmm(case 1700)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha = 0.1f;\n   float A[] = { -0.043f, -0.983f, 0.479f, -0.136f, 0.048f, 0.745f, -0.408f, -0.731f, -0.953f };\n   int lda = 3;\n   float B[] = { 0.917f, 0.682f, -0.32f, 0.557f, -0.302f, 0.989f };\n   int ldb = 2;\n   float B_expected[] = { 0.0917f, 0.0682f, -0.122141f, -0.0113406f, -0.0101157f, 0.173064f };\n   cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], flteps, \"strmm(case 1701)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha = 0;\n   double A[] = { -0.561, -0.114, -0.148, 0.488 };\n   int lda = 2;\n   double B[] = { 0.684, 0.38, 0.419, -0.361, 0.378, -0.423 };\n   int ldb = 3;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrmm(case 1702)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha = 0;\n   double A[] = { -0.378, 0.607, 0.41, 0.418 };\n   int lda = 2;\n   double B[] = { 0.146, -0.688, -0.953, -0.983, 0.237, 0.128 };\n   int ldb = 3;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrmm(case 1703)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha = 0;\n   double A[] = { -0.31, 0.277, -0.587, 0.885 };\n   int lda = 2;\n   double B[] = { -0.221, -0.831, -0.319, -0.547, -0.577, 0.295 };\n   int ldb = 3;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrmm(case 1704)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha = 0;\n   double A[] = { -0.577, 0.861, -0.439, -0.916 };\n   int lda = 2;\n   double B[] = { -0.933, -0.582, 0.528, 0.268, -0.804, 0.62 };\n   int ldb = 3;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrmm(case 1705)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha = 0;\n   double A[] = { -0.824, -0.119, -0.399, -0.653 };\n   int lda = 2;\n   double B[] = { 0.452, -0.168, 0.256, 0.554, 0.342, 0.318 };\n   int ldb = 2;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrmm(case 1706)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha = 0;\n   double A[] = { -0.299, 0.837, -0.03, 0.552 };\n   int lda = 2;\n   double B[] = { -0.83, -0.82, -0.362, -0.252, -0.062, -0.942 };\n   int ldb = 2;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrmm(case 1707)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha = 0;\n   double A[] = { -0.545, -0.107, 0.096, 0.183 };\n   int lda = 2;\n   double B[] = { -0.43, 0.841, 0.035, 0.7, 0.637, 0.095 };\n   int ldb = 2;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrmm(case 1708)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha = 0;\n   double A[] = { 0.626, 0.123, -0.959, 0.971 };\n   int lda = 2;\n   double B[] = { 0.185, -0.218, -0.074, 0.49, 0.802, -0.454 };\n   int ldb = 2;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrmm(case 1709)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha = 0;\n   double A[] = { -0.131, 0.048, 0.148, 0.834, -0.98, -0.009, -0.727, 0.241, 0.276 };\n   int lda = 3;\n   double B[] = { 0.75, -0.664, -0.136, -0.793, -0.742, 0.126 };\n   int ldb = 3;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrmm(case 1710)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha = 0;\n   double A[] = { 0.431, -0.387, 0.427, 0.495, 0.282, 0.158, -0.335, 0.535, -0.978 };\n   int lda = 3;\n   double B[] = { 0.518, -0.489, 0.899, -0.375, 0.376, -0.831 };\n   int ldb = 3;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrmm(case 1711)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha = 0;\n   double A[] = { -0.669, -0.976, -0.2, 0.661, -0.975, -0.965, -0.861, -0.779, -0.73 };\n   int lda = 3;\n   double B[] = { 0.31, 0.023, -0.853, 0.632, -0.174, 0.608 };\n   int ldb = 3;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrmm(case 1712)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha = 0;\n   double A[] = { 0.153, -0.408, -0.127, -0.634, -0.384, -0.815, 0.051, -0.096, 0.476 };\n   int lda = 3;\n   double B[] = { 0.343, -0.665, -0.348, 0.748, 0.893, 0.91 };\n   int ldb = 3;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrmm(case 1713)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha = 0;\n   double A[] = { -0.918, -0.19, 0.829, 0.942, 0.885, 0.087, 0.321, 0.67, -0.475 };\n   int lda = 3;\n   double B[] = { 0.377, 0.931, 0.291, -0.603, -0.617, 0.402 };\n   int ldb = 2;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrmm(case 1714)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha = 0;\n   double A[] = { -0.598, -0.232, -0.64, 0.595, 0.642, -0.921, -0.679, -0.846, -0.921 };\n   int lda = 3;\n   double B[] = { 0.032, -0.036, -0.278, -0.83, 0.922, -0.701 };\n   int ldb = 2;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrmm(case 1715)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha = 0;\n   double A[] = { 0.341, -0.858, -0.559, 0.499, -0.114, 0.57, 0.847, -0.612, 0.593 };\n   int lda = 3;\n   double B[] = { 0.672, 0.292, 0.752, 0.842, 0.625, 0.967 };\n   int ldb = 2;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrmm(case 1716)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha = 0;\n   double A[] = { 0.958, 0.823, -0.181, 0.141, 0.932, 0.097, -0.636, 0.844, 0.205 };\n   int lda = 3;\n   double B[] = { 0.113, -0.658, 0.703, -0.023, -0.384, 0.439 };\n   int ldb = 2;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrmm(case 1717)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha = 0;\n   double A[] = { 0.675, -0.468, -0.564, 0.71 };\n   int lda = 2;\n   double B[] = { -0.401, -0.823, 0.342, -0.384, 0.344, 0.18 };\n   int ldb = 3;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrmm(case 1718)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha = 0;\n   double A[] = { 0.932, -0.388, 0.432, -0.167 };\n   int lda = 2;\n   double B[] = { -0.624, 0.023, 0.065, 0.678, 0.044, -0.472 };\n   int ldb = 3;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrmm(case 1719)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha = 0;\n   double A[] = { -0.738, 0.649, -0.171, -0.462 };\n   int lda = 2;\n   double B[] = { -0.277, -0.519, -0.501, -0.024, -0.767, -0.591 };\n   int ldb = 3;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrmm(case 1720)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha = 0;\n   double A[] = { -0.17, -0.184, -0.243, 0.907 };\n   int lda = 2;\n   double B[] = { 0.593, 0.131, -0.317, -0.254, -0.948, 0.002 };\n   int ldb = 3;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrmm(case 1721)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha = 0;\n   double A[] = { 0.06, -0.838, -0.455, -0.715 };\n   int lda = 2;\n   double B[] = { -0.423, 0.665, -0.023, -0.872, -0.313, -0.698 };\n   int ldb = 2;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrmm(case 1722)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha = 0;\n   double A[] = { -0.506, 0.792, 0.338, -0.155 };\n   int lda = 2;\n   double B[] = { -0.257, -0.19, 0.201, 0.685, 0.663, 0.302 };\n   int ldb = 2;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrmm(case 1723)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha = 0;\n   double A[] = { 0.739, -0.996, 0.182, 0.626 };\n   int lda = 2;\n   double B[] = { 0.009, 0.485, -0.633, -0.08, -0.579, 0.223 };\n   int ldb = 2;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrmm(case 1724)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha = 0;\n   double A[] = { 0.777, 0.723, 0.378, 0.98 };\n   int lda = 2;\n   double B[] = { 0.291, -0.267, -0.076, 0.103, -0.021, -0.866 };\n   int ldb = 2;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrmm(case 1725)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha = 0;\n   double A[] = { -0.771, 0.469, 0.822, -0.619, 0.953, -0.706, 0.318, 0.559, -0.68 };\n   int lda = 3;\n   double B[] = { -0.32, 0.362, 0.719, -0.661, -0.504, 0.595 };\n   int ldb = 3;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrmm(case 1726)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha = 0;\n   double A[] = { 0.073, -0.501, -0.561, -0.229, -0.533, -0.138, 0.924, -0.164, -0.023 };\n   int lda = 3;\n   double B[] = { -0.208, 0.49, 0.827, 0.641, -0.884, -0.624 };\n   int ldb = 3;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrmm(case 1727)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha = 0;\n   double A[] = { 0.33, -0.649, -0.43, -0.266, 0.787, 0.449, 0.435, -0.774, -0.447 };\n   int lda = 3;\n   double B[] = { -0.687, -0.459, 0.189, 0.762, -0.039, 0.047 };\n   int ldb = 3;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrmm(case 1728)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha = 0;\n   double A[] = { 0.981, 0.242, 0.581, 0.064, 0.792, -0.529, 0.461, 0.224, -0.419 };\n   int lda = 3;\n   double B[] = { 0.285, 0.274, -0.912, 0.601, 0.24, 0.06 };\n   int ldb = 3;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrmm(case 1729)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha = 0;\n   double A[] = { -0.582, 0.269, -0.587, 0.68, -0.59, -0.936, 0.236, -0.728, -0.434 };\n   int lda = 3;\n   double B[] = { 0.113, 0.468, 0.943, 0.48, 0.215, -0.525 };\n   int ldb = 2;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrmm(case 1730)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha = 0;\n   double A[] = { -0.344, -0.938, 0.556, -0.678, -0.612, -0.519, -0.578, -0.848, 0.699 };\n   int lda = 3;\n   double B[] = { 0.915, -0.118, 0.538, -0.186, -0.413, -0.216 };\n   int ldb = 2;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrmm(case 1731)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha = 0;\n   double A[] = { -0.843, 0.54, -0.892, -0.296, 0.786, 0.136, 0.731, -0.418, -0.118 };\n   int lda = 3;\n   double B[] = { -0.775, 0.5, -0.399, -0.709, 0.779, 0.774 };\n   int ldb = 2;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrmm(case 1732)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha = 0;\n   double A[] = { -0.765, 0.233, 0.318, 0.547, -0.469, 0.023, -0.867, 0.687, -0.912 };\n   int lda = 3;\n   double B[] = { 0.019, -0.145, 0.472, 0.333, 0.527, -0.224 };\n   int ldb = 2;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[i], B_expected[i], dbleps, \"dtrmm(case 1733)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.1f};\n   float A[] = { -0.852f, -0.409f, 0.871f, -0.854f, -0.493f, 0.444f, 0.973f, 0.027f };\n   int lda = 2;\n   float B[] = { -0.561f, 0.132f, 0.689f, 0.653f, -0.758f, -0.109f, -0.596f, 0.395f, -0.561f, 0.378f, 0.21f, 0.51f };\n   int ldb = 3;\n   float B_expected[] = { -0.0970014f, 0.0350174f, 0.0029825f, -0.048577f, -0.066776f, 0.121969f, -0.0368243f, -0.0590573f, -0.0352647f, -0.0556059f, -0.05019f, 0.019056f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1734) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1734) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.1f};\n   float A[] = { 0.349f, 0.0f, -0.462f, 0.91f, -0.693f, 0.587f, -0.617f, 0.112f };\n   int lda = 2;\n   float B[] = { 0.842f, -0.473f, 0.825f, 0.866f, 0.986f, 0.686f, 0.346f, 0.299f, -0.659f, 0.009f, 0.007f, -0.478f };\n   int ldb = 3;\n   float B_expected[] = { 0.0296278f, 0.0410058f, -0.0262152f, 0.112127f, -0.0913206f, 0.141775f, -0.0299f, 0.0346f, -0.0009f, -0.0659f, 0.0478f, 0.0007f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1735) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1735) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.1f};\n   float A[] = { 0.661f, -0.823f, 0.28f, 0.171f, 0.267f, 0.66f, 0.844f, 0.472f };\n   int lda = 2;\n   float B[] = { -0.256f, -0.518f, -0.933f, 0.066f, -0.513f, -0.286f, 0.109f, 0.372f, -0.183f, 0.482f, 0.362f, -0.436f };\n   int ldb = 3;\n   float B_expected[] = { 0.013171f, -0.059553f, -0.0811485f, -0.0562395f, -0.0233153f, -0.0574471f, -0.005815f, 0.018994f, 0.0277726f, -0.0674627f, 0.0612062f, 0.0563109f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1736) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1736) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.1f};\n   float A[] = { 0.623f, 0.314f, -0.594f, 0.717f, 0.566f, 0.001f, -0.411f, -0.387f };\n   int lda = 2;\n   float B[] = { -0.083f, 0.937f, -0.814f, 0.9f, -0.042f, 0.678f, -0.928f, 0.228f, 0.965f, -0.16f, 0.006f, -0.281f };\n   int ldb = 3;\n   float B_expected[] = { -0.0937f, -0.0083f, -0.09f, -0.0814f, -0.0678f, -0.0042f, -0.0758259f, -0.0975915f, -0.0348586f, 0.0503376f, -0.0102706f, -0.001845f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1737) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1737) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.1f};\n   float A[] = { -0.247f, -0.582f, 0.651f, -0.534f, -0.491f, 0.346f, 0.936f, -0.227f };\n   int lda = 2;\n   float B[] = { -0.002f, -0.02f, 0.162f, -0.62f, 0.632f, -0.07f, 0.352f, 0.042f, 0.574f, 0.272f, -0.139f, 0.012f };\n   int ldb = 2;\n   float B_expected[] = { -0.0366576f, 0.0123832f, 0.0617094f, 0.0010892f, 0.0249364f, -0.0384208f, 0.0040592f, 0.0339006f, 0.0455238f, 0.0080623f, -0.0042785f, -0.012738f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1738) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1738) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.1f};\n   float A[] = { -0.152f, 0.395f, -0.077f, -0.191f, -0.757f, 0.858f, -0.494f, -0.734f };\n   int lda = 2;\n   float B[] = { -0.166f, -0.413f, -0.373f, 0.915f, -0.824f, -0.066f, -0.114f, -0.921f, 0.862f, 0.312f, 0.221f, 0.699f };\n   int ldb = 2;\n   float B_expected[] = { 0.142569f, -0.0668709f, -0.0915f, -0.0373f, -0.0533385f, 0.0052516f, 0.0921f, -0.0114f, 0.0027525f, 0.0094961f, -0.0699f, 0.0221f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1739) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1739) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.1f};\n   float A[] = { -0.426f, 0.817f, -0.993f, -0.882f, 0.615f, 0.627f, -0.238f, -0.903f };\n   int lda = 2;\n   float B[] = { 0.895f, 0.849f, 0.811f, 0.402f, 0.074f, -0.493f, -0.548f, -0.82f, 0.323f, 0.301f, 0.612f, -0.092f };\n   int ldb = 2;\n   float B_expected[] = { -0.0369541f, -0.10749f, 0.246046f, 0.0030071f, -0.0270476f, 0.0371257f, -0.111428f, -0.111834f, -0.0135665f, -0.0383515f, 0.111452f, -0.0283989f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1740) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1740) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.1f};\n   float A[] = { -0.451f, -0.754f, -0.673f, 0.433f, -0.712f, -0.033f, -0.588f, 0.116f };\n   int lda = 2;\n   float B[] = { 0.787f, -0.377f, -0.854f, -0.464f, 0.118f, 0.231f, 0.362f, -0.457f, -0.076f, 0.373f, -0.286f, -0.468f };\n   int ldb = 2;\n   float B_expected[] = { 0.0377f, 0.0787f, -0.0130492f, -0.122041f, -0.0231f, 0.0118f, 0.0561369f, 0.0182563f, -0.0373f, -0.0076f, 0.0751937f, -0.0396361f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1741) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1741) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.1f};\n   float A[] = { -0.454f, 0.494f, 0.424f, -0.907f, 0.339f, -0.141f, 0.169f, 0.364f, -0.607f, 0.955f, -0.156f, 0.962f, -0.254f, 0.079f, 0.209f, 0.946f, 0.93f, 0.677f };\n   int lda = 3;\n   float B[] = { -0.99f, -0.484f, 0.915f, -0.383f, 0.228f, 0.797f, 0.597f, 0.765f, -0.629f, 0.002f, -0.89f, 0.077f };\n   int ldb = 3;\n   float B_expected[] = { 0.0269324f, 0.0688556f, -0.179902f, -0.104839f, -0.181106f, -0.0505677f, 0.0052392f, -0.0648948f, 0.0819028f, 0.132688f, 0.0961172f, -0.0473381f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1742) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1742) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.1f};\n   float A[] = { -0.008f, -0.654f, 0.174f, 0.448f, 0.388f, -0.108f, -0.479f, -0.708f, -0.035f, 0.816f, 0.487f, 0.22f, -0.482f, 0.57f, -0.317f, 0.203f, -0.547f, -0.415f };\n   int lda = 3;\n   float B[] = { 0.651f, 0.187f, 0.591f, -0.007f, 0.171f, -0.923f, -0.029f, -0.685f, -0.049f, 0.135f, 0.578f, 0.979f };\n   int ldb = 3;\n   float B_expected[] = { -0.0187f, 0.0651f, -0.0317186f, 0.0620498f, 0.0794141f, 0.0733141f, 0.0685f, -0.0029f, -0.0002818f, 0.0252834f, -0.0771317f, 0.0439205f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1743) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1743) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.1f};\n   float A[] = { 0.952f, 0.29f, 0.944f, 0.294f, -0.762f, -0.7f, -0.949f, 0.167f, 0.307f, 0.904f, -0.428f, -0.411f, 0.496f, 0.004f, -0.611f, -0.09f, -0.846f, 0.081f };\n   int lda = 3;\n   float B[] = { 0.782f, -0.035f, -0.441f, -0.791f, -0.09f, -0.56f, -0.438f, -0.691f, 0.88f, 0.545f, -0.55f, 0.595f };\n   int ldb = 3;\n   float B_expected[] = { -0.0592352f, 0.126282f, 0.0291241f, 0.0584267f, -0.046647f, 0.01215f, 0.0862177f, -0.14179f, -0.064879f, 0.016708f, 0.054792f, 0.0417105f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1744) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1744) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.1f};\n   float A[] = { -0.519f, 0.708f, -0.934f, -0.219f, 0.376f, -0.967f, 0.322f, -0.355f, 0.972f, -0.156f, -0.735f, 0.928f, 0.084f, -0.267f, -0.152f, 0.434f, 0.267f, 0.983f };\n   int lda = 3;\n   float B[] = { -0.54f, 0.149f, 0.574f, 0.742f, 0.704f, 0.459f, -0.9f, 0.04f, 0.538f, -0.858f, 0.467f, 0.686f };\n   int ldb = 3;\n   float B_expected[] = { -0.0034742f, 0.0089927f, -0.0977768f, 0.0267786f, -0.0459f, 0.0704f, 0.0494331f, -0.0808964f, 0.0759594f, 0.0169292f, -0.0686f, 0.0467f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1745) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1745) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.1f};\n   float A[] = { -0.541f, 0.67f, 0.014f, 0.446f, 0.086f, -0.525f, 0.033f, -0.932f, 0.977f, 0.321f, -0.651f, 0.027f, 0.409f, 0.328f, 0.359f, -0.615f, 0.419f, -0.25f };\n   int lda = 3;\n   float B[] = { -0.156f, 0.666f, -0.231f, 0.691f, 0.935f, -0.481f, -0.142f, -0.117f, 0.529f, 0.526f, 0.266f, 0.417f };\n   int ldb = 2;\n   float B_expected[] = { 0.0464826f, -0.0361824f, 0.0528601f, -0.0337999f, 0.0002432f, 0.168346f, -0.0078204f, 0.0535212f, 0.0438334f, 0.0110749f, -0.0360401f, -0.0228356f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1746) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1746) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.1f};\n   float A[] = { -0.459f, -0.349f, -0.335f, 0.008f, 0.866f, 0.978f, -0.869f, -0.361f, -0.711f, 0.712f, 0.207f, 0.305f, 0.766f, -0.262f, 0.012f, -0.333f, 0.617f, 0.91f };\n   int lda = 3;\n   float B[] = { -0.138f, -0.256f, -0.319f, -0.771f, 0.674f, -0.565f, -0.779f, -0.516f, -0.017f, -0.097f, -0.555f, 0.308f };\n   int ldb = 2;\n   float B_expected[] = { 0.0256f, -0.0138f, 0.0771f, -0.0319f, 0.0292718f, 0.0701506f, -0.0269158f, -0.078012f, 0.0488162f, -0.0369837f, -0.0054207f, -0.118253f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1747) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1747) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.1f};\n   float A[] = { -0.825f, -0.785f, -0.605f, -0.508f, 0.763f, -0.578f, -0.167f, -0.233f, 0.011f, -0.853f, 0.24f, 0.192f, 0.293f, -0.72f, -0.348f, 0.023f, -0.145f, -0.493f };\n   int lda = 3;\n   float B[] = { 0.305f, -0.255f, 0.882f, 0.883f, 0.088f, -0.473f, 0.135f, -0.063f, -0.671f, 0.473f, 0.874f, 0.548f };\n   int ldb = 2;\n   float B_expected[] = { -0.0961148f, -0.0983903f, 0.153836f, 0.0835432f, 0.0095579f, -0.0654357f, -0.018348f, 0.005229f, -0.0262218f, 0.0330484f, 0.0510342f, 0.0143434f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1748) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1748) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.1f};\n   float A[] = { 0.63f, 0.353f, 0.445f, 0.845f, 0.273f, -0.135f, 0.03f, 0.936f, 0.141f, 0.638f, -0.399f, 0.343f, -0.037f, -0.335f, -0.089f, 0.081f, 0.987f, -0.256f };\n   int lda = 3;\n   float B[] = { -0.567f, 0.803f, 0.168f, 0.744f, -0.328f, 0.835f, -0.852f, 0.702f, 0.21f, -0.618f, 0.666f, -0.303f };\n   int ldb = 2;\n   float B_expected[] = { -0.0700351f, -0.144464f, -0.0163821f, -0.0663417f, -0.115361f, -0.0199816f, -0.105134f, -0.10138f, 0.0618f, 0.021f, 0.0303f, 0.0666f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1749) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1749) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.1f};\n   float A[] = { -0.741f, 0.904f, -0.599f, 0.753f, -0.297f, 0.38f, -0.056f, -0.715f };\n   int lda = 2;\n   float B[] = { 0.646f, -0.447f, -0.147f, 0.314f, -0.713f, 0.187f, -0.589f, 0.287f, -0.809f, -0.293f, 0.418f, 0.778f };\n   int ldb = 3;\n   float B_expected[] = { -0.0915211f, -0.0074598f, 0.0365562f, -0.0174929f, 0.0783119f, 0.0359285f, -0.115925f, 0.0187826f, -0.0296066f, -0.031258f, 0.099134f, 0.0819138f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1750) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1750) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.1f};\n   float A[] = { -0.645f, 0.756f, 0.709f, -0.657f, -0.023f, -0.714f, 0.03f, 0.239f };\n   int lda = 2;\n   float B[] = { -0.16f, 0.254f, -0.68f, 0.183f, -0.402f, -0.259f, 0.104f, -0.09f, 0.944f, 0.729f, -0.378f, -0.792f };\n   int ldb = 3;\n   float B_expected[] = { -0.0254f, -0.016f, -0.0183f, -0.068f, 0.0259f, -0.0402f, -0.0195206f, 0.0157438f, -0.130551f, 0.0582111f, 0.0711517f, -0.0833181f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1751) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1751) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.1f};\n   float A[] = { 0.25f, -0.038f, 0.377f, -0.209f, 0.166f, -0.073f, -0.24f, 0.938f };\n   int lda = 2;\n   float B[] = { 0.26f, 0.696f, -0.183f, 0.668f, -0.08f, -0.938f, -0.837f, -0.509f, 0.781f, -0.063f, -0.953f, 0.227f };\n   int ldb = 3;\n   float B_expected[] = { -0.0140727f, -0.0084651f, -0.0106483f, 0.0104681f, 0.0124209f, -0.0197271f, 0.0662946f, 0.0678322f, -0.0747698f, -0.0128346f, 0.0948394f, 0.0015794f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1752) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1752) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.1f};\n   float A[] = { -0.668f, 0.804f, 0.608f, -0.682f, -0.513f, 0.521f, 0.878f, -0.664f };\n   int lda = 2;\n   float B[] = { -0.871f, 0.699f, 0.561f, 0.823f, -0.787f, 0.055f, -0.686f, 0.361f, -0.662f, -0.192f, -0.301f, -0.167f };\n   int ldb = 3;\n   float B_expected[] = { -0.0156401f, -0.0707163f, -0.0576594f, 0.100064f, 0.001615f, -0.054558f, -0.0361f, -0.0686f, 0.0192f, -0.0662f, 0.0167f, -0.0301f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1753) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1753) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.1f};\n   float A[] = { 0.091f, 0.189f, -0.221f, 0.749f, 0.354f, -0.397f, 0.105f, -0.944f };\n   int lda = 2;\n   float B[] = { 0.731f, -0.446f, 0.983f, 0.793f, 0.533f, 0.386f, -0.781f, -0.063f, 0.875f, -0.128f, -0.179f, -0.079f };\n   int ldb = 2;\n   float B_expected[] = { -0.0097573f, 0.0150815f, 0.129278f, 0.0933519f, -0.0135863f, -0.0024451f, -0.0655692f, 0.0200447f, -0.0153727f, 0.0103817f, 0.0232006f, 0.0165563f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1754) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1754) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.1f};\n   float A[] = { 0.676f, 0.644f, 0.03f, 0.456f, 0.002f, -0.909f, 0.984f, 0.771f };\n   int lda = 2;\n   float B[] = { 0.65f, 0.005f, -0.883f, -0.154f, -0.137f, -0.137f, 0.531f, -0.49f, 0.052f, 0.273f, -0.602f, 0.655f };\n   int ldb = 2;\n   float B_expected[] = { -0.0005f, 0.065f, 0.074484f, -0.0877155f, 0.0137f, -0.0137f, 0.0365741f, 0.0406193f, -0.0273f, 0.0052f, -0.0608278f, -0.0353739f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1755) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1755) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.1f};\n   float A[] = { 0.832f, -0.559f, 0.188f, -0.488f, -0.051f, -0.057f, 0.909f, 0.006f };\n   int lda = 2;\n   float B[] = { -0.408f, 0.303f, 0.03f, 0.529f, -0.584f, -0.976f, 0.443f, -0.762f, 0.43f, 0.812f, -0.075f, 0.06f };\n   int ldb = 2;\n   float B_expected[] = { -0.056498f, 0.0093713f, -0.0481041f, 0.0024096f, 0.0845016f, -0.132004f, 0.069f, 0.0407259f, -0.0483094f, 0.0826848f, -0.005409f, -0.0068535f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1756) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1756) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.1f};\n   float A[] = { -0.15f, -0.297f, 0.821f, -0.576f, -0.572f, 0.924f, 0.106f, -0.131f };\n   int lda = 2;\n   float B[] = { -0.271f, 0.793f, -0.232f, -0.967f, -0.466f, 0.37f, -0.745f, -0.156f, -0.091f, -0.877f, 0.595f, 0.448f };\n   int ldb = 2;\n   float B_expected[] = { -0.0132725f, -0.101846f, 0.0967f, -0.0232f, -0.0671044f, -0.11675f, 0.0156f, -0.0745f, 0.0851912f, 0.0655543f, -0.0448f, 0.0595f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1757) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1757) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.1f};\n   float A[] = { 0.002f, 0.0f, 0.626f, -0.148f, 0.874f, 0.229f, -0.227f, -0.55f, -0.895f, 0.586f, 0.934f, 0.618f, 0.958f, -0.543f, 0.49f, 0.671f, -0.871f, 0.227f };\n   int lda = 3;\n   float B[] = { -0.415f, 0.156f, -0.539f, -0.247f, -0.725f, 0.932f, 0.565f, 0.454f, -0.118f, 0.693f, -0.968f, -0.601f };\n   int ldb = 3;\n   float B_expected[] = { -0.0574005f, -0.122188f, -0.0327649f, -0.0625979f, 0.0976347f, 0.0419911f, 0.0294756f, -0.0678577f, 0.184894f, -0.0833182f, -0.0303735f, 0.0979555f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1758) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1758) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.1f};\n   float A[] = { 0.89f, 0.309f, -0.786f, 0.999f, 0.511f, 0.599f, 0.385f, -0.615f, 0.527f, -0.328f, -0.078f, -0.666f, 0.004f, -0.69f, -0.281f, -0.438f, 0.456f, 0.524f };\n   int lda = 3;\n   float B[] = { -0.648f, -0.189f, -0.295f, 0.477f, 0.509f, 0.685f, 0.875f, 0.277f, -0.34f, -0.632f, -0.453f, -0.798f };\n   int ldb = 3;\n   float B_expected[] = { 0.0203701f, -0.104287f, -0.0084576f, 0.0121508f, -0.0685f, 0.0509f, 0.0245033f, 0.202013f, 0.0268058f, -0.0836134f, 0.0798f, -0.0453f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1759) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1759) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.1f};\n   float A[] = { 0.772f, 0.686f, 0.693f, 0.803f, -0.328f, -0.627f, -0.869f, -0.656f, -0.055f, -0.366f, -0.981f, -0.151f, 0.147f, -0.368f, -0.824f, -0.454f, -0.445f, -0.794f };\n   int lda = 3;\n   float B[] = { -0.268f, -0.521f, -0.685f, -0.618f, 0.508f, 0.525f, -0.492f, -0.502f, -0.997f, 0.28f, 0.63f, 0.664f };\n   int ldb = 3;\n   float B_expected[] = { 0.058606f, 0.015051f, -0.0913257f, -0.0297397f, -0.0205282f, 0.0243534f, 0.0725056f, -0.0035452f, -0.110849f, 0.0255551f, 0.046652f, 0.0938454f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1760) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1760) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.1f};\n   float A[] = { -0.317f, -0.822f, 0.732f, 0.383f, 0.457f, 0.443f, 0.529f, -0.949f, -0.927f, -0.65f, -0.471f, -0.624f, -0.731f, 0.107f, -0.142f, 0.623f, 0.159f, -0.419f };\n   int lda = 3;\n   float B[] = { 0.292f, -0.665f, -0.93f, 0.517f, 0.123f, -0.181f, 0.325f, 0.954f, -0.988f, -0.128f, 0.637f, -0.997f };\n   int ldb = 3;\n   float B_expected[] = { 0.0665f, 0.0292f, 0.0111893f, -0.140662f, 0.0316445f, -0.0209328f, -0.0954f, 0.0325f, -0.0068241f, 0.0089271f, 0.225695f, 0.0517387f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1761) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1761) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.1f};\n   float A[] = { -0.809f, 0.393f, -0.015f, -0.273f, -0.956f, 0.49f, 0.365f, -0.386f, 0.941f, 0.992f, 0.297f, 0.761f, 0.425f, -0.605f, 0.672f, 0.725f, -0.077f, -0.628f };\n   int lda = 3;\n   float B[] = { 0.21f, 0.153f, 0.218f, -0.129f, 0.736f, -0.006f, 0.502f, -0.165f, 0.242f, 0.915f, 0.67f, 0.07f };\n   int ldb = 2;\n   float B_expected[] = { 0.0085068f, 0.069273f, 0.0439562f, 0.0320975f, -0.15148f, 0.0197777f, -0.0875509f, 0.103555f, 0.0222431f, 0.0555986f, 0.042615f, -0.000763f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1762) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1762) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.1f};\n   float A[] = { -0.187f, -0.508f, -0.987f, -0.861f, 0.519f, 0.752f, -0.117f, 0.972f, 0.068f, -0.752f, 0.344f, 0.074f, -0.343f, 0.0f, -0.876f, 0.857f, -0.148f, -0.933f };\n   int lda = 3;\n   float B[] = { 0.827f, 0.958f, 0.395f, 0.878f, 0.88f, -0.896f, -0.771f, -0.355f, -0.979f, 0.329f, -0.166f, -0.644f };\n   int ldb = 2;\n   float B_expected[] = { -0.180535f, 0.193075f, -0.0391015f, 0.0887205f, 0.202321f, 0.145565f, -0.0066882f, -0.0073676f, -0.0329f, -0.0979f, 0.0644f, -0.0166f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1763) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1763) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.1f};\n   float A[] = { -0.622f, 0.022f, -0.966f, 0.704f, 0.43f, -0.451f, -0.221f, 0.969f, 0.977f, 0.021f, -0.725f, -0.382f, 0.779f, 0.957f, 0.25f, 0.832f, 0.029f, -0.903f };\n   int lda = 3;\n   float B[] = { 0.315f, -0.297f, -0.864f, 0.519f, -0.601f, -0.119f, 0.028f, 0.072f, -0.171f, 0.648f, 0.159f, -0.623f };\n   int ldb = 2;\n   float B_expected[] = { -0.0191664f, -0.0189396f, 0.0341826f, 0.052599f, -0.0379778f, -0.067988f, 0.103868f, 0.0495092f, -0.0219287f, 0.0971955f, -0.0388294f, -0.0688205f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1764) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1764) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.1f};\n   float A[] = { 0.106f, 0.87f, 0.21f, 0.463f, -0.496f, -0.981f, -0.354f, -0.604f, -0.149f, -0.384f, -0.958f, -0.502f, -0.579f, 0.736f, -0.322f, 0.028f, 0.193f, 0.14f };\n   int lda = 3;\n   float B[] = { -0.812f, 0.518f, 0.085f, -0.447f, -0.443f, 0.928f, -0.972f, 0.889f, 0.605f, -0.258f, -0.025f, 0.98f };\n   int ldb = 2;\n   float B_expected[] = { -0.0518f, -0.0812f, 0.0447f, 0.0085f, -0.0660824f, -0.0853354f, -0.0834485f, -0.0747189f, 0.0384994f, 0.240616f, -0.0754609f, 0.0871787f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1765) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1765) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int trans = 113;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.0f};\n   float A[] = { -0.553f, 0.204f, -0.793f, -0.558f, 0.741f, 0.26f, 0.945f, -0.757f };\n   int lda = 2;\n   float B[] = { -0.515f, 0.532f, -0.321f, 0.326f, -0.81f, -0.924f, 0.474f, 0.985f, -0.03f, 0.406f, 0.923f, -0.956f };\n   int ldb = 3;\n   float B_expected[] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1766) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1766) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int trans = 113;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.0f};\n   float A[] = { -0.41f, -0.804f, 0.988f, -0.715f, -0.281f, -0.89f, 0.389f, -0.408f };\n   int lda = 2;\n   float B[] = { 0.917f, 0.541f, -0.108f, -0.965f, 0.524f, 0.04f, -0.736f, -0.643f, -0.202f, 0.86f, 0.346f, -0.017f };\n   int ldb = 3;\n   float B_expected[] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1767) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1767) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int trans = 113;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.0f};\n   float A[] = { 0.153f, -0.812f, -0.742f, -0.18f, 0.473f, 0.023f, -0.433f, 0.559f };\n   int lda = 2;\n   float B[] = { 0.078f, -0.691f, -0.717f, -0.637f, -0.016f, 0.375f, -0.902f, -0.343f, 0.155f, 0.563f, 0.419f, 0.451f };\n   int ldb = 3;\n   float B_expected[] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1768) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1768) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int trans = 113;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.0f};\n   float A[] = { -0.288f, 0.241f, 0.593f, -0.597f, -0.469f, 0.735f, 0.193f, -0.104f };\n   int lda = 2;\n   float B[] = { -0.835f, 0.037f, -0.762f, 0.782f, -0.874f, -0.867f, -0.81f, -0.577f, 0.352f, 0.827f, 0.237f, -0.861f };\n   int ldb = 3;\n   float B_expected[] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1769) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1769) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int trans = 113;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.0f};\n   float A[] = { 0.441f, -0.217f, 0.679f, 0.106f, -0.76f, -0.258f, -0.956f, -0.858f };\n   int lda = 2;\n   float B[] = { -0.802f, 0.163f, 0.293f, 0.54f, 0.228f, 0.071f, 0.942f, 0.345f, 0.591f, 0.654f, 0.382f, -0.892f };\n   int ldb = 2;\n   float B_expected[] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1770) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1770) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int trans = 113;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.0f};\n   float A[] = { 0.916f, 0.909f, 0.834f, 0.38f, 0.391f, -0.412f, -0.714f, -0.456f };\n   int lda = 2;\n   float B[] = { -0.151f, 0.818f, 0.717f, -0.812f, -0.649f, -0.107f, -0.454f, 0.785f, 0.86f, 0.992f, -0.244f, -0.242f };\n   int ldb = 2;\n   float B_expected[] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1771) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1771) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int trans = 113;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.0f};\n   float A[] = { -0.992f, 0.284f, -0.01f, 0.182f, 0.527f, -0.348f, -0.509f, 0.839f };\n   int lda = 2;\n   float B[] = { 0.504f, -0.782f, -0.88f, 0.079f, 0.216f, 0.525f, 0.198f, 0.851f, -0.102f, -0.046f, 0.079f, -0.045f };\n   int ldb = 2;\n   float B_expected[] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1772) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1772) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int trans = 113;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.0f};\n   float A[] = { 0.985f, 0.068f, -0.095f, -0.575f, -0.607f, 0.893f, 0.085f, 0.145f };\n   int lda = 2;\n   float B[] = { -0.149f, 0.592f, 0.588f, -0.62f, -0.409f, -0.344f, 0.263f, 0.759f, -0.026f, -0.609f, 0.507f, -0.084f };\n   int ldb = 2;\n   float B_expected[] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1773) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1773) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int trans = 113;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.0f};\n   float A[] = { 0.36f, 0.508f, -0.771f, -0.442f, -0.671f, -0.691f, -0.771f, 0.113f, 0.282f, 0.312f, 0.564f, -0.568f, -0.743f, 0.912f, -0.395f, 0.503f, -0.167f, -0.581f };\n   int lda = 3;\n   float B[] = { -0.018f, 0.574f, -0.144f, -0.758f, 0.53f, 0.623f, -0.771f, -0.733f, 0.932f, -0.192f, 0.997f, 0.773f };\n   int ldb = 3;\n   float B_expected[] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1774) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1774) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int trans = 113;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.0f};\n   float A[] = { -0.627f, 0.511f, -0.246f, -0.091f, 0.66f, -0.983f, 0.99f, 0.057f, -0.259f, 0.18f, 0.606f, 0.058f, -0.238f, 0.717f, 0.358f, -0.851f, -0.71f, -0.683f };\n   int lda = 3;\n   float B[] = { -0.907f, 0.956f, 0.56f, -0.057f, 0.054f, -0.77f, 0.868f, -0.843f, 0.645f, -0.554f, -0.958f, 0.988f };\n   int ldb = 3;\n   float B_expected[] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1775) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1775) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int trans = 113;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.0f};\n   float A[] = { -0.882f, 0.431f, -0.868f, -0.098f, -0.006f, -0.639f, 0.757f, -0.009f, -0.821f, 0.45f, 0.347f, 0.801f, 0.314f, 0.936f, -0.725f, 0.956f, 0.536f, 0.771f };\n   int lda = 3;\n   float B[] = { 0.38f, -0.435f, 0.977f, 0.296f, -0.624f, -0.53f, 0.73f, -0.837f, 0.105f, 0.189f, 0.362f, -0.664f };\n   int ldb = 3;\n   float B_expected[] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1776) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1776) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int trans = 113;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.0f};\n   float A[] = { 0.595f, -0.775f, 0.75f, 0.16f, -0.572f, 0.658f, 0.216f, 0.557f, -0.279f, 0.095f, -0.495f, 0.503f, 0.071f, -0.03f, -0.116f, 0.78f, -0.104f, 0.073f };\n   int lda = 3;\n   float B[] = { 0.948f, 0.749f, -0.854f, 0.972f, 0.704f, 0.187f, 0.347f, 0.303f, -0.865f, 0.123f, -0.041f, 0.152f };\n   int ldb = 3;\n   float B_expected[] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1777) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1777) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int trans = 113;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.0f};\n   float A[] = { -0.617f, -0.331f, -0.074f, 0.719f, -0.469f, -0.852f, 0.25f, -0.175f, -0.719f, -0.613f, -0.321f, 0.973f, -0.337f, -0.35f, 0.607f, -0.553f, 0.688f, 0.463f };\n   int lda = 3;\n   float B[] = { 0.568f, -0.471f, -0.947f, -0.205f, 0.835f, -0.859f, 0.27f, -0.599f, 0.171f, -0.514f, 0.939f, 0.176f };\n   int ldb = 2;\n   float B_expected[] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1778) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1778) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int trans = 113;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.0f};\n   float A[] = { 0.99f, -0.857f, 0.728f, -0.31f, -0.506f, -0.393f, 0.97f, 0.282f, 0.375f, -0.286f, -0.496f, -0.057f, 0.186f, -0.34f, 0.608f, -0.52f, 0.921f, -0.875f };\n   int lda = 3;\n   float B[] = { -0.929f, 0.885f, 0.864f, -0.548f, 0.393f, 0.391f, 0.033f, 0.186f, 0.949f, -0.435f, 0.986f, -0.995f };\n   int ldb = 2;\n   float B_expected[] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1779) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1779) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int trans = 113;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.0f};\n   float A[] = { -0.101f, -0.92f, 0.969f, -0.017f, -0.016f, -0.024f, -0.11f, 0.219f, -0.287f, -0.937f, 0.619f, 0.166f, -0.068f, 0.753f, 0.374f, 0.076f, 0.79f, -0.64f };\n   int lda = 3;\n   float B[] = { 0.255f, 0.564f, -0.478f, -0.818f, -0.043f, 0.224f, -0.268f, 0.253f, 0.021f, 0.654f, 0.98f, -0.774f };\n   int ldb = 2;\n   float B_expected[] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1780) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1780) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int trans = 113;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   float alpha[2] = {0.0f, 0.0f};\n   float A[] = { -0.068f, -0.603f, -0.055f, 0.14f, 0.664f, 0.987f, 0.861f, -0.691f, -0.897f, -0.778f, 0.516f, -0.073f, -0.156f, -0.42f, 0.57f, 0.628f, 0.116f, 0.344f };\n   int lda = 3;\n   float B[] = { 0.922f, 0.39f, -0.724f, 0.421f, 0.418f, 0.92f, -0.222f, 0.835f, 0.417f, -0.392f, 0.012f, -0.346f };\n   int ldb = 2;\n   float B_expected[] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };\n   cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], flteps, \"ctrmm(case 1781) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, \"ctrmm(case 1781) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {0, 0};\n   double A[] = { 0.904, 0.243, 0.206, 0.68, -0.946, 0.946, -0.675, 0.729 };\n   int lda = 2;\n   double B[] = { 0.427, 0.116, 0.916, -0.384, -0.372, -0.754, 0.148, 0.089, -0.924, 0.974, -0.307, -0.55 };\n   int ldb = 3;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1782) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1782) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {0, 0};\n   double A[] = { -0.898, 0.709, 0.719, -0.207, -0.841, -0.017, 0.202, -0.385 };\n   int lda = 2;\n   double B[] = { 0.308, 0.507, -0.838, 0.594, -0.811, 0.152, 0.118, -0.024, -0.632, 0.992, -0.942, 0.901 };\n   int ldb = 3;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1783) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1783) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {0, 0};\n   double A[] = { -0.849, 0.455, -0.273, -0.668, 0.196, -0.985, -0.39, 0.564 };\n   int lda = 2;\n   double B[] = { -0.874, 0.188, -0.039, 0.692, 0.33, 0.119, 0.012, 0.425, 0.787, -0.918, 0.739, -0.871 };\n   int ldb = 3;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1784) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1784) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {0, 0};\n   double A[] = { -0.325, 0.28, 0.902, -0.603, 0.091, -0.92, 0.209, -0.009 };\n   int lda = 2;\n   double B[] = { -0.202, -0.53, -0.88, -0.688, -0.215, 0.837, 0.917, 0.755, 0.477, 0.892, -0.524, -0.741 };\n   int ldb = 3;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1785) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1785) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {0, 0};\n   double A[] = { -0.756, 0.874, 0.56, 0.157, -0.831, -0.991, -0.531, 0.813 };\n   int lda = 2;\n   double B[] = { 0.271, 0.783, -0.861, 0.635, -0.088, 0.434, 0.256, -0.34, -0.724, -0.277, -0.604, 0.986 };\n   int ldb = 2;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1786) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1786) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {0, 0};\n   double A[] = { -0.371, -0.609, -0.812, -0.818, 0.45, -0.41, -0.704, -0.917 };\n   int lda = 2;\n   double B[] = { -0.268, 0.929, 0.82, 0.253, -0.883, 0.497, -0.265, 0.623, 0.131, -0.946, -0.365, 0.333 };\n   int ldb = 2;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1787) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1787) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {0, 0};\n   double A[] = { -0.265, 0.8, -0.676, -0.592, 0.78, -0.838, -0.651, 0.115 };\n   int lda = 2;\n   double B[] = { 0.942, 0.692, -0.516, 0.378, 0.028, 0.265, 0.289, -0.721, -0.25, -0.952, 0.463, -0.34 };\n   int ldb = 2;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1788) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1788) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {0, 0};\n   double A[] = { -0.852, -0.478, 0.16, 0.824, 0.073, 0.962, 0.509, -0.58 };\n   int lda = 2;\n   double B[] = { -0.789, 0.015, -0.779, -0.565, 0.048, -0.095, -0.272, 0.405, 0.272, 0.082, -0.693, -0.365 };\n   int ldb = 2;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1789) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1789) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {0, 0};\n   double A[] = { 0.251, 0.28, -0.092, 0.724, 0.928, -0.309, -0.222, -0.791, 0.113, -0.528, 0.148, 0.421, -0.833, 0.371, 0.354, 0.616, 0.313, 0.323 };\n   int lda = 3;\n   double B[] = { -0.769, -0.059, -0.068, 0.945, 0.938, -0.358, -0.17, 0.751, -0.248, -0.321, -0.818, 0.183 };\n   int ldb = 3;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1790) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1790) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {0, 0};\n   double A[] = { -0.707, -0.802, 0.13, -0.19, -0.564, -0.74, 0.118, -0.194, -0.124, -0.421, 0.665, 0.308, 0.505, -0.278, 0.588, 0.957, -0.727, 0.976 };\n   int lda = 3;\n   double B[] = { 0.153, -0.09, -0.4, 0.669, 0.689, -0.238, -0.259, 0.891, 0.993, 0.996, -0.829, -0.736 };\n   int ldb = 3;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1791) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1791) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {0, 0};\n   double A[] = { 0.83, 0.316, -0.099, 0.824, 0.767, 0.662, 0.244, 0.872, 0.35, 0.969, -0.084, 0.907, -0.752, -0.675, 0.129, -0.649, -0.539, 0.969 };\n   int lda = 3;\n   double B[] = { -0.145, 0.254, -0.497, -0.713, -0.742, 0.183, 0.272, -0.858, -0.606, -0.605, -0.807, 0.686 };\n   int ldb = 3;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1792) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1792) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {0, 0};\n   double A[] = { -0.091, 0.658, -0.834, -0.171, -0.126, -0.268, 0.879, -0.431, 0.678, -0.749, 0.136, -0.757, -0.578, 0.456, 0.978, -0.315, 0.333, 0.327 };\n   int lda = 3;\n   double B[] = { 0.963, -0.859, 0.599, 0.856, -0.924, 0.382, -0.531, 0.567, -0.454, 0.018, 0.97, 0.578 };\n   int ldb = 3;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1793) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1793) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {0, 0};\n   double A[] = { -0.849, -0.819, 0.673, 0.574, -0.869, -0.969, -0.338, -0.097, -0.601, 0.903, 0.634, 0.313, 0.228, -0.028, 0.419, -0.762, 0.21, -0.532 };\n   int lda = 3;\n   double B[] = { -0.283, 0.999, -0.356, -0.459, 0.508, -0.132, -0.804, 0.173, 0.779, -0.427, 0.019, 0.347 };\n   int ldb = 2;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1794) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1794) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {0, 0};\n   double A[] = { -0.117, -0.663, -0.95, -0.273, -0.497, -0.037, 0.084, -0.831, 0.023, -0.241, 0.063, -0.023, -0.498, -0.137, -0.77, 0.457, -0.021, -0.69 };\n   int lda = 3;\n   double B[] = { 0.308, -0.004, 0.013, 0.354, 0.077, -0.944, -0.877, 0.741, -0.807, -0.3, 0.891, -0.056 };\n   int ldb = 2;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1795) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1795) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {0, 0};\n   double A[] = { -0.964, -0.653, 0.379, 0.994, -0.378, -0.409, 0.24, -0.333, 0.558, -0.099, -0.402, -0.812, 0.421, 0.823, -0.771, 0.998, 0.697, 0.253 };\n   int lda = 3;\n   double B[] = { 0.34, 0.479, 0.539, -0.133, 0.876, -0.347, 0.706, -0.623, 0.399, 0.903, -0.7, -0.088 };\n   int ldb = 2;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1796) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1796) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int trans = 111;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {0, 0};\n   double A[] = { -0.104, 0.643, -0.253, -0.988, -0.051, -0.805, 0.451, -0.421, -0.177, -0.534, -0.714, -0.581, -0.177, -0.582, -0.57, 0.259, -0.66, -0.864 };\n   int lda = 3;\n   double B[] = { 0.636, -0.365, -0.107, -0.279, 0.425, 0.976, 0.657, 0.294, 0.827, 0.187, 0.353, 0.31 };\n   int ldb = 2;\n   double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1797) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1797) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { 0.273, 0.812, 0.295, -0.415, -0.227, 0.901, 0.623, 0.786 };\n   int lda = 2;\n   double B[] = { -0.539, -0.551, -0.969, 0.09, -0.581, -0.594, -0.833, 0.457, -0.284, 0.434, -0.459, -0.662 };\n   int ldb = 3;\n   double B_expected[] = { -0.0312704, 0.2064538, 0.1775109, 0.1949157, -0.0337211, 0.2225517, 0.410638, -0.033917, 0.182384, -0.219409, 0.1257905, 0.1938415 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1798) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1798) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { 0.323, 0.02, 0.718, 0.152, 0.665, 0.289, 0.317, 0.705 };\n   int lda = 2;\n   double B[] = { 0.448, -0.75, 0.851, 0.172, -0.244, 0.398, 0.602, 0.31, -0.017, 0.181, -0.119, 0.402 };\n   int ldb = 3;\n   double B_expected[] = { -0.0594, 0.2698, -0.2725, 0.0335, 0.0334, -0.1438, -0.2952588, 0.1518876, -0.213747, -0.073367, 0.0413388, -0.2306716 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1799) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1799) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { -0.578, 0.018, -0.093, 0.964, 0.414, -0.729, 0.696, 0.874 };\n   int lda = 2;\n   double B[] = { -0.735, 0.788, -0.942, -0.71, -0.254, 0.265, 0.304, 0.218, 0.247, -0.172, 0.419, 0.448 };\n   int ldb = 3;\n   double B_expected[] = { -0.1486214, 0.2495598, -0.1744531, 0.0107667, -0.1648579, 0.1475263, -0.048058, -0.123122, -0.1062886, 0.0033742, -0.037823, -0.213397 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1800) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1800) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { 0.358, -0.773, -0.065, 0.532, -0.319, 0.455, 0.578, 0.493 };\n   int lda = 2;\n   double B[] = { 0.744, -0.958, 0.162, 0.555, -0.131, 0.971, -0.467, 0.175, -0.794, 0.191, 0.361, 0.882 };\n   int ldb = 3;\n   double B_expected[] = { -0.1213734, 0.4492278, -0.1117944, -0.0070022, 0.108851, -0.320916, 0.1226, -0.0992, 0.2191, -0.1367, -0.1965, -0.2285 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1801) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1801) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { -0.354, -0.504, -0.177, 0.186, -0.762, -0.506, 0.758, -0.994 };\n   int lda = 2;\n   double B[] = { -0.944, 0.562, 0.142, 0.742, 0.632, -0.627, -0.101, 0.476, 0.476, 0.675, 0.912, -0.33 };\n   int ldb = 2;\n   double B_expected[] = { -0.21291, -0.021306, -0.601736, 0.043676, 0.1715778, -0.0250026, 0.0587596, -0.2259812, -0.0036234, 0.1608258, 0.0885532, 0.6077736 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1802) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1802) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { -0.001, 0.015, 0.942, 0.497, -0.104, 0.803, 0.679, 0.026 };\n   int lda = 2;\n   double B[] = { 0.889, -0.216, -0.912, -0.263, -0.329, 0.681, 0.332, -0.5, -0.484, 0.741, -0.728, -0.912 };\n   int ldb = 2;\n   double B_expected[] = { -0.2451, 0.1537, 0.2019693, -0.2251001, 0.0306, -0.2372, 0.1376892, 0.2324406, 0.0711, -0.2707, 0.5195777, 0.2860461 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1803) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1803) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { -0.563, 0.394, -0.902, -0.27, 0.461, 0.939, -0.597, 0.803 };\n   int lda = 2;\n   double B[] = { 0.535, -0.111, 0.379, -0.036, 0.803, -0.341, 0.667, 0.001, 0.775, 0.714, 0.908, -0.508 };\n   int ldb = 2;\n   double B_expected[] = { 0.1623722, -0.1219324, 0.0266236, -0.1174842, 0.2429924, -0.1901218, 0.0662002, -0.2004014, 0.4905027, -0.2023089, -0.0629944, -0.3231352 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1804) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1804) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { 0.159, 0.032, 0.785, 0.049, -0.128, 0.132, -0.735, -0.235 };\n   int lda = 2;\n   double B[] = { -0.331, -0.257, -0.725, 0.689, -0.793, 0.398, 0.127, -0.098, -0.498, -0.307, -0.019, 0.517 };\n   int ldb = 2;\n   double B_expected[] = { 0.2553318, -0.1678906, 0.1486, -0.2792, 0.1738216, -0.1670382, -0.0283, 0.0421, 0.151683, -0.083199, -0.046, -0.157 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1805) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1805) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { -0.416, -0.424, -0.088, 0.614, -0.371, 0.983, -0.737, -0.647, 0.321, -0.518, 0.058, -0.533, 0.153, 0.283, 0.342, 0.993, -0.071, 0.225 };\n   int lda = 3;\n   double B[] = { -0.09, -0.844, -0.707, 0.903, 0.632, -0.294, -0.558, 0.74, -0.99, -0.855, -0.189, 0.543 };\n   int ldb = 3;\n   double B_expected[] = { 0.1668304, -0.2576208, -0.0664464, -0.0785782, -0.0226908, -0.0467944, -0.1091876, 0.3667652, 0.1076073, -0.1594011, 0.0407346, 0.0134478 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1806) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1806) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { -0.67, -0.423, -0.165, 0.157, -0.43, 0.674, -0.35, 0.434, 0.972, -0.116, -0.029, 0.316, 0.914, 0.321, 0.132, 0.034, -0.907, -0.401 };\n   int lda = 3;\n   double B[] = { -0.396, 0.71, -0.588, 0.709, -0.024, -0.704, -0.988, 0.656, 0.665, -0.085, -0.778, 0.264 };\n   int ldb = 3;\n   double B_expected[] = { -0.1010812, -0.2287206, 0.0372688, -0.2530336, 0.0776, 0.2088, 0.264679, -0.133739, -0.147391, 0.161965, 0.207, -0.157 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1807) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1807) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { 0.756, -0.149, -0.706, -0.162, -0.145, 0.67, 0.416, -0.27, -0.916, 0.995, -0.863, -0.25, -0.079, 0.248, -0.191, -0.195, 0.981, 0.834 };\n   int lda = 3;\n   double B[] = { 0.329, 0.921, -0.018, -0.02, 0.095, -0.892, -0.105, -0.799, -0.583, 0.564, -0.436, 0.965 };\n   int ldb = 3;\n   double B_expected[] = { -0.1805114, -0.1555812, -0.1560482, -0.0462226, -0.0967127, 0.2921239, 0.1183692, 0.1566766, 0.2260429, 0.3915667, 0.1788155, -0.2682995 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1808) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1808) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { 0.552, -0.668, -0.013, 0.088, -0.766, 0.977, 0.088, -0.06, -0.311, 0.872, -0.328, -0.01, 0.659, -0.327, -0.276, 0.553, -0.734, -0.079 };\n   int lda = 3;\n   double B[] = { -0.87, 0.728, 0.997, -0.36, -0.046, -0.505, 0.082, -0.787, 0.414, 0.965, -0.048, -0.591 };\n   int ldb = 3;\n   double B_expected[] = { 0.1882, -0.3054, -0.2648624, 0.1695328, 0.0462155, -0.3187195, 0.0541, 0.2443, -0.2012812, -0.2298476, 0.3871505, 0.2622315 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1809) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1809) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { 0.349, -0.072, 0.545, 0.212, -0.306, -0.009, 0.757, -0.925, 0.159, 0.308, 0.476, 0.1, 0.725, -0.757, -0.245, 0.571, 0.515, 0.993 };\n   int lda = 3;\n   double B[] = { 0.865, 0.501, 0.165, -0.63, -0.513, 0.351, -0.521, -0.062, 0.54, -0.634, -0.719, 0.216 };\n   int ldb = 2;\n   double B_expected[] = { -0.054193, 0.023274, 0.1487731, -0.3509657, -0.0481592, -0.1044386, 0.0666567, 0.1890461, -0.2932696, 0.0278532, 0.2357046, 0.1223408 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1810) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1810) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { 0.941, -0.496, 0.492, 0.356, 0.353, 0.346, -0.519, -0.86, -0.677, -0.154, 0.313, 0.228, -0.56, -0.451, -0.78, 0.174, -0.663, 0.22 };\n   int lda = 3;\n   double B[] = { 0.162, -0.345, 0.188, 0.578, -0.675, 0.775, -0.018, 0.198, -0.222, -0.52, 0.672, -0.438 };\n   int ldb = 2;\n   double B_expected[] = { -0.3430472, 0.0394834, 0.0185782, -0.1505014, 0.0092108, -0.3837276, 0.0741276, -0.2435652, 0.1186, 0.1338, -0.1578, 0.1986 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1811) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1811) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { 0.592, 0.708, 0.442, 0.212, 0.815, -0.638, 0.55, -0.512, -0.487, 0.181, 0.708, -0.126, 0.408, -0.51, 0.175, 0.114, -0.919, -0.268 };\n   int lda = 3;\n   double B[] = { 0.858, -0.004, 0.59, -0.395, -0.943, 0.824, 0.01, 0.455, -0.775, 0.062, -0.644, 0.03 };\n   int ldb = 2;\n   double B_expected[] = { -0.21374, -0.130452, -0.20707, 0.00773, -0.16787, 0.186571, -0.05026, 0.106515, -0.2887485, -0.0045065, -0.2446935, 0.1590455 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1812) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1812) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int trans = 112;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { -0.988, -0.915, 0.963, 0.103, 0.921, 0.555, 0.846, 0.148, -0.43, 0.336, -0.371, 0.381, -0.487, 0.717, 0.881, -0.777, 0.774, -0.962 };\n   int lda = 3;\n   double B[] = { -0.805, 0.605, 0.481, 0.163, -0.057, -0.017, -0.886, 0.809, 0.875, 0.905, 0.095, 0.894 };\n   int ldb = 2;\n   double B_expected[] = { 0.181, -0.262, -0.1606, -0.0008, 0.220089, -0.234263, 0.0303246, -0.3486122, -0.0476352, -0.3174616, -0.2077412, -0.1552106 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1813) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1813) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int trans = 113;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { -0.513, -0.385, -0.524, 0.726, 0.823, 0.839, -0.355, -0.881 };\n   int lda = 2;\n   double B[] = { -0.707, 0.016, 0.481, 0.935, 0.052, 0.719, 0.277, 0.169, 0.894, 0.352, -0.216, -0.741 };\n   int ldb = 3;\n   double B_expected[] = { -0.078919, 0.119774, 0.2114654, 0.0276682, 0.12593, 0.074299, -0.109352, -0.193196, 0.077864, 0.032876, -0.3330992, 0.2249494 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1814) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1814) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int trans = 113;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { -0.136, -0.37, 0.669, -0.731, -0.4, 0.638, 0.833, -0.29 };\n   int lda = 2;\n   double B[] = { -0.861, -0.278, 0.941, 0.822, 0.88, 0.501, 0.911, -0.502, 0.573, -0.498, -0.517, -0.518 };\n   int ldb = 3;\n   double B_expected[] = { 0.2861, -0.0027, -0.3645, -0.1525, -0.3141, -0.0623, -0.0297254, 0.4490328, -0.254473, -0.161772, 0.0423084, -0.1675858 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1815) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1815) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int trans = 113;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { 0.641, -0.058, 0.246, 0.884, -0.686, 0.123, -0.869, 0.891 };\n   int lda = 2;\n   double B[] = { 0.107, -0.333, 0.556, 0.124, 0.206, 0.049, -0.573, -0.9, -0.417, -0.734, -0.719, 0.76 };\n   int ldb = 3;\n   double B_expected[] = { -0.1591469, -0.1071617, -0.2301499, -0.1454657, -0.1758188, 0.1884616, -0.0380754, -0.4181892, -0.013453, -0.33198, -0.3886102, 0.1361404 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1816) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1816) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int trans = 113;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { 0.083, 0.441, 0.995, 0.338, -0.988, -0.828, -0.254, -0.036 };\n   int lda = 2;\n   double B[] = { -0.792, 0.552, 0.033, -0.178, -0.225, 0.553, 0.348, 0.229, -0.151, -0.594, 0.711, -0.335 };\n   int ldb = 3;\n   double B_expected[] = { 0.3362416, -0.3167112, -0.2305904, -0.0177512, 0.0477576, -0.5068152, -0.1273, -0.0339, 0.1047, 0.1631, -0.1798, 0.1716 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1817) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1817) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int trans = 113;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { 0.105, 0.584, -0.33, -0.182, -0.096, -0.257, 0.327, -0.123 };\n   int lda = 2;\n   double B[] = { -0.249, -0.274, -0.197, -0.899, 0.85, -0.318, 0.596, -0.237, 0.179, 0.046, -0.859, -0.459 };\n   int ldb = 2;\n   double B_expected[] = { 0.0441837, -0.0536099, -0.0065547, 0.1208159, 0.0819176, 0.1492908, -0.0917294, -0.0510192, -0.0037271, 0.0344777, 0.0974489, 0.0389047 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1818) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1818) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int trans = 113;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { -0.972, 0.794, -0.968, -0.406, -0.2, -0.512, 0.436, 0.161 };\n   int lda = 2;\n   double B[] = { 0.817, -0.17, -0.613, -0.565, -0.494, 0.129, -0.593, -0.516, -0.695, -0.42, 0.848, 0.122 };\n   int ldb = 2;\n   double B_expected[] = { -0.2281, 0.1327, 0.2180776, -0.0351272, 0.1353, -0.0881, 0.2475472, 0.1823936, 0.2505, 0.0565, -0.345628, 0.165156 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1819) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1819) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int trans = 113;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { 0.373, -0.316, -0.052, 0.025, -0.878, 0.612, 0.486, 0.953 };\n   int lda = 2;\n   double B[] = { -0.626, 0.408, 0.536, 0.66, -0.666, -0.127, 0.622, 0.036, -0.761, 0.773, -0.137, 0.074 };\n   int ldb = 2;\n   double B_expected[] = { 0.1214746, -0.0093742, -0.247838, 0.145962, 0.0994439, 0.0586017, -0.043453, 0.206241, 0.1510011, -0.0661437, -0.0178345, -0.0495635 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1820) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1820) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int trans = 113;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { 0.621, -0.252, -0.942, 0.073, 0.416, -0.724, -0.972, 0.028 };\n   int lda = 2;\n   double B[] = { -0.006, 0.427, 0.292, -0.212, -0.319, -0.08, -0.401, 0.465, -0.493, -0.529, 0.003, -0.19 };\n   int ldb = 2;\n   double B_expected[] = { 0.0284232, -0.2112704, -0.0664, 0.0928, 0.0210696, 0.1558958, 0.0738, -0.1796, 0.1879327, 0.0541021, 0.0181, 0.0573 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1821) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1821) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int trans = 113;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { -0.415, 0.215, 0.507, 0.094, 0.697, 0.633, 0.206, -0.383, -0.974, 0.734, -0.533, -0.15, -0.982, -0.232, -0.297, 0.501, -0.092, 0.663 };\n   int lda = 3;\n   double B[] = { 0.812, 0.323, 0.294, -0.423, -0.85, 0.043, -0.338, -0.568, 0.976, -0.375, 0.913, -0.119 };\n   int ldb = 3;\n   double B_expected[] = { 0.2153111, -0.0775367, 0.0404927, -0.0287599, -0.0879721, -0.1572073, -0.2481947, 0.2941819, 0.5234716, -0.1242382, 0.108305, 0.162022 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1822) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1822) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int trans = 113;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { 0.827, -0.754, 0.719, 0.88, -0.942, -0.152, 0.051, 0.033, -0.603, -0.557, 0.668, 0.024, 0.082, 0.458, 0.733, 0.669, 0.722, -0.661 };\n   int lda = 3;\n   double B[] = { -0.523, 0.365, -0.811, -0.632, -0.06, 0.151, -0.962, -0.71, -0.543, 0.8, -0.264, 0.994 };\n   int ldb = 3;\n   double B_expected[] = { 0.4413193, -0.3047431, 0.307206, 0.074162, 0.0029, -0.0513, 0.2285887, 0.1349491, 0.061616, -0.510648, -0.0202, -0.3246 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1823) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1823) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int trans = 113;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { 0.958, 0.948, -0.161, -0.34, -0.184, 0.43, -0.045, -0.465, -0.278, 0.461, 0.584, 0.003, -0.794, -0.778, -0.65, -0.91, 0.24, -0.944 };\n   int lda = 3;\n   double B[] = { 0.279, 0.041, -0.033, 0.332, 0.788, 0.611, -0.644, -0.133, 0.247, 0.06, 0.125, -0.407 };\n   int ldb = 3;\n   double B_expected[] = { -0.0693236, 0.0981792, -0.0442625, -0.0021815, 0.1936084, -0.3409328, 0.174601, -0.219233, 0.0274565, 0.1321885, -0.2252264, 0.1381888 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1824) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1824) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int trans = 113;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { -0.983, -0.795, -0.115, -0.542, 0.837, 0.518, -0.164, 0.776, -0.453, -0.28, 0.135, -0.377, -0.199, -0.965, 0.784, -0.39, -0.499, 0.257 };\n   int lda = 3;\n   double B[] = { -0.712, 0.364, -0.28, 0.05, 0.314, 0.748, -0.719, 0.619, 0.474, -0.906, -0.859, 0.943 };\n   int ldb = 3;\n   double B_expected[] = { 0.1772, -0.1804, -0.0900512, -0.1509216, 0.0485292, 0.0109956, 0.1538, -0.2576, -0.2767208, 0.2420976, 0.2164354, 0.0610082 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1825) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1825) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int trans = 113;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { 0.105, 0.503, -0.17, 0.2, -0.861, -0.279, -0.231, 0.058, 0.699, 0.437, 0.578, 0.462, 0.473, -0.793, -0.34, -0.162, -0.128, -0.844 };\n   int lda = 3;\n   double B[] = { -0.802, 0.292, -0.155, -0.916, -0.099, -0.082, 0.057, 0.215, 0.94, 0.911, -0.714, 0.41 };\n   int ldb = 2;\n   double B_expected[] = { -0.1044001, -0.5102243, 0.3865174, 0.0189802, 0.1888166, -0.0057672, -0.0800722, 0.0699214, 0.199086, -0.291946, 0.141904, 0.171064 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1826) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1826) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int trans = 113;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { 0.468, 0.378, -0.498, 0.251, 0.777, -0.543, -0.913, 0.095, 0.779, -0.933, 0.068, -0.669, 0.715, 0.03, 0.012, 0.392, -0.785, -0.056 };\n   int lda = 3;\n   double B[] = { 0.143, -0.242, -0.379, -0.831, -0.46, -0.663, -0.735, -0.098, -0.861, -0.894, 0.772, -0.059 };\n   int ldb = 2;\n   double B_expected[] = { 0.0633681, 0.0476643, -0.1761819, 0.3044093, 0.2798556, 0.0187868, 0.2647924, 0.0455132, 0.3477, 0.1821, -0.2257, 0.0949 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1827) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1827) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int trans = 113;\n   int diag = 131;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { -0.764, 0.908, 0.899, 0.119, -0.447, 0.279, 0.338, 0.73, -0.74, -0.366, -0.572, 0.583, 0.75, 0.519, 0.603, 0.831, 0.697, 0.822 };\n   int lda = 3;\n   double B[] = { 0.399, 0.572, -0.489, 0.964, -0.167, -0.104, 0.75, -0.199, 0.777, 0.503, -0.025, -0.386 };\n   int ldb = 2;\n   double B_expected[] = { 0.015568, 0.261244, -0.345424, 0.212636, -0.2247824, -0.0859342, 0.1074596, -0.4846822, -0.2415227, 0.2465939, 0.2042976, 0.2206978 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1828) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1828) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int trans = 113;\n   int diag = 132;\n   int M = 2;\n   int N = 3;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { 0.432, 0.063, 0.065, -0.546, 0.099, 0.892, 0.48, -0.085, 0.746, -0.541, -0.739, -0.207, 0.695, 0.765, 0.197, -0.86, 0.621, -0.653 };\n   int lda = 3;\n   double B[] = { 0.182, 0.731, 0.571, 0.01, -0.357, -0.612, 0.581, 0.756, -0.911, -0.225, 0.438, 0.546 };\n   int ldb = 2;\n   double B_expected[] = { -0.1277, -0.2011, -0.1723, 0.0541, 0.2698001, 0.0651043, -0.2906381, -0.2592593, -0.0512125, -0.0040605, 0.0647965, 0.1119875 };\n   cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);\n   {\n     int i;\n     for (i = 0; i < 6; i++) {\n       gsl_test_rel(B[2*i], B_expected[2*i], dbleps, \"ztrmm(case 1829) real\");\n       gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, \"ztrmm(case 1829) imag\");\n     };\n   };\n  };\n\n\n}\n", "meta": {"hexsha": "328163e7e1769dbd4c568d6f4b6b2412690d1cd5", "size": 123670, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/cblas/test_trmm.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/cblas/test_trmm.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/cblas/test_trmm.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 31.3247213779, "max_line_length": 177, "alphanum_fraction": 0.5185736234, "num_tokens": 60285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658973632215985, "lm_q2_score": 0.04535258265106529, "lm_q1q2_score": 0.016625791315582984}}
{"text": "/**\n * @file pflow.h\n * @brief Public header file for power flow application\n */\n\n#ifndef PFLOW_H\n#define PFLOW_H\n\n#include <petsc.h>\n#include \"cJSON.h\"\n\ntypedef struct _p_PFLOW *PFLOW;\n\nPETSC_EXTERN PetscErrorCode PFLOWCreate(MPI_Comm,PFLOW*);\nPETSC_EXTERN PetscErrorCode PFLOWDestroy(PFLOW*);\nPETSC_EXTERN PetscErrorCode PFLOWReadMatPowerData(PFLOW,const char[]);\nPETSC_EXTERN PetscErrorCode PFLOWSolve(PFLOW);\nPETSC_EXTERN PetscErrorCode PFLOWPostSolve(PFLOW);\n\n/* FUNCTIONS FOR PARSING DATA */\nint PFLOWParserGetVal(cJSON *, const char *, double *, int);\ndouble PFLOWParserGet(PFLOW,int,char *, const char *);\nvoid PFLOWParserSet(PFLOW,int,char *, PetscScalar, const char *);\n\n\n#endif\n\n\n", "meta": {"hexsha": "6d918b9bdaed163370d32983e9111f7d797fc2d4", "size": 691, "ext": "h", "lang": "C", "max_stars_repo_path": "ANL_adaptive_volt_var/include/pflow.h", "max_stars_repo_name": "GMLC-TDC/Use-Cases", "max_stars_repo_head_hexsha": "14d687fe04af731c1ee466e05acfd5813095660a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-04T07:27:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-04T07:27:34.000Z", "max_issues_repo_path": "ANL_adaptive_volt_var/include/pflow.h", "max_issues_repo_name": "GMLC-TDC/Use-Cases", "max_issues_repo_head_hexsha": "14d687fe04af731c1ee466e05acfd5813095660a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ANL_adaptive_volt_var/include/pflow.h", "max_forks_repo_name": "GMLC-TDC/Use-Cases", "max_forks_repo_head_hexsha": "14d687fe04af731c1ee466e05acfd5813095660a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-01T21:49:40.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-23T19:30:36.000Z", "avg_line_length": 23.8275862069, "max_line_length": 70, "alphanum_fraction": 0.7727930535, "num_tokens": 174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.38861804086755836, "lm_q2_score": 0.042722196937077614, "lm_q1q2_score": 0.016602616475245104}}
{"text": "/**\n * \\copyright\n * Copyright (c) 2012-2018, OpenGeoSys Community (http://www.opengeosys.org)\n *            Distributed under a Modified BSD License.\n *              See accompanying file LICENSE.txt or\n *              http://www.opengeosys.org/project/license\n *\n */\n\n#pragma once\n\n/// The LinearSolverLibrarySetup takes care of proper initialization and\n/// shutting down of an external linear solver library. The concrete\n/// implementation is chosen by the build system.\n/// An object of this class must be created at the begining of the scope where\n/// it is used. When the scope closes (or the object is destroyed explicitly)\n/// library shutting down functions are automatically called.\n/// The default implementation is empty providing polymorphic behaviour when\n/// using this class.\n\n#include \"NumLib/DOF/GlobalMatrixProviders.h\"\n\n#if defined(USE_PETSC)\n#include <petsc.h>\n#include <mpi.h>\nnamespace ApplicationsLib\n{\nstruct LinearSolverLibrarySetup final\n{\n    LinearSolverLibrarySetup(int argc, char* argv[])\n    {\n        MPI_Init(&argc, &argv);\n        char help[] = \"ogs6 with PETSc \\n\";\n        PetscInitialize(&argc, &argv, nullptr, help);\n    }\n\n    ~LinearSolverLibrarySetup()\n    {\n        NumLib::cleanupGlobalMatrixProviders();\n        PetscFinalize();\n        MPI_Finalize();\n    }\n};\n}    // ApplicationsLib\n#elif defined(USE_LIS)\n#include <lis.h>\nnamespace ApplicationsLib\n{\nstruct LinearSolverLibrarySetup final\n{\n    LinearSolverLibrarySetup(int argc, char* argv[])\n    {\n        lis_initialize(&argc, &argv);\n    }\n\n    ~LinearSolverLibrarySetup()\n    {\n        NumLib::cleanupGlobalMatrixProviders();\n        lis_finalize();\n    }\n};\n}    // ApplicationsLib\n#else\nnamespace ApplicationsLib\n{\nstruct LinearSolverLibrarySetup final\n{\n    LinearSolverLibrarySetup(int /*argc*/, char* /*argv*/[]) {}\n    ~LinearSolverLibrarySetup()\n    {\n        NumLib::cleanupGlobalMatrixProviders();\n    }\n};\n}    // ApplicationsLib\n#endif\n", "meta": {"hexsha": "8ae299b6627698d65661538100560a71333ae379", "size": 1952, "ext": "h", "lang": "C", "max_stars_repo_path": "Applications/ApplicationsLib/LinearSolverLibrarySetup.h", "max_stars_repo_name": "hosseinsotudeh/ogs", "max_stars_repo_head_hexsha": "214afcb00af23e4393168a846c7ee8ce4f13e489", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Applications/ApplicationsLib/LinearSolverLibrarySetup.h", "max_issues_repo_name": "hosseinsotudeh/ogs", "max_issues_repo_head_hexsha": "214afcb00af23e4393168a846c7ee8ce4f13e489", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Applications/ApplicationsLib/LinearSolverLibrarySetup.h", "max_forks_repo_name": "hosseinsotudeh/ogs", "max_forks_repo_head_hexsha": "214afcb00af23e4393168a846c7ee8ce4f13e489", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6842105263, "max_line_length": 78, "alphanum_fraction": 0.6849385246, "num_tokens": 438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38861802670584894, "lm_q2_score": 0.04272219282354038, "lm_q1q2_score": 0.016602614271631042}}
{"text": "#pragma once\n\n#include <gsl/span>\n#include <atomic>\n\nnamespace Halley {\n\t// This is a lock-free, wait-free ring buffer\n\t// It is only thread safe for one producer and one consumer at any given time\n\t// Loosely based on implementation from Game Audio Programming 2\n\t\n    template <typename T>\n    class RingBuffer {\n    public:\n    \texplicit RingBuffer(size_t capacity)\n\t        : numEntries(0)\n    \t{\n            entries.resize(capacity);\n    \t}\n\n    \tsize_t availableToRead() const\n    \t{\n            return numEntries.load();\n    \t}\n\n        size_t availableToWrite() const\n        {\n            return entries.size() - numEntries.load();\n        }\n\n    \tbool canWrite(size_t n) const\n    \t{\n            return numEntries.load() + n <= entries.size();\n    \t}\n\n    \tbool canRead(size_t n) const\n    \t{\n            return numEntries.load() >= n;\n    \t}\n\n    \tbool empty() const\n    \t{\n            return numEntries.load() == 0;\n    \t}\n    \t\n        void writeOne(T e)\n        {\n            Expects(canWrite(1));\n            entries[writePos] = std::move(e);\n            writePos = (writePos + 1) % entries.size();\n            ++numEntries;\n        }\n\n        void write(gsl::span<T> es)\n        {\n            const size_t numToWrite = size_t(es.size());\n            Expects(canWrite(numToWrite));\n            const size_t spaceToEnd = entries.size() - writePos;\n            const size_t nToWrite1 = std::min(spaceToEnd, numToWrite);\n\n            for (size_t i = 0; i < nToWrite1; ++i) {\n                entries[writePos + i] = std::move(es[i]);\n            }\n\n            const size_t nToWrite2 = numToWrite - nToWrite1;\n            for (size_t i = 0; i < nToWrite2; ++i) {\n                entries[i] = std::move(es[i + nToWrite1]);\n            }\n\n            writePos = (writePos + numToWrite) % entries.size();\n            numEntries.fetch_add(numToWrite);\n        }\n\n    \tvoid write(gsl::span<const T> es)\n    \t{\n            const size_t numToWrite = size_t(es.size());\n            Expects(canWrite(numToWrite));\n            const size_t spaceToEnd = entries.size() - writePos;\n            const size_t nToWrite1 = std::min(spaceToEnd, numToWrite);\n\n    \t\tfor (size_t i = 0; i < nToWrite1; ++i) {\n                entries[writePos + i] = es[i];\n    \t\t}\n\n            const size_t nToWrite2 = numToWrite - nToWrite1;\n    \t\tfor (size_t i = 0; i < nToWrite2; ++i) {\n                entries[i] = es[i + nToWrite1];\n    \t\t}\n\n            writePos = (writePos + numToWrite) % entries.size();\n            numEntries.fetch_add(numToWrite);\n    \t}\n\n    \tT readOne()\n    \t{\n            Expects(canRead(1));\n            T v = std::move(entries[readPos]);\n    \t\tentries[readPos] = T();\n            readPos = (readPos + 1) % entries.size();\n            --numEntries;\n            return v;\n    \t}\n\n    \tvoid read(gsl::span<T> es)\n    \t{\n            const size_t numToRead = size_t(es.size());\n            Expects(canRead(numToRead));\n            const size_t spaceToEnd = entries.size() - readPos;\n            const size_t nToRead1 = std::min(spaceToEnd, numToRead);\n\n            for (size_t i = 0; i < nToRead1; ++i) {\n                es[i] = std::move(entries[readPos + i]);\n            \tentries[readPos + i] = T();\n            }\n\n            const size_t nToRead2 = numToRead - nToRead1;\n            for (size_t i = 0; i < nToRead2; ++i) {\n                es[i + nToRead1] = std::move(entries[i]);\n            \tentries[i] = T();\n            }\n\n            readPos = (readPos + numToRead) % entries.size();\n            numEntries.fetch_sub(numToRead);\n    \t}\n\n    private:\n        size_t readPos = 0;\n        size_t writePos = 0;\n        std::atomic<size_t> numEntries;\n        Vector<T> entries;\n    };\n}\n", "meta": {"hexsha": "a92dae30e2bf13942a132f9a7b278954f88b63b8", "size": 3694, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engine/utils/include/halley/data_structures/ring_buffer.h", "max_stars_repo_name": "amrezzd/halley", "max_stars_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/engine/utils/include/halley/data_structures/ring_buffer.h", "max_issues_repo_name": "amrezzd/halley", "max_issues_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engine/utils/include/halley/data_structures/ring_buffer.h", "max_forks_repo_name": "amrezzd/halley", "max_forks_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9848484848, "max_line_length": 78, "alphanum_fraction": 0.5148890092, "num_tokens": 971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.039638837824654244, "lm_q1q2_score": 0.016596658887634022}}
{"text": "#ifndef MATRIX_H_\n#define MATRIX_H_\n\n#include \"matrix_funcs.h\"\n#ifdef NUMPY_INTERFACE\n#include <Python.h>\n#include <arrayobject.h>\n#endif\n#include <limits>\n#include <assert.h>\n#include <stdio.h>\n#include <string.h>\n\n#ifdef USE_MKL\n#include <mkl.h>\n#include <mkl_cblas.h>\n#include <mkl_vsl.h>\n#include <mkl_vml.h>\n\n#define IS_MKL true\n\n#ifdef DOUBLE_PRECISION\n#define MKL_UNIFORM vdRngUniform\n#define MKL_NORMAL vdRngGaussian\n#define MKL_UNIFORM_RND_METHOD VSL_METHOD_DUNIFORM_STD_ACCURATE\n#define MKL_GAUSSIAN_RND_METHOD VSL_METHOD_DGAUSSIAN_BOXMULLER\n#define MKL_EXP vdExp\n#define MKL_RECIP vdInv\n#define MKL_SQUARE vdSqr\n#define MKL_TANH vdTanh\n#define MKL_LOG vdLn\n#define MKL_VECMUL vdMul\n#define MKL_VECDIV vdDiv\n#else\n#define MKL_UNIFORM vsRngUniform\n#define MKL_NORMAL vsRngGaussian\n#define MKL_UNIFORM_RND_METHOD VSL_METHOD_SUNIFORM_STD_ACCURATE\n#define MKL_GAUSSIAN_RND_METHOD VSL_METHOD_SGAUSSIAN_BOXMULLER\n#define MKL_EXP vsExp\n#define MKL_RECIP vsInv\n#define MKL_SQUARE vsSqr\n#define MKL_TANH vsTanh\n#define MKL_LOG vsLn\n#define MKL_VECMUL vsMul\n#define MKL_VECDIV vsDiv\n#endif /* DOUBLE_PRECISION */\n\n#else\n#include <cblas.h>\n#define IS_MKL false\n#endif /* USE_MKL */\n\n#ifdef DOUBLE_PRECISION\n#define CBLAS_GEMM cblas_dgemm\n#define CBLAS_SCAL cblas_dscal\n#define CBLAS_AXPY cblas_daxpy\n#else\n#define CBLAS_GEMM cblas_sgemm\n#define CBLAS_SCAL cblas_sscal\n#define CBLAS_AXPY cblas_saxpy\n#endif /* DOUBLE_PRECISION */\n\n#define MTYPE_MAX numeric_limits<MTYPE>::max()\n\nclass Matrix {\nprivate:\n    MTYPE* _data;\n    bool _ownsData;\n    int _numRows, _numCols;\n    int _numElements;\n    int _numDataBytes;\n    CBLAS_TRANSPOSE _trans;\n\n    void _init(MTYPE* data, int numRows, int numCols, bool transpose, bool ownsData);\n    void _tileTo2(Matrix& target) const;\n    void _copyAllTo(Matrix& target) const;\n    MTYPE _sum_column(int col) const;\n    MTYPE _sum_row(int row) const;\n    MTYPE _aggregate(MTYPE(*agg_func)(MTYPE, MTYPE), MTYPE initialValue) const;\n    void _aggregate(int axis, Matrix& target, MTYPE(*agg_func)(MTYPE, MTYPE), MTYPE initialValue) const;\n    MTYPE _aggregateRow(int row, MTYPE(*agg_func)(MTYPE, MTYPE), MTYPE initialValue) const;\n    MTYPE _aggregateCol(int row, MTYPE(*agg_func)(MTYPE, MTYPE), MTYPE initialValue) const;\n    void _updateDims(int numRows, int numCols);\n    void _applyLoop(MTYPE(*func)(MTYPE));\n    void _applyLoop(MTYPE (*func)(MTYPE), Matrix& target);\n    void _applyLoop2(const Matrix& a, MTYPE(*func)(MTYPE, MTYPE), Matrix& target) const;\n    void _applyLoop2(const Matrix& a, MTYPE (*func)(MTYPE,MTYPE, MTYPE), MTYPE scalar, Matrix& target) const;\n    void _applyLoopScalar(const MTYPE scalar, MTYPE(*func)(MTYPE, MTYPE), Matrix& target) const;\n    void _checkBounds(int startRow, int endRow, int startCol, int endCol) const;\n    void _divideByVector(const Matrix& vec, Matrix& target);\n    inline int _getNumColsBackEnd() const {\n        return _trans == CblasNoTrans ? _numCols : _numRows;\n    }\npublic:\n    enum FUNCTION {\n        TANH, RECIPROCAL, SQUARE, ABS, EXP, LOG, ZERO, ONE, LOGISTIC1, LOGISTIC2\n    };\n    Matrix();\n    Matrix(int numRows, int numCols);\n#ifdef NUMPY_INTERFACE\n    Matrix(const PyArrayObject *src);\n#endif\n    Matrix(const Matrix &like);\n    Matrix(MTYPE* data, int numRows, int numCols);\n    Matrix(MTYPE* data, int numRows, int numCols, bool transpose);\n    ~Matrix();\n\n    inline MTYPE& getCell(int i, int j) const {\n//        assert(i >= 0 && i < _numRows);\n//        assert(j >= 0 && j < _numCols);\n        if (_trans == CblasTrans) {\n            return _data[j * _numRows + i];\n        }\n        return _data[i * _numCols + j];\n    }\n\n    MTYPE& operator()(int i, int j) const {\n        return getCell(i, j);\n    }\n\n    inline MTYPE* getData() const {\n        return _data;\n    }\n\n    inline bool isView() const {\n        return !_ownsData;\n    }\n\n    inline int getNumRows() const {\n        return _numRows;\n    }\n\n    inline int getNumCols() const {\n        return _numCols;\n    }\n\n    inline int getNumDataBytes() const {\n        return _numDataBytes;\n    }\n\n    inline int getNumElements() const {\n        return _numElements;\n    }\n\n    inline CBLAS_TRANSPOSE getBLASTrans() const {\n        return _trans;\n    }\n\n    inline bool isSameDims(const Matrix& a) const {\n        return a.getNumRows() == getNumRows() && a.getNumCols() == getNumCols();\n    }\n\n    inline bool isTrans() const {\n        return _trans == CblasTrans;\n    }\n\n    /*\n     * Only use if you know what you're doing!\n     * Does not update any dimensions. Just flips the _trans flag.\n     *\n     * Use transpose() if you want to get the transpose of this matrix.\n     */\n    inline void setTrans(bool trans) {\n        _trans = trans ? CblasTrans : CblasNoTrans;\n    }\n\n    void apply(FUNCTION f);\n    void apply(Matrix::FUNCTION f, Matrix& target);\n    void subtractFromScalar(MTYPE scalar);\n    void subtractFromScalar(MTYPE scalar, Matrix &target) const;\n    void biggerThanScalar(MTYPE scalar);\n    void smallerThanScalar(MTYPE scalar);\n    void equalsScalar(MTYPE scalar);\n    void biggerThanScalar(MTYPE scalar, Matrix& target) const;\n    void smallerThanScalar(MTYPE scalar, Matrix& target) const;\n    void equalsScalar(MTYPE scalar, Matrix& target) const;\n    void biggerThan(Matrix& a);\n    void biggerThan(Matrix& a, Matrix& target) const;\n    void smallerThan(Matrix& a);\n    void smallerThan(Matrix& a, Matrix& target) const;\n    void minWith(Matrix &a);\n    void minWith(Matrix &a, Matrix &target) const;\n    void maxWith(Matrix &a);\n    void maxWith(Matrix &a, Matrix &target) const;\n    void equals(Matrix& a);\n    void equals(Matrix& a, Matrix& target) const;\n    void notEquals(Matrix& a) ;\n    void notEquals(Matrix& a, Matrix& target) const;\n    void add(const Matrix &m);\n    void add(const Matrix &m, MTYPE scale);\n    void add(const Matrix &m, Matrix& target);\n    void add(const Matrix &m, MTYPE scale, Matrix& target);\n    void subtract(const Matrix &m);\n    void subtract(const Matrix &m, Matrix& target);\n    void subtract(const Matrix &m, MTYPE scale);\n    void subtract(const Matrix &m, MTYPE scale, Matrix& target);\n    void addVector(const Matrix& vec, MTYPE scale);\n    void addVector(const Matrix& vec, MTYPE scale, Matrix& target);\n    void addVector(const Matrix& vec);\n    void addVector(const Matrix& vec, Matrix& target);\n    void addScalar(MTYPE scalar);\n    void addScalar(MTYPE scalar, Matrix& target) const;\n    void maxWithScalar(MTYPE scalar);\n    void maxWithScalar(MTYPE scalar, Matrix &target) const;\n    void minWithScalar(MTYPE scalar);\n    void minWithScalar(MTYPE scalar, Matrix &target) const;\n    void eltWiseMultByVector(const Matrix& vec);\n    void eltWiseMultByVector(const Matrix& vec, Matrix& target);\n    void eltWiseDivideByVector(const Matrix& vec);\n    void eltWiseDivideByVector(const Matrix& vec, Matrix& target);\n    void resize(int newNumRows, int newNumCols);\n    void resize(const Matrix& like);\n    Matrix& slice(int startRow, int endRow, int startCol, int endCol) const;\n    void slice(int startRow, int endRow, int startCol, int endCol, Matrix &target) const;\n    Matrix& sliceRows(int startRow, int endRow) const;\n    void sliceRows(int startRow, int endRow, Matrix& target) const;\n    Matrix& sliceCols(int startCol, int endCol) const;\n    void sliceCols(int startCol, int endCol, Matrix& target) const;\n    void rightMult(const Matrix &b, MTYPE scale);\n    void rightMult(const Matrix &b, Matrix &target) const;\n    void rightMult(const Matrix &b);\n    void rightMult(const Matrix &b, MTYPE scaleAB, Matrix &target) const;\n    void addProduct(const Matrix &a, const Matrix &b, MTYPE scaleAB, MTYPE scaleThis);\n    void addProduct(const Matrix& a, const Matrix& b);\n    void eltWiseMult(const Matrix& a);\n    void eltWiseMult(const Matrix& a, Matrix& target) const;\n    void eltWiseDivide(const Matrix& a);\n    void eltWiseDivide(const Matrix& a, Matrix &target) const;\n    Matrix& transpose() const;\n    Matrix& transpose(bool hard) const;\n    Matrix& tile(int timesY, int timesX) const;\n    void tile(int timesY, int timesX, Matrix& target) const;\n    void copy(Matrix &dest, int srcStartRow, int srcEndRow, int srcStartCol, int srcEndCol, int destStartRow, int destStartCol) const;\n    Matrix& copy() const;\n    void copy(Matrix& target) const;\n    Matrix& sum(int axis) const;\n    void sum(int axis, Matrix &target) const;\n    MTYPE sum() const;\n    MTYPE max() const;\n    Matrix& max(int axis) const;\n    void max(int axis, Matrix& target) const;\n    MTYPE min() const;\n    Matrix& min(int axis) const;\n    void min(int axis, Matrix& target) const;\n    void scale(MTYPE scale);\n#ifdef USE_MKL\n    void randomizeNormal(VSLStreamStatePtr stream, MTYPE mean, MTYPE stdev);\n    void randomizeUniform(VSLStreamStatePtr stream);\n    void randomizeNormal(VSLStreamStatePtr stream);\n#else\n    void randomizeNormal(MTYPE mean, MTYPE stdev);\n    void randomizeUniform();\n    void randomizeNormal();\n#endif\n    void print() const;\n    void print(int startRow,int rows, int startCol,int cols) const;\n    void print(int rows, int cols) const;\n};\n\n#endif /* MATRIX_H_ */\n", "meta": {"hexsha": "20e2e5b6a06a53249056a9c1f7a75015b28b7d17", "size": 9093, "ext": "h", "lang": "C", "max_stars_repo_path": "cudamat/matrix.h", "max_stars_repo_name": "barapa/HF-RNN", "max_stars_repo_head_hexsha": "0cd375dc2f5e7919cb3bac6f60cb088cf0333520", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-04-15T20:20:39.000Z", "max_stars_repo_stars_event_max_datetime": "2015-04-15T20:20:39.000Z", "max_issues_repo_path": "cudamat/matrix.h", "max_issues_repo_name": "barapa/HF-RNN", "max_issues_repo_head_hexsha": "0cd375dc2f5e7919cb3bac6f60cb088cf0333520", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cudamat/matrix.h", "max_forks_repo_name": "barapa/HF-RNN", "max_forks_repo_head_hexsha": "0cd375dc2f5e7919cb3bac6f60cb088cf0333520", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8390804598, "max_line_length": 134, "alphanum_fraction": 0.7051578137, "num_tokens": 2480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.035678550108705624, "lm_q1q2_score": 0.016587014009861425}}
{"text": "/* vector/gsl_vector_double.h\r\n * \r\n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\r\n * \r\n * This program is free software; you can redistribute it and/or modify\r\n * it under the terms of the GNU General Public License as published by\r\n * the Free Software Foundation; either version 3 of the License, or (at\r\n * your option) any later version.\r\n * \r\n * This program is distributed in the hope that it will be useful, but\r\n * WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n * General Public License for more details.\r\n * \r\n * You should have received a copy of the GNU General Public License\r\n * along with this program; if not, write to the Free Software\r\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r\n */\r\n\r\n#ifndef __GSL_VECTOR_DOUBLE_H__\r\n#define __GSL_VECTOR_DOUBLE_H__\r\n\r\n#if !defined( GSL_FUN )\r\n#  if !defined( GSL_DLL )\r\n#    define GSL_FUN extern\r\n#  elif defined( BUILD_GSL_DLL )\r\n#    define GSL_FUN extern __declspec(dllexport)\r\n#  else\r\n#    define GSL_FUN extern __declspec(dllimport)\r\n#  endif\r\n#endif\r\n\r\n#include <stdlib.h>\r\n#include <gsl/gsl_types.h>\r\n#include <gsl/gsl_errno.h>\r\n#include <gsl/gsl_inline.h>\r\n#include <gsl/gsl_check_range.h>\r\n#include <gsl/gsl_block_double.h>\r\n\r\n#undef __BEGIN_DECLS\r\n#undef __END_DECLS\r\n#ifdef __cplusplus\r\n# define __BEGIN_DECLS extern \"C\" {\r\n# define __END_DECLS }\r\n#else\r\n# define __BEGIN_DECLS /* empty */\r\n# define __END_DECLS /* empty */\r\n#endif\r\n\r\n__BEGIN_DECLS\r\n\r\ntypedef struct \r\n{\r\n  size_t size;\r\n  size_t stride;\r\n  double *data;\r\n  gsl_block *block;\r\n  int owner;\r\n} \r\ngsl_vector;\r\n\r\ntypedef struct\r\n{\r\n  gsl_vector vector;\r\n} _gsl_vector_view;\r\n\r\ntypedef _gsl_vector_view gsl_vector_view;\r\n\r\ntypedef struct\r\n{\r\n  gsl_vector vector;\r\n} _gsl_vector_const_view;\r\n\r\ntypedef const _gsl_vector_const_view gsl_vector_const_view;\r\n\r\n\r\n/* Allocation */\r\n\r\nGSL_FUN gsl_vector *gsl_vector_alloc (const size_t n);\r\nGSL_FUN gsl_vector *gsl_vector_calloc (const size_t n);\r\n\r\nGSL_FUN gsl_vector *gsl_vector_alloc_from_block (gsl_block * b,\r\n                                                     const size_t offset, \r\n                                                     const size_t n, \r\n                                                     const size_t stride);\r\n\r\nGSL_FUN gsl_vector *gsl_vector_alloc_from_vector (gsl_vector * v,\r\n                                                      const size_t offset, \r\n                                                      const size_t n, \r\n                                                      const size_t stride);\r\n\r\nGSL_FUN void gsl_vector_free (gsl_vector * v);\r\n\r\n/* Views */\r\n\r\nGSL_FUN _gsl_vector_view \r\ngsl_vector_view_array (double *v, size_t n);\r\n\r\nGSL_FUN _gsl_vector_view \r\ngsl_vector_view_array_with_stride (double *base,\r\n                                         size_t stride,\r\n                                         size_t n);\r\n\r\nGSL_FUN _gsl_vector_const_view \r\ngsl_vector_const_view_array (const double *v, size_t n);\r\n\r\nGSL_FUN _gsl_vector_const_view \r\ngsl_vector_const_view_array_with_stride (const double *base,\r\n                                               size_t stride,\r\n                                               size_t n);\r\n\r\nGSL_FUN _gsl_vector_view \r\ngsl_vector_subvector (gsl_vector *v, \r\n                            size_t i, \r\n                            size_t n);\r\n\r\nGSL_FUN _gsl_vector_view \r\ngsl_vector_subvector_with_stride (gsl_vector *v, \r\n                                        size_t i,\r\n                                        size_t stride,\r\n                                        size_t n);\r\n\r\nGSL_FUN _gsl_vector_const_view \r\ngsl_vector_const_subvector (const gsl_vector *v, \r\n                                  size_t i, \r\n                                  size_t n);\r\n\r\nGSL_FUN _gsl_vector_const_view \r\ngsl_vector_const_subvector_with_stride (const gsl_vector *v, \r\n                                              size_t i, \r\n                                              size_t stride,\r\n                                              size_t n);\r\n\r\n/* Operations */\r\n\r\nGSL_FUN void gsl_vector_set_zero (gsl_vector * v);\r\nGSL_FUN void gsl_vector_set_all (gsl_vector * v, double x);\r\nGSL_FUN int gsl_vector_set_basis (gsl_vector * v, size_t i);\r\n\r\nGSL_FUN int gsl_vector_fread (FILE * stream, gsl_vector * v);\r\nGSL_FUN int gsl_vector_fwrite (FILE * stream, const gsl_vector * v);\r\nGSL_FUN int gsl_vector_fscanf (FILE * stream, gsl_vector * v);\r\nGSL_FUN int gsl_vector_fprintf (FILE * stream, const gsl_vector * v,\r\n                              const char *format);\r\n\r\nGSL_FUN int gsl_vector_memcpy (gsl_vector * dest, const gsl_vector * src);\r\n\r\nGSL_FUN int gsl_vector_reverse (gsl_vector * v);\r\n\r\nGSL_FUN int gsl_vector_swap (gsl_vector * v, gsl_vector * w);\r\nGSL_FUN int gsl_vector_swap_elements (gsl_vector * v, const size_t i, const size_t j);\r\n\r\nGSL_FUN double gsl_vector_max (const gsl_vector * v);\r\nGSL_FUN double gsl_vector_min (const gsl_vector * v);\r\nGSL_FUN void gsl_vector_minmax (const gsl_vector * v, double * min_out, double * max_out);\r\n\r\nGSL_FUN size_t gsl_vector_max_index (const gsl_vector * v);\r\nGSL_FUN size_t gsl_vector_min_index (const gsl_vector * v);\r\nGSL_FUN void gsl_vector_minmax_index (const gsl_vector * v, size_t * imin, size_t * imax);\r\n\r\nGSL_FUN int gsl_vector_add (gsl_vector * a, const gsl_vector * b);\r\nGSL_FUN int gsl_vector_sub (gsl_vector * a, const gsl_vector * b);\r\nGSL_FUN int gsl_vector_mul (gsl_vector * a, const gsl_vector * b);\r\nGSL_FUN int gsl_vector_div (gsl_vector * a, const gsl_vector * b);\r\nGSL_FUN int gsl_vector_scale (gsl_vector * a, const double x);\r\nGSL_FUN int gsl_vector_add_constant (gsl_vector * a, const double x);\r\nGSL_FUN int gsl_vector_axpby (const double alpha, const gsl_vector * x, const double beta, gsl_vector * y);\r\nGSL_FUN double gsl_vector_sum (const gsl_vector * a);\r\n\r\nGSL_FUN int gsl_vector_equal (const gsl_vector * u, \r\n                            const gsl_vector * v);\r\n\r\nGSL_FUN int gsl_vector_isnull (const gsl_vector * v);\r\nGSL_FUN int gsl_vector_ispos (const gsl_vector * v);\r\nGSL_FUN int gsl_vector_isneg (const gsl_vector * v);\r\nGSL_FUN int gsl_vector_isnonneg (const gsl_vector * v);\r\n\r\nGSL_FUN INLINE_DECL double gsl_vector_get (const gsl_vector * v, const size_t i);\r\nGSL_FUN INLINE_DECL void gsl_vector_set (gsl_vector * v, const size_t i, double x);\r\nGSL_FUN INLINE_DECL double * gsl_vector_ptr (gsl_vector * v, const size_t i);\r\nGSL_FUN INLINE_DECL const double * gsl_vector_const_ptr (const gsl_vector * v, const size_t i);\r\n\r\n#ifdef HAVE_INLINE\r\n\r\nINLINE_FUN\r\ndouble\r\ngsl_vector_get (const gsl_vector * v, const size_t i)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(i >= v->size))\r\n    {\r\n      GSL_ERROR_VAL (\"index out of range\", GSL_EINVAL, 0);\r\n    }\r\n#endif\r\n  return v->data[i * v->stride];\r\n}\r\n\r\nINLINE_FUN\r\nvoid\r\ngsl_vector_set (gsl_vector * v, const size_t i, double x)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(i >= v->size))\r\n    {\r\n      GSL_ERROR_VOID (\"index out of range\", GSL_EINVAL);\r\n    }\r\n#endif\r\n  v->data[i * v->stride] = x;\r\n}\r\n\r\nINLINE_FUN\r\ndouble *\r\ngsl_vector_ptr (gsl_vector * v, const size_t i)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(i >= v->size))\r\n    {\r\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\r\n    }\r\n#endif\r\n  return (double *) (v->data + i * v->stride);\r\n}\r\n\r\nINLINE_FUN\r\nconst double *\r\ngsl_vector_const_ptr (const gsl_vector * v, const size_t i)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(i >= v->size))\r\n    {\r\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\r\n    }\r\n#endif\r\n  return (const double *) (v->data + i * v->stride);\r\n}\r\n#endif /* HAVE_INLINE */\r\n\r\n__END_DECLS\r\n\r\n#endif /* __GSL_VECTOR_DOUBLE_H__ */\r\n\r\n\r\n", "meta": {"hexsha": "82b3aad35a6bf4a85532e98e6d6bbc2a0a38c5bc", "size": 7788, "ext": "h", "lang": "C", "max_stars_repo_path": "vendor/gsl/gsl/gsl_vector_double.h", "max_stars_repo_name": "mgreter/astrometrylib", "max_stars_repo_head_hexsha": "ef4d4539a537ab49329b77648aac893d2b4ad318", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z", "max_issues_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_vector_double.h", "max_issues_repo_name": "zzpwahaha/VimbaCamJILA", "max_issues_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z", "max_forks_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_vector_double.h", "max_forks_repo_name": "zzpwahaha/VimbaCamJILA", "max_forks_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 32.049382716, "max_line_length": 108, "alphanum_fraction": 0.6403441192, "num_tokens": 1878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473485858429, "lm_q2_score": 0.038466193671751685, "lm_q1q2_score": 0.016546131218093518}}
{"text": "/* monte/gsl_monte_plain.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Michael Booth\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Plain Monte-Carlo. */\n\n/* Author: MJB */\n\n#ifndef __GSL_MONTE_PLAIN_H__\n#define __GSL_MONTE_PLAIN_H__\n\n#if !defined( GSL_FUN )\n#  if !defined( GSL_DLL )\n#    define GSL_FUN extern\n#  elif defined( BUILD_GSL_DLL )\n#    define GSL_FUN extern __declspec(dllexport)\n#  else\n#    define GSL_FUN extern __declspec(dllimport)\n#  endif\n#endif\n\n#include <stdio.h>\n#include <gsl/gsl_monte.h>\n#include <gsl/gsl_rng.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct {\n  size_t dim;\n  double *x;\n} gsl_monte_plain_state;\n\nGSL_FUN int\ngsl_monte_plain_integrate (const gsl_monte_function * f,\n                           const double xl[], const double xu[],\n                           const size_t dim,\n                           const size_t calls, \n                           gsl_rng * r,\n                           gsl_monte_plain_state * state,\n                           double *result, double *abserr);\n\nGSL_FUN gsl_monte_plain_state* gsl_monte_plain_alloc(size_t dim);\n\nGSL_FUN int gsl_monte_plain_init(gsl_monte_plain_state* state);\n\nGSL_FUN void gsl_monte_plain_free (gsl_monte_plain_state* state);\n\n__END_DECLS\n\n#endif /* __GSL_MONTE_PLAIN_H__ */\n", "meta": {"hexsha": "a62879650bc67801f863cb9c46c93ab9de484c42", "size": 2149, "ext": "h", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_monte_plain.h", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-28T08:20:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-28T08:20:20.000Z", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_monte_plain.h", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_monte_plain.h", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-14T12:45:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-14T12:45:35.000Z", "avg_line_length": 28.2763157895, "max_line_length": 81, "alphanum_fraction": 0.6942764076, "num_tokens": 541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936413143782797, "lm_q2_score": 0.046033901581263824, "lm_q1q2_score": 0.01654293305844533}}
{"text": "/*\n * \n * Copyright (c) Kresimir Fresl 2002 \n *\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * Author acknowledges the support of the Faculty of Civil Engineering, \n * University of Zagreb, Croatia.\n *\n */\n\n#ifndef BOOST_NUMERIC_BINDINGS_BLAS_DETAIL_CBLAS_H\n#define BOOST_NUMERIC_BINDINGS_BLAS_DETAIL_CBLAS_H\n\n//\n// MKL-specific CBLAS include\n//\n#if defined BOOST_NUMERIC_BINDINGS_BLAS_MKL\n\nextern \"C\" {\n#include <mkl_cblas.h>\n//#include <mkl_service.h>\n//\n// mkl_types.h defines P4 macro which breaks MPL, undefine it here.\n//\n#undef P4\n}\n\n//\n// Default CBLAS include\n//\n#else\n\nextern \"C\" {\n#include <cblas.h>\n}\n\n#endif\n#endif \n", "meta": {"hexsha": "d0df1fe638efeca8b422f5ca387a0518c970c25f", "size": 744, "ext": "h", "lang": "C", "max_stars_repo_path": "externals/numeric_bindings/boost/numeric/bindings/blas/detail/cblas.h", "max_stars_repo_name": "siconos/siconos-deb", "max_stars_repo_head_hexsha": "2739a23f23d797dbfecec79d409e914e13c45c67", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "externals/numeric_bindings/boost/numeric/bindings/blas/detail/cblas.h", "max_issues_repo_name": "siconos/siconos-deb", "max_issues_repo_head_hexsha": "2739a23f23d797dbfecec79d409e914e13c45c67", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "externals/numeric_bindings/boost/numeric/bindings/blas/detail/cblas.h", "max_forks_repo_name": "siconos/siconos-deb", "max_forks_repo_head_hexsha": "2739a23f23d797dbfecec79d409e914e13c45c67", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.7142857143, "max_line_length": 72, "alphanum_fraction": 0.7284946237, "num_tokens": 205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3812195803163617, "lm_q2_score": 0.04336580000026228, "lm_q1q2_score": 0.016531892076183264}}
{"text": "/* ieee-utils/fp-tru64.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Tim Mooney\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n\n/*\n * Under Compaq's Unix with the silly name, read the man pages for read_rnd,\n * write_rnd, and ieee(3) for more information on the functions used here.\n *\n * Note that enabling control of dynamic rounding mode (via write_rnd) requires\n * that you pass a special flag to your C compiler.  For Compaq's C compiler\n * the flag is `-fprm d', for gcc it's `-mfp-rounding-mode=d'.\n *\n * Enabling the trap control (via ieee_set_fp_control) also requires a\n * flag be passed to the C compiler.  The flag for Compaq's C compiler\n * is `-ieee' and for gcc it's `-mieee'.\n\n * We have not implemented the `inexact' case, since it is rarely used\n * and requires the library being built with an additional compiler\n * flag that can degrade performance for everything else. If you need\n * to add support for `inexact' the relevant flag for Compaq's\n * compiler is `-ieee_with_inexact', and the flag for gcc is\n * `-mieee-with-inexact'.\n *\n * Problem have been reported with the \"fixed\" float.h installed with\n * gcc-2.95 lacking some of the definitions in the system float.h (the\n * symptoms are errors like: `FP_RND_RN' undeclared). To work around\n * this we can include the system float.h before the gcc version, e.g. \n *\n *  #include \"/usr/include/float.h\"\n *  #include <float.h>\n */\n\n#include <float.h>\n\n#ifndef FP_RND_RN\n#  undef _FLOAT_H_\n#  include \"/usr/include/float.h\"\n#  undef _FLOAT_H_\n#  include <float.h>\n#endif\n\n#include <machine/fpu.h>\n#include <stdio.h>\n#include <gsl/gsl_ieee_utils.h>\n#include <gsl/gsl_errno.h>\n\nint\ngsl_ieee_set_mode (int precision, int rounding, int exception_mask)\n{\n  unsigned long int mode = 0 ;\n  unsigned int    rnd  = 0 ;\n\n/* I'm actually not completely sure that the alpha only supports default\n * precisions rounding, but I couldn't find any information regarding this, so\n * it seems safe to assume this for now until it's proven otherwise.\n */\n\n  switch (precision)\n    {\n    case GSL_IEEE_SINGLE_PRECISION:\n      GSL_ERROR (\"Tru64 Unix on the alpha only supports default precision rounding\",\n                 GSL_EUNSUP) ;\n      break ;\n    case GSL_IEEE_DOUBLE_PRECISION:\n      GSL_ERROR (\"Tru64 Unix on the alpha only supports default precision rounding\",\n                 GSL_EUNSUP) ;\n      break ;\n    case GSL_IEEE_EXTENDED_PRECISION:\n      GSL_ERROR (\"Tru64 Unix on the alpha only supports default precision rounding\",\n                 GSL_EUNSUP) ;\n      break ;\n    }\n\n\n  switch (rounding)\n    {\n    case GSL_IEEE_ROUND_TO_NEAREST:\n      rnd = FP_RND_RN ;\n      write_rnd (rnd) ;\n      break ;\n    case GSL_IEEE_ROUND_DOWN:\n      rnd = FP_RND_RM ;\n      write_rnd (rnd) ;\n      break ;\n    case GSL_IEEE_ROUND_UP:\n      rnd = FP_RND_RP ;\n      write_rnd (rnd) ;\n      break ;\n    case GSL_IEEE_ROUND_TO_ZERO:\n      rnd = FP_RND_RZ ;\n      write_rnd (rnd) ;\n      break ;\n    default:\n      rnd = FP_RND_RN ;\n      write_rnd (rnd) ;\n    }\n\n  /* Turn on all the exceptions apart from 'inexact' */\n\n  /* from the ieee(3) man page:\n   * IEEE_TRAP_ENABLE_INV       ->      Invalid operation\n   * IEEE_TRAP_ENABLE_DZE       ->      Divide by 0\n   * IEEE_TRAP_ENABLE_OVF       ->      Overflow\n   * IEEE_TRAP_ENABLE_UNF       ->      Underflow\n   * IEEE_TRAP_ENABLE_INE       ->      Inexact (requires special option to C compiler)\n   * IEEE_TRAP_ENABLE_DNO       ->      denormal operand\n   * Note: IEEE_TRAP_ENABLE_DNO is not supported on OSF 3.x or Digital Unix\n   * 4.0 - 4.0d(?).\n   * IEEE_TRAP_ENABLE_MASK      ->      mask of all the trap enables\n   * IEEE_MAP_DMZ                       ->      map denormal inputs to zero\n   * IEEE_MAP_UMZ                       ->      map underflow results to zero\n   */\n\n  mode = IEEE_TRAP_ENABLE_INV | IEEE_TRAP_ENABLE_DZE | IEEE_TRAP_ENABLE_OVF\n                | IEEE_TRAP_ENABLE_UNF ;\n\n  if (exception_mask & GSL_IEEE_MASK_INVALID)\n    mode &= ~ IEEE_TRAP_ENABLE_INV ;\n\n  if (exception_mask & GSL_IEEE_MASK_DENORMALIZED)\n    {\n#ifdef IEEE_TRAP_ENABLE_DNO\n     mode &= ~ IEEE_TRAP_ENABLE_DNO ;\n#else\n     GSL_ERROR (\"Sorry, this version of Digital Unix does not support denormalized operands\", GSL_EUNSUP) ;\n#endif\n    }\n\n  if (exception_mask & GSL_IEEE_MASK_DIVISION_BY_ZERO)\n    mode &= ~ IEEE_TRAP_ENABLE_DZE ;\n\n  if (exception_mask & GSL_IEEE_MASK_OVERFLOW)\n    mode &= ~ IEEE_TRAP_ENABLE_OVF ;\n\n  if (exception_mask & GSL_IEEE_MASK_UNDERFLOW)\n    mode &=  ~ IEEE_TRAP_ENABLE_UNF ;\n\n  if (exception_mask & GSL_IEEE_TRAP_INEXACT)\n    {\n      /* To implement this would require a special flag to the C\n       compiler which can cause degraded performance */\n\n      GSL_ERROR (\"Sorry, GSL does not implement trap-inexact for Tru64 Unix on the alpha - see fp-tru64.c for details\", GSL_EUNSUP) ;\n\n      /* In case you need to add it, the appropriate line would be \n       *  \n       *  mode |= IEEE_TRAP_ENABLE_INE ; \n       *\n       */\n\n    }\n  else\n    {\n      mode &= ~ IEEE_TRAP_ENABLE_INE ;\n    }\n\n  ieee_set_fp_control (mode) ;\n\n  return GSL_SUCCESS ;\n}\n", "meta": {"hexsha": "7feccd9ae38408026ff397fa3fd996a0d4c6aa81", "size": 5759, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/ieee-utils/fp-tru64.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/ieee-utils/fp-tru64.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/ieee-utils/fp-tru64.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 32.5367231638, "max_line_length": 133, "alphanum_fraction": 0.6763326966, "num_tokens": 1510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3923368301671084, "lm_q2_score": 0.042087728366189174, "lm_q1q2_score": 0.016512565936124952}}
{"text": "#include <mpi.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <math.h>\n#include <sys/time.h>\n#include <sys/resource.h>\n#include <unistd.h>\n#include <signal.h>\n#include <gsl/gsl_rng.h>\n\n\n#include \"allvars.h\"\n#include \"proto.h\"\n\n#define TAG_DATAIN  100\n#define TAG_DATAOUT 101\n\n\nstatic void serial_sort(char *base, size_t nmemb, size_t size, int (*compar) (const void *, const void *));\nstatic void msort_serial_with_tmp(char *base, size_t n, size_t s, int (*compar) (const void *, const void *),\n\t\t\t\t  char *t);\nstatic void parallel_merge(int master, int ncpu, size_t * nlist, size_t nmax, char *base, size_t nmemb,\n\t\t\t   size_t size, int (*compar) (const void *, const void *));\n\n\n\nvoid parallel_sort(void *base, size_t nmemb, size_t size, int (*compar) (const void *, const void *))\n{\n  int i, ncpu_in_group, master, groupnr;\n  size_t nmax, *nlist;\n\n  serial_sort((char *) base, nmemb, size, compar);\n\n  nlist = (size_t *) mymalloc(NTask * sizeof(size_t));\n\n  MPI_Allgather(&nmemb, sizeof(size_t), MPI_BYTE, nlist, sizeof(size_t), MPI_BYTE, MPI_COMM_WORLD);\n\n  for(i = 0, nmax = 0; i < NTask; i++)\n    if(nlist[i] > nmax)\n      nmax = nlist[i];\n\n  for(ncpu_in_group = 2; ncpu_in_group <= (1 << PTask); ncpu_in_group *= 2)\n    {\n      groupnr = ThisTask / ncpu_in_group;\n\n      master = ncpu_in_group * groupnr;\n\n      parallel_merge(master, ncpu_in_group, nlist, nmax, (char *) base, nmemb, size, compar);\n    }\n\n  myfree(nlist);\n}\n\nvoid parallel_merge(int master, int ncpu, size_t * nlist, size_t nmax,\n\t\t    char *base, size_t nmemb, size_t size, int (*compar) (const void *, const void *))\n{\n  size_t na, nb, nr;\n  int cpua, cpub, cpur;\n  char *list_a, *list_b, *list_r;\n\n  if(master + ncpu / 2 >= NTask)\t/* nothing to do */\n    return;\n\n  if(ThisTask != master)\n    {\n      if(nmemb)\n\t{\n\t  list_r = (char *) mymalloc(nmemb * size);\n\n\t  MPI_Request requests[2];\n\n\t  MPI_Isend(base, nmemb * size, MPI_BYTE, master, TAG_DATAIN, MPI_COMM_WORLD, &requests[0]);\n\t  MPI_Irecv(list_r, nmemb * size, MPI_BYTE, master, TAG_DATAOUT, MPI_COMM_WORLD, &requests[1]);\n\t  MPI_Waitall(2, requests, MPI_STATUSES_IGNORE);\n\n\t  memcpy(base, list_r, nmemb * size);\n\t  myfree(list_r);\n\t}\n    }\n  else\n    {\n      list_a = (char *) mymalloc(nmax * size);\n      list_b = (char *) mymalloc(nmax * size);\n      list_r = (char *) mymalloc(nmax * size);\n\n      cpua = master;\n      cpub = master + ncpu / 2;\n      cpur = master;\n\n      na = 0;\n      nb = 0;\n      nr = 0;\n\n      memcpy(list_a, base, nmemb * size);\n      if(nlist[cpub])\n\tMPI_Recv(list_b, nlist[cpub] * size, MPI_BYTE, cpub, TAG_DATAIN, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n\n      while(cpur < master + ncpu && cpur < NTask)\n\t{\n\t  while(na >= nlist[cpua] && cpua < master + ncpu / 2 - 1)\n\t    {\n\t      cpua++;\n\t      if(nlist[cpua])\n\t\tMPI_Recv(list_a, nlist[cpua] * size, MPI_BYTE, cpua, TAG_DATAIN, MPI_COMM_WORLD,\n\t\t\t MPI_STATUS_IGNORE);\n\t      na = 0;\n\t    }\n\t  while(nb >= nlist[cpub] && cpub < master + ncpu - 1 && cpub < NTask - 1)\n\t    {\n\t      cpub++;\n\t      if(nlist[cpub])\n\t\tMPI_Recv(list_b, nlist[cpub] * size, MPI_BYTE, cpub, TAG_DATAIN, MPI_COMM_WORLD,\n\t\t\t MPI_STATUS_IGNORE);\n\t      nb = 0;\n\t    }\n\n\t  while(nr >= nlist[cpur])\n\t    {\n\t      if(cpur == master)\n\t\tmemcpy(base, list_r, nr * size);\n\t      else\n\t\t{\n\t\t  if(nlist[cpur])\n\t\t    MPI_Send(list_r, nlist[cpur] * size, MPI_BYTE, cpur, TAG_DATAOUT, MPI_COMM_WORLD);\n\t\t}\n\t      nr = 0;\n\t      cpur++;\n\t    }\n\n\t  if(na < nlist[cpua] && nb < nlist[cpub])\n\t    {\n\t      if(compar(list_a + na * size, list_b + nb * size) < 0)\n\t\t{\n\t\t  memcpy(list_r + nr * size, list_a + na * size, size);\n\t\t  na++;\n\t\t  nr++;\n\t\t}\n\t      else\n\t\t{\n\t\t  memcpy(list_r + nr * size, list_b + nb * size, size);\n\t\t  nb++;\n\t\t  nr++;\n\t\t}\n\t    }\n\t  else if(na < nlist[cpua])\n\t    {\n\t      memcpy(list_r + nr * size, list_a + na * size, size);\n\t      na++;\n\t      nr++;\n\t    }\n\t  else if(nb < nlist[cpub])\n\t    {\n\t      memcpy(list_r + nr * size, list_b + nb * size, size);\n\t      nb++;\n\t      nr++;\n\t    }\n\n\t}\n\n      myfree(list_r);\n      myfree(list_b);\n      myfree(list_a);\n    }\n}\n\n\nstatic void serial_sort(char *base, size_t nmemb, size_t size, int (*compar) (const void *, const void *))\n{\n  const size_t storage = nmemb * size;\n\n  char *tmp = (char *) mymalloc(storage);\n\n  msort_serial_with_tmp(base, nmemb, size, compar, tmp);\n\n  myfree(tmp);\n}\n\n\nstatic void msort_serial_with_tmp(char *base, size_t n, size_t s, int (*compar) (const void *, const void *),\n\t\t\t\t  char *t)\n{\n  char *tmp;\n  char *b1, *b2;\n  size_t n1, n2;\n\n  if(n <= 1)\n    return;\n\n  n1 = n / 2;\n  n2 = n - n1;\n  b1 = base;\n  b2 = base + n1 * s;\n\n  msort_serial_with_tmp(b1, n1, s, compar, t);\n  msort_serial_with_tmp(b2, n2, s, compar, t);\n\n  tmp = t;\n\n  while(n1 > 0 && n2 > 0)\n    {\n      if(compar(b1, b2) < 0)\n\t{\n\t  --n1;\n\t  memcpy(tmp, b1, s);\n\t  tmp += s;\n\t  b1 += s;\n\t}\n      else\n\t{\n\t  --n2;\n\t  memcpy(tmp, b2, s);\n\t  tmp += s;\n\t  b2 += s;\n\t}\n    }\n\n  if(n1 > 0)\n    memcpy(tmp, b1, n1 * s);\n\n  memcpy(base, t, (n - n2) * s);\n}\n", "meta": {"hexsha": "803686b65732557e9d72421082dd295454c36c83", "size": 5010, "ext": "c", "lang": "C", "max_stars_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/parallel_sort.c", "max_stars_repo_name": "egpbos/egp", "max_stars_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/parallel_sort.c", "max_issues_repo_name": "egpbos/egp", "max_issues_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/parallel_sort.c", "max_forks_repo_name": "egpbos/egp", "max_forks_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.466367713, "max_line_length": 109, "alphanum_fraction": 0.5816367265, "num_tokens": 1666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356685373537454, "lm_q2_score": 0.0408457143045326, "lm_q1q2_score": 0.016483976410454203}}
{"text": "#pragma once\n\n#include <memory_resource>\n#include <vector>\n\n#include <thrust/execution_policy.h>\n#include <thrust/functional.h>\n#include <thrust/inner_product.h>\n#include <thrust/iterator/zip_iterator.h>\n#include <thrust/merge.h>\n#include <thrust/reduce.h>\n#include <thrust/sort.h>\n#include <thrust/tuple.h>\n\n#include <gsl-lite/gsl-lite.hpp>\n\n#include <cuda/define_specifiers.hpp>\n\n#include <thrustshift/copy.h>\n#include <thrustshift/equal.h>\n#include <thrustshift/managed-vector.h>\n#include <thrustshift/math.h>\n#include <thrustshift/memory-resource.h>\n#include <thrustshift/not-a-vector.h>\n#include <thrustshift/transform.h>\n\nnamespace thrustshift {\n\nenum class storage_order_t { row_major, col_major, none };\n\ntemplate <typename DataType, typename IndexType>\nclass COO {\n\n   public:\n\tusing value_type = DataType;\n\tusing index_type = IndexType;\n\n\tCOO() : num_cols_(0), num_rows_(0) {\n\t}\n\n\ttemplate <class MemoryResource>\n\tCOO(size_t nnz,\n\t    size_t num_rows,\n\t    size_t num_cols,\n\t    MemoryResource& memory_resource)\n\t    : values_(nnz, &memory_resource),\n\t      row_indices_(nnz, &memory_resource),\n\t      col_indices_(nnz, &memory_resource),\n\t      num_rows_(num_rows),\n\t      num_cols_(num_cols),\n\t      storage_order_(storage_order_t::none) {\n\t}\n\n\tCOO(size_t nnz, size_t num_rows, size_t num_cols)\n\t    : COO(nnz, num_rows, num_cols, pmr::default_resource) {\n\t}\n\n\ttemplate <class DataRange,\n\t          class RowIndRange,\n\t          class ColIndRange,\n\t          class MemoryResource>\n\tCOO(DataRange&& values,\n\t    RowIndRange&& row_indices,\n\t    ColIndRange&& col_indices,\n\t    size_t num_rows,\n\t    size_t num_cols,\n\t    storage_order_t storage_order,\n\t    MemoryResource& memory_resource)\n\t    : values_(values.begin(), values.end(), &memory_resource),\n\t      row_indices_(row_indices.begin(),\n\t                   row_indices.end(),\n\t                   &memory_resource),\n\t      col_indices_(col_indices.begin(),\n\t                   col_indices.end(),\n\t                   &memory_resource),\n\t      num_rows_(num_rows),\n\t      num_cols_(num_cols),\n\t      storage_order_(storage_order) {\n\t\tgsl_Expects(values.size() == row_indices.size());\n\t\tgsl_Expects(values.size() == col_indices.size());\n\t}\n\n\ttemplate <class DataRange,\n\t          class RowIndRange,\n\t          class ColIndRange,\n\t          class MemoryResource>\n\tCOO(DataRange&& values,\n\t    RowIndRange&& row_indices,\n\t    ColIndRange&& col_indices,\n\t    size_t num_rows,\n\t    size_t num_cols,\n\t    MemoryResource& memory_resource)\n\t    : COO(std::forward<DataRange>(values),\n\t          std::forward<RowIndRange>(row_indices),\n\t          std::forward<ColIndRange>(col_indices),\n\t          num_rows,\n\t          num_cols,\n\t          storage_order_t::none,\n\t          memory_resource) {\n\t}\n\n\ttemplate <class DataRange, class ColIndRange, class RowIndRange>\n\tCOO(DataRange&& values,\n\t    RowIndRange&& row_indices,\n\t    ColIndRange&& col_indices,\n\t    size_t num_rows,\n\t    size_t num_cols)\n\t    : COO(std::forward<DataRange>(values),\n\t          std::forward<RowIndRange>(row_indices),\n\t          std::forward<ColIndRange>(col_indices),\n\t          num_rows,\n\t          num_cols,\n\t          pmr::default_resource) {\n\t}\n\n\t// The copy constructor is declared explicitly to ensure\n\t// managed memory is used per default.\n\tCOO(const COO& other)\n\t    : COO(other.values(),\n\t          other.row_indices(),\n\t          other.col_indices(),\n\t          other.num_rows(),\n\t          other.num_cols(),\n\t          other.get_storage_order(),\n\t          pmr::default_resource) {\n\t}\n\n\tCOO(COO&& other) = default;\n\n\tvoid change_storage_order(storage_order_t new_storage_order) {\n\t\tIndexType* primary_keys_first;\n\t\tIndexType* secondary_keys_first;\n\n\t\tif (new_storage_order == storage_order_) {\n\t\t\treturn;\n\t\t}\n\n\t\tswitch (new_storage_order) {\n\t\t\tcase storage_order_t::row_major:\n\t\t\t\tprimary_keys_first = row_indices_.data();\n\t\t\t\tsecondary_keys_first = col_indices_.data();\n\t\t\t\tbreak;\n\t\t\tcase storage_order_t::col_major:\n\t\t\t\tprimary_keys_first = col_indices_.data();\n\t\t\t\tsecondary_keys_first = row_indices_.data();\n\t\t\t\tbreak;\n\t\t\tcase storage_order_t::none:\n\t\t\t\treturn;\n\t\t}\n\n\t\t// Thrust's relational operators are overloaded for thrust::pair.\n\t\t// This ensures that we sort with respect to the second key if the first key is equal.\n\t\tauto key_it = thrust::make_zip_iterator(\n\t\t    thrust::make_tuple(primary_keys_first, secondary_keys_first));\n\t\tthrust::sort_by_key(\n\t\t    thrust::cuda::par, key_it, key_it + values_.size(), values_.data());\n\t\tstorage_order_ = new_storage_order;\n\t}\n\n\t// If the storage order is changed externally\n\tvoid set_storage_order(storage_order_t new_storage_order) {\n\t\tstorage_order_ = new_storage_order;\n\t}\n\n\tvoid transpose() {\n\t\tstd::swap(col_indices_, row_indices_);\n\t\tstd::swap(num_rows_, num_cols_);\n\t\tswitch (storage_order_) {\n\t\t\tcase storage_order_t::none:\n\t\t\t\tbreak;\n\t\t\tcase storage_order_t::row_major:\n\t\t\t\tstorage_order_ = storage_order_t::col_major;\n\t\t\t\tbreak;\n\t\t\tcase storage_order_t::col_major:\n\t\t\t\tstorage_order_ = storage_order_t::row_major;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tgsl_lite::span<DataType> values() {\n\t\treturn gsl_lite::make_span(values_);\n\t}\n\n\tgsl_lite::span<const DataType> values() const {\n\t\treturn gsl_lite::make_span(values_);\n\t}\n\n\tgsl_lite::span<IndexType> row_indices() {\n\t\treturn gsl_lite::make_span(row_indices_);\n\t}\n\n\tgsl_lite::span<const IndexType> row_indices() const {\n\t\treturn gsl_lite::make_span(row_indices_);\n\t}\n\n\tgsl_lite::span<IndexType> col_indices() {\n\t\treturn gsl_lite::make_span(col_indices_);\n\t}\n\n\tgsl_lite::span<const IndexType> col_indices() const {\n\t\treturn gsl_lite::make_span(col_indices_);\n\t}\n\n\tsize_t num_rows() const {\n\t\treturn num_rows_;\n\t}\n\n\tsize_t num_cols() const {\n\t\treturn num_cols_;\n\t}\n\n\tstorage_order_t get_storage_order() const {\n\t\treturn storage_order_;\n\t}\n\n\t//! Return row_ptrs or col_ptrs depending on the current storage order\n\tthrustshift::managed_vector<index_type> get_ptrs() const {\n\t\tgsl_Expects(storage_order_ != storage_order_t::none);\n\t\tauto indices = storage_order_ == storage_order_t::row_major\n\t\t                   ? row_indices()\n\t\t                   : col_indices();\n\t\tauto size = storage_order_ == storage_order_t::row_major ? num_rows()\n\t\t                                                         : num_cols();\n\n\t\tif (indices.size() > 0) {\n\t\t\tthrustshift::managed_vector<index_type> ptrs(size + 1, -1);\n\t\t\tfor (int nns_id = gsl_lite::narrow<int>(indices.size()) - 1;\n\t\t\t     nns_id >= 0;\n\t\t\t     --nns_id) {\n\t\t\t\tptrs[indices[nns_id]] = nns_id;\n\t\t\t}\n\t\t\tptrs[0] = 0;\n\t\t\tptrs.back() = indices.size();\n\t\t\tindex_type k = indices.size();\n\t\t\tfor (int id = gsl_lite::narrow<int>(ptrs.size()) - 1; id > 0;\n\t\t\t     --id) {\n\t\t\t\tif (ptrs[id] == -1) {\n\t\t\t\t\tptrs[id] = k;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tk = ptrs[id];\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn ptrs;\n\t\t}\n\t\telse {\n\t\t\treturn {0};\n\t\t}\n\t}\n\n   private:\n\tstd::pmr::vector<DataType> values_;\n\tstd::pmr::vector<IndexType> row_indices_;\n\tstd::pmr::vector<IndexType> col_indices_;\n\tsize_t num_rows_;\n\tsize_t num_cols_;\n\tstorage_order_t storage_order_;\n};\n\n//! Storage order does not affect comparison operator. Therefore this operator is defined explicitly.\ntemplate <typename DataType, typename IndexType>\nbool operator==(const COO<DataType, IndexType>& a,\n                const COO<DataType, IndexType>& b) {\n\treturn equal(a.values(), b.values()) &&\n\t       equal(a.row_indices(), b.row_indices()) &&\n\t       equal(a.col_indices(), b.col_indices()) &&\n\t       a.num_rows() == b.num_rows() && a.num_cols() == b.num_cols();\n}\n\ntemplate <typename DataType, typename IndexType>\nclass COO_view {\n\n   public:\n\tusing value_type = DataType;\n\tusing index_type = IndexType;\n\n\ttemplate <typename OtherDataType, typename OtherIndexType>\n\tCOO_view(COO<OtherDataType, OtherIndexType>& owner)\n\t    : values_(owner.values()),\n\t      row_indices_(owner.row_indices()),\n\t      col_indices_(owner.col_indices()),\n\t      num_rows_(owner.num_rows()),\n\t      num_cols_(owner.num_cols()) {\n\t}\n\n\ttemplate <typename OtherDataType, typename OtherIndexType>\n\tCOO_view(const COO<OtherDataType, OtherIndexType>& owner)\n\t    : values_(owner.values()),\n\t      row_indices_(owner.row_indices()),\n\t      col_indices_(owner.col_indices()),\n\t      num_rows_(owner.num_rows()),\n\t      num_cols_(owner.num_cols()) {\n\t}\n\n\ttemplate <class ValueRange, class ColIndRange, class RowIndRange>\n\tCOO_view(ValueRange&& values,\n\t         RowIndRange&& row_indices,\n\t         ColIndRange&& col_indices,\n\t         size_t num_rows,\n\t         size_t num_cols)\n\t    : values_(values),\n\t      row_indices_(row_indices),\n\t      col_indices_(col_indices),\n\t      num_rows_(num_rows),\n\t      num_cols_(num_cols) {\n\t\tconst auto nnz = values.size();\n\t\tgsl_Expects(col_indices.size() == nnz);\n\t\tgsl_Expects(row_indices.size() == nnz);\n\t}\n\n\tCOO_view(const COO_view& other) = default;\n\n\tCUDA_FHD gsl_lite::span<DataType> values() {\n\t\treturn values_;\n\t}\n\n\tCUDA_FHD gsl_lite::span<const DataType> values() const {\n\t\treturn values_;\n\t}\n\n\tCUDA_FHD gsl_lite::span<IndexType> row_indices() {\n\t\treturn row_indices_;\n\t}\n\n\tCUDA_FHD gsl_lite::span<const IndexType> row_indices() const {\n\t\treturn row_indices_;\n\t}\n\n\tCUDA_FHD gsl_lite::span<IndexType> col_indices() {\n\t\treturn col_indices_;\n\t}\n\n\tCUDA_FHD gsl_lite::span<const IndexType> col_indices() const {\n\t\treturn col_indices_;\n\t}\n\n\tCUDA_FHD size_t num_rows() const {\n\t\treturn num_rows_;\n\t}\n\n\tCUDA_FHD size_t num_cols() const {\n\t\treturn num_cols_;\n\t}\n\n   private:\n\tgsl_lite::span<DataType> values_;\n\tgsl_lite::span<IndexType> row_indices_;\n\tgsl_lite::span<IndexType> col_indices_;\n\tsize_t num_rows_;\n\tsize_t num_cols_;\n};\n\nnamespace kernel {\n\ntemplate <typename T, typename T0, typename I0, typename T1, typename I1>\n__global__ void diagmm(gsl_lite::span<const T> diag,\n                       COO_view<const T0, const I0> mtx,\n                       COO_view<T1, I1> result_mtx) {\n\n\tconst auto nnz = mtx.values().size();\n\tconst auto gtid = threadIdx.x + blockIdx.x * blockDim.x;\n\tif (gtid < nnz) {\n\t\tresult_mtx.values()[gtid] =\n\t\t    diag[mtx.row_indices()[gtid]] * mtx.values()[gtid];\n\t}\n}\n\n} // namespace kernel\n\nnamespace async {\n\n//! Calculate the product `result_coo_mtx = (diag_mtx * coo_mtx)`\n//! result_coo_mtx can be equal to coo_mtx. Then the multiplication is in place.\ntemplate <class Range, class COO_C0, class COO_C1>\nvoid diagmm(cuda::stream_t& stream,\n            Range&& diag_mtx,\n            COO_C0&& coo_mtx,\n            COO_C1&& result_coo_mtx) {\n\n\tgsl_Expects(coo_mtx.values().size() == result_coo_mtx.values().size());\n\tgsl_Expects(coo_mtx.num_cols() == result_coo_mtx.num_cols());\n\tgsl_Expects(coo_mtx.num_rows() == result_coo_mtx.num_rows());\n\tgsl_Expects(diag_mtx.size() == coo_mtx.num_rows());\n\t// Only square matrices are allowed\n\tgsl_Expects(coo_mtx.num_rows() == coo_mtx.num_cols());\n\n\tusing RangeT = typename std::remove_reference<Range>::type::value_type;\n\tusing COO_T0 = typename std::remove_reference<COO_C0>::type::value_type;\n\tusing COO_I0 = typename std::remove_reference<COO_C0>::type::index_type;\n\tusing COO_T1 = typename std::remove_reference<COO_C1>::type::value_type;\n\tusing COO_I1 = typename std::remove_reference<COO_C1>::type::index_type;\n\n\tconst auto nnz = coo_mtx.values().size();\n\tconstexpr cuda::grid::block_dimension_t block_dim = 128;\n\tconst cuda::grid::dimension_t grid_dim = ceil_divide(nnz, block_dim);\n\tcuda::enqueue_launch(kernel::diagmm<RangeT, COO_T0, COO_I0, COO_T1, COO_I1>,\n\t                     stream,\n\t                     cuda::make_launch_config(grid_dim, block_dim),\n\t                     diag_mtx,\n\t                     coo_mtx,\n\t                     result_coo_mtx);\n}\n\n} // namespace async\n\nnamespace kernel {\n\ntemplate <typename T0, typename I, typename T1>\n__global__ void get_diagonal(COO_view<const T0, const I> mtx,\n                             gsl_lite::span<T1> diag) {\n\n\tconst auto gtid = threadIdx.x + blockIdx.x * blockDim.x;\n\tconst auto values = mtx.values();\n\tconst auto nnz = values.size();\n\tif (gtid < nnz) {\n\t\tconst auto row_id = mtx.row_indices()[gtid];\n\t\tconst auto col_id = mtx.col_indices()[gtid];\n\t\tif (row_id == col_id) {\n\t\t\tdiag[row_id] = values[gtid];\n\t\t}\n\t}\n}\n\n} // namespace kernel\n\nnamespace async {\n\ntemplate <typename T, class COO>\nvoid get_diagonal(cuda::stream_t& stream, COO&& mtx, gsl_lite::span<T> diag) {\n\n\tgsl_Expects(diag.size() == std::min(mtx.num_rows(), mtx.num_cols()));\n\tusing I = typename std::remove_reference<COO>::type::index_type;\n\tusing T0 = typename std::remove_reference<COO>::type::value_type;\n\tconst auto nnz = mtx.values().size();\n\tconstexpr cuda::grid::block_dimension_t block_dim = 128;\n\tconst cuda::grid::dimension_t grid_dim =\n\t    ceil_divide(gsl_lite::narrow<cuda::grid::dimension_t>(nnz),\n\t                gsl_lite::narrow<cuda::grid::dimension_t>(block_dim));\n\tfill(stream, diag, 0);\n\tif (nnz != 0) {\n\t\tcuda::enqueue_launch(kernel::get_diagonal<T0, I, T>,\n\t\t                     stream,\n\t\t                     cuda::make_launch_config(grid_dim, block_dim),\n\t\t                     mtx,\n\t\t                     diag);\n\t}\n}\n\n} // namespace async\n\n/* \\brief Transform two sparse COO matrices coefficient-wise `op(op_a(a), op_b(b))`.\n * \\param a first sparse COO matrix.\n * \\param b second sparse COO matrix.\n * \\param op Binary operator how coefficients at the same positions are combined.\n * \\param op_a Unary operator which is applied to all non-zero coefficients of `a`.\n * \\param op_b Unary operator which is applied to all non-zero coefficients of `b`.\n * \\return COO matrix allocated with `memory_resource`\n * \\note It might be misleading that the binary operator is **not** applied to coefficients, which\n *   only appear in one of the two matrices. E.g. `op=minus`, `op_a=identity`, `op_b=identity` and `a` is a zero matrix the result\n *   is `result != a - b = -b`. Also note that it cannot be ensured that the left operand of the binary operator\n *   is always an element of `a`. Therefore the unary operators are required.\n */\ntemplate <typename DataType,\n          typename IndexType,\n          class BinaryOperator,\n          class UnaryOperatorA,\n          class UnaryOperatorB,\n          class MemoryResource>\nthrustshift::COO<DataType, IndexType> transform(\n    thrustshift::COO_view<const DataType, const IndexType> a,\n    thrustshift::COO_view<const DataType, const IndexType> b,\n    BinaryOperator&& op,\n    UnaryOperatorA&& op_a,\n    UnaryOperatorB&& op_b,\n    MemoryResource& memory_resource) {\n\n\tconst auto nnz_a = a.values().size();\n\tconst auto nnz_b = b.values().size();\n\tconst auto num_rows = a.num_rows();\n\tconst auto num_cols = b.num_cols();\n\tgsl_Expects(b.num_rows() == num_rows);\n\tgsl_Expects(b.num_cols() == num_cols);\n\n\tauto [tmp0, values] =\n\t    make_not_a_vector_and_span<DataType>(nnz_a + nnz_b, memory_resource);\n\tauto [tmp1, row_indices] =\n\t    make_not_a_vector_and_span<IndexType>(nnz_a + nnz_b, memory_resource);\n\tauto [tmp2, col_indices] =\n\t    make_not_a_vector_and_span<IndexType>(nnz_a + nnz_b, memory_resource);\n\n\tauto device = cuda::device::current::get();\n\tauto stream = device.default_stream();\n\n\tasync::transform(stream, a.values(), values.first(nnz_a), op_a);\n\tasync::copy(stream, a.row_indices(), row_indices.first(nnz_a));\n\tasync::copy(stream, a.col_indices(), col_indices.first(nnz_a));\n\n\tasync::transform(stream, b.values(), values.subspan(nnz_a), op_b);\n\tasync::copy(stream, b.row_indices(), row_indices.subspan(nnz_a));\n\tasync::copy(stream, b.col_indices(), col_indices.subspan(nnz_a));\n\n\tusing KeyT = thrust::tuple<IndexType, IndexType>;\n\tauto keys_begin = thrust::make_zip_iterator(\n\t    thrust::make_tuple(row_indices.begin(), col_indices.begin()));\n\tauto keys_end = keys_begin + nnz_a + nnz_b;\n\n\tstd::pmr::polymorphic_allocator<KeyT> alloc(&memory_resource);\n\tthrust::sort_by_key(\n\t    thrust::cuda::par(alloc), keys_begin, keys_end, values.begin());\n\n\tconst std::size_t nnz_result =\n\t    thrust::inner_product(thrust::cuda::par(alloc),\n\t                          keys_begin,\n\t                          keys_end - 1,\n\t                          keys_begin + 1,\n\t                          std::size_t(0),\n\t                          thrust::plus<std::size_t>(),\n\t                          thrust::not_equal_to<KeyT>()) +\n\t    std::size_t(1);\n\n\t// ```cpp\n\t//   auto memory_resource = ...;\n\t//   auto res = transform(..., memory_resource);\n\t//\n\t// ```\n\t// should work fine because the dtor of `res` is called before the dtor of `memory_resource`\n\tCOO<DataType, IndexType> result(\n\t    nnz_result, num_rows, num_cols, memory_resource);\n\tauto keys_result_begin = thrust::make_zip_iterator(thrust::make_tuple(\n\t    result.row_indices().begin(), result.col_indices().begin()));\n\tthrust::reduce_by_key(thrust::cuda::par(alloc),\n\t                      keys_begin,\n\t                      keys_end,\n\t                      values.begin(),\n\t                      keys_result_begin,\n\t                      result.values().begin(),\n\t                      thrust::equal_to<KeyT>(),\n\t                      op);\n\tresult.set_storage_order(storage_order_t::row_major);\n\treturn result;\n}\n\ntemplate <typename DataType, typename IndexType, class MemoryResource>\nCOO<DataType, IndexType> symmetrize_abs(\n    COO_view<const DataType, const IndexType> mtx,\n    MemoryResource& memory_resource) {\n\n\tif (mtx.values().empty()) {\n\t\treturn COO<DataType, IndexType>(\n\t\t    0, mtx.num_rows(), mtx.num_cols(), memory_resource);\n\t}\n\n\tCOO_view<const DataType, const IndexType> mtx_trans(mtx.values(),\n\t                                                    mtx.col_indices(),\n\t                                                    mtx.row_indices(),\n\t                                                    mtx.num_rows(),\n\t                                                    mtx.num_cols());\n\n\tauto abs = [] __device__(DataType x) { return std::abs(x); };\n\n\treturn transform(\n\t    mtx,\n\t    mtx_trans,\n\t    [] __device__(DataType x, DataType y) { return x + y; },\n\t    abs,\n\t    abs,\n\t    memory_resource);\n}\n\ntemplate <typename DataType, typename IndexType, class MemoryResource>\nCOO<DataType, IndexType> make_pattern_symmetric(\n    COO_view<const DataType, const IndexType> mtx,\n    MemoryResource& memory_resource) {\n\n\tif (mtx.values().empty()) {\n\t\treturn COO<DataType, IndexType>(\n\t\t    0, mtx.num_rows(), mtx.num_cols(), memory_resource);\n\t}\n\n\tCOO_view<const DataType, const IndexType> mtx_trans(mtx.values(),\n\t                                                    mtx.col_indices(),\n\t                                                    mtx.row_indices(),\n\t                                                    mtx.num_rows(),\n\t                                                    mtx.num_cols());\n\n\tauto identity = [] __device__(DataType x) { return x; };\n\tauto make_zero = [] __device__(DataType x) { return DataType(0); };\n\n\treturn transform(\n\t    mtx,\n\t    mtx_trans,\n\t    [] __device__(DataType x, DataType y) { return x + y; },\n\t    identity,\n\t    make_zero,\n\t    memory_resource);\n}\n\n} // namespace thrustshift\n", "meta": {"hexsha": "48cd49ee9e82032f6cb3370c88b3e8e2163a3a50", "size": 18882, "ext": "h", "lang": "C", "max_stars_repo_path": "include/thrustshift/COO.h", "max_stars_repo_name": "codecircuit/thrustshift", "max_stars_repo_head_hexsha": "533ed68f6aa201f54b9622dcaa203fdf6844b466", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-16T13:01:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T13:01:46.000Z", "max_issues_repo_path": "include/thrustshift/COO.h", "max_issues_repo_name": "codecircuit/thrustshift", "max_issues_repo_head_hexsha": "533ed68f6aa201f54b9622dcaa203fdf6844b466", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-23T14:12:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-17T11:40:04.000Z", "max_forks_repo_path": "include/thrustshift/COO.h", "max_forks_repo_name": "codecircuit/thrustshift", "max_forks_repo_head_hexsha": "533ed68f6aa201f54b9622dcaa203fdf6844b466", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5225375626, "max_line_length": 130, "alphanum_fraction": 0.6534795043, "num_tokens": 4652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.037892427580287096, "lm_q1q2_score": 0.016444611226268637}}
{"text": "#pragma once\n\n#include <petsc.h>\n#include <memory>\n\n#include \"partition/rank_subset.h\"\n\nnamespace TimeSteppingScheme\n{\n\nnamespace NestedMatVecUtility\n{\n\n//! from a Petsc Vec with nested type (nestedVec) create a new Petsc Vec (singleVec) that contains all values at once. If the singleVec already exists, do not create again, only copy the values.\nvoid createVecFromNestedVec(Vec nestedVec, Vec &singleVec, std::shared_ptr<Partition::RankSubset> rankSubset);\n\n//! copy the values from a singleVec back to the nested Petsc Vec (nestedVec)\nvoid fillNestedVec(Vec singleVec, Vec nestedVec);\n\n//! from a Petsc Mat with nested type (nestedMat) create a new Petsc Mat (singleMat) that contains all values at once. If the singleMat already exists, do not create again, only copy the values.\nvoid createMatFromNestedMat(Mat nestedMat, Mat &singleMat, std::shared_ptr<Partition::RankSubset> rankSubset);\n\n} \n}  // namespace\n", "meta": {"hexsha": "cc65045eee19286f85d58bf4bec932406b6a197f", "size": 915, "ext": "h", "lang": "C", "max_stars_repo_path": "core/src/specialized_solver/multidomain_solver/nested_mat_vec_utility.h", "max_stars_repo_name": "maierbn/opendihu", "max_stars_repo_head_hexsha": "577650e2f6b36a7306766b0f4176f8124458cbf0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2018-11-25T19:29:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-20T04:46:22.000Z", "max_issues_repo_path": "core/src/specialized_solver/multidomain_solver/nested_mat_vec_utility.h", "max_issues_repo_name": "maierbn/opendihu", "max_issues_repo_head_hexsha": "577650e2f6b36a7306766b0f4176f8124458cbf0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-11-12T15:15:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-29T15:29:24.000Z", "max_forks_repo_path": "core/src/specialized_solver/multidomain_solver/nested_mat_vec_utility.h", "max_forks_repo_name": "maierbn/opendihu", "max_forks_repo_head_hexsha": "577650e2f6b36a7306766b0f4176f8124458cbf0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-10-17T12:18:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-28T13:24:20.000Z", "avg_line_length": 36.6, "max_line_length": 194, "alphanum_fraction": 0.7781420765, "num_tokens": 218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.03789242337013433, "lm_q1q2_score": 0.016444609399140372}}
{"text": "/*\n * \\file base.h\n * \\brief Header file with base requirements for codes\n *\n *\n */\n\n#ifndef BASE_H\n#define BASE_H\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <getopt.h>\n#include <unistd.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <time.h>\n\n#include <bzlib.h>\n#include <hdf5.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_eigen.h>\n\n#define NAME_LENGTH 256\n#define LONG_LENGTH 3000\n\n\n#endif    /*  BASE_H  */\n", "meta": {"hexsha": "b8a96b9407f886b2853618dd43380efb2a3d629d", "size": 464, "ext": "h", "lang": "C", "max_stars_repo_path": "src/base.h", "max_stars_repo_name": "rcanasv/astrolibc", "max_stars_repo_head_hexsha": "e19b8ec8996eaa801ae462528db03e8d04532fc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/base.h", "max_issues_repo_name": "rcanasv/astrolibc", "max_issues_repo_head_hexsha": "e19b8ec8996eaa801ae462528db03e8d04532fc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/base.h", "max_forks_repo_name": "rcanasv/astrolibc", "max_forks_repo_head_hexsha": "e19b8ec8996eaa801ae462528db03e8d04532fc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.9677419355, "max_line_length": 54, "alphanum_fraction": 0.6810344828, "num_tokens": 130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.38491213037224875, "lm_q2_score": 0.04272219724178408, "lm_q1q2_score": 0.01644429195451852}}
{"text": "/* rb.c\n * \n * Copyright (C) 1998-2002, 2004 Free Software Foundation, Inc.\n * Copyright (C) 2018 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* This code is originally from GNU libavl, with some modifications */\n\n#include <config.h>\n#include <stdlib.h>\n#include <stddef.h>\n#include <string.h>\n\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_bst.h>\n#include <gsl/gsl_errno.h>\n\ntypedef struct gsl_bst_rb_node rb_node;\ntypedef gsl_bst_rb_table rb_table;\ntypedef gsl_bst_rb_traverser rb_traverser;\n\nenum rb_color\n{\n  RB_BLACK, /* black */\n  RB_RED    /* red */\n};\n\n#ifndef RB_MAX_HEIGHT\n#define RB_MAX_HEIGHT GSL_BST_RB_MAX_HEIGHT\n#endif\n\n/* tree functions */\nstatic int rb_init(const gsl_bst_allocator * allocator, gsl_bst_cmp_function * compare,\n                   void * params, void * vtable);\nstatic size_t rb_nodes (const void * vtable);\nstatic int rb_empty (void * vtable);\nstatic void ** rb_probe (void * item, rb_table * table);\nstatic void * rb_insert (void * item, void * vtable);\nstatic void * rb_find (const void * item, const void * vtable);\nstatic void * rb_remove (const void * item, void * vtable);\n\n/* traverser functions */\nstatic int rb_t_init (void * vtrav, const void * vtable);\nstatic void * rb_t_first (void * vtrav, const void * vtable);\nstatic void * rb_t_last (void * vtrav, const void * vtable);\nstatic void * rb_t_find (const void * item, void * vtrav, const void * vtable);\nstatic void * rb_t_insert (void * item, void * vtrav, void * vtable);\nstatic void * rb_t_copy (void * vtrav, const void * vsrc);\nstatic void * rb_t_next (void * vtrav);\nstatic void * rb_t_prev (void * vtrav);\nstatic void * rb_t_cur (const void * vtrav);\nstatic void * rb_t_replace (void * vtrav, void * new_item);\nstatic void rb_trav_refresh (rb_traverser *trav);\n\nstatic int\nrb_init(const gsl_bst_allocator * allocator, gsl_bst_cmp_function * compare,\n        void * params, void * vtable)\n{\n  rb_table * table = (rb_table *) vtable;\n\n  table->rb_alloc = allocator;\n  table->rb_compare = compare;\n  table->rb_param = params;\n\n  table->rb_root = NULL;\n  table->rb_count = 0;\n  table->rb_generation = 0;\n\n  return GSL_SUCCESS;\n}\n\nstatic size_t\nrb_nodes (const void * vtable)\n{\n  const rb_table * table = (const rb_table *) vtable;\n  return table->rb_count;\n}\n\n/* empty tree (delete all nodes) but do not free the tree itself */\nstatic int\nrb_empty (void * vtable)\n{\n  rb_table * table = (rb_table *) vtable;\n  rb_node *p, *q;\n\n  for (p = table->rb_root; p != NULL; p = q)\n    {\n      if (p->rb_link[0] == NULL)\n        {\n          q = p->rb_link[1];\n          table->rb_alloc->free (p, table->rb_param);\n        }\n      else\n        {\n          q = p->rb_link[0];\n          p->rb_link[0] = q->rb_link[1];\n          q->rb_link[1] = p;\n        }\n    }\n\n  table->rb_root = NULL;\n  table->rb_count = 0;\n  table->rb_generation = 0;\n\n  return GSL_SUCCESS;\n}\n\n/* Inserts |item| into |table| and returns a pointer to |item|'s address.\n   If a duplicate item is found in the tree,\n   returns a pointer to the duplicate without inserting |item|.\n   Returns |NULL| in case of memory allocation failure. */\n\nstatic void **\nrb_probe (void * item, rb_table * table)\n{\n  rb_node *pa[RB_MAX_HEIGHT];      /* nodes on stack */\n  unsigned char da[RB_MAX_HEIGHT]; /* directions moved from stack nodes */\n  int k;                           /* stack height */\n\n  rb_node *p; /* traverses tree looking for insertion point */\n  rb_node *n; /* newly inserted node */\n\n  pa[0] = (rb_node *) &table->rb_root;\n  da[0] = 0;\n  k = 1;\n  for (p = table->rb_root; p != NULL; p = p->rb_link[da[k - 1]])\n    {\n      int cmp = table->rb_compare (item, p->rb_data, table->rb_param);\n      if (cmp == 0)\n        return &p->rb_data;\n\n      pa[k] = p;\n      da[k++] = cmp > 0;\n    }\n\n  n = pa[k - 1]->rb_link[da[k - 1]] =\n    table->rb_alloc->alloc (sizeof *n, table->rb_param);\n  if (n == NULL)\n    return NULL;\n\n  n->rb_data = item;\n  n->rb_link[0] = n->rb_link[1] = NULL;\n  n->rb_color = RB_RED;\n  table->rb_count++;\n  table->rb_generation++;\n\n  while (k >= 3 && pa[k - 1]->rb_color == RB_RED)\n    {\n      if (da[k - 2] == 0)\n        {\n          rb_node *y = pa[k - 2]->rb_link[1];\n          if (y != NULL && y->rb_color == RB_RED)\n            {\n              pa[k - 1]->rb_color = y->rb_color = RB_BLACK;\n              pa[k - 2]->rb_color = RB_RED;\n              k -= 2;\n            }\n          else\n            {\n              rb_node *x;\n\n              if (da[k - 1] == 0)\n                y = pa[k - 1];\n              else\n                {\n                  x = pa[k - 1];\n                  y = x->rb_link[1];\n                  x->rb_link[1] = y->rb_link[0];\n                  y->rb_link[0] = x;\n                  pa[k - 2]->rb_link[0] = y;\n                }\n\n              x = pa[k - 2];\n              x->rb_color = RB_RED;\n              y->rb_color = RB_BLACK;\n\n              x->rb_link[0] = y->rb_link[1];\n              y->rb_link[1] = x;\n              pa[k - 3]->rb_link[da[k - 3]] = y;\n              break;\n            }\n        }\n      else\n        {\n          rb_node *y = pa[k - 2]->rb_link[0];\n          if (y != NULL && y->rb_color == RB_RED)\n            {\n              pa[k - 1]->rb_color = y->rb_color = RB_BLACK;\n              pa[k - 2]->rb_color = RB_RED;\n              k -= 2;\n            }\n          else\n            {\n              rb_node *x;\n\n              if (da[k - 1] == 1)\n                y = pa[k - 1];\n              else\n                {\n                  x = pa[k - 1];\n                  y = x->rb_link[0];\n                  x->rb_link[0] = y->rb_link[1];\n                  y->rb_link[1] = x;\n                  pa[k - 2]->rb_link[1] = y;\n                }\n\n              x = pa[k - 2];\n              x->rb_color = RB_RED;\n              y->rb_color = RB_BLACK;\n\n              x->rb_link[1] = y->rb_link[0];\n              y->rb_link[0] = x;\n              pa[k - 3]->rb_link[da[k - 3]] = y;\n              break;\n            }\n        }\n    }\n\n  table->rb_root->rb_color = RB_BLACK;\n\n  return &n->rb_data;\n}\n\n/* Inserts |item| into |table|.\n   Returns |NULL| if |item| was successfully inserted\n   or if a memory allocation error occurred.\n   Otherwise, returns the duplicate item. */\n\nstatic void *\nrb_insert (void * item, void * vtable)\n{\n  void **p = rb_probe (item, vtable);\n  return p == NULL || *p == item ? NULL : *p;\n}\n\n/* Search |table| for an item matching |item|, and return it if found.\n   Otherwise return |NULL|. */\nstatic void *\nrb_find (const void * item, const void * vtable)\n{\n  const rb_table * table = (const rb_table *) vtable;\n  const rb_node *p;\n\n  for (p = table->rb_root; p != NULL; )\n    {\n      int cmp = table->rb_compare (item, p->rb_data, table->rb_param);\n\n      if (cmp < 0)\n        p = p->rb_link[0];\n      else if (cmp > 0)\n        p = p->rb_link[1];\n      else /* |cmp == 0| */\n        return p->rb_data;\n    }\n\n  return NULL;\n}\n\n#if 0 /*XXX*/\n\n/* Inserts |item| into |table|, replacing any duplicate item.\n   Returns |NULL| if |item| was inserted without replacing a duplicate,\n   or if a memory allocation error occurred.\n   Otherwise, returns the item that was replaced. */\nvoid *\nrb_replace (struct rb_table *table, void *item)\n{\n  void **p = rb_probe (table, item);\n  if (p == NULL || *p == item)\n    return NULL;\n  else\n    {\n      void *r = *p;\n      *p = item;\n      return r;\n    }\n}\n\n#endif\n\n/* Deletes from |table| and returns an item matching |item|.\n   Returns a null pointer if no matching item found. */\n\nstatic void *\nrb_remove (const void * item, void * vtable)\n{\n  rb_table * table = (rb_table *) vtable;\n  rb_node *pa[RB_MAX_HEIGHT];      /* nodes on stack */\n  unsigned char da[RB_MAX_HEIGHT]; /* directions moved from stack nodes */\n  int k;                           /* stack height */\n\n  rb_node *p;    /* the node to delete, or a node part way to it */\n  int cmp;       /* result of comparison between |item| and |p| */\n\n  k = 0;\n  p = (rb_node *) &table->rb_root;\n  for (cmp = -1; cmp != 0;\n       cmp = table->rb_compare (item, p->rb_data, table->rb_param))\n    {\n      int dir = cmp > 0;\n\n      pa[k] = p;\n      da[k++] = dir;\n\n      p = p->rb_link[dir];\n      if (p == NULL)\n        return NULL;\n    }\n  item = p->rb_data;\n\n  if (p->rb_link[1] == NULL)\n    pa[k - 1]->rb_link[da[k - 1]] = p->rb_link[0];\n  else\n    {\n      enum rb_color t;\n      rb_node *r = p->rb_link[1];\n\n      if (r->rb_link[0] == NULL)\n        {\n          r->rb_link[0] = p->rb_link[0];\n          t = r->rb_color;\n          r->rb_color = p->rb_color;\n          p->rb_color = t;\n          pa[k - 1]->rb_link[da[k - 1]] = r;\n          da[k] = 1;\n          pa[k++] = r;\n        }\n      else\n        {\n          rb_node *s;\n          int j = k++;\n\n          for (;;)\n            {\n              da[k] = 0;\n              pa[k++] = r;\n              s = r->rb_link[0];\n              if (s->rb_link[0] == NULL)\n                break;\n\n              r = s;\n            }\n\n          da[j] = 1;\n          pa[j] = s;\n          pa[j - 1]->rb_link[da[j - 1]] = s;\n\n          s->rb_link[0] = p->rb_link[0];\n          r->rb_link[0] = s->rb_link[1];\n          s->rb_link[1] = p->rb_link[1];\n\n          t = s->rb_color;\n          s->rb_color = p->rb_color;\n          p->rb_color = t;\n        }\n    }\n\n  if (p->rb_color == RB_BLACK)\n    {\n      for (;;)\n        {\n          rb_node *x = pa[k - 1]->rb_link[da[k - 1]];\n          if (x != NULL && x->rb_color == RB_RED)\n            {\n              x->rb_color = RB_BLACK;\n              break;\n            }\n          if (k < 2)\n            break;\n\n          if (da[k - 1] == 0)\n            {\n              rb_node *w = pa[k - 1]->rb_link[1];\n\n              if (w->rb_color == RB_RED)\n                {\n                  w->rb_color = RB_BLACK;\n                  pa[k - 1]->rb_color = RB_RED;\n\n                  pa[k - 1]->rb_link[1] = w->rb_link[0];\n                  w->rb_link[0] = pa[k - 1];\n                  pa[k - 2]->rb_link[da[k - 2]] = w;\n\n                  pa[k] = pa[k - 1];\n                  da[k] = 0;\n                  pa[k - 1] = w;\n                  k++;\n\n                  w = pa[k - 1]->rb_link[1];\n                }\n\n              if ((w->rb_link[0] == NULL\n                   || w->rb_link[0]->rb_color == RB_BLACK)\n                  && (w->rb_link[1] == NULL\n                      || w->rb_link[1]->rb_color == RB_BLACK))\n                w->rb_color = RB_RED;\n              else\n                {\n                  if (w->rb_link[1] == NULL\n                      || w->rb_link[1]->rb_color == RB_BLACK)\n                    {\n                      rb_node *y = w->rb_link[0];\n                      y->rb_color = RB_BLACK;\n                      w->rb_color = RB_RED;\n                      w->rb_link[0] = y->rb_link[1];\n                      y->rb_link[1] = w;\n                      w = pa[k - 1]->rb_link[1] = y;\n                    }\n\n                  w->rb_color = pa[k - 1]->rb_color;\n                  pa[k - 1]->rb_color = RB_BLACK;\n                  w->rb_link[1]->rb_color = RB_BLACK;\n\n                  pa[k - 1]->rb_link[1] = w->rb_link[0];\n                  w->rb_link[0] = pa[k - 1];\n                  pa[k - 2]->rb_link[da[k - 2]] = w;\n                  break;\n                }\n            }\n          else\n            {\n              rb_node *w = pa[k - 1]->rb_link[0];\n\n              if (w->rb_color == RB_RED)\n                {\n                  w->rb_color = RB_BLACK;\n                  pa[k - 1]->rb_color = RB_RED;\n\n                  pa[k - 1]->rb_link[0] = w->rb_link[1];\n                  w->rb_link[1] = pa[k - 1];\n                  pa[k - 2]->rb_link[da[k - 2]] = w;\n\n                  pa[k] = pa[k - 1];\n                  da[k] = 1;\n                  pa[k - 1] = w;\n                  k++;\n\n                  w = pa[k - 1]->rb_link[0];\n                }\n\n              if ((w->rb_link[0] == NULL\n                   || w->rb_link[0]->rb_color == RB_BLACK)\n                  && (w->rb_link[1] == NULL\n                      || w->rb_link[1]->rb_color == RB_BLACK))\n                w->rb_color = RB_RED;\n              else\n                {\n                  if (w->rb_link[0] == NULL\n                      || w->rb_link[0]->rb_color == RB_BLACK)\n                    {\n                      rb_node *y = w->rb_link[1];\n                      y->rb_color = RB_BLACK;\n                      w->rb_color = RB_RED;\n                      w->rb_link[1] = y->rb_link[0];\n                      y->rb_link[0] = w;\n                      w = pa[k - 1]->rb_link[0] = y;\n                    }\n\n                  w->rb_color = pa[k - 1]->rb_color;\n                  pa[k - 1]->rb_color = RB_BLACK;\n                  w->rb_link[0]->rb_color = RB_BLACK;\n\n                  pa[k - 1]->rb_link[0] = w->rb_link[1];\n                  w->rb_link[1] = pa[k - 1];\n                  pa[k - 2]->rb_link[da[k - 2]] = w;\n                  break;\n                }\n            }\n\n          k--;\n        }\n\n    }\n\n  table->rb_alloc->free (p, table->rb_param);\n  table->rb_count--;\n  table->rb_generation++;\n\n  return (void *) item;\n}\n\n/* Initializes |trav| for use with |tree| and selects the null node. */\nstatic int\nrb_t_init (void * vtrav, const void * vtable)\n{\n  rb_traverser * trav = (rb_traverser *) vtrav;\n  const rb_table * table = (const rb_table *) vtable;\n\n  trav->rb_table = table;\n  trav->rb_node = NULL;\n  trav->rb_height = 0;\n  trav->rb_generation = table->rb_generation;\n\n  return GSL_SUCCESS;\n}\n\n/* Initializes |trav| for |table|\n   and selects and returns a pointer to its least-valued item.\n   Returns |NULL| if |table| contains no nodes. */\nstatic void *\nrb_t_first (void * vtrav, const void * vtable)\n{\n  const rb_table * table = (const rb_table *) vtable;\n  rb_traverser * trav = (rb_traverser *) vtrav;\n  rb_node *x;\n\n  trav->rb_table = table;\n  trav->rb_height = 0;\n  trav->rb_generation = table->rb_generation;\n\n  x = table->rb_root;\n  if (x != NULL)\n    {\n      while (x->rb_link[0] != NULL)\n        {\n          if (trav->rb_height >= RB_MAX_HEIGHT)\n            {\n              GSL_ERROR_NULL (\"traverser height exceeds maximum\", GSL_ETABLE);\n            }\n\n          trav->rb_stack[trav->rb_height++] = x;\n          x = x->rb_link[0];\n        }\n    }\n\n  trav->rb_node = x;\n\n  return x != NULL ? x->rb_data : NULL;\n}\n\n/* Initializes |trav| for |table|\n   and selects and returns a pointer to its greatest-valued item.\n   Returns |NULL| if |table| contains no nodes. */\nstatic void *\nrb_t_last (void * vtrav, const void * vtable)\n{\n  const rb_table * table = (const rb_table *) vtable;\n  rb_traverser * trav = (rb_traverser *) vtrav;\n  rb_node *x;\n\n  trav->rb_table = table;\n  trav->rb_height = 0;\n  trav->rb_generation = table->rb_generation;\n\n  x = table->rb_root;\n  if (x != NULL)\n    {\n      while (x->rb_link[1] != NULL)\n        {\n          if (trav->rb_height >= RB_MAX_HEIGHT)\n            {\n              GSL_ERROR_NULL (\"traverser height exceeds maximum\", GSL_ETABLE);\n            }\n\n          trav->rb_stack[trav->rb_height++] = x;\n          x = x->rb_link[1];\n        }\n    }\n\n  trav->rb_node = x;\n\n  return x != NULL ? x->rb_data : NULL;\n}\n\n/* Searches for |item| in |table|.\n   If found, initializes |trav| to the item found and returns the item\n   as well.\n   If there is no matching item, initializes |trav| to the null item\n   and returns |NULL|. */\nstatic void *\nrb_t_find (const void * item, void * vtrav, const void * vtable)\n{\n  const rb_table * table = (const rb_table *) vtable;\n  rb_traverser * trav = (rb_traverser *) vtrav;\n  rb_node *p, *q;\n\n  trav->rb_table = table;\n  trav->rb_height = 0;\n  trav->rb_generation = table->rb_generation;\n  for (p = table->rb_root; p != NULL; p = q)\n    {\n      int cmp = table->rb_compare (item, p->rb_data, table->rb_param);\n\n      if (cmp < 0)\n        q = p->rb_link[0];\n      else if (cmp > 0)\n        q = p->rb_link[1];\n      else /* |cmp == 0| */\n        {\n          trav->rb_node = p;\n          return p->rb_data;\n        }\n\n      if (trav->rb_height >= RB_MAX_HEIGHT)\n        {\n          GSL_ERROR_NULL (\"traverser height exceeds maximum\", GSL_ETABLE);\n        }\n\n      trav->rb_stack[trav->rb_height++] = p;\n    }\n\n  trav->rb_height = 0;\n  trav->rb_node = NULL;\n\n  return NULL;\n}\n\n/* Attempts to insert |item| into |table|.\n   If |item| is inserted successfully, it is returned and |trav| is\n   initialized to its location.\n   If a duplicate is found, it is returned and |trav| is initialized to\n   its location.  No replacement of the item occurs.\n   If a memory allocation failure occurs, |NULL| is returned and |trav|\n   is initialized to the null item. */\nstatic void *\nrb_t_insert (void * item, void * vtrav, void * vtable)\n{\n  rb_table * table = (rb_table *) vtable;\n  rb_traverser * trav = (rb_traverser *) vtrav;\n  void **p;\n\n  p = rb_probe (item, table);\n  if (p != NULL)\n    {\n      trav->rb_table = table;\n      trav->rb_node = ((rb_node *) ((char *) p - offsetof (rb_node, rb_data)));\n      trav->rb_generation = table->rb_generation - 1;\n      return *p;\n    }\n  else\n    {\n      rb_t_init (vtrav, vtable);\n      return NULL;\n    }\n}\n\n/* Initializes |trav| to have the same current node as |src|. */\nstatic void *\nrb_t_copy (void * vtrav, const void * vsrc)\n{\n  const rb_traverser * src = (const rb_traverser *) vsrc;\n  rb_traverser * trav = (rb_traverser *) vtrav;\n\n  if (trav != src)\n    {\n      trav->rb_table = src->rb_table;\n      trav->rb_node = src->rb_node;\n      trav->rb_generation = src->rb_generation;\n      if (trav->rb_generation == trav->rb_table->rb_generation)\n        {\n          trav->rb_height = src->rb_height;\n          memcpy (trav->rb_stack, (const void *) src->rb_stack,\n                  sizeof *trav->rb_stack * trav->rb_height);\n        }\n    }\n\n  return trav->rb_node != NULL ? trav->rb_node->rb_data : NULL;\n}\n\n/* Returns the next data item in inorder\n   within the tree being traversed with |trav|,\n   or if there are no more data items returns |NULL|. */\nstatic void *\nrb_t_next (void * vtrav)\n{\n  rb_traverser * trav = (rb_traverser *) vtrav;\n  rb_node *x;\n\n  if (trav->rb_generation != trav->rb_table->rb_generation)\n    rb_trav_refresh (trav);\n\n  x = trav->rb_node;\n  if (x == NULL)\n    {\n      return rb_t_first (vtrav, trav->rb_table);\n    }\n  else if (x->rb_link[1] != NULL)\n    {\n      if (trav->rb_height >= RB_MAX_HEIGHT)\n        {\n          GSL_ERROR_NULL (\"traverser height exceeds maximum\", GSL_ETABLE);\n        }\n\n      trav->rb_stack[trav->rb_height++] = x;\n      x = x->rb_link[1];\n\n      while (x->rb_link[0] != NULL)\n        {\n          if (trav->rb_height >= RB_MAX_HEIGHT)\n            {\n              GSL_ERROR_NULL (\"traverser height exceeds maximum\", GSL_ETABLE);\n            }\n\n          trav->rb_stack[trav->rb_height++] = x;\n          x = x->rb_link[0];\n        }\n    }\n  else\n    {\n      rb_node *y;\n\n      do\n        {\n          if (trav->rb_height == 0)\n            {\n              trav->rb_node = NULL;\n              return NULL;\n            }\n\n          y = x;\n          x = trav->rb_stack[--trav->rb_height];\n        }\n      while (y == x->rb_link[1]);\n    }\n\n  trav->rb_node = x;\n\n  return x->rb_data;\n}\n\n/* Returns the previous data item in inorder\n   within the tree being traversed with |trav|,\n   or if there are no more data items returns |NULL|. */\nstatic void *\nrb_t_prev (void * vtrav)\n{\n  rb_traverser * trav = (rb_traverser *) vtrav;\n  rb_node *x;\n\n  if (trav->rb_generation != trav->rb_table->rb_generation)\n    rb_trav_refresh (trav);\n\n  x = trav->rb_node;\n  if (x == NULL)\n    {\n      return rb_t_last (vtrav, trav->rb_table);\n    }\n  else if (x->rb_link[0] != NULL)\n    {\n      if (trav->rb_height >= RB_MAX_HEIGHT)\n        {\n          GSL_ERROR_NULL (\"traverser height exceeds maximum\", GSL_ETABLE);\n        }\n\n      trav->rb_stack[trav->rb_height++] = x;\n      x = x->rb_link[0];\n\n      while (x->rb_link[1] != NULL)\n        {\n          if (trav->rb_height >= RB_MAX_HEIGHT)\n            {\n              GSL_ERROR_NULL (\"traverser height exceeds maximum\", GSL_ETABLE);\n            }\n\n          trav->rb_stack[trav->rb_height++] = x;\n          x = x->rb_link[1];\n        }\n    }\n  else\n    {\n      rb_node *y;\n\n      do\n        {\n          if (trav->rb_height == 0)\n            {\n              trav->rb_node = NULL;\n              return NULL;\n            }\n\n          y = x;\n          x = trav->rb_stack[--trav->rb_height];\n        }\n      while (y == x->rb_link[0]);\n    }\n\n  trav->rb_node = x;\n\n  return x->rb_data;\n}\n\n/* Returns |trav|'s current item. */\nstatic void *\nrb_t_cur (const void * vtrav)\n{\n  const rb_traverser * trav = (const rb_traverser *) vtrav;\n  return trav->rb_node != NULL ? trav->rb_node->rb_data : NULL;\n}\n\n/* Replaces the current item in |trav| by |new| and returns the item replaced.\n   |trav| must not have the null item selected.\n   The new item must not upset the ordering of the tree. */\nstatic void *\nrb_t_replace (void * vtrav, void * new_item)\n{\n  rb_traverser * trav = (rb_traverser *) vtrav;\n  void *old;\n\n  old = trav->rb_node->rb_data;\n  trav->rb_node->rb_data = new_item;\n\n  return old;\n}\n\n#if 0 /*XXX*/\n/* Destroys |new| with |rb_destroy (new, destroy)|,\n   first setting right links of nodes in |stack| within |new|\n   to null pointers to avoid touching uninitialized data. */\nstatic void\ncopy_error_recovery (rb_node **stack, int height,\n                     struct rb_table *new, rb_item_func *destroy)\n{\n  assert (stack != NULL && height >= 0 && new != NULL);\n\n  for (; height > 2; height -= 2)\n    stack[height - 1]->rb_link[1] = NULL;\n  rb_destroy (new, destroy);\n}\n\n/* Copies |org| to a newly created tree, which is returned.\n   If |copy != NULL|, each data item in |org| is first passed to |copy|,\n   and the return values are inserted into the tree,\n   with |NULL| return values taken as indications of failure.\n   On failure, destroys the partially created new tree,\n   applying |destroy|, if non-null, to each item in the new tree so far,\n   and returns |NULL|.\n   If |allocator != NULL|, it is used for allocation in the new tree.\n   Otherwise, the same allocator used for |org| is used. */\nstruct rb_table *\nrb_copy (const struct rb_table *org, rb_copy_func *copy,\n          rb_item_func *destroy, struct libavl_allocator *allocator)\n{\n  rb_node *stack[2 * (RB_MAX_HEIGHT + 1)];\n  int height = 0;\n\n  struct rb_table *new;\n  const rb_node *x;\n  rb_node *y;\n\n  assert (org != NULL);\n  new = rb_create (org->rb_compare, org->rb_param,\n                    allocator != NULL ? allocator : org->rb_alloc);\n  if (new == NULL)\n    return NULL;\n  new->rb_count = org->rb_count;\n  if (new->rb_count == 0)\n    return new;\n\n  x = (const rb_node *) &org->rb_root;\n  y = (rb_node *) &new->rb_root;\n  for (;;)\n    {\n      while (x->rb_link[0] != NULL)\n        {\n          assert (height < 2 * (RB_MAX_HEIGHT + 1));\n\n          y->rb_link[0] =\n            new->rb_alloc->libavl_malloc (new->rb_alloc,\n                                           sizeof *y->rb_link[0]);\n          if (y->rb_link[0] == NULL)\n            {\n              if (y != (rb_node *) &new->rb_root)\n                {\n                  y->rb_data = NULL;\n                  y->rb_link[1] = NULL;\n                }\n\n              copy_error_recovery (stack, height, new, destroy);\n              return NULL;\n            }\n\n          stack[height++] = (rb_node *) x;\n          stack[height++] = y;\n          x = x->rb_link[0];\n          y = y->rb_link[0];\n        }\n      y->rb_link[0] = NULL;\n\n      for (;;)\n        {\n          y->rb_color = x->rb_color;\n          if (copy == NULL)\n            y->rb_data = x->rb_data;\n          else\n            {\n              y->rb_data = copy (x->rb_data, org->rb_param);\n              if (y->rb_data == NULL)\n                {\n                  y->rb_link[1] = NULL;\n                  copy_error_recovery (stack, height, new, destroy);\n                  return NULL;\n                }\n            }\n\n          if (x->rb_link[1] != NULL)\n            {\n              y->rb_link[1] =\n                new->rb_alloc->libavl_malloc (new->rb_alloc,\n                                               sizeof *y->rb_link[1]);\n              if (y->rb_link[1] == NULL)\n                {\n                  copy_error_recovery (stack, height, new, destroy);\n                  return NULL;\n                }\n\n              x = x->rb_link[1];\n              y = y->rb_link[1];\n              break;\n            }\n          else\n            y->rb_link[1] = NULL;\n\n          if (height <= 2)\n            return new;\n\n          y = stack[--height];\n          x = stack[--height];\n        }\n    }\n}\n\n#endif\n\n/* Refreshes the stack of parent pointers in |trav|\n   and updates its generation number. */\nstatic void\nrb_trav_refresh (rb_traverser *trav)\n{\n  trav->rb_generation = trav->rb_table->rb_generation;\n\n  if (trav->rb_node != NULL)\n    {\n      gsl_bst_cmp_function *cmp = trav->rb_table->rb_compare;\n      void *param = trav->rb_table->rb_param;\n      rb_node *node = trav->rb_node;\n      rb_node *i;\n\n      trav->rb_height = 0;\n      for (i = trav->rb_table->rb_root; i != node; )\n        {\n          if (trav->rb_height >= RB_MAX_HEIGHT)\n            {\n              GSL_ERROR_VOID (\"traverser height exceeds maximum\", GSL_ETABLE);\n            }\n\n          trav->rb_stack[trav->rb_height++] = i;\n          i = i->rb_link[cmp (node->rb_data, i->rb_data, param) > 0];\n        }\n    }\n}\n\nstatic const gsl_bst_type rb_tree_type =\n{\n  \"red-black\",\n  sizeof(rb_node),\n  rb_init,\n  rb_nodes,\n  rb_insert,\n  rb_find,\n  rb_remove,\n  rb_empty,\n\n  rb_t_init,\n  rb_t_first,\n  rb_t_last,\n  rb_t_find,\n  rb_t_insert,\n  rb_t_copy,\n  rb_t_next,\n  rb_t_prev,\n  rb_t_cur,\n  rb_t_replace\n};\n\nconst gsl_bst_type * gsl_bst_rb = &rb_tree_type;\n", "meta": {"hexsha": "c8bd1d5e2876579a7103253eeef025780c412f1d", "size": 26288, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/bst/rb.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "gsl-2.6/bst/rb.c", "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "test/lib/gsl-2.6/bst/rb.c", "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 26.5535353535, "max_line_length": 87, "alphanum_fraction": 0.5149878271, "num_tokens": 7427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.28140560742914383, "lm_q2_score": 0.05834583569951912, "lm_q1q2_score": 0.016418845335984204}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\r\n#ifndef NOMPI\n#include <mpi.h>\r\n#endif\n\n#include <fcntl.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <sys/file.h>\n#include <unistd.h>\n#include <gsl/gsl_rng.h>\n\n#include \"allvars.h\"\n#include \"proto.h\"\n\n/*! \\file restart.c\n *  \\brief Code for reading and writing restart files\n */\n\nstatic FILE *fd;\n\nstatic void in(int *x, int modus);\nstatic void byten(void *x, size_t n, int modus);\n\n\n/*! This function reads or writes the restart files.  Each processor writes\n *  its own restart file, with the I/O being done in parallel. To avoid\n *  congestion of the disks you can tell the program to restrict the number of\n *  files that are simultaneously written to NumFilesWrittenInParallel.\n *\n *  If modus>0 the restart()-routine reads, if modus==0 it writes a restart\n *  file.\n */\nvoid restart(int modus)\n{\n  char buf[200], buf_bak[200], buf_mv[500];\n  double save_PartAllocFactor, save_TreeAllocFactor;\n  int i, nprocgroup, masterTask, groupTask, old_MaxPart, old_MaxNodes;\n  struct global_data_all_processes all_task0;\n\n\n  sprintf(buf, \"%s%s.%d\", All.OutputDir, All.RestartFile, ThisTask);\n  sprintf(buf_bak, \"%s%s.%d.bak\", All.OutputDir, All.RestartFile, ThisTask);\n  sprintf(buf_mv, \"mv %s %s\", buf, buf_bak);\n\n\n  if((NTask < All.NumFilesWrittenInParallel))\n    {\n      printf\n\t(\"Fatal error.\\nNumber of processors must be a smaller or equal than `NumFilesWrittenInParallel'.\\n\");\n      endrun(2131);\n    }\n\n  nprocgroup = NTask / All.NumFilesWrittenInParallel;\n\n  if((NTask % All.NumFilesWrittenInParallel))\n    {\n      nprocgroup++;\n    }\n\n  masterTask = (ThisTask / nprocgroup) * nprocgroup;\n\n  for(groupTask = 0; groupTask < nprocgroup; groupTask++)\n    {\n      if(ThisTask == (masterTask + groupTask))\t/* ok, it's this processor's turn */\n\t{\n\t  if(modus)\n\t    {\n\t      if(!(fd = fopen(buf, \"r\")))\n\t\t{\n\t\t  printf(\"Restart file '%s' not found.\\n\", buf);\n\t\t  endrun(7870);\n\t\t}\n\t    }\n\t  else\n\t    {\n\t      system(buf_mv);\t/* move old restart files to .bak files */\n\n\t      if(!(fd = fopen(buf, \"w\")))\n\t\t{\n\t\t  printf(\"Restart file '%s' cannot be opened.\\n\", buf);\n\t\t  endrun(7878);\n\t\t}\n\t    }\n\n\n\t  save_PartAllocFactor = All.PartAllocFactor;\n\t  save_TreeAllocFactor = All.TreeAllocFactor;\n\n\t  /* common data  */\n\t  byten(&All, sizeof(struct global_data_all_processes), modus);\n\n\t  if(ThisTask == 0 && modus > 0)\n\t    all_task0 = All;\n\n#ifndef NOMPI\n\t  if(modus > 0 && groupTask == 0)\t/* read */\n\t    {\n\t      MPI_Bcast(&all_task0, sizeof(struct global_data_all_processes), MPI_BYTE, 0, GADGET_WORLD);\n\t    }\n#endif\n\t  old_MaxPart = All.MaxPart;\n\t  old_MaxNodes = All.TreeAllocFactor * All.MaxPart;\n\n\t  if(modus)\t\t/* read */\n\t    {\n\t      if(All.PartAllocFactor != save_PartAllocFactor)\n\t\t{\n\t\t  All.PartAllocFactor = save_PartAllocFactor;\n\t\t  All.MaxPart = All.PartAllocFactor * (All.TotNumPart / NTask);\n\t\t  All.MaxPartSph = All.PartAllocFactor * (All.TotN_gas / NTask);\n\t\t  save_PartAllocFactor = -1;\n\t\t}\n\n\t      if(All.TreeAllocFactor != save_TreeAllocFactor)\n\t\t{\n\t\t  All.TreeAllocFactor = save_TreeAllocFactor;\n\t\t  save_TreeAllocFactor = -1;\n\t\t}\n\n\t      if(all_task0.Time != All.Time)\n\t\t{\n\t\t  printf(\"The restart file on task=%d is not consistent with the one on task=0\\n\", ThisTask);\n\t\t  fflush(stdout);\n\t\t  endrun(16);\n\t\t}\n\n\t      allocate_memory();\n\t    }\n\n\t  in(&NumPart, modus);\n\n\t  if(NumPart > All.MaxPart)\n\t    {\n\t      printf\n\t\t(\"it seems you have reduced(!) 'PartAllocFactor' below the value of %g needed to load the restart file.\\n\",\n\t\t NumPart / (((double) All.TotNumPart) / NTask));\n\t      printf(\"fatal error\\n\");\n\t      endrun(22);\n\t    }\n\n\t  /* Particle data  */\n\t  byten(&P[0], NumPart * sizeof(struct particle_data), modus);\n\n\t  in(&N_gas, modus);\n\n\t  if(N_gas > 0)\n\t    {\n\t      if(N_gas > All.MaxPartSph)\n\t\t{\n\t\t  printf\n\t\t    (\"SPH: it seems you have reduced(!) 'PartAllocFactor' below the value of %g needed to load the restart file.\\n\",\n\t\t     N_gas / (((double) All.TotN_gas) / NTask));\n\t\t  printf(\"fatal error\\n\");\n\t\t  endrun(222);\n\t\t}\n\t      /* Sph-Particle data  */\n\t      byten(&SphP[0], N_gas * sizeof(struct sph_particle_data), modus);\n\t    }\n\n\t  /* write state of random number generator */\n\t  byten(gsl_rng_state(random_generator), gsl_rng_size(random_generator), modus);\n\n\n\t  /* now store relevant data for tree */\n\n\t  if(modus)\t\t/* read */\n\t    {\n\t      ngb_treeallocate(MAX_NGB);\n\n\t      force_treeallocate(All.TreeAllocFactor * All.MaxPart, All.MaxPart);\n\t    }\n\n\n\t  in(&Numnodestree, modus);\n\n\t  if(Numnodestree > MaxNodes)\n\t    {\n\t      printf\n\t\t(\"Tree storage: it seems you have reduced(!) 'PartAllocFactor' below the value needed to load the restart file (task=%d). \"\n\t\t \"Numnodestree=%d  MaxNodes=%d\\n\", ThisTask, Numnodestree, MaxNodes);\n\t      endrun(221);\n\t    }\n\n\t  byten(Nodes_base, Numnodestree * sizeof(struct NODE), modus);\n\t  byten(Extnodes_base, Numnodestree * sizeof(struct extNODE), modus);\n\n\t  byten(Father, NumPart * sizeof(int), modus);\n\n\t  byten(Nextnode, NumPart * sizeof(int), modus);\n\t  byten(Nextnode + All.MaxPart, MAXTOPNODES * sizeof(int), modus);\n\n\t  byten(DomainStartList, NTask * sizeof(int), modus);\n\t  byten(DomainEndList, NTask * sizeof(int), modus);\n\t  byten(DomainTask, MAXTOPNODES * sizeof(int), modus);\n\t  byten(DomainNodeIndex, MAXTOPNODES * sizeof(int), modus);\n\t  byten(DomainTreeNodeLen, MAXTOPNODES * sizeof(FLOAT), modus);\n\t  byten(DomainHmax, MAXTOPNODES * sizeof(FLOAT), modus);\n\t  byten(DomainMoment, MAXTOPNODES * sizeof(struct DomainNODE), modus);\n\n\t  byten(DomainCorner, 3 * sizeof(double), modus);\n\t  byten(DomainCenter, 3 * sizeof(double), modus);\n\t  byten(&DomainLen, sizeof(double), modus);\n\t  byten(&DomainFac, sizeof(double), modus);\n\t  byten(&DomainMyStart, sizeof(int), modus);\n\t  byten(&DomainMyLast, sizeof(int), modus);\n\n\t  if(modus)\t\t/* read */\n\t    if(All.PartAllocFactor != save_PartAllocFactor || All.TreeAllocFactor != save_TreeAllocFactor)\n\t      {\n\t\tfor(i = 0; i < NumPart; i++)\n\t\t  Father[i] += (All.MaxPart - old_MaxPart);\n\n\t\tfor(i = 0; i < NumPart; i++)\n\t\t  if(Nextnode[i] >= old_MaxPart)\n\t\t    {\n\t\t      if(Nextnode[i] >= old_MaxPart + old_MaxNodes)\n\t\t\tNextnode[i] += (All.MaxPart - old_MaxPart) + (MaxNodes - old_MaxPart);\n\t\t      else\n\t\t\tNextnode[i] += (All.MaxPart - old_MaxPart);\n\t\t    }\n\n\t\tfor(i = 0; i < Numnodestree; i++)\n\t\t  {\n\t\t    if(Nodes_base[i].u.d.sibling >= old_MaxPart)\n\t\t      {\n\t\t\tif(Nodes_base[i].u.d.sibling >= old_MaxPart + old_MaxNodes)\n\t\t\t  Nodes_base[i].u.d.sibling +=\n\t\t\t    (All.MaxPart - old_MaxPart) + (MaxNodes - old_MaxNodes);\n\t\t\telse\n\t\t\t  Nodes_base[i].u.d.sibling += (All.MaxPart - old_MaxPart);\n\t\t      }\n\n\t\t    if(Nodes_base[i].u.d.father >= old_MaxPart)\n\t\t      {\n\t\t\tif(Nodes_base[i].u.d.father >= old_MaxPart + old_MaxNodes)\n\t\t\t  Nodes_base[i].u.d.father += (All.MaxPart - old_MaxPart) + (MaxNodes - old_MaxNodes);\n\t\t\telse\n\t\t\t  Nodes_base[i].u.d.father += (All.MaxPart - old_MaxPart);\n\t\t      }\n\n\t\t    if(Nodes_base[i].u.d.nextnode >= old_MaxPart)\n\t\t      {\n\t\t\tif(Nodes_base[i].u.d.nextnode >= old_MaxPart + old_MaxNodes)\n\t\t\t  Nodes_base[i].u.d.nextnode +=\n\t\t\t    (All.MaxPart - old_MaxPart) + (MaxNodes - old_MaxNodes);\n\t\t\telse\n\t\t\t  Nodes_base[i].u.d.nextnode += (All.MaxPart - old_MaxPart);\n\t\t      }\n\t\t  }\n\n\t\tfor(i = 0; i < MAXTOPNODES; i++)\n\t\t  if(Nextnode[i + All.MaxPart] >= old_MaxPart)\n\t\t    {\n\t\t      if(Nextnode[i + All.MaxPart] >= old_MaxPart + old_MaxNodes)\n\t\t\tNextnode[i + All.MaxPart] += (All.MaxPart - old_MaxPart) + (MaxNodes - old_MaxNodes);\n\t\t      else\n\t\t\tNextnode[i + All.MaxPart] += (All.MaxPart - old_MaxPart);\n\t\t    }\n\n\t\tfor(i = 0; i < MAXTOPNODES; i++)\n\t\t  if(DomainNodeIndex[i] >= old_MaxPart)\n\t\t    {\n\t\t      if(DomainNodeIndex[i] >= old_MaxPart + old_MaxNodes)\n\t\t\tDomainNodeIndex[i] += (All.MaxPart - old_MaxPart) + (MaxNodes - old_MaxNodes);\n\t\t      else\n\t\t\tDomainNodeIndex[i] += (All.MaxPart - old_MaxPart);\n\t\t    }\n\t      }\n\n\t  fclose(fd);\n\t}\n      else\t\t\t/* wait inside the group */\n\t{\n#ifndef NOMPI\n\t  if(modus > 0 && groupTask == 0)\t/* read */\n\t    {\n\t      MPI_Bcast(&all_task0, sizeof(struct global_data_all_processes), MPI_BYTE, 0, GADGET_WORLD);\n\t    }\n#endif\n\t}\n\r\n#ifndef NOMPI\n\t      MPI_Barrier(GADGET_WORLD);\r\n#endif\n    }\n}\n\n\n\n/*! reads/writes n bytes in restart routine\n */\nvoid byten(void *x, size_t n, int modus)\n{\n  if(modus)\n    my_fread(x, n, 1, fd);\n  else\n    my_fwrite(x, n, 1, fd);\n}\n\n\n/*! reads/writes one `int' variable in restart routine\n */\nvoid in(int *x, int modus)\n{\n  if(modus)\n    my_fread(x, 1, sizeof(int), fd);\n  else\n    my_fwrite(x, 1, sizeof(int), fd);\n}\n", "meta": {"hexsha": "8f10a7fa26cce58ece69e04a63c630b2f83cd473", "size": 8558, "ext": "c", "lang": "C", "max_stars_repo_path": "src/amuse/community/gadget2/src/restart.c", "max_stars_repo_name": "rknop/amuse", "max_stars_repo_head_hexsha": "85d5bdcc29cfc87dc69d91c264101fafd6658aec", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 131.0, "max_stars_repo_stars_event_min_datetime": "2015-06-04T09:06:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T12:11:29.000Z", "max_issues_repo_path": "src/amuse/community/gadget2/src/restart.c", "max_issues_repo_name": "rknop/amuse", "max_issues_repo_head_hexsha": "85d5bdcc29cfc87dc69d91c264101fafd6658aec", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 690.0, "max_issues_repo_issues_event_min_datetime": "2015-10-17T12:18:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:15:58.000Z", "max_forks_repo_path": "src/amuse/community/gadget2/src/restart.c", "max_forks_repo_name": "rieder/amuse", "max_forks_repo_head_hexsha": "3ac3b6b8f922643657279ddee5c8ab3fc0440d5e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 102.0, "max_forks_repo_forks_event_min_datetime": "2015-01-22T10:00:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T13:29:43.000Z", "avg_line_length": 27.2547770701, "max_line_length": 125, "alphanum_fraction": 0.6374152839, "num_tokens": 2550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.03308597493257518, "lm_q1q2_score": 0.01641374800608007}}
{"text": "/**\n * @file cblas.h\n * @brief Header file to handle Intel MKL, OpenBLAS, or Netlib includes.\n * \n * `npypacke` can be linked with a reference CBLAS implementation, OpenBLAS, or\n * Intel MKL, but Intel MKL uses a different header file, `mkl.h`, while\n * OpenBLAS uses the CBLAS header `cblas.h`. This file includes the correct\n * header file given an appropriate preprocessor macro is defined, and defines\n * some types appropriately so that the user can simply write in terms of the\n * Intel MKL interface, whether or not Intel MKL is actually linked.\n */\n\n#ifndef NPY_LPK_CBLAS_H\n#define NPY_LPK_CBLAS_H\n// if linking with Netlib CBLAS\n#if defined(CBLAS_INCLUDE)\n#include <cblas.h>\n// define MKL_INT used in extension modules as in mkl.h\n#ifndef MKL_INT\n#define MKL_INT int\n#endif /* MKL_INT */\n// else if linking with OpenBLAS CBLAS\n#elif defined(OPENBLAS_INCLUDE)\n#include <cblas.h>\n// OpenBLAS has blasint typedef, so define MKL_INT using blasint\n#ifndef MKL_INT\n#define MKL_INT blasint\n#endif /* MKL_INT */\n// else if linking to Intel MKL\n#elif defined(MKL_INCLUDE)\n#include <mkl.h>\n// else error, no LAPACKE includes specified\n#else\n// silence error squiggles in VS Code (__INTELLISENSE__ always defined)\n#ifndef __INTELLISENSE__\n#error \"no CBLAS includes specified. try -D(CBLAS|OPENBLAS|MKL)_INCLUDE\"\n#endif /* __INTELLISENSE__ */\n#endif\n\n// silence error squiggles in VS Code. use mkl.h since it also define MKL types\n#ifdef __INTELLISENSE__\n#include <mkl.h>\n#endif /* __INTELLISENSE__ */\n\n#endif /* NPY_LPK_CBLAS_H */", "meta": {"hexsha": "0ad607e338e58b73488d483638879be63f57b80c", "size": 1528, "ext": "h", "lang": "C", "max_stars_repo_path": "npypacke/include/npypacke/cblas.h", "max_stars_repo_name": "phetdam/npy_openblas_demo", "max_stars_repo_head_hexsha": "ff5f9932b19f82162bc0d9d46b341d42805f942b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-16T00:59:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-16T00:59:11.000Z", "max_issues_repo_path": "npypacke/include/npypacke/cblas.h", "max_issues_repo_name": "phetdam/numpy-lapacke-demo", "max_issues_repo_head_hexsha": "ff5f9932b19f82162bc0d9d46b341d42805f942b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "npypacke/include/npypacke/cblas.h", "max_forks_repo_name": "phetdam/numpy-lapacke-demo", "max_forks_repo_head_hexsha": "ff5f9932b19f82162bc0d9d46b341d42805f942b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9555555556, "max_line_length": 79, "alphanum_fraction": 0.7585078534, "num_tokens": 437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215925474903, "lm_q2_score": 0.03846619367175169, "lm_q1q2_score": 0.016398968945381374}}
{"text": "/* multilarge.c\n * \n * Copyright (C) 2015 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_multifit.h>\n#include <gsl/gsl_multilarge.h>\n#include <gsl/gsl_blas.h>\n\ngsl_multilarge_linear_workspace *\ngsl_multilarge_linear_alloc(const gsl_multilarge_linear_type *T,\n                            const size_t p)\n{\n  gsl_multilarge_linear_workspace *w;\n\n  w = calloc(1, sizeof(gsl_multilarge_linear_workspace));\n  if (w == NULL)\n    {\n      GSL_ERROR_NULL(\"failed to allocate space for workspace\",\n                     GSL_ENOMEM);\n    }\n\n  w->type = T;\n\n  w->state = w->type->alloc(p);\n  if (w->state == NULL)\n    {\n      gsl_multilarge_linear_free(w);\n      GSL_ERROR_NULL(\"failed to allocate space for multilarge state\",\n                     GSL_ENOMEM);\n    }\n\n  w->p = p;\n\n  /* initialize newly allocated state */\n  gsl_multilarge_linear_reset(w);\n\n  return w;\n}\n\nvoid\ngsl_multilarge_linear_free(gsl_multilarge_linear_workspace *w)\n{\n  RETURN_IF_NULL(w);\n\n  if (w->state)\n    w->type->free(w->state);\n\n  free(w);\n}\n\nconst char *\ngsl_multilarge_linear_name(const gsl_multilarge_linear_workspace *w)\n{\n  return w->type->name;\n}\n\nint\ngsl_multilarge_linear_reset(gsl_multilarge_linear_workspace *w)\n{\n  int status = w->type->reset(w->state);\n  return status;\n}\n\nint\ngsl_multilarge_linear_accumulate(gsl_matrix * X, gsl_vector * y,\n                                 gsl_multilarge_linear_workspace * w)\n{\n  int status = w->type->accumulate(X, y, w->state);\n  return status;\n}\n\nint\ngsl_multilarge_linear_solve(const double lambda, gsl_vector * c,\n                            double * rnorm, double * snorm,\n                            gsl_multilarge_linear_workspace * w)\n{\n  int status = w->type->solve(lambda, c, rnorm, snorm, w->state);\n  return status;\n}\n\nint\ngsl_multilarge_linear_rcond(double *rcond, gsl_multilarge_linear_workspace * w)\n{\n  int status = w->type->rcond(rcond, w->state);\n  return status;\n}\n\nint\ngsl_multilarge_linear_lcurve(gsl_vector * reg_param, gsl_vector * rho,\n                             gsl_vector * eta,\n                             gsl_multilarge_linear_workspace * w)\n{\n  const size_t len = reg_param->size;\n\n  if (len != rho->size)\n    {\n      GSL_ERROR (\"reg_param and rho have different sizes\", GSL_EBADLEN);\n    }\n  else if (len != eta->size)\n    {\n      GSL_ERROR (\"reg_param and eta have different sizes\", GSL_EBADLEN);\n    }\n  else\n    {\n      int status = w->type->lcurve(reg_param, rho, eta, w->state);\n      return status;\n    }\n}\n\n/*\ngsl_multilarge_linear_wstdform1()\n  Using regularization matrix\nL = diag(l_1,l_2,...,l_p), transform to Tikhonov standard form:\n\nX~ = sqrt(W) X L^{-1}\ny~ = sqrt(W) y\nc~ = L c\n\nInputs: L    - Tikhonov matrix as a vector of diagonal elements p-by-1;\n               or NULL for L = I\n        X    - least squares matrix n-by-p\n        y    - right hand side vector n-by-1\n        w    - weight vector n-by-1; or NULL for W = I\n        Xs   - least squares matrix in standard form X~ n-by-p\n        ys   - right hand side vector in standard form y~ n-by-1\n        work - workspace\n\nReturn: success/error\n\nNotes:\n1) It is allowed for X = Xs and y = ys\n*/\n\nint\ngsl_multilarge_linear_wstdform1 (const gsl_vector * L,\n                                 const gsl_matrix * X,\n                                 const gsl_vector * w,\n                                 const gsl_vector * y,\n                                 gsl_matrix * Xs,\n                                 gsl_vector * ys,\n                                 gsl_multilarge_linear_workspace * work)\n{\n  const size_t n = X->size1;\n  const size_t p = X->size2;\n\n  (void) work;\n\n  if (L != NULL && p != L->size)\n    {\n      GSL_ERROR(\"L vector does not match X\", GSL_EBADLEN);\n    }\n  else if (n != y->size)\n    {\n      GSL_ERROR(\"y vector does not match X\", GSL_EBADLEN);\n    }\n  else if (w != NULL && n != w->size)\n    {\n      GSL_ERROR(\"weight vector does not match X\", GSL_EBADLEN);\n    }\n  else if (n != Xs->size1 || p != Xs->size2)\n    {\n      GSL_ERROR(\"Xs matrix dimensions do not match X\", GSL_EBADLEN);\n    }\n  else if (n != ys->size)\n    {\n      GSL_ERROR(\"ys vector must be length n\", GSL_EBADLEN);\n    }\n  else\n    {\n      int status = GSL_SUCCESS;\n\n      /* compute Xs = sqrt(W) X and ys = sqrt(W) y */\n      status = gsl_multifit_linear_applyW(X, w, y, Xs, ys);\n      if (status)\n        return status;\n\n      if (L != NULL)\n        {\n          size_t j;\n\n          /* construct X~ = sqrt(W) X * L^{-1} matrix */\n          for (j = 0; j < p; ++j)\n            {\n              gsl_vector_view Xj = gsl_matrix_column(Xs, j);\n              double lj = gsl_vector_get(L, j);\n\n              if (lj == 0.0)\n                {\n                  GSL_ERROR(\"L matrix is singular\", GSL_EDOM);\n                }\n\n              gsl_vector_scale(&Xj.vector, 1.0 / lj);\n            }\n        }\n\n      return status;\n    }\n}\n\nint\ngsl_multilarge_linear_stdform1 (const gsl_vector * L,\n                                const gsl_matrix * X,\n                                const gsl_vector * y,\n                                gsl_matrix * Xs,\n                                gsl_vector * ys,\n                                gsl_multilarge_linear_workspace * work)\n{\n  int status;\n\n  status = gsl_multilarge_linear_wstdform1(L, X, NULL, y, Xs, ys, work);\n\n  return status;\n}\n\nint\ngsl_multilarge_linear_L_decomp (gsl_matrix * L, gsl_vector * tau)\n{\n  const size_t m = L->size1;\n  const size_t p = L->size2;\n\n  if (m < p)\n    {\n      GSL_ERROR(\"m < p not yet supported\", GSL_EBADLEN);\n    }\n  else\n    {\n      int status;\n\n      status = gsl_multifit_linear_L_decomp(L, tau);\n\n      return status;\n    }\n}\n\nint\ngsl_multilarge_linear_wstdform2 (const gsl_matrix * LQR,\n                                 const gsl_vector * Ltau,\n                                 const gsl_matrix * X,\n                                 const gsl_vector * w,\n                                 const gsl_vector * y,\n                                 gsl_matrix * Xs,\n                                 gsl_vector * ys,\n                                 gsl_multilarge_linear_workspace * work)\n{\n  const size_t m = LQR->size1;\n  const size_t n = X->size1;\n  const size_t p = X->size2;\n\n  (void) Ltau;\n\n  if (p != work->p)\n    {\n      GSL_ERROR(\"X has wrong number of columns\", GSL_EBADLEN);\n    }\n  else if (p != LQR->size2)\n    {\n      GSL_ERROR(\"LQR and X matrices have different numbers of columns\", GSL_EBADLEN);\n    }\n  else if (n != y->size)\n    {\n      GSL_ERROR(\"y vector does not match X\", GSL_EBADLEN);\n    }\n  else if (w != NULL && n != w->size)\n    {\n      GSL_ERROR(\"weights vector must be length n\", GSL_EBADLEN);\n    }\n  else if (m < p)\n    {\n      GSL_ERROR(\"m < p not yet supported\", GSL_EBADLEN);\n    }\n  else if (n != Xs->size1 || p != Xs->size2)\n    {\n      GSL_ERROR(\"Xs matrix must be n-by-p\", GSL_EBADLEN);\n    }\n  else if (n != ys->size)\n    {\n      GSL_ERROR(\"ys vector must have length n\", GSL_EBADLEN);\n    }\n  else\n    {\n      int status;\n      size_t i;\n      gsl_matrix_const_view R = gsl_matrix_const_submatrix(LQR, 0, 0, p, p);\n\n      /* compute Xs = sqrt(W) X and ys = sqrt(W) y */\n      status = gsl_multifit_linear_applyW(X, w, y, Xs, ys);\n      if (status)\n        return status;\n\n      /* compute X~ = X R^{-1} using QR decomposition of L */\n      for (i = 0; i < n; ++i)\n        {\n          gsl_vector_view v = gsl_matrix_row(Xs, i);\n\n          /* solve: R^T y = X_i */\n          gsl_blas_dtrsv(CblasUpper, CblasTrans, CblasNonUnit, &R.matrix, &v.vector);\n        }\n\n      return GSL_SUCCESS;\n    }\n}\n\nint\ngsl_multilarge_linear_stdform2 (const gsl_matrix * LQR,\n                                const gsl_vector * Ltau,\n                                const gsl_matrix * X,\n                                const gsl_vector * y,\n                                gsl_matrix * Xs,\n                                gsl_vector * ys,\n                                gsl_multilarge_linear_workspace * work)\n{\n  int status;\n\n  status = gsl_multilarge_linear_wstdform2(LQR, Ltau, X, NULL, y, Xs, ys, work);\n\n  return status;\n}\n\n/*\ngsl_multilarge_linear_genform1()\n  Backtransform regularized solution vector using matrix\nL = diag(L)\n*/\n\nint\ngsl_multilarge_linear_genform1 (const gsl_vector * L,\n                                const gsl_vector * cs,\n                                gsl_vector * c,\n                                gsl_multilarge_linear_workspace * work)\n{\n  if (L->size != work->p)\n    {\n      GSL_ERROR(\"L vector does not match workspace\", GSL_EBADLEN);\n    }\n  else if (L->size != cs->size)\n    {\n      GSL_ERROR(\"cs vector does not match L\", GSL_EBADLEN);\n    }\n  else if (L->size != c->size)\n    {\n      GSL_ERROR(\"c vector does not match L\", GSL_EBADLEN);\n    }\n  else\n    {\n      /* compute true solution vector c = L^{-1} c~ */\n      gsl_vector_memcpy(c, cs);\n      gsl_vector_div(c, L);\n\n      return GSL_SUCCESS;\n    }\n}\n\nint\ngsl_multilarge_linear_genform2 (const gsl_matrix * LQR,\n                                const gsl_vector * Ltau,\n                                const gsl_vector * cs,\n                                gsl_vector * c,\n                                gsl_multilarge_linear_workspace * work)\n{\n  const size_t m = LQR->size1;\n  const size_t p = LQR->size2;\n\n  (void) Ltau;\n  (void) work;\n\n  if (p != c->size)\n    {\n      GSL_ERROR(\"c vector does not match LQR\", GSL_EBADLEN);\n    }\n  else if (m < p)\n    {\n      GSL_ERROR(\"m < p not yet supported\", GSL_EBADLEN);\n    }\n  else if (p != cs->size)\n    {\n      GSL_ERROR(\"cs vector size does not match c\", GSL_EBADLEN);\n    }\n  else\n    {\n      int s;\n      gsl_matrix_const_view R = gsl_matrix_const_submatrix(LQR, 0, 0, p, p); /* R factor of L */\n\n      /* solve R c = cs for true solution c, using QR decomposition of L */\n      gsl_vector_memcpy(c, cs);\n      s = gsl_blas_dtrsv(CblasUpper, CblasNoTrans, CblasNonUnit, &R.matrix, c);\n\n      return s;\n    }\n}\n\nconst gsl_matrix *\ngsl_multilarge_linear_matrix_ptr (const gsl_multilarge_linear_workspace * work)\n{\n  return work->type->matrix_ptr(work->state);\n}\n\nconst gsl_vector *\ngsl_multilarge_linear_rhs_ptr (const gsl_multilarge_linear_workspace * work)\n{\n  return work->type->rhs_ptr(work->state);\n}\n", "meta": {"hexsha": "eabe6220bb3c12a4c1a58d9b77f07e0ad0e13a1a", "size": 10994, "ext": "c", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/multilarge/multilarge.c", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/multilarge/multilarge.c", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/multilarge/multilarge.c", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 26.0521327014, "max_line_length": 96, "alphanum_fraction": 0.5688557395, "num_tokens": 2902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.034100428534459284, "lm_q1q2_score": 0.016384528823104125}}
{"text": "/*\n * C version of Diffusive Nested Sampling (DNest4) by Brendon J. Brewer\n *\n * Yan-Rong Li, liyanrong@mail.ihep.ac.cn\n * Jun 30, 2016\n *\n */\n#ifndef _DNESTVARS_H\n#define _DNESTVARS_H\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <stdbool.h>\n#include <gsl/gsl_rng.h>\n\n#define DNEST_MAJOR_VERSION 0  // Dec 2, 2018\n#define DNEST_MINOR_VERSION 1\n#define DNEST_PATCH_VERSION 0\n\n#define STR_MAX_LENGTH (100)\n#define BUF_MAX_LENGTH (200)\n#define LEVEL_NUM_MAX (2000)\n\n/* output files */\nextern FILE *fsample, *fsample_info;\n\n/* random number generator */\nextern const gsl_rng_type * dnest_gsl_T;\nextern gsl_rng * dnest_gsl_r;\n\ntypedef struct \n{\n  double value;\n  double tiebreaker;\n}LikelihoodType;\n\ntypedef struct\n{\n  LikelihoodType log_likelihood;\n  double log_X;\n  unsigned long long int visits, exceeds;\n  unsigned long long int accepts, tries;\n}Level;\n\n// struct for options\ntypedef struct\n{\n  unsigned int num_particles;\n  unsigned int new_level_interval;\n  unsigned int save_interval;\n  unsigned int thread_steps;\n  unsigned int max_num_levels;\n  double lambda, beta;\n  unsigned int max_num_saves;\n  double max_ptol;\n\n  char sample_file[STR_MAX_LENGTH];\n  char sample_info_file[STR_MAX_LENGTH];\n  char levels_file[STR_MAX_LENGTH];\n  char sampler_state_file[STR_MAX_LENGTH];\n  char posterior_sample_file[STR_MAX_LENGTH];\n  char posterior_sample_info_file[STR_MAX_LENGTH];\n  char limits_file[STR_MAX_LENGTH];\n}Options;\nextern Options options;\nextern char options_file[STR_MAX_LENGTH];\n\ntypedef struct\n{\n  void (*from_prior)(void *model, const void *arg);\n  double (*log_likelihoods_cal)(const void *model, const void *arg);\n  double (*log_likelihoods_cal_initial)(const void *model, const void *arg);\n  double (*log_likelihoods_cal_restart)(const void *model, const void *arg);\n  double (*perturb)(void *model, const void *arg);\n  void (*print_particle)(FILE *fp, const void *model, const void *arg);\n  void (*read_particle)(FILE *fp, void *model);\n  void (*restart_action)(int iflag);\n  void (*accept_action)();\n  void (*kill_action)(int i, int i_copy);\n}DNestFptrSet;\n\nextern void *particles;\nextern int dnest_size_of_modeltype;\nextern int particle_offset_size, particle_offset_double;\n\n// sampler\nextern bool save_to_disk;\nextern unsigned int num_threads;\nextern double compression;\nextern unsigned int regularisation;\n\nextern void *particles;\nextern LikelihoodType *log_likelihoods;\nextern unsigned int *level_assignments;\n\n// number account of unaccepted times\nextern unsigned int *account_unaccepts;\n\nextern int size_levels;  \nextern Level *levels;\nextern unsigned int count_saves, num_saves, num_saves_restart;\nextern unsigned long long int count_mcmc_steps;\nextern LikelihoodType *above;\nextern unsigned int size_above;\n\nextern int dnest_flag_restart, dnest_flag_postprc, dnest_flag_sample_info, dnest_flag_limits;\nextern double dnest_post_temp;\nextern char file_restart[STR_MAX_LENGTH], file_save_restart[STR_MAX_LENGTH];\n\nextern double post_logz;\nextern int dnest_num_params;\nextern char dnest_sample_postfix[STR_MAX_LENGTH], dnest_sample_tag[STR_MAX_LENGTH], dnest_sample_dir[STR_MAX_LENGTH];\n\n//the limits of parameters for each level;\nextern double *limits, *copies_of_limits;\n\nextern int dnest_which_particle_update; // which particle to be updated\nextern int dnest_which_level_update;    // which level to be updated;\nextern int *dnest_perturb_accept;\nextern int dnest_root;\n\nextern void *dnest_arg;\n//***********************************************\n/*                  functions                  */\nextern double mod(double y, double x);\nextern void dnest_wrap(double *x, double min, double max);\nextern void wrap_limit(double *x, double min, double max);\nextern int mod_int(int y, int x);\nextern int dnest_cmp(const void *pa, const void *pb);\n\nextern void options_load(int max_num_saves, double ptol);\nextern void setup(int argc, char** argv, DNestFptrSet *fptrset, int num_params, char *sample_dir, int max_num_saves, double ptol);\nextern void finalise();\n\nextern double dnest(int argc, char **argv, DNestFptrSet *fptrset,  int num_params, char *sample_dir, \n             int max_num_saves, double pdff, const void *arg);\nextern void dnest_run();\nextern void dnest_mcmc_run();\nextern void update_particle(unsigned int which);\nextern void update_level_assignment(unsigned int which);\nextern double log_push(unsigned int which_level);\nextern bool enough_levels(Level *l, int size_l);\nextern void do_bookkeeping();\nextern void save_levels();\nextern void save_particle();\nextern void save_limits();\nextern void kill_lagging_particles();\nextern void renormalise_visits();\nextern void recalculate_log_X();\nextern double dnest_randh();\nextern double dnest_rand();\nextern double dnest_randn();\nextern int dnest_rand_int(int size);\nextern void dnest_postprocess(double temperature, int max_num_saves, double ptol);\nextern void postprocess(double temperature);\nextern void initialize_output_file();\nextern void close_output_file();\nextern void dnest_save_restart();\nextern void dnest_restart();\nextern void dnest_restart_action(int iflag);\nextern void dnest_accept_action();\nextern void dnest_kill_action(int i, int i_copy);\nextern void dnest_print_particle(FILE *fp, const void *model, const void *arg);\nextern void dnest_read_particle(FILE *fp, void *model);\nextern int dnest_get_size_levels();\nextern int dnest_get_which_level_update();\nextern int dnest_get_which_particle_update();\nextern void dnest_get_posterior_sample_file(char *fname);\nextern int dnest_check_version(char *verion_str);\nextern unsigned int dnest_get_which_num_saves();\nextern unsigned int dnest_get_count_saves();\nextern unsigned long long int dnest_get_count_mcmc_steps();\nextern void dnest_check_fptrset(DNestFptrSet *fptrset);\nextern DNestFptrSet * dnest_malloc_fptrset();\nextern void dnest_free_fptrset(DNestFptrSet * fptrset);\n/*=====================================================*/\n// users responsible for following functions\nextern void (*print_particle)(FILE *fp, const void *model, const void *arg);\nextern void (*read_particle)(FILE *fp, void *model);\nextern void (*from_prior)(void *model, const void *arg);\nextern double (*log_likelihoods_cal)(const void *model, const void *arg);\nextern double (*log_likelihoods_cal_initial)(const void *model, const void *arg);\nextern double (*log_likelihoods_cal_restart)(const void *model, const void *arg);\nextern double (*perturb)(void *model, const void *arg);\nextern void (*restart_action)(int iflag);\nextern void (*accept_action)();\nextern void (*kill_action)(int i, int i_copy);\n/*=====================================================*/\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n", "meta": {"hexsha": "f675b4655e99065b291564b22edcab91c2717ed2", "size": 6696, "ext": "h", "lang": "C", "max_stars_repo_path": "src/pycali/cdnest/dnestvars.h", "max_stars_repo_name": "LiyrAstroph/PyCALI", "max_stars_repo_head_hexsha": "e232531b5c6f7817b6e3bd34dbb31463807ae2b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-01-14T01:32:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T09:23:59.000Z", "max_issues_repo_path": "src/pycali/cdnest/dnestvars.h", "max_issues_repo_name": "LiyrAstroph/pyCALI", "max_issues_repo_head_hexsha": "e232531b5c6f7817b6e3bd34dbb31463807ae2b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pycali/cdnest/dnestvars.h", "max_forks_repo_name": "LiyrAstroph/pyCALI", "max_forks_repo_head_hexsha": "e232531b5c6f7817b6e3bd34dbb31463807ae2b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-02-05T02:01:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-06T11:26:06.000Z", "avg_line_length": 33.3134328358, "max_line_length": 130, "alphanum_fraction": 0.7638888889, "num_tokens": 1607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.036769466207539105, "lm_q1q2_score": 0.01638188318309818}}
{"text": "#pragma once\n\n#include <algorithm>\n#include <array>\n#include <cstdint>\n#include <initializer_list>\n#include <iterator>\n#include <sstream>\n#include <string>\n\n#include <absl/types/span.h>\n#include <gsl/gsl>\n\n#include \"chainerx/axes.h\"\n#include \"chainerx/constant.h\"\n#include \"chainerx/dims.h\"\n#include \"chainerx/error.h\"\n\nnamespace chainerx {\n\nclass Strides;\n\nclass Shape : public Dims {\n    using BaseVector = Dims;\n\npublic:\n    using const_iterator = BaseVector::const_iterator;\n    using const_reverse_iterator = BaseVector::const_reverse_iterator;\n    // TODO(niboshi): Declare other types required for this class to be a container.\n\n    Shape() = default;\n\n    ~Shape() = default;\n\n    // by iterators\n    template <typename InputIt>\n    Shape(InputIt first, InputIt last) {\n        if (std::distance(first, last) > kMaxNdim) {\n            throw DimensionError{\"too many dimensions: \", std::distance(first, last)};\n        }\n        insert(begin(), first, last);\n    }\n\n    // by span\n    explicit Shape(absl::Span<const int64_t> dims) : Shape{dims.begin(), dims.end()} {}\n\n    // by initializer list\n    Shape(std::initializer_list<int64_t> dims) : Shape{dims.begin(), dims.end()} {}\n\n    // copy\n    Shape(const Shape&) = default;\n    Shape& operator=(const Shape&) = default;\n\n    // move\n    Shape(Shape&&) = default;\n    Shape& operator=(Shape&&) = default;\n\n    int64_t GetTotalSize() const;\n\n    std::string ToString() const;\n\n    int8_t ndim() const noexcept { return gsl::narrow_cast<int8_t>(size()); }\n\n    const int64_t& operator[](int8_t index) const {\n        if (!(0 <= index && static_cast<size_t>(index) < size())) {\n            throw IndexError{\"Shape index \", index, \" out of bounds for shape with \", size(), \" size.\"};\n        }\n        return this->Dims::operator[](index);\n    }\n\n    int64_t& operator[](int8_t index) {\n        if (!(0 <= index && static_cast<size_t>(index) < size())) {\n            throw IndexError{\"Shape index \", index, \" out of bounds for shape with \", size(), \" size.\"};\n        }\n        return this->Dims::operator[](index);\n    }\n\n    // span\n    absl::Span<const int64_t> span() const { return {*this}; }\n};\n\nnamespace internal {\n\nbool IsContiguous(const Shape& shape, const Strides& strides, int64_t item_size);\n\n// Returns true if a reduction can take place under the given conditions, only considering the number of dimensions.\n// Otherwise, returns false.\n//\n// TODO(hvy): Check the dimension lengths too and reconsider the interface. E.g. return void and assert inside the function if only used for\n// assertions.\nbool IsValidReductionShape(const Shape& in_shape, const Axes& axes, const Shape& out_shape, bool allow_keepdims);\n\nint64_t CountItemsAlongAxes(const Shape& shape, const Axes& axes);\n\nShape BroadcastShapes(const Shape& shape0, const Shape& shape1);\n\n// Returns a shape where axes are reduced.\nShape ReduceShape(const Shape& shape, const Axes& axes, bool keepdims);\n\n// Returns a shape with additional axes, with length 1.\nShape ExpandShape(const Shape& shape, const Axes& axes);\n\nShape TransposeShape(const Shape& shape, const Axes& axes);\n\n}  // namespace internal\n\nstd::ostream& operator<<(std::ostream& os, const Shape& shape);\n\nvoid CheckEqual(const Shape& lhs, const Shape& rhs);\n\n}  // namespace chainerx\n", "meta": {"hexsha": "683b25cf52af9a9bd8d100ebed6d34357a5390ac", "size": 3279, "ext": "h", "lang": "C", "max_stars_repo_path": "chainerx_cc/chainerx/shape.h", "max_stars_repo_name": "zaltoprofen/chainer", "max_stars_repo_head_hexsha": "3b03f9afc80fd67f65d5e0395ef199e9506b6ee1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-08-12T21:48:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-27T18:04:20.000Z", "max_issues_repo_path": "chainerx_cc/chainerx/shape.h", "max_issues_repo_name": "zaltoprofen/chainer", "max_issues_repo_head_hexsha": "3b03f9afc80fd67f65d5e0395ef199e9506b6ee1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chainerx_cc/chainerx/shape.h", "max_forks_repo_name": "zaltoprofen/chainer", "max_forks_repo_head_hexsha": "3b03f9afc80fd67f65d5e0395ef199e9506b6ee1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2767857143, "max_line_length": 140, "alphanum_fraction": 0.6739859713, "num_tokens": 793, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2974699426047947, "lm_q2_score": 0.05500528945529114, "lm_q1q2_score": 0.016362420297225573}}
{"text": "/////////////////////////////////////////////////////////////////////\n// = NMatrix\n//\n// A linear algebra library for scientific computation in Ruby.\n// NMatrix is part of SciRuby.\n//\n// NMatrix was originally inspired by and derived from NArray, by\n// Masahiro Tanaka: http://narray.rubyforge.org\n//\n// == Copyright Information\n//\n// SciRuby is Copyright (c) 2010 - 2012, Ruby Science Foundation\n// NMatrix is Copyright (c) 2012, Ruby Science Foundation\n//\n// Please see LICENSE.txt for additional copyright notices.\n//\n// == Contributing\n//\n// By contributing source code to SciRuby, you agree to be bound by\n// our Contributor Agreement:\n//\n// * https://github.com/SciRuby/sciruby/wiki/Contributor-Agreement\n//\n// == cblas.c\n//\n// Functions in this file allow us to call CBLAS functions using\n// arrays of function pointers, by ensuring that each has the same\n// signature.\n\n#ifndef CBLAS_C\n# define CBLAS_C\n\n#include <cblas.h>\n#include \"nmatrix.h\"\n\n//extern const enum CBLAS_ORDER;\n//extern const enum CBLAS_TRANSPOSE;\n\n\ninline void cblas_r32gemm_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, DENSE_PARAM p) {\n  if (Order == CblasColMajor) r32gemm(TransA, TransB, p.M, p.N, p.K, p.alpha.r[0], p.A, p.lda, p.B, p.ldb, p.beta.r[0], p.C, p.ldc);\n  else                        r32gemm(TransB, TransA, p.N, p.M, p.K, p.alpha.r[0], p.B, p.ldb, p.A, p.lda, p.beta.r[0], p.C, p.ldc);\n}\n\ninline void cblas_r32gemv_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, DENSE_PARAM p) {\n  r32gemv(TransA, p.M, p.N, p.alpha.r[0], p.A, p.lda, p.B, p.ldb, p.beta.r[0], p.C, p.ldc);\n}\n\ninline void cblas_r64gemm_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, DENSE_PARAM p) {\n  if (Order == CblasColMajor) r64gemm(TransA, TransB, p.M, p.N, p.K, p.alpha.ra[0], p.A, p.lda, p.B, p.ldb, p.beta.ra[0], p.C, p.ldc);\n  else                        r64gemm(TransB, TransA, p.N, p.M, p.K, p.alpha.ra[0], p.B, p.ldb, p.A, p.lda, p.beta.ra[0], p.C, p.ldc);\n}\n\ninline void cblas_r64gemv_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, DENSE_PARAM p) {\n  r64gemv(TransA, p.M, p.N, p.alpha.ra[0], p.A, p.lda, p.B, p.ldb, p.beta.ra[0], p.C, p.ldc);\n}\n\ninline void cblas_r128gemm_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, DENSE_PARAM p) {\n  if (Order == CblasColMajor) r128gemm(TransA, TransB, p.M, p.N, p.K, p.alpha.rat, p.A, p.lda, p.B, p.ldb, p.beta.rat, p.C, p.ldc);\n  else                        r128gemm(TransB, TransA, p.N, p.M, p.K, p.alpha.rat, p.B, p.ldb, p.A, p.lda, p.beta.rat, p.C, p.ldc);\n}\n\ninline void cblas_r128gemv_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, DENSE_PARAM p) {\n  r128gemv(TransA, p.M, p.N, p.alpha.rat, p.A, p.lda, p.B, p.ldb, p.beta.rat, p.C, p.ldc);\n}\n\ninline void cblas_bgemv_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, DENSE_PARAM p) {\n  bgemv(TransA, p.M, p.N, p.alpha.b[0], p.A, p.lda, p.B, p.ldb, p.beta.b[0], p.C, p.ldc);\n}\n\ninline void cblas_bgemm_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, DENSE_PARAM p) {\n  if (Order == CblasColMajor) bgemm(TransA, TransB, p.M, p.N, p.K, p.alpha.b[0], p.A, p.lda, p.B, p.ldb, p.beta.b[0], p.C, p.ldc);\n  else                        bgemm(TransB, TransA, p.N, p.M, p.K, p.alpha.b[0], p.B, p.ldb, p.A, p.lda, p.beta.b[0], p.C, p.ldc);\n}\n\ninline void cblas_i8gemv_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, DENSE_PARAM p) {\n  i8gemv(TransA, p.M, p.N, p.alpha.i[0], p.A, p.lda, p.B, p.ldb, p.beta.i[0], p.C, p.ldc);\n}\n\ninline void cblas_i8gemm_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, DENSE_PARAM p) {\n  if (Order == CblasColMajor) i8gemm(TransA, TransB, p.M, p.N, p.K, p.alpha.i[0], p.A, p.lda, p.B, p.ldb, p.beta.i[0], p.C, p.ldc);\n  else                        i8gemm(TransB, TransA, p.N, p.M, p.K, p.alpha.i[0], p.B, p.ldb, p.A, p.lda, p.beta.i[0], p.C, p.ldc);\n}\n\ninline void cblas_i16gemv_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, DENSE_PARAM p) {\n  i16gemv(TransA, p.M, p.N, p.alpha.i[0], p.A, p.lda, p.B, p.ldb, p.beta.i[0], p.C, p.ldc);\n}\n\ninline void cblas_i16gemm_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, DENSE_PARAM p) {\n  if (Order == CblasColMajor) i16gemm(TransA, TransB, p.M, p.N, p.K, p.alpha.i[0], p.A, p.lda, p.B, p.ldb, p.beta.i[0], p.C, p.ldc);\n  else                        i16gemm(TransB, TransA, p.N, p.M, p.K, p.alpha.i[0], p.B, p.ldb, p.A, p.lda, p.beta.i[0], p.C, p.ldc);\n}\n\ninline void cblas_i32gemv_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, DENSE_PARAM p) {\n  i32gemv(TransA, p.M, p.N, p.alpha.i[0], p.A, p.lda, p.B, p.ldb, p.beta.i[0], p.C, p.ldc);\n}\n\ninline void cblas_i32gemm_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, DENSE_PARAM p) {\n  if (Order == CblasColMajor) i32gemm(TransA, TransB, p.M, p.N, p.K, p.alpha.i[0], p.A, p.lda, p.B, p.ldb, p.beta.i[0], p.C, p.ldc);\n  else                        i32gemm(TransB, TransA, p.N, p.M, p.K, p.alpha.i[0], p.B, p.ldb, p.A, p.lda, p.beta.i[0], p.C, p.ldc);\n}\n\ninline void cblas_i64gemv_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, DENSE_PARAM p) {\n  i64gemv(TransA, p.M, p.N, p.alpha.i[0], p.A, p.lda, p.B, p.ldb, p.beta.i[0], p.C, p.ldc);\n}\n\ninline void cblas_i64gemm_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, DENSE_PARAM p) {\n  if (Order == CblasColMajor) i64gemm(TransA, TransB, p.M, p.N, p.K, p.alpha.i[0], p.A, p.lda, p.B, p.ldb, p.beta.i[0], p.C, p.ldc);\n  else                        i64gemm(TransB, TransA, p.N, p.M, p.K, p.alpha.i[0], p.B, p.ldb, p.A, p.lda, p.beta.i[0], p.C, p.ldc);\n}\n\ninline void cblas_vgemm_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, DENSE_PARAM p) {\n  if (Order == CblasColMajor) vgemm(TransA, TransB, p.M, p.N, p.K, p.alpha.v[0], p.A, p.lda, p.B, p.ldb, p.beta.v[0], p.C, p.ldc);\n  else                        vgemm(TransB, TransA, p.N, p.M, p.K, p.alpha.v[0], p.B, p.ldb, p.A, p.lda, p.beta.v[0], p.C, p.ldc);\n}\n\ninline void cblas_sgemv_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, DENSE_PARAM p) {\n  cblas_sgemv(Order, TransA, p.M, p.N, p.alpha.d[0], p.A, p.lda, p.B, p.ldb, p.beta.d[0], p.C, p.ldc);\n}\n\ninline void cblas_sgemm_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, DENSE_PARAM p) {\n  cblas_sgemm(Order, TransA, TransB, p.M, p.N, p.K, p.alpha.d[0], p.A, p.lda, p.B, p.ldb, p.beta.d[0], p.C, p.ldc);\n}\n\ninline void cblas_dgemv_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, DENSE_PARAM p) {\n  cblas_dgemv(Order, TransA, p.M, p.N, p.alpha.d[0], p.A, p.lda, p.B, p.ldb, p.beta.d[0], p.C, p.ldc);\n}\n\ninline void cblas_dgemm_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, DENSE_PARAM p) {\n  cblas_dgemm(Order, TransA, TransB, p.M, p.N, p.K, p.alpha.d[0], p.A, p.lda, p.B, p.ldb, p.beta.d[0], p.C, p.ldc);\n}\n\ninline void cblas_cgemv_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, DENSE_PARAM p) {\n  cblas_cgemv(Order, TransA, p.M, p.N, &(p.alpha.c), p.A, p.lda, p.B, p.ldb, &(p.beta.c), p.C, p.ldc);\n}\n\ninline void cblas_cgemm_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, DENSE_PARAM p) {\n  cblas_cgemm(Order, TransA, TransB, p.M, p.N, p.K, &(p.alpha.c), p.A, p.lda, p.B, p.ldb, &(p.beta.c), p.C, p.ldc);\n}\n\ninline void cblas_zgemv_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, DENSE_PARAM p) {\n  cblas_zgemv(Order, TransA, p.M, p.N, &(p.alpha.z), p.A, p.lda, p.B, p.ldb, &(p.beta.z), p.C, p.ldc);\n}\n\ninline void cblas_zgemm_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, DENSE_PARAM p) {\n  cblas_zgemm(Order, TransA, TransB, p.M, p.N, p.K, &(p.alpha.z), p.A, p.lda, p.B, p.ldb, &(p.beta.z), p.C, p.ldc);\n}\n\n\n#endif", "meta": {"hexsha": "8f540ee319feeaa021d95c99e838085dce9cc30c", "size": 8261, "ext": "c", "lang": "C", "max_stars_repo_path": "ext/nmatrix/cblas.c", "max_stars_repo_name": "kod3r/nmatrix", "max_stars_repo_head_hexsha": "53da083c08d44f820ad3925e42055b8c0f10c35a", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-04-19T23:05:38.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-19T23:05:38.000Z", "max_issues_repo_path": "ext/nmatrix/cblas.c", "max_issues_repo_name": "kod3r/nmatrix", "max_issues_repo_head_hexsha": "53da083c08d44f820ad3925e42055b8c0f10c35a", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ext/nmatrix/cblas.c", "max_forks_repo_name": "kod3r/nmatrix", "max_forks_repo_head_hexsha": "53da083c08d44f820ad3925e42055b8c0f10c35a", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.0733333333, "max_line_length": 144, "alphanum_fraction": 0.6659000121, "num_tokens": 3074, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38861804086755836, "lm_q2_score": 0.04208773182056191, "lm_q1q2_score": 0.016356051884665965}}
{"text": "// Copyright (c) 2005 - 2010 Marc de Kamps\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n//\n//    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n//    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation \n//      and/or other materials provided with the distribution.\n//    * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software \n//      without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED \n// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY \n// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \n// USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING \n// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n//      If you use this software in work leading to a scientific publication, you should cite\n//      the 'currently valid reference', which can be found at http://miind.sourceforge.net\n#ifndef _CODE_LIBS_NUMTOOLSLIB_NODE_GSLOBJECTS_INCLUDE_GUARD\n#define _CODE_LIBS_NUMTOOLSLIB_NODE_GSLOBJECTS_INCLUDE_GUARD\n\n#include <boost/shared_ptr.hpp>\n#include <gsl/gsl_odeiv.h>\n#include <gsl/gsl_errno.h>\n#include \"Precision.h\"\n\nusing boost::shared_ptr;\n\n\nnamespace NumtoolsLib {\n  typedef unsigned int Number;\n\n\ttypedef int (*Function)   (double t, const double y[], double dydt[], void * params);\n\ttypedef int (*Derivative) (double t, const double y[], double * dfdy, double dfdt[], void * params);\t\n\n\t//! auxilliary struct to clean up some of the code of AbstractDVIntegrator\n\tstruct GSLObjects{\n\n\t\tconst gsl_odeiv_step_type*\t\t_p_step_algorithm; //!< pointer to function, so no ownership issues\n\t\tgsl_odeiv_step*\t\t\t\t\t_p_step;\n\t\tgsl_odeiv_control*\t\t\t\t_p_controller;\n\t\tgsl_odeiv_evolve*\t\t\t\t_p_evolver; \n\t\tgsl_odeiv_system\t\t\t\t_system;\n\n\t\tGSLObjects\n\t\t(\n\t\t\tconst gsl_odeiv_step_type*,\t//<! choice for solver type\n\t\t\tNumber,\t\t\t\t\t\t//<! state size\n\t\t\tconst Precision&\t\t\t//<! absolute and relative precision conform GSL documentation\n\t\t);\n\n\t\t~GSLObjects();\n\n\t};\n}\n\n#endif // include guard\n\n", "meta": {"hexsha": "c3ce5ea720f182da6e718a73fea846e036bb0c6f", "size": 2832, "ext": "h", "lang": "C", "max_stars_repo_path": "libs/NumtoolsLib/GSLObjects.h", "max_stars_repo_name": "dekamps/miind", "max_stars_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2015-09-15T17:28:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T20:26:47.000Z", "max_issues_repo_path": "libs/NumtoolsLib/GSLObjects.h", "max_issues_repo_name": "dekamps/miind", "max_issues_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41.0, "max_issues_repo_issues_event_min_datetime": "2015-08-25T07:50:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T16:20:37.000Z", "max_forks_repo_path": "libs/NumtoolsLib/GSLObjects.h", "max_forks_repo_name": "dekamps/miind", "max_forks_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-14T20:52:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T12:18:18.000Z", "avg_line_length": 47.2, "max_line_length": 163, "alphanum_fraction": 0.7588276836, "num_tokens": 648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37022540649291935, "lm_q2_score": 0.044018650646766244, "lm_q1q2_score": 0.01629682282896884}}
{"text": "/* Initialize topic and POV assignments uniformly at random, and set\n   various hyper-parameters needed for inference. Assignments must be\n   initialized before doing inference for the first time. */\n\n#include <assert.h>\n#include <gsl/gsl_rng.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\n#include \"index.h\"\n#include \"parse_mmaps.h\"\n#include \"sample.h\"\n\nint main(int argc, char **argv) {\n  if (argc != 11) {\n    printf(\"Usage: %s mmap_directory num_topics pov_per_topic num_threads psi_alpha \"\n\t   \"psi_beta gamma_alpha gamma_beta beta alpha\\n\",\n           argv[0]);\n    exit(1);\n  }\n  int num_threads = atoi(argv[4]);\n  char *endptr;\n  create_indexes(argv[1],\n\t\t strtod(argv[5], &endptr),\n\t\t strtod(argv[6], &endptr),\n\t\t strtod(argv[7], &endptr),\n\t\t strtod(argv[8], &endptr),\n\t\t strtod(argv[9], &endptr),\n\t\t strtod(argv[10], &endptr),\n\t\t atoi(argv[2]),\n\t\t atoi(argv[3]),\n\t\t num_threads);\n  struct mmap_info mmap_info = open_mmaps_mmap(argv[1]);\n\n  // If revisions are numbered from zero, make sure the first\n  // revision gets assigned a null topic/POV\n  struct revision_assignment* first_assignment\n    = get_revision_assignment(&mmap_info, 0);\n  first_assignment->topic = -1;\n  first_assignment->pov = -1;\n\n  struct sample_threads sample_threads;\n  initialize_threads(&sample_threads, num_threads, &mmap_info);\n  resample_null(&sample_threads);\n  resample_uniform(&sample_threads);\n\n  destroy_threads(&sample_threads);\n  close_mmaps(mmap_info);\n}\n", "meta": {"hexsha": "afbe147ebf1d0f72378278986f5d6f5c9de164fc", "size": 1465, "ext": "c", "lang": "C", "max_stars_repo_path": "src/initialize.c", "max_stars_repo_name": "allenlavoie/topic-pov", "max_stars_repo_head_hexsha": "c727087d0ac2d440d4e70fbea0c3342c3c734073", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T17:04:56.000Z", "max_stars_repo_stars_event_max_datetime": "2015-01-05T17:04:56.000Z", "max_issues_repo_path": "src/initialize.c", "max_issues_repo_name": "allenlavoie/topic-pov", "max_issues_repo_head_hexsha": "c727087d0ac2d440d4e70fbea0c3342c3c734073", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/initialize.c", "max_forks_repo_name": "allenlavoie/topic-pov", "max_forks_repo_head_hexsha": "c727087d0ac2d440d4e70fbea0c3342c3c734073", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7254901961, "max_line_length": 85, "alphanum_fraction": 0.7085324232, "num_tokens": 387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.03258974535327366, "lm_q1q2_score": 0.01629487267663683}}
{"text": "#ifndef OPERATOR_H\n#define OPERATOR_H\n\n\n#include <chrono>\n#include <iostream>\n#include <utility>\n#include <vector>\n#include <memory>\n#include <string>\n#include <sstream>\n\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_spmatrix.h>\n#include <gsl/gsl_splinalg.h>\n\n#include \"constants.h\"\n\nusing std::array;\nusing std::pair;\nusing std::shared_ptr;\nusing std::tuple;\nusing std::vector;\nusing std::string;\n\n// Smart pointer to matrix\nusing mat_operator = shared_ptr<gsl_spmatrix>;\n\n// Shorthand for template types\nusing ComputeStatus = vector<pair<size_t, std::string>>;\nusing ListCmu = const vector<mat_operator>;\nusing VecPair = pair<gsl_vector *, gsl_vector *>;\nusing VecTriplet = tuple<gsl_vector *, gsl_vector *, gsl_vector *>;\n\n// Generate operator L\ngsl_matrix *computeL();\n\n// Generate operator C\nvoid computeC();\n\ngsl_spmatrix *computeSingleC(size_t mu);\n\nvoid findValidCs(vector<bool>& toStore);\n\nvoid setFilenames(string& raw, string& compressed, size_t mu); \n\ngsl_spmatrix *loadMat(size_t mu);\nvoid storeMat(const gsl_spmatrix *C_mu, size_t mu);\n\n#endif // OPERATOR_H\n", "meta": {"hexsha": "12a326efd8869ecf044b681864ef3436d27f11db", "size": 1072, "ext": "h", "lang": "C", "max_stars_repo_path": "inc/operators.h", "max_stars_repo_name": "ichi-rika/glottal-inverse", "max_stars_repo_head_hexsha": "c922ed540278e3c8eec528c2cf66b89e6d310575", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-01-24T17:01:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-26T16:22:08.000Z", "max_issues_repo_path": "inc/operators.h", "max_issues_repo_name": "ichi-rika/glottal-inverse", "max_issues_repo_head_hexsha": "c922ed540278e3c8eec528c2cf66b89e6d310575", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inc/operators.h", "max_forks_repo_name": "ichi-rika/glottal-inverse", "max_forks_repo_head_hexsha": "c922ed540278e3c8eec528c2cf66b89e6d310575", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-04-27T00:23:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-27T14:41:25.000Z", "avg_line_length": 21.0196078431, "max_line_length": 67, "alphanum_fraction": 0.7509328358, "num_tokens": 279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.03258974476602535, "lm_q1q2_score": 0.016294872383012676}}
{"text": "// Server settings and option parsing\n#ifndef _SETTINGS_H\n#define _SETTINGS_H\n\n#include <gsl/gsl_rng.h>\n#include <stdbool.h>\n\n// Settings the server has\ntypedef struct _settings {\n\tint verbose;\n\tint threads;\n\tint tcpport;\n\tdouble dist_arg1; // normal distribution mean\n\tdouble dist_arg2; // normal distribution stddev\n\tbool use_dist;\n\tgsl_rng *r;\n} settings;\n\nvoid usage(void);\nsettings settings_init(void);\nbool settings_parse(int argc, char **argv, settings *s);\n\n#endif\n\n", "meta": {"hexsha": "cc36a72f0791afceaa3d06f49cbdbf2c742e8f92", "size": 474, "ext": "h", "lang": "C", "max_stars_repo_path": "src/settings.h", "max_stars_repo_name": "dterei/synthetic-memcached", "max_stars_repo_head_hexsha": "2db588dd7f3417a912e8ac1547cd2b51c8fd7915", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/settings.h", "max_issues_repo_name": "dterei/synthetic-memcached", "max_issues_repo_head_hexsha": "2db588dd7f3417a912e8ac1547cd2b51c8fd7915", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/settings.h", "max_forks_repo_name": "dterei/synthetic-memcached", "max_forks_repo_head_hexsha": "2db588dd7f3417a912e8ac1547cd2b51c8fd7915", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.96, "max_line_length": 56, "alphanum_fraction": 0.7552742616, "num_tokens": 110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.38121956625614994, "lm_q2_score": 0.04272219724178408, "lm_q1q2_score": 0.016286537502022615}}
{"text": "#include <mpi.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n\n#include <fcntl.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <sys/file.h>\n#include <unistd.h>\n#include <gsl/gsl_rng.h>\n\n#include \"allvars.h\"\n#include \"proto.h\"\n#include \"domain.h\"\n\nstatic FILE *fd;\n\nstatic void in(int *x, int modus);\nstatic void byten(void *x, int n, int modus);\n\n\n/* This function reads or writes the restart files.\n * Each processor writes its own restart file, with the\n * I/O being done in parallel. To avoid congestion of the disks\n * you can tell the program to restrict the number of files\n * that are simultaneously written to NumFilesWrittenInParallel.\n *\n * If modus>0  the restart()-routine reads, \n * if modus==0 it writes a restart file. \n */\nvoid restart(int modus)\n{\n  char buf[200], buf_bak[200], buf_mv[500];\n  double save_PartAllocFactor;\n  int i, nprocgroup, masterTask, groupTask, old_MaxPart, old_MaxNodes;\n  struct global_data_all_processes all_task0;\n\n\n#if defined(SFR) || defined(BLACK_HOLES)\n#ifdef NO_TREEDATA_IN_RESTART\n  if(modus == 0)\n    {\n      rearrange_particle_sequence();\n      All.NumForcesSinceLastDomainDecomp = (long long) (1 + All.TreeDomainUpdateFrequency * All.TotNumPart);\t/* ensures that new tree will be constructed */\n    }\n#endif\n#endif\n\n  if(ThisTask == 0 && modus == 0)\n    {\n      sprintf(buf, \"%s/restartfiles\", All.OutputDir);\n      mkdir(buf, 02755);\n    }\n  MPI_Barrier(MPI_COMM_WORLD);\n\n  sprintf(buf, \"%s/restartfiles/%s.%d\", All.OutputDir, All.RestartFile, ThisTask);\n  sprintf(buf_bak, \"%s/restartfiles/%s.%d.bak\", All.OutputDir, All.RestartFile, ThisTask);\n  sprintf(buf_mv, \"mv %s %s\", buf, buf_bak);\n\n  if((NTask < All.NumFilesWrittenInParallel))\n    {\n      printf\n\t(\"Fatal error.\\nNumber of processors must be a smaller or equal than `NumFilesWrittenInParallel'.\\n\");\n      endrun(2131);\n    }\n\n  nprocgroup = NTask / All.NumFilesWrittenInParallel;\n\n  if((NTask % All.NumFilesWrittenInParallel))\n    {\n      nprocgroup++;\n    }\n\n  masterTask = (ThisTask / nprocgroup) * nprocgroup;\n\n  for(groupTask = 0; groupTask < nprocgroup; groupTask++)\n    {\n      if(ThisTask == (masterTask + groupTask))\n\t{\n\t  if(!modus)\n\t    {\n#ifndef NOCALLSOFSYSTEM\n\t      int ret;\n\n\t      ret = system(buf_mv);\t/* move old restart files to .bak files */\n#endif\n\t    }\n\t}\n    }\n\n  for(groupTask = 0; groupTask < nprocgroup; groupTask++)\n    {\n      if(ThisTask == (masterTask + groupTask))\t/* ok, it's this processor's turn */\n\t{\n\t  if(modus)\n\t    {\n\t      if(!(fd = fopen(buf, \"r\")))\n\t\t{\n\t\t  printf(\"Restart file '%s' not found.\\n\", buf);\n\t\t  endrun(7870);\n\t\t}\n\t    }\n\t  else\n\t    {\n\t      if(!(fd = fopen(buf, \"w\")))\n\t\t{\n\t\t  printf(\"Restart file '%s' cannot be opened.\\n\", buf);\n\t\t  endrun(7878);\n\t\t}\n\t    }\n\n\n\t  save_PartAllocFactor = All.PartAllocFactor;\n\n\t  /* common data  */\n\t  byten(&All, sizeof(struct global_data_all_processes), modus);\n\n\t  if(ThisTask == 0 && modus > 0)\n\t    all_task0 = All;\n\n\t  if(modus > 0 && groupTask == 0)\t/* read */\n\t    {\n\t      MPI_Bcast(&all_task0, sizeof(struct global_data_all_processes), MPI_BYTE, 0, MPI_COMM_WORLD);\n\t    }\n\n\t  old_MaxPart = All.MaxPart;\n\t  old_MaxNodes = (int) (All.TreeAllocFactor * All.MaxPart) + NTopnodes;\n\n\t  if(modus)\t\t/* read */\n\t    {\n\t      if(All.PartAllocFactor != save_PartAllocFactor)\n\t\t{\n\t\t  All.PartAllocFactor = save_PartAllocFactor;\n\t\t  All.MaxPart = (int) (All.PartAllocFactor * (All.TotNumPart / NTask));\n\t\t  All.MaxPartSph = (int) (All.PartAllocFactor * (All.TotN_gas / NTask));\n#ifdef INHOMOG_GASDISTR_HINT\n\t\t  All.MaxPartSph = All.MaxPart;\n#endif\n\t\t  save_PartAllocFactor = -1;\n\t\t}\n\n\t      if(all_task0.Time != All.Time)\n\t\t{\n\t\t  printf(\"The restart file on task=%d is not consistent with the one on task=0\\n\", ThisTask);\n\t\t  fflush(stdout);\n\t\t  endrun(16);\n\t\t}\n\n\t      allocate_memory();\n\t    }\n\n\t  in(&NumPart, modus);\n\n\t  if(NumPart > All.MaxPart)\n\t    {\n\t      printf\n\t\t(\"it seems you have reduced(!) 'PartAllocFactor' below the value of %g needed to load the restart file.\\n\",\n\t\t NumPart / (((double) All.TotNumPart) / NTask));\n\t      printf(\"fatal error\\n\");\n\t      endrun(22);\n\t    }\n\n\t  /* Particle data  */\n\t  byten(&P[0], NumPart * sizeof(struct particle_data), modus);\n\n\t  in(&N_gas, modus);\n\n\t  if(N_gas > 0)\n\t    {\n\t      if(N_gas > All.MaxPartSph)\n\t\t{\n\t\t  printf\n\t\t    (\"SPH: it seems you have reduced(!) 'PartAllocFactor' below the value of %g needed to load the restart file.\\n\",\n\t\t     N_gas / (((double) All.TotN_gas) / NTask));\n\t\t  printf(\"fatal error\\n\");\n\t\t  endrun(222);\n\t\t}\n\t      /* Sph-Particle data  */\n\t      byten(&SphP[0], N_gas * sizeof(struct sph_particle_data), modus);\n\t    }\n\n\t  /* write state of random number generator */\n\t  byten(gsl_rng_state(random_generator), gsl_rng_size(random_generator), modus);\n\n\t  /* now store relevant data for tree */\n#ifdef SFR\n\t  in(&Stars_converted, modus);\n#endif\n\n#ifndef NO_TREEDATA_IN_RESTART\n\t  /* now store relevant data for tree */\n\t  int nmulti = MULTIPLEDOMAINS;\n\n\t  in(&nmulti, modus);\n\t  if(modus != 0 && nmulti != MULTIPLEDOMAINS)\n\t    {\n\t      if(ThisTask == 0)\n\t\tprintf\n\t\t  (\"Looks like you changed MULTIPLEDOMAINS from %d to %d.\\nWill discard tree stored in restart files and construct a new one.\\n\",\n\t\t   nmulti, (int) MULTIPLEDOMAINS);\n\n\t      All.NumForcesSinceLastDomainDecomp = (long long) (1 + All.TreeDomainUpdateFrequency * All.TotNumPart);\t/* ensures that new tree will be constructed */\n\t    }\n\t  else\n\t    {\n\t      in(&NTopleaves, modus);\n\t      in(&NTopnodes, modus);\n\n\t      if(modus)\t\t/* read */\n\t\t{\n\t\t  domain_allocate();\n\t\t  force_treeallocate((int) (All.TreeAllocFactor * All.MaxPart) + NTopnodes, All.MaxPart);\n\t\t}\n\n\t      in(&Numnodestree, modus);\n\n\t      if(Numnodestree > MaxNodes)\n\t\t{\n\t\t  printf\n\t\t    (\"Tree storage: it seems you have reduced(!) 'PartAllocFactor' below the value needed to load the restart file (task=%d). \"\n\t\t     \"Numnodestree=%d  MaxNodes=%d\\n\", ThisTask, Numnodestree, MaxNodes);\n\t\t  endrun(221);\n\t\t}\n\n\t      byten(Nodes_base, Numnodestree * sizeof(struct NODE), modus);\n\t      byten(Extnodes_base, Numnodestree * sizeof(struct extNODE), modus);\n\n\t      byten(Father, NumPart * sizeof(int), modus);\n\n\t      byten(Nextnode, NumPart * sizeof(int), modus);\n\t      byten(Nextnode + All.MaxPart, NTopnodes * sizeof(int), modus);\n\n\t      byten(DomainStartList, NTask * MULTIPLEDOMAINS * sizeof(int), modus);\n\t      byten(DomainEndList, NTask * MULTIPLEDOMAINS * sizeof(int), modus);\n\t      byten(DomainTask, NTopnodes * sizeof(int), modus);\n\t      byten(DomainNodeIndex, NTopleaves * sizeof(int), modus);\n\n\t      byten(DomainCorner, 3 * sizeof(double), modus);\n\t      byten(DomainCenter, 3 * sizeof(double), modus);\n\t      byten(&DomainLen, sizeof(double), modus);\n\t      byten(&DomainFac, sizeof(double), modus);\n\n\t      if(modus)\t\t/* read */\n\t\tif(All.PartAllocFactor != save_PartAllocFactor)\n\t\t  {\n\t\t    for(i = 0; i < NumPart; i++)\n\t\t      Father[i] += (All.MaxPart - old_MaxPart);\n\n\t\t    for(i = 0; i < NumPart; i++)\n\t\t      if(Nextnode[i] >= old_MaxPart)\n\t\t\t{\n\t\t\t  if(Nextnode[i] >= old_MaxPart + old_MaxNodes)\n\t\t\t    Nextnode[i] += (All.MaxPart - old_MaxPart) + (MaxNodes - old_MaxPart);\n\t\t\t  else\n\t\t\t    Nextnode[i] += (All.MaxPart - old_MaxPart);\n\t\t\t}\n\n\t\t    for(i = 0; i < Numnodestree; i++)\n\t\t      {\n\t\t\tif(Nodes_base[i].u.d.sibling >= old_MaxPart)\n\t\t\t  {\n\t\t\t    if(Nodes_base[i].u.d.sibling >= old_MaxPart + old_MaxNodes)\n\t\t\t      Nodes_base[i].u.d.sibling +=\n\t\t\t\t(All.MaxPart - old_MaxPart) + (MaxNodes - old_MaxNodes);\n\t\t\t    else\n\t\t\t      Nodes_base[i].u.d.sibling += (All.MaxPart - old_MaxPart);\n\t\t\t  }\n\n\t\t\tif(Nodes_base[i].u.d.father >= old_MaxPart)\n\t\t\t  {\n\t\t\t    if(Nodes_base[i].u.d.father >= old_MaxPart + old_MaxNodes)\n\t\t\t      Nodes_base[i].u.d.father +=\n\t\t\t\t(All.MaxPart - old_MaxPart) + (MaxNodes - old_MaxNodes);\n\t\t\t    else\n\t\t\t      Nodes_base[i].u.d.father += (All.MaxPart - old_MaxPart);\n\t\t\t  }\n\n\t\t\tif(Nodes_base[i].u.d.nextnode >= old_MaxPart)\n\t\t\t  {\n\t\t\t    if(Nodes_base[i].u.d.nextnode >= old_MaxPart + old_MaxNodes)\n\t\t\t      Nodes_base[i].u.d.nextnode +=\n\t\t\t\t(All.MaxPart - old_MaxPart) + (MaxNodes - old_MaxNodes);\n\t\t\t    else\n\t\t\t      Nodes_base[i].u.d.nextnode += (All.MaxPart - old_MaxPart);\n\t\t\t  }\n\t\t      }\n\n\t\t    for(i = 0; i < NTopnodes; i++)\n\t\t      if(Nextnode[i + All.MaxPart] >= old_MaxPart)\n\t\t\t{\n\t\t\t  if(Nextnode[i + All.MaxPart] >= old_MaxPart + old_MaxNodes)\n\t\t\t    Nextnode[i + All.MaxPart] +=\n\t\t\t      (All.MaxPart - old_MaxPart) + (MaxNodes - old_MaxNodes);\n\t\t\t  else\n\t\t\t    Nextnode[i + All.MaxPart] += (All.MaxPart - old_MaxPart);\n\t\t\t}\n\n\t\t    for(i = 0; i < NTopnodes; i++)\n\t\t      if(DomainNodeIndex[i] >= old_MaxPart)\n\t\t\t{\n\t\t\t  if(DomainNodeIndex[i] >= old_MaxPart + old_MaxNodes)\n\t\t\t    DomainNodeIndex[i] += (All.MaxPart - old_MaxPart) + (MaxNodes - old_MaxNodes);\n\t\t\t  else\n\t\t\t    DomainNodeIndex[i] += (All.MaxPart - old_MaxPart);\n\t\t\t}\n\t\t  }\n\t    }\n#endif\n\t  fclose(fd);\n\t}\n      else\t\t\t/* wait inside the group */\n\t{\n\t  if(modus > 0 && groupTask == 0)\t/* read */\n\t    {\n\t      MPI_Bcast(&all_task0, sizeof(struct global_data_all_processes), MPI_BYTE, 0, MPI_COMM_WORLD);\n\t    }\n\t}\n\n      MPI_Barrier(MPI_COMM_WORLD);\n    }\n#ifdef HEALPIX\n  //this should be readed in the parameterfile\n  All.Nside=8;\n  //\n  if(ThisTask==0) \n  printf(\" Restart calculation of Healpix %i with %i \\n\",All.Nside,NSIDE2NPIX(All.Nside));\n  // initialize the healpix array (just in case)\n  All.healpixmap=(float *) malloc(NSIDE2NPIX(All.Nside) * sizeof(float));\n  for(i=0;i<NSIDE2NPIX(All.Nside);i++)All.healpixmap[i]=0;\n  healpix_halo(All.healpixmap);\n#endif\n}\n\n\n\n/* reads/writes n bytes \n */\nvoid byten(void *x, int n, int modus)\n{\n  if(modus)\n    my_fread(x, n, 1, fd);\n  else\n    my_fwrite(x, n, 1, fd);\n}\n\n\n/* reads/writes one int \n */\nvoid in(int *x, int modus)\n{\n  if(modus)\n    my_fread(x, 1, sizeof(int), fd);\n  else\n    my_fwrite(x, 1, sizeof(int), fd);\n}\n", "meta": {"hexsha": "e0922ae597bbec67280ea5d18d564bbdfdfcb66a", "size": 9865, "ext": "c", "lang": "C", "max_stars_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/restart.c", "max_stars_repo_name": "egpbos/egp", "max_stars_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/restart.c", "max_issues_repo_name": "egpbos/egp", "max_issues_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/restart.c", "max_forks_repo_name": "egpbos/egp", "max_forks_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5558659218, "max_line_length": 157, "alphanum_fraction": 0.6282818044, "num_tokens": 2950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167300566462553, "lm_q2_score": 0.036769466999181315, "lm_q1q2_score": 0.01624008100621467}}
{"text": "/* ieee-utils/fp-darwin86.c\n * \n * Copyright (C) 2006 Erik Schnetter\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <gsl/gsl_ieee_utils.h>\n#include <gsl/gsl_errno.h>\n\n/* Here is the dirty part. Set up your 387 through the control word\n * (cw) register.\n *\n *     15-13    12  11-10  9-8     7-6     5    4    3    2    1    0\n * | reserved | IC | RC  | PC | reserved | PM | UM | OM | ZM | DM | IM\n *\n * IM: Invalid operation mask\n * DM: Denormalized operand mask\n * ZM: Zero-divide mask\n * OM: Overflow mask\n * UM: Underflow mask\n * PM: Precision (inexact result) mask\n *\n * Mask bit is 1 means no interrupt.\n *\n * PC: Precision control\n * 11 - round to extended precision\n * 10 - round to double precision\n * 00 - round to single precision\n *\n * RC: Rounding control\n * 00 - rounding to nearest\n * 01 - rounding down (toward - infinity)\n * 10 - rounding up (toward + infinity)\n * 11 - rounding toward zero\n *\n * IC: Infinity control\n * That is for 8087 and 80287 only.\n *\n * The hardware default is 0x037f which we use.\n */\n\n/* masking of interrupts */\n#define _FPU_MASK_IM  0x01\n#define _FPU_MASK_DM  0x02\n#define _FPU_MASK_ZM  0x04\n#define _FPU_MASK_OM  0x08\n#define _FPU_MASK_UM  0x10\n#define _FPU_MASK_PM  0x20\n\n/* precision control */\n#define _FPU_EXTENDED 0x300\t/* libm requires double extended precision.  */\n#define _FPU_DOUBLE   0x200\n#define _FPU_SINGLE   0x0\n\n/* rounding control */\n#define _FPU_RC_NEAREST 0x0    /* RECOMMENDED */\n#define _FPU_RC_DOWN    0x400\n#define _FPU_RC_UP      0x800\n#define _FPU_RC_ZERO    0xC00\n\n#define _FPU_RESERVED 0xF0C0  /* Reserved bits in cw */\n\n\n/* The fdlibm code requires strict IEEE double precision arithmetic,\n   and no interrupts for exceptions, rounding to nearest.  */\n\n#define _FPU_DEFAULT  0x037f\n\n/* IEEE:  same as above.  */\n#define _FPU_IEEE     0x037f\n\n/* Type of the control word.  */\ntypedef unsigned int fpu_control_t __attribute__ ((__mode__ (__HI__)));\n\n/* Macros for accessing the hardware control word.\n\n   Note that the use of these macros is no sufficient anymore with\n   recent hardware.  Some floating point operations are executed in\n   the SSE/SSE2 engines which have their own control and status register.  */\n#define _FPU_GETCW(cw) __asm__ __volatile__ (\"fnstcw %0\" : \"=m\" (*&cw))\n#define _FPU_SETCW(cw) __asm__ __volatile__ (\"fldcw %0\" : : \"m\" (*&cw))\n\n/* Default control word set at startup.  */\nextern fpu_control_t __fpu_control;\n\n\n\n#define _FPU_GETMXCSR(cw_sse) asm volatile (\"stmxcsr %0\" : \"=m\" (cw_sse))\n#define _FPU_SETMXCSR(cw_sse) asm volatile (\"ldmxcsr %0\" : : \"m\" (cw_sse))\n\n\n\nint\ngsl_ieee_set_mode (int precision, int rounding, int exception_mask)\n{\n  fpu_control_t mode, mode_sse;\n\n  _FPU_GETCW (mode) ;\n  mode &= _FPU_RESERVED ;\n\n  switch (precision)\n    {\n    case GSL_IEEE_SINGLE_PRECISION:\n      mode |= _FPU_SINGLE ;\n      break ;\n    case GSL_IEEE_DOUBLE_PRECISION:\n      mode |= _FPU_DOUBLE ;\n      break ;\n    case GSL_IEEE_EXTENDED_PRECISION:\n      mode |= _FPU_EXTENDED ;\n      break ;\n    default:\n      mode |= _FPU_EXTENDED ;\n    }\n\n  switch (rounding)\n    {\n    case GSL_IEEE_ROUND_TO_NEAREST:\n      mode |= _FPU_RC_NEAREST ;\n      break ;\n    case GSL_IEEE_ROUND_DOWN:\n      mode |= _FPU_RC_DOWN ;\n      break ;\n    case GSL_IEEE_ROUND_UP:\n      mode |= _FPU_RC_UP ;\n      break ;\n    case GSL_IEEE_ROUND_TO_ZERO:\n      mode |= _FPU_RC_ZERO ;\n      break ;\n    default:\n      mode |= _FPU_RC_NEAREST ;\n    }\n\n  if (exception_mask & GSL_IEEE_MASK_INVALID)\n    mode |= _FPU_MASK_IM ;\n\n  if (exception_mask & GSL_IEEE_MASK_DENORMALIZED)\n    mode |= _FPU_MASK_DM ;\n\n  if (exception_mask & GSL_IEEE_MASK_DIVISION_BY_ZERO)\n    mode |= _FPU_MASK_ZM ;\n\n  if (exception_mask & GSL_IEEE_MASK_OVERFLOW)\n    mode |= _FPU_MASK_OM ;\n\n  if (exception_mask & GSL_IEEE_MASK_UNDERFLOW)\n    mode |= _FPU_MASK_UM ;\n\n  if (exception_mask & GSL_IEEE_TRAP_INEXACT)\n    {\n      mode &= ~ _FPU_MASK_PM ;\n    }\n  else\n    {\n      mode |= _FPU_MASK_PM ;\n    }\n\n  _FPU_SETCW (mode) ;\n\n  _FPU_GETMXCSR (mode_sse) ;\n  mode_sse &= 0xFFFF0000 ;\n\n  if (exception_mask & GSL_IEEE_MASK_INVALID)\n    mode_sse |= _FPU_MASK_IM << 7 ;\n\n  if (exception_mask & GSL_IEEE_MASK_DENORMALIZED)\n    mode_sse |= _FPU_MASK_DM << 7 ;\n\n  if (exception_mask & GSL_IEEE_MASK_DIVISION_BY_ZERO)\n    mode_sse |= _FPU_MASK_ZM << 7 ;\n\n  if (exception_mask & GSL_IEEE_MASK_OVERFLOW)\n    mode_sse |= _FPU_MASK_OM << 7 ;\n\n  if (exception_mask & GSL_IEEE_MASK_UNDERFLOW)\n    mode_sse |= _FPU_MASK_UM << 7 ;\n\n  if (exception_mask & GSL_IEEE_TRAP_INEXACT)\n    {\n      mode_sse &= ~ _FPU_MASK_PM << 7 ;\n    }\n  else\n    {\n      mode_sse |= _FPU_MASK_PM << 7 ;\n    }\n\n  _FPU_SETMXCSR (mode_sse) ;\n\n  return GSL_SUCCESS ;\n}\n", "meta": {"hexsha": "ddd4dbec03153fad18aadb2455e505c202125c98", "size": 5373, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/ieee-utils/fp-darwin86.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/ieee-utils/fp-darwin86.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/ieee-utils/fp-darwin86.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 26.2097560976, "max_line_length": 81, "alphanum_fraction": 0.6852782431, "num_tokens": 1610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356685373537454, "lm_q2_score": 0.04023794003402037, "lm_q1q2_score": 0.01623869886032227}}
{"text": "/* ieee-utils/fp-solaris.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <math.h>\n#include <ieeefp.h>\n#include <gsl/gsl_ieee_utils.h>\n#include <gsl/gsl_errno.h>\n\nint\ngsl_ieee_set_mode (int precision, int rounding, int exception_mask)\n{\n  fp_except mode = 0 ;\n  fp_rnd    rnd  = 0 ;\n\n  switch (precision)\n    {\n    case GSL_IEEE_SINGLE_PRECISION:\n      GSL_ERROR (\"solaris only supports default precision rounding\",\n                 GSL_EUNSUP) ;\n      break ;\n    case GSL_IEEE_DOUBLE_PRECISION:\n      GSL_ERROR (\"solaris only supports default precision rounding\",\n                 GSL_EUNSUP) ;\n      break ;\n    case GSL_IEEE_EXTENDED_PRECISION:\n      GSL_ERROR (\"solaris only supports default precision rounding\",\n                 GSL_EUNSUP) ;\n      break ;\n    }\n\n  switch (rounding)\n    {\n    case GSL_IEEE_ROUND_TO_NEAREST:\n      rnd = FP_RN ;\n      fpsetround (rnd) ;\n      break ;\n    case GSL_IEEE_ROUND_DOWN:\n      rnd = FP_RM ;\n      fpsetround (rnd) ;\n      break ;\n    case GSL_IEEE_ROUND_UP:\n      rnd = FP_RP ;\n      fpsetround (rnd) ;\n      break ;\n    case GSL_IEEE_ROUND_TO_ZERO:\n      rnd = FP_RZ ;\n      fpsetround (rnd) ;\n      break ;\n    default:\n      rnd = FP_RN ;\n      fpsetround (rnd) ;\n    }\n\n  /* Turn on all the exceptions apart from 'inexact' */\n\n  mode = FP_X_INV | FP_X_DZ | FP_X_OFL | FP_X_UFL ;\n\n  if (exception_mask & GSL_IEEE_MASK_INVALID)\n    mode &= ~ FP_X_INV ;\n\n  if (exception_mask & GSL_IEEE_MASK_DENORMALIZED)\n    {\n      /* do nothing */\n    }\n  else\n    {\n      GSL_ERROR (\"solaris does not support the denormalized operand exception. \"\n                 \"Use 'mask-denormalized' to work around this.\",\n                 GSL_EUNSUP) ;\n    }\n\n  if (exception_mask & GSL_IEEE_MASK_DIVISION_BY_ZERO)\n    mode &= ~ FP_X_DZ ;\n\n  if (exception_mask & GSL_IEEE_MASK_OVERFLOW)\n    mode &= ~ FP_X_OFL ;\n\n  if (exception_mask & GSL_IEEE_MASK_UNDERFLOW)\n    mode &=  ~ FP_X_UFL ;\n\n  if (exception_mask & GSL_IEEE_TRAP_INEXACT)\n    {\n      mode |= FP_X_IMP ;\n    }\n  else\n    {\n      mode &= ~ FP_X_IMP ;\n    }\n\n  fpsetmask (mode) ;\n\n  return GSL_SUCCESS ;\n\n}\n", "meta": {"hexsha": "2c3db01e1849cf506b64fd88f78c5d39efd4cfad", "size": 2854, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/ieee-utils/fp-solaris.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/ieee-utils/fp-solaris.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/ieee-utils/fp-solaris.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 25.7117117117, "max_line_length": 81, "alphanum_fraction": 0.6471618781, "num_tokens": 769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3629692055196168, "lm_q2_score": 0.044680865661299037, "lm_q1q2_score": 0.01621777831101044}}
{"text": "/* monte/gsl_monte_plain.h\r\n * \r\n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Michael Booth\r\n * \r\n * This program is free software; you can redistribute it and/or modify\r\n * it under the terms of the GNU General Public License as published by\r\n * the Free Software Foundation; either version 3 of the License, or (at\r\n * your option) any later version.\r\n * \r\n * This program is distributed in the hope that it will be useful, but\r\n * WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n * General Public License for more details.\r\n * \r\n * You should have received a copy of the GNU General Public License\r\n * along with this program; if not, write to the Free Software\r\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r\n */\r\n\r\n/* Plain Monte-Carlo. */\r\n\r\n/* Author: MJB */\r\n\r\n#ifndef __GSL_MONTE_PLAIN_H__\r\n#define __GSL_MONTE_PLAIN_H__\r\n\r\n#if !defined( GSL_FUN )\r\n#  if !defined( GSL_DLL )\r\n#    define GSL_FUN extern\r\n#  elif defined( BUILD_GSL_DLL )\r\n#    define GSL_FUN extern __declspec(dllexport)\r\n#  else\r\n#    define GSL_FUN extern __declspec(dllimport)\r\n#  endif\r\n#endif\r\n\r\n#include <stdio.h>\r\n#include <gsl/gsl_monte.h>\r\n#include <gsl/gsl_rng.h>\r\n\r\n#undef __BEGIN_DECLS\r\n#undef __END_DECLS\r\n#ifdef __cplusplus\r\n# define __BEGIN_DECLS extern \"C\" {\r\n# define __END_DECLS }\r\n#else\r\n# define __BEGIN_DECLS /* empty */\r\n# define __END_DECLS /* empty */\r\n#endif\r\n\r\n__BEGIN_DECLS\r\n\r\ntypedef struct {\r\n  size_t dim;\r\n  double *x;\r\n} gsl_monte_plain_state;\r\n\r\nGSL_FUN int\r\ngsl_monte_plain_integrate (const gsl_monte_function * f,\r\n                           const double xl[], const double xu[],\r\n                           const size_t dim,\r\n                           const size_t calls, \r\n                           gsl_rng * r,\r\n                           gsl_monte_plain_state * state,\r\n                           double *result, double *abserr);\r\n\r\nGSL_FUN gsl_monte_plain_state* gsl_monte_plain_alloc(size_t dim);\r\n\r\nGSL_FUN int gsl_monte_plain_init(gsl_monte_plain_state* state);\r\n\r\nGSL_FUN void gsl_monte_plain_free (gsl_monte_plain_state* state);\r\n\r\n__END_DECLS\r\n\r\n#endif /* __GSL_MONTE_PLAIN_H__ */\r\n", "meta": {"hexsha": "d6203055fc77643c724d70c73a4f0549b75fc59a", "size": 2224, "ext": "h", "lang": "C", "max_stars_repo_path": "deps/include/gsl/gsl_monte_plain.h", "max_stars_repo_name": "berkus/music-cs", "max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z", "max_issues_repo_path": "deps/include/gsl/gsl_monte_plain.h", "max_issues_repo_name": "berkus/music-cs", "max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z", "max_forks_repo_path": "deps/include/gsl/gsl_monte_plain.h", "max_forks_repo_name": "berkus/music-cs", "max_forks_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 29.2631578947, "max_line_length": 82, "alphanum_fraction": 0.6708633094, "num_tokens": 543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3174262526733264, "lm_q2_score": 0.051082742554942266, "lm_q1q2_score": 0.016215003545491588}}
{"text": "// --------------------------------------------------------------------------\n//                   OpenMS -- Open-Source Mass Spectrometry\n// --------------------------------------------------------------------------\n// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,\n// ETH Zurich, and Freie Universitaet Berlin 2002-2013.\n//\n// This software is released under a three-clause BSD license:\n//  * Redistributions of source code must retain the above copyright\n//    notice, this list of conditions and the following disclaimer.\n//  * Redistributions in binary form must reproduce the above copyright\n//    notice, this list of conditions and the following disclaimer in the\n//    documentation and/or other materials provided with the distribution.\n//  * Neither the name of any author or any participating institution\n//    may be used to endorse or promote products derived from this software\n//    without specific prior written permission.\n// For a full list of authors, refer to the file AUTHORS.\n// --------------------------------------------------------------------------\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING\n// INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// --------------------------------------------------------------------------\n// $Maintainer: $\n// $Authors: Hendrik Weisser $\n// --------------------------------------------------------------------------\n\n#ifndef OPENMS_ANALYSIS_MAPMATCHING_TRANSFORMATIONMODEL_H\n#define OPENMS_ANALYSIS_MAPMATCHING_TRANSFORMATIONMODEL_H\n\n#include <OpenMS/DATASTRUCTURES/Param.h>\n\n#include <gsl/gsl_bspline.h>\n#include <gsl/gsl_interp.h>\n\nnamespace OpenMS\n{\n  /**\n       @brief Base class for transformation models\n\n       Implements the identity (no transformation). Parameters and data are ignored.\n\n       @ingroup MapAlignment\n  */\n  class OPENMS_DLLAPI TransformationModel\n  {\npublic:\n    /// Coordinate pair\n    typedef std::pair<DoubleReal, DoubleReal> DataPoint;\n    /// Vector of coordinate pairs\n    typedef std::vector<DataPoint> DataPoints;\n\n    /// Constructor\n    TransformationModel() {}\n\n    /// Alternative constructor (derived classes should implement this one!)\n    TransformationModel(const TransformationModel::DataPoints &,\n                        const Param &) :\n      params_() {}\n\n    /// Destructor\n    virtual ~TransformationModel() {}\n\n    /// Evaluates the model at the given value\n    virtual DoubleReal evaluate(const DoubleReal value) const\n    {\n      return value;\n    }\n\n    /// Gets the (actual) parameters\n    void getParameters(Param & params) const\n    {\n      params = params_;\n    }\n\n    /// Gets the default parameters\n    static void getDefaultParameters(Param & params)\n    {\n      params.clear();\n    }\n\nprotected:\n    /// Parameters\n    Param params_;\n  };\n\n\n  /**\n       @brief Linear model for transformations\n\n       The model can be inferred from data or specified using explicit parameters. If data is given, a least squares fit is used to find the model parameters (slope and intercept). Depending on parameter @p symmetric_regression, a normal regression (@e y on @e x) or symmetric regression (@f$ y - x @f$ on @f$ y + x @f$) is performed.\n\n       Without data, the model can be specified by giving the parameters @p slope and @p intercept explicitly.\n\n       @ingroup MapAlignment\n  */\n  class OPENMS_DLLAPI TransformationModelLinear :\n    public TransformationModel\n  {\npublic:\n    /**\n        @brief Constructor\n\n        @exception IllegalArgument is thrown if neither data points nor explicit parameters (slope/intercept) are given.\n    */\n    TransformationModelLinear(const DataPoints & data, const Param & params);\n\n    /// Destructor\n    ~TransformationModelLinear();\n\n    /// Evaluates the model at the given value\n    virtual DoubleReal evaluate(const DoubleReal value) const;\n\n    using TransformationModel::getParameters;\n\n    /// Gets the \"real\" parameters\n    void getParameters(DoubleReal & slope, DoubleReal & intercept) const;\n\n    /// Gets the default parameters\n    static void getDefaultParameters(Param & params);\n\n    /**\n         @brief Computes the inverse\n\n         @exception DivisionByZero is thrown if the slope is zero.\n    */\n    void invert();\n\nprotected:\n    /// Parameters of the linear model\n    DoubleReal slope_, intercept_;\n    /// Was the model estimated from data?\n    bool data_given_;\n    /// Use symmetric regression?\n    bool symmetric_;\n  };\n\n\n  /**\n       @brief Interpolation model for transformations\n\n       Between the data points, the interpolation uses the neighboring points. Outside the range spanned by the points, we extrapolate using a line through the first and the last point.\n\n       Different types of interpolation (controlled by the parameter @p interpolation_type) are supported: \"linear\", \"polynomial\", \"cspline\", and \"akima\". Note that the number of required data points may differ between types.\n\n       @ingroup MapAlignment\n  */\n  class OPENMS_DLLAPI TransformationModelInterpolated :\n    public TransformationModel\n  {\npublic:\n    /**\n         @brief Constructor\n\n         @exception IllegalArgument is thrown if there are not enough data points or if an unknown interpolation type is given.\n    */\n    TransformationModelInterpolated(const DataPoints & data,\n                                    const Param & params);\n\n    /// Destructor\n    ~TransformationModelInterpolated();\n\n    /// Evaluates the model at the given value\n    DoubleReal evaluate(const DoubleReal value) const;\n\n    /// Gets the default parameters\n    static void getDefaultParameters(Param & params);\n\nprotected:\n    /// Data coordinates\n    std::vector<double> x_, y_;\n    /// Number of data points\n    size_t size_;\n    /// Look-up accelerator\n    gsl_interp_accel * acc_;\n    /// Interpolation function\n    gsl_interp * interp_;\n    /// Linear model for extrapolation\n    TransformationModelLinear * lm_;\n  };\n\n\n  /**\n       @brief B-spline model for transformations\n\n       In the range of the data points, the transformation is evaluated from a cubic smoothing spline fit to the points. The number of breakpoints is given as a parameter (@p num_breakpoints). Outside of this range, linear extrapolation through the last point with the slope of the spline at that point is used.\n\n       Positioning of the breakpoints is controlled by the parameter @p break_positions. Valid choices are \"uniform\" (equidistant spacing on the data range) and \"quantiles\" (equal numbers of data points in every interval).\n\n       @ingroup MapAlignment\n  */\n  class OPENMS_DLLAPI TransformationModelBSpline :\n    public TransformationModel\n  {\npublic:\n    /**\n         @brief Constructor\n\n         @exception IllegalArgument is thrown if not enough data points are given or if the required parameter @p num_breakpoints is missing.\n    */\n    TransformationModelBSpline(const DataPoints & data, const Param & params);\n\n    /// Destructor\n    ~TransformationModelBSpline();\n\n    /// Evaluates the model at the given value\n    DoubleReal evaluate(const DoubleReal value) const;\n\n    /// Gets the default parameters\n    static void getDefaultParameters(Param & params);\n\nprotected:\n    /**\n        @brief Finds quantile values\n\n        @param x Data vector to find quantiles in\n        @param quantiles Quantiles to find (values between 0 and 1)\n        @param results Resulting quantiles (vector must be already allocated to the correct size!)\n    */\n    void getQuantiles_(const gsl_vector * x, const std::vector<double> &\n                       quantiles, gsl_vector * results);\n\n    /// Computes the B-spline fit\n    void computeFit_();\n\n    /// Computes the linear extrapolation\n    void computeLinear_(const double pos, double & slope, double & offset,\n                        double & sd_err);\n\n    /// Vectors for B-spline computation\n    gsl_vector * x_, * y_, * w_, * bsplines_, * coeffs_;\n    /// Covariance matrix\n    gsl_matrix * cov_;\n    /// B-spline workspace\n    gsl_bspline_workspace * workspace_;\n    /// Number of data points and coefficients\n    size_t size_, ncoeffs_;\n    // First/last breakpoint\n    double xmin_, xmax_;\n    /// Parameters for linear extrapolation\n    double slope_min_, slope_max_, offset_min_, offset_max_;\n    /// Fitting errors of linear extrapolation\n    double sd_err_left_, sd_err_right_;\n  };\n\n} // end of namespace OpenMS\n\n#endif // OPENMS_ANALYSIS_MAPMATCHING_TRANSFORMATIONMODEL_H\n", "meta": {"hexsha": "681cdfe66f49e678fdd470d5a7b22c8cf6c2612f", "size": 9097, "ext": "h", "lang": "C", "max_stars_repo_path": "include/OpenMS/ANALYSIS/MAPMATCHING/TransformationModel.h", "max_stars_repo_name": "open-ms/all-svn-branches", "max_stars_repo_head_hexsha": "b182ba576e0cbfbe420b8edb0dd1c42bb6c973f3", "max_stars_repo_licenses": ["Zlib", "Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-05-23T03:43:10.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-23T03:43:10.000Z", "max_issues_repo_path": "src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/TransformationModel.h", "max_issues_repo_name": "kreinert/OpenMS", "max_issues_repo_head_hexsha": "45455356482ce5ab35e32e445609b291ec78a6d6", "max_issues_repo_licenses": ["Zlib", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/TransformationModel.h", "max_forks_repo_name": "kreinert/OpenMS", "max_forks_repo_head_hexsha": "45455356482ce5ab35e32e445609b291ec78a6d6", "max_forks_repo_licenses": ["Zlib", "Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.53515625, "max_line_length": 334, "alphanum_fraction": 0.6772562383, "num_tokens": 1844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.03258974288683082, "lm_q1q2_score": 0.01616757035020056}}
{"text": "/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*\n**                                                                                  **\n** This file forms part of the Underworld geophysics modelling application.         **\n**                                                                                  **\n** For full license and copyright information, please refer to the LICENSE.md file  **\n** located at the project root, or contact the authors.                             **\n**                                                                                  **\n**~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/\n/*\nThis provides a couple of routines which allowed the time per iteration\nto be stored. This is achieved useing the KSPMonitors. The issue with using\nthese monitors is the petsc support for these is terrible. We need to be\nable to access our user monitor context, but petsc only lets you get the\ncontext from the FIRST monitor, which we cannot guarentee will be the one \ndefined to store the timing information.\n\nTo get around this we store the index into the monitor array which our \nmonitor gets inersted into. This works, but we have no 'nice' way to \nrecover the user monitor context except via the monitor_index. Thus when\nthe monitor is set, we return the value of the monitor index. This number\nis required whenever you wish to extract the timing information.\n\n\n\n*/\n#ifndef _GNU_SOURCE\n#define _GNU_SOURCE\n#endif /* _GNU_SOURCE needed for asprintf */\n#include <stdio.h>\n#include <stdlib.h>\n\n#include <petsc.h>\n#include <petscvec.h>\n#include <petscmat.h>\n#include <petscksp.h>\n\n#include <StGermain/StGermain.h>\n#include <StgDomain/StgDomain.h>\n\n#include \"common-driver-utils.h\"\n\n#include <petscversion.h>\n#if ( (PETSC_VERSION_MAJOR >= 3) && (PETSC_VERSION_MINOR >=3) )\n  #if (PETSC_VERSION_MINOR >=6)\n     #include \"petsc/private/kspimpl.h\"\n  #else\n     #include \"petsc-private/kspimpl.h\"\n  #endif\n#else\n  #include \"private/kspimpl.h\"\n#endif\n\nstruct timed_cvg_ctx {\n\tPetscInt monitor_index;\n\tPetscInt hist_len, hist_len_max;\n\tPetscLogDouble *time_log;\n\tPetscLogDouble time;\n\tPetscReal *r_log;\n};\n\n\n/* ~~~~~~~~~~~~~~~~ SolverMonitor routines ~~~~~~~~~~~~~~~~~~~~~~ */\n/*\nI shouldn't need to include the residual log, but the petsc one does strange things, when used\nwith gmres and fgmres. I know it's related to restarts but I just don't get it. This one will \nproduce the same data as that which is displayed on the screen when you used -ksp_monitor.\n*/\n\n#undef __FUNCT__  \n#define __FUNCT__ \"BSSCR_check_validity_of_timing_monitor\"\nPetscErrorCode BSSCR_check_validity_of_timing_monitor( KSP ksp, PetscInt monitor_index )\n{\n\t\n\tif( monitor_index < 0 ) {\n\t\tStg_SETERRQ1( PETSC_ERR_ARG_WRONG, \"Monitor index cannot be negative. You had %D\", monitor_index );\n\t}\n\tif( monitor_index >= ksp->numbermonitors ) {\n\t\tStg_SETERRQ2( PETSC_ERR_ARG_WRONG, \"Monitor index >= number of monitors set (%D). You had %D\", ksp->numbermonitors, monitor_index );\n\t}\n\t\n\tPetscFunctionReturn(0);\t\n}\n\n#undef __FUNCT__  \n#define __FUNCT__ \"BSSCR_KSPLogHistory\"\nPetscErrorCode BSSCR_KSPLogHistory(struct timed_cvg_ctx *ctx,PetscReal norm) \n{\n\tPetscLogDouble t, time;\n\t\n\tPetscGetTime(&t);\n\ttime = t - ctx->time;\n\tif (ctx->hist_len==0) {\n\t\t/* Get reference time and zero first result */\n\t\tPetscGetTime(&ctx->time);\n\t\ttime = 0.0;\n\t}\n\t\n\tif (ctx->r_log && ctx->time_log && ctx->hist_len_max > ctx->hist_len) {\n\t\tctx->r_log[ctx->hist_len] = norm;\n\t\tctx->time_log[ctx->hist_len] = time;\n\t\t\n\t\tctx->hist_len++;\n\t}\n\t\n\tPetscFunctionReturn(0);\n}\n\n\n#undef __FUNCT__  \n#define __FUNCT__ \"BSSCR_timed_cvg_test\"\nPetscErrorCode BSSCR_timed_cvg_test(KSP ksp, int it, PetscReal rnorm, void *mctx)\n{\n\tstruct timed_cvg_ctx *ctx = (struct timed_cvg_ctx*)(mctx);\n\t\n\tBSSCR_KSPLogHistory(ctx,rnorm);\n\t\n\tPetscFunctionReturn(0);\n}\n\n#undef __FUNCT__  \n#define __FUNCT__ \"BSSCR_KSPLogDestroyMonitor\"\nPetscErrorCode BSSCR_KSPLogDestroyMonitor(void *_ctx)\n{\n\tstruct timed_cvg_ctx *ctx = (struct timed_cvg_ctx*)_ctx;\n\t\n\tPetscFree( ctx->r_log );\n\tPetscFree( ctx->time_log );\n\tPetscFree( ctx );\n\t\n\tPetscFunctionReturn(0);\n}\n\n\n#undef __FUNCT__  \n#define __FUNCT__ \"BSSCR_KSPLogSetMonitor\"\nPetscErrorCode BSSCR_KSPLogSetMonitor(KSP ksp,PetscInt len,PetscInt *monitor_index)\n{\n\tPetscLogDouble *time_log;\n\tPetscReal *r_log;\n\tstruct timed_cvg_ctx *ctx;\n\t\n\t\n\tPetscMalloc( sizeof(PetscLogDouble)*len, &time_log );\n\tPetscMalloc( sizeof(PetscReal)*len, &r_log );\n\tPetscMalloc( sizeof(struct timed_cvg_ctx), &ctx );\n\t\n\tctx->hist_len_max  = len;\n\tctx->hist_len      = 0;\n\tctx->time_log      = time_log;\n\tctx->r_log         = r_log;\n\t\n\tctx->monitor_index = ksp->numbermonitors;\n\t*monitor_index = ksp->numbermonitors;\n\t\n\t//KSPSetConvergenceTest(ksp,timed_cvg_test,(void*)ctx );\n\tKSPMonitorSet( ksp, BSSCR_timed_cvg_test, (void*)ctx, BSSCR_KSPLogDestroyMonitor );\n\t\n\tPetscFunctionReturn(0);\n}\n\n#undef __FUNCT__  \n#define __FUNCT__ \"BSSCR_KSPLogGetTimeHistory\"\nPetscErrorCode BSSCR_KSPLogGetTimeHistory(KSP ksp,PetscInt monitor_index, PetscInt *na,PetscLogDouble **log)\n{\n\tstruct timed_cvg_ctx *ctx;\n\tPetscInt its;\n\t\n\t\n\tctx = (struct timed_cvg_ctx*)ksp->monitorcontext[ monitor_index ];\n\t\n\tKSPGetIterationNumber(ksp,&its);\n\tits = its + 1;\n\t*na = PetscMin( (PetscInt)(its), (PetscInt)(ctx->hist_len_max) );\n\t*log = ctx->time_log;\n\t\n\tPetscFunctionReturn(0);\n}\n\n#undef __FUNCT__  \n#define __FUNCT__ \"BSSCR_KSPLogGetResidualHistory\"\nPetscErrorCode BSSCR_KSPLogGetResidualHistory(KSP ksp,PetscInt monitor_index, PetscInt *na,PetscReal **rlog)\n{\n\tstruct timed_cvg_ctx *ctx;\n\tPetscInt its;\n\t\n\t\n\tctx = (struct timed_cvg_ctx*)ksp->monitorcontext[ monitor_index ];\n\tKSPGetIterationNumber(ksp,&its);\n\tits = its + 1;\n\t*na = PetscMin( (PetscInt)(its), (PetscInt)(ctx->hist_len_max) );\n\t*rlog = ctx->r_log;\n\t\n\tPetscFunctionReturn(0);\n}\n\n#undef __FUNCT__  \n#define __FUNCT__ \"BSSCR_KSPLogGetResidualTimeHistory\"\nPetscErrorCode BSSCR_KSPLogGetResidualTimeHistory(KSP ksp,PetscInt monitor_index, PetscInt *na,PetscReal **rlog,PetscLogDouble **tlog)\n{\n\tstruct timed_cvg_ctx *ctx;\n\tPetscInt its;\n\t\n\tKSPGetIterationNumber(ksp,&its);\n\tctx = (struct timed_cvg_ctx*)ksp->monitorcontext[ monitor_index ];\n\tits = its + 1;\n\t*na = PetscMin( (PetscInt)(its), (PetscInt)(ctx->hist_len_max) );\n\t*rlog = ctx->r_log;\n\t*tlog = ctx->time_log;\n\t\n\tPetscFunctionReturn(0);\n}\n\n\nKSPNormType  BS_NO_PC=  KSP_NORM_UNPRECONDITIONED;\nKSPNormType  BS_W_PC=   KSP_NORM_PRECONDITIONED;\n\n#undef __FUNCT__  \n#define __FUNCT__ \"BSSCR_KSPGetNormType\"\nPetscErrorCode BSSCR_KSPGetNormType(KSP ksp, KSPNormType *normtype) {\n\t*normtype = ksp->normtype;\n\treturn(0);\n}\n\n#undef __FUNCT__  \n#define __FUNCT__ \"BSSCR_KSPLogSolve\"\nPetscErrorCode BSSCR_KSPLogSolve(PetscViewer v,PetscInt monitor_index, KSP ksp)\n{\n\tVec b,u;\n\tPetscInt i;\n\tKSPType type;\n\tPetscReal b_nrm, *rlog;\n\tPC pc;\n\tPetscLogDouble *log;\n\tPetscInt nits;\n\tKSPNormType ntype;\n\tPCSide side;\n\tPetscTruth has_unpc_config, ksp_matches;\n\tconst char *list[]            = { \"cg\"   , \"bicg\" , \"bcgs\" , \"gmres\" , \"fgmres\", \"minres\", \"lgmres\", 0 }; \n\tconst PCSide   pc_side[]      = { PC_LEFT, PC_LEFT, PC_LEFT, PC_RIGHT, PC_RIGHT, PC_LEFT , PC_RIGHT, 0 };\n\tconst KSPNormType norm_type[] = { BS_NO_PC  , BS_NO_PC  , BS_NO_PC  , BS_W_PC    , BS_NO_PC   , BS_NO_PC   , BS_W_PC    , 0 };\n\t\n\t\n\tKSPGetRhs( ksp, &b );\n\tKSPGetSolution( ksp, &u );\n\t\n\tKSPGetType( ksp, &type );\n\tBSSCR_KSPGetNormType( ksp, &ntype );\n\tKSPGetPreconditionerSide( ksp, &side );\n\thas_unpc_config = PETSC_FALSE;\n\t\n\ti = 0;\n\twhile (list[i]) {\n\t\tPetscStrcmp( \"fgmres\", type, &ksp_matches );\t\t\n\t\tif (ksp_matches) {\n\t\t\thas_unpc_config = PETSC_TRUE;\n\t\t\tbreak;\n\t\t}\n\n\t\tPetscStrcmp( list[i],type,&ksp_matches );\n\t\tif (ksp_matches) {\n\t\t\tif( pc_side[i] == side && ntype == norm_type[i] ) {\n\t\t\t\thas_unpc_config = PETSC_TRUE;\n\t\t\t\tbreak; \n\t\t\t}\n\t\t}\n\t\ti++;\n\t}\n\t\n\tif (has_unpc_config) {\n\t\tPetscViewerASCIIPrintf( v, \"[%s] Detected options consistent with unpreconditioned norm: using side=%d, norm_type=%d \\n\", type, side, ntype );\n\t}\n\t\n\t\n\tBSSCR_KSPLogGetResidualTimeHistory(ksp,monitor_index, &nits,&rlog,&log);\n\tif (!rlog || !log) {\n\t\tStg_SETERRQ( PETSC_ERR_ORDER, \"You need to call BSSCR_KSPLogSetMonitor() before BSSCR_KSPLogGetResidualTimeHistory()\" );\n\t}\n\t\n\tif (!has_unpc_config) {\n\t\tVec pc_b;\n\t\tVecDuplicate( u, &pc_b );\n\t\tKSPGetPC( ksp, &pc );\n\t\tPCApply( pc, b, pc_b );\n\t\tVecNorm( pc_b, NORM_2, &b_nrm );\n\t\t\n\t\tStg_VecDestroy(&pc_b );\n\t\t\n\t\tPetscViewerASCIIPrintf( v, \"# it        |Qr|               |Qr0|              |f|             |Qr|/|Qr0|         log10(Qr/Qr0)       |Qr|/|Qf|          log10(Qr/Qf)           time\\n\" );\n\t}\n\telse if (has_unpc_config) {\n\t\tVecNorm( b, NORM_2, &b_nrm );\n\t\tPetscViewerASCIIPrintf( v, \"# it         |r|               |r0|               |f|              |r|/|r0|          log10(r/r0)          |r|/|f|           log10(r/f)            time\\n\" );\n\t}\n\t\n\tfor( i=0; i<nits; i++ ) {\n\t\tPetscViewerASCIIPrintf( v, \"%1.4d %14.12e %14.12e %14.12e %14.12e %14.12e %14.12e %14.12e %14.12e\\n\", \n\t\t\t\ti, rlog[i],rlog[0],b_nrm, rlog[i]/rlog[0],log10(rlog[i]/rlog[0]), rlog[i]/b_nrm,log10(rlog[i]/b_nrm), log[i] );\n\t}\n\t\n\t\n\tPetscFunctionReturn(0);\n}\n\n\n\n#undef __FUNCT__  \n#define __FUNCT__ \"BSSCR_BSSCR_KSPLogSolveSummary\"\nPetscErrorCode BSSCR_BSSCR_KSPLogSolveSummary(PetscViewer v,PetscInt monitor_index, KSP ksp)\n{\n\tKSPConvergedReason reason;\n\tchar *reas;\n\tPetscReal *rlog;\n\tPetscLogDouble *log;\n\tPetscInt nits;\n\t\n\t\n\tKSPGetConvergedReason( ksp, &reason );\n\tif( reason == KSP_CONVERGED_RTOL )\n\t\tasprintf(&reas, \"KSP_CONVERGED_RTOL\" );\n\telse if( reason == KSP_CONVERGED_ATOL )\n\t\tasprintf(&reas, \"KSP_CONVERGED_ATOL\" );\n\telse if( reason == KSP_CONVERGED_ITS )\n\t\tasprintf(&reas, \"KSP_CONVERGED_ITS\" );\n\telse if( reason == KSP_DIVERGED_ITS )\n\t\tasprintf(&reas, \"KSP_DIVERGED_ITS\" );\n\telse if( reason == KSP_DIVERGED_DTOL )\n\t\tasprintf(&reas, \"KSP_DIVERGED_DTOL\" );\n\telse if( reason == KSP_DIVERGED_INDEFINITE_PC )\n\t\tasprintf(&reas, \"KSP_DIVERGED_INDEFINITE_PC\" );\n\telse {\n\t\tStg_SETERRQ( PETSC_ERR_SUP, \"unknown convergence reason detected\");\n\t}\n\t\n\tBSSCR_KSPLogGetResidualTimeHistory(ksp,monitor_index, &nits,&rlog,&log);\n\tif (!rlog || !log) {\n\t\tStg_SETERRQ( PETSC_ERR_ORDER, \"You need to call BSSCR_KSPLogSetMonitor() before BSSCR_KSPLogGetResidualTimeHistory()\" );\n\t}\n\tPetscViewerASCIIPrintf( v, \"\\n\");\n\tPetscViewerASCIIPrintf( v, \"# ===========================================================\\n\");\n\tPetscViewerASCIIPrintf( v, \"#  KSP summary \\n\" );\n\tPetscViewerASCIIPrintf( v, \"#  time (its) [rnorm] reason \\n\" );\n\tPetscViewerASCIIPrintf( v, \"#  %.2f (%d) %.2e %s \\n\", log[nits-1], nits-1, rlog[nits-1], reas );\n\tPetscViewerASCIIPrintf( v, \"# ===========================================================\\n\");\n\t\n\tPetscFunctionReturn(0);\n}\n", "meta": {"hexsha": "b147a53e1d785adc194f138f2616acaeff872b90", "size": 10728, "ext": "c", "lang": "C", "max_stars_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/timed_residual_hist.c", "max_stars_repo_name": "longgangfan/underworld2", "max_stars_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 116.0, "max_stars_repo_stars_event_min_datetime": "2015-09-28T10:30:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T04:12:38.000Z", "max_issues_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/timed_residual_hist.c", "max_issues_repo_name": "longgangfan/underworld2", "max_issues_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 561.0, "max_issues_repo_issues_event_min_datetime": "2015-09-29T06:05:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T23:37:29.000Z", "max_forks_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/timed_residual_hist.c", "max_forks_repo_name": "longgangfan/underworld2", "max_forks_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 68.0, "max_forks_repo_forks_event_min_datetime": "2015-12-14T21:57:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-25T04:54:26.000Z", "avg_line_length": 30.916426513, "max_line_length": 187, "alphanum_fraction": 0.6675988069, "num_tokens": 3571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3208212878370535, "lm_q2_score": 0.050330631173001586, "lm_q1q2_score": 0.01614713791057412}}
{"text": "$NetBSD: patch-Src___dotblas.c,v 1.1 2015/01/27 05:05:30 dbj Exp $\n\n--- Src/_dotblas.c.orig\t2006-07-24 20:11:35.000000000 +0000\n+++ Src/_dotblas.c\n@@ -12,7 +12,11 @@ static char module_doc[] =\n #include \"Python.h\"\n #include \"libnumarray.h\"\n #include \"arrayobject.h\"\n+#ifdef __APPLE__\n+#include <Accelerate/Accelerate.h>\n+#else\n #include <cblas.h>\n+#endif\n \n #include <stdio.h>\n \n", "meta": {"hexsha": "5a8a7af10869cb8267673a3f01c994c90bd0bc44", "size": 379, "ext": "c", "lang": "C", "max_stars_repo_path": "source/pkgsrc/math/py-numarray/patches/patch-Src___dotblas.c", "max_stars_repo_name": "Scottx86-64/dotfiles-1", "max_stars_repo_head_hexsha": "51004b1e2b032664cce6b553d2052757c286087d", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-20T22:46:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-20T22:46:39.000Z", "max_issues_repo_path": "source/pkgsrc/math/py-numarray/patches/patch-Src___dotblas.c", "max_issues_repo_name": "Scottx86-64/dotfiles-1", "max_issues_repo_head_hexsha": "51004b1e2b032664cce6b553d2052757c286087d", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/pkgsrc/math/py-numarray/patches/patch-Src___dotblas.c", "max_forks_repo_name": "Scottx86-64/dotfiles-1", "max_forks_repo_head_hexsha": "51004b1e2b032664cce6b553d2052757c286087d", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2941176471, "max_line_length": 66, "alphanum_fraction": 0.6833773087, "num_tokens": 141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4073334000459302, "lm_q2_score": 0.0396388372574028, "lm_q1q2_score": 0.016146222353925176}}
{"text": "// matrix/kaldi-blas.h\n\n// Copyright 2009-2011  Ondrej Glembek;  Microsoft Corporation\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n\n//  http://www.apache.org/licenses/LICENSE-2.0\n\n// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\n// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\n// MERCHANTABLITY OR NON-INFRINGEMENT.\n// See the Apache 2 License for the specific language governing permissions and\n// limitations under the License.\n#ifndef KALDI_MATRIX_KALDI_BLAS_H_\n#define KALDI_MATRIX_KALDI_BLAS_H_\n\n// This file handles the #includes for BLAS, LAPACK and so on.\n// It manipulates the declarations into a common format that kaldi can handle.\n// However, the kaldi code will check whether HAVE_ATLAS is defined as that\n// code is called a bit differently from CLAPACK that comes from other sources.\n\n// There are three alternatives:\n//   (i) you have ATLAS, which includes the ATLAS implementation of CBLAS\n//   plus a subset of CLAPACK (but with clapack_ in the function declarations).\n//   In this case, define HAVE_ATLAS and make sure the relevant directories are\n//   in the include path.\n\n//   (ii) you have CBLAS (some implementation thereof) plus CLAPACK.\n//   In this case, define HAVE_CLAPACK.\n//   [Since CLAPACK depends on BLAS, the presence of BLAS is implicit].\n\n//  (iii) you have the MKL library, which includes CLAPACK and CBLAS.\n\n// Note that if we are using ATLAS, no Svd implementation is supplied,\n// so we define HAVE_Svd to be zero and this directs our implementation to\n// supply its own \"by hand\" implementation which is based on TNT code.\n\n\n\n\n#if (defined(HAVE_CLAPACK) && (defined(HAVE_ATLAS) || defined(HAVE_MKL))) \\\n    || (defined(HAVE_ATLAS) && defined(HAVE_MKL))\n#error \"Do not define more than one of HAVE_CLAPACK, HAVE_ATLAS and HAVE_MKL\"\n#endif\n\n#ifdef HAVE_ATLAS\n  extern \"C\" {\n    #include <cblas.h>\n    #include <clapack.h>\n  }\n#elif defined(HAVE_CLAPACK)\n  #ifdef __APPLE__\n    #include <Accelerate/Accelerate.h>\n    typedef __CLPK_integer          integer;\n    typedef __CLPK_logical          logical;\n    typedef __CLPK_real             real;\n    typedef __CLPK_doublereal       doublereal;\n    typedef __CLPK_complex          complex;\n    typedef __CLPK_doublecomplex    doublecomplex;\n    typedef __CLPK_ftnlen           ftnlen;\n  #else\n    extern \"C\" {\n      // May be in /usr/[local]/include if installed; else this uses the one\n      // from the external/CLAPACK-* directory.\n      #include <cblas.h>    \n      #include <f2c.h>\n      #include <clapack.h>  \n\n      // get rid of macros from f2c.h -- these are dangerous.\n      #undef abs\n      #undef dabs\n      #undef min\n      #undef max\n      #undef dmin\n      #undef dmax\n      #undef bit_test\n      #undef bit_clear\n      #undef bit_set\n    }\n  #endif\n#elif defined(HAVE_MKL)\n  extern \"C\" {\n    #include <mkl.h>\n  }\n#else\n  #error \"You need to define (using the preprocessor) either HAVE_CLAPACK or HAVE_ATLAS or HAVE_MKL (but not more than one)\"  \n#endif\n\n#ifdef HAVE_CLAPACK\ntypedef integer KaldiBlasInt;\n#endif\n#ifdef HAVE_MKL\ntypedef MKL_INT KaldiBlasInt;\n#endif\n\n#ifdef HAVE_ATLAS\n// in this case there is no need for KaldiBlasInt-- this typedef is only needed\n// for Svd code which is not included in ATLAS (we re-implement it).\n#endif\n\n\n#endif  // KALDI_MATRIX_KALDI_BLAS_H_\n", "meta": {"hexsha": "23b986c07d84d574cbb2f0adfe52c3c294b00581", "size": 3548, "ext": "h", "lang": "C", "max_stars_repo_path": "src/matrix/kaldi-blas.h", "max_stars_repo_name": "hihihippp/Kaldi", "max_stars_repo_head_hexsha": "861f838a2aea264a9e4ffa4df253df00a8b1247f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2015-03-19T10:53:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-17T06:12:32.000Z", "max_issues_repo_path": "src/matrix/kaldi-blas.h", "max_issues_repo_name": "UdyanSachdev/kaldi", "max_issues_repo_head_hexsha": "861f838a2aea264a9e4ffa4df253df00a8b1247f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-12-18T17:43:44.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-18T17:43:44.000Z", "max_forks_repo_path": "src/matrix/kaldi-blas.h", "max_forks_repo_name": "UdyanSachdev/kaldi", "max_forks_repo_head_hexsha": "861f838a2aea264a9e4ffa4df253df00a8b1247f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 47.0, "max_forks_repo_forks_event_min_datetime": "2015-01-27T06:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-11T20:59:04.000Z", "avg_line_length": 33.4716981132, "max_line_length": 126, "alphanum_fraction": 0.7127959414, "num_tokens": 943, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658973632215985, "lm_q2_score": 0.044018648452070645, "lm_q1q2_score": 0.01613678472930243}}
{"text": "#ifndef COMPUTE_SIGNAL_H\n#define COMPUTE_SIGNAL_H\n\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_histogram.h>\n\nvoid compute_signal(double * signal, const size_t length, const double delta,\n    gsl_rng * r, gsl_histogram * hist);\n\n#endif\n", "meta": {"hexsha": "2de39cc48d2fdcad30f91b02e295f4573d1fddb6", "size": 234, "ext": "h", "lang": "C", "max_stars_repo_path": "compute_signal.h", "max_stars_repo_name": "JuliusRuseckas/numerical-sde-variable-step", "max_stars_repo_head_hexsha": "6204ac9d212fd6c73751d215c49e95373b573430", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-03-28T09:12:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T07:04:28.000Z", "max_issues_repo_path": "compute_signal.h", "max_issues_repo_name": "JuliusRuseckas/numerical-sde-variable-step", "max_issues_repo_head_hexsha": "6204ac9d212fd6c73751d215c49e95373b573430", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "compute_signal.h", "max_forks_repo_name": "JuliusRuseckas/numerical-sde-variable-step", "max_forks_repo_head_hexsha": "6204ac9d212fd6c73751d215c49e95373b573430", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.2727272727, "max_line_length": 77, "alphanum_fraction": 0.764957265, "num_tokens": 59, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3106943959796865, "lm_q2_score": 0.051845467016031856, "lm_q1q2_score": 0.016108096058830776}}
{"text": "/*\n * global.h\n *\n *  Created on: Apr 5, 2013\n *      Authors: vgomez, Sep Thijssen\n */\n\n#ifndef GLOBAL_H_\n#define GLOBAL_H_\n\n#include <vector>\n#include <math.h>\n#include <iostream>\n\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n\n#include <ctime>\n\n#include <hal_quadrotor/State.h>\n\n#define SIZE_MSG\t5\n\nusing namespace std;\n\n// Message structure\n//\tIIIII.XXX.xxx.YYY.yyy.ZZZ.zzz.UUU.uuu.VVV.vvv.WWW.vvv\n//\tIIIII\t\tidentifier of the UVA\n//\tXXX.xxx\tposition x\n//\tYYY.yyy\tposition y\n//\tZZZ.zzz\tposition z\n//\tUUU.uuu\tvelocity x\n//\tVVV.vvv\tvelocity y\n//\tWWW.www\tvelocity z\n\ntypedef vector<double> vec;\ntypedef vector<vec> vvec;\n\ntemplate<typename G>\nostream& operator<<(ostream& os, const vector<G>& v)\n{\n\ttypename vector<G>::const_iterator it;\n\tfor (it=v.begin(); it!=v.end(); it++)\n\t\tos << *it << \" \";\n\tos << endl;\n\treturn os;\n}\n\nstring getState(const hal_quadrotor::State::ConstPtr& msg);\n\n#endif /* GLOBAL_H_ */\n", "meta": {"hexsha": "aa993eaf1353cac23080f88901a097233979ab3c", "size": 917, "ext": "h", "lang": "C", "max_stars_repo_path": "thirdparty/cm_picontrol/pi/global.h", "max_stars_repo_name": "jiangchenzhu/crates_zhejiang", "max_stars_repo_head_hexsha": "711c9fafbdc775114345ab0ca389656db9d20df7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thirdparty/cm_picontrol/pi/global.h", "max_issues_repo_name": "jiangchenzhu/crates_zhejiang", "max_issues_repo_head_hexsha": "711c9fafbdc775114345ab0ca389656db9d20df7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thirdparty/cm_picontrol/pi/global.h", "max_forks_repo_name": "jiangchenzhu/crates_zhejiang", "max_forks_repo_head_hexsha": "711c9fafbdc775114345ab0ca389656db9d20df7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.6346153846, "max_line_length": 59, "alphanum_fraction": 0.6804798255, "num_tokens": 283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.03514484273741413, "lm_q1q2_score": 0.01606599802240012}}
{"text": "#ifndef REMESHER_GSL_HELPERS_HEADER\n#define REMESHER_GSL_HELPERS_HEADER\n\n#include <iostream>\n#include <iomanip>\n#include <string>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_vector.h>\n\nnamespace GSL\n{\n  void\n  pretty_print_matrix (gsl_matrix* m, std::string const& name)\n  {\n    std::cout << name << \" = [\";\n    for (std::size_t i = 0; i < m->size2; ++i)\n    {\n      if (i != 0) std::cout << \";\" << std::endl << \"     \";\n      for (std::size_t j = 0; j < m->size1; ++j)\n      {\n        if (j != 0) std::cout << \", \";\n        std::cout << std::setw(6) << std::fixed << std::setprecision(2)\n            << gsl_matrix_get(m, i, j);\n      }\n    }\n    std::cout << \"];\" << std::endl;\n  }\n\n  void\n  pretty_print_vector (gsl_vector* v, std::string const& name)\n  {\n    std::cout << name << \" = [\";\n    for (std::size_t i = 0; i < v->size; ++i)\n    {\n      if (i != 0) std::cout << \"; \";\n      std::cout << std::setw(6) << std::fixed << std::setprecision(2)\n            << gsl_vector_get(v, i);\n    }\n    std::cout << \"];\" << std::endl;\n  }\n\n}\n\n#endif /* REMESHER_GSL_HELPERS_HEADER */\n", "meta": {"hexsha": "394853f562fe52e117415e47b6854f2be1e0494e", "size": 1080, "ext": "h", "lang": "C", "max_stars_repo_path": "remesher/libremesh/gslhelpers.h", "max_stars_repo_name": "jjt20/scripts", "max_stars_repo_head_hexsha": "ec4a001b3082ba4079191ca8aae37be8e790aac2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2018-05-16T01:49:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-05T10:24:44.000Z", "max_issues_repo_path": "remesher/libremesh/gslhelpers.h", "max_issues_repo_name": "jjt20/scripts", "max_issues_repo_head_hexsha": "ec4a001b3082ba4079191ca8aae37be8e790aac2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 29.0, "max_issues_repo_issues_event_min_datetime": "2017-08-20T15:22:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-17T06:06:17.000Z", "max_forks_repo_path": "remesher/libremesh/gslhelpers.h", "max_forks_repo_name": "jjt20/scripts", "max_forks_repo_head_hexsha": "ec4a001b3082ba4079191ca8aae37be8e790aac2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-08-22T19:16:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-31T14:43:18.000Z", "avg_line_length": 24.0, "max_line_length": 71, "alphanum_fraction": 0.5222222222, "num_tokens": 356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2877678035446342, "lm_q2_score": 0.05582313838573451, "lm_q1q2_score": 0.016064101920230976}}
{"text": "#include <errno.h>\n#include <getopt.h>\n#include <gsl/gsl_spmatrix.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <sys/stat.h>\n\nstatic int clock = 1;\nstatic int results = 0;\nstatic int verbose = 0;\nstatic int help = 0;\n\nint test (size_t m,\n          size_t n,\n          size_t nnz,\n          const size_t *ptr,\n          const size_t *ind,\n          size_t B,\n          double epsilon,\n          double delta,\n          int trials,\n          int clock,\n          int results,\n          int verbose);\n\nchar *name ();\n\nstatic void usage () {\n  fprintf(stderr,\"usage: %s [options] <input>\\n\"\n  \"  <input>                    MatrixMarket file (estimate fill of this matrix)\\n\"\n  \"  -B, --max-block-size <arg> Maximum block dimension for fill estimates\\n\"\n  \"  -e, --epsilon <arg>        Be accurate to relative error epsilon\\n\"\n  \"  -d, --delta <arg>          With probability (1 - delta)\\n\"\n  \"  -t, --trials <arg>         Number of trials to run\\n\"\n  \"  -c, --clock                Display timing information\\n\"\n  \"  -C, --noclock              Do not display timing information\\n\"\n  \"  -r, --results              Display fill estimates for all trials\\n\"\n  \"  -R, --noresults            Do not display fill estimates\\n\"\n  \"  -v, --verbose              Verbose mode\\n\"\n  \"  -q, --quiet                Quiet mode\\n\"\n  \"  -h, --help                 Display help message\\n\", name());\n}\n\nint main (int argc, char **argv) {\n\n  size_t B = 12;\n  double epsilon = 0.1;\n  double delta = 0.01;\n  int trials = 1;\n\n  /* Beware. Option parsing below. */\n  long longarg;\n  double doublearg;\n  while (1) {\n    static char *options = \"B:e:d:t:cCrRvqh\";\n    static struct option long_options[] = {\n        {\"max-block-size\", required_argument, 0, 'B'},\n        {\"trials\",         required_argument, 0, 't'},\n        {\"epsilon\", required_argument, 0, 'e'},\n        {\"delta\", required_argument, 0, 'd'},\n        {\"clock\",     no_argument, &clock,   1},\n        {\"noclock\",   no_argument, &clock,   0},\n        {\"results\",   no_argument, &results, 1},\n        {\"noresults\", no_argument, &results, 0},\n        {\"verbose\",   no_argument, &verbose, 1},\n        {\"quiet\",     no_argument, &verbose, 0},\n        {\"help\",      no_argument, &help,    1},\n        {0, 0, 0, 0}\n      };\n\n    /* getopt_long stores the option index here. */\n    int option_index = 0;\n\n    int c = getopt_long (argc, argv, options,\n                     long_options, &option_index);\n\n    /* Detect the end of the options. */\n    if (c == -1)\n      break;\n\n    if (c == 0 && long_options[option_index].flag == 0)\n      c = long_options[option_index].val;\n\n    switch (c) {\n      case 0:\n        /* If this option set a flag, do nothing else now. */\n        break;\n\n      case 'B':\n        errno = 0;\n        longarg = strtol(optarg, 0, 10);\n        if (errno != 0 || longarg < 1) {\n          printf(\"option -B takes an integer maximum block size >= 1\\n\");\n          usage();\n          return 1;\n        }\n        B = longarg;\n        break;\n\n      case 'e':\n        errno = 0;\n        doublearg = strtod(optarg, 0);\n        if (errno != 0 || doublearg < 0.0) {\n          printf(\"option -e takes a desired relative error >= 0.0\\n\");\n          usage();\n          return 1;\n        }\n        epsilon = doublearg;\n        break;\n\n      case 'd':\n        errno = 0;\n        doublearg = strtod(optarg, 0);\n        if (errno != 0 || doublearg < 0.0 || doublearg > 1.0) {\n          printf(\"option -d takes a desired probability >= 0.0 and <= 1.0\\n\");\n          usage();\n          return 1;\n        }\n        delta = doublearg;\n        break;\n\n      case 't':\n        errno = 0;\n        longarg = strtol(optarg, 0, 10);\n        if (errno != 0 || longarg < 1) {\n          printf(\"option -t takes an integer number of trials >= 1\\n\");\n          usage();\n          return 1;\n        }\n        trials = longarg;\n        break;\n\n      case 'c':\n        clock = 1;\n        break;\n\n      case 'C':\n        clock = 0;\n        break;\n\n      case 'r':\n        results = 1;\n        break;\n\n      case 'R':\n        results = 0;\n        break;\n\n      case 'v':\n        verbose = 1;\n        break;\n\n      case 'q':\n        verbose = 0;\n        break;\n\n      case 'h':\n        help = 1;\n        break;\n\n      case '?':\n        usage();\n        return 1;\n\n      default:\n        abort();\n    }\n  }\n\n  if (help) {\n    printf(\"Run a fill estimation algorithm!\\n\");\n    usage();\n    return 0;\n  }\n\n  if (argc - optind > 1) {\n    printf(\"<input> cannot be more than one file\\n\");\n    usage();\n    return 1;\n  }\n\n  if (argc - optind < 1) {\n    printf(\"<input> not specified\\n\");\n    usage();\n    return 1;\n  }\n\n  struct stat statthing;\n  if (stat(argv[optind], &statthing) < 0 || !S_ISREG(statthing.st_mode)){\n    printf(\"<input> must be filename of MatrixMarket matrix\\n\");\n    usage();\n    return 1;\n  }\n\n  FILE *f = fopen(argv[optind], \"r\");\n  gsl_spmatrix *triples = gsl_spmatrix_fscanf(f);\n  fclose(f);\n  if (triples == 0) {\n    printf(\"<input> must be filename of MatrixMarket matrix\\n\");\n    usage();\n    return 1;\n  }\n\n  gsl_spmatrix *csr = gsl_spmatrix_crs(triples);\n  gsl_spmatrix_free(triples);\n\n  //gsl_spmatrix_fprintf(stdout, csr, \"%g\");\n\n  int ret = test(csr->size1, csr->size2, csr->nz, csr->p, csr->i, B, epsilon, delta, trials, clock, results, verbose);\n\n  gsl_spmatrix_free(csr);\n\n  return ret;\n}\n", "meta": {"hexsha": "86605794f7d1b03981b21ebb5cee78a18f3afba6", "size": 5335, "ext": "c", "lang": "C", "max_stars_repo_path": "src/run_fill.c", "max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/run_fill.c", "max_issues_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_issues_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/run_fill.c", "max_forks_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_forks_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8139534884, "max_line_length": 118, "alphanum_fraction": 0.5137769447, "num_tokens": 1500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3593641451601019, "lm_q2_score": 0.04468087392992903, "lm_q1q2_score": 0.01605670406483523}}
{"text": "/* matrix/gsl_matrix_ulong.h\r\n * \r\n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\r\n * \r\n * This program is free software; you can redistribute it and/or modify\r\n * it under the terms of the GNU General Public License as published by\r\n * the Free Software Foundation; either version 3 of the License, or (at\r\n * your option) any later version.\r\n * \r\n * This program is distributed in the hope that it will be useful, but\r\n * WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n * General Public License for more details.\r\n * \r\n * You should have received a copy of the GNU General Public License\r\n * along with this program; if not, write to the Free Software\r\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r\n */\r\n\r\n#ifndef __GSL_MATRIX_ULONG_H__\r\n#define __GSL_MATRIX_ULONG_H__\r\n\r\n#if !defined( GSL_FUN )\r\n#  if !defined( GSL_DLL )\r\n#    define GSL_FUN extern\r\n#  elif defined( BUILD_GSL_DLL )\r\n#    define GSL_FUN extern __declspec(dllexport)\r\n#  else\r\n#    define GSL_FUN extern __declspec(dllimport)\r\n#  endif\r\n#endif\r\n\r\n#include <stdlib.h>\r\n#include <gsl/gsl_types.h>\r\n#include <gsl/gsl_errno.h>\r\n#include <gsl/gsl_inline.h>\r\n#include <gsl/gsl_check_range.h>\r\n#include <gsl/gsl_vector_ulong.h>\r\n#include <gsl/gsl_blas_types.h>\r\n\r\n#undef __BEGIN_DECLS\r\n#undef __END_DECLS\r\n#ifdef __cplusplus\r\n# define __BEGIN_DECLS extern \"C\" {\r\n# define __END_DECLS }\r\n#else\r\n# define __BEGIN_DECLS /* empty */\r\n# define __END_DECLS /* empty */\r\n#endif\r\n\r\n__BEGIN_DECLS\r\n\r\ntypedef struct \r\n{\r\n  size_t size1;\r\n  size_t size2;\r\n  size_t tda;\r\n  unsigned long * data;\r\n  gsl_block_ulong * block;\r\n  int owner;\r\n} gsl_matrix_ulong;\r\n\r\ntypedef struct\r\n{\r\n  gsl_matrix_ulong matrix;\r\n} _gsl_matrix_ulong_view;\r\n\r\ntypedef _gsl_matrix_ulong_view gsl_matrix_ulong_view;\r\n\r\ntypedef struct\r\n{\r\n  gsl_matrix_ulong matrix;\r\n} _gsl_matrix_ulong_const_view;\r\n\r\ntypedef const _gsl_matrix_ulong_const_view gsl_matrix_ulong_const_view;\r\n\r\n/* Allocation */\r\n\r\nGSL_FUN gsl_matrix_ulong * \r\ngsl_matrix_ulong_alloc (const size_t n1, const size_t n2);\r\n\r\nGSL_FUN gsl_matrix_ulong * \r\ngsl_matrix_ulong_calloc (const size_t n1, const size_t n2);\r\n\r\nGSL_FUN gsl_matrix_ulong * \r\ngsl_matrix_ulong_alloc_from_block (gsl_block_ulong * b, \r\n                                   const size_t offset, \r\n                                   const size_t n1, \r\n                                   const size_t n2, \r\n                                   const size_t d2);\r\n\r\nGSL_FUN gsl_matrix_ulong * \r\ngsl_matrix_ulong_alloc_from_matrix (gsl_matrix_ulong * m,\r\n                                    const size_t k1, \r\n                                    const size_t k2,\r\n                                    const size_t n1, \r\n                                    const size_t n2);\r\n\r\nGSL_FUN gsl_vector_ulong * \r\ngsl_vector_ulong_alloc_row_from_matrix (gsl_matrix_ulong * m,\r\n                                        const size_t i);\r\n\r\nGSL_FUN gsl_vector_ulong * \r\ngsl_vector_ulong_alloc_col_from_matrix (gsl_matrix_ulong * m,\r\n                                        const size_t j);\r\n\r\nGSL_FUN void gsl_matrix_ulong_free (gsl_matrix_ulong * m);\r\n\r\n/* Views */\r\n\r\nGSL_FUN _gsl_matrix_ulong_view \r\ngsl_matrix_ulong_submatrix (gsl_matrix_ulong * m, \r\n                            const size_t i, const size_t j, \r\n                            const size_t n1, const size_t n2);\r\n\r\nGSL_FUN _gsl_vector_ulong_view \r\ngsl_matrix_ulong_row (gsl_matrix_ulong * m, const size_t i);\r\n\r\nGSL_FUN _gsl_vector_ulong_view \r\ngsl_matrix_ulong_column (gsl_matrix_ulong * m, const size_t j);\r\n\r\nGSL_FUN _gsl_vector_ulong_view \r\ngsl_matrix_ulong_diagonal (gsl_matrix_ulong * m);\r\n\r\nGSL_FUN _gsl_vector_ulong_view \r\ngsl_matrix_ulong_subdiagonal (gsl_matrix_ulong * m, const size_t k);\r\n\r\nGSL_FUN _gsl_vector_ulong_view \r\ngsl_matrix_ulong_superdiagonal (gsl_matrix_ulong * m, const size_t k);\r\n\r\nGSL_FUN _gsl_vector_ulong_view\r\ngsl_matrix_ulong_subrow (gsl_matrix_ulong * m, const size_t i,\r\n                         const size_t offset, const size_t n);\r\n\r\nGSL_FUN _gsl_vector_ulong_view\r\ngsl_matrix_ulong_subcolumn (gsl_matrix_ulong * m, const size_t j,\r\n                            const size_t offset, const size_t n);\r\n\r\nGSL_FUN _gsl_matrix_ulong_view\r\ngsl_matrix_ulong_view_array (unsigned long * base,\r\n                             const size_t n1, \r\n                             const size_t n2);\r\n\r\nGSL_FUN _gsl_matrix_ulong_view\r\ngsl_matrix_ulong_view_array_with_tda (unsigned long * base, \r\n                                      const size_t n1, \r\n                                      const size_t n2,\r\n                                      const size_t tda);\r\n\r\n\r\nGSL_FUN _gsl_matrix_ulong_view\r\ngsl_matrix_ulong_view_vector (gsl_vector_ulong * v,\r\n                              const size_t n1, \r\n                              const size_t n2);\r\n\r\nGSL_FUN _gsl_matrix_ulong_view\r\ngsl_matrix_ulong_view_vector_with_tda (gsl_vector_ulong * v,\r\n                                       const size_t n1, \r\n                                       const size_t n2,\r\n                                       const size_t tda);\r\n\r\n\r\nGSL_FUN _gsl_matrix_ulong_const_view \r\ngsl_matrix_ulong_const_submatrix (const gsl_matrix_ulong * m, \r\n                                  const size_t i, const size_t j, \r\n                                  const size_t n1, const size_t n2);\r\n\r\nGSL_FUN _gsl_vector_ulong_const_view \r\ngsl_matrix_ulong_const_row (const gsl_matrix_ulong * m, \r\n                            const size_t i);\r\n\r\nGSL_FUN _gsl_vector_ulong_const_view \r\ngsl_matrix_ulong_const_column (const gsl_matrix_ulong * m, \r\n                               const size_t j);\r\n\r\nGSL_FUN _gsl_vector_ulong_const_view\r\ngsl_matrix_ulong_const_diagonal (const gsl_matrix_ulong * m);\r\n\r\nGSL_FUN _gsl_vector_ulong_const_view \r\ngsl_matrix_ulong_const_subdiagonal (const gsl_matrix_ulong * m, \r\n                                    const size_t k);\r\n\r\nGSL_FUN _gsl_vector_ulong_const_view \r\ngsl_matrix_ulong_const_superdiagonal (const gsl_matrix_ulong * m, \r\n                                      const size_t k);\r\n\r\nGSL_FUN _gsl_vector_ulong_const_view\r\ngsl_matrix_ulong_const_subrow (const gsl_matrix_ulong * m, const size_t i,\r\n                               const size_t offset, const size_t n);\r\n\r\nGSL_FUN _gsl_vector_ulong_const_view\r\ngsl_matrix_ulong_const_subcolumn (const gsl_matrix_ulong * m, const size_t j,\r\n                                  const size_t offset, const size_t n);\r\n\r\nGSL_FUN _gsl_matrix_ulong_const_view\r\ngsl_matrix_ulong_const_view_array (const unsigned long * base,\r\n                                   const size_t n1, \r\n                                   const size_t n2);\r\n\r\nGSL_FUN _gsl_matrix_ulong_const_view\r\ngsl_matrix_ulong_const_view_array_with_tda (const unsigned long * base, \r\n                                            const size_t n1, \r\n                                            const size_t n2,\r\n                                            const size_t tda);\r\n\r\nGSL_FUN _gsl_matrix_ulong_const_view\r\ngsl_matrix_ulong_const_view_vector (const gsl_vector_ulong * v,\r\n                                    const size_t n1, \r\n                                    const size_t n2);\r\n\r\nGSL_FUN _gsl_matrix_ulong_const_view\r\ngsl_matrix_ulong_const_view_vector_with_tda (const gsl_vector_ulong * v,\r\n                                             const size_t n1, \r\n                                             const size_t n2,\r\n                                             const size_t tda);\r\n\r\n/* Operations */\r\n\r\nGSL_FUN void gsl_matrix_ulong_set_zero (gsl_matrix_ulong * m);\r\nGSL_FUN void gsl_matrix_ulong_set_identity (gsl_matrix_ulong * m);\r\nGSL_FUN void gsl_matrix_ulong_set_all (gsl_matrix_ulong * m, unsigned long x);\r\n\r\nGSL_FUN int gsl_matrix_ulong_fread (FILE * stream, gsl_matrix_ulong * m) ;\r\nGSL_FUN int gsl_matrix_ulong_fwrite (FILE * stream, const gsl_matrix_ulong * m) ;\r\nGSL_FUN int gsl_matrix_ulong_fscanf (FILE * stream, gsl_matrix_ulong * m);\r\nGSL_FUN int gsl_matrix_ulong_fprintf (FILE * stream, const gsl_matrix_ulong * m, const char * format);\r\n \r\nGSL_FUN int gsl_matrix_ulong_memcpy(gsl_matrix_ulong * dest, const gsl_matrix_ulong * src);\r\nGSL_FUN int gsl_matrix_ulong_swap(gsl_matrix_ulong * m1, gsl_matrix_ulong * m2);\r\nGSL_FUN int gsl_matrix_ulong_tricpy(CBLAS_UPLO_t Uplo, CBLAS_DIAG_t Diag, gsl_matrix_ulong * dest, const gsl_matrix_ulong * src);\r\n\r\nGSL_FUN int gsl_matrix_ulong_swap_rows(gsl_matrix_ulong * m, const size_t i, const size_t j);\r\nGSL_FUN int gsl_matrix_ulong_swap_columns(gsl_matrix_ulong * m, const size_t i, const size_t j);\r\nGSL_FUN int gsl_matrix_ulong_swap_rowcol(gsl_matrix_ulong * m, const size_t i, const size_t j);\r\nGSL_FUN int gsl_matrix_ulong_transpose (gsl_matrix_ulong * m);\r\nGSL_FUN int gsl_matrix_ulong_transpose_memcpy (gsl_matrix_ulong * dest, const gsl_matrix_ulong * src);\r\nGSL_FUN int gsl_matrix_ulong_transpose_tricpy (CBLAS_UPLO_t Uplo_src, CBLAS_DIAG_t Diag, gsl_matrix_ulong * dest, const gsl_matrix_ulong * src);\r\n\r\nGSL_FUN unsigned long gsl_matrix_ulong_max (const gsl_matrix_ulong * m);\r\nGSL_FUN unsigned long gsl_matrix_ulong_min (const gsl_matrix_ulong * m);\r\nGSL_FUN void gsl_matrix_ulong_minmax (const gsl_matrix_ulong * m, unsigned long * min_out, unsigned long * max_out);\r\n\r\nGSL_FUN void gsl_matrix_ulong_max_index (const gsl_matrix_ulong * m, size_t * imax, size_t *jmax);\r\nGSL_FUN void gsl_matrix_ulong_min_index (const gsl_matrix_ulong * m, size_t * imin, size_t *jmin);\r\nGSL_FUN void gsl_matrix_ulong_minmax_index (const gsl_matrix_ulong * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);\r\n\r\nGSL_FUN int gsl_matrix_ulong_equal (const gsl_matrix_ulong * a, const gsl_matrix_ulong * b);\r\n\r\nGSL_FUN int gsl_matrix_ulong_isnull (const gsl_matrix_ulong * m);\r\nGSL_FUN int gsl_matrix_ulong_ispos (const gsl_matrix_ulong * m);\r\nGSL_FUN int gsl_matrix_ulong_isneg (const gsl_matrix_ulong * m);\r\nGSL_FUN int gsl_matrix_ulong_isnonneg (const gsl_matrix_ulong * m);\r\n\r\nGSL_FUN unsigned long gsl_matrix_ulong_norm1 (const gsl_matrix_ulong * m);\r\n\r\nGSL_FUN int gsl_matrix_ulong_add (gsl_matrix_ulong * a, const gsl_matrix_ulong * b);\r\nGSL_FUN int gsl_matrix_ulong_sub (gsl_matrix_ulong * a, const gsl_matrix_ulong * b);\r\nGSL_FUN int gsl_matrix_ulong_mul_elements (gsl_matrix_ulong * a, const gsl_matrix_ulong * b);\r\nGSL_FUN int gsl_matrix_ulong_div_elements (gsl_matrix_ulong * a, const gsl_matrix_ulong * b);\r\nGSL_FUN int gsl_matrix_ulong_scale (gsl_matrix_ulong * a, const double x);\r\nGSL_FUN int gsl_matrix_ulong_scale_rows (gsl_matrix_ulong * a, const gsl_vector_ulong * x);\r\nGSL_FUN int gsl_matrix_ulong_scale_columns (gsl_matrix_ulong * a, const gsl_vector_ulong * x);\r\nGSL_FUN int gsl_matrix_ulong_add_constant (gsl_matrix_ulong * a, const double x);\r\nGSL_FUN int gsl_matrix_ulong_add_diagonal (gsl_matrix_ulong * a, const double x);\r\n\r\n/***********************************************************************/\r\n/* The functions below are obsolete                                    */\r\n/***********************************************************************/\r\nGSL_FUN int gsl_matrix_ulong_get_row(gsl_vector_ulong * v, const gsl_matrix_ulong * m, const size_t i);\r\nGSL_FUN int gsl_matrix_ulong_get_col(gsl_vector_ulong * v, const gsl_matrix_ulong * m, const size_t j);\r\nGSL_FUN int gsl_matrix_ulong_set_row(gsl_matrix_ulong * m, const size_t i, const gsl_vector_ulong * v);\r\nGSL_FUN int gsl_matrix_ulong_set_col(gsl_matrix_ulong * m, const size_t j, const gsl_vector_ulong * v);\r\n/***********************************************************************/\r\n\r\n/* inline functions if you are using GCC */\r\n\r\nGSL_FUN INLINE_DECL unsigned long   gsl_matrix_ulong_get(const gsl_matrix_ulong * m, const size_t i, const size_t j);\r\nGSL_FUN INLINE_DECL void    gsl_matrix_ulong_set(gsl_matrix_ulong * m, const size_t i, const size_t j, const unsigned long x);\r\nGSL_FUN INLINE_DECL unsigned long * gsl_matrix_ulong_ptr(gsl_matrix_ulong * m, const size_t i, const size_t j);\r\nGSL_FUN INLINE_DECL const unsigned long * gsl_matrix_ulong_const_ptr(const gsl_matrix_ulong * m, const size_t i, const size_t j);\r\n\r\n#ifdef HAVE_INLINE\r\nINLINE_FUN \r\nunsigned long\r\ngsl_matrix_ulong_get(const gsl_matrix_ulong * m, const size_t i, const size_t j)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(1)) \r\n    {\r\n      if (i >= m->size1)\r\n        {\r\n          GSL_ERROR_VAL(\"first index out of range\", GSL_EINVAL, 0) ;\r\n        }\r\n      else if (j >= m->size2)\r\n        {\r\n          GSL_ERROR_VAL(\"second index out of range\", GSL_EINVAL, 0) ;\r\n        }\r\n    }\r\n#endif\r\n  return m->data[i * m->tda + j] ;\r\n} \r\n\r\nINLINE_FUN \r\nvoid\r\ngsl_matrix_ulong_set(gsl_matrix_ulong * m, const size_t i, const size_t j, const unsigned long x)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(1)) \r\n    {\r\n      if (i >= m->size1)\r\n        {\r\n          GSL_ERROR_VOID(\"first index out of range\", GSL_EINVAL) ;\r\n        }\r\n      else if (j >= m->size2)\r\n        {\r\n          GSL_ERROR_VOID(\"second index out of range\", GSL_EINVAL) ;\r\n        }\r\n    }\r\n#endif\r\n  m->data[i * m->tda + j] = x ;\r\n}\r\n\r\nINLINE_FUN \r\nunsigned long *\r\ngsl_matrix_ulong_ptr(gsl_matrix_ulong * m, const size_t i, const size_t j)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(1)) \r\n    {\r\n      if (i >= m->size1)\r\n        {\r\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\r\n        }\r\n      else if (j >= m->size2)\r\n        {\r\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\r\n        }\r\n    }\r\n#endif\r\n  return (unsigned long *) (m->data + (i * m->tda + j)) ;\r\n} \r\n\r\nINLINE_FUN \r\nconst unsigned long *\r\ngsl_matrix_ulong_const_ptr(const gsl_matrix_ulong * m, const size_t i, const size_t j)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(1)) \r\n    {\r\n      if (i >= m->size1)\r\n        {\r\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\r\n        }\r\n      else if (j >= m->size2)\r\n        {\r\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\r\n        }\r\n    }\r\n#endif\r\n  return (const unsigned long *) (m->data + (i * m->tda + j)) ;\r\n} \r\n\r\n#endif\r\n\r\n__END_DECLS\r\n\r\n#endif /* __GSL_MATRIX_ULONG_H__ */\r\n", "meta": {"hexsha": "7fd554430ac80a85d5c6a016061357f1e4c51c0c", "size": 14185, "ext": "h", "lang": "C", "max_stars_repo_path": "vendor/gsl/gsl/gsl_matrix_ulong.h", "max_stars_repo_name": "mgreter/astrometrylib", "max_stars_repo_head_hexsha": "ef4d4539a537ab49329b77648aac893d2b4ad318", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z", "max_issues_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_matrix_ulong.h", "max_issues_repo_name": "zzpwahaha/VimbaCamJILA", "max_issues_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z", "max_forks_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_matrix_ulong.h", "max_forks_repo_name": "zzpwahaha/VimbaCamJILA", "max_forks_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 38.5461956522, "max_line_length": 145, "alphanum_fraction": 0.6568205851, "num_tokens": 3384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3702253925955866, "lm_q2_score": 0.04336580092752893, "lm_q1q2_score": 0.016055120673616453}}
{"text": "#include <gsl/gsl_linalg.h>\n\n/* user defined functions */\n\n", "meta": {"hexsha": "bd27405f63ce51a305ec6317084801b471dd5db3", "size": 59, "ext": "h", "lang": "C", "max_stars_repo_path": "src/yipf-gsl/yipf-gsl.h", "max_stars_repo_name": "yipf/lua-graphics", "max_stars_repo_head_hexsha": "bdb6c48820158e674a87985efa3335b14715f9f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-04-09T09:13:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T11:09:52.000Z", "max_issues_repo_path": "src/yipf-gsl/yipf-gsl.h", "max_issues_repo_name": "yipf/lua-graphics", "max_issues_repo_head_hexsha": "bdb6c48820158e674a87985efa3335b14715f9f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/yipf-gsl/yipf-gsl.h", "max_forks_repo_name": "yipf/lua-graphics", "max_forks_repo_head_hexsha": "bdb6c48820158e674a87985efa3335b14715f9f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 11.8, "max_line_length": 28, "alphanum_fraction": 0.6949152542, "num_tokens": 15, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.5, "lm_q2_score": 0.032100710073633826, "lm_q1q2_score": 0.016050355036816913}}
{"text": "///\n/// @file\n///\n/// @author Mirko Myllykoski (mirkom@cs.umu.se), Ume\u00e5 University\n///\n/// @internal LICENSE\n///\n/// Copyright (c) 2019-2020, Ume\u00e5 Universitet\n///\n/// Redistribution and use in source and binary forms, with or without\n/// modification, are permitted provided that the following conditions are met:\n///\n/// 1. Redistributions of source code must retain the above copyright notice,\n///    this list of conditions and the following disclaimer.\n///\n/// 2. Redistributions in binary form must reproduce the above copyright notice,\n///    this list of conditions and the following disclaimer in the documentation\n///    and/or other materials provided with the distribution.\n///\n/// 3. Neither the name of the copyright holder nor the names of its\n///    contributors may be used to endorse or promote products derived from this\n///    software without specific prior written permission.\n///\n/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n/// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n/// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n/// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n/// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n/// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n/// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n/// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n/// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n/// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n/// POSSIBILITY OF SUCH DAMAGE.\n///\n\n#include <starneig_config.h>\n#include <starneig/configuration.h>\n#include \"cpu.h\"\n#include \"../common/common.h\"\n#include \"../common/sanity.h\"\n#include \"../common/tiles.h\"\n#include \"../common/trace.h\"\n#include <starpu.h>\n#include <starpu_scheduler.h>\n#include <hwloc.h>\n#include <cblas.h>\n#include <omp.h>\n\nvoid starneig_hessenberg_cpu_prepare_column(\n    void *buffers[], void *cl_args)\n{\n    // LAPACK subroutine that generates a real elementary reflector H\n    extern void dlarfg_(int const *, double *, double *, int const *, double *);\n\n    int i; // the index of the currect column inside the panel\n    struct range_packing_info v_pi;\n    starpu_codelet_unpack_args(cl_args, &i, &v_pi);\n\n    int k = 0;\n\n    double *Y = NULL; int ldY = 0;\n    if (0 < i) {\n        Y = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);\n        ldY = STARPU_MATRIX_GET_LD(buffers[k]);\n        k++;\n    }\n\n    double *V = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);\n    int ldV = STARPU_MATRIX_GET_LD(buffers[k]);\n    int m = STARPU_MATRIX_GET_NX(buffers[k]);\n    int nb = STARPU_MATRIX_GET_NY(buffers[k]);\n    k++;\n\n    double *T = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);\n    int ldT = STARPU_MATRIX_GET_LD(buffers[k]);\n    k++;\n\n    double *P = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);\n    int ldP = STARPU_MATRIX_GET_LD(buffers[k]);\n    k++;\n\n    // an intemediate vector interface for the trailing matrix operation\n    struct starpu_vector_interface **v_i =\n        (struct starpu_vector_interface **)buffers + k;\n    k += v_pi.handles;\n\n    // current column\n    double *p = P+i*ldP;\n\n    //\n    // update the current column\n    //\n\n    if (0 < i) {\n\n        // A <- A - Y * V' (update column from the right)\n        cblas_dgemv(CblasColMajor, CblasNoTrans, m, i,\n            -1.0, Y, ldY, V+i-1, ldV, 1.0, p, 1);\n\n        //\n        // update column from the left\n        //\n\n        // we use the last column of T as a work space\n        double *w = T+(nb-1)*ldT;\n\n        // w <- V1' * b1 (upper part)\n        cblas_dcopy(i, p, 1, w, 1);\n        cblas_dtrmv(\n            CblasColMajor, CblasLower, CblasTrans, CblasUnit, i, V, ldV, w, 1);\n\n        // w <- w + V2' * b2 (lower part)\n        cblas_dgemv(CblasColMajor, CblasTrans, m-i, i,\n            1.0, V+i, ldV, p+i, 1, 1.0, w, 1);\n\n        // w <- T' * w\n        cblas_dtrmv(\n            CblasColMajor, CblasUpper, CblasTrans, CblasNonUnit, i,\n            T, ldT, w, 1);\n\n        // b2 <- b2 - V2 * w\n        cblas_dgemv(CblasColMajor, CblasNoTrans, m-i, i,\n            -1.0, V+i, ldV, w, 1, 1.0, p+i, 1);\n\n        // b1 <- b1 - V1 * w\n        cblas_dtrmv(\n            CblasColMajor, CblasLower, CblasNoTrans, CblasUnit, i,\n            V, ldV, w, 1);\n        cblas_daxpy(i, -1.0, w, 1, p, 1);\n    }\n\n    //\n    // compute the current unit vector\n    //\n\n    int height = m-i;\n    double tau, *v = V+i*ldV+i;\n    memcpy(v, p+i, height*sizeof(double));\n    dlarfg_(&height, p+i, v+1, (const int[]){1}, &tau);\n    v[0] = 1.0;\n\n    //\n    // copy the current unit vector to the intemediate vector interface\n    //\n\n    starneig_join_range(&v_pi, v_i, v, 1);\n\n    //\n    // set elements below the subdiagonal to zero\n    //\n\n    for (int j = i+1; j < m; j++)\n        p[j] = 0.0;\n\n    //\n    // store tau for future use\n    //\n\n    T[i*ldT+i] = tau;\n}\n\nvoid starneig_hessenberg_cpu_compute_column(\n    void *buffers[], void *cl_args)\n{\n    struct packing_info A_pi;\n    struct range_packing_info v_pi, y_pi;\n    starpu_codelet_unpack_args(cl_args, &A_pi, &v_pi, &y_pi);\n\n    STARNEIG_EVENT_BEGIN(&A_pi, starneig_event_red);\n\n    int k = 0;\n\n    // involved trailing matrix tiles\n    struct starpu_matrix_interface **A_i =\n        (struct starpu_matrix_interface **)buffers + k;\n    k += A_pi.handles;\n\n    // intemediate vector interface for the trailing matrix operation\n    struct starpu_vector_interface **v_i =\n        (struct starpu_vector_interface **)buffers + k;\n    k += v_pi.handles;\n\n    // intemediate vector interface from the trailing matrix operation\n    struct starpu_vector_interface **y_i =\n        (struct starpu_vector_interface **)buffers + k;\n    k += y_pi.handles;\n\n    int t_rows = (A_pi.rend-1) / A_pi.bm + 1 - (A_pi.rbegin-1) / A_pi.bm;\n    int t_cols = (A_pi.cend-1) / A_pi.bn + 1 - (A_pi.cbegin-1) / A_pi.bn;\n\n    //\n    // loop oper tile rows\n    //\n\n    for (int i = 0; i < t_rows; i++) {\n\n        double *y = (double *) STARPU_VECTOR_GET_PTR(y_i[i]);\n\n        int rbegin = MAX(     0,  A_pi.rbegin - i * A_pi.bm);\n        int rend =   MIN(A_pi.bm, A_pi.rend   - i * A_pi.bm);\n\n        //\n        // loop over tile columns\n        //\n\n        for (int j = 0; j < t_cols; j++) {\n\n            double *A = (double *) STARPU_MATRIX_GET_PTR(A_i[j*t_rows+i]);\n            int ldA = STARPU_MATRIX_GET_LD(A_i[j*t_rows+i]);\n\n            double *v = (double *) STARPU_VECTOR_GET_PTR(v_i[j]);\n\n            int cbegin = MAX(      0, A_pi.cbegin - j * A_pi.bn);\n            int cend =   MIN(A_pi.bn, A_pi.cend   - j * A_pi.bn);\n\n            cblas_dgemv(\n                CblasColMajor, CblasNoTrans, rend-rbegin, cend-cbegin,\n                1.0, A+cbegin*ldA+rbegin, ldA, v+cbegin, 1, 1.0, y+rbegin, 1);\n        }\n    }\n\n    STARNEIG_EVENT_END();\n}\n\nvoid starneig_hessenberg_cpu_finish_column(\n    void *buffers[], void *cl_args)\n{\n    struct range_packing_info y_pi;\n    int i;\n    starpu_codelet_unpack_args(cl_args, &i, &y_pi);\n\n    int k = 0;\n\n    double *V = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);\n    int m = STARPU_MATRIX_GET_NX(buffers[k]);\n    int ldV = STARPU_MATRIX_GET_LD(buffers[k]);\n    k++;\n\n    double *T = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);\n    int ldT = STARPU_MATRIX_GET_LD(buffers[k]);\n    k++;\n\n    double *Y = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);\n    int ldY = STARPU_MATRIX_GET_LD(buffers[k]);\n    k++;\n\n    // intemediate vector interface from the trailing matrix operation\n    struct starpu_vector_interface **y_i =\n        (struct starpu_vector_interface **)buffers + k;\n    k += y_pi.handles;\n\n    double tau = T[i*ldT+i];\n    double *v = V+i*ldV+i;\n\n    //\n    // finish Y update\n    //\n\n    starneig_join_range(&y_pi, y_i, Y+i*ldY, 0);\n\n    // w <- V' * v (shared result)\n    cblas_dgemv(CblasColMajor, CblasTrans, m-i, i,\n        1.0, V+i, ldV, v, 1, 0.0, T+i*ldT, 1);\n\n    // Y(:,i) <- Y(:,i) - Y * w\n    cblas_dgemv(CblasColMajor, CblasNoTrans, m, i,\n        -1.0, Y, ldY, T+i*ldT, 1, 1.0, Y+i*ldY, 1);\n\n    cblas_dscal(m, tau, Y+i*ldY, 1);\n\n    //\n    // update T\n    //\n\n    // w <- tau * w\n    cblas_dscal(i, -tau, T+i*ldT, 1);\n\n    // T(0:i,i) = T * w\n    cblas_dtrmv(\n        CblasColMajor, CblasUpper, CblasNoTrans, CblasNonUnit, i,\n        T, ldT, T+i*ldT, 1);\n\n    T[i*ldT+i] = tau;\n}\n\nvoid starneig_hessenberg_cpu_update_trail_right(\n    void *buffers[], void *cl_args)\n{\n    struct packing_info A_pi;\n    int nb, roffset, coffset;\n    starpu_codelet_unpack_args(cl_args, &A_pi, &nb, &roffset, &coffset);\n\n    STARNEIG_EVENT_BEGIN(&A_pi, starneig_event_blue);\n\n    int m = A_pi.rend - A_pi.rbegin;\n    int n = A_pi.cend - A_pi.cbegin;\n\n    double *V = (double *) STARPU_MATRIX_GET_PTR(buffers[0]);\n    int ldV = STARPU_MATRIX_GET_LD(buffers[0]);\n\n    double *Y = (double *) STARPU_MATRIX_GET_PTR(buffers[1]);\n    int ldY = STARPU_MATRIX_GET_LD(buffers[1]);\n\n    double *A = (double *) STARPU_MATRIX_GET_PTR(buffers[2]);\n    int ldA = STARPU_MATRIX_GET_LD(buffers[2]);\n\n    struct starpu_matrix_interface **A_i =\n        (struct starpu_matrix_interface **)buffers + 3;\n\n    // join tiles\n    starneig_join_window(&A_pi, ldA, A_i, A, 0);\n\n    // A <- Y V^T\n    cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans,\n        m, n, nb, -1.0, Y+roffset, ldY, V+coffset+nb-1, ldV, 1.0, A, ldA);\n\n    // split tiles\n    starneig_join_window(&A_pi, ldA, A_i, A, 1);\n\n    STARNEIG_EVENT_END();\n}\n\nvoid starneig_hessenberg_cpu_update_left_a(\n    void *buffers[], void *cl_args)\n{\n    struct packing_info A_pi, W_pi;\n    int nb, offset;\n    starpu_codelet_unpack_args(cl_args, &A_pi, &W_pi, &nb, &offset);\n\n    STARNEIG_EVENT_BEGIN(&A_pi, starneig_event_green);\n\n    int m = A_pi.rend - A_pi.rbegin;\n    int n = A_pi.cend - A_pi.cbegin;\n\n    int k = 0;\n\n    double *V = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);\n    int ldV = STARPU_MATRIX_GET_LD(buffers[k]);\n    k++;\n\n    double *T = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);\n    int ldT = STARPU_MATRIX_GET_LD(buffers[k]);\n    k++;\n\n    double *A = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);\n    int ldA = STARPU_MATRIX_GET_LD(buffers[k]);\n    k++;\n\n    double *W = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);\n    int ldW = STARPU_MATRIX_GET_LD(buffers[k]);\n    k++;\n\n    double *P = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);\n    int ldP = STARPU_MATRIX_GET_LD(buffers[k]);\n    k++;\n\n    struct starpu_matrix_interface **A_i =\n        (struct starpu_matrix_interface **)buffers + k;\n    k += A_pi.handles;\n\n    struct starpu_matrix_interface **W_i =\n        (struct starpu_matrix_interface **)buffers + k;\n    k += W_pi.handles;\n\n    // join A tiles\n    starneig_join_window(&A_pi, ldA, A_i, A, 0);\n\n    // join W tiles\n    starneig_join_window(&W_pi, ldW, W_i, W, 0);\n\n    // P <- A^T * V\n    cblas_dgemm(\n        CblasColMajor, CblasTrans, CblasNoTrans, n, nb, m,\n        1.0, A, ldA, V+offset, ldV, 0.0, P, ldP);\n\n    // P <- P * T\n    cblas_dtrmm(\n        CblasColMajor, CblasRight, CblasUpper, CblasNoTrans,\n        CblasNonUnit, n, nb, 1.0, T, ldT, P, ldP);\n\n    // W <- W + P\n    for (int j = 0; j < nb; j++)\n        cblas_daxpy(n, 1.0, P+j*ldP, 1, W+j*ldW, 1);\n\n    // split W tiles\n    starneig_join_window(&W_pi, ldW, W_i, W, 1);\n\n    STARNEIG_EVENT_END();\n}\n\nvoid starneig_hessenberg_cpu_update_left_b(\n    void *buffers[], void *cl_args)\n{\n    struct packing_info A_pi, W_pi;\n    int nb, offset;\n    starpu_codelet_unpack_args(cl_args, &A_pi, &W_pi, &nb, &offset);\n\n    STARNEIG_EVENT_BEGIN(&packing_info, starneig_event_green);\n\n    int m = A_pi.rend - A_pi.rbegin;\n    int n = A_pi.cend - A_pi.cbegin;\n\n    int k = 0;\n\n    double *V = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);\n    int ldV = STARPU_MATRIX_GET_LD(buffers[k]);\n    k++;\n\n    double *W = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);\n    int ldW = STARPU_MATRIX_GET_LD(buffers[k]);\n    k++;\n\n    double *A = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);\n    int ldA = STARPU_MATRIX_GET_LD(buffers[k]);\n    k++;\n\n    struct starpu_matrix_interface **W_i =\n        (struct starpu_matrix_interface **)buffers + k;\n    k += W_pi.handles;\n\n    struct starpu_matrix_interface **A_i =\n        (struct starpu_matrix_interface **)buffers + k;\n    k += A_pi.handles;\n\n    // join A tiles\n    starneig_join_window(&A_pi, ldA, A_i, A, 0);\n\n    // join W tiles\n    starneig_join_window(&W_pi, ldW, W_i, W, 0);\n\n    //  A <- A - V * W^T\n    cblas_dgemm(\n        CblasColMajor, CblasNoTrans, CblasTrans, m, n,\n        nb, -1.0, V+offset, ldV, W, ldW, 1.0, A, ldA);\n\n    // split A tiles\n    starneig_join_window(&A_pi, ldA, A_i, A, 1);\n\n    STARNEIG_EVENT_END();\n}\n\nvoid starneig_hessenberg_cpu_update_right_a(\n    void *buffers[], void *cl_args)\n{\n    struct packing_info A_pi, W_pi;\n    int nb, offset;\n    starpu_codelet_unpack_args(cl_args, &A_pi, &W_pi, &nb, &offset);\n\n    STARNEIG_EVENT_BEGIN(&packing_info, starneig_event_blue);\n\n    int m = A_pi.rend - A_pi.rbegin;\n    int n = A_pi.cend - A_pi.cbegin;\n\n    int k = 0;\n\n    double *V = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);\n    int ldV = STARPU_MATRIX_GET_LD(buffers[k]);\n    k++;\n\n    double *T = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);\n    int ldT = STARPU_MATRIX_GET_LD(buffers[k]);\n    k++;\n\n    double *A = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);\n    int ldA = STARPU_MATRIX_GET_LD(buffers[k]);\n    k++;\n\n    double *W = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);\n    int ldW = STARPU_MATRIX_GET_LD(buffers[k]);\n    k++;\n\n    double *P = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);\n    int ldP = STARPU_MATRIX_GET_LD(buffers[k]);\n    k++;\n\n    struct starpu_matrix_interface **A_i =\n        (struct starpu_matrix_interface **)buffers + k;\n    k += A_pi.handles;\n\n    struct starpu_matrix_interface **W_i =\n        (struct starpu_matrix_interface **)buffers + k;\n    k += W_pi.handles;\n\n    // join A tiles\n    starneig_join_window(&A_pi, ldA, A_i, A, 0);\n\n    // join W tiles\n    starneig_join_window(&W_pi, ldW, W_i, W, 0);\n\n    // P <- A * V\n    cblas_dgemm(\n        CblasColMajor, CblasNoTrans, CblasNoTrans, m, nb, n,\n        1.0, A, ldA, V+offset, ldV, 0.0, P, ldP);\n\n    // P <- P * T\n    cblas_dtrmm(\n        CblasColMajor, CblasRight, CblasUpper, CblasNoTrans,\n        CblasNonUnit, m, nb, 1.0, T, ldT, P, ldP);\n\n    // W <- W + P\n    for (int j = 0; j < nb; j++)\n        cblas_daxpy(m, 1.0, P+j*ldP, 1, W+j*ldW, 1);\n\n    // split W tiles\n    starneig_join_window(&W_pi, ldW, W_i, W, 1);\n\n    STARNEIG_EVENT_END();\n}\n\nvoid starneig_hessenberg_cpu_update_right_b(\n    void *buffers[], void *cl_args)\n{\n    struct packing_info A_pi, W_pi;\n    int nb, offset;\n    starpu_codelet_unpack_args(cl_args, &A_pi, &W_pi, &nb, &offset);\n\n    STARNEIG_EVENT_BEGIN(&packing_info, starneig_event_blue);\n\n    int m = A_pi.rend - A_pi.rbegin;\n    int n = A_pi.cend - A_pi.cbegin;\n\n    int k = 0;\n\n    double *V = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);\n    int ldV = STARPU_MATRIX_GET_LD(buffers[k]);\n    k++;\n\n    double *W = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);\n    int ldW = STARPU_MATRIX_GET_LD(buffers[k]);\n    k++;\n\n    double *A = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);\n    int ldA = STARPU_MATRIX_GET_LD(buffers[k]);\n    k++;\n\n    struct starpu_matrix_interface **W_i =\n        (struct starpu_matrix_interface **)buffers + k;\n    k += W_pi.handles;\n\n    struct starpu_matrix_interface **A_i =\n        (struct starpu_matrix_interface **)buffers + k;\n    k += A_pi.handles;\n\n    // join A tiles\n    starneig_join_window(&A_pi, ldA, A_i, A, 0);\n\n    // join W tiles\n    starneig_join_window(&W_pi, ldW, W_i, W, 0);\n\n    //  A <- A - W * V\n    cblas_dgemm(\n        CblasColMajor, CblasNoTrans, CblasTrans, m, n,\n        nb, -1.0, W, ldW, V+offset, ldV, 1.0, A, ldA);\n\n    // split A tiles\n    starneig_join_window(&A_pi, ldA, A_i, A, 1);\n\n    STARNEIG_EVENT_END();\n}\n", "meta": {"hexsha": "0d7e9dee5e25ab3bc50d76a8583f333e667f510f", "size": 15938, "ext": "c", "lang": "C", "max_stars_repo_path": "src/hessenberg/cpu.c", "max_stars_repo_name": "NLAFET/StarNEig", "max_stars_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2019-04-28T17:13:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-24T12:30:19.000Z", "max_issues_repo_path": "src/hessenberg/cpu.c", "max_issues_repo_name": "NLAFET/StarNEig", "max_issues_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/hessenberg/cpu.c", "max_forks_repo_name": "NLAFET/StarNEig", "max_forks_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-04-30T12:14:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-14T09:41:23.000Z", "avg_line_length": 28.4099821747, "max_line_length": 80, "alphanum_fraction": 0.6213452127, "num_tokens": 4965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.032589743826428076, "lm_q1q2_score": 0.016040285257547943}}
{"text": "#ifndef DATA_H\n#define DATA_H\n\n#include <gsl/gsl_vector.h>\n\ntypedef struct {\n  int imageIdx;\n  int labelerId;\n  int workflowId;\n  int workerPoolId;\n  int label;\n  double trueLabel;\n  double trueDifficulty;\n} Label;\n\ntypedef struct {\n  Label *labels;\n  int numLabels;\n  int numLabelers;\n  int numImages;\n  int numWorkflows;\n  int numWorkerPools;\n  double *priorAlpha;\n  double *priorBeta;\n  double *probZ1, *probZ0;\n  double *alpha, *beta;\n  double *priorZ1;\n} Dataset;\n\nvoid packX (gsl_vector *x, Dataset *data);\nvoid unpackX (const gsl_vector *x, Dataset *data);\nvoid readData (char *filename, Dataset *data, double*, double);\nvoid outputResults (Dataset *data);\n\n#endif\n", "meta": {"hexsha": "a6d190696c01a4ee5a364f586e51b12a901d991b", "size": 672, "ext": "h", "lang": "C", "max_stars_repo_path": "EM/data.h", "max_stars_repo_name": "ShreyaR/WorkerPoolSelection", "max_stars_repo_head_hexsha": "03e0bfeda422975c118efe91fe31045f9c27f002", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "EM/data.h", "max_issues_repo_name": "ShreyaR/WorkerPoolSelection", "max_issues_repo_head_hexsha": "03e0bfeda422975c118efe91fe31045f9c27f002", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "EM/data.h", "max_forks_repo_name": "ShreyaR/WorkerPoolSelection", "max_forks_repo_head_hexsha": "03e0bfeda422975c118efe91fe31045f9c27f002", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-02-25T18:59:03.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-25T18:59:03.000Z", "avg_line_length": 18.6666666667, "max_line_length": 63, "alphanum_fraction": 0.7202380952, "num_tokens": 192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4416730203630095, "lm_q2_score": 0.03622005872592178, "lm_q1q2_score": 0.01599742273520345}}
{"text": "#pragma once\n\n#include \"detail.h\"\n#include \"schedule.h\"\n#include <gsl/gsl-lite.hpp>\n#include <vector>\n#ifndef UNIT_TEST\n#include \"random_utils.h\"\n#include \"temperature.h\"\n#include \"utils.h\"\n#else // UNIT_TEST\n#include \"stub/random_utils.h\"\n#include \"stub/temperature.h\"\n#include \"stub/utils.h\"\n#endif // UNIT_TEST\n\nnamespace angonoka::stun {\n\nstruct ScheduleParams;\n/**\n    Stochastic tunneling algorithm.\n\n    The internal schedule can be updated as many times as\n    needed.\n*/\nclass StochasticTunneling {\npublic:\n    /**\n        STUN auxiliary data and utilities.\n\n        @var mutator    Instance of Mutator\n        @var random     Instance of RandomUtils\n        @var makespan   Instance of Makespan\n        @var temp       Instance of Temperature\n        @var gamma      Tunneling parameter\n    */\n    struct Options {\n        gsl::not_null<const Mutator*> mutator;\n        gsl::not_null<RandomUtils*> random;\n        gsl::not_null<Makespan*> makespan;\n        gsl::not_null<Temperature*> temp;\n        float gamma;\n    };\n\n    /**\n        Default constructor.\n\n        The object will be in an uninitialized state. User must call\n        reset to set the initial schedule.\n\n        @param options Instance of StochasticTunneling::Options\n    */\n    StochasticTunneling(const Options& options);\n\n    /**\n        Constructor.\n\n        @param options  Instance of StochasticTunneling::Options\n        @param schedule Initial schedule\n    */\n    StochasticTunneling(const Options& options, Schedule schedule);\n\n    StochasticTunneling(const StochasticTunneling& other);\n    StochasticTunneling(StochasticTunneling&& other) noexcept;\n    StochasticTunneling& operator=(const StochasticTunneling& other);\n    StochasticTunneling&\n    operator=(StochasticTunneling&& other) noexcept;\n    ~StochasticTunneling() noexcept;\n\n    /**\n        Reset stochastic tunneling algorithm to a new\n        schedule.\n\n        @param schedule Initial schedule\n    */\n    void reset(Schedule schedule);\n\n    /**\n        Set stochastic tunneling options.\n\n        @param options Instance of Options\n    */\n    void options(const Options& options);\n\n    /**\n        Get stochastic tunneling options.\n\n        @return Stochastic tunneling options.\n    */\n    [[nodiscard]] Options options() const;\n\n    /**\n        Update the internal state according to stochastic\n        tunneling algorithm.\n    */\n    void update() noexcept;\n\n    /**\n        The best schedule so far.\n\n        @return A schedule.\n    */\n    [[nodiscard]] Schedule schedule() const;\n\n    /**\n        The best makespan so far.\n\n        @return Makespan.\n    */\n    [[nodiscard]] float normalized_makespan() const;\n\nprivate:\n    struct Impl;\n\n    using index = MutSchedule::index_type;\n\n    gsl::not_null<const Mutator*> mutator;\n    gsl::not_null<RandomUtils*> random;\n    gsl::not_null<Makespan*> makespan;\n    gsl::not_null<Temperature*> temp;\n\n    std::vector<ScheduleItem> schedule_buffer;\n    MutSchedule best_schedule;\n    MutSchedule current_schedule;\n    MutSchedule target_schedule;\n\n    float current_e;\n    float lowest_e;\n    float target_e;\n\n    float gamma;\n    float current_s;\n    float target_s;\n};\n\n} // namespace angonoka::stun\n", "meta": {"hexsha": "d86207b61165d4dd81169588fb7455ef46347946", "size": 3196, "ext": "h", "lang": "C", "max_stars_repo_path": "src/stun/stochastic_tunneling.h", "max_stars_repo_name": "coffee-lord/angonoka", "max_stars_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-10-23T18:05:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T21:53:24.000Z", "max_issues_repo_path": "src/stun/stochastic_tunneling.h", "max_issues_repo_name": "coffee-lord/angonoka", "max_issues_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2022-02-12T19:52:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-12T19:55:52.000Z", "max_forks_repo_path": "src/stun/stochastic_tunneling.h", "max_forks_repo_name": "coffee-lord/angonoka", "max_forks_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3284671533, "max_line_length": 69, "alphanum_fraction": 0.6598873592, "num_tokens": 713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.03410042423988668, "lm_q1q2_score": 0.015985959247637228}}
{"text": "#ifndef _AVA_COMMON_SUPPORT_GEN_STAT_H_\n#define _AVA_COMMON_SUPPORT_GEN_STAT_H_\n\n#include <fmt/format.h>\n#include <stdint.h>\n\n#include <gsl/gsl>\n\n#include \"common/extensions/cmd_batching.h\"\n#include \"common/support/io.h\"\n#include \"guestlib/guest_thread.h\"\n#include \"time_util.h\"\n\nnamespace ava {\nnamespace support {\n\ninline void stats_end(const char *func_name, int64_t begin_ts) {\n  auto end_ts = ava::GetMonotonicNanoTimestamp();\n  fmt::memory_buffer output;\n  fmt::format_to(output, \"GuestlibStat {}, {}\\n\", func_name, gsl::narrow_cast<int32_t>(end_ts - begin_ts));\n  ava::guest_write_stats(output.data(), output.size());\n}\n\n}  // namespace support\n}  // namespace ava\n\n#endif  // _AVA_COMMON_SUPPORT_GEN_STAT_H_\n", "meta": {"hexsha": "2f116aee19250670979381d1e75bdbaec8d37942", "size": 716, "ext": "h", "lang": "C", "max_stars_repo_path": "common/support/gen_stat.h", "max_stars_repo_name": "photoszzt/ava", "max_stars_repo_head_hexsha": "a5905414c5234784fda3ca061d26f855f9fbd1d4", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2020-01-31T21:25:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-03T23:48:14.000Z", "max_issues_repo_path": "common/support/gen_stat.h", "max_issues_repo_name": "photoszzt/ava", "max_issues_repo_head_hexsha": "a5905414c5234784fda3ca061d26f855f9fbd1d4", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 81.0, "max_issues_repo_issues_event_min_datetime": "2020-03-16T02:47:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-14T12:22:47.000Z", "max_forks_repo_path": "common/support/gen_stat.h", "max_forks_repo_name": "photoszzt/ava", "max_forks_repo_head_hexsha": "a5905414c5234784fda3ca061d26f855f9fbd1d4", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2020-01-31T21:25:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-18T03:35:13.000Z", "avg_line_length": 25.5714285714, "max_line_length": 107, "alphanum_fraction": 0.7555865922, "num_tokens": 180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2200070895174993, "lm_q2_score": 0.0726367028476572, "lm_q1q2_score": 0.015980589585660517}}
{"text": "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\n#pragma once\n\n#include <gsl/gsl>\n\n#include \"core/framework/tensor.h\"\n#include \"core/util/math_cpuonly.h\"\n\nnamespace onnxruntime {\n\ntemplate <typename T>\nauto EigenMap(Tensor& t) -> EigenVectorMap<T> {\n  return EigenVectorMap<T>(t.template MutableData<T>(), gsl::narrow<ptrdiff_t>(t.Shape().Size()));\n}\n\ntemplate <typename T>\nauto EigenMap(const Tensor& t) -> ConstEigenVectorMap<T> {\n  return ConstEigenVectorMap<T>(t.template Data<T>(), gsl::narrow<ptrdiff_t>(t.Shape().Size()));\n}\n\n}  // namespace onnxruntime\n", "meta": {"hexsha": "609c2de118d637cdf9dbedf77d8b889d11b583aa", "size": 609, "ext": "h", "lang": "C", "max_stars_repo_path": "onnxruntime/core/framework/math.h", "max_stars_repo_name": "SiriusKY/onnxruntime", "max_stars_repo_head_hexsha": "3c5853dcbc9d5dda2476afa8c6105802d2b8e53d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 669.0, "max_stars_repo_stars_event_min_datetime": "2018-12-03T22:00:31.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-06T19:42:49.000Z", "max_issues_repo_path": "onnxruntime/core/framework/math.h", "max_issues_repo_name": "SiriusKY/onnxruntime", "max_issues_repo_head_hexsha": "3c5853dcbc9d5dda2476afa8c6105802d2b8e53d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 440.0, "max_issues_repo_issues_event_min_datetime": "2018-12-03T21:09:56.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-06T20:47:23.000Z", "max_forks_repo_path": "onnxruntime/core/framework/math.h", "max_forks_repo_name": "SiriusKY/onnxruntime", "max_forks_repo_head_hexsha": "3c5853dcbc9d5dda2476afa8c6105802d2b8e53d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 140.0, "max_forks_repo_forks_event_min_datetime": "2018-12-03T21:15:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-06T18:02:36.000Z", "avg_line_length": 25.375, "max_line_length": 98, "alphanum_fraction": 0.724137931, "num_tokens": 154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3738758227716966, "lm_q2_score": 0.04272219343295328, "lm_q1q2_score": 0.015972795220356984}}
{"text": "/***************************************************************************\n    File                 : FrequencyCountDialog.h\n    Project              : QtiPlot\n    --------------------------------------------------------------------\n    Copyright            : (C) 2008 by Ion Vasilief\n    Email (use @ for *)  : ion_vasilief*yahoo.fr\n    Description          : Frequency count options dialog\n\n ***************************************************************************/\n\n/***************************************************************************\n *                                                                         *\n *  This program is free software; you can redistribute it and/or modify   *\n *  it under the terms of the GNU General Public License as published by   *\n *  the Free Software Foundation; either version 2 of the License, or      *\n *  (at your option) any later version.                                    *\n *                                                                         *\n *  This program is distributed in the hope that it will be useful,        *\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of         *\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the          *\n *  GNU General Public License for more details.                           *\n *                                                                         *\n *   You should have received a copy of the GNU General Public License     *\n *   along with this program; if not, write to the Free Software           *\n *   Foundation, Inc., 51 Franklin Street, Fifth Floor,                    *\n *   Boston, MA  02110-1301  USA                                           *\n *                                                                         *\n ***************************************************************************/\n#ifndef FREQUENCYCOUNTDIALOG_H\n#define FREQUENCYCOUNTDIALOG_H\n\n#include <QDialog>\n#include <gsl/gsl_vector.h>\r\n\nclass QPushButton;\nclass DoubleSpinBox;\r\nclass Table;\n\n//! Filter options dialog\nclass FrequencyCountDialog : public QDialog\n{\n    Q_OBJECT\n\npublic:\n    FrequencyCountDialog(Table *t, QWidget* parent = 0, Qt::WFlags fl = 0 );\n    ~FrequencyCountDialog();\r\n\nprivate slots:\r\n    bool apply();\r\n    void accept();\n\nprivate:\r\n    Table *d_source_table;\r\n    Table *d_result_table;\r\n    QString d_col_name;\r\n    gsl_vector *d_col_values;\n\tint d_bins;\r\n\n    QPushButton* buttonApply;\n\tQPushButton* buttonCancel;\r\n\tQPushButton* buttonOk;\n\tDoubleSpinBox* boxStart;\n\tDoubleSpinBox* boxEnd;\r\n\tDoubleSpinBox* boxStep;\n};\n\n#endif\n", "meta": {"hexsha": "88424231156bc2e2df073b2c778fc1081ed57dad", "size": 2591, "ext": "h", "lang": "C", "max_stars_repo_path": "thirdparty/qtiplot/qtiplot/src/analysis/dialogs/FrequencyCountDialog.h", "max_stars_repo_name": "hoehnp/SpaceDesignTool", "max_stars_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_stars_repo_licenses": ["IJG"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-09-05T12:41:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T05:34:23.000Z", "max_issues_repo_path": "thirdparty/qtiplot/qtiplot/src/analysis/dialogs/FrequencyCountDialog.h", "max_issues_repo_name": "hoehnp/SpaceDesignTool", "max_issues_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_issues_repo_licenses": ["IJG"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-02-07T19:09:21.000Z", "max_issues_repo_issues_event_max_datetime": "2015-08-14T03:15:42.000Z", "max_forks_repo_path": "thirdparty/qtiplot/qtiplot/src/analysis/dialogs/FrequencyCountDialog.h", "max_forks_repo_name": "hoehnp/SpaceDesignTool", "max_forks_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_forks_repo_licenses": ["IJG"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-03-25T15:50:31.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-06T12:16:47.000Z", "avg_line_length": 38.1029411765, "max_line_length": 77, "alphanum_fraction": 0.4658433037, "num_tokens": 446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681662740417, "lm_q2_score": 0.040237943199081735, "lm_q1q2_score": 0.01593696837749935}}
{"text": "/* multiset/gsl_multiset.h\r\n * based on combination/gsl_combination.h by Szymon Jaroszewicz\r\n * based on permutation/gsl_permutation.h by Brian Gough\r\n *\r\n * Copyright (C) 2009 Rhys Ulerich\r\n *\r\n * This program is free software; you can redistribute it and/or modify\r\n * it under the terms of the GNU General Public License as published by\r\n * the Free Software Foundation; either version 3 of the License, or (at\r\n * your option) any later version.\r\n *\r\n * This program is distributed in the hope that it will be useful, but\r\n * WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n * General Public License for more details.\r\n *\r\n * You should have received a copy of the GNU General Public License\r\n * along with this program; if not, write to the Free Software\r\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r\n */\r\n\r\n#ifndef __GSL_MULTISET_H__\r\n#define __GSL_MULTISET_H__\r\n\r\n#if !defined( GSL_FUN )\r\n#  if !defined( GSL_DLL )\r\n#    define GSL_FUN extern\r\n#  elif defined( BUILD_GSL_DLL )\r\n#    define GSL_FUN extern __declspec(dllexport)\r\n#  else\r\n#    define GSL_FUN extern __declspec(dllimport)\r\n#  endif\r\n#endif\r\n\r\n#include <stdlib.h>\r\n#include <gsl/gsl_errno.h>\r\n#include <gsl/gsl_types.h>\r\n#include <gsl/gsl_inline.h>\r\n#include <gsl/gsl_check_range.h>\r\n\r\n#undef __BEGIN_DECLS\r\n#undef __END_DECLS\r\n#ifdef __cplusplus\r\n# define __BEGIN_DECLS extern \"C\" {\r\n# define __END_DECLS }\r\n#else\r\n# define __BEGIN_DECLS /* empty */\r\n# define __END_DECLS /* empty */\r\n#endif\r\n\r\n__BEGIN_DECLS\r\n\r\nstruct gsl_multiset_struct\r\n{\r\n  size_t n;\r\n  size_t k;\r\n  size_t *data;\r\n};\r\n\r\ntypedef struct gsl_multiset_struct gsl_multiset;\r\n\r\nGSL_FUN gsl_multiset *gsl_multiset_alloc (const size_t n, const size_t k);\r\nGSL_FUN gsl_multiset *gsl_multiset_calloc (const size_t n, const size_t k);\r\nGSL_FUN void gsl_multiset_init_first (gsl_multiset * c);\r\nGSL_FUN void gsl_multiset_init_last (gsl_multiset * c);\r\nGSL_FUN void gsl_multiset_free (gsl_multiset * c);\r\nGSL_FUN int gsl_multiset_memcpy (gsl_multiset * dest, const gsl_multiset * src);\r\n\r\nGSL_FUN int gsl_multiset_fread (FILE * stream, gsl_multiset * c);\r\nGSL_FUN int gsl_multiset_fwrite (FILE * stream, const gsl_multiset * c);\r\nGSL_FUN int gsl_multiset_fscanf (FILE * stream, gsl_multiset * c);\r\nGSL_FUN int gsl_multiset_fprintf (FILE * stream, const gsl_multiset * c, const char *format);\r\n\r\nGSL_FUN size_t gsl_multiset_n (const gsl_multiset * c);\r\nGSL_FUN size_t gsl_multiset_k (const gsl_multiset * c);\r\nGSL_FUN size_t * gsl_multiset_data (const gsl_multiset * c);\r\n\r\nGSL_FUN int gsl_multiset_valid (gsl_multiset * c);\r\nGSL_FUN int gsl_multiset_next (gsl_multiset * c);\r\nGSL_FUN int gsl_multiset_prev (gsl_multiset * c);\r\n\r\nGSL_FUN INLINE_DECL size_t gsl_multiset_get (const gsl_multiset * c, const size_t i);\r\n\r\n#ifdef HAVE_INLINE\r\n\r\nINLINE_FUN\r\nsize_t\r\ngsl_multiset_get (const gsl_multiset * c, const size_t i)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(i >= c->k)) /* size_t is unsigned, can't be negative */\r\n    {\r\n      GSL_ERROR_VAL (\"index out of range\", GSL_EINVAL, 0);\r\n    }\r\n#endif\r\n  return c->data[i];\r\n}\r\n\r\n#endif /* HAVE_INLINE */\r\n\r\n__END_DECLS\r\n\r\n#endif /* __GSL_MULTISET_H__ */\r\n", "meta": {"hexsha": "f77cd1646d578ec9e2f4422092bb2f33fb4959c4", "size": 3256, "ext": "h", "lang": "C", "max_stars_repo_path": "vendor/gsl/gsl/gsl_multiset.h", "max_stars_repo_name": "mgreter/astrometrylib", "max_stars_repo_head_hexsha": "ef4d4539a537ab49329b77648aac893d2b4ad318", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z", "max_issues_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_multiset.h", "max_issues_repo_name": "zzpwahaha/VimbaCamJILA", "max_issues_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z", "max_forks_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_multiset.h", "max_forks_repo_name": "zzpwahaha/VimbaCamJILA", "max_forks_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 31.3076923077, "max_line_length": 94, "alphanum_fraction": 0.734029484, "num_tokens": 871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3208212878370535, "lm_q2_score": 0.04958902456418653, "lm_q1q2_score": 0.015909214723265605}}
{"text": "/* spio.c\n * \n * Copyright (C) 2016 Patrick Alken\n * Copyright (C) 2016 Alexis Tantet\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <stdlib.h>\n#include <math.h>\n\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_spmatrix.h>\n\n/*\ngsl_spmatrix_fprintf()\n  Print sparse matrix to file in MatrixMarket format:\n\nM  N  NNZ\nI1 J1 A(I1,J1)\n...\n\nNote that indices start at 1 and not 0\n*/\n\nint\ngsl_spmatrix_fprintf(FILE *stream, const gsl_spmatrix *m,\n                     const char *format)\n{\n  int status;\n\n  /* print header */\n  status = fprintf(stream, \"%%%%MatrixMarket matrix coordinate real general\\n\");\n  if (status < 0)\n    {\n      GSL_ERROR(\"fprintf failed for header\", GSL_EFAILED);\n    }\n\n  /* print rows,columns,nnz */\n  status = fprintf(stream, \"%u\\t%u\\t%u\\n\",\n                   (unsigned int) m->size1,\n                   (unsigned int) m->size2,\n                   (unsigned int) m->nz);\n  if (status < 0)\n    {\n      GSL_ERROR(\"fprintf failed for dimension header\", GSL_EFAILED);\n    }\n\n  if (GSL_SPMATRIX_ISTRIPLET(m))\n    {\n      size_t n;\n\n      for (n = 0; n < m->nz; ++n)\n        {\n          status = fprintf(stream, \"%u\\t%u\\t\", (unsigned int) m->i[n] + 1, (unsigned int) m->p[n] + 1);\n          if (status < 0)\n            {\n              GSL_ERROR(\"fprintf failed\", GSL_EFAILED);\n            }\n\n          status = fprintf(stream, format, m->data[n]);\n          if (status < 0)\n            {\n              GSL_ERROR(\"fprintf failed\", GSL_EFAILED);\n            }\n\n          status = putc('\\n', stream);\n          if (status == EOF)\n            {\n              GSL_ERROR(\"putc failed\", GSL_EFAILED);\n            }\n        }\n    }\n  else if (GSL_SPMATRIX_ISCCS(m))\n    {\n      size_t j, p;\n\n      for (j = 0; j < m->size2; ++j)\n        {\n          for (p = m->p[j]; p < m->p[j + 1]; ++p)\n            {\n              status = fprintf(stream, \"%u\\t%u\\t\", (unsigned int) m->i[p] + 1, (unsigned int) j + 1);\n              if (status < 0)\n                {\n                  GSL_ERROR(\"fprintf failed\", GSL_EFAILED);\n                }\n\n              status = fprintf(stream, format, m->data[p]);\n              if (status < 0)\n                {\n                  GSL_ERROR(\"fprintf failed\", GSL_EFAILED);\n                }\n\n              status = putc('\\n', stream);\n              if (status == EOF)\n                {\n                  GSL_ERROR(\"putc failed\", GSL_EFAILED);\n                }\n            }\n        }\n    }\n  else if (GSL_SPMATRIX_ISCRS(m))\n    {\n      size_t i, p;\n\n      for (i = 0; i < m->size1; ++i)\n        {\n          for (p = m->p[i]; p < m->p[i + 1]; ++p)\n            {\n              status = fprintf(stream, \"%u\\t%u\\t\", (unsigned int) i + 1, (unsigned int) m->i[p] + 1);\n              if (status < 0)\n                {\n                  GSL_ERROR(\"fprintf failed\", GSL_EFAILED);\n                }\n\n              status = fprintf(stream, format, m->data[p]);\n              if (status < 0)\n                {\n                  GSL_ERROR(\"fprintf failed\", GSL_EFAILED);\n                }\n\n              status = putc('\\n', stream);\n              if (status == EOF)\n                {\n                  GSL_ERROR(\"putc failed\", GSL_EFAILED);\n                }\n            }\n        }\n    }\n  else\n    {\n      GSL_ERROR(\"unknown sparse matrix type\", GSL_EINVAL);\n    }\n\n  return GSL_SUCCESS;\n}\n\ngsl_spmatrix *\ngsl_spmatrix_fscanf(FILE *stream)\n{\n  gsl_spmatrix *m;\n  unsigned int size1, size2, nz;\n  char buf[1024];\n  int found_header = 0;\n\n  /* read file until we find rows,cols,nz header */\n  while (fgets(buf, 1024, stream) != NULL)\n    {\n      int c;\n\n      /* skip comments */\n      if (*buf == '%')\n        continue;\n\n      c = sscanf(buf, \"%u %u %u\",\n                 &size1, &size2, &nz);\n      if (c == 3)\n        {\n          found_header = 1;\n          break;\n        }\n    }\n\n  if (!found_header)\n    {\n      GSL_ERROR_NULL (\"fscanf failed reading header\", GSL_EFAILED);\n    }\n\n  m = gsl_spmatrix_alloc_nzmax((size_t) size1, (size_t) size2, (size_t) nz, GSL_SPMATRIX_TRIPLET);\n  if (!m)\n    {\n      GSL_ERROR_NULL (\"error allocating m\", GSL_ENOMEM);\n    }\n\n  {\n    unsigned int i, j;\n    double val;\n\n    while (fgets(buf, 1024, stream) != NULL)\n      {\n        int c = sscanf(buf, \"%u %u %lg\", &i, &j, &val);\n        if (c < 3 || (i == 0) || (j == 0))\n          {\n            GSL_ERROR_NULL (\"error in input file format\", GSL_EFAILED);\n          }\n        else if ((i > size1) || (j > size2))\n          {\n            GSL_ERROR_NULL (\"element exceeds matrix dimensions\", GSL_EBADLEN);\n          }\n        else\n          {\n            /* subtract 1 from (i,j) since indexing starts at 1 */\n            gsl_spmatrix_set(m, i - 1, j - 1, val);\n          }\n      }\n  }\n\n  return m;\n}\n\nint\ngsl_spmatrix_fwrite(FILE *stream, const gsl_spmatrix *m)\n{\n  size_t items;\n\n  /* write header: size1, size2, nz */\n\n  items = fwrite(&(m->size1), sizeof(size_t), 1, stream);\n  if (items != 1)\n    {\n      GSL_ERROR(\"fwrite failed on size1\", GSL_EFAILED);\n    }\n\n  items = fwrite(&(m->size2), sizeof(size_t), 1, stream);\n  if (items != 1)\n    {\n      GSL_ERROR(\"fwrite failed on size2\", GSL_EFAILED);\n    }\n\n  items = fwrite(&(m->nz), sizeof(size_t), 1, stream);\n  if (items != 1)\n    {\n      GSL_ERROR(\"fwrite failed on nz\", GSL_EFAILED);\n    }\n\n  /* write m->i and m->data which are size nz in all storage formats */\n\n  items = fwrite(m->i, sizeof(size_t), m->nz, stream);\n  if (items != m->nz)\n    {\n      GSL_ERROR(\"fwrite failed on row indices\", GSL_EFAILED);\n    }\n\n  items = fwrite(m->data, sizeof(double), m->nz, stream);\n  if (items != m->nz)\n    {\n      GSL_ERROR(\"fwrite failed on data\", GSL_EFAILED);\n    }\n\n  if (GSL_SPMATRIX_ISTRIPLET(m))\n    {\n      items = fwrite(m->p, sizeof(size_t), m->nz, stream);\n      if (items != m->nz)\n        {\n          GSL_ERROR(\"fwrite failed on column indices\", GSL_EFAILED);\n        }\n    }\n  else if (GSL_SPMATRIX_ISCCS(m))\n    {\n      items = fwrite(m->p, sizeof(size_t), m->size2 + 1, stream);\n      if (items != m->size2 + 1)\n        {\n          GSL_ERROR(\"fwrite failed on column indices\", GSL_EFAILED);\n        }\n    }\n  else if (GSL_SPMATRIX_ISCRS(m))\n    {\n      items = fwrite(m->p, sizeof(size_t), m->size1 + 1, stream);\n      if (items != m->size1 + 1)\n        {\n          GSL_ERROR(\"fwrite failed on column indices\", GSL_EFAILED);\n        }\n    }\n\n  return GSL_SUCCESS;\n}\n\nint\ngsl_spmatrix_fread(FILE *stream, gsl_spmatrix *m)\n{\n  size_t size1, size2, nz;\n  size_t items;\n\n  /* read header: size1, size2, nz */\n\n  items = fread(&size1, sizeof(size_t), 1, stream);\n  if (items != 1)\n    {\n      GSL_ERROR(\"fread failed on size1\", GSL_EFAILED);\n    }\n\n  items = fread(&size2, sizeof(size_t), 1, stream);\n  if (items != 1)\n    {\n      GSL_ERROR(\"fread failed on size2\", GSL_EFAILED);\n    }\n\n  items = fread(&nz, sizeof(size_t), 1, stream);\n  if (items != 1)\n    {\n      GSL_ERROR(\"fread failed on nz\", GSL_EFAILED);\n    }\n\n  if (m->size1 != size1)\n    {\n      GSL_ERROR(\"matrix has wrong size1\", GSL_EBADLEN);\n    }\n  else if (m->size2 != size2)\n    {\n      GSL_ERROR(\"matrix has wrong size2\", GSL_EBADLEN);\n    }\n  else if (nz > m->nzmax)\n    {\n      GSL_ERROR(\"matrix nzmax is too small\", GSL_EBADLEN);\n    }\n  else\n    {\n      /* read m->i and m->data arrays, which are size nz for all formats */\n\n      items = fread(m->i, sizeof(size_t), nz, stream);\n      if (items != nz)\n        {\n          GSL_ERROR(\"fread failed on row indices\", GSL_EFAILED);\n        }\n\n      items = fread(m->data, sizeof(double), nz, stream);\n      if (items != nz)\n        {\n          GSL_ERROR(\"fread failed on data\", GSL_EFAILED);\n        }\n\n      m->nz = nz;\n\n      if (GSL_SPMATRIX_ISTRIPLET(m))\n        {\n          items = fread(m->p, sizeof(size_t), nz, stream);\n          if (items != nz)\n            {\n              GSL_ERROR(\"fread failed on column indices\", GSL_EFAILED);\n            }\n\n          /* build binary search tree for m */\n          gsl_spmatrix_tree_rebuild(m);\n        }\n      else if (GSL_SPMATRIX_ISCCS(m))\n        {\n          items = fread(m->p, sizeof(size_t), size2 + 1, stream);\n          if (items != size2 + 1)\n            {\n              GSL_ERROR(\"fread failed on row pointers\", GSL_EFAILED);\n            }\n        }\n      else if (GSL_SPMATRIX_ISCRS(m))\n        {\n          items = fread(m->p, sizeof(size_t), size1 + 1, stream);\n          if (items != size1 + 1)\n            {\n              GSL_ERROR(\"fread failed on column pointers\", GSL_EFAILED);\n            }\n        }\n    }\n\n  return GSL_SUCCESS;\n}\n", "meta": {"hexsha": "a276ec0a884e647aa5565f295e70dccf1aa4e1d4", "size": 9228, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.4/spmatrix/spio.c", "max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-13T05:01:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-13T05:01:59.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/spmatrix/spio.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/spmatrix/spio.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0081300813, "max_line_length": 103, "alphanum_fraction": 0.5212397052, "num_tokens": 2571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.320821300824607, "lm_q2_score": 0.04958902105273151, "lm_q1q2_score": 0.015909214240756146}}
{"text": "//        Copyright The Authors 2018.\n//    Distributed under the 3-Clause BSD License.\n//    (See accompanying file LICENSE or copy at\n//   https://opensource.org/licenses/BSD-3-Clause)\n\n#pragma once\n\n#include <array>     // for std::array\n#include <bitset>    // for std::bitset\n#include <cstdint>   // for standard int types\n#include <cstring>   // for std::memcpy\n#include <iosfwd>    // for implementation of operator<<\n#include <iterator>  // for std::reverse_iterator\n#include <string>    // for std::string\n\n#include <gsl/gsl>  // for gsl::span\n\n#include <codec/base16.h>   // for hex enc/decoding\n#include <common/assert.h>  // for assertions\n#include <crypto/random.h>  // for random block generation\n\nnamespace blocxxi {\nnamespace crypto {\n\nnamespace detail {\n/// Forward declarations for utility conversion function between host and\n/// network (big endian) byte orders.\n/// Avoid including header files of boost and pulling all its bloat here.\nstd::uint32_t HostToNetwork(std::uint32_t);\nstd::uint32_t NetworkToHost(std::uint32_t);\n\n/// Count the number of leading zero bits in a buffer of contiguous 32-bit\n/// integers.\nint CountLeadingZeroBits(gsl::span<std::uint32_t const> buf);\n\n}  // namespace detail\n\n/*!\n   Represents a N bits hash digest or any other kind of N bits sequence.\n   The structure is 32-bit aligned and must be at least 32-bits wide. It\n   has almost the same semantics of std::array<> except that it will never be\n   zero-length (size() is always > 0). It offers a number of additional\n   convenience methods, such as bitwise arithemtics, comparisons etc.\n */\ntemplate <unsigned int BITS>\nclass Hash {\n  static_assert(BITS % 32 == 0, \"Hash size in bits must be a multiple of 32\");\n  static_assert(BITS > 0, \"Hash size in bits must be greater than 0\");\n\n public:\n  using value_type = std::uint8_t;\n  using pointer = uint8_t *;\n  using const_pointer = std::uint8_t const *;\n  using size_type = std::size_t;\n  using difference_type = std::ptrdiff_t;\n  using reference = std::uint8_t &;\n  using const_reference = std::uint8_t const &;\n  using iterator = pointer;\n  using const_iterator = const_pointer;\n  using reverse_iterator = std::reverse_iterator<iterator>;\n  using const_reverse_iterator = std::reverse_iterator<const_iterator>;\n\n  ///@name Constructors and Factory methods\n  //@{\n  /// Initializes the hash with all '0' bits\n  Hash() : storage_({}) {}\n\n  Hash(const Hash &other) = default;\n\n  Hash &operator=(const Hash &rhs) = default;\n\n  Hash(Hash &&) noexcept = default;\n\n  Hash &operator=(Hash &&rhs) noexcept = default;\n\n  virtual ~Hash() = default;\n\n  /*!\n  \\brief Construct a Hash by assigning content from the provided sequence of\n  bytes.\n\n  > The source sequence can be smaller than the hash size but it __cannot be\n  > bigger__.\n\n  In the case it is smaller, the hash will be padded (leading bytes)\n  with 0. The last byte in the source sequence will be the LSB of the hash\n  (last byte in the hash).\n\n  In the case it is bigger, result is undefined and, if assertions are enabled,\n  this would be considered as a fatal error.\n\n  \\param buf source sequence of bytes.\n  */\n  explicit Hash(gsl::span<std::uint8_t const> buf) noexcept : storage_({}) {\n    auto src_size = buf.size();\n    ASAP_ASSERT_PRECOND(src_size <= Size());\n    auto start = begin();\n    if (Size() > src_size) {\n      // Pad with zeros and adjust the start\n      std::memset(Data(), 0, Size() - src_size);\n      start += Size() - src_size;\n    }\n    Assign(buf, start);\n  }\n\n  /// \\brief Returns an all-1 hash, i.e. the biggest value representable by an N\n  /// bit number (N/8 bytes).\n  static Hash Max() noexcept {\n    Hash h;\n    h.storage_.fill(0xffffffffU);\n    return h;\n  }\n\n  /// \\brief Returns an all-0 hash, i.e. the smallest value representable by an\n  /// N bit number (N/8 bytes).\n  static Hash Min() noexcept {\n    return Hash();\n    // all bits are already 0\n  }\n\n  static Hash<BITS> FromHex(const std::string &src, bool reverse = false) {\n    Hash<BITS> hash;\n    codec::hex::Decode(gsl::make_span<>(src),\n                       gsl::make_span<>(hash.Data(), hash.Size()), reverse);\n    return hash;\n  }\n\n  static Hash<BITS> RandomHash() {\n    Hash<BITS> hash;\n    hash.Randomize();\n    return hash;\n  }\n  //@}\n\n  /// @name Checked element access\n  /// access specified element with bounds checking.\n  //@{\n  /*!\n    Returns a reference to the element at specified location `pos`, with\n    bounds checking.\n\n    \\param pos position of the element to return\n    \\exception std::out_of_range if !(pos < size()).\n   */\n  reference At(size_type pos) {\n    if (Size() <= pos) {\n      throw std::out_of_range(\"Hash<BITS> index out of range\");\n    }\n    return reinterpret_cast<pointer>(storage_.data())[pos];\n  }\n  const_reference At(size_type pos) const {\n    if (Size() <= pos) {\n      throw std::out_of_range(\"Hash<BITS> index out of range\");\n    }\n    return reinterpret_cast<const_pointer>(storage_.data())[pos];\n  };\n  //@}\n\n  /// @name Unchecked element access\n  /// access specified element __without__ bounds checking.\n  //@{\n  /// Returns a reference to the element at specified location pos. No bounds\n  /// checking is performed.\n  reference operator[](size_type pos) noexcept {\n    ASAP_ASSERT_PRECOND(pos < Size());\n    return reinterpret_cast<pointer>(storage_.data())[pos];\n  }\n  const_reference operator[](size_type pos) const noexcept {\n    ASAP_ASSERT_PRECOND(pos < Size());\n    return reinterpret_cast<pointer>(storage_.data())[pos];\n  }\n\n  /// Returns a reference to the first element in the container.\n  reference Front() { return reinterpret_cast<pointer>(storage_.data())[0]; }\n  const_reference Front() const {\n    return reinterpret_cast<const_pointer>(storage_.data())[0];\n  }\n\n  /// Returns reference to the last element in the container.\n  reference Back() {\n    return reinterpret_cast<pointer>(storage_.data())[Size() - 1];\n  }\n  const_reference Back() const {\n    return reinterpret_cast<const_pointer>(storage_.data())[Size() - 1];\n  }\n\n  /// Returns pointer to the underlying array serving as element storage. The\n  /// pointer is such that range [Data(); Data() + Size()) is always a valid\n  /// range.\n  pointer Data() noexcept { return reinterpret_cast<pointer>(storage_.data()); }\n  const_pointer Data() const noexcept {\n    return reinterpret_cast<const_pointer>(storage_.data());\n  }\n  //@}\n\n  /// @name Iterators\n  //@{\n  /// Returns an iterator to the first element of the container.\n  iterator begin() noexcept {\n    return reinterpret_cast<pointer>(storage_.data());\n  }\n  const_iterator begin() const noexcept {\n    return reinterpret_cast<const_pointer>(storage_.data());\n  }\n  const_iterator cbegin() const noexcept { return begin(); }\n\n  /// Returns an iterator to the element following the last element of the\n  /// container. This element acts as a placeholder; attempting to access it\n  /// results in undefined behavior.\n  iterator end() noexcept {\n    return reinterpret_cast<pointer>(storage_.data()) + Size();\n  }\n  const_iterator end() const noexcept {\n    return reinterpret_cast<const_pointer>(storage_.data()) + Size();\n  }\n  const_iterator cend() const noexcept { return end(); }\n\n  /// Returns a reverse iterator to the first element of the reversed container.\n  /// It corresponds to the last element of the non-reversed container.\n  reverse_iterator rbegin() noexcept { return reverse_iterator(end()); }\n  const_reverse_iterator rbegin() const noexcept {\n    return const_reverse_iterator(end());\n  }\n  const_reverse_iterator crbegin() const noexcept { return rbegin(); }\n\n  /// Returns a reverse iterator to the element following the last element of\n  /// the reversed container. It corresponds to the element preceding the first\n  /// element of the non-reversed container. This element acts as a placeholder,\n  /// attempting to access it results in undefined behavior.\n  reverse_iterator rend() noexcept { return reverse_iterator(begin()); }\n  const_reverse_iterator rend() const noexcept {\n    return const_reverse_iterator(begin());\n  }\n  const_reverse_iterator crend() const noexcept { return rend(); }\n  //@}\n\n  // Capacity\n\n  /// The size of the hash in bytes.\n  constexpr static std::size_t Size() { return BITS / 8; };\n\n  /// The size of the hash in bytes.\n  constexpr static std::size_t BitSize() { return BITS; };\n\n  // Operations\n\n  /// Set all bits to 0.\n  void Clear() { storage_.fill(0); }\n\n  /// Return true if all bits are set to 0.\n  bool IsAllZero() const {\n    for (auto v : storage_)\n      if (v != 0) return false;\n    return true;\n  }\n\n  /// Exchanges the contents of the container with those of other. Does not\n  /// cause iterators and references to associate with the other container.\n  void swap(Hash &other) noexcept { storage_.swap(other.storage_); }\n\n  /// Count leading zero bits.\n  int LeadingZeroBits() const {\n    return detail::CountLeadingZeroBits(gsl::make_span(storage_));\n  }\n\n  /// @name Comparison operators\n  /// The important thing to note here is that only two of these operators\n  /// actually do anything, the others are just forwarding their arguments to\n  /// either of these two to do the actual work (== and <). Therefore only these\n  /// two are implemented as friends.\n  //@{\n  /// \\brief Checks if the contents of `lhs` and `rhs` are equal, that is,\n  /// whether each element in `lhs` compares equal with the element in `rhs` at\n  /// the same position.\n  friend bool operator==(const Hash<BITS> &lhs, const Hash<BITS> &rhs) {\n    return std::equal(lhs.begin(), lhs.end(), rhs.begin());\n  }\n  /// \\brief Compares the contents of `lhs` and `rhs` lexicographically. The\n  /// comparison is performed by a function equivalent to\n  /// `std::lexicographical_compare`.\n  friend bool operator<(const Hash<BITS> &lhs, const Hash<BITS> &rhs) {\n    for (std::size_t i = 0; i < SIZE_DWORD; ++i) {\n      std::uint32_t const native_lhs = detail::NetworkToHost(lhs.storage_[i]);\n      std::uint32_t const native_rhs = detail::NetworkToHost(rhs.storage_[i]);\n      if (native_lhs < native_rhs) return true;\n      if (native_lhs > native_rhs) return false;\n    }\n    return false;\n  }\n  //@}\n\n  /// In-place bitwise XOR with the given other hash.\n  Hash &operator^=(Hash const &other) noexcept {\n    for (std::size_t i = 0; i < SIZE_DWORD; ++i)\n      storage_[i] ^= other.storage_[i];\n    return *this;\n  }\n\n  /*!\n  Starting at the given position in the hash, assign contents from the given\n  sequence of bytes.\n\n  > Data represented by the span is expected to be organized in network byte\n  > order (i.e. the byte returned by span.first() is the MSB (Most Significant\n  > Byte) and therefore will go into the MSB of the Hash).\n\n  The _span_ size can be smaller than the remaining space after _start_ in\n  the hash but it __cannot be bigger__. If this is not true, result is undefined\n  and, if assertions are enabled, this would be considered as a fatal error.\n\n  \\param buf source sequence of bytes.\n  \\param start position at which to assign the sequence in the hash.\n  */\n  void Assign(gsl::span<std::uint8_t const> buf, iterator start) noexcept {\n    size_type src_size = buf.size();\n    size_type dst_size = end() - start;\n    ASAP_ASSERT_PRECOND(src_size <= dst_size);\n    std::memcpy(start, buf.data(), std::min(src_size, dst_size));\n  }\n\n  // TODO: Replace the parameters with a span\n  void Randomize() { random::GenerateBlock(Data(), Size()); }\n\n  const std::string ToHex() const {\n    return codec::hex::Encode(gsl::make_span<>(Data(), Size()), false, true);\n  }\n\n  std::bitset<BITS> ToBitSet() const {\n    std::bitset<BITS> bs;  // [0,0,...,0]\n    int shift_left = BITS;\n    for (uint32_t num_part : storage_) {\n      shift_left -= 32;\n      num_part = detail::HostToNetwork(num_part);\n      std::bitset<BITS> bs_part(num_part);\n      bs |= bs_part << shift_left;\n    }\n    return bs;\n  }\n\n  std::string ToBitStringShort(std::size_t length = 32U) const {\n    auto truncate = false;\n    if (length < BITS) { truncate = true; length -= 3; }\n    auto str = ToBitSet().to_string().substr(0, length);\n    if (truncate) str.append(\"...\");\n    return str;\n  }\n\n private:\n  /// The size of the underlying data buffer in terms of 32-bit DWORD\n  static constexpr std::size_t SIZE_DWORD = BITS / 32;\n\n  /// The underlying data buffer is built as an array of unsigned 32-bit\n  /// integers to facilitate the math operations. Note however that iteration\n  /// over the Hash and random access to the data should always be presented as\n  /// if it were a byte array layed out in network order (big endian).\n  ///\n  /// > First DWORD is the most significant 4 bytes.\n  std::array<std::uint32_t, SIZE_DWORD> storage_;\n};\n\n/// @name Comparison operators\n/// Additional Comparison operators (not needing to be friend)\n//@{\n\ntemplate <unsigned int BITS>\ninline bool operator!=(const Hash<BITS> &lhs, const Hash<BITS> &rhs) {\n  return !(lhs == rhs);\n}\ntemplate <unsigned int BITS>\ninline bool operator>(const Hash<BITS> &lhs, const Hash<BITS> &rhs) {\n  return rhs < lhs;\n}\ntemplate <unsigned int BITS>\ninline bool operator<=(const Hash<BITS> &lhs, const Hash<BITS> &rhs) {\n  return !(lhs > rhs);\n}\ntemplate <unsigned int BITS>\ninline bool operator>=(const Hash<BITS> &lhs, const Hash<BITS> &rhs) {\n  return !(lhs < rhs);\n}\n//@}\n\n/// Bitwise XOR\ntemplate <unsigned int BITS>\ninline Hash<BITS> operator^(Hash<BITS> lhs, Hash<BITS> const &rhs) noexcept {\n  return lhs.operator^=(rhs);\n}\n\n// Specialized algorithms\n\n/// Exchanges the contents of one with other. Does not cause\n/// iterators and references to associate with the other container.\ntemplate <unsigned int BITS>\ninline void swap(Hash<BITS> &lhs, Hash<BITS> &rhs) {\n  lhs.swap(rhs);\n}\n\n/// Dump the hex-encoded contents of the hash to the stream.\ntemplate <unsigned int BITS>\ninline std::ostream &operator<<(std::ostream &out, Hash<BITS> const &hash) {\n  out << hash.ToHex();\n  return out;\n}\n\nusing Hash512 = Hash<512>;  // 64 bytes\nusing Hash256 = Hash<256>;  // 32 bytes\nusing Hash160 = Hash<160>;  // 20 bytes\n\n}  // namespace crypto\n}  // namespace blocxxi\n", "meta": {"hexsha": "6f9142b78a1d6110024b642855721feb469decad", "size": 14042, "ext": "h", "lang": "C", "max_stars_repo_path": "crypto/include/crypto/hash.h", "max_stars_repo_name": "canhld94/blocxxi", "max_stars_repo_head_hexsha": "e0e1e629334a7959c3fb9c38567f9cf28e2cf44a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2018-06-17T22:10:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T07:08:26.000Z", "max_issues_repo_path": "crypto/include/crypto/hash.h", "max_issues_repo_name": "canhld94/blocxxi", "max_issues_repo_head_hexsha": "e0e1e629334a7959c3fb9c38567f9cf28e2cf44a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-06-20T08:39:12.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-03T09:50:56.000Z", "max_forks_repo_path": "crypto/include/crypto/hash.h", "max_forks_repo_name": "canhld94/blocxxi", "max_forks_repo_head_hexsha": "e0e1e629334a7959c3fb9c38567f9cf28e2cf44a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-07-13T17:55:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-27T19:37:05.000Z", "avg_line_length": 34.1654501217, "max_line_length": 80, "alphanum_fraction": 0.6851588093, "num_tokens": 3490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3665897363221598, "lm_q2_score": 0.04336579721846243, "lm_q1q2_score": 0.015897456167716394}}
{"text": "/* -*- mode: C; c-basic-offset: 4 -*- */\n/* ex: set shiftwidth=4 tabstop=4 expandtab: */\n/*\n * Copyright (c) 2018, Colorado School of Mines\n * All rights reserved.\n *\n * Author(s): Neil T. Dantam <ndantam@miens.edu>\n * Georgia Tech Humanoid Robotics Lab\n * Under Direction of Prof. Mike Stilman <mstilman@cc.gatech.edu>\n *\n *\n * This file is provided under the following \"BSD-style\" License:\n *\n *\n *   Redistribution and use in source and binary forms, with or\n *   without modification, are permitted provided that the following\n *   conditions are met:\n *\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *\n *   * Redistributions in binary form must reproduce the above\n *     copyright notice, this list of conditions and the following\n *     disclaimer in the documentation and/or other materials provided\n *     with the distribution.\n *\n *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND\n *   CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n *   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n *   MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n *   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n *   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n *   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n *   AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n *   LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n *   ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *   POSSIBILITY OF SUCH DAMAGE.\n *\n */\n\n// uncomment to check that local allocs actually get freed\n// #define AA_ALLOC_STACK_MAX 0\n\n\n#include <stdlib.h>\n#include <cblas.h>\n\n#include \"amino.h\"\n#include \"amino/mat.h\"\n#include \"amino/mat_internal.h\"\n\n#define VEC_LEN(X) ((int)(X->len))\n#define MAT_ROWS(X) ((int)(X->rows))\n#define MAT_COLS(X) ((int)(X->cols))\n\n/******************/\n/* Error Handling */\n/******************/\n\nstatic void\ns_err_default( const char *message )\n{\n    fprintf(stderr, \"AMINO ERROR: %s\\n\",message);\n    abort();\n    exit(EXIT_FAILURE);\n}\n\nstatic aa_la_err_fun  *s_err_fun = s_err_default;\n\nvoid\naa_la_set_err( aa_la_err_fun *fun )\n{\n    s_err_fun = fun;\n}\n\nAA_API void\naa_la_err( const char *message ) {\n    s_err_fun(message);\n}\n\nAA_API void\naa_la_fail_size( size_t a, size_t b )\n{\n        const size_t size = 256;\n        char buf[size];\n        snprintf(buf,size, \"Mismatched sizes: %lu != %lu\\n\", a, b);\n        aa_la_err(buf);\n}\n\n/****************/\n/* Construction */\n/****************/\n\nAA_API void\naa_dvec_view( struct aa_dvec *vec, size_t len, double *data, size_t inc )\n{\n    *vec = AA_DVEC_INIT(len,data,inc);\n}\n\n\nAA_API void\naa_dvec_slice( const struct aa_dvec *src,\n               size_t start,\n               size_t stop,\n               size_t step,\n               struct aa_dvec *dst )\n{\n    if( stop > src->len || stop < start ) {\n        aa_la_err(\"Slice out-of-bounds\\n\");\n    }\n    *dst = AA_DVEC_INIT( (stop - start) / step,\n                         src->data + src->inc*start,\n                         src->inc*step );\n}\n\n\nAA_API void\naa_dmat_row_vec( const struct aa_dmat *src, size_t row, struct aa_dvec *dst )\n{\n    if( row >= src->rows ) {\n        aa_la_err(\"Row vector out-of-bounds\\n\");\n    }\n    aa_dvec_view(dst,src->cols, src->data + row, src->ld);\n}\n\nAA_API void\naa_dmat_col_vec( const struct aa_dmat *src, size_t col, struct aa_dvec *dst )\n{\n    if( col >= src->cols ) {\n        aa_la_err(\"Row vector out-of-bounds\\n\");\n    }\n    aa_dvec_view(dst, src->rows, src->data + col*src->ld, 1);\n}\n\nAA_API void\naa_dmat_diag_vec( const struct aa_dmat *src, struct aa_dvec *dst )\n{\n    aa_dvec_view(dst, AA_MIN(src->rows, src->cols), src->data, src->ld + 1);\n}\n\nAA_API void\naa_dmat_view( struct aa_dmat *mat, size_t rows, size_t cols,\n              double *data, size_t ld )\n{\n    *mat = AA_DMAT_INIT(rows,cols,data,ld);\n}\n\nAA_API void\naa_dmat_view_block(  struct aa_dmat *dst,\n                     const struct aa_dmat *src,\n                     size_t row_start, size_t col_start,\n                     size_t rows, size_t cols )\n{\n    aa_dmat_block( src,\n                   row_start, col_start,\n                   row_start + rows, col_start + cols,\n                   dst );\n}\n\nAA_API void\naa_dmat_block( const struct aa_dmat *src,\n               size_t row_start, size_t col_start,\n               size_t row_end, size_t col_end,\n               struct aa_dmat *dst )\n{\n    size_t m = src->rows, n = src->cols;\n    if( row_start >= row_end ||\n        row_start >= m ||\n        row_end > m ||\n        col_start >= col_end ||\n        col_start >= n ||\n        col_end > n )\n    {\n        aa_la_err(\"Block out-of-bounds\\n\");\n    }\n\n    aa_dmat_view( dst,\n                  row_end - row_start, col_end - col_start,\n                  src->data + col_start*src->ld + row_start, src->ld );\n}\n\n\nAA_API struct aa_dvec *\naa_dvec_malloc( size_t len ) {\n    struct aa_dvec *r;\n    const size_t s_desc = sizeof(*r);\n    const size_t s_elem = sizeof(r->data[0]);\n    const size_t pad =  s_elem - (s_desc % s_elem);\n    const size_t size = s_desc + pad + len * s_elem;\n\n    const size_t off = s_desc + pad;\n\n    char *ptr = (char*)malloc( size );\n\n    r = (struct aa_dvec*)ptr;\n    aa_dvec_view(r, len, (double*)(ptr+off), 1);\n    return r;\n}\n\nAA_API struct aa_dvec *\naa_dvec_alloc( struct aa_mem_region *reg, size_t len ) {\n    struct aa_dvec *r;\n    const size_t s_desc = sizeof(*r);\n    const size_t s_elem = sizeof(r->data[0]);\n    const size_t pad =  s_elem - (s_desc % s_elem);\n    char *ptr = (char*)aa_mem_region_alloc(reg, s_desc + pad + len * s_elem );\n\n    r = (struct aa_dvec*)ptr;\n    aa_dvec_view(r, len, (double*)(ptr+s_desc+pad), 1);\n    return r;\n}\n\nAA_API struct aa_dvec *\naa_dvec_dup( struct aa_mem_region *reg, const struct aa_dvec *src)\n{\n    struct aa_dvec *dst = aa_dvec_alloc(reg,src->len);\n    aa_dvec_copy(src,dst);\n    return dst;\n}\n\nAA_API struct aa_dmat *\naa_dmat_dup( struct aa_mem_region *reg, const struct aa_dmat *src)\n{\n    struct aa_dmat *dst = aa_dmat_alloc(reg,src->rows,src->cols);\n    aa_dmat_copy(src,dst);\n    return dst;\n}\n\nAA_API struct aa_dmat *\naa_dmat_malloc( size_t rows, size_t cols )\n{\n    struct aa_dmat *r;\n    const size_t s_desc = sizeof(*r);\n    const size_t s_elem = sizeof(r->data[0]);\n    const size_t pad =  s_elem - (s_desc % s_elem);\n    char *ptr = (char*)malloc( s_desc + pad + rows*cols * s_elem );\n\n    r = (struct aa_dmat*)ptr;\n    aa_dmat_view(r, rows, cols, (double*)(ptr+s_desc+pad), rows);\n\n    return r;\n}\n\nAA_API struct aa_dmat *\naa_dmat_alloc( struct aa_mem_region *reg, size_t rows, size_t cols )\n{\n    struct aa_dmat *r;\n    const size_t s_desc = sizeof(*r);\n    const size_t s_elem = sizeof(r->data[0]);\n    const size_t pad =  s_elem - (s_desc % s_elem);\n    size_t size = s_desc + pad + rows*cols * s_elem ;\n\n    char *ptr = (char*)aa_mem_region_alloc(reg, size);\n\n    r = (struct aa_dmat*)ptr;\n    aa_dmat_view( r, rows, cols, (double*)(ptr+s_desc+pad), rows );\n\n    return r;\n}\n\nAA_API void\naa_dmat_set( struct aa_dmat *A, double alpha, double beta )\n{\n    int mi   = (int)(A->rows);\n    int ni   = (int)(A->cols);\n    int ldai = (int)(A->ld);\n\n    dlaset_( \"G\", &mi, &ni,\n             &alpha, &beta,\n             A->data, &ldai );\n\n}\n\nAA_API void\naa_dvec_set( struct aa_dvec *vec, double alpha )\n{\n    double *end = vec->data + vec->len*vec->inc;\n    for( double *x = vec->data; x < end; x += vec->inc ) {\n        *x = alpha;\n    }\n}\n\nvoid\naa_dvec_zero( struct aa_dvec *vec )\n{\n    aa_dvec_set(vec,0);\n}\n\n\nAA_API void\naa_dmat_zero( struct aa_dmat *mat )\n{\n    aa_dmat_set(mat, 0, 0);\n}\n\n\n/* Level 1 BLAS */\nAA_API void\naa_dvec_swap( struct aa_dvec *x, struct aa_dvec *y )\n{\n    aa_la_check_size(x->len, y->len);\n    cblas_dswap( VEC_LEN(x), AA_VEC_ARGS(x), AA_VEC_ARGS(y) );\n}\n\nAA_API void\naa_dvec_scal( double a, struct aa_dvec *x )\n{\n    cblas_dscal( VEC_LEN(x), a, AA_VEC_ARGS(x) );\n}\n\nstatic void s_inc( size_t n, double alpha, double *x, size_t inc ) {\n    for( double *end = x + n*inc; x < end; x += inc ) {\n        *x += alpha;\n    }\n}\n\nAA_API void\naa_dvec_inc( double alpha, struct aa_dvec *x )\n{\n    s_inc( x->len, alpha, x->data, x->inc );\n}\n\nAA_API void\naa_dvec_copy( const struct aa_dvec *x, struct aa_dvec *y )\n{\n    aa_la_check_size(x->len, y->len);\n    cblas_dcopy( VEC_LEN(x), AA_VEC_ARGS(x), AA_VEC_ARGS(y) );\n}\n\nAA_API void\naa_dvec_axpy( double a, const struct aa_dvec *x, struct aa_dvec *y )\n{\n    aa_la_check_size(x->len, y->len);\n    cblas_daxpy( VEC_LEN(x), a, AA_VEC_ARGS(x), AA_VEC_ARGS(y) );\n}\n\nAA_API double\naa_dvec_dot( const struct aa_dvec *x, struct aa_dvec *y )\n{\n    aa_la_check_size(x->len, y->len);\n    return cblas_ddot( VEC_LEN(x), AA_VEC_ARGS(x), AA_VEC_ARGS(y) );\n}\n\nAA_API double\naa_dvec_nrm2( const struct aa_dvec *x )\n{\n    return cblas_dnrm2( VEC_LEN(x), AA_VEC_ARGS(x) );\n}\n\n/* Level 2 BLAS */\nAA_API void\naa_dmat_gemv( CBLAS_TRANSPOSE trans,\n              double alpha, const struct aa_dmat *A,\n              const struct aa_dvec *x,\n              double beta, struct aa_dvec *y )\n{\n    if( CblasTrans == trans ) {\n        aa_la_check_size( A->rows, x->len );\n        aa_la_check_size( A->cols, y->len );\n    } else {\n        aa_la_check_size( A->rows, y->len );\n        aa_la_check_size( A->cols, x->len );\n    }\n\n    cblas_dgemv( CblasColMajor, trans,\n                 MAT_ROWS(A), MAT_COLS(A),\n                 alpha, AA_MAT_ARGS(A),\n                 AA_VEC_ARGS(x),\n                 beta, AA_VEC_ARGS(y) );\n\n}\n\n/* Level 3 BLAS */\nAA_API void\naa_dmat_gemm( CBLAS_TRANSPOSE transA, CBLAS_TRANSPOSE transB,\n              double alpha, const struct aa_dmat *A,\n              const struct aa_dmat *B,\n              double beta, struct aa_dmat *C )\n{\n    aa_la_check_size( A->rows, C->rows );\n    aa_la_check_size( A->cols, B->rows );\n    aa_la_check_size( B->cols, C->cols );\n\n    assert( A->rows <= A->ld );\n    assert( B->rows <= B->ld );\n    assert( C->rows <= C->ld );\n\n    cblas_dgemm( CblasColMajor,\n                 transA, transB,\n                 MAT_ROWS(A), MAT_COLS(B), MAT_COLS(A),\n                 alpha, AA_MAT_ARGS(A),\n                 AA_MAT_ARGS(B),\n                 beta, AA_MAT_ARGS(C) );\n}\n\n/* LAPACK */\n\nAA_API void\naa_dmat_lacpy( const char uplo[1],\n               const struct aa_dmat *A,\n               struct aa_dmat *B )\n{\n\n    aa_la_check_size(A->rows,B->rows);\n    aa_la_check_size(A->cols,B->cols);\n    int mi   = (int)(A->rows);\n    int ni   = (int)(A->cols);\n    int ldai = (int)(A->ld);\n    int ldbi = (int)(B->ld);\n\n    dlacpy_(uplo, &mi, &ni,\n            A->data, &ldai,\n            B->data, &ldbi);\n}\n\nAA_API void\naa_dmat_copy(  const struct aa_dmat *A, struct aa_dmat *B)\n{\n    aa_dmat_lacpy(\"G\",A,B);\n}\n\n\n/* Matrix Functions */\n\nstatic double s_ssd( size_t n,\n                     double a,\n                     double *x, size_t incx,\n                     double *y, size_t incy )\n{\n    for( double *e = x + n*incx; x < e; x += incx, y+=incy ) {\n        double d = *x - *y;\n        a += d*d;\n    }\n    return a;\n}\n\n\nAA_API double\naa_dvec_ssd( const struct aa_dvec *x, const struct aa_dvec *y)\n{\n    aa_la_check_size( x->len, y->len );\n    return s_ssd( x->len, 0,\n                  x->data, x->inc,\n                  y->data, y->inc );\n}\n\nAA_API double\naa_dmat_ssd( const struct aa_dmat *A, const struct aa_dmat *B)\n{\n    size_t m = A->rows, n = A->cols;\n    aa_la_check_size( m, B->rows );\n    aa_la_check_size( n, B->cols );\n    double a = 0;\n    for( double *Ac=A->data, *Bc=B->data, *ec=A->data + n*A->ld;\n         Ac < ec;\n         Ac+=A->ld, Bc+=B->ld )\n    {\n        a = s_ssd( m, a, Ac, 1, Bc, 1 );\n    }\n    return a;\n}\n\nAA_API double\naa_dmat_nrm2( const struct aa_dmat *A )\n{\n    int m=(int)A->rows, n=(int)A->cols, ld=(int)A->ld;\n    return dlange_(\"F\", &m, &n, A->data, &ld, NULL );\n}\n\nAA_API void\naa_dmat_scal( struct aa_dmat *x, double alpha )\n{\n    int m = (int)x->rows, n=(int)x->cols, ld=(int)x->ld;\n    double cfrom=1;\n    int info;\n    dlascl_(\"G\", NULL, NULL,\n            &cfrom, &alpha,\n            &m, &n, x->data, &ld,\n            &info);\n}\n\nAA_API void\naa_dmat_inc( struct aa_dmat *A, double alpha )\n{\n    size_t m=A->rows, n=A->cols, ld=A->ld;\n    double *x = A->data;\n\n    if( m == n ) {\n        s_inc(m*n, alpha, x, 1);\n    } else {\n        for( double *e = x + n*ld; x < e; x+=ld ) {\n            s_inc(m, alpha, x, 1);\n        }\n    }\n\n}\n\nAA_API void\naa_dmat_axpy( double alpha, const struct aa_dmat *X, struct aa_dmat *Y)\n{\n    size_t m=X->rows, n=X->cols, ldX=X->ld, ldY=Y->ld;\n    double *x=X->data, *y=Y->data;\n\n    aa_la_check_size(m, Y->rows);\n    aa_la_check_size(n, Y->cols);\n\n\n    if( m == ldX && m == ldY ) {\n        cblas_daxpy( (int)(m*n), alpha, x,1, y,1 );\n    } else {\n        int mi = (int)m;\n        for( double *e = x + n*ldX; x < e; x+=ldX, y+=ldY ) {\n            cblas_daxpy( mi, alpha, x,1, y,1 );\n        }\n    }\n}\n\nvoid\naa_dmat_trans( const struct aa_dmat *A, struct aa_dmat *B)\n{\n    const size_t m   = A->rows;\n    const size_t n   = A->cols;\n    const size_t lda = A->ld;\n    const size_t ldb = B->ld;\n\n    aa_la_check_size(m, B->cols);\n    aa_la_check_size(n, B->rows);\n\n    for ( double *Acol = A->data, *Brow=B->data, *Be=B->data + n;\n          Brow < Be;\n          Brow++, Acol+=lda )\n    {\n        cblas_dcopy( (int)m, Acol, 1, Brow, (int)ldb );\n    }\n}\n\nAA_API int\naa_dmat_inv( struct aa_dmat *A )\n{\n    aa_la_check_size(A->rows,A->cols);\n    int info;\n\n    int *ipiv = (int*)\n        aa_mem_region_local_alloc(sizeof(int)*A->rows);\n\n    // LU-factor\n    info = aa_cla_dgetrf( MAT_ROWS(A), MAT_COLS(A), AA_MAT_ARGS(A), ipiv );\n\n    int lwork = -1;\n    while(1) {\n        double *work = (double*)\n            aa_mem_region_local_tmpalloc( sizeof(double)*\n                                      (size_t)(lwork < 0 ? 1 : lwork) );\n        aa_cla_dgetri( MAT_ROWS(A), AA_MAT_ARGS(A), ipiv, work, lwork );\n        if( lwork > 0 ) break;\n        assert( -1 == lwork );\n        lwork = (int)work[0];\n    }\n\n    aa_mem_region_local_pop(ipiv);\n\n    return info;\n}\n\n\nint s_svd_helper ( const struct aa_dmat *A,\n                   struct aa_mem_region *reg,\n                   size_t *pkmin, size_t *pkmax,\n                   double **pU, double **pVt, double **pS )\n{\n\n    size_t m = A->rows;\n    size_t n = A->cols;\n\n    // find  min/max dimensions\n    if( m < n ) {\n        *pkmin = m;\n        *pkmax = n;\n    } else {\n        *pkmin = n;\n        *pkmax = m;\n    }\n\n    // This method uses the SVD\n    double *W  = (double*)aa_mem_region_alloc( reg, sizeof(double) * (m*m + n*n + *pkmin) );\n    *pU  = W;        // size m*m\n    *pVt = *pU + m*m; // size n*n\n    *pS  = *pVt + n*n; // size min(m,n)\n\n    // A = U S V^T\n    aa_la_d_svd( m,n,\n                 A->data, A->ld,\n                 *pU, m, *pS, *pVt, n );\n\n\n    return 0;\n}\n\n\nint\naa_dmat_pinv( const struct aa_dmat *A, double tol, struct aa_dmat *As )\n{\n\n    aa_la_check_size(A->rows, As->cols);\n    aa_la_check_size(A->cols, As->rows);\n\n    struct aa_mem_region *reg =  aa_mem_region_local_get();\n    void *ptrtop = aa_mem_region_ptr(reg);\n\n    size_t kmin, kmax;\n    double *U, *Vt, *S;\n    s_svd_helper( A, reg,\n                  &kmin, &kmax, &U, &Vt, &S );\n\n    size_t m = A->rows;\n    const int mi = (int)(A->rows);\n    const int ni = (int)(A->cols);\n\n    if( tol < 0 ) {\n        tol = (double)kmax * S[0] * DBL_EPSILON;\n    }\n\n    // \\sum 1/s_i * v_i * u_i^T\n    aa_dmat_zero(As);\n    double *Asd = As->data;\n    for( size_t i = 0; i < kmin && S[i] > tol; i ++ ) {\n        cblas_dger( CblasColMajor, ni, mi, 1/S[i],\n                    Vt + i, ni,\n                    U + m*i, 1,\n                    Asd, ni\n            );\n    }\n\n    aa_mem_region_pop( reg, ptrtop );\n\n    return 0;\n\n    /* struct aa_mem_region *reg = aa_mem_region_local_get(); */\n    /* struct aa_dmat *Ap = aa_dmat_alloc(reg,m,n); */\n\n    /* // B = AA^T */\n    /* double *B; */\n    /* int ldb; */\n    /* if( m <= n ) { */\n    /*     /\\* Use A_star as workspace when it's big enough *\\/ */\n    /*     B = As->data; */\n    /*     ldb = (int)(As->ld); */\n    /* } else { */\n    /*     B = AA_MEM_REGION_NEW_N( reg, double, m*m ); */\n    /*     ldb = (int)m; */\n    /* } */\n\n    /* aa_la_dlacpy( \"A\", A, Ap ); */\n\n    /* // B is symmetric.  Only compute the upper half. */\n    /* cblas_dsyrk( CblasColMajor, CblasUpper, CblasNoTrans, */\n    /*              MAT_ROWS(Ap), MAT_COLS(Ap), */\n    /*              1, AA_MAT_ARGS(Ap), */\n    /*              0, B, ldb ); */\n\n    /* // B += kI */\n    /* /\\* for( size_t i = 0; i < m*(size_t)ldb; i += ((size_t)ldb+1) ) *\\/ */\n    /* /\\*     B[i] += k; *\\/ */\n\n    /* /\\* Solve via Cholesky Decomp *\\/ */\n    /* /\\* B^T (A^*)^T = A    and     B = B^T (Hermitian) *\\/ */\n\n    /* aa_cla_dposv( 'U', (int)m, (int)n, */\n    /*               B, ldb, */\n    /*               AA_MAT_ARGS(Ap) ); */\n\n    /* aa_dmat_trans( Ap, As ); */\n\n    /* aa_mem_region_pop( reg, Ap ); */\n\n}\n\nint\naa_dmat_dpinv( const struct aa_dmat *A, double k, struct aa_dmat *As)\n{\n    aa_la_check_size(A->rows, As->cols);\n    aa_la_check_size(A->cols, As->rows);\n\n    // TODO: Try DGESV for non-positive-definite matrices\n\n    size_t m = A->rows;\n    size_t n = A->cols;\n\n    struct aa_mem_region *reg = aa_mem_region_local_get();\n    void *ptrtop = aa_mem_region_ptr(reg);\n    int r = -1;\n\n    /* As = inv(A'*A - k*I) * A' A'*inv(A*A' - k*I) */\n    if( m <= n ) {\n        /*\n         * (A^*) = A^T*inv(A*A^T - k*I)\n         * (A^*) = A^T*inv(B)\n         * (A^*)*B = A^T\n         * B^T (A^*)^T = A    and     B = B^T (Hermitian)\n         *\n         */\n\n        /* Use A_star as workspace for B */\n        double *B = As->data;\n        int ldb = (int)(As->ld);\n\n        /* Ap = A */\n        struct aa_dmat *Ap = aa_dmat_alloc(reg,m,n);\n        aa_dmat_lacpy( \"A\", A, Ap );\n\n        // B is symmetric.  Only compute the upper half.\n        // B = A * A'\n        cblas_dsyrk( CblasColMajor, CblasUpper, CblasNoTrans,\n                     MAT_ROWS(Ap), MAT_COLS(Ap),\n                     1, AA_MAT_ARGS(Ap),\n                     0, B, ldb );\n\n        /* B += kI */\n        for( double *x = B, *e = B+(int)m*ldb; x < e; x+=ldb+1 )\n            *x += k;\n\n        /* B^T (A^*)^T = A    and     B = B^T (Hermitian) */\n\n        /* Solve via Cholesky (positive definite) */\n        r = aa_cla_dposv( 'U', (int)m, (int)n,\n                           B, ldb,\n                           AA_MAT_ARGS(Ap) );\n\n        /* Solve via LU */\n        /* int *ipiv = AA_MEM_REGION_NEW_N(reg,int,m); */\n        /* r = aa_la_d_sysv( \"U\", m, n, */\n        /*                   B, (size_t)ldb, */\n        /*                   ipiv, */\n        /*                   Ap->data, Ap->ld ); */\n\n\n        aa_dmat_trans( Ap, As );\n\n    } else {\n\n        /*\n         * (A^*) = inv(A^T*A - k*I) * A^T\n         * (A^*) = inv(B) * A^T\n         * B*(A^*) = A^T\n         */\n\n        /* Use A_star as workspace for B */\n        double *B = AA_MEM_REGION_NEW_N(reg,double,n*n);\n        int ldb = (int)(n);\n\n        /* As = A^T */\n        aa_dmat_trans( A, As );\n\n        // B is symmetric.  Only compute the upper half.\n        // B = A' * A = As * As'\n        cblas_dsyrk( CblasColMajor, CblasUpper, CblasNoTrans,\n                     MAT_ROWS(As), MAT_COLS(As),\n                     1, AA_MAT_ARGS(As),\n                     0, B, ldb );\n\n        /* B += kI */\n        //for( size_t i = 0; i < n*(size_t)ldb; i += ((size_t)ldb+1) )\n        for( double *x = B, *e = B+n*n; x < e; x+=ldb+1 )\n            *x += k;\n\n        /* B * (A^*)^T = A    and     B = B^T (Hermitian) */\n\n        /* Solve via Cholesky (positive definite) */\n        r = aa_cla_dposv( 'U', (int)n, (int)m,\n                           B, ldb,\n                           AA_MAT_ARGS(As) );\n\n        /* Solve via LU */\n        /* int *ipiv = AA_MEM_REGION_NEW_N(reg,int,n); */\n        /* r = aa_la_d_sysv( \"U\", n, m, */\n        /*                   B, (size_t)ldb, */\n        /*                   ipiv, */\n        /*                   As->data, As->ld ); */\n\n    }\n\n\n    aa_mem_region_pop( reg, ptrtop );\n\n    return r;\n}\n\nint\naa_dmat_dzdpinv(  const struct aa_dmat *A, double s_min, struct aa_dmat *As)\n{\n\n    aa_la_check_size(A->rows, As->cols);\n    aa_la_check_size(A->cols, As->rows);\n\n    struct aa_mem_region *reg =  aa_mem_region_local_get();\n    void *ptrtop = aa_mem_region_ptr(reg);\n\n    size_t kmin, kmax;\n    double *U, *Vt, *S;\n    s_svd_helper( A, reg,\n                  &kmin, &kmax, &U, &Vt, &S );\n\n    size_t m = A->rows;\n    const int mi = (int)(A->rows);\n    const int ni = (int)(A->cols);\n\n    // \\sum s_i/(s_i**2+k) * v_i * u_i^T\n    aa_dmat_zero(As);\n    double *Asd = As->data;\n    size_t i = 0;\n\n    // Undamped parts\n    for( ; i < kmin && S[i] >= s_min; i ++ ) {\n        cblas_dger( CblasColMajor, ni, mi, 1/S[i],\n                    Vt + i, ni,\n                    U + m*i, 1,\n                    Asd, ni\n            );\n    }\n\n    // Damped parts\n    double s2 = s_min*s_min;\n    for( ; i < kmin; i ++ ) {\n        cblas_dger( CblasColMajor, ni, mi, S[i]/s2,\n                    Vt + i, ni,\n                    U + m*i, 1,\n                    Asd, ni\n            );\n    }\n\n    aa_mem_region_pop( reg, ptrtop );\n\n    return 0;\n\n}\n", "meta": {"hexsha": "b3291373a492b8f84300d23f0eab446b921be827", "size": 21383, "ext": "c", "lang": "C", "max_stars_repo_path": "src/mat.c", "max_stars_repo_name": "dyalab/amino", "max_stars_repo_head_hexsha": "e3063ceeeed7d1a3d55fc0d3071c9aacb4466b22", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2015-06-02T20:06:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T16:49:22.000Z", "max_issues_repo_path": "src/mat.c", "max_issues_repo_name": "dyalab/amino", "max_issues_repo_head_hexsha": "e3063ceeeed7d1a3d55fc0d3071c9aacb4466b22", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 28.0, "max_issues_repo_issues_event_min_datetime": "2016-05-18T20:54:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-22T23:43:23.000Z", "max_forks_repo_path": "src/mat.c", "max_forks_repo_name": "dyalab/amino", "max_forks_repo_head_hexsha": "e3063ceeeed7d1a3d55fc0d3071c9aacb4466b22", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2016-01-05T18:55:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T01:32:20.000Z", "avg_line_length": 25.5167064439, "max_line_length": 92, "alphanum_fraction": 0.5378104101, "num_tokens": 6691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658972248186006, "lm_q2_score": 0.04336579629119585, "lm_q1q2_score": 0.01589745522759436}}
{"text": "/* roots/fdfsolver.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Reid Priedhorsky, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#include <config.h>\n#include <stdlib.h>\n#include <string.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_roots.h>\n\ngsl_root_fdfsolver *\ngsl_root_fdfsolver_alloc (const gsl_root_fdfsolver_type * T)\n{\n\n  gsl_root_fdfsolver * s = (gsl_root_fdfsolver *) malloc (sizeof (gsl_root_fdfsolver));\n\n  if (s == 0)\n    {\n      GSL_ERROR_VAL (\"failed to allocate space for root solver struct\",\n\t\t\tGSL_ENOMEM, 0);\n    };\n\n  s->state = malloc (T->size);\n\n  if (s->state == 0)\n    {\n      free (s);\t\t/* exception in constructor, avoid memory leak */\n\n      GSL_ERROR_VAL (\"failed to allocate space for root solver state\",\n\t\t\tGSL_ENOMEM, 0);\n    };\n\n  s->type = T ;\n  s->fdf = NULL;\n\n  return s;\n}\n\nint\ngsl_root_fdfsolver_set (gsl_root_fdfsolver * s, gsl_function_fdf * f, double root)\n{\n  s->fdf = f;\n  s->root = root;\n\n  return (s->type->set) (s->state, s->fdf, &(s->root));\n}\n\nint\ngsl_root_fdfsolver_iterate (gsl_root_fdfsolver * s)\n{\n  return (s->type->iterate) (s->state, s->fdf, &(s->root));\n}\n\nvoid\ngsl_root_fdfsolver_free (gsl_root_fdfsolver * s)\n{\n  free (s->state);\n  free (s);\n}\n\nconst char *\ngsl_root_fdfsolver_name (const gsl_root_fdfsolver * s)\n{\n  return s->type->name;\n}\n\ndouble\ngsl_root_fdfsolver_root (const gsl_root_fdfsolver * s)\n{\n  return s->root;\n}\n\n\n", "meta": {"hexsha": "7f4146e48bc41b7f04e68da85c4fd95c24ee1df9", "size": 2066, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/roots/fdfsolver.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/roots/fdfsolver.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/roots/fdfsolver.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 23.2134831461, "max_line_length": 87, "alphanum_fraction": 0.6907066796, "num_tokens": 614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.03358950649659707, "lm_q1q2_score": 0.015877204708776117}}
{"text": "#include <gsl/gsl_test.h>\n#include <gsl/gsl_ieee_utils.h>\n#include <gsl/gsl_math.h>\n#include \"gsl_cblas.h\"\n\n#include \"tests.h\"\n\nvoid\ntest_trmv (void) {\nconst double flteps = 1e-4, dbleps = 1e-6;\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.987f };\n   float X[] = { -0.138f };\n   int incX = -1;\n   float x_expected[] = { -0.136206f };\n   cblas_strmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"strmv(case 814)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.987f };\n   float X[] = { -0.138f };\n   int incX = -1;\n   float x_expected[] = { -0.138f };\n   cblas_strmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"strmv(case 815)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.987f };\n   float X[] = { -0.138f };\n   int incX = -1;\n   float x_expected[] = { -0.136206f };\n   cblas_strmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"strmv(case 816)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.987f };\n   float X[] = { -0.138f };\n   int incX = -1;\n   float x_expected[] = { -0.138f };\n   cblas_strmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"strmv(case 817)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.987f };\n   float X[] = { -0.138f };\n   int incX = -1;\n   float x_expected[] = { -0.136206f };\n   cblas_strmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"strmv(case 818)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.987f };\n   float X[] = { -0.138f };\n   int incX = -1;\n   float x_expected[] = { -0.138f };\n   cblas_strmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"strmv(case 819)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.987f };\n   float X[] = { -0.138f };\n   int incX = -1;\n   float x_expected[] = { -0.136206f };\n   cblas_strmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"strmv(case 820)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.987f };\n   float X[] = { -0.138f };\n   int incX = -1;\n   float x_expected[] = { -0.138f };\n   cblas_strmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"strmv(case 821)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   float A[] = { -0.329f };\n   float X[] = { 0.463f };\n   int incX = -1;\n   float x_expected[] = { -0.152327f };\n   cblas_strmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"strmv(case 822)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   float A[] = { -0.329f };\n   float X[] = { 0.463f };\n   int incX = -1;\n   float x_expected[] = { 0.463f };\n   cblas_strmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"strmv(case 823)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   float A[] = { -0.329f };\n   float X[] = { 0.463f };\n   int incX = -1;\n   float x_expected[] = { -0.152327f };\n   cblas_strmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"strmv(case 824)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   float A[] = { -0.329f };\n   float X[] = { 0.463f };\n   int incX = -1;\n   float x_expected[] = { 0.463f };\n   cblas_strmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"strmv(case 825)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   float A[] = { -0.329f };\n   float X[] = { 0.463f };\n   int incX = -1;\n   float x_expected[] = { -0.152327f };\n   cblas_strmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"strmv(case 826)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   float A[] = { -0.329f };\n   float X[] = { 0.463f };\n   int incX = -1;\n   float x_expected[] = { 0.463f };\n   cblas_strmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"strmv(case 827)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   float A[] = { -0.329f };\n   float X[] = { 0.463f };\n   int incX = -1;\n   float x_expected[] = { -0.152327f };\n   cblas_strmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"strmv(case 828)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   float A[] = { -0.329f };\n   float X[] = { 0.463f };\n   int incX = -1;\n   float x_expected[] = { 0.463f };\n   cblas_strmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"strmv(case 829)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   double A[] = { -0.429 };\n   double X[] = { -0.899 };\n   int incX = -1;\n   double x_expected[] = { 0.385671 };\n   cblas_dtrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtrmv(case 830)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   double A[] = { -0.429 };\n   double X[] = { -0.899 };\n   int incX = -1;\n   double x_expected[] = { -0.899 };\n   cblas_dtrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtrmv(case 831)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   double A[] = { -0.429 };\n   double X[] = { -0.899 };\n   int incX = -1;\n   double x_expected[] = { 0.385671 };\n   cblas_dtrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtrmv(case 832)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   double A[] = { -0.429 };\n   double X[] = { -0.899 };\n   int incX = -1;\n   double x_expected[] = { -0.899 };\n   cblas_dtrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtrmv(case 833)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   double A[] = { -0.429 };\n   double X[] = { -0.899 };\n   int incX = -1;\n   double x_expected[] = { 0.385671 };\n   cblas_dtrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtrmv(case 834)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   double A[] = { -0.429 };\n   double X[] = { -0.899 };\n   int incX = -1;\n   double x_expected[] = { -0.899 };\n   cblas_dtrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtrmv(case 835)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   double A[] = { -0.429 };\n   double X[] = { -0.899 };\n   int incX = -1;\n   double x_expected[] = { 0.385671 };\n   cblas_dtrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtrmv(case 836)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   double A[] = { -0.429 };\n   double X[] = { -0.899 };\n   int incX = -1;\n   double x_expected[] = { -0.899 };\n   cblas_dtrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtrmv(case 837)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.842 };\n   double X[] = { 0.192 };\n   int incX = -1;\n   double x_expected[] = { 0.161664 };\n   cblas_dtrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtrmv(case 838)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.842 };\n   double X[] = { 0.192 };\n   int incX = -1;\n   double x_expected[] = { 0.192 };\n   cblas_dtrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtrmv(case 839)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.842 };\n   double X[] = { 0.192 };\n   int incX = -1;\n   double x_expected[] = { 0.161664 };\n   cblas_dtrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtrmv(case 840)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.842 };\n   double X[] = { 0.192 };\n   int incX = -1;\n   double x_expected[] = { 0.192 };\n   cblas_dtrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtrmv(case 841)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.842 };\n   double X[] = { 0.192 };\n   int incX = -1;\n   double x_expected[] = { 0.161664 };\n   cblas_dtrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtrmv(case 842)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.842 };\n   double X[] = { 0.192 };\n   int incX = -1;\n   double x_expected[] = { 0.192 };\n   cblas_dtrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtrmv(case 843)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.842 };\n   double X[] = { 0.192 };\n   int incX = -1;\n   double x_expected[] = { 0.161664 };\n   cblas_dtrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtrmv(case 844)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.842 };\n   double X[] = { 0.192 };\n   int incX = -1;\n   double x_expected[] = { 0.192 };\n   cblas_dtrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtrmv(case 845)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   float A[] = { -0.162f, -0.108f };\n   float X[] = { 0.542f, 0.461f };\n   int incX = -1;\n   float x_expected[] = { -0.038016f, -0.133218f };\n   cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrmv(case 846) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrmv(case 846) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   float A[] = { -0.162f, -0.108f };\n   float X[] = { 0.542f, 0.461f };\n   int incX = -1;\n   float x_expected[] = { 0.542f, 0.461f };\n   cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrmv(case 847) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrmv(case 847) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   float A[] = { -0.162f, -0.108f };\n   float X[] = { 0.542f, 0.461f };\n   int incX = -1;\n   float x_expected[] = { -0.038016f, -0.133218f };\n   cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrmv(case 848) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrmv(case 848) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   float A[] = { -0.162f, -0.108f };\n   float X[] = { 0.542f, 0.461f };\n   int incX = -1;\n   float x_expected[] = { 0.542f, 0.461f };\n   cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrmv(case 849) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrmv(case 849) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   float A[] = { -0.162f, -0.108f };\n   float X[] = { 0.542f, 0.461f };\n   int incX = -1;\n   float x_expected[] = { -0.038016f, -0.133218f };\n   cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrmv(case 850) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrmv(case 850) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   float A[] = { -0.162f, -0.108f };\n   float X[] = { 0.542f, 0.461f };\n   int incX = -1;\n   float x_expected[] = { 0.542f, 0.461f };\n   cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrmv(case 851) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrmv(case 851) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   float A[] = { -0.162f, -0.108f };\n   float X[] = { 0.542f, 0.461f };\n   int incX = -1;\n   float x_expected[] = { -0.038016f, -0.133218f };\n   cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrmv(case 852) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrmv(case 852) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   float A[] = { -0.162f, -0.108f };\n   float X[] = { 0.542f, 0.461f };\n   int incX = -1;\n   float x_expected[] = { 0.542f, 0.461f };\n   cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrmv(case 853) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrmv(case 853) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.547f, 0.583f };\n   float X[] = { -0.302f, 0.434f };\n   int incX = -1;\n   float x_expected[] = { -0.418216f, 0.061332f };\n   cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrmv(case 854) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrmv(case 854) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.547f, 0.583f };\n   float X[] = { -0.302f, 0.434f };\n   int incX = -1;\n   float x_expected[] = { -0.302f, 0.434f };\n   cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrmv(case 855) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrmv(case 855) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.547f, 0.583f };\n   float X[] = { -0.302f, 0.434f };\n   int incX = -1;\n   float x_expected[] = { -0.418216f, 0.061332f };\n   cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrmv(case 856) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrmv(case 856) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.547f, 0.583f };\n   float X[] = { -0.302f, 0.434f };\n   int incX = -1;\n   float x_expected[] = { -0.302f, 0.434f };\n   cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrmv(case 857) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrmv(case 857) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.547f, 0.583f };\n   float X[] = { -0.302f, 0.434f };\n   int incX = -1;\n   float x_expected[] = { -0.418216f, 0.061332f };\n   cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrmv(case 858) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrmv(case 858) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.547f, 0.583f };\n   float X[] = { -0.302f, 0.434f };\n   int incX = -1;\n   float x_expected[] = { -0.302f, 0.434f };\n   cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrmv(case 859) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrmv(case 859) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.547f, 0.583f };\n   float X[] = { -0.302f, 0.434f };\n   int incX = -1;\n   float x_expected[] = { -0.418216f, 0.061332f };\n   cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrmv(case 860) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrmv(case 860) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.547f, 0.583f };\n   float X[] = { -0.302f, 0.434f };\n   int incX = -1;\n   float x_expected[] = { -0.302f, 0.434f };\n   cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrmv(case 861) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrmv(case 861) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 113;\n   int uplo = 121;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.216f, 0.192f };\n   float X[] = { -0.564f, -0.297f };\n   int incX = -1;\n   float x_expected[] = { -0.178848f, 0.044136f };\n   cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrmv(case 862) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrmv(case 862) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 113;\n   int uplo = 121;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.216f, 0.192f };\n   float X[] = { -0.564f, -0.297f };\n   int incX = -1;\n   float x_expected[] = { -0.564f, -0.297f };\n   cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrmv(case 863) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrmv(case 863) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 113;\n   int uplo = 122;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.216f, 0.192f };\n   float X[] = { -0.564f, -0.297f };\n   int incX = -1;\n   float x_expected[] = { -0.178848f, 0.044136f };\n   cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrmv(case 864) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrmv(case 864) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 113;\n   int uplo = 122;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.216f, 0.192f };\n   float X[] = { -0.564f, -0.297f };\n   int incX = -1;\n   float x_expected[] = { -0.564f, -0.297f };\n   cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrmv(case 865) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrmv(case 865) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 113;\n   int uplo = 121;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.216f, 0.192f };\n   float X[] = { -0.564f, -0.297f };\n   int incX = -1;\n   float x_expected[] = { -0.178848f, 0.044136f };\n   cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrmv(case 866) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrmv(case 866) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 113;\n   int uplo = 121;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.216f, 0.192f };\n   float X[] = { -0.564f, -0.297f };\n   int incX = -1;\n   float x_expected[] = { -0.564f, -0.297f };\n   cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrmv(case 867) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrmv(case 867) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 113;\n   int uplo = 122;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.216f, 0.192f };\n   float X[] = { -0.564f, -0.297f };\n   int incX = -1;\n   float x_expected[] = { -0.178848f, 0.044136f };\n   cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrmv(case 868) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrmv(case 868) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 113;\n   int uplo = 122;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.216f, 0.192f };\n   float X[] = { -0.564f, -0.297f };\n   int incX = -1;\n   float x_expected[] = { -0.564f, -0.297f };\n   cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrmv(case 869) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrmv(case 869) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.693, -0.22 };\n   double X[] = { -0.101, 0.889 };\n   int incX = -1;\n   double x_expected[] = { 0.125587, 0.638297 };\n   cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrmv(case 870) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrmv(case 870) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.693, -0.22 };\n   double X[] = { -0.101, 0.889 };\n   int incX = -1;\n   double x_expected[] = { -0.101, 0.889 };\n   cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrmv(case 871) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrmv(case 871) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.693, -0.22 };\n   double X[] = { -0.101, 0.889 };\n   int incX = -1;\n   double x_expected[] = { 0.125587, 0.638297 };\n   cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrmv(case 872) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrmv(case 872) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.693, -0.22 };\n   double X[] = { -0.101, 0.889 };\n   int incX = -1;\n   double x_expected[] = { -0.101, 0.889 };\n   cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrmv(case 873) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrmv(case 873) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.693, -0.22 };\n   double X[] = { -0.101, 0.889 };\n   int incX = -1;\n   double x_expected[] = { 0.125587, 0.638297 };\n   cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrmv(case 874) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrmv(case 874) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.693, -0.22 };\n   double X[] = { -0.101, 0.889 };\n   int incX = -1;\n   double x_expected[] = { -0.101, 0.889 };\n   cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrmv(case 875) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrmv(case 875) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.693, -0.22 };\n   double X[] = { -0.101, 0.889 };\n   int incX = -1;\n   double x_expected[] = { 0.125587, 0.638297 };\n   cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrmv(case 876) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrmv(case 876) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.693, -0.22 };\n   double X[] = { -0.101, 0.889 };\n   int incX = -1;\n   double x_expected[] = { -0.101, 0.889 };\n   cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrmv(case 877) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrmv(case 877) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   double A[] = { -0.216, -0.623 };\n   double X[] = { 0.048, 0.293 };\n   int incX = -1;\n   double x_expected[] = { 0.172171, -0.093192 };\n   cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrmv(case 878) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrmv(case 878) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   double A[] = { -0.216, -0.623 };\n   double X[] = { 0.048, 0.293 };\n   int incX = -1;\n   double x_expected[] = { 0.048, 0.293 };\n   cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrmv(case 879) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrmv(case 879) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   double A[] = { -0.216, -0.623 };\n   double X[] = { 0.048, 0.293 };\n   int incX = -1;\n   double x_expected[] = { 0.172171, -0.093192 };\n   cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrmv(case 880) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrmv(case 880) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   double A[] = { -0.216, -0.623 };\n   double X[] = { 0.048, 0.293 };\n   int incX = -1;\n   double x_expected[] = { 0.048, 0.293 };\n   cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrmv(case 881) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrmv(case 881) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   double A[] = { -0.216, -0.623 };\n   double X[] = { 0.048, 0.293 };\n   int incX = -1;\n   double x_expected[] = { 0.172171, -0.093192 };\n   cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrmv(case 882) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrmv(case 882) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   double A[] = { -0.216, -0.623 };\n   double X[] = { 0.048, 0.293 };\n   int incX = -1;\n   double x_expected[] = { 0.048, 0.293 };\n   cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrmv(case 883) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrmv(case 883) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   double A[] = { -0.216, -0.623 };\n   double X[] = { 0.048, 0.293 };\n   int incX = -1;\n   double x_expected[] = { 0.172171, -0.093192 };\n   cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrmv(case 884) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrmv(case 884) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   double A[] = { -0.216, -0.623 };\n   double X[] = { 0.048, 0.293 };\n   int incX = -1;\n   double x_expected[] = { 0.048, 0.293 };\n   cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrmv(case 885) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrmv(case 885) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 113;\n   int uplo = 121;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   double A[] = { -0.345, -0.851 };\n   double X[] = { -0.708, 0.298 };\n   int incX = -1;\n   double x_expected[] = { -0.009338, -0.705318 };\n   cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrmv(case 886) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrmv(case 886) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 113;\n   int uplo = 121;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   double A[] = { -0.345, -0.851 };\n   double X[] = { -0.708, 0.298 };\n   int incX = -1;\n   double x_expected[] = { -0.708, 0.298 };\n   cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrmv(case 887) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrmv(case 887) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 113;\n   int uplo = 122;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   double A[] = { -0.345, -0.851 };\n   double X[] = { -0.708, 0.298 };\n   int incX = -1;\n   double x_expected[] = { -0.009338, -0.705318 };\n   cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrmv(case 888) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrmv(case 888) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 113;\n   int uplo = 122;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   double A[] = { -0.345, -0.851 };\n   double X[] = { -0.708, 0.298 };\n   int incX = -1;\n   double x_expected[] = { -0.708, 0.298 };\n   cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrmv(case 889) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrmv(case 889) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 113;\n   int uplo = 121;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   double A[] = { -0.345, -0.851 };\n   double X[] = { -0.708, 0.298 };\n   int incX = -1;\n   double x_expected[] = { -0.009338, -0.705318 };\n   cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrmv(case 890) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrmv(case 890) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 113;\n   int uplo = 121;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   double A[] = { -0.345, -0.851 };\n   double X[] = { -0.708, 0.298 };\n   int incX = -1;\n   double x_expected[] = { -0.708, 0.298 };\n   cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrmv(case 891) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrmv(case 891) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 113;\n   int uplo = 122;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   double A[] = { -0.345, -0.851 };\n   double X[] = { -0.708, 0.298 };\n   int incX = -1;\n   double x_expected[] = { -0.009338, -0.705318 };\n   cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrmv(case 892) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrmv(case 892) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 113;\n   int uplo = 122;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   double A[] = { -0.345, -0.851 };\n   double X[] = { -0.708, 0.298 };\n   int incX = -1;\n   double x_expected[] = { -0.708, 0.298 };\n   cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrmv(case 893) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrmv(case 893) imag\");\n     };\n   };\n  };\n\n\n}\n", "meta": {"hexsha": "82bc18d37ff5dda959607b53d8b24f682c04e86c", "size": 39589, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/cblas/test_trmv.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/cblas/test_trmv.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/cblas/test_trmv.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 22.7522988506, "max_line_length": 81, "alphanum_fraction": 0.4937482634, "num_tokens": 16010, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234991142019, "lm_q2_score": 0.03622005885596484, "lm_q1q2_score": 0.01585799290644086}}
{"text": "#pragma once\r\n/****************************************************************************\r\n *\r\n *  nc.h\r\n *      ($\\nativecoin-cpp\\src)\r\n *\r\n *  by icedac \r\n *\r\n ***/\r\n#ifndef ___NATIVECOIN__NATIVECOIN__NC_H_\r\n#define ___NATIVECOIN__NATIVECOIN__NC_H_\r\n\r\n#include <string>\r\n#include <vector>\r\n#include <unordered_map>\r\n#include <set>\r\n#include <iostream>\r\n#include <sstream>\r\n\r\n#define GSL_THROW_ON_CONTRACT_VIOLATION\r\n#include <gsl/gsl>\r\n\r\n#include <utility>\r\n#include <stdio.h>\r\n#include <tuple>\r\n#include <iomanip>\r\n\r\n#include \"platform.h\"\r\n\r\nnamespace nc {\r\n    typedef unsigned char byte;\r\n    typedef std::int32_t int32;\r\n    typedef std::int64_t int64;\r\n    typedef std::uint32_t uint32;\r\n    typedef std::uint64_t uint64;\r\n    using string = std::string;\r\n    template < typename T >\r\n    using vector = std::vector<T>;\r\n    template < typename T >\r\n    using set = std::set<T>;\r\n    using stringstream = std::stringstream;\r\n    using ostringstream = std::ostringstream;\r\n\r\n    template < typename K, typename T >\r\n    using unordered_map = std::unordered_map< K, T>;\r\n\r\n    typedef uint32 difficulty_t;\r\n    typedef uint64 nonce_t;\r\n    typedef uint64 timestamp_t;\r\n    typedef uint32 blockindex_t;\r\n}\r\n\r\nnamespace nc {\r\n\r\n    class coin {\r\n    public:\r\n        static const auto SATOSHI_PER_COIN = 1000000;\r\n        explicit inline coin() noexcept : satoshi(0) {}\r\n        explicit inline coin(int32 amount) noexcept : satoshi(amount*SATOSHI_PER_COIN) {}\r\n\r\n        inline coin(const coin& c) = default;\r\n        inline coin& operator = (const coin& rhs) = default;\r\n        inline coin(coin&& c) = default;\r\n        inline coin& operator = (coin&& rhs) = default;\r\n\r\n\r\n        inline operator int32() const {\r\n            return get();\r\n        }\r\n\r\n        inline coin& operator += (const coin& rhs) {\r\n            satoshi += rhs.get_as_satoshi();\r\n            return *this;\r\n        }\r\n\r\n        inline coin& operator -= (const coin& rhs) {\r\n            satoshi -= rhs.get_as_satoshi();\r\n            return *this;\r\n        }\r\n\r\n        inline coin operator + (const coin& rhs) {\r\n            return coin::from_satoshi(this->get_as_satoshi() + rhs.get_as_satoshi());\r\n        }\r\n        inline coin operator - (const coin& rhs) {\r\n            return coin::from_satoshi(this->get_as_satoshi() - rhs.get_as_satoshi());\r\n        }\r\n\r\n        inline bool operator == (const coin& rhs) const {\r\n            return this->satoshi == rhs.satoshi;\r\n        }\r\n        inline bool operator != (const coin& rhs) const {\r\n            return !(*this == rhs);\r\n        }\r\n\r\n        inline int32 get() const {\r\n            return (int32)(satoshi / SATOSHI_PER_COIN);\r\n        }\r\n\r\n        inline int64 get_as_satoshi() const { return satoshi; }\r\n\r\n        inline int64 get_satoshi() const {\r\n            return satoshi % SATOSHI_PER_COIN;\r\n        }\r\n\r\n        inline string as_string() const {\r\n\r\n            int64 satoshi = get_satoshi();\r\n\r\n            ostringstream ss;\r\n            ss << get() << \".\";\r\n            if (satoshi)\r\n                ss << std::setfill('0') << std::setw(6) << satoshi;\r\n            else\r\n                ss << \"00\";\r\n\r\n            return ss.str();\r\n        }\r\n\r\n        static inline coin from_satoshi(int64 satoshi) {\r\n            coin c{ 0 };\r\n            c.satoshi = satoshi;\r\n            return c;\r\n        }\r\n\r\n\r\n    private:\r\n        int64\t\tsatoshi;\r\n    };\r\n}\r\n\r\n\r\n#endif// ___NATIVECOIN__NATIVECOIN__NC_H_\r\n", "meta": {"hexsha": "e22963c02f96538f0a6f6173866f8371808a83b9", "size": 3446, "ext": "h", "lang": "C", "max_stars_repo_path": "src/nc.h", "max_stars_repo_name": "icedac/nativecoin-cpp", "max_stars_repo_head_hexsha": "cc5ea9c9dfc7e8974f3b580cbb3767354d0b9b78", "max_stars_repo_licenses": ["BSL-1.0", "BSD-3-Clause", "OpenSSL", "MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/nc.h", "max_issues_repo_name": "icedac/nativecoin-cpp", "max_issues_repo_head_hexsha": "cc5ea9c9dfc7e8974f3b580cbb3767354d0b9b78", "max_issues_repo_licenses": ["BSL-1.0", "BSD-3-Clause", "OpenSSL", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/nc.h", "max_forks_repo_name": "icedac/nativecoin-cpp", "max_forks_repo_head_hexsha": "cc5ea9c9dfc7e8974f3b580cbb3767354d0b9b78", "max_forks_repo_licenses": ["BSL-1.0", "BSD-3-Clause", "OpenSSL", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9097744361, "max_line_length": 90, "alphanum_fraction": 0.5464306442, "num_tokens": 812, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3007455664065234, "lm_q2_score": 0.052618957433256106, "lm_q1q2_score": 0.015824918156985352}}
{"text": "#ifndef QDM_IJK_H\n#define QDM_IJK_H 1\n\n#include <stddef.h>\n\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_vector.h>\n#include <hdf5.h>\n\ntypedef struct {\n  size_t size1;\n  size_t size2;\n  size_t size3;\n\n  double *data;\n  bool owner;\n} qdm_ijk;\n\ntypedef struct {\n  qdm_ijk ijk;\n} qdm_ijk_view;\n\nqdm_ijk *\nqdm_ijk_alloc(\n    size_t size1,\n    size_t size2,\n    size_t size3\n);\n\nqdm_ijk *\nqdm_ijk_calloc(\n    size_t size1,\n    size_t size2,\n    size_t size3\n);\n\nvoid\nqdm_ijk_free(qdm_ijk *t);\n\nqdm_ijk_view\nqdm_ijk_view_array(\n    double *base,\n    size_t size1,\n    size_t size2,\n    size_t size3\n);\n\ngsl_vector_view\nqdm_ijk_get_k(\n    qdm_ijk *t,\n    size_t i,\n    size_t j\n);\n\ngsl_matrix_view\nqdm_ijk_get_ij(\n    qdm_ijk *t,\n    size_t k\n);\n\ndouble\nqdm_ijk_get(\n    qdm_ijk *t,\n    size_t i,\n    size_t j,\n    size_t k\n);\n\ngsl_matrix *\nqdm_ijk_cov(\n    qdm_ijk *t\n);\n\nint\nqdm_ijk_write(\n    hid_t id,\n    const char *name,\n    const qdm_ijk *t\n);\n\nint\nqdm_ijk_read(\n    hid_t id,\n    const char *name,\n    qdm_ijk **t\n);\n\n#endif /* QDM_IJK_H */\n", "meta": {"hexsha": "1dd700ef458f473b08896e0b9417a1d5454e3a3b", "size": 1043, "ext": "h", "lang": "C", "max_stars_repo_path": "include/qdm/ijk.h", "max_stars_repo_name": "calebcase/qdm", "max_stars_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/qdm/ijk.h", "max_issues_repo_name": "calebcase/qdm", "max_issues_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-03-06T18:09:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-22T20:22:53.000Z", "max_forks_repo_path": "include/qdm/ijk.h", "max_forks_repo_name": "calebcase/qdm", "max_forks_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 11.7191011236, "max_line_length": 27, "alphanum_fraction": 0.656759348, "num_tokens": 385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4035668537353746, "lm_q2_score": 0.0390482910487942, "lm_q1q2_score": 0.015758595962305066}}
{"text": "/**\n *\n * @file\n *\n *  PLASMA is a software package provided by:\n *  University of Tennessee, US,\n *  University of Manchester, UK.\n *\n **/\n#ifndef ICL_CORE_LAPACK_H\n#define ICL_CORE_LAPACK_H\n\n#ifdef PLASMA_WITH_MKL\n    #include <mkl_cblas.h>\n    #include <mkl_lapacke.h>\n\n    // MKL LAPACKE doesn't provide LAPACK_GLOBAL macro, so define it here.\n    // MKL provides all 3 name manglings (foo, foo_, FOO); pick foo_.\n    #ifndef LAPACK_GLOBAL\n    #define LAPACK_GLOBAL(lcname,UCNAME)  lcname##_\n    #endif\n#else\n    #include <cblas.h>\n    #include <lapacke.h>\n\n    // Intel mkl_cblas.h does: typedef enum {...} CBLAS_ORDER;\n    // Netlib    cblas.h does: enum CBLAS_ORDER {...};\n    // OpenBLAS  cblas.h does: typedef enum CBLAS_ORDER {...} CBLAS_ORDER;\n    // We use (CBLAS_ORDER), so add these typedefs for Netlib.\n    #ifndef OPENBLAS_VERSION\n    typedef enum CBLAS_ORDER CBLAS_ORDER;\n    typedef enum CBLAS_TRANSPOSE CBLAS_TRANSPOSE;\n    typedef enum CBLAS_UPLO CBLAS_UPLO;\n    typedef enum CBLAS_DIAG CBLAS_DIAG;\n    typedef enum CBLAS_SIDE CBLAS_SIDE;\n    #endif\n#endif\n\n#include \"core_lapack_s.h\"\n#include \"core_lapack_d.h\"\n#include \"core_lapack_c.h\"\n#include \"core_lapack_z.h\"\n\n#endif // ICL_CORE_LAPACK_H\n", "meta": {"hexsha": "6c50c72cee8ca5dbee28cd601b96453d236a8e02", "size": 1215, "ext": "h", "lang": "C", "max_stars_repo_path": "include/core_lapack.h", "max_stars_repo_name": "NLAFET/plasma", "max_stars_repo_head_hexsha": "92648b6c0ede8beb70f40b97a6ab45ae80820ca3", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2018-06-07T11:21:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T06:55:50.000Z", "max_issues_repo_path": "include/core_lapack.h", "max_issues_repo_name": "NLAFET/plasma", "max_issues_repo_head_hexsha": "92648b6c0ede8beb70f40b97a6ab45ae80820ca3", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/core_lapack.h", "max_forks_repo_name": "NLAFET/plasma", "max_forks_repo_head_hexsha": "92648b6c0ede8beb70f40b97a6ab45ae80820ca3", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0, "max_line_length": 74, "alphanum_fraction": 0.7020576132, "num_tokens": 378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167302036300954, "lm_q2_score": 0.03567855164675543, "lm_q1q2_score": 0.0157582536680001}}
{"text": "\n/*\n* -----------------------------------------------------------------\n*  Binary Search Tree Library --- bst_lib.c\n*  Version: 1.6180\n*  Date: Mar 12, 2010\n* ----------------------------------------------------------------- \n*  Programmer: Americo Barbosa da Cunha Junior\n*              americo.cunhajr@gmail.com\n* -----------------------------------------------------------------\n*  Copyright (c) 2010 by Americo Barbosa da Cunha Junior\n*\n*  This program is free software: you can redistribute it and/or\n*  modify it under the terms of the GNU General Public License as\n*  published by the Free Software Foundation, either version 3 of\n*  the License, or (at your option) any later version.\n*\n*  This program is distributed in the hope that it will be useful,\n*  but WITHOUT ANY WARRANTY; without even the implied warranty of\n*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n*  GNU General Public License for more details.\n*\n*  A copy of the GNU General Public License is available in\n*  LICENSE.txt or http://www.gnu.org/licenses/.\n* -----------------------------------------------------------------\n*  This is the implementation file of a library\n*  to work with binary search trees.\n* -----------------------------------------------------------------\n*/\n\n\n\n\n#include <stdlib.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_errno.h>\n\n#include \"../include/bst_lib.h\"\n\n\n\n\n/*\n*------------------------------------------------------------\n*   bst_leaf_alloc\n*\n*   This function allocates a struct leaf.\n*\n*   Input:\n*   void\n*\n*   Output:\n*   leaf - pointer to a struct leaf\n*\n*   last update: May 10, 2009\n*------------------------------------------------------------\n*/\n\nbst_leaf *bst_leaf_alloc()\n{\n    bst_leaf *leaf = NULL;\n    \n    /* memory allocation for bst_leaf */\n    leaf = (bst_leaf *) malloc(sizeof(bst_leaf));\n    if ( leaf == NULL )\n        return NULL;\n    \n    /* setting bst_leaf elements equal to NULL */\n    leaf->phi  = NULL;\n    leaf->Rphi = NULL;\n    leaf->A    = NULL;\n    leaf->L    = NULL;\n    \n    return leaf;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n\n/*\n*------------------------------------------------------------\n*   bst_node_alloc\n*\n*   This function allocates a struct node.\n*\n*   Input:\n*   void\n*\n*   Output:\n*   node - pointer to a struct node\n*\n*   last update: May 10, 2009\n*------------------------------------------------------------\n*/\n\nbst_node* bst_node_alloc()\n{\n    bst_node *node = NULL;\n    \n    /* memory allocation for bst_node */\n    node = (bst_node *) malloc(sizeof(bst_node));\n    if ( node == NULL )\n        return NULL;\n    \n    /* setting bst_node elements equal to NULL */\n    node->v      = NULL;\n    node->r_node = NULL;\n    node->l_node = NULL;\n    node->r_leaf = NULL;\n    node->l_leaf = NULL;\n\n    return node;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n\n/*\n*------------------------------------------------------------\n*   bst_leaf_free\n*\n*   This function frees the memory used by a struct leaf.\n*\n*   Input:\n*   leaf - pointer to a struct leaf\n*\n*   Output:\n*   void\n*\n*   last update: May 9, 2009\n*------------------------------------------------------------\n*/\n\nvoid bst_leaf_free(void **leaf_bl)\n{\n    bst_leaf *leaf = NULL;\n    \n    /* checking if leaf_bl is NULL */\n    if ( *leaf_bl == NULL )\n        return;\n    \n    leaf = (bst_leaf *) (*leaf_bl);\n    \n    /* releasing bst_leaf elements */\n    if( leaf->phi != NULL )\n    {\n        gsl_vector_free(leaf->phi);\n        leaf->phi = NULL;\n    }\n    \n    if( leaf->Rphi != NULL )\n    {\n        gsl_vector_free(leaf->Rphi);\n        leaf->Rphi = NULL;\n    }\n    \n    if( leaf->A != NULL )\n    {\n        gsl_matrix_free(leaf->A);\n        leaf->A = NULL;\n    }\n    \n    if( leaf->L != NULL )\n    {\n        gsl_matrix_free(leaf->L);\n        leaf->L = NULL;\n    }\n    \n    /* releasing allocated memory by bst_leaf */\n    free(*leaf_bl);\n    *leaf_bl = NULL;\n    \n    return;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n\n/*\n*------------------------------------------------------------\n*   bst_node_free\n*\n*   This function frees the memory used by a struct node.\n*\n*   Input:\n*   node - pointer to a struct node\n*\n*   Output:\n*   void\n*\n*   last update: Feb 19, 2010\n*------------------------------------------------------------\n*/\n\nvoid bst_node_free(void **node_bl)\n{\n    bst_node *node = NULL;\n    \n    /* checking if node_bl is NULL */\n    if ( *node_bl == NULL )\n        return;\n    \n    node = (bst_node *) (*node_bl);\n    \n    /* releasing allocated memory by bst_node elements */\n    if( node->l_leaf != NULL )\n    {\n        bst_leaf_free((void **)&(node->l_leaf));\n        node->l_leaf = NULL;\n    }\n    \n    if( node->r_leaf != NULL )\n    {\n        bst_leaf_free((void **)&(node->r_leaf));\n        node->r_leaf = NULL;\n    }\n    \n    if( node->l_node != NULL )\n    {\n        bst_node_free((void **)&(node->l_node));\n        node->l_node = NULL;\n    }\n    \n    if( node->r_node != NULL )\n    {\n        bst_node_free((void **)&(node->r_node));\n        node->r_node = NULL;\n    }\n    \n    if( node->v != NULL )\n    {\n        gsl_vector_free(node->v);\n        node->v = NULL;\n    }\n    \n    /* releasing allocated memory by bst_node */\n    free(*node_bl);\n    *node_bl = NULL;\n\n    return;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n\n/*\n*------------------------------------------------------------\n*   bst_leaf_set\n*\n*   This function sets the bst_leaf elements equal to\n*   the input elements and returns GSL_SUCCESS if\n*   there is no problem during its execution.\n*\n*   Input:\n*   phi  - composition\n*   Rphi - reaction mapping\n*   A    - mapping gradient matrix\n*   L    - ellipsoid Cholesky matrix\n*\n*   Output:\n*   leaf - pointer to a struct leaf\n*   success or error\n*\n*   last update: Feb 22, 2009\n*------------------------------------------------------------\n*/\n\nint bst_leaf_set(gsl_vector *phi,gsl_vector *Rphi,\n                    gsl_matrix *A,gsl_matrix *L,bst_leaf *leaf)\n{\n    /* checking if leaf is NULL */\n    if ( leaf == NULL )\n        return GSL_EFAILED;\n    \n    /* setting phi equal to the input vector phi */\n    if ( leaf->phi == NULL )\n        leaf->phi = gsl_vector_calloc(phi->size);\n    \n    gsl_vector_memcpy(leaf->phi,phi);\n    \n    /* setting Rphi equal to the input vector Rphi */\n    if ( leaf->Rphi == NULL )\n        leaf->Rphi = gsl_vector_calloc(Rphi->size);\n    \n    gsl_vector_memcpy(leaf->Rphi,Rphi);\n    \n    /* setting A equal to the input matrix A */\n    if ( leaf->A == NULL )\n        leaf->A = gsl_matrix_calloc(A->size1,A->size2);\n    \n    gsl_matrix_memcpy(leaf->A,A);\n    \n    /* setting L equal to the input matrix L */\n    if ( leaf->L == NULL )\n        leaf->L = gsl_matrix_calloc(L->size1,L->size2);\n    \n    gsl_matrix_memcpy(leaf->L,L);\n    \n    return GSL_SUCCESS;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n\n/*\n*------------------------------------------------------------\n*   bst_cutplane\n*\n*   This function compute the vector ( v = phi_r - phi_l )\n*   and the scalar ( a = (|phi_r|^2-|phi_l|^2)/2 )\n*   which define a cutting plane used to search any\n*   information in the binary search tree.\n*   \n*   Input:\n*   phi_l - left  composition\n*   phi_r - right compositon\n*\n*   Output:\n*   v    - cutting plane normal vector\n*   a    - cutting plane scalar\n*\n*   last update: Feb 27, 2009\n*------------------------------------------------------------\n*/\n\ndouble bst_cutplane(gsl_vector *phi_l,gsl_vector *phi_r,gsl_vector *v)\n{\n    double a1, a2;\n\n    /* v := phi_r */\n    gsl_vector_memcpy(v,phi_r);\n    \n    /* v := phi_r - phi_l */\n    gsl_vector_sub(v,phi_l);\n    \n    /* a1 := |phi_r|^2 */\n    gsl_blas_ddot(phi_r,phi_r,&a1);\n\n    /* a2 := |phi_l|^2 */\n    gsl_blas_ddot(phi_l,phi_l,&a2);\n    \n    return 0.5*(a1-a2);\n}\n/*------------------------------------------------------------*/\n\n\n\n\n\n/*\n*------------------------------------------------------------\n*   bst_node_set\n*\n*   This function set the bst_node elements equal to\n*   the input elements and define the vector and\n*   scalar to do the search for a information.\n*\n*   Input:\n*   l_leaf - left  leaf\n*   r_leaf - right leaf\n*\n*   Output:\n*   node - pointer to a struct node\n*   success or error\n*\n*   last update: Feb 27, 2009\n*------------------------------------------------------------\n*/\n\nint bst_node_set(bst_leaf *l_leaf,bst_leaf *r_leaf,bst_node *node)\n{\n    /* checking if node is NULL */\n    if ( node == NULL )\n        return GSL_EFAILED;\n    \n    /* memory allocation for v */\n    if ( node->v == NULL )\n    \tnode->v = gsl_vector_calloc(r_leaf->phi->size);\n    \n    /* setting v and a */\n    node->a = bst_cutplane(l_leaf->phi,r_leaf->phi,node->v);\n\n    /* setting leaf elements equal to the input leaves */\n    node->l_leaf = l_leaf;\n    node->r_leaf = r_leaf;\n    \n    /* setting node elements equal to NULL */\n    node->l_node = NULL;\n    node->r_node = NULL;\n    \n    return GSL_SUCCESS;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n\n/*\n*------------------------------------------------------------\n*   bst_node_add\n*\n*   This function adds a new node to a given side\n*   of a old node and returns GSL_SUCCESS if\n*   there is no problem during its execution.\n*\n*   Input:\n*   side     - new node side\n*   old_node - pointer to the old node\n*   new_node - pointer to the new node\n*\n*   Output:\n*   success or error\n*\n*   last update: Feb 22, 2009\n*------------------------------------------------------------\n*/\n\nint bst_node_add(int side,bst_node *old_node,bst_node *new_node)\n{\n    if( side == RIGHT )\n    {\n        if( old_node->r_node != NULL )\n            return GSL_EFAILED;\n        else\n        {\n            /* adding a new right node */\n            old_node->r_node = new_node;\n            old_node->r_leaf = NULL;\n            \n            return GSL_SUCCESS;\n        }\n    }\n    else if( side == LEFT )\n    {\n        if( old_node->l_node != NULL )\n            return GSL_EFAILED;\n        else\n        {\n            /* adding a new left node */\n            old_node->l_node = new_node;\n            old_node->l_leaf = NULL;\n            \n            return GSL_SUCCESS;\n        }\n    }\n    else\n        return GSL_EFAILED;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n\n/*\n*------------------------------------------------------------\n*   bst_search\n*\n*   This function searchs for a near composition phi0 in the\n*   binary search tree.\n*\n*   Input:\n*   root     - binary tree root\n*   phi      - composition\n*\n*   Output:\n*   end_leaf - leaf with the near composition\n*   end_node - node with the near composition\n*   side     - near compositon leaf side\n*\n*   last update: Feb 3, 2009\n*------------------------------------------------------------\n*/\n\nint bst_search(bst_node *root,gsl_vector *phi,\n                        bst_node **end_node,bst_leaf **end_leaf)\n{\n    double dot;\n    \n    if( root == NULL )\n    {\n        *end_leaf = NULL;\n        *end_node = NULL;\n        \n        return GSL_EFAILED;\n    }\n    \n    /* dot := v^T*phi */\n    gsl_blas_ddot(root->v,phi,&dot);\n    \n    /* if dot > a then right node else left node */\n    if( dot > root->a )\n    {\n        /* extern node */\n        if( root->r_node == NULL )\n        {\n            *end_leaf = root->r_leaf;\n            *end_node = root;\n            \n            return RIGHT;\n        }\n        else\n            return bst_search(root->r_node,phi,end_node,end_leaf);\n    }\n    else\n    {\n        /* extern node */\n        if( root->l_node == NULL )\n        {\n            *end_leaf = root->l_leaf;\n            *end_node = root;\n            \n            return LEFT;\n        }\n        else\n            return bst_search(root->l_node,phi,end_node,end_leaf);\n    }\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*\n*------------------------------------------------------------\n*   bst_height\n*\n*   This function computes the binary search tree height.\n*\n*   Input:\n*   root - binary tree root\n*\n*   Output:\n*   height - binary search tree height\n*\n*   last update: Nov 2, 2009\n*------------------------------------------------------------\n*/\n\nint bst_height(bst_node *root)\n{\n    int l_tree_height = 0;\n    int r_tree_height = 0;\n    \n    if ( root != NULL )\n    {\n        l_tree_height = bst_height(root->l_node);\n        r_tree_height = bst_height(root->r_node);\n        \n        if ( l_tree_height > r_tree_height )\n            return l_tree_height + 1;\n        else\n            return r_tree_height + 1;\n    }\n    else\n        return 0;\n    \n}\n/*------------------------------------------------------------*/\n\n", "meta": {"hexsha": "fddb9d328bd60e2b2970c6cbfe137d316e4631d7", "size": 12674, "ext": "c", "lang": "C", "max_stars_repo_path": "CRFlowLib-1.0/src/bst_lib.c", "max_stars_repo_name": "americocunhajr/CRFlowLib", "max_stars_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-29T12:56:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-29T12:56:14.000Z", "max_issues_repo_path": "CRFlowLib-1.0/src/bst_lib.c", "max_issues_repo_name": "americocunhajr/CRFlowLib", "max_issues_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CRFlowLib-1.0/src/bst_lib.c", "max_forks_repo_name": "americocunhajr/CRFlowLib", "max_forks_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-15T03:57:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-30T01:44:13.000Z", "avg_line_length": 22.1573426573, "max_line_length": 70, "alphanum_fraction": 0.4674925043, "num_tokens": 2997, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167941228964, "lm_q2_score": 0.034100426571226035, "lm_q1q2_score": 0.01572086933608986}}
{"text": "// Copyright (c) 2005 - 2010 Marc de Kamps\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n//\n//    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n//    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation \n//      and/or other materials provided with the distribution.\n//    * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software \n//      without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED \n// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY \n// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \n// USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING \n// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n//      If you use this software in work leading to a scientific publication, you should cite\n//      the 'currently valid reference', which can be found at http://miind.sourceforge.net\n#ifndef _CODE_LIBS_NUMTOOLSLIB_NODE_EXSTATEDVINTEGRATOR_INCLUDE_GUARD\n#define _CODE_LIBS_NUMTOOLSLIB_NODE_EXSTATEDVINTEGRATOR_INCLUDE_GUARD\n\n#include <limits>\n#include <vector>\n#include <gsl/gsl_odeiv.h>\n#include <gsl/gsl_errno.h>\n#include \"AbstractDVIntegratorCode.h\"\n#include \"BasicDefinitions.h\"\n#include \"DVIntegratorException.h\"\n#include \"DVIntegratorStateParameter.h\"\n\nusing std::vector;\nusing std::istream;\nusing std::ostream;\nusing std::string;\n\n\nusing std::numeric_limits;\n\nnamespace NumtoolsLib\n{\n\n\t//! This is a wrapper class for the GSL numerical ODE solvers. Examples of its usage can be\n\t//! found in DynamicLib, for example in the Wilson-Cowan Algorithm. Unlike DVIntegrator it operates on a \n\t//! state vector that is maintained by another class.\n\t//!\n\t//! The ExStateDVIntegrator is typically member of a class which requires the solution of a system\n\t//! of ODEs. In the source file of that class a function must be defined whose return type is int\n\t//! and whose arguments are given in the typedef for Function. A pointer to this function, (i.e the\n\t//! function name must be given in the constructor. If the GSL\n\t//! solver requires a Jacobian, then Derivative must also be defined, but for simple solvers,\n\t//! such as 4-th order Runge-Kutta this is not required and the derivative argument can be left out.\n\t//! Often, the ODE system requires parameters that need to be updated during the evolution of the system.\n\t//! This parameter can be a single number, a vector or anything else. The type of the parameter must\n\t//! be provided using the template argument. The class of the parameter must have a default constructor.\n\ttemplate <class ParameterObject=double>\n\tclass ExStateDVIntegrator : public AbstractDVIntegrator<ParameterObject>\n\t{\n\tpublic:\n\n\t\t//! Constructor\n\t\tExStateDVIntegrator\n\t\t(\n\t\t\tNumber,\t\t\t\t\t\t//<! maximum number of integrations\t\t\t\t\t\t\t\n\t\t\tdouble*,\t\t\t\t\t//<! initial state\n\t\t\tNumber,\t\t\t\t\t\t//<! state size\n\t\t\tTimeStep,\t\t\t\t\t//<! initial time step\n\t\t\tTime,\t\t\t\t\t\t//<! initial time\n\t\t\tconst Precision&,\t\t\t//<! absolute and relative precision\n\t\t\tFunction,\t\t\t\t\t//<! dydt\n\t\t\tDerivative deravative = 0,  //<! Jacobian, if available\n\t\t\tconst gsl_odeiv_step_type*\tp_step_algorithm = gsl_odeiv_step_rkf45 //<! gsl integrator object\n\t\t);\n\n\t\t//! copy constructor must be defined, because the state of the integrator\n\t\t//! must be handled correctly\n\t\tExStateDVIntegrator(const ExStateDVIntegrator&);\n\n\t\t//! Ditto for copy operator\n\t\tExStateDVIntegrator& operator=(const ExStateDVIntegrator&);\n\n\t\t//! virtual destructor\n\t\tvirtual ~ExStateDVIntegrator();\n\n\t\t//! Set a new state\n\t\tbool Reconfigure\n\t\t(\n\t\t\tconst DVIntegratorStateParameter<ParameterObject>&\n\t\t);\n\n\t\t//! Current time\n\t\tTime CurrentTime() const;\n\n\t\t//! Only use if for efficiency reasons, acces to internal state is necessary\n\t\tconst double* BeginState() const;\n\n\t\t//! Ditto\n\t\tconst double* EndState  () const;\n\n\t\t//! streaming tag\n\t\tvirtual string Tag () const;\n\n\t\t//! Direct access to the parameter object for performance reasons\n\t\tParameterObject& Parameter();\n\n\tprivate:\n\n\n\t}; // end of NodeIntegrator\n\n} // end of namespace\n\n#endif // include guard\n", "meta": {"hexsha": "3e59e2a1227718255cc55e08b8ac7417542bf84f", "size": 4879, "ext": "h", "lang": "C", "max_stars_repo_path": "libs/NumtoolsLib/ExStateDVIntegrator.h", "max_stars_repo_name": "dekamps/miind", "max_stars_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2015-09-15T17:28:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T20:26:47.000Z", "max_issues_repo_path": "libs/NumtoolsLib/ExStateDVIntegrator.h", "max_issues_repo_name": "dekamps/miind", "max_issues_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41.0, "max_issues_repo_issues_event_min_datetime": "2015-08-25T07:50:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T16:20:37.000Z", "max_forks_repo_path": "libs/NumtoolsLib/ExStateDVIntegrator.h", "max_forks_repo_name": "dekamps/miind", "max_forks_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-14T20:52:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T12:18:18.000Z", "avg_line_length": 42.798245614, "max_line_length": 163, "alphanum_fraction": 0.7511785202, "num_tokens": 1127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.03622005937613705, "lm_q1q2_score": 0.015718834423340138}}
{"text": "#include <stdlib.h>\n#include <stddef.h>\n#include <assert.h>\n#include <stdio.h>\n#include <string.h>\n#include <cblas.h>\n#include \"LCP_Solver.h\"\n#include \"debug.h\"\n\nvoid numericsError(char * functionName, char* message)\n{\n  char output[200] = \"Numerics error - \";\n  strcat(output, functionName);\n  strcat(output, message);\n  strcat(output, \".\\n\");\n  fprintf(stderr, \"%s\", output);\n  exit(EXIT_FAILURE);\n}\n\nvoid prodNumericsMatrix(int sizeX, int sizeY, double alpha, const NumericsMatrix* const A, const double* const x, double beta, double* y)\n{\n  assert(A);\n  assert(x);\n  assert(y);\n  assert(A->size0 == sizeY);\n  assert(A->size1 == sizeX);\n  cblas_dgemv(CblasColMajor, CblasNoTrans, sizeY, sizeX, alpha, A->matrix0, sizeY, x, 1, beta, y, 1);\n}\n\nvoid deleteSolverOptions(SolverOptions* op)\n{\n  if(op)\n  {\n    if (op->iparam != NULL)\n      free(op->iparam);\n    op->iparam = NULL;\n    if (op->dparam != NULL)\n      free(op->dparam);\n    op->dparam = NULL;\n  }\n}\n\nvoid lcp_lexicolemke(LinearComplementarityProblem* problem, double *zlem , double *wlem , int *info , SolverOptions* options)\n{\n  /* matrix M of the lcp */\n  double * M = problem->M->matrix0;\n  assert(M);\n  /* size of the LCP */\n  int dim = problem->size;\n  assert(dim>0);\n  int dim2 = 2 * (dim + 1);\n\n  int i, drive, block, Ifound;\n  int ic, jc;\n  int ITER;\n  int nobasis;\n  int itermax = options->iparam[0];\n\n  i=0;\n  int n = problem->size;\n  double *q = problem->q;\n  \n  while ((i < (n - 1)) && (q[i] >= 0.)) \n    i++;\n  \n  if ((i == (n - 1)) && (q[n - 1] >= 0.))\n  {\n    /* TRIVIAL CASE : q >= 0\n     * z = 0 and w = q is solution of LCP(q,M)\n     */\n    for (int j = 0 ; j < n; j++)\n    {\n      zlem[j] = 0.0;\n      wlem[j] = q[j];\n    }\n    *info = 0;\n    options->iparam[1] = 0;   /* Number of iterations done */\n    options->dparam[1] = 0.0; /* Error */\n    if (options->verboseMode > 0)\n      printf(\"lcp_lexicolemke: found trivial solution for the LCP (positive vector q => z = 0 and w = q). \\n\");\n    return ;\n  }\n  \n  double z0, zb, dblock;\n  double pivot, tovip;\n  double tmp;\n  int *basis;\n  double** A;\n\n  /*output*/\n  options->iparam[1] = 0;\n\n  /* Allocation */\n  basis = (int *)malloc(dim * sizeof(int));\n  A = (double **)malloc(dim * sizeof(double*));\n\n  for (ic = 0 ; ic < dim; ++ic)\n    A[ic] = (double *)malloc(dim2 * sizeof(double));\n\n  /* construction of A matrix such that\n   * A = [ q | Id | -d | -M ] with d = (1,...1)\n   */\n  /* We need to init only the part corresponding to Id */\n  for (ic = 0 ; ic < dim; ++ic)\n    for (jc = 1 ; jc <= dim; ++jc)\n      A[ic][jc] = 0.0;\n\n  for (ic = 0 ; ic < dim; ++ic)\n    for (jc = 0 ; jc < dim; ++jc)\n      A[ic][jc + dim + 2] = -M[dim * jc + ic];\n\n  assert(problem->q);\n\n  for (ic = 0 ; ic < dim; ++ic) A[ic][0] = problem->q[ic];\n\n  for (ic = 0 ; ic < dim; ++ic) A[ic][ic + 1 ] =  1.0;\n  for (ic = 0 ; ic < dim; ++ic) A[ic][dim + 1] = -1.0;\n\n  DEBUG_PRINT(\"total matrix\\n\");\n  DEBUG_EXPR_WE(for (unsigned int i = 0; i < dim; ++i)\n      { for(unsigned int j = 0 ; j < dim2; ++j)\n      { DEBUG_PRINTF(\"%1.2e \", A[i][j]) }\n      DEBUG_PRINT(\"\\n\")});\n  /* End of construction of A */\n\n  Ifound = 0;\n\n\n  for (ic = 0 ; ic < dim  ; ++ic) basis[ic] = ic + 1;\n\n  drive = dim + 1;\n  block = 0;\n  z0 = A[block][0];\n  ITER = 0;\n\n  /* Start research of argmin lexico */\n  /* With this first step the covering vector enter in the basis */\n  for (ic = 1 ; ic < dim ; ++ic)\n  {\n    zb = A[ic][0];\n    if (zb < z0)\n    {\n      z0    = zb;\n      block = ic;\n    }\n    else if (zb == z0)\n    {\n      for (jc = 0 ; jc < dim ; ++jc)\n      {\n        dblock = A[block][1 + jc] - A[ic][1 + jc];\n        if (dblock < 0)\n        {\n          break;\n        }\n        else if (dblock > 0)\n        {\n          block = ic;\n          break;\n        }\n      }\n    }\n  }\n\n  /* Stop research of argmin lexico */\n  DEBUG_PRINTF(\"Pivoting %i and %i\\n\", block, drive);\n\n  pivot = A[block][drive];\n  tovip = 1.0 / pivot;\n\n  /* Pivot < block , drive > */\n  A[block][drive] = 1;\n  for (ic = 0       ; ic < drive ; ++ic) A[block][ic] = A[block][ic] * tovip;\n  for (ic = drive + 1 ; ic < dim2  ; ++ic) A[block][ic] = A[block][ic] * tovip;\n\n  /* */\n\n  for (ic = 0 ; ic < block ; ++ic)\n  {\n    tmp = A[ic][drive];\n    for (jc = 0 ; jc < dim2 ; ++jc) A[ic][jc] -=  tmp * A[block][jc];\n  }\n  for (ic = block + 1 ; ic < dim ; ++ic)\n  {\n    tmp = A[ic][drive];\n    for (jc = 0 ; jc < dim2 ; ++jc) A[ic][jc] -=  tmp * A[block][jc];\n  }\n\n   nobasis = basis[block];\n  basis[block] = drive;\n\n  DEBUG_EXPR_WE( DEBUG_PRINT(\"new basis: \")\n      for (unsigned int i = 0; i < dim; ++i)\n      { DEBUG_PRINTF(\"%i \", basis[i])}\n      DEBUG_PRINT(\"\\n\"));\n  DEBUG_PRINT(\"total matrix\\n\");\n  DEBUG_EXPR_WE(for (unsigned int i = 0; i < dim; ++i)\n      { for(unsigned int j = 0 ; j < dim2; ++j)\n      { DEBUG_PRINTF(\"%1.2e \", A[i][j]) }\n      DEBUG_PRINT(\"\\n\")});\n\n  while (ITER < itermax && !Ifound)\n  {\n\n    ++ITER;\n\n    if (nobasis < dim + 1)      drive = nobasis + (dim + 1);\n    else if (nobasis > dim + 1) drive = nobasis - (dim + 1);\n\n    DEBUG_PRINTF(\"driving variable %i \\n\", drive);\n\n    /* Start research of argmin lexico for minimum ratio test */\n    pivot = 1e20;\n    block = -1;\n\n    for (ic = 0 ; ic < dim ; ++ic)\n    {\n      zb = A[ic][drive];\n      if (zb > 0.0)\n      {\n        z0 = A[ic][0] / zb;\n        if (z0 > pivot) continue;\n        if (z0 < pivot)\n        {\n          pivot = z0;\n          block = ic;\n        }\n        else\n        {\n          for (jc = 1 ; jc < dim + 1 ; ++jc)\n          {\n            assert(block >=0 && \"lcp_lexicolemke: block <0\");\n            dblock = A[block][jc] / pivot - A[ic][jc] / zb;\n            if (dblock < 0.0) break;\n            else if (dblock > 0.0)\n            {\n              block = ic;\n              break;\n            }\n          }\n        }\n      }\n    }\n    if (block == -1)\n    {\n      Ifound = 1;\n      DEBUG_PRINT(\"The pivot column is nonpositive !\\n\"\n          \"It either means that the algorithm failed or that the LCP is infeasible\\n\"\n          \"Check the class of the M matrix to find out the meaning of this\\n\");\n      break;\n    }\n\n    if (basis[block] == dim + 1) Ifound = 1;\n\n    /* Pivot < block , drive > */\n    pivot = A[block][drive];\n    tovip = 1.0 / pivot;\n    A[block][drive] = 1;\n\n    for (ic = 0       ; ic < drive ; ++ic) A[block][ic] = A[block][ic] * tovip;\n    for (ic = drive + 1 ; ic < dim2  ; ++ic) A[block][ic] = A[block][ic] * tovip;\n\n    /* */\n\n    for (ic = 0 ; ic < block ; ++ic)\n    {\n      tmp = A[ic][drive];\n      for (jc = 0 ; jc < dim2 ; ++jc) A[ic][jc] -=  tmp * A[block][jc];\n    }\n    for (ic = block + 1 ; ic < dim ; ++ic)\n    {\n      tmp = A[ic][drive];\n      for (jc = 0 ; jc < dim2 ; ++jc) A[ic][jc] -=  tmp * A[block][jc];\n    }\n\n    nobasis = basis[block];\n    basis[block] = drive;\n\n    DEBUG_EXPR_WE( DEBUG_PRINT(\"new basis: \")\n      for (unsigned int i = 0; i < dim; ++i)\n      { DEBUG_PRINTF(\"%i \", basis[i])}\n      DEBUG_PRINT(\"\\n\"));\n\n    DEBUG_PRINT(\"total matrix\\n\");\n    DEBUG_EXPR_WE(for (unsigned int i = 0; i < dim; ++i)\n      { for(unsigned int j = 0 ; j < dim2; ++j)\n      { DEBUG_PRINTF(\"%1.2e \", A[i][j]) }\n      DEBUG_PRINT(\"\\n\")});\n\n  } /* end while*/\n\n  DEBUG_EXPR_WE( DEBUG_PRINT(\"new basis: \")\n      for (unsigned int i = 0; i < dim; ++i)\n      { DEBUG_PRINTF(\"%i \", basis[i])}\n      DEBUG_PRINT(\"\\n\"));\n\n  DEBUG_PRINT(\"total matrix\\n\");\n  DEBUG_EXPR_WE(for (unsigned int i = 0; i < dim; ++i)\n      { for(unsigned int j = 0 ; j < dim2; ++j)\n      { DEBUG_PRINTF(\"%1.2e \", A[i][j]) }\n      DEBUG_PRINT(\"\\n\")});\n\n  for (ic = 0 ; ic < dim; ++ic)\n  {\n    drive = basis[ic];\n    if (drive < dim + 1)\n    {\n      zlem[drive - 1] = 0.0;\n      wlem[drive - 1] = A[ic][0];\n    }\n    else if (drive > dim + 1)\n    {\n      zlem[drive - dim - 2] = A[ic][0];\n      wlem[drive - dim - 2] = 0.0;\n    }\n  }\n\n  options->iparam[1] = ITER;\n\n  if (Ifound) *info = 0;\n  else *info = 1;\n\n  free(basis);\n\n  for (i = 0 ; i < dim ; ++i) free(A[i]);\n  free(A);\n}\n\nint linearComplementarity_driver(LinearComplementarityProblem* problem, double *z , double *w, SolverOptions* options)\n{\n  /********************\n   * 0 - Check inputs *\n   ********************/\n\n  if (options == NULL)\n    numericsError(\"lcp_driver\", \"null input for solver options\");\n  if (problem == NULL || z == NULL || w == NULL)\n    numericsError(\"lcp_driver\", \"null input for LinearComplementarityProblem and/or unknowns (z,w)\");\n\n  int NoDefaultOptions = options->isSet; /* true(1) if the SolverOptions structure has been filled in else false(0) */\n\n  if (NoDefaultOptions == 0)\n  {\n    numericsError(\"lcp_driver_DenseMatrix\", \"options for solver have not been set\");\n  }\n\n  if (options->verboseMode > 0)\n    printSolverOptions(options);\n\n  /* Output info. : 0: ok -  >0: problem (depends on solver) */\n  int info = -1;\n\n  /******************************************\n   *  1 - Check for trivial solution\n   ******************************************/\n\n  int i = 0;\n  int n = problem->size;\n  double *q = problem->q;\n/*  if (!((options->solverId == SICONOS_LCP_ENUM) && (options->iparam[0] == 1 )))*/\n    {      \n      while ((i < (n - 1)) && (q[i] >= 0.)) i++;\n      if ((i == (n - 1)) && (q[n - 1] >= 0.))\n      {\n        /* TRIVIAL CASE : q >= 0\n         * z = 0 and w = q is solution of LCP(q,M)\n         */\n        for (int j = 0 ; j < n; j++)\n        {\n          z[j] = 0.0;\n          w[j] = q[j];\n        }\n        info = 0;\n        options->dparam[1] = 0.0; /* Error */\n        if (options->verboseMode > 0)\n          printf(\"LCP_driver_DenseMatrix: found trivial solution for the LCP (positive vector q => z = 0 and w = q). \\n\");\n        return info;\n      }\n    }\n\n  /*************************************************\n   *  2 - Call Lemke solver (if no trivial sol.)\n   *************************************************/\n\n  if (options->verboseMode == 1)\n    printf(\" ========================== Call Lemke solver for Linear Complementarity problem ==========================\\n\");\n\n  /****** Lemke algorithm ******/\n  /* IN: itermax\n     OUT: iter */\n   lcp_lexicolemke(problem, z , w , &info , options);\n\n  /*************************************************\n   *  3 - Computes w = Mz + q and checks validity\n   *************************************************/\n  if (options->filterOn > 0)\n  {\n    int info_ = lcp_compute_error(problem, z, w, options->dparam[0], &(options->dparam[1]),\n\t\t\t\t  options->verboseMode);\n    if (info <= 0) /* info was not setor the solver was happy */\n      info = info_;\n  }\n  \n  return info;\n}\n\nvoid lcp_compute_error_only(unsigned int n, double *z , double *w, double * error)\n{\n  /* Checks complementarity */\n\n  *error = 0.;\n  double zi, wi;\n  for (unsigned int i = 0 ; i < n ; i++)\n  {\n    zi = z[i];\n    wi = w[i];\n    if (zi < 0.0)\n    {\n      *error += -zi;\n      if (wi < 0.0) *error += zi * wi;\n    }\n    if (wi < 0.0) *error += -wi;\n    if ((zi > 0.0) && (wi > 0.0)) *error += zi * wi;\n  }\n}\n\nint lcp_compute_error(LinearComplementarityProblem* problem, double *z , double *w, double tolerance, \n\t\t      double * error, int verbose)\n{\n  /* Checks inputs */\n  if (problem == NULL || z == NULL || w == NULL)\n    numericsError(\"lcp_compute_error\", \"null input for problem and/or z and/or w\");\n\n  /* Computes w = Mz + q */\n  int incx = 1, incy = 1;\n  unsigned int n = problem->size;\n  cblas_dcopy(n , problem->q , incx , w , incy);  // w <-q\n  prodNumericsMatrix(n, n, 1.0, problem->M, z, 1.0, w);\n  double normq = cblas_dnrm2(n , problem->q , incx);\n  lcp_compute_error_only(n, z, w, error);\n  *error = *error / (normq + 1.0); /* Need some comments on why this is needed */\n  if (*error > tolerance)\n  {\n    if (verbose > 0) \n\tprintf(\" Numerics - lcp_compute_error : error = %g > tolerance = %g.\\n\", *error, tolerance);\n    return 1;\n  }\n  else\n    return 0;\n}\n\nint linearComplementarity_lexicolemke_setDefaultSolverOptions(SolverOptions* options)\n{\n  /* if (options->verboseMode > 0) */\n  /* { */\n  /*   printf(\"Set the Default SolverOptions for the Lemke Solver\\n\"); */\n  /* } */\n\n  options->isSet = 1;\n  options->filterOn = 1;\n  options->iSize = 5;\n  options->dSize = 5;\n  options->iparam = (int *)calloc(options->iSize, sizeof(int));\n  options->dparam = (double *)calloc(options->dSize, sizeof(double));\n  options->verboseMode = 0;\n  options->dparam[0] = 1e-6;\n  options->iparam[0] = 10000;\n  return 0;\n}\n\nvoid printSolverOptions(SolverOptions* options)\n{\n  printf(\"\\n ========== Numerics Non Smooth Solver parameters: \\n\");\n  if (options->isSet == 0)\n    printf(\"The solver parameters have not been set. \\t options->isSet = %i \\n\", options->isSet);\n  else\n  {\n    printf(\"The solver parameters below have  been set \\t options->isSet = %i\\n\", options->isSet);\n    printf(\"Name of the solver\\t\\t\\t\\t Lemke \\n\");\n    if (options->iparam != NULL)\n    {\n      printf(\"int parameters \\t\\t\\t\\t\\t options->iparam\\n\");\n      printf(\"size of the int parameters\\t\\t\\t options->iSize = %i\\n\", options->iSize);\n      for (int i = 0; i < options->iSize; ++i)\n        printf(\"\\t\\t\\t\\t\\t\\t options->iparam[%i] = %d\\n\", i, options->iparam[i]);\n    }\n    if (options->dparam != NULL)\n    {\n      printf(\"double parameters \\t\\t\\t\\t options->dparam\\n\");\n      printf(\"size of the double parameters\\t\\t\\t options->dSize = %i\\n\", options->dSize);\n      for (int i = 0; i < options->iSize; ++i)\n        printf(\"\\t\\t\\t\\t\\t\\t options->dparam[%i] = %.6le\\n\", i, options->dparam[i]);\n    }\n  }\n\n  printf(\"See Lemke documentation for parameters definition)\\n\");\n  printf(\"\\n\");\n}\n", "meta": {"hexsha": "06d261667033f9295a553048e6bbf8bfbe5a4863", "size": 13446, "ext": "c", "lang": "C", "max_stars_repo_path": "src/LCP_Solver.c", "max_stars_repo_name": "fairbrot/Cones.jl", "max_stars_repo_head_hexsha": "653c19c6553643a15a535e82d763901c2fe90356", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-11-07T23:52:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T17:21:29.000Z", "max_issues_repo_path": "src/LCP_Solver.c", "max_issues_repo_name": "fairbrot/Cones.jl", "max_issues_repo_head_hexsha": "653c19c6553643a15a535e82d763901c2fe90356", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/LCP_Solver.c", "max_forks_repo_name": "fairbrot/Cones.jl", "max_forks_repo_head_hexsha": "653c19c6553643a15a535e82d763901c2fe90356", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0, "max_line_length": 137, "alphanum_fraction": 0.5145768258, "num_tokens": 4384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.03161876441702708, "lm_q1q2_score": 0.01568587392278181}}
{"text": "// File: nlopt_wrapper.c\n// Author: Jannis Harder\n// Description: Wrapper for nlopt using context switching\n\n#include <stdlib.h>\n#include <ucontext.h>\n#include <string.h>\n#include <stdio.h> // For debugging TODO: remove\n#include <nlopt.h>\n\n#define STACKSIZE (8 * 1024 * 1024)\n\nenum status {\n\tST_IDLE = 0,\n\tST_RUNNING,\n\tST_VALUE,\n\tST_GRAD,\n\tST_DONE\n};\n\nstruct function {\n\tstruct wrapper * w;\n\tstruct function * next;\n\tint id;\n};\n\nstruct wrapper {\n\tstruct function f;\n\tnlopt_opt opt;\n\tint n;\n\tucontext_t julia_ctx;\n\tucontext_t nlopt_ctx;\n\tchar *nlopt_stack;\n\tdouble final_f;\n\tdouble *opt_x;\n\tdouble *eval_x;\n\tdouble *eval_grad;\n\tdouble eval_f;\n\tint force_stop;\n\tint result;\n\tint function_id;\n\tenum status status;\n};\n\n\ndouble nlopt_wrapper_f(unsigned n, const double *x, double *grad, void *f_data);\nvoid nlopt_wrapper_optimize_thread(struct wrapper* w);\n\nvoid nlopt_wrapper_version(int *version)\n{\n\tnlopt_version(&version[0], &version[1], &version[2]);\n\tversion[3] = 2;\n\tversion[4] = 2;\n\tversion[5] = 4;\n\tversion[6] = 0;\n}\n\nstruct wrapper *nlopt_wrapper_create(int type_id, int dimensions)\n{\n\tnlopt_opt opt = nlopt_create(type_id, dimensions);\n\tif (!opt)\n\t\treturn NULL;\n\tstruct wrapper *w = calloc(1, sizeof(struct wrapper));\n\tw->n = dimensions;\n\tw->opt = opt;\n\tw->f.w = w;\n\tw->f.id = 1;\n\treturn w;\n}\n\nvoid nlopt_wrapper_free(struct wrapper *w)\n{\n\tnlopt_destroy(w->opt);\n\tfree(w->opt_x);\n\tstruct function *f = &w->f;\n\twhile (f) {\n\t\tstruct function *next = f->next;\n\t\tfree(f);\n\t\tf = next;\n\t}\n}\n\nint nlopt_wrapper_objective(struct wrapper *w, int max)\n{\n\tif (max)\n\t\treturn nlopt_set_max_objective(w->opt, &nlopt_wrapper_f, &w->f);\n\telse\n\t\treturn nlopt_set_min_objective(w->opt, &nlopt_wrapper_f, &w->f);\n}\n\n\ndouble nlopt_wrapper_f(unsigned n, const double *x, double *grad, void *f_data)\n{\n\tstruct function *f = f_data;\n\tstruct wrapper *w = f->w;\n\n\tw->function_id = f->id;\n\n\tw->status = grad ? ST_GRAD : ST_VALUE;\n\tmemcpy(w->eval_x, x, n * sizeof(double));\n\tswapcontext(&w->nlopt_ctx, &w->julia_ctx);\n\tif (w->force_stop)\n\t\tnlopt_force_stop(w->opt);\n\tif (grad)\n\t\tmemcpy(grad, w->eval_grad, n * sizeof(double));\n\treturn w->eval_f;\n}\n\nvoid nlopt_wrapper_optimize_start(struct wrapper *w, double *x)\n{\n\tint i;\n\tgetcontext(&w->nlopt_ctx);\n\tw->nlopt_stack = calloc(1, STACKSIZE);\n\tw->nlopt_ctx.uc_stack.ss_sp = w->nlopt_stack;\n\tw->nlopt_ctx.uc_stack.ss_size = STACKSIZE;\n\tw->nlopt_ctx.uc_link = &w->julia_ctx;\n\tmakecontext(&w->nlopt_ctx, (void(*)())&nlopt_wrapper_optimize_thread, 1, w);\n\n\n\tw->opt_x = calloc(w->n, sizeof(double));\n\tmemcpy(w->opt_x, x, w->n * sizeof(double));\n}\n\nint nlopt_wrapper_optimize_callback(struct wrapper *w, double *x, double *grad, double f, int force_stop, int *function_id)\n{\n\tw->eval_f = f;\n\tw->eval_x = x;\n\tw->eval_grad = grad;\n\tw->force_stop = force_stop;\n\tswapcontext(&w->julia_ctx, &w->nlopt_ctx);\n\t*function_id = w->function_id;\n\treturn w->status;\n}\n\nint nlopt_wrapper_optimize_finalize(struct wrapper *w, double *x, double *f)\n{\n\tmemcpy(x, w->opt_x, w->n * sizeof(double));\n\tfree(w->opt_x);\n\tw->opt_x = NULL;\n\t*f = w->final_f;\n\tfree(w->nlopt_stack);\n\tw->nlopt_stack = NULL;\n\treturn w->result;\n}\n\nvoid nlopt_wrapper_optimize_thread(struct wrapper *w)\n{\n\tw->result = nlopt_optimize(w->opt, w->opt_x, &w->final_f);\n\tw->status = ST_DONE;\n}\n\nvoid nlopt_wrapper_dimopt(struct wrapper *w, double *x, int i)\n{\n\tswitch (i) {\n\tcase 0: nlopt_set_lower_bounds(w->opt, x); break;\n\tcase 1: nlopt_set_upper_bounds(w->opt, x); break;\n\tcase 2: nlopt_set_xtol_abs(w->opt, x); break;\n\t}\n}\n\nvoid nlopt_wrapper_doubleopt(struct wrapper *w, double v, int i)\n{\n\tswitch (i) {\n\tcase 0: nlopt_set_stopval(w->opt, v); break;\n\tcase 1: nlopt_set_ftol_rel(w->opt, v); break;\n\tcase 2: nlopt_set_ftol_abs(w->opt, v); break;\n\tcase 3: nlopt_set_xtol_rel(w->opt, v); break;\n\tcase 4: nlopt_set_maxtime(w->opt, v); break;\n\t}\n}\n\nvoid nlopt_wrapper_intopt(struct wrapper *w, long int v, int i)\n{\n\tswitch (i) {\n\tcase 0: nlopt_set_maxeval(w->opt, v); break;\n\tcase 1: nlopt_set_population(w->opt, v < 0 ? 0 : v); break;\n\tcase 2: nlopt_srand(v); break;\n\t}\n}\n\nvoid nlopt_wrapper_add_constraint(struct wrapper *w, int id, double tolerance, int equality)\n{\n\tstruct function *f = calloc(1, sizeof(struct function));\n\n\tf->w = w;\n\tf->next = w->f.next;\n\tf->id = id;\n\tw->f.next = f;\n\tif (equality)\n\t\tnlopt_add_equality_constraint(w->opt, &nlopt_wrapper_f, f, tolerance);\n\telse\n\t\tnlopt_add_inequality_constraint(w->opt, &nlopt_wrapper_f, f, tolerance);\n}\n\nvoid nlopt_wrapper_local_optimizer(struct wrapper *w, struct wrapper *local_w)\n{\n\tnlopt_set_local_optimizer(w->opt, local_w->opt);\n}\n", "meta": {"hexsha": "cf3845311235dd9f655ea7f40145ff573905584f", "size": 4564, "ext": "c", "lang": "C", "max_stars_repo_path": "src/nlopt/nlopt_wrapper.c", "max_stars_repo_name": "MetalNinjas/julia-nlopt", "max_stars_repo_head_hexsha": "7308e113fd2e8940b2691301a7957a6b525c032a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/nlopt/nlopt_wrapper.c", "max_issues_repo_name": "MetalNinjas/julia-nlopt", "max_issues_repo_head_hexsha": "7308e113fd2e8940b2691301a7957a6b525c032a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/nlopt/nlopt_wrapper.c", "max_forks_repo_name": "MetalNinjas/julia-nlopt", "max_forks_repo_head_hexsha": "7308e113fd2e8940b2691301a7957a6b525c032a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-10-01T18:11:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T18:11:07.000Z", "avg_line_length": 22.9346733668, "max_line_length": 123, "alphanum_fraction": 0.6967572305, "num_tokens": 1460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632159254749036, "lm_q2_score": 0.036769469110227285, "lm_q1q2_score": 0.01567561862819785}}
{"text": "#ifndef SAMPLER_H\n#define SAMPLER_H\n#include <gsl/gsl_rng.h>\n#include <stdlib.h>\n\n\ntypedef struct sampler {\n  gsl_rng *internal_rng_state;\n  unsigned long int seed;\n  double (*generate)(void *samplerp);\n} Sampler;\n\n\nSampler *new_sampler(unsigned long int seed);\nvoid free_sampler(Sampler *p);\ndouble generate_method(void *samplerp);\n\n#endif\n", "meta": {"hexsha": "b326c2635d84303da7d3b56ba5930d8c79b46753", "size": 341, "ext": "h", "lang": "C", "max_stars_repo_path": "src/sampler.h", "max_stars_repo_name": "BlauGroup/RNMC_archived", "max_stars_repo_head_hexsha": "959370b3137ec826b3eb8e750721fd8ea09fdff1", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/sampler.h", "max_issues_repo_name": "BlauGroup/RNMC_archived", "max_issues_repo_head_hexsha": "959370b3137ec826b3eb8e750721fd8ea09fdff1", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sampler.h", "max_forks_repo_name": "BlauGroup/RNMC_archived", "max_forks_repo_head_hexsha": "959370b3137ec826b3eb8e750721fd8ea09fdff1", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-08T18:18:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-08T18:18:12.000Z", "avg_line_length": 17.9473684211, "max_line_length": 45, "alphanum_fraction": 0.7565982405, "num_tokens": 86, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.320821300824607, "lm_q2_score": 0.048857776717889774, "lm_q1q2_score": 0.015674615482031598}}
{"text": "#ifndef OPENMC_MATERIAL_H\n#define OPENMC_MATERIAL_H\n\n#include <memory> // for unique_ptr\n#include <string>\n#include <unordered_map>\n#include <vector>\n\n#include <gsl/gsl>\n#include <hdf5.h>\n#include \"pugixml.hpp\"\n#include \"xtensor/xtensor.hpp\"\n\n#include \"openmc/constants.h\"\n#include \"openmc/bremsstrahlung.h\"\n#include \"openmc/particle.h\"\n\nnamespace openmc {\n\n//==============================================================================\n// Global variables\n//==============================================================================\n\nclass Material;\n\nnamespace model {\n\nextern std::unordered_map<int32_t, int32_t> material_map;\nextern std::vector<std::unique_ptr<Material>> materials;\n\n} // namespace model\n\n//==============================================================================\n//! A substance with constituent nuclides and thermal scattering data\n//==============================================================================\n\nclass Material\n{\npublic:\n  //----------------------------------------------------------------------------\n  // Types\n  struct ThermalTable {\n    int index_table; //!< Index of table in data::thermal_scatt\n    int index_nuclide; //!< Index in nuclide_\n    double fraction; //!< How often to use table\n  };\n\n  //----------------------------------------------------------------------------\n  // Constructors, destructors, factory functions\n  Material() {};\n  explicit Material(pugi::xml_node material_node);\n  ~Material();\n\n  //----------------------------------------------------------------------------\n  // Methods\n\n  void calculate_xs(Particle& p) const;\n\n  //! Assign thermal scattering tables to specific nuclides within the material\n  //! so the code knows when to apply bound thermal scattering data\n  void init_thermal();\n\n  //! Set up mapping between global nuclides vector and indices in nuclide_\n  void init_nuclide_index();\n\n  //! Finalize the material, assigning tables, normalize density, etc.\n  void finalize();\n\n  //! Write material data to HDF5\n  void to_hdf5(hid_t group) const;\n\n  //! Add nuclide to the material\n  //\n  //! \\param[in] nuclide Name of the nuclide\n  //! \\param[in] density Density of the nuclide in [atom/b-cm]\n  void add_nuclide(const std::string& nuclide, double density);\n\n  //! Set atom densities for the material\n  //\n  //! \\param[in] name Name of each nuclide\n  //! \\param[in] density Density of each nuclide in [atom/b-cm]\n  void set_densities(const std::vector<std::string>& name,\n    const std::vector<double>& density);\n\n  //----------------------------------------------------------------------------\n  // Accessors\n\n  //! Get density in [atom/b-cm]\n  //! \\return Density in [atom/b-cm]\n  double density() const { return density_; }\n\n  //! Get density in [g/cm^3]\n  //! \\return Density in [g/cm^3]\n  double density_gpcc() const { return density_gpcc_; }\n\n  //! Get name\n  //! \\return Material name\n  const std::string& name() const { return name_; }\n\n  //! Set name\n  void set_name(const std::string& name) { name_ = name; }\n\n  //! Set total density of the material\n  //\n  //! \\param[in] density Density value\n  //! \\param[in] units Units of density\n  void set_density(double density, gsl::cstring_span units);\n\n  //! Get nuclides in material\n  //! \\return Indices into the global nuclides vector\n  gsl::span<const int> nuclides() const { return {nuclide_.data(), nuclide_.size()}; }\n\n  //! Get densities of each nuclide in material\n  //! \\return Densities in [atom/b-cm]\n  gsl::span<const double> densities() const { return {atom_density_.data(), atom_density_.size()}; }\n\n  //! Get ID of material\n  //! \\return ID of material\n  int32_t id() const { return id_; }\n\n  //! Assign a unique ID to the material\n  //! \\param[in] Unique ID to assign. A value of -1 indicates that an ID\n  //!   should be automatically assigned.\n  void set_id(int32_t id);\n\n  //! Get whether material is fissionable\n  //! \\return Whether material is fissionable\n  bool fissionable() const { return fissionable_; }\n\n  //! Get volume of material\n  //! \\return Volume in [cm^3]\n  double volume() const;\n\n  //! Get temperature of material\n  //! \\return Temperature in [K]\n  double temperature() const;\n\n  //----------------------------------------------------------------------------\n  // Data\n  int32_t id_ {C_NONE}; //!< Unique ID\n  std::string name_; //!< Name of material\n  std::vector<int> nuclide_; //!< Indices in nuclides vector\n  std::vector<int> element_; //!< Indices in elements vector\n  xt::xtensor<double, 1> atom_density_; //!< Nuclide atom density in [atom/b-cm]\n  double density_; //!< Total atom density in [atom/b-cm]\n  double density_gpcc_; //!< Total atom density in [g/cm^3]\n  double volume_ {-1.0}; //!< Volume in [cm^3]\n  bool fissionable_ {false}; //!< Does this material contain fissionable nuclides\n  bool depletable_ {false}; //!< Is the material depletable?\n  std::vector<bool> p0_; //!< Indicate which nuclides are to be treated with iso-in-lab scattering\n\n  // To improve performance of tallying, we store an array (direct address\n  // table) that indicates for each nuclide in data::nuclides the index of the\n  // corresponding nuclide in the nuclide_ vector. If it is not present in the\n  // material, the entry is set to -1.\n  std::vector<int> mat_nuclide_index_;\n\n  // Thermal scattering tables\n  std::vector<ThermalTable> thermal_tables_;\n\n  std::unique_ptr<Bremsstrahlung> ttb_;\n\nprivate:\n  //----------------------------------------------------------------------------\n  // Private methods\n\n  //! Calculate the collision stopping power\n  void collision_stopping_power(double* s_col, bool positron);\n\n  //! Initialize bremsstrahlung data\n  void init_bremsstrahlung();\n\n  //! Normalize density\n  void normalize_density();\n\n  void calculate_neutron_xs(Particle& p) const;\n  void calculate_photon_xs(Particle& p) const;\n\n  //----------------------------------------------------------------------------\n  // Private data members\n  gsl::index index_;\n\n  //! \\brief Default temperature for cells containing this material.\n  //!\n  //! A negative value indicates no default temperature was specified.\n  double temperature_ {-1};\n};\n\n//==============================================================================\n// Non-member functions\n//==============================================================================\n\n//! Calculate Sternheimer adjustment factor\ndouble sternheimer_adjustment(const std::vector<double>& f, const\n  std::vector<double>& e_b_sq, double e_p_sq, double n_conduction, double\n  log_I, double tol, int max_iter);\n\n//! Calculate density effect correction\ndouble density_effect(const std::vector<double>& f, const std::vector<double>&\n  e_b_sq, double e_p_sq, double n_conduction, double rho, double E, double tol,\n  int max_iter);\n\n//! Read material data from materials.xml\nvoid read_materials_xml();\n\nvoid free_memory_material();\n\n} // namespace openmc\n#endif // OPENMC_MATERIAL_H\n", "meta": {"hexsha": "9adb9ff97df39079e7058830f872e60be184f75f", "size": 6900, "ext": "h", "lang": "C", "max_stars_repo_path": "include/openmc/material.h", "max_stars_repo_name": "Hit-Weixg/openmc", "max_stars_repo_head_hexsha": "c5f66a3af5c1a57087e330f7b870e89a82267e4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-01-10T13:14:35.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-05T10:18:12.000Z", "max_issues_repo_path": "include/openmc/material.h", "max_issues_repo_name": "Hit-Weixg/openmc", "max_issues_repo_head_hexsha": "c5f66a3af5c1a57087e330f7b870e89a82267e4b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-03-14T12:18:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-01T15:23:23.000Z", "max_forks_repo_path": "include/openmc/material.h", "max_forks_repo_name": "Hit-Weixg/openmc", "max_forks_repo_head_hexsha": "c5f66a3af5c1a57087e330f7b870e89a82267e4b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-07-31T21:03:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-22T20:54:48.000Z", "avg_line_length": 32.8571428571, "max_line_length": 100, "alphanum_fraction": 0.6013043478, "num_tokens": 1542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334000459302, "lm_q2_score": 0.03846618871146969, "lm_q1q2_score": 0.015668563434651325}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n *\r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n *\r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n *\r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef painterpath_d2d84280_c369_48f2_99f8_28652ad13baa_h\r\n#define painterpath_d2d84280_c369_48f2_99f8_28652ad13baa_h\r\n\r\n#include <ariel/config.h>\r\n#include <gslib/std.h>\r\n\r\n__ariel_begin__\r\n\r\nclass painter_path;\r\ntypedef list<painter_path> painter_paths;\r\n\r\nclass ariel_export painter_linestrip\r\n{\r\npublic:\r\n    typedef vector<vec2> points;\r\n    typedef points::iterator ptiter;\r\n    typedef points::const_iterator ptciter;\r\n\r\nprotected:\r\n    bool                _closed;\r\n    points              _pts;\r\n\r\npublic:\r\n    painter_linestrip();\r\n    ~painter_linestrip() {}\r\n    int get_size() const { return (int)_pts.size(); }\r\n    void get_bound_rect(rectf& rc) const;\r\n    vec2& get_point(int i) { return _pts.at(i); }\r\n    const vec2& get_point(int i) const { return _pts.at(i); }\r\n    vec2& get_last_point() { return _pts.back(); }\r\n    const vec2& get_last_point() const { return _pts.back(); }\r\n    void add_point(const vec2& pt) { _pts.push_back(pt); }\r\n    void set_point(int i, const vec2& pt) { _pts.at(i) = pt; }\r\n    void reserve(int s) { _pts.reserve(s); }\r\n    void clear() { _pts.clear(); }\r\n    void swap(painter_linestrip& another);\r\n    void finish();\r\n    void transform(const mat3& m);\r\n    vec2* expand(int size);\r\n    void expand_to(int size) { _pts.resize(size); }\r\n    void reverse();\r\n    void offset(const painter_linestrip& org, float off);\r\n    int point_inside(const vec2& pt) const;\r\n    bool is_closed() const { return _closed; }\r\n    void set_closed(bool c) { _closed = c; }\r\n    bool is_clockwise() const;\r\n    bool is_convex() const;\r\n    bool is_convex(int i) const;\r\n    void tracing() const;\r\n    void trace_segments() const;\r\n    void trace_mel(float z) const;\r\n\r\nprotected:\r\n    enum\r\n    {\r\n        st_clockwise_mask = 1,\r\n        st_convex_mask = 2,\r\n    };\r\n    mutable uint        _tst_table;\r\n    mutable bool        _is_clock_wise;\r\n    mutable bool        _is_convex;\r\n\r\nprotected:\r\n    bool is_clockwise_inited() const { return (_tst_table & st_clockwise_mask) != 0; }\r\n    void set_clockwise_inited() const { _tst_table |= st_clockwise_mask; }\r\n    bool is_convex_inited() const { return (_tst_table & st_convex_mask) != 0; }\r\n    void set_convex_inited() const { _tst_table |= st_convex_mask; }\r\n};\r\n\r\ntypedef list<painter_linestrip> linestrips;\r\ntypedef vector<painter_linestrip*> linestripvec;\r\ntypedef linestrips painter_linestrips;\r\n\r\n/* create a random access view for linestrips */\r\nariel_export extern void append_linestrips_rav(linestripvec& rav, linestrips& src);\r\nariel_export extern void create_linestrips_rav(linestripvec& rav, linestrips& src);\r\n\r\nclass ariel_export painter_path\r\n{\r\npublic:\r\n    enum tag\r\n    {\r\n        pt_moveto,\r\n        pt_lineto,\r\n        pt_quadto,\r\n        pt_cubicto,\r\n    };\r\n\r\n    class __gs_novtable ariel_export node abstract\r\n    {\r\n    public:\r\n        virtual ~node() {}\r\n        virtual tag get_tag() const = 0;\r\n        virtual const vec2& get_point() const = 0;\r\n        virtual void set_point(const vec2&) = 0;\r\n        virtual void interpolate(painter_linestrip& c, const node* last, float step_len) const = 0;\r\n\r\n    public:\r\n        template<class _c>\r\n        _c* as_node() { return static_cast<_c*>(this); }\r\n        template<class _c>\r\n        const _c* as_const_node() const { return static_cast<const _c*>(this); }\r\n    };\r\n\r\n    template<tag _tag>\r\n    class node_tpl:\r\n        public node\r\n    {\r\n    public:\r\n        node_tpl() {}\r\n        node_tpl(float x, float y): _pt(x, y) {}\r\n        node_tpl(const vec2& pt): _pt(pt) {}\r\n\r\n    public:\r\n        tag get_tag() const override { return _tag; }\r\n        const vec2& get_point() const override { return _pt; }\r\n        void set_point(const vec2& pt) override { _pt = pt; }\r\n        void interpolate(painter_linestrip& c, const node*, float) const override { c.add_point(_pt); }\r\n\r\n    protected:\r\n        vec2            _pt;\r\n    };\r\n\r\n    typedef node_tpl<pt_moveto> move_to_node;\r\n    typedef node_tpl<pt_lineto> line_to_node;\r\n\r\n    class ariel_export quad_to_node:\r\n        public node_tpl<pt_quadto>\r\n    {\r\n    public:\r\n        quad_to_node() {}\r\n        quad_to_node(const vec2& p1, const vec2& p2): node_tpl(p2) { _c = p1; }\r\n        void set_control(const vec2& c) { _c = c; }\r\n        const vec2& get_control() const { return _c; }\r\n        void interpolate(painter_linestrip& c, const node* last, float step_len) const override;\r\n\r\n    protected:\r\n        vec2            _c;\r\n    };\r\n\r\n    class ariel_export cubic_to_node:\r\n        public node_tpl<pt_cubicto>\r\n    {\r\n    public:\r\n        cubic_to_node() {}\r\n        cubic_to_node(const vec2& p1, const vec2& p2, const vec2 p3): node_tpl(p3) { _c[0] = p1, _c[1] = p2; }\r\n        void set_control1(const vec2& c) { _c[0] = c; }\r\n        void set_control2(const vec2& c) { _c[1] = c; }\r\n        const vec2& get_control1() const { return _c[0]; }\r\n        const vec2& get_control2() const { return _c[1]; }\r\n        void interpolate(painter_linestrip& c, const node* last, float step_len) const override;\r\n\r\n    protected:\r\n        vec2            _c[2];\r\n    };\r\n\r\n    typedef vector<node*> node_list;\r\n    typedef node_list::iterator iterator;\r\n    typedef node_list::const_iterator const_iterator;\r\n    typedef vector<int> indices;\r\n\r\nprotected:\r\n    node_list           _nodelist;\r\n\r\npublic:\r\n    painter_path() {}\r\n    painter_path(const painter_path& path) { duplicate(path); }\r\n    ~painter_path() { destroy(); }\r\n    bool empty() const { return _nodelist.empty(); }\r\n    int size() const { return (int)_nodelist.size(); }\r\n    void resize(int len);\r\n    void destroy();\r\n    void duplicate(const painter_path& path);\r\n    void add_path(const painter_path& path);\r\n    void add_rect(const rectf& rc);\r\n    void swap(painter_path& path);\r\n    iterator begin() { return _nodelist.begin(); }\r\n    iterator end() { return _nodelist.end(); }\r\n    const_iterator begin() const { return _nodelist.begin(); }\r\n    const_iterator end() const { return _nodelist.end(); }\r\n    node* get_node(int i) { return _nodelist.at(i); }\r\n    const node* get_node(int i) const { return _nodelist.at(i); }\r\n    void close_path();\r\n    void close_sub_path();\r\n    void get_boundary_box(rectf& rc) const;\r\n    void move_to(float x, float y) { move_to(vec2(x, y)); }\r\n    void line_to(float x, float y) { line_to(vec2(x, y)); }\r\n    void arc_to(float x, float y, float r) { arc_to(vec2(x, y), r); }\r\n    void rarc_to(float x, float y, float r) { rarc_to(vec2(x, y), r); }\r\n    void quad_to(float x1, float y1, float x2, float y2) { quad_to(vec2(x1, y1), vec2(x2, y2)); }\r\n    void cubic_to(float x1, float y1, float x2, float y2, float x3, float y3) { cubic_to(vec2(x1, y1), vec2(x2, y2), vec2(x3, y3)); }\r\n    void move_to(const vec2& pt) { _nodelist.push_back(new move_to_node(pt)); }\r\n    void line_to(const vec2& pt) { _nodelist.push_back(new line_to_node(pt)); }\r\n    void quad_to(const vec2& p1, const vec2& p2) { _nodelist.push_back(new quad_to_node(p1, p2)); }\r\n    void cubic_to(const vec2& p1, const vec2& p2, const vec2& p3) { _nodelist.push_back(new cubic_to_node(p1, p2, p3)); }\r\n    void arc_to(const vec2& p1, const vec2& p2, float r);\r\n    void arc_to(const vec2& pt, float r);\r\n    void rarc_to(const vec2& pt, float r);\r\n    void transform(const mat3& m);\r\n    void get_linestrips(linestrips& c, float step_len = -1.f) const;\r\n    int get_control_contour(painter_linestrip& ls, int start) const;\r\n    int get_sub_path(painter_path& sp, int start) const;\r\n    void to_sub_paths(painter_paths& paths) const;\r\n    bool is_clockwise() const;\r\n    bool is_convex() const;\r\n    void simplify(painter_path& path) const;\r\n    void reverse();\r\n    void tracing() const;\r\n    void tracing_segments() const;\r\n};\r\n\r\ntypedef painter_path::node painter_node;\r\n\r\nstruct ariel_export path_info\r\n{\r\n    const painter_node*     node[2];\r\n\r\n    path_info() { node[0] = node[1] = 0; }\r\n    path_info(const painter_node* n1, const painter_node* n2) { node[0] = n1, node[1] = n2; }\r\n    int get_order() const;\r\n    int get_point_count() const;\r\n    bool get_points(vec2 pt[], int cnt) const;\r\n    void tracing() const;\r\n};\r\n\r\nenum curve_type\r\n{\r\n    ct_quad,\r\n    ct_cubic,\r\n};\r\n\r\nstruct __gs_novtable ariel_export curve_splitter abstract\r\n{\r\n    vec2                fixedpt;\r\n    float               ratio;\r\n    curve_splitter*     child[2];\r\n    curve_splitter*     parent;\r\n\r\npublic:\r\n    curve_splitter();\r\n    virtual ~curve_splitter();\r\n    virtual curve_type get_type() const = 0;\r\n    virtual int get_point_count() const = 0;\r\n    virtual bool get_points(vec2 p[], int count) const = 0;\r\n    virtual void split(float t) = 0;\r\n    virtual void interpolate(vec2& p, float t) const = 0;\r\n    virtual float reparameterize(const vec2& p) const = 0;\r\n    virtual void tracing() const = 0;\r\n    bool is_leaf() const;\r\n};\r\n\r\nstruct ariel_export curve_splitter_quad:\r\n    public curve_splitter\r\n{\r\n    vec2                cp[3];\r\n    vec3                para[2];\r\n\r\npublic:\r\n    curve_splitter_quad(const vec2 p[3]);\r\n    curve_type get_type() const override { return ct_quad; }\r\n    int get_point_count() const override { return 3; }\r\n    bool get_points(vec2 p[], int count) const override;\r\n    void split(float t) override;\r\n    void interpolate(vec2& p, float t) const override;\r\n    float reparameterize(const vec2& p) const override;\r\n    void tracing() const override;\r\n};\r\n\r\nstruct ariel_export curve_splitter_cubic:\r\n    public curve_splitter\r\n{\r\n    vec2                cp[4];\r\n    vec4                para[2];\r\n\r\npublic:\r\n    curve_splitter_cubic(const vec2 p[4]);\r\n    curve_type get_type() const override { return ct_cubic; }\r\n    int get_point_count() const override { return 4; }\r\n    bool get_points(vec2 p[], int count) const override;\r\n    void split(float t) override;\r\n    void interpolate(vec2& p, float t) const override;\r\n    float reparameterize(const vec2& p) const override;\r\n    void tracing() const override;\r\n};\r\n\r\nstruct ariel_export curve_helper\r\n{\r\n    static curve_splitter* create_splitter(const path_info* pnf);\r\n    static curve_splitter* create_next_splitter(vec2& p, curve_splitter* cs, float t);\r\n    static curve_splitter* query_splitter(curve_splitter* cs, float t);\r\n    static curve_splitter* query_splitter(curve_splitter* cs, const vec2& p);\r\n    static curve_splitter* query_splitter(curve_splitter* cs, const vec2& p1, const vec2& p2);\r\n};\r\n\r\nstruct ariel_export painter_helper\r\n{\r\n    enum\r\n    {\r\n        merge_straight_line = 0x01,\r\n        fix_loop = 0x02,\r\n        fix_inflection = 0x04,\r\n        reduce_straight_curve = 0x08,\r\n        reduce_short_line = 0x10,\r\n    };\r\n\r\n    static void transform(painter_path& output, const painter_path& path, uint mask);\r\n    static void close_sub_paths(painter_path& output, const painter_path& path);\r\n};\r\n\r\n__ariel_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "64d0d22c3de35a18d7ce9f2fe27d7449c3c63095", "size": 12084, "ext": "h", "lang": "C", "max_stars_repo_path": "include/ariel/painterpath.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/ariel/painterpath.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ariel/painterpath.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 35.5411764706, "max_line_length": 134, "alphanum_fraction": 0.6506951341, "num_tokens": 3196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37754065479083276, "lm_q2_score": 0.041462271675026176, "lm_q1q2_score": 0.01565369319730478}}
{"text": "/* rng/gsl_rng.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#ifndef __GSL_RNG_H__\n#define __GSL_RNG_H__\n#include <stdlib.h>\n#include <gsl/gsl_errno.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct\n  {\n    const char *name;\n    unsigned long int max;\n    unsigned long int min;\n    size_t size;\n    void (*set) (void *state, unsigned long int seed);\n    unsigned long int (*get) (void *state);\n    double (*get_double) (void *state);\n  }\ngsl_rng_type;\n\ntypedef struct\n  {\n    const gsl_rng_type * type;\n    void *state;\n  }\ngsl_rng;\n\n\n/* These structs also need to appear in default.c so you can select\n   them via the environment variable GSL_RNG_TYPE */\n\nextern const gsl_rng_type *gsl_rng_cmrg;\nextern const gsl_rng_type *gsl_rng_gfsr4;\nextern const gsl_rng_type *gsl_rng_minstd;\nextern const gsl_rng_type *gsl_rng_mrg;\nextern const gsl_rng_type *gsl_rng_mt19937;\nextern const gsl_rng_type *gsl_rng_mt19937_1998;\nextern const gsl_rng_type *gsl_rng_r250;\nextern const gsl_rng_type *gsl_rng_ran0;\nextern const gsl_rng_type *gsl_rng_ran1;\nextern const gsl_rng_type *gsl_rng_ran2;\nextern const gsl_rng_type *gsl_rng_ran3;\nextern const gsl_rng_type *gsl_rng_rand48;\nextern const gsl_rng_type *gsl_rng_rand;\nextern const gsl_rng_type *gsl_rng_random128_bsd;\nextern const gsl_rng_type *gsl_rng_random128_glibc2;\nextern const gsl_rng_type *gsl_rng_random128_libc5;\nextern const gsl_rng_type *gsl_rng_random256_bsd;\nextern const gsl_rng_type *gsl_rng_random256_glibc2;\nextern const gsl_rng_type *gsl_rng_random256_libc5;\nextern const gsl_rng_type *gsl_rng_random32_bsd;\nextern const gsl_rng_type *gsl_rng_random32_glibc2;\nextern const gsl_rng_type *gsl_rng_random32_libc5;\nextern const gsl_rng_type *gsl_rng_random64_bsd;\nextern const gsl_rng_type *gsl_rng_random64_glibc2;\nextern const gsl_rng_type *gsl_rng_random64_libc5;\nextern const gsl_rng_type *gsl_rng_random8_bsd;\nextern const gsl_rng_type *gsl_rng_random8_glibc2;\nextern const gsl_rng_type *gsl_rng_random8_libc5;\nextern const gsl_rng_type *gsl_rng_random_bsd;\nextern const gsl_rng_type *gsl_rng_random_glibc2;\nextern const gsl_rng_type *gsl_rng_random_libc5;\nextern const gsl_rng_type *gsl_rng_randu;\nextern const gsl_rng_type *gsl_rng_ranf;\nextern const gsl_rng_type *gsl_rng_ranlux389;\nextern const gsl_rng_type *gsl_rng_ranlux;\nextern const gsl_rng_type *gsl_rng_ranlxd1;\nextern const gsl_rng_type *gsl_rng_ranlxd2;\nextern const gsl_rng_type *gsl_rng_ranlxs0;\nextern const gsl_rng_type *gsl_rng_ranlxs1;\nextern const gsl_rng_type *gsl_rng_ranlxs2;\nextern const gsl_rng_type *gsl_rng_ranmar;\nextern const gsl_rng_type *gsl_rng_slatec;\nextern const gsl_rng_type *gsl_rng_taus;\nextern const gsl_rng_type *gsl_rng_transputer;\nextern const gsl_rng_type *gsl_rng_tt800;\nextern const gsl_rng_type *gsl_rng_uni32;\nextern const gsl_rng_type *gsl_rng_uni;\nextern const gsl_rng_type *gsl_rng_vax;\nextern const gsl_rng_type *gsl_rng_zuf;\n\nconst gsl_rng_type ** gsl_rng_types_setup(void);\n\nextern const gsl_rng_type *gsl_rng_default;\nextern unsigned long int gsl_rng_default_seed;\n\ngsl_rng *gsl_rng_alloc (const gsl_rng_type * T);\nint gsl_rng_memcpy (gsl_rng * dest, const gsl_rng * src);\ngsl_rng *gsl_rng_clone (const gsl_rng * r);\n\nvoid gsl_rng_free (gsl_rng * r);\n\nvoid gsl_rng_set (const gsl_rng * r, unsigned long int seed);\nunsigned long int gsl_rng_max (const gsl_rng * r);\nunsigned long int gsl_rng_min (const gsl_rng * r);\nconst char *gsl_rng_name (const gsl_rng * r);\nsize_t gsl_rng_size (const gsl_rng * r);\nvoid * gsl_rng_state (const gsl_rng * r);\n\nvoid gsl_rng_print_state (const gsl_rng * r);\n\nconst gsl_rng_type * gsl_rng_env_setup (void);\n\nunsigned long int gsl_rng_get (const gsl_rng * r);\ndouble gsl_rng_uniform (const gsl_rng * r);\ndouble gsl_rng_uniform_pos (const gsl_rng * r);\nunsigned long int gsl_rng_uniform_int (const gsl_rng * r, unsigned long int n);\n\n\n#ifdef HAVE_INLINE\nextern inline unsigned long int gsl_rng_get (const gsl_rng * r);\n\nextern inline unsigned long int\ngsl_rng_get (const gsl_rng * r)\n{\n  return (r->type->get) (r->state);\n}\n\nextern inline double gsl_rng_uniform (const gsl_rng * r);\n\nextern inline double\ngsl_rng_uniform (const gsl_rng * r)\n{\n  return (r->type->get_double) (r->state);\n}\n\nextern inline double gsl_rng_uniform_pos (const gsl_rng * r);\n\nextern inline double\ngsl_rng_uniform_pos (const gsl_rng * r)\n{\n  double x ;\n  do\n    {\n      x = (r->type->get_double) (r->state) ;\n    }\n  while (x == 0) ;\n\n  return x ;\n}\n\nextern inline unsigned long int gsl_rng_uniform_int (const gsl_rng * r, unsigned long int n);\n\nextern inline unsigned long int\ngsl_rng_uniform_int (const gsl_rng * r, unsigned long int n)\n{\n  unsigned long int offset = r->type->min;\n  unsigned long int range = r->type->max - offset;\n  unsigned long int scale = range / n;\n  unsigned long int k;\n\n  if (n > range) \n    {\n      GSL_ERROR_VAL (\"n exceeds maximum value of generator\",\n\t\t\tGSL_EINVAL, 0) ;\n    }\n\n  do\n    {\n      k = (((r->type->get) (r->state)) - offset) / scale;\n    }\n  while (k >= n);\n\n  return k;\n}\n#endif /* HAVE_INLINE */\n\n__END_DECLS\n\n#endif /* __GSL_RNG_H__ */\n", "meta": {"hexsha": "6a48bb1a1e2db060fac02a380e2dd9bac0e72d4b", "size": 5977, "ext": "h", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/rng/gsl_rng.h", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/rng/gsl_rng.h", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/rng/gsl_rng.h", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 30.0351758794, "max_line_length": 93, "alphanum_fraction": 0.7697841727, "num_tokens": 1672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.310694383214554, "lm_q2_score": 0.050330633665833374, "lm_q1q2_score": 0.015637445183603767}}
{"text": "#ifndef AMICI_SUNDIALS_MATRIX_WRAPPER_H\n#define AMICI_SUNDIALS_MATRIX_WRAPPER_H\n\n#include <sunmatrix/sunmatrix_band.h>   // SUNMatrix_Band\n#include <sunmatrix/sunmatrix_dense.h>  // SUNMatrix_Dense\n#include <sunmatrix/sunmatrix_sparse.h> // SUNMatrix_Sparse\n\n#include <gsl/gsl-lite.hpp>\n\n#include <vector>\n\n#include \"amici/vector.h\"\n\nnamespace amici {\n\n/**\n * @brief A RAII wrapper for SUNMatrix structs.\n *\n * This can create dense, sparse, or banded matrices using the respective\n * constructor.\n */\nclass SUNMatrixWrapper {\n  public:\n    SUNMatrixWrapper() = default;\n\n    /**\n     * @brief Create sparse matrix. See SUNSparseMatrix in sunmatrix_sparse.h\n     * @param M Number of rows\n     * @param N Number of columns\n     * @param NNZ Number of nonzeros\n     * @param sparsetype Sparse type\n     */\n    SUNMatrixWrapper(int M, int N, int NNZ, int sparsetype);\n\n    /**\n     * @brief Create dense matrix. See SUNDenseMatrix in sunmatrix_dense.h\n     * @param M Number of rows\n     * @param N Number of columns\n     */\n    SUNMatrixWrapper(int M, int N);\n\n    /**\n     * @brief Create banded matrix. See SUNBandMatrix in sunmatrix_band.h\n     * @param M Number of rows and columns\n     * @param ubw Upper bandwidth\n     * @param lbw Lower bandwidth\n     */\n    SUNMatrixWrapper(int M, int ubw, int lbw);\n\n    /**\n     * @brief Create sparse matrix from dense or banded matrix. See\n     * SUNSparseFromDenseMatrix and SUNSparseFromBandMatrix in\n     * sunmatrix_sparse.h\n     * @param A Wrapper for dense matrix\n     * @param droptol tolerance for dropping entries\n     * @param sparsetype Sparse type\n     */\n    SUNMatrixWrapper(const SUNMatrixWrapper &A, realtype droptol,\n                     int sparsetype);\n\n    /**\n     * @brief Wrap existing SUNMatrix\n     * @param mat\n     */\n    explicit SUNMatrixWrapper(SUNMatrix mat);\n\n    ~SUNMatrixWrapper();\n\n    /**\n     * @brief Copy constructor\n     * @param other\n     */\n    SUNMatrixWrapper(const SUNMatrixWrapper &other);\n\n    /**\n     * @brief Move constructor\n     * @param other\n     */\n    SUNMatrixWrapper(SUNMatrixWrapper &&other);\n\n    /**\n     * @brief Copy assignment\n     * @param other\n     * @return\n     */\n    SUNMatrixWrapper &operator=(const SUNMatrixWrapper &other);\n\n    /**\n     * @brief Move assignment\n     * @param other\n     * @return\n     */\n    SUNMatrixWrapper &operator=(SUNMatrixWrapper &&other);\n\n    /**\n     * @brief Access raw data\n     * @return raw data pointer\n     */\n    realtype *data() const;\n\n    /**\n     * @brief Get the wrapped SUNMatrix\n     * @return SlsMat\n     */\n    SUNMatrix get() const;\n\n    /**\n     * @brief Get the number of rows\n     * @return number\n     */\n    sunindextype rows() const;\n\n    /**\n     * @brief Get the number of columns\n     * @return number\n     */\n    sunindextype columns() const;\n\n    /**\n     * @brief Get the number of non-zero elements (sparse matrices only)\n     * @return number\n     */\n    sunindextype nonzeros() const;\n\n    /**\n     * @brief Get the index values of a sparse matrix\n     * @return index array\n     */\n    sunindextype *indexvals() const;\n\n    /**\n     * @brief Get the index pointers of a sparse matrix\n     * @return index array\n     */\n    sunindextype *indexptrs() const;\n\n    /**\n     * @brief Get the type of sparse matrix\n     * @return index array\n     */\n    int sparsetype() const;\n\n    /**\n     * @brief reset data to zeroes\n     */\n    void reset();\n\n    /**\n     * @brief multiply with a scalar (in-place)\n     * @param a scalar value to multiply matrix\n     */\n    void scale(realtype a);\n\n    /**\n     * @brief N_Vector interface for multiply\n     * @param c output vector, may already contain values\n     * @param b multiplication vector\n     */\n    void multiply(N_Vector c, const_N_Vector b) const;\n\n    /**\n     * @brief Perform matrix vector multiplication c += A*b\n     * @param c output vector, may already contain values\n     * @param b multiplication vector\n     */\n    void multiply(gsl::span<realtype> c, gsl::span<const realtype> b) const;\n\n    /**\n     * @brief Perform reordered matrix vector multiplication c += A[:,cols]*b\n     * @param c output vector, may already contain values\n     * @param b multiplication vector\n     * @param cols int vector for column reordering\n     * @param transpose bool transpose A before multiplication\n     */\n    void multiply(N_Vector c,\n                  const N_Vector b,\n                  gsl::span <const int> cols,\n                  bool transpose) const;\n\n    /**\n     * @brief Perform reordered matrix vector multiplication c += A[:,cols]*b\n     * @param c output vector, may already contain values\n     * @param b multiplication vector\n     * @param cols int vector for column reordering\n     * @param transpose bool transpose A before multiplication\n     */\n    void multiply(gsl::span<realtype> c,\n                  gsl::span<const realtype> b,\n                  gsl::span <const int> cols,\n                  bool transpose) const;\n\n    /**\n     * @brief Perform matrix matrix multiplication\n              C[:, :] += A * B\n              for sparse A, B, C\n     * @param C output matrix, may already contain values\n     * @param B multiplication matrix\n     */\n    void sparse_multiply(SUNMatrixWrapper *C,\n                         SUNMatrixWrapper *B) const;\n\n    /**\n     * @brief Set to 0.0\n     */\n    void zero();\n\n  private:\n    void update_ptrs();\n\n    /**\n     * @brief CSC matrix to which all methods are applied\n     */\n    SUNMatrix matrix_ {nullptr};\n    realtype *data_ptr_ {nullptr};\n    sunindextype *indexptrs_ptr_ {nullptr};\n    sunindextype *indexvals_ptr_ {nullptr};\n};\n\n} // namespace amici\n\nnamespace gsl {\n/**\n * @brief Create span from SUNMatrix\n * @param nv\n * @return\n */\ninline span<realtype> make_span(SUNMatrix m)\n{\n    switch (SUNMatGetID(m)) {\n    case SUNMATRIX_DENSE:\n        return span<realtype>(SM_DATA_D(m), SM_LDATA_D(m));\n    case SUNMATRIX_SPARSE:\n        return span<realtype>(SM_DATA_S(m), SM_NNZ_S(m));\n    default:\n        throw amici::AmiException(\"Unimplemented SUNMatrix type for make_span\");\n    }\n}\n} // namespace gsl\n\n#endif // AMICI_SUNDIALS_MATRIX_WRAPPER_H\n", "meta": {"hexsha": "aeb04643c61915743aa8136ad12d872967951d7b", "size": 6145, "ext": "h", "lang": "C", "max_stars_repo_path": "include/amici/sundials_matrix_wrapper.h", "max_stars_repo_name": "lcontento/AMICI", "max_stars_repo_head_hexsha": "7a1dc5ed1299273b3670239f5d614eec835f1299", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/amici/sundials_matrix_wrapper.h", "max_issues_repo_name": "lcontento/AMICI", "max_issues_repo_head_hexsha": "7a1dc5ed1299273b3670239f5d614eec835f1299", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/amici/sundials_matrix_wrapper.h", "max_forks_repo_name": "lcontento/AMICI", "max_forks_repo_head_hexsha": "7a1dc5ed1299273b3670239f5d614eec835f1299", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4979253112, "max_line_length": 80, "alphanum_fraction": 0.6224572823, "num_tokens": 1525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.334589441253186, "lm_q2_score": 0.046724957962368814, "lm_q1q2_score": 0.015633677577207586}}
{"text": "#pragma once\n\n#include <memory>\n#include <iterator>\n#include <cstddef>\n#include <gsl/gsl>\n\nnamespace dr {\n\n/// \\brief round `s` up to the nearest multiple of n\ntemplate<typename T>\nT round_up(T s, unsigned int n) { return ((s + n - 1) / n) * n; }\n\ntemplate<typename T, typename Allocator = std::allocator<T>>\nstruct gap_buffer {\n  using value_type      = T;\n  using allocator_type  = Allocator;\n  using size_type       = std::size_t;\n  using difference_type = ptrdiff_t;\n  using reference       = value_type&;\n  using const_reference = const value_type&;\n  using pointer         = typename std::allocator_traits<Allocator>::pointer;\n  using const_pointer   = typename std::allocator_traits<Allocator>::const_pointer;\n\n  struct const_iterator;\n\n  struct iterator {\n    using self_type         = iterator;\n    using container_type    = gap_buffer;\n\n    using value_type        = container_type::value_type;\n    using difference_type   = container_type::difference_type;\n    using reference         = container_type::reference;\n    using pointer           = container_type::pointer;\n    using iterator_category = std::random_access_iterator_tag;\n\n    explicit iterator(gap_buffer* container = nullptr, difference_type offset = 0)\n        : container(container), offset(offset) { }\n\n    operator const_iterator() const {\n      return const_iterator(container, offset);\n    }\n\n    reference operator [](difference_type i) const {\n      return (*container)[offset + i];\n    }\n\n    reference operator *() const {\n      return (*container)[offset];\n    }\n\n    pointer operator ->() const {\n      return &(*container)[offset];\n    }\n\n    self_type& operator ++() {\n      offset++;\n      return *this;\n    }\n\n    self_type operator ++(int) {\n      self_type retval = *this;\n      this->operator ++();\n      return retval;\n    }\n\n    self_type& operator --() {\n      offset--;\n      return *this;\n    }\n\n    self_type operator --(int) {\n      self_type retval = *this;\n      this->operator --();\n      return retval;\n    }\n\n    bool operator ==(const self_type& other) const {\n      return container == other.container && offset == other.offset;\n    }\n\n    bool operator !=(const self_type& other) const {\n      return !(*this == other);\n    }\n\n    bool operator <(const self_type& other) const {\n      Expects(container == other.container);\n      return offset < other.offset;\n    }\n\n    bool operator >(const self_type& other) const {\n      return other < *this;\n    }\n\n    bool operator <=(const self_type& other) const {\n      return !(other < *this);\n    }\n\n    bool operator >=(const self_type& other) const {\n      return !(*this < other);\n    }\n\n    self_type& operator +=(difference_type n) {\n      offset += n;\n      return *this;\n    }\n\n    friend\n    self_type operator +(self_type it, difference_type n) {\n      it.offset += n;\n      return it;\n    }\n\n    friend\n    self_type operator +(difference_type n, self_type it) {\n      it.offset += n;\n      return it;\n    }\n\n    self_type& operator -=(difference_type n) {\n      offset -= n;\n      return *this;\n    }\n\n    self_type operator -(difference_type n) const {\n      return self_type(container, offset - n);\n    }\n\n    difference_type operator -(const self_type& other) const {\n      Expects(container == other.container);\n      return offset - other.offset;\n    }\n\n    friend class gap_buffer;\n\n  private:\n    gap_buffer* container;\n    difference_type offset;\n  };\n\n  // Here we repeat ourselves, that is, DRY principle is violated.\n  // We can get rid of the repetition with CRTP. But let's keep it\n  // as is. \n  struct const_iterator {\n    using self_type         = const_iterator;\n    using container_type    = gap_buffer;\n\n    using value_type        = container_type::value_type;\n    using difference_type   = container_type::difference_type;\n    using reference         = container_type::const_reference;\n    using pointer           = container_type::const_pointer;\n    using iterator_category = std::random_access_iterator_tag;\n\n    explicit const_iterator(const gap_buffer* container = nullptr, difference_type offset = 0)\n        : container(container),\n          offset(offset) { }\n\n    reference operator [](difference_type i) const {\n      return (*container)[offset + i];\n    }\n\n    reference operator *() const {\n      return (*container)[offset];\n    }\n\n    pointer operator ->() const {\n      return &(*container)[offset];\n    }\n\n    self_type& operator ++() {\n      offset++;\n      return *this;\n    }\n\n    self_type operator ++(int) {\n      self_type retval = *this;\n      this->operator ++();\n      return retval;\n    }\n\n    self_type& operator --() {\n      offset--;\n      return *this;\n    }\n\n    self_type operator --(int) {\n      self_type retval = *this;\n      this->operator --();\n      return retval;\n    }\n\n    bool operator ==(const self_type& other) const {\n      return container == other.container && offset == other.offset;\n    }\n\n    bool operator !=(const self_type& other) const {\n      return !(*this == other);\n    }\n\n    bool operator <(const self_type& other) const {\n      Expects(container == other.container);\n      return offset < other.offset;\n    }\n\n    bool operator >(const self_type& other) const {\n      return other < *this;\n    }\n\n    bool operator <=(const self_type& other) const {\n      return !(other < *this);\n    }\n\n    bool operator >=(const self_type& other) const {\n      return !(*this < other);\n    }\n\n    self_type& operator +=(difference_type n) {\n      offset += n;\n      return *this;\n    }\n\n    friend\n    self_type operator +(self_type it, difference_type n) {\n      it.offset += n;\n      return it;\n    }\n\n    friend\n    self_type operator +(difference_type n, self_type it) {\n      it.offset += n;\n      return it;\n    }\n\n    self_type& operator -=(difference_type n) {\n      offset -= n;\n      return *this;\n    }\n\n    self_type operator -(difference_type n) const {\n      return self_type(container, offset - n);\n    }\n\n    difference_type operator -(const self_type& other) const {\n      Expects(container == other.container);\n      return offset - other.offset;\n    }\n\n    friend class gap_buffer;\n\n  private:\n    const gap_buffer* container;\n    difference_type offset;\n  };\n\n  using reverse_iterator       = std::reverse_iterator<iterator>;\n  using const_reverse_iterator = std::reverse_iterator<const_iterator>;\n\nprivate:\n  static constexpr float incremental_factor = 0.2;\n  static constexpr size_type default_size = 8;\n  static constexpr size_type alignment = 8;\n\npublic:\n  explicit gap_buffer(size_type count = default_size) {\n    if (count == 0) {\n      start = finish = gap_start = nullptr;\n      gap_size = 0;\n    }\n    else {\n      count = round_up(count, alignment);\n\n      start = allocate_and_construct(count);\n      finish = start + count;\n      gap_start = start;\n      gap_size = count;\n    }\n  }\n\n  gap_buffer(size_type count, const T& value)\n      : gap_buffer(count) {\n    for (size_type i = 0; i < count; ++i) push_back(value);\n  }\n\n  template<typename InputIt>\n  gap_buffer(InputIt first, InputIt last) {\n    difference_type n = std::distance(first, last);\n    size_type len = round_up(std::max(default_size, size_type(n)), alignment);\n\n    start = data_allocator.allocate(len);\n    finish = start + len;\n\n    int except_flag = 0;\n    try {\n      gap_start = std::uninitialized_copy(first, last, start);\n      except_flag = 1;\n      std::uninitialized_default_construct(gap_start, finish);\n    }\n    catch (...) {\n      switch (except_flag) {\n      case 1:\n        std::destroy(start, start + n);\n        // FALL THROUGH\n      case 0:\n        data_allocator.deallocate(start, finish - start);\n      default:;// DO NOTHING\n      }\n      throw;\n    }\n\n    gap_size = len - n;\n  }\n\n  gap_buffer(const gap_buffer& rhs)\n      : gap_buffer(rhs.begin(), rhs.end()) { }\n\n  gap_buffer(gap_buffer&& rhs) noexcept\n      : gap_buffer(0) { swap(rhs); }\n\n  gap_buffer(std::initializer_list<T> ilist)\n      : gap_buffer(ilist.begin(), ilist.end()) { }\n\n  gap_buffer& operator =(const gap_buffer& rhs) {\n    gap_buffer temp(rhs);\n    swap(temp);\n    return *this;\n  }\n\n  gap_buffer& operator =(gap_buffer&& rhs) noexcept {\n    swap(rhs);\n    return *this;\n  }\n\n  ~gap_buffer() {\n    destroy_and_deallocate(start, finish);\n    start = finish = gap_start = nullptr;\n    gap_size = 0;\n  }\n\n  void swap(gap_buffer& rhs) {\n    using std::swap;\n    swap(start, rhs.start);\n    swap(finish, rhs.finish);\n    swap(gap_start, rhs.gap_start);\n    swap(gap_size, rhs.gap_size);\n  }\n\n  void assign(size_type count, const T& value) { *this = gap_buffer(count, value); }\n\n  template<typename InputIt>\n  void assign(InputIt first, InputIt last) { *this = gap_buffer(first, last); }\n\n  void assign(std::initializer_list<T> ilist) { *this = gap_buffer(ilist); }\n\n  allocator_type get_allocator() const { return data_allocator; }\n\n\n  // ------ basis START HERE ------\n\n  const_reference operator [](size_type pos) const {\n    if (start + pos < gap_start) return *(start + pos);\n    else return *(start + gap_size + pos);\n  }\n\n  iterator erase(const_iterator first, const_iterator last) {\n    Expects(first.container == this && last.container == this);\n    difference_type num_to_erase = std::distance(first, last);\n    relocate_gap(first.offset);\n    std::fill_n(gap_start + gap_size, num_to_erase, T{});\n    gap_size += num_to_erase;\n    return iterator(this, first.offset);\n  }\n\n  /// \\return iterator to the first inserted element\n  template<class InputIt>\n  iterator insert(const_iterator pos, InputIt first, InputIt last) {\n    Expects(this == pos.container && pos <= end());\n\n    difference_type num_to_insert = std::distance(first, last);\n    if (gap_size >= num_to_insert) {\n      relocate_gap(pos.offset);\n\n      std::copy(first, last, gap_start);\n      gap_start += num_to_insert;\n      gap_size -= num_to_insert;\n      return iterator(this, pos.offset);\n    }\n    else {\n      size_type old_size = size();\n      size_type old_capacity = capacity();\n      auto default_delta = size_type(old_capacity * incremental_factor);\n      size_type delta = round_up(std::max(default_delta, num_to_insert - gap_size), alignment);\n      size_type new_capacity = std::max(old_capacity + delta, default_size);\n\n      gap_buffer temp(new_capacity);\n\n      relocate_gap(pos.offset);\n      auto cursor = std::copy(start, gap_start, temp.start);\n      cursor = std::copy(first, last, cursor);\n      std::copy(gap_start + gap_size, finish, cursor);\n\n      swap(temp);\n\n      gap_start = start + old_size + num_to_insert;\n      gap_size = finish - gap_start;\n\n      return iterator(this, pos.offset);\n    }\n  }\n\n  void reserve(size_type new_cap = 0) {\n    if (capacity() >= new_cap) return;\n    if (new_cap > max_size()) throw std::length_error(\"new_cap should be less than max_size()\");\n\n    size_type old_size = size();\n    size_type new_capacity = round_up(new_cap, alignment);\n\n    gap_buffer temp(new_capacity);\n    auto cursor = std::copy(start, gap_start, temp.start);\n    std::copy(gap_start + gap_size, finish, cursor);\n    swap(temp);\n\n    gap_start = start + old_size;\n    gap_size = finish - gap_start;\n  }\n\n  size_type size() const noexcept { return finish - start - gap_size; }\n  size_type max_size() const noexcept { return size_type(1 << 31); }\n  size_type capacity() const noexcept { return finish - start; }\n\n  // ------ basis END HERE ------\n\n  reference operator [](size_type pos) {\n    return const_cast<reference>(\n        static_cast<const gap_buffer&>(*this)[pos]\n    );\n  }\n\n  const_reference at(size_type pos) const {\n    if (pos >= size()) throw std::out_of_range(\"index out of range\");\n    return (*this)[pos];\n  }\n\n  reference at(size_type pos) {\n    return const_cast<reference>(\n        static_cast<const gap_buffer&>(*this).at(pos)\n    );\n  }\n\n  const_reference front() const { return (*this)[0]; }\n  reference front() {\n    return const_cast<reference>(\n        static_cast<const gap_buffer&>(*this).front()\n    );\n  }\n\n  const_reference back() const { return (*this)[size() - 1]; }\n  reference back() {\n    return const_cast<reference>(\n        static_cast<const gap_buffer&>(*this).back()\n    );\n  }\n\n  T* data() noexcept  = delete;\n  const T* data() const noexcept = delete;\n\n  [[nodiscard]] bool empty() const noexcept { return size() == 0; }\n\n  void shrink_to_fit() {\n    gap_buffer temp(begin(), end());\n    swap(temp);\n  }\n\n  void clear() { erase(begin(), end()); }\n\n  void resize(size_type count, const value_type& value = value_type{}) {\n    if (count < size())\n      erase(begin() + count, end());\n    else\n      insert(end(), count - size(), value);\n  }\n\n  iterator insert(const_iterator pos, const T& value) {\n    return insert(pos, &value, &value + 1);\n  }\n\n  iterator insert(const_iterator pos, T&& value) {\n    return insert(pos, std::make_move_iterator(&value), std::make_move_iterator(&value + 1));\n  }\n\n  iterator insert(const_iterator pos, size_type count, const T& value) {\n    for (size_type i = 0; i < count; ++i)\n      pos = insert(pos, value);\n    return iterator(this, pos.offset);\n  }\n\n  iterator insert(const_iterator pos, std::initializer_list<T> ilist) {\n    return insert(pos, ilist.begin(), ilist.end());\n  }\n\n  void erase(const_iterator pos) { erase(pos, pos + 1); }\n\n  template<typename ... Args>\n  iterator emplace(const_iterator pos, Args&& ... args) {\n    return insert(pos, T(std::forward<Args>(args)...));\n  }\n\n  template<typename ... Args>\n  reference emplace_back(Args&& ... args) {\n    return *emplace(end(), std::forward<Args>(args)...);\n  }\n\n  void push_back(const T& value) { insert(end(), &value, &value + 1); }\n  void push_back(T&& value) { insert(end(), std::make_move_iterator(&value), std::make_move_iterator(&value + 1)); }\n  void pop_back() { erase(end() - 1); }\n\n  const_iterator begin() const noexcept { return const_iterator(this); }\n  const_iterator cbegin() const noexcept { return begin(); }\n\n  const_iterator end() const noexcept { return const_iterator(this, size()); }\n  const_iterator cend() const noexcept { return end(); }\n\n  iterator begin() noexcept { return iterator(this); }\n  iterator end() noexcept { return iterator(this, size()); }\n\n  const_reverse_iterator rbegin() const noexcept { return const_reverse_iterator(end()); }\n  const_reverse_iterator crbegin() const noexcept { return rbegin(); }\n\n  const_reverse_iterator rend() const noexcept { return const_reverse_iterator(begin()); }\n  const_reverse_iterator crend() const noexcept { return rend(); }\n\n  reverse_iterator rbegin() noexcept { return reverse_iterator(end()); }\n  reverse_iterator rend() noexcept { return reverse_iterator(begin()); }\n\n  friend\n  bool operator ==(const gap_buffer& lhs, const gap_buffer& rhs) {\n    return std::equal(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());\n  }\n\n  friend\n  bool operator !=(const gap_buffer& lhs, const gap_buffer& rhs) {\n    return !(lhs == rhs);\n  }\n\n  friend\n  bool operator <(const gap_buffer& lhs, const gap_buffer& rhs) {\n    auto[left, right] = std::mismatch(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());\n\n    if (right == rhs.end()) return false;\n    else if (left == lhs.end()) return true;\n    else return *left < *right;\n  }\n\n  friend\n  bool operator >(const gap_buffer& lhs, const gap_buffer& rhs) {\n    return rhs < lhs;\n  }\n\n  friend\n  bool operator <=(const gap_buffer& lhs, const gap_buffer& rhs) {\n    return !(rhs < lhs);\n  }\n\n  friend\n  bool operator >=(const gap_buffer& lhs, const gap_buffer& rhs) {\n    return !(lhs < rhs);\n  }\n\n  // additional\n  template<typename InputIt>\n  void append(InputIt first, InputIt last) {\n    insert(end(), first, last);\n  }\n\n  void append(const T& value) { push_back(value); }\n\n  void append(T&& value) { push_back(std::move(value)); }\n\n  template<typename InputIt>\n  void replace(const_iterator f1, const_iterator l1, InputIt f2, InputIt l2) {\n    auto cursor = erase(f1, l1);\n    insert(cursor, f2, l2);\n  }\n\n  template<typename InputIt>\n  void replace(const_iterator pos, InputIt first, InputIt last) {\n    replace(pos, pos + 1, first, last);\n  }\n\n  gap_buffer substr(const_iterator first, const_iterator last) const {\n    return substr_impl<gap_buffer>(first, last);\n  }\n\nprotected:\n\n  template<typename U>\n  U substr_impl(const_iterator first, const_iterator last) const {\n    return U(first, last);\n  }\n\n  void relocate_gap(difference_type offset) {\n    if (gap_start != start + offset) {\n      if (gap_start < start + offset)\n        std::move(gap_start /**/ + gap_size,\n                  start + offset + gap_size,\n                  gap_start);\n      else\n        std::move_backward(start + offset,\n                           gap_start,\n                           gap_start + gap_size);\n\n      gap_start = start + offset;\n    }\n  }\n\n  pointer allocate_and_construct(size_type n) {\n    pointer result = data_allocator.allocate(n);\n    std::uninitialized_default_construct_n(result, n);\n    return result;\n  }\n\n  void destroy_and_deallocate(pointer start, pointer finish) {\n    std::destroy(start, finish);\n    if (start)\n      data_allocator.deallocate(start, finish - start);\n  }\n\nprivate:\n  Allocator data_allocator;\n\n  pointer start;\n  pointer finish;\n  pointer gap_start;\n  size_type gap_size;\n};\n\ntemplate<typename T, typename Allocator>\nvoid swap(gap_buffer<T, Allocator>& lhs, gap_buffer<T, Allocator>& rhs) {\n  lhs.swap(rhs);\n}\n\n\n}\n", "meta": {"hexsha": "30128633a412da2b11f1833ec52d0b0e2c142bc9", "size": 17324, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gap_buffer.h", "max_stars_repo_name": "lie-yan/gapbuffer", "max_stars_repo_head_hexsha": "b6b3d621430029d989ebed8a672eee769c214ea5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-02-28T12:41:19.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-02T09:33:21.000Z", "max_issues_repo_path": "include/gap_buffer.h", "max_issues_repo_name": "lie-yan/gapbuffer", "max_issues_repo_head_hexsha": "b6b3d621430029d989ebed8a672eee769c214ea5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gap_buffer.h", "max_forks_repo_name": "lie-yan/gapbuffer", "max_forks_repo_head_hexsha": "b6b3d621430029d989ebed8a672eee769c214ea5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9424572317, "max_line_length": 116, "alphanum_fraction": 0.6386515816, "num_tokens": 4130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869689484852374, "lm_q2_score": 0.03732688814730781, "lm_q1q2_score": 0.015628652161635944}}
{"text": "#ifndef LIB_INCLUDE_TICK_ARRAY_VECTOR_OPERATIONS_H_\n#define LIB_INCLUDE_TICK_ARRAY_VECTOR_OPERATIONS_H_\n\n// License: BSD 3 clause\n\n#include <numeric>\n\n#include <algorithm>\n#include <atomic>\n#include <type_traits>\n\n#include \"promote.h\"\n#include \"tick/base/defs.h\"\n\nnamespace tick {\nnamespace detail {\n\ntemplate <typename T>\nstruct DLL_PUBLIC vector_operations_unoptimized {\n  template <typename K>\n  tick::promote_t<K> sum(const ulong n, const T *x) const;\n\n  template <typename K>\n  typename std::enable_if<std::is_same<T, std::atomic<K>>::value, T>::type dot(\n      const ulong n, const T *x, const K *y) const;\n\n  template <typename K>\n  typename std::enable_if<std::is_same<T, std::atomic<K>>::value, K>::type dot(\n      const ulong n, const K *x, const T *y) const;\n\n  template <typename K>\n  typename std::enable_if<!std::is_same<T, std::atomic<K>>::value, T>::type dot(\n      const ulong n, const T *x, const K *y) const;\n\n  template <typename K>\n  typename std::enable_if<std::is_same<T, std::atomic<K>>::value>::type scale(\n      const ulong n, const K alpha, T *x) const;\n\n  template <typename K>\n  typename std::enable_if<!std::is_same<T, std::atomic<K>>::value>::type scale(\n      const ulong n, const K alpha, T *x) const;\n\n  template <typename K>\n  typename std::enable_if<std::is_same<T, std::atomic<K>>::value>::type set(\n      const ulong n, const K alpha, T *x) const;\n\n  template <typename K>\n  typename std::enable_if<!std::is_same<T, std::atomic<K>>::value>::type set(\n      const ulong n, const K alpha, T *x) const;\n\n  template <typename K, typename Y>\n  typename std::enable_if<std::is_same<T, std::atomic<K>>::value &&\n                          !std::is_same<Y, std::atomic<K>>::value>::type\n  mult_incr(const uint64_t n, const K alpha, const Y *x, T *y) const;\n\n  template <typename K, typename Y>\n  typename std::enable_if<std::is_same<Y, std::atomic<K>>::value &&\n                          !std::is_same<T, std::atomic<K>>::value>::type\n  mult_incr(const uint64_t n, const K alpha, const Y *x, T *y) const;\n\n  template <typename K, typename Y>\n  typename std::enable_if<std::is_same<T, std::atomic<K>>::value &&\n                          std::is_same<Y, std::atomic<K>>::value>::type\n  mult_incr(const uint64_t n, const K alpha, const Y *x, T *y) const;\n\n  template <typename K, typename Y>\n  typename std::enable_if<std::is_same<T, K>::value &&\n                          std::is_same<Y, K>::value>::type\n  mult_incr(const uint64_t n, const K alpha, const Y *x, T *y) const;\n};\n\n}  // namespace detail\n}  // namespace tick\n\n#if !defined(TICK_CBLAS_AVAILABLE)\n\nnamespace tick {\n\ntemplate <typename T>\nusing vector_operations = detail::vector_operations_unoptimized<T>;\n\n}  // namespace tick\n\n#else  // if defined(TICK_CBLAS_AVAILABLE)\n\n// Find available blas distribution\n#if defined(TICK_USE_MKL)\n\n#include <mkl.h>\n\n#elif defined(__APPLE__)\n\n#include <Accelerate/Accelerate.h>\n\n// TODO(svp) Disabling this feature until we find a good way to determine if\n// ATLAS is actually available #define XDATA_CATLAS_AVAILABLE\n\n#else\n\nextern \"C\" {\n#include <cblas.h>\n}\n\n#endif  // defined(__APPLE__)\n\n#include \"tick/array/vector/cblas.hpp\"\n\n#endif  // if !defined(TICK_CBLAS_AVAILABLE)\n\n#include \"tick/array/vector/un_optimized.hpp\"\n\n#endif  // LIB_INCLUDE_TICK_ARRAY_VECTOR_OPERATIONS_H_\n", "meta": {"hexsha": "30756866eee78dcc69d424ba4f03a3b330be1b6d", "size": 3306, "ext": "h", "lang": "C", "max_stars_repo_path": "lib/include/tick/array/vector_operations.h", "max_stars_repo_name": "andro2157/tick", "max_stars_repo_head_hexsha": "d22d0e70c8bb2d5b232ffa7b97426010c2328edc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/include/tick/array/vector_operations.h", "max_issues_repo_name": "andro2157/tick", "max_issues_repo_head_hexsha": "d22d0e70c8bb2d5b232ffa7b97426010c2328edc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/include/tick/array/vector_operations.h", "max_forks_repo_name": "andro2157/tick", "max_forks_repo_head_hexsha": "d22d0e70c8bb2d5b232ffa7b97426010c2328edc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2566371681, "max_line_length": 80, "alphanum_fraction": 0.6799758016, "num_tokens": 890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3998116264369279, "lm_q2_score": 0.03904829650044905, "lm_q1q2_score": 0.015611962933435936}}
{"text": "#ifndef S3DCV_DEMO_DEMO_UTILS_H\n#define S3DCV_DEMO_DEMO_UTILS_H\n\n#include <s3d/cv/disparity/disparity_analyzer_stan.h>\n\n#include <gsl/gsl>\n\nclass BadNumberOfArgumentsException {};\nclass FileNotFoundException {};\n\n/**\n * Creates dataset loader from program input arguments.\n *\n * First input argument must be the dataset folder, e.g. 'Arch'\n * Second input argument must be the dataset path e.g. '/home/you/dataset'\n *\n */\ninline DatasetLoaderVSG createDatasetLoader(int argc, char* argv[]) {\n  auto input_args = gsl::span<char*>(argv, argc);\n  if (input_args.size() != 3) {\n    throw BadNumberOfArgumentsException{};\n  }\n  const std::string datasetName = input_args[1];\n  const std::string datasetPath = input_args[2];\n\n  return DatasetLoaderVSG{datasetName, datasetPath};\n}\n\ninline s3d::robust::Lmeds<s3d::StanFundamentalMatrixSolver, s3d::SampsonDistanceFunction> createRansac(\n        s3d::Size imageSize) {\n  int h = imageSize.getHeight();\n  int w = imageSize.getWidth();\n\n  s3d::robust::Parameters params;\n  params.nbTrials = 500;\n  params.distanceThreshold = 0.01 * sqrt(h * h + w * w);\n\n  return s3d::DisparityAnalyzerSTAN::RansacAlgorithmSTAN(params);\n}\n\n#endif //S3DCV_DEMO_DEMO_UTILS_H\n", "meta": {"hexsha": "ae48d02da5524e69279c5e95f1ef2c78b417a265", "size": 1196, "ext": "h", "lang": "C", "max_stars_repo_path": "src/apps/S3DCVDemo/include/demo_utils.h", "max_stars_repo_name": "hugbed/OpenS3D", "max_stars_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-16T16:38:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-20T03:23:15.000Z", "max_issues_repo_path": "src/apps/S3DCVDemo/include/demo_utils.h", "max_issues_repo_name": "hugbed/OpenS3D", "max_issues_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 40.0, "max_issues_repo_issues_event_min_datetime": "2017-04-12T17:24:44.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-21T18:41:23.000Z", "max_forks_repo_path": "src/apps/S3DCVDemo/include/demo_utils.h", "max_forks_repo_name": "hugbed/OpenS3D", "max_forks_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-07-13T21:51:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-18T16:22:03.000Z", "avg_line_length": 28.4761904762, "max_line_length": 103, "alphanum_fraction": 0.7391304348, "num_tokens": 328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34864513533394575, "lm_q2_score": 0.044680873770916896, "lm_q1q2_score": 0.015577769282700268}}
{"text": "\n/*\n* -----------------------------------------------------------------\n*  In Situ Adaptive Tabulation Library --- isat_lib.c\n*  Version: 1.6180\n*  Date: Nov 15, 2010\n* ----------------------------------------------------------------- \n*  Programmer: Americo Barbosa da Cunha Junior\n*              americo.cunhajr@gmail.com\n* -----------------------------------------------------------------\n*  Copyright (c) 2010 by Americo Barbosa da Cunha Junior\n*\n*  This program is free software: you can redistribute it and/or\n*  modify it under the terms of the GNU General Public License as\n*  published by the Free Software Foundation, either version 3 of\n*  the License, or (at your option) any later version.\n*\n*  This program is distributed in the hope that it will be useful,\n*  but WITHOUT ANY WARRANTY; without even the implied warranty of\n*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n*  GNU General Public License for more details.\n*\n*  A copy of the GNU General Public License is available in\n*  LICENSE.txt or http://www.gnu.org/licenses/.\n* -----------------------------------------------------------------\n*  This is the implementation file of a library\n*  to work with ISAT algorithm.\n* -----------------------------------------------------------------\n*/\n\n\n\n\n#include <stdlib.h>\n#include <math.h>\n#include <time.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_errno.h>\n\n#include \"../include/thrm_lib.h\"\n#include \"../include/ell_lib.h\"\n#include \"../include/ode_lib.h\"\n#include \"../include/isat_lib.h\"\n\n\n\n\n/*\n*------------------------------------------------------------\n*   isat_alloc\n*\n*   This function alocates memory for a struct isat.\n*\n*   Output:\n*   isat - pointer to a struct isat\n*\n*   last update: Jul 13, 2010\n*------------------------------------------------------------\n*/\n\nisat_wrk *isat_alloc()\n{\n    /* memory allocation for isat_wrk */\n    isat_wrk *isat = NULL;\n    isat = (isat_wrk *) malloc(sizeof(isat_wrk));\n    if ( isat == NULL )\n        return NULL;\n    \n    /* setting isat_wrk elements equal NULL and 0.0 */\n    isat->root     = NULL;\n    isat->lf       = 0;\n    isat->nd       = 0;\n    isat->add      = 0;\n    isat->grw      = 0;\n    isat->rtv      = 0;\n    isat->dev      = 0;\n    isat->hgt      = 0;\n    isat->max_lf   = 0;\n    isat->time_add = 0.0;\n    isat->time_grw = 0.0;\n    isat->time_rtv = 0.0;\n    isat->time_dev = 0.0;\n    \n    return isat;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*\n*------------------------------------------------------------\n*   isat_free\n*\n*   This function frees the memory used by a struct isat.\n*\n*   Input:\n*   isat - pointer to a struct isat\n*\n*   last update: May 10, 2009\n*------------------------------------------------------------\n*/\n\nvoid isat_free(void **isat_bl)\n{\n    isat_wrk *isat = NULL;\n    \n    /* checking if isat_bl is NULL */\n    if ( *isat_bl == NULL )\n        return;\n    \n    isat = (isat_wrk *) (*isat_bl);\n    \n    /* releasing allocated memory by isat_wrk elements */\n    if( isat->root != NULL )\n    {\n        bst_node_free((void **)&(isat->root));\n        isat->root = NULL;\n    }\n    \n    /* releasing allocated memory by isat_wrk */\n    free(*isat_bl);\n    *isat_bl = NULL;\n    \n    return;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*\n*------------------------------------------------------------\n*   isat_set\n*\n*   This function initiates ISAT binary search tree.\n*\n*   Input:\n*   isat - pointer to a struct isat\n*\n*   last update: May 13, 2009\n*------------------------------------------------------------\n*/\n\nint isat_set(isat_wrk *isat)\n{\n    /* checking if isat is NULL */\n    if ( isat == NULL )\n        return GSL_EINVAL;\n    \n    /* memory allocation for binary search tree root */\n    if ( isat->root == NULL )\n    {\n        isat->root = bst_node_alloc();\n        if ( isat->root == NULL )\n        {\n            free(isat);\n            isat = NULL;\n            return GSL_EINVAL;\n        }\n    }\n    \n    return GSL_SUCCESS;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*\n*------------------------------------------------------------\n*   isat_statistics\n*\n*   This function prints on the screen informations\n*   about the isat workspace.\n*\n*   Input:\n*   isat - pointer to a struct isat\n*\n*   last update: Jul 13, 2010\n*------------------------------------------------------------\n*/\n\nvoid isat_statistics(isat_wrk *isat)\n{\n    double time_add;\n    double time_grw;\n    double time_rtv;\n    double time_dev;\n    \n    time_add = (double) (isat->time_add / CLOCKS_PER_SEC) / isat->add;\n    time_grw = (double) (isat->time_grw / CLOCKS_PER_SEC) / isat->grw;\n    time_rtv = (double) (isat->time_rtv / CLOCKS_PER_SEC) / isat->rtv;\n    time_dev = (double) (isat->time_dev / CLOCKS_PER_SEC) / isat->dev;\n    \n    printf(\"\\n ISAT statistics:\");\n    printf(\"\\n # of adds         = %d\",   isat->add);\n    printf(\"\\n # of grows        = %d\",   isat->grw);\n    printf(\"\\n # of retrieves    = %d\",   isat->rtv);\n    printf(\"\\n # of dir. eval.   = %d\",   isat->dev);\n    printf(\"\\n # of leaves       = %d\",   isat->lf);\n    printf(\"\\n # of nodes        = %d\",   isat->nd);\n    printf(\"\\n tree height       = %d\\n\", isat->hgt);\n    \n    printf(\"\\n average values for CPU time (s):\");\n    printf(\"\\n add: %+.6e\",time_add);\n    printf(\"\\n grw: %+.6e\",time_grw);\n    printf(\"\\n rtv: %+.6e\",time_rtv);\n    printf(\"\\n dev: %+.6e\",time_dev);\n    \n    return;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*\n* -----------------------------------------------------------------\n*   isat_input\n*\n*   This function receives ISAT parameters.\n*\n*   Input:\n*   max_lf - maximum value of tree leaves\n*   etol   - ISAT error tolerance\n*   n0     - factor to multiply by unit roundoff\n*\n*   Output:\n*   success or error\n*\n*   last update: Feb 25, 2010\n* -----------------------------------------------------------------\n*/\n\nint isat_input(unsigned int *max_lf,double *etol,double *n0)\n{\n    printf(\"\\n Input ISAT parameters:\\n\");\n    \n    printf(\"\\n maximum of tree leaves:\");\n    scanf(\"%d\", max_lf);\n    printf(\"\\n %d\\n\", *max_lf);\n    if( *max_lf <= 0 )\n\tGSL_ERROR(\" max_lf must be a positive integer (max_lf > 0)\",GSL_EINVAL);\n\n    printf(\"\\n ISAT error tolerance:\");\n    scanf(\"%lf\", etol);\n    printf(\"\\n %+.1e\\n\", *etol);\n    if( *etol < 0.0 )\n\tGSL_ERROR(\" etol must be grather than zero (etol > 0.0)\",GSL_EINVAL);\n    \n    printf(\"\\n Unit roundoff multiple:\");\n    scanf(\"%lf\", n0);\n    printf(\"\\n %+.1e\\n\", *n0);\n    if( *n0 < 0.0 )\n\tGSL_ERROR(\" n0 must be grather than zero (n0 > 0.0)\",GSL_EINVAL);\n    \n    return GSL_SUCCESS;\n}\n/*----------------------------------------------------------------*/\n\n\n\n\n/*\n*------------------------------------------------------------\n*   isat_eoa_matrix\n*\n*   This function computes the EOA matrix in Cholesky form.\n*   \n*   Input:\n*   A    - gradient matrix\n*   n0   - factor to multiply by unit roundoff\n*   etol - error tolerance\n*\n*   Output:\n*   L    - EOA Cholesky matrix\n*\n*   last update: Feb 19, 2010\n*------------------------------------------------------------\n*/\n\nvoid isat_eoa_mtrx(gsl_matrix *A,double etol,double n0,\n\t\t\t\t\t\tgsl_matrix *L)\n{\n    unsigned int i;\n    double  eps_max   = 0.5;\n    double  eps_min   = etol/(n0*DBL_EPSILON);\n    gsl_matrix *Aetol = NULL;\n    gsl_matrix *V     = NULL;\n    gsl_vector *sig   = NULL;\n\n    /* memory allocation */\n    Aetol = gsl_matrix_calloc(A->size2,A->size2);\n    V     = gsl_matrix_calloc(A->size2,A->size2);\n    sig   = gsl_vector_calloc(A->size2);\n    \n    /* Aetol := A */\n    gsl_matrix_memcpy(Aetol,A);\n    \n    /* Aetol := (1/etol).A */\n    gsl_matrix_scale (Aetol,1.0/etol);\n\n    /* Aetol = U*sig*V^T */\n    ell_psd2eig(Aetol,V,sig);\n\n    /* eliminating small and large singular values */\n    for ( i = 0; i < sig->size; i++ )\n        sig->data[i] = GSL_MIN( GSL_MAX(sig->data[i],eps_max), eps_min);\n    \n    /* V*sig^2*V^T = L*L^T */\n    ell_eig2chol(V,sig,L);\n    \n    /* releasing allocated memory */\n    gsl_vector_free(sig);\n    gsl_matrix_free(V);\n    gsl_matrix_free(Aetol);\n    sig   = NULL;\n    V     = NULL;\n    Aetol = NULL;\n    \n    return;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*\n*------------------------------------------------------------\n*   isat_lerror\n*\n*   This function computes the local error defined as\n*\n*   eps = 2-norm(Rl(phi)- R(phi)) where\n*\n*   Rl(phi) = R(phi0) + A*(phi-phi0).\n*\n*   Input:\n*   Rphi  - reaction mapping of phi\n*   Rphi0 - reaction mapping of phi0\n*   A     - mapping gradient matrix\n*   phi   - query composition\n*   phi0  - initial composition\n*\n*   Output:\n*   eps   - local error\n*\n*   last update: Feb 19, 2010\n*------------------------------------------------------------\n*/\n\ndouble isat_lerror(gsl_vector *Rphi,gsl_vector *Rphi0,\n\t\tgsl_matrix *A,gsl_vector *phi,gsl_vector *phi0)\n{\n    double eps;\n    gsl_vector *Rlphi = NULL;\n    \n    /* memory allocation for Rlphi */\n    Rlphi = gsl_vector_calloc(phi->size);\n    \n    /* Rlphi := R(phi0) + A*(phi-phi0) */\n    linear_approx(phi,phi0,Rphi0,A,Rlphi);\n    \n    /* Rlphi := Rl(phi) - R(phi) */\n    gsl_vector_sub(Rlphi,Rphi);\n    \n    /* eps := 2-norm(Rl(phi) - R(phi)) */\n    eps = gsl_blas_dnrm2(Rlphi);\n    \n    /* releasing allocated memory */\n    gsl_vector_free(Rlphi);\n    Rlphi = NULL;\n    \n    return eps;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*\n*------------------------------------------------------------\n*   isat4\n*\n*   This function executes the 4-th version of the\n*   in situ adaptive tabulation algorithm.\n*\n*   \n*   Input:\n*   isat      - isat workspace\n*   thrm_data - thermochemistry workspace\n*   etol      - error tolerance\n*   n0        - factor to multiply by unit roundoff\n*   t0        - initial time\n*   delta_t   - time step\n*   phi       - query composition\n*   A         - mapping gradient matrix\n*   L         - EOA Cholesky matrix\n*\n*   Output:\n*   Rphi      - reaction mapping\n*   success or error\n*\n*   last update: Nov 15, 2010\n*------------------------------------------------------------\n*/\n\nint isat4(isat_wrk *isat,void *thrm_data,void *cvode_mem,\n\t    double etol,double n0,double t0,double delta_t,\n    gsl_vector *phi,gsl_matrix *A,gsl_matrix *L,gsl_vector *Rphi)\n{\n    clock_t cpu_start = clock();\n    \n    /* ISAT first step */\n    if( isat->lf == 0 )\n    {\n        int flag;\n        bst_leaf *first_leaf = NULL;\n\t\n\t/* memory allocation for first_leaf */\n        first_leaf = bst_leaf_alloc();\n\tif ( first_leaf == NULL )\n                return GSL_ENOMEM;\n        \n        /* performing direct integration */\n        flag = odesolver_reinit(thrm_eqs,thrm_data,t0,\n                                        ATOL,RTOL,phi,cvode_mem);\n        if ( flag != GSL_SUCCESS )\n            return flag;\n        \n        flag = odesolver(cvode_mem,delta_t,Rphi);\n        if ( flag != GSL_SUCCESS )\n            return flag;\n        \n        /* computing the mapping gradient matrix */\n        flag = gradient(thrm_eqs,thrm_data,cvode_mem,t0,delta_t,\n                                                ATOL,RTOL,phi,Rphi,A);\n        if ( flag != GSL_SUCCESS )\n            return flag;\n        \n        /* computing EOA Cholesky matrix */\n        isat_eoa_mtrx(A,etol,n0,L);\n        \n        /* setting first leaf elements */\n        bst_leaf_set(phi,Rphi,A,L,first_leaf);\n        isat->root->r_leaf = first_leaf;\n        \n        /* updating leaves and height counters */\n        isat->lf++;\n        isat->hgt = bst_height(isat->root);\n        \n        return GSL_SUCCESS;\n    }\n    \n    \n    /* ISAT second and following steps */\n    int side, flag;\n    double dot         = 0.0;\n    bst_leaf *end_leaf = NULL;\n    bst_node *end_node = NULL;\n    \n    \n    /* searching for the near composition in binary search tree */\n    if( isat->lf > 1 )\n\tside = bst_search(isat->root,phi,&end_node,&end_leaf);\n    else\n    {\n        end_node = isat->root;\n        end_leaf = isat->root->r_leaf;\n        side     = RIGHT;\n    }\n    \n    /* checking if the near composition is inside EOA */\n    dot = ell_pt_in(phi,end_leaf->phi,end_leaf->L);\n    if( gsl_fcmp(dot,1.0,ATOL) < 1 )\n    {\n        /* computing linear approximation */\n        linear_approx(phi,end_leaf->phi,end_leaf->Rphi,end_leaf->A,Rphi);\n        \n        /* updating counters */\n        isat->rtv++;\n\tisat->time_rtv += clock() - cpu_start;\n        \n        return GSL_SUCCESS;\n    }\n    else\n    {\n        double lerror = 0.0;\n\t\n        /* performing direct integration */\n        flag = odesolver_reinit(thrm_eqs,thrm_data,t0,\n                                        ATOL,RTOL,phi,cvode_mem);\n        if ( flag != GSL_SUCCESS )\n            return flag;\n        \n        flag = odesolver(cvode_mem,delta_t,Rphi);\n        if ( flag != GSL_SUCCESS )\n            return flag;\n        \n        /* computing ISAT local error */\n        lerror = isat_lerror(Rphi,end_leaf->Rphi,\n                            end_leaf->A,phi,end_leaf->phi);\n        \n        /* checking if lerror is greater than etol */\n        if( gsl_fcmp(lerror,etol,ATOL) < 1 )\n        {\n            /* growing the EOA */\n            ell_pt_modify(phi,end_leaf->phi,end_leaf->L);\n            \n            /* updating counters */\n            isat->grw++;\n\t    isat->time_grw += clock() - cpu_start;\n            \n            return GSL_SUCCESS;\n        }\n        else\n        {\n\t    /* checking if the maximum # of leaves was excced */\n\t    if( isat->lf > isat->max_lf )\n\t    {\n\t        /*  updating counter */\n\t        isat->dev++;\n\t\tisat->time_dev +=  clock() - cpu_start;\n\t\t\n\t\treturn GSL_SUCCESS;\n\t    }\n\t    \n            bst_leaf *new_leaf = NULL;\n            \n\t    /* memory allocation */\n            new_leaf = bst_leaf_alloc();\n            if ( new_leaf == NULL )\n                return GSL_ENOMEM;\n            \n            /* computing the mapping gradient matrix */\n            flag = gradient(thrm_eqs,thrm_data,cvode_mem,t0,delta_t,\n                                                ATOL,RTOL,phi,Rphi,A);\n            if ( flag != GSL_SUCCESS )\n\t\treturn flag;\n            \n            /* computing EOA Cholesky matrix */\n            isat_eoa_mtrx(A,etol,n0,L);\n            \n            /* setting new_leaf elements */\n            bst_leaf_set(phi,Rphi,A,L,new_leaf);\n            \n            /* cheking if binary search tree has more than one leaf */\n            if( isat->lf > 1 )\n            {\n                bst_node *new_node = NULL;\n\t\t\n\t\t/* memory allocation for new node */\n                new_node = bst_node_alloc();\n                if ( new_node == NULL )\n                    return GSL_ENOMEM;\n                \n\t\t/* setting the leaves of the new node */\n                bst_node_set(end_leaf,new_leaf,new_node);\n\t\t\n\t\t/* adding the new node to the tree */\n                bst_node_add(side,end_node,new_node);\n            }\n\t    else\n                bst_node_set(end_leaf,new_leaf,end_node);\n            \n            /* updating counters */\n            isat->add++;\n            isat->lf++;\n            isat->nd++;\n            isat->hgt = bst_height(isat->root);\n\t    isat->time_add += clock() - cpu_start;\n            \n            return GSL_SUCCESS;\n        }\n    }\n}\n/*------------------------------------------------------------*/\n", "meta": {"hexsha": "7449bade9589b495b01864a58239d732efc987f0", "size": 15285, "ext": "c", "lang": "C", "max_stars_repo_path": "CRFlowLib-1.0/src/isat_lib.c", "max_stars_repo_name": "americocunhajr/CRFlowLib", "max_stars_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-29T12:56:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-29T12:56:14.000Z", "max_issues_repo_path": "CRFlowLib-1.0/src/isat_lib.c", "max_issues_repo_name": "americocunhajr/CRFlowLib", "max_issues_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CRFlowLib-1.0/src/isat_lib.c", "max_forks_repo_name": "americocunhajr/CRFlowLib", "max_forks_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-15T03:57:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-30T01:44:13.000Z", "avg_line_length": 26.3989637306, "max_line_length": 73, "alphanum_fraction": 0.4877330716, "num_tokens": 3945, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38121955219593834, "lm_q2_score": 0.04084571722347213, "lm_q1q2_score": 0.015571186029053972}}
{"text": "/*\n    Licensed to the OpenAirInterface (OAI) Software Alliance under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The OpenAirInterface Software Alliance licenses this file to You under\n    the OAI Public License, Version 1.1  (the \"License\"); you may not use this file\n    except in compliance with the License.\n    You may obtain a copy of the License at\n\n        http://www.openairinterface.org/?page_id=698\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n    -------------------------------------------------------------------------------\n    For more information about the OpenAirInterface (OAI) Software Alliance:\n        contact@openairinterface.org\n*/\n\n/*! \\file PHY/LTE_TRANSPORT/dlsch_demodulation.c\n    \\brief Top-level routines for demodulating the PDSCH physical channel from 36-211, V8.6 2009-03\n    \\author R. Knopp, F. Kaltenberger,A. Bhamri, S. Aubert, X. Xiang\n    \\date 2011\n    \\version 0.1\n    \\company Eurecom\n    \\email: knopp@eurecom.fr,florian.kaltenberger@eurecom.fr,ankit.bhamri@eurecom.fr,sebastien.aubert@eurecom.fr\n    \\note\n    \\warning\n*/\n#include \"PHY/defs_UE.h\"\n#include \"PHY/phy_extern_ue.h\"\n#include \"SCHED_UE/sched_UE.h\"\n#include \"transport_ue.h\"\n#include \"transport_proto_ue.h\"\n#include \"PHY/sse_intrin.h\"\n#include \"T.h\"\n#include<stdio.h>\n#include<math.h>\n#include <stdlib.h>\n#include <string.h>\n#include <linux/version.h>\n#if RHEL_RELEASE_CODE >= 1796\n    #include <lapacke/lapacke_utils.h>\n    #include <lapacke/lapacke.h>\n#else\n    #include <lapacke_utils.h>\n    #include <lapacke.h>\n#endif\n#include <cblas.h>\n#include \"linear_preprocessing_rec.h\"\n\n#define NOCYGWIN_STATIC\n//#define DEBUG_MMSE\n\n\n/*  dynamic shift for LLR computation for TM3/4\n    set as command line argument, see lte-softmodem.c\n    default value: 0\n*/\nint16_t dlsch_demod_shift = 0;\nint16_t interf_unaw_shift = 13;\n\nunsigned char offset_mumimo_llr_drange_fix = 0;\n//inferference-free case\nunsigned char interf_unaw_shift_tm4_mcs[29] = {5, 3, 4, 3, 3, 2, 1, 1, 2, 0, 1, 1, 1, 1, 0, 0,\n                                               1, 1, 1, 1, 0, 2, 1, 0, 1, 0, 1, 0, 0\n                                              } ;\nunsigned char interf_unaw_shift_tm1_mcs[29] = {5, 5, 4, 3, 3, 3, 2, 2, 4, 4, 2, 3, 3, 3, 1, 1,\n                                               0, 1, 1, 2, 5, 4, 4, 6, 5, 1, 0, 5, 6\n                                              } ; // mcs 21, 26, 28 seem to be errorneous\n\n/*\n    //original values from sebastion + same hand tuning\n    unsigned char offset_mumimo_llr_drange[29][3]={{8,8,8},{7,7,7},{7,7,7},{7,7,7},{6,6,6},{6,6,6},{6,6,6},{5,5,5},{4,4,4},{1,2,4}, // QPSK\n    {5,5,4},{5,5,5},{5,5,5},{3,3,3},{2,2,2},{2,2,2},{2,2,2}, // 16-QAM\n    {2,2,1},{3,3,3},{3,3,3},{3,3,1},{2,2,2},{2,2,2},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0}}; //64-QAM\n*/\n/*\n    //first optimization try\n    unsigned char offset_mumimo_llr_drange[29][3]={{7, 8, 7},{6, 6, 7},{6, 6, 7},{6, 6, 6},{5, 6, 6},{5, 5, 6},{5, 5, 6},{4, 5, 4},{4, 3, 4},{3, 2, 2},{6, 5, 5},{5, 4, 4},{5, 5, 4},{3, 3, 2},{2, 2, 1},{2, 1, 1},{2, 2, 2},{3, 3, 3},{3, 3, 2},{3, 3, 2},{3, 2, 1},{2, 2, 2},{2, 2, 2},{0, 0, 0},{0, 0, 0},{0, 0, 0},{0, 0, 0},{0, 0, 0}};\n*/\n//second optimization try\n/*\n    unsigned char offset_mumimo_llr_drange[29][3]={{5, 8, 7},{4, 6, 8},{3, 6, 7},{7, 7, 6},{4, 7, 8},{4, 7, 4},{6, 6, 6},{3, 6, 6},{3, 6, 6},{1, 3, 4},{1, 1, 0},{3, 3, 2},{3, 4, 1},{4, 0, 1},{4, 2, 2},{3, 1, 2},{2, 1, 0},{2, 1, 1},{1, 0, 1},{1, 0, 1},{0, 0, 0},{1, 0, 0},{0, 0, 0},{0, 1, 0},{1, 0, 0},{0, 0, 0},{0, 0, 0},{0, 0, 0},{0, 0, 0}};  w\n*/\nunsigned char offset_mumimo_llr_drange[29][3] = {{0, 6, 5}, {0, 4, 5}, {0, 4, 5}, {0, 5, 4}, {0, 5, 6}, {0, 5, 3}, {0, 4, 4}, {0, 4, 4}, {0, 3, 3}, {0, 1, 2}, {1, 1, 0}, {1, 3, 2}, {3, 4, 1}, {2, 0, 0}, {2, 2, 2}, {1, 1, 1}, {2, 1, 0}, {2, 1, 1}, {1, 0, 1}, {1, 0, 1}, {0, 0, 0}, {1, 0, 0}, {0, 0, 0}, {0, 1, 0}, {1, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}};\n\n\nextern void print_shorts(char *s, int16_t *x);\n\n\nint rx_pdsch(PHY_VARS_UE *ue,\n             PDSCH_t type,\n             unsigned char eNB_id,\n             unsigned char eNB_id_i, //if this == ue->n_connected_eNB, we assume MU interference\n             uint32_t frame,\n             uint8_t subframe,\n             unsigned char symbol,\n             unsigned char first_symbol_flag,\n             RX_type_t rx_type,\n             unsigned char i_mod,\n             unsigned char harq_pid)\n{\n    LTE_UE_COMMON *common_vars  = &ue->common_vars;\n    LTE_UE_PDSCH **pdsch_vars;\n    LTE_DL_FRAME_PARMS *frame_parms    = &ue->frame_parms;\n    PHY_MEASUREMENTS *measurements = &ue->measurements;\n    LTE_UE_DLSCH_t   **dlsch;\n    int avg[4];\n    int avg_0[2];\n    int avg_1[2];\n    unsigned short mmse_flag = 0;\n#if UE_TIMING_TRACE\n    uint8_t slot = 0;\n#endif\n    unsigned char aatx, aarx;\n    unsigned short nb_rb = 0, round;\n    int avgs = 0, rb;\n    LTE_DL_UE_HARQ_t *dlsch0_harq, *dlsch1_harq = 0;\n    uint8_t beamforming_mode;\n    uint32_t *rballoc;\n    int32_t **rxdataF_comp_ptr;\n    int32_t **dl_ch_mag_ptr;\n    int32_t codeword_TB0 = -1;\n    int32_t codeword_TB1 = -1;\n\n    switch(type)\n    {\n        case SI_PDSCH:\n            pdsch_vars = &ue->pdsch_vars_SI[eNB_id];\n            dlsch = &ue->dlsch_SI[eNB_id];\n            dlsch0_harq = dlsch[0]->harq_processes[harq_pid];\n            beamforming_mode  = 0;\n            break;\n\n        case RA_PDSCH:\n            pdsch_vars = &ue->pdsch_vars_ra[eNB_id];\n            dlsch = &ue->dlsch_ra[eNB_id];\n            dlsch0_harq = dlsch[0]->harq_processes[harq_pid];\n            beamforming_mode  = 0;\n            break;\n\n        case PDSCH:\n            pdsch_vars = ue->pdsch_vars[ue->current_thread_id[subframe]];\n            dlsch = ue->dlsch[ue->current_thread_id[subframe]][eNB_id];\n            //printf(\"status TB0 = %d, status TB1 = %d \\n\", dlsch[0]->harq_processes[harq_pid]->status, dlsch[1]->harq_processes[harq_pid]->status);\n            LOG_D(PHY, \"AbsSubframe %d.%d / Sym %d harq_pid %d,  harq status %d.%d \\n\",\n                  frame, subframe, symbol, harq_pid,\n                  dlsch[0]->harq_processes[harq_pid]->status,\n                  dlsch[1]->harq_processes[harq_pid]->status);\n\n            if((dlsch[0]->harq_processes[harq_pid]->status == ACTIVE) &&\n                    (dlsch[1]->harq_processes[harq_pid]->status == ACTIVE))\n            {\n                codeword_TB0 = dlsch[0]->harq_processes[harq_pid]->codeword;\n                codeword_TB1 = dlsch[1]->harq_processes[harq_pid]->codeword;\n                dlsch0_harq = dlsch[codeword_TB0]->harq_processes[harq_pid];\n                dlsch1_harq = dlsch[codeword_TB1]->harq_processes[harq_pid];\n#ifdef DEBUG_HARQ\n                printf(\"[DEMOD] I am assuming both TBs are active\\n\");\n#endif\n            }\n            else if((dlsch[0]->harq_processes[harq_pid]->status == ACTIVE) &&\n                    (dlsch[1]->harq_processes[harq_pid]->status != ACTIVE))\n            {\n                codeword_TB0 = dlsch[0]->harq_processes[harq_pid]->codeword;\n                dlsch0_harq = dlsch[0]->harq_processes[harq_pid];\n                dlsch1_harq = NULL;\n                codeword_TB1 = -1;\n#ifdef DEBUG_HARQ\n                printf(\"[DEMOD] I am assuming only TB0 is active\\n\");\n#endif\n            }\n            else if((dlsch[0]->harq_processes[harq_pid]->status != ACTIVE) &&\n                    (dlsch[1]->harq_processes[harq_pid]->status == ACTIVE))\n            {\n                codeword_TB1 = dlsch[1]->harq_processes[harq_pid]->codeword;\n                dlsch0_harq  = dlsch[1]->harq_processes[harq_pid];\n                dlsch1_harq  = NULL;\n                codeword_TB0 = -1;\n#ifdef DEBUG_HARQ\n                printf(\"[DEMOD] I am assuming only TB1 is active, it is in cw %d\\n\", dlsch0_harq->codeword);\n#endif\n            }\n            else\n            {\n                LOG_E(PHY, \"[UE][FATAL] Frame %d subframe %d: no active DLSCH\\n\", ue->proc.proc_rxtx[0].frame_rx, subframe);\n                return(-1);\n            }\n\n            beamforming_mode  = ue->transmission_mode[eNB_id] < 7 ? 0 : ue->transmission_mode[eNB_id];\n            break;\n\n        default:\n            LOG_E(PHY, \"[UE][FATAL] Frame %d subframe %d: Unknown PDSCH format %d\\n\", ue->proc.proc_rxtx[0].frame_rx, subframe, type);\n            return(-1);\n            break;\n    }\n\n#ifdef DEBUG_HARQ\n    printf(\"[DEMOD] MIMO mode = %d\\n\", dlsch0_harq->mimo_mode);\n    printf(\"[DEMOD] cw for TB0 = %d, cw for TB1 = %d\\n\", codeword_TB0, codeword_TB1);\n#endif\n    DevAssert(dlsch0_harq);\n    round = dlsch0_harq->round;\n    //printf(\"round = %d\\n\", round);\n\n    if(eNB_id > 2)\n    {\n        LOG_W(PHY, \"dlsch_demodulation.c: Illegal eNB_id %d\\n\", eNB_id);\n        return(-1);\n    }\n\n    if(!common_vars)\n    {\n        LOG_W(PHY, \"dlsch_demodulation.c: Null common_vars\\n\");\n        return(-1);\n    }\n\n    if(!dlsch[0])\n    {\n        LOG_W(PHY, \"dlsch_demodulation.c: Null dlsch_ue pointer\\n\");\n        return(-1);\n    }\n\n    if(!pdsch_vars)\n    {\n        LOG_W(PHY, \"dlsch_demodulation.c: Null pdsch_vars pointer\\n\");\n        return(-1);\n    }\n\n    if(!frame_parms)\n    {\n        LOG_W(PHY, \"dlsch_demodulation.c: Null frame_parms\\n\");\n        return(-1);\n    }\n\n    if(((frame_parms->Ncp == NORMAL) && (symbol >= 7)) ||\n            ((frame_parms->Ncp == EXTENDED) && (symbol >= 6)))\n    {\n        rballoc = dlsch0_harq->rb_alloc_odd;\n    }\n    else\n    {\n        rballoc = dlsch0_harq->rb_alloc_even;\n    }\n\n    if(dlsch0_harq->mimo_mode > DUALSTREAM_PUSCH_PRECODING)\n    {\n        LOG_E(PHY, \"This transmission mode is not yet supported!\\n\");\n        return(-1);\n    }\n\n    if((dlsch0_harq->mimo_mode == LARGE_CDD) || ((dlsch0_harq->mimo_mode >= DUALSTREAM_UNIFORM_PRECODING1) && (dlsch0_harq->mimo_mode <= DUALSTREAM_PUSCH_PRECODING)))\n    {\n        DevAssert(dlsch1_harq);\n\n        if(eNB_id != eNB_id_i)\n        {\n            LOG_E(PHY, \"TM3/TM4 requires to set eNB_id==eNB_id_i!\\n\");\n            return(-1);\n        }\n    }\n\n#if UE_TIMING_TRACE\n\n    if(symbol > ue->frame_parms.symbols_per_tti >> 1)\n    {\n        slot = 1;\n    }\n\n#endif\n#ifdef DEBUG_HARQ\n    printf(\"Demod  dlsch0_harq->pmi_alloc %d\\n\",  dlsch0_harq->pmi_alloc);\n#endif\n\n    if(frame_parms->nb_antenna_ports_eNB > 1 && beamforming_mode == 0)\n    {\n#ifdef DEBUG_DLSCH_MOD\n        LOG_D(PHY, \"dlsch: using pmi %x (%p), rb_alloc %x\\n\", pmi2hex_2Ar1(dlsch0_harq->pmi_alloc), dlsch[0], dlsch0_harq->rb_alloc_even[0]);\n#endif\n#if UE_TIMING_TRACE\n        start_meas(&ue->generic_stat_bis[ue->current_thread_id[subframe]][slot]);\n#endif\n        nb_rb = dlsch_extract_rbs_dual(common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].rxdataF,\n                                       common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].dl_ch_estimates[eNB_id],\n                                       pdsch_vars[eNB_id]->rxdataF_ext,\n                                       pdsch_vars[eNB_id]->dl_ch_estimates_ext,\n                                       dlsch0_harq->pmi_alloc,\n                                       pdsch_vars[eNB_id]->pmi_ext,\n                                       rballoc,\n                                       symbol,\n                                       subframe,\n                                       ue->high_speed_flag,\n                                       frame_parms,\n                                       dlsch0_harq->mimo_mode);\n#ifdef DEBUG_DLSCH_MOD\n        printf(\"dlsch: using pmi %lx, rb_alloc %x, pmi_ext \", pmi2hex_2Ar1(dlsch0_harq->pmi_alloc), *rballoc);\n\n        for(rb = 0; rb < nb_rb; rb++)\n        {\n            printf(\"%d\", pdsch_vars[eNB_id]->pmi_ext[rb]);\n        }\n\n        printf(\"\\n\");\n#endif\n\n        if(rx_type >= rx_IC_single_stream)\n        {\n            if(eNB_id_i < ue->n_connected_eNB) // we are in TM5\n                nb_rb = dlsch_extract_rbs_dual(common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].rxdataF,\n                                               common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].dl_ch_estimates[eNB_id_i],\n                                               pdsch_vars[eNB_id_i]->rxdataF_ext,\n                                               pdsch_vars[eNB_id_i]->dl_ch_estimates_ext,\n                                               dlsch0_harq->pmi_alloc,\n                                               pdsch_vars[eNB_id_i]->pmi_ext,\n                                               rballoc,\n                                               symbol,\n                                               subframe,\n                                               ue->high_speed_flag,\n                                               frame_parms,\n                                               dlsch0_harq->mimo_mode);\n            else\n                nb_rb = dlsch_extract_rbs_dual(common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].rxdataF,\n                                               common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].dl_ch_estimates[eNB_id],\n                                               pdsch_vars[eNB_id_i]->rxdataF_ext,\n                                               pdsch_vars[eNB_id_i]->dl_ch_estimates_ext,\n                                               dlsch0_harq->pmi_alloc,\n                                               pdsch_vars[eNB_id_i]->pmi_ext,\n                                               rballoc,\n                                               symbol,\n                                               subframe,\n                                               ue->high_speed_flag,\n                                               frame_parms,\n                                               dlsch0_harq->mimo_mode);\n        }\n    }\n    else if(beamforming_mode == 0)    //else if nb_antennas_ports_eNB==1 && beamforming_mode == 0\n    {\n        nb_rb = dlsch_extract_rbs_single(common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].rxdataF,\n                                         common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].dl_ch_estimates[eNB_id],\n                                         pdsch_vars[eNB_id]->rxdataF_ext,\n                                         pdsch_vars[eNB_id]->dl_ch_estimates_ext,\n                                         dlsch0_harq->pmi_alloc,\n                                         pdsch_vars[eNB_id]->pmi_ext,\n                                         rballoc,\n                                         symbol,\n                                         subframe,\n                                         ue->high_speed_flag,\n                                         frame_parms);\n\n        if(rx_type == rx_IC_single_stream)\n        {\n            if(eNB_id_i < ue->n_connected_eNB)\n                nb_rb = dlsch_extract_rbs_single(common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].rxdataF,\n                                                 common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].dl_ch_estimates[eNB_id_i],\n                                                 pdsch_vars[eNB_id_i]->rxdataF_ext,\n                                                 pdsch_vars[eNB_id_i]->dl_ch_estimates_ext,\n                                                 dlsch0_harq->pmi_alloc,\n                                                 pdsch_vars[eNB_id_i]->pmi_ext,\n                                                 rballoc,\n                                                 symbol,\n                                                 subframe,\n                                                 ue->high_speed_flag,\n                                                 frame_parms);\n            else\n                nb_rb = dlsch_extract_rbs_single(common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].rxdataF,\n                                                 common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].dl_ch_estimates[eNB_id],\n                                                 pdsch_vars[eNB_id_i]->rxdataF_ext,\n                                                 pdsch_vars[eNB_id_i]->dl_ch_estimates_ext,\n                                                 dlsch0_harq->pmi_alloc,\n                                                 pdsch_vars[eNB_id_i]->pmi_ext,\n                                                 rballoc,\n                                                 symbol,\n                                                 subframe,\n                                                 ue->high_speed_flag,\n                                                 frame_parms);\n        }\n    }\n    else if(beamforming_mode == 7)    //else if beamforming_mode == 7\n    {\n        nb_rb = dlsch_extract_rbs_TM7(common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].rxdataF,\n                                      pdsch_vars[eNB_id]->dl_bf_ch_estimates,\n                                      pdsch_vars[eNB_id]->rxdataF_ext,\n                                      pdsch_vars[eNB_id]->dl_bf_ch_estimates_ext,\n                                      rballoc,\n                                      symbol,\n                                      subframe,\n                                      ue->high_speed_flag,\n                                      frame_parms);\n    }\n    else if(beamforming_mode > 7)\n    {\n        LOG_W(PHY, \"dlsch_demodulation: beamforming mode not supported yet.\\n\");\n    }\n\n    //printf(\"nb_rb = %d, eNB_id %d\\n\",nb_rb,eNB_id);\n    if(nb_rb == 0)\n    {\n        //    LOG_D(PHY,\"dlsch_demodulation.c: nb_rb=0\\n\");\n        return(-1);\n    }\n\n#if UE_TIMING_TRACE\n    stop_meas(&ue->generic_stat_bis[ue->current_thread_id[subframe]][slot]);\n    LOG_I(PHY, \"[AbsSFN %d.%d] Slot%d Symbol %d Flag %d type %d: Pilot/Data extraction  %5.2f \\n\", frame, subframe, slot, symbol,\n          ue->high_speed_flag, type, ue->generic_stat_bis[ue->current_thread_id[subframe]][slot].p_time / (cpuf * 1000.0));\n#endif\n#if UE_TIMING_TRACE\n    start_meas(&ue->generic_stat_bis[ue->current_thread_id[subframe]][slot]);\n#endif\n    aatx = frame_parms->nb_antenna_ports_eNB;\n    aarx = frame_parms->nb_antennas_rx;\n    dlsch_scale_channel(pdsch_vars[eNB_id]->dl_ch_estimates_ext,\n                        frame_parms,\n                        dlsch,\n                        symbol,\n                        nb_rb);\n\n    if((dlsch0_harq->mimo_mode < DUALSTREAM_UNIFORM_PRECODING1) &&\n            (rx_type == rx_IC_single_stream) &&\n            (eNB_id_i == ue->n_connected_eNB) &&\n            (dlsch0_harq->dl_power_off == 0)\n      )   // TM5 two-user\n    {\n        dlsch_scale_channel(pdsch_vars[eNB_id_i]->dl_ch_estimates_ext,\n                            frame_parms,\n                            dlsch,\n                            symbol,\n                            nb_rb);\n    }\n\n#if UE_TIMING_TRACE\n    stop_meas(&ue->generic_stat_bis[ue->current_thread_id[subframe]][slot]);\n    LOG_I(PHY, \"[AbsSFN %d.%d] Slot%d Symbol %d: Channel Scale  %5.2f \\n\", frame, subframe, slot, symbol, ue->generic_stat_bis[ue->current_thread_id[subframe]][slot].p_time / (cpuf * 1000.0));\n    start_meas(&ue->generic_stat_bis[ue->current_thread_id[subframe]][slot]);\n#endif\n\n    if(first_symbol_flag == 1)\n    {\n        if(beamforming_mode == 0)\n        {\n            if(dlsch0_harq->mimo_mode < LARGE_CDD)\n            {\n                dlsch_channel_level(pdsch_vars[eNB_id]->dl_ch_estimates_ext,\n                                    frame_parms,\n                                    avg,\n                                    symbol,\n                                    nb_rb);\n                avgs = 0;\n\n                for(aatx = 0; aatx < frame_parms->nb_antenna_ports_eNB; aatx++)\n                    for(aarx = 0; aarx < frame_parms->nb_antennas_rx; aarx++)\n                    {\n                        avgs = cmax(avgs, avg[(aatx << 1) + aarx]);\n                    }\n\n                pdsch_vars[eNB_id]->log2_maxh = (log2_approx(avgs) / 2) + 1;\n            }\n            else if((dlsch0_harq->mimo_mode == LARGE_CDD) ||\n                    ((dlsch0_harq->mimo_mode >= DUALSTREAM_UNIFORM_PRECODING1) &&\n                     (dlsch0_harq->mimo_mode <= DUALSTREAM_PUSCH_PRECODING)))\n            {\n                dlsch_channel_level_TM34(pdsch_vars[eNB_id]->dl_ch_estimates_ext,\n                                         frame_parms,\n                                         pdsch_vars[eNB_id]->pmi_ext,\n                                         avg_0,\n                                         avg_1,\n                                         symbol,\n                                         nb_rb,\n                                         mmse_flag,\n                                         dlsch0_harq->mimo_mode);\n                LOG_D(PHY, \"Channel Level TM34  avg_0 %d, avg_1 %d, rx_type %d, rx_standard %d, dlsch_demod_shift %d \\n\", avg_0[0],\n                      avg_1[0], rx_type, rx_standard, dlsch_demod_shift);\n\n                if(rx_type > rx_standard)\n                {\n                    avg_0[0] = (log2_approx(avg_0[0]) / 2) + dlsch_demod_shift; // + 2 ;//+ 4;\n                    avg_1[0] = (log2_approx(avg_1[0]) / 2) + dlsch_demod_shift; // + 2 ;//+ 4;\n                    pdsch_vars[eNB_id]->log2_maxh0 = cmax(avg_0[0], 0);\n                    pdsch_vars[eNB_id]->log2_maxh1 = cmax(avg_1[0], 0);\n                    // printf(\"dlsch_demod_shift  %d\\n\", dlsch_demod_shift);\n                }\n                else\n                {\n                    avg_0[0] = (log2_approx(avg_0[0]) / 2) - 13 + interf_unaw_shift;\n                    avg_1[0] = (log2_approx(avg_1[0]) / 2) - 13 + interf_unaw_shift;\n                    pdsch_vars[eNB_id]->log2_maxh0 = cmax(avg_0[0], 0);\n                    pdsch_vars[eNB_id]->log2_maxh1 = cmax(avg_1[0], 0);\n                }\n            }\n            else if(dlsch0_harq->mimo_mode < DUALSTREAM_UNIFORM_PRECODING1)    // single-layer precoding (TM5, TM6)\n            {\n                if((rx_type == rx_IC_single_stream) && (eNB_id_i == ue->n_connected_eNB) && (dlsch0_harq->dl_power_off == 0))\n                {\n                    dlsch_channel_level_TM56(pdsch_vars[eNB_id]->dl_ch_estimates_ext,\n                                             frame_parms,\n                                             pdsch_vars[eNB_id]->pmi_ext,\n                                             avg,\n                                             symbol,\n                                             nb_rb);\n                    avg[0] = log2_approx(avg[0]) - 13 + offset_mumimo_llr_drange[dlsch0_harq->mcs][(i_mod >> 1) - 1];\n                    pdsch_vars[eNB_id]->log2_maxh = cmax(avg[0], 0);\n                }\n                else if(dlsch0_harq->dl_power_off == 1)    //TM6\n                {\n                    dlsch_channel_level(pdsch_vars[eNB_id]->dl_ch_estimates_ext,\n                                        frame_parms,\n                                        avg,\n                                        symbol,\n                                        nb_rb);\n                    avgs = 0;\n\n                    for(aatx = 0; aatx < frame_parms->nb_antenna_ports_eNB; aatx++)\n                        for(aarx = 0; aarx < frame_parms->nb_antennas_rx; aarx++)\n                        {\n                            avgs = cmax(avgs, avg[(aatx << 1) + aarx]);\n                        }\n\n                    pdsch_vars[eNB_id]->log2_maxh = (log2_approx(avgs) / 2) + 1;\n                    pdsch_vars[eNB_id]->log2_maxh++;\n                }\n            }\n        }\n        else if(beamforming_mode == 7)\n            dlsch_channel_level_TM7(pdsch_vars[eNB_id]->dl_bf_ch_estimates_ext,\n                                    frame_parms,\n                                    avg,\n                                    symbol,\n                                    nb_rb);\n\n#ifdef UE_DEBUG_TRACE\n        LOG_D(PHY, \"[DLSCH] AbsSubframe %d.%d log2_maxh = %d [log2_maxh0 %d log2_maxh1 %d] (%d,%d)\\n\",\n              frame % 1024, subframe, pdsch_vars[eNB_id]->log2_maxh,\n              pdsch_vars[eNB_id]->log2_maxh0,\n              pdsch_vars[eNB_id]->log2_maxh1,\n              avg[0], avgs);\n        //LOG_D(PHY,\"[DLSCH] mimo_mode = %d\\n\", dlsch0_harq->mimo_mode);\n#endif\n        //wait until pdcch is decoded\n        //proc->channel_level = 1;\n    }\n\n    /*\n        uint32_t wait = 0;\n        while(proc->channel_level == 0)\n        {\n        usleep(1);\n        wait++;\n        }\n    */\n#if T_TRACER\n\n    if(type == PDSCH)\n    {\n        T(T_UE_PHY_PDSCH_ENERGY, T_INT(eNB_id), T_INT(frame % 1024), T_INT(subframe),\n          T_INT(avg[0]), T_INT(avg[1]),     T_INT(avg[2]),   T_INT(avg[3]));\n    }\n\n#endif\n#if UE_TIMING_TRACE\n    stop_meas(&ue->generic_stat_bis[ue->current_thread_id[subframe]][slot]);\n    LOG_I(PHY, \"[AbsSFN %d.%d] Slot%d Symbol %d first_symbol_flag %d: Channel Level  %5.2f \\n\", frame, subframe, slot, symbol, first_symbol_flag,\n          ue->generic_stat_bis[ue->current_thread_id[subframe]][slot].p_time / (cpuf * 1000.0));\n    start_meas(&ue->generic_stat_bis[ue->current_thread_id[subframe]][slot]);\n#endif\n\n    if(rx_type == rx_IC_dual_stream && mmse_flag == 1)\n    {\n        precode_channel_est(pdsch_vars[eNB_id]->dl_ch_estimates_ext,\n                            frame_parms,\n                            pdsch_vars[eNB_id],\n                            symbol,\n                            nb_rb,\n                            dlsch0_harq->mimo_mode);\n        mmse_processing_oai(pdsch_vars[eNB_id],\n                            frame_parms,\n                            measurements,\n                            first_symbol_flag,\n                            dlsch0_harq->mimo_mode,\n                            mmse_flag,\n                            0.0,\n                            symbol,\n                            nb_rb);\n    }\n\n    // Now channel compensation\n    if(dlsch0_harq->mimo_mode < LARGE_CDD)\n    {\n        dlsch_channel_compensation(pdsch_vars[eNB_id]->rxdataF_ext,\n                                   pdsch_vars[eNB_id]->dl_ch_estimates_ext,\n                                   pdsch_vars[eNB_id]->dl_ch_mag0,\n                                   pdsch_vars[eNB_id]->dl_ch_magb0,\n                                   pdsch_vars[eNB_id]->rxdataF_comp0,\n                                   (aatx > 1) ? pdsch_vars[eNB_id]->rho : NULL,\n                                   frame_parms,\n                                   symbol,\n                                   first_symbol_flag,\n                                   dlsch0_harq->Qm,\n                                   nb_rb,\n                                   pdsch_vars[eNB_id]->log2_maxh,\n                                   measurements); // log2_maxh+I0_shift\n\n        if(symbol == 5)\n        {\n            LOG_M(\"rxF_comp_d.m\", \"rxF_c_d\", &pdsch_vars[eNB_id]->rxdataF_comp0[0][symbol * frame_parms->N_RB_DL * 12], frame_parms->N_RB_DL * 12, 1, 1);\n        }\n\n        if((rx_type == rx_IC_single_stream) &&\n                (eNB_id_i < ue->n_connected_eNB))\n        {\n            dlsch_channel_compensation(pdsch_vars[eNB_id_i]->rxdataF_ext,\n                                       pdsch_vars[eNB_id_i]->dl_ch_estimates_ext,\n                                       pdsch_vars[eNB_id_i]->dl_ch_mag0,\n                                       pdsch_vars[eNB_id_i]->dl_ch_magb0,\n                                       pdsch_vars[eNB_id_i]->rxdataF_comp0,\n                                       (aatx > 1) ? pdsch_vars[eNB_id_i]->rho : NULL,\n                                       frame_parms,\n                                       symbol,\n                                       first_symbol_flag,\n                                       i_mod,\n                                       nb_rb,\n                                       pdsch_vars[eNB_id]->log2_maxh,\n                                       measurements); // log2_maxh+I0_shift\n\n            if(symbol == 5)\n            {\n                LOG_M(\"rxF_comp_d.m\", \"rxF_c_d\", &pdsch_vars[eNB_id]->rxdataF_comp0[0][symbol * frame_parms->N_RB_DL * 12], frame_parms->N_RB_DL * 12, 1, 1);\n                LOG_M(\"rxF_comp_i.m\", \"rxF_c_i\", &pdsch_vars[eNB_id_i]->rxdataF_comp0[0][symbol * frame_parms->N_RB_DL * 12], frame_parms->N_RB_DL * 12, 1, 1);\n            }\n\n            dlsch_dual_stream_correlation(frame_parms,\n                                          symbol,\n                                          nb_rb,\n                                          pdsch_vars[eNB_id]->dl_ch_estimates_ext,\n                                          pdsch_vars[eNB_id_i]->dl_ch_estimates_ext,\n                                          pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round],\n                                          pdsch_vars[eNB_id]->log2_maxh);\n        }\n    }\n    else if((dlsch0_harq->mimo_mode == LARGE_CDD) || ((dlsch0_harq->mimo_mode >= DUALSTREAM_UNIFORM_PRECODING1) &&\n            (dlsch0_harq->mimo_mode <= DUALSTREAM_PUSCH_PRECODING)))\n    {\n        dlsch_channel_compensation_TM34(frame_parms,\n                                        pdsch_vars[eNB_id],\n                                        measurements,\n                                        eNB_id,\n                                        symbol,\n                                        dlsch0_harq->Qm,\n                                        dlsch1_harq->Qm,\n                                        harq_pid,\n                                        dlsch0_harq->round,\n                                        dlsch0_harq->mimo_mode,\n                                        nb_rb,\n                                        mmse_flag,\n                                        pdsch_vars[eNB_id]->log2_maxh0,\n                                        pdsch_vars[eNB_id]->log2_maxh1);\n\n        if(symbol == 5)\n        {\n            LOG_M(\"rxF_comp_d00.m\", \"rxF_c_d00\", &pdsch_vars[eNB_id]->rxdataF_comp0[0][symbol * frame_parms->N_RB_DL * 12], frame_parms->N_RB_DL * 12, 1, 1); // should be QAM\n            LOG_M(\"rxF_comp_d01.m\", \"rxF_c_d01\", &pdsch_vars[eNB_id]->rxdataF_comp0[1][symbol * frame_parms->N_RB_DL * 12], frame_parms->N_RB_DL * 12, 1, 1); //should be almost 0\n            LOG_M(\"rxF_comp_d10.m\", \"rxF_c_d10\", &pdsch_vars[eNB_id]->rxdataF_comp1[harq_pid][round][0][symbol * frame_parms->N_RB_DL * 12], frame_parms->N_RB_DL * 12, 1, 1); //should be almost 0\n            LOG_M(\"rxF_comp_d11.m\", \"rxF_c_d11\", &pdsch_vars[eNB_id]->rxdataF_comp1[harq_pid][round][1][symbol * frame_parms->N_RB_DL * 12], frame_parms->N_RB_DL * 12, 1, 1); //should be QAM\n        }\n\n        // compute correlation between signal and interference channels (rho12 and rho21)\n        dlsch_dual_stream_correlation(frame_parms, // this is doing h11'*h12 and h21'*h22\n                                      symbol,\n                                      nb_rb,\n                                      pdsch_vars[eNB_id]->dl_ch_estimates_ext,\n                                      &(pdsch_vars[eNB_id]->dl_ch_estimates_ext[2]),\n                                      pdsch_vars[eNB_id]->dl_ch_rho2_ext,\n                                      pdsch_vars[eNB_id]->log2_maxh0);\n        //printf(\"rho stream1 =%d\\n\", &pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round] );\n        //to be optimized (just take complex conjugate)\n        dlsch_dual_stream_correlation(frame_parms, // this is doing h12'*h11 and h22'*h21\n                                      symbol,\n                                      nb_rb,\n                                      &(pdsch_vars[eNB_id]->dl_ch_estimates_ext[2]),\n                                      pdsch_vars[eNB_id]->dl_ch_estimates_ext,\n                                      pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round],\n                                      pdsch_vars[eNB_id]->log2_maxh1);\n\n        //  printf(\"rho stream2 =%d\\n\",&pdsch_vars[eNB_id]->dl_ch_rho2_ext );\n        //printf(\"TM3 log2_maxh : %d\\n\",pdsch_vars[eNB_id]->log2_maxh);\n        if(symbol == 5)\n        {\n            LOG_M(\"rho0_0.m\", \"rho0_0\", &pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round][0][symbol * frame_parms->N_RB_DL * 12], frame_parms->N_RB_DL * 12, 1, 1); // should be QAM\n            LOG_M(\"rho2_0.m\", \"rho2_0\", &pdsch_vars[eNB_id]->dl_ch_rho2_ext[0][symbol * frame_parms->N_RB_DL * 12], frame_parms->N_RB_DL * 12, 1, 1); //should be almost 0\n            LOG_M(\"rho0_1.m.m\", \"rho0_1\", &pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round][1][symbol * frame_parms->N_RB_DL * 12], frame_parms->N_RB_DL * 12, 1, 1); //should be almost 0\n            LOG_M(\"rho2_1.m\", \"rho2_1\", &pdsch_vars[eNB_id]->dl_ch_rho2_ext[1][symbol * frame_parms->N_RB_DL * 12], frame_parms->N_RB_DL * 12, 1, 1); //should be QAM\n        }\n    }\n    else if(dlsch0_harq->mimo_mode < DUALSTREAM_UNIFORM_PRECODING1)   // single-layer precoding (TM5, TM6)\n    {\n        if((rx_type == rx_IC_single_stream) && (eNB_id_i == ue->n_connected_eNB) && (dlsch0_harq->dl_power_off == 0))\n        {\n            dlsch_channel_compensation_TM56(pdsch_vars[eNB_id]->rxdataF_ext,\n                                            pdsch_vars[eNB_id]->dl_ch_estimates_ext,\n                                            pdsch_vars[eNB_id]->dl_ch_mag0,\n                                            pdsch_vars[eNB_id]->dl_ch_magb0,\n                                            pdsch_vars[eNB_id]->rxdataF_comp0,\n                                            pdsch_vars[eNB_id]->pmi_ext,\n                                            frame_parms,\n                                            measurements,\n                                            eNB_id,\n                                            symbol,\n                                            dlsch0_harq->Qm,\n                                            nb_rb,\n                                            pdsch_vars[eNB_id]->log2_maxh,\n                                            dlsch0_harq->dl_power_off);\n\n            for(rb = 0; rb < nb_rb; rb++)\n            {\n                switch(pdsch_vars[eNB_id]->pmi_ext[rb])\n                {\n                    case 0:\n                        pdsch_vars[eNB_id_i]->pmi_ext[rb] = 1;\n                        break;\n\n                    case 1:\n                        pdsch_vars[eNB_id_i]->pmi_ext[rb] = 0;\n                        break;\n\n                    case 2:\n                        pdsch_vars[eNB_id_i]->pmi_ext[rb] = 3;\n                        break;\n\n                    case 3:\n                        pdsch_vars[eNB_id_i]->pmi_ext[rb] = 2;\n                        break;\n                }\n\n                //  if (rb==0)\n                //    printf(\"pmi %d, pmi_i %d\\n\",pdsch_vars[eNB_id]->pmi_ext[rb],pdsch_vars[eNB_id_i]->pmi_ext[rb]);\n            }\n\n            dlsch_channel_compensation_TM56(pdsch_vars[eNB_id_i]->rxdataF_ext,\n                                            pdsch_vars[eNB_id_i]->dl_ch_estimates_ext,\n                                            pdsch_vars[eNB_id_i]->dl_ch_mag0,\n                                            pdsch_vars[eNB_id_i]->dl_ch_magb0,\n                                            pdsch_vars[eNB_id_i]->rxdataF_comp0,\n                                            pdsch_vars[eNB_id_i]->pmi_ext,\n                                            frame_parms,\n                                            measurements,\n                                            eNB_id_i,\n                                            symbol,\n                                            i_mod,\n                                            nb_rb,\n                                            pdsch_vars[eNB_id]->log2_maxh,\n                                            dlsch0_harq->dl_power_off);\n\n            if(symbol == 5)\n            {\n                LOG_M(\"rxF_comp_d.m\", \"rxF_c_d\", &pdsch_vars[eNB_id]->rxdataF_comp0[0][symbol * frame_parms->N_RB_DL * 12], frame_parms->N_RB_DL * 12, 1, 1);\n                LOG_M(\"rxF_comp_i.m\", \"rxF_c_i\", &pdsch_vars[eNB_id_i]->rxdataF_comp0[0][symbol * frame_parms->N_RB_DL * 12], frame_parms->N_RB_DL * 12, 1, 1);\n            }\n\n            dlsch_dual_stream_correlation(frame_parms,\n                                          symbol,\n                                          nb_rb,\n                                          pdsch_vars[eNB_id]->dl_ch_estimates_ext,\n                                          pdsch_vars[eNB_id_i]->dl_ch_estimates_ext,\n                                          pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round],\n                                          pdsch_vars[eNB_id]->log2_maxh);\n        }\n        else if(dlsch0_harq->dl_power_off == 1)\n        {\n            dlsch_channel_compensation_TM56(pdsch_vars[eNB_id]->rxdataF_ext,\n                                            pdsch_vars[eNB_id]->dl_ch_estimates_ext,\n                                            pdsch_vars[eNB_id]->dl_ch_mag0,\n                                            pdsch_vars[eNB_id]->dl_ch_magb0,\n                                            pdsch_vars[eNB_id]->rxdataF_comp0,\n                                            pdsch_vars[eNB_id]->pmi_ext,\n                                            frame_parms,\n                                            measurements,\n                                            eNB_id,\n                                            symbol,\n                                            dlsch0_harq->Qm,\n                                            nb_rb,\n                                            pdsch_vars[eNB_id]->log2_maxh,\n                                            1);\n        }\n    }\n    else if(dlsch0_harq->mimo_mode == TM7)    //TM7\n    {\n        dlsch_channel_compensation(pdsch_vars[eNB_id]->rxdataF_ext,\n                                   pdsch_vars[eNB_id]->dl_bf_ch_estimates_ext,\n                                   pdsch_vars[eNB_id]->dl_ch_mag0,\n                                   pdsch_vars[eNB_id]->dl_ch_magb0,\n                                   pdsch_vars[eNB_id]->rxdataF_comp0,\n                                   (aatx > 1) ? pdsch_vars[eNB_id]->rho : NULL,\n                                   frame_parms,\n                                   symbol,\n                                   first_symbol_flag,\n                                   get_Qm(dlsch0_harq->mcs),\n                                   nb_rb,\n                                   //9,\n                                   pdsch_vars[eNB_id]->log2_maxh,\n                                   measurements); // log2_maxh+I0_shift\n    }\n\n#if UE_TIMING_TRACE\n    stop_meas(&ue->generic_stat_bis[ue->current_thread_id[subframe]][slot]);\n    LOG_I(PHY, \"[AbsSFN %d.%d] Slot%d Symbol %d log2_maxh %d Channel Comp  %5.2f \\n\", frame, subframe, slot, symbol, pdsch_vars[eNB_id]->log2_maxh,\n          ue->generic_stat_bis[ue->current_thread_id[subframe]][slot].p_time / (cpuf * 1000.0));\n    start_meas(&ue->generic_stat_bis[ue->current_thread_id[subframe]][slot]);\n#endif\n\n    if(frame_parms->nb_antennas_rx > 1)\n    {\n        if((dlsch0_harq->mimo_mode == LARGE_CDD) ||\n                ((dlsch0_harq->mimo_mode >= DUALSTREAM_UNIFORM_PRECODING1) &&\n                 (dlsch0_harq->mimo_mode <= DUALSTREAM_PUSCH_PRECODING)))  // TM3 or TM4\n        {\n            if(frame_parms->nb_antenna_ports_eNB == 2)\n            {\n                dlsch_detection_mrc_TM34(frame_parms,\n                                         pdsch_vars[eNB_id],\n                                         harq_pid,\n                                         dlsch0_harq->round,\n                                         symbol,\n                                         nb_rb,\n                                         1);\n\n                if(symbol == 5)\n                {\n                    LOG_M(\"rho0_mrc.m\", \"rho0_0\", &pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round][0][symbol * frame_parms->N_RB_DL * 12], frame_parms->N_RB_DL * 12, 1, 1); // should be QAM\n                    LOG_M(\"rho2_mrc.m\", \"rho2_0\", &pdsch_vars[eNB_id]->dl_ch_rho2_ext[0][symbol * frame_parms->N_RB_DL * 12], frame_parms->N_RB_DL * 12, 1, 1); //should be almost 0\n                }\n            }\n        }\n        else\n        {\n            dlsch_detection_mrc(frame_parms,\n                                pdsch_vars[eNB_id]->rxdataF_comp0,\n                                pdsch_vars[eNB_id_i]->rxdataF_comp0,\n                                pdsch_vars[eNB_id]->rho,\n                                pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round],\n                                pdsch_vars[eNB_id]->dl_ch_mag0,\n                                pdsch_vars[eNB_id]->dl_ch_magb0,\n                                pdsch_vars[eNB_id_i]->dl_ch_mag0,\n                                pdsch_vars[eNB_id_i]->dl_ch_magb0,\n                                symbol,\n                                nb_rb,\n                                rx_type == rx_IC_single_stream);\n        }\n    }\n\n    //  printf(\"Combining\");\n    if((dlsch0_harq->mimo_mode == SISO) ||\n            ((dlsch0_harq->mimo_mode >= UNIFORM_PRECODING11) &&\n             (dlsch0_harq->mimo_mode <= PUSCH_PRECODING0)) ||\n            (dlsch0_harq->mimo_mode == TM7))\n    {\n        /*\n            dlsch_siso(frame_parms,\n            pdsch_vars[eNB_id]->rxdataF_comp,\n            pdsch_vars[eNB_id_i]->rxdataF_comp,\n            symbol,\n            nb_rb);\n        */\n    }\n    else if(dlsch0_harq->mimo_mode == ALAMOUTI)\n    {\n        dlsch_alamouti(frame_parms,\n                       pdsch_vars[eNB_id]->rxdataF_comp0,\n                       pdsch_vars[eNB_id]->dl_ch_mag0,\n                       pdsch_vars[eNB_id]->dl_ch_magb0,\n                       symbol,\n                       nb_rb);\n    }\n\n    //    printf(\"LLR\");\n    if((dlsch0_harq->mimo_mode == LARGE_CDD) ||\n            ((dlsch0_harq->mimo_mode >= DUALSTREAM_UNIFORM_PRECODING1) &&\n             (dlsch0_harq->mimo_mode <= DUALSTREAM_PUSCH_PRECODING)))\n    {\n        rxdataF_comp_ptr = pdsch_vars[eNB_id]->rxdataF_comp1[harq_pid][round];\n        dl_ch_mag_ptr = pdsch_vars[eNB_id]->dl_ch_mag1[harq_pid][round];\n    }\n    else\n    {\n        rxdataF_comp_ptr = pdsch_vars[eNB_id_i]->rxdataF_comp0;\n        dl_ch_mag_ptr = pdsch_vars[eNB_id_i]->dl_ch_mag0;\n        //i_mod should have been passed as a parameter\n    }\n\n#if UE_TIMING_TRACE\n    stop_meas(&ue->generic_stat_bis[ue->current_thread_id[subframe]][slot]);\n    LOG_I(PHY, \"[AbsSFN %d.%d] Slot%d Symbol %d: Channel Combine  %5.2f \\n\", frame, subframe, slot, symbol, ue->generic_stat_bis[ue->current_thread_id[subframe]][slot].p_time / (cpuf * 1000.0));\n    start_meas(&ue->generic_stat_bis[ue->current_thread_id[subframe]][slot]);\n#endif\n    //printf(\"LLR dlsch0_harq->Qm %d rx_type %d cw0 %d cw1 %d symbol %d \\n\",dlsch0_harq->Qm,rx_type,codeword_TB0,codeword_TB1,symbol);\n    // compute LLRs\n    // -> // compute @pointer where llrs should filled for this ofdm-symbol\n    int8_t  *pllr_symbol_cw0;\n    int8_t  *pllr_symbol_cw1;\n    uint32_t llr_offset_symbol;\n    llr_offset_symbol = pdsch_vars[eNB_id]->llr_offset[symbol];\n    pllr_symbol_cw0  = (int8_t *)pdsch_vars[eNB_id]->llr[0];\n    pllr_symbol_cw1  = (int8_t *)pdsch_vars[eNB_id]->llr[1];\n    pllr_symbol_cw0 += llr_offset_symbol;\n    pllr_symbol_cw1 += llr_offset_symbol;\n\n    /*\n        LOG_I(PHY,\"compute LLRs [AbsSubframe %d.%d-%d] NbRB %d Qm %d LLRs-Length %d LLR-Offset %d @LLR Buff %p @LLR Buff(symb) %p\\n\",\n               frame, subframe,symbol,\n               nb_rb,dlsch0_harq->Qm,\n               pdsch_vars[eNB_id]->llr_length[symbol],\n               pdsch_vars[eNB_id]->llr_offset[symbol],\n               (int16_t*)pdsch_vars[eNB_id]->llr[0],\n               pllr_symbol_cw0);\n    */\n    switch(dlsch0_harq->Qm)\n    {\n        case 2 :\n            if((rx_type == rx_standard) || (codeword_TB1 == -1))\n            {\n                dlsch_qpsk_llr(frame_parms,\n                               pdsch_vars[eNB_id]->rxdataF_comp0,\n                               (int16_t *)pllr_symbol_cw0,\n                               symbol,\n                               first_symbol_flag,\n                               nb_rb,\n                               adjust_G2(frame_parms, dlsch0_harq->rb_alloc_even, 2, subframe, symbol),\n                               beamforming_mode);\n            }\n            else if(codeword_TB0 == -1)\n            {\n                dlsch_qpsk_llr(frame_parms,\n                               pdsch_vars[eNB_id]->rxdataF_comp0,\n                               (int16_t *)pllr_symbol_cw1,\n                               symbol,\n                               first_symbol_flag,\n                               nb_rb,\n                               adjust_G2(frame_parms, dlsch0_harq->rb_alloc_even, 2, subframe, symbol),\n                               beamforming_mode);\n            }\n            else if(rx_type >= rx_IC_single_stream)\n            {\n                if(dlsch1_harq->Qm == 2)\n                {\n                    dlsch_qpsk_qpsk_llr(frame_parms,\n                                        pdsch_vars[eNB_id]->rxdataF_comp0,\n                                        rxdataF_comp_ptr,\n                                        pdsch_vars[eNB_id]->dl_ch_rho2_ext,\n                                        pdsch_vars[eNB_id]->llr[0],\n                                        symbol, first_symbol_flag, nb_rb,\n                                        adjust_G2(frame_parms, dlsch0_harq->rb_alloc_even, 2, subframe, symbol),\n                                        pdsch_vars[eNB_id]->llr128);\n\n                    if(rx_type == rx_IC_dual_stream)\n                    {\n                        dlsch_qpsk_qpsk_llr(frame_parms,\n                                            rxdataF_comp_ptr,\n                                            pdsch_vars[eNB_id]->rxdataF_comp0,\n                                            pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round],\n                                            pdsch_vars[eNB_id]->llr[1],\n                                            symbol, first_symbol_flag, nb_rb,\n                                            adjust_G2(frame_parms, dlsch1_harq->rb_alloc_even, 2, subframe, symbol),\n                                            pdsch_vars[eNB_id]->llr128_2ndstream);\n                    }\n                }\n                else if(dlsch1_harq->Qm == 4)\n                {\n                    dlsch_qpsk_16qam_llr(frame_parms,\n                                         pdsch_vars[eNB_id]->rxdataF_comp0,\n                                         rxdataF_comp_ptr,//i\n                                         dl_ch_mag_ptr,//i\n                                         pdsch_vars[eNB_id]->dl_ch_rho2_ext,\n                                         pdsch_vars[eNB_id]->llr[0],\n                                         symbol, first_symbol_flag, nb_rb,\n                                         adjust_G2(frame_parms, dlsch0_harq->rb_alloc_even, 2, subframe, symbol),\n                                         pdsch_vars[eNB_id]->llr128);\n\n                    if(rx_type == rx_IC_dual_stream)\n                    {\n                        dlsch_16qam_qpsk_llr(frame_parms,\n                                             rxdataF_comp_ptr,\n                                             pdsch_vars[eNB_id]->rxdataF_comp0,//i\n                                             dl_ch_mag_ptr,\n                                             pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round],\n                                             pdsch_vars[eNB_id]->llr[1],\n                                             symbol, first_symbol_flag, nb_rb,\n                                             adjust_G2(frame_parms, dlsch1_harq->rb_alloc_even, 4, subframe, symbol),\n                                             pdsch_vars[eNB_id]->llr128_2ndstream);\n                    }\n                }\n                else\n                {\n                    dlsch_qpsk_64qam_llr(frame_parms,\n                                         pdsch_vars[eNB_id]->rxdataF_comp0,\n                                         rxdataF_comp_ptr,//i\n                                         dl_ch_mag_ptr,//i\n                                         pdsch_vars[eNB_id]->dl_ch_rho2_ext,\n                                         pdsch_vars[eNB_id]->llr[0],\n                                         symbol, first_symbol_flag, nb_rb,\n                                         adjust_G2(frame_parms, dlsch0_harq->rb_alloc_even, 2, subframe, symbol),\n                                         pdsch_vars[eNB_id]->llr128);\n\n                    if(rx_type == rx_IC_dual_stream)\n                    {\n                        dlsch_64qam_qpsk_llr(frame_parms,\n                                             rxdataF_comp_ptr,\n                                             pdsch_vars[eNB_id]->rxdataF_comp0,//i\n                                             dl_ch_mag_ptr,\n                                             pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round],\n                                             pdsch_vars[eNB_id]->llr[1],\n                                             symbol, first_symbol_flag, nb_rb,\n                                             adjust_G2(frame_parms, dlsch1_harq->rb_alloc_even, 6, subframe, symbol),\n                                             pdsch_vars[eNB_id]->llr128_2ndstream);\n                    }\n                }\n            }\n\n            break;\n\n        case 4 :\n            if((rx_type == rx_standard) || (codeword_TB1 == -1))\n            {\n                dlsch_16qam_llr(frame_parms,\n                                pdsch_vars[eNB_id]->rxdataF_comp0,\n                                pdsch_vars[eNB_id]->llr[0],\n                                pdsch_vars[eNB_id]->dl_ch_mag0,\n                                symbol, first_symbol_flag, nb_rb,\n                                adjust_G2(frame_parms, dlsch0_harq->rb_alloc_even, 4, subframe, symbol),\n                                pdsch_vars[eNB_id]->llr128,\n                                beamforming_mode);\n            }\n            else if(codeword_TB0 == -1)\n            {\n                dlsch_16qam_llr(frame_parms,\n                                pdsch_vars[eNB_id]->rxdataF_comp0,\n                                pdsch_vars[eNB_id]->llr[1],\n                                pdsch_vars[eNB_id]->dl_ch_mag0,\n                                symbol, first_symbol_flag, nb_rb,\n                                adjust_G2(frame_parms, dlsch0_harq->rb_alloc_even, 4, subframe, symbol),\n                                pdsch_vars[eNB_id]->llr128_2ndstream,\n                                beamforming_mode);\n            }\n            else if(rx_type >= rx_IC_single_stream)\n            {\n                if(dlsch1_harq->Qm == 2)\n                {\n                    dlsch_16qam_qpsk_llr(frame_parms,\n                                         pdsch_vars[eNB_id]->rxdataF_comp0,\n                                         rxdataF_comp_ptr,//i\n                                         pdsch_vars[eNB_id]->dl_ch_mag0,\n                                         pdsch_vars[eNB_id]->dl_ch_rho2_ext,\n                                         pdsch_vars[eNB_id]->llr[0],\n                                         symbol, first_symbol_flag, nb_rb,\n                                         adjust_G2(frame_parms, dlsch0_harq->rb_alloc_even, 4, subframe, symbol),\n                                         pdsch_vars[eNB_id]->llr128);\n\n                    if(rx_type == rx_IC_dual_stream)\n                    {\n                        dlsch_qpsk_16qam_llr(frame_parms,\n                                             rxdataF_comp_ptr,\n                                             pdsch_vars[eNB_id]->rxdataF_comp0,//i\n                                             pdsch_vars[eNB_id]->dl_ch_mag0,//i\n                                             pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round],\n                                             pdsch_vars[eNB_id]->llr[1],\n                                             symbol, first_symbol_flag, nb_rb,\n                                             adjust_G2(frame_parms, dlsch1_harq->rb_alloc_even, 2, subframe, symbol),\n                                             pdsch_vars[eNB_id]->llr128_2ndstream);\n                    }\n                }\n                else if(dlsch1_harq->Qm == 4)\n                {\n                    dlsch_16qam_16qam_llr(frame_parms,\n                                          pdsch_vars[eNB_id]->rxdataF_comp0,\n                                          rxdataF_comp_ptr,//i\n                                          pdsch_vars[eNB_id]->dl_ch_mag0,\n                                          dl_ch_mag_ptr,//i\n                                          pdsch_vars[eNB_id]->dl_ch_rho2_ext,\n                                          pdsch_vars[eNB_id]->llr[0],\n                                          symbol, first_symbol_flag, nb_rb,\n                                          adjust_G2(frame_parms, dlsch0_harq->rb_alloc_even, 4, subframe, symbol),\n                                          pdsch_vars[eNB_id]->llr128);\n\n                    if(rx_type == rx_IC_dual_stream)\n                    {\n                        dlsch_16qam_16qam_llr(frame_parms,\n                                              rxdataF_comp_ptr,\n                                              pdsch_vars[eNB_id]->rxdataF_comp0,//i\n                                              dl_ch_mag_ptr,\n                                              pdsch_vars[eNB_id]->dl_ch_mag0,//i\n                                              pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round],\n                                              pdsch_vars[eNB_id]->llr[1],\n                                              symbol, first_symbol_flag, nb_rb,\n                                              adjust_G2(frame_parms, dlsch1_harq->rb_alloc_even, 4, subframe, symbol),\n                                              pdsch_vars[eNB_id]->llr128_2ndstream);\n                    }\n                }\n                else\n                {\n                    dlsch_16qam_64qam_llr(frame_parms,\n                                          pdsch_vars[eNB_id]->rxdataF_comp0,\n                                          rxdataF_comp_ptr,//i\n                                          pdsch_vars[eNB_id]->dl_ch_mag0,\n                                          dl_ch_mag_ptr,//i\n                                          pdsch_vars[eNB_id]->dl_ch_rho2_ext,\n                                          pdsch_vars[eNB_id]->llr[0],\n                                          symbol, first_symbol_flag, nb_rb,\n                                          adjust_G2(frame_parms, dlsch0_harq->rb_alloc_even, 4, subframe, symbol),\n                                          pdsch_vars[eNB_id]->llr128);\n\n                    if(rx_type == rx_IC_dual_stream)\n                    {\n                        dlsch_64qam_16qam_llr(frame_parms,\n                                              rxdataF_comp_ptr,\n                                              pdsch_vars[eNB_id]->rxdataF_comp0,\n                                              dl_ch_mag_ptr,\n                                              pdsch_vars[eNB_id]->dl_ch_mag0,\n                                              pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round],\n                                              pdsch_vars[eNB_id]->llr[1],\n                                              symbol, first_symbol_flag, nb_rb,\n                                              adjust_G2(frame_parms, dlsch1_harq->rb_alloc_even, 6, subframe, symbol),\n                                              pdsch_vars[eNB_id]->llr128_2ndstream);\n                    }\n                }\n            }\n\n            break;\n\n        case 6 :\n            if((rx_type == rx_standard) || (codeword_TB1 == -1))\n            {\n                dlsch_64qam_llr(frame_parms,\n                                pdsch_vars[eNB_id]->rxdataF_comp0,\n                                (int16_t *)pllr_symbol_cw0,\n                                pdsch_vars[eNB_id]->dl_ch_mag0,\n                                pdsch_vars[eNB_id]->dl_ch_magb0,\n                                symbol, first_symbol_flag, nb_rb,\n                                adjust_G2(frame_parms, dlsch0_harq->rb_alloc_even, 6, subframe, symbol),\n                                pdsch_vars[eNB_id]->llr_offset[symbol],\n                                beamforming_mode);\n            }\n            else if(codeword_TB0 == -1)\n            {\n                dlsch_64qam_llr(frame_parms,\n                                pdsch_vars[eNB_id]->rxdataF_comp0,\n                                (int16_t *)pllr_symbol_cw1,\n                                pdsch_vars[eNB_id]->dl_ch_mag0,\n                                pdsch_vars[eNB_id]->dl_ch_magb0,\n                                symbol, first_symbol_flag, nb_rb,\n                                adjust_G2(frame_parms, dlsch0_harq->rb_alloc_even, 6, subframe, symbol),\n                                pdsch_vars[eNB_id]->llr_offset[symbol],\n                                beamforming_mode);\n            }\n            else if(rx_type >= rx_IC_single_stream)\n            {\n                if(dlsch1_harq->Qm == 2)\n                {\n                    dlsch_64qam_qpsk_llr(frame_parms,\n                                         pdsch_vars[eNB_id]->rxdataF_comp0,\n                                         rxdataF_comp_ptr,//i\n                                         pdsch_vars[eNB_id]->dl_ch_mag0,\n                                         pdsch_vars[eNB_id]->dl_ch_rho2_ext,\n                                         pdsch_vars[eNB_id]->llr[0],\n                                         symbol, first_symbol_flag, nb_rb,\n                                         adjust_G2(frame_parms, dlsch0_harq->rb_alloc_even, 6, subframe, symbol),\n                                         pdsch_vars[eNB_id]->llr128);\n\n                    if(rx_type == rx_IC_dual_stream)\n                    {\n                        dlsch_qpsk_64qam_llr(frame_parms,\n                                             rxdataF_comp_ptr,\n                                             pdsch_vars[eNB_id]->rxdataF_comp0,//i\n                                             pdsch_vars[eNB_id]->dl_ch_mag0,\n                                             pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round],\n                                             pdsch_vars[eNB_id]->llr[1],\n                                             symbol, first_symbol_flag, nb_rb,\n                                             adjust_G2(frame_parms, dlsch1_harq->rb_alloc_even, 2, subframe, symbol),\n                                             pdsch_vars[eNB_id]->llr128_2ndstream);\n                    }\n                }\n                else if(dlsch1_harq->Qm == 4)\n                {\n                    dlsch_64qam_16qam_llr(frame_parms,\n                                          pdsch_vars[eNB_id]->rxdataF_comp0,\n                                          rxdataF_comp_ptr,//i\n                                          pdsch_vars[eNB_id]->dl_ch_mag0,\n                                          dl_ch_mag_ptr,//i\n                                          pdsch_vars[eNB_id]->dl_ch_rho2_ext,\n                                          pdsch_vars[eNB_id]->llr[0],\n                                          symbol, first_symbol_flag, nb_rb,\n                                          adjust_G2(frame_parms, dlsch0_harq->rb_alloc_even, 6, subframe, symbol),\n                                          pdsch_vars[eNB_id]->llr128);\n\n                    if(rx_type == rx_IC_dual_stream)\n                    {\n                        dlsch_16qam_64qam_llr(frame_parms,\n                                              rxdataF_comp_ptr,\n                                              pdsch_vars[eNB_id]->rxdataF_comp0,//i\n                                              dl_ch_mag_ptr,\n                                              pdsch_vars[eNB_id]->dl_ch_mag0,//i\n                                              pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round],\n                                              pdsch_vars[eNB_id]->llr[1],\n                                              symbol, first_symbol_flag, nb_rb,\n                                              adjust_G2(frame_parms, dlsch1_harq->rb_alloc_even, 4, subframe, symbol),\n                                              pdsch_vars[eNB_id]->llr128_2ndstream);\n                    }\n                }\n                else\n                {\n                    dlsch_64qam_64qam_llr(frame_parms,\n                                          pdsch_vars[eNB_id]->rxdataF_comp0,\n                                          rxdataF_comp_ptr,//i\n                                          pdsch_vars[eNB_id]->dl_ch_mag0,\n                                          dl_ch_mag_ptr,//i\n                                          pdsch_vars[eNB_id]->dl_ch_rho2_ext,\n                                          (int16_t *)pllr_symbol_cw0,\n                                          symbol, first_symbol_flag, nb_rb,\n                                          adjust_G2(frame_parms, dlsch0_harq->rb_alloc_even, 6, subframe, symbol),\n                                          pdsch_vars[eNB_id]->llr_offset[symbol]);\n\n                    if(rx_type == rx_IC_dual_stream)\n                    {\n                        dlsch_64qam_64qam_llr(frame_parms,\n                                              rxdataF_comp_ptr,\n                                              pdsch_vars[eNB_id]->rxdataF_comp0,//i\n                                              dl_ch_mag_ptr,\n                                              pdsch_vars[eNB_id]->dl_ch_mag0,//i\n                                              pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round],\n                                              (int16_t *)pllr_symbol_cw1,\n                                              symbol, first_symbol_flag, nb_rb,\n                                              adjust_G2(frame_parms, dlsch1_harq->rb_alloc_even, 6, subframe, symbol),\n                                              pdsch_vars[eNB_id]->llr_offset[symbol]);\n                    }\n                }\n            }\n\n            break;\n\n        default:\n            LOG_W(PHY, \"rx_dlsch.c : Unknown mod_order!!!!\\n\");\n            return(-1);\n            break;\n    }\n\n    if(dlsch1_harq)\n    {\n        switch(get_Qm(dlsch1_harq->mcs))\n        {\n            case 2 :\n                if(rx_type == rx_standard)\n                {\n                    dlsch_qpsk_llr(frame_parms,\n                                   pdsch_vars[eNB_id]->rxdataF_comp0,\n                                   (int16_t *)pllr_symbol_cw0,\n                                   symbol, first_symbol_flag, nb_rb,\n                                   adjust_G2(frame_parms, dlsch0_harq->rb_alloc_even, 2, subframe, symbol),\n                                   beamforming_mode);\n                }\n\n                break;\n\n            case 4:\n                if(rx_type == rx_standard)\n                {\n                    dlsch_16qam_llr(frame_parms,\n                                    pdsch_vars[eNB_id]->rxdataF_comp0,\n                                    pdsch_vars[eNB_id]->llr[0],\n                                    pdsch_vars[eNB_id]->dl_ch_mag0,\n                                    symbol, first_symbol_flag, nb_rb,\n                                    adjust_G2(frame_parms, dlsch0_harq->rb_alloc_even, 4, subframe, symbol),\n                                    pdsch_vars[eNB_id]->llr128,\n                                    beamforming_mode);\n                }\n\n                break;\n\n            case 6 :\n                if(rx_type == rx_standard)\n                {\n                    dlsch_64qam_llr(frame_parms,\n                                    pdsch_vars[eNB_id]->rxdataF_comp0,\n                                    (int16_t *)pllr_symbol_cw0,\n                                    pdsch_vars[eNB_id]->dl_ch_mag0,\n                                    pdsch_vars[eNB_id]->dl_ch_magb0,\n                                    symbol, first_symbol_flag, nb_rb,\n                                    adjust_G2(frame_parms, dlsch0_harq->rb_alloc_even, 6, subframe, symbol),\n                                    pdsch_vars[eNB_id]->llr_offset[symbol],\n                                    beamforming_mode);\n                }\n\n                break;\n\n            default:\n                LOG_W(PHY, \"rx_dlsch.c : Unknown mod_order!!!!\\n\");\n                return(-1);\n                break;\n        }\n    }\n\n#if UE_TIMING_TRACE\n    stop_meas(&ue->generic_stat_bis[ue->current_thread_id[subframe]][slot]);\n    LOG_D(PHY, \"[AbsSFN %d.%d] Slot%d Symbol %d: LLR Computation  %5.2f \\n\", frame, subframe, slot, symbol, ue->generic_stat_bis[ue->current_thread_id[subframe]][slot].p_time / (cpuf * 1000.0));\n#endif\n    // Please keep it: useful for debugging\n    T(T_UE_PHY_PDSCH_IQ, T_INT(eNB_id), T_INT(frame % 1024),\n      T_INT(subframe), T_INT(nb_rb),\n      T_INT(frame_parms->N_RB_UL), T_INT(frame_parms->symbols_per_tti),\n      T_BUFFER(&pdsch_vars[eNB_id]->rxdataF_comp0[eNB_id][0],\n               2 * /* ulsch[UE_id]->harq_processes[harq_pid]->nb_rb */ frame_parms->N_RB_UL * 12 * frame_parms->symbols_per_tti * 2));\n    return 0;\n}\n\n//==============================================================================================\n// Pre-processing for LLR computation\n//==============================================================================================\n\nvoid dlsch_channel_compensation(int **rxdataF_ext,\n                                int **dl_ch_estimates_ext,\n                                int **dl_ch_mag,\n                                int **dl_ch_magb,\n                                int **rxdataF_comp,\n                                int **rho,\n                                LTE_DL_FRAME_PARMS *frame_parms,\n                                unsigned char symbol,\n                                uint8_t first_symbol_flag,\n                                unsigned char mod_order,\n                                unsigned short nb_rb,\n                                unsigned char output_shift,\n                                PHY_MEASUREMENTS *measurements)\n{\n#if defined(__i386) || defined(__x86_64)\n    unsigned short rb;\n    unsigned char aatx, aarx, symbol_mod, pilots = 0;\n    __m128i *dl_ch128, *dl_ch128_2, *dl_ch_mag128, *dl_ch_mag128b, *rxdataF128, *rxdataF_comp128, *rho128;\n    __m128i mmtmpD0, mmtmpD1, mmtmpD2, mmtmpD3, QAM_amp128;\n    symbol_mod = (symbol >= (7 - frame_parms->Ncp)) ? symbol - (7 - frame_parms->Ncp) : symbol;\n\n    if((symbol_mod == 0) || (symbol_mod == (4 - frame_parms->Ncp)))\n    {\n        if(frame_parms->nb_antenna_ports_eNB == 1) // 10 out of 12 so don't reduce size\n        {\n            nb_rb = 1 + (5 * nb_rb / 6);\n        }\n        else\n        {\n            pilots = 1;\n        }\n    }\n\n    for(aatx = 0; aatx < frame_parms->nb_antenna_ports_eNB; aatx++)\n    {\n        __m128i QAM_amp128b = _mm_setzero_si128();\n\n        if(mod_order == 4)\n        {\n            QAM_amp128 = _mm_set1_epi16(QAM16_n1);  // 2/sqrt(10)\n        }\n        else if(mod_order == 6)\n        {\n            QAM_amp128  = _mm_set1_epi16(QAM64_n1); //\n            QAM_amp128b = _mm_set1_epi16(QAM64_n2);\n        }\n\n        for(aarx = 0; aarx < frame_parms->nb_antennas_rx; aarx++)\n        {\n            /*  TODO: hack to be removed. There is crash for 1 antenna case, so\n                for 1 antenna case, I put back the value 2 as it was before\n                Elena's commit.\n            */\n            int x = frame_parms->nb_antennas_rx > 1 ? frame_parms->nb_antennas_rx : 2;\n            dl_ch128          = (__m128i *)&dl_ch_estimates_ext[aatx * x + aarx][symbol * frame_parms->N_RB_DL * 12];\n            //print_shorts(\"dl_ch128[0]=\",&dl_ch128[0]);*/\n            dl_ch_mag128      = (__m128i *)&dl_ch_mag[aatx * x + aarx][symbol * frame_parms->N_RB_DL * 12];\n            dl_ch_mag128b     = (__m128i *)&dl_ch_magb[aatx * x + aarx][symbol * frame_parms->N_RB_DL * 12];\n            rxdataF128        = (__m128i *)&rxdataF_ext[aarx][symbol * frame_parms->N_RB_DL * 12];\n            rxdataF_comp128   = (__m128i *)&rxdataF_comp[aatx * x + aarx][symbol * frame_parms->N_RB_DL * 12];\n\n            for(rb = 0; rb < nb_rb; rb++)\n            {\n                if(mod_order > 2)\n                {\n                    // get channel amplitude if not QPSK\n                    mmtmpD0 = _mm_madd_epi16(dl_ch128[0], dl_ch128[0]);\n                    mmtmpD0 = _mm_srai_epi32(mmtmpD0, output_shift);\n                    mmtmpD1 = _mm_madd_epi16(dl_ch128[1], dl_ch128[1]);\n                    mmtmpD1 = _mm_srai_epi32(mmtmpD1, output_shift);\n                    mmtmpD0 = _mm_packs_epi32(mmtmpD0, mmtmpD1);\n                    // store channel magnitude here in a new field of dlsch\n                    dl_ch_mag128[0] = _mm_unpacklo_epi16(mmtmpD0, mmtmpD0);\n                    dl_ch_mag128b[0] = dl_ch_mag128[0];\n                    dl_ch_mag128[0] = _mm_mulhi_epi16(dl_ch_mag128[0], QAM_amp128);\n                    dl_ch_mag128[0] = _mm_slli_epi16(dl_ch_mag128[0], 1);\n                    //print_ints(\"Re(ch):\",(int16_t*)&mmtmpD0);\n                    //print_shorts(\"QAM_amp:\",(int16_t*)&QAM_amp128);\n                    //print_shorts(\"mag:\",(int16_t*)&dl_ch_mag128[0]);\n                    dl_ch_mag128[1] = _mm_unpackhi_epi16(mmtmpD0, mmtmpD0);\n                    dl_ch_mag128b[1] = dl_ch_mag128[1];\n                    dl_ch_mag128[1] = _mm_mulhi_epi16(dl_ch_mag128[1], QAM_amp128);\n                    dl_ch_mag128[1] = _mm_slli_epi16(dl_ch_mag128[1], 1);\n\n                    if(pilots == 0)\n                    {\n                        mmtmpD0 = _mm_madd_epi16(dl_ch128[2], dl_ch128[2]);\n                        mmtmpD0 = _mm_srai_epi32(mmtmpD0, output_shift);\n                        mmtmpD1 = _mm_packs_epi32(mmtmpD0, mmtmpD0);\n                        dl_ch_mag128[2] = _mm_unpacklo_epi16(mmtmpD1, mmtmpD1);\n                        dl_ch_mag128b[2] = dl_ch_mag128[2];\n                        dl_ch_mag128[2] = _mm_mulhi_epi16(dl_ch_mag128[2], QAM_amp128);\n                        dl_ch_mag128[2] = _mm_slli_epi16(dl_ch_mag128[2], 1);\n                    }\n\n                    dl_ch_mag128b[0] = _mm_mulhi_epi16(dl_ch_mag128b[0], QAM_amp128b);\n                    dl_ch_mag128b[0] = _mm_slli_epi16(dl_ch_mag128b[0], 1);\n                    dl_ch_mag128b[1] = _mm_mulhi_epi16(dl_ch_mag128b[1], QAM_amp128b);\n                    dl_ch_mag128b[1] = _mm_slli_epi16(dl_ch_mag128b[1], 1);\n\n                    if(pilots == 0)\n                    {\n                        dl_ch_mag128b[2] = _mm_mulhi_epi16(dl_ch_mag128b[2], QAM_amp128b);\n                        dl_ch_mag128b[2] = _mm_slli_epi16(dl_ch_mag128b[2], 1);\n                    }\n                }\n\n                // multiply by conjugated channel\n                mmtmpD0 = _mm_madd_epi16(dl_ch128[0], rxdataF128[0]);\n                // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n                mmtmpD1 = _mm_shufflelo_epi16(dl_ch128[0], _MM_SHUFFLE(2, 3, 0, 1));\n                mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1, _MM_SHUFFLE(2, 3, 0, 1));\n                mmtmpD1 = _mm_sign_epi16(mmtmpD1, *(__m128i *)&conjugate[0]);\n                //  print_ints(\"im\",&mmtmpD1);\n                mmtmpD1 = _mm_madd_epi16(mmtmpD1, rxdataF128[0]);\n                // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n                mmtmpD0 = _mm_srai_epi32(mmtmpD0, output_shift);\n                //  print_ints(\"re(shift)\",&mmtmpD0);\n                mmtmpD1 = _mm_srai_epi32(mmtmpD1, output_shift);\n                //  print_ints(\"im(shift)\",&mmtmpD1);\n                mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0, mmtmpD1);\n                mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0, mmtmpD1);\n                //        print_ints(\"c0\",&mmtmpD2);\n                //  print_ints(\"c1\",&mmtmpD3);\n                rxdataF_comp128[0] = _mm_packs_epi32(mmtmpD2, mmtmpD3);\n                //  print_shorts(\"rx:\",rxdataF128);\n                //  print_shorts(\"ch:\",dl_ch128);\n                //  print_shorts(\"pack:\",rxdataF_comp128);\n                // multiply by conjugated channel\n                mmtmpD0 = _mm_madd_epi16(dl_ch128[1], rxdataF128[1]);\n                // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n                mmtmpD1 = _mm_shufflelo_epi16(dl_ch128[1], _MM_SHUFFLE(2, 3, 0, 1));\n                mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1, _MM_SHUFFLE(2, 3, 0, 1));\n                mmtmpD1 = _mm_sign_epi16(mmtmpD1, *(__m128i *)conjugate);\n                mmtmpD1 = _mm_madd_epi16(mmtmpD1, rxdataF128[1]);\n                // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n                mmtmpD0 = _mm_srai_epi32(mmtmpD0, output_shift);\n                mmtmpD1 = _mm_srai_epi32(mmtmpD1, output_shift);\n                mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0, mmtmpD1);\n                mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0, mmtmpD1);\n                rxdataF_comp128[1] = _mm_packs_epi32(mmtmpD2, mmtmpD3);\n                //  print_shorts(\"rx:\",rxdataF128+1);\n                //  print_shorts(\"ch:\",dl_ch128+1);\n                //  print_shorts(\"pack:\",rxdataF_comp128+1);\n\n                if(pilots == 0)\n                {\n                    // multiply by conjugated channel\n                    mmtmpD0 = _mm_madd_epi16(dl_ch128[2], rxdataF128[2]);\n                    // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n                    mmtmpD1 = _mm_shufflelo_epi16(dl_ch128[2], _MM_SHUFFLE(2, 3, 0, 1));\n                    mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1, _MM_SHUFFLE(2, 3, 0, 1));\n                    mmtmpD1 = _mm_sign_epi16(mmtmpD1, *(__m128i *)conjugate);\n                    mmtmpD1 = _mm_madd_epi16(mmtmpD1, rxdataF128[2]);\n                    // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n                    mmtmpD0 = _mm_srai_epi32(mmtmpD0, output_shift);\n                    mmtmpD1 = _mm_srai_epi32(mmtmpD1, output_shift);\n                    mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0, mmtmpD1);\n                    mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0, mmtmpD1);\n                    rxdataF_comp128[2] = _mm_packs_epi32(mmtmpD2, mmtmpD3);\n                    //  print_shorts(\"rx:\",rxdataF128+2);\n                    //  print_shorts(\"ch:\",dl_ch128+2);\n                    // print_shorts(\"pack:\",rxdataF_comp128+2);\n                    dl_ch128 += 3;\n                    dl_ch_mag128 += 3;\n                    dl_ch_mag128b += 3;\n                    rxdataF128 += 3;\n                    rxdataF_comp128 += 3;\n                }\n                else     // we have a smaller PDSCH in symbols with pilots so skip last group of 4 REs and increment less\n                {\n                    dl_ch128 += 2;\n                    dl_ch_mag128 += 2;\n                    dl_ch_mag128b += 2;\n                    rxdataF128 += 2;\n                    rxdataF_comp128 += 2;\n                }\n            }\n        }\n    }\n\n    if(rho)\n    {\n        for(aarx = 0; aarx < frame_parms->nb_antennas_rx; aarx++)\n        {\n            rho128        = (__m128i *)&rho[aarx][symbol * frame_parms->N_RB_DL * 12];\n            dl_ch128      = (__m128i *)&dl_ch_estimates_ext[aarx][symbol * frame_parms->N_RB_DL * 12];\n            dl_ch128_2    = (__m128i *)&dl_ch_estimates_ext[2 + aarx][symbol * frame_parms->N_RB_DL * 12];\n\n            for(rb = 0; rb < nb_rb; rb++)\n            {\n                // multiply by conjugated channel\n                mmtmpD0 = _mm_madd_epi16(dl_ch128[0], dl_ch128_2[0]);\n                //  print_ints(\"re\",&mmtmpD0);\n                // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n                mmtmpD1 = _mm_shufflelo_epi16(dl_ch128[0], _MM_SHUFFLE(2, 3, 0, 1));\n                mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1, _MM_SHUFFLE(2, 3, 0, 1));\n                mmtmpD1 = _mm_sign_epi16(mmtmpD1, *(__m128i *)&conjugate[0]);\n                //  print_ints(\"im\",&mmtmpD1);\n                mmtmpD1 = _mm_madd_epi16(mmtmpD1, dl_ch128_2[0]);\n                // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n                mmtmpD0 = _mm_srai_epi32(mmtmpD0, output_shift);\n                //  print_ints(\"re(shift)\",&mmtmpD0);\n                mmtmpD1 = _mm_srai_epi32(mmtmpD1, output_shift);\n                //  print_ints(\"im(shift)\",&mmtmpD1);\n                mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0, mmtmpD1);\n                mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0, mmtmpD1);\n                //        print_ints(\"c0\",&mmtmpD2);\n                //  print_ints(\"c1\",&mmtmpD3);\n                rho128[0] = _mm_packs_epi32(mmtmpD2, mmtmpD3);\n                //print_shorts(\"rx:\",dl_ch128_2);\n                //print_shorts(\"ch:\",dl_ch128);\n                //print_shorts(\"pack:\",rho128);\n                // multiply by conjugated channel\n                mmtmpD0 = _mm_madd_epi16(dl_ch128[1], dl_ch128_2[1]);\n                // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n                mmtmpD1 = _mm_shufflelo_epi16(dl_ch128[1], _MM_SHUFFLE(2, 3, 0, 1));\n                mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1, _MM_SHUFFLE(2, 3, 0, 1));\n                mmtmpD1 = _mm_sign_epi16(mmtmpD1, *(__m128i *)conjugate);\n                mmtmpD1 = _mm_madd_epi16(mmtmpD1, dl_ch128_2[1]);\n                // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n                mmtmpD0 = _mm_srai_epi32(mmtmpD0, output_shift);\n                mmtmpD1 = _mm_srai_epi32(mmtmpD1, output_shift);\n                mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0, mmtmpD1);\n                mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0, mmtmpD1);\n                rho128[1] = _mm_packs_epi32(mmtmpD2, mmtmpD3);\n                //print_shorts(\"rx:\",dl_ch128_2+1);\n                //print_shorts(\"ch:\",dl_ch128+1);\n                //print_shorts(\"pack:\",rho128+1);\n                // multiply by conjugated channel\n                mmtmpD0 = _mm_madd_epi16(dl_ch128[2], dl_ch128_2[2]);\n                // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n                mmtmpD1 = _mm_shufflelo_epi16(dl_ch128[2], _MM_SHUFFLE(2, 3, 0, 1));\n                mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1, _MM_SHUFFLE(2, 3, 0, 1));\n                mmtmpD1 = _mm_sign_epi16(mmtmpD1, *(__m128i *)conjugate);\n                mmtmpD1 = _mm_madd_epi16(mmtmpD1, dl_ch128_2[2]);\n                // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n                mmtmpD0 = _mm_srai_epi32(mmtmpD0, output_shift);\n                mmtmpD1 = _mm_srai_epi32(mmtmpD1, output_shift);\n                mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0, mmtmpD1);\n                mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0, mmtmpD1);\n                rho128[2] = _mm_packs_epi32(mmtmpD2, mmtmpD3);\n                //print_shorts(\"rx:\",dl_ch128_2+2);\n                //print_shorts(\"ch:\",dl_ch128+2);\n                //print_shorts(\"pack:\",rho128+2);\n                dl_ch128 += 3;\n                dl_ch128_2 += 3;\n                rho128 += 3;\n            }\n\n            if(first_symbol_flag == 1)\n            {\n                measurements->rx_correlation[0][aarx] = signal_energy(&rho[aarx][symbol * frame_parms->N_RB_DL * 12], rb * 12);\n            }\n        }\n    }\n\n    _mm_empty();\n    _m_empty();\n#elif defined(__arm__)\n    unsigned short rb;\n    unsigned char aatx, aarx, symbol_mod, pilots = 0;\n    int16x4_t *dl_ch128, *dl_ch128_2, *rxdataF128;\n    int32x4_t mmtmpD0, mmtmpD1, mmtmpD0b, mmtmpD1b;\n    int16x8_t *dl_ch_mag128, *dl_ch_mag128b, mmtmpD2, mmtmpD3, mmtmpD4;\n    int16x8_t QAM_amp128, QAM_amp128b;\n    int16x4x2_t *rxdataF_comp128, *rho128;\n    int16_t conj[4]__attribute__((aligned(16))) = {1, -1, 1, -1};\n    int32x4_t output_shift128 = vmovq_n_s32(-(int32_t)output_shift);\n    symbol_mod = (symbol >= (7 - frame_parms->Ncp)) ? symbol - (7 - frame_parms->Ncp) : symbol;\n\n    if((symbol_mod == 0) || (symbol_mod == (4 - frame_parms->Ncp)))\n    {\n        if(frame_parms->nb_antenna_ports_eNB == 1)  // 10 out of 12 so don't reduce size\n        {\n            nb_rb = 1 + (5 * nb_rb / 6);\n        }\n        else\n        {\n            pilots = 1;\n        }\n    }\n\n    for(aatx = 0; aatx < frame_parms->nb_antenna_ports_eNB; aatx++)\n    {\n        if(mod_order == 4)\n        {\n            QAM_amp128  = vmovq_n_s16(QAM16_n1);  // 2/sqrt(10)\n            QAM_amp128b = vmovq_n_s16(0);\n        }\n        else if(mod_order == 6)\n        {\n            QAM_amp128  = vmovq_n_s16(QAM64_n1); //\n            QAM_amp128b = vmovq_n_s16(QAM64_n2);\n        }\n\n        //    printf(\"comp: rxdataF_comp %p, symbol %d\\n\",rxdataF_comp[0],symbol);\n\n        for(aarx = 0; aarx < frame_parms->nb_antennas_rx; aarx++)\n        {\n            dl_ch128          = (int16x4_t *)&dl_ch_estimates_ext[aatx * frame_parms->nb_antennas_rx + aarx][symbol * frame_parms->N_RB_DL * 12];\n            dl_ch_mag128      = (int16x8_t *)&dl_ch_mag[aatx * frame_parms->nb_antennas_rx + aarx][symbol * frame_parms->N_RB_DL * 12];\n            dl_ch_mag128b     = (int16x8_t *)&dl_ch_magb[aatx * frame_parms->nb_antennas_rx + aarx][symbol * frame_parms->N_RB_DL * 12];\n            rxdataF128        = (int16x4_t *)&rxdataF_ext[aarx][symbol * frame_parms->N_RB_DL * 12];\n            rxdataF_comp128   = (int16x4x2_t *)&rxdataF_comp[aatx * frame_parms->nb_antennas_rx + aarx][symbol * frame_parms->N_RB_DL * 12];\n\n            for(rb = 0; rb < nb_rb; rb++)\n            {\n                if(mod_order > 2)\n                {\n                    // get channel amplitude if not QPSK\n                    mmtmpD0 = vmull_s16(dl_ch128[0], dl_ch128[0]);\n                    // mmtmpD0 = [ch0*ch0,ch1*ch1,ch2*ch2,ch3*ch3];\n                    mmtmpD0 = vqshlq_s32(vqaddq_s32(mmtmpD0, vrev64q_s32(mmtmpD0)), output_shift128);\n                    // mmtmpD0 = [ch0*ch0 + ch1*ch1,ch0*ch0 + ch1*ch1,ch2*ch2 + ch3*ch3,ch2*ch2 + ch3*ch3]>>output_shift128 on 32-bits\n                    mmtmpD1 = vmull_s16(dl_ch128[1], dl_ch128[1]);\n                    mmtmpD1 = vqshlq_s32(vqaddq_s32(mmtmpD1, vrev64q_s32(mmtmpD1)), output_shift128);\n                    mmtmpD2 = vcombine_s16(vmovn_s32(mmtmpD0), vmovn_s32(mmtmpD1));\n                    // mmtmpD2 = [ch0*ch0 + ch1*ch1,ch0*ch0 + ch1*ch1,ch2*ch2 + ch3*ch3,ch2*ch2 + ch3*ch3,ch4*ch4 + ch5*ch5,ch4*ch4 + ch5*ch5,ch6*ch6 + ch7*ch7,ch6*ch6 + ch7*ch7]>>output_shift128 on 16-bits\n                    mmtmpD0 = vmull_s16(dl_ch128[2], dl_ch128[2]);\n                    mmtmpD0 = vqshlq_s32(vqaddq_s32(mmtmpD0, vrev64q_s32(mmtmpD0)), output_shift128);\n                    mmtmpD1 = vmull_s16(dl_ch128[3], dl_ch128[3]);\n                    mmtmpD1 = vqshlq_s32(vqaddq_s32(mmtmpD1, vrev64q_s32(mmtmpD1)), output_shift128);\n                    mmtmpD3 = vcombine_s16(vmovn_s32(mmtmpD0), vmovn_s32(mmtmpD1));\n\n                    if(pilots == 0)\n                    {\n                        mmtmpD0 = vmull_s16(dl_ch128[4], dl_ch128[4]);\n                        mmtmpD0 = vqshlq_s32(vqaddq_s32(mmtmpD0, vrev64q_s32(mmtmpD0)), output_shift128);\n                        mmtmpD1 = vmull_s16(dl_ch128[5], dl_ch128[5]);\n                        mmtmpD1 = vqshlq_s32(vqaddq_s32(mmtmpD1, vrev64q_s32(mmtmpD1)), output_shift128);\n                        mmtmpD4 = vcombine_s16(vmovn_s32(mmtmpD0), vmovn_s32(mmtmpD1));\n                    }\n\n                    dl_ch_mag128b[0] = vqdmulhq_s16(mmtmpD2, QAM_amp128b);\n                    dl_ch_mag128b[1] = vqdmulhq_s16(mmtmpD3, QAM_amp128b);\n                    dl_ch_mag128[0] = vqdmulhq_s16(mmtmpD2, QAM_amp128);\n                    dl_ch_mag128[1] = vqdmulhq_s16(mmtmpD3, QAM_amp128);\n\n                    if(pilots == 0)\n                    {\n                        dl_ch_mag128b[2] = vqdmulhq_s16(mmtmpD4, QAM_amp128b);\n                        dl_ch_mag128[2]  = vqdmulhq_s16(mmtmpD4, QAM_amp128);\n                    }\n                }\n\n                mmtmpD0 = vmull_s16(dl_ch128[0], rxdataF128[0]);\n                //mmtmpD0 = [Re(ch[0])Re(rx[0]) Im(ch[0])Im(ch[0]) Re(ch[1])Re(rx[1]) Im(ch[1])Im(ch[1])]\n                mmtmpD1 = vmull_s16(dl_ch128[1], rxdataF128[1]);\n                //mmtmpD1 = [Re(ch[2])Re(rx[2]) Im(ch[2])Im(ch[2]) Re(ch[3])Re(rx[3]) Im(ch[3])Im(ch[3])]\n                mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0), vget_high_s32(mmtmpD0)),\n                                       vpadd_s32(vget_low_s32(mmtmpD1), vget_high_s32(mmtmpD1)));\n                //mmtmpD0 = [Re(ch[0])Re(rx[0])+Im(ch[0])Im(ch[0]) Re(ch[1])Re(rx[1])+Im(ch[1])Im(ch[1]) Re(ch[2])Re(rx[2])+Im(ch[2])Im(ch[2]) Re(ch[3])Re(rx[3])+Im(ch[3])Im(ch[3])]\n                mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch128[0], *(int16x4_t *)conj)), rxdataF128[0]);\n                //mmtmpD0 = [-Im(ch[0])Re(rx[0]) Re(ch[0])Im(rx[0]) -Im(ch[1])Re(rx[1]) Re(ch[1])Im(rx[1])]\n                mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch128[1], *(int16x4_t *)conj)), rxdataF128[1]);\n                //mmtmpD0 = [-Im(ch[2])Re(rx[2]) Re(ch[2])Im(rx[2]) -Im(ch[3])Re(rx[3]) Re(ch[3])Im(rx[3])]\n                mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b), vget_high_s32(mmtmpD0b)),\n                                       vpadd_s32(vget_low_s32(mmtmpD1b), vget_high_s32(mmtmpD1b)));\n                //mmtmpD1 = [-Im(ch[0])Re(rx[0])+Re(ch[0])Im(rx[0]) -Im(ch[1])Re(rx[1])+Re(ch[1])Im(rx[1]) -Im(ch[2])Re(rx[2])+Re(ch[2])Im(rx[2]) -Im(ch[3])Re(rx[3])+Re(ch[3])Im(rx[3])]\n                mmtmpD0 = vqshlq_s32(mmtmpD0, output_shift128);\n                mmtmpD1 = vqshlq_s32(mmtmpD1, output_shift128);\n                rxdataF_comp128[0] = vzip_s16(vmovn_s32(mmtmpD0), vmovn_s32(mmtmpD1));\n                mmtmpD0 = vmull_s16(dl_ch128[2], rxdataF128[2]);\n                mmtmpD1 = vmull_s16(dl_ch128[3], rxdataF128[3]);\n                mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0), vget_high_s32(mmtmpD0)),\n                                       vpadd_s32(vget_low_s32(mmtmpD1), vget_high_s32(mmtmpD1)));\n                mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch128[2], *(int16x4_t *)conj)), rxdataF128[2]);\n                mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch128[3], *(int16x4_t *)conj)), rxdataF128[3]);\n                mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b), vget_high_s32(mmtmpD0b)),\n                                       vpadd_s32(vget_low_s32(mmtmpD1b), vget_high_s32(mmtmpD1b)));\n                mmtmpD0 = vqshlq_s32(mmtmpD0, output_shift128);\n                mmtmpD1 = vqshlq_s32(mmtmpD1, output_shift128);\n                rxdataF_comp128[1] = vzip_s16(vmovn_s32(mmtmpD0), vmovn_s32(mmtmpD1));\n\n                if(pilots == 0)\n                {\n                    mmtmpD0 = vmull_s16(dl_ch128[4], rxdataF128[4]);\n                    mmtmpD1 = vmull_s16(dl_ch128[5], rxdataF128[5]);\n                    mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0), vget_high_s32(mmtmpD0)),\n                                           vpadd_s32(vget_low_s32(mmtmpD1), vget_high_s32(mmtmpD1)));\n                    mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch128[4], *(int16x4_t *)conj)), rxdataF128[4]);\n                    mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch128[5], *(int16x4_t *)conj)), rxdataF128[5]);\n                    mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b), vget_high_s32(mmtmpD0b)),\n                                           vpadd_s32(vget_low_s32(mmtmpD1b), vget_high_s32(mmtmpD1b)));\n                    mmtmpD0 = vqshlq_s32(mmtmpD0, output_shift128);\n                    mmtmpD1 = vqshlq_s32(mmtmpD1, output_shift128);\n                    rxdataF_comp128[2] = vzip_s16(vmovn_s32(mmtmpD0), vmovn_s32(mmtmpD1));\n                    dl_ch128 += 6;\n                    dl_ch_mag128 += 3;\n                    dl_ch_mag128b += 3;\n                    rxdataF128 += 6;\n                    rxdataF_comp128 += 3;\n                }\n                else     // we have a smaller PDSCH in symbols with pilots so skip last group of 4 REs and increment less\n                {\n                    dl_ch128 += 4;\n                    dl_ch_mag128 += 2;\n                    dl_ch_mag128b += 2;\n                    rxdataF128 += 4;\n                    rxdataF_comp128 += 2;\n                }\n            }\n        }\n    }\n\n    if(rho)\n    {\n        for(aarx = 0; aarx < frame_parms->nb_antennas_rx; aarx++)\n        {\n            rho128        = (int16x4x2_t *)&rho[aarx][symbol * frame_parms->N_RB_DL * 12];\n            dl_ch128      = (int16x4_t *)&dl_ch_estimates_ext[aarx][symbol * frame_parms->N_RB_DL * 12];\n            dl_ch128_2    = (int16x4_t *)&dl_ch_estimates_ext[2 + aarx][symbol * frame_parms->N_RB_DL * 12];\n\n            for(rb = 0; rb < nb_rb; rb++)\n            {\n                mmtmpD0 = vmull_s16(dl_ch128[0], dl_ch128_2[0]);\n                mmtmpD1 = vmull_s16(dl_ch128[1], dl_ch128_2[1]);\n                mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0), vget_high_s32(mmtmpD0)),\n                                       vpadd_s32(vget_low_s32(mmtmpD1), vget_high_s32(mmtmpD1)));\n                mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch128[0], *(int16x4_t *)conj)), dl_ch128_2[0]);\n                mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch128[1], *(int16x4_t *)conj)), dl_ch128_2[1]);\n                mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b), vget_high_s32(mmtmpD0b)),\n                                       vpadd_s32(vget_low_s32(mmtmpD1b), vget_high_s32(mmtmpD1b)));\n                mmtmpD0 = vqshlq_s32(mmtmpD0, output_shift128);\n                mmtmpD1 = vqshlq_s32(mmtmpD1, output_shift128);\n                rho128[0] = vzip_s16(vmovn_s32(mmtmpD0), vmovn_s32(mmtmpD1));\n                mmtmpD0 = vmull_s16(dl_ch128[2], dl_ch128_2[2]);\n                mmtmpD1 = vmull_s16(dl_ch128[3], dl_ch128_2[3]);\n                mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0), vget_high_s32(mmtmpD0)),\n                                       vpadd_s32(vget_low_s32(mmtmpD1), vget_high_s32(mmtmpD1)));\n                mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch128[2], *(int16x4_t *)conj)), dl_ch128_2[2]);\n                mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch128[3], *(int16x4_t *)conj)), dl_ch128_2[3]);\n                mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b), vget_high_s32(mmtmpD0b)),\n                                       vpadd_s32(vget_low_s32(mmtmpD1b), vget_high_s32(mmtmpD1b)));\n                mmtmpD0 = vqshlq_s32(mmtmpD0, output_shift128);\n                mmtmpD1 = vqshlq_s32(mmtmpD1, output_shift128);\n                rho128[1] = vzip_s16(vmovn_s32(mmtmpD0), vmovn_s32(mmtmpD1));\n                mmtmpD0 = vmull_s16(dl_ch128[0], dl_ch128_2[0]);\n                mmtmpD1 = vmull_s16(dl_ch128[1], dl_ch128_2[1]);\n                mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0), vget_high_s32(mmtmpD0)),\n                                       vpadd_s32(vget_low_s32(mmtmpD1), vget_high_s32(mmtmpD1)));\n                mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch128[4], *(int16x4_t *)conj)), dl_ch128_2[4]);\n                mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch128[5], *(int16x4_t *)conj)), dl_ch128_2[5]);\n                mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b), vget_high_s32(mmtmpD0b)),\n                                       vpadd_s32(vget_low_s32(mmtmpD1b), vget_high_s32(mmtmpD1b)));\n                mmtmpD0 = vqshlq_s32(mmtmpD0, output_shift128);\n                mmtmpD1 = vqshlq_s32(mmtmpD1, output_shift128);\n                rho128[2] = vzip_s16(vmovn_s32(mmtmpD0), vmovn_s32(mmtmpD1));\n                dl_ch128 += 6;\n                dl_ch128_2 += 6;\n                rho128 += 3;\n            }\n\n            if(first_symbol_flag == 1)\n            {\n                measurements->rx_correlation[0][aarx] = signal_energy(&rho[aarx][symbol * frame_parms->N_RB_DL * 12], rb * 12);\n            }\n        }\n    }\n\n#endif\n}\n\nvoid dlsch_channel_compensation_core(int **rxdataF_ext,\n                                     int **dl_ch_estimates_ext,\n                                     int **dl_ch_mag,\n                                     int **dl_ch_magb,\n                                     int **rxdataF_comp,\n                                     int **rho,\n                                     unsigned char n_tx,\n                                     unsigned char n_rx,\n                                     unsigned char mod_order,\n                                     unsigned char output_shift,\n                                     int length,\n                                     int start_point)\n\n{\n    unsigned short ii;\n    int length_mod8 = 0;\n    int length2;\n    __m128i *dl_ch128, *dl_ch_mag128, *dl_ch_mag128b, *dl_ch128_2, *rxdataF128, *rxdataF_comp128, *rho128;\n    __m128i mmtmpD0, mmtmpD1, mmtmpD2, mmtmpD3, QAM_amp128;\n    int aatx = 0, aarx = 0;\n\n    for(aatx = 0; aatx < n_tx; aatx++)\n    {\n        __m128i QAM_amp128b;\n\n        if(mod_order == 4)\n        {\n            QAM_amp128 = _mm_set1_epi16(QAM16_n1);  // 2/sqrt(10)\n            QAM_amp128b = _mm_setzero_si128();\n        }\n        else if(mod_order == 6)\n        {\n            QAM_amp128  = _mm_set1_epi16(QAM64_n1); //\n            QAM_amp128b = _mm_set1_epi16(QAM64_n2);\n        }\n\n        for(aarx = 0; aarx < n_rx; aarx++)\n        {\n            /*  TODO: hack to be removed. There is crash for 1 antenna case, so\n                for 1 antenna case, I put back the value 2 as it was before\n                Elena's commit.\n            */\n            int x = n_rx > 1 ? n_rx : 2;\n            dl_ch128          = (__m128i *)&dl_ch_estimates_ext[aatx * x + aarx][start_point];\n            dl_ch_mag128      = (__m128i *)&dl_ch_mag[aatx * x + aarx][start_point];\n            dl_ch_mag128b     = (__m128i *)&dl_ch_magb[aatx * x + aarx][start_point];\n            rxdataF128        = (__m128i *)&rxdataF_ext[aarx][start_point];\n            rxdataF_comp128   = (__m128i *)&rxdataF_comp[aatx * x + aarx][start_point];\n            length_mod8 = length & 7;\n\n            if(length_mod8 == 0)\n            {\n                length2 = length >> 3;\n\n                for(ii = 0; ii < length2; ++ii)\n                {\n                    if(mod_order > 2)\n                    {\n                        // get channel amplitude if not QPSK\n                        mmtmpD0 = _mm_madd_epi16(dl_ch128[0], dl_ch128[0]);\n                        mmtmpD0 = _mm_srai_epi32(mmtmpD0, output_shift);\n                        mmtmpD1 = _mm_madd_epi16(dl_ch128[1], dl_ch128[1]);\n                        mmtmpD1 = _mm_srai_epi32(mmtmpD1, output_shift);\n                        mmtmpD0 = _mm_packs_epi32(mmtmpD0, mmtmpD1);\n                        // store channel magnitude here in a new field of dlsch\n                        dl_ch_mag128[0] = _mm_unpacklo_epi16(mmtmpD0, mmtmpD0);\n                        dl_ch_mag128b[0] = dl_ch_mag128[0];\n                        dl_ch_mag128[0] = _mm_mulhi_epi16(dl_ch_mag128[0], QAM_amp128);\n                        dl_ch_mag128[0] = _mm_slli_epi16(dl_ch_mag128[0], 1);\n                        //print_ints(\"Re(ch):\",(int16_t*)&mmtmpD0);\n                        //print_shorts(\"QAM_amp:\",(int16_t*)&QAM_amp128);\n                        //print_shorts(\"mag:\",(int16_t*)&dl_ch_mag128[0]);\n                        dl_ch_mag128[1] = _mm_unpackhi_epi16(mmtmpD0, mmtmpD0);\n                        dl_ch_mag128b[1] = dl_ch_mag128[1];\n                        dl_ch_mag128[1] = _mm_mulhi_epi16(dl_ch_mag128[1], QAM_amp128);\n                        dl_ch_mag128[1] = _mm_slli_epi16(dl_ch_mag128[1], 1);\n                        dl_ch_mag128b[0] = _mm_mulhi_epi16(dl_ch_mag128b[0], QAM_amp128b);\n                        dl_ch_mag128b[0] = _mm_slli_epi16(dl_ch_mag128b[0], 1);\n                        dl_ch_mag128b[1] = _mm_mulhi_epi16(dl_ch_mag128b[1], QAM_amp128b);\n                        dl_ch_mag128b[1] = _mm_slli_epi16(dl_ch_mag128b[1], 1);\n                    }\n\n                    // multiply by conjugated channel\n                    mmtmpD0 = _mm_madd_epi16(dl_ch128[0], rxdataF128[0]);\n                    // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n                    mmtmpD1 = _mm_shufflelo_epi16(dl_ch128[0], _MM_SHUFFLE(2, 3, 0, 1));\n                    mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1, _MM_SHUFFLE(2, 3, 0, 1));\n                    mmtmpD1 = _mm_sign_epi16(mmtmpD1, *(__m128i *)&conjugate[0]);\n                    //  print_ints(\"im\",&mmtmpD1);\n                    mmtmpD1 = _mm_madd_epi16(mmtmpD1, rxdataF128[0]);\n                    // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n                    mmtmpD0 = _mm_srai_epi32(mmtmpD0, output_shift);\n                    //  print_ints(\"re(shift)\",&mmtmpD0);\n                    mmtmpD1 = _mm_srai_epi32(mmtmpD1, output_shift);\n                    //  print_ints(\"im(shift)\",&mmtmpD1);\n                    mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0, mmtmpD1);\n                    mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0, mmtmpD1);\n                    //        print_ints(\"c0\",&mmtmpD2);\n                    //  print_ints(\"c1\",&mmtmpD3);\n                    rxdataF_comp128[0] = _mm_packs_epi32(mmtmpD2, mmtmpD3);\n                    //  print_shorts(\"rx:\",rxdataF128);\n                    //  print_shorts(\"ch:\",dl_ch128);\n                    //  print_shorts(\"pack:\",rxdataF_comp128);\n                    // multiply by conjugated channel\n                    mmtmpD0 = _mm_madd_epi16(dl_ch128[1], rxdataF128[1]);\n                    // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n                    mmtmpD1 = _mm_shufflelo_epi16(dl_ch128[1], _MM_SHUFFLE(2, 3, 0, 1));\n                    mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1, _MM_SHUFFLE(2, 3, 0, 1));\n                    mmtmpD1 = _mm_sign_epi16(mmtmpD1, *(__m128i *)conjugate);\n                    mmtmpD1 = _mm_madd_epi16(mmtmpD1, rxdataF128[1]);\n                    // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n                    mmtmpD0 = _mm_srai_epi32(mmtmpD0, output_shift);\n                    mmtmpD1 = _mm_srai_epi32(mmtmpD1, output_shift);\n                    mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0, mmtmpD1);\n                    mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0, mmtmpD1);\n                    rxdataF_comp128[1] = _mm_packs_epi32(mmtmpD2, mmtmpD3);\n                    //  print_shorts(\"rx:\",rxdataF128+1);\n                    //  print_shorts(\"ch:\",dl_ch128+1);\n                    //print_shorts(\"pack:\",rxdataF_comp128+1);\n                    dl_ch128 += 2;\n                    dl_ch_mag128 += 2;\n                    dl_ch_mag128b += 2;\n                    rxdataF128 += 2;\n                    rxdataF_comp128 += 2;\n                }\n            }\n            else\n            {\n                printf(\"Channel Compensation: Received number of subcarriers is not multiple of 8, \\n\"\n                       \"need to adapt the code!\\n\");\n            }\n        }\n    }\n\n    /*This part of code makes sense only for processing in 2x2 blocks*/\n    if(rho)\n    {\n        for(aarx = 0; aarx < n_rx; aarx++)\n        {\n            rho128        = (__m128i *)&rho[aarx][start_point];\n            dl_ch128      = (__m128i *)&dl_ch_estimates_ext[aarx][start_point];\n            dl_ch128_2    = (__m128i *)&dl_ch_estimates_ext[2 + aarx][start_point];\n\n            if(length_mod8 == 0)\n            {\n                length2 = length >> 3;\n\n                for(ii = 0; ii < length2; ++ii)\n                {\n                    // multiply by conjugated channel\n                    mmtmpD0 = _mm_madd_epi16(dl_ch128[0], dl_ch128_2[0]);\n                    //  print_ints(\"re\",&mmtmpD0);\n                    // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n                    mmtmpD1 = _mm_shufflelo_epi16(dl_ch128[0], _MM_SHUFFLE(2, 3, 0, 1));\n                    mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1, _MM_SHUFFLE(2, 3, 0, 1));\n                    mmtmpD1 = _mm_sign_epi16(mmtmpD1, *(__m128i *)&conjugate[0]);\n                    //  print_ints(\"im\",&mmtmpD1);\n                    mmtmpD1 = _mm_madd_epi16(mmtmpD1, dl_ch128_2[0]);\n                    // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n                    mmtmpD0 = _mm_srai_epi32(mmtmpD0, output_shift);\n                    //  print_ints(\"re(shift)\",&mmtmpD0);\n                    mmtmpD1 = _mm_srai_epi32(mmtmpD1, output_shift);\n                    //  print_ints(\"im(shift)\",&mmtmpD1);\n                    mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0, mmtmpD1);\n                    mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0, mmtmpD1);\n                    //        print_ints(\"c0\",&mmtmpD2);\n                    //  print_ints(\"c1\",&mmtmpD3);\n                    rho128[0] = _mm_packs_epi32(mmtmpD2, mmtmpD3);\n                    //print_shorts(\"rx:\",dl_ch128_2);\n                    //print_shorts(\"ch:\",dl_ch128);\n                    //print_shorts(\"pack:\",rho128);\n                    // multiply by conjugated channel\n                    mmtmpD0 = _mm_madd_epi16(dl_ch128[1], dl_ch128_2[1]);\n                    // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n                    mmtmpD1 = _mm_shufflelo_epi16(dl_ch128[1], _MM_SHUFFLE(2, 3, 0, 1));\n                    mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1, _MM_SHUFFLE(2, 3, 0, 1));\n                    mmtmpD1 = _mm_sign_epi16(mmtmpD1, *(__m128i *)conjugate);\n                    mmtmpD1 = _mm_madd_epi16(mmtmpD1, dl_ch128_2[1]);\n                    // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n                    mmtmpD0 = _mm_srai_epi32(mmtmpD0, output_shift);\n                    mmtmpD1 = _mm_srai_epi32(mmtmpD1, output_shift);\n                    mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0, mmtmpD1);\n                    mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0, mmtmpD1);\n                    rho128[1] = _mm_packs_epi32(mmtmpD2, mmtmpD3);\n                    dl_ch128 += 2;\n                    dl_ch128_2 += 2;\n                    rho128 += 2;\n                }\n            }\n            else\n            {\n                printf(\"Channel Compensation: Received number of subcarriers is not multiple of 8, \\n\"\n                       \"need to adapt the code!\\n\");\n            }\n        }\n    }\n\n    _mm_empty();\n    _m_empty();\n}\n\n#if defined(__x86_64__) || defined(__i386__)\n\nvoid prec2A_TM56_128(unsigned char pmi, __m128i *ch0, __m128i *ch1)\n{\n    __m128i amp;\n    amp = _mm_set1_epi16(ONE_OVER_SQRT2_Q15);\n\n    switch(pmi)\n    {\n        case 0 :   // +1 +1\n            //    print_shorts(\"phase 0 :ch0\",ch0);\n            //    print_shorts(\"phase 0 :ch1\",ch1);\n            ch0[0] = _mm_adds_epi16(ch0[0], ch1[0]);\n            break;\n\n        case 1 :   // +1 -1\n            //    print_shorts(\"phase 1 :ch0\",ch0);\n            //    print_shorts(\"phase 1 :ch1\",ch1);\n            ch0[0] = _mm_subs_epi16(ch0[0], ch1[0]);\n            //    print_shorts(\"phase 1 :ch0-ch1\",ch0);\n            break;\n\n        case 2 :   // +1 +j\n            ch1[0] = _mm_sign_epi16(ch1[0], *(__m128i *)&conjugate[0]);\n            ch1[0] = _mm_shufflelo_epi16(ch1[0], _MM_SHUFFLE(2, 3, 0, 1));\n            ch1[0] = _mm_shufflehi_epi16(ch1[0], _MM_SHUFFLE(2, 3, 0, 1));\n            ch0[0] = _mm_subs_epi16(ch0[0], ch1[0]);\n            break;   // +1 -j\n\n        case 3 :\n            ch1[0] = _mm_sign_epi16(ch1[0], *(__m128i *)&conjugate[0]);\n            ch1[0] = _mm_shufflelo_epi16(ch1[0], _MM_SHUFFLE(2, 3, 0, 1));\n            ch1[0] = _mm_shufflehi_epi16(ch1[0], _MM_SHUFFLE(2, 3, 0, 1));\n            ch0[0] = _mm_adds_epi16(ch0[0], ch1[0]);\n            break;\n    }\n\n    ch0[0] = _mm_mulhi_epi16(ch0[0], amp);\n    ch0[0] = _mm_slli_epi16(ch0[0], 1);\n    _mm_empty();\n    _m_empty();\n}\n#elif defined(__arm__)\nvoid prec2A_TM56_128(unsigned char pmi, __m128i *ch0, __m128i *ch1)\n{\n    // sqrt(2) is already taken into account in computation sqrt_rho_a, sqrt_rho_b,\n    //so removed it\n\n    //__m128i amp;\n    //amp = _mm_set1_epi16(ONE_OVER_SQRT2_Q15);\n    switch(pmi)\n    {\n        case 0 :   // +1 +1\n            //    print_shorts(\"phase 0 :ch0\",ch0);\n            //    print_shorts(\"phase 0 :ch1\",ch1);\n            ch0[0] = _mm_adds_epi16(ch0[0], ch1[0]);\n            break;\n\n        case 1 :   // +1 -1\n            //    print_shorts(\"phase 1 :ch0\",ch0);\n            //    print_shorts(\"phase 1 :ch1\",ch1);\n            ch0[0] = _mm_subs_epi16(ch0[0], ch1[0]);\n            //    print_shorts(\"phase 1 :ch0-ch1\",ch0);\n            break;\n\n        case 2 :   // +1 +j\n            ch1[0] = _mm_sign_epi16(ch1[0], *(__m128i *)&conjugate[0]);\n            ch1[0] = _mm_shufflelo_epi16(ch1[0], _MM_SHUFFLE(2, 3, 0, 1));\n            ch1[0] = _mm_shufflehi_epi16(ch1[0], _MM_SHUFFLE(2, 3, 0, 1));\n            ch0[0] = _mm_subs_epi16(ch0[0], ch1[0]);\n            break;   // +1 -j\n\n        case 3 :\n            ch1[0] = _mm_sign_epi16(ch1[0], *(__m128i *)&conjugate[0]);\n            ch1[0] = _mm_shufflelo_epi16(ch1[0], _MM_SHUFFLE(2, 3, 0, 1));\n            ch1[0] = _mm_shufflehi_epi16(ch1[0], _MM_SHUFFLE(2, 3, 0, 1));\n            ch0[0] = _mm_adds_epi16(ch0[0], ch1[0]);\n            break;\n    }\n\n    //ch0[0] = _mm_mulhi_epi16(ch0[0],amp);\n    //ch0[0] = _mm_slli_epi16(ch0[0],1);\n    _mm_empty();\n    _m_empty();\n}\n#endif\n// precoding is stream 0 .5(1,1)  .5(1,-1) .5(1,1)  .5(1,-1)\n//              stream 1 .5(1,-1) .5(1,1)  .5(1,-1) .5(1,1)\n// store \"precoded\" channel for stream 0 in ch0, stream 1 in ch1\n\nshort TM3_prec[8]__attribute__((aligned(16))) = {1, 1, -1, -1, 1, 1, -1, -1} ;\n\nvoid prec2A_TM3_128(__m128i *ch0, __m128i *ch1)\n{\n    __m128i amp = _mm_set1_epi16(ONE_OVER_SQRT2_Q15);\n    __m128i tmp0, tmp1;\n    //_mm_mulhi_epi16\n    //  print_shorts(\"prec2A_TM3 ch0 (before):\",ch0);\n    //  print_shorts(\"prec2A_TM3 ch1 (before):\",ch1);\n    tmp0 = ch0[0];\n    tmp1  = _mm_sign_epi16(ch1[0], ((__m128i *)&TM3_prec)[0]);\n    //  print_shorts(\"prec2A_TM3 ch1*s (mid):\",(__m128i*)TM3_prec);\n    ch0[0] = _mm_adds_epi16(ch0[0], tmp1);\n    ch1[0] = _mm_subs_epi16(tmp0, tmp1);\n    ch0[0] = _mm_mulhi_epi16(ch0[0], amp);\n    ch0[0] = _mm_slli_epi16(ch0[0], 1);\n    ch1[0] = _mm_mulhi_epi16(ch1[0], amp);\n    ch1[0] = _mm_slli_epi16(ch1[0], 1);\n    //  print_shorts(\"prec2A_TM3 ch0 (mid):\",&tmp0);\n    //  print_shorts(\"prec2A_TM3 ch1 (mid):\",ch1);\n    //ch0[0] = _mm_mulhi_epi16(ch0[0],amp);\n    //ch0[0] = _mm_slli_epi16(ch0[0],1);\n    //ch1[0] = _mm_mulhi_epi16(ch1[0],amp);\n    //ch1[0] = _mm_slli_epi16(ch1[0],1);\n    //ch0[0] = _mm_srai_epi16(ch0[0],1);\n    //ch1[0] = _mm_srai_epi16(ch1[0],1);\n    //  print_shorts(\"prec2A_TM3 ch0 (after):\",ch0);\n    //  print_shorts(\"prec2A_TM3 ch1 (after):\",ch1);\n    _mm_empty();\n    _m_empty();\n}\n\n// pmi = 0 => stream 0 (1,1), stream 1 (1,-1)\n// pmi = 1 => stream 0 (1,j), stream 2 (1,-j)\n\nvoid prec2A_TM4_128(int pmi, __m128i *ch0, __m128i *ch1)\n{\n    // sqrt(2) is already taken into account in computation sqrt_rho_a, sqrt_rho_b,\n    //so divide by 2 is replaced by divide by sqrt(2).\n    // printf (\"demod pmi=%d\\n\", pmi);\n    __m128i amp;\n    amp = _mm_set1_epi16(ONE_OVER_SQRT2_Q15);\n    __m128i tmp0, tmp1;\n\n    // print_shorts(\"prec2A_TM4 ch0 (before):\",ch0);\n    // print_shorts(\"prec2A_TM4 ch1 (before):\",ch1);\n\n    if(pmi == 0)    //[1 1;1 -1]\n    {\n        tmp0 = ch0[0];\n        tmp1 = ch1[0];\n        ch0[0] = _mm_adds_epi16(tmp0, tmp1);\n        ch1[0] = _mm_subs_epi16(tmp0, tmp1);\n    }\n    else     //ch0+j*ch1 ch0-j*ch1\n    {\n        tmp0 = ch0[0];\n        tmp1   = _mm_sign_epi16(ch1[0], *(__m128i *)&conjugate[0]);\n        tmp1   = _mm_shufflelo_epi16(tmp1, _MM_SHUFFLE(2, 3, 0, 1));\n        tmp1   = _mm_shufflehi_epi16(tmp1, _MM_SHUFFLE(2, 3, 0, 1));\n        ch0[0] = _mm_subs_epi16(tmp0, tmp1);\n        ch1[0] = _mm_add_epi16(tmp0, tmp1);\n    }\n\n    //print_shorts(\"prec2A_TM4 ch0 (middle):\",ch0);\n    //print_shorts(\"prec2A_TM4 ch1 (middle):\",ch1);\n    ch0[0] = _mm_mulhi_epi16(ch0[0], amp);\n    ch0[0] = _mm_slli_epi16(ch0[0], 1);\n    ch1[0] = _mm_mulhi_epi16(ch1[0], amp);\n    ch1[0] = _mm_slli_epi16(ch1[0], 1);\n    // ch0[0] = _mm_srai_epi16(ch0[0],1); //divide by 2\n    // ch1[0] = _mm_srai_epi16(ch1[0],1); //divide by 2\n    //print_shorts(\"prec2A_TM4 ch0 (end):\",ch0);\n    //print_shorts(\"prec2A_TM4 ch1 (end):\",ch1);\n    _mm_empty();\n    _m_empty();\n    // print_shorts(\"prec2A_TM4 ch0 (end):\",ch0);\n    //print_shorts(\"prec2A_TM4 ch1 (end):\",ch1);\n}\n\nvoid dlsch_channel_compensation_TM56(int **rxdataF_ext,\n                                     int **dl_ch_estimates_ext,\n                                     int **dl_ch_mag,\n                                     int **dl_ch_magb,\n                                     int **rxdataF_comp,\n                                     unsigned char *pmi_ext,\n                                     LTE_DL_FRAME_PARMS *frame_parms,\n                                     PHY_MEASUREMENTS *measurements,\n                                     int eNB_id,\n                                     unsigned char symbol,\n                                     unsigned char mod_order,\n                                     unsigned short nb_rb,\n                                     unsigned char output_shift,\n                                     unsigned char dl_power_off)\n{\n#if defined(__x86_64__) || defined(__i386__)\n    unsigned short rb, Nre;\n    __m128i *dl_ch0_128, *dl_ch1_128, *dl_ch_mag128, *dl_ch_mag128b, *rxdataF128, *rxdataF_comp128;\n    unsigned char aarx = 0, symbol_mod, pilots = 0;\n    int precoded_signal_strength = 0;\n    __m128i mmtmpD0, mmtmpD1, mmtmpD2, mmtmpD3, QAM_amp128;\n    symbol_mod = (symbol >= (7 - frame_parms->Ncp)) ? symbol - (7 - frame_parms->Ncp) : symbol;\n\n    if((symbol_mod == 0) || (symbol_mod == (4 - frame_parms->Ncp)))\n    {\n        pilots = 1;\n    }\n\n    //printf(\"comp prec: symbol %d, pilots %d\\n\",symbol, pilots);\n    __m128i QAM_amp128b = _mm_setzero_si128();\n\n    if(mod_order == 4)\n    {\n        QAM_amp128 = _mm_set1_epi16(QAM16_n1);\n    }\n    else if(mod_order == 6)\n    {\n        QAM_amp128  = _mm_set1_epi16(QAM64_n1);\n        QAM_amp128b = _mm_set1_epi16(QAM64_n2);\n    }\n\n    for(aarx = 0; aarx < frame_parms->nb_antennas_rx; aarx++)\n    {\n        dl_ch0_128          = (__m128i *)&dl_ch_estimates_ext[aarx][symbol * frame_parms->N_RB_DL * 12];\n        dl_ch1_128          = (__m128i *)&dl_ch_estimates_ext[2 + aarx][symbol * frame_parms->N_RB_DL * 12];\n        dl_ch_mag128      = (__m128i *)&dl_ch_mag[aarx][symbol * frame_parms->N_RB_DL * 12];\n        dl_ch_mag128b     = (__m128i *)&dl_ch_magb[aarx][symbol * frame_parms->N_RB_DL * 12];\n        rxdataF128        = (__m128i *)&rxdataF_ext[aarx][symbol * frame_parms->N_RB_DL * 12];\n        rxdataF_comp128   = (__m128i *)&rxdataF_comp[aarx][symbol * frame_parms->N_RB_DL * 12];\n\n        for(rb = 0; rb < nb_rb; rb++)\n        {\n            // combine TX channels using precoder from pmi\n#ifdef DEBUG_DLSCH_DEMOD\n            printf(\"mode 6 prec: rb %d, pmi->%d\\n\", rb, pmi_ext[rb]);\n#endif\n            prec2A_TM56_128(pmi_ext[rb], &dl_ch0_128[0], &dl_ch1_128[0]);\n            prec2A_TM56_128(pmi_ext[rb], &dl_ch0_128[1], &dl_ch1_128[1]);\n\n            if(pilots == 0)\n            {\n                prec2A_TM56_128(pmi_ext[rb], &dl_ch0_128[2], &dl_ch1_128[2]);\n            }\n\n            if(mod_order > 2)\n            {\n                // get channel amplitude if not QPSK\n                mmtmpD0 = _mm_madd_epi16(dl_ch0_128[0], dl_ch0_128[0]);\n                mmtmpD0 = _mm_srai_epi32(mmtmpD0, output_shift);\n                mmtmpD1 = _mm_madd_epi16(dl_ch0_128[1], dl_ch0_128[1]);\n                mmtmpD1 = _mm_srai_epi32(mmtmpD1, output_shift);\n                mmtmpD0 = _mm_packs_epi32(mmtmpD0, mmtmpD1);\n                dl_ch_mag128[0] = _mm_unpacklo_epi16(mmtmpD0, mmtmpD0);\n                dl_ch_mag128b[0] = dl_ch_mag128[0];\n                dl_ch_mag128[0] = _mm_mulhi_epi16(dl_ch_mag128[0], QAM_amp128);\n                dl_ch_mag128[0] = _mm_slli_epi16(dl_ch_mag128[0], 1);\n                //print_shorts(\"dl_ch_mag128[0]=\",&dl_ch_mag128[0]);\n                //print_shorts(\"dl_ch_mag128[0]=\",&dl_ch_mag128[0]);\n                dl_ch_mag128[1] = _mm_unpackhi_epi16(mmtmpD0, mmtmpD0);\n                dl_ch_mag128b[1] = dl_ch_mag128[1];\n                dl_ch_mag128[1] = _mm_mulhi_epi16(dl_ch_mag128[1], QAM_amp128);\n                dl_ch_mag128[1] = _mm_slli_epi16(dl_ch_mag128[1], 1);\n\n                if(pilots == 0)\n                {\n                    mmtmpD0 = _mm_madd_epi16(dl_ch0_128[2], dl_ch0_128[2]);\n                    mmtmpD0 = _mm_srai_epi32(mmtmpD0, output_shift);\n                    mmtmpD1 = _mm_packs_epi32(mmtmpD0, mmtmpD0);\n                    dl_ch_mag128[2] = _mm_unpacklo_epi16(mmtmpD1, mmtmpD1);\n                    dl_ch_mag128b[2] = dl_ch_mag128[2];\n                    dl_ch_mag128[2] = _mm_mulhi_epi16(dl_ch_mag128[2], QAM_amp128);\n                    dl_ch_mag128[2] = _mm_slli_epi16(dl_ch_mag128[2], 1);\n                }\n\n                dl_ch_mag128b[0] = _mm_mulhi_epi16(dl_ch_mag128b[0], QAM_amp128b);\n                dl_ch_mag128b[0] = _mm_slli_epi16(dl_ch_mag128b[0], 1);\n                //print_shorts(\"dl_ch_mag128b[0]=\",&dl_ch_mag128b[0]);\n                dl_ch_mag128b[1] = _mm_mulhi_epi16(dl_ch_mag128b[1], QAM_amp128b);\n                dl_ch_mag128b[1] = _mm_slli_epi16(dl_ch_mag128b[1], 1);\n\n                if(pilots == 0)\n                {\n                    dl_ch_mag128b[2] = _mm_mulhi_epi16(dl_ch_mag128b[2], QAM_amp128b);\n                    dl_ch_mag128b[2] = _mm_slli_epi16(dl_ch_mag128b[2], 1);\n                }\n            }\n\n            // MF multiply by conjugated channel\n            mmtmpD0 = _mm_madd_epi16(dl_ch0_128[0], rxdataF128[0]);\n            //        print_ints(\"re\",&mmtmpD0);\n            // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n            mmtmpD1 = _mm_shufflelo_epi16(dl_ch0_128[0], _MM_SHUFFLE(2, 3, 0, 1));\n            mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1, _MM_SHUFFLE(2, 3, 0, 1));\n            mmtmpD1 = _mm_sign_epi16(mmtmpD1, *(__m128i *)&conjugate[0]);\n            //        print_ints(\"im\",&mmtmpD1);\n            mmtmpD1 = _mm_madd_epi16(mmtmpD1, rxdataF128[0]);\n            // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n            mmtmpD0 = _mm_srai_epi32(mmtmpD0, output_shift);\n            //        print_ints(\"re(shift)\",&mmtmpD0);\n            mmtmpD1 = _mm_srai_epi32(mmtmpD1, output_shift);\n            //        print_ints(\"im(shift)\",&mmtmpD1);\n            mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0, mmtmpD1);\n            mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0, mmtmpD1);\n            //        print_ints(\"c0\",&mmtmpD2);\n            //        print_ints(\"c1\",&mmtmpD3);\n            rxdataF_comp128[0] = _mm_packs_epi32(mmtmpD2, mmtmpD3);\n            //        print_shorts(\"rx:\",rxdataF128);\n            //        print_shorts(\"ch:\",dl_ch128);\n            //        print_shorts(\"pack:\",rxdataF_comp128);\n            // multiply by conjugated channel\n            mmtmpD0 = _mm_madd_epi16(dl_ch0_128[1], rxdataF128[1]);\n            // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n            mmtmpD1 = _mm_shufflelo_epi16(dl_ch0_128[1], _MM_SHUFFLE(2, 3, 0, 1));\n            mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1, _MM_SHUFFLE(2, 3, 0, 1));\n            mmtmpD1 = _mm_sign_epi16(mmtmpD1, *(__m128i *)conjugate);\n            mmtmpD1 = _mm_madd_epi16(mmtmpD1, rxdataF128[1]);\n            // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n            mmtmpD0 = _mm_srai_epi32(mmtmpD0, output_shift);\n            mmtmpD1 = _mm_srai_epi32(mmtmpD1, output_shift);\n            mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0, mmtmpD1);\n            mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0, mmtmpD1);\n            rxdataF_comp128[1] = _mm_packs_epi32(mmtmpD2, mmtmpD3);\n            //  print_shorts(\"rx:\",rxdataF128+1);\n            //  print_shorts(\"ch:\",dl_ch128+1);\n            //  print_shorts(\"pack:\",rxdataF_comp128+1);\n\n            if(pilots == 0)\n            {\n                // multiply by conjugated channel\n                mmtmpD0 = _mm_madd_epi16(dl_ch0_128[2], rxdataF128[2]);\n                // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n                mmtmpD1 = _mm_shufflelo_epi16(dl_ch0_128[2], _MM_SHUFFLE(2, 3, 0, 1));\n                mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1, _MM_SHUFFLE(2, 3, 0, 1));\n                mmtmpD1 = _mm_sign_epi16(mmtmpD1, *(__m128i *)conjugate);\n                mmtmpD1 = _mm_madd_epi16(mmtmpD1, rxdataF128[2]);\n                // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n                mmtmpD0 = _mm_srai_epi32(mmtmpD0, output_shift);\n                mmtmpD1 = _mm_srai_epi32(mmtmpD1, output_shift);\n                mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0, mmtmpD1);\n                mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0, mmtmpD1);\n                rxdataF_comp128[2] = _mm_packs_epi32(mmtmpD2, mmtmpD3);\n                //  print_shorts(\"rx:\",rxdataF128+2);\n                //  print_shorts(\"ch:\",dl_ch128+2);\n                //        print_shorts(\"pack:\",rxdataF_comp128+2);\n                dl_ch0_128 += 3;\n                dl_ch1_128 += 3;\n                dl_ch_mag128 += 3;\n                dl_ch_mag128b += 3;\n                rxdataF128 += 3;\n                rxdataF_comp128 += 3;\n            }\n            else\n            {\n                dl_ch0_128 += 2;\n                dl_ch1_128 += 2;\n                dl_ch_mag128 += 2;\n                dl_ch_mag128b += 2;\n                rxdataF128 += 2;\n                rxdataF_comp128 += 2;\n            }\n        }\n\n        Nre = (pilots == 0) ? 12 : 8;\n        precoded_signal_strength += ((signal_energy_nodc(&dl_ch_estimates_ext[aarx][symbol * frame_parms->N_RB_DL * Nre],\n                                      (nb_rb * Nre))) - (measurements->n0_power[aarx]));\n    } // rx_antennas\n\n    measurements->precoded_cqi_dB[eNB_id][0] = dB_fixed2(precoded_signal_strength, measurements->n0_power_tot);\n    //printf(\"eNB_id %d, symbol %d: precoded CQI %d dB\\n\",eNB_id,symbol,\n    //   measurements->precoded_cqi_dB[eNB_id][0]);\n#elif defined(__arm__)\n    uint32_t rb, Nre;\n    uint32_t aarx, symbol_mod, pilots = 0;\n    int16x4_t *dl_ch0_128, *dl_ch1_128, *rxdataF128;\n    int16x8_t *dl_ch0_128b, *dl_ch1_128b;\n    int32x4_t mmtmpD0, mmtmpD1, mmtmpD0b, mmtmpD1b;\n    int16x8_t *dl_ch_mag128, *dl_ch_mag128b, mmtmpD2, mmtmpD3, mmtmpD4, *rxdataF_comp128;\n    int16x8_t QAM_amp128, QAM_amp128b;\n    int16_t conj[4]__attribute__((aligned(16))) = {1, -1, 1, -1};\n    int32x4_t output_shift128 = vmovq_n_s32(-(int32_t)output_shift);\n    int32_t precoded_signal_strength = 0;\n    symbol_mod = (symbol >= (7 - frame_parms->Ncp)) ? symbol - (7 - frame_parms->Ncp) : symbol;\n\n    if((symbol_mod == 0) || (symbol_mod == (4 - frame_parms->Ncp)))\n    {\n        if(frame_parms->nb_antenna_ports_eNB == 1)  // 10 out of 12 so don't reduce size\n        {\n            nb_rb = 1 + (5 * nb_rb / 6);\n        }\n        else\n        {\n            pilots = 1;\n        }\n    }\n\n    if(mod_order == 4)\n    {\n        QAM_amp128  = vmovq_n_s16(QAM16_n1);  // 2/sqrt(10)\n        QAM_amp128b = vmovq_n_s16(0);\n    }\n    else if(mod_order == 6)\n    {\n        QAM_amp128  = vmovq_n_s16(QAM64_n1); //\n        QAM_amp128b = vmovq_n_s16(QAM64_n2);\n    }\n\n    //    printf(\"comp: rxdataF_comp %p, symbol %d\\n\",rxdataF_comp[0],symbol);\n\n    for(aarx = 0; aarx < frame_parms->nb_antennas_rx; aarx++)\n    {\n        dl_ch0_128          = (int16x4_t *)&dl_ch_estimates_ext[aarx][symbol * frame_parms->N_RB_DL * 12];\n        dl_ch1_128          = (int16x4_t *)&dl_ch_estimates_ext[2 + aarx][symbol * frame_parms->N_RB_DL * 12];\n        dl_ch0_128b         = (int16x8_t *)&dl_ch_estimates_ext[aarx][symbol * frame_parms->N_RB_DL * 12];\n        dl_ch1_128b         = (int16x8_t *)&dl_ch_estimates_ext[2 + aarx][symbol * frame_parms->N_RB_DL * 12];\n        dl_ch_mag128        = (int16x8_t *)&dl_ch_mag[aarx][symbol * frame_parms->N_RB_DL * 12];\n        dl_ch_mag128b       = (int16x8_t *)&dl_ch_magb[aarx][symbol * frame_parms->N_RB_DL * 12];\n        rxdataF128          = (int16x4_t *)&rxdataF_ext[aarx][symbol * frame_parms->N_RB_DL * 12];\n        rxdataF_comp128     = (int16x8_t *)&rxdataF_comp[aarx][symbol * frame_parms->N_RB_DL * 12];\n\n        for(rb = 0; rb < nb_rb; rb++)\n        {\n#ifdef DEBUG_DLSCH_DEMOD\n            printf(\"mode 6 prec: rb %d, pmi->%u\\n\", rb, pmi_ext[rb]);\n#endif\n            prec2A_TM56_128(pmi_ext[rb], &dl_ch0_128b[0], &dl_ch1_128b[0]);\n            prec2A_TM56_128(pmi_ext[rb], &dl_ch0_128b[1], &dl_ch1_128b[1]);\n\n            if(pilots == 0)\n            {\n                prec2A_TM56_128(pmi_ext[rb], &dl_ch0_128b[2], &dl_ch1_128b[2]);\n            }\n\n            if(mod_order > 2)\n            {\n                // get channel amplitude if not QPSK\n                mmtmpD0 = vmull_s16(dl_ch0_128[0], dl_ch0_128[0]);\n                // mmtmpD0 = [ch0*ch0,ch1*ch1,ch2*ch2,ch3*ch3];\n                mmtmpD0 = vqshlq_s32(vqaddq_s32(mmtmpD0, vrev64q_s32(mmtmpD0)), output_shift128);\n                // mmtmpD0 = [ch0*ch0 + ch1*ch1,ch0*ch0 + ch1*ch1,ch2*ch2 + ch3*ch3,ch2*ch2 + ch3*ch3]>>output_shift128 on 32-bits\n                mmtmpD1 = vmull_s16(dl_ch0_128[1], dl_ch0_128[1]);\n                mmtmpD1 = vqshlq_s32(vqaddq_s32(mmtmpD1, vrev64q_s32(mmtmpD1)), output_shift128);\n                mmtmpD2 = vcombine_s16(vmovn_s32(mmtmpD0), vmovn_s32(mmtmpD1));\n                // mmtmpD2 = [ch0*ch0 + ch1*ch1,ch0*ch0 + ch1*ch1,ch2*ch2 + ch3*ch3,ch2*ch2 + ch3*ch3,ch4*ch4 + ch5*ch5,ch4*ch4 + ch5*ch5,ch6*ch6 + ch7*ch7,ch6*ch6 + ch7*ch7]>>output_shift128 on 16-bits\n                mmtmpD0 = vmull_s16(dl_ch0_128[2], dl_ch0_128[2]);\n                mmtmpD0 = vqshlq_s32(vqaddq_s32(mmtmpD0, vrev64q_s32(mmtmpD0)), output_shift128);\n                mmtmpD1 = vmull_s16(dl_ch0_128[3], dl_ch0_128[3]);\n                mmtmpD1 = vqshlq_s32(vqaddq_s32(mmtmpD1, vrev64q_s32(mmtmpD1)), output_shift128);\n                mmtmpD3 = vcombine_s16(vmovn_s32(mmtmpD0), vmovn_s32(mmtmpD1));\n\n                if(pilots == 0)\n                {\n                    mmtmpD0 = vmull_s16(dl_ch0_128[4], dl_ch0_128[4]);\n                    mmtmpD0 = vqshlq_s32(vqaddq_s32(mmtmpD0, vrev64q_s32(mmtmpD0)), output_shift128);\n                    mmtmpD1 = vmull_s16(dl_ch0_128[5], dl_ch0_128[5]);\n                    mmtmpD1 = vqshlq_s32(vqaddq_s32(mmtmpD1, vrev64q_s32(mmtmpD1)), output_shift128);\n                    mmtmpD4 = vcombine_s16(vmovn_s32(mmtmpD0), vmovn_s32(mmtmpD1));\n                }\n\n                dl_ch_mag128b[0] = vqdmulhq_s16(mmtmpD2, QAM_amp128b);\n                dl_ch_mag128b[1] = vqdmulhq_s16(mmtmpD3, QAM_amp128b);\n                dl_ch_mag128[0] = vqdmulhq_s16(mmtmpD2, QAM_amp128);\n                dl_ch_mag128[1] = vqdmulhq_s16(mmtmpD3, QAM_amp128);\n\n                if(pilots == 0)\n                {\n                    dl_ch_mag128b[2] = vqdmulhq_s16(mmtmpD4, QAM_amp128b);\n                    dl_ch_mag128[2]  = vqdmulhq_s16(mmtmpD4, QAM_amp128);\n                }\n            }\n\n            mmtmpD0 = vmull_s16(dl_ch0_128[0], rxdataF128[0]);\n            //mmtmpD0 = [Re(ch[0])Re(rx[0]) Im(ch[0])Im(ch[0]) Re(ch[1])Re(rx[1]) Im(ch[1])Im(ch[1])]\n            mmtmpD1 = vmull_s16(dl_ch0_128[1], rxdataF128[1]);\n            //mmtmpD1 = [Re(ch[2])Re(rx[2]) Im(ch[2])Im(ch[2]) Re(ch[3])Re(rx[3]) Im(ch[3])Im(ch[3])]\n            mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0), vget_high_s32(mmtmpD0)),\n                                   vpadd_s32(vget_low_s32(mmtmpD1), vget_high_s32(mmtmpD1)));\n            //mmtmpD0 = [Re(ch[0])Re(rx[0])+Im(ch[0])Im(ch[0]) Re(ch[1])Re(rx[1])+Im(ch[1])Im(ch[1]) Re(ch[2])Re(rx[2])+Im(ch[2])Im(ch[2]) Re(ch[3])Re(rx[3])+Im(ch[3])Im(ch[3])]\n            mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[0], *(int16x4_t *)conj)), rxdataF128[0]);\n            //mmtmpD0 = [-Im(ch[0])Re(rx[0]) Re(ch[0])Im(rx[0]) -Im(ch[1])Re(rx[1]) Re(ch[1])Im(rx[1])]\n            mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[1], *(int16x4_t *)conj)), rxdataF128[1]);\n            //mmtmpD0 = [-Im(ch[2])Re(rx[2]) Re(ch[2])Im(rx[2]) -Im(ch[3])Re(rx[3]) Re(ch[3])Im(rx[3])]\n            mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b), vget_high_s32(mmtmpD0b)),\n                                   vpadd_s32(vget_low_s32(mmtmpD1b), vget_high_s32(mmtmpD1b)));\n            //mmtmpD1 = [-Im(ch[0])Re(rx[0])+Re(ch[0])Im(rx[0]) -Im(ch[1])Re(rx[1])+Re(ch[1])Im(rx[1]) -Im(ch[2])Re(rx[2])+Re(ch[2])Im(rx[2]) -Im(ch[3])Re(rx[3])+Re(ch[3])Im(rx[3])]\n            mmtmpD0 = vqshlq_s32(mmtmpD0, output_shift128);\n            mmtmpD1 = vqshlq_s32(mmtmpD1, output_shift128);\n            rxdataF_comp128[0] = vcombine_s16(vmovn_s32(mmtmpD0), vmovn_s32(mmtmpD1));\n            mmtmpD0 = vmull_s16(dl_ch0_128[2], rxdataF128[2]);\n            mmtmpD1 = vmull_s16(dl_ch0_128[3], rxdataF128[3]);\n            mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0), vget_high_s32(mmtmpD0)),\n                                   vpadd_s32(vget_low_s32(mmtmpD1), vget_high_s32(mmtmpD1)));\n            mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[2], *(int16x4_t *)conj)), rxdataF128[2]);\n            mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[3], *(int16x4_t *)conj)), rxdataF128[3]);\n            mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b), vget_high_s32(mmtmpD0b)),\n                                   vpadd_s32(vget_low_s32(mmtmpD1b), vget_high_s32(mmtmpD1b)));\n            mmtmpD0 = vqshlq_s32(mmtmpD0, output_shift128);\n            mmtmpD1 = vqshlq_s32(mmtmpD1, output_shift128);\n            rxdataF_comp128[1] = vcombine_s16(vmovn_s32(mmtmpD0), vmovn_s32(mmtmpD1));\n\n            if(pilots == 0)\n            {\n                mmtmpD0 = vmull_s16(dl_ch0_128[4], rxdataF128[4]);\n                mmtmpD1 = vmull_s16(dl_ch0_128[5], rxdataF128[5]);\n                mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0), vget_high_s32(mmtmpD0)),\n                                       vpadd_s32(vget_low_s32(mmtmpD1), vget_high_s32(mmtmpD1)));\n                mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[4], *(int16x4_t *)conj)), rxdataF128[4]);\n                mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[5], *(int16x4_t *)conj)), rxdataF128[5]);\n                mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b), vget_high_s32(mmtmpD0b)),\n                                       vpadd_s32(vget_low_s32(mmtmpD1b), vget_high_s32(mmtmpD1b)));\n                mmtmpD0 = vqshlq_s32(mmtmpD0, output_shift128);\n                mmtmpD1 = vqshlq_s32(mmtmpD1, output_shift128);\n                rxdataF_comp128[2] = vcombine_s16(vmovn_s32(mmtmpD0), vmovn_s32(mmtmpD1));\n                dl_ch0_128 += 6;\n                dl_ch1_128 += 6;\n                dl_ch_mag128 += 3;\n                dl_ch_mag128b += 3;\n                rxdataF128 += 6;\n                rxdataF_comp128 += 3;\n            }\n            else     // we have a smaller PDSCH in symbols with pilots so skip last group of 4 REs and increment less\n            {\n                dl_ch0_128 += 4;\n                dl_ch1_128 += 4;\n                dl_ch_mag128 += 2;\n                dl_ch_mag128b += 2;\n                rxdataF128 += 4;\n                rxdataF_comp128 += 2;\n            }\n        }\n\n        Nre = (pilots == 0) ? 12 : 8;\n        precoded_signal_strength += ((signal_energy_nodc(&dl_ch_estimates_ext[aarx][symbol * frame_parms->N_RB_DL * Nre],\n                                      (nb_rb * Nre))) - (measurements->n0_power[aarx]));\n        // rx_antennas\n    }\n\n    measurements->precoded_cqi_dB[eNB_id][0] = dB_fixed2(precoded_signal_strength, measurements->n0_power_tot);\n    //printf(\"eNB_id %d, symbol %d: precoded CQI %d dB\\n\",eNB_id,symbol,\n    //     measurements->precoded_cqi_dB[eNB_id][0]);\n#endif\n    _mm_empty();\n    _m_empty();\n}\n\nvoid precode_channel_est(int32_t **dl_ch_estimates_ext,\n                         LTE_DL_FRAME_PARMS *frame_parms,\n                         LTE_UE_PDSCH *pdsch_vars,\n                         unsigned char symbol,\n                         unsigned short nb_rb,\n                         MIMO_mode_t mimo_mode)\n{\n    unsigned short rb;\n    __m128i *dl_ch0_128, *dl_ch1_128;\n    unsigned char aarx = 0, symbol_mod, pilots = 0;\n    unsigned char *pmi_ext = pdsch_vars->pmi_ext;\n    symbol_mod = (symbol >= (7 - frame_parms->Ncp)) ? symbol - (7 - frame_parms->Ncp) : symbol;\n\n    if((symbol_mod == 0) || (symbol_mod == (4 - frame_parms->Ncp)))\n    {\n        pilots = 1;\n    }\n\n    for(aarx = 0; aarx < frame_parms->nb_antennas_rx; aarx++)\n    {\n        dl_ch0_128          = (__m128i *)&dl_ch_estimates_ext[aarx][symbol * frame_parms->N_RB_DL * 12]; // this is h11\n        dl_ch1_128          = (__m128i *)&dl_ch_estimates_ext[2 + aarx][symbol * frame_parms->N_RB_DL * 12]; // this is h12\n\n        for(rb = 0; rb < nb_rb; rb++)\n        {\n            if(mimo_mode == LARGE_CDD)\n            {\n                prec2A_TM3_128(&dl_ch0_128[0], &dl_ch1_128[0]);\n                prec2A_TM3_128(&dl_ch0_128[1], &dl_ch1_128[1]);\n\n                if(pilots == 0)\n                {\n                    prec2A_TM3_128(&dl_ch0_128[2], &dl_ch1_128[2]);\n                }\n            }\n            else if(mimo_mode == DUALSTREAM_UNIFORM_PRECODING1)\n            {\n                prec2A_TM4_128(0, &dl_ch0_128[0], &dl_ch1_128[0]);\n                prec2A_TM4_128(0, &dl_ch0_128[1], &dl_ch1_128[1]);\n\n                if(pilots == 0)\n                {\n                    prec2A_TM4_128(0, &dl_ch0_128[2], &dl_ch1_128[2]);\n                }\n            }\n            else if(mimo_mode == DUALSTREAM_UNIFORM_PRECODINGj)\n            {\n                prec2A_TM4_128(1, &dl_ch0_128[0], &dl_ch1_128[0]);\n                prec2A_TM4_128(1, &dl_ch0_128[1], &dl_ch1_128[1]);\n\n                if(pilots == 0)\n                {\n                    prec2A_TM4_128(1, &dl_ch0_128[2], &dl_ch1_128[2]);\n                }\n            }\n            else if(mimo_mode == DUALSTREAM_PUSCH_PRECODING)\n            {\n                prec2A_TM4_128(pmi_ext[rb], &dl_ch0_128[0], &dl_ch1_128[0]);\n                prec2A_TM4_128(pmi_ext[rb], &dl_ch0_128[1], &dl_ch1_128[1]);\n\n                if(pilots == 0)\n                {\n                    prec2A_TM4_128(pmi_ext[rb], &dl_ch0_128[2], &dl_ch1_128[2]);\n                }\n            }\n            else\n            {\n                LOG_E(PHY, \"Unknown MIMO mode\\n\");\n                return;\n            }\n\n            if(pilots == 0)\n            {\n                dl_ch0_128 += 3;\n                dl_ch1_128 += 3;\n            }\n            else\n            {\n                dl_ch0_128 += 2;\n                dl_ch1_128 += 2;\n            }\n        }\n    }\n}\n\nvoid dlsch_channel_compensation_TM34(LTE_DL_FRAME_PARMS *frame_parms,\n                                     LTE_UE_PDSCH *pdsch_vars,\n                                     PHY_MEASUREMENTS *measurements,\n                                     int eNB_id,\n                                     unsigned char symbol,\n                                     unsigned char mod_order0,\n                                     unsigned char mod_order1,\n                                     int harq_pid,\n                                     int round,\n                                     MIMO_mode_t mimo_mode,\n                                     unsigned short nb_rb,\n                                     unsigned short mmse_flag,\n                                     unsigned char output_shift0,\n                                     unsigned char output_shift1)\n{\n#if defined(__x86_64__) || defined(__i386__)\n    unsigned short rb, Nre;\n    __m128i *dl_ch0_128, *dl_ch1_128, *dl_ch_mag0_128, *dl_ch_mag1_128, *dl_ch_mag0_128b, *dl_ch_mag1_128b, *rxdataF128, *rxdataF_comp0_128, *rxdataF_comp1_128;\n    unsigned char aarx = 0, symbol_mod, pilots = 0;\n    int precoded_signal_strength0 = 0, precoded_signal_strength1 = 0;\n    int rx_power_correction;\n    int **rxdataF_ext           = pdsch_vars->rxdataF_ext;\n    int **dl_ch_estimates_ext   = pdsch_vars->dl_ch_estimates_ext;\n    int **dl_ch_mag0            = pdsch_vars->dl_ch_mag0;\n    int **dl_ch_mag1            = pdsch_vars->dl_ch_mag1[harq_pid][round];\n    int **dl_ch_magb0           = pdsch_vars->dl_ch_magb0;\n    int **dl_ch_magb1           = pdsch_vars->dl_ch_magb1[harq_pid][round];\n    int **rxdataF_comp0         = pdsch_vars->rxdataF_comp0;\n    int **rxdataF_comp1         = pdsch_vars->rxdataF_comp1[harq_pid][round];\n    unsigned char *pmi_ext      = pdsch_vars->pmi_ext;\n    __m128i mmtmpD0, mmtmpD1, mmtmpD2, mmtmpD3, QAM_amp0_128, QAM_amp1_128;\n    symbol_mod = (symbol >= (7 - frame_parms->Ncp)) ? symbol - (7 - frame_parms->Ncp) : symbol;\n\n    if((symbol_mod == 0) || (symbol_mod == (4 - frame_parms->Ncp)))\n    {\n        pilots = 1;\n    }\n\n    rx_power_correction = 1;\n    // printf(\"comp prec: symbol %d, pilots %d\\n\",symbol, pilots);\n    __m128i  QAM_amp0_128b = _mm_setzero_si128();\n\n    if(mod_order0 == 4)\n    {\n        QAM_amp0_128  = _mm_set1_epi16(QAM16_n1);\n    }\n    else if(mod_order0 == 6)\n    {\n        QAM_amp0_128  = _mm_set1_epi16(QAM64_n1);\n        QAM_amp0_128b = _mm_set1_epi16(QAM64_n2);\n    }\n\n    __m128i  QAM_amp1_128b = _mm_setzero_si128();\n\n    if(mod_order1 == 4)\n    {\n        QAM_amp1_128  = _mm_set1_epi16(QAM16_n1);\n    }\n    else if(mod_order1 == 6)\n    {\n        QAM_amp1_128  = _mm_set1_epi16(QAM64_n1);\n        QAM_amp1_128b = _mm_set1_epi16(QAM64_n2);\n    }\n\n    for(aarx = 0; aarx < frame_parms->nb_antennas_rx; aarx++)\n    {\n        dl_ch0_128          = (__m128i *)&dl_ch_estimates_ext[aarx][symbol * frame_parms->N_RB_DL * 12]; // this is h11\n        dl_ch1_128          = (__m128i *)&dl_ch_estimates_ext[2 + aarx][symbol * frame_parms->N_RB_DL * 12]; // this is h12\n        dl_ch_mag0_128      = (__m128i *)&dl_ch_mag0[aarx][symbol * frame_parms->N_RB_DL * 12]; //responsible for x1\n        dl_ch_mag0_128b     = (__m128i *)&dl_ch_magb0[aarx][symbol * frame_parms->N_RB_DL * 12]; //responsible for x1\n        dl_ch_mag1_128      = (__m128i *)&dl_ch_mag1[aarx][symbol * frame_parms->N_RB_DL * 12]; //responsible for x2. always coming from tx2\n        dl_ch_mag1_128b     = (__m128i *)&dl_ch_magb1[aarx][symbol * frame_parms->N_RB_DL * 12]; //responsible for x2. always coming from tx2\n        rxdataF128          = (__m128i *)&rxdataF_ext[aarx][symbol * frame_parms->N_RB_DL * 12]; //received signal on antenna of interest h11*x1+h12*x2\n        rxdataF_comp0_128   = (__m128i *)&rxdataF_comp0[aarx][symbol * frame_parms->N_RB_DL * 12]; //result of multipl with MF x1 on antenna of interest\n        rxdataF_comp1_128   = (__m128i *)&rxdataF_comp1[aarx][symbol * frame_parms->N_RB_DL * 12]; //result of multipl with MF x2 on antenna of interest\n\n        for(rb = 0; rb < nb_rb; rb++)\n        {\n            if(mmse_flag == 0)\n            {\n                // combine TX channels using precoder from pmi\n                if(mimo_mode == LARGE_CDD)\n                {\n                    prec2A_TM3_128(&dl_ch0_128[0], &dl_ch1_128[0]);\n                    prec2A_TM3_128(&dl_ch0_128[1], &dl_ch1_128[1]);\n\n                    if(pilots == 0)\n                    {\n                        prec2A_TM3_128(&dl_ch0_128[2], &dl_ch1_128[2]);\n                    }\n                }\n                else if(mimo_mode == DUALSTREAM_UNIFORM_PRECODING1)\n                {\n                    prec2A_TM4_128(0, &dl_ch0_128[0], &dl_ch1_128[0]);\n                    prec2A_TM4_128(0, &dl_ch0_128[1], &dl_ch1_128[1]);\n\n                    if(pilots == 0)\n                    {\n                        prec2A_TM4_128(0, &dl_ch0_128[2], &dl_ch1_128[2]);\n                    }\n                }\n                else if(mimo_mode == DUALSTREAM_UNIFORM_PRECODINGj)\n                {\n                    prec2A_TM4_128(1, &dl_ch0_128[0], &dl_ch1_128[0]);\n                    prec2A_TM4_128(1, &dl_ch0_128[1], &dl_ch1_128[1]);\n\n                    if(pilots == 0)\n                    {\n                        prec2A_TM4_128(1, &dl_ch0_128[2], &dl_ch1_128[2]);\n                    }\n                }\n                else if(mimo_mode == DUALSTREAM_PUSCH_PRECODING)\n                {\n                    prec2A_TM4_128(pmi_ext[rb], &dl_ch0_128[0], &dl_ch1_128[0]);\n                    prec2A_TM4_128(pmi_ext[rb], &dl_ch0_128[1], &dl_ch1_128[1]);\n\n                    if(pilots == 0)\n                    {\n                        prec2A_TM4_128(pmi_ext[rb], &dl_ch0_128[2], &dl_ch1_128[2]);\n                    }\n                }\n                else\n                {\n                    LOG_E(PHY, \"Unknown MIMO mode\\n\");\n                    return;\n                }\n            }\n\n            if(mod_order0 > 2)\n            {\n                // get channel amplitude if not QPSK\n                mmtmpD0 = _mm_madd_epi16(dl_ch0_128[0], dl_ch0_128[0]);\n                mmtmpD0 = _mm_srai_epi32(mmtmpD0, output_shift0);\n                mmtmpD1 = _mm_madd_epi16(dl_ch0_128[1], dl_ch0_128[1]);\n                mmtmpD1 = _mm_srai_epi32(mmtmpD1, output_shift0);\n                mmtmpD0 = _mm_packs_epi32(mmtmpD0, mmtmpD1);\n                dl_ch_mag0_128[0] = _mm_unpacklo_epi16(mmtmpD0, mmtmpD0);\n                dl_ch_mag0_128b[0] = dl_ch_mag0_128[0];\n                dl_ch_mag0_128[0] = _mm_mulhi_epi16(dl_ch_mag0_128[0], QAM_amp0_128);\n                dl_ch_mag0_128[0] = _mm_slli_epi16(dl_ch_mag0_128[0], 1);\n                //  print_shorts(\"dl_ch_mag0_128[0]=\",&dl_ch_mag0_128[0]);\n                dl_ch_mag0_128[1] = _mm_unpackhi_epi16(mmtmpD0, mmtmpD0);\n                dl_ch_mag0_128b[1] = dl_ch_mag0_128[1];\n                dl_ch_mag0_128[1] = _mm_mulhi_epi16(dl_ch_mag0_128[1], QAM_amp0_128);\n                dl_ch_mag0_128[1] = _mm_slli_epi16(dl_ch_mag0_128[1], 1);\n\n                if(pilots == 0)\n                {\n                    mmtmpD0 = _mm_madd_epi16(dl_ch0_128[2], dl_ch0_128[2]);\n                    mmtmpD0 = _mm_srai_epi32(mmtmpD0, output_shift0);\n                    mmtmpD1 = _mm_packs_epi32(mmtmpD0, mmtmpD0);\n                    dl_ch_mag0_128[2] = _mm_unpacklo_epi16(mmtmpD1, mmtmpD1);\n                    dl_ch_mag0_128b[2] = dl_ch_mag0_128[2];\n                    dl_ch_mag0_128[2] = _mm_mulhi_epi16(dl_ch_mag0_128[2], QAM_amp0_128);\n                    dl_ch_mag0_128[2] = _mm_slli_epi16(dl_ch_mag0_128[2], 1);\n                }\n\n                dl_ch_mag0_128b[0] = _mm_mulhi_epi16(dl_ch_mag0_128b[0], QAM_amp0_128b);\n                dl_ch_mag0_128b[0] = _mm_slli_epi16(dl_ch_mag0_128b[0], 1);\n                // print_shorts(\"dl_ch_mag0_128b[0]=\",&dl_ch_mag0_128b[0]);\n                dl_ch_mag0_128b[1] = _mm_mulhi_epi16(dl_ch_mag0_128b[1], QAM_amp0_128b);\n                dl_ch_mag0_128b[1] = _mm_slli_epi16(dl_ch_mag0_128b[1], 1);\n\n                if(pilots == 0)\n                {\n                    dl_ch_mag0_128b[2] = _mm_mulhi_epi16(dl_ch_mag0_128b[2], QAM_amp0_128b);\n                    dl_ch_mag0_128b[2] = _mm_slli_epi16(dl_ch_mag0_128b[2], 1);\n                }\n            }\n\n            if(mod_order1 > 2)\n            {\n                // get channel amplitude if not QPSK\n                mmtmpD0 = _mm_madd_epi16(dl_ch1_128[0], dl_ch1_128[0]);\n                mmtmpD0 = _mm_srai_epi32(mmtmpD0, output_shift1);\n                mmtmpD1 = _mm_madd_epi16(dl_ch1_128[1], dl_ch1_128[1]);\n                mmtmpD1 = _mm_srai_epi32(mmtmpD1, output_shift1);\n                mmtmpD0 = _mm_packs_epi32(mmtmpD0, mmtmpD1);\n                dl_ch_mag1_128[0] = _mm_unpacklo_epi16(mmtmpD0, mmtmpD0);\n                dl_ch_mag1_128b[0] = dl_ch_mag1_128[0];\n                dl_ch_mag1_128[0] = _mm_mulhi_epi16(dl_ch_mag1_128[0], QAM_amp1_128);\n                dl_ch_mag1_128[0] = _mm_slli_epi16(dl_ch_mag1_128[0], 1);\n                // print_shorts(\"dl_ch_mag1_128[0]=\",&dl_ch_mag1_128[0]);\n                dl_ch_mag1_128[1] = _mm_unpackhi_epi16(mmtmpD0, mmtmpD0);\n                dl_ch_mag1_128b[1] = dl_ch_mag1_128[1];\n                dl_ch_mag1_128[1] = _mm_mulhi_epi16(dl_ch_mag1_128[1], QAM_amp1_128);\n                dl_ch_mag1_128[1] = _mm_slli_epi16(dl_ch_mag1_128[1], 1);\n\n                if(pilots == 0)\n                {\n                    mmtmpD0 = _mm_madd_epi16(dl_ch1_128[2], dl_ch1_128[2]);\n                    mmtmpD0 = _mm_srai_epi32(mmtmpD0, output_shift1);\n                    mmtmpD1 = _mm_packs_epi32(mmtmpD0, mmtmpD0);\n                    dl_ch_mag1_128[2] = _mm_unpacklo_epi16(mmtmpD1, mmtmpD1);\n                    dl_ch_mag1_128b[2] = dl_ch_mag1_128[2];\n                    dl_ch_mag1_128[2] = _mm_mulhi_epi16(dl_ch_mag1_128[2], QAM_amp1_128);\n                    dl_ch_mag1_128[2] = _mm_slli_epi16(dl_ch_mag1_128[2], 1);\n                }\n\n                dl_ch_mag1_128b[0] = _mm_mulhi_epi16(dl_ch_mag1_128b[0], QAM_amp1_128b);\n                dl_ch_mag1_128b[0] = _mm_slli_epi16(dl_ch_mag1_128b[0], 1);\n                // print_shorts(\"dl_ch_mag1_128b[0]=\",&dl_ch_mag1_128b[0]);\n                dl_ch_mag1_128b[1] = _mm_mulhi_epi16(dl_ch_mag1_128b[1], QAM_amp1_128b);\n                dl_ch_mag1_128b[1] = _mm_slli_epi16(dl_ch_mag1_128b[1], 1);\n\n                if(pilots == 0)\n                {\n                    dl_ch_mag1_128b[2] = _mm_mulhi_epi16(dl_ch_mag1_128b[2], QAM_amp1_128b);\n                    dl_ch_mag1_128b[2] = _mm_slli_epi16(dl_ch_mag1_128b[2], 1);\n                }\n            }\n\n            // layer 0\n            // MF multiply by conjugated channel\n            mmtmpD0 = _mm_madd_epi16(dl_ch0_128[0], rxdataF128[0]);\n            //  print_ints(\"re\",&mmtmpD0);\n            // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n            mmtmpD1 = _mm_shufflelo_epi16(dl_ch0_128[0], _MM_SHUFFLE(2, 3, 0, 1));\n            mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1, _MM_SHUFFLE(2, 3, 0, 1));\n            mmtmpD1 = _mm_sign_epi16(mmtmpD1, *(__m128i *)&conjugate[0]);\n            mmtmpD1 = _mm_madd_epi16(mmtmpD1, rxdataF128[0]);\n            // print_ints(\"im\",&mmtmpD1);\n            // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n            mmtmpD0 = _mm_srai_epi32(mmtmpD0, output_shift0);\n            // printf(\"Shift: %d\\n\",output_shift);\n            // print_ints(\"re(shift)\",&mmtmpD0);\n            mmtmpD1 = _mm_srai_epi32(mmtmpD1, output_shift0);\n            // print_ints(\"im(shift)\",&mmtmpD1);\n            mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0, mmtmpD1);\n            mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0, mmtmpD1);\n            //  print_ints(\"c0\",&mmtmpD2);\n            // print_ints(\"c1\",&mmtmpD3);\n            rxdataF_comp0_128[0] = _mm_packs_epi32(mmtmpD2, mmtmpD3);\n            // print_shorts(\"rx:\",rxdataF128);\n            // print_shorts(\"ch:\",dl_ch0_128);\n            //print_shorts(\"pack:\",rxdataF_comp0_128);\n            // multiply by conjugated channel\n            mmtmpD0 = _mm_madd_epi16(dl_ch0_128[1], rxdataF128[1]);\n            // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n            mmtmpD1 = _mm_shufflelo_epi16(dl_ch0_128[1], _MM_SHUFFLE(2, 3, 0, 1));\n            mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1, _MM_SHUFFLE(2, 3, 0, 1));\n            mmtmpD1 = _mm_sign_epi16(mmtmpD1, *(__m128i *)conjugate);\n            mmtmpD1 = _mm_madd_epi16(mmtmpD1, rxdataF128[1]);\n            // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n            mmtmpD0 = _mm_srai_epi32(mmtmpD0, output_shift0);\n            mmtmpD1 = _mm_srai_epi32(mmtmpD1, output_shift0);\n            mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0, mmtmpD1);\n            mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0, mmtmpD1);\n            rxdataF_comp0_128[1] = _mm_packs_epi32(mmtmpD2, mmtmpD3);\n            //  print_shorts(\"rx:\",rxdataF128+1);\n            //  print_shorts(\"ch:\",dl_ch0_128+1);\n            // print_shorts(\"pack:\",rxdataF_comp0_128+1);\n\n            if(pilots == 0)\n            {\n                // multiply by conjugated channel\n                mmtmpD0 = _mm_madd_epi16(dl_ch0_128[2], rxdataF128[2]);\n                // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n                mmtmpD1 = _mm_shufflelo_epi16(dl_ch0_128[2], _MM_SHUFFLE(2, 3, 0, 1));\n                mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1, _MM_SHUFFLE(2, 3, 0, 1));\n                mmtmpD1 = _mm_sign_epi16(mmtmpD1, *(__m128i *)conjugate);\n                mmtmpD1 = _mm_madd_epi16(mmtmpD1, rxdataF128[2]);\n                // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n                mmtmpD0 = _mm_srai_epi32(mmtmpD0, output_shift0);\n                mmtmpD1 = _mm_srai_epi32(mmtmpD1, output_shift0);\n                mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0, mmtmpD1);\n                mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0, mmtmpD1);\n                rxdataF_comp0_128[2] = _mm_packs_epi32(mmtmpD2, mmtmpD3);\n                //   print_shorts(\"rx:\",rxdataF128+2);\n                //   print_shorts(\"ch:\",dl_ch0_128+2);\n                //  print_shorts(\"pack:\",rxdataF_comp0_128+2);\n            }\n\n            // layer 1\n            // MF multiply by conjugated channel\n            mmtmpD0 = _mm_madd_epi16(dl_ch1_128[0], rxdataF128[0]);\n            //  print_ints(\"re\",&mmtmpD0);\n            // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n            mmtmpD1 = _mm_shufflelo_epi16(dl_ch1_128[0], _MM_SHUFFLE(2, 3, 0, 1));\n            mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1, _MM_SHUFFLE(2, 3, 0, 1));\n            mmtmpD1 = _mm_sign_epi16(mmtmpD1, *(__m128i *)&conjugate[0]);\n            //  print_ints(\"im\",&mmtmpD1);\n            mmtmpD1 = _mm_madd_epi16(mmtmpD1, rxdataF128[0]);\n            // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n            mmtmpD0 = _mm_srai_epi32(mmtmpD0, output_shift1);\n            // print_ints(\"re(shift)\",&mmtmpD0);\n            mmtmpD1 = _mm_srai_epi32(mmtmpD1, output_shift1);\n            // print_ints(\"im(shift)\",&mmtmpD1);\n            mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0, mmtmpD1);\n            mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0, mmtmpD1);\n            // print_ints(\"c0\",&mmtmpD2);\n            // print_ints(\"c1\",&mmtmpD3);\n            rxdataF_comp1_128[0] = _mm_packs_epi32(mmtmpD2, mmtmpD3);\n            // print_shorts(\"rx:\",rxdataF128);\n            //  print_shorts(\"ch:\",dl_ch1_128);\n            // print_shorts(\"pack:\",rxdataF_comp1_128);\n            // multiply by conjugated channel\n            mmtmpD0 = _mm_madd_epi16(dl_ch1_128[1], rxdataF128[1]);\n            // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n            mmtmpD1 = _mm_shufflelo_epi16(dl_ch1_128[1], _MM_SHUFFLE(2, 3, 0, 1));\n            mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1, _MM_SHUFFLE(2, 3, 0, 1));\n            mmtmpD1 = _mm_sign_epi16(mmtmpD1, *(__m128i *)conjugate);\n            mmtmpD1 = _mm_madd_epi16(mmtmpD1, rxdataF128[1]);\n            // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n            mmtmpD0 = _mm_srai_epi32(mmtmpD0, output_shift1);\n            mmtmpD1 = _mm_srai_epi32(mmtmpD1, output_shift1);\n            mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0, mmtmpD1);\n            mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0, mmtmpD1);\n            rxdataF_comp1_128[1] = _mm_packs_epi32(mmtmpD2, mmtmpD3);\n            //  print_shorts(\"rx:\",rxdataF128+1);\n            // print_shorts(\"ch:\",dl_ch1_128+1);\n            // print_shorts(\"pack:\",rxdataF_comp1_128+1);\n\n            if(pilots == 0)\n            {\n                // multiply by conjugated channel\n                mmtmpD0 = _mm_madd_epi16(dl_ch1_128[2], rxdataF128[2]);\n                // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n                mmtmpD1 = _mm_shufflelo_epi16(dl_ch1_128[2], _MM_SHUFFLE(2, 3, 0, 1));\n                mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1, _MM_SHUFFLE(2, 3, 0, 1));\n                mmtmpD1 = _mm_sign_epi16(mmtmpD1, *(__m128i *)conjugate);\n                mmtmpD1 = _mm_madd_epi16(mmtmpD1, rxdataF128[2]);\n                // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n                mmtmpD0 = _mm_srai_epi32(mmtmpD0, output_shift1);\n                mmtmpD1 = _mm_srai_epi32(mmtmpD1, output_shift1);\n                mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0, mmtmpD1);\n                mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0, mmtmpD1);\n                rxdataF_comp1_128[2] = _mm_packs_epi32(mmtmpD2, mmtmpD3);\n                //   print_shorts(\"rx:\",rxdataF128+2);\n                //  print_shorts(\"ch:\",dl_ch1_128+2);\n                //         print_shorts(\"pack:\",rxdataF_comp1_128+2);\n                dl_ch0_128 += 3;\n                dl_ch1_128 += 3;\n                dl_ch_mag0_128 += 3;\n                dl_ch_mag1_128 += 3;\n                dl_ch_mag0_128b += 3;\n                dl_ch_mag1_128b += 3;\n                rxdataF128 += 3;\n                rxdataF_comp0_128 += 3;\n                rxdataF_comp1_128 += 3;\n            }\n            else\n            {\n                dl_ch0_128 += 2;\n                dl_ch1_128 += 2;\n                dl_ch_mag0_128 += 2;\n                dl_ch_mag1_128 += 2;\n                dl_ch_mag0_128b += 2;\n                dl_ch_mag1_128b += 2;\n                rxdataF128 += 2;\n                rxdataF_comp0_128 += 2;\n                rxdataF_comp1_128 += 2;\n            }\n        } // rb loop\n\n        Nre = (pilots == 0) ? 12 : 8;\n        precoded_signal_strength0 += ((signal_energy_nodc(&dl_ch_estimates_ext[aarx][symbol * frame_parms->N_RB_DL * Nre],\n                                       (nb_rb * Nre)) * rx_power_correction) - (measurements->n0_power[aarx]));\n        precoded_signal_strength1 += ((signal_energy_nodc(&dl_ch_estimates_ext[aarx + 2][symbol * frame_parms->N_RB_DL * Nre],\n                                       (nb_rb * Nre)) * rx_power_correction) - (measurements->n0_power[aarx]));\n    } // rx_antennas\n\n    measurements->precoded_cqi_dB[eNB_id][0] = dB_fixed2(precoded_signal_strength0, measurements->n0_power_tot);\n    measurements->precoded_cqi_dB[eNB_id][1] = dB_fixed2(precoded_signal_strength1, measurements->n0_power_tot);\n    // printf(\"eNB_id %d, symbol %d: precoded CQI %d dB\\n\",eNB_id,symbol,\n    //  measurements->precoded_cqi_dB[eNB_id][0]);\n    _mm_empty();\n    _m_empty();\n#elif defined(__arm__)\n    unsigned short rb, Nre;\n    unsigned char aarx, symbol_mod, pilots = 0;\n    int precoded_signal_strength0 = 0, precoded_signal_strength1 = 0, rx_power_correction;\n    int16x4_t *dl_ch0_128, *rxdataF128;\n    int16x4_t *dl_ch1_128;\n    int16x8_t *dl_ch0_128b, *dl_ch1_128b;\n    int32x4_t mmtmpD0, mmtmpD1, mmtmpD0b, mmtmpD1b;\n    int16x8_t *dl_ch_mag0_128, *dl_ch_mag0_128b, *dl_ch_mag1_128, *dl_ch_mag1_128b, mmtmpD2, mmtmpD3, mmtmpD4, *rxdataF_comp0_128, *rxdataF_comp1_128;\n    int16x8_t QAM_amp0_128, QAM_amp0_128b, QAM_amp1_128, QAM_amp1_128b;\n    int32x4_t output_shift128 = vmovq_n_s32(-(int32_t)output_shift);\n    int **rxdataF_ext           = pdsch_vars->rxdataF_ext;\n    int **dl_ch_estimates_ext   = pdsch_vars->dl_ch_estimates_ext;\n    int **dl_ch_mag0            = pdsch_vars->dl_ch_mag0;\n    int **dl_ch_mag1            = pdsch_vars->dl_ch_mag1[harq_pid][round];\n    int **dl_ch_magb0           = pdsch_vars->dl_ch_magb0;\n    int **dl_ch_magb1           = pdsch_vars->dl_ch_magb1[harq_pid][round];\n    int **rxdataF_comp0         = pdsch_vars->rxdataF_comp0;\n    int **rxdataF_comp1         = pdsch_vars->rxdataF_comp1[harq_pid][round];\n    int16_t conj[4]__attribute__((aligned(16))) = {1, -1, 1, -1};\n    symbol_mod = (symbol >= (7 - frame_parms->Ncp)) ? symbol - (7 - frame_parms->Ncp) : symbol;\n\n    if((symbol_mod == 0) || (symbol_mod == (4 - frame_parms->Ncp)))\n    {\n        if(frame_parms->nb_antenna_ports_eNB == 1)  // 10 out of 12 so don't reduce size\n        {\n            nb_rb = 1 + (5 * nb_rb / 6);\n        }\n        else\n        {\n            pilots = 1;\n        }\n    }\n\n    rx_power_correction = 1;\n\n    if(mod_order0 == 4)\n    {\n        QAM_amp0_128  = vmovq_n_s16(QAM16_n1);  // 2/sqrt(10)\n        QAM_amp0_128b = vmovq_n_s16(0);\n    }\n    else if(mod_order0 == 6)\n    {\n        QAM_amp0_128  = vmovq_n_s16(QAM64_n1); //\n        QAM_amp0_128b = vmovq_n_s16(QAM64_n2);\n    }\n\n    if(mod_order1 == 4)\n    {\n        QAM_amp1_128  = vmovq_n_s16(QAM16_n1);  // 2/sqrt(10)\n        QAM_amp1_128b = vmovq_n_s16(0);\n    }\n    else if(mod_order1 == 6)\n    {\n        QAM_amp1_128  = vmovq_n_s16(QAM64_n1); //\n        QAM_amp1_128b = vmovq_n_s16(QAM64_n2);\n    }\n\n    //    printf(\"comp: rxdataF_comp %p, symbol %d\\n\",rxdataF_comp[0],symbol);\n\n    for(aarx = 0; aarx < frame_parms->nb_antennas_rx; aarx++)\n    {\n        dl_ch0_128          = (int16x4_t *)&dl_ch_estimates_ext[aarx][symbol * frame_parms->N_RB_DL * 12];\n        dl_ch1_128          = (int16x4_t *)&dl_ch_estimates_ext[2 + aarx][symbol * frame_parms->N_RB_DL * 12];\n        dl_ch0_128b          = (int16x8_t *)&dl_ch_estimates_ext[aarx][symbol * frame_parms->N_RB_DL * 12];\n        dl_ch1_128b          = (int16x8_t *)&dl_ch_estimates_ext[2 + aarx][symbol * frame_parms->N_RB_DL * 12];\n        dl_ch_mag0_128      = (int16x8_t *)&dl_ch_mag0[aarx][symbol * frame_parms->N_RB_DL * 12];\n        dl_ch_mag0_128b     = (int16x8_t *)&dl_ch_magb0[aarx][symbol * frame_parms->N_RB_DL * 12];\n        dl_ch_mag1_128      = (int16x8_t *)&dl_ch_mag1[aarx][symbol * frame_parms->N_RB_DL * 12];\n        dl_ch_mag1_128b     = (int16x8_t *)&dl_ch_magb1[aarx][symbol * frame_parms->N_RB_DL * 12];\n        rxdataF128          = (int16x4_t *)&rxdataF_ext[aarx][symbol * frame_parms->N_RB_DL * 12];\n        rxdataF_comp0_128   = (int16x8_t *)&rxdataF_comp0[aarx][symbol * frame_parms->N_RB_DL * 12];\n        rxdataF_comp1_128   = (int16x8_t *)&rxdataF_comp1[aarx][symbol * frame_parms->N_RB_DL * 12];\n\n        for(rb = 0; rb < nb_rb; rb++)\n        {\n            if(mmse_flag == 0)\n            {\n                // combine TX channels using precoder from pmi\n                if(mimo_mode == LARGE_CDD)\n                {\n                    prec2A_TM3_128(&dl_ch0_128[0], &dl_ch1_128[0]);\n                    prec2A_TM3_128(&dl_ch0_128[1], &dl_ch1_128[1]);\n\n                    if(pilots == 0)\n                    {\n                        prec2A_TM3_128(&dl_ch0_128[2], &dl_ch1_128[2]);\n                    }\n                }\n                else if(mimo_mode == DUALSTREAM_UNIFORM_PRECODING1)\n                {\n                    prec2A_TM4_128(0, &dl_ch0_128[0], &dl_ch1_128[0]);\n                    prec2A_TM4_128(0, &dl_ch0_128[1], &dl_ch1_128[1]);\n\n                    if(pilots == 0)\n                    {\n                        prec2A_TM4_128(0, &dl_ch0_128[2], &dl_ch1_128[2]);\n                    }\n                }\n                else if(mimo_mode == DUALSTREAM_UNIFORM_PRECODINGj)\n                {\n                    prec2A_TM4_128(1, &dl_ch0_128[0], &dl_ch1_128[0]);\n                    prec2A_TM4_128(1, &dl_ch0_128[1], &dl_ch1_128[1]);\n\n                    if(pilots == 0)\n                    {\n                        prec2A_TM4_128(1, &dl_ch0_128[2], &dl_ch1_128[2]);\n                    }\n                }\n                else\n                {\n                    LOG_E(PHY, \"Unknown MIMO mode\\n\");\n                    return;\n                }\n            }\n\n            if(mod_order0 > 2)\n            {\n                // get channel amplitude if not QPSK\n                mmtmpD0 = vmull_s16(dl_ch0_128[0], dl_ch0_128[0]);\n                // mmtmpD0 = [ch0*ch0,ch1*ch1,ch2*ch2,ch3*ch3];\n                mmtmpD0 = vqshlq_s32(vqaddq_s32(mmtmpD0, vrev64q_s32(mmtmpD0)), output_shift128);\n                // mmtmpD0 = [ch0*ch0 + ch1*ch1,ch0*ch0 + ch1*ch1,ch2*ch2 + ch3*ch3,ch2*ch2 + ch3*ch3]>>output_shift128 on 32-bits\n                mmtmpD1 = vmull_s16(dl_ch0_128[1], dl_ch0_128[1]);\n                mmtmpD1 = vqshlq_s32(vqaddq_s32(mmtmpD1, vrev64q_s32(mmtmpD1)), output_shift128);\n                mmtmpD2 = vcombine_s16(vmovn_s32(mmtmpD0), vmovn_s32(mmtmpD1));\n                // mmtmpD2 = [ch0*ch0 + ch1*ch1,ch0*ch0 + ch1*ch1,ch2*ch2 + ch3*ch3,ch2*ch2 + ch3*ch3,ch4*ch4 + ch5*ch5,ch4*ch4 + ch5*ch5,ch6*ch6 + ch7*ch7,ch6*ch6 + ch7*ch7]>>output_shift128 on 16-bits\n                mmtmpD0 = vmull_s16(dl_ch0_128[2], dl_ch0_128[2]);\n                mmtmpD0 = vqshlq_s32(vqaddq_s32(mmtmpD0, vrev64q_s32(mmtmpD0)), output_shift128);\n                mmtmpD1 = vmull_s16(dl_ch0_128[3], dl_ch0_128[3]);\n                mmtmpD1 = vqshlq_s32(vqaddq_s32(mmtmpD1, vrev64q_s32(mmtmpD1)), output_shift128);\n                mmtmpD3 = vcombine_s16(vmovn_s32(mmtmpD0), vmovn_s32(mmtmpD1));\n\n                if(pilots == 0)\n                {\n                    mmtmpD0 = vmull_s16(dl_ch0_128[4], dl_ch0_128[4]);\n                    mmtmpD0 = vqshlq_s32(vqaddq_s32(mmtmpD0, vrev64q_s32(mmtmpD0)), output_shift128);\n                    mmtmpD1 = vmull_s16(dl_ch0_128[5], dl_ch0_128[5]);\n                    mmtmpD1 = vqshlq_s32(vqaddq_s32(mmtmpD1, vrev64q_s32(mmtmpD1)), output_shift128);\n                    mmtmpD4 = vcombine_s16(vmovn_s32(mmtmpD0), vmovn_s32(mmtmpD1));\n                }\n\n                dl_ch_mag0_128b[0] = vqdmulhq_s16(mmtmpD2, QAM_amp0_128b);\n                dl_ch_mag0_128b[1] = vqdmulhq_s16(mmtmpD3, QAM_amp0_128b);\n                dl_ch_mag0_128[0] = vqdmulhq_s16(mmtmpD2, QAM_amp0_128);\n                dl_ch_mag0_128[1] = vqdmulhq_s16(mmtmpD3, QAM_amp0_128);\n\n                if(pilots == 0)\n                {\n                    dl_ch_mag0_128b[2] = vqdmulhq_s16(mmtmpD4, QAM_amp0_128b);\n                    dl_ch_mag0_128[2]  = vqdmulhq_s16(mmtmpD4, QAM_amp0_128);\n                }\n            }\n\n            if(mod_order1 > 2)\n            {\n                // get channel amplitude if not QPSK\n                mmtmpD0 = vmull_s16(dl_ch1_128[0], dl_ch1_128[0]);\n                // mmtmpD0 = [ch0*ch0,ch1*ch1,ch2*ch2,ch3*ch3];\n                mmtmpD0 = vqshlq_s32(vqaddq_s32(mmtmpD0, vrev64q_s32(mmtmpD0)), output_shift128);\n                // mmtmpD0 = [ch0*ch0 + ch1*ch1,ch0*ch0 + ch1*ch1,ch2*ch2 + ch3*ch3,ch2*ch2 + ch3*ch3]>>output_shift128 on 32-bits\n                mmtmpD1 = vmull_s16(dl_ch1_128[1], dl_ch1_128[1]);\n                mmtmpD1 = vqshlq_s32(vqaddq_s32(mmtmpD1, vrev64q_s32(mmtmpD1)), output_shift128);\n                mmtmpD2 = vcombine_s16(vmovn_s32(mmtmpD0), vmovn_s32(mmtmpD1));\n                // mmtmpD2 = [ch0*ch0 + ch1*ch1,ch0*ch0 + ch1*ch1,ch2*ch2 + ch3*ch3,ch2*ch2 + ch3*ch3,ch4*ch4 + ch5*ch5,ch4*ch4 + ch5*ch5,ch6*ch6 + ch7*ch7,ch6*ch6 + ch7*ch7]>>output_shift128 on 16-bits\n                mmtmpD0 = vmull_s16(dl_ch1_128[2], dl_ch1_128[2]);\n                mmtmpD0 = vqshlq_s32(vqaddq_s32(mmtmpD0, vrev64q_s32(mmtmpD0)), output_shift128);\n                mmtmpD1 = vmull_s16(dl_ch1_128[3], dl_ch1_128[3]);\n                mmtmpD1 = vqshlq_s32(vqaddq_s32(mmtmpD1, vrev64q_s32(mmtmpD1)), output_shift128);\n                mmtmpD3 = vcombine_s16(vmovn_s32(mmtmpD0), vmovn_s32(mmtmpD1));\n\n                if(pilots == 0)\n                {\n                    mmtmpD0 = vmull_s16(dl_ch1_128[4], dl_ch1_128[4]);\n                    mmtmpD0 = vqshlq_s32(vqaddq_s32(mmtmpD0, vrev64q_s32(mmtmpD0)), output_shift128);\n                    mmtmpD1 = vmull_s16(dl_ch1_128[5], dl_ch1_128[5]);\n                    mmtmpD1 = vqshlq_s32(vqaddq_s32(mmtmpD1, vrev64q_s32(mmtmpD1)), output_shift128);\n                    mmtmpD4 = vcombine_s16(vmovn_s32(mmtmpD0), vmovn_s32(mmtmpD1));\n                }\n\n                dl_ch_mag1_128b[0] = vqdmulhq_s16(mmtmpD2, QAM_amp1_128b);\n                dl_ch_mag1_128b[1] = vqdmulhq_s16(mmtmpD3, QAM_amp1_128b);\n                dl_ch_mag1_128[0] = vqdmulhq_s16(mmtmpD2, QAM_amp1_128);\n                dl_ch_mag1_128[1] = vqdmulhq_s16(mmtmpD3, QAM_amp1_128);\n\n                if(pilots == 0)\n                {\n                    dl_ch_mag1_128b[2] = vqdmulhq_s16(mmtmpD4, QAM_amp1_128b);\n                    dl_ch_mag1_128[2]  = vqdmulhq_s16(mmtmpD4, QAM_amp1_128);\n                }\n            }\n\n            mmtmpD0 = vmull_s16(dl_ch0_128[0], rxdataF128[0]);\n            //mmtmpD0 = [Re(ch[0])Re(rx[0]) Im(ch[0])Im(ch[0]) Re(ch[1])Re(rx[1]) Im(ch[1])Im(ch[1])]\n            mmtmpD1 = vmull_s16(dl_ch0_128[1], rxdataF128[1]);\n            //mmtmpD1 = [Re(ch[2])Re(rx[2]) Im(ch[2])Im(ch[2]) Re(ch[3])Re(rx[3]) Im(ch[3])Im(ch[3])]\n            mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0), vget_high_s32(mmtmpD0)),\n                                   vpadd_s32(vget_low_s32(mmtmpD1), vget_high_s32(mmtmpD1)));\n            //mmtmpD0 = [Re(ch[0])Re(rx[0])+Im(ch[0])Im(ch[0]) Re(ch[1])Re(rx[1])+Im(ch[1])Im(ch[1]) Re(ch[2])Re(rx[2])+Im(ch[2])Im(ch[2]) Re(ch[3])Re(rx[3])+Im(ch[3])Im(ch[3])]\n            mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[0], *(int16x4_t *)conj)), rxdataF128[0]);\n            //mmtmpD0 = [-Im(ch[0])Re(rx[0]) Re(ch[0])Im(rx[0]) -Im(ch[1])Re(rx[1]) Re(ch[1])Im(rx[1])]\n            mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[1], *(int16x4_t *)conj)), rxdataF128[1]);\n            //mmtmpD0 = [-Im(ch[2])Re(rx[2]) Re(ch[2])Im(rx[2]) -Im(ch[3])Re(rx[3]) Re(ch[3])Im(rx[3])]\n            mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b), vget_high_s32(mmtmpD0b)),\n                                   vpadd_s32(vget_low_s32(mmtmpD1b), vget_high_s32(mmtmpD1b)));\n            //mmtmpD1 = [-Im(ch[0])Re(rx[0])+Re(ch[0])Im(rx[0]) -Im(ch[1])Re(rx[1])+Re(ch[1])Im(rx[1]) -Im(ch[2])Re(rx[2])+Re(ch[2])Im(rx[2]) -Im(ch[3])Re(rx[3])+Re(ch[3])Im(rx[3])]\n            mmtmpD0 = vqshlq_s32(mmtmpD0, output_shift128);\n            mmtmpD1 = vqshlq_s32(mmtmpD1, output_shift128);\n            rxdataF_comp0_128[0] = vcombine_s16(vmovn_s32(mmtmpD0), vmovn_s32(mmtmpD1));\n            mmtmpD0 = vmull_s16(dl_ch0_128[2], rxdataF128[2]);\n            mmtmpD1 = vmull_s16(dl_ch0_128[3], rxdataF128[3]);\n            mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0), vget_high_s32(mmtmpD0)),\n                                   vpadd_s32(vget_low_s32(mmtmpD1), vget_high_s32(mmtmpD1)));\n            mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[2], *(int16x4_t *)conj)), rxdataF128[2]);\n            mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[3], *(int16x4_t *)conj)), rxdataF128[3]);\n            mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b), vget_high_s32(mmtmpD0b)),\n                                   vpadd_s32(vget_low_s32(mmtmpD1b), vget_high_s32(mmtmpD1b)));\n            mmtmpD0 = vqshlq_s32(mmtmpD0, output_shift128);\n            mmtmpD1 = vqshlq_s32(mmtmpD1, output_shift128);\n            rxdataF_comp0_128[1] = vcombine_s16(vmovn_s32(mmtmpD0), vmovn_s32(mmtmpD1));\n            // second stream\n            mmtmpD0 = vmull_s16(dl_ch1_128[0], rxdataF128[0]);\n            mmtmpD1 = vmull_s16(dl_ch1_128[1], rxdataF128[1]);\n            mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0), vget_high_s32(mmtmpD0)),\n                                   vpadd_s32(vget_low_s32(mmtmpD1), vget_high_s32(mmtmpD1)));\n            mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[0], *(int16x4_t *)conj)), rxdataF128[0]);\n            mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[1], *(int16x4_t *)conj)), rxdataF128[1]);\n            //mmtmpD0 = [-Im(ch[2])Re(rx[2]) Re(ch[2])Im(rx[2]) -Im(ch[3])Re(rx[3]) Re(ch[3])Im(rx[3])]\n            mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b), vget_high_s32(mmtmpD0b)),\n                                   vpadd_s32(vget_low_s32(mmtmpD1b), vget_high_s32(mmtmpD1b)));\n            //mmtmpD1 = [-Im(ch[0])Re(rx[0])+Re(ch[0])Im(rx[0]) -Im(ch[1])Re(rx[1])+Re(ch[1])Im(rx[1]) -Im(ch[2])Re(rx[2])+Re(ch[2])Im(rx[2]) -Im(ch[3])Re(rx[3])+Re(ch[3])Im(rx[3])]\n            mmtmpD0 = vqshlq_s32(mmtmpD0, output_shift128);\n            mmtmpD1 = vqshlq_s32(mmtmpD1, output_shift128);\n            rxdataF_comp1_128[0] = vcombine_s16(vmovn_s32(mmtmpD0), vmovn_s32(mmtmpD1));\n            mmtmpD0 = vmull_s16(dl_ch1_128[2], rxdataF128[2]);\n            mmtmpD1 = vmull_s16(dl_ch1_128[3], rxdataF128[3]);\n            mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0), vget_high_s32(mmtmpD0)),\n                                   vpadd_s32(vget_low_s32(mmtmpD1), vget_high_s32(mmtmpD1)));\n            mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[2], *(int16x4_t *)conj)), rxdataF128[2]);\n            mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[3], *(int16x4_t *)conj)), rxdataF128[3]);\n            mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b), vget_high_s32(mmtmpD0b)),\n                                   vpadd_s32(vget_low_s32(mmtmpD1b), vget_high_s32(mmtmpD1b)));\n            mmtmpD0 = vqshlq_s32(mmtmpD0, output_shift128);\n            mmtmpD1 = vqshlq_s32(mmtmpD1, output_shift128);\n            rxdataF_comp1_128[1] = vcombine_s16(vmovn_s32(mmtmpD0), vmovn_s32(mmtmpD1));\n\n            if(pilots == 0)\n            {\n                mmtmpD0 = vmull_s16(dl_ch0_128[4], rxdataF128[4]);\n                mmtmpD1 = vmull_s16(dl_ch0_128[5], rxdataF128[5]);\n                mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0), vget_high_s32(mmtmpD0)),\n                                       vpadd_s32(vget_low_s32(mmtmpD1), vget_high_s32(mmtmpD1)));\n                mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[4], *(int16x4_t *)conj)), rxdataF128[4]);\n                mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[5], *(int16x4_t *)conj)), rxdataF128[5]);\n                mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b), vget_high_s32(mmtmpD0b)),\n                                       vpadd_s32(vget_low_s32(mmtmpD1b), vget_high_s32(mmtmpD1b)));\n                mmtmpD0 = vqshlq_s32(mmtmpD0, output_shift128);\n                mmtmpD1 = vqshlq_s32(mmtmpD1, output_shift128);\n                rxdataF_comp0_128[2] = vcombine_s16(vmovn_s32(mmtmpD0), vmovn_s32(mmtmpD1));\n                mmtmpD0 = vmull_s16(dl_ch1_128[4], rxdataF128[4]);\n                mmtmpD1 = vmull_s16(dl_ch1_128[5], rxdataF128[5]);\n                mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0), vget_high_s32(mmtmpD0)),\n                                       vpadd_s32(vget_low_s32(mmtmpD1), vget_high_s32(mmtmpD1)));\n                mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch1_128[4], *(int16x4_t *)conj)), rxdataF128[4]);\n                mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch1_128[5], *(int16x4_t *)conj)), rxdataF128[5]);\n                mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b), vget_high_s32(mmtmpD0b)),\n                                       vpadd_s32(vget_low_s32(mmtmpD1b), vget_high_s32(mmtmpD1b)));\n                mmtmpD0 = vqshlq_s32(mmtmpD0, output_shift128);\n                mmtmpD1 = vqshlq_s32(mmtmpD1, output_shift128);\n                rxdataF_comp1_128[2] = vcombine_s16(vmovn_s32(mmtmpD0), vmovn_s32(mmtmpD1));\n            }\n        }\n\n        Nre = (pilots == 0) ? 12 : 8;\n        // rx_antennas\n    }\n\n    Nre = (pilots == 0) ? 12 : 8;\n    precoded_signal_strength0 += ((signal_energy_nodc(&dl_ch_estimates_ext[aarx][symbol * frame_parms->N_RB_DL * Nre],\n                                   (nb_rb * Nre)) * rx_power_correction) - (measurements->n0_power[aarx]));\n    precoded_signal_strength1 += ((signal_energy_nodc(&dl_ch_estimates_ext[aarx + 2][symbol * frame_parms->N_RB_DL * Nre],\n                                   (nb_rb * Nre)) * rx_power_correction) - (measurements->n0_power[aarx]));\n    measurements->precoded_cqi_dB[eNB_id][0] = dB_fixed2(precoded_signal_strength0, measurements->n0_power_tot);\n    measurements->precoded_cqi_dB[eNB_id][1] = dB_fixed2(precoded_signal_strength1, measurements->n0_power_tot);\n#endif\n}\n\n\nvoid dlsch_dual_stream_correlation(LTE_DL_FRAME_PARMS *frame_parms,\n                                   unsigned char symbol,\n                                   unsigned short nb_rb,\n                                   int **dl_ch_estimates_ext,\n                                   int **dl_ch_estimates_ext_i,\n                                   int **dl_ch_rho_ext,\n                                   unsigned char output_shift)\n{\n#if defined(__x86_64__)||defined(__i386__)\n    unsigned short rb;\n    __m128i *dl_ch128, *dl_ch128i, *dl_ch_rho128, mmtmpD0, mmtmpD1, mmtmpD2, mmtmpD3;\n    unsigned char aarx, symbol_mod, pilots = 0;\n    //    printf(\"dlsch_dual_stream_correlation: symbol %d\\n\",symbol);\n    symbol_mod = (symbol >= (7 - frame_parms->Ncp)) ? symbol - (7 - frame_parms->Ncp) : symbol;\n\n    if((symbol_mod == 0) || (symbol_mod == (4 - frame_parms->Ncp)))\n    {\n        pilots = 1;\n    }\n\n    //  printf(\"Dual stream correlation (%p)\\n\",dl_ch_estimates_ext_i);\n\n    for(aarx = 0; aarx < frame_parms->nb_antennas_rx; aarx++)\n    {\n        dl_ch128          = (__m128i *)&dl_ch_estimates_ext[aarx][symbol * frame_parms->N_RB_DL * 12];\n\n        if(dl_ch_estimates_ext_i == NULL)  // TM3/4\n        {\n            dl_ch128i         = (__m128i *)&dl_ch_estimates_ext[aarx + frame_parms->nb_antennas_rx][symbol * frame_parms->N_RB_DL * 12];\n        }\n        else\n        {\n            dl_ch128i         = (__m128i *)&dl_ch_estimates_ext_i[aarx][symbol * frame_parms->N_RB_DL * 12];\n        }\n\n        dl_ch_rho128      = (__m128i *)&dl_ch_rho_ext[aarx][symbol * frame_parms->N_RB_DL * 12];\n\n        for(rb = 0; rb < nb_rb; rb++)\n        {\n            // multiply by conjugated channel\n            mmtmpD0 = _mm_madd_epi16(dl_ch128[0], dl_ch128i[0]);\n            //      print_ints(\"re\",&mmtmpD0);\n            // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n            mmtmpD1 = _mm_shufflelo_epi16(dl_ch128[0], _MM_SHUFFLE(2, 3, 0, 1));\n            mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1, _MM_SHUFFLE(2, 3, 0, 1));\n            mmtmpD1 = _mm_sign_epi16(mmtmpD1, *(__m128i *)&conjugate[0]);\n            mmtmpD1 = _mm_madd_epi16(mmtmpD1, dl_ch128i[0]);\n            //      print_ints(\"im\",&mmtmpD1);\n            // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n            mmtmpD0 = _mm_srai_epi32(mmtmpD0, output_shift);\n            //      print_ints(\"re(shift)\",&mmtmpD0);\n            mmtmpD1 = _mm_srai_epi32(mmtmpD1, output_shift);\n            //      print_ints(\"im(shift)\",&mmtmpD1);\n            mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0, mmtmpD1);\n            mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0, mmtmpD1);\n            //      print_ints(\"c0\",&mmtmpD2);\n            //      print_ints(\"c1\",&mmtmpD3);\n            dl_ch_rho128[0] = _mm_packs_epi32(mmtmpD2, mmtmpD3);\n            // print_shorts(\"rho 0:\",dl_ch_rho128);\n            // multiply by conjugated channel\n            mmtmpD0 = _mm_madd_epi16(dl_ch128[1], dl_ch128i[1]);\n            // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n            mmtmpD1 = _mm_shufflelo_epi16(dl_ch128[1], _MM_SHUFFLE(2, 3, 0, 1));\n            mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1, _MM_SHUFFLE(2, 3, 0, 1));\n            mmtmpD1 = _mm_sign_epi16(mmtmpD1, *(__m128i *)conjugate);\n            mmtmpD1 = _mm_madd_epi16(mmtmpD1, dl_ch128i[1]);\n            // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n            mmtmpD0 = _mm_srai_epi32(mmtmpD0, output_shift);\n            mmtmpD1 = _mm_srai_epi32(mmtmpD1, output_shift);\n            mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0, mmtmpD1);\n            mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0, mmtmpD1);\n            dl_ch_rho128[1] = _mm_packs_epi32(mmtmpD2, mmtmpD3);\n\n            if(pilots == 0)\n            {\n                // multiply by conjugated channel\n                mmtmpD0 = _mm_madd_epi16(dl_ch128[2], dl_ch128i[2]);\n                // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n                mmtmpD1 = _mm_shufflelo_epi16(dl_ch128[2], _MM_SHUFFLE(2, 3, 0, 1));\n                mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1, _MM_SHUFFLE(2, 3, 0, 1));\n                mmtmpD1 = _mm_sign_epi16(mmtmpD1, *(__m128i *)conjugate);\n                mmtmpD1 = _mm_madd_epi16(mmtmpD1, dl_ch128i[2]);\n                // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n                mmtmpD0 = _mm_srai_epi32(mmtmpD0, output_shift);\n                mmtmpD1 = _mm_srai_epi32(mmtmpD1, output_shift);\n                mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0, mmtmpD1);\n                mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0, mmtmpD1);\n                dl_ch_rho128[2] = _mm_packs_epi32(mmtmpD2, mmtmpD3);\n                dl_ch128 += 3;\n                dl_ch128i += 3;\n                dl_ch_rho128 += 3;\n            }\n            else\n            {\n                dl_ch128 += 2;\n                dl_ch128i += 2;\n                dl_ch_rho128 += 2;\n            }\n        }\n    }\n\n    _mm_empty();\n    _m_empty();\n#elif defined(__arm__)\n#endif\n}\n\n\nvoid dlsch_detection_mrc(LTE_DL_FRAME_PARMS *frame_parms,\n                         int **rxdataF_comp,\n                         int **rxdataF_comp_i,\n                         int **rho,\n                         int **rho_i,\n                         int **dl_ch_mag,\n                         int **dl_ch_magb,\n                         int **dl_ch_mag_i,\n                         int **dl_ch_magb_i,\n                         unsigned char symbol,\n                         unsigned short nb_rb,\n                         unsigned char dual_stream_UE)\n{\n#if defined(__x86_64__)||defined(__i386__)\n    unsigned char aatx;\n    int i;\n    __m128i *rxdataF_comp128_0, *rxdataF_comp128_1, *rxdataF_comp128_i0, *rxdataF_comp128_i1, *dl_ch_mag128_0, *dl_ch_mag128_1, *dl_ch_mag128_0b, *dl_ch_mag128_1b, *rho128_0, *rho128_1, *rho128_i0, *rho128_i1,\n            *dl_ch_mag128_i0, *dl_ch_mag128_i1, *dl_ch_mag128_i0b, *dl_ch_mag128_i1b;\n\n    if(frame_parms->nb_antennas_rx > 1)\n    {\n        for(aatx = 0; aatx < frame_parms->nb_antenna_ports_eNB; aatx++)\n        {\n            rxdataF_comp128_0   = (__m128i *)&rxdataF_comp[(aatx << 1)][symbol * frame_parms->N_RB_DL * 12];\n            rxdataF_comp128_1   = (__m128i *)&rxdataF_comp[(aatx << 1) + 1][symbol * frame_parms->N_RB_DL * 12];\n            dl_ch_mag128_0      = (__m128i *)&dl_ch_mag[(aatx << 1)][symbol * frame_parms->N_RB_DL * 12];\n            dl_ch_mag128_1      = (__m128i *)&dl_ch_mag[(aatx << 1) + 1][symbol * frame_parms->N_RB_DL * 12];\n            dl_ch_mag128_0b     = (__m128i *)&dl_ch_magb[(aatx << 1)][symbol * frame_parms->N_RB_DL * 12];\n            dl_ch_mag128_1b     = (__m128i *)&dl_ch_magb[(aatx << 1) + 1][symbol * frame_parms->N_RB_DL * 12];\n\n            // MRC on each re of rb, both on MF output and magnitude (for 16QAM/64QAM llr computation)\n            for(i = 0; i < nb_rb * 3; i++)\n            {\n                rxdataF_comp128_0[i] = _mm_adds_epi16(_mm_srai_epi16(rxdataF_comp128_0[i], 1), _mm_srai_epi16(rxdataF_comp128_1[i], 1));\n                dl_ch_mag128_0[i]    = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_0[i], 1), _mm_srai_epi16(dl_ch_mag128_1[i], 1));\n                dl_ch_mag128_0b[i]   = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_0b[i], 1), _mm_srai_epi16(dl_ch_mag128_1b[i], 1));\n                //       print_shorts(\"mrc comp0:\",&rxdataF_comp128_0[i]);\n                //       print_shorts(\"mrc mag0:\",&dl_ch_mag128_0[i]);\n                //       print_shorts(\"mrc mag0b:\",&dl_ch_mag128_0b[i]);\n                //      print_shorts(\"mrc rho1:\",&rho128_1[i]);\n            }\n        }\n\n        if(rho)\n        {\n            rho128_0 = (__m128i *) &rho[0][symbol * frame_parms->N_RB_DL * 12];\n            rho128_1 = (__m128i *) &rho[1][symbol * frame_parms->N_RB_DL * 12];\n\n            for(i = 0; i < nb_rb * 3; i++)\n            {\n                //      print_shorts(\"mrc rho0:\",&rho128_0[i]);\n                //      print_shorts(\"mrc rho1:\",&rho128_1[i]);\n                rho128_0[i] = _mm_adds_epi16(_mm_srai_epi16(rho128_0[i], 1), _mm_srai_epi16(rho128_1[i], 1));\n            }\n        }\n\n        if(dual_stream_UE == 1)\n        {\n            rho128_i0 = (__m128i *) &rho_i[0][symbol * frame_parms->N_RB_DL * 12];\n            rho128_i1 = (__m128i *) &rho_i[1][symbol * frame_parms->N_RB_DL * 12];\n            rxdataF_comp128_i0   = (__m128i *)&rxdataF_comp_i[0][symbol * frame_parms->N_RB_DL * 12];\n            rxdataF_comp128_i1   = (__m128i *)&rxdataF_comp_i[1][symbol * frame_parms->N_RB_DL * 12];\n            dl_ch_mag128_i0      = (__m128i *)&dl_ch_mag_i[0][symbol * frame_parms->N_RB_DL * 12];\n            dl_ch_mag128_i1      = (__m128i *)&dl_ch_mag_i[1][symbol * frame_parms->N_RB_DL * 12];\n            dl_ch_mag128_i0b     = (__m128i *)&dl_ch_magb_i[0][symbol * frame_parms->N_RB_DL * 12];\n            dl_ch_mag128_i1b     = (__m128i *)&dl_ch_magb_i[1][symbol * frame_parms->N_RB_DL * 12];\n\n            for(i = 0; i < nb_rb * 3; i++)\n            {\n                rxdataF_comp128_i0[i] = _mm_adds_epi16(_mm_srai_epi16(rxdataF_comp128_i0[i], 1), _mm_srai_epi16(rxdataF_comp128_i1[i], 1));\n                rho128_i0[i]           = _mm_adds_epi16(_mm_srai_epi16(rho128_i0[i], 1), _mm_srai_epi16(rho128_i1[i], 1));\n                dl_ch_mag128_i0[i]    = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_i0[i], 1), _mm_srai_epi16(dl_ch_mag128_i1[i], 1));\n                dl_ch_mag128_i0b[i]    = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_i0b[i], 1), _mm_srai_epi16(dl_ch_mag128_i1b[i], 1));\n            }\n        }\n    }\n\n    _mm_empty();\n    _m_empty();\n#elif defined(__arm__)\n    unsigned char aatx;\n    int i;\n    int16x8_t *rxdataF_comp128_0, *rxdataF_comp128_1, *rxdataF_comp128_i0, *rxdataF_comp128_i1, *dl_ch_mag128_0, *dl_ch_mag128_1, *dl_ch_mag128_0b, *dl_ch_mag128_1b, *rho128_0, *rho128_1, *rho128_i0, *rho128_i1,\n              *dl_ch_mag128_i0, *dl_ch_mag128_i1, *dl_ch_mag128_i0b, *dl_ch_mag128_i1b;\n\n    if(frame_parms->nb_antennas_rx > 1)\n    {\n        for(aatx = 0; aatx < frame_parms->nb_antenna_ports_eNB; aatx++)\n        {\n            rxdataF_comp128_0   = (int16x8_t *)&rxdataF_comp[(aatx << 1)][symbol * frame_parms->N_RB_DL * 12];\n            rxdataF_comp128_1   = (int16x8_t *)&rxdataF_comp[(aatx << 1) + 1][symbol * frame_parms->N_RB_DL * 12];\n            dl_ch_mag128_0      = (int16x8_t *)&dl_ch_mag[(aatx << 1)][symbol * frame_parms->N_RB_DL * 12];\n            dl_ch_mag128_1      = (int16x8_t *)&dl_ch_mag[(aatx << 1) + 1][symbol * frame_parms->N_RB_DL * 12];\n            dl_ch_mag128_0b     = (int16x8_t *)&dl_ch_magb[(aatx << 1)][symbol * frame_parms->N_RB_DL * 12];\n            dl_ch_mag128_1b     = (int16x8_t *)&dl_ch_magb[(aatx << 1) + 1][symbol * frame_parms->N_RB_DL * 12];\n\n            // MRC on each re of rb, both on MF output and magnitude (for 16QAM/64QAM llr computation)\n            for(i = 0; i < nb_rb * 3; i++)\n            {\n                rxdataF_comp128_0[i] = vhaddq_s16(rxdataF_comp128_0[i], rxdataF_comp128_1[i]);\n                dl_ch_mag128_0[i]    = vhaddq_s16(dl_ch_mag128_0[i], dl_ch_mag128_1[i]);\n                dl_ch_mag128_0b[i]   = vhaddq_s16(dl_ch_mag128_0b[i], dl_ch_mag128_1b[i]);\n            }\n        }\n\n        if(rho)\n        {\n            rho128_0 = (int16x8_t *) &rho[0][symbol * frame_parms->N_RB_DL * 12];\n            rho128_1 = (int16x8_t *) &rho[1][symbol * frame_parms->N_RB_DL * 12];\n\n            for(i = 0; i < nb_rb * 3; i++)\n            {\n                //  print_shorts(\"mrc rho0:\",&rho128_0[i]);\n                //  print_shorts(\"mrc rho1:\",&rho128_1[i]);\n                rho128_0[i] = vhaddq_s16(rho128_0[i], rho128_1[i]);\n            }\n        }\n\n        if(dual_stream_UE == 1)\n        {\n            rho128_i0 = (int16x8_t *) &rho_i[0][symbol * frame_parms->N_RB_DL * 12];\n            rho128_i1 = (int16x8_t *) &rho_i[1][symbol * frame_parms->N_RB_DL * 12];\n            rxdataF_comp128_i0   = (int16x8_t *)&rxdataF_comp_i[0][symbol * frame_parms->N_RB_DL * 12];\n            rxdataF_comp128_i1   = (int16x8_t *)&rxdataF_comp_i[1][symbol * frame_parms->N_RB_DL * 12];\n            dl_ch_mag128_i0      = (int16x8_t *)&dl_ch_mag_i[0][symbol * frame_parms->N_RB_DL * 12];\n            dl_ch_mag128_i1      = (int16x8_t *)&dl_ch_mag_i[1][symbol * frame_parms->N_RB_DL * 12];\n            dl_ch_mag128_i0b     = (int16x8_t *)&dl_ch_magb_i[0][symbol * frame_parms->N_RB_DL * 12];\n            dl_ch_mag128_i1b     = (int16x8_t *)&dl_ch_magb_i[1][symbol * frame_parms->N_RB_DL * 12];\n\n            for(i = 0; i < nb_rb * 3; i++)\n            {\n                rxdataF_comp128_i0[i] = vhaddq_s16(rxdataF_comp128_i0[i], rxdataF_comp128_i1[i]);\n                rho128_i0[i]          = vhaddq_s16(rho128_i0[i], rho128_i1[i]);\n                dl_ch_mag128_i0[i]    = vhaddq_s16(dl_ch_mag128_i0[i], dl_ch_mag128_i1[i]);\n                dl_ch_mag128_i0b[i]   = vhaddq_s16(dl_ch_mag128_i0b[i], dl_ch_mag128_i1b[i]);\n            }\n        }\n    }\n\n#endif\n}\n\nvoid dlsch_detection_mrc_TM34(LTE_DL_FRAME_PARMS *frame_parms,\n                              LTE_UE_PDSCH *pdsch_vars,\n                              int harq_pid,\n                              int round,\n                              unsigned char symbol,\n                              unsigned short nb_rb,\n                              unsigned char dual_stream_UE)\n{\n    int i;\n    __m128i *rxdataF_comp128_0, *rxdataF_comp128_1;\n    __m128i *dl_ch_mag128_0, *dl_ch_mag128_1;\n    __m128i *dl_ch_mag128_0b, *dl_ch_mag128_1b;\n    __m128i *rho128_0, *rho128_1;\n    int **rxdataF_comp0           = pdsch_vars->rxdataF_comp0;\n    int **rxdataF_comp1           = pdsch_vars->rxdataF_comp1[harq_pid][round];\n    int **dl_ch_rho_ext           = pdsch_vars->dl_ch_rho_ext[harq_pid][round]; //for second stream\n    int **dl_ch_rho2_ext          = pdsch_vars->dl_ch_rho2_ext;\n    int **dl_ch_mag0              = pdsch_vars->dl_ch_mag0;\n    int **dl_ch_mag1              = pdsch_vars->dl_ch_mag1[harq_pid][round];\n    int **dl_ch_magb0             = pdsch_vars->dl_ch_magb0;\n    int **dl_ch_magb1             = pdsch_vars->dl_ch_magb1[harq_pid][round];\n    rxdataF_comp128_0   = (__m128i *)&rxdataF_comp0[0][symbol * frame_parms->N_RB_DL * 12];\n    rxdataF_comp128_1   = (__m128i *)&rxdataF_comp0[1][symbol * frame_parms->N_RB_DL * 12];\n    dl_ch_mag128_0      = (__m128i *)&dl_ch_mag0[0][symbol * frame_parms->N_RB_DL * 12];\n    dl_ch_mag128_1      = (__m128i *)&dl_ch_mag0[1][symbol * frame_parms->N_RB_DL * 12];\n    dl_ch_mag128_0b     = (__m128i *)&dl_ch_magb0[0][symbol * frame_parms->N_RB_DL * 12];\n    dl_ch_mag128_1b     = (__m128i *)&dl_ch_magb0[1][symbol * frame_parms->N_RB_DL * 12];\n    rho128_0 = (__m128i *) &dl_ch_rho2_ext[0][symbol * frame_parms->N_RB_DL * 12];\n    rho128_1 = (__m128i *) &dl_ch_rho2_ext[1][symbol * frame_parms->N_RB_DL * 12];\n\n    // MRC on each re of rb, both on MF output and magnitude (for 16QAM/64QAM llr computation)\n    for(i = 0; i < nb_rb * 3; i++)\n    {\n        rxdataF_comp128_0[i] = _mm_adds_epi16(_mm_srai_epi16(rxdataF_comp128_0[i], 1), _mm_srai_epi16(rxdataF_comp128_1[i], 1));\n        dl_ch_mag128_0[i]    = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_0[i], 1), _mm_srai_epi16(dl_ch_mag128_1[i], 1));\n        dl_ch_mag128_0b[i]   = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_0b[i], 1), _mm_srai_epi16(dl_ch_mag128_1b[i], 1));\n        rho128_0[i] = _mm_adds_epi16(_mm_srai_epi16(rho128_0[i], 1), _mm_srai_epi16(rho128_1[i], 1));\n\n        if(frame_parms->nb_antennas_rx > 2)\n        {\n            __m128i *rxdataF_comp128_2 = NULL;\n            __m128i *rxdataF_comp128_3 = NULL;\n            __m128i *dl_ch_mag128_2 = NULL;\n            __m128i *dl_ch_mag128_3 = NULL;\n            __m128i *dl_ch_mag128_2b = NULL;\n            __m128i *dl_ch_mag128_3b = NULL;\n            __m128i *rho128_2 = NULL;\n            __m128i *rho128_3 = NULL;\n            rxdataF_comp128_2   = (__m128i *)&rxdataF_comp0[2][symbol * frame_parms->N_RB_DL * 12];\n            rxdataF_comp128_3   = (__m128i *)&rxdataF_comp0[3][symbol * frame_parms->N_RB_DL * 12];\n            dl_ch_mag128_2      = (__m128i *)&dl_ch_mag0[2][symbol * frame_parms->N_RB_DL * 12];\n            dl_ch_mag128_3      = (__m128i *)&dl_ch_mag0[3][symbol * frame_parms->N_RB_DL * 12];\n            dl_ch_mag128_2b     = (__m128i *)&dl_ch_magb0[2][symbol * frame_parms->N_RB_DL * 12];\n            dl_ch_mag128_3b     = (__m128i *)&dl_ch_magb0[3][symbol * frame_parms->N_RB_DL * 12];\n            rho128_2 = (__m128i *) &dl_ch_rho2_ext[2][symbol * frame_parms->N_RB_DL * 12];\n            rho128_3 = (__m128i *) &dl_ch_rho2_ext[3][symbol * frame_parms->N_RB_DL * 12];\n            /*rxdataF_comp*/\n            rxdataF_comp128_2[i] = _mm_adds_epi16(_mm_srai_epi16(rxdataF_comp128_2[i], 1), _mm_srai_epi16(rxdataF_comp128_3[i], 1));\n            rxdataF_comp128_0[i] = _mm_adds_epi16(_mm_srai_epi16(rxdataF_comp128_0[i], 1), _mm_srai_epi16(rxdataF_comp128_2[i], 1));\n            /*dl_ch_mag*/\n            dl_ch_mag128_2[i] = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_2[i], 1), _mm_srai_epi16(dl_ch_mag128_3[i], 1));\n            dl_ch_mag128_0[i] = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_0[i], 1), _mm_srai_epi16(dl_ch_mag128_2[i], 1));\n            /*dl_ch_mag*/\n            dl_ch_mag128_2b[i] = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_2b[i], 1), _mm_srai_epi16(dl_ch_mag128_3b[i], 1));\n            dl_ch_mag128_0b[i] = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_0b[i], 1), _mm_srai_epi16(dl_ch_mag128_2b[i], 1));\n            /*rho*/\n            rho128_2[i] = _mm_adds_epi16(_mm_srai_epi16(rho128_2[i], 1), _mm_srai_epi16(rho128_3[i], 1));\n            rho128_0[i] = _mm_adds_epi16(_mm_srai_epi16(rho128_0[i], 1), _mm_srai_epi16(rho128_2[i], 1));\n        }\n    }\n\n    if(dual_stream_UE == 1)\n    {\n        __m128i *dl_ch_mag128_i0, *dl_ch_mag128_i1;\n        __m128i *dl_ch_mag128_i0b, *dl_ch_mag128_i1b;\n        __m128i *rho128_i0, *rho128_i1;\n        __m128i *rxdataF_comp128_i0, *rxdataF_comp128_i1;\n        rxdataF_comp128_i0   = (__m128i *)&rxdataF_comp1[0][symbol * frame_parms->N_RB_DL * 12];\n        rxdataF_comp128_i1   = (__m128i *)&rxdataF_comp1[1][symbol * frame_parms->N_RB_DL * 12];\n        dl_ch_mag128_i0      = (__m128i *)&dl_ch_mag1[0][symbol * frame_parms->N_RB_DL * 12];\n        dl_ch_mag128_i1      = (__m128i *)&dl_ch_mag1[1][symbol * frame_parms->N_RB_DL * 12];\n        dl_ch_mag128_i0b     = (__m128i *)&dl_ch_magb1[0][symbol * frame_parms->N_RB_DL * 12];\n        dl_ch_mag128_i1b     = (__m128i *)&dl_ch_magb1[1][symbol * frame_parms->N_RB_DL * 12];\n        rho128_i0 = (__m128i *) &dl_ch_rho_ext[0][symbol * frame_parms->N_RB_DL * 12];\n        rho128_i1 = (__m128i *) &dl_ch_rho_ext[1][symbol * frame_parms->N_RB_DL * 12];\n\n        for(i = 0; i < nb_rb * 3; i++)\n        {\n            rxdataF_comp128_i0[i] = _mm_adds_epi16(_mm_srai_epi16(rxdataF_comp128_i0[i], 1), _mm_srai_epi16(rxdataF_comp128_i1[i], 1));\n            dl_ch_mag128_i0[i]    = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_i0[i], 1), _mm_srai_epi16(dl_ch_mag128_i1[i], 1));\n            dl_ch_mag128_i0b[i]    = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_i0b[i], 1), _mm_srai_epi16(dl_ch_mag128_i1b[i], 1));\n            rho128_i0[i]           = _mm_adds_epi16(_mm_srai_epi16(rho128_i0[i], 1), _mm_srai_epi16(rho128_i1[i], 1));\n\n            if(frame_parms->nb_antennas_rx > 2)\n            {\n                __m128i *rxdataF_comp128_i2 = NULL;\n                __m128i *rxdataF_comp128_i3 = NULL;\n                __m128i *dl_ch_mag128_i2 = NULL;\n                __m128i *dl_ch_mag128_i3 = NULL;\n                __m128i *dl_ch_mag128_i2b = NULL;\n                __m128i *dl_ch_mag128_i3b = NULL;\n                __m128i *rho128_i2 = NULL;\n                __m128i *rho128_i3 = NULL;\n                rxdataF_comp128_i2   = (__m128i *)&rxdataF_comp1[2][symbol * frame_parms->N_RB_DL * 12];\n                rxdataF_comp128_i3   = (__m128i *)&rxdataF_comp1[3][symbol * frame_parms->N_RB_DL * 12];\n                dl_ch_mag128_i2      = (__m128i *)&dl_ch_mag1[2][symbol * frame_parms->N_RB_DL * 12];\n                dl_ch_mag128_i3      = (__m128i *)&dl_ch_mag1[3][symbol * frame_parms->N_RB_DL * 12];\n                dl_ch_mag128_i2b     = (__m128i *)&dl_ch_magb1[2][symbol * frame_parms->N_RB_DL * 12];\n                dl_ch_mag128_i3b     = (__m128i *)&dl_ch_magb1[3][symbol * frame_parms->N_RB_DL * 12];\n                rho128_i2 = (__m128i *) &dl_ch_rho_ext[2][symbol * frame_parms->N_RB_DL * 12];\n                rho128_i3 = (__m128i *) &dl_ch_rho_ext[3][symbol * frame_parms->N_RB_DL * 12];\n                /*rxdataF_comp*/\n                rxdataF_comp128_i2[i] = _mm_adds_epi16(_mm_srai_epi16(rxdataF_comp128_i2[i], 1), _mm_srai_epi16(rxdataF_comp128_i3[i], 1));\n                rxdataF_comp128_i0[i] = _mm_adds_epi16(_mm_srai_epi16(rxdataF_comp128_i0[i], 1), _mm_srai_epi16(rxdataF_comp128_i2[i], 1));\n                /*dl_ch_mag*/\n                dl_ch_mag128_i2[i] = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_i2[i], 1), _mm_srai_epi16(dl_ch_mag128_i3[i], 1));\n                dl_ch_mag128_i0[i] = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_i0[i], 1), _mm_srai_epi16(dl_ch_mag128_i2[i], 1));\n                /*dl_ch_mag*/\n                dl_ch_mag128_i2b[i] = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_i2b[i], 1), _mm_srai_epi16(dl_ch_mag128_i3b[i], 1));\n                dl_ch_mag128_i0b[i] = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_i0b[i], 1), _mm_srai_epi16(dl_ch_mag128_i2b[i], 1));\n                /*rho*/\n                rho128_i2[i] = _mm_adds_epi16(_mm_srai_epi16(rho128_i2[i], 1), _mm_srai_epi16(rho128_i3[i], 1));\n                rho128_i0[i] = _mm_adds_epi16(_mm_srai_epi16(rho128_i0[i], 1), _mm_srai_epi16(rho128_i2[i], 1));\n            }\n        }\n    }\n\n    _mm_empty();\n    _m_empty();\n}\n\nvoid dlsch_scale_channel(int **dl_ch_estimates_ext,\n                         LTE_DL_FRAME_PARMS *frame_parms,\n                         LTE_UE_DLSCH_t **dlsch_ue,\n                         uint8_t symbol,\n                         unsigned short nb_rb)\n{\n#if defined(__x86_64__)||defined(__i386__)\n    short rb, ch_amp;\n    unsigned char aatx, aarx, pilots = 0, symbol_mod;\n    __m128i *dl_ch128, ch_amp128;\n    symbol_mod = (symbol >= (7 - frame_parms->Ncp)) ? symbol - (7 - frame_parms->Ncp) : symbol;\n\n    if((symbol_mod == 0) || (symbol_mod == (4 - frame_parms->Ncp)))\n    {\n        if(frame_parms->nb_antenna_ports_eNB == 1) // 10 out of 12 so don't reduce size\n        {\n            nb_rb = 1 + (5 * nb_rb / 6);\n        }\n        else\n        {\n            pilots = 1;\n        }\n    }\n\n    // Determine scaling amplitude based the symbol\n    ch_amp = ((pilots) ? (dlsch_ue[0]->sqrt_rho_b) : (dlsch_ue[0]->sqrt_rho_a));\n    LOG_D(PHY, \"Scaling PDSCH Chest in OFDM symbol %d by %d, pilots %d nb_rb %d NCP %d symbol %d\\n\", symbol_mod, ch_amp, pilots, nb_rb, frame_parms->Ncp, symbol);\n    // printf(\"Scaling PDSCH Chest in OFDM symbol %d by %d\\n\",symbol_mod,ch_amp);\n    ch_amp128 = _mm_set1_epi16(ch_amp); // Q3.13\n\n    for(aatx = 0; aatx < frame_parms->nb_antenna_ports_eNB; aatx++)\n    {\n        for(aarx = 0; aarx < frame_parms->nb_antennas_rx; aarx++)\n        {\n            dl_ch128 = (__m128i *)&dl_ch_estimates_ext[(aatx << 1) + aarx][symbol * frame_parms->N_RB_DL * 12];\n\n            for(rb = 0; rb < nb_rb; rb++)\n            {\n                dl_ch128[0] = _mm_mulhi_epi16(dl_ch128[0], ch_amp128);\n                dl_ch128[0] = _mm_slli_epi16(dl_ch128[0], 3);\n                dl_ch128[1] = _mm_mulhi_epi16(dl_ch128[1], ch_amp128);\n                dl_ch128[1] = _mm_slli_epi16(dl_ch128[1], 3);\n\n                if(pilots)\n                {\n                    dl_ch128 += 2;\n                }\n                else\n                {\n                    dl_ch128[2] = _mm_mulhi_epi16(dl_ch128[2], ch_amp128);\n                    dl_ch128[2] = _mm_slli_epi16(dl_ch128[2], 3);\n                    dl_ch128 += 3;\n                }\n            }\n        }\n    }\n\n#elif defined(__arm__)\n#endif\n}\n\n//compute average channel_level on each (TX,RX) antenna pair\nvoid dlsch_channel_level(int **dl_ch_estimates_ext,\n                         LTE_DL_FRAME_PARMS *frame_parms,\n                         int32_t *avg,\n                         uint8_t symbol,\n                         unsigned short nb_rb)\n{\n#if defined(__x86_64__)||defined(__i386__)\n    //printf(\"symbol = %d\\n\", symbol);\n    short rb;\n    unsigned char aatx, aarx, nre = 12, symbol_mod;\n    __m128i *dl_ch128, avg128D;\n    symbol_mod = (symbol >= (7 - frame_parms->Ncp)) ? symbol - (7 - frame_parms->Ncp) : symbol;\n\n    if(((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp - 1))) && (frame_parms->nb_antenna_ports_eNB != 1))\n    {\n        nre = 8;\n    }\n    else if(((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp - 1))) && (frame_parms->nb_antenna_ports_eNB == 1))\n    {\n        nre = 10;\n    }\n    else\n    {\n        nre = 12;\n    }\n\n    //nb_rb*nre = y * 2^x\n    int16_t x = factor2(nb_rb * nre);\n    int16_t y = (nb_rb * nre) >> x;\n\n    for(aatx = 0; aatx < frame_parms->nb_antenna_ports_eNB; aatx++)\n        for(aarx = 0; aarx < frame_parms->nb_antennas_rx; aarx++)\n        {\n            //clear average level\n            //printf(\"aatx = %d, aarx = %d, aatx*frame_parms->nb_antennas_rx + aarx] = %d \\n\", aatx, aarx, aatx*frame_parms->nb_antennas_rx + aarx);\n            avg128D = _mm_setzero_si128();\n            // 5 is always a symbol with no pilots for both normal and extended prefix\n            dl_ch128 = (__m128i *)&dl_ch_estimates_ext[aatx * 2 + aarx][symbol * frame_parms->N_RB_DL * 12];\n\n            for(rb = 0; rb < nb_rb; rb++)\n            {\n                //printf(\"rb %d : \",rb);\n                avg128D = _mm_add_epi32(avg128D, _mm_srai_epi32(_mm_madd_epi16(dl_ch128[0], dl_ch128[0]), x));\n                avg128D = _mm_add_epi32(avg128D, _mm_srai_epi32(_mm_madd_epi16(dl_ch128[1], dl_ch128[1]), x));\n\n                //avg128D = _mm_add_epi32(avg128D,_mm_madd_epi16(dl_ch128[0],_mm_srai_epi16(_mm_mulhi_epi16(dl_ch128[0], coeff128),15)));\n                //avg128D = _mm_add_epi32(avg128D,_mm_madd_epi16(dl_ch128[1],_mm_srai_epi16(_mm_mulhi_epi16(dl_ch128[1], coeff128),15)));\n\n                if(((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp - 1))) && (frame_parms->nb_antenna_ports_eNB != 1))\n                {\n                    dl_ch128 += 2;\n                }\n                else\n                {\n                    avg128D = _mm_add_epi32(avg128D, _mm_srai_epi32(_mm_madd_epi16(dl_ch128[2], dl_ch128[2]), x));\n                    //avg128D = _mm_add_epi32(avg128D,_mm_madd_epi16(dl_ch128[2],_mm_srai_epi16(_mm_mulhi_epi16(dl_ch128[2], coeff128),15)));\n                    dl_ch128 += 3;\n                }\n\n                /*  if(rb==0){\n                    print_shorts(\"dl_ch128\",&dl_ch128[0]);\n                    print_shorts(\"dl_ch128\",&dl_ch128[1]);\n                    print_shorts(\"dl_ch128\",&dl_ch128[2]);\n                    }*/\n            }\n\n            avg[aatx * frame_parms->nb_antennas_rx + aarx] = (((int32_t *)&avg128D)[0] +\n                    ((int32_t *)&avg128D)[1] +\n                    ((int32_t *)&avg128D)[2] +\n                    ((int32_t *)&avg128D)[3]) / y;\n        }\n\n    _mm_empty();\n    _m_empty();\n#elif defined(__arm__)\n    short rb;\n    unsigned char aatx, aarx, nre = 12, symbol_mod;\n    int32x4_t avg128D;\n    int16x4_t *dl_ch128;\n    symbol_mod = (symbol >= (7 - frame_parms->Ncp)) ? symbol - (7 - frame_parms->Ncp) : symbol;\n\n    for(aatx = 0; aatx < frame_parms->nb_antenna_ports_eNB; aatx++)\n        for(aarx = 0; aarx < frame_parms->nb_antennas_rx; aarx++)\n        {\n            //clear average level\n            avg128D = vdupq_n_s32(0);\n            // 5 is always a symbol with no pilots for both normal and extended prefix\n            dl_ch128 = (int16x4_t *)&dl_ch_estimates_ext[aatx * frame_parms->nb_antennas_rx + aarx][symbol * frame_parms->N_RB_DL * 12];\n\n            for(rb = 0; rb < nb_rb; rb++)\n            {\n                //  printf(\"rb %d : \",rb);\n                //  print_shorts(\"ch\",&dl_ch128[0]);\n                avg128D = vqaddq_s32(avg128D, vmull_s16(dl_ch128[0], dl_ch128[0]));\n                avg128D = vqaddq_s32(avg128D, vmull_s16(dl_ch128[1], dl_ch128[1]));\n                avg128D = vqaddq_s32(avg128D, vmull_s16(dl_ch128[2], dl_ch128[2]));\n                avg128D = vqaddq_s32(avg128D, vmull_s16(dl_ch128[3], dl_ch128[3]));\n\n                if(((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp - 1))) && (frame_parms->mode1_flag == 0))\n                {\n                    dl_ch128 += 4;\n                }\n                else\n                {\n                    avg128D = vqaddq_s32(avg128D, vmull_s16(dl_ch128[4], dl_ch128[4]));\n                    avg128D = vqaddq_s32(avg128D, vmull_s16(dl_ch128[5], dl_ch128[5]));\n                    dl_ch128 += 6;\n                }\n\n                /*\n                    if (rb==0) {\n                    print_shorts(\"dl_ch128\",&dl_ch128[0]);\n                    print_shorts(\"dl_ch128\",&dl_ch128[1]);\n                    print_shorts(\"dl_ch128\",&dl_ch128[2]);\n                    }\n                */\n            }\n\n            if(((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp - 1))) && (frame_parms->mode1_flag == 0))\n            {\n                nre = 8;\n            }\n            else if(((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp - 1))) && (frame_parms->mode1_flag == 1))\n            {\n                nre = 10;\n            }\n            else\n            {\n                nre = 12;\n            }\n\n            avg[aatx * frame_parms->nb_antennas_rx + aarx] = (((int32_t *)&avg128D)[0] +\n                    ((int32_t *)&avg128D)[1] +\n                    ((int32_t *)&avg128D)[2] +\n                    ((int32_t *)&avg128D)[3]) / (nb_rb * nre);\n            //printf(\"Channel level : %d\\n\",avg[aatx*(frame_parms->nb_antennas_rx-1) + aarx]);\n        }\n\n#endif\n}\n\nvoid dlsch_channel_level_core(int **dl_ch_estimates_ext,\n                              int32_t *avg,\n                              int n_tx,\n                              int n_rx,\n                              int length,\n                              int start_point)\n{\n#if defined(__x86_64__)||defined(__i386__)\n    short ii;\n    int aatx, aarx;\n    int length_mod8;\n    int length2;\n    __m128i *dl_ch128, avg128D;\n    int16_t x = factor2(length);\n    int16_t y = (length) >> x;\n\n    for(aatx = 0; aatx < n_tx; aatx++)\n        for(aarx = 0; aarx < n_rx; aarx++)\n        {\n            avg128D = _mm_setzero_si128();\n            dl_ch128 = (__m128i *)&dl_ch_estimates_ext[aatx * 2 + aarx][start_point];\n            length_mod8 = length & 7;\n\n            if(length_mod8 == 0)\n            {\n                length2 = length >> 3;\n\n                for(ii = 0; ii < length2; ii++)\n                {\n                    avg128D = _mm_add_epi32(avg128D, _mm_srai_epi32(_mm_madd_epi16(dl_ch128[0], dl_ch128[0]), x));\n                    avg128D = _mm_add_epi32(avg128D, _mm_srai_epi32(_mm_madd_epi16(dl_ch128[1], dl_ch128[1]), x));\n                    dl_ch128 += 2;\n                }\n            }\n            else\n            {\n                printf(\"Channel level: Received number of subcarriers is not multiple of 4, \\n\"\n                       \"need to adapt the code!\\n\");\n            }\n\n            avg[aatx * n_rx + aarx] = (((int32_t *)&avg128D)[0] +\n                                       ((int32_t *)&avg128D)[1] +\n                                       ((int32_t *)&avg128D)[2] +\n                                       ((int32_t *)&avg128D)[3]) / y;\n            //printf(\"Channel level [%d]: %d\\n\",aatx*n_rx + aarx, avg[aatx*n_rx + aarx]);\n        }\n\n    _mm_empty();\n    _m_empty();\n    /* FIXME This part needs to be adapted like the one above */\n#elif defined(__arm__)\n    short rb;\n    unsigned char aatx, aarx, nre = 12, symbol_mod;\n    int32x4_t avg128D;\n    int16x4_t *dl_ch128;\n    symbol_mod = (symbol >= (7 - frame_parms->Ncp)) ? symbol - (7 - frame_parms->Ncp) : symbol;\n\n    for(aatx = 0; aatx < frame_parms->nb_antenna_ports_eNB; aatx++)\n        for(aarx = 0; aarx < frame_parms->nb_antennas_rx; aarx++)\n        {\n            //clear average level\n            avg128D = vdupq_n_s32(0);\n            // 5 is always a symbol with no pilots for both normal and extended prefix\n            dl_ch128 = (int16x4_t *)&dl_ch_estimates_ext[aatx * frame_parms->nb_antennas_rx + aarx][symbol * frame_parms->N_RB_DL * 12];\n\n            for(rb = 0; rb < nb_rb; rb++)\n            {\n                //  printf(\"rb %d : \",rb);\n                //  print_shorts(\"ch\",&dl_ch128[0]);\n                avg128D = vqaddq_s32(avg128D, vmull_s16(dl_ch128[0], dl_ch128[0]));\n                avg128D = vqaddq_s32(avg128D, vmull_s16(dl_ch128[1], dl_ch128[1]));\n                avg128D = vqaddq_s32(avg128D, vmull_s16(dl_ch128[2], dl_ch128[2]));\n                avg128D = vqaddq_s32(avg128D, vmull_s16(dl_ch128[3], dl_ch128[3]));\n\n                if(((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp - 1))) && (frame_parms->nb_antenna_ports_eNB != 1))\n                {\n                    dl_ch128 += 4;\n                }\n                else\n                {\n                    avg128D = vqaddq_s32(avg128D, vmull_s16(dl_ch128[4], dl_ch128[4]));\n                    avg128D = vqaddq_s32(avg128D, vmull_s16(dl_ch128[5], dl_ch128[5]));\n                    dl_ch128 += 6;\n                }\n            }\n\n            if(((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp - 1))) && (frame_parms->nb_antenna_ports_eNB != 1))\n            {\n                nre = 8;\n            }\n            else if(((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp - 1))) && (frame_parms->nb_antenna_ports_eNB == 1))\n            {\n                nre = 10;\n            }\n            else\n            {\n                nre = 12;\n            }\n\n            avg[aatx * frame_parms->nb_antennas_rx + aarx] = (((int32_t *)&avg128D)[0] +\n                    ((int32_t *)&avg128D)[1] +\n                    ((int32_t *)&avg128D)[2] +\n                    ((int32_t *)&avg128D)[3]) / (nb_rb * nre);\n            //printf(\"Channel level : %d\\n\",avg[aatx*(frame_parms->nb_antennas_rx-1) + aarx]);\n        }\n\n#endif\n}\n\nvoid dlsch_channel_level_median(int **dl_ch_estimates_ext,\n                                int32_t *median,\n                                int n_tx,\n                                int n_rx,\n                                int length,\n                                int start_point)\n{\n#if defined(__x86_64__)||defined(__i386__)\n    short ii;\n    int aatx, aarx;\n    int length2;\n    int max = 0, min = 0;\n    int norm_pack;\n    __m128i *dl_ch128, norm128D;\n\n    for(aatx = 0; aatx < n_tx; aatx++)\n    {\n        for(aarx = 0; aarx < n_rx; aarx++)\n        {\n            max = 0;\n            min = 0;\n            norm128D = _mm_setzero_si128();\n            dl_ch128 = (__m128i *)&dl_ch_estimates_ext[aatx * 2 + aarx][start_point];\n            length2 = length >> 2;\n\n            for(ii = 0; ii < length2; ii++)\n            {\n                norm128D = _mm_srai_epi32(_mm_madd_epi16(dl_ch128[0], dl_ch128[0]), 1);\n                //print_ints(\"norm128D\",&norm128D[0]);\n                norm_pack = ((int32_t *)&norm128D)[0] +\n                            ((int32_t *)&norm128D)[1] +\n                            ((int32_t *)&norm128D)[2] +\n                            ((int32_t *)&norm128D)[3];\n\n                if(norm_pack > max)\n                {\n                    max = norm_pack;\n                }\n\n                if(norm_pack < min)\n                {\n                    min = norm_pack;\n                }\n\n                dl_ch128 += 1;\n            }\n\n            median[aatx * n_rx + aarx]  = (max + min) >> 1;\n            // printf(\"Channel level  median [%d]: %d\\n\",aatx*n_rx + aarx, median[aatx*n_rx + aarx]);\n        }\n    }\n\n    _mm_empty();\n    _m_empty();\n#elif defined(__arm__)\n    short rb;\n    unsigned char aatx, aarx, nre = 12, symbol_mod;\n    int32x4_t norm128D;\n    int16x4_t *dl_ch128;\n\n    for(aatx = 0; aatx < frame_parms->nb_antenna_ports_eNB; aatx++)\n    {\n        for(aarx = 0; aarx < frame_parms->nb_antennas_rx; aarx++)\n        {\n            max = 0;\n            min = 0;\n            norm128D = vdupq_n_s32(0);\n            dl_ch128 = (int16x4_t *)&dl_ch_estimates_ext[aatx * n_rx + aarx][start_point];\n            length_mod8 = length & 3;\n            length2 = length >> 2;\n\n            for(ii = 0; ii < length2; ii++)\n            {\n                norm128D = vshrq_n_u32(vmull_s16(dl_ch128[0], dl_ch128[0]), 1);\n                norm_pack = ((int32_t *)&norm128D)[0] +\n                            ((int32_t *)&norm128D)[1] +\n                            ((int32_t *)&norm128D)[2] +\n                            ((int32_t *)&norm128D)[3];\n\n                if(norm_pack > max)\n                {\n                    max = norm_pack;\n                }\n\n                if(norm_pack < min)\n                {\n                    min = norm_pack;\n                }\n\n                dl_ch128 += 1;\n            }\n\n            median[aatx * n_rx + aarx]  = (max + min) >> 1;\n            //printf(\"Channel level  median [%d]: %d\\n\",aatx*n_rx + aarx, median[aatx*n_rx + aarx]);\n        }\n    }\n\n#endif\n}\n\nvoid mmse_processing_oai(LTE_UE_PDSCH *pdsch_vars,\n                         LTE_DL_FRAME_PARMS *frame_parms,\n                         PHY_MEASUREMENTS *measurements,\n                         unsigned char first_symbol_flag,\n                         MIMO_mode_t mimo_mode,\n                         unsigned short mmse_flag,\n                         int noise_power,\n                         unsigned char symbol,\n                         unsigned short nb_rb)\n{\n    int **rxdataF_ext           = pdsch_vars->rxdataF_ext;\n    int **dl_ch_estimates_ext   = pdsch_vars->dl_ch_estimates_ext;\n    unsigned char *pmi_ext      = pdsch_vars->pmi_ext;\n    int avg_00[frame_parms->nb_antenna_ports_eNB * frame_parms->nb_antennas_rx];\n    int avg_01[frame_parms->nb_antenna_ports_eNB * frame_parms->nb_antennas_rx];\n    int symbol_mod, length, start_point, nre;\n    symbol_mod = (symbol >= (7 - frame_parms->Ncp)) ? symbol - (7 - frame_parms->Ncp) : symbol;\n\n    if(((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp - 1))) && (frame_parms->nb_antenna_ports_eNB != 1))\n    {\n        nre = 8;\n    }\n    else if(((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp - 1))) && (frame_parms->nb_antenna_ports_eNB == 1))\n    {\n        nre = 10;\n    }\n    else\n    {\n        nre = 12;\n    }\n\n    length  = nre * nb_rb;\n    start_point = symbol * nb_rb * 12;\n    mmse_processing_core(rxdataF_ext,\n                         dl_ch_estimates_ext,\n                         noise_power,\n                         frame_parms->nb_antenna_ports_eNB,\n                         frame_parms->nb_antennas_rx,\n                         length,\n                         start_point);\n\n    /*  dlsch_channel_aver_band(dl_ch_estimates_ext,\n                            frame_parms,\n                            chan_avg,\n                            symbol,\n                            nb_rb);\n\n\n        for (aatx=0; aatx<frame_parms->nb_antenna_ports_eNB; aatx++)\n        for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) {\n         H[aatx*frame_parms->nb_antennas_rx + aarx] = (float)(chan_avg[aatx*frame_parms->nb_antennas_rx + aarx].r/(32768.0)) + I*(float)(chan_avg[aatx*frame_parms->nb_antennas_rx + aarx].i/(32768.0));\n        // printf(\"H [%d] = (%f, %f) \\n\", aatx*frame_parms->nb_antennas_rx + aarx, creal(H[aatx*frame_parms->nb_antennas_rx + aarx]), cimag(H[aatx*frame_parms->nb_antennas_rx + aarx]));\n        }*/\n\n    if(first_symbol_flag == 1)\n    {\n        dlsch_channel_level_TM34(dl_ch_estimates_ext,\n                                 frame_parms,\n                                 pmi_ext,\n                                 avg_00,\n                                 avg_01,\n                                 symbol,\n                                 nb_rb,\n                                 mmse_flag,\n                                 mimo_mode);\n        avg_00[0] = (log2_approx(avg_00[0]) / 2) + dlsch_demod_shift + 4; // + 2 ;//+ 4;\n        avg_01[0] = (log2_approx(avg_01[0]) / 2) + dlsch_demod_shift + 4; // + 2 ;//+ 4;\n        pdsch_vars->log2_maxh0 = cmax(avg_00[0], 0);\n        pdsch_vars->log2_maxh1 = cmax(avg_01[0], 0);\n    }\n}\n\nvoid mmse_processing_core(int32_t **rxdataF_ext,\n                          int32_t **dl_ch_estimates_ext,\n                          int noise_power,\n                          int n_tx,\n                          int n_rx,\n                          int length,\n                          int start_point)\n{\n    int aatx, aarx, re;\n    float imag;\n    float real;\n    float complex **W_MMSE = malloc(n_tx * n_rx * sizeof(float complex *));\n\n    for(int j = 0; j < n_tx * n_rx; j++)\n    {\n        W_MMSE[j] = malloc(sizeof(float complex) * length);\n    }\n\n    float complex *H =  malloc(n_tx * n_rx * sizeof(float complex));\n    float complex *W_MMSE_re =  malloc(n_tx * n_rx * sizeof(float complex));\n    float complex **dl_ch_estimates_ext_flcpx = malloc(n_tx * n_rx * sizeof(float complex *));\n\n    for(int j = 0; j < n_tx * n_rx; j++)\n    {\n        dl_ch_estimates_ext_flcpx[j] = malloc(sizeof(float complex) * length);\n    }\n\n    float complex **rxdataF_ext_flcpx = malloc(n_rx * sizeof(float complex *));\n\n    for(int j = 0; j < n_rx; j++)\n    {\n        rxdataF_ext_flcpx[j] = malloc(sizeof(float complex) * length);\n    }\n\n    chan_est_to_float(dl_ch_estimates_ext,\n                      dl_ch_estimates_ext_flcpx,\n                      n_tx,\n                      n_rx,\n                      length,\n                      start_point);\n\n    for(re = 0; re < length; re++)\n    {\n        for(aatx = 0; aatx < n_tx; aatx++)\n        {\n            for(aarx = 0; aarx < n_rx; aarx++)\n            {\n                imag = cimag(dl_ch_estimates_ext_flcpx[aatx * n_rx + aarx][re]);\n                real = creal(dl_ch_estimates_ext_flcpx[aatx * n_rx + aarx][re]);\n                H[aatx * n_rx + aarx] = real + I * imag;\n            }\n        }\n\n        compute_MMSE(H, n_tx, noise_power, W_MMSE_re);\n\n        for(aatx = 0; aatx < n_tx; aatx++)\n        {\n            for(aarx = 0; aarx < n_rx; aarx++)\n            {\n                W_MMSE[aatx * n_rx + aarx][re] = W_MMSE_re[aatx * n_rx + aarx];\n            }\n        }\n    }\n\n    rxdataF_to_float(rxdataF_ext,\n                     rxdataF_ext_flcpx,\n                     n_rx,\n                     length,\n                     start_point);\n    mult_mmse_rxdataF(W_MMSE,\n                      rxdataF_ext_flcpx,\n                      n_tx,\n                      n_rx,\n                      length,\n                      start_point);\n    mult_mmse_chan_est(W_MMSE,\n                       dl_ch_estimates_ext_flcpx,\n                       n_tx,\n                       n_rx,\n                       length,\n                       start_point);\n    float_to_rxdataF(rxdataF_ext,\n                     rxdataF_ext_flcpx,\n                     n_tx,\n                     n_rx,\n                     length,\n                     start_point);\n    float_to_chan_est(dl_ch_estimates_ext,\n                      dl_ch_estimates_ext_flcpx,\n                      n_tx,\n                      n_rx,\n                      length,\n                      start_point);\n    free(W_MMSE);\n    free(H);\n    free(W_MMSE_re);\n    free(dl_ch_estimates_ext_flcpx);\n    free(rxdataF_ext_flcpx);\n}\n\n\n/*THIS FUNCTION TAKES FLOAT_POINT INPUT. SHOULD NOT BE USED WITH OAI*/\nvoid mmse_processing_core_flp(float complex **rxdataF_ext_flcpx,\n                              float complex **H,\n                              int32_t **rxdataF_ext,\n                              int32_t **dl_ch_estimates_ext,\n                              float noise_power,\n                              int n_tx,\n                              int n_rx,\n                              int length,\n                              int start_point)\n{\n    int aatx, aarx, re;\n    float max = 0;\n    float one_over_max = 0;\n    float complex **W_MMSE = malloc(n_tx * n_rx * sizeof(float complex *));\n\n    for(int j = 0; j < n_tx * n_rx; j++)\n    {\n        W_MMSE[j] = malloc(sizeof(float complex) * length);\n    }\n\n    float complex *H_re =  malloc(n_tx * n_rx * sizeof(float complex));\n    float complex *W_MMSE_re =  malloc(n_tx * n_rx * sizeof(float complex));\n\n    for(re = 0; re < length; re++)\n    {\n        for(aatx = 0; aatx < n_tx; aatx++)\n        {\n            for(aarx = 0; aarx < n_rx; aarx++)\n            {\n                H_re[aatx * n_rx + aarx] = H[aatx * n_rx + aarx][re];\n#ifdef DEBUG_MMSE\n\n                if(re == 0)\n                {\n                    printf(\" H_re[%d]= (%f + i%f)\\n\", aatx * n_rx + aarx, creal(H_re[aatx * n_rx + aarx]), cimag(H_re[aatx * n_rx + aarx]));\n                }\n\n#endif\n            }\n        }\n\n        compute_MMSE(H_re, n_tx, noise_power, W_MMSE_re);\n\n        for(aatx = 0; aatx < n_tx; aatx++)\n        {\n            for(aarx = 0; aarx < n_rx; aarx++)\n            {\n                W_MMSE[aatx * n_rx + aarx][re] = W_MMSE_re[aatx * n_rx + aarx];\n\n                if(fabs(creal(W_MMSE_re[aatx * n_rx + aarx])) > max)\n                {\n                    max = fabs(creal(W_MMSE_re[aatx * n_rx + aarx]));\n                }\n\n                if(fabs(cimag(W_MMSE_re[aatx * n_rx + aarx])) > max)\n                {\n                    max = fabs(cimag(W_MMSE_re[aatx * n_rx + aarx]));\n                }\n            }\n        }\n    }\n\n    one_over_max = 1.0 / max;\n\n    for(re = 0; re < length; re++)\n        for(aatx = 0; aatx < n_tx; aatx++)\n            for(aarx = 0; aarx < n_rx; aarx++)\n            {\n#ifdef DEBUG_MMSE\n\n                if(re == 0)\n                {\n                    printf(\" W_MMSE[%d] = (%f + i%f)\\n\", aatx * n_rx + aarx, creal(W_MMSE[aatx * n_rx + aarx][re]), cimag(W_MMSE[aatx * n_rx + aarx][re]));\n                }\n\n#endif\n                W_MMSE[aatx * n_rx + aarx][re] = one_over_max * W_MMSE[aatx * n_rx + aarx][re];\n#ifdef DEBUG_MMSE\n\n                if(re == 0)\n                {\n                    printf(\" AFTER NORM W_MMSE[%d] = (%f + i%f), max = %f \\n\", aatx * n_rx + aarx, creal(W_MMSE[aatx * n_rx + aarx][re]), cimag(W_MMSE[aatx * n_rx + aarx][re]), max);\n                }\n\n#endif\n            }\n\n    mult_mmse_rxdataF(W_MMSE,\n                      rxdataF_ext_flcpx,\n                      n_tx,\n                      n_rx,\n                      length,\n                      start_point);\n    mult_mmse_chan_est(W_MMSE,\n                       H,\n                       n_tx,\n                       n_rx,\n                       length,\n                       start_point);\n    float_to_rxdataF(rxdataF_ext,\n                     rxdataF_ext_flcpx,\n                     n_tx,\n                     n_rx,\n                     length,\n                     start_point);\n    float_to_chan_est(dl_ch_estimates_ext,\n                      H,\n                      n_tx,\n                      n_rx,\n                      length,\n                      start_point);\n    free(H_re);\n    free(W_MMSE);\n    free(W_MMSE_re);\n}\n\n\nvoid dlsch_channel_aver_band(int **dl_ch_estimates_ext,\n                             LTE_DL_FRAME_PARMS *frame_parms,\n                             struct complex32 *chan_avg,\n                             unsigned char symbol,\n                             unsigned short nb_rb)\n{\n#if defined(__x86_64__)||defined(__i386__)\n    short rb;\n    unsigned char aatx, aarx, nre = 12, symbol_mod;\n    __m128i *dl_ch128, avg128D;\n    int32_t chan_est_avg[4];\n    symbol_mod = (symbol >= (7 - frame_parms->Ncp)) ? symbol - (7 - frame_parms->Ncp) : symbol;\n\n    if(((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp - 1))) && (frame_parms->nb_antenna_ports_eNB != 1))\n    {\n        nre = 8;\n    }\n    else if(((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp - 1))) && (frame_parms->nb_antenna_ports_eNB == 1))\n    {\n        nre = 10;\n    }\n    else\n    {\n        nre = 12;\n    }\n\n    for(aatx = 0; aatx < frame_parms->nb_antenna_ports_eNB; aatx++)\n    {\n        for(aarx = 0; aarx < frame_parms->nb_antennas_rx; aarx++)\n        {\n            dl_ch128 = (__m128i *)&dl_ch_estimates_ext[aatx * frame_parms->nb_antennas_rx + aarx][symbol * frame_parms->N_RB_DL * 12];\n            avg128D = _mm_setzero_si128();\n            //  print_shorts(\"avg128D 1\",&avg128D);\n\n            for(rb = 0; rb < nb_rb; rb++)\n            {\n                /*  printf(\"symbol %d, ant %d, nre*nrb %d, rb %d \\n\", symbol, aatx*frame_parms->nb_antennas_rx + aarx, nb_rb*nre, rb);\n                    print_shorts(\"aver dl_ch128\",&dl_ch128[0]);\n                    print_shorts(\"aver dl_ch128\",&dl_ch128[1]);\n                    print_shorts(\"aver dl_ch128\",&dl_ch128[2]);\n                    avg128D = _mm_add_epi16(avg128D, dl_ch128[0]);*/\n                //print_shorts(\"avg128D 2\",&avg128D);\n                avg128D = _mm_add_epi16(avg128D, dl_ch128[1]);\n                //  print_shorts(\"avg128D 3\",&avg128D);\n\n                if(((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp - 1))) && (frame_parms->nb_antenna_ports_eNB != 1))\n                {\n                    dl_ch128 += 2;\n                }\n                else\n                {\n                    avg128D = _mm_add_epi16(avg128D, dl_ch128[2]);\n                    //  print_shorts(\"avg128D 4\",&avg128D);\n                    dl_ch128 += 3;\n                }\n            }\n\n            chan_avg[aatx * frame_parms->nb_antennas_rx + aarx].r = (((int16_t *)&avg128D)[0] +\n                    ((int16_t *)&avg128D)[2] +\n                    ((int16_t *)&avg128D)[4] +\n                    ((int16_t *)&avg128D)[6]) / (nb_rb * nre);\n            //  printf(\"symb %d chan_avg re [%d] = %d\\n\", symbol, aatx*frame_parms->nb_antennas_rx + aarx, chan_avg[aatx*frame_parms->nb_antennas_rx + aarx].r);\n            chan_avg[aatx * frame_parms->nb_antennas_rx + aarx].i = (((int16_t *)&avg128D)[1] +\n                    ((int16_t *)&avg128D)[3] +\n                    ((int16_t *)&avg128D)[5] +\n                    ((int16_t *)&avg128D)[7]) / (nb_rb * nre);\n            //  printf(\"symb %d chan_avg im [%d] = %d\\n\", symbol, aatx*frame_parms->nb_antennas_rx + aarx, chan_avg[aatx*frame_parms->nb_antennas_rx + aarx].i);\n            //printf(\"symb %d chan_avg im [%d] = %d\\n\", symbol, aatx*frame_parms->nb_antennas_rx + aarx, chan_avg[aatx*frame_parms->nb_antennas_rx + aarx].i);\n            chan_est_avg[aatx * frame_parms->nb_antennas_rx + aarx] = (((int32_t)chan_avg[aatx * frame_parms->nb_antennas_rx + aarx].i) << 16) | (((int32_t)chan_avg[aatx * frame_parms->nb_antennas_rx + aarx].r) & 0xffff);\n            //printf(\"symb %d chan_est_avg [%d] = %d\\n\", symbol, aatx*frame_parms->nb_antennas_rx + aarx, chan_est_avg[aatx*frame_parms->nb_antennas_rx + aarx]);\n            dl_ch128 = (__m128i *)&dl_ch_estimates_ext[aatx * frame_parms->nb_antennas_rx + aarx][symbol * frame_parms->N_RB_DL * 12];\n\n            for(rb = 0; rb < nb_rb; rb++)\n            {\n                dl_ch128[0] = _mm_set1_epi32(chan_est_avg[aatx * frame_parms->nb_antennas_rx + aarx]);\n                dl_ch128[1] = _mm_set1_epi32(chan_est_avg[aatx * frame_parms->nb_antennas_rx + aarx]);\n\n                if(((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp - 1))) && (frame_parms->nb_antenna_ports_eNB != 1))\n                {\n                    dl_ch128 += 2;\n                }\n                else\n                {\n                    dl_ch128[2] = _mm_set1_epi32(chan_est_avg[aatx * frame_parms->nb_antennas_rx + aarx]);\n                    dl_ch128 += 3;\n                }\n            }\n        }\n    }\n\n    _mm_empty();\n    _m_empty();\n#elif defined(__arm__)\n#endif\n}\n\nvoid rxdataF_to_float(int32_t **rxdataF_ext,\n                      float complex **rxdataF_f,\n                      int n_rx,\n                      int length,\n                      int start_point)\n{\n    short re;\n    int aarx;\n    int16_t imag;\n    int16_t real;\n\n    for(aarx = 0; aarx < n_rx; aarx++)\n    {\n        for(re = 0; re < length; re++)\n        {\n            imag = (int16_t)(rxdataF_ext[aarx][start_point + re] >> 16);\n            real = (int16_t)(rxdataF_ext[aarx][start_point + re] & 0xffff);\n            rxdataF_f[aarx][re] = (float)(real / (32768.0)) + I * (float)(imag / (32768.0));\n#ifdef DEBUG_MMSE\n\n            if(re == 0)\n            {\n                printf(\"rxdataF_to_float: aarx = %d, real= %d, imag = %d\\n\", aarx, real, imag);\n                //printf(\"rxdataF_to_float: rxdataF_ext[%d][%d] = %d\\n\", aarx, start_point + re, rxdataF_ext[aarx][start_point + re]);\n                //printf(\"rxdataF_to_float: ant %d, re = %d, rxdataF_f real = %f, rxdataF_f imag = %f \\n\", aarx, re, creal(rxdataF_f[aarx][re]), cimag(rxdataF_f[aarx][re]));\n            }\n\n#endif\n        }\n    }\n}\n\n\n\nvoid chan_est_to_float(int32_t **dl_ch_estimates_ext,\n                       float complex **dl_ch_estimates_ext_f,\n                       int n_tx,\n                       int n_rx,\n                       int length,\n                       int start_point)\n{\n    short re;\n    int aatx, aarx;\n    int16_t imag;\n    int16_t real;\n\n    for(aatx = 0; aatx < n_tx; aatx++)\n    {\n        for(aarx = 0; aarx < n_rx; aarx++)\n        {\n            for(re = 0; re < length; re++)\n            {\n                imag = (int16_t)(dl_ch_estimates_ext[aatx * n_rx + aarx][start_point + re] >> 16);\n                real = (int16_t)(dl_ch_estimates_ext[aatx * n_rx + aarx][start_point + re] & 0xffff);\n                dl_ch_estimates_ext_f[aatx * n_rx + aarx][re] = (float)(real / (32768.0)) + I * (float)(imag / (32768.0));\n#ifdef DEBUG_MMSE\n\n                if(re == 0)\n                {\n                    printf(\"ant %d, re = %d, real = %d, imag = %d \\n\", aatx * n_rx + aarx, re, real, imag);\n                    printf(\"ant %d, re = %d, real = %f, imag = %f \\n\", aatx * n_rx + aarx, re, creal(dl_ch_estimates_ext_f[aatx * n_rx + aarx][re]), cimag(dl_ch_estimates_ext_f[aatx * n_rx + aarx][re]));\n                }\n\n#endif\n            }\n        }\n    }\n}\n\nvoid float_to_chan_est(int32_t **dl_ch_estimates_ext,\n                       float complex **dl_ch_estimates_ext_f,\n                       int n_tx,\n                       int n_rx,\n                       int length,\n                       int start_point)\n{\n    short re;\n    int aarx, aatx;\n    int16_t imag;\n    int16_t real;\n\n    for(aatx = 0; aatx < n_tx; aatx++)\n    {\n        for(aarx = 0; aarx < n_rx; aarx++)\n        {\n            for(re = 0; re < length; re++)\n            {\n                if(cimag(dl_ch_estimates_ext_f[aatx * n_rx + aarx][re]) < -1)\n                {\n                    imag = 0x8000;\n                }\n                else if(cimag(dl_ch_estimates_ext_f[aatx * n_rx + aarx][re]) >= 1)\n                {\n                    imag = 0x7FFF;\n                }\n                else\n                {\n                    imag = cimag(dl_ch_estimates_ext_f[aatx * n_rx + aarx][re]) * 32768;\n                }\n\n                if(creal(dl_ch_estimates_ext_f[aatx * n_rx + aarx][re]) < -1)\n                {\n                    real = 0x8000;\n                }\n                else if(creal(dl_ch_estimates_ext_f[aatx * n_rx + aarx][re]) >= 1)\n                {\n                    real = 0x7FFF;\n                }\n                else\n                {\n                    real = creal(dl_ch_estimates_ext_f[aatx * n_rx + aarx][re]) * 32768;\n                }\n\n                dl_ch_estimates_ext[aatx * n_rx + aarx][start_point + re] = (((int32_t)imag) << 16) | ((int32_t)real & 0xffff);\n#ifdef DEBUG_MMSE\n\n                if(re == 0)\n                {\n                    printf(\" float_to_chan_est: chan est real = %f, chan est imag = %f\\n\", creal(dl_ch_estimates_ext_f[aatx * n_rx + aarx][re]), cimag(dl_ch_estimates_ext_f[aatx * n_rx + aarx][re]));\n                    printf(\"float_to_chan_est: real fixed = %d, imag fixed = %d\\n\", real, imag);\n                    printf(\"float_to_chan_est: ant %d, re = %d, dl_ch_estimates_ext = %d \\n\", aatx * n_rx + aarx, re,  dl_ch_estimates_ext[aatx * n_rx + aarx][start_point + re]);\n                }\n\n#endif\n            }\n        }\n    }\n}\n\n\nvoid float_to_rxdataF(int32_t **rxdataF_ext,\n                      float complex **rxdataF_f,\n                      int n_tx,\n                      int n_rx,\n                      int length,\n                      int start_point)\n{\n    short re;\n    int aarx;\n    int16_t imag;\n    int16_t real;\n\n    for(aarx = 0; aarx < n_rx; aarx++)\n    {\n        for(re = 0; re < length; re++)\n        {\n            if(cimag(rxdataF_f[aarx][re]) < -1)\n            {\n                imag = 0x8000;\n            }\n            else if(cimag(rxdataF_f[aarx][re]) >= 1)\n            {\n                imag = 0x7FFF;\n            }\n            else\n            {\n                imag = cimag(rxdataF_f[aarx][re]) * 32768;\n            }\n\n            if(creal(rxdataF_f[aarx][re]) < -1)\n            {\n                real = 0x8000;\n            }\n            else if(creal(rxdataF_f[aarx][re]) >= 1)\n            {\n                real = 0x7FFF;\n            }\n            else\n            {\n                real = creal(rxdataF_f[aarx][re]) * 32768;\n            }\n\n            rxdataF_ext[aarx][start_point + re] = (((int32_t)imag) << 16) | (((int32_t)real) & 0xffff);\n#ifdef DEBUG_MMSE\n\n            if(re == 0)\n            {\n                printf(\" float_to_rxdataF: real = %f, imag = %f\\n\", creal(rxdataF_f[aarx][re]), cimag(rxdataF_f[aarx][re]));\n                printf(\"float_to_rxdataF: real fixed = %d, imag fixed = %d\\n\", real, imag);\n                printf(\"float_to_rxdataF: ant %d, re = %d, rxdataF_ext = %d \\n\", aarx, re,  rxdataF_ext[aarx][start_point + re]);\n            }\n\n#endif\n        }\n    }\n}\n\n\nvoid mult_mmse_rxdataF(float complex **Wmmse,\n                       float complex **rxdataF_ext_f,\n                       int n_tx,\n                       int n_rx,\n                       int length,\n                       int start_point)\n{\n    short re;\n    int aarx, aatx;\n    float complex *rxdata_re =  malloc(n_rx * sizeof(float complex));\n    float complex *rxdata_mmse_re =  malloc(n_rx * sizeof(float complex));\n    float complex *Wmmse_re =  malloc(n_tx * n_rx * sizeof(float complex));\n\n    for(re = 0; re < length; re++)\n    {\n        for(aarx = 0; aarx < n_rx; aarx++)\n        {\n            rxdata_re[aarx] = rxdataF_ext_f[aarx][re];\n#ifdef DEBUG_MMSE\n\n            if(re == 0)\n            {\n                printf(\"mult_mmse_rxdataF before: rxdata_re[%d] = (%f, %f)\\n\", aarx, creal(rxdata_re[aarx]), cimag(rxdata_re[aarx]));\n            }\n\n#endif\n        }\n\n        for(aatx = 0; aatx < n_tx; aatx++)\n        {\n            for(aarx = 0; aarx < n_rx; aarx++)\n            {\n                Wmmse_re[aatx * n_rx + aarx] = Wmmse[aatx * n_rx + aarx][re];\n            }\n        }\n\n        mutl_matrix_matrix_col_based(Wmmse_re, rxdata_re, n_rx, n_tx, n_rx, 1, rxdata_mmse_re);\n\n        for(aarx = 0; aarx < n_rx; aarx++)\n        {\n            rxdataF_ext_f[aarx][re] = rxdata_mmse_re[aarx];\n#ifdef DEBUG_MMSE\n\n            if(re == 0)\n            {\n                printf(\"mult_mmse_rxdataF after: rxdataF_ext_f[%d] = (%f, %f)\\n\", aarx, creal(rxdataF_ext_f[aarx][re]), cimag(rxdataF_ext_f[aarx][re]));\n            }\n\n#endif\n        }\n    }\n\n    free(rxdata_re);\n    free(rxdata_mmse_re);\n    free(Wmmse_re);\n}\n\nvoid mult_mmse_chan_est(float complex **Wmmse,\n                        float complex **dl_ch_estimates_ext_f,\n                        int n_tx,\n                        int n_rx,\n                        int length,\n                        int start_point)\n{\n    short re;\n    int aarx, aatx;\n    float complex *chan_est_re =  malloc(n_tx * n_rx * sizeof(float complex));\n    float complex *chan_est_mmse_re =  malloc(n_tx * n_rx * sizeof(float complex));\n    float complex *Wmmse_re =  malloc(n_tx * n_rx * sizeof(float complex));\n\n    for(re = 0; re < length; re++)\n    {\n        for(aatx = 0; aatx < n_tx; aatx++)\n        {\n            for(aarx = 0; aarx < n_rx; aarx++)\n            {\n                chan_est_re[aatx * n_rx + aarx] = dl_ch_estimates_ext_f[aatx * n_rx + aarx][re];\n                Wmmse_re[aatx * n_rx + aarx] = Wmmse[aatx * n_rx + aarx][re];\n#ifdef DEBUG_MMSE\n\n                if(re == 0)\n                {\n                    printf(\"mult_mmse_chan_est: chan_est_re[%d] = (%f, %f)\\n\", aatx * n_rx + aarx, creal(chan_est_re[aatx * n_rx + aarx]), cimag(chan_est_re[aatx * n_rx + aarx]));\n                }\n\n#endif\n            }\n        }\n\n        mutl_matrix_matrix_col_based(Wmmse_re, chan_est_re, n_rx, n_tx, n_rx, n_tx, chan_est_mmse_re);\n\n        for(aatx = 0; aatx < n_tx; aatx++)\n        {\n            for(aarx = 0; aarx < n_rx; aarx++)\n            {\n                dl_ch_estimates_ext_f[aatx * n_rx + aarx][re] = chan_est_mmse_re[aatx * n_rx + aarx];\n#ifdef DEBUG_MMSE\n\n                if(re == 0)\n                {\n                    printf(\"mult_mmse_chan_est: dl_ch_estimates_ext_f[%d][%d] = (%f, %f)\\n\", aatx * n_rx + aarx, re, creal(dl_ch_estimates_ext_f[aatx * n_rx + aarx][re]), cimag(dl_ch_estimates_ext_f[aatx * n_rx + aarx][re]));\n                }\n\n#endif\n            }\n        }\n    }\n\n    free(Wmmse_re);\n    free(chan_est_re);\n    free(chan_est_mmse_re);\n}\n\n\n\n\n\n//compute average channel_level of effective (precoded) channel\nvoid dlsch_channel_level_TM34(int **dl_ch_estimates_ext,\n                              LTE_DL_FRAME_PARMS *frame_parms,\n                              unsigned char *pmi_ext,\n                              int *avg_0,\n                              int *avg_1,\n                              uint8_t symbol,\n                              unsigned short nb_rb,\n                              unsigned int mmse_flag,\n                              MIMO_mode_t mimo_mode)\n{\n#if defined(__x86_64__)||defined(__i386__)\n    short rb;\n    unsigned char aarx, nre = 12, symbol_mod;\n    __m128i *dl_ch0_128, *dl_ch1_128, dl_ch0_128_tmp, dl_ch1_128_tmp, avg_0_128D, avg_1_128D;\n    symbol_mod = (symbol >= (7 - frame_parms->Ncp)) ? symbol - (7 - frame_parms->Ncp) : symbol;\n    //clear average level\n    // avg_0_128D = _mm_setzero_si128();\n    // avg_1_128D = _mm_setzero_si128();\n    avg_0[0] = 0;\n    avg_0[1] = 0;\n    avg_1[0] = 0;\n    avg_1[1] = 0;\n    // 5 is always a symbol with no pilots for both normal and extended prefix\n\n    if(((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp - 1))) && (frame_parms->nb_antenna_ports_eNB != 1))\n    {\n        nre = 8;\n    }\n    else if(((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp - 1))) && (frame_parms->nb_antenna_ports_eNB == 1))\n    {\n        nre = 10;\n    }\n    else\n    {\n        nre = 12;\n    }\n\n    for(aarx = 0; aarx < frame_parms->nb_antennas_rx; aarx++)\n    {\n        dl_ch0_128 = (__m128i *)&dl_ch_estimates_ext[aarx][symbol * frame_parms->N_RB_DL * 12];\n        dl_ch1_128 = (__m128i *)&dl_ch_estimates_ext[2 + aarx][symbol * frame_parms->N_RB_DL * 12];\n        avg_0_128D = _mm_setzero_si128();\n        avg_1_128D = _mm_setzero_si128();\n\n        for(rb = 0; rb < nb_rb; rb++)\n        {\n            // printf(\"rb %d : \\n\",rb);\n            //print_shorts(\"ch0\\n\",&dl_ch0_128[0]);\n            //print_shorts(\"ch1\\n\",&dl_ch1_128[0]);\n            dl_ch0_128_tmp = _mm_load_si128(&dl_ch0_128[0]);\n            dl_ch1_128_tmp = _mm_load_si128(&dl_ch1_128[0]);\n\n            if(mmse_flag == 0)\n            {\n                if(mimo_mode == LARGE_CDD)\n                {\n                    prec2A_TM3_128(&dl_ch0_128_tmp, &dl_ch1_128_tmp);\n                }\n                else if(mimo_mode == DUALSTREAM_UNIFORM_PRECODING1)\n                {\n                    prec2A_TM4_128(0, &dl_ch0_128_tmp, &dl_ch1_128_tmp);\n                }\n                else if(mimo_mode == DUALSTREAM_UNIFORM_PRECODINGj)\n                {\n                    prec2A_TM4_128(1, &dl_ch0_128_tmp, &dl_ch1_128_tmp);\n                }\n                else if(mimo_mode == DUALSTREAM_PUSCH_PRECODING)\n                {\n                    prec2A_TM4_128(pmi_ext[rb], &dl_ch0_128_tmp, &dl_ch1_128_tmp);\n                }\n            }\n\n            //      mmtmpD0 = _mm_madd_epi16(dl_ch0_128_tmp,dl_ch0_128_tmp);\n            avg_0_128D = _mm_add_epi32(avg_0_128D, _mm_madd_epi16(dl_ch0_128_tmp, dl_ch0_128_tmp));\n            avg_1_128D = _mm_add_epi32(avg_1_128D, _mm_madd_epi16(dl_ch1_128_tmp, dl_ch1_128_tmp));\n            dl_ch0_128_tmp = _mm_load_si128(&dl_ch0_128[1]);\n            dl_ch1_128_tmp = _mm_load_si128(&dl_ch1_128[1]);\n\n            if(mmse_flag == 0)\n            {\n                if(mimo_mode == LARGE_CDD)\n                {\n                    prec2A_TM3_128(&dl_ch0_128_tmp, &dl_ch1_128_tmp);\n                }\n                else if(mimo_mode == DUALSTREAM_UNIFORM_PRECODING1)\n                {\n                    prec2A_TM4_128(0, &dl_ch0_128_tmp, &dl_ch1_128_tmp);\n                }\n                else if(mimo_mode == DUALSTREAM_UNIFORM_PRECODINGj)\n                {\n                    prec2A_TM4_128(1, &dl_ch0_128_tmp, &dl_ch1_128_tmp);\n                }\n                else if(mimo_mode == DUALSTREAM_PUSCH_PRECODING)\n                {\n                    prec2A_TM4_128(pmi_ext[rb], &dl_ch0_128_tmp, &dl_ch1_128_tmp);\n                }\n            }\n\n            //      mmtmpD1 = _mm_madd_epi16(dl_ch0_128_tmp,dl_ch0_128_tmp);\n            avg_0_128D = _mm_add_epi32(avg_0_128D, _mm_madd_epi16(dl_ch0_128_tmp, dl_ch0_128_tmp));\n            avg_1_128D = _mm_add_epi32(avg_1_128D, _mm_madd_epi16(dl_ch1_128_tmp, dl_ch1_128_tmp));\n\n            if(((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp - 1))) && (frame_parms->nb_antenna_ports_eNB != 1))\n            {\n                dl_ch0_128 += 2;\n                dl_ch1_128 += 2;\n            }\n            else\n            {\n                dl_ch0_128_tmp = _mm_load_si128(&dl_ch0_128[2]);\n                dl_ch1_128_tmp = _mm_load_si128(&dl_ch1_128[2]);\n\n                if(mmse_flag == 0)\n                {\n                    if(mimo_mode == LARGE_CDD)\n                    {\n                        prec2A_TM3_128(&dl_ch0_128_tmp, &dl_ch1_128_tmp);\n                    }\n                    else if(mimo_mode == DUALSTREAM_UNIFORM_PRECODING1)\n                    {\n                        prec2A_TM4_128(0, &dl_ch0_128_tmp, &dl_ch1_128_tmp);\n                    }\n                    else if(mimo_mode == DUALSTREAM_UNIFORM_PRECODINGj)\n                    {\n                        prec2A_TM4_128(1, &dl_ch0_128_tmp, &dl_ch1_128_tmp);\n                    }\n                    else if(mimo_mode == DUALSTREAM_PUSCH_PRECODING)\n                    {\n                        prec2A_TM4_128(pmi_ext[rb], &dl_ch0_128_tmp, &dl_ch1_128_tmp);\n                    }\n                }\n\n                //      mmtmpD2 = _mm_madd_epi16(dl_ch0_128_tmp,dl_ch0_128_tmp);\n                avg_1_128D = _mm_add_epi32(avg_1_128D, _mm_madd_epi16(dl_ch1_128_tmp, dl_ch1_128_tmp));\n                avg_0_128D = _mm_add_epi32(avg_0_128D, _mm_madd_epi16(dl_ch0_128_tmp, dl_ch0_128_tmp));\n                dl_ch0_128 += 3;\n                dl_ch1_128 += 3;\n            }\n        }\n\n        avg_0[aarx] = (((int *)&avg_0_128D)[0]) / (nb_rb * nre) +\n                      (((int *)&avg_0_128D)[1]) / (nb_rb * nre) +\n                      (((int *)&avg_0_128D)[2]) / (nb_rb * nre) +\n                      (((int *)&avg_0_128D)[3]) / (nb_rb * nre);\n        //  printf(\"From Chan_level aver stream 0 %d =%d\\n\", aarx, avg_0[aarx]);\n        avg_1[aarx] = (((int *)&avg_1_128D)[0]) / (nb_rb * nre) +\n                      (((int *)&avg_1_128D)[1]) / (nb_rb * nre) +\n                      (((int *)&avg_1_128D)[2]) / (nb_rb * nre) +\n                      (((int *)&avg_1_128D)[3]) / (nb_rb * nre);\n        //    printf(\"From Chan_level aver stream 1 %d =%d\\n\", aarx, avg_1[aarx]);\n    }\n\n    //avg_0[0] = max(avg_0[0],avg_0[1]);\n    //avg_1[0] = max(avg_1[0],avg_1[1]);\n    //avg_0[0]= max(avg_0[0], avg_1[0]);\n    avg_0[0] = avg_0[0] + avg_0[1];\n    // printf(\"From Chan_level aver stream 0 final =%d\\n\", avg_0[0]);\n    avg_1[0] = avg_1[0] + avg_1[1];\n    // printf(\"From Chan_level aver stream 1 final =%d\\n\", avg_1[0]);\n    avg_0[0] = min(avg_0[0], avg_1[0]);\n    avg_1[0] = avg_0[0];\n    _mm_empty();\n    _m_empty();\n#elif defined(__arm__)\n#endif\n}\n\n//compute average channel_level of effective (precoded) channel\nvoid dlsch_channel_level_TM56(int **dl_ch_estimates_ext,\n                              LTE_DL_FRAME_PARMS *frame_parms,\n                              unsigned char *pmi_ext,\n                              int *avg,\n                              uint8_t symbol,\n                              unsigned short nb_rb)\n{\n#if defined(__x86_64__)||defined(__i386__)\n    short rb;\n    unsigned char aarx, nre = 12, symbol_mod;\n    __m128i *dl_ch0_128, *dl_ch1_128, dl_ch0_128_tmp, dl_ch1_128_tmp, avg128D;\n    symbol_mod = (symbol >= (7 - frame_parms->Ncp)) ? symbol - (7 - frame_parms->Ncp) : symbol;\n    //clear average level\n    avg128D = _mm_setzero_si128();\n    avg[0] = 0;\n    avg[1] = 0;\n    // 5 is always a symbol with no pilots for both normal and extended prefix\n\n    if(((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp - 1))) && (frame_parms->nb_antenna_ports_eNB != 1))\n    {\n        nre = 8;\n    }\n    else if(((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp - 1))) && (frame_parms->nb_antenna_ports_eNB == 1))\n    {\n        nre = 10;\n    }\n    else\n    {\n        nre = 12;\n    }\n\n    for(aarx = 0; aarx < frame_parms->nb_antennas_rx; aarx++)\n    {\n        dl_ch0_128 = (__m128i *)&dl_ch_estimates_ext[aarx][symbol * frame_parms->N_RB_DL * 12];\n        dl_ch1_128 = (__m128i *)&dl_ch_estimates_ext[2 + aarx][symbol * frame_parms->N_RB_DL * 12];\n\n        for(rb = 0; rb < nb_rb; rb++)\n        {\n            dl_ch0_128_tmp = _mm_load_si128(&dl_ch0_128[0]);\n            dl_ch1_128_tmp = _mm_load_si128(&dl_ch1_128[0]);\n            prec2A_TM56_128(pmi_ext[rb], &dl_ch0_128_tmp, &dl_ch1_128_tmp);\n            //      mmtmpD0 = _mm_madd_epi16(dl_ch0_128_tmp,dl_ch0_128_tmp);\n            avg128D = _mm_add_epi32(avg128D, _mm_madd_epi16(dl_ch0_128_tmp, dl_ch0_128_tmp));\n            dl_ch0_128_tmp = _mm_load_si128(&dl_ch0_128[1]);\n            dl_ch1_128_tmp = _mm_load_si128(&dl_ch1_128[1]);\n            prec2A_TM56_128(pmi_ext[rb], &dl_ch0_128_tmp, &dl_ch1_128_tmp);\n            //      mmtmpD1 = _mm_madd_epi16(dl_ch0_128_tmp,dl_ch0_128_tmp);\n            avg128D = _mm_add_epi32(avg128D, _mm_madd_epi16(dl_ch0_128_tmp, dl_ch0_128_tmp));\n\n            if(((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp - 1))) && (frame_parms->nb_antenna_ports_eNB != 1))\n            {\n                dl_ch0_128 += 2;\n                dl_ch1_128 += 2;\n            }\n            else\n            {\n                dl_ch0_128_tmp = _mm_load_si128(&dl_ch0_128[2]);\n                dl_ch1_128_tmp = _mm_load_si128(&dl_ch1_128[2]);\n                prec2A_TM56_128(pmi_ext[rb], &dl_ch0_128_tmp, &dl_ch1_128_tmp);\n                //      mmtmpD2 = _mm_madd_epi16(dl_ch0_128_tmp,dl_ch0_128_tmp);\n                avg128D = _mm_add_epi32(avg128D, _mm_madd_epi16(dl_ch0_128_tmp, dl_ch0_128_tmp));\n                dl_ch0_128 += 3;\n                dl_ch1_128 += 3;\n            }\n        }\n\n        avg[aarx] = (((int *)&avg128D)[0]) / (nb_rb * nre) +\n                    (((int *)&avg128D)[1]) / (nb_rb * nre) +\n                    (((int *)&avg128D)[2]) / (nb_rb * nre) +\n                    (((int *)&avg128D)[3]) / (nb_rb * nre);\n    }\n\n    // choose maximum of the 2 effective channels\n    avg[0] = cmax(avg[0], avg[1]);\n    _mm_empty();\n    _m_empty();\n#elif defined(__arm__)\n#endif\n}\n\n//compute average channel_level for TM7\nvoid dlsch_channel_level_TM7(int **dl_bf_ch_estimates_ext,\n                             LTE_DL_FRAME_PARMS *frame_parms,\n                             int *avg,\n                             uint8_t symbol,\n                             unsigned short nb_rb)\n{\n#if defined(__x86_64__)||defined(__i386__)\n    short rb;\n    unsigned char aatx, aarx, nre = 12, symbol_mod;\n    __m128i *dl_ch128, avg128D;\n    symbol_mod = (symbol >= (7 - frame_parms->Ncp)) ? symbol - (7 - frame_parms->Ncp) : symbol;\n\n    for(aatx = 0; aatx < frame_parms->nb_antenna_ports_eNB; aatx++)\n        for(aarx = 0; aarx < frame_parms->nb_antennas_rx; aarx++)\n        {\n            //clear average level\n            avg128D = _mm_setzero_si128();\n            // 5 is always a symbol with no pilots for both normal and extended prefix\n            dl_ch128 = (__m128i *)&dl_bf_ch_estimates_ext[(aatx << 1) + aarx][symbol * frame_parms->N_RB_DL * 12];\n\n            for(rb = 0; rb < nb_rb; rb++)\n            {\n                //  printf(\"rb %d : \",rb);\n                //  print_shorts(\"ch\",&dl_ch128[0]);\n                avg128D = _mm_add_epi32(avg128D, _mm_madd_epi16(dl_ch128[0], dl_ch128[0]));\n                avg128D = _mm_add_epi32(avg128D, _mm_madd_epi16(dl_ch128[1], dl_ch128[1]));\n\n                if(((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp - 1))) && (frame_parms->nb_antenna_ports_eNB != 1))\n                {\n                    dl_ch128 += 2;\n                }\n                else\n                {\n                    avg128D = _mm_add_epi32(avg128D, _mm_madd_epi16(dl_ch128[2], dl_ch128[2]));\n                    dl_ch128 += 3;\n                }\n\n                /*\n                    if (rb==0) {\n                    print_shorts(\"dl_ch128\",&dl_ch128[0]);\n                    print_shorts(\"dl_ch128\",&dl_ch128[1]);\n                    print_shorts(\"dl_ch128\",&dl_ch128[2]);\n                    }\n                */\n            }\n\n            if(((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp - 1))))\n            {\n                nre = 10;\n            }\n            else if((frame_parms->Ncp == 0) && (symbol == 3 || symbol == 6 || symbol == 9 || symbol == 12))\n            {\n                nre = 9;\n            }\n            else if((frame_parms->Ncp == 1) && (symbol == 4 || symbol == 7 || symbol == 9))\n            {\n                nre = 8;\n            }\n            else\n            {\n                nre = 12;\n            }\n\n            avg[(aatx << 1) + aarx] = (((int *)&avg128D)[0] +\n                                       ((int *)&avg128D)[1] +\n                                       ((int *)&avg128D)[2] +\n                                       ((int *)&avg128D)[3]) / (nb_rb * nre);\n            //            printf(\"Channel level : %d\\n\",avg[(aatx<<1)+aarx]);\n        }\n\n    _mm_empty();\n    _m_empty();\n#elif defined(__arm__)\n#endif\n}\n//#define ONE_OVER_2_Q15 16384\nvoid dlsch_alamouti(LTE_DL_FRAME_PARMS *frame_parms,\n                    int **rxdataF_comp,\n                    int **dl_ch_mag,\n                    int **dl_ch_magb,\n                    unsigned char symbol,\n                    unsigned short nb_rb)\n{\n#if defined(__x86_64__)||defined(__i386__)\n    short *rxF0, *rxF1;\n    __m128i *ch_mag0, *ch_mag1, *ch_mag0b, *ch_mag1b, *rxF0_128;\n    unsigned char rb, re;\n    int jj = (symbol * frame_parms->N_RB_DL * 12);\n    uint8_t symbol_mod = (symbol >= (7 - frame_parms->Ncp)) ? symbol - (7 - frame_parms->Ncp) : symbol;\n    uint8_t pilots = ((symbol_mod == 0) || (symbol_mod == (4 - frame_parms->Ncp))) ? 1 : 0;\n    rxF0_128 = (__m128i *) &rxdataF_comp[0][jj];\n    //amp = _mm_set1_epi16(ONE_OVER_2_Q15);\n    //    printf(\"Doing alamouti!\\n\");\n    rxF0     = (short *)&rxdataF_comp[0][jj]; //tx antenna 0  h0*y\n    rxF1     = (short *)&rxdataF_comp[2][jj]; //tx antenna 1  h1*y\n    ch_mag0 = (__m128i *)&dl_ch_mag[0][jj];\n    ch_mag1 = (__m128i *)&dl_ch_mag[2][jj];\n    ch_mag0b = (__m128i *)&dl_ch_magb[0][jj];\n    ch_mag1b = (__m128i *)&dl_ch_magb[2][jj];\n\n    for(rb = 0; rb < nb_rb; rb++)\n    {\n        for(re = 0; re < ((pilots == 0) ? 12 : 8); re += 2)\n        {\n            // Alamouti RX combining\n            //      printf(\"Alamouti: symbol %d, rb %d, re %d: rxF0 (%d,%d,%d,%d), rxF1 (%d,%d,%d,%d)\\n\",symbol,rb,re,rxF0[0],rxF0[1],rxF0[2],rxF0[3],rxF1[0],rxF1[1],rxF1[2],rxF1[3]);\n            rxF0[0] = rxF0[0] + rxF1[2];\n            rxF0[1] = rxF0[1] - rxF1[3];\n            rxF0[2] = rxF0[2] - rxF1[0];\n            rxF0[3] = rxF0[3] + rxF1[1];\n            //      printf(\"Alamouti: rxF0 after (%d,%d,%d,%d)\\n\",rxF0[0],rxF0[1],rxF0[2],rxF0[3]);\n            rxF0 += 4;\n            rxF1 += 4;\n        }\n\n        // compute levels for 16QAM or 64 QAM llr unit\n        ch_mag0[0] = _mm_adds_epi16(ch_mag0[0], ch_mag1[0]);\n        ch_mag0[1] = _mm_adds_epi16(ch_mag0[1], ch_mag1[1]);\n        ch_mag0b[0] = _mm_adds_epi16(ch_mag0b[0], ch_mag1b[0]);\n        ch_mag0b[1] = _mm_adds_epi16(ch_mag0b[1], ch_mag1b[1]);\n\n        // account for 1/sqrt(2) scaling at transmission\n        //ch_mag0[0] = _mm_srai_epi16(ch_mag0[0],1);\n        //ch_mag0[1] = _mm_srai_epi16(ch_mag0[1],1);\n        //ch_mag0b[0] = _mm_srai_epi16(ch_mag0b[0],1);\n        //ch_mag0b[1] = _mm_srai_epi16(ch_mag0b[1],1);\n\n        //rxF0_128[0] = _mm_mulhi_epi16(rxF0_128[0],amp);\n        //rxF0_128[0] = _mm_slli_epi16(rxF0_128[0],1);\n        //rxF0_128[1] = _mm_mulhi_epi16(rxF0_128[1],amp);\n        //rxF0_128[1] = _mm_slli_epi16(rxF0_128[1],1);\n\n        //rxF0_128[0] = _mm_srai_epi16(rxF0_128[0],1);\n        //rxF0_128[1] = _mm_srai_epi16(rxF0_128[1],1);\n\n        if(pilots == 0)\n        {\n            ch_mag0[2] = _mm_adds_epi16(ch_mag0[2], ch_mag1[2]);\n            ch_mag0b[2] = _mm_adds_epi16(ch_mag0b[2], ch_mag1b[2]);\n            //ch_mag0[2] = _mm_srai_epi16(ch_mag0[2],1);\n            //ch_mag0b[2] = _mm_srai_epi16(ch_mag0b[2],1);\n            //rxF0_128[2] = _mm_mulhi_epi16(rxF0_128[2],amp);\n            //rxF0_128[2] = _mm_slli_epi16(rxF0_128[2],1);\n            //rxF0_128[2] = _mm_srai_epi16(rxF0_128[2],1);\n            ch_mag0 += 3;\n            ch_mag1 += 3;\n            ch_mag0b += 3;\n            ch_mag1b += 3;\n            rxF0_128 += 3;\n        }\n        else\n        {\n            ch_mag0 += 2;\n            ch_mag1 += 2;\n            ch_mag0b += 2;\n            ch_mag1b += 2;\n            rxF0_128 += 2;\n        }\n    }\n\n    _mm_empty();\n    _m_empty();\n#elif defined(__arm__)\n#endif\n}\n\n\n//==============================================================================================\n// Extraction functions\n//==============================================================================================\n\nunsigned short dlsch_extract_rbs_single(int **rxdataF,\n                                        int **dl_ch_estimates,\n                                        int **rxdataF_ext,\n                                        int **dl_ch_estimates_ext,\n                                        unsigned short pmi,\n                                        unsigned char *pmi_ext,\n                                        unsigned int *rb_alloc,\n                                        unsigned char symbol,\n                                        unsigned char subframe,\n                                        uint32_t high_speed_flag,\n                                        LTE_DL_FRAME_PARMS *frame_parms)\n{\n    unsigned short rb, nb_rb = 0;\n    unsigned char rb_alloc_ind;\n    unsigned char i, aarx, l, nsymb, skip_half = 0, sss_symb, pss_symb = 0;\n    int *dl_ch0, *dl_ch0_ext, *rxF, *rxF_ext;\n    unsigned char symbol_mod, pilots = 0, j = 0, poffset = 0;\n    symbol_mod = (symbol >= (7 - frame_parms->Ncp)) ? symbol - (7 - frame_parms->Ncp) : symbol;\n    pilots = ((symbol_mod == 0) || (symbol_mod == (4 - frame_parms->Ncp))) ? 1 : 0;\n    l = symbol;\n    nsymb = (frame_parms->Ncp == NORMAL) ? 14 : 12;\n\n    if(frame_parms->frame_type == TDD)     // TDD\n    {\n        sss_symb = nsymb - 1;\n        pss_symb = 2;\n    }\n    else\n    {\n        sss_symb = (nsymb >> 1) - 2;\n        pss_symb = (nsymb >> 1) - 1;\n    }\n\n    if(symbol_mod == (4 - frame_parms->Ncp))\n    {\n        poffset = 3;\n    }\n\n    for(aarx = 0; aarx < frame_parms->nb_antennas_rx; aarx++)\n    {\n        if(high_speed_flag == 1)\n        {\n            dl_ch0     = &dl_ch_estimates[aarx][5 + (symbol * (frame_parms->ofdm_symbol_size))];\n        }\n        else\n        {\n            dl_ch0     = &dl_ch_estimates[aarx][5];\n        }\n\n        dl_ch0_ext = &dl_ch_estimates_ext[aarx][symbol * (frame_parms->N_RB_DL * 12)];\n        rxF_ext   = &rxdataF_ext[aarx][symbol * (frame_parms->N_RB_DL * 12)];\n        rxF       = &rxdataF[aarx][(frame_parms->first_carrier_offset + (symbol * (frame_parms->ofdm_symbol_size)))];\n\n        if((frame_parms->N_RB_DL & 1) == 0) // even number of RBs\n            for(rb = 0; rb < frame_parms->N_RB_DL; rb++)\n            {\n                if(rb < 32)\n                {\n                    rb_alloc_ind = (rb_alloc[0] >> rb) & 1;\n                }\n                else if(rb < 64)\n                {\n                    rb_alloc_ind = (rb_alloc[1] >> (rb - 32)) & 1;\n                }\n                else if(rb < 96)\n                {\n                    rb_alloc_ind = (rb_alloc[2] >> (rb - 64)) & 1;\n                }\n                else if(rb < 100)\n                {\n                    rb_alloc_ind = (rb_alloc[3] >> (rb - 96)) & 1;\n                }\n                else\n                {\n                    rb_alloc_ind = 0;\n                }\n\n                if(rb_alloc_ind == 1)\n                {\n                    nb_rb++;\n                }\n\n                // For second half of RBs skip DC carrier\n                if(rb == (frame_parms->N_RB_DL >> 1))\n                {\n                    rxF       = &rxdataF[aarx][(1 + (symbol * (frame_parms->ofdm_symbol_size)))];\n                    //dl_ch0++;\n                }\n\n                // PBCH\n                if((subframe == 0) && (rb >= ((frame_parms->N_RB_DL >> 1) - 3)) && (rb < ((frame_parms->N_RB_DL >> 1) + 3)) && (l >= nsymb >> 1) && (l < ((nsymb >> 1) + 4)))\n                {\n                    rb_alloc_ind = 0;\n                }\n\n                //SSS\n                if(((subframe == 0) || (subframe == 5)) && (rb >= ((frame_parms->N_RB_DL >> 1) - 3)) && (rb < ((frame_parms->N_RB_DL >> 1) + 3)) && (l == sss_symb))\n                {\n                    rb_alloc_ind = 0;\n                }\n\n                if(frame_parms->frame_type == FDD)\n                {\n                    //PSS\n                    if(((subframe == 0) || (subframe == 5)) && (rb >= ((frame_parms->N_RB_DL >> 1) - 3)) && (rb < ((frame_parms->N_RB_DL >> 1) + 3)) && (l == pss_symb))\n                    {\n                        rb_alloc_ind = 0;\n                    }\n                }\n\n                if((frame_parms->frame_type == TDD) &&\n                        (subframe == 6)) //TDD Subframe 6\n                {\n                    if((rb >= ((frame_parms->N_RB_DL >> 1) - 3)) && (rb < ((frame_parms->N_RB_DL >> 1) + 3)) && (l == pss_symb))\n                    {\n                        rb_alloc_ind = 0;\n                    }\n                }\n\n                if(rb_alloc_ind == 1)\n                {\n                    *pmi_ext = (pmi >> ((rb >> 2) << 1)) & 3;\n                    memcpy(dl_ch0_ext, dl_ch0, 12 * sizeof(int));\n\n                    /*\n                        printf(\"rb %d\\n\",rb);\n                        for (i=0;i<12;i++)\n                        printf(\"(%d %d)\",((short *)dl_ch0)[i<<1],((short*)dl_ch0)[1+(i<<1)]);\n                        printf(\"\\n\");\n                    */\n                    if(pilots == 0)\n                    {\n                        for(i = 0; i < 12; i++)\n                        {\n                            rxF_ext[i] = rxF[i];\n                            /*\n                                printf(\"%d : (%d,%d)\\n\",(rxF+i-&rxdataF[aarx][( (symbol*(frame_parms->ofdm_symbol_size)))]),\n                                ((short*)&rxF[i])[0],((short*)&rxF[i])[1]);*/\n                        }\n\n                        dl_ch0_ext += 12;\n                        rxF_ext += 12;\n                    }\n                    else\n                    {\n                        j = 0;\n\n                        for(i = 0; i < 12; i++)\n                        {\n                            if((i != (frame_parms->nushift + poffset)) &&\n                                    (i != ((frame_parms->nushift + poffset + 6) % 12)))\n                            {\n                                rxF_ext[j] = rxF[i];\n                                //            printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[j],*(1+(short*)&rxF_ext[j]));\n                                dl_ch0_ext[j++] = dl_ch0[i];\n                            }\n                        }\n\n                        dl_ch0_ext += 10;\n                        rxF_ext += 10;\n                    }\n                }\n\n                dl_ch0 += 12;\n                rxF += 12;\n            }\n        else     // Odd number of RBs\n        {\n            for(rb = 0; rb < frame_parms->N_RB_DL >> 1; rb++)\n            {\n#ifdef DEBUG_DLSCH_DEMOD\n                printf(\"dlch_ext %u\\n\", dl_ch0_ext - &dl_ch_estimates_ext[aarx][0]);\n#endif\n                skip_half = 0;\n\n                if(rb < 32)\n                {\n                    rb_alloc_ind = (rb_alloc[0] >> rb) & 1;\n                }\n                else if(rb < 64)\n                {\n                    rb_alloc_ind = (rb_alloc[1] >> (rb - 32)) & 1;\n                }\n                else if(rb < 96)\n                {\n                    rb_alloc_ind = (rb_alloc[2] >> (rb - 64)) & 1;\n                }\n                else if(rb < 100)\n                {\n                    rb_alloc_ind = (rb_alloc[3] >> (rb - 96)) & 1;\n                }\n                else\n                {\n                    rb_alloc_ind = 0;\n                }\n\n                if(rb_alloc_ind == 1)\n                {\n                    nb_rb++;\n                }\n\n                // PBCH\n                if((subframe == 0) && (rb > ((frame_parms->N_RB_DL >> 1) - 3)) && (rb < ((frame_parms->N_RB_DL >> 1) + 3)) && (l >= (nsymb >> 1)) && (l < ((nsymb >> 1) + 4)))\n                {\n                    rb_alloc_ind = 0;\n                }\n\n                //PBCH subframe 0, symbols nsymb>>1 ... nsymb>>1 + 3\n                if((subframe == 0) && (rb == ((frame_parms->N_RB_DL >> 1) - 3)) && (l >= (nsymb >> 1)) && (l < ((nsymb >> 1) + 4)))\n                {\n                    skip_half = 1;\n                }\n                else if((subframe == 0) && (rb == ((frame_parms->N_RB_DL >> 1) + 3)) && (l >= (nsymb >> 1)) && (l < ((nsymb >> 1) + 4)))\n                {\n                    skip_half = 2;\n                }\n\n                //SSS\n\n                if(((subframe == 0) || (subframe == 5)) &&\n                        (rb > ((frame_parms->N_RB_DL >> 1) - 3)) &&\n                        (rb < ((frame_parms->N_RB_DL >> 1) + 3)) &&\n                        (l == sss_symb))\n                {\n                    rb_alloc_ind = 0;\n                }\n\n                //SSS\n                if(((subframe == 0) || (subframe == 5)) &&\n                        (rb == ((frame_parms->N_RB_DL >> 1) - 3)) &&\n                        (l == sss_symb))\n                {\n                    skip_half = 1;\n                }\n                else if(((subframe == 0) || (subframe == 5)) &&\n                        (rb == ((frame_parms->N_RB_DL >> 1) + 3)) &&\n                        (l == sss_symb))\n                {\n                    skip_half = 2;\n                }\n\n                //PSS in subframe 0/5 if FDD\n                if(frame_parms->frame_type == FDD)     //FDD\n                {\n                    if(((subframe == 0) || (subframe == 5)) &&\n                            (rb > ((frame_parms->N_RB_DL >> 1) - 3)) &&\n                            (rb < ((frame_parms->N_RB_DL >> 1) + 3)) &&\n                            (l == pss_symb))\n                    {\n                        rb_alloc_ind = 0;\n                    }\n\n                    if(((subframe == 0) || (subframe == 5)) && (rb == ((frame_parms->N_RB_DL >> 1) - 3)) && (l == pss_symb))\n                    {\n                        skip_half = 1;\n                    }\n                    else if(((subframe == 0) || (subframe == 5)) && (rb == ((frame_parms->N_RB_DL >> 1) + 3)) && (l == pss_symb))\n                    {\n                        skip_half = 2;\n                    }\n                }\n\n                if((frame_parms->frame_type == TDD) &&\n                        (subframe == 6)) //TDD Subframe 6\n                {\n                    if((rb > ((frame_parms->N_RB_DL >> 1) - 3)) && (rb < ((frame_parms->N_RB_DL >> 1) + 3)) && (l == pss_symb))\n                    {\n                        rb_alloc_ind = 0;\n                    }\n\n                    if((rb == ((frame_parms->N_RB_DL >> 1) - 3)) && (l == pss_symb))\n                    {\n                        skip_half = 1;\n                    }\n                    else if((rb == ((frame_parms->N_RB_DL >> 1) + 3)) && (l == pss_symb))\n                    {\n                        skip_half = 2;\n                    }\n                }\n\n                if(rb_alloc_ind == 1)\n                {\n#ifdef DEBUG_DLSCH_DEMOD\n                    printf(\"rb %d/symbol %d (skip_half %d)\\n\", rb, l, skip_half);\n#endif\n\n                    if(pilots == 0)\n                    {\n                        //      printf(\"Extracting w/o pilots (symbol %d, rb %d, skip_half %d)\\n\",l,rb,skip_half);\n                        if(skip_half == 1)\n                        {\n                            memcpy(dl_ch0_ext, dl_ch0, 6 * sizeof(int));\n\n                            for(i = 0; i < 6; i++)\n                            {\n                                rxF_ext[i] = rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                                printf(\"extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[i], *(1 + (short *)&rxF_ext[i]));\n#endif\n                            }\n\n                            dl_ch0_ext += 6;\n                            rxF_ext += 6;\n                        }\n                        else if(skip_half == 2)\n                        {\n                            memcpy(dl_ch0_ext, dl_ch0 + 6, 6 * sizeof(int));\n\n                            for(i = 0; i < 6; i++)\n                            {\n                                rxF_ext[i] = rxF[(i + 6)];\n#ifdef DEBUG_DLSCH_DEMOD\n                                printf(\"extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[i], *(1 + (short *)&rxF_ext[i]));\n#endif\n                            }\n\n                            dl_ch0_ext += 6;\n                            rxF_ext += 6;\n                        }\n                        else\n                        {\n                            memcpy(dl_ch0_ext, dl_ch0, 12 * sizeof(int));\n\n                            for(i = 0; i < 12; i++)\n                            {\n                                rxF_ext[i] = rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                                printf(\"extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[i], *(1 + (short *)&rxF_ext[i]));\n#endif\n                            }\n\n                            dl_ch0_ext += 12;\n                            rxF_ext += 12;\n                        }\n                    }\n                    else\n                    {\n                        //      printf(\"Extracting with pilots (symbol %d, rb %d, skip_half %d)\\n\",l,rb,skip_half);\n                        j = 0;\n\n                        if(skip_half == 1)\n                        {\n                            for(i = 0; i < 6; i++)\n                            {\n                                if(i != ((frame_parms->nushift + poffset) % 6))\n                                {\n                                    rxF_ext[j] = rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                                    printf(\"extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[j], *(1 + (short *)&rxF_ext[j]));\n#endif\n                                    dl_ch0_ext[j++] = dl_ch0[i];\n                                }\n                            }\n\n                            rxF_ext += 5;\n                            dl_ch0_ext += 5;\n                        }\n                        else if(skip_half == 2)\n                        {\n                            for(i = 0; i < 6; i++)\n                            {\n                                if(i != ((frame_parms->nushift + poffset) % 6))\n                                {\n                                    rxF_ext[j] = rxF[(i + 6)];\n#ifdef DEBUG_DLSCH_DEMOD\n                                    printf(\"extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[j], *(1 + (short *)&rxF_ext[j]));\n#endif\n                                    dl_ch0_ext[j++] = dl_ch0[i + 6];\n                                }\n                            }\n\n                            dl_ch0_ext += 5;\n                            rxF_ext += 5;\n                        }\n                        else\n                        {\n                            for(i = 0; i < 12; i++)\n                            {\n                                if((i != (frame_parms->nushift + poffset)) &&\n                                        (i != ((frame_parms->nushift + poffset + 6) % 12)))\n                                {\n                                    rxF_ext[j] = rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                                    printf(\"extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[j], *(1 + (short *)&rxF_ext[j]));\n#endif\n                                    dl_ch0_ext[j++] = dl_ch0[i];\n                                }\n                            }\n\n                            dl_ch0_ext += 10;\n                            rxF_ext += 10;\n                        }\n                    }\n                }\n\n                dl_ch0 += 12;\n                rxF += 12;\n            } // first half loop\n\n            // Do middle RB (around DC)\n            if(rb < 32)\n            {\n                rb_alloc_ind = (rb_alloc[0] >> rb) & 1;\n            }\n            else if(rb < 64)\n            {\n                rb_alloc_ind = (rb_alloc[1] >> (rb - 32)) & 1;\n            }\n            else if(rb < 96)\n            {\n                rb_alloc_ind = (rb_alloc[2] >> (rb - 64)) & 1;\n            }\n            else if(rb < 100)\n            {\n                rb_alloc_ind = (rb_alloc[3] >> (rb - 96)) & 1;\n            }\n            else\n            {\n                rb_alloc_ind = 0;\n            }\n\n            if(rb_alloc_ind == 1)\n            {\n                nb_rb++;\n            }\n\n            // PBCH\n\n            if((subframe == 0) &&\n                    (l >= (nsymb >> 1)) &&\n                    (l < ((nsymb >> 1) + 4)))\n            {\n                rb_alloc_ind = 0;\n            }\n\n            //SSS\n            if(((subframe == 0) || (subframe == 5)) && (l == sss_symb))\n            {\n                rb_alloc_ind = 0;\n            }\n\n            if(frame_parms->frame_type == FDD)\n            {\n                //PSS\n                if(((subframe == 0) || (subframe == 5)) && (l == pss_symb))\n                {\n                    rb_alloc_ind = 0;\n                }\n            }\n\n            //PSS\n            if((frame_parms->frame_type == TDD) &&\n                    (subframe == 6) &&\n                    (l == pss_symb))\n            {\n                rb_alloc_ind = 0;\n            }\n\n            //  printf(\"dlch_ext %d\\n\",dl_ch0_ext-&dl_ch_estimates_ext[aarx][0]);\n            //      printf(\"DC rb %d (%p)\\n\",rb,rxF);\n            if(rb_alloc_ind == 1)\n            {\n#ifdef DEBUG_DLSCH_DEMOD\n                printf(\"rb %d/symbol %d (skip_half %d)\\n\", rb, l, skip_half);\n#endif\n\n                if(pilots == 0)\n                {\n                    for(i = 0; i < 6; i++)\n                    {\n                        dl_ch0_ext[i] = dl_ch0[i];\n                        rxF_ext[i] = rxF[i];\n                    }\n\n                    rxF       = &rxdataF[aarx][((symbol * (frame_parms->ofdm_symbol_size)))];\n\n                    for(; i < 12; i++)\n                    {\n                        dl_ch0_ext[i] = dl_ch0[i];\n                        rxF_ext[i] = rxF[(1 + i - 6)];\n                    }\n\n                    dl_ch0_ext += 12;\n                    rxF_ext += 12;\n                }\n                else     // pilots==1\n                {\n                    j = 0;\n\n                    for(i = 0; i < 6; i++)\n                    {\n                        if(i != ((frame_parms->nushift + poffset) % 6))\n                        {\n                            dl_ch0_ext[j] = dl_ch0[i];\n                            rxF_ext[j++] = rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                            printf(\"**extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[j - 1], *(1 + (short *)&rxF_ext[j - 1]));\n#endif\n                        }\n                    }\n\n                    rxF       = &rxdataF[aarx][((symbol * (frame_parms->ofdm_symbol_size)))];\n\n                    for(; i < 12; i++)\n                    {\n                        if(i != ((frame_parms->nushift + 6 + poffset) % 12))\n                        {\n                            dl_ch0_ext[j] = dl_ch0[i];\n                            rxF_ext[j++] = rxF[(1 + i - 6)];\n#ifdef DEBUG_DLSCH_DEMOD\n                            printf(\"**extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[j - 1], *(1 + (short *)&rxF_ext[j - 1]));\n#endif\n                        }\n                    }\n\n                    dl_ch0_ext += 10;\n                    rxF_ext += 10;\n                } // symbol_mod==0\n            } // rballoc==1\n            else\n            {\n                rxF       = &rxdataF[aarx][((symbol * (frame_parms->ofdm_symbol_size)))];\n            }\n\n            dl_ch0 += 12;\n            rxF += 7;\n            rb++;\n\n            for(; rb < frame_parms->N_RB_DL; rb++)\n            {\n                //      printf(\"dlch_ext %d\\n\",dl_ch0_ext-&dl_ch_estimates_ext[aarx][0]);\n                //      printf(\"rb %d (%p)\\n\",rb,rxF);\n                skip_half = 0;\n\n                if(rb < 32)\n                {\n                    rb_alloc_ind = (rb_alloc[0] >> rb) & 1;\n                }\n                else if(rb < 64)\n                {\n                    rb_alloc_ind = (rb_alloc[1] >> (rb - 32)) & 1;\n                }\n                else if(rb < 96)\n                {\n                    rb_alloc_ind = (rb_alloc[2] >> (rb - 64)) & 1;\n                }\n                else if(rb < 100)\n                {\n                    rb_alloc_ind = (rb_alloc[3] >> (rb - 96)) & 1;\n                }\n                else\n                {\n                    rb_alloc_ind = 0;\n                }\n\n                if(rb_alloc_ind == 1)\n                {\n                    nb_rb++;\n                }\n\n                // PBCH\n                if((subframe == 0) && (rb > ((frame_parms->N_RB_DL >> 1) - 3)) && (rb < ((frame_parms->N_RB_DL >> 1) + 3)) && (l >= nsymb >> 1) && (l < ((nsymb >> 1) + 4)))\n                {\n                    rb_alloc_ind = 0;\n                }\n\n                //PBCH subframe 0, symbols nsymb>>1 ... nsymb>>1 + 3\n                if((subframe == 0) && (rb == ((frame_parms->N_RB_DL >> 1) - 3)) && (l >= (nsymb >> 1)) && (l < ((nsymb >> 1) + 4)))\n                {\n                    skip_half = 1;\n                }\n                else if((subframe == 0) && (rb == ((frame_parms->N_RB_DL >> 1) + 3)) && (l >= (nsymb >> 1)) && (l < ((nsymb >> 1) + 4)))\n                {\n                    skip_half = 2;\n                }\n\n                //SSS\n                if(((subframe == 0) || (subframe == 5)) && (rb > ((frame_parms->N_RB_DL >> 1) - 3)) && (rb < ((frame_parms->N_RB_DL >> 1) + 3)) && (l == sss_symb))\n                {\n                    rb_alloc_ind = 0;\n                }\n\n                //SSS\n                if(((subframe == 0) || (subframe == 5)) && (rb == ((frame_parms->N_RB_DL >> 1) - 3)) && (l == sss_symb))\n                {\n                    skip_half = 1;\n                }\n                else if(((subframe == 0) || (subframe == 5)) && (rb == ((frame_parms->N_RB_DL >> 1) + 3)) && (l == sss_symb))\n                {\n                    skip_half = 2;\n                }\n\n                if(frame_parms->frame_type == FDD)\n                {\n                    //PSS\n                    if(((subframe == 0) || (subframe == 5)) && (rb > ((frame_parms->N_RB_DL >> 1) - 3)) && (rb < ((frame_parms->N_RB_DL >> 1) + 3)) && (l == pss_symb))\n                    {\n                        rb_alloc_ind = 0;\n                    }\n\n                    //PSS\n\n                    if(((subframe == 0) || (subframe == 5)) && (rb == ((frame_parms->N_RB_DL >> 1) - 3)) && (l == pss_symb))\n                    {\n                        skip_half = 1;\n                    }\n                    else if(((subframe == 0) || (subframe == 5)) && (rb == ((frame_parms->N_RB_DL >> 1) + 3)) && (l == pss_symb))\n                    {\n                        skip_half = 2;\n                    }\n                }\n\n                if((frame_parms->frame_type == TDD) &&\n                        (subframe == 6)) //TDD Subframe 6\n                {\n                    if((rb > ((frame_parms->N_RB_DL >> 1) - 3)) && (rb < ((frame_parms->N_RB_DL >> 1) + 3)) && (l == pss_symb))\n                    {\n                        rb_alloc_ind = 0;\n                    }\n\n                    if((rb == ((frame_parms->N_RB_DL >> 1) - 3)) && (l == pss_symb))\n                    {\n                        skip_half = 1;\n                    }\n                    else if((rb == ((frame_parms->N_RB_DL >> 1) + 3)) && (l == pss_symb))\n                    {\n                        skip_half = 2;\n                    }\n                }\n\n                if(rb_alloc_ind == 1)\n                {\n#ifdef DEBUG_DLSCH_DEMOD\n                    printf(\"rb %d/symbol %d (skip_half %d)\\n\", rb, l, skip_half);\n#endif\n\n                    /*\n                        printf(\"rb %d\\n\",rb);\n                        for (i=0;i<12;i++)\n                        printf(\"(%d %d)\",((short *)dl_ch0)[i<<1],((short*)dl_ch0)[1+(i<<1)]);\n                        printf(\"\\n\");\n                    */\n                    if(pilots == 0)\n                    {\n                        //      printf(\"Extracting w/o pilots (symbol %d, rb %d, skip_half %d)\\n\",l,rb,skip_half);\n                        if(skip_half == 1)\n                        {\n                            memcpy(dl_ch0_ext, dl_ch0, 6 * sizeof(int));\n\n                            for(i = 0; i < 6; i++)\n                            {\n                                rxF_ext[i] = rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                                printf(\"extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[i], *(1 + (short *)&rxF_ext[i]));\n#endif\n                            }\n\n                            dl_ch0_ext += 6;\n                            rxF_ext += 6;\n                        }\n                        else if(skip_half == 2)\n                        {\n                            memcpy(dl_ch0_ext, dl_ch0 + 6, 6 * sizeof(int));\n\n                            for(i = 0; i < 6; i++)\n                            {\n                                rxF_ext[i] = rxF[(i + 6)];\n#ifdef DEBUG_DLSCH_DEMOD\n                                printf(\"extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[i], *(1 + (short *)&rxF_ext[i]));\n#endif\n                            }\n\n                            dl_ch0_ext += 6;\n                            rxF_ext += 6;\n                        }\n                        else\n                        {\n                            memcpy(dl_ch0_ext, dl_ch0, 12 * sizeof(int));\n\n                            for(i = 0; i < 12; i++)\n                            {\n                                rxF_ext[i] = rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                                printf(\"extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[i], *(1 + (short *)&rxF_ext[i]));\n#endif\n                            }\n\n                            dl_ch0_ext += 12;\n                            rxF_ext += 12;\n                        }\n                    }\n                    else\n                    {\n                        //      printf(\"Extracting with pilots (symbol %d, rb %d, skip_half %d)\\n\",l,rb,skip_half);\n                        j = 0;\n\n                        if(skip_half == 1)\n                        {\n                            for(i = 0; i < 6; i++)\n                            {\n                                if(i != ((frame_parms->nushift + poffset) % 6))\n                                {\n                                    rxF_ext[j] = rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                                    printf(\"extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[j], *(1 + (short *)&rxF_ext[j]));\n#endif\n                                    dl_ch0_ext[j++] = dl_ch0[i];\n                                }\n                            }\n\n                            dl_ch0_ext += 5;\n                            rxF_ext += 5;\n                        }\n                        else if(skip_half == 2)\n                        {\n                            for(i = 0; i < 6; i++)\n                            {\n                                if(i != ((frame_parms->nushift + poffset) % 6))\n                                {\n                                    rxF_ext[j] = rxF[(i + 6)];\n#ifdef DEBUG_DLSCH_DEMOD\n                                    printf(\"extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[j], *(1 + (short *)&rxF_ext[j]));\n#endif\n                                    dl_ch0_ext[j++] = dl_ch0[i + 6];\n                                }\n                            }\n\n                            dl_ch0_ext += 5;\n                            rxF_ext += 5;\n                        }\n                        else\n                        {\n                            for(i = 0; i < 12; i++)\n                            {\n                                if((i != (frame_parms->nushift + poffset)) &&\n                                        (i != ((frame_parms->nushift + poffset + 6) % 12)))\n                                {\n                                    rxF_ext[j] = rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                                    printf(\"extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[j], *(1 + (short *)&rxF_ext[j]));\n#endif\n                                    dl_ch0_ext[j++] = dl_ch0[i];\n                                }\n                            }\n\n                            dl_ch0_ext += 10;\n                            rxF_ext += 10;\n                        }\n                    } // pilots=0\n                }\n\n                dl_ch0 += 12;\n                rxF += 12;\n            }\n        }\n    }\n\n    return(nb_rb / frame_parms->nb_antennas_rx);\n}\n\nunsigned short dlsch_extract_rbs_dual(int **rxdataF,\n                                      int **dl_ch_estimates,\n                                      int **rxdataF_ext,\n                                      int **dl_ch_estimates_ext,\n                                      unsigned short pmi,\n                                      unsigned char *pmi_ext,\n                                      unsigned int *rb_alloc,\n                                      unsigned char symbol,\n                                      unsigned char subframe,\n                                      uint32_t high_speed_flag,\n                                      LTE_DL_FRAME_PARMS *frame_parms,\n                                      MIMO_mode_t mimo_mode)\n{\n    int prb, nb_rb = 0;\n    int prb_off, prb_off2;\n    int rb_alloc_ind, skip_half = 0, sss_symb, pss_symb = 0, nsymb, l;\n    int i, aarx;\n    int32_t *dl_ch0, *dl_ch0p, *dl_ch0_ext, *dl_ch1, *dl_ch1p, *dl_ch1_ext, *rxF, *rxF_ext;\n    int symbol_mod, pilots = 0, j = 0;\n    unsigned char *pmi_loc;\n    symbol_mod = (symbol >= (7 - frame_parms->Ncp)) ? symbol - (7 - frame_parms->Ncp) : symbol;\n    //  printf(\"extract_rbs: symbol_mod %d\\n\",symbol_mod);\n\n    if((symbol_mod == 0) || (symbol_mod == (4 - frame_parms->Ncp)))\n    {\n        pilots = 1;\n    }\n\n    nsymb = (frame_parms->Ncp == NORMAL) ? 14 : 12;\n    l = symbol;\n\n    if(frame_parms->frame_type == TDD)     // TDD\n    {\n        sss_symb = nsymb - 1;\n        pss_symb = 2;\n    }\n    else\n    {\n        sss_symb = (nsymb >> 1) - 2;\n        pss_symb = (nsymb >> 1) - 1;\n    }\n\n    for(aarx = 0; aarx < frame_parms->nb_antennas_rx; aarx++)\n    {\n        if(high_speed_flag == 1)\n        {\n            dl_ch0     = &dl_ch_estimates[aarx][5 + (symbol * (frame_parms->ofdm_symbol_size))];\n            dl_ch1     = &dl_ch_estimates[2 + aarx][5 + (symbol * (frame_parms->ofdm_symbol_size))];\n        }\n        else\n        {\n            dl_ch0     = &dl_ch_estimates[aarx][5];\n            dl_ch1     = &dl_ch_estimates[2 + aarx][5];\n        }\n\n        pmi_loc = pmi_ext;\n        // pointers to extracted RX signals and channel estimates\n        rxF_ext    = &rxdataF_ext[aarx][symbol * (frame_parms->N_RB_DL * 12)];\n        dl_ch0_ext = &dl_ch_estimates_ext[aarx][symbol * (frame_parms->N_RB_DL * 12)];\n        dl_ch1_ext = &dl_ch_estimates_ext[2 + aarx][symbol * (frame_parms->N_RB_DL * 12)];\n\n        for(prb = 0; prb < frame_parms->N_RB_DL; prb++)\n        {\n            skip_half = 0;\n\n            if(prb < 32)\n            {\n                rb_alloc_ind = (rb_alloc[0] >> prb) & 1;\n            }\n            else if(prb < 64)\n            {\n                rb_alloc_ind = (rb_alloc[1] >> (prb - 32)) & 1;\n            }\n            else if(prb < 96)\n            {\n                rb_alloc_ind = (rb_alloc[2] >> (prb - 64)) & 1;\n            }\n            else if(prb < 100)\n            {\n                rb_alloc_ind = (rb_alloc[3] >> (prb - 96)) & 1;\n            }\n            else\n            {\n                rb_alloc_ind = 0;\n            }\n\n            if(rb_alloc_ind == 1)\n            {\n                nb_rb++;\n            }\n\n            if((frame_parms->N_RB_DL & 1) == 0)   // even number of RBs\n            {\n\n                // PBCH\n                if((subframe == 0) &&\n                        (prb >= ((frame_parms->N_RB_DL >> 1) - 3)) &&\n                        (prb < ((frame_parms->N_RB_DL >> 1) + 3)) &&\n                        (l >= (nsymb >> 1)) &&\n                        (l < ((nsymb >> 1) + 4)))\n                {\n                    rb_alloc_ind = 0;\n                    //    printf(\"symbol %d / rb %d: skipping PBCH REs\\n\",symbol,prb);\n                }\n\n                //SSS\n\n                if(((subframe == 0) || (subframe == 5)) &&\n                        (prb >= ((frame_parms->N_RB_DL >> 1) - 3)) &&\n                        (prb < ((frame_parms->N_RB_DL >> 1) + 3)) &&\n                        (l == sss_symb))\n                {\n                    rb_alloc_ind = 0;\n                    //    printf(\"symbol %d / rb %d: skipping SSS REs\\n\",symbol,prb);\n                }\n\n                //PSS in subframe 0/5 if FDD\n                if(frame_parms->frame_type == FDD)     //FDD\n                {\n                    if(((subframe == 0) || (subframe == 5)) &&\n                            (prb >= ((frame_parms->N_RB_DL >> 1) - 3)) &&\n                            (prb < ((frame_parms->N_RB_DL >> 1) + 3)) &&\n                            (l == pss_symb))\n                    {\n                        rb_alloc_ind = 0;\n                        //    printf(\"symbol %d / rb %d: skipping PSS REs\\n\",symbol,prb);\n                    }\n                }\n\n                if((frame_parms->frame_type == TDD) &&\n                        (subframe == 6)) //TDD Subframe 6\n                {\n                    if((prb >= ((frame_parms->N_RB_DL >> 1) - 3)) &&\n                            (prb < ((frame_parms->N_RB_DL >> 1) + 3)) &&\n                            (l == pss_symb))\n                    {\n                        rb_alloc_ind = 0;\n                    }\n                }\n\n                if(rb_alloc_ind == 1)               // PRB is allocated\n                {\n                    prb_off      = 12 * prb;\n                    prb_off2     = 1 + (12 * (prb - (frame_parms->N_RB_DL >> 1)));\n                    dl_ch0p    = dl_ch0 + (12 * prb);\n                    dl_ch1p    = dl_ch1 + (12 * prb);\n\n                    if(prb < (frame_parms->N_RB_DL >> 1))\n                    {\n                        rxF      = &rxdataF[aarx][prb_off +\n                                                  frame_parms->first_carrier_offset +\n                                                  (symbol * (frame_parms->ofdm_symbol_size))];\n                    }\n                    else\n                    {\n                        rxF      = &rxdataF[aarx][prb_off2 +\n                                                  (symbol * (frame_parms->ofdm_symbol_size))];\n                    }\n\n                    /*\n                        if (mimo_mode <= PUSCH_PRECODING1)\n                        pmi_loc = (pmi>>((prb>>2)<<1))&3;\n                        else\n                        pmi_loc=(pmi>>prb)&1;*/\n                    *pmi_loc = get_pmi(frame_parms->N_RB_DL, mimo_mode, pmi, prb);\n                    pmi_loc++;\n\n                    if(pilots == 0)\n                    {\n                        memcpy(dl_ch0_ext, dl_ch0p, 12 * sizeof(int));\n                        memcpy(dl_ch1_ext, dl_ch1p, 12 * sizeof(int));\n                        memcpy(rxF_ext, rxF, 12 * sizeof(int));\n                        dl_ch0_ext += 12;\n                        dl_ch1_ext += 12;\n                        rxF_ext    += 12;\n                    }\n                    else     // pilots==1\n                    {\n                        j = 0;\n\n                        for(i = 0; i < 12; i++)\n                        {\n                            if((i != frame_parms->nushift) &&\n                                    (i != frame_parms->nushift + 3) &&\n                                    (i != frame_parms->nushift + 6) &&\n                                    (i != ((frame_parms->nushift + 9) % 12)))\n                            {\n                                rxF_ext[j] = rxF[i];\n                                //        printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[j],*(1+(short*)&rxF_ext[j]));\n                                dl_ch0_ext[j] = dl_ch0p[i];\n                                dl_ch1_ext[j++] = dl_ch1p[i];\n                            }\n                        }\n\n                        dl_ch0_ext += 8;\n                        dl_ch1_ext += 8;\n                        rxF_ext += 8;\n                    } // pilots==1\n                }\n            }\n            else      // Odd number of RBs\n            {\n\n                // PBCH\n                if((subframe == 0) &&\n                        (prb > ((frame_parms->N_RB_DL >> 1) - 3)) &&\n                        (prb < ((frame_parms->N_RB_DL >> 1) + 3)) &&\n                        (l >= (nsymb >> 1)) &&\n                        (l < ((nsymb >> 1) + 4)))\n                {\n                    rb_alloc_ind = 0;\n                    //    printf(\"symbol %d / rb %d: skipping PBCH REs\\n\",symbol,prb);\n                }\n\n                //SSS\n\n                if(((subframe == 0) || (subframe == 5)) &&\n                        (prb > ((frame_parms->N_RB_DL >> 1) - 3)) &&\n                        (prb < ((frame_parms->N_RB_DL >> 1) + 3)) &&\n                        (l == sss_symb))\n                {\n                    rb_alloc_ind = 0;\n                    //    printf(\"symbol %d / rb %d: skipping SSS REs\\n\",symbol,prb);\n                }\n\n                //PSS in subframe 0/5 if FDD\n                if(frame_parms->frame_type == FDD)     //FDD\n                {\n                    if(((subframe == 0) || (subframe == 5)) &&\n                            (prb > ((frame_parms->N_RB_DL >> 1) - 3)) &&\n                            (prb < ((frame_parms->N_RB_DL >> 1) + 3)) &&\n                            (l == pss_symb))\n                    {\n                        rb_alloc_ind = 0;\n                        //    printf(\"symbol %d / rb %d: skipping PSS REs\\n\",symbol,prb);\n                    }\n                }\n\n                if((frame_parms->frame_type == TDD) &&\n                        ((subframe == 1) || (subframe == 6))) //TDD Subframe 1-6\n                {\n                    if((prb > ((frame_parms->N_RB_DL >> 1) - 3)) &&\n                            (prb < ((frame_parms->N_RB_DL >> 1) + 3)) &&\n                            (l == pss_symb))\n                    {\n                        rb_alloc_ind = 0;\n                    }\n                }\n\n                if(rb_alloc_ind == 1)\n                {\n                    skip_half = 0;\n\n                    //Check if we have to drop half a PRB due to PSS/SSS/PBCH\n                    // skip_half == 0 means full PRB\n                    // skip_half == 1 means first half is used (leftmost half-PRB from PSS/SSS/PBCH)\n                    // skip_half == 2 means second half is used (rightmost half-PRB from PSS/SSS/PBCH)\n                    //PBCH subframe 0, symbols nsymb>>1 ... nsymb>>1 + 3\n                    if((subframe == 0) &&\n                            (prb == ((frame_parms->N_RB_DL >> 1) - 3)) &&\n                            (l >= (nsymb >> 1)) &&\n                            (l < ((nsymb >> 1) + 4)))\n                    {\n                        skip_half = 1;\n                    }\n                    else if((subframe == 0) &&\n                            (prb == ((frame_parms->N_RB_DL >> 1) + 3)) &&\n                            (l >= (nsymb >> 1)) &&\n                            (l < ((nsymb >> 1) + 4)))\n                    {\n                        skip_half = 2;\n                    }\n\n                    //SSS\n                    if(((subframe == 0) || (subframe == 5)) &&\n                            (prb == ((frame_parms->N_RB_DL >> 1) - 3)) &&\n                            (l == sss_symb))\n                    {\n                        skip_half = 1;\n                    }\n                    else if(((subframe == 0) || (subframe == 5)) &&\n                            (prb == ((frame_parms->N_RB_DL >> 1) + 3)) &&\n                            (l == sss_symb))\n                    {\n                        skip_half = 2;\n                    }\n\n                    //PSS Subframe 0,5\n                    if(((frame_parms->frame_type == FDD) &&\n                            (((subframe == 0) || (subframe == 5)))) || //FDD Subframes 0,5\n                            ((frame_parms->frame_type == TDD) &&\n                             (((subframe == 1) || (subframe == 6))))) //TDD Subframes 1,6\n                    {\n                        if((prb == ((frame_parms->N_RB_DL >> 1) - 3)) &&\n                                (l == pss_symb))\n                        {\n                            skip_half = 1;\n                        }\n                        else if((prb == ((frame_parms->N_RB_DL >> 1) + 3)) &&\n                                (l == pss_symb))\n                        {\n                            skip_half = 2;\n                        }\n                    }\n\n                    prb_off      = 12 * prb;\n                    prb_off2     = 7 + (12 * (prb - (frame_parms->N_RB_DL >> 1) - 1));\n                    dl_ch0p      = dl_ch0 + (12 * prb);\n                    dl_ch1p      = dl_ch1 + (12 * prb);\n\n                    if(prb <= (frame_parms->N_RB_DL >> 1))\n                    {\n                        rxF      = &rxdataF[aarx][prb_off +\n                                                  frame_parms->first_carrier_offset +\n                                                  (symbol * (frame_parms->ofdm_symbol_size))];\n                    }\n                    else\n                    {\n                        rxF      = &rxdataF[aarx][prb_off2 +\n                                                  (symbol * (frame_parms->ofdm_symbol_size))];\n                    }\n\n#ifdef DEBUG_DLSCH_DEMOD\n                    printf(\"symbol %d / rb %d: alloc %d skip_half %d (rxF %p, rxF_ext %p) prb_off (%d,%d)\\n\", symbol, prb, rb_alloc_ind, skip_half, rxF, rxF_ext, prb_off, prb_off2);\n#endif\n                    /*  if (mimo_mode <= PUSCH_PRECODING1)\n                        pmi_loc = (pmi>>((prb>>2)<<1))&3;\n                        else\n                        pmi_loc=(pmi>>prb)&1;\n                        // printf(\"symbol_mod %d (pilots %d) rb %d, sb %d, pmi %d (pmi_loc %p,rxF %p, ch00 %p, ch01 %p, rxF_ext %p dl_ch0_ext %p dl_ch1_ext %p)\\n\",symbol_mod,pilots,prb,prb>>2,*pmi_loc,pmi_loc,rxF,dl_ch0, dl_ch1, rxF_ext,dl_ch0_ext,dl_ch1_ext);\n                    */\n                    *pmi_loc = get_pmi(frame_parms->N_RB_DL, mimo_mode, pmi, prb);\n                    pmi_loc++;\n\n                    if(prb != (frame_parms->N_RB_DL >> 1))  // This PRB is not around DC\n                    {\n                        if(pilots == 0)\n                        {\n                            if(skip_half == 1)\n                            {\n                                memcpy(dl_ch0_ext, dl_ch0p, 6 * sizeof(int32_t));\n                                memcpy(dl_ch1_ext, dl_ch1p, 6 * sizeof(int32_t));\n                                memcpy(rxF_ext, rxF, 6 * sizeof(int32_t));\n#ifdef DEBUG_DLSCH_DEMOD\n\n                                for(i = 0; i < 6; i++)\n                                {\n                                    printf(\"extract rb %d, re %d => (%d,%d)\\n\", prb, i, *(short *)&rxF_ext[i], *(1 + (short *)&rxF_ext[i]));\n                                }\n\n#endif\n                                dl_ch0_ext += 6;\n                                dl_ch1_ext += 6;\n                                rxF_ext += 6;\n                            }\n                            else if(skip_half == 2)\n                            {\n                                memcpy(dl_ch0_ext, dl_ch0p + 6, 6 * sizeof(int32_t));\n                                memcpy(dl_ch1_ext, dl_ch1p + 6, 6 * sizeof(int32_t));\n                                memcpy(rxF_ext, rxF + 6, 6 * sizeof(int32_t));\n#ifdef DEBUG_DLSCH_DEMOD\n\n                                for(i = 0; i < 6; i++)\n                                {\n                                    printf(\"extract rb %d, re %d => (%d,%d)\\n\", prb, i, *(short *)&rxF_ext[i], *(1 + (short *)&rxF_ext[i]));\n                                }\n\n#endif\n                                dl_ch0_ext += 6;\n                                dl_ch1_ext += 6;\n                                rxF_ext += 6;\n                            }\n                            else      // skip_half==0\n                            {\n                                memcpy(dl_ch0_ext, dl_ch0p, 12 * sizeof(int32_t));\n                                memcpy(dl_ch1_ext, dl_ch1p, 12 * sizeof(int32_t));\n                                memcpy(rxF_ext, rxF, 12 * sizeof(int32_t));\n#ifdef DEBUG_DLSCH_DEMOD\n\n                                for(i = 0; i < 12; i++)\n                                {\n                                    printf(\"extract rb %d, re %d => (%d,%d)\\n\", prb, i, *(short *)&rxF_ext[i], *(1 + (short *)&rxF_ext[i]));\n                                }\n\n#endif\n                                dl_ch0_ext += 12;\n                                dl_ch1_ext += 12;\n                                rxF_ext += 12;\n                            }\n                        }\n                        else     // pilots=1\n                        {\n                            j = 0;\n\n                            if(skip_half == 1)\n                            {\n                                for(i = 0; i < 6; i++)\n                                {\n                                    if((i != frame_parms->nushift) &&\n                                            (i != ((frame_parms->nushift + 3) % 6)))\n                                    {\n                                        rxF_ext[j] = rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                                        printf(\"(pilots,skip1)extract rb %d, re %d (%d)=> (%d,%d)\\n\", prb, i, j, *(short *)&rxF_ext[j], *(1 + (short *)&rxF_ext[j]));\n#endif\n                                        dl_ch0_ext[j] = dl_ch0p[i];\n                                        dl_ch1_ext[j++] = dl_ch1p[i];\n                                    }\n                                }\n\n                                dl_ch0_ext += 4;\n                                dl_ch1_ext += 4;\n                                rxF_ext += 4;\n                            }\n                            else if(skip_half == 2)\n                            {\n                                for(i = 0; i < 6; i++)\n                                {\n                                    if((i != frame_parms->nushift) &&\n                                            (i != ((frame_parms->nushift + 3) % 6)))\n                                    {\n                                        rxF_ext[j] = rxF[(i + 6)];\n#ifdef DEBUG_DLSCH_DEMOD\n                                        printf(\"(pilots,skip2)extract rb %d, re %d (%d) => (%d,%d)\\n\", prb, i, j, *(short *)&rxF_ext[j], *(1 + (short *)&rxF_ext[j]));\n#endif\n                                        dl_ch0_ext[j] = dl_ch0p[i + 6];\n                                        dl_ch1_ext[j++] = dl_ch1p[i + 6];\n                                    }\n                                }\n\n                                dl_ch0_ext += 4;\n                                dl_ch1_ext += 4;\n                                rxF_ext += 4;\n                            }\n                            else     //skip_half==0\n                            {\n                                for(i = 0; i < 12; i++)\n                                {\n                                    if((i != frame_parms->nushift) &&\n                                            (i != frame_parms->nushift + 3) &&\n                                            (i != frame_parms->nushift + 6) &&\n                                            (i != ((frame_parms->nushift + 9) % 12)))\n                                    {\n                                        rxF_ext[j] = rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                                        printf(\"(pilots)extract rb %d, re %d => (%d,%d)\\n\", prb, i, *(short *)&rxF_ext[j], *(1 + (short *)&rxF_ext[j]));\n#endif\n                                        dl_ch0_ext[j]  = dl_ch0p[i];\n                                        dl_ch1_ext[j++] = dl_ch1p[i];\n                                    }\n                                }\n\n                                dl_ch0_ext += 8;\n                                dl_ch1_ext += 8;\n                                rxF_ext += 8;\n                            } //skip_half==0\n                        } //pilots==1\n                    }\n                    else           // Do middle RB (around DC)\n                    {\n                        if(pilots == 0)\n                        {\n                            memcpy(dl_ch0_ext, dl_ch0p, 6 * sizeof(int32_t));\n                            memcpy(dl_ch1_ext, dl_ch1p, 6 * sizeof(int32_t));\n                            memcpy(rxF_ext, rxF, 6 * sizeof(int32_t));\n#ifdef DEBUG_DLSCH_DEMOD\n\n                            for(i = 0; i < 6; i++)\n                            {\n                                printf(\"extract rb %d, re %d => (%d,%d)\\n\", prb, i, *(short *)&rxF_ext[i], *(1 + (short *)&rxF_ext[i]));\n                            }\n\n#endif\n                            rxF_ext += 6;\n                            dl_ch0_ext += 6;\n                            dl_ch1_ext += 6;\n                            dl_ch0p += 6;\n                            dl_ch1p += 6;\n                            rxF       = &rxdataF[aarx][1 + ((symbol * (frame_parms->ofdm_symbol_size)))];\n                            memcpy(dl_ch0_ext, dl_ch0p, 6 * sizeof(int32_t));\n                            memcpy(dl_ch1_ext, dl_ch1p, 6 * sizeof(int32_t));\n                            memcpy(rxF_ext, rxF, 6 * sizeof(int32_t));\n#ifdef DEBUG_DLSCH_DEMOD\n\n                            for(i = 0; i < 6; i++)\n                            {\n                                printf(\"extract rb %d, re %d => (%d,%d)\\n\", prb, i, *(short *)&rxF_ext[i], *(1 + (short *)&rxF_ext[i]));\n                            }\n\n#endif\n                            rxF_ext += 6;\n                            dl_ch0_ext += 6;\n                            dl_ch1_ext += 6;\n                        }\n                        else     // pilots==1\n                        {\n                            j = 0;\n\n                            for(i = 0; i < 6; i++)\n                            {\n                                if((i != frame_parms->nushift) &&\n                                        (i != ((frame_parms->nushift + 3) % 6)))\n                                {\n                                    dl_ch0_ext[j] = dl_ch0p[i];\n                                    dl_ch1_ext[j] = dl_ch1p[i];\n                                    rxF_ext[j++] = rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                                    printf(\"(pilots)extract rb %d, re %d (%d) => (%d,%d)\\n\", prb, i, j, *(short *)&rxF[i], *(1 + (short *)&rxF[i]));\n#endif\n                                }\n                            }\n\n                            rxF       = &rxdataF[aarx][1 + symbol * (frame_parms->ofdm_symbol_size)];\n\n                            for(; i < 12; i++)\n                            {\n                                if((i != ((frame_parms->nushift + 6) % 12)) &&\n                                        (i != ((frame_parms->nushift + 9) % 12)))\n                                {\n                                    dl_ch0_ext[j] = dl_ch0p[i];\n                                    dl_ch1_ext[j] = dl_ch1p[i];\n                                    rxF_ext[j++] = rxF[i - 6];\n#ifdef DEBUG_DLSCH_DEMOD\n                                    printf(\"(pilots)extract rb %d, re %d (%d) => (%d,%d)\\n\", prb, i, j, *(short *)&rxF[1 + i - 6], *(1 + (short *)&rxF[1 + i - 6]));\n#endif\n                                }\n                            }\n\n                            dl_ch0_ext += 8;\n                            dl_ch1_ext += 8;\n                            rxF_ext += 8;\n                        } //pilots==1\n                    }  // if Middle PRB\n                } // if odd PRB\n            } // if rballoc==1\n        } // for prb\n    } // for aarx\n\n    return(nb_rb / frame_parms->nb_antennas_rx);\n}\n\nunsigned short dlsch_extract_rbs_TM7(int **rxdataF,\n                                     int **dl_bf_ch_estimates,\n                                     int **rxdataF_ext,\n                                     int **dl_bf_ch_estimates_ext,\n                                     unsigned int *rb_alloc,\n                                     unsigned char symbol,\n                                     unsigned char subframe,\n                                     uint32_t high_speed_flag,\n                                     LTE_DL_FRAME_PARMS *frame_parms)\n{\n    unsigned short rb, nb_rb = 0;\n    unsigned char rb_alloc_ind;\n    unsigned char i, aarx, l, nsymb, skip_half = 0, sss_symb, pss_symb = 0;\n    int *dl_ch0, *dl_ch0_ext, *rxF, *rxF_ext;\n    unsigned char symbol_mod, pilots = 0, uespec_pilots = 0, j = 0, poffset = 0, uespec_poffset = 0;\n    int8_t uespec_nushift = frame_parms->Nid_cell % 3;\n    symbol_mod = (symbol >= (7 - frame_parms->Ncp)) ? symbol - (7 - frame_parms->Ncp) : symbol;\n    pilots = ((symbol_mod == 0) || (symbol_mod == (4 - frame_parms->Ncp))) ? 1 : 0;\n    l = symbol;\n    nsymb = (frame_parms->Ncp == NORMAL) ? 14 : 12;\n\n    if(frame_parms->Ncp == 0)\n    {\n        if(symbol == 3 || symbol == 6 || symbol == 9 || symbol == 12)\n        {\n            uespec_pilots = 1;\n        }\n    }\n    else\n    {\n        if(symbol == 4 || symbol == 7 || symbol == 10)\n        {\n            uespec_pilots = 1;\n        }\n    }\n\n    if(frame_parms->frame_type == TDD)   // TDD\n    {\n        sss_symb = nsymb - 1;\n        pss_symb = 2;\n    }\n    else\n    {\n        sss_symb = (nsymb >> 1) - 2;\n        pss_symb = (nsymb >> 1) - 1;\n    }\n\n    if(symbol_mod == (4 - frame_parms->Ncp))\n    {\n        poffset = 3;\n    }\n\n    if((frame_parms->Ncp == 0 && (symbol == 6 || symbol == 12)) || (frame_parms->Ncp == 1 && symbol == 7))\n    {\n        uespec_poffset = 2;\n    }\n\n    for(aarx = 0; aarx < frame_parms->nb_antennas_rx; aarx++)\n    {\n        if(high_speed_flag == 1)\n        {\n            dl_ch0     = &dl_bf_ch_estimates[aarx][symbol * (frame_parms->ofdm_symbol_size)];\n        }\n        else\n        {\n            dl_ch0     = &dl_bf_ch_estimates[aarx][0];\n        }\n\n        dl_ch0_ext = &dl_bf_ch_estimates_ext[aarx][symbol * (frame_parms->N_RB_DL * 12)];\n        rxF_ext    = &rxdataF_ext[aarx][symbol * (frame_parms->N_RB_DL * 12)];\n        rxF        = &rxdataF[aarx][(frame_parms->first_carrier_offset + (symbol * (frame_parms->ofdm_symbol_size)))];\n\n        if((frame_parms->N_RB_DL & 1) == 0) // even number of RBs\n            for(rb = 0; rb < frame_parms->N_RB_DL; rb++)\n            {\n                if(rb < 32)\n                {\n                    rb_alloc_ind = (rb_alloc[0] >> rb) & 1;\n                }\n                else if(rb < 64)\n                {\n                    rb_alloc_ind = (rb_alloc[1] >> (rb - 32)) & 1;\n                }\n                else if(rb < 96)\n                {\n                    rb_alloc_ind = (rb_alloc[2] >> (rb - 64)) & 1;\n                }\n                else if(rb < 100)\n                {\n                    rb_alloc_ind = (rb_alloc[3] >> (rb - 96)) & 1;\n                }\n                else\n                {\n                    rb_alloc_ind = 0;\n                }\n\n                if(rb_alloc_ind == 1)\n                {\n                    nb_rb++;\n                }\n\n                // For second half of RBs skip DC carrier\n                if(rb == (frame_parms->N_RB_DL >> 1))\n                {\n                    rxF       = &rxdataF[aarx][(1 + (symbol * (frame_parms->ofdm_symbol_size)))];\n                    //dl_ch0++;\n                }\n\n                // PBCH\n                if((subframe == 0) && (rb >= ((frame_parms->N_RB_DL >> 1) - 3)) && (rb < ((frame_parms->N_RB_DL >> 1) + 3)) && (l >= nsymb >> 1) && (l < ((nsymb >> 1) + 4)))\n                {\n                    rb_alloc_ind = 0;\n                }\n\n                //SSS\n                if(((subframe == 0) || (subframe == 5)) && (rb >= ((frame_parms->N_RB_DL >> 1) - 3)) && (rb < ((frame_parms->N_RB_DL >> 1) + 3)) && (l == sss_symb))\n                {\n                    rb_alloc_ind = 0;\n                }\n\n                if(frame_parms->frame_type == FDD)\n                {\n                    //PSS\n                    if(((subframe == 0) || (subframe == 5)) && (rb >= ((frame_parms->N_RB_DL >> 1) - 3)) && (rb < ((frame_parms->N_RB_DL >> 1) + 3)) && (l == pss_symb))\n                    {\n                        rb_alloc_ind = 0;\n                    }\n                }\n\n                if((frame_parms->frame_type == TDD) &&\n                        (subframe == 6)) //TDD Subframe 6\n                {\n                    if((rb >= ((frame_parms->N_RB_DL >> 1) - 3)) && (rb < ((frame_parms->N_RB_DL >> 1) + 3)) && (l == pss_symb))\n                    {\n                        rb_alloc_ind = 0;\n                    }\n                }\n\n                if(rb_alloc_ind == 1)\n                {\n                    /*\n                        printf(\"rb %d\\n\",rb);\n                        for (i=0;i<12;i++)\n                        printf(\"(%d %d)\",((short *)dl_ch0)[i<<1],((short*)dl_ch0)[1+(i<<1)]);\n                        printf(\"\\n\");\n                    */\n                    if(pilots == 0 && uespec_pilots == 0)\n                    {\n                        memcpy(dl_ch0_ext, dl_ch0, 12 * sizeof(int));\n\n                        for(i = 0; i < 12; i++)\n                        {\n                            rxF_ext[i] = rxF[i];\n                        }\n\n                        dl_ch0_ext += 12;\n                        rxF_ext += 12;\n                    }\n                    else if(pilots == 1 && uespec_pilots == 0)\n                    {\n                        j = 0;\n\n                        for(i = 0; i < 12; i++)\n                        {\n                            if((i != (frame_parms->nushift + poffset)) &&\n                                    (i != ((frame_parms->nushift + poffset + 6) % 12)))\n                            {\n                                rxF_ext[j] = rxF[i];\n                                dl_ch0_ext[j++] = dl_ch0[i];\n                            }\n                        }\n\n                        dl_ch0_ext += 10;\n                        rxF_ext += 10;\n                    }\n                    else if(pilots == 0 && uespec_pilots == 1)\n                    {\n                        j = 0;\n\n                        for(i = 0; i < 12; i++)\n                        {\n                            if(frame_parms->Ncp == 0)\n                            {\n                                if(i != uespec_nushift + uespec_poffset && i != uespec_nushift + uespec_poffset + 4 && i != (uespec_nushift + uespec_poffset + 8) % 12)\n                                {\n                                    rxF_ext[j] = rxF[i];\n                                    dl_ch0_ext[j++] = dl_ch0[i];\n                                }\n                            }\n                            else\n                            {\n                                if(i != uespec_nushift + uespec_poffset && i != uespec_nushift + uespec_poffset + 3 && i != uespec_nushift + uespec_poffset + 6 && i != (uespec_nushift + uespec_poffset + 9) % 12)\n                                {\n                                    rxF_ext[j] = rxF[i];\n                                    dl_ch0_ext[j++] = dl_ch0[i];\n                                }\n                            }\n                        }\n\n                        dl_ch0_ext += 9 - frame_parms->Ncp;\n                        rxF_ext += 9 - frame_parms->Ncp;\n                    }\n                    else\n                    {\n                        LOG_E(PHY, \"dlsch_extract_rbs_TM7(dl_demodulation.c):pilot or ue spec pilot detection error\\n\");\n                        exit(-1);\n                    }\n                }\n\n                dl_ch0 += 12;\n                rxF += 12;\n            }\n        else     // Odd number of RBs\n        {\n            for(rb = 0; rb < frame_parms->N_RB_DL >> 1; rb++)\n            {\n                skip_half = 0;\n\n                if(rb < 32)\n                {\n                    rb_alloc_ind = (rb_alloc[0] >> rb) & 1;\n                }\n                else if(rb < 64)\n                {\n                    rb_alloc_ind = (rb_alloc[1] >> (rb - 32)) & 1;\n                }\n                else if(rb < 96)\n                {\n                    rb_alloc_ind = (rb_alloc[2] >> (rb - 64)) & 1;\n                }\n                else if(rb < 100)\n                {\n                    rb_alloc_ind = (rb_alloc[3] >> (rb - 96)) & 1;\n                }\n                else\n                {\n                    rb_alloc_ind = 0;\n                }\n\n                if(rb_alloc_ind == 1)\n                {\n                    nb_rb++;\n                }\n\n                // PBCH\n                if((subframe == 0) && (rb > ((frame_parms->N_RB_DL >> 1) - 3)) && (rb < ((frame_parms->N_RB_DL >> 1) + 3)) && (l >= (nsymb >> 1)) && (l < ((nsymb >> 1) + 4)))\n                {\n                    rb_alloc_ind = 0;\n                }\n\n                //PBCH subframe 0, symbols nsymb>>1 ... nsymb>>1 + 3\n                if((subframe == 0) && (rb == ((frame_parms->N_RB_DL >> 1) - 3)) && (l >= (nsymb >> 1)) && (l < ((nsymb >> 1) + 4)))\n                {\n                    skip_half = 1;\n                }\n                else if((subframe == 0) && (rb == ((frame_parms->N_RB_DL >> 1) + 3)) && (l >= (nsymb >> 1)) && (l < ((nsymb >> 1) + 4)))\n                {\n                    skip_half = 2;\n                }\n\n                //SSS\n\n                if(((subframe == 0) || (subframe == 5)) &&\n                        (rb > ((frame_parms->N_RB_DL >> 1) - 3)) &&\n                        (rb < ((frame_parms->N_RB_DL >> 1) + 3)) &&\n                        (l == sss_symb))\n                {\n                    rb_alloc_ind = 0;\n                }\n\n                //SSS\n                if(((subframe == 0) || (subframe == 5)) &&\n                        (rb == ((frame_parms->N_RB_DL >> 1) - 3)) &&\n                        (l == sss_symb))\n                {\n                    skip_half = 1;\n                }\n                else if(((subframe == 0) || (subframe == 5)) &&\n                        (rb == ((frame_parms->N_RB_DL >> 1) + 3)) &&\n                        (l == sss_symb))\n                {\n                    skip_half = 2;\n                }\n\n                //PSS in subframe 0/5 if FDD\n                if(frame_parms->frame_type == FDD)     //FDD\n                {\n                    if(((subframe == 0) || (subframe == 5)) && (rb > ((frame_parms->N_RB_DL >> 1) - 3)) && (rb < ((frame_parms->N_RB_DL >> 1) + 3)) && (l == pss_symb))\n                    {\n                        rb_alloc_ind = 0;\n                    }\n\n                    if(((subframe == 0) || (subframe == 5)) && (rb == ((frame_parms->N_RB_DL >> 1) - 3)) && (l == pss_symb))\n                    {\n                        skip_half = 1;\n                    }\n                    else if(((subframe == 0) || (subframe == 5)) && (rb == ((frame_parms->N_RB_DL >> 1) + 3)) && (l == pss_symb))\n                    {\n                        skip_half = 2;\n                    }\n                }\n\n                if((frame_parms->frame_type == TDD) && ((subframe == 1) || (subframe == 6))) //TDD Subframe 1 and 6\n                {\n                    if((rb > ((frame_parms->N_RB_DL >> 1) - 3)) && (rb < ((frame_parms->N_RB_DL >> 1) + 3)) && (l == pss_symb))\n                    {\n                        rb_alloc_ind = 0;\n                    }\n\n                    if((rb == ((frame_parms->N_RB_DL >> 1) - 3)) && (l == pss_symb))\n                    {\n                        skip_half = 1;\n                    }\n                    else if((rb == ((frame_parms->N_RB_DL >> 1) + 3)) && (l == pss_symb))\n                    {\n                        skip_half = 2;\n                    }\n                }\n\n                if(rb_alloc_ind == 1)\n                {\n#ifdef DEBUG_DLSCH_DEMOD\n                    printf(\"rb %d/symbol %d pilots %d, uespec_pilots %d, (skip_half %d)\\n\", rb, l, pilots, uespec_pilots, skip_half);\n#endif\n\n                    if(pilots == 0 && uespec_pilots == 0)\n                    {\n                        //printf(\"Extracting w/o pilots (symbol %d, rb %d, skip_half %d)\\n\",l,rb,skip_half);\n                        if(skip_half == 1)\n                        {\n                            memcpy(dl_ch0_ext, dl_ch0, 6 * sizeof(int));\n\n                            for(i = 0; i < 6; i++)\n                            {\n                                rxF_ext[i] = rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                                printf(\"extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[i], *(1 + (short *)&rxF_ext[i]));\n#endif\n                            }\n\n                            dl_ch0_ext += 6;\n                            rxF_ext += 6;\n                        }\n                        else if(skip_half == 2)\n                        {\n                            memcpy(dl_ch0_ext, dl_ch0 + 6, 6 * sizeof(int));\n\n                            for(i = 0; i < 6; i++)\n                            {\n                                rxF_ext[i] = rxF[(i + 6)];\n#ifdef DEBUG_DLSCH_DEMOD\n                                printf(\"extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[i], *(1 + (short *)&rxF_ext[i]));\n#endif\n                            }\n\n                            dl_ch0_ext += 6;\n                            rxF_ext += 6;\n                        }\n                        else\n                        {\n                            memcpy(dl_ch0_ext, dl_ch0, 12 * sizeof(int));\n\n                            for(i = 0; i < 12; i++)\n                            {\n                                rxF_ext[i] = rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                                printf(\"extract symbol %d rb %d, re %d => (%d,%d)\\n\", symbol, rb, i, *(short *)&rxF[i], *(1 + (short *)&rxF[i]));\n#endif\n                            }\n\n                            dl_ch0_ext += 12;\n                            rxF_ext += 12;\n                        }\n                    }\n                    else if(pilots == 1 && uespec_pilots == 0)\n                    {\n                        // printf(\"Extracting with pilots (symbol %d, rb %d, skip_half %d)\\n\",l,rb,skip_half);\n                        j = 0;\n\n                        if(skip_half == 1)\n                        {\n                            for(i = 0; i < 6; i++)\n                            {\n                                if(i != ((frame_parms->nushift + poffset) % 6))\n                                {\n                                    rxF_ext[j] = rxF[i];\n                                    dl_ch0_ext[j++] = dl_ch0[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                                    printf(\"extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[i], *(1 + (short *)&rxF_ext[i]));\n#endif\n                                }\n                            }\n\n                            dl_ch0_ext += 5;\n                            rxF_ext += 5;\n                        }\n                        else if(skip_half == 2)\n                        {\n                            for(i = 0; i < 6; i++)\n                            {\n                                if(i != ((frame_parms->nushift + poffset) % 6))\n                                {\n                                    rxF_ext[j] = rxF[(i + 6)];\n                                    dl_ch0_ext[j++] = dl_ch0[i + 6];\n#ifdef DEBUG_DLSCH_DEMOD\n                                    printf(\"extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[i], *(1 + (short *)&rxF_ext[i]));\n#endif\n                                }\n                            }\n\n                            dl_ch0_ext += 5;\n                            rxF_ext += 5;\n                        }\n                        else\n                        {\n                            for(i = 0; i < 12; i++)\n                            {\n                                if((i != (frame_parms->nushift + poffset)) &&\n                                        (i != ((frame_parms->nushift + poffset + 6) % 12)))\n                                {\n                                    rxF_ext[j] = rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                                    printf(\"extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[j], *(1 + (short *)&rxF_ext[j]));\n#endif\n                                    dl_ch0_ext[j++] = dl_ch0[i];\n                                }\n                            }\n\n                            dl_ch0_ext += 10;\n                            rxF_ext += 10;\n                        }\n                    }\n                    else if(pilots == 0 && uespec_pilots == 1)\n                    {\n                        //printf(\"Extracting with uespec pilots (symbol %d, rb %d, skip_half %d)\\n\",l,rb,skip_half);\n                        j = 0;\n\n                        if(skip_half == 1)\n                        {\n                            if(frame_parms->Ncp == 0)\n                            {\n                                for(i = 0; i < 6; i++)\n                                {\n                                    if(i != uespec_nushift + uespec_poffset && i != uespec_nushift + uespec_poffset + 4 && i != (uespec_nushift + uespec_poffset + 8) % 12)\n                                    {\n                                        rxF_ext[j] = rxF[i];\n                                        dl_ch0_ext[j++] = dl_ch0[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                                        printf(\"extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[i], *(1 + (short *)&rxF_ext[i]));\n#endif\n                                    }\n                                }\n\n                                dl_ch0_ext += 6 - (uespec_nushift + uespec_poffset < 6) - (uespec_nushift + uespec_poffset + 4 < 6) - ((uespec_nushift + uespec_poffset + 8) % 12 < 6);\n                                rxF_ext += 6 - (uespec_nushift + uespec_poffset < 6) - (uespec_nushift + uespec_poffset + 4 < 6) - ((uespec_nushift + uespec_poffset + 8) % 12 < 6);\n                            }\n                            else\n                            {\n                                for(i = 0; i < 6; i++)\n                                {\n                                    if(i != uespec_nushift + uespec_poffset && i != uespec_nushift + uespec_poffset + 3 && i != uespec_nushift + uespec_poffset + 6 && i != (uespec_nushift + uespec_poffset + 9) % 12)\n                                    {\n                                        rxF_ext[j] = rxF[i];\n                                        dl_ch0_ext[j++] = dl_ch0[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                                        printf(\"extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[i], *(1 + (short *)&rxF_ext[i]));\n#endif\n                                    }\n                                }\n\n                                dl_ch0_ext += 4;\n                                rxF_ext += 4;\n                            }\n                        }\n                        else if(skip_half == 2)\n                        {\n                            if(frame_parms->Ncp == 0)\n                            {\n                                for(i = 0; i < 6; i++)\n                                {\n                                    if(i != uespec_nushift + uespec_poffset && i != uespec_nushift + uespec_poffset + 4 && i != (uespec_nushift + uespec_poffset + 8) % 12)\n                                    {\n                                        rxF_ext[j] = rxF[(i + 6)];\n                                        dl_ch0_ext[j++] = dl_ch0[i + 6];\n#ifdef DEBUG_DLSCH_DEMOD\n                                        printf(\"extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[i], *(1 + (short *)&rxF_ext[i]));\n#endif\n                                    }\n                                }\n\n                                dl_ch0_ext += 6 - (uespec_nushift + uespec_poffset > 6) - (uespec_nushift + uespec_poffset + 4 > 6) - ((uespec_nushift + uespec_poffset + 8) % 12 > 6);\n                                rxF_ext += 6 - (uespec_nushift + uespec_poffset > 6) - (uespec_nushift + uespec_poffset + 4 > 6) - ((uespec_nushift + uespec_poffset + 8) % 12 > 6);\n                            }\n                            else\n                            {\n                                for(i = 0; i < 6; i++)\n                                {\n                                    if(i != uespec_nushift + uespec_poffset && i != uespec_nushift + uespec_poffset + 3 && i != uespec_nushift + uespec_poffset + 6 && i != (uespec_nushift + uespec_poffset + 9) % 12)\n                                    {\n                                        rxF_ext[j] = rxF[(i + 6)];\n                                        dl_ch0_ext[j++] = dl_ch0[i + 6];\n#ifdef DEBUG_DLSCH_DEMOD\n                                        printf(\"extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[i], *(1 + (short *)&rxF_ext[i]));\n#endif\n                                    }\n                                }\n\n                                dl_ch0_ext += 4;\n                                rxF_ext += 4;\n                            }\n                        }\n                        else\n                        {\n                            for(i = 0; i < 12; i++)\n                            {\n                                if(frame_parms->Ncp == 0)\n                                {\n                                    if(i != uespec_nushift + uespec_poffset && i != uespec_nushift + uespec_poffset + 4 && i != (uespec_nushift + uespec_poffset + 8) % 12)\n                                    {\n                                        rxF_ext[j] = rxF[i];\n                                        dl_ch0_ext[j++] = dl_ch0[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                                        printf(\"extract symbol %d, rb %d, re %d, j %d => (%d,%d)\\n\",\n                                               symbol, rb, i, j - 1, *(short *)&dl_ch0[j], *(1 + (short *)&dl_ch0[i]));\n#endif\n                                    }\n                                }\n                                else\n                                {\n                                    if(i != uespec_nushift + uespec_poffset && i != uespec_nushift + uespec_poffset + 3 && i != uespec_nushift + uespec_poffset + 6 && i != (uespec_nushift + uespec_poffset + 9) % 12)\n                                    {\n                                        rxF_ext[j] = rxF[i];\n                                        dl_ch0_ext[j++] = dl_ch0[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                                        printf(\"extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[i], *(1 + (short *)&rxF_ext[i]));\n#endif\n                                    }\n                                }\n                            }\n\n                            dl_ch0_ext += 9 - frame_parms->Ncp;\n                            rxF_ext += 9 - frame_parms->Ncp;\n                        }\n                    }\n                    else\n                    {\n                        LOG_E(PHY, \"dlsch_extract_rbs_TM7(dl_demodulation.c):pilot or ue spec pilot detection error\\n\");\n                        exit(-1);\n                    }\n                }\n\n                dl_ch0 += 12;\n                rxF += 12;\n            } // first half loop\n\n            // Do middle RB (around DC)\n            if(rb < 32)\n            {\n                rb_alloc_ind = (rb_alloc[0] >> rb) & 1;\n            }\n            else if(rb < 64)\n            {\n                rb_alloc_ind = (rb_alloc[1] >> (rb - 32)) & 1;\n            }\n            else if(rb < 96)\n            {\n                rb_alloc_ind = (rb_alloc[2] >> (rb - 64)) & 1;\n            }\n            else if(rb < 100)\n            {\n                rb_alloc_ind = (rb_alloc[3] >> (rb - 96)) & 1;\n            }\n            else\n            {\n                rb_alloc_ind = 0;\n            }\n\n            if(rb_alloc_ind == 1)\n            {\n                nb_rb++;\n            }\n\n            // PBCH\n            if((subframe == 0) && (rb >= ((frame_parms->N_RB_DL >> 1) - 3)) && (rb < ((frame_parms->N_RB_DL >> 1) + 3)) && (l >= (nsymb >> 1)) && (l < ((nsymb >> 1) + 4)))\n            {\n                rb_alloc_ind = 0;\n            }\n\n            //SSS\n            if(((subframe == 0) || (subframe == 5)) && (rb >= ((frame_parms->N_RB_DL >> 1) - 3)) && (rb < ((frame_parms->N_RB_DL >> 1) + 3)) && (l == sss_symb))\n            {\n                rb_alloc_ind = 0;\n            }\n\n            if(frame_parms->frame_type == FDD)\n            {\n                //PSS\n                if(((subframe == 0) || (subframe == 5)) && (rb >= ((frame_parms->N_RB_DL >> 1) - 3)) && (rb < ((frame_parms->N_RB_DL >> 1) + 3)) && (l == pss_symb))\n                {\n                    rb_alloc_ind = 0;\n                }\n            }\n\n            if((frame_parms->frame_type == TDD) && ((subframe == 1) || (subframe == 6)))\n            {\n                //PSS\n                if((rb > ((frame_parms->N_RB_DL >> 1) - 3)) && (rb < ((frame_parms->N_RB_DL >> 1) + 3)) && (l == pss_symb))\n                {\n                    rb_alloc_ind = 0;\n                }\n            }\n\n            //printf(\"dlch_ext %d\\n\",dl_ch0_ext-&dl_ch_estimates_ext[aarx][0]);\n            //printf(\"DC rb %d (%p)\\n\",rb,rxF);\n            if(rb_alloc_ind == 1)\n            {\n                //printf(\"rb %d/symbol %d (skip_half %d)\\n\",rb,l,skip_half);\n                if(pilots == 0 && uespec_pilots == 0)\n                {\n                    for(i = 0; i < 6; i++)\n                    {\n                        dl_ch0_ext[i] = dl_ch0[i];\n                        rxF_ext[i] = rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                        printf(\"extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[i], *(1 + (short *)&rxF_ext[i]));\n#endif\n                    }\n\n                    rxF       = &rxdataF[aarx][((symbol * (frame_parms->ofdm_symbol_size)))];\n\n                    for(; i < 12; i++)\n                    {\n                        dl_ch0_ext[i] = dl_ch0[i];\n                        rxF_ext[i] = rxF[(1 + i - 6)];\n#ifdef DEBUG_DLSCH_DEMOD\n                        printf(\"extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[i], *(1 + (short *)&rxF_ext[i]));\n#endif\n                    }\n\n                    dl_ch0_ext += 12;\n                    rxF_ext += 12;\n                }\n                else if(pilots == 1 && uespec_pilots == 0) // pilots==1\n                {\n                    j = 0;\n\n                    for(i = 0; i < 6; i++)\n                    {\n                        if(i != ((frame_parms->nushift + poffset) % 6))\n                        {\n                            dl_ch0_ext[j] = dl_ch0[i];\n                            rxF_ext[j++] = rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                            printf(\"extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[i], *(1 + (short *)&rxF_ext[i]));\n#endif\n                        }\n                    }\n\n                    rxF       = &rxdataF[aarx][((symbol * (frame_parms->ofdm_symbol_size)))];\n\n                    for(; i < 12; i++)\n                    {\n                        if(i != ((frame_parms->nushift + 6 + poffset) % 12))\n                        {\n                            dl_ch0_ext[j] = dl_ch0[i];\n                            rxF_ext[j++] = rxF[(1 + i - 6)];\n#ifdef DEBUG_DLSCH_DEMOD\n                            printf(\"extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[i], *(1 + (short *)&rxF_ext[i]));\n#endif\n                        }\n                    }\n\n                    dl_ch0_ext += 10;\n                    rxF_ext += 10;\n                }\n                else if(pilots == 0 && uespec_pilots == 1)\n                {\n                    j = 0;\n\n                    for(i = 0; i < 6; i++)\n                    {\n                        if(frame_parms->Ncp == 0)\n                        {\n                            if(i != uespec_nushift + uespec_poffset && i != uespec_nushift + uespec_poffset + 4 && i != (uespec_nushift + uespec_poffset + 8) % 12)\n                            {\n                                dl_ch0_ext[j] = dl_ch0[i];\n                                rxF_ext[j++] = rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                                printf(\"extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[i], *(1 + (short *)&rxF_ext[i]));\n#endif\n                            }\n                        }\n                        else\n                        {\n                            if(i != uespec_nushift + uespec_poffset && i != uespec_nushift + uespec_poffset + 3 && i != uespec_nushift + uespec_poffset + 6 && i != (uespec_nushift + uespec_poffset + 9) % 12)\n                            {\n                                dl_ch0_ext[j] = dl_ch0[i];\n                                rxF_ext[j++] = rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                                printf(\"extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[i], *(1 + (short *)&rxF_ext[i]));\n#endif\n                            }\n                        }\n                    }\n\n                    rxF       = &rxdataF[aarx][((symbol * (frame_parms->ofdm_symbol_size)))];\n\n                    for(; i < 12; i++)\n                    {\n                        if(frame_parms->Ncp == 0)\n                        {\n                            if(i != uespec_nushift + uespec_poffset && i != uespec_nushift + uespec_poffset + 4 && i != (uespec_nushift + uespec_poffset + 8) % 12)\n                            {\n                                dl_ch0_ext[j] = dl_ch0[i];\n                                rxF_ext[j++] = rxF[(1 + i - 6)];\n#ifdef DEBUG_DLSCH_DEMOD\n                                printf(\"extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[i], *(1 + (short *)&rxF_ext[i]));\n#endif\n                            }\n                        }\n                        else\n                        {\n                            if(i != uespec_nushift + uespec_poffset && i != uespec_nushift + uespec_poffset + 3 && i != uespec_nushift + uespec_poffset + 6 && i != (uespec_nushift + uespec_poffset + 9) % 12)\n                            {\n                                dl_ch0_ext[j] = dl_ch0[i];\n                                rxF_ext[j++] = rxF[(1 + i - 6)];\n#ifdef DEBUG_DLSCH_DEMOD\n                                printf(\"extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[i], *(1 + (short *)&rxF_ext[i]));\n#endif\n                            }\n                        }\n                    }\n\n                    dl_ch0_ext += 9 - frame_parms->Ncp;\n                    rxF_ext += 9 - frame_parms->Ncp;\n                }// symbol_mod==0\n            } // rballoc==1\n            else\n            {\n                rxF       = &rxdataF[aarx][((symbol * (frame_parms->ofdm_symbol_size)))];\n            }\n\n            dl_ch0 += 12;\n            rxF += 7;\n            rb++;\n\n            for(; rb < frame_parms->N_RB_DL; rb++)\n            {\n                //  printf(\"dlch_ext %d\\n\",dl_ch0_ext-&dl_ch_estimates_ext[aarx][0]);\n                //  printf(\"rb %d (%p)\\n\",rb,rxF);\n                skip_half = 0;\n\n                if(rb < 32)\n                {\n                    rb_alloc_ind = (rb_alloc[0] >> rb) & 1;\n                }\n                else if(rb < 64)\n                {\n                    rb_alloc_ind = (rb_alloc[1] >> (rb - 32)) & 1;\n                }\n                else if(rb < 96)\n                {\n                    rb_alloc_ind = (rb_alloc[2] >> (rb - 64)) & 1;\n                }\n                else if(rb < 100)\n                {\n                    rb_alloc_ind = (rb_alloc[3] >> (rb - 96)) & 1;\n                }\n                else\n                {\n                    rb_alloc_ind = 0;\n                }\n\n                if(rb_alloc_ind == 1)\n                {\n                    nb_rb++;\n                }\n\n                // PBCH\n                if((subframe == 0) && (rb > ((frame_parms->N_RB_DL >> 1) - 3)) && (rb < ((frame_parms->N_RB_DL >> 1) + 3)) && (l >= nsymb >> 1) && (l < ((nsymb >> 1) + 4)))\n                {\n                    rb_alloc_ind = 0;\n                }\n\n                //PBCH subframe 0, symbols nsymb>>1 ... nsymb>>1 + 3\n                if((subframe == 0) && (rb == ((frame_parms->N_RB_DL >> 1) - 3)) && (l >= (nsymb >> 1)) && (l < ((nsymb >> 1) + 4)))\n                {\n                    skip_half = 1;\n                }\n                else if((subframe == 0) && (rb == ((frame_parms->N_RB_DL >> 1) + 3)) && (l >= (nsymb >> 1)) && (l < ((nsymb >> 1) + 4)))\n                {\n                    skip_half = 2;\n                }\n\n                //SSS\n                if(((subframe == 0) || (subframe == 5)) && (rb > ((frame_parms->N_RB_DL >> 1) - 3)) && (rb < ((frame_parms->N_RB_DL >> 1) + 3)) && (l == sss_symb))\n                {\n                    rb_alloc_ind = 0;\n                }\n\n                //SSS\n                if(((subframe == 0) || (subframe == 5)) && (rb == ((frame_parms->N_RB_DL >> 1) - 3)) && (l == sss_symb))\n                {\n                    skip_half = 1;\n                }\n                else if(((subframe == 0) || (subframe == 5)) && (rb == ((frame_parms->N_RB_DL >> 1) + 3)) && (l == sss_symb))\n                {\n                    skip_half = 2;\n                }\n\n                //PSS\n                if(frame_parms->frame_type == FDD)\n                {\n                    if(((subframe == 0) || (subframe == 5)) && (rb > ((frame_parms->N_RB_DL >> 1) - 3)) && (rb < ((frame_parms->N_RB_DL >> 1) + 3)) && (l == pss_symb))\n                    {\n                        rb_alloc_ind = 0;\n                    }\n\n                    if(((subframe == 0) || (subframe == 5)) && (rb == ((frame_parms->N_RB_DL >> 1) - 3)) && (l == pss_symb))\n                    {\n                        skip_half = 1;\n                    }\n                    else if(((subframe == 0) || (subframe == 5)) && (rb == ((frame_parms->N_RB_DL >> 1) + 3)) && (l == pss_symb))\n                    {\n                        skip_half = 2;\n                    }\n                }\n\n                if((frame_parms->frame_type == TDD) && ((subframe == 1) || (subframe == 6))) //TDD Subframe 1 and 6\n                {\n                    if((rb > ((frame_parms->N_RB_DL >> 1) - 3)) && (rb < ((frame_parms->N_RB_DL >> 1) + 3)) && (l == pss_symb))\n                    {\n                        rb_alloc_ind = 0;\n                    }\n\n                    if((rb == ((frame_parms->N_RB_DL >> 1) - 3)) && (l == pss_symb))\n                    {\n                        skip_half = 1;\n                    }\n                    else if((rb == ((frame_parms->N_RB_DL >> 1) + 3)) && (l == pss_symb))\n                    {\n                        skip_half = 2;\n                    }\n                }\n\n                if(rb_alloc_ind == 1)\n                {\n#ifdef DEBUG_DLSCH_DEMOD\n                    printf(\"rb %d/symbol %d (skip_half %d)\\n\", rb, l, skip_half);\n#endif\n\n                    /*\n                        printf(\"rb %d\\n\",rb);\n                        for (i=0;i<12;i++)\n                        printf(\"(%d %d)\",((short *)dl_ch0)[i<<1],((short*)dl_ch0)[1+(i<<1)]);\n                        printf(\"\\n\");\n                    */\n                    if(pilots == 0 && uespec_pilots == 0)\n                    {\n                        //printf(\"Extracting w/o pilots (symbol %d, rb %d, skip_half %d)\\n\",l,rb,skip_half);\n                        if(skip_half == 1)\n                        {\n                            memcpy(dl_ch0_ext, dl_ch0, 6 * sizeof(int));\n\n                            for(i = 0; i < 6; i++)\n                            {\n                                rxF_ext[i] = rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                                printf(\"extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[i], *(1 + (short *)&rxF_ext[i]));\n#endif\n                            }\n\n                            dl_ch0_ext += 6;\n                            rxF_ext += 6;\n                        }\n                        else if(skip_half == 2)\n                        {\n                            memcpy(dl_ch0_ext, dl_ch0 + 6, 6 * sizeof(int));\n\n                            for(i = 0; i < 6; i++)\n                            {\n                                rxF_ext[i] = rxF[i + 6];\n#ifdef DEBUG_DLSCH_DEMOD\n                                printf(\"extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[i], *(1 + (short *)&rxF_ext[i]));\n#endif\n                            }\n\n                            dl_ch0_ext += 6;\n                            rxF_ext += 6;\n                        }\n                        else\n                        {\n                            memcpy(dl_ch0_ext, dl_ch0, 12 * sizeof(int));\n                            //printf(\"symbol %d, extract rb %d, => (%d,%d)\\n\",symbol,rb,*(short *)&dl_ch0[j],*(1+(short*)&dl_ch0[i]));\n\n                            for(i = 0; i < 12; i++)\n                            {\n                                rxF_ext[i] = rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                                printf(\"extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[i], *(1 + (short *)&rxF_ext[i]));\n#endif\n                            }\n\n                            dl_ch0_ext += 12;\n                            rxF_ext += 12;\n                        }\n                    }\n                    else if(pilots == 1 && uespec_pilots == 0)\n                    {\n                        //printf(\"Extracting with pilots (symbol %d, rb %d, skip_half %d)\\n\",l,rb,skip_half);\n                        j = 0;\n\n                        if(skip_half == 1)\n                        {\n                            for(i = 0; i < 6; i++)\n                            {\n                                if(i != ((frame_parms->nushift + poffset) % 6))\n                                {\n                                    rxF_ext[j] = rxF[i];\n                                    dl_ch0_ext[j++] = dl_ch0[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                                    printf(\"extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[i], *(1 + (short *)&rxF_ext[i]));\n#endif\n                                }\n                            }\n\n                            dl_ch0_ext += 5;\n                            rxF_ext += 5;\n                        }\n                        else if(skip_half == 2)\n                        {\n                            for(i = 0; i < 6; i++)\n                            {\n                                if(i != ((frame_parms->nushift + poffset) % 6))\n                                {\n                                    rxF_ext[j] = rxF[(i + 6)];\n                                    dl_ch0_ext[j++] = dl_ch0[i + 6];\n#ifdef DEBUG_DLSCH_DEMOD\n                                    printf(\"extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[i], *(1 + (short *)&rxF_ext[i]));\n#endif\n                                }\n                            }\n\n                            dl_ch0_ext += 5;\n                            rxF_ext += 5;\n                        }\n                        else\n                        {\n                            for(i = 0; i < 12; i++)\n                            {\n                                if((i != (frame_parms->nushift + poffset)) &&\n                                        (i != ((frame_parms->nushift + poffset + 6) % 12)))\n                                {\n                                    rxF_ext[j] = rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                                    printf(\"extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[j], *(1 + (short *)&rxF_ext[j]));\n#endif\n                                    dl_ch0_ext[j++] = dl_ch0[i];\n                                }\n                            }\n\n                            dl_ch0_ext += 10;\n                            rxF_ext += 10;\n                        }\n                    }\n                    else if(pilots == 0 && uespec_pilots == 1)\n                    {\n                        j = 0;\n\n                        if(skip_half == 1)\n                        {\n                            if(frame_parms->Ncp == 0)\n                            {\n                                for(i = 0; i < 6; i++)\n                                {\n                                    if(i != uespec_nushift + uespec_poffset && i != uespec_nushift + uespec_poffset + 4 && i != (uespec_nushift + uespec_poffset + 8) % 12)\n                                    {\n                                        rxF_ext[j] = rxF[i];\n                                        dl_ch0_ext[j++] = dl_ch0[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                                        printf(\"extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[i], *(1 + (short *)&rxF_ext[i]));\n#endif\n                                    }\n                                }\n\n                                dl_ch0_ext += 6 - (uespec_nushift + uespec_poffset < 6) - (uespec_nushift + uespec_poffset + 4 < 6) - ((uespec_nushift + uespec_poffset + 8) % 12 < 6);\n                                rxF_ext += 6 - (uespec_nushift + uespec_poffset < 6) - (uespec_nushift + uespec_poffset + 4 < 6) - ((uespec_nushift + uespec_poffset + 8) % 12 < 6);\n                            }\n                            else\n                            {\n                                for(i = 0; i < 6; i++)\n                                {\n                                    if(i != uespec_nushift + uespec_poffset && i != uespec_nushift + uespec_poffset + 3 && i != uespec_nushift + uespec_poffset + 6 && i != (uespec_nushift + uespec_poffset + 9) % 12)\n                                    {\n                                        rxF_ext[j] = rxF[i];\n                                        dl_ch0_ext[j++] = dl_ch0[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                                        printf(\"extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[i], *(1 + (short *)&rxF_ext[i]));\n#endif\n                                    }\n                                }\n\n                                dl_ch0_ext += 4;\n                                rxF_ext += 4;\n                            }\n                        }\n                        else if(skip_half == 2)\n                        {\n                            if(frame_parms->Ncp == 0)\n                            {\n                                for(i = 0; i < 6; i++)\n                                {\n                                    if(i != uespec_nushift + uespec_poffset && i != uespec_nushift + uespec_poffset + 4 && i != (uespec_nushift + uespec_poffset + 8) % 12)\n                                    {\n                                        rxF_ext[j] = rxF[i + 6];\n                                        dl_ch0_ext[j++] = dl_ch0[i + 6];\n#ifdef DEBUG_DLSCH_DEMOD\n                                        printf(\"extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[i], *(1 + (short *)&rxF_ext[i]));\n#endif\n                                    }\n                                }\n\n                                dl_ch0_ext += 6 - (uespec_nushift + uespec_poffset > 6) - (uespec_nushift + uespec_poffset + 4 > 6) - ((uespec_nushift + uespec_poffset + 8) % 12 > 6);\n                                rxF_ext += 6 - (uespec_nushift + uespec_poffset > 6) - (uespec_nushift + uespec_poffset + 4 > 6) - ((uespec_nushift + uespec_poffset + 8) % 12 > 6);\n                            }\n                            else\n                            {\n                                for(i = 0; i < 6; i++)\n                                {\n                                    if(i != uespec_nushift + uespec_poffset && i != uespec_nushift + uespec_poffset + 3 && i != uespec_nushift + uespec_poffset + 6 && i != (uespec_nushift + uespec_poffset + 9) % 12)\n                                    {\n                                        rxF_ext[j] = rxF[(i + 6)];\n                                        dl_ch0_ext[j++] = dl_ch0[i + 6];\n#ifdef DEBUG_DLSCH_DEMOD\n                                        printf(\"extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[i], *(1 + (short *)&rxF_ext[i]));\n#endif\n                                    }\n                                }\n\n                                dl_ch0_ext += 4;\n                                rxF_ext += 4;\n                            }\n                        }\n                        else\n                        {\n                            for(i = 0; i < 12; i++)\n                            {\n                                if(frame_parms->Ncp == 0)\n                                {\n                                    if(i != uespec_nushift + uespec_poffset && i != uespec_nushift + uespec_poffset + 4 && i != (uespec_nushift + uespec_poffset + 8) % 12)\n                                    {\n                                        rxF_ext[j] = rxF[i];\n                                        dl_ch0_ext[j++] = dl_ch0[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                                        printf(\"extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[i], *(1 + (short *)&rxF_ext[i]));\n#endif\n                                    }\n                                }\n                                else\n                                {\n                                    if(i != uespec_nushift + uespec_poffset && i != uespec_nushift + uespec_poffset + 3 && i != uespec_nushift + uespec_poffset + 6 && i != (uespec_nushift + uespec_poffset + 9) % 12)\n                                    {\n                                        rxF_ext[j] = rxF[i];\n                                        dl_ch0_ext[j++] = dl_ch0[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                                        printf(\"extract rb %d, re %d => (%d,%d)\\n\", rb, i, *(short *)&rxF_ext[i], *(1 + (short *)&rxF_ext[i]));\n#endif\n                                    }\n                                }\n                            }\n\n                            dl_ch0_ext += 9 - frame_parms->Ncp;\n                            rxF_ext += 9 - frame_parms->Ncp;\n                        }\n                    }// pilots=0\n                }\n\n                dl_ch0 += 12;\n                rxF += 12;\n            }\n        }\n    }\n\n    _mm_empty();\n    _m_empty();\n    return(nb_rb / frame_parms->nb_antennas_rx);\n}\n\n//==============================================================================================\n\nvoid dump_dlsch2(PHY_VARS_UE *ue, uint8_t eNB_id, uint8_t subframe, unsigned int *coded_bits_per_codeword, int round,  unsigned char harq_pid)\n{\n#define NSYMB  ((ue->frame_parms.Ncp == 0) ? 14 : 12)\n    char fname[32], vname[32];\n    sprintf(fname, \"dlsch%d_rxF_r%d_ext0.m\", eNB_id, round);\n    sprintf(vname, \"dl%d_rxF_r%d_ext0\", eNB_id, round);\n    LOG_M(fname, vname, ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->rxdataF_ext[0],\n          12 * (ue->frame_parms.N_RB_DL)*NSYMB, 1, 1);\n\n    if(ue->frame_parms.nb_antennas_rx > 1)\n    {\n        sprintf(fname, \"dlsch%d_rxF_r%d_ext1.m\", eNB_id, round);\n        sprintf(vname, \"dl%d_rxF_r%d_ext1\", eNB_id, round);\n        LOG_M(fname, vname, ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->rxdataF_ext[1],\n              12 * (ue->frame_parms.N_RB_DL)*NSYMB, 1, 1);\n    }\n\n    sprintf(fname, \"dlsch%d_ch_r%d_ext00.m\", eNB_id, round);\n    sprintf(vname, \"dl%d_ch_r%d_ext00\", eNB_id, round);\n    LOG_M(fname, vname, ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->dl_ch_estimates_ext[0],\n          12 * (ue->frame_parms.N_RB_DL)*NSYMB, 1, 1);\n\n    if(ue->transmission_mode[eNB_id] == 7)\n    {\n        sprintf(fname, \"dlsch%d_bf_ch_r%d.m\", eNB_id, round);\n        sprintf(vname, \"dl%d_bf_ch_r%d\", eNB_id, round);\n        LOG_M(fname, vname, ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->dl_bf_ch_estimates[0], 512 * NSYMB, 1, 1);\n        //LOG_M(fname,vname,phy_vars_ue->lte_ue_pdsch_vars[eNB_id]->dl_bf_ch_estimates[0],512,1,1);\n        sprintf(fname, \"dlsch%d_bf_ch_r%d_ext00.m\", eNB_id, round);\n        sprintf(vname, \"dl%d_bf_ch_r%d_ext00\", eNB_id, round);\n        LOG_M(fname, vname, ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->dl_bf_ch_estimates_ext[0],\n              12 * (ue->frame_parms.N_RB_DL)*NSYMB, 1, 1);\n    }\n\n    if(ue->frame_parms.nb_antennas_rx == 2)\n    {\n        sprintf(fname, \"dlsch%d_ch_r%d_ext01.m\", eNB_id, round);\n        sprintf(vname, \"dl%d_ch_r%d_ext01\", eNB_id, round);\n        LOG_M(fname, vname, ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->dl_ch_estimates_ext[1],\n              12 * (ue->frame_parms.N_RB_DL)*NSYMB, 1, 1);\n    }\n\n    if(ue->frame_parms.nb_antenna_ports_eNB == 2)\n    {\n        sprintf(fname, \"dlsch%d_ch_r%d_ext10.m\", eNB_id, round);\n        sprintf(vname, \"dl%d_ch_r%d_ext10\", eNB_id, round);\n        LOG_M(fname, vname, ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->dl_ch_estimates_ext[2],\n              12 * (ue->frame_parms.N_RB_DL)*NSYMB, 1, 1);\n\n        if(ue->frame_parms.nb_antennas_rx == 2)\n        {\n            sprintf(fname, \"dlsch%d_ch_r%d_ext11.m\", eNB_id, round);\n            sprintf(vname, \"dl%d_ch_r%d_ext11\", eNB_id, round);\n            LOG_M(fname, vname, ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->dl_ch_estimates_ext[3],\n                  12 * (ue->frame_parms.N_RB_DL)*NSYMB, 1, 1);\n        }\n    }\n\n    sprintf(fname, \"dlsch%d_rxF_r%d_uespec0.m\", eNB_id, round);\n    sprintf(vname, \"dl%d_rxF_r%d_uespec0\", eNB_id, round);\n    LOG_M(fname, vname, ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->rxdataF_uespec_pilots[0],\n          12 * (ue->frame_parms.N_RB_DL)*NSYMB, 1, 1);\n    /*\n        LOG_M(\"dlsch%d_ch_ext01.m\",\"dl01_ch0_ext\",pdsch_vars[eNB_id]->dl_ch_estimates_ext[1],12*N_RB_DL*NSYMB,1,1);\n        LOG_M(\"dlsch%d_ch_ext10.m\",\"dl10_ch0_ext\",pdsch_vars[eNB_id]->dl_ch_estimates_ext[2],12*N_RB_DL*NSYMB,1,1);\n        LOG_M(\"dlsch%d_ch_ext11.m\",\"dl11_ch0_ext\",pdsch_vars[eNB_id]->dl_ch_estimates_ext[3],12*N_RB_DL*NSYMB,1,1);\n    */\n    sprintf(fname, \"dlsch%d_r%d_rho.m\", eNB_id, round);\n    sprintf(vname, \"dl_rho_r%d_%d\", eNB_id, round);\n    LOG_M(fname, vname, ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->dl_ch_rho_ext[harq_pid][round][0],\n          12 * (ue->frame_parms.N_RB_DL)*NSYMB, 1, 1);\n    sprintf(fname, \"dlsch%d_r%d_rho2.m\", eNB_id, round);\n    sprintf(vname, \"dl_rho2_r%d_%d\", eNB_id, round);\n    LOG_M(fname, vname, ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->dl_ch_rho2_ext[0],\n          12 * (ue->frame_parms.N_RB_DL)*NSYMB, 1, 1);\n    sprintf(fname, \"dlsch%d_rxF_r%d_comp0.m\", eNB_id, round);\n    sprintf(vname, \"dl%d_rxF_r%d_comp0\", eNB_id, round);\n    LOG_M(fname, vname, ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->rxdataF_comp0[0],\n          12 * (ue->frame_parms.N_RB_DL)*NSYMB, 1, 1);\n\n    if(ue->frame_parms.nb_antenna_ports_eNB == 2)\n    {\n        sprintf(fname, \"dlsch%d_rxF_r%d_comp1.m\", eNB_id, round);\n        sprintf(vname, \"dl%d_rxF_r%d_comp1\", eNB_id, round);\n        LOG_M(fname, vname, ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->rxdataF_comp1[harq_pid][round][0],\n              12 * (ue->frame_parms.N_RB_DL)*NSYMB, 1, 1);\n    }\n\n    sprintf(fname, \"dlsch%d_rxF_r%d_llr.m\", eNB_id, round);\n    sprintf(vname, \"dl%d_r%d_llr\", eNB_id, round);\n    LOG_M(fname, vname, ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->llr[0], coded_bits_per_codeword[0], 1, 0);\n    sprintf(fname, \"dlsch%d_r%d_mag1.m\", eNB_id, round);\n    sprintf(vname, \"dl%d_r%d_mag1\", eNB_id, round);\n    LOG_M(fname, vname, ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->dl_ch_mag0[0],\n          12 * (ue->frame_parms.N_RB_DL)*NSYMB, 1, 1);\n    sprintf(fname, \"dlsch%d_r%d_mag2.m\", eNB_id, round);\n    sprintf(vname, \"dl%d_r%d_mag2\", eNB_id, round);\n    LOG_M(fname, vname, ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->dl_ch_magb0[0],\n          12 * (ue->frame_parms.N_RB_DL)*NSYMB, 1, 1);\n}\n\n\n", "meta": {"hexsha": "6653662b7529598bac52e0d7758096a01f6f7512", "size": 349249, "ext": "c", "lang": "C", "max_stars_repo_path": "openair1/PHY/LTE_UE_TRANSPORT/dlsch_demodulation.c", "max_stars_repo_name": "AManTw/oai5g", "max_stars_repo_head_hexsha": "93e5617d68431a477e803af2fa66290fd52470d2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "openair1/PHY/LTE_UE_TRANSPORT/dlsch_demodulation.c", "max_issues_repo_name": "AManTw/oai5g", "max_issues_repo_head_hexsha": "93e5617d68431a477e803af2fa66290fd52470d2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "openair1/PHY/LTE_UE_TRANSPORT/dlsch_demodulation.c", "max_forks_repo_name": "AManTw/oai5g", "max_forks_repo_head_hexsha": "93e5617d68431a477e803af2fa66290fd52470d2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.6117278307, "max_line_length": 368, "alphanum_fraction": 0.4579483406, "num_tokens": 101478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250464935739196, "lm_q2_score": 0.036769468846346534, "lm_q1q2_score": 0.015535271541983189}}
{"text": "//==============================================================================\n//\n// Copyright 2018 The InsideLoop Authors. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//    http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//\n//==============================================================================\n\n#ifndef IL_BLAS_DEFINE_H\n#define IL_BLAS_DEFINE_H\n\n#ifdef IL_MKL\n\n#include <mkl_cblas.h>\n#define IL_CBLAS_INT MKL_INT\n#define IL_CBLAS_LAYOUT CBLAS_LAYOUT\n#define IL_CBLAS_PCOMPLEX64 float*\n#define IL_CBLAS_PCOMPLEX128 double*\n#define IL_CBLAS_PCOMPLEX64_ANS float*\n#define IL_CBLAS_PCOMPLEX128_ANS double*\n\n#elif IL_OPENBLAS\n\n#include <cblas.h>\n#define IL_CBLAS_INT int\n#define IL_CBLAS_LAYOUT CBLAS_ORDER\n#define IL_CBLAS_PCOMPLEX64 float*\n#define IL_CBLAS_PCOMPLEX128 double*\n#define IL_CBLAS_PCOMPLEX64_ANS openblas_complex_float*\n#define IL_CBLAS_PCOMPLEX128_ANS openblas_complex_double*\n\n#endif\n\n#endif  // IL_BLAS_DEFINE_H\n", "meta": {"hexsha": "805cca43d9e562739bef715046ccd433e0e81dd1", "size": 1419, "ext": "h", "lang": "C", "max_stars_repo_path": "il/linearAlgebra/dense/blas/blas_config.h", "max_stars_repo_name": "insideloop/InsideLoop", "max_stars_repo_head_hexsha": "5385e908d85697e32fa065b45f608df84d3177a3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2016-12-08T14:16:28.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-18T01:26:52.000Z", "max_issues_repo_path": "il/linearAlgebra/dense/blas/blas_config.h", "max_issues_repo_name": "insideloop/InsideLoop", "max_issues_repo_head_hexsha": "5385e908d85697e32fa065b45f608df84d3177a3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-03-10T17:28:33.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-14T11:08:32.000Z", "max_forks_repo_path": "il/linearAlgebra/dense/blas/blas_config.h", "max_forks_repo_name": "insideloop/InsideLoop", "max_forks_repo_head_hexsha": "5385e908d85697e32fa065b45f608df84d3177a3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5333333333, "max_line_length": 80, "alphanum_fraction": 0.7054263566, "num_tokens": 329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250464935739196, "lm_q2_score": 0.036769468714406166, "lm_q1q2_score": 0.01553527148623777}}
{"text": "#ifndef OPENMC_VOLUME_CALC_H\n#define OPENMC_VOLUME_CALC_H\n\n#include \"openmc/position.h\"\n#include \"openmc/tallies/trigger.h\"\n\n#include \"pugixml.hpp\"\n#include \"xtensor/xtensor.hpp\"\n\n#include <array>\n#include <string>\n#include <vector>\n#include <gsl/gsl>\n\nnamespace openmc {\n\n//==============================================================================\n// Volume calculation class\n//==============================================================================\n\nclass VolumeCalculation {\n\npublic:\n  // Aliases, types\n  struct Result {\n    std::array<double, 2> volume; //!< Mean/standard deviation of volume\n    std::vector<int> nuclides; //!< Index of nuclides\n    std::vector<double> atoms; //!< Number of atoms for each nuclide\n    std::vector<double> uncertainty; //!< Uncertainty on number of atoms\n    int iterations; //!< Number of iterations needed to obtain the results\n  }; // Results for a single domain\n\n  // Constructors\n  VolumeCalculation(pugi::xml_node node);\n\n  // Methods\n\n  //! \\brief Stochastically determine the volume of a set of domains along with the\n  //!   average number densities of nuclides within the domain\n  //\n  //! \\return Vector of results for each user-specified domain\n  std::vector<Result> execute() const;\n\n  //! \\brief Write volume calculation results to HDF5 file\n  //\n  //! \\param[in] filename  Path to HDF5 file to write\n  //! \\param[in] results   Vector of results for each domain\n  void to_hdf5(const std::string& filename, const std::vector<Result>& results) const;\n\n  // Tally filter and map types\n  enum class TallyDomain {\n    UNIVERSE,\n    MATERIAL,\n    CELL\n  };\n\n  // Data members\n  TallyDomain domain_type_; //!< Type of domain (cell, material, etc.)\n  size_t n_samples_; //!< Number of samples to use\n  double threshold_ {-1.0}; //!< Error threshold for domain volumes\n  TriggerMetric trigger_type_ {TriggerMetric::not_active}; //!< Trigger metric for the volume calculation\n  Position lower_left_; //!< Lower-left position of bounding box\n  Position upper_right_; //!< Upper-right position of bounding box\n  std::vector<int> domain_ids_; //!< IDs of domains to find volumes of\n\nprivate:\n  //! \\brief Check whether a material has already been hit for a given domain.\n  //! If not, add new entries to the vectors\n  //\n  //! \\param[in] i_material Index in global materials vector\n  //! \\param[in,out] indices Vector of material indices\n  //! \\param[in,out] hits Number of hits corresponding to each material\n  void check_hit(int i_material, std::vector<int>& indices,\n    std::vector<int>& hits) const;\n\n};\n\n//==============================================================================\n// Global variables\n//==============================================================================\n\nnamespace model {\n  extern std::vector<VolumeCalculation> volume_calcs;\n}\n\n//==============================================================================\n// Non-member functions\n//==============================================================================\n\nvoid free_memory_volume();\n\n} // namespace openmc\n\n#endif // OPENMC_VOLUME_CALC_H\n", "meta": {"hexsha": "3258be9d6b583ed2d0fbe7f264002426da978551", "size": 3089, "ext": "h", "lang": "C", "max_stars_repo_path": "include/openmc/volume_calc.h", "max_stars_repo_name": "Hit-Weixg/openmc", "max_stars_repo_head_hexsha": "c5f66a3af5c1a57087e330f7b870e89a82267e4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-01-10T13:14:35.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-05T10:18:12.000Z", "max_issues_repo_path": "include/openmc/volume_calc.h", "max_issues_repo_name": "mehmeturkmen/openmc", "max_issues_repo_head_hexsha": "ffe0f0283a81d32759e4f877909bbb64d5ad0d3d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-03-14T12:18:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-01T15:23:23.000Z", "max_forks_repo_path": "include/openmc/volume_calc.h", "max_forks_repo_name": "mehmeturkmen/openmc", "max_forks_repo_head_hexsha": "ffe0f0283a81d32759e4f877909bbb64d5ad0d3d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-07-31T21:03:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-22T20:54:48.000Z", "avg_line_length": 32.5157894737, "max_line_length": 105, "alphanum_fraction": 0.6031078019, "num_tokens": 644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046202709847, "lm_q2_score": 0.03676946330485114, "lm_q1q2_score": 0.015535268131184036}}
{"text": "// Copyright 2018 Jeremy Mason\n//\n// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or\n// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or\n// http://opensource.org/licenses/MIT>, at your option. This file may not be\n// copied, modified, or distributed except according to those terms.\n\n//! \\file vector.c\n//! Contains functions to manipulate vectors. Intended as a relatively less\n//! painful wrapper around Level 1 CBLAS.\n\n#include <cblas.h>      // daxpy\n#include <float.h>      // DBL_EPSILON\n#include <math.h>       // exp\n#include <stdbool.h>    // bool\n#include <stddef.h>     // size_t\n#include <stdio.h>      // EOF\n#include <stdlib.h>     // abort\n#include <string.h>     // memcpy\n#include \"sb_matrix.h\"  // sb_mat_is_finite\n#include \"sb_structs.h\" // sb_mat\n#include \"sb_utility.h\" // SB_CHK_ERR\n#include \"sb_vector.h\"\n#include \"safety.h\"\n\n/// Constructs a vector with the required capacity.\n///\n/// # Parameters\n/// - `n_elem`: capacity of the vector\n/// - `layout`: `c` for a column vector, `r` for a row vector\n///\n/// # Returns\n/// A `sb_vec` pointer to the allocated vector, or `NULL` if the allocation fails\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_LAYOUT`: `layout` is `c` or `r`\n/// \n/// # Examples\n/// ```\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   sb_vec * v = sb_vec_malloc(3, 'r');\n///\n///   // Fill the vector with some values and print\n///   double a[] = {1., 4., 2.};\n///   sb_vec_subcpy(v, 0, a, 3);\n///   sb_vec_print(v, \"v: \", \"%g\");\n///\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\nsb_vec * sb_vec_malloc(size_t n_elem, char layout) {\n#ifdef SAFE_LAYOUT\n  SB_CHK_ERR(layout != 'c' && layout != 'r', abort(),\n      \"sb_vec_malloc: layout must be 'c' or 'r'\");\n#endif\n  sb_vec * out = malloc(sizeof(sb_vec));\n  SB_CHK_ERR(!out, return NULL, \"sb_vec_malloc: failed to allocate vector\");\n\n  double * data = malloc(n_elem * sizeof(double));\n  SB_CHK_ERR(!data, free(out); return NULL, \"sb_vec_malloc: failed to allocate data\");\n\n  out->n_elem = n_elem;\n  out->data   = data;\n  out->layout = layout;\n\n  return out;\n}\n\n/// Constructs a vector with the required capacity and initializes all elements\n/// to zero. Requires support for the IEC 60559 standard.\n///\n/// # Parameters\n/// - `n_elem`: capacity of the vector\n/// - `layout`: `c` for a column vector, `r` for a row vector\n///\n/// # Returns\n/// A `sb_vec` pointer to the allocated vector, or `NULL` if the allocation fails\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_LAYOUT`: `layout` is `c` or `r`\n/// \n/// # Examples\n/// ```\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   sb_vec * v = sb_vec_calloc(3, 'r');\n///\n///   // Initialized to zeros\n///   sb_vec_print(v, \"v before: \", \"%g\");\n///\n///   // Fill the vector with some values and print\n///   double a[] = {1., 4., 2.};\n///   sb_vec_subcpy(v, 0, a, 3);\n///   sb_vec_print(v, \"v after: \", \"%g\");\n///\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\nsb_vec * sb_vec_calloc(size_t n_elem, char layout) {\n#ifdef SAFE_LAYOUT\n  SB_CHK_ERR(layout != 'c' && layout != 'r', abort(),\n      \"sb_vec_calloc: layout must be 'c' or 'r'\");\n#endif\n  sb_vec * out = malloc(sizeof(sb_vec));\n  SB_CHK_ERR(!out, return NULL, \"sb_vec_calloc: failed to allocate vector\");\n\n  double * data = calloc(n_elem, sizeof(double));\n  SB_CHK_ERR(!data, free(out); return NULL, \"sb_vec_calloc: failed to allocate data\");\n\n  out->n_elem = n_elem;\n  out->data   = data;\n  out->layout = layout;\n\n  return out;\n}\n\n/// Constructs a vector with the required capacity and initializes elements to\n/// the first `n_elem` elements of array `a`. The array must contain at least\n/// `n_elem` elements.\n///\n/// # Parameters\n/// - `a`: array to be copied into the vector\n/// - `n_elem`: capacity of the vector\n/// - `layout`: `c` for a column vector, `r` for a row vector\n///\n/// # Returns\n/// A `sb_vec` pointer to the allocated vector, or `NULL` if the allocation fails\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `a` is not `NULL`\n/// - `SAFE_LAYOUT`: `layout` is `c` or `r`\n/// \n/// # Examples\n/// ```\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2.};\n/// \n///   // Construct a vector from the array\n///   sb_vec * v = sb_vec_of_arr(a, 3, 'r');\n///   sb_vec_print(v, \"v: \", \"%g\");\n///\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\nsb_vec * sb_vec_of_arr(const double * a, size_t n_elem, char layout) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!a, abort(), \"sb_vec_of_arr: a cannot be NULL\");\n#endif\n#ifdef SAFE_LAYOUT\n  SB_CHK_ERR(layout != 'c' && layout != 'r', abort(),\n      \"sb_vec_of_arr: layout must be 'c' or 'r'\");\n#endif\n  sb_vec * out = malloc(sizeof(sb_vec));\n  SB_CHK_ERR(!out, return NULL, \"sb_vec_of_arr: failed to allocate vector\");\n\n  double * data = malloc(n_elem * sizeof(double));\n  SB_CHK_ERR(!data, free(out); return NULL, \"sb_vec_of_arr: failed to allocate data\");\n\n  out->n_elem = n_elem;\n  out->data   = memcpy(data, a, n_elem * sizeof(double));\n  out->layout = layout;\n\n  return out;\n}\n\n/// Constructs a vector as a deep copy of an existing vector. The state of the\n/// existing vector must be valid.\n///\n/// # Parameters\n/// - `v`: pointer to the vector to be copied\n///\n/// # Returns\n/// A `sb_vec` pointer to the allocated vector, or `NULL` if the allocation fails\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` is not `NULL`\n///\n/// # Examples\n/// ```\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7.};\n///   sb_vec * v = sb_vec_of_arr(a, 3, 'r');\n/// \n///   // `v` and `w` contain the same elements\n///   sb_vec * w = sb_vec_clone(v);\n///   sb_vec_print(w, \"w before: \", \"%g\");\n///\n///   // Fill `w` with some values and print\n///   sb_vec_subcpy(w, 0, a + 3, 3);\n///   sb_vec_print(w, \"w after: \", \"%g\");\n///\n///   // `v` is unchanged\n///   sb_vec_print(v, \"v after: \", \"%g\");\n///\n///   SB_VEC_FREE_ALL(v, w);\n/// }\n/// ```\nsb_vec * sb_vec_clone(const sb_vec * v) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_vec_clone: v cannot be NULL\");\n#endif\n  sb_vec * out = malloc(sizeof(sb_vec));\n  SB_CHK_ERR(!out, return NULL, \"sb_vec_clone: failed to allocate vector\");\n\n  size_t n_elem = v->n_elem;\n\n  double * data = malloc(n_elem * sizeof(double));\n  SB_CHK_ERR(!data, free(out); return NULL, \"sb_vec_clone: failed to allocate data\");\n\n  *out = *v;\n  out->data = memcpy(data, v->data, n_elem * sizeof(double));\n\n  return out;\n}\n\n/// Constructs a column vector containing `n_elem` elements in equal intervals\n/// from `begin` to `end`. Must contain at least one element.\n///\n/// # Parameters\n/// - `begin`: beginning of the interval\n/// - `end`: end of the interval\n/// - `step`: step within the interval\n///\n/// # Returns\n/// A `sb_vec` pointer to the allocated vector, or `NULL` if the allocation fails\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_LENGTH`: `v` contains at least two elements\n/// - `SAFE_MEMORY`: `v` is not `NULL`\n///\n/// # Examples\n/// ```\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   sb_vec * v = sb_vec_linear(4., 0., 5);\n///   sb_vec_print(v, \"v: \", \"%g\");\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\nsb_vec * sb_vec_linear(double begin, double end, size_t n_elem) {\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(n_elem < 2, abort(), \"sb_vec_range: must contain at least two elements\");\n#endif\n  sb_vec * out = malloc(sizeof(sb_vec));\n  SB_CHK_ERR(!out, return NULL, \"sb_vec_range: failed to allocate sb_vector\");\n\n  double * data = malloc(n_elem * sizeof(double));\n  SB_CHK_ERR(!data, free(out); return NULL, \"sb_vec_range: failed to allocate data\");\n\n  size_t n_elem_1 = n_elem - 1;\n  double step = (end - begin) / n_elem_1;\n  for (size_t a = 0; a < n_elem_1; ++a) {\n    data[a] = fma(a, step, begin);\n  }\n  data[n_elem_1] = end;\n\n  out->n_elem = n_elem;\n  out->data   = data;\n  out->layout = 'c';\n\n  return out;\n}\n\n/// Deconstructs a vector.\n///\n/// # Parameters\n/// - `v`: pointer to the vector\n///\n/// # Returns\n/// No return value\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` is not `NULL`\n///\n/// # Examples\n/// ```\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2.};\n/// \n///   // Allocates a pointer to vec\n///   sb_vec * v = sb_vec_of_arr(a, 3, 'r');\n///   sb_vec_print(v, \"v: \", \"%g\");\n///\n///   sb_vec_free(v);\n///   // Pointer to `v` is now invalid\n/// }\n/// ```\nvoid sb_vec_free(sb_vec * v) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_vec_free: v cannot be NULL\");\n#endif\n  free(v->data);\n  free(v);\n}\n\n/// Sets all elements of `v` to zero. Requires support for the IEC 60559\n/// standard.\n///\n/// # Parameters\n/// - `v`: pointer to the vector\n///\n/// # Returns\n/// A copy of `v`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` is not `NULL`\n///\n/// # Examples\n/// ```\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2.};\n///   sb_vec * v = sb_vec_of_arr(a, 3, 'r');\n///   \n///   // Set all elements to zero\n///   sb_vec_print(v, \"v before: \", \"%g\");\n///   sb_vec_set_zero(v);\n///   sb_vec_print(v, \"v after: \", \"%g\");\n///\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\nsb_vec * sb_vec_set_zero(sb_vec * v) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_vec_set_zero: v cannot be NULL\");\n#endif\n  return memset(v->data, 0, v->n_elem * sizeof(double));\n}\n\n/// Sets all elements of `v` to `x`.\n///\n/// # Parameters\n/// - `v`: pointer to the vector\n/// - `x`: value for the elements\n///\n/// # Returns\n/// A copy of `v`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` is not `NULL`\n///\n/// # Examples\n/// ```\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2.};\n///   sb_vec * v = sb_vec_of_arr(a, 3, 'r');\n///   \n///   // Set all elements to 8.\n///   sb_vec_print(v, \"v before: \", \"%g\");\n///   sb_vec_set_all(v, 8.);\n///   sb_vec_print(v, \"v after: \", \"%g\");\n///\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\nsb_vec * sb_vec_set_all(sb_vec * v, double x) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_vec_set_all: v cannot be NULL\");\n#endif\n  double * data = v->data;\n  for (size_t a = 0; a < v->n_elem; ++a) {\n    data[a] = x;\n  }\n  return v;\n}\n\n/// Sets all elements of `v` to zero, except for the `i`th element which is set\n/// to one. Requires support for the IEC 60559 standard.\n///\n/// # Parameters\n/// - `v`: pointer to the vector\n/// - `i`: index of the element with value one\n///\n/// # Returns\n/// A copy of `v`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` is not `NULL`\n/// - `SAFE_LENGTH`: `i` is a valid index\n///\n/// # Examples\n/// ```\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2.};\n///   sb_vec * v = sb_vec_of_arr(a, 3, 'r');\n///   \n///   // Set `v` to second basis vector\n///   sb_vec_print(v, \"v before: \", \"%g\");\n///   sb_vec_set_basis(v, 1);\n///   sb_vec_print(v, \"v after: \", \"%g\");\n///\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\nsb_vec * sb_vec_set_basis(sb_vec * v, size_t i) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_vec_set_basis: v cannot be NULL\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(i >= v->n_elem, abort(), \"sb_vec_set_basis: index out of bounds\");\n#endif\n  ((double *) memset(v->data, 0, v->n_elem * sizeof(double)))[i] = 1.;\n  return v;\n}\n\n/// Copies contents of the `src` vector into the `dest` vector. `src` and `dest`\n/// must have the same length, the same layout, and not overlap in memory.\n///\n/// # Parameters\n/// - `dest`: pointer to destination vector\n/// - `src`: const pointer to source vector\n///\n/// # Returns\n/// A copy of `dest`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `src` and `dest` are not `NULL`\n/// - `SAFE_LAYOUT`: `src` and `dest` have same layout\n/// - `SAFE_LENGTH`: `src` and `dest` have same length\n///\n/// # Examples\n/// ```\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7.};\n///   sb_vec * v = sb_vec_of_arr(a,     3, 'r');\n///   sb_vec * w = sb_vec_of_arr(a + 3, 3, 'r');\n///\n///   // Overwrite elements of `v` and print\n///   sb_vec_print(v, \"v before: \", \"%g\");\n///   sb_vec_print(w, \"w before: \", \"%g\");\n///   sb_vec_memcpy(v, w);\n///   sb_vec_print(v, \"v after: \", \"%g\");\n///   sb_vec_print(w, \"w after: \", \"%g\");\n///\n///   SB_VEC_FREE_ALL(v, w);\n/// }\n/// ```\nsb_vec * sb_vec_memcpy(sb_vec * restrict dest, const sb_vec * restrict src) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!dest, abort(), \"sb_vec_memcpy: dest cannot be NULL\");\n  SB_CHK_ERR(!src, abort(), \"sb_vec_memcpy: src cannot be NULL\");\n#endif\n#ifdef SAFE_LAYOUT\n  SB_CHK_ERR(dest->layout != src->layout, abort(),\n      \"sb_vec_memcpy: dest and src must have same layout\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(dest->n_elem != src->n_elem, abort(),\n      \"sb_vec_memcpy: dest and src must have same length\");\n#endif\n  memcpy(dest->data, src->data, src->n_elem * sizeof(double));\n  return dest;\n}\n\n/// Copies `n` elements of array `a` into vector `v` starting at index `i`. `v`\n/// must have enough capacity, `a` must contain at least `n` elements, and `v`\n/// and `a` must not overlap in memory.\n///\n/// # Parameters\n/// - `v`: pointer to destination vector\n/// - `i`: index of `v` where the copy will start\n/// - `a`: pointer to elements that will be copied\n/// - `n`: number of elements to copy\n///\n/// # Returns\n/// A copy of `v`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` and `a` are not `NULL`\n/// - `SAFE_LENGTH`: `v` has enough capacity\n///\n/// # Examples\n/// ```\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5.};\n///   sb_vec * v = sb_vec_of_arr(a, 3, 'r');\n///\n///   // Overwrite elements of `v` and print\n///   sb_vec_print(v, \"v before: \", \"%g\");\n///   sb_vec_subcpy(v, 1, a + 3, 2);\n///   sb_vec_print(v, \"v after: \", \"%g\");\n///\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\nsb_vec * sb_vec_subcpy(\n    sb_vec * restrict v,\n    size_t i,\n    const double * restrict a,\n    size_t n) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_vec_subcpy: v cannot be NULL\");\n  SB_CHK_ERR(!a, abort(), \"sb_vec_subcpy: a cannot be NULL\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(v->n_elem - i < n, abort(),\n      \"sb_vec_subcpy: v does not have enough capacity\");\n#endif\n  memcpy(v->data + i, a, n * sizeof(double));\n  return v;\n}\n\n/// Swaps the contents of `v` and `w` by exchanging data pointers. Vectors must\n/// have the same length and layout and not overlap in memory.\n///\n/// # Parameters\n/// - `v`: pointer to the first vector\n/// - `w`: pointer to the second vector\n///\n/// # Returns\n/// No return value\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` and `w` are not `NULL`\n/// - `SAFE_LAYOUT`: `v` and `w` have the same layout\n/// - `SAFE_LENGTH`: `v` and `w` have the same length\n///\n/// # Examples\n/// ```\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7.};\n///   sb_vec * v = sb_vec_of_arr(a,     3, 'r');\n///   sb_vec * w = sb_vec_of_arr(a + 3, 3, 'r');\n/// \n///   // Print vectors before and after\n///   sb_vec_print(v, \"v before: \", \"%g\");\n///   sb_vec_print(w, \"w before: \", \"%g\");\n///\n///   sb_vec_swap(v, w);\n///\n///   sb_vec_print(v, \"v after: \", \"%g\");\n///   sb_vec_print(w, \"w after: \", \"%g\");\n///\n///   SB_VEC_FREE_ALL(v, w);\n/// }\n/// ```\nvoid sb_vec_swap(sb_vec * restrict v, sb_vec * restrict w) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_vec_swap: v cannot be NULL\");\n  SB_CHK_ERR(!w, abort(), \"sb_vec_swap: w cannot be NULL\");\n#endif\n#ifdef SAFE_LAYOUT\n  SB_CHK_ERR(v->layout != w->layout, abort(),\n      \"sb_vec_swap: v and w must have same layout\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(v->n_elem != w->n_elem, abort(),\n      \"sb_vec_swap: v and w must have same length\");\n#endif\n  double * scratch;\n  SB_SWAP(v->data, w->data, scratch);\n}\n\n/// Swaps the `i`th and `j`th elements of a vector.\n///\n/// # Parameters\n/// - `v`: pointer to the vector\n/// - `i`: index of first element\n/// - `j`: index of second element\n///\n/// # Returns\n/// No return value\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` is not `NULL`\n/// - `SAFE_LENGTH`: `i` and `j` are valid indices\n///\n/// # Examples\n/// ```\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2.};\n///   sb_vec * v = sb_vec_of_arr(a, 3, 'r');\n/// \n///   // Print vector before and after\n///   sb_vec_print(v, \"v before: \", \"%g\");\n///   sb_vec_swap_elems(v, 0, 1);\n///   sb_vec_print(v, \"v after: \", \"%g\");\n///\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\nvoid sb_vec_swap_elems(sb_vec * v, size_t i, size_t j) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_vec_swap_elems: v cannot be NULL\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(i >= v->n_elem, abort(), \"sb_vec_swap_elems: index out of bounds\");\n  SB_CHK_ERR(j >= v->n_elem, abort(), \"sb_vec_swap_elems: index out of bounds\");\n#endif\n  double * data = v->data;\n  double scratch;\n  SB_SWAP(data[i], data[j], scratch);\n}\n\n/// Writes the vector `v` to `stream` in a binary format. The data is written\n/// in the native binary format of the architecture, and may not be portable.\n///\n/// # Parameters\n/// - `stream`: an open I/O stream\n/// - `v`: pointer to the vector\n///\n/// # Returns\n/// `0` on success, or `1` if the write fails\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` is not `NULL`\n///\n/// # Examples\n/// ```\n/// #include <stdio.h>\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2.};\n///   sb_vec * v = sb_vec_of_arr(a, 3, 'r');\n///   \n///   // Write the vector to file\n///   FILE * f = fopen(\"vector.bin\", \"wb\");\n///   sb_vec_fwrite(f, v);\n///   fclose(f);\n///   \n///   // Read the vector from file\n///   FILE * g = fopen(\"vector.bin\", \"rb\");\n///   sb_vec * w = sb_vec_fread(g);\n///   fclose(g);\n///   \n///   // Vectors have the same contents\n///   sb_vec_print(v, \"v: \", \"%g\");\n///   sb_vec_print(w, \"w: \", \"%g\");\n///   \n///   SB_VEC_FREE_ALL(v, w);\n/// }\n/// ```\nint sb_vec_fwrite(FILE * stream, const sb_vec * v) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_vec_fwrite: v cannot be NULL\");\n#endif\n  size_t n_write;\n\n  size_t n_elem = v->n_elem; \n  n_write = fwrite(&n_elem, sizeof(size_t), 1, stream);\n  SB_CHK_ERR(n_write != 1, return 1, \"sb_vec_fwrite: fwrite failed\");\n\n  n_write = fwrite(&(v->layout), sizeof(char), 1, stream);\n  SB_CHK_ERR(n_write != 1, return 1, \"sb_vec_fwrite: fwrite failed\");\n\n  n_write = fwrite(v->data, sizeof(double), n_elem, stream);\n  SB_CHK_ERR(n_write != n_elem, return 1, \"sb_vec_fwrite: fwrite failed\");\n\n  return 0;\n}\n\n/// Reads binary data from `stream` into the vector returned by the function.\n/// Writes the vector `v` to `stream`. The number of elements, layout, and\n/// elements are written in a human readable format.\n///\n/// # Parameters\n/// - `stream`: an open I/O stream\n/// - `v`: pointer to the vector\n/// - `format`: a format specifier for the elements\n///\n/// # Returns\n/// `0` on success, or `1` if the write fails\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` is not `NULL`\n///\n/// # Examples\n/// ```\n/// #include <stdio.h>\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double f[] = {1., 4., 2.};\n///   sb_vec * v = sb_vec_of_arr(a, 3, 'r');\n///   \n///   // Write the vector to file\n///   FILE * f = fopen(\"vector.txt\", \"w\");\n///   sb_vec_fprintf(f, v, \"%lg\");\n///   fclose(f);\n///   \n///   // Read the sb_vector from file\n///   FILE * g = fopen(\"vector.txt\", \"r\");\n///   sb_vec * w = sb_vec_fscanf(g);\n///   fclose(g);\n///   \n///   // Vectors have the same contents\n///   sb_vec_print(v, \"v: \", \"%g\");\n///   sb_vec_print(w, \"w: \", \"%g\");\n///   \n///   SB_VEC_FREE_ALL(v, w);\n/// }\n/// ```\nint sb_vec_fprintf(FILE * stream, const sb_vec * v, const char * format) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_vec_fprintf: v cannot be NULL\");\n#endif\n  int status;\n\n  size_t n_elem = v->n_elem; \n  status = fprintf(stream, \"%zu %c\", n_elem, v->layout);\n  SB_CHK_ERR(status < 0, return 1, \"sb_vec_fprintf: fprintf failed\");\n\n  double * data = v->data;\n  for (size_t a = 0; a < n_elem; ++a) {\n    status = putc(' ', stream);\n    SB_CHK_ERR(status == EOF, return 1, \"sb_vec_fprintf: putc failed\");\n    status = fprintf(stream, format, data[a]);\n    SB_CHK_ERR(status < 0, return 1, \"sb_vec_fprintf: fprintf failed\");\n  }\n  status = putc('\\n', stream);\n  SB_CHK_ERR(status == EOF, return 1, \"sb_vec_fprintf: putc failed\");\n\n  return 0;\n}\n\n/// Prints the vector `v` to stdout. Output is slightly easier to read than for\n/// `sb_vec_fprintf()`. Mainly indended for debugging.\n///\n/// # Parameters\n/// - `v`: pointer to the vector\n/// - `str`: a string to describe the vector\n/// - `format`: a format specifier for the elements\n///\n/// # Returns\n/// `0` on success, or `1` if the print fails\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` is not `NULL`\n///\n/// # Examples\n/// ```\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double array[] = {1., 4., 2., 8., 5., 7.};\n///   sb_vec * v = sb_vec_of_arr(array,     3, 'r');\n///   sb_vec * w = sb_vec_of_arr(array + 3, 3, 'c');\n///\n///   // Prints the contents of `v` and `w` to stdout\n///   sb_vec_print(v, \"v: \", \"%g\");\n///   sb_vec_print(w, \"w: \", \"%g\");\n///\n///   SB_VEC_FREE_ALL(v, w);\n/// }\n/// ```\nint sb_vec_print(const sb_vec * v, const char * str, const char * format) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_vec_print: v cannot be NULL\");\n#endif\n  int status;\n\n  status = printf(\"%s\\n\", str);\n  SB_CHK_ERR(status < 0, return 1, \"sb_vec_print: printf failed\");\n\n  size_t n_elem = v->n_elem;\n  double * data = v->data;\n\n  char   buffer[128];\n  char * dec;\n  bool   dec_mark[n_elem];\n  bool   any_mark = false;\n\n  unsigned char length;\n  unsigned char len_head[n_elem];\n  unsigned char max_head = 0;\n  unsigned char len_tail[n_elem];\n  unsigned char max_tail = 0;\n  for (size_t a = 0; a < n_elem; ++a) {\n    status = snprintf(buffer, 128, format, data[a]);\n    SB_CHK_ERR(status < 0, return 1, \"sb_vec_print: snprintf failed\");\n    dec = strchr(buffer, '.');\n    if (dec) {\n      dec_mark[a] = true;\n      any_mark    = true;\n      length = (unsigned char)(dec - buffer);\n      len_head[a] = length;\n      if (length > max_head) { max_head = length; }\n      length = strlen(buffer) - length - 1;\n      if (length > max_tail) { max_tail = length; }\n      len_tail[a] = length;\n    } else {\n      dec_mark[a] = false;\n      length = strlen(buffer);\n      len_head[a] = length;\n      if (length > max_head) { max_head = length; }\n      len_tail[a] = 0;\n    }\n  }\n\n  for (size_t a = 0; a < n_elem; ++a) {\n    for (unsigned char s = 0; s < max_head - len_head[a]; ++s) {\n      status = putchar(' ');\n      SB_CHK_ERR(status == EOF, return 1, \"sb_vec_print: putchar failed\");\n    }\n    status = printf(format, data[a]);\n    SB_CHK_ERR(status < 0, return 1, \"sb_vec_print: printf failed\");\n    if (any_mark && !dec_mark[a]) {\n      status = putchar(' ');\n      SB_CHK_ERR(status == EOF, return 1, \"sb_vec_print: putchar failed\");\n    }\n    for (unsigned char s = 0; s < max_tail - len_tail[a]; ++s) {\n      status = putchar(' ');\n      SB_CHK_ERR(status == EOF, return 1, \"sb_vec_print: putchar failed\");\n    }\n    status = putchar(v->layout == 'r' ? ' ' : '\\n');\n    SB_CHK_ERR(status == EOF, return 1, \"sb_vec_print: putchar failed\");\n  }\n  if (v->layout == 'r') {\n    status = putchar('\\n');\n    SB_CHK_ERR(status == EOF, return 1, \"sb_vec_print: putchar failed\");\n  }\n\n  return 0;\n}\n\n/// The data must be written in the native binary format of the architecture, \n/// preferably by `sb_vec_fwrite()`.\n///\n/// # Parameters\n/// - `stream`: an open I/O stream\n///\n/// # Returns\n/// A `sb_vec` pointer to the sb_vector read from `stream`, or `NULL` if the read or \n/// memory allocation fails\n/// \n/// # Examples\n/// ```\n/// #include <stdio.h>\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2.};\n///   sb_vec * v = sb_vec_of_arr(a, 3, 'r');\n///   \n///   // Write the vector to file\n///   FILE * f = fopen(\"vector.bin\", \"wb\");\n///   sb_vec_fwrite(f, v);\n///   fclose(f);\n///   \n///   // Read the vector from file\n///   FILE * g = fopen(\"vector.bin\", \"rb\");\n///   sb_vec * w = sb_vec_fread(g);\n///   fclose(g);\n///   \n///   // Vectors have the same contents\n///   sb_vec_print(v, \"v: \", \"%g\");\n///   sb_vec_print(w, \"w: \", \"%g\");\n///   \n///   SB_VEC_FREE_ALL(v, w);\n/// }\n/// ```\nsb_vec * sb_vec_fread(FILE * stream) {\n  size_t n_read;\n\n  size_t n_elem;\n  n_read = fread(&n_elem, sizeof(size_t), 1, stream);\n  SB_CHK_ERR(n_read != 1, return NULL, \"sb_vec_fread: fread failed\");\n\n  char layout;\n  n_read = fread(&layout, sizeof(char), 1, stream);\n  SB_CHK_ERR(n_read != 1, return NULL, \"sb_vec_fread: fread failed\");\n\n  sb_vec * out = sb_vec_malloc(n_elem, layout);\n  SB_CHK_ERR(!out, return NULL, \"sb_vec_fread: sb_vec_malloc failed\");\n\n  n_read = fread(out->data, sizeof(double), n_elem, stream);\n  SB_CHK_ERR(n_read != n_elem, sb_vec_free(out); return NULL, \"sb_vec_fread: fread failed\");\n\n  return out;\n}\n\n/// Reads formatted data from `stream` into the vector returned by the function.\n///\n/// # Parameters\n/// - `stream`: an open I/O stream\n///\n/// # Returns\n/// A `sb_vec` pointer to the vector read from `stream`, or `NULL` if the scan or \n/// memory allocation fails\n/// \n/// # Examples\n/// ```\n/// #include <stdio.h>\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2.};\n///   sb_vec * v = sb_vec_of_arr(a, 3, 'r');\n///   \n///   // Write the vector to file\n///   FILE * f = fopen(\"vector.txt\", \"w\");\n///   sb_vec_fprintf(f, v, \"%lg\");\n///   fclose(f);\n///   \n///   // Read the vector from file\n///   FILE * g = fopen(\"vector.txt\", \"r\");\n///   sb_vec * w = sb_vec_fscanf(g);\n///   fclose(g);\n///   \n///   // Vectors have the same contents\n///   sb_vec_print(v, \"v: \", \"%g\");\n///   sb_vec_print(w, \"w: \", \"%g\");\n///   \n///   SB_VEC_FREE_ALL(v, w);\n/// }\n/// ```\nsb_vec * sb_vec_fscanf(FILE * stream) {\n  int n_scan;\n\n  size_t n_elem;\n  char layout;\n  n_scan = fscanf(stream, \"%zu %c\", &n_elem, &layout);\n  SB_CHK_ERR(n_scan != 2, return NULL, \"sb_vec_fscanf: fscanf failed\");\n\n  sb_vec * out = sb_vec_malloc(n_elem, layout);\n  SB_CHK_ERR(!out, return NULL, \"sb_vec_fscanf: sb_vec_malloc failed\");\n\n  double * data = out->data;\n  for (size_t a = 0; a < n_elem; ++a) {\n    n_scan = fscanf(stream, \"%lg\", data + a);\n    SB_CHK_ERR(n_scan != 1, sb_vec_free(out); return NULL, \"sb_vec_fscanf: fscanf failed\");\n  }\n\n  return out;\n}\n\n/// Takes the absolute value of every element of the vector.\n///\n/// # Parameters\n/// - `v`: pointer to the vector\n///\n/// # Returns\n/// A copy of `v`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` is not `NULL`\n/// - `SAFE_FINITE`: elements of `v` are finite\n///\n/// # Examples\n/// ```\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {-1., 4., -2.};\n///   sb_vec * v = sb_vec_of_arr(a, 3, 'r');\n/// \n///   // Take absolute value\n///   sb_vec_print(v, \"v before: \", \"%g\");\n///   sb_vec_abs(v);\n///   sb_vec_print(v, \"v after: \", \"%g\");\n///\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\nsb_vec * sb_vec_abs(sb_vec * v) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_vec_abs: v cannot be NULL\");\n#endif\n  double * data = v->data;\n  for (size_t a = 0; a < v->n_elem; ++a) {\n    data[a] = fabs(data[a]);\n  }\n#ifdef SAFE_FINITE\n  SB_CHK_ERR(!sb_vec_is_finite(v), abort(), \"sb_vec_abs: element not finite\");\n#endif\n  return v;\n}\n\n/// Takes the exponent base `e` of every element of the vector.\n///\n/// # Parameters\n/// - `v`: pointer to the vector\n///\n/// # Returns\n/// A copy of `v`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` is not `NULL`\n/// - `SAFE_FINITE`: elements of `v` are finite\n///\n/// # Examples\n/// ```\n/// #include <math.h>\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {log(1.), log(4.), log(2.)};\n///   sb_vec * v = sb_vec_of_arr(a, 3, 'r');\n/// \n///   // Take exponent base e\n///   sb_vec_print(v, \"v before: \", \"%g\");\n///   sb_vec_exp(v);\n///   sb_vec_print(v, \"v after: \", \"%g\");\n///\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\nsb_vec * sb_vec_exp(sb_vec * v) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_vec_exp: v cannot be NULL\");\n#endif\n  double * data = v->data;\n  for (size_t a = 0; a < v->n_elem; ++a) {\n    data[a] = exp(data[a]);\n  }\n#ifdef SAFE_FINITE\n  SB_CHK_ERR(!sb_vec_is_finite(v), abort(), \"sb_vec_exp: element not finite\");\n#endif\n  return v;\n}\n\n/// Takes the logarithm base `e` of every element of the vector.\n///\n/// # Parameters\n/// - `v`: pointer to the vector\n///\n/// # Returns\n/// A copy of `v`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` is not `NULL`\n/// - `SAFE_FINITE`: elements of `v` are finite\n///\n/// # Examples\n/// ```\n/// #include <math.h>\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {exp(1.), exp(4.), exp(2.)};\n///   sb_vec * v = sb_vec_of_arr(a, 3, 'r');\n/// \n///   // Take logarithm base e\n///   sb_vec_print(v, \"v before: \", \"%g\");\n///   sb_vec_log(v);\n///   sb_vec_print(v, \"v after: \", \"%g\");\n///\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\nsb_vec * sb_vec_log(sb_vec * v) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_vec_log: v cannot be NULL\");\n#endif\n  double * data = v->data;\n  for (size_t a = 0; a < v->n_elem; ++a) {\n    data[a] = log(data[a]);\n  }\n#ifdef SAFE_FINITE\n  SB_CHK_ERR(!sb_vec_is_finite(v), abort(), \"sb_vec_log: element not finite\");\n#endif\n  return v;\n}\n\n/// Exponentiates every element of the vector `v` by `x`.\n///\n/// # Parameters\n/// - `v`: pointer to the vector\n/// - `x`: scalar exponent of the elements\n///\n/// # Returns\n/// A copy of `v`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` is not `NULL`\n/// - `SAFE_FINITE`: elements of `v` are finite\n///\n/// # Examples\n/// ```\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2.};\n///   sb_vec * v = sb_vec_of_arr(a, 3, 'r');\n/// \n///   // Exponentiate every element by -1.\n///   sb_vec_print(v, \"v before: \", \"%g\");\n///   sb_vec_smul(v, -1.);\n///   sb_vec_print(v, \"v after: \", \"%g\");\n///\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\nsb_vec * sb_vec_pow(sb_vec * v, double x) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_vec_pow: v cannot be NULL\");\n#endif\n  double * data = v->data;\n  for (size_t a = 0; a < v->n_elem; ++a) {\n    data[a] = pow(data[a], x);\n  }\n#ifdef SAFE_FINITE\n  SB_CHK_ERR(!sb_vec_is_finite(v), abort(), \"sb_vec_pow: element not finite\");\n#endif\n  return v;\n}\n\n/// Takes the square root of every element of the vector `v`.\n///\n/// # Parameters\n/// - `v`: pointer to the vector\n///\n/// # Returns\n/// A copy of `v`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` is not `NULL`\n/// - `SAFE_FINITE`: elements of `v` are finite\n///\n/// # Examples\n/// ```\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 16., 4.};\n///   sb_vec * v = sb_vec_of_arr(a, 3, 'r');\n/// \n///   // Take the square root of every element\n///   sb_vec_print(v, \"v before: \", \"%g\");\n///   sb_vec_sqrt(v);\n///   sb_vec_print(v, \"v after: \", \"%g\");\n///\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\nsb_vec * sb_vec_sqrt(sb_vec * v) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_vec_sqrt: v cannot be NULL\");\n#endif\n  double * data = v->data;\n  for (size_t a = 0; a < v->n_elem; ++a) {\n    data[a] = sqrt(data[a]);\n  }\n#ifdef SAFE_FINITE\n  SB_CHK_ERR(!sb_vec_is_finite(v), abort(), \"sb_vec_sqrt: element not finite\");\n#endif\n  return v;\n}\n\n/// Scalar addition of `x` to every element of the vector `v`.\n///\n/// # Parameters\n/// - `v`: pointer to the vector\n/// - `x`: scalar added to the elements\n///\n/// # Returns\n/// A copy of `v`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` is not `NULL`\n/// - `SAFE_FINITE`: elements of `v` are finite\n///\n/// # Examples\n/// ```\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2.};\n///   sb_vec * v = sb_vec_of_arr(a, 3, 'r');\n/// \n///   // Add 2. to every element\n///   sb_vec_print(v, \"v before: \", \"%g\");\n///   sb_vec_sadd(v, 2.);\n///   sb_vec_print(v, \"v after: \", \"%g\");\n///\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\nsb_vec * sb_vec_sadd(sb_vec * v, double x) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_vec_sadd: v cannot be NULL\");\n#endif\n  double * data = v->data;\n  for (size_t a = 0; a < v->n_elem; ++a) {\n    data[a] += x;\n  }\n#ifdef SAFE_FINITE\n  SB_CHK_ERR(!sb_vec_is_finite(v), abort(), \"sb_vec_sadd: element not finite\");\n#endif\n  return v;\n}\n\n/// Scalar multiplication of `x` with every element of the vector `v`.\n///\n/// # Parameters\n/// - `v`: pointer to the vector\n/// - `x`: scalar mutiplier for the elements\n///\n/// # Returns\n/// A copy of `v`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` is not `NULL`\n/// - `SAFE_FINITE`: elements of `v` are finite\n///\n/// # Examples\n/// ```\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2.};\n///   sb_vec * v = sb_vec_of_arr(a, 3, 'r');\n/// \n///   // Multiply every element by -1.\n///   sb_vec_print(v, \"v before: \", \"%g\");\n///   sb_vec_smul(v, -1.);\n///   sb_vec_print(v, \"v after: \", \"%g\");\n///\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\nsb_vec * sb_vec_smul(sb_vec * v, double x) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_vec_smul: v cannot be NULL\");\n#endif\n  cblas_dscal(v->n_elem, x, v->data, 1);\n#ifdef SAFE_FINITE\n  SB_CHK_ERR(!sb_vec_is_finite(v), abort(), \"sb_vec_smul: elements not finite\");\n#endif\n  return v;\n}\n\n/// Pointwise addition of elements of the vector `w` to elements of the vector\n/// `v`. `v` and `w` must not overlap in memory.\n///\n/// # Parameters\n/// - `v`: pointer to the first vector\n/// - `w`: pointer to the second vector\n///\n/// # Returns\n/// A copy of `v`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` and `w` are not `NULL`\n/// - `SAFE_LAYOUT`: `v` and `w` have the same layout\n/// - `SAFE_LENGTH`: `v` and `w` have the same length\n/// - `SAFE_FINITE`: elements of `v` are finite\n///\n/// # Examples\n/// ```\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7.};\n///   sb_vec * v = sb_vec_of_arr(a,     3, 'r');\n///   sb_vec * w = sb_vec_of_arr(a + 3, 3, 'r');\n/// \n///   // Add w to v\n///   sb_vec_print(v, \"v before: \", \"%g\");\n///   sb_vec_padd(v, w);\n///   sb_vec_print(v, \"v after: \", \"%g\");\n///\n///   SB_VEC_FREE_ALL(v, w);\n/// }\n/// ```\nsb_vec * sb_vec_padd(sb_vec * restrict v, const sb_vec * restrict w) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_vec_padd: v cannot be NULL\");\n  SB_CHK_ERR(!w, abort(), \"sb_vec_padd: w cannot be NULL\");\n#endif\n#ifdef SAFE_LAYOUT\n  SB_CHK_ERR(v->layout != w->layout, abort(),\n      \"sb_vec_padd: v and w must have same layout\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(v->n_elem != w->n_elem, abort(),\n      \"sb_vec_padd: v and w must have same length\");\n#endif\n  cblas_daxpy(v->n_elem, 1., w->data, 1, v->data, 1);\n#ifdef SAFE_FINITE\n  SB_CHK_ERR(!sb_vec_is_finite(v), abort(), \"sb_vec_padd: elements not finite\");\n#endif\n  return v;\n}\n\n/// Pointwise subtraction of elements of the vector `w` from elements of the\n/// vector `v`. `v` and `w` must not overlap in memory.\n///\n/// # Parameters\n/// - `v`: pointer to the first vector\n/// - `w`: pointer to the second vector\n///\n/// # Returns\n/// A copy of `v`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` and `w` are not `NULL`\n/// - `SAFE_LAYOUT`: `v` and `w` have the same layout\n/// - `SAFE_LENGTH`: `v` and `w` have the same length\n/// - `SAFE_FINITE`: elements of `v` are finite\n///\n/// # Examples\n/// ```\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7.};\n///   sb_vec * v = sb_vec_of_arr(a,     3, 'r');\n///   sb_vec * w = sb_vec_of_arr(a + 3, 3, 'r');\n/// \n///   // Subtract w from v\n///   sb_vec_print(v, \"v before: \", \"%g\");\n///   sb_vec_psub(v, w);\n///   sb_vec_print(v, \"v after: \", \"%g\");\n///\n///   SB_VEC_FREE_ALL(v, w);\n/// }\n/// ```\nsb_vec * sb_vec_psub(sb_vec * restrict v, const sb_vec * restrict w) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_vec_psub: v cannot be NULL\");\n  SB_CHK_ERR(!w, abort(), \"sb_vec_psub: w cannot be NULL\");\n#endif\n#ifdef SAFE_LAYOUT\n  SB_CHK_ERR(v->layout != w->layout, abort(),\n      \"sb_vec_psub: v and w must have same layout\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(v->n_elem != w->n_elem, abort(),\n      \"sb_vec_psub: v and w must have same length\");\n#endif\n  cblas_daxpy(v->n_elem, -1., w->data, 1, v->data, 1);\n#ifdef SAFE_FINITE\n  SB_CHK_ERR(!sb_vec_is_finite(v), abort(), \"sb_vec_psub: elements not finite\");\n#endif\n  return v;\n}\n\n/// Pointwise multiplication of elements of the vector `v` with elements of the\n/// vector `w`. `v` and `w` must not overlap in memory.\n///\n/// # Parameters\n/// - `v`: pointer to the first vector\n/// - `w`: pointer to the second vector\n///\n/// # Returns\n/// A copy of `v`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` and `w` are not `NULL`\n/// - `SAFE_LAYOUT`: `v` and `w` have the same layout\n/// - `SAFE_LENGTH`: `v` and `w` have the same length\n/// - `SAFE_FINITE`: elements of `v` are finite\n///\n/// # Examples\n/// ```\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7.};\n///   sb_vec * v = sb_vec_of_arr(a,     3, 'r');\n///   sb_vec * w = sb_vec_of_arr(a + 3, 3, 'r');\n/// \n///   // Multiply elements of v by elements of w\n///   sb_vec_print(v, \"v before: \", \"%g\");\n///   sb_vec_pmul(v, w);\n///   sb_vec_print(v, \"v after: \", \"%g\");\n///\n///   SB_VEC_FREE_ALL(v, w);\n/// }\n/// ```\nsb_vec * sb_vec_pmul(sb_vec * restrict v, const sb_vec * restrict w) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_vec_pmul: v cannot be NULL\");\n  SB_CHK_ERR(!w, abort(), \"sb_vec_pmul: w cannot be NULL\");\n#endif\n#ifdef SAFE_LAYOUT\n  SB_CHK_ERR(v->layout != w->layout, abort(),\n      \"sb_vec_pmul: v and w must have same layout\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(v->n_elem != w->n_elem, abort(),\n      \"sb_vec_pmul: v and w must have same length\");\n#endif\n  double * v_data = v->data;\n  double * w_data = w->data;\n  for (size_t a = 0; a < v->n_elem; ++a) {\n    v_data[a] *= w_data[a];\n  }\n#ifdef SAFE_FINITE\n  SB_CHK_ERR(!sb_vec_is_finite(v), abort(), \"sb_vec_pmul: element not finite\");\n#endif\n  return v;\n}\n\n/// Pointwise division of elements of the vector `v` by elements of the vector\n/// `w`. `v` and `w` must not overlap in memory.\n///\n/// # Parameters\n/// - `v`: pointer to the first vector\n/// - `w`: pointer to the second vector\n///\n/// # Returns\n/// A copy of `v`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` and `w` are not `NULL`\n/// - `SAFE_LAYOUT`: `v` and `w` have the same layout\n/// - `SAFE_LENGTH`: `v` and `w` have the same length\n/// - `SAFE_FINITE`: elements of `v` are finite\n///\n/// # Examples\n/// ```\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7.};\n///   sb_vec * v = sb_vec_of_arr(a,     3, 'r');\n///   sb_vec * w = sb_vec_of_arr(a + 3, 3, 'r');\n/// \n///   // Divide elements of v by elements of w\n///   sb_vec_print(v, \"v before: \", \"%g\");\n///   sb_vec_pdiv(v, w);\n///   sb_vec_print(v, \"v after: \", \"%g\");\n///\n///   SB_VEC_FREE_ALL(v, w);\n/// }\n/// ```\nsb_vec * sb_vec_pdiv(sb_vec * restrict v, const sb_vec * restrict w) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_vec_pdiv: v cannot be NULL\");\n  SB_CHK_ERR(!w, abort(), \"sb_vec_pdiv: w cannot be NULL\");\n#endif\n#ifdef SAFE_LAYOUT\n  SB_CHK_ERR(v->layout != w->layout, abort(),\n      \"sb_vec_pdiv: v and w must have same layout\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(v->n_elem != w->n_elem, abort(),\n      \"sb_vec_pdiv: v and w must have same length\");\n#endif\n  double * v_data = v->data;\n  double * w_data = w->data;\n  for (size_t a = 0; a < v->n_elem; ++a) {\n    v_data[a] /= w_data[a];\n  }\n#ifdef SAFE_FINITE\n  SB_CHK_ERR(!sb_vec_is_finite(v), abort(), \"sb_vec_pdiv: element not finite\");\n#endif\n  return v;\n}\n\n/// Performs the operation \\f$\\mathbf{r} x + y\\f$ where `x` and `y` are scalars\n/// and `r` is modified (result x add y). \n///\n/// # Parameters\n/// - `r`: pointer to the vector\n/// - `x`: scalar mutiplier for the elements\n/// - `y`: scalar summand for the elements\n///\n/// # Returns\n/// A copy of `r`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `r` is not `NULL`\n/// - `SAFE_FINITE`: elements of `r` are finite\n///\n/// # Examples\n/// ```\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2.};\n///   sb_vec * r = sb_vec_of_arr(a, 3, 'r');\n/// \n///   // Multiply by -1. and add 2.\n///   sb_vec_print(r, \"r before: \", \"%g\");\n///   sb_vec_rxay(r, -1., 2.);\n///   sb_vec_print(r, \"r after: \", \"%g\");\n///\n///   SB_VEC_FREE_ALL(r);\n/// }\n/// ```\nsb_vec * sb_vec_rxay(sb_vec * r, double x, double y) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!r, abort(), \"sb_vec_rxay: r cannot be NULL\");\n#endif\n  double * data = r->data;\n  for (size_t a = 0; a < r->n_elem; ++a) {\n    data[a] = fma(data[a], x, y);\n  }\n#ifdef SAFE_FINITE\n  SB_CHK_ERR(!sb_vec_is_finite(r), abort(), \"sb_vec_rxay: elements not finite\");\n#endif\n  return r;\n}\n\n/// Performs the operation \\f$\\mathbf{r} + x \\mathbf{v}\\f$ where `x` is a\n/// scalar, `v` is a vector and `r` is modified (result add x vector). `r` and\n/// `v` must not overlap in memory.\n///\n/// # Parameters\n/// - `r`: pointer to the first vector\n/// - `x`: scalar multiplier for `v`\n/// - `v`: pointer to the second vector\n///\n/// # Returns\n/// A copy of `r`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `r` and `v` are not `NULL`\n/// - `SAFE_LAYOUT`: `r` and `v` have the same layout\n/// - `SAFE_LENGTH`: `r` and `v` have the same length\n/// - `SAFE_FINITE`: elements of `r` are finite\n///\n/// # Examples\n/// ```\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7.};\n///   sb_vec * r = sb_vec_of_arr(a,     3, 'r');\n///   sb_vec * v = sb_vec_of_arr(a + 3, 3, 'r');\n/// \n///   // Multiply v by 2. and add to r\n///   sb_vec_print(r, \"r before: \", \"%g\");\n///   sb_vec_raxv(r, 2., v);\n///   sb_vec_print(r, \"r after: \", \"%g\");\n///\n///   SB_VEC_FREE_ALL(r, v);\n/// }\n/// ```\nsb_vec * sb_vec_raxv(sb_vec * restrict r, double x, const sb_vec * restrict v) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!r, abort(), \"sb_vec_raxv: r cannot be NULL\");\n  SB_CHK_ERR(!v, abort(), \"sb_vec_raxv: v cannot be NULL\");\n#endif\n#ifdef SAFE_LAYOUT\n  SB_CHK_ERR(r->layout != v->layout, abort(),\n      \"sb_vec_raxv: r and v must have same layout\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(r->n_elem != v->n_elem, abort(),\n      \"sb_vec_raxv: r and v must have same length\");\n#endif\n  cblas_daxpy(r->n_elem, x, v->data, 1, r->data, 1);\n#ifdef SAFE_FINITE\n  SB_CHK_ERR(!sb_vec_is_finite(r), abort(), \"sb_vec_raxv: elements not finite\");\n#endif\n  return r;\n}\n\n/// Performs the operation \\f$\\mathbf{r} \\otimes \\mathbf{v} - \\mathbf{w}\\f$\n/// where `v` and `w` are vectors, \\f$\\otimes\\f$ is pointwise multiplication,\n/// and `r` is modified (result v subtract w). `r`, `v` and `w` must not\n/// overlap in memory.\n///\n/// # Parameters\n/// - `r`: pointer to the first vector\n/// - `v`: pointer to the second vector\n/// - `w`: pointer to the third vector\n///\n/// # Returns\n/// A copy of `r`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `r`, `v` and `w` are not `NULL`\n/// - `SAFE_LAYOUT`: `r`, `v` and `w` have the same layout\n/// - `SAFE_LENGTH`: `r`, `v` and `w` have the same length\n/// - `SAFE_FINITE`: elements of `r` are finite\n///\n/// # Examples\n/// ```\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5.};\n///   sb_vec * r = sb_vec_of_arr(a,     3, 'r');\n///   sb_vec * v = sb_vec_of_arr(a + 1, 3, 'r');\n///   sb_vec * w = sb_vec_of_arr(a + 2, 3, 'r');\n/// \n///   // Pointwise multiply r by v and pointwise subtract w\n///   sb_vec_print(r, \"r before: \", \"%g\");\n///   sb_vec_rvsw(r, v, w);\n///   sb_vec_print(r, \"r after: \", \"%g\");\n///\n///   SB_VEC_FREE_ALL(r, v, w);\n/// }\n/// ```\nsb_vec * sb_vec_rvsw(\n    sb_vec * restrict r,\n    const sb_vec * restrict v,\n    const sb_vec * restrict w) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!r, abort(), \"sb_vec_rvsw: r cannot be NULL\");\n  SB_CHK_ERR(!v, abort(), \"sb_vec_rvsw: v cannot be NULL\");\n  SB_CHK_ERR(!w, abort(), \"sb_vec_rvsw: w cannot be NULL\");\n#endif\n#ifdef SAFE_LAYOUT\n  SB_CHK_ERR(r->layout != v->layout, abort(),\n      \"sb_vec_rvsw: r and v must have same layout\");\n  SB_CHK_ERR(r->layout != w->layout, abort(),\n      \"sb_vec_rvsw: r and w must have same layout\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(r->n_elem != v->n_elem, abort(),\n      \"sb_vec_rvsw: r and v must have same length\");\n  SB_CHK_ERR(r->n_elem != w->n_elem, abort(),\n      \"sb_vec_rvsw: r and w must have same length\");\n#endif\n  double * r_data = r->data;\n  double * v_data = v->data;\n  double * w_data = w->data;\n  for (size_t a = 0; a < r->n_elem; ++a) {\n    r_data[a] = fma(r_data[a], v_data[a], -w_data[a]);\n  }\n#ifdef SAFE_FINITE\n  SB_CHK_ERR(!sb_vec_is_finite(r), abort(), \"sb_vec_rvsw: elements not finite\");\n#endif\n  return r;\n}\n\n/// Finds the sum of the elements of the vector `v`.\n///\n/// # Parameters\n/// - `v`: pointer to the vector\n///\n/// # Returns\n/// The sum of the elements of `v`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` is not `NULL`\n/// - `SAFE_FINITE`: sum is finite\n///\n/// # Examples\n/// ```\n/// #include <stdio.h>\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2.};\n///   sb_vec * v = sb_vec_of_arr(a, 3, 'r');\n/// \n///   // Sum the elements of v\n///   sb_vec_print(v, \"v: \", \"%g\");\n///   printf(\"sum of v: %g\\n\", sb_vec_sum(v));\n///\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\ndouble sb_vec_sum(const sb_vec * v) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_vec_sum: v cannot be NULL\");\n#endif\n  double * data = v->data;\n  double out = 0.;\n  for (size_t a = 0; a < v->n_elem; ++a) {\n    out += data[a];\n  }\n#ifdef SAFE_FINITE\n  SB_CHK_ERR(!isfinite(out), abort(), \"sb_vec_sum: sum not finite\");\n#endif\n  return out;\n}\n\n/// Finds the Euclidean norm of the vector `v`.\n///\n/// # Parameters\n/// - `v`: pointer to the vector\n///\n/// # Returns\n/// The Euclidean norm of `v`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` is not `NULL`\n/// - `SAFE_FINITE`: norm is finite\n///\n/// # Examples\n/// ```\n/// #include <stdio.h>\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2.};\n///   sb_vec * v = sb_vec_of_arr(a, 3, 'r');\n/// \n///   // Norm of v\n///   sb_vec_print(v, \"v: \", \"%g\");\n///   printf(\"norm of v: %g\\n\", sb_vec_norm(v));\n///\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\ndouble sb_vec_norm(const sb_vec * v) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_vec_norm: v cannot be NULL\");\n#endif\n  double out = cblas_dnrm2(v->n_elem, v->data, 1);\n#ifdef SAFE_FINITE\n  SB_CHK_ERR(!isfinite(out), abort(), \"sb_vec_norm: norm not finite\");\n#endif\n  return out;\n}\n\n/// Finds the dot product of the vectors `v` and `w`. Layout of `v` and `w` is\n/// ignored.\n///\n/// # Parameters\n/// - `v`: pointer to the first vector\n/// - `w`: pointer to the second vector\n///\n/// # Returns\n/// The dot product of `v` and `w`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` and `w` are not `NULL`\n/// - `SAFE_LENGTH`: `v` and `w` have the same length\n/// - `SAFE_FINITE`: dot product is finite\n///\n/// # Examples\n/// ```\n/// #include <stdio.h>\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7.};\n///   sb_vec * v = sb_vec_of_arr(a,     3, 'r');\n///   sb_vec * w = sb_vec_of_arr(a + 3, 3, 'r');\n/// \n///   // Find the dot product of v and w\n///   sb_vec_print(v, \"v: \", \"%g\");\n///   sb_vec_print(w, \"w: \", \"%g\");\n///   printf(\"dot product: %g\\n\", sb_vec_dot(v, w));\n///\n///   SB_VEC_FREE_ALL(v, w);\n/// }\n/// ```\ndouble sb_vec_dot(const sb_vec * restrict v, const sb_vec * restrict w) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_vec_dot: v cannot be NULL\");\n  SB_CHK_ERR(!w, abort(), \"sb_vec_dot: w cannot be NULL\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(v->n_elem != w->n_elem, abort(),\n      \"sb_vec_dot: v and w must have same length\");\n#endif\n  double out = cblas_ddot(v->n_elem, v->data, 1, w->data, 1);\n#ifdef SAFE_FINITE\n  SB_CHK_ERR(!isfinite(out), abort(), \"sb_vec_dot: dot product not finite\");\n#endif\n  return out;\n}\n\n/// Finds the outer product of the vectors `v` and `w` and adds the result to\n/// the matrix `A`. `v` and `w` must be column and row vectors, respectively,\n/// and the matrix `A` must have the same number of rows as `v` and the same\n/// number of columns as `w`.\n///\n/// # Parameters\n/// - `v`: pointer to the first vector\n/// - `w`: pointer to the second vector\n/// - `A`: pointer to the matrix\n///\n/// # Returns\n/// A copy of `A`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v`, `w` and `A` are not `NULL`\n/// - `SAFE_LAYOUT`: `v` is a column vector and `w` is a row vector\n/// - `SAFE_LENGTH`: `v` and `A` have the same number of rows, and `w` and\n///                  `A` have the same number of columns\n/// - `SAFE_FINITE`: elements of `A` are finite\n///\n/// # Examples\n/// ```\n/// #include <assert.h>\n/// #include \"sb_matrix.h\"\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7.};\n///   sb_vec * v = sb_vec_of_arr(a,     3, 'c');\n///   sb_vec * w = sb_vec_of_arr(a + 3, 3, 'r');\n/// \n///   // Store the outer product in A\n///   sb_mat * A = sb_mat_calloc(3, 3);\n///   sb_mat_print(sb_vec_outer(A, v, w), \"A: \", \"%g\");\n///\n///   SB_VEC_FREE_ALL(v, w);\n/// }\n/// ```\nsb_mat * sb_vec_outer(\n    sb_mat * restrict A,\n    const sb_vec * restrict v,\n    const sb_vec * restrict w) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_vec_outer: v cannot be NULL\");\n  SB_CHK_ERR(!w, abort(), \"sb_vec_outer: w cannot be NULL\");\n  SB_CHK_ERR(!A, abort(), \"sb_vec_outer: A cannot be NULL\");\n#endif\n#ifdef SAFE_LAYOUT\n  SB_CHK_ERR(v->layout != 'c', abort(), \"sb_vec_outer: v must be a column vector\");\n  SB_CHK_ERR(w->layout != 'r', abort(), \"sb_vec_outer: w must be a row vector\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(v->n_elem != A->n_rows, abort(),\n      \"sb_vec_outer: v and A must have same number of rows\");\n  SB_CHK_ERR(w->n_elem != A->n_cols, abort(),\n      \"sb_vec_outer: w and A must have same number of cols\");\n#endif\n  cblas_dger(CblasColMajor, v->n_elem, w->n_elem, 1., v->data, 1, w->data, 1,\n      A->data, A->n_rows);\n#ifdef SAFE_FINITE\n  SB_CHK_ERR(!sb_mat_is_finite(A), abort(), \"sb_vec_outer: A is not finite\");\n#endif\n  return A;\n}\n\n/// Reverses the order of elements in the vector `v`.\n///\n/// # Parameters\n/// - `v`: pointer to the vector\n///\n/// # Returns\n/// A copy of `v`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` is not `NULL`\n///\n/// # Examples\n/// ```\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2.};\n///   sb_vec * v = sb_vec_of_arr(a, 3, 'r');\n/// \n///   // Print vector and reverse\n///   sb_vec_print(v, \"v before: \", \"%g\");\n///   sb_vec_reverse(v);\n///   sb_vec_print(v, \"v after: \", \"%g\");\n///\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\nsb_vec * sb_vec_reverse(sb_vec * v) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_vec_reverse: v cannot be NULL\");\n#endif\n  size_t n_elem = v->n_elem;\n  double * data = v->data;\n\n  size_t b;\n  double scratch;\n  for (size_t a = 0; a < n_elem / 2; ++a) {\n    b = n_elem - a - 1;\n    SB_SWAP(data[a], data[b], scratch);\n  }\n  return v;\n}\n\n// FOR USE ONLY WITH SB_VEC_SORT_INC\nstatic int dcmp_inc(const void * pa, const void * pb) {\n  double a = *(const double *)pa;\n  double b = *(const double *)pb;\n\n  if (a < b) { return -1; }\n  if (b < a) { return  1; }\n  return 0;\n}\n\n/// Sorts the elements of the vector `v` in increasing order.\n///\n/// # Parameters\n/// - `v`: pointer to the vector\n///\n/// # Returns\n/// A copy of `v`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` is not `NULL`\n/// - `SAFE_FINITE`: elements of `v` are finite\n///\n/// # Examples\n/// ```\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2.};\n///   sb_vec * v = sb_vec_of_arr(a, 3, 'r');\n/// \n///   // Sort vector and print\n///   sb_vec_print(v, \"v before: \", \"%g\");\n///   sb_vec_sort_inc(v);\n///   sb_vec_print(v, \"v after: \", \"%g\");\n///\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\nsb_vec * sb_vec_sort_inc(sb_vec * v) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_vec_sort_inc: v cannot be NULL\");\n#endif\n#ifdef SAFE_FINITE\n  SB_CHK_ERR(!sb_vec_is_finite(v), abort(), \"sb_vec_sort_inc: v is not finite\");\n#endif\n  qsort(v->data, v->n_elem, sizeof(double), dcmp_inc);\n  return v;\n}\n\n// FOR USE ONLY WITH SB_VEC_SORT_DEC\nstatic int dcmp_dec(const void * pa, const void * pb) {\n  double a = *(const double *)pa;\n  double b = *(const double *)pb;\n\n  if (b < a) { return -1; }\n  if (a < b) { return  1; }\n  return 0;\n}\n\n/// Sorts the elements of the vector `v` in decreasing order.\n///\n/// # Parameters\n/// - `v`: pointer to the vector\n///\n/// # Returns\n/// A copy of `v`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` is not `NULL`\n/// - `SAFE_FINITE`: elements of `v` are finite\n///\n/// # Examples\n/// ```\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2.};\n///   sb_vec * v = sb_vec_of_arr(a, 3, 'r');\n/// \n///   // Sort vector and print\n///   sb_vec_print(v, \"v before: \", \"%g\");\n///   sb_vec_sort_dec(v);\n///   sb_vec_print(v, \"v after: \", \"%g\");\n///\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\nsb_vec * sb_vec_sort_dec(sb_vec * v) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_vec_sort_dec: v cannot be NULL\");\n#endif\n#ifdef SAFE_FINITE\n  SB_CHK_ERR(!sb_vec_is_finite(v), abort(), \"sb_vec_sort_dec: v is not finite\");\n#endif\n  qsort(v->data, v->n_elem, sizeof(double), dcmp_dec);\n  return v;\n}\n\n/// Transposes the vector `v`. NOTE: This is a non-op when `SAFE_LAYOUT` is not\n/// defined, possibly leading to unexpected behavior with e.g. sb_vec_print().\n///\n/// # Parameters\n/// - `v`: pointer to the vector\n///\n/// # Returns\n/// A copy of `v`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` is not `NULL`\n/// - `SAFE_LAYOUT`: `layout` is `c` or `r`\n///\n/// # Examples\n/// ```\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2.};\n///   sb_vec * v = sb_vec_of_arr(a, 3, 'r');\n/// \n///   // Print vector and transpose\n///   sb_vec_print(v, \"v before: \", \"%g\");\n///   sb_vec_trans(v);\n///   sb_vec_print(v, \"v after: \", \"%g\");\n///\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\nsb_vec * sb_vec_trans(sb_vec * v) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_vec_trans: v cannot be NULL\");\n#endif\n#ifdef SAFE_LAYOUT\n  SB_CHK_ERR(v->layout != 'c' && v->layout != 'r', abort(),\n      \"sb_vec_trans: v has invalid layout\");\n  v->layout = (v->layout == 'c' ? 'r' : 'c');\n#endif\n  return v;\n}\n\n/// Checks the vectors `v` and `w` for equality of elements. Vectors must have\n/// the same length and layout.\n///\n/// # Parameters\n/// - `v`: pointer to the first vector\n/// - `w`: pointer to the second vector\n///\n/// # Returns\n/// `1` if `v` and `w` are equal, and `0` otherwise\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` and `w` are not `NULL`\n/// - `SAFE_LAYOUT`: `v` and `w` have the same layout\n/// - `SAFE_LENGTH`: `v` and `w` have the same length\n/// - `SAFE_FINITE`: elements of `v` and `w` are finite\n///\n/// # Examples\n/// ```\n/// #include <assert.h>\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2., 8., 5., 7.};\n///   sb_vec * v = sb_vec_of_arr(a,     3, 'r');\n///   sb_vec * w = sb_vec_of_arr(a + 3, 3, 'r');\n/// \n///   // v and w are equal after sb_vec_memcpy\n///   assert(!sb_vec_is_equal(v, w));\n///   sb_vec_memcpy(w, v);\n///   assert( sb_vec_is_equal(v, w));\n///\n///   SB_VEC_FREE_ALL(v, w);\n/// }\n/// ```\nint sb_vec_is_equal(const sb_vec * restrict v, const sb_vec * restrict w) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_vec_is_equal: v cannot be NULL\");\n  SB_CHK_ERR(!w, abort(), \"sb_vec_is_equal: w cannot be NULL\");\n#endif\n#ifdef SAFE_LAYOUT\n  SB_CHK_ERR(v->layout != w->layout, abort(),\n      \"sb_vec_is_equal: v and w must have same layout\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(v->n_elem != w->n_elem, abort(),\n      \"sb_vec_is_equal: v and w must have same length\");\n#endif\n  double * v_data = v->data;\n  double * w_data = w->data;\n  for (size_t a = 0; a < v->n_elem; ++a) {\n#ifdef SAFE_FINITE\n    SB_CHK_ERR(!isfinite(v_data[a]), abort(), \"sb_vec_is_equal: v is not finite\");\n    SB_CHK_ERR(!isfinite(w_data[a]), abort(), \"sb_vec_is_equal: w is not finite\");\n#endif\n    if (v_data[a] != w_data[a]) {\n      return 0;\n    }\n  }\n  return 1;\n}\n\n/// Checks if all elements of the vector `v` are zero.\n///\n/// # Parameters\n/// - `v`: pointer to the vector\n///\n/// # Returns\n/// `1` if all elements of `v` are zero, and `0` otherwise\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` is not `NULL`\n///\n/// # Examples\n/// ```\n/// #include <assert.h>\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2.};\n///   sb_vec * v = sb_vec_of_arr(a, 3, 'r');\n/// \n///   // v is zero after sb_vec_set_zero\n///   assert(!sb_vec_is_zero(v));\n///   sb_vec_set_zero(v);\n///   assert( sb_vec_is_zero(v));\n///\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\nint sb_vec_is_zero(const sb_vec * v) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_vec_is_zero: v cannot be NULL\");\n#endif\n  double * data = v->data;\n  for (size_t a = 0; a < v->n_elem; ++a) {\n    if (data[a] != 0.) {\n      return 0;\n    }\n  }\n  return 1;\n}\n\n/// Checks if all elements of the vector `v` are positive.\n///\n/// # Parameters\n/// - `v`: pointer to the vector\n///\n/// # Returns\n/// `1` if all elements of `v` are positive, and `0` otherwise\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` is not `NULL`\n/// - `SAFE_FINITE`: elements of `v` are finite\n///\n/// # Examples\n/// ```\n/// #include <assert.h>\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {-1., -4., -2.};\n///   sb_vec * v = sb_vec_of_arr(a, 3, 'r');\n/// \n///   // v is positive after sb_vec_abs\n///   assert(!sb_vec_is_pos(v));\n///   sb_vec_abs(v);\n///   assert( sb_vec_is_pos(v));\n///\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\nint sb_vec_is_pos(const sb_vec * v) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_vec_is_pos: v cannot be NULL\");\n#endif\n  double * data = v->data;\n  for (size_t a = 0; a < v->n_elem; ++a) {\n#ifdef SAFE_FINITE\n    SB_CHK_ERR(!isfinite(data[a]), abort(), \"sb_vec_is_pos: v is not finite\");\n#endif\n    if (data[a] <= 0.) {\n      return 0;\n    }\n  }\n  return 1;\n}\n\n/// Checks if all elements of the vector `v` are negative.\n///\n/// # Parameters\n/// - `v`: pointer to the vector\n///\n/// # Returns\n/// `1` if all elements of `v` are negative, and `0` otherwise\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` is not `NULL`\n/// - `SAFE_FINITE`: elements of `v` are finite\n///\n/// # Examples\n/// ```\n/// #include <assert.h>\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., -4., 2.};\n///   sb_vec * v = sb_vec_of_arr(a, 3, 'r');\n/// \n///   // v is negative after\n///   assert(!sb_vec_is_neg(v));\n///   sb_vec_smul(sb_vec_abs(v), -1.);\n///   assert( sb_vec_is_neg(v));\n///\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\nint sb_vec_is_neg(const sb_vec * v) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_vec_is_neg: v cannot be NULL\");\n#endif\n  double * data = v->data;\n  for (size_t a = 0; a < v->n_elem; ++a) {\n#ifdef SAFE_FINITE\n    SB_CHK_ERR(!isfinite(data[a]), abort(), \"sb_vec_is_neg: v is not finite\");\n#endif\n    if (data[a] >= 0.) {\n      return 0;\n    }\n  }\n  return 1;\n}\n\n/// Checks if all elements of the vector `v` are nonnegative.\n///\n/// # Parameters\n/// - `v`: pointer to the vector\n///\n/// # Returns\n/// `1` if all elements of `v` are nonnegative, and `0` otherwise\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` is not `NULL`\n/// - `SAFE_FINITE`: elements of `v` are finite\n///\n/// # Examples\n/// ```\n/// #include <assert.h>\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {0., -1., 4.};\n///   sb_vec * v = sb_vec_of_arr(a, 3, 'r');\n/// \n///   // v is nonnegative after\n///   assert(!sb_vec_is_nonneg(v));\n///   sb_vec_abs(v);\n///   assert( sb_vec_is_nonneg(v));\n///\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\nint sb_vec_is_nonneg(const sb_vec * v) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_vec_is_nonneg: v cannot be NULL\");\n#endif\n  double * data = v->data;\n  for (size_t a = 0; a < v->n_elem; ++a) {\n#ifdef SAFE_FINITE\n    SB_CHK_ERR(!isfinite(data[a]), abort(), \"sb_vec_is_nonneg: v is not finite\");\n#endif\n    if (data[a] < 0.) {\n      return 0;\n    }\n  }\n  return 1;\n}\n\n/// Checks if all elements of the vector `v` are not infinite or `NaN`.\n///\n/// # Parameters\n/// - `v`: pointer to the sb_vector\n///\n/// # Returns\n/// `1` if all elements of `v` are not infinite or `NaN`, and `0` otherwise\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` is not `NULL`\n///\n/// # Examples\n/// ```\n/// #include <assert.h>\n/// #include <math.h>\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., INFINITY, 2.};\n///   sb_vec * v = sb_vec_of_arr(a, 3, 'r');\n/// \n///   assert(!sb_vec_is_finite(v));\n///   sb_vec_set(v, 1, NAN);\n///   assert(!sb_vec_is_finite(v));\n///   sb_vec_set(v, 1, 4.);\n///   assert( sb_vec_is_finite(v));\n///\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\nint sb_vec_is_finite(const sb_vec * v) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_vec_is_finite: v cannot be NULL\");\n#endif\n  double * data = v->data;\n  for (size_t a = 0; a < v->n_elem; ++a) {\n    if (!isfinite(data[a])) {\n      return 0;\n    }\n  }\n  return 1;\n}\n\n/// Finds the value of the maximum element of `v`.\n///\n/// # Parameters\n/// - `v`: pointer to the vector\n///\n/// # Returns\n/// Value of the maximum element\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` is not `NULL`\n/// - `SAFE_LENGTH`: number of elements is nonzero\n/// - `SAFE_FINITE`: elements of `v` are finite\n///\n/// # Examples\n/// ```\n/// #include <assert.h>\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2.};\n///   sb_vec * v = sb_vec_of_arr(a, 3, 'r');\n/// \n///   // maximum value of v is 4.\n///   assert(sb_vec_max(v) == 4.);\n///\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\ndouble sb_vec_max(const sb_vec * v) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_vec_max: v cannot be NULL\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(v->n_elem == 0, abort(), \"sb_vec_max: n_elem must be nonzero\");\n#endif\n  double * data = v->data;\n  double max_val = -INFINITY;\n  for (size_t a = 0; a < v->n_elem; ++a) {\n#ifdef SAFE_FINITE\n    SB_CHK_ERR(!isfinite(data[a]), abort(), \"sb_vec_max: v is not finite\");\n#endif\n    if (data[a] > max_val) {\n      max_val = data[a];\n    }\n  }\n  return max_val;\n}\n\n/// Finds the value of the minimum element of `v`.\n///\n/// # Parameters\n/// - `v`: pointer to the vector\n///\n/// # Returns\n/// Value of the minimum element\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` is not `NULL`\n/// - `SAFE_LENGTH`: number of elements is nonzero\n/// - `SAFE_FINITE`: elements of `v` are finite\n///\n/// # Examples\n/// ```\n/// #include <assert.h>\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2.};\n///   sb_vec * v = sb_vec_of_arr(a, 3, 'r');\n/// \n///   // value of min is 1\n///   assert(sb_vec_min(v) == 1.);\n///\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\ndouble sb_vec_min(const sb_vec * v) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_vec_min: v cannot be NULL\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(v->n_elem == 0, abort(), \"sb_vec_min: n_elem must be nonzero\");\n#endif\n  double * data = v->data;\n  double min_val = INFINITY;\n  for (size_t a = 0; a < v->n_elem; ++a) {\n#ifdef SAFE_FINITE\n    SB_CHK_ERR(!isfinite(data[a]), abort(), \"sb_vec_min: v is not finite\");\n#endif\n    if (data[a] < min_val) {\n      min_val = data[a];\n    }\n  }\n  return min_val;\n}\n\n/// Finds the maximum absolute value of the elements of `v`.\n///\n/// # Parameters\n/// - `v`: pointer to the vector\n///\n/// # Returns\n/// Maximum absolute value of the elements\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` is not `NULL`\n/// - `SAFE_LENGTH`: number of elements is nonzero\n/// - `SAFE_FINITE`: elements of `v` are finite\n///\n/// # Examples\n/// ```\n/// #include <assert.h>\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., -4., 2.};\n///   sb_vec * v = sb_vec_of_arr(a, 3, 'r');\n/// \n///   // maximum absolute value of v is 4.\n///   assert(sb_vec_abs_max(v) == 4.);\n///\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\ndouble sb_vec_abs_max(const sb_vec * v) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_vec_abs_max: v cannot be NULL\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(v->n_elem == 0, abort(), \"sb_vec_abs_max: n_elem must be nonzero\");\n#endif\n  double * data = v->data;\n  size_t index = cblas_idamax(v->n_elem, data, 1);\n#ifdef SAFE_FINITE\n  SB_CHK_ERR(!isfinite(data[index]), abort(), \"sb_vec_abs_max: v is not finite\");\n#endif\n  return fabs(data[index]);\n}\n\n/// Finds the index of the maximum element of `v`.\n///\n/// # Parameters\n/// - `v`: pointer to the sb_vector\n///\n/// # Returns\n/// Index of the maximum element\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` is not `NULL`\n/// - `SAFE_LENGTH`: number of elements is nonzero\n/// - `SAFE_FINITE`: elements of `v` are finite\n///\n/// # Examples\n/// ```\n/// #include <assert.h>\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2.};\n///   sb_vec * v = sb_vec_of_arr(a, 3, 'r');\n/// \n///   // index of max is 1\n///   assert(sb_vec_max_index(v) == 1);\n///\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\nsize_t sb_vec_max_index(const sb_vec * v) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_vec_max_index: v cannot be NULL\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(v->n_elem == 0, abort(), \"sb_vec_max_index: n_elem must be nonzero\");\n#endif\n  double * data = v->data;\n  double max_val = -INFINITY;\n  size_t max_ind = 0;\n  for (size_t a = 0; a < v->n_elem; ++a) {\n#ifdef SAFE_FINITE\n    SB_CHK_ERR(!isfinite(data[a]), abort(), \"sb_vec_max_index: v is not finite\");\n#endif\n    if (data[a] > max_val) {\n      max_val = data[a];\n      max_ind = a;\n    }\n  }\n  return max_ind;\n}\n\n/// Finds the index of the minimum element of `v`.\n///\n/// # Parameters\n/// - `v`: pointer to the vector\n///\n/// # Returns\n/// Index of the minimum element\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` is not `NULL`\n/// - `SAFE_LENGTH`: number of elements is nonzero\n/// - `SAFE_FINITE`: elements of `v` are finite\n///\n/// # Examples\n/// ```\n/// #include <assert.h>\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., 4., 2.};\n///   sb_vec * v = sb_vec_of_arr(a, 3, 'r');\n/// \n///   // index of min is 0\n///   assert(sb_vec_min_index(v) == 0);\n///\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\nsize_t sb_vec_min_index(const sb_vec * v) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_vec_min_index: v cannot be NULL\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(v->n_elem == 0, abort(), \"sb_vec_min_index: n_elem must be nonzero\");\n#endif\n  double * data = v->data;\n  double min_val = INFINITY;\n  size_t min_ind = 0;\n  for (size_t a = 0; a < v->n_elem; ++a) {\n#ifdef SAFE_FINITE\n    SB_CHK_ERR(!isfinite(data[a]), abort(), \"sb_vec_min_index: v is not finite\");\n#endif\n    if (data[a] < min_val) {\n      min_val = data[a];\n      min_ind = a;\n    }\n  }\n  return min_ind;\n}\n\n/// Finds the index of the maximum absolute value of the elements of `v`.\n///\n/// # Parameters\n/// - `v`: pointer to the vector\n///\n/// # Returns\n/// Index of the maximum absolute value of the elements\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `v` is not `NULL`\n/// - `SAFE_LENGTH`: number of elements is nonzero\n///\n/// # Examples\n/// ```\n/// #include <assert.h>\n/// #include \"sb_structs.h\"\n/// #include \"sb_vector.h\"\n///\n/// int main(void) {\n///   double a[] = {1., -4., 2.};\n///   sb_vec * v = sb_vec_of_arr(a, 3, 'r');\n/// \n///   // index of the maximum absolute value of v is 1\n///   assert(sb_vec_abs_max_index(v) == 1);\n///\n///   SB_VEC_FREE_ALL(v);\n/// }\n/// ```\nsize_t sb_vec_abs_max_index(const sb_vec * v) {\n#ifdef SAFE_MEMORY\n  SB_CHK_ERR(!v, abort(), \"sb_vec_abs_min_index: v cannot be NULL\");\n#endif\n#ifdef SAFE_LENGTH\n  SB_CHK_ERR(v->n_elem == 0, abort(), \"sb_vec_abs_min_index: n_elem must be nonzero\");\n#endif\n  return cblas_idamax(v->n_elem, v->data, 1);\n}\n\nextern inline double sb_vec_get(const sb_vec * v, size_t i);\nextern inline void sb_vec_set(sb_vec * v, size_t i, double x);\nextern inline double * sb_vec_ptr(sb_vec * v, size_t i);\n", "meta": {"hexsha": "3e9ef1289d61fb849bfc7fcad3d679323c6aab22", "size": 74254, "ext": "c", "lang": "C", "max_stars_repo_path": "src/vector.c", "max_stars_repo_name": "harharkh/sb_desc", "max_stars_repo_head_hexsha": "e2fa146692aa4417e77366ce5ba85d9fdecc2a9c", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2019-07-08T22:34:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T20:06:47.000Z", "max_issues_repo_path": "src/vector.c", "max_issues_repo_name": "harharkh/sb_desc", "max_issues_repo_head_hexsha": "e2fa146692aa4417e77366ce5ba85d9fdecc2a9c", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-07-10T06:53:41.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-10T06:53:41.000Z", "max_forks_repo_path": "src/vector.c", "max_forks_repo_name": "harharkh/sb_desc", "max_forks_repo_head_hexsha": "e2fa146692aa4417e77366ce5ba85d9fdecc2a9c", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2391782832, "max_line_length": 92, "alphanum_fraction": 0.5957389501, "num_tokens": 22898, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.26588047309981694, "lm_q2_score": 0.058345840202334215, "lm_q1q2_score": 0.01551301959640294}}
{"text": "#ifndef _SNPLIB_SRC_MATH_LIB_H_\n#define _SNPLIB_SRC_MATH_LIB_H_\n\n#ifdef USE_MKL\n#include <mkl.h>\n#define set_num_threads mkl_set_num_threads\n#endif\n#ifdef USE_OPENBLAS\n#ifdef _MSC_VER\n#include <complex>\n#define lapack_complex_float std::complex<float>\n#define lapack_complex_double std::complex<double>\n#endif\n#include <cblas.h>\n#include <lapacke.h>\n#define set_num_threads openblas_set_num_threads\n#endif\n\n#endif //_SNPLIB_SRC_MATH_LIB_H_\n", "meta": {"hexsha": "5cf38a7eea848fea57ef741a7f6cbaa81b09d893", "size": 440, "ext": "h", "lang": "C", "max_stars_repo_path": "src/math_lib.h", "max_stars_repo_name": "VasLem/SNPLIB", "max_stars_repo_head_hexsha": "aea1cb943a7db22faa592a53cf1132561ce50c4e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-21T04:55:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-05T18:01:23.000Z", "max_issues_repo_path": "src/math_lib.h", "max_issues_repo_name": "VasLem/SNPLIB", "max_issues_repo_head_hexsha": "aea1cb943a7db22faa592a53cf1132561ce50c4e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/math_lib.h", "max_forks_repo_name": "VasLem/SNPLIB", "max_forks_repo_head_hexsha": "aea1cb943a7db22faa592a53cf1132561ce50c4e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-17T17:20:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T17:20:24.000Z", "avg_line_length": 22.0, "max_line_length": 50, "alphanum_fraction": 0.8295454545, "num_tokens": 115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3849121585956185, "lm_q2_score": 0.04023794406228033, "lm_q1q2_score": 0.015488073906462074}}
{"text": "#include \"jfftw_complex_Plan.h\"\n#include <fftw.h>\n\n/*\n * Class:     jfftw_complex_Plan\n * Method:    createPlan\n * Signature: (III)V\n */\nJNIEXPORT void JNICALL Java_jfftw_complex_Plan_createPlan( JNIEnv *env, jobject obj, jint n, jint dir, jint flags )\n{\n\tjclass clazz;\n\tjfieldID id;\n\tjbyteArray arr;\n\tunsigned char* carr;\n\n\tif( sizeof( jdouble ) != sizeof( fftw_real ) )\n\t{\n\t\t(*env)->ThrowNew( env, (*env)->FindClass( env, \"java/lang/RuntimeException\" ), \"jdouble and fftw_real are incompatible\" );\n\t\treturn;\n\t}\n\n\tclazz = (*env)->GetObjectClass( env, obj );\n\tid    = (*env)->GetFieldID( env, clazz, \"plan\", \"[B\" );\n\tarr   = (*env)->NewByteArray( env, sizeof( fftw_plan ) );\n\tcarr  = (*env)->GetByteArrayElements( env, arr, 0 );\n\n\t(*env)->MonitorEnter( env, (*env)->FindClass( env, \"jfftw/Plan\" ) );\n\n\t*(fftw_plan*)carr = fftw_create_plan( n, dir, flags );\n\n\t(*env)->MonitorExit( env, (*env)->FindClass( env, \"jfftw/Plan\" ) );\n\n\t(*env)->ReleaseByteArrayElements( env, arr, carr, 0 );\n\t(*env)->SetObjectField( env, obj, id, arr );\n}\n/*\n * Class:     jfftw_complex_Plan\n * Method:    createPlanSpecific\n * Signature: (III[DI[DI)V\n */\nJNIEXPORT void JNICALL Java_jfftw_complex_Plan_createPlanSpecific( JNIEnv *env, jobject obj, jint n, jint dir, jint flags, jdoubleArray in, jint idist, jdoubleArray out, jint odist )\n{\n\tjclass clazz;\n\tjfieldID id;\n\tjbyteArray arr;\n\tunsigned char* carr;\n\tdouble *cin, *cout;\n\n\tif( sizeof( jdouble ) != sizeof( fftw_real ) )\n\t{\n\t\t(*env)->ThrowNew( env, (*env)->FindClass( env, \"java/lang/RuntimeException\" ), \"jdouble and fftw_real are incompatible\" );\n\t\treturn;\n\t}\n\n\tclazz = (*env)->GetObjectClass( env, obj );\n\tid    = (*env)->GetFieldID( env, clazz, \"plan\", \"[B\" );\n\tarr   = (*env)->NewByteArray( env, sizeof( fftw_plan ) );\n\tcarr  = (*env)->GetByteArrayElements( env, arr, 0 );\n\tcin   = (*env)->GetDoubleArrayElements( env, in, 0 );\n\tcout  = (*env)->GetDoubleArrayElements( env, out, 0 );\n\n\t(*env)->MonitorEnter( env, (*env)->FindClass( env, \"jfftw/Plan\" ) );\n\n\t*(fftw_plan*)carr = fftw_create_plan_specific( n, dir, flags, (fftw_complex*)cin, idist, (fftw_complex*)cout, odist );\n\n\t(*env)->MonitorExit( env, (*env)->FindClass( env, \"jfftw/Plan\" ) );\n\n\t(*env)->ReleaseDoubleArrayElements( env, in, cin, 0 );\n\t(*env)->ReleaseDoubleArrayElements( env, out, cout, 0 );\n\t(*env)->ReleaseByteArrayElements( env, arr, carr, 0 );\n\t(*env)->SetObjectField( env, obj, id, arr );\n}\n/*\n * Class:     jfftw_complex_Plan\n * Method:    destroyPlan\n * Signature: ()V\n */\nJNIEXPORT void JNICALL Java_jfftw_complex_Plan_destroyPlan( JNIEnv* env, jobject obj )\n{\n\tjclass clazz = (*env)->GetObjectClass( env, obj );\n\tjfieldID id = (*env)->GetFieldID( env, clazz, \"plan\", \"[B\" );\n\tjbyteArray arr = (jbyteArray)(*env)->GetObjectField( env, obj, id );\n\tunsigned char* carr = (*env)->GetByteArrayElements( env, arr, 0 );\n\n\tfftw_destroy_plan( *(fftw_plan*)carr );\n\n\t(*env)->ReleaseByteArrayElements( env, arr, carr, 0 );\n\t(*env)->SetObjectField( env, obj, id, NULL );\n}\n/*\n * Class:     jfftw_complex_Plan\n * Method:    transform\n * Signature: ([D)[D\n */\nJNIEXPORT jdoubleArray JNICALL Java_jfftw_complex_Plan_transform___3D( JNIEnv* env, jobject obj, jdoubleArray in )\n{\n\tjdouble *cin, *cout;\n\tjdoubleArray out;\n\tint i;\n\n\tjclass clazz = (*env)->GetObjectClass( env, obj );\n\tjfieldID id = (*env)->GetFieldID( env, clazz, \"plan\", \"[B\" );\n\tjbyteArray arr = (jbyteArray)(*env)->GetObjectField( env, obj, id );\n\tunsigned char* carr = (*env)->GetByteArrayElements( env, arr, 0 );\n\tfftw_plan plan = *(fftw_plan*)carr;\n\tif( plan->n * 2 != (*env)->GetArrayLength( env, in ) )\n\t{\n\t\t(*env)->ThrowNew( env, (*env)->FindClass( env, \"java/lang/IndexOutOfBoundsException\" ), \"the Plan was created for a different length\" );\n\t\t(*env)->ReleaseByteArrayElements( env, arr, carr, 0 );\n\t\treturn NULL;\n\t}\n\n\tcin = (*env)->GetDoubleArrayElements( env, in, 0 );\n\n\tif( ! plan->flags & FFTW_THREADSAFE )\n\t{\n\t\t// synchronization\n\t\t(*env)->MonitorEnter( env, obj );\n\t}\n\n\tif( plan->flags & FFTW_IN_PLACE )\n\t{\n\t\tout = in;\n\n\t\tfftw_one( plan, (fftw_complex*)cin, NULL );\n\t}\n\telse\n\t{\n\t\tout = (*env)->NewDoubleArray( env, plan->n * 2 );\n\t\tcout = (*env)->GetDoubleArrayElements( env, out, 0 );\n\n\t\tfftw_one( plan, (fftw_complex*)cin, (fftw_complex*)cout );\n\n\t\t(*env)->ReleaseDoubleArrayElements( env, out, cout, 0 );\n\t}\n\n\tif( ! plan->flags & FFTW_THREADSAFE )\n\t{\n\t\t// synchronization\n\t\t(*env)->MonitorEnter( env, obj );\n\t}\n\n\t(*env)->ReleaseByteArrayElements( env, arr, carr, 0 );\n\t(*env)->ReleaseDoubleArrayElements( env, in, cin, 0 );\n\treturn out;\n}\n/*\n * Class:     jfftw_complex_Plan\n * Method:    transform\n * Signature: (I[DII[DII)V\n */\nJNIEXPORT void JNICALL Java_jfftw_complex_Plan_transform__I_3DII_3DII( JNIEnv *env, jobject obj, jint howmany, jdoubleArray in, jint istride, jint idist, jdoubleArray out, jint ostride, jint odist )\n{\n\tjdouble *cin, *cout;\n\tint i;\n\n\tjclass clazz = (*env)->GetObjectClass( env, obj );\n\tjfieldID id = (*env)->GetFieldID( env, clazz, \"plan\", \"[B\" );\n\tjbyteArray arr = (jbyteArray)(*env)->GetObjectField( env, obj, id );\n\tunsigned char* carr = (*env)->GetByteArrayElements( env, arr, 0 );\n\tfftw_plan plan = *(fftw_plan*)carr;\n\tif( (howmany - 1) * idist * 2 + plan->n * istride * 2 != (*env)->GetArrayLength( env, in ) )\n\t{\n\t\t(*env)->ThrowNew( env, (*env)->FindClass( env, \"java/lang/IndexOutOfBoundsException\" ), \"the Plan was created for a different length (in)\" );\n\t\t(*env)->ReleaseByteArrayElements( env, arr, carr, 0 );\n\t\treturn;\n\t}\n\tif( (howmany - 1) * odist * 2 + plan->n * ostride * 2 != (*env)->GetArrayLength( env, out ) )\n\t{\n\t\t(*env)->ThrowNew( env, (*env)->FindClass( env, \"java/lang/IndexOutOfBoundsException\" ), \"the Plan was created for a different length (out)\" );\n\t\t(*env)->ReleaseByteArrayElements( env, arr, carr, 0 );\n\t\treturn;\n\t}\n\n\tcin = (*env)->GetDoubleArrayElements( env, in, 0 );\n\tcout = (*env)->GetDoubleArrayElements( env, out, 0 );\n\n\tif( ! plan->flags & FFTW_THREADSAFE )\n\t{\n\t\t// synchronization\n\t\t(*env)->MonitorEnter( env, obj );\n\t}\n\tfftw( plan, howmany, (fftw_complex*)cin, istride, idist, (fftw_complex*)cout, ostride, odist );\n\tif( ! plan->flags & FFTW_THREADSAFE )\n\t{\n\t\t// synchronization\n\t\t(*env)->MonitorExit( env, obj );\n\t}\n\n\t(*env)->ReleaseByteArrayElements( env, arr, carr, 0 );\n\t(*env)->ReleaseDoubleArrayElements( env, in, cin, 0 );\n\t(*env)->ReleaseDoubleArrayElements( env, out, cout, 0 );\n}\n\n\n", "meta": {"hexsha": "fc982c291de16efbb47a4526fa4dd0774d28da4a", "size": 6346, "ext": "c", "lang": "C", "max_stars_repo_path": "triana-toolboxes/signalproc/src/main/java/signalproc/algorithms/c/jfftw_complex_Plan.c", "max_stars_repo_name": "CSCSI/Triana", "max_stars_repo_head_hexsha": "da48ffaa0183f59e3fe7c6dc59d9f91234e65809", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2015-11-02T10:12:13.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-15T21:45:38.000Z", "max_issues_repo_path": "triana-toolboxes/signalproc/src/main/java/signalproc/algorithms/c/jfftw_complex_Plan.c", "max_issues_repo_name": "CSCSI/Triana", "max_issues_repo_head_hexsha": "da48ffaa0183f59e3fe7c6dc59d9f91234e65809", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-08-28T13:52:42.000Z", "max_issues_repo_issues_event_max_datetime": "2016-01-22T13:06:00.000Z", "max_forks_repo_path": "triana-toolboxes/signalproc/src/main/java/signalproc/algorithms/c/jfftw_complex_Plan.c", "max_forks_repo_name": "CSCSI/Triana", "max_forks_repo_head_hexsha": "da48ffaa0183f59e3fe7c6dc59d9f91234e65809", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-03-08T14:04:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T05:30:21.000Z", "avg_line_length": 32.3775510204, "max_line_length": 198, "alphanum_fraction": 0.6564765206, "num_tokens": 1999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552952031526044, "lm_q2_score": 0.03461884095568607, "lm_q1q2_score": 0.015423715604857106}}
{"text": "#define ORIGIN_DATE       \"2012.01.05\"\n#define ORIGIN_VERSION    \"2.1\"\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <stdbool.h>\n#include <pthread.h>\n#include <assert.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n#include \"common.h\"\n#include \"ivector.h\"\n#include \"species.h\"\n#include \"specieslist.h\"\n#include \"graph.h\"\n#include \"utils.h\"\n\n#define MODEL_BDM_NEUTRAL      0\n#define MODEL_BDM_SELECTION    1\n\n// Parameters of the simulations.\ntypedef struct\n{\n    int m;             // Type of model.\n    int communities;   // Number of communities.\n    int j_per_c;       // Number of individuals per community.\n    int k_gen;         // Number of generations (in thousands).\n    int init_species;  // Initial number of species.\n    double mu;         // Mutation rate.\n    double omega;      // Weight of the links between communities.\n    double s;          // Selection coefficient.\n    double r;          // Radius (for random geometric graphs).\n    double w;          // Width (for rectangle random geometric graphs).\n    char *ofilename;   // Name of the output files.\n    char *shape;       // Shape of the metacommunity.\n}\nParams;\n\n// Prototype for the function used by the threads\nvoid *sim(void *parameters);\n// The function used to setup the cumulative jagged array from the graph.\ndouble **setup_cumulative_list(const graph *g, double omega);\n\n/////////////////////////////////////////////////////////////\n// Main                                                    //\n/////////////////////////////////////////////////////////////\nint main(int argc, const char *argv[])\n{\n    // Set default values;\n    Params p;\n    p.m = MODEL_BDM_SELECTION;\n    p.communities = 10;\n    p.j_per_c = 10000;\n    p.init_species = 20;\n    p.k_gen = 100;\n    p.mu = 1e-4;\n    p.omega = 5e-4;\n    p.s = 0.15;\n    p.r = 0.25;\n    p.w = 0.25;\n    p.ofilename = (char*)malloc(50);\n    p.shape = (char*)malloc(20);\n\n    // Number of simulations;\n    int n_threads = 1;\n\n    // Options;\n    if (argc > 1 && argv[1][0] == '-' && argv[1][1] == '-')\n    {\n        // --help\n        if (argv[1][2] == 'h')\n        {\n            printf(\"Usage: ./origin [options]\\n\");\n            printf(\"Example: ./origin -x=8 -shape=circle -model=1 -s=0.10\\n\");\n            printf(\"General options:\\n\");\n            printf(\"  --help          How you got here...\\n\");\n            printf(\"  --version       Display version.\\n\");\n            printf(\"  --ref           Display reference.\\n\");\n            printf(\"Simulation parameters:\\n\");\n            printf(\"  -x\\n\");\n            printf(\"    description:  Number of simulations to run. Each simulation\\n\");\n            printf(\"                  will use a distinct POSIX thread. \\n\");\n            printf(\"    values:       Any unsigned integer.\\n\");\n            printf(\"    default:      1\\n\");\n            printf(\"  -model\\n\");\n            printf(\"    description:  Set the model used.\\n\");\n            printf(\"    values:       0, 1.\\n\");\n            printf(\"    details:      0 = Neutral BDM speciation.\\n\");\n            printf(\"                  1 = BDM speciation with selection.\\n\");\n            printf(\"    default:      1\\n\");\n            printf(\"  -shape\\n\");\n            printf(\"    description:  Set the shape of the metacommunity.\\n\");\n            printf(\"    values:       circle, complete, random, rectangle, star.\\n\");\n            printf(\"    default:      random\\n\");\n            printf(\"  -r\\n\");\n            printf(\"    description:  Threshold radius for random geometric\\n\");\n            printf(\"                  graphs.\\n\");\n            printf(\"    values:       Any double greater than 0.\\n\");\n            printf(\"    default:      0.25\\n\");\n            printf(\"  -w\\n\");\n            printf(\"    description:  The width of a rectangle random geometric\\n\");\n            printf(\"                  graph.\\n\");\n            printf(\"    values:       0 < w < 1\\n\");\n            printf(\"    default:      0.25\\n\");\n            printf(\"  -g\\n\");\n            printf(\"    description:  Number of generations in thousands.\\n\");\n            printf(\"    values:       Any positive integer.\\n\");\n            printf(\"    default:      100 (i.e.: 100 000 generations)\\n\");\n            printf(\"  -c\\n\");\n            printf(\"    description:  Number of local communities.\\n\");\n            printf(\"    values:       Any integer greater than 0.\\n\");\n            printf(\"    default:      10\\n\");\n            printf(\"  -jpc\\n\");\n            printf(\"    description:  Number of individuals per communities.\\n\");\n            printf(\"    values:       Any integer greater than 0.\\n\");\n            printf(\"    default:      10000\\n\");\n            printf(\"  -sp\\n\");\n            printf(\"    description:  Initial number of species. Must be a factor\\n\");\n            printf(\"                  of the number of individuals/community.\\n\");\n            printf(\"    values:       Any positive integer greater than 0.\\n\");\n            printf(\"    default:      20\\n\");\n            printf(\"  -s\\n\");\n            printf(\"    description:  Set the selection coefficient (model 1 only).\\n\");\n            printf(\"    values:       Any double in the (-1.0, 1.0) interval.\\n\");\n            printf(\"    default:      0.15\\n\");\n            printf(\"  -mu\\n\");\n            printf(\"    description:  Set the mutation rate.\\n\");\n            printf(\"    values:       Any positive double.\\n\");\n            printf(\"    default:      1e-4\\n\");\n            printf(\"  -omega\\n\");\n            printf(\"    description:  The weight of the proper edges.\\n\");\n            printf(\"    values:       Any nonnegative double.\\n\");\n            printf(\"    default:      5e-4\\n\");\n            printf(\"  -o\\n\");\n            printf(\"    description:  Name of the output files.\\n\");\n            printf(\"    values:       Any string.\\n\");\n            return EXIT_SUCCESS;\n        }\n        else if (argv[1][2] == 'v') // --version\n        { \n            printf(\"origin v.%s (%s)\\n\", ORIGIN_VERSION, ORIGIN_DATE);\n            printf(\"Copyright (c) 2010-2011 Philippe Desjardins-Proulx <philippe.d.proulx@gmail.com>\\n\");\n            printf(\"GPLv2 license  (see LICENSE)\\n\");\n            return EXIT_SUCCESS;\n        }\n        else if (argv[1][2] == 'r') // --ref\n        { \n            printf(\"P. Desjardins-Proul and D. Gravel. How likely is speciation in\\n  neutral ecology? The American Naturalist 179(1).\\n\");\n            return EXIT_SUCCESS;\n        }\n    } // end '--' options\n\n    // Read options\n    read_opt_i(\"g\", argv, argc, &p.k_gen);\n    read_opt_i(\"jpc\", argv, argc, &p.j_per_c);\n    read_opt_i(\"model\", argv, argc, &p.m);\n    read_opt_i(\"c\", argv, argc, &p.communities);\n    read_opt_i(\"sp\", argv, argc, &p.init_species);\n    read_opt_i(\"x\", argv, argc, &n_threads);\n    read_opt_d(\"mu\", argv, argc, &p.mu);\n    read_opt_d(\"omega\", argv, argc, &p.omega);\n    read_opt_d(\"r\", argv, argc, &p.r);\n    read_opt_d(\"w\", argv, argc, &p.w);\n    read_opt_d(\"s\", argv, argc, &p.s);\n    if (read_opt_s(\"o\", argv, argc, p.ofilename) == false)\n    {\n        sprintf(p.ofilename, \"\");\n    }\n    if (read_opt_s(\"shape\", argv, argc, p.shape) == false)\n    {\n        sprintf(p.shape, \"random\");\n    }\n\n    printf(\"<?xml version=\\\"1.0\\\"?>\\n\");\n    printf(\"<origin_ssne>\\n\");\n    printf(\"  <model>\");\n    if (p.m == MODEL_BDM_NEUTRAL)\n    {\n        printf(\"Neutral BDM speciation</model>\\n\");\n    }\n    else if (p.m == MODEL_BDM_SELECTION)\n    {\n        printf(\"BDM speciation with selection</model>\\n\");\n    }\n    printf(\"  <n>%d</n>\\n\", n_threads);\n    printf(\"  <shape_metacom>%s</shape_metacom>\\n\", p.shape);\n    printf(\"  <metacom_size>%d</metacom_size>\\n\", p.j_per_c * p.communities);\n    printf(\"  <k_gen>%d</k_gen>\\n\", p.k_gen);\n    printf(\"  <num_comm>%d</num_comm>\\n\", p.communities);\n    printf(\"  <individuals_per_comm>%d</individuals_per_comm>\\n\", p.j_per_c);\n    printf(\"  <initial_num_species>%d</initial_num_species>\\n\", p.init_species);\n    printf(\"  <mutation_rate>%.2e</mutation_rate>\\n\", p.mu);\n    printf(\"  <omega>%.2e</omega>\\n\", p.omega);\n    if (p.m == MODEL_BDM_SELECTION)\n    {\n        printf(\"  <selection>%.2e</selection>\\n\", p.s);\n    }\n    if (p.shape[0] == 'r')\n    {\n        printf(\"  <radius>%.4f</radius>\\n\", p.r);\n    }\n    if (p.shape[0] == 'r' && p.shape[1] == 'e')\n    {\n        printf(\"  <width>%.4f</width>\\n\", p.w);\n    }\n    printf(\"  <filename>%s</filename>\\n\", p.ofilename);\n\n    // The threads:\n    pthread_t threads[n_threads];\n\n    const time_t start = time(NULL);\n\n    // Create the threads:\n    for (int i = 0; i < n_threads; ++i)\n    {\n        pthread_create(&threads[i], NULL, sim, (void*)&p);\n    }\n\n    // Wait for the threads to end:\n    for (int i = 0; i < n_threads; ++i)\n    {\n        pthread_join(threads[i], NULL);\n    }\n\n    const time_t end_t = time(NULL);\n    printf(\"  <seconds>%lu</seconds>\\n\", (unsigned long)(end_t - start));\n    printf(\"  <time>%s</time>\\n\", sec_to_string(end_t - start));\n    printf(\"</origin_ssne>\\n\");\n    return EXIT_SUCCESS; // yeppie !\n}\n\n///////////////////////////////////////////\n// The simulation                        //\n///////////////////////////////////////////\nvoid *sim(void *parameters)\n{\n    const Params P = *((Params*)parameters);\n\n    char *shape = P.shape;\n    const int k_gen = P.k_gen;\n    const int communities = P.communities;\n    const int j_per_c = P.j_per_c;\n    const int init_species = P.init_species;\n    const int init_pop_size = j_per_c / init_species;\n    const double omega = P.omega;\n    const double mu = P.mu;\n    const double s = P.s;\n    const double radius = P.r;\n    const double width = P.w;\n\n    // GSL's Taus generator:\n    gsl_rng *rng = gsl_rng_alloc(gsl_rng_taus2);\n    // Initialize the GSL generator with /dev/urandom:\n    const unsigned int seed = devurandom_get_uint();\n    gsl_rng_set(rng, seed); // Seed with time\n    printf(\"  <seed>%u</seed>\\n\", seed);\n    // Used to name the output file:\n    char *buffer = (char*)malloc(100);\n    // Nme of the file:\n    sprintf(buffer, \"%s%u.xml\", P.ofilename, seed);\n    // Open the output file:\n    FILE *restrict out = fopen(buffer, \"w\");\n    // Store the total num. of species/1000 generations:\n    int *restrict total_species = (int*)malloc(k_gen * sizeof(int));\n    // Number of speciation events/1000 generations:\n    int *restrict speciation_events = (int*)malloc(k_gen * sizeof(int));\n    // Number of extinctions/1000 generations:\n    int *restrict extinction_events = (int*)malloc(k_gen * sizeof(int));\n    // Number of speciation events/vertex:\n    int *restrict speciation_per_c = (int*)malloc(communities * sizeof(int));\n    // Number of local extinction events/vertex:\n    int *restrict extinction_per_c = (int*)malloc(communities * sizeof(int));\n    // Store the lifespan of the extinct species:\n    ivector lifespan;\n    ivector_init0(&lifespan);\n    // Store the population size at speciation event:\n    ivector pop_size;\n    ivector_init0(&pop_size);\n    // (x, y) coordinates for the spatial graph:\n    double *restrict x = (double*)malloc(communities * sizeof(double));\n    double *restrict y = (double*)malloc(communities * sizeof(double));\n    for (int i = 0; i < communities; ++i)\n    {\n        speciation_per_c[i] = 0;\n        extinction_per_c[i] = 0;\n    }\n    // Initialize an empty list of species:\n    species_list *restrict list = species_list_init();\n    // Initialize the metacommunity and fill them with the initial species evenly:\n    for (int i = 0; i < init_species; ++i)\n    {\n        // Intialize the species and add it to the list:\n        species_list_add(list, species_init(communities, 0, 3));\n    }\n    // To iterate the list;\n    slnode *it = list->head;\n    // Fill the communities:\n    while (it != NULL)\n    {\n        for (int i = 0; i < communities; ++i)\n        {\n            it->sp->n[i] = init_pop_size;\n            it->sp->genotypes[0][i] = init_pop_size;\n        }\n        it = it->next;\n    }\n\n    // To iterate the list;\n    const int remainder = j_per_c - (init_species * init_pop_size);\n    for (int i = 0; i < communities; ++i)\n    {\n        it = list->head;\n        for (int j = 0; j < remainder; ++j, it = it->next)\n        {\n            ++(it->sp->n[i]);\n            ++(it->sp->genotypes[0][i]);\n        }\n    }\n\n    // Test (will be removed for v2.0):\n    int sum = 0;\n    it = list->head;\n    while (it != NULL)\n    {\n        sum += species_total(it->sp);\n        it = it->next;\n    }\n    assert(sum == j_per_c * communities);\n\n    // Create the metacommunity;\n    graph g;\n    switch(shape[0])\n    {\n    case 's':\n        shape = \"star\";\n        graph_get_star(&g, communities);\n        break;\n    case 'c':\n        if (shape[1] == 'o')\n        {\n            shape = \"complete\";\n            graph_get_complete(&g, communities);\n            break;\n        }\n        else\n        {\n            shape = \"circle\";\n            graph_get_circle(&g, communities);\n            break;\n        }\n    case 'r':\n        if (shape[1] == 'e')\n        {\n            shape = \"rectangle\";\n            graph_get_rec_crgg(&g, communities, width, radius, x, y, rng);\n            break;\n        }\n        else\n        {\n            shape = \"random\";\n            graph_get_crgg(&g, communities, radius, x, y, rng);\n            break;\n        }\n    default:\n        shape = \"random\";\n        graph_get_crgg(&g, communities, radius, x, y, rng);\n    }\n    // Setup the cumulative jagged array for migration:\n    double **cumul = setup_cumulative_list(&g, omega);\n\n    fprintf(out, \"<?xml version=\\\"1.0\\\"?>\\n\");\n    fprintf(out, \"<simulation>\\n\");\n    fprintf(out, \"  <model>\");\n    if (P.m == MODEL_BDM_NEUTRAL)\n    {\n        fprintf(out, \"Neutral BDM speciation</model>\\n\");\n    }\n    else if (P.m == MODEL_BDM_SELECTION)\n    {\n        fprintf(out, \"BDM speciation with selection</model>\\n\");\n    }\n    fprintf(out, \"  <seed>%u</seed>\\n\", seed);\n    fprintf(out, \"  <shape_metacom>%s</shape_metacom>\\n\", shape);\n    fprintf(out, \"  <metacom_size>%d</metacom_size>\\n\", j_per_c * communities);\n    fprintf(out, \"  <k_gen>%d</k_gen>\\n\", k_gen);\n    fprintf(out, \"  <num_comm>%d</num_comm>\\n\", communities);\n    fprintf(out, \"  <individuals_per_comm>%d</individuals_per_comm>\\n\", j_per_c);\n    fprintf(out, \"  <initial_num_species>%d</initial_num_species>\\n\", init_species);\n    fprintf(out, \"  <mutation_rate>%.2e</mutation_rate>\\n\", mu);\n    fprintf(out, \"  <omega>%.2e</omega>\\n\", omega);\n    if (P.m == MODEL_BDM_SELECTION)\n    {\n        fprintf(out, \"  <selection>%.2e</selection>\\n\", s);\n    }\n    if (shape[0] == 'r')\n    {\n        fprintf(out, \"  <radius>%.4f</radius>\\n\", radius);\n    }\n    if (shape[0] == 'r' && shape[1] == 'e')\n    {\n        fprintf(out, \"  <width>%.4f</width>\\n\", width);\n    }\n    // To select the species and genotypes to pick and replace:\n    slnode *s0 = list->head; // species0\n    slnode *s1 = list->head; // species1\n    int g0 = 0;\n    int g1 = 0;\n    int v1 = 0; // Vertex of the individual 1\n\n    /////////////////////////////////////////////\n    // Groups of 1 000 generations             //\n    /////////////////////////////////////////////\n    for (int k = 0; k < k_gen; ++k)\n    {\n        extinction_events[k] = 0;\n        speciation_events[k] = 0;\n\n        /////////////////////////////////////////////\n        // 1 000 generations                       //\n        /////////////////////////////////////////////\n        for (int gen = 0; gen < 1000; ++gen)\n        {\n            const int current_date = (k * 1000) + gen;\n            /////////////////////////////////////////////\n            // A single generation                     //\n            /////////////////////////////////////////////\n            for (int t = 0; t < j_per_c; ++t)\n            {\n                /////////////////////////////////////////////\n                // A single time step (for each community) //\n                /////////////////////////////////////////////\n                for (int c = 0; c < communities; ++c)\n                {\n                    // Select the species and genotype of the individual to be replaced\n                    int position = (int)(gsl_rng_uniform(rng) * j_per_c);\n                    s0 = list->head;\n                    int index = s0->sp->n[c];\n                    while (index <= position)\n                    {\n                        s0 = s0->next;\n                        index += s0->sp->n[c];\n                    }\n                    position = (int)(gsl_rng_uniform(rng) * s0->sp->n[c]);\n                    if (position < s0->sp->genotypes[0][c])\n                    {\n                        g0 = 0;\n                    }\n                    else if (position < (s0->sp->genotypes[0][c] + s0->sp->genotypes[1][c]))\n                    {\n                        g0 = 1;\n                    }\n                    else\n                    {\n                        g0 = 2;\n                    }\n                    // Choose the vertex for the individual\n                    const double r_v1 = gsl_rng_uniform(rng);\n                    v1 = 0;\n                    while (r_v1 > cumul[c][v1])\n                    {\n                        ++v1;\n                    }\n                    v1 = g.adj_list[c][v1];\n                    // species of the new individual\n                    position = (int)(gsl_rng_uniform(rng) * j_per_c);\n                    s1 = list->head;\n                    index = s1->sp->n[v1];\n                    while (index <= position)\n                    {\n                        s1 = s1->next;\n                        index += s1->sp->n[v1];\n                    }\n                    if (v1 == c) // local remplacement\n                    {\n                        const double r = gsl_rng_uniform(rng);\n                        const int aa = s1->sp->genotypes[0][v1];\n                        const int Ab = s1->sp->genotypes[1][v1];\n                        const int AB = s1->sp->genotypes[2][v1];\n\n                        // The total fitness of the population 'W':\n                        const double w = aa + Ab * (1.0 + s) + AB * (1.0 + s) * (1.0 + s);\n\n                        if (r < aa / w)\n                        {\n                            g1 = gsl_rng_uniform(rng) < mu ? 1 : 0;\n                        }\n                        else\n                        {\n                            if (AB == 0 || r < (aa + Ab * (1.0 + s)) / w)\n                            {\n                                g1 = gsl_rng_uniform(rng) < mu ? 2 : 1;\n                            }\n                            else\n                            {\n                                g1 = 2;\n                            }\n                        }\n                    }\n                    else\n                    { // Migration event\n                        g1 = 0;\n                    }\n                    // Apply the changes\n                    s0->sp->n[c]--;\n                    s0->sp->genotypes[g0][c]--;\n                    s1->sp->n[c]++;\n                    s1->sp->genotypes[g1][c]++;\n\n                    ////////////////////////////////////////////\n                    // Check for local extinction             //\n                    ////////////////////////////////////////////\n                    if (s0->sp->n[c] == 0)\n                    {\n                        extinction_per_c[c]++;\n                    }\n                    ////////////////////////////////////////////\n                    // Check for speciation                   //\n                    ////////////////////////////////////////////\n                    else if (s0->sp->genotypes[2][c] > 0 && s0->sp->genotypes[0][c] == 0 && s0->sp->genotypes[1][c] == 0)\n                    {\n                        species_list_add(list, species_init(communities, current_date, 3)); // Add the new species\n\n                        const int pop = s0->sp->n[c];\n                        list->tail->sp->n[c] = pop;\n                        list->tail->sp->genotypes[0][c] = pop;\n                        s0->sp->n[c] = 0;\n                        s0->sp->genotypes[2][c] = 0;\n\n                        // To keep info on patterns of speciation...\n                        ivector_add(&pop_size, pop);\n                        ++speciation_events[k];\n                        ++speciation_per_c[c];\n                    }\n\n                } // End 'c'\n\n            } // End 't'\n\n            // Remove extinct species from the list and store the number of extinctions.\n            extinction_events[k] += species_list_rmv_extinct2(list, &lifespan, current_date);\n\n        } // End 'g'\n\n        total_species[k] = list->size;\n\n    } // End 'k'\n\n    //////////////////////////////////////////////////\n    // PRINT THE FINAL RESULTS                      //\n    //////////////////////////////////////////////////\n    fprintf(out, \"  <global>\\n\");\n    fprintf(out, \"    <proper_edges>%d</proper_edges>\\n\", graph_edges(&g));\n    fprintf(out, \"    <links_per_c>%.4f</links_per_c>\\n\", (double)graph_edges(&g) / communities);\n\n    fprintf(out, \"    <avr_lifespan>%.4f</avr_lifespan>\\n\", imean(lifespan.array, lifespan.size));\n    fprintf(out, \"    <median_lifespan>%.4f</median_lifespan>\\n\", imedian(lifespan.array, lifespan.size));\n\n    fprintf(out, \"    <avr_pop_size_speciation>%.4f</avr_pop_size_speciation>\\n\", imean(pop_size.array, pop_size.size));\n    fprintf(out, \"    <median_pop_size_speciation>%.4f</median_pop_size_speciation>\\n\", imedian(pop_size.array, pop_size.size));\n\n    fprintf(out, \"    <speciation_per_k_gen>\");\n    int i = 0;\n    for (; i < k_gen - 1; ++i)\n    {\n        fprintf(out, \"%d \", speciation_events[i]);\n    }\n    fprintf(out, \"%d</speciation_per_k_gen>\\n\", speciation_events[i]);\n\n    fprintf(out, \"    <extinctions_per_k_gen>\");\n    for (i = 0; i < k_gen - 1; ++i)\n    {\n        fprintf(out, \"%d \", extinction_events[i]);\n    }\n    fprintf(out, \"%d</extinctions_per_k_gen>\\n\", extinction_events[i]);\n\n    fprintf(out, \"    <extant_species_per_k_gen>\");\n    for (i = 0; i < k_gen - 1; ++i)\n    {\n        fprintf(out, \"%d \", total_species[i]);\n    }\n    fprintf(out, \"%d</extant_species_per_k_gen>\\n\", total_species[i]);\n\n    // Print global distribution\n    fprintf(out, \"    <species_distribution>\");\n    ivector species_distribution;\n    ivector_init1(&species_distribution, 128);\n    it = list->head;\n    while (it != NULL)\n    {\n        ivector_add(&species_distribution, species_total(it->sp));\n        it = it->next;\n    }\n    ivector_sort_asc(&species_distribution);\n    ivector_print(&species_distribution, out);\n    fprintf(out, \"</species_distribution>\\n\");\n\n    double *octaves;\n    int oct_num = biodiversity_octaves(species_distribution.array, species_distribution.size, &octaves);\n    fprintf(out, \"    <octaves>\");\n    for (i = 0; i < oct_num; ++i)\n    {\n        fprintf(out, \"%.2f \", octaves[i]);\n    }\n    fprintf(out, \"%.2f</octaves>\\n\", octaves[i]);\n    fprintf(out, \"  </global>\\n\");\n\n    // Print info on all vertices\n    double *restrict ric_per_c = (double*)malloc(communities * sizeof(double));\n    for (int c = 0; c < communities; ++c)\n    {\n        fprintf(out, \"  <vertex>\\n\");\n        fprintf(out, \"    <id>%d</id>\\n\", c);\n        if (shape[0] == 'r')\n        {\n            fprintf(out, \"    <xcoor>%.4f</xcoor>\\n\", x[c]);\n            fprintf(out, \"    <ycoor>%.4f</ycoor>\\n\", y[c]);\n        }\n        fprintf(out, \"    <degree>%d</degree>\\n\", g.num_e[c] + 1);\n        fprintf(out, \"    <speciation_events>%d</speciation_events>\\n\", speciation_per_c[c]);\n        fprintf(out, \"    <extinction_events>%d</extinction_events>\\n\", extinction_per_c[c]);\n\n        int vertex_richess = 0;\n        ivector_rmvall(&species_distribution);\n        it = list->head;\n        while (it != NULL)\n        {\n            ivector_add(&species_distribution, it->sp->n[c]);\n            it = it->next;\n        }\n        // Sort the species distribution and remove the 0s\n        ivector_sort_asc(&species_distribution);\n        ivector_trim_small(&species_distribution, 1);\n\n        ric_per_c[c] = (double)species_distribution.size;\n        fprintf(out, \"    <species_richess>%d</species_richess>\\n\", species_distribution.size);\n        fprintf(out, \"    <species_distribution>\");\n        ivector_print(&species_distribution, out);\n        fprintf(out, \"</species_distribution>\\n\");\n\n        // Print octaves\n        free(octaves);\n        oct_num = biodiversity_octaves(species_distribution.array, species_distribution.size, &octaves);\n        fprintf(out, \"    <octaves>\");\n        for (i = 0; i < oct_num - 1; ++i)\n        {\n            fprintf(out, \"%.2f \", octaves[i]);\n        }\n        fprintf(out, \"%.2f</octaves>\\n\", octaves[i]);\n        fprintf(out, \"  </vertex>\\n\");\n    }\n\n    fprintf(out, \"</simulation>\\n\");\n\n    // GraphML output:\n    sprintf(buffer, \"%s%u.graphml\", P.ofilename, seed);\n    FILE *outgml = fopen(buffer, \"w\");\n    graph_graphml(&g, outgml, seed);\n    \n    // Print to SVG files.\n    sprintf(buffer, \"%s%u.svg\", P.ofilename, seed);\n    FILE *outsvg = fopen(buffer, \"w\");\n    graph_svg(&g, x, y, 400.0, 20.0, outsvg);\n    \n    sprintf(buffer, \"%s%u-speciation.svg\", P.ofilename, seed);\n    FILE *outsvgspe = fopen(buffer, \"w\");\n    double *spe_per_c = (double*)malloc(communities * sizeof(double));\n    for (int c = 0; c < communities; ++c)\n    {\n        spe_per_c[c] = (double)speciation_per_c[c];\n    }\n    scale_0_1(spe_per_c, communities);\n    graph_svg_abun(&g, x, y, 400.0, 20.0, spe_per_c, 2, outsvgspe);\n    \n    sprintf(buffer, \"%s%u-richness.svg\", P.ofilename, seed);\n    FILE *outsvgric = fopen(buffer, \"w\");\n    scale_0_1(ric_per_c, communities);\n    graph_svg_abun(&g, x, y, 400.0, 20.0, ric_per_c, 1, outsvgric);\n\n    //////////////////////////////////////////////////\n    // EPILOGUE...                                  //\n    //////////////////////////////////////////////////\n    // Close files;\n    fclose(out);\n    fclose(outgml);\n    fclose(outsvg);\n    fclose(outsvgspe);\n    fclose(outsvgric);\n    // Free arrays;\n    free(x);\n    free(y);\n    free(ric_per_c);\n    free(spe_per_c);\n    free(buffer);\n    free(total_species);\n    free(octaves);\n    free(speciation_per_c);\n    free(extinction_per_c);\n    free(speciation_events);\n    free(extinction_events);\n    // Free structs;\n    species_list_free(list);\n    ivector_free(&species_distribution);\n    ivector_free(&lifespan);\n    ivector_free(&pop_size);\n    graph_free(&g);\n    gsl_rng_free(rng);\n\n    return NULL;\n}\n\ndouble **setup_cumulative_list(const graph *g, double omega)\n{\n    const int num_v = g->num_v;\n    double **cumul = (double**)malloc(num_v * sizeof(double*));\n    for (int i = 0; i < num_v; ++i) \n    {\n        cumul[i] = (double*)malloc(g->num_e[i] * sizeof(double));\n    }\n    for (int i = 0; i < num_v; ++i)\n    {\n        for (int j = 0; j < g->num_e[i]; ++j)\n        {\n            cumul[i][j] = g->w_list[i][j];\n        }\n    }\n    for (int i = 0; i < num_v; ++i)\n    {\n        for (int j = 0; j < g->num_e[i]; ++j)\n        {\n            if (i != g->adj_list[i][j])\n            {\n                cumul[i][j] = omega;\n            }\n            else\n            {\n                cumul[i][j] = 1.0;\n            }\n        }\n    }\n    for (int i = 0; i < num_v; ++i)\n    {\n        double sum = 0.0;\n        const int num_e = g->num_e[i];\n        for (int j = 0; j < num_e; ++j)\n        {\n            sum += cumul[i][j];\n        }\n        for (int j = 0; j < num_e; ++j)\n        {\n            cumul[i][j] /= sum;\n        }\n    }\n    for (int i = 0; i < num_v; ++i)\n    {\n        const int num_e = g->num_e[i];\n        for (int j = 1; j < num_e - 1; ++j)\n        {\n            cumul[i][j] += cumul[i][j - 1];\n        }\n        cumul[i][num_e - 1] = 1.0;\n    }\n    /*\n    graph_print(g, stdout);\n    for (int i = 0; i < num_v; ++i)\n    {\n        const int num_e = g->num_e[i];\n        for (int j = 0; j < num_e; ++j)\n        {\n            printf(\"%.4f   \", cumul[i][j]);\n        }\n        printf(\"\\n\");\n    }\n    */\n    return cumul;\n}\n", "meta": {"hexsha": "a172244958e240675fddc28f1c062fabcf327eec", "size": 27926, "ext": "c", "lang": "C", "max_stars_repo_path": "src/main.c", "max_stars_repo_name": "PhDP/Origin", "max_stars_repo_head_hexsha": "79d02f0d850a9b078e58d5f5af6ff1d2143cf712", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/main.c", "max_issues_repo_name": "PhDP/Origin", "max_issues_repo_head_hexsha": "79d02f0d850a9b078e58d5f5af6ff1d2143cf712", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main.c", "max_forks_repo_name": "PhDP/Origin", "max_forks_repo_head_hexsha": "79d02f0d850a9b078e58d5f5af6ff1d2143cf712", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.9871134021, "max_line_length": 139, "alphanum_fraction": 0.4811286973, "num_tokens": 7243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014736319616964, "lm_q2_score": 0.03567855113407215, "lm_q1q2_score": 0.015347034692980844}}
{"text": "/* \ngsl-sprng.h\n\nCode declaring a new GSL random number type \"gsl_rng_sprng20\"\nwhich is a thin wrapper over the SPRNG 2.0 parallel random\nnumber generator.\n\nTo use, just add the line:\n#include \"gsl-sprng.h\"\nimmediately after the line:\n#include <gsl/gsl_rng.h>\nnear the start of your code. The new type should now be available.\nMake sure you alloc the rng on each processor. If you wish to\nset a seed, you should set it to be the same on each processor.\n\nDarren Wilkinson\nd.j.wilkinson@ncl.ac.uk\nhttp://www.staff.ncl.ac.uk/d.j.wilkinson/\n\nLast updated: 28/8/2002\n\n*/\n\n\n#define SIMPLE_SPRNG\n#define USE_MPI\n#include \"sprng.h\"\n\nstatic void sprng_set(void * vstate,unsigned long int s)\n{\n  init_sprng(DEFAULT_RNG_TYPE,s,SPRNG_DEFAULT);\n}\n\nstatic unsigned long sprng_get(void * vstate)\n{\n  return( (long) isprng() );\n}\n\nstatic double sprng_get_double(void * vstate)\n{\n  return( (double) sprng());\n}\n\nstatic const gsl_rng_type sprng_type =\n  {\"sprng20\",        /* name */\n   0x7fffffffUL,     /* RAND_MAX */\n   0,                /* RAND_MIN */\n   0,                /* size of state - not sure about this */\n   &sprng_set,          /* initialisation */\n   &sprng_get,          /* get integer RN */\n   &sprng_get_double};  /* get double RN */\n\nconst gsl_rng_type *gsl_rng_sprng20 = &sprng_type;\n\n/* eof */\n", "meta": {"hexsha": "b0a3cb1303407788e485a36bdee65e2f2dceffab", "size": 1298, "ext": "h", "lang": "C", "max_stars_repo_path": "Externals/PolyChord/gsl-sprng.h", "max_stars_repo_name": "yuanfangtardis/vscode_project", "max_stars_repo_head_hexsha": "2d78a85413cc85789cc4fee8ec991eb2a0563ef8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Externals/PolyChord/gsl-sprng.h", "max_issues_repo_name": "yuanfangtardis/vscode_project", "max_issues_repo_head_hexsha": "2d78a85413cc85789cc4fee8ec991eb2a0563ef8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Externals/PolyChord/gsl-sprng.h", "max_forks_repo_name": "yuanfangtardis/vscode_project", "max_forks_repo_head_hexsha": "2d78a85413cc85789cc4fee8ec991eb2a0563ef8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-15T12:22:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-15T12:22:30.000Z", "avg_line_length": 23.1785714286, "max_line_length": 66, "alphanum_fraction": 0.6787365177, "num_tokens": 370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34864512179822543, "lm_q2_score": 0.04401864939265446, "lm_q1q2_score": 0.015346887378895396}}
{"text": "#pragma once\n\n#include <chrono>\n#include <fmt/printf.h>\n#include <gsl/gsl-lite.hpp>\n\nnamespace angonoka::cli {\n/**\n    Pretty-print values.\n\n    This class is mostly used for specializing user-defined\n    formatters for the fmt library. We don't want to specialize\n    the formatter for the original type because we might not\n    always want a human-readable output.\n\n    Instead of specializing fmt::formatter<std::chrono::seconds>\n    we specialize fmt::formatter<humanize<std::chrono::seconds>>\n    thus not interfering with the original formatter.\n\n    @var value Value to be pretty-printed\n*/\ntemplate <typename T> struct humanize {\n    T value;\n};\ntemplate <typename T> humanize(T) -> humanize<T>;\n\nnamespace detail {\n    /**\n        Enum that tells if a human-readable duration\n        printing should continue parsing durations of a\n        smaller scale or stop.\n    */\n    enum DurationParsing : bool { continue_, stop };\n\n    /**\n        Helper function to print durations in human-readable form.\n\n        @param article  \"a\" or \"an\"\n        @param name     Duration (seconds, minutes, etc)\n\n        @return Formatter function\n    */\n    template <typename T>\n    constexpr auto\n    humanize_duration(gsl::czstring article, gsl::czstring name)\n    {\n        return [=](auto total, auto& ctx) {\n            const auto dur = std::chrono::round<T>(total);\n            if (dur == dur.zero()) return DurationParsing::continue_;\n            const auto ticks = dur.count();\n            if (ticks == 1) {\n                fmt::format_to(\n                    ctx.out(),\n                    \"about {} {}\",\n                    article,\n                    name);\n            } else {\n                fmt::format_to(ctx.out(), \"{} {}s\", ticks, name);\n            }\n            return DurationParsing::stop;\n        };\n    }\n} // namespace detail\n} // namespace angonoka::cli\n\nnamespace fmt {\nusing angonoka::cli::humanize;\n/**\n    User-defined formatter for std::chrono durations.\n*/\ntemplate <typename... Ts>\nstruct fmt::formatter<humanize<std::chrono::duration<Ts...>>> {\n    using value_type = humanize<std::chrono::duration<Ts...>>;\n    static constexpr auto parse(format_parse_context& ctx)\n    {\n        return ctx.end();\n    }\n\n    template <typename FormatContext>\n    constexpr auto format(const value_type& obj, FormatContext& ctx)\n    {\n        using angonoka::cli::detail::humanize_duration;\n        using namespace std::literals::chrono_literals;\n        using namespace std::chrono;\n        constexpr auto min_threshold = 5s;\n        if (obj.value <= min_threshold)\n            return format_to(ctx.out(), \"a few seconds\");\n        [&](auto&&... fns) {\n            (fns(obj.value, ctx) || ...);\n        }(humanize_duration<months>(\"a\", \"month\"),\n          humanize_duration<days>(\"a\", \"day\"),\n          humanize_duration<hours>(\"an\", \"hour\"),\n          humanize_duration<minutes>(\"a\", \"minute\"),\n          humanize_duration<seconds>(\"a\", \"second\"));\n        return ctx.out();\n    }\n};\n} // namespace fmt\n", "meta": {"hexsha": "efdc92ef127343c1c6ac6a68037ae3de297fa815", "size": 3016, "ext": "h", "lang": "C", "max_stars_repo_path": "src/cli/humanize.h", "max_stars_repo_name": "coffee-lord/angonoka", "max_stars_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-10-23T18:05:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T21:53:24.000Z", "max_issues_repo_path": "src/cli/humanize.h", "max_issues_repo_name": "coffee-lord/angonoka", "max_issues_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2022-02-12T19:52:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-12T19:55:52.000Z", "max_forks_repo_path": "src/cli/humanize.h", "max_forks_repo_name": "coffee-lord/angonoka", "max_forks_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4646464646, "max_line_length": 69, "alphanum_fraction": 0.599801061, "num_tokens": 669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39233684437737093, "lm_q2_score": 0.03904829524237479, "lm_q1q2_score": 0.015320084933709233}}
{"text": "#ifndef _BLAS_UTIL_H_\n#define _BLAS_UTIL_H_\n\n\n#ifdef __BLAS_LEGACY__\n#include <math.h>\n#include \"utils/cblas.h\"\n//#include <lapacke.h> //! hasn't used\n#define _D2_MALLOC_SCALAR(x)       (SCALAR *) malloc( (x) *sizeof(SCALAR)) \n#define _D2_MALLOC_INT(x)       (int *) malloc( (x) *sizeof(int))\n#define _D2_MALLOC_SIZE_T(x)       (size_t *) malloc( (x) *sizeof(size_t))\n#define _D2_CALLOC_SCALAR(x)       (SCALAR *) calloc( (x) , sizeof(SCALAR)) \n#define _D2_CALLOC_INT(x)       (int *) calloc( (x) , sizeof(int))\n#define _D2_CALLOC_SIZE_T(x)       (size_t *) calloc( (x) , sizeof(size_t))\n#define _D2_FREE(x)         free(x)\n\n#elif defined __APPLE__\n#include <Accelerate/Accelerate.h>\n#define _D2_MALLOC_SCALAR(x)       (SCALAR *) malloc( (x) *sizeof(SCALAR)) \n#define _D2_MALLOC_INT(x)       (int *) malloc( (x) *sizeof(int))\n#define _D2_MALLOC_SIZE_T(x)       (size_t *) malloc( (x) *sizeof(size_t))\n#define _D2_CALLOC_SCALAR(x)       (SCALAR *) calloc( (x) , sizeof(SCALAR)) \n#define _D2_CALLOC_INT(x)       (int *) calloc( (x) , sizeof(int))\n#define _D2_CALLOC_SIZE_T(x)       (size_t *) calloc( (x) , sizeof(size_t))\n#define _D2_FREE(x)         free(x)\n\n#elif defined __USE_MKL__\n#include <mkl.h>\n#define _D2_MALLOC_SCALAR(x)       (SCALAR *) mkl_malloc( (x) *sizeof(SCALAR), 16) \n#define _D2_MALLOC_INT(x)       (int *) mkl_malloc( (x) *sizeof(int), 16)\n#define _D2_MALLOC_SIZE_T(x)       (size_t *) mkl_malloc( (x) *sizeof(size_t), 16)\n#define _D2_CALLOC_SCALAR(x)       (SCALAR *) mkl_calloc( (x) , sizeof(SCALAR), 16) \n#define _D2_CALLOC_INT(x)       (int *) mkl_calloc( (x) , sizeof(int), 16)\n#define _D2_CALLOC_SIZE_T(x)       (size_t *) mkl_calloc( (x) , sizeof(size_t), 16)\n#define _D2_FREE(x)         mkl_free(x)\n\n#endif\n\n\n#endif /* _BLAS_UTIL_H_ */\n", "meta": {"hexsha": "8be083fb3818a73af31fd807df0dc6f8dbb45fbb", "size": 1763, "ext": "h", "lang": "C", "max_stars_repo_path": "include/utils/blas_util.h", "max_stars_repo_name": "bobye/d2_kmeans", "max_stars_repo_head_hexsha": "7290657e1f6f95e633653172500a2b54d13e02be", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-11-20T18:10:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-09T12:53:19.000Z", "max_issues_repo_path": "include/utils/blas_util.h", "max_issues_repo_name": "bobye/d2_kmeans", "max_issues_repo_head_hexsha": "7290657e1f6f95e633653172500a2b54d13e02be", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/utils/blas_util.h", "max_forks_repo_name": "bobye/d2_kmeans", "max_forks_repo_head_hexsha": "7290657e1f6f95e633653172500a2b54d13e02be", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-01-11T16:55:13.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-13T20:23:40.000Z", "avg_line_length": 43.0, "max_line_length": 84, "alphanum_fraction": 0.6488939308, "num_tokens": 583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3738758227716966, "lm_q2_score": 0.040845716931578166, "lm_q1q2_score": 0.015271226024493606}}
{"text": "// Copyright 2011-2021 GameParadiso, Inc. All Rights Reserved.\n\n#pragma once\n\n#include <map>\n#include <unordered_map>\n#include <ranges>\n\n#include <glm/vec3.hpp>\n#include <glm/vec4.hpp>\n#include <glm/mat4x4.hpp>\n#include <glm/gtc/quaternion.hpp>\n#include <glm/ext/matrix_transform.hpp>\n#include <glm/ext/matrix_clip_space.hpp>\n#include <glm/ext/scalar_constants.hpp>\n\n#include <gsl/gsl>\n\nusing namespace std::string_literals;\n", "meta": {"hexsha": "704bd572205d273c6ffd942c467acd9b46fa4a86", "size": 425, "ext": "h", "lang": "C", "max_stars_repo_path": "pch.h", "max_stars_repo_name": "noirhero/MemoryChunk", "max_stars_repo_head_hexsha": "81d620e95fa677bde0dcc5f8e562500157402aa1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pch.h", "max_issues_repo_name": "noirhero/MemoryChunk", "max_issues_repo_head_hexsha": "81d620e95fa677bde0dcc5f8e562500157402aa1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pch.h", "max_forks_repo_name": "noirhero/MemoryChunk", "max_forks_repo_head_hexsha": "81d620e95fa677bde0dcc5f8e562500157402aa1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.25, "max_line_length": 62, "alphanum_fraction": 0.76, "num_tokens": 111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.0396388352720228, "lm_q1q2_score": 0.01525746908939968}}
{"text": "//! @file\n//! Various functions used during experiences (dgemmsy)\n//!\n//! @author\n//!    Copyright (C) 2009-2011 BigDFT group \n//!    This file is distributed under the terms of the\n//!    GNU General Public License, see ~/COPYING file\n//!    or http://www.gnu.org/copyleft/gpl.txt .\n//!    For the list of contributors, see ~/AUTHORS \n//! Eric Bainville, Mar 2010\n\n\n#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <malloc.h>\n#include <math.h>\n#include <unistd.h>\n#include <xmmintrin.h>\n\n// Set to 1 to use BLAS axpy call to accumulate partial results.\n#ifndef USE_AXPY\n#define USE_AXPY 1\n/*#define ACML_BLAS 1*/\n#endif\n\n#if USE_AXPY\n#if defined(MKL_BLAS) || defined(WIN32)\n#include <mkl_cblas.h>\n#else\n#if defined(ACML_BLAS)\n#include <acml.h>\n#define cblas_daxpy daxpy\n#else\n#include <cblas.h>\n#endif\n#endif\n#endif\n\n#include \"utils.h\"\n\n// System-specific functions\n\n#include <unistd.h>\nvoid * allocPages(size_t sz)\n{\n  size_t page_size = sysconf(_SC_PAGESIZE);\n  size_t extra = sz % page_size;\n  if (extra != 0) sz = (sz - extra) + page_size; // round to next page\n  void * address = 0;\n  int status = posix_memalign(&address,page_size,sz);\n  if (status != 0) return 0; // Failed\n  return address;\n}\nvoid freePages(void * address)\n{\n  free(address);\n}\ndouble * allocDoubles(int n)\n{\n  void * address = 0;\n  int status = posix_memalign(&address,16,n*sizeof(double));\n  if (status != 0) return 0; // Failed\n  return address;\n}\nfloat * allocFloats(int n)\n{\n  void * address = 0;\n  int status = posix_memalign(&address,16,n*sizeof(float));\n  if (status != 0) return 0; // Failed\n  return address;\n}\nvoid freeDoubles(double * x)\n{\n  free(x);\n}\nvoid freeFloats(float * x)\n{\n  free(x);\n}\n\n// Reference implementations\n\nvoid gemm_block_2x2_ref(const double * a,const double * b,long long int n,double * y,long long int ldy)\n{\n  int k;\n  for (k=0;k<n;k+=2)\n  {\n    y[0] += a[2*k] * b[4*k];\n    y[0] += a[2*k+1] * b[4*k+1];\n    y[1] += a[2*k] * b[4*k+2];\n    y[1] += a[2*k+1] * b[4*k+3];\n    y[ldy] += a[2*k+2] * b[4*k];\n    y[ldy] += a[2*k+3] * b[4*k+1];\n    y[ldy+1] += a[2*k+2] * b[4*k+2];\n    y[ldy+1] += a[2*k+3] * b[4*k+3];\n  }\n}\n\nvoid gemm_block_2x4_ref(const double * a,const double * b,long long int n,double * y,long long int ldy)\n{\n  int k;\n  double * work;\n  for (k=0;k<n;k+=2)\n  {\n    work = y;\n    work[0] += a[2*k]   * b[4*k];\n    work[0] += a[2*k+1] * b[4*k+1];\n    work += ldy;\n    work[0] += a[2*k]   * b[4*k+2];\n    work[0] += a[2*k+1] * b[4*k+3];\n    work += ldy;\n    work[0] += a[2*k]   * b[4*k+4];\n    work[0] += a[2*k+1] * b[4*k+5];\n    work += ldy;\n    work[0] += a[2*k]   * b[4*k+6];\n    work[0] += a[2*k+1] * b[4*k+7];\n\n    work = y + 1;\n    work[0] += a[2*k+2] * b[4*k];\n    work[0] += a[2*k+3] * b[4*k+1];\n    work += ldy;\n    work[0] += a[2*k+2] * b[4*k+2];\n    work[0] += a[2*k+3] * b[4*k+3];\n    work += ldy;\n    work[0] += a[2*k+2] * b[4*k+4];\n    work[0] += a[2*k+3] * b[4*k+5];\n    work += ldy;\n    work[0] += a[2*k+2] * b[4*k+6];\n    work[0] += a[2*k+3] * b[4*k+7];\n  }\n}\n\nint dgemmsy_base(dgemmsyBaseArgs * args)\n{\n  int status = 0; // return value\n  int row,col;\n  size_t slice_size,ywork_size;\n  int p2; // P rounded to next multiple of 4\n  double *a_slice,*b_slice,*y_work;\n  ComputeData cdata;\n  TransposeData tdata;\n  int slice_n,n,p;\n  const double *a,*b;\n  double *y;\n  int lda,ldb,ldy;\n  int transa,transb;\n  BlockPattern_2x4_Proc pattern;\n  void * pattern_arg;\n  double alpha;\n\n  if (args == 0) return -2;\n\n  pattern = args->params.pattern;\n  pattern_arg = args->params.pattern_arg;\n  slice_n = args->params.slice_n;\n\n  transa = args->transa;\n  transb = args->transb;\n  n = args->n;\n  p = args->p;\n  a = args->a;\n  lda = args->lda;\n  b = args->b;\n  ldb = args->ldb;\n  y = args->y;\n  ldy = args->ldy;\n  alpha = args->alpha;\n\n  // Check dimensions\n  if (slice_n < 8) return -1;\n  if ( n <= 0 || p <= 0 ) return -1;\n  p2 = (p+3) & 0x7FFFFFFC;\n\n  // printf(\"N=%d P=%d LDA=%d LDB=%d LDY=%d  P2=%d\\n\",n,p,lda,ldb,ldy,p2);\n\n  // Check other arguments\n  if (a == 0 || b == 0 || y == 0 || pattern == 0) return -5;\n\n  // Allocate memory\n  slice_size = slice_n * p2 * sizeof(double); // Slice size in bytes\n  ywork_size = p2 * p2 * sizeof(double); // Result size in bytes\n  a_slice = (double *)allocPages(slice_size);\n  b_slice = (double *)allocPages(slice_size);\n  y_work = (double *)allocPages(ywork_size);\n  if (a_slice == 0 || b_slice == 0 || y_work == 0) { status = -3; goto END; }\n  memset(y_work,0,ywork_size);\n\n  // Loop on all slices and accumulate products\n  initComputeData(&cdata,p2,slice_n,a_slice,b_slice,y_work);\n  for (row=0;row<n;row+=slice_n)\n  {\n    int s = slice_n;\n    if (row+s > n) s = n-row; // Limit size of last slice if needed\n\n    // 2-pack A slice\n    if (transa) tpack_2(s,p,a+lda*row,lda, slice_n,p2,a_slice);\n    else npack_2(s,p,a+row,lda, slice_n,p2,a_slice);\n\n    // 4-pack B slice\n    if (transb) tpack_4(s,p,b+ldb*row,ldb, slice_n,p2,b_slice);\n    else npack_4(s,p,b+row,ldb, slice_n,p2,b_slice);\n\n    pattern(pattern_arg,p2,Compute_visitor,&cdata);\n  }\n  cleanupComputeData(&cdata);\n\n  // Complete result by symmetry\n  initTransposeData(&tdata,p2,y_work);\n  pattern(pattern_arg,p2,Transpose_visitor,&tdata);\n  cleanupTransposeData(&tdata);\n\n  // Combine and store (untransposed) result. If we are multithreading,\n  // we must protect the update with a mutex, since all threads\n  // will update the same Y.\n  if (args->yMutex != 0)\n    {\n      int locked = pthread_mutex_lock(args->yMutex);\n      if (locked != 0) status = -4;\n    }\n  for (col=0;col<p;col++)\n    {\n      double * yy = y+ldy*col;\n      double * yy_work = y_work+p2*col;\n#if USE_AXPY\n      cblas_daxpy(p,alpha,yy_work,1,yy,1);\n#else\n      if (alpha == 1)\n\t{\n\t  for (row=0;row<p;row++) yy[row] += yy_work[row];\n\t}\n      else\n\t{\n\t  for (row=0;row<p;row++) yy[row] += alpha * yy_work[row];\n\t}\n#endif\n    }\n  if (args->yMutex != 0)\n    {\n      int unlocked = pthread_mutex_unlock(args->yMutex);\n      if (unlocked != 0) status = -4;\n    }\n\nEND:\n  // Cleanup\n  freePages(y_work);\n  freePages(a_slice);\n  freePages(b_slice);\n  return status;\n}\n\nvoid npack_2(int n,int p,const double * a,int lda,int s,int q,double * slice)\n{\n  int row,col,icol;\n  double * x = 0;\n  int oddn = 0;\n  if (n&1) { n--; oddn=1; }\n  for (col=0;col<q;col++)\n    {\n      icol = col&1;\n      x = slice + s*(col-icol) + (icol<<1);\n      row = 0;\n      if (col < p)\n\t{\n\t  for ( ;row<n;row+=2)\n\t    {\n\t      x[2*row] = a[row];\n\t      x[2*row+1] = a[row+1];\n\t    }\n\t  if (oddn) { x[2*row] = a[row]; x[2*row+1] = 0; row+=2; }\n\t}\n      for ( ;row<s;row+=2)\n\t{\n\t  x[2*row] = 0;\n\t  x[2*row+1] = 0;\n\t}\n      a += lda;\n    }\n}\n\nvoid npack_4(int n,int p,const double * a,int lda,int s,int q,double * slice)\n{\n  int row,col,icol;\n  double * x = 0;\n  int oddn = 0;\n  if (n&1) { n--; oddn=1; }\n  for (col=0;col<q;col++)\n    {\n      icol = col&3;\n      x = slice + s*(col-icol) + (icol<<1);\n      row = 0;\n      if (col < p)\n\t{\n\t  for ( ;row<n;row+=2)\n\t    {\n\t      x[4*row] = a[row];\n\t      x[4*row+1] = a[row+1];\n\t    }\n\t  if (oddn) { x[4*row] = a[row]; x[4*row+1] = 0; row+=2; }\n\t}\n      for ( ;row<s;row+=2)\n\t{\n\t  x[4*row] = 0;\n\t  x[4*row+1] = 0;\n\t}\n      a += lda;\n    }\n}\n\nvoid tpack_2(int n,int p,const double * a,int lda,int s,int q,double * slice)\n{\n  int row,col,icol;\n  double * x = 0;\n  const double * aa;\n  int da = lda<<1;\n  int oddn = 0;\n  if (n&1) { n--; oddn=1; }\n  for (col=0;col<q;col++)\n    {\n      icol = col&1;\n      x = slice + s*(col-icol) + (icol<<1);\n      row = 0;\n      if (col < p)\n\t{\n\t  aa = a;\n\t  for ( ;row<n;row+=2)\n\t    {\n\t      x[2*row] = aa[0];\n\t      x[2*row+1] = aa[lda];\n\t      aa += da;\n\t    }\n\t  if (oddn) { x[2*row] = aa[0]; x[2*row+1] = 0; row += 2; }\n\t}\n      for ( ;row<s;row+=2)\n\t{\n\t  x[2*row] = 0;\n\t  x[2*row+1] = 0;\n\t}\n      a++;\n    }\n}\n\nvoid tpack_4(int n,int p,const double * a,int lda,int s,int q,double * slice)\n{\n  int row,col,icol;\n  double * x = 0;\n  const double * aa;\n  int da = lda<<1;\n  int oddn = 0;\n  if (n&1) { n--; oddn=1; }\n  for (col=0;col<q;col++)\n    {\n      icol = col&3;\n      x = slice + s*(col-icol) + (icol<<1);\n      row = 0;\n      if (col < p)\n\t{\n\t  aa = a;\n\t  for ( ;row<n;row+=2)\n\t    {\n\t      x[4*row] = aa[0];\n\t      x[4*row+1] = aa[lda];\n\t      aa += da;\n\t    }\n\t  if (oddn) { x[4*row] = aa[0]; x[4*row+1] = 0; row += 2; }\n\t}\n      for ( ;row<s;row+=2)\n\t{\n\t  x[4*row] = 0;\n\t  x[4*row+1] = 0;\n\t}\n      a++;\n    }\n}\n", "meta": {"hexsha": "30235543f5c6a1420571fc18f90beb35ef062def", "size": 8393, "ext": "c", "lang": "C", "max_stars_repo_path": "external_libs/isf/wrappers/dgemmsy/dgemmsy_utils.c", "max_stars_repo_name": "gimunu/octopus-metric", "max_stars_repo_head_hexsha": "baabccd5402922a2f62f5cf6030d15e7ea76dc9b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-11-17T09:03:11.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-17T06:31:08.000Z", "max_issues_repo_path": "external_libs/isf/wrappers/dgemmsy/dgemmsy_utils.c", "max_issues_repo_name": "gimunu/octopus-metric", "max_issues_repo_head_hexsha": "baabccd5402922a2f62f5cf6030d15e7ea76dc9b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-15T19:35:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-07T15:32:18.000Z", "max_forks_repo_path": "external_libs/isf/wrappers/dgemmsy/dgemmsy_utils.c", "max_forks_repo_name": "gimunu/octopus-metric", "max_forks_repo_head_hexsha": "baabccd5402922a2f62f5cf6030d15e7ea76dc9b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-11-22T20:30:46.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-29T23:24:51.000Z", "avg_line_length": 22.3813333333, "max_line_length": 103, "alphanum_fraction": 0.5483140712, "num_tokens": 3221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4148988457967688, "lm_q2_score": 0.0367694622493283, "lm_q1q2_score": 0.015255607447814172}}
{"text": "// MIT License\n//\n// Copyright (c) 2021 Daniel Robertson\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#ifndef HX711_DISCOVERY_H_82654AF1_3AA3_4885_9BE7_FA38117DE328\n#define HX711_DISCOVERY_H_82654AF1_3AA3_4885_9BE7_FA38117DE328\n\n#include \"HX711.h\"\n#include <chrono>\n#include <vector>\n#include <pthread.h>\n#include <sched.h>\n#include <thread>\n#include <algorithm>\n#include <cmath>\n#include <gsl/gsl_statistics.h>\n\nnamespace HX711 {\n\nusing namespace std::chrono;\n\nstruct TimingResult {\npublic:\n    Value v;\n    high_resolution_clock::time_point start;\n    high_resolution_clock::time_point waitStart;\n    high_resolution_clock::time_point waitEnd;\n    high_resolution_clock::time_point convertStart;\n    high_resolution_clock::time_point convertEnd;\n    high_resolution_clock::time_point end;\n\n    std::chrono::microseconds getWaitTime() const noexcept {\n        return std::chrono::duration_cast<std::chrono::microseconds>(\n            this->waitEnd - this->waitStart);\n    }\n\n    std::chrono::microseconds getConversionTime() const noexcept {\n        return std::chrono::duration_cast<std::chrono::microseconds>(\n            this->convertEnd - this->convertStart);\n    }\n\n    std::chrono::microseconds getTotalTime() const noexcept {\n        return std::chrono::duration_cast<std::chrono::microseconds>(\n            this->end - this->start);\n    }\n\n};\n\nclass TimingCollection : public std::vector<TimingResult> {\npublic:\n    struct Stats {\n        double min;\n        double max;\n        double med;\n        double std;\n\n        bool inRange(const double n) const noexcept {\n            const double minDev = this->med - this->std;\n            const double maxDev = this->med + this->std;\n            return n >= minDev && n <= maxDev;\n        }\n\n    };\n\nprotected:\n\n    Stats _statsFromVector(std::vector<double>& vec) const noexcept {\n\n        Stats s;\n\n        std::sort(vec.begin(), vec.end());\n\n        s.min = gsl_stats_min(vec.data(), 1, vec.size());\n        s.max = gsl_stats_max(vec.data(), 1, vec.size());\n        s.med = gsl_stats_median_from_sorted_data(vec.data(), 1, vec.size());\n\n        //double work[vec.size()];\n        s.std = gsl_stats_sd(vec.data(), 1, vec.size());\n\n        return s;\n\n    }\n\npublic:\n\n    Stats getWaitTimeStats() const noexcept {\n\n        std::vector<double> vec;\n        vec.reserve(this->size());\n\n        for(auto it = this->cbegin(); it != this->cend(); ++it) {\n            vec.push_back(static_cast<double>(it->getWaitTime().count()));\n        }\n\n        return _statsFromVector(vec);\n\n    }\n\n    Stats getConversionTimeStats() const noexcept {\n\n        std::vector<double> vec;\n        vec.reserve(this->size());\n\n        for(auto it = this->cbegin(); it != this->cend(); ++it) {\n            vec.push_back(static_cast<double>(it->getConversionTime().count()));\n        }\n\n        return _statsFromVector(vec);\n\n    }\n\n    Stats getTotalTimeStats() const noexcept {\n\n        std::vector<double> vec;\n        vec.reserve(this->size());\n\n        for(auto it = this->cbegin(); it != this->cend(); ++it) {\n            vec.push_back(static_cast<double>(it->getTotalTime().count()));\n        }\n\n        return _statsFromVector(vec);\n\n    }\n\n};\n\nclass Discovery : public HX711 {\npublic:\n\n    Discovery(const int dataPin, const int clockPin, const Rate rate) : \n        HX711(dataPin, clockPin, rate) {\n            this->connect();\n    }\n\n    TimingCollection getTimings(const std::size_t samples) {\n\n        using namespace std::chrono;\n\n        TimingCollection vec;\n        vec.reserve(samples);\n\n        for(size_t i = 0; i < samples; ++i) {\n\n            TimingResult tr;\n\n            tr.start = high_resolution_clock::now();\n\n            tr.waitStart = high_resolution_clock::now();\n            while(!this->isReady()) ;\n            tr.waitEnd = high_resolution_clock::now();\n\n            tr.convertStart = high_resolution_clock::now();\n            tr.v = this->readValue();\n            tr.convertEnd = high_resolution_clock::now();\n\n            tr.end = high_resolution_clock::now();\n\n            vec.push_back(tr);\n\n        }\n\n        return vec;\n\n    }\n\n\n    std::vector<std::chrono::nanoseconds> getTimeToReady(const std::size_t samples) {\n\n        using namespace std::chrono;\n\n        std::vector<nanoseconds> timings;\n        timings.reserve(samples);\n\n        //do an initial read\n        while(!this->isReady()) ;\n        this->readValue();\n\n        for(std::size_t i = 0; i < samples; ++i) {\n\n            high_resolution_clock::time_point start = high_resolution_clock::now();\n            while(!this->isReady()) ;\n            high_resolution_clock::time_point end = high_resolution_clock::now();\n\n            timings.push_back(end - start);\n\n            this->readValue();\n\n        }\n\n        return timings;\n\n    }\n\n};\n};\n#endif", "meta": {"hexsha": "ca2270970251a1fd5a1a66e7e3ef38df43a006a6", "size": 5812, "ext": "h", "lang": "C", "max_stars_repo_path": "include/Discovery.h", "max_stars_repo_name": "endail/hx711", "max_stars_repo_head_hexsha": "b1cb63a55b52b76e48a75648901d8954bd67a2f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-03-01T20:05:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T19:14:11.000Z", "max_issues_repo_path": "include/Discovery.h", "max_issues_repo_name": "endail/hx711", "max_issues_repo_head_hexsha": "b1cb63a55b52b76e48a75648901d8954bd67a2f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2021-04-19T04:20:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-07T04:49:57.000Z", "max_forks_repo_path": "include/Discovery.h", "max_forks_repo_name": "endail/hx711", "max_forks_repo_head_hexsha": "b1cb63a55b52b76e48a75648901d8954bd67a2f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-03-29T14:14:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T09:43:26.000Z", "avg_line_length": 27.1588785047, "max_line_length": 85, "alphanum_fraction": 0.6366139023, "num_tokens": 1315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681662740416, "lm_q2_score": 0.038466188711469694, "lm_q1q2_score": 0.015235232826503041}}
{"text": "#ifndef PITCH_H\n#define PITCH_H\n\n\n#include <cstring>\n\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_blas.h>\n\n\n#define DECL_PITCH(name)  bool pitch_ ## name (gsl_vector *frame, double *f0res, double *T0res)\n\n\nDECL_PITCH(AMDF);\n\n\n#endif // PITCH_H\n", "meta": {"hexsha": "1935a6dc0b8a864c2262dace4e41d589847c5965", "size": 272, "ext": "h", "lang": "C", "max_stars_repo_path": "inc/pitch.h", "max_stars_repo_name": "ichi-rika/glottal-inverse", "max_stars_repo_head_hexsha": "c922ed540278e3c8eec528c2cf66b89e6d310575", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-01-24T17:01:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-26T16:22:08.000Z", "max_issues_repo_path": "inc/pitch.h", "max_issues_repo_name": "ichi-rika/glottal-inverse", "max_issues_repo_head_hexsha": "c922ed540278e3c8eec528c2cf66b89e6d310575", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inc/pitch.h", "max_forks_repo_name": "ichi-rika/glottal-inverse", "max_forks_repo_head_hexsha": "c922ed540278e3c8eec528c2cf66b89e6d310575", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-04-27T00:23:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-27T14:41:25.000Z", "avg_line_length": 14.3157894737, "max_line_length": 95, "alphanum_fraction": 0.7205882353, "num_tokens": 86, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.37754066879814546, "lm_q2_score": 0.040237942479749586, "lm_q1q2_score": 0.015191459714865966}}
{"text": "/*\n * \n * Copyright (c) Kresimir Fresl 2002 \n *\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * Author acknowledges the support of the Faculty of Civil Engineering, \n * University of Zagreb, Croatia.\n *\n */\n\n#ifndef BOOST_NUMERIC_BINDINGS_BLAS_DETAIL_CBLAS_H\n#define BOOST_NUMERIC_BINDINGS_BLAS_DETAIL_CBLAS_H\n\n\n\n#ifdef HAS_OpenBLAS\n#define OPENBLAS_CONST_FLOAT_CAST(x) reinterpret_cast<const float*>(x)\n#define OPENBLAS_CONST_DOUBLE_CAST(x) reinterpret_cast<const double*>(x)\n#define OPENBLAS_FLOAT_CAST(x) reinterpret_cast<float*>(x)\n#define OPENBLAS_DOUBLE_CAST(x) reinterpret_cast<double*>(x)\n#define OPENBLAS_OPENBLAS_COMPLEX_FLOAT_CAST(x) reinterpret_cast<openblas_complex_float*>(x)\n#define OPENBLAS_OPENBLAS_COMPLEX_DOUBLE_CAST(x) reinterpret_cast<openblas_complex_double*>(x)\n\n#else\n#define OPENBLAS_CONST_FLOAT_CAST(x) x\n#define OPENBLAS_CONST_DOUBLE_CAST(x) x\n#define OPENBLAS_FLOAT_CAST(x) x\n#define OPENBLAS_DOUBLE_CAST(x) x\n#define OPENBLAS_OPENBLAS_COMPLEX_FLOAT_CAST(x) x\n#define OPENBLAS_OPENBLAS_COMPLEX_DOUBLE_CAST(x) x\n#endif\n\n//\n// MKL-specific CBLAS include\n//\n#if defined BOOST_NUMERIC_BINDINGS_BLAS_MKL\n\nextern \"C\" {\n#include <mkl_cblas.h>\n//#include <mkl_service.h>\n//\n// mkl_types.h defines P4 macro which breaks MPL, undefine it here.\n//\n#undef P4\n}\n\n//\n// Default CBLAS include\n//\n#else\n\nextern \"C\" {\n#include <cblas.h>\n}\n\n#endif\n#endif \n", "meta": {"hexsha": "f0538233207fbadbdfa168e0651699e909b1b533", "size": 1480, "ext": "h", "lang": "C", "max_stars_repo_path": "externals/numeric_bindings/boost/numeric/bindings/blas/detail/cblas.h", "max_stars_repo_name": "ljktest/siconos", "max_stars_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "externals/numeric_bindings/boost/numeric/bindings/blas/detail/cblas.h", "max_issues_repo_name": "ljktest/siconos", "max_issues_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "externals/numeric_bindings/boost/numeric/bindings/blas/detail/cblas.h", "max_forks_repo_name": "ljktest/siconos", "max_forks_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-07T19:35:16.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-07T19:35:16.000Z", "avg_line_length": 24.262295082, "max_line_length": 94, "alphanum_fraction": 0.7858108108, "num_tokens": 389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869689484852374, "lm_q2_score": 0.03622005547484561, "lm_q1q2_score": 0.015165224758559128}}
{"text": "/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*\n**                                                                                  **\n** This file forms part of the Underworld geophysics modelling application.         **\n**                                                                                  **\n** For full license and copyright information, please refer to the LICENSE.md file  **\n** located at the project root, or contact the authors.                             **\n**                                                                                  **\n**~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/\n#include <stdlib.h>\n#include <string.h>\n#include <assert.h>\n#include <mpi.h>\n#include <petsc.h>\n#include <petscvec.h>\n#include <petscmat.h>\n#include <petscksp.h>\n#include <petscpc.h>\n#include <petscsnes.h>\n\n#include <petscversion.h>\n#if ( (PETSC_VERSION_MAJOR >= 3) && (PETSC_VERSION_MINOR >=3) )\n  #if (PETSC_VERSION_MINOR >=6)\n     #include \"petsc/private/kspimpl.h\"\n  #else\n     #include \"petsc-private/kspimpl.h\"   /*I \"petscksp.h\" I*/\n  #endif\n#else\n  #include \"private/kspimpl.h\"   /*I \"petscksp.h\" I*/\n#endif\n\n#include <StGermain/StGermain.h>\n#include <StgDomain/StgDomain.h>\n#include <StgFEM/StgFEM.h>\n#include <PICellerator/PICellerator.h>\n#include <Underworld/Underworld.h>\n#include <Solvers/Solvers.h>\n\n#include \"petsccompat.h\"\n\n#include \"TestKSP.h\"\n\n#define KSPTEST         \"test\"\n\nEXTERN_C_BEGIN\nEXTERN PetscErrorCode PETSCKSP_DLLEXPORT KSPCreate_TEST(KSP);\nEXTERN_C_END\n\n#undef __FUNCT__  \n#define __FUNCT__ \"KSPRegisterTEST\"\nPetscErrorCode PETSCKSP_DLLEXPORT KSPRegisterTEST(const char path[])\n{\n    PetscErrorCode ierr;\n\n    PetscFunctionBegin;\n    ierr = Stg_KSPRegister(KSPTEST, path, \"KSPCreate_TEST\", KSPCreate_TEST );CHKERRQ(ierr);\n    PetscFunctionReturn(0);\n}\n\n\n#undef __FUNCT__  \n#define __FUNCT__ \"KSPSolve_TEST\"\nPetscErrorCode  KSPSolve_TEST(KSP ksp)\n{\n    PetscPrintf( PETSC_COMM_WORLD, \"----- In KSP Solver %s\\n\",__func__);\n    PetscFunctionReturn(0);\n    \n}\n\n\n#undef __FUNCT__  \n#define __FUNCT__ \"KSPDestroy_TEST\" \nPetscErrorCode KSPDestroy_TEST(KSP ksp)\n{\n    PetscErrorCode ierr;\n    PetscFunctionBegin;\n    ierr = KSPDefaultDestroy(ksp);CHKERRQ(ierr);\n    PetscFunctionReturn(0);\n}\n\n#undef __FUNCT__  \n#define __FUNCT__ \"KSPSetFromOptions_TEST\"\nPetscErrorCode KSPSetFromOptions_TEST(KSP ksp)\n{\n\n    PetscFunctionReturn(0);\n}\n\n#undef __FUNCT__  \n#define __FUNCT__ \"KSPView_TEST\" \nPetscErrorCode KSPView_TEST(KSP ksp,PetscViewer viewer)\n{\n    PetscFunctionReturn(0);\n}\n\n#undef __FUNCT__  \n#define __FUNCT__ \"KSPSetUp_TEST\" \nPetscErrorCode KSPSetUp_TEST(KSP ksp)\n{\n    PetscFunctionReturn(0);\n}\n\nEXTERN_C_BEGIN\n#undef __FUNCT__  \n#define __FUNCT__ \"KSPCreate_TEST\"\nPetscErrorCode PETSCKSP_DLLEXPORT KSPCreate_TEST(KSP ksp)\n{\n    PetscErrorCode ierr;\n    PetscFunctionBegin;\n\n    #if ( (PETSC_VERSION_MAJOR >= 3) && (PETSC_VERSION_MINOR >= 2 ) )\n    ierr = KSPSetSupportedNorm(ksp,KSP_NORM_NONE,PC_LEFT,1);CHKERRQ(ierr);\n    #endif\n    /*\n       Sets the functions that are associated with this data structure \n       (in C++ this is the same as defining virtual functions)\n    */\n    ksp->ops->setup                = KSPSetUp_TEST;\n    ksp->ops->solve                = KSPSolve_TEST;\n    ksp->ops->destroy              = KSPDestroy_TEST;\n    ksp->ops->view                 = KSPView_TEST;\n    ksp->ops->setfromoptions       = KSPSetFromOptions_TEST;\n    ksp->ops->buildsolution        = KSPDefaultBuildSolution;\n    ksp->ops->buildresidual        = KSPDefaultBuildResidual;\n\n    \n    PetscFunctionReturn(0);\n}\nEXTERN_C_END\n\n", "meta": {"hexsha": "b3ba18150aedf0a49ed5ed9fcb3c7b159a6911ca", "size": 3651, "ext": "c", "lang": "C", "max_stars_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/Test/TestKSP.c", "max_stars_repo_name": "longgangfan/underworld2", "max_stars_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 116.0, "max_stars_repo_stars_event_min_datetime": "2015-09-28T10:30:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T04:12:38.000Z", "max_issues_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/Test/TestKSP.c", "max_issues_repo_name": "longgangfan/underworld2", "max_issues_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 561.0, "max_issues_repo_issues_event_min_datetime": "2015-09-29T06:05:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T23:37:29.000Z", "max_forks_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/Test/TestKSP.c", "max_forks_repo_name": "longgangfan/underworld2", "max_forks_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 68.0, "max_forks_repo_forks_event_min_datetime": "2015-12-14T21:57:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-25T04:54:26.000Z", "avg_line_length": 28.0846153846, "max_line_length": 91, "alphanum_fraction": 0.6201040811, "num_tokens": 1090, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2598256379609837, "lm_q2_score": 0.058345835699519115, "lm_q1q2_score": 0.01515974398299429}}
{"text": "/*\n * Copyright 2014 Marc Normandin\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n *     Unless required by applicable law or agreed to in writing, software\n *     distributed under the License is distributed on an \"AS IS\" BASIS,\n *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *     See the License for the specific language governing permissions and\n *     limitations under the License.\n */\n#ifndef INC_PARTICLE_H\n#define INC_PARTICLE_H\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <functional>\n#include <cmath>\n#include <cstdlib>\n#include <gsl/gsl_rng.h>\n#include <limits>\n#include <fstream>\n#include <cassert>\n\n#include \"rng.h\"\n#include \"dim.h\"\n\n\nclass Particle\n{\npublic:\n    typedef std::vector<dim_t> dvector;\n    \n    Particle();\n    \n    Particle(const std::vector<Dim>& dim);\n    \n    Particle(const dvector& pos, const prob_t fitness = -1.0 * std::numeric_limits<dim_t>::max());\n    \n    const dvector& getPosition() const;\n    \n    dvector getVelocity() const;\n    \n    double getFitness() const;\n    \n    dvector getPBestPosition() const;\n    \n    double getPBestFitness() const;\n    \n    void updateFitness(const prob_t newFitness);\n    \n    void updatePosition(const Particle& GBest, const std::vector<Dim>& dim, const double C1, const double C2,\n                        const RandomNumberGenerator& rng, const double inertiaWeight);\n        \n    size_t size() const;\n    \n    friend bool operator<(const Particle& p1, const Particle& p2);\n    \nprivate:\n    dvector     mPos;\n    dvector     mVel;\n    prob_t      mFitness;\n    \n    // The particles best position\n    dvector\t\tmPBestPos;\n    prob_t \t\tmPBestFitness;\n};\n\nbool operator<(const Particle& p1, const Particle& p2);\n\n#endif // #ifndef INC_PARTICLE_H\n", "meta": {"hexsha": "e087cccaba8bbf2e06ba7c4cceef2b8311871da0", "size": 1973, "ext": "h", "lang": "C", "max_stars_repo_path": "particle.h", "max_stars_repo_name": "marcnormandin/ParticleSwarmOptimization", "max_stars_repo_head_hexsha": "6690fde0de155acd44ba5a3eab4224276f120ed5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-05-28T05:27:28.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-09T21:25:19.000Z", "max_issues_repo_path": "particle.h", "max_issues_repo_name": "marcnormandin/ParticleSwarmOptimization", "max_issues_repo_head_hexsha": "6690fde0de155acd44ba5a3eab4224276f120ed5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2015-05-27T05:48:44.000Z", "max_issues_repo_issues_event_max_datetime": "2015-06-11T20:48:15.000Z", "max_forks_repo_path": "particle.h", "max_forks_repo_name": "marcnormandin/ParticleSwarmOptimization", "max_forks_repo_head_hexsha": "6690fde0de155acd44ba5a3eab4224276f120ed5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6233766234, "max_line_length": 109, "alphanum_fraction": 0.6751140395, "num_tokens": 465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3998116550426623, "lm_q2_score": 0.03789242635798463, "lm_q1q2_score": 0.015149833695768035}}
{"text": "#include <glib.h>\n#include <gsl/gsl_rng.h>\n#include <stdlib.h>\n#include \"util.h\"\n\nhash_t *hash_create () {\n  return (char*) g_hash_table_new(g_direct_hash, g_direct_equal);\n}\n\nvoid hash_set (hash_t *table, size_t key, size_t value) {\n  g_hash_table_replace((GHashTable*)table, (gpointer)key, (gpointer)value);\n}\n\nsize_t hash_get (hash_t *table, size_t key, size_t value) {\n  size_t orig_key;\n  size_t result;\n  if (g_hash_table_lookup_extended((GHashTable*)table, (gpointer)key, (gpointer*)&orig_key, (gpointer*)&result)) {\n    return result;\n  }\n  return value;\n}\n\nvoid hash_clear (hash_t *table) {\n  return g_hash_table_remove_all((GHashTable*)table);\n}\n\nvoid hash_destroy (hash_t *table) {\n  return g_hash_table_destroy((GHashTable*)table);\n}\n\ngsl_rng *r = 0;\n\nsize_t random_range (size_t lo, size_t hi) {\n  if (!r) {\n    gsl_rng_env_setup();\n    const gsl_rng_type *T = gsl_rng_default;\n    r = gsl_rng_alloc (T);\n  }\n  size_t n = hi - lo;\n  return lo + gsl_rng_uniform_int(r, n);//todo this range might not be big enough/type issues may occur here.\n}\n\ndouble random_uniform () {\n  if (!r) {\n    gsl_rng_env_setup();\n    const gsl_rng_type *T = gsl_rng_default;\n    r = gsl_rng_alloc (T);\n  }\n  return gsl_rng_uniform(r);\n}\n\nvoid random_choose (size_t *samples, size_t n, size_t lo, size_t hi) {\n  hash_t *table = hash_create();\n  for (size_t i = 0; i < n; i++) {\n    size_t j = random_range(lo, hi);\n    samples[i] = hash_get(table, j, j);\n    hash_set(table, j, hash_get(table, lo, lo));\n    lo++;\n  }\n  hash_destroy(table);\n}\n\nint size_t_cmp(const void *a, const void *b)\n{\n    const size_t *ia = (const size_t *)a;\n    const size_t *ib = (const size_t *)b;\n    return *ia  - *ib;\n}\n\nvoid quicksort(size_t *stuff, size_t n)\n{\n  if (n < 2) return;\n\n  size_t pivot = stuff[n / 2];\n\n  size_t i, j;\n  for (i = 0, j = n - 1; ; i++, j--)\n  {\n    while (stuff[i] < pivot) i++;\n    while (stuff[j] > pivot) j--;\n\n    if (i >= j) break;\n\n    size_t temp = stuff[i];\n    stuff[i]     = stuff[j];\n    stuff[j]     = temp;\n  }\n\n  quicksort(stuff, i);\n  quicksort(stuff + i, n - i);\n}\n\nvoid sort (size_t *stuff, size_t n) {\n  //quicksort(stuff, n);\n  qsort(stuff, n, sizeof(size_t), size_t_cmp);\n}\n\nsize_t search (const size_t *stuff, size_t lo, size_t hi, size_t key) {\n  size_t len = hi - lo;\n  size_t half;\n  size_t mid;\n  while (len > 0) {\n    half = len >> 1;\n    mid = lo + half;\n    if (stuff[mid] >= key) {\n      len = half;\n    } else {\n      lo = mid;\n      lo++;\n      len = len - half - 1;\n    }\n  }\n  return lo;\n}\n\nsize_t search_strict (const size_t *stuff, size_t lo, size_t hi, size_t key) {\n  size_t len = hi - lo;\n  size_t half;\n  size_t mid;\n  while (len > 0) {\n    half = len >> 1;\n    mid = lo + half;\n    if (stuff[mid] > key) {\n      len = half;\n    } else {\n      lo = mid;\n      lo++;\n      len = len - half - 1;\n    }\n  }\n  return lo;\n}\n", "meta": {"hexsha": "a1384745c2d480e631c6e6848b6ebcafac22a7a7", "size": 2856, "ext": "c", "lang": "C", "max_stars_repo_path": "src/util.c", "max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/util.c", "max_issues_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_issues_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/util.c", "max_forks_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_forks_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.4736842105, "max_line_length": 114, "alphanum_fraction": 0.606092437, "num_tokens": 914, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3998116264369279, "lm_q2_score": 0.03789242839515542, "lm_q1q2_score": 0.01514983342631192}}
{"text": "///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n//\n//\n// \t\t\t     //////////////////////////////////////////////////////////\n//  \t\t\t     //\t\t\t\t\t\t\t     //\n// \t\t\t     //   \t        hybridMANTIS v1.0\t\t     //\n// \t\t\t     //                fastDETECT2 - C code                  //\n//\t\t\t     //\t\t   (optical photons transport)\t\t     //\n//  \t\t\t     //\t\t\t\t\t\t\t     //\n//                           //               used for Load Balancing                //\n//\t\t\t     //\t\t\t\t\t\t\t     //\n//\t\t\t     //////////////////////////////////////////////////////////\n//\n// \n//\n//\n// ****Disclaimer****\n//  This software and documentation (the \"Software\") were developed at the Food and Drug Administration (FDA) by employees of the Federal Government in\n//  the course of their official duties. Pursuant to Title 17, Section 105 of the United States Code, this work is not subject to copyright protection\n//  and is in the public domain. Permission is hereby granted, free of charge, to any person obtaining a copy of the Software, to deal in the Software\n//  without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, or sell copies of the\n//  Software or derivatives, and to permit persons to whom the Software is furnished to do so. FDA assumes no responsibility whatsoever for use by other\n//  parties of the Software, its source code, documentation or compiled executables, and makes no guarantees, expressed or implied, about its quality,\n//  reliability, or any other characteristic. Further, use of this code in no way implies endorsement by the FDA or confers any advantage in regulatory\n//  decisions. Although this software can be redistributed and/or modified freely, we ask that any derivative works bear some notice that they are\n//  derived from it, and any modified versions bear some notice that they have been modified. \n//\n//\tDetailed comments are available in \"hybridMANTIS_cuda_ver1_0.cu\" and \"hybridMANTIS_c_ver1_0.c\" files.\n//\n//\tAssociated publication: Sharma Diksha, Badal Andreu and Badano Aldo, \"hybridMANTIS: a CPU-GPU Monte Carlo method for modeling indirect x-ray detectors with\n//\t\t\t\tcolumnar scintillators\". Physics in Medicine and Biology, 57(8), pp. 2357\u20132372 (2012)\n//\n//\n//\tFile:   \thybridMANTIS_c_ver1_0_LB.c \t\t\t\n//\tAuthor: \tDiksha Sharma (US Food and Drug Administration)\n//\tEmail: \t\tdiksha.sharma@fda.hhs.gov\t\t\t\n//\tLast updated:  \tApr 13, 2012\n// \n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n/////////////////////////////////////////\n//\n//      Header libraries\n//\n/////////////////////////////////////////\n\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n\n/////////////////////////////////////////\n//\n//      Global variables\n//\n/////////////////////////////////////////\n\n#define max_photon_per_EDE 900000\t// maximum number of optical photons that can be generated per energy deposition event (EDE)\n\n#ifndef USING_CUDA\n\t#define mybufsizeT 2304000\t// CPU buffer size: # of events sent to the CPU\n#endif\n\n/////////////////////////////////////////\n//\n//      Include kernel program\n//\n/////////////////////////////////////////\n#include \"kernel_cuda_c_ver1_0_LB.cu\"\n\n\n////////////////////////////////////////////////////////////////////////////\n//\t\t\t\tMAIN PROGRAM\t\t\t          //\n////////////////////////////////////////////////////////////////////////////\n\n#ifndef USING_CUDA\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n//\n// cpuoptlb():   Performs optical transport for finding optimal load using load balancing in the CPU \n//\t  \t Input arguments: cptime, cpubufsize\n//\n//\t\t cptime: \ttime taken by GPU to call this routine\n//\t\t cpubufsize:  \tCPU buffer size defined by user in PENELOPE tally code. Only to be used for load balancing. This is different from 'mybufsize'.\n//\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n\tvoid cpuoptlb_(double *cptime, int *cpubufsize)\n\t{    \n\n\t\tfloat dcos[3]={0}; \t\t// directional cosines\n\t\tfloat normal[3]={0}; \t\t// normal to surface in case of TIR\n\t\tfloat pos[3] = {0}; \t\t// new position\n\t\tfloat old_pos[3] = {0};  \t// source coordinates\n\t\n\t\t// command line arguments\n\t\tfloat xdetector, ydetector, radius, height, n_C, n_IC, top_absfrac, bulk_abscoeff, beta, d_min, lbound_x, lbound_y, ubound_x, ubound_y, d_max, yield, sensorRefl;\n\t\tint pixelsize, num_primary, min_optphotons, max_optphotons, num_bins;\n\n\t\tint nbytes = (*cpubufsize)*sizeof(struct start_info);\n\t\tstruct start_info *structa;\n\t\tstructa = (struct start_info*) malloc(nbytes);\n\t\tif( structa == NULL )\n\t\t\tprintf(\"\\n Struct start_info array CANNOT BE ALLOCATED - %d !!\", (*cpubufsize));\n\n\t\t// get cpu time\n\t\tclock_t start, end;\n\t\tdouble num_sec;\n\n\t\t// get current time stamp to initialize seed input for RNG\n\t\ttime_t seconds;\n\t\tseconds = time (NULL);\n\t\tstruct timeval tv;\n\t\tgettimeofday(&tv,NULL);\n\n\t\tfloat rr=0.0f, theta=0.0f;\n\t\tfloat r=0.0f;\t\t// random number\n\t\tfloat norm=0.0f;\n\t\tint jj=0;\n\n\t\t// initialize random number generator (RANECU)\n\t\tint seed_input = 271828182 ; // ranecu seed input\n\t\tint seed[2];\n\n\t\t// gsl variables\n\t\tconst gsl_rng_type * Tgsl;\n\t\tgsl_rng * rgsl;\n\t\tdouble mu_gsl;\t\n\t\tint my_index=0;\n\t\tint result_algo = 0;\n\t\tunsigned long long int *num_rebound;\n\n\t\t// output image variables\n\t\tint xdim = 0;\n\t\tint ydim = 0;\n\t\tint indexi=0, indexj=0;\n\n\t      \t// create a generator chosen by the environment variable GSL_RNG_TYPE\n\t       \tgsl_rng_env_setup();\t     \n\t       \tTgsl = gsl_rng_default;\n\t       \trgsl = gsl_rng_alloc (Tgsl);\n\n \t\t// copy to local variables from PENELOPE buffers\n\t\txdetector = inputargs_.detx;\t\t// x dimension of detector (in um). x in (0,xdetector)\n\t\tydetector = inputargs_.dety;\t\t// y dimension of detector (in um). y in (0,ydetector)\n\t\theight = inputargs_.detheight;\t\t// height of column and thickness of detector (in um). z in range (-H/2, H/2)\n\t\tradius = inputargs_.detradius;\t\t// radius of column (in um).\n\t\tn_C = inputargs_.detnC;\t\t\t// refractive index of columns\n\t\tn_IC = inputargs_.detnIC;\t\t// refractive index of intercolumnar material\n\t\ttop_absfrac = inputargs_.dettop;\t// column's top surface absorption fraction (0.0, 0.5, 0.98)\n\t\tbulk_abscoeff = inputargs_.detbulk;\t// column's bulk absorption coefficient (in um^-1) (0.001, 0.1 cm^-1) \n\t\tbeta = inputargs_.detbeta;\t\t// roughness coefficient of column walls\n\t\td_min = inputargs_.detdmin;\t\t// minimum distance a photon can travel when transmitted from a column\n\t\td_max = inputargs_.detdmax;\n\t\tlbound_x = inputargs_.detlboundx;\t// x lower bound of region of interest of output image (in um)\n\t\tlbound_y = inputargs_.detlboundy;\t// y lower bound (in um)\n\t\tubound_x = inputargs_.detuboundx;\t// x upper bound (in um) \n\t\tubound_y = inputargs_.detuboundy;\t// y upper bound (in um)\n\t\tyield = inputargs_.detyield;\t\t// yield (/eV)\n\t\tpixelsize = inputargs_.detpixel;\t// 1 pixel = pixelsize microns (in um)\n\t\tsensorRefl = inputargs_.detsensorRefl;\t// Non-Ideal sensor reflectivity (%)\n\t\tnum_primary = inputargs_.mynumhist;\t// total number of primaries to be simulated\n\t\tmin_optphotons = inputargs_.minphotons;\t// minimum number of optical photons detected to be included in PHS\n\t\tmax_optphotons = inputargs_.maxphotons;\t// maximum number of optical photons detected to be included in PHS\n\t\tnum_bins = inputargs_.mynumbins;\t// number of bins for genrating PHS\n\t\t\n\t\t// dimensions of PRF image\n\t\txdim = ceil((ubound_x - lbound_x)/pixelsize);\n\t\tydim = ceil((ubound_y - lbound_y)/pixelsize);\n\t\tunsigned long long int myimage[xdim][ydim];\n\t\t\n\t\t// memory for storing histogram of # photons detected/primary\n\t\tint *h_num_detected_prim = 0;\t\t\n\t\th_num_detected_prim = (int*)malloc(sizeof(int)*num_primary);\n\t\t\t\n\t\tfor(indexj=0; indexj < num_primary; indexj++)\n\t\t  h_num_detected_prim[indexj] = 0;\n\t\t  \t \n\t\t// start the clock\n\t\tstart = clock();\n\n\tfor(my_index = 0; my_index < (*cpubufsize); my_index++)\t\t// iterate over x-rays\n\t{\n\n\t\t// reset the global counters\n\t\tnum_generatedT = 0;\n\t\tnum_detectT=0;\n\t\tnum_abs_topT=0;\t\n\t\tnum_abs_bulkT=0;\t\n\t\tnum_lostT=0;\n\t\tnum_outofcolT=0;\n\t\tnum_theta1T=0;\n\t\tphoton_distanceT=0.0f;\n\n\t\t// copying fortran buffer into *structa\n\n\t\t// units in the penelope output file are in cm. Convert to microns.\n\t\tstructa[my_index].str_x = optical_.xbufopt[my_index] * 10000.0f;\t// x-coordinate of interaction event.\n\t\tstructa[my_index].str_y = optical_.ybufopt[my_index] * 10000.0f;\t// y-coordinate\n\t\tstructa[my_index].str_z = optical_.zbufopt[my_index] * 10000.0f;\t// z-coordinate\n\t\tstructa[my_index].str_E = optical_.debufopt[my_index];\t\t\t// energy deposited\n\t\tstructa[my_index].str_histnum = optical_.nbufopt[my_index];\t\t// x-ray history number\n\n\t\t// sample # optical photons based on light yield and energy deposited for this interaction event (using Poisson distribution)\n\t\tmu_gsl = (double)structa[my_index].str_E * yield;\n\t\tstructa[my_index].str_N = gsl_ran_poisson(rgsl,mu_gsl);\n\n\t\tif(structa[my_index].str_N > max_photon_per_EDE)\n\t\t{\n\t\t\tprintf(\"\\n\\n CPU str_n exceeds max photons. program is exiting - %d !! \\n\\n\",structa[my_index].str_N);\n\t\t\texit(0);\n\t\t}\n\n\t\tnum_rebound = (unsigned long long int*) malloc(structa[my_index].str_N*sizeof(unsigned long long int));\n\t\tif(num_rebound == NULL)\n\t\t\tprintf(\"\\n Error allocating num_rebound memory !\\n\");\n\n\n\t\t// initialize the RANECU generator in a position far away from the previous history:\n\t\tseed_input = (int)(seconds/3600+tv.tv_usec);\t\t\t// seed input=seconds passed since 1970+current time in micro secs\n\t\tinit_PRNG(my_index, 50000, seed_input, seed);      \t\t// intialize RNG\n\n\t\tfor(jj=0; jj<structa[my_index].str_N; jj++)\n\t\t\tnum_rebound[jj] = 0;\n\n\t\t// reset the vectors\n\t\tdcos[0]=0.0f; dcos[1]=0.0f; dcos[2]=0.0f;\n\t\tnormal[0]=0.0f; normal[1]=0.0f; normal[2]=0.0f;\n\n\t\t// set starting location of photon\n\t\tpos[0] = structa[my_index].str_x; pos[1] = structa[my_index].str_y; pos[2] = structa[my_index].str_z;\t\n\t\told_pos[0] = structa[my_index].str_x; old_pos[1] = structa[my_index].str_y; old_pos[2] = structa[my_index].str_z;\n\n\t\t// initializing the direction cosines for the first particle in each core\n\t\tr = (ranecu(seed) * 2.0f) - 1.0f; // random number between (-1,1)\n\t\t \t\n\t\twhile(fabs(r) <= 0.01f)\t\n\t\t {\n\t\t   \tr = (ranecu(seed) * 2.0f) - 1.0f;  \t\n\t\t }\n\n\t\tdcos[2] = r;\t\t// random number between (-1,1)\n\t\trr = sqrt(1.0f-r*r);\n\t\ttheta=ranecu(seed)*twopipen;\n\t\tdcos[0]=rr*cos(theta);\n\t\tdcos[1]=rr*sin(theta);\n\n\t\tnorm = sqrt(dcos[0]*dcos[0] + dcos[1]*dcos[1] + dcos[2]*dcos[2]);\n\n\t\tif ((norm < (1.0f - epsilon)) || (norm > (1.0f + epsilon)))\t// normalize\n\t\t {\n\t\t\tdcos[0] = dcos[0]/norm;\n\t\t\tdcos[1] = dcos[1]/norm;\n\t\t\tdcos[2] = dcos[2]/norm;\n\t\t }\n\n\t\tlocal_counterT=0;\n\t\twhile(local_counterT < structa[my_index].str_N)\n\t\t { \n\t\t\t\n\t\t\tabsorbedT = 0;\n\t\t\tdetectT = 0;\n\t\t\tbulk_absT = 0;\n\n\t\t\t// set starting location of photon\n\t\t\tpos[0] = structa[my_index].str_x; pos[1] = structa[my_index].str_y; pos[2] = structa[my_index].str_z;\t\n\t\t\told_pos[0] = structa[my_index].str_x; old_pos[1] = structa[my_index].str_y; old_pos[2] = structa[my_index].str_z;\n\t\t\tnum_generatedT++;\n\t\t\tresult_algo = 0;\n\n\t\t\twhile(result_algo == 0)\n\t\t\t {\n\t\t\t  \tresult_algo = algoT(normal, old_pos, pos, dcos, num_rebound, seed, structa[my_index], &myimage[0][0], xdetector, ydetector, radius, height, n_C, n_IC, top_absfrac, bulk_abscoeff, beta, d_min, pixelsize, lbound_x, lbound_y, ubound_x, ubound_y, sensorRefl, d_max, ydim, h_num_detected_prim);      \n\t\t\t }\n\n\t\t }\t\n\n\t\t// release resources\n\t\tfree(num_rebound);\n\n\t}\t// my_index loop ends\n\n\n\t// end the clock\t\t\n\tend = clock();\n\n\tnum_sec = (double)((end - start)/CLOCKS_PER_SEC);\n        *cptime = num_sec;\n        \n\t// release resources\n\tfree(structa);\n\tfree(h_num_detected_prim);\n\n\t\treturn;\n\t}\t// C main() ends\n\t\n#endif\n", "meta": {"hexsha": "be9f33e7d7296786f8b658f9515a8c78dcfc04d9", "size": 12094, "ext": "c", "lang": "C", "max_stars_repo_path": "main/hybridMANTIS_c_ver1_0_LB.c", "max_stars_repo_name": "diamfda/hybridmantis", "max_stars_repo_head_hexsha": "8e2d374baaad27b3eae62fab34bea7675eb1ee4d", "max_stars_repo_licenses": ["BSD-Source-Code"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main/hybridMANTIS_c_ver1_0_LB.c", "max_issues_repo_name": "diamfda/hybridmantis", "max_issues_repo_head_hexsha": "8e2d374baaad27b3eae62fab34bea7675eb1ee4d", "max_issues_repo_licenses": ["BSD-Source-Code"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main/hybridMANTIS_c_ver1_0_LB.c", "max_forks_repo_name": "diamfda/hybridmantis", "max_forks_repo_head_hexsha": "8e2d374baaad27b3eae62fab34bea7675eb1ee4d", "max_forks_repo_licenses": ["BSD-Source-Code"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.8581081081, "max_line_length": 301, "alphanum_fraction": 0.6134446833, "num_tokens": 3414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39981164073979497, "lm_q2_score": 0.03789242499987083, "lm_q1q2_score": 0.015149832610807983}}
{"text": "#include \"vector.h\"\n\n#include \"math.h\"\n#include \"mem.h\"\n#include \"string_utils.h\"\n#include \"ut_utils.h\"\n\ntypedef struct {\n    char *name;\n    char age;\n} nage_t;\n\nvoid free_nage_t(void *pnage)\n{\n    nage_t *nage = pnage;\n    ufree(nage->name);\n    ufree(nage);\n}\n\nvoid *copy_nage_t(const void *pnage)\n{\n    const nage_t *nage = pnage;\n\n    nage_t *n = umalloc(sizeof(*n));\n    UASSERT(n);\n\n    n->name = ustring_dup(nage->name);\n    n->age = nage->age;\n\n    return n;\n}\n\nvoid test_uvector_copy(bool verbose)\n{\n    (void)verbose;\n\n    uvector_t *v = uvector_create();\n    uvector_set_void_destroyer(v, free_nage_t);\n    uvector_set_void_copier(v, copy_nage_t);\n\n    nage_t *n = umalloc(sizeof(*n));\n\n    *n = (nage_t){ustring_dup(\"john\"), 34};\n    uvector_append(v, G_PTR(n)); // v owns *n data\n\n    uvector_t *v2 = uvector_copy(v); // v2 has shallow copy of *n2\n    uvector_t *v3 = uvector_deep_copy(v); // v3 has deep copy of *n2, must set own\n\n    uvector_destroy(v);\n    uvector_destroy(v2);\n    uvector_destroy(v3);\n}\n\nvoid test_uvector_bsearch(void)\n{\n    uvector_t *v = uvector_create();\n    uvector_append(v, G_INT(1));\n    uvector_append(v, G_INT(2));\n    uvector_append(v, G_INT(4));\n    uvector_append(v, G_INT(3));\n\n    uvector_sort(v); // [1, 2, 3, 4]]\n    UASSERT_INT_EQ(uvector_bsearch(v, G_INT(1)), 0);\n    UASSERT_INT_EQ(uvector_bsearch(v, G_INT(2)), 1);\n    UASSERT_INT_EQ(uvector_bsearch(v, G_INT(3)), 2);\n    UASSERT_INT_EQ(uvector_bsearch(v, G_INT(4)), 3);\n    UASSERT_INT_EQ(uvector_bsearch(v, G_INT(400)), SIZE_MAX);\n    UASSERT_INT_EQ(uvector_bsearch(v, G_INT(-400)), SIZE_MAX);\n\n    uvector_remove_at(v, 1); // [1, 3, 4]\n    UASSERT_INT_EQ(uvector_bsearch(v, G_INT(1)), 0);\n    UASSERT_INT_EQ(uvector_bsearch(v, G_INT(2)), SIZE_MAX);\n    UASSERT_INT_EQ(uvector_bsearch(v, G_INT(3)), 1);\n    UASSERT_INT_EQ(uvector_bsearch(v, G_INT(4)), 2);\n    UASSERT_INT_EQ(uvector_bsearch(v, G_INT(400)), SIZE_MAX);\n    UASSERT_INT_EQ(uvector_bsearch(v, G_INT(-400)), SIZE_MAX);\n\n    uvector_pop_back(v); // [1, 3]\n    UASSERT_INT_EQ(uvector_bsearch(v, G_INT(1)), 0);\n    UASSERT_INT_EQ(uvector_bsearch(v, G_INT(2)), SIZE_MAX);\n    UASSERT_INT_EQ(uvector_bsearch(v, G_INT(3)), 1);\n    UASSERT_INT_EQ(uvector_bsearch(v, G_INT(4)), SIZE_MAX);\n    UASSERT_INT_EQ(uvector_bsearch(v, G_INT(400)), SIZE_MAX);\n    UASSERT_INT_EQ(uvector_bsearch(v, G_INT(-400)), SIZE_MAX);\n\n    uvector_pop_at(v, 0); // [3]\n    UASSERT_INT_EQ(uvector_bsearch(v, G_INT(1)), SIZE_MAX);\n    UASSERT_INT_EQ(uvector_bsearch(v, G_INT(2)), SIZE_MAX);\n    UASSERT_INT_EQ(uvector_bsearch(v, G_INT(3)), 0);\n    UASSERT_INT_EQ(uvector_bsearch(v, G_INT(4)), SIZE_MAX);\n    UASSERT_INT_EQ(uvector_bsearch(v, G_INT(400)), SIZE_MAX);\n    UASSERT_INT_EQ(uvector_bsearch(v, G_INT(-400)), SIZE_MAX);\n\n    uvector_pop_at(v, 0);\n    UASSERT_INT_EQ(uvector_get_size(v), 0);\n    UASSERT_INT_EQ(uvector_bsearch(v, G_INT(1)), SIZE_MAX);\n    UASSERT_INT_EQ(uvector_bsearch(v, G_INT(2)), SIZE_MAX);\n    UASSERT_INT_EQ(uvector_bsearch(v, G_INT(3)), SIZE_MAX);\n    UASSERT_INT_EQ(uvector_bsearch(v, G_INT(4)), SIZE_MAX);\n    UASSERT_INT_EQ(uvector_bsearch(v, G_INT(400)), SIZE_MAX);\n    UASSERT_INT_EQ(uvector_bsearch(v, G_INT(-400)), SIZE_MAX);\n\n    uvector_destroy(v);\n}\n\nvoid test_uvector_next_permutation(bool verbose)\n{\n    uvector_t *v = uvector_create();\n    uvector_append(v, G_INT(4));\n    uvector_append(v, G_INT(3));\n    uvector_append(v, G_INT(1));\n    uvector_append(v, G_INT(2));\n\n    do {\n        if (verbose)\n            uvector_print(v);\n    } while (uvector_next_permutation(v));\n\n    uvector_destroy(v);\n}\n\nvoid test_uvector_serialization(bool verbose)\n{\n    char *vs;\n    uvector_t *v = uvector_create();\n\n    vs = uvector_as_str(v);\n    UASSERT_STR_EQ(vs, \"[]\");\n    ufree(vs);\n\n    uvector_append(v, G_INT(11));\n    uvector_append(v, G_INT(22));\n    uvector_append(v, G_INT(33));\n    uvector_append(v, G_STR(ustring_dup(\"44\")));\n    uvector_append(v, G_CSTR(\"5\"));\n\n    uvector_append(v, G_VECTOR(uvector_deep_copy(v)));\n    uvector_append(v, G_VECTOR(uvector_deep_copy(v)));\n\n    if (verbose)\n        uvector_print(v);\n    vs = uvector_as_str(v);\n    UASSERT_STR_EQ(vs,\n                  \"[11, 22, 33, \\\"44\\\", \\\"5\\\", [11, 22, 33, \\\"44\\\", \\\"5\\\"], [11, 22, 33, \\\"44\\\", \\\"5\\\", [11, 22, 33, \\\"44\\\", \\\"5\\\"]]]\");\n    ufree(vs);\n    uvector_destroy(v);\n}\n\nvoid test_uvector_api()\n{\n    uvector_t *v = uvector_create();\n    uvector_append(v, G_INT(0));\n    UASSERT(uvector_get_capacity(v) >= VECTOR_INITIAL_CAPACITY);\n    uvector_reserve_capacity(v, 1000);\n    UASSERT_INT_EQ(uvector_get_capacity(v), 1000);\n    uvector_destroy(v);\n\n    v = uvector_create_with_size(3, G_NULL());\n    UASSERT_INT_EQ(uvector_get_size(v), 3);\n\n    uvector_append(v, G_INT(11));\n    uvector_append(v, G_INT(22));\n    uvector_append(v, G_INT(33));\n    UASSERT_INT_EQ(uvector_get_size(v), 6);\n    UASSERT(G_IS_NULL(uvector_get_at(v, 0)));\n    UASSERT_INT_EQ(G_AS_INT(uvector_get_at(v, 3)), 11);\n    UASSERT_INT_EQ(G_AS_INT(uvector_get_at(v, 4)), 22);\n    UASSERT_INT_EQ(G_AS_INT(uvector_get_at(v, 5)), 33);\n\n    uvector_swap(v, 4, 5);\n    UASSERT_INT_EQ(G_AS_INT(uvector_get_at(v, 4)), 33);\n    UASSERT_INT_EQ(G_AS_INT(uvector_get_at(v, 5)), 22);\n\n    uvector_resize(v, 0, G_NULL());\n    UASSERT(uvector_is_empty(v));\n\n    uvector_append(v, G_INT(44));\n    UASSERT_INT_EQ(uvector_get_size(v), 1);\n    UASSERT_INT_EQ(G_AS_INT(uvector_get_at(v, 0)), 44);\n\n    uvector_set_at(v, 0, G_INT(2222));\n    UASSERT_INT_EQ(G_AS_INT(uvector_get_at(v, 0)), 2222);\n\n    ugeneric_t *a = uvector_get_cells(v);\n    UASSERT_INT_EQ(G_AS_INT(a[0]), 2222);\n    uvector_destroy(v);\n\n    v = uvector_create();\n    UASSERT_INT_EQ(uvector_get_size(v), 0);\n    UASSERT(uvector_is_empty(v));\n    uvector_append(v, G_INT(11));\n    UASSERT(!uvector_is_empty(v));\n    UASSERT_INT_EQ(uvector_get_size(v), 1);\n    UASSERT_INT_EQ(G_AS_INT(uvector_pop_back(v)), 11);\n    UASSERT(uvector_is_empty(v));\n    UASSERT_INT_EQ(uvector_get_size(v), 0);\n\n    uvector_resize(v, 0, G_NULL());\n    uvector_append(v, G_INT(200));\n    uvector_append(v, G_INT(100));\n    UASSERT_INT_EQ(uvector_get_size(v), 2);\n    UASSERT_INT_EQ(G_AS_INT(uvector_get_at(v, 0)), 200);\n    UASSERT_INT_EQ(G_AS_INT(uvector_get_at(v, 1)), 100);\n    uvector_insert_at(v, 1, G_INT(300));\n    UASSERT_INT_EQ(uvector_get_size(v), 3);\n    UASSERT_INT_EQ(G_AS_INT(uvector_get_at(v, 0)), 200);\n    UASSERT_INT_EQ(G_AS_INT(uvector_get_at(v, 1)), 300);\n    UASSERT_INT_EQ(G_AS_INT(uvector_get_at(v, 2)), 100);\n    UASSERT_INT_EQ(G_AS_INT(uvector_pop_at(v, 0)), 200);\n    UASSERT_INT_EQ(uvector_get_size(v), 2);\n    UASSERT_INT_EQ(G_AS_INT(uvector_pop_at(v, 0)), 300);\n    UASSERT_INT_EQ(uvector_get_size(v), 1);\n    UASSERT_INT_EQ(G_AS_INT(uvector_pop_at(v, 0)), 100);\n    UASSERT_INT_EQ(uvector_get_size(v), 0);\n    uvector_resize(v, 1000, G_NULL());\n    UASSERT_INT_EQ(uvector_get_size(v), 1000);\n    uvector_destroy(v);\n\n    v = uvector_create();\n    uvector_append(v, G_STR(ustring_dup(\"1\")));\n    uvector_append(v, G_STR(ustring_dup(\"2\")));\n    uvector_append(v, G_STR(ustring_dup(\"3\")));\n    uvector_append(v, G_STR(ustring_dup(\"4\")));\n    uvector_resize(v, 2, G_NULL());\n    uvector_resize(v, 1, G_NULL());\n    uvector_clear(v);\n    uvector_append(v, G_STR(ustring_dup(\"5\")));\n    UASSERT_INT_EQ(uvector_get_size(v), 1);\n    uvector_destroy(v);\n\n    v = uvector_create();\n    uvector_append(v, G_STR(ustring_dup(\"string\")));\n    uvector_set_at(v, 0, G_STR(ustring_dup(\"string2\")));\n    uvector_destroy(v);\n\n    v = uvector_create();\n    uvector_append(v, G_INT(123));\n    UASSERT_INT_EQ(G_AS_INT(uvector_get_at(v, 0)), 123);\n    UASSERT_INT_EQ(G_AS_INT(uvector_get_back(v)), 123);\n    uvector_t *vcopy = uvector_copy(v);\n    UASSERT(uvector_compare(v, vcopy) == 0);\n    uvector_destroy(v);\n    uvector_destroy(vcopy);\n\n    v = uvector_create();\n    uvector_reserve_capacity(v, 1024);\n    uvector_shrink_to_size(v);\n    uvector_destroy(v);\n\n    v = uvector_create();\n    uvector_append(v, G_STR(ustring_dup(\"1\")));\n    uvector_append(v, G_INT(42));\n    uvector_append(v, G_BOOL(false));\n    UASSERT(uvector_contains(v, G_STR(\"1\")));\n    UASSERT(uvector_contains(v, G_CSTR(\"1\")));\n    UASSERT(uvector_contains(v, G_BOOL(false)));\n    UASSERT(uvector_contains(v, G_INT(42)));\n    UASSERT(!uvector_contains(v, G_STR(\"2\")));\n    UASSERT(!uvector_contains(v, G_BOOL(true)));\n    UASSERT(!uvector_contains(v, G_INT(100)));\n    uvector_destroy(v);\n\n\n#if defined(__unix__) && defined(ENABLE_UASSERT_INPUT)\n    // Check asserts.\n    UASSERT_ABORTS(uvector_append(NULL, G_INT(0)));\n    UASSERT_ABORTS(uvector_pop_back(NULL));\n    UASSERT_ABORTS(uvector_get_cells(NULL));\n    UASSERT_ABORTS(uvector_get_size(NULL));\n    UASSERT_ABORTS(uvector_resize(NULL, 100, G_NULL()));\n    UASSERT_ABORTS(uvector_reserve_capacity(NULL, 100));\n    UASSERT_ABORTS(uvector_get_capacity(NULL));\n    UASSERT_ABORTS(uvector_is_empty(NULL));\n    UASSERT_ABORTS(uvector_swap(NULL, 1, 2));\n    UASSERT_ABORTS(uvector_insert_at(NULL, 1, G_INT(100)));\n    UASSERT_ABORTS(uvector_get_at(NULL, 1));\n    UASSERT_ABORTS(uvector_set_at(NULL, 1, G_INT(0)));\n    uvector_destroy(NULL);\n\n    v = uvector_create_with_size(0, G_NULL());\n    UASSERT_ABORTS(uvector_get_at(v, 1));\n    UASSERT_ABORTS(uvector_set_at(v, 1, G_INT(0)));\n\n    uvector_resize(v, 100, G_NULL());\n    UASSERT_ABORTS(uvector_swap(v, 150, 250));\n    UASSERT_ABORTS(uvector_swap(v, 50, 250));\n    UASSERT_ABORTS(uvector_insert_at(v, 500, G_INT(400)));\n    uvector_destroy(v);\n#endif\n\n}\n\nint cmp(const char *s1, const char *s2)\n{\n    ugeneric_t gv1 = ugeneric_parse(s1);\n    ugeneric_t gv2 = ugeneric_parse(s2);\n    UASSERT_NO_ERROR(gv1);\n    UASSERT_NO_ERROR(gv2);\n    uvector_t *v1 = G_AS_PTR(gv1);\n    uvector_t *v2 = G_AS_PTR(gv2);\n    int diff = uvector_compare(v1, v2);\n    uvector_destroy(v1);\n    uvector_destroy(v2);\n    return diff;\n}\n\nvoid test_uvector_compare(void)\n{\n    uvector_t *v1 = uvector_create();\n    uvector_t *v2 = uvector_create();\n    uvector_append(v1, G_STR(ustring_dup(\"s1\")));\n    uvector_append(v2, G_STR(ustring_dup(\"s1\")));\n    UASSERT(uvector_compare(v1, v2) == 0);\n    uvector_set_at(v1, 0, G_STR(ustring_dup(\"s3\")));\n    UASSERT(uvector_compare(v1, v2) != 0);\n    uvector_set_at(v2, 0, G_STR(ustring_dup(\"s4\")));\n    UASSERT(uvector_compare(v1, v2) < 0);\n    uvector_destroy(v1);\n    uvector_destroy(v2);\n\n    UASSERT(cmp(\"[]\", \"[]\") == 0);\n    UASSERT(cmp(\"[1]\", \"[1]\") == 0);\n    UASSERT(cmp(\"[1, 2, 3]\", \"[1, 2, 3]\") == 0);\n    UASSERT(cmp(\"[1, 2]\", \"[1, 2, 3]\") < 0);\n    UASSERT(cmp(\"[1, 2, 3]\", \"[1, 2]\") > 0);\n    UASSERT(cmp(\"[3, 2, 3]\", \"[1, 2, 3]\") > 0);\n}\n\n/*\ndouble f(double x, void *p)\n{\n    uvector_t *v = p;\n    return G_AS_REAL(uvector_get_at(v, x));\n}\n\nvoid test_gnuplot(void)\n{\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_deriv.h>\n\n    gsl_function F;\n    double result, abserr;\n    #define N 10\n\n    gnuplot_attrs_t a = {\n        .xlabel = \"xlabel\",\n        .ylabel = \"ylabel\",\n        .data_label = \"samples\",\n        .title = \"chart\",\n    };\n\n    uvector_t *v = uvector_create();\n    for (size_t i = 0; i < N; i++)\n    {\n        uvector_append(v, G_REAL(sin(i/50.0)));\n    }\n    uvector_dump_to_gnuplot(v, &a, stdout);\n\n    uvector_t *dv = uvector_create();\n    F.function = &f;\n    F.params = v;\n\n    for (size_t i = 0; i < N; i++)\n    {\n        UASSERT(gsl_deriv_central(&F, (double)i, 1e-8, &result, &abserr) == 0);\n        uvector_append(dv, G_REAL(result));\n    }\n    uvector_dump_to_gnuplot(dv, &a, stdout);\n\n    uvector_destroy(v);\n    uvector_destroy(dv);\n}\n*/\n\nvoid _check_slice(const uvector_t *v, size_t b, size_t e, size_t s, char *exp)\n{\n    uvector_t *slice = uvector_get_slice(v, b, e, s);\n    char *str = uvector_as_str(slice);\n    UASSERT_STR_EQ(str, exp);\n    ufree(str);\n    uvector_destroy(slice);\n}\n\nvoid test_uvector_slice(void)\n{\n    ugeneric_t g = ugeneric_parse(\"[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\");\n    UASSERT_NO_ERROR(g);\n    uvector_t *v = G_AS_PTR(g);\n\n    _check_slice(v, 0, 10, 1, \"[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\");\n    _check_slice(v, 0, 10, 2, \"[1, 3, 5, 7, 9]\");\n    _check_slice(v, 1, 10, 2, \"[2, 4, 6, 8, 10]\");\n    _check_slice(v, 0, 10, 3, \"[1, 4, 7, 10]\");\n    _check_slice(v, 1, 10, 3, \"[2, 5, 8]\");\n    _check_slice(v, 0, 10, 4, \"[1, 5, 9]\");\n    _check_slice(v, 1, 10, 4, \"[2, 6, 10]\");\n    _check_slice(v, 0, 10, 5, \"[1, 6]\");\n    _check_slice(v, 1, 10, 5, \"[2, 7]\");\n    _check_slice(v, 0, 10, 6, \"[1, 7]\");\n    _check_slice(v, 1, 10, 6, \"[2, 8]\");\n    _check_slice(v, 0, 10, 9, \"[1, 10]\");\n    _check_slice(v, 1, 10, 9, \"[2]\");\n    _check_slice(v, 1, 1, 1, \"[]\");\n    _check_slice(v, 1, 1, 5, \"[]\");\n    _check_slice(v, 0, 10, 25, \"[1]\");\n\n    uvector_destroy(v);\n}\n\nvoid test_uvector_data_ownership(void)\n{\n    uvector_t *v = uvector_create();\n    UASSERT(uvector_is_data_owner(v));\n    //uvector_append(v, G_CSTR(\"s1\"));\n    //uvector_append(v, G_CSTR(\"s1\"));\n\n    // shallow copy\n    uvector_t *copy1 = uvector_copy(v);\n    UASSERT(!uvector_is_data_owner(copy1));\n\n    // deep copy\n    uvector_t *copy2 = uvector_deep_copy(v);\n    UASSERT(uvector_is_data_owner(copy2));\n    uvector_drop_data_ownership(copy2);\n    UASSERT(!uvector_is_data_owner(copy2));\n\n    // kick the bucket\n    uvector_destroy(v);\n    uvector_destroy(copy1);\n    uvector_destroy(copy2);\n}\n\nvoid _check_reverse(const char *in, const char *rev)\n{\n    ugeneric_t g = ugeneric_parse(in);\n    UASSERT_NO_ERROR(g);\n    uvector_t *v = G_AS_PTR(g);\n    uvector_reverse(v);\n    char *t = uvector_as_str(v);\n    UASSERT_STR_EQ(t, rev);\n    ufree(t);\n    uvector_destroy(v);\n}\n\nvoid test_uvector_reverse(void)\n{\n    _check_reverse(\"[]\", \"[]\");\n    _check_reverse(\"[1]\", \"[1]\");\n    _check_reverse(\"[1, 2]\", \"[2, 1]\");\n    _check_reverse(\"[1, 2, 3]\", \"[3, 2, 1]\");\n    _check_reverse(\"[1, 2, 3, 4]\", \"[4, 3, 2, 1]\");\n    _check_reverse(\"[1, 2, 3, 4, 5]\", \"[5, 4, 3, 2, 1]\");\n}\n\nint main(int argc, char **argv)\n{\n//    test_gnuplot();\n\n    (void)argv;\n    test_uvector_api();\n    test_uvector_serialization(argc > 1);\n    test_uvector_next_permutation(argc > 1);\n    test_uvector_copy(argc > 1);\n    test_uvector_bsearch();\n    test_uvector_compare();\n    test_uvector_slice();\n    test_uvector_data_ownership();\n    test_uvector_reverse();\n\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "3131b99beca815b130a0d75d10f1091f2fb73c2f", "size": 14234, "ext": "c", "lang": "C", "max_stars_repo_path": "test_vector.c", "max_stars_repo_name": "YauheniKaratsevich/ugeneric", "max_stars_repo_head_hexsha": "e7f83c5e79fa7cec0ed85cbd833515806236e27e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-10-29T10:08:42.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-29T10:08:50.000Z", "max_issues_repo_path": "test_vector.c", "max_issues_repo_name": "YauheniKaratsevich/ugeneric", "max_issues_repo_head_hexsha": "e7f83c5e79fa7cec0ed85cbd833515806236e27e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test_vector.c", "max_forks_repo_name": "YauheniKaratsevich/ugeneric", "max_forks_repo_head_hexsha": "e7f83c5e79fa7cec0ed85cbd833515806236e27e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.156779661, "max_line_length": 136, "alphanum_fraction": 0.6478853449, "num_tokens": 4714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3702253925955866, "lm_q2_score": 0.04084571882888896, "lm_q1q2_score": 0.01512212228927436}}
{"text": "/*\n * The MIT License is a permissive free software license, which permits reuse\n * within both open source and proprietary software. The software is licensed\n * as is, and no warranty is given as to fitness for purpose or absence of\n * infringement of third parties' rights, such as patents. Generally use for\n * research activities is allowed regardless of any third party patents, but\n * commercial use may be subject to a separate license.\n *\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2015 Tuomo Raitio\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *\n *\n *\n * <><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>\n *              GlottHMM Speech Parameter Extractor\n * <><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>\n *\n * This program reads a speech file and extracts speech\n * parameters using glottal inverse filtering.\n *\n * This program has been written in Aalto University,\n * Department of Signal Processign and Acoustics, Espoo, Finland\n *\n * Author: Tuomo Raitio\n * Acknowledgements: Antti Suni, Paavo Alku, Martti Vainio\n *\n * File Analysis.c\n * Version: 1.1\n *\n */\n\n\n\n/***********************************************/\n/*                 INCLUDE                     */\n/***********************************************/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <string.h>\n#include <sndfile.h> \t\t\t\t/* Read and write wav */\n#include <gsl/gsl_vector.h>\t\t/* GSL, Vector */\n#include <gsl/gsl_matrix.h>\t\t/* GSL, Matrix */\n#include <gsl/gsl_fft_real.h>\t\t/* GSL, FFT */\n#include <libconfig.h>\t\t\t\t/* Configuration file */\n#include \"AnalysisFunctions.h\"\n\n\n\n\n\n\n\n/*******************************************************************/\n/*                          MAIN                                   */\n/*******************************************************************/\n\nint main(int argc, char *argv[]) {\n\n\t/* Check command line format */\n\tif(Check_command_line(argc) == EXIT_FAILURE)\n\t\treturn EXIT_FAILURE;\n\n\t/* Read default configuration file and assign parameters */\n\tstruct config_t *conf_def = Read_config(argv[2]);\n\tif(conf_def == NULL)\n\t\treturn EXIT_FAILURE;\n\tPARAM params;\n\tif(Assign_config_parameters(conf_def,&params,DEF_CONF) == EXIT_FAILURE) {\n\t\tconfig_destroy(conf_def);\n\t\tfree(conf_def);\n\t\treturn EXIT_FAILURE;\n\t}\n\n\t/* Read user configuration file and assign parameters */\n\tif(argc == 4) {\n\t\tstruct config_t *conf_usr = Read_config(argv[3]);\n\t\tif(conf_usr == NULL)\n\t\t\treturn EXIT_FAILURE;\n\t\tif(Assign_config_parameters(conf_usr,&params,USR_CONF) == EXIT_FAILURE) {\n\t\t\tconfig_destroy(conf_usr);\n\t\t\tfree(conf_usr);\n\t\t\treturn EXIT_FAILURE;\n\t\t}\n\t}\n\n\t/* Check the validity of the parameters */\n\tif(Check_parameter_validity(&params) == EXIT_FAILURE)\n\t\treturn EXIT_FAILURE;\n\n\t/* Read soundfile, define sampling frequency, invert signal if requested */\n\tgsl_vector *signal = Read_soundfile(argv[1], &params);\n\tif(signal == NULL)\n\t\treturn EXIT_FAILURE;\n\n\t/* Read external F0 file if requested */\n\tgsl_vector *fundf;\n\tif(Read_external_f0(&fundf,&params) == EXIT_FAILURE) {\n\t\tgsl_vector_free(signal);\n\t\treturn EXIT_FAILURE;\n\t}\n\n\t/* High-pass filtering */\n\tif(HighPassFilter(signal,&params) == EXIT_FAILURE) {\n\t\tgsl_vector_free(signal);\n\t\treturn EXIT_FAILURE;\n\t}\n\n\t/*******************************************************************/\n\t/*                    ALLOCATE MEMORY                              */\n\t/*******************************************************************/\n\n\t/* Allocate memory for variables */\n\tint i,j,index;\n\tdouble f0 = 0;\n\tgsl_vector *frame,*frame0,*glottal,*gain,*uvgain,*f0_frame,*glottal_f0,*f0_frame0,*glottsig,*glottsig_f0;\n\tgsl_vector *source_signal,*h1h2,*naq,*ph1h2,*pnaq;\n\tgsl_matrix *fundf_candidates, *LSF, *LSF2, *bp_gain, *spectral_tilt, *HNR, *waveform, *harmonics,\n\t\t\t*fftmatrix_vt, *fftmatrix_src, *fftmatrix_uv;\n\tAllocate_variables(&frame,&frame0,&glottal,&gain,&uvgain,&f0_frame,&glottal_f0,&f0_frame0,&glottsig,\n\t\t\t&glottsig_f0,&source_signal,&fundf_candidates,&LSF,&LSF2,&bp_gain,&spectral_tilt,&HNR,\n\t\t\t&waveform,&harmonics,&h1h2,&naq,&fftmatrix_vt,&fftmatrix_src,&fftmatrix_uv,&params);\n\n\n\t/*******************************************************************/\n\t/*                   ALLOCATE PULSE LIBRARY                        */\n\t/*******************************************************************/\n\n\t/* Allocate memory for pulse library variables */\n\tgsl_vector *pulse_inds,*pulse_lengths,*pulse_pos,*pgain;\n\tgsl_matrix *gpulses,*gpulses_rs,*plsf,*ptilt,*pharm,*phnr,*pwaveform;\n\tAllocate_pulselib_variables(&gpulses,&gpulses_rs,&pulse_inds,&pulse_pos,&pulse_lengths,\n\t\t\t&plsf,&ptilt,&pharm,&phnr,&pwaveform,&pgain,&ph1h2,&pnaq,&params);\n\n\n\t/********************************************************************/\n\t/*                    EXTRACT PARAMETERS                            */\n\t/********************************************************************/\n\n\t/* Analysis: Start reading signal vector */\n\tfor(index=0; index<params.n_frames; index++) {\n\n\t\t/* Print progress */\n\t\tPrint_progress(index,params.n_frames,argv[1],params.FS);\n\n\t\t/* Get samples to frames */\n\t\tGet_samples_to_frames(signal,frame,frame0,f0_frame,f0_frame0,params.shift,index);\n\n\t\t/* Gain extraction */\n\t\tGain(frame, gain, index, USE_WINDOWING);\n\t\tUnvoicedGain(frame, uvgain, index, USE_WINDOWING, params.unvoiced_frame_length);\n\t\tBandPassGain(frame, bp_gain, &params, index);\n\n\t\t/* Preliminary inverse filtering for GCI detection (e.g. in GCI-weighted SWLP) */\n\t\tif(params.lp_method == LP_METHOD_ID_WLP && params.lp_weighting == LP_WEIGHTING_ID_GCI) {\n\t\t\tInverseFiltering_long(f0_frame, f0_frame0, glottsig_f0, fundf, glottsig, index, &params);\n\t\t\tFundF(glottsig_f0, frame, fundf_candidates, fundf, bp_gain, index, &params);\n\t\t\tInverseFiltering_long(frame, frame0, glottsig, fundf, glottsig, index, &params);\n\t\t}\n\n\t\t/* Inverse filtering */\n\t\tInverseFiltering(frame, frame0, glottal, LSF, LSF2, spectral_tilt, fundf, glottsig, fftmatrix_vt,\n\t\t\t\tfftmatrix_src, fftmatrix_uv, index, &params);\n\t\tInverseFiltering_long(f0_frame, f0_frame0, glottal_f0, fundf, glottsig_f0, index, &params);\n\n\t\t/* Fundamental frequency estimation. Define a f0 value for the frame (even if unvoiced) */\n\t\tFundF(glottal_f0, frame, fundf_candidates, fundf, bp_gain, index, &params);\n\t\tf0 = Define_current_f0(fundf,f0,index);\n\n\t\t/* Estimate Harmonic-to-Noise Ratio (HNR) and magnitudes of the first N harmonics */\n\t\tHarmonic_analysis(glottal_f0, harmonics, HNR, h1h2, f0, params.FS, index);\n\n\t\t/* Extract pulses, pitch-synchronous spectrum estimation */\n\t\tExtract_pulses(f0_frame,glottal_f0,fundf,naq,gpulses,gpulses_rs,pulse_pos,pulse_inds,pulse_lengths,\n\t\t\t\tplsf,ptilt,pharm,phnr,pgain,ph1h2,pnaq,LSF,spectral_tilt,harmonics,h1h2,HNR,gain,pwaveform,waveform,index,&params);\n\n\t\t/* Construct source signal */\n\t\tConstruct_source(source_signal, glottal, glottal_f0, index, &params);\n\t}\n\n\n\t/********************************************************************/\n\t/*                POSTPROCESSING OF PARAMETERS                      */\n\t/********************************************************************/\n\n\t/* Add missing frames to the beginning and the end of parameter vectors/matrices.\n\t * This is due to the analysis scheme, where the analysis starts\n\t * and ends with whole frames instead of zero-padding */\n\tAdd_missing_frames(&fundf,&fundf_candidates,&gain,&uvgain,&HNR,&spectral_tilt,&LSF,&LSF2,&harmonics,&waveform,&naq,&h1h2,\n\t\t\t&fftmatrix_vt,&fftmatrix_src,&fftmatrix_uv,&params);\n\n\t/* Postprocess F0 */\n\tF0_postprocess(fundf,fundf_candidates,&params);\n\n\t/* Median filtering */\n\tMedFilt5_matrix(HNR);\n\tMedFilt5_matrix(harmonics);\n\tMedFilt5(h1h2);\n\tMedFilt5(naq);\n\n\t/* Replace unvoiced fetures */\n\tfor(i=0; i<fundf->size; i++) {\n\t\tif(gsl_vector_get(fundf, i) == 0) {\n\t\t\tif(params.sep_vuv_spectrum == 0) {\n\t\t\t\tfor(j=0; j<params.lpc_order_vt; j++)\n\t\t\t\t\tgsl_matrix_set(LSF, i, j, gsl_matrix_get(LSF2, i, j));\n\t\t\t}\n\t\t\tfor(j=0; j<fftmatrix_vt->size2; j++)\n\t\t\t\tgsl_matrix_set(fftmatrix_vt, i, j, gsl_matrix_get(fftmatrix_uv, i, j));\n\t\t\tgsl_vector_set(gain,i,gsl_vector_get(uvgain,i));\n\t\t}\n\t}\n\n\t/* Noise reduction */\n\tNoise_reduction(gain,&params);\n\n\t/* Fill possible gaps in waveform and NAQ */\n\tFill_waveform_gaps(fundf,waveform);\n\tFill_naq_gaps(fundf,naq);\n\n\t/* Select new values to pulse parameters according to refined parameters */\n\tSelect_new_refined_values(fundf,gain,LSF,spectral_tilt,HNR,harmonics,pgain,plsf,ptilt,\n\t\t\tphnr,pharm,pulse_pos,pulse_lengths,waveform,h1h2,ph1h2,naq,pnaq,&params);\n\n\t/* Select only unique pulses */\n\tSelect_unique_pulses(&gpulses,&gpulses_rs,&pulse_lengths,&pulse_pos,&pulse_inds,&plsf,\n\t\t\t&ptilt,&phnr,&pharm,&pwaveform,&pgain,&ph1h2,&pnaq,&params);\n\n\t/* Select only one pulse per frame */\n\tSelect_one_pulse_per_frame(&gpulses,&gpulses_rs,&pulse_lengths,&pulse_pos,&pulse_inds,&plsf,\n\t\t\t\t&ptilt,&phnr,&pharm,&pwaveform,&pgain,&ph1h2,&pnaq,&params);\n\n\n\t/********************************************************************/\n\t/*                      FORMANT ENHANCEMENT                         */\n\t/********************************************************************/\n\n\t/* Formant enhancement by LSFs*/\n\tif(params.formant_enh_method == FORMANT_ENH_ID_LSF)\n\t\tLSF_Postfilter(LSF, &params);\n\n\t/* Formant Enhancement by re-estimating LPC and modifying the autocorrelation */\n\tif(params.formant_enh_method == FORMANT_ENH_ID_LPC)\n\t\tLPC_Postfilter(LSF, &params);\n\n\t/* Differentiate LSFs if requested */\n\tif(params.differential_lsf == 1) {\n\t\tDifferentiate_LSFs(&LSF);\n\t\tDifferentiate_LSFs(&LSF2);\n\t\tDifferentiate_LSFs(&spectral_tilt);\n\t}\n\n\t/* Convert F0 to logarithmic scale */\n\tConvert_F0_to_log(fundf,&params);\n\n\n\t/********************************************************************/\n\t/*                    WRITE PARAMETERS TO FILE                      */\n\t/********************************************************************/\n\n\t/* Open files for writing parameters, free memory */\n\tWrite_parameters_to_file(argv[1],LSF,LSF2,spectral_tilt,HNR,harmonics,waveform,fundf,gain,h1h2,naq,source_signal,\n\t\t\tfftmatrix_vt,fftmatrix_src,&params);\n\tFree_variables(frame,frame0,signal,glottal,glottsig,glottsig_f0,uvgain,f0_frame,f0_frame0,glottal_f0,bp_gain,\n\t\t\tfundf_candidates,fftmatrix_uv);\n\n\n\t/**************************************************************/\n\t/*            WRITE  PULSE LIBRARY TO FILE                    */\n\t/**************************************************************/\n\n\t/* Select unique pulses and write pulse library data to file, free memory */\n\tWrite_pulselibrary_to_file(argv[1],gpulses,gpulses_rs,pulse_lengths,pulse_pos,pulse_inds,plsf,\n\t\t\tptilt,phnr,pharm,pwaveform,pgain,ph1h2,pnaq,&params);\n\n\t/* Finish */\n\tprintf(\"\\nFinished analysis.\\n\\n\");\n\treturn EXIT_SUCCESS;\n}\n\n/***********/\n/*   EOF   */\n/***********/\n\n", "meta": {"hexsha": "55c7460de87ca4d2ca24be8d50a6a3aa64187801", "size": 11767, "ext": "c", "lang": "C", "max_stars_repo_path": "src/Analysis.c", "max_stars_repo_name": "mjansche/GlottHMM", "max_stars_repo_head_hexsha": "4dfe5eb0b6dacc227299acc29c6df8b030de82b8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2016-06-29T22:08:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-03T12:46:50.000Z", "max_issues_repo_path": "src/Analysis.c", "max_issues_repo_name": "mjansche/GlottHMM", "max_issues_repo_head_hexsha": "4dfe5eb0b6dacc227299acc29c6df8b030de82b8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Analysis.c", "max_forks_repo_name": "mjansche/GlottHMM", "max_forks_repo_head_hexsha": "4dfe5eb0b6dacc227299acc29c6df8b030de82b8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2016-08-03T12:08:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T09:17:33.000Z", "avg_line_length": 38.328990228, "max_line_length": 122, "alphanum_fraction": 0.6276876009, "num_tokens": 3062, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.03161876487328601, "lm_q1q2_score": 0.01506885993037506}}
{"text": "/*\n * Copyright 2020 Makani Technologies LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#ifndef SIM_MATH_LINALG_H_\n#define SIM_MATH_LINALG_H_\n\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_vector.h>\n#include <stdint.h>\n\n// We use GSL style conventions here to maintain consistency with the\n// GSL library.  See GSL docs for comment.\n\n#define GSL_VECTOR_STACK_ALLOC(v_, size_)                               \\\n  double v_##_data[size_];                                              \\\n  gsl_block v_##_block = {size_, v_##_data};                            \\\n  gsl_vector v_##_vector = {size_, 1, v_##_block.data, &v_##_block, 0}; \\\n  gsl_vector *v_ = &v_##_vector;\n\n#define GSL_MATRIX_STACK_ALLOC(m_, size1_, size2_)                \\\n  double m_##_data[(size1_) * (size2_)];                          \\\n  gsl_block m_##_block = {(size1_) * (size2_), m_##_data};        \\\n  gsl_matrix m_##_matrix = {size1_,          size2_,      size2_, \\\n                            m_##_block.data, &m_##_block, 0};     \\\n  gsl_matrix *m_ = &m_##_matrix;\n\ndouble gsl_matrix_trace(const gsl_matrix *m);\nconst gsl_vector *gsl_matrix_diag(const gsl_matrix *m, gsl_vector *d);\nvoid gsl_matrix_disp(const gsl_matrix *m);\nvoid gsl_vector_disp(const gsl_vector *v);\nconst gsl_vector *gsl_vector_saturate(const gsl_vector *x, double low,\n                                      double high, gsl_vector *y);\ndouble gsl_vector_norm_bound(const gsl_vector *x, double low);\ndouble gsl_vector_dot(const gsl_vector *x, const gsl_vector *y);\n\n#endif  // SIM_MATH_LINALG_H_\n", "meta": {"hexsha": "8f904ef9fd45bb38729dc2dc5eadc199c791b3ff", "size": 2059, "ext": "h", "lang": "C", "max_stars_repo_path": "sim/math/linalg.h", "max_stars_repo_name": "leozz37/makani", "max_stars_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1178.0, "max_stars_repo_stars_event_min_datetime": "2020-09-10T17:15:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:59:35.000Z", "max_issues_repo_path": "sim/math/linalg.h", "max_issues_repo_name": "leozz37/makani", "max_issues_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-22T05:22:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-22T05:22:35.000Z", "max_forks_repo_path": "sim/math/linalg.h", "max_forks_repo_name": "leozz37/makani", "max_forks_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 107.0, "max_forks_repo_forks_event_min_datetime": "2020-09-10T17:29:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T09:00:14.000Z", "avg_line_length": 41.18, "max_line_length": 75, "alphanum_fraction": 0.6522583779, "num_tokens": 504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.0321007091476681, "lm_q1q2_score": 0.015048511556482123}}
{"text": "/*\n * optimize_tnc.h\n *\n *  Created on: Feb 9, 2010\n *      Author: smitty\n */\n\n#ifndef _OPTIMIZE_STATE_RECONSTRUCTOR_NLOPT_H_\n#define _OPTIMIZE_STATE_RECONSTRUCTOR_NLOPT_H_\n\n#include <nlopt.h>\n\n#include \"state_reconstructor.h\"\n#include \"rate_model.h\"\n\n#include <armadillo>\nusing namespace arma;\n\nvoid optimize_sr_nlopt(RateModel * _rm,StateReconstructor * _sr, mat * _free_mask, int _nfree);\n\n#endif /* _OPTIMIZE_STATE_RECONSTRUCTOR_NLOPT_H_ */\n", "meta": {"hexsha": "b84de327334f48c99a7363d1b286b27a28dd3a3d", "size": 446, "ext": "h", "lang": "C", "max_stars_repo_path": "src/phyx-1.01/src/optimize_state_reconstructor_nlopt.h", "max_stars_repo_name": "jlanga/smsk_selection", "max_stars_repo_head_hexsha": "08070c6d4a6fbd9320265e1e698c95ba80f81123", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-07-18T05:20:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T10:22:33.000Z", "max_issues_repo_path": "src/phyx-1.01/src/optimize_state_reconstructor_nlopt.h", "max_issues_repo_name": "jlanga/smsk_selection", "max_issues_repo_head_hexsha": "08070c6d4a6fbd9320265e1e698c95ba80f81123", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-08-21T07:26:13.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-08T13:59:48.000Z", "max_forks_repo_path": "src/phyx-1.01/src/optimize_state_reconstructor_nlopt.h", "max_forks_repo_name": "jlanga/smsk_orthofinder", "max_forks_repo_head_hexsha": "08070c6d4a6fbd9320265e1e698c95ba80f81123", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-07-18T05:20:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:23:31.000Z", "avg_line_length": 20.2727272727, "max_line_length": 95, "alphanum_fraction": 0.764573991, "num_tokens": 128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3738758227716966, "lm_q2_score": 0.04023794305521531, "lm_q1q2_score": 0.0150439940664093}}
{"text": "/*\nCopyright 2016, D. E. Shaw Research.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n* Redistributions of source code must retain the above copyright\n  notice, this list of conditions, and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright\n  notice, this list of conditions, and the following disclaimer in the\n  documentation and/or other materials provided with the distribution.\n\n* Neither the name of D. E. Shaw Research nor the names of its\n  contributors may be used to endorse or promote products derived from\n  this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n#ifdef __GNUC__\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wfloat-equal\"\n#pragma GCC diagnostic ignored \"-Wconversion\"\n#endif\n\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wexpansion-to-defined\"\n#pragma clang diagnostic ignored \"-Wreserved-id-macro\"\n#endif\n\n#ifdef _MSC_FULL_VER\n// 4311 - 'type cast': pointer truncation from 'char[54]' to 'long'\n// 4202 - nonstandard extension used: non-constant aggregate initializer\n// 4127 - conditional expression is constant\n// 4302 - 'type cast': truncation from 'const char *' to 'long'\n#pragma warning(push)\n#pragma warning(disable : 4311 4204 4127 4302)\n#endif\n\n#include \"rng/config.h\"\n\n#include \"Random123/conventional/gsl_cbrng.h\"\n#include \"ut_gsl.h\"\n#include <assert.h>\n#include <gsl/gsl_randist.h>\n#include <stdio.h>\n\n/* Exercise the GSL_CBRNG macro */\n\nGSL_CBRNG(cbrng, threefry4x64); /* creates gsl_rng_cbrng */\n\nint main(int argc, char **argv) {\n  int i;\n  gsl_rng *r;\n  gsl_rng *rcopy;\n  unsigned long x;\n  rngRemember(unsigned long save);\n  rngRemember(unsigned long saved[5]);\n  double sum = 0.;\n  (void)argc;\n  (void)argv; /* unused */\n\n  /* Silence an unused-parameter warning. */\n  (void)argc;\n\n  r = gsl_rng_alloc(gsl_rng_cbrng);\n  assert(gsl_rng_min(r) == 0);\n  assert(gsl_rng_max(r) == 0xffffffffUL); /* Not necessarily ~0UL */\n  assert(gsl_rng_size(r) > 0);\n\n  printf(\"%s\\nulongs from %s in initial state\\n\", argv[0], gsl_rng_name(r));\n  for (i = 0; i < 5; i++) {\n    x = gsl_rng_get(r);\n    rngRemember(saved[i] = x);\n    printf(\"%d: 0x%lx\\n\", i, x);\n    assert(x != 0);\n  }\n  printf(\"uniforms from %s\\n\", gsl_rng_name(r));\n  for (i = 0; i < 5; i++) {\n    double z = gsl_rng_uniform(r);\n    sum += z;\n    printf(\"%d: %.4g\\n\", i, z);\n  }\n  assert(sum < 0.9 * 5 && sum > 0.1 * 5 &&\n         (long)\"sum must be reasonably close  to 0.5*number of trials\");\n  rngRemember(save =) gsl_rng_get(r);\n\n  gsl_rng_set(r, 0xdeadbeef); /* set a non-zero seed */\n  printf(\"ulongs from %s after seed\\n\", gsl_rng_name(r));\n  for (i = 0; i < 5; i++) {\n    x = gsl_rng_get(r);\n    printf(\"%d: 0x%lx\\n\", i, x);\n    assert(x != 0);\n  }\n  /* make a copy of the total state */\n  rcopy = gsl_rng_alloc(gsl_rng_cbrng);\n  gsl_rng_memcpy(rcopy, r);\n  printf(\"uniforms from %s\\n\", gsl_rng_name(r));\n  sum = 0.;\n  for (i = 0; i < 5; i++) {\n    double x2 = gsl_rng_uniform(r);\n    rngRemember(double y = gsl_rng_uniform(rcopy));\n    printf(\"%d: %.4g\\n\", i, x2);\n    sum += x2;\n    assert(x2 == y);\n  }\n  assert(gsl_rng_get(r) != save);\n  assert(sum < 0.9 * 5 && sum > 0.1 * 5 &&\n         (long)\"sum must be reasonably close  to 0.5*number of trials\");\n\n  /* gsl_rng_set(*, 0) is supposed to recover the default seed */\n  gsl_rng_set(r, 0);\n  printf(\"ulongs from %s after restore to initial\\n\", gsl_rng_name(r));\n  for (i = 0; i < 5; i++) {\n    x = gsl_rng_get(r);\n    assert(x == saved[i]);\n    printf(\"%d: 0x%lx\\n\", i, x);\n    assert(x != 0);\n  }\n  printf(\"uniforms from %s\\n\", gsl_rng_name(r));\n  for (i = 0; i < 5; i++) {\n    printf(\"%d: %.4g\\n\", i, gsl_rng_uniform(r));\n  }\n\n  gsl_rng_free(rcopy);\n  gsl_rng_free(r);\n\n  printf(\"ut_gsl: OK\\n\");\n  return 0;\n}\n\n#ifdef _MSC_FULL_VER\n#pragma warning(pop)\n#endif\n\n#ifdef __clang__\n// Restore clang diagnostics to previous state.\n#pragma clang diagnostic pop\n#endif\n\n#ifdef __GNUC__\n// Restore GCC diagnostics to previous state.\n#pragma GCC diagnostic pop\n#endif\n", "meta": {"hexsha": "6475d484be524997ca13d1e46e7b2a7beed44163", "size": 4899, "ext": "c", "lang": "C", "max_stars_repo_path": "src/rng/test/ut_gsl.c", "max_stars_repo_name": "jhchang-lanl/Draco", "max_stars_repo_head_hexsha": "b8e3bcd38ab739615c1df506268d70bf99929efa", "max_stars_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_stars_count": 43.0, "max_stars_repo_stars_event_min_datetime": "2017-02-17T23:47:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T07:53:43.000Z", "max_issues_repo_path": "src/rng/test/ut_gsl.c", "max_issues_repo_name": "jhchang-lanl/Draco", "max_issues_repo_head_hexsha": "b8e3bcd38ab739615c1df506268d70bf99929efa", "max_issues_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_issues_count": 848.0, "max_issues_repo_issues_event_min_datetime": "2017-01-16T01:03:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-11T18:56:50.000Z", "max_forks_repo_path": "src/rng/test/ut_gsl.c", "max_forks_repo_name": "jhchang-lanl/Draco", "max_forks_repo_head_hexsha": "b8e3bcd38ab739615c1df506268d70bf99929efa", "max_forks_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_forks_count": 31.0, "max_forks_repo_forks_event_min_datetime": "2017-03-02T19:51:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-08T02:33:34.000Z", "avg_line_length": 30.8113207547, "max_line_length": 76, "alphanum_fraction": 0.6901408451, "num_tokens": 1370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34158249943831703, "lm_q2_score": 0.044018653468517875, "lm_q1q2_score": 0.01503600167368548}}
{"text": "#ifndef matops_h\n#define matops_h\n\n#include <ceed.h>\n#include <petsc.h>\n#include <petscdmplex.h>\n\n#include \"structs.h\"\n\nPetscErrorCode MatGetDiag(Mat A, Vec D);\nPetscErrorCode ApplyLocal_Ceed(Vec X, Vec Y, UserO user);\nPetscErrorCode MatMult_Ceed(Mat A, Vec X, Vec Y);\nPetscErrorCode FormResidual_Ceed(SNES snes, Vec X, Vec Y, void *ctx);\nPetscErrorCode MatMult_Prolong(Mat A, Vec X, Vec Y);\nPetscErrorCode MatMult_Restrict(Mat A, Vec X, Vec Y);\nPetscErrorCode ComputeErrorMax(UserO user, CeedOperator op_error,\n                               Vec X, CeedVector target, PetscReal *max_error);\n\n#endif // matops_h\n", "meta": {"hexsha": "fa416e730e006952e3e7f4f0f77e00b7b1d62132", "size": 612, "ext": "h", "lang": "C", "max_stars_repo_path": "examples/petsc/include/matops.h", "max_stars_repo_name": "AdelekeBankole/libCEED", "max_stars_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 123.0, "max_stars_repo_stars_event_min_datetime": "2018-01-29T02:04:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T18:13:48.000Z", "max_issues_repo_path": "examples/petsc/include/matops.h", "max_issues_repo_name": "AdelekeBankole/libCEED", "max_issues_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 781.0, "max_issues_repo_issues_event_min_datetime": "2017-12-22T17:20:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T21:34:34.000Z", "max_forks_repo_path": "examples/petsc/include/matops.h", "max_forks_repo_name": "AdelekeBankole/libCEED", "max_forks_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2017-12-27T22:35:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:02:07.000Z", "avg_line_length": 30.6, "max_line_length": 79, "alphanum_fraction": 0.7336601307, "num_tokens": 175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.032589746410320634, "lm_q1q2_score": 0.015024419928691128}}
{"text": "/* histogram/gsl_histogram.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_HISTOGRAM_H__\n#define __GSL_HISTOGRAM_H__\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <gsl/gsl_types.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct {\n  size_t n ;\n  double * range ;\n  double * bin ;\n} gsl_histogram ;\n\ntypedef struct {\n  size_t n ;\n  double * range ;\n  double * sum ;\n} gsl_histogram_pdf ;\n\nGSL_EXPORT gsl_histogram * gsl_histogram_alloc (size_t n);\n\nGSL_EXPORT gsl_histogram * gsl_histogram_calloc (size_t n);\nGSL_EXPORT gsl_histogram * gsl_histogram_calloc_uniform (const size_t n, const double xmin, const double xmax);\nGSL_EXPORT void gsl_histogram_free (gsl_histogram * h);\nGSL_EXPORT int gsl_histogram_increment (gsl_histogram * h, double x);\nGSL_EXPORT int gsl_histogram_accumulate (gsl_histogram * h, double x, double weight);\nGSL_EXPORT int gsl_histogram_find (const gsl_histogram * h,\n                                   const double x, size_t * i);\n  \nGSL_EXPORT double gsl_histogram_get (const gsl_histogram * h, size_t i);\nGSL_EXPORT int gsl_histogram_get_range (const gsl_histogram * h, size_t i,\n                                        double * lower, double * upper);\n\nGSL_EXPORT double gsl_histogram_max (const gsl_histogram * h);\nGSL_EXPORT double gsl_histogram_min (const gsl_histogram * h);\nGSL_EXPORT size_t gsl_histogram_bins (const gsl_histogram * h);\n\nGSL_EXPORT void gsl_histogram_reset (gsl_histogram * h);\n\nGSL_EXPORT gsl_histogram * gsl_histogram_calloc_range(size_t n, double * range);\n\nGSL_EXPORT \nint\ngsl_histogram_set_ranges (gsl_histogram * h, const double range[], size_t size);\nGSL_EXPORT\nint\ngsl_histogram_set_ranges_uniform (gsl_histogram * h, double xmin, double xmax);\n\n\nGSL_EXPORT\nint\ngsl_histogram_memcpy(gsl_histogram * dest, const gsl_histogram * source);\n\nGSL_EXPORT \ngsl_histogram *\ngsl_histogram_clone(const gsl_histogram * source);\n\nGSL_EXPORT double gsl_histogram_max_val (const gsl_histogram * h);\n\nGSL_EXPORT size_t gsl_histogram_max_bin (const gsl_histogram * h);\n\nGSL_EXPORT double gsl_histogram_min_val (const gsl_histogram * h);\n\nGSL_EXPORT size_t gsl_histogram_min_bin (const gsl_histogram * h);\n\nGSL_EXPORT\nint\ngsl_histogram_equal_bins_p(const gsl_histogram *h1, const gsl_histogram *h2);\n\nGSL_EXPORT\nint\ngsl_histogram_add(gsl_histogram *h1, const gsl_histogram *h2);\n\nGSL_EXPORT\nint\ngsl_histogram_sub(gsl_histogram *h1, const gsl_histogram *h2);\n\nGSL_EXPORT\nint\ngsl_histogram_mul(gsl_histogram *h1, const gsl_histogram *h2);\n\nGSL_EXPORT\nint\ngsl_histogram_div(gsl_histogram *h1, const gsl_histogram *h2);\n\nGSL_EXPORT\nint\ngsl_histogram_scale(gsl_histogram *h, double scale);\n\nGSL_EXPORT\nint\ngsl_histogram_shift (gsl_histogram * h, double shift);\n\n\nGSL_EXPORT double gsl_histogram_sigma (const gsl_histogram * h);\n\nGSL_EXPORT double gsl_histogram_mean (const gsl_histogram * h);\n\nGSL_EXPORT double gsl_histogram_sum (const gsl_histogram * h);\n\nGSL_EXPORT int gsl_histogram_fwrite (FILE * stream, const gsl_histogram * h) ;\nGSL_EXPORT int gsl_histogram_fread (FILE * stream, gsl_histogram * h);\nGSL_EXPORT int gsl_histogram_fprintf (FILE * stream, const gsl_histogram * h,\n                                      const char * range_format, const char * bin_format);\nGSL_EXPORT int gsl_histogram_fscanf (FILE * stream, gsl_histogram * h);\n\nGSL_EXPORT gsl_histogram_pdf * gsl_histogram_pdf_alloc (const size_t n);\nGSL_EXPORT int gsl_histogram_pdf_init (gsl_histogram_pdf * p, const gsl_histogram * h);\nGSL_EXPORT void gsl_histogram_pdf_free (gsl_histogram_pdf * p);\nGSL_EXPORT double gsl_histogram_pdf_sample (const gsl_histogram_pdf * p, double r);\n\n__END_DECLS\n\n#endif /* __GSL_HISTOGRAM_H__ */\n", "meta": {"hexsha": "ffb16611586678b80cd067e605199c3a3609ae8b", "size": 4587, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/gsl/include/gsl/gsl_histogram.h", "max_stars_repo_name": "dynaryu/vaws", "max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/gsl/include/gsl/gsl_histogram.h", "max_issues_repo_name": "dynaryu/vaws", "max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/gsl/include/gsl/gsl_histogram.h", "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4178082192, "max_line_length": 111, "alphanum_fraction": 0.7684761282, "num_tokens": 1129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334000459302, "lm_q2_score": 0.03676946211738795, "lm_q1q2_score": 0.014977430022135661}}
{"text": "/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*\n**                                                                                  **\n** This file forms part of the Underworld geophysics modelling application.         **\n**                                                                                  **\n** For full license and copyright information, please refer to the LICENSE.md file  **\n** located at the project root, or contact the authors.                             **\n**                                                                                  **\n**~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/\n#include <petsc.h>\n#include <petscvec.h>\n#include <petscmat.h>\n\n#include <StGermain/libStGermain/src/StGermain.h>\n#include <StgDomain/libStgDomain/src/StgDomain.h>\n\n#include \"common-driver-utils.h\"\n\n\n/*\nname[] is operator name\n*/\nPetscErrorCode BSSCR_MatInfoLog(PetscViewer v,Mat A,const char name[])\n{\n\tMatInfo i;\n\tPetscReal nrm_1,nrm_f,nrm_inf;\n\tMatType mtype;\n\tPetscInt M,N;\n\tPetscViewerType vtype;\n\tPetscTruth isascii;\n\t\n\tPetscViewerGetType( v, &vtype );\n\tStg_PetscObjectTypeCompare( (PetscObject)v,PETSC_VIEWER_ASCII,&isascii );\n\tif (!isascii) { PetscFunctionReturn(0); }\n\t\n\tMatGetSize( A, &M,&N );\n\tMatGetInfo(A,MAT_GLOBAL_SUM,&i);\n\t\n\tMatGetType( A, &mtype );\n\tMatNorm( A, NORM_1, &nrm_1 );\n\tMatNorm( A, NORM_FROBENIUS, &nrm_f );\n\tMatNorm( A, NORM_INFINITY, &nrm_inf );\n\t\n\tPetscViewerASCIIPrintf( v, \"MatInfo: %s \\n\", name );\n\tPetscViewerASCIIPushTab(v);\n\t\n\tPetscViewerASCIIPrintf( v, \"type=%s \\n\", mtype );\n\tPetscViewerASCIIPrintf( v, \"dimension=%Dx%D \\n\", M,N );\n\tPetscViewerASCIIPrintf( v, \"nnz=%D (total)\\n\", (PetscInt)i.nz_used );\n\tPetscViewerASCIIPrintf( v, \"nnz=%D (allocated)\\n\", (PetscInt)i.nz_allocated );\n\tPetscViewerASCIIPrintf( v, \"|A|_1         = %1.12e\\n\", nrm_1 );\n\tPetscViewerASCIIPrintf( v, \"|A|_frobenius = %1.12e\\n\", nrm_f );\n\tPetscViewerASCIIPrintf( v, \"|A|_inf       = %1.12e\\n\", nrm_inf );\n\t\n\tPetscViewerASCIIPopTab(v);\n\t\n\tPetscFunctionReturn(0);\n}\n\n/*\nname[] is operator name\n*/\nPetscErrorCode BSSCR_VecInfoLog(PetscViewer v,Vec x,const char name[])\n{\n\tPetscReal nrm_1,nrm_f,nrm_inf;\n\tVecType vectype;\n\tPetscInt M;\n\tPetscViewerType vtype;\n\tPetscTruth isascii;\n\t\n\tPetscViewerGetType( v, &vtype );\n\tStg_PetscObjectTypeCompare( (PetscObject)v,PETSC_VIEWER_ASCII,&isascii );\n\tif (!isascii) { PetscFunctionReturn(0); }\n\t\n\tVecGetSize( x, &M);\n\t\n\tVecGetType( x, &vectype );\n\tVecNorm( x, NORM_1, &nrm_1 );\n\tVecNorm( x, NORM_2, &nrm_f );\n\tVecNorm( x, NORM_INFINITY, &nrm_inf );\n\t\n\tPetscViewerASCIIPrintf( v, \"VecInfo: %s \\n\", name );\n\tPetscViewerASCIIPushTab(v);\n\t\n\tPetscViewerASCIIPrintf( v, \"type=%s \\n\", vectype );\n\tPetscViewerASCIIPrintf( v, \"dimension=%Dx1 \\n\", M);\n\tPetscViewerASCIIPrintf( v, \"|x|_1   = %1.12e\\n\", nrm_1 );\n\tPetscViewerASCIIPrintf( v, \"|x|_2   = %1.12e\\n\", nrm_f );\n\tPetscViewerASCIIPrintf( v, \"|x|_inf = %1.12e\\n\", nrm_inf );\n\t\n\tPetscViewerASCIIPopTab(v);\n\t\n\tPetscFunctionReturn(0);\n}\n\n\nPetscErrorCode BSSCR_StokesCreateOperatorSummary( Mat K, Mat G, Mat C, Vec f, Vec h, const char filename[] )\n{\n\tMPI_Comm comm;\n\tPetscViewer v;\n\tchar op_name[PETSC_MAX_PATH_LEN];\t\n\tPetscTruth flg;\n\t\n\tPetscObjectGetComm( (PetscObject)K, &comm );\n\tPetscViewerASCIIOpen( comm, filename, &v );\n\t\n\tBSSCR_GeneratePetscHeader_for_viewer( v );\n\tPetscViewerASCIIPrintf( v, \"\\nInput matrices:\\n\");\n\tPetscViewerASCIIPushTab(v);\n\t\n\tPetscOptionsGetString( PETSC_NULL,\"-stokes_A11\",op_name,PETSC_MAX_PATH_LEN-1,&flg );\n\tif (flg) {\tPetscViewerASCIIPrintf( v, \"A11: %s\\n\", op_name );\t}\n\t\n\tPetscOptionsGetString( PETSC_NULL,\"-stokes_A12\",op_name,PETSC_MAX_PATH_LEN-1,&flg );\n\tif (flg) {\tPetscViewerASCIIPrintf( v, \"A12: %s\\n\", op_name );\t}\n\t\n\tPetscOptionsGetString( PETSC_NULL,\"-stokes_A22\",op_name,PETSC_MAX_PATH_LEN-1,&flg );\n\tif (flg) {\tPetscViewerASCIIPrintf( v, \"A22: %s\\n\", op_name );\t}\n\t\n\tPetscOptionsGetString( PETSC_NULL,\"-stokes_Smat\",op_name,PETSC_MAX_PATH_LEN-1,&flg );\n\tif (flg) {\tPetscViewerASCIIPrintf( v, \"Smat: %s\\n\", op_name );\t}\n\t\n\tPetscOptionsGetString( PETSC_NULL,\"-stokes_b1\",op_name,PETSC_MAX_PATH_LEN-1,&flg );\n\tif (flg) {\tPetscViewerASCIIPrintf( v, \"b1: %s\\n\", op_name );\t}\n\t\n\tPetscOptionsGetString( PETSC_NULL,\"-stokes_b2\",op_name,PETSC_MAX_PATH_LEN-1,&flg );\n\tif (flg) {\tPetscViewerASCIIPrintf( v, \"b2: %s\\n\", op_name );\t}\n\t\n\tPetscViewerASCIIPopTab(v);\n\tPetscViewerASCIIPrintf( v, \"\\n\");\n\t\n\tBSSCR_MatInfoLog(v,K,\"stokes_A11\");\t\t\tPetscViewerASCIIPrintf( v, \"\\n\");\n\t\n\tBSSCR_MatInfoLog(v,G,\"stokes_A12\");\t\t\tPetscViewerASCIIPrintf( v, \"\\n\");\n\tif (C) { BSSCR_MatInfoLog(v,C,\"stokes_A22\"); \t\tPetscViewerASCIIPrintf( v, \"\\n\");\t}\t\n\t\n\tBSSCR_VecInfoLog(v,f,\"stokes_b1\");\t\t\tPetscViewerASCIIPrintf( v, \"\\n\");\n\tBSSCR_VecInfoLog(v,h,\"stokes_b2\");\t\t\tPetscViewerASCIIPrintf( v, \"\\n\");\n\t\n\tStg_PetscViewerDestroy(&v );\n\t\n\tPetscFunctionReturn(0);\n}\n", "meta": {"hexsha": "a6193dc64ebd38cc60b64bf41d4917c2ab45688e", "size": 4868, "ext": "c", "lang": "C", "max_stars_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/operator_summary.c", "max_stars_repo_name": "rbeucher/underworld2", "max_stars_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/operator_summary.c", "max_issues_repo_name": "rbeucher/underworld2", "max_issues_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/operator_summary.c", "max_forks_repo_name": "rbeucher/underworld2", "max_forks_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.041958042, "max_line_length": 108, "alphanum_fraction": 0.642358258, "num_tokens": 1853, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658973632215985, "lm_q2_score": 0.04084571649373723, "lm_q1q2_score": 0.014973620439328827}}
{"text": "/*\n This file is part of the Princeton FCMA Toolbox\n Copyright (c) 2013 the authors (see AUTHORS file)\n For license terms, please see the LICENSE file.\n*/\n\n#ifndef COMMON_H\n#define COMMON_H\n\n#include <vector>\n#include <map>\n#include <list>\n#include <algorithm>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <sys/time.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <cstdlib>\n#include <cstring>\n#include <cmath>\n#include <climits>\n#include <iomanip>\n#include <stdlib.h>\n// define NDEBUG here to disable assertions\n// if/when \"release\" builds are supported\n// #define NDEBUG\n#include <cassert>\n\n// nifti1_io.h is from nifticlib http://nifti.nimh.nih.gov\n// see README in fcma-toolbox.git/deps/\n#include <nifti1_io.h>\n\n// SSE/AVX instrinsics\n#if defined(_MSC_VER)\n// Microsoft C/C++-compatible compiler */\n#include <intrin.h>\n#elif defined(__GNUC__) && (defined(__x86_64__) || defined(__i386__))\n// GCC-compatible compiler (gcc,clang,icc) targeting x86/x86-64\n#include <x86intrin.h>\n#endif\n\n// OpenMP : gcc >= 4.7 or clang-omp http://clang-omp.github.io\n#include <omp.h>\n\n// Aligned memory blocks\n#ifdef __INTEL_COMPILER\n#include <offload.h>\n#else\n#include <mm_malloc.h>\n#endif\n#if defined(__GNUC__)\n// gcc supports this syntax\n#define ALIGNED(x) __attribute__((aligned(x)))\n#else\n// visual c++, clang, icc\n#define ALIGNED(x) __declspec(align(x))\n#endif\n\n// BLAS dependency\n#ifdef USE_MKL\n#include <mkl.h>\n#else\ntypedef int MKL_INT;\n#if defined __APPLE__\n#include <Accelerate/Accelerate.h>\n#else\nextern \"C\" {\n#include <cblas.h>\n}\n#endif\n#endif\n\n// Matrix multiplication parameters\n#define TINYNUM 1e-4\n#define LOGISTICTRHEHOLD 1e-6\n#define MAXFILENAMELENGTH 300\n#define MAXSUBJS 100\n#define MAXTRIALPERSUBJ 100\n#define MAXSVMITERATION 20000000\n\n// MPI communication tags\n#define COMPUTATIONTAG 1\n#define LENGTHTAG 2\n#define VOXELCLASSIFIERTAG 3\n#define ELAPSETAG 4\n#define POSITIONTAG 5\n#define SECONDORDERTAG 6\n\nenum Task {\n  Corr_Based_SVM = 0,\n  Corr_Based_Dis,\n  Acti_Based_SVM,\n  Corr_Sum,\n  Corr_Mask_Classification,\n  Corr_Mask_Cross_Validation,\n  Acti_Mask_Classification,\n  Acti_Mask_Cross_Validation,\n  Corr_Visualization,\n  Marginal_Screening,\n  Error_Type = -1\n};\n\ntypedef unsigned long long uint64;\ntypedef unsigned short uint16;\n\ntypedef struct raw_matrix_t {\n  std::string sname;  // subject name (file name without extension)\n  int sid;            // subject id\n  int row;\n  int col;\n  int nx, ny, nz;\n  float* matrix;\n} RawMatrix;\n\ntypedef struct trial_data_t {\n  int nTrials;\n  int nVoxels;\n  int nCols;\n  int* trialLengths;  // keep all trials data, subject by subject\n  int* scs;\n  float* data;  // normalized data for correlation\n  trial_data_t(int x, int y) : nTrials(x), nVoxels(y) {}\n} TrialData;\n\ntypedef struct corr_matrix_t {\n  int sid;      // subject id\n  int tlabel;   // trial label\n  int sr;       // starting row id\n  int step;     // row of this matrix\n  int nVoxels;  // col of this matrix\n  float* matrix;\n} CorrMatrix;\n\n// Trial: data structure for the start and end point of a trial\ntypedef struct trial_t {\n  int tid;\n  int sid;\n  int label;\n  int sc, ec;\n  // tid_withinsubj: block id within each subject,\n  // to be used in averaged matrix of searchlight\n  int tid_withinsubj;\n} Trial;\n\ntypedef struct voxel_t {\n  int* vid;  // contains global voxel ids\n  float* corr_vecs;\n  float* kernel_matrices;  // contains precomputed kernel matrix\n  int nTrials;  // row\n  int nVoxels;  // col\n  // voxel_t(int x, int y, int z) : vid(x), nTrials(y), nVoxels(z) {}\n} Voxel;\n\ntypedef struct voxel_Score_t {\n  int vid;\n  float score;\n} VoxelScore;\n\n// VoxelXYZ: voxel's 3-d coordinates in mm\ntypedef struct voxelxyz_t {\n  int x, y, z;\n} VoxelXYZ;\n\ntypedef ALIGNED(64) struct WIDELOCK_T {\n  omp_lock_t lock;\n} widelock_t;\n\nextern unsigned long long total_count;\n\n#endif\n", "meta": {"hexsha": "8a3818d3a65b7014ad4fb7b2ea89ce51e74462f1", "size": 3864, "ext": "h", "lang": "C", "max_stars_repo_path": "src/common.h", "max_stars_repo_name": "PrincetonUniversity/fcma-toolbox", "max_stars_repo_head_hexsha": "74f151d07d683fc2b1612b5b0e2cb29617b69c03", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T04:27:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-16T17:34:07.000Z", "max_issues_repo_path": "src/common.h", "max_issues_repo_name": "PrincetonUniversity/fcma-toolbox", "max_issues_repo_head_hexsha": "74f151d07d683fc2b1612b5b0e2cb29617b69c03", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-08-17T01:05:36.000Z", "max_issues_repo_issues_event_max_datetime": "2017-07-27T08:11:14.000Z", "max_forks_repo_path": "src/common.h", "max_forks_repo_name": "PrincetonUniversity/fcma-toolbox", "max_forks_repo_head_hexsha": "74f151d07d683fc2b1612b5b0e2cb29617b69c03", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-08-26T19:37:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-08T18:06:26.000Z", "avg_line_length": 22.08, "max_line_length": 69, "alphanum_fraction": 0.7217908903, "num_tokens": 1128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3451052709578724, "lm_q2_score": 0.043365798454817896, "lm_q1q2_score": 0.014965765626054414}}
{"text": "/* matrix/gsl_matrix_uint.h\r\n * \r\n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\r\n * \r\n * This program is free software; you can redistribute it and/or modify\r\n * it under the terms of the GNU General Public License as published by\r\n * the Free Software Foundation; either version 3 of the License, or (at\r\n * your option) any later version.\r\n * \r\n * This program is distributed in the hope that it will be useful, but\r\n * WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n * General Public License for more details.\r\n * \r\n * You should have received a copy of the GNU General Public License\r\n * along with this program; if not, write to the Free Software\r\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r\n */\r\n\r\n#ifndef __GSL_MATRIX_UINT_H__\r\n#define __GSL_MATRIX_UINT_H__\r\n\r\n#if !defined( GSL_FUN )\r\n#  if !defined( GSL_DLL )\r\n#    define GSL_FUN extern\r\n#  elif defined( BUILD_GSL_DLL )\r\n#    define GSL_FUN extern __declspec(dllexport)\r\n#  else\r\n#    define GSL_FUN extern __declspec(dllimport)\r\n#  endif\r\n#endif\r\n\r\n#include <stdlib.h>\r\n#include <gsl/gsl_types.h>\r\n#include <gsl/gsl_errno.h>\r\n#include <gsl/gsl_inline.h>\r\n#include <gsl/gsl_check_range.h>\r\n#include <gsl/gsl_vector_uint.h>\r\n#include <gsl/gsl_blas_types.h>\r\n\r\n#undef __BEGIN_DECLS\r\n#undef __END_DECLS\r\n#ifdef __cplusplus\r\n# define __BEGIN_DECLS extern \"C\" {\r\n# define __END_DECLS }\r\n#else\r\n# define __BEGIN_DECLS /* empty */\r\n# define __END_DECLS /* empty */\r\n#endif\r\n\r\n__BEGIN_DECLS\r\n\r\ntypedef struct \r\n{\r\n  size_t size1;\r\n  size_t size2;\r\n  size_t tda;\r\n  unsigned int * data;\r\n  gsl_block_uint * block;\r\n  int owner;\r\n} gsl_matrix_uint;\r\n\r\ntypedef struct\r\n{\r\n  gsl_matrix_uint matrix;\r\n} _gsl_matrix_uint_view;\r\n\r\ntypedef _gsl_matrix_uint_view gsl_matrix_uint_view;\r\n\r\ntypedef struct\r\n{\r\n  gsl_matrix_uint matrix;\r\n} _gsl_matrix_uint_const_view;\r\n\r\ntypedef const _gsl_matrix_uint_const_view gsl_matrix_uint_const_view;\r\n\r\n/* Allocation */\r\n\r\nGSL_FUN gsl_matrix_uint * \r\ngsl_matrix_uint_alloc (const size_t n1, const size_t n2);\r\n\r\nGSL_FUN gsl_matrix_uint * \r\ngsl_matrix_uint_calloc (const size_t n1, const size_t n2);\r\n\r\nGSL_FUN gsl_matrix_uint * \r\ngsl_matrix_uint_alloc_from_block (gsl_block_uint * b, \r\n                                   const size_t offset, \r\n                                   const size_t n1, \r\n                                   const size_t n2, \r\n                                   const size_t d2);\r\n\r\nGSL_FUN gsl_matrix_uint * \r\ngsl_matrix_uint_alloc_from_matrix (gsl_matrix_uint * m,\r\n                                    const size_t k1, \r\n                                    const size_t k2,\r\n                                    const size_t n1, \r\n                                    const size_t n2);\r\n\r\nGSL_FUN gsl_vector_uint * \r\ngsl_vector_uint_alloc_row_from_matrix (gsl_matrix_uint * m,\r\n                                        const size_t i);\r\n\r\nGSL_FUN gsl_vector_uint * \r\ngsl_vector_uint_alloc_col_from_matrix (gsl_matrix_uint * m,\r\n                                        const size_t j);\r\n\r\nGSL_FUN void gsl_matrix_uint_free (gsl_matrix_uint * m);\r\n\r\n/* Views */\r\n\r\nGSL_FUN _gsl_matrix_uint_view \r\ngsl_matrix_uint_submatrix (gsl_matrix_uint * m, \r\n                            const size_t i, const size_t j, \r\n                            const size_t n1, const size_t n2);\r\n\r\nGSL_FUN _gsl_vector_uint_view \r\ngsl_matrix_uint_row (gsl_matrix_uint * m, const size_t i);\r\n\r\nGSL_FUN _gsl_vector_uint_view \r\ngsl_matrix_uint_column (gsl_matrix_uint * m, const size_t j);\r\n\r\nGSL_FUN _gsl_vector_uint_view \r\ngsl_matrix_uint_diagonal (gsl_matrix_uint * m);\r\n\r\nGSL_FUN _gsl_vector_uint_view \r\ngsl_matrix_uint_subdiagonal (gsl_matrix_uint * m, const size_t k);\r\n\r\nGSL_FUN _gsl_vector_uint_view \r\ngsl_matrix_uint_superdiagonal (gsl_matrix_uint * m, const size_t k);\r\n\r\nGSL_FUN _gsl_vector_uint_view\r\ngsl_matrix_uint_subrow (gsl_matrix_uint * m, const size_t i,\r\n                         const size_t offset, const size_t n);\r\n\r\nGSL_FUN _gsl_vector_uint_view\r\ngsl_matrix_uint_subcolumn (gsl_matrix_uint * m, const size_t j,\r\n                            const size_t offset, const size_t n);\r\n\r\nGSL_FUN _gsl_matrix_uint_view\r\ngsl_matrix_uint_view_array (unsigned int * base,\r\n                             const size_t n1, \r\n                             const size_t n2);\r\n\r\nGSL_FUN _gsl_matrix_uint_view\r\ngsl_matrix_uint_view_array_with_tda (unsigned int * base, \r\n                                      const size_t n1, \r\n                                      const size_t n2,\r\n                                      const size_t tda);\r\n\r\n\r\nGSL_FUN _gsl_matrix_uint_view\r\ngsl_matrix_uint_view_vector (gsl_vector_uint * v,\r\n                              const size_t n1, \r\n                              const size_t n2);\r\n\r\nGSL_FUN _gsl_matrix_uint_view\r\ngsl_matrix_uint_view_vector_with_tda (gsl_vector_uint * v,\r\n                                       const size_t n1, \r\n                                       const size_t n2,\r\n                                       const size_t tda);\r\n\r\n\r\nGSL_FUN _gsl_matrix_uint_const_view \r\ngsl_matrix_uint_const_submatrix (const gsl_matrix_uint * m, \r\n                                  const size_t i, const size_t j, \r\n                                  const size_t n1, const size_t n2);\r\n\r\nGSL_FUN _gsl_vector_uint_const_view \r\ngsl_matrix_uint_const_row (const gsl_matrix_uint * m, \r\n                            const size_t i);\r\n\r\nGSL_FUN _gsl_vector_uint_const_view \r\ngsl_matrix_uint_const_column (const gsl_matrix_uint * m, \r\n                               const size_t j);\r\n\r\nGSL_FUN _gsl_vector_uint_const_view\r\ngsl_matrix_uint_const_diagonal (const gsl_matrix_uint * m);\r\n\r\nGSL_FUN _gsl_vector_uint_const_view \r\ngsl_matrix_uint_const_subdiagonal (const gsl_matrix_uint * m, \r\n                                    const size_t k);\r\n\r\nGSL_FUN _gsl_vector_uint_const_view \r\ngsl_matrix_uint_const_superdiagonal (const gsl_matrix_uint * m, \r\n                                      const size_t k);\r\n\r\nGSL_FUN _gsl_vector_uint_const_view\r\ngsl_matrix_uint_const_subrow (const gsl_matrix_uint * m, const size_t i,\r\n                               const size_t offset, const size_t n);\r\n\r\nGSL_FUN _gsl_vector_uint_const_view\r\ngsl_matrix_uint_const_subcolumn (const gsl_matrix_uint * m, const size_t j,\r\n                                  const size_t offset, const size_t n);\r\n\r\nGSL_FUN _gsl_matrix_uint_const_view\r\ngsl_matrix_uint_const_view_array (const unsigned int * base,\r\n                                   const size_t n1, \r\n                                   const size_t n2);\r\n\r\nGSL_FUN _gsl_matrix_uint_const_view\r\ngsl_matrix_uint_const_view_array_with_tda (const unsigned int * base, \r\n                                            const size_t n1, \r\n                                            const size_t n2,\r\n                                            const size_t tda);\r\n\r\nGSL_FUN _gsl_matrix_uint_const_view\r\ngsl_matrix_uint_const_view_vector (const gsl_vector_uint * v,\r\n                                    const size_t n1, \r\n                                    const size_t n2);\r\n\r\nGSL_FUN _gsl_matrix_uint_const_view\r\ngsl_matrix_uint_const_view_vector_with_tda (const gsl_vector_uint * v,\r\n                                             const size_t n1, \r\n                                             const size_t n2,\r\n                                             const size_t tda);\r\n\r\n/* Operations */\r\n\r\nGSL_FUN void gsl_matrix_uint_set_zero (gsl_matrix_uint * m);\r\nGSL_FUN void gsl_matrix_uint_set_identity (gsl_matrix_uint * m);\r\nGSL_FUN void gsl_matrix_uint_set_all (gsl_matrix_uint * m, unsigned int x);\r\n\r\nGSL_FUN int gsl_matrix_uint_fread (FILE * stream, gsl_matrix_uint * m) ;\r\nGSL_FUN int gsl_matrix_uint_fwrite (FILE * stream, const gsl_matrix_uint * m) ;\r\nGSL_FUN int gsl_matrix_uint_fscanf (FILE * stream, gsl_matrix_uint * m);\r\nGSL_FUN int gsl_matrix_uint_fprintf (FILE * stream, const gsl_matrix_uint * m, const char * format);\r\n \r\nGSL_FUN int gsl_matrix_uint_memcpy(gsl_matrix_uint * dest, const gsl_matrix_uint * src);\r\nGSL_FUN int gsl_matrix_uint_swap(gsl_matrix_uint * m1, gsl_matrix_uint * m2);\r\nGSL_FUN int gsl_matrix_uint_tricpy(CBLAS_UPLO_t Uplo, CBLAS_DIAG_t Diag, gsl_matrix_uint * dest, const gsl_matrix_uint * src);\r\n\r\nGSL_FUN int gsl_matrix_uint_swap_rows(gsl_matrix_uint * m, const size_t i, const size_t j);\r\nGSL_FUN int gsl_matrix_uint_swap_columns(gsl_matrix_uint * m, const size_t i, const size_t j);\r\nGSL_FUN int gsl_matrix_uint_swap_rowcol(gsl_matrix_uint * m, const size_t i, const size_t j);\r\nGSL_FUN int gsl_matrix_uint_transpose (gsl_matrix_uint * m);\r\nGSL_FUN int gsl_matrix_uint_transpose_memcpy (gsl_matrix_uint * dest, const gsl_matrix_uint * src);\r\nGSL_FUN int gsl_matrix_uint_transpose_tricpy (CBLAS_UPLO_t Uplo_src, CBLAS_DIAG_t Diag, gsl_matrix_uint * dest, const gsl_matrix_uint * src);\r\n\r\nGSL_FUN unsigned int gsl_matrix_uint_max (const gsl_matrix_uint * m);\r\nGSL_FUN unsigned int gsl_matrix_uint_min (const gsl_matrix_uint * m);\r\nGSL_FUN void gsl_matrix_uint_minmax (const gsl_matrix_uint * m, unsigned int * min_out, unsigned int * max_out);\r\n\r\nGSL_FUN void gsl_matrix_uint_max_index (const gsl_matrix_uint * m, size_t * imax, size_t *jmax);\r\nGSL_FUN void gsl_matrix_uint_min_index (const gsl_matrix_uint * m, size_t * imin, size_t *jmin);\r\nGSL_FUN void gsl_matrix_uint_minmax_index (const gsl_matrix_uint * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);\r\n\r\nGSL_FUN int gsl_matrix_uint_equal (const gsl_matrix_uint * a, const gsl_matrix_uint * b);\r\n\r\nGSL_FUN int gsl_matrix_uint_isnull (const gsl_matrix_uint * m);\r\nGSL_FUN int gsl_matrix_uint_ispos (const gsl_matrix_uint * m);\r\nGSL_FUN int gsl_matrix_uint_isneg (const gsl_matrix_uint * m);\r\nGSL_FUN int gsl_matrix_uint_isnonneg (const gsl_matrix_uint * m);\r\n\r\nGSL_FUN unsigned int gsl_matrix_uint_norm1 (const gsl_matrix_uint * m);\r\n\r\nGSL_FUN int gsl_matrix_uint_add (gsl_matrix_uint * a, const gsl_matrix_uint * b);\r\nGSL_FUN int gsl_matrix_uint_sub (gsl_matrix_uint * a, const gsl_matrix_uint * b);\r\nGSL_FUN int gsl_matrix_uint_mul_elements (gsl_matrix_uint * a, const gsl_matrix_uint * b);\r\nGSL_FUN int gsl_matrix_uint_div_elements (gsl_matrix_uint * a, const gsl_matrix_uint * b);\r\nGSL_FUN int gsl_matrix_uint_scale (gsl_matrix_uint * a, const double x);\r\nGSL_FUN int gsl_matrix_uint_scale_rows (gsl_matrix_uint * a, const gsl_vector_uint * x);\r\nGSL_FUN int gsl_matrix_uint_scale_columns (gsl_matrix_uint * a, const gsl_vector_uint * x);\r\nGSL_FUN int gsl_matrix_uint_add_constant (gsl_matrix_uint * a, const double x);\r\nGSL_FUN int gsl_matrix_uint_add_diagonal (gsl_matrix_uint * a, const double x);\r\n\r\n/***********************************************************************/\r\n/* The functions below are obsolete                                    */\r\n/***********************************************************************/\r\nGSL_FUN int gsl_matrix_uint_get_row(gsl_vector_uint * v, const gsl_matrix_uint * m, const size_t i);\r\nGSL_FUN int gsl_matrix_uint_get_col(gsl_vector_uint * v, const gsl_matrix_uint * m, const size_t j);\r\nGSL_FUN int gsl_matrix_uint_set_row(gsl_matrix_uint * m, const size_t i, const gsl_vector_uint * v);\r\nGSL_FUN int gsl_matrix_uint_set_col(gsl_matrix_uint * m, const size_t j, const gsl_vector_uint * v);\r\n/***********************************************************************/\r\n\r\n/* inline functions if you are using GCC */\r\n\r\nGSL_FUN INLINE_DECL unsigned int   gsl_matrix_uint_get(const gsl_matrix_uint * m, const size_t i, const size_t j);\r\nGSL_FUN INLINE_DECL void    gsl_matrix_uint_set(gsl_matrix_uint * m, const size_t i, const size_t j, const unsigned int x);\r\nGSL_FUN INLINE_DECL unsigned int * gsl_matrix_uint_ptr(gsl_matrix_uint * m, const size_t i, const size_t j);\r\nGSL_FUN INLINE_DECL const unsigned int * gsl_matrix_uint_const_ptr(const gsl_matrix_uint * m, const size_t i, const size_t j);\r\n\r\n#ifdef HAVE_INLINE\r\nINLINE_FUN \r\nunsigned int\r\ngsl_matrix_uint_get(const gsl_matrix_uint * m, const size_t i, const size_t j)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(1)) \r\n    {\r\n      if (i >= m->size1)\r\n        {\r\n          GSL_ERROR_VAL(\"first index out of range\", GSL_EINVAL, 0) ;\r\n        }\r\n      else if (j >= m->size2)\r\n        {\r\n          GSL_ERROR_VAL(\"second index out of range\", GSL_EINVAL, 0) ;\r\n        }\r\n    }\r\n#endif\r\n  return m->data[i * m->tda + j] ;\r\n} \r\n\r\nINLINE_FUN \r\nvoid\r\ngsl_matrix_uint_set(gsl_matrix_uint * m, const size_t i, const size_t j, const unsigned int x)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(1)) \r\n    {\r\n      if (i >= m->size1)\r\n        {\r\n          GSL_ERROR_VOID(\"first index out of range\", GSL_EINVAL) ;\r\n        }\r\n      else if (j >= m->size2)\r\n        {\r\n          GSL_ERROR_VOID(\"second index out of range\", GSL_EINVAL) ;\r\n        }\r\n    }\r\n#endif\r\n  m->data[i * m->tda + j] = x ;\r\n}\r\n\r\nINLINE_FUN \r\nunsigned int *\r\ngsl_matrix_uint_ptr(gsl_matrix_uint * m, const size_t i, const size_t j)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(1)) \r\n    {\r\n      if (i >= m->size1)\r\n        {\r\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\r\n        }\r\n      else if (j >= m->size2)\r\n        {\r\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\r\n        }\r\n    }\r\n#endif\r\n  return (unsigned int *) (m->data + (i * m->tda + j)) ;\r\n} \r\n\r\nINLINE_FUN \r\nconst unsigned int *\r\ngsl_matrix_uint_const_ptr(const gsl_matrix_uint * m, const size_t i, const size_t j)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(1)) \r\n    {\r\n      if (i >= m->size1)\r\n        {\r\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\r\n        }\r\n      else if (j >= m->size2)\r\n        {\r\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\r\n        }\r\n    }\r\n#endif\r\n  return (const unsigned int *) (m->data + (i * m->tda + j)) ;\r\n} \r\n\r\n#endif\r\n\r\n__END_DECLS\r\n\r\n#endif /* __GSL_MATRIX_UINT_H__ */\r\n", "meta": {"hexsha": "d6de1b3644fc5b136826c61372c883823bde02a0", "size": 13949, "ext": "h", "lang": "C", "max_stars_repo_path": "vendor/gsl/gsl/gsl_matrix_uint.h", "max_stars_repo_name": "mgreter/astrometrylib", "max_stars_repo_head_hexsha": "ef4d4539a537ab49329b77648aac893d2b4ad318", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z", "max_issues_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_matrix_uint.h", "max_issues_repo_name": "zzpwahaha/VimbaCamJILA", "max_issues_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z", "max_forks_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_matrix_uint.h", "max_forks_repo_name": "zzpwahaha/VimbaCamJILA", "max_forks_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 37.9048913043, "max_line_length": 142, "alphanum_fraction": 0.6510144096, "num_tokens": 3381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34510527095787247, "lm_q2_score": 0.04336579644574028, "lm_q1q2_score": 0.014965764932711144}}
{"text": "/////////////////////////////////////////////////////////////////////\n// = NMatrix\n//\n// A linear algebra library for scientific computation in Ruby.\n// NMatrix is part of SciRuby.\n//\n// NMatrix was originally inspired by and derived from NArray, by\n// Masahiro Tanaka: http://narray.rubyforge.org\n//\n// == Copyright Information\n//\n// SciRuby is Copyright (c) 2010 - 2014, Ruby Science Foundation\n// NMatrix is Copyright (c) 2012 - 2014, John Woods and the Ruby Science Foundation\n//\n// Please see LICENSE.txt for additional copyright notices.\n//\n// == Contributing\n//\n// By contributing source code to SciRuby, you agree to be bound by\n// our Contributor Agreement:\n//\n// * https://github.com/SciRuby/sciruby/wiki/Contributor-Agreement\n//\n// == inc.h\n//\n// Includes needed for LAPACK, CLAPACK, and CBLAS functions.\n//\n\n#ifndef INC_H\n# define INC_H\n\n\nextern \"C\" { // These need to be in an extern \"C\" block or you'll get all kinds of undefined symbol errors.\n#if defined HAVE_CBLAS_H\n  #include <cblas.h>\n#elif defined HAVE_ATLAS_CBLAS_H\n  #include <atlas/cblas.h>\n#endif\n\n#if defined HAVE_CLAPACK_H\n  #include <clapack.h>\n#elif defined HAVE_ATLAS_CLAPACK_H\n  #include <atlas/clapack.h>\n#endif\n}\n\n#endif // INC_H\n", "meta": {"hexsha": "11a9594693135142cde344600b2e406b55242a71", "size": 1213, "ext": "h", "lang": "C", "max_stars_repo_path": "ext/nmatrix_atlas/math_atlas/inc.h", "max_stars_repo_name": "VasiliCekaskin/nmatrix", "max_stars_repo_head_hexsha": "2152aa690dc394ff92a5340f53b6d24268ac0668", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 329.0, "max_stars_repo_stars_event_min_datetime": "2015-01-09T16:47:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T08:57:43.000Z", "max_issues_repo_path": "ext/nmatrix_atlas/math_atlas/inc.h", "max_issues_repo_name": "VasiliCekaskin/nmatrix", "max_issues_repo_head_hexsha": "2152aa690dc394ff92a5340f53b6d24268ac0668", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 317.0, "max_issues_repo_issues_event_min_datetime": "2015-01-05T22:47:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T18:09:48.000Z", "max_forks_repo_path": "ext/nmatrix_atlas/math_atlas/inc.h", "max_forks_repo_name": "VasiliCekaskin/nmatrix", "max_forks_repo_head_hexsha": "2152aa690dc394ff92a5340f53b6d24268ac0668", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 131.0, "max_forks_repo_forks_event_min_datetime": "2015-01-16T08:01:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T13:51:54.000Z", "avg_line_length": 25.2708333333, "max_line_length": 107, "alphanum_fraction": 0.6809563067, "num_tokens": 317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3775406687981454, "lm_q2_score": 0.039638839100970026, "lm_q1q2_score": 0.0149652738245623}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdint.h>\n#include <stddef.h>\n#include <unistd.h>\n#include <math.h>\n#include \"bigfile-mpi.h\"\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n\nvoid usage() {\n    fprintf(stderr, \"usage: bigfile-sample-mpi [-r ratio] [-N Nfile] [-f newfilepath] filepath block newblock\\n\");\n    exit(1);\n\n}\n#define DONE_TAG 1293\n#define ERROR_TAG 1295\n#define DIE_TAG 1290\n#define WORK_TAG 1291\n\nMPI_Datatype MPI_TYPE_WORK;\nBigFile bf = {0};\nBigFile bfnew = {0};\nBigBlock bb = {0};\nBigBlock bbnew = {0};\nint verbose = 0;\nint Nfile = -1;\nsize_t CHUNKSIZE = 1 * 1024 * 1024;\nint ThisTask, NTask;\nchar * newfilepath = NULL;\nvoid slave(void);\nvoid server(void);\n\ndouble ratio = 1.0;\nstruct work {\n    int64_t offset;\n    int64_t seed;\n    int64_t chunksize;\n    int64_t offsetnew;\n    int64_t nsel;\n};\n\nstatic size_t filesize();\n\nint main(int argc, char * argv[]) {\n\n    MPI_Init(&argc, &argv);\n\n    MPI_Comm_rank(MPI_COMM_WORLD, &ThisTask);\n    MPI_Comm_size(MPI_COMM_WORLD, &NTask);\n\n    MPI_Type_contiguous(sizeof(struct work), MPI_BYTE, &MPI_TYPE_WORK);\n    MPI_Type_commit(&MPI_TYPE_WORK);\n\n    int ch;\n    while(-1 != (ch = getopt(argc, argv, \"n:N:vf:r:\"))) {\n        switch(ch) {\n            case 'r':\n                ratio = atof(optarg);\n                break;\n            case 'N':\n            case 'n':\n                Nfile = atoi(optarg);\n                break;\n            case 'f':\n                newfilepath = optarg;\n                break;\n            case 'v':\n                verbose = 1;\n                break;\n            default:\n                usage();\n        }\n    }\n    if(argc - optind + 1 != 4) {\n        usage();\n    }\n    argv += optind - 1;\n    if(0 != big_file_mpi_open(&bf, argv[1], MPI_COMM_WORLD)) {\n        fprintf(stderr, \"failed to open: %s\\n\", big_file_get_error_message());\n        exit(1);\n    }\n    if(0 != big_file_mpi_open_block(&bf, &bb, argv[2], MPI_COMM_WORLD)) {\n        fprintf(stderr, \"failed to open: %s\\n\", big_file_get_error_message());\n        exit(1);\n    }\n    if(Nfile == -1 || bb.Nfile == 0) {\n        Nfile = bb.Nfile;\n    }\n    if(newfilepath == NULL) {\n        newfilepath = argv[1];\n    }\n    if(0 != big_file_mpi_create(&bfnew, newfilepath, MPI_COMM_WORLD)) {\n        fprintf(stderr, \"failed to open: %s\\n\", big_file_get_error_message());\n        exit(1);\n    }\n    size_t newsize = filesize();\n    if(0 != big_file_mpi_create_block(&bfnew, &bbnew, argv[3], bb.dtype, bb.nmemb, Nfile, newsize, MPI_COMM_WORLD)) {\n        fprintf(stderr, \"failed to create temp: %s\\n\", big_file_get_error_message());\n        exit(1);\n    }\n\n    /* copy attrs */\n    size_t nattr;\n    BigAttr * attrs = big_block_list_attrs(&bb, &nattr);\n    int i;\n    for(i = 0; i < nattr; i ++) {\n        BigAttr * attr = &attrs[i];\n        big_block_set_attr(&bbnew, attr->name, attr->data, attr->dtype, attr->nmemb);\n    }\n\n    if(bb.nmemb > 0 && bb.size > 0) {\n    /* copy data */\n        if(ThisTask == 0) {\n            server();\n        } else {\n            slave();\n        }\n    }\n    if(0 != big_block_mpi_close(&bbnew, MPI_COMM_WORLD)) {\n        fprintf(stderr, \"failed to close new: %s\\n\", big_file_get_error_message());\n        exit(1);\n    }\n    big_block_mpi_close(&bb, MPI_COMM_WORLD);\n    big_file_mpi_close(&bf, MPI_COMM_WORLD);\n    big_file_mpi_close(&bfnew, MPI_COMM_WORLD);\n    return 0;\n}\nstatic size_t filesize() {\n    gsl_rng * rng = gsl_rng_alloc(gsl_rng_mt19937);\n    gsl_rng_set(rng, 1984);\n    int64_t offset = 0;\n    int64_t offsetnew = 0;\n    struct work work;\n    for(offset = 0; offset < bb.size; ) {\n        int64_t chunksize = CHUNKSIZE;\n\n        /* never read beyond my end (read_simple caps at EOF) */\n        if(offset + chunksize >= bb.size) {\n            /* this is the last chunk */\n            chunksize = bb.size - offset;\n        }\n        work.offset = offset;\n        work.chunksize = chunksize;\n        work.seed = gsl_rng_get(rng);\n        work.offsetnew = offsetnew;\n        if(ratio == 1.0) {\n            work.nsel = chunksize;\n        } else {\n            work.nsel = gsl_ran_poisson(rng, chunksize * ratio);\n        }\n\n        offset += chunksize;\n        offsetnew += work.nsel;\n    }\n    return offsetnew;\n}\nvoid server() {\n    int64_t offset = 0;\n    int64_t offsetnew = 0;\n    struct work work;\n    gsl_rng * rng = gsl_rng_alloc(gsl_rng_mt19937);\n    gsl_rng_set(rng, 1984);\n    for(offset = 0; offset < bb.size; ) {\n        int64_t chunksize = CHUNKSIZE;\n        MPI_Status status;\n        int result = 0;\n        MPI_Recv(&result, 1, MPI_INT, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD,\n                &status);\n        if(status.MPI_TAG == ERROR_TAG) {\n            break;\n        }\n\n        /* never read beyond my end (read_simple caps at EOF) */\n        if(offset + chunksize >= bb.size) {\n            /* this is the last chunk */\n            chunksize = bb.size - offset;\n        }\n        work.offset = offset;\n        work.chunksize = chunksize;\n        work.seed = gsl_rng_get(rng);\n        work.offsetnew = offsetnew;\n        if(ratio == 1.0) {\n            work.nsel = chunksize;\n        } else {\n            work.nsel = gsl_ran_poisson(rng, chunksize * ratio);\n        }\n        MPI_Send(&work, 1, MPI_TYPE_WORK, status.MPI_SOURCE, WORK_TAG, MPI_COMM_WORLD);\n\n        offset += chunksize;\n        offsetnew += work.nsel;\n        if(verbose) {\n            fprintf(stderr, \"%td / %td done (%0.4g%%)\\r\", offset, bb.size, (100. / bb.size) * offset);\n        }\n    }\n    int i;\n    for(i = 1; i < NTask; i ++) {\n        struct work work;\n        MPI_Send(&work, 1, MPI_TYPE_WORK, i, DIE_TAG, MPI_COMM_WORLD);\n    }\n\n}\nvoid slave() {\n    gsl_rng * rng = gsl_rng_alloc(gsl_rng_mt19937);\n    int result = 0;\n    MPI_Send(&result, 1, MPI_INT, 0, DONE_TAG, MPI_COMM_WORLD);\n    while(1) {\n        struct work work;\n        MPI_Status status;\n        MPI_Recv(&work, 1, MPI_TYPE_WORK, 0, MPI_ANY_TAG, MPI_COMM_WORLD, &status);\n\n        if(status.MPI_TAG == DIE_TAG) {\n            break;\n        }\n        gsl_rng_set(rng, work.seed);\n\n        int64_t offset = work.offset;\n        int64_t chunksize = work.chunksize;\n        int64_t offsetnew = work.offsetnew;\n        int64_t nsel = work.nsel;\n        BigArray array;\n        BigBlockPtr ptrnew;\n        BigArray arraynew;\n\n        size_t dims[2];\n        void * buffer = malloc(dtype_itemsize(bb.dtype) * bb.nmemb * nsel);\n        dims[0] = nsel;\n        dims[1] = bb.nmemb;\n        big_array_init(&arraynew, buffer, bb.dtype, 2, dims, NULL);\n\n        ptrdiff_t i;\n        size_t step = dtype_itemsize(bb.dtype) * bb.nmemb;\n        size_t leftover = chunksize;\n        char * p = buffer;\n        char * q;\n        if(0 != big_block_read_simple(&bb, offset, chunksize, &array, NULL)) {\n            fprintf(stderr, \"failed to read original: %s\\n\", big_file_get_error_message());\n            result = -1;\n            goto bad;\n        }\n        q = array.data;\n\n//        printf(\"%ld %ld\\n\", nsel, leftover);\n        for(i = 0; i < chunksize; i ++) {\n            int64_t r = gsl_rng_uniform_int(rng, leftover);\n            if(r < nsel) {\n                memcpy(p, q, step);\n                p += step;\n                nsel --;\n            }\n            if(nsel == 0) break;\n            leftover --;\n            q += step;\n        }\n        if(nsel != 0) abort();\n        free(array.data);\n        if(0 != big_block_seek(&bbnew, &ptrnew, offsetnew)) {\n            fprintf(stderr, \"failed to seek new: %s\\n\", big_file_get_error_message());\n            result = -1;\n            free(arraynew.data);\n            goto bad;\n        }\n\n        if(0 != big_block_write(&bbnew, &ptrnew, &arraynew)) {\n            fprintf(stderr, \"failed to write new: %s\\n\", big_file_get_error_message());\n            result = -1;\n            free(arraynew.data);\n            goto bad;\n        }\n\n        free(arraynew.data);\n        MPI_Send(&result, 1, MPI_INT, 0, DONE_TAG, MPI_COMM_WORLD);\n        continue;\n    bad:\n        MPI_Send(&result, 1, MPI_INT, 0, ERROR_TAG, MPI_COMM_WORLD);\n        continue;\n    }\n    return;\n}\n", "meta": {"hexsha": "3dcf31b6a65d8724fb895c60333ce8bd6af06a67", "size": 8089, "ext": "c", "lang": "C", "max_stars_repo_path": "utils/bigfile-sample-mpi.c", "max_stars_repo_name": "rainwoodman/bigfile", "max_stars_repo_head_hexsha": "33e51c9168862fb9913daf74b0b00595ae6894b1", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2015-04-28T14:10:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T07:51:04.000Z", "max_issues_repo_path": "utils/bigfile-sample-mpi.c", "max_issues_repo_name": "rainwoodman/bigfile", "max_issues_repo_head_hexsha": "33e51c9168862fb9913daf74b0b00595ae6894b1", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 28.0, "max_issues_repo_issues_event_min_datetime": "2016-03-08T01:20:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-11T16:26:22.000Z", "max_forks_repo_path": "utils/bigfile-sample-mpi.c", "max_forks_repo_name": "rainwoodman/bigfile", "max_forks_repo_head_hexsha": "33e51c9168862fb9913daf74b0b00595ae6894b1", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-02-28T02:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-18T21:31:01.000Z", "avg_line_length": 28.7864768683, "max_line_length": 117, "alphanum_fraction": 0.5500061812, "num_tokens": 2198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.03114382986033942, "lm_q1q2_score": 0.014963946200644816}}
{"text": "/* testutilities.c\n *\n * 24-May-2008 Initial write: Ting Zhao\n */\n\n#include <stdlib.h>\n#include <string.h>\n#include <utilities.h>\n#include <math.h>\n#include \"tz_utilities.h\"\n#include \"tz_error.h\"\n#include \"tz_file_list.h\"\n#include \"tz_image_lib_defs.h\"\n#include \"tz_stack_utils.h\"\n\n/*\n#include \"tz_matlabio.h\"\n#include \"tz_rastergeom.h\"\n#include <gsl/gsl_math.h>\n*/\nint main(int argc, char *argv[])\n{\n  static char *Spec[] = {\"[-t]\", NULL};\n \n  Process_Arguments(argc, argv, Spec, 1);\n \n  if (Is_Arg_Matched(\"-t\")) {\n    /* example test */\n    \n    /* extract file name without extension from a path */\n    const char *path = \"../data/test.tif\";\n    char *name = fname(path, NULL);\n    if (strcmp(name, \"test\") != 0) {\n      PRINT_EXCEPTION(\"Bug?\", \"Unexpected file name.\");\n      return 1;\n    }\n\n    /* The user is responsible for freeing the returned value */\n    free(name);\n\n    /* The routine returns NULL when no name can be extracted */\n    path = \".\";\n    if (fname(path, NULL) != NULL) {\n      PRINT_EXCEPTION(\"Bug?\", \"Unexpected file name.\");\n      return 1;\n    }\n\n    path = \"../data/\";\n    if (fname(path, NULL) != NULL) {\n      PRINT_EXCEPTION(\"Bug?\", \"Unexpected file name.\");\n      return 1;\n    }\n\n    /* Different parts can be put together to form a path */\n    char new_path[500];\n    fullpath_e(\"../data/\", \"test\", \"tif\", new_path);\n    if (strcmp(new_path, \"../data/test.tif\") != 0) {\n      printf(\"%s\\n\", new_path);\n      PRINT_EXCEPTION(\"Bug?\", \"Unexpected file path.\");\n      return 1;      \n    }\n    \n    fullpath_e(\"\", \"test\", \"tif\", new_path);\n    if (strcmp(new_path, \"test.tif\") != 0) {\n      printf(\"%s\\n\", new_path);\n      PRINT_EXCEPTION(\"Bug?\", \"Unexpected file path.\");\n      return 1;      \n    }\n\n    { /* unit test */\n      char buffer[500];\n\n      if (fname(NULL, buffer) != NULL) {\n\tPRINT_EXCEPTION(\"Bug?\", \"Unexpected file name.\");\n\treturn 1;\n      }\n\n      if (fname(\"\\0\", buffer) != NULL) {\n\tPRINT_EXCEPTION(\"Bug?\", \"Unexpected file name.\");\n\treturn 1;\n      }\n\n      if (fname(\".\", buffer) != NULL) {\n\tPRINT_EXCEPTION(\"Bug?\", \"Unexpected file name.\");\n\treturn 1;\n      }\n      \n      if (strcmp(fname(\"t\", buffer), \"t\") != 0) {\n\tPRINT_EXCEPTION(\"Bug?\", \"Unexpected file name.\");\n\treturn 1;\n      }\n\n      if (fname(\"/\", buffer) != NULL) {\n\tPRINT_EXCEPTION(\"Bug?\", \"Unexpected file name.\");\n\treturn 1;\n      }\n      \n      if (fname(\"test/\", buffer) != NULL) {\n\tPRINT_EXCEPTION(\"Bug?\", \"Unexpected file name.\");\n\treturn 1;\n      }\n\n      if (strcmp(fname(\"test\", buffer), \"test\") != 0) {\n\tPRINT_EXCEPTION(\"Bug?\", \"Unexpected file name.\");\n\treturn 1;\n      }\n\n      if (strcmp(fname(\"./test\", buffer), \"test\") != 0) {\n\tPRINT_EXCEPTION(\"Bug?\", \"Unexpected file name.\");\n\treturn 1;\n      }\n\n      if (strcmp(fname(\"/test\", buffer), \"test\") != 0) {\n\tPRINT_EXCEPTION(\"Bug?\", \"Unexpected file name.\");\n\treturn 1;\n      }\n\n      if (strcmp(fname(\"/.test\", buffer), \".test\") != 0) {\n\tPRINT_EXCEPTION(\"Bug?\", \"Unexpected file name.\");\n\treturn 1;\n      }\n\n      if (strcmp(fname(\"t.est\", buffer), \"t\") != 0) {\n\tPRINT_EXCEPTION(\"Bug?\", \"Unexpected file name.\");\n\treturn 1;\n      }\n\n      if (strcmp(fname(\"/t.est\", buffer), \"t\") != 0) {\n\tPRINT_EXCEPTION(\"Bug?\", \"Unexpected file name.\");\n\treturn 1;\n      }\n\n      if (fname(\"/.\", buffer) != NULL) {\n\tPRINT_EXCEPTION(\"Bug?\", \"Unexpected file name.\");\n\treturn 1;\n      }\n\n      if (fname(\"data/.\", buffer) != NULL) {\n\tPRINT_EXCEPTION(\"Bug?\", \"Unexpected file name.\");\n\treturn 1;\n      }\n      \n      if (strcmp(fullpath_e(\"dir\", \"file\", \"ext\", buffer), \n\t\t \"dir/file.ext\") != 0) {\n\tPRINT_EXCEPTION(\"Bug?\", \"Unexpected path name.\");\n\treturn 1;\t\n      }\n\n      if (strcmp(fullpath_e(\"dir/\", \"file\", \"ext\", buffer), \n\t\t \"dir/file.ext\") != 0) {\n\tPRINT_EXCEPTION(\"Bug?\", \"Unexpected path name.\");\n\treturn 1;\t\n      }\n\n      if (strcmp(fullpath_e(\"dir\", \"file\", NULL, buffer), \n\t\t \"dir/file\") != 0) {\n\tPRINT_EXCEPTION(\"Bug?\", \"Unexpected path name.\");\n\treturn 1;\t\n      }\n\n      if (strcmp(fullpath_e(\"dir\", \"file\", \".\", buffer), \n\t\t \"dir/file.\") != 0) {\n\tprintf(\"%s\\n\", buffer);\n\tPRINT_EXCEPTION(\"Bug?\", \"Unexpected path name.\");\n\treturn 1;\t\n      }\n\n      if (strcmp(fullpath_e(\"dir\", \"file\", \".ext\", buffer), \n\t\t \"dir/file.ext\") != 0) {\n\tprintf(\"%s\\n\", buffer);\n\tPRINT_EXCEPTION(\"Bug?\", \"Unexpected path name.\");\n\treturn 1;\t\n      }\n\n    }\n\n    printf(\":) Testing passed.\\n\");\n    return 0;\n  }\n\n#if 0\n  FILE *fp = fopen(\"../data/test.fbd\", \"r\");\n\n  size_t len;\n  char *line;\n  while (!feof(fp)) {\n    if ((line = fgetln(fp, &len)) != NULL) {\n      printf(\"read %lu: \", len);\n      line[len-1] = '\\0';\n      printf(\"%s\\n\", line);\n    }\n  }\n\n  fclose(fp);\n#endif\n\n#if 0\n  char path[100];\n  Find_Matlab_Binpath(path);\n  printf(\"%s : %lu\\n\", path, strlen(path));\n#endif\n\n#if 0\n  int a = 10000;\n  int b = 11;\n  XOR_SWAP(a, b);\n\n  printf(\"%d %d\\n\", a, b);\n#endif\n\n#if 0\n  printf(\"%d\\n\", 2 << 2);\n  printf(\"%d\\n\", Compare_Float(1.01, 1.002, 0.0005));\n  printf(\"%d\\n\", gsl_fcmp(1.01, 1.002, 0.0005));\n#endif\n\n#if 0\n  char *s1 = \"hello\";\n  printf(\"%p\\n\", s1);\n  s1[0] = 't';\n  printf(\"%s\\n\", s1);\n#endif\n\n#if 0\n  double x = -100.4350;\n  printf(\"%g\\n\", Cube_Root(x) * Cube_Root(x) * Cube_Root(x));\n#endif\n\n#if 0\n  printf(\"%d\\n\", Raster_Line_Map(852, 451, 296));\n  return 1;\n\n  int m = 33;\n  int n = 10;\n  int i;\n  for (i = 0; i < m; i++) {\n    printf(\"%d \", Raster_Line_Map(m, n, i));\n  }\n  printf(\"\\n\");\n#endif\n\n#if 0\n  int w1 = 302;\n  int h1 = 586;\n  int nw2;\n  int nh2;\n  Raster_Ratio_Scale(w1, h1, 425, 236, &nw2, &nh2);\n  printf(\"%d x %d\\n\", nw2, nh2);\n  printf(\"%g => %g\\n\", (double) w1 / h1, (double) nw2 / nh2);\n#endif\n\n#if 0\n  //printf(\"%u\\n\", Hexstr_To_Uint(\"BA9B\"));\n  char str[9];\n  printf(\"%s\\n\", Uint_To_Hexstr(262, str));\n#endif\n\n#if 0\n  FILE *fp = fopen(\"/Users/zhaot/Work/neurolabi/data/movie/a0.BMP\", \"r\");\n  Fprint_File_Binary(fp, 20, stdout);\n  fclose(fp);\n#endif\n\n#if 0\n  printf(\"%d\\n\", Round_Div(110, -19));\n#endif\n\n#if 0\n  printf(\"%d\\n\", Raster_Linear_Map(31, 10, 100, 0, 231));\n#endif\n\n#if 0\n  printf(\"%d\\n\", Raster_Point_Zoom_Offset(0, 2, 100, 512, 500, 1));\n#endif\n\n#if 0\n  fcopy(\"../data/test.tif\", \"../data/test2.tif\");\n#endif\n\n#if 0\n  printf(\"%d bytes\\n\", fsize(\"../data/test.tif\"));\n#endif\n\n#if 0\n  printf(\"%g %g %g\\n\", Infinity, -Infinity, NaN);\n#endif\n\n#if 0\n  size_t x = 1000;\n  printf(\"%zd\\n\", (size_t) 1000 * 1000 * 1000 * 4);\n#endif\n\n#if 0\n  size_t index = Stack_Util_Offset(1000, 1000, 1000, 2000, 2000, 2000);\n  printf(\"%zd\\n\", index);\n  int x, y, z;\n  Stack_Util_Coord(index, 2000, 2000, &x, &y, &z);\n  printf(\"%d %d %d\\n\", x, y, z);\n#endif\n\n#if 0\n  printf(\"%s\\n\", fname(\"../data/test.dot\", NULL));\n  printf(\"%s\\n\", dname(\"../data/test.dot\", NULL));\n  printf(\"%s\\n\", dname(\"/test.dot\", NULL));\n  printf(\"%s\\n\", dname(\"test.dot\", NULL));\n#endif\n\n#if 0\n  char *line = malloc(2048 * 2048 * 4);\n  char *data = malloc(1024 * 1024 * 4);\n  int i;\n  int j;\n  tic();\n  for (i = 0; i < 2048; i++) {\n    for (j = 0; j < 2048; j++) {\n      if (*line != *data++) {\n\t*line++ = *data;\n\t*line++ = *data;\n\t*line = *data;\n\tline += 2;\n      }\n      /*\n      memset(line, *data++, 3);\n      line += 4;\n      */\n    }\n  }\n  printf(\"%lld\\n\", toc());\n#endif\n\n#if 0\n  char buf[11];\n  Memset_Pattern4( buf, \"1234\", 10 );\n  buf[10] = '\\0';\n  printf(\"%s\\n\", buf);\n\n  Memset_Pattern4( buf, \"4321\", 8 );\n  buf[8] = '\\0';\n  printf(\"%s\\n\", buf);\n\n  Memset_Pattern4( buf, \"4321\", 2);\n  buf[2] = '\\0';\n  printf(\"%s\\n\", buf);\n#endif\n\n#if 0\n  char *block[1000000];\n  int i;\n\n  tic();\n  for (i = 0; i < 1000000; i++) {\n    block[i] = (char*) malloc(i % 991 + 10);\n  }\n  printf(\"%lld\\n\", toc());\n\n  int index[1000000];\n  int j;\n  int offset = 0;\n  for (i = 0; i < 100; i++) {\n    for (j = 0; j < 10000; j++) {\n      index[offset++] = j * 100 + i;\n    }\n  }\n\n  tic();\n  for (i = 999999; i >= 0; i--) {\n    free(block[index[i]]);\n  }\n  printf(\"%lld\\n\", toc());\n#endif\n\n#if 0\n  int (*test)[10];\n  int test2[10];\n  test = &test2;\n  printf(\"%p\\n\", test);\n  printf(\"%p\\n\", *test);\n  printf(\"%p\\n\", test2);\n#endif\n\n#if 0\n  int a[100];\n  int i = 0;\n  i[a] = 0;\n  printf(\"%d\\n\", i[a]);\n#endif\n\n#if 0\n  free(NULL);\n#endif\n\n#if 0\n  int i;\n  for (i = 0; i < 10; i++) {\n    int n = 0;\n    n++;\n    printf(\"%d\\n\", n);\n  }\n#endif\n\n#if 0\n  printf(\"%g\\n\", round(0.5));\n  printf(\"%g\\n\", floor(0.5));\n#endif\n\n#if 0\n  if (fcmp(\"../data/test2.tb\", \"../data/test3.tb\")) {\n    printf(\"The files are different.\\n\");\n  } else {\n    printf(\"The files are the same.\\n\");\n  }\n#endif\n\n#if 0\n  char str[65];\n  printf(\"%s\\n\", double_binstr(0.0, str));\n#endif\n\n#if 0\n  printf(\"%d\\n\", MEDIAN3(0, 1, 2));\n  printf(\"%d\\n\", MEDIAN3(0, 2, 1));\n  printf(\"%d\\n\", MEDIAN3(1, 0, 2));\n  printf(\"%d\\n\", MEDIAN3(2, 1, 0));\n  printf(\"%d\\n\", MEDIAN3(1, 2, 0));\n  printf(\"%d\\n\", MEDIAN3(2, 0, 1));\n  printf(\"%d\\n\", MEDIAN3(0, 1, 1));\n  printf(\"%d\\n\", MEDIAN3(1, 0, 1));\n  printf(\"%d\\n\", MEDIAN3(1, 1, 0));\n  printf(\"%d\\n\", MEDIAN3(2, 1, 1));\n  printf(\"%d\\n\", MEDIAN3(1, 2, 1));\n  printf(\"%d\\n\", MEDIAN3(1, 1, 2));\n#endif\n\n#if 0\n  unsigned char ch1 = 255;\n  char ch = ch1;\n  printf(\"%x\\n\", ch);\n\n  ch1 = -1;\n  printf(\"%x\\n\", ch1);\n#endif\n\n#if 0\n  //size_t fs = fsize(\"../data/spikes/pm002.nev\");\n  FILE *fp = fopen(\"../data/spikes/pm002.nev\", \"r\");\n  /*\n  fseek(fp, fs - 104*5, SEEK_SET);\n  uint32_t tmp1;\n  uint16_t tmp2;\n  uint8_t tmp3;\n  fread(&tmp1, 4, 1, fp);\n  fread(&tmp2, 2, 1, fp);\n  fread(&tmp3, 1, 1, fp);\n  printf(\"%u, %u, %u\\n\", tmp1, tmp2, tmp3);\n  */\n\n  uint32_t head_size;\n  fseek(fp, 12, SEEK_SET);\n  fread(&head_size, 4, 1, fp);\n  fseek(fp, head_size, SEEK_SET);\n  int packetcnt = 4325366;\n  char *buffer = (char*) malloc(packetcnt * 104);\n  fread(buffer, 1, packetcnt * 104, fp);\n  int offset = 0;\n  uint32_t tmp1;\n  uint16_t tmp2;\n  uint8_t tmp3;\n  \n  int i;\n  for (i = 0; i < packetcnt; i++) {\n    tmp1 = *((uint32_t*) (buffer + offset));\n    offset += 4;\n    tmp2 = *((uint16_t*) (buffer + offset));\n    offset += 2;\n    tmp3 = *((uint8_t*) (buffer + offset));\n    if (i > 4325360) {\n      printf(\"%u %u %u\\n\", tmp1, tmp2, tmp3);\n    }\n    offset += 1;\n    offset += 97;\n  }\n\n  fclose(fp);\n#endif\n\n#if 0\n  File_List *list = New_File_List();\n\n  //File_List_Load_Dir(\"/home/zhaot/Work/neutube/neurolabi/data/test\", \"tif\", list);\n  File_List_Load_Dir(\"../data\", \"tif\", list);\n\n  File_List_Sort_By_Number(list);\n\n  Print_File_List(list);\n#endif\n\n#if 0\n  int start, end;\n  dir_fnum_pair(\"../data/ting_example_stack/superpixel_maps\", \".*\\\\.png\", \n      &start, &end);\n  printf(\"%d, %d\\n\", start, end);\n#endif\n\n#if 0\n  color_t color;\n  uint8_t overflow = Value_To_Color(0, color);\n\n  printf(\"%u %u %u %u\\n\", overflow, color[2], color[1], color[0]);\n#endif\n\n#if 0\n  printf(\"%*sD\\n\", 3, \"t\");\n#endif\n\n#if 1\n#endif\n\n\n  return 0;\n}\n", "meta": {"hexsha": "5c8dec1053efb3c0775ebd4ada8bc882a7ea863f", "size": 10666, "ext": "c", "lang": "C", "max_stars_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/testutilities.c", "max_stars_repo_name": "zzhmark/vaa3d_tools", "max_stars_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-27T19:14:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-27T19:14:03.000Z", "max_issues_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/testutilities.c", "max_issues_repo_name": "zzhmark/vaa3d_tools", "max_issues_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-12-03T05:33:13.000Z", "max_issues_repo_issues_event_max_datetime": "2016-12-03T05:33:13.000Z", "max_forks_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/testutilities.c", "max_forks_repo_name": "zzhmark/vaa3d_tools", "max_forks_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.472168906, "max_line_length": 84, "alphanum_fraction": 0.5443465217, "num_tokens": 3688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2751297238231752, "lm_q2_score": 0.054198733642444784, "lm_q1q2_score": 0.014911682618611668}}
{"text": "#include <stdio.h>\n#include <gsl/gsl_ieee_utils.h>\n\nint\nmain (void) \n{\n  float f = 1.0/3.0;\n  double d = 1.0/3.0;\n\n  double fd = f; /* promote from float to double */\n  \n  printf (\" f=\"); gsl_ieee_printf_float(&f); \n  printf (\"\\n\");\n\n  printf (\"fd=\"); gsl_ieee_printf_double(&fd); \n  printf (\"\\n\");\n\n  printf (\" d=\"); gsl_ieee_printf_double(&d); \n  printf (\"\\n\");\n\n  return 0;\n}\n", "meta": {"hexsha": "c7f111092bfe4e5c1942fd7f1e3ebb444a39a428", "size": 379, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/ieee.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/ieee.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/ieee.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 16.4782608696, "max_line_length": 51, "alphanum_fraction": 0.5857519789, "num_tokens": 130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2751297238231752, "lm_q2_score": 0.05419872447622314, "lm_q1q2_score": 0.014911680096711639}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\n * Contact: lymastee@hotmail.com\n *\n * This file is part of the gslib project.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n#pragma once\n\n#ifndef painterport_eca0917d_5109_4de2_ae6f_18d5c163d02c_h\n#define painterport_eca0917d_5109_4de2_ae6f_18d5c163d02c_h\n\n#include <gslib/rtree.h>\n#include <ariel/painter.h>\n\n__ariel_begin__\n\nclass painter_obj;\n\ntypedef rtree_entity<painter_obj*> painter_obj_entity;\ntypedef rtree_node<painter_obj_entity> painter_obj_node;\ntypedef _tree_allocator<painter_obj_node> painter_obj_alloc;\ntypedef tree<painter_obj_entity, painter_obj_node, painter_obj_alloc> painter_obj_tree;\ntypedef rtree<painter_obj_entity, quadratic_split_alg<25, 10, painter_obj_tree>, painter_obj_node, painter_obj_alloc> painter_obj_rtree;\ntypedef vector<painter_obj*> painter_objs;\n\nclass __gs_novtable painter_obj abstract\n{\npublic:\n    enum type\n    {\n        po_line,\n        po_rect,\n        po_path,\n        po_text,\n    };\n\npublic:\n    painter_obj(const painter_context& ctx): _ctx(ctx) {}\n    virtual ~painter_obj() {}\n    virtual type get_type() const = 0;\n    virtual rectf& get_rect(rectf& rc) const = 0;\n\nprotected:\n    painter_context         _ctx;\n\npublic:\n    const painter_context& get_context() const { return _ctx; }\n};\n\nclass painter_line_obj:\n    public painter_obj\n{\npublic:\n    painter_line_obj(const painter_context& ctx, const pointf& p1, const pointf& p2): painter_obj(ctx), _p1(p1), _p2(p2) {}\n    virtual type get_type() const override { return po_line; }\n    virtual rectf& get_rect(rectf& rc) const override;\n\nprivate:\n    pointf                  _p1;\n    pointf                  _p2;\n};\n\nclass painter_rect_obj:\n    public painter_obj\n{\npublic:\n    painter_rect_obj(const painter_context& ctx,  const rectf& rc): painter_obj(ctx), _rc(rc) {}\n    virtual type get_type() const override { return po_rect; }\n    virtual rectf& get_rect(rectf& rc) const override { return rc = _rc; }\n\nprivate:\n    rectf                   _rc;\n};\n\nclass painter_path_obj:\n    public painter_obj\n{\npublic:\n    painter_path_obj(const painter_context& ctx, painter_path& take_me): painter_obj(ctx) { _path.swap(take_me); }\n    painter_path_obj(const painter_context& ctx, const painter_path& path): painter_obj(ctx), _path(path) {}\n    virtual type get_type() const override { return po_path; }\n    virtual rectf& get_rect(rectf& rc) const override;\n    rectf& rebuild_rect(rectf& rc) const;\n\nprivate:\n    painter_path            _path;\n    mutable bool            _rc_valid = false;\n    mutable rectf           _rc;\n};\n\nclass painter_text_obj:\n    public painter_obj\n{\npublic:\n    painter_text_obj(const painter_context& ctx, const string& txt, const pointf& p, const color& cr): painter_obj(ctx), _text(txt), _pos(p), _cr(cr) {}\n    virtual type get_type() const override { return po_text; }\n    virtual rectf& get_rect(rectf& rc) const override;\n\nprivate:\n    string                  _text;\n    pointf                  _pos;\n    color                   _cr;\n};\n\nclass painterport:\n    public painter\n{\npublic:\n    virtual ~painterport();\n    virtual void resize(int w, int h) override {}\n    virtual void draw_path(const painter_path& path) override;\n    virtual void draw_line(const vec2& p1, const vec2& p2) override;\n    virtual void draw_rect(const rectf& rc) override;\n    virtual void draw_text(const gchar* str, float x, float y, const color& cr, int length) override;\n    virtual void on_draw_begin() override;\n\nprotected:\n    painter_obj_rtree       _rtree;\n\npublic:\n    rectf& get_area_rect(rectf& rc) const;\n    void query_objs(painter_objs& objs, const rectf& rc);\n\nprotected:\n    void add_obj(painter_obj* obj);\n    void clear_objs();\n};\n\n__ariel_end__\n\n#endif\n", "meta": {"hexsha": "06131fc0dd7dce0581f1bf427d60a0bc20103a16", "size": 4785, "ext": "h", "lang": "C", "max_stars_repo_path": "include/ariel/painterport.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/ariel/painterport.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ariel/painterport.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 31.6887417219, "max_line_length": 152, "alphanum_fraction": 0.7161964472, "num_tokens": 1181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34864513533394575, "lm_q2_score": 0.04272219724178408, "lm_q1q2_score": 0.014894886239125335}}
{"text": "# ifndef LANGIL_H\n# define LANGIL_H\n\n///////////////////////////////////////////////////////\n//////   GILLESPIE CLASS\n//////\n//////\t\t\t\t\t\tR. Perez-Carrasco\n//////                               Created: 16 Nov '13\n///////////////////////////////////////////////////////\n/* Class for simulating master equation through langil algorythm. It defines three classes:\n\t\t- langil: In charge of the integration\n\t\t- species: contains a name a number and methods to change number\n\t\t- reaction: contains a name, a stoiciometry associated and a pointer to a propensity computing function\t\t\n*/\n\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n#include <string>\n#include <fstream>\n#include <iostream>\n#include <unordered_map>\n#include <vector>\n#include <math.h>\n#include <time.h>\n#include <unistd.h>\n#include <iomanip>\n//#include <omp.h>\n\n#include \"species.h\"\n#include \"cell_cycle.h\"\n\n#define VERBOSE 1\n#define NON_VERBOSE 0\n\n#define TIMESTEPMULT 3\n#define TIMESTEP 0\n#define ALL 1\n#define NOWRITE 2\n#define LASTPOINT 4\n\n#define GILLESPIE 0\n#define MACROSCOPIC 2\n#define CLEEULER 1\n#define CLEMILSTEIN 3\t\t\n\n#define ADIABATIC true\n#define NONADIABATIC false\n\n#define GEOMETRIC true\n#define NONGEOMETRIC false\n\n#define DETERMINISTIC_TIME true\n#define STOCHASTIC_TIME false\n\n#define EXPONENTIAL_REACTION 0\n#define GEOMETRIC_REACTION 1\n#define DETERMINISTIC_REACTION 2\n#define ADIABATIC_REACTION 3\n\n\nusing namespace std;\n\n\nstruct StructDivisionState{\n\tdouble time;\n\tdouble species0before;\n\tdouble species1before;\n\tdouble species0after;\n\tdouble species1after;\n};\n\n\nclass reaction; // defined after langil\nclass species; // defined after reaction\nclass expressionzone; // defined in a separate file\n\nclass langil{\n\t\n\tfriend class expressionzone;\n\n//\tfriend class reaction; // reaction have access to the state of the system \n\n\tpublic:\n\n\t\tlangil(string outputfilename, double vol=100, int seed=-1);\n\t\tvoid SetState(string aname, float anumber); //Set Initial conditions\n\t\tdouble GetState(string a); // get the state of the selected species\n\t\tvoid SetTime(double time); //Set current time\n\t\tvoid AddSpecies(string aname, float anum); // Add a new molecular species\n\t\tvoid AddSpeciesTimeTracking(string aname, float anum, double lifetime); //  Add a molecular species with a timer\n\t\tvoid AddCellCycleSpecies(); // add a cell cycle to the system\n\t\tvoid addCellPhase(double duration, int type_phase); // add a cell phase to the cell cycle\n\t\tvoid PrintSummarySpecies();\n\t\tstring StateString();\n\t\tvoid Add_Reaction(string name,vector<int> stoich,double (*prop_f)(v_species&),int typeofrec = EXPONENTIAL_REACTION); // Add a reaction to the system overloaded to create directly\n\t\tvoid UpdateTime(); // Update times for the deterministic events \n\t\tvoid SetRunType(int rt,double dt=0);\n\t\tdouble GillespieStep(double timelimit = -1); // Advance one step in the Gillespie algorithm. Returns time of the step. Timelimit does not react if the reaction would take more than timelimit\n\t\tdouble LangevinEulerStep(double timelimit = -1); // Make an Euler-Maruyama integration step\n\t\tdouble LangevinMilsteinStep(double timelimit = -1); // Make an SDE integration step with the Milstein algorithm (not tested)\n\t\tdouble MacroStep(double timlimit = -1); // Make an Euler (deterministic) step\n\t\tdouble MacroAdiabaticStep(double dtt); //  Make an Euler step if the Adiabaitc species\t\t\n\t\tdouble Run(double time, bool verbose=true); // React until reach time time\n\t\tdouble RunTimes(int N,double time, bool verbose=true); // Run Run() N times\n\t\tdouble RunTransition(bool (*prop_f)(v_species&), bool (*prop_g)(v_species&), int loops, double maxT); // Run transition between two points, if loops=1 it also records the transition trajectory\n\t\tvoid WriteState(); // Write state in file \n\t\tvoid WriteTempState(); // Write state in file \n\t\tvoid WritePrevrecState(); // Write previous recorded state in file \n\t\tvoid SetWriteState(int flag, double tl=0);// Switch betweem different states:\n\t\tdouble (langil::*MakeStep)(double); // pointer to the actual integration chosen\n\t\t\t// TIMESTEP: write the state every tl time lapse\n\t\t\t// ALL: write after each reaction takes place\n\t\t\t// NOWRITE: don't write anything in output file\n\t\tdouble SetLangevinTimeStep(double dx); // set dt to a characteristic time that will increase with the size of the system\n\t\tvoid Add_TimeAction(double (*actionfunc)(double));\n\t\tvoid RunTimeAction();\n\t\tvoid setPhaseDuration(int phase, double duration, int type_phase);\n\t\tvoid Set_AdiabaticReaction(string aname);\n\t\tvoid Set_GeometricReaction(string aname);\n\t\tvoid Set_Boundary_Behaviour(void (*b_b)(v_species&, v_species&)); // Boundary behaviour\n\t\tvoid Set_StoreDivisionTimes();// activate the storage of division times in DivisionTimes vector\n\t\tvoid (*Boundary_Behaviour)(v_species&, v_species&); // boundary behaviour function\n\t\tvector<StructDivisionState> Get_HistoryDivision();\n\t\tvoid Reset_HistoryDivision();\n\t\tvoid SetDivisionHistory(int b,int a);\n\n\n\tprotected:\n\n\t\tv_species x; //value of each species. shared_ptr is used since the vector can contain species and also childrens of that class (i.e. different classes)\n\t\tvector<reaction> r;//vector with all the reactions\n \t\tdouble time; // current time of simulation\n\t\tgsl_rng * rng; // allocator for the rng generator\n\t\tvector<double> rnd; // rnd numbers\n\t\tvector<double> xtemp; // temporal vector for integrations\n\t\tv_species xtemp0,xtemp1; // temporal vector for integrations\n\t\tdouble pro,pro0; // auxiliar variables for the program\n\t\tint sto;  // auxiliar value for stoichiometry\n\t\tdouble totalprop,cumprop, detprop; // sum of the propensities\n\t\tdouble nexttau; // time of the next step\n\t\tvector<reaction>::iterator nextreaction; // reaction selected to react\n\t\tvector<int>* nextstoichiometry;\n\t\tdouble Omega; // volume of the system to change between concentrations and absolute numbers\n\t\tdouble signal; // variable that can modulate an external signal its time course\n\t\t\t\t\t\t// may be changed through time actions with Add_TimeAction\n\t\tint celldivided; // flag to track possible celldivision\n\t\tint geostoichiometry; // dummy variable to set random geometric stoichiometries\n\t\n\t\tbool record; // Set record of the trajectory\n\t\tofstream trajfile; // File for output traj\n\t\tstring outputfilename; // File for output name\n\t\tint fwrite; // flag for write state when integrating\n\t\tdouble timelapse; // dt for recording if TIMESTEP\n\t\tdouble nextrectime; // t for recording if TIMESTEP\n\t\tdouble totaltime; // total integration time for the trajectory\n\t\tdouble dt; // timestep used in integrations for macroscopic and langevin (if negative, it is used by Langevin as a prediction for dx)\n\t\t\n\t\tint cellcyclespeciesidx;  // index of the species vector that tracks cell cycle phases\n \t\tcell_cycle cell; // cell_cycle object to manage cell cycle events\n\n \t\tbool fStoreDivisionTimes; // flag to store Division Times\n \t\tvector<StructDivisionState> DivisionHistoryVector; // Division history vector. Each component is a vector \n \t\tStructDivisionState divisionstate;\n\t\tvector<double(*)(double)> actionfuncvec; // vector to time action functions\n\n};\n\n\n\n\n////////////////////////////////////////////////////////////////////////////\n///////////////////////////////////////////////////////////////////////////////\nclass reaction{//Class containing the info of each reaction. Each reaction added \n// through the method Add_Reaction(reaction) will be stored as an element in a vector\n// by langil class. The pointer x, points out to the state of the langil system and\n// is managed automatically by langil when a reaction is added to a langil instance\n// It has also the property \"adiabatic\" meaning that it is a fast variable and can always be simulated\n// from its deterministic behaviour\n\n\tfriend class langil;\n\n\tpublic:\n\t\t\n\t\t\n\treaction(string aname,vector<int> asto,double (*aprop_f)(v_species&)=NULL,int reacttype= EXPONENTIAL_REACTION, \n\t\t    vector<reaction>* x0=NULL){\n\t\t\tname=aname;\n\t\t\tstoichiometry=asto;\n\t\t\tprop_f=aprop_f;\n\t\t\treactiontype=reacttype;\n\t\t}\n\t\tdouble GetPropensity(){\n\t\t\treturn prop_f(*x);\n\t\t}\n\t\tdouble GetPropensity(v_species& x0){\n\t\t\treturn prop_f(x0);\n\t\t}\n\t\tstring GetName(){\n\t\t\treturn name;\n\t\t}\n\t\tvoid SetPropensity(double (*p_f)(v_species&)){\n\t\t\tprop_f=p_f;\n\t\t}\n\t\tvoid SetState(v_species& x0){\n\t\t\tx=&x0;\n\t\t}\n\t\tvector<int>* GetStoichiometry(){\n\t\t\treturn &stoichiometry;\n\t\t}\n\t\tbool IsAdiabatic(){\n\t\t\treturn (reactiontype == ADIABATIC_REACTION);\n\t\t}\n\t\tbool IsNotAdiabatic(){\n\t\t\treturn (reactiontype != ADIABATIC_REACTION);\n\t\t}\n\t\tbool IsGeometric(){\n\t\t\treturn (reactiontype == GEOMETRIC_REACTION);\n\t\t}\n\t\tbool IsNotGeometric(){\n\t\t\treturn (reactiontype != GEOMETRIC_REACTION);\n\t\t}\n\t\tbool IsNotDetermTime(){\n\t\t\treturn (reactiontype != (DETERMINISTIC_REACTION));\n\t\t}\n\t\tbool IsDetermTime(){\n\t\t\treturn (reactiontype == (DETERMINISTIC_REACTION));\n\t\t}\n\t\tvoid SetAdiabatic(){\n\t\t\treactiontype = ADIABATIC_REACTION;\n\t\t}\n\t\tvoid SetGeometric(){\n\t\t\treactiontype = GEOMETRIC_REACTION;\n\t\t}\n\t\tvoid SetDeterministicTime(){\n\t\t\treactiontype = DETERMINISTIC_REACTION;\n\t\t}\t\n\n\tprotected:\n\n\t\tstring name; // name of the reactio\n\t\tvector<int> stoichiometry; // stoichiometry\n\t\tdouble (*prop_f)(v_species&); // propensity function\n\t\tv_species* x;  //value of each species. shared_ptr is used since the vector can contain species and also childrens of that class (i.e. different classes)\n\t\tint reactiontype; // can be any of the macros EXPONENTIAL_REACTION, DETERMINISITIC_REACTION, etc.\n\n // of the system\n\n\n};\n\n\n\n#endif\n", "meta": {"hexsha": "b5eecb5545d8e2a6d5cb4e95081883b2985c997e", "size": 9428, "ext": "h", "lang": "C", "max_stars_repo_path": "langil.h", "max_stars_repo_name": "2piruben/langil", "max_stars_repo_head_hexsha": "e2e41d8d00f7de9a1ba1c014d4bac8b364dbd856", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "langil.h", "max_issues_repo_name": "2piruben/langil", "max_issues_repo_head_hexsha": "e2e41d8d00f7de9a1ba1c014d4bac8b364dbd856", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "langil.h", "max_forks_repo_name": "2piruben/langil", "max_forks_repo_head_hexsha": "e2e41d8d00f7de9a1ba1c014d4bac8b364dbd856", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1181102362, "max_line_length": 194, "alphanum_fraction": 0.7259227832, "num_tokens": 2323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.030214588268123326, "lm_q1q2_score": 0.01487126187125904}}
{"text": "#ifndef EXT_VANILLAGENERATOR_LIB_OBJECTS_BIOMEARRAY_H_\n#define EXT_VANILLAGENERATOR_LIB_OBJECTS_BIOMEARRAY_H_\n\n#include <cstddef>\n#include <gsl/span>\n\nclass BiomeArray {\n public:\n  static const size_t DATA_SIZE = 256;\n\n  explicit BiomeArray(const gsl::span<const uint_fast8_t, BiomeArray::DATA_SIZE> &values);\n\n  auto Get(uint8_t x, uint8_t z) const -> uint_fast8_t;\n  auto Set(uint8_t x, uint8_t z, uint_fast8_t value) -> void;\n\n  [[nodiscard]] gsl::span<const uint_fast8_t, DATA_SIZE> GetRawData() const;\n\n private:\n  std::array<uint_fast8_t, 256> mValues;\n\n  static inline void Index(uint8_t x, uint8_t z, uint_fast8_t &offset);\n};\n\n#endif // EXT_VANILLAGENERATOR_LIB_OBJECTS_BIOMEARRAY_H_\n", "meta": {"hexsha": "559f76b61131e2a867e3397f7774545979f25781", "size": 693, "ext": "h", "lang": "C", "max_stars_repo_path": "lib/biomes/BiomeArray.h", "max_stars_repo_name": "NetherGamesMC/noiselib", "max_stars_repo_head_hexsha": "56fc48ea1367e1d08b228dfa580b513fbec8ca31", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2021-08-16T18:58:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T01:12:31.000Z", "max_issues_repo_path": "lib/biomes/BiomeArray.h", "max_issues_repo_name": "NetherGamesMC/ext-vanillagenerator", "max_issues_repo_head_hexsha": "56fc48ea1367e1d08b228dfa580b513fbec8ca31", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-06-21T15:10:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-19T01:48:00.000Z", "max_forks_repo_path": "lib/biomes/BiomeArray.h", "max_forks_repo_name": "NetherGamesMC/ext-vanillagenerator", "max_forks_repo_head_hexsha": "56fc48ea1367e1d08b228dfa580b513fbec8ca31", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-06-21T02:10:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-04T01:36:08.000Z", "avg_line_length": 27.72, "max_line_length": 90, "alphanum_fraction": 0.7763347763, "num_tokens": 210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3738758227716966, "lm_q2_score": 0.03963884250447896, "lm_q1q2_score": 0.01482000485507977}}
{"text": "/* vector/gsl_vector_ulong.h\r\n * \r\n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\r\n * \r\n * This program is free software; you can redistribute it and/or modify\r\n * it under the terms of the GNU General Public License as published by\r\n * the Free Software Foundation; either version 3 of the License, or (at\r\n * your option) any later version.\r\n * \r\n * This program is distributed in the hope that it will be useful, but\r\n * WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n * General Public License for more details.\r\n * \r\n * You should have received a copy of the GNU General Public License\r\n * along with this program; if not, write to the Free Software\r\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r\n */\r\n\r\n#ifndef __GSL_VECTOR_ULONG_H__\r\n#define __GSL_VECTOR_ULONG_H__\r\n\r\n#if !defined( GSL_FUN )\r\n#  if !defined( GSL_DLL )\r\n#    define GSL_FUN extern\r\n#  elif defined( BUILD_GSL_DLL )\r\n#    define GSL_FUN extern __declspec(dllexport)\r\n#  else\r\n#    define GSL_FUN extern __declspec(dllimport)\r\n#  endif\r\n#endif\r\n\r\n#include <stdlib.h>\r\n#include <gsl/gsl_types.h>\r\n#include <gsl/gsl_errno.h>\r\n#include <gsl/gsl_inline.h>\r\n#include <gsl/gsl_check_range.h>\r\n#include <gsl/gsl_block_ulong.h>\r\n\r\n#undef __BEGIN_DECLS\r\n#undef __END_DECLS\r\n#ifdef __cplusplus\r\n# define __BEGIN_DECLS extern \"C\" {\r\n# define __END_DECLS }\r\n#else\r\n# define __BEGIN_DECLS /* empty */\r\n# define __END_DECLS /* empty */\r\n#endif\r\n\r\n__BEGIN_DECLS\r\n\r\ntypedef struct \r\n{\r\n  size_t size;\r\n  size_t stride;\r\n  unsigned long *data;\r\n  gsl_block_ulong *block;\r\n  int owner;\r\n} \r\ngsl_vector_ulong;\r\n\r\ntypedef struct\r\n{\r\n  gsl_vector_ulong vector;\r\n} _gsl_vector_ulong_view;\r\n\r\ntypedef _gsl_vector_ulong_view gsl_vector_ulong_view;\r\n\r\ntypedef struct\r\n{\r\n  gsl_vector_ulong vector;\r\n} _gsl_vector_ulong_const_view;\r\n\r\ntypedef const _gsl_vector_ulong_const_view gsl_vector_ulong_const_view;\r\n\r\n\r\n/* Allocation */\r\n\r\nGSL_FUN gsl_vector_ulong *gsl_vector_ulong_alloc (const size_t n);\r\nGSL_FUN gsl_vector_ulong *gsl_vector_ulong_calloc (const size_t n);\r\n\r\nGSL_FUN gsl_vector_ulong *gsl_vector_ulong_alloc_from_block (gsl_block_ulong * b,\r\n                                                     const size_t offset, \r\n                                                     const size_t n, \r\n                                                     const size_t stride);\r\n\r\nGSL_FUN gsl_vector_ulong *gsl_vector_ulong_alloc_from_vector (gsl_vector_ulong * v,\r\n                                                      const size_t offset, \r\n                                                      const size_t n, \r\n                                                      const size_t stride);\r\n\r\nGSL_FUN void gsl_vector_ulong_free (gsl_vector_ulong * v);\r\n\r\n/* Views */\r\n\r\nGSL_FUN _gsl_vector_ulong_view \r\ngsl_vector_ulong_view_array (unsigned long *v, size_t n);\r\n\r\nGSL_FUN _gsl_vector_ulong_view \r\ngsl_vector_ulong_view_array_with_stride (unsigned long *base,\r\n                                         size_t stride,\r\n                                         size_t n);\r\n\r\nGSL_FUN _gsl_vector_ulong_const_view \r\ngsl_vector_ulong_const_view_array (const unsigned long *v, size_t n);\r\n\r\nGSL_FUN _gsl_vector_ulong_const_view \r\ngsl_vector_ulong_const_view_array_with_stride (const unsigned long *base,\r\n                                               size_t stride,\r\n                                               size_t n);\r\n\r\nGSL_FUN _gsl_vector_ulong_view \r\ngsl_vector_ulong_subvector (gsl_vector_ulong *v, \r\n                            size_t i, \r\n                            size_t n);\r\n\r\nGSL_FUN _gsl_vector_ulong_view \r\ngsl_vector_ulong_subvector_with_stride (gsl_vector_ulong *v, \r\n                                        size_t i,\r\n                                        size_t stride,\r\n                                        size_t n);\r\n\r\nGSL_FUN _gsl_vector_ulong_const_view \r\ngsl_vector_ulong_const_subvector (const gsl_vector_ulong *v, \r\n                                  size_t i, \r\n                                  size_t n);\r\n\r\nGSL_FUN _gsl_vector_ulong_const_view \r\ngsl_vector_ulong_const_subvector_with_stride (const gsl_vector_ulong *v, \r\n                                              size_t i, \r\n                                              size_t stride,\r\n                                              size_t n);\r\n\r\n/* Operations */\r\n\r\nGSL_FUN void gsl_vector_ulong_set_zero (gsl_vector_ulong * v);\r\nGSL_FUN void gsl_vector_ulong_set_all (gsl_vector_ulong * v, unsigned long x);\r\nGSL_FUN int gsl_vector_ulong_set_basis (gsl_vector_ulong * v, size_t i);\r\n\r\nGSL_FUN int gsl_vector_ulong_fread (FILE * stream, gsl_vector_ulong * v);\r\nGSL_FUN int gsl_vector_ulong_fwrite (FILE * stream, const gsl_vector_ulong * v);\r\nGSL_FUN int gsl_vector_ulong_fscanf (FILE * stream, gsl_vector_ulong * v);\r\nGSL_FUN int gsl_vector_ulong_fprintf (FILE * stream, const gsl_vector_ulong * v,\r\n                              const char *format);\r\n\r\nGSL_FUN int gsl_vector_ulong_memcpy (gsl_vector_ulong * dest, const gsl_vector_ulong * src);\r\n\r\nGSL_FUN int gsl_vector_ulong_reverse (gsl_vector_ulong * v);\r\n\r\nGSL_FUN int gsl_vector_ulong_swap (gsl_vector_ulong * v, gsl_vector_ulong * w);\r\nGSL_FUN int gsl_vector_ulong_swap_elements (gsl_vector_ulong * v, const size_t i, const size_t j);\r\n\r\nGSL_FUN unsigned long gsl_vector_ulong_max (const gsl_vector_ulong * v);\r\nGSL_FUN unsigned long gsl_vector_ulong_min (const gsl_vector_ulong * v);\r\nGSL_FUN void gsl_vector_ulong_minmax (const gsl_vector_ulong * v, unsigned long * min_out, unsigned long * max_out);\r\n\r\nGSL_FUN size_t gsl_vector_ulong_max_index (const gsl_vector_ulong * v);\r\nGSL_FUN size_t gsl_vector_ulong_min_index (const gsl_vector_ulong * v);\r\nGSL_FUN void gsl_vector_ulong_minmax_index (const gsl_vector_ulong * v, size_t * imin, size_t * imax);\r\n\r\nGSL_FUN int gsl_vector_ulong_add (gsl_vector_ulong * a, const gsl_vector_ulong * b);\r\nGSL_FUN int gsl_vector_ulong_sub (gsl_vector_ulong * a, const gsl_vector_ulong * b);\r\nGSL_FUN int gsl_vector_ulong_mul (gsl_vector_ulong * a, const gsl_vector_ulong * b);\r\nGSL_FUN int gsl_vector_ulong_div (gsl_vector_ulong * a, const gsl_vector_ulong * b);\r\nGSL_FUN int gsl_vector_ulong_scale (gsl_vector_ulong * a, const unsigned long x);\r\nGSL_FUN int gsl_vector_ulong_add_constant (gsl_vector_ulong * a, const double x);\r\nGSL_FUN int gsl_vector_ulong_axpby (const unsigned long alpha, const gsl_vector_ulong * x, const unsigned long beta, gsl_vector_ulong * y);\r\nGSL_FUN unsigned long gsl_vector_ulong_sum (const gsl_vector_ulong * a);\r\n\r\nGSL_FUN int gsl_vector_ulong_equal (const gsl_vector_ulong * u, \r\n                            const gsl_vector_ulong * v);\r\n\r\nGSL_FUN int gsl_vector_ulong_isnull (const gsl_vector_ulong * v);\r\nGSL_FUN int gsl_vector_ulong_ispos (const gsl_vector_ulong * v);\r\nGSL_FUN int gsl_vector_ulong_isneg (const gsl_vector_ulong * v);\r\nGSL_FUN int gsl_vector_ulong_isnonneg (const gsl_vector_ulong * v);\r\n\r\nGSL_FUN INLINE_DECL unsigned long gsl_vector_ulong_get (const gsl_vector_ulong * v, const size_t i);\r\nGSL_FUN INLINE_DECL void gsl_vector_ulong_set (gsl_vector_ulong * v, const size_t i, unsigned long x);\r\nGSL_FUN INLINE_DECL unsigned long * gsl_vector_ulong_ptr (gsl_vector_ulong * v, const size_t i);\r\nGSL_FUN INLINE_DECL const unsigned long * gsl_vector_ulong_const_ptr (const gsl_vector_ulong * v, const size_t i);\r\n\r\n#ifdef HAVE_INLINE\r\n\r\nINLINE_FUN\r\nunsigned long\r\ngsl_vector_ulong_get (const gsl_vector_ulong * v, const size_t i)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(i >= v->size))\r\n    {\r\n      GSL_ERROR_VAL (\"index out of range\", GSL_EINVAL, 0);\r\n    }\r\n#endif\r\n  return v->data[i * v->stride];\r\n}\r\n\r\nINLINE_FUN\r\nvoid\r\ngsl_vector_ulong_set (gsl_vector_ulong * v, const size_t i, unsigned long x)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(i >= v->size))\r\n    {\r\n      GSL_ERROR_VOID (\"index out of range\", GSL_EINVAL);\r\n    }\r\n#endif\r\n  v->data[i * v->stride] = x;\r\n}\r\n\r\nINLINE_FUN\r\nunsigned long *\r\ngsl_vector_ulong_ptr (gsl_vector_ulong * v, const size_t i)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(i >= v->size))\r\n    {\r\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\r\n    }\r\n#endif\r\n  return (unsigned long *) (v->data + i * v->stride);\r\n}\r\n\r\nINLINE_FUN\r\nconst unsigned long *\r\ngsl_vector_ulong_const_ptr (const gsl_vector_ulong * v, const size_t i)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(i >= v->size))\r\n    {\r\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\r\n    }\r\n#endif\r\n  return (const unsigned long *) (v->data + i * v->stride);\r\n}\r\n#endif /* HAVE_INLINE */\r\n\r\n__END_DECLS\r\n\r\n#endif /* __GSL_VECTOR_ULONG_H__ */\r\n\r\n\r\n", "meta": {"hexsha": "324b049bc57daa3d18aa242e8213624396880067", "size": 8707, "ext": "h", "lang": "C", "max_stars_repo_path": "vendor/gsl/gsl/gsl_vector_ulong.h", "max_stars_repo_name": "mgreter/astrometrylib", "max_stars_repo_head_hexsha": "ef4d4539a537ab49329b77648aac893d2b4ad318", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z", "max_issues_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_vector_ulong.h", "max_issues_repo_name": "zzpwahaha/VimbaCamJILA", "max_issues_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z", "max_forks_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_vector_ulong.h", "max_forks_repo_name": "zzpwahaha/VimbaCamJILA", "max_forks_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 35.8312757202, "max_line_length": 140, "alphanum_fraction": 0.6755484093, "num_tokens": 2031, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38491214448393346, "lm_q2_score": 0.03846619201832428, "lm_q1q2_score": 0.014806104459903964}}
{"text": "/*\n * Copyright (C) 2015  University of Oregon\n *\n * You may distribute under the terms of either the GNU General Public\n * License or the Apache License, as specified in the LICENSE file.\n *\n * For more information, see the LICENSE file.\n */\n/* aslmirtime.h */\n/*---------------------------------------------------------------------------*/\n/*                                                                           */\n/* aslmirtime.h: Global includes and defines                                 */\n/*                                                                           */\n/* Copyright (C) 2011 Paul Kinchesh                                          */\n/*                                                                           */\n/* This file is part of aslmirtime.                                          */\n/*                                                                           */\n/* aslmirtime is free software: you can redistribute it and/or modify        */\n/* it under the terms of the GNU General Public License as published by      */\n/* the Free Software Foundation, either version 3 of the License, or         */\n/* (at your option) any later version.                                       */\n/*                                                                           */\n/* aslmirtime is distributed in the hope that it will be useful,             */\n/* but WITHOUT ANY WARRANTY; without even the implied warranty of            */\n/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the              */\n/* GNU General Public License for more details.                              */\n/*                                                                           */\n/* You should have received a copy of the GNU General Public License         */\n/* along with aslmirtime. If not, see <http://www.gnu.org/licenses/>.        */\n/*                                                                           */\n/*---------------------------------------------------------------------------*/\n/*\f*/\n\n\n/*--------------------------------------------------------*/\n/*---- Wrap the header to prevent multiple inclusions ----*/\n/*--------------------------------------------------------*/\n#ifndef _H_aslmirtime_H\n#define _H_aslmirtime_H\n\n\n/*----------------------------------*/\n/*---- Include standard headers ----*/\n/*----------------------------------*/\n#include <stdio.h>\n#include <math.h>\n#include <string.h>\n#include <stdlib.h>\n#include <sys/param.h>\n#include <sys/stat.h>\n#include <stddef.h>\n#include <sys/time.h>\n\n\n/*-----------------------------*/\n/*---- Include GSL Headers ----*/\n/*-----------------------------*/\n#include <gsl/gsl_multimin.h>\n\n\n/*-------------------------------------------*/\n/*---- Make sure __FUNCTION__ is defined ----*/\n/*-------------------------------------------*/\n#ifndef __FUNCTION__\n#define __FUNCTION__ __func__\n#endif\n\n\n/*------------------------------------------------------*/\n/*---- Floating point comparison macros (as in SGL) ----*/\n/*------------------------------------------------------*/\n/* EPSILON is the largest allowable deviation due to floating point storage */\n#define EPSILON 1e-9\n#define FP_LT(A,B)  (((A)<(B)) && (fabs((A)-(B))>EPSILON))  /* A less than B */\n#define FP_GT(A,B)  (((A)>(B)) && (fabs((A)-(B))>EPSILON))  /* A greater than B */\n#define FP_EQ(A,B)  (fabs((A)-(B))<=EPSILON)                /* A equal to B */\n#define FP_NEQ(A,B) (!FP_EQ(A,B))                           /* A not equal to B */\n#define FP_GTE(A,B) (FP_GT(A,B) || FP_EQ(A,B))              /* A greater than or equal to B */\n#define FP_LTE(A,B) (FP_LT(A,B) || FP_EQ(A,B))              /* A less than or equal to B */\n\n\n/*---------------------------------------------------------------*/\n/*---- So we can simply include aslmirtime.h in aslmirtime.c ----*/\n/*---------------------------------------------------------------*/\n#ifdef LOCAL\n#define EXTERN\n#else\n#define EXTERN extern\n#endif\n\n\n/*-----------------------------------*/\n/*---- Functions in aslmirtime.c ----*/\n/*-----------------------------------*/\ndouble my_f (const gsl_vector *v, void *params);\nvoid my_df (const gsl_vector *v, void *params, gsl_vector *df);\nvoid my_fdf (const gsl_vector *x, void *params, double *f, gsl_vector *df);\nvoid getinput(double **pars,int argc,char *argv[]);\nint nomem(char *file,const char *function,int line);\nint usage_terminate();\n\n/*----------------------------*/\n/*---- End of header wrap ----*/\n/*----------------------------*/\n#endif\n", "meta": {"hexsha": "3cbaeac9f431aaef22db1616eb83176abb148376", "size": 4488, "ext": "h", "lang": "C", "max_stars_repo_path": "src/aslmirtime/aslmirtime.h", "max_stars_repo_name": "DanIverson/OpenVnmrJ", "max_stars_repo_head_hexsha": "0db324603dbd8f618a6a9526b9477a999c5a4cc3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2016-06-17T05:04:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T17:54:44.000Z", "max_issues_repo_path": "src/aslmirtime/aslmirtime.h", "max_issues_repo_name": "timburrow/openvnmrj-source", "max_issues_repo_head_hexsha": "f5e65eb2db4bded3437701f0fa91abd41928579c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 128.0, "max_issues_repo_issues_event_min_datetime": "2016-07-13T17:09:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T17:53:52.000Z", "max_forks_repo_path": "src/aslmirtime/aslmirtime.h", "max_forks_repo_name": "timburrow/openvnmrj-source", "max_forks_repo_head_hexsha": "f5e65eb2db4bded3437701f0fa91abd41928579c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 102.0, "max_forks_repo_forks_event_min_datetime": "2016-01-23T15:27:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T05:41:54.000Z", "avg_line_length": 42.3396226415, "max_line_length": 94, "alphanum_fraction": 0.4048573975, "num_tokens": 809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489883132727684, "lm_q2_score": 0.03567855203126789, "lm_q1q2_score": 0.014802989541222488}}
{"text": "/*\n * Copyright 2012-2016 M. Andersen and L. Vandenberghe.\n * Copyright 2010-2011 L. Vandenberghe.\n * Copyright 2004-2009 J. Dahl and L. Vandenberghe.\n *\n * This file is part of CVXOPT.\n *\n * CVXOPT is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * CVXOPT is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include \"cvxopt.h\"\n\n#include <complex.h>\n\n#include \"misc.h\"\n\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n\n#include <time.h>\n\nPyDoc_STRVAR(gsl__doc__,\"Random Module.\");\n\nstatic unsigned long seed = 0;\nstatic const gsl_rng_type *rng_type;\nstatic gsl_rng *rng;\n\nstatic char doc_getseed[] =\n  \"Returns the seed value for the random number generator.\\n\\n\"\n  \"getseed()\";\n\nstatic PyObject * getseed(PyObject *self)\n{\n  return Py_BuildValue(\"l\",seed);\n}\n\nstatic char doc_setseed[] =\n  \"Sets the seed value for the random number generator.\\n\\n\"\n  \"setseed(value = 0)\\n\\n\"\n  \"ARGUMENTS\\n\"\n  \"value     integer seed. If the value is 0, then the system clock\\n\"\n  \"          measured in seconds is used instead\";\n\nstatic PyObject * setseed(PyObject *self, PyObject *args)\n{\n  unsigned long seed_ = 0;\n  time_t seconds;\n\n  if (!PyArg_ParseTuple(args, \"|l\", &seed_))\n    return NULL;\n\n  if (!seed_) {\n    time(&seconds);\n    seed = (unsigned long)seconds;\n  }\n  else seed = seed_;\n\n  return Py_BuildValue(\"\");\n}\n\n\nstatic char doc_normal[] =\n  \"Randomly generates a matrix with normally distributed entries.\\n\\n\"\n  \"normal(nrows, ncols=1, mean=0, std=1)\\n\\n\"\n  \"PURPOSE\\n\"\n  \"Returns a matrix with typecode 'd' and size nrows by ncols, with\\n\"\n  \"its entries randomly generated from a normal distribution with mean\\n\"\n  \"m and standard deviation std.\\n\\n\"\n  \"ARGUMENTS\\n\"\n  \"nrows     number of rows\\n\\n\"\n  \"ncols     number of columns\\n\\n\"\n  \"mean      approximate mean of the distribution\\n\\n\"\n  \"std       standard deviation of the distribution\";\nstatic PyObject *\nnormal(PyObject *self, PyObject *args, PyObject *kwrds)\n{\n  matrix *obj;\n  int i, nrows, ncols = 1;\n  double m = 0, s = 1;\n  char *kwlist[] = {\"nrows\", \"ncols\", \"mean\", \"std\",  NULL};\n\n  if (!PyArg_ParseTupleAndKeywords(args, kwrds, \"i|idd\", kwlist,\n\t  &nrows, &ncols, &m, &s)) return NULL;\n\n  if (s < 0.0) PY_ERR(PyExc_ValueError, \"std must be non-negative\");\n\n  if ((nrows<0) || (ncols<0)) {\n    PyErr_SetString(PyExc_TypeError, \"dimensions must be non-negative\");\n    return NULL;\n  }\n\n  if (!(obj = Matrix_New(nrows, ncols, DOUBLE)))\n    return PyErr_NoMemory();\n\n  gsl_rng_env_setup();\n  rng_type = gsl_rng_default;\n  rng = gsl_rng_alloc (rng_type);\n  gsl_rng_set(rng, seed);\n\n  for (i = 0; i < nrows*ncols; i++)\n    MAT_BUFD(obj)[i] = gsl_ran_gaussian (rng, s) + m;\n\n  seed = gsl_rng_get (rng);\n  gsl_rng_free(rng);\n\n  return (PyObject *)obj;\n}\n\nstatic char doc_uniform[] =\n  \"Randomly generates a matrix with uniformly distributed entries.\\n\\n\"\n  \"uniform(nrows, ncols=1, a=0, b=1)\\n\\n\"\n  \"PURPOSE\\n\"\n  \"Returns a matrix with typecode 'd' and size nrows by ncols, with\\n\"\n  \"its entries randomly generated from a uniform distribution on the\\n\"\n  \"interval (a,b).\\n\\n\"\n  \"ARGUMENTS\\n\"\n  \"nrows     number of rows\\n\\n\"\n  \"ncols     number of columns\\n\\n\"\n  \"a         lower bound\\n\\n\"\n  \"b         upper bound\";\n\nstatic PyObject *\nuniform(PyObject *self, PyObject *args, PyObject *kwrds)\n{\n  matrix *obj;\n  int i, nrows, ncols = 1;\n  double a = 0, b = 1;\n\n  char *kwlist[] = {\"nrows\", \"ncols\", \"a\", \"b\", NULL};\n\n  if (!PyArg_ParseTupleAndKeywords(args, kwrds, \"i|idd\", kwlist,\n\t  &nrows, &ncols, &a, &b)) return NULL;\n\n  if (a>b) PY_ERR(PyExc_ValueError, \"a must be less than b\");\n\n  if ((nrows<0) || (ncols<0))\n    PY_ERR_TYPE(\"dimensions must be non-negative\");\n\n  if (!(obj = (matrix *)Matrix_New(nrows, ncols, DOUBLE)))\n    return PyErr_NoMemory();\n\n  gsl_rng_env_setup();\n  rng_type = gsl_rng_default;\n  rng = gsl_rng_alloc (rng_type);\n  gsl_rng_set(rng, seed);\n\n  for (i= 0; i < nrows*ncols; i++)\n    MAT_BUFD(obj)[i] = gsl_ran_flat (rng, a, b);\n\n  seed = gsl_rng_get (rng);\n  gsl_rng_free(rng);\n\n  return (PyObject *)obj;\n}\n\nstatic PyMethodDef gsl_functions[] = {\n{\"getseed\", (PyCFunction)getseed, METH_VARARGS|METH_KEYWORDS, doc_getseed},\n{\"setseed\", (PyCFunction)setseed, METH_VARARGS|METH_KEYWORDS, doc_setseed},\n{\"normal\", (PyCFunction)normal, METH_VARARGS|METH_KEYWORDS, doc_normal},\n{\"uniform\", (PyCFunction)uniform, METH_VARARGS|METH_KEYWORDS, doc_uniform},\n{NULL}  /* Sentinel */\n};\n\n#if PY_MAJOR_VERSION >= 3\n\nstatic PyModuleDef gsl_module = {\n    PyModuleDef_HEAD_INIT,\n    \"gsl\",\n    gsl__doc__,\n    -1,\n    gsl_functions,\n    NULL, NULL, NULL, NULL\n};\n\nPyMODINIT_FUNC PyInit_gsl(void)\n{\n  PyObject *m;\n  if (!(m = PyModule_Create(&gsl_module))) return NULL;\n  if (import_cvxopt() < 0) return NULL;\n  return m;\n}\n\n#else\n\nPyMODINIT_FUNC initgsl(void)\n{\n  PyObject *m;\n  m = Py_InitModule3(\"cvxopt.gsl\", gsl_functions, gsl__doc__);\n  if (import_cvxopt() < 0) return;\n}\n\n#endif\n", "meta": {"hexsha": "d44f7ea6ef3ab62c3736b41a7c5f1b9d2e3dd82b", "size": 5391, "ext": "c", "lang": "C", "max_stars_repo_path": "src/cpp/qpsolver/cvxopt/src/C/gsl.c", "max_stars_repo_name": "Hap-Hugh/quicksel", "max_stars_repo_head_hexsha": "10eee90b759638d5c54ba19994ae8e36e90e12b8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2020-07-07T16:32:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T14:23:23.000Z", "max_issues_repo_path": "src/cpp/qpsolver/cvxopt/src/C/gsl.c", "max_issues_repo_name": "Hap-Hugh/quicksel", "max_issues_repo_head_hexsha": "10eee90b759638d5c54ba19994ae8e36e90e12b8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-09-02T15:25:39.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-24T08:37:18.000Z", "max_forks_repo_path": "src/cpp/qpsolver/cvxopt/src/C/gsl.c", "max_forks_repo_name": "Hap-Hugh/quicksel", "max_forks_repo_head_hexsha": "10eee90b759638d5c54ba19994ae8e36e90e12b8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-08-14T22:02:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-31T07:08:29.000Z", "avg_line_length": 26.4264705882, "max_line_length": 75, "alphanum_fraction": 0.6781673159, "num_tokens": 1591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3073580168652638, "lm_q2_score": 0.048136771799400395, "lm_q1q2_score": 0.014795222718559462}}
{"text": "/*\n * Copyright (c) Facebook, Inc. and its affiliates.\n * All rights reserved.\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree.\n */\n#pragma once\n#include <chrono>\n#include <functional>\n#include <vector>\n\n#include <immintrin.h>\n\n#ifdef USE_BLAS\n#if __APPLE__\n// not sure whether need to differentiate TARGET_OS_MAC or TARGET_OS_IPHONE,\n// etc.\n#include <Accelerate/Accelerate.h>\n#else\n#include <cblas.h>\n#endif\n#endif\n\n#ifdef _OPENMP\n#include <omp.h>\n#endif\n\n#ifdef USE_MKL\n#include <mkl.h>\n#endif\n\n#include \"./AlignedVec.h\"\n#include \"fbgemm/FbgemmBuild.h\"\n#include \"fbgemm/FbgemmPackMatrixB.h\"\n#include \"src/RefImplementations.h\"\n\nnamespace fbgemm {\n\ntemplate <typename T>\nvoid randFill(aligned_vector<T>& vec, T low, T high);\n\nvoid llc_flush(std::vector<char>& llc);\n\n// Same as omp_get_max_threads() when OpenMP is available, otherwise 1\nint fbgemm_get_max_threads();\n// Same as omp_get_num_threads() when OpenMP is available, otherwise 1\nint fbgemm_get_num_threads();\n// Same as omp_get_thread_num() when OpenMP is available, otherwise 0\nint fbgemm_get_thread_num();\n\ntemplate <typename T>\nNOINLINE float cache_evict(const T& vec) {\n  auto const size = vec.size();\n  auto const elemSize = sizeof(typename T::value_type);\n  auto const dataSize = size * elemSize;\n\n  const char* data = reinterpret_cast<const char*>(vec.data());\n  constexpr int CACHE_LINE_SIZE = 64;\n  // Not having this dummy computation significantly slows down the computation\n  // that follows.\n  float dummy = 0.0f;\n  for (std::size_t i = 0; i < dataSize; i += CACHE_LINE_SIZE) {\n    dummy += data[i] * 1.0f;\n    _mm_mfence();\n#ifndef _MSC_VER\n    asm volatile(\"\" ::: \"memory\");\n#endif\n    _mm_clflush(&data[i]);\n  }\n\n  return dummy;\n}\n\n/**\n * Parse application command line arguments\n *\n */\nint parseArgumentInt(\n    int argc,\n    const char* argv[],\n    const char* arg,\n    int non_exist_val,\n    int def_val);\nbool parseArgumentBool(\n    int argc,\n    const char* argv[],\n    const char* arg,\n    bool def_val);\n\nnamespace {\nstruct empty_flush {\n  void operator()() const {}\n};\n} // namespace\n\n/**\n * @param Fn functor to execute\n * @param Fe data eviction functor\n */\ntemplate <class Fn, class Fe = std::function<void()>>\ndouble measureWithWarmup(\n    Fn&& fn,\n    int warmupIterations,\n    int measuredIterations,\n    const Fe& fe = empty_flush(),\n    bool useOpenMP = false) {\n  for (int i = 0; i < warmupIterations; ++i) {\n    // Evict data first\n    fe();\n    fn();\n  }\n\n  double ttot = 0.0;\n\n#ifdef _OPENMP\n#pragma omp parallel if (useOpenMP)\n  {\n#endif\n    for (int i = 0; i < measuredIterations; ++i) {\n      int thread_id = 0;\n      std::chrono::time_point<std::chrono::high_resolution_clock> start, end;\n\n#ifdef _OPENMP\n      if (useOpenMP) {\n        thread_id = omp_get_thread_num();\n      }\n#endif\n\n      if (thread_id == 0) {\n        fe();\n      }\n\n#ifdef _OPENMP\n      if (useOpenMP) {\n#pragma omp barrier\n      }\n#endif\n      start = std::chrono::high_resolution_clock::now();\n\n      fn();\n\n#ifdef _OPENMP\n      if (useOpenMP) {\n#pragma omp barrier\n      }\n#endif\n\n      end = std::chrono::high_resolution_clock::now();\n      auto dur =\n          std::chrono::duration_cast<std::chrono::nanoseconds>(end - start);\n\n      if (thread_id == 0) {\n        // TODO: measure load imbalance\n        ttot += dur.count();\n      }\n    }\n\n#ifdef _OPENMP\n  }\n#endif\n  return ttot / 1e9 / measuredIterations;\n}\n\n/*\n * @brief Out-of-place transposition for M*N matrix ref.\n * @param M number of rows in input\n * @param K number of columns in input\n */\ntemplate <typename T>\nvoid transpose_matrix(\n    int M,\n    int N,\n    const T* src,\n    int ld_src,\n    T* dst,\n    int ld_dst) {\n  for (int i = 0; i < N; ++i) {\n    for (int j = 0; j < M; ++j) {\n      dst[i * ld_dst + j] = src[i + j * ld_src];\n    }\n  } // for each output row\n}\n\n/*\n * @brief In-place transposition for nxk matrix ref.\n * @param n number of rows in input (number of columns in output)\n * @param k number of columns in input (number of rows in output)\n */\ntemplate <typename T>\nvoid transpose_matrix(T* ref, int n, int k) {\n  std::vector<T> local(n * k);\n  transpose_matrix(n, k, ref, k, local.data(), n);\n  memcpy(ref, local.data(), n * k * sizeof(T));\n}\n\n#if defined(USE_MKL)\nvoid test_xerbla(char* srname, const int* info, int);\n#endif\n\n#define dataset 1\n\ntemplate <typename btype>\nvoid performance_test(\n    int num_instances,\n    bool flush,\n    int repetitions,\n    bool is_mkl) {\n#if defined(USE_MKL)\n  mkl_set_xerbla((XerblaEntry)test_xerbla);\n#endif\n\n  float alpha = 1.f, beta = 1.f;\n  matrix_op_t btran = matrix_op_t::Transpose;\n\n#if dataset == 1\n  const int NITER = (flush) ? 10 : 100;\n  std::vector<std::vector<int>> shapes;\n  for (auto m = 1; m < 120; m++) {\n    // shapes.push_back({m, 128, 512});\n    shapes.push_back({m, 512, 512});\n  }\n\n#elif dataset == 2\n  const int NITER = (flush) ? 10 : 100;\n#include \"shapes_dataset.h\"\n\n#else\n  flush = false;\n  constexpr int NITER = 1;\n  std::vector<std::vector<int>> shapes;\n  std::random_device r;\n  std::default_random_engine generator(r());\n  std::uniform_int_distribution<int> dm(1, 100);\n  std::uniform_int_distribution<int> dnk(1, 1024);\n  for (int i = 0; i < 1000; i++) {\n    int m = dm(generator);\n    int n = dnk(generator);\n    int k = dnk(generator);\n    shapes.push_back({m, n, k});\n  }\n#endif\n\n  std::string type;\n  double gflops, gbs, ttot;\n  for (auto s : shapes) {\n    int m = s[0];\n    int n = s[1];\n    int k = s[2];\n\n    // initialize with small numbers\n    aligned_vector<int> Aint(m * k);\n    randFill(Aint, 0, 4);\n    std::vector<aligned_vector<float>> A;\n    for (int i = 0; i < num_instances; ++i) {\n      A.push_back(aligned_vector<float>(Aint.begin(), Aint.end()));\n    }\n\n    aligned_vector<int> Bint(k * n);\n    randFill(Bint, 0, 4);\n    aligned_vector<float> B(Bint.begin(), Bint.end());\n    std::vector<std::unique_ptr<PackedGemmMatrixB<btype>>> Bp;\n    for (int i = 0; i < num_instances; ++i) {\n      Bp.emplace_back(std::unique_ptr<PackedGemmMatrixB<btype>>(\n          new PackedGemmMatrixB<btype>(btran, k, n, alpha, B.data())));\n    }\n    auto kAligned = ((k * sizeof(float) + 64) & ~63) / sizeof(float);\n    auto nAligned = ((n * sizeof(float) + 64) & ~63) / sizeof(float);\n    std::vector<aligned_vector<float>> Bt(num_instances);\n    auto& Bt_ref = Bt[0];\n\n    if (btran == matrix_op_t::Transpose) {\n      Bt_ref.resize(k * nAligned);\n      for (auto row = 0; row < k; ++row) {\n        for (auto col = 0; col < n; ++col) {\n          Bt_ref[row * nAligned + col] = alpha * B[col * k + row];\n        }\n      }\n    } else {\n      Bt_ref.resize(kAligned * n);\n      for (auto row = 0; row < k; ++row) {\n        for (auto col = 0; col < n; ++col) {\n          Bt_ref[col * kAligned + row] = alpha * B[col * k + row];\n        }\n      }\n    }\n\n    for (auto i = 1; i < num_instances; ++i) {\n      Bt[i] = Bt_ref;\n    }\n\n    std::vector<aligned_vector<float>> C_ref;\n    std::vector<aligned_vector<float>> C_fb;\n    if (beta != 0.0f) {\n      aligned_vector<int> Cint(m * n);\n      randFill(Cint, 0, 4);\n      for (int i = 0; i < num_instances; ++i) {\n        C_ref.push_back(aligned_vector<float>(Cint.begin(), Cint.end()));\n        C_fb.push_back(aligned_vector<float>(Cint.begin(), Cint.end()));\n      }\n    } else {\n      for (int i = 0; i < num_instances; ++i) {\n        C_ref.push_back(aligned_vector<float>(m * n, 1.f));\n        C_fb.push_back(aligned_vector<float>(m * n, NAN));\n      }\n    }\n\n    double nflops = 2.0 * m * n * k;\n    double nbytes = 4.0 * m * k + sizeof(btype) * 1.0 * k * n + 4.0 * m * n;\n\n    // warm up MKL and fbgemm\n    // check correctness at the same time\n    for (auto w = 0; w < 3; w++) {\n#if defined(USE_MKL) || defined(USE_BLAS)\n      cblas_sgemm(\n          CblasRowMajor,\n          CblasNoTrans,\n          CblasNoTrans, // B is pretransposed, if required by operation\n          m,\n          n,\n          k,\n          1.0, // Mutliplication by Alpha is done during transpose of B\n          A[0].data(),\n          k,\n          Bt[0].data(),\n          btran == matrix_op_t::NoTranspose ? kAligned : nAligned,\n          beta,\n          C_ref[0].data(),\n          n);\n#else\n      cblas_sgemm_ref(\n          matrix_op_t::NoTranspose,\n          matrix_op_t::NoTranspose,\n          m,\n          n,\n          k,\n          1.0,\n          A[0].data(),\n          k,\n          Bt[0].data(),\n          (btran == matrix_op_t::NoTranspose) ? kAligned : nAligned,\n          beta,\n          C_ref[0].data(),\n          n);\n#endif\n#ifdef _OPENMP\n#pragma omp parallel if (num_instances == 1)\n#endif\n      {\n        int num_threads = num_instances == 1 ? fbgemm_get_num_threads() : 1;\n        int tid = num_instances == 1 ? fbgemm_get_thread_num() : 0;\n        cblas_gemm_compute(\n            matrix_op_t::NoTranspose,\n            m,\n            A[0].data(),\n            *Bp[0],\n            beta,\n            C_fb[0].data(),\n            tid,\n            num_threads);\n      }\n\n#if defined(USE_MKL) || defined(USE_BLAS)\n      // Compare results\n      for (auto i = 0; i < C_ref[0].size(); i++) {\n        if (std::abs(C_ref[0][i] - C_fb[0][i]) > 1e-3) {\n          fprintf(\n              stderr,\n              \"Error: too high diff between fp32 ref %f and fp16 %f at %d\\n\",\n              C_ref[0][i],\n              C_fb[0][i],\n              i);\n          return;\n        }\n      }\n#endif\n    }\n\n#if defined(USE_MKL)\n    if (is_mkl) {\n      // Gold via MKL sgemm\n      type = \"MKL_FP32\";\n#elif defined(USE_BLAS)\n    type = \"BLAS_FP32\";\n#else\n    type = \"REF_FP32\";\n#endif\n\n      ttot = measureWithWarmup(\n          [&]() {\n            int copy = num_instances == 1 ? 0 : fbgemm_get_thread_num();\n            for (int i = 0; i < repetitions; ++i) {\n#if defined(USE_MKL) || defined(USE_BLAS)\n              cblas_sgemm(\n                  CblasRowMajor,\n                  CblasNoTrans,\n                  CblasNoTrans,\n                  m,\n                  n,\n                  k,\n                  1.0,\n                  A[copy].data(),\n                  k,\n                  Bt[copy].data(),\n                  btran == matrix_op_t::NoTranspose ? kAligned : nAligned,\n                  beta,\n                  C_ref[copy].data(),\n                  n);\n#else\n            cblas_sgemm_ref(\n                matrix_op_t::NoTranspose,\n                matrix_op_t::NoTranspose,\n                m,\n                n,\n                k,\n                1.0,\n                A[copy].data(),\n                k,\n                Bt[copy].data(),\n                (btran == matrix_op_t::NoTranspose) ? kAligned : nAligned,\n                beta,\n                C_ref[copy].data(),\n                n);\n#endif\n            }\n          },\n          3,\n          NITER,\n          [&]() {\n            if (flush) {\n              int copy = num_instances == 1 ? 0 : fbgemm_get_thread_num();\n              cache_evict(A[copy]);\n              cache_evict(Bt[copy]);\n              cache_evict(C_ref[copy]);\n            }\n          },\n          // Use OpenMP if num instances > 1\n          num_instances > 1);\n\n      gflops = nflops / ttot / 1e9;\n      gbs = nbytes / ttot / 1e9;\n      printf(\n          \"\\n%30s m = %5d n = %5d k = %5d Gflops = %8.4lf GBytes = %8.4lf\\n\",\n          type.c_str(),\n          m,\n          n,\n          k,\n          gflops * repetitions,\n          gbs * repetitions);\n#ifdef USE_MKL\n    }\n#endif\n    type = \"FBP_\" + std::string(typeid(btype).name());\n\n    ttot = measureWithWarmup(\n        [&]() {\n          // When executing in data decomposition (single-instance) mode\n          // Different threads will access different regions of the same\n          // matrices. Thus, copy to be used is always 0. The numbers of\n          // threads would be the as number of threads in the parallel\n          // region.\n          // When running in functional decomposition (multi-instance) mode\n          // different matrices are used. The copy to be used selected by\n          // thread_id (thread_num), and the number of threads performance\n          // the compute of the same instance is 1.\n          int copy = num_instances == 1 ? 0 : fbgemm_get_thread_num();\n          int num_threads = num_instances == 1 ? fbgemm_get_num_threads() : 1;\n          int tid = num_instances == 1 ? fbgemm_get_thread_num() : 0;\n\n          for (int i = 0; i < repetitions; ++i) {\n            cblas_gemm_compute(\n                matrix_op_t::NoTranspose,\n                m,\n                A[copy].data(),\n                *Bp[copy],\n                beta,\n                C_fb[copy].data(),\n                tid,\n                num_threads);\n          }\n        },\n        3,\n        NITER,\n        [&]() {\n          if (flush) {\n            int copy = num_instances == 1 ? 0 : fbgemm_get_thread_num();\n            cache_evict(A[copy]);\n            cache_evict(*Bp[copy]);\n            cache_evict(C_fb[copy]);\n          }\n        },\n        true /*useOpenMP*/);\n\n    gflops = nflops / ttot / 1e9;\n    gbs = nbytes / ttot / 1e9;\n    printf(\n        \"%30s m = %5d n = %5d k = %5d Gflops = %8.4lf GBytes = %8.4lf\\n\",\n        type.c_str(),\n        m,\n        n,\n        k,\n        gflops * repetitions,\n        gbs * repetitions);\n  }\n}\n\n} // namespace fbgemm\n", "meta": {"hexsha": "8ce0bfc3b536667aee5d31bc7751292f0ddbffe5", "size": 13256, "ext": "h", "lang": "C", "max_stars_repo_path": "bench/BenchUtils.h", "max_stars_repo_name": "joe7hu/FBGEMM", "max_stars_repo_head_hexsha": "c52008892732932d63829802403b54f551d1560f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bench/BenchUtils.h", "max_issues_repo_name": "joe7hu/FBGEMM", "max_issues_repo_head_hexsha": "c52008892732932d63829802403b54f551d1560f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bench/BenchUtils.h", "max_forks_repo_name": "joe7hu/FBGEMM", "max_forks_repo_head_hexsha": "c52008892732932d63829802403b54f551d1560f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1459566075, "max_line_length": 79, "alphanum_fraction": 0.54993965, "num_tokens": 3729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32082131381216084, "lm_q2_score": 0.046033904362384165, "lm_q1q2_score": 0.01476865767744345}}
{"text": "#ifndef AMICI_SUNDIALS_MATRIX_WRAPPER_H\n#define AMICI_SUNDIALS_MATRIX_WRAPPER_H\n\n#include <sunmatrix/sunmatrix_band.h>   // SUNMatrix_Band\n#include <sunmatrix/sunmatrix_dense.h>  // SUNMatrix_Dense\n#include <sunmatrix/sunmatrix_sparse.h> // SUNMatrix_Sparse\n\n#include <gsl/gsl-lite.hpp>\n\n#include <vector>\n\n#include \"amici/vector.h\"\n\nnamespace amici {\n\n/**\n * @brief A RAII wrapper for SUNMatrix structs.\n *\n * This can create dense, sparse, or banded matrices using the respective\n * constructor.\n */\nclass SUNMatrixWrapper {\n  public:\n    SUNMatrixWrapper() = default;\n\n    /**\n     * @brief Create sparse matrix. See SUNSparseMatrix in sunmatrix_sparse.h\n     * @param M Number of rows\n     * @param N Number of columns\n     * @param NNZ Number of nonzeros\n     * @param sparsetype Sparse type\n     */\n    SUNMatrixWrapper(sunindextype M, sunindextype N, sunindextype NNZ,\n                     int sparsetype);\n\n    /**\n     * @brief Create dense matrix. See SUNDenseMatrix in sunmatrix_dense.h\n     * @param M Number of rows\n     * @param N Number of columns\n     */\n    SUNMatrixWrapper(sunindextype M, sunindextype N);\n\n    /**\n     * @brief Create banded matrix. See SUNBandMatrix in sunmatrix_band.h\n     * @param M Number of rows and columns\n     * @param ubw Upper bandwidth\n     * @param lbw Lower bandwidth\n     */\n    SUNMatrixWrapper(sunindextype M, sunindextype ubw, sunindextype lbw);\n\n    /**\n     * @brief Create sparse matrix from dense or banded matrix. See\n     * SUNSparseFromDenseMatrix and SUNSparseFromBandMatrix in\n     * sunmatrix_sparse.h\n     * @param A Wrapper for dense matrix\n     * @param droptol tolerance for dropping entries\n     * @param sparsetype Sparse type\n     */\n    SUNMatrixWrapper(const SUNMatrixWrapper &A, realtype droptol,\n                     int sparsetype);\n\n    /**\n     * @brief Wrap existing SUNMatrix\n     * @param mat\n     */\n    explicit SUNMatrixWrapper(SUNMatrix mat);\n\n    ~SUNMatrixWrapper();\n\n    /**\n     * @brief Copy constructor\n     * @param other\n     */\n    SUNMatrixWrapper(const SUNMatrixWrapper &other);\n\n    /**\n     * @brief Move constructor\n     * @param other\n     */\n    SUNMatrixWrapper(SUNMatrixWrapper &&other);\n\n    /**\n     * @brief Copy assignment\n     * @param other\n     * @return\n     */\n    SUNMatrixWrapper &operator=(const SUNMatrixWrapper &other);\n\n    /**\n     * @brief Move assignment\n     * @param other\n     * @return\n     */\n    SUNMatrixWrapper &operator=(SUNMatrixWrapper &&other);\n\n    /**\n     * @brief Reallocate space for sparse matrix according to specified nnz\n     * @param nnz new number of nonzero entries\n     */\n    void reallocate(sunindextype nnz);\n\n    /**\n     * @brief Reallocate space for sparse matrix to used space according to last entry in indexptrs\n     */\n    void realloc();\n\n    /**\n     * @brief Get the wrapped SUNMatrix\n     * @return raw SunMatrix object\n     * @note Even though the returned matrix_ pointer is const qualified, matrix_->content will not be const.\n     * This is a shortcoming in the underlying C library, which we cannot address and it is not intended that\n     * any of those values are modified externally. If matrix_->content is manipulated,\n     * cpp:meth:SUNMatrixWrapper:`refresh` needs to be called.\n     */\n    SUNMatrix get() const;\n\n    /**\n     * @brief Get the number of rows\n     * @return number of rows\n     */\n    sunindextype rows() const;\n\n    /**\n     * @brief Get the number of columns\n     * @return number of columns\n     */\n    sunindextype columns() const;\n\n    /**\n     * @brief Get the number of specified non-zero elements (sparse matrices only)\n     * @note value will be 0 before indexptrs are set.\n     * @return number of nonzero entries\n     */\n    sunindextype num_nonzeros() const;\n\n    /**\n     * @brief Get the number of indexptrs that can be specified (sparse matrices only)\n     * @return number of indexptrs\n     */\n    sunindextype num_indexptrs() const;\n\n    /**\n     * @brief Get the number of allocated data elements\n     * @return number of allocated entries\n     */\n    sunindextype capacity() const;\n\n    /**\n     * @brief Get  raw data of a sparse matrix\n     * @return pointer to first data entry\n     */\n    realtype *data();\n\n    /**\n     * @brief Get const raw data of a sparse matrix\n     * @return pointer to first data entry\n     */\n    const realtype *data() const;\n\n    /**\n     * @brief Get data of a sparse matrix\n     * @param idx data index\n     * @return idx-th data entry\n     */\n    realtype get_data(sunindextype idx) const;\n\n    /**\n     * @brief Get data entry for a dense matrix\n     * @param irow row\n     * @param icol col\n     * @return A(irow,icol)\n     */\n    realtype get_data(sunindextype irow, sunindextype icol) const;\n\n    /**\n     * @brief Set data entry for a sparse matrix\n     * @param idx data index\n     * @param data data for idx-th entry\n     */\n    void set_data(sunindextype idx, realtype data);\n\n    /**\n     * @brief Set data entry for a dense matrix\n     * @param irow row\n     * @param icol col\n     * @param data data for idx-th entry\n     */\n    void set_data(sunindextype irow, sunindextype icol, realtype data);\n\n    /**\n     * @brief Get the index value of a sparse matrix\n     * @param idx data index\n     * @return row (CSC) or column (CSR) for idx-th data entry\n     */\n    sunindextype get_indexval(sunindextype idx) const;\n\n    /**\n     * @brief Set the index value of a sparse matrix\n     * @param idx data index\n     * @param val row (CSC) or column (CSR) for idx-th data entry\n     */\n    void set_indexval(sunindextype idx, sunindextype val);\n\n    /**\n     * @brief Set the index values of a sparse matrix\n     * @param vals rows (CSC) or columns (CSR) for data entries\n     */\n    void set_indexvals(const gsl::span<const sunindextype> vals);\n\n    /**\n     * @brief Get the index pointer of a sparse matrix\n     * @param ptr_idx pointer index\n     * @return index where the ptr_idx-th column (CSC) or row (CSR) starts\n     */\n    sunindextype get_indexptr(sunindextype ptr_idx) const;\n\n    /**\n     * @brief Set the index pointer of a sparse matrix\n     * @param ptr_idx pointer index\n     * @param ptr data-index where the ptr_idx-th column (CSC) or row (CSR) starts\n     */\n    void set_indexptr(sunindextype ptr_idx, sunindextype ptr);\n\n    /**\n     * @brief Set the index pointers of a sparse matrix\n     * @param ptrs starting data-indices where the columns (CSC) or rows (CSR) start\n     */\n    void set_indexptrs(const gsl::span<const sunindextype> ptrs);\n\n    /**\n     * @brief Get the type of sparse matrix\n     * @return matrix type\n     */\n    int sparsetype() const;\n\n    /**\n     * @brief multiply with a scalar (in-place)\n     * @param a scalar value to multiply matrix\n     */\n    void scale(realtype a);\n\n    /**\n     * @brief N_Vector interface for multiply\n     * @param c output vector, may already contain values\n     * @param b multiplication vector\n     * @param alpha scalar coefficient for matrix\n     */\n    void multiply(N_Vector c, const_N_Vector b, realtype alpha = 1.0) const;\n\n    /**\n     * @brief Perform matrix vector multiplication c += alpha * A*b\n     * @param c output vector, may already contain values\n     * @param b multiplication vector\n     * @param alpha scalar coefficient\n     */\n    void multiply(gsl::span<realtype> c, gsl::span<const realtype> b,\n                  const realtype alpha = 1.0) const;\n\n    /**\n     * @brief Perform reordered matrix vector multiplication c += A[:,cols]*b\n     * @param c output vector, may already contain values\n     * @param b multiplication vector\n     * @param cols int vector for column reordering\n     * @param transpose bool transpose A before multiplication\n     */\n    void multiply(N_Vector c,\n                  const_N_Vector b,\n                  gsl::span <const int> cols,\n                  bool transpose) const;\n\n    /**\n     * @brief Perform reordered matrix vector multiplication c += A[:,cols]*b\n     * @param c output vector, may already contain values\n     * @param b multiplication vector\n     * @param cols int vector for column reordering\n     * @param transpose bool transpose A before multiplication\n     */\n    void multiply(gsl::span<realtype> c,\n                  gsl::span<const realtype> b,\n                  gsl::span <const int> cols,\n                  bool transpose) const;\n\n    /**\n     * @brief Perform matrix matrix multiplication C = A * B for sparse A, B, C\n     * @param C output matrix,\n     * @param B multiplication matrix\n     * @note will overwrite existing data, indexptrs, indexvals for C, but will use preallocated space for these vars\n     */\n    void sparse_multiply(SUNMatrixWrapper &C,\n                         const SUNMatrixWrapper &B) const;\n\n    /**\n     * @brief Perform sparse matrix matrix addition C = alpha * A +  beta * B\n     * @param A addition matrix\n     * @param alpha scalar A\n     * @param B addition matrix\n     * @param beta scalar B\n     * @note will overwrite existing data, indexptrs, indexvals for C, but will use preallocated space for these vars\n     */\n    void sparse_add(const SUNMatrixWrapper &A, realtype alpha,\n                    const SUNMatrixWrapper &B, realtype beta);\n\n    /**\n     * @brief Perform matrix-matrix addition A = sum(mats(0)...mats(len(mats)))\n     * @param mats vector of sparse matrices\n     * @note will overwrite existing data, indexptrs, indexvals for A, but will use preallocated space for these vars\n     */\n    void sparse_sum(const std::vector<SUNMatrixWrapper> &mats);\n\n    /**\n     * @brief Compute x = x + beta * A(:,k), where x is a dense vector and A(:,k) is sparse, and update\n     * the sparsity pattern for C(:,j) if applicable\n     *\n     * This function currently has two purposes:\n     *   - perform parts of sparse matrix-matrix multiplication C(:,j)=A(:,k)*B(k,j)\n     *    enabled by passing beta=B(k,j), x=C(:,j), C=C, w=sparsity of C(:,j) from B(k,0...j-1), nnz=nnz(C(:,0...j-1)\n     *   - add the k-th column of the sparse matrix A multiplied by beta to the dense vector x.\n     *    enabled by passing beta=*, x=x, C=nullptr, w=nullptr, nnz=*\n     *\n     * @param k column index\n     * @param beta scaling factor\n     * @param w index workspace, (w[i]<mark) indicates non-zeroness of C(i,j) (dimension: m),\n     * if this is a nullptr, sparsity pattern of C will not be updated (if applicable).\n     * @param x dense output vector (dimension: m)\n     * @param mark marker for w to indicate nonzero pattern\n     * @param C sparse output matrix, if this is a nullptr, sparsity pattern of C will not be updated\n     * @param nnz number of nonzeros that were already written to C\n     * @return updated number of nonzeros in C\n     */\n    sunindextype scatter(const sunindextype k, const realtype beta,\n                         sunindextype *w, gsl::span<realtype> x,\n                         const sunindextype mark,\n                         SUNMatrixWrapper *C, sunindextype nnz) const;\n\n    /**\n     * @brief Compute transpose A' of sparse matrix A and writes it to the matrix C = alpha * A'\n     *\n     * @param C output matrix (sparse or dense)\n     * @param alpha scalar multiplier\n     * @param blocksize blocksize for transposition. For full matrix transpose set to ncols/nrows\n     */\n    void transpose(SUNMatrixWrapper &C, const realtype alpha,\n                   sunindextype blocksize) const;\n\n    /**\n     * @brief Writes a sparse matrix A to a dense matrix D.\n     *\n     * @param D dense output matrix\n     */\n    void to_dense(SUNMatrixWrapper &D) const;\n\n    /**\n     * @brief Writes the diagonal of sparse matrix A to a dense vector v.\n     *\n     * @param v dense outut vector\n     */\n    void to_diag(N_Vector v) const;\n\n    /**\n     * @brief Set to 0.0, for sparse matrices also resets indexptr/indexvals\n     */\n    void zero();\n\n    /**\n     * @brief Get matrix id\n     * @return SUNMatrix_ID\n     */\n    SUNMatrix_ID matrix_id() const {return id_;};\n\n    /**\n     * @brief Update internal cache, needs to be called after external manipulation of matrix_->content\n     */\n    void refresh();\n\n  private:\n\n    /**\n     * @brief SUNMatrix to which all methods are applied\n     */\n    SUNMatrix matrix_ {nullptr};\n\n    /**\n     * @brief cache for SUNMatrixGetId(matrix_)\n     */\n    SUNMatrix_ID id_ {SUNMATRIX_CUSTOM};\n\n    /**\n     * @brief cache for SUNMatrixGetId(matrix_)\n     */\n    int sparsetype_ {CSC_MAT};\n\n    /**\n     * @brief cache for SM_INDEXPTRS_S(matrix_)[SM_NP_S(matrix_)]\n     */\n    sunindextype num_nonzeros_ {0};\n    /**\n     * @brief cache for SM_NNZ_S(matrix_)\n     */\n    sunindextype capacity_ {0};\n\n    /**\n     * @brief cache for SM_DATA_S(matrix_)\n     */\n    realtype *data_ {nullptr};\n    /**\n     * @brief cache for SM_INDEXPTRS_S(matrix_)\n     */\n    sunindextype *indexptrs_ {nullptr};\n    /**\n     * @brief cache for SM_INDEXVALS_S(matrix_)\n     */\n    sunindextype *indexvals_ {nullptr};\n\n    /**\n     * @brief cache for SM_ROWS_X(matrix_)\n     */\n    sunindextype num_rows_ {0};\n    /**\n     * @brief cache for SM_COLUMS_X(matrix_)\n     */\n    sunindextype num_columns_ {0};\n    /**\n     * @brief cache for SM_NP_S(matrix_)\n     */\n    sunindextype num_indexptrs_ {0};\n\n    /**\n     * @brief call update_ptrs & update_size\n     */\n    void finish_init();\n    /**\n     * @brief update data_, indexptrs_, indexvals_ if applicable\n     */\n    void update_ptrs();\n    /**\n     * @brief update num_rows_, num_columns_, num_indexptrs if applicable\n     */\n    void update_size();\n    /**\n     * @brief indicator whether this wrapper allocated matrix_ and is responsible for deallocation\n     */\n    bool ownmat = true;\n};\n\n} // namespace amici\n\nnamespace gsl {\n/**\n * @brief Create span from SUNMatrix\n * @param m SUNMatrix\n * @return Created span\n */\ninline span<realtype> make_span(SUNMatrix m)\n{\n    switch (SUNMatGetID(m)) {\n    case SUNMATRIX_DENSE:\n        return span<realtype>(SM_DATA_D(m), SM_LDATA_D(m));\n    case SUNMATRIX_SPARSE:\n        return span<realtype>(SM_DATA_S(m), SM_NNZ_S(m));\n    default:\n        throw amici::AmiException(\"Unimplemented SUNMatrix type for make_span\");\n    }\n}\n} // namespace gsl\n\n#endif // AMICI_SUNDIALS_MATRIX_WRAPPER_H\n", "meta": {"hexsha": "2ccc7622ab0daf286d01e33268a228bf01751632", "size": 14173, "ext": "h", "lang": "C", "max_stars_repo_path": "include/amici/sundials_matrix_wrapper.h", "max_stars_repo_name": "PaulJonasJost/AMICI", "max_stars_repo_head_hexsha": "a5c679b0cce90e192bacf9461d43825de8f675ce", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/amici/sundials_matrix_wrapper.h", "max_issues_repo_name": "PaulJonasJost/AMICI", "max_issues_repo_head_hexsha": "a5c679b0cce90e192bacf9461d43825de8f675ce", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/amici/sundials_matrix_wrapper.h", "max_forks_repo_name": "PaulJonasJost/AMICI", "max_forks_repo_head_hexsha": "a5c679b0cce90e192bacf9461d43825de8f675ce", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-20T14:53:43.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-20T14:53:43.000Z", "avg_line_length": 30.3490364026, "max_line_length": 117, "alphanum_fraction": 0.6336696536, "num_tokens": 3611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25683200276421697, "lm_q2_score": 0.057493273551888456, "lm_q1q2_score": 0.014766112591802499}}
{"text": "/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n#ifndef SINGA_CORE_TENSOR_TENSOR_MATH_CPP_H_\n#define SINGA_CORE_TENSOR_TENSOR_MATH_CPP_H_\n\n#include \"./tensor_math.h\"\n//#include \"./stacktrace.h\"\n#include <math.h>\n\n#include <algorithm>\n#include <cfloat>\n#include <iostream>\n#include <iterator>\n#include <sstream>\n\n#include \"singa/core/common.h\"\n#include \"singa/core/tensor.h\"\n\n#ifdef USE_CBLAS\n#include <cblas.h>\n#endif\n\nnamespace singa {\n\n// ===================== Helper Functions =============================\n\n// generate a traversal_info vector based on the tensor's shape for the\n// traverse_next function to work\nvector<int> generate_traversal_info(const Tensor &x) {\n  vector<int> traversal_info = {};\n  for (size_t n = 0; n < (x.shape().size() + 2); ++n) {\n    traversal_info.push_back(0);\n  }\n  return traversal_info;\n};\n\n// generate shape multipliers\n// for e.g. tensor of shape (3,3), stride (1,3) will have shape multipliers of\n// (3,1)\n// for e.g. tensor of shape (3,3), stride (3,1) will also have shape multipliers\n// of (3,1)\n// this means that the 3rd, 6th, and 9th index of the array will always be the\n// starting element of their respective rows\n// so we need to need use the inner stride when jumping from 1st->2nd element,\n// and outer stride when jumping from 2nd->3rd\nvector<int> generate_shape_multipliers(const Tensor &x) {\n  Shape y_shape = x.shape();\n  if (y_shape.size() == 0) {\n    return {1};\n  }\n  vector<int> shape_multipliers = {1};\n  int cumulative_product = 1;\n\n  for (size_t n = 0; n < (y_shape.size() - 1); ++n) {\n    cumulative_product = cumulative_product * y_shape[y_shape.size() - 1 - n];\n    shape_multipliers.insert(shape_multipliers.begin(), cumulative_product);\n  }\n  return shape_multipliers;\n};\n\n// ******************************************************************************************\n// CPP traversal operations (works on const declarations without modifying\n// tensor variables)\n// ******************************************************************************************\n\n// this function checks whether the next index falls on a special multiplier of\n// the outer shape\n// so the algorithm knows when to jump over/back to a starting element of the\n// outer shape\n// for e.g. in [[1,4,7], [2,5,8], [3,6,9]], elements 1,2,3 are the starting\n// elements of their respective rows\n// this additional check only has 1 loop for 2d matrix\n// but runtime performance might degrade to O(nlog(n)) for higher dimensional\n// tensors\nint determine_order(vector<int> &shape_multipliers, int counter) {\n  for (size_t n = 0; n < (shape_multipliers.size() - 1); ++n) {\n    if ((counter % shape_multipliers[n]) == 0) {\n      return ((shape_multipliers.size()) - 1 - n);\n    }\n  }\n  return 0;\n};\n\n// this function updates the base indexes with the current index after every\n// single traversal step,\n// can be generalized beyond 2d cases\nvoid update_base_index(const Tensor &x, vector<int> &traversal_info) {\n  for (int n = 0; n < (traversal_info[x.shape().size() + 1] + 1); ++n) {\n    traversal_info[n] = traversal_info[x.shape().size()];\n  }\n};\n\n// function to traverse a const strided tensor object\n// it requires an additional vector, traversal_info {0,0,0,0 ...}, comprising\n// (x.shape().size()+2) elements of 0\n// for e.g. 2d matrix:\n// index 0 and 1 store the base row and column index respectively\n// index 2 stores the current index of the traversal\n// index 3 stores the order of the traversal for e.g. if the order is 0,\n// it means the next element can be navigated to using the innermost stride\nvoid traverse_next(const Tensor &x, vector<int> &shape_multipliers,\n                   vector<int> &traversal_info, int counter) {\n  update_base_index(x, traversal_info);\n  traversal_info[x.shape().size() + 1] =\n      determine_order(shape_multipliers, counter);\n  traversal_info[x.shape().size()] =\n      traversal_info[traversal_info[x.shape().size() + 1]] +\n      x.stride()[x.stride().size() - traversal_info[x.shape().size() + 1] - 1];\n};\n\ninline int next_offset(int offset, const vector<size_t> &shape,\n                       const vector<int> &stride, vector<int> *index) {\n  for (int k = shape.size() - 1; k >= 0; k--) {\n    if (index->at(k) + 1 < int(shape.at(k))) {\n      offset += stride.at(k);\n      index->at(k) += 1;\n      break;\n    }\n    index->at(k) = 0;\n    offset -= stride.at(k) * (shape.at(k) - 1);\n  }\n  return offset;\n}\n\ntemplate <typename DType>\nvoid traverse_unary(const Tensor &in, Tensor *out,\n                    std::function<DType(DType)> func) {\n  DType *outPtr = static_cast<DType *>(out->block()->mutable_data());\n  const DType *inPtr = static_cast<const DType *>(in.block()->data());\n  /*\n  vector<int> traversal_info = generate_traversal_info(in);\n  vector<int> shape_multipliers = generate_shape_multipliers(in);\n\n  for (size_t i = 0; i < in.Size(); i++) {\n    outPtr[i] = func(inPtr[traversal_info[in.shape().size()]]);\n    traverse_next(in, shape_multipliers, traversal_info, i + 1);\n  }\n  */\n  CHECK(in.shape() == out->shape());\n  if (in.stride() == out->stride()) {\n    for (size_t i = 0; i < in.Size(); i++) outPtr[i] = func(inPtr[i]);\n  } else {\n    // LOG(INFO) << \"not equal stride\";\n    size_t in_offset = 0, out_offset = 0;\n    vector<int> in_idx(in.nDim(), 0), out_idx(out->nDim(), 0);\n    for (size_t i = 0; i < Product(in.shape()); i++) {\n      outPtr[out_offset] = func(inPtr[in_offset]);\n      out_offset =\n          next_offset(out_offset, out->shape(), out->stride(), &out_idx);\n      in_offset = next_offset(in_offset, in.shape(), in.stride(), &in_idx);\n    }\n  }\n}\n\ntemplate <typename DType>\nvoid traverse_binary(const Tensor &in1, const Tensor &in2, Tensor *out,\n                     std::function<DType(DType, DType)> func) {\n  DType *outPtr = static_cast<DType *>(out->block()->mutable_data());\n  const DType *in1Ptr = static_cast<const DType *>(in1.block()->data());\n  const DType *in2Ptr = static_cast<const DType *>(in2.block()->data());\n  /*\n  vector<int> traversal_info_in1 = generate_traversal_info(in1);\n  vector<int> traversal_info_in2 = generate_traversal_info(in2);\n  vector<int> shape_multipliers_in1 = generate_shape_multipliers(in1);\n  vector<int> shape_multipliers_in2 = generate_shape_multipliers(in2);\n\n  for (size_t i = 0; i < in1.Size(); i++) {\n    outPtr[i] = func(in1Ptr[traversal_info_in1[in1.shape().size()]],\n                     in2Ptr[traversal_info_in2[in2.shape().size()]]);\n    traverse_next(in1, shape_multipliers_in1, traversal_info_in1, i + 1);\n    traverse_next(in2, shape_multipliers_in2, traversal_info_in2, i + 1);\n  }\n  */\n  auto prod = Product(in1.shape());\n  CHECK(in1.shape() == out->shape());\n  CHECK(in2.shape() == out->shape());\n  if ((in1.stride() == out->stride()) && (in2.stride() == in1.stride())) {\n    for (size_t i = 0; i < prod; i++) outPtr[i] = func(in1Ptr[i], in2Ptr[i]);\n  } else {\n    /*\n    LOG(INFO) << \"not equal stride\";\n    std::ostringstream s1, s2, s3, s4, s5, s6;\n    std::copy(in1.stride().begin(), in1.stride().end(),\n    std::ostream_iterator<int>(s1, \", \"));\n    std::copy(in2.stride().begin(), in2.stride().end(),\n    std::ostream_iterator<int>(s2, \", \"));\n    std::copy(out->stride().begin(), out->stride().end(),\n    std::ostream_iterator<int>(s3, \", \"));\n\n    std::copy(in1.shape().begin(), in1.shape().end(),\n    std::ostream_iterator<int>(s4, \", \"));\n    std::copy(in2.shape().begin(), in2.shape().end(),\n    std::ostream_iterator<int>(s5, \", \"));\n    std::copy(out->shape().begin(), out->shape().end(),\n    std::ostream_iterator<int>(s6, \", \"));\n\n    LOG(INFO) << s1.str() << \": \" << s4.str();\n    LOG(INFO) << s2.str() << \": \" << s5.str();\n    LOG(INFO) << s3.str() << \": \" << s6.str();\n    LOG(INFO) << Backtrace();\n    */\n\n    size_t in1_offset = 0, in2_offset = 0, out_offset = 0;\n    vector<int> in1_idx(in1.nDim(), 0), in2_idx(in2.nDim(), 0),\n        out_idx(out->nDim(), 0);\n    for (size_t i = 0; i < prod; i++) {\n      outPtr[out_offset] = func(in1Ptr[in1_offset], in2Ptr[in2_offset]);\n      out_offset =\n          next_offset(out_offset, out->shape(), out->stride(), &out_idx);\n      in1_offset = next_offset(in1_offset, in1.shape(), in1.stride(), &in1_idx);\n      in2_offset = next_offset(in2_offset, in2.shape(), in2.stride(), &in2_idx);\n      // LOG(INFO) <<  in1_offset << \", \" << in2_offset << \", \" << out_offset;\n    }\n  }\n}\n\n// ******************************************************************************************\n// traversal operations end\n// ******************************************************************************************\n\n// ===================== CUDA Functions =============================\n\ntemplate <>\nvoid Abs<float, lang::Cpp>(const Tensor &in, Tensor *out, Context *ctx) {\n  traverse_unary<float>(in, out, [](float x) { return fabs(x); });\n}\n\ntemplate <>\nvoid Erf<float, lang::Cpp>(const Tensor &in, Tensor *out, Context *ctx) {\n  traverse_unary<float>(in, out, [](float x) { return erff(x); });\n}\n\ntemplate <>\nvoid CastCopy<float, half_float::half, lang::Cpp>(const Tensor *src,\n                                                  Tensor *dst, Context *ctx) {\n  half_float::half *dst_array =\n      static_cast<half_float::half *>(dst->block()->mutable_data());\n  const float *src_array = static_cast<const float *>(src->block()->data());\n  for (int i = 0; i < dst->Size(); ++i)\n    dst_array[i] = static_cast<half_float::half>(src_array[i]);\n}\n\ntemplate <>\nvoid CastCopy<half_float::half, float, lang::Cpp>(const Tensor *src,\n                                                  Tensor *dst, Context *ctx) {\n  float *dst_array = static_cast<float *>(dst->block()->mutable_data());\n  const half_float::half *src_array =\n      static_cast<const half_float::half *>(src->block()->data());\n  for (int i = 0; i < dst->Size(); ++i)\n    dst_array[i] = static_cast<float>(src_array[i]);\n}\n\ntemplate <>\nvoid CastCopy<float, int, lang::Cpp>(const Tensor *src, Tensor *dst,\n                                     Context *ctx) {\n  int *dst_array = static_cast<int *>(dst->block()->mutable_data());\n  const float *src_array = static_cast<const float *>(src->block()->data());\n  for (int i = 0; i < dst->Size(); ++i) dst_array[i] = (int)src_array[i];\n}\n\ntemplate <>\nvoid CastCopy<int, float, lang::Cpp>(const Tensor *src, Tensor *dst,\n                                     Context *ctx) {\n  float *dst_array = static_cast<float *>(dst->block()->mutable_data());\n  const int *src_array = static_cast<const int *>(src->block()->data());\n  for (int i = 0; i < dst->Size(); ++i) dst_array[i] = (float)src_array[i];\n}\n\ntemplate <>\nvoid Ceil<float, lang::Cpp>(const Tensor &in, Tensor *out, Context *ctx) {\n  traverse_unary<float>(in, out, [](float x) { return std::ceil(x); });\n}\n\ntemplate <>\nvoid Floor<float, lang::Cpp>(const Tensor &in, Tensor *out, Context *ctx) {\n  traverse_unary<float>(in, out, [](float x) { return std::floor(x); });\n}\n\ntemplate <>\nvoid Round<float, lang::Cpp>(const Tensor &in, Tensor *out, Context *ctx) {\n  traverse_unary<float>(in, out, [](float x) { return std::round(x); });\n}\n\ntemplate <>\nvoid RoundE<float, lang::Cpp>(const Tensor &in, Tensor *out, Context *ctx) {\n  traverse_unary<float>(in, out, [](float x) {\n    float doub = x * 2;\n    if (ceilf(doub) == doub) {\n      return std::round(x / 2) * 2;\n    } else {\n      return std::round(x);\n    }\n  });\n}\n\n#ifdef USE_DNNL\ntemplate <>\nvoid SoftMax<float, lang::Cpp>(const Tensor &in, Tensor *out, Context *ctx) {\n  auto md = dnnl::memory::desc({static_cast<long long>(in.shape()[0]),\n                                static_cast<long long>(in.shape()[1])},\n                               dnnl::memory::data_type::f32,\n                               dnnl::memory::format_tag::ab);\n  auto in_mem = dnnl::memory(md, ctx->dnnl_engine, in.block()->mutable_data());\n  auto out_mem =\n      dnnl::memory(md, ctx->dnnl_engine, out->block()->mutable_data());\n\n  auto softmax_desc =\n      dnnl::softmax_forward::desc(dnnl::prop_kind::forward_scoring, md, 1);\n  auto softmax_prim_desc =\n      dnnl::softmax_forward::primitive_desc(softmax_desc, ctx->dnnl_engine);\n  auto softmax = dnnl::softmax_forward(softmax_prim_desc);\n  softmax.execute(ctx->dnnl_stream,\n                  {{DNNL_ARG_SRC, in_mem}, {DNNL_ARG_DST, out_mem}});\n  ctx->dnnl_stream.wait();\n}\n\ntemplate <>\nvoid SoftMaxBackward<float, lang::Cpp>(const Tensor &in, Tensor *out,\n                                       const Tensor &fdout, Context *ctx) {\n  auto md = dnnl::memory::desc({static_cast<long long>(in.shape()[0]),\n                                static_cast<long long>(in.shape()[1])},\n                               dnnl::memory::data_type::f32,\n                               dnnl::memory::format_tag::ab);\n  auto in_mem = dnnl::memory(md, ctx->dnnl_engine, in.block()->mutable_data());\n  auto fdout_mem =\n      dnnl::memory(md, ctx->dnnl_engine, fdout.block()->mutable_data());\n  auto out_mem =\n      dnnl::memory(md, ctx->dnnl_engine, out->block()->mutable_data());\n\n  auto softmax_desc =\n      dnnl::softmax_forward::desc(dnnl::prop_kind::forward_scoring, md, 1);\n  auto softmax_prim_desc =\n      dnnl::softmax_forward::primitive_desc(softmax_desc, ctx->dnnl_engine);\n\n  auto softmaxbwd_desc = dnnl::softmax_backward::desc(md, md, 1);\n  auto softmaxbwd_prim_desc = dnnl::softmax_backward::primitive_desc(\n      softmaxbwd_desc, ctx->dnnl_engine, softmax_prim_desc);\n  auto softmaxbwd = dnnl::softmax_backward(softmaxbwd_prim_desc);\n  softmaxbwd.execute(ctx->dnnl_stream, {{DNNL_ARG_DIFF_SRC, out_mem},\n                                        {DNNL_ARG_DIFF_DST, in_mem},\n                                        {DNNL_ARG_DST, fdout_mem}});\n  ctx->dnnl_stream.wait();\n}\n#else\n// native Softmax without DNNL\ntemplate <>\nvoid SoftMax<float, lang::Cpp>(const Tensor &in, Tensor *out, Context *ctx) {\n  CHECK_LE(in.nDim(), 2u)\n      << \"Axis is required for SoftMax on multi dimemsional tensor\";\n  out->CopyData(in);\n  size_t nrow = 1, ncol = in.Size(), size = ncol;\n  if (in.nDim() == 2u) {\n    nrow = in.shape(0);\n    ncol = size / nrow;\n    out->Reshape(Shape{nrow, ncol});\n  }\n  Tensor tmp = RowMax(*out);\n  SubColumn(tmp, out);\n  Exp(*out, out);\n\n  SumColumns(*out, &tmp);\n  DivColumn(tmp, out);\n  out->Reshape(in.shape());\n}\n#endif  // USE_DNNL\n\ntemplate <>\nvoid Add<float, lang::Cpp>(const Tensor &in, const float x, Tensor *out,\n                           Context *ctx) {\n  auto add_lambda = [&x](float a) { return (a + x); };\n  traverse_unary<float>(in, out, add_lambda);\n}\n\ntemplate <>\nvoid Add<float, lang::Cpp>(const Tensor &in1, const Tensor &in2, Tensor *out,\n                           Context *ctx) {\n  // CHECK_EQ(ctx->stream, nullptr);\n  auto add_lambda_binary = [](float a, float b) { return (a + b); };\n  traverse_binary<float>(in1, in2, out, add_lambda_binary);\n}\n\ntemplate <>\nvoid Clamp<float, lang::Cpp>(const float low, const float high,\n                             const Tensor &in, Tensor *out, Context *ctx) {\n  auto clamp_lambda = [&low, &high](float a) {\n    if (a < low) {\n      return low;\n    } else if (a > high) {\n      return high;\n    } else {\n      return a;\n    }\n  };\n  traverse_unary<float>(in, out, clamp_lambda);\n}\n\ntemplate <>\nvoid Div<float, lang::Cpp>(const float x, const Tensor &in, Tensor *out,\n                           Context *ctx) {\n  auto const_div = [&x](float a) {\n    CHECK_NE(a, 0.f);\n    return x / a;\n  };\n  traverse_unary<float>(in, out, const_div);\n}\n\ntemplate <>\nvoid Div<float, lang::Cpp>(const Tensor &in1, const Tensor &in2, Tensor *out,\n                           Context *ctx) {\n  auto binary_div = [](float a, float b) {\n    CHECK_NE(b, 0.f);\n    return a / b;\n  };\n  traverse_binary<float>(in1, in2, out, binary_div);\n}\n\ntemplate <>\nvoid EltwiseMult<float, lang::Cpp>(const Tensor &in, const float x, Tensor *out,\n                                   Context *ctx) {\n  auto eltwisemult_lambda = [&x](float a) { return (a * x); };\n  traverse_unary<float>(in, out, eltwisemult_lambda);\n}\n\ntemplate <>\nvoid EltwiseMult<float, lang::Cpp>(const Tensor &in1, const Tensor &in2,\n                                   Tensor *out, Context *ctx) {\n  auto eltwisemult_lambda_binary = [](float a, float b) { return (a * b); };\n  traverse_binary<float>(in1, in2, out, eltwisemult_lambda_binary);\n}\n\ntemplate <>\nvoid ReLUBackward<float, lang::Cpp>(const Tensor &in1, const Tensor &in2,\n                                    Tensor *out, Context *ctx) {\n  auto relubackward_lambda = [](float a, float b) { return (b > 0) ? a : 0.f; };\n  traverse_binary<float>(in1, in2, out, relubackward_lambda);\n}\n\ntemplate <>\nvoid Exp<float, lang::Cpp>(const Tensor &in, Tensor *out, Context *ctx) {\n  traverse_unary<float>(in, out, [](float x) { return exp(x); });\n}\n\ntemplate <>\nvoid GE<float, lang::Cpp>(const Tensor &in, const float x, Tensor *out,\n                          Context *ctx) {\n  auto ge_lambda = [&x](float a) { return (a >= x) ? 1.f : 0.f; };\n  traverse_unary<float>(in, out, ge_lambda);\n}\n\ntemplate <>\nvoid GE<float, lang::Cpp>(const Tensor &in1, const Tensor &in2, Tensor *out,\n                          Context *ctx) {\n  auto ge_lambda_binary = [](float a, float b) { return (a >= b) ? 1.f : 0.f; };\n  traverse_binary<float>(in1, in2, out, ge_lambda_binary);\n}\n\ntemplate <>\nvoid GE<int, lang::Cpp>(const Tensor &in1, const Tensor &in2, Tensor *out,\n                        Context *ctx) {\n  auto ge_lambda_binary = [](int a, int b) { return (a >= b) ? 1.f : 0.f; };\n  traverse_binary<int>(in1, in2, out, ge_lambda_binary);\n}\n\ntemplate <>\nvoid GT<float, lang::Cpp>(const Tensor &in, const float x, Tensor *out,\n                          Context *ctx) {\n  auto gt_lambda = [&x](float a) { return (a > x) ? 1.f : 0.f; };\n  traverse_unary<float>(in, out, gt_lambda);\n}\n\ntemplate <>\nvoid GT<float, lang::Cpp>(const Tensor &in1, const Tensor &in2, Tensor *out,\n                          Context *ctx) {\n  auto gt_lambda_binary = [](float a, float b) { return (a > b) ? 1.f : 0.f; };\n  traverse_binary<float>(in1, in2, out, gt_lambda_binary);\n}\n\ntemplate <>\nvoid GT<int, lang::Cpp>(const Tensor &in1, const Tensor &in2, Tensor *out,\n                        Context *ctx) {\n  auto gt_lambda_binary = [](int a, int b) { return (a > b) ? 1.f : 0.f; };\n  traverse_binary<int>(in1, in2, out, gt_lambda_binary);\n}\n\ntemplate <>\nvoid LE<float, lang::Cpp>(const Tensor &in, const float x, Tensor *out,\n                          Context *ctx) {\n  auto le_lambda = [&x](float a) { return (a <= x) ? 1.f : 0.f; };\n  traverse_unary<float>(in, out, le_lambda);\n}\n\ntemplate <>\nvoid LE<float, lang::Cpp>(const Tensor &in1, const Tensor &in2, Tensor *out,\n                          Context *ctx) {\n  auto le_lambda_binary = [](float a, float b) { return (a <= b) ? 1.f : 0.f; };\n  traverse_binary<float>(in1, in2, out, le_lambda_binary);\n}\n\ntemplate <>\nvoid LE<int, lang::Cpp>(const Tensor &in1, const Tensor &in2, Tensor *out,\n                        Context *ctx) {\n  auto le_lambda_binary = [](int a, int b) { return (a <= b) ? 1.f : 0.f; };\n  traverse_binary<int>(in1, in2, out, le_lambda_binary);\n}\n\ntemplate <>\nvoid Log<float, lang::Cpp>(const Tensor &in, Tensor *out, Context *ctx) {\n  auto ulog = [](float a) {\n    CHECK_GT(a, 0.f);\n    return log(a);\n  };\n  traverse_unary<float>(in, out, ulog);\n}\n\ntemplate <>\nvoid LT<float, lang::Cpp>(const Tensor &in, const float x, Tensor *out,\n                          Context *ctx) {\n  auto lt_lambda = [&x](float a) { return (a < x) ? 1.f : 0.f; };\n  traverse_unary<float>(in, out, lt_lambda);\n}\n\ntemplate <>\nvoid LT<float, lang::Cpp>(const Tensor &in1, const Tensor &in2, Tensor *out,\n                          Context *ctx) {\n  auto lt_lambda_binary = [](float a, float b) { return (a < b) ? 1.f : 0.f; };\n  traverse_binary<float>(in1, in2, out, lt_lambda_binary);\n}\n\ntemplate <>\nvoid LT<int, lang::Cpp>(const Tensor &in1, const Tensor &in2, Tensor *out,\n                        Context *ctx) {\n  auto lt_lambda_binary = [](int a, int b) { return (a < b) ? 1.f : 0.f; };\n  traverse_binary<int>(in1, in2, out, lt_lambda_binary);\n}\n\ntemplate <>\nvoid EQ<float, lang::Cpp>(const Tensor &in, const float x, Tensor *out,\n                          Context *ctx) {\n  auto eq_lambda = [&x](float a) { return (a == x) ? 1.f : 0.f; };\n  traverse_unary<float>(in, out, eq_lambda);\n}\n\ntemplate <>\nvoid EQ<float, lang::Cpp>(const Tensor &in1, const Tensor &in2, Tensor *out,\n                          Context *ctx) {\n  auto eq_lambda_binary = [](float a, float b) { return (a == b) ? 1.f : 0.f; };\n  traverse_binary<float>(in1, in2, out, eq_lambda_binary);\n}\n\ntemplate <>\nvoid EQ<int, lang::Cpp>(const Tensor &in1, const Tensor &in2, Tensor *out,\n                        Context *ctx) {\n  auto eq_lambda_binary = [](int a, int b) { return (a == b) ? 1.f : 0.f; };\n  traverse_binary<int>(in1, in2, out, eq_lambda_binary);\n}\n\ntemplate <>\nvoid Pow<float, lang::Cpp>(const Tensor &in, const float x, Tensor *out,\n                           Context *ctx) {\n  traverse_unary<float>(in, out, [x](float y) { return pow(y, x); });\n}\n\ntemplate <>\nvoid Pow<float, lang::Cpp>(const Tensor &in1, const Tensor &in2, Tensor *out,\n                           Context *ctx) {\n  auto pow_lambda_binary = [](float a, float b) { return pow(a, b); };\n  traverse_binary<float>(in1, in2, out, pow_lambda_binary);\n}\n\ntemplate <>\nvoid ReLU<float, lang::Cpp>(const Tensor &in, Tensor *out, Context *ctx) {\n  auto relu_lambda = [](float a) { return (a >= 0.f) ? a : 0.f; };\n  traverse_unary<float>(in, out, relu_lambda);\n}\n\ntemplate <>\nvoid Set<float, lang::Cpp>(const float x, Tensor *out, Context *ctx) {\n  float *outPtr = static_cast<float *>(out->block()->mutable_data());\n  for (size_t i = 0; i < out->Size(); i++) outPtr[i] = x;\n}\n\ntemplate <>\nvoid Set<int, lang::Cpp>(const int x, Tensor *out, Context *ctx) {\n  int *outPtr = static_cast<int *>(out->block()->mutable_data());\n  for (size_t i = 0; i < out->Size(); i++) outPtr[i] = x;\n}\n\ntemplate <>\nvoid Set<half_float::half, lang::Cpp>(const half_float::half x, Tensor *out,\n                                      Context *ctx) {\n  half_float::half *outPtr =\n      static_cast<half_float::half *>(out->block()->mutable_data());\n  for (size_t i = 0; i < out->Size(); i++) outPtr[i] = x;\n}\n\ntemplate <>\nvoid Sigmoid<float, lang::Cpp>(const Tensor &in, Tensor *out, Context *ctx) {\n  auto sigmoid_lambda = [](float a) { return 1.f / (1.f + exp(-a)); };\n  traverse_unary<float>(in, out, sigmoid_lambda);\n}\n\ntemplate <>\nvoid Sign<float, lang::Cpp>(const Tensor &in, Tensor *out, Context *ctx) {\n  auto sign_lambda = [](float a) { return (a > 0) - (a < 0); };\n  traverse_unary<float>(in, out, sign_lambda);\n}\n\ntemplate <>\nvoid SoftPlus<float, lang::Cpp>(const Tensor &in, Tensor *out, Context *ctx) {\n  auto softplus_lambda = [](float a) { return log(1.f + exp(a)); };\n  traverse_unary<float>(in, out, softplus_lambda);\n}\n\ntemplate <>\nvoid SoftSign<float, lang::Cpp>(const Tensor &in, Tensor *out, Context *ctx) {\n  auto softsign_lambda = [](float a) { return a / (1.f + fabs(a)); };\n  traverse_unary<float>(in, out, softsign_lambda);\n}\n\ntemplate <>\nvoid Sqrt<float, lang::Cpp>(const Tensor &in, Tensor *out, Context *ctx) {\n  auto usqrt = [](float a) {\n    CHECK_GE(a, 0.f);\n    return sqrt(a);\n  };\n  traverse_unary<float>(in, out, usqrt);\n}\n\ntemplate <>\nvoid Sub<float, lang::Cpp>(const Tensor &in1, const Tensor &in2, Tensor *out,\n                           Context *ctx) {\n  // CHECK_EQ(ctx->stream, nullptr);\n  auto sub_lambda_binary = [](float a, float b) { return (a - b); };\n  traverse_binary<float>(in1, in2, out, sub_lambda_binary);\n}\n\n// sum all elements of input into out\n// TODO(wangwei) optimize using omp\ntemplate <>\nvoid Sum<float, lang::Cpp>(const Tensor &in, float *out, Context *ctx) {\n  float s = 0.f;\n  const float *inPtr = static_cast<const float *>(in.block()->data());\n  for (size_t i = 0; i < in.Size(); i++) {\n    s += inPtr[i];\n  }\n  *out = s;\n}\n\n#define GenUnaryTensorCppFn(fn, cppfn)                                     \\\n  template <>                                                              \\\n  void fn<float, lang::Cpp>(const Tensor &in, Tensor *out, Context *ctx) { \\\n    auto fn_lambda = [](float a) { return cppfn(a); };                     \\\n    traverse_unary<float>(in, out, fn_lambda);                             \\\n  }\n\nGenUnaryTensorCppFn(Cos, cos);\nGenUnaryTensorCppFn(Cosh, cosh);\nGenUnaryTensorCppFn(Acos, acos);\nGenUnaryTensorCppFn(Acosh, acosh);\nGenUnaryTensorCppFn(Sin, sin);\nGenUnaryTensorCppFn(Sinh, sinh);\nGenUnaryTensorCppFn(Asin, asin);\nGenUnaryTensorCppFn(Asinh, asinh);\nGenUnaryTensorCppFn(Tan, tan);\nGenUnaryTensorCppFn(Tanh, tanh);\nGenUnaryTensorCppFn(Atan, atan);\nGenUnaryTensorCppFn(Atanh, atanh);\n\ntemplate <>\nvoid Transform<float, lang::Cpp>(const Tensor &in, Tensor *out, Context *ctx) {\n  auto identity = [](float a) { return a; };\n  traverse_unary<float>(in, out, identity);\n}\n\ntemplate <>\nvoid Transform<int, lang::Cpp>(const Tensor &in, Tensor *out, Context *ctx) {\n  auto identity = [](int a) { return a; };\n  traverse_unary<int>(in, out, identity);\n}\n\ntemplate <>\nvoid Transform<half_float::half, lang::Cpp>(const Tensor &in, Tensor *out,\n                                            Context *ctx) {\n  auto identity = [](half_float::half a) { return a; };\n  traverse_unary<half_float::half>(in, out, identity);\n}\n\ntemplate <>\nvoid Bernoulli<float, lang::Cpp>(const float p, Tensor *out, Context *ctx) {\n  std::bernoulli_distribution distribution(p);\n  float *outPtr = static_cast<float *>(out->block()->mutable_data());\n  for (size_t i = 0; i < out->Size(); i++) {\n    outPtr[i] = distribution(ctx->random_generator) ? 1.0f : 0.0f;\n  }\n}\n\ntemplate <>\nvoid Gaussian<float, lang::Cpp>(const float mean, const float std, Tensor *out,\n                                Context *ctx) {\n  std::normal_distribution<float> distribution(mean, std);\n  float *outPtr = static_cast<float *>(out->block()->mutable_data());\n  for (size_t i = 0; i < out->Size(); i++) {\n    outPtr[i] = static_cast<float>(distribution(ctx->random_generator));\n  }\n}\n\ntemplate <>\nvoid Gaussian<half_float::half, lang::Cpp>(const half_float::half mean,\n                                           const half_float::half std,\n                                           Tensor *out, Context *ctx) {\n  Tensor tmp(out->shape(), out->device(), kFloat32);\n  Gaussian<float, lang::Cpp>(static_cast<float>(mean), static_cast<float>(std),\n                             &tmp, ctx);\n  CastCopy<float, half_float::half, lang::Cpp>(&tmp, out, ctx);\n}\n\ntemplate <>\nvoid Uniform<float, lang::Cpp>(const float low, const float high, Tensor *out,\n                               Context *ctx) {\n  std::uniform_real_distribution<float> distribution(low, high);\n  float *outPtr = static_cast<float *>(out->block()->mutable_data());\n  for (size_t i = 0; i < out->Size(); i++) {\n    outPtr[i] = static_cast<float>(distribution(ctx->random_generator));\n  }\n}\n\n// ====================Blas operations======================================\n\n// warning, this function has block M overwritting to block M itself\ntemplate <>\nvoid DGMM<float, lang::Cpp>(const bool side_right, const Tensor &M,\n                            const Tensor &v, Tensor *out, Context *ctx) {\n  const float *MPtr = static_cast<const float *>(M.block()->data());\n  const float *vPtr = static_cast<const float *>(v.block()->data());\n  float *outPtr = static_cast<float *>(out->block()->mutable_data());\n  const size_t nrow = M.shape(0);\n  const size_t ncol = M.shape(1);\n\n  if (side_right) {\n    for (size_t r = 0; r < nrow; r++) {\n      size_t in_offset = M.stride()[0] * r, out_offset = out->stride()[0] * r;\n      for (size_t c = 0; c < ncol; c++) {\n        outPtr[out_offset] = MPtr[in_offset] * vPtr[c];\n        in_offset += M.stride()[1];\n        out_offset += out->stride()[1];\n      }\n    }\n  } else {\n    for (size_t r = 0; r < nrow; r++) {\n      size_t in_offset = M.stride()[0] * r, out_offset = out->stride()[0] * r;\n      for (size_t c = 0; c < ncol; c++) {\n        outPtr[out_offset] = MPtr[in_offset] * vPtr[r];\n        in_offset += M.stride()[1];\n        out_offset += out->stride()[1];\n      }\n    }\n  }\n}\n\n#ifdef USE_CBLAS\ntemplate <>\nvoid Amax<float, lang::Cpp>(const Tensor &in, size_t *out, Context *ctx) {\n  const float *inPtr = static_cast<const float *>(in.block()->data());\n  *out = cblas_isamax(in.Size(), inPtr, 1);  // not using strided traversal\n}\n\ntemplate <>\nvoid Asum<float, lang::Cpp>(const Tensor &in, float *out, Context *ctx) {\n  const float *inPtr = static_cast<const float *>(in.block()->data());\n  *out = cblas_sasum(in.Size(), inPtr, 1);  // not using strided traversal\n}\n\n// template <>\n// void Axpy<float, lang::Cpp>(const float alpha,\n//                             const Tensor& in, Tensor *out, Context *ctx) {\n//   //check input tensor for strides first\n//   if (in.stride() == out->stride()) {\n//     const float *inPtr = static_cast<const float *>(in.block()->data());\n//     float *outPtr = static_cast<float *>(out->block()->mutable_data());\n//     cblas_saxpy(in.Size(), alpha, inPtr, 1, outPtr, 1);\n//   } else {\n//     //LOG(FATAL) << \"Axpy, input and output strides do not match.\" ;\n//     EltwiseMult<float, lang::Cpp>(in, alpha, out, ctx);\n//   }\n// }\n\ntemplate <>\nvoid Axpy<float, lang::Cpp>(const float alpha, const Tensor &in, Tensor *out,\n                            Context *ctx) {\n  // check input tensor for strides first\n  const float *inPtr = static_cast<const float *>(in.block()->data());\n  float *outPtr = static_cast<float *>(out->block()->mutable_data());\n\n  if (in.stride() == out->stride()) {\n    cblas_saxpy(in.Size(), alpha, inPtr, 1, outPtr, 1);\n  } else {\n    // LOG(FATAL) << \"Axpy, input and output strides do not match.\" ;\n    Tensor t(in.shape(), in.device(), in.data_type());\n    EltwiseMult<float, lang::Cpp>(in, alpha, &t, ctx);\n    float *tPtr = static_cast<float *>(t.block()->mutable_data());\n    cblas_saxpy(in.Size(), 1, tPtr, 1, outPtr, 1);\n  }\n}\n\n// template <>\n// void Axpy<float, lang::Cpp>(const float alpha,\n//                            const Tensor& in, Tensor *out, Context *ctx) {\n//  //check input tensor for strides first\n//  if (in.stride() == out->stride()) {\n//    const float *inPtr = static_cast<const float *>(in.block()->data());\n//    float *outPtr = static_cast<float *>(out->block()->mutable_data());\n//    cblas_saxpy(in.Size(), alpha, inPtr, 1, outPtr, 1);\n//  } else if(out->transpose()) {\n//    LOG(FATAL) << \"output is already transposed.\" ;\n//  } else {\n//    LOG(FATAL) << \"Axpy, input and output strides do not match.\" ;\n//  }\n// }\n\ntemplate <>\nvoid Dot<float, lang::Cpp>(const Tensor &in1, const Tensor &in2, float *out,\n                           Context *ctx) {\n  // check input tensor for strides first\n  if (!(in1.transpose()) && !(in2.transpose())) {\n    const float *in1Ptr = static_cast<const float *>(in1.block()->data());\n    const float *in2Ptr = static_cast<const float *>(in2.block()->data());\n    *out = cblas_sdot(in1.Size(), in1Ptr, 1, in2Ptr, 1);\n  } else {\n    LOG(FATAL) << \"Dot, one of the input is tranposed. Not implemented yet.\";\n  }\n}\ntemplate <>\nvoid Dot<float, lang::Cpp>(const Tensor &in1, const Tensor &in2, Tensor *out,\n                           Context *ctx) {\n  // check input tensor for strides first\n  if (!(in1.transpose()) && !(in2.transpose())) {\n    const float *in1Ptr = static_cast<const float *>(in1.block()->data());\n    const float *in2Ptr = static_cast<const float *>(in2.block()->data());\n    float *outPtr = static_cast<float *>(out->block()->mutable_data());\n    *outPtr = cblas_sdot(in1.Size(), in1Ptr, 1, in2Ptr, 1);\n  } else {\n    LOG(FATAL) << \"Dot, one of the input is tranposed. Not implemented yet.\";\n  }\n}\n\ntemplate <>\nvoid Scale<float, lang::Cpp>(const float x, Tensor *out, Context *ctx) {\n  float *outPtr = static_cast<float *>(out->block()->mutable_data());\n  cblas_sscal(out->Size(), x, outPtr, 1);  // not using strided traversal\n}\n\ntemplate <>\nvoid Nrm2<float, lang::Cpp>(const Tensor &in, float *out, Context *ctx) {\n  const float *inPtr = static_cast<const float *>(in.block()->data());\n  *out = cblas_snrm2(in.Size(), inPtr, 1);  // not using strided traversal\n}\n\ntemplate <>\nvoid GEMV<float, lang::Cpp>(const float alpha, const Tensor &A, const Tensor &v,\n                            const float beta, Tensor *out, Context *ctx) {\n  const float *APtr = static_cast<const float *>(A.block()->data());\n  const float *vPtr = static_cast<const float *>(v.block()->data());\n  float *outPtr = static_cast<float *>(out->block()->mutable_data());\n  const size_t m = A.shape()[0];\n  const size_t n = A.shape()[1];\n  if (A.transpose()) {\n    cblas_sgemv(CblasRowMajor, CblasTrans, n, m, alpha, APtr, m, vPtr, 1, beta,\n                outPtr, 1);\n  } else {\n    cblas_sgemv(CblasRowMajor, CblasNoTrans, m, n, alpha, APtr, n, vPtr, 1,\n                beta, outPtr, 1);\n  }\n}\n\ntemplate <>\nvoid GEMM<float, lang::Cpp>(const float alpha, const Tensor &A, const Tensor &B,\n                            const float beta, Tensor *C, Context *ctx) {\n  auto transA = A.transpose();\n  auto transa = transA ? CblasTrans : CblasNoTrans;\n  auto transB = B.transpose();\n  auto transb = transB ? CblasTrans : CblasNoTrans;\n  const size_t nrowA = A.shape()[0];\n  const size_t ncolA = A.shape()[1];\n  const size_t ncolB = B.shape()[1];\n  auto lda = transA ? nrowA : ncolA;\n  auto ldb = transB ? ncolA : ncolB;\n  auto ldc = ncolB;\n  const float *APtr = static_cast<const float *>(A.block()->data());\n  const float *BPtr = static_cast<const float *>(B.block()->data());\n  float *CPtr = static_cast<float *>(C->block()->mutable_data());\n  cblas_sgemm(CblasRowMajor, transa, transb, nrowA, ncolB, ncolA, alpha, APtr,\n              lda, BPtr, ldb, beta, CPtr, ldc);\n}\n\n/*\n * implement matmul for 3d 4d tensor\n *   simulate cblas_sgemm_batch();\n *   which is only available in intel cblas\n */\ntemplate <>\nvoid GEMMBatched<float, lang::Cpp>(const float alpha, const Tensor &A,\n                                   const Tensor &B, const float beta, Tensor *C,\n                                   Context *ctx) {\n  const float *APtr = static_cast<const float *>(A.block()->data());\n  const float *BPtr = static_cast<const float *>(B.block()->data());\n  float *CPtr = static_cast<float *>(C->block()->mutable_data());\n\n  auto transA = A.transpose();\n  auto transa = transA ? CblasTrans : CblasNoTrans;\n  auto transB = B.transpose();\n  auto transb = transB ? CblasTrans : CblasNoTrans;\n\n  const size_t ncolB = B.shape().end()[-1];\n  const size_t nrowA = A.shape().end()[-2];\n  const size_t ncolA = A.shape().end()[-1];\n\n  auto lda = transA ? nrowA : ncolA;\n  auto ldb = transB ? ncolA : ncolB;\n  auto ldc = ncolB;\n  const int group_count = 1;\n\n  size_t group_size = A.shape()[0];                // 3d\n  if (A.nDim() == 4u) group_size *= A.shape()[1];  // 4d\n\n  auto matrix_stride_A = A.shape().end()[-1] * A.shape().end()[-2];\n  auto matrix_stride_B = B.shape().end()[-1] * B.shape().end()[-2];\n  auto matrix_stride_C = C->shape().end()[-1] * C->shape().end()[-2];\n  auto offset_A = 0;\n  auto offset_B = 0;\n  auto offset_C = 0;\n\n  for (int i = 0; i < group_size; i++) {\n    cblas_sgemm(CblasRowMajor, transa, transb, nrowA, ncolB, ncolA, alpha,\n                APtr + offset_A, lda, BPtr + offset_B, ldb, beta,\n                CPtr + offset_C, ldc);\n    offset_A += matrix_stride_A;\n    offset_B += matrix_stride_B;\n    offset_C += matrix_stride_C;\n  }\n}\n\n#else\n\ntemplate <>\nvoid Amax<float, lang::Cpp>(const Tensor &in, size_t *out, Context *ctx) {\n  size_t maxPos = 0;\n  float maxVal = 0;\n  const float *inPtr = static_cast<const float *>(in.block()->data());\n  for (size_t i = 0; i < in.Size(); i++) {  // not using strided traversal\n    if (i == 0) {\n      maxVal = inPtr[i];\n    } else if (inPtr[i] > maxVal) {\n      maxVal = inPtr[i];\n      maxPos = i;\n    }\n  }\n  *out = maxPos;\n}\n\ntemplate <>\nvoid Amin<float, lang::Cpp>(const Tensor &in, size_t *out, Context *ctx) {\n  size_t minPos = 0;\n  float minVal = 0;\n  const float *inPtr = static_cast<const float *>(in.block()->data());\n  for (size_t i = 0; i < in.Size(); i++) {  // not using strided traversal\n    if (i == 0) {\n      minVal = inPtr[i];\n    } else if (inPtr[i] > minVal) {\n      minVal = inPtr[i];\n      minPos = i;\n    }\n  }\n  *out = minPos;\n}\n\ntemplate <>\nvoid Asum<float, lang::Cpp>(const Tensor &in, float *out, Context *ctx) {\n  float sum = 0;\n  const float *inPtr = static_cast<const float *>(in.block()->data());\n  for (size_t i = 0; i < in.Size(); i++) {\n    sum += fabs(inPtr[i]);  // not using strided traversal\n  }\n}\n\ntemplate <>\nvoid Axpy<float, lang::Cpp>(const float alpha, const Tensor &in, Tensor *out,\n                            Context *ctx) {\n  float *outPtr = static_cast<float *>(out->block()->mutable_data());\n  const float *inPtr = static_cast<const float *>(in.block()->data());\n  vector<int> traversal_info = generate_traversal_info(in);\n  vector<int> shape_multipliers = generate_shape_multipliers(in);\n\n  for (size_t i = 0; i < in.Size(); i++) {\n    outPtr[i] += alpha * inPtr[traversal_info[in.shape().size()]];\n    traverse_next(in, shape_multipliers, traversal_info, i + 1);\n  }\n}\n\ntemplate <>\nvoid Scale<float, lang::Cpp>(const float x, Tensor *out, Context *ctx) {\n  float *outPtr = static_cast<float *>(out->block()->mutable_data());\n  for (size_t i = 0; i < out->Size(); i++) {\n    outPtr[i] *= x;  // not using strided traversal\n  }\n}\n\ntemplate <>\nvoid Dot<float, lang::Cpp>(const Tensor &in1, const Tensor &in2, float *out,\n                           Context *ctx) {\n  float sum = 0;\n  // const float *in1Ptr = static_cast<const float *>(in1.data());\n  // const float *in2Ptr = static_cast<const float *>(in2.data());\n  // for (size_t i = 0; i < in.Size(); i++) {\n  //   sum += in1Ptr[i] * in2Ptr[i];\n  // }\n  float *outPtr = static_cast<float *>(out->block()->mutable_data());\n  const float *in1Ptr = static_cast<const float *>(in1.block()->data());\n  const float *in2Ptr = static_cast<const float *>(in2.block()->data());\n  vector<int> traversal_info_in1 = generate_traversal_info(in1);\n  vector<int> traversal_info_in2 = generate_traversal_info(in2);\n  vector<int> shape_multipliers_in1 = generate_shape_multipliers(in1);\n  vector<int> shape_multipliers_in2 = generate_shape_multipliers(in2);\n\n  for (size_t i = 0; i < in1.Size(); i++) {\n    sum += in1Ptr[traversal_info_in1[in1.shape().size()]] *\n           in2Ptr[traversal_info_in2[in2.shape().size()]];\n    traverse_next(in1, shape_multipliers_in1, traversal_info_in1, i + 1);\n    traverse_next(in2, shape_multipliers_in2, traversal_info_in2, i + 1);\n  }\n}\n\ntemplate <>\nvoid GEMV<float, lang::Cpp>(const float alpha, const Tensor &A, const Tensor &v,\n                            const float beta, Tensor *out, Context *ctx) {\n  float *outPtr = static_cast<float *>(out->block()->mutable_data());\n  const float *APtr = static_cast<const float *>(A.block()->data());\n  const float *vPtr = static_cast<const float *>(v.block()->data());\n  bool trans = A.transpose();\n  const size_t m = A.shape(0);\n  const size_t n = A.shape(1);\n  for (size_t r = 0; r < m; r++) {\n    float sum = 0;\n    for (size_t c = 0; c < n; c++) {\n      size_t idx = trans ? c * m + r : r * n + c;\n      sum += APtr[idx] * vPtr[c];\n    }\n    outPtr[r] = alpha * sum + beta * outPtr[r];\n  }\n}\n\n#endif  // USE_CBLAS\ntemplate <>\nvoid ComputeCrossEntropy<float, lang::Cpp>(bool int_target,\n                                           const size_t batchsize,\n                                           const size_t dim, const Tensor &p,\n                                           const Tensor &t, Tensor *loss,\n                                           Context *ctx) {\n  const float *pPtr = static_cast<const float *>(p.block()->data());\n  const int *tPtr = static_cast<const int *>(t.block()->data());\n  float *lossPtr = static_cast<float *>(loss->block()->mutable_data());\n  if (int_target) {\n    for (size_t i = 0; i < batchsize; i++) {\n      int truth_idx = tPtr[i];\n      CHECK_GE(truth_idx, 0);\n      float prob_of_truth = pPtr[i * dim + truth_idx];\n      lossPtr[i] = -std::log((std::max)(prob_of_truth, FLT_MIN));\n    }\n  } else {\n    for (size_t i = 0; i < batchsize; i++) {\n      float sum = 0.f;\n      for (size_t j = 0; j < dim; j++) {\n        sum += tPtr[i * dim + j];\n      }\n      float loss_value = 0.f;\n      for (size_t j = 0, offset = i * dim; j < dim; j++, offset++) {\n        loss_value -=\n            tPtr[offset] / sum * std::log((std::max)(pPtr[offset], FLT_MIN));\n      }\n      lossPtr[i] = loss_value;\n    }\n  }\n}\n\ntemplate <>\nvoid SoftmaxCrossEntropyBwd<float, lang::Cpp>(bool int_target,\n                                              const size_t batchsize,\n                                              const size_t dim, const Tensor &p,\n                                              const Tensor &t, Tensor *grad,\n                                              Context *ctx) {\n  CHECK_EQ(p.block(), grad->block())\n      << \"Use the same pointer to optimize performance\";\n  // const float* pPtr = static_cast<const float*>(p->data());\n  const int *tPtr = static_cast<const int *>(t.block()->data());\n  float *gradPtr = static_cast<float *>(grad->block()->mutable_data());\n\n  if (int_target) {\n    for (size_t i = 0; i < batchsize; i++) {\n      int truth_idx = static_cast<int>(tPtr[i]);\n      CHECK_GE(truth_idx, 0);\n      gradPtr[i * dim + truth_idx] -= 1.0;\n    }\n  } else {\n    for (size_t i = 0; i < batchsize; i++) {\n      float sum = 0.f;\n      for (size_t j = 0; j < dim; j++) {\n        sum += tPtr[i * dim + j];\n      }\n      for (size_t j = 0, offset = i * dim; j < dim; j++, offset++) {\n        gradPtr[offset] -= tPtr[offset] / sum;\n      }\n    }\n  }\n}\n\ntemplate <>\nvoid RowMax<float, lang::Cpp>(const Tensor &in, Tensor *out, Context *ctx) {\n  const float *inPtr = static_cast<const float *>(in.block()->data());\n  float *outPtr = static_cast<float *>(out->block()->mutable_data());\n  const size_t nrow = in.shape()[0];\n  const size_t ncol = in.shape()[1];\n  vector<int> traversal_info = generate_traversal_info(in);\n  vector<int> shape_multipliers = generate_shape_multipliers(in);\n\n  for (size_t r = 0; r < nrow; r++) {\n    int counter_offset = (r * ncol);\n    float maxval = 0;\n    for (size_t c = 0; c < ncol; c++) {\n      maxval = (std::max)(maxval, inPtr[traversal_info[in.shape().size()]]);\n      traverse_next(in, shape_multipliers, traversal_info,\n                    counter_offset + c + 1);\n    }\n    outPtr[r] = maxval;\n  }\n}\n\n// =========Matrix operations ================================================\n/*\ntemplate <>\nvoid SoftMax<float, lang::Cpp>(const Tensor &in, Tensor *out, Context* ctx) {\n  CHECK_LE(in.nDim(), 2u) << \"Axis is required for SoftMax on multi dimemsional\ntensor\";\n  out->CopyData(in);\n  size_t nrow = 1, ncol = in.Size(), size = ncol;\n  if (in.nDim() == 2u) {\n    nrow = in.shape(0);\n    ncol = size / nrow;\n    out->Reshape(Shape{nrow, ncol});\n  }\n  Tensor tmp = RowMax(*out);\n  SubColumn(tmp, out);\n  Exp(*out, out);\n\n  SumColumns(*out, &tmp);\n  DivColumn(tmp, out);\n  out->Reshape(in.shape());\n}\n\ntemplate <>\nvoid AddCol<float, lang::Cpp>(const size_t nrow, const size_t ncol,\n                              const Tensor& A, const Tensor& v, Tensor* out,\n                              Context *ctx) {\n  float *outPtr = static_cast<float *>(out->mutable_data());\n  const float *APtr = static_cast<const float *>(A.data());\n  const float *vPtr = static_cast<const float *>(v.data());\n  for (size_t r = 0; r < nrow; r++) {\n    size_t offset = r * ncol;\n    for (size_t c = 0; c < ncol; c++) {\n      outPtr[offset + c] = APtr[offset + c] + vPtr[r];\n    }\n  }\n}\n\ntemplate <>\nvoid AddRow<float, lang::Cpp>(const size_t nrow, const size_t ncol,\n                              const Tensor& A, const Tensor& v, Tensor* out,\n                              Context *ctx) {\n  float *outPtr = static_cast<float *>(out->mutable_data());\n  const float *APtr = static_cast<const float *>(A.data());\n  const float *vPtr = static_cast<const float *>(v.data());\n  for (size_t r = 0; r < nrow; r++) {\n    size_t offset = r * ncol;\n    for (size_t c = 0; c < ncol; c++) {\n      outPtr[offset + c] = APtr[offset + c] + vPtr[c];\n    }\n  }\n}\ntemplate <>\nvoid Outer<float, lang::Cpp>(const size_t m, const size_t n, const Tensor& in1,\n                             const Tensor& in2, Tensor* out, Context *ctx) {\n  float *outPtr = static_cast<float *>(out->mutable_data());\n  const float *in1Ptr = static_cast<const float *>(in1.data());\n  const float *in2Ptr = static_cast<const float *>(in2.data());\n  for (size_t r = 0; r < m; r++) {\n    size_t offset = r * n;\n    for (size_t c = 0; c < n; c++) {\n      outPtr[offset + c] = in1Ptr[r] * in2Ptr[c];\n    }\n  }\n}\ntemplate <>\nvoid Softmax<float, lang::Cpp>(const size_t nrow, const size_t ncol,\n                               const Tensor& in, Tensor* out, Context *ctx) {\n  float *outPtr = static_cast<float *>(out->mutable_data());\n  const float *inPtr = static_cast<const float *>(in.data());\n  float *bPtr = new float[ncol];\n  for (size_t r = 0; r < nrow; r++) {\n    size_t offset = r * ncol;\n    float denom = 0.f;\n    for (size_t c = 0; c < ncol; c++) {\n      bPtr[c] = exp(inPtr[offset + c]);\n      denom += bPtr[c];\n    }\n    for (size_t c = 0; c < ncol; c++) {\n      size_t idx = offset + c;\n      outPtr[idx] = bPtr[c] / denom;\n    }\n  }\n  delete bPtr;\n}\n\ntemplate <>\nvoid SumColumns<float, lang::Cpp>(const size_t nrow, const size_t ncol,\n                                  const Tensor& in, Tensor* out, Context *ctx) {\n  float *outPtr = static_cast<float *>(out->mutable_data());\n  const float *inPtr = static_cast<const float *>(in.data());\n  for (size_t c = 0; c < ncol; c++) {\n    outPtr[c] = 0.f;\n  }\n  for (size_t r = 0; r < nrow; r++) {\n    size_t offset = r * ncol;\n    for (size_t c = 0; c < ncol; c++) {\n      outPtr[c] += inPtr[offset + c];\n    }\n  }\n}\n\ntemplate <>\nvoid SumRows<float, lang::Cpp>(const size_t nrow, const size_t ncol,\n                               const Tensor& in, Tensor* out, Context *ctx) {\n  float *outPtr = static_cast<float *>(out->mutable_data());\n  const float *inPtr = static_cast<const float *>(in.data());\n  for (size_t r = 0; r < nrow; r++) {\n    size_t offset = r * ncol;\n    outPtr[r] = 0.f;\n    for (size_t c = 0; c < ncol; c++) {\n      outPtr[r] += inPtr[offset + c];\n    }\n  }\n}\n*/\n}  // namespace singa\n\n#endif  // SINGA_CORE_TENSOR_TENSOR_MATH_CPP_H_\n", "meta": {"hexsha": "2c06f632416580a3c0f3264a2a4192ae048d1526", "size": 47051, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/tensor/tensor_math_cpp.h", "max_stars_repo_name": "fukien/incubator-singa", "max_stars_repo_head_hexsha": "a1622a9a036d68c39f8999123d60b68b17c58672", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-25T08:50:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-25T08:50:51.000Z", "max_issues_repo_path": "src/core/tensor/tensor_math_cpp.h", "max_issues_repo_name": "fukien/incubator-singa", "max_issues_repo_head_hexsha": "a1622a9a036d68c39f8999123d60b68b17c58672", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/tensor/tensor_math_cpp.h", "max_forks_repo_name": "fukien/incubator-singa", "max_forks_repo_head_hexsha": "a1622a9a036d68c39f8999123d60b68b17c58672", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.0772261623, "max_line_length": 93, "alphanum_fraction": 0.5951626958, "num_tokens": 13271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29746993014852224, "lm_q2_score": 0.04958901824356765, "lm_q1q2_score": 0.014751241793047863}}
{"text": "#pragma once\n\n#include <unordered_map>\n#include <vector>\n\n#include <gsl/gsl>\n\n#include \"huffman.h\"\n#include \"interface.h\"\n#include \"minqueue.h\"\n\nclass statistics {\n    public:\n    size_t original;\n    size_t modified;\n};\n\nclass huffman_encoder {\n    // Statistics of the current encoding.\n    statistics stats;\n\n    std::unordered_map<char, std::vector<int>> encoding;\n    std::unordered_map<char, int> count_chars(std::vector<char> buf);\n\n    void evaluate(minqueue_node* root, std::vector<int> encoding);\n\n    public:\n    huffman_encoder();\n\n    std::vector<int> encode(std::vector<char> buf);\n\n    void display_encoding();\n    void display_stats();\n};\n", "meta": {"hexsha": "8a010ad971a854658095337e1288897f7a89f68d", "size": 655, "ext": "h", "lang": "C", "max_stars_repo_path": "src/huffman.h", "max_stars_repo_name": "joshleeb/Huffman", "max_stars_repo_head_hexsha": "54660f62c6a7adf7dfb63388ed9e4f4e41306058", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/huffman.h", "max_issues_repo_name": "joshleeb/Huffman", "max_issues_repo_head_hexsha": "54660f62c6a7adf7dfb63388ed9e4f4e41306058", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/huffman.h", "max_forks_repo_name": "joshleeb/Huffman", "max_forks_repo_head_hexsha": "54660f62c6a7adf7dfb63388ed9e4f4e41306058", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.7142857143, "max_line_length": 69, "alphanum_fraction": 0.6854961832, "num_tokens": 151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35577489351363034, "lm_q2_score": 0.04146227730110808, "lm_q1q2_score": 0.01475123729163434}}
{"text": "/***************************************************************************\n *   Copyright (C) 2006 by Reed A. Cartwright                              *\n *   reed@scit.us                                                          *\n *                                                                         *\n *   Permission is hereby granted, free of charge, to any person obtaining *\n *   a copy of this software and associated documentation files (the       *\n *   \"Software\"), to deal in the Software without restriction, including   *\n *   without limitation the rights to use, copy, modify, merge, publish,   *\n *   distribute, sublicense, and/or sell copies of the Software, and to    *\n *   permit persons to whom the Software is furnished to do so, subject to *\n *   the following conditions:                                             *\n *                                                                         *\n *   The above copyright notice and this permission notice shall be        *\n *   included in all copies or substantial portions of the Software.       *\n *                                                                         *\n *   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,       *\n *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    *\n *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\n *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR     *\n *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, *\n *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR *\n *   OTHER DEALINGS IN THE SOFTWARE.                                       *\n ***************************************************************************/\n\n#ifndef EMDEL_H\n#define EMDEL_H\n\n#include <boost/config.hpp>\n#include <boost/program_options.hpp>\nnamespace po = boost::program_options;\n\n#include \"em.h\"\n\nclass emdel_app  {\npublic:\n\temdel_app(int argc, char *argv[]);\n\tvirtual ~emdel_app() { }\n\t\n\tvirtual int run();\n\t\n\tstd::string args_comment() const;\n\n\tpo::options_description desc;\t\n\t\n\t// use X-Macros to specify argument variables\n\tstruct arg_t {\n#\tdefine XCMD(lname, sname, desc, type, def) type V(lname) ;\n#\tinclude \"emdel.cmds\"\n#\tundef XCMD\n\t};\nprotected:\n\targ_t arg;\n\n};\n\n#include <ostream>\n#include <iterator>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n\nnamespace std {\ntemplate<typename _Tp, typename _CharT, typename _Traits>\nbasic_ostream<_CharT, _Traits>&\noperator<<(basic_ostream<_CharT, _Traits>& os, const std::vector<_Tp> &v)\n{\n\tif(v.size() == 1)\n\t{\n\t\tos << v.front();\n\t}\n\telse if(v.size() > 1)\n\t{\n\t\tstd::copy(v.begin(), v.end()-1, std::ostream_iterator<_Tp, _CharT, _Traits>(os, \" \"));\n\t\tos << v.back();\n\t} \n\treturn os;\n}\n}\n\n#ifdef BOOST_WINDOWS\n#\tinclude <process.h>\n#\tdefine getpid _getpid\n#endif\n\ninline unsigned int rand_seed_start()\n{\n\tunsigned int u = static_cast<unsigned int>(time(NULL));\n\tunsigned int v = static_cast<unsigned int>(getpid());\n\tv += (v << 15) + (v >> 3); // Spread 5-decimal PID over 32-bit number\n\treturn u ^ (v + 0x9e3779b9u + (u<<6) + (u>>2));\n}\n\ninline unsigned int rand_seed()\n{\n\tstatic unsigned int u = rand_seed_start();\n\treturn (u = u*1664525u + 1013904223u);\n}\n\nclass gslrand\n{\npublic:\n\ttypedef unsigned int int_type;\n\ttypedef int_type seed_type;\n\ttypedef double real_type;\n\tgslrand() {\n\t\t//gsl_rng_env_setup();\n\t\tT = gsl_rng_mt19937;\n\t\tr = gsl_rng_alloc(T);\n\t}\n\tvirtual ~gslrand() {\n\t\tgsl_rng_free(r);\n\t}\n\t\n\tinline void seed(seed_type s) { gsl_rng_set(r, s); }\n\tinline int_type get() { return gsl_rng_get(r); }\n\tinline int_type operator()() { return get(); }\n\t\n\tinline int_type uniform() { return get(); }\n\tinline int_type uniform(int_type max) { return gsl_rng_uniform_int(r, max); }\n\tinline real_type uniform01() { return gsl_rng_uniform(r); }\n\tinline int_type geometric(real_type p) { return gsl_ran_geometric(r,p); }\n\nprivate:\n\tconst gsl_rng_type *T;\n\tgsl_rng *r;\n};\n\nextern gslrand myrand;\n\n\nvoid set_rand_seed(unsigned int u);\n\n\n#endif\n", "meta": {"hexsha": "6c6da23916b19c8f5f6d97d5ca43730a7a81f4c2", "size": 4029, "ext": "h", "lang": "C", "max_stars_repo_path": "src/emdel.h", "max_stars_repo_name": "reedacartwright/emdel", "max_stars_repo_head_hexsha": "58ea9d4db89c4a1852ba5405ef73c2eca6539ce3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/emdel.h", "max_issues_repo_name": "reedacartwright/emdel", "max_issues_repo_head_hexsha": "58ea9d4db89c4a1852ba5405ef73c2eca6539ce3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-03T16:50:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-23T22:51:19.000Z", "max_forks_repo_path": "src/emdel.h", "max_forks_repo_name": "reedacartwright/emdel", "max_forks_repo_head_hexsha": "58ea9d4db89c4a1852ba5405ef73c2eca6539ce3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0671641791, "max_line_length": 88, "alphanum_fraction": 0.5961777116, "num_tokens": 937, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35577489351363034, "lm_q2_score": 0.041462274043902674, "lm_q1q2_score": 0.014751236132802433}}
{"text": "/***************************************************************************\r\n * data_cf.h is part of Math Graphic Library\r\n * Copyright (C) 2007-2016 Alexey Balakin <mathgl.abalakin@gmail.ru>       *\r\n *                                                                         *\r\n *   This program is free software; you can redistribute it and/or modify  *\r\n *   it under the terms of the GNU Library General Public License as       *\r\n *   published by the Free Software Foundation; either version 3 of the    *\r\n *   License, or (at your option) any later version.                       *\r\n *                                                                         *\r\n *   This program is distributed in the hope that it will be useful,       *\r\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\r\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\r\n *   GNU General Public License for more details.                          *\r\n *                                                                         *\r\n *   You should have received a copy of the GNU Library General Public     *\r\n *   License along with this program; if not, write to the                 *\r\n *   Free Software Foundation, Inc.,                                       *\r\n *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *\r\n ***************************************************************************/\r\n#ifndef _MGL_DATA_CF_H_\r\n#define _MGL_DATA_CF_H_\r\n//-----------------------------------------------------------------------------\r\n#include \"mgl2/abstract.h\"\r\n//-----------------------------------------------------------------------------\r\n#if MGL_HAVE_GSL\r\n#include <gsl/gsl_vector.h>\r\n#include <gsl/gsl_matrix.h>\r\n#else\r\n#ifdef __cplusplus\r\nstruct gsl_vector;\r\nstruct gsl_matrix;\r\n#else\r\ntypedef void gsl_vector;\r\ntypedef void gsl_matrix;\r\n#endif\r\n#endif\r\n//-----------------------------------------------------------------------------\r\n#ifdef __cplusplus\r\nextern \"C\" {\r\n#endif\r\n/// Get integer power of x\r\ndouble MGL_EXPORT_CONST mgl_ipow(double x,int n);\r\ndouble MGL_EXPORT_PURE mgl_ipow_(mreal *x,int *n);\r\n/// Get number of seconds since 1970 for given string\r\ndouble MGL_EXPORT mgl_get_time(const char *time, const char *fmt);\r\ndouble MGL_EXPORT mgl_get_time_(const char *time, const char *fmt,int,int);\r\n\r\n/// Create HMDT object\r\nHMDT MGL_EXPORT mgl_create_data();\r\nuintptr_t MGL_EXPORT mgl_create_data_();\r\n/// Create HMDT object with specified sizes\r\nHMDT MGL_EXPORT mgl_create_data_size(long nx, long ny, long nz);\r\nuintptr_t MGL_EXPORT mgl_create_data_size_(int *nx, int *ny, int *nz);\r\n/// Create HMDT object with data from file\r\nHMDT MGL_EXPORT mgl_create_data_file(const char *fname);\r\nuintptr_t MGL_EXPORT mgl_create_data_file_(const char *fname, int len);\r\n/// Delete HMDT object\r\nvoid MGL_EXPORT mgl_delete_data(HMDT dat);\r\nvoid MGL_EXPORT mgl_delete_data_(uintptr_t *dat);\r\n\r\n/// Rearange data dimensions\r\nvoid MGL_EXPORT mgl_data_rearrange(HMDT dat, long mx,long my,long mz);\r\nvoid MGL_EXPORT mgl_data_rearrange_(uintptr_t *dat, int *mx, int *my, int *mz);\r\n/// Link external data array (don't delete it at exit)\r\nvoid MGL_EXPORT mgl_data_link(HMDT dat, mreal *A,long mx,long my,long mz);\r\nvoid MGL_EXPORT mgl_data_link_(uintptr_t *d, mreal *A, int *nx,int *ny,int *nz);\r\n/// Allocate memory and copy the data from the (float *) array\r\nvoid MGL_EXPORT mgl_data_set_float(HMDT dat, const float *A,long mx,long my,long mz);\r\nvoid MGL_EXPORT mgl_data_set_float_(uintptr_t *dat, const float *A,int *NX,int *NY,int *NZ);\r\nvoid MGL_EXPORT mgl_data_set_float1_(uintptr_t *d, const float *A,int *N1);\r\n/// Allocate memory and copy the data from the (double *) array\r\nvoid MGL_EXPORT mgl_data_set_double(HMDT dat, const double *A,long mx,long my,long mz);\r\nvoid MGL_EXPORT mgl_data_set_double_(uintptr_t *dat, const double *A,int *NX,int *NY,int *NZ);\r\nvoid MGL_EXPORT mgl_data_set_double1_(uintptr_t *d, const double *A,int *N1);\r\n/// Allocate memory and copy the data from the (float **) array\r\nvoid MGL_EXPORT mgl_data_set_float2(HMDT d, float const * const *A,long N1,long N2);\r\nvoid MGL_EXPORT mgl_data_set_float2_(uintptr_t *d, const float *A,int *N1,int *N2);\r\n/// Allocate memory and copy the data from the (double **) array\r\nvoid MGL_EXPORT mgl_data_set_double2(HMDT d, double const * const *A,long N1,long N2);\r\nvoid MGL_EXPORT mgl_data_set_double2_(uintptr_t *d, const double *A,int *N1,int *N2);\r\n/// Allocate memory and copy the data from the (float ***) array\r\nvoid MGL_EXPORT mgl_data_set_float3(HMDT d, float const * const * const *A,long N1,long N2,long N3);\r\nvoid MGL_EXPORT mgl_data_set_float3_(uintptr_t *d, const float *A,int *N1,int *N2,int *N3);\r\n/// Allocate memory and copy the data from the (double ***) array\r\nvoid MGL_EXPORT mgl_data_set_double3(HMDT d, double const * const * const *A,long N1,long N2,long N3);\r\nvoid MGL_EXPORT mgl_data_set_double3_(uintptr_t *d, const double *A,int *N1,int *N2,int *N3);\r\n/// Import data from abstract type\r\nvoid MGL_EXPORT mgl_data_set(HMDT dat, HCDT a);\r\nvoid MGL_EXPORT mgl_data_set_(uintptr_t *dat, uintptr_t *a);\r\n/// Allocate memory and copy the data from the gsl_vector\r\nvoid MGL_EXPORT mgl_data_set_vector(HMDT dat, gsl_vector *v);\r\n/// Allocate memory and copy the data from the gsl_matrix\r\nvoid MGL_EXPORT mgl_data_set_matrix(HMDT dat, gsl_matrix *m);\r\n/// Set value of data element [i,j,k]\r\nvoid MGL_EXPORT mgl_data_set_value(HMDT dat, mreal v, long i, long j, long k);\r\nvoid MGL_EXPORT mgl_data_set_value_(uintptr_t *d, mreal *v, int *i, int *j, int *k);\r\n/// Get value of data element [i,j,k]\r\nmreal MGL_EXPORT mgl_data_get_value(HCDT dat, long i, long j, long k);\r\nmreal MGL_EXPORT mgl_data_get_value_(uintptr_t *d, int *i, int *j, int *k);\r\n/// Allocate memory and scanf the data from the string\r\nvoid MGL_EXPORT mgl_data_set_values(HMDT dat, const char *val, long nx, long ny, long nz);\r\nvoid MGL_EXPORT mgl_data_set_values_(uintptr_t *d, const char *val, int *nx, int *ny, int *nz, int l);\r\n\r\n/// Read data array from HDF file (parse HDF4 and HDF5 files)\r\nint MGL_EXPORT mgl_data_read_hdf(HMDT d,const char *fname,const char *data);\r\nint MGL_EXPORT mgl_data_read_hdf_(uintptr_t *d, const char *fname, const char *data,int l,int n);\r\n/// Read data from tab-separated text file with auto determining size\r\nint MGL_EXPORT mgl_data_read(HMDT dat, const char *fname);\r\nint MGL_EXPORT mgl_data_read_(uintptr_t *d, const char *fname,int l);\r\n/// Read data from text file with size specified at beginning of the file\r\nint MGL_EXPORT mgl_data_read_mat(HMDT dat, const char *fname, long dim);\r\nint MGL_EXPORT mgl_data_read_mat_(uintptr_t *dat, const char *fname, int *dim, int);\r\n/// Read data from text file with specifeid size\r\nint MGL_EXPORT mgl_data_read_dim(HMDT dat, const char *fname,long mx,long my,long mz);\r\nint MGL_EXPORT mgl_data_read_dim_(uintptr_t *dat, const char *fname,int *mx,int *my,int *mz,int);\r\n/// Read data from tab-separated text files with auto determining size which filenames are result of sprintf(fname,templ,t) where t=from:step:to\r\nint MGL_EXPORT mgl_data_read_range(HMDT d, const char *templ, double n1, double n2, double step, int as_slice);\r\nint MGL_EXPORT mgl_data_read_range_(uintptr_t *d, const char *fname, mreal *n1, mreal *n2, mreal *step, int *as_slice,int l);\r\n/// Read data from tab-separated text files with auto determining size which filenames are satisfied to template (like \"t_*.dat\")\r\nint MGL_EXPORT mgl_data_read_all(HMDT dat, const char *templ, int as_slice);\r\nint MGL_EXPORT mgl_data_read_all_(uintptr_t *d, const char *fname, int *as_slice,int l);\r\n/// Import data array from PNG file according color scheme\r\nvoid MGL_EXPORT mgl_data_import(HMDT dat, const char *fname, const char *scheme,mreal v1,mreal v2);\r\nvoid MGL_EXPORT mgl_data_import_(uintptr_t *dat, const char *fname, const char *scheme,mreal *v1,mreal *v2,int,int);\r\n/// Scan textual file for template and fill data array\r\nint MGL_EXPORT mgl_data_scan_file(HMDT dat,const char *fname, const char *templ);\r\nint MGL_EXPORT mgl_data_scan_file_(uintptr_t *dat,const char *fname, const char *templ,int,int);\r\n/// Read data array from Tektronix WFM file\r\n/** Parse Tektronix TDS5000/B, TDS6000/B/C, TDS/CSA7000/B, MSO70000/C, DSA70000/B/C DPO70000/B/C DPO7000/ MSO/DPO5000. */\r\nint MGL_EXPORT mgl_data_read_wfm(HMDT d,const char *fname, long num, long step, long start);\r\nint MGL_EXPORT mgl_data_read_wfm_(uintptr_t *d, const char *fname, long *num, long *step, long *start,int l);\r\n/// Read data array from Matlab MAT file (parse versions 4 and 5)\r\nint MGL_EXPORT mgl_data_read_matlab(HMDT d,const char *fname,const char *data);\r\nint MGL_EXPORT mgl_data_read_matlab_(uintptr_t *d, const char *fname, const char *data,int l,int n);\r\n\r\n/// Create or recreate the array with specified size and fill it by zero\r\nvoid MGL_EXPORT mgl_data_create(HMDT dat, long nx,long ny,long nz);\r\nvoid MGL_EXPORT mgl_data_create_(uintptr_t *dat, int *nx,int *ny,int *nz);\r\n/// Transpose dimensions of the data (generalization of Transpose)\r\nvoid MGL_EXPORT mgl_data_transpose(HMDT dat, const char *dim);\r\nvoid MGL_EXPORT mgl_data_transpose_(uintptr_t *dat, const char *dim,int);\r\n/// Normalize the data to range [v1,v2]\r\nvoid MGL_EXPORT mgl_data_norm(HMDT dat, mreal v1,mreal v2,int sym,long dim);\r\nvoid MGL_EXPORT mgl_data_norm_(uintptr_t *dat, mreal *v1,mreal *v2,int *sym,int *dim);\r\n/// Normalize the data to range [v1,v2] slice by slice\r\nvoid MGL_EXPORT mgl_data_norm_slice(HMDT dat, mreal v1,mreal v2,char dir,long keep_en,long sym);\r\nvoid MGL_EXPORT mgl_data_norm_slice_(uintptr_t *dat, mreal *v1,mreal *v2,char *dir,int *keep_en,int *sym,int l);\r\n/// Limit the data to be inside [-v,v], keeping the original sign\r\nvoid MGL_EXPORT mgl_data_limit(HMDT dat, mreal v);\r\nvoid MGL_EXPORT mgl_data_limit_(uintptr_t *dat, mreal *v);\r\n/// Project the periodical data to range [v1,v2] (like mod() function). Separate branches by NAN if sep=true.\r\nvoid MGL_EXPORT mgl_data_coil(HMDT dat, mreal v1, mreal v2, int sep);\r\nvoid MGL_EXPORT mgl_data_coil_(uintptr_t *dat, mreal *v1, mreal *v2, int *sep);\r\n\r\n/// Get sub-array of the data with given fixed indexes\r\nHMDT MGL_EXPORT mgl_data_subdata(HCDT dat, long xx,long yy,long zz);\r\nuintptr_t MGL_EXPORT mgl_data_subdata_(uintptr_t *dat, int *xx,int *yy,int *zz);\r\n/// Get sub-array of the data with given fixed indexes (like indirect access)\r\nHMDT MGL_EXPORT mgl_data_subdata_ext(HCDT dat, HCDT xx, HCDT yy, HCDT zz);\r\nuintptr_t MGL_EXPORT mgl_data_subdata_ext_(uintptr_t *dat, uintptr_t *xx,uintptr_t *yy,uintptr_t *zz);\r\n/// Get column (or slice) of the data filled by formulas of named columns\r\nHMDT MGL_EXPORT mgl_data_column(HCDT dat, const char *eq);\r\nuintptr_t MGL_EXPORT mgl_data_column_(uintptr_t *dat, const char *eq,int l);\r\n/// Get data from sections ids, separated by value val along specified direction.\r\n/** If section id is negative then reverse order is used (i.e. -1 give last section). */\r\nHMDT MGL_EXPORT mgl_data_section(HCDT dat, HCDT ids, char dir, mreal val);\r\nuintptr_t MGL_EXPORT mgl_data_section_(uintptr_t *d, uintptr_t *ids, const char *dir, mreal *val,int);\r\n/// Get data from section id, separated by value val along specified direction.\r\n/** If section id is negative then reverse order is used (i.e. -1 give last section). */\r\nHMDT MGL_EXPORT mgl_data_section_val(HCDT dat, long id, char dir, mreal val);\r\nuintptr_t MGL_EXPORT mgl_data_section_val_(uintptr_t *d, int *id, const char *dir, mreal *val,int);\r\n/// Get contour lines for dat[i,j]=val. NAN values separate the the curves\r\nHMDT mgl_data_conts(mreal val, HCDT dat);\r\n\r\n/// Equidistantly fill the data to range [x1,x2] in direction dir\r\nvoid MGL_EXPORT mgl_data_fill(HMDT dat, mreal x1,mreal x2,char dir);\r\nvoid MGL_EXPORT mgl_data_fill_(uintptr_t *dat, mreal *x1,mreal *x2,const char *dir,int);\r\n/// Modify the data by specified formula assuming x,y,z in range [r1,r2]\r\nvoid MGL_EXPORT mgl_data_fill_eq(HMGL gr, HMDT dat, const char *eq, HCDT vdat, HCDT wdat,const char *opt);\r\nvoid MGL_EXPORT mgl_data_fill_eq_(uintptr_t *gr, uintptr_t *dat, const char *eq, uintptr_t *vdat, uintptr_t *wdat,const char *opt, int, int);\r\n/// Fill dat by interpolated values of vdat parametrically depended on xdat for x in range [x1,x2] using global spline\r\nvoid MGL_EXPORT mgl_data_refill_gs(HMDT dat, HCDT xdat, HCDT vdat, mreal x1, mreal x2, long sl);\r\nvoid MGL_EXPORT mgl_data_refill_gs_(uintptr_t *dat, uintptr_t *xdat, uintptr_t *vdat, mreal *x1, mreal *x2, long *sl);\r\n/// Fill dat by interpolated values of vdat parametrically depended on xdat for x in range [x1,x2]\r\nvoid MGL_EXPORT mgl_data_refill_x(HMDT dat, HCDT xdat, HCDT vdat, mreal x1, mreal x2, long sl);\r\nvoid MGL_EXPORT mgl_data_refill_x_(uintptr_t *dat, uintptr_t *xdat, uintptr_t *vdat, mreal *x1, mreal *x2, long *sl);\r\n/// Fill dat by interpolated values of vdat parametrically depended on xdat,ydat for x,y in range [x1,x2]*[y1,y2]\r\nvoid MGL_EXPORT mgl_data_refill_xy(HMDT dat, HCDT xdat, HCDT ydat, HCDT vdat, mreal x1, mreal x2, mreal y1, mreal y2, long sl);\r\nvoid MGL_EXPORT mgl_data_refill_xy_(uintptr_t *dat, uintptr_t *xdat, uintptr_t *ydat, uintptr_t *vdat, mreal *x1, mreal *x2, mreal *y1, mreal *y2, long *sl);\r\n/// Fill dat by interpolated values of vdat parametrically depended on xdat,ydat,zdat for x,y,z in range [x1,x2]*[y1,y2]*[z1,z2]\r\nvoid MGL_EXPORT mgl_data_refill_xyz(HMDT dat, HCDT xdat, HCDT ydat, HCDT zdat, HCDT vdat, mreal x1, mreal x2, mreal y1, mreal y2, mreal z1, mreal z2);\r\nvoid MGL_EXPORT mgl_data_refill_xyz_(uintptr_t *dat, uintptr_t *xdat, uintptr_t *ydat, uintptr_t *zdat, uintptr_t *vdat, mreal *x1, mreal *x2, mreal *y1, mreal *y2, mreal *z1, mreal *z2);\r\n/// Fill dat by interpolated values of vdat parametrically depended on xdat,ydat,zdat for x,y,z in axis range\r\nvoid MGL_EXPORT mgl_data_refill_gr(HMGL gr, HMDT dat, HCDT xdat, HCDT ydat, HCDT zdat, HCDT vdat, long sl, const char *opt);\r\nvoid MGL_EXPORT mgl_data_refill_gr_(uintptr_t *gr, uintptr_t *dat, uintptr_t *xdat, uintptr_t *ydat, uintptr_t *zdat, uintptr_t *vdat, long *sl, const char *opt,int);\r\n/// Set the data by triangulated surface values assuming x,y,z in range [r1,r2]\r\nvoid MGL_EXPORT mgl_data_grid(HMGL gr, HMDT d, HCDT xdat, HCDT ydat, HCDT zdat,const char *opt);\r\nvoid MGL_EXPORT mgl_data_grid_(uintptr_t *gr, uintptr_t *dat, uintptr_t *xdat, uintptr_t *ydat, uintptr_t *zdat, const char *opt,int);\r\n/// Set the data by triangulated surface values assuming x,y,z in range [x1,x2]*[y1,y2]\r\nvoid MGL_EXPORT mgl_data_grid_xy(HMDT d, HCDT xdat, HCDT ydat, HCDT zdat, mreal x1, mreal x2, mreal y1, mreal y2);\r\nvoid MGL_EXPORT mgl_data_grid_xy_(uintptr_t *dat, uintptr_t *xdat, uintptr_t *ydat, uintptr_t *zdat, mreal *x1, mreal *x2, mreal *y1, mreal *y2);\r\n/// Put value to data element(s)\r\nvoid MGL_EXPORT mgl_data_put_val(HMDT dat, mreal val, long i, long j, long k);\r\nvoid MGL_EXPORT mgl_data_put_val_(uintptr_t *dat, mreal *val, int *i, int *j, int *k);\r\n/// Put array to data element(s)\r\nvoid MGL_EXPORT mgl_data_put_dat(HMDT dat, HCDT val, long i, long j, long k);\r\nvoid MGL_EXPORT mgl_data_put_dat_(uintptr_t *dat, uintptr_t *val, int *i, int *j, int *k);\r\n/// Modify the data by specified formula\r\nvoid MGL_EXPORT mgl_data_modify(HMDT dat, const char *eq,long dim);\r\nvoid MGL_EXPORT mgl_data_modify_(uintptr_t *dat, const char *eq,int *dim,int);\r\n/// Modify the data by specified formula\r\nvoid MGL_EXPORT mgl_data_modify_vw(HMDT dat, const char *eq,HCDT vdat,HCDT wdat);\r\nvoid MGL_EXPORT mgl_data_modify_vw_(uintptr_t *dat, const char *eq, uintptr_t *vdat, uintptr_t *wdat,int);\r\n/// Reduce size of the data\r\nvoid MGL_EXPORT mgl_data_squeeze(HMDT dat, long rx,long ry,long rz,long smooth);\r\nvoid MGL_EXPORT mgl_data_squeeze_(uintptr_t *dat, int *rx,int *ry,int *rz,int *smooth);\r\n\r\n/// Get array which is n-th pairs {x[i],y[i]} for iterated function system (fractal) generated by A\r\n/** NOTE: A.nx must be >= 7. */\r\nHMDT MGL_EXPORT mgl_data_ifs_2d(HCDT A, long n, long skip);\r\nuintptr_t MGL_EXPORT mgl_data_ifs_2d_(uintptr_t *A, long *n, long *skip);\r\n/// Get array which is n-th points {x[i],y[i],z[i]} for iterated function system (fractal) generated by A\r\n/** NOTE: A.nx must be >= 13. */\r\nHMDT MGL_EXPORT mgl_data_ifs_3d(HCDT A, long n, long skip);\r\nuintptr_t MGL_EXPORT mgl_data_ifs_3d_(uintptr_t *A, long *n, long *skip);\r\n/// Get array which is n-th points {x[i],y[i],z[i]} for iterated function system (fractal) defined in *.ifs file 'fname' and named as 'name'\r\nHMDT MGL_EXPORT mgl_data_ifs_file(const char *fname, const char *name, long n, long skip);\r\nuintptr_t mgl_data_ifs_file_(const char *fname, const char *name, long *n, long *skip,int l,int m);\r\n/// Codes for flame fractal functions\r\nenum {\r\n\tmglFlame2d_linear=0,\tmglFlame2d_sinusoidal,\tmglFlame2d_spherical,\tmglFlame2d_swirl,\t\tmglFlame2d_horseshoe,\r\n\tmglFlame2d_polar,\t\tmglFlame2d_handkerchief,mglFlame2d_heart,\t\tmglFlame2d_disc,\t\tmglFlame2d_spiral,\r\n\tmglFlame2d_hyperbolic,\tmglFlame2d_diamond,\t\tmglFlame2d_ex,\t\t\tmglFlame2d_julia,\t\tmglFlame2d_bent,\r\n\tmglFlame2d_waves,\t\tmglFlame2d_fisheye,\t\tmglFlame2d_popcorn,\t\tmglFlame2d_exponential,\tmglFlame2d_power,\r\n\tmglFlame2d_cosine,\t\tmglFlame2d_rings,\t\tmglFlame2d_fan,\t\t\tmglFlame2d_blob,\t\tmglFlame2d_pdj,\r\n\tmglFlame2d_fan2,\t\tmglFlame2d_rings2,\t\tmglFlame2d_eyefish,\t\tmglFlame2d_bubble,\t\tmglFlame2d_cylinder,\r\n\tmglFlame2d_perspective,\tmglFlame2d_noise,\t\tmglFlame2d_juliaN,\t\tmglFlame2d_juliaScope,\tmglFlame2d_blur,\r\n\tmglFlame2d_gaussian,\tmglFlame2d_radialBlur,\tmglFlame2d_pie,\t\t\tmglFlame2d_ngon,\t\tmglFlame2d_curl,\r\n\tmglFlame2d_rectangles,\tmglFlame2d_arch,\t\tmglFlame2d_tangent,\t\tmglFlame2d_square,\t\tmglFlame2d_blade,\r\n\tmglFlame2d_secant,\t\tmglFlame2d_rays,\t\tmglFlame2d_twintrian,\tmglFlame2d_cross,\t\tmglFlame2d_disc2,\r\n\tmglFlame2d_supershape,\tmglFlame2d_flower,\t\tmglFlame2d_conic,\t\tmglFlame2d_parabola,\tmglFlame2d_bent2,\r\n\tmglFlame2d_bipolar,\t\tmglFlame2d_boarders,\tmglFlame2d_butterfly,\tmglFlame2d_cell,\t\tmglFlame2d_cpow,\r\n\tmglFlame2d_curve,\t\tmglFlame2d_edisc,\t\tmglFlame2d_elliptic,\tmglFlame2d_escher,\t\tmglFlame2d_foci,\r\n\tmglFlame2d_lazySusan,\tmglFlame2d_loonie,\t\tmglFlame2d_preBlur,\t\tmglFlame2d_modulus,\t\tmglFlame2d_oscope,\r\n\tmglFlame2d_polar2,\t\tmglFlame2d_popcorn2,\tmglFlame2d_scry,\t\tmglFlame2d_separation,\tmglFlame2d_split,\r\n\tmglFlame2d_splits,\t\tmglFlame2d_stripes,\t\tmglFlame2d_wedge,\t\tmglFlame2d_wedgeJulia,\tmglFlame2d_wedgeSph,\r\n\tmglFlame2d_whorl,\t\tmglFlame2d_waves2,\t\tmglFlame2d_exp,\t\t\tmglFlame2d_log,\t\t\tmglFlame2d_sin,\r\n\tmglFlame2d_cos,\t\t\tmglFlame2d_tan,\t\t\tmglFlame2d_sec,\t\t\tmglFlame2d_csc,\t\t\tmglFlame2d_cot,\r\n\tmglFlame2d_sinh,\t\tmglFlame2d_cosh,\t\tmglFlame2d_tanh,\t\tmglFlame2d_sech,\t\tmglFlame2d_csch,\r\n\tmglFlame2d_coth,\t\tmglFlame2d_auger,\t\tmglFlame2d_flux,\t\tmglFlame2dLAST\r\n};\r\n/// Get array which is n-th pairs {x[i],y[i]} for Flame fractal generated by A with functions F\r\n/** NOTE: A.nx must be >= 7 and F.nx >= 2 and F.nz=A.ny.\r\n * F[0,i,j] denote function id. F[1,i,j] give function weight. F(2:5,i,j) provide function parameters.\r\n * Resulting point is {xnew,ynew} = sum_i F[1,i,j]*F[0,i,j]{IFS2d(A[j]){x,y}}. */\r\nHMDT MGL_EXPORT mgl_data_flame_2d(HCDT A, HCDT F, long n, long skip);\r\nuintptr_t MGL_EXPORT mgl_data_flame_2d_(uintptr_t *A, uintptr_t *F, long *n, long *skip);\r\n\r\n/// Get curves, separated by NAN, for maximal values of array d as function of x coordinate.\r\n/** Noises below lvl amplitude are ignored.\r\n  * Parameter dy \\in [0,ny] set the \"attraction\" distance of points to curve. */\r\nHMDT MGL_EXPORT mgl_data_detect(HCDT d, mreal lvl, mreal dj, mreal di, mreal min_len);\r\nuintptr_t MGL_EXPORT mgl_data_detect_(uintptr_t *d, mreal *lvl, mreal *dj, mreal *di, mreal *min_len);\r\n\r\n/// Get array as solution of tridiagonal matrix solution a[i]*x[i-1]+b[i]*x[i]+c[i]*x[i+1]=d[i]\r\n/** String \\a how may contain:\r\n * 'x', 'y', 'z' for solving along x-,y-,z-directions, or\r\n * 'h' for solving along hexagonal direction at x-y plain (need nx=ny),\r\n * 'c' for using periodical boundary conditions,\r\n * 'd' for diffraction/diffuse calculation.\r\n * NOTE: It work for flat data model only (i.e. for a[i,j]==a[i+nx*j]) */\r\nHMDT MGL_EXPORT mgl_data_tridmat(HCDT A, HCDT B, HCDT C, HCDT D, const char *how);\r\nuintptr_t MGL_EXPORT mgl_data_tridmat_(uintptr_t *A, uintptr_t *B, uintptr_t *C, uintptr_t *D, const char *how, int);\r\n\r\n/// Returns pointer to data element [i,j,k]\r\nMGL_EXPORT mreal *mgl_data_value(HMDT dat, long i,long j,long k);\r\n/// Returns pointer to internal data array\r\nMGL_EXPORT_PURE mreal *mgl_data_data(HMDT dat);\r\n\r\n/// Gets the x-size of the data.\r\nlong MGL_EXPORT mgl_data_get_nx(HCDT d);\r\nlong MGL_EXPORT mgl_data_get_nx_(uintptr_t *d);\r\n/// Gets the y-size of the data.\r\nlong MGL_EXPORT mgl_data_get_ny(HCDT d);\r\nlong MGL_EXPORT mgl_data_get_ny_(uintptr_t *d);\r\n/// Gets the z-size of the data.\r\nlong MGL_EXPORT mgl_data_get_nz(HCDT d);\r\nlong MGL_EXPORT mgl_data_get_nz_(uintptr_t *d);\r\n\r\n/// Get the data which is direct multiplication (like, d[i,j] = this[i]*a[j] and so on)\r\nHMDT MGL_EXPORT mgl_data_combine(HCDT dat1, HCDT dat2);\r\nuintptr_t MGL_EXPORT mgl_data_combine_(uintptr_t *dat1, uintptr_t *dat2);\r\n/// Extend data dimensions\r\nvoid MGL_EXPORT mgl_data_extend(HMDT dat, long n1, long n2);\r\nvoid MGL_EXPORT mgl_data_extend_(uintptr_t *dat, int *n1, int *n2);\r\n/// Insert data rows/columns/slices\r\nvoid MGL_EXPORT mgl_data_insert(HMDT dat, char dir, long at, long num);\r\nvoid MGL_EXPORT mgl_data_insert_(uintptr_t *dat, const char *dir, int *at, int *num, int);\r\n/// Delete data rows/columns/slices\r\nvoid MGL_EXPORT mgl_data_delete(HMDT dat, char dir, long at, long num);\r\nvoid MGL_EXPORT mgl_data_delete_(uintptr_t *dat, const char *dir, int *at, int *num, int);\r\n/// Joind another data array\r\nvoid MGL_EXPORT mgl_data_join(HMDT dat, HCDT d);\r\nvoid MGL_EXPORT mgl_data_join_(uintptr_t *dat, uintptr_t *d);\r\n\r\n/// Smooth the data on specified direction or directions\r\n/** String \\a dir may contain:\r\n *  \u2018x\u2019, \u2018y\u2019, \u2018z\u2019 for 1st, 2nd or 3d dimension;\r\n *  \u2018dN\u2019 for linear averaging over N points;\r\n *  \u20183\u2019 for linear averaging over 3 points;\r\n *  \u20185\u2019 for linear averaging over 5 points.\r\n *  By default quadratic averaging over 5 points is used. */\r\nvoid MGL_EXPORT mgl_data_smooth(HMDT d, const char *dirs, mreal delta);\r\nvoid MGL_EXPORT mgl_data_smooth_(uintptr_t *dat, const char *dirs, mreal *delta,int);\r\n/// Get array which is result of summation in given direction or directions\r\nHMDT MGL_EXPORT mgl_data_sum(HCDT dat, const char *dir);\r\nuintptr_t MGL_EXPORT mgl_data_sum_(uintptr_t *dat, const char *dir,int);\r\n/// Get array which is result of maximal values in given direction or directions\r\nHMDT MGL_EXPORT mgl_data_max_dir(HCDT dat, const char *dir);\r\nuintptr_t MGL_EXPORT mgl_data_max_dir_(uintptr_t *dat, const char *dir,int);\r\n/// Get array which is result of minimal values in given direction or directions\r\nHMDT MGL_EXPORT mgl_data_min_dir(HCDT dat, const char *dir);\r\nuintptr_t MGL_EXPORT mgl_data_min_dir_(uintptr_t *dat, const char *dir,int);\r\n/// Get positions of local maximums and minimums\r\nHMDT MGL_EXPORT mgl_data_minmax(HCDT dat);\r\nuintptr_t MGL_EXPORT mgl_data_minmax_(uintptr_t *dat);\r\n/// Get indexes of a set of connected surfaces for set of values {a_ijk,b_ijk} as dependent on j,k\r\n/** NOTE: not optimized for general case!!! */\r\nHMDT MGL_EXPORT mgl_data_connect(HCDT a, HCDT b);\r\nuintptr_t MGL_EXPORT mgl_data_connect_(uintptr_t *a, uintptr_t *b);\r\n/// Resort data values according found connected surfaces for set of values {a_ijk,b_ijk} as dependent on j,k\r\n/** NOTE: not optimized for general case!!! */\r\nvoid MGL_EXPORT mgl_data_connect_r(HMDT a, HMDT b);\r\nvoid MGL_EXPORT mgl_data_connect_r_(uintptr_t *a, uintptr_t *b);\r\n\r\n/// Cumulative summation the data in given direction or directions\r\nvoid MGL_EXPORT mgl_data_cumsum(HMDT dat, const char *dir);\r\nvoid MGL_EXPORT mgl_data_cumsum_(uintptr_t *dat, const char *dir,int);\r\n/// Integrate (cumulative summation) the data in given direction or directions\r\nvoid MGL_EXPORT mgl_data_integral(HMDT dat, const char *dir);\r\nvoid MGL_EXPORT mgl_data_integral_(uintptr_t *dat, const char *dir,int);\r\n/// Differentiate the data in given direction or directions\r\nvoid MGL_EXPORT mgl_data_diff(HMDT dat, const char *dir);\r\nvoid MGL_EXPORT mgl_data_diff_(uintptr_t *dat, const char *dir,int);\r\n/// Differentiate the parametrically specified data along direction v1 with v2,v3=const (v3 can be NULL)\r\nvoid MGL_EXPORT mgl_data_diff_par(HMDT dat, HCDT v1, HCDT v2, HCDT v3);\r\nvoid MGL_EXPORT mgl_data_diff_par_(uintptr_t *dat, uintptr_t *v1, uintptr_t *v2, uintptr_t *v3);\r\n/// Double-differentiate (like Laplace operator) the data in given direction\r\nvoid MGL_EXPORT mgl_data_diff2(HMDT dat, const char *dir);\r\nvoid MGL_EXPORT mgl_data_diff2_(uintptr_t *dat, const char *dir,int);\r\n/// Swap left and right part of the data in given direction (useful for Fourier spectrum)\r\nvoid MGL_EXPORT mgl_data_swap(HMDT dat, const char *dir);\r\nvoid MGL_EXPORT mgl_data_swap_(uintptr_t *dat, const char *dir,int);\r\n/// Roll data along direction dir by num slices\r\nvoid MGL_EXPORT mgl_data_roll(HMDT dat, char dir, long num);\r\nvoid MGL_EXPORT mgl_data_roll_(uintptr_t *dat, const char *dir, int *num, int);\r\n/// Mirror the data in given direction (useful for Fourier spectrum)\r\nvoid MGL_EXPORT mgl_data_mirror(HMDT dat, const char *dir);\r\nvoid MGL_EXPORT mgl_data_mirror_(uintptr_t *dat, const char *dir,int);\r\n/// Sort rows (or slices) by values of specified column\r\nvoid MGL_EXPORT mgl_data_sort(HMDT dat, long idx, long idy);\r\nvoid MGL_EXPORT mgl_data_sort_(uintptr_t *dat, int *idx, int *idy);\r\n/// Return dilated array of 0 or 1 for data values larger val\r\nvoid MGL_EXPORT mgl_data_dilate(HMDT dat, mreal val, long step);\r\nvoid MGL_EXPORT mgl_data_dilate_(uintptr_t *dat, mreal *val, int *step);\r\n/// Return eroded array of 0 or 1 for data values larger val\r\nvoid MGL_EXPORT mgl_data_erode(HMDT dat, mreal val, long step);\r\nvoid MGL_EXPORT mgl_data_erode_(uintptr_t *dat, mreal *val, int *step);\r\n\r\n/// Apply Hankel transform\r\nvoid MGL_EXPORT mgl_data_hankel(HMDT dat, const char *dir);\r\nvoid MGL_EXPORT mgl_data_hankel_(uintptr_t *dat, const char *dir,int);\r\n/// Apply Sin-Fourier transform\r\nvoid MGL_EXPORT mgl_data_sinfft(HMDT dat, const char *dir);\r\nvoid MGL_EXPORT mgl_data_sinfft_(uintptr_t *dat, const char *dir,int);\r\n/// Apply Cos-Fourier transform\r\nvoid MGL_EXPORT mgl_data_cosfft(HMDT dat, const char *dir);\r\nvoid MGL_EXPORT mgl_data_cosfft_(uintptr_t *dat, const char *dir,int);\r\n/// Fill data by coordinates/momenta samples for Hankel ('h') or Fourier ('f') transform\r\n/** Parameter \\a how may contain:\r\n * \u2018x\u2018,\u2018y\u2018,\u2018z\u2018 for direction (only one will be used),\r\n * \u2018k\u2018 for momenta samples,\r\n * \u2018h\u2018 for Hankel samples,\r\n * \u2018f\u2018 for Cartesian/Fourier samples (default). */\r\nvoid MGL_EXPORT mgl_data_fill_sample(HMDT dat, const char *how);\r\nvoid MGL_EXPORT mgl_data_fill_sample_(uintptr_t *dat, const char *how,int);\r\n/// Find correlation between 2 data arrays\r\nHMDT MGL_EXPORT mgl_data_correl(HCDT dat1, HCDT dat2, const char *dir);\r\nuintptr_t MGL_EXPORT mgl_data_correl_(uintptr_t *dat1, uintptr_t *dat2, const char *dir,int);\r\n/// Apply wavelet transform\r\n/** Parameter \\a dir may contain:\r\n * \u2018x\u2018,\u2018y\u2018,\u2018z\u2018 for directions,\r\n * \u2018d\u2018 for daubechies, \u2018D\u2018 for centered daubechies,\r\n * \u2018h\u2018 for haar, \u2018H\u2018 for centered haar,\r\n * \u2018b\u2018 for bspline, \u2018B\u2018 for centered bspline,\r\n * \u2018i\u2018 for applying inverse transform. */\r\nvoid MGL_EXPORT mgl_data_wavelet(HMDT dat, const char *how, int k);\r\nvoid MGL_EXPORT mgl_data_wavelet_(uintptr_t *d, const char *dir, int *k,int);\r\n\r\n/// Allocate and prepare data for Fourier transform by nthr threads\r\nMGL_EXPORT void *mgl_fft_alloc(long n, void **space, long nthr);\r\nMGL_EXPORT void *mgl_fft_alloc_thr(long n);\r\n/// Free data for Fourier transform\r\nvoid MGL_EXPORT mgl_fft_free(void *wt, void **ws, long nthr);\r\nvoid MGL_EXPORT mgl_fft_free_thr(void *wt);\r\n/// Make Fourier transform of data x of size n and step s between points\r\nvoid MGL_EXPORT mgl_fft(double *x, long s, long n, const void *wt, void *ws, int inv);\r\n/// Clear internal data for speeding up FFT and Hankel transforms\r\nvoid MGL_EXPORT mgl_clear_fft();\r\n\r\n/// Interpolate by cubic spline the data to given point x=[0...nx-1], y=[0...ny-1], z=[0...nz-1]\r\nmreal MGL_EXPORT mgl_data_spline(HCDT dat, mreal x,mreal y,mreal z);\r\nmreal MGL_EXPORT mgl_data_spline_(uintptr_t *dat, mreal *x,mreal *y,mreal *z);\r\n/// Interpolate by cubic spline the data and return its derivatives at given point x=[0...nx-1], y=[0...ny-1], z=[0...nz-1]\r\nmreal MGL_EXPORT mgl_data_spline_ext(HCDT dat, mreal x,mreal y,mreal z, mreal *dx,mreal *dy,mreal *dz);\r\nmreal MGL_EXPORT mgl_data_spline_ext_(uintptr_t *dat, mreal *x,mreal *y,mreal *z, mreal *dx,mreal *dy,mreal *dz);\r\n/// Prepare coefficients for global spline interpolation\r\nHMDT MGL_EXPORT mgl_gspline_init(HCDT x, HCDT v);\r\nuintptr_t MGL_EXPORT mgl_gspline_init_(uintptr_t *x, uintptr_t *v);\r\n/// Evaluate global spline (and its derivatives d1, d2 if not NULL) using prepared coefficients \\a coef\r\nmreal MGL_EXPORT mgl_gspline(HCDT coef, mreal dx, mreal *d1, mreal *d2);\r\nmreal MGL_EXPORT mgl_gspline_(uintptr_t *c, mreal *dx, mreal *d1, mreal *d2);\r\n/// Return an approximated x-value (root) when dat(x) = val\r\nmreal MGL_EXPORT mgl_data_solve_1d(HCDT dat, mreal val, int spl, long i0);\r\nmreal MGL_EXPORT mgl_data_solve_1d_(uintptr_t *dat, mreal *val, int *spl, int *i0);\r\n/// Return an approximated value (root) when dat(x) = val\r\nHMDT MGL_EXPORT mgl_data_solve(HCDT dat, mreal val, char dir, HCDT i0, int norm);\r\nuintptr_t MGL_EXPORT mgl_data_solve_(uintptr_t *dat, mreal *val, const char *dir, uintptr_t *i0, int *norm,int);\r\n\r\n/// Get trace of the data array\r\nHMDT MGL_EXPORT mgl_data_trace(HCDT d);\r\nuintptr_t MGL_EXPORT mgl_data_trace_(uintptr_t *d);\r\n/// Resize the data to new sizes\r\nHMDT MGL_EXPORT mgl_data_resize(HCDT dat, long mx,long my,long mz);\r\nuintptr_t MGL_EXPORT mgl_data_resize_(uintptr_t *dat, int *mx,int *my,int *mz);\r\n/// Resize the data to new sizes of box [x1,x2]*[y1,y2]*[z1,z2]\r\nHMDT MGL_EXPORT mgl_data_resize_box(HCDT dat, long mx,long my,long mz,mreal x1,mreal x2,mreal y1,mreal y2,mreal z1,mreal z2);\r\nuintptr_t MGL_EXPORT mgl_data_resize_box_(uintptr_t *dat, int *mx,int *my,int *mz,mreal *x1,mreal *x2,mreal *y1,mreal *y2,mreal *z1,mreal *z2);\r\n/// Create n-th points distribution of this data values in range [v1, v2]\r\nHMDT MGL_EXPORT mgl_data_hist(HCDT dat, long n, mreal v1, mreal v2, long nsub);\r\nuintptr_t MGL_EXPORT mgl_data_hist_(uintptr_t *dat, int *n, mreal *v1, mreal *v2, int *nsub);\r\n/// Create n-th points distribution of this data values in range [v1, v2] with weight w\r\nHMDT MGL_EXPORT mgl_data_hist_w(HCDT dat, HCDT weight, long n, mreal v1, mreal v2, long nsub);\r\nuintptr_t MGL_EXPORT mgl_data_hist_w_(uintptr_t *dat, uintptr_t *weight, int *n, mreal *v1, mreal *v2, int *nsub);\r\n/// Get momentum (1D-array) of data along direction 'dir'. String looks like \"x1\" for median in x-direction, \"x2\" for width in x-dir and so on.\r\nHMDT MGL_EXPORT mgl_data_momentum(HCDT dat, char dir, const char *how);\r\nuintptr_t MGL_EXPORT mgl_data_momentum_(uintptr_t *dat, char *dir, const char *how, int,int);\r\n/// Get pulse properties: pulse maximum and its position, pulse duration near maximum and by half height.\r\nHMDT MGL_EXPORT mgl_data_pulse(HCDT dat, char dir);\r\nuintptr_t MGL_EXPORT mgl_data_pulse_(uintptr_t *dat, char *dir,int);\r\n/// Get array which values is result of interpolation this for coordinates from other arrays\r\nHMDT MGL_EXPORT mgl_data_evaluate(HCDT dat, HCDT idat, HCDT jdat, HCDT kdat, int norm);\r\nuintptr_t MGL_EXPORT mgl_data_evaluate_(uintptr_t *dat, uintptr_t *idat, uintptr_t *jdat, uintptr_t *kdat, int *norm);\r\n/// Set as the data envelop\r\nvoid MGL_EXPORT mgl_data_envelop(HMDT dat, char dir);\r\nvoid MGL_EXPORT mgl_data_envelop_(uintptr_t *dat, const char *dir, int);\r\n/// Remove phase jump\r\nvoid MGL_EXPORT mgl_data_sew(HMDT dat, const char *dirs, mreal da);\r\nvoid MGL_EXPORT mgl_data_sew_(uintptr_t *dat, const char *dirs, mreal *da, int);\r\n/// Crop the data\r\nvoid MGL_EXPORT mgl_data_crop(HMDT dat, long n1, long n2, char dir);\r\nvoid MGL_EXPORT mgl_data_crop_(uintptr_t *dat, int *n1, int *n2, const char *dir,int);\r\n/// Crop the data to be most optimal for FFT (i.e. to closest value of 2^n*3^m*5^l)\r\nvoid MGL_EXPORT mgl_data_crop_opt(HMDT dat, const char *how);\r\nvoid MGL_EXPORT mgl_data_crop_opt_(uintptr_t *dat, const char *how,int);\r\n/// Remove rows with duplicate values in column id\r\nvoid MGL_EXPORT mgl_data_clean(HMDT dat, long id);\r\nvoid MGL_EXPORT mgl_data_clean_(uintptr_t *dat, int *id);\r\n\r\n/// Multiply the data by other one for each element\r\nvoid MGL_EXPORT mgl_data_mul_dat(HMDT dat, HCDT d);\r\nvoid MGL_EXPORT mgl_data_mul_dat_(uintptr_t *dat, uintptr_t *d);\r\n/// Divide the data by other one for each element\r\nvoid MGL_EXPORT mgl_data_div_dat(HMDT dat, HCDT d);\r\nvoid MGL_EXPORT mgl_data_div_dat_(uintptr_t *dat, uintptr_t *d);\r\n/// Add the other data\r\nvoid MGL_EXPORT mgl_data_add_dat(HMDT dat, HCDT d);\r\nvoid MGL_EXPORT mgl_data_add_dat_(uintptr_t *dat, uintptr_t *d);\r\n/// Subtract the other data\r\nvoid MGL_EXPORT mgl_data_sub_dat(HMDT dat, HCDT d);\r\nvoid MGL_EXPORT mgl_data_sub_dat_(uintptr_t *dat, uintptr_t *d);\r\n/// Multiply each element by the number\r\nvoid MGL_EXPORT mgl_data_mul_num(HMDT dat, mreal d);\r\nvoid MGL_EXPORT mgl_data_mul_num_(uintptr_t *dat, mreal *d);\r\n/// Divide each element by the number\r\nvoid MGL_EXPORT mgl_data_div_num(HMDT dat, mreal d);\r\nvoid MGL_EXPORT mgl_data_div_num_(uintptr_t *dat, mreal *d);\r\n/// Add the number\r\nvoid MGL_EXPORT mgl_data_add_num(HMDT dat, mreal d);\r\nvoid MGL_EXPORT mgl_data_add_num_(uintptr_t *dat, mreal *d);\r\n/// Subtract the number\r\nvoid MGL_EXPORT mgl_data_sub_num(HMDT dat, mreal d);\r\nvoid MGL_EXPORT mgl_data_sub_num_(uintptr_t *dat, mreal *d);\r\n\r\n/// Integral data transformation (like Fourier 'f' or 'i', Hankel 'h' or None 'n') for amplitude and phase\r\nHMDT MGL_EXPORT mgl_transform_a(HCDT am, HCDT ph, const char *tr);\r\nuintptr_t MGL_EXPORT mgl_transform_a_(uintptr_t *am, uintptr_t *ph, const char *tr, int);\r\n/// Integral data transformation (like Fourier 'f' or 'i', Hankel 'h' or None 'n') for real and imaginary parts\r\nHMDT MGL_EXPORT mgl_transform(HCDT re, HCDT im, const char *tr);\r\nuintptr_t MGL_EXPORT mgl_transform_(uintptr_t *re, uintptr_t *im, const char *tr, int);\r\n/// Apply Fourier transform for the data and save result into it\r\nvoid MGL_EXPORT mgl_data_fourier(HMDT re, HMDT im, const char *dir);\r\nvoid MGL_EXPORT mgl_data_fourier_(uintptr_t *re, uintptr_t *im, const char *dir, int l);\r\n/// Short time Fourier analysis for real and imaginary parts. Output is amplitude of partial Fourier (result will have size {dn, floor(nx/dn), ny} for dir='x'\r\nHMDT MGL_EXPORT mgl_data_stfa(HCDT re, HCDT im, long dn, char dir);\r\nuintptr_t MGL_EXPORT mgl_data_stfa_(uintptr_t *re, uintptr_t *im, int *dn, char *dir, int);\r\n\r\n/// Do something like Delone triangulation for 3d points\r\nHMDT MGL_EXPORT mgl_triangulation_3d(HCDT x, HCDT y, HCDT z);\r\nuintptr_t MGL_EXPORT mgl_triangulation_3d_(uintptr_t *x, uintptr_t *y, uintptr_t *z);\r\n/// Do Delone triangulation for 2d points\r\nHMDT MGL_EXPORT mgl_triangulation_2d(HCDT x, HCDT y);\r\nuintptr_t MGL_EXPORT mgl_triangulation_2d_(uintptr_t *x, uintptr_t *y);\r\n\r\n/// Find root for nonlinear equation\r\nmreal MGL_EXPORT mgl_find_root(mreal (*func)(mreal val, void *par), mreal ini, void *par);\r\n/// Find root for nonlinear equation defined by textual formula\r\nmreal MGL_EXPORT mgl_find_root_txt(const char *func, mreal ini, char var_id);\r\nmreal MGL_EXPORT mgl_find_root_txt_(const char *func, mreal *ini, const char *var_id,int,int);\r\n/// Find roots for nonlinear equation defined by textual formula\r\nHMDT MGL_EXPORT mgl_data_roots(const char *func, HCDT ini, char var_id);\r\nuintptr_t MGL_EXPORT mgl_data_roots_(const char *func, uintptr_t *ini, const char *var_id,int,int);\r\n/// Find roots for set of nonlinear equations defined by textual formulas\r\nHMDT MGL_EXPORT mgl_find_roots_txt(const char *func, const char *vars, HCDT ini);\r\nuintptr_t MGL_EXPORT mgl_find_roots_txt_(const char *func, const char *vars, uintptr_t *ini,int,int);\r\n/// Find roots for set of nonlinear equations defined by function\r\nint MGL_EXPORT mgl_find_roots(size_t n, void (*func)(const mreal *x, mreal *f, void *par), mreal *x0, void *par);\r\n//-----------------------------------------------------------------------------\r\n#ifdef __cplusplus\r\n}\r\n#endif\r\n#endif\r\n//-----------------------------------------------------------------------------\r\n", "meta": {"hexsha": "d6e098720e2de2e4428a5453e51b3d013d683b1f", "size": 36492, "ext": "h", "lang": "C", "max_stars_repo_path": "openal-mathgl-generate/include/mgl2/data_cf.h", "max_stars_repo_name": "dickensas/kotlin-gradle-templates", "max_stars_repo_head_hexsha": "dc738b9fac053ef62381ecbe88add6f6fe949fe3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 54.0, "max_stars_repo_stars_event_min_datetime": "2019-11-12T03:55:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T14:28:02.000Z", "max_issues_repo_path": "openal-mathgl-generate/include/mgl2/data_cf.h", "max_issues_repo_name": "dickensas/kotlin-gradle-templates", "max_issues_repo_head_hexsha": "dc738b9fac053ef62381ecbe88add6f6fe949fe3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-07-31T10:50:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-08T06:16:28.000Z", "max_forks_repo_path": "openal-mathgl-generate/include/mgl2/data_cf.h", "max_forks_repo_name": "dickensas/kotlin-gradle-templates", "max_forks_repo_head_hexsha": "dc738b9fac053ef62381ecbe88add6f6fe949fe3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2019-12-05T12:55:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T00:47:15.000Z", "avg_line_length": 68.3370786517, "max_line_length": 188, "alphanum_fraction": 0.735805108, "num_tokens": 11141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34510528442897664, "lm_q2_score": 0.04272220013649572, "lm_q1q2_score": 0.01474365702953702}}
{"text": "#ifndef UTIL_H\n#define UTIL_H\n\n#include <vector>\n\n#include <gsl/gsl_matrix.h>\n\nclass Matrices_keeper {\n\n    private:\n        std::vector<gsl_matrix*> matrices;\n    public:\n        Matrices_keeper();\n        Matrices_keeper(const Matrices_keeper& keeper);\n        Matrices_keeper& operator=(const Matrices_keeper& keeper);\n\n        gsl_matrix* alloc_next(int s1, int s2);\n        void dalloc_all();\n        ~Matrices_keeper();\n\n};\n\nbool validate_inputs(char **args);\nvoid usage();\n\nvoid exit_on_status(int status, char *msg);\nvoid exit_on_null(void *p, char *msg);\n\n#endif // UTIL_H\n", "meta": {"hexsha": "8deab7b7dbcf3171c220470625f8a6a297713129", "size": 582, "ext": "h", "lang": "C", "max_stars_repo_path": "src/includes/util.h", "max_stars_repo_name": "bainit/hextexsim", "max_stars_repo_head_hexsha": "c613ccb2603f0f89ee4c177047e16fa2eaf4ddd9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-01-24T13:21:03.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-20T14:07:43.000Z", "max_issues_repo_path": "src/includes/util.h", "max_issues_repo_name": "bainit/hextexsim", "max_issues_repo_head_hexsha": "c613ccb2603f0f89ee4c177047e16fa2eaf4ddd9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/includes/util.h", "max_forks_repo_name": "bainit/hextexsim", "max_forks_repo_head_hexsha": "c613ccb2603f0f89ee4c177047e16fa2eaf4ddd9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.4, "max_line_length": 66, "alphanum_fraction": 0.6718213058, "num_tokens": 137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.334589441253186, "lm_q2_score": 0.04401864829530669, "lm_q1q2_score": 0.014728174937847175}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdarg.h>\n#include <math.h>\n#include <unistd.h>\n#include <limits.h>\n#include <sys/time.h>\n#include <zlib.h>\n\n#ifdef INTEL_COMPILER\n#include \"mkl.h\"\n#else\n#include <cblas.h>\n#endif\n\n//#define FIBS_UNIT 1000\n#define DEFAULT_NDIGITS 10\n#define SZBUF 1024\n#define SZBYTE 256\n#define N_GENOTYPES 4\n#define NA_GENO_CHAR (N_GENOTYPES-1)\n#define DEFAULT_ROW_SIZE 100000\n#define DEFAULT_SIZE_MATRIX 1000000\n#define DEFAULT_SIZE_HEADER 100000\n#define DEFAULT_DELIMS \" \\t\\r\\n\"\n#define SZ_LONG_BUF 1000000\n#define DEFAULT_TPED_NUM_HEADER_COLS 4\n#define DEFAULT_TFAM_NUM_HEADER_COLS 6\n#define DEFAULT_TPED_SNPID_INDEX 1\n#define DEFAULT_PHENO_NUM_HEADER_COLS 2\n\nstruct HFILE {\n  int gzflag;       // 1 if gz if used\n  int wflag;        // r(0)/w(1) for plain, rb(0)/wb(1) for gz\n  int nheadercols;  // # of header columns (0 if nrows=0)\n  int nvaluecols;   // # of value cols (0 if nrows=0)\n  int nrows;        // # of rows\n  FILE* fp;         // plain file handle\n  gzFile gzfp;      // gzip file handle\n};\n\n// Input routines\nvoid close_file (struct HFILE* fhp);\nstruct HFILE open_file(char* filename, int gzflag, int wflag);\nstruct HFILE open_file_with_suffix(char* prefix, char* suffix, int gzflag, int wflag);\n//void read_matrix_with_col_headers( struct HFILE* fhp, int nheadercols, char* delims, int symmetric, int* p_nmiss, unsigned char** matrix, char*** headers);\nvoid read_matrix_with_col_headers( struct HFILE* fhp, int nheadercols, char* delims, int* p_nmiss, unsigned char** matrix, char*** headers);\nunsigned char* tokenize_tped_line_with_col_headers( struct HFILE* fhp, int nheadercols, char* delims, char* lbuf, unsigned char* values, char** headers, int* p_nvalues, int* p_nmiss );\n\nvoid emmax_error( const char* format, ... );\nvoid print_help(void);\nFILE* readfile(char* filename);\n\nvoid print_help(void) {\n  fprintf(stderr,\"Usage: emmax_kin [tpedf]\\n\");\n  fprintf(stderr,\"Required parameters\\n\");\n  fprintf(stderr,\"\\t[tpedf]     : tped file\\n\");\n  fprintf(stderr,\"Optional parameters\\n\");\n  fprintf(stderr,\"\\t-d [# digits]  : precision of the kinship values (default : 10)\\n\");\n  fprintf(stderr,\"\\t-M [float] : maximum memory in GB (default: 4.0)\\n\");\n  fprintf(stderr,\"\\t-s : compute IBS kinship matrix (default is Balding-Nicholas)\\n\");\n  fprintf(stderr,\"\\t-v : turn on verbose mode\\n\");\n  fprintf(stderr,\"\\t-r : randomly fill missing genotypes (default is imputation by average)\\n\");\n  fprintf(stderr,\"\\t-x : include non-autosomal chromosomes in computing kinship matrices\\n\");\n  fprintf(stderr,\"\\t-S [int] : set random seed\\n\");\n  fprintf(stderr,\"\\t-m [float] : MAF threshold (default is 0)\\n\");\n  fprintf(stderr,\"\\t-c [float] : Call rate threshold (default is 0)\\n\");\n}\n\n//void read_matrix_with_col_headers( struct HFILE* fhp, int nheadercols, char* delims, int symmetric, int* p_nmiss, unsigned char** matrix, char*** headers) {\nvoid read_matrix_with_col_headers( struct HFILE* fhp, int nheadercols, char* delims, int* p_nmiss, unsigned char** matrix, char*** headers) {\n  char* lbuf = (char*) malloc(sizeof(char*) * SZ_LONG_BUF);\n  int szmat = DEFAULT_SIZE_MATRIX;\n  int szheader = DEFAULT_SIZE_HEADER;\n  unsigned char* cmat = (unsigned char*) malloc(sizeof(unsigned char) * szmat );\n  char** cheaders = (char**) malloc(sizeof(char*) * szheader );\n  int nvalues, i, j, nmiss;\n\n  fhp->nheadercols = nheadercols; \n  nmiss = 0;\n\n  while( tokenize_tped_line_with_col_headers(fhp, nheadercols, delims, lbuf, &cmat[fhp->nrows*fhp->nvaluecols], &cheaders[fhp->nrows*fhp->nheadercols], &nvalues, &nmiss) != NULL ) {\n    if ( fhp->nrows == 1 ) {\n      fhp->nvaluecols = nvalues;\n    }\n    else if ( fhp->nvaluecols != nvalues ) {\n      emmax_error(\"The column size %d do not match to %d at line %d\\n\",nvalues,fhp->nvaluecols,fhp->nrows);\n    }\n\n    if ( (fhp->nrows+1)*(fhp->nvaluecols) > szheader ) {\n      szheader *= 2;\n      fprintf(stderr,\"Header size is doubled to %d\\n\",szheader);\n      cheaders = (char**) realloc( cheaders, sizeof(char*) * szheader );\n    }\n\n    if ( (fhp->nrows+1)*(fhp->nvaluecols) > szheader ) {\n      szmat *= 2;\n      fprintf(stderr,\"Matrix size is doubled to %d\\n\",szmat);\n      cmat = (unsigned char*) realloc( cmat, sizeof(unsigned char) * szmat );\n    }\n  }\n  free(lbuf);\n\n  *p_nmiss = nmiss;\n  \n  unsigned char* fmat = (unsigned char*) malloc(sizeof(unsigned char)*fhp->nrows*fhp->nvaluecols);\n  char** fheaders = (char**) malloc(sizeof(char*)*fhp->nrows*fhp->nheadercols);\n  for(i=0; i < fhp->nrows; ++i) {\n    for(j=0; j < fhp->nvaluecols; ++j) {\n      fmat[i+j*fhp->nrows] = cmat[i*fhp->nvaluecols+j];\n    }\n    for(j=0; j < fhp->nheadercols; ++j) {\n      fheaders[i+j*fhp->nrows] = cheaders[i*fhp->nheadercols+j];\n    }\n  }\n  free(cmat);\n  free(cheaders);\n  \n  if ( matrix != NULL ) {\n    if ( *matrix != NULL ) {\n      free(*matrix);\n    }\n    *matrix = fmat;\n  }\n  \n  if ( headers != NULL ) {\n    if ( *headers != NULL ) {\n      free(*headers);\n    }\n    *headers = fheaders;\n  }\n}\n\nunsigned char* tokenize_tped_line_with_col_headers( struct HFILE* fhp, int nheadercols, char* delims, char* lbuf, unsigned char* values, char** headers, int* p_nvalues, int* p_nmiss ) {\n  int j;\n  char *token;\n  unsigned char ctoken;\n\n  char *ret = (fhp->gzflag == 1) ? gzgets(fhp->gzfp, lbuf, SZ_LONG_BUF) : fgets( lbuf, SZ_LONG_BUF, fhp->fp );\n  int nmiss = 0;\n\n  if ( ret == NULL ) {\n    return NULL;\n  }\n\n  if ( fhp->nheadercols != nheadercols ) {\n    emmax_error(\"# of header columns mismatch (%d vs %d) at line %d\",fhp->nheadercols,nheadercols,fhp->nrows);\n  }\n\n  //fprintf(stderr,\"tokenize-line called %s\\n\",lbuf);\n\n  token = strtok(lbuf, delims);\n  for( j=0; token != NULL; ++j ) {\n    if ( j < nheadercols ) {\n      headers[j] = strdup(token);\n    }\n    // if zero_miss_flag is set, assume the genotypes are encoded 0,1,2\n    // Additively encodes the two genotypes in the following way\n    // when (j-nheadercols) is even, 0->MISSING, add 1->0, 2->1\n    // when (j-nheadercols) is odd, check 0-0 consistency, and add 1->0, 2->1\n    else {\n      ctoken = (unsigned char)(token[0]-'0');\n      \n      if ( ctoken > 2 ) {\n\tfprintf(stderr,\"Unrecognized token %s\\n\",token);\n\tabort();\n      }\n      \n      if ( (j-nheadercols) % 2 == 0 ) {\n\tvalues[(j-nheadercols)/2] = ctoken;\n      }\n      else {\n\tif ( ( ctoken > 0 ) && ( values[(j-nheadercols)/2] == 0 ) ) {\n\t  fprintf(stderr,\"Unmatched token pair 0 %s\\n\",token);\n\t  abort();\n\t}\n\telse if ( ( ctoken == 0 ) && ( values[(j-nheadercols)/2] > 0 ) ) {\n\t  fprintf(stderr,\"Unmatched token pair - %d 0\\n\",(int)values[(j-nheadercols)/2]);\n\t  abort();\n\t}\n\tvalues[(j-nheadercols)/2] = (unsigned char)(values[(j-nheadercols)/2]+ctoken);\n      }\n    }\n    token = strtok(NULL, delims);\n  }\n  //fprintf(stderr,\"tokenize-line ended %d %d\\n\",j,nheadercols);\n  if ( (j-nheadercols) % 2 != 0 ) {\n    fprintf(stderr,\"Number of value tokens are not even %d\\n\",j-nheadercols);\n    abort();\n  }\n\n  *p_nvalues = (j-nheadercols)/2;\n  *p_nmiss += nmiss;\n  ++(fhp->nrows);\n\n  if ( j < nheadercols ) {\n    fprintf(stderr,\"Number of header columns are %d, but only %d columns were observed\\n\", nheadercols, j);\n    abort();\n  }\n\n  return values;\n}\n\n// open_file_with_suffix()\n// - [prefix].[suffix] : file name to open\n// - gzflag : gzip flag (use gzfp if gzflag=1, otherwise use fp)\n// - wflag : write flag (1 if write mode otherwise read mode\nstruct HFILE open_file_with_suffix(char* prefix, char* suffix, int gzflag, int wflag) {\n  char filename[SZBUF];\n  sprintf(filename,\"%s.%s\",prefix,suffix);\n  return open_file(filename,gzflag,wflag);\n}\n\n// open_file()\n// - filename : file name to open\n// - gzflag : gzip flag (use gzfp if gzflag=1, otherwise use fp)\n// - wflag : write flag (1 if write mode otherwise read mode)\nstruct HFILE open_file(char* filename, int gzflag, int wflag) {\n  struct HFILE fh;\n  fh.gzflag = gzflag;\n  fh.wflag = wflag;\n  fh.nheadercols = 0;\n  fh.nvaluecols = 0;\n  fh.nrows = 0;\n  if ( gzflag == 1 ) {\n    char* mode = (wflag == 1) ? \"wb\" : \"rb\";\n    fh.gzfp = gzopen(filename,mode);\n    fh.fp = NULL;\n\n    if ( fh.gzfp == NULL ) {\n      emmax_error(\"Cannot open file %s for reading\",filename);\n    }\n  }\n  else {\n    char* mode = (wflag == 1) ? \"w\" : \"r\";\n    fh.gzfp = (gzFile) NULL;\n    fh.fp = fopen(filename,mode);\n\n    if ( fh.fp == NULL ) {\n      emmax_error(\"Cannot open file %s for writing\",filename);\n    }\n  }\n  return fh;\n}\n\nvoid emmax_error( const char* format, ... ) {\n  va_list args;\n  fprintf(stderr, \"ERROR: \");\n  va_start (args, format);\n  vfprintf(stderr, format, args);\n  va_end (args);\n  fprintf(stderr,\"\\n\");\n  abort();\n}\n\nvoid close_file(struct HFILE* fhp) {\n  if ( fhp->gzflag == 1 ) {\n    gzclose(fhp->gzfp);\n    fhp->gzfp = NULL;\n  }\n  else {\n    fclose(fhp->fp);\n    fhp->fp = NULL;\n  }\n}\n\nint main(int argc, char** argv) {\n  int i, j, n, c, ac0, ac1, ac2, nmiss, nelems, nex, n_sum_nin, nin, nex_maf, nex_call_rate, nex_autosomal;\n  int verbose, ndigits, tped_nheadercols, tfam_nheadercols, flag_autosomal, rand_fill_flag, ibs_flag, n_unit_lines;\n  unsigned char *snprow;\n  char *suffix, buf[SZBUF];\n  double f, max_memory_GB, maf_thres, call_rate_thres, aaf, call_rate;\n  //long *fibs_sums, *scores, mean_score;\n  double *kin, *snpunit;\n  char *tpedf, *delims, *lbuf;\n  char **tfam_headers, **tped_headers;\n  struct HFILE tpedh, tfamh, kinsh;\n  struct timeval tv;\n\n  // set default params\n  gettimeofday(&tv, NULL);\n  srand((unsigned int)tv.tv_usec);\n  delims = DEFAULT_DELIMS;\n  tped_nheadercols = DEFAULT_TPED_NUM_HEADER_COLS;\n  tfam_nheadercols = DEFAULT_TFAM_NUM_HEADER_COLS;\n  tped_headers = tfam_headers = NULL;\n  tpedf = lbuf = 0;\n  flag_autosomal = 1;\n  rand_fill_flag = 0;\n  ibs_flag = 0;\n  verbose = 0;\n  ndigits = DEFAULT_NDIGITS;\n  max_memory_GB = 4.0; // 4.0GB\n  maf_thres = 0.0;\n  call_rate_thres = 0.0;\n\n  // read arguments and update params\n  while ((c = getopt(argc, argv, \"d:rsc:vxS:M:m:c:\")) != -1 ) {\n    switch(c) {\n    case 'd': // precision of digits\n      ndigits = atoi(optarg);\n      break;\n    case 'r':\n      rand_fill_flag = 1;\n      break;\n    case 's':\n      ibs_flag = 1;\n      break;\n    case 'v':\n      verbose = 1;\n      break;\n    case 'x':\n      flag_autosomal = 0;\n      break;\n    case 'S':\n      srand(atoi(optarg));\n      break;\n    case 'M':\n      max_memory_GB = atof(optarg);\n      break;\n    case 'm':\n      maf_thres = atof(optarg);\n      break;\n    case 'c':\n      call_rate_thres = atof(optarg);\n      break;\n    default:\n      fprintf(stderr,\"Error : Unknown option unsigned character %c\\n\",c);\n      abort();\n    }\n  }\n\n  // Sanity check for the number of required parameters\n  if ( argc != optind + 1 ) {\n    print_help();\n    abort();\n  }\n\n  // Read required parameters\n  tpedf = argv[optind++];\n\n  if ( verbose) fprintf(stderr,\"\\nReading TFAM file %s.tfam ....\\n\",tpedf);\n\n  tfamh = open_file_with_suffix(tpedf, \"tfam\", 0, 0);\n  //read_matrix_with_col_headers( &tfamh, tfam_nheadercols, delims, 0, &nmiss, NULL, &tfam_headers);\n  read_matrix_with_col_headers( &tfamh, tfam_nheadercols, delims, &nmiss, NULL, &tfam_headers);\n  n = tfamh.nrows; // n is # of individuals\n  if ( verbose ) fprintf(stderr,\"Identified %d individuals from TFAM file\\n\",n);\n\n  // compute the # of lines to read together\n  // we would need two n*n matrix, and n*m matrix\n  // (n*n + n*m)*sizeof(double) < M*1e9 \n  // m < M*1e9/sizeof(double)/n - n\n  n_unit_lines = (int)floor((max_memory_GB * 1.0e9 / sizeof(double) / n - n)/2)*2;\n  n_sum_nin = 0;\n#ifdef INTEL_COMPILER\n  char cn = 'N', ct = 'T';\n  double one = 1.;\n#endif\n  \n  if ( verbose ) fprintf(stderr,\"Setting # unit lines = %d to fit the memory requirement\\n\",n_unit_lines);\n\n  snprow = (unsigned char*)malloc(sizeof(unsigned char)*n);\n  tped_headers = (char**)malloc(sizeof(char*)*n);\n  lbuf = (char*) malloc(sizeof(char*) * SZ_LONG_BUF);\n\n  kin = (double*)calloc(n*n, sizeof(double));\n  snpunit = (double*)malloc(n*n_unit_lines * sizeof(double));\n\n  if ( verbose) fprintf(stderr,\"Reading TPED file %s.tped ....\\n\",tpedf);\n\n  tpedh = open_file_with_suffix(tpedf, \"tped\", 0, 0);\n  tpedh.nheadercols = tped_nheadercols;\n\n  nex_autosomal = nex_maf = nex_call_rate = 0;\n\n  for ( i=0, nin=0, nex = 0; tokenize_tped_line_with_col_headers( &tpedh, tped_nheadercols, delims, lbuf, snprow, tped_headers, &nelems, &nmiss) != NULL; ++i) {\n    if ( ( verbose ) && ( i % 10000 ) == 0 ) fprintf(stderr,\"Reading %d SNPs\\n\",i);\n\n    if ( ( flag_autosomal == 1 ) && ( ( atoi(tped_headers[0]) == 0 ) || ( atoi(tped_headers[0]) > 22 ) ) ) // if SNP is not in autosomal chromosomes\n      //if ( ( flag_autosomal == 1 ) && ( atoi(tped_headers[0]) > 22 ) ) // if SNP is not in autosomal chromosomes\n    {\n      ++nex; // # excluded snps from the last unit\n      ++nex_autosomal;\n      continue;\n    }\n\n    if ( nelems != n ) {\n      emmax_error(\"Number of values %d in line %d do not match to %d, the number of columns\\n\", nelems, tpedh.nvaluecols, n);\n    }\n\n  /*\n    Perform rapid kinship generate IBS, BN, NCOR matrix\n--------------------\nIBS pairwise matrix\n--------------------\ni/j  0  1  2  3\n0    NA NA NA NA\n1    NA 2  1  0 \n2    NA 1  2  1\n3    NA 0  1  2\n\nIn fact is what it does is\nX = (m*n) genotype matrix (1,2,3 coded)\nXn = X-2\nK = (t(Xn) %*% Xn)/(2*m)\n------------------\n* NA column may be just averaged or predicted based on r2 with previous SNP\n  with a certain window size\n\n---------------------\npairwise BN matrix\n--------------------\nX : (m*n) genotype matrix\nXn : (m*n) matrix each row standardized, missing assigned to 0\nK = t(Xn) %*% Xn / L\n--------------------\n*/\n\n    ac0 = ac1 = ac2 = 0;\n    for(j=0; j < n; ++j) {\n      if ( snprow[j] > 0 ) {\n\tif ( snprow[j] < 2 ) {\n\t  fprintf(stderr,\"Invalid snprow[%d] value %d at line %d, individual %d\\n\",j,(int)snprow[j],i,j);\n\t}\n\tsnprow[j] -= 2; // from 2,3,4 to 0,1,2 coding\n\n\tswitch(snprow[j]) {\n\tcase 0:\n\t  ++ac0;\n\t  break;\n\tcase 1:\n\t  ++ac1;\n\t  break;\n\tcase 2:\n\t  ++ac2; \n\t  break;\n\tdefault:\n\t  emmax_error(\"Unknown allele %s, converted to %d\\n\",buf,(int)snprow[j]);\n\t  break;\n\t}\n      }\n      else {\n\tsnprow[j] = (unsigned char)NA_GENO_CHAR;\n      }\n    }\n\n    call_rate = (double)(ac0+ac1+ac2)/(double)n;\n    //fprintf(stderr,\"CallRate = %lf\\n\", call_rate);\n    if ( call_rate <= call_rate_thres ) {\n      ++nex;\n      ++nex_call_rate;\n      continue;\n    }\n    aaf = (double)(ac1+2*ac2)/(double)(2*(ac0+ac1+ac2));\n    if ( ( aaf <= maf_thres ) || ( 1.-aaf <= maf_thres ) ) {\n      ++nex;\n      ++nex_maf;\n      continue;\n    }\n    \n    if ( rand_fill_flag == 1 ) {\n      for(j=0; j < n; ++j) {\n\tif ( snprow[j] == (unsigned char)NA_GENO_CHAR ) {\n\t  if ( (rand() / (double) RAND_MAX) > aaf ) {\n\t    if ( (rand() / (double) RAND_MAX) > aaf ) {\n\t      snprow[j] = (unsigned char)2;\n\t      //ac1 += 2;\n\t      ++ac2;\n\t    }\n\t    else {\n\t      snprow[j] = (unsigned char)1;\n\t      ++ac1;\n\t      //++ac0;\n\t      //++ac1;\n\t    }\n\t  }\n\t  else {\n\t    if ( (rand() / (double) RAND_MAX) > aaf ) {\n\t      snprow[j] = (unsigned char)1;\n\t      ++ac1;\n\t      //++ac0;\n\t      //++ac1;\n\t    }\n\t    else {\n\t      snprow[j] = (unsigned char)0;\n\t      ++ac0;\n\t      //ac0 += 2;\n\t    }\n\t  }\n\t}\n      }\n      aaf = (double)(ac1+2*ac2)/(double)(2*(ac0+ac1+ac2));\n      //aaf = (double)ac1/(double)(ac0+ac1);\n    }\n\n    // copy current values to arrays\n    // Xn = [-1,1] - two rows per SNP : IBS matrix\n    // Xn ~ N(0,1) : BN matrix\n    if ( ibs_flag == 1 ) {\n      for(j=0; j < n; ++j) {\n\tif ( snprow[j] == (unsigned char)NA_GENO_CHAR ) {\n\t  snpunit[nin+  j*n_unit_lines] = 2.*aaf-1.;\n\t  snpunit[nin+1+j*n_unit_lines] = 2.*aaf-1.;\n\t}\n\telse {\n\t  if ( snprow[j] == 0 ) {\n\t    snpunit[nin+  j*n_unit_lines] = -1.;\n\t    snpunit[nin+1+j*n_unit_lines] = -1.;\n\t  }\n\t  else if ( snprow[j] == 1 ) {\n\t    snpunit[nin+  j*n_unit_lines] = 1.;\n\t    snpunit[nin+1+j*n_unit_lines] = -1.;\n\t  }\n\t  else if ( snprow[j] == 2 ) {\n\t    snpunit[nin+  j*n_unit_lines] = 1.;\n\t    snpunit[nin+1+j*n_unit_lines] = 1.;\n\t  }\n\t  else {\n\t    emmax_error(\"Invalid genotype %d\\n\",snprow[j]);\n\t  }\n\t}\n      }\n      nin += 2;\n    }\n    else {\n      for(j=0; j < n; ++j) {\n\tif ( snprow[j] == (unsigned char)NA_GENO_CHAR ) {\n\t    snpunit[nin+j*n_unit_lines] = 0.;\n\t}\n\telse {\n\t  snpunit[nin+j*n_unit_lines] = ((double)snprow[j]-(aaf*2.))/sqrt(4*aaf*(1-aaf));\n\t}\n      }\n      ++nin;\n    }\n    \n    // check if nin == n_unit_lines \n    if ( nin >= n_unit_lines ) {\n      if ( verbose ) {\n\tfprintf(stderr,\"At SNP %d, intermediately computing kinship matrix with %d SNPs..\\n\",i,n_unit_lines);\n      }\n      // kin = kin + t(snpunit)%*%(snpunit)\n#ifdef INTEL_COMPILER\n      dgemm(&ct,&cn,&n,&n,&n_unit_lines,&one,snpunit,&n_unit_lines,snpunit,&n_unit_lines,&one,kin,&n);\n#else\n      cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans, n, n, n_unit_lines, 1.0, snpunit, n_unit_lines, snpunit, n_unit_lines, 1.0, kin, n);\n#endif\n      memset(snpunit, 0, sizeof(double)*n_unit_lines*n);\n\n      n_sum_nin += nin;\n      nin = 0;\n    }\n  }\n  close_file(&tpedh);\n\n  if ( verbose ) {\n    fprintf(stderr,\"Succesfully finished reading TPED file\\n\");\n  }\n  if ( nin > 0 ) {\n    if ( verbose ) {\n      fprintf(stderr,\"Computing kinship matrix with the remaining %d SNPs..\\n\",nin);\n    }\n#ifdef INTEL_COMPILER\n    dgemm(&ct,&cn,&n,&n,&n_unit_lines,&one,snpunit,&n_unit_lines,snpunit,&n_unit_lines,&one,kin,&n);\n#else\n    cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans, n, n, n_unit_lines, 1.0, snpunit, n_unit_lines, snpunit, n_unit_lines, 1.0, kin, n);\n#endif\n    n_sum_nin += nin;\n  }\n\n  if ( ibs_flag == 1 ) {\n    if ( rand_fill_flag == 1 ) {\n      suffix = \"rIBS.kinf\";\n    }\n    else {\n      suffix = \"aIBS.kinf\";\n    }\n  }\n  else {\n    if ( rand_fill_flag == 1 ) {\n      suffix = \"rBN.kinf\";\n    }\n    else {\n      suffix = \"aBN.kinf\";\n    }\n  }\n  kinsh = open_file_with_suffix( tpedf, suffix, 0, 1 );\n\n\n  if ( verbose ) fprintf(stderr,\"Printing the kinship matrix to file %s.%s\\n\",tpedf,suffix);\n\n  for(i=0; i < n; ++i) {\n    for(j=0; j < n; ++j) {\n      if ( j > 0 ) fprintf(kinsh.fp,\"\\t\");\n      f = (double)kin[i+j*n]/(double)(n_sum_nin);\n      if ( ibs_flag == 1 ) {\n\tfprintf(kinsh.fp,\"%-.*lf\",ndigits,0.5*f+0.5);\n      }\n      else {\n\tfprintf(kinsh.fp,\"%-.*lf\",ndigits,f);  \n      }\n    }\n    fprintf(kinsh.fp,\"\\n\");\n  }\n  close_file(&kinsh);\n  free(snprow);\n  free(kin);\n  free(snpunit);\n  free(lbuf);\n  free(tped_headers);\n  free(tfam_headers);\n  return 0;\n}\n", "meta": {"hexsha": "5e67228a536e4a2fccf07bd7d258d7a3051e3b97", "size": 18320, "ext": "c", "lang": "C", "max_stars_repo_path": "emmax-kin.c", "max_stars_repo_name": "slowkoni/EPI-EMMAX", "max_stars_repo_head_hexsha": "b214b602a8f7f90e13ab4b9ddeba811b67c03a19", "max_stars_repo_licenses": ["Intel"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "emmax-kin.c", "max_issues_repo_name": "slowkoni/EPI-EMMAX", "max_issues_repo_head_hexsha": "b214b602a8f7f90e13ab4b9ddeba811b67c03a19", "max_issues_repo_licenses": ["Intel"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-06-23T09:15:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-23T09:15:17.000Z", "max_forks_repo_path": "emmax-kin.c", "max_forks_repo_name": "slowkoni/EPI-EMMAX", "max_forks_repo_head_hexsha": "b214b602a8f7f90e13ab4b9ddeba811b67c03a19", "max_forks_repo_licenses": ["Intel"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-06-26T15:01:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-26T15:01:39.000Z", "avg_line_length": 29.7402597403, "max_line_length": 185, "alphanum_fraction": 0.6080786026, "num_tokens": 6049, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378235137849365, "lm_q2_score": 0.03358950504546607, "lm_q1q2_score": 0.014706275125302808}}
{"text": "/* ieee-utils/fp-gnuc99.c\n * \n * Copyright (C) 2003, 2004, 2007 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#define _GNU_SOURCE 1\n\n#include <math.h>\n#include <stdio.h>\n#include <fenv.h>\n#include <gsl/gsl_ieee_utils.h>\n#include <gsl/gsl_errno.h>\n\nint\ngsl_ieee_set_mode (int precision, int rounding, int exception_mask)\n{\n  int mode;\n\n  switch (precision)\n    {\n    case GSL_IEEE_SINGLE_PRECISION:\n      GSL_ERROR (\"single precision rounding is not supported by <fenv.h>\",\n                 GSL_EUNSUP) ;\n      break ;\n    case GSL_IEEE_DOUBLE_PRECISION:\n      GSL_ERROR (\"double precision rounding is not supported by <fenv.h>\",\n                 GSL_EUNSUP) ;\n      break ;\n    case GSL_IEEE_EXTENDED_PRECISION:\n      GSL_ERROR (\"extended precision rounding is not supported by <fenv.h>\",\n                 GSL_EUNSUP) ;\n      break ;\n    }\n\n\n  switch (rounding)\n    {\n    case GSL_IEEE_ROUND_TO_NEAREST:\n#ifdef FE_TONEAREST\n      fesetround (FE_TONEAREST) ;\n#else\n      GSL_ERROR (\"round-to-nearest is not supported by <fenv.h>\", GSL_EUNSUP) ;\n#endif\n      break ;\n    case GSL_IEEE_ROUND_DOWN:\n#ifdef FE_DOWNWARD\n      fesetround (FE_DOWNWARD) ;\n#else\n      GSL_ERROR (\"round-down is not supported by <fenv.h>\", GSL_EUNSUP) ;\n#endif\n      break ;\n    case GSL_IEEE_ROUND_UP:\n#ifdef FE_UPWARD\n      fesetround (FE_UPWARD) ;\n#else\n      GSL_ERROR (\"round-up is not supported by <fenv.h>\", GSL_EUNSUP) ;\n#endif\n      break ;\n    case GSL_IEEE_ROUND_TO_ZERO:\n#ifdef FE_TOWARDZERO\n      fesetround (FE_TOWARDZERO) ;\n#else\n      GSL_ERROR (\"round-toward-zero is not supported by <fenv.h>\", GSL_EUNSUP) ;\n#endif\n      break ;\n    default:\n#ifdef FE_TONEAREST\n      fesetround (FE_TONEAREST) ;\n#else\n      GSL_ERROR (\"default round-to-nearest mode is not supported by <fenv.h>\", GSL_EUNSUP) ;\n#endif\n    }\n\n  /* Turn on all the exceptions apart from 'inexact' */\n\n  mode = 0;\n\n#ifdef FE_INVALID \n  mode |= FE_INVALID;\n#endif\n\n#ifdef FE_DIVBYZERO\n  mode |= FE_DIVBYZERO;\n#endif\n  \n#ifdef FE_OVERFLOW\n  mode |= FE_OVERFLOW ;\n#endif\n\n#ifdef FE_UNDERFLOW\n  mode |= FE_UNDERFLOW ;\n#endif\n\n  if (exception_mask & GSL_IEEE_MASK_INVALID)\n    {\n#ifdef FE_INVALID\n    mode &= ~ FE_INVALID ;\n#else\n    GSL_ERROR (\"invalid operation exception not supported by <fenv.h>\", \n               GSL_EUNSUP);\n#endif\n    }\n\n  if (exception_mask & GSL_IEEE_MASK_DENORMALIZED)\n    {\n      /* do nothing */\n    }\n  else\n    {\n      GSL_ERROR (\"denormalized operand exception not supported by <fenv.h>. \"\n                 \"Use 'mask-denormalized' to work around this.\", GSL_EUNSUP) ;\n    }\n\n  if (exception_mask & GSL_IEEE_MASK_DIVISION_BY_ZERO)\n    {\n#ifdef FE_DIVBYZERO\n      mode &= ~ FE_DIVBYZERO ;\n#else\n      GSL_ERROR (\"division by zero exception not supported by <fenv.h>\", \n                 GSL_EUNSUP);\n#endif\n    }\n\n  if (exception_mask & GSL_IEEE_MASK_OVERFLOW)\n    {\n#ifdef FE_OVERFLOW\n      mode &= ~ FE_OVERFLOW ;\n#else\n      GSL_ERROR (\"overflow exception not supported by <fenv.h>\", GSL_EUNSUP);\n#endif\n    }\n\n  if (exception_mask & GSL_IEEE_MASK_UNDERFLOW)\n    {\n#ifdef FE_UNDERFLOW\n      mode &=  ~ FE_UNDERFLOW ;\n#else\n      GSL_ERROR (\"underflow exception not supported by <fenv.h>\", GSL_EUNSUP);\n#endif\n    }\n\n  if (exception_mask & GSL_IEEE_TRAP_INEXACT)\n    {\n#ifdef FE_INEXACT\n      mode |= FE_INEXACT ;\n#else\n      GSL_ERROR (\"inexact exception not supported by <fenv.h>\", GSL_EUNSUP);\n#endif\n    }\n  else\n    {\n#ifdef FE_INEXACT\n      mode &= ~ FE_INEXACT ;\n#else\n      /* do nothing */\n#endif\n    }\n\n#if HAVE_DECL_FEENABLEEXCEPT\n  feenableexcept (mode) ;\n#elif HAVE_DECL_FESETTRAPENABLE\n  fesettrapenable (mode);\n#else\n  GSL_ERROR (\"unknown exception trap method\", GSL_EUNSUP)\n#endif\n\n  return GSL_SUCCESS ;\n}\n", "meta": {"hexsha": "70dcbefd91031cc8e01e3b4a5e07e6ca65fc9038", "size": 4400, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/ieee-utils/fp-gnuc99.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/ieee-utils/fp-gnuc99.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/ieee-utils/fp-gnuc99.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 24.043715847, "max_line_length": 92, "alphanum_fraction": 0.6725, "num_tokens": 1168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2751297238231752, "lm_q2_score": 0.05340332678672523, "lm_q1q2_score": 0.014692842550070485}}
{"text": "///\n/// @file\n///\n/// @author Mirko Myllykoski (mirkom@cs.umu.se), Ume\u00e5 University\n///\n/// @internal LICENSE\n///\n/// Copyright (c) 2019-2020, Ume\u00e5 Universitet\n///\n/// Redistribution and use in source and binary forms, with or without\n/// modification, are permitted provided that the following conditions are met:\n///\n/// 1. Redistributions of source code must retain the above copyright notice,\n///    this list of conditions and the following disclaimer.\n///\n/// 2. Redistributions in binary form must reproduce the above copyright notice,\n///    this list of conditions and the following disclaimer in the documentation\n///    and/or other materials provided with the distribution.\n///\n/// 3. Neither the name of the copyright holder nor the names of its\n///    contributors may be used to endorse or promote products derived from this\n///    software without specific prior written permission.\n///\n/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n/// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n/// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n/// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n/// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n/// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n/// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n/// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n/// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n/// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n/// POSSIBILITY OF SUCH DAMAGE.\n///\n\n#include <starneig_config.h>\n#include <starneig/configuration.h>\n#include \"sirobust-geig.h\"\n#include \"robust.h\"\n#include \"../common/common.h\"\n#include \"../common/node_internal.h\"\n#include <starneig/gep_sm.h>\n#include <cblas.h>\n#include <stdlib.h>\n#include <starpu.h>\n\n__attribute__ ((visibility (\"default\")))\nstarneig_error_t starneig_GEP_SM_Eigenvectors_expert(\n    struct starneig_eigenvectors_conf *_conf,\n    int n,\n    int selected[],\n    double S[], int ldS,\n    double T[], int ldT,\n    double Z[], int ldZ,\n    double X[], int ldX)\n{\n    if (n < 1)              return -2;\n    if (selected == NULL)   return -3;\n    if (S == NULL)          return -4;\n    if (ldS < n)            return -5;\n    if (T == NULL)          return -6;\n    if (ldT < n)            return -7;\n    if (Z == NULL)          return -8;\n    if (ldZ < n)            return -9;\n    if (X == NULL)          return -10;\n    if (ldX < n)            return -11;\n\n    if (!starneig_node_initialized())\n        return STARNEIG_NOT_INITIALIZED;\n\n    starneig_error_t ret = STARNEIG_SUCCESS;\n    double *_X = NULL; int ld_X;\n\n    // use default configuration if necessary\n    struct starneig_eigenvectors_conf *conf;\n    struct starneig_eigenvectors_conf local_conf;\n    if (_conf == NULL)\n        starneig_eigenvectors_init_conf(&local_conf);\n    else\n        local_conf = *_conf;\n    conf = &local_conf;\n\n    if (conf->tile_size == STARNEIG_EIGENVECTORS_DEFAULT_TILE_SIZE) {\n        conf->tile_size = MAX(64, divceil(0.016*n, 8)*8);\n        starneig_message(\"Setting tile size to %d.\", conf->tile_size);\n    }\n    else if (conf->tile_size < 8) {\n        starneig_error(\"Invalid tile size.\");\n        ret = STARNEIG_INVALID_CONFIGURATION;\n        goto cleanup;\n    }\n\n    int selected_count = 0;\n    for (int i = 0; i < n; i++)\n        if (selected[i]) selected_count++;\n\n    {\n        size_t ld;\n        _X = starneig_alloc_matrix(n, selected_count, sizeof(double), &ld);\n        ld_X = ld;\n    }\n\n    //\n    // solve\n    //\n\n    starneig_node_set_blas_mode(STARNEIG_BLAS_MODE_SEQUENTIAL);\n    starneig_node_set_mode(STARNEIG_MODE_SM);\n    starneig_node_resume_starpu();\n\n    starneig_eigvec_gen_initialize_omega(100);\n    int _ret = starneig_eigvec_gen_sinew(n, S, ldS, T, ldT, selected, _X, ld_X,\n        conf->tile_size, conf->tile_size);\n\n    starpu_task_wait_for_all();\n    starneig_node_pause_starpu();\n    starneig_node_set_blas_mode(STARNEIG_BLAS_MODE_ORIGINAL);\n\n    if (_ret != 0) {\n        ret = STARNEIG_GENERIC_ERROR;\n        goto cleanup;\n    }\n\n    //\n    // back transformation\n    //\n\n    starneig_node_set_blas_mode(STARNEIG_BLAS_MODE_PARALLEL);\n    starneig_node_pause_awake_starpu();\n\n    cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans,\n        n, selected_count, n, 1.0, Z, ldZ, _X, ld_X, 0.0, X, ldX);\n\n    starneig_node_resume_awake_starpu();\n    starneig_node_set_blas_mode(STARNEIG_BLAS_MODE_ORIGINAL);\n\ncleanup:\n\n    starneig_free_matrix(_X);\n\n    return ret;\n}\n\n__attribute__ ((visibility (\"default\")))\nstarneig_error_t starneig_GEP_SM_Eigenvectors(\n    int n,\n    int selected[],\n    double S[], int ldS,\n    double T[], int ldT,\n    double Z[], int ldZ,\n    double X[], int ldX)\n{\n    if (n < 1)              return -1;\n    if (selected == NULL)   return -2;\n    if (S == NULL)          return -3;\n    if (ldS < n)            return -4;\n    if (T == NULL)          return -5;\n    if (ldT < n)            return -6;\n    if (Z == NULL)          return -7;\n    if (ldZ < n)            return -8;\n    if (X == NULL)          return -9;\n    if (ldX < n)            return -10;\n\n    if (!starneig_node_initialized())\n        return STARNEIG_NOT_INITIALIZED;\n\n    return starneig_GEP_SM_Eigenvectors_expert(\n        NULL, n, selected, S, ldS, T, ldT, Z, ldZ, X, ldX);\n}\n", "meta": {"hexsha": "2921eda8d05f3d38b75d960ee0f9eb050ccd67c8", "size": 5476, "ext": "c", "lang": "C", "max_stars_repo_path": "src/eigenvectors/generalized/interface.c", "max_stars_repo_name": "NLAFET/StarNEig", "max_stars_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2019-04-28T17:13:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-24T12:30:19.000Z", "max_issues_repo_path": "src/eigenvectors/generalized/interface.c", "max_issues_repo_name": "NLAFET/StarNEig", "max_issues_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/eigenvectors/generalized/interface.c", "max_forks_repo_name": "NLAFET/StarNEig", "max_forks_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-04-30T12:14:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-14T09:41:23.000Z", "avg_line_length": 32.0233918129, "max_line_length": 80, "alphanum_fraction": 0.650109569, "num_tokens": 1479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356686808225123, "lm_q2_score": 0.03622005183364064, "lm_q1q2_score": 0.014617212880279153}}
{"text": "#ifndef libceed_solids_examples_utils_h\n#define libceed_solids_examples_utils_h\n\n#include <ceed.h>\n#include <petsc.h>\n\n// Translate PetscMemType to CeedMemType\nstatic inline CeedMemType MemTypeP2C(PetscMemType mem_type) {\n  return PetscMemTypeDevice(mem_type) ? CEED_MEM_DEVICE : CEED_MEM_HOST;\n}\n\n#endif // libceed_solids_examples_utils_h\n", "meta": {"hexsha": "685339916afbd3192b9706f87a390c508063390f", "size": 340, "ext": "h", "lang": "C", "max_stars_repo_path": "examples/solids/include/utils.h", "max_stars_repo_name": "wence-/libCEED", "max_stars_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/solids/include/utils.h", "max_issues_repo_name": "wence-/libCEED", "max_issues_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/solids/include/utils.h", "max_forks_repo_name": "wence-/libCEED", "max_forks_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1538461538, "max_line_length": 72, "alphanum_fraction": 0.8294117647, "num_tokens": 91, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16451646289656316, "lm_q2_score": 0.0888202857672853, "lm_q1q2_score": 0.01461239924789573}}
{"text": "/* combination/gsl_combination.h\n * based on permutation/gsl_permutation.h by Brian Gough\n * \n * Copyright (C) 2001 Szymon Jaroszewicz\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_COMBINATION_H__\n#define __GSL_COMBINATION_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_check_range.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\nstruct gsl_combination_struct\n{\n  size_t n;\n  size_t k;\n  size_t *data;\n};\n\ntypedef struct gsl_combination_struct gsl_combination;\n\ngsl_combination *gsl_combination_alloc (const size_t n, const size_t k);\ngsl_combination *gsl_combination_calloc (const size_t n, const size_t k);\nvoid gsl_combination_init_first (gsl_combination * c);\nvoid gsl_combination_init_last (gsl_combination * c);\nvoid gsl_combination_free (gsl_combination * c);\nint gsl_combination_memcpy (gsl_combination * dest, const gsl_combination * src); \n\nint gsl_combination_fread (FILE * stream, gsl_combination * c);\nint gsl_combination_fwrite (FILE * stream, const gsl_combination * c);\nint gsl_combination_fscanf (FILE * stream, gsl_combination * c);\nint gsl_combination_fprintf (FILE * stream, const gsl_combination * c, const char *format);\n\nsize_t gsl_combination_n (const gsl_combination * c);\nsize_t gsl_combination_k (const gsl_combination * c);\nsize_t * gsl_combination_data (const gsl_combination * c);\n\nsize_t gsl_combination_get (const gsl_combination * c, const size_t i);\n\nint gsl_combination_valid (gsl_combination * c);\nint gsl_combination_next (gsl_combination * c);\nint gsl_combination_prev (gsl_combination * c);\n\n#ifdef HAVE_INLINE\n\nextern inline\nsize_t\ngsl_combination_get (const gsl_combination * c, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (i >= c->k)\n    {\n      GSL_ERROR_VAL (\"index out of range\", GSL_EINVAL, 0);\n    }\n#endif\n  return c->data[i];\n}\n\n#endif /* HAVE_INLINE */\n\n__END_DECLS\n\n#endif /* __GSL_COMBINATION_H__ */\n", "meta": {"hexsha": "ece1b728754a8593db07f767a2ed3ef5b83e36f9", "size": 2769, "ext": "h", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/combination/gsl_combination.h", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/combination/gsl_combination.h", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/combination/gsl_combination.h", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 30.097826087, "max_line_length": 91, "alphanum_fraction": 0.7656193572, "num_tokens": 721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3522017820478897, "lm_q2_score": 0.041462271378916615, "lm_q1q2_score": 0.014603085867407646}}
{"text": "# ifndef __HEADER__GA__\n# define __HEADER__GA__\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <gsl/gsl_math.h>\n#include \"utils.h\"\n\n# define UL_SIZE sizeof(unsigned long)\n\n# define GENES_C1 3\n# define GENES_C2 11\n\n// we are going to use a two chromosome genome,\ntypedef struct Genome {\n\tunsigned long c1[GENES_C1];\n\tunsigned long c2[GENES_C2];\n\tdouble fitness;\n} Genome;\n\nvoid generate_genome(Genome * genome);\n\nGenome * generate_population(int individuals);\nint next_generation(\n\tGenome * parents, Genome * children,\n\tint n_elitism, int n_select, int n_cross, int n_new, double p_mutation, int mutation_bit\n);\n\n/*\n * Copies the information in the input genome to the output genome.\n * Note that the fitness function is also copied over.\n */\nvoid copy_genome(Genome * in, Genome * out);\n\n// a.k.a crossover\nvoid tinder(Genome * population, int pop_size, Genome * out);\n// actual crossover\nvoid crossover_genomes(\n\tGenome * gen1in,\n\tGenome * gen2in,\n\tGenome * out\n);\n\nvoid mutate_genome(Genome * genome, double p_mut);\n\n/*\n * Implementation of elitism operator.\n * This selects the best of the best individuals to be passed over to the next generation.\n *\n * @param population the initial population with fitness values calculated\n * @param pop_size the total population size\n * @param number_elitism the number of best individuals to be selected\n * @param out the population to be filled with the best individuals\n *\n * @return the position of the best individual\n */\n\n\nint extinction(int ek, Genome * population, Genome * survivors, int pop_size, int number_survivors);\n\n\n\n\nvoid elitism(Genome * population, int pop_size, int number_elitism, Genome * out);\n\n/*\n * Implementation of roulette wheel method.\n * This method chooses the individuals according to their fidelity, individuals with\n * lower fidelity have a lower change of being selected.\n *\n * @param population the initial population with fitness values calculated\n * @param pop_size the total population size\n * @param best_genomes the number of best individuals to choose\n * @param out the population to be filled with the best individuals\n */\nint casting(Genome * population, int pop_size, int best_genomes, Genome * out);\n\n/*\n * Add `n_new` individuals to the start of the passed genome array.\n */\nvoid migration(\n\tGenome * genome,\n\tint n_new\n);\n\n# endif\n", "meta": {"hexsha": "837a03a2c4445025e127083ce9788579ad955959", "size": 2342, "ext": "h", "lang": "C", "max_stars_repo_path": "old/src/ga.h", "max_stars_repo_name": "urisawsing/Covid_GeneticAlg", "max_stars_repo_head_hexsha": "cd4518b79d596a924660348e3799cc2594798aae", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "old/src/ga.h", "max_issues_repo_name": "urisawsing/Covid_GeneticAlg", "max_issues_repo_head_hexsha": "cd4518b79d596a924660348e3799cc2594798aae", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-01-19T15:17:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-05T17:16:45.000Z", "max_forks_repo_path": "old/src/ga.h", "max_forks_repo_name": "urisawsing/Covid_GeneticAlg", "max_forks_repo_head_hexsha": "cd4518b79d596a924660348e3799cc2594798aae", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-23T11:40:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-23T11:40:36.000Z", "avg_line_length": 26.6136363636, "max_line_length": 100, "alphanum_fraction": 0.7519214347, "num_tokens": 556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326184801538616, "lm_q2_score": 0.03210070949490525, "lm_q1q2_score": 0.014550026908265805}}
{"text": "//\n//     smctc.h\n//\n//     The principle header file for the SMC template class.\n//\n//     Copyright Adam Johansen, 2008\n//\n//\n//   This file is part of SMCTC.\n//\n//   SMCTC is free software: you can redistribute it and/or modify\n//   it under the terms of the GNU General Public License as published by\n//   the Free Software Foundation, either version 3 of the License, or\n//   (at your option) any later version.\n//\n//   SMCTC is distributed in the hope that it will be useful,\n//   but WITHOUT ANY WARRANTY; without even the implied warranty of\n//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n//   GNU General Public License for more details.\n//\n//   You should have received a copy of the GNU General Public License\n//   along with SMCTC.  If not, see <http://www.gnu.org/licenses/>.\n//\n\n/// \\mainpage smctc -- A Template Class Library for SMC Simulation\n///  \n/// \\version 1.0\n/// \\author Adam M. Johansen\n///\n/// \\section intro_sec Summary\n///\n/// The SMC template class library (SMCTC) is intended to be used to implement SMC \n/// algorithms ranging from simple particle filter to complicated SMC algorithms\n/// from simple particle filters to the SMC samplers of Del Moral, Doucet and Jasra (2006) \n/// within a generic framework.\n///\n/// \\section license License\n///\n/// SMCTC is free software: you can redistribute it and/or modify\n/// it under the terms of the GNU General Public License as published by\n/// the Free Software Foundation, either version 3 of the License, or\n/// (at your option) any later version.\n///\n/// SMCTC is distributed in the hope that it will be useful,\n/// but WITHOUT ANY WARRANTY; without even the implied warranty of\n/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n/// GNU General Public License for more details.\n///\n/// You should have received a copy of the GNU General Public License\n/// along with SMCTC.  If not, see <http://www.gnu.org/licenses/>.\n/// \n/// The software is still in development but is thought to be sufficiently fully-featured and\n/// stable for use.\n///\n/// \\section using_sec Using the Template Library\n///\n/// In order to use the template libary it is necessary to place the set of header files in \n/// a suitable include directory and then to instantiate the various classes with the \n/// appropriate type for your sampler.\n///\n/// For implementation details, please see the accompanying user guide.\n/// \n///\n/// \\section example_sec Examples\n///\n/// \\subsection A Simple Particle Filter\n///\n/// This example provides a simple particle filter for the approximate filtering of\n/// nonlinear, nongaussian state space models.\n///\n/// \\subsection SMC Samplers for Rare Event Simulation\n/// \n/// The main.cc file provides an example of a use of the template library to estimate \n/// Gaussian tail probabilities within an SMC samplers framework by making use of a sequence \n/// of intermediate distributions defined by introducing a potential function which\n/// varies from flat to being very close to an indicator function on the tail event.\n///\n/// This example is taken from from Johansen, Del Moral and Doucet (2006).\n///\n/// \\subsection Acknowledgements\n///\n/// Thanks are due to Edmund Jackson and Mark Briers for testing SMCTC on a variety of platforms.\n/// The Visual C++ project and solution files are kindly provided by Mark Briers.\n///\n\n//! \\file\n//! \\brief The main header file for SMCTC.\n//!\n//! This file serves as an interface between user-space programs and the SMCTC library.\n//! This is the only header file which applications need to include to make use of the library (it includes\n//! such additional files as are necessary).\n\n#ifndef __SMC_TDSMC_HH\n\n#define __SMC_TDSMC_HH 1.0\n\n#include <cmath>\n#include <cstdlib>\n#include <iostream>\n\n#include <gsl/gsl_rng.h>\n\n#include \"smc-exception.h\"\n#include \"sampler.h\"\n\n/// The Sequential Monte Carlo namespace\n\n///\n///    The classes and functions within this namespace are intended to be used for producing\n///    implemenetations of SMC samplers and related simulation techniques.\n\nnamespace smc {}\n\n/// The standard namespace \n\n///     The classes provided within the standard libraries reside within this namespace and \n///     the TDSMC class library adds a number of additional operator overloads to some of\n///     the standard classes to allow them to deal with our structures.\n\nnamespace std {}\n#endif\n", "meta": {"hexsha": "ce04c873d81f1bc15df8c662831b05ca3654eebe", "size": 4373, "ext": "h", "lang": "C", "max_stars_repo_path": "include/smctc.h", "max_stars_repo_name": "williamg42/IMU-GPS-Fusion", "max_stars_repo_head_hexsha": "58cb79d35e35786ecea1bf8023a639fd8bb148c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2018-03-22T09:11:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T15:16:46.000Z", "max_issues_repo_path": "include/smctc.h", "max_issues_repo_name": "williamg42/IMU-GPS-Fusion", "max_issues_repo_head_hexsha": "58cb79d35e35786ecea1bf8023a639fd8bb148c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-03-22T09:21:20.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-02T17:45:59.000Z", "max_forks_repo_path": "include/smctc.h", "max_forks_repo_name": "williamg42/IMU-GPS-Fusion", "max_forks_repo_head_hexsha": "58cb79d35e35786ecea1bf8023a639fd8bb148c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2018-05-26T22:34:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-08T13:20:35.000Z", "avg_line_length": 35.8442622951, "max_line_length": 107, "alphanum_fraction": 0.7285616282, "num_tokens": 981, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2845759920814681, "lm_q2_score": 0.051082739123977504, "lm_q1q2_score": 0.014536921164444723}}
{"text": "/**\n * @copyright (c) 2017 King Abdullah University of Science and Technology (KAUST).\n *                     All rights reserved.\n **/\n/**\n * @file auxcompute_z.h\n *\n * This file contains the declarations of computational auxiliary functions.\n *\n * HiCMA is a software package provided by King Abdullah University of Science and Technology (KAUST)\n *\n * @version 0.1.1\n * @author Kadir Akbudak\n * @date 2018-11-08\n **/\n#ifndef __AUXCOMPUTE_Z__\n#define __AUXCOMPUTE_Z__\n\n#include \"hicma_struct.h\"\n#ifdef MKL\n  #include <mkl.h>\n  //#pragma message(\"MKL is used\")\n#else\n  #include <cblas.h>\n  #ifdef LAPACKE_UTILS\n    #include <lapacke_utils.h>\n  #endif\n  #include <lapacke.h>\n  //#pragma message(\"MKL is NOT used\")\n#endif\n\n#include <stdio.h>\n#include \"morse.h\"\n#ifndef min\n#define min(a, b) ((a) < (b) ? (a) : (b))\n#endif\n\n\n#include \"starsh.h\"\nint HICMA_zuncompress(\n        MORSE_enum uplo, MORSE_desc_t *AUV, MORSE_desc_t *AD, MORSE_desc_t *Ark);\nint HICMA_zuncompress_custom_size(MORSE_enum uplo,\n        MORSE_desc_t *AUV, MORSE_desc_t *AD, MORSE_desc_t *Ark,\n        int numrows_matrix,\n        int numcolumns_matrix,\n        int numrows_block,\n        int numcolumns_block\n        );\nint HICMA_zdiag_vec2mat(\n        MORSE_desc_t *vec, MORSE_desc_t *mat);\nvoid HICMA_znormest( int M, int N, double *A, double *e, double *work);\nvoid HICMA_zgenerate_problem(\n        int probtype, //problem type defined in hicma_constants.h \n        char sym,     // symmetricity of problem: 'N' or 'S'\n        double decay, // decay of singular values. Will be used in HICMA_STARSH_PROB_RND. Set 0 for now.\n        int _M,       // number of rows/columns of matrix\n        int _nb,      // number of rows/columns of a single tile\n        int _mt,      // number of tiles in row dimension\n        int _nt,      // number of tiles in column dimension\n        HICMA_problem_t *hicma_problem // pointer to hicma struct (starsh format will be used to pass coordinate info to number generation and compression phase)\n        );\n#endif\n", "meta": {"hexsha": "20434e9a11c52a1da95d9fdeac0f847d6dc630ec", "size": 2018, "ext": "h", "lang": "C", "max_stars_repo_path": "aux/include/auxcompute_z.h", "max_stars_repo_name": "Quansight/hicma", "max_stars_repo_head_hexsha": "c8287eed9ea9a803fc88ab067426ac6baacaa534", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "aux/include/auxcompute_z.h", "max_issues_repo_name": "Quansight/hicma", "max_issues_repo_head_hexsha": "c8287eed9ea9a803fc88ab067426ac6baacaa534", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-04-08T11:06:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-08T11:06:39.000Z", "max_forks_repo_path": "aux/include/auxcompute_z.h", "max_forks_repo_name": "isabella232/hicma", "max_forks_repo_head_hexsha": "c8287eed9ea9a803fc88ab067426ac6baacaa534", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-08T11:05:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-08T11:05:38.000Z", "avg_line_length": 32.0317460317, "max_line_length": 161, "alphanum_fraction": 0.6724479683, "num_tokens": 567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.02976009448379241, "lm_q1q2_score": 0.014531359978870997}}
{"text": "/*\n * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The OpenAirInterface Software Alliance licenses this file to You under\n * the OAI Public License, Version 1.1  (the \"License\"); you may not use this file\n * except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.openairinterface.org/?page_id=698\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *-------------------------------------------------------------------------------\n * For more information about the OpenAirInterface (OAI) Software Alliance:\n *      contact@openairinterface.org\n */\n\n/*! \\file PHY/LTE_TRANSPORT/dlsch_demodulation.c\n * \\brief Top-level routines for demodulating the PDSCH physical channel from 36-211, V8.6 2009-03\n * \\author R. Knopp, F. Kaltenberger,A. Bhamri, S. Aubert, X. Xiang\n * \\date 2011\n * \\version 0.1\n * \\company Eurecom\n * \\email: knopp@eurecom.fr,florian.kaltenberger@eurecom.fr,ankit.bhamri@eurecom.fr,sebastien.aubert@eurecom.fr\n * \\note\n * \\warning\n */\n#include \"PHY/defs_UE.h\"\n#include \"PHY/phy_extern_ue.h\"\n#include \"SCHED_UE/sched_UE.h\"\n#include \"transport_ue.h\"\n#include \"transport_proto_ue.h\"\n#include \"PHY/sse_intrin.h\"\n#include \"T.h\"\n#include<stdio.h>\n#include<math.h>\n#include <stdlib.h>\n#include <string.h>\n#include <linux/version.h>\n#if RHEL_RELEASE_CODE >= 1796\n  #include <lapacke/lapacke_utils.h>\n  #include <lapacke/lapacke.h>\n#else\n  #include <lapacke_utils.h>\n  #include <lapacke.h>\n#endif\n#include <cblas.h>\n#include \"linear_preprocessing_rec.h\"\n\n#define NOCYGWIN_STATIC\n//#define DEBUG_MMSE\n\n\n/* dynamic shift for LLR computation for TM3/4\n * set as command line argument, see lte-softmodem.c\n * default value: 0\n */\nint16_t dlsch_demod_shift = 0;\nint16_t interf_unaw_shift = 13;\n\n//#define DEBUG_HARQ\n\n//#define DEBUG_PHY 1\n//#define DEBUG_DLSCH_DEMOD 1\n\n//#define DISABLE_LOG_X\n\n// [MCS][i_mod (0,1,2) = (2,4,6)]\nunsigned char offset_mumimo_llr_drange_fix=0;\n//inferference-free case\nunsigned char interf_unaw_shift_tm4_mcs[29]= {5, 3, 4, 3, 3, 2, 1, 1, 2, 0, 1, 1, 1, 1, 0, 0,\n                                              1, 1, 1, 1, 0, 2, 1, 0, 1, 0, 1, 0, 0\n                                             } ;\nunsigned char interf_unaw_shift_tm1_mcs[29]= {5, 5, 4, 3, 3, 3, 2, 2, 4, 4, 2, 3, 3, 3, 1, 1,\n                                              0, 1, 1, 2, 5, 4, 4, 6, 5, 1, 0, 5, 6\n                                             } ; // mcs 21, 26, 28 seem to be errorneous\n\n/*\n//original values from sebastion + same hand tuning\nunsigned char offset_mumimo_llr_drange[29][3]={{8,8,8},{7,7,7},{7,7,7},{7,7,7},{6,6,6},{6,6,6},{6,6,6},{5,5,5},{4,4,4},{1,2,4}, // QPSK\n{5,5,4},{5,5,5},{5,5,5},{3,3,3},{2,2,2},{2,2,2},{2,2,2}, // 16-QAM\n{2,2,1},{3,3,3},{3,3,3},{3,3,1},{2,2,2},{2,2,2},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0}}; //64-QAM\n*/\n/*\n//first optimization try\nunsigned char offset_mumimo_llr_drange[29][3]={{7, 8, 7},{6, 6, 7},{6, 6, 7},{6, 6, 6},{5, 6, 6},{5, 5, 6},{5, 5, 6},{4, 5, 4},{4, 3, 4},{3, 2, 2},{6, 5, 5},{5, 4, 4},{5, 5, 4},{3, 3, 2},{2, 2, 1},{2, 1, 1},{2, 2, 2},{3, 3, 3},{3, 3, 2},{3, 3, 2},{3, 2, 1},{2, 2, 2},{2, 2, 2},{0, 0, 0},{0, 0, 0},{0, 0, 0},{0, 0, 0},{0, 0, 0}};\n*/\n//second optimization try\n/*\n  unsigned char offset_mumimo_llr_drange[29][3]={{5, 8, 7},{4, 6, 8},{3, 6, 7},{7, 7, 6},{4, 7, 8},{4, 7, 4},{6, 6, 6},{3, 6, 6},{3, 6, 6},{1, 3, 4},{1, 1, 0},{3, 3, 2},{3, 4, 1},{4, 0, 1},{4, 2, 2},{3, 1, 2},{2, 1, 0},{2, 1, 1},{1, 0, 1},{1, 0, 1},{0, 0, 0},{1, 0, 0},{0, 0, 0},{0, 1, 0},{1, 0, 0},{0, 0, 0},{0, 0, 0},{0, 0, 0},{0, 0, 0}};  w\n*/\nunsigned char offset_mumimo_llr_drange[29][3]= {{0, 6, 5},{0, 4, 5},{0, 4, 5},{0, 5, 4},{0, 5, 6},{0, 5, 3},{0, 4, 4},{0, 4, 4},{0, 3, 3},{0, 1, 2},{1, 1, 0},{1, 3, 2},{3, 4, 1},{2, 0, 0},{2, 2, 2},{1, 1, 1},{2, 1, 0},{2, 1, 1},{1, 0, 1},{1, 0, 1},{0, 0, 0},{1, 0, 0},{0, 0, 0},{0, 1, 0},{1, 0, 0},{0, 0, 0},{0, 0, 0},{0, 0, 0},{0, 0, 0}};\n\n\nextern void print_shorts(char *s,int16_t *x);\n\n\nint rx_pdsch(PHY_VARS_UE *ue,\n             PDSCH_t type,\n             unsigned char eNB_id,\n             unsigned char eNB_id_i, //if this == ue->n_connected_eNB, we assume MU interference\n             uint32_t frame,\n             uint8_t subframe,\n             unsigned char symbol,\n             unsigned char first_symbol_flag,\n             RX_type_t rx_type,\n             unsigned char i_mod,\n             unsigned char harq_pid) {\n  LTE_UE_COMMON *common_vars  = &ue->common_vars;\n  LTE_UE_PDSCH **pdsch_vars;\n  LTE_DL_FRAME_PARMS *frame_parms    = &ue->frame_parms;\n  PHY_MEASUREMENTS *measurements = &ue->measurements;\n  LTE_UE_DLSCH_t   **dlsch;\n  int avg[4];\n  int avg_0[2];\n  int avg_1[2];\n  unsigned short mmse_flag=0;\n#if UE_TIMING_TRACE\n  uint8_t slot = 0;\n#endif\n  unsigned char aatx,aarx;\n  unsigned short nb_rb = 0, round;\n  int avgs = 0, rb;\n  LTE_DL_UE_HARQ_t *dlsch0_harq,*dlsch1_harq = 0;\n  uint8_t beamforming_mode;\n  uint32_t *rballoc;\n  int32_t **rxdataF_comp_ptr;\n  int32_t **dl_ch_mag_ptr;\n  int32_t codeword_TB0 = -1;\n  int32_t codeword_TB1 = -1;\n\n  switch (type) {\n    case SI_PDSCH:\n      pdsch_vars = &ue->pdsch_vars_SI[eNB_id];\n      dlsch = &ue->dlsch_SI[eNB_id];\n      dlsch0_harq = dlsch[0]->harq_processes[harq_pid];\n      beamforming_mode  = 0;\n      break;\n\n    case RA_PDSCH:\n      pdsch_vars = &ue->pdsch_vars_ra[eNB_id];\n      dlsch = &ue->dlsch_ra[eNB_id];\n      dlsch0_harq = dlsch[0]->harq_processes[harq_pid];\n      beamforming_mode  = 0;\n      break;\n\n    case PDSCH:\n      pdsch_vars = ue->pdsch_vars[ue->current_thread_id[subframe]];\n      dlsch = ue->dlsch[ue->current_thread_id[subframe]][eNB_id];\n      //printf(\"status TB0 = %d, status TB1 = %d \\n\", dlsch[0]->harq_processes[harq_pid]->status, dlsch[1]->harq_processes[harq_pid]->status);\n      LOG_D(PHY,\"AbsSubframe %d.%d / Sym %d harq_pid %d,  harq status %d.%d \\n\",\n            frame,subframe,symbol,harq_pid,\n            dlsch[0]->harq_processes[harq_pid]->status,\n            dlsch[1]->harq_processes[harq_pid]->status);\n\n      if ((dlsch[0]->harq_processes[harq_pid]->status == ACTIVE) &&\n          (dlsch[1]->harq_processes[harq_pid]->status == ACTIVE)) {\n        codeword_TB0 = dlsch[0]->harq_processes[harq_pid]->codeword;\n        codeword_TB1 = dlsch[1]->harq_processes[harq_pid]->codeword;\n        dlsch0_harq = dlsch[codeword_TB0]->harq_processes[harq_pid];\n        dlsch1_harq = dlsch[codeword_TB1]->harq_processes[harq_pid];\n#ifdef DEBUG_HARQ\n        printf(\"[DEMOD] I am assuming both TBs are active\\n\");\n#endif\n      } else if ((dlsch[0]->harq_processes[harq_pid]->status == ACTIVE) &&\n                 (dlsch[1]->harq_processes[harq_pid]->status != ACTIVE) ) {\n        codeword_TB0 = dlsch[0]->harq_processes[harq_pid]->codeword;\n        dlsch0_harq = dlsch[0]->harq_processes[harq_pid];\n        dlsch1_harq = NULL;\n        codeword_TB1 = -1;\n#ifdef DEBUG_HARQ\n        printf(\"[DEMOD] I am assuming only TB0 is active\\n\");\n#endif\n      } else if ((dlsch[0]->harq_processes[harq_pid]->status != ACTIVE) &&\n                 (dlsch[1]->harq_processes[harq_pid]->status == ACTIVE) ) {\n        codeword_TB1 = dlsch[1]->harq_processes[harq_pid]->codeword;\n        dlsch0_harq  = dlsch[1]->harq_processes[harq_pid];\n        dlsch1_harq  = NULL;\n        codeword_TB0 = -1;\n#ifdef DEBUG_HARQ\n        printf(\"[DEMOD] I am assuming only TB1 is active, it is in cw %d\\n\", dlsch0_harq->codeword);\n#endif\n      } else {\n        LOG_E(PHY,\"[UE][FATAL] Frame %d subframe %d: no active DLSCH\\n\",ue->proc.proc_rxtx[0].frame_rx,subframe);\n        return(-1);\n      }\n\n      beamforming_mode  = ue->transmission_mode[eNB_id]<7?0:ue->transmission_mode[eNB_id];\n      break;\n\n    default:\n      LOG_E(PHY,\"[UE][FATAL] Frame %d subframe %d: Unknown PDSCH format %d\\n\",ue->proc.proc_rxtx[0].frame_rx,subframe,type);\n      return(-1);\n      break;\n  }\n\n#ifdef DEBUG_HARQ\n  printf(\"[DEMOD] MIMO mode = %d\\n\", dlsch0_harq->mimo_mode);\n  printf(\"[DEMOD] cw for TB0 = %d, cw for TB1 = %d\\n\", codeword_TB0, codeword_TB1);\n#endif\n  DevAssert(dlsch0_harq);\n  round = dlsch0_harq->round;\n  //printf(\"round = %d\\n\", round);\n\n  if (eNB_id > 2) {\n    LOG_W(PHY,\"dlsch_demodulation.c: Illegal eNB_id %d\\n\",eNB_id);\n    return(-1);\n  }\n\n  if (!common_vars) {\n    LOG_W(PHY,\"dlsch_demodulation.c: Null common_vars\\n\");\n    return(-1);\n  }\n\n  if (!dlsch[0]) {\n    LOG_W(PHY,\"dlsch_demodulation.c: Null dlsch_ue pointer\\n\");\n    return(-1);\n  }\n\n  if (!pdsch_vars) {\n    LOG_W(PHY,\"dlsch_demodulation.c: Null pdsch_vars pointer\\n\");\n    return(-1);\n  }\n\n  if (!frame_parms) {\n    LOG_W(PHY,\"dlsch_demodulation.c: Null frame_parms\\n\");\n    return(-1);\n  }\n\n  if (((frame_parms->Ncp == NORMAL) && (symbol>=7)) ||\n      ((frame_parms->Ncp == EXTENDED) && (symbol>=6)))\n    rballoc = dlsch0_harq->rb_alloc_odd;\n  else\n    rballoc = dlsch0_harq->rb_alloc_even;\n\n  if (dlsch0_harq->mimo_mode>DUALSTREAM_PUSCH_PRECODING) {\n    LOG_E(PHY,\"This transmission mode is not yet supported!\\n\");\n    return(-1);\n  }\n\n  if ((dlsch0_harq->mimo_mode==LARGE_CDD) || ((dlsch0_harq->mimo_mode>=DUALSTREAM_UNIFORM_PRECODING1) && (dlsch0_harq->mimo_mode<=DUALSTREAM_PUSCH_PRECODING)))  {\n    DevAssert(dlsch1_harq);\n\n    if (eNB_id!=eNB_id_i) {\n      LOG_E(PHY,\"TM3/TM4 requires to set eNB_id==eNB_id_i!\\n\");\n      return(-1);\n    }\n  }\n\n#if UE_TIMING_TRACE\n\n  if(symbol > ue->frame_parms.symbols_per_tti>>1) {\n    slot = 1;\n  }\n\n#endif\n#ifdef DEBUG_HARQ\n  printf(\"Demod  dlsch0_harq->pmi_alloc %d\\n\",  dlsch0_harq->pmi_alloc);\n#endif\n\n  if (frame_parms->nb_antenna_ports_eNB>1 && beamforming_mode==0) {\n#ifdef DEBUG_DLSCH_MOD\n    LOG_I(PHY,\"dlsch: using pmi %x (%p), rb_alloc %x\\n\",pmi2hex_2Ar1(dlsch0_harq->pmi_alloc),dlsch[0],dlsch0_harq->rb_alloc_even[0]);\n#endif\n#if UE_TIMING_TRACE\n    start_meas(&ue->generic_stat_bis[ue->current_thread_id[subframe]][slot]);\n#endif\n    nb_rb = dlsch_extract_rbs_dual(common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].rxdataF,\n                                   common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].dl_ch_estimates[eNB_id],\n                                   pdsch_vars[eNB_id]->rxdataF_ext,\n                                   pdsch_vars[eNB_id]->dl_ch_estimates_ext,\n                                   dlsch0_harq->pmi_alloc,\n                                   pdsch_vars[eNB_id]->pmi_ext,\n                                   rballoc,\n                                   symbol,\n                                   subframe,\n                                   ue->high_speed_flag,\n                                   frame_parms,\n                                   dlsch0_harq->mimo_mode);\n#ifdef DEBUG_DLSCH_MOD\n    printf(\"dlsch: using pmi %lx, rb_alloc %x, pmi_ext \",pmi2hex_2Ar1(dlsch0_harq->pmi_alloc),*rballoc);\n\n    for (rb=0; rb<nb_rb; rb++)\n      printf(\"%d\",pdsch_vars[eNB_id]->pmi_ext[rb]);\n\n    printf(\"\\n\");\n#endif\n\n    if (rx_type >= rx_IC_single_stream) {\n      if (eNB_id_i<ue->n_connected_eNB) // we are in TM5\n        nb_rb = dlsch_extract_rbs_dual(common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].rxdataF,\n                                       common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].dl_ch_estimates[eNB_id_i],\n                                       pdsch_vars[eNB_id_i]->rxdataF_ext,\n                                       pdsch_vars[eNB_id_i]->dl_ch_estimates_ext,\n                                       dlsch0_harq->pmi_alloc,\n                                       pdsch_vars[eNB_id_i]->pmi_ext,\n                                       rballoc,\n                                       symbol,\n                                       subframe,\n                                       ue->high_speed_flag,\n                                       frame_parms,\n                                       dlsch0_harq->mimo_mode);\n      else\n        nb_rb = dlsch_extract_rbs_dual(common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].rxdataF,\n                                       common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].dl_ch_estimates[eNB_id],\n                                       pdsch_vars[eNB_id_i]->rxdataF_ext,\n                                       pdsch_vars[eNB_id_i]->dl_ch_estimates_ext,\n                                       dlsch0_harq->pmi_alloc,\n                                       pdsch_vars[eNB_id_i]->pmi_ext,\n                                       rballoc,\n                                       symbol,\n                                       subframe,\n                                       ue->high_speed_flag,\n                                       frame_parms,\n                                       dlsch0_harq->mimo_mode);\n    }\n  } else if (beamforming_mode==0) { //else if nb_antennas_ports_eNB==1 && beamforming_mode == 0\n    nb_rb = dlsch_extract_rbs_single(common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].rxdataF,\n                                     common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].dl_ch_estimates[eNB_id],\n                                     pdsch_vars[eNB_id]->rxdataF_ext,\n                                     pdsch_vars[eNB_id]->dl_ch_estimates_ext,\n                                     dlsch0_harq->pmi_alloc,\n                                     pdsch_vars[eNB_id]->pmi_ext,\n                                     rballoc,\n                                     symbol,\n                                     subframe,\n                                     ue->high_speed_flag,\n                                     frame_parms);\n\n    if (rx_type==rx_IC_single_stream) {\n      if (eNB_id_i<ue->n_connected_eNB)\n        nb_rb = dlsch_extract_rbs_single(common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].rxdataF,\n                                         common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].dl_ch_estimates[eNB_id_i],\n                                         pdsch_vars[eNB_id_i]->rxdataF_ext,\n                                         pdsch_vars[eNB_id_i]->dl_ch_estimates_ext,\n                                         dlsch0_harq->pmi_alloc,\n                                         pdsch_vars[eNB_id_i]->pmi_ext,\n                                         rballoc,\n                                         symbol,\n                                         subframe,\n                                         ue->high_speed_flag,\n                                         frame_parms);\n      else\n        nb_rb = dlsch_extract_rbs_single(common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].rxdataF,\n                                         common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].dl_ch_estimates[eNB_id],\n                                         pdsch_vars[eNB_id_i]->rxdataF_ext,\n                                         pdsch_vars[eNB_id_i]->dl_ch_estimates_ext,\n                                         dlsch0_harq->pmi_alloc,\n                                         pdsch_vars[eNB_id_i]->pmi_ext,\n                                         rballoc,\n                                         symbol,\n                                         subframe,\n                                         ue->high_speed_flag,\n                                         frame_parms);\n    }\n  } else if (beamforming_mode==7) { //else if beamforming_mode == 7\n    nb_rb = dlsch_extract_rbs_TM7(common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].rxdataF,\n                                  pdsch_vars[eNB_id]->dl_bf_ch_estimates,\n                                  pdsch_vars[eNB_id]->rxdataF_ext,\n                                  pdsch_vars[eNB_id]->dl_bf_ch_estimates_ext,\n                                  rballoc,\n                                  symbol,\n                                  subframe,\n                                  ue->high_speed_flag,\n                                  frame_parms);\n  } else if(beamforming_mode>7) {\n    LOG_W(PHY,\"dlsch_demodulation: beamforming mode not supported yet.\\n\");\n  }\n\n  //printf(\"nb_rb = %d, eNB_id %d\\n\",nb_rb,eNB_id);\n  if (nb_rb==0) {\n    //    LOG_D(PHY,\"dlsch_demodulation.c: nb_rb=0\\n\");\n    return(-1);\n  }\n\n#if UE_TIMING_TRACE\n  stop_meas(&ue->generic_stat_bis[ue->current_thread_id[subframe]][slot]);\n#if DISABLE_LOG_X\n  printf(\"[AbsSFN %d.%d] Slot%d Symbol %d Flag %d type %d: Pilot/Data extraction %5.2f \\n\",frame,subframe,slot,\n         symbol,ue->high_speed_flag,type,ue->generic_stat_bis[ue->current_thread_id[subframe]][slot].p_time/(cpuf*1000.0));\n#else\n  LOG_I(PHY, \"[AbsSFN %d.%d] Slot%d Symbol %d Flag %d type %d: Pilot/Data extraction  %5.2f \\n\",frame,subframe,slot,symbol,\n        ue->high_speed_flag,type,ue->generic_stat_bis[ue->current_thread_id[subframe]][slot].p_time/(cpuf*1000.0));\n#endif\n#endif\n#if UE_TIMING_TRACE\n  start_meas(&ue->generic_stat_bis[ue->current_thread_id[subframe]][slot]);\n#endif\n  aatx = frame_parms->nb_antenna_ports_eNB;\n  aarx = frame_parms->nb_antennas_rx;\n  dlsch_scale_channel(pdsch_vars[eNB_id]->dl_ch_estimates_ext,\n                      frame_parms,\n                      dlsch,\n                      symbol,\n                      nb_rb);\n\n  if ((dlsch0_harq->mimo_mode<DUALSTREAM_UNIFORM_PRECODING1) &&\n      (rx_type==rx_IC_single_stream) &&\n      (eNB_id_i==ue->n_connected_eNB) &&\n      (dlsch0_harq->dl_power_off==0)\n     ) { // TM5 two-user\n    dlsch_scale_channel(pdsch_vars[eNB_id_i]->dl_ch_estimates_ext,\n                        frame_parms,\n                        dlsch,\n                        symbol,\n                        nb_rb);\n  }\n\n#if UE_TIMING_TRACE\n  stop_meas(&ue->generic_stat_bis[ue->current_thread_id[subframe]][slot]);\n#if DISABLE_LOG_X\n  printf(\"[AbsSFN %d.%d] Slot%d Symbol %d: Channel Scale %5.2f \\n\",frame,subframe,slot,symbol,ue->generic_stat_bis[ue->current_thread_id[subframe]][slot].p_time/(cpuf*1000.0));\n#else\n  LOG_I(PHY, \"[AbsSFN %d.%d] Slot%d Symbol %d: Channel Scale  %5.2f \\n\",frame,subframe,slot,symbol,ue->generic_stat_bis[ue->current_thread_id[subframe]][slot].p_time/(cpuf*1000.0));\n#endif\n#endif\n#if UE_TIMING_TRACE\n  start_meas(&ue->generic_stat_bis[ue->current_thread_id[subframe]][slot]);\n#endif\n\n  if (first_symbol_flag==1) {\n    if (beamforming_mode==0) {\n      if (dlsch0_harq->mimo_mode<LARGE_CDD) {\n        dlsch_channel_level(pdsch_vars[eNB_id]->dl_ch_estimates_ext,\n                            frame_parms,\n                            avg,\n                            symbol,\n                            nb_rb);\n        avgs = 0;\n\n        for (aatx=0; aatx<frame_parms->nb_antenna_ports_eNB; aatx++)\n          for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++)\n            avgs = cmax(avgs,avg[(aatx<<1)+aarx]);\n\n        pdsch_vars[eNB_id]->log2_maxh = (log2_approx(avgs)/2)+1;\n      } else if ((dlsch0_harq->mimo_mode == LARGE_CDD) ||\n                 ((dlsch0_harq->mimo_mode >=DUALSTREAM_UNIFORM_PRECODING1) &&\n                  (dlsch0_harq->mimo_mode <=DUALSTREAM_PUSCH_PRECODING))) {\n        dlsch_channel_level_TM34(pdsch_vars[eNB_id]->dl_ch_estimates_ext,\n                                 frame_parms,\n                                 pdsch_vars[eNB_id]->pmi_ext,\n                                 avg_0,\n                                 avg_1,\n                                 symbol,\n                                 nb_rb,\n                                 mmse_flag,\n                                 dlsch0_harq->mimo_mode);\n        LOG_D(PHY,\"Channel Level TM34  avg_0 %d, avg_1 %d, rx_type %d, rx_standard %d, dlsch_demod_shift %d \\n\", avg_0[0],\n              avg_1[0], rx_type, rx_standard, dlsch_demod_shift);\n\n        if (rx_type>rx_standard) {\n          avg_0[0] = (log2_approx(avg_0[0])/2) + dlsch_demod_shift;// + 2 ;//+ 4;\n          avg_1[0] = (log2_approx(avg_1[0])/2) + dlsch_demod_shift;// + 2 ;//+ 4;\n          pdsch_vars[eNB_id]->log2_maxh0 = cmax(avg_0[0],0);\n          pdsch_vars[eNB_id]->log2_maxh1 = cmax(avg_1[0],0);\n          // printf(\"dlsch_demod_shift  %d\\n\", dlsch_demod_shift);\n        } else {\n          avg_0[0] = (log2_approx(avg_0[0])/2) - 13 + interf_unaw_shift;\n          avg_1[0] = (log2_approx(avg_1[0])/2) - 13 + interf_unaw_shift;\n          pdsch_vars[eNB_id]->log2_maxh0 = cmax(avg_0[0],0);\n          pdsch_vars[eNB_id]->log2_maxh1 = cmax(avg_1[0],0);\n        }\n      } else if (dlsch0_harq->mimo_mode<DUALSTREAM_UNIFORM_PRECODING1) { // single-layer precoding (TM5, TM6)\n        if ((rx_type==rx_IC_single_stream) && (eNB_id_i==ue->n_connected_eNB) && (dlsch0_harq->dl_power_off==0)) {\n          dlsch_channel_level_TM56(pdsch_vars[eNB_id]->dl_ch_estimates_ext,\n                                   frame_parms,\n                                   pdsch_vars[eNB_id]->pmi_ext,\n                                   avg,\n                                   symbol,\n                                   nb_rb);\n          avg[0] = log2_approx(avg[0]) - 13 + offset_mumimo_llr_drange[dlsch0_harq->mcs][(i_mod>>1)-1];\n          pdsch_vars[eNB_id]->log2_maxh = cmax(avg[0],0);\n        } else if (dlsch0_harq->dl_power_off==1) { //TM6\n          dlsch_channel_level(pdsch_vars[eNB_id]->dl_ch_estimates_ext,\n                              frame_parms,\n                              avg,\n                              symbol,\n                              nb_rb);\n          avgs = 0;\n\n          for (aatx=0; aatx<frame_parms->nb_antenna_ports_eNB; aatx++)\n            for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++)\n              avgs = cmax(avgs,avg[(aatx<<1)+aarx]);\n\n          pdsch_vars[eNB_id]->log2_maxh = (log2_approx(avgs)/2) + 1;\n          pdsch_vars[eNB_id]->log2_maxh++;\n        }\n      }\n    } else if (beamforming_mode==7)\n      dlsch_channel_level_TM7(pdsch_vars[eNB_id]->dl_bf_ch_estimates_ext,\n                              frame_parms,\n                              avg,\n                              symbol,\n                              nb_rb);\n\n#ifdef UE_DEBUG_TRACE\n    LOG_D(PHY,\"[DLSCH] AbsSubframe %d.%d log2_maxh = %d [log2_maxh0 %d log2_maxh1 %d] (%d,%d)\\n\",\n          frame%1024,subframe, pdsch_vars[eNB_id]->log2_maxh,\n          pdsch_vars[eNB_id]->log2_maxh0,\n          pdsch_vars[eNB_id]->log2_maxh1,\n          avg[0],avgs);\n    //LOG_D(PHY,\"[DLSCH] mimo_mode = %d\\n\", dlsch0_harq->mimo_mode);\n#endif\n    //wait until pdcch is decoded\n    //proc->channel_level = 1;\n  }\n\n  /*\n  uint32_t wait = 0;\n  while(proc->channel_level == 0)\n  {\n      usleep(1);\n      wait++;\n  }\n  */\n#if T_TRACER\n\n  if (type == PDSCH) {\n    T(T_UE_PHY_PDSCH_ENERGY, T_INT(eNB_id), T_INT(frame%1024), T_INT(subframe),\n      T_INT(avg[0]), T_INT(avg[1]),     T_INT(avg[2]),   T_INT(avg[3]));\n  }\n\n#endif\n#if UE_TIMING_TRACE\n  stop_meas(&ue->generic_stat_bis[ue->current_thread_id[subframe]][slot]);\n#if DISABLE_LOG_X\n  printf(\"[AbsSFN %d.%d] Slot%d Symbol %d first_symbol_flag %d: Channel Level %5.2f \\n\",frame,subframe,slot,symbol,first_symbol_flag,\n         ue->generic_stat_bis[ue->current_thread_id[subframe]][slot].p_time/(cpuf*1000.0));\n#else\n  LOG_I(PHY, \"[AbsSFN %d.%d] Slot%d Symbol %d first_symbol_flag %d: Channel Level  %5.2f \\n\",frame,subframe,slot,symbol,first_symbol_flag,\n        ue->generic_stat_bis[ue->current_thread_id[subframe]][slot].p_time/(cpuf*1000.0));\n#endif\n#endif\n#if UE_TIMING_TRACE\n  start_meas(&ue->generic_stat_bis[ue->current_thread_id[subframe]][slot]);\n#endif\n\n  if (rx_type==rx_IC_dual_stream && mmse_flag==1) {\n    precode_channel_est(pdsch_vars[eNB_id]->dl_ch_estimates_ext,\n                        frame_parms,\n                        pdsch_vars[eNB_id],\n                        symbol,\n                        nb_rb,\n                        dlsch0_harq->mimo_mode);\n    mmse_processing_oai(pdsch_vars[eNB_id],\n                        frame_parms,\n                        measurements,\n                        first_symbol_flag,\n                        dlsch0_harq->mimo_mode,\n                        mmse_flag,\n                        0.0,\n                        symbol,\n                        nb_rb);\n  }\n\n  // Now channel compensation\n  if (dlsch0_harq->mimo_mode<LARGE_CDD) {\n    dlsch_channel_compensation(pdsch_vars[eNB_id]->rxdataF_ext,\n                               pdsch_vars[eNB_id]->dl_ch_estimates_ext,\n                               pdsch_vars[eNB_id]->dl_ch_mag0,\n                               pdsch_vars[eNB_id]->dl_ch_magb0,\n                               pdsch_vars[eNB_id]->rxdataF_comp0,\n                               (aatx>1) ? pdsch_vars[eNB_id]->rho : NULL,\n                               frame_parms,\n                               symbol,\n                               first_symbol_flag,\n                               dlsch0_harq->Qm,\n                               nb_rb,\n                               pdsch_vars[eNB_id]->log2_maxh,\n                               measurements); // log2_maxh+I0_shift\n\n    if (symbol == 5) {\n      LOG_M(\"rxF_comp_d.m\",\"rxF_c_d\",&pdsch_vars[eNB_id]->rxdataF_comp0[0][symbol*frame_parms->N_RB_DL*12],frame_parms->N_RB_DL*12,1,1);\n    }\n\n    if ((rx_type==rx_IC_single_stream) &&\n        (eNB_id_i<ue->n_connected_eNB)) {\n      dlsch_channel_compensation(pdsch_vars[eNB_id_i]->rxdataF_ext,\n                                 pdsch_vars[eNB_id_i]->dl_ch_estimates_ext,\n                                 pdsch_vars[eNB_id_i]->dl_ch_mag0,\n                                 pdsch_vars[eNB_id_i]->dl_ch_magb0,\n                                 pdsch_vars[eNB_id_i]->rxdataF_comp0,\n                                 (aatx>1) ? pdsch_vars[eNB_id_i]->rho : NULL,\n                                 frame_parms,\n                                 symbol,\n                                 first_symbol_flag,\n                                 i_mod,\n                                 nb_rb,\n                                 pdsch_vars[eNB_id]->log2_maxh,\n                                 measurements); // log2_maxh+I0_shift\n\n      if (symbol == 5) {\n        LOG_M(\"rxF_comp_d.m\",\"rxF_c_d\",&pdsch_vars[eNB_id]->rxdataF_comp0[0][symbol*frame_parms->N_RB_DL*12],frame_parms->N_RB_DL*12,1,1);\n        LOG_M(\"rxF_comp_i.m\",\"rxF_c_i\",&pdsch_vars[eNB_id_i]->rxdataF_comp0[0][symbol*frame_parms->N_RB_DL*12],frame_parms->N_RB_DL*12,1,1);\n      }\n\n      dlsch_dual_stream_correlation(frame_parms,\n                                    symbol,\n                                    nb_rb,\n                                    pdsch_vars[eNB_id]->dl_ch_estimates_ext,\n                                    pdsch_vars[eNB_id_i]->dl_ch_estimates_ext,\n                                    pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round],\n                                    pdsch_vars[eNB_id]->log2_maxh);\n    }\n  } else if ((dlsch0_harq->mimo_mode == LARGE_CDD) || ((dlsch0_harq->mimo_mode >=DUALSTREAM_UNIFORM_PRECODING1) &&\n             (dlsch0_harq->mimo_mode <=DUALSTREAM_PUSCH_PRECODING))) {\n    dlsch_channel_compensation_TM34(frame_parms,\n                                    pdsch_vars[eNB_id],\n                                    measurements,\n                                    eNB_id,\n                                    symbol,\n                                    dlsch0_harq->Qm,\n                                    dlsch1_harq->Qm,\n                                    harq_pid,\n                                    dlsch0_harq->round,\n                                    dlsch0_harq->mimo_mode,\n                                    nb_rb,\n                                    mmse_flag,\n                                    pdsch_vars[eNB_id]->log2_maxh0,\n                                    pdsch_vars[eNB_id]->log2_maxh1);\n\n    if (symbol == 5) {\n      LOG_M(\"rxF_comp_d00.m\",\"rxF_c_d00\",&pdsch_vars[eNB_id]->rxdataF_comp0[0][symbol*frame_parms->N_RB_DL*12],frame_parms->N_RB_DL*12,1,1);// should be QAM\n      LOG_M(\"rxF_comp_d01.m\",\"rxF_c_d01\",&pdsch_vars[eNB_id]->rxdataF_comp0[1][symbol*frame_parms->N_RB_DL*12],frame_parms->N_RB_DL*12,1,1);//should be almost 0\n      LOG_M(\"rxF_comp_d10.m\",\"rxF_c_d10\",&pdsch_vars[eNB_id]->rxdataF_comp1[harq_pid][round][0][symbol*frame_parms->N_RB_DL*12],frame_parms->N_RB_DL*12,1,1);//should be almost 0\n      LOG_M(\"rxF_comp_d11.m\",\"rxF_c_d11\",&pdsch_vars[eNB_id]->rxdataF_comp1[harq_pid][round][1][symbol*frame_parms->N_RB_DL*12],frame_parms->N_RB_DL*12,1,1);//should be QAM\n    }\n\n    // compute correlation between signal and interference channels (rho12 and rho21)\n    dlsch_dual_stream_correlation(frame_parms, // this is doing h11'*h12 and h21'*h22\n                                  symbol,\n                                  nb_rb,\n                                  pdsch_vars[eNB_id]->dl_ch_estimates_ext,\n                                  &(pdsch_vars[eNB_id]->dl_ch_estimates_ext[2]),\n                                  pdsch_vars[eNB_id]->dl_ch_rho2_ext,\n                                  pdsch_vars[eNB_id]->log2_maxh0);\n    //printf(\"rho stream1 =%d\\n\", &pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round] );\n    //to be optimized (just take complex conjugate)\n    dlsch_dual_stream_correlation(frame_parms, // this is doing h12'*h11 and h22'*h21\n                                  symbol,\n                                  nb_rb,\n                                  &(pdsch_vars[eNB_id]->dl_ch_estimates_ext[2]),\n                                  pdsch_vars[eNB_id]->dl_ch_estimates_ext,\n                                  pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round],\n                                  pdsch_vars[eNB_id]->log2_maxh1);\n\n    //  printf(\"rho stream2 =%d\\n\",&pdsch_vars[eNB_id]->dl_ch_rho2_ext );\n    //printf(\"TM3 log2_maxh : %d\\n\",pdsch_vars[eNB_id]->log2_maxh);\n    if (symbol == 5) {\n      LOG_M(\"rho0_0.m\",\"rho0_0\",&pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round][0][symbol*frame_parms->N_RB_DL*12],frame_parms->N_RB_DL*12,1,1);// should be QAM\n      LOG_M(\"rho2_0.m\",\"rho2_0\",&pdsch_vars[eNB_id]->dl_ch_rho2_ext[0][symbol*frame_parms->N_RB_DL*12],frame_parms->N_RB_DL*12,1,1);//should be almost 0\n      LOG_M(\"rho0_1.m.m\",\"rho0_1\",&pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round][1][symbol*frame_parms->N_RB_DL*12],frame_parms->N_RB_DL*12,1,1);//should be almost 0\n      LOG_M(\"rho2_1.m\",\"rho2_1\",&pdsch_vars[eNB_id]->dl_ch_rho2_ext[1][symbol*frame_parms->N_RB_DL*12],frame_parms->N_RB_DL*12,1,1);//should be QAM\n    }\n  } else if (dlsch0_harq->mimo_mode<DUALSTREAM_UNIFORM_PRECODING1) {// single-layer precoding (TM5, TM6)\n    if ((rx_type==rx_IC_single_stream) && (eNB_id_i==ue->n_connected_eNB) && (dlsch0_harq->dl_power_off==0)) {\n      dlsch_channel_compensation_TM56(pdsch_vars[eNB_id]->rxdataF_ext,\n                                      pdsch_vars[eNB_id]->dl_ch_estimates_ext,\n                                      pdsch_vars[eNB_id]->dl_ch_mag0,\n                                      pdsch_vars[eNB_id]->dl_ch_magb0,\n                                      pdsch_vars[eNB_id]->rxdataF_comp0,\n                                      pdsch_vars[eNB_id]->pmi_ext,\n                                      frame_parms,\n                                      measurements,\n                                      eNB_id,\n                                      symbol,\n                                      dlsch0_harq->Qm,\n                                      nb_rb,\n                                      pdsch_vars[eNB_id]->log2_maxh,\n                                      dlsch0_harq->dl_power_off);\n\n      for (rb=0; rb<nb_rb; rb++) {\n        switch(pdsch_vars[eNB_id]->pmi_ext[rb]) {\n          case 0:\n            pdsch_vars[eNB_id_i]->pmi_ext[rb]=1;\n            break;\n\n          case 1:\n            pdsch_vars[eNB_id_i]->pmi_ext[rb]=0;\n            break;\n\n          case 2:\n            pdsch_vars[eNB_id_i]->pmi_ext[rb]=3;\n            break;\n\n          case 3:\n            pdsch_vars[eNB_id_i]->pmi_ext[rb]=2;\n            break;\n        }\n\n        //  if (rb==0)\n        //    printf(\"pmi %d, pmi_i %d\\n\",pdsch_vars[eNB_id]->pmi_ext[rb],pdsch_vars[eNB_id_i]->pmi_ext[rb]);\n      }\n\n      dlsch_channel_compensation_TM56(pdsch_vars[eNB_id_i]->rxdataF_ext,\n                                      pdsch_vars[eNB_id_i]->dl_ch_estimates_ext,\n                                      pdsch_vars[eNB_id_i]->dl_ch_mag0,\n                                      pdsch_vars[eNB_id_i]->dl_ch_magb0,\n                                      pdsch_vars[eNB_id_i]->rxdataF_comp0,\n                                      pdsch_vars[eNB_id_i]->pmi_ext,\n                                      frame_parms,\n                                      measurements,\n                                      eNB_id_i,\n                                      symbol,\n                                      i_mod,\n                                      nb_rb,\n                                      pdsch_vars[eNB_id]->log2_maxh,\n                                      dlsch0_harq->dl_power_off);\n\n      if (symbol==5) {\n        LOG_M(\"rxF_comp_d.m\",\"rxF_c_d\",&pdsch_vars[eNB_id]->rxdataF_comp0[0][symbol*frame_parms->N_RB_DL*12],frame_parms->N_RB_DL*12,1,1);\n        LOG_M(\"rxF_comp_i.m\",\"rxF_c_i\",&pdsch_vars[eNB_id_i]->rxdataF_comp0[0][symbol*frame_parms->N_RB_DL*12],frame_parms->N_RB_DL*12,1,1);\n      }\n\n      dlsch_dual_stream_correlation(frame_parms,\n                                    symbol,\n                                    nb_rb,\n                                    pdsch_vars[eNB_id]->dl_ch_estimates_ext,\n                                    pdsch_vars[eNB_id_i]->dl_ch_estimates_ext,\n                                    pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round],\n                                    pdsch_vars[eNB_id]->log2_maxh);\n    }  else if (dlsch0_harq->dl_power_off==1)  {\n      dlsch_channel_compensation_TM56(pdsch_vars[eNB_id]->rxdataF_ext,\n                                      pdsch_vars[eNB_id]->dl_ch_estimates_ext,\n                                      pdsch_vars[eNB_id]->dl_ch_mag0,\n                                      pdsch_vars[eNB_id]->dl_ch_magb0,\n                                      pdsch_vars[eNB_id]->rxdataF_comp0,\n                                      pdsch_vars[eNB_id]->pmi_ext,\n                                      frame_parms,\n                                      measurements,\n                                      eNB_id,\n                                      symbol,\n                                      dlsch0_harq->Qm,\n                                      nb_rb,\n                                      pdsch_vars[eNB_id]->log2_maxh,\n                                      1);\n    }\n  } else if (dlsch0_harq->mimo_mode==TM7) { //TM7\n    dlsch_channel_compensation(pdsch_vars[eNB_id]->rxdataF_ext,\n                               pdsch_vars[eNB_id]->dl_bf_ch_estimates_ext,\n                               pdsch_vars[eNB_id]->dl_ch_mag0,\n                               pdsch_vars[eNB_id]->dl_ch_magb0,\n                               pdsch_vars[eNB_id]->rxdataF_comp0,\n                               (aatx>1) ? pdsch_vars[eNB_id]->rho : NULL,\n                               frame_parms,\n                               symbol,\n                               first_symbol_flag,\n                               get_Qm(dlsch0_harq->mcs),\n                               nb_rb,\n                               //9,\n                               pdsch_vars[eNB_id]->log2_maxh,\n                               measurements); // log2_maxh+I0_shift\n  }\n\n#if UE_TIMING_TRACE\n  stop_meas(&ue->generic_stat_bis[ue->current_thread_id[subframe]][slot]);\n#if DISABLE_LOG_X\n  printf(\"[AbsSFN %d.%d] Slot%d Symbol %d log2_maxh %d channel_level %d: Channel Comp %5.2f \\n\",frame,subframe,slot,symbol,pdsch_vars[eNB_id]->log2_maxh,proc->channel_level,\n         ue->generic_stat_bis[ue->current_thread_id[subframe]][slot].p_time/(cpuf*1000.0));\n#else\n  LOG_I(PHY, \"[AbsSFN %d.%d] Slot%d Symbol %d log2_maxh %d Channel Comp  %5.2f \\n\",frame,subframe,slot,symbol,pdsch_vars[eNB_id]->log2_maxh,\n        ue->generic_stat_bis[ue->current_thread_id[subframe]][slot].p_time/(cpuf*1000.0));\n#endif\n#endif\n  // MRC\n#if UE_TIMING_TRACE\n  start_meas(&ue->generic_stat_bis[ue->current_thread_id[subframe]][slot]);\n#endif\n\n  if (frame_parms->nb_antennas_rx > 1) {\n    if ((dlsch0_harq->mimo_mode == LARGE_CDD) ||\n        ((dlsch0_harq->mimo_mode >=DUALSTREAM_UNIFORM_PRECODING1) &&\n         (dlsch0_harq->mimo_mode <=DUALSTREAM_PUSCH_PRECODING))) { // TM3 or TM4\n      if (frame_parms->nb_antenna_ports_eNB == 2) {\n        dlsch_detection_mrc_TM34(frame_parms,\n                                 pdsch_vars[eNB_id],\n                                 harq_pid,\n                                 dlsch0_harq->round,\n                                 symbol,\n                                 nb_rb,\n                                 1);\n\n        if (symbol == 5) {\n          LOG_M(\"rho0_mrc.m\",\"rho0_0\",&pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round][0][symbol*frame_parms->N_RB_DL*12],frame_parms->N_RB_DL*12,1,1);// should be QAM\n          LOG_M(\"rho2_mrc.m\",\"rho2_0\",&pdsch_vars[eNB_id]->dl_ch_rho2_ext[0][symbol*frame_parms->N_RB_DL*12],frame_parms->N_RB_DL*12,1,1);//should be almost 0\n        }\n      }\n    } else {\n      dlsch_detection_mrc(frame_parms,\n                          pdsch_vars[eNB_id]->rxdataF_comp0,\n                          pdsch_vars[eNB_id_i]->rxdataF_comp0,\n                          pdsch_vars[eNB_id]->rho,\n                          pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round],\n                          pdsch_vars[eNB_id]->dl_ch_mag0,\n                          pdsch_vars[eNB_id]->dl_ch_magb0,\n                          pdsch_vars[eNB_id_i]->dl_ch_mag0,\n                          pdsch_vars[eNB_id_i]->dl_ch_magb0,\n                          symbol,\n                          nb_rb,\n                          rx_type==rx_IC_single_stream);\n    }\n  }\n\n  //  printf(\"Combining\");\n  if ((dlsch0_harq->mimo_mode == SISO) ||\n      ((dlsch0_harq->mimo_mode >= UNIFORM_PRECODING11) &&\n       (dlsch0_harq->mimo_mode <= PUSCH_PRECODING0)) ||\n      (dlsch0_harq->mimo_mode == TM7)) {\n    /*\n      dlsch_siso(frame_parms,\n      pdsch_vars[eNB_id]->rxdataF_comp,\n      pdsch_vars[eNB_id_i]->rxdataF_comp,\n      symbol,\n      nb_rb);\n    */\n  } else if (dlsch0_harq->mimo_mode == ALAMOUTI) {\n    dlsch_alamouti(frame_parms,\n                   pdsch_vars[eNB_id]->rxdataF_comp0,\n                   pdsch_vars[eNB_id]->dl_ch_mag0,\n                   pdsch_vars[eNB_id]->dl_ch_magb0,\n                   symbol,\n                   nb_rb);\n  }\n\n  //    printf(\"LLR\");\n  if ((dlsch0_harq->mimo_mode == LARGE_CDD) ||\n      ((dlsch0_harq->mimo_mode >=DUALSTREAM_UNIFORM_PRECODING1) &&\n       (dlsch0_harq->mimo_mode <=DUALSTREAM_PUSCH_PRECODING)))  {\n    rxdataF_comp_ptr = pdsch_vars[eNB_id]->rxdataF_comp1[harq_pid][round];\n    dl_ch_mag_ptr = pdsch_vars[eNB_id]->dl_ch_mag1[harq_pid][round];\n  } else {\n    rxdataF_comp_ptr = pdsch_vars[eNB_id_i]->rxdataF_comp0;\n    dl_ch_mag_ptr = pdsch_vars[eNB_id_i]->dl_ch_mag0;\n    //i_mod should have been passed as a parameter\n  }\n\n#if UE_TIMING_TRACE\n  stop_meas(&ue->generic_stat_bis[ue->current_thread_id[subframe]][slot]);\n#if DISABLE_LOG_X\n  printf(\"[AbsSFN %d.%d] Slot%d Symbol %d: Channel Combine %5.2f \\n\",frame,subframe,slot,symbol,ue->generic_stat_bis[ue->current_thread_id[subframe]][slot].p_time/(cpuf*1000.0));\n#else\n  LOG_I(PHY, \"[AbsSFN %d.%d] Slot%d Symbol %d: Channel Combine  %5.2f \\n\",frame,subframe,slot,symbol,ue->generic_stat_bis[ue->current_thread_id[subframe]][slot].p_time/(cpuf*1000.0));\n#endif\n#endif\n#if UE_TIMING_TRACE\n  start_meas(&ue->generic_stat_bis[ue->current_thread_id[subframe]][slot]);\n#endif\n  //printf(\"LLR dlsch0_harq->Qm %d rx_type %d cw0 %d cw1 %d symbol %d \\n\",dlsch0_harq->Qm,rx_type,codeword_TB0,codeword_TB1,symbol);\n  // compute LLRs\n  // -> // compute @pointer where llrs should filled for this ofdm-symbol\n  int8_t  *pllr_symbol_cw0;\n  int8_t  *pllr_symbol_cw1;\n  uint32_t llr_offset_symbol;\n  llr_offset_symbol = pdsch_vars[eNB_id]->llr_offset[symbol];\n  pllr_symbol_cw0  = (int8_t *)pdsch_vars[eNB_id]->llr[0];\n  pllr_symbol_cw1  = (int8_t *)pdsch_vars[eNB_id]->llr[1];\n  pllr_symbol_cw0 += llr_offset_symbol;\n  pllr_symbol_cw1 += llr_offset_symbol;\n\n  /*\n  LOG_I(PHY,\"compute LLRs [AbsSubframe %d.%d-%d] NbRB %d Qm %d LLRs-Length %d LLR-Offset %d @LLR Buff %p @LLR Buff(symb) %p\\n\",\n             frame, subframe,symbol,\n             nb_rb,dlsch0_harq->Qm,\n             pdsch_vars[eNB_id]->llr_length[symbol],\n             pdsch_vars[eNB_id]->llr_offset[symbol],\n             (int16_t*)pdsch_vars[eNB_id]->llr[0],\n             pllr_symbol_cw0);\n  */\n  switch (dlsch0_harq->Qm) {\n    case 2 :\n      if ((rx_type==rx_standard) || (codeword_TB1 == -1)) {\n        dlsch_qpsk_llr(frame_parms,\n                       pdsch_vars[eNB_id]->rxdataF_comp0,\n                       (int16_t *)pllr_symbol_cw0,\n                       symbol,\n                       first_symbol_flag,\n                       nb_rb,\n                       adjust_G2(frame_parms,dlsch0_harq->rb_alloc_even,2,subframe,symbol),\n                       beamforming_mode);\n      } else if (codeword_TB0 == -1) {\n        dlsch_qpsk_llr(frame_parms,\n                       pdsch_vars[eNB_id]->rxdataF_comp0,\n                       (int16_t *)pllr_symbol_cw1,\n                       symbol,\n                       first_symbol_flag,\n                       nb_rb,\n                       adjust_G2(frame_parms,dlsch0_harq->rb_alloc_even,2,subframe,symbol),\n                       beamforming_mode);\n      } else if (rx_type >= rx_IC_single_stream) {\n        if (dlsch1_harq->Qm == 2) {\n          dlsch_qpsk_qpsk_llr(frame_parms,\n                              pdsch_vars[eNB_id]->rxdataF_comp0,\n                              rxdataF_comp_ptr,\n                              pdsch_vars[eNB_id]->dl_ch_rho2_ext,\n                              pdsch_vars[eNB_id]->llr[0],\n                              symbol,first_symbol_flag,nb_rb,\n                              adjust_G2(frame_parms,dlsch0_harq->rb_alloc_even,2,subframe,symbol),\n                              pdsch_vars[eNB_id]->llr128);\n\n          if (rx_type==rx_IC_dual_stream) {\n            dlsch_qpsk_qpsk_llr(frame_parms,\n                                rxdataF_comp_ptr,\n                                pdsch_vars[eNB_id]->rxdataF_comp0,\n                                pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round],\n                                pdsch_vars[eNB_id]->llr[1],\n                                symbol,first_symbol_flag,nb_rb,\n                                adjust_G2(frame_parms,dlsch1_harq->rb_alloc_even,2,subframe,symbol),\n                                pdsch_vars[eNB_id]->llr128_2ndstream);\n          }\n        } else if (dlsch1_harq->Qm == 4) {\n          dlsch_qpsk_16qam_llr(frame_parms,\n                               pdsch_vars[eNB_id]->rxdataF_comp0,\n                               rxdataF_comp_ptr,//i\n                               dl_ch_mag_ptr,//i\n                               pdsch_vars[eNB_id]->dl_ch_rho2_ext,\n                               pdsch_vars[eNB_id]->llr[0],\n                               symbol,first_symbol_flag,nb_rb,\n                               adjust_G2(frame_parms,dlsch0_harq->rb_alloc_even,2,subframe,symbol),\n                               pdsch_vars[eNB_id]->llr128);\n\n          if (rx_type==rx_IC_dual_stream) {\n            dlsch_16qam_qpsk_llr(frame_parms,\n                                 rxdataF_comp_ptr,\n                                 pdsch_vars[eNB_id]->rxdataF_comp0,//i\n                                 dl_ch_mag_ptr,\n                                 pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round],\n                                 pdsch_vars[eNB_id]->llr[1],\n                                 symbol,first_symbol_flag,nb_rb,\n                                 adjust_G2(frame_parms,dlsch1_harq->rb_alloc_even,4,subframe,symbol),\n                                 pdsch_vars[eNB_id]->llr128_2ndstream);\n          }\n        } else {\n          dlsch_qpsk_64qam_llr(frame_parms,\n                               pdsch_vars[eNB_id]->rxdataF_comp0,\n                               rxdataF_comp_ptr,//i\n                               dl_ch_mag_ptr,//i\n                               pdsch_vars[eNB_id]->dl_ch_rho2_ext,\n                               pdsch_vars[eNB_id]->llr[0],\n                               symbol,first_symbol_flag,nb_rb,\n                               adjust_G2(frame_parms,dlsch0_harq->rb_alloc_even,2,subframe,symbol),\n                               pdsch_vars[eNB_id]->llr128);\n\n          if (rx_type==rx_IC_dual_stream) {\n            dlsch_64qam_qpsk_llr(frame_parms,\n                                 rxdataF_comp_ptr,\n                                 pdsch_vars[eNB_id]->rxdataF_comp0,//i\n                                 dl_ch_mag_ptr,\n                                 pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round],\n                                 pdsch_vars[eNB_id]->llr[1],\n                                 symbol,first_symbol_flag,nb_rb,\n                                 adjust_G2(frame_parms,dlsch1_harq->rb_alloc_even,6,subframe,symbol),\n                                 pdsch_vars[eNB_id]->llr128_2ndstream);\n          }\n        }\n      }\n\n      break;\n\n    case 4 :\n      if ((rx_type==rx_standard ) || (codeword_TB1 == -1)) {\n        dlsch_16qam_llr(frame_parms,\n                        pdsch_vars[eNB_id]->rxdataF_comp0,\n                        pdsch_vars[eNB_id]->llr[0],\n                        pdsch_vars[eNB_id]->dl_ch_mag0,\n                        symbol,first_symbol_flag,nb_rb,\n                        adjust_G2(frame_parms,dlsch0_harq->rb_alloc_even,4,subframe,symbol),\n                        pdsch_vars[eNB_id]->llr128,\n                        beamforming_mode);\n      } else if (codeword_TB0 == -1) {\n        dlsch_16qam_llr(frame_parms,\n                        pdsch_vars[eNB_id]->rxdataF_comp0,\n                        pdsch_vars[eNB_id]->llr[1],\n                        pdsch_vars[eNB_id]->dl_ch_mag0,\n                        symbol,first_symbol_flag,nb_rb,\n                        adjust_G2(frame_parms,dlsch0_harq->rb_alloc_even,4,subframe,symbol),\n                        pdsch_vars[eNB_id]->llr128_2ndstream,\n                        beamforming_mode);\n      } else if (rx_type >= rx_IC_single_stream) {\n        if (dlsch1_harq->Qm == 2) {\n          dlsch_16qam_qpsk_llr(frame_parms,\n                               pdsch_vars[eNB_id]->rxdataF_comp0,\n                               rxdataF_comp_ptr,//i\n                               pdsch_vars[eNB_id]->dl_ch_mag0,\n                               pdsch_vars[eNB_id]->dl_ch_rho2_ext,\n                               pdsch_vars[eNB_id]->llr[0],\n                               symbol,first_symbol_flag,nb_rb,\n                               adjust_G2(frame_parms,dlsch0_harq->rb_alloc_even,4,subframe,symbol),\n                               pdsch_vars[eNB_id]->llr128);\n\n          if (rx_type==rx_IC_dual_stream) {\n            dlsch_qpsk_16qam_llr(frame_parms,\n                                 rxdataF_comp_ptr,\n                                 pdsch_vars[eNB_id]->rxdataF_comp0,//i\n                                 pdsch_vars[eNB_id]->dl_ch_mag0,//i\n                                 pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round],\n                                 pdsch_vars[eNB_id]->llr[1],\n                                 symbol,first_symbol_flag,nb_rb,\n                                 adjust_G2(frame_parms,dlsch1_harq->rb_alloc_even,2,subframe,symbol),\n                                 pdsch_vars[eNB_id]->llr128_2ndstream);\n          }\n        } else if (dlsch1_harq->Qm == 4) {\n          dlsch_16qam_16qam_llr(frame_parms,\n                                pdsch_vars[eNB_id]->rxdataF_comp0,\n                                rxdataF_comp_ptr,//i\n                                pdsch_vars[eNB_id]->dl_ch_mag0,\n                                dl_ch_mag_ptr,//i\n                                pdsch_vars[eNB_id]->dl_ch_rho2_ext,\n                                pdsch_vars[eNB_id]->llr[0],\n                                symbol,first_symbol_flag,nb_rb,\n                                adjust_G2(frame_parms,dlsch0_harq->rb_alloc_even,4,subframe,symbol),\n                                pdsch_vars[eNB_id]->llr128);\n\n          if (rx_type==rx_IC_dual_stream) {\n            dlsch_16qam_16qam_llr(frame_parms,\n                                  rxdataF_comp_ptr,\n                                  pdsch_vars[eNB_id]->rxdataF_comp0,//i\n                                  dl_ch_mag_ptr,\n                                  pdsch_vars[eNB_id]->dl_ch_mag0,//i\n                                  pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round],\n                                  pdsch_vars[eNB_id]->llr[1],\n                                  symbol,first_symbol_flag,nb_rb,\n                                  adjust_G2(frame_parms,dlsch1_harq->rb_alloc_even,4,subframe,symbol),\n                                  pdsch_vars[eNB_id]->llr128_2ndstream);\n          }\n        } else {\n          dlsch_16qam_64qam_llr(frame_parms,\n                                pdsch_vars[eNB_id]->rxdataF_comp0,\n                                rxdataF_comp_ptr,//i\n                                pdsch_vars[eNB_id]->dl_ch_mag0,\n                                dl_ch_mag_ptr,//i\n                                pdsch_vars[eNB_id]->dl_ch_rho2_ext,\n                                pdsch_vars[eNB_id]->llr[0],\n                                symbol,first_symbol_flag,nb_rb,\n                                adjust_G2(frame_parms,dlsch0_harq->rb_alloc_even,4,subframe,symbol),\n                                pdsch_vars[eNB_id]->llr128);\n\n          if (rx_type==rx_IC_dual_stream) {\n            dlsch_64qam_16qam_llr(frame_parms,\n                                  rxdataF_comp_ptr,\n                                  pdsch_vars[eNB_id]->rxdataF_comp0,\n                                  dl_ch_mag_ptr,\n                                  pdsch_vars[eNB_id]->dl_ch_mag0,\n                                  pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round],\n                                  pdsch_vars[eNB_id]->llr[1],\n                                  symbol,first_symbol_flag,nb_rb,\n                                  adjust_G2(frame_parms,dlsch1_harq->rb_alloc_even,6,subframe,symbol),\n                                  pdsch_vars[eNB_id]->llr128_2ndstream);\n          }\n        }\n      }\n\n      break;\n\n    case 6 :\n      if ((rx_type==rx_standard) || (codeword_TB1 == -1))  {\n        dlsch_64qam_llr(frame_parms,\n                        pdsch_vars[eNB_id]->rxdataF_comp0,\n                        (int16_t *)pllr_symbol_cw0,\n                        pdsch_vars[eNB_id]->dl_ch_mag0,\n                        pdsch_vars[eNB_id]->dl_ch_magb0,\n                        symbol,first_symbol_flag,nb_rb,\n                        adjust_G2(frame_parms,dlsch0_harq->rb_alloc_even,6,subframe,symbol),\n                        pdsch_vars[eNB_id]->llr_offset[symbol],\n                        beamforming_mode);\n      } else if (codeword_TB0 == -1) {\n        dlsch_64qam_llr(frame_parms,\n                        pdsch_vars[eNB_id]->rxdataF_comp0,\n                        (int16_t *)pllr_symbol_cw1,\n                        pdsch_vars[eNB_id]->dl_ch_mag0,\n                        pdsch_vars[eNB_id]->dl_ch_magb0,\n                        symbol,first_symbol_flag,nb_rb,\n                        adjust_G2(frame_parms,dlsch0_harq->rb_alloc_even,6,subframe,symbol),\n                        pdsch_vars[eNB_id]->llr_offset[symbol],\n                        beamforming_mode);\n      } else if (rx_type >= rx_IC_single_stream) {\n        if (dlsch1_harq->Qm == 2) {\n          dlsch_64qam_qpsk_llr(frame_parms,\n                               pdsch_vars[eNB_id]->rxdataF_comp0,\n                               rxdataF_comp_ptr,//i\n                               pdsch_vars[eNB_id]->dl_ch_mag0,\n                               pdsch_vars[eNB_id]->dl_ch_rho2_ext,\n                               pdsch_vars[eNB_id]->llr[0],\n                               symbol,first_symbol_flag,nb_rb,\n                               adjust_G2(frame_parms,dlsch0_harq->rb_alloc_even,6,subframe,symbol),\n                               pdsch_vars[eNB_id]->llr128);\n\n          if (rx_type==rx_IC_dual_stream) {\n            dlsch_qpsk_64qam_llr(frame_parms,\n                                 rxdataF_comp_ptr,\n                                 pdsch_vars[eNB_id]->rxdataF_comp0,//i\n                                 pdsch_vars[eNB_id]->dl_ch_mag0,\n                                 pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round],\n                                 pdsch_vars[eNB_id]->llr[1],\n                                 symbol,first_symbol_flag,nb_rb,\n                                 adjust_G2(frame_parms,dlsch1_harq->rb_alloc_even,2,subframe,symbol),\n                                 pdsch_vars[eNB_id]->llr128_2ndstream);\n          }\n        } else if (dlsch1_harq->Qm == 4) {\n          dlsch_64qam_16qam_llr(frame_parms,\n                                pdsch_vars[eNB_id]->rxdataF_comp0,\n                                rxdataF_comp_ptr,//i\n                                pdsch_vars[eNB_id]->dl_ch_mag0,\n                                dl_ch_mag_ptr,//i\n                                pdsch_vars[eNB_id]->dl_ch_rho2_ext,\n                                pdsch_vars[eNB_id]->llr[0],\n                                symbol,first_symbol_flag,nb_rb,\n                                adjust_G2(frame_parms,dlsch0_harq->rb_alloc_even,6,subframe,symbol),\n                                pdsch_vars[eNB_id]->llr128);\n\n          if (rx_type==rx_IC_dual_stream) {\n            dlsch_16qam_64qam_llr(frame_parms,\n                                  rxdataF_comp_ptr,\n                                  pdsch_vars[eNB_id]->rxdataF_comp0,//i\n                                  dl_ch_mag_ptr,\n                                  pdsch_vars[eNB_id]->dl_ch_mag0,//i\n                                  pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round],\n                                  pdsch_vars[eNB_id]->llr[1],\n                                  symbol,first_symbol_flag,nb_rb,\n                                  adjust_G2(frame_parms,dlsch1_harq->rb_alloc_even,4,subframe,symbol),\n                                  pdsch_vars[eNB_id]->llr128_2ndstream);\n          }\n        } else {\n          dlsch_64qam_64qam_llr(frame_parms,\n                                pdsch_vars[eNB_id]->rxdataF_comp0,\n                                rxdataF_comp_ptr,//i\n                                pdsch_vars[eNB_id]->dl_ch_mag0,\n                                dl_ch_mag_ptr,//i\n                                pdsch_vars[eNB_id]->dl_ch_rho2_ext,\n                                (int16_t *)pllr_symbol_cw0,\n                                symbol,first_symbol_flag,nb_rb,\n                                adjust_G2(frame_parms,dlsch0_harq->rb_alloc_even,6,subframe,symbol),\n                                pdsch_vars[eNB_id]->llr_offset[symbol]);\n\n          if (rx_type==rx_IC_dual_stream) {\n            dlsch_64qam_64qam_llr(frame_parms,\n                                  rxdataF_comp_ptr,\n                                  pdsch_vars[eNB_id]->rxdataF_comp0,//i\n                                  dl_ch_mag_ptr,\n                                  pdsch_vars[eNB_id]->dl_ch_mag0,//i\n                                  pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round],\n                                  (int16_t *)pllr_symbol_cw1,\n                                  symbol,first_symbol_flag,nb_rb,\n                                  adjust_G2(frame_parms,dlsch1_harq->rb_alloc_even,6,subframe,symbol),\n                                  pdsch_vars[eNB_id]->llr_offset[symbol]);\n          }\n        }\n      }\n\n      break;\n\n    default:\n      LOG_W(PHY,\"rx_dlsch.c : Unknown mod_order!!!!\\n\");\n      return(-1);\n      break;\n  }\n\n  if (dlsch1_harq) {\n    switch (get_Qm(dlsch1_harq->mcs)) {\n      case 2 :\n        if (rx_type==rx_standard) {\n          dlsch_qpsk_llr(frame_parms,\n                         pdsch_vars[eNB_id]->rxdataF_comp0,\n                         (int16_t *)pllr_symbol_cw0,\n                         symbol,first_symbol_flag,nb_rb,\n                         adjust_G2(frame_parms,dlsch0_harq->rb_alloc_even,2,subframe,symbol),\n                         beamforming_mode);\n        }\n\n        break;\n\n      case 4:\n        if (rx_type==rx_standard) {\n          dlsch_16qam_llr(frame_parms,\n                          pdsch_vars[eNB_id]->rxdataF_comp0,\n                          pdsch_vars[eNB_id]->llr[0],\n                          pdsch_vars[eNB_id]->dl_ch_mag0,\n                          symbol,first_symbol_flag,nb_rb,\n                          adjust_G2(frame_parms,dlsch0_harq->rb_alloc_even,4,subframe,symbol),\n                          pdsch_vars[eNB_id]->llr128,\n                          beamforming_mode);\n        }\n\n        break;\n\n      case 6 :\n        if (rx_type==rx_standard) {\n          dlsch_64qam_llr(frame_parms,\n                          pdsch_vars[eNB_id]->rxdataF_comp0,\n                          (int16_t *)pllr_symbol_cw0,\n                          pdsch_vars[eNB_id]->dl_ch_mag0,\n                          pdsch_vars[eNB_id]->dl_ch_magb0,\n                          symbol,first_symbol_flag,nb_rb,\n                          adjust_G2(frame_parms,dlsch0_harq->rb_alloc_even,6,subframe,symbol),\n                          pdsch_vars[eNB_id]->llr_offset[symbol],\n                          beamforming_mode);\n        }\n\n        break;\n\n      default:\n        LOG_W(PHY,\"rx_dlsch.c : Unknown mod_order!!!!\\n\");\n        return(-1);\n        break;\n    }\n  }\n\n#if UE_TIMING_TRACE\n  stop_meas(&ue->generic_stat_bis[ue->current_thread_id[subframe]][slot]);\n#if DISABLE_LOG_X\n  printf(\"[AbsSFN %d.%d] Slot%d Symbol %d: LLR Computation %5.2f \\n\",frame,subframe,slot,symbol,ue->generic_stat_bis[ue->current_thread_id[subframe]][slot].p_time/(cpuf*1000.0));\n#else\n  LOG_D(PHY, \"[AbsSFN %d.%d] Slot%d Symbol %d: LLR Computation  %5.2f \\n\",frame,subframe,slot,symbol,ue->generic_stat_bis[ue->current_thread_id[subframe]][slot].p_time/(cpuf*1000.0));\n#endif\n#endif\n  // Please keep it: useful for debugging\n#if 0\n\n  if( (symbol == 13) && (subframe==0) && (dlsch0_harq->Qm == 6) /*&& (nb_rb==25)*/) {\n    LOG_E(PHY,\"Dump Phy Chan Est \\n\");\n\n    if(1) {\n#if 1\n      LOG_M(\"rxdataF0.m\"    , \"rxdataF0\",             &common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].rxdataF[0][0],14*frame_parms->ofdm_symbol_size,1,1);\n      //LOG_M(\"rxdataF1.m\"    , \"rxdataF1\",             &common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].rxdataF[0][0],14*frame_parms->ofdm_symbol_size,1,1);\n      LOG_M(\"dl_ch_estimates00.m\", \"dl_ch_estimates00\",   &common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].dl_ch_estimates[eNB_id][0][0],14*frame_parms->ofdm_symbol_size,1,1);\n      //LOG_M(\"dl_ch_estimates01.m\", \"dl_ch_estimates01\",   &common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].dl_ch_estimates[eNB_id][1][0],14*frame_parms->ofdm_symbol_size,1,1);\n      //LOG_M(\"dl_ch_estimates10.m\", \"dl_ch_estimates10\",   &common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].dl_ch_estimates[eNB_id][2][0],14*frame_parms->ofdm_symbol_size,1,1);\n      //LOG_M(\"dl_ch_estimates11.m\", \"dl_ch_estimates11\",   &common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].dl_ch_estimates[eNB_id][3][0],14*frame_parms->ofdm_symbol_size,1,1);\n      //LOG_M(\"rxdataF_ext00.m\"    , \"rxdataF_ext00\",       &pdsch_vars[eNB_id]->rxdataF_ext[0][0],14*frame_parms->N_RB_DL*12,1,1);\n      //LOG_M(\"rxdataF_ext01.m\"    , \"rxdataF_ext01\",       &pdsch_vars[eNB_id]->rxdataF_ext[1][0],14*frame_parms->N_RB_DL*12,1,1);\n      //LOG_M(\"rxdataF_ext10.m\"    , \"rxdataF_ext10\",       &pdsch_vars[eNB_id]->rxdataF_ext[2][0],14*frame_parms->N_RB_DL*12,1,1);\n      //LOG_M(\"rxdataF_ext11.m\"    , \"rxdataF_ext11\",       &pdsch_vars[eNB_id]->rxdataF_ext[3][0],14*frame_parms->N_RB_DL*12,1,1);\n      LOG_M(\"dl_ch_estimates_ext00.m\", \"dl_ch_estimates_ext00\", &pdsch_vars[eNB_id]->dl_ch_estimates_ext[0][0],14*frame_parms->N_RB_DL*12,1,1);\n      //LOG_M(\"dl_ch_estimates_ext01.m\", \"dl_ch_estimates_ext01\", &pdsch_vars[eNB_id]->dl_ch_estimates_ext[1][0],14*frame_parms->N_RB_DL*12,1,1);\n      //LOG_M(\"dl_ch_estimates_ext10.m\", \"dl_ch_estimates_ext10\", &pdsch_vars[eNB_id]->dl_ch_estimates_ext[2][0],14*frame_parms->N_RB_DL*12,1,1);\n      //LOG_M(\"dl_ch_estimates_ext11.m\", \"dl_ch_estimates_ext11\", &pdsch_vars[eNB_id]->dl_ch_estimates_ext[3][0],14*frame_parms->N_RB_DL*12,1,1);\n      LOG_M(\"rxdataF_comp00.m\",\"rxdataF_comp00\",              &pdsch_vars[eNB_id]->rxdataF_comp0[0][0],14*frame_parms->N_RB_DL*12,1,1);\n      //LOG_M(\"rxdataF_comp01.m\",\"rxdataF_comp01\",              &pdsch_vars[eNB_id]->rxdataF_comp0[1][0],14*frame_parms->N_RB_DL*12,1,1);\n      //LOG_M(\"rxdataF_comp10.m\",\"rxdataF_comp10\",              &pdsch_vars[eNB_id]->rxdataF_comp1[harq_pid][round][0][0],14*frame_parms->N_RB_DL*12,1,1);\n      //LOG_M(\"rxdataF_comp11.m\",\"rxdataF_comp11\",              &pdsch_vars[eNB_id]->rxdataF_comp1[harq_pid][round][1][0],14*frame_parms->N_RB_DL*12,1,1);\n#endif\n      LOG_M(\"llr0.m\",\"llr0\",  &pdsch_vars[eNB_id]->llr[0][0],(14*nb_rb*12*dlsch1_harq->Qm) - 4*(nb_rb*4*dlsch1_harq->Qm),1,0);\n      //LOG_M(\"llr1.m\",\"llr1\",  &pdsch_vars[eNB_id]->llr[1][0],(14*nb_rb*12*dlsch1_harq->Qm) - 4*(nb_rb*4*dlsch1_harq->Qm),1,0);\n      AssertFatal(0,\" \");\n    }\n  }\n\n#endif\n  T(T_UE_PHY_PDSCH_IQ, T_INT(eNB_id), T_INT(frame%1024),\n    T_INT(subframe), T_INT(nb_rb),\n    T_INT(frame_parms->N_RB_UL), T_INT(frame_parms->symbols_per_tti),\n    T_BUFFER(&pdsch_vars[eNB_id]->rxdataF_comp0[eNB_id][0],\n             2 * /* ulsch[UE_id]->harq_processes[harq_pid]->nb_rb */ frame_parms->N_RB_UL *12*frame_parms->symbols_per_tti*2));\n  return 0;\n}\n\n//==============================================================================================\n// Pre-processing for LLR computation\n//==============================================================================================\n\nvoid dlsch_channel_compensation(int **rxdataF_ext,\n                                int **dl_ch_estimates_ext,\n                                int **dl_ch_mag,\n                                int **dl_ch_magb,\n                                int **rxdataF_comp,\n                                int **rho,\n                                LTE_DL_FRAME_PARMS *frame_parms,\n                                unsigned char symbol,\n                                uint8_t first_symbol_flag,\n                                unsigned char mod_order,\n                                unsigned short nb_rb,\n                                unsigned char output_shift,\n                                PHY_MEASUREMENTS *measurements) {\n#if defined(__i386) || defined(__x86_64)\n  unsigned short rb;\n  unsigned char aatx,aarx,symbol_mod,pilots=0;\n  __m128i *dl_ch128,*dl_ch128_2,*dl_ch_mag128,*dl_ch_mag128b,*rxdataF128,*rxdataF_comp128,*rho128;\n  __m128i mmtmpD0,mmtmpD1,mmtmpD2,mmtmpD3,QAM_amp128;\n  symbol_mod = (symbol>=(7-frame_parms->Ncp)) ? symbol-(7-frame_parms->Ncp) : symbol;\n\n  if ((symbol_mod == 0) || (symbol_mod == (4-frame_parms->Ncp))) {\n    if (frame_parms->nb_antenna_ports_eNB==1) // 10 out of 12 so don't reduce size\n      nb_rb=1+(5*nb_rb/6);\n    else\n      pilots=1;\n  }\n\n  for (aatx=0; aatx<frame_parms->nb_antenna_ports_eNB; aatx++) {\n    __m128i QAM_amp128b = _mm_setzero_si128();\n\n    if (mod_order == 4) {\n      QAM_amp128 = _mm_set1_epi16(QAM16_n1);  // 2/sqrt(10)\n    } else if (mod_order == 6) {\n      QAM_amp128  = _mm_set1_epi16(QAM64_n1); //\n      QAM_amp128b = _mm_set1_epi16(QAM64_n2);\n    }\n\n    for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) {\n      /* TODO: hack to be removed. There is crash for 1 antenna case, so\n       * for 1 antenna case, I put back the value 2 as it was before\n       * Elena's commit.\n       */\n      int x = frame_parms->nb_antennas_rx > 1 ? frame_parms->nb_antennas_rx : 2;\n      dl_ch128          = (__m128i *)&dl_ch_estimates_ext[aatx*x + aarx][symbol*frame_parms->N_RB_DL*12];\n      //print_shorts(\"dl_ch128[0]=\",&dl_ch128[0]);*/\n      dl_ch_mag128      = (__m128i *)&dl_ch_mag[aatx*x + aarx][symbol*frame_parms->N_RB_DL*12];\n      dl_ch_mag128b     = (__m128i *)&dl_ch_magb[aatx*x + aarx][symbol*frame_parms->N_RB_DL*12];\n      rxdataF128        = (__m128i *)&rxdataF_ext[aarx][symbol*frame_parms->N_RB_DL*12];\n      rxdataF_comp128   = (__m128i *)&rxdataF_comp[aatx*x + aarx][symbol*frame_parms->N_RB_DL*12];\n\n      for (rb=0; rb<nb_rb; rb++) {\n        if (mod_order>2) {\n          // get channel amplitude if not QPSK\n          mmtmpD0 = _mm_madd_epi16(dl_ch128[0],dl_ch128[0]);\n          mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift);\n          mmtmpD1 = _mm_madd_epi16(dl_ch128[1],dl_ch128[1]);\n          mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift);\n          mmtmpD0 = _mm_packs_epi32(mmtmpD0,mmtmpD1);\n          // store channel magnitude here in a new field of dlsch\n          dl_ch_mag128[0] = _mm_unpacklo_epi16(mmtmpD0,mmtmpD0);\n          dl_ch_mag128b[0] = dl_ch_mag128[0];\n          dl_ch_mag128[0] = _mm_mulhi_epi16(dl_ch_mag128[0],QAM_amp128);\n          dl_ch_mag128[0] = _mm_slli_epi16(dl_ch_mag128[0],1);\n          //print_ints(\"Re(ch):\",(int16_t*)&mmtmpD0);\n          //print_shorts(\"QAM_amp:\",(int16_t*)&QAM_amp128);\n          //print_shorts(\"mag:\",(int16_t*)&dl_ch_mag128[0]);\n          dl_ch_mag128[1] = _mm_unpackhi_epi16(mmtmpD0,mmtmpD0);\n          dl_ch_mag128b[1] = dl_ch_mag128[1];\n          dl_ch_mag128[1] = _mm_mulhi_epi16(dl_ch_mag128[1],QAM_amp128);\n          dl_ch_mag128[1] = _mm_slli_epi16(dl_ch_mag128[1],1);\n\n          if (pilots==0) {\n            mmtmpD0 = _mm_madd_epi16(dl_ch128[2],dl_ch128[2]);\n            mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift);\n            mmtmpD1 = _mm_packs_epi32(mmtmpD0,mmtmpD0);\n            dl_ch_mag128[2] = _mm_unpacklo_epi16(mmtmpD1,mmtmpD1);\n            dl_ch_mag128b[2] = dl_ch_mag128[2];\n            dl_ch_mag128[2] = _mm_mulhi_epi16(dl_ch_mag128[2],QAM_amp128);\n            dl_ch_mag128[2] = _mm_slli_epi16(dl_ch_mag128[2],1);\n          }\n\n          dl_ch_mag128b[0] = _mm_mulhi_epi16(dl_ch_mag128b[0],QAM_amp128b);\n          dl_ch_mag128b[0] = _mm_slli_epi16(dl_ch_mag128b[0],1);\n          dl_ch_mag128b[1] = _mm_mulhi_epi16(dl_ch_mag128b[1],QAM_amp128b);\n          dl_ch_mag128b[1] = _mm_slli_epi16(dl_ch_mag128b[1],1);\n\n          if (pilots==0) {\n            dl_ch_mag128b[2] = _mm_mulhi_epi16(dl_ch_mag128b[2],QAM_amp128b);\n            dl_ch_mag128b[2] = _mm_slli_epi16(dl_ch_mag128b[2],1);\n          }\n        }\n\n        // multiply by conjugated channel\n        mmtmpD0 = _mm_madd_epi16(dl_ch128[0],rxdataF128[0]);\n        // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n        mmtmpD1 = _mm_shufflelo_epi16(dl_ch128[0],_MM_SHUFFLE(2,3,0,1));\n        mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1));\n        mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)&conjugate[0]);\n        //  print_ints(\"im\",&mmtmpD1);\n        mmtmpD1 = _mm_madd_epi16(mmtmpD1,rxdataF128[0]);\n        // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n        mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift);\n        //  print_ints(\"re(shift)\",&mmtmpD0);\n        mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift);\n        //  print_ints(\"im(shift)\",&mmtmpD1);\n        mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1);\n        mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1);\n        //        print_ints(\"c0\",&mmtmpD2);\n        //  print_ints(\"c1\",&mmtmpD3);\n        rxdataF_comp128[0] = _mm_packs_epi32(mmtmpD2,mmtmpD3);\n        //  print_shorts(\"rx:\",rxdataF128);\n        //  print_shorts(\"ch:\",dl_ch128);\n        //  print_shorts(\"pack:\",rxdataF_comp128);\n        // multiply by conjugated channel\n        mmtmpD0 = _mm_madd_epi16(dl_ch128[1],rxdataF128[1]);\n        // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n        mmtmpD1 = _mm_shufflelo_epi16(dl_ch128[1],_MM_SHUFFLE(2,3,0,1));\n        mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1));\n        mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)conjugate);\n        mmtmpD1 = _mm_madd_epi16(mmtmpD1,rxdataF128[1]);\n        // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n        mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift);\n        mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift);\n        mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1);\n        mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1);\n        rxdataF_comp128[1] = _mm_packs_epi32(mmtmpD2,mmtmpD3);\n        //  print_shorts(\"rx:\",rxdataF128+1);\n        //  print_shorts(\"ch:\",dl_ch128+1);\n        //  print_shorts(\"pack:\",rxdataF_comp128+1);\n\n        if (pilots==0) {\n          // multiply by conjugated channel\n          mmtmpD0 = _mm_madd_epi16(dl_ch128[2],rxdataF128[2]);\n          // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n          mmtmpD1 = _mm_shufflelo_epi16(dl_ch128[2],_MM_SHUFFLE(2,3,0,1));\n          mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1));\n          mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)conjugate);\n          mmtmpD1 = _mm_madd_epi16(mmtmpD1,rxdataF128[2]);\n          // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n          mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift);\n          mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift);\n          mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1);\n          mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1);\n          rxdataF_comp128[2] = _mm_packs_epi32(mmtmpD2,mmtmpD3);\n          //  print_shorts(\"rx:\",rxdataF128+2);\n          //  print_shorts(\"ch:\",dl_ch128+2);\n          // print_shorts(\"pack:\",rxdataF_comp128+2);\n          dl_ch128+=3;\n          dl_ch_mag128+=3;\n          dl_ch_mag128b+=3;\n          rxdataF128+=3;\n          rxdataF_comp128+=3;\n        } else { // we have a smaller PDSCH in symbols with pilots so skip last group of 4 REs and increment less\n          dl_ch128+=2;\n          dl_ch_mag128+=2;\n          dl_ch_mag128b+=2;\n          rxdataF128+=2;\n          rxdataF_comp128+=2;\n        }\n      }\n    }\n  }\n\n  if (rho) {\n    for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) {\n      rho128        = (__m128i *)&rho[aarx][symbol*frame_parms->N_RB_DL*12];\n      dl_ch128      = (__m128i *)&dl_ch_estimates_ext[aarx][symbol*frame_parms->N_RB_DL*12];\n      dl_ch128_2    = (__m128i *)&dl_ch_estimates_ext[2+aarx][symbol*frame_parms->N_RB_DL*12];\n\n      for (rb=0; rb<nb_rb; rb++) {\n        // multiply by conjugated channel\n        mmtmpD0 = _mm_madd_epi16(dl_ch128[0],dl_ch128_2[0]);\n        //  print_ints(\"re\",&mmtmpD0);\n        // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n        mmtmpD1 = _mm_shufflelo_epi16(dl_ch128[0],_MM_SHUFFLE(2,3,0,1));\n        mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1));\n        mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)&conjugate[0]);\n        //  print_ints(\"im\",&mmtmpD1);\n        mmtmpD1 = _mm_madd_epi16(mmtmpD1,dl_ch128_2[0]);\n        // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n        mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift);\n        //  print_ints(\"re(shift)\",&mmtmpD0);\n        mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift);\n        //  print_ints(\"im(shift)\",&mmtmpD1);\n        mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1);\n        mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1);\n        //        print_ints(\"c0\",&mmtmpD2);\n        //  print_ints(\"c1\",&mmtmpD3);\n        rho128[0] = _mm_packs_epi32(mmtmpD2,mmtmpD3);\n        //print_shorts(\"rx:\",dl_ch128_2);\n        //print_shorts(\"ch:\",dl_ch128);\n        //print_shorts(\"pack:\",rho128);\n        // multiply by conjugated channel\n        mmtmpD0 = _mm_madd_epi16(dl_ch128[1],dl_ch128_2[1]);\n        // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n        mmtmpD1 = _mm_shufflelo_epi16(dl_ch128[1],_MM_SHUFFLE(2,3,0,1));\n        mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1));\n        mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)conjugate);\n        mmtmpD1 = _mm_madd_epi16(mmtmpD1,dl_ch128_2[1]);\n        // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n        mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift);\n        mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift);\n        mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1);\n        mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1);\n        rho128[1] =_mm_packs_epi32(mmtmpD2,mmtmpD3);\n        //print_shorts(\"rx:\",dl_ch128_2+1);\n        //print_shorts(\"ch:\",dl_ch128+1);\n        //print_shorts(\"pack:\",rho128+1);\n        // multiply by conjugated channel\n        mmtmpD0 = _mm_madd_epi16(dl_ch128[2],dl_ch128_2[2]);\n        // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n        mmtmpD1 = _mm_shufflelo_epi16(dl_ch128[2],_MM_SHUFFLE(2,3,0,1));\n        mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1));\n        mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)conjugate);\n        mmtmpD1 = _mm_madd_epi16(mmtmpD1,dl_ch128_2[2]);\n        // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n        mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift);\n        mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift);\n        mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1);\n        mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1);\n        rho128[2] = _mm_packs_epi32(mmtmpD2,mmtmpD3);\n        //print_shorts(\"rx:\",dl_ch128_2+2);\n        //print_shorts(\"ch:\",dl_ch128+2);\n        //print_shorts(\"pack:\",rho128+2);\n        dl_ch128+=3;\n        dl_ch128_2+=3;\n        rho128+=3;\n      }\n\n      if (first_symbol_flag==1) {\n        measurements->rx_correlation[0][aarx] = signal_energy(&rho[aarx][symbol*frame_parms->N_RB_DL*12],rb*12);\n      }\n    }\n  }\n\n  _mm_empty();\n  _m_empty();\n#elif defined(__arm__)\n  unsigned short rb;\n  unsigned char aatx,aarx,symbol_mod,pilots=0;\n  int16x4_t *dl_ch128,*dl_ch128_2,*rxdataF128;\n  int32x4_t mmtmpD0,mmtmpD1,mmtmpD0b,mmtmpD1b;\n  int16x8_t *dl_ch_mag128,*dl_ch_mag128b,mmtmpD2,mmtmpD3,mmtmpD4;\n  int16x8_t QAM_amp128,QAM_amp128b;\n  int16x4x2_t *rxdataF_comp128,*rho128;\n  int16_t conj[4]__attribute__((aligned(16))) = {1,-1,1,-1};\n  int32x4_t output_shift128 = vmovq_n_s32(-(int32_t)output_shift);\n  symbol_mod = (symbol>=(7-frame_parms->Ncp)) ? symbol-(7-frame_parms->Ncp) : symbol;\n\n  if ((symbol_mod == 0) || (symbol_mod == (4-frame_parms->Ncp))) {\n    if (frame_parms->nb_antenna_ports_eNB==1) { // 10 out of 12 so don't reduce size\n      nb_rb=1+(5*nb_rb/6);\n    } else {\n      pilots=1;\n    }\n  }\n\n  for (aatx=0; aatx<frame_parms->nb_antenna_ports_eNB; aatx++) {\n    if (mod_order == 4) {\n      QAM_amp128  = vmovq_n_s16(QAM16_n1);  // 2/sqrt(10)\n      QAM_amp128b = vmovq_n_s16(0);\n    } else if (mod_order == 6) {\n      QAM_amp128  = vmovq_n_s16(QAM64_n1); //\n      QAM_amp128b = vmovq_n_s16(QAM64_n2);\n    }\n\n    //    printf(\"comp: rxdataF_comp %p, symbol %d\\n\",rxdataF_comp[0],symbol);\n\n    for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) {\n      dl_ch128          = (int16x4_t *)&dl_ch_estimates_ext[aatx*frame_parms->nb_antennas_rx + aarx][symbol*frame_parms->N_RB_DL*12];\n      dl_ch_mag128      = (int16x8_t *)&dl_ch_mag[aatx*frame_parms->nb_antennas_rx + aarx][symbol*frame_parms->N_RB_DL*12];\n      dl_ch_mag128b     = (int16x8_t *)&dl_ch_magb[aatx*frame_parms->nb_antennas_rx + aarx][symbol*frame_parms->N_RB_DL*12];\n      rxdataF128        = (int16x4_t *)&rxdataF_ext[aarx][symbol*frame_parms->N_RB_DL*12];\n      rxdataF_comp128   = (int16x4x2_t *)&rxdataF_comp[aatx*frame_parms->nb_antennas_rx + aarx][symbol*frame_parms->N_RB_DL*12];\n\n      for (rb=0; rb<nb_rb; rb++) {\n        if (mod_order>2) {\n          // get channel amplitude if not QPSK\n          mmtmpD0 = vmull_s16(dl_ch128[0], dl_ch128[0]);\n          // mmtmpD0 = [ch0*ch0,ch1*ch1,ch2*ch2,ch3*ch3];\n          mmtmpD0 = vqshlq_s32(vqaddq_s32(mmtmpD0,vrev64q_s32(mmtmpD0)),output_shift128);\n          // mmtmpD0 = [ch0*ch0 + ch1*ch1,ch0*ch0 + ch1*ch1,ch2*ch2 + ch3*ch3,ch2*ch2 + ch3*ch3]>>output_shift128 on 32-bits\n          mmtmpD1 = vmull_s16(dl_ch128[1], dl_ch128[1]);\n          mmtmpD1 = vqshlq_s32(vqaddq_s32(mmtmpD1,vrev64q_s32(mmtmpD1)),output_shift128);\n          mmtmpD2 = vcombine_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1));\n          // mmtmpD2 = [ch0*ch0 + ch1*ch1,ch0*ch0 + ch1*ch1,ch2*ch2 + ch3*ch3,ch2*ch2 + ch3*ch3,ch4*ch4 + ch5*ch5,ch4*ch4 + ch5*ch5,ch6*ch6 + ch7*ch7,ch6*ch6 + ch7*ch7]>>output_shift128 on 16-bits\n          mmtmpD0 = vmull_s16(dl_ch128[2], dl_ch128[2]);\n          mmtmpD0 = vqshlq_s32(vqaddq_s32(mmtmpD0,vrev64q_s32(mmtmpD0)),output_shift128);\n          mmtmpD1 = vmull_s16(dl_ch128[3], dl_ch128[3]);\n          mmtmpD1 = vqshlq_s32(vqaddq_s32(mmtmpD1,vrev64q_s32(mmtmpD1)),output_shift128);\n          mmtmpD3 = vcombine_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1));\n\n          if (pilots==0) {\n            mmtmpD0 = vmull_s16(dl_ch128[4], dl_ch128[4]);\n            mmtmpD0 = vqshlq_s32(vqaddq_s32(mmtmpD0,vrev64q_s32(mmtmpD0)),output_shift128);\n            mmtmpD1 = vmull_s16(dl_ch128[5], dl_ch128[5]);\n            mmtmpD1 = vqshlq_s32(vqaddq_s32(mmtmpD1,vrev64q_s32(mmtmpD1)),output_shift128);\n            mmtmpD4 = vcombine_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1));\n          }\n\n          dl_ch_mag128b[0] = vqdmulhq_s16(mmtmpD2,QAM_amp128b);\n          dl_ch_mag128b[1] = vqdmulhq_s16(mmtmpD3,QAM_amp128b);\n          dl_ch_mag128[0] = vqdmulhq_s16(mmtmpD2,QAM_amp128);\n          dl_ch_mag128[1] = vqdmulhq_s16(mmtmpD3,QAM_amp128);\n\n          if (pilots==0) {\n            dl_ch_mag128b[2] = vqdmulhq_s16(mmtmpD4,QAM_amp128b);\n            dl_ch_mag128[2]  = vqdmulhq_s16(mmtmpD4,QAM_amp128);\n          }\n        }\n\n        mmtmpD0 = vmull_s16(dl_ch128[0], rxdataF128[0]);\n        //mmtmpD0 = [Re(ch[0])Re(rx[0]) Im(ch[0])Im(ch[0]) Re(ch[1])Re(rx[1]) Im(ch[1])Im(ch[1])]\n        mmtmpD1 = vmull_s16(dl_ch128[1], rxdataF128[1]);\n        //mmtmpD1 = [Re(ch[2])Re(rx[2]) Im(ch[2])Im(ch[2]) Re(ch[3])Re(rx[3]) Im(ch[3])Im(ch[3])]\n        mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0),vget_high_s32(mmtmpD0)),\n                               vpadd_s32(vget_low_s32(mmtmpD1),vget_high_s32(mmtmpD1)));\n        //mmtmpD0 = [Re(ch[0])Re(rx[0])+Im(ch[0])Im(ch[0]) Re(ch[1])Re(rx[1])+Im(ch[1])Im(ch[1]) Re(ch[2])Re(rx[2])+Im(ch[2])Im(ch[2]) Re(ch[3])Re(rx[3])+Im(ch[3])Im(ch[3])]\n        mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch128[0],*(int16x4_t *)conj)), rxdataF128[0]);\n        //mmtmpD0 = [-Im(ch[0])Re(rx[0]) Re(ch[0])Im(rx[0]) -Im(ch[1])Re(rx[1]) Re(ch[1])Im(rx[1])]\n        mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch128[1],*(int16x4_t *)conj)), rxdataF128[1]);\n        //mmtmpD0 = [-Im(ch[2])Re(rx[2]) Re(ch[2])Im(rx[2]) -Im(ch[3])Re(rx[3]) Re(ch[3])Im(rx[3])]\n        mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b),vget_high_s32(mmtmpD0b)),\n                               vpadd_s32(vget_low_s32(mmtmpD1b),vget_high_s32(mmtmpD1b)));\n        //mmtmpD1 = [-Im(ch[0])Re(rx[0])+Re(ch[0])Im(rx[0]) -Im(ch[1])Re(rx[1])+Re(ch[1])Im(rx[1]) -Im(ch[2])Re(rx[2])+Re(ch[2])Im(rx[2]) -Im(ch[3])Re(rx[3])+Re(ch[3])Im(rx[3])]\n        mmtmpD0 = vqshlq_s32(mmtmpD0,output_shift128);\n        mmtmpD1 = vqshlq_s32(mmtmpD1,output_shift128);\n        rxdataF_comp128[0] = vzip_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1));\n        mmtmpD0 = vmull_s16(dl_ch128[2], rxdataF128[2]);\n        mmtmpD1 = vmull_s16(dl_ch128[3], rxdataF128[3]);\n        mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0),vget_high_s32(mmtmpD0)),\n                               vpadd_s32(vget_low_s32(mmtmpD1),vget_high_s32(mmtmpD1)));\n        mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch128[2],*(int16x4_t *)conj)), rxdataF128[2]);\n        mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch128[3],*(int16x4_t *)conj)), rxdataF128[3]);\n        mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b),vget_high_s32(mmtmpD0b)),\n                               vpadd_s32(vget_low_s32(mmtmpD1b),vget_high_s32(mmtmpD1b)));\n        mmtmpD0 = vqshlq_s32(mmtmpD0,output_shift128);\n        mmtmpD1 = vqshlq_s32(mmtmpD1,output_shift128);\n        rxdataF_comp128[1] = vzip_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1));\n\n        if (pilots==0) {\n          mmtmpD0 = vmull_s16(dl_ch128[4], rxdataF128[4]);\n          mmtmpD1 = vmull_s16(dl_ch128[5], rxdataF128[5]);\n          mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0),vget_high_s32(mmtmpD0)),\n                                 vpadd_s32(vget_low_s32(mmtmpD1),vget_high_s32(mmtmpD1)));\n          mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch128[4],*(int16x4_t *)conj)), rxdataF128[4]);\n          mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch128[5],*(int16x4_t *)conj)), rxdataF128[5]);\n          mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b),vget_high_s32(mmtmpD0b)),\n                                 vpadd_s32(vget_low_s32(mmtmpD1b),vget_high_s32(mmtmpD1b)));\n          mmtmpD0 = vqshlq_s32(mmtmpD0,output_shift128);\n          mmtmpD1 = vqshlq_s32(mmtmpD1,output_shift128);\n          rxdataF_comp128[2] = vzip_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1));\n          dl_ch128+=6;\n          dl_ch_mag128+=3;\n          dl_ch_mag128b+=3;\n          rxdataF128+=6;\n          rxdataF_comp128+=3;\n        } else { // we have a smaller PDSCH in symbols with pilots so skip last group of 4 REs and increment less\n          dl_ch128+=4;\n          dl_ch_mag128+=2;\n          dl_ch_mag128b+=2;\n          rxdataF128+=4;\n          rxdataF_comp128+=2;\n        }\n      }\n    }\n  }\n\n  if (rho) {\n    for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) {\n      rho128        = (int16x4x2_t *)&rho[aarx][symbol*frame_parms->N_RB_DL*12];\n      dl_ch128      = (int16x4_t *)&dl_ch_estimates_ext[aarx][symbol*frame_parms->N_RB_DL*12];\n      dl_ch128_2    = (int16x4_t *)&dl_ch_estimates_ext[2+aarx][symbol*frame_parms->N_RB_DL*12];\n\n      for (rb=0; rb<nb_rb; rb++) {\n        mmtmpD0 = vmull_s16(dl_ch128[0], dl_ch128_2[0]);\n        mmtmpD1 = vmull_s16(dl_ch128[1], dl_ch128_2[1]);\n        mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0),vget_high_s32(mmtmpD0)),\n                               vpadd_s32(vget_low_s32(mmtmpD1),vget_high_s32(mmtmpD1)));\n        mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch128[0],*(int16x4_t *)conj)), dl_ch128_2[0]);\n        mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch128[1],*(int16x4_t *)conj)), dl_ch128_2[1]);\n        mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b),vget_high_s32(mmtmpD0b)),\n                               vpadd_s32(vget_low_s32(mmtmpD1b),vget_high_s32(mmtmpD1b)));\n        mmtmpD0 = vqshlq_s32(mmtmpD0,output_shift128);\n        mmtmpD1 = vqshlq_s32(mmtmpD1,output_shift128);\n        rho128[0] = vzip_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1));\n        mmtmpD0 = vmull_s16(dl_ch128[2], dl_ch128_2[2]);\n        mmtmpD1 = vmull_s16(dl_ch128[3], dl_ch128_2[3]);\n        mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0),vget_high_s32(mmtmpD0)),\n                               vpadd_s32(vget_low_s32(mmtmpD1),vget_high_s32(mmtmpD1)));\n        mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch128[2],*(int16x4_t *)conj)), dl_ch128_2[2]);\n        mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch128[3],*(int16x4_t *)conj)), dl_ch128_2[3]);\n        mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b),vget_high_s32(mmtmpD0b)),\n                               vpadd_s32(vget_low_s32(mmtmpD1b),vget_high_s32(mmtmpD1b)));\n        mmtmpD0 = vqshlq_s32(mmtmpD0,output_shift128);\n        mmtmpD1 = vqshlq_s32(mmtmpD1,output_shift128);\n        rho128[1] = vzip_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1));\n        mmtmpD0 = vmull_s16(dl_ch128[0], dl_ch128_2[0]);\n        mmtmpD1 = vmull_s16(dl_ch128[1], dl_ch128_2[1]);\n        mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0),vget_high_s32(mmtmpD0)),\n                               vpadd_s32(vget_low_s32(mmtmpD1),vget_high_s32(mmtmpD1)));\n        mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch128[4],*(int16x4_t *)conj)), dl_ch128_2[4]);\n        mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch128[5],*(int16x4_t *)conj)), dl_ch128_2[5]);\n        mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b),vget_high_s32(mmtmpD0b)),\n                               vpadd_s32(vget_low_s32(mmtmpD1b),vget_high_s32(mmtmpD1b)));\n        mmtmpD0 = vqshlq_s32(mmtmpD0,output_shift128);\n        mmtmpD1 = vqshlq_s32(mmtmpD1,output_shift128);\n        rho128[2] = vzip_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1));\n        dl_ch128+=6;\n        dl_ch128_2+=6;\n        rho128+=3;\n      }\n\n      if (first_symbol_flag==1) {\n        measurements->rx_correlation[0][aarx] = signal_energy(&rho[aarx][symbol*frame_parms->N_RB_DL*12],rb*12);\n      }\n    }\n  }\n\n#endif\n}\n\nvoid dlsch_channel_compensation_core(int **rxdataF_ext,\n                                     int **dl_ch_estimates_ext,\n                                     int **dl_ch_mag,\n                                     int **dl_ch_magb,\n                                     int **rxdataF_comp,\n                                     int **rho,\n                                     unsigned char n_tx,\n                                     unsigned char n_rx,\n                                     unsigned char mod_order,\n                                     unsigned char output_shift,\n                                     int length,\n                                     int start_point)\n\n{\n  unsigned short ii;\n  int length_mod8 = 0;\n  int length2;\n  __m128i *dl_ch128,*dl_ch_mag128,*dl_ch_mag128b, *dl_ch128_2, *rxdataF128,*rxdataF_comp128,*rho128;\n  __m128i mmtmpD0,mmtmpD1,mmtmpD2,mmtmpD3,QAM_amp128;\n  int aatx = 0, aarx = 0;\n\n  for (aatx=0; aatx<n_tx; aatx++) {\n    __m128i QAM_amp128b;\n\n    if (mod_order == 4) {\n      QAM_amp128 = _mm_set1_epi16(QAM16_n1);  // 2/sqrt(10)\n      QAM_amp128b = _mm_setzero_si128();\n    } else if (mod_order == 6) {\n      QAM_amp128  = _mm_set1_epi16(QAM64_n1); //\n      QAM_amp128b = _mm_set1_epi16(QAM64_n2);\n    }\n\n    for (aarx=0; aarx<n_rx; aarx++) {\n      /* TODO: hack to be removed. There is crash for 1 antenna case, so\n       * for 1 antenna case, I put back the value 2 as it was before\n       * Elena's commit.\n       */\n      int x = n_rx > 1 ? n_rx : 2;\n      dl_ch128          = (__m128i *)&dl_ch_estimates_ext[aatx*x + aarx][start_point];\n      dl_ch_mag128      = (__m128i *)&dl_ch_mag[aatx*x + aarx][start_point];\n      dl_ch_mag128b     = (__m128i *)&dl_ch_magb[aatx*x + aarx][start_point];\n      rxdataF128        = (__m128i *)&rxdataF_ext[aarx][start_point];\n      rxdataF_comp128   = (__m128i *)&rxdataF_comp[aatx*x + aarx][start_point];\n      length_mod8 = length&7;\n\n      if (length_mod8 == 0) {\n        length2 = length>>3;\n\n        for (ii=0; ii<length2; ++ii) {\n          if (mod_order>2) {\n            // get channel amplitude if not QPSK\n            mmtmpD0 = _mm_madd_epi16(dl_ch128[0],dl_ch128[0]);\n            mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift);\n            mmtmpD1 = _mm_madd_epi16(dl_ch128[1],dl_ch128[1]);\n            mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift);\n            mmtmpD0 = _mm_packs_epi32(mmtmpD0,mmtmpD1);\n            // store channel magnitude here in a new field of dlsch\n            dl_ch_mag128[0] = _mm_unpacklo_epi16(mmtmpD0,mmtmpD0);\n            dl_ch_mag128b[0] = dl_ch_mag128[0];\n            dl_ch_mag128[0] = _mm_mulhi_epi16(dl_ch_mag128[0],QAM_amp128);\n            dl_ch_mag128[0] = _mm_slli_epi16(dl_ch_mag128[0],1);\n            //print_ints(\"Re(ch):\",(int16_t*)&mmtmpD0);\n            //print_shorts(\"QAM_amp:\",(int16_t*)&QAM_amp128);\n            //print_shorts(\"mag:\",(int16_t*)&dl_ch_mag128[0]);\n            dl_ch_mag128[1] = _mm_unpackhi_epi16(mmtmpD0,mmtmpD0);\n            dl_ch_mag128b[1] = dl_ch_mag128[1];\n            dl_ch_mag128[1] = _mm_mulhi_epi16(dl_ch_mag128[1],QAM_amp128);\n            dl_ch_mag128[1] = _mm_slli_epi16(dl_ch_mag128[1],1);\n            dl_ch_mag128b[0] = _mm_mulhi_epi16(dl_ch_mag128b[0],QAM_amp128b);\n            dl_ch_mag128b[0] = _mm_slli_epi16(dl_ch_mag128b[0],1);\n            dl_ch_mag128b[1] = _mm_mulhi_epi16(dl_ch_mag128b[1],QAM_amp128b);\n            dl_ch_mag128b[1] = _mm_slli_epi16(dl_ch_mag128b[1],1);\n          }\n\n          // multiply by conjugated channel\n          mmtmpD0 = _mm_madd_epi16(dl_ch128[0],rxdataF128[0]);\n          // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n          mmtmpD1 = _mm_shufflelo_epi16(dl_ch128[0],_MM_SHUFFLE(2,3,0,1));\n          mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1));\n          mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)&conjugate[0]);\n          //  print_ints(\"im\",&mmtmpD1);\n          mmtmpD1 = _mm_madd_epi16(mmtmpD1,rxdataF128[0]);\n          // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n          mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift);\n          //  print_ints(\"re(shift)\",&mmtmpD0);\n          mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift);\n          //  print_ints(\"im(shift)\",&mmtmpD1);\n          mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1);\n          mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1);\n          //        print_ints(\"c0\",&mmtmpD2);\n          //  print_ints(\"c1\",&mmtmpD3);\n          rxdataF_comp128[0] = _mm_packs_epi32(mmtmpD2,mmtmpD3);\n          //  print_shorts(\"rx:\",rxdataF128);\n          //  print_shorts(\"ch:\",dl_ch128);\n          //  print_shorts(\"pack:\",rxdataF_comp128);\n          // multiply by conjugated channel\n          mmtmpD0 = _mm_madd_epi16(dl_ch128[1],rxdataF128[1]);\n          // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n          mmtmpD1 = _mm_shufflelo_epi16(dl_ch128[1],_MM_SHUFFLE(2,3,0,1));\n          mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1));\n          mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)conjugate);\n          mmtmpD1 = _mm_madd_epi16(mmtmpD1,rxdataF128[1]);\n          // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n          mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift);\n          mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift);\n          mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1);\n          mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1);\n          rxdataF_comp128[1] = _mm_packs_epi32(mmtmpD2,mmtmpD3);\n          //  print_shorts(\"rx:\",rxdataF128+1);\n          //  print_shorts(\"ch:\",dl_ch128+1);\n          //print_shorts(\"pack:\",rxdataF_comp128+1);\n          dl_ch128+=2;\n          dl_ch_mag128+=2;\n          dl_ch_mag128b+=2;\n          rxdataF128+=2;\n          rxdataF_comp128+=2;\n        }\n      } else {\n        printf (\"Channel Compensation: Received number of subcarriers is not multiple of 8, \\n\"\n                \"need to adapt the code!\\n\");\n      }\n    }\n  }\n\n  /*This part of code makes sense only for processing in 2x2 blocks*/\n  if (rho) {\n    for (aarx=0; aarx<n_rx; aarx++) {\n      rho128        = (__m128i *)&rho[aarx][start_point];\n      dl_ch128      = (__m128i *)&dl_ch_estimates_ext[aarx][start_point];\n      dl_ch128_2    = (__m128i *)&dl_ch_estimates_ext[2+aarx][start_point];\n\n      if (length_mod8 == 0) {\n        length2 = length>>3;\n\n        for (ii=0; ii<length2; ++ii) {\n          // multiply by conjugated channel\n          mmtmpD0 = _mm_madd_epi16(dl_ch128[0],dl_ch128_2[0]);\n          //  print_ints(\"re\",&mmtmpD0);\n          // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n          mmtmpD1 = _mm_shufflelo_epi16(dl_ch128[0],_MM_SHUFFLE(2,3,0,1));\n          mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1));\n          mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)&conjugate[0]);\n          //  print_ints(\"im\",&mmtmpD1);\n          mmtmpD1 = _mm_madd_epi16(mmtmpD1,dl_ch128_2[0]);\n          // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n          mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift);\n          //  print_ints(\"re(shift)\",&mmtmpD0);\n          mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift);\n          //  print_ints(\"im(shift)\",&mmtmpD1);\n          mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1);\n          mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1);\n          //        print_ints(\"c0\",&mmtmpD2);\n          //  print_ints(\"c1\",&mmtmpD3);\n          rho128[0] = _mm_packs_epi32(mmtmpD2,mmtmpD3);\n          //print_shorts(\"rx:\",dl_ch128_2);\n          //print_shorts(\"ch:\",dl_ch128);\n          //print_shorts(\"pack:\",rho128);\n          // multiply by conjugated channel\n          mmtmpD0 = _mm_madd_epi16(dl_ch128[1],dl_ch128_2[1]);\n          // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n          mmtmpD1 = _mm_shufflelo_epi16(dl_ch128[1],_MM_SHUFFLE(2,3,0,1));\n          mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1));\n          mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)conjugate);\n          mmtmpD1 = _mm_madd_epi16(mmtmpD1,dl_ch128_2[1]);\n          // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n          mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift);\n          mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift);\n          mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1);\n          mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1);\n          rho128[1] =_mm_packs_epi32(mmtmpD2,mmtmpD3);\n          dl_ch128+=2;\n          dl_ch128_2+=2;\n          rho128+=2;\n        }\n      } else {\n        printf (\"Channel Compensation: Received number of subcarriers is not multiple of 8, \\n\"\n                \"need to adapt the code!\\n\");\n      }\n    }\n  }\n\n  _mm_empty();\n  _m_empty();\n}\n\n#if defined(__x86_64__) || defined(__i386__)\n\nvoid prec2A_TM56_128(unsigned char pmi,__m128i *ch0,__m128i *ch1) {\n  __m128i amp;\n  amp = _mm_set1_epi16(ONE_OVER_SQRT2_Q15);\n\n  switch (pmi) {\n    case 0 :   // +1 +1\n      //    print_shorts(\"phase 0 :ch0\",ch0);\n      //    print_shorts(\"phase 0 :ch1\",ch1);\n      ch0[0] = _mm_adds_epi16(ch0[0],ch1[0]);\n      break;\n\n    case 1 :   // +1 -1\n      //    print_shorts(\"phase 1 :ch0\",ch0);\n      //    print_shorts(\"phase 1 :ch1\",ch1);\n      ch0[0] = _mm_subs_epi16(ch0[0],ch1[0]);\n      //    print_shorts(\"phase 1 :ch0-ch1\",ch0);\n      break;\n\n    case 2 :   // +1 +j\n      ch1[0] = _mm_sign_epi16(ch1[0],*(__m128i *)&conjugate[0]);\n      ch1[0] = _mm_shufflelo_epi16(ch1[0],_MM_SHUFFLE(2,3,0,1));\n      ch1[0] = _mm_shufflehi_epi16(ch1[0],_MM_SHUFFLE(2,3,0,1));\n      ch0[0] = _mm_subs_epi16(ch0[0],ch1[0]);\n      break;   // +1 -j\n\n    case 3 :\n      ch1[0] = _mm_sign_epi16(ch1[0],*(__m128i *)&conjugate[0]);\n      ch1[0] = _mm_shufflelo_epi16(ch1[0],_MM_SHUFFLE(2,3,0,1));\n      ch1[0] = _mm_shufflehi_epi16(ch1[0],_MM_SHUFFLE(2,3,0,1));\n      ch0[0] = _mm_adds_epi16(ch0[0],ch1[0]);\n      break;\n  }\n\n  ch0[0] = _mm_mulhi_epi16(ch0[0],amp);\n  ch0[0] = _mm_slli_epi16(ch0[0],1);\n  _mm_empty();\n  _m_empty();\n}\n#elif defined(__arm__)\nvoid prec2A_TM56_128(unsigned char pmi,__m128i *ch0,__m128i *ch1) {\n  // sqrt(2) is already taken into account in computation sqrt_rho_a, sqrt_rho_b,\n  //so removed it\n\n  //__m128i amp;\n  //amp = _mm_set1_epi16(ONE_OVER_SQRT2_Q15);\n  switch (pmi) {\n    case 0 :   // +1 +1\n      //    print_shorts(\"phase 0 :ch0\",ch0);\n      //    print_shorts(\"phase 0 :ch1\",ch1);\n      ch0[0] = _mm_adds_epi16(ch0[0],ch1[0]);\n      break;\n\n    case 1 :   // +1 -1\n      //    print_shorts(\"phase 1 :ch0\",ch0);\n      //    print_shorts(\"phase 1 :ch1\",ch1);\n      ch0[0] = _mm_subs_epi16(ch0[0],ch1[0]);\n      //    print_shorts(\"phase 1 :ch0-ch1\",ch0);\n      break;\n\n    case 2 :   // +1 +j\n      ch1[0] = _mm_sign_epi16(ch1[0],*(__m128i *)&conjugate[0]);\n      ch1[0] = _mm_shufflelo_epi16(ch1[0],_MM_SHUFFLE(2,3,0,1));\n      ch1[0] = _mm_shufflehi_epi16(ch1[0],_MM_SHUFFLE(2,3,0,1));\n      ch0[0] = _mm_subs_epi16(ch0[0],ch1[0]);\n      break;   // +1 -j\n\n    case 3 :\n      ch1[0] = _mm_sign_epi16(ch1[0],*(__m128i *)&conjugate[0]);\n      ch1[0] = _mm_shufflelo_epi16(ch1[0],_MM_SHUFFLE(2,3,0,1));\n      ch1[0] = _mm_shufflehi_epi16(ch1[0],_MM_SHUFFLE(2,3,0,1));\n      ch0[0] = _mm_adds_epi16(ch0[0],ch1[0]);\n      break;\n  }\n\n  //ch0[0] = _mm_mulhi_epi16(ch0[0],amp);\n  //ch0[0] = _mm_slli_epi16(ch0[0],1);\n  _mm_empty();\n  _m_empty();\n}\n#endif\n// precoding is stream 0 .5(1,1)  .5(1,-1) .5(1,1)  .5(1,-1)\n//              stream 1 .5(1,-1) .5(1,1)  .5(1,-1) .5(1,1)\n// store \"precoded\" channel for stream 0 in ch0, stream 1 in ch1\n\nshort TM3_prec[8]__attribute__((aligned(16))) = {1,1,-1,-1,1,1,-1,-1} ;\n\nvoid prec2A_TM3_128(__m128i *ch0,__m128i *ch1) {\n  __m128i amp = _mm_set1_epi16(ONE_OVER_SQRT2_Q15);\n  __m128i tmp0,tmp1;\n  //_mm_mulhi_epi16\n  //  print_shorts(\"prec2A_TM3 ch0 (before):\",ch0);\n  //  print_shorts(\"prec2A_TM3 ch1 (before):\",ch1);\n  tmp0 = ch0[0];\n  tmp1  = _mm_sign_epi16(ch1[0],((__m128i *)&TM3_prec)[0]);\n  //  print_shorts(\"prec2A_TM3 ch1*s (mid):\",(__m128i*)TM3_prec);\n  ch0[0] = _mm_adds_epi16(ch0[0],tmp1);\n  ch1[0] = _mm_subs_epi16(tmp0,tmp1);\n  ch0[0] = _mm_mulhi_epi16(ch0[0],amp);\n  ch0[0] = _mm_slli_epi16(ch0[0],1);\n  ch1[0] = _mm_mulhi_epi16(ch1[0],amp);\n  ch1[0] = _mm_slli_epi16(ch1[0],1);\n  //  print_shorts(\"prec2A_TM3 ch0 (mid):\",&tmp0);\n  //  print_shorts(\"prec2A_TM3 ch1 (mid):\",ch1);\n  //ch0[0] = _mm_mulhi_epi16(ch0[0],amp);\n  //ch0[0] = _mm_slli_epi16(ch0[0],1);\n  //ch1[0] = _mm_mulhi_epi16(ch1[0],amp);\n  //ch1[0] = _mm_slli_epi16(ch1[0],1);\n  //ch0[0] = _mm_srai_epi16(ch0[0],1);\n  //ch1[0] = _mm_srai_epi16(ch1[0],1);\n  //  print_shorts(\"prec2A_TM3 ch0 (after):\",ch0);\n  //  print_shorts(\"prec2A_TM3 ch1 (after):\",ch1);\n  _mm_empty();\n  _m_empty();\n}\n\n// pmi = 0 => stream 0 (1,1), stream 1 (1,-1)\n// pmi = 1 => stream 0 (1,j), stream 2 (1,-j)\n\nvoid prec2A_TM4_128(int pmi,__m128i *ch0,__m128i *ch1) {\n  // sqrt(2) is already taken into account in computation sqrt_rho_a, sqrt_rho_b,\n  //so divide by 2 is replaced by divide by sqrt(2).\n  // printf (\"demod pmi=%d\\n\", pmi);\n  __m128i amp;\n  amp = _mm_set1_epi16(ONE_OVER_SQRT2_Q15);\n  __m128i tmp0,tmp1;\n\n  // print_shorts(\"prec2A_TM4 ch0 (before):\",ch0);\n  // print_shorts(\"prec2A_TM4 ch1 (before):\",ch1);\n\n  if (pmi == 0) { //[1 1;1 -1]\n    tmp0 = ch0[0];\n    tmp1 = ch1[0];\n    ch0[0] = _mm_adds_epi16(tmp0,tmp1);\n    ch1[0] = _mm_subs_epi16(tmp0,tmp1);\n  } else { //ch0+j*ch1 ch0-j*ch1\n    tmp0 = ch0[0];\n    tmp1   = _mm_sign_epi16(ch1[0],*(__m128i *)&conjugate[0]);\n    tmp1   = _mm_shufflelo_epi16(tmp1,_MM_SHUFFLE(2,3,0,1));\n    tmp1   = _mm_shufflehi_epi16(tmp1,_MM_SHUFFLE(2,3,0,1));\n    ch0[0] = _mm_subs_epi16(tmp0,tmp1);\n    ch1[0] = _mm_add_epi16(tmp0,tmp1);\n  }\n\n  //print_shorts(\"prec2A_TM4 ch0 (middle):\",ch0);\n  //print_shorts(\"prec2A_TM4 ch1 (middle):\",ch1);\n  ch0[0] = _mm_mulhi_epi16(ch0[0],amp);\n  ch0[0] = _mm_slli_epi16(ch0[0],1);\n  ch1[0] = _mm_mulhi_epi16(ch1[0],amp);\n  ch1[0] = _mm_slli_epi16(ch1[0],1);\n  // ch0[0] = _mm_srai_epi16(ch0[0],1); //divide by 2\n  // ch1[0] = _mm_srai_epi16(ch1[0],1); //divide by 2\n  //print_shorts(\"prec2A_TM4 ch0 (end):\",ch0);\n  //print_shorts(\"prec2A_TM4 ch1 (end):\",ch1);\n  _mm_empty();\n  _m_empty();\n  // print_shorts(\"prec2A_TM4 ch0 (end):\",ch0);\n  //print_shorts(\"prec2A_TM4 ch1 (end):\",ch1);\n}\n\nvoid dlsch_channel_compensation_TM56(int **rxdataF_ext,\n                                     int **dl_ch_estimates_ext,\n                                     int **dl_ch_mag,\n                                     int **dl_ch_magb,\n                                     int **rxdataF_comp,\n                                     unsigned char *pmi_ext,\n                                     LTE_DL_FRAME_PARMS *frame_parms,\n                                     PHY_MEASUREMENTS *measurements,\n                                     int eNB_id,\n                                     unsigned char symbol,\n                                     unsigned char mod_order,\n                                     unsigned short nb_rb,\n                                     unsigned char output_shift,\n                                     unsigned char dl_power_off) {\n#if defined(__x86_64__) || defined(__i386__)\n  unsigned short rb,Nre;\n  __m128i *dl_ch0_128,*dl_ch1_128,*dl_ch_mag128,*dl_ch_mag128b,*rxdataF128,*rxdataF_comp128;\n  unsigned char aarx=0,symbol_mod,pilots=0;\n  int precoded_signal_strength=0;\n  __m128i mmtmpD0,mmtmpD1,mmtmpD2,mmtmpD3,QAM_amp128;\n  symbol_mod = (symbol>=(7-frame_parms->Ncp)) ? symbol-(7-frame_parms->Ncp) : symbol;\n\n  if ((symbol_mod == 0) || (symbol_mod == (4-frame_parms->Ncp)))\n    pilots=1;\n\n  //printf(\"comp prec: symbol %d, pilots %d\\n\",symbol, pilots);\n  __m128i QAM_amp128b = _mm_setzero_si128();\n\n  if (mod_order == 4) {\n    QAM_amp128 = _mm_set1_epi16(QAM16_n1);\n  } else if (mod_order == 6) {\n    QAM_amp128  = _mm_set1_epi16(QAM64_n1);\n    QAM_amp128b = _mm_set1_epi16(QAM64_n2);\n  }\n\n  for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) {\n    dl_ch0_128          = (__m128i *)&dl_ch_estimates_ext[aarx][symbol*frame_parms->N_RB_DL*12];\n    dl_ch1_128          = (__m128i *)&dl_ch_estimates_ext[2+aarx][symbol*frame_parms->N_RB_DL*12];\n    dl_ch_mag128      = (__m128i *)&dl_ch_mag[aarx][symbol*frame_parms->N_RB_DL*12];\n    dl_ch_mag128b     = (__m128i *)&dl_ch_magb[aarx][symbol*frame_parms->N_RB_DL*12];\n    rxdataF128        = (__m128i *)&rxdataF_ext[aarx][symbol*frame_parms->N_RB_DL*12];\n    rxdataF_comp128   = (__m128i *)&rxdataF_comp[aarx][symbol*frame_parms->N_RB_DL*12];\n\n    for (rb=0; rb<nb_rb; rb++) {\n      // combine TX channels using precoder from pmi\n#ifdef DEBUG_DLSCH_DEMOD\n      printf(\"mode 6 prec: rb %d, pmi->%d\\n\",rb,pmi_ext[rb]);\n#endif\n      prec2A_TM56_128(pmi_ext[rb],&dl_ch0_128[0],&dl_ch1_128[0]);\n      prec2A_TM56_128(pmi_ext[rb],&dl_ch0_128[1],&dl_ch1_128[1]);\n\n      if (pilots==0) {\n        prec2A_TM56_128(pmi_ext[rb],&dl_ch0_128[2],&dl_ch1_128[2]);\n      }\n\n      if (mod_order>2) {\n        // get channel amplitude if not QPSK\n        mmtmpD0 = _mm_madd_epi16(dl_ch0_128[0],dl_ch0_128[0]);\n        mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift);\n        mmtmpD1 = _mm_madd_epi16(dl_ch0_128[1],dl_ch0_128[1]);\n        mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift);\n        mmtmpD0 = _mm_packs_epi32(mmtmpD0,mmtmpD1);\n        dl_ch_mag128[0] = _mm_unpacklo_epi16(mmtmpD0,mmtmpD0);\n        dl_ch_mag128b[0] = dl_ch_mag128[0];\n        dl_ch_mag128[0] = _mm_mulhi_epi16(dl_ch_mag128[0],QAM_amp128);\n        dl_ch_mag128[0] = _mm_slli_epi16(dl_ch_mag128[0],1);\n        //print_shorts(\"dl_ch_mag128[0]=\",&dl_ch_mag128[0]);\n        //print_shorts(\"dl_ch_mag128[0]=\",&dl_ch_mag128[0]);\n        dl_ch_mag128[1] = _mm_unpackhi_epi16(mmtmpD0,mmtmpD0);\n        dl_ch_mag128b[1] = dl_ch_mag128[1];\n        dl_ch_mag128[1] = _mm_mulhi_epi16(dl_ch_mag128[1],QAM_amp128);\n        dl_ch_mag128[1] = _mm_slli_epi16(dl_ch_mag128[1],1);\n\n        if (pilots==0) {\n          mmtmpD0 = _mm_madd_epi16(dl_ch0_128[2],dl_ch0_128[2]);\n          mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift);\n          mmtmpD1 = _mm_packs_epi32(mmtmpD0,mmtmpD0);\n          dl_ch_mag128[2] = _mm_unpacklo_epi16(mmtmpD1,mmtmpD1);\n          dl_ch_mag128b[2] = dl_ch_mag128[2];\n          dl_ch_mag128[2] = _mm_mulhi_epi16(dl_ch_mag128[2],QAM_amp128);\n          dl_ch_mag128[2] = _mm_slli_epi16(dl_ch_mag128[2],1);\n        }\n\n        dl_ch_mag128b[0] = _mm_mulhi_epi16(dl_ch_mag128b[0],QAM_amp128b);\n        dl_ch_mag128b[0] = _mm_slli_epi16(dl_ch_mag128b[0],1);\n        //print_shorts(\"dl_ch_mag128b[0]=\",&dl_ch_mag128b[0]);\n        dl_ch_mag128b[1] = _mm_mulhi_epi16(dl_ch_mag128b[1],QAM_amp128b);\n        dl_ch_mag128b[1] = _mm_slli_epi16(dl_ch_mag128b[1],1);\n\n        if (pilots==0) {\n          dl_ch_mag128b[2] = _mm_mulhi_epi16(dl_ch_mag128b[2],QAM_amp128b);\n          dl_ch_mag128b[2] = _mm_slli_epi16(dl_ch_mag128b[2],1);\n        }\n      }\n\n      // MF multiply by conjugated channel\n      mmtmpD0 = _mm_madd_epi16(dl_ch0_128[0],rxdataF128[0]);\n      //        print_ints(\"re\",&mmtmpD0);\n      // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n      mmtmpD1 = _mm_shufflelo_epi16(dl_ch0_128[0],_MM_SHUFFLE(2,3,0,1));\n      mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1));\n      mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)&conjugate[0]);\n      //        print_ints(\"im\",&mmtmpD1);\n      mmtmpD1 = _mm_madd_epi16(mmtmpD1,rxdataF128[0]);\n      // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n      mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift);\n      //        print_ints(\"re(shift)\",&mmtmpD0);\n      mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift);\n      //        print_ints(\"im(shift)\",&mmtmpD1);\n      mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1);\n      mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1);\n      //        print_ints(\"c0\",&mmtmpD2);\n      //        print_ints(\"c1\",&mmtmpD3);\n      rxdataF_comp128[0] = _mm_packs_epi32(mmtmpD2,mmtmpD3);\n      //        print_shorts(\"rx:\",rxdataF128);\n      //        print_shorts(\"ch:\",dl_ch128);\n      //        print_shorts(\"pack:\",rxdataF_comp128);\n      // multiply by conjugated channel\n      mmtmpD0 = _mm_madd_epi16(dl_ch0_128[1],rxdataF128[1]);\n      // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n      mmtmpD1 = _mm_shufflelo_epi16(dl_ch0_128[1],_MM_SHUFFLE(2,3,0,1));\n      mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1));\n      mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)conjugate);\n      mmtmpD1 = _mm_madd_epi16(mmtmpD1,rxdataF128[1]);\n      // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n      mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift);\n      mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift);\n      mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1);\n      mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1);\n      rxdataF_comp128[1] = _mm_packs_epi32(mmtmpD2,mmtmpD3);\n      //  print_shorts(\"rx:\",rxdataF128+1);\n      //  print_shorts(\"ch:\",dl_ch128+1);\n      //  print_shorts(\"pack:\",rxdataF_comp128+1);\n\n      if (pilots==0) {\n        // multiply by conjugated channel\n        mmtmpD0 = _mm_madd_epi16(dl_ch0_128[2],rxdataF128[2]);\n        // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n        mmtmpD1 = _mm_shufflelo_epi16(dl_ch0_128[2],_MM_SHUFFLE(2,3,0,1));\n        mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1));\n        mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)conjugate);\n        mmtmpD1 = _mm_madd_epi16(mmtmpD1,rxdataF128[2]);\n        // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n        mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift);\n        mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift);\n        mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1);\n        mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1);\n        rxdataF_comp128[2] = _mm_packs_epi32(mmtmpD2,mmtmpD3);\n        //  print_shorts(\"rx:\",rxdataF128+2);\n        //  print_shorts(\"ch:\",dl_ch128+2);\n        //        print_shorts(\"pack:\",rxdataF_comp128+2);\n        dl_ch0_128+=3;\n        dl_ch1_128+=3;\n        dl_ch_mag128+=3;\n        dl_ch_mag128b+=3;\n        rxdataF128+=3;\n        rxdataF_comp128+=3;\n      } else {\n        dl_ch0_128+=2;\n        dl_ch1_128+=2;\n        dl_ch_mag128+=2;\n        dl_ch_mag128b+=2;\n        rxdataF128+=2;\n        rxdataF_comp128+=2;\n      }\n    }\n\n    Nre = (pilots==0) ? 12 : 8;\n    precoded_signal_strength += ((signal_energy_nodc(&dl_ch_estimates_ext[aarx][symbol*frame_parms->N_RB_DL*Nre],\n                                  (nb_rb*Nre))) - (measurements->n0_power[aarx]));\n  } // rx_antennas\n\n  measurements->precoded_cqi_dB[eNB_id][0] = dB_fixed2(precoded_signal_strength,measurements->n0_power_tot);\n  //printf(\"eNB_id %d, symbol %d: precoded CQI %d dB\\n\",eNB_id,symbol,\n  //   measurements->precoded_cqi_dB[eNB_id][0]);\n#elif defined(__arm__)\n  uint32_t rb,Nre;\n  uint32_t aarx,symbol_mod,pilots=0;\n  int16x4_t *dl_ch0_128,*dl_ch1_128,*rxdataF128;\n  int16x8_t *dl_ch0_128b,*dl_ch1_128b;\n  int32x4_t mmtmpD0,mmtmpD1,mmtmpD0b,mmtmpD1b;\n  int16x8_t *dl_ch_mag128,*dl_ch_mag128b,mmtmpD2,mmtmpD3,mmtmpD4,*rxdataF_comp128;\n  int16x8_t QAM_amp128,QAM_amp128b;\n  int16_t conj[4]__attribute__((aligned(16))) = {1,-1,1,-1};\n  int32x4_t output_shift128 = vmovq_n_s32(-(int32_t)output_shift);\n  int32_t precoded_signal_strength=0;\n  symbol_mod = (symbol>=(7-frame_parms->Ncp)) ? symbol-(7-frame_parms->Ncp) : symbol;\n\n  if ((symbol_mod == 0) || (symbol_mod == (4-frame_parms->Ncp))) {\n    if (frame_parms->nb_antenna_ports_eNB==1) { // 10 out of 12 so don't reduce size\n      nb_rb=1+(5*nb_rb/6);\n    } else {\n      pilots=1;\n    }\n  }\n\n  if (mod_order == 4) {\n    QAM_amp128  = vmovq_n_s16(QAM16_n1);  // 2/sqrt(10)\n    QAM_amp128b = vmovq_n_s16(0);\n  } else if (mod_order == 6) {\n    QAM_amp128  = vmovq_n_s16(QAM64_n1); //\n    QAM_amp128b = vmovq_n_s16(QAM64_n2);\n  }\n\n  //    printf(\"comp: rxdataF_comp %p, symbol %d\\n\",rxdataF_comp[0],symbol);\n\n  for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) {\n    dl_ch0_128          = (int16x4_t *)&dl_ch_estimates_ext[aarx][symbol*frame_parms->N_RB_DL*12];\n    dl_ch1_128          = (int16x4_t *)&dl_ch_estimates_ext[2+aarx][symbol*frame_parms->N_RB_DL*12];\n    dl_ch0_128b         = (int16x8_t *)&dl_ch_estimates_ext[aarx][symbol*frame_parms->N_RB_DL*12];\n    dl_ch1_128b         = (int16x8_t *)&dl_ch_estimates_ext[2+aarx][symbol*frame_parms->N_RB_DL*12];\n    dl_ch_mag128        = (int16x8_t *)&dl_ch_mag[aarx][symbol*frame_parms->N_RB_DL*12];\n    dl_ch_mag128b       = (int16x8_t *)&dl_ch_magb[aarx][symbol*frame_parms->N_RB_DL*12];\n    rxdataF128          = (int16x4_t *)&rxdataF_ext[aarx][symbol*frame_parms->N_RB_DL*12];\n    rxdataF_comp128     = (int16x8_t *)&rxdataF_comp[aarx][symbol*frame_parms->N_RB_DL*12];\n\n    for (rb=0; rb<nb_rb; rb++) {\n#ifdef DEBUG_DLSCH_DEMOD\n      printf(\"mode 6 prec: rb %d, pmi->%u\\n\",rb,pmi_ext[rb]);\n#endif\n      prec2A_TM56_128(pmi_ext[rb],&dl_ch0_128b[0],&dl_ch1_128b[0]);\n      prec2A_TM56_128(pmi_ext[rb],&dl_ch0_128b[1],&dl_ch1_128b[1]);\n\n      if (pilots==0) {\n        prec2A_TM56_128(pmi_ext[rb],&dl_ch0_128b[2],&dl_ch1_128b[2]);\n      }\n\n      if (mod_order>2) {\n        // get channel amplitude if not QPSK\n        mmtmpD0 = vmull_s16(dl_ch0_128[0], dl_ch0_128[0]);\n        // mmtmpD0 = [ch0*ch0,ch1*ch1,ch2*ch2,ch3*ch3];\n        mmtmpD0 = vqshlq_s32(vqaddq_s32(mmtmpD0,vrev64q_s32(mmtmpD0)),output_shift128);\n        // mmtmpD0 = [ch0*ch0 + ch1*ch1,ch0*ch0 + ch1*ch1,ch2*ch2 + ch3*ch3,ch2*ch2 + ch3*ch3]>>output_shift128 on 32-bits\n        mmtmpD1 = vmull_s16(dl_ch0_128[1], dl_ch0_128[1]);\n        mmtmpD1 = vqshlq_s32(vqaddq_s32(mmtmpD1,vrev64q_s32(mmtmpD1)),output_shift128);\n        mmtmpD2 = vcombine_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1));\n        // mmtmpD2 = [ch0*ch0 + ch1*ch1,ch0*ch0 + ch1*ch1,ch2*ch2 + ch3*ch3,ch2*ch2 + ch3*ch3,ch4*ch4 + ch5*ch5,ch4*ch4 + ch5*ch5,ch6*ch6 + ch7*ch7,ch6*ch6 + ch7*ch7]>>output_shift128 on 16-bits\n        mmtmpD0 = vmull_s16(dl_ch0_128[2], dl_ch0_128[2]);\n        mmtmpD0 = vqshlq_s32(vqaddq_s32(mmtmpD0,vrev64q_s32(mmtmpD0)),output_shift128);\n        mmtmpD1 = vmull_s16(dl_ch0_128[3], dl_ch0_128[3]);\n        mmtmpD1 = vqshlq_s32(vqaddq_s32(mmtmpD1,vrev64q_s32(mmtmpD1)),output_shift128);\n        mmtmpD3 = vcombine_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1));\n\n        if (pilots==0) {\n          mmtmpD0 = vmull_s16(dl_ch0_128[4], dl_ch0_128[4]);\n          mmtmpD0 = vqshlq_s32(vqaddq_s32(mmtmpD0,vrev64q_s32(mmtmpD0)),output_shift128);\n          mmtmpD1 = vmull_s16(dl_ch0_128[5], dl_ch0_128[5]);\n          mmtmpD1 = vqshlq_s32(vqaddq_s32(mmtmpD1,vrev64q_s32(mmtmpD1)),output_shift128);\n          mmtmpD4 = vcombine_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1));\n        }\n\n        dl_ch_mag128b[0] = vqdmulhq_s16(mmtmpD2,QAM_amp128b);\n        dl_ch_mag128b[1] = vqdmulhq_s16(mmtmpD3,QAM_amp128b);\n        dl_ch_mag128[0] = vqdmulhq_s16(mmtmpD2,QAM_amp128);\n        dl_ch_mag128[1] = vqdmulhq_s16(mmtmpD3,QAM_amp128);\n\n        if (pilots==0) {\n          dl_ch_mag128b[2] = vqdmulhq_s16(mmtmpD4,QAM_amp128b);\n          dl_ch_mag128[2]  = vqdmulhq_s16(mmtmpD4,QAM_amp128);\n        }\n      }\n\n      mmtmpD0 = vmull_s16(dl_ch0_128[0], rxdataF128[0]);\n      //mmtmpD0 = [Re(ch[0])Re(rx[0]) Im(ch[0])Im(ch[0]) Re(ch[1])Re(rx[1]) Im(ch[1])Im(ch[1])]\n      mmtmpD1 = vmull_s16(dl_ch0_128[1], rxdataF128[1]);\n      //mmtmpD1 = [Re(ch[2])Re(rx[2]) Im(ch[2])Im(ch[2]) Re(ch[3])Re(rx[3]) Im(ch[3])Im(ch[3])]\n      mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0),vget_high_s32(mmtmpD0)),\n                             vpadd_s32(vget_low_s32(mmtmpD1),vget_high_s32(mmtmpD1)));\n      //mmtmpD0 = [Re(ch[0])Re(rx[0])+Im(ch[0])Im(ch[0]) Re(ch[1])Re(rx[1])+Im(ch[1])Im(ch[1]) Re(ch[2])Re(rx[2])+Im(ch[2])Im(ch[2]) Re(ch[3])Re(rx[3])+Im(ch[3])Im(ch[3])]\n      mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[0],*(int16x4_t *)conj)), rxdataF128[0]);\n      //mmtmpD0 = [-Im(ch[0])Re(rx[0]) Re(ch[0])Im(rx[0]) -Im(ch[1])Re(rx[1]) Re(ch[1])Im(rx[1])]\n      mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[1],*(int16x4_t *)conj)), rxdataF128[1]);\n      //mmtmpD0 = [-Im(ch[2])Re(rx[2]) Re(ch[2])Im(rx[2]) -Im(ch[3])Re(rx[3]) Re(ch[3])Im(rx[3])]\n      mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b),vget_high_s32(mmtmpD0b)),\n                             vpadd_s32(vget_low_s32(mmtmpD1b),vget_high_s32(mmtmpD1b)));\n      //mmtmpD1 = [-Im(ch[0])Re(rx[0])+Re(ch[0])Im(rx[0]) -Im(ch[1])Re(rx[1])+Re(ch[1])Im(rx[1]) -Im(ch[2])Re(rx[2])+Re(ch[2])Im(rx[2]) -Im(ch[3])Re(rx[3])+Re(ch[3])Im(rx[3])]\n      mmtmpD0 = vqshlq_s32(mmtmpD0,output_shift128);\n      mmtmpD1 = vqshlq_s32(mmtmpD1,output_shift128);\n      rxdataF_comp128[0] = vcombine_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1));\n      mmtmpD0 = vmull_s16(dl_ch0_128[2], rxdataF128[2]);\n      mmtmpD1 = vmull_s16(dl_ch0_128[3], rxdataF128[3]);\n      mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0),vget_high_s32(mmtmpD0)),\n                             vpadd_s32(vget_low_s32(mmtmpD1),vget_high_s32(mmtmpD1)));\n      mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[2],*(int16x4_t *)conj)), rxdataF128[2]);\n      mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[3],*(int16x4_t *)conj)), rxdataF128[3]);\n      mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b),vget_high_s32(mmtmpD0b)),\n                             vpadd_s32(vget_low_s32(mmtmpD1b),vget_high_s32(mmtmpD1b)));\n      mmtmpD0 = vqshlq_s32(mmtmpD0,output_shift128);\n      mmtmpD1 = vqshlq_s32(mmtmpD1,output_shift128);\n      rxdataF_comp128[1] = vcombine_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1));\n\n      if (pilots==0) {\n        mmtmpD0 = vmull_s16(dl_ch0_128[4], rxdataF128[4]);\n        mmtmpD1 = vmull_s16(dl_ch0_128[5], rxdataF128[5]);\n        mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0),vget_high_s32(mmtmpD0)),\n                               vpadd_s32(vget_low_s32(mmtmpD1),vget_high_s32(mmtmpD1)));\n        mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[4],*(int16x4_t *)conj)), rxdataF128[4]);\n        mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[5],*(int16x4_t *)conj)), rxdataF128[5]);\n        mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b),vget_high_s32(mmtmpD0b)),\n                               vpadd_s32(vget_low_s32(mmtmpD1b),vget_high_s32(mmtmpD1b)));\n        mmtmpD0 = vqshlq_s32(mmtmpD0,output_shift128);\n        mmtmpD1 = vqshlq_s32(mmtmpD1,output_shift128);\n        rxdataF_comp128[2] = vcombine_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1));\n        dl_ch0_128+=6;\n        dl_ch1_128+=6;\n        dl_ch_mag128+=3;\n        dl_ch_mag128b+=3;\n        rxdataF128+=6;\n        rxdataF_comp128+=3;\n      } else { // we have a smaller PDSCH in symbols with pilots so skip last group of 4 REs and increment less\n        dl_ch0_128+=4;\n        dl_ch1_128+=4;\n        dl_ch_mag128+=2;\n        dl_ch_mag128b+=2;\n        rxdataF128+=4;\n        rxdataF_comp128+=2;\n      }\n    }\n\n    Nre = (pilots==0) ? 12 : 8;\n    precoded_signal_strength += ((signal_energy_nodc(&dl_ch_estimates_ext[aarx][symbol*frame_parms->N_RB_DL*Nre],\n                                  (nb_rb*Nre))) - (measurements->n0_power[aarx]));\n    // rx_antennas\n  }\n\n  measurements->precoded_cqi_dB[eNB_id][0] = dB_fixed2(precoded_signal_strength,measurements->n0_power_tot);\n  //printf(\"eNB_id %d, symbol %d: precoded CQI %d dB\\n\",eNB_id,symbol,\n  //     measurements->precoded_cqi_dB[eNB_id][0]);\n#endif\n  _mm_empty();\n  _m_empty();\n}\n\nvoid precode_channel_est(int32_t **dl_ch_estimates_ext,\n                         LTE_DL_FRAME_PARMS *frame_parms,\n                         LTE_UE_PDSCH *pdsch_vars,\n                         unsigned char symbol,\n                         unsigned short nb_rb,\n                         MIMO_mode_t mimo_mode) {\n  unsigned short rb;\n  __m128i *dl_ch0_128,*dl_ch1_128;\n  unsigned char aarx=0,symbol_mod,pilots=0;\n  unsigned char *pmi_ext = pdsch_vars->pmi_ext;\n  symbol_mod = (symbol>=(7-frame_parms->Ncp)) ? symbol-(7-frame_parms->Ncp) : symbol;\n\n  if ((symbol_mod == 0) || (symbol_mod == (4-frame_parms->Ncp)))\n    pilots=1;\n\n  for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) {\n    dl_ch0_128          = (__m128i *)&dl_ch_estimates_ext[aarx][symbol*frame_parms->N_RB_DL*12]; // this is h11\n    dl_ch1_128          = (__m128i *)&dl_ch_estimates_ext[2+aarx][symbol*frame_parms->N_RB_DL*12]; // this is h12\n\n    for (rb=0; rb<nb_rb; rb++) {\n      if (mimo_mode==LARGE_CDD) {\n        prec2A_TM3_128(&dl_ch0_128[0],&dl_ch1_128[0]);\n        prec2A_TM3_128(&dl_ch0_128[1],&dl_ch1_128[1]);\n\n        if (pilots==0) {\n          prec2A_TM3_128(&dl_ch0_128[2],&dl_ch1_128[2]);\n        }\n      } else if (mimo_mode==DUALSTREAM_UNIFORM_PRECODING1) {\n        prec2A_TM4_128(0,&dl_ch0_128[0],&dl_ch1_128[0]);\n        prec2A_TM4_128(0,&dl_ch0_128[1],&dl_ch1_128[1]);\n\n        if (pilots==0) {\n          prec2A_TM4_128(0,&dl_ch0_128[2],&dl_ch1_128[2]);\n        }\n      } else if (mimo_mode==DUALSTREAM_UNIFORM_PRECODINGj) {\n        prec2A_TM4_128(1,&dl_ch0_128[0],&dl_ch1_128[0]);\n        prec2A_TM4_128(1,&dl_ch0_128[1],&dl_ch1_128[1]);\n\n        if (pilots==0) {\n          prec2A_TM4_128(1,&dl_ch0_128[2],&dl_ch1_128[2]);\n        }\n      } else if (mimo_mode==DUALSTREAM_PUSCH_PRECODING) {\n        prec2A_TM4_128(pmi_ext[rb],&dl_ch0_128[0],&dl_ch1_128[0]);\n        prec2A_TM4_128(pmi_ext[rb],&dl_ch0_128[1],&dl_ch1_128[1]);\n\n        if (pilots==0) {\n          prec2A_TM4_128(pmi_ext[rb],&dl_ch0_128[2],&dl_ch1_128[2]);\n        }\n      } else {\n        LOG_E(PHY,\"Unknown MIMO mode\\n\");\n        return;\n      }\n\n      if (pilots==0) {\n        dl_ch0_128+=3;\n        dl_ch1_128+=3;\n      } else {\n        dl_ch0_128+=2;\n        dl_ch1_128+=2;\n      }\n    }\n  }\n}\n\nvoid dlsch_channel_compensation_TM34(LTE_DL_FRAME_PARMS *frame_parms,\n                                     LTE_UE_PDSCH *pdsch_vars,\n                                     PHY_MEASUREMENTS *measurements,\n                                     int eNB_id,\n                                     unsigned char symbol,\n                                     unsigned char mod_order0,\n                                     unsigned char mod_order1,\n                                     int harq_pid,\n                                     int round,\n                                     MIMO_mode_t mimo_mode,\n                                     unsigned short nb_rb,\n                                     unsigned short mmse_flag,\n                                     unsigned char output_shift0,\n                                     unsigned char output_shift1) {\n#if defined(__x86_64__) || defined(__i386__)\n  unsigned short rb,Nre;\n  __m128i *dl_ch0_128,*dl_ch1_128,*dl_ch_mag0_128,*dl_ch_mag1_128,*dl_ch_mag0_128b,*dl_ch_mag1_128b,*rxdataF128,*rxdataF_comp0_128,*rxdataF_comp1_128;\n  unsigned char aarx=0,symbol_mod,pilots=0;\n  int precoded_signal_strength0=0,precoded_signal_strength1=0;\n  int rx_power_correction;\n  int **rxdataF_ext           = pdsch_vars->rxdataF_ext;\n  int **dl_ch_estimates_ext   = pdsch_vars->dl_ch_estimates_ext;\n  int **dl_ch_mag0            = pdsch_vars->dl_ch_mag0;\n  int **dl_ch_mag1            = pdsch_vars->dl_ch_mag1[harq_pid][round];\n  int **dl_ch_magb0           = pdsch_vars->dl_ch_magb0;\n  int **dl_ch_magb1           = pdsch_vars->dl_ch_magb1[harq_pid][round];\n  int **rxdataF_comp0         = pdsch_vars->rxdataF_comp0;\n  int **rxdataF_comp1         = pdsch_vars->rxdataF_comp1[harq_pid][round];\n  unsigned char *pmi_ext      = pdsch_vars->pmi_ext;\n  __m128i mmtmpD0,mmtmpD1,mmtmpD2,mmtmpD3,QAM_amp0_128,QAM_amp1_128;\n  symbol_mod = (symbol>=(7-frame_parms->Ncp)) ? symbol-(7-frame_parms->Ncp) : symbol;\n\n  if ((symbol_mod == 0) || (symbol_mod == (4-frame_parms->Ncp)))\n    pilots=1;\n\n  rx_power_correction = 1;\n  // printf(\"comp prec: symbol %d, pilots %d\\n\",symbol, pilots);\n  __m128i  QAM_amp0_128b = _mm_setzero_si128();\n\n  if (mod_order0 == 4) {\n    QAM_amp0_128  = _mm_set1_epi16(QAM16_n1);\n  } else if (mod_order0 == 6) {\n    QAM_amp0_128  = _mm_set1_epi16(QAM64_n1);\n    QAM_amp0_128b = _mm_set1_epi16(QAM64_n2);\n  }\n\n  __m128i  QAM_amp1_128b = _mm_setzero_si128();\n\n  if (mod_order1 == 4) {\n    QAM_amp1_128  = _mm_set1_epi16(QAM16_n1);\n  } else if (mod_order1 == 6) {\n    QAM_amp1_128  = _mm_set1_epi16(QAM64_n1);\n    QAM_amp1_128b = _mm_set1_epi16(QAM64_n2);\n  }\n\n  for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) {\n    dl_ch0_128          = (__m128i *)&dl_ch_estimates_ext[aarx][symbol*frame_parms->N_RB_DL*12]; // this is h11\n    dl_ch1_128          = (__m128i *)&dl_ch_estimates_ext[2+aarx][symbol*frame_parms->N_RB_DL*12]; // this is h12\n    dl_ch_mag0_128      = (__m128i *)&dl_ch_mag0[aarx][symbol*frame_parms->N_RB_DL*12]; //responsible for x1\n    dl_ch_mag0_128b     = (__m128i *)&dl_ch_magb0[aarx][symbol*frame_parms->N_RB_DL*12];//responsible for x1\n    dl_ch_mag1_128      = (__m128i *)&dl_ch_mag1[aarx][symbol*frame_parms->N_RB_DL*12];   //responsible for x2. always coming from tx2\n    dl_ch_mag1_128b     = (__m128i *)&dl_ch_magb1[aarx][symbol*frame_parms->N_RB_DL*12];  //responsible for x2. always coming from tx2\n    rxdataF128          = (__m128i *)&rxdataF_ext[aarx][symbol*frame_parms->N_RB_DL*12]; //received signal on antenna of interest h11*x1+h12*x2\n    rxdataF_comp0_128   = (__m128i *)&rxdataF_comp0[aarx][symbol*frame_parms->N_RB_DL*12]; //result of multipl with MF x1 on antenna of interest\n    rxdataF_comp1_128   = (__m128i *)&rxdataF_comp1[aarx][symbol*frame_parms->N_RB_DL*12]; //result of multipl with MF x2 on antenna of interest\n\n    for (rb=0; rb<nb_rb; rb++) {\n      if (mmse_flag == 0) {\n        // combine TX channels using precoder from pmi\n        if (mimo_mode==LARGE_CDD) {\n          prec2A_TM3_128(&dl_ch0_128[0],&dl_ch1_128[0]);\n          prec2A_TM3_128(&dl_ch0_128[1],&dl_ch1_128[1]);\n\n          if (pilots==0) {\n            prec2A_TM3_128(&dl_ch0_128[2],&dl_ch1_128[2]);\n          }\n        } else if (mimo_mode==DUALSTREAM_UNIFORM_PRECODING1) {\n          prec2A_TM4_128(0,&dl_ch0_128[0],&dl_ch1_128[0]);\n          prec2A_TM4_128(0,&dl_ch0_128[1],&dl_ch1_128[1]);\n\n          if (pilots==0) {\n            prec2A_TM4_128(0,&dl_ch0_128[2],&dl_ch1_128[2]);\n          }\n        } else if (mimo_mode==DUALSTREAM_UNIFORM_PRECODINGj) {\n          prec2A_TM4_128(1,&dl_ch0_128[0],&dl_ch1_128[0]);\n          prec2A_TM4_128(1,&dl_ch0_128[1],&dl_ch1_128[1]);\n\n          if (pilots==0) {\n            prec2A_TM4_128(1,&dl_ch0_128[2],&dl_ch1_128[2]);\n          }\n        } else if (mimo_mode==DUALSTREAM_PUSCH_PRECODING) {\n          prec2A_TM4_128(pmi_ext[rb],&dl_ch0_128[0],&dl_ch1_128[0]);\n          prec2A_TM4_128(pmi_ext[rb],&dl_ch0_128[1],&dl_ch1_128[1]);\n\n          if (pilots==0) {\n            prec2A_TM4_128(pmi_ext[rb],&dl_ch0_128[2],&dl_ch1_128[2]);\n          }\n        } else {\n          LOG_E(PHY,\"Unknown MIMO mode\\n\");\n          return;\n        }\n      }\n\n      if (mod_order0>2) {\n        // get channel amplitude if not QPSK\n        mmtmpD0 = _mm_madd_epi16(dl_ch0_128[0],dl_ch0_128[0]);\n        mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift0);\n        mmtmpD1 = _mm_madd_epi16(dl_ch0_128[1],dl_ch0_128[1]);\n        mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift0);\n        mmtmpD0 = _mm_packs_epi32(mmtmpD0,mmtmpD1);\n        dl_ch_mag0_128[0] = _mm_unpacklo_epi16(mmtmpD0,mmtmpD0);\n        dl_ch_mag0_128b[0] = dl_ch_mag0_128[0];\n        dl_ch_mag0_128[0] = _mm_mulhi_epi16(dl_ch_mag0_128[0],QAM_amp0_128);\n        dl_ch_mag0_128[0] = _mm_slli_epi16(dl_ch_mag0_128[0],1);\n        //  print_shorts(\"dl_ch_mag0_128[0]=\",&dl_ch_mag0_128[0]);\n        dl_ch_mag0_128[1] = _mm_unpackhi_epi16(mmtmpD0,mmtmpD0);\n        dl_ch_mag0_128b[1] = dl_ch_mag0_128[1];\n        dl_ch_mag0_128[1] = _mm_mulhi_epi16(dl_ch_mag0_128[1],QAM_amp0_128);\n        dl_ch_mag0_128[1] = _mm_slli_epi16(dl_ch_mag0_128[1],1);\n\n        if (pilots==0) {\n          mmtmpD0 = _mm_madd_epi16(dl_ch0_128[2],dl_ch0_128[2]);\n          mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift0);\n          mmtmpD1 = _mm_packs_epi32(mmtmpD0,mmtmpD0);\n          dl_ch_mag0_128[2] = _mm_unpacklo_epi16(mmtmpD1,mmtmpD1);\n          dl_ch_mag0_128b[2] = dl_ch_mag0_128[2];\n          dl_ch_mag0_128[2] = _mm_mulhi_epi16(dl_ch_mag0_128[2],QAM_amp0_128);\n          dl_ch_mag0_128[2] = _mm_slli_epi16(dl_ch_mag0_128[2],1);\n        }\n\n        dl_ch_mag0_128b[0] = _mm_mulhi_epi16(dl_ch_mag0_128b[0],QAM_amp0_128b);\n        dl_ch_mag0_128b[0] = _mm_slli_epi16(dl_ch_mag0_128b[0],1);\n        // print_shorts(\"dl_ch_mag0_128b[0]=\",&dl_ch_mag0_128b[0]);\n        dl_ch_mag0_128b[1] = _mm_mulhi_epi16(dl_ch_mag0_128b[1],QAM_amp0_128b);\n        dl_ch_mag0_128b[1] = _mm_slli_epi16(dl_ch_mag0_128b[1],1);\n\n        if (pilots==0) {\n          dl_ch_mag0_128b[2] = _mm_mulhi_epi16(dl_ch_mag0_128b[2],QAM_amp0_128b);\n          dl_ch_mag0_128b[2] = _mm_slli_epi16(dl_ch_mag0_128b[2],1);\n        }\n      }\n\n      if (mod_order1>2) {\n        // get channel amplitude if not QPSK\n        mmtmpD0 = _mm_madd_epi16(dl_ch1_128[0],dl_ch1_128[0]);\n        mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift1);\n        mmtmpD1 = _mm_madd_epi16(dl_ch1_128[1],dl_ch1_128[1]);\n        mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift1);\n        mmtmpD0 = _mm_packs_epi32(mmtmpD0,mmtmpD1);\n        dl_ch_mag1_128[0] = _mm_unpacklo_epi16(mmtmpD0,mmtmpD0);\n        dl_ch_mag1_128b[0] = dl_ch_mag1_128[0];\n        dl_ch_mag1_128[0] = _mm_mulhi_epi16(dl_ch_mag1_128[0],QAM_amp1_128);\n        dl_ch_mag1_128[0] = _mm_slli_epi16(dl_ch_mag1_128[0],1);\n        // print_shorts(\"dl_ch_mag1_128[0]=\",&dl_ch_mag1_128[0]);\n        dl_ch_mag1_128[1] = _mm_unpackhi_epi16(mmtmpD0,mmtmpD0);\n        dl_ch_mag1_128b[1] = dl_ch_mag1_128[1];\n        dl_ch_mag1_128[1] = _mm_mulhi_epi16(dl_ch_mag1_128[1],QAM_amp1_128);\n        dl_ch_mag1_128[1] = _mm_slli_epi16(dl_ch_mag1_128[1],1);\n\n        if (pilots==0) {\n          mmtmpD0 = _mm_madd_epi16(dl_ch1_128[2],dl_ch1_128[2]);\n          mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift1);\n          mmtmpD1 = _mm_packs_epi32(mmtmpD0,mmtmpD0);\n          dl_ch_mag1_128[2] = _mm_unpacklo_epi16(mmtmpD1,mmtmpD1);\n          dl_ch_mag1_128b[2] = dl_ch_mag1_128[2];\n          dl_ch_mag1_128[2] = _mm_mulhi_epi16(dl_ch_mag1_128[2],QAM_amp1_128);\n          dl_ch_mag1_128[2] = _mm_slli_epi16(dl_ch_mag1_128[2],1);\n        }\n\n        dl_ch_mag1_128b[0] = _mm_mulhi_epi16(dl_ch_mag1_128b[0],QAM_amp1_128b);\n        dl_ch_mag1_128b[0] = _mm_slli_epi16(dl_ch_mag1_128b[0],1);\n        // print_shorts(\"dl_ch_mag1_128b[0]=\",&dl_ch_mag1_128b[0]);\n        dl_ch_mag1_128b[1] = _mm_mulhi_epi16(dl_ch_mag1_128b[1],QAM_amp1_128b);\n        dl_ch_mag1_128b[1] = _mm_slli_epi16(dl_ch_mag1_128b[1],1);\n\n        if (pilots==0) {\n          dl_ch_mag1_128b[2] = _mm_mulhi_epi16(dl_ch_mag1_128b[2],QAM_amp1_128b);\n          dl_ch_mag1_128b[2] = _mm_slli_epi16(dl_ch_mag1_128b[2],1);\n        }\n      }\n\n      // layer 0\n      // MF multiply by conjugated channel\n      mmtmpD0 = _mm_madd_epi16(dl_ch0_128[0],rxdataF128[0]);\n      //  print_ints(\"re\",&mmtmpD0);\n      // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n      mmtmpD1 = _mm_shufflelo_epi16(dl_ch0_128[0],_MM_SHUFFLE(2,3,0,1));\n      mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1));\n      mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)&conjugate[0]);\n      mmtmpD1 = _mm_madd_epi16(mmtmpD1,rxdataF128[0]);\n      // print_ints(\"im\",&mmtmpD1);\n      // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n      mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift0);\n      // printf(\"Shift: %d\\n\",output_shift);\n      // print_ints(\"re(shift)\",&mmtmpD0);\n      mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift0);\n      // print_ints(\"im(shift)\",&mmtmpD1);\n      mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1);\n      mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1);\n      //  print_ints(\"c0\",&mmtmpD2);\n      // print_ints(\"c1\",&mmtmpD3);\n      rxdataF_comp0_128[0] = _mm_packs_epi32(mmtmpD2,mmtmpD3);\n      // print_shorts(\"rx:\",rxdataF128);\n      // print_shorts(\"ch:\",dl_ch0_128);\n      //print_shorts(\"pack:\",rxdataF_comp0_128);\n      // multiply by conjugated channel\n      mmtmpD0 = _mm_madd_epi16(dl_ch0_128[1],rxdataF128[1]);\n      // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n      mmtmpD1 = _mm_shufflelo_epi16(dl_ch0_128[1],_MM_SHUFFLE(2,3,0,1));\n      mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1));\n      mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)conjugate);\n      mmtmpD1 = _mm_madd_epi16(mmtmpD1,rxdataF128[1]);\n      // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n      mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift0);\n      mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift0);\n      mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1);\n      mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1);\n      rxdataF_comp0_128[1] = _mm_packs_epi32(mmtmpD2,mmtmpD3);\n      //  print_shorts(\"rx:\",rxdataF128+1);\n      //  print_shorts(\"ch:\",dl_ch0_128+1);\n      // print_shorts(\"pack:\",rxdataF_comp0_128+1);\n\n      if (pilots==0) {\n        // multiply by conjugated channel\n        mmtmpD0 = _mm_madd_epi16(dl_ch0_128[2],rxdataF128[2]);\n        // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n        mmtmpD1 = _mm_shufflelo_epi16(dl_ch0_128[2],_MM_SHUFFLE(2,3,0,1));\n        mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1));\n        mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)conjugate);\n        mmtmpD1 = _mm_madd_epi16(mmtmpD1,rxdataF128[2]);\n        // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n        mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift0);\n        mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift0);\n        mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1);\n        mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1);\n        rxdataF_comp0_128[2] = _mm_packs_epi32(mmtmpD2,mmtmpD3);\n        //   print_shorts(\"rx:\",rxdataF128+2);\n        //   print_shorts(\"ch:\",dl_ch0_128+2);\n        //  print_shorts(\"pack:\",rxdataF_comp0_128+2);\n      }\n\n      // layer 1\n      // MF multiply by conjugated channel\n      mmtmpD0 = _mm_madd_epi16(dl_ch1_128[0],rxdataF128[0]);\n      //  print_ints(\"re\",&mmtmpD0);\n      // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n      mmtmpD1 = _mm_shufflelo_epi16(dl_ch1_128[0],_MM_SHUFFLE(2,3,0,1));\n      mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1));\n      mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)&conjugate[0]);\n      //  print_ints(\"im\",&mmtmpD1);\n      mmtmpD1 = _mm_madd_epi16(mmtmpD1,rxdataF128[0]);\n      // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n      mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift1);\n      // print_ints(\"re(shift)\",&mmtmpD0);\n      mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift1);\n      // print_ints(\"im(shift)\",&mmtmpD1);\n      mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1);\n      mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1);\n      // print_ints(\"c0\",&mmtmpD2);\n      // print_ints(\"c1\",&mmtmpD3);\n      rxdataF_comp1_128[0] = _mm_packs_epi32(mmtmpD2,mmtmpD3);\n      // print_shorts(\"rx:\",rxdataF128);\n      //  print_shorts(\"ch:\",dl_ch1_128);\n      // print_shorts(\"pack:\",rxdataF_comp1_128);\n      // multiply by conjugated channel\n      mmtmpD0 = _mm_madd_epi16(dl_ch1_128[1],rxdataF128[1]);\n      // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n      mmtmpD1 = _mm_shufflelo_epi16(dl_ch1_128[1],_MM_SHUFFLE(2,3,0,1));\n      mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1));\n      mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)conjugate);\n      mmtmpD1 = _mm_madd_epi16(mmtmpD1,rxdataF128[1]);\n      // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n      mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift1);\n      mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift1);\n      mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1);\n      mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1);\n      rxdataF_comp1_128[1] = _mm_packs_epi32(mmtmpD2,mmtmpD3);\n      //  print_shorts(\"rx:\",rxdataF128+1);\n      // print_shorts(\"ch:\",dl_ch1_128+1);\n      // print_shorts(\"pack:\",rxdataF_comp1_128+1);\n\n      if (pilots==0) {\n        // multiply by conjugated channel\n        mmtmpD0 = _mm_madd_epi16(dl_ch1_128[2],rxdataF128[2]);\n        // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n        mmtmpD1 = _mm_shufflelo_epi16(dl_ch1_128[2],_MM_SHUFFLE(2,3,0,1));\n        mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1));\n        mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)conjugate);\n        mmtmpD1 = _mm_madd_epi16(mmtmpD1,rxdataF128[2]);\n        // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n        mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift1);\n        mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift1);\n        mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1);\n        mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1);\n        rxdataF_comp1_128[2] = _mm_packs_epi32(mmtmpD2,mmtmpD3);\n        //   print_shorts(\"rx:\",rxdataF128+2);\n        //  print_shorts(\"ch:\",dl_ch1_128+2);\n        //         print_shorts(\"pack:\",rxdataF_comp1_128+2);\n        dl_ch0_128+=3;\n        dl_ch1_128+=3;\n        dl_ch_mag0_128+=3;\n        dl_ch_mag1_128+=3;\n        dl_ch_mag0_128b+=3;\n        dl_ch_mag1_128b+=3;\n        rxdataF128+=3;\n        rxdataF_comp0_128+=3;\n        rxdataF_comp1_128+=3;\n      } else {\n        dl_ch0_128+=2;\n        dl_ch1_128+=2;\n        dl_ch_mag0_128+=2;\n        dl_ch_mag1_128+=2;\n        dl_ch_mag0_128b+=2;\n        dl_ch_mag1_128b+=2;\n        rxdataF128+=2;\n        rxdataF_comp0_128+=2;\n        rxdataF_comp1_128+=2;\n      }\n    } // rb loop\n\n    Nre = (pilots==0) ? 12 : 8;\n    precoded_signal_strength0 += ((signal_energy_nodc(&dl_ch_estimates_ext[aarx][symbol*frame_parms->N_RB_DL*Nre],\n                                   (nb_rb*Nre))*rx_power_correction) - (measurements->n0_power[aarx]));\n    precoded_signal_strength1 += ((signal_energy_nodc(&dl_ch_estimates_ext[aarx+2][symbol*frame_parms->N_RB_DL*Nre],\n                                   (nb_rb*Nre))*rx_power_correction) - (measurements->n0_power[aarx]));\n  } // rx_antennas\n\n  measurements->precoded_cqi_dB[eNB_id][0] = dB_fixed2(precoded_signal_strength0,measurements->n0_power_tot);\n  measurements->precoded_cqi_dB[eNB_id][1] = dB_fixed2(precoded_signal_strength1,measurements->n0_power_tot);\n  // printf(\"eNB_id %d, symbol %d: precoded CQI %d dB\\n\",eNB_id,symbol,\n  //  measurements->precoded_cqi_dB[eNB_id][0]);\n  _mm_empty();\n  _m_empty();\n#elif defined(__arm__)\n  unsigned short rb,Nre;\n  unsigned char aarx,symbol_mod,pilots=0;\n  int precoded_signal_strength0=0,precoded_signal_strength1=0, rx_power_correction;\n  int16x4_t *dl_ch0_128,*rxdataF128;\n  int16x4_t *dl_ch1_128;\n  int16x8_t *dl_ch0_128b,*dl_ch1_128b;\n  int32x4_t mmtmpD0,mmtmpD1,mmtmpD0b,mmtmpD1b;\n  int16x8_t *dl_ch_mag0_128,*dl_ch_mag0_128b,*dl_ch_mag1_128,*dl_ch_mag1_128b,mmtmpD2,mmtmpD3,mmtmpD4,*rxdataF_comp0_128,*rxdataF_comp1_128;\n  int16x8_t QAM_amp0_128,QAM_amp0_128b,QAM_amp1_128,QAM_amp1_128b;\n  int32x4_t output_shift128 = vmovq_n_s32(-(int32_t)output_shift);\n  int **rxdataF_ext           = pdsch_vars->rxdataF_ext;\n  int **dl_ch_estimates_ext   = pdsch_vars->dl_ch_estimates_ext;\n  int **dl_ch_mag0            = pdsch_vars->dl_ch_mag0;\n  int **dl_ch_mag1            = pdsch_vars->dl_ch_mag1[harq_pid][round];\n  int **dl_ch_magb0           = pdsch_vars->dl_ch_magb0;\n  int **dl_ch_magb1           = pdsch_vars->dl_ch_magb1[harq_pid][round];\n  int **rxdataF_comp0         = pdsch_vars->rxdataF_comp0;\n  int **rxdataF_comp1         = pdsch_vars->rxdataF_comp1[harq_pid][round];\n  int16_t conj[4]__attribute__((aligned(16))) = {1,-1,1,-1};\n  symbol_mod = (symbol>=(7-frame_parms->Ncp)) ? symbol-(7-frame_parms->Ncp) : symbol;\n\n  if ((symbol_mod == 0) || (symbol_mod == (4-frame_parms->Ncp))) {\n    if (frame_parms->nb_antenna_ports_eNB==1) { // 10 out of 12 so don't reduce size\n      nb_rb=1+(5*nb_rb/6);\n    } else {\n      pilots=1;\n    }\n  }\n\n  rx_power_correction=1;\n\n  if (mod_order0 == 4) {\n    QAM_amp0_128  = vmovq_n_s16(QAM16_n1);  // 2/sqrt(10)\n    QAM_amp0_128b = vmovq_n_s16(0);\n  } else if (mod_order0 == 6) {\n    QAM_amp0_128  = vmovq_n_s16(QAM64_n1); //\n    QAM_amp0_128b = vmovq_n_s16(QAM64_n2);\n  }\n\n  if (mod_order1 == 4) {\n    QAM_amp1_128  = vmovq_n_s16(QAM16_n1);  // 2/sqrt(10)\n    QAM_amp1_128b = vmovq_n_s16(0);\n  } else if (mod_order1 == 6) {\n    QAM_amp1_128  = vmovq_n_s16(QAM64_n1); //\n    QAM_amp1_128b = vmovq_n_s16(QAM64_n2);\n  }\n\n  //    printf(\"comp: rxdataF_comp %p, symbol %d\\n\",rxdataF_comp[0],symbol);\n\n  for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) {\n    dl_ch0_128          = (int16x4_t *)&dl_ch_estimates_ext[aarx][symbol*frame_parms->N_RB_DL*12];\n    dl_ch1_128          = (int16x4_t *)&dl_ch_estimates_ext[2+aarx][symbol*frame_parms->N_RB_DL*12];\n    dl_ch0_128b          = (int16x8_t *)&dl_ch_estimates_ext[aarx][symbol*frame_parms->N_RB_DL*12];\n    dl_ch1_128b          = (int16x8_t *)&dl_ch_estimates_ext[2+aarx][symbol*frame_parms->N_RB_DL*12];\n    dl_ch_mag0_128      = (int16x8_t *)&dl_ch_mag0[aarx][symbol*frame_parms->N_RB_DL*12];\n    dl_ch_mag0_128b     = (int16x8_t *)&dl_ch_magb0[aarx][symbol*frame_parms->N_RB_DL*12];\n    dl_ch_mag1_128      = (int16x8_t *)&dl_ch_mag1[aarx][symbol*frame_parms->N_RB_DL*12];\n    dl_ch_mag1_128b     = (int16x8_t *)&dl_ch_magb1[aarx][symbol*frame_parms->N_RB_DL*12];\n    rxdataF128          = (int16x4_t *)&rxdataF_ext[aarx][symbol*frame_parms->N_RB_DL*12];\n    rxdataF_comp0_128   = (int16x8_t *)&rxdataF_comp0[aarx][symbol*frame_parms->N_RB_DL*12];\n    rxdataF_comp1_128   = (int16x8_t *)&rxdataF_comp1[aarx][symbol*frame_parms->N_RB_DL*12];\n\n    for (rb=0; rb<nb_rb; rb++) {\n      if (mmse_flag == 0) {\n        // combine TX channels using precoder from pmi\n        if (mimo_mode==LARGE_CDD) {\n          prec2A_TM3_128(&dl_ch0_128[0],&dl_ch1_128[0]);\n          prec2A_TM3_128(&dl_ch0_128[1],&dl_ch1_128[1]);\n\n          if (pilots==0) {\n            prec2A_TM3_128(&dl_ch0_128[2],&dl_ch1_128[2]);\n          }\n        } else if (mimo_mode==DUALSTREAM_UNIFORM_PRECODING1) {\n          prec2A_TM4_128(0,&dl_ch0_128[0],&dl_ch1_128[0]);\n          prec2A_TM4_128(0,&dl_ch0_128[1],&dl_ch1_128[1]);\n\n          if (pilots==0) {\n            prec2A_TM4_128(0,&dl_ch0_128[2],&dl_ch1_128[2]);\n          }\n        } else if (mimo_mode==DUALSTREAM_UNIFORM_PRECODINGj) {\n          prec2A_TM4_128(1,&dl_ch0_128[0],&dl_ch1_128[0]);\n          prec2A_TM4_128(1,&dl_ch0_128[1],&dl_ch1_128[1]);\n\n          if (pilots==0) {\n            prec2A_TM4_128(1,&dl_ch0_128[2],&dl_ch1_128[2]);\n          }\n        } else {\n          LOG_E(PHY,\"Unknown MIMO mode\\n\");\n          return;\n        }\n      }\n\n      if (mod_order0>2) {\n        // get channel amplitude if not QPSK\n        mmtmpD0 = vmull_s16(dl_ch0_128[0], dl_ch0_128[0]);\n        // mmtmpD0 = [ch0*ch0,ch1*ch1,ch2*ch2,ch3*ch3];\n        mmtmpD0 = vqshlq_s32(vqaddq_s32(mmtmpD0,vrev64q_s32(mmtmpD0)),output_shift128);\n        // mmtmpD0 = [ch0*ch0 + ch1*ch1,ch0*ch0 + ch1*ch1,ch2*ch2 + ch3*ch3,ch2*ch2 + ch3*ch3]>>output_shift128 on 32-bits\n        mmtmpD1 = vmull_s16(dl_ch0_128[1], dl_ch0_128[1]);\n        mmtmpD1 = vqshlq_s32(vqaddq_s32(mmtmpD1,vrev64q_s32(mmtmpD1)),output_shift128);\n        mmtmpD2 = vcombine_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1));\n        // mmtmpD2 = [ch0*ch0 + ch1*ch1,ch0*ch0 + ch1*ch1,ch2*ch2 + ch3*ch3,ch2*ch2 + ch3*ch3,ch4*ch4 + ch5*ch5,ch4*ch4 + ch5*ch5,ch6*ch6 + ch7*ch7,ch6*ch6 + ch7*ch7]>>output_shift128 on 16-bits\n        mmtmpD0 = vmull_s16(dl_ch0_128[2], dl_ch0_128[2]);\n        mmtmpD0 = vqshlq_s32(vqaddq_s32(mmtmpD0,vrev64q_s32(mmtmpD0)),output_shift128);\n        mmtmpD1 = vmull_s16(dl_ch0_128[3], dl_ch0_128[3]);\n        mmtmpD1 = vqshlq_s32(vqaddq_s32(mmtmpD1,vrev64q_s32(mmtmpD1)),output_shift128);\n        mmtmpD3 = vcombine_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1));\n\n        if (pilots==0) {\n          mmtmpD0 = vmull_s16(dl_ch0_128[4], dl_ch0_128[4]);\n          mmtmpD0 = vqshlq_s32(vqaddq_s32(mmtmpD0,vrev64q_s32(mmtmpD0)),output_shift128);\n          mmtmpD1 = vmull_s16(dl_ch0_128[5], dl_ch0_128[5]);\n          mmtmpD1 = vqshlq_s32(vqaddq_s32(mmtmpD1,vrev64q_s32(mmtmpD1)),output_shift128);\n          mmtmpD4 = vcombine_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1));\n        }\n\n        dl_ch_mag0_128b[0] = vqdmulhq_s16(mmtmpD2,QAM_amp0_128b);\n        dl_ch_mag0_128b[1] = vqdmulhq_s16(mmtmpD3,QAM_amp0_128b);\n        dl_ch_mag0_128[0] = vqdmulhq_s16(mmtmpD2,QAM_amp0_128);\n        dl_ch_mag0_128[1] = vqdmulhq_s16(mmtmpD3,QAM_amp0_128);\n\n        if (pilots==0) {\n          dl_ch_mag0_128b[2] = vqdmulhq_s16(mmtmpD4,QAM_amp0_128b);\n          dl_ch_mag0_128[2]  = vqdmulhq_s16(mmtmpD4,QAM_amp0_128);\n        }\n      }\n\n      if (mod_order1>2) {\n        // get channel amplitude if not QPSK\n        mmtmpD0 = vmull_s16(dl_ch1_128[0], dl_ch1_128[0]);\n        // mmtmpD0 = [ch0*ch0,ch1*ch1,ch2*ch2,ch3*ch3];\n        mmtmpD0 = vqshlq_s32(vqaddq_s32(mmtmpD0,vrev64q_s32(mmtmpD0)),output_shift128);\n        // mmtmpD0 = [ch0*ch0 + ch1*ch1,ch0*ch0 + ch1*ch1,ch2*ch2 + ch3*ch3,ch2*ch2 + ch3*ch3]>>output_shift128 on 32-bits\n        mmtmpD1 = vmull_s16(dl_ch1_128[1], dl_ch1_128[1]);\n        mmtmpD1 = vqshlq_s32(vqaddq_s32(mmtmpD1,vrev64q_s32(mmtmpD1)),output_shift128);\n        mmtmpD2 = vcombine_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1));\n        // mmtmpD2 = [ch0*ch0 + ch1*ch1,ch0*ch0 + ch1*ch1,ch2*ch2 + ch3*ch3,ch2*ch2 + ch3*ch3,ch4*ch4 + ch5*ch5,ch4*ch4 + ch5*ch5,ch6*ch6 + ch7*ch7,ch6*ch6 + ch7*ch7]>>output_shift128 on 16-bits\n        mmtmpD0 = vmull_s16(dl_ch1_128[2], dl_ch1_128[2]);\n        mmtmpD0 = vqshlq_s32(vqaddq_s32(mmtmpD0,vrev64q_s32(mmtmpD0)),output_shift128);\n        mmtmpD1 = vmull_s16(dl_ch1_128[3], dl_ch1_128[3]);\n        mmtmpD1 = vqshlq_s32(vqaddq_s32(mmtmpD1,vrev64q_s32(mmtmpD1)),output_shift128);\n        mmtmpD3 = vcombine_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1));\n\n        if (pilots==0) {\n          mmtmpD0 = vmull_s16(dl_ch1_128[4], dl_ch1_128[4]);\n          mmtmpD0 = vqshlq_s32(vqaddq_s32(mmtmpD0,vrev64q_s32(mmtmpD0)),output_shift128);\n          mmtmpD1 = vmull_s16(dl_ch1_128[5], dl_ch1_128[5]);\n          mmtmpD1 = vqshlq_s32(vqaddq_s32(mmtmpD1,vrev64q_s32(mmtmpD1)),output_shift128);\n          mmtmpD4 = vcombine_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1));\n        }\n\n        dl_ch_mag1_128b[0] = vqdmulhq_s16(mmtmpD2,QAM_amp1_128b);\n        dl_ch_mag1_128b[1] = vqdmulhq_s16(mmtmpD3,QAM_amp1_128b);\n        dl_ch_mag1_128[0] = vqdmulhq_s16(mmtmpD2,QAM_amp1_128);\n        dl_ch_mag1_128[1] = vqdmulhq_s16(mmtmpD3,QAM_amp1_128);\n\n        if (pilots==0) {\n          dl_ch_mag1_128b[2] = vqdmulhq_s16(mmtmpD4,QAM_amp1_128b);\n          dl_ch_mag1_128[2]  = vqdmulhq_s16(mmtmpD4,QAM_amp1_128);\n        }\n      }\n\n      mmtmpD0 = vmull_s16(dl_ch0_128[0], rxdataF128[0]);\n      //mmtmpD0 = [Re(ch[0])Re(rx[0]) Im(ch[0])Im(ch[0]) Re(ch[1])Re(rx[1]) Im(ch[1])Im(ch[1])]\n      mmtmpD1 = vmull_s16(dl_ch0_128[1], rxdataF128[1]);\n      //mmtmpD1 = [Re(ch[2])Re(rx[2]) Im(ch[2])Im(ch[2]) Re(ch[3])Re(rx[3]) Im(ch[3])Im(ch[3])]\n      mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0),vget_high_s32(mmtmpD0)),\n                             vpadd_s32(vget_low_s32(mmtmpD1),vget_high_s32(mmtmpD1)));\n      //mmtmpD0 = [Re(ch[0])Re(rx[0])+Im(ch[0])Im(ch[0]) Re(ch[1])Re(rx[1])+Im(ch[1])Im(ch[1]) Re(ch[2])Re(rx[2])+Im(ch[2])Im(ch[2]) Re(ch[3])Re(rx[3])+Im(ch[3])Im(ch[3])]\n      mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[0],*(int16x4_t *)conj)), rxdataF128[0]);\n      //mmtmpD0 = [-Im(ch[0])Re(rx[0]) Re(ch[0])Im(rx[0]) -Im(ch[1])Re(rx[1]) Re(ch[1])Im(rx[1])]\n      mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[1],*(int16x4_t *)conj)), rxdataF128[1]);\n      //mmtmpD0 = [-Im(ch[2])Re(rx[2]) Re(ch[2])Im(rx[2]) -Im(ch[3])Re(rx[3]) Re(ch[3])Im(rx[3])]\n      mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b),vget_high_s32(mmtmpD0b)),\n                             vpadd_s32(vget_low_s32(mmtmpD1b),vget_high_s32(mmtmpD1b)));\n      //mmtmpD1 = [-Im(ch[0])Re(rx[0])+Re(ch[0])Im(rx[0]) -Im(ch[1])Re(rx[1])+Re(ch[1])Im(rx[1]) -Im(ch[2])Re(rx[2])+Re(ch[2])Im(rx[2]) -Im(ch[3])Re(rx[3])+Re(ch[3])Im(rx[3])]\n      mmtmpD0 = vqshlq_s32(mmtmpD0,output_shift128);\n      mmtmpD1 = vqshlq_s32(mmtmpD1,output_shift128);\n      rxdataF_comp0_128[0] = vcombine_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1));\n      mmtmpD0 = vmull_s16(dl_ch0_128[2], rxdataF128[2]);\n      mmtmpD1 = vmull_s16(dl_ch0_128[3], rxdataF128[3]);\n      mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0),vget_high_s32(mmtmpD0)),\n                             vpadd_s32(vget_low_s32(mmtmpD1),vget_high_s32(mmtmpD1)));\n      mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[2],*(int16x4_t *)conj)), rxdataF128[2]);\n      mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[3],*(int16x4_t *)conj)), rxdataF128[3]);\n      mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b),vget_high_s32(mmtmpD0b)),\n                             vpadd_s32(vget_low_s32(mmtmpD1b),vget_high_s32(mmtmpD1b)));\n      mmtmpD0 = vqshlq_s32(mmtmpD0,output_shift128);\n      mmtmpD1 = vqshlq_s32(mmtmpD1,output_shift128);\n      rxdataF_comp0_128[1] = vcombine_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1));\n      // second stream\n      mmtmpD0 = vmull_s16(dl_ch1_128[0], rxdataF128[0]);\n      mmtmpD1 = vmull_s16(dl_ch1_128[1], rxdataF128[1]);\n      mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0),vget_high_s32(mmtmpD0)),\n                             vpadd_s32(vget_low_s32(mmtmpD1),vget_high_s32(mmtmpD1)));\n      mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[0],*(int16x4_t *)conj)), rxdataF128[0]);\n      mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[1],*(int16x4_t *)conj)), rxdataF128[1]);\n      //mmtmpD0 = [-Im(ch[2])Re(rx[2]) Re(ch[2])Im(rx[2]) -Im(ch[3])Re(rx[3]) Re(ch[3])Im(rx[3])]\n      mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b),vget_high_s32(mmtmpD0b)),\n                             vpadd_s32(vget_low_s32(mmtmpD1b),vget_high_s32(mmtmpD1b)));\n      //mmtmpD1 = [-Im(ch[0])Re(rx[0])+Re(ch[0])Im(rx[0]) -Im(ch[1])Re(rx[1])+Re(ch[1])Im(rx[1]) -Im(ch[2])Re(rx[2])+Re(ch[2])Im(rx[2]) -Im(ch[3])Re(rx[3])+Re(ch[3])Im(rx[3])]\n      mmtmpD0 = vqshlq_s32(mmtmpD0,output_shift128);\n      mmtmpD1 = vqshlq_s32(mmtmpD1,output_shift128);\n      rxdataF_comp1_128[0] = vcombine_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1));\n      mmtmpD0 = vmull_s16(dl_ch1_128[2], rxdataF128[2]);\n      mmtmpD1 = vmull_s16(dl_ch1_128[3], rxdataF128[3]);\n      mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0),vget_high_s32(mmtmpD0)),\n                             vpadd_s32(vget_low_s32(mmtmpD1),vget_high_s32(mmtmpD1)));\n      mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[2],*(int16x4_t *)conj)), rxdataF128[2]);\n      mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[3],*(int16x4_t *)conj)), rxdataF128[3]);\n      mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b),vget_high_s32(mmtmpD0b)),\n                             vpadd_s32(vget_low_s32(mmtmpD1b),vget_high_s32(mmtmpD1b)));\n      mmtmpD0 = vqshlq_s32(mmtmpD0,output_shift128);\n      mmtmpD1 = vqshlq_s32(mmtmpD1,output_shift128);\n      rxdataF_comp1_128[1] = vcombine_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1));\n\n      if (pilots==0) {\n        mmtmpD0 = vmull_s16(dl_ch0_128[4], rxdataF128[4]);\n        mmtmpD1 = vmull_s16(dl_ch0_128[5], rxdataF128[5]);\n        mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0),vget_high_s32(mmtmpD0)),\n                               vpadd_s32(vget_low_s32(mmtmpD1),vget_high_s32(mmtmpD1)));\n        mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[4],*(int16x4_t *)conj)), rxdataF128[4]);\n        mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[5],*(int16x4_t *)conj)), rxdataF128[5]);\n        mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b),vget_high_s32(mmtmpD0b)),\n                               vpadd_s32(vget_low_s32(mmtmpD1b),vget_high_s32(mmtmpD1b)));\n        mmtmpD0 = vqshlq_s32(mmtmpD0,output_shift128);\n        mmtmpD1 = vqshlq_s32(mmtmpD1,output_shift128);\n        rxdataF_comp0_128[2] = vcombine_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1));\n        mmtmpD0 = vmull_s16(dl_ch1_128[4], rxdataF128[4]);\n        mmtmpD1 = vmull_s16(dl_ch1_128[5], rxdataF128[5]);\n        mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0),vget_high_s32(mmtmpD0)),\n                               vpadd_s32(vget_low_s32(mmtmpD1),vget_high_s32(mmtmpD1)));\n        mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch1_128[4],*(int16x4_t *)conj)), rxdataF128[4]);\n        mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch1_128[5],*(int16x4_t *)conj)), rxdataF128[5]);\n        mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b),vget_high_s32(mmtmpD0b)),\n                               vpadd_s32(vget_low_s32(mmtmpD1b),vget_high_s32(mmtmpD1b)));\n        mmtmpD0 = vqshlq_s32(mmtmpD0,output_shift128);\n        mmtmpD1 = vqshlq_s32(mmtmpD1,output_shift128);\n        rxdataF_comp1_128[2] = vcombine_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1));\n      }\n    }\n\n    Nre = (pilots==0) ? 12 : 8;\n    // rx_antennas\n  }\n\n  Nre = (pilots==0) ? 12 : 8;\n  precoded_signal_strength0 += ((signal_energy_nodc(&dl_ch_estimates_ext[aarx][symbol*frame_parms->N_RB_DL*Nre],\n                                 (nb_rb*Nre))*rx_power_correction) - (measurements->n0_power[aarx]));\n  precoded_signal_strength1 += ((signal_energy_nodc(&dl_ch_estimates_ext[aarx+2][symbol*frame_parms->N_RB_DL*Nre],\n                                 (nb_rb*Nre))*rx_power_correction) - (measurements->n0_power[aarx]));\n  measurements->precoded_cqi_dB[eNB_id][0] = dB_fixed2(precoded_signal_strength0,measurements->n0_power_tot);\n  measurements->precoded_cqi_dB[eNB_id][1] = dB_fixed2(precoded_signal_strength1,measurements->n0_power_tot);\n#endif\n}\n\n\nvoid dlsch_dual_stream_correlation(LTE_DL_FRAME_PARMS *frame_parms,\n                                   unsigned char symbol,\n                                   unsigned short nb_rb,\n                                   int **dl_ch_estimates_ext,\n                                   int **dl_ch_estimates_ext_i,\n                                   int **dl_ch_rho_ext,\n                                   unsigned char output_shift) {\n#if defined(__x86_64__)||defined(__i386__)\n  unsigned short rb;\n  __m128i *dl_ch128,*dl_ch128i,*dl_ch_rho128,mmtmpD0,mmtmpD1,mmtmpD2,mmtmpD3;\n  unsigned char aarx,symbol_mod,pilots=0;\n  //    printf(\"dlsch_dual_stream_correlation: symbol %d\\n\",symbol);\n  symbol_mod = (symbol>=(7-frame_parms->Ncp)) ? symbol-(7-frame_parms->Ncp) : symbol;\n\n  if ((symbol_mod == 0) || (symbol_mod == (4-frame_parms->Ncp))) {\n    pilots=1;\n  }\n\n  //  printf(\"Dual stream correlation (%p)\\n\",dl_ch_estimates_ext_i);\n\n  for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) {\n    dl_ch128          = (__m128i *)&dl_ch_estimates_ext[aarx][symbol*frame_parms->N_RB_DL*12];\n\n    if (dl_ch_estimates_ext_i == NULL) // TM3/4\n      dl_ch128i         = (__m128i *)&dl_ch_estimates_ext[aarx + frame_parms->nb_antennas_rx][symbol*frame_parms->N_RB_DL*12];\n    else\n      dl_ch128i         = (__m128i *)&dl_ch_estimates_ext_i[aarx][symbol*frame_parms->N_RB_DL*12];\n\n    dl_ch_rho128      = (__m128i *)&dl_ch_rho_ext[aarx][symbol*frame_parms->N_RB_DL*12];\n\n    for (rb=0; rb<nb_rb; rb++) {\n      // multiply by conjugated channel\n      mmtmpD0 = _mm_madd_epi16(dl_ch128[0],dl_ch128i[0]);\n      //      print_ints(\"re\",&mmtmpD0);\n      // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n      mmtmpD1 = _mm_shufflelo_epi16(dl_ch128[0],_MM_SHUFFLE(2,3,0,1));\n      mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1));\n      mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)&conjugate[0]);\n      mmtmpD1 = _mm_madd_epi16(mmtmpD1,dl_ch128i[0]);\n      //      print_ints(\"im\",&mmtmpD1);\n      // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n      mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift);\n      //      print_ints(\"re(shift)\",&mmtmpD0);\n      mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift);\n      //      print_ints(\"im(shift)\",&mmtmpD1);\n      mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1);\n      mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1);\n      //      print_ints(\"c0\",&mmtmpD2);\n      //      print_ints(\"c1\",&mmtmpD3);\n      dl_ch_rho128[0] = _mm_packs_epi32(mmtmpD2,mmtmpD3);\n      // print_shorts(\"rho 0:\",dl_ch_rho128);\n      // multiply by conjugated channel\n      mmtmpD0 = _mm_madd_epi16(dl_ch128[1],dl_ch128i[1]);\n      // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n      mmtmpD1 = _mm_shufflelo_epi16(dl_ch128[1],_MM_SHUFFLE(2,3,0,1));\n      mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1));\n      mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)conjugate);\n      mmtmpD1 = _mm_madd_epi16(mmtmpD1,dl_ch128i[1]);\n      // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n      mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift);\n      mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift);\n      mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1);\n      mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1);\n      dl_ch_rho128[1] =_mm_packs_epi32(mmtmpD2,mmtmpD3);\n\n      if (pilots==0) {\n        // multiply by conjugated channel\n        mmtmpD0 = _mm_madd_epi16(dl_ch128[2],dl_ch128i[2]);\n        // mmtmpD0 contains real part of 4 consecutive outputs (32-bit)\n        mmtmpD1 = _mm_shufflelo_epi16(dl_ch128[2],_MM_SHUFFLE(2,3,0,1));\n        mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1));\n        mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)conjugate);\n        mmtmpD1 = _mm_madd_epi16(mmtmpD1,dl_ch128i[2]);\n        // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit)\n        mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift);\n        mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift);\n        mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1);\n        mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1);\n        dl_ch_rho128[2] = _mm_packs_epi32(mmtmpD2,mmtmpD3);\n        dl_ch128+=3;\n        dl_ch128i+=3;\n        dl_ch_rho128+=3;\n      } else {\n        dl_ch128+=2;\n        dl_ch128i+=2;\n        dl_ch_rho128+=2;\n      }\n    }\n  }\n\n  _mm_empty();\n  _m_empty();\n#elif defined(__arm__)\n#endif\n}\n\n\nvoid dlsch_detection_mrc(LTE_DL_FRAME_PARMS *frame_parms,\n                         int **rxdataF_comp,\n                         int **rxdataF_comp_i,\n                         int **rho,\n                         int **rho_i,\n                         int **dl_ch_mag,\n                         int **dl_ch_magb,\n                         int **dl_ch_mag_i,\n                         int **dl_ch_magb_i,\n                         unsigned char symbol,\n                         unsigned short nb_rb,\n                         unsigned char dual_stream_UE) {\n#if defined(__x86_64__)||defined(__i386__)\n  unsigned char aatx;\n  int i;\n  __m128i *rxdataF_comp128_0,*rxdataF_comp128_1,*rxdataF_comp128_i0,*rxdataF_comp128_i1,*dl_ch_mag128_0,*dl_ch_mag128_1,*dl_ch_mag128_0b,*dl_ch_mag128_1b,*rho128_0,*rho128_1,*rho128_i0,*rho128_i1,\n          *dl_ch_mag128_i0,*dl_ch_mag128_i1,*dl_ch_mag128_i0b,*dl_ch_mag128_i1b;\n\n  if (frame_parms->nb_antennas_rx>1) {\n    for (aatx=0; aatx<frame_parms->nb_antenna_ports_eNB; aatx++) {\n      rxdataF_comp128_0   = (__m128i *)&rxdataF_comp[(aatx<<1)][symbol*frame_parms->N_RB_DL*12];\n      rxdataF_comp128_1   = (__m128i *)&rxdataF_comp[(aatx<<1)+1][symbol*frame_parms->N_RB_DL*12];\n      dl_ch_mag128_0      = (__m128i *)&dl_ch_mag[(aatx<<1)][symbol*frame_parms->N_RB_DL*12];\n      dl_ch_mag128_1      = (__m128i *)&dl_ch_mag[(aatx<<1)+1][symbol*frame_parms->N_RB_DL*12];\n      dl_ch_mag128_0b     = (__m128i *)&dl_ch_magb[(aatx<<1)][symbol*frame_parms->N_RB_DL*12];\n      dl_ch_mag128_1b     = (__m128i *)&dl_ch_magb[(aatx<<1)+1][symbol*frame_parms->N_RB_DL*12];\n\n      // MRC on each re of rb, both on MF output and magnitude (for 16QAM/64QAM llr computation)\n      for (i=0; i<nb_rb*3; i++) {\n        rxdataF_comp128_0[i] = _mm_adds_epi16(_mm_srai_epi16(rxdataF_comp128_0[i],1),_mm_srai_epi16(rxdataF_comp128_1[i],1));\n        dl_ch_mag128_0[i]    = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_0[i],1),_mm_srai_epi16(dl_ch_mag128_1[i],1));\n        dl_ch_mag128_0b[i]   = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_0b[i],1),_mm_srai_epi16(dl_ch_mag128_1b[i],1));\n        //       print_shorts(\"mrc comp0:\",&rxdataF_comp128_0[i]);\n        //       print_shorts(\"mrc mag0:\",&dl_ch_mag128_0[i]);\n        //       print_shorts(\"mrc mag0b:\",&dl_ch_mag128_0b[i]);\n        //      print_shorts(\"mrc rho1:\",&rho128_1[i]);\n      }\n    }\n\n    if (rho) {\n      rho128_0 = (__m128i *) &rho[0][symbol*frame_parms->N_RB_DL*12];\n      rho128_1 = (__m128i *) &rho[1][symbol*frame_parms->N_RB_DL*12];\n\n      for (i=0; i<nb_rb*3; i++) {\n        //      print_shorts(\"mrc rho0:\",&rho128_0[i]);\n        //      print_shorts(\"mrc rho1:\",&rho128_1[i]);\n        rho128_0[i] = _mm_adds_epi16(_mm_srai_epi16(rho128_0[i],1),_mm_srai_epi16(rho128_1[i],1));\n      }\n    }\n\n    if (dual_stream_UE == 1) {\n      rho128_i0 = (__m128i *) &rho_i[0][symbol*frame_parms->N_RB_DL*12];\n      rho128_i1 = (__m128i *) &rho_i[1][symbol*frame_parms->N_RB_DL*12];\n      rxdataF_comp128_i0   = (__m128i *)&rxdataF_comp_i[0][symbol*frame_parms->N_RB_DL*12];\n      rxdataF_comp128_i1   = (__m128i *)&rxdataF_comp_i[1][symbol*frame_parms->N_RB_DL*12];\n      dl_ch_mag128_i0      = (__m128i *)&dl_ch_mag_i[0][symbol*frame_parms->N_RB_DL*12];\n      dl_ch_mag128_i1      = (__m128i *)&dl_ch_mag_i[1][symbol*frame_parms->N_RB_DL*12];\n      dl_ch_mag128_i0b     = (__m128i *)&dl_ch_magb_i[0][symbol*frame_parms->N_RB_DL*12];\n      dl_ch_mag128_i1b     = (__m128i *)&dl_ch_magb_i[1][symbol*frame_parms->N_RB_DL*12];\n\n      for (i=0; i<nb_rb*3; i++) {\n        rxdataF_comp128_i0[i] = _mm_adds_epi16(_mm_srai_epi16(rxdataF_comp128_i0[i],1),_mm_srai_epi16(rxdataF_comp128_i1[i],1));\n        rho128_i0[i]           = _mm_adds_epi16(_mm_srai_epi16(rho128_i0[i],1),_mm_srai_epi16(rho128_i1[i],1));\n        dl_ch_mag128_i0[i]    = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_i0[i],1),_mm_srai_epi16(dl_ch_mag128_i1[i],1));\n        dl_ch_mag128_i0b[i]    = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_i0b[i],1),_mm_srai_epi16(dl_ch_mag128_i1b[i],1));\n      }\n    }\n  }\n\n  _mm_empty();\n  _m_empty();\n#elif defined(__arm__)\n  unsigned char aatx;\n  int i;\n  int16x8_t *rxdataF_comp128_0,*rxdataF_comp128_1,*rxdataF_comp128_i0,*rxdataF_comp128_i1,*dl_ch_mag128_0,*dl_ch_mag128_1,*dl_ch_mag128_0b,*dl_ch_mag128_1b,*rho128_0,*rho128_1,*rho128_i0,*rho128_i1,\n            *dl_ch_mag128_i0,*dl_ch_mag128_i1,*dl_ch_mag128_i0b,*dl_ch_mag128_i1b;\n\n  if (frame_parms->nb_antennas_rx>1) {\n    for (aatx=0; aatx<frame_parms->nb_antenna_ports_eNB; aatx++) {\n      rxdataF_comp128_0   = (int16x8_t *)&rxdataF_comp[(aatx<<1)][symbol*frame_parms->N_RB_DL*12];\n      rxdataF_comp128_1   = (int16x8_t *)&rxdataF_comp[(aatx<<1)+1][symbol*frame_parms->N_RB_DL*12];\n      dl_ch_mag128_0      = (int16x8_t *)&dl_ch_mag[(aatx<<1)][symbol*frame_parms->N_RB_DL*12];\n      dl_ch_mag128_1      = (int16x8_t *)&dl_ch_mag[(aatx<<1)+1][symbol*frame_parms->N_RB_DL*12];\n      dl_ch_mag128_0b     = (int16x8_t *)&dl_ch_magb[(aatx<<1)][symbol*frame_parms->N_RB_DL*12];\n      dl_ch_mag128_1b     = (int16x8_t *)&dl_ch_magb[(aatx<<1)+1][symbol*frame_parms->N_RB_DL*12];\n\n      // MRC on each re of rb, both on MF output and magnitude (for 16QAM/64QAM llr computation)\n      for (i=0; i<nb_rb*3; i++) {\n        rxdataF_comp128_0[i] = vhaddq_s16(rxdataF_comp128_0[i],rxdataF_comp128_1[i]);\n        dl_ch_mag128_0[i]    = vhaddq_s16(dl_ch_mag128_0[i],dl_ch_mag128_1[i]);\n        dl_ch_mag128_0b[i]   = vhaddq_s16(dl_ch_mag128_0b[i],dl_ch_mag128_1b[i]);\n      }\n    }\n\n    if (rho) {\n      rho128_0 = (int16x8_t *) &rho[0][symbol*frame_parms->N_RB_DL*12];\n      rho128_1 = (int16x8_t *) &rho[1][symbol*frame_parms->N_RB_DL*12];\n\n      for (i=0; i<nb_rb*3; i++) {\n        //  print_shorts(\"mrc rho0:\",&rho128_0[i]);\n        //  print_shorts(\"mrc rho1:\",&rho128_1[i]);\n        rho128_0[i] = vhaddq_s16(rho128_0[i],rho128_1[i]);\n      }\n    }\n\n    if (dual_stream_UE == 1) {\n      rho128_i0 = (int16x8_t *) &rho_i[0][symbol*frame_parms->N_RB_DL*12];\n      rho128_i1 = (int16x8_t *) &rho_i[1][symbol*frame_parms->N_RB_DL*12];\n      rxdataF_comp128_i0   = (int16x8_t *)&rxdataF_comp_i[0][symbol*frame_parms->N_RB_DL*12];\n      rxdataF_comp128_i1   = (int16x8_t *)&rxdataF_comp_i[1][symbol*frame_parms->N_RB_DL*12];\n      dl_ch_mag128_i0      = (int16x8_t *)&dl_ch_mag_i[0][symbol*frame_parms->N_RB_DL*12];\n      dl_ch_mag128_i1      = (int16x8_t *)&dl_ch_mag_i[1][symbol*frame_parms->N_RB_DL*12];\n      dl_ch_mag128_i0b     = (int16x8_t *)&dl_ch_magb_i[0][symbol*frame_parms->N_RB_DL*12];\n      dl_ch_mag128_i1b     = (int16x8_t *)&dl_ch_magb_i[1][symbol*frame_parms->N_RB_DL*12];\n\n      for (i=0; i<nb_rb*3; i++) {\n        rxdataF_comp128_i0[i] = vhaddq_s16(rxdataF_comp128_i0[i],rxdataF_comp128_i1[i]);\n        rho128_i0[i]          = vhaddq_s16(rho128_i0[i],rho128_i1[i]);\n        dl_ch_mag128_i0[i]    = vhaddq_s16(dl_ch_mag128_i0[i],dl_ch_mag128_i1[i]);\n        dl_ch_mag128_i0b[i]   = vhaddq_s16(dl_ch_mag128_i0b[i],dl_ch_mag128_i1b[i]);\n      }\n    }\n  }\n\n#endif\n}\n\nvoid dlsch_detection_mrc_TM34(LTE_DL_FRAME_PARMS *frame_parms,\n                              LTE_UE_PDSCH *pdsch_vars,\n                              int harq_pid,\n                              int round,\n                              unsigned char symbol,\n                              unsigned short nb_rb,\n                              unsigned char dual_stream_UE) {\n  int i;\n  __m128i *rxdataF_comp128_0,*rxdataF_comp128_1;\n  __m128i *dl_ch_mag128_0,*dl_ch_mag128_1;\n  __m128i *dl_ch_mag128_0b,*dl_ch_mag128_1b;\n  __m128i *rho128_0, *rho128_1;\n  int **rxdataF_comp0           = pdsch_vars->rxdataF_comp0;\n  int **rxdataF_comp1           = pdsch_vars->rxdataF_comp1[harq_pid][round];\n  int **dl_ch_rho_ext           = pdsch_vars->dl_ch_rho_ext[harq_pid][round]; //for second stream\n  int **dl_ch_rho2_ext          = pdsch_vars->dl_ch_rho2_ext;\n  int **dl_ch_mag0              = pdsch_vars->dl_ch_mag0;\n  int **dl_ch_mag1              = pdsch_vars->dl_ch_mag1[harq_pid][round];\n  int **dl_ch_magb0             = pdsch_vars->dl_ch_magb0;\n  int **dl_ch_magb1             = pdsch_vars->dl_ch_magb1[harq_pid][round];\n  rxdataF_comp128_0   = (__m128i *)&rxdataF_comp0[0][symbol*frame_parms->N_RB_DL*12];\n  rxdataF_comp128_1   = (__m128i *)&rxdataF_comp0[1][symbol*frame_parms->N_RB_DL*12];\n  dl_ch_mag128_0      = (__m128i *)&dl_ch_mag0[0][symbol*frame_parms->N_RB_DL*12];\n  dl_ch_mag128_1      = (__m128i *)&dl_ch_mag0[1][symbol*frame_parms->N_RB_DL*12];\n  dl_ch_mag128_0b     = (__m128i *)&dl_ch_magb0[0][symbol*frame_parms->N_RB_DL*12];\n  dl_ch_mag128_1b     = (__m128i *)&dl_ch_magb0[1][symbol*frame_parms->N_RB_DL*12];\n  rho128_0 = (__m128i *) &dl_ch_rho2_ext[0][symbol*frame_parms->N_RB_DL*12];\n  rho128_1 = (__m128i *) &dl_ch_rho2_ext[1][symbol*frame_parms->N_RB_DL*12];\n\n  // MRC on each re of rb, both on MF output and magnitude (for 16QAM/64QAM llr computation)\n  for (i=0; i<nb_rb*3; i++) {\n    rxdataF_comp128_0[i] = _mm_adds_epi16(_mm_srai_epi16(rxdataF_comp128_0[i],1),_mm_srai_epi16(rxdataF_comp128_1[i],1));\n    dl_ch_mag128_0[i]    = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_0[i],1),_mm_srai_epi16(dl_ch_mag128_1[i],1));\n    dl_ch_mag128_0b[i]   = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_0b[i],1),_mm_srai_epi16(dl_ch_mag128_1b[i],1));\n    rho128_0[i] = _mm_adds_epi16(_mm_srai_epi16(rho128_0[i],1),_mm_srai_epi16(rho128_1[i],1));\n\n    if (frame_parms->nb_antennas_rx>2) {\n      __m128i *rxdataF_comp128_2 = NULL;\n      __m128i *rxdataF_comp128_3 = NULL;\n      __m128i *dl_ch_mag128_2 = NULL;\n      __m128i *dl_ch_mag128_3 = NULL;\n      __m128i *dl_ch_mag128_2b = NULL;\n      __m128i *dl_ch_mag128_3b = NULL;\n      __m128i *rho128_2 = NULL;\n      __m128i *rho128_3 = NULL;\n      rxdataF_comp128_2   = (__m128i *)&rxdataF_comp0[2][symbol*frame_parms->N_RB_DL*12];\n      rxdataF_comp128_3   = (__m128i *)&rxdataF_comp0[3][symbol*frame_parms->N_RB_DL*12];\n      dl_ch_mag128_2      = (__m128i *)&dl_ch_mag0[2][symbol*frame_parms->N_RB_DL*12];\n      dl_ch_mag128_3      = (__m128i *)&dl_ch_mag0[3][symbol*frame_parms->N_RB_DL*12];\n      dl_ch_mag128_2b     = (__m128i *)&dl_ch_magb0[2][symbol*frame_parms->N_RB_DL*12];\n      dl_ch_mag128_3b     = (__m128i *)&dl_ch_magb0[3][symbol*frame_parms->N_RB_DL*12];\n      rho128_2 = (__m128i *) &dl_ch_rho2_ext[2][symbol*frame_parms->N_RB_DL*12];\n      rho128_3 = (__m128i *) &dl_ch_rho2_ext[3][symbol*frame_parms->N_RB_DL*12];\n      /*rxdataF_comp*/\n      rxdataF_comp128_2[i] = _mm_adds_epi16(_mm_srai_epi16(rxdataF_comp128_2[i],1),_mm_srai_epi16(rxdataF_comp128_3[i],1));\n      rxdataF_comp128_0[i] = _mm_adds_epi16(_mm_srai_epi16(rxdataF_comp128_0[i],1),_mm_srai_epi16(rxdataF_comp128_2[i],1));\n      /*dl_ch_mag*/\n      dl_ch_mag128_2[i] = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_2[i],1),_mm_srai_epi16(dl_ch_mag128_3[i],1));\n      dl_ch_mag128_0[i] = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_0[i],1),_mm_srai_epi16(dl_ch_mag128_2[i],1));\n      /*dl_ch_mag*/\n      dl_ch_mag128_2b[i] = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_2b[i],1),_mm_srai_epi16(dl_ch_mag128_3b[i],1));\n      dl_ch_mag128_0b[i] = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_0b[i],1),_mm_srai_epi16(dl_ch_mag128_2b[i],1));\n      /*rho*/\n      rho128_2[i] = _mm_adds_epi16(_mm_srai_epi16(rho128_2[i],1),_mm_srai_epi16(rho128_3[i],1));\n      rho128_0[i] = _mm_adds_epi16(_mm_srai_epi16(rho128_0[i],1),_mm_srai_epi16(rho128_2[i],1));\n    }\n  }\n\n  if (dual_stream_UE == 1) {\n    __m128i *dl_ch_mag128_i0, *dl_ch_mag128_i1;\n    __m128i *dl_ch_mag128_i0b, *dl_ch_mag128_i1b;\n    __m128i *rho128_i0, *rho128_i1;\n    __m128i *rxdataF_comp128_i0, *rxdataF_comp128_i1;\n    rxdataF_comp128_i0   = (__m128i *)&rxdataF_comp1[0][symbol*frame_parms->N_RB_DL*12];\n    rxdataF_comp128_i1   = (__m128i *)&rxdataF_comp1[1][symbol*frame_parms->N_RB_DL*12];\n    dl_ch_mag128_i0      = (__m128i *)&dl_ch_mag1[0][symbol*frame_parms->N_RB_DL*12];\n    dl_ch_mag128_i1      = (__m128i *)&dl_ch_mag1[1][symbol*frame_parms->N_RB_DL*12];\n    dl_ch_mag128_i0b     = (__m128i *)&dl_ch_magb1[0][symbol*frame_parms->N_RB_DL*12];\n    dl_ch_mag128_i1b     = (__m128i *)&dl_ch_magb1[1][symbol*frame_parms->N_RB_DL*12];\n    rho128_i0 = (__m128i *) &dl_ch_rho_ext[0][symbol*frame_parms->N_RB_DL*12];\n    rho128_i1 = (__m128i *) &dl_ch_rho_ext[1][symbol*frame_parms->N_RB_DL*12];\n\n    for (i=0; i<nb_rb*3; i++) {\n      rxdataF_comp128_i0[i] = _mm_adds_epi16(_mm_srai_epi16(rxdataF_comp128_i0[i],1),_mm_srai_epi16(rxdataF_comp128_i1[i],1));\n      dl_ch_mag128_i0[i]    = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_i0[i],1),_mm_srai_epi16(dl_ch_mag128_i1[i],1));\n      dl_ch_mag128_i0b[i]    = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_i0b[i],1),_mm_srai_epi16(dl_ch_mag128_i1b[i],1));\n      rho128_i0[i]           = _mm_adds_epi16(_mm_srai_epi16(rho128_i0[i],1),_mm_srai_epi16(rho128_i1[i],1));\n\n      if (frame_parms->nb_antennas_rx>2) {\n        __m128i *rxdataF_comp128_i2 = NULL;\n        __m128i *rxdataF_comp128_i3 = NULL;\n        __m128i *dl_ch_mag128_i2 = NULL;\n        __m128i *dl_ch_mag128_i3 = NULL;\n        __m128i *dl_ch_mag128_i2b = NULL;\n        __m128i *dl_ch_mag128_i3b = NULL;\n        __m128i *rho128_i2 = NULL;\n        __m128i *rho128_i3 = NULL;\n        rxdataF_comp128_i2   = (__m128i *)&rxdataF_comp1[2][symbol*frame_parms->N_RB_DL*12];\n        rxdataF_comp128_i3   = (__m128i *)&rxdataF_comp1[3][symbol*frame_parms->N_RB_DL*12];\n        dl_ch_mag128_i2      = (__m128i *)&dl_ch_mag1[2][symbol*frame_parms->N_RB_DL*12];\n        dl_ch_mag128_i3      = (__m128i *)&dl_ch_mag1[3][symbol*frame_parms->N_RB_DL*12];\n        dl_ch_mag128_i2b     = (__m128i *)&dl_ch_magb1[2][symbol*frame_parms->N_RB_DL*12];\n        dl_ch_mag128_i3b     = (__m128i *)&dl_ch_magb1[3][symbol*frame_parms->N_RB_DL*12];\n        rho128_i2 = (__m128i *) &dl_ch_rho_ext[2][symbol*frame_parms->N_RB_DL*12];\n        rho128_i3 = (__m128i *) &dl_ch_rho_ext[3][symbol*frame_parms->N_RB_DL*12];\n        /*rxdataF_comp*/\n        rxdataF_comp128_i2[i] = _mm_adds_epi16(_mm_srai_epi16(rxdataF_comp128_i2[i],1),_mm_srai_epi16(rxdataF_comp128_i3[i],1));\n        rxdataF_comp128_i0[i] = _mm_adds_epi16(_mm_srai_epi16(rxdataF_comp128_i0[i],1),_mm_srai_epi16(rxdataF_comp128_i2[i],1));\n        /*dl_ch_mag*/\n        dl_ch_mag128_i2[i] = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_i2[i],1),_mm_srai_epi16(dl_ch_mag128_i3[i],1));\n        dl_ch_mag128_i0[i] = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_i0[i],1),_mm_srai_epi16(dl_ch_mag128_i2[i],1));\n        /*dl_ch_mag*/\n        dl_ch_mag128_i2b[i] = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_i2b[i],1),_mm_srai_epi16(dl_ch_mag128_i3b[i],1));\n        dl_ch_mag128_i0b[i] = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_i0b[i],1),_mm_srai_epi16(dl_ch_mag128_i2b[i],1));\n        /*rho*/\n        rho128_i2[i] = _mm_adds_epi16(_mm_srai_epi16(rho128_i2[i],1),_mm_srai_epi16(rho128_i3[i],1));\n        rho128_i0[i] = _mm_adds_epi16(_mm_srai_epi16(rho128_i0[i],1),_mm_srai_epi16(rho128_i2[i],1));\n      }\n    }\n  }\n\n  _mm_empty();\n  _m_empty();\n}\n\nvoid dlsch_scale_channel(int **dl_ch_estimates_ext,\n                         LTE_DL_FRAME_PARMS *frame_parms,\n                         LTE_UE_DLSCH_t **dlsch_ue,\n                         uint8_t symbol,\n                         unsigned short nb_rb) {\n#if defined(__x86_64__)||defined(__i386__)\n  short rb, ch_amp;\n  unsigned char aatx,aarx,pilots=0,symbol_mod;\n  __m128i *dl_ch128, ch_amp128;\n  symbol_mod = (symbol>=(7-frame_parms->Ncp)) ? symbol-(7-frame_parms->Ncp) : symbol;\n\n  if ((symbol_mod == 0) || (symbol_mod == (4-frame_parms->Ncp))) {\n    if (frame_parms->nb_antenna_ports_eNB==1) // 10 out of 12 so don't reduce size\n      nb_rb=1+(5*nb_rb/6);\n    else\n      pilots=1;\n  }\n\n  // Determine scaling amplitude based the symbol\n  ch_amp = ((pilots) ? (dlsch_ue[0]->sqrt_rho_b) : (dlsch_ue[0]->sqrt_rho_a));\n  LOG_D(PHY,\"Scaling PDSCH Chest in OFDM symbol %d by %d, pilots %d nb_rb %d NCP %d symbol %d\\n\",symbol_mod,ch_amp,pilots,nb_rb,frame_parms->Ncp,symbol);\n  // printf(\"Scaling PDSCH Chest in OFDM symbol %d by %d\\n\",symbol_mod,ch_amp);\n  ch_amp128 = _mm_set1_epi16(ch_amp); // Q3.13\n\n  for (aatx=0; aatx<frame_parms->nb_antenna_ports_eNB; aatx++) {\n    for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) {\n      dl_ch128=(__m128i *)&dl_ch_estimates_ext[(aatx<<1)+aarx][symbol*frame_parms->N_RB_DL*12];\n\n      for (rb=0; rb<nb_rb; rb++) {\n        dl_ch128[0] = _mm_mulhi_epi16(dl_ch128[0],ch_amp128);\n        dl_ch128[0] = _mm_slli_epi16(dl_ch128[0],3);\n        dl_ch128[1] = _mm_mulhi_epi16(dl_ch128[1],ch_amp128);\n        dl_ch128[1] = _mm_slli_epi16(dl_ch128[1],3);\n\n        if (pilots) {\n          dl_ch128+=2;\n        } else {\n          dl_ch128[2] = _mm_mulhi_epi16(dl_ch128[2],ch_amp128);\n          dl_ch128[2] = _mm_slli_epi16(dl_ch128[2],3);\n          dl_ch128+=3;\n        }\n      }\n    }\n  }\n\n#elif defined(__arm__)\n#endif\n}\n\n//compute average channel_level on each (TX,RX) antenna pair\nvoid dlsch_channel_level(int **dl_ch_estimates_ext,\n                         LTE_DL_FRAME_PARMS *frame_parms,\n                         int32_t *avg,\n                         uint8_t symbol,\n                         unsigned short nb_rb) {\n#if defined(__x86_64__)||defined(__i386__)\n  //printf(\"symbol = %d\\n\", symbol);\n  short rb;\n  unsigned char aatx,aarx,nre=12,symbol_mod;\n  __m128i *dl_ch128, avg128D;\n  symbol_mod = (symbol>=(7-frame_parms->Ncp)) ? symbol-(7-frame_parms->Ncp) : symbol;\n\n  if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->nb_antenna_ports_eNB!=1))\n    nre=8;\n  else if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->nb_antenna_ports_eNB==1))\n    nre=10;\n  else\n    nre=12;\n\n  //nb_rb*nre = y * 2^x\n  int16_t x = factor2(nb_rb*nre);\n  int16_t y = (nb_rb*nre)>>x;\n\n  for (aatx=0; aatx<frame_parms->nb_antenna_ports_eNB; aatx++)\n    for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) {\n      //clear average level\n      //printf(\"aatx = %d, aarx = %d, aatx*frame_parms->nb_antennas_rx + aarx] = %d \\n\", aatx, aarx, aatx*frame_parms->nb_antennas_rx + aarx);\n      avg128D = _mm_setzero_si128();\n      // 5 is always a symbol with no pilots for both normal and extended prefix\n      dl_ch128=(__m128i *)&dl_ch_estimates_ext[aatx*2 + aarx][symbol*frame_parms->N_RB_DL*12];\n\n      for (rb=0; rb<nb_rb; rb++) {\n        //printf(\"rb %d : \",rb);\n        avg128D = _mm_add_epi32(avg128D,_mm_srai_epi32(_mm_madd_epi16(dl_ch128[0],dl_ch128[0]),x));\n        avg128D = _mm_add_epi32(avg128D,_mm_srai_epi32(_mm_madd_epi16(dl_ch128[1],dl_ch128[1]),x));\n\n        //avg128D = _mm_add_epi32(avg128D,_mm_madd_epi16(dl_ch128[0],_mm_srai_epi16(_mm_mulhi_epi16(dl_ch128[0], coeff128),15)));\n        //avg128D = _mm_add_epi32(avg128D,_mm_madd_epi16(dl_ch128[1],_mm_srai_epi16(_mm_mulhi_epi16(dl_ch128[1], coeff128),15)));\n\n        if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->nb_antenna_ports_eNB!=1)) {\n          dl_ch128+=2;\n        } else {\n          avg128D = _mm_add_epi32(avg128D,_mm_srai_epi32(_mm_madd_epi16(dl_ch128[2],dl_ch128[2]),x));\n          //avg128D = _mm_add_epi32(avg128D,_mm_madd_epi16(dl_ch128[2],_mm_srai_epi16(_mm_mulhi_epi16(dl_ch128[2], coeff128),15)));\n          dl_ch128+=3;\n        }\n\n        /*if(rb==0){\n          print_shorts(\"dl_ch128\",&dl_ch128[0]);\n          print_shorts(\"dl_ch128\",&dl_ch128[1]);\n          print_shorts(\"dl_ch128\",&dl_ch128[2]);\n        }*/\n      }\n\n      avg[aatx*frame_parms->nb_antennas_rx + aarx] =(((int32_t *)&avg128D)[0] +\n          ((int32_t *)&avg128D)[1] +\n          ((int32_t *)&avg128D)[2] +\n          ((int32_t *)&avg128D)[3])/y;\n    }\n\n  _mm_empty();\n  _m_empty();\n#elif defined(__arm__)\n  short rb;\n  unsigned char aatx,aarx,nre=12,symbol_mod;\n  int32x4_t avg128D;\n  int16x4_t *dl_ch128;\n  symbol_mod = (symbol>=(7-frame_parms->Ncp)) ? symbol-(7-frame_parms->Ncp) : symbol;\n\n  for (aatx=0; aatx<frame_parms->nb_antenna_ports_eNB; aatx++)\n    for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) {\n      //clear average level\n      avg128D = vdupq_n_s32(0);\n      // 5 is always a symbol with no pilots for both normal and extended prefix\n      dl_ch128=(int16x4_t *)&dl_ch_estimates_ext[aatx*frame_parms->nb_antennas_rx + aarx][symbol*frame_parms->N_RB_DL*12];\n\n      for (rb=0; rb<nb_rb; rb++) {\n        //  printf(\"rb %d : \",rb);\n        //  print_shorts(\"ch\",&dl_ch128[0]);\n        avg128D = vqaddq_s32(avg128D,vmull_s16(dl_ch128[0],dl_ch128[0]));\n        avg128D = vqaddq_s32(avg128D,vmull_s16(dl_ch128[1],dl_ch128[1]));\n        avg128D = vqaddq_s32(avg128D,vmull_s16(dl_ch128[2],dl_ch128[2]));\n        avg128D = vqaddq_s32(avg128D,vmull_s16(dl_ch128[3],dl_ch128[3]));\n\n        if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->mode1_flag==0)) {\n          dl_ch128+=4;\n        } else {\n          avg128D = vqaddq_s32(avg128D,vmull_s16(dl_ch128[4],dl_ch128[4]));\n          avg128D = vqaddq_s32(avg128D,vmull_s16(dl_ch128[5],dl_ch128[5]));\n          dl_ch128+=6;\n        }\n\n        /*\n          if (rb==0) {\n          print_shorts(\"dl_ch128\",&dl_ch128[0]);\n          print_shorts(\"dl_ch128\",&dl_ch128[1]);\n          print_shorts(\"dl_ch128\",&dl_ch128[2]);\n          }\n        */\n      }\n\n      if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->mode1_flag==0))\n        nre=8;\n      else if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->mode1_flag==1))\n        nre=10;\n      else\n        nre=12;\n\n      avg[aatx*frame_parms->nb_antennas_rx + aarx] = (((int32_t *)&avg128D)[0] +\n          ((int32_t *)&avg128D)[1] +\n          ((int32_t *)&avg128D)[2] +\n          ((int32_t *)&avg128D)[3])/(nb_rb*nre);\n      //printf(\"Channel level : %d\\n\",avg[aatx*(frame_parms->nb_antennas_rx-1) + aarx]);\n    }\n\n#endif\n}\n\nvoid dlsch_channel_level_core(int **dl_ch_estimates_ext,\n                              int32_t *avg,\n                              int n_tx,\n                              int n_rx,\n                              int length,\n                              int start_point) {\n#if defined(__x86_64__)||defined(__i386__)\n  short ii;\n  int aatx,aarx;\n  int length_mod8;\n  int length2;\n  __m128i *dl_ch128, avg128D;\n  int16_t x = factor2(length);\n  int16_t y = (length)>>x;\n\n  for (aatx=0; aatx<n_tx; aatx++)\n    for (aarx=0; aarx<n_rx; aarx++) {\n      avg128D = _mm_setzero_si128();\n      dl_ch128=(__m128i *)&dl_ch_estimates_ext[aatx*2 + aarx][start_point];\n      length_mod8=length&7;\n\n      if (length_mod8 == 0) {\n        length2 = length>>3;\n\n        for (ii=0; ii<length2; ii++) {\n          avg128D = _mm_add_epi32(avg128D,_mm_srai_epi32(_mm_madd_epi16(dl_ch128[0],dl_ch128[0]),x));\n          avg128D = _mm_add_epi32(avg128D,_mm_srai_epi32(_mm_madd_epi16(dl_ch128[1],dl_ch128[1]),x));\n          dl_ch128+=2;\n        }\n      } else {\n        printf (\"Channel level: Received number of subcarriers is not multiple of 4, \\n\"\n                \"need to adapt the code!\\n\");\n      }\n\n      avg[aatx*n_rx + aarx] =(((int32_t *)&avg128D)[0] +\n                              ((int32_t *)&avg128D)[1] +\n                              ((int32_t *)&avg128D)[2] +\n                              ((int32_t *)&avg128D)[3])/y;\n      //printf(\"Channel level [%d]: %d\\n\",aatx*n_rx + aarx, avg[aatx*n_rx + aarx]);\n    }\n\n  _mm_empty();\n  _m_empty();\n  /* FIXME This part needs to be adapted like the one above */\n#elif defined(__arm__)\n  short rb;\n  unsigned char aatx,aarx,nre=12,symbol_mod;\n  int32x4_t avg128D;\n  int16x4_t *dl_ch128;\n  symbol_mod = (symbol>=(7-frame_parms->Ncp)) ? symbol-(7-frame_parms->Ncp) : symbol;\n\n  for (aatx=0; aatx<frame_parms->nb_antenna_ports_eNB; aatx++)\n    for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) {\n      //clear average level\n      avg128D = vdupq_n_s32(0);\n      // 5 is always a symbol with no pilots for both normal and extended prefix\n      dl_ch128=(int16x4_t *)&dl_ch_estimates_ext[aatx*frame_parms->nb_antennas_rx + aarx][symbol*frame_parms->N_RB_DL*12];\n\n      for (rb=0; rb<nb_rb; rb++) {\n        //  printf(\"rb %d : \",rb);\n        //  print_shorts(\"ch\",&dl_ch128[0]);\n        avg128D = vqaddq_s32(avg128D,vmull_s16(dl_ch128[0],dl_ch128[0]));\n        avg128D = vqaddq_s32(avg128D,vmull_s16(dl_ch128[1],dl_ch128[1]));\n        avg128D = vqaddq_s32(avg128D,vmull_s16(dl_ch128[2],dl_ch128[2]));\n        avg128D = vqaddq_s32(avg128D,vmull_s16(dl_ch128[3],dl_ch128[3]));\n\n        if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->nb_antenna_ports_eNB!=1)) {\n          dl_ch128+=4;\n        } else {\n          avg128D = vqaddq_s32(avg128D,vmull_s16(dl_ch128[4],dl_ch128[4]));\n          avg128D = vqaddq_s32(avg128D,vmull_s16(dl_ch128[5],dl_ch128[5]));\n          dl_ch128+=6;\n        }\n      }\n\n      if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->nb_antenna_ports_eNB!=1))\n        nre=8;\n      else if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->nb_antenna_ports_eNB==1))\n        nre=10;\n      else\n        nre=12;\n\n      avg[aatx*frame_parms->nb_antennas_rx + aarx] = (((int32_t *)&avg128D)[0] +\n          ((int32_t *)&avg128D)[1] +\n          ((int32_t *)&avg128D)[2] +\n          ((int32_t *)&avg128D)[3])/(nb_rb*nre);\n      //printf(\"Channel level : %d\\n\",avg[aatx*(frame_parms->nb_antennas_rx-1) + aarx]);\n    }\n\n#endif\n}\n\nvoid dlsch_channel_level_median(int **dl_ch_estimates_ext,\n                                int32_t *median,\n                                int n_tx,\n                                int n_rx,\n                                int length,\n                                int start_point) {\n#if defined(__x86_64__)||defined(__i386__)\n  short ii;\n  int aatx,aarx;\n  int length2;\n  int max = 0, min=0;\n  int norm_pack;\n  __m128i *dl_ch128, norm128D;\n\n  for (aatx=0; aatx<n_tx; aatx++) {\n    for (aarx=0; aarx<n_rx; aarx++) {\n      max = 0;\n      min = 0;\n      norm128D = _mm_setzero_si128();\n      dl_ch128=(__m128i *)&dl_ch_estimates_ext[aatx*2 + aarx][start_point];\n      length2 = length>>2;\n\n      for (ii=0; ii<length2; ii++) {\n        norm128D = _mm_srai_epi32( _mm_madd_epi16(dl_ch128[0],dl_ch128[0]), 1);\n        //print_ints(\"norm128D\",&norm128D[0]);\n        norm_pack = ((int32_t *)&norm128D)[0] +\n                    ((int32_t *)&norm128D)[1] +\n                    ((int32_t *)&norm128D)[2] +\n                    ((int32_t *)&norm128D)[3];\n\n        if (norm_pack > max)\n          max = norm_pack;\n\n        if (norm_pack < min)\n          min = norm_pack;\n\n        dl_ch128+=1;\n      }\n\n      median[aatx*n_rx + aarx]  = (max+min)>>1;\n      // printf(\"Channel level  median [%d]: %d\\n\",aatx*n_rx + aarx, median[aatx*n_rx + aarx]);\n    }\n  }\n\n  _mm_empty();\n  _m_empty();\n#elif defined(__arm__)\n  short rb;\n  unsigned char aatx,aarx,nre=12,symbol_mod;\n  int32x4_t norm128D;\n  int16x4_t *dl_ch128;\n\n  for (aatx=0; aatx<frame_parms->nb_antenna_ports_eNB; aatx++) {\n    for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) {\n      max = 0;\n      min = 0;\n      norm128D = vdupq_n_s32(0);\n      dl_ch128=(int16x4_t *)&dl_ch_estimates_ext[aatx*n_rx + aarx][start_point];\n      length_mod8=length&3;\n      length2 = length>>2;\n\n      for (ii=0; ii<length2; ii++) {\n        norm128D = vshrq_n_u32(vmull_s16(dl_ch128[0],dl_ch128[0]), 1);\n        norm_pack = ((int32_t *)&norm128D)[0] +\n                    ((int32_t *)&norm128D)[1] +\n                    ((int32_t *)&norm128D)[2] +\n                    ((int32_t *)&norm128D)[3];\n\n        if (norm_pack > max)\n          max = norm_pack;\n\n        if (norm_pack < min)\n          min = norm_pack;\n\n        dl_ch128+=1;\n      }\n\n      median[aatx*n_rx + aarx]  = (max+min)>>1;\n      //printf(\"Channel level  median [%d]: %d\\n\",aatx*n_rx + aarx, median[aatx*n_rx + aarx]);\n    }\n  }\n\n#endif\n}\n\nvoid mmse_processing_oai(LTE_UE_PDSCH *pdsch_vars,\n                         LTE_DL_FRAME_PARMS *frame_parms,\n                         PHY_MEASUREMENTS *measurements,\n                         unsigned char first_symbol_flag,\n                         MIMO_mode_t mimo_mode,\n                         unsigned short mmse_flag,\n                         int noise_power,\n                         unsigned char symbol,\n                         unsigned short nb_rb) {\n  int **rxdataF_ext           = pdsch_vars->rxdataF_ext;\n  int **dl_ch_estimates_ext   = pdsch_vars->dl_ch_estimates_ext;\n  unsigned char *pmi_ext      = pdsch_vars->pmi_ext;\n  int avg_00[frame_parms->nb_antenna_ports_eNB*frame_parms->nb_antennas_rx];\n  int avg_01[frame_parms->nb_antenna_ports_eNB*frame_parms->nb_antennas_rx];\n  int symbol_mod, length, start_point, nre;\n  symbol_mod = (symbol>=(7-frame_parms->Ncp)) ? symbol-(7-frame_parms->Ncp) : symbol;\n\n  if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->nb_antenna_ports_eNB!=1))\n    nre=8;\n  else if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->nb_antenna_ports_eNB==1))\n    nre=10;\n  else\n    nre=12;\n\n  length  = nre*nb_rb;\n  start_point = symbol*nb_rb*12;\n  mmse_processing_core(rxdataF_ext,\n                       dl_ch_estimates_ext,\n                       noise_power,\n                       frame_parms->nb_antenna_ports_eNB,\n                       frame_parms->nb_antennas_rx,\n                       length,\n                       start_point);\n\n  /*dlsch_channel_aver_band(dl_ch_estimates_ext,\n                          frame_parms,\n                          chan_avg,\n                          symbol,\n                          nb_rb);\n\n\n   for (aatx=0; aatx<frame_parms->nb_antenna_ports_eNB; aatx++)\n     for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) {\n       H[aatx*frame_parms->nb_antennas_rx + aarx] = (float)(chan_avg[aatx*frame_parms->nb_antennas_rx + aarx].r/(32768.0)) + I*(float)(chan_avg[aatx*frame_parms->nb_antennas_rx + aarx].i/(32768.0));\n      // printf(\"H [%d] = (%f, %f) \\n\", aatx*frame_parms->nb_antennas_rx + aarx, creal(H[aatx*frame_parms->nb_antennas_rx + aarx]), cimag(H[aatx*frame_parms->nb_antennas_rx + aarx]));\n   }*/\n\n  if (first_symbol_flag == 1) {\n    dlsch_channel_level_TM34(dl_ch_estimates_ext,\n                             frame_parms,\n                             pmi_ext,\n                             avg_00,\n                             avg_01,\n                             symbol,\n                             nb_rb,\n                             mmse_flag,\n                             mimo_mode);\n    avg_00[0] = (log2_approx(avg_00[0])/2) + dlsch_demod_shift+4;// + 2 ;//+ 4;\n    avg_01[0] = (log2_approx(avg_01[0])/2) + dlsch_demod_shift+4;// + 2 ;//+ 4;\n    pdsch_vars->log2_maxh0 = cmax(avg_00[0],0);\n    pdsch_vars->log2_maxh1 = cmax(avg_01[0],0);\n  }\n}\n\nvoid mmse_processing_core(int32_t **rxdataF_ext,\n                          int32_t **dl_ch_estimates_ext,\n                          int noise_power,\n                          int n_tx,\n                          int n_rx,\n                          int length,\n                          int start_point) {\n  int aatx, aarx, re;\n  float imag;\n  float real;\n  float complex **W_MMSE= malloc(n_tx*n_rx*sizeof(float complex *));\n\n  for (int j=0; j<n_tx*n_rx; j++) {\n    W_MMSE[j] = malloc(sizeof(float complex)*length);\n  }\n\n  float complex *H=  malloc(n_tx*n_rx*sizeof(float complex));\n  float complex *W_MMSE_re=  malloc(n_tx*n_rx*sizeof(float complex));\n  float complex **dl_ch_estimates_ext_flcpx = malloc(n_tx*n_rx*sizeof(float complex *));\n\n  for (int j=0; j<n_tx*n_rx; j++) {\n    dl_ch_estimates_ext_flcpx[j] = malloc(sizeof(float complex)*length);\n  }\n\n  float complex **rxdataF_ext_flcpx = malloc(n_rx*sizeof(float complex *));\n\n  for (int j=0; j<n_rx; j++) {\n    rxdataF_ext_flcpx[j] = malloc(sizeof(float complex)*length);\n  }\n\n  chan_est_to_float(dl_ch_estimates_ext,\n                    dl_ch_estimates_ext_flcpx,\n                    n_tx,\n                    n_rx,\n                    length,\n                    start_point);\n\n  for (re=0; re<length; re++) {\n    for (aatx=0; aatx<n_tx; aatx++) {\n      for (aarx=0; aarx<n_rx; aarx++) {\n        imag = cimag(dl_ch_estimates_ext_flcpx[aatx*n_rx + aarx][re]);\n        real = creal(dl_ch_estimates_ext_flcpx[aatx*n_rx + aarx][re]);\n        H[aatx*n_rx + aarx] = real+ I*imag;\n      }\n    }\n\n    compute_MMSE(H, n_tx, noise_power, W_MMSE_re);\n\n    for (aatx=0; aatx<n_tx; aatx++) {\n      for (aarx=0; aarx<n_rx; aarx++) {\n        W_MMSE[aatx*n_rx + aarx][re] = W_MMSE_re[aatx*n_rx + aarx];\n      }\n    }\n  }\n\n  rxdataF_to_float(rxdataF_ext,\n                   rxdataF_ext_flcpx,\n                   n_rx,\n                   length,\n                   start_point);\n  mult_mmse_rxdataF(W_MMSE,\n                    rxdataF_ext_flcpx,\n                    n_tx,\n                    n_rx,\n                    length,\n                    start_point);\n  mult_mmse_chan_est(W_MMSE,\n                     dl_ch_estimates_ext_flcpx,\n                     n_tx,\n                     n_rx,\n                     length,\n                     start_point);\n  float_to_rxdataF(rxdataF_ext,\n                   rxdataF_ext_flcpx,\n                   n_tx,\n                   n_rx,\n                   length,\n                   start_point);\n  float_to_chan_est(dl_ch_estimates_ext,\n                    dl_ch_estimates_ext_flcpx,\n                    n_tx,\n                    n_rx,\n                    length,\n                    start_point);\n  free(W_MMSE);\n  free(H);\n  free(W_MMSE_re);\n  free(dl_ch_estimates_ext_flcpx);\n  free(rxdataF_ext_flcpx);\n}\n\n\n/*THIS FUNCTION TAKES FLOAT_POINT INPUT. SHOULD NOT BE USED WITH OAI*/\nvoid mmse_processing_core_flp(float complex **rxdataF_ext_flcpx,\n                              float complex **H,\n                              int32_t **rxdataF_ext,\n                              int32_t **dl_ch_estimates_ext,\n                              float noise_power,\n                              int n_tx,\n                              int n_rx,\n                              int length,\n                              int start_point) {\n  int aatx, aarx, re;\n  float max = 0;\n  float one_over_max = 0;\n  float complex **W_MMSE= malloc(n_tx*n_rx*sizeof(float complex *));\n\n  for (int j=0; j<n_tx*n_rx; j++) {\n    W_MMSE[j] = malloc(sizeof(float complex)*length);\n  }\n\n  float complex *H_re=  malloc(n_tx*n_rx*sizeof(float complex));\n  float complex *W_MMSE_re=  malloc(n_tx*n_rx*sizeof(float complex));\n\n  for (re=0; re<length; re++) {\n    for (aatx=0; aatx<n_tx; aatx++) {\n      for (aarx=0; aarx<n_rx; aarx++) {\n        H_re[aatx*n_rx + aarx] = H[aatx*n_rx + aarx][re];\n#ifdef DEBUG_MMSE\n\n        if (re == 0)\n          printf(\" H_re[%d]= (%f + i%f)\\n\", aatx*n_rx + aarx, creal(H_re[aatx*n_rx + aarx]), cimag(H_re[aatx*n_rx + aarx]));\n\n#endif\n      }\n    }\n\n    compute_MMSE(H_re, n_tx, noise_power, W_MMSE_re);\n\n    for (aatx=0; aatx<n_tx; aatx++) {\n      for (aarx=0; aarx<n_rx; aarx++) {\n        W_MMSE[aatx*n_rx + aarx][re] = W_MMSE_re[aatx*n_rx + aarx];\n\n        if (fabs(creal(W_MMSE_re[aatx*n_rx + aarx])) > max)\n          max = fabs(creal(W_MMSE_re[aatx*n_rx + aarx]));\n\n        if (fabs(cimag(W_MMSE_re[aatx*n_rx + aarx])) > max)\n          max = fabs(cimag(W_MMSE_re[aatx*n_rx + aarx]));\n      }\n    }\n  }\n\n  one_over_max = 1.0/max;\n\n  for (re=0; re<length; re++)\n    for (aatx=0; aatx<n_tx; aatx++)\n      for (aarx=0; aarx<n_rx; aarx++) {\n#ifdef DEBUG_MMSE\n\n        if (re == 0)\n          printf(\" W_MMSE[%d] = (%f + i%f)\\n\", aatx*n_rx + aarx, creal(W_MMSE[aatx*n_rx + aarx][re]), cimag(W_MMSE[aatx*n_rx + aarx][re]));\n\n#endif\n        W_MMSE[aatx*n_rx + aarx][re] = one_over_max*W_MMSE[aatx*n_rx + aarx][re];\n#ifdef DEBUG_MMSE\n\n        if (re == 0)\n          printf(\" AFTER NORM W_MMSE[%d] = (%f + i%f), max = %f \\n\", aatx*n_rx + aarx, creal(W_MMSE[aatx*n_rx + aarx][re]), cimag(W_MMSE[aatx*n_rx + aarx][re]), max);\n\n#endif\n      }\n\n  mult_mmse_rxdataF(W_MMSE,\n                    rxdataF_ext_flcpx,\n                    n_tx,\n                    n_rx,\n                    length,\n                    start_point);\n  mult_mmse_chan_est(W_MMSE,\n                     H,\n                     n_tx,\n                     n_rx,\n                     length,\n                     start_point);\n  float_to_rxdataF(rxdataF_ext,\n                   rxdataF_ext_flcpx,\n                   n_tx,\n                   n_rx,\n                   length,\n                   start_point);\n  float_to_chan_est(dl_ch_estimates_ext,\n                    H,\n                    n_tx,\n                    n_rx,\n                    length,\n                    start_point);\n  free(H_re);\n  free(W_MMSE);\n  free(W_MMSE_re);\n}\n\n\nvoid dlsch_channel_aver_band(int **dl_ch_estimates_ext,\n                             LTE_DL_FRAME_PARMS *frame_parms,\n                             struct complex32 *chan_avg,\n                             unsigned char symbol,\n                             unsigned short nb_rb) {\n#if defined(__x86_64__)||defined(__i386__)\n  short rb;\n  unsigned char aatx,aarx,nre=12,symbol_mod;\n  __m128i *dl_ch128, avg128D;\n  int32_t chan_est_avg[4];\n  symbol_mod = (symbol>=(7-frame_parms->Ncp)) ? symbol-(7-frame_parms->Ncp) : symbol;\n\n  if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->nb_antenna_ports_eNB!=1))\n    nre=8;\n  else if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->nb_antenna_ports_eNB==1))\n    nre=10;\n  else\n    nre=12;\n\n  for (aatx=0; aatx<frame_parms->nb_antenna_ports_eNB; aatx++) {\n    for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) {\n      dl_ch128=(__m128i *)&dl_ch_estimates_ext[aatx*frame_parms->nb_antennas_rx + aarx][symbol*frame_parms->N_RB_DL*12];\n      avg128D = _mm_setzero_si128();\n      //  print_shorts(\"avg128D 1\",&avg128D);\n\n      for (rb=0; rb<nb_rb; rb++) {\n        /*  printf(\"symbol %d, ant %d, nre*nrb %d, rb %d \\n\", symbol, aatx*frame_parms->nb_antennas_rx + aarx, nb_rb*nre, rb);\n          print_shorts(\"aver dl_ch128\",&dl_ch128[0]);\n          print_shorts(\"aver dl_ch128\",&dl_ch128[1]);\n          print_shorts(\"aver dl_ch128\",&dl_ch128[2]);\n        avg128D = _mm_add_epi16(avg128D, dl_ch128[0]);*/\n        //print_shorts(\"avg128D 2\",&avg128D);\n        avg128D = _mm_add_epi16(avg128D, dl_ch128[1]);\n        //  print_shorts(\"avg128D 3\",&avg128D);\n\n        if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->nb_antenna_ports_eNB!=1)) {\n          dl_ch128+=2;\n        } else {\n          avg128D = _mm_add_epi16(avg128D,dl_ch128[2]);\n          //  print_shorts(\"avg128D 4\",&avg128D);\n          dl_ch128+=3;\n        }\n      }\n\n      chan_avg[aatx*frame_parms->nb_antennas_rx + aarx].r =(((int16_t *)&avg128D)[0] +\n          ((int16_t *)&avg128D)[2] +\n          ((int16_t *)&avg128D)[4] +\n          ((int16_t *)&avg128D)[6])/(nb_rb*nre);\n      //  printf(\"symb %d chan_avg re [%d] = %d\\n\", symbol, aatx*frame_parms->nb_antennas_rx + aarx, chan_avg[aatx*frame_parms->nb_antennas_rx + aarx].r);\n      chan_avg[aatx*frame_parms->nb_antennas_rx + aarx].i =(((int16_t *)&avg128D)[1] +\n          ((int16_t *)&avg128D)[3] +\n          ((int16_t *)&avg128D)[5] +\n          ((int16_t *)&avg128D)[7])/(nb_rb*nre);\n      //  printf(\"symb %d chan_avg im [%d] = %d\\n\", symbol, aatx*frame_parms->nb_antennas_rx + aarx, chan_avg[aatx*frame_parms->nb_antennas_rx + aarx].i);\n      //printf(\"symb %d chan_avg im [%d] = %d\\n\", symbol, aatx*frame_parms->nb_antennas_rx + aarx, chan_avg[aatx*frame_parms->nb_antennas_rx + aarx].i);\n      chan_est_avg[aatx*frame_parms->nb_antennas_rx + aarx] = (((int32_t)chan_avg[aatx*frame_parms->nb_antennas_rx + aarx].i)<<16)|(((int32_t)chan_avg[aatx*frame_parms->nb_antennas_rx + aarx].r) & 0xffff);\n      //printf(\"symb %d chan_est_avg [%d] = %d\\n\", symbol, aatx*frame_parms->nb_antennas_rx + aarx, chan_est_avg[aatx*frame_parms->nb_antennas_rx + aarx]);\n      dl_ch128=(__m128i *)&dl_ch_estimates_ext[aatx*frame_parms->nb_antennas_rx + aarx][symbol*frame_parms->N_RB_DL*12];\n\n      for (rb=0; rb<nb_rb; rb++) {\n        dl_ch128[0] = _mm_set1_epi32(chan_est_avg[aatx*frame_parms->nb_antennas_rx + aarx]);\n        dl_ch128[1] = _mm_set1_epi32(chan_est_avg[aatx*frame_parms->nb_antennas_rx + aarx]);\n\n        if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->nb_antenna_ports_eNB!=1)) {\n          dl_ch128+=2;\n        } else {\n          dl_ch128[2] = _mm_set1_epi32(chan_est_avg[aatx*frame_parms->nb_antennas_rx + aarx]);\n          dl_ch128+=3;\n        }\n      }\n    }\n  }\n\n  _mm_empty();\n  _m_empty();\n#elif defined(__arm__)\n#endif\n}\n\nvoid rxdataF_to_float(int32_t **rxdataF_ext,\n                      float complex **rxdataF_f,\n                      int n_rx,\n                      int length,\n                      int start_point) {\n  short re;\n  int aarx;\n  int16_t imag;\n  int16_t real;\n\n  for (aarx=0; aarx<n_rx; aarx++) {\n    for (re=0; re<length; re++) {\n      imag = (int16_t) (rxdataF_ext[aarx][start_point + re] >> 16);\n      real = (int16_t) (rxdataF_ext[aarx][start_point + re] & 0xffff);\n      rxdataF_f[aarx][re] = (float)(real/(32768.0)) + I*(float)(imag/(32768.0));\n#ifdef DEBUG_MMSE\n\n      if (re==0) {\n        printf(\"rxdataF_to_float: aarx = %d, real= %d, imag = %d\\n\", aarx, real, imag);\n        //printf(\"rxdataF_to_float: rxdataF_ext[%d][%d] = %d\\n\", aarx, start_point + re, rxdataF_ext[aarx][start_point + re]);\n        //printf(\"rxdataF_to_float: ant %d, re = %d, rxdataF_f real = %f, rxdataF_f imag = %f \\n\", aarx, re, creal(rxdataF_f[aarx][re]), cimag(rxdataF_f[aarx][re]));\n      }\n\n#endif\n    }\n  }\n}\n\n\n\nvoid chan_est_to_float(int32_t **dl_ch_estimates_ext,\n                       float complex **dl_ch_estimates_ext_f,\n                       int n_tx,\n                       int n_rx,\n                       int length,\n                       int start_point) {\n  short re;\n  int aatx,aarx;\n  int16_t imag;\n  int16_t real;\n\n  for (aatx=0; aatx<n_tx; aatx++) {\n    for (aarx=0; aarx<n_rx; aarx++) {\n      for (re=0; re<length; re++) {\n        imag = (int16_t) (dl_ch_estimates_ext[aatx*n_rx + aarx][start_point + re] >> 16);\n        real = (int16_t) (dl_ch_estimates_ext[aatx*n_rx + aarx][start_point+ re] & 0xffff);\n        dl_ch_estimates_ext_f[aatx*n_rx + aarx][re] = (float)(real/(32768.0)) + I*(float)(imag/(32768.0));\n#ifdef DEBUG_MMSE\n\n        if (re==0) {\n          printf(\"ant %d, re = %d, real = %d, imag = %d \\n\", aatx*n_rx + aarx, re, real, imag);\n          printf(\"ant %d, re = %d, real = %f, imag = %f \\n\", aatx*n_rx + aarx, re, creal(dl_ch_estimates_ext_f[aatx*n_rx + aarx][re]), cimag(dl_ch_estimates_ext_f[aatx*n_rx + aarx][re]));\n        }\n\n#endif\n      }\n    }\n  }\n}\n\nvoid float_to_chan_est(int32_t **dl_ch_estimates_ext,\n                       float complex **dl_ch_estimates_ext_f,\n                       int n_tx,\n                       int n_rx,\n                       int length,\n                       int start_point) {\n  short re;\n  int aarx, aatx;\n  int16_t imag;\n  int16_t real;\n\n  for (aatx=0; aatx<n_tx; aatx++) {\n    for (aarx=0; aarx<n_rx; aarx++) {\n      for (re=0; re<length; re++) {\n        if (cimag(dl_ch_estimates_ext_f[aatx*n_rx + aarx][re])<-1)\n          imag = 0x8000;\n        else if (cimag(dl_ch_estimates_ext_f[aatx*n_rx + aarx][re])>=1)\n          imag = 0x7FFF;\n        else\n          imag = cimag(dl_ch_estimates_ext_f[aatx*n_rx + aarx][re])*32768;\n\n        if (creal(dl_ch_estimates_ext_f[aatx*n_rx + aarx][re])<-1)\n          real = 0x8000;\n        else if (creal(dl_ch_estimates_ext_f[aatx*n_rx + aarx][re])>=1)\n          real = 0x7FFF;\n        else\n          real = creal(dl_ch_estimates_ext_f[aatx*n_rx + aarx][re])*32768;\n\n        dl_ch_estimates_ext[aatx*n_rx + aarx][start_point + re] = (((int32_t)imag)<<16)|((int32_t)real & 0xffff);\n#ifdef DEBUG_MMSE\n\n        if (re==0) {\n          printf(\" float_to_chan_est: chan est real = %f, chan est imag = %f\\n\",creal(dl_ch_estimates_ext_f[aatx*n_rx + aarx][re]), cimag(dl_ch_estimates_ext_f[aatx*n_rx + aarx][re]));\n          printf(\"float_to_chan_est: real fixed = %d, imag fixed = %d\\n\", real, imag);\n          printf(\"float_to_chan_est: ant %d, re = %d, dl_ch_estimates_ext = %d \\n\", aatx*n_rx + aarx, re,  dl_ch_estimates_ext[aatx*n_rx + aarx][start_point + re]);\n        }\n\n#endif\n      }\n    }\n  }\n}\n\n\nvoid float_to_rxdataF(int32_t **rxdataF_ext,\n                      float complex **rxdataF_f,\n                      int n_tx,\n                      int n_rx,\n                      int length,\n                      int start_point) {\n  short re;\n  int aarx;\n  int16_t imag;\n  int16_t real;\n\n  for (aarx=0; aarx<n_rx; aarx++) {\n    for (re=0; re<length; re++) {\n      if (cimag(rxdataF_f[aarx][re])<-1)\n        imag = 0x8000;\n      else if (cimag(rxdataF_f[aarx][re])>=1)\n        imag = 0x7FFF;\n      else\n        imag = cimag(rxdataF_f[aarx][re])*32768;\n\n      if (creal(rxdataF_f[aarx][re])<-1)\n        real = 0x8000;\n      else if (creal(rxdataF_f[aarx][re])>=1)\n        real = 0x7FFF;\n      else\n        real = creal(rxdataF_f[aarx][re])*32768;\n\n      rxdataF_ext[aarx][start_point + re] = (((int32_t)imag)<<16)|(((int32_t)real) & 0xffff);\n#ifdef DEBUG_MMSE\n\n      if (re==0) {\n        printf(\" float_to_rxdataF: real = %f, imag = %f\\n\",creal(rxdataF_f[aarx][re]), cimag(rxdataF_f[aarx][re]));\n        printf(\"float_to_rxdataF: real fixed = %d, imag fixed = %d\\n\", real, imag);\n        printf(\"float_to_rxdataF: ant %d, re = %d, rxdataF_ext = %d \\n\", aarx, re,  rxdataF_ext[aarx][start_point + re]);\n      }\n\n#endif\n    }\n  }\n}\n\n\nvoid mult_mmse_rxdataF(float complex **Wmmse,\n                       float complex **rxdataF_ext_f,\n                       int n_tx,\n                       int n_rx,\n                       int length,\n                       int start_point) {\n  short re;\n  int aarx, aatx;\n  float complex *rxdata_re =  malloc(n_rx*sizeof(float complex));\n  float complex *rxdata_mmse_re =  malloc(n_rx*sizeof(float complex));\n  float complex *Wmmse_re =  malloc(n_tx*n_rx*sizeof(float complex));\n\n  for (re=0; re<length; re++) {\n    for (aarx=0; aarx<n_rx; aarx++) {\n      rxdata_re[aarx] = rxdataF_ext_f[aarx][re];\n#ifdef DEBUG_MMSE\n\n      if (re==0)\n        printf(\"mult_mmse_rxdataF before: rxdata_re[%d] = (%f, %f)\\n\", aarx, creal(rxdata_re[aarx]), cimag(rxdata_re[aarx]));\n\n#endif\n    }\n\n    for (aatx=0; aatx<n_tx; aatx++) {\n      for (aarx=0; aarx<n_rx; aarx++) {\n        Wmmse_re[aatx*n_rx + aarx] = Wmmse[aatx*n_rx + aarx][re];\n      }\n    }\n\n    mutl_matrix_matrix_col_based(Wmmse_re, rxdata_re, n_rx, n_tx, n_rx, 1, rxdata_mmse_re);\n\n    for (aarx=0; aarx<n_rx; aarx++) {\n      rxdataF_ext_f[aarx][re] = rxdata_mmse_re[aarx];\n#ifdef DEBUG_MMSE\n\n      if (re==0)\n        printf(\"mult_mmse_rxdataF after: rxdataF_ext_f[%d] = (%f, %f)\\n\", aarx, creal(rxdataF_ext_f[aarx][re]), cimag(rxdataF_ext_f[aarx][re]));\n\n#endif\n    }\n  }\n\n  free(rxdata_re);\n  free(rxdata_mmse_re);\n  free(Wmmse_re);\n}\n\nvoid mult_mmse_chan_est(float complex **Wmmse,\n                        float complex **dl_ch_estimates_ext_f,\n                        int n_tx,\n                        int n_rx,\n                        int length,\n                        int start_point) {\n  short re;\n  int aarx, aatx;\n  float complex *chan_est_re =  malloc(n_tx*n_rx*sizeof(float complex));\n  float complex *chan_est_mmse_re =  malloc(n_tx*n_rx*sizeof(float complex));\n  float complex *Wmmse_re =  malloc(n_tx*n_rx*sizeof(float complex));\n\n  for (re=0; re<length; re++) {\n    for (aatx=0; aatx<n_tx; aatx++) {\n      for (aarx=0; aarx<n_rx; aarx++) {\n        chan_est_re[aatx*n_rx + aarx] = dl_ch_estimates_ext_f[aatx*n_rx + aarx][re];\n        Wmmse_re[aatx*n_rx + aarx] = Wmmse[aatx*n_rx + aarx][re];\n#ifdef DEBUG_MMSE\n\n        if (re==0)\n          printf(\"mult_mmse_chan_est: chan_est_re[%d] = (%f, %f)\\n\", aatx*n_rx + aarx, creal(chan_est_re[aatx*n_rx + aarx]), cimag(chan_est_re[aatx*n_rx + aarx]));\n\n#endif\n      }\n    }\n\n    mutl_matrix_matrix_col_based(Wmmse_re, chan_est_re, n_rx, n_tx, n_rx, n_tx, chan_est_mmse_re);\n\n    for (aatx=0; aatx<n_tx; aatx++) {\n      for (aarx=0; aarx<n_rx; aarx++) {\n        dl_ch_estimates_ext_f[aatx*n_rx + aarx][re] = chan_est_mmse_re[aatx*n_rx + aarx];\n#ifdef DEBUG_MMSE\n\n        if (re==0)\n          printf(\"mult_mmse_chan_est: dl_ch_estimates_ext_f[%d][%d] = (%f, %f)\\n\", aatx*n_rx + aarx, re, creal(dl_ch_estimates_ext_f[aatx*n_rx + aarx][re]), cimag(dl_ch_estimates_ext_f[aatx*n_rx + aarx][re]));\n\n#endif\n      }\n    }\n  }\n\n  free(Wmmse_re);\n  free(chan_est_re);\n  free(chan_est_mmse_re);\n}\n\n\n\n\n\n//compute average channel_level of effective (precoded) channel\nvoid dlsch_channel_level_TM34(int **dl_ch_estimates_ext,\n                              LTE_DL_FRAME_PARMS *frame_parms,\n                              unsigned char *pmi_ext,\n                              int *avg_0,\n                              int *avg_1,\n                              uint8_t symbol,\n                              unsigned short nb_rb,\n                              unsigned int mmse_flag,\n                              MIMO_mode_t mimo_mode) {\n#if defined(__x86_64__)||defined(__i386__)\n  short rb;\n  unsigned char aarx,nre=12,symbol_mod;\n  __m128i *dl_ch0_128,*dl_ch1_128, dl_ch0_128_tmp, dl_ch1_128_tmp, avg_0_128D, avg_1_128D;\n  symbol_mod = (symbol>=(7-frame_parms->Ncp)) ? symbol-(7-frame_parms->Ncp) : symbol;\n  //clear average level\n  // avg_0_128D = _mm_setzero_si128();\n  // avg_1_128D = _mm_setzero_si128();\n  avg_0[0] = 0;\n  avg_0[1] = 0;\n  avg_1[0] = 0;\n  avg_1[1] = 0;\n  // 5 is always a symbol with no pilots for both normal and extended prefix\n\n  if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->nb_antenna_ports_eNB!=1))\n    nre=8;\n  else if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->nb_antenna_ports_eNB==1))\n    nre=10;\n  else\n    nre=12;\n\n  for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) {\n    dl_ch0_128 = (__m128i *)&dl_ch_estimates_ext[aarx][symbol*frame_parms->N_RB_DL*12];\n    dl_ch1_128 = (__m128i *)&dl_ch_estimates_ext[2+aarx][symbol*frame_parms->N_RB_DL*12];\n    avg_0_128D = _mm_setzero_si128();\n    avg_1_128D = _mm_setzero_si128();\n\n    for (rb=0; rb<nb_rb; rb++) {\n      // printf(\"rb %d : \\n\",rb);\n      //print_shorts(\"ch0\\n\",&dl_ch0_128[0]);\n      //print_shorts(\"ch1\\n\",&dl_ch1_128[0]);\n      dl_ch0_128_tmp = _mm_load_si128(&dl_ch0_128[0]);\n      dl_ch1_128_tmp = _mm_load_si128(&dl_ch1_128[0]);\n\n      if (mmse_flag == 0) {\n        if (mimo_mode==LARGE_CDD)\n          prec2A_TM3_128(&dl_ch0_128_tmp,&dl_ch1_128_tmp);\n        else if (mimo_mode==DUALSTREAM_UNIFORM_PRECODING1)\n          prec2A_TM4_128(0,&dl_ch0_128_tmp,&dl_ch1_128_tmp);\n        else if (mimo_mode==DUALSTREAM_UNIFORM_PRECODINGj)\n          prec2A_TM4_128(1,&dl_ch0_128_tmp,&dl_ch1_128_tmp);\n        else if (mimo_mode==DUALSTREAM_PUSCH_PRECODING)\n          prec2A_TM4_128(pmi_ext[rb],&dl_ch0_128_tmp,&dl_ch1_128_tmp);\n      }\n\n      //      mmtmpD0 = _mm_madd_epi16(dl_ch0_128_tmp,dl_ch0_128_tmp);\n      avg_0_128D = _mm_add_epi32(avg_0_128D,_mm_madd_epi16(dl_ch0_128_tmp,dl_ch0_128_tmp));\n      avg_1_128D = _mm_add_epi32(avg_1_128D,_mm_madd_epi16(dl_ch1_128_tmp,dl_ch1_128_tmp));\n      dl_ch0_128_tmp = _mm_load_si128(&dl_ch0_128[1]);\n      dl_ch1_128_tmp = _mm_load_si128(&dl_ch1_128[1]);\n\n      if (mmse_flag == 0) {\n        if (mimo_mode==LARGE_CDD)\n          prec2A_TM3_128(&dl_ch0_128_tmp,&dl_ch1_128_tmp);\n        else if (mimo_mode==DUALSTREAM_UNIFORM_PRECODING1)\n          prec2A_TM4_128(0,&dl_ch0_128_tmp,&dl_ch1_128_tmp);\n        else if (mimo_mode==DUALSTREAM_UNIFORM_PRECODINGj)\n          prec2A_TM4_128(1,&dl_ch0_128_tmp,&dl_ch1_128_tmp);\n        else if (mimo_mode==DUALSTREAM_PUSCH_PRECODING)\n          prec2A_TM4_128(pmi_ext[rb],&dl_ch0_128_tmp,&dl_ch1_128_tmp);\n      }\n\n      //      mmtmpD1 = _mm_madd_epi16(dl_ch0_128_tmp,dl_ch0_128_tmp);\n      avg_0_128D = _mm_add_epi32(avg_0_128D,_mm_madd_epi16(dl_ch0_128_tmp,dl_ch0_128_tmp));\n      avg_1_128D = _mm_add_epi32(avg_1_128D,_mm_madd_epi16(dl_ch1_128_tmp,dl_ch1_128_tmp));\n\n      if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->nb_antenna_ports_eNB!=1)) {\n        dl_ch0_128+=2;\n        dl_ch1_128+=2;\n      } else {\n        dl_ch0_128_tmp = _mm_load_si128(&dl_ch0_128[2]);\n        dl_ch1_128_tmp = _mm_load_si128(&dl_ch1_128[2]);\n\n        if (mmse_flag == 0) {\n          if (mimo_mode==LARGE_CDD)\n            prec2A_TM3_128(&dl_ch0_128_tmp,&dl_ch1_128_tmp);\n          else if (mimo_mode==DUALSTREAM_UNIFORM_PRECODING1)\n            prec2A_TM4_128(0,&dl_ch0_128_tmp,&dl_ch1_128_tmp);\n          else if (mimo_mode==DUALSTREAM_UNIFORM_PRECODINGj)\n            prec2A_TM4_128(1,&dl_ch0_128_tmp,&dl_ch1_128_tmp);\n          else if (mimo_mode==DUALSTREAM_PUSCH_PRECODING)\n            prec2A_TM4_128(pmi_ext[rb],&dl_ch0_128_tmp,&dl_ch1_128_tmp);\n        }\n\n        //      mmtmpD2 = _mm_madd_epi16(dl_ch0_128_tmp,dl_ch0_128_tmp);\n        avg_1_128D = _mm_add_epi32(avg_1_128D,_mm_madd_epi16(dl_ch1_128_tmp,dl_ch1_128_tmp));\n        avg_0_128D = _mm_add_epi32(avg_0_128D,_mm_madd_epi16(dl_ch0_128_tmp,dl_ch0_128_tmp));\n        dl_ch0_128+=3;\n        dl_ch1_128+=3;\n      }\n    }\n\n    avg_0[aarx] = (((int *)&avg_0_128D)[0])/(nb_rb*nre) +\n                  (((int *)&avg_0_128D)[1])/(nb_rb*nre) +\n                  (((int *)&avg_0_128D)[2])/(nb_rb*nre) +\n                  (((int *)&avg_0_128D)[3])/(nb_rb*nre);\n    //  printf(\"From Chan_level aver stream 0 %d =%d\\n\", aarx, avg_0[aarx]);\n    avg_1[aarx] = (((int *)&avg_1_128D)[0])/(nb_rb*nre) +\n                  (((int *)&avg_1_128D)[1])/(nb_rb*nre) +\n                  (((int *)&avg_1_128D)[2])/(nb_rb*nre) +\n                  (((int *)&avg_1_128D)[3])/(nb_rb*nre);\n    //    printf(\"From Chan_level aver stream 1 %d =%d\\n\", aarx, avg_1[aarx]);\n  }\n\n  //avg_0[0] = max(avg_0[0],avg_0[1]);\n  //avg_1[0] = max(avg_1[0],avg_1[1]);\n  //avg_0[0]= max(avg_0[0], avg_1[0]);\n  avg_0[0] = avg_0[0] + avg_0[1];\n  // printf(\"From Chan_level aver stream 0 final =%d\\n\", avg_0[0]);\n  avg_1[0] = avg_1[0] + avg_1[1];\n  // printf(\"From Chan_level aver stream 1 final =%d\\n\", avg_1[0]);\n  avg_0[0] = min (avg_0[0], avg_1[0]);\n  avg_1[0] = avg_0[0];\n  _mm_empty();\n  _m_empty();\n#elif defined(__arm__)\n#endif\n}\n\n//compute average channel_level of effective (precoded) channel\nvoid dlsch_channel_level_TM56(int **dl_ch_estimates_ext,\n                              LTE_DL_FRAME_PARMS *frame_parms,\n                              unsigned char *pmi_ext,\n                              int *avg,\n                              uint8_t symbol,\n                              unsigned short nb_rb) {\n#if defined(__x86_64__)||defined(__i386__)\n  short rb;\n  unsigned char aarx,nre=12,symbol_mod;\n  __m128i *dl_ch0_128,*dl_ch1_128, dl_ch0_128_tmp, dl_ch1_128_tmp,avg128D;\n  symbol_mod = (symbol>=(7-frame_parms->Ncp)) ? symbol-(7-frame_parms->Ncp) : symbol;\n  //clear average level\n  avg128D = _mm_setzero_si128();\n  avg[0] = 0;\n  avg[1] = 0;\n  // 5 is always a symbol with no pilots for both normal and extended prefix\n\n  if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->nb_antenna_ports_eNB!=1))\n    nre=8;\n  else if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->nb_antenna_ports_eNB==1))\n    nre=10;\n  else\n    nre=12;\n\n  for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) {\n    dl_ch0_128 = (__m128i *)&dl_ch_estimates_ext[aarx][symbol*frame_parms->N_RB_DL*12];\n    dl_ch1_128 = (__m128i *)&dl_ch_estimates_ext[2+aarx][symbol*frame_parms->N_RB_DL*12];\n\n    for (rb=0; rb<nb_rb; rb++) {\n      dl_ch0_128_tmp = _mm_load_si128(&dl_ch0_128[0]);\n      dl_ch1_128_tmp = _mm_load_si128(&dl_ch1_128[0]);\n      prec2A_TM56_128(pmi_ext[rb],&dl_ch0_128_tmp,&dl_ch1_128_tmp);\n      //      mmtmpD0 = _mm_madd_epi16(dl_ch0_128_tmp,dl_ch0_128_tmp);\n      avg128D = _mm_add_epi32(avg128D,_mm_madd_epi16(dl_ch0_128_tmp,dl_ch0_128_tmp));\n      dl_ch0_128_tmp = _mm_load_si128(&dl_ch0_128[1]);\n      dl_ch1_128_tmp = _mm_load_si128(&dl_ch1_128[1]);\n      prec2A_TM56_128(pmi_ext[rb],&dl_ch0_128_tmp,&dl_ch1_128_tmp);\n      //      mmtmpD1 = _mm_madd_epi16(dl_ch0_128_tmp,dl_ch0_128_tmp);\n      avg128D = _mm_add_epi32(avg128D,_mm_madd_epi16(dl_ch0_128_tmp,dl_ch0_128_tmp));\n\n      if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->nb_antenna_ports_eNB!=1)) {\n        dl_ch0_128+=2;\n        dl_ch1_128+=2;\n      } else {\n        dl_ch0_128_tmp = _mm_load_si128(&dl_ch0_128[2]);\n        dl_ch1_128_tmp = _mm_load_si128(&dl_ch1_128[2]);\n        prec2A_TM56_128(pmi_ext[rb],&dl_ch0_128_tmp,&dl_ch1_128_tmp);\n        //      mmtmpD2 = _mm_madd_epi16(dl_ch0_128_tmp,dl_ch0_128_tmp);\n        avg128D = _mm_add_epi32(avg128D,_mm_madd_epi16(dl_ch0_128_tmp,dl_ch0_128_tmp));\n        dl_ch0_128+=3;\n        dl_ch1_128+=3;\n      }\n    }\n\n    avg[aarx] = (((int *)&avg128D)[0])/(nb_rb*nre) +\n                (((int *)&avg128D)[1])/(nb_rb*nre) +\n                (((int *)&avg128D)[2])/(nb_rb*nre) +\n                (((int *)&avg128D)[3])/(nb_rb*nre);\n  }\n\n  // choose maximum of the 2 effective channels\n  avg[0] = cmax(avg[0],avg[1]);\n  _mm_empty();\n  _m_empty();\n#elif defined(__arm__)\n#endif\n}\n\n//compute average channel_level for TM7\nvoid dlsch_channel_level_TM7(int **dl_bf_ch_estimates_ext,\n                             LTE_DL_FRAME_PARMS *frame_parms,\n                             int *avg,\n                             uint8_t symbol,\n                             unsigned short nb_rb) {\n#if defined(__x86_64__)||defined(__i386__)\n  short rb;\n  unsigned char aatx,aarx,nre=12,symbol_mod;\n  __m128i *dl_ch128,avg128D;\n  symbol_mod = (symbol>=(7-frame_parms->Ncp)) ? symbol-(7-frame_parms->Ncp) : symbol;\n\n  for (aatx=0; aatx<frame_parms->nb_antenna_ports_eNB; aatx++)\n    for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) {\n      //clear average level\n      avg128D = _mm_setzero_si128();\n      // 5 is always a symbol with no pilots for both normal and extended prefix\n      dl_ch128=(__m128i *)&dl_bf_ch_estimates_ext[(aatx<<1)+aarx][symbol*frame_parms->N_RB_DL*12];\n\n      for (rb=0; rb<nb_rb; rb++) {\n        //  printf(\"rb %d : \",rb);\n        //  print_shorts(\"ch\",&dl_ch128[0]);\n        avg128D = _mm_add_epi32(avg128D,_mm_madd_epi16(dl_ch128[0],dl_ch128[0]));\n        avg128D = _mm_add_epi32(avg128D,_mm_madd_epi16(dl_ch128[1],dl_ch128[1]));\n\n        if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->nb_antenna_ports_eNB!=1)) {\n          dl_ch128+=2;\n        } else {\n          avg128D = _mm_add_epi32(avg128D,_mm_madd_epi16(dl_ch128[2],dl_ch128[2]));\n          dl_ch128+=3;\n        }\n\n        /*\n          if (rb==0) {\n          print_shorts(\"dl_ch128\",&dl_ch128[0]);\n          print_shorts(\"dl_ch128\",&dl_ch128[1]);\n          print_shorts(\"dl_ch128\",&dl_ch128[2]);\n          }\n        */\n      }\n\n      if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1))))\n        nre=10;\n      else if ((frame_parms->Ncp==0) && (symbol==3 || symbol==6 || symbol==9 || symbol==12))\n        nre=9;\n      else if ((frame_parms->Ncp==1) && (symbol==4 || symbol==7 || symbol==9))\n        nre=8;\n      else\n        nre=12;\n\n      avg[(aatx<<1)+aarx] = (((int *)&avg128D)[0] +\n                             ((int *)&avg128D)[1] +\n                             ((int *)&avg128D)[2] +\n                             ((int *)&avg128D)[3])/(nb_rb*nre);\n      //            printf(\"Channel level : %d\\n\",avg[(aatx<<1)+aarx]);\n    }\n\n  _mm_empty();\n  _m_empty();\n#elif defined(__arm__)\n#endif\n}\n//#define ONE_OVER_2_Q15 16384\nvoid dlsch_alamouti(LTE_DL_FRAME_PARMS *frame_parms,\n                    int **rxdataF_comp,\n                    int **dl_ch_mag,\n                    int **dl_ch_magb,\n                    unsigned char symbol,\n                    unsigned short nb_rb) {\n#if defined(__x86_64__)||defined(__i386__)\n  short *rxF0,*rxF1;\n  __m128i *ch_mag0,*ch_mag1,*ch_mag0b,*ch_mag1b, *rxF0_128;\n  unsigned char rb,re;\n  int jj = (symbol*frame_parms->N_RB_DL*12);\n  uint8_t symbol_mod = (symbol>=(7-frame_parms->Ncp)) ? symbol-(7-frame_parms->Ncp) : symbol;\n  uint8_t pilots = ((symbol_mod==0)||(symbol_mod==(4-frame_parms->Ncp))) ? 1 : 0;\n  rxF0_128 = (__m128i *) &rxdataF_comp[0][jj];\n  //amp = _mm_set1_epi16(ONE_OVER_2_Q15);\n  //    printf(\"Doing alamouti!\\n\");\n  rxF0     = (short *)&rxdataF_comp[0][jj]; //tx antenna 0  h0*y\n  rxF1     = (short *)&rxdataF_comp[2][jj]; //tx antenna 1  h1*y\n  ch_mag0 = (__m128i *)&dl_ch_mag[0][jj];\n  ch_mag1 = (__m128i *)&dl_ch_mag[2][jj];\n  ch_mag0b = (__m128i *)&dl_ch_magb[0][jj];\n  ch_mag1b = (__m128i *)&dl_ch_magb[2][jj];\n\n  for (rb=0; rb<nb_rb; rb++) {\n    for (re=0; re<((pilots==0)?12:8); re+=2) {\n      // Alamouti RX combining\n      //      printf(\"Alamouti: symbol %d, rb %d, re %d: rxF0 (%d,%d,%d,%d), rxF1 (%d,%d,%d,%d)\\n\",symbol,rb,re,rxF0[0],rxF0[1],rxF0[2],rxF0[3],rxF1[0],rxF1[1],rxF1[2],rxF1[3]);\n      rxF0[0] = rxF0[0] + rxF1[2];\n      rxF0[1] = rxF0[1] - rxF1[3];\n      rxF0[2] = rxF0[2] - rxF1[0];\n      rxF0[3] = rxF0[3] + rxF1[1];\n      //      printf(\"Alamouti: rxF0 after (%d,%d,%d,%d)\\n\",rxF0[0],rxF0[1],rxF0[2],rxF0[3]);\n      rxF0+=4;\n      rxF1+=4;\n    }\n\n    // compute levels for 16QAM or 64 QAM llr unit\n    ch_mag0[0] = _mm_adds_epi16(ch_mag0[0],ch_mag1[0]);\n    ch_mag0[1] = _mm_adds_epi16(ch_mag0[1],ch_mag1[1]);\n    ch_mag0b[0] = _mm_adds_epi16(ch_mag0b[0],ch_mag1b[0]);\n    ch_mag0b[1] = _mm_adds_epi16(ch_mag0b[1],ch_mag1b[1]);\n\n    // account for 1/sqrt(2) scaling at transmission\n    //ch_mag0[0] = _mm_srai_epi16(ch_mag0[0],1);\n    //ch_mag0[1] = _mm_srai_epi16(ch_mag0[1],1);\n    //ch_mag0b[0] = _mm_srai_epi16(ch_mag0b[0],1);\n    //ch_mag0b[1] = _mm_srai_epi16(ch_mag0b[1],1);\n\n    //rxF0_128[0] = _mm_mulhi_epi16(rxF0_128[0],amp);\n    //rxF0_128[0] = _mm_slli_epi16(rxF0_128[0],1);\n    //rxF0_128[1] = _mm_mulhi_epi16(rxF0_128[1],amp);\n    //rxF0_128[1] = _mm_slli_epi16(rxF0_128[1],1);\n\n    //rxF0_128[0] = _mm_srai_epi16(rxF0_128[0],1);\n    //rxF0_128[1] = _mm_srai_epi16(rxF0_128[1],1);\n\n    if (pilots==0) {\n      ch_mag0[2] = _mm_adds_epi16(ch_mag0[2],ch_mag1[2]);\n      ch_mag0b[2] = _mm_adds_epi16(ch_mag0b[2],ch_mag1b[2]);\n      //ch_mag0[2] = _mm_srai_epi16(ch_mag0[2],1);\n      //ch_mag0b[2] = _mm_srai_epi16(ch_mag0b[2],1);\n      //rxF0_128[2] = _mm_mulhi_epi16(rxF0_128[2],amp);\n      //rxF0_128[2] = _mm_slli_epi16(rxF0_128[2],1);\n      //rxF0_128[2] = _mm_srai_epi16(rxF0_128[2],1);\n      ch_mag0+=3;\n      ch_mag1+=3;\n      ch_mag0b+=3;\n      ch_mag1b+=3;\n      rxF0_128+=3;\n    } else {\n      ch_mag0+=2;\n      ch_mag1+=2;\n      ch_mag0b+=2;\n      ch_mag1b+=2;\n      rxF0_128+=2;\n    }\n  }\n\n  _mm_empty();\n  _m_empty();\n#elif defined(__arm__)\n#endif\n}\n\n\n//==============================================================================================\n// Extraction functions\n//==============================================================================================\n\nunsigned short dlsch_extract_rbs_single(int **rxdataF,\n                                        int **dl_ch_estimates,\n                                        int **rxdataF_ext,\n                                        int **dl_ch_estimates_ext,\n                                        unsigned short pmi,\n                                        unsigned char *pmi_ext,\n                                        unsigned int *rb_alloc,\n                                        unsigned char symbol,\n                                        unsigned char subframe,\n                                        uint32_t high_speed_flag,\n                                        LTE_DL_FRAME_PARMS *frame_parms) {\n  unsigned short rb,nb_rb=0;\n  unsigned char rb_alloc_ind;\n  unsigned char i,aarx,l,nsymb,skip_half=0,sss_symb,pss_symb=0;\n  int *dl_ch0,*dl_ch0_ext,*rxF,*rxF_ext;\n  unsigned char symbol_mod,pilots=0,j=0,poffset=0;\n  symbol_mod = (symbol>=(7-frame_parms->Ncp)) ? symbol-(7-frame_parms->Ncp) : symbol;\n  pilots = ((symbol_mod==0)||(symbol_mod==(4-frame_parms->Ncp))) ? 1 : 0;\n  l=symbol;\n  nsymb = (frame_parms->Ncp==NORMAL) ? 14:12;\n\n  if (frame_parms->frame_type == TDD) {  // TDD\n    sss_symb = nsymb-1;\n    pss_symb = 2;\n  } else {\n    sss_symb = (nsymb>>1)-2;\n    pss_symb = (nsymb>>1)-1;\n  }\n\n  if (symbol_mod==(4-frame_parms->Ncp))\n    poffset=3;\n\n  for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) {\n    if (high_speed_flag == 1)\n      dl_ch0     = &dl_ch_estimates[aarx][5+(symbol*(frame_parms->ofdm_symbol_size))];\n    else\n      dl_ch0     = &dl_ch_estimates[aarx][5];\n\n    dl_ch0_ext = &dl_ch_estimates_ext[aarx][symbol*(frame_parms->N_RB_DL*12)];\n    rxF_ext   = &rxdataF_ext[aarx][symbol*(frame_parms->N_RB_DL*12)];\n    rxF       = &rxdataF[aarx][(frame_parms->first_carrier_offset + (symbol*(frame_parms->ofdm_symbol_size)))];\n\n    if ((frame_parms->N_RB_DL&1) == 0)  // even number of RBs\n      for (rb=0; rb<frame_parms->N_RB_DL; rb++) {\n        if (rb < 32)\n          rb_alloc_ind = (rb_alloc[0]>>rb) & 1;\n        else if (rb < 64)\n          rb_alloc_ind = (rb_alloc[1]>>(rb-32)) & 1;\n        else if (rb < 96)\n          rb_alloc_ind = (rb_alloc[2]>>(rb-64)) & 1;\n        else if (rb < 100)\n          rb_alloc_ind = (rb_alloc[3]>>(rb-96)) & 1;\n        else\n          rb_alloc_ind = 0;\n\n        if (rb_alloc_ind == 1)\n          nb_rb++;\n\n        // For second half of RBs skip DC carrier\n        if (rb==(frame_parms->N_RB_DL>>1)) {\n          rxF       = &rxdataF[aarx][(1 + (symbol*(frame_parms->ofdm_symbol_size)))];\n          //dl_ch0++;\n        }\n\n        // PBCH\n        if ((subframe==0) && (rb>=((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l>=nsymb>>1) && (l<((nsymb>>1) + 4))) {\n          rb_alloc_ind = 0;\n        }\n\n        //SSS\n        if (((subframe==0)||(subframe==5)) && (rb>=((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l==sss_symb) ) {\n          rb_alloc_ind = 0;\n        }\n\n        if (frame_parms->frame_type == FDD) {\n          //PSS\n          if (((subframe==0)||(subframe==5)) && (rb>=((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb) ) {\n            rb_alloc_ind = 0;\n          }\n        }\n\n        if ((frame_parms->frame_type == TDD) &&\n            (subframe==6)) { //TDD Subframe 6\n          if ((rb>=((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb) ) {\n            rb_alloc_ind = 0;\n          }\n        }\n\n        if (rb_alloc_ind==1) {\n          *pmi_ext = (pmi>>((rb>>2)<<1))&3;\n          memcpy(dl_ch0_ext,dl_ch0,12*sizeof(int));\n\n          /*\n            printf(\"rb %d\\n\",rb);\n            for (i=0;i<12;i++)\n            printf(\"(%d %d)\",((short *)dl_ch0)[i<<1],((short*)dl_ch0)[1+(i<<1)]);\n            printf(\"\\n\");\n          */\n          if (pilots==0) {\n            for (i=0; i<12; i++) {\n              rxF_ext[i]=rxF[i];\n              /*\n                printf(\"%d : (%d,%d)\\n\",(rxF+i-&rxdataF[aarx][( (symbol*(frame_parms->ofdm_symbol_size)))]),\n                ((short*)&rxF[i])[0],((short*)&rxF[i])[1]);*/\n            }\n\n            dl_ch0_ext+=12;\n            rxF_ext+=12;\n          } else {\n            j=0;\n\n            for (i=0; i<12; i++) {\n              if ((i!=(frame_parms->nushift+poffset)) &&\n                  (i!=((frame_parms->nushift+poffset+6)%12))) {\n                rxF_ext[j]=rxF[i];\n                //            printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[j],*(1+(short*)&rxF_ext[j]));\n                dl_ch0_ext[j++]=dl_ch0[i];\n              }\n            }\n\n            dl_ch0_ext+=10;\n            rxF_ext+=10;\n          }\n        }\n\n        dl_ch0+=12;\n        rxF+=12;\n      }\n    else {  // Odd number of RBs\n      for (rb=0; rb<frame_parms->N_RB_DL>>1; rb++) {\n#ifdef DEBUG_DLSCH_DEMOD\n        printf(\"dlch_ext %u\\n\",dl_ch0_ext-&dl_ch_estimates_ext[aarx][0]);\n#endif\n        skip_half=0;\n\n        if (rb < 32)\n          rb_alloc_ind = (rb_alloc[0]>>rb) & 1;\n        else if (rb < 64)\n          rb_alloc_ind = (rb_alloc[1]>>(rb-32)) & 1;\n        else if (rb < 96)\n          rb_alloc_ind = (rb_alloc[2]>>(rb-64)) & 1;\n        else if (rb < 100)\n          rb_alloc_ind = (rb_alloc[3]>>(rb-96)) & 1;\n        else\n          rb_alloc_ind = 0;\n\n        if (rb_alloc_ind == 1)\n          nb_rb++;\n\n        // PBCH\n        if ((subframe==0) && (rb>((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l>=(nsymb>>1)) && (l<((nsymb>>1) + 4))) {\n          rb_alloc_ind = 0;\n        }\n\n        //PBCH subframe 0, symbols nsymb>>1 ... nsymb>>1 + 3\n        if ((subframe==0) && (rb==((frame_parms->N_RB_DL>>1)-3)) && (l>=(nsymb>>1)) && (l<((nsymb>>1) + 4)))\n          skip_half=1;\n        else if ((subframe==0) && (rb==((frame_parms->N_RB_DL>>1)+3)) && (l>=(nsymb>>1)) && (l<((nsymb>>1) + 4)))\n          skip_half=2;\n\n        //SSS\n\n        if (((subframe==0)||(subframe==5)) &&\n            (rb>((frame_parms->N_RB_DL>>1)-3)) &&\n            (rb<((frame_parms->N_RB_DL>>1)+3)) &&\n            (l==sss_symb) ) {\n          rb_alloc_ind = 0;\n        }\n\n        //SSS\n        if (((subframe==0)||(subframe==5)) &&\n            (rb==((frame_parms->N_RB_DL>>1)-3)) &&\n            (l==sss_symb))\n          skip_half=1;\n        else if (((subframe==0)||(subframe==5)) &&\n                 (rb==((frame_parms->N_RB_DL>>1)+3)) &&\n                 (l==sss_symb))\n          skip_half=2;\n\n        //PSS in subframe 0/5 if FDD\n        if (frame_parms->frame_type == FDD) {  //FDD\n          if (((subframe==0)||(subframe==5)) &&\n              (rb>((frame_parms->N_RB_DL>>1)-3)) &&\n              (rb<((frame_parms->N_RB_DL>>1)+3)) &&\n              (l==pss_symb) ) {\n            rb_alloc_ind = 0;\n          }\n\n          if (((subframe==0)||(subframe==5)) && (rb==((frame_parms->N_RB_DL>>1)-3)) && (l==pss_symb))\n            skip_half=1;\n          else if (((subframe==0)||(subframe==5)) && (rb==((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb))\n            skip_half=2;\n        }\n\n        if ((frame_parms->frame_type == TDD) &&\n            (subframe==6)) { //TDD Subframe 6\n          if ((rb>((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb) ) {\n            rb_alloc_ind = 0;\n          }\n\n          if ((rb==((frame_parms->N_RB_DL>>1)-3)) && (l==pss_symb))\n            skip_half=1;\n          else if ((rb==((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb))\n            skip_half=2;\n        }\n\n        if (rb_alloc_ind==1) {\n#ifdef DEBUG_DLSCH_DEMOD\n          printf(\"rb %d/symbol %d (skip_half %d)\\n\",rb,l,skip_half);\n#endif\n\n          if (pilots==0) {\n            //      printf(\"Extracting w/o pilots (symbol %d, rb %d, skip_half %d)\\n\",l,rb,skip_half);\n            if (skip_half==1) {\n              memcpy(dl_ch0_ext,dl_ch0,6*sizeof(int));\n\n              for (i=0; i<6; i++) {\n                rxF_ext[i]=rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i]));\n#endif\n              }\n\n              dl_ch0_ext+=6;\n              rxF_ext+=6;\n            } else if (skip_half==2) {\n              memcpy(dl_ch0_ext,dl_ch0+6,6*sizeof(int));\n\n              for (i=0; i<6; i++) {\n                rxF_ext[i]=rxF[(i+6)];\n#ifdef DEBUG_DLSCH_DEMOD\n                printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i]));\n#endif\n              }\n\n              dl_ch0_ext+=6;\n              rxF_ext+=6;\n            } else {\n              memcpy(dl_ch0_ext,dl_ch0,12*sizeof(int));\n\n              for (i=0; i<12; i++) {\n                rxF_ext[i]=rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i]));\n#endif\n              }\n\n              dl_ch0_ext+=12;\n              rxF_ext+=12;\n            }\n          } else {\n            //      printf(\"Extracting with pilots (symbol %d, rb %d, skip_half %d)\\n\",l,rb,skip_half);\n            j=0;\n\n            if (skip_half==1) {\n              for (i=0; i<6; i++) {\n                if (i!=((frame_parms->nushift+poffset)%6)) {\n                  rxF_ext[j]=rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                  printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[j],*(1+(short *)&rxF_ext[j]));\n#endif\n                  dl_ch0_ext[j++]=dl_ch0[i];\n                }\n              }\n\n              rxF_ext+=5;\n              dl_ch0_ext+=5;\n            } else if (skip_half==2) {\n              for (i=0; i<6; i++) {\n                if (i!=((frame_parms->nushift+poffset)%6)) {\n                  rxF_ext[j]=rxF[(i+6)];\n#ifdef DEBUG_DLSCH_DEMOD\n                  printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[j],*(1+(short *)&rxF_ext[j]));\n#endif\n                  dl_ch0_ext[j++]=dl_ch0[i+6];\n                }\n              }\n\n              dl_ch0_ext+=5;\n              rxF_ext+=5;\n            } else {\n              for (i=0; i<12; i++) {\n                if ((i!=(frame_parms->nushift+poffset)) &&\n                    (i!=((frame_parms->nushift+poffset+6)%12))) {\n                  rxF_ext[j]=rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                  printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[j],*(1+(short *)&rxF_ext[j]));\n#endif\n                  dl_ch0_ext[j++]=dl_ch0[i];\n                }\n              }\n\n              dl_ch0_ext+=10;\n              rxF_ext+=10;\n            }\n          }\n        }\n\n        dl_ch0+=12;\n        rxF+=12;\n      } // first half loop\n\n      // Do middle RB (around DC)\n      if (rb < 32)\n        rb_alloc_ind = (rb_alloc[0]>>rb) & 1;\n      else if (rb < 64)\n        rb_alloc_ind = (rb_alloc[1]>>(rb-32)) & 1;\n      else if (rb < 96)\n        rb_alloc_ind = (rb_alloc[2]>>(rb-64)) & 1;\n      else if (rb < 100)\n        rb_alloc_ind = (rb_alloc[3]>>(rb-96)) & 1;\n      else\n        rb_alloc_ind = 0;\n\n      if (rb_alloc_ind == 1)\n        nb_rb++;\n\n      // PBCH\n\n      if ((subframe==0) &&\n          (l>=(nsymb>>1)) &&\n          (l<((nsymb>>1) + 4))) {\n        rb_alloc_ind = 0;\n      }\n\n      //SSS\n      if (((subframe==0)||(subframe==5)) && (l==sss_symb) ) {\n        rb_alloc_ind = 0;\n      }\n\n      if (frame_parms->frame_type == FDD) {\n        //PSS\n        if (((subframe==0)||(subframe==5)) && (l==pss_symb) ) {\n          rb_alloc_ind = 0;\n        }\n      }\n\n      //PSS\n      if ((frame_parms->frame_type == TDD) &&\n          (subframe==6) &&\n          (l==pss_symb) ) {\n        rb_alloc_ind = 0;\n      }\n\n      //  printf(\"dlch_ext %d\\n\",dl_ch0_ext-&dl_ch_estimates_ext[aarx][0]);\n      //      printf(\"DC rb %d (%p)\\n\",rb,rxF);\n      if (rb_alloc_ind==1) {\n#ifdef DEBUG_DLSCH_DEMOD\n        printf(\"rb %d/symbol %d (skip_half %d)\\n\",rb,l,skip_half);\n#endif\n\n        if (pilots==0) {\n          for (i=0; i<6; i++) {\n            dl_ch0_ext[i]=dl_ch0[i];\n            rxF_ext[i]=rxF[i];\n          }\n\n          rxF       = &rxdataF[aarx][((symbol*(frame_parms->ofdm_symbol_size)))];\n\n          for (; i<12; i++) {\n            dl_ch0_ext[i]=dl_ch0[i];\n            rxF_ext[i]=rxF[(1+i-6)];\n          }\n\n          dl_ch0_ext+=12;\n          rxF_ext+=12;\n        } else { // pilots==1\n          j=0;\n\n          for (i=0; i<6; i++) {\n            if (i!=((frame_parms->nushift+poffset)%6)) {\n              dl_ch0_ext[j]=dl_ch0[i];\n              rxF_ext[j++]=rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n              printf(\"**extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[j-1],*(1+(short *)&rxF_ext[j-1]));\n#endif\n            }\n          }\n\n          rxF       = &rxdataF[aarx][((symbol*(frame_parms->ofdm_symbol_size)))];\n\n          for (; i<12; i++) {\n            if (i!=((frame_parms->nushift+6+poffset)%12)) {\n              dl_ch0_ext[j]=dl_ch0[i];\n              rxF_ext[j++]=rxF[(1+i-6)];\n#ifdef DEBUG_DLSCH_DEMOD\n              printf(\"**extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[j-1],*(1+(short *)&rxF_ext[j-1]));\n#endif\n            }\n          }\n\n          dl_ch0_ext+=10;\n          rxF_ext+=10;\n        } // symbol_mod==0\n      } // rballoc==1\n      else {\n        rxF       = &rxdataF[aarx][((symbol*(frame_parms->ofdm_symbol_size)))];\n      }\n\n      dl_ch0+=12;\n      rxF+=7;\n      rb++;\n\n      for (; rb<frame_parms->N_RB_DL; rb++) {\n        //      printf(\"dlch_ext %d\\n\",dl_ch0_ext-&dl_ch_estimates_ext[aarx][0]);\n        //      printf(\"rb %d (%p)\\n\",rb,rxF);\n        skip_half=0;\n\n        if (rb < 32)\n          rb_alloc_ind = (rb_alloc[0]>>rb) & 1;\n        else if (rb < 64)\n          rb_alloc_ind = (rb_alloc[1]>>(rb-32)) & 1;\n        else if (rb < 96)\n          rb_alloc_ind = (rb_alloc[2]>>(rb-64)) & 1;\n        else if (rb < 100)\n          rb_alloc_ind = (rb_alloc[3]>>(rb-96)) & 1;\n        else\n          rb_alloc_ind = 0;\n\n        if (rb_alloc_ind == 1)\n          nb_rb++;\n\n        // PBCH\n        if ((subframe==0) && (rb>((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l>=nsymb>>1) && (l<((nsymb>>1) + 4))) {\n          rb_alloc_ind = 0;\n        }\n\n        //PBCH subframe 0, symbols nsymb>>1 ... nsymb>>1 + 3\n        if ((subframe==0) && (rb==((frame_parms->N_RB_DL>>1)-3)) && (l>=(nsymb>>1)) && (l<((nsymb>>1) + 4)))\n          skip_half=1;\n        else if ((subframe==0) && (rb==((frame_parms->N_RB_DL>>1)+3)) && (l>=(nsymb>>1)) && (l<((nsymb>>1) + 4)))\n          skip_half=2;\n\n        //SSS\n        if (((subframe==0)||(subframe==5)) && (rb>((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l==sss_symb) ) {\n          rb_alloc_ind = 0;\n        }\n\n        //SSS\n        if (((subframe==0)||(subframe==5)) && (rb==((frame_parms->N_RB_DL>>1)-3)) && (l==sss_symb))\n          skip_half=1;\n        else if (((subframe==0)||(subframe==5)) && (rb==((frame_parms->N_RB_DL>>1)+3)) && (l==sss_symb))\n          skip_half=2;\n\n        if (frame_parms->frame_type == FDD) {\n          //PSS\n          if (((subframe==0)||(subframe==5)) && (rb>((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb) ) {\n            rb_alloc_ind = 0;\n          }\n\n          //PSS\n\n          if (((subframe==0)||(subframe==5)) && (rb==((frame_parms->N_RB_DL>>1)-3)) && (l==pss_symb))\n            skip_half=1;\n          else if (((subframe==0)||(subframe==5)) && (rb==((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb))\n            skip_half=2;\n        }\n\n        if ((frame_parms->frame_type == TDD) &&\n            (subframe==6)) { //TDD Subframe 6\n          if ((rb>((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb) ) {\n            rb_alloc_ind = 0;\n          }\n\n          if ((rb==((frame_parms->N_RB_DL>>1)-3)) && (l==pss_symb))\n            skip_half=1;\n          else if ((rb==((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb))\n            skip_half=2;\n        }\n\n        if (rb_alloc_ind==1) {\n#ifdef DEBUG_DLSCH_DEMOD\n          printf(\"rb %d/symbol %d (skip_half %d)\\n\",rb,l,skip_half);\n#endif\n\n          /*\n            printf(\"rb %d\\n\",rb);\n            for (i=0;i<12;i++)\n            printf(\"(%d %d)\",((short *)dl_ch0)[i<<1],((short*)dl_ch0)[1+(i<<1)]);\n            printf(\"\\n\");\n          */\n          if (pilots==0) {\n            //      printf(\"Extracting w/o pilots (symbol %d, rb %d, skip_half %d)\\n\",l,rb,skip_half);\n            if (skip_half==1) {\n              memcpy(dl_ch0_ext,dl_ch0,6*sizeof(int));\n\n              for (i=0; i<6; i++) {\n                rxF_ext[i]=rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i]));\n#endif\n              }\n\n              dl_ch0_ext+=6;\n              rxF_ext+=6;\n            } else if (skip_half==2) {\n              memcpy(dl_ch0_ext,dl_ch0+6,6*sizeof(int));\n\n              for (i=0; i<6; i++) {\n                rxF_ext[i]=rxF[(i+6)];\n#ifdef DEBUG_DLSCH_DEMOD\n                printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i]));\n#endif\n              }\n\n              dl_ch0_ext+=6;\n              rxF_ext+=6;\n            } else {\n              memcpy(dl_ch0_ext,dl_ch0,12*sizeof(int));\n\n              for (i=0; i<12; i++) {\n                rxF_ext[i]=rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i]));\n#endif\n              }\n\n              dl_ch0_ext+=12;\n              rxF_ext+=12;\n            }\n          } else {\n            //      printf(\"Extracting with pilots (symbol %d, rb %d, skip_half %d)\\n\",l,rb,skip_half);\n            j=0;\n\n            if (skip_half==1) {\n              for (i=0; i<6; i++) {\n                if (i!=((frame_parms->nushift+poffset)%6)) {\n                  rxF_ext[j]=rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                  printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[j],*(1+(short *)&rxF_ext[j]));\n#endif\n                  dl_ch0_ext[j++]=dl_ch0[i];\n                }\n              }\n\n              dl_ch0_ext+=5;\n              rxF_ext+=5;\n            } else if (skip_half==2) {\n              for (i=0; i<6; i++) {\n                if (i!=((frame_parms->nushift+poffset)%6)) {\n                  rxF_ext[j]=rxF[(i+6)];\n#ifdef DEBUG_DLSCH_DEMOD\n                  printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[j],*(1+(short *)&rxF_ext[j]));\n#endif\n                  dl_ch0_ext[j++]=dl_ch0[i+6];\n                }\n              }\n\n              dl_ch0_ext+=5;\n              rxF_ext+=5;\n            } else {\n              for (i=0; i<12; i++) {\n                if ((i!=(frame_parms->nushift+poffset)) &&\n                    (i!=((frame_parms->nushift+poffset+6)%12))) {\n                  rxF_ext[j]=rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                  printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[j],*(1+(short *)&rxF_ext[j]));\n#endif\n                  dl_ch0_ext[j++]=dl_ch0[i];\n                }\n              }\n\n              dl_ch0_ext+=10;\n              rxF_ext+=10;\n            }\n          } // pilots=0\n        }\n\n        dl_ch0+=12;\n        rxF+=12;\n      }\n    }\n  }\n\n  return(nb_rb/frame_parms->nb_antennas_rx);\n}\n\nunsigned short dlsch_extract_rbs_dual(int **rxdataF,\n                                      int **dl_ch_estimates,\n                                      int **rxdataF_ext,\n                                      int **dl_ch_estimates_ext,\n                                      unsigned short pmi,\n                                      unsigned char *pmi_ext,\n                                      unsigned int *rb_alloc,\n                                      unsigned char symbol,\n                                      unsigned char subframe,\n                                      uint32_t high_speed_flag,\n                                      LTE_DL_FRAME_PARMS *frame_parms,\n                                      MIMO_mode_t mimo_mode) {\n  int prb,nb_rb=0;\n  int prb_off,prb_off2;\n  int rb_alloc_ind,skip_half=0,sss_symb,pss_symb=0,nsymb,l;\n  int i,aarx;\n  int32_t *dl_ch0,*dl_ch0p,*dl_ch0_ext,*dl_ch1,*dl_ch1p,*dl_ch1_ext,*rxF,*rxF_ext;\n  int symbol_mod,pilots=0,j=0;\n  unsigned char *pmi_loc;\n  symbol_mod = (symbol>=(7-frame_parms->Ncp)) ? symbol-(7-frame_parms->Ncp) : symbol;\n  //  printf(\"extract_rbs: symbol_mod %d\\n\",symbol_mod);\n\n  if ((symbol_mod == 0) || (symbol_mod == (4-frame_parms->Ncp)))\n    pilots=1;\n\n  nsymb = (frame_parms->Ncp==NORMAL) ? 14:12;\n  l=symbol;\n\n  if (frame_parms->frame_type == TDD) {  // TDD\n    sss_symb = nsymb-1;\n    pss_symb = 2;\n  } else {\n    sss_symb = (nsymb>>1)-2;\n    pss_symb = (nsymb>>1)-1;\n  }\n\n  for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) {\n    if (high_speed_flag==1) {\n      dl_ch0     = &dl_ch_estimates[aarx][5+(symbol*(frame_parms->ofdm_symbol_size))];\n      dl_ch1     = &dl_ch_estimates[2+aarx][5+(symbol*(frame_parms->ofdm_symbol_size))];\n    } else {\n      dl_ch0     = &dl_ch_estimates[aarx][5];\n      dl_ch1     = &dl_ch_estimates[2+aarx][5];\n    }\n\n    pmi_loc = pmi_ext;\n    // pointers to extracted RX signals and channel estimates\n    rxF_ext    = &rxdataF_ext[aarx][symbol*(frame_parms->N_RB_DL*12)];\n    dl_ch0_ext = &dl_ch_estimates_ext[aarx][symbol*(frame_parms->N_RB_DL*12)];\n    dl_ch1_ext = &dl_ch_estimates_ext[2+aarx][symbol*(frame_parms->N_RB_DL*12)];\n\n    for (prb=0; prb<frame_parms->N_RB_DL; prb++) {\n      skip_half=0;\n\n      if (prb < 32)\n        rb_alloc_ind = (rb_alloc[0]>>prb) & 1;\n      else if (prb < 64)\n        rb_alloc_ind = (rb_alloc[1]>>(prb-32)) & 1;\n      else if (prb < 96)\n        rb_alloc_ind = (rb_alloc[2]>>(prb-64)) & 1;\n      else if (prb < 100)\n        rb_alloc_ind = (rb_alloc[3]>>(prb-96)) & 1;\n      else\n        rb_alloc_ind = 0;\n\n      if (rb_alloc_ind == 1)\n        nb_rb++;\n\n      if ((frame_parms->N_RB_DL&1) == 0) {  // even number of RBs\n\n        // PBCH\n        if ((subframe==0) &&\n            (prb>=((frame_parms->N_RB_DL>>1)-3)) &&\n            (prb<((frame_parms->N_RB_DL>>1)+3)) &&\n            (l>=(nsymb>>1)) &&\n            (l<((nsymb>>1) + 4))) {\n          rb_alloc_ind = 0;\n          //    printf(\"symbol %d / rb %d: skipping PBCH REs\\n\",symbol,prb);\n        }\n\n        //SSS\n\n        if (((subframe==0)||(subframe==5)) &&\n            (prb>=((frame_parms->N_RB_DL>>1)-3)) &&\n            (prb<((frame_parms->N_RB_DL>>1)+3)) &&\n            (l==sss_symb) ) {\n          rb_alloc_ind = 0;\n          //    printf(\"symbol %d / rb %d: skipping SSS REs\\n\",symbol,prb);\n        }\n\n        //PSS in subframe 0/5 if FDD\n        if (frame_parms->frame_type == FDD) {  //FDD\n          if (((subframe==0)||(subframe==5)) &&\n              (prb>=((frame_parms->N_RB_DL>>1)-3)) &&\n              (prb<((frame_parms->N_RB_DL>>1)+3)) &&\n              (l==pss_symb) ) {\n            rb_alloc_ind = 0;\n            //    printf(\"symbol %d / rb %d: skipping PSS REs\\n\",symbol,prb);\n          }\n        }\n\n        if ((frame_parms->frame_type == TDD) &&\n            (subframe==6)) { //TDD Subframe 6\n          if ((prb>=((frame_parms->N_RB_DL>>1)-3)) &&\n              (prb<((frame_parms->N_RB_DL>>1)+3)) &&\n              (l==pss_symb) ) {\n            rb_alloc_ind = 0;\n          }\n        }\n\n        if (rb_alloc_ind==1) {              // PRB is allocated\n          prb_off      = 12*prb;\n          prb_off2     = 1+(12*(prb-(frame_parms->N_RB_DL>>1)));\n          dl_ch0p    = dl_ch0+(12*prb);\n          dl_ch1p    = dl_ch1+(12*prb);\n\n          if (prb<(frame_parms->N_RB_DL>>1)) {\n            rxF      = &rxdataF[aarx][prb_off+\n                                      frame_parms->first_carrier_offset +\n                                      (symbol*(frame_parms->ofdm_symbol_size))];\n          } else {\n            rxF      = &rxdataF[aarx][prb_off2+\n                                      (symbol*(frame_parms->ofdm_symbol_size))];\n          }\n\n          /*\n          if (mimo_mode <= PUSCH_PRECODING1)\n           *pmi_loc = (pmi>>((prb>>2)<<1))&3;\n          else\n           *pmi_loc=(pmi>>prb)&1;*/\n          *pmi_loc = get_pmi(frame_parms->N_RB_DL,mimo_mode,pmi,prb);\n          pmi_loc++;\n\n          if (pilots == 0) {\n            memcpy(dl_ch0_ext,dl_ch0p,12*sizeof(int));\n            memcpy(dl_ch1_ext,dl_ch1p,12*sizeof(int));\n            memcpy(rxF_ext,rxF,12*sizeof(int));\n            dl_ch0_ext +=12;\n            dl_ch1_ext +=12;\n            rxF_ext    +=12;\n          } else { // pilots==1\n            j=0;\n\n            for (i=0; i<12; i++) {\n              if ((i!=frame_parms->nushift) &&\n                  (i!=frame_parms->nushift+3) &&\n                  (i!=frame_parms->nushift+6) &&\n                  (i!=((frame_parms->nushift+9)%12))) {\n                rxF_ext[j]=rxF[i];\n                //        printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[j],*(1+(short*)&rxF_ext[j]));\n                dl_ch0_ext[j]=dl_ch0p[i];\n                dl_ch1_ext[j++]=dl_ch1p[i];\n              }\n            }\n\n            dl_ch0_ext+=8;\n            dl_ch1_ext+=8;\n            rxF_ext+=8;\n          } // pilots==1\n        }\n      } else {  // Odd number of RBs\n\n        // PBCH\n        if ((subframe==0) &&\n            (prb>((frame_parms->N_RB_DL>>1)-3)) &&\n            (prb<((frame_parms->N_RB_DL>>1)+3)) &&\n            (l>=(nsymb>>1)) &&\n            (l<((nsymb>>1) + 4))) {\n          rb_alloc_ind = 0;\n          //    printf(\"symbol %d / rb %d: skipping PBCH REs\\n\",symbol,prb);\n        }\n\n        //SSS\n\n        if (((subframe==0)||(subframe==5)) &&\n            (prb>((frame_parms->N_RB_DL>>1)-3)) &&\n            (prb<((frame_parms->N_RB_DL>>1)+3)) &&\n            (l==sss_symb) ) {\n          rb_alloc_ind = 0;\n          //    printf(\"symbol %d / rb %d: skipping SSS REs\\n\",symbol,prb);\n        }\n\n        //PSS in subframe 0/5 if FDD\n        if (frame_parms->frame_type == FDD) {  //FDD\n          if (((subframe==0)||(subframe==5)) &&\n              (prb>((frame_parms->N_RB_DL>>1)-3)) &&\n              (prb<((frame_parms->N_RB_DL>>1)+3)) &&\n              (l==pss_symb) ) {\n            rb_alloc_ind = 0;\n            //    printf(\"symbol %d / rb %d: skipping PSS REs\\n\",symbol,prb);\n          }\n        }\n\n        if ((frame_parms->frame_type == TDD) &&\n            ((subframe==1) || (subframe==6))) { //TDD Subframe 1-6\n          if ((prb>((frame_parms->N_RB_DL>>1)-3)) &&\n              (prb<((frame_parms->N_RB_DL>>1)+3)) &&\n              (l==pss_symb) ) {\n            rb_alloc_ind = 0;\n          }\n        }\n\n        if (rb_alloc_ind == 1) {\n          skip_half=0;\n\n          //Check if we have to drop half a PRB due to PSS/SSS/PBCH\n          // skip_half == 0 means full PRB\n          // skip_half == 1 means first half is used (leftmost half-PRB from PSS/SSS/PBCH)\n          // skip_half == 2 means second half is used (rightmost half-PRB from PSS/SSS/PBCH)\n          //PBCH subframe 0, symbols nsymb>>1 ... nsymb>>1 + 3\n          if ((subframe==0) &&\n              (prb==((frame_parms->N_RB_DL>>1)-3)) &&\n              (l>=(nsymb>>1)) &&\n              (l<((nsymb>>1) + 4)))\n            skip_half=1;\n          else if ((subframe==0) &&\n                   (prb==((frame_parms->N_RB_DL>>1)+3)) &&\n                   (l>=(nsymb>>1)) &&\n                   (l<((nsymb>>1) + 4)))\n            skip_half=2;\n\n          //SSS\n          if (((subframe==0)||(subframe==5)) &&\n              (prb==((frame_parms->N_RB_DL>>1)-3)) &&\n              (l==sss_symb))\n            skip_half=1;\n          else if (((subframe==0)||(subframe==5)) &&\n                   (prb==((frame_parms->N_RB_DL>>1)+3)) &&\n                   (l==sss_symb))\n            skip_half=2;\n\n          //PSS Subframe 0,5\n          if (((frame_parms->frame_type == FDD) &&\n               (((subframe==0)||(subframe==5)))) ||  //FDD Subframes 0,5\n              ((frame_parms->frame_type == TDD) &&\n               (((subframe==1) || (subframe==6))))) { //TDD Subframes 1,6\n            if ((prb==((frame_parms->N_RB_DL>>1)-3)) &&\n                (l==pss_symb))\n              skip_half=1;\n            else if ((prb==((frame_parms->N_RB_DL>>1)+3)) &&\n                     (l==pss_symb))\n              skip_half=2;\n          }\n\n          prb_off      = 12*prb;\n          prb_off2     = 7+(12*(prb-(frame_parms->N_RB_DL>>1)-1));\n          dl_ch0p      = dl_ch0+(12*prb);\n          dl_ch1p      = dl_ch1+(12*prb);\n\n          if (prb<=(frame_parms->N_RB_DL>>1)) {\n            rxF      = &rxdataF[aarx][prb_off+\n                                      frame_parms->first_carrier_offset +\n                                      (symbol*(frame_parms->ofdm_symbol_size))];\n          } else {\n            rxF      = &rxdataF[aarx][prb_off2+\n                                      (symbol*(frame_parms->ofdm_symbol_size))];\n          }\n\n#ifdef DEBUG_DLSCH_DEMOD\n          printf(\"symbol %d / rb %d: alloc %d skip_half %d (rxF %p, rxF_ext %p) prb_off (%d,%d)\\n\",symbol,prb,rb_alloc_ind,skip_half,rxF,rxF_ext,prb_off,prb_off2);\n#endif\n          /* if (mimo_mode <= PUSCH_PRECODING1)\n            *pmi_loc = (pmi>>((prb>>2)<<1))&3;\n           else\n            *pmi_loc=(pmi>>prb)&1;\n          // printf(\"symbol_mod %d (pilots %d) rb %d, sb %d, pmi %d (pmi_loc %p,rxF %p, ch00 %p, ch01 %p, rxF_ext %p dl_ch0_ext %p dl_ch1_ext %p)\\n\",symbol_mod,pilots,prb,prb>>2,*pmi_loc,pmi_loc,rxF,dl_ch0, dl_ch1, rxF_ext,dl_ch0_ext,dl_ch1_ext);\n          */\n          *pmi_loc = get_pmi(frame_parms->N_RB_DL,mimo_mode,pmi,prb);\n          pmi_loc++;\n\n          if (prb != (frame_parms->N_RB_DL>>1)) { // This PRB is not around DC\n            if (pilots==0) {\n              if (skip_half==1) {\n                memcpy(dl_ch0_ext,dl_ch0p,6*sizeof(int32_t));\n                memcpy(dl_ch1_ext,dl_ch1p,6*sizeof(int32_t));\n                memcpy(rxF_ext,rxF,6*sizeof(int32_t));\n#ifdef DEBUG_DLSCH_DEMOD\n\n                for (i=0; i<6; i++)\n                  printf(\"extract rb %d, re %d => (%d,%d)\\n\",prb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i]));\n\n#endif\n                dl_ch0_ext+=6;\n                dl_ch1_ext+=6;\n                rxF_ext+=6;\n              } else if (skip_half==2) {\n                memcpy(dl_ch0_ext,dl_ch0p+6,6*sizeof(int32_t));\n                memcpy(dl_ch1_ext,dl_ch1p+6,6*sizeof(int32_t));\n                memcpy(rxF_ext,rxF+6,6*sizeof(int32_t));\n#ifdef DEBUG_DLSCH_DEMOD\n\n                for (i=0; i<6; i++)\n                  printf(\"extract rb %d, re %d => (%d,%d)\\n\",prb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i]));\n\n#endif\n                dl_ch0_ext+=6;\n                dl_ch1_ext+=6;\n                rxF_ext+=6;\n              } else {  // skip_half==0\n                memcpy(dl_ch0_ext,dl_ch0p,12*sizeof(int32_t));\n                memcpy(dl_ch1_ext,dl_ch1p,12*sizeof(int32_t));\n                memcpy(rxF_ext,rxF,12*sizeof(int32_t));\n#ifdef DEBUG_DLSCH_DEMOD\n\n                for (i=0; i<12; i++)\n                  printf(\"extract rb %d, re %d => (%d,%d)\\n\",prb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i]));\n\n#endif\n                dl_ch0_ext+=12;\n                dl_ch1_ext+=12;\n                rxF_ext+=12;\n              }\n            } else { // pilots=1\n              j=0;\n\n              if (skip_half==1) {\n                for (i=0; i<6; i++) {\n                  if ((i!=frame_parms->nushift) &&\n                      (i!=((frame_parms->nushift+3)%6))) {\n                    rxF_ext[j]=rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                    printf(\"(pilots,skip1)extract rb %d, re %d (%d)=> (%d,%d)\\n\",prb,i,j,*(short *)&rxF_ext[j],*(1+(short *)&rxF_ext[j]));\n#endif\n                    dl_ch0_ext[j]=dl_ch0p[i];\n                    dl_ch1_ext[j++]=dl_ch1p[i];\n                  }\n                }\n\n                dl_ch0_ext+=4;\n                dl_ch1_ext+=4;\n                rxF_ext+=4;\n              } else if (skip_half==2) {\n                for (i=0; i<6; i++) {\n                  if ((i!=frame_parms->nushift) &&\n                      (i!=((frame_parms->nushift+3)%6))) {\n                    rxF_ext[j]=rxF[(i+6)];\n#ifdef DEBUG_DLSCH_DEMOD\n                    printf(\"(pilots,skip2)extract rb %d, re %d (%d) => (%d,%d)\\n\",prb,i,j,*(short *)&rxF_ext[j],*(1+(short *)&rxF_ext[j]));\n#endif\n                    dl_ch0_ext[j]=dl_ch0p[i+6];\n                    dl_ch1_ext[j++]=dl_ch1p[i+6];\n                  }\n                }\n\n                dl_ch0_ext+=4;\n                dl_ch1_ext+=4;\n                rxF_ext+=4;\n              } else { //skip_half==0\n                for (i=0; i<12; i++) {\n                  if ((i!=frame_parms->nushift) &&\n                      (i!=frame_parms->nushift+3) &&\n                      (i!=frame_parms->nushift+6) &&\n                      (i!=((frame_parms->nushift+9)%12))) {\n                    rxF_ext[j]=rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                    printf(\"(pilots)extract rb %d, re %d => (%d,%d)\\n\",prb,i,*(short *)&rxF_ext[j],*(1+(short *)&rxF_ext[j]));\n#endif\n                    dl_ch0_ext[j]  =dl_ch0p[i];\n                    dl_ch1_ext[j++]=dl_ch1p[i];\n                  }\n                }\n\n                dl_ch0_ext+=8;\n                dl_ch1_ext+=8;\n                rxF_ext+=8;\n              } //skip_half==0\n            } //pilots==1\n          } else {       // Do middle RB (around DC)\n            if (pilots==0) {\n              memcpy(dl_ch0_ext,dl_ch0p,6*sizeof(int32_t));\n              memcpy(dl_ch1_ext,dl_ch1p,6*sizeof(int32_t));\n              memcpy(rxF_ext,rxF,6*sizeof(int32_t));\n#ifdef DEBUG_DLSCH_DEMOD\n\n              for (i=0; i<6; i++) {\n                printf(\"extract rb %d, re %d => (%d,%d)\\n\",prb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i]));\n              }\n\n#endif\n              rxF_ext+=6;\n              dl_ch0_ext+=6;\n              dl_ch1_ext+=6;\n              dl_ch0p+=6;\n              dl_ch1p+=6;\n              rxF       = &rxdataF[aarx][1+((symbol*(frame_parms->ofdm_symbol_size)))];\n              memcpy(dl_ch0_ext,dl_ch0p,6*sizeof(int32_t));\n              memcpy(dl_ch1_ext,dl_ch1p,6*sizeof(int32_t));\n              memcpy(rxF_ext,rxF,6*sizeof(int32_t));\n#ifdef DEBUG_DLSCH_DEMOD\n\n              for (i=0; i<6; i++) {\n                printf(\"extract rb %d, re %d => (%d,%d)\\n\",prb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i]));\n              }\n\n#endif\n              rxF_ext+=6;\n              dl_ch0_ext+=6;\n              dl_ch1_ext+=6;\n            } else { // pilots==1\n              j=0;\n\n              for (i=0; i<6; i++) {\n                if ((i!=frame_parms->nushift) &&\n                    (i!=((frame_parms->nushift+3)%6))) {\n                  dl_ch0_ext[j]=dl_ch0p[i];\n                  dl_ch1_ext[j]=dl_ch1p[i];\n                  rxF_ext[j++]=rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                  printf(\"(pilots)extract rb %d, re %d (%d) => (%d,%d)\\n\",prb,i,j,*(short *)&rxF[i],*(1+(short *)&rxF[i]));\n#endif\n                }\n              }\n\n              rxF       = &rxdataF[aarx][1+symbol*(frame_parms->ofdm_symbol_size)];\n\n              for (; i<12; i++) {\n                if ((i!=((frame_parms->nushift+6)%12)) &&\n                    (i!=((frame_parms->nushift+9)%12))) {\n                  dl_ch0_ext[j]=dl_ch0p[i];\n                  dl_ch1_ext[j]=dl_ch1p[i];\n                  rxF_ext[j++]=rxF[i-6];\n#ifdef DEBUG_DLSCH_DEMOD\n                  printf(\"(pilots)extract rb %d, re %d (%d) => (%d,%d)\\n\",prb,i,j,*(short *)&rxF[1+i-6],*(1+(short *)&rxF[1+i-6]));\n#endif\n                }\n              }\n\n              dl_ch0_ext+=8;\n              dl_ch1_ext+=8;\n              rxF_ext+=8;\n            } //pilots==1\n          }  // if Middle PRB\n        } // if odd PRB\n      } // if rballoc==1\n    } // for prb\n  } // for aarx\n\n  return(nb_rb/frame_parms->nb_antennas_rx);\n}\n\nunsigned short dlsch_extract_rbs_TM7(int **rxdataF,\n                                     int **dl_bf_ch_estimates,\n                                     int **rxdataF_ext,\n                                     int **dl_bf_ch_estimates_ext,\n                                     unsigned int *rb_alloc,\n                                     unsigned char symbol,\n                                     unsigned char subframe,\n                                     uint32_t high_speed_flag,\n                                     LTE_DL_FRAME_PARMS *frame_parms) {\n  unsigned short rb,nb_rb=0;\n  unsigned char rb_alloc_ind;\n  unsigned char i,aarx,l,nsymb,skip_half=0,sss_symb,pss_symb=0;\n  int *dl_ch0,*dl_ch0_ext,*rxF,*rxF_ext;\n  unsigned char symbol_mod,pilots=0,uespec_pilots=0,j=0,poffset=0,uespec_poffset=0;\n  int8_t uespec_nushift = frame_parms->Nid_cell%3;\n  symbol_mod = (symbol>=(7-frame_parms->Ncp)) ? symbol-(7-frame_parms->Ncp) : symbol;\n  pilots = ((symbol_mod==0)||(symbol_mod==(4-frame_parms->Ncp))) ? 1 : 0;\n  l=symbol;\n  nsymb = (frame_parms->Ncp==NORMAL) ? 14:12;\n\n  if (frame_parms->Ncp==0) {\n    if (symbol==3 || symbol==6 || symbol==9 || symbol==12)\n      uespec_pilots = 1;\n  } else {\n    if (symbol==4 || symbol==7 || symbol==10)\n      uespec_pilots = 1;\n  }\n\n  if (frame_parms->frame_type == TDD) {// TDD\n    sss_symb = nsymb-1;\n    pss_symb = 2;\n  } else {\n    sss_symb = (nsymb>>1)-2;\n    pss_symb = (nsymb>>1)-1;\n  }\n\n  if (symbol_mod==(4-frame_parms->Ncp))\n    poffset=3;\n\n  if ((frame_parms->Ncp==0 && (symbol==6 ||symbol ==12)) || (frame_parms->Ncp==1 && symbol==7))\n    uespec_poffset=2;\n\n  for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) {\n    if (high_speed_flag == 1)\n      dl_ch0     = &dl_bf_ch_estimates[aarx][symbol*(frame_parms->ofdm_symbol_size)];\n    else\n      dl_ch0     = &dl_bf_ch_estimates[aarx][0];\n\n    dl_ch0_ext = &dl_bf_ch_estimates_ext[aarx][symbol*(frame_parms->N_RB_DL*12)];\n    rxF_ext    = &rxdataF_ext[aarx][symbol*(frame_parms->N_RB_DL*12)];\n    rxF        = &rxdataF[aarx][(frame_parms->first_carrier_offset + (symbol*(frame_parms->ofdm_symbol_size)))];\n\n    if ((frame_parms->N_RB_DL&1) == 0)  // even number of RBs\n      for (rb=0; rb<frame_parms->N_RB_DL; rb++) {\n        if (rb < 32)\n          rb_alloc_ind = (rb_alloc[0]>>rb) & 1;\n        else if (rb < 64)\n          rb_alloc_ind = (rb_alloc[1]>>(rb-32)) & 1;\n        else if (rb < 96)\n          rb_alloc_ind = (rb_alloc[2]>>(rb-64)) & 1;\n        else if (rb < 100)\n          rb_alloc_ind = (rb_alloc[3]>>(rb-96)) & 1;\n        else\n          rb_alloc_ind = 0;\n\n        if (rb_alloc_ind == 1)\n          nb_rb++;\n\n        // For second half of RBs skip DC carrier\n        if (rb==(frame_parms->N_RB_DL>>1)) {\n          rxF       = &rxdataF[aarx][(1 + (symbol*(frame_parms->ofdm_symbol_size)))];\n          //dl_ch0++;\n        }\n\n        // PBCH\n        if ((subframe==0) && (rb>=((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l>=nsymb>>1) && (l<((nsymb>>1) + 4))) {\n          rb_alloc_ind = 0;\n        }\n\n        //SSS\n        if (((subframe==0)||(subframe==5)) && (rb>=((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l==sss_symb) ) {\n          rb_alloc_ind = 0;\n        }\n\n        if (frame_parms->frame_type == FDD) {\n          //PSS\n          if (((subframe==0)||(subframe==5)) && (rb>=((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb) ) {\n            rb_alloc_ind = 0;\n          }\n        }\n\n        if ((frame_parms->frame_type == TDD) &&\n            (subframe==6)) { //TDD Subframe 6\n          if ((rb>=((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb) ) {\n            rb_alloc_ind = 0;\n          }\n        }\n\n        if (rb_alloc_ind==1) {\n          /*\n              printf(\"rb %d\\n\",rb);\n              for (i=0;i<12;i++)\n              printf(\"(%d %d)\",((short *)dl_ch0)[i<<1],((short*)dl_ch0)[1+(i<<1)]);\n              printf(\"\\n\");\n          */\n          if (pilots==0 && uespec_pilots==0) {\n            memcpy(dl_ch0_ext,dl_ch0,12*sizeof(int));\n\n            for (i=0; i<12; i++) {\n              rxF_ext[i]=rxF[i];\n            }\n\n            dl_ch0_ext+=12;\n            rxF_ext+=12;\n          } else if(pilots==1 && uespec_pilots==0) {\n            j=0;\n\n            for (i=0; i<12; i++) {\n              if ((i!=(frame_parms->nushift+poffset)) &&\n                  (i!=((frame_parms->nushift+poffset+6)%12))) {\n                rxF_ext[j]=rxF[i];\n                dl_ch0_ext[j++]=dl_ch0[i];\n              }\n            }\n\n            dl_ch0_ext+=10;\n            rxF_ext+=10;\n          } else if (pilots==0 && uespec_pilots==1) {\n            j=0;\n\n            for (i=0; i<12; i++) {\n              if (frame_parms->Ncp==0) {\n                if (i!=uespec_nushift+uespec_poffset && i!=uespec_nushift+uespec_poffset+4 && i!=(uespec_nushift+uespec_poffset+8)%12) {\n                  rxF_ext[j] = rxF[i];\n                  dl_ch0_ext[j++]=dl_ch0[i];\n                }\n              } else {\n                if (i!=uespec_nushift+uespec_poffset && i!=uespec_nushift+uespec_poffset+3 && i!=uespec_nushift+uespec_poffset+6 && i!=(uespec_nushift+uespec_poffset+9)%12) {\n                  rxF_ext[j] = rxF[i];\n                  dl_ch0_ext[j++]=dl_ch0[i];\n                }\n              }\n            }\n\n            dl_ch0_ext+=9-frame_parms->Ncp;\n            rxF_ext+=9-frame_parms->Ncp;\n          } else {\n            LOG_E(PHY,\"dlsch_extract_rbs_TM7(dl_demodulation.c):pilot or ue spec pilot detection error\\n\");\n            exit(-1);\n          }\n        }\n\n        dl_ch0+=12;\n        rxF+=12;\n      }\n    else {  // Odd number of RBs\n      for (rb=0; rb<frame_parms->N_RB_DL>>1; rb++) {\n        skip_half=0;\n\n        if (rb < 32)\n          rb_alloc_ind = (rb_alloc[0]>>rb) & 1;\n        else if (rb < 64)\n          rb_alloc_ind = (rb_alloc[1]>>(rb-32)) & 1;\n        else if (rb < 96)\n          rb_alloc_ind = (rb_alloc[2]>>(rb-64)) & 1;\n        else if (rb < 100)\n          rb_alloc_ind = (rb_alloc[3]>>(rb-96)) & 1;\n        else\n          rb_alloc_ind = 0;\n\n        if (rb_alloc_ind == 1)\n          nb_rb++;\n\n        // PBCH\n        if ((subframe==0) && (rb>((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l>=(nsymb>>1)) && (l<((nsymb>>1) + 4))) {\n          rb_alloc_ind = 0;\n        }\n\n        //PBCH subframe 0, symbols nsymb>>1 ... nsymb>>1 + 3\n        if ((subframe==0) && (rb==((frame_parms->N_RB_DL>>1)-3)) && (l>=(nsymb>>1)) && (l<((nsymb>>1) + 4)))\n          skip_half=1;\n        else if ((subframe==0) && (rb==((frame_parms->N_RB_DL>>1)+3)) && (l>=(nsymb>>1)) && (l<((nsymb>>1) + 4)))\n          skip_half=2;\n\n        //SSS\n\n        if (((subframe==0)||(subframe==5)) &&\n            (rb>((frame_parms->N_RB_DL>>1)-3)) &&\n            (rb<((frame_parms->N_RB_DL>>1)+3)) &&\n            (l==sss_symb) ) {\n          rb_alloc_ind = 0;\n        }\n\n        //SSS\n        if (((subframe==0)||(subframe==5)) &&\n            (rb==((frame_parms->N_RB_DL>>1)-3)) &&\n            (l==sss_symb))\n          skip_half=1;\n        else if (((subframe==0)||(subframe==5)) &&\n                 (rb==((frame_parms->N_RB_DL>>1)+3)) &&\n                 (l==sss_symb))\n          skip_half=2;\n\n        //PSS in subframe 0/5 if FDD\n        if (frame_parms->frame_type == FDD) {  //FDD\n          if (((subframe==0)||(subframe==5)) && (rb>((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb) ) {\n            rb_alloc_ind = 0;\n          }\n\n          if (((subframe==0)||(subframe==5)) && (rb==((frame_parms->N_RB_DL>>1)-3)) && (l==pss_symb))\n            skip_half=1;\n          else if (((subframe==0)||(subframe==5)) && (rb==((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb))\n            skip_half=2;\n        }\n\n        if ((frame_parms->frame_type == TDD) && ((subframe==1)||(subframe==6))) { //TDD Subframe 1 and 6\n          if ((rb>((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb) ) {\n            rb_alloc_ind = 0;\n          }\n\n          if ((rb==((frame_parms->N_RB_DL>>1)-3)) && (l==pss_symb))\n            skip_half=1;\n          else if ((rb==((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb))\n            skip_half=2;\n        }\n\n        if (rb_alloc_ind==1) {\n#ifdef DEBUG_DLSCH_DEMOD\n          printf(\"rb %d/symbol %d pilots %d, uespec_pilots %d, (skip_half %d)\\n\",rb,l,pilots,uespec_pilots,skip_half);\n#endif\n\n          if (pilots==0 && uespec_pilots==0) {\n            //printf(\"Extracting w/o pilots (symbol %d, rb %d, skip_half %d)\\n\",l,rb,skip_half);\n            if (skip_half==1) {\n              memcpy(dl_ch0_ext,dl_ch0,6*sizeof(int));\n\n              for (i=0; i<6; i++) {\n                rxF_ext[i]=rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i]));\n#endif\n              }\n\n              dl_ch0_ext+=6;\n              rxF_ext+=6;\n            } else if (skip_half==2) {\n              memcpy(dl_ch0_ext,dl_ch0+6,6*sizeof(int));\n\n              for (i=0; i<6; i++) {\n                rxF_ext[i]=rxF[(i+6)];\n#ifdef DEBUG_DLSCH_DEMOD\n                printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i]));\n#endif\n              }\n\n              dl_ch0_ext+=6;\n              rxF_ext+=6;\n            } else {\n              memcpy(dl_ch0_ext,dl_ch0,12*sizeof(int));\n\n              for (i=0; i<12; i++) {\n                rxF_ext[i]=rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                printf(\"extract symbol %d rb %d, re %d => (%d,%d)\\n\",symbol,rb,i,*(short *)&rxF[i],*(1+(short *)&rxF[i]));\n#endif\n              }\n\n              dl_ch0_ext+=12;\n              rxF_ext+=12;\n            }\n          } else if (pilots==1 && uespec_pilots==0) {\n            // printf(\"Extracting with pilots (symbol %d, rb %d, skip_half %d)\\n\",l,rb,skip_half);\n            j=0;\n\n            if (skip_half==1) {\n              for (i=0; i<6; i++) {\n                if (i!=((frame_parms->nushift+poffset)%6)) {\n                  rxF_ext[j]=rxF[i];\n                  dl_ch0_ext[j++]=dl_ch0[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                  printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i]));\n#endif\n                }\n              }\n\n              dl_ch0_ext+=5;\n              rxF_ext+=5;\n            } else if (skip_half==2) {\n              for (i=0; i<6; i++) {\n                if (i!=((frame_parms->nushift+poffset)%6)) {\n                  rxF_ext[j]=rxF[(i+6)];\n                  dl_ch0_ext[j++]=dl_ch0[i+6];\n#ifdef DEBUG_DLSCH_DEMOD\n                  printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i]));\n#endif\n                }\n              }\n\n              dl_ch0_ext+=5;\n              rxF_ext+=5;\n            } else {\n              for (i=0; i<12; i++) {\n                if ((i!=(frame_parms->nushift+poffset)) &&\n                    (i!=((frame_parms->nushift+poffset+6)%12))) {\n                  rxF_ext[j]=rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                  printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[j],*(1+(short *)&rxF_ext[j]));\n#endif\n                  dl_ch0_ext[j++]=dl_ch0[i];\n                }\n              }\n\n              dl_ch0_ext+=10;\n              rxF_ext+=10;\n            }\n          } else if(pilots==0 && uespec_pilots==1) {\n            //printf(\"Extracting with uespec pilots (symbol %d, rb %d, skip_half %d)\\n\",l,rb,skip_half);\n            j=0;\n\n            if (skip_half==1) {\n              if (frame_parms->Ncp==0) {\n                for (i=0; i<6; i++) {\n                  if (i!=uespec_nushift+uespec_poffset && i!=uespec_nushift+uespec_poffset+4 && i!=(uespec_nushift+uespec_poffset+8)%12) {\n                    rxF_ext[j]=rxF[i];\n                    dl_ch0_ext[j++]=dl_ch0[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                    printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i]));\n#endif\n                  }\n                }\n\n                dl_ch0_ext+=6-(uespec_nushift+uespec_poffset<6)-(uespec_nushift+uespec_poffset+4<6)-((uespec_nushift+uespec_poffset+8)%12<6);\n                rxF_ext+=6-(uespec_nushift+uespec_poffset<6)-(uespec_nushift+uespec_poffset+4<6)-((uespec_nushift+uespec_poffset+8)%12<6);\n              } else {\n                for (i=0; i<6; i++) {\n                  if (i!=uespec_nushift+uespec_poffset && i!=uespec_nushift+uespec_poffset+3 && i!=uespec_nushift+uespec_poffset+6 && i!=(uespec_nushift+uespec_poffset+9)%12) {\n                    rxF_ext[j]=rxF[i];\n                    dl_ch0_ext[j++]=dl_ch0[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                    printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i]));\n#endif\n                  }\n                }\n\n                dl_ch0_ext+=4;\n                rxF_ext+=4;\n              }\n            } else if (skip_half==2) {\n              if(frame_parms->Ncp==0) {\n                for (i=0; i<6; i++) {\n                  if (i!=uespec_nushift+uespec_poffset && i!=uespec_nushift+uespec_poffset+4 && i!=(uespec_nushift+uespec_poffset+8)%12) {\n                    rxF_ext[j]=rxF[(i+6)];\n                    dl_ch0_ext[j++]=dl_ch0[i+6];\n#ifdef DEBUG_DLSCH_DEMOD\n                    printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i]));\n#endif\n                  }\n                }\n\n                dl_ch0_ext+=6-(uespec_nushift+uespec_poffset>6)-(uespec_nushift+uespec_poffset+4>6)-((uespec_nushift+uespec_poffset+8)%12>6);\n                rxF_ext+=6-(uespec_nushift+uespec_poffset>6)-(uespec_nushift+uespec_poffset+4>6)-((uespec_nushift+uespec_poffset+8)%12>6);\n              } else {\n                for (i=0; i<6; i++) {\n                  if (i!=uespec_nushift+uespec_poffset && i!=uespec_nushift+uespec_poffset+3 && i!=uespec_nushift+uespec_poffset+6 && i!=(uespec_nushift+uespec_poffset+9)%12) {\n                    rxF_ext[j]=rxF[(i+6)];\n                    dl_ch0_ext[j++]=dl_ch0[i+6];\n#ifdef DEBUG_DLSCH_DEMOD\n                    printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i]));\n#endif\n                  }\n                }\n\n                dl_ch0_ext+=4;\n                rxF_ext+=4;\n              }\n            } else {\n              for (i=0; i<12; i++) {\n                if (frame_parms->Ncp==0) {\n                  if (i!=uespec_nushift+uespec_poffset && i!=uespec_nushift+uespec_poffset+4 && i!=(uespec_nushift+uespec_poffset+8)%12) {\n                    rxF_ext[j] = rxF[i];\n                    dl_ch0_ext[j++] = dl_ch0[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                    printf(\"extract symbol %d, rb %d, re %d, j %d => (%d,%d)\\n\",\n                           symbol,rb,i,j-1,*(short *)&dl_ch0[j],*(1+(short *)&dl_ch0[i]));\n#endif\n                  }\n                } else {\n                  if (i!=uespec_nushift+uespec_poffset && i!=uespec_nushift+uespec_poffset+3 && i!=uespec_nushift+uespec_poffset+6 && i!=(uespec_nushift+uespec_poffset+9)%12) {\n                    rxF_ext[j] = rxF[i];\n                    dl_ch0_ext[j++]=dl_ch0[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                    printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i]));\n#endif\n                  }\n                }\n              }\n\n              dl_ch0_ext+=9-frame_parms->Ncp;\n              rxF_ext+=9-frame_parms->Ncp;\n            }\n          } else {\n            LOG_E(PHY,\"dlsch_extract_rbs_TM7(dl_demodulation.c):pilot or ue spec pilot detection error\\n\");\n            exit(-1);\n          }\n        }\n\n        dl_ch0+=12;\n        rxF+=12;\n      } // first half loop\n\n      // Do middle RB (around DC)\n      if (rb < 32)\n        rb_alloc_ind = (rb_alloc[0]>>rb) & 1;\n      else if (rb < 64)\n        rb_alloc_ind = (rb_alloc[1]>>(rb-32)) & 1;\n      else if (rb < 96)\n        rb_alloc_ind = (rb_alloc[2]>>(rb-64)) & 1;\n      else if (rb < 100)\n        rb_alloc_ind = (rb_alloc[3]>>(rb-96)) & 1;\n      else\n        rb_alloc_ind = 0;\n\n      if (rb_alloc_ind == 1)\n        nb_rb++;\n\n      // PBCH\n      if ((subframe==0) && (rb>=((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l>=(nsymb>>1)) && (l<((nsymb>>1) + 4))) {\n        rb_alloc_ind = 0;\n      }\n\n      //SSS\n      if (((subframe==0)||(subframe==5)) && (rb>=((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l==sss_symb) ) {\n        rb_alloc_ind = 0;\n      }\n\n      if (frame_parms->frame_type == FDD) {\n        //PSS\n        if (((subframe==0)||(subframe==5)) && (rb>=((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb) ) {\n          rb_alloc_ind = 0;\n        }\n      }\n\n      if ((frame_parms->frame_type == TDD) && ((subframe==1)||(subframe==6))) {\n        //PSS\n        if ((rb>((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb) ) {\n          rb_alloc_ind = 0;\n        }\n      }\n\n      //printf(\"dlch_ext %d\\n\",dl_ch0_ext-&dl_ch_estimates_ext[aarx][0]);\n      //printf(\"DC rb %d (%p)\\n\",rb,rxF);\n      if (rb_alloc_ind==1) {\n        //printf(\"rb %d/symbol %d (skip_half %d)\\n\",rb,l,skip_half);\n        if (pilots==0 && uespec_pilots==0) {\n          for (i=0; i<6; i++) {\n            dl_ch0_ext[i]=dl_ch0[i];\n            rxF_ext[i]=rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n            printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i]));\n#endif\n          }\n\n          rxF       = &rxdataF[aarx][((symbol*(frame_parms->ofdm_symbol_size)))];\n\n          for (; i<12; i++) {\n            dl_ch0_ext[i]=dl_ch0[i];\n            rxF_ext[i]=rxF[(1+i-6)];\n#ifdef DEBUG_DLSCH_DEMOD\n            printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i]));\n#endif\n          }\n\n          dl_ch0_ext+=12;\n          rxF_ext+=12;\n        } else if(pilots==1 && uespec_pilots==0) { // pilots==1\n          j=0;\n\n          for (i=0; i<6; i++) {\n            if (i!=((frame_parms->nushift+poffset)%6)) {\n              dl_ch0_ext[j]=dl_ch0[i];\n              rxF_ext[j++]=rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n              printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i]));\n#endif\n            }\n          }\n\n          rxF       = &rxdataF[aarx][((symbol*(frame_parms->ofdm_symbol_size)))];\n\n          for (; i<12; i++) {\n            if (i!=((frame_parms->nushift+6+poffset)%12)) {\n              dl_ch0_ext[j]=dl_ch0[i];\n              rxF_ext[j++]=rxF[(1+i-6)];\n#ifdef DEBUG_DLSCH_DEMOD\n              printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i]));\n#endif\n            }\n          }\n\n          dl_ch0_ext+=10;\n          rxF_ext+=10;\n        } else if(pilots==0 && uespec_pilots==1) {\n          j=0;\n\n          for (i=0; i<6; i++) {\n            if (frame_parms->Ncp==0) {\n              if (i!=uespec_nushift+uespec_poffset && i!=uespec_nushift+uespec_poffset+4 && i!=(uespec_nushift+uespec_poffset+8)%12) {\n                dl_ch0_ext[j]=dl_ch0[i];\n                rxF_ext[j++] = rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i]));\n#endif\n              }\n            } else {\n              if (i!=uespec_nushift+uespec_poffset && i!=uespec_nushift+uespec_poffset+3 && i!=uespec_nushift+uespec_poffset+6 && i!=(uespec_nushift+uespec_poffset+9)%12) {\n                dl_ch0_ext[j]=dl_ch0[i];\n                rxF_ext[j++] = rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i]));\n#endif\n              }\n            }\n          }\n\n          rxF       = &rxdataF[aarx][((symbol*(frame_parms->ofdm_symbol_size)))];\n\n          for (; i<12; i++) {\n            if (frame_parms->Ncp==0) {\n              if (i!=uespec_nushift+uespec_poffset && i!=uespec_nushift+uespec_poffset+4 && i!=(uespec_nushift+uespec_poffset+8)%12) {\n                dl_ch0_ext[j]=dl_ch0[i];\n                rxF_ext[j++]=rxF[(1+i-6)];\n#ifdef DEBUG_DLSCH_DEMOD\n                printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i]));\n#endif\n              }\n            } else {\n              if (i!=uespec_nushift+uespec_poffset && i!=uespec_nushift+uespec_poffset+3 && i!=uespec_nushift+uespec_poffset+6 && i!=(uespec_nushift+uespec_poffset+9)%12) {\n                dl_ch0_ext[j]=dl_ch0[i];\n                rxF_ext[j++] = rxF[(1+i-6)];\n#ifdef DEBUG_DLSCH_DEMOD\n                printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i]));\n#endif\n              }\n            }\n          }\n\n          dl_ch0_ext+=9-frame_parms->Ncp;\n          rxF_ext+=9-frame_parms->Ncp;\n        }// symbol_mod==0\n      } // rballoc==1\n      else {\n        rxF       = &rxdataF[aarx][((symbol*(frame_parms->ofdm_symbol_size)))];\n      }\n\n      dl_ch0+=12;\n      rxF+=7;\n      rb++;\n\n      for (; rb<frame_parms->N_RB_DL; rb++) {\n        //  printf(\"dlch_ext %d\\n\",dl_ch0_ext-&dl_ch_estimates_ext[aarx][0]);\n        //  printf(\"rb %d (%p)\\n\",rb,rxF);\n        skip_half=0;\n\n        if (rb < 32)\n          rb_alloc_ind = (rb_alloc[0]>>rb) & 1;\n        else if (rb < 64)\n          rb_alloc_ind = (rb_alloc[1]>>(rb-32)) & 1;\n        else if (rb < 96)\n          rb_alloc_ind = (rb_alloc[2]>>(rb-64)) & 1;\n        else if (rb < 100)\n          rb_alloc_ind = (rb_alloc[3]>>(rb-96)) & 1;\n        else\n          rb_alloc_ind = 0;\n\n        if (rb_alloc_ind==1)\n          nb_rb++;\n\n        // PBCH\n        if ((subframe==0) && (rb>((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l>=nsymb>>1) && (l<((nsymb>>1) + 4))) {\n          rb_alloc_ind = 0;\n        }\n\n        //PBCH subframe 0, symbols nsymb>>1 ... nsymb>>1 + 3\n        if ((subframe==0) && (rb==((frame_parms->N_RB_DL>>1)-3)) && (l>=(nsymb>>1)) && (l<((nsymb>>1) + 4)))\n          skip_half=1;\n        else if ((subframe==0) && (rb==((frame_parms->N_RB_DL>>1)+3)) && (l>=(nsymb>>1)) && (l<((nsymb>>1) + 4)))\n          skip_half=2;\n\n        //SSS\n        if (((subframe==0)||(subframe==5)) && (rb>((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l==sss_symb) ) {\n          rb_alloc_ind = 0;\n        }\n\n        //SSS\n        if (((subframe==0)||(subframe==5)) && (rb==((frame_parms->N_RB_DL>>1)-3)) && (l==sss_symb))\n          skip_half=1;\n        else if (((subframe==0)||(subframe==5)) && (rb==((frame_parms->N_RB_DL>>1)+3)) && (l==sss_symb))\n          skip_half=2;\n\n        //PSS\n        if (frame_parms->frame_type == FDD) {\n          if (((subframe==0)||(subframe==5)) && (rb>((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb) ) {\n            rb_alloc_ind = 0;\n          }\n\n          if (((subframe==0)||(subframe==5)) && (rb==((frame_parms->N_RB_DL>>1)-3)) && (l==pss_symb))\n            skip_half=1;\n          else if (((subframe==0)||(subframe==5)) && (rb==((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb))\n            skip_half=2;\n        }\n\n        if ((frame_parms->frame_type == TDD) && ((subframe==1)||(subframe==6))) { //TDD Subframe 1 and 6\n          if ((rb>((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb) ) {\n            rb_alloc_ind = 0;\n          }\n\n          if ((rb==((frame_parms->N_RB_DL>>1)-3)) && (l==pss_symb))\n            skip_half=1;\n          else if ((rb==((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb))\n            skip_half=2;\n        }\n\n        if (rb_alloc_ind==1) {\n#ifdef DEBUG_DLSCH_DEMOD\n          printf(\"rb %d/symbol %d (skip_half %d)\\n\",rb,l,skip_half);\n#endif\n\n          /*\n              printf(\"rb %d\\n\",rb);\n            for (i=0;i<12;i++)\n            printf(\"(%d %d)\",((short *)dl_ch0)[i<<1],((short*)dl_ch0)[1+(i<<1)]);\n            printf(\"\\n\");\n          */\n          if (pilots==0 && uespec_pilots==0) {\n            //printf(\"Extracting w/o pilots (symbol %d, rb %d, skip_half %d)\\n\",l,rb,skip_half);\n            if (skip_half==1) {\n              memcpy(dl_ch0_ext,dl_ch0,6*sizeof(int));\n\n              for (i=0; i<6; i++) {\n                rxF_ext[i]=rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i]));\n#endif\n              }\n\n              dl_ch0_ext+=6;\n              rxF_ext+=6;\n            } else if (skip_half==2) {\n              memcpy(dl_ch0_ext,dl_ch0+6,6*sizeof(int));\n\n              for (i=0; i<6; i++) {\n                rxF_ext[i]=rxF[i+6];\n#ifdef DEBUG_DLSCH_DEMOD\n                printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i]));\n#endif\n              }\n\n              dl_ch0_ext+=6;\n              rxF_ext+=6;\n            } else {\n              memcpy(dl_ch0_ext,dl_ch0,12*sizeof(int));\n              //printf(\"symbol %d, extract rb %d, => (%d,%d)\\n\",symbol,rb,*(short *)&dl_ch0[j],*(1+(short*)&dl_ch0[i]));\n\n              for (i=0; i<12; i++) {\n                rxF_ext[i]=rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i]));\n#endif\n              }\n\n              dl_ch0_ext+=12;\n              rxF_ext+=12;\n            }\n          } else if (pilots==1 && uespec_pilots==0) {\n            //printf(\"Extracting with pilots (symbol %d, rb %d, skip_half %d)\\n\",l,rb,skip_half);\n            j=0;\n\n            if (skip_half==1) {\n              for (i=0; i<6; i++) {\n                if (i!=((frame_parms->nushift+poffset)%6)) {\n                  rxF_ext[j]=rxF[i];\n                  dl_ch0_ext[j++]=dl_ch0[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                  printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i]));\n#endif\n                }\n              }\n\n              dl_ch0_ext+=5;\n              rxF_ext+=5;\n            } else if (skip_half==2) {\n              for (i=0; i<6; i++) {\n                if (i!=((frame_parms->nushift+poffset)%6)) {\n                  rxF_ext[j]=rxF[(i+6)];\n                  dl_ch0_ext[j++]=dl_ch0[i+6];\n#ifdef DEBUG_DLSCH_DEMOD\n                  printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i]));\n#endif\n                }\n              }\n\n              dl_ch0_ext+=5;\n              rxF_ext+=5;\n            } else {\n              for (i=0; i<12; i++) {\n                if ((i!=(frame_parms->nushift+poffset)) &&\n                    (i!=((frame_parms->nushift+poffset+6)%12))) {\n                  rxF_ext[j]=rxF[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                  printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[j],*(1+(short *)&rxF_ext[j]));\n#endif\n                  dl_ch0_ext[j++]=dl_ch0[i];\n                }\n              }\n\n              dl_ch0_ext+=10;\n              rxF_ext+=10;\n            }\n          } else if(pilots==0 && uespec_pilots==1) {\n            j=0;\n\n            if (skip_half==1) {\n              if (frame_parms->Ncp==0) {\n                for (i=0; i<6; i++) {\n                  if (i!=uespec_nushift+uespec_poffset && i!=uespec_nushift+uespec_poffset+4 && i!=(uespec_nushift+uespec_poffset+8)%12) {\n                    rxF_ext[j]=rxF[i];\n                    dl_ch0_ext[j++]=dl_ch0[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                    printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i]));\n#endif\n                  }\n                }\n\n                dl_ch0_ext+=6-(uespec_nushift+uespec_poffset<6)-(uespec_nushift+uespec_poffset+4<6)-((uespec_nushift+uespec_poffset+8)%12<6);\n                rxF_ext+=6-(uespec_nushift+uespec_poffset<6)-(uespec_nushift+uespec_poffset+4<6)-((uespec_nushift+uespec_poffset+8)%12<6);\n              } else {\n                for (i=0; i<6; i++) {\n                  if (i!=uespec_nushift+uespec_poffset && i!=uespec_nushift+uespec_poffset+3 && i!=uespec_nushift+uespec_poffset+6 && i!=(uespec_nushift+uespec_poffset+9)%12) {\n                    rxF_ext[j]=rxF[i];\n                    dl_ch0_ext[j++]=dl_ch0[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                    printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i]));\n#endif\n                  }\n                }\n\n                dl_ch0_ext+=4;\n                rxF_ext+=4;\n              }\n            } else if (skip_half==2) {\n              if(frame_parms->Ncp==0) {\n                for (i=0; i<6; i++) {\n                  if (i!=uespec_nushift+uespec_poffset && i!=uespec_nushift+uespec_poffset+4 && i!=(uespec_nushift+uespec_poffset+8)%12) {\n                    rxF_ext[j]=rxF[i+6];\n                    dl_ch0_ext[j++]=dl_ch0[i+6];\n#ifdef DEBUG_DLSCH_DEMOD\n                    printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i]));\n#endif\n                  }\n                }\n\n                dl_ch0_ext+=6-(uespec_nushift+uespec_poffset>6)-(uespec_nushift+uespec_poffset+4>6)-((uespec_nushift+uespec_poffset+8)%12>6);\n                rxF_ext+=6-(uespec_nushift+uespec_poffset>6)-(uespec_nushift+uespec_poffset+4>6)-((uespec_nushift+uespec_poffset+8)%12>6);\n              } else {\n                for (i=0; i<6; i++) {\n                  if (i!=uespec_nushift+uespec_poffset && i!=uespec_nushift+uespec_poffset+3 && i!=uespec_nushift+uespec_poffset+6 && i!=(uespec_nushift+uespec_poffset+9)%12) {\n                    rxF_ext[j]=rxF[(i+6)];\n                    dl_ch0_ext[j++]=dl_ch0[i+6];\n#ifdef DEBUG_DLSCH_DEMOD\n                    printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i]));\n#endif\n                  }\n                }\n\n                dl_ch0_ext+=4;\n                rxF_ext+=4;\n              }\n            } else {\n              for (i=0; i<12; i++) {\n                if (frame_parms->Ncp==0) {\n                  if (i!=uespec_nushift+uespec_poffset && i!=uespec_nushift+uespec_poffset+4 && i!=(uespec_nushift+uespec_poffset+8)%12) {\n                    rxF_ext[j] = rxF[i];\n                    dl_ch0_ext[j++]=dl_ch0[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                    printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i]));\n#endif\n                  }\n                } else {\n                  if (i!=uespec_nushift+uespec_poffset && i!=uespec_nushift+uespec_poffset+3 && i!=uespec_nushift+uespec_poffset+6 && i!=(uespec_nushift+uespec_poffset+9)%12) {\n                    rxF_ext[j] = rxF[i];\n                    dl_ch0_ext[j++]=dl_ch0[i];\n#ifdef DEBUG_DLSCH_DEMOD\n                    printf(\"extract rb %d, re %d => (%d,%d)\\n\",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i]));\n#endif\n                  }\n                }\n              }\n\n              dl_ch0_ext+=9-frame_parms->Ncp;\n              rxF_ext+=9-frame_parms->Ncp;\n            }\n          }// pilots=0\n        }\n\n        dl_ch0+=12;\n        rxF+=12;\n      }\n    }\n  }\n\n  _mm_empty();\n  _m_empty();\n  return(nb_rb/frame_parms->nb_antennas_rx);\n}\n\n//==============================================================================================\n\nvoid dump_dlsch2(PHY_VARS_UE *ue,uint8_t eNB_id,uint8_t subframe,unsigned int *coded_bits_per_codeword,int round,  unsigned char harq_pid) {\n#define NSYMB  ((ue->frame_parms.Ncp == 0) ? 14 : 12)\n  char fname[32],vname[32];\n  sprintf(fname,\"dlsch%d_rxF_r%d_ext0.m\",eNB_id,round);\n  sprintf(vname,\"dl%d_rxF_r%d_ext0\",eNB_id,round);\n  LOG_M(fname,vname,ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->rxdataF_ext[0],\n        12*(ue->frame_parms.N_RB_DL)*NSYMB,1,1);\n\n  if (ue->frame_parms.nb_antennas_rx >1) {\n    sprintf(fname,\"dlsch%d_rxF_r%d_ext1.m\",eNB_id,round);\n    sprintf(vname,\"dl%d_rxF_r%d_ext1\",eNB_id,round);\n    LOG_M(fname,vname,ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->rxdataF_ext[1],\n          12*(ue->frame_parms.N_RB_DL)*NSYMB,1,1);\n  }\n\n  sprintf(fname,\"dlsch%d_ch_r%d_ext00.m\",eNB_id,round);\n  sprintf(vname,\"dl%d_ch_r%d_ext00\",eNB_id,round);\n  LOG_M(fname,vname,ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->dl_ch_estimates_ext[0],\n        12*(ue->frame_parms.N_RB_DL)*NSYMB,1,1);\n\n  if (ue->transmission_mode[eNB_id]==7) {\n    sprintf(fname,\"dlsch%d_bf_ch_r%d.m\",eNB_id,round);\n    sprintf(vname,\"dl%d_bf_ch_r%d\",eNB_id,round);\n    LOG_M(fname,vname,ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->dl_bf_ch_estimates[0],512*NSYMB,1,1);\n    //LOG_M(fname,vname,phy_vars_ue->lte_ue_pdsch_vars[eNB_id]->dl_bf_ch_estimates[0],512,1,1);\n    sprintf(fname,\"dlsch%d_bf_ch_r%d_ext00.m\",eNB_id,round);\n    sprintf(vname,\"dl%d_bf_ch_r%d_ext00\",eNB_id,round);\n    LOG_M(fname,vname,ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->dl_bf_ch_estimates_ext[0],\n          12*(ue->frame_parms.N_RB_DL)*NSYMB,1,1);\n  }\n\n  if (ue->frame_parms.nb_antennas_rx == 2) {\n    sprintf(fname,\"dlsch%d_ch_r%d_ext01.m\",eNB_id,round);\n    sprintf(vname,\"dl%d_ch_r%d_ext01\",eNB_id,round);\n    LOG_M(fname,vname,ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->dl_ch_estimates_ext[1],\n          12*(ue->frame_parms.N_RB_DL)*NSYMB,1,1);\n  }\n\n  if (ue->frame_parms.nb_antenna_ports_eNB == 2) {\n    sprintf(fname,\"dlsch%d_ch_r%d_ext10.m\",eNB_id,round);\n    sprintf(vname,\"dl%d_ch_r%d_ext10\",eNB_id,round);\n    LOG_M(fname,vname,ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->dl_ch_estimates_ext[2],\n          12*(ue->frame_parms.N_RB_DL)*NSYMB,1,1);\n\n    if (ue->frame_parms.nb_antennas_rx == 2) {\n      sprintf(fname,\"dlsch%d_ch_r%d_ext11.m\",eNB_id,round);\n      sprintf(vname,\"dl%d_ch_r%d_ext11\",eNB_id,round);\n      LOG_M(fname,vname,ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->dl_ch_estimates_ext[3],\n            12*(ue->frame_parms.N_RB_DL)*NSYMB,1,1);\n    }\n  }\n\n  sprintf(fname,\"dlsch%d_rxF_r%d_uespec0.m\",eNB_id,round);\n  sprintf(vname,\"dl%d_rxF_r%d_uespec0\",eNB_id,round);\n  LOG_M(fname,vname,ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->rxdataF_uespec_pilots[0],\n        12*(ue->frame_parms.N_RB_DL)*NSYMB,1,1);\n  /*\n    LOG_M(\"dlsch%d_ch_ext01.m\",\"dl01_ch0_ext\",pdsch_vars[eNB_id]->dl_ch_estimates_ext[1],12*N_RB_DL*NSYMB,1,1);\n    LOG_M(\"dlsch%d_ch_ext10.m\",\"dl10_ch0_ext\",pdsch_vars[eNB_id]->dl_ch_estimates_ext[2],12*N_RB_DL*NSYMB,1,1);\n    LOG_M(\"dlsch%d_ch_ext11.m\",\"dl11_ch0_ext\",pdsch_vars[eNB_id]->dl_ch_estimates_ext[3],12*N_RB_DL*NSYMB,1,1);\n  */\n  sprintf(fname,\"dlsch%d_r%d_rho.m\",eNB_id,round);\n  sprintf(vname,\"dl_rho_r%d_%d\",eNB_id,round);\n  LOG_M(fname,vname,ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->dl_ch_rho_ext[harq_pid][round][0],\n        12*(ue->frame_parms.N_RB_DL)*NSYMB,1,1);\n  sprintf(fname,\"dlsch%d_r%d_rho2.m\",eNB_id,round);\n  sprintf(vname,\"dl_rho2_r%d_%d\",eNB_id,round);\n  LOG_M(fname,vname,ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->dl_ch_rho2_ext[0],\n        12*(ue->frame_parms.N_RB_DL)*NSYMB,1,1);\n  sprintf(fname,\"dlsch%d_rxF_r%d_comp0.m\",eNB_id,round);\n  sprintf(vname,\"dl%d_rxF_r%d_comp0\",eNB_id,round);\n  LOG_M(fname,vname,ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->rxdataF_comp0[0],\n        12*(ue->frame_parms.N_RB_DL)*NSYMB,1,1);\n\n  if (ue->frame_parms.nb_antenna_ports_eNB == 2) {\n    sprintf(fname,\"dlsch%d_rxF_r%d_comp1.m\",eNB_id,round);\n    sprintf(vname,\"dl%d_rxF_r%d_comp1\",eNB_id,round);\n    LOG_M(fname,vname,ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->rxdataF_comp1[harq_pid][round][0],\n          12*(ue->frame_parms.N_RB_DL)*NSYMB,1,1);\n  }\n\n  sprintf(fname,\"dlsch%d_rxF_r%d_llr.m\",eNB_id,round);\n  sprintf(vname,\"dl%d_r%d_llr\",eNB_id,round);\n  LOG_M(fname,vname, ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->llr[0],coded_bits_per_codeword[0],1,0);\n  sprintf(fname,\"dlsch%d_r%d_mag1.m\",eNB_id,round);\n  sprintf(vname,\"dl%d_r%d_mag1\",eNB_id,round);\n  LOG_M(fname,vname,ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->dl_ch_mag0[0],\n        12*(ue->frame_parms.N_RB_DL)*NSYMB,1,1);\n  sprintf(fname,\"dlsch%d_r%d_mag2.m\",eNB_id,round);\n  sprintf(vname,\"dl%d_r%d_mag2\",eNB_id,round);\n  LOG_M(fname,vname,ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->dl_ch_magb0[0],\n        12*(ue->frame_parms.N_RB_DL)*NSYMB,1,1);\n}\n\n\n", "meta": {"hexsha": "aafd579899ad023de7cbc7e0c843b75bab09215d", "size": 289028, "ext": "c", "lang": "C", "max_stars_repo_path": "openair1/PHY/LTE_UE_TRANSPORT/dlsch_demodulation.c", "max_stars_repo_name": "LaughingBlue/openairinterface5g", "max_stars_repo_head_hexsha": "2195e8e4cf6c8c5e059b0e982620480225bfa17a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-08T07:58:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-08T07:58:23.000Z", "max_issues_repo_path": "openair1/PHY/LTE_UE_TRANSPORT/dlsch_demodulation.c", "max_issues_repo_name": "LaughingBlue/openairinterface5g", "max_issues_repo_head_hexsha": "2195e8e4cf6c8c5e059b0e982620480225bfa17a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "openair1/PHY/LTE_UE_TRANSPORT/dlsch_demodulation.c", "max_forks_repo_name": "LaughingBlue/openairinterface5g", "max_forks_repo_head_hexsha": "2195e8e4cf6c8c5e059b0e982620480225bfa17a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-06-06T16:35:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-30T08:01:04.000Z", "avg_line_length": 43.9786975046, "max_line_length": 343, "alphanum_fraction": 0.5656752979, "num_tokens": 98051, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552953503957266, "lm_q2_score": 0.03258974711501865, "lm_q1q2_score": 0.014519694879211514}}
{"text": "/* rng/rng.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_rng.h>\n\ngsl_rng *\ngsl_rng_alloc (const gsl_rng_type * T)\n{\n\n  gsl_rng *r = (gsl_rng *) malloc (sizeof (gsl_rng));\n\n  if (r == 0)\n    {\n      GSL_ERROR_VAL (\"failed to allocate space for rng struct\",\n                        GSL_ENOMEM, 0);\n    };\n\n  r->state = malloc (T->size);\n\n  if (r->state == 0)\n    {\n      free (r);         /* exception in constructor, avoid memory leak */\n\n      GSL_ERROR_VAL (\"failed to allocate space for rng state\",\n                        GSL_ENOMEM, 0);\n    };\n\n  r->type = T;\n\n  gsl_rng_set (r, gsl_rng_default_seed);        /* seed the generator */\n\n  return r;\n}\n\nint\ngsl_rng_memcpy (gsl_rng * dest, const gsl_rng * src)\n{\n  if (dest->type != src->type)\n    {\n      GSL_ERROR (\"generators must be of the same type\", GSL_EINVAL);\n    }\n\n  memcpy (dest->state, src->state, src->type->size);\n\n  return GSL_SUCCESS;\n}\n\ngsl_rng *\ngsl_rng_clone (const gsl_rng * q)\n{\n  gsl_rng *r = (gsl_rng *) malloc (sizeof (gsl_rng));\n\n  if (r == 0)\n    {\n      GSL_ERROR_VAL (\"failed to allocate space for rng struct\",\n                        GSL_ENOMEM, 0);\n    };\n\n  r->state = malloc (q->type->size);\n\n  if (r->state == 0)\n    {\n      free (r);         /* exception in constructor, avoid memory leak */\n\n      GSL_ERROR_VAL (\"failed to allocate space for rng state\",\n                        GSL_ENOMEM, 0);\n    };\n\n  r->type = q->type;\n\n  memcpy (r->state, q->state, q->type->size);\n\n  return r;\n}\n\nvoid\ngsl_rng_set (const gsl_rng * r, unsigned long int seed)\n{\n  (r->type->set) (r->state, seed);\n}\n\n#ifndef HIDE_INLINE_STATIC\nunsigned long int\ngsl_rng_get (const gsl_rng * r)\n{\n  return (r->type->get) (r->state);\n}\n\ndouble\ngsl_rng_uniform (const gsl_rng * r)\n{\n  return (r->type->get_double) (r->state);\n}\n\ndouble\ngsl_rng_uniform_pos (const gsl_rng * r)\n{\n  double x ;\n  do\n    {\n      x = (r->type->get_double) (r->state) ;\n    }\n  while (x == 0) ;\n\n  return x ;\n}\n\n/* Note: to avoid integer overflow in (range+1) we work with scale =\n   range/n = (max-min)/n rather than scale=(max-min+1)/n, this reduces\n   efficiency slightly but avoids having to check for the out of range\n   value.  Note that range is typically O(2^32) so the addition of 1\n   is negligible in most usage. */\n\nunsigned long int\ngsl_rng_uniform_int (const gsl_rng * r, unsigned long int n)\n{\n  unsigned long int offset = r->type->min;\n  unsigned long int range = r->type->max - offset;\n  unsigned long int scale;\n  unsigned long int k;\n\n  if (n > range || n == 0) \n    {\n      GSL_ERROR_VAL (\"invalid n, either 0 or exceeds maximum value of generator\",\n                     GSL_EINVAL, 0) ;\n    }\n\n  scale = range / n;\n\n  do\n    {\n      k = (((r->type->get) (r->state)) - offset) / scale;\n    }\n  while (k >= n);\n\n  return k;\n}\n#endif\n\nunsigned long int\ngsl_rng_max (const gsl_rng * r)\n{\n  return r->type->max;\n}\n\nunsigned long int\ngsl_rng_min (const gsl_rng * r)\n{\n  return r->type->min;\n}\n\nconst char *\ngsl_rng_name (const gsl_rng * r)\n{\n  return r->type->name;\n}\n\nsize_t\ngsl_rng_size (const gsl_rng * r)\n{\n  return r->type->size;\n}\n\nvoid *\ngsl_rng_state (const gsl_rng * r)\n{\n  return r->state;\n}\n\nvoid\ngsl_rng_print_state (const gsl_rng * r)\n{\n  size_t i;\n  unsigned char *p = (unsigned char *) (r->state);\n  const size_t n = r->type->size;\n\n  for (i = 0; i < n; i++)\n    {\n      /* FIXME: we're assuming that a char is 8 bits */\n      printf (\"%.2x\", *(p + i));\n    }\n\n}\n\nvoid\ngsl_rng_free (gsl_rng * r)\n{\n  free (r->state);\n  free (r);\n}\n", "meta": {"hexsha": "eafdefb5da0e3cbff4b81714f0acd282cf36c955", "size": 4378, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/rng/rng.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/rng/rng.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/rng/rng.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 20.6509433962, "max_line_length": 81, "alphanum_fraction": 0.6206030151, "num_tokens": 1278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3106943959796865, "lm_q2_score": 0.04672496294029601, "lm_q1q2_score": 0.014517184137908506}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <getopt.h>\n#include <mpi.h>\n#include <iniparser.h>\n#include \"prepmt/prepmt_hpulse96.h\"\n#include \"prepmt/prepmt_event.h\"\n#ifdef PARMT_USE_INTEL\n#include <mkl_cblas.h>\n#else\n#include <cblas.h>\n#endif\n#include \"sacio.h\"\n#include \"cps.h\"\n#include \"cps_mpi.h\"\n#include \"cps_utils.h\"\n#include \"cps_defaults.h\"\n#include \"iscl/array/array.h\"\n#include \"iscl/memory/memory.h\"\n#include \"iscl/os/os.h\"\n#include \"iscl/string/string.h\"\n\n#define PROGRAM_NAME \"hspec96\"\n\nstatic void grns2sac(const struct hwave_greens_struct grns,\n                     struct sacData_struct sac[10]);\nstruct precompute_struct\n{\n    char sourceModel[PATH_MAX]; /*!< Source model */\n    char crustDir[PATH_MAX];  /*!< Crust1.0 directory */\n    char hspecDistanceFile[PATH_MAX];  /*!< Table of distances for hspec */\n    char hspecArchiveFile[PATH_MAX];  /*!< Name of archive file with ff green's\n                                           functions. */\n    double *depths; /*!< Depths (km) at which to compute greens fns */\n    double *dists;  /*!< Distances (degrees) at which to compute\n                         surface wave greens fns */\n    double slat;    /*!< Source latitude (degrees) */\n    double slon;    /*!< Source longitude (degrees) */\n    double dt;   /*!< Sampling period */\n    int npts;    /*!< Number of samples */\n    int ndepths; /*!< Number of depths at which to compute greens fns */\n    int ndists;  /*!< Number of distances to compute surface waves */\n    bool luseSourceMod; /*!< If true then use the local source model */ \n    bool luseCrust; /*!< If true then use crust1.0 at teleseismic distances */\n    bool luseDistanceTable; /*!< If true then use a distance table.\n                                 Otherwise linearly interpolate distances */\n};\nint prepmt_hspec96_readParameters(const char *iniFile,\n                                  const char *section,\n                                  struct precompute_struct *precompute);\nint prepmt_hspec96_initializeArchive(\n    const char *archiveName, const char *model,\n    const int ndepths, const double *__restrict__ depths,\n    const int ngcarcs,  const double *__restrict__ gcarcs);\nint prepmt_hspec96_readHspec96Parameters(\n    const char *iniFile,\n    struct hprep96_parms_struct *hprepParms,\n    struct hspec96_parms_struct *hspecParms,\n    struct hpulse96_parms_struct *hpulseParms);\nstatic void printUsage(void);\nstatic int parseArguments(int argc, char *argv[], char iniFile[PATH_MAX]);\n\n/*!\n * @brief Makes the regional fullwaveform fundamental fault Green's \n *        functions archive.\n *\n */\nint main(int argc, char **argv)\n{\n    char fname[PATH_MAX], iniFile[PATH_MAX], groupName[512], *modelName;\n    struct prepmtEventParms_struct event;\n    struct sacData_struct *sac;\n    struct precompute_struct precompute;\n    struct hwave_greens_struct *grns;\n    struct hpulse96_data_struct *zresp;\n    struct hprep96_parms_struct hprepParms;\n    struct hspec96_parms_struct hspecParms;\n    struct hpulse96_parms_struct hpulseParms;\n    struct vmodel_struct recmod, vmodel;\n    double *depthr, *depths, *r, *tshift, *vred, dt;\n    hid_t groupID, h5fl;\n    int idep, idist, ierr, k, l, myid, ndeps, ndists, nprocs, npts, nwaves;\n    // Here's the idea: I want to input magnitudes with units of N-m so:\n    // N-m -> Dyne-dm (1.e+7)\n    // CPS internally scales from Dyne-cm to cm (1.e+20)\n    // Finally, I want outputs proprotional to m (1.e-2)\n    const double xmom = 1.0;     // no confusing `relative' magnitudes \n    const double xcps = 1.e-20;  // convert dyne-cm mt to output cm\n    const double cm2m = 1.e-2;   // cm to meters\n    const double dcm2nm = 1.e+7; // magnitudes intended to be specified in\n                                 // Dyne-cm but I work in N-m\n    const char *cfaults[10] = {\"ZDS\\0\", \"ZSS\\0\", \"ZDD\", \"ZEX\\0\",\n                               \"RDS\\0\", \"RSS\\0\", \"RDD\", \"REX\\0\",\n                               \"TDS\\0\", \"TSS\\0\"};\n    // Given a M0 in Newton-meters get a seismogram in meters\n    const double xscal = xmom*xcps*cm2m*dcm2nm;\n    const int master = 0;\n    MPI_Init(&argc, &argv);\n    MPI_Comm_rank(MPI_COMM_WORLD, &myid);\n    MPI_Comm_size(MPI_COMM_WORLD, &nprocs);\n    sac = NULL;\n    grns = NULL;\n    zresp = NULL;\n    modelName = NULL;\n    r = NULL;\n    depthr = NULL;\n    depths = NULL;\n    vred = NULL;\n    tshift = NULL; \n    memset(&hprepParms, 0, sizeof(struct hprep96_parms_struct));\n    memset(&hspecParms, 0, sizeof(struct hspec96_parms_struct));\n    memset(&hpulseParms, 0, sizeof(struct hpulse96_parms_struct));\n    memset(&vmodel, 0, sizeof(struct vmodel_struct));\n    if (myid == master)\n    {\n        // Parse the input arguments\n        ierr = parseArguments(argc, argv, iniFile);\n        if (ierr != 0)\n        {\n            if (ierr !=-1)\n            {\n                printf(\"%s: Failed to parse input commands\\n\", PROGRAM_NAME);\n            }\n            goto FINISH_EARLY;\n        } \n        // Read the CPS variables\n        ierr = prepmt_hspec96_readHspec96Parameters(iniFile,\n                                                    &hprepParms, &hspecParms,\n                                                    &hpulseParms);\n        if (ierr != 0)\n        {\n            printf(\"Error reading hprep parameters\\n\");\n            MPI_Abort(MPI_COMM_WORLD, 30);\n        }\n        // Read the additional contrived forward modeling variables\n        ierr = prepmt_hspec96_readParameters(iniFile,\n                                             \"precompute\", &precompute);\n        if (ierr != 0)\n        {\n            printf(\"Error reading precompute parameters\\n\");\n            MPI_Abort(MPI_COMM_WORLD, 30);\n        }\n        ndists = precompute.ndists;\n        ndeps = precompute.ndepths;\n        // expand to make a grid\n        r = (double *) calloc((size_t) (ndists*ndeps), sizeof(double));\n        depths = (double *) calloc((size_t) (ndists*ndeps), sizeof(double));\n        for (idep=0; idep<ndeps; idep++)\n        {\n            for (idist=0; idist<ndists; idist++)\n            {\n                k = idist*ndeps + idep;\n                r[k] = precompute.dists[idist]*111.195;\n                depths[k] = precompute.depths[idep];\n                printf(\"Wavform %d has distance %f (deg) and depth %f (km)\\n\",\n                       k+1, r[k]/111.195, depths[k]);\n            }\n        }\n        npts = precompute.npts;\n        dt = precompute.dt;\n//ndists = 31;\n//ndeps = 26;\n//npts = 1024; //2048;\n//dt = 1.0; //0.5;\n        printf(\"%d %f %s\\n\", npts, dt, hprepParms.mfile);\n        // load the model into memory\n        if (precompute.luseSourceMod)\n        {\n            printf(\"%s: Loading source model %s...\\n\",\n                   PROGRAM_NAME, precompute.sourceModel);\n            strcpy(hprepParms.mfile, precompute.sourceModel);\n            ierr = cps_getmod(hprepParms.mfile, &vmodel);\n            if (ierr != 0)\n            {\n                printf(\"Failed to load source model\\n\");\n                goto FINISH_EARLY;\n            }\n        }\n        else if (precompute.luseCrust)\n        {\n            ierr = prepmt_event_initializeFromIniFile(iniFile, &event);\n            if (ierr != 0)\n            {\n                printf(\"%s: Error getting event info\\n\", PROGRAM_NAME);\n                goto FINISH_EARLY;\n            } \n            printf(\"%s: Loading CPS model (lat,lon)=(%f,%f)\\n\", PROGRAM_NAME,\n                   event.latitude, event.longitude);\n            ierr = cps_crust1_getCrust1ForHerrmann(precompute.crustDir, false,\n                                              event.latitude, event.longitude,\n                                              &event.latitude, &event.longitude,\n                                              1, &vmodel, &recmod);\n            cps_utils_freeVmodelStruct(&recmod);\n        }\n        else\n        {\n            printf(\"%s: Model is not set\\n\", PROGRAM_NAME);\n            ierr = 1;\n            goto FINISH_EARLY;\n        }\n        // Initialize the archive - remove NULL terminator\n        modelName = string_strip(NULL, vmodel.title);\n        printf(\"%s: Initializing archive file %s with model %s\\n\",\n               PROGRAM_NAME, precompute.hspecArchiveFile, modelName); \n        ierr = prepmt_hspec96_initializeArchive(precompute.hspecArchiveFile,\n                                                modelName,\n                                                ndeps, depths,\n                                                ndists, precompute.dists);\n        if (ierr != 0)\n        {\n            printf(\"%s: Failed to initialize archive\\n\", PROGRAM_NAME);\n            goto FINISH_EARLY;\n        }\n        free(precompute.depths);\n        free(precompute.dists);\n    }\nFINISH_EARLY:;\n    MPI_Barrier(MPI_COMM_WORLD);\n    MPI_Bcast(&ierr, 1, MPI_INTEGER, master, MPI_COMM_WORLD);\n    if (ierr != 0){goto FINISH;}\n    cps_broadcast_vmodelStruct(MPI_COMM_WORLD, master, &vmodel);\n    cps_broadcast_hprep96ParmsStruct(MPI_COMM_WORLD, master, &hprepParms);\n    cps_broadcast_hspec96ParmsStruct(MPI_COMM_WORLD, master, &hspecParms);\n    cps_broadcast_hpulse96ParmsStruct(MPI_COMM_WORLD, master, &hpulseParms);\n    MPI_Bcast(&ndists, 1, MPI_INTEGER, master, MPI_COMM_WORLD);\n    MPI_Bcast(&ndeps,  1, MPI_INTEGER, master, MPI_COMM_WORLD);\n    MPI_Bcast(&npts, 1, MPI_INTEGER, master, MPI_COMM_WORLD);\n    MPI_Bcast(&dt, 1, MPI_DOUBLE, master, MPI_COMM_WORLD);\n    // initialize receiver information\n    nwaves = ndists*ndeps;\n    depthr = (double *) calloc((size_t) nwaves, sizeof(double));\n    if (myid != master)\n    {\n        depths = (double *) calloc((size_t) nwaves, sizeof(double));\n        r = (double *) calloc((size_t) nwaves, sizeof(double));\n    }\n    tshift = (double *) calloc((size_t) nwaves, sizeof(double));\n    vred = (double *) calloc((size_t) nwaves, sizeof(double));\n    MPI_Bcast(depths, nwaves, MPI_DOUBLE, master, MPI_COMM_WORLD);\n    MPI_Bcast(r, nwaves, MPI_DOUBLE, master, MPI_COMM_WORLD);\n    // set the receiver distances\n//r[0] = 55.597; //111.195;\n//r[1] = 111.195;\n//r[2] = 166.792;\n//depths[0] = 7.0;\n//for (idep=0; idep<ndeps; idep++)\n//{\n//    for (idist=0;  idist<ndists; idist++)\n//    {\n//        k = idist*ndeps + idep;\n//        r[k] = 55.597*(double) (idist + 1); \n//        depths[k] = (double) idep;\n//    }\n//}\n/*\nprintf(\"premature end\\n\");\nMPI_Finalize();\nreturn 0;\n*/\n    // call hspec\n    zresp = hspec96_mpi_interface(MPI_COMM_WORLD, nwaves, npts, dt,\n                                  r, tshift, vred, depthr, depths,\n                                  hprepParms, hspecParms,\n                                  vmodel, &ierr);\n    MPI_Barrier(MPI_COMM_WORLD);\n    if (ierr != 0)\n    {\n        printf(\"Error calling hspec\\n\");\n        goto FINISH;\n    }\n    // convolve STF and convert back to time domain\n    grns = hpulse96_mpi_interface(MPI_COMM_WORLD, nwaves, hpulseParms,\n                                  zresp, &ierr); \n    if (ierr != 0)\n    {\n        printf(\"Error computing greens fns\\n\");\n        goto FINISH;\n    }\n    // dump the results\n    if (myid == master)\n    {\n        printf(\"Writing results...\\n\");\n        h5fl = H5Fopen(precompute.hspecArchiveFile, H5F_ACC_RDWR, H5P_DEFAULT);\n        sac = (struct sacData_struct *)\n              calloc(10, sizeof(struct sacData_struct));\n        k = 0;\n        //for (idist=0; idist<ndists; idist++)\n        for (idep=0; idep<ndeps; idep++)\n        {\n            memset(fname, 0, PATH_MAX*sizeof(char));\n            sprintf(fname, \"dump/depth_%d\", idep);\n            os_makedirs(fname);\n\n            memset(groupName, 0, 512*sizeof(char));\n            sprintf(groupName, \"/%s/Depth_%d\", modelName, idep);\n            groupID = H5Gopen(h5fl, groupName, H5P_DEFAULT);\n            //for (idep=0; idep<ndeps; idep++)\n            for (idist=0; idist<ndists; idist++)\n            {\n                k = idist*ndeps + idep;\n                grns2sac(grns[k], sac);\n                memset(fname, 0, PATH_MAX*sizeof(char));\n                sprintf(fname, \"dump/depth_%d/%04d01ZDD.SAC\", idep, idist+1);\n                sacio_writeTimeSeriesFile(fname, sac[0]);\n                sprintf(fname, \"dump/depth_%d/%04d02RDD.SAC\", idep, idist+1);\n                sacio_writeTimeSeriesFile(fname, sac[1]);\n                sprintf(fname, \"dump/depth_%d/%04d03ZDS.SAC\", idep, idist+1);\n                sacio_writeTimeSeriesFile(fname, sac[2]);\n                sprintf(fname, \"dump/depth_%d/%04d04RDS.SAC\", idep, idist+1);\n                sacio_writeTimeSeriesFile(fname, sac[3]);\n                sprintf(fname, \"dump/depth_%d/%04d05TDS.SAC\", idep, idist+1);\n                sacio_writeTimeSeriesFile(fname, sac[4]);\n                sprintf(fname, \"dump/depth_%d/%04d06ZSS.SAC\", idep, idist+1);\n                sacio_writeTimeSeriesFile(fname, sac[5]);\n                sprintf(fname, \"dump/depth_%d/%04d07RSS.SAC\", idep, idist+1);\n                sacio_writeTimeSeriesFile(fname, sac[6]);\n                sprintf(fname, \"dump/depth_%d/%04d08TSS.SAC\", idep, idist+1);\n                sacio_writeTimeSeriesFile(fname, sac[7]);\n                sprintf(fname, \"dump/depth_%d/%04d09ZEX.SAC\", idep, idist+1);\n                sacio_writeTimeSeriesFile(fname, sac[8]);\n                sprintf(fname, \"dump/depth_%d/%04d10REX.SAC\", idep, idist+1);\n                sacio_writeTimeSeriesFile(fname, sac[9]);\n                // Dump to the H5 archive and release memory\n                for (l=0; l<10; l++)\n                {\n                    // Rescale to unit magnitude\n                    cblas_dscal(sac[l].npts, xscal, sac[l].data, 1);\n                    sprintf(fname, \"Greens_%s_%d\", cfaults[l], idist);\n                    sacioh5_writeTimeSeries2(fname, groupID, sac[l]);\n                    sacio_free(&sac[l]);\n                }\n//break;\n            }\n            H5Gclose(groupID);\n//break;\n        }\n        if (sac != NULL){free(sac);}\n        H5Fclose(h5fl);\n        printf(\"%s: Finishing program\\n\", PROGRAM_NAME);\n    }\n    MPI_Barrier(MPI_COMM_WORLD);\nFINISH:;\n    if (grns != NULL)\n    {\n        for (k=0; k<nwaves; k++)\n        {\n            cps_utils_freeHwaveGreensStruct(&grns[k]);\n        }\n        free(grns);\n        grns = NULL;\n    }\n    if (zresp != NULL)\n    {\n        for (k=0; k<nwaves; k++)\n        {\n            cps_utils_freeHpulse96DataStruct(&zresp[k]);\n        }\n        free(zresp);\n        zresp = NULL;\n    }\n    // release memory\n    memory_free8c(&modelName);\n    free(depthr);\n    free(depths);\n    free(r);\n    free(tshift);\n    free(vred); \n    cps_utils_freeHpulse96ParmsStruct(&hpulseParms);\n    cps_utils_freeVmodelStruct(&vmodel);\n    MPI_Finalize();\n    return 0;\n}\n//============================================================================//\nint prepmt_hspec96_initializeArchive(\n    const char *archiveName, const char *model,\n    const int ndepths, const double *__restrict__ depths,\n    const int ngcarcs,  const double *__restrict__ gcarcs)\n{\n    char modelName[512], depthName[512]; //, varName[512];\n    hid_t h5fl, dataSet, dataSpace, depthGroup, modelGroup;\n    hsize_t dims[1];\n    int idep;\n    //------------------------------------------------------------------------//\n    h5fl = H5Fcreate(archiveName, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);\n    memset(modelName, 0, 512*sizeof(char));\n    sprintf(modelName, \"/%s\", model);\n    printf(\"%s: Initializing model: %s\\n\", __func__, modelName);\n    modelGroup = H5Gcreate2(h5fl, modelName, H5P_DEFAULT,\n                            H5P_DEFAULT, H5P_DEFAULT);\n    // write the depths and distances\n    dims[0] = (hsize_t) ndepths;\n    dataSpace = H5Screate_simple(1, dims, NULL);\n    dataSet = H5Dcreate2(modelGroup, \"Depths\\0\", H5T_NATIVE_DOUBLE,\n                         dataSpace,\n                         H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);\n    H5Dwrite(dataSet, H5T_NATIVE_DOUBLE, H5S_ALL,\n             H5S_ALL, H5P_DEFAULT, depths);\n    H5Dclose(dataSet);\n    H5Sclose(dataSpace);\n    // Write the distances\n    dims[0] = (hsize_t) ngcarcs;\n    dataSpace = H5Screate_simple(1, dims, NULL);\n    dataSet = H5Dcreate2(modelGroup, \"Distances\\0\", H5T_NATIVE_DOUBLE,\n                         dataSpace,\n                         H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);\n    H5Dwrite(dataSet, H5T_NATIVE_DOUBLE, H5S_ALL,\n             H5S_ALL, H5P_DEFAULT, gcarcs);\n    H5Dclose(dataSet);\n    H5Sclose(dataSpace);\n    // Create the depths groups\n    for (idep=0; idep<ndepths; idep++)\n    {\n        memset(depthName, 0, 512*sizeof(char));\n        sprintf(depthName, \"%s/Depth_%d\", modelName, idep);\n        depthGroup = H5Gcreate2(h5fl, depthName, H5P_DEFAULT,\n                                H5P_DEFAULT, H5P_DEFAULT);\n        H5Gclose(depthGroup);\n    }\n    H5Gclose(modelGroup);\n    H5Fclose(h5fl);\n    return 0;\n}\n//============================================================================//\nint prepmt_hspec96_readParameters(const char *iniFile,\n                                  const char *section,\n                                  struct precompute_struct *precompute)\n{\n    const char *fcnm = \"prepmt_hspec96_readParameters\\0\";\n    FILE *dfl;\n    const char *s;\n    char *dirName, cline[256], vname[128];\n    double depth0, depth1, dist0, dist1;\n    int i, ierr;\n    dictionary *ini;\n    memset(precompute, 0, sizeof(struct precompute_struct));\n    if (!os_path_isfile(iniFile))\n    {\n        printf(\"%s: ini file: %s does not exist\\n\", fcnm, iniFile);\n        return -1;\n    }\n    ini = iniparser_load(iniFile);\n    if (ini == NULL)\n    {\n        printf(\"%s: Cannot parse ini file\\n\", fcnm);\n        return -1;\n    }\n    memset(vname, 0, 128*sizeof(char));\n    sprintf(vname, \"%s:ndepths\", section);\n    precompute->ndepths = iniparser_getint(ini, vname, 1);\n\n    memset(vname, 0, 128*sizeof(char));\n    sprintf(vname, \"%s:depthMin\", section);\n    depth0 = iniparser_getdouble(ini, vname, 1.0);\n\n    memset(vname, 0, 128*sizeof(char));\n    sprintf(vname, \"%s:depthMax\", section);\n    depth1 = iniparser_getdouble(ini, vname, 1.0);\n\n    memset(vname, 0, 128*sizeof(char));\n    sprintf(vname, \"%s:ndists\", section);\n    precompute->ndists = iniparser_getint(ini, vname, 1);\n\n    memset(vname, 0, 128*sizeof(char));\n    sprintf(vname, \"%s:minDistance\", section);\n    dist0 = iniparser_getdouble(ini, vname, 1.0);\n\n    memset(vname, 0, 128*sizeof(char));\n    sprintf(vname, \"%s:maxDistance\", section);\n    dist1 = iniparser_getdouble(ini, vname, 1.0);\n\n    memset(vname, 0, 128*sizeof(char));\n    sprintf(vname, \"%s:dtHspec\", section);\n    precompute->dt = iniparser_getdouble(ini, vname, 1.0);\n\n    memset(vname, 0, 128*sizeof(char));\n    sprintf(vname, \"%s:nptsHspec\", section);\n    precompute->npts = iniparser_getint(ini, vname, 1024);\n\n    memset(vname, 0, 128*sizeof(char));\n    sprintf(vname, \"%s:luseCrust1\", section);\n    precompute->luseCrust = iniparser_getboolean(ini, vname, 0);\n\n    memset(vname, 0, 128*sizeof(char));\n    sprintf(vname, \"%s:luseSourceModel\", section);\n    precompute->luseSourceMod = iniparser_getboolean(ini, vname, 1);\n\n    memset(vname, 0, 128*sizeof(char));\n    sprintf(vname, \"%s:sourceModel\", section);\n    s = iniparser_getstring(ini, vname, NULL);\n    if (s != NULL)\n    {\n        strcpy(precompute->sourceModel, s);\n        if (!os_path_isfile(precompute->sourceModel) &&\n            precompute->luseSourceMod)\n        {\n            printf(\"%s: Source model doesn't %s exist\\n\", fcnm, s);\n            precompute->luseSourceMod = false;\n        }\n    }\n    else\n    {\n        precompute->luseSourceMod = false;\n    }\n\n    memset(vname, 0, 128*sizeof(char));\n    sprintf(vname, \"%s:hspecArchiveFile\", section);\n    s = iniparser_getstring(ini, vname, \"hspecFFgreens.h5\");\n    dirName = os_dirname(s, &ierr);\n    if (!os_path_isdir(dirName))\n    {\n        ierr = os_makedirs(dirName);\n        if (ierr != 0)\n        {\n            printf(\"%s: Failed to make output directory: %s\\n\", fcnm, dirName);\n            return -1;\n        }\n    }\n    memory_free8c(&dirName);\n    strcpy(precompute->hspecArchiveFile, s);\n\n    //memset(vname, 0, 128*sizeof(char));\n    //sprintf(vname, \"%s:modelIdentifier\", section);\n    //s = iniparser_getstring(ini, vname, \"UNKNOWN\");\n    //strcpy(precompute->modelIdentifer, s);\n\n    memset(vname, 0, 128*sizeof(char));\n    sprintf(vname, \"%s:crustDir\", section);\n    s = iniparser_getstring(ini, vname, CPS_DEFAULT_CRUST1_DIRECTORY);\n    if (s != NULL)\n    {\n        strcpy(precompute->crustDir, s);\n        if (!os_path_isdir(precompute->crustDir) && precompute->luseCrust)\n        {\n            printf(\"%s: crust1.0 directory %s doesn't exist\\n\", fcnm, s);\n            precompute->luseCrust = false;\n        }\n    }\n    else\n    {\n        precompute->luseCrust = false;\n    }\n\n    memset(vname, 0, 128*sizeof(char)); \n    sprintf(vname, \"%s:luseDistanceTable\", section);\n    precompute->luseDistanceTable = iniparser_getboolean(ini, vname, false);\n    if (precompute->luseDistanceTable)\n    {\n        memset(vname, 0, 128*sizeof(char));\n        sprintf(vname, \"%s:hspecDistanceFile\", section);\n        s = iniparser_getstring(ini, vname, NULL);\n        if (!os_path_isfile(s))\n        {\n            printf(\"%s: files %s doesn't exist\\n\", fcnm, s);\n            return -1;\n        }\n        strcpy(precompute->hspecDistanceFile, s);\n        dfl = fopen(s, \"r\");\n        memset(cline, 0, 256*sizeof(char));\n        fgets(cline, 256, dfl);\n        memset(cline, 0, 256*sizeof(char));\n        fgets(cline, 256, dfl);\n        precompute->ndists = atoi(cline);\n        if (precompute->ndists < 1)\n        {\n            printf(\"%s: Invalid number of distances\\n\", fcnm);\n            return -1;\n        }\n        precompute->dists\n            = (double *) calloc((size_t) precompute->ndists, sizeof(double));\n        for (i=0; i<precompute->ndists; i++)\n        {\n            memset(cline, 0, 256*sizeof(char));\n            if (fgets(cline, 256, dfl) == NULL)\n            {\n                printf(\"%s: premature end of distance file\\n\", fcnm);\n                return -1;\n            }\n            precompute->dists[i] = atof(cline);\n        }\n        fclose(dfl);\n    }\n    else\n    {\n        precompute->dists\n            = (double *) calloc((size_t) precompute->ndists, sizeof(double));\n        ierr = array_linspace64f_work(dist0, dist1,\n                                      precompute->ndists, precompute->dists);\n    }\n    // depths\n    precompute->depths\n        = (double *) calloc((size_t) precompute->ndepths, sizeof(double));\n    ierr = array_linspace64f_work(depth0, depth1,\n                                  precompute->ndepths, precompute->depths);\n    iniparser_freedict(ini);\n    return ierr;\n}\n//============================================================================//\nint prepmt_hspec96_readHspec96Parameters(\n    const char *iniFile,\n    struct hprep96_parms_struct *hprepParms,\n    struct hspec96_parms_struct *hspecParms,\n    struct hpulse96_parms_struct *hpulseParms)\n{\n    const char *fcnm = \"prepmt_hspec96_readHspec96Parameters\\0\";\n    int ierr;\n    cps_setHprep96Defaults(hprepParms);\n    cps_setHspec96Defaults(hspecParms);\n    ierr = prepmt_hpulse96_readHpulse96Parameters(iniFile,\n                                                  \"hpulse96\\0\", hpulseParms);\n    if (ierr != 0)\n    {\n        printf(\"%s: Error reading hpulse parameters\\n\", fcnm);\n    }\n    return ierr;\n}\n//============================================================================//\n/*!\n * @brief Parses the command line arguments for the ini file.\n *\n * @param[in] argc      Number of arguments input to the program.\n * @param[in] argv      Command line arguments.\n *\n * @param[out] iniFile  If the result is 0 then this is the ini file.\n *\n * @result 0 indicates success. \\n\n *        -1 indicates the user inquired about the usage. \\n\n *        -2 indicates the command line argument is invalid.\n *\n * @author Ben Baker, ISTI\n *\n */\nstatic int parseArguments(int argc, char *argv[], char iniFile[PATH_MAX])\n{\n    bool linFile;\n    linFile = false;\n    memset(iniFile, 0, PATH_MAX*sizeof(char));\n    while (true)\n    {   \n        static struct option longOptions[] =\n        {\n            {\"help\", no_argument, 0, '?'},\n            {\"help\", no_argument, 0, 'h'},\n            {\"ini_file\", required_argument, 0, 'i'},\n            {\"section\", required_argument, 0, 's'},\n            {0, 0, 0, 0}\n        };\n        int c, optionIndex;\n        c = getopt_long(argc, argv, \"?hi:\",\n                        longOptions, &optionIndex);\n        if (c ==-1){break;}\n        if (c == 'i')\n        {\n            strcpy(iniFile, (const char *) optarg);\n            linFile = true;\n        }\n        else if (c == 'h' || c == '?')\n        {\n            printUsage();\n            return -2;\n        }\n        else\n        {\n            printf(\"%s: Unknown options: %s\\n\",\n                   PROGRAM_NAME, argv[optionIndex]);\n        }\n    }\n    if (!linFile)\n    {\n        printf(\"%s: Error must specify ini file\\n\\n\", PROGRAM_NAME);\n        printUsage();\n        return -1;\n    }\n    else\n    {\n        if (!os_path_isfile(iniFile))\n        {\n            printf(\"%s: Error - ini file: %s does not exist\\n\",\n                   PROGRAM_NAME, iniFile);\n            return EXIT_FAILURE;\n        }\n    }\n    return 0;\n}\n//============================================================================//\nstatic void printUsage(void)\n{\n    printf(\"Usage:\\n   %s -i iniFile\\n\", PROGRAM_NAME); \n    printf(\"or\\n\");\n    printf(\"    mpirun -np nProcessors %s -i iniFile\\n\", PROGRAM_NAME);\n    printf(\"Required arguments:\\n\");\n    printf(\"    -i ini_file specifies the initialization file\\n\");\n    printf(\"Optional arguments:\\n\");\n    printf(\"    -h displays this message\\n\");\n    printf(\"    -np Number of computer processors to use\\n\");\n    return;\n}\n//============================================================================//\nstatic void grns2sac(const struct hwave_greens_struct grns,\n                     struct sacData_struct sac[10])\n{\n    const char *kcmpnm[10] = {\"ZDD\\0\", \"RDD\\0\", \"ZDS\\0\", \"RDS\\0\", \"TDS\\0\",\n                              \"ZSS\\0\", \"RSS\\0\", \"TSS\\0\", \"ZEX\\0\", \"REX\\0\"};\n    double cmpinc, cmpaz;\n    int i, k;\n    bool lsh;\n    for (k=0; k<10; k++)\n    {\n        memset(&sac[k], 0, sizeof(struct sacData_struct));\n        sacio_setDefaultHeader(&sac[k].header);\n        lsh = false;\n        sac[k].header.npts = grns.npts;\n        //sac[k].header.b = grns.b;\n        sac[k].npts = grns.npts;\n        sac[k].header.b = grns.t0;\n        sac[k].header.e = grns.t0 + (double) (grns.npts - 1)*grns.dt;\n        sac[k].header.delta = grns.dt;\n        sac[k].header.dist = grns.dist;\n        sac[k].header.evdp = grns.evdep;\n        sac[k].header.stel = grns.stelel;\n        sac[k].header.gcarc = grns.dist/111.195;\n        sac[k].header.o =-grns.t0;\n        strcpy(sac[k].header.kevnm, \"SYNTHETIC\");\n        strcpy(sac[k].header.ko, \"O\\0\");\n        sac[k].header.a = grns.timep;\n        strcpy(sac[k].header.ka, \"P\\0\");\n        sac[k].header.az = 0.0;\n        sac[k].header.baz = 180.0;\n        sac[k].header.lcalda = 0;\n        sac[k].header.norid = 0;\n        sac[k].header.nevid = 0;\n        sac[k].header.nzyear = 1970;\n        sac[k].header.nzjday = 1;\n        sac[k].header.nzhour = 0;\n        sac[k].header.nzmin = 0;\n        sac[k].header.nzsec = 0;\n        sac[k].header.nzmsec = 0;\n        sac[k].header.lhaveHeader = true;\n        strcpy(sac[k].header.kcmpnm, kcmpnm[k]); \n        sac[k].data = (double *) calloc((size_t) grns.npts, sizeof(double));\n        cmpaz = 0.0;\n        cmpinc = 0.0;\n        if (k == 0)\n        {\n            for (i=0; i<grns.npts; i++){sac[k].data[i] = grns.zdd[i];}\n        }\n        else if (k == 1)\n        {\n            for (i=0; i<grns.npts; i++){sac[k].data[i] = grns.rdd[i];}\n            cmpinc = 90.0;\n        }\n        else if (k == 2)\n        {\n            for (i=0; i<grns.npts; i++){sac[k].data[i] = grns.zds[i];}\n        }\n        else if (k == 3)\n        {\n            for (i=0; i<grns.npts; i++){sac[k].data[i] = grns.rds[i];}\n            cmpinc = 90.0;\n        }\n        else if (k == 4)\n        {\n            for (i=0; i<grns.npts; i++){sac[k].data[i] = grns.tds[i];}\n            lsh = true;\n            cmpaz = 90.0;\n            cmpinc = 90.0;\n        }\n        else if (k == 5)\n        {\n            for (i=0; i<grns.npts; i++){sac[k].data[i] = grns.zss[i];}\n        }\n        else if (k == 6)\n        {\n            for (i=0; i<grns.npts; i++){sac[k].data[i] = grns.rss[i];}\n            cmpinc = 90.0;\n        }\n        else if (k == 7)\n        {\n            for (i=0; i<grns.npts; i++){sac[k].data[i] = grns.tss[i];}\n            lsh = true;\n            cmpaz = 90.0;\n            cmpinc = 90.0;\n        }\n        else if (k == 8)\n        {\n            for (i=0; i<grns.npts; i++){sac[k].data[i] = grns.zex[i];}\n        }\n        else if (k == 9)\n        {\n            for (i=0; i<grns.npts; i++){sac[k].data[i] = grns.rex[i];}\n            cmpinc = 90.0;\n        }\n        if (lsh)\n        {\n            sac[k].header.t1 = grns.timesh;\n            strcpy(sac[k].header.kt0, \"SH\\0\");\n        }\n        else\n        {\n            sac[k].header.t1 = grns.timesv;\n            strcpy(sac[k].header.kt0, \"SV\\0\");\n        }\n        sac[k].header.cmpaz = cmpaz;\n        sac[k].header.cmpinc = cmpinc;\n    }\n    return;\n}\n", "meta": {"hexsha": "89b51f096ed808feef64a46baf7a4547816ae913", "size": 29242, "ext": "c", "lang": "C", "max_stars_repo_path": "prepmt/hspec96.c", "max_stars_repo_name": "bakerb845/parmt", "max_stars_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_stars_repo_licenses": ["Intel"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "prepmt/hspec96.c", "max_issues_repo_name": "bakerb845/parmt", "max_issues_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_issues_repo_licenses": ["Intel"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "prepmt/hspec96.c", "max_forks_repo_name": "bakerb845/parmt", "max_forks_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_forks_repo_licenses": ["Intel"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1905940594, "max_line_length": 80, "alphanum_fraction": 0.5465426441, "num_tokens": 8120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.03067579960602992, "lm_q1q2_score": 0.014499943605889926}}
{"text": "#if !defined(PETIGABL_H)\n#define PETIGABL_H\n\n#include <petsc.h>\n#include <petscblaslapack.h>\n#if defined(PETSC_BLASLAPACK_UNDERSCORE)\n   #define sgetri_ sgetri_\n   #define dgetri_ dgetri_\n   #define qgetri_ qgetri_\n   #define cgetri_ cgetri_\n   #define zgetri_ zgetri_\n#elif defined(PETSC_BLASLAPACK_CAPS)\n   #define sgetri_ SGETRI\n   #define dgetri_ DGETRI\n   #define qgetri_ QGETRI\n   #define cgetri_ CGETRI\n   #define zgetri_ ZGETRI\n#else /* (PETSC_BLASLAPACK_C) */\n   #define sgetri_ sgetri\n   #define dgetri_ dgetri\n   #define qgetri_ qgetri\n   #define cgetri_ cgetri\n   #define zgetri_ zgetri\n#endif\n#if !defined(PETSC_USE_COMPLEX)\n  #if defined(PETSC_USE_REAL_SINGLE)\n    #define LAPACKgetri_ sgetri_\n  #elif defined(PETSC_USE_REAL_DOUBLE)\n    #define LAPACKgetri_ dgetri_\n  #else /* (PETSC_USE_REAL_QUAD) */\n    #define LAPACKgetri_ qgetri_\n  #endif\n#else\n  #if defined(PETSC_USE_REAL_SINGLE)\n    #define LAPACKgetri_ cgetri_\n  #elif defined(PETSC_USE_REAL_DOUBLE)\n    #define LAPACKgetri_ zgetri_\n  #else /* (PETSC_USE_REAL_QUAD) */\n    #define LAPACKgetri_ wgetri_\n  #endif\n#endif\nEXTERN_C_BEGIN\nextern void LAPACKgetri_(PetscBLASInt*,PetscScalar*,PetscBLASInt*,\n                         PetscBLASInt*,PetscScalar*,PetscBLASInt*,\n                         PetscBLASInt*);\nEXTERN_C_END\n\n#if PETSC_VERSION_LE(3,3,0)\n#undef PetscBLASIntCast\n#undef  __FUNCT__\n#define __FUNCT__ \"PetscBLASIntCast\"\nPETSC_STATIC_INLINE PetscErrorCode PetscBLASIntCast(PetscInt a,PetscBLASInt *b)\n{\n  PetscFunctionBegin;\n#if defined(PETSC_USE_64BIT_INDICES) && !defined(PETSC_HAVE_64BIT_BLAS_INDICES)\n  if ((a) > PETSC_BLAS_INT_MAX) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,\"Array too long for BLAS/LAPACK\");\n#endif\n  *b =  (PetscBLASInt)(a);\n  PetscFunctionReturn(0);\n}\n#endif\n\n#endif/*PETIGABL_H*/\n", "meta": {"hexsha": "31a31d4073537c615250e4bf1d6ba0f3e139411e", "size": 1793, "ext": "h", "lang": "C", "max_stars_repo_path": "src/petigabl.h", "max_stars_repo_name": "otherlab/petiga", "max_stars_repo_head_hexsha": "ce8c07de8511000ee6f1cbfd3fb90fda9cb31954", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-08-31T21:20:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T10:40:32.000Z", "max_issues_repo_path": "src/petigabl.h", "max_issues_repo_name": "otherlab/petiga", "max_issues_repo_head_hexsha": "ce8c07de8511000ee6f1cbfd3fb90fda9cb31954", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/petigabl.h", "max_forks_repo_name": "otherlab/petiga", "max_forks_repo_head_hexsha": "ce8c07de8511000ee6f1cbfd3fb90fda9cb31954", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-11-08T12:55:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-14T10:40:40.000Z", "avg_line_length": 28.015625, "max_line_length": 115, "alphanum_fraction": 0.7506971556, "num_tokens": 622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.0346188415781891, "lm_q1q2_score": 0.014494801974261918}}
{"text": "//  This random generator is a C++ wrapper for the GNU Scientific Library\n//  Copyright (C) 2001 Torbjorn Vik\n\n//  This program is free software; you can redistribute it and/or modify\n//  it under the terms of the GNU General Public License as published by\n//  the Free Software Foundation; either version 2 of the License, or\n//  (at your option) any later version.\n\n//  This program is distributed in the hope that it will be useful,\n//  but WITHOUT ANY WARRANTY; without even the implied warranty of\n//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n//  GNU General Public License for more details.\n\n//  You should have received a copy of the GNU General Public License\n//  along with this program; if not, write to the Free Software\n//  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n#ifndef __histogram_h\n#define __histogram_h\n\n#include <gsl/gsl_histogram.h>\n#include <stdexcept>\n#include <exception>\n\nnamespace gsl{\n#ifndef __HP_aCC\nusing std::string;\nusing std::runtime_error;\n#endif\n\n//! Encapsulates the histogram object of gsl. Only uniformly spaced bins yet.\nclass histogram\n{\npublic:\n\thistogram(int nBins, double xmin, double xmax)\n\t{\n\t\th=gsl_histogram_calloc(nBins);\n\t\tif (!h)\n\t\t{\n\t\t\tthrow runtime_error(\"Couldn't allocate memory for histogram\");\n\t\t}\n\t\tgsl_histogram_set_ranges_uniform(h, xmin, xmax);\n\t}\n\t~histogram(){gsl_histogram_free(h);}\n\n//@{ Updating and Accessing Methods\n\tint increment(double x){return gsl_histogram_increment(h, x);}\n\tint accumulate(double x, double weight){return gsl_histogram_accumulate(h, x, weight);}\n\tdouble get(int i) const {return gsl_histogram_get(h, i);}\n\tdouble& operator[](const uint & i) \n\t{\n\t\tconst uint n = h->n;\n\t\t\n\t\tif (i >= n)\n\t\t{\n\t\t\tthrow runtime_error(\"index lies outside valid range of 0 .. n - 1\");\n//\t\t\tGSL_ERROR_VAL (\"index lies outside valid range of 0 .. n - 1\", GSL_EDOM, 0);\n\t\t}\n\t\t\n\t\treturn h->bin[i];\n\t}\n\tconst double& operator[](const uint & i) const //{return (*this)[i];/*gsl_histogram_get(h, i);*/}\n\t{\n\t\tconst uint n = h->n;\n\t\t\n\t\tif (i >= n)\n\t\t{\n\t\t\tthrow runtime_error(\"index lies outside valid range of 0 .. n - 1\");\n//\t\t\tGSL_ERROR_VAL (\"index lies outside valid range of 0 .. n - 1\", GSL_EDOM, 0);\n\t\t}\n\t\t\n\t\treturn h->bin[i];\n\t}\n\n\tvoid get_range(int i, double& xmin, double& xmax) const {gsl_histogram_get_range(h, i, &xmin, &xmax);}\n//@}\n\n//@{These functions return the maximum upper and minimum lower range limits\n// and the number of bins of the histogram h. They provide a way of determining these values without\n//    accessing the gsl_histogram struct directly. \n\tdouble max() const {return gsl_histogram_max(h);}\n\tdouble min() const {return gsl_histogram_min(h);}\n\tint bins()const {return gsl_histogram_bins(h);}\n\tint size()const {return gsl_histogram_bins(h);}\n\n//@}\n\n//@{ Histogram statistics\n\tdouble mean()const {return gsl_histogram_mean(h);} // not in gsl library ?\n\tdouble max_val() const {return gsl_histogram_max_val(h);}\n\tint max_bin() const {return gsl_histogram_max_bin(h);}\n\tdouble min_val() const {return gsl_histogram_min_val(h);}\n\tint min_bin() const {return gsl_histogram_min_bin(h);}\n\tdouble sum() const {return gsl_histogram_sum(h);}\n//@}\n\n\n//@{ Accessor for gsl compatibility\n\tgsl_histogram*       gslobj()       { return h;}\n\tconst gsl_histogram* gslobj() const { return h;}\n//@}\n\nprotected:\n\tgsl_histogram * h;\n};\n}\n\n#endif // __histogram_h\n", "meta": {"hexsha": "61408fac42a672fed949f8a37def05821ff6f8bd", "size": 3370, "ext": "h", "lang": "C", "max_stars_repo_path": "src/gslwrap/histogram.h", "max_stars_repo_name": "entn-at/GlottDNN", "max_stars_repo_head_hexsha": "b7db669d7f34da92ab34742d75a8ba3c70763a65", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-11-27T01:35:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T01:17:11.000Z", "max_issues_repo_path": "src/gslwrap/histogram.h", "max_issues_repo_name": "entn-at/GlottDNN", "max_issues_repo_head_hexsha": "b7db669d7f34da92ab34742d75a8ba3c70763a65", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gslwrap/histogram.h", "max_forks_repo_name": "entn-at/GlottDNN", "max_forks_repo_head_hexsha": "b7db669d7f34da92ab34742d75a8ba3c70763a65", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-11-27T01:35:33.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-27T01:35:33.000Z", "avg_line_length": 31.2037037037, "max_line_length": 103, "alphanum_fraction": 0.7103857567, "num_tokens": 862, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014734858584297, "lm_q2_score": 0.03358950298969727, "lm_q1q2_score": 0.014448435651334525}}
{"text": "// A cascade of IntegralHOGDetectors.\n//\n// Copyright 2012 Mark Desnoyer (mdesnoyer@gmail.com)\n\n#ifndef __HOG_DETECTOR_INTEGRAL_HOG_CASCADE_TRAINER_H__\n#define __HOG_DETECTOR_INTEGRAL_HOG_CASCADE_TRAINER_H__\n\n#include <ros/ros.h>\n#include <boost/shared_ptr.hpp>\n#include <boost/scoped_ptr.hpp>\n#include <functional>\n#include <vector>\n#include <string>\n#include <queue>\n#include <limits>\n#include <cmath>\n#include <opencv2/core/core.hpp>\n#include <boost/unordered_map.hpp>\n#include <boost/unordered_set.hpp>\n#include <gsl/gsl_multimin.h>\n#include \"hog_detector/integral_hog_cascade.h\"\n#include \"hog_detector/integral_hog_detector.h\"\n#include \"hog_detector/interpolation.h\"\n\nnamespace hog_detector {\n\n// Class to calculate the various time components of the cascade\nclass IntegralCascadeTimeCalculator {\npublic:\n  // Creates the calculator based on text files with timing data (in seconds)\n  //\n  // integralHistTime - single line with the time\n  // fillBlockCacheTime - lines of <blockW>,<blockH>,<time>\n  // svmEvalTime - lines of <descriptorSize>,<subWinW>,<subWinH>,<time/window>\n  // trueHogTime - lines of <nWindows>,<time>\n  IntegralCascadeTimeCalculator(const std::string& integralHistTime,\n                                const std::string& fillBlockCacheTime,\n                                const std::string& svmEvalTime,\n                                const std::string& trueHogTime);\n\n  // Time to compute the integral histogram\n  double GetIntegralHistTime() const { return integralHistTime_; }\n\n  // Time to fill the block cache for a given block size\n  double GetFillCacheTime(const cv::Size& blockSize) const;\n\n  // Time to do the svm evaluation of a single window\n  double GetSVMEvalTime(int descriptorSize) const;\n\n  // Time to compute the full HOG detector on N windows\n  double GetTrueHogTime(int nWindows) const;\n\n  int GetMaxWindows() const { return maxWindows_; }\n\n  double GetMaxHogTime() const { return GetTrueHogTime(GetMaxWindows()); }\n\nprivate:\n  double integralHistTime_;\n\n  boost::unordered_map<cv::Size, double> cacheFillTime_;\n\n  boost::scoped_ptr<Interpolator> svmTime_;\n  boost::scoped_ptr<Interpolator> trueHogTime_;\n\n  int maxWindows_;\n};\n\nclass IntegralHogCascadeTrainer {\npublic:\n  // Constructor\n  //\n  // timeCalculator - takes ownership of it\n  IntegralHogCascadeTrainer(IntegralCascadeTimeCalculator* timeCalculator,\n                            const cv::Size& winSize);\n\n  // Add a candidate IntegralHogDetector.\n  void AddCandidateDetector(IntegralHogDetector::Ptr detector) {\n    if (detector->winSize() == winSize_) {\n      detectorIdx_[detector.get()] = detectors_.size();\n      detectors_.push_back(detector);\n    } else {\n      ROS_WARN_STREAM(\"The detector has the wrong window size: (\" \n                      << winSize_.width << \",\"\n                      << winSize_.height  << \") vs. (\"\n                      << detector->winSize().width << \",\"\n                      << detector->winSize().height << \")\");\n    }\n  }\n\n  // Trains the cascade detector\n  //\n  // Inputs:\n  // filenames - Filenames of images to train with. Uses the center\n  //             winSize window in the image.\n  // labels - Labels for all the images. 1 is positive, -1 is negative\n  // budget - Processing budget in seconds (average per/frame)\n  // missCost - The cost of a miss\n  // falsePosCost - The cost of a false positive\n  // fracNegSampled - fraction of the number of negative examples we're\n  //                  actually training with. So the number of negative \n  //                  samples seen by this class is trueNegs/fracNegSampled\n  void Train(const std::vector<std::string>& filenames,\n             const std::vector<float>& labels,\n             float budget,\n             float missCost,\n             float falsePosCost);\n  // Train using the supermodular-submodular approach\n  void TrainSupSub(const std::vector<std::string>& filenames,\n                   const std::vector<float>& label,\n                   float missCost,\n                   float falsePosCost,\n                   float timeCostPerError, // time is per seconds\n                   float fracNegSampled);\n\n  // Training can also be done by adding one image at a time and then\n  // calling TrainWithLoadedData\n  void AddImageForTraining(const cv::Mat& image,\n                           const std::vector<cv::Rect>& rois,\n                           float label);\n  void TrainWithLoadedData(float budget,\n                           float missCost,\n                           float falsePosCost);\n  void TrainSupSubWithLoadedData(float missCost,\n                                 float falsePosCost,\n                                 float timeCostPerError,\n                                 float fracNegSampled);\n\n  const IntegralHogCascade* cascade() const { return cascade_.get(); }\n\nprivate:\n  // Structure to hold the score and selected threshold for a given detector\n  struct DetectorStats {\n    DetectorStats(float _score, float _thresh, unsigned int _detectorIdx)\n      : score(_score), thresh(_thresh), detectorIdx(_detectorIdx) {}\n\n    // Sort primarily based on the score\n    bool operator<(const DetectorStats& other) const {\n      if (fequal(score, other.score)) {\n        if (detectorIdx == other.detectorIdx) {\n          return thresh < other.thresh;\n        }\n        return detectorIdx < other.detectorIdx;\n      }\n      return score < other.score;\n    }\n    bool operator==(const DetectorStats& other) const {\n      return detectorIdx == other.detectorIdx && fequal(score, other.score)\n        && fequal(thresh, other.thresh);\n    }\n    bool operator>(const DetectorStats& other) const {return other < *this;}\n\n    bool fequal(float a, float b,\n                float ep=std::numeric_limits<float>::epsilon()*100) const {\n      return std::fabs(a-b) < ep;\n    }\n\n    float score;\n    float thresh;\n    unsigned int detectorIdx;\n  };\n      \n\n  // Number of images being trained on\n  int nImages_;\n\n  cv::Size winSize_;\n\n  boost::scoped_ptr<IntegralCascadeTimeCalculator> timeCalculator_;\n\n  // All the possible detectors\n  std::vector<IntegralHogDetector::Ptr> detectors_;\n\n  // Scores of the training images for all the detectors. Each row is\n  // a different detector and each column is a different training\n  // image.\n  cv::Mat_<float> scores_;\n\n  // Labels for all the loaded images\n  cv::Mat_<float> labels_;\n\n  // Inverse index from the detector to its index in scores_ and labels_\n  boost::unordered_map<IntegralHogDetector*, int> detectorIdx_;\n\n  // The trained cascade\n  boost::scoped_ptr<IntegralHogCascade> cascade_;\n\n  // The true sum of the number of images given that the negatives are\n  // sampled more sparsely.\n  double trueImageSum_;\n\n  void LoadImagesForTraining(const std::vector<std::string>& filenames,\n                             const std::vector<float>& labels);\n\n  // Trains a cascade using a greedy metric.\n  //\n  // Inputs:\n  // budget - Time budget in seconds,\n  // mistCost - Cost of a miss\n  // falsePosCost - Cost of a false positive\n  // metric - The metric to use\n  //\n  // Outputs:\n  // cascade - The trained cascade\n  // returns - Total cost of the cascade\n  template <typename T>\n  float TrainUsingGreedyMetric(float budget, float missCost,\n                               float falsePosCost,\n                               T metric,\n                               IntegralHogCascade* cascade);\n\n  // Two different metrics for selecting the next best detector.\n  //\n  // Inputs:\n  // missCost - Cost of a miss\n  // falsePosCost - Cost of a false positive\n  // inputWindows - - Boolean matrix identifying which training windows are\n  //                still in play. Will be updated\n  // allocatedTime - The time already allocated. Will be updated after this\n  //                 selection\n  // cacheSizesUsed - Set of cache sizes used. Will be updated after this\n  //                  selection.\n  //\n  // Returns:\n  // pair of threshold and index of the selected detector\n  std::pair<float, int> SelectBestDetectorIgnoringTime(\n    float missCost,\n    float falsePosCost,\n    cv::Mat& inputWindows,\n    float& allocatedTime,\n    boost::unordered_set<cv::Size>& cacheSizesUsed);\n\n  std::pair<float, int> SelectBestDetectorPerTime(\n    float missCost,\n    float falsePosCost,\n    cv::Mat& inputWindows,\n    float& allocatedTime,\n    boost::unordered_set<cv::Size>& cacheSizesUsed);\n\n  // Updates all the tracking data for when a detector is chosen\n  void ChooseDetector(int detectorI, float thresh,\n                      cv::Mat& inputWindows,\n                      float& allocatedTime,\n                      boost::unordered_set<cv::Size>& cacheSizesUsed);   \n\n\n  // Selects the best detector that is under budget\n  void SelectBestDetectorUnderBudget(\n    float budget, float missCost,\n    float falsePosCost,\n    const cv::Mat& inputWindows,\n    float allocatedTime,\n    const boost::unordered_set<cv::Size>& cacheSizesUsed,\n    float* thresh,\n    int* chosenDetector,\n    float* cost);\n\n  // Selects the best detector according to an approximate submodular measure that is tight at cascade.\n  // \n  // Inputs:\n  //   missCost - Cost of a miss\n  //   falsePosCost - Cost of a false positive\n  //   timeCostPerError - Conversion factor for 1s of processing time compared\n  //                    to an error.\n  //   cascade - The best cascade so far. The approximation is tight at\n  //               this point.\n  //   winPastCascade - Boolean vector specifying the windows that pass the cascade\n  //\n  // Outputs:\n  //  thresh - Threshold of the detector to choose\n  //  chosenDetector - Index of the chosen detector\n  //  returns - The delta cost for the added detector\n  typedef std::priority_queue<DetectorStats, std::vector<DetectorStats>,\n                              std::greater<DetectorStats> > DetectorQueue;\n  float SelectBestDetectorApprox(\n    float missCost,\n    float falsePosCost,\n    float timeCostPerError,\n    float fracNegSampled,\n    const IntegralHogCascade& cascade,\n    const cv::Mat& winPastApproxCascade,\n    DetectorQueue* detectorQueue,\n    float* thresh,\n    int* chosenDetector);\n\n  // Compute the bayes risk for a given threshold on a set of images\n  // whose scores are curScores.\n  double ComputeBayesRisk(const cv::Mat& inputWindows,\n                          const cv::Mat_<float>& curScores,\n                          float thresh,\n                          double missCost,\n                          double falsePosCost);\n\n  double ComputeProcessingTimeForDetector(\n    float fracInputWindows,\n    int detectorI,\n    const boost::unordered_set<cv::Size>& cacheSizesUsed);\n\n  // For the SupSub proceedure find the cascade that minimizes the\n  // approximate cost. The cost is approximate because the D_a and C_M\n  // terms are approximated by an upper bound.\n  //\n  // Inputs:\n  // missCost - Cost of a miss\n  // falsePosCost - Cost of a false positive, already adjusted with\n  //                fracNegSampled\n  // timeCostPerError - Conversion factor for 1s of processing time compared\n  //                    to an error.\n  // bestCascade - The best cascade so far. The approximation is tight at\n  //               this point.\n  // fracNegSampled - fraction of the number of negative examples we're\n  //                  actually training with. So the number of negative \n  //                  samples seen by this class is trueNegs/fracNegSampled\n  //\n  // Outputs:\n  // bestCascade - An update\n  // Returns - The true cost of the best cascade (not the approximate cost)\n  float MinimizeApproxCost(float missCost, float falsePosCost,\n                           float timeCostPerError,\n                           float fracNegSampled,\n                           boost::scoped_ptr<IntegralHogCascade>* ioCascade);\n                \n  // Computes the total cost of the cascade\n  double ComputeTotalCost(float missCost,\n                          float falsePosCost,\n                          float timeCostPerError,\n                          float fracNegSampled,\n                          const IntegralHogCascade& cascade);\n\n  // Initializes the data for computing the approximate submodular cost.\n  //\n  // Inputs:\n  // missCost - Cost of a miss\n  // falsePosCost - Cost of a false positive\n  // timeCostPerError - Conversion factor for 1s of processing time compared\n  //                    to an error.\n  // fracNegSampled - fraction of the number of negative examples we're\n  //                  actually training with. So the number of negative \n  //                  samples seen by this class is trueNegs/fracNegSampled\n  // cascade - The cascade to approximate to\n  //\n  // Outputs:\n  // removeCosts - Map for each stage for the change in cost if it is removed\n  // pastCascade - Vector specifying which entries got past the cascade from\n  //               rows in scores_\n  void InitializeApproxSubCost(\n    float missCost,\n    float falsePosCost,\n    float timeCostPerError,\n    float fracNegSampled,\n    const IntegralHogCascade& cascade,\n    boost::unordered_map<IntegralHogCascade::Stage, float>* removeCosts,\n    cv::Mat* pastCascade);\n\n  float CalculateDeltaForRemovingStage(\n    float falsePosCost,\n    float timeCostPerError,\n    float fracNegSampled,\n    const IntegralHogCascade& cascade,\n    const boost::unordered_map<IntegralHogCascade::Stage, float>& approxCosts,\n    const IntegralHogCascade::Stage& stage);\n\n  // Find the best approximate cost for a given detector.\n  //\n  // missCost, falsePosCost, timeCostPerError, fraceNegSampled - \n  //   relative weights for the costs.\n  // scores - score of the detector evaluated on each candidate region\n  // usefulPassApproxCascade - usefule regions that pass the approx cascade\n  // falsePosWins - False positive windows from the current cascade\n  // windowsPassed - Windows that pass the current cascade\n  // usefulWindows - Windows that are positives for training\n  // notUsefuleWindows - Windows that are negatives for training\n  //\n  // Returns: Pair of <cost, bestThreshold>\n  std::pair<float, float> GetBestApproxCost(\n    unsigned int detectorIdx,\n    float missCost, \n    float falsePosCost, \n    float timeCostPerError,\n    float fracNegSampled,\n    double baseHogTime,\n    float nPassedApproxCascade,\n    const cv::Mat& usefulPassApproxCascade,\n    const cv::Mat& falsePosWins,\n    const cv::Mat& windowsPassed,\n    const cv::Mat& usefulWindows,\n    const cv::Mat& notUsefulWindows);\n                                            \n};\n\n// Class that finds the threshold to minimize the cost of a filter\nclass DeltaMinimizer {\npublic:\n  DeltaMinimizer();\n  ~DeltaMinimizer();\n\n  // Minimizes the cost of adding a current detector\n  //\n  // Inputs:\n  // missCost, falsePosCost, timeCostPerError, fraceNegSampled - \n  //   relative weights for the costs.\n  // scores - score of the detector evaluated on each candidate region\n  // usefulPassApproxCascade - usefule regions that pass the approx cascade\n  // falsePosWins - False positive windows from the current cascade\n  // windowsPassed - Windows that pass the current cascade\n  // usefulWindows - Windows that are positives for training\n  // notUsefuleWindows - Windows that are negatives for training\n  // timeCalculator - To calculate the time\n  // cpuDelta - cpu cost to run this detector\n  float MinimizeCost(float missCost, \n                     float falsePosCost, \n                     float timeCostPerError,\n                     float fracNegSampled,\n                     int nImages,\n                     float trueImageSum,\n                     double baseHogTime,\n                     const cv::Mat_<float>& scores,\n                     const cv::Mat& usefulPassApproxCascade,\n                     const cv::Mat& falsePosWins,\n                     const cv::Mat& windowsPassed,\n                     const cv::Mat& usefulWindows,\n                     const cv::Mat& notUsefulWindows,\n                     const IntegralCascadeTimeCalculator* timeCalculator,\n                     float cpuDelta);\n\n  float bestCost() const { return bestCost_; }\n  float bestThresh() const { return bestThresh_; }\n\n  // Evaluates the cost function and its derivative with respect to\n  // the number of entries filtered. Public because gsl is old and\n  // needs acess to this.\n  void EvalWithDeriv(const gsl_vector* nFiltered, void* params,\n                     double* val, gsl_vector* derivs) const;\n  double EvalCost(const gsl_vector* nFiltered, void* params) const;\n  void EvalDeriv(const gsl_vector* nFiltered, void* params,\n                 gsl_vector* derivs) const;\n\nprivate:\n  float bestCost_;\n  float bestThresh_;\n\n  // Used for the minimization\n  gsl_multimin_fdfminimizer* minimizer_;\n  gsl_multimin_function_fdf minFunc_;\n\n  // Data used for the calculator\n  double cpuDelta_;\n  // Map from the number of new windows thresholded to the threshold.\n  boost::scoped_ptr<Interpolator> thresholdInterpolator_;\n  // Interpolator for the cost of extra misses with a given threshold\n  boost::scoped_ptr<Interpolator> missCostInterpolator_;\n  // Interpolator for the cost of the false positives relative to the\n  // number of new windows thresholded.\n  boost::scoped_ptr<Interpolator> falsePosInterpolator_;\n  // Interpolator for the HOG time delta\n  boost::scoped_ptr<Interpolator> hogTimeInterpolator_;\n\n  void RunMinimization(double minWindowsThreshed, double maxWindowsThreshed,\n                       double startPoint, double firstStep,\n                       float* bestCost, float* bestThresh);\n\n};\n\n} // namespace\n\n#endif //__HOG_DETECTOR_INTEGRAL_HOG_CASCADE_TRAINER_H__\n", "meta": {"hexsha": "f5954100f1ffdf56947cb93a1f174dd8787ba5b8", "size": 17502, "ext": "h", "lang": "C", "max_stars_repo_path": "hog_detector/include/hog_detector/integral_hog_cascade_trainer.h", "max_stars_repo_name": "MRSD2018/reefbot-1", "max_stars_repo_head_hexsha": "a595ca718d0cda277726894a3105815cef000475", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hog_detector/include/hog_detector/integral_hog_cascade_trainer.h", "max_issues_repo_name": "MRSD2018/reefbot-1", "max_issues_repo_head_hexsha": "a595ca718d0cda277726894a3105815cef000475", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hog_detector/include/hog_detector/integral_hog_cascade_trainer.h", "max_forks_repo_name": "MRSD2018/reefbot-1", "max_forks_repo_head_hexsha": "a595ca718d0cda277726894a3105815cef000475", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5579399142, "max_line_length": 103, "alphanum_fraction": 0.6618672152, "num_tokens": 3936, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.02887090872189326, "lm_q1q2_score": 0.01443545436094663}}
{"text": "//! \\file openmc_driver.h\n//! Driver to initialize and run OpenMC in stages\n#ifndef ENRICO_OPENMC_DRIVER_H\n#define ENRICO_OPENMC_DRIVER_H\n\n#include \"enrico/cell_instance.h\"\n#include \"enrico/geom.h\"\n#include \"enrico/neutronics_driver.h\"\n\n#include \"openmc/cell.h\"\n#include \"openmc/tallies/filter_cell_instance.h\"\n#include \"openmc/tallies/tally.h\"\n#include <gsl/gsl>\n#include <mpi.h>\n\n#include <vector>\n\nnamespace enrico {\n\n//! Driver to initialize and run OpenMC in stages\nclass OpenmcDriver : public NeutronicsDriver {\npublic:\n  //! One-time initalization of OpenMC and member variables\n  //! \\param comm An existing MPI communicator used to inialize OpenMC\n  explicit OpenmcDriver(MPI_Comm comm);\n\n  //! One-time finalization of OpenMC\n  ~OpenmcDriver();\n\n  //////////////////////////////////////////////////////////////////////////////\n  // NeutronicsDriver interface\n\n  //! Find cells corresponding to a vector of positions\n  //! \\param positions (x,y,z) coordinates to search for\n  //! \\return Handles to cells\n  std::vector<CellHandle> find(const std::vector<Position>& position) override;\n\n  //! Set the density of the material in a cell\n  //! \\param cell Handle to a cell\n  //! \\param rho Density in [g/cm^3]\n  void set_density(CellHandle cell, double rho) const override;\n\n  //! Set the temperature of a cell\n  //! \\param cell Handle to a cell\n  //! \\param T Temperature in [K]\n  void set_temperature(CellHandle cell, double T) const override;\n\n  //! Get the density of a cell\n  //! \\param cell Handle to a cell\n  //! \\return Cell density in [g/cm^3]\n  double get_density(CellHandle cell) const override;\n\n  //! Get the temperature of a cell\n  //! \\param cell Handle to a cell\n  //! \\return Temperature in [K]\n  double get_temperature(CellHandle cell) const override;\n\n  //! Get the volume of a cell\n  //! \\param cell Handle to a cell\n  //! \\return Volume in [cm^3]\n  double get_volume(CellHandle cell) const override;\n\n  //! Detemrine whether a cell contains fissionable nuclides\n  //! \\param cell Handle to a cell\n  //! \\return Whether the cell contains fissionable nuclides\n  bool is_fissionable(CellHandle cell) const override;\n\n  std::size_t n_cells() const override { return cells_.size(); }\n\n  //! Create energy production tallies\n  void create_tallies() override;\n\n  //! Determine number of cells participating in coupling\n  //! \\return Number of cells\n  xt::xtensor<double, 1> heat_source(double power) const final;\n\n  std::string cell_label(CellHandle cell) const;\n\n  //////////////////////////////////////////////////////////////////////////////\n  // Driver interface\n\n  //! Initialization required in each Picard iteration\n  void init_step() final;\n\n  //! Runs OpenMC for one Picard iteration\n  void solve_step() final;\n\n  //! Writes OpenMC output for given timestep and iteration\n  //! \\param timestep timestep index\n  //! \\param iteration iteration index\n  void write_step(int timestep, int iteration) final;\n\n  //! Finalization required in each Picard iteration\n  void finalize_step() final;\n\nprivate:\n  // Data members\n  openmc::Tally* tally_;               //!< Fission energy deposition tally\n  openmc::CellInstanceFilter* filter_; //!< Cell instance filter\n  std::vector<CellInstance> cells_;    //!< Array of cell instances\n  int n_fissionable_cells_;            //!< Number of fissionable cells in model\n};\n\n} // namespace enrico\n\n#endif // ENRICO_OPENMC_DRIVER_H\n", "meta": {"hexsha": "d6073e69df182dbbaa87cae89c857999eeee4fdd", "size": 3392, "ext": "h", "lang": "C", "max_stars_repo_path": "include/enrico/openmc_driver.h", "max_stars_repo_name": "pshriwise/enrico", "max_stars_repo_head_hexsha": "72b95ca947804f672e5f1726e169ef6f4889e78e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-02T16:21:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-02T16:21:59.000Z", "max_issues_repo_path": "include/enrico/openmc_driver.h", "max_issues_repo_name": "pshriwise/enrico", "max_issues_repo_head_hexsha": "72b95ca947804f672e5f1726e169ef6f4889e78e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-06-14T18:14:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-15T15:30:51.000Z", "max_forks_repo_path": "include/enrico/openmc_driver.h", "max_forks_repo_name": "lebuller/enrico", "max_forks_repo_head_hexsha": "edd04f1e02caf1c3fae2992e55d9a47e4429655c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7009345794, "max_line_length": 80, "alphanum_fraction": 0.6880896226, "num_tokens": 804, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2909808785120009, "lm_q2_score": 0.049589028426787335, "lm_q1q2_score": 0.014429459056183164}}
{"text": "/*******************************************************************************  *\n*\n*       This file is part of the General Hidden Markov Model Library,\n*       GHMM version __VERSION__, see http://ghmm.org\n*\n*       Filename: ghmm/ghmm/root_finder.c\n*       Authors:  Achim Gaedke\n*\n*       Copyright (C) 1998-2004 Alexander Schliep\n*       Copyright (C) 1998-2001 ZAIK/ZPR, Universitaet zu Koeln\n*       Copyright (C) 2002-2004 Max-Planck-Institut fuer Molekulare Genetik,\n*                               Berlin\n*\n*       Contact: schliep@ghmm.org\n*\n*       This library is free software; you can redistribute it and/or\n*       modify it under the terms of the GNU Library General Public\n*       License as published by the Free Software Foundation; either\n*       version 2 of the License, or (at your option) any later version.\n*\n*       This library is distributed in the hope that it will be useful,\n*       but WITHOUT ANY WARRANTY; without even the implied warranty of\n*       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n*       Library General Public License for more details.\n*\n*       You should have received a copy of the GNU Library General Public\n*       License along with this library; if not, write to the Free\n*       Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n*\n*\n*       This file is version $Revision: 2267 $\n*                       from $Date: 2009-04-24 11:01:58 -0400 (Fri, 24 Apr 2009) $\n*             last change by $Author: grunau $.\n*\n*******************************************************************************/\n\n#ifdef HAVE_CONFIG_H\n#  include \"../config.h\"\n#endif  /*  */\n  \n#ifndef DO_WITH_GSL\n  \n#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n#include \"ghmm_internals.h\"\n\ndouble ghmm_zbrent_AB (double (*func) (double, double, double, double),\n                   double x1, double x2, double tol, double A, double B,\n                   double eps) \n{\n  fprintf (stderr, \"Function ghmm_zbrent_AB() not implemented!\\n\");\n  exit (1);\n  \n    /*\n       double a, b, c;\n       double fa, fb, fc;\n       \n       a = min(x1, x2);\n       fa = (*func)(a);\n       c = max(x1, x2);\n       fc = (*func)(c);\n       b = (c - a)/2.0;\n       fb = (*func)(b);\n       \n       while (fabs(c - a) > tol + (tol * min(fabs(a), fabs(c))))\n       {\n       r = fb/fc;\n       s = fb/fa;\n       t = fa/fc;\n       p = s * (t * (r - t) * (c - b) - (1.0 - r) * (b - a));\n       q = (t - 1.0) * (r - 1.0) * (s - 1.0);\n       \n       x = b + p/q;\n       \n       if (x > a && x < c)\n       {\n       / * Accept interpolating point * /\n       if (x < b)\n       {\n       c = b;\n       fc = fb;\n       b = x;\n       fb = (*func)(b);\n       }\n       else if (x > b)\n       {\n       a = b;\n       fa = fb;\n       b = x;\n       fb = (*func)(b);\n       }\n       }\n       else\n       {\n       / * Use bisection * /\n       }\n       }\n     */ \n} \n#else   /*  */\n  \n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_roots.h>\n  \n/* struct for function pointer and parameters except 1st one */ \n  struct parameter_wrapper {\n  double (*func) (double, double, double, double);\n   double x2;\n    double x3;\n    double x4;\n } parameter;\n\n/* calls the given function during gsl root solving iteration\n   the first parameter variates, all other are kept constant\n*/ \ndouble function_wrapper (double x, void *p) \n{\n  struct parameter_wrapper *param = (struct parameter_wrapper *) p;\n  return param->func (x, param->x2, param->x3, param->x4);\n}\n\n\n/*\n  this interface is used in sreestimate.c\n */ \ndouble ghmm_zbrent_AB (double (*func) (double, double, double, double), double x1,\n                  double x2, double tol, double A, double B, double eps) \n{\n  \n    /* initialisation of wrapper structure */ \n  struct parameter_wrapper param;\n  gsl_function f;\n  \n#ifdef HAVE_GSL_INTERVAL /* gsl_interval vanished with version 0.9 */\n    gsl_interval x;\n  \n#endif  /*  */\n    gsl_root_fsolver * s;\n  double tolerance;\n  int success = 0;\n  double result = 0;\n  param.func = func;\n  param.x2 = A;\n  param.x3 = B;\n  param.x4 = eps;\n  f.function = &function_wrapper;\n  f.params = (void *) &param;\n  tolerance = tol;\n  \n    /* initialisation */ \n#ifdef HAVE_GSL_INTERVAL\n# ifdef GSL_ROOT_FSLOVER_ALLOC_WITH_ONE_ARG\n    x.lower = x1;\n  x.upper = x2;\n  s = gsl_root_fsolver_alloc (gsl_root_fsolver_brent);\n  gsl_root_fsolver_set (s, &f, x);\n  \n# else\n    s = gsl_root_fsolver_alloc (gsl_root_fsolver_brent, &f, x);\n  \n# endif\n#else   /* gsl_interval vanished with version 0.9 */\n    s = gsl_root_fsolver_alloc (gsl_root_fsolver_brent);\n  gsl_root_fsolver_set (s, &f, x1, x2);\n  \n#endif  /*  */\n    \n    /* iteration */ \n    do {\n    success = gsl_root_fsolver_iterate (s);\n    if (success == GSL_SUCCESS)\n       {\n      \n#ifdef HAVE_GSL_INTERVAL\n        gsl_interval new_x;\n      new_x = gsl_root_fsolver_interval (s);\n      success = gsl_root_test_interval (new_x, tolerance, tolerance);\n      \n#else   /* gsl_interval vanished with version 0.9 */\n      double x_up;\n      double x_low;\n      (void) gsl_root_fsolver_iterate (s);\n      x_up = gsl_root_fsolver_x_upper (s);\n      x_low = gsl_root_fsolver_x_lower (s);\n      success = gsl_root_test_interval (x_low, x_up, tolerance, tolerance);\n      \n#endif  /*  */\n      }\n  } while (success == GSL_CONTINUE);\n  \n    /* result */ \n    if (success != GSL_SUCCESS)\n     {\n    gsl_error (\"solver failed\", __FILE__, __LINE__, success);\n    }\n  \n  else\n     {\n    result = gsl_root_fsolver_root (s);\n    }\n  \n    /* destruction */ \n    gsl_root_fsolver_free (s);\n  return result;\n}\n\n\n#endif  /*  */\n\n", "meta": {"hexsha": "1f1a39c6a8a15ba660e688cd78818ceab46fb116", "size": 5577, "ext": "c", "lang": "C", "max_stars_repo_path": "Trash/sandbox/hmm/ghmm-0.9-rc3/ghmm/root_finder.c", "max_stars_repo_name": "ruslankuzmin/julia", "max_stars_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2017-03-13T17:32:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-27T16:51:22.000Z", "max_issues_repo_path": "Trash/sandbox/hmm/ghmm-0.9-rc3/ghmm/root_finder.c", "max_issues_repo_name": "ruslankuzmin/julia", "max_issues_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-29T19:54:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-29T19:54:52.000Z", "max_forks_repo_path": "Trash/sandbox/hmm/ghmm-0.9-rc3/ghmm/root_finder.c", "max_forks_repo_name": "ruslankuzmin/julia", "max_forks_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2016-10-18T03:31:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-29T13:23:10.000Z", "avg_line_length": 26.3066037736, "max_line_length": 83, "alphanum_fraction": 0.5664335664, "num_tokens": 1548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39233683016710835, "lm_q2_score": 0.03676946383261257, "lm_q1q2_score": 0.014426014887031352}}
{"text": "/* Author: Edward Hutter */\n\n#ifndef SHARED\n#define SHARED\n\n// System includes\n#include <fstream>\n#include <iostream>\n#include <cstring>\n#include <cstdlib>\n#include <stdio.h>\n#include <complex>\n#include <vector>\n#include <map>\n#include <algorithm>\n#include <utility>\n#include <tuple>\n#include <cmath>\n#include <string>\n#include <assert.h>\n#include <complex>\n\n#include <mpi.h>\n#include \"mkl.h\"\n\n#ifdef CRITTER\n#include \"critter.h\"\n#else\n//#ifdef PORTER\n//#include <cblas.h>\n//#include \"/home/hutter2/hutter2/external/BLAS/OpenBLAS/lapack-netlib/LAPACKE/include/lapacke.h\"\n//#endif\n#define CRITTER_START(ARG)\n#define CRITTER_STOP(ARG)\n#endif\n\ntemplate<typename ScalarType>\nclass mpi_type;\n\ntemplate<>\nclass mpi_type<float>{\npublic:\n  constexpr static size_t type = MPI_FLOAT;\n};\ntemplate<>\nclass mpi_type<double>{\npublic:\n  constexpr static size_t type = MPI_DOUBLE;\n};\n\n\n#endif /*SHARED*/\n", "meta": {"hexsha": "b7aa2beca2ddc97fbdd412b63d0590300b4017ab", "size": 888, "ext": "h", "lang": "C", "max_stars_repo_path": "src/util/shared.h", "max_stars_repo_name": "tbennun/capital", "max_stars_repo_head_hexsha": "574dc04caf4a2eefd7af77517123b6eb4f9a18cc", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-20T01:13:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-20T01:13:21.000Z", "max_issues_repo_path": "src/util/shared.h", "max_issues_repo_name": "tbennun/capital", "max_issues_repo_head_hexsha": "574dc04caf4a2eefd7af77517123b6eb4f9a18cc", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2019-09-15T00:37:37.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-21T22:01:27.000Z", "max_forks_repo_path": "src/util/shared.h", "max_forks_repo_name": "tbennun/capital", "max_forks_repo_head_hexsha": "574dc04caf4a2eefd7af77517123b6eb4f9a18cc", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-20T01:13:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-20T01:13:23.000Z", "avg_line_length": 16.7547169811, "max_line_length": 97, "alphanum_fraction": 0.7331081081, "num_tokens": 221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35220179564702847, "lm_q2_score": 0.04084571153154022, "lm_q1q2_score": 0.014385932945889003}}
{"text": "/*\n *  gslrandomgen.h\n *\n *  This file is part of NEST.\n *\n *  Copyright (C) 2004 The NEST Initiative\n *\n *  NEST is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 2 of the License, or\n *  (at your option) any later version.\n *\n *  NEST is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with NEST.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n/*\n *  Interface to GSL Random Number Generators\n *\n */\n\n#ifndef GSLRANDOMGEN_H\n#define GSLRANDOMGEN_H\n\n// C++ includes:\n#include <cassert>\n#include <list>\n#include <string>\n\n// Generated includes:\n#include \"config.h\"\n\n// Includes from librandom:\n#include \"random_datums.h\"\n#include \"randomgen.h\"\n\n// Includes from sli:\n#include \"dictdatum.h\"\n\n// essential GSL includes or replacements\n// GSL Versions < 1.2 have weak MT seeding\n#ifdef HAVE_GSL\n\n// \"Real\" version in presence of GSL\n\n// External includes:\n#include <gsl/gsl_rng.h>\n\nnamespace librandom\n{\n\n/**\n * class GslRandomGen\n * C++ wrapper for GSL/GSL-style generators.\n * @note\n * This class should only be used within librandom.\n *\n * @ingroup RandomNumberGenerators\n */\n\nclass GslRandomGen : public RandomGen\n{\n  friend class GSL_BinomialRandomDev;\n\npublic:\n  explicit GslRandomGen( const gsl_rng_type*, //!< given RNG, given seed\n    unsigned long );\n\n  ~GslRandomGen();\n\n  //! Add all GSL RNGs to rngdict\n  static void add_gsl_rngs( Dictionary& );\n\n  RngPtr\n  clone( unsigned long s )\n  {\n    return RngPtr( new GslRandomGen( rng_type_, s ) );\n  }\n\n\nprivate:\n  void seed_( unsigned long );\n  double drand_( void );\n\nprivate:\n  gsl_rng_type const* rng_type_;\n  gsl_rng* rng_;\n};\n\ninline void\nGslRandomGen::seed_( unsigned long s )\n{\n  gsl_rng_set( rng_, s );\n}\n\ninline double\nGslRandomGen::drand_( void )\n{\n  return gsl_rng_uniform( rng_ );\n}\n\n//! Factory class for GSL-based random generators\nclass GslRNGFactory : public GenericRNGFactory\n{\npublic:\n  GslRNGFactory( gsl_rng_type const* const );\n  RngPtr create( unsigned long ) const;\n\nprivate:\n  //! GSL generator type information\n  gsl_rng_type const* const gsl_rng_;\n};\n}\n\n#else\n\n// NO GSL Available---Implement class as empty shell\nnamespace librandom\n{\n\nclass GslRandomGen : public RandomGen\n{\npublic:\n  //! Add all GSL RNGs to rngdict\n  //! Do nothing if GSL not available\n  static void\n  add_gsl_rngs( Dictionary& )\n  {\n  }\n\nprivate:\n  GslRandomGen()\n  {\n    assert( false );\n  }\n  ~GslRandomGen()\n  {\n    assert( false );\n  }\n};\n}\n\n#endif\n\n\n#endif\n", "meta": {"hexsha": "a120dc4accf2293420bf97a5cd2987a3a35ae18e", "size": 2813, "ext": "h", "lang": "C", "max_stars_repo_path": "NEST-14.0-FPGA/librandom/gslrandomgen.h", "max_stars_repo_name": "OpenHEC/SNN-simulator-on-PYNQcluster", "max_stars_repo_head_hexsha": "14f86a76edf4e8763b58f84960876e95d4efc43a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 45.0, "max_stars_repo_stars_event_min_datetime": "2019-12-09T06:45:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T12:16:41.000Z", "max_issues_repo_path": "NEST-14.0-FPGA/librandom/gslrandomgen.h", "max_issues_repo_name": "zlchai/SNN-simulator-on-PYNQcluster", "max_issues_repo_head_hexsha": "14f86a76edf4e8763b58f84960876e95d4efc43a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-05-23T05:34:21.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-08T02:33:46.000Z", "max_forks_repo_path": "NEST-14.0-FPGA/librandom/gslrandomgen.h", "max_forks_repo_name": "OpenHEC/SNN-simulator-on-PYNQcluster", "max_forks_repo_head_hexsha": "14f86a76edf4e8763b58f84960876e95d4efc43a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-09T06:45:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-25T09:32:56.000Z", "avg_line_length": 18.385620915, "max_line_length": 72, "alphanum_fraction": 0.7017419125, "num_tokens": 738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37387582277169656, "lm_q2_score": 0.03846619064046817, "lm_q1q2_score": 0.01438157867459797}}
{"text": "#ifndef LIBTENSOR_CBLAS_H_H\n#define LIBTENSOR_CBLAS_H_H\n\n#ifdef USE_CBLAS\nextern \"C\" { // Fixes older cblas.h versions without extern \"C\"\n#include <cblas.h>\n}\n#endif // USE_CBLAS\n\n#ifdef USE_GSL\n#include <gsl/gsl_cblas.h>\n#endif // USE_GSL\n\n#endif // LIBTENSOR_CBLAS_H_H\n", "meta": {"hexsha": "5320c3e89bbfe40e017259da7cc17e71e73f1935", "size": 271, "ext": "h", "lang": "C", "max_stars_repo_path": "libtensor/linalg/cblas/cblas_h.h", "max_stars_repo_name": "pjknowles/libtensor", "max_stars_repo_head_hexsha": "f18e0e33c6c4512e4ea1dde31ed8d74fe536ed24", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 33.0, "max_stars_repo_stars_event_min_datetime": "2016-02-08T06:05:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T01:23:11.000Z", "max_issues_repo_path": "libtensor/linalg/cblas/cblas_h.h", "max_issues_repo_name": "pjknowles/libtensor", "max_issues_repo_head_hexsha": "f18e0e33c6c4512e4ea1dde31ed8d74fe536ed24", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2016-06-14T15:54:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-07T08:27:20.000Z", "max_forks_repo_path": "libtensor/linalg/cblas/cblas_h.h", "max_forks_repo_name": "pjknowles/libtensor", "max_forks_repo_head_hexsha": "f18e0e33c6c4512e4ea1dde31ed8d74fe536ed24", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2016-05-19T18:09:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-24T17:35:21.000Z", "avg_line_length": 18.0666666667, "max_line_length": 63, "alphanum_fraction": 0.7527675277, "num_tokens": 89, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.28140560742914383, "lm_q2_score": 0.05108273695705248, "lm_q1q2_score": 0.014374968622542528}}
{"text": "#ifndef _EM_LA_H_\n#define _EM_LA_H_ 1\n\n#include <petsc.h>\n\nstruct EMContext;\n\nPetscErrorCode access_vec(Vec, std::vector<PetscInt> &, int, double *);\n\nPetscErrorCode setup_ams(EMContext *);\nPetscErrorCode destroy_ams(EMContext *);\n\nPetscErrorCode create_pc(EMContext *);\nPetscErrorCode destroy_pc(EMContext *);\nPetscErrorCode pc_apply_b(PC, Vec, Vec);\n\nPetscErrorCode matshell_createvecs_a(Mat, Vec *, Vec *);\nPetscErrorCode matshell_mult_a(Mat, Vec, Vec);\n\nPetscErrorCode solve_linear_system(EMContext *, const PETScBlockVector &, PETScBlockVector &, PetscInt, PetscReal);\n\n#endif\n", "meta": {"hexsha": "9c3aec455363042c12b60ac9cd105df02d534f56", "size": 582, "ext": "h", "lang": "C", "max_stars_repo_path": "src/em_la.h", "max_stars_repo_name": "emfem/emfem", "max_stars_repo_head_hexsha": "9129e28610d7fcb83a88021528575dfeaadad502", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-03T12:22:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-03T12:22:37.000Z", "max_issues_repo_path": "src/em_la.h", "max_issues_repo_name": "emfem/emfem", "max_issues_repo_head_hexsha": "9129e28610d7fcb83a88021528575dfeaadad502", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/em_la.h", "max_forks_repo_name": "emfem/emfem", "max_forks_repo_head_hexsha": "9129e28610d7fcb83a88021528575dfeaadad502", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3043478261, "max_line_length": 115, "alphanum_fraction": 0.7869415808, "num_tokens": 151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.03461884220069214, "lm_q1q2_score": 0.014363317671887641}}
{"text": "/*\n * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The OpenAirInterface Software Alliance licenses this file to You under\n * the OAI Public License, Version 1.1  (the \"License\"); you may not use this file\n * except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.openairinterface.org/?page_id=698\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *-------------------------------------------------------------------------------\n * For more information about the OpenAirInterface (OAI) Software Alliance:\n *      contact@openairinterface.org\n */\n\n#include <string.h>\n#include <math.h>\n#include <unistd.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <time.h>\n#include <cblas.h>\n\n#include \"SIMULATION/TOOLS/defs.h\"\n#include \"SIMULATION/RF/defs.h\"\n#include \"PHY/types.h\"\n#include \"PHY/defs.h\"\n#include \"PHY/extern.h\"\n#include \"oaisim_config.h\"\n\n#ifdef OPENAIR2\n#include \"LAYER2/MAC/defs.h\"\n#include \"LAYER2/MAC/extern.h\"\n#include \"UTIL/LOG/log_if.h\"\n#include \"UTIL/LOG/log_extern.h\"\n#include \"RRC/LITE/extern.h\"\n#include \"PHY_INTERFACE/extern.h\"\n#include \"UTIL/OCG/OCG.h\"\n#include \"UTIL/OMG/omg.h\"\n#include \"UTIL/OPT/opt.h\" // to test OPT\n#endif\n\n#include \"SCHED/defs.h\"\n#include \"SCHED/extern.h\"\n\n#include \"oaisim.h\"\n\n#define PI 3.1416\n#define Am 20\n\n#define MCL (-70) /*minimum coupling loss (MCL) in dB*/\n//double sinr[NUMBER_OF_eNB_MAX][2*25];\n/*\nextern double sinr_bler_map[MCS_COUNT][2][16];\nextern double sinr_bler_map_up[MCS_COUNT][2][16];\ndouble SINRpost_eff[301];\nextern double MI_map_4qam[3][162];\nextern double MI_map_16qam[3][197];\nextern double MI_map_64qam[3][227];\n*/\n// Extract the positions of UE and ENB from the mobility model\n\nvoid extract_position (node_list* input_node_list, node_desc_t **node_data, int nb_nodes)\n{\n\n  int i;\n\n  for (i=0; i<nb_nodes; i++) {\n    if ((input_node_list != NULL) &&  (node_data[i] != NULL)) {\n\n      node_data[i]->x = input_node_list->node->x_pos;\n\n      if (node_data[i]->x <0.0)\n        node_data[i]->x = 0.0;\n\n      node_data[i]->y = input_node_list->node->y_pos;\n\n      if (node_data[i]->y <0.0)\n        node_data[i]->y = 0.0;\n\n      LOG_D(OCM, \"extract_position: added node_data %d with position X: %f and Y: %f \\n\", i,input_node_list->node->x_pos, input_node_list->node->y_pos );\n      input_node_list = input_node_list->next;\n    } else {\n      LOG_E(OCM, \"extract_position: Null pointer!!!\\n\");\n      //exit(-1);\n    }\n  }\n}\nvoid extract_position_fixed_enb  (node_desc_t **node_data, int nb_nodes, frame_t frame)\n{\n  int i;\n\n  for (i=0; i<nb_nodes; i++) {\n    if (i==0) {\n      node_data[i]->x = 0;\n      node_data[i]->y = 500;\n    } else if (i == 1 ) {\n      node_data[i]->x = 866;//\n      node_data[i]->y = 1000;\n    } else if (i == 2 ) {\n      node_data[i]->x = 866;\n      node_data[i]->y = 0;\n    }\n  }\n}\n\nvoid extract_position_fixed_ue  (node_desc_t **node_data, int nb_nodes, frame_t frame)\n{\n  int i;\n\n  if(frame<50)\n    for (i=0; i<nb_nodes; i++) {\n      if (i==0) {\n        node_data[i]->x = 2050;\n        node_data[i]->y = 1500;\n      } else {\n        node_data[i]->x = 2150;\n        node_data[i]->y = 1500;\n      }\n    }\n  else {\n    for (i=0; i<nb_nodes; i++) {\n      if (i==0) {\n        node_data[i]->x = 1856 - (frame - 49);\n        // if(node_data[i]->x > 2106)\n        //  node_data[i]->x = 2106;\n        node_data[i]->y = 1813 + (frame - 49);\n        // if(node_data[i]->y < 1563)\n        //  node_data[i]->y = 1563;\n        // if( node_data[i]->x == 2106)\n        //   node_data[i]->x = 2106 - (frame - 49);\n      } else {\n        node_data[i]->x = 2106 - (frame - 49);\n        // if(node_data[i]->x < 1856)\n        //  node_data[i]->x = 1856;\n        node_data[i]->y = 1563 + (frame - 49);\n        // if(node_data[i]->y < 1813)\n        //  node_data[i]->y = 1813;\n      }\n    }\n  }\n\n}\n\nvoid init_ue(node_desc_t  *ue_data, UE_Antenna ue_ant)  //changed from node_struct\n{\n\n  ue_data->n_sectors = 1;\n  ue_data->phi_rad = 2 * PI;\n  ue_data->ant_gain_dBi = ue_ant.antenna_gain_dBi;\n  ue_data->tx_power_dBm = ue_ant.tx_power_dBm;\n  ue_data->rx_noise_level = ue_ant.rx_noise_level_dB; //value in db\n\n}\n\nvoid init_enb(node_desc_t  *enb_data, eNB_Antenna enb_ant)  //changed from node_struct\n{\n\n  int i;\n  double sect_angle[3]= {0,2*PI/3,4*PI/3};\n\n  enb_data->n_sectors = enb_ant.number_of_sectors;\n\n  for (i=0; i<enb_data->n_sectors; i++)\n    enb_data->alpha_rad[i] = sect_angle[i]; //enb_ant.alpha_rad[i];\n\n  enb_data->phi_rad = enb_ant.beam_width_dB;\n  enb_data->ant_gain_dBi = enb_ant.antenna_gain_dBi;\n  enb_data->tx_power_dBm = enb_ant.tx_power_dBm;\n  enb_data->rx_noise_level = enb_ant.rx_noise_level_dB;\n\n}\n\n\n\nvoid calc_path_loss(node_desc_t* enb_data, node_desc_t* ue_data, channel_desc_t *ch_desc, Environment_System_Config env_desc, double **Shad_Fad)\n{\n\n  double dist;\n  double path_loss;\n  double gain_max;\n  double gain_sec[3];\n  double alpha, theta;\n\n  int count;\n\n\n  dist = sqrt(pow((enb_data->x - ue_data->x), 2) + pow((enb_data->y - ue_data->y), 2));\n\n  path_loss = env_desc.fading.free_space_model_parameters.pathloss_0_dB -\n              10*env_desc.fading.free_space_model_parameters.pathloss_exponent * log10(dist/1000);\n  LOG_D(OCM,\"dist %f, Path loss %f\\n\",dist,ch_desc->path_loss_dB);\n\n  /* Calculating the angle in the range -pi to pi from the slope */\n  alpha = atan2((ue_data->y - enb_data->y),(ue_data->x - enb_data->x));\n\n  if (alpha < 0)\n    alpha += 2*PI;\n\n  //printf(\"angle in radians is %lf\\n\", ue_data[UE_id]->alpha_rad[eNB_id]);\n  ch_desc->aoa = alpha;\n  ch_desc->random_aoa = 0;\n\n  if (enb_data->n_sectors==1) //assume omnidirectional antenna\n    gain_max = 0;\n  else {\n    gain_max = -1000;\n\n    for(count = 0; count < enb_data->n_sectors; count++) {\n      theta = enb_data->alpha_rad[count] - alpha;\n      /* gain = -min(Am , 12 * (theta/theta_3dB)^2) */\n      gain_sec[count] = -(Am < (12 * pow((theta/enb_data->phi_rad),2)) ? Am : (12 * pow((theta/enb_data->phi_rad),2)));\n\n      if (gain_sec[count]>gain_max)  //take the sector that we are closest too (or where the gain is maximum)\n        gain_max = gain_sec[count];\n    }\n  }\n\n  path_loss += enb_data->ant_gain_dBi + gain_max + ue_data->ant_gain_dBi;\n\n  if (Shad_Fad!=NULL)\n    path_loss += Shad_Fad[(int)ue_data->x][(int)ue_data->y];\n\n  ch_desc->path_loss_dB = MCL < path_loss ?  MCL : path_loss;\n  //LOG_D(OCM,\"x_coordinate\\t%f\\t,y_coordinate\\t%f\\t, path_loss %f\\n\",ue_data->x,ue_data->y,ch_desc->path_loss_dB);\n}\n\n\n\n\n\nvoid init_snr(channel_desc_t* eNB2UE, node_desc_t *enb_data, node_desc_t *ue_data, double* sinr_dB, double* N0, uint8_t transmission_mode, uint16_t q, uint8_t dl_power_off, uint16_t nb_rb)\n{\n\n  double thermal_noise,abs_channel,channelx, channely,channelx_i, channely_i ;\n  int count;\n  int aarx,aatx;\n  uint8_t qq;\n\n  /* Thermal noise is calculated using 10log10(K*T*B) K = Boltzmann's constant T = room temperature B = bandwidth*/\n  thermal_noise = -174 + 10*log10(15000); //per RE; value in dBm\n\n  //for (aarx=0; aarx<eNB2UE->nb_rx; aarx++)\n  *N0 = thermal_noise + ue_data->rx_noise_level;\n\n  LOG_D(OCM,\"Path loss %lf, noise (N0) %lf, signal %lf, snr %lf\\n\",\n        eNB2UE->path_loss_dB,\n        thermal_noise + ue_data->rx_noise_level,\n        enb_data->tx_power_dBm + eNB2UE->path_loss_dB,\n        enb_data->tx_power_dBm + eNB2UE->path_loss_dB - (thermal_noise + ue_data->rx_noise_level));\n\n  if(transmission_mode == 5 && dl_power_off==1)\n    transmission_mode = 6;\n\n  switch(transmission_mode) {\n  case 1:\n\n    //printf (\"coupling factor is %lf\\n\", coupling);\n    for (count = 0; count < (12 * nb_rb); count++) {\n      sinr_dB[count] = enb_data->tx_power_dBm\n                       + eNB2UE->path_loss_dB\n                       - (thermal_noise + ue_data->rx_noise_level)\n                       + 10 * log10 (pow(eNB2UE->chF[0][count].x, 2)\n                                     + pow(eNB2UE->chF[0][count].y, 2));\n      //printf(\"sinr_dB[%d]: %1f\\n\",count,sinr_dB[count]);\n      //printf(\"Dl_link SNR for res. block %d is %lf\\n\", count, sinr[eNB_id][count]);\n    }\n\n    break;\n\n  case 2:\n\n    for (count = 0; count < (12 * nb_rb); count++) {\n      abs_channel=0;\n\n      for (aarx=0; aarx<eNB2UE->nb_rx; aarx++) {\n        for (aatx=0; aatx<eNB2UE->nb_tx; aatx++) {\n          abs_channel += (pow(eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x, 2) + pow(eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y, 2));\n        }\n      }\n\n      sinr_dB[count] = enb_data->tx_power_dBm\n                       + eNB2UE->path_loss_dB\n                       - (thermal_noise + ue_data->rx_noise_level)\n                       + 10 * log10 (abs_channel/2);\n      // printf(\"sinr_dB[%d]: %1f\\n\",count,sinr_dB[count]);\n    }\n\n    break;\n\n  case 5:\n    for (count = 0; count < (12 * nb_rb); count++) {\n      channelx=0;\n      channely=0;\n      channelx_i=0;\n      channely_i=0;\n      qq = (q>>(((count/12)>>2)<<1))&3;\n      //printf(\"pmi_alloc %d: rb %d, pmi %d\\n\",q,count/12,qq);\n\n\n\n      //      qq = q;\n      for (aarx=0; aarx<eNB2UE->nb_rx; aarx++) {\n        for (aatx=0; aatx<eNB2UE->nb_tx; aatx++) {\n          switch(qq) {\n          case 0:\n            if (channelx==0 || channely==0) {\n              channelx = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;\n              channely = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;\n              channelx_i = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;\n              channely_i = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;\n            } else {\n              channelx += eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;\n              channely += eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;\n              channelx_i -= eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;\n              channely_i -= eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;\n            }\n\n            break;\n\n          case 1:\n            if (channelx==0 || channely==0) {\n              channelx = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;\n              channely = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;\n              channelx_i = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;\n              channely_i = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;\n            } else {\n              channelx -= eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;\n              channely -= eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;\n              channelx_i += eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;\n              channely_i += eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;\n            }\n\n            break;\n\n          case 2:\n            if (channelx==0 || channely==0) {\n              channelx = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;\n              channely = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;\n              channelx_i = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;\n              channely_i = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;\n            } else {\n              channelx -= eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;\n              channely += eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;\n              channelx_i += eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;\n              channely_i -= eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;\n\n            }\n\n            break;\n\n          case 3:\n            if (channelx==0 || channely==0) {\n              channelx = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;\n              channely = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;\n              channelx_i = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;\n              channely_i = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;\n            } else {\n              channelx += eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;\n              channely -= eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;\n              channelx_i -= eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;\n              channely_i += eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;\n            }\n\n            break;\n\n          default:\n            LOG_E(EMU,\"Problem in SINR Calculation for TM5 \\n\");\n            break;\n\n          }//switch(q)\n\n        }//aatx\n      }//aarx\n\n      /*  sinr_dB[count] = enb_data->tx_power_dBm\n         + eNB2UE->path_loss_dB\n        - (thermal_noise + ue_data->rx_noise_level)\n        + 10 * log10 ((pow(channelx,2) + pow(channely,2))/2) - 10 * log10 ((pow(channelx_i,2) + pow(channely_i,2))/2);\n      */\n      sinr_dB[count] = enb_data->tx_power_dBm\n                       + eNB2UE->path_loss_dB\n                       - (thermal_noise + ue_data->rx_noise_level)\n                       + 10 * log10 ((pow(channelx,2) + pow(channely,2))) - 10 * log10 ((pow(channelx_i,2) + pow(channely_i,2))) - 3; // 3dB is subtracted as the tx_power_dBm is to be adjusted on per user basis\n      // printf(\"sinr_dB[%d]: %1f\\n\",count,sinr_dB[count]);\n    }\n\n    break;\n\n  case 6:\n    for (count = 0; count < (12 * nb_rb); count++) {\n      channelx=0;\n      channely=0;\n      qq = (q>>(((count/12)>>2)<<1))&3;\n      //printf(\"pmi_alloc %d: rb %d, pmi %d\\n\",q,count/12,qq);\n\n\n\n      //      qq = q;\n      for (aarx=0; aarx<eNB2UE->nb_rx; aarx++) {\n        for (aatx=0; aatx<eNB2UE->nb_tx; aatx++) {\n          switch(qq) {\n          case 0:\n            if (channelx==0 || channely==0) {\n              channelx = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;\n              channely = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;\n            } else {\n              channelx += eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;\n              channely += eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;\n            }\n\n            break;\n\n          case 1:\n            if (channelx==0 || channely==0) {\n              channelx = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;\n              channely = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;\n            } else {\n              channelx -= eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;\n              channely -= eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;\n            }\n\n            break;\n\n          case 2:\n            if (channelx==0 || channely==0) {\n              channelx = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;\n              channely = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;\n            } else {\n              channelx -= eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;\n              channely += eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;\n            }\n\n            break;\n\n          case 3:\n            if (channelx==0 || channely==0) {\n              channelx = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;\n              channely = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;\n            } else {\n              channelx += eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;\n              channely -= eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;\n            }\n\n            break;\n\n          default:\n            LOG_E(EMU,\"Problem in SINR Calculation for TM6 \\n\");\n            break;\n\n          }//switch(q)\n\n        }//aatx\n      }//aarx\n\n      sinr_dB[count] = enb_data->tx_power_dBm\n                       + eNB2UE->path_loss_dB\n                       - (thermal_noise + ue_data->rx_noise_level)\n                       + 10 * log10 ((pow(channelx,2) + pow(channely,2))/2);\n\n      // printf(\"sinr_dB[%d]: %1f\\n\",count,sinr_dB[count]);\n    }\n\n    break;\n\n  default:\n    LOG_E(EMU,\"Problem in SINR Initialization in sinr_sim.c\\n\");\n    break;\n  }//switch\n}//function ends\n\nvoid calculate_sinr(channel_desc_t* eNB2UE, node_desc_t *enb_data, node_desc_t *ue_data, double *sinr_dB, uint16_t nb_rb)\n{\n\n  double sir, thermal_noise;\n  short count;\n\n  /* Thermal noise is calculated using 10log10(K*T*B) K = Boltzmann's constant T = room temperature B = bandwidth */\n  thermal_noise = -174 + 10*log10(15000); //per RE, value in dBm\n\n  for (count = 0; count < 12 * nb_rb; count++) {\n    sir = enb_data->tx_power_dBm\n          + eNB2UE->path_loss_dB\n          - (thermal_noise + ue_data->rx_noise_level)\n          + 10 * log10 (pow(eNB2UE->chF[0][count].x, 2)\n                        + pow(eNB2UE->chF[0][count].y, 2));\n\n    if (sir > 0)\n      sinr_dB[count] -= sir;\n\n    //printf(\"*****sinr% lf \\n\",sinr_dB[count]);\n  }\n}\nvoid get_beta_map()\n{\n  char *file_path = NULL;\n  //int table_len = 0;\n  int t,u;\n  int mcs = 0;\n  char *sinr_bler;\n  char buffer[1000];\n  FILE *fp;\n  double perf_array[13];\n\n  file_path = (char*) malloc(512);\n\n  for (mcs = 0; mcs < MCS_COUNT; mcs++) {\n    snprintf( file_path, 512, \"%s/SIMULATION/LTE_PHY/BLER_SIMULATIONS/AWGN/AWGN_results/bler_tx1_chan18_nrx1_mcs%d.csv\", getenv(\"OPENAIR1_DIR\"), mcs );\n    fp = fopen(file_path,\"r\");\n\n    if (fp == NULL) {\n      LOG_E(OCM,\"ERROR: Unable to open the file %s! Exitng.\\n\", file_path);\n      exit(-1);\n    }\n\n    // else {\n    if (fgets (buffer, 1000, fp) != NULL) {\n      if (fgets (buffer, 1000, fp) != NULL) {\n        table_length[mcs] = 0;\n\n        while (!feof (fp)) {\n          u = 0;\n          sinr_bler = strtok (buffer, \";\");\n\n          while (sinr_bler != NULL) {\n            perf_array[u] = atof (sinr_bler);\n            u++;\n            sinr_bler = strtok (NULL, \";\");\n          }\n\n          if ((perf_array[4] / perf_array[5]) < 1) {\n            sinr_bler_map[mcs][0][table_length[mcs]] = perf_array[0];\n            sinr_bler_map[mcs][1][table_length[mcs]] = (perf_array[4] / perf_array[5]);\n            table_length[mcs]++;\n\n            if (table_length[mcs]>MCS_TABLE_LENGTH_MAX) {\n              LOG_E(OCM,\"Error reading MCS table. Increase MCS_TABLE_LENGTH_MAX (mcs %d)!\\n\",mcs);\n              exit(-1);\n            }\n          }\n\n          if (fgets (buffer, 1000, fp) != NULL) {\n          }\n        }\n      }\n    }\n\n    fclose(fp);\n    //   }\n    LOG_D(OCM,\"Print the table for mcs %d\\n\",mcs);\n\n    for (t = 0; t<table_length[mcs]; t++)\n      LOG_D(OCM,\"%lf  %lf \\n \",sinr_bler_map[mcs][0][t],sinr_bler_map[mcs][1][t]);\n  }\n\n  free(file_path);\n}\n\n//this function reads and stores the Mutual information tables for the MIESM abstraction.\nvoid get_MIESM_param()\n{\n  char *file_path = NULL;\n  char buffer[10000];\n  FILE *fp;\n  int qam[3] = {4,16,64};\n  int q,cnt;\n  char *result = NULL;\n  int table_len=0;\n  int t;\n  file_path = (char*) malloc(512);\n\n  for (q=0; q<3; q++) {\n    sprintf(file_path,\"%s/SIMU/USER/files/MI_%dqam.csv\",getenv(\"OPENAIR_TARGETS\"),qam[q]);\n    fp = fopen(file_path,\"r\");\n\n    if (fp == NULL) {\n      printf(\"ERROR: Unable to open the file %s\\n\", file_path);\n      exit(-1);\n    } else {\n      cnt=-1;\n\n      switch(qam[q]) {\n      case 4:\n        while (!feof(fp)) {\n          table_len =0;\n          cnt++;\n\n          if (fgets(buffer, 10000, fp) != NULL) {\n            result = strtok (buffer, \",\");\n\n            while (result != NULL) {\n              MI_map_4qam[cnt][table_len] = atof (result);\n              result = strtok (NULL, \",\");\n              table_len++;\n            }\n          }\n        }\n\n        for (t = 0; t < 162; t++) {\n          // MI_map_4Qam[0][t] = pow(10,0.1*(MI_map_4Qam[0][t]));\n          LOG_D(OCM, \"MIESM 4QAM Table: %lf  %lf  %1f\\n \",MI_map_4qam[0][t],MI_map_4qam[1][t], MI_map_4qam[2][t]);\n          // printf(\"MIESM 4QAM Table: %lf  %lf  %1f\\n \",MI_map_4qam[0][t],MI_map_4qam[1][t], MI_map_4qam[2][t]);\n        }\n\n        break;\n\n      case 16:\n        while (!feof(fp)) {\n          table_len =0;\n          cnt++;\n\n          if (fgets (buffer, 10000, fp) != NULL) {\n            result = strtok (buffer, \",\");\n\n            while (result != NULL) {\n              MI_map_16qam[cnt][table_len] = atof (result);\n              result = strtok (NULL, \",\");\n              table_len++;\n            }\n          }\n        }\n\n        for (t = 0; t < 197; t++) {\n          // MI_map_16Qam[0][t] = pow(10,0.1*(MI_map_16Qam[0][t]));\n          LOG_D(OCM, \"MIESM 16 QAM Table: %lf  %lf  %1f\\n \",MI_map_16qam[0][t],MI_map_16qam[1][t], MI_map_16qam[2][t]);\n          // printf(\"MIESM 16 QAM Table: %lf  %lf  %1f\\n \",MI_map_16qam[0][t],MI_map_16qam[1][t], MI_map_16qam[2][t]);\n        }\n\n        break;\n\n      case 64:\n        while (!feof(fp)) {\n          table_len=0;\n          cnt++;\n\n          if(cnt==3)\n            break;\n\n          if (fgets (buffer, 10000, fp) != NULL) {\n            result = strtok(buffer, \",\");\n\n            while (result != NULL) {\n              MI_map_64qam[cnt][table_len]= atof(result);\n              result = strtok(NULL, \",\");\n              table_len++;\n            }\n          }\n        }\n\n        for (t = 0; t < 227; t++) {\n          //MI_map_64Qam[0][t] = pow(10,0.1*(MI_map_64Qam[0][t]));\n          LOG_D(OCM, \"MIESM 64QAM Table: %lf  %lf  %1f\\n \",MI_map_64qam[0][t],MI_map_64qam[1][t], MI_map_64qam[2][t]);\n          // printf(\"MIESM 64QAM Table: %lf  %lf  %1f\\n \",MI_map_64qam[0][t],MI_map_64qam[1][t], MI_map_64qam[2][t]);\n        }\n\n        break;\n\n      default:\n        LOG_E(EMU,\"Error, bad input, quitting\\n\");\n        break;\n      }\n\n    }\n\n    fclose(fp);\n  }\n\n  free(file_path);\n}\n\n\n\n\n\n", "meta": {"hexsha": "7c752ce432f2b268cc7d11b2efd1f770a2c2482b", "size": 21362, "ext": "c", "lang": "C", "max_stars_repo_path": "targets/SIMU/USER/sinr_sim.c", "max_stars_repo_name": "davidraditya/OAI-Powder", "max_stars_repo_head_hexsha": "a082c3e8af06cd7583c003a69ec517eb73d175b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-16T00:00:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-16T00:00:04.000Z", "max_issues_repo_path": "targets/SIMU/USER/sinr_sim.c", "max_issues_repo_name": "davidraditya/OAI-Powder", "max_issues_repo_head_hexsha": "a082c3e8af06cd7583c003a69ec517eb73d175b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "targets/SIMU/USER/sinr_sim.c", "max_forks_repo_name": "davidraditya/OAI-Powder", "max_forks_repo_head_hexsha": "a082c3e8af06cd7583c003a69ec517eb73d175b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-06-07T13:49:42.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-07T13:49:42.000Z", "avg_line_length": 31.3685756241, "max_line_length": 210, "alphanum_fraction": 0.5609493493, "num_tokens": 7152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326184801538616, "lm_q2_score": 0.031618764873286, "lm_q1q2_score": 0.014331579798429589}}
{"text": "/*\nGENETIC - A simple genetic algorithm.\n\nCopyright 2014, Javier Burguete Tolosa.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\n\tlist of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice,\n\tthis list of conditions and the following disclaimer in the documentation\n\tand/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``AS IS'' AND ANY EXPRESS\nOR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\nEVENT SHALL Javier Burguete Tolosa OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\nINDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\nBUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\nADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n/**\n * \\file population.c\n * \\brief Header file to define the population functions.\n * \\author Javier Burguete Tolosa.\n * \\copyright Copyright 2014 Javier Burguete Tolosa. All rights reserved.\n */\n#define _GNU_SOURCE\n#include <stdio.h>\n#include <gsl/gsl_rng.h>\n#include <glib.h>\n#include \"bits.h\"\n#include \"entity.h\"\n#include \"population.h\"\n\n/**\n * Function to init a population.\n *\n * \\return 1 on succes, 0 on error.\n */\nint\npopulation_new (Population * population,        ///< Population.\n                GeneticVariable * variable,     ///< Variables data.\n                unsigned int nvariables,        ///< Number of variables.\n                unsigned int genome_nbits,\n                ///< Number of bits of each entity genome.\n                unsigned int nentities, ///< Number of entities.\n                double mutation_ratio,  ///< Mutation ratio.\n                double reproduction_ratio,      ///< Reproduction ratio.\n                double adaptation_ratio,        ///< Adaptation ratio.\n                double threshold)\n                ///< Threshold to finish the simulations.\n{\n  unsigned int i, nmutations, nreproductions, nadaptations;\n  nmutations = mutation_ratio * nentities;\n  nreproductions = reproduction_ratio * nentities;\n  nadaptations = adaptation_ratio * nentities;\n  i = nmutations + nreproductions + nadaptations;\n  if (!i)\n    {\n      fprintf (stderr, \"ERROR: no evolution\\n\");\n      return 0;\n    }\n  if (i >= nentities)\n    {\n      fprintf (stderr, \"ERROR: no survival of entities\\n\");\n      return 0;\n    }\n  population->nsurvival = nentities - i;\n  if (population->nsurvival < 2)\n    {\n      fprintf (stderr, \"ERROR: unable to reproduce the entities\\n\");\n      return 0;\n    }\n  population->variable = variable;\n  population->nvariables = nvariables;\n  population->nentities = nentities;\n  population->mutation_max = nentities;\n  population->mutation_min = population->reproduction_max\n    = nentities - nmutations;\n  population->reproduction_min = population->adaptation_max\n    = population->reproduction_max - nreproductions;\n  population->adaptation_min = population->nsurvival;\n  population->genome_nbits = genome_nbits;\n  population->genome_nbytes = bit_sizeof (genome_nbits);\n  population->objective\n\t\t= (double *) g_slice_alloc (nentities * sizeof (double));\n  population->entity = (Entity *) g_slice_alloc (nentities * sizeof (Entity));\n  for (i = 0; i < population->nentities; ++i)\n    {\n      entity_new (population->entity + i, population->genome_nbytes, i);\n      population->objective[i] = G_MAXDOUBLE;\n    }\n  population->threshold = threshold;\n  population->stop = 0;\n  return 1;\n}\n\n/**\n * Function to free the memory allocated in a population.\n */\nvoid\npopulation_init_genomes (Population * population,       ///< Population.\n                         gsl_rng * rng) ///< GSL random numbers generator.\n{\n  unsigned int i;\n  for (i = 0; i < population->nentities; ++i)\n    entity_init (population->entity + i, rng);\n}\n\n/**\n * Function to free the memory allocated in a population.\n */\nvoid\npopulation_free (Population * population)       ///< Population.\n{\n  unsigned int i, nentities;\n\tnentities = population->nentities;\n  for (i = 0; i < nentities; ++i)\n    entity_free (population->entity + i);\n  g_slice_free1 (nentities * sizeof (Entity), population->entity);\n  g_slice_free1 (nentities * sizeof (double), population->objective);\n}\n", "meta": {"hexsha": "75d3d6e74218659cdd2ac8fec544bdb814100c33", "size": 4709, "ext": "c", "lang": "C", "max_stars_repo_path": "3.0.0/population.c", "max_stars_repo_name": "jburguete/genetic", "max_stars_repo_head_hexsha": "e7b5473412eeb4bdd9d1f724ab555d7329b7156d", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-04-07T07:31:25.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-02T02:31:16.000Z", "max_issues_repo_path": "3.0.0/population.c", "max_issues_repo_name": "jburguete/genetic", "max_issues_repo_head_hexsha": "e7b5473412eeb4bdd9d1f724ab555d7329b7156d", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3.0.0/population.c", "max_forks_repo_name": "jburguete/genetic", "max_forks_repo_head_hexsha": "e7b5473412eeb4bdd9d1f724ab555d7329b7156d", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-05-22T08:54:08.000Z", "max_forks_repo_forks_event_max_datetime": "2017-05-22T08:54:08.000Z", "avg_line_length": 36.2230769231, "max_line_length": 79, "alphanum_fraction": 0.698449777, "num_tokens": 1064, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3665897363221599, "lm_q2_score": 0.03904828951114809, "lm_q1q2_score": 0.01431470215572314}}
{"text": "/*\n * C version of Diffusive Nested Sampling (DNest4) by Brendon J. Brewer\n *\n * Yan-Rong Li, liyanrong@mail.ihep.ac.cn\n * Jun 30, 2016\n *\n */\n\n#ifndef _MODEL2_H\n#define _MODEL2_H\n\n#include <stdbool.h>\n#include <gsl/gsl_rng.h>\n\n/*  data type */\ntypedef struct \n{\n  double x;\n  double y;\n}DataType;\n\n/* number of model parameters */\nextern int num_params;\n\n/* data storage */\nextern int num_data_points;\nextern DataType *data;\n\nextern int which_particle_update; // which particule to be updated\nextern int which_level_update;\nextern double *limits;\nextern int thistask, totaltask;\n\nextern DNestFptrSet *fptrset_thismodel2;\n\n/* functions */\nvoid from_prior_thismodel2(void *model);\nvoid data_load_thismodel2();\nvoid print_particle_thismodel2(FILE *fp, const void *model);\ndouble log_likelihoods_cal_thismodel2(const void *model);\ndouble perturb_thismodel2(void *model);\nvoid restart_action_model2(int iflag);\n\n#endif\n", "meta": {"hexsha": "6efdf6ea5ce8c2c1d59c455c167fc8b25d1563c2", "size": 915, "ext": "h", "lang": "C", "max_stars_repo_path": "src/model2.h", "max_stars_repo_name": "LiyrAstroph/CDNest", "max_stars_repo_head_hexsha": "afb6b869ce1c4ebd76662b20310f1d9d3db4e26e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-09-11T03:34:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-16T12:14:05.000Z", "max_issues_repo_path": "src/model2.h", "max_issues_repo_name": "LiyrAstroph/DNest_C", "max_issues_repo_head_hexsha": "afb6b869ce1c4ebd76662b20310f1d9d3db4e26e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-05-14T10:04:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-06T02:04:19.000Z", "max_forks_repo_path": "src/model2.h", "max_forks_repo_name": "LiyrAstroph/DNest_C", "max_forks_repo_head_hexsha": "afb6b869ce1c4ebd76662b20310f1d9d3db4e26e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.3333333333, "max_line_length": 71, "alphanum_fraction": 0.7584699454, "num_tokens": 238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.029760093730832948, "lm_q1q2_score": 0.01429909049437242}}
{"text": "#pragma once\n\n#include <gsl\\gsl>\n#include <winrt\\base.h>\n#include <d3d11.h>\n#include \"DrawableGameComponent.h\"\n#include \"DynamicLODMaterial.h\"\n#include \"MatrixHelper.h\"\n\nnamespace Rendering\n{\n\tclass DynamicLODDemo final : public Library::DrawableGameComponent\n\t{\n\tpublic:\n\t\tDynamicLODDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera);\n\t\tDynamicLODDemo(const DynamicLODDemo&) = delete;\n\t\tDynamicLODDemo(DynamicLODDemo&&) = default;\n\t\tDynamicLODDemo& operator=(const DynamicLODDemo&) = default;\t\t\n\t\tDynamicLODDemo& operator=(DynamicLODDemo&&) = default;\n\t\t~DynamicLODDemo();\n\n\t\tint MaxTessellationFactor() const;\n\t\tvoid SetMaxTessellationFactor(int maxTessellationFactor);\n\n\t\tDirectX::XMFLOAT2 TessellationDistances() const;\n\t\tvoid SetTessellationDistances(DirectX::XMFLOAT2 tessellationDistances);\n\t\tvoid SetTessellationDistances(float minTessellationDistance, float maxTessellationDistance);\n\n\t\tvirtual void Initialize() override;\n\t\tvirtual void Draw(const Library::GameTime& gameTime) override;\n\n\tprivate:\n\t\tDynamicLODMaterial mMaterial;\n\t\tDirectX::XMFLOAT4X4 mWorldMatrix{ Library::MatrixHelper::Identity };\n\t\twinrt::com_ptr<ID3D11Buffer> mVertexBuffer;\n\t\twinrt::com_ptr<ID3D11Buffer> mIndexBuffer;\n\t\tstd::size_t mIndexCount{ 0 };\n\t\tbool mUpdateMaterial{ true };\n\t};\n}", "meta": {"hexsha": "5f3d8402df4e6ad09ed5d5837c3adcabe772fe5e", "size": 1294, "ext": "h", "lang": "C", "max_stars_repo_path": "source/10.4_Dynamic_LOD/DynamicLODDemo.h", "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/10.4_Dynamic_LOD/DynamicLODDemo.h", "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/10.4_Dynamic_LOD/DynamicLODDemo.h", "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.35, "max_line_length": 94, "alphanum_fraction": 0.7820710974, "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.02976009362326731, "lm_q1q2_score": 0.014299090442689425}}
{"text": "/* rng/rng-dump.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 James Theiler, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <gsl/gsl_rng.h>\n\nint\nmain (int argc, char **argv)\n{\n  int i, j ;\n  char buffer[1024 * 4] ;\n  gsl_rng * r ;\n\n  gsl_rng_env_setup () ;\n\n  r = gsl_rng_alloc (gsl_rng_default) ;\n\n  if (argc != 1)\n    {\n      printf (\"Usage: diehard\\n\");\n      printf (\"Output 3 million numbers in binary format,\" \n              \"suitable for testing with DIEHARD\\n\");\n      exit (0);\n    }\n\n  argv = 0 ; /* prevent warning about unused argument */\n\n  for (i = 0; i < 3000 ; i++)\n    {\n      int status ;\n\n      for (j = 0; j < 1024; j++)\n        {\n          unsigned long int u = gsl_rng_get (r) ;\n          buffer[4 * j + 0] = u & 0xFF ;\n          u >>= 8;\n          buffer[4 * j + 1] = u & 0xFF ;\n          u >>= 8;\n          buffer[4 * j + 2] = u & 0xFF ;\n          u >>= 8;\n          buffer[4 * j + 3] = u & 0xFF ;\n\n        }\n      \n      status = fwrite(buffer, 4 * sizeof(char), 1024, stdout) ;\n\n      if (status != 1024) \n        {\n          perror(\"fwrite\") ;\n          exit(EXIT_FAILURE) ;\n        }\n    }\n\n  return 0;\n}\n", "meta": {"hexsha": "801df44dc24bd6bdafe6e1785ae66069f99646c2", "size": 1907, "ext": "c", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/rng/rng-dump.c", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/rng/rng-dump.c", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/rng/rng-dump.c", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 25.7702702703, "max_line_length": 81, "alphanum_fraction": 0.5831148401, "num_tokens": 551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3886180267058489, "lm_q2_score": 0.036769469374108035, "lm_q1q2_score": 0.01428927863118701}}
{"text": "#include <gsl/gsl_test.h>\n#include <gsl/gsl_ieee_utils.h>\n#include <gsl/gsl_math.h>\n#include \"gsl_cblas.h\"\n\n#include \"tests.h\"\n\nvoid\ntest_her2 (void) {\nconst double flteps = 1e-4, dbleps = 1e-6;\n  {\n   int order = 101;\n   int uplo = 121;\n   int N = 1;\n   int lda = 1;\n   float alpha[2] = {-1.0f, 0.0f};\n   float A[] = { -0.821f, 0.954f };\n   float X[] = { 0.532f, 0.802f };\n   int incX = -1;\n   float Y[] = { 0.016f, -0.334f };\n   int incY = -1;\n   float A_expected[] = { -0.302288f, 0.0f };\n   cblas_cher2(order, uplo, N, alpha, X, incX, Y, incY, A, lda);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(A[2*i], A_expected[2*i], flteps, \"cher2(case 1450) real\");\n       gsl_test_rel(A[2*i+1], A_expected[2*i+1], flteps, \"cher2(case 1450) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int uplo = 122;\n   int N = 1;\n   int lda = 1;\n   float alpha[2] = {-1.0f, 0.0f};\n   float A[] = { -0.821f, 0.954f };\n   float X[] = { 0.532f, 0.802f };\n   int incX = -1;\n   float Y[] = { 0.016f, -0.334f };\n   int incY = -1;\n   float A_expected[] = { -0.302288f, 0.0f };\n   cblas_cher2(order, uplo, N, alpha, X, incX, Y, incY, A, lda);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(A[2*i], A_expected[2*i], flteps, \"cher2(case 1451) real\");\n       gsl_test_rel(A[2*i+1], A_expected[2*i+1], flteps, \"cher2(case 1451) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int uplo = 121;\n   int N = 1;\n   int lda = 1;\n   float alpha[2] = {-1.0f, 0.0f};\n   float A[] = { -0.821f, 0.954f };\n   float X[] = { 0.532f, 0.802f };\n   int incX = -1;\n   float Y[] = { 0.016f, -0.334f };\n   int incY = -1;\n   float A_expected[] = { -0.302288f, 0.0f };\n   cblas_cher2(order, uplo, N, alpha, X, incX, Y, incY, A, lda);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(A[2*i], A_expected[2*i], flteps, \"cher2(case 1452) real\");\n       gsl_test_rel(A[2*i+1], A_expected[2*i+1], flteps, \"cher2(case 1452) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int uplo = 122;\n   int N = 1;\n   int lda = 1;\n   float alpha[2] = {-1.0f, 0.0f};\n   float A[] = { -0.821f, 0.954f };\n   float X[] = { 0.532f, 0.802f };\n   int incX = -1;\n   float Y[] = { 0.016f, -0.334f };\n   int incY = -1;\n   float A_expected[] = { -0.302288f, 0.0f };\n   cblas_cher2(order, uplo, N, alpha, X, incX, Y, incY, A, lda);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(A[2*i], A_expected[2*i], flteps, \"cher2(case 1453) real\");\n       gsl_test_rel(A[2*i+1], A_expected[2*i+1], flteps, \"cher2(case 1453) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int uplo = 121;\n   int N = 1;\n   int lda = 1;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { -0.334, 0.286 };\n   double X[] = { -0.14, -0.135 };\n   int incX = -1;\n   double Y[] = { 0.455, 0.358 };\n   int incY = -1;\n   double A_expected[] = { -0.264521, 0.0 };\n   cblas_zher2(order, uplo, N, alpha, X, incX, Y, incY, A, lda);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(A[2*i], A_expected[2*i], dbleps, \"zher2(case 1454) real\");\n       gsl_test_rel(A[2*i+1], A_expected[2*i+1], dbleps, \"zher2(case 1454) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int uplo = 122;\n   int N = 1;\n   int lda = 1;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { -0.334, 0.286 };\n   double X[] = { -0.14, -0.135 };\n   int incX = -1;\n   double Y[] = { 0.455, 0.358 };\n   int incY = -1;\n   double A_expected[] = { -0.264521, 0.0 };\n   cblas_zher2(order, uplo, N, alpha, X, incX, Y, incY, A, lda);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(A[2*i], A_expected[2*i], dbleps, \"zher2(case 1455) real\");\n       gsl_test_rel(A[2*i+1], A_expected[2*i+1], dbleps, \"zher2(case 1455) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int uplo = 121;\n   int N = 1;\n   int lda = 1;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { -0.334, 0.286 };\n   double X[] = { -0.14, -0.135 };\n   int incX = -1;\n   double Y[] = { 0.455, 0.358 };\n   int incY = -1;\n   double A_expected[] = { -0.264521, 0.0 };\n   cblas_zher2(order, uplo, N, alpha, X, incX, Y, incY, A, lda);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(A[2*i], A_expected[2*i], dbleps, \"zher2(case 1456) real\");\n       gsl_test_rel(A[2*i+1], A_expected[2*i+1], dbleps, \"zher2(case 1456) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int uplo = 122;\n   int N = 1;\n   int lda = 1;\n   double alpha[2] = {-0.3, 0.1};\n   double A[] = { -0.334, 0.286 };\n   double X[] = { -0.14, -0.135 };\n   int incX = -1;\n   double Y[] = { 0.455, 0.358 };\n   int incY = -1;\n   double A_expected[] = { -0.264521, 0.0 };\n   cblas_zher2(order, uplo, N, alpha, X, incX, Y, incY, A, lda);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(A[2*i], A_expected[2*i], dbleps, \"zher2(case 1457) real\");\n       gsl_test_rel(A[2*i+1], A_expected[2*i+1], dbleps, \"zher2(case 1457) imag\");\n     };\n   };\n  };\n\n\n}\n", "meta": {"hexsha": "5b43dd1a957c32dff6279ef3f3d495c10c33a553", "size": 4921, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/cblas/test_her2.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/cblas/test_her2.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/cblas/test_her2.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 25.1071428571, "max_line_length": 82, "alphanum_fraction": 0.5013208697, "num_tokens": 2115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.03021458957800994, "lm_q1q2_score": 0.014281937246393234}}
{"text": "#pragma once\n\n#include <gsl-lite/gsl-lite.hpp>\n\n#include <cuda/define_specifiers.hpp>\n#include <cuda/runtime_api.hpp>\n\n#include <thrustshift/math.h>\n\nnamespace thrustshift {\n\nnamespace device_function {\n\nnamespace explicit_unroll {\n\n/*! \\brief Fill range of length `N` with `x`.\n *\n *  \\param N length of the range\n *  \\param p pointer to the range\n *  \\param x value\n *  \\param tid ID of the thread which enters the function\n *  \\param num_threads total amount of threads which enter the function\n */\ntemplate <typename T, int num_threads, int N>\nCUDA_FD void fill(T* p, T x, int tid) {\n\tconstexpr int num_elements_per_thread = N / num_threads;\n#pragma unroll\n\tfor (int i = 0; i < num_elements_per_thread; ++i) {\n\t\tp[i * num_threads + tid] = x;\n\t}\n\tconstexpr int num_rest = N % num_threads;\n\tif (tid < num_rest) {\n\t\tp[num_elements_per_thread * num_threads + tid] = x;\n\t}\n}\n\n} // namespace explicit_unroll\n\nnamespace implicit_unroll {\n\ntemplate <typename T0, typename T1, typename I0, typename I1, typename I2>\nCUDA_FD void fill(T0* p, T1 x, I0 tid, I1 num_threads, I2 N) {\n\tauto num_elements_per_thread = N / num_threads;\n#pragma unroll\n\tfor (int i = 0; i < num_elements_per_thread; ++i) {\n\t\tp[i * num_threads + tid] = x;\n\t}\n\tauto num_rest = N % num_threads;\n\tif (tid < num_rest) {\n\t\tp[num_elements_per_thread * num_threads + tid] = x;\n\t}\n}\n\n} // namespace implicit_unroll\n\n} // namespace device_function\n\nnamespace kernel {\ntemplate <typename T, class Range>\n__global__ void fill(Range r, T val) {\n\n\tconst auto gtid = threadIdx.x + blockIdx.x * blockDim.x;\n\tif (gtid < r.size()) {\n\t\tr[gtid] = val;\n\t}\n}\n\n} // namespace kernel\n\nnamespace async {\n\ntemplate <typename T, class Range>\nvoid fill(cuda::stream_t& stream, Range&& r, T val) {\n\n\tconstexpr cuda::grid::block_dimension_t block_dim = 256;\n\tconst cuda::grid::dimension_t grid_dim =\n\t    ceil_divide(r.size(), gsl_lite::narrow<decltype(r.size())>(block_dim));\n\n\tusing RangeT = typename std::remove_reference<Range>::type::value_type;\n\n\tif (!r.empty()) {\n\t\tcuda::enqueue_launch(kernel::fill<T, gsl_lite::span<RangeT>>,\n\t\t                     stream,\n\t\t                     cuda::make_launch_config(grid_dim, block_dim),\n\t\t                     r,\n\t\t                     val);\n\t}\n}\n\n} // namespace async\n\n} // namespace thrustshift\n", "meta": {"hexsha": "85b293d17e1d3b76bed2786b635dddbf7d640cd7", "size": 2284, "ext": "h", "lang": "C", "max_stars_repo_path": "include/thrustshift/fill.h", "max_stars_repo_name": "pauleonix/thrustshift", "max_stars_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-16T13:01:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T13:01:46.000Z", "max_issues_repo_path": "include/thrustshift/fill.h", "max_issues_repo_name": "pauleonix/thrustshift", "max_issues_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-23T14:12:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-17T11:40:04.000Z", "max_forks_repo_path": "include/thrustshift/fill.h", "max_forks_repo_name": "pauleonix/thrustshift", "max_forks_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5591397849, "max_line_length": 76, "alphanum_fraction": 0.673380035, "num_tokens": 607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.26284183737131667, "lm_q2_score": 0.054198724476223134, "lm_q1q2_score": 0.01424569232451224}}
{"text": "//**************************************************************************\\\n//* This file is property of and copyright by the ALICE Project            *\\\n//* ALICE Experiment at CERN, All rights reserved.                         *\\\n//*                                                                        *\\\n//* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no>        *\\\n//*                  for The ALICE HLT Project.                            *\\\n//*                                                                        *\\\n//* Permission to use, copy, modify and distribute this software and its   *\\\n//* documentation strictly for non-commercial purposes is hereby granted   *\\\n//* without fee, provided that the above copyright notice appears in all   *\\\n//* copies and that both the copyright notice and this permission notice   *\\\n//* appear in the supporting documentation. The authors make no claims     *\\\n//* about the suitability of this software for any purpose. It is          *\\\n//* provided \"as is\" without express or implied warranty.                  *\\\n//**************************************************************************\n\n/// \\file GPUO2InterfaceRefit.h\n/// \\author David Rohr\n\n#ifndef GPUO2INTERFACEREFIT_H\n#define GPUO2INTERFACEREFIT_H\n\n// Some defines denoting that we are compiling for O2\n#ifndef HAVE_O2HEADERS\n#define HAVE_O2HEADERS\n#endif\n#ifndef GPUCA_TPC_GEOMETRY_O2\n#define GPUCA_TPC_GEOMETRY_O2\n#endif\n#ifndef GPUCA_O2_INTERFACE\n#define GPUCA_O2_INTERFACE\n#endif\n\n#include <memory>\n#include <vector>\n#include <gsl/span>\n\nnamespace o2::base\n{\ntemplate <typename value_T>\nclass PropagatorImpl;\nusing Propagator = PropagatorImpl<float>;\n} // namespace o2::base\nnamespace o2::dataformats\n{\ntemplate <typename FirstEntry, typename NElem>\nclass RangeReference;\n}\nnamespace o2::tpc\n{\nusing TPCClRefElem = uint32_t;\nusing TrackTPCClusRef = o2::dataformats::RangeReference<uint32_t, uint16_t>;\nclass TrackTPC;\nstruct ClusterNativeAccess;\n} // namespace o2::tpc\nnamespace o2::track\n{\ntemplate <typename value_T>\nclass TrackParametrizationWithError;\nusing TrackParCovF = TrackParametrizationWithError<float>;\nusing TrackParCov = TrackParCovF;\n} // namespace o2::track\n\nnamespace o2::gpu\n{\nclass GPUParam;\nclass GPUTrackingRefit;\nclass TPCFastTransform;\nclass GPUO2InterfaceRefit\n{\n public:\n  // Must initialize with:\n  // - In any case: Cluster Native access structure (cl), TPC Fast Transformation instance (trans), solenoid field (bz), TPC Track hit references (trackRef)\n  // - Either the shared cluster map (sharedmap) or the vector of tpc tracks (trks) to build the shared cluster map internally\n  // - o2::base::Propagator (p) in case RefitTrackAsTrackParCov is to be used\n\n  GPUO2InterfaceRefit(const o2::tpc::ClusterNativeAccess* cl, const TPCFastTransform* trans, float bz, const o2::tpc::TPCClRefElem* trackRef, const unsigned char* sharedmap = nullptr, const std::vector<o2::tpc::TrackTPC>* trks = nullptr, o2::base::Propagator* p = nullptr);\n  ~GPUO2InterfaceRefit();\n\n  int RefitTrackAsGPU(o2::tpc::TrackTPC& trk, bool outward = false, bool resetCov = false);\n  int RefitTrackAsTrackParCov(o2::tpc::TrackTPC& trk, bool outward = false, bool resetCov = false);\n  int RefitTrackAsGPU(o2::track::TrackParCov& trk, const o2::tpc::TrackTPCClusRef& clusRef, float time0, float* chi2 = nullptr, bool outward = false, bool resetCov = false);\n  int RefitTrackAsTrackParCov(o2::track::TrackParCov& trk, const o2::tpc::TrackTPCClusRef& clusRef, float time0, float* chi2 = nullptr, bool outward = false, bool resetCov = false);\n  void setGPUTrackFitInProjections(bool v = true);\n  void setTrackReferenceX(float v);\n  void setIgnoreErrorsAtTrackEnds(bool v);\n\n  static void fillSharedClustersMap(const o2::tpc::ClusterNativeAccess* cl, const gsl::span<const o2::tpc::TrackTPC> trks, const o2::tpc::TPCClRefElem* trackRef, unsigned char* shmap);\n\n private:\n  std::unique_ptr<GPUTrackingRefit> mRefit;\n  std::unique_ptr<GPUParam> mParam;\n  std::vector<unsigned char> mSharedMap;\n};\n} // namespace o2::gpu\n\n#endif\n", "meta": {"hexsha": "98efb4f714ed29c6b3acc25d99be58ab26cad327", "size": 4059, "ext": "h", "lang": "C", "max_stars_repo_path": "GPU/GPUTracking/Interface/GPUO2InterfaceRefit.h", "max_stars_repo_name": "chengtt0406/AliRoot", "max_stars_repo_head_hexsha": "c1d89b133b433f608b2373112d3608d8cec26095", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 52.0, "max_stars_repo_stars_event_min_datetime": "2016-12-11T13:04:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T11:49:35.000Z", "max_issues_repo_path": "GPU/GPUTracking/Interface/GPUO2InterfaceRefit.h", "max_issues_repo_name": "chengtt0406/AliRoot", "max_issues_repo_head_hexsha": "c1d89b133b433f608b2373112d3608d8cec26095", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1388.0, "max_issues_repo_issues_event_min_datetime": "2016-11-01T10:27:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T15:26:09.000Z", "max_forks_repo_path": "GPU/GPUTracking/Interface/GPUO2InterfaceRefit.h", "max_forks_repo_name": "chengtt0406/AliRoot", "max_forks_repo_head_hexsha": "c1d89b133b433f608b2373112d3608d8cec26095", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 275.0, "max_forks_repo_forks_event_min_datetime": "2016-06-21T20:24:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T13:06:19.000Z", "avg_line_length": 41.4183673469, "max_line_length": 273, "alphanum_fraction": 0.6819413649, "num_tokens": 1058, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3140505449918074, "lm_q2_score": 0.04535258297364358, "lm_q1q2_score": 0.014243003399658932}}
{"text": "///\n/// @file This file contains the Schur reduction experiment.\n///\n/// @author Mirko Myllykoski (mirkom@cs.umu.se), Ume\u00e5 University\n///\n/// @internal LICENSE\n///\n/// Copyright (c) 2019-2020, Ume\u00e5 Universitet\n///\n/// Redistribution and use in source and binary forms, with or without\n/// modification, are permitted provided that the following conditions are met:\n///\n/// 1. Redistributions of source code must retain the above copyright notice,\n///    this list of conditions and the following disclaimer.\n///\n/// 2. Redistributions in binary form must reproduce the above copyright notice,\n///    this list of conditions and the following disclaimer in the documentation\n///    and/or other materials provided with the distribution.\n///\n/// 3. Neither the name of the copyright holder nor the names of its\n///    contributors may be used to endorse or promote products derived from this\n///    software without specific prior written permission.\n///\n/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n/// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n/// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n/// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n/// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n/// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n/// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n/// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n/// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n/// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n/// POSSIBILITY OF SUCH DAMAGE.\n///\n\n#include <starneig_test_config.h>\n#include <starneig/configuration.h>\n#include \"experiment.h\"\n#include \"solvers.h\"\n#include \"../common/common.h\"\n#include \"../common/threads.h\"\n#include \"../common/parse.h\"\n#include \"../common/init.h\"\n#include \"../common/checks.h\"\n#include \"../common/hooks.h\"\n#include \"../common/local_pencil.h\"\n#ifdef STARNEIG_ENABLE_MPI\n#include \"../common/starneig_pencil.h\"\n#endif\n#include \"../common/io.h\"\n#include \"../common/crawler.h\"\n#include \"../common/complex_distr.h\"\n#include \"../hessenberg/solvers.h\"\n#include <starneig/starneig.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <unistd.h>\n#ifdef GSL_FOUND\n#include <gsl/gsl_randist.h>\n#endif\n\n#define DEFLATE         0x1\n#define SET_TO_INF      0x2\n\nstatic int deflate_and_place_infinities_crawler(\n    int offset, int size, int m, int n, int count, size_t *lds,\n    void **ptrs, void *arg)\n{\n    int const *sub = arg;\n\n    double *A = ptrs[0];\n    size_t ldA = lds[0];\n\n    double *B = NULL; size_t ldB = 0;\n    if (ptrs[1] != NULL) {\n        B = ptrs[1];\n        ldB = lds[1];\n    }\n\n    for (int i = 1; i < size; i++) {\n        if (sub[offset+i] & DEFLATE)\n            A[(i-1)*ldA+i] = 0.0;\n        if (B != NULL && sub[offset+i] & SET_TO_INF)\n            B[i*ldB+i] = 0.0;\n    }\n\n    return size;\n}\n\n///\n/// @brief Modifies a matrix pencil such that it is decoupled to multiple\n/// independent subproblems and adds\n///\n/// @param[in] cuts\n///         The desired number of deflations.\n///\n/// @param[in] infinities\n///         The desired number of infinities.\n///\n/// @param[in,out] pencil\n///         The matrix pencil.\n///\nstatic void deflate_and_place_infinities(\n    int cuts, int infinities, pencil_t pencil)\n{\n    int n = GENERIC_MATRIX_N(pencil->mat_a);\n    int *sub = malloc(n*sizeof(int));\n    memset(sub, 0, n*sizeof(int));\n\n    cuts = MIN(cuts, n-1);\n    for (int i = 0; i < cuts; i++) {\n        int p = prand() % (n-1) + 1;\n        while (sub[p] & DEFLATE)\n            p = prand() % (n-1) + 1;\n        sub[p] |= DEFLATE;\n    }\n\n    for (int i = 0; i < infinities; i++) {\n        int p = prand() % (n-1) + 1;\n        while (sub[p] & SET_TO_INF)\n            p = prand() % (n-1) + 1;\n        sub[p] |= SET_TO_INF;\n    }\n\n    crawl_matrices(CRAWLER_RW, CRAWLER_DIAG_WINDOW,\n        &deflate_and_place_infinities_crawler, sub, 0,\n        pencil->mat_a, pencil->mat_b, NULL);\n\n    free(sub);\n\n    free_matrix_descr(pencil->mat_ca);\n    pencil->mat_ca = NULL;\n\n    free_matrix_descr(pencil->mat_cb);\n    pencil->mat_cb = NULL;\n\n    fill_pencil(pencil);\n}\n\n////////////////////////////////////////////////////////////////////////////////\n\nstatic void random_initializer_print_usage(int argc, char * const *argv)\n{\n    printf(\n        \"  --n (num) -- Problem dimension\\n\"\n        \"  --generalized -- Generalized problem\\n\"\n        \"  --decouple (num) -- Decouple the problem\\n\"\n        \"  --set-to-inf (num) -- Place infinities\\n\"\n    );\n\n    init_helper_print_usage(\"\", INIT_HELPER_ALL, argc, argv);\n}\n\nstatic void random_initializer_print_args(int argc, char * const *argv)\n{\n    printf(\" --n %d\", read_int(\"--n\", argc, argv, NULL, -1));\n    if (read_opt(\"--generalized\", argc, argv, NULL))\n        printf(\" --generalized\");\n\n    printf(\" --decouple %d\", read_int(\"--decouple\", argc, argv, NULL, 0));\n    printf(\" --set-to-inf %d\", read_int(\"--set-to-inf\", argc, argv, NULL, 0));\n\n    init_helper_print_args(\"\", INIT_HELPER_ALL, argc, argv);\n}\n\nstatic int random_initializer_check_args(\n    int argc, char * const *argv, int *argr)\n{\n    if (read_int(\"--n\", argc, argv, argr, -1) < 1)\n        return 1;\n\n    read_opt(\"--generalized\", argc, argv, argr);\n\n    if (read_int(\"--decouple\", argc, argv, argr, 0) < 0)\n        return 1;\n\n    if (read_int(\"--set-to-inf\", argc, argv, argr, 0) < 0)\n        return 1;\n\n    return init_helper_check_args(\"\", INIT_HELPER_ALL, argc, argv, argr);\n}\n\nstatic struct hook_data_env* random_initializer_init(\n    hook_data_format_t format, int argc, char * const *argv)\n{\n    printf(\"INIT...\\n\");\n\n    int n = read_int(\"--n\", argc, argv, NULL, -1);\n    int generalized = read_opt(\"--generalized\", argc, argv, NULL);\n    int decouple = read_int(\"--decouple\", argc, argv, NULL, 0);\n    int set_to_inf = read_int(\"--set-to-inf\", argc, argv, NULL, 0);\n\n    init_helper_t helper = init_helper_init_hook(\n        \"\", format, n, n, PREC_DOUBLE | NUM_REAL, argc, argv);\n\n    struct hook_data_env *env = malloc(sizeof(struct hook_data_env));\n    env->format = format;\n    env->copy_data = (hook_data_env_copy_t) copy_pencil;\n    env->free_data = (hook_data_env_free_t) free_pencil;\n    pencil_t data = env->data = init_pencil();\n\n    data->mat_a = generate_random_hessenberg(n, n, helper);\n    data->mat_q = generate_random_householder(n, helper);\n\n    if (generalized) {\n        data->mat_b = generate_random_uptriag(n, n, helper);\n        data->mat_z = generate_random_householder(n, helper);\n    }\n\n    if (0 < decouple || 0 < set_to_inf)\n        deflate_and_place_infinities(decouple, set_to_inf, data);\n\n    init_helper_free(helper);\n\n    return env;\n}\n\nstatic const struct hook_initializer_t random_initializer = {\n    .name = \"random\",\n    .desc = \"Generates a random upper Hessenberg matrix\",\n    .formats = (hook_data_format_t[]) {\n        HOOK_DATA_FORMAT_PENCIL_LOCAL,\n#ifdef STARNEIG_ENABLE_MPI\n        HOOK_DATA_FORMAT_PENCIL_STARNEIG,\n#endif\n#ifdef STARNEIG_ENABLE_BLACS\n        HOOK_DATA_FORMAT_PENCIL_BLACS,\n#endif\n        0 },\n    .print_usage = &random_initializer_print_usage,\n    .print_args = &random_initializer_print_args,\n    .check_args = &random_initializer_check_args,\n    .init = &random_initializer_init\n};\n\n////////////////////////////////////////////////////////////////////////////////\n\nstatic void known_initializer_print_usage(int argc, char * const *argv)\n{\n    printf(\n        \"  --n (num) -- Problem dimension\\n\"\n        \"  --generalized -- Generalized problem\\n\"\n        \"  --complex-distr (complex distribution) -- 2-by-2 block \"\n        \"distribution module\\n\"\n    );\n\n    init_helper_print_usage(\"\", INIT_HELPER_ALL, argc, argv);\n}\n\nstatic void known_initializer_print_args(int argc, char * const *argv)\n{\n    printf(\" --n %d\", read_int(\"--n\", argc, argv, NULL, -1));\n\n    int generalized = read_opt(\"--generalized\", argc, argv, NULL);\n\n    if (generalized)\n        printf(\" --generalized\");\n\n    struct complex_distr const *complex_distr =\n        read_complex_distr(\"--complex-distr\", argc, argv, NULL);\n\n    printf(\" --complex-distr %s\", complex_distr->name);\n\n    if (complex_distr->print_args != NULL)\n        complex_distr->print_args(argc, argv);\n\n    init_helper_print_args(\"\", INIT_HELPER_ALL, argc, argv);\n}\n\nstatic int known_initializer_check_args(\n    int argc, char * const *argv, int *argr)\n{\n    if (read_int(\"--n\", argc, argv, argr, -1) < 1)\n        return 1;\n\n    read_opt(\"--generalized\", argc, argv, argr);\n\n    struct complex_distr const *complex_distr =\n        read_complex_distr(\"--complex-distr\", argc, argv, argr);\n    if (complex_distr == NULL) {\n        fprintf(stderr, \"Invalid 2-by-2 block distribution module.\\n\");\n        return -1;\n    }\n\n    if (complex_distr->check_args != NULL) {\n        int ret = complex_distr->check_args(argc, argv, argr);\n        if (ret)\n            return ret;\n    }\n\n    return init_helper_check_args(\"\", INIT_HELPER_ALL, argc, argv, argr);\n}\n\nstatic struct hook_data_env* known_initializer_init(\n    hook_data_format_t format, int argc, char * const *argv)\n{\n    printf(\"INIT...\\n\");\n\n    int n = read_int(\"--n\", argc, argv, NULL, -1);\n\n    int generalized = read_opt(\"--generalized\", argc, argv, NULL);\n\n    struct complex_distr const *complex_distr =\n        read_complex_distr(\"--complex-distr\", argc, argv, NULL);\n\n    init_helper_t helper = init_helper_init_hook(\n        \"\", format, n, n, PREC_DOUBLE | NUM_REAL, argc, argv);\n\n    struct hook_data_env *env = malloc(sizeof(struct hook_data_env));\n    env->format = format;\n    env->copy_data = (hook_data_env_copy_t) copy_pencil;\n    env->free_data = (hook_data_env_free_t) free_pencil;\n    pencil_t pencil = env->data = init_pencil();\n\n    double *real, *imag, *beta;\n    init_supplementary_known_eigenvalues(n, &real, &imag, &beta, &pencil->supp);\n\n    // generate (generalized) Schur form and multiply with Householder\n    // reflectors from both sides\n\n    if (generalized) {\n        matrix_t mat_s = generate_random_uptriag(n, n, helper);\n        matrix_t mat_t = generate_identity(n, n, helper);\n\n        complex_distr->init(argc, argv, mat_s, mat_t);\n        extract_eigenvalues(mat_s, mat_t, real, imag, beta);\n\n        matrix_t mat_q = generate_random_householder(n, helper);\n        matrix_t mat_z = generate_random_householder(n, helper);\n\n        mul_QAZT(mat_q, mat_s, mat_z, &pencil->mat_a);\n        mul_QAZT(mat_q, mat_t, mat_z, &pencil->mat_b);\n\n        free_matrix_descr(mat_s);\n        free_matrix_descr(mat_t);\n        free_matrix_descr(mat_q);\n        free_matrix_descr(mat_z);\n    }\n    else {\n        matrix_t mat_s = generate_random_uptriag(n, n, helper);\n\n        complex_distr->init(argc, argv, mat_s, NULL);\n        extract_eigenvalues(mat_s, NULL, real, imag, beta);\n\n        matrix_t mat_q = generate_random_householder(n, helper);\n\n        mul_QAZT(mat_q, mat_s, mat_q, &pencil->mat_a);\n\n        free_matrix_descr(mat_s);\n        free_matrix_descr(mat_q);\n    }\n\n    // reduce the dense matrix (pencil) to Hessenberg(-triangular) form\n\n    pencil->mat_q = generate_identity(n, n, helper);\n    pencil->mat_ca = copy_matrix_descr(pencil->mat_a);\n    if (generalized) {\n        pencil->mat_z = generate_identity(n, n, helper);\n        pencil->mat_cb = copy_matrix_descr(pencil->mat_b);\n    }\n\n#ifdef STARNEIG_ENABLE_BLACS\n    if (format == HOOK_DATA_FORMAT_PENCIL_BLACS) {\n        starneig_node_init(threads_get_workers(), STARNEIG_USE_ALL,\n            STARNEIG_HINT_DM | STARNEIG_FXT_DISABLE);\n\n        if (generalized) {\n            starneig_GEP_DM_HessenbergTriangular(\n                STARNEIG_MATRIX_HANDLE(pencil->mat_a),\n                STARNEIG_MATRIX_HANDLE(pencil->mat_b),\n                STARNEIG_MATRIX_HANDLE(pencil->mat_q),\n                STARNEIG_MATRIX_HANDLE(pencil->mat_z));\n        }\n        else {\n            starneig_SEP_DM_Hessenberg(\n                STARNEIG_MATRIX_HANDLE(pencil->mat_a),\n                STARNEIG_MATRIX_HANDLE(pencil->mat_q));\n        }\n\n        starneig_node_finalize();\n    }\n#endif\n\n    if (format == HOOK_DATA_FORMAT_PENCIL_LOCAL) {\n        starneig_node_init(threads_get_workers(), STARNEIG_USE_ALL,\n            STARNEIG_HINT_SM | STARNEIG_FXT_DISABLE);\n\n        if (generalized) {\n            starneig_GEP_SM_HessenbergTriangular(LOCAL_MATRIX_N(pencil->mat_a),\n                LOCAL_MATRIX_PTR(pencil->mat_a), LOCAL_MATRIX_LD(pencil->mat_a),\n                LOCAL_MATRIX_PTR(pencil->mat_b), LOCAL_MATRIX_LD(pencil->mat_b),\n                LOCAL_MATRIX_PTR(pencil->mat_q), LOCAL_MATRIX_LD(pencil->mat_q),\n                LOCAL_MATRIX_PTR(pencil->mat_z), LOCAL_MATRIX_LD(pencil->mat_z)\n            );\n        }\n\n        else {\n            starneig_SEP_SM_Hessenberg(LOCAL_MATRIX_N(pencil->mat_a),\n                LOCAL_MATRIX_PTR(pencil->mat_a), LOCAL_MATRIX_LD(pencil->mat_a),\n                LOCAL_MATRIX_PTR(pencil->mat_q), LOCAL_MATRIX_LD(pencil->mat_q));\n        }\n\n        starneig_node_finalize();\n    }\n\n    init_helper_free(helper);\n\n    return env;\n}\n\nstatic const struct hook_initializer_t known_initializer = {\n    .name = \"known\",\n    .desc = \"Generates an upper Hessenberg matrix with known eigenvalues\",\n    .formats = (hook_data_format_t[]) {\n        HOOK_DATA_FORMAT_PENCIL_LOCAL,\n#ifdef STARNEIG_ENABLE_MPI\n        HOOK_DATA_FORMAT_PENCIL_STARNEIG,\n#endif\n#ifdef STARNEIG_ENABLE_BLACS\n        HOOK_DATA_FORMAT_PENCIL_BLACS,\n#endif\n        0 },\n    .print_usage = &known_initializer_print_usage,\n    .print_args = &known_initializer_print_args,\n    .check_args = &known_initializer_check_args,\n    .init = &known_initializer_init\n};\n\n\n////////////////////////////////////////////////////////////////////////////////\n\n#ifdef GSL_FOUND\n\nstatic void hessrand_initializer_print_usage(int argc, char * const *argv)\n{\n    printf(\n        \"  --n (num) -- Problem dimension\\n\"\n        \"  --generalized -- Generalized problem\\n\"\n        \"  --decouple (num) -- Decouple the problem\\n\"\n        \"  --set-to-inf (num) -- Place infinities\\n\"\n    );\n\n    init_helper_print_usage(\"\", INIT_HELPER_ALL, argc, argv);\n}\n\nstatic void hessrand_initializer_print_args(int argc, char * const *argv)\n{\n    printf(\" --n %d\", read_int(\"--n\", argc, argv, NULL, -1));\n    if (read_opt(\"--generalized\", argc, argv, NULL))\n        printf(\" --generalized\");\n\n    printf(\" --decouple %d\", read_int(\"--decouple\", argc, argv, NULL, 0));\n    printf(\" --set-to-inf %d\", read_int(\"--set-to-inf\", argc, argv, NULL, 0));\n\n    init_helper_print_args(\"\", INIT_HELPER_ALL, argc, argv);\n}\n\nstatic int hessrand_initializer_check_args(\n    int argc, char * const *argv, int *argr)\n{\n    if (read_int(\"--n\", argc, argv, argr, -1) < 1)\n        return 1;\n\n    read_opt(\"--generalized\", argc, argv, argr);\n\n    if (read_int(\"--decouple\", argc, argv, argr, 0) < 0)\n        return 1;\n\n    if (read_int(\"--set-to-inf\", argc, argv, argr, 0) < 0)\n        return 1;\n\n    return init_helper_check_args(\"\", INIT_HELPER_ALL, argc, argv, argr);\n}\n\nstatic int hessrand_crawler(\n    int offset, int width, int m, int n, int count, size_t *lds,\n    void **ptrs, void *arg)\n{\n    gsl_rng *r = arg;\n\n    {\n        double *A = ptrs[0];\n        size_t ldA = lds[0];\n\n        for (int i = 0; i < width; i++) {\n            for (int j = 0; j < offset+i+1; j++)\n                A[i*ldA+j] = gsl_ran_gaussian(r, 1.0);\n            if (offset+i+1 < m)\n                A[i*ldA+offset+i+1] = sqrt(gsl_ran_chisq(r, n-offset-i-1));\n            for (int j = offset+i+2; j < m; j++)\n                A[i*ldA+j] = 0.0;\n        }\n    }\n\n    if (1 < count) {\n        double *B = ptrs[1];\n        size_t ldB = lds[1];\n\n        for (int i = 0; i < width; i++) {\n            for (int j = 0; j < offset+i; j++)\n                B[i*ldB+j] = gsl_ran_gaussian(r, 1.0);\n            B[i*ldB+offset+i] = sqrt(gsl_ran_chisq(r, offset+i));\n            for (int j = offset+i+1; j < m; j++)\n                B[i*ldB+j] = 0.0;\n        }\n\n        if (offset == 0)\n            B[0] = sqrt(gsl_ran_chisq(r, n));\n    }\n\n    return width;\n}\n\nstatic struct hook_data_env* hessrand_initializer_init(\n    hook_data_format_t format, int argc, char * const *argv)\n{\n    printf(\"INIT...\\n\");\n\n    int n = read_int(\"--n\", argc, argv, NULL, -1);\n    int generalized = read_opt(\"--generalized\", argc, argv, NULL);\n    int decouple = read_int(\"--decouple\", argc, argv, NULL, 0);\n    int set_to_inf = read_int(\"--set-to-inf\", argc, argv, NULL, 0);\n\n    init_helper_t helper = init_helper_init_hook(\n        \"\", format, n, n, PREC_DOUBLE | NUM_REAL, argc, argv);\n\n    struct hook_data_env *env = malloc(sizeof(struct hook_data_env));\n    env->format = format;\n    env->copy_data = (hook_data_env_copy_t) copy_pencil;\n    env->free_data = (hook_data_env_free_t) free_pencil;\n    pencil_t data = env->data = init_pencil();\n\n    data->mat_a = init_matrix(n, n, helper);\n    if (generalized)\n        data->mat_b = init_matrix(n, n, helper);\n\n    gsl_rng_env_setup();\n\n    const gsl_rng_type *T = gsl_rng_default;\n    gsl_rng *r = gsl_rng_alloc(T);\n    gsl_rng_set(r, prand());\n\n    crawl_matrices(\n        CRAWLER_W, CRAWLER_PANEL, &hessrand_crawler, r, 0,\n        data->mat_a, data->mat_b, NULL);\n\n    gsl_rng_free(r);\n\n    data->mat_q = generate_random_householder(n, helper);\n    if (generalized)\n        data->mat_z = generate_random_householder(n, helper);\n\n    if (0 < decouple || 0 < set_to_inf)\n        deflate_and_place_infinities(decouple, set_to_inf, data);\n\n    init_helper_free(helper);\n\n    return env;\n}\n\nstatic const struct hook_initializer_t hessrand_initializer = {\n    .name = \"hessrand\",\n    .desc = \"Generates a hessrand upper Hessenberg matrix\",\n    .formats = (hook_data_format_t[]) {\n        HOOK_DATA_FORMAT_PENCIL_LOCAL,\n#ifdef STARNEIG_ENABLE_MPI\n        HOOK_DATA_FORMAT_PENCIL_STARNEIG,\n#endif\n#ifdef STARNEIG_ENABLE_BLACS\n        HOOK_DATA_FORMAT_PENCIL_BLACS,\n#endif\n        0 },\n    .print_usage = &hessrand_initializer_print_usage,\n    .print_args = &hessrand_initializer_print_args,\n    .check_args = &hessrand_initializer_check_args,\n    .init = &hessrand_initializer_init\n};\n\n#endif\n\n////////////////////////////////////////////////////////////////////////////////\n\nstatic void generic_initializer_print_usage(int argc, char * const *argv)\n{\n    printf(\n        \"  --left-input (mtx filename) -- Left-hand side matrix input \"\n        \"file name\\n\"\n        \"  --right-input (mtx filename) -- Right-hand side matrix input \"\n        \"file name\\n\"\n        \"  --input-begin (num) -- First matrix row/column to be read\\n\"\n        \"  --input-end (num) -- Last matrix row/column to be read + 1\\n\"\n        \"  --n (num) -- Problem dimension\\n\"\n        \"  --generalized -- Generate a generalized problem\\n\"\n        \"  --decouple (num) -- Decouple the problem\\n\"\n        \"  --set-to-inf (num) -- Place infinities\\n\"\n    );\n    init_helper_print_usage(\"\", INIT_HELPER_BLACS_PENCIL, argc, argv);\n}\n\nstatic void generic_initializer_print_args(int argc, char * const *argv)\n{\n    char const *left_input = read_str(\"--left-input\", argc, argv, NULL, NULL);\n    char const *right_input = read_str(\"--right-input\", argc, argv, NULL, NULL);\n\n    if (left_input != NULL) {\n        printf(\" --left-input %s\", left_input);\n        if (right_input)\n            printf(\" --right-input %s\", right_input);\n        int input_begin = read_int(\"--input-begin\", argc, argv, NULL, -1);\n        int input_end = read_int(\"--input-end\", argc, argv, NULL, -1);\n        if (0 <= input_begin && 0 <= input_end)\n            printf(\" --input-begin %d --input-end %d\", input_begin, input_end);\n    }\n    else {\n        printf(\" --n %d\", read_int(\"--n\", argc, argv, NULL, -1));\n        if (read_opt(\"--generalized\", argc, argv, NULL))\n            printf(\" --generalized\");\n    }\n\n    printf(\" --decouple %d\", read_int(\"--decouple\", argc, argv, NULL, 0));\n    printf(\" --set-to-inf %d\", read_int(\"--set-to-inf\", argc, argv, NULL, 0));\n\n    init_helper_print_args(\"\", INIT_HELPER_BLACS_PENCIL, argc, argv);\n}\n\nstatic int generic_initializer_check_args(\n    int argc, char * const *argv, int *argr)\n{\n    char const *left_input = read_str(\"--left-input\", argc, argv, argr, NULL);\n    char const *right_input = read_str(\"--right-input\", argc, argv, argr, NULL);\n    if (left_input != NULL) {\n        if (access(left_input, R_OK) != 0) {\n            fprintf(stderr, \"Left-hand side input file does not exists.\\n\");\n            return 1;\n        }\n        int input_begin = read_int(\"--input-begin\", argc, argv, argr, -1);\n        int input_end = read_int(\"--input-end\", argc, argv, argr, -1);\n        if (input_begin < 0 && input_end < input_begin)\n            return 1;\n    }\n    else if (right_input != NULL) {\n        fprintf(stderr, \"Left-hand side input filename is missing.\\n\");\n        return 1;\n    }\n    else {\n        if (read_int(\"--n\", argc, argv, argr, -1) < 1)\n            return 1;\n        read_opt(\"--generalized\", argc, argv, argr);\n    }\n\n    if (read_int(\"--decouple\", argc, argv, argr, 0) < 0)\n        return 1;\n\n    if (read_int(\"--set-to-inf\", argc, argv, argr, 0) < 0)\n        return 1;\n\n    return init_helper_check_args(\n        \"\", INIT_HELPER_BLACS_PENCIL, argc, argv, argr);\n}\n\nstatic struct hook_data_env* lapack_initializer_init(\n    hook_data_format_t format, int argc, char * const *argv)\n{\n    printf(\"INIT...\\n\");\n\n    int n = read_int(\"--n\", argc, argv, NULL, -1);\n    char const *left_input = read_str(\"--left-input\", argc, argv, NULL, NULL);\n    char const *right_input = read_str(\"--right-input\", argc, argv, NULL, NULL);\n    int input_begin = read_int(\"--input-begin\", argc, argv, NULL, -1);\n    int input_end = read_int(\"--input-end\", argc, argv, NULL, -1);\n    int generalized = read_opt(\"--generalized\", argc, argv, NULL);\n    int decouple = read_int(\"--decouple\", argc, argv, NULL, 0);\n    int set_to_inf = read_int(\"--set-to-inf\", argc, argv, NULL, 0);\n\n    if (left_input != NULL) {\n        int m;\n        read_mtx_dimensions_from_file(left_input, &m, &n);\n    }\n\n    if (input_begin == -1)\n        input_begin = 0;\n    if (input_end == -1)\n        input_end = n;\n\n    init_helper_t helper = init_helper_init_hook(\n        \"\", format, n, n, PREC_DOUBLE | NUM_REAL, argc, argv);\n\n    struct hook_data_env *env = malloc(sizeof(struct hook_data_env));\n    env->format = HOOK_DATA_FORMAT_PENCIL_LOCAL;\n    env->copy_data = (hook_data_env_copy_t) copy_pencil;\n    env->free_data = (hook_data_env_free_t) free_pencil;\n    pencil_t data = env->data = data = init_pencil();\n\n    // initialize A\n\n    if (left_input != NULL)\n        data->mat_a = read_mtx_sub_matrix_from_file(\n            input_begin, input_end, left_input, helper);\n    else\n        data->mat_a = generate_random_fullpos(n, n, helper);\n\n    // initialize B\n\n    if (right_input != NULL) {\n        generalized = 1;\n        data->mat_b = read_mtx_sub_matrix_from_file(\n            input_begin, input_end, right_input, helper);\n    }\n    else if (generalized) {\n        data->mat_b = generate_random_fullpos(n, n, helper);\n    }\n\n    // initialize Q and Z\n\n    data->mat_q = generate_identity(n, n, helper);\n    if (generalized)\n        data->mat_z = generate_identity(n, n, helper);\n\n    // prepare for decoupling\n\n    if (decouple < 1) {\n        data->mat_ca = copy_matrix_descr(data->mat_a);\n        data->mat_cb = copy_matrix_descr(data->mat_b);\n    }\n\n    // reduce\n\n    hook_solver_state_t state =\n        hessenberg_lapack_solver.prepare(argc, argv, env);\n    hessenberg_lapack_solver.run(state);\n    hessenberg_lapack_solver.finalize(state, env);\n\n    if (0 < decouple || 0 < set_to_inf)\n        deflate_and_place_infinities(decouple, set_to_inf, data);\n\n    init_helper_free(helper);\n\n    printf(\"INIT FINISHED.\\n\");\n\n    return env;\n}\n\nstatic struct hook_data_env* starpu_initializer_init(\n    hook_data_format_t format, int argc, char * const *argv)\n{\n    printf(\"INIT...\\n\");\n\n    int n = read_int(\"--n\", argc, argv, NULL, -1);\n    char const *left_input = read_str(\"--left-input\", argc, argv, NULL, NULL);\n    char const *right_input = read_str(\"--right-input\", argc, argv, NULL, NULL);\n    int input_begin = read_int(\"--input-begin\", argc, argv, NULL, -1);\n    int input_end = read_int(\"--input-end\", argc, argv, NULL, -1);\n    int generalized = read_opt(\"--generalized\", argc, argv, NULL);\n    int decouple = read_int(\"--decouple\", argc, argv, NULL, 0);\n    int set_to_inf = read_int(\"--set-to-inf\", argc, argv, NULL, 0);\n\n    if (left_input != NULL) {\n        int m;\n        read_mtx_dimensions_from_file(left_input, &m, &n);\n    }\n\n    init_helper_t helper =\n        init_helper_init_hook(\"\", format, n, n, PREC_DOUBLE | NUM_REAL, argc, argv);\n\n    struct hook_data_env *env = malloc(sizeof(struct hook_data_env));\n    env->format = format;\n    env->copy_data = (hook_data_env_copy_t) copy_pencil;\n    env->free_data = (hook_data_env_free_t) free_pencil;\n    pencil_t data = env->data = data = init_pencil();\n\n    // initialize A\n\n    if (left_input != NULL) {\n        if (0 <= input_begin)\n            data->mat_a = read_mtx_sub_matrix_from_file(\n                input_begin, input_end, left_input, helper);\n        else\n            data->mat_a = read_mtx_matrix_from_file(left_input, helper);\n    }\n    else {\n        data->mat_a = generate_random_fullpos(n, n, helper);\n    }\n\n    // initialize B\n\n    if (right_input != NULL) {\n        generalized = 1;\n        if (0 <= input_begin)\n            data->mat_b = read_mtx_sub_matrix_from_file(\n                input_begin, input_end, right_input, helper);\n        else\n            data->mat_b = read_mtx_matrix_from_file(right_input, helper);\n    }\n    else if (generalized) {\n        data->mat_b = generate_random_fullpos(n, n, helper);\n    }\n\n    // initialize Q and Z\n\n    data->mat_q = generate_identity(n, n, helper);\n    if (generalized)\n        data->mat_z = generate_identity(n, n, helper);\n\n    // prepare for decoupling\n\n    if (decouple < 1 && set_to_inf < 1) {\n        data->mat_ca = copy_matrix_descr(data->mat_a);\n        data->mat_cb = copy_matrix_descr(data->mat_b);\n    }\n\n    // reduce\n\n    if (format == HOOK_DATA_FORMAT_PENCIL_LOCAL) {\n\n        starneig_node_init(threads_get_workers(), STARNEIG_USE_ALL,\n            STARNEIG_HINT_SM | STARNEIG_FXT_DISABLE);\n\n        if (generalized)\n            starneig_GEP_SM_HessenbergTriangular(LOCAL_MATRIX_N(data->mat_a),\n                LOCAL_MATRIX_PTR(data->mat_a), LOCAL_MATRIX_LD(data->mat_a),\n                LOCAL_MATRIX_PTR(data->mat_b), LOCAL_MATRIX_LD(data->mat_b),\n                LOCAL_MATRIX_PTR(data->mat_q), LOCAL_MATRIX_LD(data->mat_q),\n                LOCAL_MATRIX_PTR(data->mat_z), LOCAL_MATRIX_LD(data->mat_z));\n        else\n            starneig_SEP_SM_Hessenberg(LOCAL_MATRIX_N(data->mat_a),\n                LOCAL_MATRIX_PTR(data->mat_a), LOCAL_MATRIX_LD(data->mat_a),\n                LOCAL_MATRIX_PTR(data->mat_q), LOCAL_MATRIX_LD(data->mat_q));\n\n        starneig_node_finalize();\n\n    }\n\n#ifdef STARNEIG_ENABLE_BLACS\n    if (format == HOOK_DATA_FORMAT_PENCIL_BLACS) {\n\n        starneig_node_init(threads_get_workers(), STARNEIG_USE_ALL,\n            STARNEIG_HINT_DM | STARNEIG_FXT_DISABLE);\n\n        if (generalized)\n            starneig_GEP_DM_HessenbergTriangular(\n                STARNEIG_MATRIX_HANDLE(data->mat_a),\n                STARNEIG_MATRIX_HANDLE(data->mat_b),\n                STARNEIG_MATRIX_HANDLE(data->mat_q),\n                STARNEIG_MATRIX_HANDLE(data->mat_z));\n        else\n            starneig_SEP_DM_Hessenberg(\n                STARNEIG_MATRIX_HANDLE(data->mat_a),\n                STARNEIG_MATRIX_HANDLE(data->mat_q));\n\n        starneig_node_finalize();\n    }\n#endif\n\n    if (0 < decouple || 0 < set_to_inf)\n        deflate_and_place_infinities(decouple, set_to_inf, data);\n\n    init_helper_free(helper);\n\n    printf(\"INIT FINISHED.\\n\");\n\n    return env;\n}\n\nstatic const struct hook_initializer_t lapack_initializer = {\n    .name = \"lapack\",\n    .desc =\n        \"Reduces a matrix pencil to upper Hessenberg / Hessenberg-triangular \"\n        \"form using a LAPACK algorithm\",\n    .formats = (hook_data_format_t[]) { HOOK_DATA_FORMAT_PENCIL_LOCAL, 0 },\n    .print_usage = &generic_initializer_print_usage,\n    .print_args = &generic_initializer_print_args,\n    .check_args = &generic_initializer_check_args,\n    .init = &lapack_initializer_init\n};\n\nstatic const struct hook_initializer_t starpu_initializer = {\n    .name = \"starneig\",\n    .desc =\n        \"Reduces a matrix pencil to upper Hessenberg / Hessenberg-triangular \"\n        \"form using a StarPU based parallel algorithm\",\n    .formats = (hook_data_format_t[]) {\n        HOOK_DATA_FORMAT_PENCIL_LOCAL,\n#ifdef STARNEIG_ENABLE_BLACS\n        HOOK_DATA_FORMAT_PENCIL_BLACS,\n#endif\n        0 },\n    .print_usage = &generic_initializer_print_usage,\n    .print_args = &generic_initializer_print_args,\n    .check_args = &generic_initializer_check_args,\n    .init = &starpu_initializer_init\n};\n\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n\nstatic void print_usage(int argc, char * const *argv)\n{\n    print_avail_complex_distr();\n    print_opt_complex_distr();\n}\n\nconst struct hook_experiment_descr schur_experiment = {\n    .print_usage = &print_usage,\n    .initializers = (struct hook_initializer_t const *[])\n    {\n#ifdef GSL_FOUND\n        &hessrand_initializer,\n#endif\n        &starpu_initializer,\n        &lapack_initializer,\n        &random_initializer,\n        &known_initializer,\n        &mtx_initializer,\n        &raw_initializer,\n        0\n    },\n    .supplementers = (struct hook_supplementer_t const *[])\n    {\n        0\n    },\n    .solvers = (struct hook_solver const *[])\n    {\n        &schur_starpu_solver,\n        &schur_starpu_simple_solver,\n        &schur_lapack_solver,\n#ifdef PDLAHQR_FOUND\n        &schur_pdlahqr_solver,\n#endif\n#ifdef PDHSEQR_FOUND\n        &schur_pdhseqr_solver,\n#endif\n#ifdef CUSTOM_PDHSEQR\n        &schur_custom_pdhseqr_solver,\n#endif\n#ifdef PDHGEQZ_FOUND\n        &schur_pdhgeqz_solver,\n#endif\n        0\n    },\n    .hook_descrs = (struct hook_descr_t const *[])\n    {\n        &default_schur_test_descr,\n        &default_eigenvalues_descr,\n        &default_known_eigenvalues_descr,\n        &default_analysis_descr,\n        &default_residual_test_descr,\n        &default_print_pencil_descr,\n        &default_print_input_pencil_descr,\n        &default_store_raw_pencil_descr,\n        &default_store_raw_input_pencil_descr,\n        0\n    }\n};\n", "meta": {"hexsha": "5e3f70598091e5d3f3e47dc8c51a207524c7723e", "size": 30680, "ext": "c", "lang": "C", "max_stars_repo_path": "test/schur/experiment.c", "max_stars_repo_name": "NLAFET/StarNEig", "max_stars_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2019-04-28T17:13:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-24T12:30:19.000Z", "max_issues_repo_path": "test/schur/experiment.c", "max_issues_repo_name": "NLAFET/StarNEig", "max_issues_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/schur/experiment.c", "max_forks_repo_name": "NLAFET/StarNEig", "max_forks_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-04-30T12:14:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-14T09:41:23.000Z", "avg_line_length": 32.0920502092, "max_line_length": 84, "alphanum_fraction": 0.6254889179, "num_tokens": 7993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38121955219593834, "lm_q2_score": 0.03732688372982708, "lm_q1q2_score": 0.014229737900354535}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <iniparser.h>\n#include \"prepmt/prepmt_hudson96.h\"\n#ifdef PARMT_USE_INTEL\n#include <mkl_cblas.h>\n#else\n#include <cblas.h>\n#endif\n#include \"cps.h\"\n#include \"iscl/array/array.h\"\n#include \"iscl/fft/fft.h\"\n#include \"iscl/memory/memory.h\"\n#include \"iscl/os/os.h\"\n\n/*!\n * @brief Reads the ini file for Computer Programs in Seismology hudson96\n *        forward modeling variables.\n *\n * @param[in] iniFile    Name of ini file.\n * @param[in] section    Section of ini file to read.\n *\n * @param[out] parms     The hudson96 parameters.\n *\n * @result 0 indicates success.\n *\n * @author Ben Baker, ISTI\n *\n */\nint prepmt_hudson96_readHudson96Parameters(const char *iniFile,\n                                           const char *section,\n                                           struct hudson96_parms_struct *parms)\n{\n    const char *s;\n    char vname[256];\n    dictionary *ini;\n    //------------------------------------------------------------------------//\n    cps_setHudson96Defaults(parms);\n    if (!os_path_isfile(iniFile))\n    {\n        fprintf(stderr, \"%s: ini file: %s does not exist\\n\", __func__, iniFile);\n        return -1;\n    }\n    ini = iniparser_load(iniFile);\n    if (ini == NULL)\n    {\n        fprintf(stderr, \"%s: Cannot parse ini file\\n\", __func__);\n        return -1;\n    }\n    // Teleseismic model\n    memset(vname, 0, 256*sizeof(char));\n    sprintf(vname, \"%s:modeltel\", section);\n    s = iniparser_getstring(ini, vname, NULL);\n    if (s != NULL)\n    {\n        strcpy(parms->modeltel, s);\n    }\n    else\n    {\n        strcpy(parms->modeltel, \"tak135sph.mod\\0\");\n    }\n    // Receiver model\n    memset(vname, 0, 256*sizeof(char));\n    sprintf(vname, \"%s:modelrec\", section);\n    s = iniparser_getstring(ini, vname, NULL);\n    if (s != NULL)\n    {\n        strcpy(parms->modelrec, s);\n    }\n    else\n    {\n        strcpy(parms->modelrec, parms->modelrec);\n    }\n    // Source model\n    memset(vname, 0, 256*sizeof(char));\n    sprintf(vname, \"%s:modelsrc\", section);\n    s = iniparser_getstring(ini, vname, NULL);\n    if (s != NULL)\n    {\n        strcpy(parms->modelsrc, s);\n    }\n    else\n    {\n        strcpy(parms->modelsrc, parms->modelsrc);\n    }\n    memset(vname, 0, 256*sizeof(char));\n    sprintf(vname, \"%s:hs\", section);\n    parms->hs = iniparser_getdouble(ini, vname, 0.0);\n\n    memset(vname, 0, 256*sizeof(char));\n    sprintf(vname, \"%s:dt\", section);\n    parms->dt = iniparser_getdouble(ini, vname, 1.0);\n\n    memset(vname, 0, 256*sizeof(char));\n    sprintf(vname, \"%s:npts\", section);\n    parms->npts = iniparser_getint(ini, vname, 1024);\n\n    memset(vname, 0, 256*sizeof(char));\n    sprintf(vname, \"%s:gcarc\", section);\n    parms->gcarc = iniparser_getdouble(ini, vname, 50.0);\n\n    memset(vname, 0, 256*sizeof(char));\n    sprintf(vname, \"%s:offset\", section);\n    parms->offset = iniparser_getdouble(ini, vname, 10.0);\n\n    memset(vname, 0, 256*sizeof(char));\n    sprintf(vname, \"%s:dosrc\", section);\n    parms->dosrc = iniparser_getboolean(ini, vname, 1);\n\n    memset(vname, 0, 256*sizeof(char));\n    sprintf(vname, \"%s:dorec\", section);\n    parms->dorec = iniparser_getboolean(ini, vname, 1);\n\n    memset(vname, 0, 256*sizeof(char));\n    sprintf(vname, \"%s:dotel\", section);\n    parms->dotel = iniparser_getboolean(ini, vname, 1);\n\n    memset(vname, 0, 256*sizeof(char));\n    sprintf(vname, \"%s:dop\", section);\n    parms->dop = iniparser_getboolean(ini, vname, 1);\n\n    memset(vname, 0, 256*sizeof(char));\n    sprintf(vname, \"%s:dokjar\", section);\n    parms->dokjar = iniparser_getboolean(ini, vname, 1);\n\n    memset(vname, 0, 256*sizeof(char));\n    sprintf(vname, \"%s:loffsetdefault\", section);\n    parms->loffsetdefault = iniparser_getboolean(ini, vname, 1);\n\n    memset(vname, 0, 256*sizeof(char));\n    sprintf(vname, \"%s:verbose\", section);\n    parms->verbose = iniparser_getboolean(ini, vname, 0);\n\n    memset(vname, 0, 256*sizeof(char));\n    sprintf(vname, \"%s:utstar\", section);\n    parms->utstar = iniparser_getdouble(ini, vname, -12345.0);\n\n    memset(vname, 0, 256*sizeof(char));\n    sprintf(vname, \"%s:dottonly\", section);\n    parms->dottonly = iniparser_getboolean(ini, vname, 0);\n\n    memset(vname, 0, 256*sizeof(char));\n    sprintf(vname, \"%s:zsrc\", section);\n    parms->zsrc = iniparser_getdouble(ini, vname, 100.0);\n\n    memset(vname, 0, 256*sizeof(char));\n    sprintf(vname, \"%s:zrec\", section);\n    parms->zrec = iniparser_getdouble(ini, vname, 60.0);\n    // Free ini dictionary\n    iniparser_freedict(ini);\n    return 0;\n}\n//============================================================================//\n/*!\n * @brief Computes the fundamental fault Green's functions for the teleseismic\n *        body waves with hudson96.\n *\n * @param[in] nobs            Number of observations.\n * @param[in] obs             Observations with source location and\n *                            receiver location.  This is an array of length\n *                            nobs.\n * @param[in] luseCrust1      If true then use crust1.0 models at source\n *                            and receiver.\n * @param[in] crust1Dir       If luseCrust1 is true then this is the name\n *                            of the crust1.0 directory.  If NULL and \n *                            luseCrust1 is used then it will default to\n *                            libcps configuration.\n * @param[in] luseSrcModel    If true then use the local source velocity\n *                            at the source.  This supersedes the crust1.0\n *                            source velocity if it is defined.\n * @param[in] sourceModel     If luseSrcModel is true then this is the name\n *                            of the CPS style source model to read.\n *\n * @param[out] telmod         Holds the teleseismic model (ak135).\n * @param[out] srcmod         Holds the local source model.\n * @param[in,out] recmod      On input contains sufficient space and should\n *                            be an array of length nobs.\n *                            On output holds the receiver models.\n *\n * @param[out] ierr           0 indicates success.\n *\n * @author Ben Baker, ISTI\n *\n * @bug I need better handling of the offset.\n *\n */\nint hudson96_getModels(const int nobs, const struct sacData_struct *obs,\n                       const bool luseCrust1, const char *crust1Dir,\n                       const bool luseSrcModel, const char *sourceModel,\n                       struct vmodel_struct *telmod,\n                       struct vmodel_struct *srcmod, \n                       struct vmodel_struct *recmod)\n{\n    double *lats, *lons, evla, evlo;\n    int ierr, iobs;\n    ierr = 0;\n    // Set the teleseismic model\n    memset(srcmod, 0, sizeof(struct vmodel_struct));\n    memset(telmod, 0, sizeof(struct vmodel_struct));\n    cps_globalModel_ak135f(telmod);\n    if (luseCrust1)\n    {\n        fprintf(stdout, \"%s: Reading crust1.0...\\n\", __func__);\n        lats = memory_calloc64f(nobs);\n        lons = memory_calloc64f(nobs);\n        ierr = sacio_getFloatHeader(SAC_FLOAT_EVLA, obs[0].header, &evla);\n        if (ierr != 0)\n        {\n            fprintf(stderr, \"%s: Error - evla not set\\n\", __func__);\n            return ierr;\n        }\n        ierr = sacio_getFloatHeader(SAC_FLOAT_EVLO, obs[0].header, &evlo);\n        if (ierr != 0)\n        {\n            fprintf(stderr, \"%s: Error - evlo not set\\n\", __func__);\n            return ierr;\n        }\n        for (iobs=0; iobs<nobs; iobs++)\n        {\n            sacio_getFloatHeader(SAC_FLOAT_STLA, obs[iobs].header,\n                                 &lats[iobs]);\n            sacio_getFloatHeader(SAC_FLOAT_STLO, obs[iobs].header,\n                                 &lons[iobs]);\n        }\n        ierr = cps_crust1_getCrust1ForHerrmann(crust1Dir, false,\n                                               evla, evlo,\n                                               lats, lons,\n                                               nobs,\n                                               srcmod, recmod);\n        if (ierr != 0)\n        {\n            fprintf(stderr, \"%s: Failed to load crust1.0 model\\n\", __func__);\n            return ierr;\n        }\n        memory_free64f(&lats);\n        memory_free64f(&lons);\n    }\n    // Use teleseismic model for receiver model\n    else\n    {\n        fprintf(stdout, \"%s: Setting receiver models to teleseismic model\\n\",\n                __func__);\n        for (iobs=0; iobs<nobs; iobs++)\n        {\n            cps_utils_copyVmodelStruct(*telmod, &recmod[iobs]);\n        }\n    }\n    // Use source model\n    if (luseSrcModel)\n    {\n        fprintf(stdout, \"%s: Using source model: %s\\n\", __func__, sourceModel);\n        cps_utils_freeVmodelStruct(srcmod);\n        ierr = cps_getmod(sourceModel, srcmod);\n        if (ierr != 0)\n        {\n            fprintf(stderr, \"%s: Error loading srcmod\\n\", __func__);\n            return ierr;\n        }\n    }\n    fprintf(stdout, \"%s: Computing Green's functions...\\n\", __func__);\n    // Otherwise source to teleseismic model\n    if (!luseSrcModel && !luseCrust1)\n    {\n        fprintf(stdout, \"%s: Setting source model to teleseismic model\\n\",\n                __func__);\n        cps_utils_copyVmodelStruct(*telmod, srcmod);\n    }\n    return 0;\n}\n//============================================================================//\n/*!\n * @brief Computes the fundamental fault Green's functions for the teleseismic\n *        body waves with hudson96.\n *\n * @param[in] hudson96Parms   hudson96 forward modeling parameters.\n * @param[in] hpulse96Parms   hpulse96 forward modeling parameters.\n * @param[in] telmod          Holds the teleseismic model (ak135).\n * @param[in] srcmod          Holds the local source model.\n * @param[in] recmod          Holds each receiver model.\n *                            This is an array of dimension [nobs].\n * @param[in] ntstar          Number of t*'s in grid.\n * @param[in] tstars          Array of dimension [ntstar] with the attenuation\n *                            factors.\n * @param[in] ndepth          Number of source depths in grid.\n * @param[in] depths          Array of dimension [ndepth] with the source\n *                            depths specified in (km).\n * @param[in] nobs            Number of observations.\n * @param[in] obs             Observed waveforms which contain the receiver\n *                            locations, components of motion, first\n *                            arrival time, sampling period, and number of\n *                            points in waveform.\n *\n * @param[out] ierr           0 indicates success.\n *\n * @author Ben Baker, ISTI\n *\n * @bug I need better handling of the offset.\n *\n */\nstruct sacData_struct *prepmt_hudson96_computeGreensFF(\n    const struct hudson96_parms_struct hudson96Parms,\n    const struct hpulse96_parms_struct hpulse96Parms,\n    const struct vmodel_struct telmod,\n    const struct vmodel_struct srcmod,\n    const struct vmodel_struct *recmod,\n    const int ntstar, const double *__restrict__ tstars,\n    const int ndepth, const double *__restrict__ depths,\n    const int nobs, const struct sacData_struct *obs, int *ierr)\n{\n    struct hudson96_parms_struct hudson96ParmsWork;\n    struct hpulse96_parms_struct hpulse96ParmsWork;\n    struct hpulse96_data_struct zresp;\n    struct sacData_struct *sacFFGrns;\n    struct hwave_greens_struct *ffGrns;\n    char sncl[64], phaseName[8];\n    double *dptr, cmpaz, cmpinc, dt, gcarc, offset0,\n           pickTime, xnorm;\n    int i, idep, ierrAll, ierr1, ierr2, indx, iobs, iobs0, ip, it,\n        factor, kndx, nloop, npts;\n    bool lzero[10], lfound, lsh;\n    enum isclError_enum isclError;\n    const enum sacHeader_enum pickVars[11]\n       = {SAC_FLOAT_A,\n          SAC_FLOAT_T0, SAC_FLOAT_T1, SAC_FLOAT_T2, SAC_FLOAT_T3,\n          SAC_FLOAT_T4, SAC_FLOAT_T5, SAC_FLOAT_T6, SAC_FLOAT_T7,\n          SAC_FLOAT_T8, SAC_FLOAT_T9};\n    const enum sacHeader_enum pickTypes[11]\n       = {SAC_CHAR_KA,\n          SAC_CHAR_KT0, SAC_CHAR_KT1, SAC_CHAR_KT2, SAC_CHAR_KT3,\n          SAC_CHAR_KT4, SAC_CHAR_KT5, SAC_CHAR_KT6, SAC_CHAR_KT7,\n          SAC_CHAR_KT8, SAC_CHAR_KT9};\n    // Here's the idea: I want to input magnitudes with units of N-m so:\n    // N-m -> Dyne-dm (1.e+7)\n    // CPS internally scales from Dyne-cm to cm (1.e+20)\n    // Finally, I want outputs proprotional to m (1.e-2)\n    const double xmom = 1.0;     // no confusing `relative' magnitudes \n    const double xcps = 1.e-20;  // convert dyne-cm mt to output cm\n    const double cm2m = 1.e-2;   // cm to meters\n    const double dcm2nm = 1.e+7; // magnitudes intended to be specified in\n                                 // Dyne-cm but I work in N-m\n    // Given a M0 in Newton-meters get a seismogram in meters\n    const double xscal = xmom*xcps*cm2m*dcm2nm;\n    const char *cfaults[10] = {\"ZDS\\0\", \"ZSS\\0\", \"ZDD\", \"ZEX\\0\",\n                               \"RDS\\0\", \"RSS\\0\", \"RDD\", \"REX\\0\",\n                               \"TDS\\0\", \"TSS\\0\"};\n    const int npTypes = 11;\n    const int nrDist = 1;\n    const int nrDepths = 1;\n    const int nsDepths = 1;\n    //------------------------------------------------------------------------//\n    //\n    // Quick error checks \n    *ierr = 0;\n    sacFFGrns = NULL;\n    if (nobs < 1 || obs == NULL ||\n        ntstar < 1 || tstars == NULL ||\n        ndepth < 1 || depths == NULL)\n    {\n        *ierr = 1;\n        if (nobs < 1){fprintf(stderr, \"%s: Error no observations\\n\", __func__);}\n        if (obs == NULL){fprintf(stderr, \"%s: Error obs is NULL\\n\", __func__);}\n        if (ntstar < 1){fprintf(stderr, \"%s: Error no t*'s\\n\", __func__);}\n        if (tstars == NULL)\n        {\n            fprintf(stderr, \"%s: Error tstars is NULL\\n\", __func__);\n        }\n        if (ndepth < 1){fprintf(stderr, \"%s: Error no depths\\n\", __func__);}\n        if (depths == NULL)\n        {\n            fprintf(stderr, \"%s: Error depths is NULL\\n\", __func__);\n        }\n        return sacFFGrns;\n    }\n    // Set the modeling structures\n    memset(&hudson96ParmsWork, 0, sizeof(struct hudson96_parms_struct));\n    memset(&hpulse96ParmsWork, 0, sizeof(struct hpulse96_parms_struct));\n    cps_setHudson96Defaults(&hudson96ParmsWork);\n    cps_setHpulse96Defaults(&hpulse96ParmsWork);\n    cps_utils_copyHudson96ParmsStruct(hudson96Parms, &hudson96ParmsWork);\n    cps_utils_copyHpulse96ParmsStruct(hpulse96Parms, &hpulse96ParmsWork);\n    offset0 = hudson96Parms.offset;\n    // Set space for output\n    nloop = nobs*ndepth*ntstar;\n    sacFFGrns = (struct sacData_struct *)\n                 calloc((size_t) (10*nloop), sizeof(struct sacData_struct));\n    // Loop on the distances, depths, t*'s and compute greens functions\n    iobs0 =-1;\n    ierrAll = 0;\n    for (indx=0; indx<nloop; indx++)\n    {\n        ffGrns = NULL;\n        // Convert 3D grid into loop indices (i->n1 is fast; k->n3 is slow)\n        *ierr = prepmt_hudson96_grd2ijk(indx,\n                                        ntstar, ndepth, nobs,\n                                        &it, &idep, &iobs);\n        if (*ierr != 0)\n        {\n            fprintf(stderr, \"%s: Failed to convert to grid\\n\", __func__);\n            break;\n        }\n        // New observation (station) -> may need to update velocity model\n        if (iobs != iobs0)\n        {\n            iobs0 = iobs;\n        }\n        *ierr = sacio_getFloatHeader(SAC_FLOAT_DELTA,\n                                     obs[iobs].header, &dt);\n        if (*ierr != 0)\n        {\n            fprintf(stderr, \"%s: Could not get sampling period\\n\", __func__);\n            break;\n        }\n        *ierr = sacio_getFloatHeader(SAC_FLOAT_GCARC,\n                                     obs[iobs].header, &gcarc);\n        if (*ierr != 0)\n        {\n            fprintf(stderr, \"%s: Could not get gcarc\\n\", __func__);\n            break;\n        }\n        *ierr = sacio_getIntegerHeader(SAC_INT_NPTS,\n                                       obs[iobs].header, &npts);\n        if (*ierr != 0)\n        {\n            fprintf(stderr, \"%s: Could not get npts\\n\", __func__);\n            break;\n        }\n        // Tie waveform modeling to first pick type \n        lfound = false;\n        hudson96ParmsWork.dop = true;\n        for (ip=0; ip<npTypes; ip++)\n        {\n            ierr1 = sacio_getCharacterHeader(pickTypes[ip],\n                                             obs[iobs].header, phaseName);\n            ierr2 = sacio_getFloatHeader(pickVars[ip], \n                                         obs[iobs].header, &pickTime);\n            if (ierr1 == 0 && ierr2 == 0)\n            {\n                lfound = true;\n                if (strncasecmp(phaseName, \"P\", 1) == 0)\n                {\n                    hudson96ParmsWork.dop = true;\n                }\n                else if (strncasecmp(phaseName, \"S\", 1) == 0)\n                {\n                    hudson96ParmsWork.dop = false;\n                }\n                else\n                {\n                    fprintf(stderr, \"%s: Can't classify phase: %s\\n\",\n                            __func__, phaseName);\n                    lfound = false;\n                }\n                break;\n            }\n        }\n        if (!lfound)\n        {\n            fprintf(stdout, \"%s: No pick available - won't be able to align\\n\",\n                    __func__);\n            continue;\n        }\n        memset(&zresp, 0, sizeof(struct hpulse96_data_struct));\n        hudson96ParmsWork.hs = depths[idep];\n        hudson96ParmsWork.dt = dt;\n        hudson96ParmsWork.gcarc = gcarc;\n        hudson96ParmsWork.utstar = tstars[it];\n        factor = 2;\n        if (hudson96ParmsWork.dt < 0.1){factor = 4;}\n        hudson96ParmsWork.npts = MAX(256,\n                                     MIN(2048,\n                                         factor*fft_nextpow2(MAX(1, npts), ierr)));\n        hudson96ParmsWork.offset = fmin(pickTime, offset0); //TODO: fmin or fmax?\n//printf(\"%s %f\\n\", phaseName, pickTime);\n        // Try to pad this out a little\n        hudson96ParmsWork.offset = fmax(hudson96ParmsWork.offset,\n                                  (double) (hudson96ParmsWork.npts - 1)*dt*0.2);\n//        printf(\"%e %d\\n\", hudson96ParmsWork.offset/dt, npts);\n/*\n        if (pickTime < hudson96ParmsWork.offset)\n        {\n            hudson96ParmsWork.offset = (double) (int) (pickTime/dt + 0.5)*dt;\n        }\n*/\n        zresp = hudson96_interface(hudson96ParmsWork,\n                                   telmod, recmod[iobs], srcmod, ierr);\n        if (*ierr != 0)\n        {\n            fprintf(stderr, \"%s: Error calling hudson96\\n\", __func__);\n            ierrAll = ierrAll + 1;\n            goto NEXT_OBS;\n        }\n        ffGrns = hpulse96_interface(nrDist, nrDepths, nsDepths,\n                                    hpulse96ParmsWork,\n                                    &zresp, ierr);\n        if (*ierr != 0)\n        {\n            fprintf(stderr, \"%s: Error calling hpulse96 interface\\n\", __func__);\n            ierrAll = ierrAll + 1;\n            goto NEXT_OBS;\n        }\n        // Set the fundamental fault Green's functions\n        for (i=0; i<10; i++)\n        {\n            dptr = NULL;\n            lsh = false;\n            lzero[i] = false;\n            if (i == 0)\n            {\n                dptr = ffGrns->zds;\n            }\n            else if (i == 1)\n            {\n                dptr = ffGrns->zss;\n            }\n            else if (i == 2)\n            {\n                dptr = ffGrns->zdd;\n            }\n            else if (i == 3)\n            {\n                dptr = ffGrns->zex;\n            }\n            else if (i == 4)\n            {\n                dptr = ffGrns->rds;\n                cmpinc = 90.0;\n            }\n            else if (i == 5)\n            {\n                dptr = ffGrns->rss;\n                cmpinc = 90.0;\n            }\n            else if (i == 6)\n            {\n                dptr = ffGrns->rdd;\n                cmpinc = 90.0;\n            }\n            else if (i == 7)\n            {\n                dptr = ffGrns->rex;\n                cmpinc = 90.0;\n            }\n            else if (i == 8)\n            {\n                dptr = ffGrns->tds;\n                lsh = true;\n                cmpaz = 90.0;\n                cmpinc = 90.0;\n            }\n            else if (i == 9)\n            {\n                dptr = ffGrns->tss;\n                lsh = true;\n                cmpaz = 90.0;\n                cmpinc = 90.0;\n            }\n            kndx = indx*10 + i;\n            sacio_setDefaultHeader(&sacFFGrns[kndx].header);\n            sacFFGrns[kndx].header.lhaveHeader = true;\n            sacio_setIntegerHeader(SAC_INT_NPTS, ffGrns->npts,\n                                   &sacFFGrns[kndx].header);\n            sacio_setIntegerHeader(SAC_INT_NZYEAR, 1970,\n                                   &sacFFGrns[kndx].header);\n            sacio_setIntegerHeader(SAC_INT_NZJDAY, 1,\n                                   &sacFFGrns[kndx].header);\n            sacio_setIntegerHeader(SAC_INT_NZHOUR, 0,\n                                   &sacFFGrns[kndx].header);\n            sacio_setIntegerHeader(SAC_INT_NZMIN, 0,\n                                   &sacFFGrns[kndx].header);\n            sacio_setIntegerHeader(SAC_INT_NZSEC, 0,\n                                   &sacFFGrns[kndx].header);\n            sacio_setIntegerHeader(SAC_INT_NZMSEC, 0,\n                                   &sacFFGrns[kndx].header);\n            sacio_setBooleanHeader(SAC_BOOL_LCALDA, false,\n                                   &sacFFGrns[kndx].header);\n            sacio_setFloatHeader(SAC_FLOAT_DELTA, ffGrns->dt,\n                                 &sacFFGrns[kndx].header);\n            sacio_setFloatHeader(SAC_FLOAT_GCARC, ffGrns->dist/111.195,\n                                 &sacFFGrns[kndx].header);\n            sacio_setFloatHeader(SAC_FLOAT_DIST, ffGrns->dist,\n                                 &sacFFGrns[kndx].header);\n            sacio_setFloatHeader(SAC_FLOAT_EVDP, depths[idep],\n                                 &sacFFGrns[kndx].header);\n            sacio_setFloatHeader(SAC_FLOAT_STEL, ffGrns->stelel,\n                                 &sacFFGrns[kndx].header); \n            sacio_setFloatHeader(SAC_FLOAT_AZ,  0.0,\n                                 &sacFFGrns[kndx].header);\n            sacio_setFloatHeader(SAC_FLOAT_BAZ, 180.0,\n                                 &sacFFGrns[kndx].header);\n            sacio_setFloatHeader(SAC_FLOAT_O, -ffGrns->t0, \n                                 &sacFFGrns[kndx].header); \n            sacio_setFloatHeader(SAC_FLOAT_B, ffGrns->t0,\n                                 &sacFFGrns[kndx].header);\n            sacio_setFloatHeader(SAC_FLOAT_CMPAZ, cmpaz,\n                                 &sacFFGrns[kndx].header);\n            sacio_setFloatHeader(SAC_FLOAT_CMPINC, cmpinc,\n                                 &sacFFGrns[kndx].header);\n            if (hudson96ParmsWork.dop)\n            {\n                sacio_setFloatHeader(SAC_FLOAT_A, ffGrns->timep,\n                                     &sacFFGrns[kndx].header);\n                sacio_setCharacterHeader(SAC_CHAR_KA, \"P\",\n                                         &sacFFGrns[kndx].header);\n            }\n            else\n            {\n                if (!lsh)\n                {\n                    sacio_setFloatHeader(SAC_FLOAT_A, ffGrns->timesv,\n                                         &sacFFGrns[kndx].header);\n                }\n                else\n                {\n                    sacio_setFloatHeader(SAC_FLOAT_A, ffGrns->timesh,\n                                         &sacFFGrns[kndx].header);\n                }\n                sacio_setCharacterHeader(SAC_CHAR_KA, \"S\",\n                                         &sacFFGrns[kndx].header);\n            }\n            sacio_setCharacterHeader(SAC_CHAR_KO, \"O\\0\",\n                                     &sacFFGrns[kndx].header);\n            sacio_setCharacterHeader(SAC_CHAR_KEVNM, \"SYNTHETIC\\0\",\n                                     &sacFFGrns[kndx].header);\n            sacio_setCharacterHeader(SAC_CHAR_KCMPNM, cfaults[i],\n                                     &sacFFGrns[kndx].header);\n            sacFFGrns[kndx].npts = ffGrns->npts;\n            sacFFGrns[kndx].data = sacio_malloc64f(ffGrns->npts);\n            if (dptr != NULL)\n            {\n                array_copy64f_work(ffGrns->npts, dptr, sacFFGrns[kndx].data);\n            }\n            else\n            {\n                array_set64f_work(ffGrns->npts, 0.0, sacFFGrns[kndx].data);\n            }\n            xnorm = cblas_dnrm2(sacFFGrns[kndx].npts, sacFFGrns[kndx].data, 1);\n            if (xnorm == 0.0){lzero[i] = true;}\n            // Handle scaling\n            cblas_dscal(sacFFGrns[kndx].npts, xscal, sacFFGrns[kndx].data, 1);\n            dptr = NULL;\n        } // Loop on fundamnetal faults\n        if (array_sum8l(10, lzero, &isclError) == 10)\n        {\n            memset(sncl, 0, 64*sizeof(char));\n            sprintf(sncl, \"%s.%s.%s.%s\",\n                    obs[iobs].header.knetwk, obs[iobs].header.kstnm, \n                    obs[iobs].header.kcmpnm, obs[iobs].header.khole);\n            fprintf(stdout,\n                    \"%s: Warning Greens fn %s w/ npts %d at gcarc=%e is zero\\n\",\n                    __func__, sncl, hudson96ParmsWork.npts, gcarc);\n        }\nNEXT_OBS:;\n        if (ffGrns != NULL)\n        {\n            cps_utils_freeHwaveGreensStruct(ffGrns);\n            free(ffGrns);\n        }\n        cps_utils_freeHpulse96DataStruct(&zresp);\n    }\n    return sacFFGrns;\n}\n//============================================================================//\n/*!\n * @brief Converts a 1D index to 3D grid indices:\n *\n *        Changes:\n *        for (igrd=0; igrd<n1*n2*n3; igrd++)\n *        {\n *\n *        }\n *        To: \n *        for (k=0; k<n3; k++)\n *        {\n *            for (j=0; j<n2; j++)\n *            {\n *                for (i=0; i<n1; i++)\n *                {\n *                    igrd = k*n2*n1 + j*n1 + i;\n *                }\n *            }\n *        }\n *\n * @param[in] igrd  Flattened C numbered grid index: igrd = k*n2*n1 + j*n1 + i.\n * @param[in] n1    This is the fastest loop iterator (innermost loop).\n * @param[in] n2    This is the middle loop iterator (intermediate loop).\n * @param[in] n3    This is the slowest loop iterator (outermost loop).\n * @param[out] i    C index in inner loop [0,n1).\n * @param[out] j    C index in intermediate loop [0,n2).\n * @param[out] k    C index in outermost loop [0,n3).\n *\n * @result 0 indicates success.\n *\n */\nint prepmt_hudson96_grd2ijk(const int igrd,\n                            const int n1, const int n2, const int n3,\n                            int *i, int *j, int *k) \n{\n    int ierr, n12;\n    ierr = 0;\n    n12 = n1*n2;\n    *k = (igrd)/n12;\n    *j = (igrd - *k*n12)/n1;\n    *i =  igrd - *k*n12 - *j*n1;\n    if (*i < 0 || *i > n1 - 1){ierr = ierr + 1;}\n    if (*j < 0 || *j > n2 - 1){ierr = ierr + 1;} \n    if (*k < 0 || *k > n3 - 1){ierr = ierr + 1;} \n    return ierr; \n}\n//============================================================================//\n/*!\n * @brief Maps the observation, depth, and t* to the global index.\n *\n * @param[in] ndepth    Number of depths.\n * @param[in] ntstar    Number of t*'s.\n * @param[in] iobs      C indexed observation number [0,nobs-1]\n * @param[in] idep      C indexed depth number [0,ndepth-1]\n * @param[in] it        C indexed t* number [0,ntstar-1]\n *\n * @result If >= 0 then this (iobs, idep, it) index in the Green's functions\n *         table.\n * \n * @author Ben Baker, ISTI\n *\n */\nint prepmt_hudson96_observationDepthTstarToIndex(\n    const int ndepth, const int ntstar,\n    const int iobs, const int idep, const int it)\n{\n    int indx;\n    indx = iobs*ntstar*ndepth + idep*ntstar + it;\n    return indx;\n}\n", "meta": {"hexsha": "ab7dabd404e7d7606c1c65b466a545bf216b887b", "size": 27566, "ext": "c", "lang": "C", "max_stars_repo_path": "prepmt/hudson96.c", "max_stars_repo_name": "bakerb845/parmt", "max_stars_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_stars_repo_licenses": ["Intel"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "prepmt/hudson96.c", "max_issues_repo_name": "bakerb845/parmt", "max_issues_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_issues_repo_licenses": ["Intel"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "prepmt/hudson96.c", "max_forks_repo_name": "bakerb845/parmt", "max_forks_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_forks_repo_licenses": ["Intel"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5558583106, "max_line_length": 83, "alphanum_fraction": 0.5168686063, "num_tokens": 7388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2909808785120009, "lm_q2_score": 0.04885778312321277, "lm_q1q2_score": 0.014216680655341261}}
{"text": "/* Starting from version 7.8, MATLAB BLAS expects ptrdiff_t arguments for integers */\r\n#if MATLAB_VERSION >= 0x0708\r\n#include <stddef.h>\r\n#include <stdlib.h>\r\n#endif \r\n#include <string.h>\r\n        \r\n/* Define MX_HAS_INTERLEAVED_COMPLEX for version <9.4 */\r\n#ifndef MX_HAS_INTERLEAVED_COMPLEX\r\n#define MX_HAS_INTERLEAVED_COMPLEX 0\r\n#endif\r\n\r\n/* Starting from version 7.6, MATLAB BLAS is seperated */\r\n#if MATLAB_VERSION >= 0x0705\r\n#include <blas.h>\r\n#else\r\n#define dcabs1 FORTRAN_WRAPPER(dcabs1)\r\nextern doublereal dcabs1(\r\n        doublereal *z\r\n        );\r\n#endif\r\n#include <lapack.h>\r\n#include \"f2c.h\"\r\n\r\n#define cgeqpb FORTRAN_WRAPPER(cgeqpb)\r\nint cgeqpb(integer *, integer *, integer *, integer *,\r\n        complex *, integer *, complex *, integer *, integer *,\r\n        real *, real *, integer *, real *, complex *, integer *, \r\n        real *, integer *);\r\n\r\n#define cgeqpc FORTRAN_WRAPPER(cgeqpc)\r\nint cgeqpc(integer *, integer *, integer *, integer *, complex *,\r\n        integer *, complex *, integer *, integer *, integer *, real *,\r\n        integer *, integer *, complex *, complex *, real *, real *,\r\n        complex *, integer *, real *);\r\n\r\n#define cgeqpw FORTRAN_WRAPPER(cgeqpw)\r\nint cgeqpw(integer *, integer *, integer *, integer *, integer *,\r\n        complex *, integer *, integer *, real *, complex *, real *, real *,\r\n        complex *, complex *, real *);\r\n\r\n#define cgeqpx FORTRAN_WRAPPER(cgeqpx)\r\nint cgeqpx(integer*, integer*, integer*, integer*, complex*,\r\n        integer*, complex*, integer*, integer*, real*, real*, integer*,\r\n        real*, complex*, integer*, real*, integer*);\r\n\r\n#define cgeqpy FORTRAN_WRAPPER(cgeqpy)\r\nint cgeqpy(integer*, integer*, integer*, integer*, complex*,\r\n        integer*, complex*, integer*, integer*, real*, real*, integer*,\r\n        real*, complex*, integer*, real*, integer*);\r\n\r\n#define clasmx FORTRAN_WRAPPER(clasmx)\r\ndoublereal clasmx(integer *);\r\n\r\n#define clauc1 FORTRAN_WRAPPER(clauc1)\r\nlogical clauc1(integer *, complex *, real *, complex *, complex *, real *);\r\n\r\n#define ctrqpx FORTRAN_WRAPPER(ctrqpx)\r\nint ctrqpx(integer *, integer *, integer *, integer *, complex *,\r\n        integer *, complex *, integer *, integer *, real *, real *,\r\n        integer *, real *, complex *, real *, integer *);\r\n\r\n#define ctrqpy FORTRAN_WRAPPER(ctrqpy)\r\nint ctrqpy(integer *, integer *, integer *, integer *,\r\n        complex *, integer *, complex *c, integer *, integer *,\r\n        real *, real *, integer *, real *, complex *, real *, integer *);\r\n\r\n#define ctrqxc FORTRAN_WRAPPER(ctrqxc)\r\nint ctrqxc(integer *, integer *, integer *, integer *, complex *,\r\n        integer *, complex *, integer *, integer *, integer *, real *,\r\n        real *, real *, complex *, real *, integer *);\r\n\r\n#define cglbif FORTRAN_WRAPPER(cglbif)\r\nint cglbif(integer *, integer *, integer *, integer *,\r\n        complex *, integer *, complex *, integer *, integer *,\r\n        real *, integer *, logical *, complex *, real *, integer *);\r\n\r\n#define ccniif FORTRAN_WRAPPER(ccniif)\r\nint ccniif(integer *, integer *, integer *, integer *,\r\n        complex *, integer *, complex *, integer *, integer *,\r\n        real *, real *, integer *, logical *, complex *, real *, integer *);\r\n\r\n#define cgret FORTRAN_WRAPPER(cgret)\r\nint cgret(integer *, integer *, integer *, integer *,\r\n       complex *, integer *, complex *, integer *, complex *,\r\n       real *, integer *);\r\n\r\n#define shess FORTRAN_WRAPPER(shess)\r\nint chess(integer *, integer *, integer *, integer *,\r\n        complex *, integer *, complex *, integer *,\r\n       complex *, real *, integer *);\r\n\r\n#define ctrqyc FORTRAN_WRAPPER(ctrqyc)\r\nint ctrqyc(integer *, integer *, integer *, integer *,\r\n        complex *, integer *, complex *, integer *, integer *,\r\n        integer *, real *, real *, real *, complex *, real *, integer *);\r\n\r\n#define ctrrnk FORTRAN_WRAPPER(ctrrnk)\r\nint ctrrnk(integer *, complex *, integer *, real *, integer *, complex *, integer *);\r\n\r\n\r\n#define dgeqpb FORTRAN_WRAPPER(dgeqpb)\r\nint dgeqpb(integer *, integer *, integer *,\r\n        integer *, doublereal *, integer *, doublereal *, integer *,\r\n        integer *, doublereal *, doublereal *, integer *, doublereal *,\r\n        doublereal *, integer *, integer *);\r\n  \r\n#define dgeqpc FORTRAN_WRAPPER(dgeqpc)\r\nint dgeqpc(integer *, integer *, integer *,\r\n        integer *, doublereal *, integer *, doublereal *, integer *,\r\n        integer *, integer *, doublereal *, integer *, integer *,\r\n        doublereal *, doublereal *, doublereal *, doublereal *,\r\n        doublereal *, integer *);\r\n\r\n#define dgeqpw FORTRAN_WRAPPER(dgeqpw)\r\nint dgeqpw(integer *, integer *, integer *,\r\n        integer *, integer *, doublereal *, integer *, integer *,\r\n        doublereal *, doublereal *, doublereal *, doublereal *,\r\n        doublereal *, doublereal *);\r\n\r\n#define dgeqpx FORTRAN_WRAPPER(dgeqpx)\r\nint dgeqpx(integer*, integer*, integer*, integer*, doublereal*,\r\n        integer*, doublereal*, integer*, integer*, doublereal*,\r\n        doublereal*, integer*, doublereal*, doublereal*, integer*,\r\n        integer*);\r\n\r\n#define dgeqpy FORTRAN_WRAPPER(dgeqpy)\r\nint dgeqpy(integer*, integer*, integer*, integer*, doublereal*,\r\n        integer*, doublereal*, integer*, integer*, doublereal*,\r\n        doublereal*, integer*, doublereal*, doublereal*, integer*,\r\n        integer*);\r\n\r\n#define dlasmx FORTRAN_WRAPPER(dlasmx)\r\ndoublereal dlasmx(integer *);\r\n\r\n#define dlauc1 FORTRAN_WRAPPER(dlauc1)\r\nlogical dlauc1(integer *, doublereal *, doublereal *, doublereal *,\r\n        doublereal *, doublereal *);\r\n\r\n#define dtrqpx FORTRAN_WRAPPER(dtrqpx)\r\nint dtrqpx(integer *, integer *, integer *, integer *,\r\n        doublereal *, integer *, doublereal *, integer *, integer *,\r\n        doublereal *, doublereal *, integer *, doublereal *, doublereal *,\r\n        integer *, integer *);\r\n\r\n#define dtrqpy FORTRAN_WRAPPER(dtrqpy)\r\nint dtrqpy(integer *, integer *, integer *, integer *,\r\n        doublereal *, integer *, doublereal *, integer *, integer *,\r\n        doublereal *, doublereal *, integer *, doublereal *, doublereal *,\r\n        integer *, integer *);\r\n\r\n#define dtrqxc FORTRAN_WRAPPER(dtrqxc)\r\nint dtrqxc(integer *, integer *, integer *, integer *, doublereal *,\r\n        integer*, doublereal *, integer *, integer *, integer *,\r\n        doublereal *, doublereal *, doublereal *, doublereal *, integer *);\r\n\r\n#define dcniif FORTRAN_WRAPPER(dcniif)\r\nint dcniif(integer *, integer *, integer *, integer *,\r\n        doublereal *, integer *, doublereal *, integer *, integer *,\r\n        doublereal *, doublereal *, integer *, logical *, doublereal *,\r\n        integer *);\r\n\r\n#define dglbif FORTRAN_WRAPPER(dglbif)\r\nint dglbif(integer *, integer *, integer *, integer *,\r\n        doublereal *, integer *, doublereal *, integer *, integer *,\r\n        doublereal *, integer *, logical *, doublereal *, integer *);\r\n\r\n#define dgret FORTRAN_WRAPPER(dgret)\r\nint dgret(integer *, integer *, integer *, integer *,\r\n        doublereal *, integer *, doublereal *, integer *,\r\n        doublereal *, integer *);\r\n\r\n#define dhess FORTRAN_WRAPPER(dhess)\r\nint dhess(integer *, integer *, integer *, integer *,\r\n       doublereal *, integer *, doublereal *, integer *,\r\n       doublereal *, integer *);\r\n\r\n#define dtrqyc FORTRAN_WRAPPER(dtrqyc)\r\nint dtrqyc(integer *, integer *, integer *, integer *, doublereal *,\r\n        integer*, doublereal *, integer *, integer *, integer *,\r\n        doublereal *, doublereal *, doublereal *, doublereal *, integer *);\r\n\r\n#define dtrrnk FORTRAN_WRAPPER(dtrrnk)\r\nint dtrrnk(integer *, doublereal *, integer *,\r\n        doublereal *, integer *, doublereal *, integer *);\r\n\r\n\r\n#define sgeqpb FORTRAN_WRAPPER(sgeqpb)\r\nint sgeqpb(integer *, integer *, integer *, integer *, real *,\r\n        integer *, real *, integer *, integer *, real *, real *, integer *,\r\n        real *, real *, integer *, integer *);\r\n\r\n#define sgeqpc FORTRAN_WRAPPER(sgeqpc)\r\nint sgeqpc(integer *, integer *, integer *, integer *, real *,\r\n        integer *, real *, integer *, integer *, integer *, real *,\r\n        integer *, integer *, real *, real *, real *, real *, real *, integer *);\r\n\r\n#define sgeqpw FORTRAN_WRAPPER(sgeqpw)\r\nint sgeqpw(integer *, integer *, integer *, integer *,\r\n        integer *, real *, integer *, integer *, real *, real *, real *,\r\n        real *, real *, real *);\r\n\r\n#define sgeqpx FORTRAN_WRAPPER(sgeqpx)\r\nint sgeqpx(integer*, integer*, integer*, integer*, real*, integer*,\r\n        real*, integer*, integer*, real*, real*, integer*, real*, real*,\r\n        integer*, integer*);\r\n\r\n#define sgeqpy FORTRAN_WRAPPER(sgeqpy)\r\nint sgeqpy(integer*, integer*, integer*, integer*, real*, integer*,\r\n        real*, integer*, integer*, real*, real*, integer*, real*, real*,\r\n        integer*, integer*);\r\n\r\n#define slasmx FORTRAN_WRAPPER(slasmx)\r\ndoublereal slasmx(integer *);\r\n\r\n#define slauc1 FORTRAN_WRAPPER(slauc1)\r\nlogical slauc1(integer *, real *, real *, real *, real *, real *);\r\n\r\n#define strqpx FORTRAN_WRAPPER(strqpx)\r\nint strqpx(integer *, integer *, integer *, integer *, real *,\r\n        integer *, real *, integer *, integer *, real *, real *, integer *,\r\n        real *, real *, integer *, integer *);\r\n\r\n#define strqpy FORTRAN_WRAPPER(strqpy)\r\nint strqpy(integer *, integer *, integer *, integer *, real *,\r\n        integer *, real *, integer *, integer *, real *, real *, integer *,\r\n        real *, real *, integer *, integer *);\r\n\r\n#define strqxc FORTRAN_WRAPPER(strqxc)\r\nint strqxc(integer *, integer *, integer *, integer *, real *,\r\n        integer *, real *, integer *, integer *, integer *, real *,\r\n        real *, real *, real *, integer *);\r\n\r\n#define sglbif FORTRAN_WRAPPER(sglbif)\r\nint sglbif(integer *, integer *, integer *, integer *,\r\n        real *, integer *, real *, integer *, integer *,\r\n        real *, integer *, logical *, real *, integer *);\r\n\r\n#define scniif FORTRAN_WRAPPER(scniif)\r\nint scniif(integer *, integer *, integer *, integer *,\r\n        real *, integer *, real *, integer *, integer *,\r\n        real *, real *, integer *, logical *, real *, integer *);\r\n\r\n#define sgret FORTRAN_WRAPPER(sgret)\r\nint sgret(integer *, integer *, integer *, integer *,\r\n        real *, integer *, real *, integer *, real *, integer *);\r\n\r\n#define shess FORTRAN_WRAPPER(shess)\r\nint shess(integer *, integer *, integer *, integer *,\r\n        real *, integer *, real *, integer *, real *, integer *);\r\n\r\n#define strqyc FORTRAN_WRAPPER(strqyc)\r\nint strqyc(integer *, integer *, integer *, integer *, real *,\r\n        integer *, real *, integer *, integer *, integer *, real *,\r\n        real *, real *, real *, integer *);\r\n\r\n#define strrnk FORTRAN_WRAPPER(strrnk)\r\nint strrnk(integer *, real *, integer *, real *,\r\n        integer *, real *, integer *);\r\n\r\n\r\n#define zgeqpb FORTRAN_WRAPPER(zgeqpb)\r\nint zgeqpb(integer *, integer *, integer *, integer *, doublecomplex *,\r\n        integer *, doublecomplex *, integer *, integer *, doublereal *,\r\n        doublereal *, integer *, doublereal *, doublecomplex *, integer *,\r\n        doublereal *, integer *);\r\n\r\n#define zgeqpc FORTRAN_WRAPPER(zgeqpc)\r\nint zgeqpc(integer *, integer *, integer *, integer *, doublecomplex *,\r\n        integer *, doublecomplex *, integer *, integer *, integer *, doublereal *,\r\n        integer *, integer *, doublecomplex *, doublecomplex *, doublereal *, doublereal *,\r\n        doublecomplex *, integer *, doublereal *);\r\n\r\n#define zgeqpw FORTRAN_WRAPPER(zgeqpw)\r\nint zgeqpw(integer *, integer *, integer *, integer *, integer *,\r\n        doublecomplex *, integer *, integer *, doublereal *, doublecomplex *,\r\n        doublereal *, doublereal *, doublecomplex *, doublecomplex *, doublereal *);\r\n\r\n#define zgeqpx FORTRAN_WRAPPER(zgeqpx)\r\nint zgeqpx(integer*, integer*, integer*, integer*, doublecomplex*,\r\n        integer*, doublecomplex*, integer*, integer*, doublereal*,\r\n        doublereal*, integer*, doublereal*, doublecomplex*, integer*,\r\n        doublereal*, integer*);\r\n\r\n#define zgeqpy FORTRAN_WRAPPER(zgeqpy)\r\nint zgeqpy(integer*, integer*, integer*, integer*, doublecomplex*,\r\n        integer*, doublecomplex*, integer*, integer*, doublereal*,\r\n        doublereal*, integer*, doublereal*, doublecomplex*, integer*,\r\n        doublereal*, integer*);\r\n\r\n#define zlasmx FORTRAN_WRAPPER(zlasmx)\r\ndoublereal zlasmx(integer *i);\r\n\r\n#define zlauc1 FORTRAN_WRAPPER(zlauc1)\r\nlogical zlauc1(integer *, doublecomplex *, doublereal *,\r\n        doublecomplex *, doublecomplex *, doublereal *);\r\n\r\n#define ztrqpx FORTRAN_WRAPPER(ztrqpx)\r\nint ztrqpx(integer *, integer *, integer *, integer *,\r\n        doublecomplex *, integer *, doublecomplex *, integer*,\r\n        integer *, doublereal *, doublereal *, integer *, doublereal *,\r\n        doublecomplex *, doublereal *, integer *);\r\n\r\n#define ztrqpy FORTRAN_WRAPPER(ztrqpy)\r\nint ztrqpy(integer *, integer *, integer *, integer *,\r\n        doublecomplex *, integer *, doublecomplex *, integer*,\r\n        integer *, doublereal *, doublereal *, integer *, doublereal *,\r\n        doublecomplex *, doublereal *, integer *);\r\n\r\n#define ztrqxc FORTRAN_WRAPPER(ztrqxc)\r\nint ztrqxc(integer *, integer *, integer *, integer *, doublecomplex *,\r\n        integer *, doublecomplex *, integer *, integer *, integer *,\r\n        doublereal *, doublereal *, doublereal *, doublecomplex *,\r\n        doublereal *, integer *);\r\n\r\n#define zcniif FORTRAN_WRAPPER(zcniif)\r\nint zcniif(integer *, integer *, integer *, integer *,\r\n        doublecomplex *, integer *, doublecomplex *, integer *, integer *,\r\n        doublereal *, doublereal *, integer *, logical *, doublecomplex *,\r\n        doublereal *, integer *);\r\n\r\n#define zglbif FORTRAN_WRAPPER(zglbif)\r\nint zglbif(integer *, integer *, integer *, integer *,\r\n        doublecomplex *, integer *, doublecomplex *, integer *, integer *,\r\n        doublereal *, integer *, logical *, doublecomplex *, doublereal *,\r\n        integer *);\r\n        \r\n#define zgret FORTRAN_WRAPPER(zgret)\r\nint zgret(integer *, integer *, integer *, integer *,\r\n        doublecomplex *, integer *,doublecomplex *, integer *, \r\n        doublecomplex *, doublereal *, integer *);\r\n\r\n#define dzhess FORTRAN_WRAPPER(dhess)\r\nint zhess(integer *, integer *, integer *, integer *,\r\n        doublecomplex *, integer *, doublecomplex *, integer *,\r\n        doublecomplex *, doublereal *, integer *);\r\n\r\n#define ztrqyc FORTRAN_WRAPPER(ztrqyc)\r\nint ztrqyc(integer *, integer *, integer *, integer *, doublecomplex *,\r\n        integer *, doublecomplex *, integer *, integer *, integer *,\r\n        doublereal *, doublereal *, doublereal *, doublecomplex *,\r\n        doublereal *, integer *);\r\n\r\n#define ztrrnk FORTRAN_WRAPPER(ztrrnk)\r\nint ztrrnk(integer *, doublecomplex *, integer *,\r\n        doublereal *, integer *, doublecomplex *, integer *);\r\n", "meta": {"hexsha": "67ae66c2d6e80802a302ca1da951b06053e476c7", "size": 14764, "ext": "h", "lang": "C", "max_stars_repo_path": "rrqr.h", "max_stars_repo_name": "iwoodsawyer/rrqr", "max_stars_repo_head_hexsha": "6b8e644c12b01aba4ae8de858f90e9c5955571f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rrqr.h", "max_issues_repo_name": "iwoodsawyer/rrqr", "max_issues_repo_head_hexsha": "6b8e644c12b01aba4ae8de858f90e9c5955571f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rrqr.h", "max_forks_repo_name": "iwoodsawyer/rrqr", "max_forks_repo_head_hexsha": "6b8e644c12b01aba4ae8de858f90e9c5955571f3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.5475504323, "max_line_length": 92, "alphanum_fraction": 0.6326876185, "num_tokens": 3546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.031618767040516, "lm_q1q2_score": 0.014209241018864996}}
{"text": "/*\nFRACTAL - A program growing fractals to benchmark parallelization and drawing\nlibraries.\n\nCopyright 2009-2021, Javier Burguete Tolosa.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\n  list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice,\n  this list of conditions and the following disclaimer in the documentation\n  and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``AS IS'' AND ANY EXPRESS\nOR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\nEVENT SHALL Javier Burguete Tolosa OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\nINDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\nBUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\nADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n/**\n * \\file fractal.c\n * \\brief Source file to define the fractal data and functions.\n * \\author Javier Burguete Tolosa.\n * \\copyright Copyright 2009-2021, Javier Burguete Tolosa.\n */\n#define _GNU_SOURCE\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <time.h>\n#if HAVE_SYSINFO\n#include <sys/sysinfo.h>\n#endif\n#include <gsl/gsl_rng.h>\n#include <libxml/parser.h>\n#include <glib.h>\n#if HAVE_GTOP\n#include <glibtop.h>\n#include <glibtop/close.h>\n#endif\n#ifdef G_OS_WIN32\n#include <windows.h>\n#endif\n#include <libintl.h>\n#include <GL/glew.h>\n#include <ft2build.h>\n#include FT_FREETYPE_H\n#include <gtk/gtk.h>\n#include \"config.h\"\n#include \"fractal.h\"\n#include \"simulator.h\"\n\nextern void draw ();\n\nunsigned int width = WIDTH;     ///< Medium width.\nunsigned int height = HEIGHT;   ///< Medium height.\nunsigned int length = LENGTH;   ///< Medium length.\nunsigned int area;              ///< Medium area.\nunsigned int medium_bytes;      ///< Number of bytes used by the medium.\nunsigned int breaking = 0;      ///< 1 on breaking, 0 otherwise.\nunsigned int simulating = 0;    ///< 1 on simulating, 0 otherwise.\nunsigned int animating = 1;     ///< 1 on animating, 0 otherwise.\n\nunsigned int fractal_type = FRACTAL_TYPE_TREE;  ///< Fractal type.\nunsigned int fractal_3D = 0;    ///< 1 on 3D fractals, 0 on 2D fractals.\nunsigned int fractal_diagonal = 0;\n///< 1 on diagonal point movement, 0 otherwise.\n\nunsigned long t0;               ///< Computational time.\n\nunsigned int max_d = 0;         ///< Maximum fractal size.\nunsigned int *medium = NULL;    ///< Array of fractal points.\nPoint3D *point = NULL;          ///< Array of 3D points.\nunsigned int npoints = 0;       ///< Number of points.\n\nunsigned int random_algorithm = 0;\n///< Type of random numbers generator algorithm.\nunsigned int random_seed_type = 1;      ///< Type of random seed.\nunsigned long random_seed = SEED;       ///< Random seed.\nstatic void *(*parallel_fractal) (gsl_rng * rng);\n///< Pointer to the function to calculate the fractal.\n\nstatic const float color3f[16][3] = {\n  {0., 0., 0.},\n  {1., 0., 0.},\n  {0., 1., 0.},\n  {0., 0., 1.},\n  {0.5, 0.5, 0.},\n  {0.5, 0., 0.5},\n  {0., 0.5, 0.5},\n  {0.5, 0.25, 0.25},\n  {0.25, 0.5, 0.25},\n  {0.25, 0.25, 0.5},\n  {0.75, 0.25, 0.},\n  {0.75, 0., 0.25},\n  {0.25, 0.75, 0.},\n  {0., 0.75, 0.25},\n  {0.25, 0., 0.75},\n  {0., 0.25, 0.75}\n};                              ///< Array of colors.\n\nDialogOptions dialog_options[1];\n  ///< DialogOptions to set the fractal options.\nDialogSimulator dialog_simulator[1];\n  ///< DialogSimulator to show the main window.\n\n// PARALLELIZING DATA\n\nunsigned int nthreads;          ///< Threads number.\nGMutex mutex[1];                ///< Mutex to lock memory saves.\n\n// END\n\n/**\n * Function to return the square of an unsigned int.\n\n * \\return square.\n */\nstatic inline unsigned int\nsqr (int x)                     ///< unsigned int.\n{\n  return x * x;\n}\n\n/**\n * Function to get the number of cores of the CPU.\n *\n * \\return CPU number of cores.\n */\nint\nthreads_number ()\n{\n#if HAVE_GTOP\n  int ncores;\n  glibtop *top;\n  top = glibtop_init ();\n  ncores = top->ncpu + 1;\n  glibtop_close ();\n  return ncores;\n#elif HAVE_GET_NPROCS\n  return get_nprocs ();\n#elif defined(G_OS_WIN32)\n  SYSTEM_INFO sysinfo;\n  GetSystemInfo (&sysinfo);\n  return sysinfo.dwNumberOfProcessors;\n#else\n  return (int) sysconf (_SC_NPROCESSORS_ONLN);\n#endif\n}\n\n/**\n * Function to add a point to the array.\n */\nstatic inline void\npoints_add (int x,              ///< Point x-coordinate.\n            int y,              ///< Point y-coordinate.\n            int z,              ///< Point z-coordinate.\n            unsigned int c)     ///< Point color.\n{\n  Point3D *p;\n  ++npoints;\n  point = (Point3D *) g_realloc (point, npoints * sizeof (Point3D));\n  p = point + npoints - 1;\n  p->r[0] = x;\n  p->r[1] = y;\n  p->r[2] = z;\n  memcpy (p->c, color3f[c], 3 * sizeof (float));\n}\n\n/**\n * Function to make a random 2D movement on a point.\n */\nstatic inline void\npoint_2D_move (int *x,          ///< Point x-coordinate.\n               int *y,          ///< Point y-coordinate.\n               gsl_rng * rng)   ///< Pseudo-random number generator.\n{\n  register unsigned int k;\n  static const int mx[4] = { 0, 0, 1, -1 }, my[4] = { 1, -1, 0, 0 };\n  k = gsl_rng_uniform_int (rng, 4);\n  *x += mx[k];\n  *y += my[k];\n}\n\n/**\n * Function to make a random 2D movement on a point enabling diagonals.\n */\nstatic inline void\npoint_2D_move_diagonal (int *x, ///< Point x-coordinate.\n                        int *y, ///< Point y-coordinate.\n                        gsl_rng * rng)  ///< Pseudo-random number generator.\n{\n  register unsigned int k;\n  static const int mx[8] = { 1, 1, 1, 0, -1, -1, -1, 0 },\n    my[8] = { 1, 0, -1, -1, -1, 0, 1, 1 };\n  k = gsl_rng_uniform_int (rng, 8);\n  *x += mx[k];\n  *y += my[k];\n}\n\n/**\n * Function to make a random 3D movement on a point.\n */\nstatic inline void\npoint_3D_move (int *x,          ///< Point x-coordinate.\n               int *y,          ///< Point y-coordinate.\n               int *z,          ///< Point z-coordinate.\n               gsl_rng * rng)   ///< Pseudo-random number generator.\n{\n  register unsigned int k;\n  static const int mx[6] = { 0, 1, -1, 0, 0, 0 },\n    my[6] = { 0, 0, 0, 1, -1, 0 }, mz[6] = { 1, 0, 0, 0, 0, -1 };\n  k = gsl_rng_uniform_int (rng, 6);\n  *x += mx[k];\n  *y += my[k];\n  *z += mz[k];\n}\n\n/**\n * Function to make a random 3D movement on a point enabling diagonals.\n */\nstatic inline void\npoint_3D_move_diagonal (int *x, ///< Point x-coordinate.\n                        int *y, ///< Point y-coordinate.\n                        int *z, ///< Point z-coordinate.\n                        gsl_rng * rng)  ///< Pseudo-random number generator.\n{\n  register int k;\n  static const int mx[26] = {\n    1, 1, 1, 0, 0, 0, -1, -1, -1,\n    1, 1, 1, 0, 0, -1, -1, -1,\n    1, 1, 1, 0, 0, 0, -1, -1, -1\n  }, my[26] = {\n    1, 0, -1, 1, 0, -1, 1, 0, -1,\n    1, 0, -1, 1, -1, 1, 0, -1, 1, 0, -1, 1, 0, -1, 1, 0, -1\n  }, mz[26] = {\n    1, 1, 1, 1, 1, 1, 1, 1, 1,\n    0, 0, 0, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1\n  };\n  k = gsl_rng_uniform_int (rng, 26);\n  *x += mx[k];\n  *y += my[k];\n  *z += mz[k];\n}\n\n/**\n * Function to start a new 2D tree point.\n */\nstatic inline void\ntree_2D_point_new (int *x,      ///< Point x-coordinate.\n                   int *y,      ///< Point y-coordinate.\n                   gsl_rng * rng)       ///< Pseudo-random number generator.\n{\n  *x = gsl_rng_uniform_int (rng, width);\n  *y = max_d;\n#if DEBUG\n  printf (\"New point x %d y %d\\n\", *x, *y);\n#endif\n}\n\n/**\n * Function to check the limits of a 2D tree point.\n */\nstatic inline void\ntree_2D_point_boundary (int *x, ///< Point x-coordinate.\n                        int *y, ///< Point y-coordinate.\n                        gsl_rng * rng)  ///< Pseudo-random number generator.\n{\n  if (*y < 0 || *y == (int) height)\n    {\n      tree_2D_point_new (x, y, rng);\n      return;\n    }\n  if (*x < 0)\n    *x = width - 1;\n  else if (*x == (int) width)\n    *x = 0;\n#if DEBUG\n  printf (\"Boundary point x %d y %d\\n\", *x, *y);\n#endif\n}\n\n/**\n * Function to fix a 2D tree point.\n *\n * \\return 1 on fixing point, 0 on otherwise.\n */\nstatic inline unsigned int\ntree_2D_point_fix (int x,       ///< Point x-coordinate.\n                   int y)       ///< Point y-coordinate.\n{\n  register unsigned int *point;\n#if DEBUG\n  printf (\"x=%d y=%d max_d=%d width=%d height=%d\\n\", x, y, max_d, width,\n          height);\n#endif\n  if (y > (int) max_d || x == 0 || y == 0 || x == (int) width - 1\n      || y == (int) height - 1)\n    return 0;\n  point = medium + y * width + x;\n  if (point[1] || point[-1] || point[width] || point[-(int) width])\n    {\n#if DEBUG\n      printf (\"fixing point\\n\");\n#endif\n// PARALLELIZING MUTEX\n      g_mutex_lock (mutex);\n      point[0] = 2;\n      points_add (x, y, 0, 2);\n      g_mutex_unlock (mutex);\n// END\n      return 1;\n    }\n  return 0;\n}\n\n/**\n * Function to init a 2D tree.\n */\nstatic inline void\ntree_2D_init ()\n{\n  medium[width / 2] = 2;\n}\n\n/**\n * Function to check the end a 2D tree.\n *\n * \\return 1 on ending, 0 on continuing.\n */\nstatic inline unsigned int\ntree_2D_end (int y)             ///< Point y-coordinate.\n{\n  if (y == (int) max_d)\n    {\n// PARALLELIZING MUTEX\n      g_mutex_lock (mutex);\n      ++max_d;\n      g_mutex_unlock (mutex);\n// END\n    }\n  if (max_d >= height - 1)\n    {\n// PARALLELIZING MUTEX\n      g_mutex_lock (mutex);\n      max_d = height - 1;\n      g_mutex_unlock (mutex);\n// END\n      return 1;\n    }\n  return 0;\n}\n\n/**\n * Function to start a new 3D tree point.\n */\nstatic inline void\ntree_3D_point_new (int *x,      ///< Point x-coordinate.\n                   int *y,      ///< Point y-coordinate.\n                   int *z,      ///< Point z-coordinate.\n                   gsl_rng * rng)       ///< Pseudo-random number generator.\n{\n  *x = gsl_rng_uniform_int (rng, length);\n  *y = gsl_rng_uniform_int (rng, width);\n  *z = max_d;\n#if DEBUG\n  printf (\"New point x %d y %d z %d\\n\", *x, *y, *z);\n#endif\n}\n\n/**\n * Function to check the limits of a 2D tree point.\n */\nstatic inline void\ntree_3D_point_boundary (int *x, ///< Point x-coordinate.\n                        int *y, ///< Point y-coordinate.\n                        int *z, ///< Point z-coordinate.\n                        gsl_rng * rng)  ///< Pseudo-random number generator.\n{\n  if (*z < 0 || *z == (int) height)\n    {\n      tree_3D_point_new (x, y, z, rng);\n      return;\n    }\n  if (*x < 0)\n    *x = length - 1;\n  else if (*x == (int) length)\n    *x = 0;\n  if (*y < 0)\n    *y = width - 1;\n  else if (*y == (int) width)\n    *y = 0;\n#if DEBUG\n  printf (\"New point x %d y %d z %d\\n\", *x, *y, *z);\n#endif\n}\n\n/**\n * Function to fix a 2D tree point.\n *\n * \\return 1 on fixing point, 0 on otherwise.\n */\nstatic inline unsigned int\ntree_3D_point_fix (int x,       ///< Point x-coordinate.\n                   int y,       ///< Point y-coordinate.\n                   int z)       ///< point z-coordinate.\n{\n  register unsigned int *point;\n  if (z > (int) max_d || z == 0 || y == 0 || x == 0 || z == (int) height - 1\n      || y == (int) width - 1 || x == (int) length - 1)\n    return 0;\n  point = medium + z * area + y * length + x;\n  if (point[1] || point[-1] || point[length] || point[-(int) length]\n      || point[area] || point[-(int) area])\n    {\n// PARALLELIZING MUTEX\n      g_mutex_lock (mutex);\n      point[0] = 2;\n      points_add (x, y, z, 2);\n      g_mutex_unlock (mutex);\n// END\n      return 1;\n    }\n  return 0;\n}\n\n/**\n * Function to init a 3D tree.\n */\nstatic inline void\ntree_3D_init ()\n{\n  medium[length * (width / 2) + length / 2] = 2;\n}\n\n/**\n * Function to check the end a 3D tree.\n * \n * \\return 1 on ending, 0 on continuing.\n */\nstatic inline unsigned int\ntree_3D_end (int z)             ///< Point z-coordinate.\n{\n  if (z == (int) max_d)\n    {\n// PARALLELIZING MUTEX\n      g_mutex_lock (mutex);\n      ++max_d;\n      g_mutex_unlock (mutex);\n// END\n    }\n  if (max_d >= height - 1)\n    {\n// PARALLELIZING MUTEX\n      g_mutex_lock (mutex);\n      max_d = height - 1;\n      g_mutex_unlock (mutex);\n// END\n      return 1;\n    }\n  return 0;\n}\n\n/**\n * Function to check the limits of a 2D forest point.\n */\nstatic inline void\nforest_2D_point_boundary (int *x,       ///< Point x-coordinate.\n                          int *y,       ///< Point y-coordinate.\n                          gsl_rng * rng)\n///< Pseudo-random number generator.\n{\n  if (*y == (int) height || *y < 0)\n    {\n      tree_2D_point_new (x, y, rng);\n      return;\n    }\n  if (*x < 0)\n    *x = width - 1;\n  else if (*x == (int) width)\n    *x = 0;\n#if DEBUG\n  printf (\"Boundary point x %d y %d\\n\", *x, *y);\n#endif\n}\n\n/**\n * Function to fix a 2D forest point.\n *\n * \\return 1 on fixing point, 0 on otherwise.\n */\nstatic inline unsigned int\nforest_2D_point_fix (int x,     ///< Point x-coordinate.\n                     int y,     ///< Point y-coordinate.\n                     gsl_rng * rng)     ///< Pseudo-random number generator.\n{\n  register unsigned int k, *point;\n  if (y > (int) max_d || x == 0 || x == (int) width - 1\n      || y == (int) height - 1)\n    return 0;\n  point = medium + y * width + x;\n  if (y == 0)\n    {\n      k = 1 + gsl_rng_uniform_int (rng, 15);\n      goto forest;\n    }\n  k = point[1];\n  if (k)\n    goto forest;\n  k = point[-1];\n  if (k)\n    goto forest;\n  k = point[width];\n  if (k)\n    goto forest;\n  k = point[-(int) width];\n  if (k)\n    goto forest;\n  return 0;\n\nforest:\n// PARALLELIZING MUTEX\n  g_mutex_lock (mutex);\n  point[0] = k;\n  points_add (x, y, 0, k);\n  g_mutex_unlock (mutex);\n// END\n  return k;\n}\n\n/**\n * Function to check the limits of a 3D forest point.\n */\nstatic inline void\nforest_3D_point_boundary (int *x,       ///< Point x-coordinate.\n                          int *y,       ///< Point y-coordinate.\n                          int *z,       ///< Point z-coordinate.\n                          gsl_rng * rng)\n///< Pseudo-random number generator.\n{\n  if (*z == (int) height || *z < 0)\n    {\n      tree_3D_point_new (x, y, z, rng);\n      return;\n    }\n  if (*y < 0)\n    *y = width - 1;\n  else if (*y == (int) width)\n    *y = 0;\n  if (*x < 0)\n    *x = length - 1;\n  else if (*x == (int) length)\n    *x = 0;\n#if DEBUG\n  printf (\"Boundary point x %d y %d z %d\\n\", *x, *y, *z);\n#endif\n}\n\n/**\n * Function to fix a 3D forest point.\n *\n * \\return 1 on fixing point, 0 on otherwise.\n */\nstatic inline unsigned int\nforest_3D_point_fix (int x,     ///< Point x-coordinate.\n                     int y,     ///< Point y-coordinate.\n                     int z,     ///< Point z-coordinate.\n                     gsl_rng * rng)     ///< Pseudo-random number generator.\n{\n  register unsigned int k, *point;\n  if (z > (int) max_d || y == 0 || x == 0 || z == (int) height - 1\n      || y == (int) width - 1 || x == (int) length - 1)\n    return 0;\n  point = medium + z * area + y * length + x;\n  if (z == 0)\n    {\n      k = 1 + gsl_rng_uniform_int (rng, 15);\n      goto forest;\n    }\n  k = point[1];\n  if (k)\n    goto forest;\n  k = point[-1];\n  if (k)\n    goto forest;\n  k = point[length];\n  if (k)\n    goto forest;\n  k = point[-(int) length];\n  if (k)\n    goto forest;\n  k = point[area];\n  if (k)\n    goto forest;\n  k = point[-(int) area];\n  if (k)\n    goto forest;\n  return 0;\n\nforest:\n// PARALLELIZING MUTEX\n  g_mutex_lock (mutex);\n  point[0] = k;\n  points_add (x, y, z, k);\n  g_mutex_unlock (mutex);\n// END\n  return k;\n}\n\n/**\n * Function to start a new 2D neuron point.\n */\nstatic inline void\nneuron_2D_point_new (int *x,    ///< Point x-coordinate.\n                     int *y,    ///< Point y-coordinate.\n                     gsl_rng * rng)     ///< Pseudo-random number generator.\n{\n  register double angle;\n  angle = 2 * M_PI * gsl_rng_uniform (rng);\n  *x = width / 2 + max_d * cos (angle);\n  *y = height / 2 + max_d * sin (angle);\n#if DEBUG\n  printf (\"New point x %d y %d\\n\", *x, *y);\n#endif\n}\n\n/**\n * Function to check the limits of a 2D neuron point.\n */\nstatic inline void\nneuron_2D_point_boundary (int *x,       ///< Point x-coordinate.\n                          int *y,       ///< Point y-coordinate.\n                          gsl_rng * rng)\n///< Pseudo-random number generator.\n{\n  if (*y < 0 || *y == (int) height || *x < 0 || *x == (int) width)\n    {\n      neuron_2D_point_new (x, y, rng);\n#if DEBUG\n      printf (\"Boundary point x %d y %d\\n\", *x, *y);\n#endif\n    }\n}\n\n/**\n * Function to fix a 2D neuron point.\n *\n * \\return 1 on fixing point, 0 on otherwise.\n */\nstatic inline unsigned int\nneuron_2D_point_fix (int x,     ///< Point x-coordinate.\n                     int y)     ///< Point y-coordinate.\n{\n  register unsigned int *point;\n  if (x == 0 || y == 0 || x == (int) width - 1 || y == (int) height - 1)\n    return 0;\n  point = medium + y * width + x;\n  if (point[1] || point[-1] || point[width] || point[-(int) width])\n    {\n// PARALLELIZING MUTEX\n      g_mutex_lock (mutex);\n      point[0] = 2;\n      points_add (x, y, 0, 2);\n      g_mutex_unlock (mutex);\n// END\n      return 1;\n    }\n  return 0;\n}\n\n/**\n * Function to init a 2D neuron.\n */\nstatic inline void\nneuron_2D_init ()\n{\n  medium[(height / 2) * width + width / 2] = 2;\n}\n\n/**\n * Function to check the end a 2D neuron.\n *\n * \\return 1 on ending, 0 on continuing.\n */\nstatic inline unsigned int\nneuron_2D_end (int x,           ///< Point x-coordinate.\n               int y)           ///< Point y-coordinate.\n{\n  register int r, k;\n  r = 1 + round (sqrt (sqr (x - width / 2) + sqr (y - height / 2)));\n  if (r >= (int) max_d)\n    {\n// PARALLELIZING MUTEX\n      g_mutex_lock (mutex);\n      ++max_d;\n      g_mutex_unlock (mutex);\n// END\n    }\n  if (height < width)\n    k = height;\n  else\n    k = width;\n  k = k / 2 - 1;\n  if ((int) max_d >= k)\n    {\n// PARALLELIZING MUTEX\n      g_mutex_lock (mutex);\n      max_d = k;\n      g_mutex_unlock (mutex);\n// END\n      return 1;\n    }\n  return 0;\n}\n\n/**\n * Function to start a new 3D neuron point.\n */\nstatic inline void\nneuron_3D_point_new (int *x,    ///< Point x-coordinate.\n                     int *y,    ///< Point y-coordinate.\n                     int *z,    ///< Point z-coordinate.\n                     gsl_rng * rng)     ///< Pseudo-random number generator.\n{\n  double c1, s1, c2, s2;\n  sincos (2. * M_PI * gsl_rng_uniform (rng), &s1, &c1);\n  sincos (asin (2. * gsl_rng_uniform (rng) - 1), &s2, &c2);\n  *x = length / 2 + max_d * c1 * c2;\n  *y = width / 2 + max_d * s1 * c2;\n  *z = height / 2 + max_d * s2;\n#if DEBUG\n  printf (\"New point x %d y %d z %d\\n\", *x, *y, *z);\n#endif\n}\n\n/**\n * Function to check the limits of a 3D neuron point.\n */\nstatic inline void\nneuron_3D_point_boundary (int *x,       ///< Point x-coordinate.\n                          int *y,       ///< Point y-coordinate.\n                          int *z,       ///< Point z-coordinate.\n                          gsl_rng * rng)\n///< Pseudo-random number generator.\n{\n  if (*z < 0 || *y < 0 || *x < 0 || *z == (int) height || *y == (int) width\n      || *x == (int) length)\n    {\n      neuron_3D_point_new (x, y, z, rng);\n#if DEBUG\n      printf (\"Boundary point x %d y %d z %d\\n\", *x, *y, *z);\n#endif\n    }\n}\n\n/**\n * Function to fix a 3D neuron point.\n *\n * \\return 1 on fixing point, 0 on otherwise.\n */\nstatic inline unsigned int\nneuron_3D_point_fix (int x,     ///< Point x-coordinate.\n                     int y,     ///< Point y-coordinate.\n                     int z)     ///< Point z-coordinate.\n{\n  register unsigned int *point;\n  if (z == 0 || y == 0 || x == 0 || z == (int) height - 1\n      || y == (int) width - 1 || x == (int) length - 1)\n    return 0;\n  point = medium + z * area + y * length + x;\n  if (point[1] || point[-1] || point[length] || point[-(int) length] ||\n      point[area] || point[-(int) area])\n    {\n// PARALLELIZING MUTEX\n      g_mutex_lock (mutex);\n      point[0] = 2;\n      points_add (x, y, z, 2);\n      g_mutex_unlock (mutex);\n// END\n      return 1;\n    }\n  return 0;\n}\n\n/**\n * Function to init a 3D neuron.\n */\nstatic inline void\nneuron_3D_init ()\n{\n  medium[area * (height / 2) + length * (width / 2) + length / 2] = 2;\n}\n\n/**\n * Function to check the end a 3D neuron.\n *\n * \\return 1 on ending, 0 on continuing.\n */\nstatic inline unsigned int\nneuron_3D_end (int x,           ///< Point x-coordinate.\n               int y,           ///< Point y-coordinate.\n               int z)           ///< Point z-coordinate.\n{\n  register int r, k;\n  r = 1 + sqrt (sqr (x - length / 2) + sqr (y - width / 2)\n                + sqr (z - height / 2));\n  if (r >= (int) max_d)\n    {\n// PARALLELIZING MUTEX\n      g_mutex_lock (mutex);\n      ++max_d;\n      g_mutex_unlock (mutex);\n// END\n    }\n  k = length;\n  if ((int) width < k)\n    k = width;\n  if ((int) height < k)\n    k = height;\n  k = k / 2 - 1;\n  if ((int) max_d >= k)\n    {\n// PARALLELIZING MUTEX\n      g_mutex_lock (mutex);\n      max_d = k;\n      g_mutex_unlock (mutex);\n// END\n      return 1;\n    }\n  return 0;\n}\n\n/**\n * Function to stop the fractal simulation.\n */\nvoid\nfractal_stop ()\n{\n// PARALLELIZING MUTEX\n  g_mutex_lock (mutex);\n  breaking = 1;\n  g_mutex_unlock (mutex);\n// END\n}\n\n// PARALLELIZED FUNCTIONS\n\n/**\n * Function to create a 2D fractal tree.\n *\n * \\return NULL.\n */\nvoid *\nparallel_fractal_tree_2D (gsl_rng * rng)\n///< Pseudo-random number generator.\n{\n  int x, y;\n  long t0;\n#if DEBUG\n  printf (\"parallel_fractal_tree_2D: start\\n\");\n#endif\n  t0 = time (NULL);\n  do\n    {\n#if DEBUG\n      printf (\"creating point\\n\");\n#endif\n      tree_2D_point_new (&x, &y, rng);\n#if DEBUG\n      printf (\"checking fix\\n\");\n#endif\n      while (!breaking && !tree_2D_point_fix (x, y))\n        {\n#if DEBUG\n          printf (\"moving point\\n\");\n#endif\n          point_2D_move (&x, &y, rng);\n#if DEBUG\n          printf (\"checking boundary\\n\");\n#endif\n          tree_2D_point_boundary (&x, &y, rng);\n        }\n#if DEBUG\n      printf (\"checking end\\n\");\n#endif\n      if (animating && time (NULL) > t0)\n        break;\n      if (tree_2D_end (y))\n        fractal_stop ();\n    }\n  while (!breaking);\n  g_thread_exit (NULL);\n  return NULL;\n}\n\n/**\n * Function to create a 3D fractal tree.\n *\n * \\return NULL.\n */\nvoid *\nparallel_fractal_tree_3D (gsl_rng * rng)\n///< Pseudo-random number generator.\n{\n  int x, y, z;\n  long t0;\n  t0 = time (NULL);\n  do\n    {\n      tree_3D_point_new (&x, &y, &z, rng);\n      while (!breaking && !tree_3D_point_fix (x, y, z))\n        {\n          point_3D_move (&x, &y, &z, rng);\n          tree_3D_point_boundary (&x, &y, &z, rng);\n        }\n      if (animating && time (NULL) > t0)\n        break;\n      if (tree_3D_end (z))\n        fractal_stop ();\n    }\n  while (!breaking);\n  g_thread_exit (NULL);\n  return NULL;\n}\n\n/**\n * Function to create a 2D fractal forest.\n *\n * \\return NULL.\n */\nvoid *\nparallel_fractal_forest_2D (gsl_rng * rng)\n///< Pseudo-random number generator.\n{\n  int x, y;\n  long t0;\n  t0 = time (NULL);\n  do\n    {\n      tree_2D_point_new (&x, &y, rng);\n      while (!breaking && !forest_2D_point_fix (x, y, rng))\n        {\n          point_2D_move (&x, &y, rng);\n          forest_2D_point_boundary (&x, &y, rng);\n        }\n      if (animating && time (NULL) > t0)\n        break;\n      if (tree_2D_end (y))\n        fractal_stop ();\n    }\n  while (!breaking);\n  g_thread_exit (NULL);\n  return NULL;\n}\n\n/**\n * Function to create a 3D fractal forest.\n *\n * \\return NULL.\n */\nvoid *\nparallel_fractal_forest_3D (gsl_rng * rng)\n///< Pseudo-random number generator.\n{\n  int x, y, z;\n  long t0;\n  t0 = time (NULL);\n  do\n    {\n      tree_3D_point_new (&x, &y, &z, rng);\n      while (!breaking && !forest_3D_point_fix (x, y, z, rng))\n        {\n          point_3D_move (&x, &y, &z, rng);\n          forest_3D_point_boundary (&x, &y, &z, rng);\n        }\n      if (animating && time (NULL) > t0)\n        break;\n      if (tree_3D_end (z))\n        fractal_stop ();\n    }\n  while (!breaking);\n  g_thread_exit (NULL);\n  return NULL;\n}\n\n/**\n * Function to create a 2D fractal neuron.\n *\n * \\return NULL.\n */\nvoid *\nparallel_fractal_neuron_2D (gsl_rng * rng)\n///< Pseudo-random number generator.\n{\n  int x, y;\n  long t0;\n  t0 = time (NULL);\n  do\n    {\n      neuron_2D_point_new (&x, &y, rng);\n      while (!breaking && !neuron_2D_point_fix (x, y))\n        {\n          point_2D_move (&x, &y, rng);\n          neuron_2D_point_boundary (&x, &y, rng);\n        }\n      if (animating && time (NULL) > t0)\n        break;\n      if (neuron_2D_end (x, y))\n        fractal_stop ();\n    }\n  while (!breaking);\n  g_thread_exit (NULL);\n  return NULL;\n}\n\n/**\n * Function to create a 3D fractal neuron.\n *\n * \\return NULL.\n */\nvoid *\nparallel_fractal_neuron_3D (gsl_rng * rng)\n///< Pseudo-random number generator.\n{\n  int x, y, z;\n  long t0;\n  t0 = time (NULL);\n  do\n    {\n      neuron_3D_point_new (&x, &y, &z, rng);\n      while (!breaking && !neuron_3D_point_fix (x, y, z))\n        {\n          point_3D_move (&x, &y, &z, rng);\n          neuron_3D_point_boundary (&x, &y, &z, rng);\n        }\n      if (animating && time (NULL) > t0)\n        break;\n      if (neuron_3D_end (x, y, z))\n        fractal_stop ();\n    }\n  while (!breaking);\n  g_thread_exit (NULL);\n  return NULL;\n}\n\n/**\n * Function to create a 2D fractal tree with diagonal movements.\n *\n * \\return NULL.\n */\nvoid *\nparallel_fractal_tree_2D_diagonal (gsl_rng * rng)\n///< Pseudo-random number generator.\n{\n  int x, y;\n  long t0;\n  t0 = time (NULL);\n  do\n    {\n      tree_2D_point_new (&x, &y, rng);\n      while (!breaking && !tree_2D_point_fix (x, y))\n        {\n          point_2D_move (&x, &y, rng);\n          tree_2D_point_boundary (&x, &y, rng);\n        }\n      if (animating && time (NULL) > t0)\n        break;\n      if (tree_2D_end (y))\n        fractal_stop ();\n    }\n  while (!breaking);\n  g_thread_exit (NULL);\n  return NULL;\n}\n\n/**\n * Function to create a 3D fractal tree with diagonal movements.\n *\n * \\return NULL.\n */\nvoid *\nparallel_fractal_tree_3D_diagonal (gsl_rng * rng)\n///< Pseudo-random number generator.\n{\n  int x, y, z;\n  long t0;\n  t0 = time (NULL);\n  do\n    {\n      tree_3D_point_new (&x, &y, &z, rng);\n      while (!breaking && !tree_3D_point_fix (x, y, z))\n        {\n          point_3D_move (&x, &y, &z, rng);\n          tree_3D_point_boundary (&x, &y, &z, rng);\n        }\n      if (animating && time (NULL) > t0)\n        break;\n      if (tree_3D_end (z))\n        fractal_stop ();\n    }\n  while (!breaking);\n  g_thread_exit (NULL);\n  return NULL;\n}\n\n/**\n * Function to create a 2D fractal forest with diagonal movements.\n *\n * \\return NULL.\n */\nvoid *\nparallel_fractal_forest_2D_diagonal (gsl_rng * rng)\n///< Pseudo-random number generator.\n{\n  int x, y;\n  long t0;\n  t0 = time (NULL);\n  do\n    {\n      tree_2D_point_new (&x, &y, rng);\n      while (!breaking && !forest_2D_point_fix (x, y, rng))\n        {\n          point_2D_move_diagonal (&x, &y, rng);\n          forest_2D_point_boundary (&x, &y, rng);\n        }\n      if (animating && time (NULL) > t0)\n        break;\n      if (tree_2D_end (y))\n        fractal_stop ();\n    }\n  while (!breaking);\n  g_thread_exit (NULL);\n  return NULL;\n}\n\n/**\n * Function to create a 3D fractal forest with diagonal movements.\n *\n * \\return NULL.\n */\nvoid *\nparallel_fractal_forest_3D_diagonal (gsl_rng * rng)\n///< Pseudo-random number generator.\n{\n  int x, y, z;\n  long t0;\n  t0 = time (NULL);\n  do\n    {\n      tree_3D_point_new (&x, &y, &z, rng);\n      while (!breaking && !forest_3D_point_fix (x, y, z, rng))\n        {\n          point_3D_move_diagonal (&x, &y, &z, rng);\n          forest_3D_point_boundary (&x, &y, &z, rng);\n        }\n      if (animating && time (NULL) > t0)\n        break;\n      if (tree_3D_end (z))\n        fractal_stop ();\n    }\n  while (!breaking);\n  g_thread_exit (NULL);\n  return NULL;\n}\n\n/**\n * Function to create a 2D fractal neuron with diagonal movements.\n *\n * \\return NULL.\n */\nvoid *\nparallel_fractal_neuron_2D_diagonal (gsl_rng * rng)\n///< Pseudo-random number generator.\n{\n  int x, y;\n  long t0;\n  t0 = time (NULL);\n  do\n    {\n      neuron_2D_point_new (&x, &y, rng);\n      while (!breaking && !neuron_2D_point_fix (x, y))\n        {\n          point_2D_move_diagonal (&x, &y, rng);\n          neuron_2D_point_boundary (&x, &y, rng);\n        }\n      if (animating && time (NULL) > t0)\n        break;\n      if (neuron_2D_end (x, y))\n        fractal_stop ();\n    }\n  while (!breaking);\n  g_thread_exit (NULL);\n  return NULL;\n}\n\n/**\n * Function to create a 3D fractal neuron with diagonal movements.\n *\n * \\return NULL.\n */\nvoid *\nparallel_fractal_neuron_3D_diagonal (gsl_rng * rng)\n///< Pseudo-random number generator.\n{\n  int x, y, z;\n  long t0;\n  t0 = time (NULL);\n  do\n    {\n      neuron_3D_point_new (&x, &y, &z, rng);\n      while (!breaking && !neuron_3D_point_fix (x, y, z))\n        {\n          point_3D_move_diagonal (&x, &y, &z, rng);\n          neuron_3D_point_boundary (&x, &y, &z, rng);\n        }\n      if (animating && time (NULL) > t0)\n        break;\n      if (neuron_3D_end (x, y, z))\n        fractal_stop ();\n    }\n  while (!breaking);\n  g_thread_exit (NULL);\n  return NULL;\n}\n\n//END OF PARALLELIZED FUNCTIONS\n\n/**\n * Function to start the fractal functions and data.\n */\nvoid\nmedium_start ()\n{\n  register int i, j;\n\n#if DEBUG\n  printf (\"Deleting points\\n\");\n#endif\n  g_free (point);\n  point = NULL;\n  npoints = 0;\n\n  j = area = width * length;\n  if (fractal_3D)\n    j *= length;\n  medium_bytes = j * sizeof (unsigned int);\n  medium = (unsigned int *) g_slice_alloc (medium_bytes);\n  for (i = j; --i >= 0;)\n    medium[i] = 0;\n#if DEBUG\n  printf (\"Medium size=%d pointer=%ld\\n\", j, (size_t) medium);\n#endif\n\n#if DEBUG\n  printf (\"Setting functions\\n\");\n#endif\n  if (fractal_diagonal)\n    {\n      if (fractal_3D)\n        {\n          switch (fractal_type)\n            {\n            case FRACTAL_TYPE_TREE:\n              tree_3D_init ();\n              parallel_fractal = parallel_fractal_tree_3D_diagonal;\n              max_d = 1;\n              break;\n            case FRACTAL_TYPE_FOREST:\n              parallel_fractal = parallel_fractal_forest_3D_diagonal;\n              max_d = 1;\n              break;\n            default:\n              neuron_3D_init ();\n              parallel_fractal = parallel_fractal_neuron_3D_diagonal;\n              max_d = 2;\n            }\n        }\n      else\n        {\n          switch (fractal_type)\n            {\n            case FRACTAL_TYPE_TREE:\n              tree_2D_init ();\n              parallel_fractal = parallel_fractal_tree_2D_diagonal;\n              max_d = 1;\n              break;\n            case FRACTAL_TYPE_FOREST:\n              parallel_fractal = parallel_fractal_forest_2D_diagonal;\n              max_d = 1;\n              break;\n            default:\n              neuron_2D_init ();\n              parallel_fractal = parallel_fractal_neuron_2D_diagonal;\n              max_d = 2;\n            }\n        }\n    }\n  else\n    {\n      if (fractal_3D)\n        {\n          switch (fractal_type)\n            {\n            case FRACTAL_TYPE_TREE:\n              tree_3D_init ();\n              parallel_fractal = parallel_fractal_tree_3D;\n              max_d = 1;\n              break;\n            case FRACTAL_TYPE_FOREST:\n              parallel_fractal = parallel_fractal_forest_3D;\n              max_d = 1;\n              break;\n            default:\n              neuron_3D_init ();\n              parallel_fractal = parallel_fractal_neuron_3D;\n              max_d = 2;\n            }\n        }\n      else\n        {\n          switch (fractal_type)\n            {\n            case FRACTAL_TYPE_TREE:\n              tree_2D_init ();\n              parallel_fractal = parallel_fractal_tree_2D;\n              max_d = 1;\n              break;\n            case FRACTAL_TYPE_FOREST:\n              parallel_fractal = parallel_fractal_forest_2D;\n              max_d = 1;\n              break;\n            default:\n              neuron_2D_init ();\n              parallel_fractal = parallel_fractal_neuron_2D;\n              max_d = 2;\n            }\n        }\n    }\n}\n\n/**\n * Function to get an unsigned integer number of a XML node property.\n *\n * \\return Unsigned integer number value.\n */\nstatic unsigned int\nxml_node_get_uint_with_default (xmlNode * node, ///< XML node.\n                                const xmlChar * prop,   ///< XML property.\n                                unsigned int default_value,     ///< Default value.\n                                int *error_code)        ///< Error code.\n{\n  unsigned int i = 0;\n  xmlChar *buffer;\n  buffer = xmlGetProp (node, prop);\n  *error_code = 0;\n  if (!buffer)\n    return default_value;\n  else\n    {\n      if (sscanf ((char *) buffer, \"%u\", &i) != 1)\n        *error_code = 1;\n      xmlFree (buffer);\n    }\n  return i;\n}\n\n/**\n * Function to get an unsigned long integer number of a XML node property.\n *\n * \\return Unsigned long integer number value.\n */\nstatic unsigned long\nxml_node_get_ulong_with_default (xmlNode * node,        ///< XML node.\n                                 const xmlChar * prop,  ///< XML property.\n                                 unsigned long default_value,\n                                 ///< Default value.\n                                 int *error_code)       ///< Error code.\n{\n  unsigned long i = 0l;\n  xmlChar *buffer;\n  buffer = xmlGetProp (node, prop);\n  *error_code = 0;\n  if (!buffer)\n    return default_value;\n  else\n    {\n      if (sscanf ((char *) buffer, \"%lu\", &i) != 1)\n        *error_code = 1;\n      xmlFree (buffer);\n    }\n  return i;\n}\n\n/**\n * Function to open the fractal data on a file.\n *\n * \\return 1 on success, 0 on error.\n */\nint\nfractal_input (char *filename)  ///< File name.\n{\n  xmlDoc *doc;\n  xmlNode *node;\n  xmlChar *buffer;\n  const char *error_message;\n  int error_code;\n  buffer = NULL;\n  xmlKeepBlanksDefault (0);\n  doc = xmlParseFile ((const char *) filename);\n  if (!doc)\n    {\n      error_message = _(\"Unable to parse the input file\");\n      goto exit_on_error;\n    }\n  node = xmlDocGetRootElement (doc);\n  if (!node || xmlStrcmp (node->name, XML_FRACTAL))\n    {\n      error_message = _(\"Bad XML root node\");\n      goto exit_on_error;\n    }\n  width = xml_node_get_uint_with_default (node, XML_WIDTH, WIDTH, &error_code);\n  if (error_code)\n    {\n      error_message = _(\"Bad width\");\n      goto exit_on_error;\n    }\n  height\n    = xml_node_get_uint_with_default (node, XML_HEIGHT, HEIGHT, &error_code);\n  if (error_code)\n    {\n      error_message = _(\"Bad height\");\n      goto exit_on_error;\n    }\n  length\n    = xml_node_get_uint_with_default (node, XML_LENGTH, LENGTH, &error_code);\n  if (error_code)\n    {\n      error_message = _(\"Bad length\");\n      goto exit_on_error;\n    }\n  random_seed\n    = xml_node_get_ulong_with_default (node, XML_SEED, SEED, &error_code);\n  if (error_code)\n    {\n      error_message = _(\"Bad random seed\");\n      goto exit_on_error;\n    }\n  nthreads\n    = xml_node_get_uint_with_default (node, XML_THREADS, threads_number (),\n                                      &error_code);\n  if (!nthreads || error_code)\n    {\n      error_message = _(\"Bad threads number\");\n      goto exit_on_error;\n    }\n  buffer = xmlGetProp (node, XML_DIAGONAL);\n  if (!buffer || !xmlStrcmp (buffer, XML_NO))\n    fractal_diagonal = 0;\n  else if (!xmlStrcmp (buffer, XML_YES))\n    fractal_diagonal = 1;\n  else\n    {\n      error_message = _(\"Bad diagonal movement\");\n      goto exit_on_error;\n    }\n  xmlFree (buffer);\n  buffer = xmlGetProp (node, XML_3D);\n  if (!buffer || !xmlStrcmp (buffer, XML_NO))\n    fractal_3D = 0;\n  else if (!xmlStrcmp (buffer, XML_YES))\n    fractal_3D = 1;\n  else\n    {\n      error_message = _(\"Bad 3D\");\n      goto exit_on_error;\n    }\n  xmlFree (buffer);\n  buffer = xmlGetProp (node, XML_ANIMATE);\n  if (!buffer || !xmlStrcmp (buffer, XML_YES))\n    animating = 1;\n  else if (!xmlStrcmp (buffer, XML_NO))\n    animating = 0;\n  else\n    {\n      error_message = _(\"Bad animation\");\n      goto exit_on_error;\n    }\n  xmlFree (buffer);\n  buffer = xmlGetProp (node, XML_TYPE);\n  if (!buffer || !xmlStrcmp (buffer, XML_TREE))\n    fractal_type = FRACTAL_TYPE_TREE;\n  else if (!xmlStrcmp (buffer, XML_FOREST))\n    fractal_type = FRACTAL_TYPE_FOREST;\n  else if (!xmlStrcmp (buffer, XML_NEURON))\n    fractal_type = FRACTAL_TYPE_NEURON;\n  else\n    {\n      error_message = _(\"Unknown fractal type\");\n      goto exit_on_error;\n    }\n  xmlFree (buffer);\n  buffer = xmlGetProp (node, XML_RANDOM_SEED);\n  if (!buffer || !xmlStrcmp (buffer, XML_CLOCK))\n    random_seed_type = RANDOM_SEED_TYPE_CLOCK;\n  else if (!xmlStrcmp (buffer, XML_DEFAULT))\n    random_seed_type = RANDOM_SEED_TYPE_DEFAULT;\n  else if (!xmlStrcmp (buffer, XML_FIXED))\n    random_seed_type = RANDOM_SEED_TYPE_FIXED;\n  else\n    {\n      error_message = _(\"Unknown random seed type\");\n      goto exit_on_error;\n    }\n  xmlFree (buffer);\n  buffer = xmlGetProp (node, XML_RANDOM_TYPE);\n  if (!buffer || !xmlStrcmp (buffer, XML_MT19937))\n    random_algorithm = 0;\n  else if (!xmlStrcmp (buffer, XML_RANLXS0))\n    random_algorithm = 1;\n  else if (!xmlStrcmp (buffer, XML_RANLXS1))\n    random_algorithm = 2;\n  else if (!xmlStrcmp (buffer, XML_RANLXS2))\n    random_algorithm = 3;\n  else if (!xmlStrcmp (buffer, XML_RANLXD1))\n    random_algorithm = 4;\n  else if (!xmlStrcmp (buffer, XML_RANLXD2))\n    random_algorithm = 5;\n  else if (!xmlStrcmp (buffer, XML_RANLUX))\n    random_algorithm = 6;\n  else if (!xmlStrcmp (buffer, XML_RANLUX389))\n    random_algorithm = 7;\n  else if (!xmlStrcmp (buffer, XML_CMRG))\n    random_algorithm = 8;\n  else if (!xmlStrcmp (buffer, XML_MRG))\n    random_algorithm = 9;\n  else if (!xmlStrcmp (buffer, XML_TAUS2))\n    random_algorithm = 10;\n  else if (!xmlStrcmp (buffer, XML_GFSR4))\n    random_algorithm = 11;\n  else\n    {\n      error_message = _(\"Unknown random algorithm\");\n      goto exit_on_error;\n    }\n  xmlFree (buffer);\n  xmlFreeDoc (doc);\n  return 1;\n\nexit_on_error:\n  show_error (error_message);\n  xmlFree (buffer);\n  xmlFreeDoc (doc);\n  return 0;\n}\n\n/**\n * Function with the main bucle to draw the fractal.\n */\nvoid\nfractal ()\n{\n  const gsl_rng_type *random_type[N_RANDOM_TYPES] = {\n    gsl_rng_mt19937,\n    gsl_rng_ranlxs0,\n    gsl_rng_ranlxs1,\n    gsl_rng_ranlxs2,\n    gsl_rng_ranlxd1,\n    gsl_rng_ranlxd2,\n    gsl_rng_ranlux,\n    gsl_rng_ranlux389,\n    gsl_rng_cmrg,\n    gsl_rng_mrg,\n    gsl_rng_taus2,\n    gsl_rng_gfsr4\n  };\n  FILE *file;\n  unsigned int i;\n\n// PARALLELIZING DATA\n  gsl_rng *rng[nthreads];\n  GThread *thread[nthreads];\n\n  t0 = time (NULL);\n#if DEBUG\n  printf (\"t0=%lu\\n\", t0);\n#endif\n\n#if DEBUG\n  printf (\"Opening log file\\n\");\n#endif\n  file = fopen (\"log\", \"w\");\n\n#if DEBUG\n  printf (\"Opening pseudo-random generators\\n\");\n#endif\n  for (i = 0; i < nthreads; ++i)\n    {\n      rng[i] = gsl_rng_alloc (random_type[random_algorithm]);\n      switch (random_seed_type)\n        {\n        case RANDOM_SEED_TYPE_DEFAULT:\n          break;\n        case RANDOM_SEED_TYPE_CLOCK:\n          gsl_rng_set (rng[i], (unsigned long) clock () + i);\n          break;\n        default:\n          gsl_rng_set (rng[i], random_seed + i);\n        }\n    }\n\n// END\n\n  breaking = 0;\n  simulating = 1;\n\n#if DEBUG\n  printf (\"Updating simulator dialog\\n\");\n#endif\n  dialog_simulator_update ();\n\n#if DEBUG\n  printf (\"Starting medium\\n\");\n#endif\n  medium_start ();\n\n#if DEBUG\n  printf (\"Main bucle\\n\");\n#endif\n  do\n    {\n#if DEBUG\n      printf (\"Calculating fractal\\n\");\n#endif\n// PARALLELIZING CALLS\n      for (i = 0; i < nthreads; ++i)\n        thread[i] = g_thread_new (NULL, (void (*)) parallel_fractal, rng[i]);\n      for (i = 0; i < nthreads; ++i)\n        g_thread_join (thread[i]);\n// END\n\n#if DEBUG\n      printf (\"Updating simulator dialog\\n\");\n#endif\n      dialog_simulator_progress ();\n\n// DISPLAYING DRAW\n#if DEBUG\n      printf (\"Redisplaying draw\\n\");\n#endif\n      draw ();\n// END\n\n#if DEBUG\n      printf (\"Saving log data\\n\");\n#endif\n      fprintf (file, \"%d %d\\n\", max_d, npoints);\n    }\n  while (!breaking);\n\n#if DEBUG\n  printf (\"Closing log file\\n\");\n#endif\n  fclose (file);\n\n#if DEBUG\n  printf (\"Updating simulator dialog\\n\");\n#endif\n  breaking = simulating = 0;\n  dialog_simulator_update ();\n\n#if DEBUG\n  printf (\"Freeing threads\\n\");\n#endif\n  for (i = 0; i < nthreads; ++i)\n    gsl_rng_free (rng[i]);\n  g_slice_free1 (medium_bytes, medium);\n}\n", "meta": {"hexsha": "f68511d16a91a5adced31ec3afe7fbb5fbe6e12c", "size": 40353, "ext": "c", "lang": "C", "max_stars_repo_path": "3.4.15/fractal.c", "max_stars_repo_name": "jburguete/fractal", "max_stars_repo_head_hexsha": "95d711dcb7b385556fb77794bc01737b21e99774", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "3.4.15/fractal.c", "max_issues_repo_name": "jburguete/fractal", "max_issues_repo_head_hexsha": "95d711dcb7b385556fb77794bc01737b21e99774", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3.4.15/fractal.c", "max_forks_repo_name": "jburguete/fractal", "max_forks_repo_head_hexsha": "95d711dcb7b385556fb77794bc01737b21e99774", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9058056872, "max_line_length": 83, "alphanum_fraction": 0.5638490323, "num_tokens": 12068, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046348141882, "lm_q2_score": 0.03358950444082818, "lm_q1q2_score": 0.014191721307361663}}
{"text": "/* monte/gsl_monte_vegas.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Michael Booth\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* header for the gsl \"vegas\" routines.  Mike Booth, May 1998 */\n\n#ifndef __GSL_MONTE_VEGAS_H__\n#define __GSL_MONTE_VEGAS_H__\n\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_monte.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\nenum {GSL_VEGAS_MODE_IMPORTANCE = 1, \n      GSL_VEGAS_MODE_IMPORTANCE_ONLY = 0, \n      GSL_VEGAS_MODE_STRATIFIED = -1};\n\ntypedef struct {\n  /* grid */\n  size_t dim;\n  size_t bins_max;\n  unsigned int bins;\n  unsigned int boxes; /* these are both counted along the axes */\n  double * xi;\n  double * xin;\n  double * delx;\n  double * weight;\n  double vol;\n\n  double * x;\n  int * bin;\n  int * box;\n  \n  /* distribution */\n  double * d;\n\n  /* control variables */\n  double alpha;\n  int mode;\n  int verbose;\n  unsigned int iterations;\n  int stage;\n\n  /* scratch variables preserved between calls to vegas1/2/3  */\n  double jac;\n  double wtd_int_sum; \n  double sum_wgts;\n  double chi_sum;\n  double chisq;\n\n  double result;\n  double sigma;\n\n  unsigned int it_start;\n  unsigned int it_num;\n  unsigned int samples;\n  unsigned int calls_per_box;\n\n  FILE * ostream;\n\n} gsl_monte_vegas_state;\n\nint gsl_monte_vegas_integrate(gsl_monte_function * f, \n                              double xl[], double xu[], \n                              size_t dim, size_t calls,\n                              gsl_rng * r,\n                              gsl_monte_vegas_state *state,\n                              double* result, double* abserr);\n\ngsl_monte_vegas_state* gsl_monte_vegas_alloc(size_t dim);\n\nint gsl_monte_vegas_init(gsl_monte_vegas_state* state);\n\nvoid gsl_monte_vegas_free (gsl_monte_vegas_state* state);\n\n__END_DECLS\n\n#endif /* __GSL_MONTE_VEGAS_H__ */\n\n", "meta": {"hexsha": "b328307e1e879ea026548bd82d77fc9852a8887a", "size": 2654, "ext": "h", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/monte/gsl_monte_vegas.h", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/monte/gsl_monte_vegas.h", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/monte/gsl_monte_vegas.h", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 25.0377358491, "max_line_length": 81, "alphanum_fraction": 0.6868877167, "num_tokens": 699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3738758227716966, "lm_q2_score": 0.03789242690123016, "lm_q1q2_score": 0.014167062284513797}}
{"text": "/* Output the current topic and POV assignments in text in text form\n   to stdout, optionally iteratively maximizing the assignments first\n   (to find a high-probability assignments). Even if performing\n   maximization, the current assignments should be post-burn-in for\n   best results. */\n\n#include <assert.h>\n#include <gsl/gsl_rng.h>\n#include <inttypes.h>\n#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n\n#include \"index.h\"\n#include \"parse_mmaps.h\"\n#include \"probability.h\"\n#include \"sample.h\"\n\nint main(int argc, char **argv) {\n  if (argc != 4) {\n    printf(\"Usage: %s mmap_directory maximization_iterations threads\\n\",\n           argv[0]);\n    exit(1);\n  }\n  int maximization_iterations = atoi(argv[2]);\n  int num_threads = atoi(argv[3]);\n  struct mmap_info mmap_info = open_mmaps_readonly(argv[1]);\n  int64_t count_revisions;\n  struct revision_assignment* revision_assignments;\n  get_revision_assignment_array(&mmap_info, &count_revisions, &revision_assignments);\n\n  if (maximization_iterations > 0) {\n    struct sample_threads sample_threads;\n    initialize_threads(&sample_threads, num_threads, &mmap_info);\n    for (int i = 0; i < maximization_iterations; ++i) {\n      resample_maximize(&sample_threads);\n    }\n    destroy_threads(&sample_threads);\n  }\n  for (int64_t revision_num = 0; revision_num < count_revisions; ++revision_num) {\n    if (revision_assignments[revision_num].pov < 0\n\t|| revision_assignments[revision_num].topic < 0) {\n      continue;\n    }\n    printf(\"%\" PRId64 \" %d %d\\n\", \n\t   revision_num, \n\t   revision_assignments[revision_num].topic, \n\t   revision_assignments[revision_num].pov);\n  }\n  close_mmaps(mmap_info);\n}\n", "meta": {"hexsha": "3dbb9e17a4a712d6e24a9119daa9168aead08f81", "size": 1695, "ext": "c", "lang": "C", "max_stars_repo_path": "src/readout.c", "max_stars_repo_name": "allenlavoie/topic-pov", "max_stars_repo_head_hexsha": "c727087d0ac2d440d4e70fbea0c3342c3c734073", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T17:04:56.000Z", "max_stars_repo_stars_event_max_datetime": "2015-01-05T17:04:56.000Z", "max_issues_repo_path": "src/readout.c", "max_issues_repo_name": "allenlavoie/topic-pov", "max_issues_repo_head_hexsha": "c727087d0ac2d440d4e70fbea0c3342c3c734073", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/readout.c", "max_forks_repo_name": "allenlavoie/topic-pov", "max_forks_repo_head_hexsha": "c727087d0ac2d440d4e70fbea0c3342c3c734073", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3888888889, "max_line_length": 85, "alphanum_fraction": 0.7174041298, "num_tokens": 433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.030214583901835006, "lm_q1q2_score": 0.01416431372059245}}
{"text": "/*! \\file allvars.h\n *  \\brief declares global variables and structures.\n *\n *  This file declares all global variables and structures. Further variables should be added here, and declared as\n *  \\e \\b extern. The actual existence of these variables is provided by the file \\ref allvars.cxx. To produce\n *  \\ref allvars.cxx from \\ref allvars.h, do the following:\n *\n *     \\arg Erase all \\#define's, typedef's, and enum's\n *     \\arg add \\#include \"allvars.h\", delete the \\#ifndef ALLVARS_H conditional\n *     \\arg delete all keywords 'extern'\n *     \\arg delete all struct definitions enclosed in {...}, e.g.\n *        \"extern struct global_data_all_processes {....} All;\"\n *        becomes \"struct global_data_all_processes All;\"\n */\n\n#ifndef ALLVARS_H\n#define ALLVARS_H\n#include <cstdio>\n#include <cstdlib>\n#include <iostream>\n#include <fstream>\n#include <cmath>\n#include <string>\n#include <getopt.h>\n#include <sys/stat.h>\n#include <sys/timeb.h>\n\n//gsl stuff\n#include <gsl/gsl_heapsort.h>\n\n//nbody code\n#include <NBody.h>\n#include <NBodyMath.h>\n#include <KDTree.h>\n\n#ifdef USEOPENMP\n#include <omp.h>\n#endif\n\n#ifdef USEMPI\n#include <mpi.h>\n///Includes external global variables used for MPI version of code\n#include \"mpivar.h\"\n#endif\n\n#include \"../../src/gadgetitems.h\"\n#include \"../../src/tipsy_structs.h\"\n\n//for morphological classifications (where tidal tails, or completely disrupted)\n#define NUMMORPHCLASS 3;\n#define QTIDAL 0.60\n#define STIDAL 0.40\n#define QLIMTIDAL 0.30\n#define SLIMTIDAL 0.25\n#define VFTIDAL 0.85\n#define VFLIMTIDAL 0.50\n#define V2TIDAL 0.6\n#define V3TIDAL 0.4\n#define V2LIMTIDAL 0.35\n#define V3LIMTIDAL 0.30\n\n#define ETIDAL 0.90\n#define ELIMTIDAL 0.50\n\n//number of bands in which to calculate magnitude\n#define NBANDS 9\n\n///define the particle types\n//@{\n#define NPARTTYPES 5\n#define ALLTYPE 4\n#define GASTYPE 0\n#define DMTYPE 1\n#define STARTYPE 2\n#define BHTYPE 3\n//@}\n\n///\\todo need to alter how stats are stored if one can update the number of quantiles stored\n///the number of values that is used to characterize a bulk distribution\n///where idea is 0=mean,1=sd,2-4=quantiles of 0.16,0.5,0.84\n#define NDISTRIB 5\n///max number of quantiles\n#define MAXNQUANTS 11\n\n///max number of radial bins\n#define NRAD 1000\n\n\n/// Structures and external variables\n\n///for stars,gas, define lower limits for Z and sfr\n#define MINGASZ 1e-7\n#define MINSTARZ 1e-7\n#define MINSFR 1e-3\n\n///define sphi io block points for gadget\n//@{\n///self energy  \n#define sphioblock_u 0\n///density\n#define sphioblock_d 1\n#ifdef SPHCOOLING\n///mean molecular weight\n#define sphioblock_mmw 2\n///neutral hydrogen abundance\n#define sphioblock_nha 3\n#endif\n///smoothing lengths\n#define sphioblock_h\n//@}\n\n///define different reference frames\n//@{\n///cm ref\n#define ICMFRAME 1\n///particle with largest potential\n#define IPOTFRAME 2\n///most bound particle based in input data\n#define IMBFRAME 3\n//@}\n\n///define omp number of elements threshold\n#define ompunbindnum 1000\n#define omppropnum 50000\n\n///minimum number of particles for properties to be calculated\n#define MINNPROP 10 \n///minimum number of particles for a profile to be calculated\n#define MINNPROFILE 100\n///minimum mass fraction of candidate structure for enclosed quantities to be useful\n#define MINMASSFRAC 0.05\n\n///some useful constants for gas\n//@{\n///mass of helium relative to hydrogen\n#define M_HetoM_H 4.0026\n//@}\n\nusing namespace std;\nusing namespace Math;\nusing namespace NBody;\n\n///for potential calculation\nstruct PotInfo\n{\n    ///bucket size for tree calculation\n    int BucketSize;\n    ///for tree potential calculation;\n    Double_t TreeThetaOpen;\n    ///gravitational softening (here simple plummer)\n    Double_t eps;\n    ///\\todo When calculating the thermal internal energy of gas particles\n    ///I should probably include some temperature floors and ceilings\n    ///and perhaps some sound speed constrains. But I should produce\n    ///properties of the baryonic material for all, gravitationally self-bound and grav+therm bound\n\n    PotInfo(){\n        BucketSize=8;\n        TreeThetaOpen=0.7;\n        eps=0.01;\n    }\n};\n\n///Options structure\nstruct Options\n{\n    ///filenames\n    //@{\n    ///input particle data and output name\n    char *fname,*outname;\n    ///halo catalog base name\n    char *halocatname;\n    ///optional config file name\n    char *configname;\n    ///optional stellar synthesis model file name\n    char *magname;\n    //@}\n    ///number of files per particle data snapshot, if zero then tipsy file\n    int nfiles;\n    ///number of files per halo catalog\n    int nfileshalocat;\n    ///number of sph blocks in gadget file\n    int sphnio;\n    ///defining units and cosmology\n    //@{\n    ///length,m,v,grav units pressure unit, temperature\n    Double_t L, M, V, G, PUnit, TUnit;\n    ///scalbodydata/utils/haloanalcode/e factor, Hubunit, h and cosmology\n    Double_t a,H,h, Omega_m, Omega_Lambda,rhoc;\n    ///softening length and period (comove)\n    Double_t eps, p;\n    ///background density and virial level\n    Double_t rhobg, virlevel;\n    int comove;\n    ///for gas, mass fraction of hydrogen\n    Double_t Xh;\n    ///for gas, boltzmann constant\n    Double_t Boltzmann;\n    ///for gas, number of hydrogen atoms per sph particle\n    Double_t N_H;\n    ///for gas, correction for helium to mass of sph particle /mh ie: Number of particles = M_p / (M_H*Xh+M_He*(1-Xh)) or even M_H*Xh+M_He*(1-Xh)*Y_Li+M_Li*(1-Xh)*(1-Y_Li) ...\n    Double_t N_He_corr;\n    ///for gas, relation of specific internal energy to Temperature (u=3/2*k_B*(N_H*(Xh+(1-Xh)*N_He)*T\n    Double_t utoT;\n    ///for gas, temperature threshold when calculating X-ray based spectroscopic-like temperature)\n    Double_t Tempthreshold;\n    ///\\todo may want some specific stuff for stars too\n    //@}\n\n    ///store number of particles\n    Int_t npart[NPARTTYPES];\n\n    ///structure that contains variables for potentialcalc\n    PotInfo pinfo;\n    Double_t error;\n\n    ///quantile points for characterization of distribution\n    int nquants;\n    Double_t quants[MAXNQUANTS];\n\n    ///minimum number a halo has to have to be analyzed\n    Int_t minnum;\n    ///Kinetic/Potential Energy ratio\n    Double_t TVratio;\n    ///number of mpi files that were written in parallel that must be read for group_catalog files\n    int mpinum;\n\n    ///for calculaion of CM\n    Double_t cmfrac, cmadjustfac;\n    PotInfo uinfo;\n\n    ///for calculating kinetic energy to a reference frame\n    int reframe;\n\n    ///if no mass is stored\n    Double_t MassValue;\n\n    ///if zoom simulations, store effective resolution\n    long int Neff;\n\n    ///for verbose output\n    int verbose;\n\n    ///store whether potential has been already calculated as object has been moved to particle with deepest potential well. \n    int ipotcalc;\n\n    ///used to calculate kinetic reference frame about particle at bottom of potential well\n    Int_t Nbref;\n    Double_t fracbref;\n\n    ///input STF/VELOCIraptor format flags\n    //@{\n    int iseparatefiles,ibinaryin;\n    //@}\n\n    ///output format\n    int ibinaryout;\n\n    Options()\n    {\n        fname=outname=halocatname=NULL;\n        nfiles=1;\n        sphnio=2;\n        nfileshalocat=1;\n\n        L = 1.0;\n        M = 1.0;\n        V = 1.0;\n        PUnit=5.588e-14;//(assumes T in kelvin) makes pressure into ergs/cm^3 assuming standard gadget units (this is boltzmann's constant / proton mass *Massunit_g/(Lengthunit_cm)^3\n        TUnit=1.0;\n        MassValue=1.0;\n\n        p = 0.0;\n        a = 1.0;\n        H = 0.1;\n        h = 1.0;\n        Omega_m = 1.0;\n        Omega_Lambda = 0.0;\n        rhobg = 1.0;\n        virlevel = 50.;\n        comove=0;\n        G = 43.01;//for G in units of (km/s)^2 Mpc/1e10 Msun\n        rhoc=27.753;//for same units as above, of course missing factors of h^2\n        G = 43021.1349;//for G in units of (km/s)^2 kpc/1e10 Msun\n        rhoc=2.7753e-8;\n\n        Xh=0.76;\n        Boltzmann=log(6.94107285)-70.0*log(10.0); //ln of boltzmann in units of K^(-1) (km/s)^2 (1e10 Msun)\n        N_H=log(1.1892)+67.0*log(10.0); //number of hydrogen atoms per 10^10 Msun\n        N_He_corr=-log(Xh+M_HetoM_H*(1.0-Xh));\n        utoT=log(1.5)+Boltzmann+N_H+N_He_corr; \n        Tempthreshold=7.0*log(10.0);\n\n        error=1e-3;\n\n        nquants=3;\n        quants[0]=0.16;quants[1]=0.5;quants[2]=0.84;\n        for (int i=0;i<NPARTTYPES;i++) npart[i]=0;\n\n        minnum=20;\n        TVratio=-1.0;\n        mpinum=0;\n\n        cmfrac=0.1;\n        cmadjustfac=0.7;\n        Neff=-1;\n\n        reframe=IPOTFRAME;\n        verbose=0;\n\n        ipotcalc=1;\n        Nbref=10;\n        fracbref=0.05;\n\n        iseparatefiles=0;\n        ibinaryin=0;\n        ibinaryout=0;\n\n    }\n};\n\n///Radial profile data in spherical shells\nstruct RadPropData\n{\n    ///To store radial profiles\n    //@{\n    Int_t nbins;\n    int ptype;\n    Double_t *numinbin;\n    Double_t *radval;\n    Double_t *Menc;\n    Coordinate *velenc;\n    Matrix *sigmavenc;\n    Coordinate *Jenc;\n    Double_t *qenc;\n    Double_t *senc;\n    Matrix *eigvecenc;\n    ///primarily for sph particles\n    Double_t *Den;\n    ///gas/star particle info\n    Double_t *Tempenc;\n    Double_t *Tdispenc;\n    Double_t *Temenc;\n    Double_t *Tslenc;\n#ifdef RADIATIVE\n    Double_t *Zmetenc;\n    Double_t *Tageenc;\n#endif\n//@}\n    RadPropData(){\n        //for (int i=0;i<NRAD;i++) {numinbin[i]=radval[i]=Menc[i]=0.;Jenc[i]=Coordinate(0,0,0);velenc[i]=Coordinate(0,0,0);qenc[i]=senc[i]=1.0;}\n        ptype=DMTYPE;\n        numinbin=NULL;radval=NULL;Menc=NULL;velenc=NULL;sigmavenc=NULL;Jenc=NULL;qenc=NULL;senc=NULL;eigvecenc=NULL;\n        Den=NULL;Tempenc=NULL;Tdispenc=NULL;Temenc=NULL;Tslenc=NULL;\n#ifdef RADIATIVE\n        Zmetenc=NULL;\n        Tageenc=NULL;\n#endif\n    }\n    void SetBins(int N) {\n        nbins=N;\n        if(numinbin!=NULL) delete[] numinbin;numinbin=new Double_t[nbins];\n        if(radval!=NULL) delete[] radval;radval=new Double_t[nbins];\n        if(Menc!=NULL) delete[] Menc;Menc=new Double_t[nbins];\n        if(velenc!=NULL) delete[] velenc;velenc=new Coordinate[nbins];\n        if(sigmavenc!=NULL) delete[] sigmavenc;sigmavenc=new Matrix[nbins];\n        if(Jenc!=NULL) delete[] Jenc;Jenc=new Coordinate[nbins];\n        if(qenc!=NULL) delete[] qenc;qenc=new Double_t[nbins];\n        if(senc!=NULL) delete[] senc;senc=new Double_t[nbins];\n        if(eigvecenc!=NULL) delete[] eigvecenc;eigvecenc=new Matrix[nbins];\n        if(Tempenc!=NULL) delete[] Tempenc;Tempenc=new Double_t[nbins];\n        if(Tdispenc!=NULL) delete[] Tdispenc;Tdispenc=new Double_t[nbins];\n        if(Temenc!=NULL) delete[] Temenc;Temenc=new Double_t[nbins];\n        if(Tslenc!=NULL) delete[] Tslenc;Tslenc=new Double_t[nbins];\n        if(Den!=NULL) delete[] Den;Den=new Double_t[nbins];\n#ifdef RADIATIVE\n        if(Zmetenc!=NULL) delete[] Zmetenc;Zmetenc=new Double_t[nbins];\n        if(Tageenc!=NULL) delete[] Tageenc;Tageenc=new Double_t[nbins];\n#endif\n        for (int i=0;i<nbins;i++) {numinbin[i]=radval[i]=Menc[i]=0;Jenc[i]=Coordinate(0,0,0);velenc[i]=Coordinate(0,0,0);qenc[i]=senc[i]=1.0;}\n        for (int i=0;i<nbins;i++) {Tempenc[i]=Tdispenc[i]=Den[i]=Temenc[i]=Tslenc[i]=0.;}\n    }\n};\n\n///Cylindrical profile data\nstruct CylPropData\n{\n    ///reference axis of cylinder\n    Coordinate zref;\n    ///To store cylindrical profiles \n    //@{\n    Int_t nbins;\n    Double_t *numinbin;\n    Double_t *radval;\n    Double_t *Menc;\n    Coordinate *Jenc;\n    Coordinate *velenc;\n    Matrix *sigmavenc;\n    Double_t *zmean;\n    Double_t *Rmean;\n    Double_t *zdisp;\n    Double_t *Rdisp;\n    Double_t *qenc;\n    Double_t *senc;\n    Matrix *eigvecenc;\n    ///primarily for sph particles\n    Double_t *Den;\n    ///gas/star particle info\n    Double_t *Tempenc;\n    Double_t *Tdispenc;\n    Double_t *Temenc;\n    Double_t *Tslenc;\n#ifdef RADIATIVE\n    Double_t *Zmetenc;\n    Double_t *Tageenc;\n#endif\n    //@}\n    CylPropData(){\n        numinbin=NULL;radval=NULL;Menc=NULL;velenc=NULL;sigmavenc=NULL;Jenc=NULL;zmean=NULL;Rmean=NULL;zdisp=NULL;Rdisp=NULL;qenc=NULL;senc=NULL;eigvecenc=NULL;\n        Den=NULL;Tempenc=NULL;Tdispenc=NULL;Temenc=NULL;Tslenc=NULL;\n#ifdef RADIATIVE\n        Zmetenc=NULL;\n        Tageenc=NULL;\n#endif\n    }\n    void SetBins(int N) {\n        nbins=N;\n        if(numinbin!=NULL) delete[] numinbin;numinbin=new Double_t[nbins];\n        if(radval!=NULL) delete[] radval;radval=new Double_t[nbins];\n        if(Menc!=NULL) delete[] Menc;Menc=new Double_t[nbins];\n        if(velenc!=NULL) delete[] velenc;velenc=new Coordinate[nbins];\n        if(sigmavenc!=NULL) delete[] sigmavenc;sigmavenc=new Matrix[nbins];\n        if(Jenc!=NULL) delete[] Jenc;Jenc=new Coordinate[nbins];\n        if(zmean!=NULL) delete[] zmean;zmean=new Double_t[nbins];\n        if(Rmean!=NULL) delete[] Rmean;Rmean=new Double_t[nbins];\n        if(zdisp!=NULL) delete[] zdisp;zdisp=new Double_t[nbins];\n        if(Rdisp!=NULL) delete[] Rdisp;Rdisp=new Double_t[nbins];\n        if(qenc!=NULL) delete[] qenc;qenc=new Double_t[nbins];\n        if(senc!=NULL) delete[] senc;senc=new Double_t[nbins];\n        if(eigvecenc!=NULL) delete[] eigvecenc;eigvecenc=new Matrix[nbins];\n        if(Tempenc!=NULL) delete[] Tempenc;Tempenc=new Double_t[nbins];\n        if(Tdispenc!=NULL) delete[] Tdispenc;Tdispenc=new Double_t[nbins];\n        if(Temenc!=NULL) delete[] Temenc;Temenc=new Double_t[nbins];\n        if(Tslenc!=NULL) delete[] Tslenc;Tslenc=new Double_t[nbins];\n        if(Den!=NULL) delete[] Den;Den=new Double_t[nbins];\n#ifdef RADIATIVE\n        if(Zmetenc!=NULL) delete[] Zmetenc;Zmetenc=new Double_t[nbins];\n        if(Tageenc!=NULL) delete[] Tageenc;Tageenc=new Double_t[nbins];\n#endif\n        for (int i=0;i<nbins;i++) {numinbin[i]=radval[i]=Menc[i]=0.;Jenc[i]=velenc[i]=Coordinate(0,0,0);qenc[i]=senc[i]=1.0;zmean[i]=Rmean[i]=zdisp[i]=Rdisp[i]=0.;}\n        for (int i=0;i<nbins;i++) {Tempenc[i]=Tdispenc[i]=Den[i]=Temenc[i]=Tslenc[i]=0.;}\n    }\n};\n\n///Based on PropData in \\ref allvars.h of STF/VELOCIraptor\n///Here the data also stores the type of particles it corresponds to\nstruct PropData\n{\n    ///type of structure, dm, gas, star, etc\n    Int_t ptype;\n    ///number of particles\n    Int_t num;\n    ///centre of mass\n    Coordinate gcm, gcmvel;\n    ///Position of most bound particle\n    Coordinate gpos, gvel;\n    ///physical properties regarding mass, size\n    Double_t gmass,gsize,gMvir,gRvir,gRmbp,gmaxvel,gRmaxvel,gMmaxvel;\n    ///physical properties for shape/mass distribution\n    Double_t gq,gs;\n    Matrix geigvec;\n    ///physical properties for velocity\n    Double_t gsigma_v;\n    Matrix gveldisp;\n    ///physical properties for dynamical state\n    Double_t Efrac,Pot,T;\n    ///physical properties for dynamical state for specific particle types\n    Double_t Efractyped[NPARTTYPES],Pottyped[NPARTTYPES],Ttyped[NPARTTYPES];\n    ///physical properties for angular momentum\n    Coordinate gJ;\n\n    ///metallicity, temperature, pressure,etc\n    Double_t Temp[NDISTRIB];\n#ifdef RADIATIVE\n    Double_t Zmet[NDISTRIB];\n    ///stellar age\n    Double_t Tage[NDISTRIB];\n    ///luminosity, which for gas which would probably be Infrared and radio bands\n    Double_t LUM[NBANDS];\n#endif\n\n    ///To store cylindrical profiles \n    RadPropData radprofile;\n    ///To store cylindrical profiles \n    CylPropData cylprofile;\n\n\n    PropData(){\n        num=0;\n        gmass=gsize=gRmaxvel=Efrac=Pot=T=gcm[0]=gcm[1]=gcm[2]=gcmvel[0]=gcmvel[1]=gcmvel[2]=0.;\n        gveldisp=Matrix(0.);\n        gq=gs=1.0;\n        gRmbp=0.0;\n\n        for (int i=0;i<NDISTRIB;i++)Temp[i]=0;\n#ifdef RADIATIVE\n        for (int i=0;i<NDISTRIB;i++)Zmet[i]=Tage[i]=0.;\n        for (int i=0;i<NBANDS;i++)LUM[i]=0;\n#endif\n    }\n};\n\n\n///used to store halo particle id data\nstruct HaloParticleData{\n    ///store the halo id\n    long unsigned haloID;\n    ///number of particles, eventually used to store bound number\n    long unsigned NumberofParticles;\n    ///number of particles of different types, eventually used to store bound number\n    Int_t NumofType[NPARTTYPES];\n    ///number of all particles\n    long unsigned AllNumberofParticles;\n    ///number of all particles of different types\n    Int_t AllNumofType[NPARTTYPES];\n\n    ///offset of halo's particle in list of all particles in structures\n    Int_t noffset;\n    ///array of particle ids\n    long unsigned *ParticleID;\n    HaloParticleData(long unsigned numinhalo=0){\n        AllNumberofParticles=NumberofParticles=numinhalo;\n        if (NumberofParticles>0) {\n            ParticleID=new long unsigned[NumberofParticles];\n        }\n        for (int i=0;i<NPARTTYPES;i++) AllNumofType[i]=NumofType[i]=0;\n    }\n    void Alloc(long unsigned ninhalos=0){\n        if (AllNumberofParticles>0){\n            delete[] ParticleID;\n        }\n        AllNumberofParticles=NumberofParticles=ninhalos;\n        if (AllNumberofParticles>0) {\n            ParticleID=new long unsigned[NumberofParticles];\n        }\n    }\n    ~HaloParticleData(){\n        if (NumberofParticles>0){\n            delete[] ParticleID;\n        }\n    }\n};\n\n///External types for tipsy\n//@{\n#define TGASTYPE 0;\n#define TDARKTYPE 1;\n#define TSTARTYPE 2;\n//@}\n\n///note that for grouped particles type is 10+TYPE.\n#define SUBSTRUCTTYPE 10;\n\n#endif\n\n", "meta": {"hexsha": "92a5622150d210fe155c95f4befb0209dd8d4f5c", "size": 17094, "ext": "h", "lang": "C", "max_stars_repo_path": "stf/analysis/baryons/allvars.h", "max_stars_repo_name": "broukema/VELOCIraptor-STF", "max_stars_repo_head_hexsha": "f18cb8bf088065f9361fc537d4e5858962499a21", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stf/analysis/baryons/allvars.h", "max_issues_repo_name": "broukema/VELOCIraptor-STF", "max_issues_repo_head_hexsha": "f18cb8bf088065f9361fc537d4e5858962499a21", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stf/analysis/baryons/allvars.h", "max_forks_repo_name": "broukema/VELOCIraptor-STF", "max_forks_repo_head_hexsha": "f18cb8bf088065f9361fc537d4e5858962499a21", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2014134276, "max_line_length": 182, "alphanum_fraction": 0.6663156663, "num_tokens": 5066, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3775406547908327, "lm_q2_score": 0.03732688640708807, "lm_q1q2_score": 0.014092417135435062}}
{"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/*                                                                           */\n/*                  This file is part of the program                         */\n/*          GCG --- Generic Column Generation                                */\n/*                  a Dantzig-Wolfe decomposition based extension            */\n/*                  of the branch-cut-and-price framework                    */\n/*         SCIP --- Solving Constraint Integer Programs                      */\n/*                                                                           */\n/* Copyright (C) 2010-2018 Operations Research, RWTH Aachen University       */\n/*                         Zuse Institute Berlin (ZIB)                       */\n/*                                                                           */\n/* This program is free software; you can redistribute it and/or             */\n/* modify it under the terms of the GNU Lesser General Public License        */\n/* as published by the Free Software Foundation; either version 3            */\n/* of the License, or (at your option) any later version.                    */\n/*                                                                           */\n/* This program is distributed in the hope that it will be useful,           */\n/* but WITHOUT ANY WARRANTY; without even the implied warranty of            */\n/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the             */\n/* GNU Lesser General Public License for more details.                       */\n/*                                                                           */\n/* You should have received a copy of the GNU Lesser General Public License  */\n/* along with this program; if not, write to the Free Software               */\n/* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.*/\n/*                                                                           */\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n/**@file   sepa_basis.c\n * @brief  basis separator\n * @author Jonas Witt\n */\n\n/*---+----1----+----2----+----3----+----4----+----5----+----6----+----7----+----8----+----9----+----0----+----1----+----2*/\n\n/*#define SCIP_DEBUG*/\n\n#include <assert.h>\n#include <stdio.h>\n#include <string.h>\n\n#include \"scip/scip.h\"\n#include \"scip/scipdefplugins.h\"\n#include \"sepa_basis.h\"\n#include \"sepa_master.h\"\n#include \"gcg.h\"\n#include \"relax_gcg.h\"\n#include \"pricer_gcg.h\"\n#include \"pub_gcgvar.h\"\n\n\n#ifdef GSL\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_permutation.h>\n#include <gsl/gsl_linalg.h>\n#endif\n\n#define SEPA_NAME              \"basis\"\n#define SEPA_DESC              \"separator calculates a basis of the orig problem to generate cuts, which cut off the master lp sol\"\n#define SEPA_PRIORITY                100\n#define SEPA_FREQ                     0\n#define SEPA_MAXBOUNDDIST           1.0\n#define SEPA_USESSUBSCIP           FALSE /**< does the separator use a secondary SCIP instance? */\n#define SEPA_DELAY                FALSE /**< should separation method be delayed, if other separators found cuts? */\n\n#define STARTMAXCUTS 50       /**< maximal cuts used at the beginning */\n#define MAXCUTSINC   20       /**< increase of allowed number of cuts */\n\n\n/*\n * Data structures\n */\n\n/** separator data */\nstruct SCIP_SepaData\n{\n   SCIP_ROW**            mastercuts;         /**< cuts in the master problem */\n   SCIP_ROW**            origcuts;           /**< cuts in the original problem */\n   int                   norigcuts;          /**< number of cuts in the original problem */\n   int                   nmastercuts;        /**< number of cuts in the master problem */\n   int                   maxcuts;            /**< maximal number of allowed cuts */\n   SCIP_ROW**            newcuts;            /**< new cuts to tighten original problem */\n   int                   nnewcuts;           /**< number of new cuts */\n   int                   maxnewcuts;         /**< maximal number of allowed new cuts */\n   SCIP_ROW*             objrow;             /**< row with obj coefficients */\n   SCIP_Bool             enable;             /**< parameter returns if basis separator is enabled */\n   SCIP_Bool             enableobj;          /**< parameter returns if objective constraint is enabled */\n   SCIP_Bool             enableobjround;     /**< parameter returns if rhs/lhs of objective constraint is rounded, when obj is int */\n   SCIP_Bool             enableppcuts;       /**< parameter returns if cuts generated during pricing are added to newconss array */\n   SCIP_Bool             enableppobjconss;   /**< parameter returns if objective constraint for each redcost of pp is enabled */\n   SCIP_Bool             enableppobjcg;      /**< parameter returns if objective constraint for each redcost of pp is enabled during pricing */\n   int                   separationsetting;  /**< parameter returns which parameter setting is used for separation */\n   SCIP_Bool             chgobj;             /**< parameter returns if basis is searched with different objective */\n   SCIP_Bool             chgobjallways;      /**< parameter returns if obj is not only changed in first iteration */\n   SCIP_Bool             genobjconvex;       /**< parameter returns if objconvex is generated dynamically */\n   SCIP_Bool             enableposslack;     /**< parameter returns if positive slack should influence the probing objective function */\n   SCIP_Bool             forcecuts;          /**< parameter returns if cuts are forced to enter the LP */\n   int                   posslackexp;        /**< parameter returns exponent of usage of positive slack */\n   SCIP_Bool             posslackexpgen;     /**< parameter returns if exponent should be automatically generated */\n   SCIP_Real             posslackexpgenfactor; /**< parameter returns factor for automatically generated exponent */\n   int                   iterations;         /**< parameter returns number of new rows adding iterations (rows just cut off probing lp sol) */\n   int                   mincuts;            /**< parameter returns number of minimum cuts needed to return *result = SCIP_Separated */\n   SCIP_Real             objconvex;          /**< parameter return convex combination factor */\n};\n\n/*\n * Local methods\n */\n\n/** allocates enough memory to hold more cuts */\nstatic\nSCIP_RETCODE ensureSizeCuts(\n   SCIP*                 scip,               /**< SCIP data structure */\n   SCIP_SEPADATA*        sepadata,           /**< separator data data structure */\n   int                   size                /**< new size of cut arrays */\n   )\n{\n   assert(scip != NULL);\n   assert(sepadata != NULL);\n   assert(sepadata->mastercuts != NULL);\n   assert(sepadata->origcuts != NULL);\n   assert(sepadata->norigcuts <= sepadata->maxcuts);\n   assert(sepadata->norigcuts >= 0);\n   assert(sepadata->nmastercuts <= sepadata->maxcuts);\n   assert(sepadata->nmastercuts >= 0);\n\n   if( sepadata->maxcuts < size )\n   {\n      while ( sepadata->maxcuts < size )\n      {\n         sepadata->maxcuts += MAXCUTSINC;\n      }\n      SCIP_CALL( SCIPreallocMemoryArray(scip, &(sepadata->mastercuts), sepadata->maxcuts) );\n      SCIP_CALL( SCIPreallocMemoryArray(scip, &(sepadata->origcuts), sepadata->maxcuts) );\n   }\n   assert(sepadata->maxcuts >= size);\n\n   return SCIP_OKAY;\n}\n\n/** allocates enough memory to hold more new cuts */\nstatic\nSCIP_RETCODE ensureSizeNewCuts(\n   SCIP*                 scip,               /**< SCIP data structure */\n   SCIP_SEPADATA*        sepadata,           /**< separator data data structure */\n   int                   size                /**< new size of cut arrays */\n   )\n{\n   assert(scip != NULL);\n   assert(sepadata != NULL);\n   assert(sepadata->newcuts != NULL);\n   assert(sepadata->nnewcuts <= sepadata->maxnewcuts);\n   assert(sepadata->nnewcuts >= 0);\n\n   if( sepadata->maxnewcuts < size )\n   {\n      while ( sepadata->maxnewcuts < size )\n      {\n         sepadata->maxnewcuts += MAXCUTSINC;\n      }\n      SCIP_CALL( SCIPreallocMemoryArray(scip, &(sepadata->newcuts), sepadata->maxnewcuts) );\n   }\n   assert(sepadata->maxnewcuts >= size);\n\n   return SCIP_OKAY;\n}\n\n/** returns the result of the exponentiation for given exponent and basis (basis^exponent) */\nstatic\nSCIP_Real exponentiate(\n   SCIP_Real            basis,               /**< basis for exponentiation */\n   int                  exponent            /**< exponent for exponentiation */\n   )\n{\n   SCIP_Real result;\n   int i;\n\n   assert(exponent >= 0);\n\n   result = 1.0;\n   for( i = 0; i < exponent; ++i )\n   {\n      result *= basis;\n   }\n\n   return result;\n}\n\n/**< Initialize probing objective coefficient for each variable with original objective. */\nstatic\nSCIP_RETCODE initProbingObjWithOrigObj(\n   SCIP*                origscip,           /**< orig scip problem */\n   SCIP_Bool            enableobj,          /**< returns if objective row was added to the lp */\n   SCIP_Real            objfactor           /**< factor, the objective is multiplied with */\n)\n{\n   SCIP_VAR** origvars;\n   int norigvars;\n   SCIP_VAR* origvar;\n\n   SCIP_Real newobj;\n   int i;\n\n   assert(SCIPinProbing(origscip));\n\n   origvars = SCIPgetVars(origscip);\n   norigvars = SCIPgetNVars(origscip);\n\n   /** loop over original variables */\n   for( i = 0; i < norigvars; ++i )\n   {\n      /* get variable information */\n      origvar = origvars[i];\n      newobj = 0.0;\n\n      /* if objective row is enabled consider also the original objective value */\n      if( enableobj )\n         newobj = objfactor * SCIPvarGetObj(origvar);\n\n      SCIP_CALL( SCIPchgVarObjProbing(origscip, origvar, newobj) );\n   }\n   return SCIP_OKAY;\n}\n\n/**< Change probing objective coefficient for each variable by adding original objective\n *   to the probing objective.\n */\nstatic\nSCIP_RETCODE chgProbingObjAddingOrigObj(\n   SCIP*                origscip,           /**< orig scip problem */\n   SCIP_Real            objfactor,          /**< factor the additional part of the objective is multiplied with */\n   SCIP_Real            objdivisor          /**< factor the additional part of the objective is divided with */\n)\n{\n   SCIP_VAR** origvars;\n   int norigvars;\n   SCIP_VAR* origvar;\n\n   SCIP_Real newobj;\n   int i;\n\n   assert(SCIPinProbing(origscip));\n\n   origvars = SCIPgetVars(origscip);\n   norigvars = SCIPgetNVars(origscip);\n\n   /** loop over original variables */\n   for( i = 0; i < norigvars; ++i )\n   {\n      /* get variable information */\n      origvar = origvars[i];\n\n      newobj = SCIPgetVarObjProbing(origscip, origvar) + (objfactor * SCIPvarGetObj(origvar))/ objdivisor ;\n\n      SCIP_CALL( SCIPchgVarObjProbing(origscip, origvar, newobj) );\n   }\n   return SCIP_OKAY;\n}\n\n/**< Initialize probing objective coefficient for each variable depending on the current origsol.\n *\n *   If variable is at upper bound set objective to -1, if variable is at lower bound set obj to 1,\n *   else set obj to 0.\n *   Additionally, add original objective to the probing objective if this is enabled.\n */\nstatic\nSCIP_RETCODE initProbingObjUsingVarBounds(\n   SCIP*                origscip,           /**< orig scip problem */\n   SCIP_SEPADATA*       sepadata,           /**< separator specific data */\n   SCIP_SOL*            origsol,            /**< orig solution */\n   SCIP_Bool            enableobj,          /**< returns if objective row was added to the lp */\n   SCIP_Real            objfactor           /**< factor the objective is multiplied with */\n)\n{\n   SCIP_Bool enableposslack;\n   int posslackexp;\n\n   SCIP_VAR** origvars;\n   int norigvars;\n   SCIP_VAR* origvar;\n\n   SCIP_Real lb;\n   SCIP_Real ub;\n   SCIP_Real solval;\n   SCIP_Real newobj;\n   SCIP_Real distance;\n\n   int i;\n\n   origvars = SCIPgetVars(origscip);\n   norigvars = SCIPgetNVars(origscip);\n\n   enableposslack = sepadata->enableposslack;\n   posslackexp = sepadata->posslackexp;\n\n   /** loop over original variables */\n   for( i = 0; i < norigvars; ++i )\n   {\n      /* get variable information */\n      origvar = origvars[i];\n      lb = SCIPvarGetLbLocal(origvar);\n      ub = SCIPvarGetUbLocal(origvar);\n      solval = SCIPgetSolVal(origscip, origsol, origvar);\n\n      assert(SCIPisFeasLE(origscip, solval, ub));\n      assert(SCIPisFeasGE(origscip, solval, lb));\n\n      /* if solution value of variable is at ub or lb initialize objective value of the variable\n       * such that the difference to this bound is minimized\n       */\n      if( SCIPisFeasEQ(origscip, lb, ub) )\n      {\n         newobj = 0.0;\n      }\n      else if( SCIPisLT(origscip, ub, SCIPinfinity(origscip)) && SCIPisFeasLE(origscip, ub, solval) )\n      {\n         newobj = -1.0;\n      }\n      else if( SCIPisGT(origscip, lb, -SCIPinfinity(origscip)) && SCIPisFeasGE(origscip, lb, solval) )\n      {\n         newobj = 1.0;\n      }\n      else if( enableposslack )\n      {\n         /* compute distance from solution to variable bound */\n         distance = MIN(solval - lb, ub - solval);\n\n         assert(SCIPisFeasPositive(origscip, distance));\n\n         /* check if distance is lower than 1 and compute factor */\n         if( SCIPisLT(origscip, distance, 1.0) )\n         {\n            newobj = exponentiate(MAX(0.0, 1.0 - distance), posslackexp);\n\n            /* check if algebraic sign has to be changed */\n            if( SCIPisLT(origscip, distance, solval - lb) )\n               newobj = -newobj;\n         }\n         else\n         {\n            newobj = 0.0;\n         }\n      }\n      else\n      {\n         newobj = 0.0;\n      }\n\n      newobj = newobj * (int) SCIPgetObjsense(origscip);\n\n      /* if objective row is enabled consider also the original objective value */\n      if( enableobj )\n         newobj = newobj + SCIPvarGetObj(origvar);\n\n      SCIP_CALL( SCIPchgVarObjProbing(origscip, origvar, objfactor*newobj) );\n   }\n\n   return SCIP_OKAY;\n}\n\n/**< Change probing objective depending on the current origsol.\n *\n * Loop over all constraints lhs <= sum a_i*x_i <= rhs. If lhs == sum a_i*x_i^* add a_i to objective\n * of variable i and if rhs == sum a_i*x_i^* add -a_i to objective of variable i.\n */\nstatic\nSCIP_RETCODE chgProbingObjUsingRows(\n   SCIP*                origscip,           /**< orig scip problem */\n   SCIP_SEPADATA*       sepadata,           /**< separator data */\n   SCIP_SOL*            origsol,            /**< orig solution */\n   SCIP_Real            objfactor,          /**< factor the objective is multiplied with */\n   SCIP_Real            objdivisor          /**< factor the objective is divided with */\n)\n{\n   SCIP_Bool enableposslack;\n   int posslackexp;\n\n   SCIP_ROW** rows;\n   int nrows;\n   SCIP_ROW* row;\n   SCIP_Real* vals;\n   SCIP_VAR** vars;\n   SCIP_COL** cols;\n   int nvars;\n\n   SCIP_Real lhs;\n   SCIP_Real rhs;\n   SCIP_Real* solvals;\n   SCIP_Real activity;\n   SCIP_Real factor;\n   SCIP_Real objadd;\n   SCIP_Real obj;\n   SCIP_Real norm;\n   SCIP_Real distance;\n\n   int i;\n   int j;\n\n   rows = SCIPgetLPRows(origscip);\n   nrows = SCIPgetNLPRows(origscip);\n\n   enableposslack = sepadata->enableposslack;\n   posslackexp = sepadata->posslackexp;\n\n   assert(SCIPinProbing(origscip));\n\n   SCIP_CALL( SCIPallocBufferArray(origscip, &solvals, SCIPgetNVars(origscip)) );\n   SCIP_CALL( SCIPallocBufferArray(origscip, &vars, SCIPgetNVars(origscip)) );\n\n   /** loop over constraint and check activity */\n   for( i = 0; i < nrows; ++i )\n   {\n      row = rows[i];\n      lhs = SCIProwGetLhs(row);\n      rhs = SCIProwGetRhs(row);\n\n      nvars = SCIProwGetNNonz(row);\n      if( nvars == 0 || (sepadata->objrow != NULL && strcmp(SCIProwGetName(row),SCIProwGetName(sepadata->objrow)) == 0 ) )\n         continue;\n\n      /* get values, variables and solution values */\n      vals = SCIProwGetVals(row);\n      cols = SCIProwGetCols(row);\n      for( j = 0; j < nvars; ++j )\n      {\n         vars[j] = SCIPcolGetVar(cols[j]);\n      }\n\n      activity = SCIPgetRowSolActivity(origscip, row, origsol);\n\n      if( SCIPisFeasEQ(origscip, rhs, lhs) )\n      {\n         continue;\n      }\n      if( SCIPisLT(origscip, rhs, SCIPinfinity(origscip)) && SCIPisFeasLE(origscip, rhs, activity) )\n      {\n         factor = -1.0;\n      }\n      else if( SCIPisGT(origscip, lhs, -SCIPinfinity(origscip)) && SCIPisFeasGE(origscip, lhs, activity) )\n      {\n         factor = 1.0;\n      }\n      else if( enableposslack )\n      {\n         assert(!(SCIPisInfinity(origscip, rhs) && SCIPisInfinity(origscip, lhs)));\n         assert(!(SCIPisInfinity(origscip, activity) && SCIPisInfinity(origscip, -activity)));\n\n         /* compute distance from solution to row */\n         if( SCIPisInfinity(origscip, rhs) && SCIPisGT(origscip, lhs, -SCIPinfinity(origscip)) )\n            distance = activity - lhs;\n         else if( SCIPisInfinity(origscip, lhs) && SCIPisLT(origscip, rhs, SCIPinfinity(origscip)) )\n            distance = rhs - activity;\n         else\n            distance = MIN(activity - lhs, rhs - activity);\n\n         assert(SCIPisFeasPositive(origscip, distance) || !SCIPisCutEfficacious(origscip, origsol, row));\n\n         /* check if distance is lower than 1 and compute factor */\n         if( SCIPisLT(origscip, distance, 1.0) )\n         {\n            factor = exponentiate(MAX(0.0, 1.0 - distance), posslackexp);\n\n            /* check if algebraic sign has to be changed */\n            if( SCIPisLT(origscip, distance, activity - lhs) )\n               factor = -1.0*factor;\n         }\n         else\n         {\n            continue;\n         }\n      }\n      else\n      {\n         continue;\n      }\n\n      norm = SCIProwGetNorm(row);\n\n      /** loop over variables of the constraint and change objective */\n      for( j = 0; j < nvars; ++j )\n      {\n         obj = SCIPgetVarObjProbing(origscip, vars[j]);\n         objadd = (factor * vals[j]) / norm;\n\n         objadd = objadd * (int) SCIPgetObjsense(origscip);\n\n         SCIP_CALL( SCIPchgVarObjProbing(origscip, vars[j], obj + (objfactor * objadd) / objdivisor) );\n      }\n   }\n\n   SCIPfreeBufferArray(origscip, &solvals);\n   SCIPfreeBufferArray(origscip, &vars);\n\n   return SCIP_OKAY;\n}\n\n#ifdef GSL\n/**< Get matrix (including nrows and ncols) of rows that are satisfied with equality by sol */\nstatic\nSCIP_RETCODE getEqualityMatrixGsl(\n   SCIP*                scip,               /**< SCIP data structure */\n   SCIP_SOL*            sol,                /**< solution */\n   gsl_matrix**         matrix,             /**< pointer to store equality matrix */\n   int*                 nrows,              /**< pointer to store number of rows */\n   int*                 ncols,              /**< pointer to store number of columns */\n   int*                 prerank             /**< pointer to store preprocessed rank */\n)\n{\n   int* var2col;\n   int* delvars;\n\n   int nvar2col;\n   int ndelvars;\n\n   SCIP_ROW** lprows;\n   int nlprows;\n\n   SCIP_COL** lpcols;\n   int nlpcols;\n\n   int i;\n   int j;\n\n   *ncols = SCIPgetNLPCols(scip);\n   nlprows = SCIPgetNLPRows(scip);\n   lprows = SCIPgetLPRows(scip);\n   nlpcols = SCIPgetNLPCols(scip);\n   lpcols = SCIPgetLPCols(scip);\n\n   *nrows = 0;\n\n   ndelvars = 0;\n   nvar2col = 0;\n\n   SCIP_CALL( SCIPallocBufferArray(scip, &var2col, nlpcols) );\n   SCIP_CALL( SCIPallocBufferArray(scip, &delvars, nlpcols) );\n\n   /* loop over lp cols and check if it is at one of its bounds */\n   for( i = 0; i < nlpcols; ++i )\n   {\n      SCIP_COL* lpcol;\n      SCIP_VAR* lpvar;\n\n      lpcol = lpcols[i];\n\n      lpvar = SCIPcolGetVar(lpcol);\n\n      if( SCIPisEQ(scip, SCIPgetSolVal(scip, sol, lpvar), SCIPcolGetUb(lpcol) )\n         || SCIPisEQ(scip, SCIPgetSolVal(scip, sol, lpvar), SCIPcolGetLb(lpcol)) )\n      {\n         int ind;\n\n         ind = SCIPcolGetIndex(lpcol);\n\n         delvars[ndelvars] = ind;\n\n         ++ndelvars;\n\n         var2col[ind] = -1;\n      }\n      else\n      {\n         int ind;\n\n         ind = SCIPcolGetIndex(lpcol);\n\n         var2col[ind] = nvar2col;\n\n         ++nvar2col;\n      }\n   }\n\n   SCIPsortInt(delvars, ndelvars);\n\n   *matrix = gsl_matrix_calloc(nlprows, nvar2col);\n\n   *ncols = nvar2col;\n\n   /* loop over lp rows and check if solution feasibility is equal to zero */\n   for( i = 0; i < nlprows; ++i )\n   {\n      SCIP_ROW* lprow;\n\n      lprow = lprows[i];\n\n      /* if solution feasiblity is equal to zero, add row to matrix */\n      if( SCIPisEQ(scip, SCIPgetRowSolFeasibility(scip, lprow, sol), 0.0) )\n      {\n         SCIP_COL** cols;\n         SCIP_Real* vals;\n         int nnonz;\n\n         cols = SCIProwGetCols(lprow);\n         vals = SCIProwGetVals(lprow);\n         nnonz = SCIProwGetNNonz(lprow);\n\n         /* get nonzero coefficients of row */\n         for( j = 0; j < nnonz; ++j )\n         {\n            int ind;\n            int pos;\n\n            ind = SCIPcolGetIndex(cols[j]);\n            assert(ind >= 0 && ind < nlpcols);\n\n            if( !SCIPsortedvecFindInt(delvars, ind, ndelvars, &pos) )\n            {\n               gsl_matrix_set(*matrix, *nrows, var2col[ind], vals[j]);\n            }\n         }\n         ++(*nrows);\n      }\n   }\n   *nrows = nlprows;\n   *prerank = ndelvars;\n\n   SCIPfreeBufferArray(scip, &delvars);\n   SCIPfreeBufferArray(scip, &var2col);\n\n   return SCIP_OKAY;\n}\n\n/**< get the rank of a given matrix */\nstatic\nSCIP_RETCODE getRank(\n   SCIP*                scip,\n   gsl_matrix*          matrix,\n   int                  nrows,\n   int                  ncols,\n   int*                 rank\n)\n{\n   gsl_matrix* matrixq;\n   gsl_matrix* matrixr;\n\n   gsl_vector* tau;\n   gsl_vector* norm;\n   gsl_permutation* permutation;\n\n   int ranktmp;\n   int signum;\n\n   int i;\n\n   matrixq = gsl_matrix_alloc(nrows, nrows);\n   matrixr = gsl_matrix_alloc(nrows, ncols);\n\n   norm = gsl_vector_alloc(ncols);\n   tau = gsl_vector_alloc(MIN(nrows, ncols));\n\n   permutation = gsl_permutation_alloc(ncols);\n\n   gsl_linalg_QRPT_decomp(matrix, tau, permutation, &signum, norm);\n\n   gsl_linalg_QR_unpack(matrix, tau, matrixq, matrixr);\n\n   ranktmp = 0;\n\n   for( i = 0; i < MIN(nrows, ncols); ++i )\n   {\n      SCIP_Real val;\n\n      val = gsl_matrix_get(matrixr, i, i);\n\n      if( SCIPisZero(scip, val) )\n      {\n         break;\n      }\n      ++(ranktmp);\n   }\n\n   *rank = ranktmp;\n\n   gsl_matrix_free(matrixq);\n   gsl_matrix_free(matrixr);\n\n   gsl_vector_free(tau);\n   gsl_vector_free(norm);\n\n   gsl_permutation_free(permutation);\n\n   return SCIP_OKAY;\n}\n\n/**< Get rank (number of linear independent rows) of rows that are satisfied\n *   with equality by solution sol */\nstatic\nSCIP_RETCODE getEqualityRankGsl(\n   SCIP*                scip,               /**< SCIP data structure */\n   SCIP_SOL*            sol,                /**< solution */\n   int*                 equalityrank        /**< pointer to store rank of rows with equality */\n   )\n{\n   gsl_matrix* matrix;\n   int nrows;\n   int ncols;\n\n   int prerank;\n   int rowrank;\n\n   SCIP_CALL( getEqualityMatrixGsl(scip, sol, &matrix, &nrows, &ncols, &prerank) );\n\n   SCIP_CALL( getRank(scip, matrix, nrows, ncols, &rowrank) );\n\n   gsl_matrix_free(matrix);\n\n   *equalityrank = rowrank + prerank;\n\n   return SCIP_OKAY;\n}\n#endif\n\n/** add cuts which are due to the latest objective function of the pricing problems\n *  (reduced cost non-negative) */\nstatic\nSCIP_RETCODE addPPObjConss(\n   SCIP*                scip,               /**< SCIP data structure */\n   SCIP_SEPA*           sepa,               /**< separator basis */\n   int                  ppnumber,           /**< number of pricing problem */\n   SCIP_Real            dualsolconv,        /**< dual solution corresponding to convexity constraint */\n   SCIP_Bool            newcuts,            /**< add cut to newcuts in sepadata? (otherwise add it just to the cutpool) */\n   SCIP_Bool            probing             /**< add cut to probing LP? */\n)\n{\n   SCIP_SEPADATA* sepadata;\n\n   SCIP* pricingscip;\n\n   SCIP_VAR** pricingvars;\n   SCIP_VAR* var;\n\n   int npricingvars;\n   int nvars;\n\n   char name[SCIP_MAXSTRLEN];\n\n   int j;\n   int k;\n\n   SCIP_OBJSENSE objsense;\n\n   SCIP_Real lhs;\n   SCIP_Real rhs;\n\n   sepadata = SCIPsepaGetData(sepa);\n\n   nvars = 0;\n   pricingscip = GCGgetPricingprob(scip, ppnumber);\n   pricingvars = SCIPgetOrigVars(pricingscip);\n   npricingvars = SCIPgetNOrigVars(pricingscip);\n\n   if( !GCGisPricingprobRelevant(scip, ppnumber) || pricingscip == NULL )\n      return SCIP_OKAY;\n\n   objsense = SCIPgetObjsense(pricingscip);\n\n   if( objsense == SCIP_OBJSENSE_MINIMIZE )\n   {\n      lhs = dualsolconv;\n      rhs = SCIPinfinity(scip);\n   }\n   else\n   {\n      rhs = dualsolconv;\n      lhs = -SCIPinfinity(scip);\n   }\n\n   for( k = 0; k < GCGgetNIdenticalBlocks(scip, ppnumber); ++k )\n   {\n      SCIP_ROW* origcut;\n\n      (void) SCIPsnprintf(name, SCIP_MAXSTRLEN, \"newconstraint_%d_%d_%d\", SCIPsepaGetNCalls(sepa), ppnumber, k);\n\n      SCIP_CALL( SCIPcreateEmptyRowUnspec(scip, &origcut, name, lhs, rhs, FALSE, FALSE, TRUE) );\n\n      nvars = 0;\n\n      for( j = 0; j < npricingvars ; ++j )\n      {\n         assert(GCGvarIsPricing(pricingvars[j]));\n\n         if( !SCIPisEQ(scip, SCIPvarGetObj(pricingvars[j]), 0.0) )\n         {\n            var = GCGpricingVarGetOrigvars(pricingvars[j])[k];\n            assert(var != NULL);\n            SCIP_CALL( SCIPaddVarToRow(scip, origcut, var, SCIPvarGetObj(pricingvars[j])) );\n            ++nvars;\n         }\n      }\n\n      if( nvars > 0 )\n      {\n         if( newcuts )\n         {\n            SCIP_CALL( ensureSizeNewCuts(scip, sepadata, sepadata->nnewcuts + 1) );\n\n            sepadata->newcuts[sepadata->nnewcuts] = origcut;\n            SCIP_CALL( SCIPcaptureRow(scip, sepadata->newcuts[sepadata->nnewcuts]) );\n            ++(sepadata->nnewcuts);\n\n            SCIPdebugMessage(\"cut added to new cuts in relaxdata\\n\");\n         }\n         else\n         {\n            SCIP_CALL( SCIPaddPoolCut(scip, origcut) );\n            SCIPdebugMessage(\"cut added to orig cut pool\\n\");\n         }\n\n         if( probing )\n         {\n            SCIP_CALL( SCIPaddRowProbing(scip, origcut) );\n            SCIPdebugMessage(\"cut added to probing\\n\");\n         }\n\n\n      }\n      SCIP_CALL( SCIPreleaseRow(scip, &origcut) );\n   }\n\n   return SCIP_OKAY;\n}\n/*\n * Callback methods of separator\n */\n\n/** copy method for separator plugins (called when SCIP copies plugins) */\n#if 0\nstatic\nSCIP_DECL_SEPACOPY(sepaCopyBasis)\n{  /*lint --e{715}*/\n   SCIPerrorMessage(\"method of basis separator not implemented yet\\n\");\n   SCIPABORT(); /*lint --e{527}*/\n\n   return SCIP_OKAY;\n}\n#else\n#define sepaCopyBasis NULL\n#endif\n\n/** destructor of separator to free user data (called when SCIP is exiting) */\nstatic\nSCIP_DECL_SEPAFREE(sepaFreeBasis)\n{  /*lint --e{715}*/\n   SCIP_SEPADATA* sepadata;\n\n   sepadata = SCIPsepaGetData(sepa);\n   assert(sepadata != NULL);\n\n   SCIPfreeMemory(scip, &sepadata);\n\n   return SCIP_OKAY;\n}\n\n/** initialization method of separator (called after problem was transformed) */\nstatic\nSCIP_DECL_SEPAINIT(sepaInitBasis)\n{  /*lint --e{715}*/\n   SCIP*   origscip;\n   SCIP_SEPADATA* sepadata;\n\n   SCIP_VAR** origvars;\n   int norigvars;\n\n   char name[SCIP_MAXSTRLEN];\n\n   SCIP_Real obj;\n   int i;\n\n   SCIP_Bool enable;\n   SCIP_Bool enableobj;\n\n   assert(scip != NULL);\n\n   origscip = GCGmasterGetOrigprob(scip);\n   assert(origscip != NULL);\n\n   sepadata = SCIPsepaGetData(sepa);\n   assert(sepadata != NULL);\n\n   origvars = SCIPgetVars(origscip);\n   norigvars = SCIPgetNVars(origscip);\n\n   SCIPdebugMessage(\"sepaInitBasis\\n\");\n\n   enable = sepadata->enable;\n   enableobj = sepadata->enableobj;\n\n   sepadata->maxcuts = STARTMAXCUTS;\n   sepadata->norigcuts = 0;\n   sepadata->maxnewcuts = 0;\n   sepadata->nnewcuts = 0;\n   sepadata->objrow = NULL;\n\n   /* if separator is disabled do nothing */\n   if( !enable )\n   {\n      return SCIP_OKAY;\n   }\n\n   SCIP_CALL( SCIPallocMemoryArray(scip, &(sepadata->origcuts), STARTMAXCUTS) ); /*lint !e506*/\n   SCIP_CALL( SCIPallocMemoryArray(scip, &(sepadata->mastercuts), STARTMAXCUTS) ); /*lint !e506*/\n   SCIP_CALL( SCIPallocMemoryArray(scip, &(sepadata->newcuts), STARTMAXCUTS) ); /*lint !e506*/\n\n   /* if objective row is enabled create row with objective coefficients */\n   if( enableobj )\n   {\n      (void) SCIPsnprintf(name, SCIP_MAXSTRLEN, \"objrow\");\n      SCIP_CALL( SCIPcreateEmptyRowUnspec(origscip, &(sepadata->objrow), name, -SCIPinfinity(origscip), SCIPinfinity(origscip), TRUE, FALSE, TRUE) );\n\n      for( i = 0; i < norigvars; ++i )\n      {\n         obj = SCIPvarGetObj(origvars[i]);\n         SCIP_CALL( SCIPaddVarToRow(origscip, sepadata->objrow, origvars[i], obj) );\n      }\n   }\n\n   return SCIP_OKAY;\n}\n\n\n/** deinitialization method of separator (called before transformed problem is freed) */\nstatic\nSCIP_DECL_SEPAEXIT(sepaExitBasis)\n{  /*lint --e{715}*/\n   SCIP* origscip;\n   SCIP_SEPADATA* sepadata;\n   SCIP_Bool enableobj;\n\n   int i;\n\n   sepadata = SCIPsepaGetData(sepa);\n   assert(sepadata != NULL);\n   enableobj = sepadata->enableobj;\n   assert(sepadata->nmastercuts == sepadata->norigcuts);\n\n   origscip = GCGmasterGetOrigprob(scip);\n   assert(origscip != NULL);\n\n   for( i = 0; i < sepadata->norigcuts; i++ )\n   {\n      SCIP_CALL( SCIPreleaseRow(origscip, &(sepadata->origcuts[i])) );\n   }\n\n   for( i = 0; i < sepadata->nnewcuts; ++i )\n   {\n      if( sepadata->newcuts[i] != NULL )\n         SCIP_CALL( SCIPreleaseRow(origscip, &(sepadata->newcuts[i])) );\n   }\n\n   if( enableobj )\n      SCIP_CALL( SCIPreleaseRow(origscip, &(sepadata->objrow)) );\n\n   SCIPfreeMemoryArrayNull(scip, &(sepadata->origcuts));\n   SCIPfreeMemoryArrayNull(scip, &(sepadata->mastercuts));\n   SCIPfreeMemoryArrayNull(scip, &(sepadata->newcuts));\n\n   return SCIP_OKAY;\n}\n\n/** solving process initialization method of separator (called when branch and bound process is about to begin) */\nstatic\nSCIP_DECL_SEPAINITSOL(sepaInitsolBasis)\n{  /*lint --e{715}*/\n   SCIP_SEPADATA* sepadata;\n\n   sepadata = SCIPsepaGetData(sepa);\n   assert(sepadata != NULL);\n\n   sepadata->nmastercuts = 0;\n\n   return SCIP_OKAY;\n}\n\n\n/** solving process deinitialization method of separator (called before branch and bound process data is freed) */\nstatic\nSCIP_DECL_SEPAEXITSOL(sepaExitsolBasis)\n{  /*lint --e{715}*/\n   SCIP_SEPADATA* sepadata;\n   int i;\n\n   sepadata = SCIPsepaGetData(sepa);\n   assert(sepadata != NULL);\n   assert(sepadata->nmastercuts == sepadata->norigcuts);\n\n   assert(GCGmasterGetOrigprob(scip) != NULL);\n\n   for( i = 0; i < sepadata->nmastercuts; i++ )\n   {\n      SCIP_CALL( SCIPreleaseRow(scip, &(sepadata->mastercuts[i])) );\n   }\n\n   return SCIP_OKAY;\n}\n\n\n/**< Initialize objective due to generation of convex combination */\nstatic\nSCIP_RETCODE initGenconv(\n   SCIP*                origscip,           /**< original SCIP data structure */\n   SCIP_SEPADATA*       sepadata,           /**< separator data structure */\n   SCIP_SOL*            origsol,            /**< current original solution */\n   int                  nbasis,             /**< rank of constraint matrix */\n   SCIP_Real*           convex              /**< pointer to store convex combination coefficient */\n)\n{  /*lint --e{715}*/\n#ifdef GSL\n   int rank;\n\n\n   SCIP_CALL( getEqualityRankGsl(origscip, origsol, &rank) );\n\n   *convex = 1.0* rank/nbasis;\n\n   SCIPdebugMessage(\"use generic coefficient %d/%d = %f\\n\", rank, nbasis, *convex);\n\n#else\n   SCIPwarningMessage(origscip, \"Gnu Scientific Library is not enabled! \\n\"\n      \"either set sepa/basis/genobjconvex = FALSE sepa/basis/posslackexpgen = FALSE \\n\"\n      \"or compile with GSL=true and include Gnu Scientific Library\\n\");\n   *convex = sepadata->objconvex;\n#endif\n\n   return SCIP_OKAY;\n}\n\n\n/**< Initialize objective due to generation of convex combination */\nstatic\nSCIP_RETCODE initConvObj(\n   SCIP*                origscip,           /**< original SCIP data structure */\n   SCIP_SEPADATA*       sepadata,           /**< separator data structure */\n   SCIP_SOL*            origsol,            /**< current original solution */\n   SCIP_Real            convex,             /**< convex coefficient to initialize objective */\n   SCIP_Bool            genericconv         /**< was convex coefficient calculated generically? */\n)\n{\n   SCIP_Real objnormnull;\n   SCIP_Real objnormcurrent;\n\n   objnormnull = 1.0;\n   objnormcurrent = 1.0;\n\n   if( SCIPisEQ(origscip, convex, 0.0) )\n   {\n      SCIP_CALL( initProbingObjWithOrigObj(origscip, TRUE, 1.0) );\n   }\n   else if( SCIPisLT(origscip, convex, 1.0) )\n   {\n      SCIP_CALL( initProbingObjWithOrigObj(origscip, TRUE, 1.0) );\n      objnormnull = SCIPgetObjNorm(origscip);\n\n      SCIP_CALL( initProbingObjUsingVarBounds(origscip, sepadata, origsol, FALSE, convex) );\n      SCIP_CALL( chgProbingObjUsingRows(origscip, sepadata, origsol, convex, 1.0) );\n\n      objnormcurrent = SCIPgetObjNorm(origscip)/(convex);\n\n      if( SCIPisEQ(origscip, objnormcurrent, 0.0) )\n         SCIP_CALL( initProbingObjWithOrigObj(origscip, TRUE, 1.0) );\n      else if( SCIPisGT(origscip, objnormnull, 0.0) )\n         SCIP_CALL( chgProbingObjAddingOrigObj(origscip, (1.0 - convex) * objnormcurrent, objnormnull) );\n   }\n   else if( SCIPisEQ(origscip, convex, 1.0) )\n   {\n      SCIP_CALL( initProbingObjUsingVarBounds(origscip, sepadata, origsol, !genericconv && sepadata->enableobj, 1.0) );\n      SCIP_CALL( chgProbingObjUsingRows(origscip, sepadata, origsol, 1.0, 1.0) );\n   }\n\n   return SCIP_OKAY;\n}\n\n/** LP solution separation method of separator */\nstatic\nSCIP_DECL_SEPAEXECLP(sepaExeclpBasis)\n{  /*lint --e{715}*/\n\n   SCIP* origscip;\n   SCIP_SEPADATA* sepadata;\n\n   SCIP_SEPA** sepas;\n   int nsepas;\n\n   SCIP_ROW** cuts;\n   SCIP_ROW* mastercut;\n   SCIP_ROW* origcut;\n   SCIP_COL** cols;\n   SCIP_VAR** roworigvars;\n   SCIP_VAR** mastervars;\n   SCIP_Real* mastervals;\n   int ncols;\n   int ncuts;\n   SCIP_Real* vals;\n   int nmastervars;\n\n   SCIP_RESULT resultdummy;\n   SCIP_OBJSENSE objsense;\n   SCIP_SOL* origsol;\n   SCIP_Bool lperror;\n   SCIP_Bool delayed;\n   SCIP_Bool cutoff;\n   SCIP_Bool infeasible;\n   SCIP_Real obj;\n\n   SCIP_Bool enable;\n   SCIP_Bool enableobj;\n   SCIP_Bool enableobjround;\n   SCIP_Bool enableppobjconss;\n\n   char name[SCIP_MAXSTRLEN];\n\n   int i;\n   int j;\n   int iteration;\n   int nbasis;\n   int nlprowsstart;\n   int nlprows;\n   SCIP_ROW** lprows;\n\n   assert(scip != NULL);\n   assert(result != NULL);\n\n   origscip = GCGmasterGetOrigprob(scip);\n   assert(origscip != NULL);\n\n   sepadata = SCIPsepaGetData(sepa);\n   assert(sepadata != NULL);\n\n   SCIPdebugMessage(\"calling sepaExeclpBasis\\n\");\n\n   *result = SCIP_DIDNOTFIND;\n\n   enable = sepadata->enable;\n   enableobj = sepadata->enableobj;\n   enableobjround = sepadata->enableobjround;\n   enableppobjconss = sepadata->enableppobjconss;\n\n   /* if separator is disabled do nothing */\n   if( !enable )\n   {\n      SCIPdebugMessage(\"separator is not enabled\\n\");\n      *result = SCIP_DIDNOTRUN;\n      return SCIP_OKAY;\n   }\n\n   /* ensure master LP is solved to optimality */\n   if( SCIPgetLPSolstat(scip) != SCIP_LPSOLSTAT_OPTIMAL )\n   {\n      SCIPdebugMessage(\"master LP not solved to optimality, do no separation!\\n\");\n      *result = SCIP_DIDNOTRUN;\n      return SCIP_OKAY;\n   }\n\n   if( GCGgetNRelPricingprobs(origscip) < GCGgetNPricingprobs(origscip) )\n   {\n      SCIPdebugMessage(\"aggregated pricing problems, do no separation!\\n\");\n      *result = SCIP_DIDNOTRUN;\n      return SCIP_OKAY;\n   }\n\n   if( GCGrelaxIsOrigSolFeasible(origscip) )\n   {\n      SCIPdebugMessage(\"Current solution is feasible, no separation necessary!\\n\");\n      *result = SCIP_DIDNOTRUN;\n      return SCIP_OKAY;\n   }\n\n   /* get current original solution */\n   origsol = GCGrelaxGetCurrentOrigSol(origscip);\n\n   /* get obj and objsense */\n   objsense = SCIPgetObjsense(origscip);\n   obj = SCIPgetSolOrigObj(origscip, origsol);\n\n   /** get number of linearly independent rows needed for basis */\n   nbasis = SCIPgetNLPCols(origscip);\n\n   *result = SCIP_DIDNOTFIND;\n\n   /* init iteration counter */\n   iteration = 0;\n\n   /* set parameter setting for separation */\n   SCIP_CALL( SCIPsetSeparating(origscip, (SCIP_PARAMSETTING) sepadata->separationsetting, TRUE) );\n\n   /* start diving */\n   SCIP_CALL( SCIPstartProbing(origscip) );\n\n   SCIP_CALL( SCIPnewProbingNode(origscip) );\n\n   SCIP_CALL( SCIPconstructLP(origscip, &cutoff) );\n\n   /** add origcuts to probing lp */\n   for( i = 0; i < GCGsepaGetNCuts(scip); ++i )\n   {\n      if( SCIProwGetLPPos(GCGsepaGetOrigcuts(scip)[i]) == -1 )\n         SCIP_CALL( SCIPaddRowProbing(origscip, GCGsepaGetOrigcuts(scip)[i]) );\n   }\n\n   /** add new cuts which did not cut off master sol to probing lp */\n   for( i = 0; i < sepadata->nnewcuts; ++i )\n   {\n      if( SCIProwGetLPPos(sepadata->newcuts[i]) == -1 )\n         SCIP_CALL( SCIPaddRowProbing(origscip, sepadata->newcuts[i]) );\n   }\n\n   /* store number of lp rows in the beginning */\n   nlprowsstart = SCIPgetNLPRows(origscip);\n\n   /* while the counter is smaller than the number of allowed iterations,\n    * try to separate origsol via probing lp sol */\n   /* TODO: while z*(T) = 0 like Range suggests? But then we have to adjust which cuts are added */\n   while( iteration < sepadata->iterations )\n   {\n      SCIPdebugMessage(\"iteration %d of at most %d iterations\\n\", iteration + 1, sepadata->iterations);\n\n      SCIP_CALL( SCIPapplyCutsProbing(origscip, &cutoff) );\n\n      /* add new constraints if this is enabled  */\n      if( enableppobjconss && iteration == 0 )\n      {\n         SCIP_Real* dualsolconv;\n\n         SCIPdebugMessage(\"add reduced cost cut for relevant pricing problems\\n\");\n\n         SCIP_CALL( SCIPallocMemoryArray(scip, &dualsolconv, GCGgetNPricingprobs(origscip)) );\n         SCIP_CALL( GCGsetPricingObjs(scip, dualsolconv) );\n\n         for( i = 0; i < GCGgetNPricingprobs(origscip); ++i )\n         {\n            SCIP_CALL( addPPObjConss(origscip, sepa, i, dualsolconv[i], FALSE, TRUE) );\n         }\n\n         SCIPfreeMemoryArray(scip, &dualsolconv);\n      }\n\n      /* init objective */\n      if( sepadata->chgobj && (iteration == 0 || sepadata->chgobjallways) )\n      {\n         SCIPdebugMessage(\"initialize objective function\\n\");\n         if( sepadata->genobjconvex )\n         {\n            SCIP_Real genconvex;\n\n            SCIP_CALL( initGenconv(origscip, sepadata, origsol, nbasis, &genconvex) );\n\n            SCIP_CALL( initConvObj(origscip, sepadata, origsol, genconvex, TRUE) );\n         }\n         else\n         {\n            SCIPdebugMessage(\"use given coefficient %g\\n\", sepadata->objconvex);\n\n            if( sepadata->enableposslack && sepadata->posslackexpgen )\n            {\n               SCIP_Real genconvex;\n               SCIP_Real factor;\n\n               factor = sepadata->posslackexpgenfactor;\n\n               SCIP_CALL( initGenconv(origscip, sepadata, origsol, nbasis, &genconvex) );\n\n               sepadata->posslackexp = (int) (SCIPceil(origscip, factor/(1.0 - genconvex)) + 0.5);\n\n               SCIPdebugMessage(\"exponent = %d\\n\", sepadata->posslackexp);\n\n            }\n            SCIP_CALL( initConvObj(origscip, sepadata, origsol, sepadata->objconvex, FALSE) );\n         }\n      }\n\n      /* update rhs/lhs of objective constraint and add it to probing LP, if it exists (only in first iteration) */\n      if( enableobj && iteration == 0 )\n      {\n         SCIPdebugMessage(\"initialize original objective cut\\n\");\n\n         /* round rhs/lhs of objective constraint, if it exists, obj is integral and this is enabled */\n         if( SCIPisObjIntegral(origscip) && enableobjround )\n         {\n            if( objsense == SCIP_OBJSENSE_MAXIMIZE )\n            {\n               SCIPdebugMessage(\"round rhs down\\n\");\n               obj = SCIPfloor(origscip, obj);\n            }\n            else\n            {\n               SCIPdebugMessage(\"round lhs up\\n\");\n               obj = SCIPceil(origscip, obj);\n            }\n         }\n\n         /* update rhs/lhs of objective constraint */\n         if( objsense == SCIP_OBJSENSE_MAXIMIZE )\n         {\n            SCIP_CALL( SCIPchgRowRhs(origscip, sepadata->objrow, obj) );\n            SCIP_CALL( SCIPchgRowLhs(origscip, sepadata->objrow, -1.0*SCIPinfinity(origscip)) );\n         }\n         else\n         {\n            SCIP_CALL( SCIPchgRowLhs(origscip, sepadata->objrow, obj) );\n            SCIP_CALL( SCIPchgRowRhs(origscip, sepadata->objrow, SCIPinfinity(origscip)) );\n         }\n         SCIPdebugMessage(\"add original objective cut to probing LP\\n\");\n\n         /** add row to probing lp */\n         SCIP_CALL( SCIPaddRowProbing(origscip, sepadata->objrow) );\n      }\n\n      SCIPdebugMessage(\"solve probing LP\\n\");\n\n      /* solve probing lp */\n      SCIP_CALL( SCIPsolveProbingLP(origscip, -1, &lperror, &cutoff) );\n\n      assert(!lperror);\n\n      /* get separators of origscip */\n      sepas = SCIPgetSepas(origscip);\n      nsepas = SCIPgetNSepas(origscip);\n\n      SCIPdebugMessage(\"set parameters of separators\\n\");\n\n      /* loop over sepas and enable/disable sepa */\n      for( i = 0; i < nsepas; ++i )\n      {\n         const char* sepaname;\n         char paramname[SCIP_MAXSTRLEN];\n\n         sepaname = SCIPsepaGetName(sepas[i]);\n\n         (void) SCIPsnprintf(paramname, SCIP_MAXSTRLEN, \"separating/%s/freq\", sepaname);\n\n         /* disable intobj, closecuts, rapidlearning and cgmip separator*/\n         if( strcmp(sepaname, \"intobj\") == 0 || strcmp(sepaname, \"closecuts\") == 0\n            || strcmp(sepaname, \"rapidlearning\") == 0\n            || (strcmp(sepaname, \"cgmip\") == 0))\n         {\n            SCIP_CALL( SCIPsetIntParam(origscip, paramname, -1) );\n         }\n         else\n         {\n            SCIP_CALL( SCIPsetIntParam(origscip, paramname, 0) );\n         }\n      }\n\n      SCIPdebugMessage(\"separate current LP solution\\n\");\n\n      /** separate current probing lp sol of origscip */\n      SCIP_CALL( SCIPseparateSol(origscip, NULL, TRUE, FALSE, TRUE, &delayed, &cutoff) );\n\n      if( delayed && !cutoff )\n      {\n         SCIPdebugMessage(\"call delayed separators\\n\");\n\n         SCIP_CALL( SCIPseparateSol(origscip, NULL, TRUE, TRUE, TRUE, &delayed, &cutoff) );\n      }\n\n      /* if cut off is detected set result pointer and return SCIP_OKAY */\n      if( cutoff )\n      {\n         *result = SCIP_CUTOFF;\n         SCIP_CALL( SCIPendProbing(origscip) );\n\n         /* disable separating again */\n         SCIP_CALL( SCIPsetSeparating(origscip, SCIP_PARAMSETTING_OFF, TRUE) );\n\n         return SCIP_OKAY;\n      }\n\n      SCIPdebugMessage(\"separate current LP solution and current original solution in cutpool\\n\");\n\n      /* separate cuts in cutpool */\n      SCIP_CALL( SCIPseparateSolCutpool(origscip, SCIPgetGlobalCutpool(origscip), NULL, &resultdummy) );\n      SCIP_CALL( SCIPseparateSolCutpool(origscip, SCIPgetDelayedGlobalCutpool(origscip), NULL, &resultdummy) );\n\n      /* separate cuts in cutpool */\n      SCIP_CALL( SCIPseparateSolCutpool(origscip, SCIPgetGlobalCutpool(origscip), origsol, &resultdummy) );\n      SCIP_CALL( SCIPseparateSolCutpool(origscip, SCIPgetDelayedGlobalCutpool(origscip), origsol, &resultdummy) );\n\n      assert(sepadata->norigcuts == sepadata->nmastercuts);\n\n      SCIPdebugMessage(\"%d cuts are in the original sepastore!\\n\", SCIPgetNCuts(origscip));\n\n      /* get separated cuts */\n      cuts = SCIPgetCuts(origscip);\n      ncuts = SCIPgetNCuts(origscip);\n\n      SCIP_CALL( ensureSizeCuts(scip, sepadata, sepadata->norigcuts + ncuts) );\n\n      mastervars = SCIPgetVars(scip);\n      nmastervars = SCIPgetNVars(scip);\n      SCIP_CALL( SCIPallocBufferArray(scip, &mastervals, nmastervars) );\n\n      /** loop over cuts and transform cut to master problem (and safe cuts) if it seperates origsol */\n      for( i = 0; i < ncuts; i++ )\n      {\n         SCIP_Bool colvarused;\n\n         colvarused = FALSE;\n         origcut = cuts[i];\n\n         /* get columns and vals of the cut */\n         ncols = SCIProwGetNNonz(origcut);\n         cols = SCIProwGetCols(origcut);\n         vals = SCIProwGetVals(origcut);\n\n         /* get the variables corresponding to the columns in the cut */\n         SCIP_CALL( SCIPallocBufferArray(scip, &roworigvars, ncols) );\n         for( j = 0; j < ncols; j++ )\n         {\n            roworigvars[j] = SCIPcolGetVar(cols[j]);\n            assert(roworigvars[j] != NULL);\n            if( !GCGvarIsOriginal(roworigvars[j]) )\n            {\n               colvarused = TRUE;\n               break;\n            }\n         }\n\n         if( colvarused )\n         {\n            SCIPwarningMessage(origscip, \"colvar used in original cut %s\\n\", SCIProwGetName(origcut));\n            SCIPfreeBufferArray(scip, &roworigvars);\n            continue;\n         }\n\n         if( !SCIPisCutEfficacious(origscip, origsol, origcut) )\n         {\n            if( !SCIProwIsLocal(origcut) )\n               SCIP_CALL( SCIPaddPoolCut(origscip, origcut) );\n\n            SCIPfreeBufferArray(scip, &roworigvars);\n\n            continue;\n         }\n\n         /* add the cut to the original cut storage */\n         sepadata->origcuts[sepadata->norigcuts] = origcut;\n         SCIP_CALL( SCIPcaptureRow(origscip, sepadata->origcuts[sepadata->norigcuts]) );\n         sepadata->norigcuts++;\n\n         /* create new cut in the master problem */\n         (void) SCIPsnprintf(name, SCIP_MAXSTRLEN, \"mc_basis_%s\", SCIProwGetName(origcut));\n         SCIP_CALL( SCIPcreateEmptyRowSepa(scip, &mastercut, sepa, name,\n               ( SCIPisInfinity(scip, -SCIProwGetLhs(origcut)) ?\n                  SCIProwGetLhs(origcut) : SCIProwGetLhs(origcut) - SCIProwGetConstant(origcut)),\n               ( SCIPisInfinity(scip, SCIProwGetRhs(origcut)) ?\n                  SCIProwGetRhs(origcut) : SCIProwGetRhs(origcut) - SCIProwGetConstant(origcut)),\n                  SCIProwIsLocal(origcut), TRUE, FALSE) );\n\n         /* transform the original variables to master variables and add them to the cut */\n         GCGtransformOrigvalsToMastervals(origscip, roworigvars, vals, ncols, mastervars, mastervals, nmastervars);\n         SCIP_CALL( SCIPaddVarsToRow(scip, mastercut, nmastervars, mastervars, mastervals) );\n\n         /* add the cut to the master problem and to the master cut storage */\n         SCIP_CALL( SCIPaddRow(scip, mastercut, sepadata->forcecuts, &infeasible) );\n         sepadata->mastercuts[sepadata->nmastercuts] = mastercut;\n         SCIP_CALL( SCIPcaptureRow(scip, sepadata->mastercuts[sepadata->nmastercuts]) );\n         sepadata->nmastercuts++;\n         SCIP_CALL( GCGsepaAddMastercuts(scip, origcut, mastercut) );\n\n         SCIP_CALL( SCIPreleaseRow(scip, &mastercut) );\n         SCIPfreeBufferArray(scip, &roworigvars);\n      }\n\n      if( SCIPgetNCuts(scip) >= sepadata->mincuts )\n      {\n         *result = SCIP_SEPARATED;\n\n         iteration = sepadata->iterations;\n      }\n      else if( SCIPgetNCuts(origscip) == 0 )\n      {\n         iteration = sepadata->iterations;\n      }\n      else\n      {\n         ++iteration;\n      }\n\n      SCIPdebugMessage(\"%d cuts are in the master sepastore!\\n\", SCIPgetNCuts(scip));\n\n      SCIPfreeBufferArray(scip, &mastervals);\n\n      assert(sepadata->norigcuts == sepadata->nmastercuts );\n   }\n\n   SCIP_CALL( SCIPclearCuts(origscip) );\n\n   lprows = SCIPgetLPRows(origscip);\n   nlprows = SCIPgetNLPRows(origscip);\n\n   assert(nlprowsstart <= nlprows);\n\n   SCIP_CALL( ensureSizeNewCuts(scip, sepadata, sepadata->nnewcuts + nlprows - nlprowsstart) );\n\n   for( i = nlprowsstart; i < nlprows; ++i )\n   {\n      if( SCIProwGetOrigintype(lprows[i]) == SCIP_ROWORIGINTYPE_SEPA )\n\t   {\n         sepadata->newcuts[sepadata->nnewcuts] = lprows[i];\n\t      SCIP_CALL( SCIPcaptureRow(origscip, sepadata->newcuts[sepadata->nnewcuts]) );\n\t      ++(sepadata->nnewcuts);\n\t   }\n   }\n\n   /* end diving */\n   SCIP_CALL( SCIPendProbing(origscip) );\n\n   if( SCIPgetNCuts(scip) > 0 )\n   {\n      *result = SCIP_SEPARATED;\n   }\n\n   /* disable separating again */\n   SCIP_CALL( SCIPsetSeparating(origscip, SCIP_PARAMSETTING_OFF, TRUE) );\n\n\n   SCIPdebugMessage(\"exiting sepaExeclpBasis\\n\");\n\n   return SCIP_OKAY;\n}\n\n/** arbitrary primal solution separation method of separator */\n#if 0\nstatic\nSCIP_DECL_SEPAEXECSOL(sepaExecsolBasis)\n{  /*lint --e{715}*/\n   SCIPerrorMessage(\"method of basis separator not implemented yet\\n\");\n   SCIPABORT(); /*lint --e{527}*/\n\n   return SCIP_OKAY;\n}\n#else\n#define sepaExecsolBasis NULL\n#endif\n\n/*\n * separator specific interface methods\n */\n\n/** creates the basis separator and includes it in SCIP */\nSCIP_RETCODE SCIPincludeSepaBasis(\n   SCIP*                 scip                /**< SCIP data structure */\n   )\n{\n   SCIP_SEPADATA* sepadata;\n\n   /* create master separator data */\n   SCIP_CALL( SCIPallocMemory(scip, &sepadata) );\n\n   sepadata->mastercuts = NULL;\n   sepadata->origcuts = NULL;\n   sepadata->norigcuts = 0;\n   sepadata->nmastercuts = 0;\n   sepadata->maxcuts = 0;\n   sepadata->newcuts = NULL;\n   sepadata->nnewcuts = 0;\n   sepadata->maxnewcuts = 0;\n   sepadata->objrow = NULL;\n\n   /* include separator */\n   SCIP_CALL( SCIPincludeSepa(scip, SEPA_NAME, SEPA_DESC, SEPA_PRIORITY, SEPA_FREQ, SEPA_MAXBOUNDDIST,\n         SEPA_USESSUBSCIP, SEPA_DELAY,\n         sepaCopyBasis, sepaFreeBasis, sepaInitBasis, sepaExitBasis, sepaInitsolBasis, sepaExitsolBasis, sepaExeclpBasis, sepaExecsolBasis,\n         sepadata) );\n\n   /* add basis separator parameters */\n   SCIP_CALL( SCIPaddBoolParam(GCGmasterGetOrigprob(scip), \"sepa/basis/enable\", \"is basis separator enabled?\",\n         &(sepadata->enable), FALSE, TRUE, NULL, NULL) );\n   SCIP_CALL( SCIPaddBoolParam(GCGmasterGetOrigprob(scip), \"sepa/basis/enableobj\", \"is objective constraint of separator enabled?\",\n         &(sepadata->enableobj), FALSE, FALSE, NULL, NULL) );\n   SCIP_CALL( SCIPaddBoolParam(GCGmasterGetOrigprob(scip), \"sepa/basis/enableobjround\", \"round obj rhs/lhs of obj constraint if obj is int?\",\n         &(sepadata->enableobjround), FALSE, FALSE, NULL, NULL) );\n   SCIP_CALL( SCIPaddBoolParam(GCGmasterGetOrigprob(scip), \"sepa/basis/enableppcuts\", \"add cuts generated during pricing to newconss array?\",\n         &(sepadata->enableppcuts), FALSE, FALSE, NULL, NULL) );\n   SCIP_CALL( SCIPaddBoolParam(GCGmasterGetOrigprob(scip), \"sepa/basis/enableppobjconss\", \"is objective constraint for redcost of each pp of \"\n      \"separator enabled?\", &(sepadata->enableppobjconss), FALSE, FALSE, NULL, NULL) );\n   SCIP_CALL( SCIPaddBoolParam(GCGmasterGetOrigprob(scip), \"sepa/basis/enableppobjcg\", \"is objective constraint for redcost of each pp during \"\n      \"pricing of separator enabled?\", &(sepadata->enableppobjcg), FALSE, FALSE, NULL, NULL) );\n   SCIP_CALL( SCIPaddBoolParam(GCGmasterGetOrigprob(scip), \"sepa/basis/genobjconvex\", \"generated obj convex dynamically\",\n         &(sepadata->genobjconvex), FALSE, FALSE, NULL, NULL) );\n   SCIP_CALL( SCIPaddBoolParam(GCGmasterGetOrigprob(scip), \"sepa/basis/enableposslack\", \"should positive slack influence the probing objective \"\n      \"function?\", &(sepadata->enableposslack), FALSE, FALSE, NULL, NULL) );\n   SCIP_CALL( SCIPaddIntParam(GCGmasterGetOrigprob(scip), \"sepa/basis/posslackexp\", \"exponent of positive slack usage\",\n         &(sepadata->posslackexp), FALSE, 1, 1, INT_MAX, NULL, NULL) );\n   SCIP_CALL( SCIPaddBoolParam(GCGmasterGetOrigprob(scip), \"sepa/basis/posslackexpgen\", \"automatically generated exponent?\",\n            &(sepadata->posslackexpgen), FALSE, FALSE, NULL, NULL) );\n   SCIP_CALL( SCIPaddRealParam(GCGmasterGetOrigprob(scip), \"sepa/basis/posslackexpgenfactor\", \"factor for automatically generated exponent\",\n            &(sepadata->posslackexpgenfactor), FALSE, 0.1, SCIPepsilon(GCGmasterGetOrigprob(scip)),\n            SCIPinfinity(GCGmasterGetOrigprob(scip)), NULL, NULL) );\n   SCIP_CALL( SCIPaddRealParam(GCGmasterGetOrigprob(scip), \"sepa/basis/objconvex\", \"convex combination factor\",\n         &(sepadata->objconvex), FALSE, 1.0, 0.0, 1.0, NULL, NULL) );\n   SCIP_CALL( SCIPaddIntParam(GCGmasterGetOrigprob(scip), \"sepa/basis/paramsetting\", \"parameter returns which parameter setting is used for \"\n      \"separation (default = 0, aggressive = 1, fast = 2\", &(sepadata->separationsetting), FALSE, 1, 0, 2, NULL, NULL) );\n   SCIP_CALL( SCIPaddBoolParam(GCGmasterGetOrigprob(scip), \"sepa/basis/chgobj\", \"parameter returns if basis is searched with different objective\",\n      &(sepadata->chgobj), FALSE, TRUE, NULL, NULL) );\n   SCIP_CALL( SCIPaddIntParam(GCGmasterGetOrigprob(scip), \"sepa/basis/iterations\", \"parameter returns if number new rows adding\"\n      \"iterations (rows just cut off probing lp sol)\", &(sepadata->iterations), FALSE, 100, 1, 10000000 , NULL, NULL) );\n   SCIP_CALL( SCIPaddIntParam(GCGmasterGetOrigprob(scip), \"sepa/basis/mincuts\", \"parameter returns number of minimum cuts needed to \"\n      \"return *result = SCIP_Separated\", &(sepadata->mincuts), FALSE, 1, 1, 100, NULL, NULL) );\n   SCIP_CALL( SCIPaddBoolParam(GCGmasterGetOrigprob(scip), \"sepa/basis/chgobjallways\", \"parameter returns if obj is changed not only in the \"\n      \"first iteration\", &(sepadata->chgobjallways), FALSE, FALSE, NULL, NULL) );\n   SCIP_CALL( SCIPaddBoolParam(GCGmasterGetOrigprob(scip), \"sepa/basis/forcecuts\", \"parameter returns if cuts are forced to enter the LP \",\n      &(sepadata->forcecuts), FALSE, FALSE, NULL, NULL) );\n\n   return SCIP_OKAY;\n}\n\n\n/** returns the array of original cuts saved in the separator data */\nSCIP_ROW** GCGsepaBasisGetOrigcuts(\n   SCIP*                 scip                /**< SCIP data structure */\n   )\n{\n   SCIP_SEPA* sepa;\n   SCIP_SEPADATA* sepadata;\n\n   assert(scip != NULL);\n\n   sepa = SCIPfindSepa(scip, SEPA_NAME);\n   assert(sepa != NULL);\n\n   sepadata = SCIPsepaGetData(sepa);\n   assert(sepadata != NULL);\n\n   return sepadata->origcuts;\n}\n\n/** returns the number of original cuts saved in the separator data */\nint GCGsepaBasisGetNOrigcuts(\n   SCIP*                 scip                /**< SCIP data structure */\n   )\n{\n   SCIP_SEPA* sepa;\n   SCIP_SEPADATA* sepadata;\n\n   assert(scip != NULL);\n\n   sepa = SCIPfindSepa(scip, SEPA_NAME);\n   assert(sepa != NULL);\n\n   sepadata = SCIPsepaGetData(sepa);\n   assert(sepadata != NULL);\n\n   return sepadata->norigcuts;\n}\n\n/** returns the array of master cuts saved in the separator data */\nSCIP_ROW** GCGsepaBasisGetMastercuts(\n   SCIP*                 scip                /**< SCIP data structure */\n   )\n{\n   SCIP_SEPA* sepa;\n   SCIP_SEPADATA* sepadata;\n\n   assert(scip != NULL);\n\n   sepa = SCIPfindSepa(scip, SEPA_NAME);\n   assert(sepa != NULL);\n\n   sepadata = SCIPsepaGetData(sepa);\n   assert(sepadata != NULL);\n\n   return sepadata->mastercuts;\n}\n\n/** returns the number of master cuts saved in the separator data */\nint GCGsepaBasisGetNMastercuts(\n   SCIP*                 scip                /**< SCIP data structure */\n   )\n{\n   SCIP_SEPA* sepa;\n   SCIP_SEPADATA* sepadata;\n\n   assert(scip != NULL);\n\n   sepa = SCIPfindSepa(scip, SEPA_NAME);\n   assert(sepa != NULL);\n\n   sepadata = SCIPsepaGetData(sepa);\n   assert(sepadata != NULL);\n\n   return sepadata->nmastercuts;\n}\n\n/** transforms cut in pricing variables to cut in original variables and adds it to newcuts array */\nSCIP_RETCODE GCGsepaBasisAddPricingCut(\n   SCIP*                scip,\n   int                  ppnumber,\n   SCIP_ROW*            cut\n   )\n{\n   SCIP* origscip;\n   SCIP_SEPA* sepa;\n   SCIP_SEPADATA* sepadata;\n\n   SCIP* pricingprob;\n   SCIP_Real* vals;\n   SCIP_COL** cols;\n   SCIP_VAR** pricingvars;\n   int nvars;\n\n   int i;\n   int j;\n   int k;\n\n   char name[SCIP_MAXSTRLEN];\n\n   assert(GCGisMaster(scip));\n\n   sepa = SCIPfindSepa(scip, SEPA_NAME);\n\n   if( sepa == NULL )\n   {\n      SCIPerrorMessage(\"sepa basis not found\\n\");\n      return SCIP_OKAY;\n   }\n\n   sepadata = SCIPsepaGetData(sepa);\n   origscip = GCGmasterGetOrigprob(scip);\n   pricingprob = GCGgetPricingprob(origscip, ppnumber);\n\n   if( !sepadata->enableppcuts )\n   {\n      return SCIP_OKAY;\n   }\n\n   assert(!SCIProwIsLocal(cut));\n\n   nvars = SCIProwGetNNonz(cut);\n   cols = SCIProwGetCols(cut);\n   vals = SCIProwGetVals(cut);\n\n   if( nvars == 0 )\n   {\n      return SCIP_OKAY;\n   }\n\n   SCIP_CALL( SCIPallocMemoryArray(scip, &pricingvars, nvars) );\n\n   for( i = 0; i < nvars; ++i )\n   {\n      pricingvars[i] = SCIPcolGetVar(cols[i]);\n      assert(pricingvars[i] != NULL);\n   }\n\n   for( k = 0; k < GCGgetNIdenticalBlocks(origscip, ppnumber); ++k )\n   {\n      SCIP_ROW* origcut;\n\n      (void) SCIPsnprintf(name, SCIP_MAXSTRLEN, \"ppcut_%d_%d_%d\", SCIPsepaGetNCalls(sepa), ppnumber, k);\n\n      SCIP_CALL( SCIPcreateEmptyRowUnspec(origscip, &origcut, name,\n         ( SCIPisInfinity(pricingprob, -SCIProwGetLhs(cut)) ?\n            -SCIPinfinity(origscip) : SCIProwGetLhs(cut) - SCIProwGetConstant(cut)),\n         ( SCIPisInfinity(pricingprob, SCIProwGetRhs(cut)) ?\n            SCIPinfinity(origscip) : SCIProwGetRhs(cut) - SCIProwGetConstant(cut)),\n             FALSE, FALSE, TRUE) );\n\n      for( j = 0; j < nvars ; ++j )\n      {\n         SCIP_VAR* var;\n\n         if( !GCGvarIsPricing(pricingvars[j]) )\n         {\n            nvars = 0;\n            break;\n         }\n         assert(GCGvarIsPricing(pricingvars[j]));\n\n         var = GCGpricingVarGetOrigvars(pricingvars[j])[k];\n         assert(var != NULL);\n\n         SCIP_CALL( SCIPaddVarToRow(origscip, origcut, var, vals[j]) );\n      }\n\n      if( nvars > 0 )\n      {\n         SCIP_CALL( ensureSizeNewCuts(scip, sepadata, sepadata->nnewcuts + 1) );\n\n         sepadata->newcuts[sepadata->nnewcuts] = origcut;\n         SCIP_CALL( SCIPcaptureRow(scip, sepadata->newcuts[sepadata->nnewcuts]) );\n         ++(sepadata->nnewcuts);\n\n         SCIPdebugMessage(\"cut added to orig cut pool\\n\");\n      }\n      SCIP_CALL( SCIPreleaseRow(origscip, &origcut) );\n   }\n\n   SCIPfreeMemoryArray(scip, &pricingvars);\n\n   return SCIP_OKAY;\n}\n\n/** add cuts which are due to the latest objective function of the pricing problems\n *  (reduced cost non-negative) */\nSCIP_RETCODE SCIPsepaBasisAddPPObjConss(\n   SCIP*                scip,               /**< SCIP data structure */\n   int                  ppnumber,           /**< number of pricing problem */\n   SCIP_Real            dualsolconv,        /**< dual solution corresponding to convexity constraint */\n   SCIP_Bool            newcuts             /**< add cut to newcuts in sepadata? (otherwise add it just to the cutpool) */\n)\n{\n   SCIP_SEPA* sepa;\n\n   assert(GCGisMaster(scip));\n\n   sepa = SCIPfindSepa(scip, SEPA_NAME);\n\n   if( sepa == NULL )\n   {\n      SCIPerrorMessage(\"sepa basis not found\\n\");\n      return SCIP_OKAY;\n   }\n\n   SCIP_CALL( addPPObjConss(GCGmasterGetOrigprob(scip), sepa, ppnumber, dualsolconv, newcuts, FALSE) );\n\n   return SCIP_OKAY;\n}\n", "meta": {"hexsha": "8adc30080a29fdedeaa77550e91be81b527cb1a2", "size": 58124, "ext": "c", "lang": "C", "max_stars_repo_path": "lib/scipoptsuite-5.0.1/gcg/src/sepa_basis.c", "max_stars_repo_name": "npwebste/UPS_Controller", "max_stars_repo_head_hexsha": "a90ce2229108197fd48f956310ae2929e0fa5d9a", "max_stars_repo_licenses": ["AFL-1.1"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/scipoptsuite-5.0.1/gcg/src/sepa_basis.c", "max_issues_repo_name": "npwebste/UPS_Controller", "max_issues_repo_head_hexsha": "a90ce2229108197fd48f956310ae2929e0fa5d9a", "max_issues_repo_licenses": ["AFL-1.1"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/scipoptsuite-5.0.1/gcg/src/sepa_basis.c", "max_forks_repo_name": "npwebste/UPS_Controller", "max_forks_repo_head_hexsha": "a90ce2229108197fd48f956310ae2929e0fa5d9a", "max_forks_repo_licenses": ["AFL-1.1"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9889928453, "max_line_length": 149, "alphanum_fraction": 0.6158557567, "num_tokens": 15430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.03021458510256423, "lm_q1q2_score": 0.013929430712242043}}
{"text": "\n// Licensed under the Apache License, Version 2.0 (the 'License');\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an 'AS IS' BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//\n// Copyright 2005-2016 Brian Roark and Google, Inc.\n// Classes to generate random sentences from an LM or more generally\n// paths through any FST where epsilons are treated as failure transitions.\n\n#ifndef NGRAM_NGRAM_RANDGEN_H_\n#define NGRAM_NGRAM_RANDGEN_H_\n\n#include <sys/types.h>\n#include <unistd.h>\n\n#include <vector>\n\n// Faster multinomial sampling possible if Gnu Scientific Library available.\n#ifdef HAVE_GSL\n#include <gsl/gsl_randist.h>\n#include <gsl/gsl_rng.h>\n#endif  // HAVE_GSL\n\n#include <fst/fst.h>\n#include <fst/randgen.h>\n#include <ngram/util.h>\n\nnamespace ngram {\n\nusing fst::Fst;\nusing fst::ArcIterator;\nusing fst::LogWeight;\nusing fst::Log64Weight;\n\n// Same as FastLogProbArcSelector but treats *all* epsilons as\n// failure transitions that have a backoff weight. The LM must\n// be fully normalized.\ntemplate <class A>\nclass NGramArcSelector {\n public:\n  typedef typename A::StateId StateId;\n  typedef typename A::Weight Weight;\n\n  explicit NGramArcSelector(int seed = time(0) + getpid()) : seed_(seed) {\n    srand(seed);\n  }\n\n  // Samples one transition.\n  size_t operator()(const Fst<A> &fst, StateId s, double total_prob,\n                    fst::CacheLogAccumulator<A> *accumulator) const {\n    double r = rand() / (RAND_MAX + 1.0);\n    // In effect, subtract out excess mass from the cumulative distribution.\n    // Requires the backoff epsilon be the initial transition.\n    double z = r + total_prob - 1.0;\n    if (z <= 0.0) return 0;\n    ArcIterator<Fst<A> > aiter(fst, s);\n    return accumulator->LowerBound(-log(z), &aiter);\n  }\n\n  int Seed() const { return seed_; }\n\n private:\n  int seed_;\n  fst::WeightConvert<Weight, LogWeight> to_log_weight_;\n};\n\n}  // namespace ngram\n\nnamespace fst {\n\n// Specialization for NGramArcSelector.\ntemplate <class A>\nclass ArcSampler<A, ngram::NGramArcSelector<A> > {\n public:\n  typedef ngram::NGramArcSelector<A> S;\n  typedef typename A::StateId StateId;\n  typedef typename A::Weight Weight;\n  typedef typename A::Label Label;\n  typedef CacheLogAccumulator<A> C;\n\n  ArcSampler(const Fst<A> &fst, const S &arc_selector, int max_length = INT_MAX)\n      : fst_(fst),\n        arc_selector_(arc_selector),\n        max_length_(max_length),\n        matcher_(fst_, MATCH_INPUT) {\n    // Ensure the input FST has any epsilons as the initial transitions.\n    if (!fst_.Properties(kILabelSorted, true))\n      NGRAMERROR() << \"ArcSampler:  is not input-label sorted\";\n    accumulator_.reset(new C());\n    accumulator_->Init(fst);\n#ifdef HAVE_GSL\n    rng_ = gsl_rng_alloc(gsl_rng_taus);\n    gsl_rng_set(rng_, arc_selector.Seed());\n#endif  // HAVE_GSL\n  }\n\n  ArcSampler(const ArcSampler<A, S> &sampler, const Fst<A> *fst = 0)\n      : fst_(fst ? *fst : sampler.fst_),\n        arc_selector_(sampler.arc_selector_),\n        max_length_(sampler.max_length_),\n        matcher_(fst_, MATCH_INPUT) {\n    if (fst) {\n      accumulator_.reset(new C());\n      accumulator_->Init(*fst);\n    } else {  // shallow copy\n      accumulator_.reset(new C(*sampler.accumulator_));\n    }\n  }\n\n  ~ArcSampler() {\n#ifdef HAVE_GSL\n    gsl_rng_free(rng_);\n#endif  // HAVE_GSL\n  }\n\n  bool Sample(const RandState<A> &rstate) {\n    sample_map_.clear();\n    forbidden_labels_.clear();\n\n    if ((fst_.NumArcs(rstate.state_id) == 0 &&\n         fst_.Final(rstate.state_id) == Weight::Zero()) ||\n        rstate.length == max_length_) {\n      Reset();\n      return false;\n    }\n\n    double total_prob = TotalProb(rstate.state_id);\n\n#ifdef HAVE_GSL\n    if (fst_.NumArcs(rstate.state_id) + 1 < rstate.nsamples) {\n      Weight numer_weight, denom_weight;\n      BackoffWeight(rstate.state_id, total_prob, &numer_weight, &denom_weight);\n      MultinomialSample(rstate, numer_weight);\n      Reset();\n      return true;\n    }\n#endif  // HAVE_GSL\n\n    ArcIterator<Fst<A> > aiter(fst_, rstate.state_id);\n\n    for (size_t i = 0; i < rstate.nsamples; ++i) {\n      size_t pos = 0;\n      Label label = kNoLabel;\n      do {\n        pos = arc_selector_(fst_, rstate.state_id, total_prob,\n                            accumulator_.get());\n        if (pos < fst_.NumArcs(rstate.state_id)) {\n          aiter.Seek(pos);\n          label = aiter.Value().ilabel;\n        } else {\n          label = kNoLabel;\n        }\n      } while (ForbiddenLabel(label, rstate));\n      ++sample_map_[pos];\n    }\n    Reset();\n    return true;\n  }\n\n  bool Done() const { return sample_iter_ == sample_map_.end(); }\n  void Next() { ++sample_iter_; }\n  std::pair<size_t, size_t> Value() const { return *sample_iter_; }\n  void Reset() { sample_iter_ = sample_map_.begin(); }\n  bool Error() const { return false; }\n\n private:\n  double TotalProb(StateId s) {\n    // Get cumulative weight at the state.\n    ArcIterator<Fst<A> > aiter(fst_, s);\n    accumulator_->SetState(s);\n    Weight total_weight =\n        accumulator_->Sum(fst_.Final(s), &aiter, 0, fst_.NumArcs(s));\n    return exp(-to_log_weight_(total_weight).Value());\n  }\n\n  void BackoffWeight(StateId s, double total_prob, Weight *numer_weight,\n                     Weight *denom_weight);\n\n#ifdef HAVE_GSL\n  void MultinomialSample(const RandState<A> &rstate, Weight fail_weight);\n#endif  // HAVE_GSL\n\n  bool ForbiddenLabel(Label l, const RandState<A> &rstate);\n\n  const Fst<A> &fst_;\n  const S &arc_selector_;\n  int max_length_;\n\n  // Stores (N, K) as described for Value().\n  std::map<size_t, size_t> sample_map_;\n  std::map<size_t, size_t>::const_iterator sample_iter_;\n  std::unique_ptr<C> accumulator_;\n\n#ifdef HAVE_GSL\n  gsl_rng *rng_;              // GNU Sci Lib random number generator\n  vector<double> pr_;         // multinomial parameters\n  vector<unsigned int> pos_;  // sample positions\n  vector<unsigned int> n_;    // sample counts\n#endif                        // HAVE_GSL\n\n  WeightConvert<Log64Weight, Weight> to_weight_;\n  WeightConvert<Weight, Log64Weight> to_log_weight_;\n  std::set<Label>\n      forbidden_labels_;  // labels forbidden for failure transitions\n  Matcher<Fst<A> > matcher_;\n};\n\n// Finds and decomposes the backoff probability into its numerator and\n// denominator.\ntemplate <class A>\nvoid ArcSampler<A, ngram::NGramArcSelector<A> >::BackoffWeight(\n    StateId s, double total, Weight *numer_weight, Weight *denom_weight) {\n  // Get backoff prob.\n  double backoff = 0.0;\n  matcher_.SetState(s);\n  matcher_.Find(0);\n  for (; !matcher_.Done(); matcher_.Next()) {\n    const A &arc = matcher_.Value();\n    if (arc.ilabel != kNoLabel) {  // not an implicit epsilon loop\n      backoff = exp(-to_log_weight_(arc.weight).Value());\n      break;\n    }\n  }\n\n  if (backoff == 0.0) {  // no backoff transition\n    *numer_weight = Weight::Zero();\n    *denom_weight = Weight::Zero();\n    return;\n  }\n\n  // total = 1 - numer + backoff\n  double numer = 1.0 + backoff - total;\n  *numer_weight = to_weight_(-log(numer));\n\n  // backoff = numer/denom\n  double denom = numer / backoff;\n  *denom_weight = to_weight_(-log(denom));\n}\n\n#ifdef HAVE_GSL\ntemplate <class A>\nvoid ArcSampler<A, ngram::NGramArcSelector<A> >::MultinomialSample(\n    const RandState<A> &rstate, Weight fail_weight) {\n  pr_.clear();\n  pos_.clear();\n  n_.clear();\n  size_t pos = 0;\n  for (ArcIterator<Fst<A> > aiter(fst_, rstate.state_id); !aiter.Done();\n       aiter.Next(), ++pos) {\n    const A &arc = aiter.Value();\n    if (!ForbiddenLabel(arc.ilabel, rstate)) {\n      pos_.push_back(pos);\n      Weight weight = arc.ilabel == 0 ? fail_weight : arc.weight;\n      pr_.push_back(exp(-to_log_weight_(weight).Value()));\n    }\n  }\n  if (fst_.Final(rstate.state_id) != Weight::Zero() &&\n      !ForbiddenLabel(kNoLabel, rstate)) {\n    pos_.push_back(pos);\n    pr_.push_back(exp(-to_log_weight_(fst_.Final(rstate.state_id)).Value()));\n  }\n\n  if (rstate.nsamples < UINT_MAX) {\n    n_.resize(pr_.size());\n    gsl_ran_multinomial(rng_, pr_.size(), rstate.nsamples, &(pr_[0]), &(n_[0]));\n    for (size_t i = 0; i < n_.size(); ++i)\n      if (n_[i] != 0) sample_map_[pos_[i]] = n_[i];\n  } else {\n    for (size_t i = 0; i < pr_.size(); ++i)\n      sample_map_[pos_[i]] = ceil(pr_[i] * rstate.nsamples);\n  }\n}\n#endif  // HAVE_GSL\n\ntemplate <class A>\nbool ArcSampler<A, ngram::NGramArcSelector<A> >::ForbiddenLabel(\n    Label l, const RandState<A> &rstate) {\n  if (l == 0) return false;\n\n  if (fst_.NumArcs(rstate.state_id) > rstate.nsamples) {\n    for (const RandState<A> *rs = &rstate; rs->parent != 0; rs = rs->parent) {\n      StateId parent_id = rs->parent->state_id;\n      ArcIterator<Fst<A> > aiter(fst_, parent_id);\n      aiter.Seek(rs->select);\n      if (aiter.Value().ilabel != 0)  // not backoff transition\n        return false;\n\n      if (l == kNoLabel) {  // super-final label\n        return fst_.Final(parent_id) != Weight::Zero();\n      } else {\n        matcher_.SetState(parent_id);\n        if (matcher_.Find(l)) return true;\n      }\n    }\n    return false;\n  } else {\n    if (forbidden_labels_.empty()) {\n      for (const RandState<A> *rs = &rstate; rs->parent != 0; rs = rs->parent) {\n        StateId parent_id = rs->parent->state_id;\n        ArcIterator<Fst<A> > aiter(fst_, parent_id);\n        aiter.Seek(rs->select);\n        if (aiter.Value().ilabel != 0)  // not backoff transition\n          break;\n\n        for (aiter.Reset(); !aiter.Done(); aiter.Next()) {\n          Label l = aiter.Value().ilabel;\n          if (l != 0) forbidden_labels_.insert(l);\n        }\n\n        if (fst_.Final(parent_id) != Weight::Zero())\n          forbidden_labels_.insert(kNoLabel);\n      }\n    }\n    return forbidden_labels_.count(l) > 0;\n  }\n}\n\n}  // namespace fst\n\n#endif  // NGRAM_NGRAM_RANDGEN_H_\n", "meta": {"hexsha": "eacb75b2f49154d3127f826748c81713c3824ac3", "size": 10053, "ext": "h", "lang": "C", "max_stars_repo_path": "src/include/ngram/ngram-randgen.h", "max_stars_repo_name": "unixnme/opengrm_ngram", "max_stars_repo_head_hexsha": "ce9b55b406c681902a20c4b547bdd254a8a399e7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-11T00:44:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-11T00:44:55.000Z", "max_issues_repo_path": "src/include/ngram/ngram-randgen.h", "max_issues_repo_name": "unixnme/opengrm_ngram", "max_issues_repo_head_hexsha": "ce9b55b406c681902a20c4b547bdd254a8a399e7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/include/ngram/ngram-randgen.h", "max_forks_repo_name": "unixnme/opengrm_ngram", "max_forks_repo_head_hexsha": "ce9b55b406c681902a20c4b547bdd254a8a399e7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.556231003, "max_line_length": 80, "alphanum_fraction": 0.6512483836, "num_tokens": 2762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.028007523344164863, "lm_q1q2_score": 0.01389435950980292}}
{"text": "#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n#include <string.h>\n#include <sys/stat.h>\n#include <sys/time.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n#include <Accelerate/Accelerate.h>\n\n#include \"infmcmc.h\"\n\n#define nj1 32\n#define nk1 32\n\nvoid infmcmc_initChain(INFCHAIN *C, const int nj, const int nk) {\n  const int maxk      = (nk >> 1) + 1;\n  const int sspectral = sizeof(fftw_complex) * nj * maxk;\n  const int sphysical = sizeof(double      ) * nj * nk;\n  //const int obsVecMem = sizeof(double      ) * sizeObsVector;\n  FILE *fp;\n  unsigned long int seed;\n  \n  // Set up variables\n  C->nj = nj;\n  C->nk = nk;\n  //C->sizeObsVector = sizeObsVector;\n  C->currentIter = 0;\n  C->accepted = 0;\n  C->_shortTimeAccProbAvg = 0.0;\n  C->_bLow = 0.0;\n  C->_bHigh = 1.0;\n  \n  // Allocate a ton of memory\n  C->currentPhysicalState      = (double *)malloc(sphysical);\n  C->avgPhysicalState          = (double *)malloc(sphysical);\n  C->varPhysicalState          = (double *)malloc(sphysical);\n  C->proposedPhysicalState     = (double *)malloc(sphysical);\n  C->_M2                       = (double *)malloc(sphysical);\n  //C->currentStateObservations  = (double *)malloc(obsVecMem);\n  //C->proposedStateObservations = (double *)malloc(obsVecMem);\n  //C->data                      = (double *)malloc(obsVecMem);\n  \n  C->currentSpectralState  = (fftw_complex *)fftw_malloc(sspectral);\n  C->avgSpectralState      = (fftw_complex *)fftw_malloc(sspectral);\n  C->priorDraw             = (fftw_complex *)fftw_malloc(sspectral);\n  C->proposedSpectralState = (fftw_complex *)fftw_malloc(sspectral);\n  \n  memset(C->currentPhysicalState,  0, sphysical);\n  memset(C->avgPhysicalState,      0, sphysical);\n  memset(C->varPhysicalState,      0, sphysical);\n  memset(C->proposedPhysicalState, 0, sphysical);\n  memset(C->_M2,                   0, sphysical);\n  memset(C->currentSpectralState,  0, sspectral);\n  memset(C->avgSpectralState,      0, sspectral);\n  memset(C->proposedSpectralState, 0, sspectral);\n  \n  C->accProb = 0.0;\n  C->avgAccProb = 0.0;\n  C->logLHDCurrentState = 0.0;\n  \n  /*\n   * Set some default values\n   */\n  C->alphaPrior = 3.0;\n  C->rwmhStepSize = 1e-4;\n  C->priorVar = 1.0;\n  C->priorStd = 1.0;\n  \n  C->r = gsl_rng_alloc(gsl_rng_taus2);\n  \n  fp = fopen(\"/dev/urandom\", \"rb\");\n  \n  if (fp != NULL) {\n    fread(&seed, sizeof(unsigned long int), 1, fp);\n    gsl_rng_set(C->r, seed);\n    fclose(fp);\n    printf(\"Using random seed\\n\");\n  }\n  else {\n    gsl_rng_set(C->r, 0);\n    printf(\"Using zero seed\\n\");\n  }\n  \n  C->_c2r = fftw_plan_dft_c2r_2d(nj, nk, C->proposedSpectralState, C->proposedPhysicalState, FFTW_MEASURE);\n  C->_r2c = fftw_plan_dft_r2c_2d(nj, nk, C->currentPhysicalState, C->currentSpectralState, FFTW_MEASURE);\n}\n\nvoid infmcmc_freeChain(INFCHAIN *C) {\n  // Free all allocated memory used by the chain\n  free(C->currentPhysicalState);\n  free(C->avgPhysicalState);\n  free(C->varPhysicalState);\n  free(C->proposedPhysicalState);\n  free(C->_M2);\n  //free(C->currentStateObservations);\n  //free(C->proposedStateObservations);\n  \n  fftw_free(C->currentSpectralState);\n  fftw_free(C->avgSpectralState);\n  fftw_free(C->priorDraw);\n  fftw_free(C->proposedSpectralState);\n  \n  gsl_rng_free(C->r);\n}\n\nvoid infmcmc_resetChain(INFCHAIN *C) {\n  infmcmc_freeChain(C);\n  infmcmc_initChain(C, C->nj, C->nk);\n}\n\nvoid infmcmc_writeChain(const INFCHAIN *C, FILE *fp) {\n  const int s = C->nj * C->nk;\n  \n  fwrite(&(C->nj),                 sizeof(int),    1,         fp);\n  fwrite(&(C->nk),                 sizeof(int),    1,         fp);\n  fwrite(&(C->currentIter),        sizeof(int),    1,         fp);\n  fwrite(C->currentPhysicalState,  sizeof(double), s,         fp);\n  fwrite(C->avgPhysicalState,      sizeof(double), s,         fp);\n  fwrite(C->varPhysicalState,      sizeof(double), s,         fp);\n  fwrite(&(C->logLHDCurrentState), sizeof(double), 1,         fp);\n  fwrite(&(C->accProb),            sizeof(double), 1,         fp);\n  fwrite(&(C->avgAccProb),         sizeof(double), 1,         fp);\n}\n\nvoid infmcmc_writeChainInfo(const INFCHAIN *C, FILE *fp) {\n  fwrite(&(C->nj),             sizeof(int), 1, fp);\n  fwrite(&(C->nk),             sizeof(int), 1, fp);\n}\n\nvoid infmcmc_writeVFChain(const INFCHAIN *U, const INFCHAIN *V, FILE *fp) {\n  const int s = U->nj * U->nk;\n  \n  fwrite(U->currentPhysicalState,  sizeof(double), s,         fp);\n  fwrite(U->avgPhysicalState,      sizeof(double), s,         fp);\n  fwrite(U->varPhysicalState,      sizeof(double), s,         fp);\n  fwrite(V->currentPhysicalState,  sizeof(double), s,         fp);\n  fwrite(V->avgPhysicalState,      sizeof(double), s,         fp);\n  fwrite(V->varPhysicalState,      sizeof(double), s,         fp);\n  fwrite(&(U->logLHDCurrentState), sizeof(double), 1,         fp);\n  fwrite(&(U->accProb),            sizeof(double), 1,         fp);\n  fwrite(&(U->avgAccProb),         sizeof(double), 1,         fp);\n}\n\nvoid infmcmc_printChain(INFCHAIN *C) {\n  printf(\"Iteration %d\\n\", C->currentIter);\n  printf(\"-- Length is         %d x %d\\n\", C->nj, C->nk);\n  printf(\"-- llhd val is       %lf\\n\", C->logLHDCurrentState);\n  printf(\"-- Acc. prob is      %.10lf\\n\", C->accProb);\n  printf(\"-- Avg. acc. prob is %.10lf\\n\", C->avgAccProb);\n  printf(\"-- Beta is           %.10lf\\n\\n\", C->rwmhStepSize);\n  //finmcmc_printCurrentState(C);\n  //finmcmc_printAvgState(C);\n  //finmcmc_printVarState(C);\n}\n\nvoid randomPriorDraw(INFCHAIN *C) {\n  int j, k;\n  const int maxk = (C->nk >> 1) + 1;\n  const int nko2 = C->nk >> 1;\n  const int njo2 = C->nj >> 1;\n  double xrand, yrand, c;\n  //const double one = 1.0;\n  \n  c = 4.0 * M_PI * M_PI;\n  \n  for(j = 0; j < C->nj; j++) {\n    for(k = 0; k < maxk; k++) {\n      xrand = gsl_ran_gaussian_ziggurat(C->r, C->priorStd);\n      if((j == 0) && (k == 0)) {\n        C->priorDraw[0] = 0.0;\n      }\n      else if((j == njo2) && (k == nko2)) {\n        C->priorDraw[maxk*njo2+nko2] = /*C->nj */ xrand / pow(c * ((j * j) + (k * k)), (double)C->alphaPrior/2.0);\n      }\n      else if((j == 0) && (k == nko2)) {\n        C->priorDraw[nko2] = /*C->nj */ xrand / pow(c * ((j * j) + (k * k)), (double)C->alphaPrior/2.0);\n      }\n      else if((j == njo2) && (k == 0)) {\n        C->priorDraw[maxk*njo2] = /*C->nj */ xrand / pow(c * ((j * j) + (k * k)), (double)C->alphaPrior/2.0);\n      }\n      else {\n        xrand /= sqrt(2.0);\n        yrand = gsl_ran_gaussian_ziggurat(C->r, C->priorStd) / sqrt(2.0);\n        C->priorDraw[maxk*j+k] = /*C->nj */ (xrand + I * yrand) / pow(c * ((j * j) + (k * k)), (double)C->alphaPrior/2.0);\n        if(j > njo2) {\n          C->priorDraw[maxk*j+k] = conj(C->priorDraw[maxk*(C->nj-j)+k]);\n        }\n      }\n    }\n  }\n}\n\nvoid randomDivFreePriorDraw(INFCHAIN *C1, INFCHAIN *C2) {\n  int j, k;\n  const int maxk = (C1->nk >> 1) + 1;\n  const int njo2 = C2->nj >> 1;\n  const int nko2 = C1->nk >> 1;\n  double modk;\n  \n  randomPriorDraw(C1);\n  \n  for (j = 0; j < C1->nj; j++) {\n    for (k = 0; k < maxk; k++) {\n      if (j == 0 && k == 0) {\n        C1->priorDraw[0] = 0.0;\n        C2->priorDraw[0] = 0.0;\n        continue;\n      }\n      \n      modk = sqrt(j * j + k * k);\n      if (j < njo2) {\n        C2->priorDraw[maxk*j+k] = -j * C1->priorDraw[maxk*j+k] / modk;\n      }\n      else if (j > njo2) {\n        C2->priorDraw[maxk*j+k] = -(j - C1->nj) * C1->priorDraw[maxk*j+k] / modk;\n      }\n      else {\n        C2->priorDraw[maxk*j+k] = 0.0;\n      }\n      \n      if (k < nko2) {\n        C1->priorDraw[maxk*j+k] *= k / modk;\n      }\n      else {\n        C1->priorDraw[maxk*j+k] = 0.0;\n      }\n    }\n  }\n}\n\nvoid infmcmc_seedWithPriorDraw(INFCHAIN *C) {\n  const int size = sizeof(fftw_complex) * C->nj * ((C->nk >> 1) + 1);\n  fftw_complex *uk = (fftw_complex *)fftw_malloc(size);\n  const fftw_plan p = fftw_plan_dft_c2r_2d(C->nj, C->nk, uk, C->currentPhysicalState, FFTW_ESTIMATE);\n  \n  randomPriorDraw(C);\n  memcpy(uk, C->priorDraw, size);\n  \n  //fixme: put into current spectral state\n  \n  fftw_execute(p);\n  fftw_destroy_plan(p);\n  fftw_free(uk);\n}\n\nvoid infmcmc_seedWithDivFreePriorDraw(INFCHAIN *C1, INFCHAIN *C2) {\n  const int size = sizeof(fftw_complex) * C1->nj * ((C1->nk >> 1) + 1);\n  fftw_complex *uk = (fftw_complex *)fftw_malloc(size);\n  const fftw_plan p = fftw_plan_dft_c2r_2d(C1->nj, C1->nk, uk, C1->currentPhysicalState, FFTW_ESTIMATE);\n  \n  randomDivFreePriorDraw(C1, C2);\n  \n  memcpy(uk, C1->priorDraw, size);\n  fftw_execute_dft_c2r(p, uk, C1->currentPhysicalState);\n  \n  memcpy(uk, C2->priorDraw, size);\n  fftw_execute_dft_c2r(p, uk, C2->currentPhysicalState);\n  \n  memcpy(C1->currentSpectralState, C1->priorDraw, size);\n  memcpy(C2->currentSpectralState, C2->priorDraw, size);\n  \n  fftw_destroy_plan(p);\n  fftw_free(uk);\n}\n\nvoid infmcmc_proposeRWMH(INFCHAIN *C) {\n  int j, k;\n  const int maxk = (C->nk >> 1) + 1;\n  const int N = C->nj * C->nk;\n  const double sqrtOneMinusBeta2 = sqrt(1.0 - C->rwmhStepSize * C->rwmhStepSize);\n  double *u = (double *)malloc(sizeof(double) * C->nj * C->nk);\n  fftw_complex *uk = (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * C->nj * maxk);\n  \n  memcpy(u, C->currentPhysicalState, sizeof(double) * C->nj * C->nk);\n  fftw_execute_dft_r2c(C->_r2c, u, C->currentSpectralState);\n  \n  // Draw from prior distribution\n  randomPriorDraw(C);\n  \n  for(j = 0; j < C->nj; j++) {\n    for(k = 0; k < maxk; k++) {\n      C->proposedSpectralState[maxk*j+k] = sqrtOneMinusBeta2 * C->currentSpectralState[maxk*j+k] + C->rwmhStepSize * C->priorDraw[maxk*j+k];\n      C->proposedSpectralState[maxk*j+k] /= N;\n    }\n  }\n  \n  memcpy(uk, C->proposedSpectralState, sizeof(fftw_complex) * C->nj * maxk);\n  fftw_execute_dft_c2r(C->_c2r, uk, C->proposedPhysicalState);\n  fftw_free(uk);\n  free(u);\n}\n\nvoid infmcmc_adaptRWMHStepSize(INFCHAIN *C, double inc) {\n  // Adapt to stay in 20-30% range.\n  int adaptFreq = 100;\n  double rate;\n  \n  if (C->currentIter > 0 && C->currentIter % adaptFreq == 0) {\n    rate = (double) C->_shortTimeAccProbAvg / adaptFreq;\n    \n    if (rate < 0.2) {\n      //C->_bHigh = C->rwmhStepSize;\n      //C->rwmhStepSize = (C->_bLow + C->_bHigh) / 2.0;\n      C->rwmhStepSize -= inc;\n    }\n    else if (rate > 0.3) {\n      //C->_bLow = C->rwmhStepSize;\n      //C->rwmhStepSize = (C->_bLow + C->_bHigh) / 2.0;\n      C->rwmhStepSize += inc;\n    }\n    \n    C->_shortTimeAccProbAvg = 0.0;\n  }\n  else {\n    C->_shortTimeAccProbAvg += C->accProb;\n  }\n}\n\nvoid infmcmc_proposeDivFreeRWMH(INFCHAIN *C1, INFCHAIN *C2) {\n  int j, k;\n  const int maxk = (C1->nk >> 1) + 1;\n  const int N = C1->nj * C1->nk;\n  const double sqrtOneMinusBeta2 = sqrt(1.0 - C1->rwmhStepSize * C1->rwmhStepSize);\n  double *u = (double *)malloc(sizeof(double) * C1->nj * C1->nk);\n  fftw_complex *uk = (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * C1->nj * maxk);\n  \n  memcpy(u, C1->currentPhysicalState, sizeof(double) * C1->nj * C1->nk);\n  fftw_execute_dft_r2c(C1->_r2c, u, C1->currentSpectralState);\n  \n  memcpy(u, C2->currentPhysicalState, sizeof(double) * C2->nj * C2->nk);\n  fftw_execute_dft_r2c(C2->_r2c, u, C2->currentSpectralState);\n    \n  // Draw from prior distribution\n  randomDivFreePriorDraw(C1, C2);\n  \n  for(j = 0; j < C1->nj; j++) {\n    for(k = 0; k < maxk; k++) {\n      C1->currentSpectralState[maxk*j+k] /= N;\n      C2->currentSpectralState[maxk*j+k] /= N;\n      C1->proposedSpectralState[maxk*j+k] = sqrtOneMinusBeta2 * C1->currentSpectralState[maxk*j+k] + C1->rwmhStepSize * C1->priorDraw[maxk*j+k];\n      //C1->proposedSpectralState[maxk*j+k] /= N;\n      C2->proposedSpectralState[maxk*j+k] = sqrtOneMinusBeta2 * C2->currentSpectralState[maxk*j+k] + C2->rwmhStepSize * C2->priorDraw[maxk*j+k];\n      //C2->proposedSpectralState[maxk*j+k] /= N;\n    }\n  }\n  \n  memcpy(uk, C1->proposedSpectralState, sizeof(fftw_complex) * C1->nj * maxk);\n  fftw_execute_dft_c2r(C1->_c2r, uk, C1->proposedPhysicalState);\n  memcpy(uk, C2->proposedSpectralState, sizeof(fftw_complex) * C1->nj * maxk);\n  fftw_execute_dft_c2r(C2->_c2r, uk, C2->proposedPhysicalState);\n  \n  fftw_free(uk);\n  free(u);\n}\n\nvoid infmcmc_updateAvgs(INFCHAIN *C) {\n  int j, k;\n  double deltar;\n  fftw_complex deltac;\n  C->currentIter++;\n  \n  /*\n   Update physical vectors\n   */\n  if (C->currentIter == 1) {\n    for (j = 0; j < C->nj; j++) {\n      for (k = 0; k < C->nk; k++) {\n        deltar = C->currentPhysicalState[C->nk * j + k] - C->avgPhysicalState[C->nk * j + k];\n        C->avgPhysicalState[C->nk * j + k] += (deltar / C->currentIter);\n        C->_M2[C->nk * j + k] += (deltar * (C->currentPhysicalState[C->nk * j + k] - C->avgPhysicalState[C->nk * j + k]));\n        C->varPhysicalState[C->nk * j + k] = -1.0;\n      }\n    }\n  }\n  else {\n    for (j = 0; j < C->nj; j++) {\n      for (k = 0; k < C->nk; k++) {\n        deltar = C->currentPhysicalState[C->nk * j + k] - C->avgPhysicalState[C->nk * j + k];\n        C->avgPhysicalState[C->nk * j + k] += (deltar / C->currentIter);\n        C->_M2[C->nk * j + k] += (deltar * (C->currentPhysicalState[C->nk * j + k] - C->avgPhysicalState[C->nk * j + k]));\n        C->varPhysicalState[C->nk * j + k] = C->_M2[C->nk * j + k] / (C->currentIter - 1);\n      }\n    }\n  }\n  \n  /*\n   Update spectral vectors\n  */\n  if (C->currentIter == 1) {\n    for (j = 0; j < C->nj; j++) {\n      for (k = 0; k < C->nk/2 + 1; k++) {\n        deltac = C->currentSpectralState[(C->nk/2 + 1) * j + k] - C->avgSpectralState[(C->nk/2 + 1) * j + k];\n        C->avgSpectralState[(C->nk/2 + 1) * j + k] += (deltac / C->currentIter);\n      }\n    }\n  }\n  else {\n    for (j = 0; j < C->nj; j++) {\n      for (k = 0; k < C->nk/2 + 1; k++) {\n        deltac = C->currentSpectralState[(C->nk/2 + 1) * j + k] - C->avgSpectralState[(C->nk/2 + 1) * j + k];\n        C->avgSpectralState[(C->nk/2 + 1) * j + k] += (deltac / C->currentIter);\n      }\n    }\n  }\n  \n  /*\n   Update scalars\n   */\n  C->avgAccProb += ((C->accProb - C->avgAccProb) / C->currentIter);\n}\n\nvoid infmcmc_updateRWMH(INFCHAIN *C, double logLHDOfProposal) {\n  double alpha;\n  \n  alpha = exp(C->logLHDCurrentState - logLHDOfProposal);\n  \n  if (alpha > 1.0) {\n    alpha = 1.0;\n  }\n  // fixme: set acc prob here instead\n  if (gsl_rng_uniform(C->r) < alpha) {\n    memcpy(C->currentSpectralState, C->proposedSpectralState, sizeof(fftw_complex) * C->nj * ((C->nk >> 1) + 1));\n    memcpy(C->currentPhysicalState, C->proposedPhysicalState, sizeof(double) * C->nj * C->nk);\n    C->accProb = alpha;\n    C->logLHDCurrentState = logLHDOfProposal;\n  }\n  \n  infmcmc_updateAvgs(C);\n}\n\nvoid infmcmc_updateVectorFieldRWMH(INFCHAIN *C1, INFCHAIN *C2, double logLHDOfProposal) {\n  double alpha;\n  \n  // log likelihoods will be the same for both chains\n\talpha = exp(C1->logLHDCurrentState - logLHDOfProposal);\n\t\n  if (alpha > 1.0) {\n    alpha = 1.0;\n  }\n  \n  C1->accepted = 0;\n  C2->accepted = 0;\n  C1->accProb = alpha;\n  C2->accProb = alpha;\n  \n  if (gsl_rng_uniform(C1->r) < alpha) {\n    C1->accepted = 1;\n    C2->accepted = 1;\n    memcpy(C1->currentSpectralState, C1->proposedSpectralState, sizeof(fftw_complex) * C1->nj * ((C1->nk >> 1) + 1));\n    memcpy(C1->currentPhysicalState, C1->proposedPhysicalState, sizeof(double) * C1->nj * C1->nk);\n    C1->logLHDCurrentState = logLHDOfProposal;\n    memcpy(C2->currentSpectralState, C2->proposedSpectralState, sizeof(fftw_complex) * C2->nj * ((C2->nk >> 1) + 1));\n    memcpy(C2->currentPhysicalState, C2->proposedPhysicalState, sizeof(double) * C2->nj * C2->nk);\n    C2->logLHDCurrentState = logLHDOfProposal;\n  }\n  \n  infmcmc_updateAvgs(C1);\n  infmcmc_updateAvgs(C2);\n}\n\nvoid infmcmc_setRWMHStepSize(INFCHAIN *C, double beta) {\n  C->rwmhStepSize = beta;\n}\n\nvoid infmcmc_setPriorAlpha(INFCHAIN *C, double alpha) {\n  C->alphaPrior = alpha;\n}\n\nvoid infmcmc_setPriorVar(INFCHAIN *C, double var) {\n  C->priorVar = var;\n  C->priorStd = sqrt(var);\n}\n\ndouble L2Field(fftw_complex *uk, int nj, int nk) {\n  int j, k;\n  const int maxk = (nk >> 1) + 1;\n  double sum = 0.0;\n  \n  for (j = 0; j < nj; j++) {\n    for (k = 0; k < maxk; k++) {\n      sum += cabs(uk[maxk*j+k]) * cabs(uk[maxk*j+k]);\n    }\n  }\n  \n  return 2.0 * sum;\n}\n\ndouble infmcmc_L2Current(INFCHAIN *C) {\n  return L2Field(C->currentSpectralState, C->nj, C->nk);\n}\n\ndouble infmcmc_L2Proposed(INFCHAIN *C) {\n  return L2Field(C->proposedSpectralState, C->nj, C->nk);\n}\n\ndouble infmcmc_L2Prior(INFCHAIN *C) {\n  return L2Field(C->priorDraw, C->nj, C->nk);\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nvoid randomPriorDrawOLD(gsl_rng *r, double PRIOR_ALPHA, fftw_complex *randDrawCoeffs) {\n  int j, k;\n  double xrand, yrand, c;//, scale;\n  //const double one = 1.0;\n  \n  c = 4.0 * M_PI * M_PI;\n  \n  for(j = 0; j < nj1; j++) {\n    for(k = 0; k < nk1/2 + 1; k++) {\n      if((j == 0) && (k == 0)) {\n        randDrawCoeffs[0] = 0.0;\n      }\n      else if((j == nj1/2) && (k == nk1/2)) {\n        xrand = gsl_ran_gaussian_ziggurat(r, 1.0);\n        randDrawCoeffs[(nk1/2 + 1) * nj1/2 + nk1/2] = xrand / pow((c * ((j * j) + (k * k))), (double)PRIOR_ALPHA/2.0);\n      }\n      else if((j == 0) && (k == nk1/2)) {\n        xrand = gsl_ran_gaussian_ziggurat(r, 1.0);\n        randDrawCoeffs[nk1/2] = xrand / pow((c * ((j * j) + (k * k))), (double)PRIOR_ALPHA/2.0);\n      }\n      else if((j == nj1/2) && (k == 0)) {\n        xrand = gsl_ran_gaussian_ziggurat(r, 1.0);\n        randDrawCoeffs[(nk1/2 + 1) * nj1/2] = xrand / pow((c * ((j * j) + (k * k))), (double)PRIOR_ALPHA/2.0);\n      }\n      else {\n        xrand = gsl_ran_gaussian_ziggurat(r, 1.0) / sqrt(2.0);\n        yrand = gsl_ran_gaussian_ziggurat(r, 1.0) / sqrt(2.0);\n        randDrawCoeffs[(nk1/2 + 1) * j + k] = (xrand + I * yrand) / pow((c * ((j * j) + (k * k))), (double)PRIOR_ALPHA/2.0);\n        if(j > nj1/2) {\n          randDrawCoeffs[(nk1/2 + 1) * j + k] = conj(randDrawCoeffs[(nk1/2+1)*(nj1-j)+k]);\n        }\n      }\n    }\n  }\n  \n  /*\n  for(j = 1; j < nj1 / 2; j++) {\n    for(k = 0; k < nk1 / 2 + 1; k++) {\n      xrand = gsl_ran_gaussian_ziggurat(r, 1.0) / M_SQRT2;\n      yrand = gsl_ran_gaussian_ziggurat(r, 1.0) / M_SQRT2;\n      scale = pow(c * ((j * j) + (k * k)), (double)PRIOR_ALPHA/2.0);\n      randDrawCoeffs[(nk1/2 + 1) * j + k] = (xrand + I * yrand) / scale;\n      randDrawCoeffs[(nk1/2 + 1) * (nj1-j) + k] = (xrand - I * yrand) / scale;\n    }\n  }\n  \n  for(k = 1; k < nk1 / 2 + 1; k++) {\n    xrand = gsl_ran_gaussian_ziggurat(r, 1.0) / M_SQRT2;\n    randDrawCoeffs[k] = (xrand + I * yrand) / pow(c * (k * k), (double)PRIOR_ALPHA/2.0);\n  }\n  \n  for(k = 0; k < nk1/2; k++) {\n    xrand = gsl_ran_gaussian_ziggurat(r, 1.0) / M_SQRT2;\n    randDrawCoeffs[(nk1/2+1)*(nj1/2)+k] = (xrand + I * yrand) / pow(c * ((nj1 * nj1 / 4) + (k * k)), (double)PRIOR_ALPHA/2.0);\n  }\n  \n  randDrawCoeffs[0] = 0.0;\n  \n  xrand = gsl_ran_gaussian_ziggurat(r, 1.0);\n  randDrawCoeffs[(nk1/2+1)*(nj1/2)+(nk1/2)] = xrand / pow(c * ((j * j) + (k * k)), (double)PRIOR_ALPHA/2.0);\n  */\n}\n\nvoid setRWMHStepSize(CHAIN *C, double stepSize) {\n  C->rwmhStepSize = stepSize;\n}\n\nvoid resetAvgs(CHAIN *C) {\n  /*\n    Sets avgPhysicalState to currentPhysicalState and\n         avgSpectralState to currentSpectralState\n  */\n  const size_t size_doublenj = sizeof(double) * C->nj;\n  memcpy(C->avgPhysicalState, C->currentPhysicalState, size_doublenj * C->nk);\n  memcpy(C->avgSpectralState, C->currentSpectralState, size_doublenj * ((C->nk >> 1) + 1));\n}\n\nvoid resetVar(CHAIN *C) {\n  // Sets varPhysicalState to 0\n  memset(C->varPhysicalState, 0, sizeof(double) * C->nj * C->nk);\n}\n\nvoid proposeIndependence(CHAIN *C) {\n  const int maxk = (C->nk >> 1) + 1;\n  \n  memcpy(C->proposedSpectralState, C->priorDraw, sizeof(fftw_complex) * C->nj * maxk);\n}\n\ndouble lsqFunctional(const double * const data, const double * const obsVec, const int obsVecSize, const double obsStdDev) {\n  int i;\n  double temp1, sum1 = 0.0;\n  \n  for(i = 0; i < obsVecSize; i++) {\n    temp1 = (data[i] - obsVec[i]);\n    sum1 += temp1 * temp1;\n  }\n  \n  return sum1 / (2.0 * obsStdDev * obsStdDev);\n}\n\nvoid acceptReject(CHAIN *C) {\n  const double phi1 = lsqFunctional(C->data, C->currentStateObservations, C->sizeObsVector, C->obsStdDev);\n  const double phi2 = lsqFunctional(C->data, C->proposedStateObservations, C->sizeObsVector, C->obsStdDev);\n  double tempAccProb = exp(phi1 - phi2);\n  \n  if(tempAccProb > 1.0) {\n    tempAccProb = 1.0;\n  }\n  \n  if(gsl_rng_uniform(C->r) < tempAccProb) {\n    memcpy(C->currentSpectralState, C->proposedSpectralState, sizeof(fftw_complex) * C->nj * ((C->nk >> 1) + 1));\n    memcpy(C->currentPhysicalState, C->proposedPhysicalState, sizeof(double) * C->nj * C->nk);\n    memcpy(C->currentStateObservations, C->proposedStateObservations, sizeof(double) * C->sizeObsVector);\n    \n    C->accProb = tempAccProb;\n    C->currentLSQFunctional = phi2;\n  }\n  else {\n    C->currentLSQFunctional = phi1;\n  }\n}\n\n//\n//void updateChain(CHAIN *C) {\n//C->currentIter++;\n//void updateAvgs(CHAIN *C);\n//void updateVar(CHAIN *C);\n/*\nint main(void) {\n  int nj = 32, nk = 32, sizeObsVector = 0;\n  unsigned long int randseed = 0;\n  \n  FILE *fp;\n  CHAIN *C;\n  \n  C = (CHAIN *)malloc(sizeof(CHAIN));\n  \n  initChain(C, nj, nk, sizeObsVector, randseed);\n  \n  randomPriorDraw2(C);\n  \n  fp = fopen(\"2.dat\", \"w\");\n  fwrite(C->priorDraw, sizeof(fftw_complex), nj * (nk / 2 + 1), fp);\n  fclose(fp);\n  \n  return 0;\n}\n*/\n", "meta": {"hexsha": "b59756ab4ab54757e990c3d111b85c761083bf7e", "size": 21045, "ext": "c", "lang": "C", "max_stars_repo_path": "mcmclib/infmcmc.c", "max_stars_repo_name": "dmcdougall/mcmclib", "max_stars_repo_head_hexsha": "b745c933203c52732a5daac12e84f52d7af13266", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-11-21T22:02:58.000Z", "max_stars_repo_stars_event_max_datetime": "2015-11-21T22:02:58.000Z", "max_issues_repo_path": "mcmclib/infmcmc.c", "max_issues_repo_name": "dmcdougall/mcmclib", "max_issues_repo_head_hexsha": "b745c933203c52732a5daac12e84f52d7af13266", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mcmclib/infmcmc.c", "max_forks_repo_name": "dmcdougall/mcmclib", "max_forks_repo_head_hexsha": "b745c933203c52732a5daac12e84f52d7af13266", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9941089838, "max_line_length": 144, "alphanum_fraction": 0.5901164172, "num_tokens": 7589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.028436035926617798, "lm_q1q2_score": 0.013884844171003276}}
{"text": "/**\n * \\author Sylvain Marsat, University of Maryland - NASA GSFC\n *\n * \\brief C header for functions computing coeffcients of Not-A-Knot and Quadratic splines in matrix form.\n *\n */\n\n#ifndef _FRESNEL_H\n#define _FRESNEL_H\n\n#define _XOPEN_SOURCE 500\n\n#ifdef __GNUC__\n#define UNUSED __attribute__ ((unused))\n#else\n#define UNUSED\n#endif\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <complex.h>\n#include <time.h>\n#include <unistd.h>\n#include <getopt.h>\n#include <stdbool.h>\n#include <string.h>\n\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_bspline.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_min.h>\n#include <gsl/gsl_spline.h>\n#include <gsl/gsl_complex.h>\n\n#include \"constants.h\"\n#include \"struct.h\"\n\n\n#if defined(__cplusplus)\n#define complex _Complex\nextern \"C\" {\n#elif 0\n} /* so that editors will match preceding brace */\n#endif\n\ndouble complex ComputeInt(\n  gsl_matrix* splinecoeffsAreal,         /*  */\n  gsl_matrix* splinecoeffsAimag,         /*  */\n  gsl_matrix* splinecoeffsphase);        /*  */\n\ndouble complex ComputeIntCase1a(\n  const double complex* coeffsA,         /* */\n  const double p1,                       /* */\n  const double p2,                       /* */\n  const double scale);                   /* */\ndouble complex ComputeIntCase1b(\n  const double complex* coeffsA,         /* */\n  const double p1,                       /* */\n  const double p2,                       /* */\n  const double scale);                   /* */\ndouble complex ComputeIntCase2(\n  const double complex* coeffsA,         /* */\n  const double p1,                       /* */\n  const double p2);                      /* */\ndouble complex ComputeIntCase3(\n  const double complex* coeffsA,         /* */\n  const double p1,                       /* */\n  const double p2);                      /* */\ndouble complex ComputeIntCase4(\n  const double complex* coeffsA,         /* */\n  const double p1,                       /* */\n  const double p2);                      /* */\n\n\n#if 0\n{ /* so that editors will match succeeding brace */\n#elif defined(__cplusplus)\n}\n#endif\n\n#endif /* _FRESNEL_H */\n", "meta": {"hexsha": "af0862b0fe9deb21faebc2fd49603e81ec81f59e", "size": 2107, "ext": "h", "lang": "C", "max_stars_repo_path": "tools/fresnel.h", "max_stars_repo_name": "titodalcanton/flare", "max_stars_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z", "max_issues_repo_path": "tools/fresnel.h", "max_issues_repo_name": "titodalcanton/flare", "max_issues_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tools/fresnel.h", "max_forks_repo_name": "titodalcanton/flare", "max_forks_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z", "avg_line_length": 25.3855421687, "max_line_length": 106, "alphanum_fraction": 0.5866160418, "num_tokens": 504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490155654565424, "lm_q2_score": 0.029760091364389046, "lm_q1q2_score": 0.01383551279824535}}
{"text": "// A rectangular block of data of type float.  A transparent block\n// cache is used for each instance of this class if necessary, so the\n// image can be much bigger than will fit in memory, and pixels can\n// still be accessed and written efficiently, provided subsequent\n// accesses are spatially correlated.  A variety of useful methods are\n// implemented (filtering, subsetting, interpolating, etc.)\n//\n// Don't try to access the same instance concurrently.  Split your\n// images up into separate instances if you must parallelize things.\n//\n// For many methods, arguments of type ssize_t are used, but are not\n// allowed to be negative.  This is to help prevent people from\n// shooting themselves in the foor by accidently passing negative\n// values which don't yield warnings and can't be caught with\n// assertions.\n\n#ifndef FLOAT_IMAGE_H\n#define FLOAT_IMAGE_H\n\n#ifndef solaris\n#  include <stdint.h>\n#endif\n#include \"asf_meta.h\"\n#include <stdio.h>\n#include <sys/types.h>\n\n#include <glib.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_histogram.h>\n\n// sometimes we don't have this - choose a conservative value\n#ifndef SSIZE_MAX\n#define SSIZE_MAX 32767\n#endif\n\n// Instance structure.  Everything here is private and need not be\n// used or understood by client code, except for the size_x and size_y\n// fields.\ntypedef struct {\n  size_t size_x, size_y;    // Image dimensions.\n  size_t cache_space;       // Memory cache space in bytes.\n  size_t cache_area;        // Memory cache area in pixels.\n  size_t tile_size;         // Tile size in pixels on a side.\n  size_t cache_size_in_tiles;   // Number of tiles in cache.\n  size_t tile_count_x;      // Number of tiles in image in x direction.\n  size_t tile_count_y;      // Number of tiles in image in y direction.\n  size_t tile_count;        // Total number of tiles in image.\n  size_t tile_area;         // Area of a tile, in pixels.\n  float *cache;             // Memory cache.\n  float **tile_addresses;   // Addresss of individual tiles in the cache.\n  GQueue *tile_queue;       // Queue of tile offsets kept in load order.\n  FILE *tile_file;          // File with tiles stored contiguously.\n  GString *tile_file_name;  // Name of the tile file\n  int reference_count;      // For optional reference counting.\n} FloatImage;\n\n///////////////////////////////////////////////////////////////////////////////\n//\n// Creating New Instances\n//\n// Includeing methods which create new instances by copying existing\n// ones.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n// Thaw out a previously frozen instance (produced with\n// float_image_freeze) using data pointed to by file_pointer.  Frozen\n// instances aren't portable between platforms.  After thawing\n// file_pointer points to the data immediately following the data from\n// the thawed instance (or to the end of the file).\nFloatImage *\nfloat_image_thaw (FILE *file_pointer);\n\n// Create a new image filled with zero pixel values.\nFloatImage *\nfloat_image_new (ssize_t size_x, ssize_t size_y);\n\n// Create a new image with pixels initialized to value.\nFloatImage *\nfloat_image_new_with_value (ssize_t size_x, ssize_t size_y, float value);\n\n// Create a new image from memory.  This pixels are assumed to be\n// layed out in memory in the usual way, i.e. contiguous rows of\n// pixels in the x direction are contiguous in memory.\nFloatImage *\nfloat_image_new_from_memory (ssize_t size_x, ssize_t size_y, float *buffer);\n\n// Create a new independent copy of model.\nFloatImage *\nfloat_image_copy (FloatImage *model);\n\n// Form reduced resolution version of the model.  The scale_factor\n// must be positive and odd.  The new image will be round ((double)\n// model->size_x / scale_factor) pixels by round ((double)\n// model->size_y / scale_factor) pixels.  Scaling is performed by\n// averaging blocks of pixels together, using odd pixel reflection\n// around the image edges (see the description of the apply_kernel\n// method).  The upper and leftmost blocks of pixels averaged together\n// are always centered at the 0 index in the direction in question, so\n// reflection is always used for these edges.  Whether reflection is\n// used for the right and lower edges depends on the relationship\n// between the model dimensions and the scale factor.\nFloatImage *\nfloat_image_new_from_model_scaled (FloatImage *model, ssize_t scale_factor);\n\n// Create a new image by copying the portion of model with upper left\n// corner at model coordinates (x, y), width size_x, and height\n// size_y.\nFloatImage *\nfloat_image_new_subimage (FloatImage *model, ssize_t x, ssize_t y,\n              ssize_t size_x, ssize_t size_y);\n\n// Type used to specify whether disk files should be in big or little\n// endian byte order.\ntypedef enum {\n  FLOAT_IMAGE_BYTE_ORDER_LITTLE_ENDIAN=1,\n  FLOAT_IMAGE_BYTE_ORDER_BIG_ENDIAN\n} float_image_byte_order_t;\n\n// Create a new image from data at byte offset in file.  The pixel\n// layout in the file is assumed to be the same as for the\n// float_image_new_from_memory method.  The byte order of individual\n// pixels in the file should be byte_order.\nFloatImage *\nfloat_image_new_from_file (ssize_t size_x, ssize_t size_y, const char *file,\n               off_t offset, float_image_byte_order_t byte_order);\n\n// The method is like new_from_file, but takes a file pointer instead\n// of a file name, and the offset argument is with respect to the\n// current position in the file_pointer stream.\nFloatImage *\nfloat_image_new_from_file_pointer (ssize_t size_x, ssize_t size_y,\n                   FILE *file_pointer, off_t offset,\n                   float_image_byte_order_t byte_order);\n\n// Form a low quality reduced resolution version of the\n// original_size_x by original_size_y image in file.  The new image\n// will be size_x by size_y pixels.  This method is like new_from_file\n// method, but gets its data by sampling in each dimension using\n// bilinear interpolation.  This is a decent way of forming quick\n// thumbnails of images, or of scaling images down just slightly (by a\n// factor of say 1.5 or less), but not much else.\nFloatImage *\nfloat_image_new_from_file_scaled (ssize_t size_x, ssize_t size_y,\n                  ssize_t original_size_x,\n                  ssize_t original_size_y,\n                  const char *file, off_t offset,\n                  float_image_byte_order_t byte_order);\n\n// The function that does it all, generating an instance of FloatImage\n// from a file and the metadata\nFloatImage *\nfloat_image_new_from_metadata(meta_parameters *meta, const char *file);\n\n// For multi-band imagery the previous function needs to be more specific.\nFloatImage *\nfloat_image_band_new_from_metadata(meta_parameters *meta,\n                   int band, const char *file);\n\n// Sample type of an image that is to be used to create a float_image\n// instance.  For example, floating point image can be created from\n// signed sixteen bit integer data.\ntypedef enum {\n  FLOAT_IMAGE_SAMPLE_TYPE_SIGNED_TWO_BYTE_INTEGER=1,\n  FLOAT_IMAGE_SAMPLE_TYPE_UNSIGNED_BYTE\n} float_image_sample_type;\n\n// Form a new image by reading a data file full of sample_type\n// samples.  The integer sample type are converted to floating point\n// values by simple assignment (i.e. C assignment semantics apply,\n// which for the smaller integer types should mean than an exact\n// floating point representation is possible).  The other arguments\n// are like those of the new_from_file method.\nFloatImage *\nfloat_image_new_from_file_with_sample_type\n  (ssize_t size_x, ssize_t size_y, const char *file, off_t offset,\n   float_image_byte_order_t byte_order, float_image_sample_type sample_type);\n\n// This method is to new_from_file_with_sample_type as\n// new_from_file_pointer is to new_from_file.\nFloatImage *\nfloat_image_new_from_file_pointer_with_sample_type\n  (ssize_t size_x, ssize_t size_y, FILE *file_pointer, off_t offset,\n   float_image_byte_order_t byte_order, float_image_sample_type sample_type);\n\n///////////////////////////////////////////////////////////////////////////////\n//\n// Getting and Setting Image Pixels and Regions\n//\n///////////////////////////////////////////////////////////////////////////////\n\n// Get pixel at 0-indexed position x, y.  A cache is used so pixel\n// access does not usually involve the hard disk, provided subsequent\n// pixel lookups are spatially close together.  You can probably get\n// away with trating this function just as if everything was in\n// memory.  For details, see the cache control methods below.\n//\n// The x and y arguments should always be positive, ssize_t is used\n// only so people can't as easily shoot themselves in the foot by\n// accidently supplying negative arguments which get promoted in some\n// strange way.\nfloat\nfloat_image_get_pixel (FloatImage *self, ssize_t x, ssize_t y);\n\n// Set pixel at 0-indexed position x, y to value.  A cache is used to\n// make this fast, as for the float_image_get_pixel method.\nvoid\nfloat_image_set_pixel (FloatImage *self, ssize_t x, ssize_t y, float value);\n\n// Get rectangular image region of size_x, size_y having upper left\n// corner at x, y and copy it into already allocated buffer.  There is\n// not necessarily any caching help for this method, i.e. it may\n// always involve disk access and always be slow.\nvoid\nfloat_image_get_region (FloatImage *self, ssize_t x, ssize_t y,\n            ssize_t size_x, ssize_t size_y, float *buffer);\n\n// This method is analogous to float_image_get_region.\nvoid\nfloat_image_set_region (FloatImage *self, size_t x, size_t y, size_t size_x,\n            size_t size_y, float *buffer);\n\n// Get a full row of pixels, copying the data into already allocated\n// buffer.  This method will be fast on the average for calls with\n// sequential row numbers.\nvoid\nfloat_image_get_row (FloatImage *self, size_t row, float *buffer);\n\n// Get a pixel, performing odd reflection at image edges if the pixel\n// indicies fall outside the image.  See the description of the\n// apply_kernel method for an explanation of reflection.\nfloat\nfloat_image_get_pixel_with_reflection (FloatImage *self, ssize_t x, ssize_t y);\n\n///////////////////////////////////////////////////////////////////////////////\n//\n// Image Analysis and Statistics\n//\n///////////////////////////////////////////////////////////////////////////////\n\n// Default mask value when figuring image stats\n#define FLOAT_IMAGE_DEFAULT_MASK (0.0)\n\n// Finds the minimum and maximum pixel values in the image, and the\n// mean and standard deviation of all pixels.  This function considers\n// every pixel in the image when mask is NAN, otherwise it discounts\n// all values within .00000000001 of the mask\nvoid\nfloat_image_statistics (FloatImage *self, float *min, float *max, float *mean,\n                        float *standard_deviation, float mask);\n\n//  Does the same thing as float_image_statistics() but for only one selected\n// band within a multi-band float image.  Returns 1 on error, otherwise 0\nint\nfloat_image_band_statistics(FloatImage *self, meta_stats *stats,\n                            int line_count, int band_no,\n                            float mask);\n\n// This method works like the statistics method, except values in the\n// interval [interval_start, interval_end] are not considered at all\n// for the purposes of determining any of the outputs.\nvoid\nfloat_image_statistics_with_mask_interval (FloatImage *self, float *min,\n                       float *max, float *mean,\n                       float *standard_deviation,\n                       double interval_start,\n                       double interval_end);\n\n// Compute an efficient estimate of the mean and standard deviation of\n// the pixels in the image, by sampling every stride th pixel in each\n// dimension, beginning with pixel (0, 0). If the mask is a non-NAN\n// value, this function will discount all values within .00000000001\n// of the mask\nvoid\nfloat_image_approximate_statistics (FloatImage *self, size_t stride,\n                                    float *mean, float *standard_deviation,\n                                    float mask);\n\n// This method is a logical combination of the\n// statistics_with_mask_interval and approximate_statistics methods.\nvoid\nfloat_image_approximate_statistics_with_mask_interval\n  (FloatImage *self, size_t stride, float *mean, float *standard_deviation,\n   double interval_start, double interval_end);\n\n// Creates a gsl_histogram with 'num_bins' bins evenly spaced between\n// 'min' and 'max'.  This function considers every pixel in the image.\ngsl_histogram *\nfloat_image_gsl_histogram (FloatImage *self, float min, float max,\n                           size_t num_bins);\n\n///////////////////////////////////////////////////////////////////////////////\n//\n// Kernels, Interpolation, and Sampling\n//\n///////////////////////////////////////////////////////////////////////////////\n\n// Apply kernel centerd at pixel x, y and return the value.  The\n// kernel matrix must be have equal odd dimensions.  The values in the\n// kernel are multiplied by the pixels, and the sum of the products\n// returned.  When part of the kernel would fall outside the image\n// extents, the values used for the out-of-image pixels are the mirror\n// images of the corresponding in-image pixels, with the edge pixels\n// not duplicated, i.e. reflection about the middle of the edge pixels\n// is used.\nfloat\nfloat_image_apply_kernel (FloatImage *self, ssize_t x, ssize_t y,\n              gsl_matrix_float *kernel);\n\n// Type used to specify whether disk files should be in big or little\n// endian byte order.\n\n// Sample method types.  These dictate how nearby pixels are\n// considered when we want to find the approximate value for a point\n// which falls between pixel indicies.\ntypedef enum {\n  // Nearest pixel.\n  FLOAT_IMAGE_SAMPLE_METHOD_NEAREST_NEIGHBOR,\n  // Linearly weited average of four nearest pixels\n  FLOAT_IMAGE_SAMPLE_METHOD_BILINEAR,\n  // Bicubic spline interpolation (which consideres the nearest 16 pixels).\n  FLOAT_IMAGE_SAMPLE_METHOD_BICUBIC\n} float_image_sample_method_t;\n\nfloat\nfloat_image_sample (FloatImage *self, float x, float y,\n            float_image_sample_method_t sample_method);\n\n///////////////////////////////////////////////////////////////////////////////\n//\n// Comparing Images\n//\n///////////////////////////////////////////////////////////////////////////////\n\n// Return true iff self and other have identical sizes and pixels that\n// are all approximately equal to relative accuracy epsilon, as\n// understood by the GNU Scientific Library function gsl_fcmp.\ngboolean\nfloat_image_equals (FloatImage *self, FloatImage *other, float epsilon);\n\n///////////////////////////////////////////////////////////////////////////////\n//\n// Manipulating Images\n//\n///////////////////////////////////////////////////////////////////////////////\n\n// Flip an image about a horizontal line through the center of the image\nvoid\nfloat_image_flip_y(FloatImage *self);\n\n// Flip an image about a vertical line through the center of the image\nvoid\nfloat_image_flip_x(FloatImage *self);\n\n///////////////////////////////////////////////////////////////////////////////\n//\n// Storing Images in Files\n//\n///////////////////////////////////////////////////////////////////////////////\n\n// Store instance self at position pointed to by file_pointer, for\n// later retrieval using float_image_thaw.  The serialized version of\n// self is not portable between platforms.\nvoid\nfloat_image_freeze (FloatImage *self, FILE *file_pointer);\n\n// Store image pixels in file.  The image is stored in the usual\n// order, i.e. contiguous rows of pixels in the x direction are stored\n// contiguously in memory.  Individual pixels are stored in byte order\n// byte_order.  Returns 0 on success, nonzero on error.\nint\nfloat_image_store (FloatImage *self, const char *file,\n           float_image_byte_order_t byte_order);\nint\nfloat_image_store_ext(FloatImage *self, const char *file,\n                      float_image_byte_order_t byte_order, int append_flag);\n\nint\nfloat_image_band_store(FloatImage *self, const char *file,\n               meta_parameters *meta, int append_flag);\n\n\n///////////////////////////////////////////////////////////////////////////////\n//\n// Exporting Images in Various Image File Formats\n//\n///////////////////////////////////////////////////////////////////////////////\n\n// Export image to file as a gray scaled jpeg image, with largest\n// dimension no larger than max_dimension.  The max_dimension argument\n// must be less than or equal to the largest dimension of the image.\n// The image may be scaled st its largest dimension is considerably\n// less than max_dimension.  Scaling is performed by averaging blocks\n// of pixels together, using odd pixel reflection around the image\n// edges (see the description of the apply_kernel method).  The JPEG\n// format uses byte-valued gray scale samples, so the dynamic range of\n// gray scale output pixels is limited to [0, 255].  Image pixel\n// values inside two standard deviations of the mean pixel value are\n// mapped linearly into this range; image pixel values outside two\n// standard are clamped at the appropriate limit.  In determining the\n// image statistics (mean and standard deviation), values equal to mask\n// are not considered, unless mask is NAN, in which case mask has no\n// effect.  If all image pixels have the same value, the output is\n// made black if the pixels have value 0.0, and white otherwise.  This\n// routine slurps the whole image into memory, so beware.  Returns 0\n// on success, nonzero on error.\nint\nfloat_image_export_as_jpeg (FloatImage *self, const char *file,\n                size_t max_dimension, double mask);\n\n// This method works like the export_as_jpeg method, but all values in\n// the interval [interval_start, interval_end] are considered to be\n// uninteresting low values which should be mapped to zero in the\n// output image, and should not be included in the calculations which\n// determine the image statistics used to map the other floating point\n// values into bytes.  For example, if one has an a bright island\n// surrounded by very dark water in a radar image, setting the dark\n// water covered areas to zero and not including them in the mean and\n// standard deviation calculations will prevent the more interesting\n// land areas from being driven into saturation in the generated\n// image.\nint\nfloat_image_export_as_jpeg_with_mask_interval (FloatImage *self,\n                           const char *file,\n                           ssize_t max_dimension,\n                           double interval_start,\n                           double interval_end);\n\n// Export image to file as a gray scaled tiff image, with largest\n// dimension no larger than max_dimension.  The max_dimension argument\n// must be less than or equal to the largest dimension of the image.\n// The image may be scaled st its largest dimension is considerably\n// less than max_dimension.  Scaling is performed by averaging blocks\n// of pixels together, using odd pixel reflection around the image\n// edges (see the description of the apply_kernel method).  The TIFF\n// format (here) uses byte-valued gray scale samples, so the dynamic range\n// of gray scale output pixels is limited to [0, 255].  Image pixel\n// values inside two standard deviations of the mean pixel value are\n// mapped linearly into this range; image pixel values outside two\n// standard are clamped at the appropriate limit.  In determining the\n// image statistics (mean and standard deviation), values equal to mask\n// are not considered, unless mask is NAN, in which case mask has no\n// effect.  If all image pixels have the same value, the output is\n// made black if the pixels have value 0.0, and white otherwise.  This\n// routine slurps the whole image into memory, so beware.  Returns 0\n// on success, nonzero on error.\nint\nfloat_image_export_as_tiff (FloatImage *self, const char *file,\n                            size_t max_dimension, double mask);\n\n// This method exports the float image data as an ascii CSV file.\n// Don't use this method on large sections of data - it will give\n// an assertion failure if either dimension is larger than 255.\nint\nfloat_image_export_as_csv (FloatImage *self, const char *file);\n\n///////////////////////////////////////////////////////////////////////////////\n//\n// Controlling Image Data Caching\n//\n// It probably isn't necessary to use these methods.  They are\n// provided largely to make it clear how the cache works.  The major\n// tunable parameter is the size of the in-memory cache to use.\n//\n// When a new image is created, the following steps are performed:\n//\n//      1. The image is divided up into square tiles st two full rows\n//         or columns of tiles will fit in the memory cache.\n//\n//      2. A copy of the image is created on disk with the memory\n//         layout rearranged st individual tiles are contiguous in\n//         memory.  This allows tiles to be quickly retrieved later.\n//\n// When a pixel is accessed (read or set), the following happens:\n//\n//      1. If the pixel is in a tile already loaded into the cache,\n//         it is simply fetched or set.\n//\n//      2. Otherwise, the tile containing the pixel is loaded,\n//         possibly displacing an already loaded tile, and then the\n//         pixel is fetched or set.  The tile displaced is the one\n//         loaded longest ago (there is no most-recently-accessed\n//         heuristic, as this would make pixel access too slow).\n//\n// Thus, using a larger memory cache will result in larger tiles being\n// used, and fewer tile loads being needed.  In general, the default\n// behavior is pretty good, but if you know will be performing lots of\n// widely (but not too widely) scattered accesses, you might want to\n// make it bigger.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n// Get the image memory cache size setting, in bytes.  Note that this\n// is the memory cache used per image, not the class-wide cache usage.\n// If you will have a lot of objects instantiated simultaneously, you\n// may find it necessary to use a smaller cache for each image.\nsize_t\nfloat_image_get_cache_size (FloatImage *self);\n\n// Set the image memory cache to size bytes.  Changing the cache size\n// requires the tiling to be recomputed, the on-disk tile cache to be\n// regenerated, and the in memory cache to be flushed, so its slow.\nvoid\nfloat_image_set_cache_size (FloatImage *self, size_t size);\n\n///////////////////////////////////////////////////////////////////////////////\n//\n// Reference Counting or Freeing Instances\n//\n///////////////////////////////////////////////////////////////////////////////\n\n// Increment reference count.  Return pointer to self for convenience.\nFloatImage *\nfloat_image_ref (FloatImage *self);\n\n// Decrement reference count, freeing instance if count falls to 0.\nvoid\nfloat_image_unref (FloatImage *self);\n\n// Destroy self, regardless of reference count.\nvoid\nfloat_image_free (FloatImage *self);\n\n#endif // #ifndef FLOAT_IMAGE_H\n", "meta": {"hexsha": "b08369e3ee844440f4c22d8ff8513f2d53b5bcb6", "size": 22976, "ext": "h", "lang": "C", "max_stars_repo_path": "src/libasf_raster/float_image.h", "max_stars_repo_name": "glshort/MapReady", "max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z", "max_issues_repo_path": "src/libasf_raster/float_image.h", "max_issues_repo_name": "glshort/MapReady", "max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libasf_raster/float_image.h", "max_forks_repo_name": "glshort/MapReady", "max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z", "avg_line_length": 43.7638095238, "max_line_length": 79, "alphanum_fraction": 0.691678273, "num_tokens": 4841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41111086923216794, "lm_q2_score": 0.033589503594335136, "lm_q1q2_score": 0.013809010019744147}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef mesh_7c5c4ae5_0f3e_4a2d_936e_0447239ac3a7_h\r\n#define mesh_7c5c4ae5_0f3e_4a2d_936e_0447239ac3a7_h\r\n\r\n#include <gslib/type.h>\r\n#include <gslib/std.h>\r\n#include <ariel/type.h>\r\n\r\n__ariel_begin__\r\n\r\nstruct mesh_uv_set;\r\nstruct mesh_tangent_set;\r\n\r\ntypedef vector<vec3> mesh_points;\r\ntypedef vector<vec3> mesh_normals;\r\ntypedef vector<vec3> mesh_tangents;\r\ntypedef vector<vec3> mesh_colors;\r\ntypedef vector<vec2> mesh_uv_coords;\r\ntypedef vector<int32> mesh_faces;\r\ntypedef vector<mesh_uv_set> mesh_uv_sets;\r\ntypedef vector<mesh_tangent_set> mesh_tangent_sets;\r\n\r\nstruct mesh_uv_set\r\n{\r\n    string              name;\r\n    mesh_uv_coords      coords;\r\n};\r\n\r\nstruct mesh_tangent_set\r\n{\r\n    string              name;\r\n    mesh_tangents       tangents;\r\n};\r\n\r\nclass mesh:\r\n    public res_node\r\n{\r\n    friend class mesh_io;\r\n\r\npublic:\r\n    mesh();\r\n    virtual ~mesh() {}\r\n    virtual res_type get_type() const override { return res_mesh; }\r\n    bool has_indices() const { return !_faces.empty(); }\r\n    bool has_points() const { return !_points.empty(); }\r\n    bool has_normals() const { return !_normals.empty(); }\r\n    bool has_colors() const { return !_vcolors.empty(); }\r\n    bool has_uvs() const { return !_uvsets.empty(); }\r\n    bool has_tangents() const { return !_tangentsets.empty(); }\r\n    int32 num_uv_sets() const { return (int32)_uvsets.size(); }\r\n    int32 num_tangent_sets() const { return (int32)_tangentsets.size(); }\r\n    int32 num_points() const { return (int32)_points.size(); }\r\n    int32 num_indices() const { return (int32)_faces.size(); }\r\n    const mesh_points& get_const_points() const { return _points; }\r\n    const mesh_faces& get_const_indices() const { return _faces; }\r\n    const mesh_normals& get_const_normals() const { return _normals; }\r\n    const mesh_colors& get_const_colors() const { return _vcolors; }\r\n\r\nprotected:\r\n    mesh_points         _points;\r\n    mesh_normals        _normals;\r\n    mesh_colors         _vcolors;\r\n    mesh_uv_sets        _uvsets;\r\n    mesh_tangent_sets   _tangentsets;\r\n    mesh_faces          _faces;\r\n    matrix              _transforms;\r\n\r\npublic:\r\n    /*\r\n     * Caution:\r\n     * If there were splited vertices in the mesh, the normals & tangents could be incorrect,\r\n     * in such situations, you should always trust the data from exporter.\r\n     */\r\n    void calc_normals();\r\n};\r\n\r\n__ariel_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "30443879dbb7d04d863d236cbf30b14296b7ce4b", "size": 3641, "ext": "h", "lang": "C", "max_stars_repo_path": "include/ariel/mesh.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/ariel/mesh.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ariel/mesh.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 34.3490566038, "max_line_length": 94, "alphanum_fraction": 0.6962372974, "num_tokens": 881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33807713748839185, "lm_q2_score": 0.040845718099154035, "lm_q1q2_score": 0.013809003453619795}}
{"text": "/* vector/gsl_vector_complex_float.h\r\n * \r\n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\r\n * \r\n * This program is free software; you can redistribute it and/or modify\r\n * it under the terms of the GNU General Public License as published by\r\n * the Free Software Foundation; either version 3 of the License, or (at\r\n * your option) any later version.\r\n * \r\n * This program is distributed in the hope that it will be useful, but\r\n * WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n * General Public License for more details.\r\n * \r\n * You should have received a copy of the GNU General Public License\r\n * along with this program; if not, write to the Free Software\r\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r\n */\r\n\r\n#ifndef __GSL_VECTOR_COMPLEX_FLOAT_H__\r\n#define __GSL_VECTOR_COMPLEX_FLOAT_H__\r\n\r\n#if !defined( GSL_FUN )\r\n#  if !defined( GSL_DLL )\r\n#    define GSL_FUN extern\r\n#  elif defined( BUILD_GSL_DLL )\r\n#    define GSL_FUN extern __declspec(dllexport)\r\n#  else\r\n#    define GSL_FUN extern __declspec(dllimport)\r\n#  endif\r\n#endif\r\n\r\n#include <stdlib.h>\r\n#include <gsl/gsl_types.h>\r\n#include <gsl/gsl_errno.h>\r\n#include <gsl/gsl_complex.h>\r\n#include <gsl/gsl_check_range.h>\r\n#include <gsl/gsl_vector_float.h>\r\n#include <gsl/gsl_vector_complex.h>\r\n#include <gsl/gsl_block_complex_float.h>\r\n\r\n#undef __BEGIN_DECLS\r\n#undef __END_DECLS\r\n#ifdef __cplusplus\r\n# define __BEGIN_DECLS extern \"C\" {\r\n# define __END_DECLS }\r\n#else\r\n# define __BEGIN_DECLS /* empty */\r\n# define __END_DECLS /* empty */\r\n#endif\r\n\r\n__BEGIN_DECLS\r\n\r\ntypedef struct \r\n{\r\n  size_t size;\r\n  size_t stride;\r\n  float *data;\r\n  gsl_block_complex_float *block;\r\n  int owner;\r\n} gsl_vector_complex_float;\r\n\r\ntypedef struct\r\n{\r\n  gsl_vector_complex_float vector;\r\n} _gsl_vector_complex_float_view;\r\n\r\ntypedef _gsl_vector_complex_float_view gsl_vector_complex_float_view;\r\n\r\ntypedef struct\r\n{\r\n  gsl_vector_complex_float vector;\r\n} _gsl_vector_complex_float_const_view;\r\n\r\ntypedef const _gsl_vector_complex_float_const_view gsl_vector_complex_float_const_view;\r\n\r\n/* Allocation */\r\n\r\nGSL_FUN gsl_vector_complex_float *gsl_vector_complex_float_alloc (const size_t n);\r\nGSL_FUN gsl_vector_complex_float *gsl_vector_complex_float_calloc (const size_t n);\r\n\r\nGSL_FUN gsl_vector_complex_float *\r\ngsl_vector_complex_float_alloc_from_block (gsl_block_complex_float * b, \r\n                                           const size_t offset, \r\n                                           const size_t n, \r\n                                           const size_t stride);\r\n\r\nGSL_FUN gsl_vector_complex_float *\r\ngsl_vector_complex_float_alloc_from_vector (gsl_vector_complex_float * v, \r\n                                             const size_t offset, \r\n                                             const size_t n, \r\n                                             const size_t stride);\r\n\r\nGSL_FUN void gsl_vector_complex_float_free (gsl_vector_complex_float * v);\r\n\r\n/* Views */\r\n\r\nGSL_FUN _gsl_vector_complex_float_view\r\ngsl_vector_complex_float_view_array (float *base,\r\n                                     size_t n);\r\n\r\nGSL_FUN _gsl_vector_complex_float_view\r\ngsl_vector_complex_float_view_array_with_stride (float *base,\r\n                                                 size_t stride,\r\n                                                 size_t n);\r\n\r\nGSL_FUN _gsl_vector_complex_float_const_view\r\ngsl_vector_complex_float_const_view_array (const float *base,\r\n                                           size_t n);\r\n\r\nGSL_FUN _gsl_vector_complex_float_const_view\r\ngsl_vector_complex_float_const_view_array_with_stride (const float *base,\r\n                                                       size_t stride,\r\n                                                       size_t n);\r\n\r\nGSL_FUN _gsl_vector_complex_float_view\r\ngsl_vector_complex_float_subvector (gsl_vector_complex_float *base,\r\n                                         size_t i, \r\n                                         size_t n);\r\n\r\n\r\nGSL_FUN _gsl_vector_complex_float_view \r\ngsl_vector_complex_float_subvector_with_stride (gsl_vector_complex_float *v, \r\n                                                size_t i, \r\n                                                size_t stride, \r\n                                                size_t n);\r\n\r\nGSL_FUN _gsl_vector_complex_float_const_view\r\ngsl_vector_complex_float_const_subvector (const gsl_vector_complex_float *base,\r\n                                               size_t i, \r\n                                               size_t n);\r\n\r\n\r\nGSL_FUN _gsl_vector_complex_float_const_view \r\ngsl_vector_complex_float_const_subvector_with_stride (const gsl_vector_complex_float *v, \r\n                                                      size_t i, \r\n                                                      size_t stride, \r\n                                                      size_t n);\r\n\r\nGSL_FUN _gsl_vector_float_view\r\ngsl_vector_complex_float_real (gsl_vector_complex_float *v);\r\n\r\nGSL_FUN _gsl_vector_float_view \r\ngsl_vector_complex_float_imag (gsl_vector_complex_float *v);\r\n\r\nGSL_FUN _gsl_vector_float_const_view\r\ngsl_vector_complex_float_const_real (const gsl_vector_complex_float *v);\r\n\r\nGSL_FUN _gsl_vector_float_const_view \r\ngsl_vector_complex_float_const_imag (const gsl_vector_complex_float *v);\r\n\r\n\r\n/* Operations */\r\n\r\nGSL_FUN void gsl_vector_complex_float_set_zero (gsl_vector_complex_float * v);\r\nGSL_FUN void gsl_vector_complex_float_set_all (gsl_vector_complex_float * v,\r\n                                       gsl_complex_float z);\r\nGSL_FUN int gsl_vector_complex_float_set_basis (gsl_vector_complex_float * v, size_t i);\r\n\r\nGSL_FUN int gsl_vector_complex_float_fread (FILE * stream,\r\n                                    gsl_vector_complex_float * v);\r\nGSL_FUN int gsl_vector_complex_float_fwrite (FILE * stream,\r\n                                     const gsl_vector_complex_float * v);\r\nGSL_FUN int gsl_vector_complex_float_fscanf (FILE * stream,\r\n                                     gsl_vector_complex_float * v);\r\nGSL_FUN int gsl_vector_complex_float_fprintf (FILE * stream,\r\n                                      const gsl_vector_complex_float * v,\r\n                                      const char *format);\r\n\r\nGSL_FUN int gsl_vector_complex_float_memcpy (gsl_vector_complex_float * dest, const gsl_vector_complex_float * src);\r\n\r\nGSL_FUN int gsl_vector_complex_float_reverse (gsl_vector_complex_float * v);\r\n\r\nGSL_FUN int gsl_vector_complex_float_swap (gsl_vector_complex_float * v, gsl_vector_complex_float * w);\r\nGSL_FUN int gsl_vector_complex_float_swap_elements (gsl_vector_complex_float * v, const size_t i, const size_t j);\r\n\r\nGSL_FUN int gsl_vector_complex_float_equal (const gsl_vector_complex_float * u, \r\n                                    const gsl_vector_complex_float * v);\r\n\r\nGSL_FUN int gsl_vector_complex_float_isnull (const gsl_vector_complex_float * v);\r\nGSL_FUN int gsl_vector_complex_float_ispos (const gsl_vector_complex_float * v);\r\nGSL_FUN int gsl_vector_complex_float_isneg (const gsl_vector_complex_float * v);\r\nGSL_FUN int gsl_vector_complex_float_isnonneg (const gsl_vector_complex_float * v);\r\n\r\nGSL_FUN int gsl_vector_complex_float_add (gsl_vector_complex_float * a, const gsl_vector_complex_float * b);\r\nGSL_FUN int gsl_vector_complex_float_sub (gsl_vector_complex_float * a, const gsl_vector_complex_float * b);\r\nGSL_FUN int gsl_vector_complex_float_mul (gsl_vector_complex_float * a, const gsl_vector_complex_float * b);\r\nGSL_FUN int gsl_vector_complex_float_div (gsl_vector_complex_float * a, const gsl_vector_complex_float * b);\r\nGSL_FUN int gsl_vector_complex_float_scale (gsl_vector_complex_float * a, const gsl_complex_float x);\r\nGSL_FUN int gsl_vector_complex_float_add_constant (gsl_vector_complex_float * a, const gsl_complex_float x);\r\nGSL_FUN int gsl_vector_complex_float_axpby (const gsl_complex_float alpha, const gsl_vector_complex_float * x, const gsl_complex_float beta, gsl_vector_complex_float * y);\r\n\r\nGSL_FUN INLINE_DECL gsl_complex_float gsl_vector_complex_float_get (const gsl_vector_complex_float * v, const size_t i);\r\nGSL_FUN INLINE_DECL void gsl_vector_complex_float_set (gsl_vector_complex_float * v, const size_t i, gsl_complex_float z);\r\nGSL_FUN INLINE_DECL gsl_complex_float *gsl_vector_complex_float_ptr (gsl_vector_complex_float * v, const size_t i);\r\nGSL_FUN INLINE_DECL const gsl_complex_float *gsl_vector_complex_float_const_ptr (const gsl_vector_complex_float * v, const size_t i);\r\n\r\n#ifdef HAVE_INLINE\r\n\r\nINLINE_FUN\r\ngsl_complex_float\r\ngsl_vector_complex_float_get (const gsl_vector_complex_float * v,\r\n                              const size_t i)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(i >= v->size))\r\n    {\r\n      gsl_complex_float zero = {{0, 0}};\r\n      GSL_ERROR_VAL (\"index out of range\", GSL_EINVAL, zero);\r\n    }\r\n#endif\r\n  return *GSL_COMPLEX_FLOAT_AT (v, i);\r\n}\r\n\r\nINLINE_FUN\r\nvoid\r\ngsl_vector_complex_float_set (gsl_vector_complex_float * v,\r\n                              const size_t i, gsl_complex_float z)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(i >= v->size))\r\n    {\r\n      GSL_ERROR_VOID (\"index out of range\", GSL_EINVAL);\r\n    }\r\n#endif\r\n  *GSL_COMPLEX_FLOAT_AT (v, i) = z;\r\n}\r\n\r\nINLINE_FUN\r\ngsl_complex_float *\r\ngsl_vector_complex_float_ptr (gsl_vector_complex_float * v,\r\n                              const size_t i)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(i >= v->size))\r\n    {\r\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\r\n    }\r\n#endif\r\n  return GSL_COMPLEX_FLOAT_AT (v, i);\r\n}\r\n\r\nINLINE_FUN\r\nconst gsl_complex_float *\r\ngsl_vector_complex_float_const_ptr (const gsl_vector_complex_float * v,\r\n                                    const size_t i)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(i >= v->size))\r\n    {\r\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\r\n    }\r\n#endif\r\n  return GSL_COMPLEX_FLOAT_AT (v, i);\r\n}\r\n\r\n\r\n#endif /* HAVE_INLINE */\r\n\r\n__END_DECLS\r\n\r\n#endif /* __GSL_VECTOR_COMPLEX_FLOAT_H__ */\r\n", "meta": {"hexsha": "5341cfbfa551d6793dc49a0d1e41669606000467", "size": 10090, "ext": "h", "lang": "C", "max_stars_repo_path": "vendor/gsl/gsl/gsl_vector_complex_float.h", "max_stars_repo_name": "mgreter/astrometrylib", "max_stars_repo_head_hexsha": "ef4d4539a537ab49329b77648aac893d2b4ad318", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z", "max_issues_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_vector_complex_float.h", "max_issues_repo_name": "zzpwahaha/VimbaCamJILA", "max_issues_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z", "max_forks_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_vector_complex_float.h", "max_forks_repo_name": "zzpwahaha/VimbaCamJILA", "max_forks_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 38.3650190114, "max_line_length": 172, "alphanum_fraction": 0.6779980178, "num_tokens": 2151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473485858429, "lm_q2_score": 0.03210070648551677, "lm_q1q2_score": 0.013808033782477412}}
{"text": "/*\nWe are using the OpenCV implementation and adding gridding to the \nfeature detection. \n\nModified : computeKeyPoints\nAdded methods : keepBestKeyPoints and subimageToImageCoordinates\n*/\n\n\n/*********************************************************************\n* Software License Agreement (BSD License)\n*\n*  Copyright (c) 2009, Willow Garage, Inc.\n*  All rights reserved.\n*\n*  Redistribution and use in source and binary forms, with or without\n*  modification, are permitted provided that the following conditions\n*  are met:\n*\n*   * Redistributions of source code must retain the above copyright\n*     notice, this list of conditions and the following disclaimer.\n*   * Redistributions in binary form must reproduce the above\n*     copyright notice, this list of conditions and the following\n*     disclaimer in the documentation and/or other materials provided\n*     with the distribution.\n*   * Neither the name of the Willow Garage nor the names of its\n*     contributors may be used to endorse or promote products derived\n*     from this software without specific prior written permission.\n*\n*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n*  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n*  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n*  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n*  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n*  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n*  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n*  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n*  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n*  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n*  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n*  POSSIBILITY OF SUCH DAMAGE.\n*********************************************************************/\n\n/** Authors: Ethan Rublee, Vincent Rabaud, Gary Bradski */\n\n\n#pragma once\n\n#include \"Utils\\thread_memory.h\"\n#include \"ImageData.h\"\n\n#include <iterator>\n\n#include <opencv2\\core\\types.hpp>\n\n#include <gsl\\gsl>\n\nnamespace UnitTests\n{\n    class OpenCVModifiedUnitTest;\n    class OrbFeatureDetectorUnitTest;\n}\n\nclass OrbDetector\n{\n    using ImageData = mage::ImageData<mage::ImageAllocator>;\npublic:\n    OrbDetector(\n        unsigned int gaussianKernelSize,\n        unsigned int nfeatures,\n        float scaleFactor,\n        unsigned int nlevels,\n        unsigned int patchSize,\n        unsigned int fastThreshold,\n        bool useOrientation,\n        float featureFactorANMS,\n        float featureStrengthANMS,\n        int strongResponseANMS,\n        float minRobustFactor,\n        float maxRobustFactor,\n        int numCellsX,\n        int numCellsY);\n\n    // Compute the ORB_Impl features and descriptors on an image\n    void DetectAndCompute(\n        mage::thread_memory memory,\n        ImageData& imageData,\n        const cv::Mat& image);\nprivate:\n\n    void ComputeKeyPoints(const cv::Mat& imagePyramid,\n        gsl::span<const cv::Rect> layerInfo,\n        gsl::span<const float> layerScale,\n        mage::thread_memory memory,\n        ImageData& result);\n    \n    static void ResizeAndComputeOrbDescriptorsPrerotated(\n        const cv::Mat& image,\n        gsl::span<const cv::KeyPoint> keypoints,\n        gsl::span<mage::ORBDescriptor> descriptors,\n        const std::vector<std::vector<signed char>>& scaledPatterns,\n        size_t dsize,\n        float upScale);    // amount to upscale the source image\n\n\n    static void ComputeOrbDescriptorsPrerotated(\n        const cv::Mat& imagePyramid,\n        gsl::span<const cv::Rect> layerInfo,\n        gsl::span<const float> layerScale,\n        gsl::span<const cv::KeyPoint> keypoints,\n        gsl::span<mage::ORBDescriptor> descriptors,\n        const signed char* _patternRotated,\n        size_t dsize);\n\n    static void ComputeOrbDescriptors(\n        const cv::Mat& imagePyramid,\n        gsl::span<const cv::Rect> layerInfo,\n        gsl::span<const float> layerScale,\n        gsl::span<const cv::KeyPoint> keypoints,\n        gsl::span<mage::ORBDescriptor> descriptors,\n        gsl::span<const cv::Point> _pattern,\n        size_t dsize);\n\n    static void ICAngles(\n        const cv::Mat& img,\n        gsl::span<const cv::Rect> layerinfo,\n        gsl::span<const int> u_max,\n        int half_k,\n        gsl::span<cv::KeyPoint> pts);\n\n    static void HarrisResponses(\n        const cv::Mat& img,\n        gsl::span<const cv::Rect> layerinfo,\n        gsl::span<cv::KeyPoint> pts,\n        int blockSize,\n        float harris_k);\n\n    static void MakeRandomPattern(int patchSize, cv::Point* pattern, int npoints);\n\n    enum class FeatureType\n    {\n        TYPE_5_8 = 0, TYPE_7_12 = 1, TYPE_9_16 = 2\n    };\n\n    void AdaptiveNonMaximalSuppresion(mage::temp::vector<cv::KeyPoint>& keypoints,\n        unsigned int numToKeep, int threshold, mage::thread_memory memory);\n    void FAST(\n        const cv::Mat& img,\n        mage::temp::vector<cv::KeyPoint>& keypoints,\n        int threshold,\n        bool nonmax_suppression,\n        uchar* threshold_tab,\n        mage::thread_memory& memory,\n        FeatureType type = FeatureType::TYPE_9_16);\n\n    const unsigned int m_gaussianKernelSize;\n    const unsigned int m_nfeatures;\n    const float m_scaleFactor;\n    const unsigned int m_nlevels;\n    const unsigned int m_patchSize;\n    const unsigned int m_fastThreshold;\n    const bool m_useOrientation;\n    const float m_featureFactorANMS;\n    const float m_featureStrengthANMS;\n    const int m_strongResponseANMS;\n    const float m_minRobustFactorANMS;\n    const float m_maxRobustFactorANMS;\n    const int m_numCellsX;\n    const int m_numCellsY;\n\n    friend class ::UnitTests::OpenCVModifiedUnitTest;\n    friend class ::UnitTests::OrbFeatureDetectorUnitTest;\n};\n\n", "meta": {"hexsha": "58b3e7331fd2edde9e06407a0d7f04e2f5cbeffa", "size": 5852, "ext": "h", "lang": "C", "max_stars_repo_path": "Core/MAGESLAM/Source/Image/OpenCVModified.h", "max_stars_repo_name": "syntheticmagus/mageslam", "max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z", "max_issues_repo_path": "Core/MAGESLAM/Source/Image/OpenCVModified.h", "max_issues_repo_name": "syntheticmagus/mageslam", "max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z", "max_forks_repo_path": "Core/MAGESLAM/Source/Image/OpenCVModified.h", "max_forks_repo_name": "syntheticmagus/mageslam", "max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z", "avg_line_length": 33.44, "max_line_length": 82, "alphanum_fraction": 0.6816473001, "num_tokens": 1324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046493573919, "lm_q2_score": 0.0325897421821329, "lm_q1q2_score": 0.013769317593309864}}
{"text": "#pragma once\n#include <map>\n#include <vector>\n#ifndef _NOGSL\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_blas.h>\n#else\n#include \"FakeGSL.h\"\n#endif\n#include \"BooleanNodes.h\"\n#include \"CommandLineArgs.h\"\n\n\nclass Util {\npublic:\n\tstatic map<int, int> getNodeToValMap(map<int, int>& inputMap, vector<int>& inputs) {\n\t\tmap<int, int> res;\n\t\tfor(auto i = 0; i < inputs.size(); i++) {\n\t\t\tif (inputs[i] == 0 || inputs[i] == 1) {\n\t\t\t\tres[inputMap[i]] = inputs[i];\n\t\t\t}\n\t\t}\n\t\treturn res;\n\t}\n\n    static bool isAbsolute(bool_node* n) {\n        if (n->type != bool_node::LT) {\n            return false;\n        }\n        bool_node* v;\n        if (n->mother()->type == bool_node::CONST && ((CONST_node*) (n->mother()))->getFval() == 0) {\n            v = n->father();\n        } else if (n->father()->type == bool_node::CONST && ((CONST_node*) (n->father()))->getFval() == 0) {\n            v = n->mother();\n        } else {\n            return false;\n        }\n        FastSet<bool_node>& children = n->children;\n        if (children.size() > 1) return false;\n        for(child_iter it = children.begin(); it != children.end(); ++it) {\n            if ((*it)->type == bool_node::ARRACC) {\n                ARRACC_node* ac = (ARRACC_node*)(*it);\n                if (ac->mother() != n) {\n                    return false;\n                }\n                bool_node* m = ac->arguments(0);\n                bool_node* f = ac->arguments(1);\n                if (m != v && f != v) {\n                    return false;\n                }\n                if (m == v) {\n                    if (f->type != bool_node::NEG || f->mother() != v) {\n                        return false;\n                    }\n                }\n                if (f == v) {\n                    if (m->type != bool_node::NEG || m->mother() != v) {\n                        return false;\n                    }\n                }\n            } else {\n                return false;\n            }\n        }\n        cout << \"Absolute node: \" << n->lprint() << endl;\n        return true;\n    }\n    \n    static bool isSqrt(bool_node* n) {\n        if (n->type != bool_node::UFUN) {\n            return false;\n        }\n        UFUN_node* un = (UFUN_node*) n;\n        if (un->get_ufname() == \"sqrt_math\") {\n            return true;\n        }\n        return false;\n    }\n    \n    static bool hasArraccChild(bool_node* n) {\n        FastSet<bool_node>& children = n->children;\n        for(child_iter it = children.begin(); it != children.end(); ++it) {\n            if ((*it)->type == bool_node::ARRACC && (*it)->mother() == n) {\n                return true;\n            }\n        }\n        return false;\n    }\n    \n    static bool hasAssertChild(bool_node& n) {\n        FastSet<bool_node>& children = n.children;\n        if (children.size() > 1) return false;\n        for(child_iter it = children.begin(); it != children.end(); ++it) {\n            if ((*it)->type == bool_node::ASSERT) {\n                return true;\n            }\n        }\n        return false;\n    }\n    \n    static bool hasNotAssertChild(bool_node& n) {\n        FastSet<bool_node>& children = n.children;\n        if (children.size() > 1) return false;\n        for(child_iter it = children.begin(); it != children.end(); ++it) {\n            if ((*it)->type == bool_node::NOT) {\n                FastSet<bool_node>& grandChildren = (*it)->children;\n                if (grandChildren.size() > 1) return false;\n                for (child_iter it1 = grandChildren.begin(); it1 != grandChildren.end(); ++it1) {\n                    if ((*it1)->type == bool_node::ASSERT) {\n                        return true;\n                    }\n                }\n            }\n        }\n        return false;\n    }\n    \n    static bool hasAssertChild(bool_node* n) {\n        return hasAssertChild(*n);\n    }\n    \n    static bool hasNotAssertChild(bool_node* n) {\n        return hasNotAssertChild(*n);\n    }\n    \n    static set<int> getRelevantNodes(bool_node* n) {\n        set<int> ids;\n        set<int> visitedIds;\n        vector<bool_node*> toVisit;\n        toVisit.push_back(n);\n        \n        while(toVisit.size() > 0) {\n            bool_node* node = toVisit.back();\n            toVisit.pop_back();\n            if (visitedIds.find(node->id) == visitedIds.end()) {\n                visitedIds.insert(node->id);\n                ids.insert(node->id);\n                \n\t\t\t\tfor (auto it = node->p_begin(); it != node->p_end(); ++it) {\n                    toVisit.push_back(*it);\n                }\n            }\n        }\n        return ids;\n    }\n    \n    static string print(const gsl_vector* v) {\n        stringstream s;\n        for (int i = 0; i < v->size; i++) {\n            s << gsl_vector_get(v, i) << \";\";\n        }\n        return s.str();\n    }\n    static string print(const gsl_vector* v, string delimiter) {\n        stringstream s;\n        for (int i = 0; i < v->size; i++) {\n            s << gsl_vector_get(v, i) << delimiter;\n        }\n        return s.str();\n    }\n    \n    static string print(double* arr, int len) {\n        stringstream s;\n        for (int i = 0; i < len; i++) {\n            s << arr[i] << \";\";\n        }\n        return s.str();\n    }\n\n    static string print(const vector<int>& v) {\n        stringstream s;\n        for (auto it = v.begin(); it != v.end(); it++) {\n            s << *it << \";\";\n        }\n        return s.str();\n    }\n\n    static string print(const vector<double>& v) {\n        stringstream s;\n        for (auto it = v.begin(); it != v.end(); it++) {\n            s << *it << \";\";\n        }\n        return s.str();\n    }\n\n    static string print(const set<int>& v) {\n        stringstream s;\n        for (auto it = v.begin(); it != v.end(); it++) {\n            s << *it << \";\";\n        }\n        return s.str();\n    }\n\n    static double getMin(const vector<double>& vals) {\n        double minval = 1e30;\n        for (int i = 0; i < vals.size(); i++) {\n            if (vals[i] < minval) {\n                minval = vals[i];\n            }\n        }\n        return minval;\n    }\n\n    static double norm(const gsl_vector* v) {\n        return gsl_blas_dnrm2(v);\n    }\n\n    static bool sameDir(const gsl_vector* v1, const gsl_vector* v2) {\n        double dp = 0.0;\n        gsl_blas_ddot(v1, v2, &dp);\n        dp = dp/(norm(v1) * norm(v2));\n        //cout << \"dot product: \" << dp << endl;\n        if (dp > 0.9) return true;\n        return false;\n    }\n\n    static string benchName() {\n        string s = PARAMS->inputFname;\n        int x1 = s.rfind(\".sk\");\n        int x2 = s.rfind(\"/tmp/\");\n        return s.substr(x2+5, x1-x2 - 5);\n\n    }\n\n    static vector<string> split(string &text, string sep) {\n        vector<string> tokens;\n        size_t start = 0, end = 0;\n        while ((end = text.find(sep, start)) != string::npos) {\n            tokens.push_back(text.substr(start, end - start));\n            start = end + 1;\n        }\n        tokens.push_back(text.substr(start));\n        return tokens;\n    }\n\n};\n", "meta": {"hexsha": "5603afd18cc63e1e8cf67c2d4660f291c661e071", "size": 6932, "ext": "h", "lang": "C", "max_stars_repo_path": "src/SketchSolver/NumericalSynthesis/Utils/Util.h", "max_stars_repo_name": "natebragg/sketch-backend", "max_stars_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_stars_repo_licenses": ["X11"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2020-08-20T14:54:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T00:28:40.000Z", "max_issues_repo_path": "src/SketchSolver/NumericalSynthesis/Utils/Util.h", "max_issues_repo_name": "natebragg/sketch-backend", "max_issues_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_issues_repo_licenses": ["X11"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-01T16:53:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T04:02:09.000Z", "max_forks_repo_path": "src/SketchSolver/NumericalSynthesis/Utils/Util.h", "max_forks_repo_name": "natebragg/sketch-backend", "max_forks_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_forks_repo_licenses": ["X11"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-04T20:47:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-06T01:45:04.000Z", "avg_line_length": 29.2489451477, "max_line_length": 108, "alphanum_fraction": 0.4614829775, "num_tokens": 1743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3629692055196168, "lm_q2_score": 0.037892423505945697, "lm_q1q2_score": 0.013753782855165963}}
{"text": "/* multifit/work.c\n * \n * Copyright (C) 2000 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_multifit.h>\n\ngsl_multifit_linear_workspace *\ngsl_multifit_linear_alloc (size_t n, size_t p)\n{\n  gsl_multifit_linear_workspace *w;\n\n  w = (gsl_multifit_linear_workspace *)\n    malloc (sizeof (gsl_multifit_linear_workspace));\n\n  if (w == 0)\n    {\n      GSL_ERROR_VAL (\"failed to allocate space for multifit_linear struct\",\n                     GSL_ENOMEM, 0);\n    }\n\n  w->n = n;                     /* number of observations */\n  w->p = p;                     /* number of parameters */\n\n  w->A = gsl_matrix_alloc (n, p);\n\n  if (w->A == 0)\n    {\n      free (w);\n      GSL_ERROR_VAL (\"failed to allocate space for A\", GSL_ENOMEM, 0);\n    }\n\n  w->Q = gsl_matrix_alloc (p, p);\n\n  if (w->Q == 0)\n    {\n      gsl_matrix_free (w->A);\n      free (w);\n      GSL_ERROR_VAL (\"failed to allocate space for Q\", GSL_ENOMEM, 0);\n    }\n\n  w->QSI = gsl_matrix_alloc (p, p);\n\n  if (w->QSI == 0)\n    {\n      gsl_matrix_free (w->Q);\n      gsl_matrix_free (w->A);\n      free (w);\n      GSL_ERROR_VAL (\"failed to allocate space for QSI\", GSL_ENOMEM, 0);\n    }\n\n  w->S = gsl_vector_alloc (p);\n\n  if (w->S == 0)\n    {\n      gsl_matrix_free (w->QSI);\n      gsl_matrix_free (w->Q);\n      gsl_matrix_free (w->A);\n      free (w);\n      GSL_ERROR_VAL (\"failed to allocate space for S\", GSL_ENOMEM, 0);\n    }\n\n  w->t = gsl_vector_alloc (n);\n\n  if (w->t == 0)\n    {\n      gsl_vector_free (w->S);\n      gsl_matrix_free (w->QSI);\n      gsl_matrix_free (w->Q);\n      gsl_matrix_free (w->A);\n      free (w);\n      GSL_ERROR_VAL (\"failed to allocate space for t\", GSL_ENOMEM, 0);\n    }\n\n  w->xt = gsl_vector_calloc (p);\n\n  if (w->xt == 0)\n    {\n      gsl_vector_free (w->t);\n      gsl_vector_free (w->S);\n      gsl_matrix_free (w->QSI);\n      gsl_matrix_free (w->Q);\n      gsl_matrix_free (w->A);\n      free (w);\n      GSL_ERROR_VAL (\"failed to allocate space for xt\", GSL_ENOMEM, 0);\n    }\n\n  w->D = gsl_vector_calloc (p);\n\n  if (w->D == 0)\n    {\n      gsl_vector_free (w->D);\n      gsl_vector_free (w->t);\n      gsl_vector_free (w->S);\n      gsl_matrix_free (w->QSI);\n      gsl_matrix_free (w->Q);\n      gsl_matrix_free (w->A);\n      free (w);\n      GSL_ERROR_VAL (\"failed to allocate space for xt\", GSL_ENOMEM, 0);\n    }\n\n  return w;\n}\n\nvoid\ngsl_multifit_linear_free (gsl_multifit_linear_workspace * work)\n{\n  gsl_matrix_free (work->A);\n  gsl_matrix_free (work->Q);\n  gsl_matrix_free (work->QSI);\n  gsl_vector_free (work->S);\n  gsl_vector_free (work->t);\n  gsl_vector_free (work->xt);\n  gsl_vector_free (work->D);\n  free (work);\n}\n\n", "meta": {"hexsha": "f05e3ff4b5da9bd0ee5c6308a0b6141585c7b1ba", "size": 3349, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/multifit/work.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/multifit/work.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/multifit/work.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 24.9925373134, "max_line_length": 81, "alphanum_fraction": 0.6174977605, "num_tokens": 976, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3738758227716966, "lm_q2_score": 0.03676946871440616, "lm_q1q2_score": 0.013747215368476761}}
{"text": "#ifdef ESL_WITH_GSL\n/* interface_gsl.h\n * Easel's interfaces to the GNU Scientific Library\n * \n * SRE, Tue Jul 13 15:36:48 2004\n * SVN $Id: interface_gsl.h 11 2005-01-06 11:44:17Z eddy $\n */\n#ifndef ESL_INTERFACE_GSL_INCLUDED\n#define ESL_INTERFACE_GSL_INCLUDED\n\n#include <stdlib.h>\n#include <easel/easel.h>\n#include <easel/dmatrix.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_permutation.h>\n#include <gsl/gsl_eigen.h>\n\nextern int esl_GSL_MatrixInversion(ESL_DMATRIX *A, ESL_DMATRIX **ret_Ai);\n\n\n#endif /*ESL_INTERFACE_GSL_INCLUDED*/\n#endif /*ESL_WITH_GSL*/\n", "meta": {"hexsha": "1e65a0c7e950a71e4550f357c134c8388d57fccf", "size": 585, "ext": "h", "lang": "C", "max_stars_repo_path": "third_party_software/hmmer-3.0-linux-intel-x86_64/easel/interface_gsl.h", "max_stars_repo_name": "juan-rodriguez-rivas/cointerfaces", "max_stars_repo_head_hexsha": "d9cfdb93e241e2246718c0fc5a4ec22424ee6ed4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "third_party_software/hmmer-3.0-linux-intel-x86_64/easel/interface_gsl.h", "max_issues_repo_name": "juan-rodriguez-rivas/cointerfaces", "max_issues_repo_head_hexsha": "d9cfdb93e241e2246718c0fc5a4ec22424ee6ed4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party_software/hmmer-3.0-linux-intel-x86_64/easel/interface_gsl.h", "max_forks_repo_name": "juan-rodriguez-rivas/cointerfaces", "max_forks_repo_head_hexsha": "d9cfdb93e241e2246718c0fc5a4ec22424ee6ed4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.375, "max_line_length": 73, "alphanum_fraction": 0.7555555556, "num_tokens": 187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.02931223075135632, "lm_q1q2_score": 0.013741299021741381}}
{"text": "#ifndef BRATU3D_H\n#define BRATU3D_H\n\n#include <petsc.h>\n\ntypedef struct Params {\n  double lambda_;\n} Params;\n\nPetscErrorCode FormInitGuess(DM da, Vec x, Params *p);\nPetscErrorCode FormFunction(DM da, Vec x, Vec F, Params *p);\nPetscErrorCode FormJacobian(DM da, Vec x, Mat J, Params *p);\n\n#endif/*BRATU3D_H*/\n", "meta": {"hexsha": "10709d04e5e73aabed0ea9dfbaadfb99f70c2004", "size": 308, "ext": "h", "lang": "C", "max_stars_repo_path": "demo/wrap-swig/Bratu3D.h", "max_stars_repo_name": "underworldcode/petsc4py", "max_stars_repo_head_hexsha": "fdfdd79be39b8cbe95cf57010f29a6cb2ef463a6", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-11-11T05:00:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-11T05:00:53.000Z", "max_issues_repo_path": "demo/wrap-swig/Bratu3D.h", "max_issues_repo_name": "underworldcode/petsc4py", "max_issues_repo_head_hexsha": "fdfdd79be39b8cbe95cf57010f29a6cb2ef463a6", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "demo/wrap-swig/Bratu3D.h", "max_forks_repo_name": "underworldcode/petsc4py", "max_forks_repo_head_hexsha": "fdfdd79be39b8cbe95cf57010f29a6cb2ef463a6", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.5333333333, "max_line_length": 60, "alphanum_fraction": 0.737012987, "num_tokens": 98, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3311197396289915, "lm_q2_score": 0.04146227123086184, "lm_q1q2_score": 0.013728976454389598}}
{"text": "/* ode-initval/odeiv.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Author:  G. Jungman\n */\n#include <config.h>\n#include <stdlib.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_odeiv2.h>\n\ngsl_odeiv2_step *\ngsl_odeiv2_step_alloc (const gsl_odeiv2_step_type * T, size_t dim)\n{\n  gsl_odeiv2_step *s = (gsl_odeiv2_step *) malloc (sizeof (gsl_odeiv2_step));\n\n  if (s == 0)\n    {\n      GSL_ERROR_NULL (\"failed to allocate space for ode struct\", GSL_ENOMEM);\n    };\n\n  s->type = T;\n  s->dimension = dim;\n\n  s->state = s->type->alloc (dim);\n\n  if (s->state == 0)\n    {\n      free (s);                 /* exception in constructor, avoid memory leak */\n\n      GSL_ERROR_NULL (\"failed to allocate space for ode state\", GSL_ENOMEM);\n    };\n\n  return s;\n}\n\nconst char *\ngsl_odeiv2_step_name (const gsl_odeiv2_step * s)\n{\n  return s->type->name;\n}\n\nunsigned int\ngsl_odeiv2_step_order (const gsl_odeiv2_step * s)\n{\n  return s->type->order (s->state);\n}\n\nint\ngsl_odeiv2_step_apply (gsl_odeiv2_step * s,\n                       double t,\n                       double h,\n                       double y[],\n                       double yerr[],\n                       const double dydt_in[],\n                       double dydt_out[], const gsl_odeiv2_system * dydt)\n{\n  return s->type->apply (s->state, s->dimension, t, h, y, yerr, dydt_in,\n                         dydt_out, dydt);\n}\n\nint\ngsl_odeiv2_step_reset (gsl_odeiv2_step * s)\n{\n  return s->type->reset (s->state, s->dimension);\n}\n\nvoid\ngsl_odeiv2_step_free (gsl_odeiv2_step * s)\n{\n  RETURN_IF_NULL (s);\n  s->type->free (s->state);\n  free (s);\n}\n\nint\ngsl_odeiv2_step_set_driver (gsl_odeiv2_step * s, const gsl_odeiv2_driver * d)\n{\n  if (d != NULL)\n    {\n      s->type->set_driver (s->state, d);\n    }\n  else\n    {\n      GSL_ERROR (\"driver pointer is null\", GSL_EFAULT);\n    }\n\n  return GSL_SUCCESS;\n}\n", "meta": {"hexsha": "0ee5421877b37076e4f1e5bfbd75c0a7cd61906d", "size": 2591, "ext": "c", "lang": "C", "max_stars_repo_path": "thirdparty/gsl-2.7/ode-initval2/step.c", "max_stars_repo_name": "igormcoelho/optstats", "max_stars_repo_head_hexsha": "6d95cf06fbb96b1cc047fa570690c6eb3d21ece4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thirdparty/gsl-2.7/ode-initval2/step.c", "max_issues_repo_name": "igormcoelho/optstats", "max_issues_repo_head_hexsha": "6d95cf06fbb96b1cc047fa570690c6eb3d21ece4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thirdparty/gsl-2.7/ode-initval2/step.c", "max_forks_repo_name": "igormcoelho/optstats", "max_forks_repo_head_hexsha": "6d95cf06fbb96b1cc047fa570690c6eb3d21ece4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6761904762, "max_line_length": 81, "alphanum_fraction": 0.6395214203, "num_tokens": 756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3311197264277872, "lm_q2_score": 0.041462269750314105, "lm_q1q2_score": 0.013728975416799124}}
{"text": "#pragma once\n#include <fstream>\n#include <memory>\n#include <optional>\n#include <sstream>\n#include <utility>\n\n#include <gsl/pointers>\n\n#include <fmt/core.h>\n#include <fmt/ranges.h>\n\n#include <nop/serializer.h>\n#include <nop/status.h>\n#include <nop/structure.h>\n#include <nop/utility/die.h>\n#include <nop/utility/stream_reader.h>\n#include <nop/utility/stream_writer.h>\n\n#include <core/Util.h>\n#include <core/storage/Page.h>\n#include <core/storage/PageCache.h>\n#include <core/storage/btree/Config.h>\n#include <core/storage/btree/Node.h>\n\nnamespace internal::storage::btree {\n\nnamespace util {\ntemplate<BtreeConfig Config = DefaultConfig>\nclass BtreePrinter;\n}\n\ntemplate<BtreeConfig Config = DefaultConfig>\nclass Btree final {\n\tusing Self = Btree<Config>;\n\n\tusing Key = typename Config::Key;\n\tusing Val = typename Config::Val;\n\tusing Ref = typename Config::Ref;\n\tusing Nod = Node<Config>;\n\n\tfriend util::BtreePrinter<Config>;\n\npublic:\n\t//! Number of entries in branch and leaf nodes may differ\n\t//! Directly unwrap with `.value()` since we _want to fail at compile time_ in case their is no value which\n\t//! satisfies the predicates\n\tint NUM_LINKS_BRANCH = ::internal::binsearch_primitive(2l, Page::size(), [](long current, long, long)\n\t\t\t{ return nop::Encoding<Nod>::Size({typename Nod::Metadata(typename Nod::Branch(std::vector<Ref>(current), std::vector<Position>(current))), {}, true}) - Page::size(); }).value();\n\tint NUM_RECORDS_BRANCH = NUM_LINKS_BRANCH - 1;\n\n\t//! Equivalent to `m` in Knuth's definition\n\t//! Make sure that when a leaf is split, its contents could be distributed among the two branch nodes.\n\t//! Directly unwrap with `.value()` since we _want to fail at compile time_ in case their is no value which\n\t//! satisfies the predicates\n\tint _NUM_RECORDS_LEAF = ::internal::binsearch_primitive(2l, Page::size(), [](long current, long, long)\n\t\t\t{ return nop::Encoding<Nod>::Size({typename Nod::Metadata(typename Nod::Leaf(std::vector<Key>(current), std::vector<Val>(current))), {}, true}) - Page::size(); }).value();\n\tint NUM_RECORDS_LEAF = _NUM_RECORDS_LEAF - 1 >= NUM_RECORDS_BRANCH * 2\n\t        ? NUM_RECORDS_BRANCH * 2 - 1\n\t        : _NUM_RECORDS_LEAF;\n\nprivate:\n\tstatic inline constexpr bool APPLY_COMPRESSION = Config::APPLY_COMPRESSION;\n\tstatic inline constexpr int PAGE_CACHE_SIZE = Config::PAGE_CACHE_SIZE;\n\n\tstatic inline constexpr uint32_t MAGIC = 0xB75EEA41;\n\npublic:\n\tstruct Header {\n\t\tPosition m_rootpos;\n\t\tstd::size_t m_size{};\n\t\tstd::size_t m_depth{};\n\t\tuint32_t m_magic{MAGIC};\n\t\tuint32_t m_pgcache_size{PAGE_CACHE_SIZE};\n\t\tuint8_t m_apply_compression{APPLY_COMPRESSION};\n\n\t\t/*\n\t\t * The storage locations of the tree header and the tree contents differ.\n\t\t * This one stores the name of the file which contains the header of the tree,\n\t\t * whereas the other name passed to the Btree constructor is the one where\n\t\t * the actual nodes of the tree are stored.\n\t\t */\n\t\tstd::string m_content_file;\n\n\t\t/*\n\t\t * We don't want to serialize this. It is used only to check whether the header\n\t\t * we are currently possessing is valid.\n\t\t */\n\t\tbool m_dirty{false};\n\n\t\tHeader() = default;\n\t\texplicit Header(Position rootpos, std::size_t size, std::size_t depth, std::string_view content_file)\n\t\t    : m_rootpos{rootpos},\n\t\t      m_size{size},\n\t\t      m_depth{depth},\n\t\t      m_content_file{std::string{content_file}} {}\n\n\t\t[[nodiscard]] auto &rootpos() noexcept { return m_rootpos; }\n\n\t\t[[nodiscard]] auto &size() noexcept { return m_size; }\n\n\t\t[[nodiscard]] auto &depth() noexcept { return m_depth; }\n\n\t\t[[nodiscard]] auto &dirty() noexcept { return m_dirty; }\n\n\t\tauto operator<=>(const Header &) const noexcept = default;\n\n\t\tfriend std::ostream &operator<<(std::ostream &os, const Header &h) {\n\t\t\tos << \"Header { .rootpos = \" << h.m_rootpos << \", .size =\" << h.m_size << \", .depth =\" << h.m_depth << \" }\";\n\t\t\treturn os;\n\t\t}\n\n\t\tNOP_STRUCTURE(Header, m_rootpos, m_size, m_depth, m_magic, m_pgcache_size, m_apply_compression, m_content_file);\n\t};\n\nprivate:\n\t[[nodiscard]] bool is_node_full(const Self::Nod &node) {\n\t\tif (node.is_branch())\n\t\t\treturn node.is_full(NUM_RECORDS_BRANCH);\n\t\treturn node.is_full(NUM_RECORDS_LEAF);\n\t}\n\n\t[[nodiscard]] auto node_split(Self::Nod &node) {\n\t\tif (node.is_branch())\n\t\t\treturn node.split(NUM_RECORDS_BRANCH);\n\t\treturn node.split(NUM_RECORDS_LEAF);\n\t}\n\n\t[[nodiscard]] std::optional<Val> search_subtree(const Self::Nod &node, const Self::Key &target_key) const noexcept {\n\t\tif (node.is_branch()) {\n\t\t\tconst auto &refs = node.branch().m_refs;\n\t\t\tconst std::size_t index = std::lower_bound(refs.cbegin(), refs.cend(), target_key) - refs.cbegin();\n\t\t\tconst Position pos = node.branch().m_links[index];\n\t\t\tconst auto other = Nod::from_page(m_pgcache.get_page(pos));\n\t\t\treturn search_subtree(other, target_key);\n\t\t}\n\t\tassert(node.is_leaf());\n\n\t\tconst auto &keys = node.leaf().m_keys;\n\t\tconst auto &vals = node.leaf().m_vals;\n\t\tconst auto it = std::lower_bound(keys.cbegin(), keys.cend(), target_key);\n\t\tif (it == keys.cend() || *it != target_key)\n\t\t\treturn {};\n\t\treturn vals[it - keys.cbegin()];\n\t}\n\n\tNod make_new_root() {\n\t\tauto old_root = root();\n\t\tauto old_pos = m_rootpos;\n\n\t\tauto new_pos = m_pgcache.get_new_pos();\n\n\t\told_root.set_parent(new_pos);\n\t\told_root.set_root(false);\n\n\t\tauto [midkey, sibling] = node_split(old_root);\n\t\tauto sibling_pos = m_pgcache.get_new_pos();\n\n\t\tNod new_root{typename Nod::Metadata(typename Nod::Branch({midkey}, {old_pos, sibling_pos})), new_pos, true};\n\n\t\tm_pgcache.put_page(new_pos, new_root.make_page());\n\t\tm_pgcache.put_page(old_pos, old_root.make_page());\n\t\tm_pgcache.put_page(sibling_pos, sibling.make_page());\n\n\t\tm_rootpos = new_pos;\n\t\t++m_depth;\n\t\tm_header.m_dirty = true;\n\n\t\treturn new_root;\n\t}\n\npublic:\n\t[[nodiscard]] auto root() noexcept { return std::as_const(*this).root(); }\n\n\t[[nodiscard]] auto root() const noexcept { return Nod::from_page(m_pgcache.get_page(rootpos())); }\n\n\t[[nodiscard]] auto &header() noexcept { return m_header; }\n\n\t[[nodiscard]] const auto &rootpos() const noexcept { return m_rootpos; }\n\n\t[[nodiscard]] std::size_t size() noexcept { return m_size; }\n\n\t[[nodiscard]] std::size_t size() const noexcept { return m_size; }\n\n\t[[nodiscard]] bool empty() const noexcept { return size() == 0; }\n\n\t[[nodiscard]] bool empty() noexcept { return size() == 0; }\n\n\t[[nodiscard]] std::size_t depth() { return m_depth; }\n\n\t[[nodiscard]] auto num_records_leaf() const noexcept { return NUM_RECORDS_LEAF; }\n\n\t[[nodiscard]] auto num_records_branch() const noexcept { return NUM_RECORDS_BRANCH; }\n\npublic:\n\t/*\n\t *  Operations API\n\t */\n\n\tvoid put(const Self::Key &key, const Self::Val &val) {\n\t\tPosition currpos{rootpos()};\n\t\tNod curr{root()};\n\n\t\tif (is_node_full(curr))\n\t\t\tcurr = make_new_root();\n\n\t\twhile (true) {\n\t\t\tif (curr.is_leaf()) {\n\t\t\t\t/* fmt::print(\" -- Putting kv pair in leaf ... \\n\"); */\n\t\t\t\tauto &keys = curr.leaf().m_keys;\n\t\t\t\tauto &vals = curr.leaf().m_vals;\n\n\t\t\t\tconst std::size_t index = std::lower_bound(keys.cbegin(), keys.cend(), key) - keys.cbegin();\n\t\t\t\tif (!keys.empty() && index < keys.size() && keys[index] == key)\n\t\t\t\t\treturn;\n\n\t\t\t\tkeys.insert(keys.begin() + index, key);\n\t\t\t\tvals.insert(vals.begin() + index, val);\n\t\t\t\tm_pgcache.put_page(currpos, curr.make_page());\n\t\t\t\t++m_size;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tauto &refs = curr.branch().m_refs;\n\t\t\tauto &links = curr.branch().m_links;\n\n\t\t\tconst std::size_t index = std::lower_bound(refs.cbegin(), refs.cend(), key) - refs.cbegin();\n\t\t\tconst Position child_pos = links[index];\n\t\t\tassert(child_pos.is_set());\n\t\t\tauto child = Nod::from_page(m_pgcache.get_page(child_pos));\n\n\t\t\tif (!is_node_full(child)) {\n\t\t\t\tcurrpos = child_pos;\n\t\t\t\tcurr = std::move(child);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tauto [midkey, sibling] = node_split(child);\n\t\t\tauto sibling_pos = m_pgcache.get_new_pos();\n\n\t\t\tassert(std::find(refs.cbegin(), refs.cend(), midkey) == refs.cend());\n\t\t\tassert(std::find(links.cbegin(), links.cend(), sibling_pos) == links.cend());\n\n\t\t\trefs.insert(refs.begin() + index, midkey);\n\t\t\tlinks.insert(links.begin() + index + 1, sibling_pos);\n\n\t\t\tm_pgcache.put_page(sibling_pos, std::move(sibling.make_page()));\n\t\t\tm_pgcache.put_page(child_pos, std::move(child.make_page()));\n\t\t\tm_pgcache.put_page(currpos, std::move(curr.make_page()));\n\n\t\t\tif (key < midkey) {\n\t\t\t\tcurrpos = child_pos;\n\t\t\t\tcurr = std::move(child);\n\t\t\t} else if (key > midkey) {\n\t\t\t\tcurrpos = sibling_pos;\n\t\t\t\tcurr = std::move(sibling);\n\t\t\t}\n\t\t}\n\t}\n\n\t[[nodiscard]] std::optional<Val> get(const Self::Key &key) const noexcept {\n\t\treturn search_subtree(root(), key);\n\t}\n\n\t[[nodiscard]] bool contains(const Self::Key &key) const noexcept {\n\t\treturn search_subtree(root(), key).has_value();\n\t}\n\nprivate:\n\tvoid save_header() const noexcept {\n\t\tif (m_header.dirty()) {\n\t\t\tm_header.rootpos() = m_rootpos;\n\t\t\tm_header.size() = m_size;\n\t\t\tm_header.dirty() = false;\n\t\t}\n\n\t\tnop::Serializer<nop::StreamWriter<std::ofstream>> serializer{m_header_name.data(), std::ios::trunc};\n\t\tserializer.Write(m_header) || nop::Die(std::cerr);\n\t}\n\n\tbool load_header() {\n\t\tnop::Deserializer<nop::StreamReader<std::ifstream>> deserializer{m_header_name.data()};\n\t\tdeserializer.Read(&m_header) || nop::Die(std::cerr);\n\t\tstd::cout << m_header << \"\\n\";\n\t\treturn true;\n\t}\n\n\tvoid bare_init() noexcept {\n\t\tm_rootpos = m_pgcache.get_new_pos();\n\t\tNod root_initial{typename Nod::Metadata(typename Nod::Leaf({}, {})), m_rootpos, true};\n\t\tm_pgcache.put_page(m_rootpos, std::move(root_initial.make_page()));\n\n\t\t// Fill in initial header\n\t\tm_header.rootpos() = m_rootpos;\n\t\tm_header.size() = m_size;\n\t\tm_header.depth() = m_depth;\n\t}\n\npublic:\n\t/*\n\t *  Persistence API\n\t */\n\n\tvoid load() {\n\t\tauto ok = load_header();\n\t\tassert(ok);\n\n\t\tm_rootpos = m_header.m_rootpos;\n\t\tm_size = m_header.m_size;\n\t\tm_depth = m_header.m_depth;\n\t}\n\n\tvoid save() const {\n\t\tsave_header();\n\t\tm_pgcache.flush_all();\n\t}\n\npublic:\n\texplicit Btree(std::string_view pgcache_name,\n\t               std::string_view btree_header_name = \"/tmp/eu-btree-header\",\n\t               bool should_load = false)\n\t    : m_pgcache{pgcache_name, PAGE_CACHE_SIZE},\n\t      m_header_name{btree_header_name} {\n\n\t\tassert(NUM_RECORDS_BRANCH > 1);\n\t\tassert(NUM_RECORDS_LEAF > 1);\n\n\t\tif (should_load)\n\t\t\tload();\n\t\telse\n\t\t\tbare_init();\n\t}\n\nprivate:\n\tmutable PageCache m_pgcache;\n\n\tmutable Header m_header;\n\tconst std::string_view m_header_name;\n\n\tPosition m_rootpos;\n\n\tstd::size_t m_size{0};\n\n\tstd::size_t m_depth{0};\n};\n\n}// namespace internal::storage::btree\n", "meta": {"hexsha": "37f04e39d3e5514a17d35cce3a3cbeb84aca5ae3", "size": 10380, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/storage/btree/Btree.h", "max_stars_repo_name": "boki1/eugene", "max_stars_repo_head_hexsha": "fceedc2d535715ce40d9c80e62fb61e2b26e78ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-01T05:17:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-01T05:17:05.000Z", "max_issues_repo_path": "src/core/storage/btree/Btree.h", "max_issues_repo_name": "boki1/eugene", "max_issues_repo_head_hexsha": "fceedc2d535715ce40d9c80e62fb61e2b26e78ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2021-09-01T08:41:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-05T14:46:33.000Z", "max_forks_repo_path": "src/core/storage/btree/Btree.h", "max_forks_repo_name": "boki1/eugene", "max_forks_repo_head_hexsha": "fceedc2d535715ce40d9c80e62fb61e2b26e78ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8275862069, "max_line_length": 181, "alphanum_fraction": 0.6853564547, "num_tokens": 2799, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3775406828054583, "lm_q2_score": 0.03622005352420005, "lm_q1q2_score": 0.013674543738776733}}
{"text": "/* vector/gsl_vector_uchar.h\r\n * \r\n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\r\n * \r\n * This program is free software; you can redistribute it and/or modify\r\n * it under the terms of the GNU General Public License as published by\r\n * the Free Software Foundation; either version 3 of the License, or (at\r\n * your option) any later version.\r\n * \r\n * This program is distributed in the hope that it will be useful, but\r\n * WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n * General Public License for more details.\r\n * \r\n * You should have received a copy of the GNU General Public License\r\n * along with this program; if not, write to the Free Software\r\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r\n */\r\n\r\n#ifndef __GSL_VECTOR_UCHAR_H__\r\n#define __GSL_VECTOR_UCHAR_H__\r\n\r\n#if !defined( GSL_FUN )\r\n#  if !defined( GSL_DLL )\r\n#    define GSL_FUN extern\r\n#  elif defined( BUILD_GSL_DLL )\r\n#    define GSL_FUN extern __declspec(dllexport)\r\n#  else\r\n#    define GSL_FUN extern __declspec(dllimport)\r\n#  endif\r\n#endif\r\n\r\n#include <stdlib.h>\r\n#include <gsl/gsl_types.h>\r\n#include <gsl/gsl_errno.h>\r\n#include <gsl/gsl_inline.h>\r\n#include <gsl/gsl_check_range.h>\r\n#include <gsl/gsl_block_uchar.h>\r\n\r\n#undef __BEGIN_DECLS\r\n#undef __END_DECLS\r\n#ifdef __cplusplus\r\n# define __BEGIN_DECLS extern \"C\" {\r\n# define __END_DECLS }\r\n#else\r\n# define __BEGIN_DECLS /* empty */\r\n# define __END_DECLS /* empty */\r\n#endif\r\n\r\n__BEGIN_DECLS\r\n\r\ntypedef struct \r\n{\r\n  size_t size;\r\n  size_t stride;\r\n  unsigned char *data;\r\n  gsl_block_uchar *block;\r\n  int owner;\r\n} \r\ngsl_vector_uchar;\r\n\r\ntypedef struct\r\n{\r\n  gsl_vector_uchar vector;\r\n} _gsl_vector_uchar_view;\r\n\r\ntypedef _gsl_vector_uchar_view gsl_vector_uchar_view;\r\n\r\ntypedef struct\r\n{\r\n  gsl_vector_uchar vector;\r\n} _gsl_vector_uchar_const_view;\r\n\r\ntypedef const _gsl_vector_uchar_const_view gsl_vector_uchar_const_view;\r\n\r\n\r\n/* Allocation */\r\n\r\nGSL_FUN gsl_vector_uchar *gsl_vector_uchar_alloc (const size_t n);\r\nGSL_FUN gsl_vector_uchar *gsl_vector_uchar_calloc (const size_t n);\r\n\r\nGSL_FUN gsl_vector_uchar *gsl_vector_uchar_alloc_from_block (gsl_block_uchar * b,\r\n                                                     const size_t offset, \r\n                                                     const size_t n, \r\n                                                     const size_t stride);\r\n\r\nGSL_FUN gsl_vector_uchar *gsl_vector_uchar_alloc_from_vector (gsl_vector_uchar * v,\r\n                                                      const size_t offset, \r\n                                                      const size_t n, \r\n                                                      const size_t stride);\r\n\r\nGSL_FUN void gsl_vector_uchar_free (gsl_vector_uchar * v);\r\n\r\n/* Views */\r\n\r\nGSL_FUN _gsl_vector_uchar_view \r\ngsl_vector_uchar_view_array (unsigned char *v, size_t n);\r\n\r\nGSL_FUN _gsl_vector_uchar_view \r\ngsl_vector_uchar_view_array_with_stride (unsigned char *base,\r\n                                         size_t stride,\r\n                                         size_t n);\r\n\r\nGSL_FUN _gsl_vector_uchar_const_view \r\ngsl_vector_uchar_const_view_array (const unsigned char *v, size_t n);\r\n\r\nGSL_FUN _gsl_vector_uchar_const_view \r\ngsl_vector_uchar_const_view_array_with_stride (const unsigned char *base,\r\n                                               size_t stride,\r\n                                               size_t n);\r\n\r\nGSL_FUN _gsl_vector_uchar_view \r\ngsl_vector_uchar_subvector (gsl_vector_uchar *v, \r\n                            size_t i, \r\n                            size_t n);\r\n\r\nGSL_FUN _gsl_vector_uchar_view \r\ngsl_vector_uchar_subvector_with_stride (gsl_vector_uchar *v, \r\n                                        size_t i,\r\n                                        size_t stride,\r\n                                        size_t n);\r\n\r\nGSL_FUN _gsl_vector_uchar_const_view \r\ngsl_vector_uchar_const_subvector (const gsl_vector_uchar *v, \r\n                                  size_t i, \r\n                                  size_t n);\r\n\r\nGSL_FUN _gsl_vector_uchar_const_view \r\ngsl_vector_uchar_const_subvector_with_stride (const gsl_vector_uchar *v, \r\n                                              size_t i, \r\n                                              size_t stride,\r\n                                              size_t n);\r\n\r\n/* Operations */\r\n\r\nGSL_FUN void gsl_vector_uchar_set_zero (gsl_vector_uchar * v);\r\nGSL_FUN void gsl_vector_uchar_set_all (gsl_vector_uchar * v, unsigned char x);\r\nGSL_FUN int gsl_vector_uchar_set_basis (gsl_vector_uchar * v, size_t i);\r\n\r\nGSL_FUN int gsl_vector_uchar_fread (FILE * stream, gsl_vector_uchar * v);\r\nGSL_FUN int gsl_vector_uchar_fwrite (FILE * stream, const gsl_vector_uchar * v);\r\nGSL_FUN int gsl_vector_uchar_fscanf (FILE * stream, gsl_vector_uchar * v);\r\nGSL_FUN int gsl_vector_uchar_fprintf (FILE * stream, const gsl_vector_uchar * v,\r\n                              const char *format);\r\n\r\nGSL_FUN int gsl_vector_uchar_memcpy (gsl_vector_uchar * dest, const gsl_vector_uchar * src);\r\n\r\nGSL_FUN int gsl_vector_uchar_reverse (gsl_vector_uchar * v);\r\n\r\nGSL_FUN int gsl_vector_uchar_swap (gsl_vector_uchar * v, gsl_vector_uchar * w);\r\nGSL_FUN int gsl_vector_uchar_swap_elements (gsl_vector_uchar * v, const size_t i, const size_t j);\r\n\r\nGSL_FUN unsigned char gsl_vector_uchar_max (const gsl_vector_uchar * v);\r\nGSL_FUN unsigned char gsl_vector_uchar_min (const gsl_vector_uchar * v);\r\nGSL_FUN void gsl_vector_uchar_minmax (const gsl_vector_uchar * v, unsigned char * min_out, unsigned char * max_out);\r\n\r\nGSL_FUN size_t gsl_vector_uchar_max_index (const gsl_vector_uchar * v);\r\nGSL_FUN size_t gsl_vector_uchar_min_index (const gsl_vector_uchar * v);\r\nGSL_FUN void gsl_vector_uchar_minmax_index (const gsl_vector_uchar * v, size_t * imin, size_t * imax);\r\n\r\nGSL_FUN int gsl_vector_uchar_add (gsl_vector_uchar * a, const gsl_vector_uchar * b);\r\nGSL_FUN int gsl_vector_uchar_sub (gsl_vector_uchar * a, const gsl_vector_uchar * b);\r\nGSL_FUN int gsl_vector_uchar_mul (gsl_vector_uchar * a, const gsl_vector_uchar * b);\r\nGSL_FUN int gsl_vector_uchar_div (gsl_vector_uchar * a, const gsl_vector_uchar * b);\r\nGSL_FUN int gsl_vector_uchar_scale (gsl_vector_uchar * a, const unsigned char x);\r\nGSL_FUN int gsl_vector_uchar_add_constant (gsl_vector_uchar * a, const double x);\r\nGSL_FUN int gsl_vector_uchar_axpby (const unsigned char alpha, const gsl_vector_uchar * x, const unsigned char beta, gsl_vector_uchar * y);\r\nGSL_FUN unsigned char gsl_vector_uchar_sum (const gsl_vector_uchar * a);\r\n\r\nGSL_FUN int gsl_vector_uchar_equal (const gsl_vector_uchar * u, \r\n                            const gsl_vector_uchar * v);\r\n\r\nGSL_FUN int gsl_vector_uchar_isnull (const gsl_vector_uchar * v);\r\nGSL_FUN int gsl_vector_uchar_ispos (const gsl_vector_uchar * v);\r\nGSL_FUN int gsl_vector_uchar_isneg (const gsl_vector_uchar * v);\r\nGSL_FUN int gsl_vector_uchar_isnonneg (const gsl_vector_uchar * v);\r\n\r\nGSL_FUN INLINE_DECL unsigned char gsl_vector_uchar_get (const gsl_vector_uchar * v, const size_t i);\r\nGSL_FUN INLINE_DECL void gsl_vector_uchar_set (gsl_vector_uchar * v, const size_t i, unsigned char x);\r\nGSL_FUN INLINE_DECL unsigned char * gsl_vector_uchar_ptr (gsl_vector_uchar * v, const size_t i);\r\nGSL_FUN INLINE_DECL const unsigned char * gsl_vector_uchar_const_ptr (const gsl_vector_uchar * v, const size_t i);\r\n\r\n#ifdef HAVE_INLINE\r\n\r\nINLINE_FUN\r\nunsigned char\r\ngsl_vector_uchar_get (const gsl_vector_uchar * v, const size_t i)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(i >= v->size))\r\n    {\r\n      GSL_ERROR_VAL (\"index out of range\", GSL_EINVAL, 0);\r\n    }\r\n#endif\r\n  return v->data[i * v->stride];\r\n}\r\n\r\nINLINE_FUN\r\nvoid\r\ngsl_vector_uchar_set (gsl_vector_uchar * v, const size_t i, unsigned char x)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(i >= v->size))\r\n    {\r\n      GSL_ERROR_VOID (\"index out of range\", GSL_EINVAL);\r\n    }\r\n#endif\r\n  v->data[i * v->stride] = x;\r\n}\r\n\r\nINLINE_FUN\r\nunsigned char *\r\ngsl_vector_uchar_ptr (gsl_vector_uchar * v, const size_t i)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(i >= v->size))\r\n    {\r\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\r\n    }\r\n#endif\r\n  return (unsigned char *) (v->data + i * v->stride);\r\n}\r\n\r\nINLINE_FUN\r\nconst unsigned char *\r\ngsl_vector_uchar_const_ptr (const gsl_vector_uchar * v, const size_t i)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(i >= v->size))\r\n    {\r\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\r\n    }\r\n#endif\r\n  return (const unsigned char *) (v->data + i * v->stride);\r\n}\r\n#endif /* HAVE_INLINE */\r\n\r\n__END_DECLS\r\n\r\n#endif /* __GSL_VECTOR_UCHAR_H__ */\r\n\r\n\r\n", "meta": {"hexsha": "2a0d6135ea6db008f45fa78895646856f3353fab", "size": 8707, "ext": "h", "lang": "C", "max_stars_repo_path": "vendor/gsl/gsl/gsl_vector_uchar.h", "max_stars_repo_name": "mgreter/astrometrylib", "max_stars_repo_head_hexsha": "ef4d4539a537ab49329b77648aac893d2b4ad318", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z", "max_issues_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_vector_uchar.h", "max_issues_repo_name": "zzpwahaha/VimbaCamJILA", "max_issues_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z", "max_forks_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_vector_uchar.h", "max_forks_repo_name": "zzpwahaha/VimbaCamJILA", "max_forks_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 35.8312757202, "max_line_length": 140, "alphanum_fraction": 0.6755484093, "num_tokens": 2159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38861801254413975, "lm_q2_score": 0.03514484475858878, "lm_q1q2_score": 0.013657919721255097}}
{"text": "//! \\file heat_driver.h\n//! Driver for Magnolia's heat transfer solver\n#ifndef ENRICO_SURROGATE_HEAT_DRIVER_H\n#define ENRICO_SURROGATE_HEAT_DRIVER_H\n\n#include \"enrico/geom.h\"\n#include \"enrico/heat_fluids_driver.h\"\n\n#include <gsl/gsl>\n#include <mpi.h>\n#include <pugixml.hpp>\n#include <xtensor/xtensor.hpp>\n\n#include <cstddef>\n\nnamespace enrico {\n\n//! Struct containing geometric information for a flow channel\nstruct Channel {\n  //! Channel index\n  int index_;\n\n  //! Channel flow area\n  double area_;\n\n  //! Vector of rod IDs connected to this channel, all with a fractional perimeter\n  //! in contact with the channel equal to 0.25\n  std::vector<std::size_t> rod_ids_;\n};\n\n//! Struct containing geometry information for a cylindrical solid rod\nstruct Rod {\n  //! Rod index\n  int index_;\n\n  //! Rod cladding outer radius\n  double clad_outer_radius_;\n\n  //! Rod cladding inner radius\n  double clad_inner_radius_;\n\n  //! Rod pellet radius\n  double pellet_radius_;\n\n  //! Vector of channel IDs connected to this rod, all with a fractional perimeter\n  //! in contact with the rod equal to 0.25\n  std::vector<std::size_t> channel_ids_;\n};\n\n//! Class to construct flow channels for a Cartesian lattice of pins\nclass ChannelFactory {\npublic:\n  ChannelFactory(double pitch, double rod_radius)\n    : pitch_(pitch)\n    , radius_(rod_radius)\n    , interior_area_(pitch_ * pitch_ - M_PI * radius_ * radius_)\n  {}\n\n  //! Make a corner subchannel connected to given rods\n  Channel make_corner(const std::vector<std::size_t>& rods) const\n  {\n    Channel c;\n    c.index_ = index_++;\n    c.area_ = 0.25 * interior_area_;\n    c.rod_ids_ = rods;\n    return c;\n  }\n\n  //! Make an edge subchannel connected to given rods\n  Channel make_edge(const std::vector<std::size_t>& rods) const\n  {\n    Channel c;\n    c.index_ = index_++;\n    c.area_ = 0.5 * interior_area_;\n    c.rod_ids_ = rods;\n    return c;\n  }\n\n  //! Make an interior subchannel connected to given rods\n  Channel make_interior(const std::vector<std::size_t>& rods) const\n  {\n    Channel c;\n    c.index_ = index_++;\n    c.area_ = interior_area_;\n    c.rod_ids_ = rods;\n    return c;\n  }\n\nprivate:\n  //! rod pitch\n  double pitch_;\n\n  //! rod outer radius\n  double radius_;\n\n  //! interior channel flow area, which is proportional to flow areas for all\n  //! other channel types\n  double interior_area_;\n\n  //! index of constructed channel\n  static int index_;\n};\n\nclass RodFactory {\npublic:\n  RodFactory(double clad_OR, double clad_IR, double pellet_OR)\n    : clad_outer_r_(clad_OR)\n    , clad_inner_r_(clad_IR)\n    , pellet_outer_r_(pellet_OR)\n  {}\n\n  //! Make a rod connected to given channels\n  Rod make_rod(const std::vector<std::size_t>& channels) const\n  {\n    Rod r;\n    r.index_ = index_++;\n    r.clad_inner_radius_ = clad_inner_r_;\n    r.clad_outer_radius_ = clad_outer_r_;\n    r.pellet_radius_ = pellet_outer_r_;\n    r.channel_ids_ = channels;\n    return r;\n  }\n\nprivate:\n  //! Cladding outer radius\n  double clad_outer_r_;\n\n  //! Cladding inner radius\n  double clad_inner_r_;\n\n  //! Pellet outer radius\n  double pellet_outer_r_;\n\n  //! Index of constructed rod\n  static int index_;\n};\n\n/**\n * Class providing surrogate thermal-hydraulic solution for a Cartesian\n * bundle of rods with upwards-flowing coolant. A conduction model is used\n * for the solid phase, with axial conduction neglected. The solid phase is\n * linked to the fluid phase by conjugate heat transfer, which is treated\n * here with a pseudo-steady-state approach where the power entering the fluid\n * matches the power in the rod at that axial elevation. It is assumed that\n * there is zero thermal resistance between the rod and the fluid.\n *\n * The fluid solution is obtained with a very simplified \"subchannel\" method\n * that neglects all crossflow terms between channels such that the method\n * is more akin to a single-pin analysis in a coolant-centered basis. The\n * enthalpy is solved by simply axial energy balance, while the axial momentum\n * equation is solved for pressure (the mass flow rate in each channel being\n * fixed) while neglecting friction effects.\n */\nclass SurrogateHeatDriver : public HeatFluidsDriver {\npublic:\n  //! Initializes heat-fluids surrogate with the given MPI communicator.\n  //!\n  //! \\param comm  The MPI communicator used to initialze the surrogate\n  //! \\param node  XML node containing settings for surrogate\n  explicit SurrogateHeatDriver(MPI_Comm comm, pugi::xml_node node);\n\n  //! Verbosity options for printing simulation results\n  enum class verbose { NONE, LOW, HIGH };\n\n  bool has_coupling_data() const final { return comm_.rank == 0; }\n\n  //! Get the number of local mesh elements\n  //! \\return Number of local mesh elements\n  int n_local_elem() const override;\n\n  //! Get the number of global mesh elements\n  //! \\return Number of global mesh elements\n  std::size_t n_global_elem() const override;\n\n  //! Set the heat source for a given local element\n  //!\n  //! \\param local_elem A local element ID\n  //! \\param heat A heat source term\n  //! \\return Error code\n  int set_heat_source_at(int32_t local_elem, double heat) override;\n\n  //! Solves the heat-fluids surrogate solver\n  void solve_step() final;\n\n  void solve_heat();\n\n  void solve_fluid();\n\n  //! Returns Number of rings in fuel and clad\n  std::size_t n_rings() const { return n_fuel_rings_ + n_clad_rings_; }\n\n  //! Returns cladding inner radius\n  double clad_inner_radius() const { return clad_inner_radius_; }\n\n  //! Returns cladding outer radius\n  double clad_outer_radius() const { return clad_outer_radius_; }\n\n  //! Returns pellet outer radius\n  double pellet_radius() const { return pellet_radius_; }\n\n  //! Returns number of fuel rings\n  std::size_t n_fuel_rings() const { return n_fuel_rings_; }\n\n  //! Returns number of clad rings\n  std::size_t n_clad_rings() const { return n_clad_rings_; }\n\n  //! Returns number of pins in x-direction\n  std::size_t n_pins_x() const { return n_pins_x_; }\n\n  //! Returns number of pins in y-direction\n  std::size_t n_pins_y() const { return n_pins_y_; }\n\n  //! Returns pin pitch\n  double pin_pitch() const { return pin_pitch_; }\n\n  //! Returns inlet temperature boundary condition in [K]\n  double inlet_temperature() const { return inlet_temperature_; }\n\n  //! Returns inlet mass flowrate boundary condition in [kg/s]\n  double mass_flowrate() const { return mass_flowrate_; }\n\n  //! Returns maximum number of subchannel iterations\n  std::size_t max_subchannel_its() const { return max_subchannel_its_; }\n\n  //! Returns subchannel convergence tolerance for enthalpy\n  double subchannel_tol_h() const { return subchannel_tol_h_; }\n\n  //! Returns subchannel convergence tolerance for pressure\n  double subchannel_tol_p() const { return subchannel_tol_p_; }\n\n  //! Returns convergence tolerance for solid energy equation\n  double heat_tol() const { return heat_tol_; }\n\n  //! Write data to VTK\n  void write_step(int timestep, int iteration) final;\n\n  //! Returns solid temperature in [K] for given region\n  double solid_temperature(std::size_t pin, std::size_t axial, std::size_t ring) const;\n\n  //! Returns fluid density in [g/cm^3] for given region\n  double fluid_density(std::size_t pin, std::size_t axial) const;\n\n  //! Returns fluid temperature in [K] for given region\n  double fluid_temperature(std::size_t pin, std::size_t axial) const;\n\n  // Data on fuel pins\n  xt::xtensor<double, 2> pin_centers_; //!< (x,y) values for center of fuel pins\n  xt::xtensor<double, 1> z_;           //!< Bounding z-values for axial segments\n  std::size_t n_axial_;                //!< number of axial segments\n  std::size_t n_azimuthal_{4};         //!< number of azimuthal segments\n\n  //! Total number of pins\n  std::size_t n_pins_;\n\n  // Dimensions for a single fuel pin axial segment\n  double clad_outer_radius_;     //!< clad outer radius in [cm]\n  double clad_inner_radius_;     //!< clad inner radius in [cm]\n  double pellet_radius_;         //!< fuel pellet radius in [cm]\n  std::size_t n_fuel_rings_{20}; //!< number of fuel rings\n  std::size_t n_clad_rings_{2};  //!< number of clad rings\n\n  //!< Channels in the domain\n  std::vector<Channel> channels_;\n\n  //!< Rods in the domain\n  std::vector<Rod> rods_;\n\n  //! Mass flowrate for coolant-centered channels; this is determine by distributing\n  //! a total inlet mass flowrate among the channels based on the fractional flow area.\n  xt::xtensor<double, 1> channel_flowrates_;\n\n  // solver variables and settings\n  xt::xtensor<double, 4>\n    source_; //!< heat source for each (pin, axial segment, ring, azimuthal segment)\n  xt::xtensor<double, 1> r_grid_clad_; //!< radii of each clad ring in [cm]\n  xt::xtensor<double, 1> r_grid_fuel_; //!< radii of each fuel ring in [cm]\n\n  //! Cross-sectional areas of rings in fuel and cladding\n  xt::xtensor<double, 1> solid_areas_;\n\n  // visualization\n  std::string viz_basename_{\n    \"heat_surrogate\"}; //!< base filename for visualization files (default: magnolia)\n  std::string viz_iterations_{\n    \"none\"};                    //!< visualization iterations to write (none, all, final)\n  std::string viz_data_{\"all\"}; //!< visualization data to write\n  std::string viz_regions_{\"all\"}; //!< visualization regions to write\n  size_t vtk_radial_res_{20};      //!< radial resolution of resulting vtk files\n\nprivate:\n  //! Get temperature of local mesh elements\n  //! \\return Temperature of local mesh elements in [K]\n  std::vector<double> temperature_local() const override;\n\n  //! Get density of local mesh elements\n  //! \\return Density of local mesh elements in [g/cm^3]\n  std::vector<double> density_local() const override;\n\n  //! States whether each local region is in fluid\n  //! \\return For each local region, 1 if region is in fluid and 0 otherwise\n  std::vector<int> fluid_mask_local() const override;\n\n  //! Get centroids of local mesh elements\n  //! \\return Centroids of local mesh elements\n  std::vector<Position> centroid_local() const override;\n\n  //! Get volumes of local mesh elements\n  //! \\return Volumes of local mesh elements\n  std::vector<double> volume_local() const override;\n\n  //! Create internal arrays used for heat equation solver\n  void generate_arrays();\n\n  //! Channel index in terms of row, column index\n  int channel_index(int row, int col) const { return row * (n_pins_x_ + 1) + col; }\n\n  //! Rod power at a given node in a given pin, computed by integrating the heat source\n  //! (assumed constant in each ring) over the pin.\n  //! \\param pin   pin index\n  //! \\param axial axial index\n  double rod_axial_node_power(const int pin, const int axial) const;\n\n  //! Diagnostic function to assess whether the mass is conserved by the subchannel\n  //! solver by comparing the mass flowrate in each axial plane (at cell-centered\n  //! positions) to the specified inlet mass flowrate.\n  //! \\param rho density in a cell-centered basis\n  //! \\param u   axial velocity in a face-centered basis\n  bool is_mass_conserved(const xt::xtensor<double, 2>& rho,\n                         const xt::xtensor<double, 2>& u) const;\n\n  //! Diagnostic function to assess whether the energy is conserved by the subchannel\n  //! solver by comparing the energy deposition in each channel in each axial plane\n  //! (at cell-centered positions) to the powers of the rods connected to that channel.\n  //! \\param rho density in a cell-centered basis\n  //! \\param u   axial velocity in a face-centered basis\n  //! \\param h   enthalpy in a face-centered basis\n  //! \\param q   powers in each channel in a cell-centered basis\n  bool is_energy_conserved(const xt::xtensor<double, 2>& rho,\n                           const xt::xtensor<double, 2>& u,\n                           const xt::xtensor<double, 2>& h,\n                           const xt::xtensor<double, 2>& q) const;\n\n  //!< solid temperature in [K] for each (pin, axial segment, ring)\n  xt::xtensor<double, 3> solid_temperature_;\n\n  //! Flow areas for coolant-centered channels\n  xt::xtensor<double, 1> channel_areas_;\n\n  //! Fluid temperature in a rod-centered basis indexed by rod ID and axial ID\n  xt::xtensor<double, 2> fluid_temperature_;\n\n  //! Fluid density in [g/cm^3] in a rod-centered basis indexed by rod ID and axial ID\n  xt::xtensor<double, 2> fluid_density_;\n\n  //! Number of pins in the x-direction in a Cartesian grid\n  std::size_t n_pins_x_;\n\n  //! Number of pins in the y-direction in a Cartesian grid\n  std::size_t n_pins_y_;\n\n  //! Pin pitch, assumed the same for the x and y directions\n  double pin_pitch_;\n\n  //! Inlet fluid temperature [K]\n  double inlet_temperature_;\n\n  //! Mass flowrate of fluid into the domain [kg/s]\n  double mass_flowrate_;\n\n  //! Number of channels\n  std::size_t n_channels_;\n\n  //! Maximum number of iterations for subchannel solution, set to a default value\n  //! of 100 if not set by the user\n  int max_subchannel_its_ = 100;\n\n  //! Convergence tolerance on enthalpy for the subchannel solution for use in\n  //! convergence based on the L-1 norm, set to a default value of 1e-2\n  double subchannel_tol_h_ = 1e-2;\n\n  //! Convergence tolerance on pressure for the subchannel solution for use in\n  //! convergence based on the L-1 norm, set to a default value of 1e-2\n  double subchannel_tol_p_ = 1e-2;\n\n  //! Convergence tolerance for solid temperature solution, set to a default value\n  //! of 1e-4\n  double heat_tol_ = 1e-4;\n\n  //! Gravitational acceleration\n  const double g_ = 9.81;\n\n  //! Verbosity setting for printing simulation results; defaults to NONE\n  verbose verbosity_ = verbose::NONE;\n\n}; // end SurrogateHeatDriver\n\n} // namespace enrico\n\n#endif // ENRICO_SURROGATE_HEAT_DRIVER_H\n", "meta": {"hexsha": "4fa134e88c81e6b5de66c28e254de49c266845b8", "size": 13558, "ext": "h", "lang": "C", "max_stars_repo_path": "include/enrico/surrogate_heat_driver.h", "max_stars_repo_name": "pshriwise/enrico", "max_stars_repo_head_hexsha": "72b95ca947804f672e5f1726e169ef6f4889e78e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/enrico/surrogate_heat_driver.h", "max_issues_repo_name": "pshriwise/enrico", "max_issues_repo_head_hexsha": "72b95ca947804f672e5f1726e169ef6f4889e78e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-06-14T18:14:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-15T15:30:51.000Z", "max_forks_repo_path": "include/enrico/surrogate_heat_driver.h", "max_forks_repo_name": "lebuller/enrico", "max_forks_repo_head_hexsha": "edd04f1e02caf1c3fae2992e55d9a47e4429655c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.895, "max_line_length": 89, "alphanum_fraction": 0.71087181, "num_tokens": 3366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4186969238628498, "lm_q2_score": 0.032589747702267004, "lm_q1q2_score": 0.013645227112405572}}
{"text": "#ifndef AMICI_MISC_H\n#define AMICI_MISC_H\n\n#include \"amici/defines.h\"\n#include <sunmatrix/sunmatrix_sparse.h> // SUNMatrixContent_Sparse\n\n#include <algorithm>\n#include <vector>\n#include <memory>\n#include <regex>\n\n#include <gsl/gsl-lite.hpp>\n\nnamespace amici {\n\n/**\n * @brief creates a slice from existing data\n *\n * @param data to be sliced\n * @param index slice index\n * @param size slice size\n * @return span of the slice\n */\n\n gsl::span<realtype> slice(std::vector<realtype> &data, int index,\n                           unsigned size);\n\n\n\n/**\n  * @brief Remove parameter scaling according to the parameter scaling in pscale\n  *\n  * All vectors must be of same length.\n  *\n  * @param bufferScaled scaled parameters\n  * @param pscale parameter scaling\n  * @param bufferUnscaled unscaled parameters are written to the array\n  */\nvoid unscaleParameters(gsl::span<const realtype> bufferScaled,\n                       gsl::span<const ParameterScaling> pscale,\n                       gsl::span<realtype> bufferUnscaled);\n\n/**\n  * @brief Remove parameter scaling according to `scaling`\n  *\n  * @param scaledParameter scaled parameter\n  * @param scaling parameter scaling\n  *\n  * @return Unscaled parameter\n  */\ndouble getUnscaledParameter(double scaledParameter, ParameterScaling scaling);\n\n\n/**\n * @brief Apply parameter scaling according to `scaling`\n * @param unscaledParameter\n * @param scaling parameter scaling\n * @return Scaled parameter\n */\ndouble getScaledParameter(double unscaledParameter, ParameterScaling scaling);\n\n\n/**\n * @brief Apply parameter scaling according to `scaling`\n * @param bufferUnscaled\n * @param pscale parameter scaling\n * @param bufferScaled destination\n */\nvoid scaleParameters(gsl::span<const realtype> bufferUnscaled,\n                     gsl::span<const ParameterScaling> pscale,\n                     gsl::span<realtype> bufferScaled);\n\n/**\n * @brief Returns the current backtrace as std::string\n * @param maxFrames Number of frames to include\n * @return Backtrace\n */\nstd::string backtraceString(int maxFrames);\n\n/**\n * @brief Convert std::regex_constants::error_type to string\n * @param err_type error type\n * @return Error type as string\n */\nstd::string regexErrorToString(std::regex_constants::error_type err_type);\n\n/**\n * @brief Format printf-style arguments to std::string\n * @param fmt Format string\n * @param ap Argument list pointer\n * @return Formatted String\n */\nstd::string printfToString(const char *fmt, va_list ap);\n\n\n} // namespace amici\n\n#ifndef __cpp_lib_make_unique\n// custom make_unique while we are still using c++11\nnamespace std {\ntemplate<typename T, typename... Args>\nstd::unique_ptr<T> make_unique(Args&&... args)\n{\n    return std::unique_ptr<T>(new T(std::forward<Args>(args)...));\n}\n}\n#endif\n\n#endif // AMICI_MISC_H\n\n", "meta": {"hexsha": "6284a1d8f9d7a25740ce09447fb93600c590be2e", "size": 2777, "ext": "h", "lang": "C", "max_stars_repo_path": "include/amici/misc.h", "max_stars_repo_name": "paszkow/AMICI", "max_stars_repo_head_hexsha": "a0407673453d6e18a9abec5b6f73758dd09f7aaf", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/amici/misc.h", "max_issues_repo_name": "paszkow/AMICI", "max_issues_repo_head_hexsha": "a0407673453d6e18a9abec5b6f73758dd09f7aaf", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/amici/misc.h", "max_forks_repo_name": "paszkow/AMICI", "max_forks_repo_head_hexsha": "a0407673453d6e18a9abec5b6f73758dd09f7aaf", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.018018018, "max_line_length": 80, "alphanum_fraction": 0.7108390349, "num_tokens": 637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24798742624020276, "lm_q2_score": 0.055005289068012136, "lm_q1q2_score": 0.01364062006557469}}
{"text": "/**\n *\n * @file core_blas.h\n *\n *  PLASMA auxiliary routines\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Jakub Kurzak\n * @author Hatem Ltaief\n * @date 2010-11-15\n *\n **/\n#ifndef _PLASMA_CORE_BLAS_H_\n#define _PLASMA_CORE_BLAS_H_\n\n#include <cblas.h>\n#include \"plasmatypes.h\"\n#include \"descriptor.h\"\n\n#include \"core_zblas.h\"\n#include \"core_dblas.h\"\n#include \"core_cblas.h\"\n#include \"core_sblas.h\"\n#include \"core_zcblas.h\"\n#include \"core_dsblas.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n  /*\n   * Coreblas Error\n   */\n#define coreblas_error(k, str) fprintf(stderr, \"%s: Parameter %d / %s\\n\", __func__, k, str);\n\n /** ****************************************************************************\n  *  LAPACK Constants\n  **/\nextern char *plasma_lapack_constants[];\n#define lapack_const(plasma_const) plasma_lapack_constants[plasma_const][0]\n\n  /*\n   * CBlas enum\n   */\n#define CBLAS_TRANSPOSE enum CBLAS_TRANSPOSE\n#define CBLAS_UPLO      enum CBLAS_UPLO\n#define CBLAS_DIAG      enum CBLAS_DIAG\n#define CBLAS_SIDE      enum CBLAS_SIDE\n\n/* CBLAS requires for scalar arguments to be passed by address rather than by value */\n#ifndef CBLAS_SADDR\n#define CBLAS_SADDR( _val_ ) &(_val_)\n#endif\n\n /** ****************************************************************************\n  *  External interface of the GKK algorithm for InPlace Layout Translation\n  **/\nint  GKK_minloc(int n, int *T);\nvoid GKK_BalanceLoad(int thrdnbr, int *Tp, int *leaders, int nleaders, int L);\nint  GKK_getLeaderNbr(int me, int ne, int *nleaders, int **leaders);\n\n/** ****************************************************************************\n *  Extra quark wrapper functions that do not rely on precision\n *  (Defined only if quark.h is included prior to this file)\n **/\n#if defined(QUARK_H)\n  /*\n   * Functions which don't depend on precision\n   */\nvoid CORE_free_quark(Quark *quark);\nvoid CORE_foo_quark(Quark *quark);\nvoid CORE_foo2_quark(Quark *quark);\n\nvoid QUARK_CORE_free(Quark *quark, Quark_Task_Flags *task_flags,\n                     void *A, int szeA);\n\nvoid CORE_pivot_update(int m, int n, int *ipiv, int *indices,\n                       int offset, int init);\nvoid CORE_pivot_update_quark(Quark *quark);\nvoid QUARK_CORE_pivot_update(Quark *quark, Quark_Task_Flags *task_flags,\n                             int m, int n, int *ipiv, int *indices,\n                             int offset, int init);\n#endif /* defined(QUARK_H) */\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* _PLASMA_CORE_BLAS_H_ */\n", "meta": {"hexsha": "6f77a2f95250ba83cb99cbf02ecfb08df090898e", "size": 2587, "ext": "h", "lang": "C", "max_stars_repo_path": "include/core_blas.h", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/core_blas.h", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/core_blas.h", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1195652174, "max_line_length": 92, "alphanum_fraction": 0.6300734441, "num_tokens": 692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.399811640739795, "lm_q2_score": 0.03410042620311981, "lm_q1q2_score": 0.01363374735019563}}
{"text": "#ifndef libceed_solids_examples_misc_h\n#define libceed_solids_examples_misc_h\n\n#include <ceed.h>\n#include <petsc.h>\n#include \"../include/structs.h\"\n\n// -----------------------------------------------------------------------------\n// Context setup\n// -----------------------------------------------------------------------------\n// Setup context data for Jacobian evaluation\nPetscErrorCode SetupJacobianCtx(MPI_Comm comm, AppCtx app_ctx, DM dm, Vec V,\n                                Vec V_loc, CeedData ceed_data, Ceed ceed,\n                                CeedQFunctionContext ctx_phys,\n                                CeedQFunctionContext ctx_phys_smoother,\n                                UserMult jacobian_ctx);\n\n// Setup context data for prolongation and restriction operators\nPetscErrorCode SetupProlongRestrictCtx(MPI_Comm comm, AppCtx app_ctx, DM dm_c,\n                                       DM dm_f, Vec V_f, Vec V_loc_c, Vec V_loc_f,\n                                       CeedData ceed_data_c, CeedData ceed_data_f,\n                                       Ceed ceed,\n                                       UserMultProlongRestr prolong_restr_ctx);\n\n// -----------------------------------------------------------------------------\n// Jacobian setup\n// -----------------------------------------------------------------------------\nPetscErrorCode FormJacobian(SNES snes, Vec U, Mat J, Mat J_pre, void *ctx);\n\n// -----------------------------------------------------------------------------\n// Solution output\n// -----------------------------------------------------------------------------\nPetscErrorCode ViewSolution(MPI_Comm comm, AppCtx app_ctx, Vec U,\n                            PetscInt increment, PetscScalar load_increment);\n\nPetscErrorCode ViewDiagnosticQuantities(MPI_Comm comm, DM dm_U,\n                                        UserMult user, AppCtx app_ctx, Vec U,\n                                        CeedElemRestriction elem_restr_diagnostic);\n\n// -----------------------------------------------------------------------------\n// Regression testing\n// -----------------------------------------------------------------------------\nPetscErrorCode RegressionTests_solids(AppCtx app_ctx, PetscReal energy);\n\n#endif // libceed_solids_examples_misc_h\n", "meta": {"hexsha": "daae9d9d06edddeba2b52a42d68bf7e34ed02906", "size": 2266, "ext": "h", "lang": "C", "max_stars_repo_path": "examples/solids/include/misc.h", "max_stars_repo_name": "wence-/libCEED", "max_stars_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/solids/include/misc.h", "max_issues_repo_name": "wence-/libCEED", "max_issues_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/solids/include/misc.h", "max_forks_repo_name": "wence-/libCEED", "max_forks_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.2608695652, "max_line_length": 83, "alphanum_fraction": 0.4448367167, "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41111086923216805, "lm_q2_score": 0.03308597600516689, "lm_q1q2_score": 0.013602004354878816}}
{"text": "/*\n** read nifti-1 or nifti-2 to vista format\n**\n** G.Lohmann, MPI-KYB, 2016\n*/\n#include <viaio/Vlib.h>\n#include <viaio/VImage.h>\n#include <viaio/mu.h>\n#include <viaio/option.h>\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <strings.h>\n#include <math.h>\n#include <ctype.h>\n\n#include <gsl/gsl_math.h>\n\n#include <nifti/nifti2.h>\n#include <nifti/nifti1_io.h>\n\n#define MIN_HEADER_SIZE 348\n#define NII_HEADER_SIZE 352\n\n#define ABS(x) ((x) > 0 ? (x) : -(x))\n\n/*extern int isinff(float x);\n  extern int isnanf(float x);\n*/\nextern char *VReadGzippedData(char *filename,size_t *len);\nextern char *VReadUnzippedData(char *filename,VBoolean nofail,size_t *size);\nextern char *VReadDataContainer(char *filename,VBoolean nofail,size_t *size);\nextern FILE *VReadInputFile (char *filename,VBoolean nofail);\nextern int  CheckGzip(char *filename);\n\nextern void VByteSwapNiftiHeader(nifti_1_header *hdr);\nextern void VByteSwapNifti2Header(nifti_2_header *hdr);\nextern void VByteSwapData(char *data,size_t ndata,size_t nsize);\nextern float strtof(const char *str, char **endptr);\n\n\nint NiftiVersion(char *databuffer,int *swap)\n{\n  int *k = (int *)(&databuffer[0]);\n  int type = *k;\n  *swap = 0;\n  if (type == 348) return 1;\n  else if (type == 540) return 2;\n  else {\n    nifti_swap_4bytes(1,k);\n    type = *k;\n    *swap = 1;\n    if (type == 348) return 1;\n    else if (type == 540) return 2;\n    else return 0;\n  }\n  return 0;\n}\n\n\n/* read repetition time from description field instead of pixdim  */\nfloat TRfromString(const char *str)\n{\n  float f_tr   = -1;    /* return value on failure */\n  float factor = 1000;  /* expect seconds as default */\n  char* c_tr;\n\n  if( ( c_tr = strstr( str, \"TR=\" ) ) || ( c_tr = strstr( str, \"TR =\" ) ) ) {\n      while( *c_tr++ != '=' )\n    ;\n\n      while( *c_tr && isspace( *c_tr ) )\n\tc_tr++;\n\n      f_tr = strtof( c_tr, &c_tr );\n      \n      if( f_tr > 0.0 ) {   \n\twhile( *c_tr && isspace( *c_tr ) )\n\t  c_tr++;\n\t\n\tif( strncasecmp( c_tr, \"ms\", 2 ) == 0 )\n\t  factor = 1;\n      }\n  }\n  return f_tr * factor;\n}\n\n\n\n/* set dimension in geo info */\nvoid VUpdateGeoinfo(VAttrList geolist,int dimtype,VLong tr)\n{\n  double *D = VGetGeoDim(geolist,NULL);\n  D[0] = (double)dimtype;\n  VSetGeoDim(geolist,D);\n\n  double *E = VGetGeoPixdim(geolist,NULL);\n  if (tr > 0) {\n    E[4] = (double)tr;\n    VSetGeoPixdim(geolist,E);\n  }\n} \n\n\n/*\n *  VIniImage\n *\n *  Allocate Image structure and fill voxel values with databuffer.\n *  Returns a pointer to the image if successful, zero otherwise.\n *  Useful for converting from 4D nifti to list of 3D vista images\n */\nVImage VIniImage (int nbands, int nrows, int ncolumns, VRepnKind pixel_repn, char *databuffer)\n{\n  size_t row_size = ncolumns * VRepnSize (pixel_repn);\n  size_t row_index_size = nbands * nrows * sizeof (char *);\n  size_t band_index_size = nbands * sizeof (char **);\n  size_t pixel_size=0;\n  VImage image;\n  int band=0, row=0;\n  char *p = NULL;\n\n  /* Check parameters: */\n  if (nbands < 1) VError(\"VIniImage: Invalid number of bands: %d\", (int) nbands);\n  if (nrows < 1)  VError (\"VIniImage: Invalid number of rows: %d\", (int) nrows);\n  if (ncolumns < 1) VError (\"VIniImage: Invalid number of columns: %d\",(int) ncolumns);\n\n\n#define AlignUp(v, b) ((((v) + (b) - 1) / (b)) * (b))\n\n  /* Initialize VImage data struct */ \n  pixel_size = VRepnSize (pixel_repn);\n  p = VMalloc(AlignUp (sizeof (VImageRec) + row_index_size + band_index_size, pixel_size));\n\n  image = (VImage) p;\n  image->nbands = nbands;\n  image->nrows  = nrows;\n  image->ncolumns = ncolumns;\n  image->flags    = VImageSingleAlloc;\n  image->pixel_repn = pixel_repn;\n  image->attributes = VCreateAttrList ();\n  image->band_index = (VPointer **) (p += sizeof (VImageRec));\n  image->row_index  = (VPointer *) (p += band_index_size);\n  image->data = (VPointer) AlignUp((long) (databuffer+4), pixel_size);\n\n  image->nframes = nbands;\n  image->nviewpoints = image->ncolors = image->ncomponents = 1;\n\n  /* Initialize the indices: */\n  for (band = 0; band < nbands; band++)\n    image->band_index[band] = image->row_index + band * nrows;\n  for (row = 0, p = image->data; row < nbands * nrows; row++, p += row_size)\n    image->row_index[row] = p;\n\n  return image;\n\n#undef AlignUp\n}\n\n\n#define xgetval(data,index,Datatype) \\\n{ \\\n  Datatype *k = (Datatype *)(&data[index]); \\\n  u = (float)(*k); \\\n}\n\n\nfloat VGetValue(char *data,size_t index,int datatype)\n{\n  float u=0;\n  switch(datatype) {\n  case DT_BINARY:\n    xgetval(data,index,VBit);\n    break;\n  case DT_UNSIGNED_CHAR:\n    xgetval(data,index,VUByte);\n    break;\n  case DT_SIGNED_SHORT:\n    xgetval(data,index,short);\n    break;\n  case DT_SIGNED_INT:\n    xgetval(data,index,int);\n    break;\n  case DT_FLOAT:\n    xgetval(data,index,float);\n    break;\n  case DT_DOUBLE:\n    xgetval(data,index,double);\n    break;\n  case DT_INT8:\n    xgetval(data,index,VSByte);\n    break;\n  case DT_UINT16:\n    xgetval(data,index,unsigned short);\n    break;\n  case DT_UINT32:\n    xgetval(data,index,unsigned int);\n    break;\n  case DT_INT64:\n    xgetval(data,index,long);\n    break;\n  case DT_UINT64:\n    xgetval(data,index,unsigned long);\n    break;\n  default:\n    VError(\" unknown datatype %d\",datatype);\n  }\n  if (isinf(u) || isnan(u))\n    u = 0;\n  return u;\n}\n\n\nvoid VCleanData(VImage src)\n{\n  int b,r,c;\n  double u=0;\n  for (b=0; b<VImageNBands(src); b++) {\n    for (r=0; r<VImageNRows(src); r++) {\n      for (c=0; c<VImageNColumns(src); c++) {\n\tu = VGetPixel(src,b,r,c);\n\tif (isinf(u) || isnan(u)) {\n\t  u = 0;\n\t  VSetPixel(src,b,r,c,u);\n\t}\n      }\n    }\n  }\n}\n\n\n/* get image statistics for re-scaling parameters */\nvoid VDataStats(char *data,size_t ndata,size_t nsize,int datatype,float *xmin,float *xmax)\n{\n  size_t i,n;\n  float u=0;\n  float zmin = VRepnMaxValue(VFloatRepn);\n  float zmax = VRepnMinValue(VFloatRepn);\n\n  n=0;\n  for (i=0; i<ndata; i+= nsize) {\n    u = VGetValue(data,i,datatype);\n    if (fabs(u) < TINY) continue;\n    if (u < zmin) zmin = u;\n    if (u > zmax) zmax = u;\n    n++;\n  }\n  if (n < 1) VError(\" no non-zero data points found\");\n\n  *xmin = (zmin+TINY);\n  *xmax = (zmax-TINY);\n}\n\n\n\n/* list of 3D images */\nvoid Nii2Vista3DList(char *data,size_t nsize,size_t nslices,size_t nrows,size_t ncols,size_t nt,\n\t\t     VRepnKind dst_repn,int datatype,float scl_slope,float scl_inter,\n\t\t     VString voxelstr,VLong tr,VAttrList out_list)\n{\n  int slice,row,col;\n  float u=0;\n  size_t i;\n  size_t add=0;      \n  size_t nrnc = nrows*ncols;\n  size_t npix = nrnc*nslices;\n  size_t ndata = nt * npix * nsize;  \n\n\n  if (nsize == 1) add=4;\n  if (nsize == 2) add=2;\n  if (nsize == 4) add=1;\n\n  VImage *dst = (VImage *) VCalloc(nt,sizeof(VImage));\n  if (nt > 1) VAppendAttr(out_list,\"nimages\",NULL,VLongRepn,(VLong) nt);\n\n  for (i=0; i<nt; i++) {\n\n    /* rescale if needed */\n    if (fabs(scl_slope) > 0 || fabs(scl_inter) > 0) {\n\n      VImage tmp = VCreateImage(nslices,nrows,ncols,dst_repn);\n      VSetAttr(VImageAttrList(tmp),\"voxel\",NULL,VStringRepn,voxelstr);\n      if (tr > 0) VSetAttr(VImageAttrList(tmp),\"repetition_time\",NULL,VLongRepn,(VLong)tr);\n      for (slice=0; slice<nslices; slice++) {\n\tfor (row=0; row<nrows; row++) {\n\t  for (col=0; col<ncols; col++) {\n\t    const size_t src_index = (col + row*ncols + slice*nrnc + i*npix)*nsize;\n\t    if (src_index >= ndata || src_index < 0) continue;\n\t    u = VGetValue(data,src_index,datatype);\n\t    u = scl_slope*u + scl_inter;\n\t    VSetPixel(tmp,slice,row,col,(double)u);\t    \n\t  }\n\t}\n      }\n      VAppendAttr(out_list,\"image\",NULL,VImageRepn,tmp);\n    }\n\n    /* otherwise just copy */\n    else {\n      const size_t index = (i*npix-add)*nsize;\n      dst[i] = VIniImage(nslices,nrows,ncols,dst_repn,&data[index]);\n      VSetAttr(VImageAttrList(dst[i]),\"voxel\",NULL,VStringRepn,voxelstr);\n      if (tr > 0) VSetAttr(VImageAttrList(dst[i]),\"repetition_time\",NULL,VLongRepn,(VLong)tr);\n      VAppendAttr(out_list,\"image\",NULL,VImageRepn,dst[i]);\n      VCleanData(dst[i]);\n    }\n  }\n}\n\n\n\n\n/* 4D time series data */\nvoid Nii2Vista4D(char *data,size_t nsize,size_t nslices,size_t nrows,size_t ncols,size_t nt,\n\t\t VRepnKind dst_repn,int datatype,VBoolean do_scaling,float scl_slope,float scl_inter,\n\t\t VString voxelstr,double *slicetime,VLong tr,VAttrList out_list)\n{\n  size_t slice,row,col,ti;\n  size_t nrnc = nrows*ncols;\n  size_t npix = nrnc*nslices;\n  size_t ndata = nt * npix * nsize;\n  size_t add=0;\n  float u=0;\n\n  /* rescale to 16bit integer if needed */\n  float xmin=0,xmax=0,umin=0,umax=0;\n  if (do_scaling && dst_repn != VShortRepn) {\n    dst_repn = VShortRepn;\n    VDataStats(data,ndata,nsize,datatype,&xmin,&xmax);\n    fprintf(stderr,\" data range: [%f, %f]\\n\",xmin,xmax);\n    umin = 0;\n    umax = VRepnMaxValue(VShortRepn);\n  }\n\n\n  VImage *dst = (VImage *) VCalloc(nslices,sizeof(VImage));\n\n  for (slice=0; slice<nslices; slice++) {\n    dst[slice] = VCreateImage(nt,nrows,ncols,dst_repn);\n    if (!dst[slice]) VError(\" err allocating image\");\n    VFillImage(dst[slice],VAllBands,0);\n\n    VSetAttr(VImageAttrList(dst[slice]),\"voxel\",NULL,VStringRepn,voxelstr);\n    if (tr > 0) VSetAttr(VImageAttrList(dst[slice]),\"repetition_time\",NULL,VLongRepn,(VLong)tr);\n    if (slicetime != NULL)\n      VSetAttr(VImageAttrList(dst[slice]),\"slice_time\",NULL,VShortRepn,(VShort)slicetime[slice]);\n\n    for (ti=0; ti<nt; ti++) {\n      for (row=0; row<nrows; row++) {\n\tfor (col=0; col<ncols; col++) {\n\t  const size_t src_index = (col + row*ncols + slice*nrnc + ti*npix + add)*nsize;\n\t  if (src_index >= ndata || src_index < 0) continue;\n\n\t  if (!do_scaling) {\n\t    u = VGetValue(data,src_index,datatype);\n\t    if (fabs(scl_slope) > 0 || fabs(scl_inter) > 0) {\n\t      u = scl_slope*u + scl_inter;\n\t    }\n\t    if (VPixelRepn(dst[slice]) == VShortRepn) {\n\t      VPixel(dst[slice],ti,row,col,VShort) = u;\n\t    }\n\t    else if (VPixelRepn(dst[slice]) == VFloatRepn) {\n\t      VPixel(dst[slice],ti,row,col,VFloat) = u;\n\t    }\n\t    else {\n\t      VSetPixel(dst[slice],ti,row,col,(double)u);\n\t    }\n\t  }\n\t  else {\n\t    u = VGetValue(data,src_index,datatype);\n\t    u = umax * (u-xmin)/(xmax-xmin);\t    \n\t    if (u < umin) u = umin;\n\t    if (u > umax) u = umax;\n\t    VPixel(dst[slice],ti,row,col,VShort) = (VShort)u;\n\t  }\n\t}\n      }\n    }\n    VCleanData(dst[slice]);\n    VAppendAttr(out_list,\"image\",NULL,VImageRepn,dst[slice]);\n  }\n}\n\n\n\n/* copy nifti header infos to geolist in vista header */\ndouble *VGetNiftiHeader(VAttrList geolist,nifti_2_header hdr,VLong tr)\n{\n\n  /* units in lipsia: mm and sec */\n  char xyzt = hdr.xyzt_units;\n  int spaceunits = XYZT_TO_SPACE(xyzt);\n  int timeunits  = XYZT_TO_TIME(xyzt);\n  double xscale  = 1.0;\n  double tscale  = 1.0;\n\n  if (spaceunits == NIFTI_UNITS_MICRON) xscale=1000.0;\n  if (timeunits == NIFTI_UNITS_SEC) tscale=1000.0;\n\n\n  /* dim info */\n  VSetAttr(geolist,\"dim_info\",NULL,VShortRepn,(VShort)hdr.dim_info);\n\n\n  /* dim */\n  /* hdr.dim[0]==3 means dim=3,  hdr.dim[0]==4 means dim=4 (timeseries) */\n  float *E = VCalloc(8,sizeof(float));\n  VAttrList elist = VCreateAttrList();\n  VBundle ebundle = VCreateBundle (\"bundle\",elist,8*sizeof(float),(VPointer)E);\n  VSetAttr(geolist,\"dim\",NULL,VBundleRepn,ebundle);\n  int i;\n  for (i=0; i<8; i++) E[i] = hdr.dim[i];\n  for (i=5; i<8; i++) E[i] = 0;\n\n\n  /* pixdim */  \n  float *D = VCalloc(8,sizeof(float));\n  for (i=0; i<8; i++) D[i] = hdr.pixdim[i];\n  for (i=1; i<=3; i++) D[i] *= xscale; \n  D[4] *= tscale;\n  if (tr > 0) D[4] = (double)tr;\n\n\n  /* override if TR info is in description field */\n  float xtr = TRfromString(hdr.descrip);\n  if (xtr > 0) {\n    D[4] = (double)(xtr*tscale);\n    fprintf(stderr,\" reading TR from description field, TR= %.4f ms\\n\",D[4]);\n  }\n  if (fabs(D[0]) < 0.0001) D[0] = 1.0;  /* if not specified, assume pixdim[0] = 1 */\n\n\n  for (i=5; i<8; i++) D[i] = 0; \n  VAttrList dlist = VCreateAttrList();\n  VBundle dbundle = VCreateBundle (\"bundle\",dlist,8*sizeof(float),(VPointer)D);\n  VSetAttr(geolist,\"pixdim\",NULL,VBundleRepn,dbundle);\n\n\n  /* sform */\n  VImage sform = VCreateImage(1,4,4,VFloatRepn);\n  VFillImage (sform,VAllBands,0);\n  int j;\n  for (j=0; j<4; j++) {\n    VPixel(sform,0,0,j,VFloat) = hdr.srow_x[j];\n    VPixel(sform,0,1,j,VFloat) = hdr.srow_y[j];\n    VPixel(sform,0,2,j,VFloat) = hdr.srow_z[j];\n  }\n  VSetAttr(geolist,\"sform_code\",NULL,VShortRepn,(VShort)hdr.sform_code);\n  VSetAttr(geolist,\"sform\",NULL,VImageRepn,sform);\n\n\n  /* qform */\n  size_t dim=6;\n  float *Q = VCalloc(dim,sizeof(float));\n  VAttrList qlist = VCreateAttrList();\n  VBundle qbundle = VCreateBundle (\"bundle\",qlist,dim*sizeof(float),(VPointer)Q);\n  Q[0] = hdr.quatern_b;\n  Q[1] = hdr.quatern_c;\n  Q[2] = hdr.quatern_d;\n  Q[3] = hdr.qoffset_x;\n  Q[4] = hdr.qoffset_y;\n  Q[5] = hdr.qoffset_z;\n\n  VShort qform_code = hdr.qform_code;\n  if (hdr.sform_code==0 && qform_code==0) qform_code = 1;    /* if both codes are unspecified, assume scanner coord */\n  VSetAttr(geolist,\"qform_code\",NULL,VShortRepn,(VShort)qform_code);\n  VSetAttr(geolist,\"qform\",NULL,VBundleRepn,qbundle);\n\n  \n  /* MRI encoding directions */\n  int freq_dim=0,phase_dim=0,slice_dim=0;\n  if (hdr.dim_info != 0) {\n    freq_dim  = DIM_INFO_TO_FREQ_DIM (hdr.dim_info );\n    phase_dim = DIM_INFO_TO_PHASE_DIM(hdr.dim_info );\n    slice_dim = DIM_INFO_TO_SLICE_DIM(hdr.dim_info );\n    VSetAttr(geolist,\"freq_dim\",NULL,VShortRepn,(VShort)freq_dim);\n    VSetAttr(geolist,\"phase_dim\",NULL,VShortRepn,(VShort)phase_dim);\n    VSetAttr(geolist,\"slice_dim\",NULL,VShortRepn,(VShort)slice_dim);\n  }\n  if (slice_dim == 0) return NULL;\n\n\n\n  /* slicetiming information */\n  int slice_start = hdr.slice_start;\n  int slice_end = hdr.slice_end;\n  int slice_code = hdr.slice_code;\n  double slice_duration = hdr.slice_duration;\n  if (slice_code == 0 || slice_duration < 1.0e-10) return NULL;\n  fprintf(stderr,\" slice duration: %.2f ms\\n\", slice_duration);\n  VSetAttr(geolist,\"slice_start\",NULL,VShortRepn,(VShort)slice_start);\n  VSetAttr(geolist,\"slice_end\",NULL,VShortRepn,(VShort)slice_end);\n  VSetAttr(geolist,\"slice_code\",NULL,VShortRepn,(VShort)slice_code);\n  VSetAttr(geolist,\"slice_duration\",NULL,VFloatRepn,(VFloat)slice_duration);\n\n  int nslices = (int)E[3];\n  double *slicetimes = (double *) VCalloc(nslices,sizeof(double));\n  VGetSlicetimes(slice_start,slice_end,slice_code,slice_duration,slicetimes);\n  return slicetimes;\n}\n\n\n\nVAttrList Nifti1_to_Vista(char *databuffer,VLong tr,VBoolean attrtype,VBoolean do_scaling,VBoolean *ok)\n{\n  /* read header */\n  nifti_1_header hdr1;\n  nifti_2_header hdr;\n  int i=0,swap=0;\n  size_t header_size=0;\n\n  int nifti_version = NiftiVersion(databuffer,&swap);\n  if (nifti_version < 1) VError(\" unknown nifti version\");\n  /* fprintf(stderr,\" nifti version: %d\\n\",nifti_version); */\n\n  \n  if (nifti_version == 1) {  /* nifti-1 */\n    header_size = 348;\n    memcpy(&hdr1,databuffer,header_size);\n    swap = NIFTI_NEEDS_SWAP(hdr1);\n    if (swap == 1) VByteSwapNiftiHeader(&hdr1);\n    \n    hdr.datatype = hdr1.datatype;\n    for (i=0; i<8; i++) hdr.dim[i]=hdr1.dim[i];\n    for (i=0; i<8; i++) hdr.pixdim[i]=hdr1.pixdim[i];\n    hdr.bitpix=hdr1.bitpix;\n    hdr.vox_offset=hdr1.vox_offset;\n    hdr.intent_p1 = hdr1.intent_p1;\n    hdr.intent_p2 = hdr1.intent_p2;\n    hdr.intent_p3 = hdr1.intent_p3;\n    hdr.scl_slope = hdr1.scl_slope;\n    hdr.scl_inter = hdr1.scl_inter;\n    hdr.slice_duration = hdr1.slice_duration;\n    hdr.slice_start = hdr1.slice_start;\n    hdr.slice_end = hdr1.slice_end;\n    for (i=0; i<80; i++) hdr.descrip[i] = hdr1.descrip[i];\n    hdr.qform_code = hdr1.qform_code;\n    hdr.sform_code = hdr1.sform_code;\n    hdr.quatern_b = hdr1.quatern_b;\n    hdr.quatern_c = hdr1.quatern_c;\n    hdr.quatern_d = hdr1.quatern_d;\n    hdr.qoffset_x = hdr1.qoffset_x;\n    hdr.qoffset_y = hdr1.qoffset_y;\n    hdr.qoffset_z = hdr1.qoffset_z;\n    for (i=0; i<4; i++) hdr.srow_x[i]=hdr1.srow_x[i];\n    for (i=0; i<4; i++) hdr.srow_y[i]=hdr1.srow_y[i];\n    for (i=0; i<4; i++) hdr.srow_z[i]=hdr1.srow_z[i];\n    hdr.xyzt_units = hdr1.xyzt_units;\n    hdr.dim_info = hdr1.dim_info;\n  }\n  else if (nifti_version == 2) {  /* nifti-2 */    \n    header_size = 540;\n    memcpy(&hdr,databuffer,header_size);\n    if (swap) {\n      VByteSwapNifti2Header(&hdr);\n    }\n  }\n  else {\n    VError(\" not a nifti file\");\n  }\n\n\n\n  /* get data type */\n  VRepnKind dst_repn = DT_UNKNOWN;\n  int datatype = (int)hdr.datatype;\n\n\n  switch(datatype) {\n  case DT_UNKNOWN:\n    VError(\" unknown data type\");\n    break;\n  case DT_BINARY:\n    dst_repn = VBitRepn;\n    break;\n  case DT_UNSIGNED_CHAR:\n    dst_repn = VUByteRepn;\n    break;\n  case DT_SIGNED_SHORT:\n    dst_repn = VShortRepn;\n    break;\n  case DT_SIGNED_INT:\n    dst_repn = VIntegerRepn;\n    break;\n  case DT_FLOAT:\n    dst_repn = VFloatRepn;\n    break;\n  case DT_DOUBLE:\n    dst_repn = VDoubleRepn;\n    break;\n  case DT_INT8:\n    dst_repn = VSByteRepn;\n    break;\n  case DT_UINT16:\n    dst_repn = VUShortRepn;\n    break;\n  case DT_UINT32:\n    dst_repn = VUIntegerRepn;\n    break;\n  case DT_INT64:\n    dst_repn = VLongRepn;\n    break;\n  case DT_UINT64:\n    dst_repn = VULongRepn;\n    break;\n  default:\n    VError(\" unknown data type %d\",datatype);\n  }\n\n  /* get scaling parameters */\n  double scl_slope = (double)hdr.scl_slope;\n  double scl_inter = (double)hdr.scl_inter;\n  double tiny=1.0e-6;\n  if (fabs(scl_slope) < tiny && fabs(scl_inter) < tiny) {\n    scl_slope = 1.0;\n    scl_inter = 0;\n  }\n  else if (fabs(scl_slope-1.0) < tiny && fabs(scl_inter) < tiny) {\n    scl_slope = 1.0;\n    scl_inter = 0;\n  }\n  else {\n    dst_repn = VFloatRepn;\n    do_scaling = FALSE;  /* no automatic scaling */  \n  }\n\n\n  /* number of values stored at each time point */\n  if (hdr.dim[5] > 1) VError(\"data type not supported, dim[5]= %d\\n\",hdr.dim[5]);\n\n\n  /* image size */\n  /* size_t dimtype = (size_t)hdr.dim[0]; */\n  size_t ncols   = (size_t)hdr.dim[1];\n  size_t nrows   = (size_t)hdr.dim[2];\n  size_t nslices = (size_t)hdr.dim[3];\n  size_t nt      = (size_t)hdr.dim[4];\n\n\n  /* fill data container */\n  size_t bytesize = 8;\n  if (dst_repn == VBitRepn) bytesize = 1;\n  size_t nsize   = hdr.bitpix/bytesize;\n  size_t npixels = nslices * nrows * ncols;\n  size_t ndata   = nt * npixels * nsize;\n  size_t vox_offset = (size_t)hdr.vox_offset;\n  size_t startdata = MIN_HEADER_SIZE;\n  if (vox_offset > 0) startdata = vox_offset;\n  char *data = &databuffer[startdata];\n\n\n  /* byte swap image data, if needed */\n  if (swap == 1) {\n    VByteSwapData(data,ndata,nsize);\n  }\n\n\n  /* repetition time (may be wrong in some cases) */\n  char xyzt = hdr.xyzt_units;\n  int tcode = XYZT_TO_TIME(xyzt);\n  float factor = 1.0;\n  float xtr=0;\n  if (tcode == NIFTI_UNITS_MSEC) factor = 1.0;\n  if (tcode == NIFTI_UNITS_SEC) factor = 1000.0;\n\n\n  if (nt > 1)  {\n    if (tr == 0) tr = (short)(factor*hdr.pixdim[4]);\n\n    /* override if TR info is in description field */\n    xtr = TRfromString(hdr.descrip);\n    if (xtr > 0) {\n      tr = (short) (xtr*factor);\n      fprintf(stderr,\" reading TR from description field, TR= %ld ms\\n\",tr);\n    }\n    /* fprintf(stderr,\" nt=%ld,  TR= %ld milliseconds\\n\",nt,tr); */\n    if (tr < 0.1) VWarning(\" implausible TR (%d ms), use 'vnifti' for data conversion to specify TR on the command line\",tr);\n  }\n\n  \n  /* voxel reso */\n  int blen=512;\n  char *voxelstr = (char *) VCalloc(blen,sizeof(char));\n  memset(voxelstr,0,blen);\n  sprintf(voxelstr,\"%f %f %f\",hdr.pixdim[1],hdr.pixdim[2],hdr.pixdim[3]);\n\n\n  /* geometry information */\n  VAttrList geolist = VCreateAttrList();\n  double *slicetime = VGetNiftiHeader(geolist,hdr,tr);\n\n\n  /* read nii image into vista attrlist */\n  VAttrList out_list = VCreateAttrList();\n  VAppendAttr(out_list,\"geoinfo\",NULL,VAttrListRepn,geolist);\n\n\n  (*ok) = FALSE;\n  if (nt <= 1) {      /* output one 3D image */\n    Nii2Vista3DList(data,nsize,nslices,nrows,ncols,nt,dst_repn,datatype,scl_slope,scl_inter,voxelstr,tr,out_list);\n    VUpdateGeoinfo(geolist,(int)3,tr);\n  }\n  else if (attrtype == FALSE) {        /* output list of 3D images */\n    Nii2Vista3DList(data,nsize,nslices,nrows,ncols,nt,dst_repn,datatype,scl_slope,scl_inter,voxelstr,tr,out_list);\n    VUpdateGeoinfo(geolist,(int)3,tr);\n  }\n  else if (attrtype == TRUE && nt > 1) {   /* output one 4D image */\n    Nii2Vista4D(data,nsize,nslices,nrows,ncols,nt,dst_repn,datatype,do_scaling,scl_slope,scl_inter,voxelstr,slicetime,tr,out_list);\n    VUpdateGeoinfo(geolist,(int)4,tr);\n    (*ok) = TRUE;\n  }\n\n  return out_list;\n}\n", "meta": {"hexsha": "636b384407cb94fd4c66bdd146bc3ec475c750ec", "size": 20226, "ext": "c", "lang": "C", "max_stars_repo_path": "src/conv/vnifti/Nii2Vista.c", "max_stars_repo_name": "zrajna/lipsia", "max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z", "max_issues_repo_path": "src/conv/vnifti/Nii2Vista.c", "max_issues_repo_name": "zrajna/lipsia", "max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z", "max_forks_repo_path": "src/conv/vnifti/Nii2Vista.c", "max_forks_repo_name": "zrajna/lipsia", "max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z", "avg_line_length": 28.248603352, "max_line_length": 131, "alphanum_fraction": 0.6483239395, "num_tokens": 6818, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41111086923216794, "lm_q2_score": 0.033085974694221476, "lm_q1q2_score": 0.013602003815934903}}
{"text": "/*\n    KGSX: Biomolecular Kino-geometric Sampling and Fitting of Experimental Data\n    Yao et al, Proteins. 2012 Jan;80(1):25-43\n    e-mail: latombe@cs.stanford.edu, vdbedem@slac.stanford.edu, julie.bernauer@inria.fr\n\n        Copyright (C) 2011-2013 Stanford University\n\n        Permission is hereby granted, free of charge, to any person obtaining a copy of\n        this software and associated documentation files (the \"Software\"), to deal in\n        the Software without restriction, including without limitation the rights to\n        use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\n        of the Software, and to permit persons to whom the Software is furnished to do\n        so, subject to the following conditions:\n\n        This entire text, including the above copyright notice and this permission notice\n        shall be included in all copies or substantial portions of the Software.\n\n        THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n        AUTHORS, CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n        OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n        FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n        IN THE SOFTWARE.\n*/\n\n#ifndef KGS_RELATIVEMSDDIRECTION_H\n#define KGS_RELATIVEMSDDIRECTION_H\n\n\n#include <gsl/gsl_vector.h>\n\n#include <tuple>\n#include <vector>\n\n#include \"core/graph/KinTree.h\"\n#include \"Direction.h\"\n#include \"Selection.h\"\n\nclass RelativeMSDDirection: public Direction {\n public:\n  RelativeMSDDirection( std::vector< std::tuple<Atom*, Atom*, double> > &relativeDistances);\n\n protected:\n  void computeGradient(Configuration* conf, Configuration* target, gsl_vector* ret);\n\n private:\n  std::vector< std::tuple<Atom*, Atom*, double> > &m_relativeDistances;\n};\n\n\n#endif //KGS_RELATIVEMSDDIRECTION_H\n", "meta": {"hexsha": "59204bf8c05be568b59fcccbc719582fc931a93a", "size": 2047, "ext": "h", "lang": "C", "max_stars_repo_path": "src/directions/RelativeMSDDirection.h", "max_stars_repo_name": "XiyuChenFAU/kgs_vibration_entropy", "max_stars_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-23T18:26:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-23T18:26:14.000Z", "max_issues_repo_path": "src/directions/RelativeMSDDirection.h", "max_issues_repo_name": "XiyuChenFAU/kgs_vibration_entropy", "max_issues_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2017-01-26T19:54:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-06T16:06:30.000Z", "max_forks_repo_path": "src/directions/RelativeMSDDirection.h", "max_forks_repo_name": "XiyuChenFAU/kgs_vibration_entropy", "max_forks_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.6226415094, "max_line_length": 92, "alphanum_fraction": 0.7352222765, "num_tokens": 467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4111108548019597, "lm_q2_score": 0.03308597529010575, "lm_q1q2_score": 0.01360200358347189}}
{"text": "/* This program is free software; you can redistribute it and/or\n   modify it under the terms of the GNU General Public License as\n   published by the Free Software Foundation; either version 2 of the\n   License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but\n   WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n   General Public License for more details.  You should have received\n   a copy of the GNU General Public License along with this program;\n   if not, write to the Free Foundation, Inc., 59 Temple Place, Suite\n   330, Boston, MA 02111-1307 USA\n\n   Original implementation was copyright (C) 1997 Makoto Matsumoto and\n   Takuji Nishimura. Coded by Takuji Nishimura, considering the\n   suggestions by Topher Cooper and Marc Rieffel in July-Aug. 1997, \"A\n   C-program for MT19937: Integer version (1998/4/6)\"\n\n   This implementation copyright (C) 1998 Brian Gough. I reorganized\n   the code to use the module framework of GSL.  The license on this\n   implementation was changed from LGPL to GPL, following paragraph 3\n   of the LGPL, version 2.\n\n   The seeding procedure has been updated to match the 10/99 release\n   of MT19937.\n\n   The original code included the comment: \"When you use this, send an\n   email to: matumoto@math.keio.ac.jp with an appropriate reference to\n   your work\".\n\n   Makoto Matsumoto has a web page with more information about the\n   generator, http://www.math.keio.ac.jp/~matumoto/emt.html. \n\n   The paper below has details of the algorithm.\n\n   From: Makoto Matsumoto and Takuji Nishimura, \"Mersenne Twister: A\n   623-dimensionally equidistributerd uniform pseudorandom number\n   generator\". ACM Transactions on Modeling and Computer Simulation,\n   Vol. 8, No. 1 (Jan. 1998), Pages 3-30\n\n   You can obtain the paper directly from Makoto Matsumoto's web page.\n\n   The period of this generator is 2^{19937} - 1.\n\n*/\n\n#include <config.h>\n#include <stdlib.h>\n#include <gsl/gsl_rng.h>\n\nstatic inline unsigned long int mt_get (void *vstate);\nstatic double mt_get_double (void *vstate);\nstatic void mt_set (void *state, unsigned long int s);\n\n#define N 624\t/* Period parameters */\n#define M 397\n\n/* most significant w-r bits */\nstatic const unsigned long UPPER_MASK = 0x80000000UL;\t\n\n/* least significant r bits */\nstatic const unsigned long LOWER_MASK = 0x7fffffffUL;\t\n\ntypedef struct\n  {\n    unsigned long mt[N];\n    int mti;\n  }\nmt_state_t;\n\nstatic inline unsigned long\nmt_get (void *vstate)\n{\n  mt_state_t *state = (mt_state_t *) vstate;\n\n  unsigned long k ;\n  unsigned long int *const mt = state->mt;\n\n#define MAGIC(y) (((y)&0x1) ? 0x9908b0dfUL : 0)\n\n  if (state->mti >= N)\n    {\t/* generate N words at one time */\n      int kk;\n\n      for (kk = 0; kk < N - M; kk++)\n\t{\n\t  unsigned long y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK);\n\t  mt[kk] = mt[kk + M] ^ (y >> 1) ^ MAGIC(y);\n\t}\n      for (; kk < N - 1; kk++)\n\t{\n\t  unsigned long y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK);\n\t  mt[kk] = mt[kk + (M - N)] ^ (y >> 1) ^ MAGIC(y);\n\t}\n\n      {\n\tunsigned long y = (mt[N - 1] & UPPER_MASK) | (mt[0] & LOWER_MASK);\n\tmt[N - 1] = mt[M - 1] ^ (y >> 1) ^ MAGIC(y);\n      }\n\n      state->mti = 0;\n    }\n\n  /* Tempering */\n  \n  k = mt[state->mti];\n  k ^= (k >> 11);\n  k ^= (k << 7) & 0x9d2c5680UL;\n  k ^= (k << 15) & 0xefc60000UL;\n  k ^= (k >> 18);\n\n  state->mti++;\n\n  return k;\n}\n\nstatic double\nmt_get_double (void * vstate)\n{\n  return mt_get (vstate) / 4294967296.0 ;\n}\n\nstatic void\nmt_set (void *vstate, unsigned long int s)\n{\n  mt_state_t *state = (mt_state_t *) vstate;\n  int i;\n\n  if (s == 0)\n    s = 4357;\t/* the default seed is 4357 */\n\n  /* This is the October 1999 version of the seeding procedure. It\n     was updated by the original developers to avoid the periodicity\n     in the simple congruence originally used.\n\n     Note that an ANSI-C unsigned long integer arithmetic is\n     automatically modulo 2^32 (or a higher power of two), so we can\n     safely ignore overflow. */\n\n#define LCG(x) ((69069 * x) + 1) &0xffffffffUL\n\n  for (i = 0; i < N; i++)\n    {\n      state->mt[i] = s & 0xffff0000UL;\n      s = LCG(s);\n      state->mt[i] |= (s &0xffff0000UL) >> 16;\n      s = LCG(s);\n    }\n\n  state->mti = i;\n}\n\n/* This is the original version of the seeding procedure, no longer\n   used but available for compatibility with the original MT19937. */\n\nstatic void\nmt_1998_set (void *vstate, unsigned long int s)\n{\n  mt_state_t *state = (mt_state_t *) vstate;\n  int i;\n\n  if (s == 0)\n    s = 4357;\t/* the default seed is 4357 */\n\n  state->mt[0] = s & 0xffffffffUL;\n\n#define LCG1998(n) ((69069 * n) & 0xffffffffUL)\n\n  for (i = 1; i < N; i++)\n    state->mt[i] = LCG1998 (state->mt[i - 1]);\n\n  state->mti = i;\n}\n\nstatic const gsl_rng_type mt_type =\n{\"mt19937\",\t\t\t/* name */\n 0xffffffffUL,\t\t\t/* RAND_MAX  */\n 0,\t\t\t        /* RAND_MIN  */\n sizeof (mt_state_t),\n &mt_set,\n &mt_get,\n &mt_get_double};\n\nstatic const gsl_rng_type mt_1998_type =\n{\"mt19937_1998\",\t\t/* name */\n 0xffffffffUL,\t\t\t/* RAND_MAX  */\n 0,\t\t\t        /* RAND_MIN  */\n sizeof (mt_state_t),\n &mt_1998_set,\n &mt_get,\n &mt_get_double};\n\nconst gsl_rng_type *gsl_rng_mt19937 = &mt_type;\nconst gsl_rng_type *gsl_rng_mt19937_1998 = &mt_1998_type;\n\n/* MT19937 is the default generator, so define that here too */\n\nconst gsl_rng_type *gsl_rng_default = &mt_type;\nunsigned long int gsl_rng_default_seed = 0;\n", "meta": {"hexsha": "eac955534d7b6c6c7d0a8b42c7c3683d7c15fe55", "size": 5449, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/rng/mt.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/rng/mt.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/rng/mt.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 27.245, "max_line_length": 71, "alphanum_fraction": 0.6630574417, "num_tokens": 1678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31742627850202554, "lm_q2_score": 0.04272219739413732, "lm_q1q2_score": 0.013561148128249944}}
{"text": "/*\t$Id$ */\n/*\n * Copyright (c) 2014 Kristaps Dzonsons <kristaps@kcons.eu>\n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n */\n#include <assert.h>\n#include <ctype.h>\n#include <math.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include <gtk/gtk.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_multifit.h>\n#include <gsl/gsl_histogram.h>\n#include <kplot.h>\n\n#include \"extern.h\"\n\n#define\tBUFSZ 1024\n\n/*\n * All possible input tokens, including some which are \"virtual\" tokens\n * in that they don't map to an exact character representation.\n */\nenum\ttoken {\n\tTOKEN_PAREN_OPEN,\n\tTOKEN_PAREN_CLOSE,\n\tTOKEN_ADD,\n\tTOKEN_SUB,\n\tTOKEN_MUL,\n\tTOKEN_DIV,\n\tTOKEN_EXP,\n\tTOKEN_END,\n\tTOKEN_NUMBER,\n\tTOKEN_SQRT,\n\tTOKEN_EXPF,\n\tTOKEN_P1,\n\tTOKEN_PN,\n\tTOKEN_N,\n\tTOKEN_ERROR,\n\tTOKEN_SKIP,\n\tTOKEN_POSITIVE,\n\tTOKEN_NEGATIVE,\n\tTOK__MAX\n};\n\nenum\tarity {\n\tARITY_NONE = 0,\n\tARITY_ONE,\n\tARITY_TWO\n};\n\nenum\tassoc {\n\tASSOC_NONE = 0,\n\tASSOC_L,\n\tASSOC_R,\n};\n\nstruct\ttok {\n\tchar\t\t key; /* input identifier */\n\tint\t\t prec; /* precedence (if applicable) */\n\tint\t\t oper; /* is operator? */\n\tint\t\t func; /* is function? */\n\tenum assoc\t assoc; /* associativity */\n\tenum arity\t arity; /* n-ary-ess */\n\tenum htype\t map; /* map to htype (if applicable) */\n};\n\nstatic\tconst struct tok toks[TOK__MAX] = {\n\t{ '(',  -1, 0, 0, ASSOC_NONE, ARITY_NONE, HNODE__MAX }, /* TOKEN_PAREN_OPEN */\n\t{ ')',  -1, 0, 0, ASSOC_NONE, ARITY_NONE, HNODE__MAX }, /* TOKEN_PAREN_CLOSE */\n\t{ '+',  2, 1, 0, ASSOC_L, ARITY_TWO, HNODE_ADD }, /* TOKEN_ADD */\n\t{ '-',  2, 1, 0, ASSOC_L, ARITY_TWO, HNODE_SUB }, /* TOKEN_SUB */\n\t{ '*',  3, 1, 0, ASSOC_L, ARITY_TWO, HNODE_MUL }, /* TOKEN_MUL */\n\t{ '/',  3, 1, 0, ASSOC_L, ARITY_TWO, HNODE_DIV }, /* TOKEN_DIV */\n\t{ '^',  5, 1, 0, ASSOC_R, ARITY_TWO, HNODE_EXP }, /* TOKEN_EXP */\n\t{ '\\0', -1, 0, 0, ASSOC_NONE, ARITY_NONE, HNODE__MAX }, /* TOKEN_END */\n\t{ '\\0', -1, 0, 0, ASSOC_NONE, ARITY_NONE, HNODE_NUMBER }, /* TOKEN_NUMBER */\n\t{ '\\0', -1, 0, 1, ASSOC_NONE, ARITY_NONE, HNODE_SQRT }, /* TOKEN_SQRT */\n\t{ '\\0', -1, 0, 1, ASSOC_NONE, ARITY_NONE, HNODE_EXPF }, /* TOKEN_EXPF */\n\t{ 'x',  -1, 0, 0, ASSOC_NONE, ARITY_NONE, HNODE_P1 }, /* TOKEN_P1 */\n\t{ 'X',  -1, 0, 0, ASSOC_NONE, ARITY_NONE, HNODE_PN }, /* TOKEN_PN */\n\t{ 'n',  -1, 0, 0, ASSOC_NONE, ARITY_NONE, HNODE_N }, /* TOKEN_N */\n\t{ '\\0', -1, 0, 0, ASSOC_NONE, ARITY_NONE, HNODE__MAX }, /* TOKEN_ERROR */\n\t{ ' ',  -1, 0, 0, ASSOC_NONE, ARITY_NONE, HNODE__MAX }, /* TOKEN_SKIP */\n\t{ '+',  4, 1, 0, ASSOC_R, ARITY_ONE, HNODE_POSITIVE }, /* TOKEN_POSITIVE */\n\t{ '-',  4, 1, 0, ASSOC_R, ARITY_ONE, HNODE_NEGATIVE }, /* TOKEN_NEGATIVE */\n};\n\n#if 0\nstatic void\nhnode_print(struct hnode **p)\n{\n\tstruct hnode\t**pp;\n\n\tif (NULL == p)\n\t\treturn;\n\n\tfor (pp = p; NULL != *pp; pp++) {\n\t\tswitch ((*pp)->type) {\n\t\tcase (HNODE_VAR):\n\t\t\tputchar('v');\n\t\t\tbreak;\n\t\tcase (HNODE_P1):\n\t\t\tputchar('x');\n\t\t\tbreak;\n\t\tcase (HNODE_P2):\n\t\t\tputchar('y');\n\t\t\tbreak;\n\t\tcase (HNODE_NUMBER):\n\t\t\tprintf(\"%g\", (*pp)->real);\n\t\t\tbreak;\n\t\tcase (HNODE_SQRT):\n\t\t\tprintf(\"sqrt\");\n\t\t\tbreak;\n\t\tcase (HNODE_ADD):\n\t\t\tputchar('+');\n\t\t\tbreak;\n\t\tcase (HNODE_EXP):\n\t\t\tputchar('^');\n\t\t\tbreak;\n\t\tcase (HNODE_SUB):\n\t\t\tputchar('-');\n\t\t\tbreak;\n\t\tcase (HNODE_MUL):\n\t\t\tputchar('*');\n\t\t\tbreak;\n\t\tcase (HNODE_DIV):\n\t\t\tputchar('/');\n\t\t\tbreak;\n\t\tcase (HNODE_POSITIVE):\n\t\t\tprintf(\"+'\");\n\t\t\tbreak;\n\t\tcase (HNODE_NEGATIVE):\n\t\t\tprintf(\"-'\");\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tabort();\n\t\t}\n\t\tputchar(' ');\n\t}\n\tputchar('\\n');\n}\n#endif\n\n/*\n * Check if the current token (which has ARITY_ONE, we assume) is in\n * fact unary.\n * We do this by checking the previous token: if it's a binary operator\n * or an open parenthesis, then we're a unary operator.\n */\nstatic int\ncheck_unary(enum token lasttok)\n{\n\tswitch (lasttok) {\n\tcase (TOK__MAX):\n\t\t/* FALLTHROUGH */\n\tcase (TOKEN_PAREN_OPEN):\n\t\t/* FALLTHROUGH */\n\tcase (TOKEN_ADD):\n\t\t/* FALLTHROUGH */\n\tcase (TOKEN_SUB):\n\t\t/* FALLTHROUGH */\n\tcase (TOKEN_MUL):\n\t\t/* FALLTHROUGH */\n\tcase (TOKEN_DIV):\n\t\t/* FALLTHROUGH */\n\tcase (TOKEN_EXP):\n\t\treturn(1);\n\tdefault:\n\t\tbreak;\n\t}\n\treturn(0);\n}\n\n/*\n * Check if the current token (which has ARITY_TWO, we assume) is in\n * fact binary.\n * We do this by checking the previous token: if it's an operand or a\n * close-paren (i.e., an operand), then we're a binary operator.\n */\nstatic int\ncheck_binary(enum token lasttok)\n{\n\tswitch (lasttok) {\n\tcase (TOKEN_PAREN_CLOSE):\n\t\t/* FALLTHROUGH */\n\tcase (TOKEN_NUMBER):\n\t\t/* FALLTHROUGH */\n\tcase (TOKEN_P1):\n\t\t/* FALLTHROUGH */\n\tcase (TOKEN_PN):\n\t\t/* FALLTHROUGH */\n\tcase (TOKEN_N):\n\t\treturn(1);\n\tdefault:\n\t\tbreak;\n\t}\n\treturn(0);\n}\n\n/*\n * Extra a token from input.\n * If TOKEN_ERROR, something bad has happened in the attempt to do so.\n * Otherwise, this returns a valid token (possibly end of input).\n */\nstatic enum token\ntokenise(const char **v, char *buf, enum token lasttok)\n{\n\tsize_t\t\ti, sz;\n\n\t/* Short-circuit this case. */\n\tif ('\\0' == **v)\n\t\treturn(TOKEN_END);\n\n\t/* Look for token in our predefined inputs. */\n\tfor (i = 0; i < TOK__MAX; i++)\n\t\tif ('\\0' != toks[i].key && **v == toks[i].key) {\n\t\t\tswitch (toks[i].arity) {\n\t\t\tcase (ARITY_NONE):\n\t\t\t\t(*v)++;\n\t\t\t\treturn((enum token)i);\n\t\t\tcase (ARITY_ONE):\n\t\t\t\tif ( ! check_unary(lasttok))\n\t\t\t\t\tcontinue;\n\t\t\t\tbreak;\n\t\t\tcase (ARITY_TWO):\n\t\t\t\tif ( ! check_binary(lasttok))\n\t\t\t\t\tcontinue;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t(*v)++;\n\t\t\treturn((enum token)i);\n\t\t}\n\n\t/* See if we're a real number or identifier. */\n\tif (isdigit((int)**v) || '.' == **v) {\n\t\tsz = 0;\n\t\tfor ( ; isdigit((int)**v) || '.' == **v; (*v)++) {\n\t\t\tassert(sz < BUFSZ);\n\t\t\tbuf[sz++] = **v;\n\t\t}\n\t\tbuf[sz] = '\\0';\n\t\treturn(TOKEN_NUMBER);\n\t} else if (isalpha((int)**v)) {\n\t\tsz = 0;\n\t\tfor ( ; isalpha((int)**v); (*v)++) {\n\t\t\tassert(sz < BUFSZ);\n\t\t\tbuf[sz++] = **v;\n\t\t}\n\t\tbuf[sz] = '\\0';\n\t\tif (0 == strcmp(buf, \"sqrt\"))\n\t\t\treturn(TOKEN_SQRT);\n\t\telse if (0 == strcmp(buf, \"exp\"))\n\t\t\treturn(TOKEN_EXPF);\n\t} \n\n\t/* Eh... */\n\treturn(TOKEN_ERROR);\n}\n\n/*\n * Queue something onto the output RPN queue.\n */\nstatic void\nenqueue(struct hnode ***q, size_t *qsz, enum token tok)\n{\n\n\t*q = realloc(*q, ++(*qsz) * sizeof(struct hnode *));\n\t(*q)[*qsz - 1] = calloc(1, sizeof(struct hnode));\n\t(*q)[*qsz - 1]->type = toks[tok].map;\n\tassert(HNODE__MAX != toks[tok].map);\n}\n\n/*\n * Make sure that all operators and functions are matched with\n * arguments.\n * The Shunting-Yard algorithm itself doesn't do this, so we need to do\n * it now.\n */\nstatic int\ncheck(struct hnode **p)\n{\n\tstruct hnode\t**pp;\n\tsize_t\t\t  ssz;\n\n\tfor (ssz = 0, pp = p; NULL != *pp; pp++)\n\t\tswitch ((*pp)->type) {\n\t\tcase (HNODE_P1):\n\t\t\t/* FALLTHROUGH */\n\t\tcase (HNODE_PN):\n\t\t\t/* FALLTHROUGH */\n\t\tcase (HNODE_N):\n\t\t\t/* FALLTHROUGH */\n\t\tcase (HNODE_NUMBER):\n\t\t\tssz++;\n\t\t\tbreak;\n\t\tcase (HNODE_POSITIVE):\n\t\t\t/* FALLTHROUGH */\n\t\tcase (HNODE_NEGATIVE):\n\t\t\t/* FALLTHROUGH */\n\t\tcase (HNODE_SQRT):\n\t\t\t/* FALLTHROUGH */\n\t\tcase (HNODE_EXPF):\n\t\t\tif (0 == ssz)\n\t\t\t\treturn(0);\n\t\t\tbreak;\n\t\tcase (HNODE_ADD):\n\t\t\t/* FALLTHROUGH */\n\t\tcase (HNODE_SUB):\n\t\t\t/* FALLTHROUGH */\n\t\tcase (HNODE_MUL):\n\t\t\t/* FALLTHROUGH */\n\t\tcase (HNODE_DIV):\n\t\t\t/* FALLTHROUGH */\n\t\tcase (HNODE_EXP):\n\t\t\tif (ssz < 2)\n\t\t\t\treturn(0);\n\t\t\tssz--;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tabort();\n\t\t}\n\n\treturn(1 == ssz);\n}\n\n/*\n * Dijkstra's Shunting-Yard algorithm for converting an infix-order\n * expression to prefix order.\n * This returns a NULL-terminated list of expressions to evaluate in\n * post-fix order.\n */\nstruct hnode **\nhnode_parse(const char **v)\n{\n\tenum token\t  tok, lasttok;\n\tenum token\t  stack[STACKSZ];\n\tchar\t\t  buf[BUFSZ + 1];\n\tstruct hnode\t**q;\n\tint\t\t  found;\n\tsize_t\t\t  i, qsz, ssz;\n\n\tq = NULL;\n\tqsz = ssz = 0;\n\tlasttok = TOK__MAX;\n\n\twhile (TOKEN_END != (tok = tokenise(v, buf, lasttok))) {\n\t\tswitch (tok) {\n\t\tcase (TOKEN_ERROR): \n\t\t\tgoto err;\n\t\tcase (TOKEN_SKIP):\n\t\t\tbreak;\n\t\tcase (TOKEN_P1):\n\t\t\t/* FALLTHROUGH */\n\t\tcase (TOKEN_PN):\n\t\t\t/* FALLTHROUGH */\n\t\tcase (TOKEN_N):\n\t\t\tenqueue(&q, &qsz, tok);\n\t\t\tbreak;\n\t\tcase (TOKEN_NUMBER):\n\t\t\tenqueue(&q, &qsz, tok);\n\t\t\tq[qsz - 1]->real = atof(buf);\n\t\t\tbreak;\n\t\tcase (TOKEN_SQRT):\n\t\t\t/* FALLTHROUGH */\n\t\tcase (TOKEN_EXPF):\n\t\t\t/* FALLTHROUGH */\n\t\tcase (TOKEN_PAREN_OPEN):\n\t\t\tassert(ssz < STACKSZ);\n\t\t\tstack[ssz++] = tok;\n\t\t\tbreak;\n\t\tcase (TOKEN_PAREN_CLOSE):\n\t\t\tassert(ssz > 0);\n\t\t\tfound = 0;\n\t\t\tdo {\n\t\t\t\tif (TOKEN_PAREN_OPEN == stack[--ssz])\n\t\t\t\t\tfound = 1;\n\t\t\t\telse\n\t\t\t\t\tenqueue(&q, &qsz, stack[ssz]);\n\t\t\t} while ( ! found && ssz > 0);\n\t\t\tassert(found);\n\t\t\tif (ssz > 0 && toks[stack[ssz - 1]].func)\n\t\t\t\tenqueue(&q, &qsz, stack[--ssz]);\n\t\t\tbreak;\n\t\tcase (TOKEN_POSITIVE):\n\t\t\t/* FALLTHROUGH */\n\t\tcase (TOKEN_NEGATIVE):\n\t\t\t/* FALLTHROUGH */\n\t\tcase (TOKEN_SUB):\n\t\t\t/* FALLTHROUGH */\n\t\tcase (TOKEN_MUL):\n\t\t\t/* FALLTHROUGH */\n\t\tcase (TOKEN_DIV):\n\t\t\t/* FALLTHROUGH */\n\t\tcase (TOKEN_EXP):\n\t\t\t/* FALLTHROUGH */\n\t\tcase (TOKEN_ADD):\n\t\t\tassert(toks[tok].prec >= 0);\n\t\t\tassert(ASSOC_NONE != toks[tok].assoc);\n\t\t\twhile (ssz > 0 && toks[stack[ssz - 1]].oper) {\n\t\t\t\tassert(toks[stack[ssz - 1]].prec >= 0);\n\t\t\t\tassert(ASSOC_NONE != \n\t\t\t\t\ttoks[stack[ssz - 1]].assoc);\n\t\t\t\tif ((ASSOC_L == toks[tok].assoc \n\t\t\t\t\t && toks[tok].prec == \n\t\t\t\t\t toks[stack[ssz - 1]].prec) || \n\t\t\t\t\t (toks[tok].prec < \n\t\t\t\t\t  toks[stack[ssz - 1]].prec))\n\t\t\t\t\tenqueue(&q, &qsz, stack[--ssz]);\n\t\t\t\telse\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tassert(ssz < STACKSZ);\n\t\t\tstack[ssz++] = tok;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tabort();\n\t\t}\n\t\tif (TOKEN_SKIP != tok)\n\t\t\tlasttok = tok;\n\t}\n\n\twhile (ssz > 0) {\n\t\t--ssz;\n\t\tif (TOKEN_PAREN_OPEN == stack[ssz])\n\t\t\tgoto err;\n\t\tenqueue(&q, &qsz, stack[ssz]);\n\t} \n\n\tq = realloc(q, ++qsz * sizeof(struct hnode *));\n\tq[qsz - 1] = NULL;\n\n\tif ( ! check(q))\n\t\tgoto err;\n\n#if 0\n\thnode_print(q);\n#endif\n\treturn(q);\nerr:\n\tfor (i = 0; i < qsz; i++)\n\t\tfree(q[i]);\n\tfree(q);\n\treturn(NULL);\n}\n\nstruct hnode **\nhnode_copy(struct hnode **p)\n{\n\tstruct hnode\t**pp;\n\tsize_t\t\t  sz;\n\n\tfor (sz = 0, pp = p; NULL != *pp; pp++)\n\t\tsz++;\n\n\tpp = calloc(sz + 1, sizeof(struct hnode *));\n\tfor (sz = 0; NULL != *p; p++, sz++) {\n\t\tpp[sz] = calloc(1, sizeof(struct hnode));\n\t\tpp[sz]->type = (*p)->type;\n\t\tpp[sz]->real = (*p)->real;\n\t}\n\n\treturn(pp);\n}\n\nvoid\nhnode_free(struct hnode **p)\n{\n\tstruct hnode\t**pp;\n\n\tif (NULL == p)\n\t\treturn;\n\n\tfor (pp = p; NULL != *pp; pp++)\n\t\tfree(*pp);\n\n\tfree(p);\n}\n\n/*\n * Execute a function in prefix order given variables x (given player's\n * strategy), y (other player's strategy), and var (given player's\n * morality index).\n */\ndouble\nhnode_exec(const struct hnode *const *p, double x, double X, size_t n)\n{\n\tdouble\t\t  stack[STACKSZ];\n\tconst struct hnode *const *pp;\n\tsize_t\t\t  ssz;\n\tdouble\t\t  val;\n\n\tfor (ssz = 0, pp = p; NULL != *pp; pp++)\n\t\tswitch ((*pp)->type) {\n\t\tcase (HNODE_P1):\n\t\t\tassert(ssz < STACKSZ);\n\t\t\tstack[ssz++] = x;\n\t\t\tbreak;\n\t\tcase (HNODE_PN):\n\t\t\tassert(ssz < STACKSZ);\n\t\t\tstack[ssz++] = X;\n\t\t\tbreak;\n\t\tcase (HNODE_N):\n\t\t\tassert(ssz < STACKSZ);\n\t\t\tstack[ssz++] = (double)n;\n\t\t\tbreak;\n\t\tcase (HNODE_NUMBER):\n\t\t\tassert(ssz < STACKSZ);\n\t\t\tstack[ssz++] = (*pp)->real;\n\t\t\tbreak;\n\t\tcase (HNODE_SQRT):\n\t\t\tassert(ssz > 0);\n\t\t\tval = sqrt(stack[--ssz]);\n\t\t\tstack[ssz++] = val;\n\t\t\tbreak;\n\t\tcase (HNODE_EXPF):\n\t\t\tassert(ssz > 0);\n\t\t\tval = exp(stack[--ssz]);\n\t\t\tstack[ssz++] = val;\n\t\t\tbreak;\n\t\tcase (HNODE_ADD):\n\t\t\tassert(ssz > 1);\n\t\t\tval = stack[ssz - 2] + stack[ssz - 1];\n\t\t\tssz -= 2;\n\t\t\tstack[ssz++] = val;\n\t\t\tbreak;\n\t\tcase (HNODE_SUB):\n\t\t\tassert(ssz > 1);\n\t\t\tval = stack[ssz - 2] - stack[ssz - 1];\n\t\t\tssz -= 2;\n\t\t\tstack[ssz++] = val;\n\t\t\tbreak;\n\t\tcase (HNODE_MUL):\n\t\t\tassert(ssz > 1);\n\t\t\tval = stack[ssz - 2] * stack[ssz - 1];\n\t\t\tssz -= 2;\n\t\t\tstack[ssz++] = val;\n\t\t\tbreak;\n\t\tcase (HNODE_DIV):\n\t\t\tassert(ssz > 1);\n\t\t\tval = stack[ssz - 2] / stack[ssz - 1];\n\t\t\tssz -= 2;\n\t\t\tstack[ssz++] = val;\n\t\t\tbreak;\n\t\tcase (HNODE_EXP):\n\t\t\tassert(ssz > 1);\n\t\t\tval = pow(stack[ssz - 2], stack[ssz - 1]);\n\t\t\tssz -= 2;\n\t\t\tstack[ssz++] = val;\n\t\t\tbreak;\n\t\tcase (HNODE_POSITIVE):\n\t\t\tassert(ssz > 0);\n\t\t\tbreak;\n\t\tcase (HNODE_NEGATIVE):\n\t\t\tassert(ssz > 0);\n\t\t\tval = -(stack[--ssz]);\n\t\t\tstack[ssz++] = val;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tabort();\n\t\t}\n\n\tassert(1 == ssz);\n\treturn(stack[0]);\n}\n\nstatic void\nhnode_test_expect(double x, double X, \n\tdouble n, const char *expf, double vexp)\n{\n\tstruct hnode\t **exp;\n\tdouble\t\t   v;\n\tconst char\t  *expfp;\n\n\texpfp = expf;\n\texp = hnode_parse((const char **)&expfp);\n\tassert(NULL != exp);\n\tv = hnode_exec\n\t\t((const struct hnode *const *)exp, x, X, n);\n\tg_debug(\"pi(x=%g, X=%g, n=%g) = %s = %g (want %g)\", \n\t\tx, X, n, expf, v, vexp);\n\thnode_free(exp);\n}\n\nvoid\nhnode_test(void)\n{\n\tdouble\tx, X, n;\n\n\tx = 10.0;\n\tX = 20.0;\n\tn = 2.0;\n\thnode_test_expect(x, X, n, \n\t\t\"(1 - exp(-X)) - x\", \n\t\t(1.0 - exp(-X)) - x);\n\thnode_test_expect(x, X, n, \n\t\t\"sqrt(1 / n * X) - 0.5 * x^2\", \n\t\tsqrt(1.0 / n * X) - 0.5 * pow(x, 2.0));\n\thnode_test_expect(x, X, n, \n\t\t\"x - (X - x) * x - x^2\",\n\t\tx - (X - x) * x - pow(x, 2.0));\n\thnode_test_expect(x, X, n, \n\t\t\"x * (1 / X) - x\",\n\t\tx * (1.0 / X) - x);\n}\n", "meta": {"hexsha": "eeb79d3cad3fada0c42ac79f1107fd4d1d8c64ed", "size": 13390, "ext": "c", "lang": "C", "max_stars_repo_path": "parser.c", "max_stars_repo_name": "kristapsdz/bmigrate", "max_stars_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-03-03T17:13:19.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-03T17:13:19.000Z", "max_issues_repo_path": "parser.c", "max_issues_repo_name": "kristapsdz/bmigrate", "max_issues_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "parser.c", "max_forks_repo_name": "kristapsdz/bmigrate", "max_forks_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5619967794, "max_line_length": 80, "alphanum_fraction": 0.5910380881, "num_tokens": 4603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167300566462553, "lm_q2_score": 0.03067580038142513, "lm_q1q2_score": 0.013548672955632104}}
{"text": "/**\n * \\file TypedBaseFilter.h\n */\n\n#ifndef ATK_CORE_TYPEDBASEFILTER_H\n#define ATK_CORE_TYPEDBASEFILTER_H\n\n#include <ATK/Core/BaseFilter.h>\n#include <ATK/Core/TypeTraits.h>\n\n#include <memory>\n#include <vector>\n\n#include <boost/align/aligned_allocator.hpp>\n\n#include <gsl/gsl>\n\nnamespace ATK\n{\n  const gsl::index ALIGNMENT = 32;\n\n  /// Interface for output filters\n  template<typename DataType>\n  class ATK_CORE_EXPORT OutputArrayInterface\n  {\n  public:\n    virtual ~OutputArrayInterface() = default;\n\n    /**\n     * @brief Returns an array with the processed output\n     * @param port is the port that the next plugin listens to\n     */\n    virtual DataType* get_output_array(gsl::index port) const = 0;\n    /**\n     * Returns the size of the output arrays (usually the last size processed)\n     */\n    virtual gsl::index get_output_array_size() const = 0;\n  };\n\n  /// Base class for typed filters, contains arrays\n  template<typename DataType_, typename DataType__ = DataType_>\n  class ATK_CORE_EXPORT TypedBaseFilter : public BaseFilter, public OutputArrayInterface<DataType__>\n  {\n  protected:\n    /// Simplify parent calls\n    using Parent = BaseFilter;\n  public:\n    /// To be used by inherited APIs\n    using DataType = DataType_;\n    /// To be used by inherited APIs\n    using DataTypeInput = DataType_;\n    /// To be used by inherited APIs\n    using DataTypeOutput = DataType__;\n    /// To be used for filters that require aligned data\n    using AlignedVector = std::vector<DataTypeInput, boost::alignment::aligned_allocator<DataTypeInput, ALIGNMENT> >;\n    /// To be used for filters that require aligned data for output data\n    using AlignedOutVector = std::vector<DataTypeOutput, boost::alignment::aligned_allocator<DataTypeOutput, ALIGNMENT> >;\n    /// To be used for filters that required aligned data for parameters (like EQ)\n    using AlignedScalarVector = std::vector<typename TypeTraits<DataType>::Scalar, boost::alignment::aligned_allocator<typename TypeTraits<DataType>::Scalar, ALIGNMENT> >;\n\n    /// Base constructor for filters with actual data\n    TypedBaseFilter(gsl::index nb_input_ports, gsl::index nb_output_ports);\n    /// Move constructor\n    TypedBaseFilter(TypedBaseFilter&& other);\n    /// Destructor\n    ~TypedBaseFilter() override = default;\n\n    TypedBaseFilter(const TypedBaseFilter&) = delete;\n    TypedBaseFilter& operator=(const TypedBaseFilter&) = delete;\n\n    /**\n     * @brief Returns an array with the processed output\n     * @param port is the port that the next plugin listens to\n     */\n    DataType__* get_output_array(gsl::index port) const final;\n    gsl::index get_output_array_size() const final;\n\n    void set_nb_input_ports(gsl::index nb_ports) override;\n    void set_nb_output_ports(gsl::index nb_ports) override;\n\n    void full_setup() override;\n\n    /// Connects this filter input to another's output\n    void set_input_port(gsl::index input_port, gsl::not_null<BaseFilter*> filter, gsl::index output_port) final;\n    void set_input_port(gsl::index input_port, BaseFilter& filter, gsl::index output_port) final;\n\n  private:\n    int get_type() const override;\n  protected:\n    /// This implementation does nothing\n    void process_impl(gsl::index size) const override;\n    /// Prepares the filter by retrieving the inputs arrays\n    void prepare_process(gsl::index size) final;\n    /// Prepares the filter by resizing the outputs arrays\n    void prepare_outputs(gsl::index size) final;\n\n    /// Used to convert other filter outputs to DataType*\n    void convert_inputs(gsl::index size);\n\n    /// Input arrays with the input delay, owned here\n    std::vector<AlignedVector> converted_inputs_delay;\n    /// Input arrays, starting from t=0 (without input delay)\n    std::vector<DataTypeInput*> converted_inputs;\n    /// Current size of the input arrays, without delay\n    std::vector<gsl::index> converted_inputs_size;\n    /// Current input delay\n    std::vector<gsl::index> converted_in_delays;\n    /// Pointer to the output interface of the connected filters\n    std::vector<OutputArrayInterface<DataType_>*> direct_filters;\n\n    /// Output arrays with the output delay, owned here\n    std::vector<AlignedOutVector> outputs_delay;\n    /// Output arrays, starting from t=0 (without output delay)\n    std::vector<DataTypeOutput*> outputs;\n    /// Current size of the output arrays, without delay\n    std::vector<gsl::index> outputs_size;\n    /// Current output delay\n    std::vector<gsl::index> out_delays;\n\n    /// A vector containing the default values for the input arrays\n    AlignedVector default_input;\n    /// A vector containing the default values for the output arrays\n    AlignedOutVector default_output;\n  };\n}\n\n#endif\n", "meta": {"hexsha": "48f7a9d888238363a7cc405c53e97889b61ac2f6", "size": 4683, "ext": "h", "lang": "C", "max_stars_repo_path": "ATK/Core/TypedBaseFilter.h", "max_stars_repo_name": "D-J-Roberts/AudioTK", "max_stars_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 249.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T13:36:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T18:47:46.000Z", "max_issues_repo_path": "ATK/Core/TypedBaseFilter.h", "max_issues_repo_name": "D-J-Roberts/AudioTK", "max_issues_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2015-07-28T15:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-11T14:18:19.000Z", "max_forks_repo_path": "ATK/Core/TypedBaseFilter.h", "max_forks_repo_name": "D-J-Roberts/AudioTK", "max_forks_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 48.0, "max_forks_repo_forks_event_min_datetime": "2015-08-15T12:08:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-07T02:33:07.000Z", "avg_line_length": 36.5859375, "max_line_length": 171, "alphanum_fraction": 0.7249626308, "num_tokens": 1069, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29421498454004374, "lm_q2_score": 0.04603390747069532, "lm_q1q2_score": 0.013543865374808428}}
{"text": "/*\r\n * Copyright 2014 RWTH Aachen University. All rights reserved.\r\n *\r\n * Licensed under the RWTH LM License (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n#pragma once\r\n#include <gsl/gsl_cblas.h>\r\n#include <cassert>\r\n#include <cstring>\r\n#include <cmath>\r\n#include <algorithm>\r\n#include <numeric>\r\n\r\ntypedef double Real;\r\n\r\ninline void FastZero(const int size, float x[]) {\r\n  std::fill(x, x + size, 0.0f);\r\n}\r\n\r\ninline void FastZero(const int size, double x[]) {\r\n  std::fill(x, x + size, 0.0);\r\n}\r\n\r\ninline void FastCopy(const float source[],\r\n                     const int size,\r\n                     float destination[]) {\r\n  memcpy(destination, source, size * sizeof(float));\r\n}\r\n\r\ninline void FastCopy(const double source[], \r\n                     const int size,\r\n                     double destination[]) {\r\n  memcpy(destination, source, size * sizeof(double));\r\n}\r\n\r\ninline float FastMax(const float x[], const int size) {\r\n  return *std::max_element(x, x + size);\r\n}\r\n\r\ninline double FastMax(const double x[], const int size) {\r\n  return *std::max_element(x, x + size);\r\n}\r\n\r\ninline float FastComputeSum(const float x[], const int size) {\r\n  return std::accumulate(x, x + size, 0.0f);\r\n}\r\n\r\ninline double FastComputeSum(const double x[], const int size) {\r\n  return std::accumulate(x, x + size, 0.0);\r\n}\r\n\r\ninline void FastAddConstant(const float source[],\r\n                            const int size,\r\n                            const float value,\r\n                            float destination[]) {\r\n  std::transform(source,\r\n                 source + size,\r\n                 destination,\r\n                 [value](const float x) { return x + value; });\r\n}\r\n\r\ninline void FastAddConstant(const double source[],\r\n                            const int size,\r\n                            const double value,\r\n                            double destination[]) {\r\n  std::transform(source,\r\n                 source + size,\r\n                 destination,\r\n                 [value](const double x) { return x + value; });\r\n}\r\n\r\ninline void FastSubtractConstant(const float source[],\r\n                                 const int size,\r\n                                 const float value,\r\n                                 float destination[]) {\r\n  std::transform(source,\r\n                 source + size,\r\n                 destination,\r\n                 [value](const double x) { return x - value; });\r\n}\r\n\r\ninline void FastSubtractConstant(const double source[],\r\n                                 const int size,\r\n                                 const double value,\r\n                                 double destination[]) {\r\n  std::transform(source,\r\n                 source + size,\r\n                 destination,\r\n                 [value](const double x) { return x - value; });\r\n}\r\n\r\ninline void FastReverseSubtractConstant(\r\n    const float source[],\r\n    const int size,\r\n    const float value,\r\n    float destination[]) {\r\n  std::transform(source,\r\n                 source + size,\r\n                 destination,\r\n                 [value](const float x) { return value - x; });\r\n}\r\n\r\ninline void FastReverseSubtractConstant(\r\n    const double source[],\r\n    const int size,\r\n    const double value,\r\n    double destination[]) {\r\n  std::transform(source,\r\n                 source + size,\r\n                 destination,\r\n                 [value](const double x) { return value - x; });\r\n}\r\n\r\ninline void FastMultiplyByConstant(const float source[],\r\n                                   const int size,\r\n                                   const float value,\r\n                                   float destination[]) {\r\n  std::transform(source,\r\n                 source + size,\r\n                 destination,\r\n                 [value](const float x) { return value * x; });\r\n}\r\n\r\ninline void FastMultiplyByConstant(const double source[],\r\n                                   const int size,\r\n                                   const double value,\r\n                                   double destination[]) {\r\n  std::transform(source,\r\n                 source + size,\r\n                 destination,\r\n                 [value](const double x) { return value * x; });\r\n}\r\n\r\ninline void FastDivideByConstant(const float source[],\r\n                                 const int size,\r\n                                 const float value,\r\n                                 float destination[]) {\r\n  std::transform(source,\r\n                 source + size,\r\n                 destination,\r\n                 [value](const float x) { return x / value; });\r\n}\r\n\r\ninline void FastDivideByConstant(const double source[],\r\n                                 const int size,\r\n                                 const double value,\r\n                                 double destination[]) {\r\n  std::transform(source,\r\n                 source + size,\r\n                 destination,\r\n                 [value](const double x) { return x / value; });\r\n}\r\n\r\ninline void FastInvert(const float source[],\r\n                       const int size,\r\n                       float destination[]) {\r\n  std::transform(source,\r\n                 source + size,\r\n                 destination,\r\n                 [](const double x) { return 1.0f / x; });\r\n}\r\n\r\ninline void FastInvert(const double source[],\r\n                       const int size,\r\n                       double destination[]) {\r\n  std::transform(source,\r\n                 source + size,\r\n                 destination,\r\n                 [](const double x) { return 1.0 / x; });\r\n}\r\n\r\ninline void FastAdd(const float a[],\r\n                    const int size,\r\n                    const float b[],\r\n                    float c[]) {\r\n  std::transform(a,\r\n                 a + size,\r\n                 b,\r\n                 c,\r\n                 [](const float x, const float y) { return x + y; });\r\n}\r\n\r\ninline void FastAdd(const double a[],\r\n                    const int size,\r\n                    const double b[],\r\n                    double c[]) {\r\n  std::transform(a,\r\n                 a + size,\r\n                 b,\r\n                 c,\r\n                 [](const double x, const double y) { return x + y; });\r\n}\r\n\r\ninline void FastMultiplyByConstantAdd(const float alpha,\r\n                                      const float a[],\r\n                                      const int size,\r\n                                      float b[]) {\r\n  cblas_saxpy(size, alpha, a, 1, b, 1);\r\n}\r\n\r\ninline void FastMultiplyByConstantAdd(const double alpha,\r\n                                      const double a[],\r\n                                      const int size,\r\n                                      double b[]) {\r\n  cblas_daxpy(size, alpha, a, 1, b, 1);\r\n}\r\n\r\ninline void FastSub(const float a[],\r\n                    const int size,\r\n                    const float b[],\r\n                    float c[]) {\r\n  std::transform(a,\r\n                 a + size,\r\n                 b,\r\n                 c,\r\n                 [](const float x, const float y) { return x - y; });\r\n}\r\n\r\ninline void FastSub(const double a[],\r\n                    const int size,\r\n                    const double b[],\r\n                    double c[]) {\r\n  std::transform(a,\r\n                 a + size,\r\n                 b,\r\n                 c,\r\n                 [](const double x, const double y) { return x - y; });\r\n}\r\n\r\ninline void FastMultiply(const float a[],\r\n                         const int size,\r\n                         const float b[],\r\n                         float c[]) {\r\n  std::transform(a,\r\n                 a + size,\r\n                 b,\r\n                 c,\r\n                 [](const float x, const float y) { return x * y; });\r\n}\r\n\r\ninline void FastMultiply(const double a[],\r\n                         const int size,\r\n                         const double b[],\r\n                         double c[]) {\r\n  std::transform(a,\r\n                 a + size,\r\n                 b,\r\n                 c,\r\n                 [](const double x, const double y) { return x * y; });\r\n}\r\n\r\ninline void FastMultiplyAdd(const float a[],\r\n                            const int size,\r\n                            const float b[],\r\n                            float c[]) {\r\n  for (int i = 0; i < size; ++i)\r\n    c[i] += a[i] * b[i];\r\n}\r\n\r\ninline void FastMultiplyAdd(const double a[],\r\n                            const int size,\r\n                            const double b[],\r\n                            double c[]) {\r\n  for (int i = 0; i < size; ++i)\r\n    c[i] += a[i] * b[i];\r\n}\r\n\r\ninline void FastTanh(const float source[],\r\n                     const int size,\r\n                     float destination[]) {\r\n  std::transform(source,\r\n                 source + size,\r\n                 destination,\r\n                 [](const float x) { return std::tanh(x); });\r\n}\r\n\r\ninline void FastTanh(const double source[],\r\n                     const int size,\r\n                     double destination[]) {\r\n  std::transform(source,\r\n                 source + size,\r\n                 destination,\r\n                 [](const double x) { return std::tanh(x); });\r\n}\r\n\r\ninline void FastExponential(const float source[],\r\n                            const int size,\r\n                            float destination[]) {\r\n  std::transform(source,\r\n                 source + size,\r\n                 destination,\r\n                 [](const float x) { return std::exp(x); });\r\n}\r\n\r\ninline void FastExponential(const double source[],\r\n                            const int size,\r\n                            double destination[]) {\r\n  std::transform(source,\r\n                 source + size,\r\n                 destination,\r\n                 [](const double x) { return std::exp(x); });\r\n}\r\n\r\ninline void FastMatrixVectorMultiply(const float a[],\r\n                                     const bool transpose_a,\r\n                                     const int rows_a,\r\n                                     const int columns_a,\r\n                                     const float x[],\r\n                                     float y[]) {\r\n  cblas_sgemv(CblasColMajor,\r\n              transpose_a ? CblasTrans : CblasNoTrans,\r\n              rows_a,\r\n              columns_a,\r\n              1.0f,\r\n              a,\r\n              rows_a,\r\n              x,\r\n              1,\r\n              1.0f,\r\n              y,\r\n              1);\r\n}\r\n\r\ninline void FastMatrixVectorMultiply(const double a[],\r\n                                     const bool transpose_a,\r\n                                     const int rows_a,\r\n                                     const int columns_a,\r\n                                     const double x[],\r\n                                     double y[]) {\r\n  cblas_dgemv(CblasColMajor,\r\n              transpose_a ? CblasTrans : CblasNoTrans,\r\n              rows_a,\r\n              columns_a,\r\n              1.0,\r\n              a,\r\n              rows_a,\r\n              x,\r\n              1,\r\n              1.0,\r\n              y,\r\n              1);\r\n}\r\n\r\ninline void FastOuterProduct(const float alpha,\r\n                             const float x[],\r\n                             const int size_x,\r\n                             const float y[],\r\n                             const int size_y,\r\n                             float a[]) {\r\n  cblas_sger(CblasColMajor,\r\n             size_x,\r\n             size_y,\r\n             alpha,\r\n             x,\r\n             1,\r\n             y,\r\n             1,\r\n             a,\r\n             size_x);\r\n}\r\n\r\ninline void FastOuterProduct(const double alpha,\r\n                             const double x[],\r\n                             const int size_x,\r\n                             const double y[],\r\n                             const int size_y,\r\n                             double a[]) {\r\n  cblas_dger(CblasColMajor,\r\n             size_x,\r\n             size_y,\r\n             alpha,\r\n             x,\r\n             1,\r\n             y,\r\n             1,\r\n             a,\r\n             size_x);\r\n}\r\n\r\ninline void FastMatrixMatrixMultiply(\r\n      const float alpha,\r\n      const float a[],\r\n      const bool transpose_a,\r\n      const int rows_a,\r\n      const int columns_a,\r\n      const float b[],\r\n      const bool transpose_b,\r\n      const int columns_b,\r\n      float c[]) {\r\n  cblas_sgemm(CblasColMajor,\r\n              transpose_a ? CblasTrans : CblasNoTrans,\r\n              transpose_b ? CblasTrans : CblasNoTrans,\r\n              rows_a,\r\n              columns_b,\r\n              columns_a,\r\n              alpha,\r\n              a,\r\n              transpose_a ? columns_a : rows_a,\r\n              b,\r\n              transpose_b ? columns_b : columns_a,\r\n              1.0f,\r\n              c,\r\n              rows_a);\r\n}\r\n\r\ninline void FastMatrixMatrixMultiply(\r\n      const double alpha,\r\n      const double a[],\r\n      const bool transpose_a,\r\n      const int rows_a,  // m\r\n      const int columns_a,  // k\r\n      const double b[],\r\n      const bool transpose_b,\r\n      const int columns_b,  // n\r\n      double c[]) {\r\n  cblas_dgemm(CblasColMajor,\r\n              transpose_a ? CblasTrans : CblasNoTrans,\r\n              transpose_b ? CblasTrans : CblasNoTrans,\r\n              rows_a,  // m\r\n              columns_b,  // n\r\n              columns_a,  // k\r\n              alpha,\r\n              a,\r\n              transpose_a ? columns_a : rows_a,\r\n              b,\r\n              transpose_b ? columns_b : columns_a,\r\n              1.0,\r\n              c,\r\n              rows_a);\r\n}\r\n\r\ninline Real *FastMalloc(const int size) {\r\n  Real *result = new Real[size];\r\n  assert(result != nullptr || size == 0);\r\n  return result;\r\n}\r\n\r\ninline void FastFree(Real *x) {\r\n  delete [] x;\r\n}\r\n", "meta": {"hexsha": "071ae714f20d6848b23998a5cceadfb2f26f5e35", "size": 13959, "ext": "h", "lang": "C", "max_stars_repo_path": "rwthlm/fast.h", "max_stars_repo_name": "darongliu/Input_Method", "max_stars_repo_head_hexsha": "28055937fc777cbba8cbc4c87ba5a2670da7d4e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-07-03T07:42:42.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-03T07:42:42.000Z", "max_issues_repo_path": "rwthlm/fast.h", "max_issues_repo_name": "darongliu/Input_Method", "max_issues_repo_head_hexsha": "28055937fc777cbba8cbc4c87ba5a2670da7d4e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rwthlm/fast.h", "max_forks_repo_name": "darongliu/Input_Method", "max_forks_repo_head_hexsha": "28055937fc777cbba8cbc4c87ba5a2670da7d4e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1584821429, "max_line_length": 76, "alphanum_fraction": 0.4335554123, "num_tokens": 2567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34158249943831703, "lm_q2_score": 0.039638839668221494, "lm_q1q2_score": 0.013539933928705807}}
{"text": "/****************************************************************\n *\n * Copyright (C) Max Planck Institute\n * for Biological Cybernetics, Tuebingen, Germany\n *\n * Author: Gabriele Lohmann, 2015\n *\n * This program is free software; you can redistribute it and/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 2\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.\n *\n *****************************************************************/\n\n/*\n** trial average using spline interpolation\n**\n** G.Lohmann, May 2014\n*/\n#include <viaio/Vlib.h>\n#include <viaio/VImage.h>\n#include <viaio/mu.h>\n#include <viaio/option.h>\n\n#include <gsl/gsl_cblas.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_spline.h>\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <math.h>\n\n#define ABS(x) ((x) > 0 ? (x) : -(x))\n#define SQR(x) ((x)*(x))\n\n#define LEN     10000   /* buffer length        */\n#define NTRIALS 10000   /* max number of trials */\n\ntypedef struct SpointStruct {\n  VShort x;\n  VShort y;\n  VShort z;\n} SPoint;\n\ntypedef struct TrialStruct {\n  int   id;\n  float onset;\n  float duration;\n  float height;\n} Trial;\n\n\n\nTrial trial[NTRIALS];\nint ntrials=0;\nint nevents=0;\n\nint test_ascii(int val)\n{\n  if (val >= 'a' && val <= 'z') return 1;\n  if (val >= 'A' && val <= 'Z') return 1;\n  if (val >= '0' && val <= '9') return 1;\n  if (val ==  ' ') return 1;\n  if (val == '\\0') return 1;\n  if (val == '\\n') return 1;\n  if (val == '\\r') return 1;\n  if (val == '\\t') return 1;\n  if (val == '\\v') return 1;\n  return 0;\n}\n\n\n\n/* parse design file */\nvoid ReadDesign(VString designfile)\n{\n  FILE *fp=NULL;\n  int  i,j,k,id;\n  char buf[LEN];\n  float onset=0,duration=0,height=0;\n\n  fp = fopen(designfile,\"r\");\n  if (!fp) VError(\" error opening design file %s\",designfile);\n\n  i = ntrials = nevents = 0;\n  while (!feof(fp)) {\n    for (j=0; j<LEN; j++) buf[j] = '\\0';\n    if (fgets(buf,LEN,fp) == NULL) break;\n    if (strlen(buf) < 2) continue;\n    if (buf[0] == '%' || buf[0] == '#') continue;\n    if (! test_ascii((int)buf[0])) VError(\" input file must be a text file\");\n\n    /* remove non-alphanumeric characters */\n    for (j=0; j<strlen(buf); j++) {\n      k = (int)buf[j];\n      if (!isgraph(k) && buf[j] != '\\n' && buf[j] != '\\r' && buf[j] != '\\0') {\n\tbuf[j] = ' ';\n      }\n      if (buf[j] == '\\v') buf[j] = ' '; /* remove tabs */\n      if (buf[j] == '\\t') buf[j] = ' ';\n    }\n\n    if (sscanf(buf,\"%d %f %f %f\",&id,&onset,&duration,&height) != 4)\n      VError(\" line %d: illegal input format\",i+1);\n\n    if (duration < 0.5 && duration >= -0.0001) duration = 0.5;\n    trial[i].id       = id;\n    trial[i].onset    = onset;\n    trial[i].duration = duration;\n    trial[i].height   = height;\n    i++;\n    if (i > NTRIALS) VError(\" too many trials %d\",i);\n\n    if (id > nevents) nevents = id;\n  }\n  fclose(fp);\n\n  ntrials = i;\n}\n\nint main (int argc,char *argv[])\n{\n  static VString  designfile = \"\";\n  static VShort   cond_id = 1;\n  static VShort   trial_id = 0;\n  static VDouble  temporal_resolution = 1.0;\n  static VDouble  start = 0;\n  static VDouble  length = 20;\n  static VOptionDescRec  options[] = {\n    {\"design\", VStringRepn, 1, & designfile, VRequiredOpt, NULL,\"Design file (ascii)\" },\n    {\"cond\", VShortRepn, 1, & cond_id, VOptionalOpt, NULL,\"Id of experimental condition\"},\n    {\"trial\", VShortRepn, 1, & trial_id, VOptionalOpt, NULL,\"Id of trial (starts at 0)\"},\n    {\"resolution\", VDoubleRepn, 1, & temporal_resolution, VOptionalOpt, NULL,\" output temporal resolution in secs\"},\n    {\"start\", VDoubleRepn, 1, & start, VOptionalOpt, NULL, \"start relative to beginning of trial in secs\"},\n    {\"length\", VDoubleRepn, 1, & length, VOptionalOpt, NULL, \"trial length in seconds\"},\n  };\n  FILE *in_file=NULL,*out_file=NULL;\n  VAttrList list=NULL;\n  VAttrListPosn posn;\n  int i,j,k,slice,row,col;\n  int nslices=0,nrows=0,ncols=0,ntimesteps=0;\n  double t=0;\n  char *prg = GetLipsiaName(\"vcuttrials\");\n  fprintf (stderr, \"%s\\n\", prg);\n\n\n  /*  parse command line */\n  VParseFilterCmd (VNumber (options),options,argc,argv,&in_file,&out_file);\n\n\n  /* get image dimensions, read functional data */\n  if (! (list = VReadFile (in_file, NULL))) exit (1);\n  fclose(in_file);\n\n  nslices = 0;\n  VImage tmp=NULL;\n  for (VFirstAttr (list, & posn); VAttrExists (& posn); VNextAttr (& posn)) {\n    if (VGetAttrRepn (& posn) != VImageRepn) continue;\n    VGetAttrValue (& posn, NULL,VImageRepn, & tmp);\n    /* if (VPixelRepn(tmp) != VShortRepn) continue; */\n    nslices++;\n  }\n  if (nslices < 1) VError(\" no slices\");\n\n\n  VAttrList geoinfo = VGetGeoInfo(list);\n  VImage *src = (VImage *) VCalloc(nslices,sizeof(VImage));\n  i = ntimesteps = nrows = ncols = 0;\n  for (VFirstAttr (list, & posn); VAttrExists (& posn); VNextAttr (& posn)) {\n    if (VGetAttrRepn (& posn) != VImageRepn) continue;\n    VGetAttrValue (& posn, NULL,VImageRepn, & src[i]);\n    /* if (VPixelRepn(src[i]) != VShortRepn) continue; */\n    if (VImageNBands(src[i]) > ntimesteps) ntimesteps = VImageNBands(src[i]);\n    if (VImageNRows(src[i])  > nrows)  nrows = VImageNRows(src[i]);\n    if (VImageNColumns(src[i]) > ncols) ncols = VImageNColumns(src[i]);\n    i++;\n  }\n  fprintf(stderr,\" nslices: %d, nrows: %d, ncols: %d,  ntimesteps: %d\\n\",nslices,nrows,ncols,ntimesteps);\n\n\n  /* read repetition time */\n  double tr = 0;\n  if (VGetAttr (VImageAttrList (src[0]), \"repetition_time\", NULL,\n\t\tVDoubleRepn, (VPointer) & tr) != VAttrFound) {\n    VError(\" attribute 'repetition_time' missing\");\n  }\n  tr /= 1000.0;\n  double experiment_duration = tr * (double)ntimesteps;\n\n\n  /* read design file */\n  ReadDesign(designfile);\n  \n\n  /* select trial id */\n  int tid=0,j0=-1;\n  for (j=0; j<ntrials; j++) {\n    if (trial[j].id == cond_id && tid == trial_id) {\n      j0 = j;\n      break;\n    }\n    if (trial[j].id == cond_id) tid++;\n  }\n  if (j0 < 0) VError(\"trial not found\");\n  fprintf(stderr,\" trial onset: %f\\n\",trial[j0].onset);\n\n\n\n  /* adjust start time */\n  trial[j0].onset += start;\n  if (trial[j0].onset < 0) {\n    VWarning(\" negative onset, reset to zero\");\n    trial[j0].onset = 0;\n  }\n  if (trial[j0].onset + length >= experiment_duration) {\n    VWarning(\" experiment_duration exceeded\",experiment_duration);\n    length = experiment_duration - trial[j0].onset-0.5;\n    VWarning(\" parameter '-length' set to %f\\n\",length);\n  }\n  \n  int nt = (int)(length/temporal_resolution + 0.5);\n  fprintf(stderr,\" number of output timesteps: %d\\n\",nt);  \n\n\n  /* ini output data structs  */\n  VImage *dest = (VImage *) VCalloc(nslices, sizeof(VImage));\n  VAttrList out_list = VCreateAttrList();  \n  if (geoinfo != NULL) VSetGeoInfo(geoinfo,out_list);\n  for (slice=0; slice<nslices; slice++) {\n    dest[slice] = VCreateImage(nt,nrows,ncols,VPixelRepn(src[slice]));\n    VFillImage(dest[slice],VAllBands,0);\n    VCopyImageAttrs (src[slice], dest[slice]);\n    VAppendAttr(out_list,\"image\",NULL,VImageRepn,dest[slice]);\n  }\n\n  \n  /* spline interpolation  */\n  double tstep = temporal_resolution;\n  double *xx = (double *) VCalloc(ntimesteps,sizeof(double));\n  double *yy = (double *) VCalloc(ntimesteps,sizeof(double));\n \n  gsl_interp_accel *acc = gsl_interp_accel_alloc ();\n  gsl_spline *spline = gsl_spline_alloc (gsl_interp_cspline, ntimesteps);\n\n\n  for (slice=0; slice<nslices; slice++) {\n    for (row=0; row<nrows; row++) {\n      for (col=0; col<ncols; col++) {\n\n\tfor (k=0; k<ntimesteps; k++) {\n\t  xx[k] = tr*((double)k);\n\t  yy[k] = (double)VGetPixel(src[slice],k,row,col);\n\t}\n\tgsl_spline_init (spline, xx, yy, ntimesteps);\n\n\tk=0;\n\tfor (t=0; t<length; t += tstep) {\n\t  if (k >= nt) break;\n\t  double xi = trial[j].onset + t;\n\t  double yi = 0;\n\t  if (xi < experiment_duration && xi >= 0) {\n\t    if (gsl_spline_eval_e (spline,xi,acc,&yi) == GSL_EDOM) continue;\n\t  }\n\t  VSetPixel(dest[slice],k,row,col,yi);\n\t  k++;\n\t}\n      }\n    } \n  }\n\n\n  /* write to disk */\n  if (! VWriteFile (out_file, out_list)) exit (1);\n  fprintf (stderr, \"%s: done.\\n\", argv[0]);\n  exit(0);\n}\n", "meta": {"hexsha": "289e6fb4a614fe56693e715083c58df5bc9d5409", "size": 8488, "ext": "c", "lang": "C", "max_stars_repo_path": "src/ted/vcuttrials/vcuttrials.c", "max_stars_repo_name": "zrajna/lipsia", "max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z", "max_issues_repo_path": "src/ted/vcuttrials/vcuttrials.c", "max_issues_repo_name": "zrajna/lipsia", "max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z", "max_forks_repo_path": "src/ted/vcuttrials/vcuttrials.c", "max_forks_repo_name": "zrajna/lipsia", "max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z", "avg_line_length": 29.3702422145, "max_line_length": 116, "alphanum_fraction": 0.6140433553, "num_tokens": 2678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681662740416, "lm_q2_score": 0.03410042473069495, "lm_q1q2_score": 0.01350609269225233}}
{"text": "#pragma once\n\n#include \"BoundingRegion.h\"\n#include \"Ellipsoid.h\"\n#include \"S2CellID.h\"\n\n#include <CesiumGeometry/CullingResult.h>\n#include <CesiumGeometry/Plane.h>\n\n#include <glm/vec3.hpp>\n#include <gsl/span>\n\n#include <array>\n#include <string_view>\n\nnamespace CesiumGeospatial {\n\n/**\n * A tile bounding volume specified as an S2 cell token with minimum and maximum\n * heights. The bounding volume is a k DOP. A k-DOP is the Boolean intersection\n * of extents along k directions.\n *\n * @param cellID The S2 cell ID.\n * @param minimumHeight The minimum height of the bounding volume.\n * @param maximumHeight The maximum height of the bounding volume.\n * @param ellipsoid The ellipsoid.\n */\nclass CESIUMGEOSPATIAL_API S2CellBoundingVolume final {\npublic:\n  S2CellBoundingVolume(\n      const S2CellID& cellID,\n      double minimumHeight,\n      double maximumHeight,\n      const Ellipsoid& ellipsoid = Ellipsoid::WGS84);\n\n  /**\n   * @brief Gets this bounding volume's cell ID.\n   */\n  const S2CellID& getCellID() const { return this->_cellID; }\n\n  /**\n   * @brief Gets the minimum height of the cell.\n   */\n  double getMinimumHeight() const noexcept { return this->_minimumHeight; }\n\n  /**\n   * @brief Gets the maximum height of the cell.\n   */\n  double getMaximumHeight() const noexcept { return this->_maximumHeight; }\n\n  /**\n   * @brief Gets the center of this bounding volume in ellipsoid-fixed (ECEF)\n   * coordinates.\n   */\n  glm::dvec3 getCenter() const noexcept;\n\n  /**\n   * @brief Gets the either corners of the bounding volume, in ellipsoid-fixed\n   * (ECEF) coordinates.\n   *\n   * @return An array of positions with a `size()` of 8.\n   */\n  gsl::span<const glm::dvec3> getVertices() const noexcept;\n\n  /**\n   * @brief Determines on which side of a plane the bounding volume is located.\n   *\n   * @param plane The plane to test against.\n   * @return The {@link CesiumGeometry::CullingResult}\n   *  * `Inside` if the entire region is on the side of the plane the normal is\n   * pointing.\n   *  * `Outside` if the entire region is on the opposite side.\n   *  * `Intersecting` if the region intersects the plane.\n   */\n  CesiumGeometry::CullingResult\n  intersectPlane(const CesiumGeometry::Plane& plane) const noexcept;\n\n  /**\n   * @brief Computes the distance squared from a given position to the closest\n   * point on this bounding volume. The position must be expressed in\n   * ellipsoid-centered (ECEF) coordinates.\n   *\n   * @param position The position\n   * @return The estimated distance squared from the bounding box to the point.\n   *\n   * @snippet TestOrientedBoundingBox.cpp distanceSquaredTo\n   */\n  double\n  computeDistanceSquaredToPosition(const glm::dvec3& position) const noexcept;\n\n  /**\n   * @brief Gets the six planes that bound the volume.\n   *\n   * @return An array of planes with a `size()` of 6.\n   */\n  gsl::span<const CesiumGeometry::Plane> getBoundingPlanes() const noexcept;\n\n  /**\n   * @brief Computes the bounding begion that best fits this S2 cell volume.\n   *\n   * @return The bounding region.\n   */\n  BoundingRegion computeBoundingRegion() const noexcept;\n\nprivate:\n  S2CellID _cellID;\n  double _minimumHeight;\n  double _maximumHeight;\n  glm::dvec3 _center;\n  std::array<CesiumGeometry::Plane, 6> _boundingPlanes;\n  std::array<glm::dvec3, 8> _vertices;\n};\n\n} // namespace CesiumGeospatial\n", "meta": {"hexsha": "e8978902c7d35d9a719ae43add22260cb78da303", "size": 3324, "ext": "h", "lang": "C", "max_stars_repo_path": "CesiumGeospatial/include/CesiumGeospatial/S2CellBoundingVolume.h", "max_stars_repo_name": "yieryi/cesium-native", "max_stars_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 154.0, "max_stars_repo_stars_event_min_datetime": "2021-03-30T14:08:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T00:01:43.000Z", "max_issues_repo_path": "CesiumGeospatial/include/CesiumGeospatial/S2CellBoundingVolume.h", "max_issues_repo_name": "yieryi/cesium-native", "max_issues_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 256.0, "max_issues_repo_issues_event_min_datetime": "2021-03-30T18:12:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:44:21.000Z", "max_forks_repo_path": "CesiumGeospatial/include/CesiumGeospatial/S2CellBoundingVolume.h", "max_forks_repo_name": "yieryi/cesium-native", "max_forks_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 66.0, "max_forks_repo_forks_event_min_datetime": "2021-03-30T15:14:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T13:38:41.000Z", "avg_line_length": 28.9043478261, "max_line_length": 80, "alphanum_fraction": 0.7072803851, "num_tokens": 847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.029760096742670907, "lm_q1q2_score": 0.013489116446699688}}
{"text": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n#pragma once\n\n#include \"Utils\\buffer.h\"\n#include \"MageSettings.h\"           // for CameraIdentity\n#include \"ORBDescriptor.h\"\n\n#include \"Memory\\allocators.h\"\n#include \"arcana\\utils\\serialization\\serializable.h\"\n\n#include <opencv2\\core\\core.hpp>\n#include <stdint.h>\n#include <atomic>\n\n#include <gsl\\span>\n\nnamespace mage\n{\n    using ImageAllocator = memory::std_allocator<void*, block_splitting_allocation_strategy>;\n\n    template<typename AllocT>\n    struct ImageData : mira::serializable<ImageData<AllocT>>\n    {\n        ImageData(CameraIdentity cameraIdentity, size_t maxFeatures, float pyramidScale, size_t numLevels, float imageBorder, const AllocT& allocator)\n            :   m_cameraIdentity{ cameraIdentity },\n                m_featureCount{ 0 },\n                m_pyramidScale { pyramidScale },\n                m_numLevels { numLevels },\n                m_imageBorder { imageBorder },\n                m_published{ false },\n                m_maxFeatures{ maxFeatures },\n                m_keypointBuffer{ maxFeatures, allocator },\n                m_descriptorBuffer{ maxFeatures, allocator }\n        {}\n\n        template<typename StreamT, typename = mira::is_stream_t<StreamT>>\n        ImageData(CameraIdentity cameraIdentity, size_t maxFeatures, float pyramidScale, size_t numLevels, float imageBorder, const AllocT& allocator, StreamT& stream)\n            : ImageData{ cameraIdentity, imageWidth, imageHeight, maxFeatures, pyramidScale, allocator }\n        {\n            deserialize(stream);\n        }\n\n        static constexpr auto members()\n        {\n            return declare_members(\n                &ImageData::m_cameraIdentity,\n                &ImageData::m_featureCount,\n                &ImageData::m_pyramidScale,\n                &ImageData::m_numLevels,\n                &ImageData::m_imageBorder,\n                &ImageData::m_published,\n                &ImageData::m_maxFeatures,\n                &ImageData::m_keypointBuffer,\n                &ImageData::m_descriptorBuffer\n            );\n        }\n\n        /*\n            Inserts the keypoints into the image data, and returns how many\n            items it copied. Because we only support a fixed size, we\n            only copy items if we have space.\n        */\n        size_t Insert(gsl::span<const cv::KeyPoint> keypoints)\n        {\n            auto toCopy = std::min<int>(gsl::narrow_cast<int>(keypoints.size()), gsl::narrow_cast<int>(m_maxFeatures - m_featureCount));\n            m_featureCount += m_keypointBuffer.copy(keypoints.data(), keypoints.data() + toCopy, m_featureCount);\n            return toCopy;\n        }\n\n        size_t Insert(const cv::KeyPoint& kp)\n        {\n            if (m_featureCount == m_maxFeatures)\n                return 0;\n\n            m_keypointBuffer[m_featureCount] = kp;\n            m_featureCount++;\n            return 1;\n        }\n\n        size_t Insert(const cv::KeyPoint* beg, const cv::KeyPoint* end)\n        {\n            auto toCopy = std::min<int>(gsl::narrow_cast<int>(end - beg), gsl::narrow_cast<int>(m_maxFeatures - m_featureCount));\n            m_featureCount += m_keypointBuffer.copy(beg, beg + toCopy, m_featureCount);\n            return toCopy;\n        }\n\n        size_t GetMaxFeatures() const\n        {\n            return m_maxFeatures;\n        }\n\n        size_t GetFeatureCount() const\n        {\n            return m_featureCount;\n        }\n\n        float GetPyramidScale() const\n        {\n            return m_pyramidScale;\n        }\n\n        size_t GetNumLevels() const\n        {\n            return m_numLevels;\n        }\n\n        float GetImageBorder() const\n        {\n            return m_imageBorder;\n        }\n\n        CameraIdentity GetCameraIdentity() const\n        {\n            return m_cameraIdentity;\n        }\n\n        const cv::KeyPoint& GetKeypoint(size_t idx) const\n        {\n            return const_cast<ImageData*>(this)->GetKeypoint(idx);\n        }\n\n        cv::KeyPoint& GetKeypoint(size_t idx)\n        {\n            assert(0 <= idx && idx < m_featureCount);\n            return m_keypointBuffer[idx];\n        }\n\n        gsl::span<const cv::KeyPoint> GetKeypoints() const\n        {\n            return { m_keypointBuffer.begin(), m_keypointBuffer.begin() + m_featureCount };\n        }\n\n        gsl::span<cv::KeyPoint> GetKeypoints()\n        {\n            return { m_keypointBuffer.begin(), m_keypointBuffer.begin() + m_featureCount };\n        }\n\n        const ORBDescriptor& GetDescriptor(size_t idx) const\n        {\n            return const_cast<ImageData*>(this)->GetDescriptor(idx);\n        }\n\n        ORBDescriptor& GetDescriptor(size_t idx)\n        {\n            assert(0 <= idx && idx < m_featureCount);\n            return m_descriptorBuffer[idx];\n        }\n\n        gsl::span<const ORBDescriptor> GetDescriptors() const\n        {\n            return const_cast<ImageData*>(this)->GetDescriptors();\n        }\n\n        gsl::span<ORBDescriptor> GetDescriptors()\n        {\n            return { m_descriptorBuffer.begin(), m_descriptorBuffer.begin() + m_featureCount };\n        }\n\n        void SetDescriptors(gsl::span<const ORBDescriptor> values)\n        {\n            assert(m_featureCount == values.size());\n            m_descriptorBuffer.copy(values.begin(), values.end());\n        }\n\n        void ZeroOutDescriptors()\n        {\n            m_descriptorBuffer.fill(0);\n        }\n\n        /*\n            Returns whether or not this image was ever published to the map\n        */\n        bool IsPublished() const\n        {\n            return m_published;\n        }\n\n        void MarkAsPublished() const\n        {\n            m_published = true;\n        }\n\n        template<typename DerivedT>\n        static size_t AllocationSizeInBytes(size_t maxFeatures)\n        {\n            return sizeof(DerivedT) + maxFeatures * sizeof(cv::KeyPoint) + maxFeatures * sizeof(ORBDescriptor);\n        }\n\n    private:\n        template<typename T>\n        using rebind_allocator = typename std::allocator_traits<AllocT>::template rebind_alloc<T>;\n\n        size_t m_featureCount{};\n        mutable std::atomic<bool> m_published{ false };\n\n        const size_t m_maxFeatures{};\n        const float m_pyramidScale{};\n        const size_t m_numLevels{}; //TODO: change numlevels to be reasonable with image resolution\n        const float m_imageBorder{};\n        const CameraIdentity m_cameraIdentity{};\n\n        buffer<cv::KeyPoint, rebind_allocator<cv::KeyPoint>> m_keypointBuffer{};\n        buffer<ORBDescriptor, rebind_allocator<ORBDescriptor>> m_descriptorBuffer{};\n    };\n}\n", "meta": {"hexsha": "6f171ba6c36d32f92a780cdfee56289fd2798045", "size": 6580, "ext": "h", "lang": "C", "max_stars_repo_path": "Core/MAGESLAM/Source/Image/ImageData.h", "max_stars_repo_name": "syntheticmagus/mageslam", "max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z", "max_issues_repo_path": "Core/MAGESLAM/Source/Image/ImageData.h", "max_issues_repo_name": "syntheticmagus/mageslam", "max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z", "max_forks_repo_path": "Core/MAGESLAM/Source/Image/ImageData.h", "max_forks_repo_name": "syntheticmagus/mageslam", "max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z", "avg_line_length": 31.6346153846, "max_line_length": 167, "alphanum_fraction": 0.5925531915, "num_tokens": 1389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632159254749036, "lm_q2_score": 0.03161876555767441, "lm_q1q2_score": 0.01347976248693349}}
{"text": "/* permutation/gsl_permutation.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2004 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_PERMUTATION_H__\n#define __GSL_PERMUTATION_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_check_range.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\nstruct gsl_permutation_struct\n{\n  size_t size;\n  size_t *data;\n};\n\ntypedef struct gsl_permutation_struct gsl_permutation;\n\nGSL_EXPORT gsl_permutation *gsl_permutation_alloc (const size_t n);\nGSL_EXPORT gsl_permutation *gsl_permutation_calloc (const size_t n);\nGSL_EXPORT void gsl_permutation_init (gsl_permutation * p);\nGSL_EXPORT void gsl_permutation_free (gsl_permutation * p);\nGSL_EXPORT int gsl_permutation_memcpy (gsl_permutation * dest, const gsl_permutation * src);\n\nGSL_EXPORT int gsl_permutation_fread (FILE * stream, gsl_permutation * p);\nGSL_EXPORT int gsl_permutation_fwrite (FILE * stream, const gsl_permutation * p);\nGSL_EXPORT int gsl_permutation_fscanf (FILE * stream, gsl_permutation * p);\nGSL_EXPORT int gsl_permutation_fprintf (FILE * stream, const gsl_permutation * p, const char *format);\n\nGSL_EXPORT size_t gsl_permutation_size (const gsl_permutation * p);\nGSL_EXPORT size_t * gsl_permutation_data (const gsl_permutation * p);\n\nGSL_EXPORT size_t gsl_permutation_get (const gsl_permutation * p, const size_t i);\nGSL_EXPORT int gsl_permutation_swap (gsl_permutation * p, const size_t i, const size_t j);\n\nGSL_EXPORT int gsl_permutation_valid (gsl_permutation * p);\nGSL_EXPORT void gsl_permutation_reverse (gsl_permutation * p);\nGSL_EXPORT int gsl_permutation_inverse (gsl_permutation * inv, const gsl_permutation * p);\nGSL_EXPORT int gsl_permutation_next (gsl_permutation * p);\nGSL_EXPORT int gsl_permutation_prev (gsl_permutation * p);\nGSL_EXPORT int gsl_permutation_mul (gsl_permutation * p, const gsl_permutation * pa, const gsl_permutation * pb);\n\nGSL_EXPORT int gsl_permutation_linear_to_canonical (gsl_permutation * q, const gsl_permutation * p);\nGSL_EXPORT int gsl_permutation_canonical_to_linear (gsl_permutation * p, const gsl_permutation * q);\n\nGSL_EXPORT size_t gsl_permutation_inversions (const gsl_permutation * p);\nGSL_EXPORT size_t gsl_permutation_linear_cycles (const gsl_permutation * p);\nGSL_EXPORT size_t gsl_permutation_canonical_cycles (const gsl_permutation * q);\n\n#ifdef HAVE_INLINE\n\nextern inline\nsize_t\ngsl_permutation_get (const gsl_permutation * p, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (i >= p->size)\n    {\n      GSL_ERROR_VAL (\"index out of range\", GSL_EINVAL, 0);\n    }\n#endif\n  return p->data[i];\n}\n\n#endif /* HAVE_INLINE */\n\n__END_DECLS\n\n#endif /* __GSL_PERMUTATION_H__ */\n", "meta": {"hexsha": "50227a3c882fc46fca294f0cbdb4aff72e47cb42", "size": 3544, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/gsl/include/gsl/gsl_permutation.h", "max_stars_repo_name": "dynaryu/vaws", "max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/gsl/include/gsl/gsl_permutation.h", "max_issues_repo_name": "dynaryu/vaws", "max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/gsl/include/gsl/gsl_permutation.h", "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.797979798, "max_line_length": 113, "alphanum_fraction": 0.7847065463, "num_tokens": 926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.310694383214554, "lm_q2_score": 0.04336580200934005, "lm_q1q2_score": 0.013473511107896375}}
{"text": "#include <stdio.h>\n#include <string.h>\n#include <gsl/gsl_statistics_double.h>\n#include \"tz_error.h\"\n#include \"tz_constant.h\"\n#include \"tz_image_lib.h\"\n#include \"tz_objdetect.h\"\n#include \"tz_imatrix.h\"\n#include \"tz_stack_math.h\"\n#include \"tz_stack_bwdist.h\"\n#include \"tz_stack_bwmorph.h\"\n#include \"tz_voxel_linked_list.h\"\n#include \"tz_stack_sampling.h\"\n#include \"tz_stack_draw.h\"\n#include \"tz_voxel_graphics.h\"\n\nINIT_EXCEPTION_MAIN(e)\n\nint main(int argc, char* argv[]) \n{\n  char neuron_name[100];\n  if (argc == 1) {\n    strcpy(neuron_name, \"fly_neuron\");\n  } else {\n    strcpy(neuron_name, argv[1]);\n  }\n\n  char file_path[100];\n\n  sprintf(file_path, \"../data/%s.tif\", neuron_name);\n  Stack *canvas = Read_Stack(file_path);\n  \n  Translate_Stack(canvas, COLOR, 1);\n  Print_Stack_Info(canvas);\n\n  sprintf(file_path, \"../data/%s/grow_bundle.tif\", neuron_name);\n  Stack *bundle = Read_Stack(file_path);\n  Stack *bundle_boundary = Stack_Perimeter(bundle, NULL, 4);\n  Kill_Stack(bundle);\n\n  sprintf(file_path, \"../data/%s/bundle_seed.tif\", neuron_name);\n  Stack *seed = Read_Stack(file_path);\n\n  Rgb_Color color;\n  Set_Color(&color, 0, 255, 0);\n  Stack_Label_Bwc(canvas, bundle_boundary, color);\n  Set_Color(&color, 255, 0, 0);\n  Stack_Label_Bwc(canvas, seed, color);\n\n  sprintf(file_path, \"../data/%s/bundle_label.tif\", neuron_name);\n  Write_Stack(file_path, canvas);\n\n  Kill_Stack(canvas);\n  Kill_Stack(bundle_boundary);\n  Kill_Stack(seed);\n\n  return 0;\n}\n", "meta": {"hexsha": "c2612307588d451a49b2cca5d6c834bc41926c95", "size": 1450, "ext": "c", "lang": "C", "max_stars_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/fly_neuron_bundle_label.c", "max_stars_repo_name": "zzhmark/vaa3d_tools", "max_stars_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-27T19:14:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-27T19:14:03.000Z", "max_issues_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/fly_neuron_bundle_label.c", "max_issues_repo_name": "zzhmark/vaa3d_tools", "max_issues_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-12-03T05:33:13.000Z", "max_issues_repo_issues_event_max_datetime": "2016-12-03T05:33:13.000Z", "max_forks_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/fly_neuron_bundle_label.c", "max_forks_repo_name": "zzhmark/vaa3d_tools", "max_forks_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5762711864, "max_line_length": 65, "alphanum_fraction": 0.7165517241, "num_tokens": 407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552952031526044, "lm_q2_score": 0.030214586630765136, "lm_q1q2_score": 0.013461490288128672}}
{"text": "/**\n * @file binauralprocessing.h\n * @brief Binaural processing\n * @author Kenichi Kumatani\n */\n#ifndef BINAURALPROCESSING_H\n#define BINAURALPROCESSING_H\n\n#include <stdio.h>\n#include <assert.h>\n#include <float.h>\n\n#include <gsl/gsl_block.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_complex.h>\n#include <gsl/gsl_complex_math.h>\n#include <gsl/gsl_fft_complex.h>\n#include <common/refcount.h>\n#include \"common/jexception.h\"\n\n#include \"stream/stream.h\"\n#include \"postfilter/spectralsubtraction.h\"\n#include \"beamformer/spectralinfoarray.h\"\n#include \"beamformer/beamformer.h\"\n\nclass BinaryMaskFilter : public VectorComplexFeatureStream {\npublic:\n  BinaryMaskFilter( unsigned chanX, VectorComplexFeatureStreamPtr &srcL, VectorComplexFeatureStreamPtr &srcR,\n\t\t       unsigned M, float threshold, float alpha,\n\t\t       float dEta = 0.01, const String& nm = \"BinaryMaskFilter\" );\n  ~BinaryMaskFilter();\n  virtual const gsl_vector_complex* next(int frame_no = -5);\n  virtual void reset();\n  void set_threshold( float threshold ){ threshold_ = threshold; }\n  void set_thresholds( const gsl_vector *thresholds );\n  double threshold(){ return threshold_; }\n  gsl_vector *thresholds(){ return threshold_per_freq_; }\n\n#ifdef ENABLE_LEGACY_BTK_API\n  void setThreshold( float threshold ){ set_threshold(threshold); }\n  void setThresholds( const gsl_vector *thresholds ){ set_thresholds(thresholds); }\n  double getThreshold(){ return threshold(); }\n  gsl_vector *getThresholds(){ return thresholds(); }\n#endif\n\nprotected:\n  VectorComplexFeatureStreamPtr srcL_; /* left channel */\n  VectorComplexFeatureStreamPtr srcR_; /* right channel */\n  unsigned          chanX_;  /* want to extract the index of a channel */\n  gsl_vector_float *prevMu_; /* binary mask at a previous frame */\n  float             alpha_;  /* forgetting factor */\n  float             dEta_;        /* flooring value */\n  float             threshold_;   /* threshold for the ITD */\n  gsl_vector        *threshold_per_freq_;\n};\n\ntypedef Inherit<BinaryMaskFilter, VectorComplexFeatureStreamPtr> BinaryMaskFilterPtr;\n\n/**\n   @class Implementation of binary masking based on C. Kim's Interspeech2010 paper \n   @brief binary mask two inputs based of the threshold of the interaural time delay (ITD)\n   @usage\n */\nclass KimBinaryMaskFilter : public BinaryMaskFilter {\npublic:\n  KimBinaryMaskFilter( unsigned chanX, VectorComplexFeatureStreamPtr &srcL, VectorComplexFeatureStreamPtr &srcR,\n\t\t       unsigned M, float threshold, float alpha,\n\t\t       float dEta = 0.01, float dPowerCoeff = 1/15.0, const String& nm = \"KimBinaryMaskFilter\" );\n  ~KimBinaryMaskFilter();\n  virtual const gsl_vector_complex* next(int frame_no = -5);\n  virtual void reset();\n\n  virtual const gsl_vector_complex* masking1( const gsl_vector_complex* ad_X_L, const gsl_vector_complex* ad_X_R, float threshold );\n\nprotected:\n  float             dpower_coeff_; /* power law non-linearity */\n};\n\ntypedef Inherit<KimBinaryMaskFilter, BinaryMaskFilterPtr> KimBinaryMaskFilterPtr;\n\n/**\n   @class Implementation of estimating the threshold for C. Kim's ITD-based binary masking\n   @brief binary mask two inputs based of the threshold of the interaural time delay (ITD)\n   @usage\n */\nclass KimITDThresholdEstimator : public KimBinaryMaskFilter {\npublic:\n  KimITDThresholdEstimator( VectorComplexFeatureStreamPtr &srcL, VectorComplexFeatureStreamPtr &srcR, unsigned M, float minThreshold = 0, float maxThreshold = 0, float width = 0.02, float minFreq= -1, float maxFreq=-1, int sampleRate=-1, float dEta = 0.01, float dPowerCoeff = 1/15.0, const String& nm = \"KimITDThresholdEstimator\" );\n  ~KimITDThresholdEstimator();\n  virtual const gsl_vector_complex* next(int frame_no = -5);\n  virtual void   reset();\n  virtual double calc_threshold();\n  const gsl_vector* cost_function();\n\n#ifdef ENABLE_LEGACY_BTK_API\n  virtual double calcThreshold(){ return calc_threshold(); }\n  const gsl_vector* getCostFunction(){ return cost_function(); }\n#endif\n\nprotected:\n  virtual void accumStats1( const gsl_vector_complex* ad_X_L, const gsl_vector_complex* ad_X_R );\n\n  /* for restricting the search space */\n  float min_threshold_;\n  float max_threshold_;\n  float width_;\n  unsigned min_fbinX_;\n  unsigned max_fbinX_;\n  /* work space */\n  double *cost_func_values_;\n  double *sigma_T_;\n  double *sigma_I_;\n  double *mean_T_;\n  double *mean_I_;\n  unsigned int nCand_;\n  unsigned int nSamples_;\n  gsl_vector *buffer_; /* for returning values from the python */\n  bool cost_func_computed_;\n};\n\ntypedef Inherit<KimITDThresholdEstimator, KimBinaryMaskFilterPtr> KimITDThresholdEstimatorPtr;\n\n/**\n\t@class\n */\nclass IIDBinaryMaskFilter : public BinaryMaskFilter {\npublic:\n\tIIDBinaryMaskFilter( unsigned chanX, VectorComplexFeatureStreamPtr &srcL, VectorComplexFeatureStreamPtr &srcR,\n\t\t\t\t\t\tunsigned M, float threshold, float alpha,\n\t\t\t\t\t\tfloat dEta = 0.01, const String& nm = \"IIDBinaryMaskFilter\" );\n\t~IIDBinaryMaskFilter();\n\tvirtual const gsl_vector_complex* next(int frame_no = -5);\n\tvirtual void reset();\n\t\n\tvirtual const gsl_vector_complex* masking1( const gsl_vector_complex* ad_X_L, const gsl_vector_complex* ad_X_R, float threshold );\n};\n\ntypedef Inherit<IIDBinaryMaskFilter, BinaryMaskFilterPtr> IIDBinaryMaskFilterPtr;\n\n/**\n @class binary masking based on a difference between magnitudes of two beamformers' outputs.\n @brief set zero to beamformer's output with the smaller magnitude over frequency bins\n */\nclass IIDThresholdEstimator : public KimITDThresholdEstimator {\npublic:\n\tIIDThresholdEstimator( VectorComplexFeatureStreamPtr &srcL, VectorComplexFeatureStreamPtr &srcR, unsigned M, \n\t\t\t\t\t\t\t float minThreshold = 0, float maxThreshold = 0, float width = 0.02,\n\t\t\t\t\t\t\t float minFreq= -1, float maxFreq=-1, int sampleRate=-1, float dEta = 0.01, float dPowerCoeff = 0.5, const String& nm = \"IIDThresholdEstimator\" );\n\t~IIDThresholdEstimator();\n\tvirtual const gsl_vector_complex* next(int frame_no = -5);\n\tvirtual void reset();\n\tvirtual double calc_threshold();\n\n#ifdef ENABLE_LEGACY_BTK_API\n\tvirtual double calcThreshold(){ return calc_threshold(); }\n#endif\n\nprotected:\n        virtual void accumStats1( const gsl_vector_complex* ad_X_L, const gsl_vector_complex* ad_X_R );\n\nprivate:\n        double *_Y4_T;\n        double *_Y4_I;\n        double _beta;\n};\n\ntypedef Inherit<IIDThresholdEstimator, KimITDThresholdEstimatorPtr> IIDThresholdEstimatorPtr;\n\n/**\n @class binary masking based on a difference between magnitudes of two beamformers' outputs at each frequency bin.\n @brief set zero to beamformer's output with the smaller magnitude at each frequency bin\n */\nclass FDIIDThresholdEstimator : public BinaryMaskFilter {\npublic:\n  FDIIDThresholdEstimator( VectorComplexFeatureStreamPtr &srcL, VectorComplexFeatureStreamPtr &srcR, unsigned M,\n\t\t\t   float minThreshold = 0, float maxThreshold = 0, float width = 1000,\n\t\t\t   float dEta = 0.01, float dPowerCoeff = 1/15.0, const String& nm = \"FDIIDThresholdEstimator\" );\n  ~FDIIDThresholdEstimator();\n  virtual const gsl_vector_complex* next(int frame_no = -5);\n  virtual void   reset();\n  virtual double calc_threshold();\n  const gsl_vector* cost_function(unsigned freqX);\n\n#ifdef ENABLE_LEGACY_BTK_API\n  virtual double calcThreshold(){ return calc_threshold(); }\n  const gsl_vector* getCostFunction( unsigned freqX ){ return cost_function(freqX); }\n#endif\n\nprotected:\n  virtual void accumStats1( const gsl_vector_complex* ad_X_L, const gsl_vector_complex* ad_X_R );\n\n  /* for restricting the search space */\n  float min_threshold_;\n  float max_threshold_;\n  float width_;\n  float dpower_coeff_;\n\n  /* work space */\n  double **cost_func_values_;\n  double **_Y4;\n  double **_sigma;\n  double **_mean;\n  double _beta;\n  unsigned int nCand_;\n  unsigned int nSamples_;\n  gsl_vector *buffer_; /* for returning values from the python */\n  bool cost_func_computed_;\n};\n\ntypedef Inherit<FDIIDThresholdEstimator, BinaryMaskFilterPtr> FDIIDThresholdEstimatorPtr;\n\n#endif\n", "meta": {"hexsha": "ae6150d6f364d86d2c95ef7f31ad0f1bbb7eb1fe", "size": 7939, "ext": "h", "lang": "C", "max_stars_repo_path": "btk20_src/postfilter/binauralprocessing.h", "max_stars_repo_name": "musiclvme/distant_speech_recognition", "max_stars_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 136.0, "max_stars_repo_stars_event_min_datetime": "2018-12-06T06:35:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T15:07:42.000Z", "max_issues_repo_path": "btk20_src/postfilter/binauralprocessing.h", "max_issues_repo_name": "musiclvme/distant_speech_recognition", "max_issues_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2018-12-03T04:33:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-28T22:01:37.000Z", "max_forks_repo_path": "btk20_src/postfilter/binauralprocessing.h", "max_forks_repo_name": "musiclvme/distant_speech_recognition", "max_forks_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 68.0, "max_forks_repo_forks_event_min_datetime": "2019-01-08T06:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-17T09:33:10.000Z", "avg_line_length": 37.0981308411, "max_line_length": 333, "alphanum_fraction": 0.7560146114, "num_tokens": 1950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.028007522228611345, "lm_q1q2_score": 0.013457017255800549}}
{"text": "/* matrix/gsl_matrix_int.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_MATRIX_INT_H__\n#define __GSL_MATRIX_INT_H__\n\n#if !defined( GSL_FUN )\n#  if !defined( GSL_DLL )\n#    define GSL_FUN extern\n#  elif defined( BUILD_GSL_DLL )\n#    define GSL_FUN extern __declspec(dllexport)\n#  else\n#    define GSL_FUN extern __declspec(dllimport)\n#  endif\n#endif\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_inline.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_vector_int.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size1;\n  size_t size2;\n  size_t tda;\n  int * data;\n  gsl_block_int * block;\n  int owner;\n} gsl_matrix_int;\n\ntypedef struct\n{\n  gsl_matrix_int matrix;\n} _gsl_matrix_int_view;\n\ntypedef _gsl_matrix_int_view gsl_matrix_int_view;\n\ntypedef struct\n{\n  gsl_matrix_int matrix;\n} _gsl_matrix_int_const_view;\n\ntypedef const _gsl_matrix_int_const_view gsl_matrix_int_const_view;\n\n/* Allocation */\n\nGSL_FUN gsl_matrix_int * \ngsl_matrix_int_alloc (const size_t n1, const size_t n2);\n\nGSL_FUN gsl_matrix_int * \ngsl_matrix_int_calloc (const size_t n1, const size_t n2);\n\nGSL_FUN gsl_matrix_int * \ngsl_matrix_int_alloc_from_block (gsl_block_int * b, \n                                   const size_t offset, \n                                   const size_t n1, \n                                   const size_t n2, \n                                   const size_t d2);\n\nGSL_FUN gsl_matrix_int * \ngsl_matrix_int_alloc_from_matrix (gsl_matrix_int * m,\n                                    const size_t k1, \n                                    const size_t k2,\n                                    const size_t n1, \n                                    const size_t n2);\n\nGSL_FUN gsl_vector_int * \ngsl_vector_int_alloc_row_from_matrix (gsl_matrix_int * m,\n                                        const size_t i);\n\nGSL_FUN gsl_vector_int * \ngsl_vector_int_alloc_col_from_matrix (gsl_matrix_int * m,\n                                        const size_t j);\n\nGSL_FUN void gsl_matrix_int_free (gsl_matrix_int * m);\n\n/* Views */\n\nGSL_FUN _gsl_matrix_int_view \ngsl_matrix_int_submatrix (gsl_matrix_int * m, \n                            const size_t i, const size_t j, \n                            const size_t n1, const size_t n2);\n\nGSL_FUN _gsl_vector_int_view \ngsl_matrix_int_row (gsl_matrix_int * m, const size_t i);\n\nGSL_FUN _gsl_vector_int_view \ngsl_matrix_int_column (gsl_matrix_int * m, const size_t j);\n\nGSL_FUN _gsl_vector_int_view \ngsl_matrix_int_diagonal (gsl_matrix_int * m);\n\nGSL_FUN _gsl_vector_int_view \ngsl_matrix_int_subdiagonal (gsl_matrix_int * m, const size_t k);\n\nGSL_FUN _gsl_vector_int_view \ngsl_matrix_int_superdiagonal (gsl_matrix_int * m, const size_t k);\n\nGSL_FUN _gsl_vector_int_view\ngsl_matrix_int_subrow (gsl_matrix_int * m, const size_t i,\n                         const size_t offset, const size_t n);\n\nGSL_FUN _gsl_vector_int_view\ngsl_matrix_int_subcolumn (gsl_matrix_int * m, const size_t j,\n                            const size_t offset, const size_t n);\n\nGSL_FUN _gsl_matrix_int_view\ngsl_matrix_int_view_array (int * base,\n                             const size_t n1, \n                             const size_t n2);\n\nGSL_FUN _gsl_matrix_int_view\ngsl_matrix_int_view_array_with_tda (int * base, \n                                      const size_t n1, \n                                      const size_t n2,\n                                      const size_t tda);\n\n\nGSL_FUN _gsl_matrix_int_view\ngsl_matrix_int_view_vector (gsl_vector_int * v,\n                              const size_t n1, \n                              const size_t n2);\n\nGSL_FUN _gsl_matrix_int_view\ngsl_matrix_int_view_vector_with_tda (gsl_vector_int * v,\n                                       const size_t n1, \n                                       const size_t n2,\n                                       const size_t tda);\n\n\nGSL_FUN _gsl_matrix_int_const_view \ngsl_matrix_int_const_submatrix (const gsl_matrix_int * m, \n                                  const size_t i, const size_t j, \n                                  const size_t n1, const size_t n2);\n\nGSL_FUN _gsl_vector_int_const_view \ngsl_matrix_int_const_row (const gsl_matrix_int * m, \n                            const size_t i);\n\nGSL_FUN _gsl_vector_int_const_view \ngsl_matrix_int_const_column (const gsl_matrix_int * m, \n                               const size_t j);\n\nGSL_FUN _gsl_vector_int_const_view\ngsl_matrix_int_const_diagonal (const gsl_matrix_int * m);\n\nGSL_FUN _gsl_vector_int_const_view \ngsl_matrix_int_const_subdiagonal (const gsl_matrix_int * m, \n                                    const size_t k);\n\nGSL_FUN _gsl_vector_int_const_view \ngsl_matrix_int_const_superdiagonal (const gsl_matrix_int * m, \n                                      const size_t k);\n\nGSL_FUN _gsl_vector_int_const_view\ngsl_matrix_int_const_subrow (const gsl_matrix_int * m, const size_t i,\n                               const size_t offset, const size_t n);\n\nGSL_FUN _gsl_vector_int_const_view\ngsl_matrix_int_const_subcolumn (const gsl_matrix_int * m, const size_t j,\n                                  const size_t offset, const size_t n);\n\nGSL_FUN _gsl_matrix_int_const_view\ngsl_matrix_int_const_view_array (const int * base,\n                                   const size_t n1, \n                                   const size_t n2);\n\nGSL_FUN _gsl_matrix_int_const_view\ngsl_matrix_int_const_view_array_with_tda (const int * base, \n                                            const size_t n1, \n                                            const size_t n2,\n                                            const size_t tda);\n\nGSL_FUN _gsl_matrix_int_const_view\ngsl_matrix_int_const_view_vector (const gsl_vector_int * v,\n                                    const size_t n1, \n                                    const size_t n2);\n\nGSL_FUN _gsl_matrix_int_const_view\ngsl_matrix_int_const_view_vector_with_tda (const gsl_vector_int * v,\n                                             const size_t n1, \n                                             const size_t n2,\n                                             const size_t tda);\n\n/* Operations */\n\nGSL_FUN void gsl_matrix_int_set_zero (gsl_matrix_int * m);\nGSL_FUN void gsl_matrix_int_set_identity (gsl_matrix_int * m);\nGSL_FUN void gsl_matrix_int_set_all (gsl_matrix_int * m, int x);\n\nGSL_FUN int gsl_matrix_int_fread (FILE * stream, gsl_matrix_int * m) ;\nGSL_FUN int gsl_matrix_int_fwrite (FILE * stream, const gsl_matrix_int * m) ;\nGSL_FUN int gsl_matrix_int_fscanf (FILE * stream, gsl_matrix_int * m);\nGSL_FUN int gsl_matrix_int_fprintf (FILE * stream, const gsl_matrix_int * m, const char * format);\n \nGSL_FUN int gsl_matrix_int_memcpy(gsl_matrix_int * dest, const gsl_matrix_int * src);\nGSL_FUN int gsl_matrix_int_swap(gsl_matrix_int * m1, gsl_matrix_int * m2);\n\nGSL_FUN int gsl_matrix_int_swap_rows(gsl_matrix_int * m, const size_t i, const size_t j);\nGSL_FUN int gsl_matrix_int_swap_columns(gsl_matrix_int * m, const size_t i, const size_t j);\nGSL_FUN int gsl_matrix_int_swap_rowcol(gsl_matrix_int * m, const size_t i, const size_t j);\nGSL_FUN int gsl_matrix_int_transpose (gsl_matrix_int * m);\nGSL_FUN int gsl_matrix_int_transpose_memcpy (gsl_matrix_int * dest, const gsl_matrix_int * src);\n\nGSL_FUN int gsl_matrix_int_max (const gsl_matrix_int * m);\nGSL_FUN int gsl_matrix_int_min (const gsl_matrix_int * m);\nGSL_FUN void gsl_matrix_int_minmax (const gsl_matrix_int * m, int * min_out, int * max_out);\n\nGSL_FUN void gsl_matrix_int_max_index (const gsl_matrix_int * m, size_t * imax, size_t *jmax);\nGSL_FUN void gsl_matrix_int_min_index (const gsl_matrix_int * m, size_t * imin, size_t *jmin);\nGSL_FUN void gsl_matrix_int_minmax_index (const gsl_matrix_int * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);\n\nGSL_FUN int gsl_matrix_int_equal (const gsl_matrix_int * a, const gsl_matrix_int * b);\n\nGSL_FUN int gsl_matrix_int_isnull (const gsl_matrix_int * m);\nGSL_FUN int gsl_matrix_int_ispos (const gsl_matrix_int * m);\nGSL_FUN int gsl_matrix_int_isneg (const gsl_matrix_int * m);\nGSL_FUN int gsl_matrix_int_isnonneg (const gsl_matrix_int * m);\n\nGSL_FUN int gsl_matrix_int_add (gsl_matrix_int * a, const gsl_matrix_int * b);\nGSL_FUN int gsl_matrix_int_sub (gsl_matrix_int * a, const gsl_matrix_int * b);\nGSL_FUN int gsl_matrix_int_mul_elements (gsl_matrix_int * a, const gsl_matrix_int * b);\nGSL_FUN int gsl_matrix_int_div_elements (gsl_matrix_int * a, const gsl_matrix_int * b);\nGSL_FUN int gsl_matrix_int_scale (gsl_matrix_int * a, const double x);\nGSL_FUN int gsl_matrix_int_add_constant (gsl_matrix_int * a, const double x);\nGSL_FUN int gsl_matrix_int_add_diagonal (gsl_matrix_int * a, const double x);\n\n/***********************************************************************/\n/* The functions below are obsolete                                    */\n/***********************************************************************/\nGSL_FUN int gsl_matrix_int_get_row(gsl_vector_int * v, const gsl_matrix_int * m, const size_t i);\nGSL_FUN int gsl_matrix_int_get_col(gsl_vector_int * v, const gsl_matrix_int * m, const size_t j);\nGSL_FUN int gsl_matrix_int_set_row(gsl_matrix_int * m, const size_t i, const gsl_vector_int * v);\nGSL_FUN int gsl_matrix_int_set_col(gsl_matrix_int * m, const size_t j, const gsl_vector_int * v);\n/***********************************************************************/\n\n/* inline functions if you are using GCC */\n\nGSL_FUN INLINE_DECL int   gsl_matrix_int_get(const gsl_matrix_int * m, const size_t i, const size_t j);\nGSL_FUN INLINE_DECL void    gsl_matrix_int_set(gsl_matrix_int * m, const size_t i, const size_t j, const int x);\nGSL_FUN INLINE_DECL int * gsl_matrix_int_ptr(gsl_matrix_int * m, const size_t i, const size_t j);\nGSL_FUN INLINE_DECL const int * gsl_matrix_int_const_ptr(const gsl_matrix_int * m, const size_t i, const size_t j);\n\n#ifdef HAVE_INLINE\nINLINE_FUN \nint\ngsl_matrix_int_get(const gsl_matrix_int * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_VAL(\"first index out of range\", GSL_EINVAL, 0) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_VAL(\"second index out of range\", GSL_EINVAL, 0) ;\n        }\n    }\n#endif\n  return m->data[i * m->tda + j] ;\n} \n\nINLINE_FUN \nvoid\ngsl_matrix_int_set(gsl_matrix_int * m, const size_t i, const size_t j, const int x)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_VOID(\"first index out of range\", GSL_EINVAL) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_VOID(\"second index out of range\", GSL_EINVAL) ;\n        }\n    }\n#endif\n  m->data[i * m->tda + j] = x ;\n}\n\nINLINE_FUN \nint *\ngsl_matrix_int_ptr(gsl_matrix_int * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n        }\n    }\n#endif\n  return (int *) (m->data + (i * m->tda + j)) ;\n} \n\nINLINE_FUN \nconst int *\ngsl_matrix_int_const_ptr(const gsl_matrix_int * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n        }\n    }\n#endif\n  return (const int *) (m->data + (i * m->tda + j)) ;\n} \n\n#endif\n\n__END_DECLS\n\n#endif /* __GSL_MATRIX_INT_H__ */\n", "meta": {"hexsha": "a67df8b2db9b0bede764f0c864e911b5f4b18b8d", "size": 12646, "ext": "h", "lang": "C", "max_stars_repo_path": "mbsysCopy/win64_include_lib/include/gsl/gsl_matrix_int.h", "max_stars_repo_name": "mharding01/augmented-neuromuscular-RT-running", "max_stars_repo_head_hexsha": "7e1ef00d3fdf9cfa9d59fc4f3a6a0e6dd792a834", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mbsysCopy/win64_include_lib/include/gsl/gsl_matrix_int.h", "max_issues_repo_name": "mharding01/augmented-neuromuscular-RT-running", "max_issues_repo_head_hexsha": "7e1ef00d3fdf9cfa9d59fc4f3a6a0e6dd792a834", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mbsysCopy/win64_include_lib/include/gsl/gsl_matrix_int.h", "max_forks_repo_name": "mharding01/augmented-neuromuscular-RT-running", "max_forks_repo_head_hexsha": "7e1ef00d3fdf9cfa9d59fc4f3a6a0e6dd792a834", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0304709141, "max_line_length": 128, "alphanum_fraction": 0.6531709632, "num_tokens": 3196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.02887090370841958, "lm_q1q2_score": 0.01342212850101405}}
{"text": "#ifndef __GSL_PERMUTE_VECTOR_H__\n#define __GSL_PERMUTE_VECTOR_H__\n\n#include <gsl/gsl_permute_vector_complex_long_double.h>\n#include <gsl/gsl_permute_vector_complex_double.h>\n#include <gsl/gsl_permute_vector_complex_float.h>\n\n#include <gsl/gsl_permute_vector_long_double.h>\n#include <gsl/gsl_permute_vector_double.h>\n#include <gsl/gsl_permute_vector_float.h>\n\n#include <gsl/gsl_permute_vector_ulong.h>\n#include <gsl/gsl_permute_vector_long.h>\n\n#include <gsl/gsl_permute_vector_uint.h>\n#include <gsl/gsl_permute_vector_int.h>\n\n#include <gsl/gsl_permute_vector_ushort.h>\n#include <gsl/gsl_permute_vector_short.h>\n\n#include <gsl/gsl_permute_vector_uchar.h>\n#include <gsl/gsl_permute_vector_char.h>\n\n#endif /* __GSL_PERMUTE_VECTOR_H__ */\n", "meta": {"hexsha": "76265078630b7d116e29db2f73dca446f3220818", "size": 733, "ext": "h", "lang": "C", "max_stars_repo_path": "gsl-2.6/gsl/gsl_permute_vector.h", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gsl-2.6/gsl/gsl_permute_vector.h", "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gsl-2.6/gsl/gsl_permute_vector.h", "max_forks_repo_name": "ielomariala/Hex-Game", "max_forks_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-30T20:40:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-30T20:40:25.000Z", "avg_line_length": 29.32, "max_line_length": 55, "alphanum_fraction": 0.8362892224, "num_tokens": 207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38121956625614994, "lm_q2_score": 0.03514484715873382, "lm_q1q2_score": 0.01339790338999119}}
{"text": "/*****************************************************************************\nCopyright (c) 2011-2014, The OpenBLAS Project\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n   1. Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n\n   2. Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and/or other materials provided with the\n      distribution.\n   3. Neither the name of the OpenBLAS project nor the names of \n      its contributors may be used to endorse or promote products \n      derived from this software without specific prior written \n      permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE\nUSE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n**********************************************************************************/\n\n#include \"openblas_utest.h\"\n#include <sys/types.h>\n#include <sys/wait.h>\n#include <cblas.h>\n\nvoid* xmalloc(size_t n)\n{\n    void* tmp;\n    tmp = malloc(n);\n    if (tmp == NULL) {\n        fprintf(stderr, \"You are about to die\\n\");\n        exit(1);\n    } else {\n        return tmp;\n    }\n}\n\nvoid check_dgemm(double *a, double *b, double *result, double *expected, int n)\n{\n    int i;\n    cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, n, n, n,\n        1.0, a, n, b, n, 0.0, result, n);\n    for(i = 0; i < n * n; ++i) {\n        ASSERT_DBL_NEAR_TOL(expected[i], result[i], DOUBLE_EPS);\n    }\n}\n\nCTEST(fork, safety)\n{\n    int n = 1000;\n    int i;\n\n    double *a, *b, *c, *d;\n    size_t n_bytes;\n\n    pid_t fork_pid;\n    pid_t fork_pid_nested;\n\n    n_bytes = sizeof(*a) * n * n;\n\n    a = xmalloc(n_bytes);\n    b = xmalloc(n_bytes);\n    c = xmalloc(n_bytes);\n    d = xmalloc(n_bytes);\n\n    // Put ones in a and b\n    for(i = 0; i < n * n; ++i) {\n        a[i] = 1;\n        b[i] = 1;\n    }\n\n    // Compute a DGEMM product in the parent process prior to forking to\n    // ensure that the OpenBLAS thread pool is initialized.\n    cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, n, n, n,\n       1.0, a, n, b, n, 0.0, c, n);\n\n    fork_pid = fork();\n    if (fork_pid == -1) {\n        CTEST_ERR(\"Failed to fork process.\");\n    } else if (fork_pid == 0) {\n        // Compute a DGEMM product in the child process to check that the\n        // thread pool as been properly been reinitialized after the fork.\n        check_dgemm(a, b, d, c, n);\n\n        // Nested fork to check that the pthread_atfork protection can work\n        // recursively\n        fork_pid_nested = fork();\n        if (fork_pid_nested == -1) {\n            CTEST_ERR(\"Failed to fork process.\");\n            exit(1);\n        } else if (fork_pid_nested == 0) {\n            check_dgemm(a, b, d, c, n);\n            exit(0);\n        } else {\n            check_dgemm(a, b, d, c, n);\n            int child_status = 0;\n            pid_t wait_pid = wait(&child_status);\n            ASSERT_EQUAL(wait_pid, fork_pid_nested);\n            ASSERT_EQUAL(0, WEXITSTATUS (child_status));\n            exit(0);\n        }\n    } else {\n        check_dgemm(a, b, d, c, n);\n        // Wait for the child to finish and check the exit code.\n        int child_status = 0;\n        pid_t wait_pid = wait(&child_status);\n        ASSERT_EQUAL(wait_pid, fork_pid);\n        ASSERT_EQUAL(0, WEXITSTATUS (child_status));\n    }\n}\n", "meta": {"hexsha": "9e0244305b38526517005f93a26fb2ffaa9e4af4", "size": 4173, "ext": "c", "lang": "C", "max_stars_repo_path": "utest/test_fork.c", "max_stars_repo_name": "fenrus75/OpenBLAS", "max_stars_repo_head_hexsha": "47bf0dba8f7a9cbd559e2f9cabe0bf2c7d3ee7a8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utest/test_fork.c", "max_issues_repo_name": "fenrus75/OpenBLAS", "max_issues_repo_head_hexsha": "47bf0dba8f7a9cbd559e2f9cabe0bf2c7d3ee7a8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utest/test_fork.c", "max_forks_repo_name": "fenrus75/OpenBLAS", "max_forks_repo_head_hexsha": "47bf0dba8f7a9cbd559e2f9cabe0bf2c7d3ee7a8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6532258065, "max_line_length": 83, "alphanum_fraction": 0.6199376947, "num_tokens": 1049, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38121956625615, "lm_q2_score": 0.03514484349535461, "lm_q1q2_score": 0.013397901993439357}}
{"text": "\n#ifndef EIGEN_BENCH_UTIL_H\n#define EIGEN_BENCH_UTIL_H\n\n#include <Eigen/Core>\n#include \"BenchTimer.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\n#include <boost/preprocessor/repetition/enum_params.hpp>\n#include <boost/preprocessor/repetition.hpp>\n#include <boost/preprocessor/seq.hpp>\n#include <boost/preprocessor/array.hpp>\n#include <boost/preprocessor/arithmetic.hpp>\n#include <boost/preprocessor/comparison.hpp>\n#include <boost/preprocessor/punctuation.hpp>\n#include <boost/preprocessor/punctuation/comma.hpp>\n#include <boost/preprocessor/stringize.hpp>\n\ntemplate<typename MatrixType> void initMatrix_random(MatrixType& mat) __attribute__((noinline));\ntemplate<typename MatrixType> void initMatrix_random(MatrixType& mat)\n{\n  mat.setRandom();// = MatrixType::random(mat.rows(), mat.cols());\n}\n\ntemplate<typename MatrixType> void initMatrix_identity(MatrixType& mat) __attribute__((noinline));\ntemplate<typename MatrixType> void initMatrix_identity(MatrixType& mat)\n{\n  mat.setIdentity();\n}\n\n#ifndef __INTEL_COMPILER\n#define DISABLE_SSE_EXCEPTIONS()  { \\\n  int aux; \\\n  asm( \\\n  \"stmxcsr   %[aux]           \\n\\t\" \\\n  \"orl       $32832, %[aux]   \\n\\t\" \\\n  \"ldmxcsr   %[aux]           \\n\\t\" \\\n  : : [aux] \"m\" (aux)); \\\n}\n#else\n#define DISABLE_SSE_EXCEPTIONS()  \n#endif\n\n#ifdef BENCH_GMM\n#include <gmm/gmm.h>\ntemplate <typename EigenMatrixType, typename GmmMatrixType>\nvoid eiToGmm(const EigenMatrixType& src, GmmMatrixType& dst)\n{\n  dst.resize(src.rows(),src.cols());\n  for (int j=0; j<src.cols(); ++j)\n    for (int i=0; i<src.rows(); ++i)\n      dst(i,j) = src.coeff(i,j);\n}\n#endif\n\n\n#ifdef BENCH_GSL\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_eigen.h>\ntemplate <typename EigenMatrixType>\nvoid eiToGsl(const EigenMatrixType& src, gsl_matrix** dst)\n{\n  for (int j=0; j<src.cols(); ++j)\n    for (int i=0; i<src.rows(); ++i)\n      gsl_matrix_set(*dst, i, j, src.coeff(i,j));\n}\n#endif\n\n#ifdef BENCH_UBLAS\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\ntemplate <typename EigenMatrixType, typename UblasMatrixType>\nvoid eiToUblas(const EigenMatrixType& src, UblasMatrixType& dst)\n{\n  dst.resize(src.rows(),src.cols());\n  for (int j=0; j<src.cols(); ++j)\n    for (int i=0; i<src.rows(); ++i)\n      dst(i,j) = src.coeff(i,j);\n}\ntemplate <typename EigenType, typename UblasType>\nvoid eiToUblasVec(const EigenType& src, UblasType& dst)\n{\n  dst.resize(src.size());\n  for (int j=0; j<src.size(); ++j)\n      dst[j] = src.coeff(j);\n}\n#endif\n\n#endif // EIGEN_BENCH_UTIL_H\n", "meta": {"hexsha": "8883a13804414f6682c984a9268785c5f6f20cf5", "size": 2529, "ext": "h", "lang": "C", "max_stars_repo_path": "src/Eigen-3.3/bench/BenchUtil.h", "max_stars_repo_name": "shareq2005/CarND-MPC-Project", "max_stars_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3457.0, "max_stars_repo_stars_event_min_datetime": "2018-06-09T15:36:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-01T22:09:25.000Z", "max_issues_repo_path": "src/Eigen-3.3/bench/BenchUtil.h", "max_issues_repo_name": "shareq2005/CarND-MPC-Project", "max_issues_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 851.0, "max_issues_repo_issues_event_min_datetime": "2017-11-27T15:09:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:26:38.000Z", "max_forks_repo_path": "src/Eigen-3.3/bench/BenchUtil.h", "max_forks_repo_name": "shareq2005/CarND-MPC-Project", "max_forks_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1380.0, "max_forks_repo_forks_event_min_datetime": "2017-06-12T23:58:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:52:48.000Z", "avg_line_length": 27.1935483871, "max_line_length": 98, "alphanum_fraction": 0.7077896402, "num_tokens": 714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014734858584286, "lm_q2_score": 0.031143827499802875, "lm_q1q2_score": 0.013396434823855066}}
{"text": "/* gsl_histogram2d_copy.c\n * Copyright (C) 2000  Simone Piccardi\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU General Public License as\n * published by the Free Software Foundation; either version 2 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n *\n * You should have received a copy of the GNU General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n */\n/***************************************************************\n *\n * File gsl_histogram2d_copy.c: \n * Routine to copy a 2D histogram. \n * Need GSL library and header.\n *\n * Author: S. Piccardi\n * Jan. 2000\n *\n ***************************************************************/\n#include <config.h>\n#include <stdlib.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_histogram2d.h>\n\n/*\n * gsl_histogram2d_copy:\n * copy the contents of an histogram into another\n */\nint\ngsl_histogram2d_memcpy (gsl_histogram2d * dest, const gsl_histogram2d * src)\n{\n  size_t nx = src->nx;\n  size_t ny = src->ny;\n  size_t i;\n  if (dest->nx != src->nx || dest->ny != src->ny)\n    {\n      GSL_ERROR (\"histograms have different sizes, cannot copy\",\n\t\t GSL_EINVAL);\n    }\n  \n  for (i = 0; i <= nx; i++)\n    {\n      dest->xrange[i] = src->xrange[i];\n    }\n\n  for (i = 0; i <= ny; i++)\n    {\n      dest->yrange[i] = src->yrange[i];\n    }\n\n  for (i = 0; i < nx * ny; i++)\n    {\n      dest->bin[i] = src->bin[i];\n    }\n\n  return GSL_SUCCESS;\n}\n\n/*\n * gsl_histogram2d_duplicate:\n * duplicate an histogram creating\n * an identical new one\n */\n\ngsl_histogram2d *\ngsl_histogram2d_clone (const gsl_histogram2d * src)\n{\n  size_t nx = src->nx;\n  size_t ny = src->ny;\n  size_t i;\n  gsl_histogram2d *h;\n\n  h = gsl_histogram2d_calloc_range (nx, ny, src->xrange, src->yrange);\n\n  if (h == 0)\n    {\n      GSL_ERROR_VAL (\"failed to allocate space for histogram struct\",\n\t\t\tGSL_ENOMEM, 0);\n    }\n\n  for (i = 0; i < nx * ny; i++)\n    {\n      h->bin[i] = src->bin[i];\n    }\n\n  return h;\n}\n", "meta": {"hexsha": "96086601240a7befaa18147ea727e72b7e5d707b", "size": 2330, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/histogram/copy2d.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/histogram/copy2d.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/histogram/copy2d.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 24.0206185567, "max_line_length": 76, "alphanum_fraction": 0.6115879828, "num_tokens": 650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3276682876897044, "lm_q2_score": 0.04084571518021443, "lm_q1q2_score": 0.013383845552562229}}
{"text": "/*\n * CircularDB implementation for time series data.\n *\n * Copyright (c) 2007-2009 Powerset, Inc\n * Copyright (c) Dan Grillo, Manish Dubey, Dan Sully\n *\n * All rights reserved.\n */\n\n#include \"config.h\"\n\n#include <ctype.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <float.h>\n#include <inttypes.h>\n#include <math.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <time.h>\n#include <unistd.h>\n\n/* For the aggregation interface */\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_interp.h>\n#include <gsl/gsl_sort.h>\n#include <gsl/gsl_statistics.h>\n\n#include <circulardb_interface.h>\n\n/* Future win32 support */\n#ifndef O_BINARY\n#define O_BINARY 0\n#endif\n\n/* Save away errno so it doesn't get overwritten */\nint cdb_error(void) {\n    int cdb_error = errno;\n    return cdb_error;\n}\n\nstatic void _print_record(FILE *fh, cdb_time_t time, double value, const char *date_format) {\n\n    if (date_format == NULL || strcmp(date_format, \"\") == 0) {\n\n        fprintf(fh, \"%d %.8g\\n\", (int)(time), value);\n\n    } else {\n\n        char formatted[256];\n        time_t stime = (time_t)time;\n\n        strftime(formatted, sizeof(formatted), date_format, localtime(&stime));\n\n        fprintf(fh, \"%d [%s] %.8g\\n\", (int)(time), formatted, value);\n    }\n}\n\nstatic uint64_t _physical_record_for_logical_record(cdb_header_t *header, int64_t logical_record) {\n\n    uint64_t physical_record = 0;\n\n    /* -ve indicates nth record from the end\n       +ve indicates nth record from the beginning (zero based counting for\n          this case)\n\n       -3 = seek to 3rd record from the end\n        5 = seek to 6th record from the beginning\n        0 = seek to first record (start) from the beginning\n\n       change the request for -nth record (nth record from the end)\n       to a request for mth record from the beginning, where:\n\n       m = N + n (n is -ve)\n\n       N : total num of records. */\n\n    if (logical_record < 0) {\n        int64_t rec_num_from_start = header->num_records + logical_record;\n\n        /* if asking for records more than there are in the db, just give as many as we can */\n        logical_record = rec_num_from_start >= 0 ? rec_num_from_start : 0;\n    }\n\n    if (logical_record >= header->num_records) {\n#ifdef DEBUG\n        printf(\"Can't seek to record [%\"PRIu64\"] with only [%\"PRIu64\"] in db\\n\", logical_record, header->num_records);\n#endif\n        return 0;\n    }\n\n    /* DRK unclear behavior here. Looks like if I specify -N where N >\n       num_records, I get pointed to #0, but if I specify +N where N >\n       num_records, it's an error */\n\n    /* Nth logical record (from the beginning) maps to Mth physical record\n       in the file, where:\n\n       m = (n+s) % N\n\n       s = physical record that is 0th logical record\n       N = total number of records in the db.  */\n\n    physical_record = logical_record + header->start_record;\n\n    if (header->num_records > 0) {\n        physical_record = (physical_record % header->num_records);\n    }\n\n    return physical_record;\n}\n\nstatic int64_t _seek_to_logical_record(cdb_t *cdb, int64_t logical_record) {\n\n    uint64_t physical_record = _physical_record_for_logical_record(cdb->header, logical_record);\n    uint64_t offset = HEADER_SIZE + (physical_record * RECORD_SIZE);\n\n    if (lseek(cdb->fd, offset, SEEK_SET) != offset) {\n        return -1;\n    }\n\n    return physical_record;\n}\n\nstatic cdb_time_t _time_for_logical_record(cdb_t *cdb, int64_t logical_record) {\n\n    cdb_record_t record[RECORD_SIZE];\n    cdb_time_t time = 0;\n\n    /* skip over any record that has NULL time or bad time values\n       Such datapoints in cdb indicate a corrupted cdb. */\n    while (!time || time <= 0) {\n\n        if (_seek_to_logical_record(cdb, logical_record) < 0) {\n            time = 0;\n            break;\n        }\n\n        logical_record += 1;\n\n        if (read(cdb->fd, &record, RECORD_SIZE) < 0) {\n            time = 0;\n            break;\n        }\n\n        time = record->time;\n    }\n\n    return time;\n}\n\n/* note - if no exact match, will return a record with a time greater than the requested value */\nstatic int64_t _logical_record_for_time(cdb_t *cdb, cdb_time_t req_time, int64_t start_logical_record, int64_t end_logical_record) {\n\n    bool first_time = false;\n    cdb_time_t start_time, next_time, center_time;\n    int64_t delta, center_logical_record, next_logical_record;\n\n    uint64_t num_recs = cdb->header->num_records;\n\n    /* for the very first time find start and end */\n    if (start_logical_record == 0 && end_logical_record == 0) {\n\n        start_logical_record = 0;\n        end_logical_record   = num_recs - 1;\n\n        first_time = true;\n    }\n\n    /* if no particular time was requested, just return the first one. */\n    if (req_time == 0) {\n        return start_logical_record;\n    }\n\n    /* if there are only 2 or 1 records in the search space, return the last record */\n    if (end_logical_record - start_logical_record <= 1) {\n        return end_logical_record;\n    }\n\n    start_time = _time_for_logical_record(cdb, start_logical_record);\n\n    /* if requested time is less than start_time, start_time is the best we can do. */\n    if (req_time <= start_time) {\n        return start_logical_record;\n    }\n\n    /* don't go out of bounds */\n    if (start_logical_record + 1 >= num_recs) {\n        return start_logical_record;\n    }\n\n    next_logical_record = start_logical_record;\n    next_time = start_time;\n\n    /* if _seek_to_logical_record encounters bad data it fabricates and\n       returns next good value. Try to get the *real* next rec. */\n    while ((next_time - start_time) == 0) {\n\n        next_logical_record += 1;\n\n        next_time = _time_for_logical_record(cdb, next_logical_record);\n\n        if (next_logical_record >= num_recs) {\n            break;\n        }\n    }\n\n    delta = next_time - start_time;\n\n    /* delta = 0 means that _seek_to_logical_record fabricated data on the fly */\n    if (delta == 0) {\n        return start_logical_record;\n    /* if we have wrapped over, or if the requested time is in the range of start and next, return start */\n    } else if (delta < 0) {\n        return start_logical_record;\n    } else if (req_time <= next_time) {\n        return next_logical_record;\n    }\n\n    /* for the very first binary search pivot point, take an aggressive guess to make search converge faster */\n    if (first_time) {\n        center_logical_record = (req_time - start_time) / (next_time - start_time) - 1;\n    } else {\n        center_logical_record = start_logical_record + (end_logical_record - start_logical_record) / 2;\n    }\n\n    if (num_recs > 0) {\n        center_logical_record = (center_logical_record % num_recs);\n    }\n\n    center_time = _time_for_logical_record(cdb, center_logical_record);\n\n    if (req_time >= center_time) {\n        start_logical_record = center_logical_record;\n    } else {\n        end_logical_record = center_logical_record;\n    }\n\n    return _logical_record_for_time(cdb, req_time, start_logical_record, end_logical_record);\n}\n\nbool _cdb_is_writable(cdb_t *cdb) {\n\n    /* We can't check for the O_RDONLY bit being because its defined value is zero.\n     * i.e. there are no bits set to look for. We therefore assume\n     * O_RDONLY if neither O_WRONLY nor O_RDWR are set. */\n    if (cdb->flags & O_RDWR) {\n        return true;\n    }\n\n    return false;\n}\n\nint cdb_read_header(cdb_t *cdb) {\n    struct stat st;\n\n    /* If the header has already been read from backing store do not read again */\n    if (cdb->synced == true) {\n        return CDB_SUCCESS;\n    }\n\n    if (cdb_open(cdb) != 0) {\n        return cdb_error();\n    }\n\n    if (pread(cdb->fd, cdb->header, HEADER_SIZE, 0) != HEADER_SIZE) {\n        return cdb_error();\n    }\n\n    if (strncmp(cdb->header->token, CDB_TOKEN, sizeof(CDB_TOKEN)) != 0) {\n        return CDB_EBADTOK;\n    }\n\n    if (strncmp(cdb->header->version, CDB_VERSION, sizeof(CDB_VERSION)) != 0) {\n        return CDB_EBADVER;\n    }\n\n    cdb->synced = true;\n\n    /* Calculate the number of records */\n    if (fstat(cdb->fd, &st) == 0) {\n        cdb->header->num_records = (st.st_size - HEADER_SIZE) / RECORD_SIZE;\n    } else {\n        cdb->header->num_records = 0;\n    }\n\n    return CDB_SUCCESS;\n}\n\nint cdb_write_header(cdb_t *cdb) {\n\n    if (cdb->synced) {\n        return CDB_SUCCESS;\n    }\n\n    if (_cdb_is_writable(cdb) == false) {\n        return CDB_ERDONLY;\n    }\n\n    cdb->synced = false;\n\n    if (cdb_open(cdb) > 0) {\n        return cdb_error();\n    }\n\n    if (pwrite(cdb->fd, cdb->header, HEADER_SIZE, 0) != HEADER_SIZE) {\n        return cdb_error();\n    }\n\n    cdb->synced = true;\n\n    return CDB_SUCCESS;\n}\n\nvoid cdb_print_header(cdb_t * cdb) {\n\n    printf(\"version: [%s]\\n\", cdb->header->version);\n    printf(\"name: [%s]\\n\", cdb->header->name);\n    printf(\"desc: [%s]\\n\", cdb->header->desc);\n    printf(\"units: [%s]\\n\", cdb->header->units);\n\n    if (cdb->header->type == CDB_TYPE_COUNTER) {\n        printf(\"type: [COUNTER]\\n\");\n    }\n\n    if (cdb->header->type == CDB_TYPE_GAUGE) {\n        printf(\"type: [GAUGE]\\n\");\n    }\n\n    printf(\"min_value: [%g]\\n\", cdb->header->min_value);\n    printf(\"max_value: [%g]\\n\", cdb->header->max_value);\n    printf(\"max_records: [%\"PRIu64\"]\\n\", cdb->header->max_records);\n    printf(\"num_records: [%\"PRIu64\"]\\n\", cdb->header->num_records);\n    printf(\"start_record: [%\"PRIu64\"]\\n\", cdb->header->start_record);\n}\n\nint cdb_write_records(cdb_t *cdb, cdb_record_t *records, uint64_t len, uint64_t *num_recs) {\n\n    /* read old header if it exists.\n       write a header out, since the db may not have existed.\n    */\n    uint64_t i   = 0;\n    uint64_t j   = 0;\n    off_t offset = 0;\n    *num_recs    = 0;\n\n    if (cdb_read_header(cdb) != CDB_SUCCESS) {\n        return cdb_error();\n    }\n\n    if (_cdb_is_writable(cdb) == false) {\n        return CDB_ERDONLY;\n    }\n\n    if (cdb->header->max_records <= 0) {\n        return CDB_EINVMAX;\n    }\n\n    /* Logic for writes:\n    cdb is 5 records.\n        try to write 7 records\n        len = 7\n        len + 0 > 5\n        j = (7 + 0) - 5\n        j = 2\n        i = 7 - 2\n        i = 5\n\n        need to write j records at offset: HEADER_SIZE + (cdb->header->start_record * RECORD_SIZE)\n        index into records is i\n\n        need to write i records at offset: HEADER_SIZE + (cdb->header->num_records * RECORD_SIZE)\n        index into records is 0;\n    */\n\n    /* Calculate our indicies into the records array. */\n    if (len + cdb->header->num_records >= cdb->header->max_records) {\n        j = (len + cdb->header->num_records) - cdb->header->max_records;\n        i = (len - j);\n    } else {\n        i = len;\n    }\n\n    /* If we need to wrap around */\n    if (j > 0) {\n\n        offset = HEADER_SIZE + (cdb->header->start_record * RECORD_SIZE);\n\n        cdb->header->start_record += j;\n        cdb->header->start_record %= cdb->header->max_records;\n\n        if (pwrite(cdb->fd, &records[i], (RECORD_SIZE * j), offset) != (RECORD_SIZE * j)) {\n            return cdb_error();\n        }\n\n        cdb->synced = false;\n\n        /* start_record is no longer 0, so update the header */\n        if (cdb_write_header(cdb) != CDB_SUCCESS) {\n            return cdb_error();\n        }\n    }\n\n    /* Normal case */\n    offset = HEADER_SIZE + (cdb->header->num_records * RECORD_SIZE);\n    cdb->header->num_records += i;\n\n    if (pwrite(cdb->fd, &records[0], (RECORD_SIZE * i), offset) != (RECORD_SIZE * i)) {\n        return cdb_error();\n    }\n\n    *num_recs += len;\n\n#ifdef DEBUG\n    printf(\"write_records: wrote [%\"PRIu64\"] records\\n\", *num_recs);\n#endif\n\n    return CDB_SUCCESS;\n}\n\nbool cdb_write_record(cdb_t *cdb, cdb_time_t time, double value) {\n\n    cdb_record_t record[RECORD_SIZE];\n    uint64_t num_recs = 0;\n\n    record->time  = time;\n    record->value = value;\n\n    if (cdb_write_records(cdb, record, 1, &num_recs) != CDB_SUCCESS) {\n        return false;\n    }\n\n    return true;\n}\n\nint cdb_update_records(cdb_t *cdb, cdb_record_t *records, uint64_t len, uint64_t *num_recs) {\n\n    int ret    = CDB_SUCCESS;\n    *num_recs  = 0;\n    uint64_t i = 0;\n\n    if (cdb_read_header(cdb) != CDB_SUCCESS) {\n        return cdb_error();\n    }\n\n    if (_cdb_is_writable(cdb) == false) {\n        return CDB_ERDONLY;\n    }\n\n#ifdef DEBUG\n    printf(\"in update_records with [%\"PRIu64\"] num_recs\\n\", cdb->header->num_records);\n#endif\n\n    for (i = 0; i < len; i++) {\n\n        cdb_time_t time = records[i].time;\n        cdb_time_t rtime;\n        uint64_t lrec;\n\n        lrec = _logical_record_for_time(cdb, time, 0, 0);\n\n        if (lrec >= 1) {\n            lrec -= 1;\n            /* DRK things like this are extremely confusing. some logical\n               functions are zero based? some are one? or you're trying to back up? */\n        }\n\n        rtime = _time_for_logical_record(cdb, lrec);\n\n        while (rtime < time && lrec < cdb->header->num_records - 1) {\n\n            /* DRK is this true? or is the condition (lrec - start_lrec) <\n               num_recs -- seems you can't wrap here (i.e. what if the initial\n               lrec was num_recs - 1) */\n\n            lrec += 1;\n            rtime = _time_for_logical_record(cdb, lrec);\n        }\n\n#ifdef DEBUG\n        printf(\"update_records: value: lrec [%\"PRIu64\"] time [%d] rtime [%d]\\n\", lrec, (int)time, (int)rtime);\n#endif\n\n        while (time == rtime && lrec < cdb->header->num_records - 1) {\n\n            _seek_to_logical_record(cdb, lrec);\n\n            if (write(cdb->fd, &records[0], RECORD_SIZE) != RECORD_SIZE) {\n                ret = cdb_error();\n                break;\n            }\n\n            lrec += 1;\n\n            rtime = _time_for_logical_record(cdb, lrec);\n        }\n    }\n\n    if (ret == CDB_SUCCESS) {\n\n        if (i > 0) {\n            cdb->synced = false;\n            *num_recs = i;\n        }\n\n        if (cdb_write_header(cdb) != CDB_SUCCESS) {\n            ret = cdb_error();\n        }\n    }\n\n    return ret;\n}\n\nbool cdb_update_record(cdb_t *cdb, cdb_time_t time, double value) {\n\n    cdb_record_t record[RECORD_SIZE];\n    uint64_t num_recs = 0;\n\n    record->time  = time;\n    record->value = value;\n\n    if (cdb_update_records(cdb, record, 1, &num_recs) != 0) {\n        return false;\n    }\n\n    return true;\n}\n\nint cdb_discard_records_in_time_range(cdb_t *cdb, cdb_request_t *request, uint64_t *num_recs) {\n\n    uint64_t i = 0;\n    int64_t lrec;\n    off_t offset = RECORD_SIZE;\n    *num_recs = 0;\n\n    if (cdb_read_header(cdb) != CDB_SUCCESS) {\n        return cdb_error();\n    }\n\n    if (_cdb_is_writable(cdb) == false) {\n        return CDB_ERDONLY;\n    }\n\n    lrec = _logical_record_for_time(cdb, request->start, 0, 0);\n\n    if (lrec >= 1) {\n        lrec -= 1;\n    }\n\n    for (i = lrec; i < cdb->header->num_records; i++) {\n\n        cdb_time_t rtime = _time_for_logical_record(cdb, i);\n\n        if (rtime >= request->start && rtime <= request->end) {\n\n            cdb_record_t record[RECORD_SIZE];\n\n            record->time  = rtime;\n            record->value = CDB_NAN;\n\n            if (pwrite(cdb->fd, &record, RECORD_SIZE, offset) != RECORD_SIZE) {\n                return cdb_error();\n            }\n\n            *num_recs += 1;\n        }\n    }\n\n    if (*num_recs > 0) {\n        cdb->synced = false;\n    }\n\n    if (cdb_write_header(cdb) != CDB_SUCCESS) {\n        return cdb_error();\n    }\n\n    return CDB_SUCCESS;\n}\n\nstatic int _compute_scale_factor_and_num_records(cdb_t *cdb, int64_t *num_records, int32_t *factor) {\n\n    if (cdb->header->type == CDB_TYPE_COUNTER) {\n        if (*num_records != 0) {\n\n            if (*num_records > 0) {\n                *num_records += 1;\n            } else {\n                *num_records -= 1;\n            }\n        }\n    }\n\n    if (strlen(cdb->header->units) > 0) {\n\n        int32_t multiplier = 1;\n        char *frequency;\n\n        if ((frequency = calloc(strlen(cdb->header->units), sizeof(char))) == NULL) {\n            return CDB_ENOMEM;\n        }\n\n        if ((sscanf(cdb->header->units, \"per %d %s\", &multiplier, frequency) == 2) ||\n            (sscanf(cdb->header->units, \"per %s\", frequency) == 1) ||\n            (sscanf(cdb->header->units, \"%*s per %s\", frequency) == 1)) {\n\n            if (strcmp(frequency, \"min\") == 0) {\n                *factor = 60;\n            } else if (strcmp(frequency, \"hour\") == 0) {\n                *factor = 60 * 60;\n            } else if (strcmp(frequency, \"sec\") == 0 || strcmp(frequency, \"second\") == 0) {\n                *factor = 1;\n            } else if (strcmp(frequency, \"day\") == 0) {\n                *factor = 60 * 60 * 24;\n            } else if (strcmp(frequency, \"week\") == 0) {\n                *factor = 60 * 60 * 24 * 7;\n            } else if (strcmp(frequency, \"month\") == 0) {\n                *factor = 60 * 60 * 24 * 30;\n            } else if (strcmp(frequency, \"quarter\") == 0) {\n                *factor = 60 * 60 * 24 * 90;\n            } else if (strcmp(frequency, \"year\") == 0) {\n                *factor = 60 * 60 * 24 * 365;\n            }\n\n            if (*factor != 0) {\n                *factor *= multiplier;\n            }\n        }\n\n        free(frequency);\n    }\n\n    return CDB_SUCCESS;\n}\n\n/* Statistics code\n * Make only one call to reading for a particular time range and compute all our stats\n */\nvoid _compute_statistics(cdb_range_t *range, uint64_t *num_recs, cdb_record_t *records) {\n\n    uint64_t i     = 0;\n    uint64_t valid = 0;\n    double sum     = 0.0;\n    double *values = calloc(*num_recs, sizeof(double));\n\n    for (i = 0; i < *num_recs; i++) {\n\n        if (!isnan(records[i].value)) {\n\n            sum += values[valid] = records[i].value;\n            valid++;\n        }\n    }\n\n    range->num_recs = valid;\n    range->mean     = gsl_stats_mean(values, 1, valid);\n    range->max      = gsl_stats_max(values, 1, valid);\n    range->min      = gsl_stats_min(values, 1, valid);\n    range->sum      = sum;\n    range->stddev   = gsl_stats_sd(values, 1, valid);\n    range->absdev   = gsl_stats_absdev(values, 1, valid);\n\n    /* The rest need sorted data */\n    gsl_sort(values, 1, valid);\n\n    range->median   = gsl_stats_median_from_sorted_data(values, 1, valid);\n    range->pct95th  = gsl_stats_quantile_from_sorted_data(values, 1, valid, 0.95);\n    range->pct75th  = gsl_stats_quantile_from_sorted_data(values, 1, valid, 0.75);\n    range->pct50th  = gsl_stats_quantile_from_sorted_data(values, 1, valid, 0.50);\n    range->pct25th  = gsl_stats_quantile_from_sorted_data(values, 1, valid, 0.25);\n\n    /* MAD must come last because it alters the values array\n     * http://en.wikipedia.org/wiki/Median_absolute_deviation */\n    for (i = 0; i < valid; i++) {\n        values[i] = fabs(values[i] - range->median);\n\n        if (values[i] < 0.0) {\n            values[i] *= -1.0;\n        }\n    }\n\n    /* Final sort is required MAD */\n    gsl_sort(values, 1, valid);\n    range->mad = gsl_stats_median_from_sorted_data(values, 1, valid);\n\n    free(values);\n}\n\ndouble cdb_get_statistic(cdb_range_t *range, cdb_statistics_enum_t type) {\n\n    switch (type) {\n        case CDB_MEDIAN:\n            return range->median;\n        case CDB_MAD:\n            return range->mad;\n        case CDB_95TH:\n            return range->pct95th;\n        case CDB_75TH:\n            return range->pct75th;\n        case CDB_50TH:\n            return range->pct50th;\n        case CDB_25TH:\n            return range->pct25th;\n        case CDB_MEAN:\n            return range->mean;\n        case CDB_SUM:\n            return range->sum;\n        case CDB_MAX:\n            return range->max;\n        case CDB_MIN:\n            return range->min;\n        case CDB_STDDEV:\n            return range->stddev;\n        case CDB_ABSDEV:\n            return range->absdev;\n        default:\n            fprintf(stderr, \"aggregate_using_function_for_records() function: [%d] not supported\\n\", type);\n            return CDB_FAILURE;\n    }\n}\n\nstatic int _cdb_read_records(cdb_t *cdb, cdb_request_t *request, uint64_t *num_recs, cdb_record_t **records) {\n\n    int64_t first_requested_logical_record;\n    int64_t last_requested_logical_record;\n    uint64_t last_requested_physical_record;\n    int64_t seek_physical_record;\n\n    cdb_record_t *buffer = NULL;\n\n    if (cdb_read_header(cdb) != CDB_SUCCESS) {\n        return cdb_error();\n    }\n\n    if (request->start != 0 && request->end != 0 && request->end < request->start) {\n        return CDB_ETMRANGE;\n    }\n\n    if (cdb->header == NULL || cdb->synced == false) {\n        return CDB_ESANITY;\n    }\n\n    /* bail out if there are no records */\n    if (cdb->header->num_records <= 0) {\n        return CDB_ENORECS;\n    }\n\n    /*\n      get the number of requested records:\n\n      -ve indicates n records from the beginning\n      +ve indicates n records off of the end.\n      0 or undef means the whole thing.\n\n      switch the meaning of -ve/+ve to be more array like\n    */\n    if (request->count != 0) {\n        request->count = -request->count;\n    }\n\n#ifdef DEBUG\n    printf(\"read_records start: [%ld]\\n\", request->start);\n    printf(\"read_records end: [%ld]\\n\", request->end);\n    printf(\"read_records num_requested: [%\"PRIu64\"]\\n\", request->count);\n#endif\n\n    if (request->count != 0 && request->count < 0 && request->start == 0) {\n        /* if reading only few records from the end, just set -ve offset to seek to */\n        first_requested_logical_record = request->count;\n\n    } else {\n        /* compute which record to start reading from the beginning, based on start time specified. */\n        first_requested_logical_record = _logical_record_for_time(cdb, request->start, 0, 0);\n    }\n\n    /* if end is not defined, read all the records or only read uptill the specified record. */\n    if (request->end == 0) {\n\n        last_requested_logical_record = cdb->header->num_records - 1;\n\n    } else {\n\n        last_requested_logical_record = _logical_record_for_time(cdb, request->end, 0, 0);\n\n        /* this can return something > end, check for that */\n        if (_time_for_logical_record(cdb, last_requested_logical_record) > request->end) {\n            last_requested_logical_record -= 1;\n        }\n    }\n\n    last_requested_physical_record = (last_requested_logical_record + cdb->header->start_record) % cdb->header->num_records;\n\n    /* After _seek_to_logical_record(), we're at the offset to read from. */\n    seek_physical_record = _seek_to_logical_record(cdb, first_requested_logical_record);\n\n    if (last_requested_physical_record >= seek_physical_record) {\n\n        uint64_t nrec = (last_requested_physical_record - seek_physical_record + 1);\n        uint64_t rlen = RECORD_SIZE * nrec;\n\n        if ((buffer = calloc(1, rlen)) == NULL) {\n            free(buffer);\n            return CDB_ENOMEM;\n        }\n\n        if (read(cdb->fd, buffer, rlen) != rlen) {\n            free(buffer);\n            return cdb_error();\n        }\n\n        *num_recs = nrec;\n\n    } else {\n\n        /* We've wrapped around the end of the file */\n        uint64_t nrec1 = (cdb->header->num_records - seek_physical_record);\n        uint64_t nrec2 = (last_requested_physical_record + 1);\n\n        uint64_t rlen1 = RECORD_SIZE * nrec1;\n        uint64_t rlen2 = RECORD_SIZE * nrec2;\n\n        if ((buffer = calloc(1, rlen1 + rlen2)) == NULL) {\n            free(buffer);\n            return CDB_ENOMEM;\n        }\n\n        /* Read at the offset set by _seek_to_logical_record() */\n        if (read(cdb->fd, buffer, rlen1) != rlen1) {\n            free(buffer);\n            return cdb_error();\n        }\n\n        /* And then the wrap around portion past the header. */\n        if (pread(cdb->fd, &buffer[nrec1], rlen2, HEADER_SIZE) != rlen2) {\n            free(buffer);\n            return cdb_error();\n        }\n\n        *num_recs = nrec1 + nrec2;\n    }\n\n    /* Deal with cooking the output */\n    if (request->cooked) {\n\n        bool check_min_max = true;\n        int32_t factor = 0;\n        uint64_t i = 0;\n        uint64_t cooked_recs = 0;\n        double prev_value = 0.0;\n        cdb_time_t prev_date = 0;\n        cdb_record_t *crecords;\n\n        if ((crecords = calloc(*num_recs, RECORD_SIZE)) == NULL) {\n            free(crecords);\n            free(buffer);\n            return CDB_ENOMEM;\n        }\n\n        if (_compute_scale_factor_and_num_records(cdb, &request->count, &factor)) {\n            free(crecords);\n            free(buffer);\n            return cdb_error();\n        }\n\n        if (cdb->header->min_value == 0 && cdb->header->max_value == 0) {\n            check_min_max = false;\n        }\n\n        for (i = 0; i < *num_recs; i++) {\n\n            cdb_time_t date = buffer[i].time;\n            double value    = buffer[i].value;\n\n            if (cdb->header->type == CDB_TYPE_COUNTER) {\n                double new_value = value;\n                value = CDB_NAN;\n\n                if (!isnan(prev_value) && !isnan(new_value)) {\n\n                    double val_delta = new_value - prev_value;\n\n                    if (val_delta >= 0) {\n                        value = val_delta;\n                    }\n                }\n\n                prev_value = new_value;\n            }\n\n            if (factor != 0 && cdb->header->type == CDB_TYPE_COUNTER) {\n\n                /* Skip the first entry, since it's absolute and is needed\n                 * to calculate the second */\n                if (prev_date == 0) {\n                    prev_date = date;\n                    continue;\n                }\n\n                cdb_time_t time_delta = date - prev_date;\n\n                if (time_delta > 0 && !isnan(value)) {\n                    value = factor * (value / time_delta);\n                }\n\n                prev_date = date;\n            }\n\n            /* Check for min/max boundaries */\n            /* Should this be done on write instead of read? */\n            if (check_min_max && !isnan(value)) {\n                if (value > cdb->header->max_value || value < cdb->header->min_value) {\n                    value = CDB_NAN;\n                }\n            }\n\n            /* Copy the munged data to our new array, since we might skip\n             * elements. Also keep in mind mmap for the future */\n            crecords[cooked_recs].time  = date;\n            crecords[cooked_recs].value = value;\n            cooked_recs += 1;\n        }\n\n        /* Now swap our cooked records for the buffer, so we can slice it as needed. */\n        free(buffer);\n        buffer = crecords;\n        *num_recs = cooked_recs;\n    }\n\n    /* If we've been requested to average the records & timestamps */\n    if (request->step > 1) {\n\n        cdb_record_t *arecords;\n        uint32_t step      = request->step;\n        uint64_t step_recs = 0;\n        uint64_t leftover  = (*num_recs % step);\n        uint64_t walkend   = (*num_recs - leftover);\n        uint64_t i = 0;\n\n        if ((arecords = calloc(((*num_recs / step) + leftover), RECORD_SIZE)) == NULL) {\n            free(arecords);\n            free(buffer);\n            return CDB_ENOMEM;\n        }\n\n        /* Walk our list of cooked records, jumping ahead by the given step.\n           For each set of records within that step, we want to get the average\n           for those records and place them into a new array.\n         */\n        for (i = 0; i < walkend; i += step) {\n\n            uint64_t j = 0;\n            double xi[step];\n            double yi[step];\n\n            for (j = 0; j < step; j++) {\n\n                /* No NaNs on average - they cause bogus graphs. Is there a\n                 * better value than 0 to use here? */\n                if (isnan(buffer[i+j].value)) {\n                    buffer[i+j].value = 0;\n                }\n\n                xi[j] = (double)buffer[i+j].time;\n                yi[j] = buffer[i+j].value;\n            }\n\n            arecords[step_recs].time  = (cdb_time_t)gsl_stats_mean(xi, 1, step);\n            arecords[step_recs].value = gsl_stats_mean(yi, 1, step);\n            step_recs += 1;\n        }\n\n        /* Now collect from the last step point to the end & average. */\n        if (leftover > 0) {\n            uint64_t leftover_start = *num_recs - leftover;\n\n            uint64_t j = 0;\n            double xi[leftover];\n            double yi[leftover];\n\n            for (i = leftover_start; i < *num_recs; i++) {\n\n                /* No NaNs on average - they cause bogus graphs. Is there a\n                 * better value than 0 to use here? */\n                if (isnan(buffer[i].value)) {\n                    buffer[i].value = 0;\n                }\n\n                xi[j] = (double)buffer[i].time;\n                yi[j] = buffer[i].value;\n                j++;\n            }\n\n            arecords[step_recs].time  = (cdb_time_t)gsl_stats_mean(xi, 1, j);\n            arecords[step_recs].value = gsl_stats_mean(yi, 1, j);\n            step_recs += 1;\n        }\n\n        free(buffer);\n        buffer = arecords;\n        *num_recs = step_recs;\n    }\n\n    /* now pull out the number of requested records if asked */\n    if (request->count != 0 && *num_recs >= abs(request->count)) {\n\n        uint64_t start_index = 0;\n\n        if (request->count <= 0) {\n            start_index = *num_recs - abs(request->count);\n        }\n\n        *num_recs = abs(request->count);\n\n        if ((*records  = calloc(*num_recs, RECORD_SIZE)) == NULL) {\n            free(buffer);\n            return CDB_ENOMEM;\n        }\n\n        memcpy(*records, &buffer[start_index], RECORD_SIZE * *num_recs);\n\n        free(buffer);\n\n    } else {\n\n        *records = buffer;\n    }\n\n    return CDB_SUCCESS;\n}\n\nint cdb_read_records(cdb_t *cdb, cdb_request_t *request,\n    uint64_t *num_recs, cdb_record_t **records, cdb_range_t *range) {\n\n    int ret   = CDB_SUCCESS;\n\n    ret = _cdb_read_records(cdb, request, num_recs, records);\n\n    if (ret == CDB_SUCCESS) {\n\n        if (*num_recs > 0) {\n            range->start_time = request->start;\n            range->end_time   = request->end;\n\n            _compute_statistics(range, num_recs, *records);\n        }\n    }\n\n    return ret;\n}\n\nvoid cdb_print_records(cdb_t *cdb, cdb_request_t *request, FILE *fh, const char *date_format) {\n\n    uint64_t i = 0;\n    uint64_t num_recs = 0;\n\n    cdb_record_t *records = NULL;\n\n    if (_cdb_read_records(cdb, request, &num_recs, &records) == CDB_SUCCESS) {\n\n        for (i = 0; i < num_recs; i++) {\n\n            _print_record(fh, records[i].time, records[i].value, date_format);\n        }\n    }\n\n    free(records);\n}\n\nvoid cdb_print(cdb_t *cdb) {\n\n    const char *date_format = \"%Y-%m-%d %H:%M:%S\";\n    cdb_request_t request;\n\n    request.start  = 0;\n    request.end    = 0;\n    request.count  = 0;\n    request.step   = 0;\n    request.cooked = false;\n\n    printf(\"============== Header ================\\n\");\n\n    if (cdb_read_header(cdb) == CDB_SUCCESS) {\n        cdb_print_header(cdb);\n    }\n\n    if (cdb->header->type == CDB_TYPE_COUNTER) {\n\n        printf(\"============= Raw Counter Records =============\\n\");\n        cdb_print_records(cdb, &request, stdout, date_format);\n        printf(\"============== End Raw Counter Records ==============\\n\");\n\n        printf(\"============== Cooked Records ================\\n\");\n\n    } else {\n        printf(\"============== Records ================\\n\");\n    }\n\n    request.cooked = true;\n    cdb_print_records(cdb, &request, stdout, date_format);\n\n    printf(\"============== End ================\\n\");\n}\n\n/* Take in an array of cdbs */\nint cdb_read_aggregate_records(cdb_t **cdbs, int num_cdbs, cdb_request_t *request,\n    uint64_t *driver_num_recs, cdb_record_t **records, cdb_range_t *range) {\n\n    uint64_t i = 0;\n    int ret    = CDB_SUCCESS;\n    cdb_record_t *driver_records = NULL;\n    *driver_num_recs = 0;\n\n    if (cdbs[0] == NULL) {\n        return CDB_ESANITY;\n    }\n\n    /* The first cdb is the driver */\n    ret = _cdb_read_records(cdbs[0], request, driver_num_recs, &driver_records);\n\n    if (ret != CDB_SUCCESS) {\n        fprintf(stderr, \"Bailed on: %s\\n\", cdbs[0]->filename);\n        free(driver_records);\n        return ret;\n    }\n\n    if ((*records = calloc(*driver_num_recs, RECORD_SIZE)) == NULL) {\n        free(driver_records);\n        return CDB_ENOMEM;\n    }\n\n    if (*driver_num_recs <= 1) {\n        free(driver_records);\n        return CDB_EINTERPD;\n    }\n\n    double *driver_x_values   = calloc(*driver_num_recs, sizeof(double));\n    double *driver_y_values   = calloc(*driver_num_recs, sizeof(double));\n    double *follower_x_values = calloc(*driver_num_recs, sizeof(double));\n    double *follower_y_values = calloc(*driver_num_recs, sizeof(double));\n\n    for (i = 0; i < *driver_num_recs; i++) {\n        (*records)[i].time  = driver_x_values[i] = driver_records[i].time;\n        (*records)[i].value = driver_y_values[i] = driver_records[i].value;\n    }\n\n    /* initialize and allocate the gsl objects  */\n    gsl_interp_accel *accel = gsl_interp_accel_alloc();\n    gsl_interp *interp = gsl_interp_alloc(gsl_interp_linear, *driver_num_recs);\n\n    /* Allows 0.0 to be returned as a valid yi */\n    gsl_set_error_handler_off();\n\n    gsl_interp_init(interp, driver_x_values, driver_y_values, *driver_num_recs);\n\n    for (i = 1; i < num_cdbs; i++) {\n\n        uint64_t j = 0;\n        uint64_t follower_num_recs = 0;\n\n        cdb_record_t *follower_records = NULL;\n\n        ret = _cdb_read_records(cdbs[i], request, &follower_num_recs, &follower_records);\n\n        /* Just bail, free all allocations below and let the error bubble up */\n        if (ret == CDB_SUCCESS && follower_num_recs != 0) {\n\n            for (j = 0; j < *driver_num_recs; j++) {\n\n                /* Check for out of bounds */\n                if (j >= follower_num_recs) {\n                    break;\n                }\n\n                follower_x_values[j] = follower_records[j].time;\n                follower_y_values[j] = follower_records[j].value;\n            }\n\n            for (j = 0; j < *driver_num_recs; j++) {\n\n                double yi = gsl_interp_eval(interp, follower_x_values, follower_y_values, driver_x_values[j], accel);\n\n                if (isnormal(yi)) {\n                    (*records)[j].value += yi;\n                }\n            }\n        }\n\n        free(follower_records);\n\n        if (ret != CDB_SUCCESS) {\n            break;\n        }\n    }\n\n    if (ret == CDB_SUCCESS && *driver_num_recs > 0) {\n        /* Compute all the statistics for this range */\n        range->start_time = request->start;\n        range->end_time   = request->end;\n\n        _compute_statistics(range, driver_num_recs, *records);\n    }\n\n    free(driver_x_values);\n    free(driver_y_values);\n    free(follower_x_values);\n    free(follower_y_values);\n\n    gsl_interp_free(interp);\n    gsl_interp_accel_free(accel);\n    free(driver_records);\n\n    return ret;\n}\n\nvoid cdb_print_aggregate_records(cdb_t **cdbs, int32_t num_cdbs, cdb_request_t *request, FILE *fh, const char *date_format) {\n\n    uint64_t i = 0;\n    uint64_t num_recs = 0;\n\n    cdb_record_t *records = NULL;\n    cdb_range_t *range = calloc(1, sizeof(cdb_range_t));\n\n    cdb_read_aggregate_records(cdbs, num_cdbs, request, &num_recs, &records, range);\n\n    for (i = 0; i < num_recs; i++) {\n\n        _print_record(fh, records[i].time, records[i].value, date_format);\n    }\n\n    free(range);\n    free(records);\n}\n\nvoid cdb_generate_header(cdb_t *cdb, char* name, char* desc, uint64_t max_records, int32_t type,\n    char* units, uint64_t min_value, uint64_t max_value) {\n\n    if (max_records == 0) {\n        max_records = CDB_DEFAULT_RECORDS;\n    }\n\n    if (type == 0) {\n        cdb->header->type = CDB_DEFAULT_DATA_TYPE;\n    }\n\n    if (units == NULL || (strcmp(units, \"\") == 0)) {\n        units = (char*)CDB_DEFAULT_DATA_UNIT;\n    }\n\n    if (desc == NULL) {\n        desc = (char*)\"\";\n    }\n\n    memset(cdb->header->name, 0, sizeof(cdb->header->name));\n    memset(cdb->header->desc, 0, sizeof(cdb->header->desc));\n    memset(cdb->header->units, 0, sizeof(cdb->header->units));\n    memset(cdb->header->version, 0, sizeof(cdb->header->version));\n    memset(cdb->header->token, 0, sizeof(cdb->header->token));\n\n    strncpy(cdb->header->name, name, sizeof(cdb->header->name));\n    strncpy(cdb->header->desc, desc, sizeof(cdb->header->desc));\n    strncpy(cdb->header->units, units, sizeof(cdb->header->units));\n    strncpy(cdb->header->version, CDB_VERSION, sizeof(cdb->header->version));\n    strncpy(cdb->header->token, CDB_TOKEN, sizeof(cdb->header->token));\n\n    cdb->header->type         = type;\n    cdb->header->max_records  = max_records;\n    cdb->header->min_value    = min_value;\n    cdb->header->max_value    = max_value;\n    cdb->header->num_records  = 0;\n    cdb->header->start_record = 0;\n}\n\ncdb_t* cdb_new(void) {\n\n    cdb_t *cdb  = calloc(1, sizeof(cdb_t));\n    cdb->header = calloc(1, HEADER_SIZE);\n\n    cdb->fd = -1;\n    cdb->synced = false;\n    cdb->flags = -1;\n    cdb->mode = -1;\n\n    return cdb;\n}\n\ncdb_request_t cdb_new_request(void) {\n    cdb_request_t request;\n    memset (&request, 0, sizeof (request));\n    request.start  = 0;\n    request.end    = 0;\n    request.count  = 0;\n    request.cooked = true;\n    request.step   = 0;\n    return request;\n}\n\nint cdb_open(cdb_t *cdb) {\n\n    if (cdb->fd >= 0) {\n        return CDB_SUCCESS;\n    }\n\n    /* Default flags if none were set */\n    if (cdb->flags == -1) {\n        cdb->flags = O_RDONLY|O_BINARY;\n    }\n\n    /* A cdb can't be write only - we need to read the header */\n    if (cdb->flags & O_WRONLY) {\n        cdb->flags = O_RDWR;\n    }\n\n    if (cdb->mode == -1) {\n        cdb->mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;\n    }\n\n    cdb->fd = open(cdb->filename, cdb->flags, cdb->mode);\n\n    if (cdb->fd < 0) {\n        return cdb_error();\n    }\n\n    return CDB_SUCCESS;\n}\n\nint cdb_close(cdb_t *cdb) {\n\n    if (cdb != NULL) {\n\n        if (cdb->fd > 0) {\n            if (close(cdb->fd) != 0) {\n                return cdb_error();\n            }\n            cdb->fd = -1;\n        }\n    }\n\n    return CDB_SUCCESS;\n}\n\nint cdb_free(cdb_t *cdb) {\n    int ret = CDB_SUCCESS;\n\n    if (cdb != NULL) {\n\n        if (cdb->header != NULL) {\n            ret = cdb_close(cdb);\n            free(cdb->header);\n            cdb->header = NULL;\n        }\n\n        free(cdb);\n        cdb = NULL;\n    }\n\n    return ret;\n}\n\n/* -*- Mode: C; tab-width: 4 -*- */\n/* vim: set tabstop=4 expandtab shiftwidth=4: */\n", "meta": {"hexsha": "fba1152dd4938c8f72aea83aea7fba0d1f84902e", "size": 38051, "ext": "c", "lang": "C", "max_stars_repo_path": "src/circulardb.c", "max_stars_repo_name": "dsully/circulardb", "max_stars_repo_head_hexsha": "8191d65e18324e5c2e7481de8ed3281ab197d205", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-12-24T12:59:03.000Z", "max_stars_repo_stars_event_max_datetime": "2016-11-25T03:35:03.000Z", "max_issues_repo_path": "src/circulardb.c", "max_issues_repo_name": "dsully/circulardb", "max_issues_repo_head_hexsha": "8191d65e18324e5c2e7481de8ed3281ab197d205", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-09T08:28:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-09T08:28:27.000Z", "max_forks_repo_path": "src/circulardb.c", "max_forks_repo_name": "dsully/circulardb", "max_forks_repo_head_hexsha": "8191d65e18324e5c2e7481de8ed3281ab197d205", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8761904762, "max_line_length": 132, "alphanum_fraction": 0.5749651783, "num_tokens": 10329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.026759283088424575, "lm_q1q2_score": 0.013379641544212287}}
{"text": "/* Copyright 2018 Los Alamos National Laboratory\n * Copyright 2009-2018 The University of Tennessee and The University \n *                     of Tennessee Research Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n#ifndef _TESTSCOMMON_H\n#define _TESTSCOMMON_H\n\n/* parsec things */\n#include \"parsec.h\"\n\n/* system and io */\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n/* Plasma and math libs */\n#include <math.h>\n//#include <cblas.h>\n//#include <lapacke.h>\n//#include <core_blas.h>\n\n#include \"parsec/profiling.h\"\n#include \"parsec/parsec_internal.h\"\n#include \"parsec/utils/debug.h\"\n//#include \"dplasma.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/* these are globals in common.c */\nextern const char *PARSEC_SCHED_NAME[];\nextern int unix_timestamp;\nextern char cwd[];\n\n/* Update PASTE_CODE_PROGRESS_KERNEL below if you change this list */\nenum iparam_t {\n  IPARAM_RANK,         /* Rank                              */\n  IPARAM_NNODES,       /* Number of nodes                   */\n  IPARAM_NCORES,       /* Number of cores                   */\n  IPARAM_NGPUS,        /* Number of GPUs                    */\n  IPARAM_P,            /* Rows in the process grid          */\n  IPARAM_Q,            /* Columns in the process grid       */\n  IPARAM_M,            /* Number of rows of the matrix      */\n  IPARAM_N,            /* Number of columns of the matrix   */\n  IPARAM_K,            /* RHS or K                          */\n  IPARAM_LDA,          /* Leading dimension of A            */\n  IPARAM_LDB,          /* Leading dimension of B            */\n  IPARAM_LDC,          /* Leading dimension of C            */\n  IPARAM_IB,           /* Inner-blocking size               */\n  IPARAM_NB,           /* Number of columns in a tile       */\n  IPARAM_MB,           /* Number of rows in a tile          */\n  IPARAM_SNB,          /* Number of columns in a super-tile */\n  IPARAM_SMB,          /* Number of rows in a super-tile    */\n  IPARAM_HMB,          /* Small MB for recursive hdags */\n  IPARAM_HNB,          /* Small NB for recursive hdags */\n  IPARAM_CHECK,        /* Checking activated or not         */\n  IPARAM_VERBOSE,      /* How much noise do we want?        */\n  IPARAM_SCHEDULER,    /* User-selected scheduler */\n  IPARAM_SIZEOF\n};\n\n#define PARSEC_SCHEDULER_DEFAULT 0\n#define PARSEC_SCHEDULER_LFQ 1\n#define PARSEC_SCHEDULER_LTQ 2\n#define PARSEC_SCHEDULER_AP  3\n#define PARSEC_SCHEDULER_LHQ 4\n#define PARSEC_SCHEDULER_GD  5\n#define PARSEC_SCHEDULER_PBQ 6\n#define PARSEC_SCHEDULER_IP  7\n#define PARSEC_SCHEDULER_RND 8\n\nvoid iparam_default_gemm(int* iparam);\nvoid iparam_default_ibnbmb(int* iparam, int ib, int nb, int mb);\n\n#define PASTE_CODE_IPARAM_LOCALS(iparam)                                \\\n    rank  = iparam[IPARAM_RANK];                                    \\\n    nodes = iparam[IPARAM_NNODES];                                  \\\n    cores = iparam[IPARAM_NCORES];                                  \\\n    gpus  = iparam[IPARAM_NGPUS];                                   \\\n    P     = iparam[IPARAM_P];                                       \\\n    Q     = iparam[IPARAM_Q];                                       \\\n    M     = iparam[IPARAM_M];                                       \\\n    N     = iparam[IPARAM_N];                                       \\\n    K     = iparam[IPARAM_K];                                       \\\n    NRHS  = K;                                                      \\\n    LDA   = max(M, iparam[IPARAM_LDA]);                             \\\n    LDB   = max(N, iparam[IPARAM_LDB]);                             \\\n    LDC   = max(K, iparam[IPARAM_LDC]);                             \\\n    IB    = iparam[IPARAM_IB];                                      \\\n    MB    = iparam[IPARAM_MB];                                      \\\n    NB    = iparam[IPARAM_NB];                                      \\\n    SMB   = iparam[IPARAM_SMB];                                     \\\n    SNB   = iparam[IPARAM_SNB];                                     \\\n    HMB   = iparam[IPARAM_HMB];                                     \\\n    HNB   = iparam[IPARAM_HNB];                                     \\\n    MT    = (M%MB==0) ? (M/MB) : (M/MB+1);                          \\\n    NT    = (N%NB==0) ? (N/NB) : (N/NB+1);                          \\\n    KT    = (K%MB==0) ? (K/MB) : (K/MB+1);                          \\\n    check = iparam[IPARAM_CHECK];                                   \\\n    loud  = iparam[IPARAM_VERBOSE];                                 \\\n    scheduler = iparam[IPARAM_SCHEDULER];                           \\\n    (void)rank;(void)nodes;(void)cores;(void)gpus;(void)P;(void)Q;(void)M;(void)N;(void)K;(void)NRHS; \\\n    (void)LDA;(void)LDB;(void)LDC;(void)IB;(void)MB;(void)NB;(void)MT;(void)NT;(void)KT; \\\n    (void)SMB;(void)SNB;(void)HMB;(void)HNB;(void)check;(void)loud; \\\n    (void)scheduler;\n\n/*******************************\n * globals values\n *******************************/\n\n#if defined(PARSEC_HAVE_MPI)\nextern MPI_Datatype SYNCHRO;\n#endif  /* PARSEC_HAVE_MPI */\n\nvoid print_usage(void);\nvoid print_arguments(int* iparam);\n\nparsec_context_t *setup_parsec(int argc, char* argv[], int *iparam);\nvoid cleanup_parsec(parsec_context_t* parsec, int *iparam);\n\n/**\n * No macro with the name max or min is acceptable as there is\n * no way to correctly define them without borderline effects.\n */\n#undef max\n#undef min\nstatic inline int max(int a, int b) { return a > b ? a : b; }\nstatic inline int min(int a, int b) { return a < b ? a : b; }\n\n\n/* Paste code to allocate a matrix in desc if cond_init is true */\n#define PASTE_CODE_ALLOCATE_MATRIX(DC, COND, TYPE, INIT_PARAMS)      \\\n    if(COND) {                                                          \\\n        DC.mat = parsec_data_allocate((size_t)DC.super.nb_local_tiles * \\\n                                        (size_t)DC.super.bsiz *      \\\n                                        (size_t)parsec_datadist_getsizeoftype(DC.super.mtype)); \\\n        parsec_data_collection_set_key((parsec_data_collection_t*)&DC, #DC);          \\\n    }\n\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* _TESTSCOMMON_H */\n", "meta": {"hexsha": "635de63bdd9d879f835dcbf8b4ac12c0d38244c2", "size": 6602, "ext": "h", "lang": "C", "max_stars_repo_path": "parsec/common.h", "max_stars_repo_name": "nicog98/task-bench", "max_stars_repo_head_hexsha": "a5a7dd36e383f194302dd816cf29f7f21b1f28a5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "parsec/common.h", "max_issues_repo_name": "nicog98/task-bench", "max_issues_repo_head_hexsha": "a5a7dd36e383f194302dd816cf29f7f21b1f28a5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "parsec/common.h", "max_forks_repo_name": "nicog98/task-bench", "max_forks_repo_head_hexsha": "a5a7dd36e383f194302dd816cf29f7f21b1f28a5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.7848101266, "max_line_length": 103, "alphanum_fraction": 0.5202968797, "num_tokens": 1597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3738758227716966, "lm_q2_score": 0.03567855049321807, "lm_q1q2_score": 0.013339347420953426}}
{"text": "#ifndef Performance_h\n#define Performance_h 1\n#include <vector>\n\n#include <gsl/gsl_errno.h>\n\n// if p0 is less than chop, then set to zero, associated with calling routine chop\nconst double chop = 1e-3;\nconst double p1bound = 1e-5;\n\nvoid debugPerformanceOn(unsigned);\n\nenum class signalType {output, controlOpen, controlClosed};\n\ndouble performance(const std::vector<double>& num, const std::vector<double>& den, \n\t\t\t\t\tdouble gamma, double tmax, signalType s);\n\n// GSL error handling: call setGSLErrorHandle(s), s = 0 turns off error handler, 1 sets my handler; should check return status of all significant GSL calls and take appropriate action within code, for example return high performance value and thus zero fitness if cannot evaluate performance for parameter combination\ninline void my_gsl_handler (const char *reason, const char *file, int line, int gsl_errno __attribute__((unused)))\n{std::cout << fmt::format(\"GSL error: {}:{}, {}\\n\", file, line, reason);}\ninline void setGSLErrorHandle(int s)\n    {(s) ? gsl_set_error_handler(&my_gsl_handler) : gsl_set_error_handler_off();}\n\n#endif\n", "meta": {"hexsha": "bac9a3e6b48216f463cffdab6e2d4630fbb358d9", "size": 1095, "ext": "h", "lang": "C", "max_stars_repo_path": "src/Performance.h", "max_stars_repo_name": "evolbio/design2", "max_stars_repo_head_hexsha": "7f1856e682382e91e56569de2a6d64a61cc424cc", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Performance.h", "max_issues_repo_name": "evolbio/design2", "max_issues_repo_head_hexsha": "7f1856e682382e91e56569de2a6d64a61cc424cc", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Performance.h", "max_forks_repo_name": "evolbio/design2", "max_forks_repo_head_hexsha": "7f1856e682382e91e56569de2a6d64a61cc424cc", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.8, "max_line_length": 317, "alphanum_fraction": 0.7607305936, "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38491214448393346, "lm_q2_score": 0.03461883834117344, "lm_q1q2_score": 0.013325211305443688}}
{"text": "/* fp-win.c\n * \n * Author: Brian Gladman\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <float.h>\n\n#include <config.h>\n#include <gsl/gsl_ieee_utils.h>\n#include <gsl/gsl_errno.h>\n\nconst char *fp_env_string = \"round-to-nearest,double-precision,mask-all\";\n\nint\ngsl_ieee_set_mode (int precision, int rounding, int exception_mask)\n{\n\tunsigned int old, mode = _DN_SAVE, mask = _MCW_DN | _MCW_RC | _MCW_EM;\n\n\tswitch(precision)\n    {\n    case GSL_IEEE_SINGLE_PRECISION:\t\tmode |= _PC_24; break;\n    case GSL_IEEE_EXTENDED_PRECISION:\tmode |= _PC_64; break;\n    case GSL_IEEE_DOUBLE_PRECISION:\n    default:\t\t\t\t\t\t\tmode |= _PC_53;\n\t}\n\n\t/* precison control is disabled on Windows x64 with MSVC \n\t   but is allowed by the Intel compiler \n\t*/\n#if !defined( _WIN64 ) || defined( __ICL )\n\tmask |= _MCW_PC;\n#endif\n\n\tswitch(rounding)\n    {\n    case GSL_IEEE_ROUND_DOWN:\t\t\tmode |= _RC_DOWN; break;\n    case GSL_IEEE_ROUND_UP:\t\t\t\tmode |= _RC_UP;   break;\n    case GSL_IEEE_ROUND_TO_ZERO:\t\tmode |= _RC_CHOP; break;\n    case GSL_IEEE_ROUND_TO_NEAREST:\n    default:\t\t\t\t\t\t\tmode |= _RC_NEAR;\n    }\n\n\tif(exception_mask & GSL_IEEE_MASK_INVALID)\n\t\tmode |= _EM_INVALID;\n\tif(exception_mask & GSL_IEEE_MASK_DENORMALIZED)\n\t\tmode |= _EM_DENORMAL;\n\tif(exception_mask & GSL_IEEE_MASK_DIVISION_BY_ZERO)\n\t\tmode |= _EM_ZERODIVIDE;\n\tif(exception_mask & GSL_IEEE_MASK_OVERFLOW)\n\t\tmode |= _EM_OVERFLOW;\n\tif(exception_mask & GSL_IEEE_MASK_UNDERFLOW)\n\t\tmode |= _EM_UNDERFLOW;\n\tif(exception_mask & GSL_IEEE_TRAP_INEXACT)\n\t\tmode &= ~_EM_INEXACT;\n\telse\n\t\tmode |= _EM_INEXACT;\n\t\n\t_clearfp();\n\t_controlfp_s(&old, mode, mask);\n\treturn GSL_SUCCESS;\n}\n", "meta": {"hexsha": "a4a522df2922830b94e47a07c3277ae423a1e550", "size": 2290, "ext": "c", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/build.vc/fp-win.c", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/build.vc/fp-win.c", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/build.vc/fp-win.c", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 30.1315789474, "max_line_length": 81, "alphanum_fraction": 0.7253275109, "num_tokens": 626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39606816627404173, "lm_q2_score": 0.033589502747842115, "lm_q1q2_score": 0.013303732759394712}}
{"text": "/* vector/gsl_vector_int.h\r\n * \r\n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\r\n * \r\n * This program is free software; you can redistribute it and/or modify\r\n * it under the terms of the GNU General Public License as published by\r\n * the Free Software Foundation; either version 3 of the License, or (at\r\n * your option) any later version.\r\n * \r\n * This program is distributed in the hope that it will be useful, but\r\n * WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n * General Public License for more details.\r\n * \r\n * You should have received a copy of the GNU General Public License\r\n * along with this program; if not, write to the Free Software\r\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r\n */\r\n\r\n#ifndef __GSL_VECTOR_INT_H__\r\n#define __GSL_VECTOR_INT_H__\r\n\r\n#if !defined( GSL_FUN )\r\n#  if !defined( GSL_DLL )\r\n#    define GSL_FUN extern\r\n#  elif defined( BUILD_GSL_DLL )\r\n#    define GSL_FUN extern __declspec(dllexport)\r\n#  else\r\n#    define GSL_FUN extern __declspec(dllimport)\r\n#  endif\r\n#endif\r\n\r\n#include <stdlib.h>\r\n#include <gsl/gsl_types.h>\r\n#include <gsl/gsl_errno.h>\r\n#include <gsl/gsl_inline.h>\r\n#include <gsl/gsl_check_range.h>\r\n#include <gsl/gsl_block_int.h>\r\n\r\n#undef __BEGIN_DECLS\r\n#undef __END_DECLS\r\n#ifdef __cplusplus\r\n# define __BEGIN_DECLS extern \"C\" {\r\n# define __END_DECLS }\r\n#else\r\n# define __BEGIN_DECLS /* empty */\r\n# define __END_DECLS /* empty */\r\n#endif\r\n\r\n__BEGIN_DECLS\r\n\r\ntypedef struct \r\n{\r\n  size_t size;\r\n  size_t stride;\r\n  int *data;\r\n  gsl_block_int *block;\r\n  int owner;\r\n} \r\ngsl_vector_int;\r\n\r\ntypedef struct\r\n{\r\n  gsl_vector_int vector;\r\n} _gsl_vector_int_view;\r\n\r\ntypedef _gsl_vector_int_view gsl_vector_int_view;\r\n\r\ntypedef struct\r\n{\r\n  gsl_vector_int vector;\r\n} _gsl_vector_int_const_view;\r\n\r\ntypedef const _gsl_vector_int_const_view gsl_vector_int_const_view;\r\n\r\n\r\n/* Allocation */\r\n\r\nGSL_FUN gsl_vector_int *gsl_vector_int_alloc (const size_t n);\r\nGSL_FUN gsl_vector_int *gsl_vector_int_calloc (const size_t n);\r\n\r\nGSL_FUN gsl_vector_int *gsl_vector_int_alloc_from_block (gsl_block_int * b,\r\n                                                     const size_t offset, \r\n                                                     const size_t n, \r\n                                                     const size_t stride);\r\n\r\nGSL_FUN gsl_vector_int *gsl_vector_int_alloc_from_vector (gsl_vector_int * v,\r\n                                                      const size_t offset, \r\n                                                      const size_t n, \r\n                                                      const size_t stride);\r\n\r\nGSL_FUN void gsl_vector_int_free (gsl_vector_int * v);\r\n\r\n/* Views */\r\n\r\nGSL_FUN _gsl_vector_int_view \r\ngsl_vector_int_view_array (int *v, size_t n);\r\n\r\nGSL_FUN _gsl_vector_int_view \r\ngsl_vector_int_view_array_with_stride (int *base,\r\n                                         size_t stride,\r\n                                         size_t n);\r\n\r\nGSL_FUN _gsl_vector_int_const_view \r\ngsl_vector_int_const_view_array (const int *v, size_t n);\r\n\r\nGSL_FUN _gsl_vector_int_const_view \r\ngsl_vector_int_const_view_array_with_stride (const int *base,\r\n                                               size_t stride,\r\n                                               size_t n);\r\n\r\nGSL_FUN _gsl_vector_int_view \r\ngsl_vector_int_subvector (gsl_vector_int *v, \r\n                            size_t i, \r\n                            size_t n);\r\n\r\nGSL_FUN _gsl_vector_int_view \r\ngsl_vector_int_subvector_with_stride (gsl_vector_int *v, \r\n                                        size_t i,\r\n                                        size_t stride,\r\n                                        size_t n);\r\n\r\nGSL_FUN _gsl_vector_int_const_view \r\ngsl_vector_int_const_subvector (const gsl_vector_int *v, \r\n                                  size_t i, \r\n                                  size_t n);\r\n\r\nGSL_FUN _gsl_vector_int_const_view \r\ngsl_vector_int_const_subvector_with_stride (const gsl_vector_int *v, \r\n                                              size_t i, \r\n                                              size_t stride,\r\n                                              size_t n);\r\n\r\n/* Operations */\r\n\r\nGSL_FUN void gsl_vector_int_set_zero (gsl_vector_int * v);\r\nGSL_FUN void gsl_vector_int_set_all (gsl_vector_int * v, int x);\r\nGSL_FUN int gsl_vector_int_set_basis (gsl_vector_int * v, size_t i);\r\n\r\nGSL_FUN int gsl_vector_int_fread (FILE * stream, gsl_vector_int * v);\r\nGSL_FUN int gsl_vector_int_fwrite (FILE * stream, const gsl_vector_int * v);\r\nGSL_FUN int gsl_vector_int_fscanf (FILE * stream, gsl_vector_int * v);\r\nGSL_FUN int gsl_vector_int_fprintf (FILE * stream, const gsl_vector_int * v,\r\n                              const char *format);\r\n\r\nGSL_FUN int gsl_vector_int_memcpy (gsl_vector_int * dest, const gsl_vector_int * src);\r\n\r\nGSL_FUN int gsl_vector_int_reverse (gsl_vector_int * v);\r\n\r\nGSL_FUN int gsl_vector_int_swap (gsl_vector_int * v, gsl_vector_int * w);\r\nGSL_FUN int gsl_vector_int_swap_elements (gsl_vector_int * v, const size_t i, const size_t j);\r\n\r\nGSL_FUN int gsl_vector_int_max (const gsl_vector_int * v);\r\nGSL_FUN int gsl_vector_int_min (const gsl_vector_int * v);\r\nGSL_FUN void gsl_vector_int_minmax (const gsl_vector_int * v, int * min_out, int * max_out);\r\n\r\nGSL_FUN size_t gsl_vector_int_max_index (const gsl_vector_int * v);\r\nGSL_FUN size_t gsl_vector_int_min_index (const gsl_vector_int * v);\r\nGSL_FUN void gsl_vector_int_minmax_index (const gsl_vector_int * v, size_t * imin, size_t * imax);\r\n\r\nGSL_FUN int gsl_vector_int_add (gsl_vector_int * a, const gsl_vector_int * b);\r\nGSL_FUN int gsl_vector_int_sub (gsl_vector_int * a, const gsl_vector_int * b);\r\nGSL_FUN int gsl_vector_int_mul (gsl_vector_int * a, const gsl_vector_int * b);\r\nGSL_FUN int gsl_vector_int_div (gsl_vector_int * a, const gsl_vector_int * b);\r\nGSL_FUN int gsl_vector_int_scale (gsl_vector_int * a, const int x);\r\nGSL_FUN int gsl_vector_int_add_constant (gsl_vector_int * a, const double x);\r\nGSL_FUN int gsl_vector_int_axpby (const int alpha, const gsl_vector_int * x, const int beta, gsl_vector_int * y);\r\nGSL_FUN int gsl_vector_int_sum (const gsl_vector_int * a);\r\n\r\nGSL_FUN int gsl_vector_int_equal (const gsl_vector_int * u, \r\n                            const gsl_vector_int * v);\r\n\r\nGSL_FUN int gsl_vector_int_isnull (const gsl_vector_int * v);\r\nGSL_FUN int gsl_vector_int_ispos (const gsl_vector_int * v);\r\nGSL_FUN int gsl_vector_int_isneg (const gsl_vector_int * v);\r\nGSL_FUN int gsl_vector_int_isnonneg (const gsl_vector_int * v);\r\n\r\nGSL_FUN INLINE_DECL int gsl_vector_int_get (const gsl_vector_int * v, const size_t i);\r\nGSL_FUN INLINE_DECL void gsl_vector_int_set (gsl_vector_int * v, const size_t i, int x);\r\nGSL_FUN INLINE_DECL int * gsl_vector_int_ptr (gsl_vector_int * v, const size_t i);\r\nGSL_FUN INLINE_DECL const int * gsl_vector_int_const_ptr (const gsl_vector_int * v, const size_t i);\r\n\r\n#ifdef HAVE_INLINE\r\n\r\nINLINE_FUN\r\nint\r\ngsl_vector_int_get (const gsl_vector_int * v, const size_t i)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(i >= v->size))\r\n    {\r\n      GSL_ERROR_VAL (\"index out of range\", GSL_EINVAL, 0);\r\n    }\r\n#endif\r\n  return v->data[i * v->stride];\r\n}\r\n\r\nINLINE_FUN\r\nvoid\r\ngsl_vector_int_set (gsl_vector_int * v, const size_t i, int x)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(i >= v->size))\r\n    {\r\n      GSL_ERROR_VOID (\"index out of range\", GSL_EINVAL);\r\n    }\r\n#endif\r\n  v->data[i * v->stride] = x;\r\n}\r\n\r\nINLINE_FUN\r\nint *\r\ngsl_vector_int_ptr (gsl_vector_int * v, const size_t i)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(i >= v->size))\r\n    {\r\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\r\n    }\r\n#endif\r\n  return (int *) (v->data + i * v->stride);\r\n}\r\n\r\nINLINE_FUN\r\nconst int *\r\ngsl_vector_int_const_ptr (const gsl_vector_int * v, const size_t i)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(i >= v->size))\r\n    {\r\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\r\n    }\r\n#endif\r\n  return (const int *) (v->data + i * v->stride);\r\n}\r\n#endif /* HAVE_INLINE */\r\n\r\n__END_DECLS\r\n\r\n#endif /* __GSL_VECTOR_INT_H__ */\r\n\r\n\r\n", "meta": {"hexsha": "c8bbcd3fbae68e1854a804ae793b14517dcdcd92", "size": 8205, "ext": "h", "lang": "C", "max_stars_repo_path": "vendor/gsl/gsl/gsl_vector_int.h", "max_stars_repo_name": "mgreter/astrometrylib", "max_stars_repo_head_hexsha": "ef4d4539a537ab49329b77648aac893d2b4ad318", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z", "max_issues_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_vector_int.h", "max_issues_repo_name": "zzpwahaha/VimbaCamJILA", "max_issues_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z", "max_forks_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_vector_int.h", "max_forks_repo_name": "zzpwahaha/VimbaCamJILA", "max_forks_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 33.7654320988, "max_line_length": 114, "alphanum_fraction": 0.658622791, "num_tokens": 2004, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658973632215985, "lm_q2_score": 0.03622005495467345, "lm_q1q2_score": 0.01327790039540788}}
{"text": "#pragma once\n\n#include <gsl\\gsl>\n#include <winrt\\Windows.Foundation.h>\n#include <d3d11.h>\n#include \"DrawableGameComponent.h\"\n#include \"MatrixHelper.h\"\n#include \"PointLight.h\"\n#include \"DepthMap.h\"\n#include \"Rectangle.h\"\n#include \"ShadowMappingMaterial.h\"\n#include \"RenderStateHelper.h\"\n\nnamespace DirectX\n{\n\tclass SpriteBatch;\n}\n\nnamespace Library\n{\n\tclass ProxyModel;\n\tclass RenderableFrustum;\n\tclass DepthMapMaterial;\n}\n\nnamespace Rendering\n{\n\tclass ShadowMappingDemo final : public Library::DrawableGameComponent\n\t{\n\tpublic:\n\t\tShadowMappingDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera);\n\t\tShadowMappingDemo(const ShadowMappingDemo&) = delete;\n\t\tShadowMappingDemo(ShadowMappingDemo&&) = default;\n\t\tShadowMappingDemo& operator=(const ShadowMappingDemo&) = default;\t\t\n\t\tShadowMappingDemo& operator=(ShadowMappingDemo&&) = default;\n\t\t~ShadowMappingDemo();\n\n\t\tShadowMappingDrawModes DrawMode() const;\n\t\tconst std::string& DrawModeString() const;\n\t\tvoid SetDrawMode(ShadowMappingDrawModes drawMode);\n\n\t\tfloat DepthBias() const;\n\t\tvoid SetDepthBias(float bias);\n\n\t\tfloat SlopeScaledDepthBias() const;\n\t\tvoid SetSlopeScaledDepthBias(float bias);\n\n\t\tfloat AmbientLightIntensity() const;\n\t\tvoid SetAmbientLightIntensity(float intensity);\n\n\t\tfloat PointLightIntensity() const;\n\t\tvoid SetPointLightIntensity(float intensity);\n\n\t\tfloat PointLightRadius() const;\n\t\tvoid SetPointLightRadius(float radius);\n\n\t\tconst Library::Camera& Projector() const;\n\t\tconst DirectX::XMFLOAT3& ProjectorPosition() const;\n\t\tconst DirectX::XMVECTOR ProjectorPositionVector() const;\n\t\tvoid SetProjectorPosition(const DirectX::XMFLOAT3& position);\n\t\tvoid SetProjectorPosition(DirectX::FXMVECTOR position);\n\t\tconst DirectX::XMFLOAT3& ProjectorDirection() const;\t\t\n\t\tvoid RotateProjector(const DirectX::XMFLOAT2& amount);\n\n\t\tvirtual void Initialize() override;\n\t\tvirtual void Update(const Library::GameTime& gameTime) override;\n\t\tvirtual void Draw(const Library::GameTime& gameTime) override;\n\n\tprivate:\n\t\tinline static const std::uint32_t ShadowMapWidth{ 1024 };\n\t\tinline static const std::uint32_t ShadowMapHeight{ 1024 };\n\t\tstatic inline const RECT ShadowMapDestinationRectangle{ 0, 512, 256, 768 };\n\t\n\t\tinline static DirectX::XMFLOAT4X4 mProjectedTextureScalingMatrix\n\t\t{\n\t\t\t0.5f,  0.0f, 0.0f, 0.0f,\n\t\t\t0.0f, -0.5f, 0.0f, 0.0f,\n\t\t\t0.0f,  0.0f, 1.0f, 0.0f,\n\t\t\t0.5f,  0.5f, 0.0f, 1.0f\n\t\t};\n\n\t\tvoid UpdateTransforms(ShadowMappingMaterial::VertexCBufferPerObject& transforms, DirectX::FXMMATRIX worldViewProjectionMatrix, DirectX::CXMMATRIX worldMatrix, DirectX::CXMMATRIX projectiveTextureMatrix);\n\t\tvoid UpdateDepthBiasRasterizerState();\n\n\t\tShadowMappingMaterial::VertexCBufferPerObject mPlaneTransforms;\n\t\tShadowMappingMaterial::VertexCBufferPerObject mTeapotTransforms;\n\t\tDirectX::XMFLOAT4X4 mPlaneWorldMatrix{ Library::MatrixHelper::Identity };\n\t\tDirectX::XMFLOAT4X4 mTeapotWorldMatrix{ Library::MatrixHelper::Identity };\n\t\t\n\t\tLibrary::PointLight mPointLight;\n\t\tLibrary::DepthMap mShadowMap;\n\t\tLibrary::RenderStateHelper mRenderStateHelper;\n\t\tstd::shared_ptr<ShadowMappingMaterial> mMaterial;\n\t\tstd::shared_ptr<Library::DepthMapMaterial> mDepthMapMaterial;\n\t\twinrt::com_ptr<ID3D11Buffer> mPlaneVertexBuffer;\n\t\twinrt::com_ptr<ID3D11Buffer> mTeapotVertexBuffer;\n\t\twinrt::com_ptr<ID3D11Buffer> mTeapotPositionOnlyVertexBuffer;\n\t\twinrt::com_ptr<ID3D11Buffer> mTeapotIndexBuffer;\n\t\tstd::uint32_t mPlaneVertexCount{ 0 };\t\t\n\t\tstd::uint32_t mTeapotIndexCount{ 0 };\n\t\tstd::unique_ptr<Library::ProxyModel> mProxyModel;\n\t\tstd::unique_ptr<Library::Camera> mProjector;\n\t\tstd::unique_ptr<Library::RenderableFrustum> mRenderableProjectorFrustum;\n\t\tstd::unique_ptr<DirectX::SpriteBatch> mSpriteBatch;\n\t\tbool mUpdateMaterial{ true };\n\t\tfloat mDepthBias{ 0.0f };\n\t\tfloat mSlopeScaledDepthBias{ 2.0f };\n\t\twinrt::com_ptr<ID3D11RasterizerState> mDepthBiasState;\n\t};\n}", "meta": {"hexsha": "63f474909faa0fbfa632cf7402793951a8a8ab73", "size": 3845, "ext": "h", "lang": "C", "max_stars_repo_path": "source/8.2_Shadow_Mapping/ShadowMappingDemo.h", "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/8.2_Shadow_Mapping/ShadowMappingDemo.h", "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/8.2_Shadow_Mapping/ShadowMappingDemo.h", "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9545454545, "max_line_length": 205, "alphanum_fraction": 0.7828348505, "num_tokens": 1072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.026759285125814606, "lm_q1q2_score": 0.013275116231969582}}
{"text": "/* matrix/gsl_matrix_double.h\r\n * \r\n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\r\n * \r\n * This program is free software; you can redistribute it and/or modify\r\n * it under the terms of the GNU General Public License as published by\r\n * the Free Software Foundation; either version 3 of the License, or (at\r\n * your option) any later version.\r\n * \r\n * This program is distributed in the hope that it will be useful, but\r\n * WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n * General Public License for more details.\r\n * \r\n * You should have received a copy of the GNU General Public License\r\n * along with this program; if not, write to the Free Software\r\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r\n */\r\n\r\n#ifndef __GSL_MATRIX_DOUBLE_H__\r\n#define __GSL_MATRIX_DOUBLE_H__\r\n\r\n#if !defined( GSL_FUN )\r\n#  if !defined( GSL_DLL )\r\n#    define GSL_FUN extern\r\n#  elif defined( BUILD_GSL_DLL )\r\n#    define GSL_FUN extern __declspec(dllexport)\r\n#  else\r\n#    define GSL_FUN extern __declspec(dllimport)\r\n#  endif\r\n#endif\r\n\r\n#include <stdlib.h>\r\n#include <gsl/gsl_types.h>\r\n#include <gsl/gsl_errno.h>\r\n#include <gsl/gsl_inline.h>\r\n#include <gsl/gsl_check_range.h>\r\n#include <gsl/gsl_vector_double.h>\r\n#include <gsl/gsl_blas_types.h>\r\n\r\n#undef __BEGIN_DECLS\r\n#undef __END_DECLS\r\n#ifdef __cplusplus\r\n# define __BEGIN_DECLS extern \"C\" {\r\n# define __END_DECLS }\r\n#else\r\n# define __BEGIN_DECLS /* empty */\r\n# define __END_DECLS /* empty */\r\n#endif\r\n\r\n__BEGIN_DECLS\r\n\r\ntypedef struct \r\n{\r\n  size_t size1;\r\n  size_t size2;\r\n  size_t tda;\r\n  double * data;\r\n  gsl_block * block;\r\n  int owner;\r\n} gsl_matrix;\r\n\r\ntypedef struct\r\n{\r\n  gsl_matrix matrix;\r\n} _gsl_matrix_view;\r\n\r\ntypedef _gsl_matrix_view gsl_matrix_view;\r\n\r\ntypedef struct\r\n{\r\n  gsl_matrix matrix;\r\n} _gsl_matrix_const_view;\r\n\r\ntypedef const _gsl_matrix_const_view gsl_matrix_const_view;\r\n\r\n/* Allocation */\r\n\r\nGSL_FUN gsl_matrix * \r\ngsl_matrix_alloc (const size_t n1, const size_t n2);\r\n\r\nGSL_FUN gsl_matrix * \r\ngsl_matrix_calloc (const size_t n1, const size_t n2);\r\n\r\nGSL_FUN gsl_matrix * \r\ngsl_matrix_alloc_from_block (gsl_block * b, \r\n                                   const size_t offset, \r\n                                   const size_t n1, \r\n                                   const size_t n2, \r\n                                   const size_t d2);\r\n\r\nGSL_FUN gsl_matrix * \r\ngsl_matrix_alloc_from_matrix (gsl_matrix * m,\r\n                                    const size_t k1, \r\n                                    const size_t k2,\r\n                                    const size_t n1, \r\n                                    const size_t n2);\r\n\r\nGSL_FUN gsl_vector * \r\ngsl_vector_alloc_row_from_matrix (gsl_matrix * m,\r\n                                        const size_t i);\r\n\r\nGSL_FUN gsl_vector * \r\ngsl_vector_alloc_col_from_matrix (gsl_matrix * m,\r\n                                        const size_t j);\r\n\r\nGSL_FUN void gsl_matrix_free (gsl_matrix * m);\r\n\r\n/* Views */\r\n\r\nGSL_FUN _gsl_matrix_view \r\ngsl_matrix_submatrix (gsl_matrix * m, \r\n                            const size_t i, const size_t j, \r\n                            const size_t n1, const size_t n2);\r\n\r\nGSL_FUN _gsl_vector_view \r\ngsl_matrix_row (gsl_matrix * m, const size_t i);\r\n\r\nGSL_FUN _gsl_vector_view \r\ngsl_matrix_column (gsl_matrix * m, const size_t j);\r\n\r\nGSL_FUN _gsl_vector_view \r\ngsl_matrix_diagonal (gsl_matrix * m);\r\n\r\nGSL_FUN _gsl_vector_view \r\ngsl_matrix_subdiagonal (gsl_matrix * m, const size_t k);\r\n\r\nGSL_FUN _gsl_vector_view \r\ngsl_matrix_superdiagonal (gsl_matrix * m, const size_t k);\r\n\r\nGSL_FUN _gsl_vector_view\r\ngsl_matrix_subrow (gsl_matrix * m, const size_t i,\r\n                         const size_t offset, const size_t n);\r\n\r\nGSL_FUN _gsl_vector_view\r\ngsl_matrix_subcolumn (gsl_matrix * m, const size_t j,\r\n                            const size_t offset, const size_t n);\r\n\r\nGSL_FUN _gsl_matrix_view\r\ngsl_matrix_view_array (double * base,\r\n                             const size_t n1, \r\n                             const size_t n2);\r\n\r\nGSL_FUN _gsl_matrix_view\r\ngsl_matrix_view_array_with_tda (double * base, \r\n                                      const size_t n1, \r\n                                      const size_t n2,\r\n                                      const size_t tda);\r\n\r\n\r\nGSL_FUN _gsl_matrix_view\r\ngsl_matrix_view_vector (gsl_vector * v,\r\n                              const size_t n1, \r\n                              const size_t n2);\r\n\r\nGSL_FUN _gsl_matrix_view\r\ngsl_matrix_view_vector_with_tda (gsl_vector * v,\r\n                                       const size_t n1, \r\n                                       const size_t n2,\r\n                                       const size_t tda);\r\n\r\n\r\nGSL_FUN _gsl_matrix_const_view \r\ngsl_matrix_const_submatrix (const gsl_matrix * m, \r\n                                  const size_t i, const size_t j, \r\n                                  const size_t n1, const size_t n2);\r\n\r\nGSL_FUN _gsl_vector_const_view \r\ngsl_matrix_const_row (const gsl_matrix * m, \r\n                            const size_t i);\r\n\r\nGSL_FUN _gsl_vector_const_view \r\ngsl_matrix_const_column (const gsl_matrix * m, \r\n                               const size_t j);\r\n\r\nGSL_FUN _gsl_vector_const_view\r\ngsl_matrix_const_diagonal (const gsl_matrix * m);\r\n\r\nGSL_FUN _gsl_vector_const_view \r\ngsl_matrix_const_subdiagonal (const gsl_matrix * m, \r\n                                    const size_t k);\r\n\r\nGSL_FUN _gsl_vector_const_view \r\ngsl_matrix_const_superdiagonal (const gsl_matrix * m, \r\n                                      const size_t k);\r\n\r\nGSL_FUN _gsl_vector_const_view\r\ngsl_matrix_const_subrow (const gsl_matrix * m, const size_t i,\r\n                               const size_t offset, const size_t n);\r\n\r\nGSL_FUN _gsl_vector_const_view\r\ngsl_matrix_const_subcolumn (const gsl_matrix * m, const size_t j,\r\n                                  const size_t offset, const size_t n);\r\n\r\nGSL_FUN _gsl_matrix_const_view\r\ngsl_matrix_const_view_array (const double * base,\r\n                                   const size_t n1, \r\n                                   const size_t n2);\r\n\r\nGSL_FUN _gsl_matrix_const_view\r\ngsl_matrix_const_view_array_with_tda (const double * base, \r\n                                            const size_t n1, \r\n                                            const size_t n2,\r\n                                            const size_t tda);\r\n\r\nGSL_FUN _gsl_matrix_const_view\r\ngsl_matrix_const_view_vector (const gsl_vector * v,\r\n                                    const size_t n1, \r\n                                    const size_t n2);\r\n\r\nGSL_FUN _gsl_matrix_const_view\r\ngsl_matrix_const_view_vector_with_tda (const gsl_vector * v,\r\n                                             const size_t n1, \r\n                                             const size_t n2,\r\n                                             const size_t tda);\r\n\r\n/* Operations */\r\n\r\nGSL_FUN void gsl_matrix_set_zero (gsl_matrix * m);\r\nGSL_FUN void gsl_matrix_set_identity (gsl_matrix * m);\r\nGSL_FUN void gsl_matrix_set_all (gsl_matrix * m, double x);\r\n\r\nGSL_FUN int gsl_matrix_fread (FILE * stream, gsl_matrix * m) ;\r\nGSL_FUN int gsl_matrix_fwrite (FILE * stream, const gsl_matrix * m) ;\r\nGSL_FUN int gsl_matrix_fscanf (FILE * stream, gsl_matrix * m);\r\nGSL_FUN int gsl_matrix_fprintf (FILE * stream, const gsl_matrix * m, const char * format);\r\n \r\nGSL_FUN int gsl_matrix_memcpy(gsl_matrix * dest, const gsl_matrix * src);\r\nGSL_FUN int gsl_matrix_swap(gsl_matrix * m1, gsl_matrix * m2);\r\nGSL_FUN int gsl_matrix_tricpy(CBLAS_UPLO_t Uplo, CBLAS_DIAG_t Diag, gsl_matrix * dest, const gsl_matrix * src);\r\n\r\nGSL_FUN int gsl_matrix_swap_rows(gsl_matrix * m, const size_t i, const size_t j);\r\nGSL_FUN int gsl_matrix_swap_columns(gsl_matrix * m, const size_t i, const size_t j);\r\nGSL_FUN int gsl_matrix_swap_rowcol(gsl_matrix * m, const size_t i, const size_t j);\r\nGSL_FUN int gsl_matrix_transpose (gsl_matrix * m);\r\nGSL_FUN int gsl_matrix_transpose_memcpy (gsl_matrix * dest, const gsl_matrix * src);\r\nGSL_FUN int gsl_matrix_transpose_tricpy (CBLAS_UPLO_t Uplo_src, CBLAS_DIAG_t Diag, gsl_matrix * dest, const gsl_matrix * src);\r\n\r\nGSL_FUN double gsl_matrix_max (const gsl_matrix * m);\r\nGSL_FUN double gsl_matrix_min (const gsl_matrix * m);\r\nGSL_FUN void gsl_matrix_minmax (const gsl_matrix * m, double * min_out, double * max_out);\r\n\r\nGSL_FUN void gsl_matrix_max_index (const gsl_matrix * m, size_t * imax, size_t *jmax);\r\nGSL_FUN void gsl_matrix_min_index (const gsl_matrix * m, size_t * imin, size_t *jmin);\r\nGSL_FUN void gsl_matrix_minmax_index (const gsl_matrix * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);\r\n\r\nGSL_FUN int gsl_matrix_equal (const gsl_matrix * a, const gsl_matrix * b);\r\n\r\nGSL_FUN int gsl_matrix_isnull (const gsl_matrix * m);\r\nGSL_FUN int gsl_matrix_ispos (const gsl_matrix * m);\r\nGSL_FUN int gsl_matrix_isneg (const gsl_matrix * m);\r\nGSL_FUN int gsl_matrix_isnonneg (const gsl_matrix * m);\r\n\r\nGSL_FUN double gsl_matrix_norm1 (const gsl_matrix * m);\r\n\r\nGSL_FUN int gsl_matrix_add (gsl_matrix * a, const gsl_matrix * b);\r\nGSL_FUN int gsl_matrix_sub (gsl_matrix * a, const gsl_matrix * b);\r\nGSL_FUN int gsl_matrix_mul_elements (gsl_matrix * a, const gsl_matrix * b);\r\nGSL_FUN int gsl_matrix_div_elements (gsl_matrix * a, const gsl_matrix * b);\r\nGSL_FUN int gsl_matrix_scale (gsl_matrix * a, const double x);\r\nGSL_FUN int gsl_matrix_scale_rows (gsl_matrix * a, const gsl_vector * x);\r\nGSL_FUN int gsl_matrix_scale_columns (gsl_matrix * a, const gsl_vector * x);\r\nGSL_FUN int gsl_matrix_add_constant (gsl_matrix * a, const double x);\r\nGSL_FUN int gsl_matrix_add_diagonal (gsl_matrix * a, const double x);\r\n\r\n/***********************************************************************/\r\n/* The functions below are obsolete                                    */\r\n/***********************************************************************/\r\nGSL_FUN int gsl_matrix_get_row(gsl_vector * v, const gsl_matrix * m, const size_t i);\r\nGSL_FUN int gsl_matrix_get_col(gsl_vector * v, const gsl_matrix * m, const size_t j);\r\nGSL_FUN int gsl_matrix_set_row(gsl_matrix * m, const size_t i, const gsl_vector * v);\r\nGSL_FUN int gsl_matrix_set_col(gsl_matrix * m, const size_t j, const gsl_vector * v);\r\n/***********************************************************************/\r\n\r\n/* inline functions if you are using GCC */\r\n\r\nGSL_FUN INLINE_DECL double   gsl_matrix_get(const gsl_matrix * m, const size_t i, const size_t j);\r\nGSL_FUN INLINE_DECL void    gsl_matrix_set(gsl_matrix * m, const size_t i, const size_t j, const double x);\r\nGSL_FUN INLINE_DECL double * gsl_matrix_ptr(gsl_matrix * m, const size_t i, const size_t j);\r\nGSL_FUN INLINE_DECL const double * gsl_matrix_const_ptr(const gsl_matrix * m, const size_t i, const size_t j);\r\n\r\n#ifdef HAVE_INLINE\r\nINLINE_FUN \r\ndouble\r\ngsl_matrix_get(const gsl_matrix * m, const size_t i, const size_t j)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(1)) \r\n    {\r\n      if (i >= m->size1)\r\n        {\r\n          GSL_ERROR_VAL(\"first index out of range\", GSL_EINVAL, 0) ;\r\n        }\r\n      else if (j >= m->size2)\r\n        {\r\n          GSL_ERROR_VAL(\"second index out of range\", GSL_EINVAL, 0) ;\r\n        }\r\n    }\r\n#endif\r\n  return m->data[i * m->tda + j] ;\r\n} \r\n\r\nINLINE_FUN \r\nvoid\r\ngsl_matrix_set(gsl_matrix * m, const size_t i, const size_t j, const double x)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(1)) \r\n    {\r\n      if (i >= m->size1)\r\n        {\r\n          GSL_ERROR_VOID(\"first index out of range\", GSL_EINVAL) ;\r\n        }\r\n      else if (j >= m->size2)\r\n        {\r\n          GSL_ERROR_VOID(\"second index out of range\", GSL_EINVAL) ;\r\n        }\r\n    }\r\n#endif\r\n  m->data[i * m->tda + j] = x ;\r\n}\r\n\r\nINLINE_FUN \r\ndouble *\r\ngsl_matrix_ptr(gsl_matrix * m, const size_t i, const size_t j)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(1)) \r\n    {\r\n      if (i >= m->size1)\r\n        {\r\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\r\n        }\r\n      else if (j >= m->size2)\r\n        {\r\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\r\n        }\r\n    }\r\n#endif\r\n  return (double *) (m->data + (i * m->tda + j)) ;\r\n} \r\n\r\nINLINE_FUN \r\nconst double *\r\ngsl_matrix_const_ptr(const gsl_matrix * m, const size_t i, const size_t j)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(1)) \r\n    {\r\n      if (i >= m->size1)\r\n        {\r\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\r\n        }\r\n      else if (j >= m->size2)\r\n        {\r\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\r\n        }\r\n    }\r\n#endif\r\n  return (const double *) (m->data + (i * m->tda + j)) ;\r\n} \r\n\r\n#endif\r\n\r\n__END_DECLS\r\n\r\n#endif /* __GSL_MATRIX_DOUBLE_H__ */\r\n", "meta": {"hexsha": "7f93ec322c940647c3f630c4b79a0a7096c138f0", "size": 12783, "ext": "h", "lang": "C", "max_stars_repo_path": "vendor/gsl/gsl/gsl_matrix_double.h", "max_stars_repo_name": "mgreter/astrometrylib", "max_stars_repo_head_hexsha": "ef4d4539a537ab49329b77648aac893d2b4ad318", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z", "max_issues_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_matrix_double.h", "max_issues_repo_name": "zzpwahaha/VimbaCamJILA", "max_issues_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z", "max_forks_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_matrix_double.h", "max_forks_repo_name": "zzpwahaha/VimbaCamJILA", "max_forks_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 34.7364130435, "max_line_length": 127, "alphanum_fraction": 0.6208245326, "num_tokens": 3150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33458942798284697, "lm_q2_score": 0.039638842362666085, "lm_q1q2_score": 0.013262737592026688}}
{"text": "/*\n\nExcited States software: KGS\nContributors: See CONTRIBUTORS.txt\nContact: kgs-contact@simtk.org\n\nCopyright (C) 2009-2017 Stanford University\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\n\nThis entire text, including the above copyright notice and this permission notice\nshall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS, CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\nOTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\nIN THE SOFTWARE.\n\n*/\n\n\n#ifndef KGS_DIRECTION_H\n#define KGS_DIRECTION_H\n\n#include <gsl/gsl_vector.h>\n\n#include \"core/Configuration.h\"\n\n/**\n * Implementing sub-classes specify different methods of computing gradients.\n */\nclass Direction {\n public:\n  virtual ~Direction() = 0;\n\n  /**\n   * Compute a gradient for the configuration `conf` and store the result in `ret`.\n   * A target configuration can be specified if the implementing subclass performs directed\n   * gradients. If not the target will be ignored.\n   *\n   * Any values stored in the `ret` vector will be overwritten by this function so there is\n   * no need to reset it to zero before use.\n   *\n   * \\pre  { `conf` and `ret` are both non-nullptr }\n   * \\post { All values in `ret` are guaranteed to be in the the range -\u03c0 to \u03c0. }\n   */\n  void gradient(Configuration* conf, Configuration* target, gsl_vector* ret);\n\n protected:\n  virtual void computeGradient(Configuration* conf, Configuration* target, gsl_vector* ret) = 0;\n\n};\n\n\n#endif //KGS_DIRECTION_H\n", "meta": {"hexsha": "ce9aa32dc18bf6aecfc84662966913094325c96e", "size": 2209, "ext": "h", "lang": "C", "max_stars_repo_path": "src/directions/Direction.h", "max_stars_repo_name": "XiyuChenFAU/kgs_vibration_entropy", "max_stars_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-23T18:26:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-23T18:26:14.000Z", "max_issues_repo_path": "src/directions/Direction.h", "max_issues_repo_name": "XiyuChenFAU/kgs_vibration_entropy", "max_issues_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2017-01-26T19:54:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-06T16:06:30.000Z", "max_forks_repo_path": "src/directions/Direction.h", "max_forks_repo_name": "XiyuChenFAU/kgs_vibration_entropy", "max_forks_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.515625, "max_line_length": 96, "alphanum_fraction": 0.7627885921, "num_tokens": 488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.02843603520617649, "lm_q1q2_score": 0.013219957450980448}}
{"text": "#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include <php.h>\n#include <cblas.h>\n#include \"kernel/operators.h\"\n\n/**\n * Sets the number of threads to use when parallel processesing.\n * \n * @param return_value\n * @param threads\n */\nvoid tensor_set_num_threads(zval * return_value, zval * threads)\n{\n    int n = zephir_get_intval(threads);\n    \n    openblas_set_num_threads(n);\n\n    RETURN_TRUE;\n}\n\n/**\n * Return the number of threads to use when parallel processesing.\n * \n * @param return_value\n */\nvoid tensor_get_num_threads(zval * return_value)\n{\n    long threads = openblas_get_num_threads();\n\n    RETURN_LONG(threads);\n}\n", "meta": {"hexsha": "d4be6ae2b1cf6e48d1663e0c6c311317a5d0b67f", "size": 629, "ext": "c", "lang": "C", "max_stars_repo_path": "ext/include/settings.c", "max_stars_repo_name": "cmb69/Tensor", "max_stars_repo_head_hexsha": "1f1e7611dfa720eed73b7cf4dcf21a2e6238b0f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 118.0, "max_stars_repo_stars_event_min_datetime": "2018-10-21T06:54:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T13:23:06.000Z", "max_issues_repo_path": "ext/include/settings.c", "max_issues_repo_name": "cmb69/Tensor", "max_issues_repo_head_hexsha": "1f1e7611dfa720eed73b7cf4dcf21a2e6238b0f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2020-07-04T07:40:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-28T03:36:39.000Z", "max_forks_repo_path": "ext/include/settings.c", "max_forks_repo_name": "cmb69/Tensor", "max_forks_repo_head_hexsha": "1f1e7611dfa720eed73b7cf4dcf21a2e6238b0f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2018-12-16T11:11:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T08:34:22.000Z", "avg_line_length": 17.9714285714, "max_line_length": 66, "alphanum_fraction": 0.7090620032, "num_tokens": 152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3380771241500058, "lm_q2_score": 0.039048289790720114, "lm_q1q2_score": 0.013201333515422688}}
{"text": "#include <petsc.h>\n#include \"quantum_gates.h\"\n\nvoid projectq_qasm_read(char[],PetscInt*,circuit*);\nvoid projectq_vqe_get_expectation(char[],Vec,PetscScalar*);\nvoid _projectq_qasm_add_gate(char*,circuit*,PetscReal);\nvoid projectq_vqe_get_expectation_encoded(char[],Vec,PetscScalar*,PetscInt,...);\nvoid qiskit_qasm_read(char[],PetscInt*,circuit*);\nvoid _qiskit_qasm_add_gate(char*,circuit*,PetscReal);\nvoid qiskit_vqe_get_expectation(char[],Vec,PetscScalar*);\nvoid quil_read(char[],PetscInt*,circuit*);\nvoid _quil_add_gate(char*,circuit*,PetscReal);\nvoid _quil_get_angle_pi(char[],PetscReal*);\n", "meta": {"hexsha": "b6bb7a5232e1c1c3e777fa521bb86717bf60461e", "size": 592, "ext": "h", "lang": "C", "max_stars_repo_path": "src/qasm_parser.h", "max_stars_repo_name": "sgulania/QuaC", "max_stars_repo_head_hexsha": "2b47b378c6b5b823a094e9af79f7cb8eb39dd337", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2017-06-18T02:11:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-28T10:27:57.000Z", "max_issues_repo_path": "src/qasm_parser.h", "max_issues_repo_name": "sgulania/QuaC", "max_issues_repo_head_hexsha": "2b47b378c6b5b823a094e9af79f7cb8eb39dd337", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-07-17T15:16:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-03T14:21:56.000Z", "max_forks_repo_path": "src/qasm_parser.h", "max_forks_repo_name": "sgulania/QuaC", "max_forks_repo_head_hexsha": "2b47b378c6b5b823a094e9af79f7cb8eb39dd337", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2017-03-13T15:03:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T20:07:22.000Z", "avg_line_length": 42.2857142857, "max_line_length": 80, "alphanum_fraction": 0.8023648649, "num_tokens": 173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.02887090997526182, "lm_q1q2_score": 0.013197952997913357}}
{"text": "#ifdef FUTILITY_HAVE_PETSC\n#include <petsc.h>\n#include <petscsys.h>\n#include <petscfix.h>\n#include <petscksp.h>\n#if ((PETSC_VERSION_MAJOR<=3) && (PETSC_VERSION_MINOR<=5))\n#include <petsc-private/fortranimpl.h>\n#include <petsc-private/pcimpl.h>\n#else\n#include <petsc/private/fortranimpl.h>\n#include <petsc/private/pcmgimpl.h>\n#endif\n\n#ifdef PETSC_USE_POINTER_CONVERSION\nextern void *PetscToPointer(void*);\nextern int PetscFromPointer(void *); \nextern void PetscRmPointer(void*);\n#else\n#define PetscToPointer(a) (*(PetscFortranAddr *)(a))\n#define PetscFromPointer(a) (PetscFortranAddr)(a)\n#define PetscRmPointer(a)\n#endif\n\n#if ((PETSC_VERSION_MAJOR<=3) && (PETSC_VERSION_MINOR<=5))\n//This is taken from petsc-3.5/src/ksp/pc/impls/mg/mgimpl.h\n//There is no version of petsc/private/pcmgimpl.h that is includable in older\n//  versions of PETSc, so we just have to manually redefine the typdefs defined\n//  in mgimpl.h here.\ntypedef struct {\n  PetscInt cycles;                             /* Type of cycle to run: 1 V 2 W */\n  PetscInt level;                              /* level = 0 coarsest level */\n  PetscInt levels;                             /* number of active levels used */\n  Vec      b;                                  /* Right hand side */\n  Vec      x;                                  /* Solution */\n  Vec      r;                                  /* Residual */\n\n  PetscErrorCode (*residual)(Mat,Vec,Vec,Vec);\n\n  Mat           A;                             /* matrix used in forming residual*/\n  KSP           smoothd;                       /* pre smoother */\n  KSP           smoothu;                       /* post smoother */\n  Mat           interpolate;\n  Mat           restrct;                       /* restrict is a reserved word in C99 and on Cray */\n  Vec           rscale;                        /* scaling of restriction matrix */\n  PetscLogEvent eventsmoothsetup;              /* if logging times for each level */\n  PetscLogEvent eventsmoothsolve;\n  PetscLogEvent eventresidual;\n  PetscLogEvent eventinterprestrict;\n} PC_MG_Levels;\ntypedef struct {\n  PCMGType  am;                               /* Multiplicative, additive or full */\n  PetscInt  cyclesperpcapply;                 /* Number of cycles to use in each PCApply(), multiplicative only*/\n  PetscInt  maxlevels;                        /* total number of levels allocated */\n  PetscInt  galerkin;                         /* use Galerkin process to compute coarser matrices, 0=no, 1=yes, 2=yes but computed externally */\n  PetscBool usedmfornumberoflevels;           /* sets the number of levels by getting this information out of the DM */\n\n  PetscInt     nlevels;\n  PC_MG_Levels **levels;\n  PetscInt     default_smoothu;               /* number of smooths per level if not over-ridden */\n  PetscInt     default_smoothd;               /*  with calls to KSPSetTolerances() */\n  PetscReal    rtol,abstol,dtol,ttol;         /* tolerances for when running with PCApplyRichardson_MG */\n\n  void          *innerctx;                   /* optional data for preconditioner, like PCEXOTIC that inherits off of PCMG */\n  PetscLogStage stageApply;\n} PC_MG;\n#endif\n\n#ifdef PETSC_HAVE_FORTRAN_CAPS\n#define pcmgsoftreset_ PCMGSOFTRESET\n#elif !defined(PETSC_HAVE_FORTRAN_UNDERSCORE) && !defined(FORTRANDOUBLEUNDERSCORE)\n#define pcmgsoftreset_ pcmgsoftreset\n#endif\n\n#undef __FUNCT__\n#define __FUNCT__ \"PCMGSoftReset\"\n\nPetscErrorCode PCMGSoftReset(PC pc)\n{\n  PC_MG          *mg        = (PC_MG*)pc->data;\n  PC_MG_Levels   **mglevels = mg->levels;\n  PetscErrorCode ierr;\n  PetscInt       i,n;\n\n  PetscFunctionBegin;\n  if (mglevels) {\n    n = mglevels[0]->levels;\n    for (i=0; i<n; i++) {\n      ierr = MatDestroy(&mglevels[i]->A);CHKERRQ(ierr);\n      if (mglevels[i]->smoothd != mglevels[i]->smoothu) {\n        ierr = KSPReset(mglevels[i]->smoothd);CHKERRQ(ierr);\n      }\n      ierr = KSPReset(mglevels[i]->smoothu);CHKERRQ(ierr);\n    }\n  }\n  //This may not work if DM's are used to define the MG structure.\n  pc->setupcalled = PETSC_FALSE;\n  PetscFunctionReturn(0);\n}\n\nPETSC_EXTERN void PETSC_STDCALL  pcmgsoftreset_(PC pc, int *__ierr ){\n*__ierr = PCMGSoftReset(\n  (PC)PetscToPointer((pc) ));\n}\n#endif\n", "meta": {"hexsha": "cc34f4cd4cf3c3712fde81126549092c0a72dce6", "size": 4164, "ext": "c", "lang": "C", "max_stars_repo_path": "src/pcmg_supplement.c", "max_stars_repo_name": "picmc/Futility", "max_stars_repo_head_hexsha": "158950c2c3aceffedf547ed4ea777e023035ca6e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 36.0, "max_stars_repo_stars_event_min_datetime": "2017-02-26T01:17:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-02T07:15:07.000Z", "max_issues_repo_path": "src/pcmg_supplement.c", "max_issues_repo_name": "picmc/Futility", "max_issues_repo_head_hexsha": "158950c2c3aceffedf547ed4ea777e023035ca6e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 183.0, "max_issues_repo_issues_event_min_datetime": "2017-03-30T20:14:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-03T21:34:06.000Z", "max_forks_repo_path": "src/pcmg_supplement.c", "max_forks_repo_name": "wgurecky/Futility", "max_forks_repo_head_hexsha": "cd7831395c7c56adcbbc5be38773d2e850c6b5b6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2017-06-29T17:13:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T08:05:59.000Z", "avg_line_length": 39.6571428571, "max_line_length": 144, "alphanum_fraction": 0.6229586936, "num_tokens": 1061, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.411110869232168, "lm_q2_score": 0.03210070428634845, "lm_q1q2_score": 0.013196948442125494}}
{"text": "//           $Id: pfc_libraries.h 37984 2018-10-27 15:50:30Z p20068 $\n//          $URL: https://svn01.fh-hagenberg.at/bin/cepheiden/vocational/teaching/ESD/SPS3/2018-WS/ILV/src/Snippets/bitmap-gsl/pfc_libraries.h $\n//     $Revision: 37984 $\n//         $Date: 2018-10-27 17:50:30 +0200 (Sa., 27 Okt 2018) $\n//       $Author: p20068 $\n//\n//       Creator: Peter Kulczycki (peter.kulczycki<AT>fh-hagenberg.at)\n// Creation Date:\n//     Copyright: (c) 2018 Peter Kulczycki (peter.kulczycki<AT>fh-hagenberg.at)\n//\n//       License: This document contains proprietary information belonging to\n//                University of Applied Sciences Upper Austria, Campus\n//                Hagenberg. It is distributed under the Boost Software License,\n//                Version 1.0 (see http://www.boost.org/LICENSE_1_0.txt).\n//\n//    Annotation: This file is part of the code snippets handed out during one\n//                of my HPC lessons held at the University of Applied Sciences\n//                Upper Austria, Campus Hagenberg.\n\n#pragma once\n\n#include \"./pfc_macros.h\"\n\n// -------------------------------------------------------------------------------------------------\n\n#if defined PFC_DETECTED_COMPILER_NVCC\n   #define PFC_DO_NOT_USE_BOOST_UNITS\n   #define PFC_DO_NOT_USE_GSL\n   #define PFC_DO_NOT_USE_VLD\n   #define PFC_DO_NOT_USE_WINDOWS\n#endif\n\n// -------------------------------------------------------------------------------------------------\n\n#undef PFC_HAVE_VLD\n#undef PFC_VLD_INCLUDED\n\n#if __has_include (<vld.h>) && !defined PFC_DO_NOT_USE_VLD   // Visual Leak Detector (https://kinddragon.github.io/vld)\n   #include <vld.h>\n\n   #define PFC_HAVE_VLD\n   #define PFC_VLD_INCLUDED\n\n   #pragma message (\"PFC: using 'Visual Leak Detector'\")\n#else\n   #pragma message (\"PFC: not using 'Visual Leak Detector'\")\n#endif\n\n// -------------------------------------------------------------------------------------------------\n\n#undef PFC_HAVE_GSL\n#undef PFC_GSL_INCLUDED\n\n#if __has_include (<gsl/gsl>) && !defined PFC_DO_NOT_USE_GSL   // Guideline Support Library (https://github.com/Microsoft/GSL)\n   #include <gsl/gsl>\n\n   #define PFC_HAVE_GSL\n   #define PFC_GSL_INCLUDED\n\n   #pragma message (\"PFC: using 'Guideline Support Library'\")\n#else\n   #pragma message (\"PFC: not using 'Guideline Support Library'\")\n#endif\n\n// -------------------------------------------------------------------------------------------------\n\n#undef PFC_HAVE_BOOST_UNITS\n#undef PFC_BOOST_UNITS_INCLUDED\n\n#if __has_include (<boost/units/io.hpp>)\n#if __has_include (<boost/units/systems/si/length.hpp>)\n#if __has_include (<boost/units/systems/si/prefixes.hpp>) && !defined PFC_DO_NOT_USE_BOOST_UNITS\n   #include <boost/units/io.hpp>                    // http://www.boost.org\n   #include <boost/units/systems/si/length.hpp>     // https://sourceforge.net/projects/boost/files/boost-binaries\n   #include <boost/units/systems/si/prefixes.hpp>   //\n\n   #define PFC_HAVE_BOOST_UNITS\n   #define PFC_BOOST_UNITS_INCLUDED\n\n   #pragma message (\"PFC: using 'Boost.Units'\")\n#else\n   #pragma message (\"PFC: not using 'Boost.Units'\")\n#endif\n#endif\n#endif\n\n// -------------------------------------------------------------------------------------------------\n\n#undef PFC_HAVE_WINDOWS\n#undef PFC_WINDOWS_INCLUDED\n\n#if __has_include (<windows.h>) && !defined PFC_DO_NOT_USE_WINDOWS\n   #undef  NOMINMAX\n   #define NOMINMAX\n\n   #undef  STRICT\n   #define STRICT\n\n   #undef  VC_EXTRALEAN\n   #define VC_EXTRALEAN\n\n   #undef  WIN32_LEAN_AND_MEAN\n   #define WIN32_LEAN_AND_MEAN\n\n   #include <windows.h>\n\n   #define PFC_HAVE_WINDOWS\n   #define PFC_WINDOWS_INCLUDED\n\n   #pragma message (\"PFC: using 'windows.h'\")\n#else\n   #pragma message (\"PFC: not using 'windows.h'\")\n#endif\n", "meta": {"hexsha": "a6dd381d444d64d59c1cc0906a7416646608e651", "size": 3720, "ext": "h", "lang": "C", "max_stars_repo_path": "FractalCudaVersions/pfc/pfc_libraries.h", "max_stars_repo_name": "MMayr96/MandelbrotCuda", "max_stars_repo_head_hexsha": "86abf791cd1df1e51ed7790e3f9c52fbce7990e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FractalCudaVersions/pfc/pfc_libraries.h", "max_issues_repo_name": "MMayr96/MandelbrotCuda", "max_issues_repo_head_hexsha": "86abf791cd1df1e51ed7790e3f9c52fbce7990e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FractalCudaVersions/pfc/pfc_libraries.h", "max_forks_repo_name": "MMayr96/MandelbrotCuda", "max_forks_repo_head_hexsha": "86abf791cd1df1e51ed7790e3f9c52fbce7990e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6315789474, "max_line_length": 144, "alphanum_fraction": 0.6067204301, "num_tokens": 943, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20689404881588808, "lm_q2_score": 0.06371498936282499, "lm_q1q2_score": 0.013182252119536103}}
{"text": "#ifndef AMICI_MISC_H\n#define AMICI_MISC_H\n\n#include \"amici/defines.h\"\n#include \"amici/exception.h\"\n#include \"amici/vector.h\"\n#include <sunmatrix/sunmatrix_sparse.h> // SUNMatrixContent_Sparse\n\n#include <algorithm>\n#include <vector>\n#include <memory>\n#include <regex>\n\n#include <gsl/gsl-lite.hpp>\n\nnamespace amici {\n\n/**\n * @brief creates a slice from existing data\n *\n * @param data to be sliced\n * @param index slice index\n * @param size slice size\n * @return span of the slice\n */\n\ntemplate <class T>\ngsl::span<T> slice(std::vector<T> &data, int index, unsigned size) {\n    if ((index + 1) * size > data.size())\n        throw std::out_of_range(\"requested slice is out of data range\");\n    if (size > 0)\n        return gsl::make_span(&data.at(index*size), size);\n\n    return gsl::make_span(static_cast<T*>(nullptr), 0);\n}\n\n/**\n * @brief creates a constant slice from existing constant data\n *\n * @param data to be sliced\n * @param index slice index\n * @param size slice size\n * @return span of the slice\n */\n\ntemplate <class T>\nconst gsl::span<const T> slice(const std::vector<T> &data,\n                               int index, unsigned size) {\n    if ((index + 1) * size > data.size())\n        throw std::out_of_range(\"requested slice is out of data range\");\n    if (size > 0)\n        return gsl::make_span(&data.at(index*size), size);\n\n    return gsl::make_span(static_cast<T*>(nullptr), 0);\n}\n\n/**\n * @brief local helper to check whether the provided buffer has the expected\n * size\n * @param buffer buffer to which values are to be written\n * @param expected_size expected size of the buffer\n */\ntemplate <class T>\nvoid checkBufferSize(gsl::span<T> buffer,\n                     typename gsl::span<T>::index_type expected_size) {\n    if (buffer.size() != expected_size)\n        throw AmiException(\"Incorrect buffer size! Was %u, expected %u.\",\n                           buffer.size(), expected_size);\n}\n\n/* TODO: templating writeSlice breaks implicit conversion between vector & span\n not sure whether this is fixable */\n\n/**\n * @brief local helper function to write computed slice to provided buffer (span)\n * @param slice computed value\n * @param buffer buffer to which values are to be written\n */\ntemplate <class T>\nvoid writeSlice(const gsl::span<const T> slice, gsl::span<T> buffer) {\n    checkBufferSize(buffer, slice.size());\n    std::copy(slice.begin(), slice.end(), buffer.data());\n};\n\n/**\n * @brief local helper function to write computed slice to provided buffer (vector)\n * @param s computed value\n * @param b buffer to which values are to be written\n */\ntemplate <class T>\nvoid writeSlice(const std::vector<T> &s, std::vector<T> &b) {\n    writeSlice(gsl::make_span(s.data(), s.size()),\n               gsl::make_span(b.data(), b.size()));\n};\n\n/**\n * @brief local helper function to write computed slice to provided buffer (vector/span)\n * @param s computed value\n * @param b buffer to which values are to be written\n */\ntemplate <class T>\nvoid writeSlice(const std::vector<T> &s, gsl::span<T> b) {\n    writeSlice(gsl::make_span(s.data(), s.size()), b);\n};\n\n/**\n * @brief local helper function to write computed slice to provided buffer (AmiVector/span)\n * @param s computed value\n * @param b buffer to which values are to be written\n */\nvoid writeSlice(const AmiVector &s, gsl::span<realtype> b);\n\n\n/**\n  * @brief Remove parameter scaling according to the parameter scaling in pscale\n  *\n  * All vectors must be of same length.\n  *\n  * @param bufferScaled scaled parameters\n  * @param pscale parameter scaling\n  * @param bufferUnscaled unscaled parameters are written to the array\n  */\nvoid unscaleParameters(gsl::span<const realtype> bufferScaled,\n                       gsl::span<const ParameterScaling> pscale,\n                       gsl::span<realtype> bufferUnscaled);\n\n/**\n  * @brief Remove parameter scaling according to `scaling`\n  *\n  * @param scaledParameter scaled parameter\n  * @param scaling parameter scaling\n  *\n  * @return Unscaled parameter\n  */\ndouble getUnscaledParameter(double scaledParameter, ParameterScaling scaling);\n\n\n/**\n * @brief Apply parameter scaling according to `scaling`\n * @param unscaledParameter\n * @param scaling parameter scaling\n * @return Scaled parameter\n */\ndouble getScaledParameter(double unscaledParameter, ParameterScaling scaling);\n\n\n/**\n * @brief Apply parameter scaling according to `scaling`\n * @param bufferUnscaled\n * @param pscale parameter scaling\n * @param bufferScaled destination\n */\nvoid scaleParameters(gsl::span<const realtype> bufferUnscaled,\n                     gsl::span<const ParameterScaling> pscale,\n                     gsl::span<realtype> bufferScaled);\n\n/**\n * @brief Returns the current backtrace as std::string\n * @param maxFrames Number of frames to include\n * @return Backtrace\n */\nstd::string backtraceString(int maxFrames);\n\n/**\n * @brief Convert std::regex_constants::error_type to string\n * @param err_type error type\n * @return Error type as string\n */\nstd::string regexErrorToString(std::regex_constants::error_type err_type);\n\n/**\n * @brief Format printf-style arguments to std::string\n * @param fmt Format string\n * @param ap Argument list pointer\n * @return Formatted String\n */\nstd::string printfToString(const char *fmt, va_list ap);\n\n/**\n * @brief Generic implementation for a context manager, explicitly deletes copy\n * and move operators for derived classes\n */\nclass ContextManager{\n  public:\n    ContextManager() = default;\n    ContextManager(ContextManager &other) = delete;\n    ContextManager(ContextManager &&other) = delete;\n};\n\n} // namespace amici\n\n#endif // AMICI_MISC_H\n", "meta": {"hexsha": "dd59b03fc9c759b97654f8ce6f3417920768bd71", "size": 5588, "ext": "h", "lang": "C", "max_stars_repo_path": "include/amici/misc.h", "max_stars_repo_name": "PaulJonasJost/AMICI", "max_stars_repo_head_hexsha": "a5c679b0cce90e192bacf9461d43825de8f675ce", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/amici/misc.h", "max_issues_repo_name": "PaulJonasJost/AMICI", "max_issues_repo_head_hexsha": "a5c679b0cce90e192bacf9461d43825de8f675ce", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/amici/misc.h", "max_forks_repo_name": "PaulJonasJost/AMICI", "max_forks_repo_head_hexsha": "a5c679b0cce90e192bacf9461d43825de8f675ce", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9533678756, "max_line_length": 91, "alphanum_fraction": 0.6916607015, "num_tokens": 1305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2538610069692489, "lm_q2_score": 0.05184546793166193, "lm_q1q2_score": 0.013161542695923598}}
{"text": "/*\n Copyright (c) 2015, Mina Kamel, ASL, ETH Zurich, Switzerland\n\n You can contact the author at <mina.kamel@mavt.ethz.ch>\n\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n * Neither the name of ETHZ-ASL nor the\n names of its contributors may be used to endorse or promote products\n derived from this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n DISCLAIMED. IN NO EVENT SHALL ETHZ-ASL BE LIABLE FOR ANY\n DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef INCLUDE_MAV_NONLINEAR_MPC_NONLINEAR_MPC_H_\n#define INCLUDE_MAV_NONLINEAR_MPC_NONLINEAR_MPC_H_\n\n#include <ros/ros.h>\n#include <Eigen/Eigen>\n#include <mav_msgs/conversions.h>\n#include <mav_msgs/eigen_mav_msgs.h>\n#include <stdio.h>\n#include <mav_control_interface/mpc_queue.h>\n#include \"acado_common.h\"\n#include \"acado_auxiliary_functions.h\"\n#include <mav_disturbance_observer/KF_disturbance_observer.h>\n#include <std_srvs/Empty.h>\n#include <lapacke.h>\n\nACADOvariables acadoVariables;\nACADOworkspace acadoWorkspace;\n\nnamespace mav_control {\n\nlapack_logical select_lhp(const double *real, const double *imag)\n{\n  return *real < 0.0;\n}\n\nclass NonlinearModelPredictiveControl\n{\n public:\n  NonlinearModelPredictiveControl(const ros::NodeHandle& nh, const ros::NodeHandle& private_nh);\n  ~NonlinearModelPredictiveControl();\n\n  // Dynamic parameters\n  void setPositionPenality(const Eigen::Vector3d& q_position)\n  {\n    q_position_ = q_position;\n  }\n  void setVelocityPenality(const Eigen::Vector3d& q_velocity)\n  {\n    q_velocity_ = q_velocity;\n  }\n  void setAttitudePenality(const Eigen::Vector2d& q_attitude)\n  {\n    q_attitude_ = q_attitude;\n  }\n  void setCommandPenality(const Eigen::Vector3d& r_command)\n  {\n    r_command_ = r_command;\n  }\n  void setYawGain(double K_yaw)\n  {\n    K_yaw_ = K_yaw;\n  }\n\n  void setAltitudeIntratorGain(double Ki_altitude)\n  {\n    Ki_altitude_ = Ki_altitude;\n  }\n\n  void setXYIntratorGain(double Ki_xy)\n  {\n    Ki_xy_ = Ki_xy;\n  }\n\n  void setEnableOffsetFree(bool enable_offset_free)\n  {\n    enable_offset_free_ = enable_offset_free;\n  }\n\n  void setEnableIntegrator(bool enable_integrator)\n  {\n    enable_integrator_ = enable_integrator;\n  }\n\n  void setControlLimits(const Eigen::VectorXd& control_limits)\n  {\n    //roll_max, pitch_max, yaw_rate_max, thrust_min and thrust_max\n    roll_limit_ = control_limits(0);\n    pitch_limit_ = control_limits(1);\n    yaw_rate_limit_ = control_limits(2);\n    thrust_min_ = control_limits(3);\n    thrust_max_ = control_limits(4);\n  }\n\n  void applyParameters();\n\n  double getMass() const\n  {\n    return mass_;\n  }\n\n  // get reference and predicted state\n  bool getCurrentReference(mav_msgs::EigenTrajectoryPoint* reference) const;\n  bool getCurrentReference(mav_msgs::EigenTrajectoryPointDeque* reference) const;\n  bool getPredictedState(mav_msgs::EigenTrajectoryPointDeque* predicted_state) const;\n\n  // set odom and commands\n  void setOdometry(const mav_msgs::EigenOdometry& odometry);\n  void setCommandTrajectoryPoint(const mav_msgs::EigenTrajectoryPoint& command_trajectory);\n  void setCommandTrajectory(const mav_msgs::EigenTrajectoryPointDeque& command_trajectory);\n\n  // compute control input\n  void calculateRollPitchYawrateThrustCommand(Eigen::Vector4d* ref_attitude_thrust);\n\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n private:\n\n  // constants\n  static constexpr double kGravity = 9.8066;\n  static constexpr int kDisturbanceSize = 3;\n\n  // ros node handles\n  ros::NodeHandle nh_, private_nh_;\n\n  // reset integrator service\n  ros::ServiceServer reset_integrator_service_server_;\n  bool resetIntegratorServiceCallback(std_srvs::Empty::Request &req,\n                                      std_srvs::Empty::Response &res);\n\n  // sampling time parameters\n  void initializeParameters();\n  bool initialized_parameters_;\n\n  // sampling time parameters\n  double sampling_time_;\n  double prediction_sampling_time_;\n\n  // system model parameters\n  double mass_;\n  double roll_time_constant_;\n  double roll_gain_;\n  double pitch_time_constant_;\n  double pitch_gain_;\n  Eigen::Vector3d drag_coefficients_;\n\n  // controller parameters\n  // state penalty\n  Eigen::Vector3d q_position_;\n  Eigen::Vector3d q_velocity_;\n  Eigen::Vector2d q_attitude_;\n\n  // control penalty\n  Eigen::Vector3d r_command_;\n\n  // yaw P gain\n  double K_yaw_;\n\n  // error integrator\n  bool enable_integrator_;\n  double Ki_altitude_;\n  double Ki_xy_;\n  double antiwindup_ball_;\n  Eigen::Vector3d position_error_integration_;\n  double position_error_integration_limit_;\n\n  // control input limits\n  double roll_limit_;\n  double pitch_limit_;\n  double yaw_rate_limit_;\n  double thrust_min_;\n  double thrust_max_;\n\n  // reference queue\n  MPCQueue mpc_queue_;\n  Vector3dDeque position_ref_, velocity_ref_, acceleration_ref_;\n  std::deque<double> yaw_ref_, yaw_rate_ref_;\n\n  // solver matrices\n  Eigen::Matrix<double, ACADO_NY, ACADO_NY> W_;\n  Eigen::Matrix<double, ACADO_NYN, ACADO_NYN> WN_;\n  Eigen::Matrix<double, ACADO_N + 1, ACADO_NX> state_;\n  Eigen::Matrix<double, ACADO_N, ACADO_NU> input_;\n  Eigen::Matrix<double, ACADO_N, ACADO_NY> reference_;\n  Eigen::Matrix<double, 1, ACADO_NYN> referenceN_;\n  Eigen::Matrix<double, ACADO_N + 1, ACADO_NOD> acado_online_data_;\n\n  // disturbance observer\n  bool enable_offset_free_;\n  KFDisturbanceObserver disturbance_observer_;\n\n  // commands\n  Eigen::Vector4d command_roll_pitch_yaw_thrust_;\n\n  // debug info\n  bool verbose_;\n  double solve_time_average_;\n\n  // most recent odometry information\n  mav_msgs::EigenOdometry odometry_;\n  bool received_first_odometry_;\n\n  // initilize solver\n  void initializeAcadoSolver(Eigen::VectorXd x0);\n\n  // solve continuous time Riccati equation\n  Eigen::MatrixXd solveCARE(Eigen::MatrixXd Q, Eigen::MatrixXd R);\n\n};\n\n}\n\n#endif /* INCLUDE_MAV_NONLINEAR_MPC_NONLINEAR_MPC_H_ */\n", "meta": {"hexsha": "39ec0b604a9edc883d8afecf07efdc02a860cc1b", "size": 6841, "ext": "h", "lang": "C", "max_stars_repo_path": "mav_nonlinear_mpc/include/mav_nonlinear_mpc/nonlinear_mpc.h", "max_stars_repo_name": "caomuqing/mav_control_rw", "max_stars_repo_head_hexsha": "207058d78428b944fb8afe51cde06bf9629d8d7a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 230.0, "max_stars_repo_stars_event_min_datetime": "2016-11-11T01:48:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T13:56:13.000Z", "max_issues_repo_path": "mav_nonlinear_mpc/include/mav_nonlinear_mpc/nonlinear_mpc.h", "max_issues_repo_name": "caomuqing/mav_control_rw", "max_issues_repo_head_hexsha": "207058d78428b944fb8afe51cde06bf9629d8d7a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 40.0, "max_issues_repo_issues_event_min_datetime": "2017-01-22T16:27:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-28T03:41:13.000Z", "max_forks_repo_path": "mav_nonlinear_mpc/include/mav_nonlinear_mpc/nonlinear_mpc.h", "max_forks_repo_name": "caomuqing/mav_control_rw", "max_forks_repo_head_hexsha": "207058d78428b944fb8afe51cde06bf9629d8d7a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 142.0, "max_forks_repo_forks_event_min_datetime": "2016-12-04T03:32:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T12:23:21.000Z", "avg_line_length": 29.4870689655, "max_line_length": 96, "alphanum_fraction": 0.7709399211, "num_tokens": 1674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.027169233406485478, "lm_q1q2_score": 0.013160235567174494}}
{"text": "/* spmatrix.c\n * \n * Copyright (C) 2012 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <stdlib.h>\n#include <math.h>\n\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_spmatrix.h>\n\n#include \"avl.c\"\n\nstatic int compare_triplet(const void *pa, const void *pb, void *param);\nstatic void *avl_spmalloc (size_t size, void *param);\nstatic void avl_spfree (void *block, void *param);\n\nstatic struct libavl_allocator avl_allocator_spmatrix =\n{\n  avl_spmalloc,\n  avl_spfree\n};\n\n/*\ngsl_spmatrix_alloc()\n  Allocate a sparse matrix in triplet representation\n\nInputs: n1 - number of rows\n        n2 - number of columns\n\nNotes: if (n1,n2) are not known at allocation time, they can each be\nset to 1, and they will be expanded as elements are added to the matrix\n*/\n\ngsl_spmatrix *\ngsl_spmatrix_alloc(const size_t n1, const size_t n2)\n{\n  const double density = 0.1; /* estimate */\n  size_t nzmax = (size_t) floor(n1 * n2 * density);\n\n  if (nzmax == 0)\n    nzmax = 10;\n\n  return gsl_spmatrix_alloc_nzmax(n1, n2, nzmax, GSL_SPMATRIX_TRIPLET);\n} /* gsl_spmatrix_alloc() */\n\n/*\ngsl_spmatrix_alloc_nzmax()\n  Allocate a sparse matrix with given nzmax\n\nInputs: n1     - number of rows\n        n2     - number of columns\n        nzmax  - maximum number of matrix elements\n        sptype - type of matrix (triplet, CCS, CRS)\n\nNotes: if (n1,n2) are not known at allocation time, they can each be\nset to 1, and they will be expanded as elements are added to the matrix\n*/\n\ngsl_spmatrix *\ngsl_spmatrix_alloc_nzmax(const size_t n1, const size_t n2,\n                         const size_t nzmax, const size_t sptype)\n{\n  gsl_spmatrix *m;\n\n  if (n1 == 0)\n    {\n      GSL_ERROR_NULL (\"matrix dimension n1 must be positive integer\",\n                      GSL_EINVAL);\n    }\n  else if (n2 == 0)\n    {\n      GSL_ERROR_NULL (\"matrix dimension n2 must be positive integer\",\n                      GSL_EINVAL);\n    }\n\n  m = calloc(1, sizeof(gsl_spmatrix));\n  if (!m)\n    {\n      GSL_ERROR_NULL(\"failed to allocate space for spmatrix struct\",\n                     GSL_ENOMEM);\n    }\n\n  m->size1 = n1;\n  m->size2 = n2;\n  m->nz = 0;\n  m->nzmax = GSL_MAX(nzmax, 1);\n  m->sptype = sptype;\n\n  m->i = malloc(m->nzmax * sizeof(size_t));\n  if (!m->i)\n    {\n      gsl_spmatrix_free(m);\n      GSL_ERROR_NULL(\"failed to allocate space for row indices\",\n                     GSL_ENOMEM);\n    }\n\n  if (sptype == GSL_SPMATRIX_TRIPLET)\n    {\n      m->tree_data = malloc(sizeof(gsl_spmatrix_tree));\n      if (!m->tree_data)\n        {\n          gsl_spmatrix_free(m);\n          GSL_ERROR_NULL(\"failed to allocate space for AVL tree struct\",\n                         GSL_ENOMEM);\n        }\n\n      m->tree_data->n = 0;\n\n      /* allocate tree data structure */\n      m->tree_data->tree = avl_create(compare_triplet, (void *) m,\n                                      &avl_allocator_spmatrix);\n      if (!m->tree_data->tree)\n        {\n          gsl_spmatrix_free(m);\n          GSL_ERROR_NULL(\"failed to allocate space for AVL tree\",\n                         GSL_ENOMEM);\n        }\n\n      /* preallocate nzmax tree nodes */\n      m->tree_data->node_array = malloc(m->nzmax * sizeof(struct avl_node));\n      if (!m->tree_data->node_array)\n        {\n          gsl_spmatrix_free(m);\n          GSL_ERROR_NULL(\"failed to allocate space for AVL tree nodes\",\n                         GSL_ENOMEM);\n        }\n\n      m->p = malloc(m->nzmax * sizeof(size_t));\n      if (!m->p)\n        {\n          gsl_spmatrix_free(m);\n          GSL_ERROR_NULL(\"failed to allocate space for column indices\",\n                         GSL_ENOMEM);\n        }\n    }\n  else if (sptype == GSL_SPMATRIX_CCS)\n    {\n      m->p = malloc((n2 + 1) * sizeof(size_t));\n      m->work = malloc(GSL_MAX(n1, n2) *\n                       GSL_MAX(sizeof(size_t), sizeof(double)));\n      if (!m->p || !m->work)\n        {\n          gsl_spmatrix_free(m);\n          GSL_ERROR_NULL(\"failed to allocate space for column pointers\",\n                         GSL_ENOMEM);\n        }\n    }\n  else if (sptype == GSL_SPMATRIX_CRS)\n    {\n      m->p = malloc((n1 + 1) * sizeof(size_t));\n      m->work = malloc(GSL_MAX(n1, n2) *\n                       GSL_MAX(sizeof(size_t), sizeof(double)));\n      if (!m->p || !m->work)\n        {\n          gsl_spmatrix_free(m);\n          GSL_ERROR_NULL(\"failed to allocate space for row pointers\",\n                         GSL_ENOMEM);\n        }\n    }\n\n  m->data = malloc(m->nzmax * sizeof(double));\n  if (!m->data)\n    {\n      gsl_spmatrix_free(m);\n      GSL_ERROR_NULL(\"failed to allocate space for data\",\n                     GSL_ENOMEM);\n    }\n\n  return m;\n} /* gsl_spmatrix_alloc_nzmax() */\n\n/*\ngsl_spmatrix_free()\n  Free sparse matrix object\n*/\n\nvoid\ngsl_spmatrix_free(gsl_spmatrix *m)\n{\n  if (m->i)\n    free(m->i);\n\n  if (m->p)\n    free(m->p);\n\n  if (m->data)\n    free(m->data);\n\n  if (m->work)\n    free(m->work);\n\n  if (m->tree_data)\n    {\n      if (m->tree_data->tree)\n        avl_destroy(m->tree_data->tree, NULL);\n\n      if (m->tree_data->node_array)\n        free(m->tree_data->node_array);\n\n      free(m->tree_data);\n    }\n\n  free(m);\n} /* gsl_spmatrix_free() */\n\n/*\ngsl_spmatrix_realloc()\n  As elements are added to the sparse matrix, its possible that they\nwill exceed the previously specified nzmax - reallocate the matrix\nwith a new nzmax\n*/\n\nint\ngsl_spmatrix_realloc(const size_t nzmax, gsl_spmatrix *m)\n{\n  int s = GSL_SUCCESS;\n  void *ptr;\n\n  if (nzmax < m->nz)\n    {\n      GSL_ERROR(\"new nzmax is less than current nz\", GSL_EINVAL);\n    }\n\n  ptr = realloc(m->i, nzmax * sizeof(size_t));\n  if (!ptr)\n    {\n      GSL_ERROR(\"failed to allocate space for row indices\", GSL_ENOMEM);\n    }\n\n  m->i = (size_t *) ptr;\n\n  if (GSL_SPMATRIX_ISTRIPLET(m))\n    {\n      ptr = realloc(m->p, nzmax * sizeof(size_t));\n      if (!ptr)\n        {\n          GSL_ERROR(\"failed to allocate space for column indices\", GSL_ENOMEM);\n        }\n\n      m->p = (size_t *) ptr;\n    }\n\n  ptr = realloc(m->data, nzmax * sizeof(double));\n  if (!ptr)\n    {\n      GSL_ERROR(\"failed to allocate space for data\", GSL_ENOMEM);\n    }\n\n  m->data = (double *) ptr;\n\n  /* rebuild binary tree */\n  if (GSL_SPMATRIX_ISTRIPLET(m))\n    {\n      size_t n;\n\n      /* reset tree to empty state, but don't free root tree ptr */\n      avl_empty(m->tree_data->tree, NULL);\n      m->tree_data->n = 0;\n\n      ptr = realloc(m->tree_data->node_array, nzmax * sizeof(struct avl_node));\n      if (!ptr)\n        {\n          GSL_ERROR(\"failed to allocate space for AVL tree nodes\", GSL_ENOMEM);\n        }\n\n      m->tree_data->node_array = ptr;\n\n      /*\n       * need to reinsert all tree elements since the m->data addresses\n       * have changed\n       */\n      for (n = 0; n < m->nz; ++n)\n        {\n          ptr = avl_insert(m->tree_data->tree, &m->data[n]);\n          if (ptr != NULL)\n            {\n              GSL_ERROR(\"detected duplicate entry\", GSL_EINVAL);\n            }\n        }\n    }\n\n  /* update to new nzmax */\n  m->nzmax = nzmax;\n\n  return s;\n} /* gsl_spmatrix_realloc() */\n\nint\ngsl_spmatrix_set_zero(gsl_spmatrix *m)\n{\n  m->nz = 0;\n\n  if (GSL_SPMATRIX_ISTRIPLET(m))\n    {\n      /* reset tree to empty state and node index pointer to 0 */\n      avl_empty(m->tree_data->tree, NULL);\n      m->tree_data->n = 0;\n    }\n\n  return GSL_SUCCESS;\n} /* gsl_spmatrix_set_zero() */\n\nsize_t\ngsl_spmatrix_nnz(const gsl_spmatrix *m)\n{\n  return m->nz;\n} /* gsl_spmatrix_nnz() */\n\n/*\ngsl_spmatrix_compare_idx()\n  Comparison function for searching binary tree in triplet\nrepresentation.\n\nTo detect duplicate elements in the tree, we want to determine\nif there already exists an entry for (i,j) in the tree. Since\nthe actual tree node stores only the data elements data[n],\nwe will do pointer arithmetic to get from the given data[n]\nto the row/column indices i[n] and j[n].\n\nThis compare function will sort the tree first by row i,\nand for equal rows, it will then sort by column j\n\nInputs: ia - row index of element a\n        ja - column index of element a\n        ib - row index of element b\n        jb - column index of element b\n\nReturn:\n  -1 if pa < pb: (ia,ja) < (ib,jb)\n  +1 if pa > pb: (ia,ja) > (ib,jb)\n   0 if pa = pb: (ia,ja) == (ib,jb)\n*/\n\nint\ngsl_spmatrix_compare_idx(const size_t ia, const size_t ja,\n                         const size_t ib, const size_t jb)\n{\n  if (ia < ib)\n    return -1;\n  else if (ia > ib)\n    return 1;\n  else\n    {\n      /* row indices are equal, sort by column index */\n      if (ja < jb)\n        return -1;\n      else if (ja > jb)\n        return 1;\n      else\n        return 0; /* row and column indices are equal */\n    }\n}\n\n/*\ngsl_spmatrix_tree_rebuild()\n  When reading a triplet matrix from disk, or when\ncopying a triplet matrix, it is necessary to rebuild the\nbinary tree for element searches.\n\nInputs: m - triplet matrix\n*/\n\nint\ngsl_spmatrix_tree_rebuild(gsl_spmatrix * m)\n{\n  if (!GSL_SPMATRIX_ISTRIPLET(m))\n    {\n      GSL_ERROR(\"m must be in triplet format\", GSL_EINVAL);\n    }\n  else\n    {\n      size_t n;\n\n      /* reset tree to empty state, but don't free root tree ptr */\n      avl_empty(m->tree_data->tree, NULL);\n      m->tree_data->n = 0;\n\n      /* insert all tree elements */\n      for (n = 0; n < m->nz; ++n)\n        {\n          void *ptr = avl_insert(m->tree_data->tree, &m->data[n]);\n          if (ptr != NULL)\n            {\n              GSL_ERROR(\"detected duplicate entry\", GSL_EINVAL);\n            }\n        }\n\n      return GSL_SUCCESS;\n    }\n}\n\n/*\ncompare_triplet()\n  Comparison function for searching binary tree in triplet\nrepresentation.\n\nTo detect duplicate elements in the tree, we want to determine\nif there already exists an entry for (i,j) in the tree. Since\nthe actual tree node stores only the data elements data[n],\nwe will do pointer arithmetic to get from the given data[n]\nto the row/column indices i[n] and j[n].\n\nThis compare function will sort the tree first by row i,\nand for equal rows, it will then sort by column j\n\nInputs: pa    - element 1 for comparison (double *) \n        pb    - element 2 for comparison (double *)\n        param - parameter (gsl_spmatrix)\n\nReturn:\n  -1 if pa < pb: (ia,ja) < (ib,jb)\n  +1 if pa > pb: (ia,ja) > (ib,jb)\n   0 if pa = pb: (ia,ja) == (ib,jb)\n*/\n\nstatic int\ncompare_triplet(const void *pa, const void *pb, void *param)\n{\n  gsl_spmatrix *m = (gsl_spmatrix *) param;\n\n  /* pointer arithmetic to find indices in data array */\n  const size_t idxa = (const double *) pa - m->data;\n  const size_t idxb = (const double *) pb - m->data;\n\n  return gsl_spmatrix_compare_idx(m->i[idxa], m->p[idxa],\n                                  m->i[idxb], m->p[idxb]);\n} /* compare_triplet() */\n\nstatic void *\navl_spmalloc (size_t size, void *param)\n{\n  gsl_spmatrix *m = (gsl_spmatrix *) param;\n\n  if (size != sizeof(struct avl_node))\n    {\n      GSL_ERROR_NULL(\"attemping to allocate incorrect node size\", GSL_EBADLEN);\n    }\n\n  /*\n   * return the next available avl_node slot; index\n   * m->tree_data->n keeps track of next open slot\n   */\n  if (m->tree_data->n < m->nzmax)\n    {\n      /* cast to char* for pointer arithmetic */\n      unsigned char *node_ptr = (unsigned char *) m->tree_data->node_array;\n\n      /* offset in bytes for next node slot */\n      size_t offset = (m->tree_data->n)++ * sizeof(struct avl_node);\n\n      return node_ptr + offset;\n    }\n  else\n    {\n      /*\n       * we should never get here - gsl_spmatrix_realloc() should\n       * be called before exceeding nzmax nodes\n       */\n      GSL_ERROR_NULL(\"attemping to allocate tree node past nzmax\", GSL_EINVAL);\n    }\n}\n\nstatic void\navl_spfree (void *block, void *param)\n{\n  (void)block;\n  (void)param;\n  /*\n   * do nothing - instead of allocating/freeing individual nodes,\n   * we malloc and free nzmax nodes at a time\n   */\n}\n", "meta": {"hexsha": "02ecaa9579764cae2b5aa7e53ec11ec9512060d9", "size": 12418, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.4/spmatrix/spmatrix.c", "max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-13T05:01:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-13T05:01:59.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/spmatrix/spmatrix.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/spmatrix/spmatrix.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3428571429, "max_line_length": 81, "alphanum_fraction": 0.6077468191, "num_tokens": 3425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36296920551961676, "lm_q2_score": 0.03622005287398489, "lm_q1q2_score": 0.013146763815548806}}
{"text": "#include <stdio.h>\n#include <gsl/gsl_matrix.h>\n\nint\nmain (void)\n{\n  int i, j, k = 0; \n  gsl_matrix * m = gsl_matrix_alloc (100, 100);\n  gsl_matrix * a = gsl_matrix_alloc (100, 100);\n  \n  for (i = 0; i < 100; i++)\n    for (j = 0; j < 100; j++)\n      gsl_matrix_set (m, i, j, 0.23 + i + j);\n\n  {  \n     FILE * f = fopen (\"test.dat\", \"wb\");\n     gsl_matrix_fwrite (f, m);\n     fclose (f);\n  }\n\n  {  \n     FILE * f = fopen (\"test.dat\", \"rb\");\n     gsl_matrix_fread (f, a);\n     fclose (f);\n  }\n\n  for (i = 0; i < 100; i++)\n    for (j = 0; j < 100; j++)\n      {\n        double mij = gsl_matrix_get (m, i, j);\n        double aij = gsl_matrix_get (a, i, j);\n        if (mij != aij) k++;\n      }\n\n  gsl_matrix_free (m);\n  gsl_matrix_free (a);\n\n  printf (\"differences = %d (should be zero)\\n\", k);\n  return (k > 0);\n}\n", "meta": {"hexsha": "b05ffbd03f899d3987655987815d8dbea9eeee45", "size": 809, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/matrixw.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/matrixw.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/matrixw.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 19.7317073171, "max_line_length": 52, "alphanum_fraction": 0.4969097651, "num_tokens": 294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3629692055196168, "lm_q2_score": 0.03622005183364064, "lm_q1q2_score": 0.013146763437935883}}
{"text": "/* ode-initval/control.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n/* Author:  G. Jungman */\n\n#include <config.h>\n#include <stdlib.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_errno.h>\n#include \"gsl_odeiv.h\"\n\ngsl_odeiv_control *\ngsl_odeiv_control_alloc(const gsl_odeiv_control_type * T)\n{\n  gsl_odeiv_control * c = \n    (gsl_odeiv_control *) malloc(sizeof(gsl_odeiv_control));\n\n  if(c == 0) \n    {\n      GSL_ERROR_NULL (\"failed to allocate space for control struct\", \n                      GSL_ENOMEM);\n    };\n\n  c->type = T;\n  c->state = c->type->alloc();\n\n  if (c->state == 0)\n    {\n      free (c);\t\t/* exception in constructor, avoid memory leak */\n\n      GSL_ERROR_NULL (\"failed to allocate space for control state\", \n                      GSL_ENOMEM);\n    };\n\n  return c;\n}\n\nint\ngsl_odeiv_control_init(gsl_odeiv_control * c, \n                       double eps_abs, double eps_rel, \n                       double a_y, double a_dydt)\n{\n  return c->type->init (c->state, eps_abs, eps_rel, a_y, a_dydt);\n}\n\nvoid\ngsl_odeiv_control_free(gsl_odeiv_control * c)\n{\n  c->type->free(c->state);\n  free(c);\n}\n\nconst char *\ngsl_odeiv_control_name(const gsl_odeiv_control * c)\n{\n  return c->type->name;\n}\n\nint\ngsl_odeiv_control_hadjust (gsl_odeiv_control * c, gsl_odeiv_step * s, const double y0[], const double yerr[], const double dydt[], double * h)\n{\n  return c->type->hadjust(c->state, s->dimension, s->type->order(s->state),\n                          y0, yerr, dydt, h);\n}\n", "meta": {"hexsha": "1b3a132b69ab613e85f36b542772ad6955991d95", "size": 2202, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/ode-initval/control.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/ode-initval/control.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/ode-initval/control.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 27.1851851852, "max_line_length": 142, "alphanum_fraction": 0.6634877384, "num_tokens": 615, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.02976009545188317, "lm_q1q2_score": 0.013144230807099394}}
{"text": "#include \"cwc.h\"\n#include \"../ccv_internal.h\"\n#ifdef HAVE_GSL\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n#endif\n#include \"cwc_ext.h\"\n#ifdef USE_DISPATCH\n#include <dispatch/dispatch.h>\n#endif\n\n#ifdef HAVE_GSL\nstatic void _cwc_convnet_random_image_manipulation(gsl_rng* rng, ccv_dense_matrix_t* image, float image_manipulation)\n{\n\tassert(rng && CCV_GET_CHANNEL(image->type) == CCV_C3 && image_manipulation > 0 && image_manipulation <= 1);\n\tint ord[3] = {0, 1, 2};\n\tgsl_ran_shuffle(rng, ord, 3, sizeof(int));\n\tint i;\n\tfor (i = 0; i < 3; i++)\n\t\t// change the applying order\n\t\tswitch (ord[i])\n\t\t{\n\t\t\tcase 0:\n\t\t\t\t// introduce some brightness changes to the original image\n\t\t\t\tccv_scale(image, (ccv_matrix_t**)&image, 0, gsl_rng_uniform_pos(rng) * image_manipulation * 2 + (1 - image_manipulation));\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\t// introduce some saturation changes to the original image\n\t\t\t\tccv_saturation(image, &image, 0, gsl_rng_uniform_pos(rng) * image_manipulation * 2 + (1 - image_manipulation));\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\t// introduce some contrast changes to the original image\n\t\t\t\tccv_contrast(image, &image, 0, gsl_rng_uniform_pos(rng) * image_manipulation * 2 + (1 - image_manipulation));\n\t\t\t\tbreak;\n\t\t}\n}\n\nvoid cwc_convnet_batch_formation(gsl_rng* rng, ccv_array_t* categorizeds, ccv_dense_matrix_t* mean_activity, ccv_dense_matrix_t* eigenvectors, ccv_dense_matrix_t* eigenvalues, float image_manipulation, float color_gain, int* idx, ccv_size_t dim, int min_dim, int max_dim, int rows, int cols, int channels, int category_count, int symmetric, int batch, int offset, int size, float* b, int* c)\n{\n\tassert(size > 0 && size <= batch);\n\tassert(min_dim >= rows && min_dim >= cols);\n\tassert(max_dim >= min_dim);\n\tfloat* channel_gains = (float*)alloca(sizeof(float) * channels * size);\n\tmemset(channel_gains, 0, sizeof(float) * channels * size);\n\tint i;\n\tgsl_rng** rngs = (gsl_rng**)alloca(sizeof(gsl_rng*) * size);\n\tmemset(rngs, 0, sizeof(gsl_rng*) * size);\n\tif (rng)\n\t\tfor (i = 0; i < size; i++)\n\t\t{\n\t\t\trngs[i] = gsl_rng_alloc(gsl_rng_default);\n\t\t\tgsl_rng_set(rngs[i], gsl_rng_get(rng));\n\t\t}\n\tparallel_for(i, size) {\n\t\tint j, k;\n\t\tassert(offset + i < categorizeds->rnum);\n\t\tccv_categorized_t* categorized = (ccv_categorized_t*)ccv_array_get(categorizeds, idx ? idx[offset + i] : offset + i);\n\t\tassert(categorized->c < category_count && categorized->c >= 0); // now only accept classes listed\n\t\tif (c)\n\t\t\tc[i] = categorized->c;\n\t\tccv_dense_matrix_t* image = 0;\n\t\tswitch (categorized->type)\n\t\t{\n\t\t\tcase CCV_CATEGORIZED_DENSE_MATRIX:\n\t\t\t\timage = categorized->matrix;\n\t\t\t\tbreak;\n\t\t\tcase CCV_CATEGORIZED_FILE:\n\t\t\t\timage = 0;\n\t\t\t\tccv_read(categorized->file.filename, &image, CCV_IO_ANY_FILE | CCV_IO_RGB_COLOR);\n\t\t\t\tbreak;\n\t\t}\n\t\tif (image)\n\t\t{\n\t\t\t// first resize to between min_dim and max_dim\n\t\t\tccv_dense_matrix_t* input = 0;\n\t\t\tccv_size_t resize = dim;\n\t\t\tif (rngs[i]) // randomize the resized dimensions\n\t\t\t{\n\t\t\t\tint d = gsl_rng_uniform_int(rngs[i], max_dim - min_dim + 1) + min_dim;\n\t\t\t\tresize = ccv_size(d, d);\n\t\t\t}\n\t\t\t// if neither side is the same as expected, we have to resize first\n\t\t\tif (resize.height != image->rows && resize.width != image->cols)\n\t\t\t\tccv_convnet_input_formation(resize, image, &input);\n\t\t\telse\n\t\t\t\tinput = image;\n\t\t\tif (rngs[i] && image_manipulation > 0)\n\t\t\t\t_cwc_convnet_random_image_manipulation(rngs[i], input, image_manipulation);\n\t\t\tccv_dense_matrix_t* patch = 0;\n\t\t\tif (input->cols != cols || input->rows != rows)\n\t\t\t{\n\t\t\t\tint x = rngs[i] ? gsl_rng_uniform_int(rngs[i], input->cols - cols + 1) : (input->cols - cols + 1) / 2;\n\t\t\t\tint y = rngs[i] ? gsl_rng_uniform_int(rngs[i], input->rows - rows + 1) : (input->rows - rows + 1) / 2;\n\t\t\t\tccv_slice(input, (ccv_matrix_t**)&patch, CCV_32F, y, x, rows, cols);\n\t\t\t} else\n\t\t\t\tccv_shift(input, (ccv_matrix_t**)&patch, CCV_32F, 0, 0); // converting to 32f\n\t\t\tif (input != image) // only unload if we created new input\n\t\t\t\tccv_matrix_free(input);\n\t\t\t// we loaded image in, deallocate it now\n\t\t\tif (categorized->type != CCV_CATEGORIZED_DENSE_MATRIX)\n\t\t\t\tccv_matrix_free(image);\n\t\t\t// random horizontal reflection\n\t\t\tif (symmetric && rngs[i] && gsl_rng_uniform_int(rngs[i], 2) == 0)\n\t\t\t\tccv_flip(patch, &patch, 0, CCV_FLIP_X);\n\t\t\tint x = rngs[i] ? gsl_rng_uniform_int(rngs[i], mean_activity->cols - cols + 1) : (mean_activity->cols - cols + 1) / 2;\n\t\t\tint y = rngs[i] ? gsl_rng_uniform_int(rngs[i], mean_activity->rows - rows + 1) : (mean_activity->rows - rows + 1) / 2;\n\t\t\tccv_dense_matrix_t mean_patch = ccv_reshape(mean_activity, y, x, rows, cols);\n\t\t\tccv_subtract(patch, &mean_patch, (ccv_matrix_t**)&patch, 0);\n\t\t\tassert(channels == CCV_GET_CHANNEL(patch->type));\n\t\t\tif (color_gain > 0 && rngs[i] && eigenvectors && eigenvalues)\n\t\t\t{\n\t\t\t\tassert(channels == 3); // only support RGB color gain\n\t\t\t\tmemset(channel_gains + channels * i, 0, sizeof(float) * channels);\n\t\t\t\tfor (j = 0; j < channels; j++)\n\t\t\t\t{\n\t\t\t\t\tfloat alpha = gsl_ran_gaussian(rngs[i], color_gain) * eigenvalues->data.f64[j];\n\t\t\t\t\tfor (k = 0; k < channels; k++)\n\t\t\t\t\t\tchannel_gains[k + i * channels] += eigenvectors->data.f64[j * channels + k] * alpha;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (j = 0; j < channels; j++)\n\t\t\t\tfor (k = 0; k < rows * cols; k++)\n\t\t\t\t\tb[(j * rows * cols + k) * batch + i] = patch->data.f32[k * channels + j] + channel_gains[j + i * channels];\n\t\t\tccv_matrix_free(patch);\n\t\t} else\n\t\t\tPRINT(CCV_CLI_ERROR, \"cannot load %s.\\n\", categorized->file.filename);\n\t} parallel_endfor\n\tif (rng)\n\t\tfor (i = 0; i < size; i++)\n\t\t\tgsl_rng_free(rngs[i]);\n}\n#endif\n\nvoid cwc_convnet_mean_formation(ccv_array_t* categorizeds, ccv_size_t dim, int channels, int symmetric, ccv_dense_matrix_t** b)\n{\n\tint i, count = 0;\n\tccv_dense_matrix_t* c = ccv_dense_matrix_new(dim.height, dim.width, channels | CCV_64F, 0, 0);\n\tccv_zero(c);\n\tccv_dense_matrix_t* db = *b = ccv_dense_matrix_renew(*b, dim.height, dim.width, channels | CCV_32F, channels | CCV_32F, 0);\n\tfor (i = 0; i < categorizeds->rnum; i++)\n\t{\n\t\tif (i % 23 == 0 || i == categorizeds->rnum - 1)\n\t\t\tFLUSH(CCV_CLI_INFO, \" - compute mean activity %d / %d\", i + 1, categorizeds->rnum);\n\t\tccv_categorized_t* categorized = (ccv_categorized_t*)ccv_array_get(categorizeds, i);\n\t\tccv_dense_matrix_t* image = 0;\n\t\tswitch (categorized->type)\n\t\t{\n\t\t\tcase CCV_CATEGORIZED_DENSE_MATRIX:\n\t\t\t\timage = categorized->matrix;\n\t\t\t\tbreak;\n\t\t\tcase CCV_CATEGORIZED_FILE:\n\t\t\t\tccv_read(categorized->file.filename, &image, CCV_IO_ANY_FILE | CCV_IO_RGB_COLOR);\n\t\t\t\tbreak;\n\t\t}\n\t\tif (!image)\n\t\t{\n\t\t\tPRINT(CCV_CLI_ERROR, \"cannot load %s.\\n\", categorized->file.filename);\n\t\t\tcontinue;\n\t\t}\n\t\tccv_dense_matrix_t* patch = 0;\n\t\tif (image->cols != dim.width || image->rows != dim.height)\n\t\t{\n\t\t\tint x = (image->cols - dim.width + 1) / 2;\n\t\t\tint y = (image->rows - dim.height + 1) / 2;\n\t\t\tassert(x == 0 || y == 0);\n\t\t\tccv_slice(image, (ccv_matrix_t**)&patch, CCV_32F, y, x, dim.height, dim.width);\n\t\t} else\n\t\t\tccv_shift(image, (ccv_matrix_t**)&patch, CCV_32F, 0, 0); // converting to 32f\n\t\tif (categorized->type != CCV_CATEGORIZED_DENSE_MATRIX)\n\t\t\tccv_matrix_free(image);\n\t\tccv_add(patch, c, (ccv_matrix_t**)&c, CCV_64F);\n\t\t++count;\n\t\tccv_matrix_free(patch);\n\t}\n\tif (symmetric)\n\t{\n\t\tint j, k;\n\t\tdouble p = 0.5 / count;\n\t\tdouble* cptr = c->data.f64;\n\t\tfloat* dbptr = db->data.f32;\n\t\tfor (i = 0; i < db->rows; i++)\n\t\t{\n\t\t\tfor (j = 0; j < db->cols; j++)\n\t\t\t\tfor (k = 0; k < channels; k++)\n\t\t\t\t\tdbptr[j * channels + k] = p * (cptr[j * channels + k] + cptr[(c->cols - j - 1) * channels + k]);\n\t\t\tdbptr += db->cols * channels;\n\t\t\tcptr += c->cols * channels;\n\t\t}\n\t} else {\n\t\tdouble p = 1.0 / count;\n\t\tfor (i = 0; i < dim.height * dim.width * channels; i++)\n\t\t\tdb->data.f32[i] = p * c->data.f64[i];\n\t}\n\tccv_matrix_free(c);\n\tPRINT(CCV_CLI_INFO, \"\\n\");\n}\n\nvoid cwc_convnet_channel_eigen(ccv_array_t* categorizeds, ccv_dense_matrix_t* mean_activity, ccv_size_t dim, int channels, ccv_dense_matrix_t** eigenvectors, ccv_dense_matrix_t** eigenvalues)\n{\n\tassert(channels == 3); // this function cannot handle anything other than 3x3 covariance matrix\n\tdouble* mean_value = (double*)alloca(sizeof(double) * channels);\n\tmemset(mean_value, 0, sizeof(double) * channels);\n\tassert(CCV_GET_CHANNEL(mean_activity->type) == channels);\n\tassert(mean_activity->rows == dim.height);\n\tassert(mean_activity->cols == dim.width);\n\tint i, j, k, c, count = 0;\n\tfor (i = 0; i < dim.height * dim.width; i++)\n\t\tfor (k = 0; k < channels; k++)\n\t\t\tmean_value[k] += mean_activity->data.f32[i * channels + k];\n\tfor (i = 0; i < channels; i++)\n\t\tmean_value[i] = mean_value[i] / (dim.height * dim.width);\n\tdouble* covariance = (double*)alloca(sizeof(double) * channels * channels);\n\tmemset(covariance, 0, sizeof(double) * channels * channels);\n\tfor (c = 0; c < categorizeds->rnum; c++)\n\t{\n\t\tif (c % 23 == 0 || c == categorizeds->rnum - 1)\n\t\t\tFLUSH(CCV_CLI_INFO, \" - compute covariance matrix for data augmentation (color gain) %d / %d\", c + 1, categorizeds->rnum);\n\t\tccv_categorized_t* categorized = (ccv_categorized_t*)ccv_array_get(categorizeds, c);\n\t\tccv_dense_matrix_t* image = 0;\n\t\tswitch (categorized->type)\n\t\t{\n\t\t\tcase CCV_CATEGORIZED_DENSE_MATRIX:\n\t\t\t\timage = categorized->matrix;\n\t\t\t\tbreak;\n\t\t\tcase CCV_CATEGORIZED_FILE:\n\t\t\t\tccv_read(categorized->file.filename, &image, CCV_IO_ANY_FILE | CCV_IO_RGB_COLOR);\n\t\t\t\tbreak;\n\t\t}\n\t\tif (!image)\n\t\t{\n\t\t\tPRINT(CCV_CLI_ERROR, \"cannot load %s.\\n\", categorized->file.filename);\n\t\t\tcontinue;\n\t\t}\n\t\tccv_dense_matrix_t* patch = 0;\n\t\tif (image->cols != dim.width || image->rows != dim.height)\n\t\t{\n\t\t\tint x = (image->cols - dim.width + 1) / 2;\n\t\t\tint y = (image->rows - dim.height + 1) / 2;\n\t\t\tassert(x == 0 || y == 0);\n\t\t\tccv_slice(image, (ccv_matrix_t**)&patch, CCV_32F, y, x, dim.height, dim.width);\n\t\t} else\n\t\t\tccv_shift(image, (ccv_matrix_t**)&patch, CCV_32F, 0, 0); // converting to 32f\n\t\tif (categorized->type != CCV_CATEGORIZED_DENSE_MATRIX)\n\t\t\tccv_matrix_free(image);\n\t\tfor (i = 0; i < dim.width * dim.height; i++)\n\t\t\tfor (j = 0; j < channels; j++)\n\t\t\t\tfor (k = j; k < channels; k++)\n\t\t\t\t\tcovariance[j * channels + k] += (patch->data.f32[i * channels + j] - mean_value[j]) * (patch->data.f32[i * channels + k] - mean_value[k]);\n\t\t++count;\n\t\tccv_matrix_free(patch);\n\t}\n\tfor (i = 0; i < channels; i++)\n\t\tfor (j = 0; j < i; j++)\n\t\t\tcovariance[i * channels + j] = covariance[j * channels + i];\n\tdouble p = 1.0 / ((double)count * dim.height * dim.width);\n\tfor (i = 0; i < channels; i++)\n\t\tfor (j = 0; j < channels; j++)\n\t\t\tcovariance[i * channels + j] *= p; // scale down\n\tccv_dense_matrix_t covm = ccv_dense_matrix(3, 3, CCV_64F | CCV_C1, covariance, 0);\n\tccv_eigen(&covm, eigenvectors, eigenvalues, CCV_64F, 1e-8);\n\tPRINT(CCV_CLI_INFO, \"\\n\");\n}\n", "meta": {"hexsha": "0a1c5d32df1fe6511c9dbb8d92652d7d07eff2a2", "size": 10598, "ext": "c", "lang": "C", "max_stars_repo_path": "lib/cuda/cwc_convnet_ext.c", "max_stars_repo_name": "ChiahungTai/ccv", "max_stars_repo_head_hexsha": "7fb761f4d8188776dd42b8a06b07ecda7840cd3c", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/cuda/cwc_convnet_ext.c", "max_issues_repo_name": "ChiahungTai/ccv", "max_issues_repo_head_hexsha": "7fb761f4d8188776dd42b8a06b07ecda7840cd3c", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/cuda/cwc_convnet_ext.c", "max_forks_repo_name": "ChiahungTai/ccv", "max_forks_repo_head_hexsha": "7fb761f4d8188776dd42b8a06b07ecda7840cd3c", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.2965779468, "max_line_length": 391, "alphanum_fraction": 0.6598414795, "num_tokens": 3471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.028007521417299727, "lm_q1q2_score": 0.01312966351546388}}
{"text": "/*\n This file forms part of hpGEM. This package has been developed over a number of\n years by various people at the University of Twente and a full list of\n contributors can be found at http://hpgem.org/about-the-code/team\n\n This code is distributed using BSD 3-Clause License. A copy of which can found\n below.\n\n\n Copyright (c) 2020, University of Twente\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\n 3. Neither the name of the copyright holder nor the names of its contributors\n may be used to endorse or promote products derived from this software without\n specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n#ifndef HPGEM_MATRIXBLOCKS_H\n#define HPGEM_MATRIXBLOCKS_H\n\n#include <vector>\n#include <petsc.h>\n\n#include \"LinearAlgebra/MiddleSizeMatrix.h\"\n\nnamespace DGMax {\n\nusing namespace hpgem;\n\n/// A block from the global matrix, or a pair of blocks that are placed\n/// symmetrically.\nclass MatrixBlocks {\n   public:\n    MatrixBlocks(std::vector<PetscInt> rowIndices,\n                 std::vector<PetscInt> columnIndices,\n                 LinearAlgebra::MiddleSizeMatrix block)\n        : rowIndices_(std::move(rowIndices)),\n          columnIndices_(std::move(columnIndices)),\n          block1_(std::move(block)),\n          pair_(false){};\n\n    MatrixBlocks(std::vector<PetscInt> rowIndices,\n                 std::vector<PetscInt> columnIndices,\n                 LinearAlgebra::MiddleSizeMatrix block1,\n                 LinearAlgebra::MiddleSizeMatrix block2)\n        : rowIndices_(std::move(rowIndices)),\n          columnIndices_(std::move(columnIndices)),\n          block1_(std::move(block1)),\n          block2_(std::move(block2)),\n          pair_(true){};\n\n    /// Number of entries in the matrix block. If this is pair, then this gives\n    /// the size of a single block.\n    std::size_t getBlockSize() const {\n        return rowIndices_.size() * columnIndices_.size();\n    }\n\n    /// Whether this is a pair of blocks or a single block.\n    bool isPair() const { return pair_; }\n\n    /// \\brief Load blocks into temporary storage for insertion.\n    ///\n    /// This stores the raw entries of the block in the storage space for use\n    /// with insertBlocks(). The first getBlockSize() entries of the storage are\n    /// used for storing the first matrix block. If this object is a pair then\n    /// the subsequent getBlockSize() entries will be used for the second block.\n    ///\n    /// \\param storage The storage to use, will be resized if necessary.\n    void loadBlocks(std::vector<PetscScalar>& storage) const {\n        // Make sure we have enough space\n        std::size_t storageSize = getBlockSize();\n        std::size_t storageMultiplier = pair_ ? 2 : 1;\n        if (storage.size() < storageMultiplier * storageSize) {\n            storage.resize(storageMultiplier * storageSize);\n        }\n        // Copy data\n        for (std::size_t i = 0; i < storageSize; ++i) {\n            storage[i] = block1_[i];\n        }\n        if (pair_) {\n            for (std::size_t i = 0; i < storageSize; ++i) {\n                storage[i + storageSize] = block2_[i];\n            }\n        }\n    }\n\n    /// \\brief Insert the block or blocks in a PetscMatrix.\n    void insertBlocks(std::vector<PetscScalar>& storage, Mat mat) const {\n        insertBlock(storage, false, mat);\n        if (pair_) {\n            insertBlock(storage, true, mat);\n        }\n    }\n\n   private:\n    /// The global indices for the rows\n    std::vector<PetscInt> rowIndices_;\n    /// The global indices for the columns\n    std::vector<PetscInt> columnIndices_;\n\n    /// The primary block\n    LinearAlgebra::MiddleSizeMatrix block1_;\n    /// The symmetrically placed block\n    LinearAlgebra::MiddleSizeMatrix block2_;\n\n    /// Whether this is a single block or a symmetrically placed pair.\n    bool pair_;\n\n    /// Helper function inserting a single block.\n    void insertBlock(std::vector<PetscScalar>& storage, bool hermitianPart,\n                     Mat mat) const;\n\n    /// Validate the correctnees\n    void validate() const;\n};\n\n}  // namespace DGMax\n\n#endif  // HPGEM_MATRIXBLOCKS_H\n", "meta": {"hexsha": "0c2a331b3719d0e0062451d01f1ed3341377db95", "size": 5277, "ext": "h", "lang": "C", "max_stars_repo_path": "applications/DG-Max/Utils/MatrixBlocks.h", "max_stars_repo_name": "hpgem/hpgem", "max_stars_repo_head_hexsha": "b2f7ac6bdef3262af0c3e8559cb991357a96457f", "max_stars_repo_licenses": ["BSD-3-Clause-Clear"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-04-01T15:35:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T02:48:12.000Z", "max_issues_repo_path": "applications/DG-Max/Utils/MatrixBlocks.h", "max_issues_repo_name": "hpgem/hpgem", "max_issues_repo_head_hexsha": "b2f7ac6bdef3262af0c3e8559cb991357a96457f", "max_issues_repo_licenses": ["BSD-3-Clause-Clear"], "max_issues_count": 139.0, "max_issues_repo_issues_event_min_datetime": "2020-01-06T12:42:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T20:58:14.000Z", "max_forks_repo_path": "applications/DG-Max/Utils/MatrixBlocks.h", "max_forks_repo_name": "hpgem/hpgem", "max_forks_repo_head_hexsha": "b2f7ac6bdef3262af0c3e8559cb991357a96457f", "max_forks_repo_licenses": ["BSD-3-Clause-Clear"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-04-10T09:19:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-21T07:20:42.000Z", "avg_line_length": 37.6928571429, "max_line_length": 80, "alphanum_fraction": 0.6892173583, "num_tokens": 1172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.028007519084778953, "lm_q1q2_score": 0.013129662422000005}}
{"text": "#pragma once\n\n#include \"mexObjectiveFunction.h\"\n\n#include <nlopt.h>\n#include <mex.h>\n\n#include <string>\n#include <unordered_map>\n#include <utility>\n\n#ifndef MX_CURRENT_API_VER\n#define mxIsScalar(A) (mxGetNumberOfElements(A)==1)\n#endif\n\n#define MEX_ACTION_ARGUMENTS const mxArray *mxObj, int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n// The class that we are interfacing to\nclass mexNLopt\n{\npublic:\n  mexNLopt(const mxArray *mxObj, int nrhs, const mxArray *prhs[]) : opt(NULL) { init(prhs[0], prhs[1]); }\n\n  /**\n   * \\brief Copy constructor\n   */\n  mexNLopt(const mexNLopt &src) : opt(nlopt_copy(src.opt)) {}\n\n  /**\n   * \\brief Move constructor\n   */\n  mexNLopt(mexNLopt &&src) : opt(std::move(src.opt)) {}\n\n  /**\n   * \\brief Destructor\n   */\n  ~mexNLopt() { if (opt) nlopt_destroy(opt); }\n\n  /**\n   * \\brief Copy assignment\n   */\n  mexNLopt &operator=(const mexNLopt &src);\n\n  /**\n   * \\brief Copy assignment\n   */\n  mexNLopt &operator=(mexNLopt &&src) noexcept;\n\n  /**\n   * \\brief Returns the wrapping MATLAB class name\n   */\n  static std::string get_classname() { return \"nlopt.options\"; }; // must match the Matlab classname\n\n  /**\n   * \\brief Performs static (object-independent) actions\n   */\n  static bool static_handler(std::string command, int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]);\n\n  /**\n   * \\brief Performs object-dependent actions\n   */\n  bool action_handler(const mxArray *mxObj, const std::string &command, int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]);\n\nprivate:\n  /**\n * \\brief Return NLopt version string\n */\n  static mxArray *getNLoptVersion();\n\n  /**\n * \\brief Return algorithm name given algorithm enum\n */\n  static std::string get_algorithm_name_string(nlopt_algorithm a);\n\n  /**\n * \\brief Return algorithm name given algorithm enum\n */\n  static mxArray *get_algorithm_name(nlopt_algorithm a);\n\n  /**\n * \\brief Return algorithm description given algorithm enum\n */\n  static mxArray *get_algorithm_desc(nlopt_algorithm a);\n\n  /**\n * \\brief Iterate over algorithms performing unary function on each element\n * \n * \\note signature for f: \\code bool f(const nlopt_algorithm a) \\endcode \n * \\note if f returns false, iteration stops immediately\n */\n  template <class UnaryFunction>\n  static void for_each_algorithm(UnaryFunction f)\n  {\n    for (int n = 0; n < (int)NLOPT_NUM_ALGORITHMS && f((nlopt_algorithm)n); ++n)\n      ;\n  }\n\n  /**\n * \\brief Returns a cellstr array of all available algorithms\n */\n  static mxArray *getAlgorithms(const mxArray *incl_desc);\n\n  /**\n * \\brief Returns algorithm given by mxString\n */\n  static nlopt_algorithm find_algorithm_by_name(const mxArray *mxStr);\n\n  nlopt_opt opt; /** nlopt_opt \"object\" (an opaque pointer) */\n\n  /**\n * \\brief Initialize nlopt object\n */\n  void init(const mxArray *mxAlgorithm, const mxArray *mxDim);\n\n  // GET ROUTINES\n\n  void getAlgorithm(MEX_ACTION_ARGUMENTS) const { plhs[0] = mexNLopt::get_algorithm_name(nlopt_get_algorithm(opt)); }\n  void getDimension(MEX_ACTION_ARGUMENTS) const { plhs[0] = mxCreateDoubleScalar((double)nlopt_get_dimension(opt)); }\n\n  /* stopping criteria: */\n  void getStopVal(MEX_ACTION_ARGUMENTS) const { plhs[0] = mxCreateDoubleScalar(nlopt_get_stopval(opt)); }\n  void getFTolRel(MEX_ACTION_ARGUMENTS) const { plhs[0] = mxCreateDoubleScalar(nlopt_get_ftol_rel(opt)); }\n  void getXTolRel(MEX_ACTION_ARGUMENTS) const { plhs[0] = mxCreateDoubleScalar(nlopt_get_xtol_rel(opt)); }\n  void getFTolAbs(MEX_ACTION_ARGUMENTS) const { plhs[0] = mxCreateDoubleScalar(nlopt_get_ftol_abs(opt)); }\n  void getXTolAbs(MEX_ACTION_ARGUMENTS) const;\n  void getMaxEval(MEX_ACTION_ARGUMENTS) const { plhs[0] = mxCreateDoubleScalar((double)nlopt_get_maxeval(opt)); }\n  void getMaxTime(MEX_ACTION_ARGUMENTS) const { plhs[0] = mxCreateDoubleScalar(nlopt_get_maxtime(opt)); }\n  void getPopulation(MEX_ACTION_ARGUMENTS) const { plhs[0] = mxCreateDoubleScalar((double)nlopt_get_population(opt)); }\n  void getVectorStorage(MEX_ACTION_ARGUMENTS) const { plhs[0] = mxCreateDoubleScalar((double)nlopt_get_vector_storage(opt)); }\n  void getInitialStep(MEX_ACTION_ARGUMENTS) const;\n  mxArray *getInitialStep(const mxArray *x0) const;\n\n  // SET ROUTINES\n  void setStopVal(MEX_ACTION_ARGUMENTS)\n  {\n    double sval = mxGetScalar(prhs[0]);\n    nlopt_set_stopval(opt, isinf(sval) ? (sval > 0) ? HUGE_VAL : -HUGE_VAL : sval);\n  }\n  void setFTolRel(MEX_ACTION_ARGUMENTS) { nlopt_set_ftol_rel(opt, mxGetScalar(prhs[0])); }\n  void setXTolRel(MEX_ACTION_ARGUMENTS) { nlopt_set_xtol_rel(opt, mxGetScalar(prhs[0])); }\n  void setFTolAbs(MEX_ACTION_ARGUMENTS) { nlopt_set_ftol_abs(opt, mxGetScalar(prhs[0])); }\n  void setXTolAbs(MEX_ACTION_ARGUMENTS)\n  {\n    if (mxIsScalar(prhs[0]))\n      nlopt_set_xtol_abs1(opt, mxGetScalar(prhs[0]));\n    else\n      nlopt_set_xtol_abs(opt, mxGetPr(prhs[0]));\n  }\n  void setMaxEval(MEX_ACTION_ARGUMENTS) { nlopt_set_maxeval(opt, (int)mxGetScalar(prhs[0])); }\n  void setMaxTime(MEX_ACTION_ARGUMENTS) { nlopt_set_maxtime(opt, mxGetScalar(prhs[0])); }\n  void setPopulation(MEX_ACTION_ARGUMENTS) { nlopt_set_population(opt, (unsigned)mxGetScalar(prhs[0])); }\n  void setVectorStorage(MEX_ACTION_ARGUMENTS) { nlopt_set_vector_storage(opt, (unsigned)mxGetScalar(prhs[0])); }\n  void setInitialStep(MEX_ACTION_ARGUMENTS)\n  {\n    if (mxIsChar(prhs[0])) // 'auto'\n      nlopt_set_initial_step(opt, NULL);\n    else if (mxIsScalar(prhs[0]))\n      nlopt_set_initial_step1(opt, mxGetScalar(prhs[0]));\n    else\n      nlopt_set_initial_step(opt, mxGetPr(prhs[0]));\n  }\n\n  // OPTIMIZATION ROUTINES\n  void fminunc(MEX_ACTION_ARGUMENTS);\n  void fmincon(MEX_ACTION_ARGUMENTS);\n  void fminbnd(MEX_ACTION_ARGUMENTS);\n\n  // common routine to run and gather the outcome\n  static void config_obj_fun(nlopt_opt opt, mexObjectiveFunction &data);\n  static void run_n_report(int nlhs, mxArray *plhs[], nlopt_opt opt, mexObjectiveFunction &data);\n  \n  // routine to set subproblem options\n  static void set_local_optimizer(nlopt_opt opt, const mxArray *mxObj);\n\n  static void set_bounds(nlopt_opt opt, const mxArray *mxLB, const mxArray *mxUB);\n\n  // map of actions\n  typedef void (mexNLopt::*action_fcn)(MEX_ACTION_ARGUMENTS);\n  static const std::unordered_map<std::string, action_fcn> action_map;\n\n  typedef void (mexNLopt::*const_action_fcn)(MEX_ACTION_ARGUMENTS) const;\n  static const std::unordered_map<std::string, const_action_fcn> const_action_map;\n};\n", "meta": {"hexsha": "a5ed2fdd0b145c0c43194e113fbb0e71014e3d87", "size": 6499, "ext": "h", "lang": "C", "max_stars_repo_path": "+nlopt/@options/mexNLopt.h", "max_stars_repo_name": "hokiedsp/matlab-nlopt", "max_stars_repo_head_hexsha": "19d3de4d2d3ad80a247dfc95fb1e43faae92a19f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-07-30T06:35:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-02T05:57:14.000Z", "max_issues_repo_path": "+nlopt/@options/mexNLopt.h", "max_issues_repo_name": "hokiedsp/matlab-nlopt", "max_issues_repo_head_hexsha": "19d3de4d2d3ad80a247dfc95fb1e43faae92a19f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-09-22T03:36:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-25T01:13:12.000Z", "max_forks_repo_path": "+nlopt/@options/mexNLopt.h", "max_forks_repo_name": "hokiedsp/matlab-nlopt", "max_forks_repo_head_hexsha": "19d3de4d2d3ad80a247dfc95fb1e43faae92a19f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-04-23T09:52:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T02:23:20.000Z", "avg_line_length": 34.9408602151, "max_line_length": 132, "alphanum_fraction": 0.7154946915, "num_tokens": 1805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33111972642778714, "lm_q2_score": 0.039638838675531425, "lm_q1q2_score": 0.013125201418157154}}
{"text": "/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*\n**                                                                                  **\n** This file forms part of the Underworld geophysics modelling application.         **\n**                                                                                  **\n** For full license and copyright information, please refer to the LICENSE.md file  **\n** located at the project root, or contact the authors.                             **\n**                                                                                  **\n**~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/\n#ifndef __BSSCR_MG_h__\n#define __BSSCR_MG_h__\n\n#include <petsc.h>\n#include <petscmat.h>\n#include <petscvec.h>\n#include <petscksp.h>\n#include <petscpc.h>\n#include <StGermain/StGermain.h>\n#include <StgDomain/StgDomain.h>\n#include <StgFEM/StgFEM.h>\n#include <PICellerator/PICellerator.h>\n#include <Underworld/Underworld.h>\n#include \"Solvers/KSPSolvers/KSPSolvers.h\"\n\n#include \"common-driver-utils.h\"\n#include \"BSSCR.h\" /* includes StokesBlockKSPInterface.h */\n\n#define KSPBSSCR         \"bsscr\"\n\ntypedef struct {\n  KSP ksp;\n  PC pc;\n\n  PetscTruth useAcceleratingSmoothingMG;\n  PetscTruth acceleratingSmoothingMGView;\n\n  /* mg_accelerating_smoothing options */\n  \n  PetscInt smoothsMax;\n  PetscInt smoothsToStartWith;\n  PetscInt currentNumberOfSmooths;\n  PetscInt smoothingIncrement;\n  PetscInt targetCyclesForTenfoldReduction;\n  \n  PetscInt smoothingCountThisSolve;\n  PetscInt totalSmoothingCount;\n  PetscInt totalMgCycleCount;  \n} MGContext;\n\nPetscErrorCode KSPCycleEffectivenessMonitorAndAdjust(KSP ksp, PetscInt n, PetscReal rnorm, void *_mgctx );\n//PetscErrorCode MG_inner_solver_mgContext_initialise(MGContext *mgCtx);\nPetscErrorCode MG_inner_solver_pcmg_shutdown( PC pc_MG );\n//PetscErrorCode BSSCR_mgPCApply( void *ctx, Vec x, Vec y );\n//PetscErrorCode BSSCR_mgPCAccelerating( void *ctx, Vec x, Vec y );\ndouble setupMG( KSP_BSSCR * bsscrp_self, KSP ksp_inner, PC pc_MG, Mat K, MGContext *mgCtx );\n#endif\n\n", "meta": {"hexsha": "9e27c4915cf4b15fddd3e0ad66a5b0018e6ffda7", "size": 2105, "ext": "h", "lang": "C", "max_stars_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/mg.h", "max_stars_repo_name": "longgangfan/underworld2", "max_stars_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 116.0, "max_stars_repo_stars_event_min_datetime": "2015-09-28T10:30:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T04:12:38.000Z", "max_issues_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/mg.h", "max_issues_repo_name": "longgangfan/underworld2", "max_issues_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 561.0, "max_issues_repo_issues_event_min_datetime": "2015-09-29T06:05:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T23:37:29.000Z", "max_forks_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/mg.h", "max_forks_repo_name": "longgangfan/underworld2", "max_forks_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 68.0, "max_forks_repo_forks_event_min_datetime": "2015-12-14T21:57:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-25T04:54:26.000Z", "avg_line_length": 36.9298245614, "max_line_length": 106, "alphanum_fraction": 0.6057007126, "num_tokens": 644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326184801538616, "lm_q2_score": 0.028870909035235398, "lm_q1q2_score": 0.013086081583194907}}
{"text": "/*! @copyright (c) 2017 King Abdullah University of Science and\n *                      Technology (KAUST). All rights reserved.\n *\n * STARS-H is a software package, provided by King Abdullah\n *             University of Science and Technology (KAUST)\n *\n * @file include/common.h\n *\n * @cond\n * This command in pair with endcond will prevent file from being documented.\n *\n * @version 0.3.0\n * @author Aleksandr Mikhalev\n * @date 2020-06-09\n * */\n\n#ifndef __COMMON_H__\n#define __COMMON_H__\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <complex.h>\n#include <limits.h>\n#include <stdint.h>\n\n#ifdef MKL\n    #include <mkl.h>\n#else\n    #include <cblas.h>\n    #include <lapacke.h>\n#endif\n\n#ifdef OPENMP\n    #include <omp.h>\n#endif\n\n#ifdef MPI\n    #include <mpi.h>\n    #ifndef SIZE_MAX\n        #error \"SIZE_MAX not defined\"\n    #endif\n    #if SIZE_MAX == UCHAR_MAX\n       #define my_MPI_SIZE_T MPI_UNSIGNED_CHAR\n    #elif SIZE_MAX == USHRT_MAX\n       #define my_MPI_SIZE_T MPI_UNSIGNED_SHORT\n    #elif SIZE_MAX == UINT_MAX\n       #define my_MPI_SIZE_T MPI_UNSIGNED\n    #elif SIZE_MAX == ULONG_MAX\n       #define my_MPI_SIZE_T MPI_UNSIGNED_LONG\n    #elif SIZE_MAX == ULLONG_MAX\n       #define my_MPI_SIZE_T MPI_UNSIGNED_LONG_LONG\n    #else\n       #error \"No MPI data type fits size_t\"\n    #endif\n#endif\n\n#ifdef STARPU\n    #include <starpu.h>\n#endif\n\n#ifdef GSL\n    #include <gsl/gsl_sf_bessel.h>\n    #include <gsl/gsl_sf_gamma.h>\n#endif\n\n#define STARSH_ERROR(format, ...)\\\n{\\\n    fprintf(stderr, \"STARSH ERROR: %s(): \", __func__);\\\n    fprintf(stderr, format, ##__VA_ARGS__);\\\n    fprintf(stderr, \"\\n\");\\\n}\n\n#ifdef SHOW_WARNINGS\n    #define STARSH_WARNING(format, ...)\\\n    {\\\n        fprintf(stderr, \"STARSH WARNING: %s(): \", __func__);\\\n        fprintf(stderr, format, ##__VA_ARGS__);\\\n        fprintf(stderr, \"\\n\");\\\n    }\n#else\n    #define STARSH_WARNING(...)\n#endif\n\n#define STARSH_MALLOC(var, expr_nitems)\\\n{\\\n    var = malloc(sizeof(*var)*(expr_nitems));\\\n    if(!var)\\\n    {\\\n        STARSH_ERROR(\"line %d: malloc() failed\", __LINE__);\\\n        return STARSH_MALLOC_ERROR;\\\n    }\\\n}\n\n#define STARSH_REALLOC(var, expr_nitems)\\\n{\\\n    var = realloc(var, sizeof(*var)*(expr_nitems));\\\n    if(!var)\\\n    {\\\n        STARSH_ERROR(\"malloc() failed\");\\\n        return STARSH_MALLOC_ERROR;\\\n    }\\\n}\n\n#define STARSH_PMALLOC(var, expr_nitems, var_info)\\\n{\\\n    var = malloc(sizeof(*var)*(expr_nitems));\\\n    if(!var)\\\n    {\\\n        STARSH_ERROR(\"malloc() failed\");\\\n        var_info = STARSH_MALLOC_ERROR;\\\n    }\\\n}\n\n#define STARSH_PREALLOC(var, expr_nitems, var_info)\\\n{\\\n    var = realloc(var, sizeof(*var)*(expr_nitems));\\\n    if(!var)\\\n    {\\\n        STARSH_ERROR(\"malloc() failed\");\\\n        var_info = STARSH_MALLOC_ERROR;\\\n    }\\\n}\n\nint cmp_size_t(const void *a, const void *b);\n\n#endif // __COMMON_H__\n\n//! @endcond\n", "meta": {"hexsha": "90c4b846603e3aa5bb504664729fb4b2aee402ab", "size": 2857, "ext": "h", "lang": "C", "max_stars_repo_path": "include/common.h", "max_stars_repo_name": "enp1s0/stars-h", "max_stars_repo_head_hexsha": "380a5d41be2931e89629e1bdca95db1fdab066cc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-11-22T22:28:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T07:35:59.000Z", "max_issues_repo_path": "include/common.h", "max_issues_repo_name": "enp1s0/stars-h", "max_issues_repo_head_hexsha": "380a5d41be2931e89629e1bdca95db1fdab066cc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-11-04T01:10:54.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-08T20:01:54.000Z", "max_forks_repo_path": "include/common.h", "max_forks_repo_name": "enp1s0/stars-h", "max_forks_repo_head_hexsha": "380a5d41be2931e89629e1bdca95db1fdab066cc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-11-12T16:28:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T18:08:24.000Z", "avg_line_length": 21.8091603053, "max_line_length": 77, "alphanum_fraction": 0.6310815541, "num_tokens": 780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2628418489200747, "lm_q2_score": 0.0495890231596045, "lm_q1q2_score": 0.013034070533410852}}
{"text": "#ifndef CONSTANTS_H\n#define CONSTANTS_H\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n#include <limits.h>\n#include <math.h>\n#include <time.h>\n#include <float.h>\n#include <utils/version.h>\n#include <utils/help.h>\n#include <utils/error.h>\n#include <gsl/gsl_statistics_double.h>\n\n/*\n * MIN macro\n */\n#define MIN(a,b) (((a)<(b))?(a):(b))\n\n/*\n * MAX macro\n */\n#define MAX(a,b) (((a)>(b))?(a):(b))\n\n/*\n * STR macro\n */\n#define STR(a) ((a > 0)?(\"-\"):(\"+\"))\n\n/*\n * Default value for read_minlen parameter\n */\n#define MIN_READ_LEN 0\n\n/*\n * Default value for minlen parameter\n */\n#define MIN_LEN 15\n\n/*\n * Default value for maxlen parameter\n */\n#define MAX_LEN 30\n\n/*\n * Default value for spacing parameter\n */\n#define SPACING 20\n\n/*\n * Default value for minheight parameter\n */\n#define MIN_READS 10.0f\n\n/*\n * Default value for trimming threshold parameter\n */\n#define TRIM_THRESHOLD 0.05\n\n/*\n * Default value for minimum trimming parameter\n */\n#define TRIM_MIN 2\n\n/*\n * Default value for maximum trimming parameter\n */\n#define TRIM_MAX 20\n\n/*\n * Default value for IDR cutoff\n */\n#define CUTOFF 2.0f\n\n/*\n * Default value for Replicate number\n */\n#define REPLICATE_NUMBER 1\n\n/*\n * Replicate treatment options\n */\n#define REPLICATE_POOL_STR \"pool\" // default value\n#define REPLICATE_MEAN_STR \"mean\"\n#define REPLICATE_REPLICATE_STR \"replicate\"\n#define REPLICATE_POOL 0\n#define REPLICATE_MEAN 1\n#define REPLICATE_REPLICATE 2\n\n/*\n * IDR method options\n */\n#define IDR_COMMON_STR \"common\" // default value\n#define IDR_NONE_STR \"none\"\n#define IDR_SERE_STR \"sere\"\n#define IDR_IDR_STR \"idr\"\n#define IDR_COMMON 0\n#define IDR_NONE 1\n#define IDR_SERE 2\n#define IDR_IDR 3\n\n/*\n * Maximum length of a contig\n */\n#define MAX_CONTIG_LENGTH 200\n\n/*\n * Maximum number of contigs\n */\n#define MAX_CONTIGS 10000000\n\n/*\n * Maximum size, in chars, of an error message\n */\n#define MAX_ERR_MSG 100\n\n/*\n * Maximum size, in chars, of a given path\n */\n#define MAX_PATH 500\n\n/*\n * Maximum size, in chars, of the 4th field (name) in the query BED file\n */\n#define MAX_FEATURE 50\n\n/*\n * Maximum number of replicates\n */\n#define MAX_REPLICATES 10 \n\n/*\n * Maximum number of alignments per heap\n */\n#define MAX_ALIGN_HEAP 50000000\n\n/*\n * Maximum read length\n */\n#define MAX_READ_LENGTH 200\n\n/*\n * Maximum profile length\n */\n#define MAX_PROFILE_LENGTH 500\n\n/*\n * Maximum number of block base pairs\n */\n#define MAX_BLOCK 3000\n\n/*\n * Alignment strand\n */\n#define FWD_STRAND 0 // forward/watson\n#define REV_STRAND 1 // reverse/crick\n\n/*\n * Alignment validity\n */\n#define VALID_ALIGNMENT 1\n#define INVALID_ALIGNMENT 0\n\n/*\n * Constants for npIDR method\n */\n#define ABSOLUTE 0\n#define CONDITIONAL 1 \n\n/*\n * Path separator\n */\n#ifdef __unix__\n  #define PATH_SEPARATOR \"/\"\n#else\n  #define PATH_SEPARATOR \"\\\\\"\n#endif\n\n/*\n * Output file suffixes\n */\n#define PROFILES_SUFFIX \"profiles.dat\"\n#define CONTIGS_SUFFIX \"contigs.dat\"\n#define CROSSCOR_SUFFIX \"crosscor.dat\"\n#define CLUSTERS_SUFFIX \"clusters.neWick\"\n#define ANNOTATION_O_SUFFIX \"annotation.bed\" \n#define TMPROFILES_SUFFIX \"tmprofiles.dat\"\n\n/*\n * Maximum N limit for gaussian white noise generation\n */\n#define MAX_GNOISE_N 20\n\n/*\n * Cluster cutoff default value\n */\n#define CLUSTER_CUTOFF -1.0f\n\n/*\n * Condition for existence of annotation file\n */\n#define ANNOTATION_CONDITION 0\n\n/*\n * Condition for existence of additional profiles file\n */\n#define ADDITIONAL_P_CONDITION 0\n\n/*\n * Default value for the feature to profile overlap percentage\n */\n#define OVERLAP_FTOP 0.9\n\n/*\n * Default value for the profile to feature overlap percentage\n */\n#define OVERLAP_PTOF 0.5\n\n/*\n * Maximum number of annotation files\n */\n#define MAX_ANNOTATIONS 10\n\n/*\n * Condition for existence of correlations file\n */\n#define CORRELATIONS_CONDITION 0\n\n/*\n * Constants for profile category\n */\n#define NOVEL 0\n#define KNOWN 1\n\n/*\n * Differential processing default p-value\n */\n#define P_VALUE 0.01\n\n/*\n * Differential processing default overlap\n */\n#define DP_FOLD_CHANGE 7 \n\n/*\n * Suffix for differentially processed profiles\n */\n#define DIFFPROC_PROFILE_O_SUFFIX \"diffprofiles.dat\"\n/*\n * Suffix for differentially processed clusters\n */\n#define DIFFPROC_CLUSTER_O_SUFFIX \"diffclusters.dat\"\n#endif\n", "meta": {"hexsha": "95cd51b66d0e1b22f968732465a91be69afb917c", "size": 4212, "ext": "h", "lang": "C", "max_stars_repo_path": "src/include/core/constants.h", "max_stars_repo_name": "comprna/SeRPeNT", "max_stars_repo_head_hexsha": "40846923672b19a700b84fa332ac5df07ffb86cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-07-27T21:04:23.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-27T21:04:23.000Z", "max_issues_repo_path": "src/include/core/constants.h", "max_issues_repo_name": "comprna/SeRPeNT", "max_issues_repo_head_hexsha": "40846923672b19a700b84fa332ac5df07ffb86cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/include/core/constants.h", "max_forks_repo_name": "comprna/SeRPeNT", "max_forks_repo_head_hexsha": "40846923672b19a700b84fa332ac5df07ffb86cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-10T17:53:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-10T17:53:08.000Z", "avg_line_length": 16.453125, "max_line_length": 72, "alphanum_fraction": 0.7184235518, "num_tokens": 1058, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.02800751766498379, "lm_q1q2_score": 0.0130207389727189}}
{"text": "#include <pygsl/solver.h>\n#include <pygsl/rng.h>\n#include <gsl/gsl_monte.h>\n#include <gsl/gsl_monte_plain.h>\n#include <gsl/gsl_monte_miser.h>\n#include <gsl/gsl_monte_vegas.h>\n\nconst char  * filename = __FILE__;\nPyObject *module = NULL;\nstatic const char monte_f_type_name[] = \"F-monte\";\nstatic const char module_doc[] = \"XXX Missing\";\nstatic const char PyGSL_monte_type[] = \"monte\";\n\nenum PyGSL_gsl_monte_type{\n     PyGSL_MONTE_plain = 1,\n     PyGSL_MONTE_miser = 2,\n     PyGSL_MONTE_vegas = 3\n};\n\nstruct _monte_csys{\n     enum PyGSL_gsl_monte_type type;\n};\n\ntypedef struct _monte_csys monte_csys;\n\nstatic double\nPyGSL_g_test(double *k, size_t dim, void *params)\n{\n     double A = 1.0 / (M_PI * M_PI * M_PI);\n     return A / (1.0 - cos (k[0]) * cos (k[1]) * cos (k[2]));\n}\n\nstatic double\nPyGSL_monte_function_wrap(double *x,  size_t dim, void *params)\n{\n     double tmp, *dresult;\n     int dimension;\n     PyGSL_solver *s;\n     PyArrayObject *a_array = NULL;\n     PyObject *result = NULL, *arglist=NULL, *callback, *retval;\n     PyGSL_error_info  info;\n     /* the line number to appear in the traceback */ \n     int trb_lineno = -1, i;\n     struct pygsl_array_cache * cache_ptr;\n     gsl_vector_view view;\n\n     FUNC_MESS_BEGIN();\n     s = (PyGSL_solver  *) params;\n\n     /*\n     flag = PyGSL_function_wrap_On_O(&view.vector, s->cbs[0], s->args,\n                                     &tmp, NULL, view.vector.size, \n                                     \"monte_wrap\");\n     */\n\n     FUNC_MESS_BEGIN();    \n     callback = s->cbs[0];\n     assert(s->args != NULL);\n     assert(callback != NULL);\n\n     /* Do I need to copy the array ??? */\n     for(i = 2; i < PyGSL_SOLVER_N_ARRAYS; ++i){\n\t  cache_ptr = &(s->cache[i]);\n\t  if(cache_ptr->ref == NULL)\n\t       /* no array found */\n\t       break;\n\t  if(x == cache_ptr->data){\n\t       a_array = cache_ptr->ref;\n\t       break;\n\t  }\n     }\n     if(i >= PyGSL_SOLVER_N_ARRAYS){\n\t  trb_lineno = __LINE__ -1;\n\t  pygsl_error(\"Not enough space to cache arrays...\", filename, trb_lineno, GSL_ESANITY);\n\t  goto fail;\n     }\n     if(a_array == NULL){\n\t  dimension = dim;\n\t  a_array = (PyArrayObject *) PyArray_FromDimsAndData(1, &dimension, PyArray_DOUBLE, (char *)x);\n\t  cache_ptr->ref = a_array;\n\t  cache_ptr->data = x;\n\t  /*\n\t   * Required for deallocation.      \n\t   * Tuples steal the references. But this array will be dereferenced by the\n\t   * normal procedure!\n\t   */\n\t  Py_INCREF(a_array);\n     }\n     if (a_array == NULL){\n\t  trb_lineno = __LINE__ - 2;\n\t  goto fail;\n     }\n     /* arglist was already set up */\n     result = (PyObject *) s->cache[1].ref;\n     dresult = (double *) s->cache[1].data;\n     arglist = (PyObject *) s->cache[0].ref;\n\n     Py_INCREF(s->args);\n     PyTuple_SET_ITEM(arglist, 0, (PyObject *) a_array);\n     PyTuple_SET_ITEM(arglist, 1, s->args);\n\n     /*\n     arglist = Py_BuildValue(\"(OOO)\", a_array, s->args, result);\n     if(DEBUG > 2){\n\t  fprintf(stderr, \"callback = %p, arglist = %p\\n\", callback, arglist);\n     }\n     */\n     FUNC_MESS(\"    Call Python Object BEGIN\");\n     retval = PyEval_CallObject(callback, arglist);\n     FUNC_MESS(\"    Call Python Object END\");\n\n     /*\n     info.callback = callback;\n     info.message  = __FUNCTION__;\n     if(PyGSL_CHECK_PYTHON_RETURN(retval, 0, &info) != GSL_SUCCESS){\n\t  trb_lineno = __LINE__ - 1;\n\t  goto fail;\n     }\n     info.argnum = 1;\n     DEBUG_MESS(3, \"result was %e\", *dresult);\n     */\n     FUNC_MESS_END();\n     return *dresult;\n\n\n fail:\n     PyGSL_add_traceback(NULL, __FILE__, __FUNCTION__, trb_lineno);\n     FUNC_MESS(\"Failure\");\n\n     if(s->isset == 1){\n\t  longjmp(s->buffer, GSL_EFAILED);\n\t  FUNC_MESS(\"\\t\\t Using jump buffer\");\n     } else {\n\t  FUNC_MESS(\"\\t\\t Jump buffer was not defined!\");\n     }\n     tmp = gsl_nan();\n     return tmp;\n}\n\nstatic PyObject *\nPyGSL_monte_init(PyGSL_solver *self, PyObject *args)\n{\n     int flag = GSL_EFAILED;\n     monte_csys * csys;\n     \n     FUNC_MESS_BEGIN();\n     assert(PyGSL_solver_check(self));\n     csys = (monte_csys *)self->c_sys;\n     assert(csys);\n     switch(csys->type){\n     case PyGSL_MONTE_plain:\n\t  flag = gsl_monte_plain_init(self->solver);\n\t  break;\n     case PyGSL_MONTE_miser:\n\t  flag = gsl_monte_miser_init(self->solver);\n\t  break;\n     case PyGSL_MONTE_vegas:\n\t  flag = gsl_monte_vegas_init(self->solver);\n\t  break;\n     default:\n\t  DEBUG_MESS(2, \"Monte type %d unknown\",flag);\n\t  PyGSL_ERROR_NULL(\"Unknown monte type!\", GSL_ESANITY);\n     }\n\n     if(PyGSL_ERROR_FLAG(flag) != GSL_SUCCESS){\n\t  PyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__);\n\t  return NULL;\n     }\n     Py_INCREF(Py_None);\n     FUNC_MESS_END();\n     return Py_None;\n}\n\ntypedef int (*pygsl_monte_fptr_t)(gsl_monte_function * F, double XL[], double XU[], size_t DIM,\n\t\t     size_t CALLS, gsl_rng * R, gsl_monte_plain_state * S, \n\t\t     double * RESULT, double * ABSERR);\n\nstatic PyObject *\nPyGSL_monte_integrate(PyGSL_solver *self, PyObject *args)\n{\n\n     int flag = GSL_EFAILED, line, dim;\n     unsigned int ncalls;\n     monte_csys * csys;\n     gsl_rng * rng;\n     PyObject  *func=NULL, *xlo=NULL, *xuo=NULL, *rng_obj=NULL, *ncallso=NULL, *argso=NULL;\n     PyArrayObject *xla=NULL;\n     PyArrayObject *xua=NULL;\n     double result, abserr;\n     gsl_monte_function mfunc;\n     pygsl_monte_fptr_t fptr;\n\n     FUNC_MESS_BEGIN();\n     assert(PyGSL_solver_check(self));\n     \n     if(!PyArg_ParseTuple(args, \"OOOOO|O\", &func, &xlo, &xuo, &ncallso, &rng_obj, &argso)){\n\t  line = __LINE__ - 1;\n\t  goto fail;\n     }\n\n     if(!PyCallable_Check(func)){\n\t  line = __LINE__ - 1;\n\t  pygsl_error(\"The function argument must be callable!\", filename, line, GSL_EINVAL);\n\t  goto fail;\t  \n     }\n\n     if(PyGSL_PYLONG_TO_UINT(ncallso, &ncalls, NULL) != GSL_SUCCESS){\n\t  line = __LINE__ - 1;\n\t  goto fail;\n     }\n\n     if(!PyGSL_RNG_Check(rng_obj)){\n\t  line = __LINE__ - 1;\n\t  pygsl_error(\"The rng object must be a rng!\", filename, line, GSL_EINVAL);\n\t  goto fail;\n     }\n\n     rng = ((PyGSL_rng *) rng_obj)->rng;\n     \n     xla = PyGSL_vector_check(xlo, -1, PyGSL_DARRAY_CINPUT(2), NULL, NULL);\n     if(xla == NULL){\n\t  line = __LINE__ - 2;\n\t  goto fail;\n     }\n\n     dim = xla->dimensions[0];\n     xua = PyGSL_vector_check(xuo, dim, PyGSL_DARRAY_CINPUT(3), NULL, NULL);\n     if(xua == NULL){\n\t  line = __LINE__ - 2;\n\t  goto fail;\n     }\n\n     if(argso == NULL){\n\t  Py_INCREF(Py_None);\n\t  argso = Py_None;\n     }\n     Py_XDECREF(self->cbs[0]);\n     Py_INCREF(func);\n     self->cbs[0] = func;\n     self->args = argso;\n     csys = (monte_csys *)self->c_sys;\n\n     switch(csys->type){\n     case PyGSL_MONTE_plain:\t  fptr = (pygsl_monte_fptr_t)&gsl_monte_plain_integrate; break;\n     case PyGSL_MONTE_miser:\t  fptr = (pygsl_monte_fptr_t)&gsl_monte_miser_integrate; break;\n     case PyGSL_MONTE_vegas:\t  fptr = (pygsl_monte_fptr_t)&gsl_monte_vegas_integrate; break;\n     default:\n\t  line = __LINE__ - 5;\n\t  DEBUG_MESS(2, \"Monte type %d unknown\",flag);\n\t  pygsl_error(\"Unknown monte type!\", filename, line, GSL_ESANITY);\n\t  goto fail;\n     }\n\n     assert(fptr);\n     mfunc.f = &PyGSL_monte_function_wrap;\n     mfunc.f = &PyGSL_g_test;\n     mfunc.dim = dim;\n     mfunc.params = self;\n\n     if(setjmp(self->buffer) != 0){\n\t  self->isset = 0;\n\t  line = __LINE__ - 2;\n\t  goto fail;\n     }else{\n\t  self->isset = 1;\n     }\n     flag = fptr(&mfunc, (double *) xla->data, (double *)xua->data,\n\t\t dim, ncalls, rng, self->solver, &result, &abserr);\n     self->isset = 0;\n     if(PyGSL_ERROR_FLAG(flag) != GSL_SUCCESS){\n\t  line = __LINE__ - 2;\n\t  return NULL;\n     }\n\n     Py_DECREF(xla);     xla = NULL;\n     Py_DECREF(xua);     xua = NULL;\n     Py_DECREF(self->cbs[0]);\n     Py_DECREF(self->args);\n     self->cbs[0] = NULL;\n     self->args = NULL;\n     FUNC_MESS_END();\n\n     return Py_BuildValue(\"dd\", result, abserr);\n\n fail:\n     FUNC_MESS(\"FAIL\");\n     Py_XDECREF(xla);\n     Py_XDECREF(xua);\n     Py_XDECREF(self->cbs[0]);\n     Py_XDECREF(self->args);\n     self->cbs[0] = NULL;\n     self->args = NULL;\n     PyGSL_add_traceback(module, filename, __FUNCTION__, line);\n     return NULL;\n}\n\n#define GET_SET(montetype, name, mode) \\\nstatic PyObject * GetSet_ ## montetype ## _ ## name(PyGSL_solver *self, PyObject *args) \\\n{ \\\n     gsl_monte_## montetype ## _state *state = self->solver; \\\n     return PyGSL_solver_GetSet((PyObject *)self, args, &(state->name), mode); \\\n}\n\n#define GET_SET_DOUBLE(mintype, name) GET_SET(mintype, name, PyGSL_MODE_DOUBLE)\n#define GET_SET_SIZE_T(mintype, name) GET_SET(mintype, name, PyGSL_MODE_SIZE_T)\n#define GET_SET_INT(mintype, name)    GET_SET(mintype, name, PyGSL_MODE_INT)\n\nGET_SET_DOUBLE(miser, estimate_frac)\nGET_SET_SIZE_T(miser, min_calls)\nGET_SET_SIZE_T(miser, min_calls_per_bisection)\nGET_SET_DOUBLE(miser, alpha)\nGET_SET_DOUBLE(miser, dither)\n\nGET_SET_DOUBLE(vegas, result)\nGET_SET_DOUBLE(vegas, sigma)\nGET_SET_DOUBLE(vegas, chisq)\nGET_SET_DOUBLE(vegas, alpha)\nGET_SET_SIZE_T(vegas, iterations)\nGET_SET_INT(vegas, stage)\nGET_SET_INT(vegas, mode)\nGET_SET_INT(vegas, verbose)\n\n#undef GET_SET_DOUBLE\n#undef GET_SET_SIZE_T\n#undef GET_SET_INT\n#undef GET_SET\n#define GETSET(montetype, name, mode) {#name, (PyCFunction) GetSet_ ## montetype ## _ ## name, METH_VARARGS, NULL},\n#define GET_SET_DOUBLE(montetype, name) GETSET(montetype, name, 0)\n#define GET_SET_INT(montetype, name) GETSET(montetype, name, 0)\n#define GET_SET_SIZE_T(montetype, name) GETSET(montetype, name, 0)\n\n#define MONTE_STANDARD_METHODS \\\n     {\"init\",      (PyCFunction)PyGSL_monte_init,      METH_VARARGS, NULL}, \\\n     {\"integrate\", (PyCFunction)PyGSL_monte_integrate, METH_VARARGS, NULL}, \\\n\nstatic PyMethodDef PyGSL_monte_plain_methods[] = {\n     MONTE_STANDARD_METHODS\n     {NULL, NULL, 0, NULL}\n};\n\nstatic PyMethodDef PyGSL_monte_miser_methods[] = {\n     MONTE_STANDARD_METHODS\n     GET_SET_DOUBLE(miser, estimate_frac)\n     GET_SET_SIZE_T(miser, min_calls)\n     GET_SET_SIZE_T(miser, min_calls_per_bisection)\n     GET_SET_DOUBLE(miser, alpha)\n     GET_SET_DOUBLE(miser, dither)\n     {NULL, NULL, 0, NULL}\n};\n\nstatic PyMethodDef PyGSL_monte_vegas_methods[] = {\n     MONTE_STANDARD_METHODS\n     GET_SET_DOUBLE(vegas, result)\n     GET_SET_DOUBLE(vegas, sigma)\n     GET_SET_DOUBLE(vegas, chisq)\n     GET_SET_DOUBLE(vegas, alpha)\n     GET_SET_SIZE_T(vegas, iterations)\n     GET_SET_INT(vegas, stage)\n     GET_SET_INT(vegas, mode)\n     GET_SET_INT(vegas, verbose)\n     {NULL, NULL, 0, NULL}\n};\n\n\n/* make the init look similar to the one */\nstatic void *\nPyGSL_gsl_monte_alloc(void * type, int n)\n{\n     enum PyGSL_gsl_monte_type flag = (enum PyGSL_gsl_monte_type) type;\n     void * result = NULL;\n\n     FUNC_MESS_BEGIN();\n     switch(flag){\n     case PyGSL_MONTE_plain:\n\t  result = gsl_monte_plain_alloc(n);\n\t  break;\n     case PyGSL_MONTE_miser:\n\t  result = gsl_monte_miser_alloc(n);\n\t  break;\n     case PyGSL_MONTE_vegas:\n\t  result = gsl_monte_vegas_alloc(n);\n\t  break;\n     default:\n\t  DEBUG_MESS(2, \"Monte type %d unknown\",flag);\n\t  PyGSL_ERROR_NULL(\"Unknown monte type!\", GSL_ESANITY);\n     }\n     FUNC_MESS_END();\n     return result;\n}\n\nconst struct _SolverStatic\nmonte_plain_solver_f   = {{(void_m_t) gsl_monte_plain_free,   \n\t\t\t  (void_m_t) NULL,\n\t\t\t  NULL,   \n\t\t\t  NULL},\n\t\t\t  1, PyGSL_monte_plain_methods,  PyGSL_monte_type},\nmonte_miser_solver_f   = {{(void_m_t) gsl_monte_miser_free,   \n\t\t\t  (void_m_t) NULL,\n\t\t\t  NULL,   \n\t\t\t   NULL},\n\t\t\t  1, PyGSL_monte_miser_methods,  PyGSL_monte_type},\nmonte_vegas_solver_f   = {{(void_m_t) gsl_monte_vegas_free,   \n\t\t\t  (void_m_t) NULL,\n\t\t\t  NULL,   \n\t\t\t  NULL},\n\t\t\t  1, PyGSL_monte_vegas_methods,  PyGSL_monte_type};\n\nstatic PyObject*\nPyGSL_init_monte(PyObject *self, PyObject *args, int type, const struct _SolverStatic *sost)\n{\n     PyGSL_solver *result = NULL;\n     struct pygsl_array_cache *tmp;\n     int line = -1, dims;\n     monte_csys * csys;\n     PyObject *mytuple;\n\n     FUNC_MESS_BEGIN();\n     const solver_alloc_struct alloc = {(const void *) type, (void *) PyGSL_gsl_monte_alloc, sost};          \n     result = (PyGSL_solver *) PyGSL_solver_dn_init(self, args, &alloc, 1);\n     if(result == NULL){\n\t  line = __LINE__ - 2;\n\t  goto fail;\n     }\n\t  \n     csys = (monte_csys *) calloc(1, sizeof(monte_csys));\n     if(csys == NULL){\n\t  PyErr_NoMemory();\n\t  line = __LINE__ - 1;\n\t  goto fail;\n     }\n     \n\n     dims = 1;\n     tmp = result->cache;\n\n     tmp[1].ref = PyGSL_New_Array(1, &dims, PyArray_DOUBLE);\n     tmp[1].data = (double *) tmp[1].ref->data;\n     mytuple =  PyTuple_New(3);\n     PyTuple_SetItem(mytuple, 2, (PyObject *) tmp[1].ref);\n     /*\n      * Required for deallocation.      \n      * Tuples steal the references. But this array will be dereferenced by the\n      * normal procedure!\n      */\n     Py_INCREF(tmp[1].ref);\n     Py_INCREF(tmp[1].ref);\n\n     /*\n      * Initalise the others\n      */\n     Py_INCREF(Py_None);\n     Py_INCREF(Py_None);\n     Py_INCREF(Py_None);\n     Py_INCREF(Py_None);\n     PyTuple_SetItem(mytuple, 0, Py_None);\n     PyTuple_SetItem(mytuple, 1, Py_None);\n\n     tmp[0].ref = (PyArrayObject*) mytuple;\n     \n     result->cache = tmp;\n     csys->type = type;\n     result->c_sys = csys;\n\n     FUNC_MESS_END();\n     return (PyObject *) result;\n\n fail:\n     FUNC_MESS(\"Fail\");\n     Py_XDECREF(result);\n     PyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__);\n     return NULL;\n}\n\n#define MONTE_INIT(name) \\\nstatic PyObject* PyGSL_init_ ## name(PyObject * self, PyObject *args) \\\n{ return PyGSL_init_monte(self, args, PyGSL_MONTE_ ##name, &monte_ ## name ## _solver_f); }\n\nMONTE_INIT(plain)\nMONTE_INIT(miser)\nMONTE_INIT(vegas)\n\n\nstatic PyMethodDef mMethods[] = {\n     {\"plain\", PyGSL_init_plain, METH_VARARGS, NULL},\n     {\"miser\", PyGSL_init_miser, METH_VARARGS, NULL},\n     {\"vegas\", PyGSL_init_vegas, METH_VARARGS, NULL},\n     {NULL, NULL, 0, NULL}\n};\n\nvoid\ninitmonte(void)\n{\n     PyObject* m, *dict, *item;\n     FUNC_MESS_BEGIN();\n\n     m=Py_InitModule(\"monte\", mMethods);\n     module = m;\n     assert(m);\n     dict = PyModule_GetDict(m);\n     if(!dict)\n\t  goto fail;\n\n     init_pygsl()\n     import_pygsl_solver();\n     assert(PyGSL_API);\n\n\n     if (!(item = PyString_FromString((char*)module_doc))){\n\t  PyErr_SetString(PyExc_ImportError, \n\t\t\t  \"I could not generate module doc string!\");\n\t  goto fail;\n     }\n     if (PyDict_SetItemString(dict, \"__doc__\", item) != 0){\n\t  PyErr_SetString(PyExc_ImportError, \n\t\t\t  \"I could not init doc string!\");\n\t  goto fail;\n     }\n     PyModule_AddIntConstant(m, \"GSL_VEGAS_MODE_IMPORTANCE\",      GSL_VEGAS_MODE_IMPORTANCE);\n     PyModule_AddIntConstant(m, \"GSL_VEGAS_MODE_IMPORTANCE_ONLY\", GSL_VEGAS_MODE_IMPORTANCE_ONLY);\n     PyModule_AddIntConstant(m, \"GSL_VEGAS_MODE_STRATIFIED\",      GSL_VEGAS_MODE_STRATIFIED);\n     \n     FUNC_MESS_END();\n     return;\n\n fail:\n     FUNC_MESS(\"FAIL\");\n     return;\n\n}\n", "meta": {"hexsha": "6ca5a06119e17608e0563d2644a925e0856f920b", "size": 14706, "ext": "c", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/testing/src/solvers/monte.c", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/testing/src/solvers/monte.c", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/testing/src/solvers/monte.c", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 27.7471698113, "max_line_length": 115, "alphanum_fraction": 0.646130831, "num_tokens": 4447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3593641451601019, "lm_q2_score": 0.03622005521475953, "lm_q1q2_score": 0.013016189179903749}}
{"text": "/***************************************************************************\n * mgl_c.h is part of Math Graphic Library\n * Copyright (C) 2007 Alexey Balakin <balakin@appl.sci-nnov.ru>            *\n *                                                                         *\n *   This program is free software; you can redistribute it and/or modify  *\n *   it under the terms of the GNU Library General Public License as       *\n *   published by the Free Software Foundation; either version 3 of the    *\n *   License, or (at your option) any later version.                       *\n *                                                                         *\n *   This program is distributed in the hope that it will be useful,       *\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\n *   GNU General Public License for more details.                          *\n *                                                                         *\n *   You should have received a copy of the GNU Library General Public     *\n *   License along with this program; if not, write to the                 *\n *   Free Software Foundation, Inc.,                                       *\n *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *\n ***************************************************************************/\n#ifndef _MGL_C_H_\n#define _MGL_C_H_\n\n#include <mgl/config.h>\n\n#if(MGL_USE_DOUBLE==1)\ntypedef double mreal;\n#else\ntypedef float mreal;\n#endif\n//#include <mgl/mgl_define.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n/*****************************************************************************/\n//#ifdef _MGL_DATA_H_\n#ifdef __cplusplus\nstruct mglDraw;\ntypedef mglDraw* HMDR;\nclass mglGraph;\ntypedef mglGraph* HMGL;\nclass mglData;\ntypedef mglData* HMDT;\nclass mglParse;\ntypedef mglParse* HMPR;\n#else\ntypedef void* HMDR;\ntypedef void* HMGL;\ntypedef void* HMDT;\ntypedef void* HMPR;\n#endif\n#ifndef NO_GSL\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#else\nstruct gsl_vector;\nstruct gsl_matrix;\n#endif\n/*****************************************************************************/\nHMGL mgl_create_graph_gl();\nHMGL mgl_create_graph_zb(int width, int height);\nHMGL mgl_create_graph_ps(int width, int height);\nHMGL mgl_create_graph_idtf();\n#ifndef MGL_NO_WIDGET\nint mgl_fortran_func(HMGL gr, void *);\nHMGL mgl_create_graph_glut(int (*draw)(HMGL gr, void *p), const char *title, void *par);\nHMGL mgl_create_graph_fltk(int (*draw)(HMGL gr, void *p), const char *title, void *par);\nHMGL mgl_create_graph_qt(int (*draw)(HMGL gr, void *p), const char *title, void *par);\nHMGL mgl_create_graph_glut_dr(HMDR dr, const char *title);\nHMGL mgl_create_graph_fltk_dr(HMDR dr, const char *title);\nHMGL mgl_create_graph_qt_dr(HMDR dr, const char *title);\nvoid mgl_fltk_run();\nvoid mgl_qt_run();\n\nvoid mgl_wnd_set_delay(HMGL gr, mreal dt);\nvoid mgl_wnd_set_auto_clf(HMGL gr, int val);\nvoid mgl_wnd_set_show_mouse_pos(HMGL gr, int val);\nvoid mgl_wnd_set_clf_update(HMGL gr, int val);\nvoid mgl_wnd_toggle_alpha(HMGL gr);\nvoid mgl_wnd_toggle_light(HMGL gr);\nvoid mgl_wnd_toggle_zoom(HMGL gr);\nvoid mgl_wnd_toggle_rotate(HMGL gr);\nvoid mgl_wnd_toggle_no(HMGL gr);\nvoid mgl_wnd_update(HMGL gr);\nvoid mgl_wnd_reload(HMGL gr, int o);\nvoid mgl_wnd_adjust(HMGL gr);\nvoid mgl_wnd_next_frame(HMGL gr);\nvoid mgl_wnd_prev_frame(HMGL gr);\nvoid mgl_wnd_animation(HMGL gr);\n#endif\nvoid mgl_set_show_mouse_pos(HMGL gr, int enable);\nvoid mgl_get_last_mouse_pos(HMGL gr, mreal *x, mreal *y, mreal *z);\nvoid mgl_calc_xyz(HMGL gr, int xs, int ys, mreal *x, mreal *y, mreal *z);\nvoid mgl_calc_scr(HMGL gr, mreal x, mreal y, mreal z, int *xs, int *ys);\n//void mgl_fltk_thread();\n//void mgl_qt_thread();\nvoid mgl_update(HMGL graph);\nvoid mgl_delete_graph(HMGL graph);\n/*****************************************************************************/\nHMDT mgl_create_data();\nHMDT mgl_create_data_size(int nx, int ny, int nz);\nHMDT mgl_create_data_file(const char *fname);\nvoid mgl_delete_data(HMDT dat);\n/*****************************************************************************/\nHMPR mgl_create_parser();\nvoid mgl_delete_parser(HMPR p);\nvoid mgl_scan_func(HMPR p, const wchar_t *line);\nvoid mgl_add_param(HMPR p, int id, const char *str);\nvoid mgl_add_paramw(HMPR p, int id, const wchar_t *str);\n/*===!!! NOTE !!! You must not delete obtained data arrays !!!===============*/\nHMDT mgl_add_var(HMPR, const char *name);\n/*===!!! NOTE !!! You must not delete obtained data arrays !!!===============*/\nHMDT mgl_find_var(HMPR, const char *name);\nint mgl_parse(HMGL gr, HMPR p, const char *str, int pos);\nint mgl_parsew(HMGL gr, HMPR p, const wchar_t *str, int pos);\nvoid mgl_parse_text(HMGL gr, HMPR p, const char *str);\nvoid mgl_parsew_text(HMGL gr, HMPR p, const wchar_t *str);\nvoid mgl_restore_once(HMPR p);\nvoid mgl_parser_allow_setsize(HMPR p, int a);\n/*****************************************************************************/\n/*\t\tSetup mglGraph\t\t\t\t\t\t\t\t\t\t\t\t\t\t */\n/*****************************************************************************/\nvoid mgl_set_def_param(HMGL gr);\nvoid mgl_set_palette(HMGL gr, const char *colors);\nvoid mgl_set_pal_color(HMGL graph, int n, mreal r, mreal g, mreal b);\nvoid mgl_set_pal_num(HMGL graph, int num);\nvoid mgl_set_rotated_text(HMGL graph, int rotated);\nvoid mgl_set_cut(HMGL graph, int cut);\nvoid mgl_set_cut_box(HMGL gr, mreal x1,mreal y1,mreal z1,mreal x2,mreal y2,mreal z2);\nvoid mgl_set_tick_len(HMGL graph, mreal len, mreal stt);\nvoid mgl_set_tick_stl(HMGL gr, const char *stl, const char *sub);\nvoid mgl_set_bar_width(HMGL graph, mreal width);\nvoid mgl_set_base_line_width(HMGL gr, mreal size);\nvoid mgl_set_mark_size(HMGL graph, mreal size);\nvoid mgl_set_arrow_size(HMGL graph, mreal size);\nvoid mgl_set_font_size(HMGL graph, mreal size);\nvoid mgl_set_font_def(HMGL graph, const char *fnt);\nvoid mgl_set_alpha_default(HMGL graph, mreal alpha);\nvoid mgl_set_size(HMGL graph, int width, int height);\nvoid mgl_set_axial_dir(HMGL graph, char dir);\nvoid mgl_set_meshnum(HMGL graph, int num);\nvoid mgl_set_zoom(HMGL gr, mreal x1, mreal y1, mreal x2, mreal y2);\nvoid mgl_set_plotfactor(HMGL gr, mreal val);\nvoid mgl_set_draw_face(HMGL gr, int enable);\nvoid mgl_set_scheme(HMGL gr, const char *sch);\nvoid mgl_load_font(HMGL gr, const char *name, const char *path);\nvoid mgl_copy_font(HMGL gr, HMGL gr_from);\nvoid mgl_restore_font(HMGL gr);\nint mgl_get_warn(HMGL gr);\n/*****************************************************************************/\n/*\t\tExport to file or to memory\t\t\t\t\t\t\t\t\t\t\t */\n/*****************************************************************************/\nvoid mgl_show_image(HMGL graph, const char *viewer, int keep);\nvoid mgl_write_frame(HMGL graph, const char *fname,const char *descr);\nvoid mgl_write_bmp(HMGL graph, const char *fname,const char *descr);\nvoid mgl_write_jpg(HMGL graph, const char *fname,const char *descr);\nvoid mgl_write_png(HMGL graph, const char *fname,const char *descr);\nvoid mgl_write_png_solid(HMGL graph, const char *fname,const char *descr);\nvoid mgl_write_eps(HMGL graph, const char *fname,const char *descr);\nvoid mgl_write_svg(HMGL graph, const char *fname,const char *descr);\nvoid mgl_write_idtf(HMGL graph, const char *fname,const char *descr);\nvoid mgl_write_gif(HMGL graph, const char *fname,const char *descr);\nvoid mgl_start_gif(HMGL graph, const char *fname,int ms);\nvoid mgl_close_gif(HMGL graph);\nconst unsigned char *mgl_get_rgb(HMGL graph);\nconst unsigned char *mgl_get_rgba(HMGL graph);\nint mgl_get_width(HMGL graph);\nint mgl_get_height(HMGL graph);\n/*****************************************************************************/\n/*\t\tSetup frames transparency (alpha) and lightning\t\t\t\t\t\t */\n/*****************************************************************************/\nint mgl_new_frame(HMGL graph);\nvoid mgl_end_frame(HMGL graph);\nint mgl_get_num_frame(HMGL graph);\nvoid mgl_reset_frames(HMGL graph);\nvoid mgl_set_transp_type(HMGL graph, int type);\nvoid mgl_set_transp(HMGL graph, int enable);\nvoid mgl_set_alpha(HMGL graph, int enable);\nvoid mgl_set_fog(HMGL graph, mreal d, mreal dz);\nvoid mgl_set_light(HMGL graph, int enable);\nvoid mgl_set_light_n(HMGL gr, int n, int enable);\nvoid mgl_add_light(HMGL graph, int n, mreal x, mreal y, mreal z, char c);\nvoid mgl_add_light_rgb(HMGL graph, int n, mreal x, mreal y, mreal z, int infty, mreal r, mreal g, mreal b, mreal i);\nvoid mgl_set_ambbr(HMGL gr, mreal i);\n/*****************************************************************************/\n/*\t\tScale and rotate\t\t\t\t\t\t\t\t\t\t\t\t\t */\n/*****************************************************************************/\nvoid mgl_mat_pop(HMGL gr);\nvoid mgl_mat_push(HMGL gr);\nvoid mgl_identity(HMGL graph, int rel);\nvoid mgl_clf(HMGL graph);\nvoid mgl_flush(HMGL gr);\nvoid mgl_clf_rgb(HMGL graph, mreal r, mreal g, mreal b);\nvoid mgl_subplot(HMGL graph, int nx,int ny,int m);\nvoid mgl_subplot_d(HMGL graph, int nx,int ny,int m, mreal dx, mreal dy);\nvoid mgl_subplot_s(HMGL graph, int nx,int ny,int m,const char *style);\nvoid mgl_inplot(HMGL graph, mreal x1,mreal x2,mreal y1,mreal y2);\nvoid mgl_relplot(HMGL graph, mreal x1,mreal x2,mreal y1,mreal y2);\nvoid mgl_columnplot(HMGL graph, int num, int ind);\nvoid mgl_columnplot_d(HMGL graph, int num, int ind, mreal d);\nvoid mgl_stickplot(HMGL graph, int num, int ind, mreal tet, mreal phi);\nvoid mgl_aspect(HMGL graph, mreal Ax,mreal Ay,mreal Az);\nvoid mgl_rotate(HMGL graph, mreal TetX,mreal TetZ,mreal TetY);\nvoid mgl_rotate_vector(HMGL graph, mreal Tet,mreal x,mreal y,mreal z);\nvoid mgl_perspective(HMGL graph, mreal val);\n/*****************************************************************************/\n/*\t\tAxis functions\t\t\t\t\t\t\t\t\t\t\t\t\t\t */\n/*****************************************************************************/\nvoid mgl_adjust_ticks(HMGL graph, const char *dir);\nvoid mgl_set_ticks(HMGL graph, mreal DX, mreal DY, mreal DZ);\nvoid mgl_set_subticks(HMGL graph, int NX, int NY, int NZ);\nvoid mgl_set_ticks_dir(HMGL graph, char dir, mreal d, int ns, mreal org);\nvoid mgl_set_ticks_val(HMGL graph, char dir, int n, double val, const char *lbl, ...);\nvoid mgl_set_ticks_vals(HMGL graph, char dir, int n, mreal *val, const char **lbl);\nvoid mgl_set_caxis(HMGL graph, mreal C1,mreal C2);\nvoid mgl_set_axis(HMGL graph, mreal x1, mreal y1, mreal z1, mreal x2, mreal y2, mreal z2, mreal x0, mreal y0, mreal z0);\nvoid mgl_set_axis_3d(HMGL graph, mreal x1, mreal y1, mreal z1, mreal x2, mreal y2, mreal z2);\nvoid mgl_set_axis_2d(HMGL graph, mreal x1, mreal y1, mreal x2, mreal y2);\ninline void mgl_set_ranges(HMGL graph, mreal x1, mreal x2, mreal y1, mreal y2, mreal z1, mreal z2)\n{\tmgl_set_axis_3d(graph, x1,y1,z1,x2,y2,z2);\t};\nvoid mgl_set_origin(HMGL graph, mreal x0, mreal y0, mreal z0);\nvoid mgl_set_tick_origin(HMGL graph, mreal x0, mreal y0, mreal z0);\nvoid mgl_set_crange(HMGL graph, const HMDT a, int add);\nvoid mgl_set_xrange(HMGL graph, const HMDT a, int add);\nvoid mgl_set_yrange(HMGL graph, const HMDT a, int add);\nvoid mgl_set_zrange(HMGL graph, const HMDT a, int add);\nvoid mgl_set_auto(HMGL graph, mreal x1, mreal x2, mreal y1, mreal y2, mreal z1, mreal z2);\nvoid mgl_set_func(HMGL graph, const char *EqX,const char *EqY,const char *EqZ);\nvoid mgl_set_func_ext(HMGL graph, const char *EqX,const char *EqY,const char *EqZ,const char *EqA);\nvoid mgl_set_coor(HMGL gr, int how);\nvoid mgl_set_ternary(HMGL gr, int enable);\nvoid mgl_set_cutoff(HMGL graph, const char *EqC);\nvoid mgl_box(HMGL graph, int ticks);\nvoid mgl_box_str(HMGL graph, const char *col, int ticks);\nvoid mgl_box_rgb(HMGL graph, mreal r, mreal g, mreal b, int ticks);\nvoid mgl_axis(HMGL graph, const char *dir);\nvoid mgl_axis_grid(HMGL graph, const char *dir,const char *pen);\nvoid mgl_label(HMGL graph, char dir, const char *text);\nvoid mgl_label_ext(HMGL graph, char dir, const char *text, mreal pos, mreal size, mreal shift);\nvoid mgl_labelw_ext(HMGL graph, char dir, const wchar_t *text, mreal pos, mreal size, mreal shift);\nvoid mgl_label_xy(HMGL graph, mreal x, mreal y, const char *text, const char *fnt, mreal size);\nvoid mgl_labelw_xy(HMGL graph, mreal x, mreal y, const wchar_t *text, const char *fnt, mreal size);\nvoid mgl_tune_ticks(HMGL graph, int tune, mreal fact_pos);\nvoid mgl_set_xttw(HMGL graph, const wchar_t *templ);\nvoid mgl_set_yttw(HMGL graph, const wchar_t *templ);\nvoid mgl_set_zttw(HMGL graph, const wchar_t *templ);\nvoid mgl_set_cttw(HMGL graph, const wchar_t *templ);\nvoid mgl_set_xtt(HMGL graph, const char *templ);\nvoid mgl_set_ytt(HMGL graph, const char *templ);\nvoid mgl_set_ztt(HMGL graph, const char *templ);\nvoid mgl_set_ctt(HMGL graph, const char *templ);\n/*****************************************************************************/\n/*\t\tSimple drawing\t\t\t\t\t\t\t\t\t\t\t\t\t\t */\n/*****************************************************************************/\nvoid mgl_ball(HMGL graph, mreal x,mreal y,mreal z);\nvoid mgl_ball_rgb(HMGL graph, mreal x, mreal y, mreal z, mreal r, mreal g, mreal b, mreal alpha);\nvoid mgl_ball_str(HMGL graph, mreal x, mreal y, mreal z, char col);\nvoid mgl_line(HMGL graph, mreal x1, mreal y1, mreal z1, mreal x2, mreal y2, mreal z2, const char *pen,int n);\nvoid mgl_facex(HMGL graph, mreal x0, mreal y0, mreal z0, mreal wy, mreal wz, const char *stl, mreal dx, mreal dy);\nvoid mgl_facey(HMGL graph, mreal x0, mreal y0, mreal z0, mreal wx, mreal wz, const char *stl, mreal dx, mreal dy);\nvoid mgl_facez(HMGL graph, mreal x0, mreal y0, mreal z0, mreal wx, mreal wy, const char *stl, mreal dx, mreal dy);\nvoid mgl_curve(HMGL graph, mreal x1, mreal y1, mreal z1, mreal dx1, mreal dy1, mreal dz1, mreal x2, mreal y2, mreal z2, mreal dx2, mreal dy2, mreal dz2, const char *pen,int n);\n\nvoid mgl_puts(HMGL graph, mreal x, mreal y, mreal z,const char *text);\nvoid mgl_putsw(HMGL graph, mreal x, mreal y, mreal z,const wchar_t *text);\nvoid mgl_puts_dir(HMGL graph, mreal x, mreal y, mreal z, mreal dx, mreal dy, mreal dz, const char *text, mreal size);\nvoid mgl_putsw_dir(HMGL graph, mreal x, mreal y, mreal z, mreal dx, mreal dy, mreal dz, const wchar_t *text, mreal size);\nvoid mgl_text(HMGL graph, mreal x, mreal y, mreal z,const char *text);\nvoid mgl_title(HMGL graph, const char *text, const char *fnt, mreal size);\nvoid mgl_titlew(HMGL graph, const wchar_t *text, const char *fnt, mreal size);\nvoid mgl_putsw_ext(HMGL graph, mreal x, mreal y, mreal z,const wchar_t *text,const char *font,mreal size,char dir);\nvoid mgl_puts_ext(HMGL graph, mreal x, mreal y, mreal z,const char *text,const char *font,mreal size,char dir);\nvoid mgl_text_ext(HMGL graph, mreal x, mreal y, mreal z,const char *text,const char *font,mreal size,char dir);\nvoid mgl_colorbar(HMGL graph, const char *sch,int where);\nvoid mgl_colorbar_ext(HMGL graph, const char *sch, int where, mreal x, mreal y, mreal w, mreal h);\nvoid mgl_colorbar_val(HMGL graph, const HMDT dat, const char *sch,int where);\nvoid mgl_simple_plot(HMGL graph, const HMDT a, int type, const char *stl);\nvoid mgl_add_legend(HMGL graph, const char *text,const char *style);\nvoid mgl_add_legendw(HMGL graph, const wchar_t *text,const char *style);\nvoid mgl_clear_legend(HMGL graph);\nvoid mgl_legend_xy(HMGL graph, mreal x, mreal y, const char *font, mreal size, mreal llen);\nvoid mgl_legend(HMGL graph, int where, const char *font, mreal size, mreal llen);\nvoid mgl_set_legend_box(HMGL gr, int enable);\nvoid mgl_set_legend_marks(HMGL gr, int num);\n/*****************************************************************************/\n/*\t\t1D plotting functions\t\t\t\t\t\t\t\t\t\t\t\t */\n/*****************************************************************************/\nvoid mgl_fplot(HMGL graph, const char *fy, const char *stl, int n);\nvoid mgl_fplot_xyz(HMGL graph, const char *fx, const char *fy, const char *fz, const char *stl, int n);\nvoid mgl_plot_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const char *pen);\nvoid mgl_plot_xy(HMGL graph, const HMDT x, const HMDT y, const char *pen);\nvoid mgl_plot(HMGL graph, const HMDT y, const char *pen);\nvoid mgl_radar(HMGL graph, const HMDT a, const char *pen, mreal r);\nvoid mgl_boxplot_xy(HMGL graph, const HMDT x, const HMDT a, const char *pen);\nvoid mgl_boxplot(HMGL graph, const HMDT a, const char *pen);\nvoid mgl_tens_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT c, const char *pen);\nvoid mgl_tens_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT c, const char *pen);\nvoid mgl_tens(HMGL graph, const HMDT y, const HMDT c,\tconst char *pen);\nvoid mgl_area_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const char *pen);\nvoid mgl_area_xy(HMGL graph, const HMDT x, const HMDT y, const char *pen);\nvoid mgl_area_xys(HMGL graph, const HMDT x, const HMDT y, const char *pen);\nvoid mgl_area_s(HMGL graph, const HMDT y, const char *pen);\nvoid mgl_area(HMGL graph, const HMDT y, const char *pen);\nvoid mgl_region_xy(HMGL graph, const HMDT x, const HMDT y1, const HMDT y2, const char *pen, int inside);\nvoid mgl_region(HMGL graph, const HMDT y1, const HMDT y2, const char *pen, int inside);\nvoid mgl_mark(HMGL graph, mreal x,mreal y,mreal z,char mark);\nvoid mgl_stem_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const char *pen);\nvoid mgl_stem_xy(HMGL graph, const HMDT x, const HMDT y, const char *pen);\nvoid mgl_stem(HMGL graph, const HMDT y,\tconst char *pen);\nvoid mgl_step_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const char *pen);\nvoid mgl_step_xy(HMGL graph, const HMDT x, const HMDT y, const char *pen);\nvoid mgl_step(HMGL graph, const HMDT y,\tconst char *pen);\nvoid mgl_bars_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const char *pen);\nvoid mgl_bars_xy(HMGL graph, const HMDT x, const HMDT y, const char *pen);\nvoid mgl_bars(HMGL graph, const HMDT y,\tconst char *pen);\nvoid mgl_barh_yx(HMGL graph, const HMDT y, const HMDT v, const char *pen);\nvoid mgl_barh(HMGL graph, const HMDT v,\tconst char *pen);\n/*****************************************************************************/\n/*\t\tAdvanced 1D plotting functions\t\t\t\t\t\t\t\t\t\t\t\t */\n/*****************************************************************************/\nvoid mgl_torus(HMGL graph, const HMDT r, const HMDT z, const char *pen);\nvoid mgl_text_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z,const char *text, const char *font, mreal size);\nvoid mgl_text_xy(HMGL graph, const HMDT x, const HMDT y, const char *text, const char *font, mreal size);\nvoid mgl_text_y(HMGL graph, const HMDT y, const char *text, const char *font, mreal size);\nvoid mgl_chart(HMGL graph, const HMDT a, const char *col);\nvoid mgl_error(HMGL graph, const HMDT y, const HMDT ey, const char *pen);\nvoid mgl_error_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT ey, const char *pen);\nvoid mgl_error_exy(HMGL graph, const HMDT x, const HMDT y, const HMDT ex, const HMDT ey, const char *pen);\nvoid mgl_mark_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT r, const char *pen);\nvoid mgl_mark_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT r, const char *pen);\nvoid mgl_mark_y(HMGL graph, const HMDT y, const HMDT r, const char *pen);\nvoid mgl_tube_xyzr(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT r, const char *pen);\nvoid mgl_tube_xyr(HMGL graph, const HMDT x, const HMDT y, const HMDT r, const char *pen);\nvoid mgl_tube_r(HMGL graph, const HMDT y, const HMDT r, const char *pen);\nvoid mgl_tube_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, mreal r, const char *pen);\nvoid mgl_tube_xy(HMGL graph, const HMDT x, const HMDT y, mreal r, const char *penl);\nvoid mgl_tube(HMGL graph, const HMDT y, mreal r, const char *pen);\n\nvoid mgl_textmark_xyzr(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT r, const char *text, const char *fnt);\nvoid mgl_textmark_xyr(HMGL graph, const HMDT x, const HMDT y, const HMDT r, const char *text, const char *fnt);\nvoid mgl_textmark_yr(HMGL graph, const HMDT y, const HMDT r, const char *text, const char *fnt);\nvoid mgl_textmark(HMGL graph, const HMDT y, const char *text, const char *fnt);\nvoid mgl_textmarkw_xyzr(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT r, const wchar_t *text, const char *fnt);\nvoid mgl_textmarkw_xyr(HMGL graph, const HMDT x, const HMDT y, const HMDT r, const wchar_t *text, const char *fnt);\nvoid mgl_textmarkw_yr(HMGL graph, const HMDT y, const HMDT r, const wchar_t *text, const char *fnt);\nvoid mgl_textmarkw(HMGL graph, const HMDT y, const wchar_t *text, const char *fnt);\n/*****************************************************************************/\n/*\t\t2D plotting functions\t\t\t\t\t\t\t\t\t\t\t\t */\n/*****************************************************************************/\nvoid mgl_fsurf(HMGL graph, const char *fz, const char *stl, int n);\nvoid mgl_fsurf_xyz(HMGL graph, const char *fx, const char *fy, const char *fz, const char *stl, int n);\nvoid mgl_grid_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const char *stl,mreal zVal);\nvoid mgl_grid(HMGL graph, const HMDT a,const char *stl,mreal zVal);\nvoid mgl_mesh_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const char *sch);\nvoid mgl_mesh(HMGL graph, const HMDT z, const char *sch);\nvoid mgl_fall_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const char *sch);\nvoid mgl_fall(HMGL graph, const HMDT z, const char *sch);\nvoid mgl_belt_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const char *sch);\nvoid mgl_belt(HMGL graph, const HMDT z, const char *sch);\nvoid mgl_surf_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const char *sch);\nvoid mgl_surf(HMGL graph, const HMDT z, const char *sch);\nvoid mgl_dens_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const char *sch,mreal zVal);\nvoid mgl_dens(HMGL graph, const HMDT z, const char *sch,mreal zVal);\nvoid mgl_boxs_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const char *sch,mreal zVal);\nvoid mgl_boxs(HMGL graph, const HMDT z, const char *sch,mreal zVal);\nvoid mgl_tile_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const char *sch);\nvoid mgl_tile(HMGL graph, const HMDT z, const char *sch);\nvoid mgl_tiles_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT r, const char *sch);\nvoid mgl_tiles(HMGL graph, const HMDT z, const HMDT r, const char *sch);\nvoid mgl_cont_xy_val(HMGL graph, const HMDT v, const HMDT x, const HMDT y, const HMDT z, const char *sch, mreal zVal);\nvoid mgl_cont_val(HMGL graph, const HMDT v, const HMDT z, const char *sch,mreal zVal);\nvoid mgl_cont_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const char *sch, int Num, mreal zVal);\nvoid mgl_cont(HMGL graph, const HMDT z, const char *sch, int Num, mreal zVal);\n\nvoid mgl_contf_xy_val(HMGL graph, const HMDT v, const HMDT x, const HMDT y, const HMDT z, const char *sch, mreal zVal);\nvoid mgl_contf_val(HMGL graph, const HMDT v, const HMDT z, const char *sch,mreal zVal);\nvoid mgl_contf_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const char *sch, int Num, mreal zVal);\nvoid mgl_contf(HMGL graph, const HMDT z, const char *sch, int Num, mreal zVal);\n\nvoid mgl_contd_xy_val(HMGL graph, const HMDT v, const HMDT x, const HMDT y, const HMDT z, const char *sch, mreal zVal);\nvoid mgl_contd_val(HMGL graph, const HMDT v, const HMDT z, const char *sch,mreal zVal);\nvoid mgl_contd_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const char *sch, int Num, mreal zVal);\nvoid mgl_contd(HMGL graph, const HMDT z, const char *sch, int Num, mreal zVal);\n\nvoid mgl_axial_xy_val(HMGL graph, const HMDT v, const HMDT x, const HMDT y, const HMDT a, const char *sch);\nvoid mgl_axial_val(HMGL graph, const HMDT v, const HMDT a, const char *sch);\nvoid mgl_axial_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT a, const char *sch, int Num);\nvoid mgl_axial(HMGL graph, const HMDT a, const char *sch, int Num);\n/*****************************************************************************/\n/*\t\tDual plotting functions\t\t\t\t\t\t\t\t\t\t\t\t */\n/*****************************************************************************/\nvoid mgl_surfc_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT c, const char *sch);\nvoid mgl_surfc(HMGL graph, const HMDT z, const HMDT c, const char *sch);\nvoid mgl_surfa_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT c, const char *sch);\nvoid mgl_surfa(HMGL graph, const HMDT z, const HMDT c, const char *sch);\nvoid mgl_stfa_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT re, const HMDT im, int dn, const char *sch, mreal zVal);\nvoid mgl_stfa(HMGL graph, const HMDT re, const HMDT im, int dn, const char *sch, mreal zVal);\nvoid mgl_traj_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT ax, const HMDT ay, const char *sch,mreal zVal,mreal len);\nvoid mgl_traj_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT ax, const HMDT ay, const HMDT az, const char *sch,mreal len);\nvoid mgl_vect_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT ax, const HMDT ay, const char *sch,mreal zVal,int flag);\nvoid mgl_vect_2d(HMGL graph, const HMDT ax, const HMDT ay, const char *sch,mreal zVal,int flag);\nvoid mgl_vectl_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT ax, const HMDT ay, const char *sch,mreal zVal);\nvoid mgl_vectl_2d(HMGL graph, const HMDT ax, const HMDT ay, const char *sch,mreal zVal);\nvoid mgl_vectc_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT ax, const HMDT ay, const char *sch,mreal zVal);\nvoid mgl_vectc_2d(HMGL graph, const HMDT ax, const HMDT ay, const char *sch,mreal zVal);\nvoid mgl_vect_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT ax, const HMDT ay, const HMDT az, const char *sch,int flag);\nvoid mgl_vect_3d(HMGL graph, const HMDT ax, const HMDT ay, const HMDT az, const char *sch,int flag);\nvoid mgl_vectl_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT ax, const HMDT ay, const HMDT az, const char *sch);\nvoid mgl_vectl_3d(HMGL graph, const HMDT ax, const HMDT ay, const HMDT az, const char *sch);\nvoid mgl_vectc_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT ax, const HMDT ay, const HMDT az, const char *sch);\nvoid mgl_vectc_3d(HMGL graph, const HMDT ax, const HMDT ay, const HMDT az, const char *sch);\nvoid mgl_map_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT a, const HMDT b, const char *sch, int ks, int pnts);\nvoid mgl_map(HMGL graph, const HMDT a, const HMDT b, const char *sch, int ks, int pnts);\nvoid mgl_surf3a_xyz_val(HMGL graph, mreal Val, const HMDT x, const HMDT y, const HMDT z, const HMDT a, const HMDT b, const char *stl);\nvoid mgl_surf3a_val(HMGL graph, mreal Val, const HMDT a, const HMDT b, const char *stl);\nvoid mgl_surf3a_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT a, const HMDT b, const char *stl, int num);\nvoid mgl_surf3a(HMGL graph, const HMDT a, const HMDT b, const char *stl, int num);\nvoid mgl_surf3c_xyz_val(HMGL graph, mreal Val, const HMDT x, const HMDT y, const HMDT z, const HMDT a, const HMDT b, const char *stl);\nvoid mgl_surf3c_val(HMGL graph, mreal Val, const HMDT a, const HMDT b, const char *stl);\nvoid mgl_surf3c_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT a, const HMDT b,\n\t\t\tconst char *stl, int num);\nvoid mgl_surf3c(HMGL graph, const HMDT a, const HMDT b, const char *stl, int num);\nvoid mgl_flow_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT ax, const HMDT ay, const char *sch, int num, int central, mreal zVal);\nvoid mgl_flow_2d(HMGL graph, const HMDT ax, const HMDT ay, const char *sch, int num, int central, mreal zVal);\nvoid mgl_flow_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT ax, const HMDT ay, const HMDT az, const char *sch, int num, int central);\nvoid mgl_flow_3d(HMGL graph, const HMDT ax, const HMDT ay, const HMDT az, const char *sch, int num, int central);\n\nvoid mgl_flowp_xy(HMGL graph, mreal x0, mreal y0, mreal z0, const HMDT x, const HMDT y, const HMDT ax, const HMDT ay, const char *sch);\nvoid mgl_flowp_2d(HMGL graph, mreal x0, mreal y0, mreal z0, const HMDT ax, const HMDT ay, const char *sch);\nvoid mgl_flowp_xyz(HMGL graph, mreal x0, mreal y0, mreal z0, const HMDT x, const HMDT y, const HMDT z, const HMDT ax, const HMDT ay, const HMDT az, const char *sch);\nvoid mgl_flowp_3d(HMGL graph, mreal x0, mreal y0, mreal z0, const HMDT ax, const HMDT ay, const HMDT az, const char *sch);\n\nvoid mgl_pipe_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT ax, const HMDT ay, const char *sch, mreal r0, int num, int central, mreal zVal);\nvoid mgl_pipe_2d(HMGL graph, const HMDT ax, const HMDT ay, const char *sch, mreal r0, int num, int central, mreal zVal);\nvoid mgl_pipe_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT ax, const HMDT ay, const HMDT az, const char *sch, mreal r0, int num, int central);\nvoid mgl_pipe_3d(HMGL graph, const HMDT ax, const HMDT ay, const HMDT az, const char *sch, mreal r0, int num, int central);\nvoid mgl_dew_xy(HMGL gr, const HMDT x, const HMDT y, const HMDT ax, const HMDT ay, const char *sch,mreal zVal);\nvoid mgl_dew_2d(HMGL gr, const HMDT ax, const HMDT ay, const char *sch,mreal zVal);\n\nvoid mgl_grad_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT ph, const char *sch, int num);\nvoid mgl_grad_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT ph, const char *sch, int num, mreal zVal);\nvoid mgl_grad(HMGL graph, const HMDT ph, const char *sch, int num, mreal zVal);\n/*****************************************************************************/\n/*\t\t3D plotting functions\t\t\t\t\t\t\t\t\t\t\t\t */\n/*****************************************************************************/\nvoid mgl_grid3_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT a, char dir, int sVal, const char *stl);\nvoid mgl_grid3(HMGL graph, const HMDT a, char dir, int sVal, const char *stl);\nvoid mgl_grid3_all_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT a, const char *stl);\nvoid mgl_grid3_all(HMGL graph, const HMDT a, const char *stl);\nvoid mgl_dens3_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT a, char dir, int sVal, const char *stl);\nvoid mgl_dens3(HMGL graph, const HMDT a, char dir, int sVal, const char *stl);\nvoid mgl_dens3_all_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT a, const char *stl);\nvoid mgl_dens3_all(HMGL graph, const HMDT a, const char *stl);\nvoid mgl_surf3_xyz_val(HMGL graph, mreal Val, const HMDT x, const HMDT y, const HMDT z, const HMDT a, const char *stl);\nvoid mgl_surf3_val(HMGL graph, mreal Val, const HMDT a, const char *stl);\nvoid mgl_surf3_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT a, const char *stl, int num);\nvoid mgl_surf3(HMGL graph, const HMDT a, const char *stl, int num);\nvoid mgl_cont3_xyz_val(HMGL graph, const HMDT v, const HMDT x, const HMDT y, const HMDT z, const HMDT a, char dir, int sVal, const char *sch);\nvoid mgl_cont3_val(HMGL graph, const HMDT v, const HMDT a, char dir, int sVal, const char *sch);\nvoid mgl_cont3_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT a, char dir, int sVal, const char *sch, int Num);\nvoid mgl_cont3(HMGL graph, const HMDT a, char dir, int sVal, const char *sch, int Num);\nvoid mgl_cont_all_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT a, const char *sch, int Num);\nvoid mgl_cont_all(HMGL graph, const HMDT a, const char *sch, int Num);\nvoid mgl_cloudp_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT a, const char *stl, mreal alpha);\nvoid mgl_cloudp(HMGL graph, const HMDT a, const char *stl, mreal alpha);\nvoid mgl_cloud_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT a, const char *stl, mreal alpha);\nvoid mgl_cloud(HMGL graph, const HMDT a, const char *stl, mreal alpha);\nvoid mgl_contf3_xyz_val(HMGL graph, const HMDT v, const HMDT x, const HMDT y, const HMDT z, const HMDT a, char dir, int sVal, const char *sch);\nvoid mgl_contf3_val(HMGL graph, const HMDT v, const HMDT a, char dir, int sVal, const char *sch);\nvoid mgl_contf3_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT a, char dir, int sVal, const char *sch, int Num);\nvoid mgl_contf3(HMGL graph, const HMDT a, char dir, int sVal, const char *sch, int Num);\nvoid mgl_contf_all_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT a, const char *sch, int Num);\nvoid mgl_contf_all(HMGL graph, const HMDT a, const char *sch, int Num);\nvoid mgl_beam_val(HMGL graph, mreal Val, const HMDT tr, const HMDT g1, const HMDT g2, const HMDT a, mreal r, const char *stl, int norm);\nvoid mgl_beam(HMGL graph, const HMDT tr, const HMDT g1, const HMDT g2, const HMDT a, mreal r, const char *stl, int norm, int num);\n/*****************************************************************************/\n/*\t\tTriangular plotting functions\t\t\t\t\t\t\t\t\t\t\t */\n/*****************************************************************************/\nvoid mgl_triplot_xyzc(HMGL gr, const HMDT nums, const HMDT x, const HMDT y, const HMDT z, const HMDT c, const char *sch);\nvoid mgl_triplot_xyz(HMGL gr, const HMDT nums, const HMDT x, const HMDT y, const HMDT z, const char *sch);\nvoid mgl_triplot_xy(HMGL gr, const HMDT nums, const HMDT x, const HMDT y, const char *sch, mreal zVal);\nvoid mgl_quadplot_xyzc(HMGL gr, const HMDT nums, const HMDT x, const HMDT y, const HMDT z, const HMDT c, const char *sch);\nvoid mgl_quadplot_xyz(HMGL gr, const HMDT nums, const HMDT x, const HMDT y, const HMDT z, const char *sch);\nvoid mgl_quadplot_xy(HMGL gr, const HMDT nums, const HMDT x, const HMDT y, const char *sch, mreal zVal);\nvoid mgl_tricont_xyzcv(HMGL gr, const HMDT v, const HMDT nums, const HMDT x, const HMDT y, const HMDT z, const HMDT c, const char *sch, mreal zVal);\nvoid mgl_tricont_xyzv(HMGL gr, const HMDT v, const HMDT nums, const HMDT x, const HMDT y, const HMDT z, const char *sch, mreal zVal);\nvoid mgl_tricont_xyzc(HMGL gr, const HMDT nums, const HMDT x, const HMDT y, const HMDT z, const HMDT c, const char *sch, int n, mreal zVal);\nvoid mgl_tricont_xyz(HMGL gr, const HMDT nums, const HMDT x, const HMDT y, const HMDT z, const char *sch, int n, mreal zVal);\nvoid mgl_dots(HMGL gr, const HMDT x, const HMDT y, const HMDT z, const char *sch);\nvoid mgl_dots_a(HMGL gr, const HMDT x, const HMDT y, const HMDT z, const HMDT a, const char *sch);\nvoid mgl_dots_tr(HMGL gr, const HMDT tr, const char *sch);\nvoid mgl_crust(HMGL gr, const HMDT x, const HMDT y, const HMDT z, const char *sch, mreal er);\nvoid mgl_crust_tr(HMGL gr, const HMDT tr, const char *sch, mreal er);\n/*****************************************************************************/\n/*\t\tCombined plotting functions\t\t\t\t\t\t\t\t\t\t\t */\n/*****************************************************************************/\nvoid mgl_dens_x(HMGL graph, const HMDT a, const char *stl, mreal sVal);\nvoid mgl_dens_y(HMGL graph, const HMDT a, const char *stl, mreal sVal);\nvoid mgl_dens_z(HMGL graph, const HMDT a, const char *stl, mreal sVal);\nvoid mgl_cont_x(HMGL graph, const HMDT a, const char *stl, mreal sVal, int Num);\nvoid mgl_cont_y(HMGL graph, const HMDT a, const char *stl, mreal sVal, int Num);\nvoid mgl_cont_z(HMGL graph, const HMDT a, const char *stl, mreal sVal, int Num);\nvoid mgl_cont_x_val(HMGL graph, const HMDT v, const HMDT a, const char *stl, mreal sVal);\nvoid mgl_cont_y_val(HMGL graph, const HMDT v, const HMDT a, const char *stl, mreal sVal);\nvoid mgl_cont_z_val(HMGL graph, const HMDT v, const HMDT a, const char *stl, mreal sVal);\nvoid mgl_contf_x(HMGL graph, const HMDT a, const char *stl, mreal sVal, int Num);\nvoid mgl_contf_y(HMGL graph, const HMDT a, const char *stl, mreal sVal, int Num);\nvoid mgl_contf_z(HMGL graph, const HMDT a, const char *stl, mreal sVal, int Num);\nvoid mgl_contf_x_val(HMGL graph, const HMDT v, const HMDT a, const char *stl, mreal sVal);\nvoid mgl_contf_y_val(HMGL graph, const HMDT v, const HMDT a, const char *stl, mreal sVal);\nvoid mgl_contf_z_val(HMGL graph, const HMDT v, const HMDT a, const char *stl, mreal sVal);\n/*****************************************************************************/\n/*\t\tData creation functions\t\t\t\t\t\t\t\t\t\t\t\t */\n/*****************************************************************************/\nvoid mgl_data_rearrange(HMDT dat, int mx, int my, int mz);\nvoid mgl_data_set_float(HMDT dat, const float *A,int NX,int NY,int NZ);\nvoid mgl_data_set_double(HMDT dat, const double *A,int NX,int NY,int NZ);\nvoid mgl_data_set_float2(HMDT d, const float **A,int N1,int N2);\nvoid mgl_data_set_double2(HMDT d, const double **A,int N1,int N2);\nvoid mgl_data_set_float3(HMDT d, const float ***A,int N1,int N2,int N3);\nvoid mgl_data_set_double3(HMDT d, const double ***A,int N1,int N2,int N3);\nvoid mgl_data_set(HMDT dat, const HMDT a);\nvoid mgl_data_set_vector(HMDT dat, gsl_vector *v);\nvoid mgl_data_set_matrix(HMDT dat, gsl_matrix *m);\n\nmreal mgl_data_get_value(const HMDT dat, int i, int j, int k);\nint mgl_data_get_nx(const HMDT dat);\nint mgl_data_get_ny(const HMDT dat);\nint mgl_data_get_nz(const HMDT dat);\nvoid mgl_data_set_value(HMDT dat, mreal v, int i, int j, int k);\nvoid mgl_data_set_values(HMDT dat, const char *val, int nx, int ny, int nz);\nint mgl_data_read(HMDT dat, const char *fname);\nint mgl_data_read_mat(HMDT dat, const char *fname, int dim);\nint mgl_data_read_dim(HMDT dat, const char *fname,int mx,int my,int mz);\nvoid mgl_data_save(HMDT dat, const char *fname,int ns);\nvoid mgl_data_export(HMDT dat, const char *fname, const char *scheme,mreal v1,mreal v2,int ns);\nvoid mgl_data_import(HMDT dat, const char *fname, const char *scheme,mreal v1,mreal v2);\nvoid mgl_data_create(HMDT dat, int nx,int ny,int nz);\nvoid mgl_data_transpose(HMDT dat, const char *dim);\nvoid mgl_data_norm(HMDT dat, mreal v1,mreal v2,int sym,int dim);\nvoid mgl_data_norm_slice(HMDT dat, mreal v1,mreal v2,char dir,int keep_en,int sym);\nHMDT mgl_data_subdata(const HMDT dat, int xx,int yy,int zz);\nHMDT mgl_data_subdata_ext(const HMDT dat, const HMDT xx, const HMDT yy, const HMDT zz);\nHMDT mgl_data_column(const HMDT dat, const char *eq);\nvoid mgl_data_set_id(HMDT d, const char *id);\nvoid mgl_data_fill(HMDT dat, mreal x1,mreal x2,char dir);\nvoid mgl_data_fill_eq(HMGL gr, HMDT dat, const char *eq, const HMDT vdat, const HMDT wdat);\nvoid mgl_data_put_val(HMDT dat, mreal val, int i, int j, int k);\nvoid mgl_data_put_dat(HMDT dat, const HMDT val, int i, int j, int k);\nvoid mgl_data_modify(HMDT dat, const char *eq,int dim);\nvoid mgl_data_modify_vw(HMDT dat, const char *eq,const HMDT vdat,const HMDT wdat);\nvoid mgl_data_squeeze(HMDT dat, int rx,int ry,int rz,int smooth);\nmreal mgl_data_max(const HMDT dat);\nmreal mgl_data_min(const HMDT dat);\nmreal *mgl_data_value(HMDT dat, int i,int j,int k);\nconst mreal *mgl_data_data(const HMDT dat);\n\nmreal mgl_data_first(const HMDT dat, const char *cond, int *i, int *j, int *k);\nmreal mgl_data_last(const HMDT dat, const char *cond, int *i, int *j, int *k);\nint mgl_data_find(const HMDT dat, const char *cond, char dir, int i, int j, int k);\nint mgl_data_find_any(const HMDT dat, const char *cond);\nmreal mgl_data_max_int(const HMDT dat, int *i, int *j, int *k);\nmreal mgl_data_max_real(const HMDT dat, mreal *x, mreal *y, mreal *z);\nmreal mgl_data_min_int(const HMDT dat, int *i, int *j, int *k);\nmreal mgl_data_min_real(const HMDT dat, mreal *x, mreal *y, mreal *z);\nmreal mgl_data_momentum_mw(const HMDT dat, char dir, mreal *m, mreal *w);\n\nHMDT mgl_data_combine(const HMDT dat1, const HMDT dat2);\nvoid mgl_data_extend(HMDT dat, int n1, int n2);\nvoid mgl_data_insert(HMDT dat, char dir, int at, int num);\nvoid mgl_data_delete(HMDT dat, char dir, int at, int num);\n/*****************************************************************************/\n/*\t\tData manipulation functions\t\t\t\t\t\t\t\t\t\t\t */\n/*****************************************************************************/\nvoid mgl_data_smooth(HMDT dat, int Type,mreal delta,const char *dirs);\nHMDT mgl_data_sum(const HMDT dat, const char *dir);\nHMDT mgl_data_max_dir(const HMDT dat, const char *dir);\nHMDT mgl_data_min_dir(const HMDT dat, const char *dir);\nvoid mgl_data_cumsum(HMDT dat, const char *dir);\nvoid mgl_data_integral(HMDT dat, const char *dir);\nvoid mgl_data_diff(HMDT dat, const char *dir);\nvoid mgl_data_diff_par(HMDT dat, const HMDT v1, const HMDT v2, const HMDT v3);\nvoid mgl_data_diff2(HMDT dat, const char *dir);\nvoid mgl_data_swap(HMDT dat, const char *dir);\nvoid mgl_data_roll(HMDT dat, char dir, int num);\nvoid mgl_data_mirror(HMDT dat, const char *dir);\n\nvoid mgl_data_hankel(HMDT dat, const char *dir);\nvoid mgl_data_sinfft(HMDT dat, const char *dir);\nvoid mgl_data_cosfft(HMDT dat, const char *dir);\nvoid mgl_data_fill_sample(HMDT dat, int num, const char *how);\n\nmreal mgl_data_spline(const HMDT dat, mreal x,mreal y,mreal z);\nmreal mgl_data_spline1(const HMDT dat, mreal x,mreal y,mreal z);\nmreal mgl_data_linear(const HMDT dat, mreal x,mreal y,mreal z);\nmreal mgl_data_linear1(const HMDT dat, mreal x,mreal y,mreal z);\nHMDT mgl_data_resize(const HMDT dat, int mx,int my,int mz);\nHMDT mgl_data_resize_box(const HMDT dat, int mx,int my,int mz,mreal x1,mreal x2,\n\tmreal y1,mreal y2,mreal z1,mreal z2);\nHMDT mgl_data_hist(const HMDT dat, int n, mreal v1, mreal v2, int nsub);\nHMDT mgl_data_hist_w(const HMDT dat, const HMDT weight, int n, mreal v1, mreal v2, int nsub);\nHMDT mgl_data_momentum(const HMDT dat, char dir, const char *how);\nHMDT mgl_data_evaluate_i(const HMDT dat, const HMDT idat, int norm);\nHMDT mgl_data_evaluate_ij(const HMDT dat, const HMDT idat, const HMDT jdat, int norm);\nHMDT mgl_data_evaluate_ijk(const HMDT dat, const HMDT idat, const HMDT jdat, const HMDT kdat, int norm);\nvoid mgl_data_envelop(HMDT dat, char dir);\nvoid mgl_data_sew(HMDT dat, const char *dirs, mreal da);\nvoid mgl_data_crop(HMDT dat, int n1, int n2, char dir);\n/*****************************************************************************/\n/*\t\tData operations\t\t\t\t\t\t\t\t\t\t\t\t\t\t */\n/*****************************************************************************/\nvoid mgl_data_mul_dat(HMDT dat, const HMDT d);\nvoid mgl_data_div_dat(HMDT dat, const HMDT d);\nvoid mgl_data_add_dat(HMDT dat, const HMDT d);\nvoid mgl_data_sub_dat(HMDT dat, const HMDT d);\nvoid mgl_data_mul_num(HMDT dat, mreal d);\nvoid mgl_data_div_num(HMDT dat, mreal d);\nvoid mgl_data_add_num(HMDT dat, mreal d);\nvoid mgl_data_sub_num(HMDT dat, mreal d);\n/*****************************************************************************/\n/*\t\tNonlinear fitting\t\t\t\t\t\t\t\t\t\t\t\t\t */\n/*****************************************************************************/\nvoid mgl_hist_x(HMGL gr, HMDT res, const HMDT x, const HMDT a);\nvoid mgl_hist_xy(HMGL gr, HMDT res, const HMDT x, const HMDT y, const HMDT a);\nvoid mgl_hist_xyz(HMGL gr, HMDT res, const HMDT x, const HMDT y, const HMDT z, const HMDT a);\n/*****************************************************************************/\n/*\t\tNonlinear fitting\t\t\t\t\t\t\t\t\t\t\t\t\t */\n/*****************************************************************************/\nmreal mgl_fit_1(HMGL gr, HMDT fit, const HMDT y, const char *eq, const char *var, mreal *ini);\nmreal mgl_fit_2(HMGL gr, HMDT fit, const HMDT z, const char *eq, const char *var, mreal *ini);\nmreal mgl_fit_3(HMGL gr, HMDT fit, const HMDT a, const char *eq, const char *var, mreal *ini);\nmreal mgl_fit_xy(HMGL gr, HMDT fit, const HMDT x, const HMDT y, const char *eq, const char *var, mreal *ini);\nmreal mgl_fit_xyz(HMGL gr, HMDT fit, const HMDT x, const HMDT y, const HMDT z, const char *eq, const char *var, mreal *ini);\nmreal mgl_fit_xyza(HMGL gr, HMDT fit, const HMDT x, const HMDT y, const HMDT z, const HMDT a, const char *eq, const char *var, mreal *ini);\nmreal mgl_fit_ys(HMGL gr, HMDT fit, const HMDT y, const HMDT s, const char *eq, const char *var, mreal *ini);\nmreal mgl_fit_xys(HMGL gr, HMDT fit, const HMDT x, const HMDT y, const HMDT s, const char *eq, const char *var, mreal *ini);\nmreal mgl_fit_xyzs(HMGL gr, HMDT fit, const HMDT x, const HMDT y, const HMDT z, const HMDT s, const char *eq, const char *var, mreal *ini);\nmreal mgl_fit_xyzas(HMGL gr, HMDT fit, const HMDT x, const HMDT y, const HMDT z, const HMDT a, const HMDT s, const char *eq, const char *var, mreal *ini);\n\nmreal mgl_fit_1_d(HMGL gr, HMDT fit, const HMDT y, const char *eq, const char *var, HMDT ini);\nmreal mgl_fit_2_d(HMGL gr, HMDT fit, const HMDT z, const char *eq, const char *var, HMDT ini);\nmreal mgl_fit_3_d(HMGL gr, HMDT fit, const HMDT a, const char *eq, const char *var, HMDT ini);\nmreal mgl_fit_xy_d(HMGL gr, HMDT fit, const HMDT x, const HMDT y, const char *eq, const char *var, HMDT ini);\nmreal mgl_fit_xyz_d(HMGL gr, HMDT fit, const HMDT x, const HMDT y, const HMDT z, const char *eq, const char *var, HMDT ini);\nmreal mgl_fit_xyza_d(HMGL gr, HMDT fit, const HMDT x, const HMDT y, const HMDT z, const HMDT a, const char *eq, const char *var, HMDT ini);\nmreal mgl_fit_ys_d(HMGL gr, HMDT fit, const HMDT y, const HMDT s, const char *eq, const char *var, HMDT ini);\nmreal mgl_fit_xys_d(HMGL gr, HMDT fit, const HMDT x, const HMDT y, const HMDT s, const char *eq, const char *var, HMDT ini);\nmreal mgl_fit_xyzs_d(HMGL gr, HMDT fit, const HMDT x, const HMDT y, const HMDT z, const HMDT s, const char *eq, const char *var, HMDT ini);\nmreal mgl_fit_xyzas_d(HMGL gr, HMDT fit, const HMDT x, const HMDT y, const HMDT z, const HMDT a, const HMDT s, const char *eq, const char *var, HMDT ini);\n\nvoid mgl_puts_fit(HMGL gr, mreal x, mreal y, mreal z, const char *prefix, const char *font, mreal size);\nconst char *mgl_get_fit(HMGL gr);\n/*****************************************************************************/\nvoid mgl_sphere(HMGL graph, mreal x, mreal y, mreal z, mreal r, const char *stl);\nvoid mgl_drop(HMGL graph, mreal x1, mreal y1, mreal z1, mreal x2, mreal y2, mreal z2, mreal r, const char *stl, mreal shift, mreal ap);\nvoid mgl_cone(HMGL graph, mreal x1, mreal y1, mreal z1, mreal x2, mreal y2, mreal z2, mreal r1, mreal r2, const char *stl, int edge);\n\nHMDT mgl_pde_solve(HMGL gr, const char *ham, const HMDT ini_re, const HMDT ini_im, mreal dz, mreal k0);\nHMDT mgl_qo2d_solve(const char *ham, const HMDT ini_re, const HMDT ini_im, const HMDT ray, mreal r, mreal k0, HMDT xx, HMDT yy);\nHMDT mgl_af2d_solve(const char *ham, const HMDT ini_re, const HMDT ini_im, const HMDT ray, mreal r, mreal k0, HMDT xx, HMDT yy);\nHMDT mgl_ray_trace(const char *ham, mreal x0, mreal y0, mreal z0, mreal px, mreal py, mreal pz, mreal dt, mreal tmax);\nHMDT mgl_jacobian_2d(const HMDT x, const HMDT y);\nHMDT mgl_jacobian_3d(const HMDT x, const HMDT y, const HMDT z);\nHMDT mgl_transform_a(const HMDT am, const HMDT ph, const char *tr);\nHMDT mgl_transform(const HMDT re, const HMDT im, const char *tr);\nHMDT mgl_data_stfa(const HMDT re, const HMDT im, int dn, char dir);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* _mgl_c_h_ */\n", "meta": {"hexsha": "80b2f1fb8b765bb8ddbeba267c216b9360355870", "size": 46757, "ext": "h", "lang": "C", "max_stars_repo_path": "iup/srcmglplot/mgl/mgl_c.h", "max_stars_repo_name": "xuminic/iup-porting", "max_stars_repo_head_hexsha": "1146f0c683f3d3487cf5524d7d9d7dc01b20aec9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68.0, "max_stars_repo_stars_event_min_datetime": "2015-01-21T11:06:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T11:01:40.000Z", "max_issues_repo_path": "iup/srcmglplot/mgl/mgl_c.h", "max_issues_repo_name": "xuminic/iup-porting", "max_issues_repo_head_hexsha": "1146f0c683f3d3487cf5524d7d9d7dc01b20aec9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "iup/srcmglplot/mgl/mgl_c.h", "max_forks_repo_name": "xuminic/iup-porting", "max_forks_repo_head_hexsha": "1146f0c683f3d3487cf5524d7d9d7dc01b20aec9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2015-01-08T16:38:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T15:00:57.000Z", "avg_line_length": 69.4754829123, "max_line_length": 176, "alphanum_fraction": 0.6844536647, "num_tokens": 15427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.411110869232168, "lm_q2_score": 0.0316187664701923, "lm_q1q2_score": 0.012998818567609685}}
{"text": "#pragma once\n\n// STL and std libs\n#include <map>\n#include <set>\n#include <vector>\n#include <list>\n#include <memory>\n#include <functional>\n#include <iostream>\n#include <fstream>\n#include <algorithm>\n#include <chrono>\n#include <type_traits>\n\n// Guildline Support Library\n#include <gsl.h>\n\n//// boost and std extension\n//#include <boost\\signals2.hpp>\n//#include <boost\\any.hpp>\n//#include <boost\\range\\iterator_range_core.hpp>\n//#include <boost\\range\\adaptor\\transformed.hpp>\n//#include <boost\\operators.hpp>\n//#include <boost\\format.hpp>\n//#include <boost\\filesystem.hpp>\n\n#include <stride_range.h>\n#include <tree.h>\n#include <minmax>\n\n#include \"Math3D.h\"\n#include \"SmartPointers.h\"\n#include \"String.h\"\n\n//#if defined __AVX__\n//#undef __AVX__ //#error Eigen have problem with AVX now\n//#endif\n//#define EIGEN_HAS_CXX11_MATH 1\n//#define EIGEN_HAS_STD_RESULT_OF 1\n//#define EIGEN_HAS_VARIADIC_TEMPLATES 1\n//#include <Eigen\\Dense>\n\n\nnamespace Causality\n{\n\tusing time_seconds = std::chrono::duration<double>;\n\ttypedef uint64_t id_t;\n\n\tusing std::string;\n\tusing std::iterator_range;\n\t//using boost::sub_range;\n\n\t//namespace adaptors = boost::adaptors;\n\n\tusing gsl::owner;\n\tusing gsl::byte;\n\tusing gsl::not_null;\n\n\tusing stdx::tree_node;\n\tusing stdx::foward_tree_node;\n\tusing stdx::stride_range;\n\tusing stdx::stride_iterator;\n\n\tusing std::vector;\n\tusing std::map;\n\tusing std::function;\n\tusing std::unique_ptr;\n\tusing std::shared_ptr;\n\tusing std::list;\n\tusing std::weak_ptr;\n}", "meta": {"hexsha": "b4f6a6791ea47e8f3a51dc67bfeab41579516e79", "size": 1467, "ext": "h", "lang": "C", "max_stars_repo_path": "Causality/BCL.h", "max_stars_repo_name": "ArcEarth/SrInspection", "max_stars_repo_head_hexsha": "63c540d1736e323a0f409914e413cb237f03c5c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-07-13T18:30:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-31T22:20:34.000Z", "max_issues_repo_path": "Causality/BCL.h", "max_issues_repo_name": "ArcEarth/SrInspection", "max_issues_repo_head_hexsha": "63c540d1736e323a0f409914e413cb237f03c5c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Causality/BCL.h", "max_forks_repo_name": "ArcEarth/SrInspection", "max_forks_repo_head_hexsha": "63c540d1736e323a0f409914e413cb237f03c5c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-01-16T14:25:28.000Z", "max_forks_repo_forks_event_max_datetime": "2017-06-12T16:15:18.000Z", "avg_line_length": 20.375, "max_line_length": 57, "alphanum_fraction": 0.7348329925, "num_tokens": 387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3923368443773709, "lm_q2_score": 0.033085980176357166, "lm_q1q2_score": 0.01298084905552422}}
{"text": "/* gsl_splinalg.h\n * \n * Copyright (C) 2012-2014 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_SPLINALG_H__\n#define __GSL_SPLINALG_H__\n\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_spmatrix.h>\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_types.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\n/* iteration solver type */\ntypedef struct\n{\n  const char *name;\n  void * (*alloc) (const size_t n, const size_t m);\n  int (*iterate) (const gsl_spmatrix *A, const gsl_vector *b,\n                  const double tol, gsl_vector *x, void *);\n  double (*normr)(const void *);\n  void (*free) (void *);\n} gsl_splinalg_itersolve_type;\n\ntypedef struct\n{\n  const gsl_splinalg_itersolve_type * type;\n  double normr; /* current residual norm || b - A x || */\n  void * state;\n} gsl_splinalg_itersolve;\n\n/* available types */\nGSL_VAR const gsl_splinalg_itersolve_type * gsl_splinalg_itersolve_gmres;\n\n/*\n * Prototypes\n */\ngsl_splinalg_itersolve *\ngsl_splinalg_itersolve_alloc(const gsl_splinalg_itersolve_type *T,\n                             const size_t n, const size_t m);\nvoid gsl_splinalg_itersolve_free(gsl_splinalg_itersolve *w);\nconst char *gsl_splinalg_itersolve_name(const gsl_splinalg_itersolve *w);\nint gsl_splinalg_itersolve_iterate(const gsl_spmatrix *A,\n                                   const gsl_vector *b,\n                                   const double tol, gsl_vector *x,\n                                   gsl_splinalg_itersolve *w);\ndouble gsl_splinalg_itersolve_normr(const gsl_splinalg_itersolve *w);\n\n__END_DECLS\n\n#endif /* __GSL_SPLINALG_H__ */\n", "meta": {"hexsha": "265b6ae60b659991dd6f0a242ee354bae9476373", "size": 2489, "ext": "h", "lang": "C", "max_stars_repo_path": "315/gsltest/gsl/include/gsl/gsl_splinalg.h", "max_stars_repo_name": "shi-bash-cmd/qtTest", "max_stars_repo_head_hexsha": "3eb0cf4b8fcfa2c36e133e4df2b2a3e6d2d3e589", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-12-18T16:35:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-14T07:38:05.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/splinalg/gsl_splinalg.h", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2020-05-29T16:26:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-07T08:59:52.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/splinalg/gsl_splinalg.h", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-06-27T11:11:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T19:22:30.000Z", "avg_line_length": 31.1125, "max_line_length": 81, "alphanum_fraction": 0.7111289675, "num_tokens": 645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926197162523, "lm_q2_score": 0.028870906632945795, "lm_q1q2_score": 0.012974372365362835}}
{"text": "//\n// Copyright (c) 2009, Markus Rickert\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are met:\n//\n// * Redistributions of source code must retain the above copyright notice,\n//   this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above copyright notice,\n//   this list of conditions and the following disclaimer in the documentation\n//   and/or other materials provided with the distribution.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n// POSSIBILITY OF SUCH DAMAGE.\n//\n\n#include <chrono>\n#include <memory>\n#include <nlopt.h>\n#include <random>\n#include <utility>\n\n#include \"Exception.h\"\n#include \"IterativeInverseKinematics.h\"\n\nnamespace rl\n{\n\tnamespace mdl\n\t{\n\t\tclass RL_MDL_EXPORT WeightedInverseKinematics : public IterativeInverseKinematics\n\t\t{\n\t\tpublic:\n\t\t\tclass Exception : public ::rl::mdl::Exception\n\t\t\t{\n\t\t\tpublic:\n\t\t\t\tException(const ::nlopt_result& result);\n\t\t\t\t\n\t\t\t\tvirtual ~Exception() throw();\n\t\t\t\t\n\t\t\t\tstatic void check(const ::nlopt_result& result);\n\t\t\t\t\n\t\t\t\t::nlopt_result getResult() const;\n\t\t\t\t\n\t\t\t\tvirtual const char* what() const throw();\n\t\t\t\t\n\t\t\tprotected:\n\t\t\t\t\n\t\t\tprivate:\n\t\t\t\t::nlopt_result result;\n\t\t\t};\n\t\t\t\n\t\t\tWeightedInverseKinematics(Kinematic* kinematic);\n\t\t\t\n\t\t\tvirtual ~WeightedInverseKinematics();\n\t\t\t\n\t\t\t::rl::math::Real getFunctionToleranceAbsolute() const;\n\t\t\t\n\t\t\t::rl::math::Real getFunctionToleranceRelative() const;\n\t\t\t\n\t\t\tconst ::rl::math::Vector& getLowerBound() const;\n\t\t\t\n\t\t\t::rl::math::Vector getOptimizationToleranceAbsolute() const;\n\t\t\t\n\t\t\t::rl::math::Real getOptimizationToleranceRelative() const;\n\t\t\t\n\t\t\tconst ::rl::math::Vector& getUpperBound() const;\n\t\t\t\n\t\t\tvoid seed(const ::std::mt19937::result_type& value);\n\t\t\t\n\t\t\tvoid setEpsilon(const ::rl::math::Real& epsilon);\n\t\t\t\n\t\t\tvoid setFunctionToleranceAbsolute(const ::rl::math::Real& functionToleranceAbsolute);\n\t\t\t\n\t\t\tvoid setFunctionToleranceRelative(const ::rl::math::Real& functionToleranceRelative);\n\t\t\t\n\t\t\tvoid setLowerBound(const ::rl::math::Vector& lb);\n\t\t\t\n\t\t\tvoid setOptimizationToleranceAbsolute(const ::rl::math::Real& optimizationToleranceAbsolute);\n\t\t\t\n\t\t\tvoid setOptimizationToleranceAbsolute(const ::rl::math::Vector& optimizationToleranceAbsolute);\n\t\t\t\n\t\t\tvoid setOptimizationToleranceRelative(const ::rl::math::Real& optimizationToleranceRelative);\n\t\t\t\n\t\t\tvoid setUpperBound(const ::rl::math::Vector& ub);\n\t\t\t\n\t\t\tbool solve();\n\t\t\t\n\t\tprotected:\n\t\t\t\n\t\tprivate:\n\t\t\tstatic double f(unsigned int n, const double* x, double* grad, void* data);\n\t\t\t\n\t\t\t::std::size_t iteration;\n\t\t\t\n\t\t\t::rl::math::Vector lb;\n\t\t\t\n\t\t\t::std::unique_ptr<::nlopt_opt_s, decltype(&::nlopt_destroy)> opt;\n\t\t\t\n\t\t\t::std::uniform_real_distribution<::rl::math::Real> randDistribution;\n\t\t\t\n\t\t\t::std::mt19937 randEngine;\n\t\t\t\n\t\t\t::rl::math::Vector ub;\n\t\t};\n\t}\n}\n\n", "meta": {"hexsha": "5830386a1c346daec1e62af981f0962ef06cc7fa", "size": 3638, "ext": "h", "lang": "C", "max_stars_repo_path": "src/rl/mdl/WeightedInverseKinematics.h", "max_stars_repo_name": "Mark-Yeatman/rl", "max_stars_repo_head_hexsha": "1579ba2097576818dadb447d314edfb336293c6d", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/rl/mdl/WeightedInverseKinematics.h", "max_issues_repo_name": "Mark-Yeatman/rl", "max_issues_repo_head_hexsha": "1579ba2097576818dadb447d314edfb336293c6d", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/rl/mdl/WeightedInverseKinematics.h", "max_forks_repo_name": "Mark-Yeatman/rl", "max_forks_repo_head_hexsha": "1579ba2097576818dadb447d314edfb336293c6d", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8305084746, "max_line_length": 98, "alphanum_fraction": 0.7157778999, "num_tokens": 867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207955, "lm_q2_score": 0.026355349978307813, "lm_q1q2_score": 0.012971790572092431}}
{"text": "#ifndef utils_h\n#define utils_h\n\n#include <ceed.h>\n#include <petsc.h>\n\n// Translate PetscMemType to CeedMemType\nstatic inline CeedMemType MemTypeP2C(PetscMemType mem_type) {\n  return PetscMemTypeDevice(mem_type) ? CEED_MEM_DEVICE : CEED_MEM_HOST;\n}\n\n#endif // utils_h", "meta": {"hexsha": "4d85e777c503eb9b153b80196e1ca79a110ccae7", "size": 267, "ext": "h", "lang": "C", "max_stars_repo_path": "examples/solids/include/utils.h", "max_stars_repo_name": "AdelekeBankole/libCEED", "max_stars_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 123.0, "max_stars_repo_stars_event_min_datetime": "2018-01-29T02:04:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T18:13:48.000Z", "max_issues_repo_path": "examples/solids/include/utils.h", "max_issues_repo_name": "AdelekeBankole/libCEED", "max_issues_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 781.0, "max_issues_repo_issues_event_min_datetime": "2017-12-22T17:20:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T21:34:34.000Z", "max_forks_repo_path": "examples/solids/include/utils.h", "max_forks_repo_name": "AdelekeBankole/libCEED", "max_forks_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2017-12-27T22:35:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:02:07.000Z", "avg_line_length": 22.25, "max_line_length": 72, "alphanum_fraction": 0.7865168539, "num_tokens": 75, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1732882059293266, "lm_q2_score": 0.07477005012394414, "lm_q1q2_score": 0.012956767843224103}}
{"text": "/* histogram/ntuple.c\n * \n * Copyright (C) 2000 Simone Piccardi\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n/* Jan/2001 Modified by Brian Gough. Minor changes for GSL */\n\n#include <config.h>\n#include <errno.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_ntuple.h>\n\n/* \n * gsl_ntuple_open:\n * Initialize an ntuple structure and create the related file\n */\n\ngsl_ntuple *\ngsl_ntuple_create (char *filename, void *ntuple_data, size_t size)\n{\n  gsl_ntuple *ntuple = malloc (sizeof (gsl_ntuple));\n\n  if (ntuple == 0)\n    {\n      GSL_ERROR_VAL (\"failed to allocate space for ntuple struct\",\n\t\t     GSL_ENOMEM, 0);\n    }\n\n  ntuple->ntuple_data = ntuple_data;\n  ntuple->size = size;\n\n  ntuple->file = fopen (filename, \"wb\");\n\n  if (ntuple->file == 0)\n    {\n      free (ntuple);\n      GSL_ERROR_VAL (\"unable to create ntuple file\", GSL_EFAILED, 0);\n    }\n\n  return ntuple;\n}\n\n/* \n * gsl_ntuple_open:\n * Initialize an ntuple structure and open the related file\n */\n\ngsl_ntuple *\ngsl_ntuple_open (char *filename, void *ntuple_data, size_t size)\n{\n  gsl_ntuple *ntuple = malloc (sizeof (gsl_ntuple));\n\n  if (ntuple == 0)\n    {\n      GSL_ERROR_VAL (\"failed to allocate space for ntuple struct\",\n\t\t     GSL_ENOMEM, 0);\n    }\n\n  ntuple->ntuple_data = ntuple_data;\n  ntuple->size = size;\n\n  ntuple->file = fopen (filename, \"rb\");\n\n  if (ntuple->file == 0)\n    {\n      free (ntuple);\n      GSL_ERROR_VAL (\"unable to open ntuple file for reading\", \n                     GSL_EFAILED, 0);\n    }\n\n  return ntuple;\n}\n\n/* \n * gsl_ntuple_write:\n * write to file a data row, must be used in a loop!\n */\n\nint\ngsl_ntuple_write (gsl_ntuple * ntuple)\n{\n  size_t nwrite;\n\n  nwrite = fwrite (ntuple->ntuple_data, ntuple->size,\n\t\t   1, ntuple->file);\n\n  if (nwrite != 1)\n    {\n      GSL_ERROR (\"failed to write ntuple entry to file\", GSL_EFAILED);\n    }\n\n  return GSL_SUCCESS;\n}\n\n/* the following function is a synonym for gsl_ntuple_write */\n\nint\ngsl_ntuple_bookdata (gsl_ntuple * ntuple)\n{\n  return gsl_ntuple_write (ntuple);\n}\n\n/* \n * gsl_ntuple_read:\n * read form file a data row, must be used in a loop!\n */\n\nint\ngsl_ntuple_read (gsl_ntuple * ntuple)\n{\n  size_t nread;\n\n  nread = fread (ntuple->ntuple_data, ntuple->size, 1, ntuple->file);\n\n  if (nread == 0 && feof(ntuple->file))\n    {\n      return GSL_EOF;\n    }\n\n  if (nread != 1)\n    {\n      GSL_ERROR (\"failed to read ntuple entry from file\", GSL_EFAILED);\n    }\n\n  return GSL_SUCCESS;\n}\n\n/* \n * gsl_ntuple_project:\n * fill an histogram with an ntuple file contents, use\n * SelVal and SelFunc user defined functions to get \n * the value to book and the selection funtion\n */\n\n#define EVAL(f,x) ((*((f)->function))(x,(f)->params))\n\nint\ngsl_ntuple_project (gsl_histogram * h, gsl_ntuple * ntuple,\n                    gsl_ntuple_value_fn * value_func, \n                    gsl_ntuple_select_fn * select_func)\n{\n  size_t nread;\n\n  do\n    {\n      nread = fread (ntuple->ntuple_data, ntuple->size,\n                     1, ntuple->file);\n\n      if (nread == 0 && feof(ntuple->file))\n        {\n          break ;\n        }\n      \n      if (nread != 1) \n        {\n\t  GSL_ERROR (\"failed to read ntuple for projection\", GSL_EFAILED);\n\t}\n\n      if (EVAL(select_func, ntuple->ntuple_data))\n\t{\n\t  gsl_histogram_increment (h, EVAL(value_func, ntuple->ntuple_data));\n\t}\n    }\n  while (1);\n\n  return GSL_SUCCESS;\n}\n\n\n/* \n * gsl_ntuple_close:\n * close the ntuple file and free the memory\n */\n\nint\ngsl_ntuple_close (gsl_ntuple * ntuple)\n{\n  int status = fclose (ntuple->file);\n  \n  if (status)\n    {\n      GSL_ERROR (\"failed to close ntuple file\", GSL_EFAILED);\n    }\n\n  free (ntuple);\n\n  return GSL_SUCCESS;\n}\n", "meta": {"hexsha": "cf7b2f5ea9283b2105a2327f73c9730134b2c2b0", "size": 4283, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/ntuple/ntuple.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/ntuple/ntuple.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/ntuple/ntuple.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 21.0985221675, "max_line_length": 72, "alphanum_fraction": 0.6493112304, "num_tokens": 1206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2974699550610674, "lm_q2_score": 0.04336580200934005, "lm_q1q2_score": 0.012900023174905531}}
{"text": "/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*\n**                                                                                  **\n** This file forms part of the Underworld geophysics modelling application.         **\n**                                                                                  **\n** For full license and copyright information, please refer to the LICENSE.md file  **\n** located at the project root, or contact the authors.                             **\n**                                                                                  **\n**~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/\n#include <stdlib.h>\n#include <string.h>\n#include <assert.h>\n#include <mpi.h>\n#include <petsc.h>\n#include <petscvec.h>\n#include <petscmat.h>\n#include <petscksp.h>\n#include <petscpc.h>\n#include <petscsnes.h>\n\n#include <petscversion.h>\n#if ( (PETSC_VERSION_MAJOR >= 3) && (PETSC_VERSION_MINOR >=3) )\n  #if (PETSC_VERSION_MINOR >=6)\n     #include <petsc/private/kspimpl.h>\n  #else\n     #include <petsc-private/kspimpl.h>   /*I \"petscksp.h\" I*/\n     //#include \"petsc-private/kspimpl.h\"\n  #endif\n#else\n  #include \"private/kspimpl.h\"   /*I \"petscksp.h\" I*/\n#endif\n\n#include <StGermain/libStGermain/src/StGermain.h>\n#include <StgDomain/libStgDomain/src/StgDomain.h>\n#include <StgFEM/libStgFEM/src/StgFEM.h>\n#include <PICellerator/libPICellerator/src/PICellerator.h>\n#include <Underworld/libUnderworld/src/Underworld.h>\n#include \"Solvers/SLE/src/SLE.h\" /* to give the AugLagStokes_SLE type */\n#include \"Solvers/KSPSolvers/src/KSPSolvers.h\"\n\n#include \"BSSCR.h\"\n#include \"createK2.h\"\n#include \"writeMatVec.h\"\n#include \"ksp_pressure_nullspace.h\"\n\n#define KSPBSSCR         \"bsscr\"\n\nEXTERN_C_BEGIN\nEXTERN PetscErrorCode PETSCKSP_DLLEXPORT KSPCreate_BSSCR(KSP);\nEXTERN_C_END\n\nPetscErrorCode BSSCR_DRIVER_auglag( KSP ksp, Mat stokes_A, Vec stokes_x, Vec stokes_b, Mat approxS,\n                                    MatStokesBlockScaling BA, PetscTruth sym, KSP_BSSCR * bsscrp_self );\nPetscErrorCode BSSCR_DRIVER_flex( KSP ksp, Mat stokes_A, Vec stokes_x, Vec stokes_b, Mat approxS, KSP ksp_K,\n                                  MatStokesBlockScaling BA, PetscTruth sym, KSP_BSSCR * bsscrp_self );\n\n/*************************************************************************************************/\n/****** START Helper Functions *******************************************************************/\n#define BSSCR_GetPetscMatrix( matrix ) ( (Mat)(matrix) )\n/****** END Helper Functions *********************************************************************/\n/*************************************************************************************************/\ntypedef struct {\n    void *ctx;\n    KSP_BSSCR * bsscr;\n} BSSCR_KSPConverged_Ctx;\n\n\n/*************************************************************************************************/\n/*************************************************************************************************/\n\n#undef __FUNCT__\n#define __FUNCT__ \"BSSCR_KSPSetConvergenceMinIts\"\nPetscErrorCode BSSCR_KSPSetConvergenceMinIts(KSP ksp, PetscInt n, KSP_BSSCR * bsscr)\n{\n      BSSCR_KSPConverged_Ctx *ctx;\n      PetscErrorCode ierr;\n\n      PetscFunctionBegin;\n\n      bsscr->min_it = n; /* set minimum its */\n\n#if ( (PETSC_VERSION_MAJOR == 3) && (PETSC_VERSION_MINOR >= 5 ) )\n      ierr = Stg_PetscNew(BSSCR_KSPConverged_Ctx,&ctx);CHKERRQ(ierr);\n      ierr = KSPConvergedDefaultCreate(&ctx->ctx);CHKERRQ(ierr);\n      ctx->bsscr=bsscr;\n      ierr = KSPSetConvergenceTest(ksp,BSSCR_KSPConverged,ctx,BSSCR_KSPConverged_Destroy);CHKERRQ(ierr);\n#endif\n#if ( (PETSC_VERSION_MAJOR == 3) && (PETSC_VERSION_MINOR <=4 ) )\n      ierr = Stg_PetscNew(BSSCR_KSPConverged_Ctx,&ctx);CHKERRQ(ierr);\n      ierr = KSPDefaultConvergedCreate(&ctx->ctx);CHKERRQ(ierr);\n      ctx->bsscr=bsscr;\n      ierr = KSPSetConvergenceTest(ksp,BSSCR_KSPConverged,ctx,BSSCR_KSPConverged_Destroy);CHKERRQ(ierr);\n#endif\n#if ( PETSC_VERSION_MAJOR < 3)\n      ierr = KSPSetConvergenceTest(ksp,BSSCR_KSPConverged,(void*)bsscr);CHKERRQ(ierr);\n#endif\n\n      PetscFunctionReturn(0);\n}\n\n#undef __FUNCT__\n#define __FUNCT__ \"BSSCR_KSPConverged\"\nPetscErrorCode BSSCR_KSPConverged(KSP ksp,PetscInt n,PetscReal rnorm,KSPConvergedReason *reason,void *cctx)\n{\n  PetscErrorCode           ierr;\n#if(PETSC_VERSION_MAJOR == 3)\n  BSSCR_KSPConverged_Ctx  *ctx = (BSSCR_KSPConverged_Ctx *)cctx;\n  KSP_BSSCR               *bsscr = ctx->bsscr;\n#else\n  KSP_BSSCR               *bsscr = (KSP_BSSCR*)cctx;\n#endif\n\n\n  PetscFunctionBegin;\n#if ( (PETSC_VERSION_MAJOR == 3) && (PETSC_VERSION_MINOR >=5 ) )\n  ierr = KSPConvergedDefault(ksp,n,rnorm,reason,ctx->ctx);CHKERRQ(ierr);\n#endif\n#if ( (PETSC_VERSION_MAJOR == 3) && (PETSC_VERSION_MINOR <=4 ) )\n  ierr = KSPDefaultConverged(ksp,n,rnorm,reason,ctx->ctx);CHKERRQ(ierr);\n#endif\n#if ( PETSC_VERSION_MAJOR < 3)\n  ierr = KSPDefaultConverged(ksp,n,rnorm,reason,cctx);CHKERRQ(ierr);\n#endif\n  if (*reason) {\n    ierr = PetscInfo2(ksp,\"default convergence test KSP iterations=%D, rnorm=%G\\n\",n,rnorm);CHKERRQ(ierr);\n  }\n  if(ksp->its < bsscr->min_it){\n      ksp->reason          = KSP_CONVERGED_ITERATING;\n  }\n  PetscFunctionReturn(0);\n}\n\n#undef __FUNCT__\n#define __FUNCT__ \"BSSCR_KSPConverged_Destroy\"\nPetscErrorCode BSSCR_KSPConverged_Destroy(void *cctx)\n{\n  BSSCR_KSPConverged_Ctx *ctx = (BSSCR_KSPConverged_Ctx *)cctx;\n  PetscErrorCode           ierr;\n\n  PetscFunctionBegin;\n#if ( (PETSC_VERSION_MAJOR == 3) && (PETSC_VERSION_MINOR >=5 ) )\n  ierr = KSPConvergedDefaultDestroy(ctx->ctx);CHKERRQ(ierr);\n#else\n  ierr = KSPDefaultConvergedDestroy(ctx->ctx);CHKERRQ(ierr);\n#endif\n  ierr = PetscFree(ctx);CHKERRQ(ierr);\n  PetscFunctionReturn(0);\n}\n\n#undef __FUNCT__\n#define __FUNCT__ \"KSPRegisterBSSCR\"\nPetscErrorCode PETSCKSP_DLLEXPORT KSPRegisterBSSCR(const char path[])\n{\n    PetscErrorCode ierr;\n\n    PetscFunctionBegin;\n    ierr = Stg_KSPRegister(KSPBSSCR, path, \"KSPCreate_BSSCR\", KSPCreate_BSSCR );CHKERRQ(ierr);\n    PetscFunctionReturn(0);\n}\n\n\n#undef __FUNCT__\n#define __FUNCT__ \"KSPSolve_BSSCR\"\nPetscErrorCode  KSPSolve_BSSCR(KSP ksp)\n{\n    Mat            Amat,Pmat; /* Stokes Matrix and it's Preconditioner matrix: Both 2x2 PetscExt block matrices */\n    Vec            B, X; /* rhs and solution vectors */\n    //MatStructure   pflag;\n    PetscErrorCode ierr;\n    KSP_BSSCR *    bsscr;\n    Stokes_SLE *    SLE;\n    //PETScMGSolver * MG;\n    Mat K,D,ApproxS;\n    MatStokesBlockScaling BA;\n    PetscTruth flg, sym, augment;\n    double TotalSolveTime;\n\n    PetscFunctionBegin;\n\n    TotalSolveTime = MPI_Wtime();\n\n    PetscPrintf( PETSC_COMM_WORLD, \"\\nBSSCR -- Block Stokes Schur Compliment Reduction Solver \\n\");\n    /** Get the stokes Block matrix and its preconditioner matrix */\n    ierr = Stg_PCGetOperators(ksp->pc,&Amat,&Pmat,PETSC_NULL);CHKERRQ(ierr);\n\n    /** In Petsc proper, KSP's ksp->data is usually set in KSPCreate_XXX function.\n        Here it is set in the _StokesBlockKSPInterface_Solve function instead so that we can ensure that the solver\n        has everything it needs */\n\n    bsscr         = (KSP_BSSCR*)ksp->data;\n    //MG            = (PETScMGSolver*)bsscr->mg;\n    SLE           = (Stokes_SLE*)bsscr->st_sle;\n    X             = ksp->vec_sol;\n    B             = ksp->vec_rhs;\n\n    if( bsscr->do_scaling ){\n        (*bsscr->scale)(ksp); /* scales everything including the UW preconditioner */\n        BA =  bsscr->BA;\n    }\n\n    if( (bsscr->k2type != 0) ){\n      if(bsscr->buildK2 != PETSC_NULL) {\n            (*bsscr->buildK2)(ksp); /* building K2 from scaled version of stokes operators: K2 lives on bsscr struct = ksp->data */\n        }\n    }\n\n    /* get sub matrix / vector objects */\n    MatNestGetSubMat( Amat, 0,0, &K );\n    /* Underworld preconditioner matrix*/\n    ApproxS = PETSC_NULL;\n    if( ((StokesBlockKSPInterface*)SLE->solver)->preconditioner ) { /* SLE->solver->st_sle == SLE here, by the way */\n        StiffnessMatrix *preconditioner;\n        preconditioner = ((StokesBlockKSPInterface*)SLE->solver)->preconditioner;\n        ApproxS = BSSCR_GetPetscMatrix( preconditioner->matrix );\n    }\n\n    sym = bsscr->DIsSym;\n\n    MatNestGetSubMat( Amat, 1,0, &D );if(!D){ PetscPrintf( PETSC_COMM_WORLD, \"D does not exist but should!!\\n\"); exit(1); }\n\n    /**********************************************************/\n    /******* SOLVE!! ******************************************/\n    /**********************************************************/\n    \n    flg = PETSC_FALSE;\n    augment = PETSC_TRUE;\n    PetscOptionsGetTruth(PETSC_NULL, \"-augmented_lagrangian\", &augment, &flg);\n    BSSCR_DRIVER_auglag( ksp, Amat, X, B, ApproxS, BA, sym, bsscr );\n\n    /**********************************************************/\n    /***** END SOLVE!! ****************************************/\n    /**********************************************************/\n    if( bsscr->do_scaling ){\n        (*bsscr->unscale)(ksp);  }\n    if( (bsscr->k2type != 0) && bsscr->K2 != PETSC_NULL ){\n        if(bsscr->k2type != K2_SLE){/* don't destroy here, as in this case, K2 is just pointing to an existing matrix on the SLE */\n            Stg_MatDestroy(&bsscr->K2 );\n        }\n        bsscr->K2built = PETSC_FALSE;\n        bsscr->K2 = PETSC_NULL;  }\n\n    ksp->reason = KSP_CONVERGED_RTOL;\n\n    TotalSolveTime =  MPI_Wtime() - TotalSolveTime;\n    PetscPrintf( PETSC_COMM_WORLD, \"  Total BSSCR Linear solve time: %lf seconds\\n\\n\", TotalSolveTime);\n    bsscr->solver->stats.total_time=TotalSolveTime;\n    PetscFunctionReturn(0);\n}\n\n#undef __FUNCT__\n#define __FUNCT__ \"KSPDestroy_BSSCR\"\nPetscErrorCode KSPDestroy_BSSCR(KSP ksp)\n{\n    KSP_BSSCR     *bsscr = (KSP_BSSCR *)ksp->data;\n    Mat            K2=bsscr->K2;\n    Vec            t,v;\n    MatStokesBlockScaling BA=bsscr->BA;\n    PetscErrorCode ierr;\n\n    PetscFunctionBegin;\n\n    t=bsscr->t;\n    v=bsscr->v;\n    if ( v ){ Stg_VecDestroy(&v); }\n    if ( t ){ Stg_VecDestroy(&t); }\n    if( K2 ){ Stg_MatDestroy(&K2 ); }/* shouldn't need this now */\n    if(BA) BSSCR_MatStokesBlockScalingDestroy( BA );\n    ierr = PetscFree(ksp->data);CHKERRQ(ierr);\n\n    PetscFunctionReturn(0);\n}\nstatic const char *K2Types[] = {\"NULL\",\"DGMGD\",\"GMG\",\"GG\",\"SLE\",\"K2Type\",\"K2_\",0};\n#undef __FUNCT__\n#define __FUNCT__ \"KSPSetFromOptions_BSSCR\"\n#if ( (PETSC_VERSION_MAJOR >= 3) && (PETSC_VERSION_MINOR <6) )\nPetscErrorCode KSPSetFromOptions_BSSCR(KSP ksp)\n{\n\n    PetscTruth  flg;\n    KSP_BSSCR  *bsscr = (KSP_BSSCR *)ksp->data;\n    PetscErrorCode ierr;\n    PetscFunctionBegin;\n    ierr = PetscOptionsHead(\"KSP BSSCR options\");CHKERRQ(ierr);\n    /* if this ksp has a prefix \"XXX_\" it will be automatically added to the options. e.g. -ksp_test -> -XXX_ksp_test */\n    /* ierr = PetscOptionsTruth(\"-ksp_test\",\"Test KSP flag\",\"nil\",PETSC_FALSE,&test,PETSC_NULL);CHKERRQ(ierr); */\n    /* if(test){ PetscPrintf( PETSC_COMM_WORLD,  \"\\n\\n-----  test flag set  ------\\n\\n\"); } */\n    ierr = PetscOptionsEnum(\"-ksp_k2_type\",\"Augmented Lagrangian matrix type\",\"\",K2Types, bsscr->k2type,(PetscEnum*)&bsscr->k2type,&flg);CHKERRQ(ierr);\n    //if(flg){  PetscPrintf( PETSC_COMM_WORLD,  \"-----  k2 type is  ------\\n\"); }\n    ierr = PetscOptionsTail();CHKERRQ(ierr);\n    PetscFunctionReturn(0);\n}\n#else\nPetscErrorCode KSPSetFromOptions_BSSCR(Stg_PetscOptions *PetscOptionsObject, KSP ksp)\n{\n\n    PetscTruth  flg;\n    KSP_BSSCR  *bsscr = (KSP_BSSCR *)ksp->data;\n    PetscErrorCode ierr;\n    PetscFunctionBegin;\n    ierr = PetscOptionsHead(PetscOptionsObject,\"KSP BSSCR options\");CHKERRQ(ierr);\n    /* if this ksp has a prefix \"XXX_\" it will be automatically added to the options. e.g. -ksp_test -> -XXX_ksp_test */\n    /* ierr = PetscOptionsTruth(\"-ksp_test\",\"Test KSP flag\",\"nil\",PETSC_FALSE,&test,PETSC_NULL);CHKERRQ(ierr); */\n    /* if(test){ PetscPrintf( PETSC_COMM_WORLD,  \"\\n\\n-----  test flag set  ------\\n\\n\"); } */\n    ierr = PetscOptionsEnum(\"-ksp_k2_type\",\"Augmented Lagrangian matrix type\",\"\",K2Types, bsscr->k2type,(PetscEnum*)&bsscr->k2type,&flg);CHKERRQ(ierr);\n    //if(flg){  PetscPrintf( PETSC_COMM_WORLD,  \"-----  k2 type is  ------\\n\"); }\n    ierr = PetscOptionsTail();CHKERRQ(ierr);\n    PetscFunctionReturn(0);\n}\n#endif\n\n#undef __FUNCT__\n#define __FUNCT__ \"KSPView_BSSCR\"\nPetscErrorCode KSPView_BSSCR(KSP ksp,PetscViewer viewer)\n{\n    PetscFunctionReturn(0);\n}\n\n#undef __FUNCT__\n#define __FUNCT__ \"KSPSetUp_BSSCR\"\nPetscErrorCode KSPSetUp_BSSCR(KSP ksp)\n{\n    KSP_BSSCR  *bsscr = (KSP_BSSCR *)ksp->data;\n    Mat K;\n    Stokes_SLE*  stokesSLE  = (Stokes_SLE*)bsscr->st_sle;\n    PetscTruth ismumps,augment,scale,konly,found,conp,checkerp;\n\n    PetscFunctionBegin;\n\n    BSSCR_PetscExtStokesSolversInitialize();\n\n    K = stokesSLE->kStiffMat->matrix;\n    bsscr->K2=PETSC_NULL;\n\n    BSSCR_MatStokesBlockScalingCreate( &(bsscr->BA) );/* allocate memory for scaling struct */\n    found = PETSC_FALSE;\n    augment = PETSC_TRUE;\n    PetscOptionsGetTruth(PETSC_NULL, \"-augmented_lagrangian\", &augment, &found);\n    if(augment){\n        bsscr->buildK2 = bsscr_buildK2; }\n    else {\n        bsscr->buildK2 = PETSC_NULL; }\n\n    /***************************************************************************************************************/\n    /** Do scaling *************************************************************************************************/\n    /***************************************************************************************************************/\n    found = PETSC_FALSE;\n    scale = PETSC_FALSE;/* scaling off by default */\n    PetscOptionsGetTruth(PETSC_NULL, \"-rescale_equations\", &scale, &found);\n    Stg_PetscObjectTypeCompare((PetscObject)K, \"mataijmumps\", &ismumps);/** older versions of petsc have this */\n    if(ismumps && scale){\n        PetscPrintf( PETSC_COMM_WORLD, \"\\t* Not applying scaling to matrices as MatGetRowMax operation not defined for MATAIJMUMPS matrix type \\n\");\n        scale = PETSC_FALSE;\n    }\n    if( scale ) {\n        bsscr->scale       = KSPScale_BSSCR;\n        bsscr->unscale     = KSPUnscale_BSSCR;\n        bsscr->do_scaling  = PETSC_TRUE;\n        bsscr->scaletype   = KONLY;\n        konly = PETSC_TRUE;\n        found = PETSC_FALSE;\n        PetscOptionsGetTruth(PETSC_NULL, \"-k_scale_only\", &konly, &found);\n        if(!konly){ bsscr->scaletype = DEFAULT; }\n    }\n\n    /***************************************************************************************************************/\n    /**  Set up functions for building Pressure Null Space Vectors *************************************************/\n    /***************************************************************************************************************/\n    found = PETSC_FALSE;\n    checkerp = PETSC_FALSE;\n    PetscOptionsGetTruth(PETSC_NULL, \"-remove_checkerboard_pressure_null_space\", &checkerp, &found );\n    if(checkerp){\n        bsscr->check_cb_pressureNS    = PETSC_TRUE;\n        bsscr->check_pressureNS       = PETSC_TRUE;\n        bsscr->buildPNS               = KSPBuildPressure_CB_Nullspace_BSSCR;\n    }\n    found = PETSC_FALSE;\n    conp = PETSC_FALSE;\n    PetscOptionsGetTruth(PETSC_NULL, \"-remove_constant_pressure_null_space\", &conp, &found );\n    if(conp){\n        bsscr->check_const_pressureNS = PETSC_TRUE;\n        bsscr->check_pressureNS       = PETSC_TRUE;\n        bsscr->buildPNS               = KSPBuildPressure_Const_Nullspace_BSSCR;\n    }\n    /***************************************************************************************************************/\n    PetscFunctionReturn(0);\n}\n\nEXTERN_C_BEGIN\n#undef __FUNCT__\n#define __FUNCT__ \"KSPCreate_BSSCR\"\nPetscErrorCode PETSCKSP_DLLEXPORT KSPCreate_BSSCR(KSP ksp)\n{\n    KSP_BSSCR  *bsscr;\n    PetscErrorCode ierr;\n    PetscFunctionBegin;\n    ierr = Stg_PetscNew(KSP_BSSCR,&bsscr);CHKERRQ(ierr);\n    ierr = PetscLogObjectMemory((PetscObject)ksp,sizeof(KSP_BSSCR));CHKERRQ(ierr);\n    //ierr = PetscNewLog(ksp,KSP_BSSCR,&bsscr);CHKERRQ(ierr);\n    ksp->data                              = (void*)bsscr;\n\n    #if ( (PETSC_VERSION_MAJOR >= 3) && (PETSC_VERSION_MINOR >= 2 ) )\n    ierr = KSPSetSupportedNorm(ksp,KSP_NORM_PRECONDITIONED,PC_LEFT,0);CHKERRQ(ierr);\n    ierr = KSPSetSupportedNorm(ksp,KSP_NORM_UNPRECONDITIONED,PC_LEFT,1);CHKERRQ(ierr);\n    ierr = KSPSetSupportedNorm(ksp,KSP_NORM_NATURAL,PC_LEFT,0);CHKERRQ(ierr);\n    ierr = KSPSetSupportedNorm(ksp,KSP_NORM_NONE,PC_LEFT,1);CHKERRQ(ierr);\n    #endif\n    /*\n       Sets the functions that are associated with this data structure\n       (in C++ this is the same as defining virtual functions)\n    */\n    ksp->ops->setup                = KSPSetUp_BSSCR;\n    ksp->ops->solve                = KSPSolve_BSSCR;\n    ksp->ops->destroy              = KSPDestroy_BSSCR;\n    ksp->ops->view                 = KSPView_BSSCR;\n    ksp->ops->setfromoptions       = KSPSetFromOptions_BSSCR;\n    ksp->ops->buildsolution        = KSPDefaultBuildSolution;\n    ksp->ops->buildresidual        = KSPDefaultBuildResidual;\n\n//    bsscr->k2type=K2_GMG;\n    bsscr->k2type      = 0;\n    bsscr->do_scaling  = PETSC_FALSE;\n    bsscr->scaled      = PETSC_FALSE;\n    bsscr->K2built     = PETSC_FALSE;\n    bsscr->check_cb_pressureNS     = PETSC_FALSE;/* checker board nullspace */\n    bsscr->check_const_pressureNS  = PETSC_FALSE;/* constant nullspace */\n    bsscr->check_pressureNS        = PETSC_FALSE;/* is true if either of above two are true */\n    bsscr->t           = NULL;/* null space vectors for pressure */\n    bsscr->v           = NULL;\n    bsscr->nstol       = 1e-7;/* null space detection tolerance */\n    bsscr->uStar       = NULL;\n    bsscr->been_here   = 0;\n    PetscFunctionReturn(0);\n}\nEXTERN_C_END\n", "meta": {"hexsha": "b6e20293ea5f5f10acbb5faccd2c9aae39a54d3b", "size": 17550, "ext": "c", "lang": "C", "max_stars_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/BSSCR.c", "max_stars_repo_name": "rbeucher/underworld2", "max_stars_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/BSSCR.c", "max_issues_repo_name": "rbeucher/underworld2", "max_issues_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/BSSCR.c", "max_forks_repo_name": "rbeucher/underworld2", "max_forks_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.4377880184, "max_line_length": 151, "alphanum_fraction": 0.5958974359, "num_tokens": 5040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3665897501624599, "lm_q2_score": 0.03514484943255559, "lm_q1q2_score": 0.012883741572977824}}
{"text": "#include <config.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_vector.h>\n\n/* Compile all the inline matrix functions */\n\n#define COMPILE_INLINE_STATIC\n#include \"build.h\"\n#include <gsl/gsl_matrix.h>\n\n", "meta": {"hexsha": "fe595fa189f61d40e911309e35a30b21f12325a4", "size": 201, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-an/matrix/matrix.c", "max_stars_repo_name": "juandesant/astrometry.net", "max_stars_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_stars_repo_licenses": ["Net-SNMP", "Xnet"], "max_stars_count": 460.0, "max_stars_repo_stars_event_min_datetime": "2015-01-06T13:20:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T00:37:55.000Z", "max_issues_repo_path": "gsl-an/matrix/matrix.c", "max_issues_repo_name": "juandesant/astrometry.net", "max_issues_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_issues_repo_licenses": ["Net-SNMP", "Xnet"], "max_issues_count": 208.0, "max_issues_repo_issues_event_min_datetime": "2015-01-08T20:26:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T15:21:34.000Z", "max_forks_repo_path": "gsl-an/matrix/matrix.c", "max_forks_repo_name": "juandesant/astrometry.net", "max_forks_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_forks_repo_licenses": ["Net-SNMP", "Xnet"], "max_forks_count": 173.0, "max_forks_repo_forks_event_min_datetime": "2015-01-08T18:01:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T07:27:04.000Z", "avg_line_length": 18.2727272727, "max_line_length": 45, "alphanum_fraction": 0.7462686567, "num_tokens": 51, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334000459302, "lm_q2_score": 0.031618770462458395, "lm_q1q2_score": 0.012879381277745008}}
{"text": "#include <gsl/gsl_math.h>\n#include \"gsl_cblas.h\"\n#include \"cblas.h\"\n\nvoid\ncblas_dcopy (const int N, const double *X, const int incX, double *Y,\n\t     const int incY)\n{\n#define BASE double\n#include \"source_copy_r.h\"\n#undef BASE\n}\n", "meta": {"hexsha": "271d78fec0cf7dea4dea703d8dc4a4c36adc51f5", "size": 229, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/cblas/dcopy.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/cblas/dcopy.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/cblas/dcopy.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 17.6153846154, "max_line_length": 69, "alphanum_fraction": 0.7074235808, "num_tokens": 70, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.02675928512581461, "lm_q1q2_score": 0.012857265942758427}}
{"text": "/* interpolation/gsl_interp.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2004 Gerard Jungman\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Author:  G. Jungman\n */\n#ifndef __GSL_INTERP_H__\n#define __GSL_INTERP_H__\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\n/* evaluation accelerator */\ntypedef struct {\n  size_t  cache;        /* cache of index   */\n  size_t  miss_count;   /* keep statistics  */\n  size_t  hit_count;\n}\ngsl_interp_accel;\n\n\n/* interpolation object type */\ntypedef struct {\n  const char * name;\n  unsigned int min_size;\n  void *  (*alloc) (size_t size);\n  int     (*init)    (void *, const double xa[], const double ya[], size_t size);\n  int     (*eval)    (const void *, const double xa[], const double ya[], size_t size, double x, gsl_interp_accel *, double * y);\n  int     (*eval_deriv)  (const void *, const double xa[], const double ya[], size_t size, double x, gsl_interp_accel *, double * y_p);\n  int     (*eval_deriv2) (const void *, const double xa[], const double ya[], size_t size, double x, gsl_interp_accel *, double * y_pp);\n  int     (*eval_integ)  (const void *, const double xa[], const double ya[], size_t size, gsl_interp_accel *, double a, double b, double * result);\n  void    (*free)         (void *);\n\n} gsl_interp_type;\n\n\n/* general interpolation object */\ntypedef struct {\n  const gsl_interp_type * type;\n  double  xmin;\n  double  xmax;\n  size_t  size;\n  void * state;\n} gsl_interp;\n\n\n/* available types */\nGSL_VAR const gsl_interp_type * gsl_interp_linear;\nGSL_VAR const gsl_interp_type * gsl_interp_polynomial;\nGSL_VAR const gsl_interp_type * gsl_interp_cspline;\nGSL_VAR const gsl_interp_type * gsl_interp_cspline_periodic;\nGSL_VAR const gsl_interp_type * gsl_interp_akima;\nGSL_VAR const gsl_interp_type * gsl_interp_akima_periodic;\n\ngsl_interp_accel *\ngsl_interp_accel_alloc(void);\n\nsize_t\ngsl_interp_accel_find(gsl_interp_accel * a, const double x_array[], size_t size, double x);\n\nint\ngsl_interp_accel_reset (gsl_interp_accel * a);\n\nvoid\ngsl_interp_accel_free(gsl_interp_accel * a);\n\ngsl_interp *\ngsl_interp_alloc(const gsl_interp_type * T, size_t n);\n     \nint\ngsl_interp_init(gsl_interp * obj, const double xa[], const double ya[], size_t size);\n\nconst char * gsl_interp_name(const gsl_interp * interp);\nunsigned int gsl_interp_min_size(const gsl_interp * interp);\n\n\nint\ngsl_interp_eval_e(const gsl_interp * obj,\n                  const double xa[], const double ya[], double x,\n                  gsl_interp_accel * a, double * y);\n\ndouble\ngsl_interp_eval(const gsl_interp * obj,\n                const double xa[], const double ya[], double x,\n                gsl_interp_accel * a);\n\nint\ngsl_interp_eval_deriv_e(const gsl_interp * obj,\n                        const double xa[], const double ya[], double x,\n                        gsl_interp_accel * a,\n                        double * d);\n\ndouble\ngsl_interp_eval_deriv(const gsl_interp * obj,\n                      const double xa[], const double ya[], double x,\n                      gsl_interp_accel * a);\n\nint\ngsl_interp_eval_deriv2_e(const gsl_interp * obj,\n                         const double xa[], const double ya[], double x,\n                         gsl_interp_accel * a,\n                         double * d2);\n\ndouble\ngsl_interp_eval_deriv2(const gsl_interp * obj,\n                       const double xa[], const double ya[], double x,\n                       gsl_interp_accel * a);\n\nint\ngsl_interp_eval_integ_e(const gsl_interp * obj,\n                        const double xa[], const double ya[],\n                        double a, double b,\n                        gsl_interp_accel * acc,\n                        double * result);\n\ndouble\ngsl_interp_eval_integ(const gsl_interp * obj,\n                      const double xa[], const double ya[],\n                      double a, double b,\n                      gsl_interp_accel * acc);\n\nvoid\ngsl_interp_free(gsl_interp * interp);\n\nsize_t gsl_interp_bsearch(const double x_array[], double x,\n                          size_t index_lo, size_t index_hi);\n\n#ifdef HAVE_INLINE\nextern inline size_t\ngsl_interp_bsearch(const double x_array[], double x,\n                   size_t index_lo, size_t index_hi);\n\nextern inline size_t\ngsl_interp_bsearch(const double x_array[], double x,\n                   size_t index_lo, size_t index_hi)\n{\n  size_t ilo = index_lo;\n  size_t ihi = index_hi;\n  while(ihi > ilo + 1) {\n    size_t i = (ihi + ilo)/2;\n    if(x_array[i] > x)\n      ihi = i;\n    else\n      ilo = i;\n  }\n  \n  return ilo;\n}\n#endif\n\n#ifdef HAVE_INLINE\nextern inline size_t\ngsl_interp_accel_find(gsl_interp_accel * a, const double xa[], size_t len, double x)\n{\n  size_t x_index = a->cache;\n \n  if(x < xa[x_index]) {\n    a->miss_count++;\n    a->cache = gsl_interp_bsearch(xa, x, 0, x_index);\n  }\n  else if(x > xa[x_index + 1]) {\n    a->miss_count++;\n    a->cache = gsl_interp_bsearch(xa, x, x_index, len-1);\n  }\n  else {\n    a->hit_count++;\n  }\n  \n  return a->cache;\n}\n#endif /* HAVE_INLINE */\n\n\n__END_DECLS\n\n#endif /* __GSL_INTERP_H__ */\n", "meta": {"hexsha": "d4757ca95e06de818718d9de638bc3a8e4aedf35", "size": 5903, "ext": "h", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/interpolation/gsl_interp.h", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/interpolation/gsl_interp.h", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/interpolation/gsl_interp.h", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 29.078817734, "max_line_length": 148, "alphanum_fraction": 0.6544130103, "num_tokens": 1454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.399811640739795, "lm_q2_score": 0.03210071030512526, "lm_q1q2_score": 0.012834237656004978}}
{"text": "/*\n * MIT License\n *\n * Copyright (c) 2017 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n *\n * Abstract: misc util functions and macros\n */\n\n#ifndef __UTIL_H__\n#define __UTIL_H__\n\n#include <algorithm>\n#include <gsl/span>\n#include <iterator>\n#include <sstream>\n#include <string>\n#include <vector>\n\ntypedef gsl::span<const uint8_t> cbspan;\n\n#ifndef block_round\n#define block_round(ODD, BLK)                                                  \\\n    ((ODD) + (((BLK) - ((ODD) & ((BLK)-1))) & ((BLK)-1)))\n#endif\n\ntemplate <class TContainer>\nstatic inline bool starts_with(const TContainer& haystack,\n                               const TContainer& needle)\n{\n    return haystack.size() >= needle.size() &&\n           std::equal(needle.begin(), needle.end(), haystack.begin());\n}\n\nstatic inline void split(const std::string& s, char delim,\n                         std::vector<std::string>& result)\n{\n    std::string::size_type prev_pos = 0, pos = 0;\n    do\n    {\n        pos = s.find(delim, pos);\n        if (pos == std::string::npos)\n        {\n            result.emplace_back(std::move(s.substr(prev_pos)));\n        }\n        else\n        {\n            result.emplace_back(std::move(s.substr(prev_pos, pos - prev_pos)));\n            prev_pos = ++pos;\n        }\n    } while (pos != std::string::npos);\n}\n\nstatic inline std::vector<std::string> split(const std::string& s, char delim)\n{\n    std::vector<std::string> elems;\n    split(s, delim, elems);\n    return elems;\n}\n\nstatic constexpr uint64_t prime = 0x100000001B3ull;\nstatic constexpr uint64_t basis = 0xCBF29CE484222325ull;\n\nstatic constexpr uint64_t const_hash(const char* str,\n                                     uint64_t last_value = basis)\n{\n    return *str ? const_hash(str + 1, (*str ^ last_value) * prime) : last_value;\n}\n\nstatic inline uint64_t hash(const std::string& str)\n{\n    uint64_t ret{basis};\n\n    for (auto i : str)\n    {\n        ret ^= static_cast<uint64_t>(i);\n        ret *= prime;\n    }\n\n    return ret;\n}\n\n#endif /* __UTIL_H__ */\n", "meta": {"hexsha": "9a61ed2cc1e5572d180d5ec5f6c3b779cabc70a1", "size": 3052, "ext": "h", "lang": "C", "max_stars_repo_path": "util.h", "max_stars_repo_name": "Intel-BMC/mtd-util", "max_stars_repo_head_hexsha": "708072b62a3cecb520eeaacac88b4f2c2e101fe4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "util.h", "max_issues_repo_name": "Intel-BMC/mtd-util", "max_issues_repo_head_hexsha": "708072b62a3cecb520eeaacac88b4f2c2e101fe4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "util.h", "max_forks_repo_name": "Intel-BMC/mtd-util", "max_forks_repo_head_hexsha": "708072b62a3cecb520eeaacac88b4f2c2e101fe4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-02-17T06:51:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-19T15:17:54.000Z", "avg_line_length": 29.9215686275, "max_line_length": 80, "alphanum_fraction": 0.6490825688, "num_tokens": 713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39981165504266236, "lm_q2_score": 0.032100703707619964, "lm_q1q2_score": 0.012834235477377666}}
{"text": "#include <gsl/gsl_math.h>\n#include \"gsl_cblas.h\"\n#include \"cblas.h\"\n\nvoid\ncblas_sswap (const int N, float *X, const int incX, float *Y, const int incY)\n{\n#define BASE float\n#include \"source_swap_r.h\"\n#undef BASE\n}\n", "meta": {"hexsha": "ecb0020d808c8db772644c9c821b6934d6d29686", "size": 214, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/cblas/sswap.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/cblas/sswap.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/cblas/sswap.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 17.8333333333, "max_line_length": 77, "alphanum_fraction": 0.7196261682, "num_tokens": 68, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378235137849365, "lm_q2_score": 0.029312231281335192, "lm_q1q2_score": 0.012833584096470906}}
{"text": "/*\n  C code for actionAngle calculations\n*/\n#ifndef __GALPY_ACTIONANGLE_H__\n#define __GALPY_ACTIONANGLE_H__\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n#ifdef _WIN32\n#include <Python.h>\n#endif\n#include <stdbool.h>\n#include <gsl/gsl_roots.h>\n#include <gsl/gsl_spline.h>\n#include \"interp_2d.h\"\n/*\n  Macro for dealing with potentially unused variables due to OpenMP\n */\n/* If we're not using GNU C, elide __attribute__ if it doesn't exist*/\n#ifndef __has_attribute      // Compatibility with non-clang compilers. \n#define __has_attribute(x) 0  \n#endif\n#if defined(__GNUC__) || __has_attribute(unused)\n#  define UNUSED __attribute__((unused))\n#else\n#  define UNUSED /*NOTHING*/\n#endif\n/*\n  Structure declarations\n*/\nstruct pragmasolver{\n  gsl_root_fsolver *s;\n};\n#ifdef __cplusplus\n}\n#endif\n#endif /* actionAngle.h */\n", "meta": {"hexsha": "bffc8d7bb91305e7c2edfb9f537253fe08d686e3", "size": 809, "ext": "h", "lang": "C", "max_stars_repo_path": "galpy/actionAngle/actionAngle_c_ext/actionAngle.h", "max_stars_repo_name": "gusbeane/galpy", "max_stars_repo_head_hexsha": "d6db971285f163456c81775fc2fdc7d75189762c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 147.0, "max_stars_repo_stars_event_min_datetime": "2015-01-01T14:06:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T14:47:41.000Z", "max_issues_repo_path": "galpy/actionAngle/actionAngle_c_ext/actionAngle.h", "max_issues_repo_name": "gusbeane/galpy", "max_issues_repo_head_hexsha": "d6db971285f163456c81775fc2fdc7d75189762c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 269.0, "max_issues_repo_issues_event_min_datetime": "2015-01-07T15:58:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T18:42:08.000Z", "max_forks_repo_path": "galpy/actionAngle/actionAngle_c_ext/actionAngle.h", "max_forks_repo_name": "gusbeane/galpy", "max_forks_repo_head_hexsha": "d6db971285f163456c81775fc2fdc7d75189762c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 110.0, "max_forks_repo_forks_event_min_datetime": "2015-02-08T10:57:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-28T07:56:49.000Z", "avg_line_length": 21.2894736842, "max_line_length": 72, "alphanum_fraction": 0.7428924598, "num_tokens": 210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.027585282326718426, "lm_q1q2_score": 0.012824441100469958}}
{"text": "#ifndef CTETRA_TETRA_H\n#define CTETRA_TETRA_H\n\n#include <stdlib.h>\n#include <gsl/gsl_vector.h>\n#include \"ecache.h\"\n\ntypedef double (*tetra_SumFn)(double E, double E1, double E2, double E3, double E4, double num_tetra);\n\ndouble tetra_SumTetra(tetra_SumFn F, double E, EnergyCache *Ecache);\n\nvoid sortEs(double Es[4]);\n\n#endif // CTETRA_TETRA_H\n", "meta": {"hexsha": "00edd38cb29d92fe8ee96bcd5395eb9f68cd6363", "size": 343, "ext": "h", "lang": "C", "max_stars_repo_path": "tetra.h", "max_stars_repo_name": "tflovorn/ctetra", "max_stars_repo_head_hexsha": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tetra.h", "max_issues_repo_name": "tflovorn/ctetra", "max_issues_repo_head_hexsha": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-11-19T22:44:14.000Z", "max_issues_repo_issues_event_max_datetime": "2016-11-30T15:23:35.000Z", "max_forks_repo_path": "tetra.h", "max_forks_repo_name": "tflovorn/ctetra", "max_forks_repo_head_hexsha": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8666666667, "max_line_length": 102, "alphanum_fraction": 0.7609329446, "num_tokens": 115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.411110869232168, "lm_q2_score": 0.031143830197558942, "lm_q1q2_score": 0.0128035671037375}}
{"text": "#ifndef ARRUS_CORE_COMMON_COLLECTIONS_H\n#define ARRUS_CORE_COMMON_COLLECTIONS_H\n\n#include <string>\n#include <vector>\n#include <numeric>\n#include <unordered_set>\n#include <type_traits>\n#include <bitset>\n#include <stdexcept>\n\n#include <gsl/span>\n#include <boost/range/combine.hpp>\n\nnamespace arrus {\n\n/**\n * Returns an array of range [start, end).\n */\ntemplate<typename T>\ninline std::vector<T> getRange(T start, T end, T step = 1) {\n    std::vector<T> values;\n    for(T i = start; i < end; i += step) {\n        values.push_back(i);\n    }\n    return values;\n}\n\ntemplate<typename Out, typename In>\ninline std::vector<Out> castTo(std::vector<In> values) {\n    std::vector<Out> result(values.size());\n    std::transform(\n        std::begin(values), std::end(values),\n        std::begin(result),\n        [](In &value) { return Out(value); }\n    );\n    return result;\n}\n\ntemplate<typename Out, typename Iterator>\ninline std::vector<Out> castTo(const Iterator begin, const Iterator end) {\n    std::vector<Out> result;\n    std::transform(begin, end, std::back_inserter(result),\n                   [](auto &value) { return Out(value); });\n    return result;\n}\n\n/**\n * Returns an array that holds given value n times.\n */\ntemplate<typename T>\ninline std::vector<T> getNTimes(const T value, size_t n) {\n    std::vector<T> values;\n    for(size_t i = 0; i < n; ++i) {\n        values.push_back(value);\n    }\n    return values;\n}\n\ntemplate<typename T>\ninline size_t countUnique(const std::vector<T> &values) {\n    return std::unordered_set<T>(std::begin(values), std::end(values)).size();\n}\n\ntemplate<typename T>\ninline bool\nsetContains(const std::unordered_set<T> &set, const T &value) {\n    return set.find(value) != set.end();\n}\n\ntemplate<typename T, typename U>\ninline std::vector<std::pair<T, U>>\nzip(const std::vector<T> &a, const std::vector<U> &b) {\n    if(a.size() != b.size()) {\n        throw std::runtime_error(\"Zipped vectors should have the same size.\");\n    }\n    std::vector<std::pair<T, U>> res;\n    res.reserve(a.size());\n    for(const auto &[x, y] : boost::combine(a, b)) {\n        res.emplace_back(x, y);\n    }\n    return res;\n}\n\ntemplate<typename R>\ninline std::vector<R>\ngenerate(size_t nElements, std::function<R(size_t)> transformation) {\n    std::vector<R> result;\n    result.reserve(nElements);\n    for(size_t i = 0; i < nElements; ++i) {\n        result.emplace_back(transformation(i));\n    }\n    return result;\n}\n\ntemplate<typename T>\ninline std::vector<T>\nconcat(const std::vector<T> &a, const std::vector<T> &b) {\n    std::vector<T> result;\n    result.reserve(a.size() + b.size());\n    result.insert(std::begin(result), std::begin(a), std::end(a));\n    result.insert(std::end(result), std::begin(b), std::end(b));\n    return result;\n\n}\n\ntemplate<typename T>\ninline std::vector<T>\nconcat(const std::vector<std::vector<T>> &a) {\n    std::vector<T> result;\n    size_t totalSize = 0;\n    for(const auto &v : a) {\n        totalSize += v.size();\n    }\n    result.reserve(totalSize);\n    for(const auto &vec : a) {\n        result.insert(std::end(result), std::begin(vec), std::end(vec));\n    }\n    return result;\n}\n\ntemplate<typename T>\ninline std::vector<T>\npermute(const std::vector<T> &input, const std::vector<unsigned short> &perm) {\n    std::vector<T> output(perm.size());\n    for(size_t i = 0; i < static_cast<size_t>(perm.size()); ++i) {\n        output[perm[i]] = input[i];\n    }\n    return output;\n}\n\ntemplate<int size>\ninline std::bitset<size>\ntoBitset(const std::vector<bool> &in) {\n    std::bitset<size> result;\n    for(size_t i = 0; i < size; ++i) {\n        result[i] = in[i];\n    }\n    return result;\n}\n\ntemplate<typename Map, typename K>\ninline bool containsKey(Map map, const K &key) {\n    return map.find(key) != std::end(map);\n}\n\ntemplate<typename T>\ninline void setValuesInRange(std::vector<T> &container, size_t start, size_t end, const T &value) {\n    for(size_t i = start; i < end; ++i) {\n        container[i] = value;\n    }\n}\n\ntemplate<size_t N>\ninline void setValuesInRange(std::bitset<N> &container, size_t start, size_t end, const bool &value) {\n    for(size_t i = start; i < end; ++i) {\n        container[i] = value;\n    }\n}\n\ntemplate<typename T>\ninline void setValuesInRange(std::vector<T> &container, size_t start, size_t end,\n                             const std::function<T(size_t)> &generator) {\n    for(size_t i = start; i < end; ++i) {\n        container[i] = generator(i);\n    }\n}\n\ntemplate<typename T>\ninline void setValuesInRange(std::vector<T> &container, size_t start, size_t end,\n                             const std::vector<T>& source) {\n    if(source.size != end-start) {\n        throw std::runtime_error(\"Source vector should have exactly \"\n                            + std::to_string(end-start) + \" elements \"\n                          \"when assigning it to the selected range.\");\n    }\n    for(size_t i = start; i < end; ++i) {\n        container[i] = source[i-start];\n    }\n}\n\ntemplate<class InputIt, class T, class BinaryOp>\ninline T reduce(InputIt first, InputIt last, T init, BinaryOp binaryOp) {\n    T result = init;\n    for(auto it = first; it != last; ++it) {\n        result = binaryOp(result, *it);\n    }\n    return result;\n}\n\n}\n\n#endif //ARRUS_CORE_COMMON_COLLECTIONS_H\n", "meta": {"hexsha": "186a92777ad45a8b11d6b50e693a7b84a6ef030e", "size": 5232, "ext": "h", "lang": "C", "max_stars_repo_path": "arrus/core/common/collections.h", "max_stars_repo_name": "us4useu/arrus", "max_stars_repo_head_hexsha": "10487b09f556e327ddb1bec28fbaccf3b8b08064", "max_stars_repo_licenses": ["BSL-1.0", "MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2021-02-04T19:56:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T09:41:51.000Z", "max_issues_repo_path": "arrus/core/common/collections.h", "max_issues_repo_name": "us4useu/arrus", "max_issues_repo_head_hexsha": "10487b09f556e327ddb1bec28fbaccf3b8b08064", "max_issues_repo_licenses": ["BSL-1.0", "MIT"], "max_issues_count": 60.0, "max_issues_repo_issues_event_min_datetime": "2020-11-06T04:59:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T17:39:06.000Z", "max_forks_repo_path": "arrus/core/common/collections.h", "max_forks_repo_name": "us4useu/arrus", "max_forks_repo_head_hexsha": "10487b09f556e327ddb1bec28fbaccf3b8b08064", "max_forks_repo_licenses": ["BSL-1.0", "MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-07-22T16:13:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T08:53:31.000Z", "avg_line_length": 26.9690721649, "max_line_length": 102, "alphanum_fraction": 0.6236620795, "num_tokens": 1365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32766831395172374, "lm_q2_score": 0.039048290210078135, "lm_q1q2_score": 0.012794887415833903}}
{"text": "#include <assert.h>\n\n#include <gsl/gsl_statistics_double.h>\n#include <hdf5.h>\n#include <hdf5_hl.h>\n\n#include <qdm.h>\n\nqdm_evaluation *\nqdm_evaluation_new(const qdm_parameters *parameters)\n{\n  qdm_evaluation *e = malloc(sizeof(qdm_evaluation));\n\n  e->parameters = *parameters;\n\n  e->rng = gsl_rng_alloc(gsl_rng_default);\n\n  e->years_min = 0;\n  e->years_max = 0;\n\n  e->lower_bound = 0;\n  e->upper_bound = 0;\n\n  e->waic = 0;\n  e->pwaic = 0;\n  e->dic = 0;\n  e->pd = 0;\n\n  e->t = NULL;\n\n  e->mcmc = NULL;\n\n  e->theta_bar = NULL;\n  e->theta_star_bar = NULL;\n\n  e->xi_cov = NULL;\n  e->theta_star_cov = NULL;\n\n  e->xi_low_bar = 0;\n  e->xi_high_bar = 0;\n\n  e->theta_acc = NULL;\n  e->xi_acc = NULL;\n\n  e->m_knots = NULL;\n\n  e->rng_seed = 0;\n\n  e->elapsed = 0;\n\n  return e;\n}\n\nvoid\nqdm_evaluation_free(qdm_evaluation *e)\n{\n  if (e == NULL) {\n    return;\n  }\n\n  e->rng_seed = 0;\n\n  gsl_vector_free(e->m_knots);\n  e->m_knots = NULL;\n\n  gsl_vector_free(e->xi_acc);\n  e->xi_acc = NULL;\n\n  gsl_matrix_free(e->theta_acc);\n  e->theta_acc = NULL;\n\n  gsl_matrix_free(e->theta_star_cov);\n  e->theta_bar = NULL;\n\n  gsl_matrix_free(e->xi_cov);\n  e->theta_bar = NULL;\n\n  gsl_matrix_free(e->theta_star_bar);\n  e->theta_bar = NULL;\n\n  gsl_matrix_free(e->theta_bar);\n  e->theta_bar = NULL;\n\n  qdm_mcmc_free(e->mcmc);\n  e->mcmc = NULL;\n\n  qdm_tau_free(e->t);\n  e->t = NULL;\n\n  gsl_rng_free(e->rng);\n  e->rng = NULL;\n\n  free(e);\n}\n\nvoid\nqdm_evaluation_fprint(\n    FILE *f,\n    const qdm_evaluation *e\n)\n{\n  const char *prefix = \"  \";\n\n  fprintf(f, \"%sparameters:\\n\", prefix);\n  qdm_parameters_fprint(f, &e->parameters);\n\n  fprintf(f, \"%syears_min: %f\\n\", prefix, e->years_min);\n  fprintf(f, \"%syears_max: %f\\n\", prefix, e->years_max);\n\n  fprintf(f, \"%slower_bound: %f\\n\", prefix, e->lower_bound);\n  fprintf(f, \"%supper_bound: %f\\n\", prefix, e->upper_bound);\n\n  fprintf(f, \"%swaic: %f\\n\", prefix, e->waic);\n  fprintf(f, \"%spwaic: %f\\n\", prefix, e->pwaic);\n  fprintf(f, \"%sdic: %f\\n\", prefix, e->dic);\n  fprintf(f, \"%spd: %f\\n\", prefix, e->pd);\n\n  fprintf(f, \"%smcmc r.s: %zu\\n\", prefix, e->mcmc->r.s);\n\n  fprintf(f, \"%stheta_bar:\\n\", prefix);\n  qdm_matrix_csv_fwrite(f, e->theta_bar);\n\n  fprintf(f, \"%stheta_star_bar:\\n\", prefix);\n  qdm_matrix_csv_fwrite(f, e->theta_star_bar);\n\n  fprintf(f, \"%sxi_cov:\\n\", prefix);\n  qdm_matrix_csv_fwrite(f, e->xi_cov);\n\n  fprintf(f, \"%stheta_star_cov:\\n\", prefix);\n  qdm_matrix_csv_fwrite(f, e->theta_star_cov);\n\n  fprintf(f, \"%sxi_low_bar: %f\\n\", prefix, e->xi_low_bar);\n  fprintf(f, \"%sxi_high_bar: %f\\n\", prefix, e->xi_high_bar);\n\n  fprintf(f, \"%stheta_acc:\\n\", prefix);\n  qdm_matrix_csv_fwrite(f, e->theta_acc);\n\n  fprintf(f, \"%sxi_acc:\\n\", prefix);\n  qdm_vector_csv_fwrite(f, e->xi_acc);\n\n  fprintf(f, \"%sm_knots:\\n\", prefix);\n  qdm_vector_csv_fwrite(f, e->m_knots);\n\n  fprintf(f, \"%srng_seed: %lu\\n\", prefix, e->rng_seed);\n\n  fprintf(f, \"%selapsed: %f\\n\", prefix, e->elapsed);\n}\n\nint\nqdm_evaluation_read(\n    hid_t id,\n    qdm_evaluation **e\n)\n{\n  int status = 0;\n\n  hid_t parameters_group = -1;\n  hid_t mcmc_group = -1;\n\n  parameters_group = H5Gopen(id, \"parameters\", H5P_DEFAULT);\n  if (parameters_group < 0) {\n    status = parameters_group;\n\n    goto cleanup;\n  }\n\n  qdm_parameters parameters = {0};\n  status = qdm_parameters_read(parameters_group, &parameters);\n  if (status != 0) {\n    goto cleanup;\n  }\n\n  *e = qdm_evaluation_new(&parameters);\n\n#define READ(t, n) \\\n  status = H5LTread_dataset_##t(id, #n, &(*e)->n); \\\n  if (status < 0) { \\\n    goto cleanup; \\\n  }\n\n  READ(double, years_min);\n  READ(double, years_max);\n\n  READ(double, lower_bound);\n  READ(double, upper_bound);\n\n  READ(double, waic);\n  READ(double, pwaic);\n  READ(double, dic);\n  READ(double, pd);\n\n  mcmc_group = H5Gopen(id, \"mcmc\", H5P_DEFAULT);\n  if (mcmc_group < 0) {\n    status = mcmc_group;\n\n    goto cleanup;\n  }\n\n  status = qdm_mcmc_read(mcmc_group, &(*e)->mcmc);\n  if (status != 0) {\n    goto cleanup;\n  }\n\n  status = qdm_matrix_hd5_read(id, \"theta_bar\", &(*e)->theta_bar);\n  if (status != 0) {\n    goto cleanup;\n  }\n\n  status = qdm_matrix_hd5_read(id, \"theta_star_bar\", &(*e)->theta_star_bar);\n  if (status != 0) {\n    goto cleanup;\n  }\n\n  status = qdm_matrix_hd5_read(id, \"xi_cov\", &(*e)->xi_cov);\n  if (status != 0) {\n    goto cleanup;\n  }\n\n  status = qdm_matrix_hd5_read(id, \"theta_star_cov\", &(*e)->theta_star_cov);\n  if (status != 0) {\n    goto cleanup;\n  }\n\n  READ(double, xi_high_bar);\n  READ(double, xi_low_bar);\n\n  status = qdm_matrix_hd5_read(id, \"theta_acc\", &(*e)->theta_acc);\n  if (status != 0) {\n    goto cleanup;\n  }\n\n  status = qdm_vector_hd5_read(id, \"xi_acc\", &(*e)->xi_acc);\n  if (status != 0) {\n    goto cleanup;\n  }\n\n  status = qdm_vector_hd5_read(id, \"m_knots\", &(*e)->m_knots);\n  if (status != 0) {\n    goto cleanup;\n  }\n\n  status = H5LTread_dataset(id, \"rng_seed\", H5T_NATIVE_ULONG, &(*e)->rng_seed);\n  if (status < 0) {\n    goto cleanup;\n  }\n\n  READ(double, elapsed);\n\n#undef READ\n\n  (*e)->t = qdm_tau_alloc(\n      (*e)->parameters.tau_table,\n      (*e)->parameters.tau_low,\n      (*e)->parameters.tau_high,\n      (*e)->parameters.spline_df,\n      (*e)->m_knots\n  );\n\ncleanup:\n  if (parameters_group >= 0) {\n    H5Gclose(parameters_group);\n  }\n\n  if (mcmc_group >= 0) {\n    H5Gclose(mcmc_group);\n  }\n\n  return status;\n}\n\nint\nqdm_evaluation_write(\n    hid_t id,\n    const qdm_evaluation *e\n)\n{\n  int status = 0;\n\n  hid_t parameters_group = -1;\n  hid_t mcmc_group = -1;\n\n#define WRITE_DOUBLE(n) \\\n  status = qdm_double_write(id, #n, e->n); \\\n  if (status != 0) { \\\n    goto cleanup; \\\n  }\n\n  parameters_group = qdm_data_create_group(id, \"parameters\");\n  if (parameters_group < 0) {\n    status = parameters_group;\n\n    goto cleanup;\n  }\n\n  status = qdm_parameters_write(parameters_group, &e->parameters);\n  if (status != 0) {\n    goto cleanup;\n  }\n\n  WRITE_DOUBLE(years_min);\n  WRITE_DOUBLE(years_max);\n\n  WRITE_DOUBLE(lower_bound);\n  WRITE_DOUBLE(upper_bound);\n\n  WRITE_DOUBLE(waic);\n  WRITE_DOUBLE(pwaic);\n  WRITE_DOUBLE(dic);\n  WRITE_DOUBLE(pd);\n\n  mcmc_group = qdm_data_create_group(id, \"mcmc\");\n  if (mcmc_group < 0) {\n    status = mcmc_group;\n\n    goto cleanup;\n  }\n\n  status = qdm_mcmc_write(mcmc_group, e->mcmc);\n  if (status != 0) {\n    goto cleanup;\n  }\n\n  status = qdm_matrix_hd5_write(id, \"theta_bar\", e->theta_bar);\n  if (status != 0) {\n    goto cleanup;\n  }\n\n  status = qdm_matrix_hd5_write(id, \"theta_star_bar\", e->theta_star_bar);\n  if (status != 0) {\n    goto cleanup;\n  }\n\n  status = qdm_matrix_hd5_write(id, \"xi_cov\", e->xi_cov);\n  if (status != 0) {\n    goto cleanup;\n  }\n\n  status = qdm_matrix_hd5_write(id, \"theta_star_cov\", e->theta_star_cov);\n  if (status != 0) {\n    goto cleanup;\n  }\n\n  WRITE_DOUBLE(xi_high_bar);\n  WRITE_DOUBLE(xi_low_bar);\n\n  status = qdm_matrix_hd5_write(id, \"theta_acc\", e->theta_acc);\n  if (status != 0) {\n    goto cleanup;\n  }\n\n  status = qdm_vector_hd5_write(id, \"xi_acc\", e->xi_acc);\n  if (status != 0) {\n    goto cleanup;\n  }\n\n  status = qdm_vector_hd5_write(id, \"m_knots\", e->m_knots);\n  if (status != 0) {\n    goto cleanup;\n  }\n\n  {\n    hsize_t dims[1] = {1};\n    unsigned long int data[1] = {e->rng_seed};\n\n    status = H5LTmake_dataset(id, \"rng_seed\", 1, dims, H5T_NATIVE_ULONG, data);\n    if (status < 0) {\n      goto cleanup;\n    }\n  }\n\n  WRITE_DOUBLE(elapsed);\n\n#undef WRITE_DOUBLE\n\ncleanup:\n  if (parameters_group >= 0) {\n    H5Gclose(parameters_group);\n  }\n\n  if (mcmc_group >= 0) {\n    H5Gclose(mcmc_group);\n  }\n\n  return status;\n}\n\nint\nqdm_evaluation_run(\n    qdm_evaluation *e,\n    const gsl_matrix *data,\n    size_t data_year_idx,\n    size_t data_month_idx,\n    size_t data_value_idx\n)\n{\n  int status = 0;\n\n  clock_t started_at = clock();\n\n  gsl_vector *years = NULL;\n  gsl_vector *years_norm = NULL;\n\n  gsl_vector *values = NULL;\n  gsl_vector *values_sorted = NULL;\n\n  gsl_vector *interior_knots = NULL;\n\n  gsl_vector *m_knots = NULL;\n  gsl_matrix *theta = NULL;\n  gsl_vector *ll = NULL;\n  gsl_vector *tau = NULL;\n\n  gsl_matrix *theta_tune = NULL;\n  gsl_matrix *theta_acc = NULL;\n  gsl_vector *xi_tune = NULL;\n  gsl_vector *xi_acc = NULL;\n\n  gsl_vector *xi = gsl_vector_alloc(2);\n  gsl_vector_set(xi, 0, e->parameters.xi_low);\n  gsl_vector_set(xi, 1, e->parameters.xi_high);\n\n  /* Initialize RNG */\n\n  gsl_rng_set(e->rng, e->parameters.rng_seed);\n\n  /* Normalize Years */\n\n  {\n    years = qdm_matrix_filter(data, data_month_idx, e->parameters.month, data_year_idx);\n    years_norm = qdm_matrix_filter(data, data_month_idx, e->parameters.month, data_year_idx);\n\n    gsl_vector_minmax(years, &e->years_min, &e->years_max);\n\n    double years_range = e->years_max - e->years_min;\n\n    status = gsl_vector_add_constant(years_norm, -e->years_min);\n    if (status != 0) {\n      goto cleanup;\n    }\n\n    status = gsl_vector_scale(years_norm, 1 / years_range);\n    if (status != 0) {\n      goto cleanup;\n    }\n  }\n\n  /* Extract Values */\n\n  {\n    values = qdm_matrix_filter(data, data_month_idx, e->parameters.month, data_value_idx);\n    values_sorted = qdm_vector_sorted(values);\n\n    e->lower_bound = gsl_vector_get(values_sorted, 0) - e->parameters.bound;\n    e->upper_bound = gsl_vector_get(values_sorted, values_sorted->size - 1) + e->parameters.bound;\n  }\n\n  /* Optimize Knots */\n\n  {\n    gsl_vector *middle = qdm_vector_seq(e->parameters.tau_low, e->parameters.tau_high, 0.005);\n\n    double possible_low = e->parameters.tau_low + 0.1;\n    double possible_high = e->parameters.tau_high - 0.1;\n    double possible_delta = (possible_high - possible_low) / 19;\n\n    gsl_vector *possible_knots = qdm_vector_seq(possible_low, possible_high, possible_delta);\n\n    interior_knots = gsl_vector_calloc(e->parameters.knot);\n\n    status = qdm_knots_optimize(\n        interior_knots,\n\n        e->rng,\n\n        values_sorted,\n        middle,\n        possible_knots,\n\n        e->parameters.knot_try,\n        e->parameters.spline_df\n    );\n    if (status != 0) {\n      goto cleanup;\n    }\n\n    gsl_vector_free(possible_knots);\n    gsl_vector_free(middle);\n  }\n\n  /* Optimize Theta */\n\n  {\n    size_t m = e->parameters.spline_df + e->parameters.knot;\n\n    m_knots = qdm_knots_vector(e->parameters.spline_df, interior_knots);\n    e->t = qdm_tau_alloc(\n        e->parameters.tau_table,\n        e->parameters.tau_low,\n        e->parameters.tau_high,\n        e->parameters.spline_df,\n        m_knots\n    );\n\n    gsl_vector *middle = qdm_vector_seq(e->parameters.tau_low, e->parameters.tau_high, 0.01);\n\n    gsl_matrix *ix = gsl_matrix_alloc(middle->size, m+1);\n    qdm_ispline_matrix(ix, middle, e->parameters.spline_df, m_knots);\n\n    theta = gsl_matrix_alloc(2, ix->size2);\n    gsl_vector_view theta0 = gsl_matrix_row(theta, 0);\n    gsl_vector_view theta1 = gsl_matrix_row(theta, 1);\n\n    size_t theta_pivot = qdm_vector_greater_than(years_norm, 0.3);\n    gsl_vector_view values0 = gsl_vector_subvector(values, 0, theta_pivot);\n    gsl_vector_view values1 = gsl_vector_subvector(values, theta_pivot, values->size - theta_pivot);\n    assert(values0.vector.size + values1.vector.size == values->size);\n\n    gsl_vector *eq0 = qdm_vector_quantile(&values0.vector, middle);\n    status = qdm_theta_optimize(&theta0.vector, eq0, ix);\n    if (status != 0) {\n      goto cleanup;\n    }\n\n    gsl_vector *eq1 = NULL;\n\n    if (e->parameters.truncate) {\n      gsl_vector_set_zero(&theta1.vector);\n    } else {\n      eq1 = qdm_vector_quantile(&values1.vector, middle);\n      status = qdm_theta_optimize(&theta1.vector, eq1, ix);\n      if (status != 0) {\n        goto cleanup;\n      }\n\n      status = gsl_vector_sub(&theta1.vector, &theta0.vector);\n      if (status != 0) {\n        goto cleanup;\n      }\n    }\n\n    qdm_theta_matrix_constrain(theta, e->parameters.theta_min);\n\n    ll = gsl_vector_alloc(values->size);\n    tau = gsl_vector_alloc(values->size);\n\n    for (size_t i = 0; i < values->size; i++) {\n      qdm_logl_3(\n          &ll->data[i],\n          &tau->data[i],\n\n          gsl_vector_get(years_norm, i),\n          gsl_vector_get(values, i),\n\n          e->t,\n          xi,\n\n          theta\n      );\n    }\n\n    gsl_vector_free(eq1);\n    gsl_vector_free(eq0);\n    gsl_matrix_free(ix);\n    gsl_vector_free(middle);\n  }\n\n  /* MCMC */\n\n  {\n    qdm_mcmc_parameters mcmc_p = {\n      .rng = e->rng,\n\n      .burn = e->parameters.burn,\n      .iter = e->parameters.iter,\n      .thin = e->parameters.thin,\n\n      .acc_check = e->parameters.acc_check,\n      .spline_df = e->parameters.spline_df,\n\n      .xi    = xi,\n      .ll    = ll,\n      .tau   = tau,\n      .theta = theta,\n\n      .xi_prior_mean = e->parameters.xi_prior_mean,\n      .xi_prior_var  = e->parameters.xi_prior_var,\n      .xi_tune_sd    = e->parameters.xi_tune_sd,\n\n      .theta_min     = e->parameters.theta_min,\n      .theta_tune_sd = e->parameters.theta_tune_sd,\n\n      .x = years_norm,\n      .y = values,\n\n      .t = e->t,\n      .m_knots = m_knots,\n\n      .truncate = e->parameters.truncate,\n    };\n\n    e->mcmc = qdm_mcmc_alloc(mcmc_p);\n\n    status = qdm_mcmc_run(e->mcmc);\n    if (status != 0) {\n      goto cleanup;\n    }\n  }\n\n  /* Model Diagnostics */\n\n  {\n    // WAIC\n\n    gsl_vector *ll_exp = gsl_vector_calloc(e->mcmc->r.s);\n\n    gsl_vector *lppd = gsl_vector_calloc(values->size);\n    gsl_vector *vlog = gsl_vector_calloc(values->size);\n\n    for (size_t j = 0; j < values->size; j++) {\n      gsl_vector_view ll_k = qdm_ijk_get_k(e->mcmc->r.ll, 0, j);\n\n      for (size_t i = 0; i < ll_k.vector.size; i++) {\n        gsl_vector_set(ll_exp, i, exp(gsl_vector_get(&ll_k.vector, i)));\n      }\n\n      gsl_vector_set(lppd, j, log(gsl_stats_mean(ll_exp->data, ll_exp->stride, ll_exp->size)));\n      gsl_vector_set(vlog, j, gsl_stats_variance(ll_k.vector.data, ll_k.vector.stride, ll_k.vector.size));\n    }\n\n    status = gsl_vector_sub(lppd, vlog);\n    if (status != 0) {\n      goto cleanup;\n    }\n\n    e->waic = -2 * qdm_vector_sum(lppd);\n    e->pwaic = qdm_vector_sum(vlog);\n\n    // DIC\n\n    gsl_vector *ll_sum = gsl_vector_alloc(e->mcmc->r.s);\n\n    for (size_t k = 0; k < e->mcmc->r.s; k++) {\n      gsl_matrix_view ll_ij_m = qdm_ijk_get_ij(e->mcmc->r.ll, k);\n      gsl_vector_view ll_ij = gsl_matrix_row(&ll_ij_m.matrix, 0);\n\n      gsl_vector_set(ll_sum, k, qdm_vector_sum(&ll_ij.vector));\n    }\n\n    status = gsl_vector_scale(ll_sum, -2);\n    if (status != 0) {\n      goto cleanup;\n    }\n\n    double d_bar = gsl_stats_mean(ll_sum->data, ll_sum->stride, ll_sum->size);\n    double d_theta_bar = 0;\n\n    gsl_vector_view xi_low = qdm_ijk_get_k(e->mcmc->r.xi, 0, 0);\n    gsl_vector_view xi_high = qdm_ijk_get_k(e->mcmc->r.xi, 0, 1);\n\n    double xi_low_bar = gsl_stats_mean(xi_low.vector.data, xi_low.vector.stride, xi_low.vector.size);\n    double xi_high_bar = gsl_stats_mean(xi_high.vector.data, xi_high.vector.stride, xi_high.vector.size);\n\n    gsl_vector *xi_bar = gsl_vector_alloc(2);\n    gsl_vector_set(xi_bar, 0, xi_low_bar);\n    gsl_vector_set(xi_bar, 1, xi_high_bar);\n\n    gsl_matrix *theta_bar = gsl_matrix_alloc(theta->size1, theta->size2);\n\n    for (size_t i = 0; i < e->mcmc->r.theta->size1; i++) {\n      for (size_t j = 0; j < e->mcmc->r.theta->size2; j++) {\n        gsl_vector_view theta_k = qdm_ijk_get_k(e->mcmc->r.theta, i, j);\n\n        gsl_matrix_set(theta_bar, i, j, gsl_stats_mean(theta_k.vector.data, theta_k.vector.stride, theta_k.vector.size));\n      }\n    }\n\n    gsl_matrix *theta_star_bar = gsl_matrix_alloc(theta->size1, theta->size2);\n\n    for (size_t i = 0; i < e->mcmc->r.theta_star->size1; i++) {\n      for (size_t j = 0; j < e->mcmc->r.theta_star->size2; j++) {\n        gsl_vector_view theta_k = qdm_ijk_get_k(e->mcmc->r.theta_star, i, j);\n\n        gsl_matrix_set(theta_star_bar, i, j, gsl_stats_mean(theta_k.vector.data, theta_k.vector.stride, theta_k.vector.size));\n      }\n    }\n\n    for (size_t i = 0; i < values->size; i++) {\n      double theta_bar_ll = 0;\n      double tau_tmp = 0;\n\n      qdm_logl_3(\n          &theta_bar_ll,\n          &tau_tmp,\n\n          gsl_vector_get(years_norm, i),\n          gsl_vector_get(values, i),\n\n          e->t,\n          xi_bar,\n\n          theta_bar\n      );\n\n      d_theta_bar = d_theta_bar + -2 * theta_bar_ll;\n    }\n\n    e->pd = d_bar - d_theta_bar;\n    e->dic = e->pd + d_bar;\n\n    e->theta_bar = qdm_matrix_copy(theta_bar);\n    e->theta_star_bar = qdm_matrix_copy(theta_star_bar);\n\n    e->xi_cov = qdm_ijk_cov(e->mcmc->r.xi);\n    e->theta_star_cov = qdm_ijk_cov(e->mcmc->r.theta_star);\n\n    e->xi_low_bar = xi_low_bar;\n    e->xi_high_bar = xi_high_bar;\n\n    gsl_vector_free(xi_bar);\n    gsl_matrix_free(theta_star_bar);\n    gsl_matrix_free(theta_bar);\n    gsl_vector_free(ll_sum);\n\n    gsl_vector_free(vlog);\n    gsl_vector_free(lppd);\n    gsl_vector_free(ll_exp);\n  }\n\n  /* Results */\n  {\n    e->theta_acc = qdm_matrix_copy(e->mcmc->w.theta_acc);\n    e->xi_acc = qdm_vector_copy(e->mcmc->w.xi_acc);\n\n    e->m_knots = qdm_vector_copy(m_knots);\n\n    e->rng_seed = gsl_rng_get(e->rng);\n  }\n\n  gsl_vector_free(years);\n  gsl_vector_free(years_norm);\n  gsl_vector_free(values);\n  gsl_vector_free(values_sorted);\n  gsl_vector_free(interior_knots);\n  gsl_vector_free(m_knots);\n  gsl_matrix_free(theta);\n  gsl_vector_free(ll);\n  gsl_vector_free(tau);\n\n  gsl_matrix_free(theta_tune);\n  gsl_matrix_free(theta_acc);\n  gsl_vector_free(xi_tune);\n  gsl_vector_free(xi_acc);\n\ncleanup:\n  e->elapsed = ((double)(clock() - started_at)) / CLOCKS_PER_SEC;\n\n  return status;\n}\n", "meta": {"hexsha": "e4805061d6ef1609b84678abd62ff2083b455cc7", "size": 17240, "ext": "c", "lang": "C", "max_stars_repo_path": "src/evaluation.c", "max_stars_repo_name": "calebcase/qdm", "max_stars_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/evaluation.c", "max_issues_repo_name": "calebcase/qdm", "max_issues_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-03-06T18:09:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-22T20:22:53.000Z", "max_forks_repo_path": "src/evaluation.c", "max_forks_repo_name": "calebcase/qdm", "max_forks_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.7140974967, "max_line_length": 126, "alphanum_fraction": 0.6371809745, "num_tokens": 5325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3923368443773709, "lm_q2_score": 0.03258974441367637, "lm_q1q2_score": 0.012786157482326838}}
{"text": "/* histogram/init2d.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#include <config.h>\n#include <stdlib.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_histogram2d.h>\n\ngsl_histogram2d *\ngsl_histogram2d_alloc (const size_t nx, const size_t ny)\n{\n  gsl_histogram2d *h;\n\n  if (nx == 0)\n    {\n      GSL_ERROR_VAL (\"histogram2d length nx must be positive integer\",\n\t\t\tGSL_EDOM, 0);\n    }\n\n  if (ny == 0)\n    {\n      GSL_ERROR_VAL (\"histogram2d length ny must be positive integer\",\n\t\t\tGSL_EDOM, 0);\n    }\n\n  h = (gsl_histogram2d *) malloc (sizeof (gsl_histogram2d));\n\n  if (h == 0)\n    {\n      GSL_ERROR_VAL (\"failed to allocate space for histogram2d struct\",\n\t\t\tGSL_ENOMEM, 0);\n    }\n\n  h->xrange = (double *) malloc ((nx + 1) * sizeof (double));\n\n  if (h->xrange == 0)\n    {\n      free (h);\t\t/* exception in constructor, avoid memory leak */\n\n      GSL_ERROR_VAL (\"failed to allocate space for histogram2d x ranges\",\n\t\t\tGSL_ENOMEM, 0);\n    }\n\n  h->yrange = (double *) malloc ((ny + 1) * sizeof (double));\n\n  if (h->yrange == 0)\n    {\n      free (h->xrange);\n      free (h);\t\t/* exception in constructor, avoid memory leak */\n\n      GSL_ERROR_VAL (\"failed to allocate space for histogram2d y ranges\",\n\t\t\tGSL_ENOMEM, 0);\n    }\n\n  h->bin = (double *) malloc (nx * ny * sizeof (double));\n\n  if (h->bin == 0)\n    {\n      free (h->xrange);\n      free (h->yrange);\n      free (h);\t\t/* exception in constructor, avoid memory leak */\n\n      GSL_ERROR_VAL (\"failed to allocate space for histogram bins\",\n\t\t\tGSL_ENOMEM, 0);\n    }\n\n  h->nx = nx;\n  h->ny = ny;\n\n  return h;\n}\n\ngsl_histogram2d *\ngsl_histogram2d_calloc_uniform (const size_t nx, const size_t ny,\n\t\t\t\tconst double xmin, const double xmax,\n\t\t\t\tconst double ymin, const double ymax)\n{\n  gsl_histogram2d *h;\n\n  if (xmin >= xmax)\n    {\n      GSL_ERROR_VAL (\"xmin must be less than xmax\", GSL_EINVAL, 0);\n    }\n\n  if (ymin >= ymax)\n    {\n      GSL_ERROR_VAL (\"ymin must be less than ymax\", GSL_EINVAL, 0);\n    }\n\n  h = gsl_histogram2d_calloc (nx, ny);\n\n  if (h == 0)\n    {\n      return h;\n    }\n\n  {\n    size_t i;\n\n    for (i = 0; i < nx + 1; i++)\n      {\n\th->xrange[i] = xmin + ((double) i / (double) nx) * (xmax - xmin);\n      }\n\n    for (i = 0; i < ny + 1; i++)\n      {\n\th->yrange[i] = ymin + ((double) i / (double) ny) * (ymax - ymin);\n      }\n  }\n\n  return h;\n}\n\ngsl_histogram2d *\ngsl_histogram2d_calloc (const size_t nx, const size_t ny)\n{\n  gsl_histogram2d *h;\n\n  if (nx == 0)\n    {\n      GSL_ERROR_VAL (\"histogram2d length nx must be positive integer\",\n\t\t\tGSL_EDOM, 0);\n    }\n\n  if (ny == 0)\n    {\n      GSL_ERROR_VAL (\"histogram2d length ny must be positive integer\",\n\t\t\tGSL_EDOM, 0);\n    }\n\n  h = (gsl_histogram2d *) malloc (sizeof (gsl_histogram2d));\n\n  if (h == 0)\n    {\n      GSL_ERROR_VAL (\"failed to allocate space for histogram2d struct\",\n\t\t\tGSL_ENOMEM, 0);\n    }\n\n  h->xrange = (double *) malloc ((nx + 1) * sizeof (double));\n\n  if (h->xrange == 0)\n    {\n      free (h);\t\t/* exception in constructor, avoid memory leak */\n\n      GSL_ERROR_VAL (\"failed to allocate space for histogram2d x ranges\",\n\t\t\tGSL_ENOMEM, 0);\n    }\n\n  h->yrange = (double *) malloc ((ny + 1) * sizeof (double));\n\n  if (h->yrange == 0)\n    {\n      free (h->xrange);\n      free (h);\t\t/* exception in constructor, avoid memory leak */\n\n      GSL_ERROR_VAL (\"failed to allocate space for histogram2d y ranges\",\n\t\t\tGSL_ENOMEM, 0);\n    }\n\n  h->bin = (double *) malloc (nx * ny * sizeof (double));\n\n  if (h->bin == 0)\n    {\n      free (h->xrange);\n      free (h->yrange);\n      free (h);\t\t/* exception in constructor, avoid memory leak */\n\n      GSL_ERROR_VAL (\"failed to allocate space for histogram bins\",\n\t\t\tGSL_ENOMEM, 0);\n    }\n\n  {\n    size_t i;\n\n    for (i = 0; i < nx + 1; i++)\n      {\n\th->xrange[i] = i;\n      }\n\n    for (i = 0; i < ny + 1; i++)\n      {\n\th->yrange[i] = i;\n      }\n\n    for (i = 0; i < nx * ny; i++)\n      {\n\th->bin[i] = 0;\n      }\n  }\n\n  h->nx = nx;\n  h->ny = ny;\n\n  return h;\n}\n\n\nvoid\ngsl_histogram2d_free (gsl_histogram2d * h)\n{\n  free (h->xrange);\n  free (h->yrange);\n  free (h->bin);\n  free (h);\n}\n\n\nint \ngsl_histogram2d_set_ranges_uniform (gsl_histogram2d * h, \n                                    double xmin, double xmax,\n                                    double ymin, double ymax)\n{\n  size_t i;\n  const size_t nx = h->nx, ny = h->ny;\n\n  if (xmin >= xmax)\n    {\n      GSL_ERROR_VAL (\"xmin must be less than xmax\", GSL_EINVAL, 0);\n    }\n\n  if (ymin >= ymax)\n    {\n      GSL_ERROR_VAL (\"ymin must be less than ymax\", GSL_EINVAL, 0);\n    }\n\n  /* initialize ranges */\n\n  for (i = 0; i <= nx; i++)\n    {\n      h->xrange[i] = xmin + ((double) i / (double) nx) * (xmax - xmin);\n    }\n\n  for (i = 0; i <= ny; i++)\n    {\n      h->yrange[i] = ymin + ((double) i / (double) ny) * (ymax - ymin);\n    }\n\n  /* clear contents */\n\n  for (i = 0; i < nx * ny; i++)\n    {\n      h->bin[i] = 0;\n    }\n\n  return GSL_SUCCESS;\n}\n\nint \ngsl_histogram2d_set_ranges (gsl_histogram2d * h, \n                            const double xrange[], size_t xsize,\n                            const double yrange[], size_t ysize)\n{\n  size_t i;\n  const size_t nx = h->nx, ny = h->ny;\n\n  if (xsize != (nx + 1))\n    {\n      GSL_ERROR_VAL (\"size of xrange must match size of histogram\", \n                     GSL_EINVAL, 0);\n    }\n\n  if (ysize != (ny + 1))\n    {\n      GSL_ERROR_VAL (\"size of yrange must match size of histogram\", \n                     GSL_EINVAL, 0);\n    }\n\n  /* initialize ranges */\n\n  for (i = 0; i <= nx; i++)\n    {\n      h->xrange[i] = xrange[i];\n    }\n\n  for (i = 0; i <= ny; i++)\n    {\n      h->yrange[i] = yrange[i];\n    }\n\n  /* clear contents */\n\n  for (i = 0; i < nx * ny; i++)\n    {\n      h->bin[i] = 0;\n    }\n\n  return GSL_SUCCESS;\n}\n", "meta": {"hexsha": "9895ec5c918458bcc6aaffa2be1dbf7025abdd27", "size": 6405, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/histogram/init2d.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/histogram/init2d.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/histogram/init2d.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 21.0, "max_line_length": 73, "alphanum_fraction": 0.5619047619, "num_tokens": 1979, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29421497216298875, "lm_q2_score": 0.043365801391162265, "lm_q1q2_score": 0.012758868049126505}}
{"text": "#undef FP_T\n#undef FP_ID\n#undef VECTOR_T\n#undef VECTOR_ID\n#undef MATRIX_T\n#undef MATRIX_ID\n\n#ifdef GSL_FLOAT\n#define MATLAB_NAMESPACE matlab_float\n#define BCT_NAMESPACE bct_float\n#define FP_T float\n#define FP_ID(id) id##_##float\n#define VECTOR_T gsl_vector_float\n#define VECTOR_ID(id) gsl_vector_float##_##id\n#define MATRIX_T gsl_matrix_float\n#define MATRIX_ID(id) gsl_matrix_float##_##id\n#include <gsl/gsl_matrix_float.h>\n#include <gsl/gsl_vector_float.h>\n#endif\n\n#ifdef GSL_DOUBLE\n#define MATLAB_NAMESPACE matlab\n#define BCT_NAMESPACE bct\n#define FP_T double\n#define FP_ID(id) id##_##double\n#define VECTOR_T gsl_vector\n#define VECTOR_ID(id) gsl_vector##_##id\n#define MATRIX_T gsl_matrix\n#define MATRIX_ID(id) gsl_matrix##_##id\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_vector.h>\n#endif\n\n#ifdef GSL_LONG_DOUBLE\n#define MATLAB_NAMESPACE matlab_long_double\n#define BCT_NAMESPACE bct_long_double\n#define FP_T long double\n#define FP_ID(id) id##_##long_double\n#define VECTOR_T gsl_vector_long_double\n#define VECTOR_ID(id) gsl_vector_long_double##_##id\n#define MATRIX_T gsl_matrix_long_double\n#define MATRIX_ID(id) gsl_matrix_long_double##_##id\n#include <gsl/gsl_matrix_long_double.h>\n#include <gsl/gsl_vector_long_double.h>\n#endif\n", "meta": {"hexsha": "582a96f20e3931fc048d90b2b5304cf0b2bd815c", "size": 1231, "ext": "h", "lang": "C", "max_stars_repo_path": "precision.h", "max_stars_repo_name": "devuci/bct-cpp", "max_stars_repo_head_hexsha": "bbb33f476bffbb5669e051841f00c3241f4d6f69", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "precision.h", "max_issues_repo_name": "devuci/bct-cpp", "max_issues_repo_head_hexsha": "bbb33f476bffbb5669e051841f00c3241f4d6f69", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "precision.h", "max_forks_repo_name": "devuci/bct-cpp", "max_forks_repo_head_hexsha": "bbb33f476bffbb5669e051841f00c3241f4d6f69", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7608695652, "max_line_length": 51, "alphanum_fraction": 0.8139723802, "num_tokens": 306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4765796510636759, "lm_q2_score": 0.02675928308842458, "lm_q1q2_score": 0.01275292979699551}}
{"text": "\n#ifndef _OPTIMIZE_STATE_RECONSTRUCTOR_GSL_H_\n#define _OPTIMIZE_STATE_RECONSTRUCTOR_GSL_H_\n\nusing namespace std;\n\n#include <armadillo>\nusing namespace arma;\n\n#include \"rate_model.h\"\n#include \"state_reconstructor.h\"\n\n#include <gsl/gsl_vector.h>\n\nclass OptimizeStateReconstructor{\nprivate:\n    RateModel * rm;\n    StateReconstructor * sr;\n    mat * free_variables;\n    int nfree_variables;\n    int maxiterations;\n    double stoppingprecision;\n\n    double GetLikelihoodWithOptimized(const gsl_vector * variables);\n    static double GetLikelihoodWithOptimized_gsl(const gsl_vector * variables, void *obj);\n\npublic:\n    OptimizeStateReconstructor(RateModel *,StateReconstructor *, mat *, int);\n    mat optimize();\n};\n\n#endif /* _OPTIMIZE_STATE_RECONSTRUCTOR_GSL_H_ */\n", "meta": {"hexsha": "2a23531a8e8964b65a327aa358aafb144329e5c9", "size": 763, "ext": "h", "lang": "C", "max_stars_repo_path": "src/phyx-1.01/src/optimize_state_reconstructor_gsl.h", "max_stars_repo_name": "jlanga/smsk_selection", "max_stars_repo_head_hexsha": "08070c6d4a6fbd9320265e1e698c95ba80f81123", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-07-18T05:20:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T10:22:33.000Z", "max_issues_repo_path": "src/phyx-1.01/src/optimize_state_reconstructor_gsl.h", "max_issues_repo_name": "jlanga/smsk_selection", "max_issues_repo_head_hexsha": "08070c6d4a6fbd9320265e1e698c95ba80f81123", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-08-21T07:26:13.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-08T13:59:48.000Z", "max_forks_repo_path": "src/phyx-1.01/src/optimize_state_reconstructor_gsl.h", "max_forks_repo_name": "jlanga/smsk_orthofinder", "max_forks_repo_head_hexsha": "08070c6d4a6fbd9320265e1e698c95ba80f81123", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-07-18T05:20:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:23:31.000Z", "avg_line_length": 23.1212121212, "max_line_length": 90, "alphanum_fraction": 0.7732634338, "num_tokens": 179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.341582499438317, "lm_q2_score": 0.037326885737772805, "lm_q1q2_score": 0.012750210926556902}}
{"text": "\n/**\n  * THE BIG PICTURE\n  *\n  * This file:\n  * 1) (libmtm.a, actually) loads and parses the input matrix\n  * 2) iterates through a sequence of feature pairs specified in one of\n  *    a variety of ways\n  * 3) for each pair it calls a high-level analysis method that selects\n  *    and executes an appropriate covariate analysis.\n  * 4) routes the analysis results to either\n  *    a) immediate output using a specified formatter or\n  *    b) a cache to be post-processed (for FDR control) and subsequently\n  *       output.\n  *\n  * Implementation notes:\n  *   1) If row labels are present then, by default, they are parsed to\n  *      infer the statistical class of the row. Moreover, the parser is\n  *      one for \"TCGA\" format by default. This is so that Sheila et al.'s\n  *      scripts need not pass an option for something they consider\n  *      \"standard.\" In order to minimize the danger of mis-interpreted\n  *      row labels a conservative definition is used (by the\n  *      mtm_sclass_by_prefix function). The first two characters of the row\n  *      label must match /[BCDFNO][[:punct:]]/.\n  *      Otherwise, mtm_sclass_by_prefix returns MTM_STATCLASS_UNKNOWN,\n  *      and the class is inferred from the data content of the row.\n  * Audit:\n  *   1) All error exits return -1. When used as webservice proper status\n  *      returns is the least we can do...\n  *   2) stdout is ONLY used for data output (at verbosity 0)\n  *   3) Analysis failures (because of degeneracy) still return something\n  *      the web service can deal with. Striving for data-as-error,\n  *      instead of a separate error channel.\n  *   4) Insure mtm_resort is called before named rows are used.\n  *   5) Every statistical test must fully initialize 1st 4 members of\n  *      struct Statistic\n  *   6) Casts, ALL casts!\n  */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <string.h>\n#include <time.h>\n#include <math.h>\n#include <signal.h>\n#include <time.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <unistd.h>\n#include <getopt.h>\n#include <stdbool.h>\n#include <assert.h>\n#include <ctype.h>\n#include <err.h>\n#include <alloca.h>\n\n#include <gsl/gsl_errno.h>\n\n#include \"mtmatrix.h\"\n#include \"mtheader.h\"\n#include \"mtsclass.h\"\n#include \"mterror.h\"\n#include \"featpair.h\"\n#include \"stattest.h\"\n#include \"analysis.h\"\n#include \"varfmt.h\"\n#include \"fixfmt.h\"\n#include \"limits.h\"\n#include \"version.h\"\n\n#ifdef HAVE_LUA\n#include \"lua.h\"\n#include \"lauxlib.h\"\n#include \"lualib.h\"\n#endif\n\n/***************************************************************************\n * externs\n */\n\nextern int mtm_sclass_by_prefix( const char *token );\n\nextern int get_base10_ints( FILE *fp, int *index, int n );\n\n/***************************************************************************\n * Globals & statics\n */\n\nstatic const char *MAGIC_SUFFIX         = \"-www\";\nstatic const char *MAGIC_FORMAT_ID_STD  = \"std\";\nstatic const char *MAGIC_FORMAT_ID_TCGA = \"tcga\";\n\nstatic const char *TYPE_PARSER_INFER    = \"auto\";\n\nconst char *AUTHOR_EMAIL = \"rkramer@systemsbiology.org\";\n\n/**\n  * False Discovery Rate control state.\n  */\n\nstatic double arg_q_value = 0.0;\n#define USE_FDR_CONTROL (arg_q_value > 0.0)\n\n/**\n  * This is used simply to preclude bloating the FDR cache with results\n  * that can't possibly be relevant to the final BH-calculated p-value\n  * threshold for FDR.\n  * I'm setting this high for safety since it's just an optimization, but\n  * it could probably be MUCH smaller.\n  */\nstatic double opt_fdr_cache_threshold = 0.5;\n\n\n// No default on opt_script because looking for a \"default.lua\" script\n// or any *.lua file invites all sorts of confusion with the defaults\n// and precedence of other row selection methods.\nstatic const char *opt_script          = NULL;\nstatic bool        opt_header          = true;\nstatic bool        opt_row_labels      = true;\nstatic const char *opt_type_parser     = NULL;\nstatic const char *opt_preproc_matrix  = NULL; // ...or optarg\nstatic       char *opt_single_pair     = NULL; // non-const because it's split\n\nstatic const char *opt_pairlist_source = NULL;\n\nstatic const char *NO_ROW_LABELS       = \"matrix has no row labels\";\nstatic bool        opt_by_name         = false;\n#ifdef HAVE_LUA\nstatic const char *DEFAULT_COROUTINE   = \"pair_generator\";\n#endif\nstatic const char *opt_coroutine       = NULL;\nstatic bool        opt_dry_run         = false;\nstatic const char *opt_format          = \"tcga\";\nstatic bool     opt_warnings_are_fatal = false;\n\n/**\n  * Primary output and critical error messages.\n  */\n#define V_ESSENTIAL (1)\n\n/**\n  * Non-critical information that may, nonetheless, be helpful.\n  */\n#define V_WARNINGS  (2)\n\n/**\n  * Purely informational.\n  */\n#define V_INFO      (3)\n\nstatic int opt_verbosity = V_ESSENTIAL;\n\n#ifdef _DEBUG\nstatic bool  dbg_silent               = false;\n#endif\n\n#define GLOBAL\nGLOBAL unsigned  arg_min_cell_count   = 5;\nGLOBAL unsigned  arg_min_mixb_count   = 1;\nGLOBAL unsigned  arg_min_sample_count = 2; // < 2 NEVER makes sense\n#undef  GLOBAL\n\nstatic const char *opt_na_regex       = NULL; // must be initialized in main\n\nstatic double      opt_p_value        = 1.0;\n\n/**\n  * Eventually it is (was) intended to support delegating row label\n  * interpretation--in particular inference of a row's statistical class\n  * based on its row label--to a user-provided Lua function.\n  * Currently, only the default interpreter built into libmtm is actually\n  * supported, which interprets row labels according to \"ISB conventions.\"\n  */\nstatic MTM_ROW_LABEL_INTERPRETER _interpret_row_label = mtm_sclass_by_prefix;\n\nstatic unsigned opt_status_mask       = COVAN_E_MASK;\n\n#ifdef HAVE_LUA\nstatic lua_State *_L = NULL;\n/**\n  * Delegate inference of a row's statistical class to a user-provided\n  * function.\n  */\nint _lua_statclass_inference( const char *label ) {\n\tfprintf( stderr, \"interpret %s\\n\", label );\n\treturn MTM_STATCLASS_UNKNOWN;\n}\n\nstatic void _freeLua() {\n\tlua_close( _L );\n}\n\n/**\n  * <source> may be literal Lua code or a filename reference.\n  */\nstatic int _load_script( const char *source, lua_State *state ) {\n\n\tstruct stat info;\n\treturn (access( source, R_OK ) == 0) && (stat( source, &info ) == 0)\n\t\t? luaL_dofile(   state, source )\n\t\t: luaL_dostring( state, source );\n}\n\n#endif\n\nstatic FILE *_fp_output = NULL;\nstatic void (*_emit)( EMITTER_SIG ) = format_tcga;\n\nstatic bool _sigint_received = false;\n\n/**\n  * Records the number of pairwise tests COMPLETED WITHOUT ERROR\n  * but not emitted (because they didn't pass the p-value threshold\n  * for emission.\n  *\n  * This is NOT used when FDR control is active in pairwise; rather it is\n  * for use in FDR control calculations *outside* the context of pairwise.\n  *\n  * Note that the total number of tests *attempted* is *not* separately\n  * counted because it is assumed that that is known to the caller who\n  * set up the run, after all.\n  */\nstatic unsigned _insignificant = 0;\nstatic unsigned _untested      = 0;\n\n/**\n  * The binary matrix is accessed at runtime through this variable.\n  * Notice, in particular, that the analysis code (analysis.cpp)\n  * only has access to pairs of rows, NOT the whole matrix.\n  * The matrix' structure and implementation is strictly encapsulated\n  * within this file, and code in here dolls out just what analysis\n  * requires: row pairs.\n  */\nstatic struct mtm_matrix _matrix;\n\nstatic void _freeMatrix( void ) {\n\t_matrix.destroy( &_matrix );\n}\n\nstatic void _interrupt( int n ) {\n\t_sigint_received = true;\n}\n\n/***************************************************************************\n * Pipeline\n * A) explicit pairs\n *    1. row pair -> analysis -> filtering -> output\n * B) all-pairs or Lua generated pair lists\n *    1. row pair -> analysis -> filtering -> output\n *    2. row pair -> analysis -> fdr aggregation -> re-processing ->output\n */\n\n/**\n  * Analysis results on feature pairs are passed EITHER to:\n  * 1. an emitter for immediate output (single pair only)\n  * 2. a filter (and then possibly to an emitter)\n  * 3. an aggregator (to be filtered and stored for later emission)\n  *\n  * All three of these methods must have the same signature.\n  */\n#define ANALYSIS_FN_SIG const struct feature_pair *pair\n\ntypedef void (*ANALYSIS_FN)( ANALYSIS_FN_SIG );\n\n/***************************************************************************\n * Encapsulates all the decision making regarding actual emission of\n * results.\n */\nstatic void _filter( ANALYSIS_FN_SIG ) {\n\n\tstruct CovariateAnalysis covan;\n\tmemset( &covan, 0, sizeof(covan) );\n\tcovan_exec( pair, &covan );\n\n\t// One last thing to check before filtering to insure corner cases\n\t// don't fall through the following conditionals....\n\n\tif( ! ( isfinite( covan.result.probability ) && fpclassify( covan.result.probability ) != FP_SUBNORMAL ) ) {\n\t\tcovan.result.probability = 1.0;\n\t\tcovan.status             = COVAN_E_MATH;\n\t\t// The assumption is that if a NaN shows up in the result, it was\n\t\t// triggered by an un\"pre\"detected degeneracy, and so the pair was\n\t\t// in fact untestable (how it will be interpreted below).\n\t}\n\n#ifdef _DEBUG\n\tif( ! dbg_silent ) {\n#endif\n\n\t\tif( ( covan.status & opt_status_mask ) == 0 ) {\n\t\t\tif( covan.result.probability <= opt_p_value )\n\t\t\t\t_emit( pair, &covan, _fp_output );\n\t\t\telse\n\t\t\t\t_insignificant += 1;\n\t\t} else\n\t\t\t_untested += 1;\n\n#ifdef _DEBUG\n\t}\t\n#endif\n}\n\nstatic ANALYSIS_FN _analyze = _filter;\n\nstatic void _error_handler(const char * reason,\n                        const char * file,\n                        int line,\n                        int gsl_errno) {\n\tfprintf( stderr,\n\t\t\"#GSL error(%d): %s\\n\"\n\t\t\"#GSL error  at: %s:%d\\n\",\n\t\tgsl_errno, reason, file, line );\n}\n\n\nstatic FILE *_fdr_cache_fp = NULL;\n\n/***************************************************************************\n  * FDR processing\n  * This currently involves some redundant computation in the interest of\n  * simplicity. Since the whole point of FDR is to limit output, though, the\n  * actual runtime cost should be bearabe. Specifically...\n  *\n  * 1. Two passes are made over the (selected) pairs.\n  * 2. The offsets and p-value of the result of the first pass are cached\n  *    in a tmp file.\n  * 3. After completion, the p-value appropriate for the given q-value is\n  *    determined and results from the 1st pass with sufficiently low\n  *    p-values are recalculated and, this time, fully emitted.\n  *\n  * TODO: Optimization: Pairs with very high p-values (i.e. *clearly*\n  * uninteresting pairs) can be omitted from the cache even in the first\n  * pass and merely counted as tests since their recomputation will *almost*\n  * certainly, depending ultimately on the threshold, not be required.\n  */\n\nstruct FDRCacheRecord {\n\tdouble p;\n\tunsigned a,b;\n} __attribute__((packed));\ntypedef struct FDRCacheRecord FDRCacheRecord_t;\ntypedef const FDRCacheRecord_t FDRCACHERECORD_T;\n\nstatic int _cmp_fdr_cache_records( const void *pvl, const void *pvr ) {\n\n\tFDRCACHERECORD_T *l = (FDRCACHERECORD_T*)pvl;\n\tFDRCACHERECORD_T *r = (FDRCACHERECORD_T*)pvr;\n\n\tif( l->p == r->p )\n\t\treturn  0;\n\telse\n\t\treturn (l->p < r->p) ? -1 : +1;\n}\n\n\nstatic int _fdr_uncached_count = 0;\n\n\n/**\n  * Analyze the pair and cache just the offsets and p-value of the result\n  * for possible recalculation during post-processing--after FDR control\n  * has calculated an appropriate p-value threshold from the q-value.\n  */\nstatic void _fdr_cache( ANALYSIS_FN_SIG ) {\n\n\tstruct CovariateAnalysis covan;\n\tmemset( &covan, 0, sizeof(covan) );\n\n\tcovan_exec( pair, &covan );\n\n\t// Failed tests (for reasons of one kind of degeneracy or another)\n\t// do not contribute to the calculation of the p-value threshold.\n\n\tif( covan.status == 0\n\t\t&& isfinite( covan.result.probability ) ) {\n\n\t\t// ...then, whatever the p-value, the test was at least\n\t\t// successfully *executed*.\n\n\t\tif( covan.result.probability <= opt_fdr_cache_threshold ) {\n\t\t\tstruct FDRCacheRecord rec = {\n\t\t\t\t.p = covan.result.probability,\n\t\t\t\t.a = pair->l.offset,\n\t\t\t\t.b = pair->r.offset\n\t\t\t};\n\t\t\tfwrite( &rec, sizeof(rec), 1, _fdr_cache_fp );\n\t\t} else\n\t\t\t_fdr_uncached_count += 1;\n\t}\n}\n\n\n/**\n  * This implements the Benjamini-Hochberg algorithm as described on\n  * page 49 of \"Large-Scale Inference\", Bradley Efron, Cambridge.\n  * \"...for a fixed value of q in (0,1), let i_max be the largest\n  *  index for which\n  *                     p_(i) <= (i/N)q\n  *\n  *  ...and reject H_{0(i)}, the null hypothesis corresponding to\n  *  p_(i), if\n  *                         i <= i_max,\n  *\n  *  ...accepting H_{0(i)} otherwise.\"\n  *\n  * [...And i is 1-based in this notation!]\n  */\nstatic void _fdr_postprocess( FILE *cache, double Q, FILE *final_output, bool minimal_output ) {\n\n\tconst unsigned CACHED_COUNT\n\t\t= ftell( cache ) / sizeof(struct FDRCacheRecord);\n\tconst unsigned TESTED_COUNT\n\t\t= CACHED_COUNT\n\t\t+ _fdr_uncached_count;\n\n\tstruct FDRCacheRecord *prec, *sortbuf\n\t\t= calloc( CACHED_COUNT, sizeof(struct FDRCacheRecord) );\n\n\tconst double RATIO\n\t\t= Q/TESTED_COUNT;\n\tint i = 0;\n\n\t// Load and sort the cached test records...\n\n\trewind( cache );\n\tfread( sortbuf, sizeof(struct FDRCacheRecord), CACHED_COUNT, cache );\n\tqsort( sortbuf, CACHED_COUNT, sizeof(struct FDRCacheRecord), _cmp_fdr_cache_records );\n\n\t// ...and recompute the full statistics of all earlier tests that\n\t// pass the now-established p-value threshold.\n\n\tprec = sortbuf;\n\tif( minimal_output ) {\n\n\t\twhile( prec->p <= (i+1)*RATIO && i < CACHED_COUNT) \n\t\t\tfprintf( final_output, \"%d\\t%d\\t%.3e\\n\", prec->a, prec->b, prec->p );\n\n\t} else {\n\n\t\twhile( prec->p <= (i+1)*RATIO && i < CACHED_COUNT) {\n\t\t\n\t\t\tstruct feature_pair fpair;\n\t\t\tstruct CovariateAnalysis covan;\n\t\t\tmemset( &covan, 0, sizeof(covan) );\n\n\t\t\tfpair.l.offset = prec->a;\n\t\t\tfpair.r.offset = prec->b;\n\t\t\tfetch_by_offset( &_matrix, &fpair );\n\n\t\t\tcovan_exec( &fpair, &covan );\n\n\t\t\t// At this point emission is unconditional; FDR control has\n\t\t\t// already filtered all that will be filtered...\n\n\t\t\t_emit( &fpair, &covan, final_output );\n\n\t\t\tif( _sigint_received ) {\n\t\t\t\ttime_t now = time(NULL);\n\t\t\t\tfprintf( stderr, \"# FDR postprocess interrupted @ %s\", ctime(&now) );\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tprec += 1;\n\t\t\ti    += 1;\n\t\t}\n\t}\n\n\t// However, the preceding loop exited\n\n\tif( opt_verbosity >= V_WARNINGS ) {\n\t\tif( i > 0 )\n\t\t\tfprintf( final_output, \"# max p-value %.3f\\n\", sortbuf[i-1].p );\n\t\telse\n\t\t\tfprintf( final_output, \"# no values passed FDR control\\n\" );\n\t}\n\tif( sortbuf )\n\t\tfree( sortbuf );\n}\n\n\n/***************************************************************************\n  * Row selection iterators\n  * Each of these 5 methods takes arguments specific to the\n  * source of input pairs and uses file static state for output.\n  * All but the first delegate to the _analyze function which may be a\n  * filter on immediate-mode output or a caching function for FDR.\n  */\n\n// BEGIN:RSI\n\nstatic int /*ANCP*/ _analyze_cross_product(\n\t\tconst struct mtm_matrix_header *hdr, FILE *fp[] ) {\n\n\tbool completed = true;\n\tstruct feature_pair fpair;\n\tstruct mtm_row *rrid;\n\n\t/**\n\t  * Location of left data won't change: same buffer, same offset for\n\t  * duration of iteration.\n\t  */\n\tfpair.l.data\n\t\t= calloc( _matrix.columns, sizeof(mtm_int_t) );\n\n\t/**\n\t  * TODO: I actually could enumerate the disk-resident matrix'\n\t  * row names just as I do the descriptors. In general, the\n\t  * pervasive assumption throughout this source that the input\n\t  * is exactly one matrix needs to be revisited.\n\t  */\n\tfpair.l.name = NULL;\n\n\tif( fpair.l.data == NULL )\n\t\treturn -1;\n\n\tassert( ! _matrix.lexigraphic_order /* should be row order */ );\n\n\tfor(fpair.l.offset = 0;\n\t\tfpair.l.offset < hdr->rows;\n\t\tfpair.l.offset++ ) {\n\n\t\t/**\n\t\t  * Read the \"left\" feature's data and descriptor\n\t\t  */\n\n\t\tif( fread( (void*)fpair.l.data, sizeof(mtm_int_t), hdr->columns,  fp[0] ) != hdr->columns )\n\t\t\tbreak;\n\t\tif( fread( &fpair.l.desc, sizeof(struct mtm_descriptor), 1, fp[1] ) != 1 )\n\t\t\tbreak;\n\n\t\t/**\n\t\t  * RAM-resident matrix is *fully* reset for each row of disk-\n\t\t  * resident matrix...\n\t\t  */\n\n\t\tfpair.r.data = _matrix.data;\n\t\trrid         = _matrix.row_map; // may be NULL\n\n\t\tfor(fpair.r.offset = 0;\n\t\t\tfpair.r.offset < _matrix.rows;\n\t\t\tfpair.r.offset++ ) {\n\n\t\t\tfpair.r.name = rrid ? rrid->string : \"\";\n\t\t\tfpair.r.desc = _matrix.desc[ fpair.r.offset ];\n\n\t\t\t_analyze( &fpair );\n\n\t\t\tif( _sigint_received ) {\n\t\t\t\ttime_t now = time(NULL);\n\t\t\t\tfprintf( stderr, \"# main analysis loop interrupted @ %s\", ctime(&now) );\n\t\t\t\tcompleted = false;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tfpair.r.data += _matrix.columns;\n\t\t\tif( rrid ) rrid += 1;\n\n\t\t} // inner for\n\t}\n\n\tif( ferror( fp[0] ) || ferror( fp[1] ) ) {\n\t\twarn( \"reading row %d of preprocessed matrix\", fpair.l.offset );\n\t\tcompleted = false;\n\t}\n\n\tif( fpair.l.data )\n\t\tfree( (void*)fpair.l.data );\n\n\treturn completed ? 0 : -1;\n}\n\n\nstatic bool _is_integer( const char *pc ) {\n\twhile( *pc ) if( ! isdigit(*pc++) ) return false;\n\treturn true;\n}\n\n\nstatic int _analyze_single_pair( const char *csv, const bool HAVE_ROW_LABELS ) {\n\n\tstatic const char *MISSING_MSG\n\t\t= \"you specified row %s for a matrix without row names.\\n\";\n\n\tint econd;\n\tchar *right, *left = alloca( strlen(csv)+1 );\n\tstruct CovariateAnalysis covan;\n\tstruct feature_pair pair;\n\n\tmemset( &pair,  0, sizeof(pair) );\n\tmemset( &covan, 0, sizeof(covan) );\n\n\t// Split the string in two...\n\n\tstrcpy( left, csv );\n\tright = strchr( left, ',' );\n\tif( NULL == right )\n\t\terrx( -1, \"missing comma separator in feature pair \\\"%s\\\"\", left );\n\t*right++ = '\\0';\n\n\t// Lookup each part.(They need not be the same format.)\n\n\tif( _is_integer( left ) ) {\n\t\tpair.l.offset = atoi( left );\n\t\tmtm_resort_rowmap( &_matrix, MTM_RESORT_BYROWOFFSET );\n\t\tecond = mtm_fetch_by_offset( &_matrix, &(pair.l) );\n\t} else\n\tif( HAVE_ROW_LABELS ) {\n\t\tpair.l.name   = left;\n\t\tif( mtm_resort_rowmap( &_matrix, MTM_RESORT_LEXIGRAPHIC ) )\n\t\t\terrx( -1, NO_ROW_LABELS );\n\t\tecond = mtm_fetch_by_name( &_matrix, &(pair.l) );\n\t} else\n\t\terrx( -1, MISSING_MSG, left );\n\n\tif( _is_integer( right ) ) {\n\t\tpair.r.offset = atoi( right );\n\t\tmtm_resort_rowmap( &_matrix, MTM_RESORT_BYROWOFFSET );\n\t\tecond = mtm_fetch_by_offset( &_matrix, &(pair.r) );\n\t} else\n\tif( HAVE_ROW_LABELS ) {\n\t\tpair.r.name = right;\n\t\tif( mtm_resort_rowmap( &_matrix, MTM_RESORT_LEXIGRAPHIC ) )\n\t\t\terrx( -1, NO_ROW_LABELS );\n\t\tecond = mtm_fetch_by_name( &_matrix, &(pair.r) );\n\t} else\n\t\terrx( -1, MISSING_MSG, right );\n\n\tcovan_exec( &pair, &covan );\n\n\t_emit( &pair, &covan, _fp_output );\n\n\treturn 0;\n}\n\n\nstatic int /*ANAM*/ _analyze_named_pair_list( FILE *fp ) {\n\n\tstruct feature_pair fpair;\n\n\tsize_t blen = 0;\n\tssize_t llen;\n\tchar *right, *left = NULL;\n\n\twhile( ( llen = getline( &left, &blen, fp ) ) > 0 ) {\n\n\t\t// Trim off the newline char.\n\n\t\tif( left[llen-1] == '\\n' )\n\t\t\tleft[--llen] = '\\0'; // Strip the NL\n\n\t\t// Parse the two names out of the line.\n\n\t\tright = strchr( left, '\\t' );\n\t\tif( right )\n\t\t\t*right++ = '\\0';\n\t\telse {\n\t\t\tfprintf( stderr, \"error: no tab found in '%s'.\\n\", left );\n\t\t\tif( opt_warnings_are_fatal )\n\t\t\t\tbreak;\n\t\t\telse\n\t\t\t\tcontinue; // no reason we -can't- continue\n\t\t}\n\n\t\tfpair.l.name  = left;\n\t\tfpair.r.name = right;\n\n\t\tif( fetch_by_name( &_matrix, &fpair ) ) {\n\n\t\t\twarnx( \"error: one or both of...\\n\"\n\t\t\t\t\"\\t1) %s\\n\"\n\t\t\t\t\"\\t2) %s\\n\"\n\t\t\t\t\"\\t...not found.\\n\",\n\t\t\t\tfpair.l.name,\n\t\t\t\tfpair.r.name );\n\t\t\tif( opt_warnings_are_fatal )\n\t\t\t\tbreak;\n\t\t\telse\n\t\t\t\tcontinue; // no reason we -can't- continue\n\t\t} else\n\t\t\t_analyze( &fpair );\n\t}\n\n\tif( left )\n\t\tfree( left );\n\n\treturn 0;\n}\n\n\nstatic int /*ANUM*/ _analyze_pair_list( FILE *fp ) {\n\n\tstruct feature_pair fpair;\n\n\tint arr[2];\n\n\twhile( get_base10_ints( fp, arr, 2 ) == 2 ) {\n\n\t\tfpair.l.offset = arr[0];\n\t\tfpair.r.offset = arr[1];\n\n\t\tif( fetch_by_offset( &_matrix, &fpair ) ) {\n\t\t\twarnx( \"error: one of row indices (%d,%d) not in [0,%d)\\n\"\n\t\t\t\t\"\\tjust before byte offset %ld in the stream.\\n\"\n\t\t\t\t\"\\tAborting...\\n\",\n\t\t\t\tfpair.l.offset,\n\t\t\t\tfpair.r.offset,\n\t\t\t\t_matrix.rows,\n\t\t\t\tftell( fp ) );\n\t\t\tif( opt_warnings_are_fatal )\n\t\t\t\tbreak;\n\t\t\telse\t\n\t\t\t\tcontinue; // no reason we -can't- continue\n\t\t} else\n\t\t\t_analyze( &fpair );\n\t}\n\treturn 0;\n}\n\n\n#ifdef HAVE_LUA\nstatic int /*ALUA*/ _analyze_generated_pair_list( lua_State *state ) {\n\n\tstruct feature_pair fpair;\n\tint isnum, lua_status;\n\n\tlua_getglobal( _L, opt_coroutine );\n\n\tassert( ! lua_isnil( _L, -1 ) /* because it was checked early */ );\n\n\tdo {\n\n\t\tlua_pushnumber( _L, _matrix.rows );\n\t\tlua_status = lua_resume( _L, NULL, 1 );\n\n\t\tif( lua_status == LUA_YIELD ) {\n\n\t\t\tfpair.r.offset = lua_tonumberx( _L, -1, &isnum );\n\t\t\tfpair.l.offset = lua_tonumberx( _L, -2, &isnum );\n\t\t\tlua_pop( _L, 2 );\n\n\t\t\tif( fetch_by_offset( &_matrix, &fpair ) ) {\n\t\t\t\twarnx( \"one or both of %s-generated row indices (%d,%d) not in [0,%d)\\n\",\n\t\t\t\t\topt_coroutine,\n\t\t\t\t\tfpair.l.offset,\n\t\t\t\t\tfpair.r.offset,\n\t\t\t\t\t_matrix.rows );\n\t\t\t\tif( opt_warnings_are_fatal )\n\t\t\t\t\tbreak;\n\t\t\t\telse\t\n\t\t\t\t\tcontinue; // no reason we -can't- continue\n\t\t\t} else\n\t\t\t\t_analyze( &fpair );\n\n\t\t} else\n\t\tif( lua_status == LUA_OK )\n\t\t\tbreak;\n\t\telse { // some sort of error occurred.\n\t\t\tfputs( lua_tostring( _L, -1 ), stderr );\n\t\t}\n\n\t\tif( _sigint_received ) {\n\t\t\ttime_t now = time(NULL);\n\t\t\tfprintf( stderr, \"analysis loop interrupted @ %s\", ctime(&now) );\n\t\t\tbreak;\n\t\t}\n\n\t} while( lua_status == LUA_YIELD );\n\n\n\treturn 0;\n}\n#endif\n\n/**\n  * This clause serves the primary use case motivating this\n  * application: FAST, EXHAUSTIVE (n-choose-2) pairwise analysis.\n  * As a result, the coding of this iteration schema is quite\n  * different from the others. In particular:\n  * 1. Since I -know- the order of feature pair evaluation I can\n  *    preclude lots of useless work by entirely skipping outer loop\n  * features with univariate degeneracy. This isn't feasible in\n  * the other iteration sc\n  * I'm dispensing with \"pretty\" and doing the\n  * pointer arithmetic locally to eek out maximum possible speed.\n  * In particular, I set up lots of ptrs below to obviate\n  * redundant pointer arithmetic--only do fixed additions.\n  */\nstatic int /*AALL*/ _analyze_all_pairs( void ) {\n\n\tbool completed = true;\n\tstruct feature_pair fpair;\n\n\tstruct mtm_row *lrid, *rrid;\n\n\tassert( ! _matrix.lexigraphic_order /* should be row order */ );\n\n\tfpair.l.data = _matrix.data;\n\tlrid         = _matrix.row_map; // may be NULL\n\n\tfor(fpair.l.offset = 0;\n\t\tfpair.l.offset < _matrix.rows;\n\t\tfpair.l.offset++ ) {\n\n\t\tfpair.l.name = lrid ? lrid->string : \"\";\n\t\tfpair.l.desc = _matrix.desc[ fpair.l.offset ];\n\n\t\tfpair.r.data = fpair.l.data + _matrix.columns;\n\t\trrid = lrid ? lrid + 1 : NULL;\n\n\t\tfor(fpair.r.offset = fpair.l.offset+1;\n\t\t\tfpair.r.offset < _matrix.rows;\n\t\t\tfpair.r.offset++ ) {\n\n\t\t\tfpair.r.name = rrid ? rrid->string : \"\";\n\t\t\tfpair.r.desc = _matrix.desc[ fpair.r.offset ];\n\n\t\t\t_analyze( &fpair );\n\n\t\t\tif( _sigint_received ) {\n\t\t\t\ttime_t now = time(NULL);\n\t\t\t\tfprintf( stderr, \"# main analysis loop interrupted @ %s\", ctime(&now) );\n\t\t\t\tcompleted = false;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tfpair.r.data += _matrix.columns;\n\t\t\tif( rrid ) rrid += 1;\n\n\t\t} // inner for\n\n\t\tfpair.l.data += _matrix.columns;\n\t\tif( lrid ) lrid += 1;\n\t}\n\treturn completed ? 0 : -1;\n}\n\n// END:RSI\n\n/**\n  * Initializations for which static initialization can't/shouldn't \n  * be relied upon. Common to executable and Python extension.\n  */\nstatic void _jit_initialization( void ) {\n\topt_na_regex = mtm_default_NA_regex;\n\tmemset( &_matrix,  0, sizeof(struct mtm_matrix) );\n\tgsl_set_error_handler( _error_handler );\n}\n\n\n/***************************************************************************\n  * Online help\n  */\n\nstatic const char *_YN( bool y ) {\n\treturn y ? \"yes\" : \"no\";\n}\n\n#define USAGE_SHORT false\n#define USAGE_LONG  true\n\nstatic void _print_usage( const char *exename, FILE *fp, bool exhaustive ) {\n\n\textern const char *USAGE_UNABRIDGED;\n\textern const char *USAGE_ABRIDGED;\n\n\tchar debug_state[64];\n\tdebug_state[0] = 0;\n#ifdef _DEBUG\n\tsprintf( debug_state, \"(DEBUG) Compiled %s %s\", __DATE__,__TIME__ );\n#endif\n\n\tif( exhaustive )\n\t\tfprintf( fp, USAGE_UNABRIDGED,\n\t\t\texename, VER_MAJOR, VER_MINOR, VER_PATCH, VER_TAG, debug_state,\n\t\t\texename,\n\t\t\texename,\n\t\t\tTYPE_PARSER_INFER,\n\t\t\topt_na_regex,\n#ifdef HAVE_LUA\n\t\t\tDEFAULT_COROUTINE,\n#endif\n\t\t\targ_min_cell_count,\n\t\t\targ_min_mixb_count,\n\t\t\targ_min_sample_count,\n\n\t\t\topt_p_value,\n\t\t\topt_status_mask,\n\t\t\topt_format,\n\t\t\tMAGIC_FORMAT_ID_STD, MAGIC_FORMAT_ID_TCGA,\n\t\t\t_YN(opt_warnings_are_fatal),\n\t\t\topt_verbosity,\n\t\t\tMAGIC_SUFFIX,\n\t\t\tMAX_CATEGORY_COUNT,\n\t\t\tMTM_MAX_MISSING_VALUES,\n\t\t\tAUTHOR_EMAIL );\n\telse\n\t\tfprintf( fp, USAGE_ABRIDGED,\n\t\t\texename, VER_MAJOR, VER_MINOR, VER_PATCH, VER_TAG, debug_state,\n\t\t\texename,\n\t\t\topt_p_value,\n\t\t  \tAUTHOR_EMAIL );\n}\n\n\nint main( int argc, char *argv[] ) {\n\n\tint exit_status = EXIT_SUCCESS;\n\n\tconst char *i_file = NULL;\n\tconst char *o_file = NULL;\n\tFILE *fp           = NULL;\n\n\tif( argc < 2 ) { // absolute minimum args: <executable name> <input matrix>\n\t\t_print_usage( argv[0], stdout, USAGE_SHORT );\n\t\texit( EXIT_SUCCESS );\n\t}\n\n\t_jit_initialization();\n\n\tdo {\n\n\t\tstatic const char *CHAR_OPTIONS\n#ifdef HAVE_LUA\n\t\t\t= \"s:hrt:N:C:P:n:x:c:DM:p:f:q:v:?X\";\n#else\n\t\t\t= \"hrt:N:C:P:n:x:DM:p:f:q:v:?X\";\n#endif\n\n\t\tstatic struct option LONG_OPTIONS[] = {\n#ifdef HAVE_LUA\n\t\t\t{\"script\",        required_argument,  0,'s'},\n#endif\n\t\t\t{\"no-header\",     no_argument,        0,'h'},\n\t\t\t{\"no-row-labels\", no_argument,        0,'r'},\n\t\t\t{\"type-parser\",   required_argument,  0,'t'},\n\t\t\t{\"na-regex\",      required_argument,  0,'N'},\n\n\t\t\t{\"crossprod\",     required_argument,  0,'C'},\n\t\t\t{\"pair\",          required_argument,  0,'P'},\n\t\t\t{\"by-name\",       required_argument,  0,'n'},\n\t\t\t{\"by-index\",      required_argument,  0,'x'},\n#ifdef HAVE_LUA\n\t\t\t{\"coroutine\",     required_argument,  0,'c'},\n#endif\n\t\t\t{\"dry-run\",       no_argument,        0,'D'},\n\n\t\t\t{\"min-ct-cell\",   required_argument,  0, 256 }, // no short equivalents\n\t\t\t{\"min-mx-cell\",   required_argument,  0, 257 }, // no short equivalents\n\t\t\t{\"min-samples\",   required_argument,  0,'M'},\n\n\t\t\t{\"p-value\",       required_argument,  0,'p'},\n\t\t\t{\"format\",        required_argument,  0,'f'},\n\t\t\t{\"fdr\",           required_argument,  0,'q'},\n\t\t\t{\"verbosity\",     required_argument,  0,'v'},\n#ifdef _DEBUG\n\t\t\t{\"debug\",         required_argument,  0, 258 }, // no short equivalents\n#endif\n\t\t\t{\"help\",          no_argument,        0,'?'},\n\t\t\t{ NULL,           0,                  0, 0 }\n\t\t};\n\n\t\tint arg_index = 0;\n\t\tconst int c\n\t\t\t= getopt_long( argc, argv, CHAR_OPTIONS, LONG_OPTIONS, &arg_index );\n\n\t\tswitch (c) {\n\n\t\tcase 's': // script\n\t\t\topt_script      = optarg;\n\t\t\tbreak;\n\t\tcase 'h': // no-header\n\t\t\topt_header      = false;\n\t\t\tbreak;\n\t\tcase 'r': // no-row-labels\n\t\t\topt_row_labels  = false;\n\t\t\tbreak;\n\t\tcase 't': // type-parser\n\t\t\topt_type_parser = optarg;\n\t\t\tbreak;\n\t\tcase 'N': // na-regex\n\t\t\topt_na_regex    = optarg;\n\t\t\tbreak;\n\t\tcase 'C': // cross-product of matrices\n\t\t\topt_preproc_matrix = optarg;\n\t\t\tbreak;\n\t\tcase 'P': // pair\n\t\t\topt_single_pair = optarg;\n\t\t\tbreak;\n\t\tcase 'n': // by-name\n\t\t\topt_pairlist_source = optarg;\n\t\t\topt_by_name         = true;\n\t\t\tbreak;\n\t\tcase 'x': // by-index\n\t\t\topt_pairlist_source = optarg;\n\t\t\topt_by_name         = false;\n\t\t\tbreak;\n\t\tcase 'c': // coroutine\n\t\t\topt_coroutine       = optarg;\n\t\t\tbreak;\n\t\tcase 'D': // dry-run\n\t\t\topt_dry_run         = true;\n\t\t\tbreak;\n\n\t\t////////////////////////////////////////////////////////////////////\n\t\tcase 256: // ...because I haven't defined a short form for this\n\t\t\targ_min_cell_count = atoi( optarg );\n\t\t\tbreak;\n\n\t\tcase 257: // ...because I haven't defined a short form for this\n\t\t\targ_min_mixb_count = atoi( optarg );\n\t\t\tbreak;\n\n\t\tcase 'M':\n\t\t\targ_min_sample_count = atoi( optarg );\n\t\t\tif( arg_min_sample_count < 2 ) {\n\t\t\t\twarnx( \"Seriously...%d samples is acceptable?\\n\"\n\t\t\t\t\t\"I don't think so... ;)\\n\",\n\t\t\t\t\targ_min_sample_count );\n\t\t\t\texit( EXIT_FAILURE );\n\t\t\t}\n\t\t\tbreak;\n\t\t////////////////////////////////////////////////////////////////////\n\n\t\tcase 'p':\n\t\t\topt_p_value = atof( optarg );\n\t\t\tif( ! ( 0 < opt_p_value ) ) {\n\t\t\t\twarnx( \"specified p-value %.3f will preclude all output.\\n\",\n\t\t\t\t\topt_p_value );\n\t\t\t\tabort();\n\t\t\t} else\n\t\t\tif( ! ( opt_p_value < 1.0 ) ) {\n\t\t\t\twarnx( \"p-value %.3f will filter nothing.\\n\"\n\t\t\t\t\t\"\\tIs this really what you want?\\n\",\n\t\t\t\t\topt_p_value );\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase 'J': // JSON format\n\t\tcase 'f': // tabular format\n\t\t\t// Check for magic-value strings first\n\t\t\tif( strcmp( MAGIC_FORMAT_ID_STD, optarg ) == 0 )\n\t\t\t\t_emit = format_standard;\n\t\t\telse\n\t\t\tif( strcmp( MAGIC_FORMAT_ID_TCGA, optarg ) == 0 )\n\t\t\t\t_emit = format_tcga;\n\t\t\telse {\n\t\t\t\tconst char *specifier\n\t\t\t\t\t= emit_config( optarg, c=='J' ? FORMAT_JSON : FORMAT_TABULAR );\n\t\t\t\tif( specifier ) {\n\t\t\t\t\terrx( -1, \"invalid specifier \\\"%s\\\"\", specifier );\n\t\t\t\t}\n\t\t\t\t_emit = emit_exec;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase 'q':\n\t\t\targ_q_value = atof( optarg );\n\t\t\t_analyze = _fdr_cache;\n\t\t\tbreak;\n\n\t\tcase 'v': // verbosity\n\t\t\topt_verbosity = atoi( optarg );\n\t\t\tbreak;\n\n\t\tcase '?': // help\n\t\t\t_print_usage( argv[0], stdout, USAGE_SHORT );\n\t\t\texit( EXIT_SUCCESS );\n\t\t\tbreak;\n\n\t\tcase 'X': // help\n\t\t\t_print_usage( argv[0], stdout, USAGE_LONG );\n\t\t\texit( EXIT_SUCCESS );\n\t\t\tbreak;\n\n#ifdef _DEBUG\n\t\tcase 258:\n\t\t\tif( strchr( optarg, 'X' ) != NULL ) {\n\t\t\t\t// Turn OFF all filtering to turn on \"exhaustive\"\n\t\t\t\t// output mode.\n\t\t\t\topt_status_mask = 0;\n\t\t\t\topt_p_value     = 1.0;\n\t\t\t}\n\t\t\tdbg_silent     = strchr( optarg, 'S' ) != NULL;\n\t\t\tbreak;\n#endif\n\t\tcase -1: // ...signals no more options.\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tprintf (\"error: unknown option: %c\\n\", c );\n\t\t\texit( EXIT_FAILURE );\n\t\t}\n\t\tif( -1 == c ) break;\n\n\t} while( true );\n\n#ifdef HAVE_LUA\n\n\tif( opt_script ) {\n\n\t\t/**\n\t\t  * Create a Lua state machine and load/run the Lua script from file\n\t\t  * or command line before anything else.\n\t\t  */\n\n\t\t_L = luaL_newstate();\n\t\tif( _L ) {\n\t\t\tatexit( _freeLua ); // ...so lua_close needed NOWHERE else.\n\t\t\tluaL_openlibs( _L );\n\t\t\tif( _load_script( opt_script, _L ) != LUA_OK ) {\n\t\t\t\terrx( -1, \"in \\\"%s\\\": %s\",\n\t\t\t\t\topt_script, lua_tostring( _L,-1) );\n\t\t\t}\n\t\t} else\n\t\t\terrx( -1, \"failed creating Lua statespace\" );\n\n\t\t/**\n\t\t  * Fail early!\n\t\t  * If the user provided a coroutine name, check for its presence.\n\t\t  * Otherwise, see if the default coroutine is present.\n\t\t  * Otherwise, Lua is not being used to generate pairs.\n\t\t  */\n\n\t\tif( opt_coroutine ) {\n\n\t\t\tlua_getglobal( _L, opt_coroutine );\n\t\t\tif( lua_isnil( _L, -1 ) ) {\n\t\t\t\terrx( -1, \"pair generator coroutine \\\"%s\\\" not defined in \\\"%s\\\"\",\n\t\t\t\t\topt_coroutine, opt_script );\n\t\t\t}\n\n\t\t} else {\n\n\t\t\tlua_getglobal( _L, DEFAULT_COROUTINE );\n\n\t\t\tif( ! lua_isnil( _L, -1 ) )\n\t\t\t\topt_coroutine = DEFAULT_COROUTINE;\n\n\t\t\t// Non-existence of DEFAULT_COROUTINE is not an error;\n\t\t\t// we assume user does NOT intend Lua to generate the pairs.\n\t\t}\n\n\t\tlua_pop( _L, 1 ); // clean the stack\n\n\t\t/**\n\t\t  * Similarly verify NOW that the a specified type parser is present.\n\t\t  */\n\t\tif( opt_type_parser ) {\n\t\t\tlua_getglobal( _L, opt_type_parser );\n\t\t\tif( lua_isnil( _L, -1 ) ) {\n\t\t\t\terrx( -1, \"pair generator coroutine \\\"%s\\\" not defined in \\\"%s\\\"\",\n\t\t\t\t\topt_type_parser, opt_script );\n\t\t\t}\n\t\t\tlua_pop( _L, 1 ); // clean the stack\n\t\t}\n\n\t\t/**\n\t\t  * Load Lua script and execute a dry-run if applicable.\n\t\t  * This is in advance of other argument validation since other\n\t\t  * arguments will be ignored...\n\t\t  */\n\n\t\tif( opt_dry_run && opt_coroutine != NULL ) {\n\n\t\t\tconst int COUNT\n\t\t\t\t= getenv(\"DRY_RUN_COUNT\")\n\t\t\t\t? atoi( getenv(\"DRY_RUN_COUNT\") )\n\t\t\t\t: 8;\n\n\t\t\tint isnum, lua_status = LUA_YIELD;\n\n\t\t\tlua_getglobal( _L, opt_coroutine );\n\t\t\tif( lua_isnil( _L, -1 ) )\n\t\t\t\terrx( -1, \"%s not defined (in Lua's global namespace)\",\n\t\t\t\t\topt_coroutine );\n\n\t\t\twhile( lua_status == LUA_YIELD ) {\n\t\t\t\tlua_pushnumber( _L, COUNT );\n\t\t\t\tlua_status = lua_resume( _L, NULL, 1 );\n\t\t\t\tif( lua_status <= LUA_YIELD /* OK == 0, YIELD == 1*/ ) {\n\t\t\t\t\t// Only output coroutine.yield'ed values...\n\t\t\t\t\tif( lua_status == LUA_YIELD ) {\n\t\t\t\t\t\tconst int b = lua_tonumberx( _L, -1, &isnum );\n\t\t\t\t\t\tconst int a = lua_tonumberx( _L, -2, &isnum );\n\t\t\t\t\t\tlua_pop( _L, 2 );\n\t\t\t\t\t\tfprintf( stdout, \"%d %d\\n\", a, b );\n\t\t\t\t\t}\n\t\t\t\t} else\n\t\t\t\t\tfputs( lua_tostring( _L, -1 ), stderr );\n\t\t\t}\n\n\t\t\texit( EXIT_SUCCESS );\n\t\t}\n\t} else\n\tif( opt_coroutine ) {\n\t\terrx( -1, \"coroutine specified (\\\"%s\\\") but no script\", opt_coroutine );\n\t}\n\n#endif\n\n\t/**\n\t  * Catch simple argument inconsistencies and fail early!\n\t  */\n\n\tif( opt_single_pair ) {\n\t\tif( USE_FDR_CONTROL ) {\n\t\t\twarnx( \"FDR is senseless on a single pair.\\n\" );\n\t\t\tif( opt_warnings_are_fatal )\n\t\t\t\tabort();\n\t\t\telse\n\t\t\t\targ_q_value = 0.0;\n\t\t}\n\t}\n\n\t/**\n\t  * The last two positional arguments are expected to be filenames\n\t  * ... <filename1>\n\t  */\n\n\tstatic const char *NAME_STDIN  = \"stdin\";\n\tstatic const char *NAME_STDOUT = \"stdout\";\n\n\tswitch( argc - optind ) {\n\n\tcase 0: // input MUST be stdin, output stdout\n\t\ti_file = NAME_STDIN;\n\t\to_file = NAME_STDOUT;\n\t\tbreak;\n\n\tcase 1:\n\t\tif( access( argv[ optind ], R_OK ) == 0 ) {\n\t\t\ti_file = argv[ optind++ ];\n\t\t\to_file = NAME_STDOUT;\n\t\t} else {\n\t\t\ti_file = NAME_STDIN;\n\t\t\to_file = argv[ optind++ ];\n\t\t}\n\t\tbreak;\n\n\tcase 2:\n\tdefault:\n\t\ti_file = argv[ optind++ ];\n\t\to_file = argv[ optind++ ];\n\t\tif( (argc-optind) > 0 && opt_verbosity >= V_ESSENTIAL ) {\n\t\t\t// This behavior of ignoring \"extra\" arguments is implemented\n\t\t\t// ONLY so that this executable plays nicely with a job control\n\t\t\t// system which uses extra command line args NOT intended for\n\t\t\t// the executable. TODO: Revisit this!\n\t\t\tfprintf( stderr,\n\t\t\t\t\"warning: ignoring %d trailing positional arguments.\\n\", argc-optind );\n\t\t\twhile( optind < argc )\n\t\t\t\tfprintf( stderr, \"\\t\\\"%s\\\"\\n\", argv[optind++] );\n\t\t\tif( opt_warnings_are_fatal )\n\t\t\t\texit( EXIT_FAILURE );\n\t\t}\n\t}\n\n\tif( opt_pairlist_source != NULL\n\t\t\t&& strcmp( opt_pairlist_source, i_file ) == 0 ) {\n\t\terrx( -1, \"error: stdin specified (or implied) for both pair list and the input matrix\\n\" );\n\t}\n\n\t/**\n\t  * Emit intentions...\n\t  */\n\n\tif( opt_verbosity >= V_INFO ) {\n\n#define MAXLEN_FS 75\n\n\t\tchar feature_selection[MAXLEN_FS+1];\n\t\tfeature_selection[MAXLEN_FS] = 0; // insure NUL termination\n\n\t\t/**\n\t\t  * Following conditional cascade must exactly match the larger\n\t\t  * one below in order to accurately report feature selection method.\n\t\t  */\n\t\tif( opt_single_pair ) {\n\t\t\tstrncpy( feature_selection, opt_single_pair, MAXLEN_FS );\n\t\t} else\n\t\tif( opt_pairlist_source ) {\n\t\t\tsnprintf( feature_selection,\n\t\t\t\tMAXLEN_FS,\n\t\t\t\t\"by %s in %s\",\n\t\t\t\topt_by_name ? \"name\" : \"offset\", opt_pairlist_source );\n\t\t} else {\n#ifdef HAVE_LUA\n\t\t\tif( opt_coroutine )\n\t\t\t\tsnprintf( feature_selection,\n\t\t\t\t\tMAXLEN_FS,\n\t\t\t\t\t\"%s in %s\",\n\t\t\t\t\topt_coroutine, opt_script /* may be literal source */ );\n\t\t\telse\n#endif\n\t\t\t\tstrncpy( feature_selection, \"all-pairs\", MAXLEN_FS );\n\t\t}\n\n\t\tfprintf( stderr,\n\t\t\t\"       input: %s\\n\"\n\t\t\t\"      select: %s\\n\"\n\t\t\t\"      output: %s\\n\"\n#ifdef _DEBUG\n\t\t\t\"       debug: silent: %s\\n\"\n#endif\n\t\t\t,i_file,\n\t\t\tfeature_selection,\n\t\t\to_file\n#ifdef _DEBUG\n\t\t\t, _YN( dbg_silent )\n#endif\n\t\t\t);\n\t}\n\n\t/**\n\t  * Load the input matrix.\n\t  */\n\n\tfp = strcmp( i_file, NAME_STDIN )\n\t\t? fopen( i_file, \"r\" )\n\t\t: stdin;\n\tif( fp ) {\n\n\t\tconst unsigned int FLAGS\n\t\t\t= ( opt_header ? MTM_MATRIX_HAS_HEADER : 0 )\n\t\t\t| ( opt_row_labels ? MTM_MATRIX_HAS_ROW_NAMES : 0 )\n\t\t\t| ( opt_verbosity & MTM_VERBOSITY_MASK);\n\n\t\tconst int econd\n\t\t\t= mtm_parse( fp,\n\t\t\t\tFLAGS,\n\t\t\t\topt_na_regex,\n\t\t\t\tMAX_CATEGORY_COUNT,\n\t\t\t\topt_row_labels ? _interpret_row_label : NULL,\n\t\t\t\tNULL, // ...since no persistent binary matrix is needed.\n\t\t\t\t&_matrix );\n\t\tfclose( fp );\n\n\t\tif( econd )\n\t\t\terrx( -1, \"mtm_parse returned (%d)\", econd );\n\t\telse\n\t\t\tatexit( _freeMatrix );\n\t}\n\n\tif( opt_dry_run ) { // a second possible\n\t\texit( EXIT_SUCCESS );\n\t}\n\n\tif( SIG_ERR == signal( SIGINT, _interrupt ) ) {\n\t\twarn( \"failed installing interrupt handler\\n\"\n\t\t\t\"\\tCtrl-C will terminated gracelessly\\n\" );\n\t}\n\n\t/**\n\t  * Choose and open, if necessary, an output stream.\n\t  */\n\n\t_fp_output\n\t\t= (strcmp( o_file, NAME_STDOUT ) == 0 )\n\t\t? stdout\n\t\t: fopen( o_file, \"w\" );\n\n\tif( NULL == _fp_output ) {\n\t\terr( -1, \"opening output file \\\"%s\\\"\", o_file );\n\t}\n\n\tif( covan_init( _matrix.columns ) ) {\n\t\terr( -1, \"error: covan_init(%d)\\n\", _matrix.columns );\n\t} else\n\t\tatexit( covan_fini );\n\n\tif( opt_verbosity >= V_INFO )\n\t\tfprintf( _fp_output, \"# %d rows/features X %d columns/samples\\n\", _matrix.rows, _matrix.columns );\n\n\tif( USE_FDR_CONTROL ) {\n\t\t_fdr_cache_fp = tmpfile();\n\t\t_fdr_uncached_count = 0;\n\t\tif( NULL == _fdr_cache_fp )\n\t\t\terr( -1, \"creating a temporary file\" );\n\t}\n\n\t/**\n\t  * Here the main decision is made regarding feature selection.\n\t  * In order of precedence:\n\t  * 0. cross-product of matrices\n\t  * 1. single pair\n\t  * 2. explicit pairs (by name or by offset)\n\t  * 3. Lua-generated offsets\n\t  * 4. all-pairs\n\t  */\n\n\tif( opt_preproc_matrix ) {\n\t\tFILE *ppm[2];\n\t\tppm[0] = fopen( opt_preproc_matrix, \"r\" );\n\t\tif( ppm[0] ) {\n\n\t\t\tstruct mtm_matrix_header hdr;\n\n\t\t\t/**\n\t\t\t  * Open a second stream on the file to access the\n\t\t\t  * descriptor table.\n\t\t\t  */\n\t\t\tppm[1] = fopen( opt_preproc_matrix, \"r\" );\n\t\t\t\n\t\t\t/**\n\t\t\t  * Read the header and verify compatibility\n\t\t\t  */\n\n\t\t\tif( mtm_load_header( ppm[0], &hdr ) != MTM_OK )\n\t\t\t\terr( -1, \"failed reading preprocessed matrix' (%s) header\",\n\t\t\t\t\topt_preproc_matrix );\n\n\t\t\t// Verify file is the preprocessed matrix the user thinks it is.\n\n\t\t\tif( strcmp( hdr.sig, MTM_SIGNATURE ) )\n\t\t\t\terrx( -1, \"%s has wrong signature.\"\n\t\t\t\t\t\"Are you sure this is a preprocessed matrix\",\n\t\t\t\t\topt_preproc_matrix );\n\n\t\t\t// Verify equality of columns\n\n\t\t\tif( _matrix.columns != hdr.columns )\n\t\t\t\terrx( -1, \"processed matrix has %d columns; other has %d\",\n\t\t\t\t\thdr.columns, _matrix.columns );\n\n\t\t\t// Skip past the header to the row data.\n\n\t\t\tif( fseek( ppm[0], hdr.section[ S_DATA ].offset, SEEK_SET ) )\n\t\t\t\terr( -1, \"failed seeking to start of data\" );\n\n\t\t\t// Skip to the descriptor table in the 2nd stream.\n\n\t\t\tif( fseek( ppm[1], hdr.section[ S_DESC ].offset, SEEK_SET ) )\n\t\t\t\terr( -1, \"failed seeking to start of data\" );\n\n\t\t\t_analyze_cross_product( &hdr, ppm );\n\n\t\t\tfclose( ppm[1] );\n\t\t\tfclose( ppm[0] );\n\t\t}\n\t} else\n\tif( opt_single_pair ) {\n\n\t\t_analyze_single_pair( opt_single_pair, opt_row_labels );\n\n\t} else\n\tif( opt_pairlist_source ) {\n\n\t\tFILE *fp\n\t\t\t= strcmp(opt_pairlist_source,NAME_STDIN)\n\t\t\t? fopen( opt_pairlist_source, \"r\" )\n\t\t\t: stdin;\n\t\n\t\tif( opt_by_name ) {\t\n\t\t\tif( mtm_resort_rowmap( &_matrix, MTM_RESORT_LEXIGRAPHIC ) )\n\t\t\t\terrx( -1, NO_ROW_LABELS );\n\t\t}\n\n\t\tif( fp ) {\n\t\t\tconst int econd\n\t\t\t\t= opt_by_name\n\t\t\t\t? _analyze_named_pair_list( fp )\n\t\t\t\t: _analyze_pair_list( fp );\n\t\t\tif( econd )\n\t\t\t\twarn( \"error (%d) analyzing%s pair list\",\n\t\t\t\t\tecond, opt_by_name ? \" named\" : \"\" );\n\t\t\tfclose( fp );\n\t\t} else\n\t\t\twarn( \"opening \\\"%s\\\"\", opt_pairlist_source );\n\n\t} else {\n\n#ifdef HAVE_LUA\n\t\tif( opt_coroutine )\n\t\t\t_analyze_generated_pair_list( _L );\n\t\telse\n#endif\n\t\t\t_analyze_all_pairs();\n\t}\n\n\t// Post process results if FDR is in effect and the 1st pass was\n\t// allowed to complete. (Post-processing involves a repetition of\n\t// analysis FOR A SUBSET of the original input.)\n\n\tif( USE_FDR_CONTROL && (! _sigint_received) ) {\n\t\t_fdr_postprocess( _fdr_cache_fp, arg_q_value, _fp_output, opt_preproc_matrix != NULL );\n\t} else\n\tif( opt_verbosity >= V_ESSENTIAL ) {\n\t\tfprintf( _fp_output, \n\t\t\t\t\"# %d filtered for insignificance\\n\"\n\t\t\t\t\"# %d filtered for some sort of degeneracy\\n\", \n\t\t\t\t_insignificant,\n\t\t\t\t_untested );\n\t\t// ...which does not apply in FDR control context.\n\t}\n\n\tif( _fdr_cache_fp )\n\t\tfclose( _fdr_cache_fp );\n\n\tif( _fp_output )\n\t\tfclose( _fp_output );\n\n\treturn exit_status;\n}\n\n", "meta": {"hexsha": "4c89045c41c040fa4aa947590dee69dd03f19900", "size": 39299, "ext": "c", "lang": "C", "max_stars_repo_path": "pairwise/src/main.c", "max_stars_repo_name": "IlyaLab/kramtools", "max_stars_repo_head_hexsha": "987eb145f1f99378fcf24d4f89664e986e7c2a81", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-30T03:07:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-30T03:07:45.000Z", "max_issues_repo_path": "pairwise/src/main.c", "max_issues_repo_name": "IlyaLab/kramtools", "max_issues_repo_head_hexsha": "987eb145f1f99378fcf24d4f89664e986e7c2a81", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pairwise/src/main.c", "max_forks_repo_name": "IlyaLab/kramtools", "max_forks_repo_head_hexsha": "987eb145f1f99378fcf24d4f89664e986e7c2a81", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1122923588, "max_line_length": 109, "alphanum_fraction": 0.636377516, "num_tokens": 11341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3886180267058489, "lm_q2_score": 0.032589742534481866, "lm_q1q2_score": 0.012664961434602013}}
{"text": "// Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at\n// the Lawrence Livermore National Laboratory. LLNL-CODE-734707. All Rights\n// reserved. See files LICENSE and NOTICE for details.\n//\n// This file is part of CEED, a collection of benchmarks, miniapps, software\n// libraries and APIs for efficient high-order finite element and spectral\n// element discretizations for exascale applications. For more information and\n// source code availability see http://github.com/ceed.\n//\n// The CEED research is supported by the Exascale Computing Project 17-SC-20-SC,\n// a collaborative effort of two U.S. Department of Energy organizations (Office\n// of Science and the National Nuclear Security Administration) responsible for\n// the planning and preparation of a capable exascale ecosystem, including\n// software, applications, hardware, advanced system engineering and early\n// testbed platforms, in support of the nation's exascale computing imperative.\n\n#ifndef setup_h\n#define setup_h\n\n#include <stdbool.h>\n#include <string.h>\n#include <petsc.h>\n#include <petscdmplex.h>\n#include <petscfe.h>\n#include <ceed.h>\n#include \"qfunctions/bps/common.h\"\n#include \"qfunctions/bps/bp1.h\"\n#include \"qfunctions/bps/bp2.h\"\n#include \"qfunctions/bps/bp3.h\"\n#include \"qfunctions/bps/bp4.h\"\n\n// -----------------------------------------------------------------------------\n// PETSc Operator Structs\n// -----------------------------------------------------------------------------\n\n// Data for PETSc Matshell\ntypedef struct UserO_ *UserO;\nstruct UserO_ {\n  MPI_Comm comm;\n  DM dm;\n  Vec Xloc, Yloc, diag;\n  CeedVector xceed, yceed;\n  CeedOperator op;\n  Ceed ceed;\n};\n\n// Data for PETSc Interp/Restrict Matshells\ntypedef struct UserIR_ *UserIR;\nstruct UserIR_ {\n  MPI_Comm comm;\n  DM dmc, dmf;\n  Vec Xloc, Yloc, mult;\n  CeedVector ceedvecc, ceedvecf;\n  CeedOperator op;\n  Ceed ceed;\n};\n\n// -----------------------------------------------------------------------------\n// libCEED Data Struct\n// -----------------------------------------------------------------------------\n\n// libCEED data struct for level\ntypedef struct CeedData_ *CeedData;\nstruct CeedData_ {\n  Ceed ceed;\n  CeedBasis basisx, basisu, basisctof;\n  CeedElemRestriction Erestrictx, Erestrictu, Erestrictxi, Erestrictui,\n                      Erestrictqdi;\n  CeedQFunction qf_apply;\n  CeedOperator op_apply, op_restrict, op_interp;\n  CeedVector qdata, xceed, yceed;\n};\n\n// -----------------------------------------------------------------------------\n// Command Line Options\n// -----------------------------------------------------------------------------\n\n// Coarsening options\ntypedef enum {\n  COARSEN_UNIFORM = 0, COARSEN_LOGARITHMIC = 1\n} coarsenType;\nstatic const char *const coarsenTypes [] = {\"uniform\",\"logarithmic\",\n                                            \"coarsenType\",\"COARSEN\",0\n                                           };\n\n// -----------------------------------------------------------------------------\n// Boundary Conditions\n// -----------------------------------------------------------------------------\n\n// Diff boundary condition function\nPetscErrorCode BCsDiff(PetscInt dim, PetscReal time, const PetscReal x[],\n                       PetscInt ncompu, PetscScalar *u, void *ctx) {\n  // *INDENT-OFF*\n  #ifndef M_PI\n  #define M_PI    3.14159265358979323846\n  #endif\n  // *INDENT-ON*\n  const CeedScalar c[3] = { 0, 1., 2. };\n  const CeedScalar k[3] = { 1., 2., 3. };\n\n  PetscFunctionBeginUser;\n\n  for (PetscInt i = 0; i < ncompu; i++)\n    u[i] = sin(M_PI*(c[0] + k[0]*x[0])) *\n           sin(M_PI*(c[1] + k[1]*x[1])) *\n           sin(M_PI*(c[2] + k[2]*x[2]));\n\n  PetscFunctionReturn(0);\n}\n\n// Mass boundary condition function\nPetscErrorCode BCsMass(PetscInt dim, PetscReal time, const PetscReal x[],\n                       PetscInt ncompu, PetscScalar *u, void *ctx) {\n  PetscFunctionBeginUser;\n\n  for (PetscInt i = 0; i < ncompu; i++)\n    u[i] = PetscSqrtScalar(PetscSqr(x[0]) + PetscSqr(x[1]) +\n                           PetscSqr(x[2]));\n\n  PetscFunctionReturn(0);\n}\n\n// Create BC label\nstatic PetscErrorCode CreateBCLabel(DM dm, const char name[]) {\n  int ierr;\n  DMLabel label;\n\n  PetscFunctionBeginUser;\n\n  ierr = DMCreateLabel(dm, name); CHKERRQ(ierr);\n  ierr = DMGetLabel(dm, name, &label); CHKERRQ(ierr);\n  ierr = DMPlexMarkBoundaryFaces(dm, 1, label); CHKERRQ(ierr);\n  ierr = DMPlexLabelComplete(dm, label); CHKERRQ(ierr);\n\n  PetscFunctionReturn(0);\n}\n\n// -----------------------------------------------------------------------------\n// BP Option Data\n// -----------------------------------------------------------------------------\n\n// BP options\ntypedef enum {\n  CEED_BP1 = 0, CEED_BP2 = 1, CEED_BP3 = 2,\n  CEED_BP4 = 3, CEED_BP5 = 4, CEED_BP6 = 5\n} bpType;\nstatic const char *const bpTypes[] = {\"bp1\",\"bp2\",\"bp3\",\"bp4\",\"bp5\",\"bp6\",\n                                      \"bpType\",\"CEED_BP\",0\n                                     };\n\n// BP specific data\ntypedef struct {\n  CeedInt ncompu, qdatasize, qextra;\n  CeedQFunctionUser setupgeo, setuprhs, apply, error;\n  const char *setupgeofname, *setuprhsfname, *applyfname, *errorfname;\n  CeedEvalMode inmode, outmode;\n  CeedQuadMode qmode;\n  PetscBool enforce_bc;\n  PetscErrorCode (*bcs_func)(PetscInt, PetscReal, const PetscReal *,\n                             PetscInt, PetscScalar *, void *);\n} bpData;\n\nbpData bpOptions[6] = {\n  [CEED_BP1] = {\n    .ncompu = 1,\n    .qdatasize = 1,\n    .qextra = 1,\n    .setupgeo = SetupMassGeo,\n    .setuprhs = SetupMassRhs,\n    .apply = Mass,\n    .error = Error,\n    .setupgeofname = SetupMassGeo_loc,\n    .setuprhsfname = SetupMassRhs_loc,\n    .applyfname = Mass_loc,\n    .errorfname = Error_loc,\n    .inmode = CEED_EVAL_INTERP,\n    .outmode = CEED_EVAL_INTERP,\n    .qmode = CEED_GAUSS,\n    .enforce_bc = false,\n    .bcs_func = BCsMass\n  },\n  [CEED_BP2] = {\n    .ncompu = 3,\n    .qdatasize = 1,\n    .qextra = 1,\n    .setupgeo = SetupMassGeo,\n    .setuprhs = SetupMassRhs3,\n    .apply = Mass3,\n    .error = Error3,\n    .setupgeofname = SetupMassGeo_loc,\n    .setuprhsfname = SetupMassRhs3_loc,\n    .applyfname = Mass3_loc,\n    .errorfname = Error3_loc,\n    .inmode = CEED_EVAL_INTERP,\n    .outmode = CEED_EVAL_INTERP,\n    .qmode = CEED_GAUSS,\n    .enforce_bc = false,\n    .bcs_func = BCsMass\n  },\n  [CEED_BP3] = {\n    .ncompu = 1,\n    .qdatasize = 6,\n    .qextra = 1,\n    .setupgeo = SetupDiffGeo,\n    .setuprhs = SetupDiffRhs,\n    .apply = Diff,\n    .error = Error,\n    .setupgeofname = SetupDiffGeo_loc,\n    .setuprhsfname = SetupDiffRhs_loc,\n    .applyfname = Diff_loc,\n    .errorfname = Error_loc,\n    .inmode = CEED_EVAL_GRAD,\n    .outmode = CEED_EVAL_GRAD,\n    .qmode = CEED_GAUSS,\n    .enforce_bc = true,\n    .bcs_func = BCsDiff\n  },\n  [CEED_BP4] = {\n    .ncompu = 3,\n    .qdatasize = 6,\n    .qextra = 1,\n    .setupgeo = SetupDiffGeo,\n    .setuprhs = SetupDiffRhs3,\n    .apply = Diff3,\n    .error = Error3,\n    .setupgeofname = SetupDiffGeo_loc,\n    .setuprhsfname = SetupDiffRhs3_loc,\n    .applyfname = Diff_loc,\n    .errorfname = Error3_loc,\n    .inmode = CEED_EVAL_GRAD,\n    .outmode = CEED_EVAL_GRAD,\n    .qmode = CEED_GAUSS,\n    .enforce_bc = true,\n    .bcs_func = BCsDiff\n  },\n  [CEED_BP5] = {\n    .ncompu = 1,\n    .qdatasize = 6,\n    .qextra = 0,\n    .setupgeo = SetupDiffGeo,\n    .setuprhs = SetupDiffRhs,\n    .apply = Diff,\n    .error = Error,\n    .setupgeofname = SetupDiffGeo_loc,\n    .setuprhsfname = SetupDiffRhs_loc,\n    .applyfname = Diff_loc,\n    .errorfname = Error_loc,\n    .inmode = CEED_EVAL_GRAD,\n    .outmode = CEED_EVAL_GRAD,\n    .qmode = CEED_GAUSS_LOBATTO,\n    .enforce_bc = true,\n    .bcs_func = BCsDiff\n  },\n  [CEED_BP6] = {\n    .ncompu = 3,\n    .qdatasize = 6,\n    .qextra = 0,\n    .setupgeo = SetupDiffGeo,\n    .setuprhs = SetupDiffRhs3,\n    .apply = Diff3,\n    .error = Error3,\n    .setupgeofname = SetupDiffGeo_loc,\n    .setuprhsfname = SetupDiffRhs3_loc,\n    .applyfname = Diff_loc,\n    .errorfname = Error3_loc,\n    .inmode = CEED_EVAL_GRAD,\n    .outmode = CEED_EVAL_GRAD,\n    .qmode = CEED_GAUSS_LOBATTO,\n    .enforce_bc = true,\n    .bcs_func = BCsDiff\n  }\n};\n\n// -----------------------------------------------------------------------------\n// PETSc FE Boilerplate\n// -----------------------------------------------------------------------------\n\n// Create FE by degree\nstatic int PetscFECreateByDegree(DM dm, PetscInt dim, PetscInt Nc,\n                                 PetscBool isSimplex, const char prefix[],\n                                 PetscInt order, PetscFE *fem) {\n  PetscQuadrature q, fq;\n  DM              K;\n  PetscSpace      P;\n  PetscDualSpace  Q;\n  PetscInt        quadPointsPerEdge;\n  PetscBool       tensor = isSimplex ? PETSC_FALSE : PETSC_TRUE;\n  PetscErrorCode  ierr;\n\n  PetscFunctionBeginUser;\n  /* Create space */\n  ierr = PetscSpaceCreate(PetscObjectComm((PetscObject) dm), &P); CHKERRQ(ierr);\n  ierr = PetscObjectSetOptionsPrefix((PetscObject) P, prefix); CHKERRQ(ierr);\n  ierr = PetscSpacePolynomialSetTensor(P, tensor); CHKERRQ(ierr);\n  ierr = PetscSpaceSetFromOptions(P); CHKERRQ(ierr);\n  ierr = PetscSpaceSetNumComponents(P, Nc); CHKERRQ(ierr);\n  ierr = PetscSpaceSetNumVariables(P, dim); CHKERRQ(ierr);\n  ierr = PetscSpaceSetDegree(P, order, order); CHKERRQ(ierr);\n  ierr = PetscSpaceSetUp(P); CHKERRQ(ierr);\n  ierr = PetscSpacePolynomialGetTensor(P, &tensor); CHKERRQ(ierr);\n  /* Create dual space */\n  ierr = PetscDualSpaceCreate(PetscObjectComm((PetscObject) dm), &Q);\n  CHKERRQ(ierr);\n  ierr = PetscDualSpaceSetType(Q,PETSCDUALSPACELAGRANGE); CHKERRQ(ierr);\n  ierr = PetscObjectSetOptionsPrefix((PetscObject) Q, prefix); CHKERRQ(ierr);\n  ierr = PetscDualSpaceCreateReferenceCell(Q, dim, isSimplex, &K); CHKERRQ(ierr);\n  ierr = PetscDualSpaceSetDM(Q, K); CHKERRQ(ierr);\n  ierr = DMDestroy(&K); CHKERRQ(ierr);\n  ierr = PetscDualSpaceSetNumComponents(Q, Nc); CHKERRQ(ierr);\n  ierr = PetscDualSpaceSetOrder(Q, order); CHKERRQ(ierr);\n  ierr = PetscDualSpaceLagrangeSetTensor(Q, tensor); CHKERRQ(ierr);\n  ierr = PetscDualSpaceSetFromOptions(Q); CHKERRQ(ierr);\n  ierr = PetscDualSpaceSetUp(Q); CHKERRQ(ierr);\n  /* Create element */\n  ierr = PetscFECreate(PetscObjectComm((PetscObject) dm), fem); CHKERRQ(ierr);\n  ierr = PetscObjectSetOptionsPrefix((PetscObject) *fem, prefix); CHKERRQ(ierr);\n  ierr = PetscFESetFromOptions(*fem); CHKERRQ(ierr);\n  ierr = PetscFESetBasisSpace(*fem, P); CHKERRQ(ierr);\n  ierr = PetscFESetDualSpace(*fem, Q); CHKERRQ(ierr);\n  ierr = PetscFESetNumComponents(*fem, Nc); CHKERRQ(ierr);\n  ierr = PetscFESetUp(*fem); CHKERRQ(ierr);\n  ierr = PetscSpaceDestroy(&P); CHKERRQ(ierr);\n  ierr = PetscDualSpaceDestroy(&Q); CHKERRQ(ierr);\n  /* Create quadrature */\n  quadPointsPerEdge = PetscMax(order + 1,1);\n  if (isSimplex) {\n    ierr = PetscDTGaussJacobiQuadrature(dim,   1, quadPointsPerEdge, -1.0, 1.0,\n                                        &q); CHKERRQ(ierr);\n    ierr = PetscDTGaussJacobiQuadrature(dim-1, 1, quadPointsPerEdge, -1.0, 1.0,\n                                        &fq); CHKERRQ(ierr);\n  } else {\n    ierr = PetscDTGaussTensorQuadrature(dim,   1, quadPointsPerEdge, -1.0, 1.0,\n                                        &q); CHKERRQ(ierr);\n    ierr = PetscDTGaussTensorQuadrature(dim-1, 1, quadPointsPerEdge, -1.0, 1.0,\n                                        &fq); CHKERRQ(ierr);\n  }\n  ierr = PetscFESetQuadrature(*fem, q); CHKERRQ(ierr);\n  ierr = PetscFESetFaceQuadrature(*fem, fq); CHKERRQ(ierr);\n  ierr = PetscQuadratureDestroy(&q); CHKERRQ(ierr);\n  ierr = PetscQuadratureDestroy(&fq); CHKERRQ(ierr);\n\n  PetscFunctionReturn(0);\n}\n\n// -----------------------------------------------------------------------------\n// PETSc Setup for Level\n// -----------------------------------------------------------------------------\n\n// This function sets up a DM for a given degree\nstatic int SetupDMByDegree(DM dm, PetscInt degree, PetscInt ncompu,\n                           bpType bpChoice) {\n  PetscInt ierr, dim, marker_ids[1] = {1};\n  PetscFE fe;\n\n  PetscFunctionBeginUser;\n\n  // Setup FE\n  ierr = DMGetDimension(dm, &dim); CHKERRQ(ierr);\n  ierr = PetscFECreateByDegree(dm, dim, ncompu, PETSC_FALSE, NULL, degree, &fe);\n  CHKERRQ(ierr);\n  ierr = DMSetFromOptions(dm); CHKERRQ(ierr);\n  ierr = DMAddField(dm, NULL, (PetscObject)fe); CHKERRQ(ierr);\n\n  // Setup DM\n  ierr = DMCreateDS(dm); CHKERRQ(ierr);\n  if (bpOptions[bpChoice].enforce_bc) {\n    PetscBool hasLabel;\n    DMHasLabel(dm, \"marker\", &hasLabel);\n    if (!hasLabel) {CreateBCLabel(dm, \"marker\");}\n    ierr = DMAddBoundary(dm, DM_BC_ESSENTIAL, \"wall\", \"marker\", 0, 0, NULL,\n                         (void(*)(void))bpOptions[bpChoice].bcs_func,\n                         1, marker_ids, NULL);\n    CHKERRQ(ierr);\n  }\n  ierr = DMPlexSetClosurePermutationTensor(dm, PETSC_DETERMINE, NULL);\n  CHKERRQ(ierr);\n  ierr = PetscFEDestroy(&fe); CHKERRQ(ierr);\n\n  PetscFunctionReturn(0);\n}\n\n// -----------------------------------------------------------------------------\n// libCEED Setup for Level\n// -----------------------------------------------------------------------------\n\n// Destroy libCEED operator objects\nstatic PetscErrorCode CeedDataDestroy(CeedInt i, CeedData data) {\n  PetscInt ierr;\n\n  CeedVectorDestroy(&data->qdata);\n  CeedVectorDestroy(&data->xceed);\n  CeedVectorDestroy(&data->yceed);\n  CeedBasisDestroy(&data->basisx);\n  CeedBasisDestroy(&data->basisu);\n  CeedElemRestrictionDestroy(&data->Erestrictu);\n  CeedElemRestrictionDestroy(&data->Erestrictx);\n  CeedElemRestrictionDestroy(&data->Erestrictui);\n  CeedElemRestrictionDestroy(&data->Erestrictxi);\n  CeedElemRestrictionDestroy(&data->Erestrictqdi);\n  CeedQFunctionDestroy(&data->qf_apply);\n  CeedOperatorDestroy(&data->op_apply);\n  if (i > 0) {\n    CeedOperatorDestroy(&data->op_interp);\n    CeedBasisDestroy(&data->basisctof);\n    CeedOperatorDestroy(&data->op_restrict);\n  }\n  ierr = PetscFree(data); CHKERRQ(ierr);\n\n  PetscFunctionReturn(0);\n}\n\n// Get CEED restriction data from DMPlex\nstatic int CreateRestrictionPlex(Ceed ceed, CeedInt P, CeedInt ncomp,\n                                 CeedElemRestriction *Erestrict, DM dm) {\n  PetscInt ierr;\n  PetscInt c, cStart, cEnd, nelem, nnodes, *erestrict, eoffset;\n  PetscSection section;\n  Vec Uloc;\n\n  PetscFunctionBeginUser;\n\n  // Get Nelem\n  ierr = DMGetSection(dm, &section); CHKERRQ(ierr);\n  ierr = DMPlexGetHeightStratum(dm, 0, &cStart,& cEnd); CHKERRQ(ierr);\n  nelem = cEnd - cStart;\n\n  // Get indices\n  ierr = PetscMalloc1(nelem*P*P*P, &erestrict); CHKERRQ(ierr);\n  for (c=cStart, eoffset=0; c<cEnd; c++) {\n    PetscInt numindices, *indices, i;\n    ierr = DMPlexGetClosureIndices(dm, section, section, c, &numindices,\n                                   &indices, NULL); CHKERRQ(ierr);\n    for (i=0; i<numindices; i+=ncomp) {\n      for (PetscInt j=0; j<ncomp; j++) {\n        if (indices[i+j] != indices[i] + (PetscInt)(copysign(j, indices[i])))\n          SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP,\n                   \"Cell %D closure indices not interlaced\", c);\n      }\n      // Essential boundary conditions are encoded as -(loc+1)\n      PetscInt loc = indices[i] >= 0 ? indices[i] : -(indices[i] + 1);\n      erestrict[eoffset++] = loc/ncomp;\n    }\n    ierr = DMPlexRestoreClosureIndices(dm, section, section, c, &numindices,\n                                       &indices, NULL); CHKERRQ(ierr);\n  }\n\n  // Setup CEED restriction\n  ierr = DMGetLocalVector(dm, &Uloc); CHKERRQ(ierr);\n  ierr = VecGetLocalSize(Uloc, &nnodes); CHKERRQ(ierr);\n\n  ierr = DMRestoreLocalVector(dm, &Uloc); CHKERRQ(ierr);\n  CeedElemRestrictionCreate(ceed, nelem, P*P*P, nnodes/ncomp, ncomp,\n                            CEED_MEM_HOST, CEED_COPY_VALUES, erestrict,\n                            Erestrict);\n  ierr = PetscFree(erestrict); CHKERRQ(ierr);\n\n  PetscFunctionReturn(0);\n}\n\n// Set up libCEED for a given degree\nstatic int SetupLibceedByDegree(DM dm, Ceed ceed, CeedInt degree, CeedInt dim,\n                                CeedInt qextra, PetscInt ncompu, PetscInt gsize,\n                                PetscInt xlsize, bpType bpChoice, CeedData data,\n                                PetscBool setup_rhs, CeedVector rhsceed,\n                                CeedVector *target) {\n  int ierr;\n  DM dmcoord;\n  PetscSection section;\n  Vec coords;\n  const PetscScalar *coordArray;\n  CeedBasis basisx, basisu;\n  CeedElemRestriction Erestrictx, Erestrictu, Erestrictxi,\n                      Erestrictui, Erestrictqdi;\n  CeedQFunction qf_setupgeo, qf_apply;\n  CeedOperator op_setupgeo, op_apply;\n  CeedVector xcoord, qdata, xceed, yceed;\n  CeedInt qdatasize = bpOptions[bpChoice].qdatasize, ncompx = dim, P, Q,\n          cStart, cEnd, nelem;\n\n  // CEED bases\n  P = degree + 1;\n  Q = P + qextra;\n  CeedBasisCreateTensorH1Lagrange(ceed, dim, ncompu, P, Q,\n                                  bpOptions[bpChoice].qmode, &basisu);\n  CeedBasisCreateTensorH1Lagrange(ceed, dim, ncompx, 2, Q,\n                                  bpOptions[bpChoice].qmode, &basisx);\n\n  // CEED restrictions\n  ierr = DMGetCoordinateDM(dm, &dmcoord); CHKERRQ(ierr);\n  ierr = DMPlexSetClosurePermutationTensor(dmcoord, PETSC_DETERMINE, NULL);\n  CHKERRQ(ierr);\n\n  CreateRestrictionPlex(ceed, 2, ncompx, &Erestrictx, dmcoord);\n  CreateRestrictionPlex(ceed, P, ncompu, &Erestrictu, dm);\n\n  ierr = DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd); CHKERRQ(ierr);\n  nelem = cEnd - cStart;\n\n  CeedElemRestrictionCreateIdentity(ceed, nelem, Q*Q*Q, nelem*Q*Q*Q, ncompu,\n                                    &Erestrictui); CHKERRQ(ierr);\n  CeedElemRestrictionCreateIdentity(ceed, nelem, Q*Q*Q, nelem*Q*Q*Q,\n                                    qdatasize, &Erestrictqdi); CHKERRQ(ierr);\n  CeedElemRestrictionCreateIdentity(ceed, nelem, Q*Q*Q, nelem*Q*Q*Q, ncompx,\n                                    &Erestrictxi); CHKERRQ(ierr);\n\n  // Element coordinates\n  ierr = DMGetCoordinatesLocal(dm, &coords); CHKERRQ(ierr);\n  ierr = VecGetArrayRead(coords, &coordArray); CHKERRQ(ierr);\n  ierr = DMGetSection(dmcoord, &section); CHKERRQ(ierr);\n\n  CeedElemRestrictionCreateVector(Erestrictx, &xcoord, NULL);\n  CeedVectorSetArray(xcoord, CEED_MEM_HOST, CEED_COPY_VALUES,\n                     (PetscScalar *)coordArray);\n  ierr = VecRestoreArrayRead(coords, &coordArray); CHKERRQ(ierr);\n\n  // Create the persistent vectors that will be needed in setup and apply\n  CeedInt nqpts;\n  CeedBasisGetNumQuadraturePoints(basisu, &nqpts);\n  CeedVectorCreate(ceed, qdatasize*nelem*nqpts, &qdata);\n  CeedVectorCreate(ceed, xlsize, &xceed);\n  CeedVectorCreate(ceed, xlsize, &yceed);\n\n  // Create the Q-function that builds the operator (i.e. computes its\n  // quadrature data) and set its context data\n  CeedQFunctionCreateInterior(ceed, 1, bpOptions[bpChoice].setupgeo,\n                              bpOptions[bpChoice].setupgeofname, &qf_setupgeo);\n  CeedQFunctionAddInput(qf_setupgeo, \"dx\", ncompx*dim, CEED_EVAL_GRAD);\n  CeedQFunctionAddInput(qf_setupgeo, \"weight\", 1, CEED_EVAL_WEIGHT);\n  CeedQFunctionAddOutput(qf_setupgeo, \"qdata\", qdatasize, CEED_EVAL_NONE);\n\n  // Set up PDE operator\n  CeedInt inscale = bpOptions[bpChoice].inmode==CEED_EVAL_GRAD ? dim : 1;\n  CeedInt outscale = bpOptions[bpChoice].outmode==CEED_EVAL_GRAD ? dim : 1;\n  CeedQFunctionCreateInterior(ceed, 1, bpOptions[bpChoice].apply,\n                              bpOptions[bpChoice].applyfname, &qf_apply);\n  CeedQFunctionAddInput(qf_apply, \"u\", ncompu*inscale,\n                        bpOptions[bpChoice].inmode);\n  CeedQFunctionAddInput(qf_apply, \"qdata\", qdatasize, CEED_EVAL_NONE);\n  CeedQFunctionAddOutput(qf_apply, \"v\", ncompu*outscale,\n                         bpOptions[bpChoice].outmode);\n\n  // Create the operator that builds the quadrature data for the operator\n  CeedOperatorCreate(ceed, qf_setupgeo, CEED_QFUNCTION_NONE,\n                     CEED_QFUNCTION_NONE, &op_setupgeo);\n  CeedOperatorSetField(op_setupgeo, \"dx\", Erestrictx, CEED_TRANSPOSE,\n                       basisx, CEED_VECTOR_ACTIVE);\n  CeedOperatorSetField(op_setupgeo, \"weight\", Erestrictxi, CEED_NOTRANSPOSE,\n                       basisx, CEED_VECTOR_NONE);\n  CeedOperatorSetField(op_setupgeo, \"qdata\", Erestrictqdi, CEED_NOTRANSPOSE,\n                       CEED_BASIS_COLLOCATED, CEED_VECTOR_ACTIVE);\n\n  // Create the operator\n  CeedOperatorCreate(ceed, qf_apply, CEED_QFUNCTION_NONE, CEED_QFUNCTION_NONE,\n                     &op_apply);\n  CeedOperatorSetField(op_apply, \"u\", Erestrictu, CEED_TRANSPOSE,\n                       basisu, CEED_VECTOR_ACTIVE);\n  CeedOperatorSetField(op_apply, \"qdata\", Erestrictqdi, CEED_NOTRANSPOSE,\n                       CEED_BASIS_COLLOCATED, qdata);\n  CeedOperatorSetField(op_apply, \"v\", Erestrictu, CEED_TRANSPOSE,\n                       basisu, CEED_VECTOR_ACTIVE);\n\n  // Setup qdata\n  CeedOperatorApply(op_setupgeo, xcoord, qdata, CEED_REQUEST_IMMEDIATE);\n\n  // Set up RHS if needed\n  if (setup_rhs) {\n    CeedQFunction qf_setuprhs;\n    CeedOperator op_setuprhs;\n    CeedVectorCreate(ceed, nelem*nqpts*ncompu, target);\n\n    // Create the q-function that sets up the RHS and true solution\n    CeedQFunctionCreateInterior(ceed, 1, bpOptions[bpChoice].setuprhs,\n                                bpOptions[bpChoice].setuprhsfname, &qf_setuprhs);\n    CeedQFunctionAddInput(qf_setuprhs, \"x\", dim, CEED_EVAL_INTERP);\n    CeedQFunctionAddInput(qf_setuprhs, \"dx\", ncompx*dim, CEED_EVAL_GRAD);\n    CeedQFunctionAddInput(qf_setuprhs, \"weight\", 1, CEED_EVAL_WEIGHT);\n    CeedQFunctionAddOutput(qf_setuprhs, \"true_soln\", ncompu, CEED_EVAL_NONE);\n    CeedQFunctionAddOutput(qf_setuprhs, \"rhs\", ncompu, CEED_EVAL_INTERP);\n\n    // Create the operator that builds the RHS and true solution\n    CeedOperatorCreate(ceed, qf_setuprhs, CEED_QFUNCTION_NONE,\n                       CEED_QFUNCTION_NONE, &op_setuprhs);\n    CeedOperatorSetField(op_setuprhs, \"x\", Erestrictx, CEED_TRANSPOSE,\n                         basisx, CEED_VECTOR_ACTIVE);\n    CeedOperatorSetField(op_setuprhs, \"dx\", Erestrictx, CEED_TRANSPOSE,\n                         basisx, CEED_VECTOR_ACTIVE);\n    CeedOperatorSetField(op_setuprhs, \"weight\", Erestrictxi, CEED_NOTRANSPOSE,\n                         basisx, CEED_VECTOR_NONE);\n    CeedOperatorSetField(op_setuprhs, \"true_soln\", Erestrictui, CEED_NOTRANSPOSE,\n                         CEED_BASIS_COLLOCATED, *target);\n    CeedOperatorSetField(op_setuprhs, \"rhs\", Erestrictu, CEED_TRANSPOSE,\n                         basisu, CEED_VECTOR_ACTIVE);\n\n    // Setup RHS and target\n    CeedOperatorApply(op_setuprhs, xcoord, rhsceed, CEED_REQUEST_IMMEDIATE);\n    CeedVectorSyncArray(rhsceed, CEED_MEM_HOST);\n\n    // Cleanup\n    CeedQFunctionDestroy(&qf_setuprhs);\n    CeedOperatorDestroy(&op_setuprhs);\n  }\n\n  // Cleanup\n  CeedQFunctionDestroy(&qf_setupgeo);\n  CeedOperatorDestroy(&op_setupgeo);\n  CeedVectorDestroy(&xcoord);\n\n  // Save libCEED data required for level\n  data->basisx = basisx; data->basisu = basisu;\n  data->Erestrictx = Erestrictx;\n  data->Erestrictu = Erestrictu;\n  data->Erestrictxi = Erestrictxi;\n  data->Erestrictui = Erestrictui;\n  data->Erestrictqdi = Erestrictqdi;\n  data->qf_apply = qf_apply;\n  data->op_apply = op_apply;\n  data->qdata = qdata;\n  data->xceed = xceed;\n  data->yceed = yceed;\n\n  PetscFunctionReturn(0);\n}\n\n#ifdef multigrid\n// Setup libCEED level transfer operator objects\nstatic PetscErrorCode CeedLevelTransferSetup(Ceed ceed, CeedInt numlevels,\n    CeedInt ncompu, bpType bpChoice, CeedData *data, CeedInt *leveldegrees,\n    CeedQFunction qf_restrict, CeedQFunction qf_prolong) {\n  // Return early if numlevels=1\n  if (numlevels==1)\n    PetscFunctionReturn(0);\n\n  // Set up each level\n  for (CeedInt i=1; i<numlevels; i++) {\n    // P coarse and P fine\n    CeedInt Pc = leveldegrees[i-1] + 1;\n    CeedInt Pf = leveldegrees[i] + 1;\n\n    // Restriction - Fine to corse\n    CeedBasis basisctof;\n    CeedOperator op_restrict;\n\n    // Basis\n    CeedBasisCreateTensorH1Lagrange(ceed, 3, ncompu, Pc, Pf,\n                                    CEED_GAUSS_LOBATTO, &basisctof);\n\n    // Create the restriction operator\n    CeedOperatorCreate(ceed, qf_restrict, CEED_QFUNCTION_NONE,\n                       CEED_QFUNCTION_NONE, &op_restrict);\n    CeedOperatorSetField(op_restrict, \"input\", data[i]->Erestrictu,\n                         CEED_NOTRANSPOSE, CEED_BASIS_COLLOCATED,\n                         CEED_VECTOR_ACTIVE);\n    CeedOperatorSetField(op_restrict, \"output\", data[i-1]->Erestrictu,\n                         CEED_TRANSPOSE, basisctof, CEED_VECTOR_ACTIVE);\n\n    // Save libCEED data required for level\n    data[i]->basisctof = basisctof;\n    data[i]->op_restrict = op_restrict;\n\n    // Interpolation - Corse to fine\n    CeedOperator op_interp;\n\n    // Create the prolongation operator\n    CeedOperatorCreate(ceed, qf_prolong, CEED_QFUNCTION_NONE,\n                       CEED_QFUNCTION_NONE, &op_interp);\n    CeedOperatorSetField(op_interp, \"input\", data[i-1]->Erestrictu,\n                         CEED_NOTRANSPOSE, basisctof, CEED_VECTOR_ACTIVE);\n    CeedOperatorSetField(op_interp, \"output\", data[i]->Erestrictu,\n                         CEED_TRANSPOSE, CEED_BASIS_COLLOCATED,\n                         CEED_VECTOR_ACTIVE);\n\n    // Save libCEED data required for level\n    data[i]->op_interp = op_interp;\n  }\n\n  PetscFunctionReturn(0);\n}\n#endif\n\n// -----------------------------------------------------------------------------\n// Mat Shell Functions\n// -----------------------------------------------------------------------------\n\n#ifdef multigrid\n// This function returns the computed diagonal of the operator\nstatic PetscErrorCode MatGetDiag(Mat A, Vec D) {\n  PetscErrorCode ierr;\n  UserO user;\n\n  PetscFunctionBeginUser;\n  ierr = MatShellGetContext(A, &user); CHKERRQ(ierr);\n\n  ierr = VecCopy(user->diag, D); CHKERRQ(ierr);\n\n  PetscFunctionReturn(0);\n}\n#endif\n\n// This function uses libCEED to compute the action of the Laplacian with\n// Dirichlet boundary conditions\nstatic PetscErrorCode MatMult_Ceed(Mat A, Vec X, Vec Y) {\n  PetscErrorCode ierr;\n  UserO user;\n  PetscScalar *x, *y;\n\n  PetscFunctionBeginUser;\n  ierr = MatShellGetContext(A, &user); CHKERRQ(ierr);\n\n  // Global-to-local\n  ierr = DMGlobalToLocalBegin(user->dm, X, INSERT_VALUES, user->Xloc);\n  CHKERRQ(ierr);\n  ierr = DMGlobalToLocalEnd(user->dm, X, INSERT_VALUES, user->Xloc);\n  CHKERRQ(ierr);\n  ierr = VecZeroEntries(user->Yloc); CHKERRQ(ierr);\n\n  // Setup CEED vectors\n  ierr = VecGetArrayRead(user->Xloc, (const PetscScalar **)&x); CHKERRQ(ierr);\n  ierr = VecGetArray(user->Yloc, &y); CHKERRQ(ierr);\n  CeedVectorSetArray(user->xceed, CEED_MEM_HOST, CEED_USE_POINTER, x);\n  CeedVectorSetArray(user->yceed, CEED_MEM_HOST, CEED_USE_POINTER, y);\n\n  // Apply CEED operator\n  CeedOperatorApply(user->op, user->xceed, user->yceed, CEED_REQUEST_IMMEDIATE);\n  CeedVectorSyncArray(user->yceed, CEED_MEM_HOST);\n\n  // Restore PETSc vectors\n  ierr = VecRestoreArrayRead(user->Xloc, (const PetscScalar **)&x);\n  CHKERRQ(ierr);\n  ierr = VecRestoreArray(user->Yloc, &y); CHKERRQ(ierr);\n\n  // Local-to-global\n  ierr = VecZeroEntries(Y); CHKERRQ(ierr);\n  ierr = DMLocalToGlobalBegin(user->dm, user->Yloc, ADD_VALUES, Y);\n  CHKERRQ(ierr);\n  ierr = DMLocalToGlobalEnd(user->dm, user->Yloc, ADD_VALUES, Y);\n  CHKERRQ(ierr);\n\n  PetscFunctionReturn(0);\n}\n\n#ifdef multigrid\n// This function uses libCEED to compute the action of the interp operator\nstatic PetscErrorCode MatMult_Interp(Mat A, Vec X, Vec Y) {\n  PetscErrorCode ierr;\n  UserIR user;\n  PetscScalar *x, *y;\n\n  PetscFunctionBeginUser;\n  ierr = MatShellGetContext(A, &user); CHKERRQ(ierr);\n\n  // Global-to-local\n  ierr = VecZeroEntries(user->Xloc); CHKERRQ(ierr);\n  ierr = DMGlobalToLocalBegin(user->dmc, X, INSERT_VALUES, user->Xloc);\n  CHKERRQ(ierr);\n  ierr = DMGlobalToLocalEnd(user->dmc, X, INSERT_VALUES, user->Xloc);\n  CHKERRQ(ierr);\n  ierr = VecZeroEntries(user->Yloc); CHKERRQ(ierr);\n\n  // Setup CEED vectors\n  ierr = VecGetArrayRead(user->Xloc, (const PetscScalar **)&x); CHKERRQ(ierr);\n  ierr = VecGetArray(user->Yloc, &y); CHKERRQ(ierr);\n  CeedVectorSetArray(user->ceedvecc, CEED_MEM_HOST, CEED_USE_POINTER, x);\n  CeedVectorSetArray(user->ceedvecf, CEED_MEM_HOST, CEED_USE_POINTER, y);\n\n  // Apply CEED operator\n  CeedOperatorApply(user->op, user->ceedvecc, user->ceedvecf,\n                    CEED_REQUEST_IMMEDIATE);\n  CeedVectorSyncArray(user->ceedvecf, CEED_MEM_HOST);\n\n  // Restore PETSc vectors\n  ierr = VecRestoreArrayRead(user->Xloc, (const PetscScalar **)&x);\n  CHKERRQ(ierr);\n  ierr = VecRestoreArray(user->Yloc, &y); CHKERRQ(ierr);\n\n  // Multiplicity\n  ierr = VecPointwiseMult(user->Yloc, user->Yloc, user->mult);\n\n  // Local-to-global\n  ierr = VecZeroEntries(Y); CHKERRQ(ierr);\n  ierr = DMLocalToGlobalBegin(user->dmf, user->Yloc, ADD_VALUES, Y);\n  CHKERRQ(ierr);\n  ierr = DMLocalToGlobalEnd(user->dmf, user->Yloc, ADD_VALUES, Y);\n  CHKERRQ(ierr);\n\n  PetscFunctionReturn(0);\n}\n\n// This function uses libCEED to compute the action of the restriction operator\nstatic PetscErrorCode MatMult_Restrict(Mat A, Vec X, Vec Y) {\n  PetscErrorCode ierr;\n  UserIR user;\n  PetscScalar *x, *y;\n\n  PetscFunctionBeginUser;\n  ierr = MatShellGetContext(A, &user); CHKERRQ(ierr);\n\n  // Global-to-local\n  ierr = VecZeroEntries(user->Xloc); CHKERRQ(ierr);\n  ierr = DMGlobalToLocalBegin(user->dmf, X, INSERT_VALUES, user->Xloc);\n  CHKERRQ(ierr);\n  ierr = DMGlobalToLocalEnd(user->dmf, X, INSERT_VALUES, user->Xloc);\n  CHKERRQ(ierr);\n  ierr = VecZeroEntries(user->Yloc); CHKERRQ(ierr);\n\n  // Multiplicity\n  ierr = VecPointwiseMult(user->Xloc, user->Xloc, user->mult); CHKERRQ(ierr);\n\n  // Setup CEED vectors\n  ierr = VecGetArrayRead(user->Xloc, (const PetscScalar **)&x); CHKERRQ(ierr);\n  ierr = VecGetArray(user->Yloc, &y); CHKERRQ(ierr);\n  CeedVectorSetArray(user->ceedvecf, CEED_MEM_HOST, CEED_USE_POINTER, x);\n  CeedVectorSetArray(user->ceedvecc, CEED_MEM_HOST, CEED_USE_POINTER, y);\n\n  // Apply CEED operator\n  CeedOperatorApply(user->op, user->ceedvecf, user->ceedvecc,\n                    CEED_REQUEST_IMMEDIATE);\n  CeedVectorSyncArray(user->ceedvecc, CEED_MEM_HOST);\n\n  // Restore PETSc vectors\n  ierr = VecRestoreArrayRead(user->Xloc, (const PetscScalar **)&x);\n  CHKERRQ(ierr);\n  ierr = VecRestoreArray(user->Yloc, &y); CHKERRQ(ierr);\n\n  // Local-to-global\n  ierr = VecZeroEntries(Y); CHKERRQ(ierr);\n  ierr = DMLocalToGlobalBegin(user->dmc, user->Yloc, ADD_VALUES, Y);\n  CHKERRQ(ierr);\n  ierr = DMLocalToGlobalEnd(user->dmc, user->Yloc, ADD_VALUES, Y);\n  CHKERRQ(ierr);\n\n  PetscFunctionReturn(0);\n}\n#endif\n\n// This function calculates the error in the final solution\nstatic PetscErrorCode ComputeErrorMax(UserO user, CeedOperator op_error,\n                                      Vec X, CeedVector target,\n                                      PetscReal *maxerror) {\n  PetscErrorCode ierr;\n  PetscScalar *x;\n  CeedVector collocated_error;\n  CeedInt length;\n\n  PetscFunctionBeginUser;\n  CeedVectorGetLength(target, &length);\n  CeedVectorCreate(user->ceed, length, &collocated_error);\n\n  // Global-to-local\n  ierr = DMGlobalToLocal(user->dm, X, INSERT_VALUES, user->Xloc); CHKERRQ(ierr);\n\n  // Setup CEED vector\n  ierr = VecGetArrayRead(user->Xloc, (const PetscScalar **)&x); CHKERRQ(ierr);\n  CeedVectorSetArray(user->xceed, CEED_MEM_HOST, CEED_USE_POINTER, x);\n\n  // Apply CEED operator\n  CeedOperatorApply(op_error, user->xceed, collocated_error,\n                    CEED_REQUEST_IMMEDIATE);\n\n  // Restore PETSc vector\n  VecRestoreArrayRead(user->Xloc, (const PetscScalar **)&x); CHKERRQ(ierr);\n\n  // Reduce max error\n  *maxerror = 0;\n  const CeedScalar *e;\n  CeedVectorGetArrayRead(collocated_error, CEED_MEM_HOST, &e);\n  for (CeedInt i=0; i<length; i++) {\n    *maxerror = PetscMax(*maxerror, PetscAbsScalar(e[i]));\n  }\n  CeedVectorRestoreArrayRead(collocated_error, &e);\n  ierr = MPI_Allreduce(MPI_IN_PLACE, maxerror,\n                       1, MPIU_REAL, MPIU_MAX, user->comm); CHKERRQ(ierr);\n\n  // Cleanup\n  CeedVectorDestroy(&collocated_error);\n\n  PetscFunctionReturn(0);\n}\n#endif\n", "meta": {"hexsha": "36127a97868112b55da2ffa56101bf10a930253e", "size": 31804, "ext": "h", "lang": "C", "max_stars_repo_path": "examples/petsc/setup.h", "max_stars_repo_name": "jrwrigh/libCEED", "max_stars_repo_head_hexsha": "15e77cd9c9ad8c81f93cb17e681f4732bd8b573f", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/petsc/setup.h", "max_issues_repo_name": "jrwrigh/libCEED", "max_issues_repo_head_hexsha": "15e77cd9c9ad8c81f93cb17e681f4732bd8b573f", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/petsc/setup.h", "max_forks_repo_name": "jrwrigh/libCEED", "max_forks_repo_head_hexsha": "15e77cd9c9ad8c81f93cb17e681f4732bd8b573f", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1820250284, "max_line_length": 81, "alphanum_fraction": 0.6447302226, "num_tokens": 8957, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30074557894124154, "lm_q2_score": 0.04208772911713975, "lm_q1q2_score": 0.012657698459656343}}
{"text": "/*\n   Copyright [2019, 2020] [IBM Corporation]\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n       http://www.apache.org/licenses/LICENSE-2.0\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\n#ifndef __CCPM_AREATOP_ALLOCATOR_H__\n#define __CCPM_AREATOP_ALLOCATOR_H__\n\n#include \"atomic_word.h\"\n#include \"list_item.h\"\n#include <ccpm/interfaces.h>\n#include <common/byte_span.h>\n#include <gsl/pointers>\n#include <array>\n#include <cstddef>\n#include <ios> // ios_base::fmtflags, ostream\n#include <vector>\n\nnamespace ccpm\n{\n\tstruct level_hints\n\t{\n\tprivate:\n\t\t/* Each level has a list for every possible number of contiguous free elements.\n\t\t * of contiguous free elements.\n\t\t * Since \"contiguous\" free elements do not span a word, that is one list\n\t\t * for every possible contiguous size in a word.\n\t\t * The list at element n locates an area_ctl with has maximal runs of exactly\n\t\t * n+1 free elements,\n\t\t */\n\n\t\tusing free_ctls_t = std::array<list_item, alloc_states_per_word>;\n\t\tfree_ctls_t _free_ctls;\n\t\tfree_ctls_t::size_type find_free_ctl_ix(unsigned min_run_length) const;\n\t\tfree_ctls_t::size_type tier_ix_from_run_length(unsigned run_length) const;\n\tpublic:\n\t\tunsigned _ct_alloc_probe_success;\n\t\tunsigned _ct_alloc_probe_failure;\n\t\tunsigned _ct_subdivision;\n\n\tpublic:\n\t\tstatic constexpr auto size() { return alloc_states_per_word; }\n\n\t\t/* return smallest tier index which has an area with\n\t\t *   run length >= min_run_length\n\t\t * If no such tier, return sub_states_per_word.\n\t\t */\n\t\tauto find_free_ctl(unsigned min_run_length_) const -> const list_item *\n\t\t{\n\t\t\treturn & _free_ctls[find_free_ctl_ix(min_run_length_)];\n\t\t}\n\n\t\tauto find_free_ctl(unsigned min_run_length_) -> list_item *\n\t\t{\n\t\t\treturn & _free_ctls[find_free_ctl_ix(min_run_length_)];\n\t\t}\n\n\t\tconst auto *tier_from_run_length(unsigned run_length_) const\n\t\t{\n\t\t\treturn & _free_ctls[tier_ix_from_run_length(run_length_)];\n\t\t}\n\n\t\tauto *tier_from_run_length(unsigned run_length_)\n\t\t{\n\t\t\treturn & _free_ctls[tier_ix_from_run_length(run_length_)];\n\t\t}\n\n\t\tconst auto *tier_end() const\n\t\t{\n\t\t\treturn &_free_ctls[alloc_states_per_word];\n\t\t}\n\n\t\t/* Find the longest run length less than mac_run_length.\n\t\t * Used for tracing, when find_free_ctl_ix has failed to\n\t\t * find a long enough run\n\t\t */\n\t\tfree_ctls_t::size_type find_mac_ctl_ix(unsigned mac_run_length) const;\n\n\t\tlevel_hints()\n\t\t\t: _free_ctls()\n\t\t\t, _ct_alloc_probe_success(0)\n\t\t\t, _ct_alloc_probe_failure(0)\n\t\t\t, _ct_subdivision(0)\n\t\t{}\n\n\t\tusing level_ix_t = std::uint8_t;\n\t\tvoid print(\n\t\t\tstd::ostream &o_\n\t\t\t, level_ix_t level_\n\t\t\t, std::ios_base::fmtflags // size_format_\n\t\t) const;\n\t};\n\n\tstruct area_ctl;\n\n\t/*\n\t * Location of non-persisted items for a single \"region\" managed by the crash-consistent allocator.\n\t * Persisted items are keps in an area_ctl, which is in persistent memory.\n\t */\n\tstruct area_top\n\t{\n\tprivate:\n\t\tusing level_ix_t = std::uint8_t;\n\t\tusing byte_span = common::byte_span;\n\t\tusing persist_type = gsl::not_null<ccpm::persister *>;\n\t\tarea_ctl *_ctl;\n\t\tstd::size_t _bytes_free;\n\t\tbool _all_restored;\n\t\tunsigned _trace_level;\n\t\tstd::ostream *_o;\n\t\tusing level_hints_vec = std::vector<level_hints>;\n\t\tlevel_hints_vec _level;\n\t\tunsigned _ct_allocation;\n\t\tbyte_span _region; /* for get_region only */\n\n\t\tarea_top(\n\t\t\t// persist_type persist\n\t\t\tarea_ctl *ctl\n\t\t\t, unsigned trace_level\n\t\t\t, byte_span iov\n\t\t\t, std::ostream &o\n\t\t);\n\t\tarea_top(const area_top &) = delete;\n\t\tarea_top &operator=(const area_top &) = delete;\n\n\t\tvoid allocate_strategy_1(\n\t\t\tpersist_type persist_\n\t\t\t, void * & ptr_\n\t\t\t, std::size_t bytes\n\t\t\t, std::size_t alignment\n\t\t\t, level_hints_vec::iterator level_\n\t\t\t, unsigned run_length\n\t\t);\n\n\t\tbool allocate_recovery_1();\n\t\tbool allocate_recovery_2(persist_type persist, level_hints_vec::iterator level);\n\t\tbool trace_coarse() const { return 0 < _trace_level; }\n\t\tbool trace_fine() const { return 1 < _trace_level; }\n\n\tpublic:\n\t\t/* Initial area_ctl */\n\t\texplicit area_top(\n\t\t\tpersist_type persist\n\t\t\t, byte_span iov\n\t\t\t, unsigned trace_level\n\t\t\t, std::ostream &o\n\t\t);\n\t\t/* Restored area_ctl */\n\t\texplicit area_top(\n\t\t\tpersist_type persist\n\t\t\t, byte_span iov\n\t\t\t, const ownership_callback_t &resolver\n\t\t\t, unsigned trace_level\n\t\t\t, std::ostream &o\n\t\t);\n\t\t~area_top();\n\n\t\tbool includes(const void *addr) const;\n\n\t\t/* Free byte count. Required by users */\n\t\tstd::size_t bytes_free() const;\n\n\t\tbyte_span get_region() const { return _region; }\n\n\t\tvoid allocate(\n\t\t\tpersist_type persist\n\t\t\t, void * & ptr, std::size_t bytes\n\t\t\t, std::size_t alignment\n\t\t);\n\n\t\tvoid deallocate(\n\t\t\tpersist_type persist\n\t\t\t, void * & ptr, std::size_t bytes\n\t\t);\n\n\t\tvoid print(\n\t\t\tstd::ostream &o\n\t\t\t, std::ios_base::fmtflags size_format\n\t\t) const;\n\n\t\tvoid print_ctls(\n\t\t\tstd::ostream *o_\n\t\t\t, std::ios_base::fmtflags format_\n\t\t) const;\n\n    level_ix_t height() const { return level_ix_t(_level.size()); }\n\n    void set_root(const byte_span & iov, persist_type persist);\n    byte_span get_root() const;\n\n\t\t/*\n\t\t * called by area_ctl to add area_ctl a, at level level_ix, with a longest\n\t\t * free run (consecutive free elements) of free_run, to _level, which is the\n\t\t * non-persistent catalog of area_ctl items.\n\t\t */\n\t\tvoid remove_from_chain(area_ctl *a, level_ix_t level_ix, unsigned longest_run);\n\t\tvoid restore_to_chain(area_ctl *a, level_ix_t level_ix, unsigned run_length);\n\n\t\tbool contains(const void *p) const;\n\n\t\tbool is_in_chain(\n\t\t\tconst area_ctl *a\n\t\t\t, level_ix_t level_ix\n\t\t\t, unsigned run_length\n\t\t) const;\n\t};\n}\n\n#endif\n", "meta": {"hexsha": "21840f94503ff1a37723b0ddcda5d0e937472f30", "size": 5864, "ext": "h", "lang": "C", "max_stars_repo_path": "src/lib/libccpm/src/area_top.h", "max_stars_repo_name": "omriarad/mcas", "max_stars_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 60.0, "max_stars_repo_stars_event_min_datetime": "2020-04-28T08:15:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T10:35:15.000Z", "max_issues_repo_path": "src/lib/libccpm/src/area_top.h", "max_issues_repo_name": "omriarad/mcas", "max_issues_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 66.0, "max_issues_repo_issues_event_min_datetime": "2020-09-03T23:40:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T20:34:52.000Z", "max_forks_repo_path": "src/lib/libccpm/src/area_top.h", "max_forks_repo_name": "omriarad/mcas", "max_forks_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2019-11-02T06:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T01:56:42.000Z", "avg_line_length": 26.8990825688, "max_line_length": 100, "alphanum_fraction": 0.7218622101, "num_tokens": 1611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.03021458433846381, "lm_q1q2_score": 0.012650753079981533}}
{"text": "#pragma once\n\n#include <type_traits>\n\n#include <cuda/runtime_api.hpp>\n#include <gsl-lite/gsl-lite.hpp>\n\nnamespace thrustshift {\n\nnamespace kernel {\n\ntemplate <typename SrcT, typename MapT, typename DstT>\n__global__ void scatter(gsl_lite::span<const SrcT> src,\n                        gsl_lite::span<const MapT> map,\n                        gsl_lite::span<DstT> dst) {\n\n\tconst auto gtid = threadIdx.x + blockIdx.x * blockDim.x;\n\tif (gtid < src.size()) {\n\t\tdst[map[gtid]] = src[gtid];\n\t}\n}\n\n} // namespace kernel\n\nnamespace async {\n\ntemplate <class SrcRange, class MapRange, class DstRange>\nvoid scatter(cuda::stream_t& stream,\n             SrcRange&& src,\n             MapRange&& map,\n             DstRange&& dst) {\n\n\tgsl_Expects(src.size() == dst.size());\n\tgsl_Expects(src.size() == map.size());\n\tgsl_Expects(src.data() != dst.data());\n\n\tif (src.empty()) {\n\t\treturn;\n\t}\n\n\tusing src_value_type =\n\t    typename std::remove_reference<SrcRange>::type::value_type;\n\tusing map_index_type =\n\t    typename std::remove_reference<MapRange>::type::value_type;\n\tusing dst_value_type =\n\t    typename std::remove_reference<DstRange>::type::value_type;\n\n\tconstexpr cuda::grid::block_dimension_t block_dim = 128;\n\tconst cuda::grid::dimension_t grid_dim =\n\t    (src.size() + block_dim - 1) / block_dim;\n\tauto c = cuda::make_launch_config(grid_dim, block_dim);\n\tauto k = kernel::scatter<src_value_type, map_index_type, dst_value_type>;\n\tcuda::enqueue_launch(k, stream, c, src, map, dst);\n}\n\n} // namespace async\n\n} // namespace thrustshift\n", "meta": {"hexsha": "fa6f283949096b338be8aef36ae96218a0210fb7", "size": 1522, "ext": "h", "lang": "C", "max_stars_repo_path": "include/thrustshift/scatter.h", "max_stars_repo_name": "pauleonix/thrustshift", "max_stars_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-16T13:01:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T13:01:46.000Z", "max_issues_repo_path": "include/thrustshift/scatter.h", "max_issues_repo_name": "pauleonix/thrustshift", "max_issues_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-23T14:12:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-17T11:40:04.000Z", "max_forks_repo_path": "include/thrustshift/scatter.h", "max_forks_repo_name": "pauleonix/thrustshift", "max_forks_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7966101695, "max_line_length": 74, "alphanum_fraction": 0.673455979, "num_tokens": 381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25091278688527247, "lm_q2_score": 0.050330637048962415, "lm_q1q2_score": 0.012628600407666305}}
{"text": "/* spprop.c\n * \n * Copyright (C) 2014 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <stdlib.h>\n\n#include <gsl/gsl_spmatrix.h>\n#include <gsl/gsl_errno.h>\n\n/*\ngsl_spmatrix_equal()\n  Return 1 if a = b, 0 otherwise\n*/\n\nint\ngsl_spmatrix_equal(const gsl_spmatrix *a, const gsl_spmatrix *b)\n{\n  const size_t M = a->size1;\n  const size_t N = a->size2;\n\n  if (b->size1 != M || b->size2 != N)\n    {\n      GSL_ERROR_VAL(\"matrices must have same dimensions\", GSL_EBADLEN, 0);\n    }\n  else if (a->sptype != b->sptype)\n    {\n      GSL_ERROR_VAL(\"trying to compare different sparse matrix types\", GSL_EINVAL, 0);\n    }\n  else\n    {\n      const size_t nz = a->nz;\n      size_t n;\n\n      if (nz != b->nz)\n        return 0; /* different number of non-zero elements */\n\n      if (GSL_SPMATRIX_ISTRIPLET(a))\n        {\n          /*\n           * triplet formats could be out of order but identical, so use\n           * gsl_spmatrix_get() on b for each aij\n           */\n          for (n = 0; n < nz; ++n)\n            {\n              double bij = gsl_spmatrix_get(b, a->i[n], a->p[n]);\n\n              if (a->data[n] != bij)\n                return 0;\n            }\n        }\n      else if (GSL_SPMATRIX_ISCCS(a))\n        {\n          /*\n           * for CCS, both matrices should have everything\n           * in the same order\n           */\n\n          /* check row indices and data */\n          for (n = 0; n < nz; ++n)\n            {\n              if ((a->i[n] != b->i[n]) || (a->data[n] != b->data[n]))\n                return 0;\n            }\n\n          /* check column pointers */\n          for (n = 0; n < a->size2 + 1; ++n)\n            {\n              if (a->p[n] != b->p[n])\n                return 0;\n            }\n        }\n      else if (GSL_SPMATRIX_ISCRS(a))\n        {\n          /*\n           * for CRS, both matrices should have everything\n           * in the same order\n           */\n\n          /* check column indices and data */\n          for (n = 0; n < nz; ++n)\n            {\n              if ((a->i[n] != b->i[n]) || (a->data[n] != b->data[n]))\n                return 0;\n            }\n\n          /* check row pointers */\n          for (n = 0; n < a->size1 + 1; ++n)\n            {\n              if (a->p[n] != b->p[n])\n                return 0;\n            }\n        }\n      else\n        {\n          GSL_ERROR_VAL(\"unknown sparse matrix type\", GSL_EINVAL, 0);\n        }\n\n      return 1;\n    }\n} /* gsl_spmatrix_equal() */\n", "meta": {"hexsha": "50419a38121d6d0cf308d21db766714c7a2d77d8", "size": 3138, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.4/spmatrix/spprop.c", "max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-13T05:01:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-13T05:01:59.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/spmatrix/spprop.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/spmatrix/spprop.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8205128205, "max_line_length": 86, "alphanum_fraction": 0.5133843212, "num_tokens": 852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3380771241500058, "lm_q2_score": 0.0373268852023206, "lm_q1q2_score": 0.012619366002677957}}
{"text": "/* Function in common for mlfit1, mlfitN, etc ...\n */\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <assert.h>\n#include <stdint.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_sort.h>\n#include <gsl/gsl_statistics.h>\n\n\n#include \"mlfit.h\"\n#include \"blit3.h\"\n\n#ifndef verbose\n#define verbose 0\n#endif\n\ndouble estimateNphot(double *V, size_t Vm)\n  // V is a Vm x Vm matrix\n  // The number of photons locally as sum(V-min(V))\n{\n  double s = 0;\n  double minV = INFINITY;\n\n  for(size_t kk=0; kk<Vm*Vm; kk++)\n    s+=V[kk];\n\n  for(size_t kk=0; kk<Vm*Vm; kk++)\n    minV = GSL_MIN(V[kk], minV);\n\n  s = s-minV*Vm*Vm;\n\n  //printf(\"estimateNphot: %f\\n\", s);\n  return s;\n}\n\nint double_cmp(const void * a, const void * b)\n{\n  if (*(const double*)a > *(const double*)b) {\n    return 1;\n  } else {\n    if (*(const double*)a < *(const double*)b) { \n      return -1;\n    } else { \n    return 0;\n  }\n}\n}\n\ndouble estimateBGV(double *V, size_t Vm, size_t Vn, size_t Vp, double * D)\n  // estimate the background level in V [VmxVnxVp] around the point D\n  // (x,y,z)\n{\n\n  int32_t radius = 7;\n  double * ePixels = malloc(sizeof(double)*6*(2*radius+1)*(2*radius+1)); // a few more than we need\n\n  int32_t x = nearbyint(D[0]);\n  int32_t y = nearbyint(D[1]);\n  int32_t z = nearbyint(D[2]);\n\n  // Loop over the box, and copy the edge pixels to ePixels\n  size_t nPixels = 0;\n  for(int32_t zz = z-radius; zz<=z+radius; zz++)\n    for(int32_t yy = y-radius; yy<=y+radius; yy++)\n     for(int32_t xx = x-radius; xx<=x+radius; xx++)\n       if((abs(zz-z)+abs(yy-y)+abs(xx-x)) == radius)\n         if(xx>=0 && yy>=0 && zz>=0 && xx< (int32_t) Vm && yy<(int32_t) Vn && zz<(int32_t) Vp)\n           ePixels[nPixels++] = V[xx + yy*Vm + zz*Vm*Vn];\n\n#if verbose > 0\n  printf(\"%lu ePixels\\n\", nPixels);\n#endif\n\n  double median = 0;\n  if(nPixels>0)\n  {\n  qsort(ePixels, nPixels, sizeof(double),  double_cmp);\n  gsl_sort(ePixels, 1, nPixels);\n  median = gsl_stats_median_from_sorted_data(ePixels, 1, nPixels);\n  //median = (double) nPixels;\n#if verbose > 0\n  printf(\"Median: %f\\n\", median);\n#endif \n  }\n  else\n  { median = 0;}\n\n  free(ePixels);\n  return(median);\n  //return((double) q);\n}\n\ndouble estimateBG(double *V, size_t Vm)\n  // Estimate the background level as the median of the edge pixels\n{\n\n  size_t nEdge = 4*Vm-4;\n  double * ePixels = malloc(nEdge*sizeof(double));\n\n  size_t pos = 0;\n  for(uint32_t kk = 0; kk<Vm; kk++, pos++) // Left\n    ePixels[pos] = V[kk];\n  for(uint32_t kk = 0; kk<Vm; kk++, pos++) // Right\n    ePixels[pos] = V[kk+(Vm-1)*Vm];\n  for(uint32_t kk = 1; kk<Vm-1; kk++, pos++) // Top\n    ePixels[pos] = V[Vm*kk];\n  for(uint32_t kk = 1; kk<Vm-1; kk++, pos++) // Bottom\n    ePixels[pos] = (double) V[Vm-1+Vm*kk];\n\n  assert(pos == 4*Vm-4);\n\n  if(0) {\n    for(uint32_t kk = 0; kk<nEdge; kk++)\n      printf(\"%2d :%f\\n\", kk, ePixels[kk]);\n    printf(\"\\n\");\n  }\n\n//  qsort(ePixels, nEdge, sizeof(double),  double_cmp);\n\n  if(0) {\n    for(uint32_t kk = 0; kk<nEdge; kk++)\n      printf(\"%2d %f\\n\", kk, ePixels[kk]);\n    printf(\"\\n\");\n  }\n\n  gsl_sort(ePixels, 1, nEdge);\n  double median = gsl_stats_median_from_sorted_data(ePixels, 1, nEdge);\n  // double mean = gsl_stats_mean(ePixels, 1, nEdge);\n#if verbose > 0\n  printf(\"Median: %f\\n\", median);\n#endif \n  free(ePixels);\n  return(median);\n}\n\nint getZLine(double *W, size_t Ws,\n    double * V, size_t Vm, size_t Vn, size_t Vp,\n    double *D)\n  /* Copy a line from V into W.\n   * The line will be D[x, y, z-hWs:z+hWs]\n   * where hWs = (Ws-1)/2 and D = [x,y,z]\n   *\n   * returns 1 on failure (i.e. line is out of bounds)\n   * returns 0 if ok.\n   *\n   * See also: getRegion\n   */\n{\n\n  int64_t x = nearbyint(D[0]);\n  int64_t y = nearbyint(D[1]);\n  int64_t z = nearbyint(D[2]);\n\n  size_t Ws2 = (Ws-1)/2;\n\n  if(z+Ws2 >= Vp)\n    return 1;\n  if(z<(int64_t) Ws2)\n    return 1;\n\n  size_t pos = 0;\n  for(size_t zz = z-Ws2; zz<=z+Ws2; zz++)\n  {\n    W[pos++] = V[x + y*Vm + zz*Vm*Vn];\n  }\n  return 0;\n}\n\nint getRegion(double * W, size_t Ws,\n    double * V, size_t Vm, size_t Vn, size_t Vp,\n    double * D)\n  // Get a 2D region for constant z or returns 0 if out of bounds\n  // Vm, Vn, Vp is the centre of the region.\n{  \n  size_t Ws2 = (Ws-1)/2;\n  size_t pos = 0;\n\n  int64_t x = nearbyint(D[0]);\n  int64_t y = nearbyint(D[1]);\n  int64_t z = nearbyint(D[2]);\n\n#if verbose > 0\n  printf(\"getRegion round(D): (%lu %lu %lu)\\n\", x, y, z);\n  printf(\"getRegion size(V)   (%lu %lu %lu)\\n\", Vm, Vn, Vp);\n#endif\n\n  if(x-(int64_t) Ws2 < 0)\n    return 1;\n  if(y-(int64_t) Ws2 < 0)\n    return 1;\n  if(x+(uint64_t) Ws2  >= Vm)\n    return 1;\n  if(y+(uint64_t) Ws2  >= Vn)\n    return 1;\n  if(z<0)\n    return 1;\n  if((size_t) z>=Vp)\n    return 1;\n\n#if verbose > 1\n  printf(\"Region valid\\n\");\n  printf(\"%lu %lu %lu\\n\", Vm, Vn, Vp);\n#endif\n \n  uint32_t zz = z;\n  for(uint32_t yy = y-Ws2; yy<=y+Ws2; yy++) {\n    for(uint32_t xx = x-Ws2; xx<=x+Ws2; xx++) {\n      assert(xx<Vm); assert(yy<Vn); assert(zz<Vp);\n    // printf(\"x %lu y %lu z %lu\\n\", x, y, z);\n \n      W[pos++] = V[xx + yy*Vm + zz*Vm*Vn];\n    }\n  }\n  //  showRegion(W, Ws);\n return 0;\n}\n\nvoid showRegion(double * W, size_t Ws)\n  // Dump some quadratic region to the terminal\n{\nprintf(\"Show region ...\\n\");\n  for(size_t xx = 0 ; xx<Ws; xx++) {\n    for(size_t yy = 0; yy<Ws; yy++) {\n      printf(\"%f \", W[yy*Ws+xx]);\n    }\n    printf(\"\\n\");\n  }\n}\n", "meta": {"hexsha": "68a323a1257bc8ab3dd17fd52ea28697203355d0", "size": 5292, "ext": "c", "lang": "C", "max_stars_repo_path": "common/mex/mlfit.c", "max_stars_repo_name": "elgw/dotter", "max_stars_repo_head_hexsha": "8fe0ab3610ff5473bccbac169795a0d1b72c1938", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-15T08:20:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-15T08:20:13.000Z", "max_issues_repo_path": "common/mex/mlfit.c", "max_issues_repo_name": "elgw/dotter", "max_issues_repo_head_hexsha": "8fe0ab3610ff5473bccbac169795a0d1b72c1938", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "common/mex/mlfit.c", "max_forks_repo_name": "elgw/dotter", "max_forks_repo_head_hexsha": "8fe0ab3610ff5473bccbac169795a0d1b72c1938", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8103448276, "max_line_length": 99, "alphanum_fraction": 0.5801209373, "num_tokens": 1949, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713673161914675, "lm_q2_score": 0.02758528142736254, "lm_q1q2_score": 0.012610245392498864}}
{"text": "/*\n * Copyright 2016 Maikel Nadolski\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#ifndef HMM_ALGORITHM_H_\n#define HMM_ALGORITHM_H_\n\n#include <map>\n#include <range/v3/core.hpp>\n#include <range/v3/algorithm.hpp>\n#include <range/v3/view/map.hpp>\n#include <range/v3/view/unique.hpp>\n#include <gsl_util.h>\n\n#include \"maikel/hmm/algorithm/forward.h\"\n#include \"maikel/hmm/algorithm/backward.h\"\n#include \"maikel/hmm/algorithm/baum_welch.h\"\n\nnamespace maikel {\n\n  template <class SymbolType, class IndexType>\n    // requires UnsignedIntegral<I>\n    bool is_bijective_index_map(std::map<SymbolType,IndexType> const& map)\n    {\n      IndexType max_index = ranges::max( map | ranges::view::values );\n      std::vector<std::size_t> histogram(max_index+1);\n      for (IndexType index : map|ranges::view::values)\n        ++histogram[index];\n      return ranges::all_of(histogram, [](std::size_t count){ return count == 1; });\n    }\n\n  template <class T>\n  using ValueType = typename std::remove_reference<T>::type::value_type;\n\n  template <class Index, class Range, class T = ranges::range_value_t<Range>>\n    std::map<T,Index>\n    map_from_symbols(Range&& range)\n    {\n      std::map<T,Index> symbols_to_index;\n      Index index { 0 };\n      ranges::for_each(range | ranges::view::unique, [&symbols_to_index,&index](T const& s){\n          symbols_to_index[s] = index++;\n      });\n      Ensures(is_bijective_index_map(symbols_to_index));\n      return symbols_to_index;\n    }\n\n}\n\n#endif /* HMM_ALGORITHM_H_ */\n", "meta": {"hexsha": "f030b91134c63ad26ce9cd07bfe829a288adf8c7", "size": 2011, "ext": "h", "lang": "C", "max_stars_repo_path": "include/maikel/hmm/algorithm.h", "max_stars_repo_name": "maikel/hidden-markov-model", "max_stars_repo_head_hexsha": "db97cd0344a3cb55afdd2d341fd2c5c326f6476a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-14T07:16:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-14T07:16:01.000Z", "max_issues_repo_path": "include/maikel/hmm/algorithm.h", "max_issues_repo_name": "maikel/Hidden-Markov-Model", "max_issues_repo_head_hexsha": "db97cd0344a3cb55afdd2d341fd2c5c326f6476a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/maikel/hmm/algorithm.h", "max_forks_repo_name": "maikel/Hidden-Markov-Model", "max_forks_repo_head_hexsha": "db97cd0344a3cb55afdd2d341fd2c5c326f6476a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9206349206, "max_line_length": 92, "alphanum_fraction": 0.7031327698, "num_tokens": 504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25386099567919973, "lm_q2_score": 0.049589021579449735, "lm_q1q2_score": 0.01258871839291643}}
{"text": "/* matrix/gsl_matrix_double.h\n *\n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_MATRIX_DOUBLE_H__\n#define __GSL_MATRIX_DOUBLE_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/block/gsl_check_range.h>\n#include <gsl/vector/gsl_vector_double.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct\n{\n  size_t size1;\t\t//nr rows\n  size_t size2;\t\t//nr cols\n  size_t tda;\t\t//space between two consecutive rows \n  double * data;\t//a pointer to the data\n  gsl_block * block;//the block pointer. \n  int owner;\t\t//this is 1 if the current object owns the memory block, 0 otherwise\n} gsl_matrix;\n\ntypedef struct\n{\n  gsl_matrix matrix;\n} _gsl_matrix_view;\n\ntypedef _gsl_matrix_view gsl_matrix_view;\n\ntypedef struct\n{\n  gsl_matrix matrix;\n} _gsl_matrix_const_view;\n\ntypedef const _gsl_matrix_const_view gsl_matrix_const_view;\n\n/* Allocation */\n\nGSL_FUNC gsl_matrix *\ngsl_matrix_alloc (const size_t n1, const size_t n2);\n\nGSL_FUNC gsl_matrix *\ngsl_matrix_calloc (const size_t n1, const size_t n2);\n\nGSL_FUNC gsl_matrix *\ngsl_matrix_alloc_from_block (gsl_block * b,\n                                   const size_t offset,\n                                   const size_t n1,\n                                   const size_t n2,\n                                   const size_t d2);\n\nGSL_FUNC gsl_matrix *\ngsl_matrix_alloc_from_matrix (gsl_matrix * m,\n                                    const size_t k1,\n                                    const size_t k2,\n                                    const size_t n1,\n                                    const size_t n2);\n\nGSL_FUNC gsl_vector *\ngsl_vector_alloc_row_from_matrix (gsl_matrix * m,\n                                        const size_t i);\n\nGSL_FUNC gsl_vector *\ngsl_vector_alloc_col_from_matrix (gsl_matrix * m,\n                                        const size_t j);\n\nGSL_FUNC void gsl_matrix_free (gsl_matrix * m);\n\n/* Views */\n\nGSL_FUNC _gsl_matrix_view\ngsl_matrix_submatrix (gsl_matrix * m,\n                            const size_t i, const size_t j,\n                            const size_t n1, const size_t n2);\n\nGSL_FUNC _gsl_vector_view\ngsl_matrix_row (gsl_matrix * m, const size_t i);\n\nGSL_FUNC _gsl_vector_view\ngsl_matrix_column (gsl_matrix * m, const size_t j);\n\nGSL_FUNC _gsl_vector_view\ngsl_matrix_diagonal (gsl_matrix * m);\n\nGSL_FUNC _gsl_vector_view\ngsl_matrix_subdiagonal (gsl_matrix * m, const size_t k);\n\nGSL_FUNC _gsl_vector_view\ngsl_matrix_superdiagonal (gsl_matrix * m, const size_t k);\n\nGSL_FUNC _gsl_matrix_view\ngsl_matrix_view_array (double * base,\n                             const size_t n1,\n                             const size_t n2);\n\nGSL_FUNC _gsl_matrix_view\ngsl_matrix_view_array_with_tda (double * base,\n                                      const size_t n1,\n                                      const size_t n2,\n                                      const size_t tda);\n\n\nGSL_FUNC _gsl_matrix_view\ngsl_matrix_view_vector (gsl_vector * v,\n                              const size_t n1,\n                              const size_t n2);\n\nGSL_FUNC _gsl_matrix_view\ngsl_matrix_view_vector_with_tda (gsl_vector * v,\n                                       const size_t n1,\n                                       const size_t n2,\n                                       const size_t tda);\n\n\nGSL_FUNC _gsl_matrix_const_view\ngsl_matrix_const_submatrix (const gsl_matrix * m,\n                                  const size_t i, const size_t j,\n                                  const size_t n1, const size_t n2);\n\nGSL_FUNC _gsl_vector_const_view\ngsl_matrix_const_row (const gsl_matrix * m,\n                            const size_t i);\n\nGSL_FUNC _gsl_vector_const_view\ngsl_matrix_const_column (const gsl_matrix * m,\n                               const size_t j);\n\nGSL_FUNC _gsl_vector_const_view\ngsl_matrix_const_diagonal (const gsl_matrix * m);\n\nGSL_FUNC _gsl_vector_const_view\ngsl_matrix_const_subdiagonal (const gsl_matrix * m,\n                                    const size_t k);\n\nGSL_FUNC _gsl_vector_const_view\ngsl_matrix_const_superdiagonal (const gsl_matrix * m,\n                                      const size_t k);\n\nGSL_FUNC _gsl_matrix_const_view\ngsl_matrix_const_view_array (const double * base,\n                                   const size_t n1,\n                                   const size_t n2);\n\nGSL_FUNC _gsl_matrix_const_view\ngsl_matrix_const_view_array_with_tda (const double * base,\n                                            const size_t n1,\n                                            const size_t n2,\n                                            const size_t tda);\n\nGSL_FUNC _gsl_matrix_const_view\ngsl_matrix_const_view_vector (const gsl_vector * v,\n                                    const size_t n1,\n                                    const size_t n2);\n\nGSL_FUNC _gsl_matrix_const_view\ngsl_matrix_const_view_vector_with_tda (const gsl_vector * v,\n                                             const size_t n1,\n                                             const size_t n2,\n                                             const size_t tda);\n\n/* Operations */\n\nGSL_FUNC double   gsl_matrix_get(const gsl_matrix * m, const size_t i, const size_t j);\nGSL_FUNC void    gsl_matrix_set(gsl_matrix * m, const size_t i, const size_t j, const double x);\n\nGSL_FUNC double * gsl_matrix_ptr(gsl_matrix * m, const size_t i, const size_t j);\nGSL_FUNC const double * gsl_matrix_const_ptr(const gsl_matrix * m, const size_t i, const size_t j);\n\nGSL_FUNC void gsl_matrix_set_zero (gsl_matrix * m);\nGSL_FUNC void gsl_matrix_set_identity (gsl_matrix * m);\nGSL_FUNC void gsl_matrix_set_all (gsl_matrix * m, double x);\n\nGSL_FUNC int gsl_matrix_fread (FILE * stream, gsl_matrix * m) ;\nGSL_FUNC int gsl_matrix_fwrite (FILE * stream, const gsl_matrix * m) ;\nGSL_FUNC int gsl_matrix_fscanf (FILE * stream, gsl_matrix * m);\nGSL_FUNC int gsl_matrix_fprintf (FILE * stream, const gsl_matrix * m, const char * format);\n\nGSL_FUNC int gsl_matrix_memcpy(gsl_matrix * dest, const gsl_matrix * src);\nGSL_FUNC int gsl_matrix_swap(gsl_matrix * m1, gsl_matrix * m2);\n\nGSL_FUNC int gsl_matrix_swap_rows(gsl_matrix * m, const size_t i, const size_t j);\nGSL_FUNC int gsl_matrix_swap_columns(gsl_matrix * m, const size_t i, const size_t j);\nGSL_FUNC int gsl_matrix_swap_rowcol(gsl_matrix * m, const size_t i, const size_t j);\nGSL_FUNC int gsl_matrix_transpose (gsl_matrix * m);\nGSL_FUNC int gsl_matrix_transpose_memcpy (gsl_matrix * dest, const gsl_matrix * src);\n\nGSL_FUNC double gsl_matrix_max (const gsl_matrix * m);\nGSL_FUNC double gsl_matrix_min (const gsl_matrix * m);\nGSL_FUNC void gsl_matrix_minmax (const gsl_matrix * m, double * min_out, double * max_out);\n\nGSL_FUNC void gsl_matrix_max_index (const gsl_matrix * m, size_t * imax, size_t *jmax);\nGSL_FUNC void gsl_matrix_min_index (const gsl_matrix * m, size_t * imin, size_t *jmin);\nGSL_FUNC void gsl_matrix_minmax_index (const gsl_matrix * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);\n\nGSL_FUNC int gsl_matrix_isnull (const gsl_matrix * m);\nGSL_FUNC int gsl_matrix_ispos (const gsl_matrix * m);\nGSL_FUNC int gsl_matrix_isneg (const gsl_matrix * m);\n\nGSL_FUNC int gsl_matrix_add (gsl_matrix * a, const gsl_matrix * b);\nGSL_FUNC int gsl_matrix_add_scaled (gsl_matrix * a, const gsl_matrix * b, double scaleA, double scaleB);\nGSL_FUNC int gsl_matrix_sub (gsl_matrix * a, const gsl_matrix * b);\nGSL_FUNC int gsl_matrix_mul_elements (gsl_matrix * a, const gsl_matrix * b);\nGSL_FUNC int gsl_matrix_div_elements (gsl_matrix * a, const gsl_matrix * b);\nGSL_FUNC int gsl_matrix_scale (gsl_matrix * a, const double x);\nGSL_FUNC int gsl_matrix_add_constant (gsl_matrix * a, const double x);\nGSL_FUNC int gsl_matrix_add_diagonal (gsl_matrix * a, const double x);\n\n/***********************************************************************/\n/* The functions below are obsolete                                    */\n/***********************************************************************/\nGSL_FUNC int gsl_matrix_get_row(gsl_vector * v, const gsl_matrix * m, const size_t i);\nGSL_FUNC int gsl_matrix_get_col(gsl_vector * v, const gsl_matrix * m, const size_t j);\nGSL_FUNC int gsl_matrix_set_row(gsl_matrix * m, const size_t i, const gsl_vector * v);\nGSL_FUNC int gsl_matrix_set_col(gsl_matrix * m, const size_t j, const gsl_vector * v);\n\n/* inline functions if you are using GCC */\n\n#ifdef HAVE_INLINE\nextern inline\ndouble\ngsl_matrix_get(const gsl_matrix * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_VAL(\"first index out of range\", GSL_EINVAL, 0) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_VAL(\"second index out of range\", GSL_EINVAL, 0) ;\n    }\n#endif\n  return m->data[i * m->tda + j] ;\n}\n\nextern inline\nvoid\ngsl_matrix_set(gsl_matrix * m, const size_t i, const size_t j, const double x)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_VOID(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_VOID(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  m->data[i * m->tda + j] = x ;\n}\n\nextern inline\ndouble *\ngsl_matrix_ptr(gsl_matrix * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  return (double *) (m->data + (i * m->tda + j)) ;\n}\n\nextern inline\nconst double *\ngsl_matrix_const_ptr(const gsl_matrix * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  return (const double *) (m->data + (i * m->tda + j)) ;\n}\n\n#endif\n\n__END_DECLS\n\n#endif /* __GSL_MATRIX_DOUBLE_H__ */\n", "meta": {"hexsha": "1b42b59ef32046427672c1c66ffe41e203cfdc1f", "size": 10834, "ext": "h", "lang": "C", "max_stars_repo_path": "Cartwheel/cartwheel-3d/gsl/matrix/gsl_matrix_double.h", "max_stars_repo_name": "MontyThibault/centre-of-mass-awareness", "max_stars_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Cartwheel/cartwheel-3d/gsl/matrix/gsl_matrix_double.h", "max_issues_repo_name": "MontyThibault/centre-of-mass-awareness", "max_issues_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cartwheel/cartwheel-3d/gsl/matrix/gsl_matrix_double.h", "max_forks_repo_name": "MontyThibault/centre-of-mass-awareness", "max_forks_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.85625, "max_line_length": 121, "alphanum_fraction": 0.6490677497, "num_tokens": 2711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34158251284363395, "lm_q2_score": 0.036769464096493294, "lm_q1q2_score": 0.012559805941993957}}
{"text": "#ifndef RL_MDL_NLOPTINVERSEKINEMATICS_H\n#define RL_MDL_NLOPTINVERSEKINEMATICS_H\n\n#include <chrono>\n#include <nlopt.h>\n#include <random>\n#include <utility>\n\n#include \"InverseKinematics.h\"\n\nnamespace rl\n{\n\tnamespace mdl\n\t{\n\t\tclass NloptInverseKinematics : public InverseKinematics\n\t\t{\n\t\tpublic:\n\t\t\tNloptInverseKinematics(Kinematic* kinematic);\n\t\t\t\n\t\t\tvirtual ~NloptInverseKinematics();\n\t\t\t\n\t\t\tbool solve();\n\t\t\t\n\t\t\t::rl::math::Real delta;\n\t\t\t\n\t\t\t::std::chrono::nanoseconds duration;\n\t\t\t\n\t\t\t::rl::math::Real epsilonRotation;\n\t\t\t\n\t\t\t::rl::math::Real epsilonTranslation;\n\t\t\t\n\t\t\tdouble tolerance;\n\t\t\t\n\t\tprotected:\n\t\t\t\n\t\tprivate:\n\t\t\tstatic void check(const nlopt_result& ret);\n\t\t\t\n\t\t\t::rl::math::Real error(const ::rl::math::Vector& q);\n\t\t\t\n\t\t\tstatic ::rl::math::Real f(unsigned n, const double* x, double* grad, void* data);\n\t\t\t\n\t\t\t::std::uniform_real_distribution< ::rl::math::Real> randDistribution;\n\t\t\t\n\t\t\t::std::mt19937 randEngine;\n\t\t};\n\t}\n}\n\n#endif // RL_MDL_NLOPTINVERSEKINEMATICS_H\n", "meta": {"hexsha": "c879b1f9e601287af81a0578981e131f7109a6ab", "size": 982, "ext": "h", "lang": "C", "max_stars_repo_path": "src/rl/mdl/NloptInverseKinematics.h", "max_stars_repo_name": "Roboy/rl", "max_stars_repo_head_hexsha": "7686cbd5f9c3630daa6d972f2244ed31f4dc5142", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-10T17:26:21.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-10T17:26:21.000Z", "max_issues_repo_path": "src/rl/mdl/NloptInverseKinematics.h", "max_issues_repo_name": "Roboy/rl", "max_issues_repo_head_hexsha": "7686cbd5f9c3630daa6d972f2244ed31f4dc5142", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/rl/mdl/NloptInverseKinematics.h", "max_forks_repo_name": "Roboy/rl", "max_forks_repo_head_hexsha": "7686cbd5f9c3630daa6d972f2244ed31f4dc5142", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-10T17:26:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-10T17:26:06.000Z", "avg_line_length": 19.2549019608, "max_line_length": 84, "alphanum_fraction": 0.6822810591, "num_tokens": 288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.02887090475289319, "lm_q1q2_score": 0.012529437534874423}}
{"text": "/* matrix/gsl_matrix_float.h\r\n * \r\n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\r\n * \r\n * This program is free software; you can redistribute it and/or modify\r\n * it under the terms of the GNU General Public License as published by\r\n * the Free Software Foundation; either version 3 of the License, or (at\r\n * your option) any later version.\r\n * \r\n * This program is distributed in the hope that it will be useful, but\r\n * WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n * General Public License for more details.\r\n * \r\n * You should have received a copy of the GNU General Public License\r\n * along with this program; if not, write to the Free Software\r\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r\n */\r\n\r\n#ifndef __GSL_MATRIX_FLOAT_H__\r\n#define __GSL_MATRIX_FLOAT_H__\r\n\r\n#if !defined( GSL_FUN )\r\n#  if !defined( GSL_DLL )\r\n#    define GSL_FUN extern\r\n#  elif defined( BUILD_GSL_DLL )\r\n#    define GSL_FUN extern __declspec(dllexport)\r\n#  else\r\n#    define GSL_FUN extern __declspec(dllimport)\r\n#  endif\r\n#endif\r\n\r\n#include <stdlib.h>\r\n#include <gsl/gsl_types.h>\r\n#include <gsl/gsl_errno.h>\r\n#include <gsl/gsl_inline.h>\r\n#include <gsl/gsl_check_range.h>\r\n#include <gsl/gsl_vector_float.h>\r\n\r\n#undef __BEGIN_DECLS\r\n#undef __END_DECLS\r\n#ifdef __cplusplus\r\n# define __BEGIN_DECLS extern \"C\" {\r\n# define __END_DECLS }\r\n#else\r\n# define __BEGIN_DECLS /* empty */\r\n# define __END_DECLS /* empty */\r\n#endif\r\n\r\n__BEGIN_DECLS\r\n\r\ntypedef struct \r\n{\r\n  size_t size1;\r\n  size_t size2;\r\n  size_t tda;\r\n  float * data;\r\n  gsl_block_float * block;\r\n  int owner;\r\n} gsl_matrix_float;\r\n\r\ntypedef struct\r\n{\r\n  gsl_matrix_float matrix;\r\n} _gsl_matrix_float_view;\r\n\r\ntypedef _gsl_matrix_float_view gsl_matrix_float_view;\r\n\r\ntypedef struct\r\n{\r\n  gsl_matrix_float matrix;\r\n} _gsl_matrix_float_const_view;\r\n\r\ntypedef const _gsl_matrix_float_const_view gsl_matrix_float_const_view;\r\n\r\n/* Allocation */\r\n\r\nGSL_FUN gsl_matrix_float * \r\ngsl_matrix_float_alloc (const size_t n1, const size_t n2);\r\n\r\nGSL_FUN gsl_matrix_float * \r\ngsl_matrix_float_calloc (const size_t n1, const size_t n2);\r\n\r\nGSL_FUN gsl_matrix_float * \r\ngsl_matrix_float_alloc_from_block (gsl_block_float * b, \r\n                                   const size_t offset, \r\n                                   const size_t n1, \r\n                                   const size_t n2, \r\n                                   const size_t d2);\r\n\r\nGSL_FUN gsl_matrix_float * \r\ngsl_matrix_float_alloc_from_matrix (gsl_matrix_float * m,\r\n                                    const size_t k1, \r\n                                    const size_t k2,\r\n                                    const size_t n1, \r\n                                    const size_t n2);\r\n\r\nGSL_FUN gsl_vector_float * \r\ngsl_vector_float_alloc_row_from_matrix (gsl_matrix_float * m,\r\n                                        const size_t i);\r\n\r\nGSL_FUN gsl_vector_float * \r\ngsl_vector_float_alloc_col_from_matrix (gsl_matrix_float * m,\r\n                                        const size_t j);\r\n\r\nGSL_FUN void gsl_matrix_float_free (gsl_matrix_float * m);\r\n\r\n/* Views */\r\n\r\nGSL_FUN _gsl_matrix_float_view \r\ngsl_matrix_float_submatrix (gsl_matrix_float * m, \r\n                            const size_t i, const size_t j, \r\n                            const size_t n1, const size_t n2);\r\n\r\nGSL_FUN _gsl_vector_float_view \r\ngsl_matrix_float_row (gsl_matrix_float * m, const size_t i);\r\n\r\nGSL_FUN _gsl_vector_float_view \r\ngsl_matrix_float_column (gsl_matrix_float * m, const size_t j);\r\n\r\nGSL_FUN _gsl_vector_float_view \r\ngsl_matrix_float_diagonal (gsl_matrix_float * m);\r\n\r\nGSL_FUN _gsl_vector_float_view \r\ngsl_matrix_float_subdiagonal (gsl_matrix_float * m, const size_t k);\r\n\r\nGSL_FUN _gsl_vector_float_view \r\ngsl_matrix_float_superdiagonal (gsl_matrix_float * m, const size_t k);\r\n\r\nGSL_FUN _gsl_vector_float_view\r\ngsl_matrix_float_subrow (gsl_matrix_float * m, const size_t i,\r\n                         const size_t offset, const size_t n);\r\n\r\nGSL_FUN _gsl_vector_float_view\r\ngsl_matrix_float_subcolumn (gsl_matrix_float * m, const size_t j,\r\n                            const size_t offset, const size_t n);\r\n\r\nGSL_FUN _gsl_matrix_float_view\r\ngsl_matrix_float_view_array (float * base,\r\n                             const size_t n1, \r\n                             const size_t n2);\r\n\r\nGSL_FUN _gsl_matrix_float_view\r\ngsl_matrix_float_view_array_with_tda (float * base, \r\n                                      const size_t n1, \r\n                                      const size_t n2,\r\n                                      const size_t tda);\r\n\r\n\r\nGSL_FUN _gsl_matrix_float_view\r\ngsl_matrix_float_view_vector (gsl_vector_float * v,\r\n                              const size_t n1, \r\n                              const size_t n2);\r\n\r\nGSL_FUN _gsl_matrix_float_view\r\ngsl_matrix_float_view_vector_with_tda (gsl_vector_float * v,\r\n                                       const size_t n1, \r\n                                       const size_t n2,\r\n                                       const size_t tda);\r\n\r\n\r\nGSL_FUN _gsl_matrix_float_const_view \r\ngsl_matrix_float_const_submatrix (const gsl_matrix_float * m, \r\n                                  const size_t i, const size_t j, \r\n                                  const size_t n1, const size_t n2);\r\n\r\nGSL_FUN _gsl_vector_float_const_view \r\ngsl_matrix_float_const_row (const gsl_matrix_float * m, \r\n                            const size_t i);\r\n\r\nGSL_FUN _gsl_vector_float_const_view \r\ngsl_matrix_float_const_column (const gsl_matrix_float * m, \r\n                               const size_t j);\r\n\r\nGSL_FUN _gsl_vector_float_const_view\r\ngsl_matrix_float_const_diagonal (const gsl_matrix_float * m);\r\n\r\nGSL_FUN _gsl_vector_float_const_view \r\ngsl_matrix_float_const_subdiagonal (const gsl_matrix_float * m, \r\n                                    const size_t k);\r\n\r\nGSL_FUN _gsl_vector_float_const_view \r\ngsl_matrix_float_const_superdiagonal (const gsl_matrix_float * m, \r\n                                      const size_t k);\r\n\r\nGSL_FUN _gsl_vector_float_const_view\r\ngsl_matrix_float_const_subrow (const gsl_matrix_float * m, const size_t i,\r\n                               const size_t offset, const size_t n);\r\n\r\nGSL_FUN _gsl_vector_float_const_view\r\ngsl_matrix_float_const_subcolumn (const gsl_matrix_float * m, const size_t j,\r\n                                  const size_t offset, const size_t n);\r\n\r\nGSL_FUN _gsl_matrix_float_const_view\r\ngsl_matrix_float_const_view_array (const float * base,\r\n                                   const size_t n1, \r\n                                   const size_t n2);\r\n\r\nGSL_FUN _gsl_matrix_float_const_view\r\ngsl_matrix_float_const_view_array_with_tda (const float * base, \r\n                                            const size_t n1, \r\n                                            const size_t n2,\r\n                                            const size_t tda);\r\n\r\nGSL_FUN _gsl_matrix_float_const_view\r\ngsl_matrix_float_const_view_vector (const gsl_vector_float * v,\r\n                                    const size_t n1, \r\n                                    const size_t n2);\r\n\r\nGSL_FUN _gsl_matrix_float_const_view\r\ngsl_matrix_float_const_view_vector_with_tda (const gsl_vector_float * v,\r\n                                             const size_t n1, \r\n                                             const size_t n2,\r\n                                             const size_t tda);\r\n\r\n/* Operations */\r\n\r\nGSL_FUN void gsl_matrix_float_set_zero (gsl_matrix_float * m);\r\nGSL_FUN void gsl_matrix_float_set_identity (gsl_matrix_float * m);\r\nGSL_FUN void gsl_matrix_float_set_all (gsl_matrix_float * m, float x);\r\n\r\nGSL_FUN int gsl_matrix_float_fread (FILE * stream, gsl_matrix_float * m) ;\r\nGSL_FUN int gsl_matrix_float_fwrite (FILE * stream, const gsl_matrix_float * m) ;\r\nGSL_FUN int gsl_matrix_float_fscanf (FILE * stream, gsl_matrix_float * m);\r\nGSL_FUN int gsl_matrix_float_fprintf (FILE * stream, const gsl_matrix_float * m, const char * format);\r\n \r\nGSL_FUN int gsl_matrix_float_memcpy(gsl_matrix_float * dest, const gsl_matrix_float * src);\r\nGSL_FUN int gsl_matrix_float_swap(gsl_matrix_float * m1, gsl_matrix_float * m2);\r\n\r\nGSL_FUN int gsl_matrix_float_swap_rows(gsl_matrix_float * m, const size_t i, const size_t j);\r\nGSL_FUN int gsl_matrix_float_swap_columns(gsl_matrix_float * m, const size_t i, const size_t j);\r\nGSL_FUN int gsl_matrix_float_swap_rowcol(gsl_matrix_float * m, const size_t i, const size_t j);\r\nGSL_FUN int gsl_matrix_float_transpose (gsl_matrix_float * m);\r\nGSL_FUN int gsl_matrix_float_transpose_memcpy (gsl_matrix_float * dest, const gsl_matrix_float * src);\r\n\r\nGSL_FUN float gsl_matrix_float_max (const gsl_matrix_float * m);\r\nGSL_FUN float gsl_matrix_float_min (const gsl_matrix_float * m);\r\nGSL_FUN void gsl_matrix_float_minmax (const gsl_matrix_float * m, float * min_out, float * max_out);\r\n\r\nGSL_FUN void gsl_matrix_float_max_index (const gsl_matrix_float * m, size_t * imax, size_t *jmax);\r\nGSL_FUN void gsl_matrix_float_min_index (const gsl_matrix_float * m, size_t * imin, size_t *jmin);\r\nGSL_FUN void gsl_matrix_float_minmax_index (const gsl_matrix_float * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);\r\n\r\nGSL_FUN int gsl_matrix_float_isnull (const gsl_matrix_float * m);\r\nGSL_FUN int gsl_matrix_float_ispos (const gsl_matrix_float * m);\r\nGSL_FUN int gsl_matrix_float_isneg (const gsl_matrix_float * m);\r\nGSL_FUN int gsl_matrix_float_isnonneg (const gsl_matrix_float * m);\r\n\r\nGSL_FUN int gsl_matrix_float_add (gsl_matrix_float * a, const gsl_matrix_float * b);\r\nGSL_FUN int gsl_matrix_float_sub (gsl_matrix_float * a, const gsl_matrix_float * b);\r\nGSL_FUN int gsl_matrix_float_mul_elements (gsl_matrix_float * a, const gsl_matrix_float * b);\r\nGSL_FUN int gsl_matrix_float_div_elements (gsl_matrix_float * a, const gsl_matrix_float * b);\r\nGSL_FUN int gsl_matrix_float_scale (gsl_matrix_float * a, const double x);\r\nGSL_FUN int gsl_matrix_float_add_constant (gsl_matrix_float * a, const double x);\r\nGSL_FUN int gsl_matrix_float_add_diagonal (gsl_matrix_float * a, const double x);\r\n\r\n/***********************************************************************/\r\n/* The functions below are obsolete                                    */\r\n/***********************************************************************/\r\nGSL_FUN int gsl_matrix_float_get_row(gsl_vector_float * v, const gsl_matrix_float * m, const size_t i);\r\nGSL_FUN int gsl_matrix_float_get_col(gsl_vector_float * v, const gsl_matrix_float * m, const size_t j);\r\nGSL_FUN int gsl_matrix_float_set_row(gsl_matrix_float * m, const size_t i, const gsl_vector_float * v);\r\nGSL_FUN int gsl_matrix_float_set_col(gsl_matrix_float * m, const size_t j, const gsl_vector_float * v);\r\n/***********************************************************************/\r\n\r\n/* inline functions if you are using GCC */\r\n\r\nGSL_FUN INLINE_DECL float   gsl_matrix_float_get(const gsl_matrix_float * m, const size_t i, const size_t j);\r\nGSL_FUN INLINE_DECL void    gsl_matrix_float_set(gsl_matrix_float * m, const size_t i, const size_t j, const float x);\r\nGSL_FUN INLINE_DECL float * gsl_matrix_float_ptr(gsl_matrix_float * m, const size_t i, const size_t j);\r\nGSL_FUN INLINE_DECL const float * gsl_matrix_float_const_ptr(const gsl_matrix_float * m, const size_t i, const size_t j);\r\n\r\n#ifdef HAVE_INLINE\r\nINLINE_FUN \r\nfloat\r\ngsl_matrix_float_get(const gsl_matrix_float * m, const size_t i, const size_t j)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(1)) \r\n    {\r\n      if (i >= m->size1)\r\n        {\r\n          GSL_ERROR_VAL(\"first index out of range\", GSL_EINVAL, 0) ;\r\n        }\r\n      else if (j >= m->size2)\r\n        {\r\n          GSL_ERROR_VAL(\"second index out of range\", GSL_EINVAL, 0) ;\r\n        }\r\n    }\r\n#endif\r\n  return m->data[i * m->tda + j] ;\r\n} \r\n\r\nINLINE_FUN \r\nvoid\r\ngsl_matrix_float_set(gsl_matrix_float * m, const size_t i, const size_t j, const float x)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(1)) \r\n    {\r\n      if (i >= m->size1)\r\n        {\r\n          GSL_ERROR_VOID(\"first index out of range\", GSL_EINVAL) ;\r\n        }\r\n      else if (j >= m->size2)\r\n        {\r\n          GSL_ERROR_VOID(\"second index out of range\", GSL_EINVAL) ;\r\n        }\r\n    }\r\n#endif\r\n  m->data[i * m->tda + j] = x ;\r\n}\r\n\r\nINLINE_FUN \r\nfloat *\r\ngsl_matrix_float_ptr(gsl_matrix_float * m, const size_t i, const size_t j)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(1)) \r\n    {\r\n      if (i >= m->size1)\r\n        {\r\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\r\n        }\r\n      else if (j >= m->size2)\r\n        {\r\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\r\n        }\r\n    }\r\n#endif\r\n  return (float *) (m->data + (i * m->tda + j)) ;\r\n} \r\n\r\nINLINE_FUN \r\nconst float *\r\ngsl_matrix_float_const_ptr(const gsl_matrix_float * m, const size_t i, const size_t j)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(1)) \r\n    {\r\n      if (i >= m->size1)\r\n        {\r\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\r\n        }\r\n      else if (j >= m->size2)\r\n        {\r\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\r\n        }\r\n    }\r\n#endif\r\n  return (const float *) (m->data + (i * m->tda + j)) ;\r\n} \r\n\r\n#endif\r\n\r\n__END_DECLS\r\n\r\n#endif /* __GSL_MATRIX_FLOAT_H__ */\r\n", "meta": {"hexsha": "3793a89e0d95e8e9a9b72763ee1999eabc8b3222", "size": 13352, "ext": "h", "lang": "C", "max_stars_repo_path": "deps/include/gsl/gsl_matrix_float.h", "max_stars_repo_name": "berkus/music-cs", "max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "deps/include/gsl/gsl_matrix_float.h", "max_issues_repo_name": "berkus/music-cs", "max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "deps/include/gsl/gsl_matrix_float.h", "max_forks_repo_name": "berkus/music-cs", "max_forks_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1922005571, "max_line_length": 133, "alphanum_fraction": 0.6460455362, "num_tokens": 3177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2720245510940225, "lm_q2_score": 0.04603390076328728, "lm_q1q2_score": 0.012522351190240004}}
{"text": "#include <mpi.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <gsl/gsl_math.h>\n\n#include \"allvars.h\"\n#include \"proto.h\"\n\n#ifdef MPISENDRECV_SIZELIMIT\n\n\n#undef MPI_Sendrecv\n\n\nint MPI_Sizelimited_Sendrecv(void *sendbuf, int sendcount, MPI_Datatype sendtype,\n\t\t\t     int dest, int sendtag, void *recvbuf, int recvcount,\n\t\t\t     MPI_Datatype recvtype, int source, int recvtag, MPI_Comm comm,\n\t\t\t     MPI_Status * status)\n{\n  int iter = 0, size_sendtype, size_recvtype, send_now, recv_now;\n  int count_limit;\n\n\n  if(dest != source)\n    endrun(3);\n\n  MPI_Type_size(sendtype, &size_sendtype);\n  MPI_Type_size(recvtype, &size_recvtype);\n\n  if(dest == ThisTask)\n    {\n      memcpy(recvbuf, sendbuf, recvcount * size_recvtype);\n      return 0;\n    }\n\n  count_limit = (int) ((((long long) MPISENDRECV_SIZELIMIT) * 1024 * 1024) / size_sendtype);\n\n  while(sendcount > 0 || recvcount > 0)\n    {\n      if(sendcount > count_limit)\n\t{\n\t  send_now = count_limit;\n\t  if(iter == 0)\n\t    {\n\t      printf(\"imposing size limit on MPI_Sendrecv() on task=%d (send of size=%d)\\n\",\n\t\t     ThisTask, sendcount * size_sendtype);\n\t      fflush(stdout);\n\t    }\n\t  iter++;\n\t}\n      else\n\tsend_now = sendcount;\n\n      if(recvcount > count_limit)\n\trecv_now = count_limit;\n      else\n\trecv_now = recvcount;\n\n      MPI_Sendrecv(sendbuf, send_now, sendtype, dest, sendtag,\n\t\t   recvbuf, recv_now, recvtype, source, recvtag, comm, status);\n\n      sendcount -= send_now;\n      recvcount -= recv_now;\n\n      sendbuf += send_now * size_sendtype;\n      recvbuf += recv_now * size_recvtype;\n    }\n\n  return 0;\n}\n\n#endif\n", "meta": {"hexsha": "56566cb13abba1f5339b40e9c8c42c585bf14256", "size": 1618, "ext": "c", "lang": "C", "max_stars_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/sizelimited_sendrecv.c", "max_stars_repo_name": "egpbos/egp", "max_stars_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/sizelimited_sendrecv.c", "max_issues_repo_name": "egpbos/egp", "max_issues_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/sizelimited_sendrecv.c", "max_forks_repo_name": "egpbos/egp", "max_forks_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5733333333, "max_line_length": 92, "alphanum_fraction": 0.6557478368, "num_tokens": 458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29746994260479465, "lm_q2_score": 0.04208773242132242, "lm_q1q2_score": 0.012519835347736733}}
{"text": "/* WidiPadi is a motif discovery tool for DNA sequences */\n/* Copyright (C) 2006 Bioinformatics Centre */\n/* Author: Eivind Valen and Ole Winther */\n\n/* This program is free software; you can redistribute it and/or */\n/* modify it under the terms of the GNU General Public License */\n/* as published by the Free Software Foundation; either version 2 */\n/* of the License, or (at your option) any later version. */\n\n/* This program is distributed in the hope that it will be useful, */\n/* but WITHOUT ANY WARRANTY; without even the implied warranty of */\n/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the */\n/* GNU General Public License for more details. */\n\n/* You should have received a copy of the GNU General Public License */\n/* along with this program; if not, write to the Free Software */\n/* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA. */\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <getopt.h>\n#include <gsl/gsl_sf_gamma.h>\n\n#include \"error.h\"\n#include \"sesa.h\"\n\n#define USAGE \"Usage: widipadi [OPTIONS] SEQUENCES\"\n\nenum bool {false, true};\n\n/* FUNCTION PROTOTYPES */\nPSSM hits_to_count_matrix(SESA sesa, struct HitTable *hits, const double threshold, int length, int alphabetSize);\nint compare_hit_scores(const void *hit1, const void *hit2);\nint parse_options(int argc, char **argv);\nvoid print_help();\n\n/* Acceptance */\nint accept_all(SESA sesa, struct HitTable *hits);\nint acceptIf_over_300_hits(SESA sesa, struct HitTable *hits);\nint acceptIf_required_presence(SESA sesa, struct HitTable *hits);\n\n\n/* DEFAULTS */\nunsigned int length = 8;\nunsigned int alphabetSize = 4;\nunsigned int mismatches = 1;\nint (*acceptanceFunc)(SESA, struct HitTable *) = acceptIf_required_presence;  \ndouble required_presence = 0.7;\nunsigned int exhaustive = false;\n\n/**\n * Prints a help message to stdout.\n */\nvoid print_help() {\n  printf(USAGE);\n  printf(\"\\nOptions:\\n\");\n/*   printf(\"  -a                 Size of alphabet\\n\"); */\n  printf(\"  -h                 Prints this help and exits\\n\");\n  printf(\"  -l LENGTH          Length of WM\\n\");\n  printf(\"  -m MISMATCHES      Number of mismatches\\n\");\n  printf(\"  -r RATIO           Sets the ratio of sequences where the PSSM must match\\n\");\n  printf(\"  -x                 Do exhaustive search\\n\");\n  printf(\"\\n\");\n}\n\n\n/**\n * Parses command line options\n */\nint parse_options(int argc, char **argv) {\n  int count = 1;\n  int c;\n\n  while ((c = getopt(argc, argv, \"hl:m:r:x\")) != -1) {\n    count++;\n    switch (c) {\n    case 'h': \n      print_help(); \n      exit(EXIT_SUCCESS);\n    case 'l':\n      length = (unsigned int) strtol(optarg, (char **) NULL, 0);\n      count++;\n      break;\n    case 'm':\n      mismatches = (unsigned int) strtol(optarg, (char **) NULL, 0);\n      count++;\n      break;\n    case 'r':\n      acceptanceFunc = acceptIf_required_presence;  \n      required_presence = strtod(optarg, (char **) NULL);\n      count++;\n      break;\n    case 'x':\n      exhaustive = true;\n      break;\n    default: \n      fprintf(stderr, USAGE);\n      exit(EXIT_FAILURE);\n    }\n  }\n\n  return count;\n}\n\n\n/*\n * Converts all hits above scoring threshold to a count matrix\n *\n * Only 0th order\n */\nPSSM hits_to_count_matrix(SESA sesa, struct HitTable *hits, const double threshold, int length, int alphabetSize) {\n  PSSM pssm = initMatrix(0, length, alphabetSize);\n  ESA esa = sesa->esa;\n  struct HitEntry *hit;\n  int i, j;\n\n  i = pssm->offsets[pssm->length];\n  while (i--) pssm->counts[i] = 0;\n\n  for (i = 0; i < hits->nScores; i++) {\n    hit = &hits->pScores[i];\n\n    if (hit->score < threshold) \n      break;\n\n    for (j = 0; j < length; j++) {\n      int ltr = esa->pStr[hit->position + j];\n      /*       fprintf(stderr, \"%c\", ind2chr(ltr)); */\n      pssm->counts[ pssm->offsets[j] + ltr ]++;\n    }\n/*     fprintf(stderr, \" (%f)\\n\", hit->score); */\n  }\n\n  return pssm;\n}\n\n\n/**\n * Comparing function for sort. Sorts on scores from low to high.\n */\nint compare_hit_scores(const void *hit1, const void *hit2) {\n  return ((struct HitEntry *)hit2)->score - ((struct HitEntry *)hit1)->score;\n}\n \n\n/**\n * Accepts all PSSMs (for testing)\n */\nint accept_all(SESA sesa, struct HitTable *hits) {\n  return true;\n}\n\n\n/**\n * Accepts PSSMs with more than 300 hits (for testing)\n */\nint acceptIf_over_300_hits(SESA sesa, struct HitTable *hits) {\n  return (hits->nScores > 300 ? true : false);\n}\n\n\n/**\n * Accepts PSSMs with hits present in at least \"required_presence\" of\n * the sequences\n */\nint acceptIf_required_presence(SESA sesa, struct HitTable *hits) {\n  int present[sesa->nSeq];\n  int i, j;\n\n  i = sesa->nSeq;\n  while(i--) present[i] = 0;\n  \n  i = hits->nScores;\n  while (i--) present[ sesa->seq[ hits->pScores[i].position ] ]++;\n\n  j = 0;\n  i = sesa->nSeq;\n  while (i--) if (present[i]) j++;\n\n\n  return ( ((double) j / (double) sesa->nSeq)  > required_presence ? true : false);\n}\n\n/*                                                                                                \n * Log likelihood scoring\n */\ndouble log_likelihood(ESA esa, PSSM pssm, int *count_bg_all, double *pcount, double *pcount_bg) {\n  int pcount_tot = 0, pcount_bg_tot = 0, count_tot = 0, count_bg_tot = 0;\n  int alphlen = pssm->alphabetSize;\n  int count_bg[alphlen];\n  int ccount, ltr, pos, ord, i;\n  double ll = 0.0;\n\n  i = alphlen;\n  while (i--) count_bg[i] = count_bg_all[i];\n\n  pos = pssm->length;\n  while (pos--) {\n    ltr = alphlen;\n    while(ltr--) {\n      ccount = pssm->counts[pos * alphlen + ltr];\n      count_bg[ltr] -= ccount ;\n      ll += gsl_sf_lngamma( ccount + pcount[ltr] );    \n    }\n  }\n\n  ltr = alphlen;\n  while (ltr--) {\n    pcount_tot += pcount[ltr];\n    pcount_bg_tot += pcount_bg[ltr];\n    count_tot += pssm->counts[ltr];   \n    count_bg_tot += count_bg[ltr];\n    ll += gsl_sf_lngamma( count_bg[ltr] + pcount_bg[ltr] ); \n  }\n\n\n  ll -= alphlen * gsl_sf_lngamma( count_tot + pcount_tot ) + gsl_sf_lngamma(count_bg_tot + pcount_bg_tot );\n  \n  return ll;\n}\n\n\n\n/*                                                                                                \n * Log likelihood scoring\n */\ndouble higher_log_likelihood(ESA esa, PSSM pssm, double *pcount, double *pcount_bg) {\n  int pos, lcpi, skip, curSuf, i, j, p;\n  int numSufs = getSize(esa);\n  int curEsaIndex = 0;\n  int order = 2;\n  int wcount[order+1];\n\n  i = order+1;\n  while (i--) wcount[i] = 0;\n\n  /* Iterate all suffixes */\n  while(curEsaIndex < numSufs){\n    lcpi = getLcp(esa, curEsaIndex);\n    curSuf = getSuf(esa, curEsaIndex);\n    skip = getSkip(esa, curEsaIndex);\n\n\n    /* We can skip if the lcp is longer than the order */\n    if (lcpi > order) {\n\n      /* FIX: HACK */\n      if (skip == 0) {\n\tcurEsaIndex++;\n\tcontinue;\n      }\n\n      /* Count all the skipped words */\n      i = order+1;\n      while (i--) wcount[i] += skip - curEsaIndex;\n\n      curEsaIndex = skip;\n      continue;\n\n    } else {\n\n      pos = pssm->length;\n      while (pos--) { }\n\n      /* Print the hits */\n      p = 1;\n      for (j = 0; j <= order; j++)\n\tif (ind2chr(esa->pStr[getSuf(esa, curEsaIndex-1)+j]) == '-')\n\t  p = 0;\n\n      if (p) {\n\tfor (i = 0; i <= order; i++) fprintf(stderr, \"%c\", ind2chr(esa->pStr[getSuf(esa, curEsaIndex-1)+i]));\n\tfprintf(stderr, \": %5i\\n\", wcount[2]);\n      }\n\n      wcount[order] = 1;\n\n      /* For higher order models the first columns have fewer letters */\n      i = order;\n      while (i--) {\n\tif (i >= lcpi) {\t  \n\n\t  p = 1;\n\t  for (j = 0; j <= i; j++)\n\t    if (ind2chr(esa->pStr[getSuf(esa, curEsaIndex-1)+j]) == '-')\n\t\tp = 0;\n\n\t  if (p) {\n\t    for (j = 0; j <= i; j++) fprintf(stderr, \"%c\", ind2chr(esa->pStr[getSuf(esa, curEsaIndex-1)+j]));\n\t    for (j = i; j < order; j++) fprintf(stderr, \" \");\n\t    fprintf(stderr, \": %5i\\n\", wcount[i]);\n\t  }\n\n\t  wcount[i] = 1;\n\t}\n      }\n\n\n      curEsaIndex++;\n    }\n\n  }\n  \n  exit(0);\n}\n\nvoid print_esa (ESA esa) {\n  int numSufs = getSize(esa);\n  int i,j;\n\n  for (i = 0; i < numSufs; i++) {\n    fprintf(stderr, \"%4i: SUF(%3i) LCP(%3i) SKIP(%4i) \", i, getSuf(esa, i), getLcp(esa, i), getSkip(esa, i));\n\n    for (j = 0; j < 8; j++) {\n      fprintf(stderr, \"%c\", ind2chr(esa->pStr[getSuf(esa, i)+j]));\n    }\n    fprintf(stderr, \"\\n\");\n  }\n}\n\nint main(int argc, char **argv) {\n  PSSMScoreTable results;\n  struct HitTable *hits = NULL;\n  PSSM pssm, count;\n  SESA sesa;\n  unsigned int arg_count, j;\n  int i;\n\n  arg_count = parse_options(argc, argv);\n\n  printf(\"Reading file: %s  (%i)\\n\", argv[arg_count], argc - arg_count);\n  if (!argv[arg_count]) {\n    fprintf(stderr, \"Need an input file\\n\");\n    exit(EXIT_FAILURE);\n  }\n  \n  sesa = build_SESA(argc - arg_count, &argv[arg_count], \"ACGT\", \"N\", 0);\n\n  if (!sesa) {\n    fprintf(stderr, \"%s\\n\", getError());\n    exit(EXIT_FAILURE);\n  }\n\n  \n  printf(\"Searching %s for motifs of length %i with %i mismatch%s\\n\", (exhaustive ? \"exhaustively\" : \"exclusively\"), length, mismatches, (mismatches > 1 ? \"es\" : \"\"));\n\n  if (exhaustive) {\n    /* Exhaustive search searches for all words og length n.  */\n    results = SESA_exhaustive_search(sesa, length, mismatches, alphabetSize, acceptanceFunc);\n  } else {\n    /* Exclusive search only searches for PSSMs representing words present in the sequence.  */\n    results = SESA_exclusive_search(sesa, length, mismatches, alphabetSize, acceptanceFunc);\n  }\n\n  /** \n   * Both the above methods return a list of integers that uniquely\n   * identifies pssms.  We do not return the hits of the PSSMs even\n   * though we have searched with them since this might be very(!)\n   * memory demanding, depending on criteria used for acceptance.\n   *\n   * If we know the criteria is strict we might considering altering\n   * this to avoid re-searching and thus speed up the process.\n   */\n\n  pssm = initMatrix(0, length, alphabetSize);\n\n  for (i = 0; i < results->nPssm; i++) {\n    /* Sets the pssm to the values corresponding to the ID*/\n    set_mismatch_scores(pssm, results->pssmNr[i]);    \n    calcAndSetThresholds(pssm, -((double)mismatches)-0.5);    \n\n    /* Search with the PSSM again */\n    init_hittable();                 /* Creates a hittable */\n    hits = SESA_search(sesa, pssm);  /* Searches again */\n\n    /* Sort the hits */\n    qsort((void*)hits->pScores, hits->nScores, sizeof(struct HitEntry), compare_hit_scores);\n\n    printf(\"\\n\\n\");\n    print_pssm(pssm);\n    for (j = 0; j <= mismatches; j++) {\n      printf(\"Count matrix for %i mismatches\\n\", j);\n      count = hits_to_count_matrix(sesa, hits, -((double)j)-0.5, pssm->length, pssm->alphabetSize);\n\n      double ost1[] = {1.0, 1.0, 1.0, 1.0};\n      double ost2[] = {1.0, 1.0, 1.0, 1.0};\n\n/*       double foo = log_likelihood(count, sesa->bg, ost1, ost2); */\n\n      double foo = higher_log_likelihood(sesa->esa, count, ost1, ost2); \n\n/*       fprintf(stderr, \"LL: %g\\n\", foo); */\n/*       print_counts(count);  */\n      printf(\"\\n\\n\");\n    }\n    \n    release_hits(hits); /* Frees the allocated hittable*/\n  }\n\n\n  exit(EXIT_SUCCESS);\n}\n", "meta": {"hexsha": "a0ca57bdbffa564c2fc93f260eff9a5ecec34ff2", "size": 10861, "ext": "c", "lang": "C", "max_stars_repo_path": "src/MoAn/widipadi.c", "max_stars_repo_name": "kipkurui/gimmemotifs", "max_stars_repo_head_hexsha": "51bd0c6700877f79179f08e5bab7de70fc2eab94", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-07-14T08:28:25.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-14T08:28:25.000Z", "max_issues_repo_path": "src/MoAn/widipadi.c", "max_issues_repo_name": "kipkurui/gimmemotifs", "max_issues_repo_head_hexsha": "51bd0c6700877f79179f08e5bab7de70fc2eab94", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MoAn/widipadi.c", "max_forks_repo_name": "kipkurui/gimmemotifs", "max_forks_repo_head_hexsha": "51bd0c6700877f79179f08e5bab7de70fc2eab94", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9503722084, "max_line_length": 167, "alphanum_fraction": 0.603535586, "num_tokens": 3241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29746994260479465, "lm_q2_score": 0.0420877273148584, "lm_q1q2_score": 0.012519833828717176}}
{"text": "/* vector/gsl_vector_uint.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_VECTOR_UINT_H__\n#define __GSL_VECTOR_UINT_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_inline.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_block_uint.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size;\n  size_t stride;\n  unsigned int *data;\n  gsl_block_uint *block;\n  int owner;\n} \ngsl_vector_uint;\n\ntypedef struct\n{\n  gsl_vector_uint vector;\n} _gsl_vector_uint_view;\n\ntypedef _gsl_vector_uint_view gsl_vector_uint_view;\n\ntypedef struct\n{\n  gsl_vector_uint vector;\n} _gsl_vector_uint_const_view;\n\ntypedef const _gsl_vector_uint_const_view gsl_vector_uint_const_view;\n\n\n/* Allocation */\n\ngsl_vector_uint *gsl_vector_uint_alloc (const size_t n);\ngsl_vector_uint *gsl_vector_uint_calloc (const size_t n);\n\ngsl_vector_uint *gsl_vector_uint_alloc_from_block (gsl_block_uint * b,\n                                                     const size_t offset, \n                                                     const size_t n, \n                                                     const size_t stride);\n\ngsl_vector_uint *gsl_vector_uint_alloc_from_vector (gsl_vector_uint * v,\n                                                      const size_t offset, \n                                                      const size_t n, \n                                                      const size_t stride);\n\nvoid gsl_vector_uint_free (gsl_vector_uint * v);\n\n/* Views */\n\n_gsl_vector_uint_view \ngsl_vector_uint_view_array (unsigned int *v, size_t n);\n\n_gsl_vector_uint_view \ngsl_vector_uint_view_array_with_stride (unsigned int *base,\n                                         size_t stride,\n                                         size_t n);\n\n_gsl_vector_uint_const_view \ngsl_vector_uint_const_view_array (const unsigned int *v, size_t n);\n\n_gsl_vector_uint_const_view \ngsl_vector_uint_const_view_array_with_stride (const unsigned int *base,\n                                               size_t stride,\n                                               size_t n);\n\n_gsl_vector_uint_view \ngsl_vector_uint_subvector (gsl_vector_uint *v, \n                            size_t i, \n                            size_t n);\n\n_gsl_vector_uint_view \ngsl_vector_uint_subvector_with_stride (gsl_vector_uint *v, \n                                        size_t i,\n                                        size_t stride,\n                                        size_t n);\n\n_gsl_vector_uint_const_view \ngsl_vector_uint_const_subvector (const gsl_vector_uint *v, \n                                  size_t i, \n                                  size_t n);\n\n_gsl_vector_uint_const_view \ngsl_vector_uint_const_subvector_with_stride (const gsl_vector_uint *v, \n                                              size_t i, \n                                              size_t stride,\n                                              size_t n);\n\n/* Operations */\n\nvoid gsl_vector_uint_set_zero (gsl_vector_uint * v);\nvoid gsl_vector_uint_set_all (gsl_vector_uint * v, unsigned int x);\nint gsl_vector_uint_set_basis (gsl_vector_uint * v, size_t i);\n\nint gsl_vector_uint_fread (FILE * stream, gsl_vector_uint * v);\nint gsl_vector_uint_fwrite (FILE * stream, const gsl_vector_uint * v);\nint gsl_vector_uint_fscanf (FILE * stream, gsl_vector_uint * v);\nint gsl_vector_uint_fprintf (FILE * stream, const gsl_vector_uint * v,\n                              const char *format);\n\nint gsl_vector_uint_memcpy (gsl_vector_uint * dest, const gsl_vector_uint * src);\n\nint gsl_vector_uint_reverse (gsl_vector_uint * v);\n\nint gsl_vector_uint_swap (gsl_vector_uint * v, gsl_vector_uint * w);\nint gsl_vector_uint_swap_elements (gsl_vector_uint * v, const size_t i, const size_t j);\n\nunsigned int gsl_vector_uint_max (const gsl_vector_uint * v);\nunsigned int gsl_vector_uint_min (const gsl_vector_uint * v);\nvoid gsl_vector_uint_minmax (const gsl_vector_uint * v, unsigned int * min_out, unsigned int * max_out);\n\nsize_t gsl_vector_uint_max_index (const gsl_vector_uint * v);\nsize_t gsl_vector_uint_min_index (const gsl_vector_uint * v);\nvoid gsl_vector_uint_minmax_index (const gsl_vector_uint * v, size_t * imin, size_t * imax);\n\nint gsl_vector_uint_add (gsl_vector_uint * a, const gsl_vector_uint * b);\nint gsl_vector_uint_sub (gsl_vector_uint * a, const gsl_vector_uint * b);\nint gsl_vector_uint_mul (gsl_vector_uint * a, const gsl_vector_uint * b);\nint gsl_vector_uint_div (gsl_vector_uint * a, const gsl_vector_uint * b);\nint gsl_vector_uint_scale (gsl_vector_uint * a, const double x);\nint gsl_vector_uint_add_constant (gsl_vector_uint * a, const double x);\n\nint gsl_vector_uint_equal (const gsl_vector_uint * u, \n                            const gsl_vector_uint * v);\n\nint gsl_vector_uint_isnull (const gsl_vector_uint * v);\nint gsl_vector_uint_ispos (const gsl_vector_uint * v);\nint gsl_vector_uint_isneg (const gsl_vector_uint * v);\nint gsl_vector_uint_isnonneg (const gsl_vector_uint * v);\n\nINLINE_DECL unsigned int gsl_vector_uint_get (const gsl_vector_uint * v, const size_t i);\nINLINE_DECL void gsl_vector_uint_set (gsl_vector_uint * v, const size_t i, unsigned int x);\nINLINE_DECL unsigned int * gsl_vector_uint_ptr (gsl_vector_uint * v, const size_t i);\nINLINE_DECL const unsigned int * gsl_vector_uint_const_ptr (const gsl_vector_uint * v, const size_t i);\n\n#ifdef HAVE_INLINE\n\nINLINE_FUN\nunsigned int\ngsl_vector_uint_get (const gsl_vector_uint * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= v->size))\n    {\n      GSL_ERROR_VAL (\"index out of range\", GSL_EINVAL, 0);\n    }\n#endif\n  return v->data[i * v->stride];\n}\n\nINLINE_FUN\nvoid\ngsl_vector_uint_set (gsl_vector_uint * v, const size_t i, unsigned int x)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= v->size))\n    {\n      GSL_ERROR_VOID (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  v->data[i * v->stride] = x;\n}\n\nINLINE_FUN\nunsigned int *\ngsl_vector_uint_ptr (gsl_vector_uint * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= v->size))\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return (unsigned int *) (v->data + i * v->stride);\n}\n\nINLINE_FUN\nconst unsigned int *\ngsl_vector_uint_const_ptr (const gsl_vector_uint * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= v->size))\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return (const unsigned int *) (v->data + i * v->stride);\n}\n#endif /* HAVE_INLINE */\n\n__END_DECLS\n\n#endif /* __GSL_VECTOR_UINT_H__ */\n\n\n", "meta": {"hexsha": "d2f6cb35e38ea5da48f6d91b3e4614fe26cd949b", "size": 7506, "ext": "h", "lang": "C", "max_stars_repo_path": "gsl-an/gsl/gsl_vector_uint.h", "max_stars_repo_name": "juandesant/astrometry.net", "max_stars_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_stars_repo_licenses": ["Net-SNMP", "Xnet"], "max_stars_count": 460.0, "max_stars_repo_stars_event_min_datetime": "2015-01-06T13:20:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T00:37:55.000Z", "max_issues_repo_path": "gsl-an/gsl/gsl_vector_uint.h", "max_issues_repo_name": "juandesant/astrometry.net", "max_issues_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_issues_repo_licenses": ["Net-SNMP", "Xnet"], "max_issues_count": 208.0, "max_issues_repo_issues_event_min_datetime": "2015-01-08T20:26:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T15:21:34.000Z", "max_forks_repo_path": "gsl-an/gsl/gsl_vector_uint.h", "max_forks_repo_name": "juandesant/astrometry.net", "max_forks_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_forks_repo_licenses": ["Net-SNMP", "Xnet"], "max_forks_count": 173.0, "max_forks_repo_forks_event_min_datetime": "2015-01-08T18:01:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T07:27:04.000Z", "avg_line_length": 32.4935064935, "max_line_length": 104, "alphanum_fraction": 0.6761257661, "num_tokens": 1771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215925474903, "lm_q2_score": 0.029312227677479034, "lm_q1q2_score": 0.012496435584577486}}
{"text": "#ifndef H_LASER_DATA_INLINE\n#define H_LASER_DATA_INLINE\n\n//#include <gsl/gsl_math.h>\n//#include <gsl/gsl_vector.h>\n#include <limits>\n\n//#include \"csm.h\"\n\n/* Simple inline functions */\n\n/*#warning Seen ld_valid_ray*/\n\nINLINE int ld_valid_ray(LDP ld, int i) { return (i >= 0) && (i < ld->nrays) && (ld->valid[i]); }\n\nINLINE int ld_valid_alpha(LDP ld, int i) { return ld->alpha_valid[i] != 0; }\n\nINLINE void ld_set_null_correspondence(LDP ld, int i) {\n  ld->corr[i].valid = 0;\n  ld->corr[i].j1 = -1;\n  ld->corr[i].j2 = -1;\n  ld->corr[i].dist2_j1 = std::numeric_limits<double>::quiet_NaN();  // GSL_NAN;\n}\n\nINLINE void ld_set_correspondence(LDP ld, int i, int j1, int j2) {\n  ld->corr[i].valid = 1;\n  ld->corr[i].j1 = j1;\n  ld->corr[i].j2 = j2;\n}\n\n/** -1 if not found */\n\nINLINE int ld_next_valid(LDP ld, int i, int dir) {\n  int j;\n  for (j = i + dir; (j < ld->nrays) && (j >= 0) && !ld_valid_ray(ld, j); j += dir)\n    ;\n  return ld_valid_ray(ld, j) ? j : -1;\n}\n\nINLINE int ld_next_valid_up(LDP ld, int i) { return ld_next_valid(ld, i, +1); }\n\nINLINE int ld_next_valid_down(LDP ld, int i) { return ld_next_valid(ld, i, -1); }\n\nINLINE int ld_valid_corr(LDP ld, int i) { return ld->corr[i].valid; }\n\n#endif\n", "meta": {"hexsha": "20384def0e35a5b2919a86964d82c1d9035d8185", "size": 1201, "ext": "h", "lang": "C", "max_stars_repo_path": "include/csm/laser_data_inline.h", "max_stars_repo_name": "smallsunsun1/imu_veh_calib", "max_stars_repo_head_hexsha": "0b84e90ad3582a7d303bfc2e4c3ed198c780bf0b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/csm/laser_data_inline.h", "max_issues_repo_name": "smallsunsun1/imu_veh_calib", "max_issues_repo_head_hexsha": "0b84e90ad3582a7d303bfc2e4c3ed198c780bf0b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/csm/laser_data_inline.h", "max_forks_repo_name": "smallsunsun1/imu_veh_calib", "max_forks_repo_head_hexsha": "0b84e90ad3582a7d303bfc2e4c3ed198c780bf0b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-23T06:35:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T01:59:48.000Z", "avg_line_length": 25.5531914894, "max_line_length": 96, "alphanum_fraction": 0.6361365529, "num_tokens": 418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.02800752253285321, "lm_q1q2_score": 0.012478178491672447}}
{"text": "#include \"stdlib.h\"\n#include \"stdio.h\"\n#include \"/home/lillian/work/install_fpdebug/valgrind-3.7.0/fpdebug/fpdebug.h\"\n#include <gsl/gsl_sf.h>\nint main(int argc, const char * argv[]) {\nunsigned long int hexdouble;\ndouble a;\nsscanf(argv[1], \"%lX\", &hexdouble);\na = *(double*)(&hexdouble);\ndouble result = gsl_sf_Si(a);\n//printf(\"%.15f\\n\", result);\nVALGRIND_PRINT_ERROR(\"result\", &result);\nreturn 0;\n}", "meta": {"hexsha": "b134ae9b55c2204bbf4041034ba13a8c5deb739c", "size": 398, "ext": "c", "lang": "C", "max_stars_repo_path": "others_ori/gsl_sf_Si.c", "max_stars_repo_name": "floatfeather/FpGenetic", "max_stars_repo_head_hexsha": "57bee06e637084c0f9d4b34b77d6ca8a9ad4c559", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "others_ori/gsl_sf_Si.c", "max_issues_repo_name": "floatfeather/FpGenetic", "max_issues_repo_head_hexsha": "57bee06e637084c0f9d4b34b77d6ca8a9ad4c559", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "others_ori/gsl_sf_Si.c", "max_forks_repo_name": "floatfeather/FpGenetic", "max_forks_repo_head_hexsha": "57bee06e637084c0f9d4b34b77d6ca8a9ad4c559", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4285714286, "max_line_length": 78, "alphanum_fraction": 0.7035175879, "num_tokens": 123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552953503957266, "lm_q2_score": 0.028007518983365013, "lm_q1q2_score": 0.012478176910270618}}
{"text": "/**\n@file\n\nCopyright John Reid 2006\n\n*/\n\n#include \"biopsy/defs.h\"\n\n#include <gsl/gsl_rng.h>\n\n\nnamespace biopsy {\n\ngsl_rng *\nget_gsl_rng();\n\n} //namespace biopsy\n\n\n", "meta": {"hexsha": "314ba6dff7cd3c3afb32e62d607116c11f8d1d45", "size": 163, "ext": "h", "lang": "C", "max_stars_repo_path": "C++/include/biopsy/gsl.h", "max_stars_repo_name": "JohnReid/biopsy", "max_stars_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "C++/include/biopsy/gsl.h", "max_issues_repo_name": "JohnReid/biopsy", "max_issues_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "C++/include/biopsy/gsl.h", "max_forks_repo_name": "JohnReid/biopsy", "max_forks_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 7.7619047619, "max_line_length": 24, "alphanum_fraction": 0.6687116564, "num_tokens": 46, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3242353989809524, "lm_q2_score": 0.03846619408510855, "lm_q1q2_score": 0.012472101786463921}}
{"text": "///\n/// @file\n///\n/// @author Mirko Myllykoski (mirkom@cs.umu.se), Ume\u00e5 University\n///\n/// @internal LICENSE\n///\n/// Copyright (c) 2019-2020, Ume\u00e5 Universitet\n///\n/// Redistribution and use in source and binary forms, with or without\n/// modification, are permitted provided that the following conditions are met:\n///\n/// 1. Redistributions of source code must retain the above copyright notice,\n///    this list of conditions and the following disclaimer.\n///\n/// 2. Redistributions in binary form must reproduce the above copyright notice,\n///    this list of conditions and the following disclaimer in the documentation\n///    and/or other materials provided with the distribution.\n///\n/// 3. Neither the name of the copyright holder nor the names of its\n///    contributors may be used to endorse or promote products derived from this\n///    software without specific prior written permission.\n///\n/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n/// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n/// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n/// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n/// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n/// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n/// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n/// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n/// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n/// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n/// POSSIBILITY OF SUCH DAMAGE.\n///\n\n#include <starneig_test_config.h>\n#include <starneig/configuration.h>\n#include \"solvers.h\"\n#include \"../common/common.h\"\n#include \"../common/parse.h\"\n#include \"../common/local_pencil.h\"\n#ifdef STARNEIG_ENABLE_MPI\n#include \"../common/starneig_pencil.h\"\n#endif\n#include \"../common/threads.h\"\n#include <starneig/starneig.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <cblas.h>\n#include <omp.h>\n\n#ifdef MAGMA_FOUND\n#include <cuda_runtime_api.h>\n#include <cuda.h>\n#include <magma_auxiliary.h>\n#include <magma_d.h>\n#endif\n\nstatic hook_solver_state_t lapack_prepare(\n    int argc, char * const *argv, struct hook_data_env *env)\n{\n    return (hook_solver_state_t) env->data;\n}\n\nstatic int lapack_finalize(hook_solver_state_t state, struct hook_data_env *env)\n{\n    return 0;\n}\n\nstatic int lapack_run(hook_solver_state_t state)\n{\n    pencil_t data = (pencil_t) state;\n\n    extern void dgehrd_(\n        int const *,    // the order of the matrix A\n        int const *,    // left bound\n        int const *,    // right bound\n        double *,       // input/output matrix\n        int const *,    // input/output matrix leading dimension\n        double *,       // tau (scalar factors)\n        double *,       // work space\n        int const *,    // work space size\n        int *);         // info\n\n    extern void dormhr_(\n        char const *,   // side\n        char const *,   // transpose\n        int const *,    // row count\n        int const *,    // column count\n        int const *,    // left bound\n        int const *,    // right bound\n        double const *, // elementary reflectors\n        int const *,    // elementary reflector leading dimension\n        double const *, // scalar factors (tau)\n        double *,       // input/output matrix\n        int const *,    // input/output matrix leading dimension\n        double *,       // work space\n        int const *,    // work space size\n        int *);         // info\n\n    extern void dgeqrf_(int const *, int const *, double *, int const *,\n        double *, double *, int const *, int *);\n\n    extern void dormqr_(char const *, char const *, int const *, int const *,\n        int const *, double const *, int const *, double const *, double *,\n        int const *, double*, const int *, int *);\n\n    extern void dgghd3_(char const *, char const *, int const *, int const *,\n        int const *, double *, int const *, double *, int const *, double *,\n        int const *, double *, int const *, double *, int const *, int *);\n\n    int n = LOCAL_MATRIX_N(data->mat_a);\n    double *A = LOCAL_MATRIX_PTR(data->mat_a);\n    int ldA = LOCAL_MATRIX_LD(data->mat_a);\n    double *Q = LOCAL_MATRIX_PTR(data->mat_q);\n    int ldQ = LOCAL_MATRIX_LD(data->mat_q);\n\n    double *B = NULL;\n    int ldB = 0;\n    double *Z = NULL;\n    int ldZ = 0;\n\n    double *tau = NULL;\n    double *work = NULL;\n    int info, ilo = 1, ihi = n;\n\n    threads_set_mode(THREADS_MODE_LAPACK);\n\n    if (data->mat_b != NULL) {\n        B = LOCAL_MATRIX_PTR(data->mat_b);\n        ldB = LOCAL_MATRIX_LD(data->mat_b);\n        Z = LOCAL_MATRIX_PTR(data->mat_z);\n        ldZ = LOCAL_MATRIX_LD(data->mat_z);\n\n        //\n        // allocate workspace\n        //\n\n        int lwork = 0;\n\n        {\n            int _lwork = -1;\n            double dlwork;\n\n            dgeqrf_(&n, &n, B, &ldB, tau, &dlwork, &_lwork, &info);\n            if (info != 0)\n                goto cleanup;\n\n            lwork = MAX(lwork, dlwork);\n        }\n\n        {\n            int _lwork = -1;\n            double dlwork;\n\n            dormqr_(\"L\", \"T\", &n, &n, &n,\n                B, &ldB, tau, A, &ldA, &dlwork, &_lwork, &info);\n            if (info != 0)\n                goto cleanup;\n\n            lwork = MAX(lwork, dlwork);\n        }\n\n        {\n            int _lwork = -1;\n            double dlwork;\n\n            dormqr_(\"R\", \"N\", &n, &n, &n,\n                B, &ldB, tau, Q, &ldQ, &dlwork, &_lwork, &info);\n            if (info != 0)\n                goto cleanup;\n\n            lwork = MAX(lwork, dlwork);\n        }\n\n        {\n            int _lwork = -1;\n            double dlwork;\n\n            dgghd3_(\"V\", \"V\", &n, &ilo, &ihi,\n                A, &ldA, B, &ldB, Q, &ldQ, Z, &ldZ, &dlwork, &_lwork, &info);\n            if (info != 0)\n                goto cleanup;\n\n            lwork = MAX(lwork, dlwork);\n        }\n\n        tau = malloc(n*sizeof(double));\n        work = malloc(lwork*sizeof(double));\n\n        //\n        // reduce\n        //\n\n        // form B = ~Q * R\n        dgeqrf_(&n, &n, B, &ldB, tau, work, &lwork, &info);\n        if (info != 0)\n            goto cleanup;\n\n        // A <- ~Q^T * A\n        dormqr_(\"L\", \"T\", &n, &n, &n, B, &ldB, tau, A, &ldA, work, &lwork,\n            &info);\n        if (info != 0)\n            goto cleanup;\n\n        // Q <- Q * ~Q\n        dormqr_(\"R\", \"N\", &n, &n, &n, B, &ldB, tau, Q, &ldQ, work, &lwork,\n            &info);\n        if (info != 0)\n            goto cleanup;\n\n        // clean B (B <- R)\n        for (int i = 0; i < n; i++)\n            for (int j = i+1; j < n; j++)\n                B[(size_t)i*ldB+j] = 0.0;\n\n        // reduce (A,B) to Hessenberg-triangular form\n        dgghd3_(\"V\", \"V\", &n, &ilo, &ihi,\n            A, &ldA, B, &ldB, Q, &ldQ, Z, &ldZ, work, &lwork, &info);\n        if (info != 0)\n            goto cleanup;\n    }\n    else {\n\n        int lwork = -1;\n        double dlwork;\n\n        // request optimal work space size\n        dgehrd_(&n, &ilo, &ihi, A, &ldA,\n            tau, &dlwork, &lwork, &info);\n\n        if (info != 0)\n            goto cleanup;\n\n        lwork = dlwork;\n        work = malloc(lwork*sizeof(double));\n        tau = malloc(n*sizeof(double));\n\n        // reduce\n        dgehrd_(&n, &ilo, &ihi, A, &ldA,\n            tau, work, &lwork, &info);\n\n        if (info != 0)\n            goto cleanup;\n\n        free(work);\n        work = NULL;\n\n        // request optimal work space size\n        lwork = -1;\n        dormhr_(\"Right\", \"No transpose\", &n, &n, &ilo, &ihi, A, &ldA, tau,\n            Q, &ldQ, &dlwork, &lwork, &info);\n\n        if (info != 0)\n            goto cleanup;\n\n        lwork = dlwork;\n        work = malloc(lwork*sizeof(double));\n\n        // form Q\n        dormhr_(\"Right\", \"No transpose\", &n, &n, &ilo, &ihi, A, &ldA, tau,\n            Q, &ldQ, work, &lwork, &info);\n\n        if (info != 0)\n            goto cleanup;\n\n        for (int i = 0; i < n; i++)\n            for (int j = i+2; j < n; j++)\n                A[i*ldA+j] = 0.0;\n    }\n\ncleanup:\n\n    threads_set_mode(THREADS_MODE_DEFAULT);\n\n    free(work);\n    free(tau);\n    return info;\n}\n\nconst struct hook_solver hessenberg_lapack_solver = {\n    .name = \"lapack\",\n    .desc = \"LAPACK's dgehrd/dgghrd subroutine\",\n    .formats = (hook_data_format_t[]) { HOOK_DATA_FORMAT_PENCIL_LOCAL, 0 },\n    .prepare = &lapack_prepare,\n    .finalize = &lapack_finalize,\n    .run = &lapack_run\n};\n\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n\n#if defined(PDGEHRD_FOUND) && defined(PDORMHR_FOUND) && defined(PDLASET_FOUND)\n\nstatic hook_solver_state_t scalapack_prepare(\n    int argc, char * const *argv, struct hook_data_env *env)\n{\n    return env;\n}\n\nstatic int scalapack_finalize(\n    hook_solver_state_t state, struct hook_data_env *env)\n{\n    return 0;\n}\n\nstatic int has_valid_descr(\n    int matrix_size, int section_size, const starneig_blacs_descr_t *descr)\n{\n    if (descr->m != matrix_size || descr->n != matrix_size)\n        return 0;\n    if (descr->sm != section_size || descr->sn != section_size)\n        return 0;\n    return 1;\n}\n\nstatic int scalapack_run(hook_solver_state_t state)\n{\n    extern void pdgehrd_(int const *, int const *, int const *, double *,\n        int const *, int const *, const starneig_blacs_descr_t *, double *,\n        double *, int const *, int *);\n\n    extern void pdormhr_(char const *, char const *, int const *, int const *,\n        int const *, int const *, double *, int const *, int const *,\n        const starneig_blacs_descr_t *, double *, double *, int const *,\n        int const *, const starneig_blacs_descr_t *, double *, int const *,\n        int *);\n\n    extern void pdlaset_(char const *, int const *, int const *,\n        double const *, double const *, double *, int const *, int const *,\n        const starneig_blacs_descr_t *);\n\n    threads_set_mode(THREADS_MODE_SCALAPACK);\n\n    struct hook_data_env *env = state;\n    pencil_t pencil = (pencil_t) env->data;\n\n    if (pencil->mat_a == NULL) {\n        fprintf(stderr, \"Missing matrix A.\\n\");\n        return -1;\n    }\n\n    if (pencil->mat_b != NULL) {\n        fprintf(stderr, \"Solver does not support generalized cases.\\n\");\n        return -1;\n    }\n\n    int n = STARNEIG_MATRIX_N(pencil->mat_a);\n    int sn = STARNEIG_MATRIX_BN(pencil->mat_a);\n\n    starneig_distr_t distr = STARNEIG_MATRIX_DISTR(pencil->mat_a);\n    starneig_blacs_context_t context = starneig_distr_to_blacs_context(distr);\n\n    starneig_blacs_descr_t desc_a, desc_q;\n    double *local_a, *local_q;\n    STARNEIG_BLACS_MATRIX_DESCR_LOCAL(\n        pencil->mat_a, context, &desc_a, (void **)&local_a);\n    STARNEIG_BLACS_MATRIX_DESCR_LOCAL(\n        pencil->mat_q, context, &desc_q, (void **)&local_q);\n\n    if (!has_valid_descr(n, sn, &desc_a)) {\n        fprintf(stderr, \"Matrix A has invalid dimensions.\\n\");\n        return -1;\n    }\n\n    if (pencil->mat_q != NULL && !has_valid_descr(n, sn, &desc_q)) {\n        fprintf(stderr, \"Matrix Q has invalid dimension.\\n\");\n        return -1;\n    }\n\n    int ilo = 1, ihi = n, ia = 1, ja = 1, ic = 1, jc = 1, lwork, info;\n    double *work = NULL, *tau = NULL, _work;\n\n    lwork = -1;\n    pdgehrd_(&n, &ilo, &ihi, NULL, &ia, &ja, &desc_a, NULL,\n        &_work, &lwork, &info);\n\n    if (info)\n        goto cleanup;\n\n    lwork = _work;\n    work = malloc(lwork*sizeof(double));\n    tau = malloc(n*sizeof(double));\n\n    pdgehrd_(&n, &ilo, &ihi, local_a, &ia, &ja, &desc_a, tau,\n        work, &lwork, &info);\n\n    if (info)\n        goto cleanup;\n\n    lwork = -1;\n    pdormhr_(\"Right\", \"No transpose\", &n, &n, &ilo, &ihi, NULL,\n        &ia, &ja, &desc_a, NULL, NULL, &ic, &jc,\n        &desc_q, &_work, &lwork, &info);\n\n    if (info)\n        goto cleanup;\n\n    free(work);\n    lwork = _work;\n    work = malloc(lwork*sizeof(double));\n\n    pdormhr_(\"Right\", \"No transpose\", &n, &n, &ilo, &ihi, local_a,\n        &ia, &ja, &desc_a, tau, local_q, &ic, &jc,\n        &desc_q, work, &lwork, &info);\n\n    {\n        int nm1 = n-2, one = 1, three = 3;\n        double dzero = 0.0;\n        pdlaset_(\"Lower\", &nm1, &nm1, &dzero, &dzero, local_a, &three,\n            &one, &desc_a);\n    }\n\ncleanup:\n\n    threads_set_mode(THREADS_MODE_DEFAULT);\n    starneig_blacs_gridexit(context);\n\n    free(work);\n    free(tau);\n\n    return info;\n}\n\nconst struct hook_solver hessenberg_scalapack_solver = {\n    .name = \"scalapack\",\n    .desc = \"pdgehrd subroutine from scaLAPACK\",\n    .formats = (hook_data_format_t[]) {\n#ifdef STARNEIG_ENABLE_BLACS\n        HOOK_DATA_FORMAT_PENCIL_BLACS,\n#endif\n        0 },\n    .prepare = &scalapack_prepare,\n    .finalize = &scalapack_finalize,\n    .run = &scalapack_run\n};\n\n#endif // PDGEHRD_FOUND\n\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n\nstruct starpu_state {\n    int argc;\n    char * const *argv;\n    struct hook_data_env *env;\n};\n\nstatic void starpu_print_usage(int argc, char * const *argv)\n{\n    printf(\n        \"  --cores [default,(num)} -- Number of CPU cores\\n\"\n        \"  --gpus [default,(num)} -- Number of GPUS\\n\"\n        \"  --tile-size [default,(num)] -- tile size\\n\"\n        \"  --panel-width [default,(num)] -- Panel width\\n\"\n    );\n}\n\nstatic int starpu_check_args(int argc, char * const *argv, int *argr)\n{\n    struct multiarg_t arg_cores = read_multiarg(\n        \"--cores\", argc, argv, argr, \"default\", NULL);\n    struct multiarg_t arg_gpus = read_multiarg(\n        \"--gpus\", argc, argv, argr, \"default\", NULL);\n    struct multiarg_t tile_size = read_multiarg(\n        \"--tile-size\", argc, argv, argr, \"default\", NULL);\n    struct multiarg_t panel_width = read_multiarg(\n        \"--panel-width\", argc, argv, argr, \"default\", NULL);\n\n    if (arg_cores.type == MULTIARG_INVALID)\n        return -1;\n\n    if (arg_gpus.type == MULTIARG_INVALID)\n        return -1;\n\n    if (tile_size.type == MULTIARG_INVALID ||\n    (tile_size.type == MULTIARG_INT && tile_size.int_value < 1)) {\n        fprintf(stderr, \"Invalid tile size.\\n\");\n        return -1;\n    }\n\n    if (panel_width.type == MULTIARG_INVALID ||\n    (panel_width.type == MULTIARG_INT && panel_width.int_value < 1)) {\n        fprintf(stderr, \"Invalid panel width.\\n\");\n        return -1;\n    }\n\n    return 0;\n}\n\nstatic void starpu_print_args(int argc, char * const *argv)\n{\n    print_multiarg(\"--cores\", argc, argv, \"default\", NULL);\n    print_multiarg(\"--gpus\", argc, argv, \"default\", NULL);\n    print_multiarg(\"--tile-size\", argc, argv, \"default\", NULL);\n    print_multiarg(\"--panel-width\", argc, argv, \"default\", NULL);\n}\n\nstatic hook_solver_state_t starpu_prepare(\n    int argc, char * const *argv, struct hook_data_env *env)\n{\n    struct starpu_state *state = malloc(sizeof(struct starpu_state));\n\n    state->argc = argc;\n    state->argv = argv;\n    state->env = env;\n\n    struct multiarg_t arg_cores = read_multiarg(\n        \"--cores\", argc, argv, NULL, \"default\", NULL);\n    struct multiarg_t arg_gpus = read_multiarg(\n        \"--gpus\", argc, argv, NULL, \"default\", NULL);\n\n    int cores = STARNEIG_USE_ALL;\n    if (arg_cores.type == MULTIARG_INT)\n        cores = arg_cores.int_value;\n\n    int gpus = STARNEIG_USE_ALL;\n    if (arg_gpus.type == MULTIARG_INT)\n        gpus = arg_gpus.int_value;\n\n#ifdef STARNEIG_ENABLE_MPI\n    if (env->format == HOOK_DATA_FORMAT_PENCIL_STARNEIG ||\n    env->format == HOOK_DATA_FORMAT_PENCIL_BLACS)\n        starneig_node_init(cores, gpus, STARNEIG_FAST_DM);\n    else\n#endif\n        starneig_node_init(\n            cores, gpus, STARNEIG_HINT_SM | STARNEIG_AWAKE_WORKERS);\n\n    return state;\n}\n\nstatic int starpu_finalize(hook_solver_state_t state, struct hook_data_env *env)\n{\n    if (state == NULL)\n        return 0;\n\n    starneig_node_finalize();\n\n    free(state);\n    return 0;\n}\n\nstatic int starpu_run(hook_solver_state_t state)\n{\n    int argc = ((struct starpu_state *) state)->argc;\n    char * const *argv = ((struct starpu_state *) state)->argv;\n    struct hook_data_env *env = ((struct starpu_state *) state)->env;\n\n    struct starneig_hessenberg_conf conf;\n    starneig_hessenberg_init_conf(&conf);\n\n    struct multiarg_t tile_size = read_multiarg(\n        \"--tile-size\", argc, argv, NULL, \"default\", NULL);\n    struct multiarg_t panel_width = read_multiarg(\n        \"--panel-width\", argc, argv, NULL, \"default\", NULL);\n\n    if (tile_size.type == MULTIARG_INT)\n        conf.tile_size = tile_size.int_value;\n    if (panel_width.type == MULTIARG_INT)\n        conf.panel_width = panel_width.int_value;\n\n    int ret = 0;\n\n    if (env->format == HOOK_DATA_FORMAT_PENCIL_LOCAL) {\n        pencil_t pencil = (pencil_t) env->data;\n        if (pencil->mat_b != NULL) {\n            ret = starneig_GEP_SM_HessenbergTriangular(\n                LOCAL_MATRIX_N(pencil->mat_a),\n                LOCAL_MATRIX_PTR(pencil->mat_a), LOCAL_MATRIX_LD(pencil->mat_a),\n                LOCAL_MATRIX_PTR(pencil->mat_b), LOCAL_MATRIX_LD(pencil->mat_b),\n                LOCAL_MATRIX_PTR(pencil->mat_q), LOCAL_MATRIX_LD(pencil->mat_q),\n                LOCAL_MATRIX_PTR(pencil->mat_z), LOCAL_MATRIX_LD(pencil->mat_z)\n            );\n        }\n        else {\n            ret = starneig_SEP_SM_Hessenberg_expert(&conf,\n                LOCAL_MATRIX_N(pencil->mat_a), 0, LOCAL_MATRIX_N(pencil->mat_a),\n                LOCAL_MATRIX_PTR(pencil->mat_a), LOCAL_MATRIX_LD(pencil->mat_a),\n                LOCAL_MATRIX_PTR(pencil->mat_q), LOCAL_MATRIX_LD(pencil->mat_q)\n            );\n        }\n    }\n#ifdef STARNEIG_ENABLE_MPI\n    if (env->format == HOOK_DATA_FORMAT_PENCIL_BLACS) {\n        pencil_t pencil = (pencil_t) env->data;\n        if (pencil->mat_b != NULL) {\n#ifdef STARNEIG_GEP_DM_HESSENBERGTRIANGULAR\n            ret = starneig_GEP_DM_HessenbergTriangular(\n                STARNEIG_MATRIX_HANDLE(pencil->mat_a),\n                STARNEIG_MATRIX_HANDLE(pencil->mat_b),\n                STARNEIG_MATRIX_HANDLE(pencil->mat_q),\n                STARNEIG_MATRIX_HANDLE(pencil->mat_z));\n#else\n            fprintf(stderr,\n                \"Solver does not support generalized cases in distributed \"\n                \"memory.\\n\");\n            return -1;\n#endif\n        }\n        else {\n            ret = starneig_SEP_DM_Hessenberg(\n                STARNEIG_MATRIX_HANDLE(pencil->mat_a),\n                STARNEIG_MATRIX_HANDLE(pencil->mat_q));\n        }\n    }\n#endif\n\n    return ret;\n}\n\nconst struct hook_solver hessenberg_starpu_solver = {\n    .name = \"starneig\",\n    .desc = \"StarPU based subroutine\",\n    .formats = (hook_data_format_t[]) {\n        HOOK_DATA_FORMAT_PENCIL_LOCAL,\n#ifdef STARNEIG_ENABLE_BLACS\n        HOOK_DATA_FORMAT_PENCIL_BLACS,\n#endif\n        0 },\n    .print_usage = &starpu_print_usage,\n    .print_args = &starpu_print_args,\n    .check_args = &starpu_check_args,\n    .prepare = &starpu_prepare,\n    .finalize = &starpu_finalize,\n    .run = &starpu_run\n};\n\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n\nstatic void starpu_simple_print_usage(int argc, char * const *argv)\n{\n    printf(\n        \"  --cores [default,(num)} -- Number of CPU cores\\n\"\n        \"  --gpus [default,(num)} -- Number of GPUS\\n\"\n    );\n}\n\nstatic void starpu_simple_print_args(int argc, char * const *argv)\n{\n    print_multiarg(\"--cores\", argc, argv, \"default\", NULL);\n    print_multiarg(\"--gpus\", argc, argv, \"default\", NULL);\n}\n\nstatic int starpu_simple_check_args(int argc, char * const *argv, int *argr)\n{\n    struct multiarg_t arg_cores = read_multiarg(\n        \"--cores\", argc, argv, argr, \"default\", NULL);\n    struct multiarg_t arg_gpus = read_multiarg(\n        \"--gpus\", argc, argv, argr, \"default\", NULL);\n\n    if (arg_cores.type == MULTIARG_INVALID)\n        return -1;\n\n    if (arg_gpus.type == MULTIARG_INVALID)\n        return -1;\n\n    return 0;\n}\n\nstatic hook_solver_state_t starpu_simple_prepare(\n    int argc, char * const *argv, struct hook_data_env *env)\n{\n    struct starpu_state *state = malloc(sizeof(struct starpu_state));\n\n    state->argc = argc;\n    state->argv = argv;\n    state->env = env;\n\n    struct multiarg_t arg_cores = read_multiarg(\n        \"--cores\", argc, argv, NULL, \"default\", NULL);\n    struct multiarg_t arg_gpus = read_multiarg(\n        \"--gpus\", argc, argv, NULL, \"default\", NULL);\n\n    int cores = STARNEIG_USE_ALL;\n    if (arg_cores.type == MULTIARG_INT)\n        cores = arg_cores.int_value;\n\n    int gpus = STARNEIG_USE_ALL;\n    if (arg_gpus.type == MULTIARG_INT)\n        gpus = arg_gpus.int_value;\n\n#ifdef STARNEIG_ENABLE_MPI\n    if (env->format == HOOK_DATA_FORMAT_PENCIL_STARNEIG ||\n    env->format == HOOK_DATA_FORMAT_PENCIL_BLACS)\n        starneig_node_init(cores, gpus, STARNEIG_FAST_DM);\n    else\n#endif\n        starneig_node_init(\n            cores, gpus, STARNEIG_HINT_SM | STARNEIG_AWAKE_WORKERS);\n\n    return state;\n}\n\nstatic int starpu_simple_finalize(\n    hook_solver_state_t state, struct hook_data_env *env)\n{\n    if (state == NULL)\n        return 0;\n\n    starneig_node_finalize();\n\n    free(state);\n    return 0;\n}\n\nstatic int starpu_simple_run(hook_solver_state_t state)\n{\n    struct hook_data_env *env = ((struct starpu_state *) state)->env;\n\n    int ret = 0;\n\n    if (env->format == HOOK_DATA_FORMAT_PENCIL_LOCAL) {\n        pencil_t pencil = (pencil_t) env->data;\n\n        if (pencil->mat_b != NULL) {\n            ret = starneig_GEP_SM_HessenbergTriangular(\n                LOCAL_MATRIX_N(pencil->mat_a),\n                LOCAL_MATRIX_PTR(pencil->mat_a), LOCAL_MATRIX_LD(pencil->mat_a),\n                LOCAL_MATRIX_PTR(pencil->mat_b), LOCAL_MATRIX_LD(pencil->mat_b),\n                LOCAL_MATRIX_PTR(pencil->mat_q), LOCAL_MATRIX_LD(pencil->mat_q),\n                LOCAL_MATRIX_PTR(pencil->mat_z), LOCAL_MATRIX_LD(pencil->mat_z)\n            );\n        }\n        else {\n            ret = starneig_SEP_SM_Hessenberg(LOCAL_MATRIX_N(pencil->mat_a),\n                LOCAL_MATRIX_PTR(pencil->mat_a), LOCAL_MATRIX_LD(pencil->mat_a),\n                LOCAL_MATRIX_PTR(pencil->mat_q), LOCAL_MATRIX_LD(pencil->mat_q)\n            );\n        }\n    }\n#ifdef STARNEIG_ENABLE_MPI\n    if (env->format == HOOK_DATA_FORMAT_PENCIL_BLACS) {\n        pencil_t pencil = (pencil_t) env->data;\n\n        if (pencil->mat_b != NULL) {\n#ifdef STARNEIG_GEP_DM_HESSENBERGTRIANGULAR\n            ret = starneig_GEP_DM_HessenbergTriangular(\n                STARNEIG_MATRIX_HANDLE(pencil->mat_a),\n                STARNEIG_MATRIX_HANDLE(pencil->mat_b),\n                STARNEIG_MATRIX_HANDLE(pencil->mat_q),\n                STARNEIG_MATRIX_HANDLE(pencil->mat_z));\n#else\n            fprintf(stderr,\n                \"Solver does not support distributed memory in generalized \"\n                \"cases.\\n\");\n            return -1;\n#endif\n        }\n        else {\n            ret = starneig_SEP_DM_Hessenberg(\n                STARNEIG_MATRIX_HANDLE(pencil->mat_a),\n                STARNEIG_MATRIX_HANDLE(pencil->mat_q));\n        }\n    }\n#endif\n\n    return ret;\n}\n\nconst struct hook_solver hessenberg_starpu_simple_solver = {\n    .name = \"starneig-simple\",\n    .desc = \"StarPU based subroutine (simplified interface)\",\n    .formats = (hook_data_format_t[]) {\n        HOOK_DATA_FORMAT_PENCIL_LOCAL,\n#ifdef STARNEIG_ENABLE_BLACS\n        HOOK_DATA_FORMAT_PENCIL_BLACS,\n#endif\n        0 },\n    .print_usage = &starpu_simple_print_usage,\n    .print_args = &starpu_simple_print_args,\n    .check_args = &starpu_simple_check_args,\n    .prepare = &starpu_simple_prepare,\n    .finalize = &starpu_simple_finalize,\n    .run = &starpu_simple_run\n};\n\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n\n#ifdef MAGMA_FOUND\n\nstatic hook_solver_state_t magma_dgehrd_prepare(\n    int argc, char * const *argv, struct hook_data_env *env)\n{\n    if (magma_init() != MAGMA_SUCCESS)\n        return NULL;\n    return (hook_solver_state_t) env->data;\n}\n\nstatic int magma_dgehrd_finalize(\n    hook_solver_state_t state, struct hook_data_env *env)\n{\n    magma_finalize();\n    return 0;\n}\n\nstatic int magma_dgehrd_run(hook_solver_state_t state)\n{\n    pencil_t data = (pencil_t) state;\n\n    int n = LOCAL_MATRIX_N(data->mat_a);\n    double *A = LOCAL_MATRIX_PTR(data->mat_a);\n    double *Q = LOCAL_MATRIX_PTR(data->mat_q);\n    int ldA = LOCAL_MATRIX_LD(data->mat_a);\n    int ldQ = LOCAL_MATRIX_LD(data->mat_q);\n\n    int info;\n\n    double *tau = NULL;\n    double *work = NULL;\n    double *dT = NULL;\n\n    threads_set_mode(THREADS_MODE_LAPACK);\n\n    // request optimal work space size\n    double _work;\n    magma_dgehrd(n, 1, n, A, ldA, tau, &_work, -1, dT, &info);\n\n    if (info != 0)\n        goto finalize;\n\n    tau = malloc(LOCAL_MATRIX_N(data->mat_a)*sizeof(double));\n\n    int lwork = _work;\n    work = malloc(lwork*sizeof(double));\n\n    int nb = magma_get_dgehrd_nb(LOCAL_MATRIX_N(data->mat_a));\n    cudaMalloc((void**)&dT, nb*n*sizeof(double));\n\n    // reduce\n    magma_dgehrd(n, 1, n, A, ldA, tau, work, lwork, dT, &info);\n\n    if (info != 0)\n        goto finalize;\n\n    free(work);\n    work = NULL;\n\n    // copy A -> Q\n    for (int i = 0; i < n; i++)\n        memcpy(Q+i*ldQ, A+i*ldA, n*sizeof(double));\n\n    // form Q\n    magma_dorghr(n, 1, n, Q, ldQ, tau, dT, nb, &info);\n\n    if (info != 0)\n        goto finalize;\n\n    // zero entries below the first sub-diagonal\n    for (int i = 0; i < n-1; i++)\n        memset(A+i*ldA+i+2, 0, (n-i-2)*sizeof(double));\n\nfinalize:\n\n    threads_set_mode(THREADS_MODE_DEFAULT);\n\n    cudaFree(dT);\n    free(work);\n    free(tau);\n    return info;\n}\n\nconst struct hook_solver hessenberg_magma_solver = {\n    .name = \"magma\",\n    .desc = \"MAGMA's dgehrd subroutine\",\n    .formats = (hook_data_format_t[]) { HOOK_DATA_FORMAT_PENCIL_LOCAL, 0 },\n    .prepare = &magma_dgehrd_prepare,\n    .finalize = &magma_dgehrd_finalize,\n    .run = &magma_dgehrd_run\n};\n\n#endif // MAGMA_FOUND\n", "meta": {"hexsha": "8dcf72c5c84ccd3cd71dceb35667771ed635a65f", "size": 26422, "ext": "c", "lang": "C", "max_stars_repo_path": "test/hessenberg/solvers.c", "max_stars_repo_name": "NLAFET/StarNEig", "max_stars_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2019-04-28T17:13:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-24T12:30:19.000Z", "max_issues_repo_path": "test/hessenberg/solvers.c", "max_issues_repo_name": "NLAFET/StarNEig", "max_issues_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/hessenberg/solvers.c", "max_forks_repo_name": "NLAFET/StarNEig", "max_forks_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-04-30T12:14:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-14T09:41:23.000Z", "avg_line_length": 29.9909194098, "max_line_length": 80, "alphanum_fraction": 0.581787904, "num_tokens": 6968, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234991142019, "lm_q2_score": 0.028436031089369332, "lm_q1q2_score": 0.01244996263246791}}
{"text": "//===--- Sudoku/precompiled_basic.h                                     ---===//\n//\n// Lists the standard system includes consumed by this library,\n// or project specific include files that are used frequently, but\n// are changed infrequently.\n//\n// - To be used as part of a precompiled header configuration for a project\n//   consuming this library.\n// - Where frequent changes to the Sudoku library code are expected.\n// - Not required when the library itself is added to a precompiled header.\n//\n//===----------------------------------------------------------------------===//\n#pragma once\n\n// STL containers\n#include <array>\n#include <bitset>\n#include <vector>\n// STL\n#include <algorithm>\n#include <iterator>\n#include <limits>\n#include <memory>\n#include <stdexcept>\n#include <utility>\n\n// Libraries\n#include <gsl/gsl>\n", "meta": {"hexsha": "6e1b4bac5b35812523cc2750435b1fe7a2a40118", "size": 823, "ext": "h", "lang": "C", "max_stars_repo_path": "Sudoku/Sudoku/precompiled_basic.h", "max_stars_repo_name": "FeodorFitsner/fwkSudoku", "max_stars_repo_head_hexsha": "760aa5731efe089dc08e51898a37d42f3db5bb10", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-03-17T18:27:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-18T19:26:28.000Z", "max_issues_repo_path": "Sudoku/Sudoku/precompiled_basic.h", "max_issues_repo_name": "FeodorFitsner/fwkSudoku", "max_issues_repo_head_hexsha": "760aa5731efe089dc08e51898a37d42f3db5bb10", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 38.0, "max_issues_repo_issues_event_min_datetime": "2018-12-28T18:15:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-17T01:22:35.000Z", "max_forks_repo_path": "Sudoku/Sudoku/precompiled_basic.h", "max_forks_repo_name": "FeodorFitsner/fwkSudoku", "max_forks_repo_head_hexsha": "760aa5731efe089dc08e51898a37d42f3db5bb10", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-04-20T16:26:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-20T16:26:42.000Z", "avg_line_length": 28.3793103448, "max_line_length": 80, "alphanum_fraction": 0.6221142163, "num_tokens": 156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.14414886038616345, "lm_q2_score": 0.08632348422559333, "lm_q1q2_score": 0.012443431875682236}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef type_f33c5e03_70f2_4879_9504_332323832a40_h\r\n#define type_f33c5e03_70f2_4879_9504_332323832a40_h\r\n\r\n#include <ariel/config.h>\r\n#include <gslib/type.h>\r\n#include <gslib/string.h>\r\n#include <gslib/math.h>\r\n#include <gslib/std.h>\r\n\r\n__ariel_begin__\r\n\r\nstruct ariel_export color\r\n{\r\n    union\r\n    {\r\n        struct { byte red, green, blue, alpha; };\r\n        uint _data;\r\n    };\r\n\r\npublic:\r\n    color() { data() = 0; }\r\n    color(int r, int g, int b) { set_color(r, g, b); }\r\n    color(int r, int g, int b, int a) { set_color(r, g, b, a); }\r\n    uint& data() { return _data; }\r\n    uint data() const { return _data; }\r\n    void set_color(int r, int g, int b) { red = r, green = g, blue = b, alpha = 255; }\r\n    void set_color(int r, int g, int b, int a) { red = r, green = g, blue = b, alpha = a; }\r\n    bool operator !=(const color& cr) const { return blue != cr.blue || green != cr.green || red != cr.red || alpha != cr.alpha; }\r\n    bool operator ==(const color& cr) const { return blue == cr.blue && green == cr.green && red == cr.red && alpha == cr.alpha; }\r\n    color& lerp(const color& c1, const color& c2, float s)\r\n    {\r\n        assert(s >= 0.f && s <= 1.f);\r\n        float t = 1.f - s;\r\n        red = (int)(s * c1.red + t * c2.red);\r\n        green = (int)(s * c1.green + t * c2.green);\r\n        blue = (int)(s * c1.blue + t * c2.blue);\r\n        alpha = (int)(s * c1.alpha + t * c2.alpha);\r\n        return *this;\r\n    }\r\n};\r\n\r\nstruct ariel_export font\r\n{\r\n    enum\r\n    {\r\n        declare_mask(ftm_italic,    0),\r\n        declare_mask(ftm_underline, 1),\r\n        declare_mask(ftm_strikeout, 2),\r\n    };\r\n\r\npublic:\r\n    string      name;\r\n    int         size;\r\n    int         escape;\r\n    int         orient;\r\n    int         weight; /* 0-9 */\r\n    uint        mask;\r\n\r\nprivate:\r\n    friend class fsys_win32;\r\n    friend class fsys_dwrite;\r\n    mutable uint sysfont;\r\n\r\npublic:\r\n    font()\r\n    {\r\n        size = 0;\r\n        escape = 0;\r\n        orient = 0;\r\n        weight = 3;\r\n        mask = 0;\r\n        sysfont = 0;\r\n    }\r\n    font(const font& that)\r\n    {\r\n        name    = that.name;\r\n        size    = that.size;\r\n        escape  = that.escape;\r\n        orient  = that.orient;\r\n        weight  = that.weight;\r\n        mask    = that.mask;\r\n        sysfont = that.sysfont;\r\n    }\r\n    font(const gchar* n, int sz)\r\n    {\r\n        name.assign(n);\r\n        size = sz;\r\n        escape = 0;\r\n        orient = 0;\r\n        weight = 3;\r\n        mask = 0;\r\n        sysfont = 0;\r\n    }\r\n    font& operator = (const font& that)\r\n    {\r\n        name    = that.name;\r\n        size  = that.size;\r\n        escape  = that.escape;\r\n        orient  = that.orient;\r\n        weight  = that.weight;\r\n        mask    = that.mask;\r\n        return *this;\r\n    }\r\n    bool operator == (const font& that) const\r\n    {\r\n        if(name != that.name)\r\n            return false;\r\n        if(size != that.size)\r\n            return false;\r\n        if(escape != that.escape)\r\n            return false;\r\n        if(orient != that.orient)\r\n            return false;\r\n        if(weight != that.weight)\r\n            return false;\r\n        if(mask != that.mask)\r\n            return false;\r\n        return true;\r\n    }\r\n    bool operator != (const font& that) const\r\n    {\r\n        if(name != that.name)\r\n            return true;\r\n        if(size != that.size)\r\n            return true;\r\n        if(escape != that.escape)\r\n            return true;\r\n        if(orient != that.orient)\r\n            return true;\r\n        if(weight != that.weight)\r\n            return true;\r\n        if(mask != that.mask)\r\n            return true;\r\n        return false;\r\n    }\r\n    size_t hash_value() const\r\n    {\r\n        hasher h;\r\n        h.add_bytes((const byte*)name.c_str(), name.length() * sizeof(gchar));\r\n        h.add_bytes((const byte*)&size, sizeof(size));\r\n        h.add_bytes((const byte*)&escape, sizeof(escape));\r\n        h.add_bytes((const byte*)&orient, sizeof(orient));\r\n        h.add_bytes((const byte*)&weight, sizeof(weight));\r\n        return h.add_bytes((const byte*)&mask, sizeof(mask));\r\n    }\r\n};\r\n\r\nstruct ariel_export viewport\r\n{\r\n    float           left;\r\n    float           top;\r\n    float           width;\r\n    float           height;\r\n    float           min_depth;\r\n    float           max_depth;\r\n};\r\n\r\nstruct ariel_export axis_aligned_bound_box\r\n{\r\n    float           left = FLT_MAX;\r\n    float           right = -FLT_MAX;\r\n    float           top = FLT_MAX;\r\n    float           bottom = -FLT_MAX;\r\n    float           front = FLT_MAX;\r\n    float           back = -FLT_MAX;\r\n\r\npublic:\r\n    void reset()\r\n    {\r\n        left = top = front = FLT_MAX;\r\n        right = bottom = back = -FLT_MAX;\r\n    }\r\n    float width() const { return right - left; }\r\n    float height() const { return bottom - top; }\r\n    float depth() const { return back - front; }\r\n};\r\n\r\nstruct ariel_export origin_bound_sphere\r\n{\r\n    float           radius = 0.f;\r\n};\r\n\r\nstruct ariel_export bound_sphere\r\n{\r\n    vec3            origin;\r\n    float           radius = 0.f;\r\n};\r\n\r\nenum res_type\r\n{\r\n    res_mesh,\r\n};\r\n\r\nclass __gs_novtable ariel_export res_node abstract\r\n{\r\npublic:\r\n    virtual ~res_node() {}\r\n    virtual res_type get_type() const = 0;\r\n    virtual const string& get_name() const { return _name; }\r\n    virtual bool has_name() const { return !_name.empty(); }\r\n\r\nprotected:\r\n    string          _name;\r\n\r\npublic:\r\n    void set_name(const string& name) { _name = name; }\r\n};\r\n\r\n__ariel_end__\r\n\r\nnamespace std {\r\n\r\ntemplate<>\r\nclass hash<gs::ariel::font>\r\n#if defined(_MSC_VER) && (_MSC_VER < 1914)\r\n    : public unary_function<gs::ariel::font, size_t>\r\n#endif\r\n{\r\npublic:\r\n    size_t operator()(const gs::ariel::font& ft) const { return ft.hash_value(); }\r\n};\r\n\r\n};\r\n\r\n#endif\r\n", "meta": {"hexsha": "f8ff71e746ee4da2514982be26ad4813039ce9d5", "size": 7034, "ext": "h", "lang": "C", "max_stars_repo_path": "include/ariel/type.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/ariel/type.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ariel/type.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 27.8023715415, "max_line_length": 131, "alphanum_fraction": 0.5555871481, "num_tokens": 1753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25091277568224823, "lm_q2_score": 0.049589021930595244, "lm_q1q2_score": 0.012442519135973532}}
{"text": "#pragma once\n\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_vector.h>\n\nsize_t nn_utils_sizeof_gsl_matrix(void);\nsize_t nn_utils_sizeof_gsl_vector(void);\n", "meta": {"hexsha": "ae1d3fd390e2f4d0e6f2477ea42bd417aba0320a", "size": 153, "ext": "h", "lang": "C", "max_stars_repo_path": "include/nn_utils.h", "max_stars_repo_name": "mygulamali/neural-net", "max_stars_repo_head_hexsha": "250995db0e9d555cc51dfda2f0ee6720c15fc4c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/nn_utils.h", "max_issues_repo_name": "mygulamali/neural-net", "max_issues_repo_head_hexsha": "250995db0e9d555cc51dfda2f0ee6720c15fc4c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/nn_utils.h", "max_forks_repo_name": "mygulamali/neural-net", "max_forks_repo_head_hexsha": "250995db0e9d555cc51dfda2f0ee6720c15fc4c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.125, "max_line_length": 40, "alphanum_fraction": 0.8104575163, "num_tokens": 43, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936414516010196, "lm_q2_score": 0.03461883921267763, "lm_q1q2_score": 0.012440769560098914}}
{"text": "#ifndef RAYS_H\n#define RAYS_H\n\n#include <complex.h>\n#include <gsl/gsl_randist.h>\n#include <gsl/gsl_rng.h>\n#include <malloc.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/time.h>\n#include <time.h>\n\n#include \"tsvread.h\"\n\n// A ray.\ntypedef struct {\n  double p0[3];           // position\n  double e0[3];           // direction\n  complex double pol[3];  // polarization\n  double OPL;             // optical path length\n  double lambda;          // wavelength\n  double intensity;       // intensity of this paricular ray\n  double g;               // apodisation factor\n} ray_t;\n\nray_t *readrays(char *filename, unsigned int *nrays);\nvoid movefocus(ray_t *ray, unsigned int nrays);\n\n#endif  // RAYS_H\n", "meta": {"hexsha": "db1de68fffd772d20d960189e1699f7fa93809e6", "size": 704, "ext": "h", "lang": "C", "max_stars_repo_path": "rays.h", "max_stars_repo_name": "AaronWebster/directdebye", "max_stars_repo_head_hexsha": "ddc61f250ed2c7ad185dcaf78def714231328ef4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rays.h", "max_issues_repo_name": "AaronWebster/directdebye", "max_issues_repo_head_hexsha": "ddc61f250ed2c7ad185dcaf78def714231328ef4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rays.h", "max_forks_repo_name": "AaronWebster/directdebye", "max_forks_repo_head_hexsha": "ddc61f250ed2c7ad185dcaf78def714231328ef4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4666666667, "max_line_length": 60, "alphanum_fraction": 0.6420454545, "num_tokens": 189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3593641451601019, "lm_q2_score": 0.03461883846567404, "lm_q1q2_score": 0.012440769291652606}}
{"text": "//! \\file neutronics_driver.h\n//! Base class for single-physics neutronics solver\n#ifndef NEUTRONICS_DRIVER_H\n#define NEUTRONICS_DRIVER_H\n\n#include \"enrico/driver.h\"\n#include \"enrico/geom.h\"\n#include \"enrico/mpi_types.h\"\n\n#include <gsl/gsl>\n#include <xtensor/xtensor.hpp>\n\n#include <vector>\n\nnamespace enrico {\n\nusing CellHandle = gsl::index;\n\n//! Base class for driver that controls a neutronics solve\nclass NeutronicsDriver : public Driver {\npublic:\n  explicit NeutronicsDriver(MPI_Comm comm)\n    : Driver(comm)\n  {}\n\n  virtual ~NeutronicsDriver() = default;\n\n  //! Get energy deposition in each material normalized to a given power\n  //! \\param power User-specified power in [W]\n  //! \\return Heat source in each material as [W/cm3]\n  virtual xt::xtensor<double, 1> heat_source(double power) const = 0;\n\n  //! Find cells corresponding to a vector of positions\n  //! \\param positions (x,y,z) coordinates to search for\n  //! \\return Handles to cells\n  virtual std::vector<CellHandle> find(const std::vector<Position>& positions) = 0;\n\n  //! Set the density of the material in a cell\n  //! \\param cell Handle to a cell\n  //! \\param rho Density in [g/cm^3]\n  virtual void set_density(CellHandle cell, double rho) const = 0;\n\n  //! Set the temperature of a cell\n  //! \\param cell Handle to a cell\n  //! \\param T Temperature in [K]\n  virtual void set_temperature(CellHandle cell, double T) const = 0;\n\n  //! Get the density of a cell\n  //! \\param cell Handle to a cell\n  //! \\return Cell density in [g/cm^3]\n  virtual double get_density(CellHandle cell) const = 0;\n\n  //! Get the temperature of a cell\n  //! \\param cell Handle to a cell\n  //! \\return Temperature in [K]\n  virtual double get_temperature(CellHandle cell) const = 0;\n\n  //! Get the volume of a cell\n  //! \\param cell Handle to a cell\n  //! \\return Volume in [cm^3]\n  virtual double get_volume(CellHandle cell) const = 0;\n\n  //! Detemrine whether a cell contains fissionable nuclides\n  //! \\param cell Handle to a cell\n  //! \\return Whether the cell contains fissionable nuclides\n  virtual bool is_fissionable(CellHandle cell) const = 0;\n\n  //! Determine number of cells participating in coupling\n  //! \\return Number of cells\n  virtual std::size_t n_cells() const = 0;\n\n  //! Create energy production tallies\n  virtual void create_tallies() = 0;\n\n  //! Get a label for a cell\n  //! \\param cell Handle to a clel\n  //! \\return Label for the cell\n  virtual std::string cell_label(CellHandle cell) const = 0;\n};\n\n} // namespace enrico\n\n#endif // NEUTRONICS_DRIVER_H\n", "meta": {"hexsha": "7f8c8dce23b2d3cfa5493a6283e9169763da491a", "size": 2523, "ext": "h", "lang": "C", "max_stars_repo_path": "include/enrico/neutronics_driver.h", "max_stars_repo_name": "pshriwise/enrico", "max_stars_repo_head_hexsha": "72b95ca947804f672e5f1726e169ef6f4889e78e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-02T16:21:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-02T16:21:59.000Z", "max_issues_repo_path": "include/enrico/neutronics_driver.h", "max_issues_repo_name": "pshriwise/enrico", "max_issues_repo_head_hexsha": "72b95ca947804f672e5f1726e169ef6f4889e78e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-03-17T15:52:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-17T20:56:35.000Z", "max_forks_repo_path": "include/enrico/neutronics_driver.h", "max_forks_repo_name": "lebuller/enrico", "max_forks_repo_head_hexsha": "edd04f1e02caf1c3fae2992e55d9a47e4429655c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0357142857, "max_line_length": 83, "alphanum_fraction": 0.707491082, "num_tokens": 662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33807712415000585, "lm_q2_score": 0.03676946594365837, "lm_q1q2_score": 0.012430915302763601}}
{"text": "#ifndef MODULE_WASM_LINEAR_MEMORY_H\n#define MODULE_WASM_LINEAR_MEMORY_H\n#include <array>\n#include <vector>\n#include <algorithm>\n#include \"wasm_base.h\"\n#include \"wasm_value.h\"\n#include <stdexcept>\n#include <iostream>\n#include <cstring>\n#include <gsl/span>\n#include \"utilities/endianness.h\"\n\nnamespace wasm {\n\nstruct WasmLinearMemory\n{\n\tstatic constexpr const std::size_t page_size = 65536;\n\tusing page_type = alignas(page_size) char[page_size];\nprivate:\n\tusing vector_type = wasm::SimpleVector<page_type>;\npublic:\n\tusing wasm_external_kind_type = parse::Memory;\n\n\tusing page_iterator = page_type*;\n\tusing const_page_iterator = const page_type*;\n\tusing page_pointer = page_type*;\n\tusing const_page_pointer = const page_type*;\n\tusing page_reference = page_type&;\n\tusing const_page_reference = const page_type&;\n\t\n\tusing page_span = gsl::span<const page_type>;\n\tusing const_page_span = gsl::span<const page_type>;\n\n\tusing value_type = char;\n\tusing iterator = value_type*;\n\tusing const_iterator = const value_type*;\n\tusing pointer = value_type*;\n\tusing const_pointer = const value_type*;\n\tusing reference = value_type&;\n\tusing const_reference = const value_type&;\n\n\tusing raw_span = gsl::span<const value_type>;\n\tusing const_raw_span = gsl::span<const value_type>;\n\n\tusing size_type = vector_type::size_type;\n\tusing difference_type = vector_type::difference_type;\n\n\tWasmLinearMemory(const parse::Memory& def, const parse::DataSegment& seg);\n\n\tfriend const_page_span pages(const WasmLinearMemory& self)\n\t{ return const_page_span(self.memory_.data(), self.memory_.size()); }\n\n\tfriend page_span pages(WasmLinearMemory& self)\n\t{ return page_span(self.memory_.data(), self.memory_.size()); }\n\n\tfriend const_raw_span data(const WasmLinearMemory& self)\n\t{\n\t\treturn raw_span(\n\t\t\tstatic_cast<const_pointer>(self.vec_.data()), \n\t\t\tpage_size * self.vec_.size()\n\t\t);\n\t}\n\n\tfriend raw_span data(WasmLinearMemory& self)\n\t{\n\t\treturn raw_span(\n\t\t\tstatic_cast<pointer>(self.vec_.data()), \n\t\t\tpage_size * self.vec_.size()\n\t\t);\n\t}\n\n\tfriend wasm_sint32_t grow_memory(WasmLinearMemory& self, wasm_uint32_t delta)\n\t{\n\t\twasm_uint32_t prev = static_cast<wasm_uint32_t>(pages(self).size());\n\t\tassert(prev == pages(self).size());\n\t\tif(delta > 0u)\n\t\t{\n\t\t\tstd::size_t new_size = self.vec_.size() + delta;\n\t\t\tif(new_size > maximum_)\n\t\t\t\treturn -1;\n\t\t\ttry\n\t\t\t{\n\t\t\t\tself.resize(self.vec_.size() + delta);\n\t\t\t}\n\t\t\tcatch(std::bad_alloc& e)\n\t\t\t{\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\t\treturn reinterpret_cast<const wasm_sint32_t&>(prev);\n\t}\n\n\tfriend bool matches(const WasmLinearMemory& self, const parse::Memory& tp)\n\t{\n\t\treturn self.memory_.size() >= tp.size() and (\n\t\t\tself.maximum_ == tp.maximum.value_or(std::numeric_limits<std::size_t>::max())\n\t\t);\n\t}\n\nprivate:\n\tvoid resize(std::size_t n)\n\t{\n\t\tassert(n <= maximum_);\n\t\tusing std::swap;\n\t\tvector_type tmp(n);\n\t\tswap(memory_, tmp);\n\t\tstd::memcpy(v.data(), tmp.data(), tmp.size() * sizeof(tmp.front()));\n\t\tstd::memset(v.data() + tmp.size(), 0, v.size() - tmp.size());\n\t}\n\tvector_type memory_;\n\tconst std::size_t maximum_ = std::numeric_limits<std::size_t>::max();\n};\n\nLanguageType index_type(const WasmLinearMemory& self)\n{\n\treturn \n}\n\nWasmLinearMemory::size_type current_memory(const WasmLinearMemory& self)\n{ return pages(self).size(); }\n\nWasmLinearMemory::size_type page_count(const WasmLinearMemory& self)\n{ return current_memory(self); }\t\n\nWasmLinearMemory::size_type size(const WasmLinearMemory& self)\n{ return data(self).size(); }\n\n\nWasmLinearMemory::WasmLinearMemory(const parse::Memory& def):\n\tmemory_(def.initial),\n\tmaximum_(def.maximum.value_or(std::numeric_limits<std::size_t>::max())\n{\n\tauto bytes = data(*this);\n\tstd::fill(bytes.begin(), bytes.end(), 0);\n}\n\ngsl::span<const char> compute_effective_address(\n\tconst WasmLinearMemory& self,\n\twasm_uint32_t base,\n\twasm_uint32_t offset,\n\tstd::size_t size\n)\n{\n\tauto mem = data(self);\n\tif(mem.size() <= base)\n\t\tthrow std::out_of_range(\"Base address is too large while computing linear memory effective address.\");\n\tstd::size_t effective_address = base;\n\teffective_address += offset;\n\tif(mem.size() <= effective_address)\n\t\tthrow std::out_of_range(\"Computed effective address is too large for linear memory.\");\n\tif(std::size_t remaining = mem.size() - effective_address; remaining < sizeof(Type))\n\t\tthrow std::out_of_range(\"Linear memory access partially acesses out-of-bounds memory.\");\n\treturn mem.subspan(effective_address, size);\n}\n\ngsl::span<char> compute_effective_address(\n\tWasmLinearMemory& self,\n\twasm_uint32_t base,\n\twasm_uint32_t offset,\n\tstd::size_t size\n)\n{\n\tauto addr = compute_effective_address(std::as_const(self), base, offset, size);\n\tconst char* data = addr.data();\n\tauto size = addr.data();\n\treturn gsl::span<char>(const_cast<char*>(data), size);\n}\n\n\ntemplate <class Type>\nType load_little_endian(const WasmLinearMemory& self, wasm_uint32_t base, wasm_uint32_t offset)\n{\n\tstatic_assert(std::is_trivially_copyable_v<Type>);\n\tstatic_assert(std::is_arithmetic_v<Type>);\n\tType result;\n\tauto addr = compute_effective_address(self, base, offset, sizeof(Type));\n\tassert(addr.size() == sizeof(result));\n\tstd::memcpy(&result, addr.data(), sizeof(result));\n\tif(not system_is_little_endian())\n\t{\n\t\tstatic_assert(std::is_same_v<decltype(byte_swap(value)), decltype(value)>);\n\t\tresult = byte_swap(result);\n\t}\n\treturn result;\n}\n\ntemplate <class Type, class PassedType>\nvoid store_little_endian(const WasmLinearMemory& self, wasm_uint32_t base, wasm_uint32_t offset, PassedType value)\n{\n\tstatic_assert(std::is_trivially_copyable_v<Type>);\n\tstatic_assert(std::is_arithmetic_v<Type>);\n\tstatic_assert(std::is_same_v<Type, PassedType>);\n\tauto pos = compute_effective_address(self, base, offset, sizeof(Type));\n\tassert(addr.size() == sizeof(value));\n\tif(not system_is_little_endian())\n\t{\n\t\tstatic_assert(std::is_same_v<decltype(byte_swap(value)), decltype(value)>);\n\t\tvalue = byte_swap(value);\n\t}\n\tstd::memcpy(pos, &value, sizeof(value));\n}\n\n} /* namespace wasm */\n\n#endif /* MODULE_WASM_LINEAR_MEMORY_H */\n", "meta": {"hexsha": "7068e89421d640073e02d6df6636071f801710b6", "size": 5963, "ext": "h", "lang": "C", "max_stars_repo_path": "include/module/WasmLinearMemory.h", "max_stars_repo_name": "tvanslyke/wasm-cpp", "max_stars_repo_head_hexsha": "8a56c1706e2723ece36e3642bae9e36792dbd7b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/module/WasmLinearMemory.h", "max_issues_repo_name": "tvanslyke/wasm-cpp", "max_issues_repo_head_hexsha": "8a56c1706e2723ece36e3642bae9e36792dbd7b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/module/WasmLinearMemory.h", "max_forks_repo_name": "tvanslyke/wasm-cpp", "max_forks_repo_head_hexsha": "8a56c1706e2723ece36e3642bae9e36792dbd7b2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.806763285, "max_line_length": 114, "alphanum_fraction": 0.737548214, "num_tokens": 1481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4111108836623764, "lm_q2_score": 0.030214587176551188, "lm_q1q2_score": 0.012421545633645866}}
{"text": "/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*\n**                                                                                  **\n** This file forms part of the Underworld geophysics modelling application.         **\n**                                                                                  **\n** For full license and copyright information, please refer to the LICENSE.md file  **\n** located at the project root, or contact the authors.                             **\n**                                                                                  **\n**~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/\n#include <mpi.h>\n#include <StGermain/StGermain.h>\n#include <StgDomain/StgDomain.h>\n#include <StgFEM/StgFEM.h>\n#include \"types.h\"\n#include <petsc.h>\n#include <petscvec.h>\n#include <petscmat.h>\n#include <petscksp.h>\n#include <petscpc.h>\n#include <petscsnes.h>\n#include <petscis.h>\n#include <petscviewer.h>\n#include <petscsys.h>\n#include <petscversion.h>\n\n#if ( (PETSC_VERSION_MAJOR >= 3) && (PETSC_VERSION_MINOR >=3) )\n  #if (PETSC_VERSION_MINOR >=6)\n     #include \"petsc/private/kspimpl.h\"\n  #else\n     #include \"petsc-private/kspimpl.h\"   /*I \"petscksp.h\" I*/\n  #endif\n#else\n  #include \"private/kspimpl.h\"   /*I \"petscksp.h\" I*/\n#endif\n\n//#include \"ksptypes.h\"\n#include \"ksp-register.h\"\n#include \"StokesBlockKSPInterface.h\"\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <assert.h>\n#include <string.h>\n\n/* Macro for checking number integrity - i.e. checks if number is infinite or \"not a number\" */\n#define SBKSP_isGoodNumber( number ) ( (! isnan( number ) ) && ( ! isinf( number ) ) )\n#define SBKSP_GetPetscMatrix( matrix ) ( (Mat)(matrix) )\n#define SBKSP_GetPetscVector( vector ) ( (Vec)(vector) )\n#define SBKSP_GetPetscKSP( solver ) ( (KSP)(solver)  )\nPetscErrorCode _BlockSolve( void* solver, void* _stokesSLE );\n\nconst Type StokesBlockKSPInterface_Type = \"StokesBlockKSPInterface\";\n\nvoid* _StokesBlockKSPInterface_DefaultNew( Name name ) {\n    SizeT                                              _sizeOfSelf = sizeof(StokesBlockKSPInterface);\n    Type                                                      type = StokesBlockKSPInterface_Type;\n    Stg_Class_DeleteFunction*                              _delete = _SLE_Solver_Delete;\n    Stg_Class_PrintFunction*                                _print = _SLE_Solver_Print;\n    Stg_Class_CopyFunction*                                  _copy = _SLE_Solver_Copy;\n    Stg_Component_BuildFunction*                            _build = _StokesBlockKSPInterface_Build;\n    Stg_Component_InitialiseFunction*                  _initialise = _StokesBlockKSPInterface_Initialise;\n    Stg_Component_ExecuteFunction*                        _execute = _SLE_Solver_Execute;\n    Stg_Component_DestroyFunction*                        _destroy = _SLE_Solver_Destroy;\n    SLE_Solver_GetResidualFunc*                       _getResidual = NULL;\n    Stg_Component_DefaultConstructorFunction*  _defaultConstructor = _StokesBlockKSPInterface_DefaultNew;\n    Stg_Component_ConstructFunction*                    _construct = _StokesBlockKSPInterface_AssignFromXML;\n    SLE_Solver_SolverSetupFunction*                   _solverSetup = _StokesBlockKSPInterface_SolverSetup;\n    SLE_Solver_SolveFunction*                               _solve = _StokesBlockKSPInterface_Solve;\n\n    AllocationType  nameAllocationType = NON_GLOBAL /* default value NON_GLOBAL */;\n    return (void*) _StokesBlockKSPInterface_New( STOKESBLOCKKSPINTERFACE_PASSARGS );\n}\n\n\n/* Creation implementation / Virtual constructor */\n/* Set up function pointers */\nStokesBlockKSPInterface* _StokesBlockKSPInterface_New( STOKESBLOCKKSPINTERFACE_DEFARGS )\n{\n    StokesBlockKSPInterface* self;\n    /* Allocate memory */\n    assert( _sizeOfSelf >= sizeof(StokesBlockKSPInterface) );\n\n    self = (StokesBlockKSPInterface*) _SLE_Solver_New( SLE_SOLVER_PASSARGS );\n\n    /* Virtual info */\n    return self;\n}\n\nvoid _StokesBlockKSPInterface_Init(\n\t\tStokesBlockKSPInterface*      self,\n\t\tStiffnessMatrix*   preconditioner,\n\t\tStokes_SLE *       st_sle,\n\t\tPETScMGSolver *    mg,\n        Name   filename,\n        char * string,\n\t\tStiffnessMatrix*  k2StiffMat,\n\t\tStiffnessMatrix*  mStiffMat,\n\t\tForceVector*\t  f2ForceVec,\n\t\tForceVector*\t  jForceVec,\n\t\tdouble            penaltyNumber,\n\t\tdouble            hFactor,\n\t\tStiffnessMatrix*  vmStiffMat,\n\t\tForceVector*\t  vmForceVec  )\n{\n\tself->preconditioner = preconditioner;\n\tself->st_sle = st_sle;\n\tself->mg     = mg;\n    self->optionsFile = filename;\n    self->optionsString = string;\n\tself->k2StiffMat = k2StiffMat;\n\tself->f2ForceVec = f2ForceVec;\n\tself->penaltyNumber = penaltyNumber;\n\tself->hFactor       = hFactor;\n\tself->mStiffMat = mStiffMat;\n\tself->jForceVec = jForceVec;\n\tself->vmStiffMat = vmStiffMat;\n\tself->vmForceVec = vmForceVec;\n\t/* add the vecs and matrices to the Base SLE class's dynamic lists, so they can be\n\tinitialised and built properly */\n\n\t/*\n\tif (k2StiffMat )\n\t    SystemLinearEquations_AddStiffnessMatrix( st_sle, k2StiffMat );\n\n\tif (f2ForceVec )\n\t    SystemLinearEquations_AddForceVector( st_sle, f2ForceVec );\n\n\tif (mStiffMat )\n\t    SystemLinearEquations_AddStiffnessMatrix( st_sle, mStiffMat );\n\n\tif (jForceVec )\n\t    SystemLinearEquations_AddForceVector( st_sle, jForceVec );\n\n\tif (vmStiffMat )\n\t    SystemLinearEquations_AddStiffnessMatrix( st_sle, vmStiffMat );\n\n\tif (vmForceVec )\n\t    SystemLinearEquations_AddForceVector( st_sle, vmForceVec );\n    */\n}\n\nvoid _StokesBlockKSPInterface_Build( void* solver, void* sle ) {/* it is the sle here being passed in*/\n\tStokesBlockKSPInterface*\tself  = (StokesBlockKSPInterface*)solver;\n\n\tStream_IndentBranch( StgFEM_Debug );\n\n\t/* Build Preconditioner */\n\tif ( self->preconditioner ) {\n\t\tStg_Component_Build( self->preconditioner, sle, False );\n\t\tSystemLinearEquations_AddStiffnessMatrix( self->st_sle, self->preconditioner );\n\n\t}\n\tif( self->mg ){\n\t    Stg_Component_Build( self->mg, sle, False );\n\t}\n\n\tStream_UnIndentBranch( StgFEM_Debug );\n}\n\nvoid _StokesBlockKSPInterface_AssignFromXML( void* solver, Stg_ComponentFactory* cf, void* data ) {\n\tStokesBlockKSPInterface* self         = (StokesBlockKSPInterface*) solver;\n\t//double                  tolerance;\n\t//Iteration_Index         maxUzawaIterations, minUzawaIterations;\n\tStiffnessMatrix*  preconditioner;\n\tStiffnessMatrix*  k2StiffMat;\n\tForceVector*\t  f2ForceVec;\n\tStiffnessMatrix*  mStiffMat;\n\tForceVector*\t  jForceVec;\n\tdouble            penaltyNumber;\n\tdouble            hFactor;\n\tStiffnessMatrix*  vmStiffMat;\n\tForceVector*\t  vmForceVec;\n\t//Bool                    useAbsoluteTolerance;\n\t//Bool                    monitor;\n\tStokes_SLE *            st_sle;\n\tPETScMGSolver *         mg;\n\t//Name                filename;\n\t//char* \t\t        string;\n\n\t_SLE_Solver_AssignFromXML( self, cf, data );\n\n\tpreconditioner = Stg_ComponentFactory_ConstructByKey( cf, self->name, (Dictionary_Entry_Key)\"Preconditioner\", StiffnessMatrix, False, data  );\n\tst_sle  = Stg_ComponentFactory_ConstructByKey( cf, self->name, (Dictionary_Entry_Key)\"stokesEqn\", Stokes_SLE, True, data  );\n\tmg      = Stg_ComponentFactory_ConstructByKey( cf, self->name, (Dictionary_Entry_Key)\"mgSolver\", PETScMGSolver, False, data);\n\tk2StiffMat = Stg_ComponentFactory_ConstructByKey( cf, self->name, (Dictionary_Entry_Key)\"2ndStressTensorMatrix\", StiffnessMatrix, False, data  );\n\tf2ForceVec = Stg_ComponentFactory_ConstructByKey( cf, self->name, (Dictionary_Entry_Key)\"2ndForceVector\", ForceVector, False, data  );\n\tpenaltyNumber   = Stg_ComponentFactory_GetDouble( cf, self->name, (Dictionary_Entry_Key)\"penaltyNumber\", 0.0  );\n\thFactor         = Stg_ComponentFactory_GetDouble( cf, self->name, (Dictionary_Entry_Key)\"hFactor\", 0.0  );\n\tmStiffMat = Stg_ComponentFactory_ConstructByKey( cf, self->name, (Dictionary_Entry_Key)\"MassMatrix\", StiffnessMatrix, False, data  );\n\tjForceVec = Stg_ComponentFactory_ConstructByKey( cf, self->name, (Dictionary_Entry_Key)\"JunkForceVector\", ForceVector, False, data  );\n\tvmStiffMat = Stg_ComponentFactory_ConstructByKey( cf, self->name, (Dictionary_Entry_Key)\"VelocityMassMatrix\", StiffnessMatrix, False, data  );\n\tvmForceVec = Stg_ComponentFactory_ConstructByKey( cf, self->name, (Dictionary_Entry_Key)\"VMassForceVector\", ForceVector, False, data  );\n\n\t_StokesBlockKSPInterface_Init( self, preconditioner, st_sle, mg, NULL, NULL, k2StiffMat, mStiffMat,\n                                   f2ForceVec, jForceVec, penaltyNumber, hFactor, vmStiffMat, vmForceVec);\n\n}\n\nvoid _StokesBlockKSPInterface_Initialise( void* solver, void* data ) {\n\tStokesBlockKSPInterface* self = (StokesBlockKSPInterface*) solver;\n\tStokes_SLE*             sle  = (Stokes_SLE*)  self->st_sle;\n\n\t/* Initialise Parent */\n\t_SLE_Solver_Initialise( self, sle );\n\n\tKSPRegisterAllKSP(\"Solvers/KSPSolvers/src\");\n}\n\n/* SolverSetup */\n\nvoid _StokesBlockKSPInterface_SolverSetup( void* solver, void* stokesSLE ) {\n\tStokesBlockKSPInterface* self = (StokesBlockKSPInterface*) solver;\n\t//Stokes_SLE*             sle  = (Stokes_SLE*)             stokesSLE;\n\n \tJournal_DPrintf( self->debug, \"In %s:\\n\", __func__ );\n\tStream_IndentBranch( StgFEM_Debug );\n\n\tStream_UnIndentBranch( StgFEM_Debug );\n}\nvoid SBKSP_SetSolver( void* solver, void* stokesSLE ) {\n\tSLE_Solver* self = (SLE_Solver*) solver;\n\tStokes_SLE*              sle  = (Stokes_SLE*) stokesSLE;\n\n    sle->solver=self;\n\n}\nvoid SBKSP_SetPenalty( void* solver, double penalty ) {\n  StokesBlockKSPInterface* self = (StokesBlockKSPInterface*) solver;\n  self->penaltyNumber=penalty;\n}\n\nint SBKSP_GetPressureIts(void *solver){\n  StokesBlockKSPInterface* self = (StokesBlockKSPInterface*) solver;\n  return self->stats.pressure_its;\n}\n\n/***********************************************************************************************************/\n/***********************************************************************************************************/\n/***********************************************************************************************************/\n\nvoid SBKSP_GetStokesOperators(\n\t\tStokes_SLE *stokesSLE,\n\t\tMat *K,Mat *G,Mat *D,Mat *C,Mat *approxS,\n\t\tVec *f,Vec *h,Vec *u,Vec *p )\n{\n\n\t*K = *G = *D = *C = PETSC_NULL;\n\tif (stokesSLE->kStiffMat){      *K = SBKSP_GetPetscMatrix( stokesSLE->kStiffMat->matrix );     }\n\tif (stokesSLE->gStiffMat){      *G = SBKSP_GetPetscMatrix( stokesSLE->gStiffMat->matrix );     }\n\tif (stokesSLE->dStiffMat){      *D = SBKSP_GetPetscMatrix( stokesSLE->dStiffMat->matrix );     }\n\tif (stokesSLE->cStiffMat){      *C = SBKSP_GetPetscMatrix( stokesSLE->cStiffMat->matrix );     }\n\n\t/* preconditioner */\n\t*approxS = PETSC_NULL;\n\tif( ((StokesBlockKSPInterface*)stokesSLE->solver)->preconditioner ) {\n\t\tStiffnessMatrix *preconditioner;\n\n\t\tpreconditioner = ((StokesBlockKSPInterface*)stokesSLE->solver)->preconditioner;\n\t\t*approxS = SBKSP_GetPetscMatrix( preconditioner->matrix );\n\t}\n\n\t*f = *h = PETSC_NULL;\n\tif (stokesSLE->fForceVec){      *f = SBKSP_GetPetscVector( stokesSLE->fForceVec->vector );     }\n\tif (stokesSLE->hForceVec){      *h = SBKSP_GetPetscVector( stokesSLE->hForceVec->vector );     }\n\n\t*u = *p = PETSC_NULL;\n\tif (stokesSLE->uSolnVec){       *u = SBKSP_GetPetscVector( stokesSLE->uSolnVec->vector );      }\n\tif (stokesSLE->pSolnVec){       *p = SBKSP_GetPetscVector( stokesSLE->pSolnVec->vector );      }\n\n}\n/***********************************************************************************************************/\n/***********************************************************************************************************/\n/***********************************************************************************************************/\n/* Sets up Solver to be a custom ksp (KSP_BSSCR) solve by default: */\nvoid _StokesBlockKSPInterface_Solve( void* solver, void* _stokesSLE ) {\n  StokesBlockKSPInterface* self    = (StokesBlockKSPInterface*)solver;\n  PetscLogDouble flopsA,flopsB;\n  PetscTruth found, get_flops;\n\n  found = PETSC_FALSE;\n  get_flops = PETSC_FALSE;\n  PetscOptionsGetTruth( PETSC_NULL, \"-get_flops\", &get_flops, &found);\n  if(get_flops){\n    PetscGetFlops(&flopsA); }\n\n  _BlockSolve(solver, _stokesSLE);\n\n  if(get_flops){\n    PetscGetFlops(&flopsB);\n    self->stats.total_flops=(double)(flopsB-flopsA); }\n}\nPetscErrorCode _BlockSolve( void* solver, void* _stokesSLE ) {\n  Stokes_SLE*  stokesSLE  = (Stokes_SLE*)_stokesSLE;\n  StokesBlockKSPInterface* Solver    = (StokesBlockKSPInterface*)solver;\n\n  /* Create shortcuts to stuff needed on sle */\n  Mat       K;\n  Mat       G;\n  Mat       Gt;\n  Mat       D;\n  Mat       C;\n  Mat       approxS;\n  Vec       u;\n  Vec       p;\n  Vec       f;\n  Vec       h;\n  Mat stokes_P;\n  Mat stokes_A;\n  Vec stokes_x;\n  Vec stokes_b;\n  Mat a[2][2];\n  Vec x[2];\n  Vec b[2];\n  KSP stokes_ksp;\n  PC  stokes_pc;\n  PetscTruth sym,flg;\n  PetscErrorCode ierr;\n\n  PetscInt   N,n;\n\n  SBKSP_GetStokesOperators( stokesSLE, &K,&G,&D,&C, &approxS, &f,&h, &u,&p );\n\n  /* create Gt */\n  if( !D ) {\n    ierr = MatTranspose( G, MAT_INITIAL_MATRIX, &Gt);CHKERRQ(ierr);\n    sym = PETSC_TRUE;\n    Solver->DIsSym = sym;\n  }\n  else {\n    Gt = D;\n    sym = PETSC_FALSE;\n    Solver->DIsSym = sym;\n  }\n  flg=PETSC_FALSE;\n  PetscOptionsHasName(PETSC_NULL,\"-use_petsc_ksp\",&flg);\n  if (flg) {\n    if( !C ) {\n      /* Everything in this bracket, dependent on !C, is to build\n         a matrix with diagonals of 0 for C the previous comment ways\n\n      need a 'zero' matrix to keep fieldsplit happy in petsc? */\n      MatType mtype;\n      Vec V;\n      //MatGetSize( G, &M, &N );\n      VecGetSize(p, &N);\n      VecGetLocalSize( p, &n );\n      MatCreate( PetscObjectComm((PetscObject) K), &C );\n      MatSetSizes( C, PETSC_DECIDE ,PETSC_DECIDE, N, N );\n#if (((PETSC_VERSION_MAJOR==3) && (PETSC_VERSION_MINOR>=3)) || (PETSC_VERSION_MAJOR>3) )\n      MatSetUp(C);\n#endif\n      MatGetType( G, &mtype );\n      MatSetType( C, mtype );\n      MatGetVecs( G, &V, PETSC_NULL );\n      VecSet(V, 0.0);\n      //VecSet(h, 1.0);\n      ierr = VecAssemblyBegin( V );CHKERRQ(ierr);\n      ierr = VecAssemblyEnd  ( V );CHKERRQ(ierr);\n      ierr = MatDiagonalSet(C,V,INSERT_VALUES);CHKERRQ(ierr);\n      ierr = MatAssemblyBegin( C, MAT_FINAL_ASSEMBLY );CHKERRQ(ierr);\n      ierr = MatAssemblyEnd  ( C, MAT_FINAL_ASSEMBLY );CHKERRQ(ierr);\n    }\n  }\n  a[0][0]=K;  a[0][1]=G;\n  a[1][0]=Gt; a[1][1]=C;\n  ierr = MatCreateNest(PetscObjectComm((PetscObject) K), 2, NULL, 2, NULL, (Mat *)a, &stokes_A);CHKERRQ(ierr);\n  ierr = MatAssemblyBegin( stokes_A, MAT_FINAL_ASSEMBLY );CHKERRQ(ierr);\n  ierr = MatAssemblyEnd( stokes_A, MAT_FINAL_ASSEMBLY );CHKERRQ(ierr);\n\n\n\n  x[0]=u;\n  x[1]=p;\n  ierr = VecCreateNest(PetscObjectComm((PetscObject) u), 2, NULL, x, &stokes_x);CHKERRQ(ierr);\n  ierr = VecAssemblyBegin( stokes_x );CHKERRQ(ierr);\n  ierr = VecAssemblyEnd( stokes_x);CHKERRQ(ierr);\n\n  b[0]=f;\n  b[1]=h;\n  ierr = VecCreateNest(PetscObjectComm((PetscObject) f), 2, NULL, b, &stokes_b);CHKERRQ(ierr);\n  ierr = VecAssemblyBegin( stokes_b );CHKERRQ(ierr);\n  ierr = VecAssemblyEnd( stokes_b);CHKERRQ(ierr);\n\n  /* if( approxS ) { */\n  /*   a[0][0]=K;    a[0][1]=G; */\n  /*   a[1][0]=NULL; a[1][1]=approxS; */\n  /*   ierr = MatCreateNest(PetscObjectComm((PetscObject) K), 2, NULL, 2, NULL, (Mat *)a, &stokes_P);CHKERRQ(ierr); */\n  /*   ierr = MatAssemblyBegin( stokes_P, MAT_FINAL_ASSEMBLY );CHKERRQ(ierr); */\n  /*   ierr = MatAssemblyEnd( stokes_P, MAT_FINAL_ASSEMBLY );CHKERRQ(ierr); */\n  /* } */\n  /* else { */\n    stokes_P = stokes_A;\n  /* } */\n\n  /* probably should make a Destroy function for these two */\n  /* Update options from file and/or string here so we can change things on the fly */\n  //PetscOptionsInsertFile(PETSC_COMM_WORLD, Solver->optionsFile, PETSC_FALSE);\n  //PetscOptionsInsertString(Solver->optionsString);\n\n  ierr = KSPCreate( PETSC_COMM_WORLD, &stokes_ksp );CHKERRQ(ierr);\n  Stg_KSPSetOperators( stokes_ksp, stokes_A, stokes_P, SAME_NONZERO_PATTERN );\n  ierr = KSPSetType( stokes_ksp, \"bsscr\" );/* i.e. making this the default solver : calls KSPCreate_XXX */CHKERRQ(ierr);\n\n  ierr = KSPGetPC( stokes_ksp, &stokes_pc );CHKERRQ(ierr);\n  ierr = PCSetType( stokes_pc, PCNONE );CHKERRQ(ierr);\n  ierr = KSPSetInitialGuessNonzero( stokes_ksp, PETSC_TRUE );CHKERRQ(ierr);\n  ierr = KSPSetFromOptions( stokes_ksp );CHKERRQ(ierr);\n\n  /*\n    Doing this so the KSP Solver has access to the StgFEM Multigrid struct (PETScMGSolver).\n    As well as any custom stuff on the Stokes_SLE struct\n  */\n  if( stokes_ksp->data ){/* then ksp->data has been created in a KSpSetUp_XXX function */\n    /* testing for our KSP types that need the data that is on Solver... */\n    /* for the moment then, this function not completely agnostic about our KSPs */\n    //if(!strcmp(\"bsscr\",stokes_ksp->type_name)){/* if is bsscr then set up the data on the ksp */\n    flg=PETSC_FALSE;\n    PetscOptionsHasName(PETSC_NULL,\"-use_petsc_ksp\",&flg);\n    if (!flg) {\n      ((KSP_COMMON*)(stokes_ksp->data))->st_sle         = Solver->st_sle;\n      ((KSP_COMMON*)(stokes_ksp->data))->mg             = Solver->mg;\n      ((KSP_COMMON*)(stokes_ksp->data))->DIsSym         = Solver->DIsSym;\n      ((KSP_COMMON*)(stokes_ksp->data))->preconditioner = Solver->preconditioner;\n      ((KSP_COMMON*)(stokes_ksp->data))->solver         = Solver;\n    }\n  }\n\n  ierr = KSPSolve( stokes_ksp, stokes_b, stokes_x );CHKERRQ(ierr);\n\n  Stg_KSPDestroy(&stokes_ksp );\n  //if( ((StokesBlockKSPInterface*)stokesSLE->solver)->preconditioner )\n  if(stokes_P != stokes_A) { Stg_MatDestroy(&stokes_P ); }\n\n  Stg_MatDestroy(&stokes_A );\n\n  Stg_VecDestroy(&stokes_x);\n  Stg_VecDestroy(&stokes_b);\n\n  if(!D){ Stg_MatDestroy(&Gt); }\n  if(C && (stokesSLE->cStiffMat->matrix != C) ){ Stg_MatDestroy(&C); }\n\n  PetscFunctionReturn(0);\n}\n", "meta": {"hexsha": "034ddd5c2e7beb43fdcab74784dced52da333612", "size": 17674, "ext": "c", "lang": "C", "max_stars_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/StokesBlockKSPInterface.c", "max_stars_repo_name": "StuartRClark/mantle", "max_stars_repo_head_hexsha": "27acbbbb70b00870bebc4f98c69af8edaa4f8bc4", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-28T20:00:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-28T20:00:12.000Z", "max_issues_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/StokesBlockKSPInterface.c", "max_issues_repo_name": "StuartRClark/mantle", "max_issues_repo_head_hexsha": "27acbbbb70b00870bebc4f98c69af8edaa4f8bc4", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/StokesBlockKSPInterface.c", "max_forks_repo_name": "StuartRClark/mantle", "max_forks_repo_head_hexsha": "27acbbbb70b00870bebc4f98c69af8edaa4f8bc4", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.8961625282, "max_line_length": 146, "alphanum_fraction": 0.6415072989, "num_tokens": 5219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39233683016710835, "lm_q2_score": 0.031618767382710224, "lm_q1q2_score": 0.012405206968723687}}
{"text": "#pragma once\n\n#include <type_traits>\n\n#include <cuda/runtime_api.hpp>\n#include <gsl-lite/gsl-lite.hpp>\n\nnamespace thrustshift {\n\nnamespace kernel {\n\ntemplate <typename MapT, typename SrcT, typename DstT>\n__global__ void gather(gsl_lite::span<const MapT> map, gsl_lite::span<const SrcT> src, gsl_lite::span<DstT> dst) {\n\n\tconst auto gtid = threadIdx.x + blockIdx.x * blockDim.x;\n\tif (gtid < src.size()) {\n\t\tdst[gtid] = src[map[gtid]];\n\t}\n}\n\n} // namespace kernel\n\nnamespace async {\n\ntemplate <class MapRange, class SrcRange, class DstRange>\nvoid gather(cuda::stream_t& stream, MapRange&& map, SrcRange&& src, DstRange&& dst) {\n\tgsl_Expects(src.size() == dst.size());\n\tgsl_Expects(src.size() == map.size());\n\tgsl_Expects(src.data() != dst.data());\n\n\tif (src.empty()) {\n\t\treturn;\n\t}\n\n\tusing map_index_type =\n\t    typename std::remove_reference<MapRange>::type::value_type;\n\tusing src_value_type =\n\t    typename std::remove_reference<SrcRange>::type::value_type;\n\tusing dst_value_type =\n\t    typename std::remove_reference<DstRange>::type::value_type;\n\n\tconstexpr cuda::grid::block_dimension_t block_dim = 128;\n\tconst cuda::grid::dimension_t grid_dim =\n\t    (src.size() + block_dim - 1) / block_dim;\n\tauto c = cuda::make_launch_config(grid_dim, block_dim);\n\tauto k = kernel::gather<map_index_type, src_value_type, dst_value_type>;\n\tcuda::enqueue_launch(k, stream, c, map, src, dst);\n}\n\n} // namespace async\n\n} // namespace thrustshift\n", "meta": {"hexsha": "1e5c92adb570d9980897e72e066e384a4b7199fa", "size": 1431, "ext": "h", "lang": "C", "max_stars_repo_path": "include/thrustshift/gather.h", "max_stars_repo_name": "pauleonix/thrustshift", "max_stars_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-16T13:01:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T13:01:46.000Z", "max_issues_repo_path": "include/thrustshift/gather.h", "max_issues_repo_name": "pauleonix/thrustshift", "max_issues_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-23T14:12:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-17T11:40:04.000Z", "max_forks_repo_path": "include/thrustshift/gather.h", "max_forks_repo_name": "pauleonix/thrustshift", "max_forks_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0, "max_line_length": 114, "alphanum_fraction": 0.714185884, "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2538610069692489, "lm_q2_score": 0.04885778364256332, "lm_q1q2_score": 0.01240308615378682}}
{"text": "/* integration/workspace.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#include <config.h>\n#include <stdlib.h>\n#include <gsl/gsl_integration.h>\n#include <gsl/gsl_errno.h>\n\ngsl_integration_workspace *\ngsl_integration_workspace_alloc (const size_t n) \n{\n  gsl_integration_workspace * w ;\n  \n  if (n == 0)\n    {\n      GSL_ERROR_VAL (\"workspace length n must be positive integer\",\n\t\t\tGSL_EDOM, 0);\n    }\n\n  w = (gsl_integration_workspace *) \n    malloc (sizeof (gsl_integration_workspace));\n\n  if (w == 0)\n    {\n      GSL_ERROR_VAL (\"failed to allocate space for workspace struct\",\n\t\t\tGSL_ENOMEM, 0);\n    }\n\n  w->alist = (double *) malloc (n * sizeof (double));\n\n  if (w->alist == 0)\n    {\n      free (w);\t\t/* exception in constructor, avoid memory leak */\n\n      GSL_ERROR_VAL (\"failed to allocate space for alist ranges\",\n\t\t\tGSL_ENOMEM, 0);\n    }\n\n  w->blist = (double *) malloc (n * sizeof (double));\n\n  if (w->blist == 0)\n    {\n      free (w->alist);\n      free (w);\t\t/* exception in constructor, avoid memory leak */\n\n      GSL_ERROR_VAL (\"failed to allocate space for blist ranges\",\n\t\t\tGSL_ENOMEM, 0);\n    }\n\n  w->rlist = (double *) malloc (n * sizeof (double));\n\n  if (w->rlist == 0)\n    {\n      free (w->blist);\n      free (w->alist);\n      free (w);\t\t/* exception in constructor, avoid memory leak */\n\n      GSL_ERROR_VAL (\"failed to allocate space for rlist ranges\",\n\t\t\tGSL_ENOMEM, 0);\n    }\n\n\n  w->elist = (double *) malloc (n * sizeof (double));\n\n  if (w->elist == 0)\n    {\n      free (w->rlist);\n      free (w->blist);\n      free (w->alist);\n      free (w);\t\t/* exception in constructor, avoid memory leak */\n\n      GSL_ERROR_VAL (\"failed to allocate space for elist ranges\",\n\t\t\tGSL_ENOMEM, 0);\n    }\n\n  w->order = (size_t *) malloc (n * sizeof (size_t));\n\n  if (w->order == 0)\n    {\n      free (w->elist);\n      free (w->rlist);\n      free (w->blist);\n      free (w->alist);\n      free (w);\t\t/* exception in constructor, avoid memory leak */\n\n      GSL_ERROR_VAL (\"failed to allocate space for order ranges\",\n\t\t\tGSL_ENOMEM, 0);\n    }\n\n  w->level = (size_t *) malloc (n * sizeof (size_t));\n\n  if (w->level == 0)\n    {\n      free (w->order);\n      free (w->elist);\n      free (w->rlist);\n      free (w->blist);\n      free (w->alist);\n      free (w);\t\t/* exception in constructor, avoid memory leak */\n\n      GSL_ERROR_VAL (\"failed to allocate space for order ranges\",\n\t\t\tGSL_ENOMEM, 0);\n    }\n\n  w->size = 0 ;\n  w->limit = n ;\n  w->maximum_level = 0 ;\n  \n  return w ;\n}\n\nvoid\ngsl_integration_workspace_free (gsl_integration_workspace * w)\n{\n  free (w->level) ;\n  free (w->order) ;\n  free (w->elist) ;\n  free (w->rlist) ;\n  free (w->blist) ;\n  free (w->alist) ;\n  free (w) ;\n}\n\n/*\nsize_t \ngsl_integration_workspace_limit (gsl_integration_workspace * w) \n{\n  return w->limit ;\n}\n\n\nsize_t \ngsl_integration_workspace_size (gsl_integration_workspace * w) \n{\n  return w->size ;\n}\n*/\n", "meta": {"hexsha": "dcf8ee0bca416d0fb9c1cddd43e1bb6b75f64f27", "size": 3611, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/integration/workspace.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/integration/workspace.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/integration/workspace.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 23.4480519481, "max_line_length": 72, "alphanum_fraction": 0.6236499585, "num_tokens": 1024, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.28140560742914383, "lm_q2_score": 0.04401865127382215, "lm_q1q2_score": 0.012387095299921578}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n//\n// Copyright (c) 2015 Microsoft Corporation. All rights reserved.\n//\n// This code is licensed under the MIT License (MIT).\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef GSL_UTIL_H\n#define GSL_UTIL_H\n\n#include <gsl/gsl_assert> // for Expects\n\n#include <array>\n#include <cstddef>          // for ptrdiff_t, size_t\n#include <exception>        // for exception\n#include <initializer_list> // for initializer_list\n#include <type_traits>      // for is_signed, integral_constant\n#include <utility>          // for forward\n\n#if defined(_MSC_VER)\n\n#pragma warning(push)\n#pragma warning(disable : 4127) // conditional expression is constant\n\n#if _MSC_VER < 1910\n#pragma push_macro(\"constexpr\")\n#define constexpr /*constexpr*/\n#endif            // _MSC_VER < 1910\n#endif            // _MSC_VER\n\nnamespace gsl\n{\n//\n// GSL.util: utilities\n//\n\n// index type for all container indexes/subscripts/sizes\nusing index = std::ptrdiff_t;\n\n// final_action allows you to ensure something gets run at the end of a scope\ntemplate <class F>\nclass final_action\n{\npublic:\n    explicit final_action(F f) noexcept : f_(std::move(f)) {}\n\n    final_action(final_action&& other) noexcept : f_(std::move(other.f_)), invoke_(other.invoke_)\n    {\n        other.invoke_ = false;\n    }\n\n    final_action(const final_action&) = delete;\n    final_action& operator=(const final_action&) = delete;\n    final_action& operator=(final_action&&) = delete;\n\n    GSL_SUPPRESS(f.6) // NO-FORMAT: attribute // terminate if throws\n    ~final_action() noexcept\n    {\n        if (invoke_) f_();\n    }\n\nprivate:\n    F f_;\n    bool invoke_{true};\n};\n\n// finally() - convenience function to generate a final_action\ntemplate <class F>\nfinal_action<F> finally(const F& f) noexcept\n{\n    return final_action<F>(f);\n}\n\ntemplate <class F>\nfinal_action<F> finally(F&& f) noexcept\n{\n    return final_action<F>(std::forward<F>(f));\n}\n\n// narrow_cast(): a searchable way to do narrowing casts of values\ntemplate <class T, class U>\nGSL_SUPPRESS(type.1) // NO-FORMAT: attribute\nconstexpr T narrow_cast(U&& u) noexcept\n{\n    return static_cast<T>(std::forward<U>(u));\n}\n\nstruct narrowing_error : public std::exception\n{\n};\n\nnamespace details\n{\n    template <class T, class U>\n    struct is_same_signedness\n        : public std::integral_constant<bool, std::is_signed<T>::value == std::is_signed<U>::value>\n    {\n    };\n} // namespace details\n\n// narrow() : a checked version of narrow_cast() that throws if the cast changed the value\ntemplate <class T, class U>\nGSL_SUPPRESS(type.1) // NO-FORMAT: attribute\nGSL_SUPPRESS(f.6) // NO-FORMAT: attribute // TODO: MSVC /analyze does not recognise noexcept(false)\nT narrow(U u) noexcept(false)\n{\n    T t = narrow_cast<T>(u);\n    if (static_cast<U>(t) != u) gsl::details::throw_exception(narrowing_error());\n    if (!details::is_same_signedness<T, U>::value && ((t < T{}) != (u < U{})))\n        gsl::details::throw_exception(narrowing_error());\n    return t;\n}\n\n//\n// at() - Bounds-checked way of accessing builtin arrays, std::array, std::vector\n//\ntemplate <class T, std::size_t N>\nGSL_SUPPRESS(bounds.4) // NO-FORMAT: attribute\nGSL_SUPPRESS(bounds.2) // NO-FORMAT: attribute\nconstexpr T& at(T (&arr)[N], const index i)\n{\n    Expects(i >= 0 && i < narrow_cast<index>(N));\n    return arr[narrow_cast<std::size_t>(i)];\n}\n\ntemplate <class Cont>\nGSL_SUPPRESS(bounds.4) // NO-FORMAT: attribute\nGSL_SUPPRESS(bounds.2) // NO-FORMAT: attribute\nconstexpr auto at(Cont& cont, const index i) -> decltype(cont[cont.size()])\n{\n    Expects(i >= 0 && i < narrow_cast<index>(cont.size()));\n    using size_type = decltype(cont.size());\n    return cont[narrow_cast<size_type>(i)];\n}\n\ntemplate <class T>\nGSL_SUPPRESS(bounds.1) // NO-FORMAT: attribute\nconstexpr T at(const std::initializer_list<T> cont, const index i)\n{\n    Expects(i >= 0 && i < narrow_cast<index>(cont.size()));\n    return *(cont.begin() + i);\n}\n\n} // namespace gsl\n\n#if defined(_MSC_VER)\n#if _MSC_VER < 1910\n#undef constexpr\n#pragma pop_macro(\"constexpr\")\n\n#endif // _MSC_VER < 1910\n\n#pragma warning(pop)\n\n#endif // _MSC_VER\n\n#endif // GSL_UTIL_H\n", "meta": {"hexsha": "542bbaa252c3aa2aaed4389e635a55b5e0a70282", "size": 4688, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gsl/gsl_util.h", "max_stars_repo_name": "Redchards/CVRP", "max_stars_repo_head_hexsha": "f372f2fa06cb374ebdac2f6eee7e6fe297d94103", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-09-01T14:40:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-15T05:01:23.000Z", "max_issues_repo_path": "include/gsl/gsl_util.h", "max_issues_repo_name": "Redchards/CVRP", "max_issues_repo_head_hexsha": "f372f2fa06cb374ebdac2f6eee7e6fe297d94103", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gsl/gsl_util.h", "max_forks_repo_name": "Redchards/CVRP", "max_forks_repo_head_hexsha": "f372f2fa06cb374ebdac2f6eee7e6fe297d94103", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-02T17:50:23.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-26T08:25:35.000Z", "avg_line_length": 28.0718562874, "max_line_length": 99, "alphanum_fraction": 0.6657423208, "num_tokens": 1155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22815650216092534, "lm_q2_score": 0.054198729059333775, "lm_q1q2_score": 0.012365792443745293}}
{"text": "#include <stdlib.h>\n\n#include <gsl/gsl_statistics_double.h>\n#include <hdf5.h>\n#include <hdf5_hl.h>\n\n#include \"qdm.h\"\n\nqdm_ijk *\nqdm_ijk_alloc(\n    size_t size1,\n    size_t size2,\n    size_t size3\n)\n{\n  qdm_ijk *t = malloc(sizeof(qdm_ijk));\n\n  t->size1 = size1;\n  t->size2 = size2;\n  t->size3 = size3;\n\n  t->data = malloc(sizeof(double) * size1 * size2 * size3);\n  t->owner = true;\n\n  return t;\n}\n\nqdm_ijk *\nqdm_ijk_calloc(\n    size_t size1,\n    size_t size2,\n    size_t size3\n)\n{\n  qdm_ijk *t = malloc(sizeof(qdm_ijk));\n\n  t->size1 = size1;\n  t->size2 = size2;\n  t->size3 = size3;\n\n  t->data = calloc(sizeof(double), size1 * size2 * size3);\n  t->owner = true;\n\n  return t;\n}\n\nvoid\nqdm_ijk_free(\n    qdm_ijk *t\n)\n{\n  if (t == NULL) {\n    return;\n  }\n\n  if (t->owner) {\n    free(t->data);\n  }\n\n  free(t);\n}\n\nqdm_ijk_view\nqdm_ijk_view_array(\n    double *base,\n    size_t size1,\n    size_t size2,\n    size_t size3\n)\n{\n  qdm_ijk_view v = {\n    .ijk = {\n      .size1 = size1,\n      .size2 = size2,\n      .size3 = size3,\n\n      .data = base,\n      .owner = false,\n    },\n  };\n\n  return v;\n}\n\ngsl_vector_view\nqdm_ijk_get_k(\n    qdm_ijk *t,\n    size_t i,\n    size_t j\n)\n{\n  return gsl_vector_view_array_with_stride(\n      &t->data[i * t->size2 + j],\n      t->size1 * t->size2,\n      t->size3\n  );\n}\n\ngsl_matrix_view\nqdm_ijk_get_ij(\n    qdm_ijk *t,\n    size_t k\n)\n{\n  return gsl_matrix_view_array(\n      &t->data[k * t->size1 * t->size2],\n      t->size1,\n      t->size2\n  );\n}\n\ndouble\nqdm_ijk_get(\n    qdm_ijk *t,\n    size_t i,\n    size_t j,\n    size_t k\n)\n{\n  gsl_matrix_view ij = qdm_ijk_get_ij(t, k);\n\n  return gsl_matrix_get(&ij.matrix, i, j);\n}\n\ngsl_matrix *\nqdm_ijk_cov(\n    qdm_ijk *t\n)\n{\n  size_t d = t->size1 * t->size2;\n  size_t dr = 0;\n\n  gsl_matrix *r = gsl_matrix_calloc(d, d);\n\n  for (size_t i0 = 0; i0 < t->size1; i0++) {\n    for (size_t j0 = 0; j0 < t->size2; j0++) {\n      gsl_vector_view k0 = qdm_ijk_get_k(t, i0, j0);\n\n      /* TODO: When we have time (and if it matters), this is symmetric and we\n       * don't need to do a bunch of these if we get a little clever about\n       * copying the mirror'd results.\n       */\n      for (size_t ip = 0; ip < t->size1; ip++) {\n        for (size_t jp = 0; jp < t->size2; jp++) {\n          gsl_vector_view kp = qdm_ijk_get_k(t, ip, jp);\n\n          double cov = gsl_stats_covariance(\n              k0.vector.data,\n              k0.vector.stride,\n              kp.vector.data,\n              kp.vector.stride,\n              kp.vector.size\n          );\n\n          gsl_matrix_set(r, dr, ip * t->size2 + jp, cov);\n        }\n      }\n\n      dr++;\n    }\n  }\n\n  return r;\n}\n\nint\nqdm_ijk_write(\n    hid_t id,\n    const char *name,\n    const qdm_ijk *t\n)\n{\n  int status = 0;\n\n  hid_t datatype  = -1;\n  hid_t dataspace = -1;\n  hid_t dataset   = -1;\n\n  if (t == NULL) {\n    goto cleanup;\n  }\n\n  datatype = H5Tcopy(H5T_NATIVE_DOUBLE);\n\n  status = H5Tset_order(datatype, H5T_ORDER_LE);\n  if (status != 0) {\n    goto cleanup;\n  }\n\n  hsize_t dims[3] = {\n    t->size3,\n    t->size1,\n    t->size2,\n  };\n  dataspace = H5Screate_simple(3, dims, NULL);\n  if (dataspace < 0) {\n    status = dataspace;\n    goto cleanup;\n  }\n\n  dataset = H5Dcreate(id, name, datatype, dataspace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);\n  if (dataset < 0) {\n    status = dataset;\n    goto cleanup;\n  }\n\n  status = H5Dwrite(dataset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, t->data);\n  if (status != 0) {\n    goto cleanup;\n  }\n\ncleanup: \n  if (dataset >= 0) {\n    H5Dclose(dataset);\n  }\n\n  if (dataspace >= 0) {\n    H5Sclose(dataspace);\n  }\n\n  if (datatype >= 0) {\n    H5Tclose(datatype);\n  }\n\n  H5Oflush(id);\n\n  return status;\n}\n\nint\nqdm_ijk_read(\n    hid_t id,\n    const char *name,\n    qdm_ijk **t\n)\n{\n  int status = 0;\n\n  int rank = 0;\n\n  status = H5LTget_dataset_ndims(id, name, &rank);\n  if (status < 0) {\n    return status;\n  }\n\n  if (rank != 3) {\n    return -1;\n  }\n\n  hsize_t dims[3];\n\n  status = H5LTget_dataset_info(id, name, dims, NULL, NULL);\n  if (status < 0) {\n    return status;\n  }\n\n  size_t size3 = dims[0];\n  size_t size1 = dims[1];\n  size_t size2 = dims[2];\n\n  qdm_ijk *tmp = qdm_ijk_alloc(size1, size2, size3);\n\n  status = H5LTread_dataset_double(id, name, tmp->data);\n  if (status < 0) {\n    qdm_ijk_free(tmp);\n\n    return status;\n  }\n\n  *t = tmp;\n\n  return status;\n}\n", "meta": {"hexsha": "3f9e3e8d99c929acdc462fcb93ce404dd8f69315", "size": 4305, "ext": "c", "lang": "C", "max_stars_repo_path": "src/ijk.c", "max_stars_repo_name": "calebcase/qdm", "max_stars_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ijk.c", "max_issues_repo_name": "calebcase/qdm", "max_issues_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-03-06T18:09:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-22T20:22:53.000Z", "max_forks_repo_path": "src/ijk.c", "max_forks_repo_name": "calebcase/qdm", "max_forks_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.7116788321, "max_line_length": 92, "alphanum_fraction": 0.5718931475, "num_tokens": 1501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33111973962899144, "lm_q2_score": 0.03732688921821231, "lm_q1q2_score": 0.012359669839094669}}
{"text": "#ifndef UBLAS_LIB_ATLAS_H\n#define UBLAS_LIB_ATLAS_H\n\n#include <stdio.h>\n#include <ublas_types.h>\n#include <cblas.h>\n\nint ubf_init(void **ctx);\nint ubf_gemm(void *ctx, ublas_matrix *a, ublas_matrix *b, ublas_matrix *c, double alpha, double beta);\nint ubf_free(void *ctx);\n\n#endif", "meta": {"hexsha": "97f74e5f1487d00bf3d3130eb3b78bf598740dfd", "size": 278, "ext": "h", "lang": "C", "max_stars_repo_path": "src/drivers/atlas/atlas.h", "max_stars_repo_name": "brgmnn/uob-ublas", "max_stars_repo_head_hexsha": "770ae52382e2d7705ed3d990d8e33e6b6cc66e2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-13T03:13:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-13T03:13:08.000Z", "max_issues_repo_path": "src/drivers/atlas/atlas.h", "max_issues_repo_name": "brgmnn/uob-ublas", "max_issues_repo_head_hexsha": "770ae52382e2d7705ed3d990d8e33e6b6cc66e2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/drivers/atlas/atlas.h", "max_forks_repo_name": "brgmnn/uob-ublas", "max_forks_repo_head_hexsha": "770ae52382e2d7705ed3d990d8e33e6b6cc66e2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1666666667, "max_line_length": 102, "alphanum_fraction": 0.7553956835, "num_tokens": 86, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.03210070625402536, "lm_q1q2_score": 0.01235595168368572}}
{"text": "#ifndef _CCS_RNG_H\n#define _CCS_RNG_H\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#include <gsl/gsl_rng.h>\n\n/**\n * @file rng.h\n * CCS rng define random number generators. For now they are wrappers over gsl\n * random number generators.\n */\n\n/**\n * Create a new random number generator using the gsl default type (see\n * gsl_rng_default).\n * @param [out] rng_ret a pointer to the variable that will contain the returned\n *              random number generator\n * @return #CCS_SUCCESS on success\n * @return -#CCS_INVALID_VALUE if \\p rng_ret is NULL\n * @return -#CCS_OUT_OF_MEMORY if there was not enough memory to allocate the\n *                             new random number generator\n */\nextern ccs_result_t\nccs_rng_create(ccs_rng_t *rng_ret);\n\n/**\n * Create a new random number generator using the provided gsl type (see\n * gsl_rng_type).\n * @param [in] rng_type a pointer to the type of gsl random number generator to\n *                      use.\n * @param [out] rng_ret a pointer to the variable that will contain the returned\n *              random number generator\n * @return #CCS_SUCCESS on success\n * @return -#CCS_INVALID_VALUE if \\p rng_ret or \\p rng_type are NULL\n * @return -#CCS_OUT_OF_MEMORY if there was not enough memory to allocate the\n *                             new random number generator\n */\nextern ccs_result_t\nccs_rng_create_with_type(const gsl_rng_type *rng_type,\n                         ccs_rng_t          *rng_ret);\n\n/**\n * Get the gsl type of a random number generator.\n * @param [in] rng\n * @param [out] rng_type_ret a pointer that will contained a pointer to the\n *                           returned gsl random number generator type.\n * @return #CCS_SUCCESS on success\n * @return -#CCS_INVALID_OBJECT if \\p rng is not a valid CCS random number\n *                              generator\n * @return -#CCS_INVALID_VALUE if \\p rng_type_ret is NULL\n */\nextern ccs_result_t\nccs_rng_get_type(ccs_rng_t            rng,\n                 const gsl_rng_type **rng_type_ret);\n\n/**\n * Set the seed of a random number generator.\n * @param [in] rng\n * @param [in] seed the seed to use with the random number generator\n * @return #CCS_SUCCESS on success\n * @return -#CCS_INVALID_OBJECT if \\p rng is not a valid CCS random number\n *                              generator\n */\nextern ccs_result_t\nccs_rng_set_seed(ccs_rng_t         rng,\n                 unsigned long int seed);\n\n/**\n * Get a random integer from a random number generator. Integer is contained\n * between the value returned by #ccs_rng_min and #ccs_rng_max, both included.\n * @param [in] rng\n * @param [out] value_ret a pointer to the variable that will contain the\n *                        returned value\n * @return #CCS_SUCCESS on success\n * @return -#CCS_INVALID_OBJECT if \\p rng is not a valid CCS random number\n *                              generator\n * @return -#CCS_INVALID_VALUE if \\p value_ret is NULL\n */\nextern ccs_result_t\nccs_rng_get(ccs_rng_t          rng,\n            unsigned long int *value_ret);\n\n/**\n * Get a random floating point value uniformly sampled in the interval [0.0,\n * 1.0).\n * @param [in] rng\n * @param [out] value_ret a pointer to the variable that will contain the\n *                        returned value\n * @return #CCS_SUCCESS on success\n * @return -#CCS_INVALID_OBJECT if \\p rng is not a valid CCS random number\n *                              generator\n * @return -#CCS_INVALID_VALUE if \\p value_ret is NULL\n */\nextern ccs_result_t\nccs_rng_uniform(ccs_rng_t    rng,\n                ccs_float_t *value_ret);\n\n/**\n * Get the underlying gsl random number generator.\n * @param [in] rng\n * @param [out] gsl_rng_ret a pointer to the variable that will contain a\n *                          pointer to the underlying random number generator\n * @return #CCS_SUCCESS on success\n * @return -#CCS_INVALID_OBJECT if \\p rng is not a valid CCS random number\n *                              generator\n * @return -#CCS_INVALID_VALUE if \\p gsl_rng_ret is NULL\n */\nextern ccs_result_t\nccs_rng_get_gsl_rng(ccs_rng_t   rng,\n                    gsl_rng   **gsl_rng_ret);\n\n/**\n * Get the minimum value that can be returned by #ccs_rng_get.\n * @param [in] rng\n * @param [out] value_ret a pointer to the variable that will contain the\n *                        returned value\n * @return #CCS_SUCCESS on success\n * @return -#CCS_INVALID_OBJECT if \\p rng is not a valid CCS random number\n *                              generator\n * @return -#CCS_INVALID_VALUE if \\p value_ret is NULL\n */\nextern ccs_result_t\nccs_rng_min(ccs_rng_t          rng,\n            unsigned long int *value_ret);\n\n/**\n * Get the maximum value that can be returned by #ccs_rng_get.\n * @param [in] rng\n * @param [out] value_ret a pointer to the variable that will contain the\n *                        returned value\n * @return #CCS_SUCCESS on success\n * @return -#CCS_INVALID_OBJECT if \\p rng is not a valid CCS random number\n *                              generator\n * @return -#CCS_INVALID_VALUE if \\p value_ret is NULL\n */\nextern ccs_result_t\nccs_rng_max(ccs_rng_t          rng,\n            unsigned long int *value_ret);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif //_CCS_RNG_H\n", "meta": {"hexsha": "c43e31c28d569815a422a1bb8a480a91ae862506", "size": 5143, "ext": "h", "lang": "C", "max_stars_repo_path": "include/cconfigspace/rng.h", "max_stars_repo_name": "deephyper/CCS", "max_stars_repo_head_hexsha": "dd8c976eca2a510c995862cc5c871e81932f3ff4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-29T16:31:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T16:31:28.000Z", "max_issues_repo_path": "include/cconfigspace/rng.h", "max_issues_repo_name": "deephyper/CCS", "max_issues_repo_head_hexsha": "dd8c976eca2a510c995862cc5c871e81932f3ff4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-15T10:37:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-15T10:48:24.000Z", "max_forks_repo_path": "include/cconfigspace/rng.h", "max_forks_repo_name": "deephyper/CCS", "max_forks_repo_head_hexsha": "dd8c976eca2a510c995862cc5c871e81932f3ff4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-16T18:20:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-07T17:54:11.000Z", "avg_line_length": 34.75, "max_line_length": 80, "alphanum_fraction": 0.6521485514, "num_tokens": 1248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489886026626094, "lm_q2_score": 0.029760096742670904, "lm_q1q2_score": 0.012347430219947823}}
{"text": "//setzt constanten auf\n#define EXTERN_VARIABLES\n#include <stdio.h>\n#include <math.h>\n#include <gsl/gsl_sf_bessel.h>\n#include \"global.h\"\n#include \"utility.h\"\n#include \"steppmethods.h\"\n#include <gsl/gsl_cblas.h>\n#include <time.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <unistd.h>\n#include <omp.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n\n\n\nvoid Set_Target_Length(double * TARGET_LENGTH, double volfrac,  void (*Stepper_Method)(int N,  double  x[N/2] , double v[N/2], double a[N/2], double *t, \n\t\t\t\t\tvoid (*deriv) (double *y, double *ans, double t,int N)),\n\t\t\t\t\tvoid (*Poti_Handle) (double *y, double *ans, double t,int N))\n{\tint FLAG = 1;\n\t*TARGET_LENGTH = 0.0;\n\tif (Stepper_Method == VVerlet_Step_deriv)\n\t{  \n\t\t *TARGET_LENGTH = 0.0;\n\t\tprintf(\" No  Targets\\n\");\n\t\tFLAG = 0;\n\t}\n\t//if (Stepper_Method == VVerlet_Step_Target_Circle)\n\t//{\n\t//\t*TARGET_LENGTH = LATTICE_SPACING * sqrt(volfrac/ M_PI);\n\t//\tprintf(\" Targets set to hard circles\\n\");\n\t//} \n\n\tif (Stepper_Method == VVerlet_Step_hardsphere_reflect)\n\t{  \n\t\t *TARGET_LENGTH = LATTICE_SPACING * sqrt(volfrac/ M_PI);\n\t\tprintf(\" Targets set to hard circles\\n\");\n\t\tFLAG = 0;\n\t}\n\n\tif (Stepper_Method == VVerlet_Step_hardsphere_reflect_Kupf)\n\t{  \n\t\t *TARGET_LENGTH = LATTICE_SPACING * sqrt(volfrac/ M_PI);\n\t\tprintf(\" Targets set to hard circles Kupferman \\n\");\n\t\tFLAG = 0;\n\t}\n\n\tif (Stepper_Method == VVerlet_Step_hardsphere_reflect_all)\n\t{  \n\t\t *TARGET_LENGTH = LATTICE_SPACING * sqrt(volfrac/ M_PI);\n\t\tprintf(\" Targets set to hard circles, reflect ALL particles\\n\");\n\t\tFLAG = 0;\n\t}\n\n\tif (Stepper_Method == VVerlet_Step_deriv_Kupf)\n\t{  \n\t\t*TARGET_LENGTH = 0.0;\n\t\tprintf(\" No  Targets\\n, Kupfermann bath\");\n\t\tFLAG = 0;\n\t}\n\n\tif (Stepper_Method == VVerlet_Step_deriv_Box)\n\t{  \n\t\t //*TARGET_LENGTH = LATTICE_SPACING * sqrt(volfrac/ M_PI/5.0);\n\t\t//printf(\" Targets set to soft Yukawa circles in 3 per pore corner\\n\");\n\t\t*TARGET_LENGTH = 0;\n\t\tFLAG = 0;\n\t\tif (DIM > 1)\n\t\t{\n\t\t\tprintf(\"wrong Dimension, please switch to 1d\");\n\t\t\texit(1);\n\t\t}\n\t\tif (volfrac > 0.0)\n\t\t{\n\t\t\tprintf(\"no need for volume fractions >0 \\n\");\n\t\t\texit(1);\n\t\t}\n\t\tprintf(\"box set up with hard wall \\n\");\t\n\t}\n\tif(FLAG)\n\t{\n\t\tprintf(\"Kein bekannter Stepper in global, cannot set tarhet length!\\n\");\n\t\texit(1);\n\t}\n}\n\nvoid Constants(){\n// call to setup the bathh parameters and give rudimentary output for the run\n\tint i;\n\tOUTPUT_FLAG = 1; \n\tprintf (\"OSSZI = %d  DIM =%d  ORDER =%d  \\n\", OSSZI, DIM, ORDER);\n\tprintf (\"KBOLTZ = %e \\nTIME_STEPS =%f  \\nTIME_END =%f  \\n\", KBOLTZ, TIME_STEPS, TIME_END);\n\tfor(i=0;i<OSSZI;i++){\n\t\tcoupling[i] = 0.0;\n\t}\n\tfor(i=0;i<OSSZI;i++){\n\t\tommega[i] = 0.0;\n\t}\n\tfor(i=0;i<OSSZI;i++){\n\t\tmassq[i] = 1.0;\n\t}\n\tfor(i=0;i<ORDER;i++){\n\t\ty[i] = 1.0;\n\t}\n\tprintf(\"ALPHA = %1.2E  GAMMA = %1.2E  mass  = %1.2E \\n\", ALPHA, GAMMA, mass);\n\tprintf(\"NUMBER_TO_INF = %d  \\nTIME_ARRIVAL =%1.2E  \\n \", NUMBER_TO_INF, TIME_ARRIVAL);\n\tprintf(\"Startbedingungen = \"); \n\tprintf(\"%s\",LABEL); \n\tprintf(\"\\n\");\n\tif (!(OMMEGA_READ_BINARY))\n\t{\n\t\t// random Number Preparation for Taus GSL genrator\n\t\tgsl_rng * r;\n\t\tconst gsl_rng_type * T;\n\t\tgsl_rng_env_setup();\n\t\tT = gsl_rng_taus2;\n\t\tr = gsl_rng_alloc (T);\n\t\tgsl_rng_set(r, time(NULL)); // Seed with time\n\t\t// Random number end // \n\t    Ommega_Setup(r);\n\t    gsl_rng_free (r);\n\t}else\t// read in from ommega.dat\n\t{\n\t\tFILE *fp;\n\t\tfp = fopen(\"ommega.dat\", \"r\");\t\n\t\tfor (i=0;i<OSSZI;i++)\n\t\t{\n\t\t\tif (fscanf(fp, \"%lf\", &ommega[i]) != 1) \n\t\t\t{\n\t            printf(\"ERROT READING ommega.dat\");\n\t            break;\n        \t}\n\t\t}\n\t\tfclose(fp);\n\t\tprintf(\"read in ommega.dat\\n\");\n\t}\n\tif(VIRTUAL_FLAG) printf(\"Virtuelles Teilchen benutzt, ohne Badr\u00fcckkopplung\");\n  \tGamma_Setup(coupling);\n\t\n  \tdouble ommega_max = ommega[cblas_idamax(OSSZI, ommega, 1)];\n  \tdouble coupling_max = coupling[cblas_idamax(OSSZI, coupling, 1)];\n  \tprintf(\"MAX coupling =  %1.2e\\n\",coupling_max);\n  \tif(!(MAXSTEPSIZE_BINARY))\n\t{\n  \t\tMAXSTEPSIZE = (2*M_PI/ommega[cblas_idamax(OSSZI, ommega, 1)] * MAXSTEPSIZEMULT);\n  \t\tprintf(\"MAXSTEPSIZE =  %1.2e set according to smallest period times %3.3e\\n\",MAXSTEPSIZE, MAXSTEPSIZEMULT);\n  \t}else\n  \t{\n  \t\tMAXSTEPSIZE = (MAXSTEPSIZEMULT / (double) OSSZI);\n  \t\tprintf(\"MAXSTEPSIZE =  %1.2e set according to OSSZInr times Stepsize dt = %3.3e\\n\",MAXSTEPSIZE, MAXSTEPSIZEMULT);\n  \t}\n  \tSum_Method =  SUMMATION_METHOD;\n  \tStepper_Method = STEPPER_METHOD;\n  \tPoti_Handle = POTI_HANDLE;\n\n  \tint m = ipow(NUMBER_TO_INF,DIM); int n = DIM;\n  \t// Setze Gitter auf auf globale Matrix POSITIONS\n\tPOSITIONS = (double **) malloc(m * sizeof(int *));\n\tPOSITIONS[0] = (double *) malloc(m* n * sizeof(int));\n\tfor (i=1; i<m; i++) POSITIONS[i] = POSITIONS[0] + n *i;\n\tvec_zero_i(lattice_position,DIM);\n\tprintf(\"lattice allocated, current lattice cell set to zero\\n\");\n\tTARGET_CONTACT = 0;\n\tOUTPUT_FLAG = 0; // subsequent setup calls should not display text\n\tprintf(\"Running on %d threads, optimally DIM = %d\\n\", THREADS, DIM);\n\n\t// set masses for chosen type of coupling\n\tif( !(KUPF_BINARY) )\n\t{\n\t\tfor (int osi = 0; osi < OSSZI; osi ++)\t\t\t\n\t\t{\n\t\t\tmassq[osi] \t\t= 1.0;\n\t\t}\n\t\tprintf(\"Set all masses \u00e9qual\\n\");\n\t}else\n\t{\n\t\tfor (int osi = 0; osi < OSSZI; osi ++)\t\t\t\n\t\t{\n\t\t\tmassq[osi] \t\t= coupling[osi] / ommega[osi] / ommega[osi];\n\t\t\t\n\t\t}\n\t\tprintf(\"Set all masses according to k = m w^2l\\n\");\n\t}\n\t// Setup masses of bath for simpsons rule, split ends, odd and even parts\n\n\tif (SIMPSON_BINARY)\n\t{\n\t\tfor (int osi = 1; osi < OSSZI/2-1; osi ++)\n\t\t{\t\t\t\n\t\t\tmassq[osi * 2] \t\t*= 2.0/3.0;\n\t\t\tmassq[osi * 2 + 1] \t*= 4.0/3.0;\n\t\t}\n\t\tmassq[0] \t\t*= 1.0/3.0;;\n\t\tmassq[OSSZI-1] \t*= 1.0/3.0;\n\n\t\tif (KUPF_BINARY)\n\t\t{\n\t\t\tfor (int osi = 0; osi < OSSZI; osi ++)\t\t\t\n\t\t\t{\n\t\t\t\tcoupling[osi] = massq[osi] * ommega[osi] * ommega[osi];\n\t\t\t}\t\n\t\t}\n\t}\n}\n\n\n", "meta": {"hexsha": "9e0b2f1b28b55dfb5f230c3f1c6a212176b09067", "size": 5684, "ext": "c", "lang": "C", "max_stars_repo_path": "constants.c", "max_stars_repo_name": "nowottnm/KAC_ZWANZIG_SIM", "max_stars_repo_head_hexsha": "b8cacd50b7d307aeaa503b5a2f41cef4300f15a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "constants.c", "max_issues_repo_name": "nowottnm/KAC_ZWANZIG_SIM", "max_issues_repo_head_hexsha": "b8cacd50b7d307aeaa503b5a2f41cef4300f15a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "constants.c", "max_forks_repo_name": "nowottnm/KAC_ZWANZIG_SIM", "max_forks_repo_head_hexsha": "b8cacd50b7d307aeaa503b5a2f41cef4300f15a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0666666667, "max_line_length": 153, "alphanum_fraction": 0.6365235749, "num_tokens": 2059, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.026759282700350304, "lm_q1q2_score": 0.012336478327223269}}
{"text": "/* interpolation/gsl_interp.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2004 Gerard Jungman\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Author:  G. Jungman\n */\n#ifndef __GSL_INTERP_H__\n#define __GSL_INTERP_H__\n#include <stdlib.h>\n#include <gsl/gsl_inline.h>\n#include <gsl/gsl_types.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\n/* evaluation accelerator */\ntypedef struct {\n  size_t  cache;        /* cache of index   */\n  size_t  miss_count;   /* keep statistics  */\n  size_t  hit_count;\n}\ngsl_interp_accel;\n\n\n/* interpolation object type */\ntypedef struct {\n  const char * name;\n  unsigned int min_size;\n  void *  (*alloc) (size_t size);\n  int     (*init)    (void *, const double xa[], const double ya[], size_t size);\n  int     (*eval)    (const void *, const double xa[], const double ya[], size_t size, double x, gsl_interp_accel *, double * y);\n  int     (*eval_deriv)  (const void *, const double xa[], const double ya[], size_t size, double x, gsl_interp_accel *, double * y_p);\n  int     (*eval_deriv2) (const void *, const double xa[], const double ya[], size_t size, double x, gsl_interp_accel *, double * y_pp);\n  int     (*eval_integ)  (const void *, const double xa[], const double ya[], size_t size, gsl_interp_accel *, double a, double b, double * result);\n  void    (*free)         (void *);\n\n} gsl_interp_type;\n\n\n/* general interpolation object */\ntypedef struct {\n  const gsl_interp_type * type;\n  double  xmin;\n  double  xmax;\n  size_t  size;\n  void * state;\n} gsl_interp;\n\n\n/* available types */\nGSL_VAR const gsl_interp_type * gsl_interp_linear;\nGSL_VAR const gsl_interp_type * gsl_interp_polynomial;\nGSL_VAR const gsl_interp_type * gsl_interp_cspline;\nGSL_VAR const gsl_interp_type * gsl_interp_cspline_periodic;\nGSL_VAR const gsl_interp_type * gsl_interp_akima;\nGSL_VAR const gsl_interp_type * gsl_interp_akima_periodic;\n\ngsl_interp_accel *\ngsl_interp_accel_alloc(void);\n\nint\ngsl_interp_accel_reset (gsl_interp_accel * a);\n\nvoid\ngsl_interp_accel_free(gsl_interp_accel * a);\n\ngsl_interp *\ngsl_interp_alloc(const gsl_interp_type * T, size_t n);\n     \nint\ngsl_interp_init(gsl_interp * obj, const double xa[], const double ya[], size_t size);\n\nconst char * gsl_interp_name(const gsl_interp * interp);\nunsigned int gsl_interp_min_size(const gsl_interp * interp);\n\n\nint\ngsl_interp_eval_e(const gsl_interp * obj,\n                  const double xa[], const double ya[], double x,\n                  gsl_interp_accel * a, double * y);\n\ndouble\ngsl_interp_eval(const gsl_interp * obj,\n                const double xa[], const double ya[], double x,\n                gsl_interp_accel * a);\n\nint\ngsl_interp_eval_deriv_e(const gsl_interp * obj,\n                        const double xa[], const double ya[], double x,\n                        gsl_interp_accel * a,\n                        double * d);\n\ndouble\ngsl_interp_eval_deriv(const gsl_interp * obj,\n                      const double xa[], const double ya[], double x,\n                      gsl_interp_accel * a);\n\nint\ngsl_interp_eval_deriv2_e(const gsl_interp * obj,\n                         const double xa[], const double ya[], double x,\n                         gsl_interp_accel * a,\n                         double * d2);\n\ndouble\ngsl_interp_eval_deriv2(const gsl_interp * obj,\n                       const double xa[], const double ya[], double x,\n                       gsl_interp_accel * a);\n\nint\ngsl_interp_eval_integ_e(const gsl_interp * obj,\n                        const double xa[], const double ya[],\n                        double a, double b,\n                        gsl_interp_accel * acc,\n                        double * result);\n\ndouble\ngsl_interp_eval_integ(const gsl_interp * obj,\n                      const double xa[], const double ya[],\n                      double a, double b,\n                      gsl_interp_accel * acc);\n\nvoid\ngsl_interp_free(gsl_interp * interp);\n\nINLINE_DECL size_t\ngsl_interp_bsearch(const double x_array[], double x,\n                   size_t index_lo, size_t index_hi);\n\n#ifdef HAVE_INLINE\n\n/* Perform a binary search of an array of values.\n * \n * The parameters index_lo and index_hi provide an initial bracket,\n * and it is assumed that index_lo < index_hi. The resulting index\n * is guaranteed to be strictly less than index_hi and greater than\n * or equal to index_lo, so that the implicit bracket [index, index+1]\n * always corresponds to a region within the implicit value range of\n * the value array.\n *\n * Note that this means the relationship of 'x' to x_array[index]\n * and x_array[index+1] depends on the result region, i.e. the\n * behaviour at the boundaries may not correspond to what you\n * expect. We have the following complete specification of the\n * behaviour.\n * Suppose the input is x_array[] = { x0, x1, ..., xN }\n *    if ( x == x0 )           then  index == 0\n *    if ( x > x0 && x <= x1 ) then  index == 0, and sim. for other interior pts\n *    if ( x == xN )           then  index == N-1\n *    if ( x > xN )            then  index == N-1\n *    if ( x < x0 )            then  index == 0 \n */\n\nINLINE_FUN size_t\ngsl_interp_bsearch(const double x_array[], double x,\n                   size_t index_lo, size_t index_hi)\n{\n  size_t ilo = index_lo;\n  size_t ihi = index_hi;\n  while(ihi > ilo + 1) {\n    size_t i = (ihi + ilo)/2;\n    if(x_array[i] > x)\n      ihi = i;\n    else\n      ilo = i;\n  }\n  \n  return ilo;\n}\n#endif\n\nINLINE_DECL size_t \ngsl_interp_accel_find(gsl_interp_accel * a, const double x_array[], size_t size, double x);\n\n#ifdef HAVE_INLINE\nINLINE_FUN size_t\ngsl_interp_accel_find(gsl_interp_accel * a, const double xa[], size_t len, double x)\n{\n  size_t x_index = a->cache;\n \n  if(x < xa[x_index]) {\n    a->miss_count++;\n    a->cache = gsl_interp_bsearch(xa, x, 0, x_index);\n  }\n  else if(x >= xa[x_index + 1]) {\n    a->miss_count++;\n    a->cache = gsl_interp_bsearch(xa, x, x_index, len-1);\n  }\n  else {\n    a->hit_count++;\n  }\n  \n  return a->cache;\n}\n#endif /* HAVE_INLINE */\n\n\n__END_DECLS\n\n#endif /* __GSL_INTERP_H__ */\n", "meta": {"hexsha": "cfc60abc3c46bac3e7a1646599d5107206b8fd4f", "size": 6843, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gsl/gsl_interp.h", "max_stars_repo_name": "iti-luebeck/HANSE2011", "max_stars_repo_head_hexsha": "0bd5b3f1e0bc5a02516e7514b2241897337334c2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 77.0, "max_stars_repo_stars_event_min_datetime": "2015-01-18T00:45:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-24T22:20:56.000Z", "max_issues_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/interpolation/gsl_interp.h", "max_issues_repo_name": "skair39/structured", "max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-02-12T21:17:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-20T13:50:38.000Z", "max_forks_repo_path": "gsl/include/gsl/gsl_interp.h", "max_forks_repo_name": "gersteinlab/LESSeq", "max_forks_repo_head_hexsha": "bfc0a9aae081682a176e26d9804b980999595f16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2015-02-01T15:12:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-30T23:53:15.000Z", "avg_line_length": 30.5491071429, "max_line_length": 148, "alphanum_fraction": 0.6527838667, "num_tokens": 1716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39606816627404173, "lm_q2_score": 0.031143832558095677, "lm_q1q2_score": 0.012335080652030752}}
{"text": "/*\nCopyright (c) 2017, LibMars Developers.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n  list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n  this list of conditions and the following disclaimer in the documentation\n  and/or other materials provided with the distribution.\n\n* Neither the name of the copyright holder nor the names of its\n  contributors may be used to endorse or promote products derived from\n  this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n#ifndef MARS_HEADER_H\n#define MARS_HEADER_H 1\n\n#include <iostream>\n#include <cstring>\n#include <math.h>\n#include <inttypes.h>\n#include <fstream>\n#include <sstream>\n#include <iostream>\n#include <map>\n#include <iomanip>\n#include <iterator>\n#include <chrono>\n#include <typeinfo>\n#include <type_traits>\n#include <complex>\n#include <vector>\n#include <algorithm>\n#include <assert.h>\n#include <cassert>\n#include <csignal>\n#include <ctime>\n#include <stdarg.h>\n#include <stdexcept>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string>\n#include <string.h>\n#include <list>\n#include <set>\n#include <utility>\n#include <ctype.h>\n#include <deque>\n#include <initializer_list>\n#include <unordered_map>\n#include <unordered_set>\n#include <cstdint>\n#include <limits.h>\n\n#include <new>\n#include <locale>\n\n#define UNW_LOCAL_ONLY\n\n//#include <thread>\n#include <cxxabi.h>\n\n#include <dirent.h>\n#include <errno.h>\n#include <exception>\n#include <execinfo.h>\n#include <fcntl.h>\n\n#include <libgen.h>\n#include <libunwind.h>\n\n#include <regex>\n#include <semaphore.h>\n\n#include <signal.h>\n\n#include <sys/mman.h>\n#include <sys/shm.h>\n#include <sys/stat.h>\n#include <sys/time.h>\n#include <sys/types.h>\n#include <sys/wait.h>\n#include <sys/resource.h>\n\n#include <unistd.h>\n\n#include <gsl/gsl_cdf.h>\n#include <gsl/gsl_histogram.h>\n#include <gsl/gsl_randist.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_sf.h>\n#include <gsl/gsl_statistics.h>\n\n#include <fftw3.h>\n\n#include <boost/range/irange.hpp>\n#include <boost/functional/hash.hpp> /* hash std::pair<long,long> */\n\n#define MARS_COLOR_MODE   1\n#ifdef  MARS_COLOR_MODE\n\n#define MARS_COLOR_RED     \"\\033[22;31m\"\n#define MARS_COLOR_GREEN   \"\\033[22;32m\"\n#define MARS_COLOR_YELLOW  \"\\033[22;33m\"\n#define MARS_COLOR_BLUE    \"\\033[22;34m\"\n#define MARS_COLOR_MAGENTA \"\\033[22;35m\"\n//#define MARS_COLOR_CYAN    \"\\033[22;36m\"\n#define MARS_COLOR_CYAN    \"\\e[1;36m\" // bright cyan\n#define MARS_COLOR_WHITE   \"\\e[1;37m\"\n\n#define codef          \"\\033[0;22m\"\n#else\n#define MARS_COLOR_RED     \"\"\n#define MARS_COLOR_GREEN   \"\"\n#define MARS_COLOR_YELLOW  \"\"\n#define MARS_COLOR_BLUE    \"\"\n#define MARS_COLOR_MAGENTA \"\"\n#define MARS_COLOR_CYAN    \"\"\n\n#define CODEF         \"\"\n#endif\n\n#define COFUNC   MARS_COLOR_CYAN\n#define COFILE   MARS_COLOR_CYAN\n#define COFOLDER MARS_COLOR_BLUE\n#define COVAR    MARS_COLOR_RED\n#define COVAL    MARS_COLOR_WHITE\n#define COERR    MARS_COLOR_RED\n#define COWARN   MARS_COLOR_YELLOW\n\n#if __STDC_VERSION__ < 199901L\n#if __GNUC__ >= 2\n#define __FCN__ __PRETTY_FUNCTION__\n#else\n#define __FCN__ __func__\n#endif\n#endif\n\n#endif\n", "meta": {"hexsha": "4c7c4f4eb1df5724a7cf57026b1f4b89c2ca70dc", "size": 4076, "ext": "h", "lang": "C", "max_stars_repo_path": "mars_header.h", "max_stars_repo_name": "marsrobot/Tensor", "max_stars_repo_head_hexsha": "c8bf394334f7d9baad9d0305a591a1ad587ccd13", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-18T21:37:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-25T06:27:05.000Z", "max_issues_repo_path": "mars_header.h", "max_issues_repo_name": "marsrobot/Tensor", "max_issues_repo_head_hexsha": "c8bf394334f7d9baad9d0305a591a1ad587ccd13", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mars_header.h", "max_forks_repo_name": "marsrobot/Tensor", "max_forks_repo_head_hexsha": "c8bf394334f7d9baad9d0305a591a1ad587ccd13", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-02-26T01:54:08.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-15T04:07:37.000Z", "avg_line_length": 25.9617834395, "max_line_length": 78, "alphanum_fraction": 0.7568694799, "num_tokens": 1001, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29746995506106744, "lm_q2_score": 0.04146227256335484, "lm_q1q2_score": 0.012333780356150894}}
{"text": "/* err/gsl_errno.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#ifndef __GSL_ERRNO_H__\n#define __GSL_ERRNO_H__\n\n#include <stdio.h>\n#include <errno.h>\n#include <gsl/gsl_types.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\nenum { \n  GSL_SUCCESS  = 0, \n  GSL_FAILURE  = -1,\n  GSL_CONTINUE = -2,  /* iteration has not converged */\n  GSL_EDOM     = 1,   /* input domain error, e.g sqrt(-1) */\n  GSL_ERANGE   = 2,   /* output range error, e.g. exp(1e100) */\n  GSL_EFAULT   = 3,   /* invalid pointer */\n  GSL_EINVAL   = 4,   /* invalid argument supplied by user */\n  GSL_EFAILED  = 5,   /* generic failure */\n  GSL_EFACTOR  = 6,   /* factorization failed */\n  GSL_ESANITY  = 7,   /* sanity check failed - shouldn't happen */\n  GSL_ENOMEM   = 8,   /* malloc failed */\n  GSL_EBADFUNC = 9,   /* problem with user-supplied function */\n  GSL_ERUNAWAY = 10,  /* iterative process is out of control */\n  GSL_EMAXITER = 11,  /* exceeded max number of iterations */\n  GSL_EZERODIV = 12,  /* tried to divide by zero */\n  GSL_EBADTOL  = 13,  /* user specified an invalid tolerance */\n  GSL_ETOL     = 14,  /* failed to reach the specified tolerance */\n  GSL_EUNDRFLW = 15,  /* underflow */\n  GSL_EOVRFLW  = 16,  /* overflow  */\n  GSL_ELOSS    = 17,  /* loss of accuracy */\n  GSL_EROUND   = 18,  /* failed because of roundoff error */\n  GSL_EBADLEN  = 19,  /* matrix, vector lengths are not conformant */\n  GSL_ENOTSQR  = 20,  /* matrix not square */\n  GSL_ESING    = 21,  /* apparent singularity detected */\n  GSL_EDIVERGE = 22,  /* integral or series is divergent */\n  GSL_EUNSUP   = 23,  /* requested feature is not supported by the hardware */\n  GSL_EUNIMPL  = 24,  /* requested feature not (yet) implemented */\n  GSL_ECACHE   = 25,  /* cache limit exceeded */\n  GSL_ETABLE   = 26,  /* table limit exceeded */\n  GSL_ENOPROG  = 27,  /* iteration is not making progress towards solution */\n  GSL_ENOPROGJ = 28,  /* jacobian evaluations are not improving the solution */\n  GSL_ETOLF    = 29,  /* cannot reach the specified tolerance in F */\n  GSL_ETOLX    = 30,  /* cannot reach the specified tolerance in X */\n  GSL_ETOLG    = 31,  /* cannot reach the specified tolerance in gradient */\n  GSL_EOF      = 32   /* end of file */\n} ;\n\nvoid gsl_error (const char * reason, const char * file, int line,\n                int gsl_errno);\n\nvoid gsl_stream_printf (const char *label, const char *file,\n                        int line, const char *reason);\n\nconst char * gsl_strerror (const int gsl_errno);\n\ntypedef void gsl_error_handler_t (const char * reason, const char * file,\n                                  int line, int gsl_errno);\n\ntypedef void gsl_stream_handler_t (const char * label, const char * file,\n                                   int line, const char * reason);\n\ngsl_error_handler_t * \ngsl_set_error_handler (gsl_error_handler_t * new_handler);\n\ngsl_error_handler_t *\ngsl_set_error_handler_off (void);\n\ngsl_stream_handler_t * \ngsl_set_stream_handler (gsl_stream_handler_t * new_handler);\n\nFILE * gsl_set_stream (FILE * new_stream);\n\n/* GSL_ERROR: call the error handler, and return the error code */\n\n#define GSL_ERROR(reason, gsl_errno) \\\n       do { \\\n       gsl_error (reason, __FILE__, __LINE__, gsl_errno) ; \\\n       return gsl_errno ; \\\n       } while (0)\n\n/* GSL_ERROR_VAL: call the error handler, and return the given value */\n\n#define GSL_ERROR_VAL(reason, gsl_errno, value) \\\n       do { \\\n       gsl_error (reason, __FILE__, __LINE__, gsl_errno) ; \\\n       return value ; \\\n       } while (0)\n\n/* GSL_ERROR_VOID: call the error handler, and then return\n   (for void functions which still need to generate an error) */\n\n#define GSL_ERROR_VOID(reason, gsl_errno) \\\n       do { \\\n       gsl_error (reason, __FILE__, __LINE__, gsl_errno) ; \\\n       return ; \\\n       } while (0)\n\n/* GSL_ERROR_NULL suitable for out-of-memory conditions */\n\n#define GSL_ERROR_NULL(reason, gsl_errno) GSL_ERROR_VAL(reason, gsl_errno, 0)\n\n/* Sometimes you have several status results returned from\n * function calls and you want to combine them in some sensible\n * way. You cannot produce a \"total\" status condition, but you can\n * pick one from a set of conditions based on an implied hierarchy.\n *\n * In other words:\n *    you have: status_a, status_b, ...\n *    you want: status = (status_a if it is bad, or status_b if it is bad,...)\n *\n * In this example you consider status_a to be more important and\n * it is checked first, followed by the others in the order specified.\n *\n * Here are some dumb macros to do this.\n */\n#define GSL_ERROR_SELECT_2(a,b)       ((a) != GSL_SUCCESS ? (a) : ((b) != GSL_SUCCESS ? (b) : GSL_SUCCESS))\n#define GSL_ERROR_SELECT_3(a,b,c)     ((a) != GSL_SUCCESS ? (a) : GSL_ERROR_SELECT_2(b,c))\n#define GSL_ERROR_SELECT_4(a,b,c,d)   ((a) != GSL_SUCCESS ? (a) : GSL_ERROR_SELECT_3(b,c,d))\n#define GSL_ERROR_SELECT_5(a,b,c,d,e) ((a) != GSL_SUCCESS ? (a) : GSL_ERROR_SELECT_4(b,c,d,e))\n\n#define GSL_STATUS_UPDATE(sp, s) do { if ((s) != GSL_SUCCESS) *(sp) = (s);} while(0)\n\n__END_DECLS\n\n#endif /* __GSL_ERRNO_H__ */\n", "meta": {"hexsha": "d0be1b9bbc7ccd29aea8b8d7d724e02d465284e9", "size": 5938, "ext": "h", "lang": "C", "max_stars_repo_path": "gsl_subset/err/gsl_errno.h", "max_stars_repo_name": "pvnuffel/test_repos", "max_stars_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2015-04-29T05:13:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T02:07:41.000Z", "max_issues_repo_path": "gsl_subset/err/gsl_errno.h", "max_issues_repo_name": "pvnuffel/test_repos", "max_issues_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-11-07T05:42:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-20T16:32:02.000Z", "max_forks_repo_path": "gsl_subset/err/gsl_errno.h", "max_forks_repo_name": "pvnuffel/test_repos", "max_forks_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-04-29T20:31:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-10T03:09:53.000Z", "avg_line_length": 38.3096774194, "max_line_length": 107, "alphanum_fraction": 0.6737958909, "num_tokens": 1609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21733753118592733, "lm_q2_score": 0.05665242769705894, "lm_q1q2_score": 0.01231269877136804}}
{"text": "// Implementation of the interface described in viewer_window.h.\n\n#include <fcntl.h>\n#include <math.h>\n#include <stdint.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <unistd.h>\n\n#include <gtk/gtkgl.h>\n#include <gdk/gdk.h>\n#include <gdk/gdkkeysyms.h>\n\n#include <GL/gl.h>\n#include <GL/glu.h>\n\n#include <gsl/gsl_math.h>\n\n#include \"space_2d.h\"\n#include \"utilities.h\"\n#include \"viewer_window.h\"\n\n#ifdef G_LOG_DOMAIN\n#  undef G_LOG_DOMAIN\n#endif\n#define G_LOG_DOMAIN \"ViewerWindow\"\n\n// Flag true iff initialize_libraries has been run.\nstatic gboolean initialized = FALSE;\n\n// OpenGL configuration we use.\nstatic GdkGLConfig *glconfig = NULL;\n\n// Throw a fatal exception if an OpenGL error is found.\nstatic void\ntrap_opengl_errors (void)\n{\n  GLenum gl_error_code = glGetError ();\n  \n  if ( gl_error_code != GL_NO_ERROR ) {\n    g_error (__FILE__ \" line %d: OpenGL error detected: %s\", __LINE__,\n\t     gluErrorString (gl_error_code));\n  }\n}\n\n// Get a pointer to a blob of floating point data using fair means or\n// foul.  We want a blob st the region defined by start_x, start_y and\n// extending min (ceil (win_w / zoom), image->size_x) in the x\n// direction and min (ceil (win_h / zoom), image->size_y) in the y\n// direction (all in base image coordinates) is fully represented at\n// zoom factor zoom (as defined in ViewerWindow class) or better\n// (better meaning more detailed).  We return a pointer to the region,\n// the position of the upper left corner of the region with respect to\n// the base, the width and height of the returned data region in\n// pixels (actual pixels, not base pixels), the actual zoom factor of\n// the data retrieved, and a flag indicating if the returned memory is\n// otherwise unowned (if it is, then the caller is responsible for\n// freeing it, otherwise the caller must not).\nstatic void\nget_data_pointer (ViewerImage *image, size_t start_x, size_t start_y,\n\t\t  gfloat zoom, gint win_w, gint win_h, float **dp,\n\t\t  size_t *dp_start_x, size_t *dp_start_y, \n\t\t  size_t *dp_w, size_t *dp_h, gfloat *actual_zoom,\n\t\t  gboolean *unowned_memory)\n{\n  // Insist that (start_x, start_y) refers to an image pixel.\n  g_assert (start_x >= 0);\n  g_assert (start_x < image->size_x + image->x_offset);\n  g_assert (start_y >= 0);\n  g_assert (start_y < image->size_y + image->y_offset);\n  \n  // With a few small tweaks we might be able to make things work when\n  // zoomed in to the point of pixelation, but I haven't thought about\n  // it.\n  if ( zoom > 1.0 ) {\n    g_error (\"zoom factor %f is greater than 1.0\", zoom);\n  }\n  \n  guint layer_zoom = lrint (pow (2.0, floor (log2 (1.0 / zoom))));\n  ssize_t desired_width = GSL_MIN (ceil (win_w / zoom),\n\t\t\t\t   image->size_x - start_x);\n  ssize_t desired_height = GSL_MIN (ceil (win_h / zoom),\n\t\t\t\t    image->size_y - start_y);\n\n  if ( viewer_image_pyramid (image) != NULL ) {\n    *actual_zoom = 1.0 / layer_zoom;\n    // Ensure that floating point math has worked as expected since we\n    // validated the zoom input parameter.\n    g_assert (*actual_zoom <= 1.0);\n    pyramid_get_region (image->pyramid, start_x, start_y, desired_width,\n\t\t\tdesired_height, layer_zoom, dp, dp_start_x,\n\t\t\tdp_start_y, dp_w, dp_h, unowned_memory);\n  }    \n  else {\n    // The image pyramids aren't ready yet, so in the meantime we show\n    // the user some data from the quickview image, or if that isn't\n    // sufficiently high resolution, we form a new region.\n    if ( zoom <= 1.0 / image->quick_view_stride ) {\n      *dp = image->quick_view;\n      *dp_start_x = 0;\n      *dp_start_y = 0;\n      *dp_w = image->qvw;\n      *dp_h = image->qvh;\n      *actual_zoom = 1.0 / image->quick_view_stride;\n      *unowned_memory = FALSE;\n    }\n    else {\n      // We don't try to center our sample pixels in the middle of the\n      // areas they represent or anything, after all we are only doing\n      // this while the pyramid is prepared.\n      const size_t pixel_stride = layer_zoom;\n      *dp_start_x = start_x;\n      *dp_start_y = start_y;\n      *dp_w = desired_width / pixel_stride;\n      *dp_h = desired_height / pixel_stride;\n      size_t dp_area = *dp_w * *dp_h;\n      g_assert (dp_area > 0);\n      *dp = g_new (float, dp_area);\n      size_t ii, jj;\n      size_t cr = 0;\n      GString *data_name\n\t= my_g_string_new_printf (\"%s.img\", image->base_name->str);\n      int data_fd = open (data_name->str, O_RDONLY);\n      g_assert (data_fd != -1);\n      float *row_buffer = g_new (float, desired_width);\n      g_assert (row_buffer != NULL);\n      for ( jj = start_y ; jj <= desired_height - pixel_stride + start_y ;\n\t    jj += pixel_stride, cr++ ) {\n\tsize_t cc = 0;\n\toff_t row_offset = sizeof (float) * (jj * image->size_x + start_x);\n\toff_t lseek_result = lseek (data_fd, row_offset, SEEK_SET);\n\tg_assert (lseek_result == row_offset);\n\t// We don't bother trying to seek between samples in a row:\n\t// its highly unlikely to be any faster, even if the stride is\n\t// large.\n\tsize_t bytes_to_read = sizeof (float) * desired_width;\n\tg_assert (bytes_to_read <= SSIZE_MAX);\n\tssize_t bytes_read = read (data_fd, row_buffer, bytes_to_read);\n\tg_assert (bytes_read != -1);\n\tif ( bytes_read != bytes_to_read ) {\n\t  g_error (\"bytes_read (%llu) != bytes_to_read (%lld) while \"\n\t\t   \"attempting to read from file %s\",\n\t\t   (long long unsigned) bytes_read,\n\t\t   (long long int) bytes_to_read, data_name->str);\n\t}\n\tg_assert (bytes_read == bytes_to_read);\n\tfor ( ii = start_x ; ii <= desired_width - pixel_stride + start_x ;\n\t      ii += pixel_stride, cc++ ) {\n\t  float pv = row_buffer[ii - start_x];\n\t  if ( G_BYTE_ORDER == G_LITTLE_ENDIAN ) {\n\t    swap_bytes_32 ((unsigned char *) &pv);\n\t  }\n\t  if ( cr * *dp_w + cc >= dp_area ) {\n\t    g_error (\"internal memory allocation or reference error\");\n\t  }\n\t  (*dp)[cr * *dp_w + cc] = pv;\n\t}\n      }\n      int return_code = close (data_fd);\n      g_assert (return_code != -1);\n      my_g_string_free (data_name);\n      g_assert (row_buffer != NULL);\n      g_free (row_buffer);\n      *actual_zoom = 1.0 / pixel_stride;\n      *unowned_memory = TRUE;\n    }\n  }\n\n  return;\n}\n\n// Use the Space2d class to translate between big picture and OpenGL\n// orthographic view coordinates (implicit in this is an understanding\n// of the OpenGL projection in use -- see elsewhere).\nstatic void\ncoord_translate_big_picture_to_opengl (ViewerWindow *self,\n\t\t\t\t       gdouble *x, gdouble *y)\n{\n  GtkWidget *da = self->da;\n\n  Space2D *space = space_2d_new ();\n\n  // Register the big picture coordinate system.\n  CoordinateSystem2D *big_picture\n    = coordinate_system_2d_new (0.0, 0.0, 1.0, -1.0, 0.0, 0.0,\n\t\t\t\tself->max_x, self->max_y);\n  space_2d_add_system (space, NULL, big_picture);\n\n  // Register the virtual window coordinate system (which covers the\n  // entire big picture coordinate system, but at reduced resolution).\n  CoordinateSystem2D *virtual_window\n    = coordinate_system_2d_new (0.0, 0.0, 1.0 / self->zoom, 1.0 / self->zoom,\n\t\t\t\t0.0, 0.0, self->max_x * self->zoom,\n\t\t\t\tself->max_y * self->zoom);\n  space_2d_add_system (space, big_picture, virtual_window);\n\n  // Register the drawing area coordinates as Gdk/Gtk knows them.\n  CoordinateSystem2D *screen\n    = coordinate_system_2d_new (self->hadj->value, self->vadj->value, 1.0, 1.0,\n\t\t\t\t0.0, 0.0,\n\t\t\t\tda->allocation.width,\n\t\t\t\tda->allocation.height);\n  space_2d_add_system (space, virtual_window, screen);\n\n  CoordinateSystem2D *opengl_orthographic\n    = coordinate_system_2d_new (0.0, da->allocation.height, 1.0, -1.0,\n\t\t\t\t0.0, 0.0,\n\t\t\t\tda->allocation.width, da->allocation.height);\n  space_2d_add_system (space, screen, opengl_orthographic);\n\n  space_2d_translate (space, big_picture, opengl_orthographic, x, y);\n\n  space_2d_unref (space);\n}\n\n// Draw on the current gldrawable using the current glcontext in the\n// current viewport and projection (i.e. gdk_gl_drawable_gl_begin must\n// be in effect and the appropriate viewport and transformation\n// matricies set).\nstatic void\ndraw (ViewerWindow *viewer_window)\n{\n  ViewerWindow *self = viewer_window; // Convenience alias.\n  \n  glClear (GL_COLOR_BUFFER_BIT);\n  \n  gint win_w = self->da->allocation.width;\n  gint win_h = self->da->allocation.height;\n\n  if ( self->dp_to_free != NULL ) {\n    g_free (self->dp_to_free);\n    self->dp_to_free = NULL;\n  }\n\n  // Pointer to data to draw for current frame.\n  float *dp = NULL;\n\n  // Position of upper left corner of data pointed to by dp relative\n  // to base image.\n  size_t dp_start_x, dp_start_y;\n\n  // Width and height of memory region pointed to by dp.\n  size_t dp_w, dp_h;\n\n  // dp pixels per image pixel.\n  gfloat dp_zoom;\n\n  // Upper left pixel image coordinates to fetch.\n  size_t ulp_x = GSL_MAX (0, (self->hadj->value / self->zoom \n\t\t\t      - self->image->x_offset));\n  size_t ulp_y = GSL_MAX (0, (self->vadj->value / self->zoom\n\t\t\t      - self->image->y_offset));\n\n  gboolean must_free_dp;\n\n  // If we have anything to draw (once we get trimming set up we\n  // should always have).\n  if ( !(ulp_x >= self->image->size_x || ulp_y >= self->image->size_y) ) {\n\n    get_data_pointer (self->image, ulp_x, ulp_y, self->zoom,\n\t\t      win_w, win_h, &dp, &dp_start_x, &dp_start_y,\n\t\t      &dp_w, &dp_h, &dp_zoom, &must_free_dp);\n\n    // If we don't own the memory, we will need to free it before the\n    // next redraw, so save a pointer to it.\n    if ( must_free_dp ) {\n      self->dp_to_free = dp;\n    }\n    else {\n      self->dp_to_free = NULL;\n    }\n\n    // We may have to let OpenGL do a bit more zooming out for us,\n    // since the pixels in our data region dp may still be higher\n    // resolution than we need.\n    GLfloat residual_zoom = self->zoom / dp_zoom;\n  \n    g_assert (sizeof (int32_t) == sizeof (GLint));\n    g_assert (dp_w <= INT32_MAX);\n    glPixelStorei (GL_UNPACK_ROW_LENGTH, dp_w); \n\n    // Now we need to determine the actual region of interest in the\n    // returned data.  Here we determine the offsets in get_data\n    // coordinates of the point we want to put in the top left corner\n    // of the window.  // FIIXME: obviously the exact positioning of\n    // the raster image on screen is questionable after all the\n    // shenanegans we go through.  All that is really gauranteed is\n    // that the cursor cross hair rendering is right for a zoom factor\n    // of 1.0 on the OpenGL implementation I developed on (though I\n    // think it should be ok for other sane implementations as well).\n    // It would be lovely to fix this for other zoom factors (i.e. so\n    // when the cursor steps visibly off the edge of the image, the\n    // info command reports it as off), but I think this is actually\n    // pretty hard: it would need an special single interface through\n    // which all positioning command and queries could go, plus a\n    // detailed knowledge of what OpenGL actually specifies.  I'm not\n    // sure if it is even possible to use OpenGL commands to, say,\n    // draw the lines for the cursor and have things work out.  One\n    // might have to set pixel values in the image itself.  This way\n    // you only have to know precisly where the image is rendered,\n    // instead of precicely where the image is rendered, plus\n    // precisely where the drawing commands render, plus gaurantee\n    // that the two correspond perfectly.  Another possibility is to\n    // find a library like cairo and/or glitz that has already\n    // addressed these formidible issues, and use it.\n    GLint roi_offset_x\n      = GSL_MAX ((round (self->hadj->value / self->zoom) - dp_start_x\n\t\t  - self->image->x_offset) * dp_zoom, 0.0);\n    g_assert (roi_offset_x >= 0);\n    GLint roi_offset_y\n      = GSL_MAX ((round (self->vadj->value / self->zoom) - dp_start_y\n\t\t  - self->image->y_offset) * dp_zoom, 0.0);\n    g_assert (roi_offset_y >= 0);\n\n    glPixelStorei (GL_UNPACK_SKIP_ROWS, roi_offset_y);\n    glPixelStorei (GL_UNPACK_SKIP_PIXELS, roi_offset_x);\n\n    // Here we do a bit of defensive programming to avoid problems\n    // with floating point inexactness.  I'm not sure these assertions\n    // will always pass, it may be necessary to explicitly clamp the\n    // region of interest to be no wider than the remaining portion of\n    // the data region retrieved.\n\n    // One dimension of the data is probably smaller than the other,\n    // so we have these GSL_MIN calls to just use all the available\n    // data in a given direction if there isn't enough to fill the\n    // window.\n    GLint roi_w = GSL_MIN (dp_w - roi_offset_x,\n\t\t\t   ceil (win_w / residual_zoom));\n    g_assert (roi_offset_x + roi_w <= dp_w);\n    GLint roi_h = GSL_MIN (dp_h - roi_offset_y,\n\t\t\t   ceil (win_h / residual_zoom));\n    g_assert (roi_offset_y + roi_h <= dp_h);\n    \n    glPixelZoom (residual_zoom, -residual_zoom);\n\n    // Raster position to pass to glRasterPos.\n    GLdouble x_raster_pos \n      = GSL_MAX (round (self->image->x_offset * self->zoom)\n\t\t - self->hadj->value, 0);\n    GLdouble y_raster_pos\n      = (win_h - GSL_MAX (round (self->image->y_offset * self->zoom)\n\t\t\t  - self->vadj->value, 0));\n    // Sometimes floating point inexactness in the above expression\n    // may lead cause the entire image to get clipped (since OpenGL\n    // weirdly insists on clipping the entire image if the raster\n    // point is clipped).  Instead of going to the trouble of texture\n    // mapping the image onto a polygon (OpenGL doesn't clip the\n    // entire polygon), we just have a small check to ensure that we\n    // haven't slipped below zero.  But if we have slipped by very\n    // much, we need to rethink our algorithm.\n    GLdouble allowable_slop = 0.001;\n    if ( y_raster_pos > win_h ) {\n      g_assert (y_raster_pos < win_h + allowable_slop);\n      y_raster_pos = win_h;\n    }\n\n    // We would like the raster position to be exactly at the top of\n    // the window.  But some sort of floating point comparison\n    // problems seem to occur even when we ensure that this is the\n    // case with the above code, and then use a glRasterPos2i call.\n    // The only thing that seems to work is to use glRasterPos2f and\n    // then nudge the value down just slightly.  This gets us an image\n    // placed at the very top pixel of the window (no black line at\n    // the top) and doesn't seem to get the entire image clipped.  But\n    // I wouldn't be shocked to see other OpenGL implementation behave\n    // differently, possibly clipping the image out of existence.\n    GLdouble downward_nudge = 0.0001;\n    GLdouble rightward_nudge = downward_nudge;\n    glRasterPos2d (x_raster_pos + rightward_nudge,\n\t\t   y_raster_pos - downward_nudge);\n\n    // The range for which we will perform linear mapping.\n    gdouble linear_bottom, linear_top;\n    ViewerImage *ci = self->image;\n    if ( ci->sigmas <= 0.0 ) {\n      linear_bottom = ci->min;\n      linear_top = ci->max;\n    }\n    else {\n      linear_bottom = ci->mean - ci->sigmas * ci->sdev;\n      linear_top = ci->mean + ci->sigmas * ci->sdev;\n    }\n\n    float bias = linear_bottom;\n    float scale = linear_top - linear_bottom;\n\n    // FIIXME: should bias be negated here?  It works this way but seems\n    // strange.\n    glPixelTransferf (GL_RED_BIAS, bias / scale);\n    glPixelTransferf (GL_GREEN_BIAS, bias / scale);\n    glPixelTransferf (GL_BLUE_BIAS, bias / scale);\n    glPixelTransferf (GL_RED_SCALE, 1.0 / scale);\n    glPixelTransferf (GL_GREEN_SCALE, 1.0 / scale);\n    glPixelTransferf (GL_BLUE_SCALE, 1.0 / scale);\n\n    // OpenGL will clamp the results of the above scale and bias\n    // operations into the range [0, 1] for us, so at this point we\n    // have effectively implemented the advertised sigma clamping.\n\n    glDrawPixels (roi_w, roi_h, GL_LUMINANCE, GL_FLOAT, dp);\n  }\n\n  // If the cursor has been placed, draw it (it may get clipped, which\n  // is fine).\n  if ( self->cursor_x != -1 ) {\n    g_assert (self->cursor_y != -1);\n    const int cursor_size = 19;   // Cursor size, in pixels.\n    g_assert (cursor_size % 2 == 1);\n    gdouble x_ogl = self->cursor_x, y_ogl = self->cursor_y;\n    coord_translate_big_picture_to_opengl (self, &x_ogl, &y_ogl);\n    \n    // Deal with translation inexactness.\n    x_ogl = round (x_ogl);\n    y_ogl = round (y_ogl);\n\n    // The same trick we have to pull with the raster position for the\n    // image itself to keep the image from sometimes getting clipped,\n    // we have to pull here.  I'm not exactly sure why.\n            GLdouble downward_nudge = 0.1;\n            y_ogl -= downward_nudge;\n    // Looks like we also have to pull this trick in the x direction.\n    //        GLdouble rightward_nudge = downward_nudge;\n    //x_ogl += rightward_nudge;\n    \n\n    glColor3d (1.0, 0.0, 0.0);   // A pretty red cursor.\n\n    glBegin (GL_LINES);\n    {\n      glVertex2d (x_ogl - cursor_size / 2, y_ogl);\n      glVertex2d (x_ogl + cursor_size / 2, y_ogl);\n    }\n    glEnd ();\n    glBegin (GL_LINES);\n    {\n      glVertex2d (x_ogl, y_ogl - cursor_size / 2);\n      glVertex2d (x_ogl, y_ogl + cursor_size / 2);\n    }\n    glEnd ();\n    // Sigh... OpenGL is pixel-inexact.  The implementation I'm on\n    // seems to omit the pixel at the end of the line segment, others\n    // might do it differently.  So we explicitly add the end points\n    // as dots.  IMPROVEME: we're assuming dot size of 1 pixel here,\n    // this is a piece of OpenGL state that should be queried and\n    // asserted.\n    glBegin (GL_POINTS);\n    {\n      glVertex2d (x_ogl - cursor_size / 2, y_ogl);\n      glVertex2d (x_ogl + cursor_size / 2, y_ogl);\n      glVertex2d (x_ogl, y_ogl - cursor_size / 2);\n      glVertex2d (x_ogl, y_ogl + cursor_size / 2);\n    }\n    glEnd ();\n  }\n\n  // This code draws a little red X near the lower left corner of the\n  // window (maybe useful for sorting out flipping and clipping\n  // issues).\n  /*\n    glColor3d (1.0, 0.0, 0.0);\n    glBegin (GL_LINES);\n    glVertex2d (20, 20);\n    glVertex2d (80, 80);\n    glEnd ();\n    glBegin (GL_LINES);\n    glVertex2d (20, 80);\n    glVertex2d (80, 20);\n    glEnd ();\n  */\n  \n  trap_opengl_errors ();\n}\n\n// This is currently a no-op handler.  Its difficult to say exactly\n// when we want to prevent the user from making the window large (they\n// may be planning to zoom in as the next thing they do, so that\n// displayed space that is outside the big picture coordinate system\n// will then immediately get used).  And making the window big doesn't\n// happen by accident or cause a lot of confusion, so we don't worry\n// about it.\nstatic void\nreset_window_max_dimensions (ViewerWindow *self)\n{\n  // GdkGeometry hints;\n  // hints.max_width = self->max_x - self->hadj->value / self->zoom;\n  // hints.max_height = self->max_y - self->vadj->value / self->zoom;\n  // gtk_window_set_geometry_hints (GTK_WINDOW (self->w), self->da, &hints,\n  // \t\t\t\t    GDK_HINT_MAX_SIZE);\n}\n\n// Fetch the GdkGLContext and GdkGLDrawable associated with\n// drawing_area, call the draw routing to perform OpenGL rendering\n// according to the current state of self, and swap or flush buffer\n// (depending on double buffered status of the drawable).\nstatic void\nredraw_drawing_area (ViewerWindow *self, GtkWidget *drawing_area)\n{\n  GdkGLContext *glcontext = gtk_widget_get_gl_context (drawing_area);\n  GdkGLDrawable *gldrawable = gtk_widget_get_gl_drawable (drawing_area);\n\n  gboolean return_code = gdk_gl_drawable_gl_begin (gldrawable, glcontext);\n  g_assert (return_code);\n  {\n    draw (self);\n\n    if ( gdk_gl_drawable_is_double_buffered (gldrawable) ) {\n      gdk_gl_drawable_swap_buffers (gldrawable);\n    }\n    else {\n      // This code path is simple, but untested.\n      g_assert_not_reached ();\n      glFlush ();\n    }\n  }\n  gdk_gl_drawable_gl_end (gldrawable);\n}\n\n// Recompute the maximum window dimensions given self->zoom and the\n// current adjustment positions, and hint gtk appropriately, then\n// redraw the drawing area.\nstatic void\non_adjustment_changed (GtkAdjustment *adj, ViewerWindow *self)\n{\n  reset_window_max_dimensions (self);\n\n  redraw_drawing_area (self, self->da);\n\n  // FIIXME: I assume since the signature for this signal in the\n  // GtkAdjustment docs says this handler returns void, that either\n  // the default handler always runs and updates the rendering of the\n  // sliders themselves.  Confirm this.\n}\n\nstatic void\nafter_realize (GtkWidget *widget, gpointer data)\n{\n  ViewerWindow *self = data;\n\n  // It seems that only after we realize the drawing window do we\n  // really finally find out how big it really is.\n  GtkAdjustment *va = self->vadj, *ha = self->hadj;\n  va->page_size = self->da->allocation.height;\n  va->upper = ceil (GSL_MAX (self->max_y * self->zoom, va->page_size));\n  ha->page_size = self->da->allocation.width;\n  ha->upper = ceil (GSL_MAX (self->max_x * self->zoom, ha->page_size));\n\n  // In case Gtk needs to know to redraw its scrollbars (maybe the\n  // scrollbars get drawn before the drawing area is realized, I'm not\n  // sure).  We disable our handler since the drawing area will get\n  // redrawn anyway.\n  g_signal_handlers_block_by_func (va, on_adjustment_changed, self);\n  g_signal_handlers_block_by_func (ha, on_adjustment_changed, self);\n  g_signal_emit_by_name (va, \"changed::\");\n  g_signal_emit_by_name (ha, \"changed::\");\n  g_signal_handlers_unblock_by_func (ha, on_adjustment_changed, self);\n  g_signal_handlers_unblock_by_func (va, on_adjustment_changed, self);\n\n  GdkGLContext *glcontext = gtk_widget_get_gl_context (widget);\n  GdkGLDrawable *gldrawable = gtk_widget_get_gl_drawable (widget);\n\n  gboolean return_code = gdk_gl_drawable_gl_begin (gldrawable, glcontext);\n  g_assert (return_code);\n  {\n    draw (self);\n  }\n  gdk_gl_drawable_gl_end (gldrawable);\n}\n\ntypedef struct {\n  GtkAdjustment *vertical;\n  GtkAdjustment *horizontal;\n} marshaled_adjustments;\n\nstatic gboolean\non_drawing_area_configure_event (GtkWidget *widget, GdkEventConfigure *event,\n\t\t\t\t gpointer data)\n{\n  GdkGLContext *glcontext = gtk_widget_get_gl_context (widget);\n  GdkGLDrawable *gldrawable = gtk_widget_get_gl_drawable (widget);\n\n  gint w = widget->allocation.width, h = widget->allocation.height;\n\n  gboolean return_code = gdk_gl_drawable_gl_begin (gldrawable, glcontext);\n  g_assert (return_code);\n  {\n    glViewport (0, 0, w, h);\n    glMatrixMode (GL_PROJECTION);\n    glLoadIdentity ();\n    gluOrtho2D (0.0, (GLfloat) w, 0.0, (GLfloat) h);\n    glMatrixMode (GL_MODELVIEW);\n    glLoadIdentity ();\n  }\n  gdk_gl_drawable_gl_end (gldrawable);\n\n  ViewerWindow *self = data;\n\n  // Convenience aliases.\n  GtkAdjustment *ha = self->hadj, *va = self->vadj;\n\n  // We want the increments to be whole numbers, hence floor().\n  ha->step_increment = floor (w / 4.0);\n  ha->page_increment = floor (w / 2.0);\n  ha->page_size = w;\n  va->step_increment = floor (h / 4.0);\n  va->page_increment = floor (h / 2.0);\n  va->page_size = h;\n\n  // If the window is now bigger the the portion of the big picture\n  // domain with upper left corner at the same position it was before\n  // the resize, as rendered at this zoom level, go ahead and zoom in\n  // (leaving the upper left corner in the same position in big\n  // picture coordinates).\n\n  // Bottom right of big picture in current virtual window\n  // coordinates.  IMPROVEME: this way of handling resizing\n  // unfortunately pulls us off power-of-two zoom levels, which\n  // creates aliasing.  When power-of-two zoom level locking is\n  // implemented, probably what will need to happen is to make the big\n  // picture domain bigger by a precomputed amount so that we only\n  // need to zoom on resize if we can do it as a power of two.\n\n  // Bottom right of big picture coordinate domain in viewer window\n  // coordinates.\n  double brvw_x = self->max_x * self->zoom, brvw_y = self->max_y * self->zoom;\n\n  gfloat old_zoom = self->zoom;\n\n  if ( brvw_x - ha->value < w && brvw_y - va->value < h ) {\n    if ( (brvw_x - ha->value) / w > (brvw_y - va->value) / h ) {\n      self->zoom = (w + ha->value) / self->max_x;\n    }\n    else {\n      self->zoom = (w + va->value) / self->max_y;\n    }\n\n    // Since we don't zooming to the point of pixelation at the\n    // moment, floating inexactness in the above code can trip us up\n    // elsewhere.  It would also be nice to clamp to power of two or\n    // using antialiasing convolution filtering in OpenGL, as\n    // mentioned elsewhere.\n    if ( self->zoom > 1.0 ) {\n      gdouble max_slop = 0.01;\n      // If this isn't a small correction, we probably have a genuine\n      // problem somewhere.\n      if ( self->zoom - 1.0 > max_slop ) {\n\tg_error (\"floating point slop too large: self->zoom - 1.0 = %lf\\n\",\n\t\t self->zoom - 1.0);\n      }\n      self->zoom = 1.0; \n    }\n\n    ha->value = round (ha->value * self->zoom / old_zoom);\n    va->value = round (va->value * self->zoom / old_zoom);\n\n    ha->upper = ceil (GSL_MAX (self->max_x * self->zoom, ha->page_size));\n    va->upper = ceil (GSL_MAX (self->max_x * self->zoom, va->page_size));\n  }\n\n  // FIIXME: confirm: I don't think we need or want to emit any changed\n  // signals for the adjustments here, since if we get a configure\n  // event we should also get an expose event or the like which should\n  // redraw the scroll bars and image area correctly anyway.  It seems\n  // to work.\n  //  g_signal_emit_by_name (self->hadj, \"changed::\");\n  //  g_signal_emit_by_name (self->vadj, \"changed::\");\n\n  return TRUE;\n}\n\nstatic gboolean\non_expose_event (GtkWidget *widget, GdkEventExpose *event, ViewerWindow *self)\n{\n  redraw_drawing_area (self, widget);\n\n  return TRUE;\n}\n\nstatic gboolean\non_button_press_event (GtkWidget *widget, GdkEventButton *event,\n\t\t       ViewerWindow *self)\n{\n  // Here I test out the mental economy of my Space2D class.  Indulge\n  // me.  It would of course be more economical to keep the coordinate\n  // systems around more permanently somewhere else.\n  Space2D *space = space_2d_new ();\n\n  // Register the big picture coordinate system.\n  CoordinateSystem2D *big_picture\n    = coordinate_system_2d_new (0.0, 0.0, 1.0, -1.0, 0.0, 0.0,\n\t\t\t\tself->max_x, self->max_y);\n  space_2d_add_system (space, NULL, big_picture);\n\n  // Register the virtual window coordinate system (which covers the\n  // entire big picture coordinate system, but at reduced resolution).\n  CoordinateSystem2D *virtual_window\n    = coordinate_system_2d_new (0.0, 0.0, 1.0 / self->zoom, 1.0 / self->zoom,\n\t\t\t\t0.0, 0.0, self->max_x * self->zoom,\n\t\t\t\tself->max_y * self->zoom);\n  space_2d_add_system (space, big_picture, virtual_window);\n\n  // Register the drawing area coordinates as Gdk/Gtk knows them.\n  CoordinateSystem2D *screen\n    = coordinate_system_2d_new (self->hadj->value, self->vadj->value, 1.0, 1.0,\n\t\t\t\t0.0, 0.0,\n\t\t\t\twidget->allocation.width,\n\t\t\t\twidget->allocation.height);\n  space_2d_add_system (space, virtual_window, screen);\n\n  // Register the current image under the big picture system.\n  ViewerImage *ci = self->image;   // Convenience alias.\n  CoordinateSystem2D *current_image\n    = coordinate_system_2d_new (ci->x_offset, ci->y_offset, 1.0, 1.0,\n\t\t\t\t0.0, 0.0, ci->size_x - 1, ci->size_y - 1);\n  space_2d_add_system (space, big_picture, current_image);\n\n  // Now we should be able to effortlessly translate the window\n  // coordinates given to us in the GdkEventButton structure into\n  // coordinates in (or not in, as the case may be) the current image.\n  gdouble xc = event->x, yc = event->y;\n  space_2d_translate (space, screen, big_picture, &xc, &yc);\n\n  space_2d_unref (space);\n\n  if ( event->button == 1 ) {\n    self->cursor_x = xc;\n    self->cursor_y = yc;\n  }\n\n  redraw_drawing_area (self, self->da);\n\n  return FALSE;  // Return FALSE tell Gtk to go ahead and propagate event.\n}\n\n// Convert a GDK state, keyval pair to a single representative\n// character.\nstatic gchar\nfind_key_op (guint state, guint keyval)\n{\n  if ( keyval == GDK_minus ) {\n    return '-';\n  }\n  if ( state | GDK_SHIFT_MASK && keyval == GDK_plus ) {\n    return '+';\n  }\n  if ( keyval == GDK_N ) {\n    return 'N';\n  }\n  if ( keyval == GDK_n ) {\n    return 'n';\n  }\n  if ( keyval == GDK_P ) {\n    return 'P';\n  }\n  if ( keyval == GDK_p ) {\n    return 'p';\n  }\n  if ( keyval == GDK_I ) {\n    return 'I';\n  }\n  if ( keyval == GDK_i ) {\n    return 'i';\n  }\n  if ( keyval == GDK_a ) {\n    return 'a';\n  }\n  if ( keyval == GDK_A ) {\n    return 'a';\n  }\n  // When Escape is pressed this routing returns... 'e'.  Pretty silly\n  // but oh well, we didn't envision wanting Esc and our caller knows\n  // what 'e' means.\n  if ( keyval == GDK_Escape ) {\n    return 'e';\n  }\n\n  // We use this magic to mean \"otherwise unrecognized key press\".\n  return '~';\n}\n\n// Print to standard output some information about the pixel at the\n// current cursor position.\nstatic void\nprint_point_info_for_cursor (ViewerWindow *self)\n{\n  // Convert cursor coordinates to current image coordinates.\n  size_t img_x = self->cursor_x - self->image->x_offset;\n  size_t img_y = self->cursor_y - self->image->y_offset;\n\n  g_print (\"\\n\");\n  if ( self->cursor_x == -1 ) {\n    g_assert (self->cursor_y == -1);   // By definition.\n    g_print (\"Pixel info requested, but the cursor hasn't been placed yet.\\n\"\n\t     \"Left click on the image to place it.\\n\");\n\n  }\n  else if ( img_x >= 0 && img_x < self->image->size_x\n       && img_y >= 0 && img_y < self->image->size_y ) {\n    // Look up the value of the current pixel in the data file.\n    GString *data_file = g_string_new (self->image->base_name->str);\n    g_string_append (data_file, \".img\");\n    // IMPROVEME: it would be nice to through in a check to make sure\n    // the file size is what we expect, to help catch file changes\n    // while the viewer is running.\n    FILE *df = fopen (data_file->str, \"r\");\n    g_assert (df != NULL);\n    off_t offset = (img_y * self->image->size_x + img_x) * sizeof (float);\n    int return_code = fseeko (df, offset, SEEK_SET);\n    g_assert (return_code == 0);\n    float pixel_value;\n    size_t read_count = fread (&pixel_value, sizeof(float), 1, df);\n    g_assert (read_count == 1);\n    return_code = fclose (df);\n    g_assert (return_code == 0);\n    if ( G_BYTE_ORDER == G_LITTLE_ENDIAN ) {\n      swap_bytes_32 ((unsigned char *) &pixel_value);\n    }\n    g_print (\"Pixel information:\\n\");\n    g_print (\"------------------------------------------------------------\\n\");\n    g_print (\"File base name: %s\\n\", self->image->base_name->str);\n    g_print (\"Image pixel (row, column): (%d, %d)\\n\", img_x, img_y);\n    g_print (\"Pixel value: %f\\n\", pixel_value);\n  }\n  else {\n    g_print (\"Current cursor position is outside current image.  Left click\\n\"\n\t     \"on the image to reposition the cursor inside the image.\\n\");\n  }\n  g_print (\"\\n\");\n}\n\n// Run the analysis program on the tile surrounding the current cursor\n// position using the analysis-program related data members.\nstatic void\nrun_analysis (ViewerWindow *self)\n{\n  g_assert (self->cursor_x != -1);\n  g_assert (self->cursor_y != -1);\n  g_assert (self->analysis_program != NULL);\n\n  GString *command_line = g_string_new (self->analysis_program->str);\n\n  g_string_append_c (command_line, ' ');\n  \n  g_string_append_printf (command_line, \"%u \", self->images->len);\n\n  // We will end up creating a bunch of temporary files that we'll\n  // need to remove.\n  GPtrArray *tmp_files = g_ptr_array_new ();\n\n  guint ii;\n  for ( ii = 0 ; ii < self->images->len ; ii++ ) {\n\n    ViewerImage *ci = g_ptr_array_index (self->images, ii);   // Current image.\n\n    g_string_append_printf (command_line, \"%s \", ci->base_name->str);\n\n    ssize_t image_x = self->cursor_x - ci->x_offset;\n    ssize_t image_y = self->cursor_y - ci->y_offset;\n\n    // Start x and start y of tile in image.\n    size_t start_x = image_x - self->analysis_tile_size / 2;\n    size_t start_y = image_y - self->analysis_tile_size / 2;\n\n    // Tile width and height.\n    ssize_t tw = self->analysis_tile_size; \n    ssize_t th = self->analysis_tile_size;\n\n    // Adjust dimensions and/or starting point if near image edges.\n    if ( image_x - self->analysis_tile_size / 2 < 0 ) {\n      start_x = 0;\n      tw += image_x - self->analysis_tile_size / 2;\n    }\n    if ( image_x + self->analysis_tile_size / 2 >= ci->size_x ) {\n      size_t overhang\n\t= image_x + self->analysis_tile_size / 2 - ci->size_x + 1;\n      //      start_x -= overhang;\n      tw -= overhang;\n    }\n    if ( tw < 0 ) {\n      tw = 0;\n    }\n    if ( image_y - self->analysis_tile_size / 2 < 0 ) {\n      start_y = 0;\n      th += image_y - self->analysis_tile_size / 2;\n    }\n    if ( image_y + self->analysis_tile_size / 2 >= ci->size_y ) {\n      size_t overhang\n\t= image_y + self->analysis_tile_size / 2 - ci->size_y + 1;\n      //      start_y -= overhang;\n      th -= overhang;\n    }\n    if ( th < 0 ) {\n      th = 0;\n    }\n\n    g_string_append_printf (command_line, \"%lld %lld \",\n\t\t\t    (long long int) tw, (long long int) th);\n\n    // Read the actual tile data.\n    GString *data_name = g_string_new (ci->base_name->str);\n    g_string_append (data_name, \".img\");\n    float *tile_data = my_read_data_rectangle (data_name->str, sizeof (float),\n\t\t\t\t\t       ci->size_x, start_x, start_y,\n\t\t\t\t\t       tw, th);\n    swap_array_bytes_32 (tile_data, tw * th);\n    \n    // Store tile data in temporary file for use by analysis program.\n    // For uniqueness :)\n    GString *tile_tmp_file_name\n      = make_unique_tmp_file_name (\"/tmp\", \"blagLEweird\");\n    g_ptr_array_add (tmp_files, tile_tmp_file_name);\n    if ( tw > 0 && th > 0 ) {\n      g_assert (tw <= SSIZE_MAX);\n      g_assert (th <= SSIZE_MAX);\n      FloatImage *tile_fi = float_image_new_from_memory (tw, th, tile_data);\n      // FIIXME: verify: works for zero width or height tiles?\n      int return_code = float_image_store (tile_fi, tile_tmp_file_name->str,\n\t\t\t\t\t   FLOAT_IMAGE_BYTE_ORDER_BIG_ENDIAN);\n      g_assert (return_code == 0);\n    }\n    else {\n      // We have a tile file of size zero, which the float_image\n      // interface doesn't contend with, so we just use touch to\n      // create an empty file.\n      GString *touch_command = g_string_new (\"touch \");\n      g_string_append (touch_command, tile_tmp_file_name->str);\n      int exit_code = system (touch_command->str);\n      g_assert (exit_code == 0);\n      g_string_free (touch_command, TRUE);\n    }\n    g_string_append_printf (command_line, \"%s \", tile_tmp_file_name->str);\n  }\n\n  if ( self->async_analysis ) {\n    // IMPROVEME: in an ideal world we might document somehow for the\n    // user the fact that when analysis commands are run\n    // asynchronously, the temporary tile files that are created need\n    // to be removed by the analysis program itself.\n    GError *err = NULL;\n    gboolean exit_code = g_spawn_command_line_async (command_line->str, &err);\n    if ( ! exit_code ) {\n      g_printerr (\"\\nasynchronous analysis command execution failed: %s\\n\",\n\t\t  err->message);\n    }\n  }\n  else {\n    // FIIXME: confirm: I'm guess glib allocates these for us.\n    gchar *standard_output = NULL, *standard_error = NULL;\n    gint exit_status;\n    GError *err = NULL;\n    gboolean exit_code\n      = g_spawn_command_line_sync (command_line->str, &standard_output,\n\t\t\t\t   &standard_error, &exit_status, &err);\n    if ( standard_output != NULL ) {\n      g_print (\"%s\", standard_output);\n    }\n    if ( standard_error != NULL ) {\n      g_printerr (\"%s\", standard_error);\n    }\n    if ( ! exit_code ) {\n      g_printerr (\"\\nanalysis command execution failed: %s\\n\", err->message);\n    }\n  }\n}\n\n// Zoom in one step (power of two).  We have to do a lot of special\n// stuff at minimum or maximum zoom, around image edges, etc.\nstatic void\nstep_zoom_in (ViewerWindow *self)\n{\n  // At most one screen pixel per image pixel.\n  const gfloat max_zoom = 1.0; \n\n  // Remember old values so we can adjust the adjustments correctly.\n  GtkAdjustment *va = self->vadj, *ha = self->hadj;\n  gdouble v_old_upper = va->upper, h_old_upper = ha->upper;\n  gdouble v_old_middle = va->value + va->page_size / 2.0;\n  gdouble h_old_middle = ha->value + ha->page_size / 2.0;\n  gfloat old_zoom = self->zoom;\n\n  // Zoom, but only up to the maximum.  IMPROVEME: it would be best to\n  // only zoom by factors of 2.0, even when the window is resized.\n  // The pyramids are of these powers naturally, so no additional\n  // OpenGL scaling needs to be done.  The additional scaling probably\n  // introduces aliasing, which is kind of a shame since the whole\n  // point of building the pyramids is to produce good looking results\n  // at different resolutions.  For now, we just clamp to powers ot\n  // two here in the zoom in/out code, not in the code that handles\n  // window resizing.  This is somewhat reasonable, since doing this\n  // gives the user our best available rendering when they try to look\n  // at something in detail, which is when it counts.  It isn't really\n  // the ideal arrangement though.  Another potential option is to use\n  // an antialiasing OpenGL convolution filter.  But I'm not sure\n  // exactly how to do that, or even what the tradeoffs are exactly.\n  self->zoom *= 2.0;\n  // Clamp to a power of 2.0.\n  gdouble power = round (log2 (self->zoom));\n  self->zoom = pow (2.0, power);\n  if ( self->zoom > max_zoom ) {\n    self->zoom = max_zoom;\n  }\n  \n  // Compute the new upper value and current value of the adjustments,\n  // given the new virtual window size.\n  gfloat zoom_ratio = self->zoom / old_zoom;\n\n  // Update the vertical adjustment.\n  \n  va->upper = ceil (va->upper * zoom_ratio);\n  \n  gfloat v_new_middle = v_old_middle * va->upper / v_old_upper;\n  \n  // When we zoom, we may end up with a different part of the image in\n  // the center, since we try to avoid showing areas not in the big\n  // picture coordinate system, and configure events may have changed\n  // the window size.\n  if ( v_new_middle < va->page_size / 2.0 ) {\n    v_new_middle = va->page_size / 2.0;\n  }\n  if ( v_new_middle > va->upper - va->page_size / 2.0 ) {\n    v_new_middle = GSL_MAX (va->upper - va->page_size / 2.0,\n\t\t\t    va->page_size / 2.0);\n  }\n  va->value = round (v_new_middle - va->page_size / 2.0);\n  // Floating point math might put us off by a tiny bit, so we check\n  // for this and clamp if needed.\n  const gfloat max_slop = 0.4;      \n  if ( va->value < 0.0) {\n    // We should only be dealing with slight floating point\n    // inexactness here.\n    g_assert (va->value >= -0.4);\n    va->value = 0.0;\n  }\n  if ( va->value > va->upper - va->page_size ) {\n    g_assert (va->value - (va->upper - va->page_size) <= max_slop);\n    va->value = va->upper - va->page_size;\n  }\n  \n  // Update the horizontal adjustment.\n  \n  ha->upper = ceil (ha->upper * zoom_ratio);\n  \n  gfloat h_new_middle = h_old_middle * ha->upper / h_old_upper;\n  \n  // When we zoom, we may end up with a different part of the image in\n  // the center, since we try to avoid showing areas not in the big\n  // picture coordinate system, and configure events may have changed\n  // the window size.\n  if ( h_new_middle < ha->page_size / 2.0 ) {\n    h_new_middle = ha->page_size / 2.0;\n  }\n  if ( h_new_middle > ha->upper - ha->page_size / 2.0 ) {\n    h_new_middle = GSL_MAX (ha->upper - ha->page_size / 2.0,\n\t\t\t    ha->page_size / 2.0);\n  }\n  ha->value = round (h_new_middle - ha->page_size / 2.0);\n  if ( ha->value < 0.0 ) {\n    // We should only be dealing with slight floating point\n    // inexactness here.\n    g_assert (ha->value >= -max_slop);\n    ha->value = 0.0;\n  }\n  if ( ha->value > ha->upper - ha->page_size ) {\n    gdouble slop = ha->value - (ha->upper - ha->page_size);\n    // FIIXME: I swear I got this condition to trip once at this slop\n    // threshold.  So it might be necessary to change this into a\n    // warning, or loosen the tolerance a bit.\n    if ( slop > max_slop ) {\n      g_error (\"too much slop (%lf) in floating point calculation in \"\n\t       \"file \" __FILE__ \" function %s, line %d\", slop, __func__,\n\t       __LINE__);\n    }\n    ha->value = round (ha->upper - ha->page_size);\n  }\n\n  // We unblock our own handler for three of the next four\n  // adjustment-related emissions, since all it does it recompute\n  // and rehint the max window dimensions and redraw the drawing\n  // area.  Doing this once is enough.  But we do want gtk to have\n  // a chance to run any code it needs to run to redraw the\n  // scrollbars and such.\n  gint block_count\n    = g_signal_handlers_block_by_func (va, on_adjustment_changed, self);\n  g_assert (block_count == 2);\n  block_count\n    = g_signal_handlers_block_by_func (ha, on_adjustment_changed, self);\n  g_assert (block_count == 2);\n  {\n    g_signal_emit_by_name (va, \"changed::\");\n    g_signal_emit_by_name (ha, \"changed::\");\n    // IMPROVEME: Do we need both changed and value-changed\n    // emmisions?  Gtk docs seem to suggest we do as of this\n    // writing, but this seems like a pretty silly requirement.\n    g_signal_emit_by_name (va, \"value-changed::\");\n  }\n  gint unblock_count\n    = g_signal_handlers_unblock_by_func (ha, on_adjustment_changed, self);\n  g_assert (unblock_count == 2);\n  unblock_count\n    = g_signal_handlers_unblock_by_func (va, on_adjustment_changed, self);\n  g_assert (unblock_count == 2);\n  g_signal_emit_by_name (ha, \"value-changed::\");\n}\n\nstatic void\nstep_zoom_out (ViewerWindow *self) {\n  // Remember old values so we can adjust the adjustments correctly.\n  GtkAdjustment *va = self->vadj, *ha = self->hadj;\n  gdouble v_old_middle = va->value + va->page_size / 2.0;\n  gdouble h_old_middle = ha->value + ha->page_size / 2.0;\n  gfloat old_zoom = self->zoom;\n\n  // The maximum zoom out we will allow is one that displays the\n  // entire big picture coordinate systme in the current window.\n  const gfloat min_zoom = GSL_MIN (ha->page_size / self->max_x,\n\t\t\t\t   va->page_size / self->max_y);\n\n  // Zoom, but only out to the maximum.\n  self->zoom /= 2.0;\n  if ( self->zoom < min_zoom ) {\n    self->zoom = min_zoom;\n  }\n\n  // Compute the new upper value and current value of the adjustments,\n  // given the new virtual window size.\n  gfloat zoom_ratio = self->zoom / old_zoom;\n\n  // Update the vertical adjustment.\n\n  va->upper = ceil (GSL_MAX (self->max_y * self->zoom, va->page_size));\n\n  gfloat v_new_middle = v_old_middle * zoom_ratio;\n  // When we zoom out, we may end up with a different part of the\n  // image in the center, since we try to avoid showing areas not in\n  // the big picture coordinate system.\n  if ( v_new_middle < va->page_size / 2.0 ) {\n    v_new_middle = va->page_size / 2.0;\n  }\n  if ( v_new_middle > va->upper - va->page_size / 2.0 ) {\n    v_new_middle = GSL_MAX (va->upper - va->page_size / 2.0,\n\t\t\t    va->page_size / 2.0);\n  }\n\n  va->value = round (v_new_middle - va->page_size / 2.0);\n  // Floating point math might put us off by a tiny bit, so we check\n  // for this and clamp if needed.\n  const gfloat max_slop = 0.4;      \n  if ( va->value < 0.0 ) {\n    // We should only be dealing with slight floating point\n    // inexactness here.\n    if ( va->value < -max_slop ) {\n      g_error (\"Current vertical page position too negative: %lf\\n\",\n\t       va->value);\n    }\n    g_assert (va->value >= -max_slop);\n    va->value = 0.0;\n  }\n  if ( va->value > va->upper - va->page_size ) {\n    g_assert (va->value - (va->upper - va->page_size) <= max_slop);\n    va->value = va->upper - va->page_size;\n  }\n\n  // Update the horizontal adjustment.\n\n  ha->upper = ceil (GSL_MAX (self->max_x * self->zoom, ha->page_size));\n\n  gfloat h_new_middle = h_old_middle * zoom_ratio;\n  if ( h_new_middle < ha->page_size / 2.0 ) {\n    h_new_middle = ha->page_size / 2.0;\n  }\n  if ( h_new_middle > ha->upper - ha->page_size / 2.0 ) {\n    h_new_middle = GSL_MAX (ha->upper - ha->page_size / 2.0,\n\t\t\t    ha->page_size / 2.0);\n  }\n\n  ha->value = round (h_new_middle - ha->page_size / 2.0);\n  if ( ha->value < 0.0 ) {\n    // We should only be dealing with slight floating point\n    // inexactness here.\n    g_assert (ha->value > -max_slop);\n    ha->value = 0.0;\n  }\n  if ( ha->value > ha->upper - ha->page_size ) {\n    gdouble margin = ha->value - (ha->upper - ha->page_size);\n    if ( margin > max_slop ) {\n      g_error (\"Current hosizontal page position too much too large: %lf\",\n\t       margin);\n    }\n    g_assert (ha->value - (ha->upper - ha->page_size) <= max_slop);\n    ha->value = ha->upper - ha->page_size;\n  }\n  \n  // We unblock our own handler for three of the next four\n  // adjustment-related emissions, since all it does it recompute and\n  // rehint the max window dimensions and redraw the drawing area.\n  // Doing this once is enough.  But we do want gtk to have a chance\n  // to run any code it needs to run to redraw the scrollbars and\n  // such.\n  gint block_count\n    = g_signal_handlers_block_by_func (va, on_adjustment_changed, self);\n  g_assert (block_count == 2);\n  block_count\n    = g_signal_handlers_block_by_func (ha, on_adjustment_changed, self);\n  g_assert (block_count == 2);\n  {\n    g_signal_emit_by_name (va, \"changed::\");\n    g_signal_emit_by_name (ha, \"changed::\");\n    // IMPROVEME: Do we need both changed and value-changed emmisions?\n    // Gtk does seem to suggest yes as of this writing, but this seems\n    // like a pretty silly requirement.\n    g_signal_emit_by_name (va, \"value-changed::\");\n  }\n  gint unblock_count\n    = g_signal_handlers_unblock_by_func (ha, on_adjustment_changed, self);\n  g_assert (unblock_count == 2);\n  unblock_count\n    = g_signal_handlers_unblock_by_func (va, on_adjustment_changed, self);\n  g_assert (unblock_count == 2);\n  g_signal_emit_by_name (ha, \"value-changed::\");\n}\n\nstatic gboolean\non_key_press_event (GtkWidget *win, GdkEventKey *event, gpointer user_data)\n{\n  ViewerWindow *self = user_data;\n\n  gchar key_op = find_key_op (event->state, event->keyval);\n\n  switch ( key_op ) {\n  case 'I':\n  case 'i':\n    print_point_info_for_cursor (self);\n    break;\n  case '+': \n    {\n      // FIIXME: all this code should be replaced with a step_zoom_in call.\n\n      // At most one screen pixel per image pixel.\n      const gfloat max_zoom = 1.0; \n\n      // Remember old values so we can adjust the adjustments\n      // correctly.\n      GtkAdjustment *va = self->vadj, *ha = self->hadj;\n      gdouble v_old_upper = va->upper, h_old_upper = ha->upper;\n      gdouble v_old_middle = va->value + va->page_size / 2.0;\n      gdouble h_old_middle = ha->value + ha->page_size / 2.0;\n      gfloat old_zoom = self->zoom;\n\n      // Zoom, but only up to the maximum.  IMPROVEME: it would be\n      // best to only zoom by factors of 2.0, even when the window is\n      // resized.  The pyramids are of these powers naturally, so no\n      // additional OpenGL scaling needs to be done.  The additional\n      // scaling probably introduces aliasing, which is kind of a\n      // shame since the whole point of building the pyramids is to\n      // produce good looking results at different resolutions.  For\n      // now, we just clamp to powers ot two here in the zoom in/out\n      // code, not in the code that handles window resizing.  This is\n      // somewhat reasonable, since doing this gives the user our best\n      // available rendering when they try to look at something in\n      // detail, which is when it counts.  It isn't really the ideal\n      // arrangement though.  Another potential option is to use an\n      // antialiasing OpenGL convolution filter.  But I'm not sure\n      // exactly how to do that, or even what the tradeoffs are\n      // exactly.\n      self->zoom *= 2.0;\n      // Clamp to a power of 2.0.\n      gdouble power = round (log2 (self->zoom));\n      self->zoom = pow (2.0, power);\n      if ( self->zoom > max_zoom ) {\n\tself->zoom = max_zoom;\n      }\n\n      // Compute the new upper value and current value of the\n      // adjustments, given the new virtual window size.\n      gfloat zoom_ratio = self->zoom / old_zoom;\n\n      // Update the vertical adjustment.\n\n      va->upper = ceil (va->upper * zoom_ratio);\n      \n      gfloat v_new_middle = v_old_middle * va->upper / v_old_upper;\n\n      // When we zoom, we may end up with a different part of the\n      // image in the center, since we try to avoid showing areas not\n      // in the big picture coordinate system, and configure events\n      // may have changed the window size.\n      if ( v_new_middle < va->page_size / 2.0 ) {\n\tv_new_middle = va->page_size / 2.0;\n      }\n      if ( v_new_middle > va->upper - va->page_size / 2.0 ) {\n\tv_new_middle = GSL_MAX (va->upper - va->page_size / 2.0,\n\t\t\t\tva->page_size / 2.0);\n      }\n      va->value = round (v_new_middle - va->page_size / 2.0);\n      // Floating point math might put us off by a tiny bit, so we\n      // check for this and clamp if needed.\n      const gfloat max_slop = 0.4;      \n      if ( va->value < 0.0) {\n\t// We should only be dealing with slight floating point\n\t// inexactness here.\n\tg_assert (va->value >= -0.4);\n\tva->value = 0.0;\n      }\n      if ( va->value > va->upper - va->page_size ) {\n\tg_assert (va->value - (va->upper - va->page_size) <= max_slop);\n\tva->value = va->upper - va->page_size;\n      }\n\n      // Update the horizontal adjustment.\n\n      ha->upper = ceil (ha->upper * zoom_ratio);\n\n      gfloat h_new_middle = h_old_middle * ha->upper / h_old_upper;\n\n      // When we zoom, we may end up with a different part of the\n      // image in the center, since we try to avoid showing areas not\n      // in the big picture coordinate system, and configure events\n      // may have changed the window size.\n      if ( h_new_middle < ha->page_size / 2.0 ) {\n\th_new_middle = ha->page_size / 2.0;\n      }\n      if ( h_new_middle > ha->upper - ha->page_size / 2.0 ) {\n\th_new_middle = GSL_MAX (ha->upper - ha->page_size / 2.0,\n\t\t\t\tha->page_size / 2.0);\n      }\n      ha->value = round (h_new_middle - ha->page_size / 2.0);\n      if ( ha->value < 0.0 ) {\n\t// We should only be dealing with slight floating point\n\t// inexactness here.\n\tg_assert (ha->value >= -max_slop);\n\tha->value = 0.0;\n      }\n      if ( ha->value > ha->upper - ha->page_size ) {\n\tgdouble slop = ha->value - (ha->upper - ha->page_size);\n\t// FIIXME: I swear I got this condition to trip once at this\n\t// slop threshold.  So it might be necessary to change this\n\t// into a warning, or loosen the tolerance a bit.\n\tif ( slop > max_slop ) {\n\t  g_error (\"too much slop (%lf) in floating point calculation in \"\n\t\t   \"file \" __FILE__ \" function %s, line %d\", slop, __func__,\n\t\t   __LINE__);\n\t}\n\tha->value = round (ha->upper - ha->page_size);\n      }\n\n      // We unblock our own handler for three of the next four\n      // adjustment-related emissions, since all it does it recompute\n      // and rehint the max window dimensions and redraw the drawing\n      // area.  Doing this once is enough.  But we do want gtk to have\n      // a chance to run any code it needs to run to redraw the\n      // scrollbars and such.\n      gint block_count\n\t= g_signal_handlers_block_by_func (va, on_adjustment_changed, self);\n      g_assert (block_count == 2);\n      block_count\n\t= g_signal_handlers_block_by_func (ha, on_adjustment_changed, self);\n      g_assert (block_count == 2);\n      {\n\tg_signal_emit_by_name (va, \"changed::\");\n\tg_signal_emit_by_name (ha, \"changed::\");\n\t// IMPROVEME: Do we need both changed and value-changed\n\t// emmisions?  Gtk docs seem to suggest we do as of this\n\t// writing, but this seems like a pretty silly requirement.\n\tg_signal_emit_by_name (va, \"value-changed::\");\n      }\n      gint unblock_count\n\t= g_signal_handlers_unblock_by_func (ha, on_adjustment_changed, self);\n      g_assert (unblock_count == 2);\n      unblock_count\n\t= g_signal_handlers_unblock_by_func (va, on_adjustment_changed, self);\n      g_assert (unblock_count == 2);\n      g_signal_emit_by_name (ha, \"value-changed::\");\n      break;\n    }\n  case '-':\n    {\n      // FIIXME: all this code should be replaced with a step_zoom_out call.\n\n      // Remember old values so we can adjust the adjustments\n      // correctly.\n      GtkAdjustment *va = self->vadj, *ha = self->hadj;\n      gdouble v_old_middle = va->value + va->page_size / 2.0;\n      gdouble h_old_middle = ha->value + ha->page_size / 2.0;\n      gfloat old_zoom = self->zoom;\n\n      // The maximum zoom out we will allow is one that displays the\n      // entire big picture coordinate systme in the current window.\n      const gfloat min_zoom = GSL_MIN (ha->page_size / self->max_x,\n\t\t\t\t       va->page_size / self->max_y);\n\n      // Zoom, but only out to the maximum.\n      self->zoom /= 2.0;\n      if ( self->zoom < min_zoom ) {\n\tself->zoom = min_zoom;\n      }\n\n      // Compute the new upper value and current value of the\n      // adjustments, given the new virtual window size.\n      gfloat zoom_ratio = self->zoom / old_zoom;\n\n      // Update the vertical adjustment.\n\n      va->upper = ceil (GSL_MAX (self->max_y * self->zoom, va->page_size));\n\n      gfloat v_new_middle = v_old_middle * zoom_ratio;\n      // When we zoom out, we may end up with a different part of the\n      // image in the center, since we try to avoid showing areas not\n      // in the big picture coordinate system.\n      if ( v_new_middle < va->page_size / 2.0 ) {\n\tv_new_middle = va->page_size / 2.0;\n      }\n      if ( v_new_middle > va->upper - va->page_size / 2.0 ) {\n\tv_new_middle = GSL_MAX (va->upper - va->page_size / 2.0,\n\t\t\t\tva->page_size / 2.0);\n      }\n\n      va->value = round (v_new_middle - va->page_size / 2.0);\n      // Floating point math might put us off by a tiny bit, so we\n      // check for this and clamp if needed.\n      const gfloat max_slop = 0.4;      \n      if ( va->value < 0.0 ) {\n\t// We should only be dealing with slight floating point\n\t// inexactness here.\n\tif ( va->value < -max_slop ) {\n\t  g_error (\"Current vertical page position too negative: %lf\\n\",\n\t\t   va->value);\n\t}\n\tg_assert (va->value >= -max_slop);\n\tva->value = 0.0;\n      }\n      if ( va->value > va->upper - va->page_size ) {\n\tg_assert (va->value - (va->upper - va->page_size) <= max_slop);\n\tva->value = va->upper - va->page_size;\n      }\n\n      // Update the horizontal adjustment.\n\n      ha->upper = ceil (GSL_MAX (self->max_x * self->zoom, ha->page_size));\n\n      gfloat h_new_middle = h_old_middle * zoom_ratio;\n      if ( h_new_middle < ha->page_size / 2.0 ) {\n\th_new_middle = ha->page_size / 2.0;\n      }\n      if ( h_new_middle > ha->upper - ha->page_size / 2.0 ) {\n\th_new_middle = GSL_MAX (ha->upper - ha->page_size / 2.0,\n\t\t\t\tha->page_size / 2.0);\n      }\n\n      ha->value = round (h_new_middle - ha->page_size / 2.0);\n      if ( ha->value < 0.0 ) {\n\t// We should only be dealing with slight floating point\n\t// inexactness here.\n\tg_assert (ha->value > -max_slop);\n\tha->value = 0.0;\n      }\n      if ( ha->value > ha->upper - ha->page_size ) {\n\tgdouble margin = ha->value - (ha->upper - ha->page_size);\n\tif ( margin > max_slop ) {\n\t  g_error (\"Current hosizontal page position too much too large: %lf\",\n\t\t   margin);\n\t}\n\tg_assert (ha->value - (ha->upper - ha->page_size) <= max_slop);\n\tha->value = ha->upper - ha->page_size;\n      }\n\n      // We unblock our own handler for three of the next four\n      // adjustment-related emissions, since all it does it recompute\n      // and rehint the max window dimensions and redraw the drawing\n      // area.  Doing this once is enough.  But we do want gtk to have\n      // a chance to run any code it needs to run to redraw the\n      // scrollbars and such.\n      gint block_count\n\t= g_signal_handlers_block_by_func (va, on_adjustment_changed, self);\n      g_assert (block_count == 2);\n      block_count\n\t= g_signal_handlers_block_by_func (ha, on_adjustment_changed, self);\n      g_assert (block_count == 2);\n     {\n\tg_signal_emit_by_name (va, \"changed::\");\n\tg_signal_emit_by_name (ha, \"changed::\");\n\t// IMPROVEME: Do we need both changed and value-changed\n\t// emmisions?  Gtk does seem to suggest yes as of this\n\t// writing, but this seems like a pretty silly requirement.\n\tg_signal_emit_by_name (va, \"value-changed::\");\n      }\n      gint unblock_count\n\t= g_signal_handlers_unblock_by_func (ha, on_adjustment_changed, self);\n      g_assert (unblock_count == 2);\n      unblock_count\n\t= g_signal_handlers_unblock_by_func (va, on_adjustment_changed, self);\n      g_assert (unblock_count == 2);\n      g_signal_emit_by_name (ha, \"value-changed::\");\n      break;\n    }\n  case 'N':\n  case 'n':\n    {\n      // Find the current image.\n      gboolean found = FALSE;\n      guint ii;\n      for ( ii = 0 ; ii < self->images->len ; ii++ ) {\n\tViewerImage *ci = g_ptr_array_index ( self->images, ii);\n\tif ( ci == self->image ) {\n\t  found = TRUE;\n\t  break;\n\t}\n      }\n      g_assert (found);\n      if ( self->images->len > 1 ) {\n\tii = (ii + 1) % self->images->len;\n      }\n      else {\n\tg_print (\"Only 1 image is loaded (i.e. there is no next image).\");\n      }\n      self->image = g_ptr_array_index (self->images, ii);\n      redraw_drawing_area (self, self->da);\n      break;\n    }\n  case 'P':\n  case 'p':\n    {\n      // Find the current image.\n      gboolean found = FALSE;\n      guint ii;\n      for ( ii = 0 ; ii < self->images->len ; ii++ ) {\n\tif ( g_ptr_array_index (self->images, ii) == self->image ) {\n\t  found = TRUE;\n\t  break;\n\t}\n      }\n      g_assert (found);\n      if ( self->images->len > 1 ) {\n\tif ( ii == 0 ) {\n\t  ii = self->images->len - 1;\n\t}\n\telse {\n\t  ii--;\n\t}\n      }\n      else {\n\tg_print (\"Only 1 image is loaded (i.e. there is no previous image).\");\n      }\n      self->image = g_ptr_array_index (self->images, ii);\n      redraw_drawing_area (self, self->da);\n      break;\n    }\n  case 'a':\n    {\n      // Analyze a tile around the current cursor location.\n      if ( self->analysis_program == NULL ) {\n\tg_print (\"\\n\");\n\tg_print (\"Analysis requested, but no analysis program was specified\\n\"\n\t\t \"with the --analysis-program command line option.\\n\");\n      }\n      else if ( self->cursor_x == -1 ) {\n\tg_assert (self->cursor_y == -1);\n\tg_print (\"\\n\");\n\tg_print (\"Analysis requested, but the cursor has not been placed.\\n\"\n\t\t \"(left click to place the cursor)\\n\");\n      }\n      else {\n\trun_analysis (self);\n      }\n    }\n    break;\n  case 'e':\n    {\n      g_signal_emit_by_name (self->w, \"delete_event::\");\n    }\n  case '~':\n    {\n      // An key not obviously convertible to a single letter, or an\n      // key the simple conversion routine hasn't been taught about.\n      switch ( event->keyval ) {\n      case GDK_Up:\n\tself->cursor_y--;\n\tif ( self->cursor_y < 0 ) {\n\t  self->cursor_y = 0;\n\t}\n\tbreak;\n      case GDK_Down:\n\tself->cursor_y++;\n\t// The cursor can be on max_y (instead of max_y - 1) because\n\t// we have defined max_y as the largest addressable index.\n\tif ( self->cursor_y > self->max_y ) {\n\t  self->cursor_y = self->max_y;\n\t}\n\tbreak;\n      case GDK_Left:\n\tself->cursor_x--;\n\tif ( self->cursor_x < 0 ) {\n\t  self->cursor_x = 0;\n\t}\n\tbreak;\n      case GDK_Right:\n\tself->cursor_x++;\n\t// The cursor can be on max_x (instead of max_x - 1) because\n\t// we have defined max_y as the largest addressable index.\n\tif ( self->cursor_x > self->max_x ) {\n\t  self->cursor_x = self->max_x;\n\t}\n\tbreak;\n      default:\n\tbreak;\n      }\n      redraw_drawing_area (self, self->da);\n      break;\n    }\n  default:\n    break;\n  }\n\n  return FALSE;\n}\n\nstatic gboolean\non_scroll_event (GtkDrawingArea *da, GdkEventScroll *event, ViewerWindow *self)\n{\n  if ( event->direction == GDK_SCROLL_UP ) {\n    step_zoom_in (self);\n  }\n  else if ( event->direction == GDK_SCROLL_DOWN ) {\n    step_zoom_out (self);\n  }\n\n  return FALSE;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n//\n// Click and Drag Scrolling\n//\n// Together these handlers implement click-and-drag-to-scroll.\n//\n\nstatic gboolean\nalso_on_button_press_event (GtkDrawingArea *da, GdkEventButton *event,\n\t\t\t    ViewerWindow *self)\n{\n  if ( event->type == GDK_BUTTON_PRESS && event->button == 2 ) {\n    // FIXME: initialize these to magic and reset between to magic.\n    self->drag_start_x = event->x;\n    self->drag_start_y = event->y;\n    self->drag_start_hadj_value = gtk_adjustment_get_value (self->hadj);\n    self->drag_start_vadj_value = gtk_adjustment_get_value (self->vadj);\n  }\n\n  return FALSE;\n}\n\nstatic void\ndrag_scroll (ViewerWindow *self, gdouble x, gdouble y)\n{\n  gdouble delta_x = x - self->drag_start_x, delta_y = y - self->drag_start_y;\n\n  // Determine the new horizontal adjustment value.\n  gdouble new_hval = self->drag_start_hadj_value - delta_x;\n  gdouble drag_hmax = self->hadj->upper - self->hadj->page_size;\n  if ( new_hval > drag_hmax ) {\n    new_hval = drag_hmax;\n  }\n  gtk_adjustment_set_value (self->hadj, new_hval);\n\n  // Determine the new vertical adjustment value.\n  gdouble new_vval = self->drag_start_vadj_value - delta_y;\n  gdouble drag_vmax = self->vadj->upper - self->vadj->page_size;\n  if ( new_vval > drag_vmax ) {\n    new_vval = drag_vmax;\n  }\n  gtk_adjustment_set_value (self->vadj, new_vval);\n\n  // We only want to end up redrawing once, so we block our handler\n  // for one of the two adjustment changed emissions.  But we still\n  // emit both so internal Gtk handlers can update the scroll bars or\n  // whatever they do.\n  gint block_count\n    = g_signal_handlers_block_by_func (self->hadj, on_adjustment_changed,\n\t\t\t\t       self);\n  g_assert (block_count == 2);\n  {\n    gtk_adjustment_value_changed (self->hadj);\n  }\n  gint unblock_count\n    = g_signal_handlers_unblock_by_func (self->hadj, on_adjustment_changed,\n\t\t\t\t\t self);\n  g_assert (unblock_count == 2);\n  gtk_adjustment_value_changed (self->vadj);\n}\n\nstatic gboolean\non_motion_notify_event (GtkDrawingArea *da, GdkEventMotion *event,\n\t\t\tViewerWindow *self)\n{\n  if ( event->state & GDK_BUTTON2_MASK ) {\n    if ( self->drag_start_x != -1 ) {\n      drag_scroll (self, event->x, event->y);\n    }\n    else {\n      g_assert (self->drag_start_y == -1);\n    }\n\n    // We don't really care what this call returns, since we have\n    // already redrawn according to the motion_notify_event we just\n    // received, but we make it in order to let GDK know we're ready\n    // for the next motion event (seek GdkEventMask documentation, in\n    // particular the discussion of GDK_POINTER_MOTION_HINT_MASK).\n    gint junk_x, junk_y;\n    GdkModifierType mask;\n    gdk_window_get_pointer ((GTK_WIDGET (da))->window, &junk_x, &junk_y,\n\t\t\t    &mask);\n  }\n\n  return FALSE;\n}\n\nstatic gboolean\non_button_release_event (GtkDrawingArea *da, GdkEventButton *event,\n\t\t\t ViewerWindow *self)\n{\n  if ( event->type == GDK_BUTTON_RELEASE && event->button == 2 ) {\n    if ( self->drag_start_x != -1 ) {\n      drag_scroll (self, event->x, event->y);\n    }\n    self->drag_start_x = -1;\n    self->drag_start_y = -1;\n  }\n\n  return FALSE;\n}\n\t\t\t \n\n///////////////////////////////////////////////////////////////////////////////\n\n// Initialize the gtk and gtkglext libraries, and create the\n// GdkGLConfig we will be usein.\nstatic void\ninitialize_libraries (void)\n{\n\n  // FIIXME: verify that passing NULL is really ok.  It sure seems to work.\n  gtk_init (NULL, NULL);\n  gtk_gl_init (NULL, NULL);\n\n  // Check OpenGL version.\n  gint major, minor;\n  gdk_gl_query_version (&major, &minor);\n  g_assert (major >= 1 && minor >= 2);\n\n  glconfig = gdk_gl_config_new_by_mode (  GDK_GL_MODE_RGB \n\t\t\t\t\t  | GDK_GL_MODE_DEPTH\n\t\t\t\t\t  | GDK_GL_MODE_DOUBLE); \n  g_assert (glconfig != NULL);\n}\n\nViewerWindow *\nviewer_window_new (ViewerImage *image, GPtrArray *images,\n\t\t   size_t max_x, size_t max_y,\n\t\t   size_t start_x, size_t start_y, size_t w, size_t h,\n\t\t   GString *analysis_program, gboolean async_analysis,\n\t\t   gint analysis_tile_size)\t\t   \n{\n  if ( ! initialized ) {\n    initialize_libraries ();\n  }\n\n  ViewerWindow *self = g_new0 (ViewerWindow, 1);\n\n  self->image = viewer_image_ref (image);\n\n  // Note this is a pointer to a list owned by main(), so we must not\n  // change or free it.\n  self->images = images;\n\n  self->max_x = max_x;\n  self->max_y = max_y;\n\n  self->start_x = start_x;\n  self->start_y = start_y;\n\n  // The cursor begins life unplaced.\n  self->cursor_x = -1;\n  self->cursor_y = -1;\n\n  // Store the analysis-related arguments.\n  if ( analysis_program == NULL ) {\n    self->analysis_program = NULL;\n  }\n  else {\n    self->analysis_program = g_string_new (analysis_program->str);\n    self->async_analysis = async_analysis;\n    self->analysis_tile_size = analysis_tile_size;\n  }\n\n  // Haven't gotten any data to draw before, so there isn't going to\n  // be anything to free the first time we draw.\n  self->dp_to_free = NULL;\n\n  // Set up the Gtk window.\n  GtkWidget *window = gtk_window_new (GTK_WINDOW_TOPLEVEL);\n  // Top level GtkObject instances have only a floating reference\n  // which gets claimed by the GTK library itself, so we have to ref\n  // the window.\n  gtk_widget_ref (window);\n  GString *title = g_string_new (image->base_name->str);\n  g_string_prepend (title, \"ssv: \");\n  gtk_window_set_title (GTK_WINDOW (window), title->str);\n  gtk_container_set_reallocate_redraws (GTK_CONTAINER (window), TRUE);\n  \n  self->w = window;\n\n  // Set up table to hold the drawing area and scrollbars.\n\n  GtkTable *table = GTK_TABLE (gtk_table_new (2, 2, FALSE));\n  GtkWidget *hbar = gtk_hscrollbar_new (NULL);\n  // IMPROVEME: we may want to use UPDATE_DELAYED until we find that\n  // the pyramids are done.\n  gtk_range_set_update_policy (GTK_RANGE (hbar), GTK_UPDATE_CONTINUOUS);\n  GtkAdjustment *hadj = gtk_range_get_adjustment (GTK_RANGE (hbar));\n  hadj->lower = 0;\n  hadj->value = 0;\n  self->hadj = hadj;\n\n  GtkWidget *vbar = gtk_vscrollbar_new (NULL);\n  // IMPROVEME: we may want to use UPDATE_DELAYED until we find that\n  // the pyramids are done.\n  gtk_range_set_update_policy (GTK_RANGE (vbar), GTK_UPDATE_CONTINUOUS);\n  GtkAdjustment *vadj = gtk_range_get_adjustment (GTK_RANGE (vbar));\n  vadj->lower = 0;\n  vadj->value = 0;\n  self->vadj = vadj;\n\n  gtk_table_attach (table, vbar, 1, 2, 0, 1, GTK_FILL, GTK_FILL | GTK_EXPAND,\n\t\t    0, 0);\n  gtk_table_attach (table, hbar, 0, 1, 1, 2, GTK_FILL | GTK_EXPAND, GTK_FILL,\n\t\t    0, 0);\n\n  // When the GtkAdjustment instances associated with the scrollbars\n  // change, we need to redraw things.\n  g_signal_connect (vadj, \"changed::\", G_CALLBACK (on_adjustment_changed),\n\t\t    self);\n  g_signal_connect (vadj, \"value-changed::\",\n\t\t    G_CALLBACK (on_adjustment_changed), self);\n  g_signal_connect (hadj, \"changed::\", G_CALLBACK (on_adjustment_changed),\n  \t\t    self);\n  g_signal_connect (hadj, \"value-changed::\",\n  \t\t    G_CALLBACK (on_adjustment_changed), self);\n\n  // Set up the drawing area.\n  GtkWidget *da = gtk_drawing_area_new ();\n  gboolean return_code = gtk_widget_set_gl_capability (da, glconfig, NULL,\n\t\t\t\t\t\t       TRUE, GDK_GL_RGBA_TYPE);\n  g_assert (return_code);\n  g_signal_connect_after (G_OBJECT (da), \"realize\", G_CALLBACK (after_realize),\n  \t\t\t  self);\n  g_signal_connect (G_OBJECT (da), \"configure_event\",\n  \t\t    G_CALLBACK (on_drawing_area_configure_event), self);\n  g_signal_connect (G_OBJECT (da), \"expose_event\",\n  \t\t    G_CALLBACK (on_expose_event), self);\n  gtk_widget_add_events (da, GDK_BUTTON_PRESS_MASK);\n  g_signal_connect (G_OBJECT (da), \"button_press_event\",\n\t\t      G_CALLBACK (on_button_press_event), self);\n  self->da = da;\n\n  // Path the drawing area into the table.\n  gtk_table_attach_defaults (table, self->da, 0, 1, 0, 1);\n\n  // Pack the table into the window.\n  gtk_container_add (GTK_CONTAINER (self->w), GTK_WIDGET (table));\n\n  // True iff the entire image should fit in a drawing area of the\n  // default dimensions without any zooming.\n  size_t def_w = VIEWER_WINDOW_DRAWING_AREA_DEFAULT_WIDTH;\n  size_t def_h = VIEWER_WINDOW_DRAWING_AREA_DEFAULT_HEIGHT;\n  gboolean image_fits = (w <= def_w && h <= def_h);\n  if ( image_fits ) {\n    self->zoom = 1.0;\n    // The entire image should ift in the drawing area, so we can just\n    // use a smaller drawing area.  IMPROVEME: but maybe using small\n    // windows sometimes is just confusing and irritating to the user,\n    // and causes window managers to place things inconsistently?\n    gtk_widget_set_size_request (self->da, w, h);\n  }\n  else {\n    // We try to make the drawing area have the standard default size.\n    // The window manager may thwart us, of course.  IMPROVEME: here\n    // is another point where work might be needed to implement\n    // power-of-two zoom level locking (see IMPROVEME elsewhere).\n    gtk_widget_set_size_request (self->da, def_w, def_h);\n    if ( (double) w / def_w > (double) h / def_h ) {\n      self->zoom = (double) def_w / w;\n    }\n    else {\n      self->zoom = (double) def_h / h;\n    }\n  }\n  vadj->page_size = self->da->allocation.height;\n  vadj->upper = GSL_MAX (self->max_y * self->zoom, vadj->page_size);\n  hadj->page_size = self->da->allocation.width;\n  hadj->upper = GSL_MAX (self->max_x * self->zoom, hadj->page_size);\n\n  // FIIXME: Presumably don't need to emit a changed signal or\n  // anything on the adjustments here since everything is yet to be\n  // drawn (confirm)?\n\n  g_signal_connect (G_OBJECT (self->w), \"key_press_event\",\n\t\t    G_CALLBACK (on_key_press_event), self);\n\n  g_signal_connect (G_OBJECT (self->da), \"scroll_event\",\n\t\t    G_CALLBACK (on_scroll_event), self);\n\n  // Connect to the click-and-drag scrolling handlers.\n  g_signal_connect (G_OBJECT (self->da), \"button_press_event\",\n  \t\t    G_CALLBACK (also_on_button_press_event), self);\n  g_signal_connect (G_OBJECT (self->da), \"motion_notify_event\",\n\t\t    G_CALLBACK (on_motion_notify_event), self);\n  g_signal_connect (G_OBJECT (self->da), \"button_release_event\",\n\t\t    G_CALLBACK (on_button_release_event), self);\n\n  GdkEventMask da_events;\n  g_object_get (G_OBJECT (self->da), \"events\", &da_events, NULL);\n  if ( ! (da_events\n\t  & (GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON2_MOTION_MASK)) ) {\n    da_events |= (GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON2_MOTION_MASK);\n    g_object_set (G_OBJECT (self->da), \"events\", da_events, NULL);\n  }\n\n  // Set the maximum dimensions of the window commensurate with the\n  // available data.\n  reset_window_max_dimensions (self);\n\n  // Here lies an attempt to figure out why sometimes the window comes\n  // out only the height of the layer for a roughly square layer.  Who\n  // knows.  Put it down to window manager evilness, though I think it\n  // might be a concurrency issue of some sort at the Gtk level.\n  /*\n  GtkResizeMode rm = gtk_container_get_resize_mode (GTK_CONTAINER (table));\n  switch ( rm ) {\n  case GTK_RESIZE_PARENT:\n    g_print (\"table in PARENT mode\\n\");\n    break;\n  case GTK_RESIZE_QUEUE:\n    g_print (\"table in QUEUE mode\\n\");\n    break;\n  case GTK_RESIZE_IMMEDIATE:\n    g_print (\"table in IMMEDIATE mode\\n\");\n    break;\n  default:\n    g_assert_not_reached ();\n    break;\n  }\n  */\t\t\t\t\t    \n\n  // Display the new window and everything it contains (triggering the\n  // signals that do the OpenGL drawing).\n  gtk_widget_show_all (self->w);\n\n  gtk_widget_set_size_request (self->da, -1, -1);\n\n  self->reference_count = 1;\n\n  return self;\n}\n\nvoid\nviewer_window_unref (ViewerWindow *self)\n{\n  self->reference_count--;\n\n  if ( self->reference_count == 0 ) {\n    g_assert (self->w != NULL);\n    gtk_widget_unref (self->w);\n    viewer_image_unref (self->image);\n\n    g_free (self);\n  }\n}\n", "meta": {"hexsha": "fe4490c23159b9cb222f603fb8e3a0c51be06ff2", "size": 70573, "ext": "c", "lang": "C", "max_stars_repo_path": "src/ssv/viewer_window.c", "max_stars_repo_name": "glshort/MapReady", "max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z", "max_issues_repo_path": "src/ssv/viewer_window.c", "max_issues_repo_name": "glshort/MapReady", "max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ssv/viewer_window.c", "max_forks_repo_name": "glshort/MapReady", "max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z", "avg_line_length": 35.6970156803, "max_line_length": 79, "alphanum_fraction": 0.6645742706, "num_tokens": 19667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.026759284058610288, "lm_q1q2_score": 0.012232651259207427}}
{"text": "/* matrix/gsl_matrix_complex_double.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_MATRIX_COMPLEX_DOUBLE_H__\n#define __GSL_MATRIX_COMPLEX_DOUBLE_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_complex.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_vector_complex_double.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size1;\n  size_t size2;\n  size_t tda;\n  double * data;\n  gsl_block_complex * block;\n  int owner;\n} gsl_matrix_complex ;\n\ntypedef struct\n{\n  gsl_matrix_complex matrix;\n} _gsl_matrix_complex_view;\n\ntypedef _gsl_matrix_complex_view gsl_matrix_complex_view;\n\ntypedef struct\n{\n  gsl_matrix_complex matrix;\n} _gsl_matrix_complex_const_view;\n\ntypedef const _gsl_matrix_complex_const_view gsl_matrix_complex_const_view;\n\n\n/* Allocation */\n\nGSL_EXPORT\ngsl_matrix_complex *\ngsl_matrix_complex_alloc (const size_t n1, const size_t n2);\n\nGSL_EXPORT\ngsl_matrix_complex *\ngsl_matrix_complex_calloc (const size_t n1, const size_t n2);\n\nGSL_EXPORT\ngsl_matrix_complex *\ngsl_matrix_complex_alloc_from_block (gsl_block_complex * b,\n                                           const size_t offset,\n                                           const size_t n1, const size_t n2, const size_t d2);\n\nGSL_EXPORT\ngsl_matrix_complex *\ngsl_matrix_complex_alloc_from_matrix (gsl_matrix_complex * b,\n                                            const size_t k1, const size_t k2,\n                                            const size_t n1, const size_t n2);\n\nGSL_EXPORT\ngsl_vector_complex *\ngsl_vector_complex_alloc_row_from_matrix (gsl_matrix_complex * m,\n                                                const size_t i);\n\nGSL_EXPORT\ngsl_vector_complex *\ngsl_vector_complex_alloc_col_from_matrix (gsl_matrix_complex * m,\n                                                const size_t j);\n\nGSL_EXPORT void gsl_matrix_complex_free (gsl_matrix_complex * m);\n\n/* Views */\n\nGSL_EXPORT\n_gsl_matrix_complex_view\ngsl_matrix_complex_submatrix (gsl_matrix_complex * m,\n                            const size_t i, const size_t j,\n                            const size_t n1, const size_t n2);\n\nGSL_EXPORT\n_gsl_vector_complex_view\ngsl_matrix_complex_row (gsl_matrix_complex * m, const size_t i);\n\nGSL_EXPORT\n_gsl_vector_complex_view\ngsl_matrix_complex_column (gsl_matrix_complex * m, const size_t j);\n\nGSL_EXPORT\n_gsl_vector_complex_view\ngsl_matrix_complex_diagonal (gsl_matrix_complex * m);\n\nGSL_EXPORT\n_gsl_vector_complex_view\ngsl_matrix_complex_subdiagonal (gsl_matrix_complex * m, const size_t k);\n\nGSL_EXPORT\n_gsl_vector_complex_view\ngsl_matrix_complex_superdiagonal (gsl_matrix_complex * m, const size_t k);\n\nGSL_EXPORT\n_gsl_matrix_complex_view\ngsl_matrix_complex_view_array (double * base,\n                             const size_t n1,\n                             const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_complex_view\ngsl_matrix_complex_view_array_with_tda (double * base,\n                                      const size_t n1,\n                                      const size_t n2,\n                                      const size_t tda);\n\nGSL_EXPORT\n_gsl_matrix_complex_view\ngsl_matrix_complex_view_vector (gsl_vector_complex * v,\n                              const size_t n1,\n                              const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_complex_view\ngsl_matrix_complex_view_vector_with_tda (gsl_vector_complex * v,\n                                       const size_t n1,\n                                       const size_t n2,\n                                       const size_t tda);\n\n\nGSL_EXPORT\n_gsl_matrix_complex_const_view\ngsl_matrix_complex_const_submatrix (const gsl_matrix_complex * m,\n                                  const size_t i, const size_t j,\n                                  const size_t n1, const size_t n2);\n\nGSL_EXPORT\n_gsl_vector_complex_const_view\ngsl_matrix_complex_const_row (const gsl_matrix_complex * m,\n                            const size_t i);\n\nGSL_EXPORT\n_gsl_vector_complex_const_view\ngsl_matrix_complex_const_column (const gsl_matrix_complex * m,\n                               const size_t j);\n\nGSL_EXPORT\n_gsl_vector_complex_const_view\ngsl_matrix_complex_const_diagonal (const gsl_matrix_complex * m);\n\nGSL_EXPORT\n_gsl_vector_complex_const_view\ngsl_matrix_complex_const_subdiagonal (const gsl_matrix_complex * m,\n                                    const size_t k);\n\nGSL_EXPORT\n_gsl_vector_complex_const_view\ngsl_matrix_complex_const_superdiagonal (const gsl_matrix_complex * m,\n                                      const size_t k);\n\nGSL_EXPORT\n_gsl_matrix_complex_const_view\ngsl_matrix_complex_const_view_array (const double * base,\n                                   const size_t n1,\n                                   const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_complex_const_view\ngsl_matrix_complex_const_view_array_with_tda (const double * base,\n                                            const size_t n1,\n                                            const size_t n2,\n                                            const size_t tda);\n\nGSL_EXPORT\n_gsl_matrix_complex_const_view\ngsl_matrix_complex_const_view_vector (const gsl_vector_complex * v,\n                                    const size_t n1,\n                                    const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_complex_const_view\ngsl_matrix_complex_const_view_vector_with_tda (const gsl_vector_complex * v,\n                                             const size_t n1,\n                                             const size_t n2,\n                                             const size_t tda);\n\n/* Operations */\n\nGSL_EXPORT gsl_complex gsl_matrix_complex_get(const gsl_matrix_complex * m, const size_t i, const size_t j);\nGSL_EXPORT void gsl_matrix_complex_set(gsl_matrix_complex * m, const size_t i, const size_t j, const gsl_complex x);\n\nGSL_EXPORT gsl_complex * gsl_matrix_complex_ptr(gsl_matrix_complex * m, const size_t i, const size_t j);\nGSL_EXPORT const gsl_complex * gsl_matrix_complex_const_ptr(const gsl_matrix_complex * m, const size_t i, const size_t j);\n\nGSL_EXPORT void gsl_matrix_complex_set_zero (gsl_matrix_complex * m);\nGSL_EXPORT void gsl_matrix_complex_set_identity (gsl_matrix_complex * m);\nGSL_EXPORT void gsl_matrix_complex_set_all (gsl_matrix_complex * m, gsl_complex x);\n\nGSL_EXPORT int gsl_matrix_complex_fread (FILE * stream, gsl_matrix_complex * m) ;\nGSL_EXPORT int gsl_matrix_complex_fwrite (FILE * stream, const gsl_matrix_complex * m) ;\nGSL_EXPORT int gsl_matrix_complex_fscanf (FILE * stream, gsl_matrix_complex * m);\nGSL_EXPORT int gsl_matrix_complex_fprintf (FILE * stream, const gsl_matrix_complex * m, const char * format);\n\nGSL_EXPORT int gsl_matrix_complex_memcpy(gsl_matrix_complex * dest, const gsl_matrix_complex * src);\nGSL_EXPORT int gsl_matrix_complex_swap(gsl_matrix_complex * m1, gsl_matrix_complex * m2);\n\nGSL_EXPORT int gsl_matrix_complex_swap_rows(gsl_matrix_complex * m, const size_t i, const size_t j);\nGSL_EXPORT int gsl_matrix_complex_swap_columns(gsl_matrix_complex * m, const size_t i, const size_t j);\nGSL_EXPORT int gsl_matrix_complex_swap_rowcol(gsl_matrix_complex * m, const size_t i, const size_t j);\n\nGSL_EXPORT int gsl_matrix_complex_transpose (gsl_matrix_complex * m);\nGSL_EXPORT int gsl_matrix_complex_transpose_memcpy (gsl_matrix_complex * dest, const gsl_matrix_complex * src);\n\nGSL_EXPORT int gsl_matrix_complex_isnull (const gsl_matrix_complex * m);\n\nGSL_EXPORT int gsl_matrix_complex_add (gsl_matrix_complex * a, const gsl_matrix_complex * b);\nGSL_EXPORT int gsl_matrix_complex_sub (gsl_matrix_complex * a, const gsl_matrix_complex * b);\nGSL_EXPORT int gsl_matrix_complex_mul_elements (gsl_matrix_complex * a, const gsl_matrix_complex * b);\nGSL_EXPORT int gsl_matrix_complex_div_elements (gsl_matrix_complex * a, const gsl_matrix_complex * b);\nGSL_EXPORT int gsl_matrix_complex_scale (gsl_matrix_complex * a, const gsl_complex x);\nGSL_EXPORT int gsl_matrix_complex_add_constant (gsl_matrix_complex * a, const gsl_complex x);\nGSL_EXPORT int gsl_matrix_complex_add_diagonal (gsl_matrix_complex * a, const gsl_complex x);\n\n/***********************************************************************/\n/* The functions below are obsolete                                    */\n/***********************************************************************/\nGSL_EXPORT int gsl_matrix_complex_get_row(gsl_vector_complex * v, const gsl_matrix_complex * m, const size_t i);\nGSL_EXPORT int gsl_matrix_complex_get_col(gsl_vector_complex * v, const gsl_matrix_complex * m, const size_t j);\nGSL_EXPORT int gsl_matrix_complex_set_row(gsl_matrix_complex * m, const size_t i, const gsl_vector_complex * v);\nGSL_EXPORT int gsl_matrix_complex_set_col(gsl_matrix_complex * m, const size_t j, const gsl_vector_complex * v);\n\n#ifdef HAVE_INLINE\n\nextern inline \ngsl_complex\ngsl_matrix_complex_get(const gsl_matrix_complex * m, \n                     const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  gsl_complex zero = {{0,0}};\n\n  if (i >= m->size1)\n    {\n      GSL_ERROR_VAL(\"first index out of range\", GSL_EINVAL, zero) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_VAL(\"second index out of range\", GSL_EINVAL, zero) ;\n    }\n#endif\n  return *(gsl_complex *)(m->data + 2*(i * m->tda + j)) ;\n} \n\nextern inline \nvoid\ngsl_matrix_complex_set(gsl_matrix_complex * m, \n                     const size_t i, const size_t j, const gsl_complex x)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_VOID(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_VOID(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  *(gsl_complex *)(m->data + 2*(i * m->tda + j)) = x ;\n}\n\nextern inline \ngsl_complex *\ngsl_matrix_complex_ptr(gsl_matrix_complex * m, \n                             const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  return (gsl_complex *)(m->data + 2*(i * m->tda + j)) ;\n} \n\nextern inline \nconst gsl_complex *\ngsl_matrix_complex_const_ptr(const gsl_matrix_complex * m, \n                                   const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  return (const gsl_complex *)(m->data + 2*(i * m->tda + j)) ;\n} \n\n#endif /* HAVE_INLINE */\n\n__END_DECLS\n\n#endif /* __GSL_MATRIX_COMPLEX_DOUBLE_H__ */\n", "meta": {"hexsha": "87dda05a44c420778fb87656055a12dacf8051f7", "size": 11571, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/gsl/include/gsl/gsl_matrix_complex_double.h", "max_stars_repo_name": "dynaryu/vaws", "max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/gsl/include/gsl/gsl_matrix_complex_double.h", "max_issues_repo_name": "dynaryu/vaws", "max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/gsl/include/gsl/gsl_matrix_complex_double.h", "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2337278107, "max_line_length": 122, "alphanum_fraction": 0.6842969493, "num_tokens": 2687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473485858429, "lm_q2_score": 0.028436029957247463, "lm_q1q2_score": 0.012231682890417596}}
{"text": "#pragma once\n\n#include <gsl/span>\n\n#include <cstddef>\n\nnamespace imageview {\n\n// Class representing a color in RGBA32 color space.\nclass RGBA32 {\n public:\n  constexpr RGBA32() noexcept = default;\n\n  constexpr RGBA32(unsigned char red, unsigned char green, unsigned char blue, unsigned char alpha) noexcept\n      : red(red), green(green), blue(blue), alpha(alpha) {}\n\n  unsigned char red = 0;\n  unsigned char green = 0;\n  unsigned char blue = 0;\n  unsigned char alpha = 0;\n};\n\n// Implementation of the PixelFormat concept for RGBA32 pixel format.\n// In this pixel format the color is represented via 4 8-bit integers,\n// specifying the red, green, blue and alpha channels. When serializing to /\n// deserializing from  a byte array, the order of the channels is RGBA (i.e.\n// not BGRA).\nclass PixelFormatRGBA32 {\n public:\n  using color_type = RGBA32;\n  static constexpr int kBytesPerPixel = 4;\n\n  constexpr color_type read(gsl::span<const std::byte, kBytesPerPixel> data) const;\n\n  constexpr void write(const color_type& color, gsl::span<std::byte, kBytesPerPixel> data) const;\n};\n\nconstexpr bool operator==(const RGBA32& lhs, const RGBA32& rhs) {\n  return lhs.red == rhs.red && lhs.green == rhs.green && lhs.blue == rhs.blue && lhs.alpha == rhs.alpha;\n}\n\nconstexpr bool operator!=(const RGBA32& lhs, const RGBA32& rhs) { return !(lhs == rhs); }\n\nconstexpr PixelFormatRGBA32::color_type PixelFormatRGBA32::read(gsl::span<const std::byte, kBytesPerPixel> data) const {\n  return color_type(static_cast<unsigned char>(data[0]), static_cast<unsigned char>(data[1]),\n                    static_cast<unsigned char>(data[2]), static_cast<unsigned char>(data[3]));\n}\n\nconstexpr void PixelFormatRGBA32::write(const color_type& color, gsl::span<std::byte, kBytesPerPixel> data) const {\n  data[0] = static_cast<std::byte>(color.red);\n  data[1] = static_cast<std::byte>(color.green);\n  data[2] = static_cast<std::byte>(color.blue);\n  data[3] = static_cast<std::byte>(color.alpha);\n}\n\n}  // namespace imageview\n", "meta": {"hexsha": "3d209c75d7987f05ed64c10b5dd1cc9fa0936d6a", "size": 1996, "ext": "h", "lang": "C", "max_stars_repo_path": "include/imageview/pixel_formats/PixelFormatRGBA32.h", "max_stars_repo_name": "alexanderbelous/imageview", "max_stars_repo_head_hexsha": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/imageview/pixel_formats/PixelFormatRGBA32.h", "max_issues_repo_name": "alexanderbelous/imageview", "max_issues_repo_head_hexsha": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/imageview/pixel_formats/PixelFormatRGBA32.h", "max_forks_repo_name": "alexanderbelous/imageview", "max_forks_repo_head_hexsha": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0175438596, "max_line_length": 120, "alphanum_fraction": 0.7159318637, "num_tokens": 502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3174262526733264, "lm_q2_score": 0.03846618967596892, "lm_q1q2_score": 0.01221017844346421}}
{"text": "#pragma once\n\n#include <cuda/runtime_api.hpp>\n\n#include <gsl-lite/gsl-lite.hpp>\n\n#include <cub/cub.cuh>\n\n#include <thrustshift/not-a-vector.h>\n\nnamespace thrustshift {\n\nnamespace async {\n\ntemplate <class ValuesInRange,\n          class ValuesOutRange,\n          class ScanOp,\n          class MemoryResource>\nvoid inclusive_scan(cuda::stream_t& stream,\n                    ValuesInRange&& values_in,\n                    ValuesOutRange&& values_out,\n                    ScanOp scan_op,\n                    MemoryResource& delayed_memory_resource) {\n\n\tconst std::size_t N = values_in.size();\n\n\tgsl_Expects(values_out.size() == N);\n\n\tsize_t tmp_bytes_size = 0;\n\tvoid* tmp_ptr = nullptr;\n\n\tauto exec = [&] {\n\t\tcuda::throw_if_error(cub::DeviceScan::InclusiveScan(tmp_ptr,\n\t\t                                                    tmp_bytes_size,\n\t\t                                                    values_in.data(),\n\t\t                                                    values_out.data(),\n\t\t                                                    scan_op,\n\t\t                                                    N,\n\t\t                                                    stream.handle()));\n\t};\n\texec();\n\tauto tmp =\n\t    make_not_a_vector<uint8_t>(tmp_bytes_size, delayed_memory_resource);\n\ttmp_ptr = tmp.to_span().data();\n\texec();\n}\n\n} // namespace async\n\n} // namespace thrustshift\n", "meta": {"hexsha": "1f842c15dfc5b7ab9b649436b9a0e2d7bf0a6c6b", "size": 1366, "ext": "h", "lang": "C", "max_stars_repo_path": "include/thrustshift/scan.h", "max_stars_repo_name": "pauleonix/thrustshift", "max_stars_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/thrustshift/scan.h", "max_issues_repo_name": "pauleonix/thrustshift", "max_issues_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/thrustshift/scan.h", "max_forks_repo_name": "pauleonix/thrustshift", "max_forks_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7843137255, "max_line_length": 73, "alphanum_fraction": 0.5043923865, "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35220178204788966, "lm_q2_score": 0.034618838963676436, "lm_q1q2_score": 0.012192816775435758}}
{"text": "#include <gsl/gsl_test.h>\n#include <gsl/gsl_ieee_utils.h>\n#include <gsl/gsl_math.h>\n#include \"gsl_cblas.h\"\n\n#include \"tests.h\"\n\nvoid\ntest_syr2 (void) {\nconst double flteps = 1e-4, dbleps = 1e-6;\n  {\n   int order = 101;\n   int uplo = 121;\n   int N = 1;\n   int lda = 1;\n   float alpha = 0.0f;\n   float A[] = { 0.862f };\n   float X[] = { 0.823f };\n   int incX = -1;\n   float Y[] = { 0.699f };\n   int incY = -1;\n   float A_expected[] = { 0.862f };\n   cblas_ssyr2(order, uplo, N, alpha, X, incX, Y, incY, A, lda);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(A[i], A_expected[i], flteps, \"ssyr2(case 1434)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int uplo = 122;\n   int N = 1;\n   int lda = 1;\n   float alpha = 0.0f;\n   float A[] = { 0.862f };\n   float X[] = { 0.823f };\n   int incX = -1;\n   float Y[] = { 0.699f };\n   int incY = -1;\n   float A_expected[] = { 0.862f };\n   cblas_ssyr2(order, uplo, N, alpha, X, incX, Y, incY, A, lda);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(A[i], A_expected[i], flteps, \"ssyr2(case 1435)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int uplo = 121;\n   int N = 1;\n   int lda = 1;\n   float alpha = 0.0f;\n   float A[] = { 0.862f };\n   float X[] = { 0.823f };\n   int incX = -1;\n   float Y[] = { 0.699f };\n   int incY = -1;\n   float A_expected[] = { 0.862f };\n   cblas_ssyr2(order, uplo, N, alpha, X, incX, Y, incY, A, lda);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(A[i], A_expected[i], flteps, \"ssyr2(case 1436)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int uplo = 122;\n   int N = 1;\n   int lda = 1;\n   float alpha = 0.0f;\n   float A[] = { 0.862f };\n   float X[] = { 0.823f };\n   int incX = -1;\n   float Y[] = { 0.699f };\n   int incY = -1;\n   float A_expected[] = { 0.862f };\n   cblas_ssyr2(order, uplo, N, alpha, X, incX, Y, incY, A, lda);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(A[i], A_expected[i], flteps, \"ssyr2(case 1437)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int uplo = 121;\n   int N = 1;\n   int lda = 1;\n   double alpha = 0;\n   double A[] = { -0.824 };\n   double X[] = { 0.684 };\n   int incX = -1;\n   double Y[] = { 0.965 };\n   int incY = -1;\n   double A_expected[] = { -0.824 };\n   cblas_dsyr2(order, uplo, N, alpha, X, incX, Y, incY, A, lda);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(A[i], A_expected[i], dbleps, \"dsyr2(case 1438)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int uplo = 122;\n   int N = 1;\n   int lda = 1;\n   double alpha = 0;\n   double A[] = { -0.824 };\n   double X[] = { 0.684 };\n   int incX = -1;\n   double Y[] = { 0.965 };\n   int incY = -1;\n   double A_expected[] = { -0.824 };\n   cblas_dsyr2(order, uplo, N, alpha, X, incX, Y, incY, A, lda);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(A[i], A_expected[i], dbleps, \"dsyr2(case 1439)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int uplo = 121;\n   int N = 1;\n   int lda = 1;\n   double alpha = 0;\n   double A[] = { -0.824 };\n   double X[] = { 0.684 };\n   int incX = -1;\n   double Y[] = { 0.965 };\n   int incY = -1;\n   double A_expected[] = { -0.824 };\n   cblas_dsyr2(order, uplo, N, alpha, X, incX, Y, incY, A, lda);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(A[i], A_expected[i], dbleps, \"dsyr2(case 1440)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int uplo = 122;\n   int N = 1;\n   int lda = 1;\n   double alpha = 0;\n   double A[] = { -0.824 };\n   double X[] = { 0.684 };\n   int incX = -1;\n   double Y[] = { 0.965 };\n   int incY = -1;\n   double A_expected[] = { -0.824 };\n   cblas_dsyr2(order, uplo, N, alpha, X, incX, Y, incY, A, lda);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(A[i], A_expected[i], dbleps, \"dsyr2(case 1441)\");\n     }\n   };\n  };\n\n\n}\n", "meta": {"hexsha": "9ba29598998dbabad91c432a16548433cac4b7d9", "size": 3813, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/cblas/test_syr2.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/cblas/test_syr2.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/cblas/test_syr2.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 20.2819148936, "max_line_length": 69, "alphanum_fraction": 0.4781012326, "num_tokens": 1543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3629692055196168, "lm_q2_score": 0.03358950444082818, "lm_q1q2_score": 0.012191955740685045}}
{"text": "/**\n * @file common.h\n * @brief Public header file containing the common objects, API used by different applications\n */\n\n#ifndef COMMON_H\n#define COMMON_H\n\n#include <petsc.h>\n\n/** \n * @brief The communicator context \n */\nstruct _p_COMM {\n  MPI_Comm     type; /**< MPI communicator SELF or WORLD */\n  PetscMPIInt  rank; /**< Process rank */\n  PetscMPIInt  size; /**< Communicator size */\n  PetscInt     refct; /**< Reference count to know how many objects are sharing the communicator */\n};\n\ntypedef struct _p_COMM *COMM;\n\n/**\n * @brief Creates the communicator object COMM\n * @param [in] MPI_Comm mpicomm - The MPI communicator\n * @param [out] COMM* outcomm - The COMM object\n */\nextern PetscErrorCode COMMCreate(MPI_Comm,COMM*);\n/**\n * @brief Destroys the communicator object COMM created with COMMCreate\n * @param [in] COMM* outcomm - The COMM object\n */\nextern PetscErrorCode COMMDestroy(COMM*);\n/**\n * @brief NOT IMPLIMENTED\n */\nextern PetscErrorCode SetMatrixValues(Mat,PetscInt,PetscInt[],PetscInt,PetscInt[],PetscScalar[]);\n#endif\n", "meta": {"hexsha": "bfa6caa86ae8423e7b548a8db21f27fffd236914", "size": 1039, "ext": "h", "lang": "C", "max_stars_repo_path": "include/common.h", "max_stars_repo_name": "pflow-team/PFLOW", "max_stars_repo_head_hexsha": "85b21a84514f438b6b956f024e4b753c0f3ccc95", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/common.h", "max_issues_repo_name": "pflow-team/PFLOW", "max_issues_repo_head_hexsha": "85b21a84514f438b6b956f024e4b753c0f3ccc95", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/common.h", "max_forks_repo_name": "pflow-team/PFLOW", "max_forks_repo_head_hexsha": "85b21a84514f438b6b956f024e4b753c0f3ccc95", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-11T00:24:08.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-11T00:24:08.000Z", "avg_line_length": 26.641025641, "max_line_length": 99, "alphanum_fraction": 0.7131857555, "num_tokens": 252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3311197396289915, "lm_q2_score": 0.03676946383261257, "lm_q1q2_score": 0.012175095290552294}}
{"text": "#include <pygsl/error_helpers.h>\n#include <pygsl/function_helpers.h>\n#include <pygsl/pygsl_features.h>\n\n#ifdef PyGSL_DERIV_MODULE\n#if ( _PYGSL_GSL_HAS_DERIV == 0 )\n#error \"The deriv module was only introduced by GSL 1.5. You seem to compile against an older verion!\"\n#endif\n#include <gsl/gsl_deriv.h>\n#endif /* PyGSL_DERIV_MODULE */\n\n#include <gsl/gsl_diff.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_math.h>\n#include <setjmp.h>\n/* \n * callback functions\n * - python function passed by user\n * - actual C callback\n * - GSL wrapper struct\n */\n\n/* Used for traceback */\nstatic PyObject *module = NULL;\n\ntypedef struct{\n\tPyObject * callback;\n\tPyObject * args;\n\tjmp_buf  buffer;\n}pygsl_diff_args;\n\n\nstatic double \ndiff_callback(double x, void *p)\n{\n\tdouble value;\n\tint flag;\n\tpygsl_diff_args *pargs = NULL;\n\n\tpargs = (pygsl_diff_args *) p;\n\n\tassert(pargs->callback);\n\tassert(pargs->args);\n\tflag = PyGSL_function_wrap_helper(x, &value, NULL, pargs->callback,\n\t\t\t\t\t  pargs->args, (char *)__FUNCTION__);\n\n\tif(GSL_SUCCESS != flag){\n\t\tlongjmp(pargs->buffer, flag);\n\t\treturn gsl_nan();\n\t}\n\treturn value;\n}\n\n/* wrapper function */\ntypedef int pygsl_deriv_func(const gsl_function *, double, double, double *, double *);\ntypedef int pygsl_diff_func(const gsl_function *, double, double *, double *);\n\nstatic PyObject *\nPyGSL_diff_generic(PyObject *self, PyObject *args, \n#ifndef PyGSL_DIFF_MODULE\n\t\t   pygsl_deriv_func func\n#else \n\t\t   pygsl_diff_func func\n#endif\n)\n{\n\tPyObject *result=NULL, *myargs=NULL;\n\tPyObject *cb=NULL;\n\n\tpygsl_diff_args pargs = {NULL, NULL};\n\t/* Changed to compile using Sun's Compiler */\n\tgsl_function diff_gsl_callback = {NULL, NULL};\n\n\n\n\n\tdouble x, value, abserr;\n\tint flag;\n#ifndef PyGSL_DIFF_MODULE\n\tdouble h;\n\tif(! PyArg_ParseTuple(args, \"Odd|O\", &cb, &x, &h, &myargs)){\n\t\treturn NULL;\n\t}\n#else\n\tif(! PyArg_ParseTuple(args, \"Od|O\", &cb, &x, &myargs)){\n\t\treturn NULL;\n\t}\n#endif\n\n\t/* Changed to compile using Sun's Compiler */\n\tdiff_gsl_callback.function = diff_callback;\n\tdiff_gsl_callback.params = (void *) &pargs;\n\n\tif(! PyCallable_Check(cb)) {\n\t\tPyErr_SetString(PyExc_TypeError, \n\t\t\t\t\"The first parameter must be callable\");\n\t\treturn NULL;\n\t}\n\tPy_INCREF(cb);               /* Add a reference to new callback */\n\n\tpargs.callback = cb;        /* Remember new callback */\n\n\n\t/* Did I get arguments? If so handle them */\n\tif(NULL == myargs){\n\t\tPy_INCREF(Py_None);\n\t\tpargs.args= Py_None;\n\t}else{\n\t\tPy_INCREF(myargs);\n\t\tpargs.args= myargs;\n\t}\n\n\tif((flag=setjmp(pargs.buffer)) == 0){\n\t\t/* Jmp buffer set, call the function */\n#ifndef PyGSL_DIFF_MODULE\n\t     flag = func(&diff_gsl_callback, x, h, &value, &abserr);\n#else\n\t     flag = func(&diff_gsl_callback, x, &value, &abserr);\t\n#endif\n\t}else{\n\t\tDEBUG_MESS(2, \"CALLBACK called longjmp! flag =%d\", flag);\n\t}\n\t\n\t/* Arguments no longer used */\n\tPy_DECREF(pargs.args);\n\n\t/* Dispose of callback */\n\tPy_DECREF(pargs.callback);\n\n \n\tif(flag != GSL_SUCCESS){\n\t\tPyGSL_ERROR_FLAG(flag);\n\t\treturn NULL;\n\t}\n\n\tresult = Py_BuildValue(\"(dd)\", value, abserr);\n\treturn result;\n}\n", "meta": {"hexsha": "736e882b0a2fe01e1f4e5e9f9fb22c402780e67c", "size": 3028, "ext": "c", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/src/diff_deriv_common.c", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/src/diff_deriv_common.c", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/src/diff_deriv_common.c", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 21.7841726619, "max_line_length": 102, "alphanum_fraction": 0.6912153236, "num_tokens": 843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.02931222810146209, "lm_q1q2_score": 0.012161609607028234}}
{"text": "#ifndef main_H_INCLUDED\n#define main_H_INCLUDED\n\n#include \"wf.h\"\n#include \"glasma.h\"\n#include \"jet.h\"\n#include \"bfkl.h\"\n#include \"time.h\"\n#include \"single.h\"\n#include <gsl/gsl_errno.h>\n\nchar tag[256];\n\n//*\n//*\n// This section of code initializes and reads in the\n// following global variables from file\n//*\n//*\n#define X_FIELDS \\\n   X(int, wfTAG, \"%d\") \\\n   X(int, A1, \"%d\") \\\n   X(int, A2, \"%d\") \\\n   X(double, rts, \"%lf\") \\\n\n#include \"ReadParameters.cxx\"\n//\n\n\n#endif\n", "meta": {"hexsha": "aba644605cca988445b58850fe0a98bd9a819025", "size": 469, "ext": "h", "lang": "C", "max_stars_repo_path": "src/main.h", "max_stars_repo_name": "kdusling/mpc", "max_stars_repo_head_hexsha": "ccdc1f5ddcdba6cfc6ea5413ef5cc180ffe682bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/main.h", "max_issues_repo_name": "kdusling/mpc", "max_issues_repo_head_hexsha": "ccdc1f5ddcdba6cfc6ea5413ef5cc180ffe682bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main.h", "max_forks_repo_name": "kdusling/mpc", "max_forks_repo_head_hexsha": "ccdc1f5ddcdba6cfc6ea5413ef5cc180ffe682bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.1290322581, "max_line_length": 52, "alphanum_fraction": 0.6332622601, "num_tokens": 140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.396068180531364, "lm_q2_score": 0.030675799052176208, "lm_q1q2_score": 0.012149707916941171}}
{"text": "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT license.\n\n#pragma once\n\n#if SEAL_COMPILER == SEAL_COMPILER_GCC\n\n// We require GCC >= 6\n#if (__GNUC__ < 6) || not defined(__cplusplus)\n#pragma GCC error \"SEAL requires __GNUC__ >= 6\"\n#endif\n\n// Read in config.h\n#include \"seal/util/config.h\"\n\n#if (__GNUC__ == 6) && defined(SEAL_USE_IF_CONSTEXPR)\n#pragma GCC error \"g++-6 cannot compile Microsoft SEAL as C++17; set CMake build option `SEAL_USE_CXX17' to OFF\"\n#endif\n\n// Are we using MSGSL?\n#ifdef SEAL_USE_MSGSL\n#include <gsl/gsl>\n#endif\n\n// Are intrinsics enabled?\n#ifdef SEAL_USE_INTRIN\n#include <x86intrin.h>\n\n#ifdef SEAL_USE___BUILTIN_CLZLL\n#define SEAL_MSB_INDEX_UINT64(result, value) {                                      \\\n    *result = 63UL - static_cast<unsigned long>(__builtin_clzll(value));            \\\n}\n#endif\n\n#ifdef SEAL_USE___INT128\n#define SEAL_MULTIPLY_UINT64_HW64(operand1, operand2, hw64) {                       \\\n    *hw64 = static_cast<unsigned long long>(                                        \\\n            ((static_cast<unsigned __int128>(operand1)                              \\\n            * static_cast<unsigned __int128>(operand2)) >> 64));                    \\\n}\n\n#define SEAL_MULTIPLY_UINT64(operand1, operand2, result128) {                       \\\n    unsigned __int128 product = static_cast<unsigned __int128>(operand1) * operand2;\\\n    result128[0] = static_cast<unsigned long long>(product);                        \\\n    result128[1] = static_cast<unsigned long long>(product >> 64);                  \\\n}\n\n#define SEAL_DIVIDE_UINT128_UINT64(numerator, denominator, result) {                \\\n    unsigned __int128 n, q;                                                         \\\n    n = (static_cast<unsigned __int128>(numerator[1]) << 64) |                      \\\n        (static_cast<unsigned __int128>(numerator[0]));                             \\\n    q = n / denominator;                                                            \\\n    n -= q * denominator;                                                           \\\n    numerator[0] = static_cast<std::uint64_t>(n);                                   \\\n    numerator[1] = static_cast<std::uint64_t>(n >> 64);                             \\\n    quotient[0] = static_cast<std::uint64_t>(q);                                    \\\n    quotient[1] = static_cast<std::uint64_t>(q >> 64);                              \\\n}\n#endif\n\n#ifdef SEAL_USE__ADDCARRY_U64\n#define SEAL_ADD_CARRY_UINT64(operand1, operand2, carry, result) _addcarry_u64(     \\\n    carry, operand1, operand2, result)\n#endif\n\n#ifdef SEAL_USE__SUBBORROW_U64\n#if ((__GNUC__ == 7) && (__GNUC_MINOR__ >= 2)) || (__GNUC__  >= 8)\n// The inverted arguments problem was fixed in GCC-7.2\n// (https://patchwork.ozlabs.org/patch/784309/)\n#define SEAL_SUB_BORROW_UINT64(operand1, operand2, borrow, result) _subborrow_u64(  \\\n    borrow, operand1, operand2, result)\n#else\n// Warning: Note the inverted order of operand1 and operand2\n#define SEAL_SUB_BORROW_UINT64(operand1, operand2, borrow, result) _subborrow_u64(  \\\n    borrow, operand2, operand1, result)\n#endif //(__GNUC__ == 7) && (__GNUC_MINOR__ >= 2)\n#endif\n\n#endif //SEAL_USE_INTRIN\n\n#endif\n", "meta": {"hexsha": "c41873770f49f7735f0c31a8a3032a97d02001df", "size": 3226, "ext": "h", "lang": "C", "max_stars_repo_path": "native/src/seal/util/gcc.h", "max_stars_repo_name": "deisler134/SEAL", "max_stars_repo_head_hexsha": "4a019473ad90b066b593f5714d6bf07d3a3ed671", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-12-24T07:08:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-13T17:40:28.000Z", "max_issues_repo_path": "native/src/seal/util/gcc.h", "max_issues_repo_name": "KoizumiRuby/SEAL", "max_issues_repo_head_hexsha": "1d5c8169aa5aca9deb75c4079e53ea8d5e94007d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "native/src/seal/util/gcc.h", "max_forks_repo_name": "KoizumiRuby/SEAL", "max_forks_repo_head_hexsha": "1d5c8169aa5aca9deb75c4079e53ea8d5e94007d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-09T08:38:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-09T08:38:44.000Z", "avg_line_length": 39.3414634146, "max_line_length": 112, "alphanum_fraction": 0.5799752015, "num_tokens": 781, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3557749071749625, "lm_q2_score": 0.03410042841175721, "lm_q1q2_score": 0.012132076752819375}}
{"text": "#include \"quantum_gates.h\"\n#include \"quac_p.h\"\n#include <stdlib.h>\n#include <stdio.h>\n#include <petsc.h>\n#include <stdarg.h>\n\n\nint _num_quantum_gates = 0;\nint _current_gate = 0;\nstruct quantum_gate_struct _quantum_gate_list[MAX_GATES];\nint _min_gate_enum = 5; // Minimum gate enumeration number\nint _gate_array_initialized = 0;\nint _num_circuits    = 0;\nint _current_circuit = 0;\ncircuit _circuit_list[MAX_GATES];\nvoid (*_get_val_j_functions_gates[MAX_GATES])(PetscInt,struct quantum_gate_struct,PetscInt*,PetscInt[],PetscScalar[],PetscInt);\n\n/* EventFunction is one step in Petsc to apply some action at a specific time.\n * This function checks to see if an event has happened.\n */\nPetscErrorCode _QG_EventFunction(TS ts,PetscReal t,Vec U,PetscScalar *fvalue,void *ctx) {\n  /* Check if the time has passed a gate */\n\n  if (_current_gate<_num_quantum_gates) {\n    /* We signal that we passed the time by returning a negative number */\n    fvalue[0] = _quantum_gate_list[_current_gate].time - t;\n  } else {\n    fvalue[0] = t;\n  }\n\n  return(0);\n}\n\n/* PostEventFunction is the other step in Petsc. If an event has happend, petsc will call this function\n * to apply that event.\n*/\nPetscErrorCode _QG_PostEventFunction(TS ts,PetscInt nevents,PetscInt event_list[],PetscReal t,\n                                     Vec U,PetscBool forward,void* ctx) {\n\n   /* We only have one event at the moment, so we do not need to branch.\n    * If we had more than one event, we would put some logic here.\n    */\n  if (nevents) {\n    /* Apply the current gate */\n    //Deprecated?\n    /* _apply_gate(_quantum_gate_list[_current_gate].my_gate_type,_quantum_gate_list[_current_gate].qubit_numbers,U); */\n    /* Increment our gate counter */\n    _current_gate = _current_gate + 1;\n  }\n\n  TSSetSolution(ts,U);\n  return(0);\n}\n\n/* EventFunction is one step in Petsc to apply some action at a specific time.\n * This function checks to see if an event has happened.\n */\nPetscErrorCode _QC_EventFunction(TS ts,PetscReal t,Vec U,PetscScalar *fvalue,void *ctx) {\n  /* Check if the time has passed a gate */\n  PetscInt current_gate,num_gates;\n  PetscLogEventBegin(_qc_event_function_event,0,0,0,0);\n  if (_current_circuit<_num_circuits) {\n    current_gate = _circuit_list[_current_circuit].current_gate;\n    num_gates    = _circuit_list[_current_circuit].num_gates;\n    if (current_gate<num_gates) {\n      /* We signal that we passed the time by returning a negative number */\n      fvalue[0] = _circuit_list[_current_circuit].gate_list[current_gate].time\n        +_circuit_list[_current_circuit].start_time - t;\n    } else {\n      if (nid==0){\n        printf(\"ERROR! current_gate should never be larger than num_gates in _QC_EventFunction\\n\");\n        exit(0);\n      }\n    }\n  } else {\n    fvalue[0] = t;\n  }\n  PetscLogEventEnd(_qc_event_function_event,0,0,0,0);\n  return(0);\n}\n\n/* PostEventFunction is the other step in Petsc. If an event has happend, petsc will call this function\n * to apply that event.\n*/\nPetscErrorCode _QC_PostEventFunction(TS ts,PetscInt nevents,PetscInt event_list[],\n                                     PetscReal t,Vec U,PetscBool forward,void* ctx) {\n  PetscInt current_gate,num_gates;\n  PetscReal gate_time;\n   /* We only have one event at the moment, so we do not need to branch.\n    * If we had more than one event, we would put some logic here.\n    */\n\n  PetscLogEventBegin(_qc_postevent_function_event,0,0,0,0);\n\n  if (nevents) {\n    num_gates    = _circuit_list[_current_circuit].num_gates;\n    current_gate = _circuit_list[_current_circuit].current_gate;\n    gate_time = _circuit_list[_current_circuit].gate_list[current_gate].time;\n    /* Apply all gates at a given time incrementally  */\n    while (current_gate<num_gates && _circuit_list[_current_circuit].gate_list[current_gate].time == gate_time){\n      /* apply the current gate */\n        printf(\"current_gate %d num_gates %d\\n\",current_gate,num_gates);\n      _apply_gate(_circuit_list[_current_circuit].gate_list[current_gate],U);\n\n      /* Increment our gate counter */\n      _circuit_list[_current_circuit].current_gate = _circuit_list[_current_circuit].current_gate + 1;\n      current_gate = _circuit_list[_current_circuit].current_gate;\n    }\n    if(_circuit_list[_current_circuit].current_gate>=_circuit_list[_current_circuit].num_gates){\n      /* We've exhausted this circuit; move on to the next. */\n      _current_circuit = _current_circuit + 1;\n    }\n\n  }\n\n  TSSetSolution(ts,U);\n  PetscLogEventEnd(_qc_postevent_function_event,0,0,0,0);\n  return(0);\n}\n\n/* Add a gate to the list */\nvoid add_gate(PetscReal time,gate_type my_gate_type,...) {\n  int num_qubits=0,qubit,i;\n  va_list ap;\n\n  if (my_gate_type==HADAMARD) {\n    num_qubits = 1;\n  } else if (my_gate_type==CNOT){\n    num_qubits = 2;\n  } else {\n    if (nid==0){\n      printf(\"ERROR! Gate type not recognized!\\n\");\n      exit(0);\n    }\n  }\n\n  // Store arguments in list\n  _quantum_gate_list[_num_quantum_gates].qubit_numbers = malloc(num_qubits*sizeof(int));\n  _quantum_gate_list[_num_quantum_gates].time = time;\n  _quantum_gate_list[_num_quantum_gates].my_gate_type = my_gate_type;\n  _quantum_gate_list[_num_quantum_gates]._get_val_j_from_global_i = HADAMARD_get_val_j_from_global_i;\n\n  // Loop through and store qubits\n  for (i=0;i<num_qubits;i++){\n    qubit = va_arg(ap,int);\n    _quantum_gate_list[_num_quantum_gates].qubit_numbers[i] = qubit;\n  }\n\n  _num_quantum_gates = _num_quantum_gates + 1;\n}\n\n\n/* Apply a specific gate */\nvoid _apply_gate(struct quantum_gate_struct this_gate,Vec rho){\n  PetscScalar op_vals[total_levels*2];\n  Mat gate_mat; //FIXME Consider having only one static Mat for all gates, rather than creating new ones every time\n  Vec tmp_answer;\n  PetscInt dim,i,Istart,Iend,num_js,these_js[total_levels*2];\n  // FIXME: maybe total_levels*2 is too much or not enough? Consider having a better bound.\n\n  PetscLogEventBegin(_apply_gate_event,0,0,0,0);\n\n  if (_lindblad_terms){\n    dim = total_levels*total_levels;\n  } else {\n    dim = total_levels;\n  }\n\n  VecDuplicate(rho,&tmp_answer); //Create a new vec with the same size as rho\n\n  MatCreate(PETSC_COMM_WORLD,&gate_mat);\n  MatSetSizes(gate_mat,PETSC_DECIDE,PETSC_DECIDE,dim,dim);\n  MatSetFromOptions(gate_mat);\n  MatMPIAIJSetPreallocation(gate_mat,4,NULL,4,NULL); //This matrix is incredibly sparse!\n  MatSetUp(gate_mat);\n  /* Construct the gate matrix, on the fly */\n  MatGetOwnershipRange(gate_mat,&Istart,&Iend);\n\n  for (i=Istart;i<Iend;i++){\n    if (_lindblad_terms){\n      // Get the corresponding j and val for the superoperator U* cross U\n      this_gate._get_val_j_from_global_i(i,this_gate,&num_js,these_js,op_vals,0);\n    } else {\n      // Get the corresponding j and val for just the matrix U\n      this_gate._get_val_j_from_global_i(i,this_gate,&num_js,these_js,op_vals,-1);\n    }\n    MatSetValues(gate_mat,1,&i,num_js,these_js,op_vals,ADD_VALUES);\n  }\n  MatAssemblyBegin(gate_mat,MAT_FINAL_ASSEMBLY);\n  MatAssemblyEnd(gate_mat,MAT_FINAL_ASSEMBLY);\n  /* MatView(gate_mat,PETSC_VIEWER_STDOUT_SELF); */\n  MatMult(gate_mat,rho,tmp_answer);\n  VecCopy(tmp_answer,rho); //Copy our tmp_answer array into rho\n\n  VecDestroy(&tmp_answer); //Destroy the temp answer\n  MatDestroy(&gate_mat);\n\n  PetscLogEventEnd(_apply_gate_event,0,0,0,0);\n}\n\n/*z\n * _construct_gate_mat constructs the matrix needed for the quantum\n * computing gates.\n *\n * Inputs:\n *     gate_type my_gate_type  type of quantum gate\n *     int *s\n * Outputs:\n *      Mat gate_mat: the expanded, superoperator matrix for that gate\n */\n\nvoid _construct_gate_mat(gate_type my_gate_type,int *systems,Mat gate_mat){\n  PetscInt i,j,i_mat,j_mat,k1,k2,k3,k4,n_before1,n_before2,my_levels,n_after;\n  PetscInt i1,j1,i2=0,j2=0,comb_levels,control=-1,moved_system;\n  PetscReal    val1,val2;\n  PetscScalar add_to_mat;\n\n  if (my_gate_type == CNOT) {\n\n    /* The controlled NOT gate has two inputs, a target and a control.\n     * the target output is equal to the target input if the control is\n     * |0> and is flipped if the control input is |1> (Marinescu 146)\n     * As a matrix, for a two qubit system:\n     *     1 0 0 0        I2 0\n     *     0 1 0 0   =    0  sig_x\n     *     0 0 0 1\n     *     0 0 1 0\n     * Of course, when there are other qubits, tensor products and such\n     * must be applied to get the full basis representation.\n     */\n\n\n    /* Figure out which system is first in our basis\n     * 0 and 1 is hardcoded because CNOT gates have only 2 qubits */\n    n_before1  = subsystem_list[systems[0]]->n_before;\n    n_before2  = subsystem_list[systems[1]]->n_before;\n    control    = 0;\n    moved_system = systems[1];\n    /* 2 is hardcoded because CNOT gates are for qubits, which have 2 levels */\n    /* 4 is hardcoded because 2 qubits with 2 levels each */\n    n_after   = total_levels/(4*n_before1);\n\n    /* Check which is the control and which is the target */\n    if (n_before2<n_before1) {\n      n_after   = total_levels/(4*n_before2);\n      control   = 1;\n      moved_system = systems[0];\n      n_before1 = n_before2;\n    }\n    /* 4 is hardcoded because 2 qubits with 2 levels each */\n    my_levels   = 4;\n    for (k1=0;k1<n_after;k1++){\n      for (k2=0;k2<n_before1;k2++){\n        for (i=0;i<4;i++){ //4 is hardcoded because there are only 4 entries\n          val1 = _get_val_in_subspace_gate(i,my_gate_type,control,&i1,&j1);\n\n          /* Get I_b cross CNOT cross I_a in the temporary basis */\n          i1 = i1*n_after + k1 + k2*my_levels*n_after;\n          j1 = j1*n_after + k1 + k2*my_levels*n_after;\n\n          /* Permute to computational basis\n           * To aid in the computation, we generated the matrix in the 'temporary basis',\n           * where we exchanged the subsystem immediately after the first qubit with\n           * the second qubit of interest. I.e., doing a CNOT(q3,q7)\n           * Computational basis: q1 q2 q3 q4 q5 q6 q7 q8 q9 q10\n           * Temporary basis:     q1 q2 q3 q7 q5 q6 q4 q8 q9 q10\n           * This allows us to calculate CNOT easily - we just need to change\n           * the basis back to the computational one.\n           *\n           * Since the control variable tells us which qubit was the first,\n           * we switched the system immediately before that one with the\n           * stored variable moved_system\n           */\n           _change_basis_ij_pair(&i1,&j1,systems[control]+1,moved_system);\n          for (k3=0;k3<n_after;k3++){\n            for (k4=0;k4<n_before1;k4++){\n              for (j=0;j<4;j++){ //4 is hardcoded because there are only 4 entries\n                val2 = _get_val_in_subspace_gate(j,my_gate_type,control,&i2,&j2);\n\n                /* Get I_b cross CNOT cross I_a in the temporary basis */\n                i2 = i2*n_after + k3 + k4*my_levels*n_after;\n                j2 = j2*n_after + k3 + k4*my_levels*n_after;\n\n                /* Permute to computational basis */\n                _change_basis_ij_pair(&i2,&j2,systems[control]+1,moved_system);\n\n                add_to_mat = val1*val2;\n                /* Do the normal kron product expansion */\n                i_mat = my_levels*n_before1*n_after*i1 + i2;\n                j_mat = my_levels*n_before1*n_after*j1 + j2;\n                MatSetValue(gate_mat,i_mat,j_mat,add_to_mat,ADD_VALUES);\n              }\n            }\n          }\n        }\n      }\n    }\n  } else if (my_gate_type == HADAMARD) {\n\n    /*\n     * The Hadamard gate is a one qubit gate defined as:\n     *\n     *    H = 1/sqrt(2) 1  1\n     *                  1 -1\n     *\n     * Find the necessary Hilbert space dimensions for constructing the\n     * full space matrix.\n     */\n\n    n_before1  = subsystem_list[systems[0]]->n_before;\n    my_levels  = subsystem_list[systems[0]]->my_levels; //Should be 2, because qubit\n    n_after   = total_levels/(my_levels*n_before1);\n    comb_levels = my_levels*my_levels*n_before1*n_after;\n\n    for (k4=0;k4<n_before1*n_after;k4++){\n      for (i=0;i<4;i++){ // 4 hardcoded because there are 4 values in the hadamard\n        val1 = _get_val_in_subspace_gate(i,my_gate_type,control,&i1,&j1);\n        for (j=0;j<4;j++){\n          val2 = _get_val_in_subspace_gate(j,my_gate_type,control,&i2,&j2);\n          i2 = i2 + k4*my_levels;\n          j2 = j2 + k4*my_levels;\n          /*\n           * We need my_levels*n_before*n_after because we are taking\n           * H cross (Ia cross Ib cross H), so the the size of the second operator\n           * is my_levels*n_before*n_after\n           */\n          add_to_mat = val1*val2;\n          i_mat = my_levels*n_before1*n_after*i1 + i2;\n          j_mat = my_levels*n_before1*n_after*j1 + j2;\n          _add_to_PETSc_kron_ij(gate_mat,add_to_mat,i_mat,j_mat,n_before1,n_after,comb_levels);\n        }\n      }\n    }\n  } else if (my_gate_type == SIGMAX || my_gate_type == SIGMAY || my_gate_type == SIGMAZ || my_gate_type == SWAP) {\n\n    /*\n     * The pauli matrices are two qubit gates, sigmax, sigmay, sigmaz\n     * The SWAP gate swaps two qubits.\n     */\n\n    n_before1  = subsystem_list[systems[0]]->n_before;\n    my_levels  = subsystem_list[systems[0]]->my_levels; //Should be 2, because qubit\n    n_after   = total_levels/(my_levels*n_before1);\n    comb_levels = my_levels*my_levels*n_before1*n_after;\n\n    for (k4=0;k4<n_before1*n_after;k4++){\n      for (i=0;i<2;i++){// 2 hardcoded because there are 4 values in the hadamard\n        val1 = _get_val_in_subspace_gate(i,my_gate_type,control,&i1,&j1);\n        for (j=0;j<2;j++){\n          val2 = _get_val_in_subspace_gate(j,my_gate_type,control,&i2,&j2);\n          i2 = i2 + k4*my_levels;\n          j2 = j2 + k4*my_levels;\n          /*\n           * We need my_levels*n_before*n_after because we are taking\n           * H cross (Ia cross Ib cross H), so the the size of the second operator\n           * is my_levels*n_before*n_after\n           */\n          add_to_mat = val1*val2;\n          i_mat = my_levels*n_before1*n_after*i1 + i2;\n          j_mat = my_levels*n_before1*n_after*j1 + j2;\n          _add_to_PETSc_kron_ij(gate_mat,add_to_mat,i_mat,j_mat,n_before1,n_after,comb_levels);\n        }\n      }\n    }\n  }\n\n  return;\n}\n\n\n\nvoid _change_basis_ij_pair(PetscInt *i_op,PetscInt *j_op,PetscInt system1,PetscInt system2){\n  PetscInt na1,na2,lev1,lev2;\n\n  /*\n   * To apply our change of basis we use the neat trick that the row number\n   * in a given basis can be calculated similar to how a binary number is\n   * calculated (but generalized in that some bits can have more than two\n   * states. e.g. with three qubits\n   *  i(| 0 1 0 >) = 0*4 + 1*2 + 0*1 = 2\n   * where i() is the index, in this ordering, of the ket.\n   * Another example, with 1 2level, 1 3levels, and 1 4 level system:\n   *  i(| 0 1 0 >) = 0*12 + 1*4 + 0*1 = 4\n   * that is,\n   *  i(| a b c >) = a*n_af^a + b*n_af^b + c*n_af^c\n   * where n_af^a is the Hilbert space before system a, etc.\n   *\n   * Given a specific i, and only switching two systems,\n   * we can calculate i's partner in the switched basis\n   * by subtracting off the part from the current basis and\n   * adding in the part from the desired basis. This leaves everything\n   * else the same, but switches the two systems of interest.\n   *\n   * We need to be able to go from i to a specific subsystem's state.\n   * This is accomplished with the formula:\n   * (i/n_a % l)\n   * Take our example above:\n   * three qubits:  2 -> 2/4 % 2 = 0$2 = 0\n   *                2 -> 2/2 % 2 = 1%2 = 1\n   *                2 -> 2/1 % 2 = 2%2 = 0\n   * Or, the other example: 4 -> 4/12 % 2 = 0\n   *                        4 -> 4/4 % 3  = 1\n   *                        4 -> 4/1 % 4  = 0\n   * Note that this depends on integer division - 4/12 = 0\n   *\n   * Using this, we can precisely calculate a system's part of the sum,\n   * subtract that off, and then add the new basis.\n   *\n   * For example, let's switch our qubits from before around:\n   * i(| 1 0 0 >) = 1*4 + 0*2 + 0*1 = 4\n   * Now, switch back to the original basis. Note we swapped q3 and q2\n   * first, subtract off the contributions from q3 and q2\n   * i_new = 4 - 1*4 - 0*2 = 0\n   * Now, add on the contributions in the original basis\n   * i_new = 0 + 0*4 + 1*2 = 2\n   * Algorithmically,\n   * i_new = i - (i/na1)%lev1 * na1 - (i/na2)%lev2 * na2\n   *           + (i/na2)%lev1 * na1 + (i/na1)%lev2 * na2\n   * Note that we use our formula above to calculate the qubits\n   * state in this basis, given this specific i.\n   */\n\n\n  lev1  = subsystem_list[system1]->my_levels;\n  na1   = total_levels/(lev1*subsystem_list[system1]->n_before);\n\n  lev2  = subsystem_list[system2]->my_levels;\n  na2   = total_levels/(lev2*subsystem_list[system2]->n_before); // Changed from lev1->lev2\n\n  *i_op = *i_op - ((*i_op/na1)%lev1)*na1 - ((*i_op/na2)%lev2)*na2 +\n    ((*i_op/na1)%lev2)*na2 + ((*i_op/na2)%lev1)*na1;\n\n  *j_op = *j_op - ((*j_op/na1)%lev1)*na1 - ((*j_op/na2)%lev2)*na2 +\n    ((*j_op/na1)%lev2)*na2 + ((*j_op/na2)%lev1)*na1;\n\n  return;\n}\n\n\n\n/*\n * _get_val_in_subspace_gate is a simple function that returns the\n * i_op,j_op pair and val for a given index;\n * Inputs:\n *      int i:              current index\n *      gate_type my_gate_type the gate type\n * Outputs:\n *      int *i_op:          row value in subspace\n *      int *j_op:          column value in subspace\n * Return value:\n *      PetscScalar val:         value at i_op,j_op\n */\n\nPetscScalar _get_val_in_subspace_gate(PetscInt i,gate_type my_gate_type,PetscInt control,PetscInt *i_op,PetscInt *j_op){\n  PetscScalar val=0.0;\n  if (my_gate_type == CNOT) {\n    /* The controlled NOT gate has two inputs, a target and a control.\n     * the target output is equal to the target input if the control is\n     * |0> and is flipped if the control input is |1> (Marinescu 146)\n     * As a matrix, for a two qubit system:\n     *     1 0 0 0        I2 0\n     *     0 1 0 0   =    0  sig_x\n     *     0 0 0 1\n     *     0 0 1 0\n     * Of course, when there are other qubits, tensor products and such\n     * must be applied to get the full basis representation.\n     */\n    if (control==0) {\n      if (i==0){\n        *i_op = 0; *j_op = 0;\n        val = 1.0;\n      } else if (i==1) {\n        *i_op = 1; *j_op = 1;\n        val = 1.0;\n      } else if (i==2) {\n        *i_op = 2; *j_op = 3;\n        val = 1.0;\n      } else if (i==3) {\n        *i_op = 3; *j_op = 2;\n        val = 1.0;\n      }\n    } else if (control==1) {\n\n      if (i==0){\n        *i_op = 0; *j_op = 0;\n        val = 1.0;\n      } else if (i==1) {\n        *i_op = 1; *j_op = 3;\n        val = 1.0;\n      } else if (i==2) {\n        *i_op = 2; *j_op = 2;\n        val = 1.0;\n      } else if (i==3) {\n        *i_op = 3; *j_op = 1;\n        val = 1.0;\n      }\n    }\n\n  } else if (my_gate_type == HADAMARD) {\n    /*\n     * The Hadamard gate is a one qubit gate defined as:\n     *\n     *    H = 1/sqrt(2) 1  1\n     *                  1 -1\n     *\n     * Find the necessary Hilbert space dimensions for constructing the\n     * full space matrix.\n     */\n    if (i==0){\n      *i_op = 0; *j_op = 0;\n      val = 1.0/sqrt(2);\n    } else if (i==1) {\n      *i_op = 0; *j_op = 1;\n      val = 1.0/sqrt(2);\n    } else if (i==2) {\n      *i_op = 1; *j_op = 0;\n      val = 1.0/sqrt(2);\n    } else if (i==3) {\n      *i_op = 1; *j_op = 1;\n      val = -1.0/sqrt(2);\n    }\n  } else if (my_gate_type == SIGMAX){\n    /*\n     * SIGMAX gate\n     *\n     *   | 0  1 |\n     *   | 1  0 |\n     *\n     */\n    if (i==0){\n      *i_op = 0; *j_op = 1;\n      val = 1.0;\n    } else if (i==1) {\n      *i_op = 1; *j_op = 0;\n      val = 1.0;\n    } else if (i==2){\n      *i_op = 1; *j_op = 1;\n      val = 0.0;\n    } else if (i==2) {\n      *i_op = 0; *j_op = 0;\n      val = 0.0;\n    }\n  } else if (my_gate_type == SIGMAX){\n    /*\n     * SIGMAY gate\n     *\n     *   | 0    -1.j |\n     *   | 1.j    0 |\n     *\n     */\n    if (i==0){\n      *i_op = 0; *j_op = 1;\n      val = -PETSC_i;\n    } else if (i==1) {\n      *i_op = 1; *j_op = 0;\n      val = PETSC_i;\n    } else if (i==2){\n      *i_op = 1; *j_op = 1;\n      val = 0.0;\n    } else if (i==2) {\n      *i_op = 0; *j_op = 0;\n      val = 0.0;\n    }\n  } else if (my_gate_type == SIGMAZ){\n    /*\n     * SIGMAZ gate\n     *\n     *   | 1  0 |\n     *   | 0 -1 |\n     *\n     */\n    if (i==0){\n      *i_op = 0; *j_op = 0;\n      val = 1.0;\n    } else if (i==1) {\n      *i_op = 1; *j_op = 1;\n      val = 1.0;\n    }else if (i==2){\n      *i_op = 1; *j_op = 0;\n      val = 0.0;\n    } else if (i==2) {\n      *i_op = 0; *j_op = 1;\n      val = 0.0;\n    }\n  }\n\n  return val;\n\n}\n\n/*\n * create_circuit initializez the circuit struct. Gates can be added\n * later.\n *\n * Inputs:\n *        circuit circ: circuit to be initialized\n *        PetscIn num_gates_est: an estimate of the number of gates in\n *                               the circuit; can be negative, if no\n *                               estimate is known.\n * Outputs:\n *       operator *new_op: lowering op (op), raising op (op->dag), and number op (op->n)\n */\n\nvoid create_circuit(circuit *circ,PetscInt num_gates_est){\n  (*circ).start_time   = 0.0;\n  (*circ).num_gates    = 0;\n  (*circ).current_gate = 0;\n  /*\n   * If num_gates_est was positive when passed in, use that\n   * as the initial gate_list size, otherwise set to\n   * 100. gate_list will be dynamically resized when needed.\n   */\n  if (num_gates_est>0) {\n    (*circ).gate_list_size = num_gates_est;\n  } else {\n    // Default gate_list_size\n    (*circ).gate_list_size = 100;\n  }\n  // Allocate gate list\n  (*circ).gate_list = malloc((*circ).gate_list_size * sizeof(struct quantum_gate_struct));\n}\n\n/*\n * Add a gate to a circuit.\n * Inputs:\n *        circuit circ: circuit to add to\n *        PetscReal time: time that gate would be applied, counting from 0 at\n *                        the start of the circuit\n *        gate_type my_gate_type: which gate to add\n *        ...:   list of qubit gate will act on, other (U for controlled_U?)\n */\nvoid add_gate_to_circuit(circuit *circ,PetscReal time,gate_type my_gate_type,...){\n  PetscReal theta,phi,lambda;\n  int num_qubits=0,qubit,i;\n  va_list ap;\n\n  if (_gate_array_initialized==0){\n    //Initialize the array of gate function pointers\n    _initialize_gate_function_array();\n    _gate_array_initialized = 1;\n  }\n\n  _check_gate_type(my_gate_type,&num_qubits);\n\n  if ((*circ).num_gates==(*circ).gate_list_size){\n    if (nid==0){\n      printf(\"ERROR! Gate list not large enough!\\n\");\n      exit(1);\n    }\n  }\n  // Store arguments in list\n  (*circ).gate_list[(*circ).num_gates].qubit_numbers = malloc(num_qubits*sizeof(int));\n  (*circ).gate_list[(*circ).num_gates].time = time;\n  (*circ).gate_list[(*circ).num_gates].my_gate_type = my_gate_type;\n  (*circ).gate_list[(*circ).num_gates]._get_val_j_from_global_i = _get_val_j_functions_gates[my_gate_type+_min_gate_enum];\n\n  if (my_gate_type==RX||my_gate_type==RY||my_gate_type==RZ) {\n    va_start(ap,num_qubits+1);\n  } else if (my_gate_type==U3){\n    va_start(ap,num_qubits+3);\n  } else {\n    va_start(ap,num_qubits);\n  }\n\n  // Loop through and store qubits\n  for (i=0;i<num_qubits;i++){\n    qubit = va_arg(ap,int);\n    if (qubit>=num_subsystems) {\n      if (nid==0){\n        // Disable warning because of qasm parser will make the circuit before\n        // the qubits are allocated\n        //printf(\"Warning! Qubit number greater than total systems\\n\");\n      }\n    }\n    (*circ).gate_list[(*circ).num_gates].qubit_numbers[i] = qubit;\n  }\n  if (my_gate_type==RX||my_gate_type==RY||my_gate_type==RZ||my_gate_type==PHASESHIFT){\n    //Get the theta parameter from the last argument passed in\n    theta = va_arg(ap,PetscReal);\n    (*circ).gate_list[(*circ).num_gates].theta = theta;\n    (*circ).gate_list[(*circ).num_gates].phi = 0;\n    (*circ).gate_list[(*circ).num_gates].lambda = 0;\n  } else if (my_gate_type==U3){\n    theta = va_arg(ap,PetscReal);\n    (*circ).gate_list[(*circ).num_gates].theta = theta;\n    phi = va_arg(ap,PetscReal);\n    (*circ).gate_list[(*circ).num_gates].phi = phi;\n    lambda = va_arg(ap,PetscReal);\n    (*circ).gate_list[(*circ).num_gates].lambda = lambda;\n  } else {\n    //Set theta to 0\n    (*circ).gate_list[(*circ).num_gates].theta = 0;\n    (*circ).gate_list[(*circ).num_gates].phi = 0;\n    (*circ).gate_list[(*circ).num_gates].lambda = 0;\n  }\n\n  (*circ).num_gates = (*circ).num_gates + 1;\n  return;\n}\n\n\n/*\n * Add a circuit to another circuit.\n * Assumes whole circuit happens at time\n */\nvoid add_circuit_to_circuit(circuit *circ,circuit circ_to_add,PetscReal time){\n  int num_qubits=0,i,j;\n\n  // Check that we can fit the circuit in\n  if (((*circ).num_gates+circ_to_add.num_gates-1)==(*circ).gate_list_size){\n    if (nid==0){\n      printf(\"ERROR! Gate list not large enough to add this circuit!\\n\");\n      exit(1);\n    }\n  }\n\n  for (i=0;i<circ_to_add.num_gates;i++){\n    // Copy gate information over\n    (*circ).gate_list[(*circ).num_gates].time = time;\n    if (circ_to_add.gate_list[i].my_gate_type<0){\n      num_qubits = 2;\n    } else {\n      num_qubits = 1;\n    }\n    (*circ).gate_list[(*circ).num_gates].qubit_numbers = malloc(num_qubits*sizeof(int));\n    for (j=0;j<num_qubits;j++){\n      (*circ).gate_list[(*circ).num_gates].qubit_numbers[j] = circ_to_add.gate_list[i].qubit_numbers[j];\n    }\n\n    (*circ).gate_list[(*circ).num_gates].my_gate_type = circ_to_add.gate_list[i].my_gate_type;\n    (*circ).gate_list[(*circ).num_gates]._get_val_j_from_global_i = circ_to_add.gate_list[i]._get_val_j_from_global_i;\n    (*circ).gate_list[(*circ).num_gates].theta = circ_to_add.gate_list[i].theta;\n    (*circ).num_gates = (*circ).num_gates + 1;\n  }\n\n\n\n  return;\n}\n\n/* register a circuit to be run a specific time during the time stepping */\nvoid start_circuit_at_time(circuit *circ,PetscReal time){\n  (*circ).start_time = time;\n  _circuit_list[_num_circuits] = *circ;\n  _num_circuits = _num_circuits + 1;\n\n}\n\n/*\n *\n * tensor_control - switch on which superoperator to compute\n *                  -1: I cross G or just G (the difference is controlled by the passed in i's, but\n *                                           the internal logic is exactly the same)\n *                   0: G* cross G\n *                   1: G* cross I\n */\n\nvoid _get_val_j_from_global_i_gates(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js,\n                                    PetscInt js[],PetscScalar vals[],PetscInt tensor_control){\n  operator this_op1,this_op2;\n  PetscInt n_after,i_sub,tmp_int,control,moved_system,my_levels,num_js_i1=0,num_js_i2=0;\n  PetscInt k1,k2,n_before1,n_before2,i_tmp,j_sub,extra_after,i1,i2,j1,js_i1[2],js_i2[2];\n  PetscScalar vals_i1[2],vals_i2[2],theta,phi,lambda;\n  //2 is hardcoded because 2 is the largest number of js from 1 i (HADAMARD)\n  /*\n   * We store our gates as a type and affected systems;\n   * we use the stored information to calculate the global j(s) location\n   * and nonzero value(s) for a give global i\n   *\n   * Fo all 2-qubit gates, we use the fact that\n   * diagonal elements are diagonal, even in global space\n   * and that off-diagonal elements can be worked out from the\n   * following:\n   * Off diagonal elements:\n   *    if (i_sub==1)\n   *       i = 1 * n_af + k1 + k2*n_me*n_af\n   *       j = 0 * n_af + k1 + k2*n_me*n_af\n   *    if (i_sub==0)\n   *       i = 0 * n_af + k1 + k2*n_l*n_af\n   *       j = 1 * n_af + k1 + k2*n_l*n_af\n   * We work out k1 and k2 from i to get j.\n   *\n   */\n  if (tensor_control!= 0) {\n    if (tensor_control==1) {\n      extra_after = total_levels;\n    } else {\n      extra_after = 1;\n    }\n\n    if (gate.my_gate_type > 0) { // Single qubit gates are coded as positive numbers\n\n      //Get the system this is affecting\n      this_op1 = subsystem_list[gate.qubit_numbers[0]];\n      if (this_op1->my_levels!=2) {\n        //Check that it is a two level system\n        if (nid==0){\n          printf(\"ERROR! Single qubit gates can only affect 2-level systems\\n\");\n          exit(0);\n        }\n      }\n      n_after = total_levels/(this_op1->my_levels*this_op1->n_before)*extra_after;\n      i_sub = i/n_after%this_op1->my_levels; //Use integer arithmetic to get floor function\n\n\n      //Branch on the gate types\n      if (gate.my_gate_type == HADAMARD){\n        /*\n         * HADAMARD gate\n         *\n         * 1/sqrt(2) | 1  1 |\n         *           | 1 -1 |\n         * Hadamard gates have two values per row,\n         * with both diagonal anad off diagonal elements\n         *\n         */\n        *num_js = 2;\n        if (i_sub==0) {\n          // Diagonal element\n          js[0]   = i;\n          vals[0] = pow(2,-0.5);\n\n          // Off diagonal element\n          tmp_int = i - 0 * n_after;\n          k2      = tmp_int/(this_op1->my_levels*n_after);//Use integer arithmetic to get floor function\n          k1      = tmp_int%(this_op1->my_levels*n_after);\n          js[1]   = (0 + 1) * n_after + k1 + k2*this_op1->my_levels*n_after;\n          vals[1] = pow(2,-0.5);\n\n        } else if (i_sub==1){\n          // Diagonal element\n          js[0]   = i;\n          vals[0] = -pow(2,-0.5);\n\n          // Off diagonal element\n          tmp_int = i - (0+1) * n_after;\n          k2      = tmp_int/(this_op1->my_levels*n_after);//Use integer arithmetic to get floor function\n          k1      = tmp_int%(this_op1->my_levels*n_after);\n          js[1]   = 0 * n_after + k1 + k2*this_op1->my_levels*n_after;\n          vals[1] = pow(2,-0.5);\n\n        } else {\n          if (nid==0){\n            printf(\"ERROR! Hadamard gate is only defined for qubits\\n\");\n            exit(0);\n          }\n        }\n      } else if (gate.my_gate_type == SIGMAX){\n        /*\n         * SIGMAX gate\n         *\n         *   | 0  1 |\n         *   | 1  0 |\n         *\n         */\n        *num_js = 1;\n        if (i_sub==0) {\n\n          // Off diagonal element\n          tmp_int = i - 0 * n_after;\n          k2      = tmp_int/(this_op1->my_levels*n_after);//Use integer arithmetic to get floor function\n          k1      = tmp_int%(this_op1->my_levels*n_after);\n          js[0]     = (0 + 1) * n_after + k1 + k2*this_op1->my_levels*n_after;\n          vals[0]   = 1.0;\n\n        } else if (i_sub==1){\n\n          // Off diagonal element\n          tmp_int = i - (0+1) * n_after;\n          k2      = tmp_int/(this_op1->my_levels*n_after);//Use integer arithmetic to get floor function\n          k1      = tmp_int%(this_op1->my_levels*n_after);\n          js[0]   = 0 * n_after + k1 + k2*this_op1->my_levels*n_after;\n          vals[0] = 1.0;\n\n        } else {\n          if (nid==0){\n            printf(\"ERROR! sigmax gate is only defined for qubits\\n\");\n            exit(0);\n          }\n        }\n      } else if (gate.my_gate_type == SIGMAY){\n        /*\n         * SIGMAY gate\n         *\n         *   | 0  -1.j |\n         *   | 1.j  0 |\n         *\n         */\n        *num_js = 1;\n        if (i_sub==0) {\n\n          // Off diagonal element\n          tmp_int = i - 0 * n_after;\n          k2      = tmp_int/(this_op1->my_levels*n_after);//Use integer arithmetic to get floor function\n          k1      = tmp_int%(this_op1->my_levels*n_after);\n          js[0]   = (0 + 1) * n_after + k1 + k2*this_op1->my_levels*n_after;\n          vals[0] = -1.0*PETSC_i;\n\n        } else if (i_sub==1){\n\n          // Off diagonal element\n          tmp_int = i - (0+1) * n_after;\n          k2      = tmp_int/(this_op1->my_levels*n_after);//Use integer arithmetic to get floor function\n          k1      = tmp_int%(this_op1->my_levels*n_after);\n          js[0]   = 0 * n_after + k1 + k2*this_op1->my_levels*n_after;\n          vals[0] = 1.0*PETSC_i;\n\n        } else {\n          if (nid==0){\n            printf(\"ERROR! sigmax gate is only defined for qubits\\n\");\n            exit(0);\n          }\n        }\n      } else if (gate.my_gate_type == SIGMAZ){\n        /*\n         * SIGMAZ gate\n         *\n         *   | 1   0 |\n         *   | 0  -1 |\n         *\n         */\n        *num_js = 1;\n        if (i_sub==0) {\n          // Diagonal element\n          js[0] = i;\n          vals[0] = 1.0;\n\n        } else if (i_sub==1){\n          // Diagonal element\n          js[0] = i;\n          vals[0] = -1.0;\n\n        } else {\n          if (nid==0){\n            printf(\"ERROR! sigmax gate is only defined for qubits\\n\");\n            exit(0);\n          }\n        }\n\n      } else if (gate.my_gate_type == EYE){\n          /*\n           * Identity (EYE) gate\n           *\n           *   | 1   0 |\n           *   | 0   1 |\n           *\n           */\n          *num_js = 1;\n          if (i_sub==0) {\n              // Diagonal element\n              js[0] = i;\n              vals[0] = 1.0;\n              \n          } else if (i_sub==1){\n              // Diagonal element\n              js[0] = i;\n              vals[0] = 1.0;\n              \n          } else {\n              if (nid==0){\n                  printf(\"ERROR! sigmax gate is only defined for qubits\\n\");\n                  exit(0);\n              }\n          }\n          \n      } else if (gate.my_gate_type == PHASESHIFT){\n           /*\n           * PHASESHIFT gate\n           *\n           *   | 1   0 |\n           *   | 0  e^(-i*theta) |\n           *\n           */\n          *num_js = 1;\n          theta = gate.theta;\n          if (i_sub==0) {\n              // Diagonal element\n              js[0] = i;\n              vals[0] = 1.0;\n              \n          } else if (i_sub==1){\n              // Diagonal element\n              js[0] = i;\n              vals[0] = PetscExpComplex(-PETSC_i*theta);\n          } else {\n              if (nid==0){\n                  printf(\"ERROR! phaseshift gate is only defined for qubits\\n\");\n                  exit(0);\n              }\n          }\n          \n      } else if (gate.my_gate_type == T){\n          /*\n           * T gate\n           *\n           *   | 1   0 |\n           *   | 0  e^(i*pi/4) |\n           *\n           */\n          *num_js = 1;\n          theta = gate.theta;\n          if (i_sub==0) {\n              // Diagonal element\n              js[0] = i;\n              vals[0] = 1.0;\n              \n          } else if (i_sub==1){\n              // Diagonal element\n              js[0] = i;\n              vals[0] = PetscExpComplex(PETSC_i*PETSC_PI/4);\n          } else {\n              if (nid==0){\n                  printf(\"ERROR! t gate is only defined for qubits\\n\");\n                  exit(0);\n              }\n          }\n          \n      } else if (gate.my_gate_type == TDAG){\n          /*\n           * TDAG gate\n           *\n           *   | 1   0 |\n           *   | 0  e^(-i*pi/4) |\n           *\n           */\n          *num_js = 1;\n          theta = gate.theta;\n          if (i_sub==0) {\n              // Diagonal element\n              js[0] = i;\n              vals[0] = 1.0;\n              \n          } else if (i_sub==1){\n              // Diagonal element\n              js[0] = i;\n              vals[0] = PetscExpComplex(-PETSC_i*PETSC_PI/4);\n          } else {\n              if (nid==0){\n                  printf(\"ERROR! tdag gate is only defined for qubits\\n\");\n                  exit(0);\n              }\n          }\n          \n      } else if (gate.my_gate_type == S){\n          /*\n           * S gate\n           *\n           *   | 1   0 |\n           *   | 0   i |\n           *\n           */\n          *num_js = 1;\n          theta = gate.theta;\n          if (i_sub==0) {\n              // Diagonal element\n              js[0] = i;\n              vals[0] = 1.0;\n              \n          } else if (i_sub==1){\n              // Diagonal element\n              js[0] = i;\n              vals[0] = PetscExpComplex(PETSC_i*PETSC_PI/4);\n          } else {\n              if (nid==0){\n                  printf(\"ERROR! t gate is only defined for qubits\\n\");\n                  exit(0);\n              }\n          }\n          \n      } else if (gate.my_gate_type == RX){\n          /*\n           * RX gate\n           *\n           *   | cos(theta/2)    i*sin(theta/2) |\n           *   | i*sin(theta/2)  cos(theta/2)   |\n           *\n           */\n          theta = gate.theta;\n          *num_js = 2;\n          if (i_sub==0) {\n              // Diagonal element\n              js[0] = i;\n              vals[0] = PetscCosReal(theta/2);\n              \n              // Off diagonal element\n              tmp_int = i - 0 * n_after;\n              k2      = tmp_int/(this_op1->my_levels*n_after);//Use integer arithmetic to get floor function\n              k1      = tmp_int%(this_op1->my_levels*n_after);\n              js[1]     = (0 + 1) * n_after + k1 + k2*this_op1->my_levels*n_after;\n              vals[1]   = PETSC_i * PetscSinReal(theta/2);\n              \n              \n          } else if (i_sub==1){\n              // Diagonal element\n              js[0] = i;\n              vals[0] = PetscCosReal(theta/2);\n              \n              // Off diagonal element\n              tmp_int = i - (0+1) * n_after;\n              k2      = tmp_int/(this_op1->my_levels*n_after);//Use integer arithmetic to get floor function\n              k1      = tmp_int%(this_op1->my_levels*n_after);\n              js[1]   = 0 * n_after + k1 + k2*this_op1->my_levels*n_after;\n              vals[1]   = PETSC_i * PetscSinReal(theta/2);              \n              \n          } else {\n              if (nid==0){\n                  printf(\"ERROR! rz gate is only defined for qubits\\n\");\n                  exit(0);\n              }\n          }\n          \n      } else if (gate.my_gate_type == U3) {\n          /*\n           * u3 gate\n           *\n           * u3(theta,phi,lambda)  = | cos(theta/2)              -e^(i lambda) * sin(theta/2)    |\n           *                         | e^(i phi) sin(theta/2)    e^(i (lambda+phi)) cos(theta/2) |\n           * the u3 gate is a general one qubit transformation.\n           * the u2 gate is u3(pi/2,phi,lambda)\n           * the u1 gate is u3(0,0,lambda)\n           * The u3 gate has two elements per row,\n           * with both diagonal anad off diagonal elements\n           *\n           */\n          theta = gate.theta;\n          phi = gate.phi;\n          lambda = gate.lambda;\n          *num_js = 2;\n          if (i_sub==0) {\n              // Diagonal element\n              js[0]   = i;\n              vals[0] = PetscCosReal(theta/2);\n              \n              // Off diagonal element\n              tmp_int = i - 0 * n_after;\n              k2      = tmp_int/(this_op1->my_levels*n_after);//Use integer arithmetic to get floor function\n              k1      = tmp_int%(this_op1->my_levels*n_after);\n              js[1]   = (0 + 1) * n_after + k1 + k2*this_op1->my_levels*n_after;\n              vals[1] = -PetscExpComplex(PETSC_i*lambda)*PetscSinReal(theta/2);\n              \n          } else if (i_sub==1){\n              // Diagonal element\n              js[0]   = i;\n              vals[0] = PetscExpComplex(PETSC_i*(lambda+phi))*PetscCosReal(theta/2);\n              // Off diagonal element\n              tmp_int = i - (0+1) * n_after;\n              k2      = tmp_int/(this_op1->my_levels*n_after);//Use integer arithmetic to get floor function\n              k1      = tmp_int%(this_op1->my_levels*n_after);\n              js[1]   = 0 * n_after + k1 + k2*this_op1->my_levels*n_after;\n              vals[1] = PetscExpComplex(PETSC_i*phi)*PetscSinReal(theta/2);\n              \n          } else {\n              if (nid==0){\n                  printf(\"ERROR! u3 gate is only defined for qubits\\n\");\n                  exit(0);\n              }\n          }\n      } else {\n\n\n        if (nid==0){\n          printf(\"ERROR! Gate type not understood! %d\\n\", gate.my_gate_type);\n          exit(0);\n        }\n      }\n    } else {\n      //Two qubit gates\n      this_op1 = subsystem_list[gate.qubit_numbers[0]];\n      this_op2 = subsystem_list[gate.qubit_numbers[1]];\n      if (this_op1->my_levels * this_op2->my_levels != 4) {\n        //Check that it is a two level system\n        if (nid==0){\n          printf(\"ERROR! Two qubit gates can only affect two 2-level systems (global_i)\\n\");\n          exit(0);\n        }\n      }\n\n      n_before1  = this_op1->n_before;\n      n_before2  = this_op2->n_before;\n\n      control = 0;\n      moved_system = gate.qubit_numbers[1];\n\n      /* 2 is hardcoded because CNOT gates are for qubits, which have 2 levels */\n      /* 4 is hardcoded because 2 qubits with 2 levels each */\n      n_after   = total_levels/(4*n_before1)*extra_after;\n\n      /*\n       * Check which is the control and which is the target,\n       * flip if need be.\n       */\n      if (n_before2<n_before1) {\n        n_after   = total_levels/(4*n_before2);\n        control   = 1;\n        moved_system = gate.qubit_numbers[0];\n        n_before1 = n_before2;\n      }\n\n      /* 4 is hardcoded because 2 qubits with 2 levels each */\n      my_levels   = 4;\n\n      /*\n       * Permute to temporary basis\n       * Get the i_sub in the permuted basis\n       */\n      i_tmp = i;\n      _change_basis_ij_pair(&i_tmp,&j1,gate.qubit_numbers[control]+1,moved_system); // j1 useless here\n\n      i_sub = i_tmp/n_after%my_levels; //Use integer arithmetic to get floor function\n\n      if (gate.my_gate_type == CNOT) {\n        /* The controlled NOT gate has two inputs, a target and a control.\n         * the target output is equal to the target input if the control is\n         * |0> and is flipped if the control input is |1> (Marinescu 146)\n         * As a matrix, for a two qubit system:\n         *     1 0 0 0        I2 0\n         *     0 1 0 0   =    0  sig_x\n         *     0 0 0 1\n         *     0 0 1 0\n         * Of course, when there are other qubits, tensor products and such\n         * must be applied to get the full basis representation.\n         */\n        *num_js = 1;\n        if (i_sub==0){\n          // Same, regardless of control\n          // Diagonal\n          vals[0] = 1.0;\n          /*\n           * We shouldn't need to deal with any permutation here;\n           * i_sub is in the permuted basis, but we know that a\n           * diagonal element is diagonal in all bases, so\n           * we just use the computational basis value.\n           p         */\n          js[0]  = i;\n\n        } else if (i_sub==1){\n          // Check which is the control bit\n          vals[0] = 1.0;\n          if (control==0){\n            // Diagonal\n            js[0]   = i;\n          } else {\n            // Off diagonal\n            tmp_int = i_tmp - i_sub * n_after;\n            k2      = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function\n            k1      = tmp_int%(my_levels*n_after);\n            j_sub   = 3;\n            j1   = (j_sub) * n_after + k1 + k2*my_levels*n_after; // 3 = j_sub\n\n            /* Permute back to computational basis */\n            _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here\n            js[0] = j1;\n          }\n\n        } else if (i_sub==2){\n          vals[0] = 1.0;\n          if (control==0){\n            // Off diagonal\n            tmp_int = i_tmp - i_sub * n_after;\n            k2      = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function\n            k1      = tmp_int%(my_levels*n_after);\n            j_sub   = 3;\n            j1     = j_sub * n_after + k1 + k2*my_levels*n_after;\n\n            /* Permute back to computational basis */\n            _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here\n            js[0] = j1;\n          } else {\n            // Diagonal\n            js[0]   = i;\n          }\n        } else if (i_sub==3){\n          vals[0]   = 1.0;\n          if (control==0){\n            // Off diagonal element\n            tmp_int = i_tmp - i_sub * n_after;\n            k2      = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function\n            k1      = tmp_int%(my_levels*n_after);\n            j_sub   = 2;\n            j1     = j_sub * n_after + k1 + k2*my_levels*n_after;\n          } else {\n            // Off diagonal element\n            tmp_int = i_tmp - i_sub * n_after;\n            k2      = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function\n            k1      = tmp_int%(my_levels*n_after);\n            j_sub   = 1;\n            j1     = j_sub * n_after + k1 + k2*my_levels*n_after;\n          }\n          /* Permute back to computational basis */\n          _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1);//i_tmp useless here\n          js[0] = j1;\n        } else {\n          if (nid==0){\n            printf(\"ERROR! CNOT gate is only defined for 2 qubits!\\n\");\n            exit(0);\n          }\n        }\n      } else if (gate.my_gate_type == CXZ) {\n        /* The controlled-XZ gate has two inputs, a target and a control.\n         * As a matrix, for a two qubit system\n         *     1 0 0 0        I2 0\n         *     0 1 0 0   =    0  sig_x * sig_z\n         *     0 0 0 -1\n         *     0 0 1 0\n         * Of course, when there are other qubits, tensor products and such\n         * must be applied to get the full basis representation.\n         *\n         * Note that this is a temporary gate; i.e., we will create a more\n         * general controlled-U gate at a later time that will replace this.\n         */\n        *num_js = 1;\n        if (i_sub==0){\n          // Same, regardless of control\n          // Diagonal\n          vals[0] = 1.0;\n          /*\n           * We shouldn't need to deal with any permutation here;\n           * i_sub is in the permuted basis, but we know that a\n           * diagonal element is diagonal in all bases, so\n           * we just use the computational basis value.\n           p         */\n          js[0]  = i;\n\n        } else if (i_sub==1){\n          // Check which is the control bit\n          if (control==0){\n            // Diagonal\n            vals[0] = 1.0;\n            js[0]   = i;\n          } else {\n            // Off diagonal\n            vals[0] = -1.0;\n            tmp_int = i_tmp - i_sub * n_after;\n            k2      = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function\n            k1      = tmp_int%(my_levels*n_after);\n            j_sub   = 3;\n            j1   = (j_sub) * n_after + k1 + k2*my_levels*n_after; // 3 = j_sub\n\n            /* Permute back to computational basis */\n            _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here\n            js[0] = j1;\n          }\n\n        } else if (i_sub==2){\n          if (control==0){\n            vals[0] = -1.0;\n            // Off diagonal\n            tmp_int = i_tmp - i_sub * n_after;\n            k2      = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function\n            k1      = tmp_int%(my_levels*n_after);\n            j_sub   = 3;\n            j1     = j_sub * n_after + k1 + k2*my_levels*n_after;\n\n            /* Permute back to computational basis */\n            _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here\n            js[0] = j1;\n          } else {\n            // Diagonal\n            vals[0] = 1.0;\n            js[0]   = i;\n          }\n        } else if (i_sub==3){\n          vals[0]   = 1.0;\n          if (control==0){\n            // Off diagonal element\n            tmp_int = i_tmp - i_sub * n_after;\n            k2      = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function\n            k1      = tmp_int%(my_levels*n_after);\n            j_sub   = 2;\n            j1     = j_sub * n_after + k1 + k2*my_levels*n_after;\n          } else {\n            // Off diagonal element\n            tmp_int = i_tmp - i_sub * n_after;\n            k2      = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function\n            k1      = tmp_int%(my_levels*n_after);\n            j_sub   = 1;\n            j1     = j_sub * n_after + k1 + k2*my_levels*n_after;\n          }\n          /* Permute back to computational basis */\n          _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1);//i_tmp useless here\n          js[0] = j1;\n        } else {\n          if (nid==0){\n            printf(\"ERROR! CXZ gate is only defined for 2 qubits!\\n\");\n            exit(0);\n          }\n        }\n      } else if (gate.my_gate_type == CZX) {\n        /* The controlled-ZX gate has two inputs, a target and a control.\n         * As a matrix, for a two qubit system\n         *     1 0 0 0        I2 0\n         *     0 1 0 0   =    0  sig_z * sig_x\n         *     0 0 0 1\n         *     0 0 -1 0\n         * Of course, when there are other qubits, tensor products and such\n         * must be applied to get the full basis representation.\n         *\n         * Note that this is a temporary gate; i.e., we will create a more\n         * general controlled-U gate at a later time that will replace this.\n         */\n        *num_js = 1;\n        if (i_sub==0){\n          // Same, regardless of control\n          // Diagonal\n          vals[0] = 1.0;\n          /*\n           * We shouldn't need to deal with any permutation here;\n           * i_sub is in the permuted basis, but we know that a\n           * diagonal element is diagonal in all bases, so\n           * we just use the computational basis value.\n           p         */\n          js[0]  = i;\n\n        } else if (i_sub==1){\n          // Check which is the control bit\n          vals[0] = 1.0;\n          if (control==0){\n            // Diagonal\n            js[0]   = i;\n          } else {\n            // Off diagonal\n            tmp_int = i_tmp - i_sub * n_after;\n            k2      = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function\n            k1      = tmp_int%(my_levels*n_after);\n            j_sub   = 3;\n            j1   = (j_sub) * n_after + k1 + k2*my_levels*n_after; // 3 = j_sub\n\n            /* Permute back to computational basis */\n            _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here\n            js[0] = j1;\n          }\n\n        } else if (i_sub==2){\n          vals[0] = 1.0;\n          if (control==0){\n            // Off diagonal\n            tmp_int = i_tmp - i_sub * n_after;\n            k2      = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function\n            k1      = tmp_int%(my_levels*n_after);\n            j_sub   = 3;\n            j1     = j_sub * n_after + k1 + k2*my_levels*n_after;\n\n            /* Permute back to computational basis */\n            _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here\n            js[0] = j1;\n          } else {\n            // Diagonal\n            js[0]   = i;\n          }\n        } else if (i_sub==3){\n          vals[0]   = -1.0;\n          if (control==0){\n            // Off diagonal element\n            tmp_int = i_tmp - i_sub * n_after;\n            k2      = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function\n            k1      = tmp_int%(my_levels*n_after);\n            j_sub   = 2;\n            j1     = j_sub * n_after + k1 + k2*my_levels*n_after;\n          } else {\n            // Off diagonal element\n            tmp_int = i_tmp - i_sub * n_after;\n            k2      = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function\n            k1      = tmp_int%(my_levels*n_after);\n            j_sub   = 1;\n            j1     = j_sub * n_after + k1 + k2*my_levels*n_after;\n          }\n          /* Permute back to computational basis */\n          _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1);//i_tmp useless here\n          js[0] = j1;\n        } else {\n          if (nid==0){\n            printf(\"ERROR! CZX gate is only defined for 2 qubits!\\n\");\n            exit(0);\n          }\n        }\n      } else if (gate.my_gate_type == CZ) {\n        /* The controlled-Z gate has two inputs, a target and a control.\n         * As a matrix, for a two qubit system\n         *     1 0 0 0        I2 0\n         *     0 1 0 0   =    0  sig_z\n         *     0 0 1 0\n         *     0 0 0 -1\n         * Of course, when there are other qubits, tensor products and such\n         * must be applied to get the full basis representation.\n         *\n         * Note that this is a temporary gate; i.e., we will create a more\n         * general controlled-U gate at a later time that will replace\n         *\n         * Controlled-z is the same for both possible controls\n         */\n        *num_js = 1;\n        if (i_sub==0){\n          // Same, regardless of control\n          // Diagonal\n          vals[0] = 1.0;\n          /*\n           * We shouldn't need to deal with any permutation here;\n           * i_sub is in the permuted basis, but we know that a\n           * diagonal element is diagonal in all bases, so\n           * we just use the computational basis value.\n           p         */\n          js[0]  = i;\n\n        } else if (i_sub==1){\n          // Diagonal\n          vals[0] = 1.0;\n          js[0]   = i;\n        } else if (i_sub==2){\n          // Diagonal\n          vals[0] = 1.0;\n          js[0]   = i;\n        } else if (i_sub==3){\n          vals[0] = -1.0;\n          js[0]   = i;\n        } else {\n          if (nid==0){\n            printf(\"ERROR! CZ gate is only defined for 2 qubits!\\n\");\n            exit(0);\n          }\n        }\n      } else if (gate.my_gate_type == CmZ) {\n        /* The controlled-mZ gate has two inputs, a target and a control.\n         * As a matrix, for a two qubit system\n         *     1 0 0 0        I2 0\n         *     0 1 0 0   =    0  -sig_z\n         *     0 0 -1 0\n         *     0 0 0 1\n         * Of course, when there are other qubits, tensor products and such\n         * must be applied to get the full basis representation.\n         *\n         * Note that this is a temporary gate; i.e., we will create a more\n         * general controlled-U gate at a later time that will replace\n         *\n         */\n        *num_js = 1;\n        if (i_sub==0){\n          // Same, regardless of control\n          // Diagonal\n          vals[0] = 1.0;\n          /*\n           * We shouldn't need to deal with any permutation here;\n           * i_sub is in the permuted basis, but we know that a\n           * diagonal element is diagonal in all bases, so\n           * we just use the computational basis value.\n           p         */\n          js[0]  = i;\n\n        } else if (i_sub==1){\n          // Diagonal\n          js[0]   = i;\n          if (control==0) {\n            vals[0] = 1.0;\n          } else {\n            vals[0] = -1.0;\n          }\n        } else if (i_sub==2){\n          // Diagonal\n          js[0]   = i;\n          if (control==0) {\n            vals[0] = -1.0;\n          } else {\n            vals[0] = 1.0;\n          }\n        } else if (i_sub==3){\n          vals[0] = 1.0;\n          js[0]   = i;\n        } else {\n          if (nid==0){\n            printf(\"ERROR! CmZ gate is only defined for 2 qubits!\\n\");\n            exit(0);\n          }\n        }\n      } else if (gate.my_gate_type == SWAP) {\n          /* The swap gate swaps two qubits.\n           * As a matrix, for a two qubit system\n           *     1 0 0 0        I2 0\n           *     0 0 1 0   =    0  sig_z * sig_x\n           *     0 1 0 0\n           *     0 0 0 1\n           */\n          *num_js = 1;\n          if (i_sub==0){\n              // Same, regardless of control\n              // Diagonal\n              vals[0] = 1.0;\n              /*\n               * We shouldn't need to deal with any permutation here;\n               * i_sub is in the permuted basis, but we know that a\n               * diagonal element is diagonal in all bases, so\n               * we just use the computational basis value.\n               p         */\n              js[0]  = i;\n              \n          } else if (i_sub==1){\n              // Check which is the control bit\n              vals[0] = 1.0;\n                  // Off diagonal\n                  tmp_int = i_tmp - i_sub * n_after;\n                  k2      = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function\n                  k1      = tmp_int%(my_levels*n_after);\n                  j_sub   = 3;\n                  j1   = (j_sub) * n_after + k1 + k2*my_levels*n_after; // 3 = j_sub\n                  \n                  /* Permute back to computational basis */\n                  _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here\n                  js[0] = j1;\n              \n          } else if (i_sub==2){\n              vals[0] = 1.0;\n                  // Off diagonal\n                  tmp_int = i_tmp - i_sub * n_after;\n                  k2      = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function\n                  k1      = tmp_int%(my_levels*n_after);\n                  j_sub   = 3;\n                  j1     = j_sub * n_after + k1 + k2*my_levels*n_after;\n                  \n                  /* Permute back to computational basis */\n                  _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here\n                  js[0] = j1;\n          } else if (i_sub==3){\n              vals[0]   = 1.0;\n                  // Off diagonal element\n                  tmp_int = i_tmp - i_sub * n_after;\n                  k2      = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function\n                  k1      = tmp_int%(my_levels*n_after);\n                  j_sub   = 1;\n                  j1     = j_sub * n_after + k1 + k2*my_levels*n_after;\n              /* Permute back to computational basis */\n              _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1);//i_tmp useless here\n              js[0] = j1;\n          } else {\n              if (nid==0){\n                  printf(\"ERROR! SWAP gate is only defined for 2 qubits!\\n\");\n                  exit(0);\n              }\n          }\n      } else {\n        if (nid==0){\n          printf(\"ERROR!Two Qubit gate type not understood! %d\\n\",gate.my_gate_type);\n          exit(0);\n        }\n      }\n    }\n    if (tensor_control==1){\n      //Take complex conjugate of answer to get U* cross I\n      for (i=0;i<*num_js;i++){\n        vals[i] = PetscConjComplex(vals[i]);\n      }\n    }\n  } else {\n    /*\n     * U* cross U\n     * To calculate this, we first take our i_global, convert\n     * it to i1 (for U*) and i2 (for U) within their own\n     * part of the Hilbert space. pWe then treat i1 and i2 as\n     * global i's for the matrices U* and U themselves, which\n     * gives us j's for those matrices. We then expand the j's\n     * to get the full space representation, using the normal\n     * tensor product.\n     */\n\n    /* Calculate i1, i2 */\n    i1 = i/total_levels;\n    i2 = i%total_levels;\n\n    /* Now, get js for U* (i1) by calling this function */\n    _get_val_j_from_global_i_gates(i1,gate,&num_js_i1,js_i1,vals_i1,-1);\n\n    /* Now, get js for U (i2) by calling this function */\n    _get_val_j_from_global_i_gates(i2,gate,&num_js_i2,js_i2,vals_i2,-1);\n\n    /*\n     * Combine j's to get U* cross U\n     * Must do all possible permutations\n     */\n    *num_js = 0;\n    for(k1=0;k1<num_js_i1;k1++){\n      for(k2=0;k2<num_js_i2;k2++){\n        js[*num_js] = total_levels * js_i1[k1] + js_i2[k2];\n        //Need to take complex conjugate to get true U*\n        vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2];\n\n        *num_js = *num_js + 1;\n      }\n    }\n  }\n  return;\n}\n\n\nvoid combine_circuit_to_mat2(Mat *matrix_out,circuit circ){\n  PetscScalar op_val,op_vals[total_levels],vals[2]={0};\n  PetscInt Istart,Iend;\n  PetscInt i,j,k,l,this_i,these_js[total_levels],js[2]={0},num_js_tmp=0,num_js,num_js_current;\n\n  // Should this inherit its stucture from full_A?\n  MatCreate(PETSC_COMM_WORLD,matrix_out);\n  MatSetType(*matrix_out,MATMPIAIJ);\n  MatSetSizes(*matrix_out,PETSC_DECIDE,PETSC_DECIDE,total_levels,total_levels);\n  MatSetFromOptions(*matrix_out);\n\n  MatMPIAIJSetPreallocation(*matrix_out,16,NULL,16,NULL);\n\n  /*\n   * Calculate G1*G2*G3*.. using the following observation:\n   *     Each gate is very sparse - having no more than\n   *          2 values per row. This allows us to efficiently do the\n   *          multiplication by just touching the nonzero values\n   */\n  MatGetOwnershipRange(*matrix_out,&Istart,&Iend);\n  for (i=Istart;i<Iend;i++){\n    this_i = i; // The leading index which we check\n    // Reset the result for the row\n    num_js = 1;\n    these_js[0] = i;\n    op_vals[0]  = 1.0;\n    for (j=0;j<circ.num_gates;j++){\n      num_js_current = num_js;\n      for (k=0;k<num_js_current;k++){\n        // Loop through all of the js from the previous gate multiplications\n        this_i = these_js[k];\n        op_val = op_vals[k];\n\n        _get_val_j_from_global_i_gates(this_i,circ.gate_list[j],&num_js_tmp,js,vals,-1); // Get the corresponding j and val\n        /*\n         * Assume there is always at least 1 nonzero per row. This is a good assumption\n         * because all basic quantum gates have at least 1 nonzero per row\n         */\n        // WARNING! CODE NOT FINISHED\n        // WILL NOT WORK FOR HADAMARD * HADAMARD\n\n        these_js[k] = js[0];\n        op_vals[k]  = op_val*vals[0];\n\n        for (l=1;l<num_js_tmp;l++){\n          //If we have more than 1 num_js_tmp, we append to the end of the list\n          these_js[num_js+l-1] = js[l];\n          op_vals[num_js+l-1]  = op_val*vals[l];\n        }\n         num_js = num_js + num_js_tmp - 1; //If we spawned an extra j, add it here\n      }\n    }\n    MatSetValues(*matrix_out,1,&i,num_js,these_js,op_vals,ADD_VALUES);\n  }\n\n  MatAssemblyBegin(*matrix_out,MAT_FINAL_ASSEMBLY);\n  MatAssemblyEnd(*matrix_out,MAT_FINAL_ASSEMBLY);\n\n  return;\n}\n\n\nvoid combine_circuit_to_mat(Mat *matrix_out,circuit circ){\n  PetscScalar op_vals[2];\n  PetscInt Istart,Iend,i_mat;\n  PetscInt i,these_js[2],num_js;\n  Mat tmp_mat1,tmp_mat2,tmp_mat3;\n\n  // Should this inherit its stucture from full_A?\n\n  MatCreate(PETSC_COMM_WORLD,&tmp_mat1);\n  MatSetType(tmp_mat1,MATMPIAIJ);\n  MatSetSizes(tmp_mat1,PETSC_DECIDE,PETSC_DECIDE,total_levels,total_levels);\n  MatSetFromOptions(tmp_mat1);\n\n  MatMPIAIJSetPreallocation(tmp_mat1,2,NULL,2,NULL);\n\n  /* Construct the first matrix in tmp_mat1 */\n  MatGetOwnershipRange(tmp_mat1,&Istart,&Iend);\n  for (i=Istart;i<Iend;i++){\n    circ.gate_list[0]._get_val_j_from_global_i(i,circ.gate_list[0],&num_js,these_js,op_vals,-1); // Get the corresponding j and val\n    MatSetValues(tmp_mat1,1,&i,num_js,these_js,op_vals,ADD_VALUES);\n  }\n\n  MatAssemblyBegin(tmp_mat1,MAT_FINAL_ASSEMBLY);\n  MatAssemblyEnd(tmp_mat1,MAT_FINAL_ASSEMBLY);\n\n  for (i_mat=1;i_mat<circ.num_gates;i_mat++){\n    // Create the next matrix\n    MatCreate(PETSC_COMM_WORLD,&tmp_mat2);\n    MatSetType(tmp_mat2,MATMPIAIJ);\n    MatSetSizes(tmp_mat2,PETSC_DECIDE,PETSC_DECIDE,total_levels,total_levels);\n    MatSetFromOptions(tmp_mat2);\n\n    MatMPIAIJSetPreallocation(tmp_mat2,2,NULL,2,NULL);\n\n    /* Construct new matrix */\n    MatGetOwnershipRange(tmp_mat2,&Istart,&Iend);\n    for (i=Istart;i<Iend;i++){\n      _get_val_j_from_global_i_gates(i,circ.gate_list[i_mat],&num_js,these_js,op_vals,-1); // Get the corresponding j and val\n      MatSetValues(tmp_mat2,1,&i,num_js,these_js,op_vals,ADD_VALUES);\n    }\n\n    MatAssemblyBegin(tmp_mat2,MAT_FINAL_ASSEMBLY);\n    MatAssemblyEnd(tmp_mat2,MAT_FINAL_ASSEMBLY);\n\n    // Now do matrix matrix multiply\n    MatMatMult(tmp_mat2,tmp_mat1,MAT_INITIAL_MATRIX,PETSC_DEFAULT,&tmp_mat3);\n    MatDestroy(&tmp_mat1);\n    MatDestroy(&tmp_mat2); //Do I need to destroy it?\n\n    //Store tmp_mat3 into tmp_mat1\n    MatConvert(tmp_mat3,MATSAME,MAT_INITIAL_MATRIX,&tmp_mat1);\n    MatDestroy(&tmp_mat3);\n  }\n\n  //Copy tmp_mat1 into *matrix_out\n  MatConvert(tmp_mat1,MATSAME,MAT_INITIAL_MATRIX,matrix_out);;\n\n  MatDestroy(&tmp_mat1);\n  return;\n}\n\n\nvoid combine_circuit_to_super_mat(Mat *matrix_out,circuit circ){\n  PetscScalar op_vals[4];\n  PetscInt Istart,Iend,i_mat,dim;\n  PetscInt i,these_js[4],num_js;\n  Mat tmp_mat1,tmp_mat2,tmp_mat3;\n\n  // Should this inherit its stucture from full_A?\n  dim = total_levels*total_levels;\n  MatCreate(PETSC_COMM_WORLD,&tmp_mat1);\n  MatSetType(tmp_mat1,MATMPIAIJ);\n  MatSetSizes(tmp_mat1,PETSC_DECIDE,PETSC_DECIDE,dim,dim);\n  MatSetFromOptions(tmp_mat1);\n\n  MatMPIAIJSetPreallocation(tmp_mat1,8,NULL,8,NULL);\n\n  /* Construct the first matrix in tmp_mat1 */\n  MatGetOwnershipRange(tmp_mat1,&Istart,&Iend);\n  for (i=Istart;i<Iend;i++){\n    _get_val_j_from_global_i_gates(i,circ.gate_list[0],&num_js,these_js,op_vals,0); // Get the corresponding j and val\n    MatSetValues(tmp_mat1,1,&i,num_js,these_js,op_vals,ADD_VALUES);\n  }\n\n  MatAssemblyBegin(tmp_mat1,MAT_FINAL_ASSEMBLY);\n  MatAssemblyEnd(tmp_mat1,MAT_FINAL_ASSEMBLY);\n\n  for (i_mat=1;i_mat<circ.num_gates;i_mat++){\n    // Create the next matrix\n    MatCreate(PETSC_COMM_WORLD,&tmp_mat2);\n    MatSetType(tmp_mat2,MATMPIAIJ);\n    MatSetSizes(tmp_mat2,PETSC_DECIDE,PETSC_DECIDE,dim,dim);\n    MatSetFromOptions(tmp_mat2);\n\n    MatMPIAIJSetPreallocation(tmp_mat2,8,NULL,8,NULL);\n\n    /* Construct new matrix */\n    MatGetOwnershipRange(tmp_mat2,&Istart,&Iend);\n    for (i=Istart;i<Iend;i++){\n      _get_val_j_from_global_i_gates(i,circ.gate_list[i_mat],&num_js,these_js,op_vals,0); // Get the corresponding j and val\n      MatSetValues(tmp_mat2,1,&i,num_js,these_js,op_vals,ADD_VALUES);\n    }\n\n    MatAssemblyBegin(tmp_mat2,MAT_FINAL_ASSEMBLY);\n    MatAssemblyEnd(tmp_mat2,MAT_FINAL_ASSEMBLY);\n\n    // Now do matrix matrix multiply\n    MatMatMult(tmp_mat2,tmp_mat1,MAT_INITIAL_MATRIX,PETSC_DEFAULT,&tmp_mat3);\n    MatDestroy(&tmp_mat1);\n    MatDestroy(&tmp_mat2); //Do I need to destroy it?\n\n    //Store tmp_mat3 into tmp_mat1\n    MatConvert(tmp_mat3,MATSAME,MAT_INITIAL_MATRIX,&tmp_mat1);\n    MatDestroy(&tmp_mat3);\n  }\n\n  //Copy tmp_mat1 into *matrix_out\n  MatConvert(tmp_mat1,MATSAME,MAT_INITIAL_MATRIX,matrix_out);;\n\n  MatDestroy(&tmp_mat1);\n  return;\n}\n\n\n/*\n * No issue for js_i* = -1 because every row is guaranteed to have a 0\n * in all the gates implemented below.\n * See commit: 9956c78171fdac1fa0ef9e2f0a39cbffd4d755dc where this was an issue\n * in _get_val_j_from_global_i for raising / lowering / number operators, where\n * -1 was used to say there was no nonzero in that row.\n */\n\n\nvoid CNOT_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js,\n                                  PetscInt js[],PetscScalar vals[],PetscInt tensor_control){\n  PetscInt n_after,i_sub,k1,k2,tmp_int,i1,i2,num_js_i1=0,num_js_i2=0,js_i1[2],js_i2[2];\n  PetscInt control,i_tmp,my_levels,j_sub,moved_system,j1;\n  PetscScalar vals_i1[2],vals_i2[2];\n\n  /* The controlled NOT gate has two inputs, a target and a control.\n   * the target output is equal to the target input if the control is\n   * |0> and is flipped if the control input is |1> (Marinescu 146)\n   * As a matrix, for a two qubit system:\n   *     1 0 0 0        I2 0\n   *     0 1 0 0   =    0  sig_x\n   *     0 0 0 1\n   *     0 0 1 0\n   * Of course, when there are other qubits, tensor products and such\n   * must be applied to get the full basis representation.\n   */\n\n  if (tensor_control!= 0) {\n\n    /* 4 is hardcoded because 2 qubits with 2 levels each */\n    my_levels   = 4;\n    // Get the correct hilbert space information\n    i_tmp = i;\n    _get_n_after_2qbit(&i_tmp,gate.qubit_numbers,tensor_control,&n_after,&control,&moved_system,&i_sub);\n\n    *num_js = 1;\n    if (i_sub==0){\n      // Same, regardless of control\n      // Diagonal\n      vals[0] = 1.0;\n      /*\n       * We shouldn't need to deal with any permutation here;\n       * i_sub is in the permuted basis, but we know that a\n       * diagonal element is diagonal in all bases, so\n       * we just use the computational basis value.\n       p         */\n      js[0]  = i;\n\n    } else if (i_sub==1){\n      // Check which is the control bit\n      vals[0] = 1.0;\n      if (control==0){\n        // Diagonal\n        js[0]   = i;\n      } else {\n        // Off diagonal\n        tmp_int = i_tmp - i_sub * n_after;\n        k2      = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function\n        k1      = tmp_int%(my_levels*n_after);\n        j_sub   = 3;\n        j1   = (j_sub) * n_after + k1 + k2*my_levels*n_after; // 3 = j_sub\n\n        /* Permute back to computational basis */\n        _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here\n        js[0] = j1;\n      }\n\n    } else if (i_sub==2){\n      vals[0] = 1.0;\n      if (control==0){\n        // Off diagonal\n        tmp_int = i_tmp - i_sub * n_after;\n        k2      = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function\n        k1      = tmp_int%(my_levels*n_after);\n        j_sub   = 3;\n        j1     = j_sub * n_after + k1 + k2*my_levels*n_after;\n        /* Permute back to computational basis */\n        _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here\n        js[0] = j1;\n      } else {\n        // Diagonal\n        js[0]   = i;\n      }\n    } else if (i_sub==3){\n      vals[0]   = 1.0;\n      if (control==0){\n        // Off diagonal element\n        tmp_int = i_tmp - i_sub * n_after;\n        k2      = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function\n        k1      = tmp_int%(my_levels*n_after);\n        j_sub   = 2;\n        j1     = j_sub * n_after + k1 + k2*my_levels*n_after;\n      } else {\n        // Off diagonal element\n        tmp_int = i_tmp - i_sub * n_after;\n        k2      = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function\n        k1      = tmp_int%(my_levels*n_after);\n        j_sub   = 1;\n        j1     = j_sub * n_after + k1 + k2*my_levels*n_after;\n      }\n      /* Permute back to computational basis */\n      _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1);//i_tmp useless here\n      js[0] = j1;\n    } else {\n      if (nid==0){\n        printf(\"ERROR! CNOT gate is only defined for 2 qubits!\\n\");\n        exit(0);\n      }\n    }\n  } else {\n    /*\n     * U* cross U\n     * To calculate this, we first take our i_global, convert\n     * it to i1 (for U*) and i2 (for U) within their own\n     * part of the Hilbert space. pWe then treat i1 and i2 as\n     * global i's for the matrices U* and U themselves, which\n     * gives us j's for those matrices. We then expand the j's\n     * to get the full space representation, using the normal\n     * tensor product.\n     */\n\n    /* Calculate i1, i2 */\n    i1 = i/total_levels;\n    i2 = i%total_levels;\n\n    /* Now, get js for U* (i1) by calling this function */\n    CNOT_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1);\n\n    /* Now, get js for U (i2) by calling this function */\n    CNOT_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1);\n\n    /*\n     * Combine j's to get U* cross U\n     * Must do all possible permutations\n     */\n    *num_js = 0;\n    for(k1=0;k1<num_js_i1;k1++){\n      for(k2=0;k2<num_js_i2;k2++){\n        js[*num_js] = total_levels * js_i1[k1] + js_i2[k2];\n        //Need to take complex conjugate to get true U*\n        vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2];\n\n        *num_js = *num_js + 1;\n      }\n    }\n\n  }\n\n  return;\n}\n\n\nvoid CXZ_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js,\n                                  PetscInt js[],PetscScalar vals[],PetscInt tensor_control){\n  PetscInt n_after,i_sub,k1,k2,tmp_int,i1,i2,num_js_i1=0,num_js_i2=0,js_i1[2],js_i2[2];\n  PetscInt control,i_tmp,my_levels,j_sub,moved_system,j1;\n  PetscScalar vals_i1[2],vals_i2[2];\n\n  /* The controlled-XZ gate has two inputs, a target and a control.\n   * As a matrix, for a two qubit system\n   *     1 0 0 0        I2 0\n   *     0 1 0 0   =    0  sig_x * sig_z\n   *     0 0 0 -1\n   *     0 0 1 0\n   * Of course, when there are other qubits, tensor products and such\n   * must be applied to get the full basis representation.\n   *\n   * Note that this is a temporary gate; i.e., we will create a more\n   * general controlled-U gate at a later time that will replace this.\n   */\n\n  if (tensor_control!= 0) {\n\n    /* 4 is hardcoded because 2 qubits with 2 levels each */\n    my_levels   = 4;\n    // Get the correct hilbert space information\n    i_tmp = i;\n    _get_n_after_2qbit(&i_tmp,gate.qubit_numbers,tensor_control,&n_after,&control,&moved_system,&i_sub);\n    *num_js = 1;\n    if (i_sub==0){\n      // Same, regardless of control\n      // Diagonal\n      vals[0] = 1.0;\n      /*\n       * We shouldn't need to deal with any permutation here;\n       * i_sub is in the permuted basis, but we know that a\n       * diagonal element is diagonal in all bases, so\n       * we just use the computational basis value.\n       p         */\n      js[0]  = i;\n\n    } else if (i_sub==1){\n      // Check which is the control bit\n      if (control==0){\n        // Diagonal\n        vals[0] = 1.0;\n        js[0]   = i;\n      } else {\n        // Off diagonal\n        vals[0] = -1.0;\n        tmp_int = i_tmp - i_sub * n_after;\n        k2      = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function\n        k1      = tmp_int%(my_levels*n_after);\n        j_sub   = 3;\n        j1   = (j_sub) * n_after + k1 + k2*my_levels*n_after; // 3 = j_sub\n\n        /* Permute back to computational basis */\n        _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here\n        js[0] = j1;\n      }\n\n    } else if (i_sub==2){\n      if (control==0){\n        vals[0] = -1.0;\n        // Off diagonal\n        tmp_int = i_tmp - i_sub * n_after;\n        k2      = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function\n        k1      = tmp_int%(my_levels*n_after);\n        j_sub   = 3;\n        j1     = j_sub * n_after + k1 + k2*my_levels*n_after;\n\n        /* Permute back to computational basis */\n        _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here\n        js[0] = j1;\n      } else {\n        // Diagonal\n        vals[0] = 1.0;\n        js[0]   = i;\n      }\n    } else if (i_sub==3){\n      vals[0]   = 1.0;\n      if (control==0){\n        // Off diagonal element\n        tmp_int = i_tmp - i_sub * n_after;\n        k2      = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function\n        k1      = tmp_int%(my_levels*n_after);\n        j_sub   = 2;\n        j1     = j_sub * n_after + k1 + k2*my_levels*n_after;\n      } else {\n        // Off diagonal element\n        tmp_int = i_tmp - i_sub * n_after;\n        k2      = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function\n        k1      = tmp_int%(my_levels*n_after);\n        j_sub   = 1;\n        j1     = j_sub * n_after + k1 + k2*my_levels*n_after;\n      }\n      /* Permute back to computational basis */\n      _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1);//i_tmp useless here\n      js[0] = j1;\n    } else {\n      if (nid==0){\n        printf(\"ERROR! CXZ gate is only defined for 2 qubits!\\n\");\n        exit(0);\n      }\n    }\n  } else {\n        /*\n     * U* cross U\n     * To calculate this, we first take our i_global, convert\n     * it to i1 (for U*) and i2 (for U) within their own\n     * part of the Hilbert space. pWe then treat i1 and i2 as\n     * global i's for the matrices U* and U themselves, which\n     * gives us j's for those matrices. We then expand the j's\n     * to get the full space representation, using the normal\n     * tensor product.\n     */\n\n    /* Calculate i1, i2 */\n    i1 = i/total_levels;\n    i2 = i%total_levels;\n\n    /* Now, get js for U* (i1) by calling this function */\n    CXZ_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1);\n\n    /* Now, get js for U (i2) by calling this function */\n    CXZ_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1);\n\n    /*\n     * Combine j's to get U* cross U\n     * Must do all possible permutations\n     */\n    *num_js = 0;\n    for(k1=0;k1<num_js_i1;k1++){\n      for(k2=0;k2<num_js_i2;k2++){\n        js[*num_js] = total_levels * js_i1[k1] + js_i2[k2];\n        //Need to take complex conjugate to get true U*\n        vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2];\n\n        *num_js = *num_js + 1;\n      }\n    }\n\n  }\n\n  return;\n}\n\nvoid CZ_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js,\n                                  PetscInt js[],PetscScalar vals[],PetscInt tensor_control){\n  PetscInt n_after,i_sub,k1,k2,i1,i2,num_js_i1=0,num_js_i2=0,js_i1[2],js_i2[2];\n  PetscInt control,i_tmp,my_levels,moved_system;\n  PetscScalar vals_i1[2],vals_i2[2];\n\n  /* The controlled-Z gate has two inputs, a target and a control.\n   * As a matrix, for a two qubit system\n   *     1 0 0 0        I2 0\n   *     0 1 0 0   =    0  sig_z\n   *     0 0 1 0\n   *     0 0 0 -1\n   * Of course, when there are other qubits, tensor products and such\n   * must be applied to get the full basis representation.\n   *\n   * Note that this is a temporary gate; i.e., we will create a more\n   * general controlled-U gate at a later time that will replace\n   *\n   * Controlled-z is the same for both possible controls\n   */\n\n  if (tensor_control!= 0) {\n\n    /* 4 is hardcoded because 2 qubits with 2 levels each */\n    my_levels   = 4;\n    // Get the correct hilbert space information\n    i_tmp = i;\n    _get_n_after_2qbit(&i_tmp,gate.qubit_numbers,tensor_control,&n_after,&control,&moved_system,&i_sub);\n    *num_js = 1;\n    if (i_sub==0){\n      // Same, regardless of control\n      // Diagonal\n      vals[0] = 1.0;\n      /*\n       * We shouldn't need to deal with any permutation here;\n       * i_sub is in the permuted basis, but we know that a\n       * diagonal element is diagonal in all bases, so\n       * we just use the computational basis value.\n       p         */\n      js[0]  = i;\n\n    } else if (i_sub==1){\n      // Diagonal\n      vals[0] = 1.0;\n      js[0]   = i;\n    } else if (i_sub==2){\n      // Diagonal\n      vals[0] = 1.0;\n      js[0]   = i;\n    } else if (i_sub==3){\n      vals[0] = -1.0;\n      js[0]   = i;\n    } else {\n      if (nid==0){\n        printf(\"ERROR! CZ gate is only defined for 2 qubits!\\n\");\n        exit(0);\n      }\n    }\n  } else {\n        /*\n     * U* cross U\n     * To calculate this, we first take our i_global, convert\n     * it to i1 (for U*) and i2 (for U) within their own\n     * part of the Hilbert space. pWe then treat i1 and i2 as\n     * global i's for the matrices U* and U themselves, which\n     * gives us j's for those matrices. We then expand the j's\n     * to get the full space representation, using the normal\n     * tensor product.\n     */\n\n    /* Calculate i1, i2 */\n    i1 = i/total_levels;\n    i2 = i%total_levels;\n\n    /* Now, get js for U* (i1) by calling this function */\n    CZ_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1);\n\n    /* Now, get js for U (i2) by calling this function */\n    CZ_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1);\n\n    /*\n     * Combine j's to get U* cross U\n     * Must do all possible permutations\n     */\n    *num_js = 0;\n    for(k1=0;k1<num_js_i1;k1++){\n      for(k2=0;k2<num_js_i2;k2++){\n        js[*num_js] = total_levels * js_i1[k1] + js_i2[k2];\n        //Need to take complex conjugate to get true U*\n        vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2];\n\n        *num_js = *num_js + 1;\n      }\n    }\n\n  }\n\n  return;\n}\n\n\nvoid CmZ_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js,\n                                  PetscInt js[],PetscScalar vals[],PetscInt tensor_control){\n  PetscInt n_after,i_sub,k1,k2,i1,i2,num_js_i1=0,num_js_i2=0,js_i1[2],js_i2[2];\n  PetscInt control,i_tmp,my_levels,moved_system;\n  PetscScalar vals_i1[2],vals_i2[2];\n\n  /* The controlled-mZ gate has two inputs, a target and a control.\n   * As a matrix, for a two qubit system\n   *     1 0 0 0        I2 0\n   *     0 1 0 0   =    0  -sig_z\n   *     0 0 -1 0\n   *     0 0 0 1\n   * Of course, when there are other qubits, tensor products and such\n   * must be applied to get the full basis representation.\n   *\n   * Note that this is a temporary gate; i.e., we will create a more\n   * general controlled-U gate at a later time that will replace\n   *\n   */\n\n  if (tensor_control!= 0) {\n\n    /* 4 is hardcoded because 2 qubits with 2 levels each */\n    my_levels   = 4;\n    // Get the correct hilbert space information\n    i_tmp = i;\n    _get_n_after_2qbit(&i_tmp,gate.qubit_numbers,tensor_control,&n_after,&control,&moved_system,&i_sub);\n\n    *num_js = 1;\n    if (i_sub==0){\n      // Same, regardless of control\n      // Diagonal\n      vals[0] = 1.0;\n      /*\n       * We shouldn't need to deal with any permutation here;\n       * i_sub is in the permuted basis, but we know that a\n       * diagonal element is diagonal in all bases, so\n       * we just use the computational basis value.\n       p         */\n      js[0]  = i;\n\n    } else if (i_sub==1){\n      // Diagonal\n      js[0]   = i;\n      if (control==0) {\n        vals[0] = 1.0;\n      } else {\n        vals[0] = -1.0;\n      }\n    } else if (i_sub==2){\n      // Diagonal\n      js[0]   = i;\n      if (control==0) {\n        vals[0] = -1.0;\n      } else {\n        vals[0] = 1.0;\n      }\n    } else if (i_sub==3){\n      vals[0] = 1.0;\n      js[0]   = i;\n    } else {\n      if (nid==0){\n        printf(\"ERROR! CmZ gate is only defined for 2 qubits!\\n\");\n        exit(0);\n      }\n    }\n  } else {\n        /*\n     * U* cross U\n     * To calculate this, we first take our i_global, convert\n     * it to i1 (for U*) and i2 (for U) within their own\n     * part of the Hilbert space. pWe then treat i1 and i2 as\n     * global i's for the matrices U* and U themselves, which\n     * gives us j's for those matrices. We then expand the j's\n     * to get the full space representation, using the normal\n     * tensor product.\n     */\n\n    /* Calculate i1, i2 */\n    i1 = i/total_levels;\n    i2 = i%total_levels;\n\n    /* Now, get js for U* (i1) by calling this function */\n    CmZ_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1);\n\n    /* Now, get js for U (i2) by calling this function */\n    CmZ_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1);\n\n    /*\n     * Combine j's to get U* cross U\n     * Must do all possible permutations\n     */\n    *num_js = 0;\n    for(k1=0;k1<num_js_i1;k1++){\n      for(k2=0;k2<num_js_i2;k2++){\n        js[*num_js] = total_levels * js_i1[k1] + js_i2[k2];\n        //Need to take complex conjugate to get true U*\n        vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2];\n\n        *num_js = *num_js + 1;\n      }\n    }\n\n  }\n\n  return;\n}\n\n\nvoid CZX_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js,\n                                  PetscInt js[],PetscScalar vals[],PetscInt tensor_control){\n  PetscInt n_after,i_sub,k1,k2,tmp_int,i1,i2,num_js_i1=0,num_js_i2=0,js_i1[2],js_i2[2];\n  PetscInt control,i_tmp,my_levels,j_sub,moved_system,j1;\n  PetscScalar vals_i1[2],vals_i2[2];\n\n  /* The controlled-ZX gate has two inputs, a target and a control.\n   * As a matrix, for a two qubit system\n   *     1 0 0 0        I2 0\n   *     0 1 0 0   =    0  sig_z * sig_x\n   *     0 0 0 1\n   *     0 0 -1 0\n   * Of course, when there are other qubits, tensor products and such\n   * must be applied to get the full basis representation.\n   *\n   * Note that this is a temporary gate; i.e., we will create a more\n   * general controlled-U gate at a later time that will replace this.\n   */\n\n  if (tensor_control!= 0) {\n\n    /* 4 is hardcoded because 2 qubits with 2 levels each */\n    my_levels   = 4;\n    // Get the correct hilbert space information\n    i_tmp = i;\n    _get_n_after_2qbit(&i_tmp,gate.qubit_numbers,tensor_control,&n_after,&control,&moved_system,&i_sub);\n\n    *num_js = 1;\n    if (i_sub==0){\n      // Same, regardless of control\n      // Diagonal\n      vals[0] = 1.0;\n      /*\n       * We shouldn't need to deal with any permutation here;\n       * i_sub is in the permuted basis, but we know that a\n       * diagonal element is diagonal in all bases, so\n       * we just use the computational basis value.\n       p         */\n      js[0]  = i;\n\n    } else if (i_sub==1){\n      // Check which is the control bit\n      vals[0] = 1.0;\n      if (control==0){\n        // Diagonal\n        js[0]   = i;\n      } else {\n        // Off diagonal\n        tmp_int = i_tmp - i_sub * n_after;\n        k2      = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function\n        k1      = tmp_int%(my_levels*n_after);\n        j_sub   = 3;\n        j1   = (j_sub) * n_after + k1 + k2*my_levels*n_after; // 3 = j_sub\n\n        /* Permute back to computational basis */\n        _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here\n        js[0] = j1;\n      }\n\n    } else if (i_sub==2){\n      vals[0] = 1.0;\n      if (control==0){\n        // Off diagonal\n        tmp_int = i_tmp - i_sub * n_after;\n        k2      = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function\n        k1      = tmp_int%(my_levels*n_after);\n        j_sub   = 3;\n        j1     = j_sub * n_after + k1 + k2*my_levels*n_after;\n\n        /* Permute back to computational basis */\n        _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here\n        js[0] = j1;\n      } else {\n        // Diagonal\n        js[0]   = i;\n      }\n    } else if (i_sub==3){\n      vals[0]   = -1.0;\n      if (control==0){\n        // Off diagonal element\n        tmp_int = i_tmp - i_sub * n_after;\n        k2      = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function\n        k1      = tmp_int%(my_levels*n_after);\n        j_sub   = 2;\n        j1     = j_sub * n_after + k1 + k2*my_levels*n_after;\n      } else {\n        // Off diagonal element\n        tmp_int = i_tmp - i_sub * n_after;\n        k2      = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function\n        k1      = tmp_int%(my_levels*n_after);\n        j_sub   = 1;\n        j1     = j_sub * n_after + k1 + k2*my_levels*n_after;\n      }\n      /* Permute back to computational basis */\n      _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1);//i_tmp useless here\n      js[0] = j1;\n    } else {\n      if (nid==0){\n        printf(\"ERROR! CZX gate is only defined for 2 qubits!\\n\");\n        exit(0);\n      }\n    }\n  } else {\n        /*\n     * U* cross U\n     * To calculate this, we first take our i_global, convert\n     * it to i1 (for U*) and i2 (for U) within their own\n     * part of the Hilbert space. pWe then treat i1 and i2 as\n     * global i's for the matrices U* and U themselves, which\n     * gives us j's for those matrices. We then expand the j's\n     * to get the full space representation, using the normal\n     * tensor product.\n     */\n\n    /* Calculate i1, i2 */\n    i1 = i/total_levels;\n    i2 = i%total_levels;\n\n    /* Now, get js for U* (i1) by calling this function */\n    CZX_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1);\n\n    /* Now, get js for U (i2) by calling this function */\n    CZX_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1);\n\n    /*\n     * Combine j's to get U* cross U\n     * Must do all possible permutations\n     */\n    *num_js = 0;\n    for(k1=0;k1<num_js_i1;k1++){\n      for(k2=0;k2<num_js_i2;k2++){\n        js[*num_js] = total_levels * js_i1[k1] + js_i2[k2];\n        //Need to take complex conjugate to get true U*\n        vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2];\n\n        *num_js = *num_js + 1;\n      }\n    }\n\n  }\n\n  return;\n}\n\nvoid SWAP_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js,\n                                 PetscInt js[],PetscScalar vals[],PetscInt tensor_control){\n    PetscInt n_after,i_sub,k1,k2,tmp_int,i1,i2,num_js_i1=0,num_js_i2=0,js_i1[2],js_i2[2];\n    PetscInt control,i_tmp,my_levels,j_sub,moved_system,j1;\n    PetscScalar vals_i1[2],vals_i2[2];\n    \n    /* The swap gate swaps two qubits.\n     * As a matrix, for a two qubit system\n     *     1 0 0 0        I2 0\n     *     0 0 1 0   =    0  sig_z * sig_x\n     *     0 1 0 0\n     *     0 0 0 1\n     */\n    \n    if (tensor_control!= 0) {\n        \n        /* 4 is hardcoded because 2 qubits with 2 levels each */\n        my_levels   = 4;\n        // Get the correct hilbert space information\n        i_tmp = i;\n        _get_n_after_2qbit(&i_tmp,gate.qubit_numbers,tensor_control,&n_after,&control,&moved_system,&i_sub);\n        \n        printf(\"\\n tensor_control %d,control %d,i_sub %d n_after %d\\n\", tensor_control, control, i_sub, n_after );\n        *num_js = 1;\n        if (i_sub==0){\n            // Diagonal\n            vals[0] = 1.0;\n            /*\n             * We shouldn't need to deal with any permutation here;\n             * i_sub is in the permuted basis, but we know that a\n             * diagonal element is diagonal in all bases, so\n             * we just use the computational basis value.\n             p         */\n            js[0]  = i;\n            \n        } else if (i_sub==1){\n            // Check which is the control bit\n            vals[0] = 1.0;\n                // Off diagonal\n                tmp_int = i_tmp - i_sub * n_after;\n                k2      = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function\n                k1      = tmp_int%(my_levels*n_after);\n                j_sub   = 2;\n                j1   = (j_sub) * n_after + k1 + k2*my_levels*n_after; // 3 = j_sub\n                \n                // Permute back to computational basis\n                _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here\n                js[0] = j1;\n            \n        } else if (i_sub==2){\n            vals[0] = 1.0;\n                // Off diagonal\n                tmp_int = i_tmp - i_sub * n_after;\n                k2      = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function\n                k1      = tmp_int%(my_levels*n_after);\n                j_sub   = 1;\n                j1     = j_sub * n_after + k1 + k2*my_levels*n_after;\n                \n                /* Permute back to computational basis */\n                _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here\n                js[0] = j1;\n        } else if (i_sub==3){\n            // Diagonal\n            vals[0] = 1.0;\n            /*\n             * We shouldn't need to deal with any permutation here;\n             * i_sub is in the permuted basis, but we know that a\n             * diagonal element is diagonal in all bases, so\n             * we just use the computational basis value.\n             p         */\n            js[0]  = i;\n        } else {\n            if (nid==0){\n                printf(\"ERROR! SWAP gate is only defined for 2 qubits!\\n\");\n                exit(0);\n            }\n        }\n    } else {\n        /*\n         * U* cross U\n         * To calculate this, we first take our i_global, convert\n         * it to i1 (for U*) and i2 (for U) within their own\n         * part of the Hilbert space. pWe then treat i1 and i2 as\n         * global i's for the matrices U* and U themselves, which\n         * gives us j's for those matrices. We then expand the j's\n         * to get the full space representation, using the normal\n         * tensor product.\n         */\n        \n        /* Calculate i1, i2 */\n        i1 = i/total_levels;\n        i2 = i%total_levels;\n        \n        /* Now, get js for U* (i1) by calling this function */\n        SWAP_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1);\n        \n        /* Now, get js for U (i2) by calling this function */\n        SWAP_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1);\n        \n        /*\n         * Combine j's to get U* cross U\n         * Must do all possible permutations\n         */\n        *num_js = 0;\n        for(k1=0;k1<num_js_i1;k1++){\n            for(k2=0;k2<num_js_i2;k2++){\n                js[*num_js] = total_levels * js_i1[k1] + js_i2[k2];\n                //Need to take complex conjugate to get true U*\n                vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2];\n                \n                *num_js = *num_js + 1;\n            }\n        }\n        \n    }\n    \n    return;\n}\n\n\nvoid HADAMARD_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js,\n                                      PetscInt js[],PetscScalar vals[],PetscInt tensor_control){\n  PetscInt n_after,i_sub,k1,k2,tmp_int,i1,i2,num_js_i1,num_js_i2,js_i1[2],js_i2[2],my_levels;\n  PetscScalar vals_i1[2],vals_i2[2];\n\n  /*\n   * HADAMARD gate\n   *\n   * 1/sqrt(2) | 1  1 |\n   *           | 1 -1 |\n   * Hadamard gates have two values per row,\n   * with both diagonal anad off diagonal elements\n   *\n   */\n  if (tensor_control!= 0) {\n    my_levels = 2; //Hardcoded becase single qubit gate\n    _get_n_after_1qbit(i,gate.qubit_numbers[0],tensor_control,&n_after,&i_sub);\n    *num_js = 2;\n    if (i_sub==0) {\n      // Diagonal element\n      js[0]   = i;\n      vals[0] = pow(2,-0.5);\n\n      // Off diagonal element\n      tmp_int = i - 0 * n_after;\n      k2      = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function\n      k1      = tmp_int%(my_levels*n_after);\n      js[1]   = (0 + 1) * n_after + k1 + k2*my_levels*n_after;\n      vals[1] = pow(2,-0.5);\n\n    } else if (i_sub==1){\n      // Diagonal element\n      js[0]   = i;\n      vals[0] = -pow(2,-0.5);\n\n      // Off diagonal element\n      tmp_int = i - (0+1) * n_after;\n      k2      = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function\n      k1      = tmp_int%(my_levels*n_after);\n      js[1]   = 0 * n_after + k1 + k2*my_levels*n_after;\n      vals[1] = pow(2,-0.5);\n\n    } else {\n      if (nid==0){\n        printf(\"ERROR! Hadamard gate is only defined for qubits\\n\");\n        exit(0);\n      }\n    }\n  } else {\n    /*\n     * U* cross U\n     * To calculate this, we first take our i_global, convert\n     * it to i1 (for U*) and i2 (for U) within their own\n     * part of the Hilbert space. pWe then treat i1 and i2 as\n     * global i's for the matrices U* and U themselves, which\n     * gives us j's for those matrices. We then expand the j's\n     * to get the full space representation, using the normal\n     * tensor product.\n     */\n\n    /* Calculate i1, i2 */\n    i1 = i/total_levels;\n    i2 = i%total_levels;\n\n    /* Now, get js for U* (i1) by calling this function */\n    HADAMARD_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1);\n\n    /* Now, get js for U (i2) by calling this function */\n    HADAMARD_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1);\n\n    /*\n     * Combine j's to get U* cross U\n     * Must do all possible permutations\n     */\n    *num_js = 0;\n    for(k1=0;k1<num_js_i1;k1++){\n      for(k2=0;k2<num_js_i2;k2++){\n        js[*num_js] = total_levels * js_i1[k1] + js_i2[k2];\n        //Need to take complex conjugate to get true U*\n        vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2];\n\n        *num_js = *num_js + 1;\n      }\n    }\n  }\n\n  return;\n}\n\nvoid U3_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js,\n                                      PetscInt js[],PetscScalar vals[],PetscInt tensor_control){\n  PetscInt n_after,i_sub,k1,k2,tmp_int,i1,i2,num_js_i1,num_js_i2,js_i1[2],js_i2[2],my_levels;\n  PetscScalar vals_i1[2],vals_i2[2];\n  PetscReal theta,lambda,phi;\n  /*\n   * u3 gate\n   *\n   * u3(theta,phi,lambda)  = | cos(theta/2)              -e^(i lambda) * sin(theta/2)    |\n   *                         | e^(i phi) sin(theta/2)    e^(i (lambda+phi)) cos(theta/2) |\n   * the u3 gate is a general one qubit transformation.\n   * the u2 gate is u3(pi/2,phi,lambda)\n   * the u1 gate is u3(0,0,lambda)\n   * The u3 gate has two elements per row,\n   * with both diagonal anad off diagonal elements\n   *\n   */\n  theta = gate.theta;\n  phi = gate.phi;\n  lambda = gate.lambda;\n  if (tensor_control!= 0) {\n    my_levels = 2; //Hardcoded becase single qubit gate\n    _get_n_after_1qbit(i,gate.qubit_numbers[0],tensor_control,&n_after,&i_sub);\n    *num_js = 2;\n    if (i_sub==0) {\n      // Diagonal element\n      js[0]   = i;\n      vals[0] = PetscCosReal(theta/2);\n\n      // Off diagonal element\n      tmp_int = i - 0 * n_after;\n      k2      = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function\n      k1      = tmp_int%(my_levels*n_after);\n      js[1]   = (0 + 1) * n_after + k1 + k2*my_levels*n_after;\n      vals[1] = -PetscExpComplex(PETSC_i*lambda)*PetscSinReal(theta/2);\n\n    } else if (i_sub==1){\n      // Diagonal element\n      js[0]   = i;\n      vals[0] = PetscExpComplex(PETSC_i*(lambda+phi))*PetscCosReal(theta/2);\n      // Off diagonal element\n      tmp_int = i - (0+1) * n_after;\n      k2      = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function\n      k1      = tmp_int%(my_levels*n_after);\n      js[1]   = 0 * n_after + k1 + k2*my_levels*n_after;\n      vals[1] = PetscExpComplex(PETSC_i*phi)*PetscSinReal(theta/2);\n\n    } else {\n      if (nid==0){\n        printf(\"ERROR! u3 gate is only defined for qubits\\n\");\n        exit(0);\n      }\n    }\n  } else {\n    /*\n     * U* cross U\n     * To calculate this, we first take our i_global, convert\n     * it to i1 (for U*) and i2 (for U) within their own\n     * part of the Hilbert space. pWe then treat i1 and i2 as\n     * global i's for the matrices U* and U themselves, which\n     * gives us j's for those matrices. We then expand the j's\n     * to get the full space representation, using the normal\n     * tensor product.\n     */\n\n    /* Calculate i1, i2 */\n    i1 = i/total_levels;\n    i2 = i%total_levels;\n\n    /* Now, get js for U* (i1) by calling this function */\n    U3_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1);\n\n    /* Now, get js for U (i2) by calling this function */\n    U3_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1);\n\n\n    /*\n     * Combine j's to get U* cross U\n     * Must do all possible permutations\n     */\n    *num_js = 0;\n    for(k1=0;k1<num_js_i1;k1++){\n      for(k2=0;k2<num_js_i2;k2++){\n        js[*num_js] = total_levels * js_i1[k1] + js_i2[k2];\n        //Need to take complex conjugate to get true U*\n        vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2];\n\n        *num_js = *num_js + 1;\n      }\n    }\n  }\n\n  return;\n}\n\n\nvoid EYE_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js,\n                                      PetscInt js[],PetscScalar vals[],PetscInt tensor_control){\n  PetscInt n_after,i_sub,k1,k2,i1,i2,num_js_i1,num_js_i2,js_i1[2],js_i2[2];\n  PetscScalar vals_i1[2],vals_i2[2];\n\n  /*\n   * Identity (EYE) gate\n   *\n   *   | 1   0 |\n   *   | 0   1 |\n   *\n   */\n\n  if (tensor_control!= 0) {\n    _get_n_after_1qbit(i,gate.qubit_numbers[0],tensor_control,&n_after,&i_sub);\n    *num_js = 1;\n    js[0] = i;\n    vals[0] = 1.0;\n  } else {\n    /*\n     * U* cross U\n     * To calculate this, we first take our i_global, convert\n     * it to i1 (for U*) and i2 (for U) within their own\n     * part of the Hilbert space. pWe then treat i1 and i2 as\n     * global i's for the matrices U* and U themselves, which\n     * gives us j's for those matrices. We then expand the j's\n     * to get the full space representation, using the normal\n     * tensor product.\n     */\n\n    /* Calculate i1, i2 */\n    i1 = i/total_levels;\n    i2 = i%total_levels;\n\n    /* Now, get js for U* (i1) by calling this function */\n    EYE_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1);\n\n    /* Now, get js for U (i2) by calling this function */\n    EYE_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1);\n\n    /*\n     * Combine j's to get U* cross U\n     * Must do all possible permutations\n     */\n    *num_js = 0;\n    for(k1=0;k1<num_js_i1;k1++){\n      for(k2=0;k2<num_js_i2;k2++){\n        js[*num_js] = total_levels * js_i1[k1] + js_i2[k2];\n        //Need to take complex conjugate to get true U*\n        vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2];\n\n        *num_js = *num_js + 1;\n      }\n    }\n  }\n  return;\n}\n\n\nvoid PHASESHIFT_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js,\n                                    PetscInt js[],PetscScalar vals[],PetscInt tensor_control){\n    PetscInt n_after,i_sub,k1,k2,i1,i2,num_js_i1,num_js_i2,js_i1[2],js_i2[2],my_levels;\n    PetscScalar vals_i1[2],vals_i2[2];\n    PetscReal theta;\n    \n    /*\n     * PHASESHIFT gate\n     *\n     *   | 1   0 |\n     *   | 0  e^(-i*theta) |\n     *\n     */\n    \n    theta=gate.theta;\n    if (tensor_control!= 0) {\n        my_levels = 2; //Hardcoded becase single qubit gate\n        _get_n_after_1qbit(i,gate.qubit_numbers[0],tensor_control,&n_after,&i_sub);\n        *num_js = 1;\n        if (i_sub==0) {\n            // Diagonal element\n            js[0] = i;\n            vals[0] = 1.0;\n            \n        } else if (i_sub==1){\n            // Diagonal element\n            js[0] = i;\n            vals[0] = PetscExpComplex(-PETSC_i*theta);\n            \n        } else {\n            if (nid==0){\n                printf(\"ERROR! phaseshift gate is only defined for qubits\\n\");\n                exit(0);\n            }\n        }\n    } else {\n        /*\n         * U* cross U\n         * To calculate this, we first take our i_global, convert\n         * it to i1 (for U*) and i2 (for U) within their own\n         * part of the Hilbert space. pWe then treat i1 and i2 as\n         * global i's for the matrices U* and U themselves, which\n         * gives us j's for those matrices. We then expand the j's\n         * to get the full space representation, using the normal\n         * tensor product.\n         */\n        \n        /* Calculate i1, i2 */\n        i1 = i/total_levels;\n        i2 = i%total_levels;\n        \n        /* Now, get js for U* (i1) by calling this function */\n        PHASESHIFT_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1);\n        \n        /* Now, get js for U (i2) by calling this function */\n        PHASESHIFT_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1);\n        \n        /*\n         * Combine j's to get U* cross U\n         * Must do all possible permutations\n         */\n        *num_js = 0;\n        for(k1=0;k1<num_js_i1;k1++){\n            for(k2=0;k2<num_js_i2;k2++){\n                js[*num_js] = total_levels * js_i1[k1] + js_i2[k2];\n                //Need to take complex conjugate to get true U*\n                vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2];\n                \n                *num_js = *num_js + 1;\n            }\n        }\n    }\n    return;\n}\n\nvoid SIGMAZ_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js,\n                                      PetscInt js[],PetscScalar vals[],PetscInt tensor_control){\n  PetscInt n_after,i_sub,k1,k2,i1,i2,num_js_i1,num_js_i2,js_i1[2],js_i2[2],my_levels;\n  PetscScalar vals_i1[2],vals_i2[2];\n\n  /*\n   * SIGMAZ gate\n   *\n   *   | 1   0 |\n   *   | 0  -1 |\n   *\n   */\n\n  if (tensor_control!= 0) {\n    my_levels = 2; //Hardcoded becase single qubit gate\n    _get_n_after_1qbit(i,gate.qubit_numbers[0],tensor_control,&n_after,&i_sub);\n    *num_js = 1;\n    if (i_sub==0) {\n      // Diagonal element\n      js[0] = i;\n      vals[0] = 1.0;\n\n    } else if (i_sub==1){\n      // Diagonal element\n      js[0] = i;\n      vals[0] = -1.0;\n\n    } else {\n      if (nid==0){\n        printf(\"ERROR! sigmaz gate is only defined for qubits\\n\");\n        exit(0);\n      }\n    }\n  } else {\n    /*\n     * U* cross U\n     * To calculate this, we first take our i_global, convert\n     * it to i1 (for U*) and i2 (for U) within their own\n     * part of the Hilbert space. pWe then treat i1 and i2 as\n     * global i's for the matrices U* and U themselves, which\n     * gives us j's for those matrices. We then expand the j's\n     * to get the full space representation, using the normal\n     * tensor product.\n     */\n\n    /* Calculate i1, i2 */\n    i1 = i/total_levels;\n    i2 = i%total_levels;\n\n    /* Now, get js for U* (i1) by calling this function */\n    SIGMAZ_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1);\n\n    /* Now, get js for U (i2) by calling this function */\n    SIGMAZ_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1);\n\n    /*\n     * Combine j's to get U* cross U\n     * Must do all possible permutations\n     */\n    *num_js = 0;\n    for(k1=0;k1<num_js_i1;k1++){\n      for(k2=0;k2<num_js_i2;k2++){\n        js[*num_js] = total_levels * js_i1[k1] + js_i2[k2];\n        //Need to take complex conjugate to get true U*\n        vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2];\n\n        *num_js = *num_js + 1;\n      }\n    }\n  }\n  return;\n}\n\nvoid RZ_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js,\n                                      PetscInt js[],PetscScalar vals[],PetscInt tensor_control){\n  PetscInt n_after,i_sub,k1,k2,i1,i2,num_js_i1,num_js_i2,js_i1[2],js_i2[2],my_levels;\n  PetscScalar vals_i1[2],vals_i2[2];\n  PetscReal theta;\n  /*\n   * RZ gate\n   *\n   *   | exp(i*theta/2)   0               |\n   *   | 0                -exp(i*theta/2) |\n   *\n   */\n\n  theta = gate.theta;\n  if (tensor_control!= 0) {\n    my_levels = 2; //Hardcoded becase single qubit gate\n    _get_n_after_1qbit(i,gate.qubit_numbers[0],tensor_control,&n_after,&i_sub);\n    *num_js = 1;\n    if (i_sub==0) {\n      // Diagonal element\n      js[0] = i;\n      vals[0] = PetscExpComplex(PETSC_i*theta/2);\n\n    } else if (i_sub==1){\n      // Diagonal element\n      js[0] = i;\n      vals[0] = PetscExpComplex(-PETSC_i*theta/2);\n\n    } else {\n      if (nid==0){\n        printf(\"ERROR! rz gate is only defined for qubits\\n\");\n        exit(0);\n      }\n    }\n  } else {\n    /*\n     * U* cross U\n     * To calculate this, we first take our i_global, convert\n     * it to i1 (for U*) and i2 (for U) within their own\n     * part of the Hilbert space. pWe then treat i1 and i2 as\n     * global i's for the matrices U* and U themselves, which\n     * gives us j's for those matrices. We then expand the j's\n     * to get the full space representation, using the normal\n     * tensor product.\n     */\n\n    /* Calculate i1, i2 */\n    i1 = i/total_levels;\n    i2 = i%total_levels;\n\n    /* Now, get js for U* (i1) by calling this function */\n    RZ_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1);\n\n    /* Now, get js for U (i2) by calling this function */\n    RZ_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1);\n\n    /*\n     * Combine j's to get U* cross U\n     * Must do all possible permutations\n     */\n    *num_js = 0;\n    for(k1=0;k1<num_js_i1;k1++){\n      for(k2=0;k2<num_js_i2;k2++){\n        js[*num_js] = total_levels * js_i1[k1] + js_i2[k2];\n        //Need to take complex conjugate to get true U*\n        vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2];\n\n        *num_js = *num_js + 1;\n      }\n    }\n  }\n  return;\n}\n\nvoid RY_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js,\n                                      PetscInt js[],PetscScalar vals[],PetscInt tensor_control){\n  PetscInt n_after,i_sub,k1,k2,tmp_int,i1,i2,num_js_i1,num_js_i2,js_i1[2],js_i2[2],my_levels;\n  PetscScalar vals_i1[2],vals_i2[2];\n  PetscReal theta;\n  /*\n   * RY gate\n   *\n   *   | cos(theta/2)   sin(theta/2)  |\n   *   | -sin(theta/2)  cos(theta/2)  |\n   *\n   */\n\n  theta = gate.theta;\n  if (tensor_control!= 0) {\n    my_levels = 2; //Hardcoded becase single qubit gate\n    _get_n_after_1qbit(i,gate.qubit_numbers[0],tensor_control,&n_after,&i_sub);\n    *num_js = 2;\n    if (i_sub==0) {\n      // Diagonal element\n      js[0] = i;\n      vals[0] = PetscCosReal(theta/2.0);\n      // Off diagonal element\n      tmp_int = i - 0 * n_after;\n      k2      = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function\n      k1      = tmp_int%(my_levels*n_after);\n      js[1]     = (0 + 1) * n_after + k1 + k2*my_levels*n_after;\n      vals[1]   = PetscSinReal(theta/2);\n\n\n    } else if (i_sub==1){\n      // Diagonal element\n      js[0] = i;\n      vals[0] = PetscCosReal(theta/2);\n\n      // Off diagonal element\n      tmp_int = i - (0+1) * n_after;\n      k2      = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function\n      k1      = tmp_int%(my_levels*n_after);\n      js[1]   = 0 * n_after + k1 + k2*my_levels*n_after;\n      vals[1]   = -PetscSinReal(theta/2);\n\n\n    } else {\n      if (nid==0){\n        printf(\"ERROR! rz gate is only defined for qubits\\n\");\n        exit(0);\n      }\n    }\n  } else {\n    /*\n     * U* cross U\n     * To calculate this, we first take our i_global, convert\n     * it to i1 (for U*) and i2 (for U) within their own\n     * part of the Hilbert space. pWe then treat i1 and i2 as\n     * global i's for the matrices U* and U themselves, which\n     * gives us j's for those matrices. We then expand the j's\n     * to get the full space representation, using the normal\n     * tensor product.\n     */\n\n    /* Calculate i1, i2 */\n    i1 = i/total_levels;\n    i2 = i%total_levels;\n\n    /* Now, get js for U* (i1) by calling this function */\n    RY_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1);\n\n    /* Now, get js for U (i2) by calling this function */\n    RY_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1);\n\n    /*\n     * Combine j's to get U* cross U\n     * Must do all possible permutations\n     */\n    *num_js = 0;\n    for(k1=0;k1<num_js_i1;k1++){\n      for(k2=0;k2<num_js_i2;k2++){\n        js[*num_js] = total_levels * js_i1[k1] + js_i2[k2];\n        //Need to take complex conjugate to get true U*\n        vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2];\n\n        *num_js = *num_js + 1;\n      }\n    }\n  }\n  return;\n}\n\n\nvoid RX_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js,\n                                      PetscInt js[],PetscScalar vals[],PetscInt tensor_control){\n  PetscInt n_after,i_sub,k1,k2,tmp_int,i1,i2,num_js_i1,num_js_i2,js_i1[2],js_i2[2],my_levels;\n  PetscScalar vals_i1[2],vals_i2[2];\n  PetscReal theta;\n  /*\n   * RX gate\n   *\n   *   | cos(theta/2)    i*sin(theta/2) |\n   *   | i*sin(theta/2)  cos(theta/2)   |\n   *\n   */\n\n  theta = gate.theta;\n  if (tensor_control!= 0) {\n    my_levels = 2; //Hardcoded becase single qubit gate\n    _get_n_after_1qbit(i,gate.qubit_numbers[0],tensor_control,&n_after,&i_sub);\n    *num_js = 2;\n    if (i_sub==0) {\n      // Diagonal element\n      js[0] = i;\n      vals[0] = PetscCosReal(theta/2);\n\n      // Off diagonal element\n      tmp_int = i - 0 * n_after;\n      k2      = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function\n      k1      = tmp_int%(my_levels*n_after);\n      js[1]     = (0 + 1) * n_after + k1 + k2*my_levels*n_after;\n      vals[1]   = PETSC_i * PetscSinReal(theta/2);\n\n\n    } else if (i_sub==1){\n      // Diagonal element\n      js[0] = i;\n      vals[0] = PetscCosReal(theta/2);\n\n      // Off diagonal element\n      tmp_int = i - (0+1) * n_after;\n      k2      = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function\n      k1      = tmp_int%(my_levels*n_after);\n      js[1]   = 0 * n_after + k1 + k2*my_levels*n_after;\n      vals[1]   = PETSC_i * PetscSinReal(theta/2);\n\n\n    } else {\n      if (nid==0){\n        printf(\"ERROR! rz gate is only defined for qubits\\n\");\n        exit(0);\n      }\n    }\n  } else {\n    /*\n     * U* cross U\n     * To calculate this, we first take our i_global, convert\n     * it to i1 (for U*) and i2 (for U) within their own\n     * part of the Hilbert space. pWe then treat i1 and i2 as\n     * global i's for the matrices U* and U themselves, which\n     * gives us j's for those matrices. We then expand the j's\n     * to get the full space representation, using the normal\n     * tensor product.\n     */\n\n    /* Calculate i1, i2 */\n    i1 = i/total_levels;\n    i2 = i%total_levels;\n\n    /* Now, get js for U* (i1) by calling this function */\n    RX_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1);\n\n    /* Now, get js for U (i2) by calling this function */\n    RX_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1);\n\n    /*\n     * Combine j's to get U* cross U\n     * Must do all possible permutations\n     */\n    *num_js = 0;\n    for(k1=0;k1<num_js_i1;k1++){\n      for(k2=0;k2<num_js_i2;k2++){\n        js[*num_js] = total_levels * js_i1[k1] + js_i2[k2];\n        //Need to take complex conjugate to get true U*\n        vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2];\n\n        *num_js = *num_js + 1;\n      }\n    }\n  }\n  return;\n}\n\n\nvoid SIGMAY_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js,\n                                      PetscInt js[],PetscScalar vals[],PetscInt tensor_control){\n  PetscInt n_after,i_sub,k1,k2,tmp_int,i1,i2,num_js_i1,num_js_i2,js_i1[2],js_i2[2],my_levels;\n  PetscScalar vals_i1[2],vals_i2[2];\n\n  /*\n   * SIGMAY gate\n   *\n   *   | 0  -1.j |\n   *   | 1.j  0 |\n   *\n   */\n  if (tensor_control!= 0) {\n    my_levels = 2; //Hardcoded becase single qubit gate\n    _get_n_after_1qbit(i,gate.qubit_numbers[0],tensor_control,&n_after,&i_sub);\n    *num_js = 1;\n    if (i_sub==0) {\n\n      // Off diagonal element\n      tmp_int = i - 0 * n_after;\n      k2      = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function\n      k1      = tmp_int%(my_levels*n_after);\n      js[0]   = (0 + 1) * n_after + k1 + k2*my_levels*n_after;\n      vals[0] = -1.0*PETSC_i;\n\n    } else if (i_sub==1){\n\n      // Off diagonal element\n      tmp_int = i - (0+1) * n_after;\n      k2      = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function\n      k1      = tmp_int%(my_levels*n_after);\n      js[0]   = 0 * n_after + k1 + k2*my_levels*n_after;\n      vals[0] = 1.0*PETSC_i;\n\n    } else {\n      if (nid==0){\n        printf(\"ERROR! sigmay gate is only defined for qubits\\n\");\n        exit(0);\n      }\n    }\n\n  } else {\n    /*\n     * U* cross U\n     * To calculate this, we first take our i_global, convert\n     * it to i1 (for U*) and i2 (for U) within their own\n     * part of the Hilbert space. pWe then treat i1 and i2 as\n     * global i's for the matrices U* and U themselves, which\n     * gives us j's for those matrices. We then expand the j's\n     * to get the full space representation, using the normal\n     * tensor product.\n     */\n\n    /* Calculate i1, i2 */\n    i1 = i/total_levels;\n    i2 = i%total_levels;\n\n    /* Now, get js for U* (i1) by calling this function */\n    SIGMAY_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1);\n\n    /* Now, get js for U (i2) by calling this function */\n    SIGMAY_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1);\n\n    /*\n     * Combine j's to get U* cross U\n     * Must do all possible permutations\n     */\n    *num_js = 0;\n    for(k1=0;k1<num_js_i1;k1++){\n      for(k2=0;k2<num_js_i2;k2++){\n        js[*num_js] = total_levels * js_i1[k1] + js_i2[k2];\n        //Need to take complex conjugate to get true U*\n        vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2];\n\n        *num_js = *num_js + 1;\n      }\n    }\n  }\n  return;\n}\n\n\nvoid SIGMAX_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js,\n                                      PetscInt js[],PetscScalar vals[],PetscInt tensor_control){\n  PetscInt n_after,i_sub,k1,k2,tmp_int,i1,i2,num_js_i1,num_js_i2,js_i1[2],js_i2[2],my_levels;\n  PetscScalar vals_i1[2],vals_i2[2];\n\n  /*\n   * SIGMAX gate\n   *\n   *   | 0  1 |\n   *   | 1  0 |\n   *\n   */\n  if (tensor_control!= 0) {\n    my_levels = 2; //Hardcoded becase single qubit gate\n    _get_n_after_1qbit(i,gate.qubit_numbers[0],tensor_control,&n_after,&i_sub);\n    *num_js = 1;\n    if (i_sub==0) {\n\n      // Off diagonal element\n      tmp_int = i - 0 * n_after;\n      k2      = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function\n      k1      = tmp_int%(my_levels*n_after);\n      js[0]     = (0 + 1) * n_after + k1 + k2*my_levels*n_after;\n      vals[0]   = 1.0;\n\n    } else if (i_sub==1){\n\n      // Off diagonal element\n      tmp_int = i - (0+1) * n_after;\n      k2      = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function\n      k1      = tmp_int%(my_levels*n_after);\n      js[0]   = 0 * n_after + k1 + k2*my_levels*n_after;\n      vals[0] = 1.0;\n\n    } else {\n      if (nid==0){\n        printf(\"ERROR! sigmax gate is only defined for qubits\\n\");\n        exit(0);\n      }\n    }\n  } else {\n    /*\n     * U* cross U\n     * To calculate this, we first take our i_global, convert\n     * it to i1 (for U*) and i2 (for U) within their own\n     * part of the Hilbert space. pWe then treat i1 and i2 as\n     * global i's for the matrices U* and U themselves, which\n     * gives us j's for those matrices. We then expand the j's\n     * to get the full space representation, using the normal\n     * tensor product.\n     */\n\n    /* Calculate i1, i2 */\n    i1 = i/total_levels;\n    i2 = i%total_levels;\n\n    /* Now, get js for U* (i1) by calling this function */\n    SIGMAX_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1);\n\n    /* Now, get js for U (i2) by calling this function */\n    SIGMAX_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1);\n\n    /*\n     * Combine j's to get U* cross U\n     * Must do all possible permutations\n     */\n    *num_js = 0;\n    for(k1=0;k1<num_js_i1;k1++){\n      for(k2=0;k2<num_js_i2;k2++){\n        js[*num_js] = total_levels * js_i1[k1] + js_i2[k2];\n        //Need to take complex conjugate to get true U*\n        vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2];\n\n        *num_js = *num_js + 1;\n      }\n    }\n  }\n  return;\n}\n\nvoid T_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js,\n                                PetscInt js[],PetscScalar vals[],PetscInt tensor_control){\n    PetscInt n_after,i_sub,k1,k2,i1,i2,num_js_i1,num_js_i2,js_i1[2],js_i2[2],my_levels;\n    PetscScalar vals_i1[2],vals_i2[2];\n    PetscReal theta;\n    /*\n     * T gate\n     *\n     *   | 1   0               |\n     *   | 0       exp(i*pi/4) |\n     *\n     */\n    \n    theta = gate.theta;\n    if (tensor_control!= 0) {\n        my_levels = 2; //Hardcoded becase single qubit gate\n        _get_n_after_1qbit(i,gate.qubit_numbers[0],tensor_control,&n_after,&i_sub);\n        *num_js = 1;\n        if (i_sub==0) {\n            // Diagonal element\n            js[0] = i;\n            vals[0] = 1;\n            \n        } else if (i_sub==1){\n            // Diagonal element\n            js[0] = i;\n            vals[0] = PetscExpComplex(PETSC_i*PETSC_PI/4);\n            \n        } else {\n            if (nid==0){\n                printf(\"ERROR! T gate is only defined for qubits\\n\");\n                exit(0);\n            }\n        }\n    } else {\n        /*\n         * U* cross U\n         * To calculate this, we first take our i_global, convert\n         * it to i1 (for U*) and i2 (for U) within their own\n         * part of the Hilbert space. pWe then treat i1 and i2 as\n         * global i's for the matrices U* and U themselves, which\n         * gives us j's for those matrices. We then expand the j's\n         * to get the full space representation, using the normal\n         * tensor product.\n         */\n        \n        /* Calculate i1, i2 */\n        i1 = i/total_levels;\n        i2 = i%total_levels;\n        \n        /* Now, get js for U* (i1) by calling this function */\n        T_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1);\n        \n        /* Now, get js for U (i2) by calling this function */\n        T_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1);\n        \n        /*\n         * Combine j's to get U* cross U\n         * Must do all possible permutations\n         */\n        *num_js = 0;\n        for(k1=0;k1<num_js_i1;k1++){\n            for(k2=0;k2<num_js_i2;k2++){\n                js[*num_js] = total_levels * js_i1[k1] + js_i2[k2];\n                //Need to take complex conjugate to get true U*\n                vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2];\n                \n                *num_js = *num_js + 1;\n            }\n        }\n    }\n    return;\n}\n\nvoid TDAG_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js,\n                               PetscInt js[],PetscScalar vals[],PetscInt tensor_control){\n    PetscInt n_after,i_sub,k1,k2,i1,i2,num_js_i1,num_js_i2,js_i1[2],js_i2[2],my_levels;\n    PetscScalar vals_i1[2],vals_i2[2];\n    PetscReal theta;\n    /*\n     * TDAG gate\n     *\n     *   | 1   0               |\n     *   | 0       exp(i*pi/4) |\n     *\n     */\n    \n    theta = gate.theta;\n    if (tensor_control!= 0) {\n        my_levels = 2; //Hardcoded becase single qubit gate\n        _get_n_after_1qbit(i,gate.qubit_numbers[0],tensor_control,&n_after,&i_sub);\n        *num_js = 1;\n        if (i_sub==0) {\n            // Diagonal element\n            js[0] = i;\n            vals[0] = 1;\n            \n        } else if (i_sub==1){\n            // Diagonal element\n            js[0] = i;\n            vals[0] = PetscExpComplex(-PETSC_i*PETSC_PI/4);\n            \n        } else {\n            if (nid==0){\n                printf(\"ERROR! T gate is only defined for qubits\\n\");\n                exit(0);\n            }\n        }\n    } else {\n        /*\n         * U* cross U\n         * To calculate this, we first take our i_global, convert\n         * it to i1 (for U*) and i2 (for U) within their own\n         * part of the Hilbert space. pWe then treat i1 and i2 as\n         * global i's for the matrices U* and U themselves, which\n         * gives us j's for those matrices. We then expand the j's\n         * to get the full space representation, using the normal\n         * tensor product.\n         */\n        \n        /* Calculate i1, i2 */\n        i1 = i/total_levels;\n        i2 = i%total_levels;\n        \n        /* Now, get js for U* (i1) by calling this function */\n        TDAG_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1);\n        \n        /* Now, get js for U (i2) by calling this function */\n        TDAG_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1);\n        \n        /*\n         * Combine j's to get U* cross U\n         * Must do all possible permutations\n         */\n        *num_js = 0;\n        for(k1=0;k1<num_js_i1;k1++){\n            for(k2=0;k2<num_js_i2;k2++){\n                js[*num_js] = total_levels * js_i1[k1] + js_i2[k2];\n                //Need to take complex conjugate to get true U*\n                vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2];\n                \n                *num_js = *num_js + 1;\n            }\n        }\n    }\n    return;\n}\n\nvoid S_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js,\n                               PetscInt js[],PetscScalar vals[],PetscInt tensor_control){\n    PetscInt n_after,i_sub,k1,k2,i1,i2,num_js_i1,num_js_i2,js_i1[2],js_i2[2],my_levels;\n    PetscScalar vals_i1[2],vals_i2[2];\n    PetscReal theta;\n    /*\n     * S gate\n     *\n     *   | 1   0 |\n     *   | 0   i |\n     *\n     */\n    \n    theta = gate.theta;\n    if (tensor_control!= 0) {\n        my_levels = 2; //Hardcoded becase single qubit gate\n        _get_n_after_1qbit(i,gate.qubit_numbers[0],tensor_control,&n_after,&i_sub);\n        *num_js = 1;\n        if (i_sub==0) {\n            // Diagonal element\n            js[0] = i;\n            vals[0] = 1;\n            \n        } else if (i_sub==1){\n            // Diagonal element\n            js[0] = i;\n            vals[0] = PETSC_i;\n            \n        } else {\n            if (nid==0){\n                printf(\"ERROR! S gate is only defined for qubits\\n\");\n                exit(0);\n            }\n        }\n    } else {\n        /*\n         * U* cross U\n         * To calculate this, we first take our i_global, convert\n         * it to i1 (for U*) and i2 (for U) within their own\n         * part of the Hilbert space. pWe then treat i1 and i2 as\n         * global i's for the matrices U* and U themselves, which\n         * gives us j's for those matrices. We then expand the j's\n         * to get the full space representation, using the normal\n         * tensor product.\n         */\n        \n        /* Calculate i1, i2 */\n        i1 = i/total_levels;\n        i2 = i%total_levels;\n        \n        /* Now, get js for U* (i1) by calling this function */\n        S_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1);\n        \n        /* Now, get js for U (i2) by calling this function */\n        S_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1);\n        \n        /*\n         * Combine j's to get U* cross U\n         * Must do all possible permutations\n         */\n        *num_js = 0;\n        for(k1=0;k1<num_js_i1;k1++){\n            for(k2=0;k2<num_js_i2;k2++){\n                js[*num_js] = total_levels * js_i1[k1] + js_i2[k2];\n                //Need to take complex conjugate to get true U*\n                vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2];\n                \n                *num_js = *num_js + 1;\n            }\n        }\n    }\n    return;\n}\n\nvoid _get_n_after_2qbit(PetscInt *i,int qubit_numbers[],PetscInt tensor_control,PetscInt *n_after, PetscInt *control, PetscInt *moved_system, PetscInt *i_sub){\n  operator this_op1,this_op2;\n  PetscInt n_before1,n_before2,extra_after,my_levels=4,j1; //4 is hardcoded because 2 qbits\n  if (tensor_control==1) {\n    extra_after = total_levels;\n  } else {\n    extra_after = 1;\n  }\n\n  //Two qubit gates\n  this_op1 = subsystem_list[qubit_numbers[0]];\n  this_op2 = subsystem_list[qubit_numbers[1]];\n  if (this_op1->my_levels * this_op2->my_levels != 4) {\n    //Check that it is a two level system\n    if (nid==0){\n      printf(\"ERROR! Two qubit gates can only affect two 2-level systems (global_i)\\n\");\n      exit(0);\n    }\n  }\n\n  n_before1  = this_op1->n_before;\n  n_before2  = this_op2->n_before;\n\n  *control = 0;\n  *moved_system = qubit_numbers[1];\n\n  /* 2 is hardcoded because CNOT gates are for qubits, which have 2 levels */\n  /* 4 is hardcoded because 2 qubits with 2 levels each */\n  *n_after   = total_levels/(4*n_before1)*extra_after;\n\n  /*\n   * Check which is the control and which is the target,\n   * flip if need be.\n   */\n  if (n_before2<n_before1) {\n    *n_after   = total_levels/(4*n_before2);\n    *control   = 1;\n    *moved_system = qubit_numbers[0];\n    n_before1 = n_before2;\n  }\n  /*\n   * Permute to temporary basis\n   * Get the i_sub in the permuted basis\n   */\n  _change_basis_ij_pair(i,&j1,qubit_numbers[*control]+1,*moved_system); // j1 useless here\n\n  *i_sub = *i/(*n_after)%my_levels; //Use integer arithmetic to get floor function\n\n  return;\n}\n\nvoid _get_n_after_1qbit(PetscInt i,int qubit_number,PetscInt tensor_control,PetscInt *n_after,PetscInt *i_sub){\n  operator this_op1;\n  PetscInt extra_after;\n  if (tensor_control==1) {\n    extra_after = total_levels;\n  } else {\n    extra_after = 1;\n  }\n\n  //Get the system this is affecting\n  this_op1 = subsystem_list[qubit_number];\n  if (this_op1->my_levels!=2) {\n    //Check that it is a two level system\n    if (nid==0){\n      printf(\"ERROR! Single qubit gates can only affect 2-level systems\\n\");\n      exit(0);\n    }\n  }\n  *n_after = total_levels/(this_op1->my_levels*this_op1->n_before)*extra_after;\n  *i_sub = i/(*n_after)%this_op1->my_levels; //Use integer arithmetic to get floor function\n\n  return;\n}\n\n// Check that the gate type is valid and set the number of qubits\nvoid _check_gate_type(gate_type my_gate_type,int *num_qubits){\n\n  if (my_gate_type==HADAMARD||my_gate_type==SIGMAX||my_gate_type==SIGMAY||my_gate_type==SIGMAZ||my_gate_type==EYE||\n      my_gate_type==RZ||my_gate_type==RX||my_gate_type==RY||my_gate_type==U3||my_gate_type==PHASESHIFT||my_gate_type==T||my_gate_type==TDAG||my_gate_type==S) {\n    *num_qubits = 1;\n  } else if (my_gate_type==CNOT||my_gate_type==CXZ||my_gate_type==CZ||my_gate_type==CmZ||my_gate_type==CZX||my_gate_type==SWAP){\n    *num_qubits = 2;\n  } else {\n    if (nid==0){\n      printf(\"ERROR! Gate type not recognized\\n\");\n      exit(0);\n    }\n  }\n\n}\n/*\n * Put the gate function pointers into an array\n */\nvoid _initialize_gate_function_array(){\n  _get_val_j_functions_gates[CZX+_min_gate_enum] = CZX_get_val_j_from_global_i;\n  _get_val_j_functions_gates[CmZ+_min_gate_enum] = CmZ_get_val_j_from_global_i;\n  _get_val_j_functions_gates[CZ+_min_gate_enum] = CZ_get_val_j_from_global_i;\n  _get_val_j_functions_gates[CXZ+_min_gate_enum] = CXZ_get_val_j_from_global_i;\n  _get_val_j_functions_gates[CNOT+_min_gate_enum] = CNOT_get_val_j_from_global_i;\n  _get_val_j_functions_gates[HADAMARD+_min_gate_enum] = HADAMARD_get_val_j_from_global_i;\n  _get_val_j_functions_gates[SIGMAX+_min_gate_enum] = SIGMAX_get_val_j_from_global_i;\n  _get_val_j_functions_gates[SIGMAY+_min_gate_enum] = SIGMAY_get_val_j_from_global_i;\n  _get_val_j_functions_gates[SIGMAZ+_min_gate_enum] = SIGMAZ_get_val_j_from_global_i;\n  _get_val_j_functions_gates[EYE+_min_gate_enum] = EYE_get_val_j_from_global_i;\n  _get_val_j_functions_gates[RX+_min_gate_enum] = RX_get_val_j_from_global_i;\n  _get_val_j_functions_gates[RY+_min_gate_enum] = RY_get_val_j_from_global_i;\n  _get_val_j_functions_gates[RZ+_min_gate_enum] = RZ_get_val_j_from_global_i;\n  _get_val_j_functions_gates[U3+_min_gate_enum] = U3_get_val_j_from_global_i;\n  _get_val_j_functions_gates[SWAP+_min_gate_enum] = SWAP_get_val_j_from_global_i;\n  _get_val_j_functions_gates[PHASESHIFT+_min_gate_enum] = PHASESHIFT_get_val_j_from_global_i;\n  _get_val_j_functions_gates[T+_min_gate_enum] = T_get_val_j_from_global_i;\n  _get_val_j_functions_gates[TDAG+_min_gate_enum] = TDAG_get_val_j_from_global_i;\n  _get_val_j_functions_gates[S+_min_gate_enum] = S_get_val_j_from_global_i;\n}\n", "meta": {"hexsha": "1ca90ac558e934ff29655862b9329f4eee53ce25", "size": 129198, "ext": "c", "lang": "C", "max_stars_repo_path": "src/quantum_gates.c", "max_stars_repo_name": "sriharikrishna/QuaC", "max_stars_repo_head_hexsha": "679018a8f2642ca4c1fdf2b5eee275b4645bdbad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/quantum_gates.c", "max_issues_repo_name": "sriharikrishna/QuaC", "max_issues_repo_head_hexsha": "679018a8f2642ca4c1fdf2b5eee275b4645bdbad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/quantum_gates.c", "max_forks_repo_name": "sriharikrishna/QuaC", "max_forks_repo_head_hexsha": "679018a8f2642ca4c1fdf2b5eee275b4645bdbad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0442687747, "max_line_length": 159, "alphanum_fraction": 0.5716961563, "num_tokens": 38624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.02675928337948029, "lm_q1q2_score": 0.012128962236150643}}
{"text": "/// @file \n/// @brief shared pointers to gsl types\n/// @details We use gsl for linear algebra routines. However, the interface is C-like and is based on\n/// raw pointers. The file contains code to leverage on boost shared pointer and use it with gsl types\n/// such as vector and matrix.\n///\n/// @copyright (c) 2008 CSIRO\n/// Australia Telescope National Facility (ATNF)\n/// Commonwealth Scientific and Industrial Research Organisation (CSIRO)\n/// PO Box 76, Epping NSW 1710, Australia\n/// atnf-enquiries@csiro.au\n///\n/// This file is part of the ASKAP software distribution.\n///\n/// The ASKAP software distribution is free software: you can redistribute it\n/// and/or modify it under the terms of the GNU General Public License as\n/// published by the Free Software Foundation; either version 2 of the License,\n/// or (at your option) any later version.\n///\n/// This program is distributed in the hope that it will be useful,\n/// but WITHOUT ANY WARRANTY; without even the implied warranty of\n/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n/// GNU General Public License for more details.\n///\n/// You should have received a copy of the GNU General Public License\n/// along with this program; if not, write to the Free Software\n/// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA\n///\n/// @author Max Voronkov <maxim.voronkov@csiro.au>\n\n#ifndef ASKAP_SCIMATH_SHARED_GSL_TYPES_H\n#define ASKAP_SCIMATH_SHARED_GSL_TYPES_H\n\n// boost includes\n#include <boost/shared_ptr.hpp>\n#include <boost/static_assert.hpp>\n\n\n// gsl includes\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_eigen.h>\n\n\n// own includes\n#include \"askap/AskapError.h\"\n\nnamespace askap {\n\nnamespace utility {\n\n// typedefs for shared pointers, we can add more here when needed\n\n/// @brief shared pointer to gsl vector\n/// @ingroup utils\ntypedef boost::shared_ptr<gsl_vector> SharedGSLVector;\n\n/// @brief shared pointer to gsl matrix\n/// @ingroup utils\ntypedef boost::shared_ptr<gsl_matrix> SharedGSLMatrix;\n\n/// @brief custom deleter for gsl types\n/// @details This is a custom deleter class to allow deallocation of\n/// a gsl object. Exact operation should be present in specialised types\n/// @ingroup utils\ntemplate<typename GSLType> struct CustomGSLDeleter {\n    /// @brief this method frees the object\n    /// @param[in] obj pointer to gsl object\n    void operator()(GSLType *obj) const { BOOST_STATIC_ASSERT_MSG(sizeof(GSLType) == 0, \n                            \"Generic version is not supposed to be used - specialise it for your type\"); }\n};\n\n/// @brief specialised deleter for a gsl vector\n/// @ingroup utils\ntemplate<> struct CustomGSLDeleter<gsl_vector> {\n    /// @brief this method frees the object\n    /// @param[in] obj pointer to gsl vector\n    void operator()(gsl_vector *obj) const;\n};\n\n/// @brief specialised deleter for a gsl matrix\n/// @ingroup utils\ntemplate<> struct CustomGSLDeleter<gsl_matrix> {\n    /// @brief this method frees the object\n    /// @param[in] obj pointer to gsl matrix\n    void operator()(gsl_matrix *obj) const;\n};\n\n/// @brief specialised deleter for a gsl eigen_symmv_workspace\n/// @ingroup utils\ntemplate<> struct CustomGSLDeleter<gsl_eigen_symmv_workspace> {\n    /// @brief this method frees the object\n    /// @param[in] obj pointer to gsl eigen_symmv_workspace\n    void operator()(gsl_eigen_symmv_workspace *obj) const;\n};\n\n\n/// @brief templated helper method to wrap newly allocated gsl object \n/// @details This method processes a pointer to a gsl object and transfers the ownership (i.e. \n/// responsibility for deallocation to the boost shared pointer. Templates are used to automatically\n/// deduce the object type and add an appropriate deleter. \n/// @note the pointer passed as a parameter is tested to be non-zero. Otherwise an exception is thrown.\n/// @param[in] obj a pointer to gsl object\n/// @return boost shared pointer to the object\ntemplate<typename GSLType>\ninline boost::shared_ptr<GSLType> createGSLObject(GSLType *obj) \n   { ASKAPASSERT(obj); return boost::shared_ptr<GSLType>(obj, CustomGSLDeleter<GSLType>()); }\n\n\n/// @brief helper method to allocate gsl vector\n/// @details This method allocates a gsl vector of requested length and returns a\n/// shared pointer. \n/// @param[in] size size of the vector\n/// @return shared pointer to gsl vector\ninline SharedGSLVector createGSLVector(size_t size) { return createGSLObject(gsl_vector_alloc(size));}\n\n\n/// @brief helper method to allocate gsl matrix\n/// @details This method allocates a gsl matrix of requested shape and returns a\n/// shared pointer. \n/// @param[in] nrow number of rows\n/// @param[in] ncol number of columns\n/// @return shared pointer to gsl matrix\ninline SharedGSLMatrix createGSLMatrix(size_t nrow, size_t ncol) { return createGSLObject(gsl_matrix_alloc(nrow,ncol));}\n\n} // namespace utility\n\n} // namespace askap\n\n#endif // #ifndef ASKAP_SCIMATH_SHARED_GSL_TYPES_H\n\n", "meta": {"hexsha": "8e70ef5aa18a44f03652c4626e89ec47b804d437", "size": 4927, "ext": "h", "lang": "C", "max_stars_repo_path": "Code/Base/scimath/current/utils/SharedGSLTypes.h", "max_stars_repo_name": "rtobar/askapsoft", "max_stars_repo_head_hexsha": "6bae06071d7d24f41abe3f2b7f9ee06cb0a9445e", "max_stars_repo_licenses": ["BSL-1.0", "Apache-2.0", "OpenSSL"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-18T08:37:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-18T08:37:43.000Z", "max_issues_repo_path": "Code/Base/scimath/current/utils/SharedGSLTypes.h", "max_issues_repo_name": "ATNF/askapsoft", "max_issues_repo_head_hexsha": "d839c052d5c62ad8a511e58cd4b6548491a6006f", "max_issues_repo_licenses": ["BSL-1.0", "Apache-2.0", "OpenSSL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/Base/scimath/current/utils/SharedGSLTypes.h", "max_forks_repo_name": "ATNF/askapsoft", "max_forks_repo_head_hexsha": "d839c052d5c62ad8a511e58cd4b6548491a6006f", "max_forks_repo_licenses": ["BSL-1.0", "Apache-2.0", "OpenSSL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3257575758, "max_line_length": 120, "alphanum_fraction": 0.7391922062, "num_tokens": 1194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.28776780354463427, "lm_q2_score": 0.042087729717900216, "lm_q1q2_score": 0.012111493537100376}}
{"text": "#ifndef ___BEST_SCORE_SO_FAR_FOR_NLOPT_H____\n#define ___BEST_SCORE_SO_FAR_FOR_NLOPT_H____\n\n#include \"OptimizedNonlinearController.h\"\n#include <mutex>\n#include <nlopt.h>\n#include <thread>\n\n\nclass BestNLOptScoreSoFar\n{\npublic:\n\tstd::mutex my_mutex;\n\tstd::thread* thethread;\n\t\n\tbool force_stop;\n\tnlopt_opt opt;\n\t\n\tMyNLOPTdata my_nloptdata;\n\tint num_iterations_so_far;\n\t\n\tdouble* my_best_params;\n\tdouble my_best_score;\n\t\n\tdouble original_starting_score;\n\tint which_algorithm;\n\t\n\tBestNLOptScoreSoFar() : my_best_params(nullptr), thethread(nullptr), opt(nullptr), force_stop(false) {}\n\tBestNLOptScoreSoFar(const BestNLOptScoreSoFar & other) : my_nloptdata(other.my_nloptdata), thethread(other.thethread), my_best_params(other.my_best_params), force_stop(other.force_stop), opt(other.opt) {}\n\t\n\tvoid Reset() {\n\t\tnum_iterations_so_far = 0;\n\t\tif(my_best_params != nullptr) {free(my_best_params); my_best_params = nullptr;}\n\t\tmy_best_score = 1e12;\n\t\toriginal_starting_score = 1e12;\n\t\twhich_algorithm = 0;\n\t\tforce_stop = false;\n\t\tif(opt != nullptr) {nlopt_destroy(opt);}\n\t\topt = nullptr;\n\t}\n};\n\n\n\n#endif\n", "meta": {"hexsha": "dce27a03569e8f153f23a9b9778a38ad8a3e2b44", "size": 1093, "ext": "h", "lang": "C", "max_stars_repo_path": "Source/NLControllerOptimization/BestNLOptScoreSoFar.h", "max_stars_repo_name": "jasonbunk/InvertedPendulumVisualControl", "max_stars_repo_head_hexsha": "90577a4abb2215065845d0f878a85cc345b1ae98", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Source/NLControllerOptimization/BestNLOptScoreSoFar.h", "max_issues_repo_name": "jasonbunk/InvertedPendulumVisualControl", "max_issues_repo_head_hexsha": "90577a4abb2215065845d0f878a85cc345b1ae98", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/NLControllerOptimization/BestNLOptScoreSoFar.h", "max_forks_repo_name": "jasonbunk/InvertedPendulumVisualControl", "max_forks_repo_head_hexsha": "90577a4abb2215065845d0f878a85cc345b1ae98", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7608695652, "max_line_length": 205, "alphanum_fraction": 0.7703568161, "num_tokens": 304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583475, "lm_q2_score": 0.024798161637017424, "lm_q1q2_score": 0.012108530561217783}}
{"text": "#pragma once\n\n#include \"concepts/MemoryIntrospection.h\"\n#include \"math/Vector3.h\"\n#include \"pointcloud/PointAttributes.h\"\n\n#include <gsl/gsl>\n#include <optional>\n#include <vector>\n\n// TECH_DEBT Make attributes more dynamic (map<AttributeType, GenericAttribute*>\n// or something like that)\n\n/// <summary>\n/// Buffer structure that stores point attributes (position, color etc.) for\n/// multiple points at once in a structure-of-array fashion. Compared to storing\n/// all points as Point structures, this has better performance for data access\n/// </summary>\nstruct PointBuffer\n{\n  struct PointConstReference;\n\n  /// <summary>\n  /// Mutable indirect reference to a single point inside the PointBuffer\n  /// </summary>\n  struct PointReference\n  {\n    friend struct PointBuffer;\n    friend struct PointConstReference;\n\n    PointReference();\n    PointReference(const PointReference&) = default;\n    PointReference& operator=(const PointReference&) = default;\n\n    Vector3<double>& position() const;\n    Vector3<uint8_t>* rgbColor() const;\n    Vector3<float>* normal() const;\n    uint16_t* intensity() const;\n    uint8_t* classification() const;\n    uint8_t* edge_of_flight_line() const;\n    double* gps_time() const;\n    uint8_t* number_of_returns() const;\n    uint8_t* return_number() const;\n    uint16_t* point_source_id() const;\n    uint8_t* scan_direction_flag() const;\n    int8_t* scan_angle_rank() const;\n    uint8_t* user_data() const;\n\n  private:\n    PointReference(PointBuffer* pointBuffer, size_t index);\n\n    PointBuffer* _pointBuffer;\n    size_t _index;\n  };\n\n  /// <summary>\n  /// Constant indirect reference to a single point inside the PointBuffer\n  /// </summary>\n  struct PointConstReference\n  {\n    friend struct PointBuffer;\n\n    PointConstReference();\n    PointConstReference(const PointReference& point_reference);\n    PointConstReference(const PointConstReference&) = default;\n    PointConstReference& operator=(const PointConstReference&) = default;\n\n    const Vector3<double>& position() const;\n    const Vector3<uint8_t>* rgbColor() const;\n    const Vector3<float>* normal() const;\n    const uint16_t* intensity() const;\n    const uint8_t* classification() const;\n    const uint8_t* edge_of_flight_line() const;\n    const double* gps_time() const;\n    const uint8_t* number_of_returns() const;\n    const uint8_t* return_number() const;\n    const uint16_t* point_source_id() const;\n    const uint8_t* scan_direction_flag() const;\n    const int8_t* scan_angle_rank() const;\n    const uint8_t* user_data() const;\n\n  private:\n    PointConstReference(PointBuffer const* pointBuffer, size_t index);\n\n    PointBuffer const* _pointBuffer;\n    size_t _index;\n  };\n\n  /// <summary>\n  /// Creates an empty point buffer\n  /// </summary>\n  PointBuffer();\n\n  /// <summary>\n  /// Creates a PointBuffer from the given range of PointReferences\n  /// </summary>\n  explicit PointBuffer(gsl::span<PointReference> points);\n  /// <summary>\n  /// Creates a PointBuffer from the given range of PointConstReferences\n  /// </summary>\n  explicit PointBuffer(gsl::span<PointConstReference> points);\n\n  /// <summary>\n  /// Creates a new PointBuffer storing count points. For all passed attribute\n  /// vectors, their count has to be equal to the specified count, otherwise a\n  /// invalid_argument error is thrown\n  /// </summary>\n  PointBuffer(size_t count,\n              std::vector<Vector3<double>> positions,\n              std::vector<Vector3<uint8_t>> rgbColors = {},\n              std::vector<Vector3<float>> normals = {},\n              std::vector<uint16_t> intensities = {},\n              std::vector<uint8_t> classifications = {},\n              std::vector<uint8_t> edge_of_flight_lines = {},\n              std::vector<double> gps_times = {},\n              std::vector<uint8_t> number_of_returns = {},\n              std::vector<uint8_t> return_numbers = {},\n              std::vector<uint16_t> point_source_ids = {},\n              std::vector<uint8_t> scan_direction_flags = {},\n              std::vector<int8_t> scan_angle_ranks = {},\n              std::vector<uint8_t> user_data = {});\n\n  /**\n   * Creates a new PointBuffer storing 'count' default-constructed points with the\n   * attributes given by 'attributes'\n   */\n  PointBuffer(size_t count, const PointAttributes& attributes);\n\n  PointBuffer(const PointBuffer&) = default;\n  PointBuffer(PointBuffer&&) = default;\n\n  PointBuffer& operator=(const PointBuffer&) = default;\n  PointBuffer& operator=(PointBuffer&&) = default;\n\n  /// <summary>\n  /// Push a single point into this PointBuffer. If the point has attributes\n  /// that are not defined in this PointBuffer they are ignored. Attributes from\n  /// this PointBuffer that are not defined in the given point are filled with\n  /// default values\n  /// </summary>\n  void push_point(PointConstReference point);\n\n  /// <summary>\n  /// Returns a constant indirect reference to the point with the given index\n  /// </summary>\n  PointConstReference get_point(size_t point_index) const;\n\n  /// <summary>\n  /// Returns a mutable indirect reference to the point with the given index\n  /// </summary>\n  PointReference get_point(size_t point_index);\n\n  /// <summary>\n  /// Appends the contents of the given PointBuffer to this PointBuffer. This\n  /// will copy all attributes that exist from the given buffer into this\n  /// buffer. Attributes that exist in this buffer but not in the other buffer\n  /// are filled with default values\n  /// </summary>\n  void append_buffer(const PointBuffer& other);\n\n  /**\n   * Applies a new attribute schema to this PointBuffer. Clears all attributes that are not in the\n   * new schema and fills all attributes that are in the new schema but weren't in the PointBuffers\n   * old schema (i.e. the state of the PointBuffer prior to calling 'apply_schema') with default\n   * values\n   */\n  void apply_schema(const PointAttributes& schema);\n\n  size_t count() const { return _count; }\n  bool empty() const { return _count == 0; }\n  void clear();\n  void shrink_to_fit();\n  void resize(size_t new_size);\n\n  std::vector<Vector3<double>>& positions() { return _positions; }\n  std::vector<Vector3<uint8_t>>& rgbColors() { return _rgbColors; }\n  std::vector<Vector3<float>>& normals() { return _normals; }\n  std::vector<uint16_t>& intensities() { return _intensities; }\n  std::vector<uint8_t>& classifications() { return _classifications; }\n\n  auto& edge_of_flight_lines() { return _edge_of_flight_lines; }\n  auto& gps_times() { return _gps_times; }\n  auto& number_of_returns() { return _number_of_returns; }\n  auto& return_numbers() { return _return_numbers; }\n  auto& point_source_ids() { return _point_source_ids; }\n  auto& scan_direction_flags() { return _scan_direction_flags; }\n  auto& scan_angle_ranks() { return _scan_angle_ranks; }\n  auto& user_data() { return _user_data; }\n\n  const std::vector<Vector3<double>>& positions() const { return _positions; }\n  const std::vector<Vector3<uint8_t>>& rgbColors() const { return _rgbColors; }\n  const std::vector<Vector3<float>>& normals() const { return _normals; }\n  const std::vector<uint16_t>& intensities() const { return _intensities; }\n  const std::vector<uint8_t>& classifications() const { return _classifications; }\n\n  const auto& edge_of_flight_lines() const { return _edge_of_flight_lines; }\n  const auto& gps_times() const { return _gps_times; }\n  const auto& number_of_returns() const { return _number_of_returns; }\n  const auto& return_numbers() const { return _return_numbers; }\n  const auto& point_source_ids() const { return _point_source_ids; }\n  const auto& scan_direction_flags() const { return _scan_direction_flags; }\n  const auto& scan_angle_ranks() const { return _scan_angle_ranks; }\n  const auto& user_data() const { return _user_data; }\n\n  bool hasColors() const;\n  bool hasNormals() const;\n  bool hasIntensities() const;\n  bool hasClassifications() const;\n  bool has_edge_of_flight_lines() const;\n  bool has_gps_times() const;\n  bool has_number_of_returns() const;\n  bool has_return_numbers() const;\n  bool has_point_source_ids() const;\n  bool has_scan_direction_flags() const;\n  bool has_scan_angle_ranks() const;\n  bool has_user_data() const;\n\n  void verify() const;\n\n  /// <summary>\n  /// Returns the raw size in bytes of the contents (positions, normals etc.) of\n  /// this PointBuffer. This does NOT include the in-memory size of a\n  /// PointBuffer structure itself, but rather the allocated memory of all the\n  /// vectors of the PointBuffer\n  /// </summary>\n  size_t content_byte_size() const;\n\n  struct PointIterator\n  {\n    PointIterator(PointBuffer& pointBuffer, size_t idx);\n\n    PointReference operator*() const;\n    PointIterator& operator++();\n    PointIterator operator++(int);\n    PointIterator& operator--();\n    PointIterator operator--(int);\n    PointIterator operator+(std::ptrdiff_t count) const;\n    PointIterator operator-(std::ptrdiff_t count) const;\n    PointIterator& operator+=(std::ptrdiff_t count);\n    PointIterator& operator-=(std::ptrdiff_t count);\n    friend std::ptrdiff_t operator-(const PointIterator& l, const PointIterator& r);\n    PointReference operator[](std::ptrdiff_t idx) const;\n\n    bool operator==(const PointIterator& other) const;\n    bool operator!=(const PointIterator& other) const;\n    friend bool operator<(const PointIterator& l, const PointIterator& r);\n    friend bool operator<=(const PointIterator& l, const PointIterator& r);\n    friend bool operator>(const PointIterator& l, const PointIterator& r);\n    friend bool operator>=(const PointIterator& l, const PointIterator& r);\n\n  private:\n    PointBuffer* _pointBuffer;\n    size_t _index;\n  };\n\n  struct PointConstIterator\n  {\n    PointConstIterator(PointBuffer const& pointBuffer, size_t idx);\n\n    PointConstReference operator*() const;\n    PointConstIterator& operator++();\n    PointConstIterator operator++(int);\n    PointConstIterator& operator--();\n    PointConstIterator operator--(int);\n    PointConstIterator operator+(std::ptrdiff_t count) const;\n    PointConstIterator operator-(std::ptrdiff_t count) const;\n    PointConstIterator& operator+=(std::ptrdiff_t count);\n    PointConstIterator& operator-=(std::ptrdiff_t count);\n    friend std::ptrdiff_t operator-(const PointConstIterator& l, const PointConstIterator& r);\n    PointConstReference operator[](std::ptrdiff_t idx) const;\n\n    bool operator==(const PointConstIterator& other) const;\n    bool operator!=(const PointConstIterator& other) const;\n    friend bool operator<(const PointConstIterator& l, const PointConstIterator& r);\n    friend bool operator<=(const PointConstIterator& l, const PointConstIterator& r);\n    friend bool operator>(const PointConstIterator& l, const PointConstIterator& r);\n    friend bool operator>=(const PointConstIterator& l, const PointConstIterator& r);\n\n  private:\n    PointBuffer const* _pointBuffer;\n    size_t _index;\n  };\n\n  PointIterator begin();\n  PointIterator end();\n\n  PointConstIterator begin() const;\n  PointConstIterator end() const;\n\nprivate:\n  size_t _count;\n  std::vector<Vector3<double>> _positions;\n  std::vector<Vector3<uint8_t>> _rgbColors;\n  std::vector<Vector3<float>> _normals;\n  std::vector<uint16_t> _intensities;\n  std::vector<uint8_t> _classifications;\n  std::vector<uint8_t> _edge_of_flight_lines;\n  std::vector<double> _gps_times;\n  std::vector<uint8_t> _number_of_returns;\n  std::vector<uint8_t> _return_numbers;\n  std::vector<uint16_t> _point_source_ids;\n  std::vector<uint8_t> _scan_direction_flags;\n  std::vector<int8_t> _scan_angle_ranks;\n  std::vector<uint8_t> _user_data;\n};\n\nnamespace std {\ntemplate<>\nstruct iterator_traits<::PointBuffer::PointIterator>\n{\n  using difference_type = std::ptrdiff_t;\n  using value_type = ::PointBuffer::PointReference;\n  using iterator_category = std::random_access_iterator_tag;\n};\n\ntemplate<>\nstruct iterator_traits<::PointBuffer::PointConstIterator>\n{\n  using difference_type = std::ptrdiff_t;\n  using value_type = ::PointBuffer::PointConstReference;\n  using iterator_category = std::random_access_iterator_tag;\n};\n} // namespace std\n\nnamespace concepts {\n\nnamespace detail {\ntemplate<>\nconstexpr bool has_constant_size_impl<::PointBuffer> = false;\n}\n\ntemplate<>\ninline unit::byte\nsize_in_memory(PointBuffer const& point_buffer)\n{\n  return (sizeof(size_t) * boost::units::information::byte) +\n         size_in_memory(point_buffer.positions()) + size_in_memory(point_buffer.rgbColors()) +\n         size_in_memory(point_buffer.normals()) + size_in_memory(point_buffer.intensities()) +\n         size_in_memory(point_buffer.classifications());\n}\n} // namespace concepts", "meta": {"hexsha": "c4b511ee0d7fbb5e25b3784b216ddbea49857f49", "size": 12551, "ext": "h", "lang": "C", "max_stars_repo_path": "schwarzwald/core/datastructures/PointBuffer.h", "max_stars_repo_name": "igd-geo/schwarzwald", "max_stars_repo_head_hexsha": "e3e041f87c93985394444ee056ce8ba7ae62194b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2021-01-06T14:16:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T00:15:17.000Z", "max_issues_repo_path": "schwarzwald/core/datastructures/PointBuffer.h", "max_issues_repo_name": "igd-geo/schwarzwald", "max_issues_repo_head_hexsha": "e3e041f87c93985394444ee056ce8ba7ae62194b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-25T08:37:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T06:28:06.000Z", "max_forks_repo_path": "schwarzwald/core/datastructures/PointBuffer.h", "max_forks_repo_name": "igd-geo/schwarzwald", "max_forks_repo_head_hexsha": "e3e041f87c93985394444ee056ce8ba7ae62194b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T13:50:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T11:45:45.000Z", "avg_line_length": 36.8064516129, "max_line_length": 99, "alphanum_fraction": 0.7209784081, "num_tokens": 2965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.02479815780821447, "lm_q1q2_score": 0.012108528691676874}}
{"text": "#include <pygsl/solver.h>\n#include <pygsl/utils.h>\n#include <gsl/gsl_odeiv.h>\n\nstatic const char odeiv_step_type_name   [] = \"Odeiv-Step\";\nstatic const char odeiv_control_type_name[] = \"Odeiv-Control\";\nstatic const char odeiv_evolve_type_name [] = \"Odeiv-Evolve\";\n\nconst char  * filename = __FILE__;\nPyObject *module = NULL;\n\nstruct _mycontrol{\n     gsl_odeiv_control *control;\n     gsl_odeiv_step    *step;\n     PyGSL_solver      *step_ob;\n};\ntypedef struct _mycontrol mycontrol;\n\nstruct _myevolve{\n     gsl_odeiv_evolve  *evolve;\n     gsl_odeiv_control *control;\n     gsl_odeiv_step    *step;\n     PyGSL_solver      *control_ob;\n     PyGSL_solver      *step_ob;\n};\ntypedef struct _myevolve myevolve;\n\nvoid\n_mycontrol_free(mycontrol *c)\n{\n     FUNC_MESS_BEGIN();     \n     gsl_odeiv_control_free(c->control);\n     if(c->step_ob){\n\t  DEBUG_MESS(3, \"Decreasing step @ %p refcont %d\", c->step_ob,\n\t\t     c->step_ob->ob_refcnt);\n\t  Py_DECREF(c->step_ob);\n     }else{\n\t  DEBUG_MESS(3, \"Freeing GSL Step @ %p\", c->step);\n\t  gsl_odeiv_step_free(c->step);\n     }     \n     memset(c, 0, sizeof(mycontrol));\n     free(c);\n     c = NULL;\n     FUNC_MESS_END();\n}\n\nvoid\n_myevolve_free(myevolve *c)\n{\n     FUNC_MESS_BEGIN();\n     gsl_odeiv_evolve_free(c->evolve);\n     if(c->control_ob){\n\t  DEBUG_MESS(3, \"Decreasing control @ %p refcont %d\", c->control_ob,\n\t\t     c->control_ob->ob_refcnt);\n\t  Py_DECREF(c->control_ob);\n     }else{\n\t  DEBUG_MESS(3, \"Freeing GSL Control @ %p\", c->control);\n\t  gsl_odeiv_control_free(c->control);\n     }\n     if(c->step_ob){\n\t  DEBUG_MESS(3, \"Decreasing step @ %p refcont %d\", c->step_ob,\n\t\t     c->step_ob->ob_refcnt);\n\t  Py_DECREF(c->step_ob);\n     }else{\n\t  DEBUG_MESS(3, \"Freeing GSL Step @ %p\", c->step);\n\t  gsl_odeiv_step_free(c->step);\n     }\n     memset(c, 0, sizeof(myevolve));\n     free(c);\n     c = NULL;\n     FUNC_MESS_END();\n}\n\nconst char *\nPyGSL_mycontrol_getname(void *v)\n{\n     mycontrol *c = (mycontrol *) v;\n     return gsl_odeiv_control_name(c->control);\n}\n\n\n\n\n#define _PyGSL_ODEIV_GENERIC_CHECK(ob, type_desc) \\\n  ((PyGSL_solver_check((ob))) && (((PyGSL_solver *)ob)->mstatic->type_name == (type_desc)))\n\n#define PyGSL_ODEIV_STEP_Check(ob)    _PyGSL_ODEIV_GENERIC_CHECK((ob), odeiv_step_type_name)\n#define PyGSL_ODEIV_CONTROL_Check(ob) _PyGSL_ODEIV_GENERIC_CHECK((ob), odeiv_control_type_name)\n#define PyGSL_ODEIV_EVOLVE_Check(ob)  _PyGSL_ODEIV_GENERIC_CHECK((ob), odeiv_evolve_type_name)\n\n\nstatic const char *this_file = __FILE__;\nstatic char odeiv_step_init_err_msg[] = \"odeiv_step.__init__\";\nstatic char odeiv_step_apply_doc[] =  \"XXX Documentation missing\\n\"; \nstatic char odeiv_step_order_doc[] =  \"XXX Documentation missing\\n\"; \n       \nstatic char odeiv_control_hadjust_doc[] =  \"XXX Documentation missing\\n\"; \nstatic char odeiv_evolve_apply_doc[] =  \"XXX Documentation missing\\n\"; \n\n\nstatic char  PyGSL_odeiv_step_doc[] = \"XXX Documentation missing\\n\"; \nstatic char  PyGSL_odeiv_control_doc[] = \"XXX Documentation missing\\n\";\nstatic char  PyGSL_odeiv_evolve_doc[] = \"XXX Documentation missing\\n\"; \n       \n\n/*---------------------------------------------------------------------------\n  Wrapper functions to push call the approbriate Python Objects\n  ---------------------------------------------------------------------------*/\nstatic int \nPyGSL_odeiv_func(double t, const double y[], double f[], void *params)\n{\n    int dimension, flag = GSL_FAILURE;\n\n    PyObject *arglist = NULL, *result = NULL;\n    PyArrayObject *yo = NULL;\n    PyGSL_solver * step;\n    gsl_vector_view yv, fv;\n    PyGSL_error_info  info;\n\n    FUNC_MESS_BEGIN();\n\n    step = (PyGSL_solver *) params;\n    if(!PyGSL_ODEIV_STEP_Check(step)){\n\t  PyGSL_add_traceback(module, this_file, __FUNCTION__, \n\t\t\t      __LINE__ - 2);\n\t  pygsl_error(\"Param not a step type!\", \n\t\t    this_file, __LINE__ -2, GSL_EFAULT);\n\t  goto fail;\n    }\n    dimension =  step->problem_dimensions[0];\n\n\n    /* Do I need to copy the array ??? */\n    yv = gsl_vector_view_array((double *) y, dimension);\n    yo = PyGSL_copy_gslvector_to_pyarray(&yv.vector);\n    if (yo == NULL) goto fail;\n\n    FUNC_MESS(\"\\t\\tBuild args\");\n    arglist = Py_BuildValue(\"(dOO)\", t, yo, step->args);\n    FUNC_MESS(\"\\t\\tEnd Build args\");\n\n    info.callback = step->cbs[0];\n    info.message  = \"odeiv_func\";\n    result  = PyEval_CallObject(step->cbs[0], arglist);\n\n\n    if((flag = PyGSL_CHECK_PYTHON_RETURN(result, 1, &info)) != GSL_SUCCESS){\n\t  goto fail;\n     }\n    info.argnum = 1;\n    fv = gsl_vector_view_array(f, dimension);\n    if((flag = PyGSL_copy_pyarray_to_gslvector(&fv.vector, result, dimension, \n\t\t\t\t\t       &info)) != GSL_SUCCESS){\n\t  goto fail;\n     }     \n     \n\n    Py_DECREF(arglist);    arglist = NULL;\n    Py_DECREF(yo);         yo = NULL;\n    Py_DECREF(result);     result = NULL;\n    FUNC_MESS_END();\n    return GSL_SUCCESS;\n\n fail:\n    FUNC_MESS(\"    IN Fail BEGIN\");\n    Py_XDECREF(yo);\n    Py_XDECREF(result);\n    Py_XDECREF(arglist);\n    assert(flag != GSL_SUCCESS);\n    FUNC_MESS(\"    IN Fail END\");\n    if(step->isset)\n\t longjmp(step->buffer, flag);\n    return flag;\n}\n\nstatic int \nPyGSL_odeiv_jac(double t, const double y[], double *dfdy, double dfdt[], \n\t\tvoid *params)\n{\n    int dimension, flag = GSL_FAILURE;\n    PyGSL_solver *step;\n    PyGSL_error_info  info;\n    \n    PyObject *arglist = NULL, *result = NULL, *tmp=NULL;\n    PyArrayObject *yo = NULL;\n\n    gsl_vector_view yv, dfdtv;\n    gsl_matrix_view dfdyv;\n\n\n    FUNC_MESS_BEGIN();\n    \n    step = (PyGSL_solver *) params;\n    if(!PyGSL_ODEIV_STEP_Check(step)){\n\t  PyGSL_add_traceback(module, this_file, __FUNCTION__, \n\t\t\t      __LINE__ - 2);\n\t  pygsl_error(\"Param not a step type!\", \n\t\t    this_file, __LINE__ -2, GSL_EFAULT);\n\t  goto fail;\n    }\n    dimension = step->problem_dimensions[0];\n\n\n\n    yv = gsl_vector_view_array((double *) y, dimension);\n    yo = PyGSL_copy_gslvector_to_pyarray(&yv.vector);\n    if (yo == NULL) goto fail;\n\n\n    arglist = Py_BuildValue(\"(dOO)\", t, yo, step->args);\n\n\n    result  = PyEval_CallObject(step->cbs[1], arglist);\n\n    info.callback = step->cbs[1];\n    info.message  = \"odeiv_jac\";\n    if((flag = PyGSL_CHECK_PYTHON_RETURN(result, 2, &info)) != GSL_SUCCESS){\n\t  goto fail;\n     }\n\n    info.argnum = 1;\n    tmp = PyTuple_GET_ITEM(result, 0);\n    dfdyv = gsl_matrix_view_array((double *) dfdy, dimension, dimension);\n    if((flag = PyGSL_copy_pyarray_to_gslmatrix(&dfdyv.matrix, tmp, dimension, dimension, &info)) != GSL_SUCCESS){\n\t  goto fail;\n    }     \n    \n    info.argnum = 2;\n    tmp = PyTuple_GET_ITEM(result, 1);\n    dfdtv = gsl_vector_view_array((double *) dfdt, dimension);\n    if((flag = PyGSL_copy_pyarray_to_gslvector(&dfdtv.vector, tmp, dimension, &info)) != GSL_SUCCESS){\n\t  goto fail;\n    }     \n\n    \n\n      \n    Py_DECREF(arglist);    arglist = NULL;\n    Py_DECREF(result);     result = NULL;\n    Py_DECREF(yo);         yo = NULL;\n    FUNC_MESS_END();\n    return GSL_SUCCESS;\n fail:\n    FUNC_MESS(\"IN Fail\");\n    assert(flag != GSL_SUCCESS);\n    longjmp(step->buffer, flag);\n    return flag;\n}\n\n\n/* Wrappers for the evaluation of the system */\nstatic PyObject *\nPyGSL_odeiv_step_apply(PyGSL_solver *self, PyObject *args)\n{\n    PyObject *result = NULL;\n    PyObject *y0_o = NULL, *dydt_in_o = NULL;\n    PyArrayObject *volatile y0 = NULL, * volatile yerr = NULL, \n\t *volatile dydt_in = NULL, *volatile dydt_out = NULL,\n\t *volatile yout = NULL;\n\n    double t=0, h=0, *volatile dydt_in_d;\n    int  r, flag;\n    PyGSL_array_index_t dimension;\n\n    FUNC_MESS_BEGIN();\n    assert(PyGSL_ODEIV_STEP_Check(self));\n    if(! PyArg_ParseTuple(args, \"ddOOO\", &t, &h, &y0_o,  &dydt_in_o)){\n      return NULL;\n    }\n\n\n    dimension = self->problem_dimensions[0];\n    y0 = PyGSL_vector_check(y0_o, dimension, PyGSL_DARRAY_CINPUT(1), NULL, NULL);\n    if(y0 == NULL) goto fail;\n\n\n    if (Py_None == dydt_in_o){\n\t dydt_in_d = NULL;\n    }else{\n\t dydt_in = PyGSL_vector_check(dydt_in_o, dimension, PyGSL_DARRAY_CINPUT(2), NULL, NULL);\n\t if(dydt_in == NULL) goto fail;\n\t dydt_in_d = (double *) dydt_in->data;\n    }\n\n\n    dydt_out =  PyGSL_New_Array(1, &dimension, PyArray_DOUBLE);\n    if (dydt_out == NULL) goto fail;\n\n    yerr = PyGSL_New_Array(1, &dimension, PyArray_DOUBLE);\n    if(yerr == NULL) goto fail;\n\n\n    yout = (PyArrayObject *) PyGSL_Copy_Array(y0);\n    if(yout == NULL) goto fail;\n\n\n    self->isset = 0;\n    if((flag=setjmp(self->buffer)) == 0){\n\t  FUNC_MESS(\"\\t\\t Setting Jmp Buffer\");\n\t  self->isset = 1;\n    } else {\n\t  FUNC_MESS(\"\\t\\t Returning from Jmp Buffer\");\n\t  self->isset = 0;\n\t  goto fail;\n    }\n    \n    r = gsl_odeiv_step_apply(self->solver, t, h, \n\t\t\t     (double *) yout->data, \n\t\t\t     (double *) yerr->data, \n\t\t\t     dydt_in_d, \n\t\t\t     (double *) dydt_out->data, \n\t\t\t     ((gsl_odeiv_system *)self->c_sys));\n    self->isset = 0;\n    if (GSL_SUCCESS != r){\n\tPyErr_SetString(PyExc_TypeError, \"Error While evaluating gsl_odeiv\");\n      goto fail;\n    }\n\n    FUNC_MESS(\"    Returnlist create \");\n    assert(yout != NULL);\n    assert(yerr != NULL);\n    assert(dydt_out != NULL);\n\n    result = Py_BuildValue(\"(OOO)\", yout, yerr, dydt_out);\n\n    FUNC_MESS(\"    Memory free \");\n    /* Deleting the arrays */    \n    Py_DECREF(y0);           y0 = NULL;\n    Py_DECREF(yout);         yout = NULL;\n    Py_DECREF(yerr);         yerr = NULL;\n    Py_DECREF(dydt_out);     dydt_out = NULL;\n    /* This array does not need to exist ... */\n    Py_XDECREF(dydt_in);\t dydt_in=NULL;\n    \n    FUNC_MESS_END();\n    return result;\n\n    fail:\n    FUNC_MESS(\"IN Fail\");\n    self->isset = 0;\n    Py_XDECREF(y0);\n    Py_XDECREF(yout);\n    Py_XDECREF(yerr);\n    Py_XDECREF(dydt_in);\n    Py_XDECREF(dydt_out);\n    FUNC_MESS(\"IN Fail End\");   \n    return NULL;\n}\n\nstatic PyObject *\nPyGSL_odeiv_control_hadjust(PyGSL_solver *self, PyObject *args)\n{\n  \n  PyObject *result = NULL;\n  PyObject *y0_o = NULL, *yerr_o = NULL, *dydt_o = NULL;\n  PyArrayObject *y0 = NULL, *yerr = NULL, *dydt = NULL;\n  double h = 0;\n  int r = 0;\n  mycontrol *c;\n\n  PyGSL_array_index_t dimension = 0;\n\n  FUNC_MESS_BEGIN();\n  assert(PyGSL_ODEIV_CONTROL_Check(self));\n  if(!PyArg_ParseTuple(args, \"OOOd\",  &y0_o, &yerr_o, &dydt_o, &h)){\n    return NULL;\n  }\n\n  dimension = self->problem_dimensions[0];\n\n\n  y0 = PyGSL_vector_check(y0_o, dimension, PyGSL_DARRAY_CINPUT(1), NULL, NULL);\n  if(y0 == NULL)   goto fail;\n  yerr = PyGSL_vector_check(yerr_o, dimension, PyGSL_DARRAY_CINPUT(2), NULL, NULL);\n  if(yerr == NULL) goto fail;\n  dydt = PyGSL_vector_check(dydt_o, dimension, PyGSL_DARRAY_CINPUT(3), NULL, NULL);\n  if(dydt == NULL) goto fail;\n  \n  FUNC_MESS(\"      Array Pointers End\");\n\n  c = (mycontrol *) self->solver;\n  r = gsl_odeiv_control_hadjust(c->control, c->step, \n\t\t\t\t(double *) y0->data,\n\t\t\t\t(double *) yerr->data,\n\t\t\t\t(double *) dydt->data, &h);\n\n  FUNC_MESS(\"      Function End\");\n  Py_DECREF(y0);       y0 = NULL;  \n  Py_DECREF(yerr);     yerr = NULL;\n  Py_DECREF(dydt);     dydt = NULL;\n\n  result = Py_BuildValue(\"di\",h,r);\n  FUNC_MESS_END();\n  return result;\n\n fail:\n  FUNC_MESS(\"IN Fail\");\n  Py_XDECREF(y0);\n  Py_XDECREF(yerr);\n  Py_XDECREF(dydt);\n  FUNC_MESS(\"IN Fail END\");\n  return NULL;\n}\n\nstatic PyObject *\nPyGSL_odeiv_evolve_apply(PyGSL_solver *self, PyObject *args)\n{\n    PyObject *result = NULL;\n    PyObject *y0_o = NULL,  *myargs = NULL;\n    PyArrayObject *volatile y0 = NULL, *volatile yout = NULL;\n    myevolve *e = NULL;\n    \n    double t=0, h=0, t1 = 0, flag;\n\n    int dimension = self->problem_dimensions[0], r;\n\n    assert(PyGSL_ODEIV_EVOLVE_Check(self));\n    FUNC_MESS_BEGIN();\n\n    if(!PyArg_ParseTuple(args, \"dddOO\", &t, &t1, &h, &y0_o, &myargs)){\n      return NULL;\n    }\n\n\n    DEBUG_MESS(3, \"y0_o @ %p\", y0_o);\n    \n    y0 = PyGSL_vector_check(y0_o, dimension, PyGSL_DARRAY_CINPUT(1), NULL, NULL);\n    if(y0 == NULL) goto fail;\n\n\n    yout = (PyArrayObject *)  PyGSL_Copy_Array(y0);\n    if(yout == NULL) goto fail;\n\n\n    e = (myevolve *) self->solver;\n\n    if((flag=setjmp(e->step_ob->buffer)) == 0){\n\t e->step_ob->isset = 1;\n\t  FUNC_MESS(\"\\t\\t Setting Jmp Buffer\");\n     } else {\n\t  FUNC_MESS(\"\\t\\t Returning from Jmp Buffer\");\n\t  e->step_ob->isset = 0;\n\t  goto fail;\n     }\n    DEBUG_MESS(3, \"evolve @ %p\\t control @ %p\\t step @ %p\", e, e->control, e->step);\n\n    r = gsl_odeiv_evolve_apply(e->evolve, \n\t\t\t       e->control, \n\t\t\t       e->step, \n\t\t\t       e->step_ob->c_sys, &t, t1, &h,\n\t\t\t       (double * )yout->data); \n   e->step_ob->isset = 0;\n    if (GSL_SUCCESS != r){\n\t goto fail;\n    } \n\n\n    assert(yout != NULL);\n\n\n    result = Py_BuildValue(\"(ddO)\", t, h, yout);\n\n    /* Deleting the arrays */    \n    Py_DECREF(yout);     yout = NULL;\n    Py_DECREF(y0);       y0=NULL;\n    FUNC_MESS_END();\n    return result;\n\n fail:\n    FUNC_MESS(\"IN Fail\");\n    e->step_ob->isset = 0;\n    PyGSL_add_traceback(module, this_file, odeiv_step_init_err_msg, __LINE__);\n    Py_XDECREF(y0);\n    Py_XDECREF(yout); \n    FUNC_MESS(\"IN Fail End\");   \n    return NULL;\n}\n\nGETINT(odeiv_step_order)\n\nstatic struct PyMethodDef PyGSL_odeiv_step_methods[] = {\n     {\"apply\", (PyCFunction) PyGSL_odeiv_step_apply, METH_VARARGS, odeiv_step_apply_doc},\n     {\"order\", (PyCFunction) PyGSL_odeiv_step_order, METH_VARARGS, odeiv_step_order_doc},\n     {NULL, NULL}\n};\nstatic struct PyMethodDef PyGSL_odeiv_control_methods[] = {\n     {\"hadjust\", (PyCFunction) PyGSL_odeiv_control_hadjust, METH_VARARGS, odeiv_control_hadjust_doc},\n     {NULL, NULL}\n};\n\nstatic struct PyMethodDef PyGSL_odeiv_evolve_methods[] = {\n     {\"apply\", (PyCFunction) PyGSL_odeiv_evolve_apply, METH_VARARGS, odeiv_evolve_apply_doc},\n     {NULL, NULL}\n};\n\n\nstatic const struct _SolverStatic\n_StepMethods     = {{(void_m_t) gsl_odeiv_step_free,   \n\t\t   (void_m_t) gsl_odeiv_step_reset,\n\t\t   (name_m_t) gsl_odeiv_step_name,   \n\t\t   (int_m_t) NULL},\n\t\t    3, PyGSL_odeiv_step_methods, odeiv_step_type_name},\n_ControlMethods  = {{(void_m_t) _mycontrol_free,   \n\t\t      (void_m_t) NULL,\n\t\t      (name_m_t) PyGSL_mycontrol_getname,\n\t\t      (int_m_t) NULL},\n\t\t    3, PyGSL_odeiv_control_methods, odeiv_control_type_name},\n_EvolveMethods   = {{(void_m_t) _myevolve_free,   \n\t\t     (void_m_t) gsl_odeiv_evolve_reset,\n\t\t     (name_m_t) NULL,   \n\t\t     (int_m_t) NULL,},\n\t\t    3, PyGSL_odeiv_evolve_methods, odeiv_evolve_type_name};\n\n\nstatic PyObject *\nPyGSL_odeiv_step_init(PyObject *self, PyObject *args, PyObject *kwdict, const gsl_odeiv_step_type * odeiv_type)\n{\n     \n     PyObject *func=NULL, *jac=NULL, *o_params=NULL;\n     PyGSL_solver *solver = NULL;\n\n     static char * kwlist[] = {\"dimension\", \"func\", \"jac\", \"args\", NULL}; \n     int dim, has_jacobian = 0;\n     gsl_odeiv_system * c_sys;\n     \n     solver_alloc_struct s = {odeiv_type, (void_an_t) gsl_odeiv_step_alloc,\n\t\t\t      &_StepMethods};\n\n\n     FUNC_MESS_BEGIN();\n\n     assert(args);\n     if (0 == PyArg_ParseTupleAndKeywords(args, kwdict, \"iOOO:odeiv_step.__init__\", kwlist, \n\t\t\t\t\t  &dim, &func, &jac, &o_params)){\n\t  PyGSL_add_traceback(module, this_file, odeiv_step_init_err_msg, __LINE__ - 2);\n\t  return NULL;\n     }     \n     if (dim <= 0){\t  \n\t  PyGSL_add_traceback(module, this_file, odeiv_step_init_err_msg, __LINE__ - 1);\n\t  pygsl_error(\"The dimension of the problem must be at least 1\", \n\t\t    this_file, __LINE__ -2, GSL_EDOM);\n\t  return NULL;\n     }\n     if(!PyCallable_Check(func)){\n\t  PyGSL_add_traceback(module, this_file, odeiv_step_init_err_msg, __LINE__ - 1);\n\t  pygsl_error(\"The function object is not callable!\", \n\t\t    this_file, __LINE__ -2, GSL_EBADFUNC);\n\t  goto fail;\t  \n     }\n\n     if(jac == Py_None){\n\t  if(odeiv_type == gsl_odeiv_step_bsimp){\n\t       PyGSL_add_traceback(module, this_file, odeiv_step_init_err_msg, __LINE__ - 1);\n\t       pygsl_error(\"The bsimp method needs a jacobian! You supplied None.\", \n\t\t\t this_file, __LINE__ -2, GSL_EBADFUNC);\n\t       goto fail;\n\t  }\n     }else{\n\t  if(!PyCallable_Check(jac)){\n\t       PyGSL_add_traceback(module, this_file, odeiv_step_init_err_msg, __LINE__ - 1);\n\t       pygsl_error(\"The jacobian object must be None or callable!\", \n\t\t\t this_file, __LINE__ -2, GSL_EBADFUNC);\n\t       goto fail;\n\t  }\n\t  has_jacobian = 1;\n\n     }\n\n     solver = (PyGSL_solver *) PyGSL_solver_dn_init(self, args, &s, 3);\n\n     if(solver == NULL){\n\t  goto fail;\n     }\n     DEBUG_MESS(3, \"solver @ %p\", solver);\n\n     solver->solver =  gsl_odeiv_step_alloc(odeiv_type, dim);     \n     if(solver->solver == NULL){\n\t  goto fail;\n     }\n     DEBUG_MESS(3, \"step @ %p\", solver->solver);\n     c_sys = (gsl_odeiv_system *)calloc(1, sizeof(gsl_odeiv_system));\n     if(c_sys == NULL){\n\t  PyErr_NoMemory();\n\t  goto fail;\n     }\n\n     /* Need for cleanup in fail : */\n     solver->c_sys = c_sys;     \n     DEBUG_MESS(3, \"c_sys @ %p\", solver->c_sys);\n     solver->problem_dimensions[0] = dim;\n     if(has_jacobian){\n\t  c_sys->jacobian = PyGSL_odeiv_jac;\n\t  if(!PyCallable_Check(jac))\n\t       goto fail;\n\t  solver->cbs[1] = jac;\n     }else{\n\t  c_sys->jacobian = NULL;\n\t  solver->cbs[1] = NULL;\n     }\n     c_sys->function = PyGSL_odeiv_func;\n     if(!PyCallable_Check(func))\n\t       goto fail;\n\n     solver->cbs[0] = func;\n     c_sys->params = (void *) solver;\n     DEBUG_MESS(3, \"params @ %p\", c_sys->params);\n     Py_INCREF(solver->cbs[0]);\n     Py_XINCREF(solver->cbs[1]);\n     Py_XINCREF(solver->args);\n\t  \n     solver->args  = o_params;\n     Py_INCREF(solver->args);\n\n     FUNC_MESS_END();\n     return (PyObject *) solver;\n\n fail:\n     FUNC_MESS(\"FAIL\");\n     Py_XDECREF(solver);\n     return NULL;\n}\n#define ADD_ODESTEPPER(mytype)                                                   \\\nstatic PyObject *                                                                \\\nPyGSL_odeiv_step_init_ ## mytype (PyObject * self, PyObject * args, PyObject *kwdic)   \\\n{                                                                                \\\n     return PyGSL_odeiv_step_init(self, args, kwdic, gsl_odeiv_step_ ## mytype); \\\n}   \nADD_ODESTEPPER(rk2)\nADD_ODESTEPPER(rk4)\nADD_ODESTEPPER(rkf45)\nADD_ODESTEPPER(rkck)\nADD_ODESTEPPER(rk8pd)\nADD_ODESTEPPER(rk2imp)\nADD_ODESTEPPER(rk4imp)\nADD_ODESTEPPER(bsimp)\nADD_ODESTEPPER(gear1)\nADD_ODESTEPPER(gear2)\n\n\nstatic PyObject *\nPyGSL_odeiv_control_init(PyObject *self, PyObject *args, void * type)\n{\n     int nargs = -1, tmp=0;\n     double eps_abs, eps_rel, a_y, a_dydt;\n     PyGSL_solver *step=NULL, *solver=NULL;\n     mycontrol * c;\n\n     gsl_odeiv_control *(*evaluator_5)(double , double , double , double ) = NULL;\n     gsl_odeiv_control *(*evaluator_3)(double , double ) = NULL;\n\n     solver_alloc_struct s = {type, (void_an_t) gsl_odeiv_control_alloc,\n\t\t\t      &_ControlMethods};\n\n     FUNC_MESS_BEGIN();\n     /* The arguments depend on the type of control */\n     if(type == (void *) gsl_odeiv_control_standard_new){\n\t  /* step, eps_abs, eps_rel, a_y, a_dydt */\n\t  nargs = 5;\n     }else if(type == (void *) gsl_odeiv_control_y_new || \n\t      type == (void *) gsl_odeiv_control_yp_new){\n\t  nargs = 3;\n     }else{\n\t  PyGSL_add_traceback(module, this_file, odeiv_step_init_err_msg, \n\t\t\t      __LINE__ - 2);\n\t  pygsl_error(\"Unknown control type\", \n\t\t    this_file, __LINE__ -2, GSL_EFAULT);\n\t  goto fail;\n     }\n     assert(nargs > -1);\n\n\n     switch(nargs){\n     case 5:\n\t  tmp == PyArg_ParseTuple(args, \"Odddd:odeiv_control.__init__\", \n\t\t\t\t   &step, &eps_abs, &eps_rel, &a_y, &a_dydt);\n\t  break;\n     case 3:\n\t  tmp == PyArg_ParseTuple(args, \"Odd:odeiv_control.__init__\", \n\t\t\t\t  &step, &eps_abs, &eps_rel);\n\t  break;\n     default:\n\t  fprintf(stderr, \"nargs = %d\\n\", nargs);\n\t  pygsl_error(\"Unknown number of arguments\", \n\t\t    this_file, __LINE__ -2, GSL_EFAULT);\n\t  goto fail; break;\n     }\n     if(!PyGSL_ODEIV_STEP_Check(step)){\n\t  int flag;\n\t  flag = PyGSL_solver_check(step);\n\t  DEBUG_MESS(3, \"is solver?  %d, %p %p \", flag,  PyGSL_API[PyGSL_solver_type_NUM], step->ob_type);\n\t  if(flag){\n\t       DEBUG_MESS(3, \"solver = %s, %p !=  %p\", step->mstatic->type_name, step->mstatic->type_name, \n\t\t\t  odeiv_step_type_name);\n\t       pygsl_error(\"First argument must be a step solver!\", __FILE__, __LINE__, GSL_EINVAL);\n\t  }     \n\t  goto fail;\n     }\n\t  \n     \n     if(tmp){\t  \n\t  PyGSL_add_traceback(module, this_file, odeiv_step_init_err_msg, \n\t\t\t      __LINE__ - 2);\n\t  return NULL;\n     }\n\n\n     solver =  (PyGSL_solver *) PyGSL_solver_dn_init(self, args, &s, 3);\n     if (NULL == solver){\n\t  PyErr_NoMemory();\n\t  goto fail;\n     }\n     c = calloc(1, sizeof(mycontrol));\n     if(c == NULL){\n\t  PyErr_NoMemory();\n\t  goto fail;\n     }\n     solver->solver = c;\n     switch(nargs){\n     case 5:\n\t  evaluator_5 = type;\n\t  c->control = evaluator_5(eps_abs, eps_rel, a_y, a_dydt);\n\t  break;\n     case 3:\n\t  evaluator_3 = type;\n\t  c->control = evaluator_3(eps_abs, eps_rel);\n\t  break;\n     default:\n\t  goto fail;\n     }\n     if (NULL == c->control){\n\t  PyErr_NoMemory();\n\t  goto fail;\n     }\n     DEBUG_MESS(3, \"c->control @ %p\", c->control);\n     c->step =  step->solver;\n     c->step_ob = step;\n     Py_INCREF(step);\n     FUNC_MESS_END();\n     return (PyObject *) solver;\n\n fail:\n     FUNC_MESS(\"FAIL\");\n     Py_XDECREF(solver);\n     return NULL;\n     \n}\n\n#define ADD_ODECONTROL(name)                                                  \\\nstatic PyObject *                                                             \\\nPyGSL_odeiv_control_init_ ## name (PyObject * self, PyObject * args)          \\\n{                                                                             \\\n     return PyGSL_odeiv_control_init(self, args, (void *) gsl_odeiv_control_ ## name);    \\\n}   \nADD_ODECONTROL(standard_new)\nADD_ODECONTROL(y_new)\nADD_ODECONTROL(yp_new)\n\nstatic PyObject *\nPyGSL_odeiv_evolve_init(PyObject *self, PyObject *args)\n{\n     PyGSL_solver *step, *control, *a_ev = NULL;\n     myevolve *e;\n     solver_alloc_struct s = {NULL, (void_an_t) gsl_odeiv_evolve_alloc,\n\t\t\t      &_EvolveMethods};\n\n     /* step, control */\n     FUNC_MESS_BEGIN();\n     if(0== PyArg_ParseTuple(args, \"OO:odeiv_evolve.__init__\", \n\t\t\t     &step, &control)){\n\t  return NULL;\n     }\n     if(!PyGSL_ODEIV_STEP_Check(step)){\n\t  pygsl_error(\"First argument must be a step solver!\", __FILE__, __LINE__, GSL_EINVAL);\n\t  goto fail;\n     }\n\n     if(!PyGSL_ODEIV_CONTROL_Check(control)){\n\t  pygsl_error(\"Second argument must be a control solver!\", __FILE__, __LINE__, GSL_EINVAL);\n\t  goto fail;\n     }\n\n     a_ev =  (PyGSL_solver *) PyGSL_solver_dn_init(self, args, &s, 3);\n     if(NULL == a_ev){\n\t  PyErr_NoMemory();\n\t  return NULL;\n     }\n     a_ev->problem_dimensions[0] = step->problem_dimensions[0];\n\n     e = (myevolve *) calloc(1, sizeof(myevolve));\n     if(e == NULL){\n\t  PyErr_NoMemory();\n\t  goto fail;\n     }\n     a_ev->solver = e;\n     e->step_ob =  step;\n     e->control_ob = control;\n     Py_INCREF(step);\n     Py_INCREF(control);\n     e->step = step->solver;\n     e->control = ((mycontrol *)control->solver)->control;\n     e->evolve = gsl_odeiv_evolve_alloc(step->problem_dimensions[0]);\n     if(NULL == e->evolve){\n\t  PyErr_NoMemory();\n\t  goto fail;\n     }\n     FUNC_MESS_END();\n     return (PyObject *) a_ev;\n fail:\n     FUNC_MESS(\"FAIL\");\n     Py_XDECREF(a_ev);\n     return NULL;\n}\n\nstatic const char PyGSL_odeiv_module_doc [] = \"XXX Missing \";\nstatic PyMethodDef mMethods[] = {\n     {\"step_rk2\",    (PyCFunction)PyGSL_odeiv_step_init_rk2,    METH_VARARGS|METH_KEYWORDS, PyGSL_odeiv_step_doc},\n     {\"step_rk4\",    (PyCFunction)PyGSL_odeiv_step_init_rk4,    METH_VARARGS|METH_KEYWORDS, PyGSL_odeiv_step_doc},\n     {\"step_rkf45\",  (PyCFunction)PyGSL_odeiv_step_init_rkf45,  METH_VARARGS|METH_KEYWORDS, PyGSL_odeiv_step_doc},\n     {\"step_rkck\",   (PyCFunction)PyGSL_odeiv_step_init_rkck,   METH_VARARGS|METH_KEYWORDS, PyGSL_odeiv_step_doc},\n     {\"step_rk8pd\",  (PyCFunction)PyGSL_odeiv_step_init_rk8pd,  METH_VARARGS|METH_KEYWORDS, PyGSL_odeiv_step_doc},\n     {\"step_rk2imp\", (PyCFunction)PyGSL_odeiv_step_init_rk2imp, METH_VARARGS|METH_KEYWORDS, PyGSL_odeiv_step_doc},\n     {\"step_rk4imp\", (PyCFunction)PyGSL_odeiv_step_init_rk4imp, METH_VARARGS|METH_KEYWORDS, PyGSL_odeiv_step_doc},\n     {\"step_bsimp\",  (PyCFunction)PyGSL_odeiv_step_init_bsimp,  METH_VARARGS|METH_KEYWORDS, PyGSL_odeiv_step_doc},\n     {\"step_gear1\",  (PyCFunction)PyGSL_odeiv_step_init_gear1,  METH_VARARGS|METH_KEYWORDS, PyGSL_odeiv_step_doc},\n     {\"step_gear2\",  (PyCFunction)PyGSL_odeiv_step_init_gear2,  METH_VARARGS|METH_KEYWORDS, PyGSL_odeiv_step_doc},\n     {\"control_standard_new\", PyGSL_odeiv_control_init_standard_new, METH_VARARGS, PyGSL_odeiv_control_doc},\n     {\"control_y_new\",        PyGSL_odeiv_control_init_y_new,        METH_VARARGS, PyGSL_odeiv_control_doc},\n     {\"control_yp_new\",       PyGSL_odeiv_control_init_yp_new,       METH_VARARGS, PyGSL_odeiv_control_doc},\n     {\"evolve\", PyGSL_odeiv_evolve_init, METH_VARARGS, PyGSL_odeiv_evolve_doc},\n     {NULL, NULL, 0, NULL}\n};\n\nvoid\ninitodeiv(void)\n{\n     PyObject* m, *dict, *item;\n     FUNC_MESS_BEGIN();\n\n     m=Py_InitModule(\"odeiv\", mMethods);\n     module = m;\n     assert(m);\n     dict = PyModule_GetDict(m);\n     if(!dict)\n\t  goto fail;\n\n     init_pygsl()\n     import_pygsl_solver();\n     assert(PyGSL_API);\n\n\n     if (!(item = PyString_FromString((char*)PyGSL_odeiv_module_doc))){\n\t  PyErr_SetString(PyExc_ImportError, \n\t\t\t  \"I could not generate module doc string!\");\n\t  goto fail;\n     }\n     if (PyDict_SetItemString(dict, \"__doc__\", item) != 0){\n\t  PyErr_SetString(PyExc_ImportError, \n\t\t\t  \"I could not init doc string!\");\n\t  goto fail;\n     }\n     \n     FUNC_MESS_END();\n\n fail:\n     FUNC_MESS(\"FAIL\");\n     return;\n}\n", "meta": {"hexsha": "e715ed590649947cb660df5c62c6f1c53c550c45", "size": 25331, "ext": "c", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/testing/src/solvers/odeiv.c", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/testing/src/solvers/odeiv.c", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/testing/src/solvers/odeiv.c", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 29.1831797235, "max_line_length": 114, "alphanum_fraction": 0.6365717895, "num_tokens": 7658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3242353989809524, "lm_q2_score": 0.037326887879581695, "lm_q1q2_score": 0.012102698384353447}}
{"text": "#include <gsl/gsl_errno.h>\n#include <gsl/matrix/gsl_matrix.h>\n\n\n#define BASE_DOUBLE\n#include <gsl/templates_on.h>\n#include <gsl/matrix/matrix_source.c>\n#include <gsl/templates_off.h>\n#undef BASE_DOUBLE\n", "meta": {"hexsha": "1b965a5eaa1520e0a4057b71f20027175511f7c8", "size": 202, "ext": "c", "lang": "C", "max_stars_repo_path": "Cartwheel/cartwheel-3d/gsl/matrix/matrix.c", "max_stars_repo_name": "MontyThibault/centre-of-mass-awareness", "max_stars_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Cartwheel/cartwheel-3d/gsl/matrix/matrix.c", "max_issues_repo_name": "MontyThibault/centre-of-mass-awareness", "max_issues_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cartwheel/cartwheel-3d/gsl/matrix/matrix.c", "max_forks_repo_name": "MontyThibault/centre-of-mass-awareness", "max_forks_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.2, "max_line_length": 37, "alphanum_fraction": 0.7772277228, "num_tokens": 55, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3998116407397951, "lm_q2_score": 0.030214589578009935, "lm_q1q2_score": 0.012080144633463664}}
{"text": "/*\nODE: a program to get optime Runge-Kutta and multi-steps methods.\n\nCopyright 2011-2019, Javier Burguete Tolosa.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n\t1. Redistributions of source code must retain the above copyright notice,\n\t\tthis list of conditions and the following disclaimer.\n\n\t2. Redistributions in binary form must reproduce the above copyright notice,\n\t\tthis list of conditions and the following disclaimer in the\n\t\tdocumentation and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``AS IS'' AND ANY EXPRESS OR\nIMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT\nSHALL Javier Burguete Tolosa OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\nADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n/**\n * \\file optimize.c\n * \\brief Source file with optimize functions.\n * \\author Javier Burguete Tolosa.\n * \\copyright Copyright 2011-2019.\n */\n#define _GNU_SOURCE\n#include <stdio.h>\n#include <string.h>\n#include <float.h>\n#include <math.h>\n#include <libxml/parser.h>\n#include <glib.h>\n#include <libintl.h>\n#include <gsl/gsl_rng.h>\n#if HAVE_MPI\n#include <mpi.h>\n#endif\n#include \"config.h\"\n#include \"utils.h\"\n#include \"optimize.h\"\n\n#define DEBUG_OPTIMIZE 0        ///< macro to debug.\n\nGMutex mutex[1];                ///< GMutex struct.\nFILE *file_variables = NULL;    ///< random variables file.\nint rank;                       ///< MPI rank.\nint nnodes;                     ///< MPI nodes number.\nunsigned nthreads;              ///< threads number.\n\n/**\n * Function to print the random variables on a file.\n */\nvoid\noptimize_print_random (Optimize * optimize,     ///< Optimize struct.\n                       FILE * file)     ///< file.\n{\n  unsigned int i, n;\n  n = optimize->nfree;\n  for (i = 0; i < n; ++i)\n    fprintf (file, \"o%d:%.19Le;\\n\", i, optimize->value_optimal[i]);\n  for (i = 0; i < n; ++i)\n    fprintf (file, \"m%d:%.19Le;\\n\", i, optimize->minimum[i]);\n  for (i = 0; i < n; ++i)\n    fprintf (file, \"i%d:%.19Le;\\n\", i, optimize->interval[i]);\n}\n\n/**\n * Function to perform every optimization step.\n */\nvoid\noptimize_step (Optimize * optimize)     ///< Optimize struct.\n{\n  long double *is, *vo, *vo2, *random;\n  long double o, o2, v, f;\n  unsigned long long int ii, nrandom;\n  unsigned int i, j, k, n, nfree;\n\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_step: start\\n\");\n#endif\n\n  // save optimal values\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_step: save optimal values\\n\");\n#endif\n  nfree = optimize->nfree;\n  o2 = *optimize->optimal;\n  vo = (long double *) alloca (nfree * sizeof (long double));\n  vo2 = (long double *) alloca (nfree * sizeof (long double));\n  memcpy (vo, optimize->value_optimal, nfree * sizeof (long double));\n\n  // optimization algorithm sampling\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_step: optimization algorithm sampling\\n\");\n  fprintf (stderr, \"optimize_step: nsimulations=%Lu\\n\", optimize->nsimulations);\n#endif\n  random = optimize->random_data;\n  ii = optimize->nsimulations * (rank * nthreads + optimize->thread)\n    / (nnodes * nthreads);\n  nrandom = optimize->nsimulations * (rank * nthreads + optimize->thread + 1)\n    / (nnodes * nthreads);\n  for (; ii < nrandom; ++ii)\n    {\n\n      // random freedom degrees\n#if DEBUG_OPTIMIZE\n      fprintf (stderr, \"optimize_step: random freedom degrees\\n\");\n      fprintf (stderr, \"optimize_step: simulation=%Lu\\n\", ii);\n#endif\n      optimize_generate_freedom (optimize, ii);\n\n      // method coefficients\n#if DEBUG_OPTIMIZE\n      fprintf (stderr, \"optimize_step: method coefficients\\n\");\n#endif\n      if (!optimize->method (optimize))\n        o = INFINITY;\n      else\n        o = optimize->objective (optimize);\n      if (o < o2)\n        {\n          o2 = o;\n          memcpy (vo, random, nfree * sizeof (long double));\n        }\n      if (file_variables)\n        {\n          g_mutex_lock (mutex);\n          print_variables (random, nfree, file_variables);\n          fprintf (file_variables, \"%.19Le\\n\", o);\n          g_mutex_unlock (mutex);\n        }\n    }\n\n  // array of intervals to climb around the optimal\n#if DEBUG_OPTIMIZE\n  fprintf (stderr,\n           \"optimize_step: array of intervals to climb around the optimal\\n\");\n#endif\n  is = (long double *) alloca (nfree * sizeof (long double));\n  for (j = 0; j < nfree; ++j)\n    is[j] = optimize->interval0[j] * optimize->climbing_factor;\n\n  // hill climbing algorithm bucle\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_step: hill climbing algorithm bucle\\n\");\n#endif\n  memcpy (vo2, vo, nfree * sizeof (long double));\n  n = optimize->nclimbings;\n  for (i = 0; i < n; ++i)\n    {\n      memcpy (random, vo, nfree * sizeof (long double));\n      for (j = k = 0; j < nfree; ++j)\n        {\n          v = vo[j];\n          random[j] = v + is[j];\n          if (!optimize->method (optimize))\n            o = INFINITY;\n          else\n            o = optimize->objective (optimize);\n          if (o < o2)\n            {\n              k = 1;\n              o2 = o;\n              memcpy (vo2, random, nfree * sizeof (long double));\n            }\n          if (file_variables)\n            {\n              g_mutex_lock (mutex);\n              print_variables (random, nfree, file_variables);\n              fprintf (file_variables, \"%.19Le\\n\", o);\n              g_mutex_unlock (mutex);\n            }\n          random[j] = fmaxl (0.L, v - is[j]);\n          if (!optimize->method (optimize))\n            o = INFINITY;\n          else\n            o = optimize->objective (optimize);\n          if (o < o2)\n            {\n              k = 1;\n              o2 = o;\n              memcpy (vo2, random, nfree * sizeof (long double));\n            }\n          if (file_variables)\n            {\n              g_mutex_lock (mutex);\n              print_variables (random, nfree, file_variables);\n              fprintf (file_variables, \"%.19Le\\n\", o);\n              g_mutex_unlock (mutex);\n            }\n          random[j] = v;\n        }\n\n\n      // update optimal values and increase or reduce intervals if converging or\n      // not\n      if (!k)\n        f = 0.5L;\n      else\n        {\n          f = 1.2L;\n          memcpy (vo, vo2, nfree * sizeof (long double));\n        }\n      for (j = 0; j < nfree; ++j)\n        is[j] *= f;\n    }\n\n  // update optimal values\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_step: update optimal values\\n\");\n#endif\n  if (o2 < *optimize->optimal)\n    {\n      g_mutex_lock (mutex);\n      *optimize->optimal = o2;\n      memcpy (optimize->value_optimal, vo2, nfree * sizeof (long double));\n      g_mutex_unlock (mutex);\n    }\n\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_step: end\\n\");\n#endif\n}\n\n/**\n * Function to init required variables on an Optimize struct data.\n */\nvoid\noptimize_init (Optimize * optimize,     ///< Optimize struct.\n               gsl_rng * rng,   ///< GSL pseudo-random number generator struct.\n               unsigned int thread)     ///< thread number.\n{\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_init: start\\n\");\n#endif\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_init: nsimulations=%Lu nfree=%u size=%u\\n\",\n           optimize->nsimulations, optimize->nfree, optimize->size);\n#endif\n  optimize->random_data\n    = (long double *) g_slice_alloc (optimize->nfree * sizeof (long double));\n  optimize->coefficient\n    = (long double *) g_slice_alloc (optimize->size * sizeof (long double));\n  optimize->minimum\n    = (long double *) g_slice_alloc (optimize->nfree * sizeof (long double));\n  optimize->interval\n    = (long double *) g_slice_alloc (optimize->nfree * sizeof (long double));\n  memcpy (optimize->minimum, optimize->minimum0,\n          optimize->nfree * sizeof (long double));\n  memcpy (optimize->interval, optimize->interval0,\n          optimize->nfree * sizeof (long double));\n  optimize->rng = rng;\n  optimize->thread = thread;\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_init: end\\n\");\n#endif\n}\n\n/**\n * Function to free the memory allocated by an Optimize struct.\n */\nvoid\noptimize_delete (Optimize * optimize)   ///< Optimize struct.\n{\n  g_slice_free1 (optimize->nfree * sizeof (long double), optimize->interval);\n  g_slice_free1 (optimize->nfree * sizeof (long double), optimize->minimum);\n  g_slice_free1 (optimize->size * sizeof (long double), optimize->coefficient);\n  g_slice_free1 (optimize->nfree * sizeof (long double), optimize->random_data);\n}\n\n/**\n * Function to do the optimization bucle.\n */\nvoid\noptimize_bucle (Optimize * optimize)    ///< Optimize struct.\n{\n  GThread *thread[nthreads];\n#if HAVE_MPI\n  long double *vo;\n  MPI_Status status;\n#endif\n  unsigned int i, j, nfree;\n\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_bucle: start\\n\");\n  fprintf (stderr, \"optimize_bucle: nfree=%u\\n\", optimize->nfree);\n#endif\n\n  // Allocate local array of optimal values\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_bucle: allocate local array of optimal values\\n\");\n#endif\n  nfree = optimize->nfree;\n#if HAVE_MPI\n  vo = (long double *) alloca ((1 + nfree) * sizeof (long double));\n  printf (\"Rank=%d NNodes=%d\\n\", rank, nnodes);\n#endif\n\n  // Init some parameters\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_bucle: init some parameters\\n\");\n#endif\n  *optimize->optimal = INFINITY;\n  for (i = 0; i < nfree; ++i)\n    optimize->value_optimal[i]\n      = optimize->minimum[i] + 0.5L * optimize->interval[i];\n\n  // Iterate\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_bucle: iterate\\n\");\n#endif\n  for (i = 0; i < optimize->niterations; ++i)\n    {\n\n      // Optimization step parallelized for every node by GThreads\n      if (nthreads > 1)\n        {\n          for (j = 0; j < nthreads; ++j)\n            thread[j]\n              = g_thread_new (NULL,\n                              (GThreadFunc) (void (*)(void)) optimize_step,\n                              (void *) (optimize + j));\n          for (j = 0; j < nthreads; ++j)\n            g_thread_join (thread[j]);\n        }\n      else\n        optimize_step (optimize);\n\n#if HAVE_MPI\n      if (rank > 0)\n        {\n\n          // Secondary nodes send the optimal coefficients to the master node\n          vo[0] = *optimize->optimal;\n          memcpy (vo + 1, optimize->value_optimal,\n                  nfree * sizeof (long double));\n          MPI_Send (vo, 1 + nfree, MPI_LONG_DOUBLE, 0, 1, MPI_COMM_WORLD);\n\n          // Secondary nodes receive the optimal coefficients\n          MPI_Recv (vo, 1 + nfree, MPI_LONG_DOUBLE, 0, 1, MPI_COMM_WORLD,\n                    &status);\n          *optimize->optimal = vo[0];\n          memcpy (optimize->value_optimal, vo + 1,\n                  nfree * sizeof (long double));\n        }\n      else\n        {\n          printf (\"rank=%d optimal=%.19Le\\n\", rank, *optimize->optimal);\n\n          for (j = 1; j < nnodes; ++j)\n            {\n\n              // Master node receives the optimal coefficients obtained by\n              // secondary nodes\n              MPI_Recv (vo, 1 + nfree, MPI_LONG_DOUBLE, j, 1, MPI_COMM_WORLD,\n                        &status);\n\n              // Master node selects the optimal coefficients\n              if (vo[0] < *optimize->optimal)\n                {\n                  *optimize->optimal = vo[0];\n                  memcpy (optimize->value_optimal, vo + 1,\n                          nfree * sizeof (long double));\n                }\n            }\n\n          // Master node sends the optimal coefficients to secondary nodes\n          vo[0] = *optimize->optimal;\n          memcpy (vo + 1, optimize->value_optimal,\n                  nfree * sizeof (long double));\n          for (j = 1; j < nnodes; ++j)\n            MPI_Send (vo, 1 + nfree, MPI_LONG_DOUBLE, j, 1, MPI_COMM_WORLD);\n        }\n\n#endif\n\n      // Print the optimal coefficients\n#if DEBUG_OPTIMIZE\n      optimize_print_random (optimize, stderr);\n      fprintf (stderr, \"optimal=%.19Le\\n\", *optimize->optimal);\n#endif\n\n      // Updating coefficient intervals to converge\n      optimize_converge (optimize);\n\n      // Iterate\n#if HAVE_MPI\n      printf (\"Rank %u\\n\", rank);\n#endif\n      printf (\"Iteration %u Optimal %.19Le\\n\", i + 1, *optimize->optimal);\n    }\n\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_bucle: end\\n\");\n#endif\n}\n\n/**\n * Function to create an Optimize struct data.\n */\nvoid\noptimize_create (Optimize * optimize,   ///< Optimize struct.\n                 long double *optimal,\n                 ///< pointer to the optimal objective function value.\n                 long double *value_optimal)\n                 ///< array of optimal freedom degree values.\n{\n  unsigned long long int nsimulations;\n  unsigned int i, nfree;\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_create: start\\n\");\n#endif\n  optimize->optimal = optimal;\n  optimize->value_optimal = value_optimal;\n  nfree = optimize->nfree;\n  optimize->nsimulations = nsimulations = optimize->nvariable;\n  for (i = 1; i < nfree; ++i)\n    optimize->nsimulations *= nsimulations;\n  optimize->nclimbings *= nfree;\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_create nsimulations=%Lu nclimbings=%u nfree=%u\\n\",\n           optimize->nsimulations, optimize->nclimbings, nfree);\n  fprintf (stderr, \"optimize_create: end\\n\");\n#endif\n}\n\n/**\n * Function to read the Optimize struct data on a XML node.\n *\n * \\return 1 on success, 0 on error.\n */\nint\noptimize_read (Optimize * optimize,     ///< Optimize struct.\n               xmlNode * node)  ///< XML node.\n{\n  int code;\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_read: start\\n\");\n#endif\n  optimize->nvariable = xml_node_get_uint (node, XML_NSIMULATIONS, &code);\n  if (code || !optimize->nvariable)\n    {\n      error_message = g_strdup (_(\"Bad simulations number\"));\n      goto exit_on_error;\n    }\n  optimize->nclimbings\n    = xml_node_get_uint_with_default (node, XML_NCLIMBINGS, 0, &code);\n  if (code)\n    {\n      error_message = g_strdup (_(\"Bad hill climbings number\"));\n      goto exit_on_error;\n    }\n  optimize->niterations = xml_node_get_uint (node, XML_NITERATIONS, &code);\n  if (code || !optimize->niterations)\n    {\n      error_message = g_strdup (_(\"Bad iterations number\"));\n      goto exit_on_error;\n    }\n  optimize->convergence_factor\n    = xml_node_get_float (node, XML_CONVERGENCE_FACTOR, &code);\n  if (code || optimize->convergence_factor < LDBL_EPSILON)\n    {\n      error_message = g_strdup (_(\"Bad convergence factor\"));\n      goto exit_on_error;\n    }\n  optimize->climbing_factor\n    = xml_node_get_float (node, XML_CLIMBING_FACTOR, &code);\n  if (code || optimize->climbing_factor < LDBL_EPSILON)\n    {\n      error_message = g_strdup (_(\"Bad climging factor\"));\n      goto exit_on_error;\n    }\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_read: end\\n\");\n#endif\n  return 1;\n\nexit_on_error:\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_read: end\\n\");\n#endif\n  return 0;\n}\n", "meta": {"hexsha": "ecb8e16bf079c97e6b6daeeba64443aefd7af303", "size": 15262, "ext": "c", "lang": "C", "max_stars_repo_path": "optimize.c", "max_stars_repo_name": "jburguete/ode", "max_stars_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "optimize.c", "max_issues_repo_name": "jburguete/ode", "max_issues_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "optimize.c", "max_forks_repo_name": "jburguete/ode", "max_forks_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0203252033, "max_line_length": 80, "alphanum_fraction": 0.618660726, "num_tokens": 3882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3593641588823761, "lm_q2_score": 0.03358950190134913, "lm_q1q2_score": 0.012070863098056302}}
{"text": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n#pragma once\n\n#include \"BaseWorker.h\"\n\n#include \"MageSlam.h\"\n\n#include <arcana/scheduling/state_machine.h>\n#include <gsl/gsl>\n#include <memory>\n\nnamespace mage\n{\n    struct MageContext;\n    struct MageSlamSettings;\n    struct FrameData;\n\n    class Fuser;\n\n    class Runtime\n    {\n    public:\n        Runtime(const MageSlamSettings& settings, MageContext& context, Fuser& fuser, mira::state_machine_driver& driver);\n        ~Runtime();\n\n        void Run(gsl::span<const MAGESlam::CameraConfiguration> cameras);\n\n        void TrackMono(std::shared_ptr<FrameData> frame);\n        void TrackStereo(std::shared_ptr<FrameData> one, std::shared_ptr<FrameData> two);\n\n        void AddSample(const mage::SensorSample& sample);\n    private:\n        struct Impl;\n        const std::unique_ptr<Impl> m_impl;\n    };\n}\n", "meta": {"hexsha": "7e7634aa1043baa465ad1372134de36384f3286d", "size": 881, "ext": "h", "lang": "C", "max_stars_repo_path": "Core/MAGESLAM/Source/Tasks/Runtime.h", "max_stars_repo_name": "syntheticmagus/mageslam", "max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z", "max_issues_repo_path": "Core/MAGESLAM/Source/Tasks/Runtime.h", "max_issues_repo_name": "syntheticmagus/mageslam", "max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z", "max_forks_repo_path": "Core/MAGESLAM/Source/Tasks/Runtime.h", "max_forks_repo_name": "syntheticmagus/mageslam", "max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z", "avg_line_length": 22.5897435897, "max_line_length": 122, "alphanum_fraction": 0.6833144154, "num_tokens": 211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.025957359175758542, "lm_q1q2_score": 0.01206761706951359}}
{"text": "/* Internal header file for cminpack, by Frederic Devernay. */\n#ifndef __CMINPACKP_H__\n#define __CMINPACKP_H__\n\n#ifndef __CMINPACK_H__\n#error \"cminpackP.h in an internal cminpack header, and must be included after all other headers (including cminpack.h)\"\n#endif\n\n#if (defined (USE_CBLAS) || defined (USE_LAPACK)) && !defined (__cminpack_double__) && !defined (__cminpack_float__)\n#error \"cminpack can use cblas and lapack only in double or single precision mode\"\n#endif\n\n#ifdef USE_CBLAS\n#ifdef __APPLE__\n#include <Accelerate/Accelerate.h>\n#else\n#include <cblas.h>\n#endif\n#define __cminpack_enorm__(n,x) __cminpack_cblas__(nrm2)(n,x,1)\n#else\n#define __cminpack_enorm__(n,x) __cminpack_func__(enorm)(n,x)\n#endif\n\n#ifdef USE_LAPACK\n#ifdef __APPLE__\n#include <Accelerate/Accelerate.h>\n#else\n#if defined(__LP64__) /* In LP64 match sizes with the 32 bit ABI */\ntypedef int \t\t__CLPK_integer;\ntypedef int \t\t__CLPK_logical;\ntypedef __CLPK_logical \t(*__CLPK_L_fp)();\ntypedef int \t\t__CLPK_ftnlen;\n#else\ntypedef long int \t__CLPK_integer;\ntypedef long int \t__CLPK_logical;\ntypedef __CLPK_logical \t(*__CLPK_L_fp)();\ntypedef long int \t__CLPK_ftnlen;\n#endif\nint __cminpack_lapack__(lartg_)(\n  __cminpack_real__ *f, __cminpack_real__ *g, __cminpack_real__ *cs,\n  __cminpack_real__ *sn, __cminpack_real__ *r__);\nint __cminpack_lapack__(geqp3_)(\n  __CLPK_integer *m, __CLPK_integer *n, __cminpack_real__ *a, __CLPK_integer * lda,\n  __CLPK_integer *jpvt, __cminpack_real__ *tau, __cminpack_real__ *work, __CLPK_integer *lwork,\n  __CLPK_integer *info);\nint __cminpack_lapack__(geqrf_)(\n  __CLPK_integer *m, __CLPK_integer *n, __cminpack_real__ *a, __CLPK_integer * lda,\n  __cminpack_real__ *tau, __cminpack_real__ *work, __CLPK_integer *lwork, __CLPK_integer *info);\n#endif\n#endif\n\n#include \"minpackP.h\"\n\n#endif /* !__CMINPACKP_H__ */\n", "meta": {"hexsha": "1b460ec8a245da1d3cb5b0f15bc82a234e8a4025", "size": 1816, "ext": "h", "lang": "C", "max_stars_repo_path": "SciPy/cminpack-master/cminpackP.h", "max_stars_repo_name": "ianormy/Pyto", "max_stars_repo_head_hexsha": "e69a9ab57d5ef86675041f9e1f4427e9b79bb8e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-08-25T13:55:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-25T16:36:03.000Z", "max_issues_repo_path": "Extensions/SciPy/cminpack-master/cminpackP.h", "max_issues_repo_name": "ProjectZeroDays/Pyto", "max_issues_repo_head_hexsha": "d5d77f3541f329bbb28142d18606b22f115b7df6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Extensions/SciPy/cminpack-master/cminpackP.h", "max_forks_repo_name": "ProjectZeroDays/Pyto", "max_forks_repo_head_hexsha": "d5d77f3541f329bbb28142d18606b22f115b7df6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0181818182, "max_line_length": 120, "alphanum_fraction": 0.7813876652, "num_tokens": 597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.026355350360682723, "lm_q1q2_score": 0.01204799833472083}}
{"text": "#ifndef SmtkMatcher_h\n#define SmtkMatcher_h\n\n/** This is free and unencumbered software released into the public domain.\nThe authors of ISIS do not claim copyright on the contents of this file.\nFor more details about the LICENSE terms and the AUTHORS, you will\nfind files of those names at the top level of this repository. **/\n\n/* SPDX-License-Identifier: CC0-1.0 */\n\n#include <memory>\n\n\n#include <QSharedPointer>\n#include \"SmtkStack.h\"\n#include \"Gruen.h\"\n#include \"SmtkPoint.h\"\n\n#include \"GSLUtility.h\"\n#include <gsl/gsl_rng.h>\n\n\nnamespace Isis {\n\n/**\n * @brief Workhorse of stereo matcher\n *\n * This class provides stereo matching functionality to the SMTK toolkit.  It\n * registers points, clones them by adjusting parameters to nearby point\n * locations and manages point selection processes.\n *\n * The Gruen algorithm is initialized here and maintained for use in the\n * stereo matching process.\n *\n * @author 2011-05-28 Kris Becker\n *\n * @internal\n *   @history 2012-12-20 Debbie A. Cook - Removed unused Projection.h\n *                           References #775.\n *   @history 2017-08-18 Summer Stapleton, Ian Humphrey, Tyler Wilson - \n *                           Changed auto_ptr reference to QSharedPointer\n *                           so this class compiles under C++14.  \n *                           References #4809.\n */\nclass SmtkMatcher {\n  public:\n    SmtkMatcher();\n    SmtkMatcher(const QString &regdef);\n    SmtkMatcher(const QString &regdef, Cube *lhImage, Cube *rhImage);\n    SmtkMatcher(Cube *lhImage, Cube *rhImage);\n    ~SmtkMatcher();\n\n    void setImages(Cube *lhImage, Cube *rhImage);\n    void setGruenDef(const QString &regdef);\n\n    bool isValid(const Coordinate &pnt);\n    bool isValid(const SmtkPoint &spnt);\n\n    /** Return pattern chip */\n    Chip *PatternChip() const {\n      validate();\n      return (m_gruen->PatternChip());\n    }\n\n    /** Return search chip */\n    Chip *SearchChip() const {\n      validate();\n      return (m_gruen->SearchChip());\n    }\n\n    /** Returns the fit chip */\n    Chip *FitChip() const {\n      validate();\n      return (m_gruen->FitChip());\n    }\n\n    void setWriteSubsearchChipPattern(const QString &fileptrn = \"SmtkMatcher\");\n\n    SmtkQStackIter FindSmallestEV(SmtkQStack &stack);\n    SmtkQStackIter FindExpDistEV(SmtkQStack &stack, const double &seedsample,\n                                 const double &minEV, const double &maxEV);\n\n    SmtkPoint Register(const Coordinate &lpnt,\n                       const AffineRadio &affrad = AffineRadio());\n    SmtkPoint Register(const PointPair &pnts,\n                       const AffineRadio &affrad = AffineRadio());\n    SmtkPoint Register(const SmtkPoint &spnt,\n                       const AffineRadio &affrad = AffineRadio());\n    SmtkPoint Register(const PointGeometry &lpg, const PointGeometry &rpg,\n                       const AffineRadio &affrad  = AffineRadio());\n\n    SmtkPoint Create(const Coordinate &left, const Coordinate &right);\n    SmtkPoint Clone(const SmtkPoint &point, const Coordinate &left);\n\n    inline BigInt OffImageErrorCount() const { return (m_offImage);  }\n    inline BigInt SpiceErrorCount() const { return (m_spiceErr);  }\n\n    /** Return Gruen template parameters */\n    PvlGroup RegTemplate() { return (m_gruen->RegTemplate());  }\n    /** Return Gruen registration statistics */\n    Pvl RegistrationStatistics() { return (m_gruen->RegistrationStatistics()); }\n\n  private:\n    SmtkMatcher &operator=(const SmtkMatcher &matcher); // Assignment disabled\n    SmtkMatcher(const SmtkMatcher &matcher);            // Copy const disabled\n\n    Cube     *m_lhCube;                // Left image cube (not owned)\n    Cube     *m_rhCube;                // Right image cube (not owned)\n    QSharedPointer<Gruen> m_gruen;     // Gruen matcher\n    BigInt  m_offImage;                // Offimage counter\n    BigInt  m_spiceErr;                // SPICE distance error\n    bool    m_useAutoReg;              // Select AutoReg features\n    const gsl_rng_type * T;            // GSL random number type\n    gsl_rng * r;                       // GSL random number generator\n\n    void randomNumberSetup();\n    bool validate(const bool &throwError = true) const;\n\n    inline Camera &lhCamera() { return (*m_lhCube->camera());   }\n    inline Camera &rhCamera() { return (*m_rhCube->camera());   }\n\n    Coordinate getLineSample(Camera &camera, const Coordinate &geom);\n    Coordinate getLatLon(Camera &camera, const Coordinate &pnt);\n\n    bool inCube(const Camera &camera, const Coordinate &point) const;\n\n    SmtkPoint makeRegisteredPoint(const PointGeometry &left,\n                                  const PointGeometry &right, Gruen *gruen);\n};\n} // namespace Isis\n\n#endif\n", "meta": {"hexsha": "80c78332ab7b072489b31dd36bf7eb25b07f01b1", "size": 4694, "ext": "h", "lang": "C", "max_stars_repo_path": "isis/src/base/objs/SmtkMatcher/SmtkMatcher.h", "max_stars_repo_name": "kdl222/ISIS3", "max_stars_repo_head_hexsha": "aab0e63088046690e6c031881825596c1c2cc380", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 134.0, "max_stars_repo_stars_event_min_datetime": "2018-01-18T00:16:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T03:53:33.000Z", "max_issues_repo_path": "isis/src/base/objs/SmtkMatcher/SmtkMatcher.h", "max_issues_repo_name": "kdl222/ISIS3", "max_issues_repo_head_hexsha": "aab0e63088046690e6c031881825596c1c2cc380", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 3825.0, "max_issues_repo_issues_event_min_datetime": "2017-12-11T21:27:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:45:20.000Z", "max_forks_repo_path": "isis/src/base/objs/SmtkMatcher/SmtkMatcher.h", "max_forks_repo_name": "jlaura/isis3", "max_forks_repo_head_hexsha": "2c40e08caed09968ea01d5a767a676172ad20080", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 164.0, "max_forks_repo_forks_event_min_datetime": "2017-11-30T21:15:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T10:22:29.000Z", "avg_line_length": 35.2932330827, "max_line_length": 80, "alphanum_fraction": 0.650404772, "num_tokens": 1135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.02675928619301897, "lm_q1q2_score": 0.012025426118677263}}
{"text": "#include \"rb_sm.h\"\n#include <stdio.h>\n#include <gsl/gsl_nan.h>\n#include <options/options.h>\n\nstruct sm_params rb_sm_params; \nstruct sm_result rb_sm_result;\n\nvoid rb_sm_init_journal(const char*journal_file) {\n\tjj_set_stream(open_file_for_writing(journal_file));\n/*\tsm_journal_open(journal_file);*/\n}\n\nvoid rb_sm_close_journal() {\n\tFILE * s = jj_get_stream();\n\tif(s) fclose(s);\n\t\n\tjj_set_stream(0);\n}\n\nvoid rb_sm_odometry(double x, double y, double theta){\n\trb_sm_params.first_guess[0]=x;\n\trb_sm_params.first_guess[1]=y;\n\trb_sm_params.first_guess[2]=theta;\n}\n\nvoid rb_sm_odometry_cov(double cov_x, double cov_y, double cov_theta){\n\t\n}\n\nstruct option* ops = 0;\n\nint rb_sm_set_configuration(const char*name, const char*value) {\n\tif(!ops) { \n\t\tops = options_allocate(30);\n\t\tsm_options(&rb_sm_params, ops);\n\t}\n\t\n\tif(!options_try_pair(ops, name, value)) {\n\n\t\treturn 0;\n\t} else\n\treturn 1;\n}\n\nconst char *rb_result_to_json() {\n\tstatic char buf[5000];\n\tJO jo = result_to_json(&rb_sm_params, &rb_sm_result);\n\tstrcpy(buf, jo_to_string(jo));\n\tjo_free(jo);\n\treturn buf;\n}\n\nint rb_sm_icp() {\n\tsm_icp(&rb_sm_params, &rb_sm_result);\n\treturn rb_sm_result.valid;\n}\n\nint rb_sm_gpm() {\t\n\tsm_gpm(&rb_sm_params, &rb_sm_result);\n\treturn rb_sm_result.valid;\n}\n\nvoid rb_set_laser_ref(const char*s) {\n\trb_sm_params.laser_ref = string_to_ld(s);\n/*\tfprintf(stderr, \"Set laser_ref to %p\\n \", rb_sm_params.laser_ref );*/\n}\n\nvoid rb_set_laser_sens(const char*s) {\n\trb_sm_params.laser_sens = string_to_ld(s);\n/*\tfprintf(stderr, \"Set laser_sens to %p\\n \", rb_sm_params.laser_sens );*/\n}\n\nvoid rb_sm_cleanup() {\n\tif(rb_sm_params.laser_ref)\n\tld_free(rb_sm_params.laser_ref);\n\tif(rb_sm_params.laser_sens)\n\tld_free(rb_sm_params.laser_sens);\n}\n\nLDP string_to_ld(const char*s) {\n\tJO jo = json_parse(s);\n\tif(!jo) {\n\t\tfprintf(stderr, \"String passed from Ruby is invalid JSON: \\n\\n%s\\n\", s);\n\t\treturn 0;\n\t}\n\tLDP ld = json_to_ld(jo);\n\tif(!ld) {\n\t\tfprintf(stderr, \"String passed from Ruby is valid JSON, \"\n\t\t\t\"but can't load laser_data. \\n\\n%s\\n\", s);\n\t\treturn 0;\n\t}\n\tjo_free(jo);\n\treturn ld;\n}\n\n", "meta": {"hexsha": "53da151003c1a66147e415ea9cf24a085bdf6efe", "size": 2051, "ext": "c", "lang": "C", "max_stars_repo_path": "src/csm/misc/sm_ruby_wrapper/rb_sm.c", "max_stars_repo_name": "alecone/ROS_project", "max_stars_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/csm/misc/sm_ruby_wrapper/rb_sm.c", "max_issues_repo_name": "alecone/ROS_project", "max_issues_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/csm/misc/sm_ruby_wrapper/rb_sm.c", "max_forks_repo_name": "alecone/ROS_project", "max_forks_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1443298969, "max_line_length": 74, "alphanum_fraction": 0.7196489517, "num_tokens": 610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3522017956470284, "lm_q2_score": 0.034100422767461905, "lm_q1q2_score": 0.012010230131022892}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <gsl/vector/gsl_vector.h>\n#include <gsl/gsl_math.h>\n\n#define BASE_DOUBLE\n#include <gsl/templates_on.h>\n#include <gsl/vector/minmax_source.c>\n#include <gsl/templates_off.h>\n#undef BASE_DOUBLE\n\n", "meta": {"hexsha": "00a3849860eebcdea32338646aec1c80b769bc93", "size": 240, "ext": "c", "lang": "C", "max_stars_repo_path": "Cartwheel/cartwheel-3d/gsl/vector/minmax.c", "max_stars_repo_name": "MontyThibault/centre-of-mass-awareness", "max_stars_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Cartwheel/cartwheel-3d/gsl/vector/minmax.c", "max_issues_repo_name": "MontyThibault/centre-of-mass-awareness", "max_issues_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cartwheel/cartwheel-3d/gsl/vector/minmax.c", "max_forks_repo_name": "MontyThibault/centre-of-mass-awareness", "max_forks_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0, "max_line_length": 37, "alphanum_fraction": 0.7625, "num_tokens": 63, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167300566462553, "lm_q2_score": 0.027169231831071214, "lm_q1q2_score": 0.01199991628442824}}
{"text": "#if !defined(fvSupport_h)\n#define fvSupport_h\n\n#include <petsc.h>\n\n#define MAX_FVM_RHS_FUNCTION_FIELDS 4\n\ntypedef PetscErrorCode (*FVMRHSFluxFunction)(PetscInt dim, const PetscFVFaceGeom *fg, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar fieldL[], const PetscScalar fieldR[],\n                                             const PetscScalar gradL[], const PetscScalar gradR[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar auxL[], const PetscScalar auxR[],\n                                             const PetscScalar gradAuxL[], const PetscScalar gradAuxR[], PetscScalar flux[], void *ctx);\n\ntypedef PetscErrorCode (*FVMRHSPointFunction)(PetscInt dim, const PetscFVCellGeom *cg, const PetscInt uOff[], const PetscScalar u[], const PetscInt aOff[], const PetscScalar a[], PetscScalar f[], void *ctx);\n\ntypedef PetscErrorCode (*FVAuxFieldUpdateFunction)(PetscReal time, PetscInt dim, const PetscFVCellGeom *cellGeom, const PetscScalar *conservedValues, PetscScalar *auxField, void *ctx);\n\n/**\n * struct to describe how to compute RHS finite volume flux source terms\n */\nstruct _FVMRHSFluxFunctionDescription {\n    FVMRHSFluxFunction function;\n    void *context;\n\n    PetscInt field;\n    PetscInt inputFields[MAX_FVM_RHS_FUNCTION_FIELDS];\n    PetscInt numberInputFields;\n\n    PetscInt auxFields[MAX_FVM_RHS_FUNCTION_FIELDS];\n    PetscInt numberAuxFields;\n};\n\ntypedef struct _FVMRHSFluxFunctionDescription FVMRHSFluxFunctionDescription;\n\n/**\n * struct to describe how to compute RHS finite volume point source terms\n */\nstruct _FVMRHSPointFunctionDescription {\n    FVMRHSPointFunction function;\n    void *context;\n\n    PetscInt fields[MAX_FVM_RHS_FUNCTION_FIELDS];\n    PetscInt numberFields;\n\n    PetscInt inputFields[MAX_FVM_RHS_FUNCTION_FIELDS];\n    PetscInt numberInputFields;\n\n    PetscInt auxFields[MAX_FVM_RHS_FUNCTION_FIELDS];\n    PetscInt numberAuxFields;\n};\n\ntypedef struct _FVMRHSPointFunctionDescription FVMRHSPointFunctionDescription;\n\n/**\n  DMPlexTSComputeRHSFunctionFVM - Form the local forcing F from the local input X using flux and pointfunctions specified by the user\n\n  Input Parameters:\n+ dm - The mesh\n. t - The time\n. locX  - Local solution\n- user - The user context\n\n  Output Parameter:\n. F  - Global output vector\n\n  Level: developer\n\n.seealso: DMPlexComputeJacobianActionFEM()\n**/\nPETSC_EXTERN PetscErrorCode ABLATE_DMPlexComputeRHSFunctionFVM(FVMRHSFluxFunctionDescription *fluxFunctionDescriptions, PetscInt numberFluxFunctionDescription,\n                                                               FVMRHSPointFunctionDescription *pointFunctionDescriptions, PetscInt numberPointFunctionDescription, DM dm, PetscReal time, Vec locX, Vec F);\n\n/**\n * Populate the boundary with gradient information\n * @param dm\n * @param auxDM\n * @param time\n * @param locXVec\n * @param locAuxField\n * @param numberUpdateFunctions\n * @param updateFunctions\n * @param data\n * @return\n */\n\n/**\n * Takes all local vector\n * @return\n */\nPETSC_EXTERN PetscErrorCode ABLATE_DMPlexComputeFluxResidual_Internal(FVMRHSFluxFunctionDescription functionDescription[], PetscInt numberFunctionDescription, DM, IS, PetscReal, Vec, Vec, PetscReal, Vec);\n\n/**\n   Form the local forcing F from the local input X using pointwise functions specified by the user\n\n  Input Parameters:\n+ dm - The mesh\n. t - The time\n. locX  - Local solution\n\n  Output Parameter:\n. F  - local output vector\n\n**/\nPETSC_EXTERN PetscErrorCode ABLATE_DMPlexComputePointResidual_Internal(FVMRHSPointFunctionDescription *functionDescription, PetscInt numberFunctionDescription, DM, IS, PetscReal, Vec, Vec, PetscReal, Vec);\n\n/**\n * reproduces the petsc call with grad fixes for multiple fields\n * @param dm\n * @param fvm\n * @param locX\n * @param grad\n * @return\n */\nPETSC_EXTERN PetscErrorCode DMPlexReconstructGradientsFVM_MulfiField(DM dm, PetscFV fvm, Vec locX, Vec grad);\n\n/**\n * reproduces the petsc call with grad fixes for multiple fields\n * @param dm\n * @param fvm\n * @param locX\n * @param grad\n * @return\n */\nPETSC_EXTERN PetscErrorCode DMPlexGetDataFVM_MulfiField(DM dm, PetscFV fv, Vec *cellgeom, Vec *facegeom, DM *gradDM);\n\n/**\n * Function to update all cells.  This should be merged into other update calls\n * @param dm\n * @param auxDM\n * @param time\n * @param locXVec\n * @param locAuxField\n * @param numberUpdateFunctions\n * @param updateFunctions\n * @param ctx\n * @return\n */\nPETSC_EXTERN PetscErrorCode FVFlowUpdateAuxFieldsFV(DM dm, DM auxDM, PetscReal time, Vec locXVec, Vec locAuxField, PetscInt numberUpdateFunctions, FVAuxFieldUpdateFunction *updateFunctions, void **ctx);\n\n#endif", "meta": {"hexsha": "4565e02bca7cf4b58b2b67e4770a464bb5cd7898", "size": 4604, "ext": "h", "lang": "C", "max_stars_repo_path": "ablateCore/flow/fvSupport.h", "max_stars_repo_name": "mschulwitz/ablate", "max_stars_repo_head_hexsha": "27df14008f0d0c595bc25334a2f5a4ef7ccbe4bf", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ablateCore/flow/fvSupport.h", "max_issues_repo_name": "mschulwitz/ablate", "max_issues_repo_head_hexsha": "27df14008f0d0c595bc25334a2f5a4ef7ccbe4bf", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ablateCore/flow/fvSupport.h", "max_forks_repo_name": "mschulwitz/ablate", "max_forks_repo_head_hexsha": "27df14008f0d0c595bc25334a2f5a4ef7ccbe4bf", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3623188406, "max_line_length": 207, "alphanum_fraction": 0.7517376195, "num_tokens": 1153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3451052709578724, "lm_q2_score": 0.03461884207619153, "lm_q1q2_score": 0.011947144874951871}}
{"text": "/* ieee-utils/read.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <stdlib.h>\n#include <string.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_ieee_utils.h>\n\nstatic int \nlookup_string (const char * p, int * precision, int * rounding, \n               int * exception_mask) ;\n\nint\ngsl_ieee_read_mode_string (const char * description, \n                           int * precision, \n                           int * rounding, \n                           int * exception_mask)\n{\n  char * start ;\n  char * end;\n  char * p;\n\n  int precision_count = 0 ;\n  int rounding_count = 0 ;\n  int exception_count = 0 ;\n\n  start = (char *) malloc(strlen(description) + 1) ;\n\n  if (start == 0) \n    {\n      GSL_ERROR (\"no memory to parse mode string\", GSL_ENOMEM) ;\n    }\n\n  strcpy (start, description) ;\n\n  p = start ;\n\n  *precision = 0 ;\n  *rounding = 0 ;\n  *exception_mask = 0 ;\n\n  do {\n    int status ;\n    int new_precision, new_rounding, new_exception ;\n\n    end = strchr (p,',') ;\n\n    if (end) \n      {\n        *end = '\\0' ;\n        do \n          {\n            end++ ;  /* skip over trailing whitespace */\n          } \n        while (*end == ' ' || *end == ',') ;\n      }\n        \n    new_precision = 0 ; \n    new_rounding = 0 ; \n    new_exception = 0 ;\n\n    status = lookup_string (p, &new_precision, &new_rounding, &new_exception) ;\n\n    if (status)\n      GSL_ERROR (\"unrecognized GSL_IEEE_MODE string.\\nValid settings are:\\n\\n\" \n                 \"  single-precision double-precision extended-precision\\n\"\n                 \"  round-to-nearest round-down round-up round-to-zero\\n\"\n                 \"  mask-invalid mask-denormalized mask-division-by-zero\\n\"\n                 \"  mask-overflow mask-underflow mask-all\\n\"\n                 \"  trap-common trap-inexact\\n\"\n                 \"\\n\"\n                 \"separated by commas. \"\n                 \"(e.g. GSL_IEEE_MODE=\\\"round-down,mask-underflow\\\")\",\n                 GSL_EINVAL) ;\n\n    if (new_precision) \n      {\n        *precision = new_precision ;\n        precision_count ++ ;\n        if (precision_count > 1)\n          GSL_ERROR (\"attempted to set IEEE precision twice\", GSL_EINVAL) ;\n      }\n\n    if (new_rounding) \n      {\n        *rounding = new_rounding ;\n        rounding_count ++ ;\n        if (rounding_count > 1)\n          GSL_ERROR (\"attempted to set IEEE rounding mode twice\", GSL_EINVAL) ;\n      }\n\n    if (new_exception) \n      {\n        *exception_mask |= new_exception ;\n        exception_count ++ ;\n      }\n\n    p = end ; \n\n  } while (end && *p != '\\0') ;\n\n  free(start) ;\n\n  return GSL_SUCCESS ;\n}\n\nstatic int \nlookup_string (const char * p, int * precision, int * rounding, \n               int * exception_mask)\n{\n  if (strcmp(p,\"single-precision\") == 0) \n    {\n      *precision = GSL_IEEE_SINGLE_PRECISION ;\n    }\n  else if (strcmp(p,\"double-precision\") == 0) \n    {\n      *precision = GSL_IEEE_DOUBLE_PRECISION ;\n    }\n  else if (strcmp(p,\"extended-precision\") == 0) \n    {\n      *precision = GSL_IEEE_EXTENDED_PRECISION ;\n    }\n  else if (strcmp(p,\"round-to-nearest\") == 0) \n    {\n      *rounding = GSL_IEEE_ROUND_TO_NEAREST ;\n    }\n  else if (strcmp(p,\"round-down\") == 0) \n    {\n      *rounding = GSL_IEEE_ROUND_DOWN ;\n    }\n  else if (strcmp(p,\"round-up\") == 0) \n    {\n      *rounding = GSL_IEEE_ROUND_UP ;\n    }\n  else if (strcmp(p,\"round-to-zero\") == 0) \n    {\n      *rounding = GSL_IEEE_ROUND_TO_ZERO ;\n    }\n  else if (strcmp(p,\"mask-all\") == 0) \n    {\n      *exception_mask = GSL_IEEE_MASK_ALL ;\n    }\n  else if (strcmp(p,\"mask-invalid\") == 0) \n    {\n      *exception_mask = GSL_IEEE_MASK_INVALID ;\n    }\n  else if (strcmp(p,\"mask-denormalized\") == 0) \n    {\n      *exception_mask = GSL_IEEE_MASK_DENORMALIZED ;\n    }\n  else if (strcmp(p,\"mask-division-by-zero\") == 0) \n    {\n      *exception_mask = GSL_IEEE_MASK_DIVISION_BY_ZERO ;\n    }\n  else if (strcmp(p,\"mask-overflow\") == 0) \n    {\n      *exception_mask = GSL_IEEE_MASK_OVERFLOW ;\n    }\n  else if (strcmp(p,\"mask-underflow\") == 0) \n    {\n      *exception_mask = GSL_IEEE_MASK_UNDERFLOW ;\n    }\n  else if (strcmp(p,\"trap-inexact\") == 0) \n    {\n      *exception_mask = GSL_IEEE_TRAP_INEXACT ;\n    }\n  else if (strcmp(p,\"trap-common\") == 0) \n    {\n      return 0 ;\n    }\n  else\n    {\n      return 1 ;\n    }\n\n  return 0 ;\n}\n", "meta": {"hexsha": "1de26e84ab78d832cd0cfd95b9e5633d34f4b5ce", "size": 5025, "ext": "c", "lang": "C", "max_stars_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/ieee-utils/read.c", "max_stars_repo_name": "ruslankuzmin/julia", "max_stars_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/ieee-utils/read.c", "max_issues_repo_name": "skair39/structured", "max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/ieee-utils/read.c", "max_forks_repo_name": "skair39/structured", "max_forks_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 25.7692307692, "max_line_length": 81, "alphanum_fraction": 0.5791044776, "num_tokens": 1350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24798741512455283, "lm_q2_score": 0.04813677026317784, "lm_q1q2_score": 0.011937313230009914}}
{"text": "/*\n\nExcited States software: KGS\nContributors: See CONTRIBUTORS.txt\nContact: kgs-contact@simtk.org\n\nCopyright (C) 2009-2017 Stanford University\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\n\nThis entire text, including the above copyright notice and this permission notice\nshall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS, CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\nOTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\nIN THE SOFTWARE.\n\n*/\n\n#ifndef CONFIGURATION_H\n#define CONFIGURATION_H\n\n#include <list>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <vector>\n#include <tuple>\n\n#include \"math/Nullspace.h\"\n#include \"math/Eigenvalue.h\"\n#include \"core/graph/KinGraph.h\"\n\nclass Molecule;\nclass Selection;\n\n\n/**\n * A configuration holds all DOF-values necessary to update a molecules atom-positions.\n * DOF-values are relative to whatever is stored in the Atom::reference_positions, so calling\n * Configuration* conf = new Configuration(m_protein);\n * will create a configuration where all DOF-values are 0 and which represents whatever is in\n * the reference positions of m_protein. Modifying for example\n * conf->m_dofs[2] += 0.1\n * will add 0.1 units (often radians) to the third DOF. To see the resulting structure call either\n * m_protein->setConfiguration(conf);\n * or\n * conf->updatedProtein();\n * and then access Atom::position (not Atom::m_referencePosition).\n *\n * As new configurations are generated from older ones, the field m_children and m_parent store the\n * connectivity information.\n */\nclass Configuration\n{\n public:\n  double *m_dofs;                    ///< DOF-values (relative to Atom::m_referencePosition)\n  //double *m_sumProjSteps;          //TODO: What is this?\n\n  /** Construct a configuration with all DOF-values set to 0 and no m_parent. */\n  Configuration(Molecule * mol);\n\n  /** Construct a configuration with all DOF-values set to 0 and the specified m_parent. */\n  Configuration(Configuration* parent);\n\n  ~Configuration();\n\n  double getGlobalTorsion( int i ) ; ///< Get a global DOF-value\n  double* getGlobalTorsions() ;     ///< Get global DOF-value array\n\n  unsigned int getNumDOFs() const;\n\n  /** Set the specified dof to the global torsion value. Convenient function for\n   * calculating difference between reference torsion and val. */\n  void setGlobalTorsion(int i, double val);\n\n  Configuration* clone() const;          ///< Copy this configuration\n\n  void Print();                          // TODO: Remove or rename to printDOFs\n//  Molecule* collapseRigidBonds();\n//  void identifyBiggerRigidBodies();      ///< Identify clusters\n//  void readBiggerSet();                  ///< read the set of clusters, related to identifying clusters\n  void projectOnCycleNullSpace (gsl_vector *to_project, gsl_vector *after_project);\n\n  void convertAllDofsToCycleDofs( gsl_vector *cycleDofs, gsl_vector *allDofs);\n  void convertCycleDofsToAllDofs( gsl_vector *allDofsAfter, gsl_vector *cycleDofs, gsl_vector *allDofsBefore = nullptr);\n\n//  static bool compareSize(std::pair<int, unsigned int> firstEntry, std::pair<int, unsigned int> secondEntry);//TODO: What is this?\n\n  void writeQToBfactor();\n\n  // When the samples are generated as an expanding tree, the m_children and m_parent store the connectivity information of these nodes\n  const int m_treeDepth;             ///< Depth in the exploration tree\n  int m_id;                         ///< ID of configuration\n  double m_vdwEnergy;               ///< van der Waals energy of configuration\n  double m_deltaH;                  ///< change in enthalpy due to clash constraints\n  double m_distanceToTarget;        ///< Distance to target configuration\n  double m_distanceToParent;        ///< Distance to m_parent configuration\n  double m_distanceToIni;           ///< Distance to initial configuration\n  double m_paretoFrontDistance;\n  double m_maxConstraintViolation;  //Maximum detected distance violation of h-bond constraints, Todo: maybe not necessary to keep\n  double m_minCollisionFactor;      //minimum necessary clash-factor for configuration to be clash free, Todo: maybe not necessary to keep\n  double m_usedClashPrevention;\n\n//  std::map<unsigned int, Rigidbody*> m_biggerRBMap;  // <Cluster-idx, Pointer-to-cluster>\n//  std::vector< std::pair<int, unsigned int> > m_sortedRBs; // < cluster-idx, cluster size>\n\n  int m_numClusters;             ///< Number of rigid clusters (super rigid bodies)\n  int m_maxIndex;                ///< Index of largest cluster\n  int m_maxSize;                 ///< Size of largest cluster\n  int m_clashFreeDofs;           ///< Number of clash-free dofs (for post-processing)\n\n  Molecule * updatedMolecule();  ///< Update the atom-positions to reflect this configuration and return the molecule\n  Molecule * getMolecule() const;///< Return the associated molecule\n  void updateMolecule();         ///< Update the atom-positions to reflect this configuration\n\n  /** Return the cycle jacobian. Calls computeJacobians if CycleJacobian is not up to date */\n  gsl_matrix* getCycleJacobian();\n  Nullspace* getNullspace();    ///< Compute the nullspace (if it wasn't already) and return it\n  //Nullspace* getNullspaceligand();  ///< Compute the nullspace for ligand (if it wasn't already) and return it\n  Nullspace* getNullspacenocoupling();\n  void Hessianmatrixentropy(double cutoff=20.0, double coefficientvalue=1.0, double vdwenergyvalue=10000.0, Nullspace* Nu=nullptr, Molecule* mol=nullptr, bool proteinonly=false, std::string nocoupling=\"true\");  ///< Compute the nullspace for vibrational entropy (if it wasn't already) and return it\n  Eigenvalue* geteigenvalue();\n  gsl_matrix* getHydrophobicJacobian();\n  gsl_matrix* getHydrogenJacobian();\n  gsl_matrix* getDistanceJacobian();\n\n  void rigidityAnalysis();\n  void deleteNullspace(); ///if not needed anymore, save memory\n\n  Configuration* getParent();   ///< Access configuration that spawned this one\n  std::list<Configuration*>& getChildren(); ///< Access child configurations\n\n  double siteDOFTransfer(Selection& source, Selection& sink,gsl_matrix* baseMatrix); //\n  void sortFreeEnergyModes(gsl_matrix* baseMatrix, gsl_vector* singVals, gsl_vector* returnIDs); //return index list of modes sorted by free energy\n  int getNumRigidDihedralsligand();\n\n  bool checknocoupling();\n  static Nullspace* ClashAvoidingNullSpace; //TODO: Make private (or even better put in ClashAvoidingMove).\n  void setrigiddofid();\n    \n protected:\n\n    int numligandRigidDihedrals=0; ///< Rigid dihedrals in ligand\n  void updateGlobalTorsions();           ///< Update the global DOF-values (m_dofs_global field)\n  double *m_dofs_global;                 ///< DOF-values in a global system (not relative to Atom::reference_position)\n  Molecule * const m_molecule;           ///< The molecule related to the configuration\n  Configuration * m_parent;              ///< The parent-configuration this configuration was generated from\n  std::list<Configuration*> m_children;  ///< List of child-configurations\n\n  void computeCycleJacobianAndNullSpace();\n  void computeCycleJacobianentropyforall();\n  void computeCycleJacobianentropy(Nullspace* Nu,std::string nocoupling);\n  void computeMassmatrix();\n  void computedistancematrix(Molecule* mol);\n  void computeHessiancartesian(double cutoff, double coefficientvalue, double vdwenergyvalue,Molecule* mol);\n  void computeJacobians();               ///< Compute non-redundant cycle jacobian and hbond-jacobian // and also HydrophobicBond-jacobian\n  // Jacobian matrix of all the cycles of rigid bodies\n  void computeJacobiansnocoupling();\n  static gsl_matrix* CycleJacobian; // column dimension is the number of DOFs; row dimension is 5 times the number of cycles because 2 atoms on each cycle-closing edge\n  //static gsl_matrix* CycleJacobianligand;// column dimension is the number of DOFS; row dimension is the number of cycles\\//\n  //static gsl_matrix* ClashAvoidingJacobian;\n  //Nullspace* nullspaceligand;\n  //static SVD* JacobianSVDligand;\n  static gsl_matrix* CycleJacobiannocoupling;\n  gsl_matrix* CycleJacobianentropy;// column dimension is the number of DOFS; row dimension is the number of cycles\\//\n  gsl_matrix* CycleJacobianentropycoupling;\n  gsl_matrix* CycleJacobianentropynocoupling;\n  gsl_matrix* Hessianmatrix_cartesian;\n  static gsl_matrix* Massmatrix;\n  static gsl_matrix* distancematrix;\n  static gsl_matrix* coefficientmatrix;\n  Eigenvalue* Entropyeigen;\n  static gsl_matrix* HBondJacobian; // column dimension is the number of DOFS; row dimension is the number of cycles\\//\n  static gsl_matrix* HydrophobicBondJacobian; //column dimension is the number of DOFs; row dimension is the 5 times the number of Hydrophobic bond\n  static gsl_matrix* DBondJacobian; //column dimension is the number of DOFs; row dimension is the 5 times the number of Hydrophobic bond\n  static Configuration* CycleJacobianOwner;\n\n  static SVD* JacobianSVD;\n  static SVD* JacobianSVDnocoupling;\n  Nullspace* nullspace;                  ///< Nullspace of hbond of this configuration\n  Nullspace* nullspacenocoupling;\n  Nullspace* nullspaceHydro;\n  \n};\n\n\n\n\n#endif\n\n", "meta": {"hexsha": "32e36b11ee5a7a586dca6e4d74edac69d18a8ad8", "size": 9845, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/Configuration.h", "max_stars_repo_name": "XiyuChenFAU/kgs_vibration_entropy", "max_stars_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/Configuration.h", "max_issues_repo_name": "XiyuChenFAU/kgs_vibration_entropy", "max_issues_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/Configuration.h", "max_forks_repo_name": "XiyuChenFAU/kgs_vibration_entropy", "max_forks_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.225, "max_line_length": 298, "alphanum_fraction": 0.7447435246, "num_tokens": 2330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.02405355258834728, "lm_q1q2_score": 0.01193281901593335}}
{"text": "#pragma once\n\n#include <optional>\n#include <sam.h>\n#include <gsl/span>\n#include \"clocks.h\"\n#include \"utils.h\"\n\nnamespace mcu {\n\nclass I2cMaster {\npublic:\n\tI2cMaster(Sercom* sercom, const mcu::ClockGenerator& clock, const mcu::ClockGenerator& slowClock, unsigned frequency = 100000)\n\t\t:port{sercom->I2CM}\n\t{\n\t\tint sercomIndex = mcu::util::getSercomIndex(sercom);\n\t\tPM->APBCMASK.reg |= 1 << (PM_APBCMASK_SERCOM0_Pos + sercomIndex);\n\t\tclock.routeToPeripheral(GCLK_CLKCTRL_ID_SERCOM0_CORE_Val + sercomIndex);\n\t\tslowClock.routeToPeripheral(GCLK_CLKCTRL_ID_SERCOMX_SLOW_Val);\n\n\t\tport.CTRLA.reg = SERCOM_I2CM_CTRLA_MODE_I2C_MASTER;\n\t\t(void)port.CTRLB.reg;\n\t\tvolatile uint32_t ctrla = port.CTRLA.reg;\n\t\tport.CTRLB.reg = 0;\n\t\tport.BAUD.reg = computeBaud(frequency, clock.frequency);\n\t\twhile (port.STATUS.bit.SYNCBUSY);\n\t\tport.CTRLA.bit.ENABLE = true;\n\t\twhile (port.STATUS.bit.SYNCBUSY);\n\t\tport.STATUS.bit.BUSSTATE = BusstateIdle;\n\t}\n\n\tstd::optional<std::byte> readReg(uint8_t slaveAddress, uint8_t reg)\n\t{\n\t\tport.ADDR.reg = (slaveAddress << 1) | 0;\n\t\twhile (port.INTFLAG.reg == 0);\n\t\tport.INTFLAG.reg = SERCOM_I2CM_INTFLAG_MB | SERCOM_I2CM_INTFLAG_SB;\n\t\tif (port.STATUS.reg & (StatusErrorMask | SERCOM_I2CM_STATUS_RXNACK) != 0) {\n\t\t\tif (port.STATUS.bit.BUSSTATE == BusstateOwner)\n\t\t\t\tport.CTRLB.reg = SERCOM_I2CM_CTRLB_CMD(CommandStop);\n\t\t\treturn std::nullopt;\n\t\t}\n\t\t\n\t\tport.DATA.reg = reg;\n\t\twhile (port.INTFLAG.reg == 0);\n\t\tport.INTFLAG.reg = SERCOM_I2CM_INTFLAG_MB | SERCOM_I2CM_INTFLAG_SB;\n\t\tif (port.STATUS.reg & StatusErrorMask) {\n\t\t\tif (port.STATUS.bit.BUSSTATE == BusstateOwner)\n\t\t\t\tport.CTRLB.reg = SERCOM_I2CM_CTRLB_CMD(CommandStop);\n\t\t\treturn std::nullopt;\n\t\t}\n\n\t\tport.ADDR.reg = (slaveAddress << 1) | 1;\n\t\twhile (port.INTFLAG.reg == 0);\n\t\tport.INTFLAG.reg = SERCOM_I2CM_INTFLAG_MB | SERCOM_I2CM_INTFLAG_SB;\n\t\tif (port.STATUS.reg & (StatusErrorMask | SERCOM_I2CM_STATUS_RXNACK) != 0) {\n\t\t\tif (port.STATUS.bit.BUSSTATE == BusstateOwner)\n\t\t\t\tport.CTRLB.reg = SERCOM_I2CM_CTRLB_CMD(CommandStop);\n\t\t\treturn std::nullopt;\n\t\t}\n\n\t\tstd::byte result = static_cast<std::byte>(port.DATA.reg);\n\t\tport.CTRLB.reg = SERCOM_I2CM_CTRLB_ACKACT | SERCOM_I2CM_CTRLB_CMD(CommandStop);\n\t\treturn result;\n\t}\n\n\tbool writeReg(uint8_t slaveAddress, uint8_t reg, std::byte data)\n\t{\n\t\tport.ADDR.reg = (slaveAddress << 1) | 0;\n\t\twhile (port.INTFLAG.reg == 0);\n\t\tport.INTFLAG.reg = SERCOM_I2CM_INTFLAG_MB | SERCOM_I2CM_INTFLAG_SB;\n\t\tif (port.STATUS.reg & (StatusErrorMask | SERCOM_I2CM_STATUS_RXNACK) != 0) {\n\t\t\tif (port.STATUS.bit.BUSSTATE == BusstateOwner)\n\t\t\t\tport.CTRLB.reg = SERCOM_I2CM_CTRLB_CMD(CommandStop);\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tport.DATA.reg = reg;\n\t\twhile (port.INTFLAG.reg == 0);\n\t\tport.INTFLAG.reg = SERCOM_I2CM_INTFLAG_MB | SERCOM_I2CM_INTFLAG_SB;\n\t\tif (port.STATUS.reg & (StatusErrorMask | SERCOM_I2CM_STATUS_RXNACK) != 0) {\n\t\t\tif (port.STATUS.bit.BUSSTATE == BusstateOwner)\n\t\t\t\tport.CTRLB.reg = SERCOM_I2CM_CTRLB_CMD(CommandStop);\n\t\t\treturn false;\n\t\t}\n\n\t\tport.DATA.reg = static_cast<uint8_t>(data);\n\t\twhile (port.INTFLAG.reg == 0);\n\t\tport.INTFLAG.reg = SERCOM_I2CM_INTFLAG_MB | SERCOM_I2CM_INTFLAG_SB;\n\t\tif (port.STATUS.reg & (StatusErrorMask) != 0) {\n\t\t\tif (port.STATUS.bit.BUSSTATE == BusstateOwner)\n\t\t\t\tport.CTRLB.reg = SERCOM_I2CM_CTRLB_CMD(CommandStop);\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tport.CTRLB.reg = SERCOM_I2CM_CTRLB_CMD(CommandStop);\n\t\treturn true;\n\t}\n\nprivate:\n\tSercomI2cm& port;\n\t\n\tstatic constexpr unsigned CommandRead = 0x2;\n\tstatic constexpr unsigned CommandStop = 0x3;\n\tstatic constexpr unsigned BusstateIdle = 0x1;\n\tstatic constexpr unsigned BusstateOwner = 0x2;\n\tstatic constexpr unsigned StatusErrorMask = SERCOM_I2CM_STATUS_ARBLOST;\n\t\n\tstatic constexpr unsigned i2cRise = 215;\n\tstatic constexpr uint16_t computeBaud(unsigned desiredFrequency, unsigned coreFrequency)\n\t{\n\t\t//                  coreFreq - (desiredFreq * 10) - (coreFreq * desiredFreq * i2cRise)\n\t\t// BAUD + BAUDLOW = ------------------------------------------------------------------\n\t\t//                  desiredFreq\n\t\tint baudSum = (((coreFrequency - (desiredFrequency * 10) - (i2cRise * (desiredFrequency / 100) * (coreFrequency / 1000) / 10000)) * 10 + 5) / (desiredFrequency * 10));\n\t\tassert(2 <= baudSum && baudSum <= 0xff*2);\n\n\t\tif (baudSum % 2 == 1)\n\t\t\treturn (baudSum / 2) | ((baudSum / 2 + 1) << 8);\n\t\telse\n\t\t\treturn baudSum / 2;\n\t}\n};\n\n}\n", "meta": {"hexsha": "8708a13127e83abda99574b16eedee7d502a0264", "size": 4318, "ext": "h", "lang": "C", "max_stars_repo_path": "include/i2c_master.h", "max_stars_repo_name": "dachsei/platform-samd20", "max_stars_repo_head_hexsha": "520ecaefb0a0c1b92be281d5834f44e927995190", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/i2c_master.h", "max_issues_repo_name": "dachsei/platform-samd20", "max_issues_repo_head_hexsha": "520ecaefb0a0c1b92be281d5834f44e927995190", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/i2c_master.h", "max_forks_repo_name": "dachsei/platform-samd20", "max_forks_repo_head_hexsha": "520ecaefb0a0c1b92be281d5834f44e927995190", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.544, "max_line_length": 169, "alphanum_fraction": 0.7026401112, "num_tokens": 1367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3380771374883919, "lm_q2_score": 0.03514484728505725, "lm_q1q2_score": 0.011881669367598836}}
{"text": "/*\nGENETIC - A simple genetic algorithm.\n\nCopyright 2014, Javier Burguete Tolosa.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\n\tlist of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice,\n\tthis list of conditions and the following disclaimer in the documentation\n\tand/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``AS IS'' AND ANY EXPRESS\nOR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\nEVENT SHALL Javier Burguete Tolosa OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\nINDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\nBUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\nADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n/**\n * \\file evolution.c\n * \\brief Source file to define evolution functions.\n * \\author Javier Burguete Tolosa.\n * \\copyright Copyright 2014 Javier Burguete Tolosa. All rights reserved.\n */\n#define _GNU_SOURCE\n#include <stdio.h>\n#include <string.h>\n#include <math.h>\n#include <gsl/gsl_rng.h>\n//#include \"config.h\"\n#include \"bits.h\"\n#include \"sort.h\"\n#include \"entity.h\"\n#include \"population.h\"\n#include \"mutation.h\"\n#include \"reproduction.h\"\n#include \"adaptation.h\"\n#include \"selection.h\"\n#include \"evolution.h\"\n\n#define DEBUG_EVOLUTION 0       ///< Macro to debug the evolution functions.\n\n/**\n * Function to sort the survivals of the evaluated population\n */\nvoid\nevolution_sort (Population * population)        ///< Population.\n{\n  unsigned int i, j, index[population->nentities];\n  double objective[population->nsurvival];\n  Entity entity[population->nsurvival];\n#if DEBUG_EVOLUTION\n  fprintf (stderr, \"evolution_sort: start\\n\");\n#endif\n  index_new (population->objective, index, population->nentities);\n  for (i = 0; i < population->nsurvival; ++i)\n    {\n      j = index[i];\n      objective[i] = population->objective[j];\n      entity_new (entity + i, population->genome_nbytes, i);\n      memcpy (entity[i].genome, population->entity[j].genome,\n              population->genome_nbytes);\n    }\n  for (i = 0; i < population->nsurvival; ++i)\n    {\n      population->objective[i] = objective[i];\n      memcpy (population->entity[i].genome, entity[i].genome,\n              population->genome_nbytes);\n      entity_free (entity + i);\n    }\n#if DEBUG_EVOLUTION\n  fprintf (stderr, \"evolution_sort: end\\n\");\n#endif\n}\n\n/**\n * Funtion to apply the mutation evolution.\n */\nvoid\nevolution_mutation (Population * population,    ///< Population.\n                    gsl_rng * rng)      ///< GSL random numbers generator.\n{\n  unsigned int i;\n  Entity *mother, *son;\n#if DEBUG_EVOLUTION\n  fprintf (stderr, \"evolution_mutation: start\\n\");\n#endif\n  for (i = population->mutation_max; i > population->mutation_min;)\n    {\n#if DEBUG_EVOLUTION\n      fprintf (stderr, \"evolution_mutation: selection\\n\");\n#endif\n      selection_mutation (population, &mother, rng);\n      son = population->entity + --i;\n#if DEBUG_EVOLUTION\n      fprintf (stderr, \"evolution_mutation: mutation in %u\\n\", i);\n#endif\n      mutation (population, mother, son, rng);\n    }\n#if DEBUG_EVOLUTION\n  fprintf (stderr, \"evolution_mutation: end\\n\");\n#endif\n}\n\n/**\n * Funtion to apply the reproduction evolution.\n */\nvoid\nevolution_reproduction (Population * population,        ///< Population.\n                        gsl_rng * rng)  ///< GSL random numbers generator.\n{\n  unsigned int i;\n  Entity *mother, *father, *son;\n#if DEBUG_EVOLUTION\n  fprintf (stderr, \"evolution_reproduction: start\\n\");\n#endif\n  for (i = population->reproduction_max; i > population->reproduction_min;)\n    {\n#if DEBUG_EVOLUTION\n      fprintf (stderr, \"evolution_reproduction: selection\\n\");\n#endif\n      selection_reproduction (population, &mother, &father, rng);\n      son = population->entity + --i;\n#if DEBUG_EVOLUTION\n      fprintf (stderr, \"evolution_reproduction: reproduction in %u\\n\", i);\n#endif\n      reproduction (mother, father, son, population->genome_nbits, rng);\n    }\n#if DEBUG_EVOLUTION\n  fprintf (stderr, \"evolution_reproduction: end\\n\");\n#endif\n}\n\n/**\n * Funtion to apply the adaptation evolution.\n */\nvoid\nevolution_adaptation (Population * population,  ///< Population.\n                      gsl_rng * rng)    ///< GSL random numbers generator.\n{\n  unsigned int i;\n  Entity *mother, *son;\n#if DEBUG_EVOLUTION\n  fprintf (stderr, \"evolution_adaptation: start\\n\");\n#endif\n  for (i = population->adaptation_max; i > population->adaptation_min;)\n    {\n#if DEBUG_EVOLUTION\n      fprintf (stderr, \"evolution_adaptation: selection\\n\");\n#endif\n      selection_adaptation (population, &mother, rng);\n      son = population->entity + --i;\n#if DEBUG_EVOLUTION\n      fprintf (stderr, \"evolution_adaptation: adaptation in %u\\n\", i);\n#endif\n      adaptation (population, mother, son, rng);\n    }\n#if DEBUG_EVOLUTION\n  fprintf (stderr, \"evolution_adaptation: end\\n\");\n#endif\n}\n", "meta": {"hexsha": "27a1f954bcd76468a9f8e2ef9614479931fe1d37", "size": 5424, "ext": "c", "lang": "C", "max_stars_repo_path": "3.0.0/evolution.c", "max_stars_repo_name": "jburguete/genetic", "max_stars_repo_head_hexsha": "e7b5473412eeb4bdd9d1f724ab555d7329b7156d", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-04-07T07:31:25.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-02T02:31:16.000Z", "max_issues_repo_path": "3.0.0/evolution.c", "max_issues_repo_name": "jburguete/genetic", "max_issues_repo_head_hexsha": "e7b5473412eeb4bdd9d1f724ab555d7329b7156d", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3.0.0/evolution.c", "max_forks_repo_name": "jburguete/genetic", "max_forks_repo_head_hexsha": "e7b5473412eeb4bdd9d1f724ab555d7329b7156d", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-05-22T08:54:08.000Z", "max_forks_repo_forks_event_max_datetime": "2017-05-22T08:54:08.000Z", "avg_line_length": 31.7192982456, "max_line_length": 79, "alphanum_fraction": 0.7081489676, "num_tokens": 1284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3040416623541848, "lm_q2_score": 0.039048291048794204, "lm_q1q2_score": 0.011872307322565423}}
{"text": "/* Copyright (C) 2015 Atsushi Togo */\n/* All rights reserved. */\n\n/* This file is part of phonopy. */\n\n/* Redistribution and use in source and binary forms, with or without */\n/* modification, are permitted provided that the following conditions */\n/* are met: */\n\n/* * Redistributions of source code must retain the above copyright */\n/*   notice, this list of conditions and the following disclaimer. */\n\n/* * Redistributions in binary form must reproduce the above copyright */\n/*   notice, this list of conditions and the following disclaimer in */\n/*   the documentation and/or other materials provided with the */\n/*   distribution. */\n\n/* * Neither the name of the phonopy project nor the names of its */\n/*   contributors may be used to endorse or promote products derived */\n/*   from this software without specific prior written permission. */\n\n/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS */\n/* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT */\n/* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS */\n/* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE */\n/* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, */\n/* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, */\n/* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */\n/* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER */\n/* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT */\n/* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN */\n/* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE */\n/* POSSIBILITY OF SUCH DAMAGE. */\n\n#include <Python.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <numpy/arrayobject.h>\n#include <lapacke.h>\n#include \"phonoc_array.h\"\n#include \"phonon4_h/fc4.h\"\n#include \"phonon4_h/real_to_reciprocal.h\"\n#include \"phonon4_h/frequency_shift.h\"\n\nstatic PyObject * py_get_fc4_normal_for_frequency_shift(PyObject *self, PyObject *args);\nstatic PyObject * py_get_fc4_frequency_shifts(PyObject *self, PyObject *args);\nstatic PyObject * py_real_to_reciprocal4(PyObject *self, PyObject *args);\nstatic PyObject * py_reciprocal_to_normal4(PyObject *self, PyObject *args);\nstatic PyObject * py_set_phonons_grid_points(PyObject *self, PyObject *args);\nstatic PyObject * py_distribute_fc4(PyObject *self, PyObject *args);\nstatic PyObject * py_rotate_delta_fc3s_elem(PyObject *self, PyObject *args);\nstatic PyObject * py_set_translational_invariance_fc4(PyObject *self,\n\t\t\t\t\t\t      PyObject *args);\nstatic PyObject * py_set_permutation_symmetry_fc4(PyObject *self,\n\t\t\t\t\t\t  PyObject *args);\nstatic PyObject * py_get_drift_fc4(PyObject *self, PyObject *args);\n\nstatic PyMethodDef functions[] = {\n  {\"fc4_normal_for_frequency_shift\", py_get_fc4_normal_for_frequency_shift, METH_VARARGS, \"Calculate fc4 normal for frequency shift\"},\n  {\"fc4_frequency_shifts\", py_get_fc4_frequency_shifts, METH_VARARGS, \"Calculate fc4 frequency shift\"},\n  {\"real_to_reciprocal4\", py_real_to_reciprocal4, METH_VARARGS, \"Transform fc4 of real space to reciprocal space\"},\n  {\"reciprocal_to_normal4\", py_reciprocal_to_normal4, METH_VARARGS, \"Transform fc4 of reciprocal space to normal coordinate in special case for frequency shift\"},\n  {\"phonons_grid_points\", py_set_phonons_grid_points, METH_VARARGS, \"Set phonons on grid points\"},\n  {\"distribute_fc4\", py_distribute_fc4, METH_VARARGS, \"Distribute least fc4 to full fc4\"},\n  {\"rotate_delta_fc3s_elem\", py_rotate_delta_fc3s_elem, METH_VARARGS, \"Rotate delta fc3s for a set of atomic indices\"},\n  {\"translational_invariance_fc4\", py_set_translational_invariance_fc4, METH_VARARGS, \"Set translational invariance for fc4\"},\n  {\"permutation_symmetry_fc4\", py_set_permutation_symmetry_fc4, METH_VARARGS, \"Set permutation symmetry for fc4\"},\n  {\"drift_fc4\", py_get_drift_fc4, METH_VARARGS, \"Get drifts of fc4\"},\n  {NULL, NULL, 0, NULL}\n};\n\nPyMODINIT_FUNC init_phono4py(void)\n{\n  Py_InitModule3(\"_phono4py\", functions, \"C-extension for phono4py\\n\\n...\\n\");\n  return;\n}\n\nstatic PyObject * py_get_fc4_normal_for_frequency_shift(PyObject *self,\n\t\t\t\t\t\t\tPyObject *args)\n{\n  PyArrayObject* fc4_normal_py;\n  PyArrayObject* frequencies_py;\n  PyArrayObject* eigenvectors_py;\n  PyArrayObject* grid_points1_py;\n  PyArrayObject* grid_address_py;\n  PyArrayObject* mesh_py;\n  PyArrayObject* fc4_py;\n  PyArrayObject* shortest_vectors_py;\n  PyArrayObject* multiplicity_py;\n  PyArrayObject* masses_py;\n  PyArrayObject* p2s_map_py;\n  PyArrayObject* s2p_map_py;\n  PyArrayObject* band_indicies_py;\n  double cutoff_frequency;\n  int grid_point0;\n\n  if (!PyArg_ParseTuple(args, \"OOOiOOOOOOOOOOd\",\n\t\t\t&fc4_normal_py,\n\t\t\t&frequencies_py,\n\t\t\t&eigenvectors_py,\n\t\t\t&grid_point0,\n\t\t\t&grid_points1_py,\n\t\t\t&grid_address_py,\n\t\t\t&mesh_py,\n\t\t\t&fc4_py,\n\t\t\t&shortest_vectors_py,\n\t\t\t&multiplicity_py,\n\t\t\t&masses_py,\n\t\t\t&p2s_map_py,\n\t\t\t&s2p_map_py,\n\t\t\t&band_indicies_py,\n\t\t\t&cutoff_frequency)) {\n    return NULL;\n  }\n\n  double* fc4_normal = (double*)fc4_normal_py->data;\n  double* freqs = (double*)frequencies_py->data;\n  /* npy_cdouble and lapack_complex_double may not be compatible. */\n  /* So eigenvectors should not be used in Python side */\n  lapack_complex_double* eigvecs =\n    (lapack_complex_double*)eigenvectors_py->data;\n  Iarray* grid_points1 = convert_to_iarray(grid_points1_py);\n  const int* grid_address = (int*)grid_address_py->data;\n  const int* mesh = (int*)mesh_py->data;\n  double* fc4 = (double*)fc4_py->data;\n  Darray* svecs = convert_to_darray(shortest_vectors_py);\n  Iarray* multi = convert_to_iarray(multiplicity_py);\n  const double* masses = (double*)masses_py->data;\n  const int* p2s = (int*)p2s_map_py->data;\n  const int* s2p = (int*)s2p_map_py->data;\n  Iarray* band_indicies = convert_to_iarray(band_indicies_py);\n\n  get_fc4_normal_for_frequency_shift(fc4_normal,\n\t\t\t\t     freqs,\n\t\t\t\t     eigvecs,\n\t\t\t\t     grid_point0,\n\t\t\t\t     grid_points1,\n\t\t\t\t     grid_address,\n\t\t\t\t     mesh,\n\t\t\t\t     fc4,\n\t\t\t\t     svecs,\n\t\t\t\t     multi,\n\t\t\t\t     masses,\n\t\t\t\t     p2s,\n\t\t\t\t     s2p,\n\t\t\t\t     band_indicies,\n\t\t\t\t     cutoff_frequency);\n\n  free(grid_points1);\n  free(svecs);\n  free(multi);\n  free(band_indicies);\n  \n  Py_RETURN_NONE;\n}\n\nstatic PyObject * py_get_fc4_frequency_shifts(PyObject *self, PyObject *args)\n{\n  PyArrayObject* frequency_shifts_py;\n  PyArrayObject* fc4_normal_py;\n  PyArrayObject* frequencies_py;\n  PyArrayObject* grid_points1_py;\n  PyArrayObject* temperatures_py;\n  PyArrayObject* band_indicies_py;\n  double unit_conversion_factor;\n\n  if (!PyArg_ParseTuple(args, \"OOOOOOd\",\n\t\t\t&frequency_shifts_py,\n\t\t\t&fc4_normal_py,\n\t\t\t&frequencies_py,\n\t\t\t&grid_points1_py,\n\t\t\t&temperatures_py,\n\t\t\t&band_indicies_py,\n\t\t\t&unit_conversion_factor)) {\n    return NULL;\n  }\n\n  double* freq_shifts = (double*)frequency_shifts_py->data;\n  double* fc4_normal = (double*)fc4_normal_py->data;\n  double* freqs = (double*)frequencies_py->data;\n  Iarray* grid_points1 = convert_to_iarray(grid_points1_py);\n  Darray* temperatures = convert_to_darray(temperatures_py);\n  int* band_indicies = (int*)band_indicies_py->data;\n  const int num_band0 = (int)band_indicies_py->dimensions[0];\n  const int num_band = (int)frequencies_py->dimensions[1];\n\n  get_fc4_frequency_shifts(freq_shifts,\n\t\t\t   fc4_normal,\n\t\t\t   freqs,\n\t\t\t   grid_points1,\n\t\t\t   temperatures,\n\t\t\t   band_indicies,\n\t\t\t   num_band0,\n\t\t\t   num_band,\n\t\t\t   unit_conversion_factor);\n\n  free(grid_points1);\n  free(temperatures);\n  \n  Py_RETURN_NONE;\n}\n\nstatic PyObject * py_real_to_reciprocal4(PyObject *self, PyObject *args)\n{\n  PyArrayObject* fc4_py;\n  PyArrayObject* fc4_reciprocal_py;\n  PyArrayObject* q_py;\n  PyArrayObject* shortest_vectors;\n  PyArrayObject* multiplicity;\n  PyArrayObject* p2s_map;\n  PyArrayObject* s2p_map;\n\n  if (!PyArg_ParseTuple(args, \"OOOOOOO\",\n\t\t\t&fc4_reciprocal_py,\n\t\t\t&fc4_py,\n\t\t\t&q_py,\n\t\t\t&shortest_vectors,\n\t\t\t&multiplicity,\n\t\t\t&p2s_map,\n\t\t\t&s2p_map)) {\n    return NULL;\n  }\n\n  double* fc4 = (double*)fc4_py->data;\n  lapack_complex_double* fc4_reciprocal =\n    (lapack_complex_double*)fc4_reciprocal_py->data;\n  Darray* svecs = convert_to_darray(shortest_vectors);\n  Iarray* multi = convert_to_iarray(multiplicity);\n  const int* p2s = (int*)p2s_map->data;\n  const int* s2p = (int*)s2p_map->data;\n  const double* q = (double*)q_py->data;\n\n  real_to_reciprocal4(fc4_reciprocal,\n\t\t      q,\n\t\t      fc4,\n\t\t      svecs,\n\t\t      multi,\n\t\t      p2s,\n\t\t      s2p);\n\n  free(svecs);\n  free(multi);\n  \n  Py_RETURN_NONE;\n}\n\nstatic PyObject * py_reciprocal_to_normal4(PyObject *self, PyObject *args)\n{\n  PyArrayObject* fc4_normal_py;\n  PyArrayObject* fc4_reciprocal_py;\n  PyArrayObject* frequencies_py;\n  PyArrayObject* eigenvectors_py;\n  PyArrayObject* grid_points_py;\n  PyArrayObject* masses_py;\n  PyArrayObject* band_indicies_py;\n  double cutoff_frequency;\n\n  if (!PyArg_ParseTuple(args, \"OOOOOOOd\",\n\t\t\t&fc4_normal_py,\n\t\t\t&fc4_reciprocal_py,\n\t\t\t&frequencies_py,\n\t\t\t&eigenvectors_py,\n\t\t\t&grid_points_py,\n\t\t\t&masses_py,\n\t\t\t&band_indicies_py,\n\t\t\t&cutoff_frequency)) {\n    return NULL;\n  }\n\n  lapack_complex_double* fc4_normal =\n    (lapack_complex_double*)fc4_normal_py->data;\n  const lapack_complex_double* fc4_reciprocal =\n    (lapack_complex_double*)fc4_reciprocal_py->data;\n  const lapack_complex_double* eigenvectors =\n    (lapack_complex_double*)eigenvectors_py->data;\n  const double* frequencies = (double*)frequencies_py->data;\n  const int* grid_points = (int*)grid_points_py->data;\n  const double* masses = (double*)masses_py->data;\n  const int* band_indices = (int*)band_indicies_py->data;\n  const int num_band0 = (int)band_indicies_py->dimensions[0];\n  const int num_band = (int)frequencies_py->dimensions[1];\n\n  reciprocal_to_normal4(fc4_normal,\n\t\t\tfc4_reciprocal,\n\t\t\tfrequencies + grid_points[0] * num_band,\n\t\t\tfrequencies + grid_points[1] * num_band,\n\t\t\teigenvectors + grid_points[0] * num_band * num_band,\n\t\t\teigenvectors + grid_points[1] * num_band * num_band,\n\t\t\tmasses,\n\t\t\tband_indices,\n\t\t\tnum_band0,\n\t\t\tnum_band,\n\t\t\tcutoff_frequency);\n\n  Py_RETURN_NONE;\n}\n\nstatic PyObject * py_set_phonons_grid_points(PyObject *self, PyObject *args)\n{\n  PyArrayObject* frequencies;\n  PyArrayObject* eigenvectors;\n  PyArrayObject* phonon_done_py;\n  PyArrayObject* grid_points_py;\n  PyArrayObject* grid_address_py;\n  PyArrayObject* mesh_py;\n  PyArrayObject* shortest_vectors_fc2;\n  PyArrayObject* multiplicity_fc2;\n  PyArrayObject* fc2_py;\n  PyArrayObject* atomic_masses_fc2;\n  PyArrayObject* p2s_map_fc2;\n  PyArrayObject* s2p_map_fc2;\n  PyArrayObject* reciprocal_lattice;\n  PyArrayObject* born_effective_charge;\n  PyArrayObject* q_direction;\n  PyArrayObject* dielectric_constant;\n  double nac_factor, unit_conversion_factor;\n  char uplo;\n\n  if (!PyArg_ParseTuple(args, \"OOOOOOOOOOOOdOOOOdc\",\n\t\t\t&frequencies,\n\t\t\t&eigenvectors,\n\t\t\t&phonon_done_py,\n\t\t\t&grid_points_py,\n\t\t\t&grid_address_py,\n\t\t\t&mesh_py,\n\t\t\t&fc2_py,\n\t\t\t&shortest_vectors_fc2,\n\t\t\t&multiplicity_fc2,\n\t\t\t&atomic_masses_fc2,\n\t\t\t&p2s_map_fc2,\n\t\t\t&s2p_map_fc2,\n\t\t\t&unit_conversion_factor,\n\t\t\t&born_effective_charge,\n\t\t\t&dielectric_constant,\n\t\t\t&reciprocal_lattice,\n\t\t\t&q_direction,\n\t\t\t&nac_factor,\n\t\t\t&uplo)) {\n    return NULL;\n  }\n\n  double* born;\n  double* dielectric;\n  double *q_dir;\n  Darray* freqs = convert_to_darray(frequencies);\n  /* npy_cdouble and lapack_complex_double may not be compatible. */\n  /* So eigenvectors should not be used in Python side */\n  Carray* eigvecs = convert_to_carray(eigenvectors);\n  char* phonon_done = (char*)phonon_done_py->data;\n  Iarray* grid_points = convert_to_iarray(grid_points_py);\n  const int* grid_address = (int*)grid_address_py->data;\n  const int* mesh = (int*)mesh_py->data;\n  Darray* fc2 = convert_to_darray(fc2_py);\n  Darray* svecs_fc2 = convert_to_darray(shortest_vectors_fc2);\n  Iarray* multi_fc2 = convert_to_iarray(multiplicity_fc2);\n  const double* masses_fc2 = (double*)atomic_masses_fc2->data;\n  const int* p2s_fc2 = (int*)p2s_map_fc2->data;\n  const int* s2p_fc2 = (int*)s2p_map_fc2->data;\n  const double* rec_lat = (double*)reciprocal_lattice->data;\n  if ((PyObject*)born_effective_charge == Py_None) {\n    born = NULL;\n  } else {\n    born = (double*)born_effective_charge->data;\n  }\n  if ((PyObject*)dielectric_constant == Py_None) {\n    dielectric = NULL;\n  } else {\n    dielectric = (double*)dielectric_constant->data;\n  }\n  if ((PyObject*)q_direction == Py_None) {\n    q_dir = NULL;\n  } else {\n    q_dir = (double*)q_direction->data;\n  }\n\n  set_phonons_for_frequency_shift(freqs,\n\t\t\t\t  eigvecs,\n\t\t\t\t  phonon_done,\n\t\t\t\t  grid_points,\n\t\t\t\t  grid_address,\n\t\t\t\t  mesh,\n\t\t\t\t  fc2,\n\t\t\t\t  svecs_fc2,\n\t\t\t\t  multi_fc2,\n\t\t\t\t  masses_fc2,\n\t\t\t\t  p2s_fc2,\n\t\t\t\t  s2p_fc2,\n\t\t\t\t  unit_conversion_factor,\n\t\t\t\t  born,\n\t\t\t\t  dielectric,\n\t\t\t\t  rec_lat,\n\t\t\t\t  q_dir,\n\t\t\t\t  nac_factor,\n\t\t\t\t  uplo);\n\n  free(freqs);\n  free(eigvecs);\n  free(grid_points);\n  free(fc2);\n  free(svecs_fc2);\n  free(multi_fc2);\n  \n  Py_RETURN_NONE;\n}\n\nstatic PyObject * py_distribute_fc4(PyObject *self, PyObject *args)\n{\n  PyArrayObject* fc4_copy_py;\n  PyArrayObject* fc4_py;\n  int fourth_atom;\n  PyArrayObject* rotation_cart_inv;\n  PyArrayObject* atom_mapping_py;\n\n  if (!PyArg_ParseTuple(args, \"OOiOO\",\n\t\t\t&fc4_copy_py,\n\t\t\t&fc4_py,\n\t\t\t&fourth_atom,\n\t\t\t&atom_mapping_py,\n\t\t\t&rotation_cart_inv)) {\n    return NULL;\n  }\n\n  double* fc4_copy = (double*)fc4_copy_py->data;\n  const double* fc4 = (double*)fc4_py->data;\n  const double* rot_cart_inv = (double*)rotation_cart_inv->data;\n  const int* atom_mapping = (int*)atom_mapping_py->data;\n  const int num_atom = (int)atom_mapping_py->dimensions[0];\n\n  return PyInt_FromLong((long) distribute_fc4(fc4_copy,\n\t\t\t\t\t      fc4,\n\t\t\t\t\t      fourth_atom,\n\t\t\t\t\t      atom_mapping,\n\t\t\t\t\t      num_atom,\n\t\t\t\t\t      rot_cart_inv));\n}\n\nstatic PyObject * py_rotate_delta_fc3s_elem(PyObject *self, PyObject *args)\n{\n  PyArrayObject* rotated_delta_fc3s_py;\n  PyArrayObject* delta_fc3s_py;\n  PyArrayObject* atom_mappings_of_rotations_py;\n  PyArrayObject* site_symmetries_cartesian_py;\n  int atom1, atom2, atom3;\n\n  if (!PyArg_ParseTuple(args, \"OOOOiii\",\n\t\t\t&rotated_delta_fc3s_py,\n\t\t\t&delta_fc3s_py,\n\t\t\t&atom_mappings_of_rotations_py,\n\t\t\t&site_symmetries_cartesian_py,\n\t\t\t&atom1,\n\t\t\t&atom2,\n\t\t\t&atom3)) {\n    return NULL;\n  }\n\n  double* rotated_delta_fc3s = (double*)rotated_delta_fc3s_py->data;\n  const double* delta_fc3s = (double*)delta_fc3s_py->data;\n  const int* rot_map_syms = (int*)atom_mappings_of_rotations_py->data;\n  const double* site_syms_cart = (double*)site_symmetries_cartesian_py->data;\n  const int num_rot = (int)site_symmetries_cartesian_py->dimensions[0];\n  const int num_delta_fc3s = (int)delta_fc3s_py->dimensions[0];\n  const int num_atom = (int)delta_fc3s_py->dimensions[1];\n\n  return PyInt_FromLong((long) rotate_delta_fc3s_elem(rotated_delta_fc3s,\n\t\t\t\t\t\t      delta_fc3s,\n\t\t\t\t\t\t      rot_map_syms,\n\t\t\t\t\t\t      site_syms_cart,\n\t\t\t\t\t\t      num_rot,\n\t\t\t\t\t\t      num_delta_fc3s,\n\t\t\t\t\t\t      atom1,\n\t\t\t\t\t\t      atom2,\n\t\t\t\t\t\t      atom3,\n\t\t\t\t\t\t      num_atom));\n}\n\nstatic PyObject * py_set_translational_invariance_fc4(PyObject *self,\n\t\t\t\t\t\t      PyObject *args)\n{\n  PyArrayObject* fc4_py;\n  int index;\n\n  if (!PyArg_ParseTuple(args, \"Oi\",\n\t\t\t&fc4_py,\n\t\t\t&index)) {\n    return NULL;\n  }\n\n  double* fc4 = (double*)fc4_py->data;\n  const int num_atom = (int)fc4_py->dimensions[0];\n\n  set_translational_invariance_fc4_per_index(fc4, num_atom, index);\n\n  Py_RETURN_NONE;\n}\n\nstatic PyObject * py_set_permutation_symmetry_fc4(PyObject *self, PyObject *args)\n{\n  PyArrayObject* fc4_py;\n\n  if (!PyArg_ParseTuple(args, \"O\",\n\t\t\t&fc4_py)) {\n    return NULL;\n  }\n\n  double* fc4 = (double*)fc4_py->data;\n  const int num_atom = (int)fc4_py->dimensions[0];\n\n  set_permutation_symmetry_fc4(fc4, num_atom);\n\n  Py_RETURN_NONE;\n}\n\nstatic PyObject * py_get_drift_fc4(PyObject *self, PyObject *args)\n{\n  PyArrayObject* fc4_py;\n\n  if (!PyArg_ParseTuple(args, \"O\",\n\t\t\t&fc4_py)) {\n    return NULL;\n  }\n\n  double* fc4 = (double*)fc4_py->data;\n  const int num_atom = (int)fc4_py->dimensions[0];\n\n  int i;\n  double drift[4];\n  PyObject* drift_py;\n\n  get_drift_fc4(drift, fc4, num_atom);\n  drift_py = PyList_New(4);\n\n  for (i = 0; i < 4; i++) {\n    PyList_SetItem(drift_py, i, PyFloat_FromDouble(drift[i]));\n  }\n\n  return drift_py;\n}\n", "meta": {"hexsha": "1a3f7eaeaa44bc9b4d844e47b0034ccc7fc0c9e9", "size": 16172, "ext": "c", "lang": "C", "max_stars_repo_path": "c/_phono4py.c", "max_stars_repo_name": "atztogo/forcefit", "max_stars_repo_head_hexsha": "faa1aea23a31faa3d642b99c51ebb8756e53c934", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-20T23:19:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-20T23:19:49.000Z", "max_issues_repo_path": "c/_phono4py.c", "max_issues_repo_name": "atztogo/forcefit", "max_issues_repo_head_hexsha": "faa1aea23a31faa3d642b99c51ebb8756e53c934", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c/_phono4py.c", "max_forks_repo_name": "atztogo/forcefit", "max_forks_repo_head_hexsha": "faa1aea23a31faa3d642b99c51ebb8756e53c934", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-08-02T13:53:25.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-30T08:36:46.000Z", "avg_line_length": 30.0594795539, "max_line_length": 162, "alphanum_fraction": 0.7237818452, "num_tokens": 4654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41111086923216805, "lm_q2_score": 0.02887090537957738, "lm_q1q2_score": 0.011869143006117733}}
{"text": "#ifndef libceed_solids_examples_setup_libceed_h\n#define libceed_solids_examples_setup_libceed_h\n\n#include <ceed.h>\n#include <petsc.h>\n#include \"../include/structs.h\"\n\n// -----------------------------------------------------------------------------\n// libCEED Functions\n// -----------------------------------------------------------------------------\n// Destroy libCEED objects\nPetscErrorCode CeedDataDestroy(CeedInt level, CeedData data);\n\n// Utility function - essential BC dofs are encoded in closure indices as -(i+1)\nPetscInt Involute(PetscInt i);\n\n// Utility function to create local CEED restriction from DMPlex\nPetscErrorCode CreateRestrictionFromPlex(Ceed ceed, DM dm, CeedInt height,\n    DMLabel domain_label, CeedInt value, CeedElemRestriction *elem_restr);\n\n// Utility function to get Ceed Restriction for each domain\nPetscErrorCode GetRestrictionForDomain(Ceed ceed, DM dm, CeedInt height,\n                                       DMLabel domain_label, PetscInt value,\n                                       CeedInt Q, CeedInt q_data_size,\n                                       CeedElemRestriction *elem_restr_q,\n                                       CeedElemRestriction *elem_restr_x,\n                                       CeedElemRestriction *elem_restr_qd_i);\n\n// Set up libCEED for a given degree\nPetscErrorCode SetupLibceedFineLevel(DM dm, DM dm_energy, DM dm_diagnostic,\n                                     Ceed ceed, AppCtx app_ctx,\n                                     CeedQFunctionContext phys_ctx,\n                                     ProblemData problem_data,\n                                     PetscInt fine_level, PetscInt num_comp_u,\n                                     PetscInt U_g_size, PetscInt U_loc_size,\n                                     CeedVector force_ceed,\n                                     CeedVector neumann_ceed, CeedData *data);\n\n// Set up libCEED multigrid level for a given degree\nPetscErrorCode SetupLibceedLevel(DM dm, Ceed ceed, AppCtx app_ctx,\n                                 ProblemData problem_data, PetscInt level,\n                                 PetscInt num_comp_u, PetscInt U_g_size,\n                                 PetscInt U_loc_size, CeedVector fine_mult,\n                                 CeedData *data);\n\n#endif // libceed_solids_examples_setup_libceed_h\n", "meta": {"hexsha": "5b29e6f75d3a58f1122cf0a0ec637c35a1611801", "size": 2326, "ext": "h", "lang": "C", "max_stars_repo_path": "examples/solids/include/setup-libceed.h", "max_stars_repo_name": "wence-/libCEED", "max_stars_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/solids/include/setup-libceed.h", "max_issues_repo_name": "wence-/libCEED", "max_issues_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/solids/include/setup-libceed.h", "max_forks_repo_name": "wence-/libCEED", "max_forks_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.4893617021, "max_line_length": 80, "alphanum_fraction": 0.5593293207, "num_tokens": 450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3923368301671084, "lm_q2_score": 0.030214586521607925, "lm_q1q2_score": 0.011854295100697491}}
{"text": "/* multimin/fminimizer.c\n * \n * Copyright (C) 2002 Tuomo Keskitalo, Ivo Alxneit\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_multimin.h>\n\ngsl_multimin_fminimizer *\ngsl_multimin_fminimizer_alloc (const gsl_multimin_fminimizer_type * T,\n                               size_t n)\n{\n  int status;\n\n  gsl_multimin_fminimizer *s =\n    (gsl_multimin_fminimizer *) malloc (sizeof (gsl_multimin_fminimizer));\n\n  if (s == 0)\n    {\n      GSL_ERROR_VAL (\"failed to allocate space for minimizer struct\",\n                     GSL_ENOMEM, 0);\n    }\n\n  s->type = T;\n\n  s->x = gsl_vector_calloc (n);\n\n  if (s->x == 0) \n    {\n      free (s);\n      GSL_ERROR_VAL (\"failed to allocate space for x\", GSL_ENOMEM, 0);\n    }\n\n  s->state = malloc (T->size);\n\n  if (s->state == 0)\n    {\n      gsl_vector_free (s->x);\n      free (s);\n      GSL_ERROR_VAL (\"failed to allocate space for minimizer state\",\n                     GSL_ENOMEM, 0);\n    }\n\n  status = (T->alloc) (s->state, n);\n\n  if (status != GSL_SUCCESS)\n    {\n      free (s->state);\n      gsl_vector_free (s->x);\n      free (s);\n\n      GSL_ERROR_VAL (\"failed to initialize minimizer state\", GSL_ENOMEM, 0);\n    }\n\n  return s;\n}\n\nint\ngsl_multimin_fminimizer_set (gsl_multimin_fminimizer * s,\n                             gsl_multimin_function * f,\n                             const gsl_vector * x,\n                             const gsl_vector * step_size)\n{\n  if (s->x->size != f->n)\n    {\n      GSL_ERROR (\"function incompatible with solver size\", GSL_EBADLEN);\n    }\n  \n  if (x->size != f->n || step_size->size != f->n) \n    {\n      GSL_ERROR (\"vector length not compatible with function\", GSL_EBADLEN);\n    }  \n    \n  s->f = f;\n\n  gsl_vector_memcpy (s->x,x);\n\n  return (s->type->set) (s->state, s->f, s->x, &(s->size), step_size);\n}\n\nvoid\ngsl_multimin_fminimizer_free (gsl_multimin_fminimizer * s)\n{\n  (s->type->free) (s->state);\n  free (s->state);\n  gsl_vector_free (s->x);\n  free (s);\n}\n\nint\ngsl_multimin_fminimizer_iterate (gsl_multimin_fminimizer * s)\n{\n  return (s->type->iterate) (s->state, s->f, s->x, &(s->size), &(s->fval));\n}\n\nconst char * \ngsl_multimin_fminimizer_name (const gsl_multimin_fminimizer * s)\n{\n  return s->type->name;\n}\n\n\ngsl_vector * \ngsl_multimin_fminimizer_x (const gsl_multimin_fminimizer * s)\n{\n  return s->x;\n}\n\ndouble \ngsl_multimin_fminimizer_minimum (const gsl_multimin_fminimizer * s)\n{\n  return s->fval;\n}\n\ndouble\ngsl_multimin_fminimizer_size (const gsl_multimin_fminimizer * s)\n{\n  return s->size;\n}\n", "meta": {"hexsha": "507dfd4efca87f52f577b64b44c8a186985def7c", "size": 3220, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/multimin/fminimizer.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/multimin/fminimizer.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/multimin/fminimizer.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 23.8518518519, "max_line_length": 81, "alphanum_fraction": 0.6400621118, "num_tokens": 924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3522017684487511, "lm_q2_score": 0.033589503957117864, "lm_q1q2_score": 0.011830282695013235}}
{"text": "\n#pragma once\n\n#pragma warning(disable:4201) // nonstandard extension used : nameless struct/union\n#pragma warning(disable:4238) // nonstandard extension used : class rvalue used as lvalue\n#pragma warning(disable:4324) // structure was padded due to __declspec(align())\n\n#ifndef WIN32_LEAN_AND_MEAN\n    #define WIN32_LEAN_AND_MEAN\n#endif\n#ifndef NOMINMAX\n    #define NOMINMAX\n#endif\n#include <windows.h>\n\n#include <d3d12.h>\n\n#pragma comment(lib, \"d3d12.lib\")\n#pragma comment(lib, \"dxgi.lib\")\n\n#define MY_IID_PPV_ARGS IID_PPV_ARGS\n#define D3D12_GPU_VIRTUAL_ADDRESS_NULL      ((D3D12_GPU_VIRTUAL_ADDRESS)0)\n#define D3D12_GPU_VIRTUAL_ADDRESS_UNKNOWN   ((D3D12_GPU_VIRTUAL_ADDRESS)-1)\n\n\n#pragma region\n#include <d3dx12.h>\n#include <d3d12shader.h>\n#include <d3dcompiler.h>\n#pragma endregion\n\n\n#pragma region\n\n#pragma comment (lib, \"d3dcompiler.lib\")\n\n#pragma endregion\n\n#include <cstdint>\n#include <cstdio>\n#include <cstdarg>\n#include <vector>\n#include <memory>\n#include <string>\n#include <exception>\n#include <numeric>\n#include <wrl.h>\n#include <ppltasks.h>\n#include <gsl\\gsl>\n\n#include \"Utility.h\"\n#include \"VectorMath.h\"\n#include \"EngineTuning.h\"\n#include \"EngineProfiling.h\"\n\ntemplate< typename T >\nusing NotNull = gsl::not_null< T >;\n\n#define SHADER_ARGS(shader) (shader), \\\n\t\t\t\t\t\t\t\t sizeof(shader)\n\ntemplate<typename T, std::size_t N>\nstruct Array :public std::array<T, N>\n{\n    static inline std::function<T(T, T)> multiply = [](T priview, T current) {\n        return priview * current;\n    };\npublic:\n    T product()\n    {\n        return std::accumulate(begin(), end(), 1, multiply);\n    }  \n};\nusing U8 = uint8_t;\nusing U32 = uint32_t;\nusing U32x1 = U32;\nusing U32x2 = Array<U32, 2>;\nusing U32x3 = Array<U32, 3>;\nusing U32x4 = Array<U32, 4>;\nusing F32 = float;\nusing F32x2 = Array<F32, 2>;\nusing F32x3 = Array<F32, 3>;\nusing F32x4 = Array<F32, 4>;\n\n\n#pragma region voxel\n#define VOXEL_RESOLUTION 128\n#define CLIP_REGION_COUNT 6\n#define FACE_COUNT 6\n#pragma endregion\n\n\ntemplate <typename T, size_t N > Array<T, N> DivideByMultiple(Array <T, N> value, Array <T, N> alignment)\n{\n    Array <T, N> result;\n    for (size_t i = 0; i < N; i++)\n    {\n        result[i] = (T)((value[i] + alignment[i] - 1) / alignment[i]);\n    }\n    return result;\n}", "meta": {"hexsha": "6b2d2cb9936f289a9c2e9f767c79bf24b1e1501a", "size": 2244, "ext": "h", "lang": "C", "max_stars_repo_path": "Core/pch.h", "max_stars_repo_name": "sienaiwun/D3D12Practice", "max_stars_repo_head_hexsha": "3c75fc8e6367816882955888a0e9ea7021d46a62", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2020-01-21T13:11:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T03:51:11.000Z", "max_issues_repo_path": "Core/pch.h", "max_issues_repo_name": "sienaiwun/D3D12Practice", "max_issues_repo_head_hexsha": "3c75fc8e6367816882955888a0e9ea7021d46a62", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-03-30T05:20:30.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-08T03:27:46.000Z", "max_forks_repo_path": "Core/pch.h", "max_forks_repo_name": "sienaiwun/D3D12Practice", "max_forks_repo_head_hexsha": "3c75fc8e6367816882955888a0e9ea7021d46a62", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-01-21T13:11:34.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-08T05:22:40.000Z", "avg_line_length": 22.2178217822, "max_line_length": 105, "alphanum_fraction": 0.6987522282, "num_tokens": 656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.341582499438317, "lm_q2_score": 0.03461883746966928, "lm_q1q2_score": 0.011825189030538493}}
{"text": "#pragma once\n\n#include \"cell.h\"\n#include <boost/mp11/algorithm.hpp>\n#include <array>\n#include <gsl/span>\n#include <type_traits>\n#include <tuple>\n\nusing ColumnId = CellId;\n\ntemplate <typename T>\nconstexpr ColumnId GetColumnId() {\n    return CellMetaT<T>().id;\n}\n\ntemplate <typename T>\nconstexpr auto storage_required_v = std::is_empty_v<T> ? 0 : sizeof(T);\n\n// Sorts by alignment, storage size, and then name.\ntemplate <typename L, typename R>\nstruct ColumnId_less {\n    static constexpr bool value = CellMetaT<L>() > CellMetaT<R>();\n};\n\n// List is assumed to be unique and sorted by criteria listed above\nclass ColumnList : public gsl::span<const ColumnId> {\npublic:\n    using span::span;\n\n    bool ContainsAll(const ColumnList& rhs) const {\n        auto curL = begin(), endL = end();\n        auto curR = rhs.begin(), endR = rhs.end();\n        for (; curR != endR; ++curR) {\n            for (;; ++curL) {\n                if (curL == endL)\n                    return false;\n                if (*curL == *curR)\n                    break;\n            }\n        }\n        return true;\n    }\n};\n\ntemplate <typename U>\nstruct extraction;\n\ntemplate <typename... Us>\nstruct extraction<std::tuple<Us...>> {\n    static constexpr std::array<ColumnId, sizeof...(Us)> ids = { GetColumnId<Us>()... };\n    static constexpr std::array<CellMeta, sizeof...(Us)> metas = { CellMetaT<Us>()... };\n};\n\ntemplate <typename... Ts>\nstruct ColumnListT : ColumnList {\n    using unique = boost::mp11::mp_unique<std::tuple<Ts...>>;\n    using sorted = boost::mp11::mp_sort<unique, ColumnId_less>;\n    using types = sorted;\n\n    static constexpr auto ids = extraction<types>::ids;\n    static constexpr auto metas = extraction<types>::metas;\n    constexpr ColumnListT() : ColumnList(ids) { }\n};\n", "meta": {"hexsha": "8dc8c1f5a66570e004f2c49803a6d5069d2c77f7", "size": 1762, "ext": "h", "lang": "C", "max_stars_repo_path": "inc/lime/column.h", "max_stars_repo_name": "zestier/lime", "max_stars_repo_head_hexsha": "c2e500421c443ebe40f04637d0c8340fa52fc495", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "inc/lime/column.h", "max_issues_repo_name": "zestier/lime", "max_issues_repo_head_hexsha": "c2e500421c443ebe40f04637d0c8340fa52fc495", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inc/lime/column.h", "max_forks_repo_name": "zestier/lime", "max_forks_repo_head_hexsha": "c2e500421c443ebe40f04637d0c8340fa52fc495", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1076923077, "max_line_length": 88, "alphanum_fraction": 0.6242905789, "num_tokens": 438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38491214448393346, "lm_q2_score": 0.030675800824508114, "lm_q1q2_score": 0.011807488279123432}}
{"text": "#ifndef __INC_ESTIMATE_THREADED__\n#define __INC_ESTIMATE_THREADED__\n\n#include <unistd.h>\n#include <pthread.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_vector.h>\n\n\n/* common data block for most options to be passed around */\n\nstruct optstruct;\nstruct modelstruct;\n\n\n//! used to pass the args into estimate_thread_function\nstruct estimate_thetas_params{\n\t// these are direct copies of the respective data structures\n\tstruct optstruct* options;\n\tstruct modelstruct* the_model;\n\t// things needed specifically for the estimation\n\tgsl_rng* random_number;\t\n\tgsl_matrix* h_matrix;\n\tint max_tries;\n\tint success_count;\n\tdouble lhood_current;\n\tdouble my_best; // want to check on the local best values\n} estimate_thetas_params;\n\n#define USEMUTEX\n\n#include \"../modelstruct.h\"\n#include \"../optstruct.h\"\n\nvoid estimate_thetas_threaded(modelstruct* the_model, optstruct* options);\n\n// this won't work unless it has access to the nasty globals in estimate_threaded.c\nvoid* estimate_thread_function(void* args);\nint get_number_cpus(void);\n\n\nvoid setup_params(struct estimate_thetas_params *params, modelstruct* the_model, optstruct* options, int nthreads, int max_tries);\n\nvoid fprintPt(FILE *f, pthread_t pt);\n\n// see the source for defs of the number of threads etc etc\n#endif\n\n", "meta": {"hexsha": "1c5893ad9e256e980465c9d2d0699d0a24663203", "size": 1293, "ext": "h", "lang": "C", "max_stars_repo_path": "src/libEmu/estimate_threaded.h", "max_stars_repo_name": "jackdawjackdaw/emulator", "max_stars_repo_head_hexsha": "1c11f69c535acef8159ef0e780cca343785ea004", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-04-02T17:37:42.000Z", "max_stars_repo_stars_event_max_datetime": "2017-06-02T00:34:49.000Z", "max_issues_repo_path": "src/libEmu/estimate_threaded.h", "max_issues_repo_name": "MADAI/MADAIEmulator", "max_issues_repo_head_hexsha": "7d926ad04a791c7694defd88db41c13f7ee4e6aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libEmu/estimate_threaded.h", "max_forks_repo_name": "MADAI/MADAIEmulator", "max_forks_repo_head_hexsha": "7d926ad04a791c7694defd88db41c13f7ee4e6aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-30T16:43:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-30T16:43:33.000Z", "avg_line_length": 25.86, "max_line_length": 130, "alphanum_fraction": 0.7842227378, "num_tokens": 303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.02517884234065917, "lm_q1q2_score": 0.01180360527860101}}
{"text": "/*\n *  parameters.h\n *  Spike\n *\n *  Created by Ben Evans on 18/08/2008.\n *  Copyright 2008 University of Oxford. All rights reserved.\n *\n */\n\n#ifndef _PARAMETERS_H\n#define _PARAMETERS_H\n\n#include <stdbool.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n#include <gsl/gsl_version.h>\n\ntypedef int tstep; // Signed to allow spikeTimes[0] = -BIG //long long\n\ntypedef unsigned char uchar;\n\nstruct SIMULATION{\n\tbool Xgrid;\n\ttstep tally;\n\ttstep ptTS;\n\ttstep trainTS;\n\ttstep testTS;\n\ttstep totTS;\n\tfloat minTau; \n\tdouble start;\n\tdouble elapsed;\n\tdouble realSecPerSimSec;\n} SIM;\n\ntypedef struct DIMENSIONS {\n\tint nRows;\n\tint nCols;\n\tint nFilt;\n} DIM;\n\n//extern SIMULATION SIM;\n\n/*typedef enum {\n\tOff,\n\t//Uniform,\n\tGaussian\n} NOISE;*/\n\ntypedef enum {\n\tMinD,\n\tConstD,\n\tUniformD,\n\tGaussD,\n\tSOMD\n} DELAY;\n\ntypedef enum {\n\t//Zero,\n\tConstant, // Zero set using appropriate Dg modifier\n\tUniform,\n\tGaussian,\n\tSOM\n} INITIALISATION;\n\ntypedef enum {\n\tNone,\n\tMaintainLength,\n\tMaintainSum\n} NORMALISATION;\n\n/********************** Main Network Parmeters *************************/\n// Update read_parameters and defaults.m when a new parameter is added\ntypedef struct {\n\t// Simulation\n\tfloat DT;\n    bool initialised; // Internal\n\tint loops;\n\tbool pretrain;// = true;\n\tbool train;// = true;\n\tbool priorPhases;\n\tbool isolateEfE;\n\tbool trainPause;\n\tbool noise; // int\n\tfloat noiseScale;\n\tfloat SigmaE;\n\tfloat SigmaI;\n\tNORMALISATION normalise;\n\tint nRecordsPL;// = 0;\n\tint nRecords;\n\tint * vRecords;\n\t//float TotalTime;\n\tfloat MaxTime;\n\tfloat EpochTime;\n\tfloat TestTime;\n\tint EpochMS;\n\tint TestMS;\n\tint TotalMS;\n\tint RecordMS;\n\t//tstep TotalTS;\n\tint TSperMS;\n\tint spkBuffer;\n\t//int inpSpkBuff;\n\tbool printConnections;\n\tbool saveInputSpikes;\n\tbool probConnect;\n\tbool loadWeights;\n\t\n\t// Stimuli\n\tchar * imgDir;\n\tchar * imgList;\n\tbool randStimOrder;// = true;\n\tbool randTransOrder;\n\tbool randTransDirection;\n\tbool interleaveTrans;\n\tbool localRep;// = true;\n\tfloat current;// = 1.25e-9;\n\tfloat currentSpread;\n\tbool loadStimuli;\n\tbool stimGroups;\n\tint nBG; // # shared between groups\n\tint nWG; // # specific within each group\n\tint nGroups;\n\tint nStimuli;\n\tint nTransPS;\n\tbool newTestSet;\n\tint M; // Degree of training i.e. train with M of the NCK\n\tint K; // Number of stimuli presented simultaneously\n\t//int nTestGroups;\n\tint nTestStimuli;\n\tint nTestTransPS;\n\tfloat transP_Train;\n\tfloat transP_Test;\n\tint shift;\n\tint nFiringNeurons;\n\tfloat a; // Sparseness of stimuli\n\tbool useFilteredImages;\n\tbool gabor;\n\tint nScales;\n\tint * vScales;\n\tint nOrients;\n\tint * vOrients;\n\tint nPhases;\n\tint * vPhases;\n\tint sInputs;\n\tint nRows;\n\tint nCols;\n\t\n\t// Network\n\tint nLayers;// = 2;\n\tint nWLayers;\n\tbool inputInhib;\n\tint nExcit;// = 120;\n\tint * vExcit;\n\tint LvExcit;\n\tint nSynEfE;\n\tfloat * pCnxEfE;\n\tint LpEfE;\n\tint nSynElE;\n\tfloat * pCnxElE;\n\tint LpElE;\n\tint nSynIE;\n\tfloat * pCnxIE;\n\tint LpIE;\n\tint nInhib;// = 40;\n\tfloat rInhib;\n\tint * vInhib;\n\tint LvInhib;\n\tint nSynEI;\n\tfloat * pCnxEI;\n\tint LpEI;\n\tint nSynII;\n\tfloat * pCnxII;\n\tint LpII;\n\tINITIALISATION initEfE;\n\tfloat iEfE;\n\tbool axonDelay; //DELAY axonDelay;\n    DELAY delayEfE;\n    DELAY delayElE;\n    DELAY delayEI;\n\tfloat d_const;\n\tfloat d_min;\n\tfloat d_max;\n\tfloat d_mean;\n\tfloat d_sd;\n\tfloat spatialScale;\n\tfloat condSpeed;\n\tfloat maxDelay;\n\tbool SOM;\n\tbool SOMinput;\n\tfloat SOMsigE;\n\tfloat SOMsigI;\n\tfloat SOMclip;\n\t//float SOMstrE;\n\t//float SOMstrI;\n\tbool trainEfE; // Internal var modified through isolateEfE\n\tbool trainElE;\n\tINITIALISATION initElE;\n\tfloat iElE;\n\tDIM * layDim; \n\tint * vSquare;\n\t\n\t// Cell bodies\n\tfloat capE;// = 2.0e-10;\n\tfloat capI;// = 10.0e-12;\n\tfloat gLeakE;// = 10.0e-9;\n\tfloat gLeakI;// = 5.0e-9;\n\tfloat VrestE;\n\tfloat VrestI;\n\tfloat VhyperE;\n\tfloat VhyperI;\n\tfloat ThreshE;\n\tfloat ThreshI;\n\tfloat VrevE;\n\tfloat VrevI;\n\tfloat refract;// = 0.002\n\tbool adaptation;\n\tfloat alphaCa;\n\tfloat tauCa;\n\tfloat gAHP;\n\tfloat VK;\n\t\n\t// Synapses (afferent axons)\n    bool noSTDPdelay;\n\tfloat alphaC;// = 0.5;\n\tfloat tauC;// = 0.005;\n\tfloat alphaD;// = 0.5;\n\tfloat tauD;// = 0.009;\n\tfloat learnR;// = 0.1;\n\tfloat DgEfE; //modEf; // alter the strength of Excit f-f synapses\n\t//float tauEfE;// tauEE = 0.01;\n\tfloat DgElE;//Dg_ElE\n\t//float tauElE;\n\tfloat tauEE;\n\tfloat DgIE;//Dg_IE = 0.5;\n\tfloat tauIE;// = 0.001\n\tfloat DgEI;//Dg_EI = 0.5;\n\tfloat tauEI;// = 0.001;\n\tfloat DgII;//Dg_II = 0.5;\n\tfloat tauII;// = 0.001;\n\tfloat gMax;// = 48.0e-10;\n} PARAMS;\n\n//PARAMS * mp;\nextern PARAMS * mp;\nextern gsl_rng * mSeed;\nextern gsl_rng ** states;\n\n#endif\n", "meta": {"hexsha": "0e55ed07cead0141abf816bf42b6f5527a2ce5ba", "size": 4487, "ext": "h", "lang": "C", "max_stars_repo_path": "_Spike/parameters.h", "max_stars_repo_name": "wincle626/SpikingNeuralNetworkSimulatorXOS", "max_stars_repo_head_hexsha": "23f537bfa3605a5d1100b51eea7160d92d43be58", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "_Spike/parameters.h", "max_issues_repo_name": "wincle626/SpikingNeuralNetworkSimulatorXOS", "max_issues_repo_head_hexsha": "23f537bfa3605a5d1100b51eea7160d92d43be58", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_Spike/parameters.h", "max_forks_repo_name": "wincle626/SpikingNeuralNetworkSimulatorXOS", "max_forks_repo_head_hexsha": "23f537bfa3605a5d1100b51eea7160d92d43be58", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.0200803213, "max_line_length": 73, "alphanum_fraction": 0.6884332516, "num_tokens": 1423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.02517884096910781, "lm_q1q2_score": 0.011803604635630589}}
{"text": "#ifndef SIMULATION_STEPS\n\n#define SIMULATION_STEPS\n\n#include <gsl/gsl_matrix.h>\n\nextern void calculateLIFTVolMat(int N, int Np, gsl_matrix **LIFT, gsl_matrix **VolMat, gsl_matrix** MassMatrix);\n\nextern void store_mesh(char *Mesh);\nextern void initialize();\nextern void time_evolution(double FinalTime);\nextern void boundary_conditions();\n#endif\n", "meta": {"hexsha": "99ad90b3bece4af4488412a3f6bffb6bfed3fba9", "size": 345, "ext": "h", "lang": "C", "max_stars_repo_path": "1DCode/SimulationSteps.h", "max_stars_repo_name": "evalseth/DG-RAIN", "max_stars_repo_head_hexsha": "f4765de2050adedfbe57ea25437c54de1f05ca9c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-05T12:23:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-05T12:23:11.000Z", "max_issues_repo_path": "1DCode/SimulationSteps.h", "max_issues_repo_name": "evalseth/DG-RAIN", "max_issues_repo_head_hexsha": "f4765de2050adedfbe57ea25437c54de1f05ca9c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "1DCode/SimulationSteps.h", "max_forks_repo_name": "evalseth/DG-RAIN", "max_forks_repo_head_hexsha": "f4765de2050adedfbe57ea25437c54de1f05ca9c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-06-18T02:50:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-03T20:59:00.000Z", "avg_line_length": 24.6428571429, "max_line_length": 112, "alphanum_fraction": 0.7942028986, "num_tokens": 81, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.028436033868214097, "lm_q1q2_score": 0.011798077630959856}}
{"text": "#include <errno.h>\n#include <float.h>\n#include <limits.h>\n#include <math.h>\n#include <signal.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <unistd.h>\n#include <setjmp.h>\n\n#include <glib.h>\n#if GLIB_CHECK_VERSION (2, 6, 0)\n#  include <glib/gstdio.h>\n#endif\n#include <gsl/gsl_spline.h>\n#include <gsl/gsl_histogram.h>\n#include <gsl/gsl_math.h>\n\n#include \"asf.h\"\n#include \"float_image.h\"\n#include \"asf_endian.h\"\n#include \"asf_jpeg.h\"\n\n#include \"asf_view.h\"\n\n#ifndef linux\n#ifndef darwin\n#ifndef win32\nstatic double\nround (double arg)\n{\n  return floor (arg + 0.5);\n}\n#endif // #ifndef win32\n#endif // #ifndef darwin\n#endif // #ifndef linux\n\n#include \"asf_glib.h\"\n\n// at 64MB tiles, this is ~1.5GB\nstatic const int MAX_TILES = 24;\n\n// quit blathering?\nint quiet = FALSE;\n\nstatic int data_size(CachedImage *self)\n{\n    switch (self->data_type) {\n        case GREYSCALE_FLOAT:\n            return 4;\n        case RGB_BYTE:\n            return 3;\n        case GREYSCALE_BYTE:\n            return 1;\n        case RGB_FLOAT:\n            return 12;\n        default:\n            assert(FALSE);\n            return 0;\n    }\n}\n\nstatic void print_cache_size(CachedImage *self)\n{\n    int i;\n    int size=0;\n    int ds = data_size(self);\n    for (i=0; i<self->n_tiles; ++i)\n        size += ds*self->rows_per_tile*self->ns;\n\n    asfPrintStatus(\"Cache size is %.1f megabytes.\\n\",\n        (float)size/1024./1024.);\n}\n\nstatic unsigned char *get_pixel(CachedImage *self, int line, int samp)\n{\n    // check if outside the image\n    static unsigned char zero = 0;\n    if (line<0 || samp<0 || line >= self->nl || samp >= self->ns)\n        return &zero;\n\n    // size of each pixel\n    int ds = data_size(self);\n\n    int i;\n    for (i=0; i<self->n_tiles; ++i) {\n        int rs = self->rowstarts[i];\n        if (rs >= 0) {\n            if (line >= rs && line < rs+self->rows_per_tile) {\n                // found the right cache\n                assert(self->cache[i]);\n\n                // this probably won't ever happen, but here we go anyway\n                if (self->n_access > 1024*1024*1024) {\n                    asfPrintStatus(\"Resetting n_access.\\n\");\n                    for (i=0; i<self->n_tiles; ++i)\n                        self->access_counts[i] = 0;\n                    self->n_access = 1;\n                }\n\n                // mark this as the most recently accessed\n                self->access_counts[i] = self->n_access++;\n\n                // return pointer to the cached value\n                return &self->cache[i][((line-rs)*self->ns + samp)*ds];\n            }\n        }\n    }\n\n    int spot = 0;\n    if (!self->reached_max_tiles) {\n        assert(self->cache[self->n_tiles] == NULL);\n        unsigned char *data = malloc(ds*self->ns*self->rows_per_tile);\n        if (!data) {\n            // if this is the first tile -- abort, we are out of memory\n            if (self->n_tiles == 0)\n                asfPrintError(\"Failed to allocate cache of %ld bytes.\\n\"\n                              \"Out of memory.\\n\",\n                              ds*self->ns*self->rows_per_tile);\n            // couldn't allocate the next tile -- must dump existing\n            if (!quiet)\n                asfPrintStatus(\"reached max # of tiles: %d\\n\", self->n_tiles);\n            print_cache_size(self);\n            self->reached_max_tiles = TRUE;\n        } else {\n            spot = self->n_tiles;\n            self->cache[spot] = data;\n            ++self->n_tiles;\n        }\n    }\n\n    if (self->reached_max_tiles) {\n        // dump an existing cached tile\n        // not found in the cache -- find least used spot\n        int least_access_count = self->access_counts[0];\n        for (i=0; i<self->n_tiles; ++i) {\n            if (self->access_counts[i] < least_access_count) {\n                least_access_count = self->access_counts[i];\n                spot = i;\n            }\n        }\n    }\n\n    if (!self->reached_max_tiles && self->n_tiles == MAX_TILES) {\n        if (!quiet)\n            asfPrintStatus(\"Fully loaded with %d tiles.\\n\", self->n_tiles);\n        print_cache_size(self);\n        self->reached_max_tiles = TRUE;\n    }\n\n    // load info from file\n    assert(spot >= 0 && spot < self->n_tiles);\n    assert(self->cache[spot] != NULL);\n\n    // clear out the cache -- we may not fill up the tile, if\n    // we are near the end of the file, and we don't want old data\n    // to appear\n    int ns = self->ns;\n    memset(self->cache[spot], 0, ds*ns*self->rows_per_tile);\n\n    // update where this cache entry starts\n    int rs = (line / self->rows_per_tile) * self->rows_per_tile;\n    self->rowstarts[spot] = rs;\n\n    // mark this tile as the most recently accessed\n    self->access_counts[spot] = self->n_access++;\n\n    //printf(\"Updated entry #%d:\\n\"\n    //    \"     row start: %d\\n\"\n    //    \"     row end: %d\\n\"\n    //    \"     access count: %d\\n\", spot,\n    //    rs, rs+self->rows_per_tile-1, self->access_counts[spot]);\n\n    // ensure we don't read past the end of the file\n    int rows_to_get = self->rows_per_tile;\n    if (rs + self->rows_per_tile > self->nl)\n        rows_to_get = self->nl - rs;\n\n    if (!quiet) {\n        asfPrintStatus(\"Cache: loading into spot #%d: rows %d-%d\\n\",\n            spot, rs, rs+rows_to_get);\n        //print_cache_size(self);\n    }\n\n    self->client->read_fn(rs, rows_to_get, (void*)(self->cache[spot]),\n        self->client->read_client_info, self->meta, self->client->data_type);\n\n    assert((line-rs)*self->ns + samp <= self->ns*self->rows_per_tile);\n    return &self->cache[spot][((line-rs)*self->ns + samp)*ds];\n}\n\nvoid load_thumbnail_data(CachedImage *self, int thumb_size_x, int thumb_size_y,\n                         void *dest_void)\n{\n    if (self->entire_image_fits || !self->client->thumb_fn) {\n        // Either we don't have thumbnailing support from the client,\n        // or the image will fit entirely in memory.  In both cases, we\n        // can just call get_pixel() on the subset necessary to show\n        // the image, which will load the entire image into cache.\n        // (... well, unless it is so huge that our tiles fit between\n        //      the thumbnail grid ... but that's crazy talk)\n        int ds = data_size(self);\n        unsigned char *dest = (unsigned char*)dest_void;\n\n        // this will fill the cache with the image data\n        int sf = self->meta->general->line_count / thumb_size_y;\n        //assert(sf == self->meta->general->sample_count / thumb_size_x);\n\n        // supress the \"populating cache\" msgs when loading the whole thing\n        quiet=TRUE;\n\n        int i,j;\n        for (i=0; i<thumb_size_y; ++i) {\n            for (j=0; j<thumb_size_x; ++j) {\n                // make this independent of the data type\n                unsigned char *p = get_pixel(self,i*sf,j*sf);\n                memcpy(dest+(i*thumb_size_x+j)*ds, p, ds);\n            }\n            asfPercentMeter((float)i/(thumb_size_y-1));\n        }\n\n        quiet=FALSE;\n    } else {\n        self->client->thumb_fn(thumb_size_x, thumb_size_y,\n            self->meta, self->client->read_client_info, dest_void,\n            self->client->data_type);\n    }\n}\n\nCachedImage * cached_image_new_from_file(\n    const char *file, meta_parameters *meta, ClientInterface *client,\n    ImageStats *stats, ImageStatsRGB *stats_r, ImageStatsRGB *stats_g,\n    ImageStatsRGB *stats_b)\n{\n    CachedImage *self = MALLOC(sizeof(CachedImage));\n\n    asfPrintStatus(\"Opening cache: %s\\n\", file);\n\n    self->data_type = client->data_type;\n    assert(self->data_type != UNDEFINED);\n\n    self->client = client;     // take ownership of this\n    self->meta = meta;         // do NOT take ownership of this\n\n    self->stats = stats;       // do NOT take ownership of this\n\n    self->stats_r = stats_r;   // do NOT take ownership of this\n    self->stats_g = stats_g;   // do NOT take ownership of this\n    self->stats_b = stats_b;   // do NOT take ownership of this\n\n    // line line_count may have been fudges, if we are multilooking\n    self->nl = meta->general->line_count;\n    self->ns = meta->general->sample_count;\n    asfPrintStatus(\"Image is %dx%d LxS\\n\", self->nl, self->ns);\n\n    if (client->require_full_load) {\n        // Use only 1 tile -- load entire image into it\n        // (client tells us we should do it this way)\n        // will it fit?  Who knows.  Assume it will, MALLOC will fail\n        // if it actually does not.\n        self->rows_per_tile = self->nl;\n    } else {\n        // how many rows per tile?\n        // We will use ~64 Meg tiles\n        self->rows_per_tile = 64*1024*1024 / (self->ns*data_size(self));\n\n        // test line -- uncomment this for very small tiles\n        //self->rows_per_tile = 2*1024*1024 / (self->ns*data_size(self));\n    }\n\n    asfPrintStatus(\"Using %d rows per tile.\\n\", self->rows_per_tile);\n\n    int n_tiles_required = (int)ceil((double)self->nl / self->rows_per_tile);\n    self->entire_image_fits = n_tiles_required <= MAX_TILES;\n    // self->entire_image_fits = FALSE; // uncomment to test thumb_fn\n\n    // at the beginning, we have no tiles\n    self->n_tiles = 0;\n    self->reached_max_tiles = FALSE;\n\n    int i;\n    self->rowstarts = MALLOC(sizeof(int)*MAX_TILES);\n    self->cache = MALLOC(sizeof(float*)*MAX_TILES);\n    self->access_counts = MALLOC(sizeof(int)*MAX_TILES);\n    for (i=0; i<MAX_TILES; ++i) {\n        self->rowstarts[i] = -1;\n        self->cache[i] = NULL;\n        self->access_counts[i] = 0;\n    }\n\n    self->n_access = 0;\n\n    asfPrintStatus(\"Number of tiles required for the entire image: %d\\n\",\n        n_tiles_required);\n    asfPrintStatus(\"Fits in memory: %s\\n\",\n        self->entire_image_fits ? \"Yes\" : \"No\");\n\n    return self;\n}\n\nfloat cached_image_get_pixel (CachedImage *self, int line, int samp)\n{\n    if (self->data_type == GREYSCALE_FLOAT) {\n        return *((float*)get_pixel(self, line, samp));\n    }\n    else if (self->data_type == GREYSCALE_BYTE) {\n        return (float) *(get_pixel(self, line, samp));\n    }\n    else if (self->data_type == RGB_BYTE || self->data_type == RGB_FLOAT) {\n        unsigned char r, g, b;\n        cached_image_get_rgb(self, line, samp, &r, &g, &b);\n        return ((float)r + (float)g + (float)b)/3.;\n    }\n\n    // not reached\n    assert(0);\n    return 0;\n}\n\nvoid cached_image_get_rgb(CachedImage *self, int line, int samp,\n                          unsigned char *r, unsigned char *g,\n                          unsigned char *b)\n{\n    if (self->data_type == GREYSCALE_FLOAT) {\n        float f = cached_image_get_pixel(self, line, samp);\n        if (have_lut()) {\n            // do not scale in the case of a lut\n            apply_lut((int)f, r, g, b);\n        } else {\n            *r = *g = *b =\n              (unsigned char)calc_scaled_pixel_value(self->stats, f);\n        }\n    }\n    else if (self->data_type == GREYSCALE_BYTE) {\n        if (have_lut()) {\n            apply_lut((int)(*(get_pixel(self, line, samp))), r, g, b);\n        }\n        else {\n            float f = (float) *(get_pixel(self, line, samp));\n            *r = *g = *b =\n                (unsigned char)calc_scaled_pixel_value(self->stats, f);\n        }\n    }\n    else if (self->data_type == RGB_BYTE) {\n        unsigned char *uc = get_pixel(self, line, samp);\n\n        *r = (unsigned char)calc_rgb_scaled_pixel_value(self->stats_r,\n                                                        (float)uc[0]);\n        *g = (unsigned char)calc_rgb_scaled_pixel_value(self->stats_g,\n                                                        (float)uc[1]);\n        *b = (unsigned char)calc_rgb_scaled_pixel_value(self->stats_b,\n                                                        (float)uc[2]);\n    }\n    else if (self->data_type == RGB_FLOAT) {\n        float *f = (float*)get_pixel(self, line, samp);\n\n        *r = (unsigned char)calc_rgb_scaled_pixel_value(self->stats_r,f[0]);\n        *g = (unsigned char)calc_rgb_scaled_pixel_value(self->stats_g,f[1]);\n        *b = (unsigned char)calc_rgb_scaled_pixel_value(self->stats_b,f[2]);\n    }\n    else {\n        // impossible!\n        assert(0);\n        *r = *g = *b = 0;\n    }\n}\n\nvoid cached_image_get_rgb_float(CachedImage *self, int line, int samp,\n                                float *r, float *g, float *b)\n{\n    if (self->data_type == GREYSCALE_FLOAT) {\n        float f = cached_image_get_pixel(self, line, samp);\n        *r = *g = *b = calc_scaled_pixel_value(self->stats, f);\n    }\n    else if (self->data_type == GREYSCALE_BYTE) {\n        *r = *g = *b = (float)(*(get_pixel(self, line, samp)));\n    }\n    else if (self->data_type == RGB_BYTE) {\n        unsigned char *uc = get_pixel(self, line, samp);\n\n        *r = (float)(uc[0]);\n        *g = (float)(uc[1]);\n        *b = (float)(uc[2]);\n    }\n    else if (self->data_type == RGB_FLOAT) {\n        float *f = (float*)get_pixel(self, line, samp);\n\n        *r = f[0];\n        *g = f[1];\n        *b = f[2];\n    }\n    else {\n        // impossible!\n        assert(0);\n        *r = *g = *b = 0.;\n    }\n}\n\nvoid cached_image_free (CachedImage *self)\n{\n    int i;\n    for (i=0; i<self->n_tiles; ++i) {\n        if (self->cache[i])\n            free(self->cache[i]);\n    }\n\n    if (self->client->free_fn)\n      self->client->free_fn(self->client->read_client_info);\n\n    free(self->rowstarts);\n    free(self->access_counts);\n    free(self->cache);\n    free(self->client);\n\n    // we do not own the metadata -- don't free it!\n\n    free(self);\n}\n\n", "meta": {"hexsha": "d29956e480e1c791fcc599149eaf6f0f13ddf97e", "size": 13398, "ext": "c", "lang": "C", "max_stars_repo_path": "src/asf_view/cache.c", "max_stars_repo_name": "glshort/MapReady", "max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z", "max_issues_repo_path": "src/asf_view/cache.c", "max_issues_repo_name": "glshort/MapReady", "max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/asf_view/cache.c", "max_forks_repo_name": "glshort/MapReady", "max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z", "avg_line_length": 31.6737588652, "max_line_length": 79, "alphanum_fraction": 0.565158979, "num_tokens": 3604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398147944527615, "lm_q2_score": 0.02716923291416851, "lm_q1q2_score": 0.011790943895484142}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef base_type_2aa01495_7feb_4c5e_ae38_9c775c29c9f1_h\r\n#define base_type_2aa01495_7feb_4c5e_ae38_9c775c29c9f1_h\r\n\r\n#include <assert.h>\r\n#include <stdint.h>\r\n#include <gslib/config.h>\r\n\r\n__gslib_begin__\r\n\r\n#ifdef _GS_X86\r\n\r\ntypedef int8_t int8;\r\ntypedef int16_t int16;\r\ntypedef int32_t int32;\r\ntypedef int64_t int64;\r\ntypedef wchar_t wchar;\r\ntypedef float real32;\r\ntypedef double real;\r\ntypedef uint8_t byte;\r\ntypedef uint16_t word;\r\ntypedef uint32_t dword;\r\ntypedef uint64_t qword;\r\ntypedef uint32_t uint;\r\ntypedef uint16_t uint16;\r\ntypedef uint32_t uint32;\r\ntypedef uint64_t uint64;\r\ntypedef void* addrptr;\r\n\r\n#ifdef _UNICODE\r\ntypedef wchar gchar;\r\n#else\r\ntypedef char gchar;\r\n#endif\r\n\r\ntemplate<class t>\r\nstruct typeof { typedef void type; };\r\n\r\n/* virtual class ptr convert tools */\r\ntemplate<class ccp, class bcp>\r\ninline int virtual_bias()\r\n{\r\n    static typeof<ccp>::type c;\r\n    static const int bias = (int)&c - (int)static_cast<bcp>(&c);\r\n    return bias;\r\n}\r\n\r\ntemplate<class ccp, class bcp>\r\ninline ccp virtual_cast(bcp p)\r\n{\r\n    byte* ptr = (byte*)p;\r\n    ptr += virtual_bias<ccp, bcp>();\r\n    return reinterpret_cast<ccp>(ptr);\r\n}\r\n\r\n#endif  /* end of _GS_X86 */\r\n\r\ntemplate<class _ty>\r\ninline _ty gs_min(_ty a, _ty b) { return a < b ? a : b; }\r\ntemplate<class _ty>\r\ninline _ty gs_max(_ty a, _ty b) { return a > b ? a : b; }\r\ntemplate<class _ty>\r\ninline _ty gs_clamp(_ty v, _ty a, _ty b)\r\n{\r\n    assert(a <= b);\r\n    return gs_min(b, gs_max(a, v));\r\n}\r\n\r\ntemplate<class _ty>\r\ninline void gs_swap(_ty& a, _ty& b)\r\n{\r\n    auto t = a;\r\n    a = b;\r\n    b = t;\r\n}\r\n\r\n__gslib_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "f7b1bb9d91b60d77525cb28a4471af3bb447f3c4", "size": 2868, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gslib/basetype.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/gslib/basetype.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gslib/basetype.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 27.0566037736, "max_line_length": 82, "alphanum_fraction": 0.7071129707, "num_tokens": 753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20181322226037884, "lm_q2_score": 0.05834583692755957, "lm_q1q2_score": 0.0117749613558294}}
{"text": "/* Starting from version 7.8, MATLAB BLAS expects ptrdiff_t arguments for integers */\r\n#if MATLAB_VERSION >= 0x0708\r\n#include <stddef.h>\r\n#include <stdlib.h>\r\n#endif \r\n\r\n/* Starting from version 7.6, MATLAB BLAS is seperated */\r\n#if MATLAB_VERSION >= 0x0705\r\n#include <blas.h>\r\n#endif\r\n#include <lapack.h>\r\n\r\n#ifndef min\r\n#define min(a,b) ((a) <= (b) ? (a) : (b))\r\n#endif\r\n", "meta": {"hexsha": "e5aa2e0aad3da3401a2d275c208220a16138c9e0", "size": 373, "ext": "h", "lang": "C", "max_stars_repo_path": "matrix_factorisations_mex_fileexchg/factor.h", "max_stars_repo_name": "krishnakumarg1984/EKF_DAE_example", "max_stars_repo_head_hexsha": "cd51554954c1bfb77f250751d586ae4c1ab7eec0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "matrix_factorisations_mex_fileexchg/factor.h", "max_issues_repo_name": "krishnakumarg1984/EKF_DAE_example", "max_issues_repo_head_hexsha": "cd51554954c1bfb77f250751d586ae4c1ab7eec0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "matrix_factorisations_mex_fileexchg/factor.h", "max_forks_repo_name": "krishnakumarg1984/EKF_DAE_example", "max_forks_repo_head_hexsha": "cd51554954c1bfb77f250751d586ae4c1ab7eec0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3125, "max_line_length": 86, "alphanum_fraction": 0.6595174263, "num_tokens": 106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.35577489351363034, "lm_q2_score": 0.03308597767364294, "lm_q1q2_score": 0.01177116018363467}}
{"text": "/*\n** read data matrix, map of voxel addresses\n**\n** G.Lohmann, Jan 2013\n*/\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <string.h>\n\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_sort.h>\n\n#include \"viaio/Vlib.h\"\n#include \"viaio/VImage.h\"\n#include \"viaio/mu.h\"\n\n#define SQR(x) ((x) * (x))\n#define ABS(x) ((x) > 0 ? (x) : -(x))\n\n\nVImage *VImagePointer(VAttrList list,int *nt)\n{\n  VImage tmp;\n  VAttrListPosn posn;\n  int i,ntimesteps,nrows,ncols,nslices;\n \n  /* get image dimensions, read functional data */\n  nslices = 0;\n  for (VFirstAttr (list, & posn); VAttrExists (& posn); VNextAttr (& posn)) {\n    if (VGetAttrRepn (& posn) != VImageRepn) continue;\n    VGetAttrValue (& posn, NULL,VImageRepn, & tmp);\n    if (VPixelRepn(tmp) != VShortRepn) continue;\n    nslices++;\n  }\n  /* VDestroyImage(tmp); */\n  if (nslices < 1) VError(\" no slices\");\n\n  VImage *src = (VImage *) VCalloc(nslices,sizeof(VImage));\n  i = ntimesteps = nrows = ncols = 0;\n  for (VFirstAttr (list, & posn); VAttrExists (& posn); VNextAttr (& posn)) {\n    if (VGetAttrRepn (& posn) != VImageRepn) continue;\n    VGetAttrValue (& posn, NULL,VImageRepn, & src[i]);\n    if (VPixelRepn(src[i]) != VShortRepn) continue;\n    if (VImageNBands(src[i]) > ntimesteps) ntimesteps = VImageNBands(src[i]);\n    if (VImageNRows(src[i])  > nrows)  nrows = VImageNRows(src[i]);\n    if (VImageNColumns(src[i]) > ncols) ncols = VImageNColumns(src[i]);\n    i++;\n  }\n  nslices = i;\n  if (nslices < 1) return NULL;\n  if (ntimesteps < 2) return NULL;\n  *nt = ntimesteps;\n  return src;\n}\n\n\n/* read functional data */\nvoid VReadImagePointer(VAttrList list,VImage *src)\n{\n  VAttrListPosn posn;\n \n  int i = 0;\n  for (VFirstAttr (list, & posn); VAttrExists (& posn); VNextAttr (& posn)) {\n    if (VGetAttrRepn (& posn) != VImageRepn) continue;\n    VGetAttrValue (& posn, NULL,VImageRepn, & src[i]);\n    if (VPixelRepn(src[i]) != VShortRepn) continue;\n    i++;\n  }\n}\n\n/* check if mask covers data. If not, set surplus voxels to zero */\nlong VMaskCoverage(VAttrList list,VImage mask)\n{\n  VImage src=NULL;\n  VAttrListPosn posn;\n  int b,r,c;\n  long count=0;\n\n  b = 0; \n  for (VFirstAttr (list, & posn); VAttrExists (& posn); VNextAttr (& posn)) {\n    if (VGetAttrRepn (& posn) != VImageRepn) continue;\n    VGetAttrValue (& posn, NULL,VImageRepn, & src);\n    if (VPixelRepn(src) != VShortRepn) continue;\n    if (VImageNRows(src) < 3) continue;\n\n    if (VImageNRows(src) != VImageNRows(mask)) \n      VError(\" inconsistent nrows: %d,  mask: %d\",VImageNRows(src),VImageNRows(mask));\n    if (VImageNColumns(src) != VImageNColumns(mask)) \n      VError(\" inconsistent ncols: %d,  mask: %d\",VImageNColumns(src),VImageNColumns(mask));\n\n    for (r=0; r<VImageNRows(src); r++) {\n      for (c=0; c<VImageNColumns(src); c++) {\n\tif (b >= VImageNBands(mask)) VError(\"VMaskCoverage, illegal addr, band= %d\",b);\n\tfloat u = VGetPixel(mask,b,r,c);\n\tint j = (int)VPixel(src,0,r,c,VShort);\n\tif (j == 0 && u > 0.3) {\n\t  VSetPixel(mask,b,r,c,0);\n\t  count++;\n\t}\n      }\n    }\n    b++;\n  }\n  return count;\n}\n\n\n/* check if data matrix contains zero voxels */\nvoid VCheckMatrix(gsl_matrix_float *X)\n{\n  long i,j,nvox=X->size1,nt=X->size2;\n  double sum1,sum2,nx,mean,var,tiny=1.0e-4;\n\n  long count = 0;\n  nx = (double)nt;\n  for (i=0; i<nvox; i++) {\n    const float *arr1 = gsl_matrix_float_const_ptr(X,i,0);\n    sum1 = sum2 = 0;\n    for (j=0; j<nt; j++) {\n      const double u = (double)arr1[j];\n      sum1 += u;\n      sum2 += u*u;\n    }\n    mean = sum1/nx;\n    var = (sum2 - nx * mean * mean) / (nx - 1.0);\n    if (var < tiny) count++;\n  }\n  if (count > 0)\n    VWarning(\" number of empty voxels: %ld\",count);\n}\n\n\nVImage VoxelMap(VImage mask,size_t *nvoxels)\n{\n  int b,r,c;\n  int nslices = VImageNBands(mask);\n  int nrows = VImageNRows(mask);\n  int ncols = VImageNColumns(mask);\n\n  /* count number of non-zero voxels */\n  size_t nvox = 0;  \n  for (b=0; b<nslices; b++) {\n    for (r=0; r<nrows; r++) {\n      for (c=0; c<ncols; c++) {\n\tfloat u = VGetPixel(mask,b,r,c);\n\tif (ABS(u) < 0.5) continue;\n\tnvox++;\n      }\n    }\n  }\n  (*nvoxels) = nvox;\n\n  /* voxel addresses */\n  VImage map = VCreateImage(1,4,nvox,VShortRepn);\n  if (map == NULL) VError(\" error allocating addr map\");\n  VFillImage(map,VAllBands,0);\n  VImage xmap=NULL;\n  VExtractAttr (VImageAttrList(mask),\"map\",NULL,VImageRepn,&xmap,FALSE);\n  VCopyImageAttrs (mask,map);\n  VSetAttr(VImageAttrList(map),\"nvoxels\",NULL,VLongRepn,(VLong)nvox);\n  VSetAttr(VImageAttrList(map),\"nslices\",NULL,VLongRepn,(VLong)nslices);\n  VSetAttr(VImageAttrList(map),\"nrows\",NULL,VLongRepn,(VLong)nrows);\n  VSetAttr(VImageAttrList(map),\"ncols\",NULL,VLongRepn,(VLong)ncols);\n\n  VPixel(map,0,3,0,VShort) = nslices;\n  VPixel(map,0,3,1,VShort) = nrows;\n  VPixel(map,0,3,2,VShort) = ncols;\n\n  size_t i = 0;\n  for (b=0; b<nslices; b++) {\n    for (r=0; r<nrows; r++) {\n      for (c=0; c<ncols; c++) {\n\tfloat u = VGetPixel(mask,b,r,c);\n\tif (ABS(u) < 0.5) continue;\n\tVPixel(map,0,0,i,VShort) = b;\n\tVPixel(map,0,1,i,VShort) = r;\n\tVPixel(map,0,2,i,VShort) = c;\n\ti++;\n      }\n    }\n  }\n  return map;\n}\n\n/* two-pass formula, correct for round-off error */\nvoid VNormalize(float *data,int nt,VBoolean stddev)\n{\n  int j;\n  float ave,var,sd,nx,s,u,tiny=1.0e-6;\n\n  nx = (float)nt;\n  ave = 0;\n  for (j=0; j<nt; j++) ave += data[j];\n  ave /= nx;\n\n  var = u = 0;\n  for (j=0; j<nt; j++) {\n    s = data[j]-ave;\n    u   += s;\n    var += s*s;\n  }\n  var=(var-u*u/nx)/(nx-1);\n  sd = sqrt(var);\n  if (sd < tiny) {\n    for (j=0; j<nt; j++) data[j] = 0;\n  }\n  else {\n    if (stddev==FALSE) sd = 1.0;  /* only subtract mean !!!! */\n    for (j=0; j<nt; j++) {\n      u = data[j];\n      data[j] = (u-ave)/sd;\n    }\n  }\n}\n\n\n/*  copy data to input matrix X, contains fMRI time series */\nvoid VDataMatrix(VImage *src,int first,int len,VImage map,gsl_matrix_float *X)\n{\n  long i,j,k,nvox;\n  int b,r,c;\n  float *data=NULL;\n\n  data = (float *) VCalloc(len,sizeof(float));\n\n  gsl_matrix_float_set_zero (X);\n  nvox = VImageNColumns(map);\n  if (nvox != (long)X->size1) VError(\" err, %ld %ld\",(long)X->size1,nvox);\n  if (len  != (long)X->size2) VError(\" err, %ld %ld\",(long)X->size2,len);\n\n  for (i=0; i<nvox; i++) {\n    \n    b = VPixel(map,0,0,i,VShort);\n    r = VPixel(map,0,1,i,VShort);\n    c = VPixel(map,0,2,i,VShort);\n\n    if ((first+len) > VImageNBands(src[b])) VError(\" illegal len addr, %d  %d %d %d\",\n\t\t\t\t\t\t   b,first,len,VImageNBands(src[b]));\n    if (r >= VImageNRows(src[b])) VError(\" illegal row addr\");\n    if (c >= VImageNColumns(src[b])) VError(\" illegal column addr\");\n\n    k = 0;\n    for (j=first; j<first+len; j++) {\n      data[k] = (float) VGetPixel(src[b],j,r,c);\n      k++;\n    }\n    VNormalize(data,len,TRUE);\n\n    float *ptr = gsl_matrix_float_ptr(X,i,0);\n    for (j=0; j<len; j++) *ptr++ = data[j];\n  }\n  VFree(data);\n}\n\n", "meta": {"hexsha": "e41fca749e7984b1fcc820df5a3a467b1eefc777", "size": 6822, "ext": "c", "lang": "C", "max_stars_repo_path": "src/ted/vted/VoxelMap.c", "max_stars_repo_name": "zrajna/lipsia", "max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z", "max_issues_repo_path": "src/ted/vted/VoxelMap.c", "max_issues_repo_name": "zrajna/lipsia", "max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z", "max_forks_repo_path": "src/ted/vted/VoxelMap.c", "max_forks_repo_name": "zrajna/lipsia", "max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z", "avg_line_length": 26.4418604651, "max_line_length": 92, "alphanum_fraction": 0.6030489592, "num_tokens": 2436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3775406828054583, "lm_q2_score": 0.031143829972745923, "lm_q1q2_score": 0.011758062833087595}}
{"text": "#ifndef OPENMC_TALLIES_FILTER_TIME_H\n#define OPENMC_TALLIES_FILTER_TIME_H\n\n#include <gsl/gsl-lite.hpp>\n\n#include \"openmc/tallies/filter.h\"\n#include \"openmc/vector.h\"\n\nnamespace openmc {\n\n//==============================================================================\n//! Bins the incident particle time.\n//==============================================================================\n\nclass TimeFilter : public Filter {\npublic:\n  //----------------------------------------------------------------------------\n  // Constructors, destructors\n\n  ~TimeFilter() = default;\n\n  //----------------------------------------------------------------------------\n  // Methods\n\n  std::string type() const override { return \"time\"; }\n\n  void from_xml(pugi::xml_node node) override;\n\n  void get_all_bins(const Particle& p, TallyEstimator estimator,\n    FilterMatch& match) const override;\n\n  void to_statepoint(hid_t filter_group) const override;\n\n  std::string text_label(int bin) const override;\n\n  //----------------------------------------------------------------------------\n  // Accessors\n\n  const vector<double>& bins() const { return bins_; }\n  void set_bins(gsl::span<const double> bins);\n\nprotected:\n  //----------------------------------------------------------------------------\n  // Data members\n\n  vector<double> bins_;\n};\n\n} // namespace openmc\n#endif // OPENMC_TALLIES_FILTER_ENERGY_H\n", "meta": {"hexsha": "c66481c5780945b7d28c1f33343f0d8082fd2b8a", "size": 1387, "ext": "h", "lang": "C", "max_stars_repo_path": "include/openmc/tallies/filter_time.h", "max_stars_repo_name": "RyotaroOKabe/openmc", "max_stars_repo_head_hexsha": "9926294324cb80dd7ff0e4f1a9b361addfcfa8fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 123.0, "max_stars_repo_stars_event_min_datetime": "2015-01-09T18:21:00.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-21T03:05:48.000Z", "max_issues_repo_path": "include/openmc/tallies/filter_time.h", "max_issues_repo_name": "RyotaroOKabe/openmc", "max_issues_repo_head_hexsha": "9926294324cb80dd7ff0e4f1a9b361addfcfa8fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 673.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T20:37:12.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-02T15:28:47.000Z", "max_forks_repo_path": "include/openmc/tallies/filter_time.h", "max_forks_repo_name": "RyotaroOKabe/openmc", "max_forks_repo_head_hexsha": "9926294324cb80dd7ff0e4f1a9b361addfcfa8fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 102.0, "max_forks_repo_forks_event_min_datetime": "2015-01-03T18:18:46.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-26T14:34:13.000Z", "avg_line_length": 27.1960784314, "max_line_length": 80, "alphanum_fraction": 0.4780100937, "num_tokens": 248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31405053215160816, "lm_q2_score": 0.037326883729827086, "lm_q1q2_score": 0.011722527698913401}}
{"text": "/* gsl_histogram_copy.c\n * Copyright (C) 2000  Simone Piccardi\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU General Public License as\n * published by the Free Software Foundation; either version 2 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n *\n * You should have received a copy of the GNU General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n */\n/***************************************************************\n *\n * File gsl_histogram_copy.c: \n * Routine to copy an histogram. \n * Need GSL library and headers.\n *\n * Author: S. Piccardi\n * Jan. 2000\n *\n ***************************************************************/\n#include <config.h>\n#include <stdlib.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_histogram.h>\n\n/*\n * gsl_histogram_copy:\n * copy the contents of an histogram into another\n */\n\nint\ngsl_histogram_memcpy (gsl_histogram * dest, const gsl_histogram * src)\n{\n  size_t n = src->n;\n  size_t i;\n\n  if (dest->n != src->n)\n    {\n      GSL_ERROR (\"histograms have different sizes, cannot copy\",\n                 GSL_EINVAL);\n    }\n\n  for (i = 0; i <= n; i++)\n    {\n      dest->range[i] = src->range[i];\n    }\n\n  for (i = 0; i < n; i++)\n    {\n      dest->bin[i] = src->bin[i];\n    }\n\n  return GSL_SUCCESS;\n}\n\n/*\n * gsl_histogram_duplicate:\n * duplicate an histogram creating\n * an identical new one\n */\n\ngsl_histogram *\ngsl_histogram_clone (const gsl_histogram * src)\n{\n  size_t n = src->n;\n  size_t i;\n  gsl_histogram *h;\n\n  h = gsl_histogram_calloc_range (n, src->range);\n\n  if (h == 0)\n    {\n      GSL_ERROR_VAL (\"failed to allocate space for histogram struct\",\n                        GSL_ENOMEM, 0);\n    }\n\n  for (i = 0; i < n; i++)\n    {\n      h->bin[i] = src->bin[i];\n    }\n\n  return h;\n}\n", "meta": {"hexsha": "848dcf10a31d33b80300c4bc5cc6c0734fbc988c", "size": 2148, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/histogram/copy.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/histogram/copy.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/histogram/copy.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 23.347826087, "max_line_length": 70, "alphanum_fraction": 0.6070763501, "num_tokens": 547, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3486451488696663, "lm_q2_score": 0.03358950456175575, "lm_q1q2_score": 0.011710817818391669}}
{"text": "/* vector/gsl_vector_float.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_VECTOR_FLOAT_H__\n#define __GSL_VECTOR_FLOAT_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_block_float.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size;\n  size_t stride;\n  float *data;\n  gsl_block_float *block;\n  int owner;\n} \ngsl_vector_float;\n\ntypedef struct\n{\n  gsl_vector_float vector;\n} _gsl_vector_float_view;\n\ntypedef _gsl_vector_float_view gsl_vector_float_view;\n\ntypedef struct\n{\n  gsl_vector_float vector;\n} _gsl_vector_float_const_view;\n\ntypedef const _gsl_vector_float_const_view gsl_vector_float_const_view;\n\n\n/* Allocation */\n\ngsl_vector_float *gsl_vector_float_alloc (const size_t n);\ngsl_vector_float *gsl_vector_float_calloc (const size_t n);\n\ngsl_vector_float *gsl_vector_float_alloc_from_block (gsl_block_float * b,\n                                                     const size_t offset, \n                                                     const size_t n, \n                                                     const size_t stride);\n\ngsl_vector_float *gsl_vector_float_alloc_from_vector (gsl_vector_float * v,\n                                                      const size_t offset, \n                                                      const size_t n, \n                                                      const size_t stride);\n\nvoid gsl_vector_float_free (gsl_vector_float * v);\n\n/* Views */\n\n_gsl_vector_float_view \ngsl_vector_float_view_array (float *v, size_t n);\n\n_gsl_vector_float_view \ngsl_vector_float_view_array_with_stride (float *base,\n                                         size_t stride,\n                                         size_t n);\n\n_gsl_vector_float_const_view \ngsl_vector_float_const_view_array (const float *v, size_t n);\n\n_gsl_vector_float_const_view \ngsl_vector_float_const_view_array_with_stride (const float *base,\n                                               size_t stride,\n                                               size_t n);\n\n_gsl_vector_float_view \ngsl_vector_float_subvector (gsl_vector_float *v, \n                            size_t i, \n                            size_t n);\n\n_gsl_vector_float_view \ngsl_vector_float_subvector_with_stride (gsl_vector_float *v, \n                                        size_t i,\n                                        size_t stride,\n                                        size_t n);\n\n_gsl_vector_float_const_view \ngsl_vector_float_const_subvector (const gsl_vector_float *v, \n                                  size_t i, \n                                  size_t n);\n\n_gsl_vector_float_const_view \ngsl_vector_float_const_subvector_with_stride (const gsl_vector_float *v, \n                                              size_t i, \n                                              size_t stride,\n                                              size_t n);\n\n/* Operations */\n\nfloat gsl_vector_float_get (const gsl_vector_float * v, const size_t i);\nvoid gsl_vector_float_set (gsl_vector_float * v, const size_t i, float x);\n\nfloat *gsl_vector_float_ptr (gsl_vector_float * v, const size_t i);\nconst float *gsl_vector_float_const_ptr (const gsl_vector_float * v, const size_t i);\n\nvoid gsl_vector_float_set_zero (gsl_vector_float * v);\nvoid gsl_vector_float_set_all (gsl_vector_float * v, float x);\nint gsl_vector_float_set_basis (gsl_vector_float * v, size_t i);\n\nint gsl_vector_float_fread (FILE * stream, gsl_vector_float * v);\nint gsl_vector_float_fwrite (FILE * stream, const gsl_vector_float * v);\nint gsl_vector_float_fscanf (FILE * stream, gsl_vector_float * v);\nint gsl_vector_float_fprintf (FILE * stream, const gsl_vector_float * v,\n                              const char *format);\n\nint gsl_vector_float_memcpy (gsl_vector_float * dest, const gsl_vector_float * src);\n\nint gsl_vector_float_reverse (gsl_vector_float * v);\n\nint gsl_vector_float_swap (gsl_vector_float * v, gsl_vector_float * w);\nint gsl_vector_float_swap_elements (gsl_vector_float * v, const size_t i, const size_t j);\n\nfloat gsl_vector_float_max (const gsl_vector_float * v);\nfloat gsl_vector_float_min (const gsl_vector_float * v);\nvoid gsl_vector_float_minmax (const gsl_vector_float * v, float * min_out, float * max_out);\n\nsize_t gsl_vector_float_max_index (const gsl_vector_float * v);\nsize_t gsl_vector_float_min_index (const gsl_vector_float * v);\nvoid gsl_vector_float_minmax_index (const gsl_vector_float * v, size_t * imin, size_t * imax);\n\nint gsl_vector_float_add (gsl_vector_float * a, const gsl_vector_float * b);\nint gsl_vector_float_sub (gsl_vector_float * a, const gsl_vector_float * b);\nint gsl_vector_float_mul (gsl_vector_float * a, const gsl_vector_float * b);\nint gsl_vector_float_div (gsl_vector_float * a, const gsl_vector_float * b);\nint gsl_vector_float_scale (gsl_vector_float * a, const double x);\nint gsl_vector_float_add_constant (gsl_vector_float * a, const double x);\n\nint gsl_vector_float_isnull (const gsl_vector_float * v);\nint gsl_vector_float_ispos (const gsl_vector_float * v);\nint gsl_vector_float_isneg (const gsl_vector_float * v);\n\n#ifdef HAVE_INLINE\n\nextern inline\nfloat\ngsl_vector_float_get (const gsl_vector_float * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_VAL (\"index out of range\", GSL_EINVAL, 0);\n    }\n#endif\n  return v->data[i * v->stride];\n}\n\nextern inline\nvoid\ngsl_vector_float_set (gsl_vector_float * v, const size_t i, float x)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_VOID (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  v->data[i * v->stride] = x;\n}\n\nextern inline\nfloat *\ngsl_vector_float_ptr (gsl_vector_float * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return (float *) (v->data + i * v->stride);\n}\n\nextern inline\nconst float *\ngsl_vector_float_const_ptr (const gsl_vector_float * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return (const float *) (v->data + i * v->stride);\n}\n\n\n#endif /* HAVE_INLINE */\n\n__END_DECLS\n\n#endif /* __GSL_VECTOR_FLOAT_H__ */\n\n\n", "meta": {"hexsha": "4fb280ba9c4ddaa02a68f2fbb0ceaf6d04563e61", "size": 7184, "ext": "h", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/vector/gsl_vector_float.h", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/vector/gsl_vector_float.h", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/vector/gsl_vector_float.h", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 31.3711790393, "max_line_length": 94, "alphanum_fraction": 0.6744153675, "num_tokens": 1679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3380771241500058, "lm_q2_score": 0.034618837345168685, "lm_q1q2_score": 0.011703836971071451}}
{"text": "#pragma once\n\n#include \"Rendering/Utility/peBxDF.h\"\n#include \"Type/peColor.h\"\n#include <gsl.h>\n\nnamespace pe {\n\nenum class ToneMapping { Saturate, Linear, Log };\n\n//! \\brief Performs tone mapping from the given input image to a displayable\n//! 8-bit RGBA output image \\param result Result image \\param input Input image\n//! \\param imageWidth Width of the image\n//! \\param imageHeight Height of the image\n//! \\param strategy The tone-mapping strategy to use\nvoid ToneMap(gsl::span<RGBA_8Bit> result, const gsl::span<Spectrum_t> input,\n             const uint32_t imageWidth, const uint32_t imageHeight,\n             const ToneMapping strategy);\n\n} // namespace pe\n", "meta": {"hexsha": "4e9a0ccfa290ceac83622d5da25d6a6b74efa9a7", "size": 663, "ext": "h", "lang": "C", "max_stars_repo_path": "PrismaticPathTracer/Headers/Util/ToneMapping.h", "max_stars_repo_name": "Mortano/Prismatic", "max_stars_repo_head_hexsha": "e2e931e1ee8bfd3899b26f8c91e593f0d7213d64", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PrismaticPathTracer/Headers/Util/ToneMapping.h", "max_issues_repo_name": "Mortano/Prismatic", "max_issues_repo_head_hexsha": "e2e931e1ee8bfd3899b26f8c91e593f0d7213d64", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PrismaticPathTracer/Headers/Util/ToneMapping.h", "max_forks_repo_name": "Mortano/Prismatic", "max_forks_repo_head_hexsha": "e2e931e1ee8bfd3899b26f8c91e593f0d7213d64", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5714285714, "max_line_length": 79, "alphanum_fraction": 0.7285067873, "num_tokens": 161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.32766831395172374, "lm_q2_score": 0.03567854754528941, "lm_q1q2_score": 0.011690729518411392}}
{"text": "/* sys/gsl_sys.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_SYS_H__\n#define __GSL_SYS_H__\n\n#include <gsl/gsl_types.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\nGSL_EXPORT double gsl_log1p (const double x);\nGSL_EXPORT double gsl_expm1 (const double x);\nGSL_EXPORT double gsl_hypot (const double x, const double y);\nGSL_EXPORT double gsl_acosh (const double x);\nGSL_EXPORT double gsl_asinh (const double x);\nGSL_EXPORT double gsl_atanh (const double x);\n\nGSL_EXPORT int gsl_isnan (const double x);\nGSL_EXPORT int gsl_isinf (const double x);\nGSL_EXPORT int gsl_finite (const double x);\n\nGSL_EXPORT double gsl_nan (void);\nGSL_EXPORT double gsl_posinf (void);\nGSL_EXPORT double gsl_neginf (void);\nGSL_EXPORT double gsl_fdiv (const double x, const double y);\n\nGSL_EXPORT double gsl_coerce_double (const double x);\nGSL_EXPORT float gsl_coerce_float (const float x);\nGSL_EXPORT long double gsl_coerce_long_double (const long double x);\n\nGSL_EXPORT double gsl_ldexp(const double x, const int e);\nGSL_EXPORT double gsl_frexp(const double x, int * e);\n\nGSL_EXPORT int gsl_fcmp (const double x1, const double x2, const double epsilon);\n\n__END_DECLS\n\n#endif /* __GSL_SYS_H__ */\n", "meta": {"hexsha": "8f831580f53a84e77b877e7396960b3da4721136", "size": 2117, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/gsl/include/gsl/gsl_sys.h", "max_stars_repo_name": "dynaryu/vaws", "max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/gsl/include/gsl/gsl_sys.h", "max_issues_repo_name": "dynaryu/vaws", "max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/gsl/include/gsl/gsl_sys.h", "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5692307692, "max_line_length": 81, "alphanum_fraction": 0.7671232877, "num_tokens": 553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3276683008207139, "lm_q2_score": 0.03567854844248507, "lm_q1q2_score": 0.011690729343898611}}
{"text": "#include \"ccv.h\"\n#include <ctype.h>\n#include <getopt.h>\n#ifdef HAVE_GSL\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n#endif\n\n#ifdef HAVE_GSL\nstatic ccv_dense_matrix_t* _ccv_aflw_slice_with_rect(gsl_rng* rng, ccv_dense_matrix_t* image, ccv_rect_t rect, ccv_size_t size, ccv_margin_t margin, float deform_angle, float deform_scale, float deform_shift)\n{\n\tccv_dense_matrix_t* resize = 0;\n\tccv_slice(image, (ccv_matrix_t**)&resize, 0, rect.y, rect.x, rect.height, rect.width);\n\tassert(rect.width == rect.height);\n\tfloat scale = gsl_rng_uniform(rng);\n\t// to make the scale evenly distributed, for example, when deforming of 1/2 ~ 2, we want it to distribute around 1, rather than any average of 1/2 ~ 2\n\tscale = (1 + deform_scale * scale) / (1 + deform_scale * (1 - scale));\n\tint new_width = (int)(rect.width * scale + 0.5);\n\tint new_height = (int)(rect.height * scale + 0.5);\n\tccv_point_t offset = ccv_point((int)((deform_shift * 2 * gsl_rng_uniform(rng) - deform_shift) * rect.width + 0.5 + (rect.width - new_width) * 0.5), (int)((deform_shift * 2 * gsl_rng_uniform(rng) - deform_shift) * rect.height + 0.5 + (rect.height - new_height) * 0.5));\n\trect.x += offset.x;\n\trect.y += offset.y;\n\tccv_dense_matrix_t* b = 0;\n\tif (size.width > rect.width)\n\t\tccv_resample(resize, &b, 0, size.height + margin.top + margin.bottom, size.width + margin.left + margin.right, CCV_INTER_CUBIC);\n\telse\n\t\tccv_resample(resize, &b, 0, size.height + margin.top + margin.bottom, size.width + margin.left + margin.right, CCV_INTER_AREA);\n\tccv_matrix_free(resize);\n\treturn b;\n}\n#endif\n\nint main(int argc, char** argv)\n{\n#ifdef HAVE_GSL\n\tassert(argc == 4);\n\tgsl_rng* rng = gsl_rng_alloc(gsl_rng_default);\n\tFILE* r = fopen(argv[1], \"r\");\n\tchar* base_dir = argv[2];\n\tint dirlen = (base_dir != 0) ? strlen(base_dir) + 1 : 0;\n\tchar* file = (char*)malloc(1024);\n\tint i = 0;\n\tccv_rect_t rect;\n\tccv_decimal_pose_t pose;\n\t// rect.x, rect.y, rect.width, rect.height roll pitch yaw\n\twhile (fscanf(r, \"%s %d %d %d %d %f %f %f\", file, &rect.x, &rect.y, &rect.width, &rect.height, &pose.roll, &pose.pitch, &pose.yaw) != EOF)\n\t{\n\t\tif (pose.pitch < CCV_PI * 22.5 / 180 && pose.pitch > -CCV_PI * 22.5 / 180 &&\n\t\t\tpose.roll < CCV_PI * 22.5 / 180 && pose.roll > -CCV_PI * 22.5 / 180 &&\n\t\t\tpose.yaw < CCV_PI * 20 / 180 && pose.yaw > -CCV_PI * 20 / 180 &&\n\t\t\trect.width >= 15 && rect.height >= 15)\n\t\t{\n\t\t\t// resize to a more proper sizes\n\t\t\tchar* filename = (char*)malloc(1024);\n\t\t\tstrncpy(filename, base_dir, 1024);\n\t\t\tfilename[dirlen - 1] = '/';\n\t\t\tstrncpy(filename + dirlen, file, 1024 - dirlen);\n\t\t\tccv_dense_matrix_t* image = 0;\n\t\t\tccv_read(filename, &image, CCV_IO_ANY_FILE | CCV_IO_GRAY);\n\t\t\tchar* savefile = (char*)malloc(1024);\n\t\t\tccv_dense_matrix_t* b = _ccv_aflw_slice_with_rect(rng, image, rect, ccv_size(48, 48), ccv_margin(0, 0, 0, 0), 10, 0.1, 0.05);\n\t\t\tsnprintf(savefile, 1024, \"%s/aflw-%07d-bw.png\", argv[3], i);\n\t\t\tccv_write(b, savefile, 0, CCV_IO_PNG_FILE, 0);\n\t\t\tccv_matrix_free(b);\n\t\t\tccv_matrix_free(image);\n\t\t\timage = 0;\n\t\t\tccv_read(filename, &image, CCV_IO_ANY_FILE | CCV_IO_RGB_COLOR);\n\t\t\tb = _ccv_aflw_slice_with_rect(rng, image, rect, ccv_size(48, 48), ccv_margin(0, 0, 0, 0), 10, 0.1, 0.05);\n\t\t\tsnprintf(savefile, 1024, \"%s/aflw-%07d-rgb.png\", argv[3], i);\n\t\t\tccv_write(b, savefile, 0, CCV_IO_PNG_FILE, 0);\n\t\t\tccv_matrix_free(b);\n\t\t\tccv_matrix_free(image);\n\t\t\ti++;\n\t\t\tfree(savefile);\n\t\t\tfree(filename);\n\t\t}\n\t}\n\tfclose(r);\n\tfree(file);\n\tgsl_rng_free(rng);\n#else\n\tassert(0 && \"aflw requires GSL library support\");\n#endif\n\treturn 0;\n}\n", "meta": {"hexsha": "e729cef61fa6d8bad2dbac7d6b6201041421cccf", "size": 3518, "ext": "c", "lang": "C", "max_stars_repo_path": "bin/aflw.c", "max_stars_repo_name": "sunkaianna/ccv", "max_stars_repo_head_hexsha": "3a8cc247c1f4c36cb910c94fad0abeafe3e029b0", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 3296.0, "max_stars_repo_stars_event_min_datetime": "2015-01-01T02:05:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T00:29:55.000Z", "max_issues_repo_path": "bin/aflw.c", "max_issues_repo_name": "sunkaianna/ccv", "max_issues_repo_head_hexsha": "3a8cc247c1f4c36cb910c94fad0abeafe3e029b0", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 111.0, "max_issues_repo_issues_event_min_datetime": "2015-01-12T15:55:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-05T18:13:11.000Z", "max_forks_repo_path": "bin/aflw.c", "max_forks_repo_name": "sunkaianna/ccv", "max_forks_repo_head_hexsha": "3a8cc247c1f4c36cb910c94fad0abeafe3e029b0", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 940.0, "max_forks_repo_forks_event_min_datetime": "2015-01-02T02:21:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T23:27:43.000Z", "avg_line_length": 40.9069767442, "max_line_length": 269, "alphanum_fraction": 0.6731097214, "num_tokens": 1208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.02333076829916378, "lm_q1q2_score": 0.01166538414958189}}
{"text": "/* monte/gsl_monte_miser.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Michael Booth\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Author: MJB */\n\n#ifndef __GSL_MONTE_MISER_H__\n#define __GSL_MONTE_MISER_H__\n\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_monte.h>\n#include <gsl/gsl_monte_plain.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct {\n  size_t min_calls;\n  size_t min_calls_per_bisection;\n  double dither;\n  double estimate_frac;\n  double alpha;\n  size_t dim;\n  int estimate_style;\n  int depth;\n  int verbose;\n  double * x;\n  double * xmid;\n  double * sigma_l;\n  double * sigma_r;\n  double * fmax_l;\n  double * fmax_r;\n  double * fmin_l;\n  double * fmin_r;\n  double * fsum_l;\n  double * fsum_r;\n  double * fsum2_l;\n  double * fsum2_r;\n  size_t * hits_l;\n  size_t * hits_r;\n} gsl_monte_miser_state; \n\nint gsl_monte_miser_integrate(gsl_monte_function * f, \n                              const double xl[], const double xh[], \n                              size_t dim, size_t calls, \n                              gsl_rng *r, \n                              gsl_monte_miser_state* state,\n                              double *result, double *abserr);\n\ngsl_monte_miser_state* gsl_monte_miser_alloc(size_t dim);\n\nint gsl_monte_miser_init(gsl_monte_miser_state* state);\n\nvoid gsl_monte_miser_free(gsl_monte_miser_state* state);\n\n\n__END_DECLS\n\n#endif /* __GSL_MONTE_MISER_H__ */\n", "meta": {"hexsha": "d08cb8c8a883e746a9dfdee8ca759cfa5b56b145", "size": 2254, "ext": "h", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/monte/gsl_monte_miser.h", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/monte/gsl_monte_miser.h", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/monte/gsl_monte_miser.h", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 26.8333333333, "max_line_length": 81, "alphanum_fraction": 0.6925465839, "num_tokens": 608, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3629692055196168, "lm_q2_score": 0.03210070463358554, "lm_q1q2_score": 0.011651567257472425}}
{"text": "/* specfunc/gsl_sf_result.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Author:  G. Jungman */\n\n#ifndef __GSL_SF_RESULT_H__\n#define __GSL_SF_RESULT_H__\n\n#include <gsl/gsl_types.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\nstruct gsl_sf_result_struct {\n  double val;\n  double err;\n};\ntypedef struct gsl_sf_result_struct gsl_sf_result;\n\n#define GSL_SF_RESULT_SET(r,v,e) do { (r)->val=(v); (r)->err=(e); } while(0)\n\n\nstruct gsl_sf_result_e10_struct {\n  double val;\n  double err;\n  int    e10;\n};\ntypedef struct gsl_sf_result_e10_struct gsl_sf_result_e10;\n\n\nGSL_EXPORT int gsl_sf_result_smash_e(const gsl_sf_result_e10 * re, gsl_sf_result * r);\n\n\n__END_DECLS\n\n#endif /* __GSL_SF_RESULT_H__ */\n", "meta": {"hexsha": "305b75ad5bfdf170011362245e0781e7f6e43c8d", "size": 1616, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/gsl/include/gsl/gsl_sf_result.h", "max_stars_repo_name": "dynaryu/vaws", "max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/gsl/include/gsl/gsl_sf_result.h", "max_issues_repo_name": "dynaryu/vaws", "max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/gsl/include/gsl/gsl_sf_result.h", "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.064516129, "max_line_length": 86, "alphanum_fraction": 0.7438118812, "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33111973962899144, "lm_q2_score": 0.035144847664027534, "lm_q1q2_score": 0.011637152807813364}}
{"text": "#include <sys/stat.h>\n#include <sys/time.h>\n#include <sys/types.h>\n\n#include <err.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n#include <unistd.h>\n\n#include <gsl/gsl_histogram.h>\n#include <gsl/gsl_errno.h>\n\n#include \"my_signal.h\"\n#include \"my_socket.h\"\n#include \"set_timer.h\"\n#include \"get_num.h\"\n\nint debug = 0;\ngsl_histogram *histo;\nunsigned long histo_overflow = 0;\nunsigned long total_bytes    = 0;\nunsigned long read_count     = 0;\nstruct timeval start, stop;\nint bufsize = 2*1024*1024;\n\nint usage()\n{\n    //char msg[] = \"Usage: ./read-sock-histo [-b bufsize] [-w bin_width] [-B n_bin] [-t TIMEOUT] ip_address:port x_min x_max n_bin\\n\"\n    char msg[] = \"Usage: ./read-sock-histo [-b bufsize] [-t TIMEOUT] ip_address:port x_min x_max n_bin\\n\"\n                 \"example of ip_address:port\\n\"\n                 \"remote_host:1234\\n\"\n                 \"192.168.10.16:24\\n\"\n                 \"default port: 1234\\n\"\n                 \" Options:\\n\"\n                 \"    -b bufsize: suffix k for kilo (1024), m for mega(1024*1024) (default 2MB)\\n\"\n                 \"    -t TIMEOUT: seconds.  (default: 10 seconds)\\n\";\n    fprintf(stderr, \"%s\\n\", msg);\n\n    return 0;\n}\n\nvoid sig_int(int signo)\n{\n    struct timeval elapse;\n    gettimeofday(&stop, NULL);\n    timersub(&stop, &start, &elapse);\n    fprintf(stderr, \"bufsize: %.3f kB\\n\", bufsize/1024.0);\n    fprintf(stderr, \"total bytes: %ld bytes\\n\", total_bytes);\n    fprintf(stderr, \"read count : %ld\\n\", read_count);\n    fprintf(stderr, \"running %ld.%06ld sec\\n\", elapse.tv_sec, elapse.tv_usec);\n    double elapsed_time        = elapse.tv_sec + 0.000001*elapse.tv_usec;\n    double transfer_rate_MB_s  = (double)total_bytes / elapsed_time / 1024.0 / 1024.0;\n    double transfer_rate_Gbps  = (double)total_bytes * 8 / elapsed_time / 1000000000.0;\n    double read_bytes_per_read = (double)total_bytes / (double)read_count / 1024.0;\n    fprintf(stderr, \"transfer_rate: %.3f MB/s %.3f Gbps\\n\", transfer_rate_MB_s, transfer_rate_Gbps);\n    fprintf(stderr, \"read_bytes_per_read: %.3f kB/read\\n\", read_bytes_per_read);\n\n    gsl_histogram_fprintf(stdout, histo, \"%g\", \"%g\");\n    gsl_histogram_free(histo);\n    //if (histo_overflow > 0) {\n    printf(\"# overflow: %ld\\n\", histo_overflow);\n    //}\n\n    exit(0);\n}\n\nint main(int argc, char *argv[])\n{\n    int c;\n    int period = 10; /* default run time (10 seconds) */\n\n    while ( (c = getopt(argc, argv, \"b:dht:w:B:\")) != -1) {\n        switch (c) {\n            case 'b':\n                bufsize = get_num(optarg);\n                break;\n            case 'h':\n                usage();\n                exit(0);\n                break; /* NOTREACHED */\n            case 'd':\n                debug = 1;\n                break;\n            case 't':\n                period = strtol(optarg, NULL, 0);\n                break;\n            default:\n                break;\n        }\n    }\n\n    argc -= optind;\n    argv += optind;\n\n    if (argc != 4) {\n        usage();\n        exit(1);\n    }\n\n    int port = 1234;\n    char *remote_host_info = argv[0];\n    char *tmp = strdup(remote_host_info);\n    char *remote_host = strsep(&tmp, \":\");\n    if (tmp != NULL) {\n        port = strtol(tmp, NULL, 0);\n    }\n\n    double x_min = (double) get_num(argv[1]);\n    double x_max = (double) get_num(argv[2]);\n    int n_bin    = strtol(argv[3], NULL, 0);\n\n    my_signal(SIGINT,  sig_int);\n    my_signal(SIGTERM, sig_int);\n    my_signal(SIGALRM, sig_int);\n\n    histo = gsl_histogram_alloc(n_bin);\n    gsl_histogram_set_ranges_uniform(histo, x_min, x_max);\n\n    int sockfd = tcp_socket();\n    if (sockfd < 0) {\n        errx(1, \"tcp_socket\");\n    }\n\n    if (connect_tcp(sockfd, remote_host, port) < 0) {\n        errx(1, \"connect_tcp\");\n    }\n\n    set_timer(period, 0, period, 0);\n    gettimeofday(&start, NULL);\n\n    char *buf = malloc(bufsize);\n    if (buf == NULL) {\n        err(1, \"malloc for buf\");\n    }\n\n    for ( ; ; ) {\n        int n, m;\n        n = read(sockfd, buf, bufsize);\n        total_bytes += n;\n        read_count ++;\n        m = gsl_histogram_increment(histo, n);\n        if (m == GSL_EDOM) {\n            histo_overflow += 1;\n        }\n    }\n}\n", "meta": {"hexsha": "3d57dba7293324fa99c1d1fddd7e8c295c9e8550", "size": 4188, "ext": "c", "lang": "C", "max_stars_repo_path": "read-sock-histo.c", "max_stars_repo_name": "h-sendai/read-sock-histo", "max_stars_repo_head_hexsha": "bc212c555ae044eb5b96d80c9f204fee63be3e8e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "read-sock-histo.c", "max_issues_repo_name": "h-sendai/read-sock-histo", "max_issues_repo_head_hexsha": "bc212c555ae044eb5b96d80c9f204fee63be3e8e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "read-sock-histo.c", "max_forks_repo_name": "h-sendai/read-sock-histo", "max_forks_repo_head_hexsha": "bc212c555ae044eb5b96d80c9f204fee63be3e8e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7350993377, "max_line_length": 133, "alphanum_fraction": 0.5668576886, "num_tokens": 1180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34510525748676846, "lm_q2_score": 0.033589505891959144, "lm_q1q2_score": 0.011591915079697887}}
{"text": "#ifndef WASM_INSTRUCTION_H\n#define WASM_INSTRUCTION_H\n#include <cstddef>\n#include <cstring>\n#include <cstdint>\n#include <type_traits>\n#include <array>\n#include <bitset>\n#include <optional>\n#include <variant>\n#include <algorithm>\n#include <iosfwd>\n#include <ostream>\n#include <iomanip>\n#include <gsl/span>\n#include <gsl/gsl>\n#include \"wasm_base.h\"\n\n\nnamespace wasm {\nnamespace opc {\n\nenum class OpCode: wasm_ubyte_t\n{\n\t// BLOCK INSTRUCTIONS\n\tBLOCK\t\t\t= 0x02u,\n\tLOOP\t\t\t= 0x03u,\n\tBR\t\t\t= 0x0cu,\n\tBR_IF\t\t\t= 0x0du,\n\tBR_TABLE\t\t= 0x0eu,\n\tIF\t\t\t= 0x04u,\n\tELSE\t\t\t= 0x05u,\n\tEND\t\t\t= 0x0bu,\n\tRETURN\t\t\t= 0x0fu,\n\tUNREACHABLE\t\t= 0x00u,\n\n\t// BASIC INSTRUCTIONS\n\tNOP \t\t\t= 0x01u,\n\tDROP \t\t\t= 0x1au,\n\tI32_CONST \t\t= 0x41u,\n\tI64_CONST \t\t= 0x42u,\n\tF32_CONST \t\t= 0x43u,\n\tF64_CONST \t\t= 0x44u,\n\tGET_LOCAL \t\t= 0x20u,\n\tSET_LOCAL \t\t= 0x21u,\n\tTEE_LOCAL \t\t= 0x22u,\n\tGET_GLOBAL \t\t= 0x23u,\n\tSET_GLOBAL \t\t= 0x24u,\n\tSELECT \t\t\t= 0x1bu,\n\tCALL \t\t\t= 0x10u,\n\tCALL_INDIRECT \t\t= 0x11u,\n\t\n\t// INTEGER ARITHMETIC INSTRUCTIONS\n\t// int32\n\tI32_ADD\t\t\t= 0x6au,\n\tI32_SUB\t\t\t= 0x6bu,\n\tI32_MUL\t\t\t= 0x6cu,\n\tI32_DIV_S\t\t= 0x6du,\n\tI32_DIV_U\t\t= 0x6eu,\n\tI32_REM_S\t\t= 0x6fu,\n\tI32_REM_U\t\t= 0x70u,\n\tI32_AND\t\t\t= 0x71u,\n\tI32_OR\t\t\t= 0x72u,\n\tI32_XOR\t\t\t= 0x73u,\n\tI32_SHL\t\t\t= 0x74u,\n\tI32_SHR_S\t\t= 0x75u,\n\tI32_SHR_U\t\t= 0x76u,\n\tI32_ROTL\t\t= 0x77u,\n\tI32_ROTR\t\t= 0x78u,\n\tI32_CLZ\t\t\t= 0x67u,\n\tI32_CTZ\t\t\t= 0x68u,\n\tI32_POPCNT\t\t= 0x69u,\n\tI32_EQZ\t\t\t= 0x45u,\n\t// int64\n\tI64_ADD\t\t\t= 0x7cu,\n\tI64_SUB\t\t\t= 0x7du,\n\tI64_MUL\t\t\t= 0x7eu,\n\tI64_DIV_S\t\t= 0x7fu,\n\tI64_DIV_U\t\t= 0x80u,\n\tI64_REM_S\t\t= 0x81u,\n\tI64_REM_U\t\t= 0x82u,\n\tI64_AND\t\t\t= 0x83u,\n\tI64_OR\t\t\t= 0x84u,\n\tI64_XOR\t\t\t= 0x85u,\n\tI64_SHL\t\t\t= 0x86u,\n\tI64_SHR_S\t\t= 0x87u,\n\tI64_SHR_U\t\t= 0x88u,\n\tI64_ROTL\t\t= 0x89u,\n\tI64_ROTR\t\t= 0x8au,\n\tI64_CLZ\t\t\t= 0x79u,\n\tI64_CTZ\t\t\t= 0x7au,\n\tI64_POPCNT\t\t= 0x7bu,\n\tI64_EQZ\t\t\t= 0x50u,\n\n\t// FLOATING POINT ARITHMETIC INSTRUCTIONS\n\t// float32\n\tF32_ADD\t\t\t= 0x92u,\n\tF32_SUB\t    \t\t= 0x93u,\n\tF32_MUL\t    \t\t= 0x94u,\n\tF32_DIV\t    \t\t= 0x95u,\n\tF32_SQRT    \t\t= 0x91u,\n\tF32_MIN\t    \t\t= 0x96u,\n\tF32_MAX\t    \t\t= 0x97u,\n\tF32_CEIL    \t\t= 0x8du,\n\tF32_FLOOR   \t\t= 0x8eu,\n\tF32_TRUNC   \t\t= 0x8fu,\n\tF32_NEAREST \t\t= 0x90u,\n\tF32_ABS\t    \t\t= 0x8bu,\n\tF32_NEG\t    \t\t= 0x8cu,\n\tF32_COPYSIGN\t\t= 0x98u,\n\t// float64\n\tF64_ADD\t    \t\t= 0xa0u,\n\tF64_SUB\t    \t\t= 0xa1u,\n\tF64_MUL\t    \t\t= 0xa2u,\n\tF64_DIV\t    \t\t= 0xa3u,\n\tF64_SQRT    \t\t= 0x9fu,\n\tF64_MIN\t    \t\t= 0xa4u,\n\tF64_MAX\t    \t\t= 0xa5u,\n\tF64_CEIL    \t\t= 0x9bu,\n\tF64_FLOOR   \t\t= 0x9cu,\n\tF64_TRUNC   \t\t= 0x9du,\n\tF64_NEAREST \t\t= 0x9eu,\n\tF64_ABS\t    \t\t= 0x99u,\n\tF64_NEG\t    \t\t= 0x9au,\n\tF64_COPYSIGN\t\t= 0xa6u,\n\n\t// INTEGER COMPARISON INSTRUCTIONS\n\t// int32\n\tI32_EQ  \t\t= 0x46u,\n\tI32_NE  \t\t= 0x47u,\n\tI32_LT_S\t\t= 0x48u,\n\tI32_LT_U\t\t= 0x49u,\n\tI32_GT_S\t\t= 0x4au,\n\tI32_GT_U\t\t= 0x4bu,\n\tI32_LE_S\t\t= 0x4cu,\n\tI32_LE_U\t\t= 0x4du,\n\tI32_GE_S\t\t= 0x4eu,\n\tI32_GE_U\t\t= 0x4fu,\n\t// int64\n\tI64_EQ  \t\t= 0x51u,\n\tI64_NE  \t\t= 0x52u,\n\tI64_LT_S\t\t= 0x53u,\n\tI64_LT_U\t\t= 0x54u,\n\tI64_GT_S\t\t= 0x55u,\n\tI64_GT_U\t\t= 0x56u,\n\tI64_LE_S\t\t= 0x57u,\n\tI64_LE_U\t\t= 0x58u,\n\tI64_GE_S\t\t= 0x59u,\n\tI64_GE_U\t\t= 0x5au,\n\t\n\t// FLOATING POINT COMPARISON INSTRUCTIONS\n\t// float32\n\tF32_EQ  \t\t= 0x5bu,\n\tF32_NE  \t\t= 0x5cu,\n\tF32_LT\t\t\t= 0x5du,\n\tF32_GT\t\t\t= 0x5eu,\n\tF32_LE\t\t\t= 0x5fu,\n\tF32_GE\t\t\t= 0x60u,\n\t// float64\n\tF64_EQ  \t\t= 0x61u,\n\tF64_NE  \t\t= 0x62u,\n\tF64_LT\t\t\t= 0x63u,\n\tF64_GT\t\t\t= 0x64u,\n\tF64_LE\t\t\t= 0x65u,\n\tF64_GE\t\t\t= 0x66u,\n\n\n\t// CONVERSION INSTRUCTIONS\n\t// to int32\n\tI32_WRAP\t\t= 0xa7u,\n\tI32_TRUNC_F32_S\t\t= 0xa8u,\n\tI32_TRUNC_F32_U\t\t= 0xa9u,\n\tI32_TRUNC_F64_S\t\t= 0xaau,\n\tI32_TRUNC_F64_U\t\t= 0xabu,\n\tI32_REINTERPRET_F32\t= 0xbcu,\n\t\n\t// to int64\n\tI64_EXTEND_S \t\t= 0xacu,\n\tI64_EXTEND_U\t\t= 0xadu,\n\tI64_TRUNC_F32_S\t\t= 0xaeu,\n\tI64_TRUNC_F32_U\t\t= 0xafu,\n\tI64_TRUNC_F64_S\t\t= 0xb0u,\n\tI64_TRUNC_F64_U\t\t= 0xb1u,\n\tI64_REINTERPRET_F64\t= 0xbdu,\n\n\t// to float32\n\tF32_DEMOTE              = 0xb6u,\n\tF32_CONVERT_I32_S       = 0xb2u,\n\tF32_CONVERT_I32_U       = 0xb3u,\n\tF32_CONVERT_I64_S       = 0xb4u,\n\tF32_CONVERT_I64_U       = 0xb5u,\n\tF32_REINTERPRET_I32     = 0xbeu,\n\n\t// to float64\n\tF64_PROMOTE             = 0xbbu,\n\tF64_CONVERT_I32_S       = 0xb7u,\n\tF64_CONVERT_I32_U       = 0xb8u,\n\tF64_CONVERT_I64_S       = 0xb9u,\n\tF64_CONVERT_I64_U       = 0xbau,\n\tF64_REINTERPRET_I64     = 0xbfu,\n\n\n\t// LOAD AND STORE INSTRUCTIONSu\n\n\tI32_LOAD\t\t= 0x28u,\n\tI64_LOAD\t\t= 0x29u,\n\tF32_LOAD\t\t= 0x2au,\n\tF64_LOAD\t\t= 0x2bu,\n\tI32_LOAD8_S\t\t= 0x2cu,\n\tI32_LOAD8_U\t\t= 0x2du,\n\tI32_LOAD16_S\t\t= 0x2eu,\n\tI32_LOAD16_U\t\t= 0x2fu,\n\tI64_LOAD8_S\t\t= 0x30u,\n\tI64_LOAD8_U\t\t= 0x31u,\n\tI64_LOAD16_S\t\t= 0x32u,\n\tI64_LOAD16_U\t\t= 0x33u,\n\tI64_LOAD32_S\t\t= 0x34u,\n\tI64_LOAD32_U\t\t= 0x35u,\n\tI32_STORE\t\t= 0x36u,\n\tI64_STORE\t\t= 0x37u,\n\tF32_STORE\t\t= 0x38u,\n\tF64_STORE\t\t= 0x39u,\n\tI32_STORE8\t\t= 0x3au,\n\tI32_STORE16\t\t= 0x3bu,\n\tI64_STORE8\t\t= 0x3cu,\n\tI64_STORE16\t\t= 0x3du,\n\tI64_STORE32\t\t= 0x3eu,\n\n\t// MEMORY INSTRUCTIONS\n\tGROW_MEMORY \t\t= 0x40u,\n\tCURRENT_MEMORY \t\t= 0x3fu,\n};\n\n\ntemplate <template <OpCode> class TemplateVis, class Vis>\ndecltype(auto) visit_opcode_template(Vis&& visitor) {\n\tswitch(opcode())\n\t{\n\t/// CONTROL FLOW OPS\n\tcase OpCode::UNREACHABLE:       return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::UNREACHABLE>{});\n\tcase OpCode::NOP:               return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::NOP>{});\n\tcase OpCode::BLOCK:             return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::BLOCK>{});\n\tcase OpCode::LOOP:              return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::LOOP>{});\n\tcase OpCode::IF:                return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::IF>{});\n\tcase OpCode::ELSE:              return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::ELSE>{});\n\tcase OpCode::END:               return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::END>{});\n\tcase OpCode::BR:                return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::BR>{});\n\tcase OpCode::BR_IF:             return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::BR_IF>{});\n\tcase OpCode::BR_TABLE:          return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::BR_TABLE>{});\n\tcase OpCode::RETURN:            return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::RETURN>{});\n\tcase OpCode::CALL:              return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::CALL>{});\n\tcase OpCode::CALL_INDIRECT:     return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::CALL_INDIRECT>{});\n\t/// PARAMETRIC OPS\n\tcase OpCode::DROP:              return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::DROP>{});\n\tcase OpCode::SELECT:            return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::SELECT>{});\n\tcase OpCode::GET_LOCAL:         return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::GET_LOCAL>{});\n\tcase OpCode::SET_LOCAL:         return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::SET_LOCAL>{});\n\tcase OpCode::TEE_LOCAL:         return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::TEE_LOCAL>{});\n\tcase OpCode::GET_GLOBAL:        return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::GET_GLOBAL>{});\n\tcase OpCode::SET_GLOBAL:        return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::SET_GLOBAL>{});\n\t/// MEMORY OPS\n\t// load\n\tcase OpCode::I32_LOAD:          return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_LOAD>{});\n\tcase OpCode::I64_LOAD:          return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_LOAD>{});\n\tcase OpCode::F32_LOAD:          return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_LOAD>{});\n\tcase OpCode::F64_LOAD:          return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_LOAD>{});\n\t// i32 extending loads\n\tcase OpCode::I32_LOAD8_S:       return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_LOAD8_S>{});\n\tcase OpCode::I32_LOAD8_U:       return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_LOAD8_U>{});\n\tcase OpCode::I32_LOAD16_S:      return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_LOAD16_S>{});\n\tcase OpCode::I32_LOAD16_U:      return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_LOAD16_U>{});\n\t// i64 extending loads\n\tcase OpCode::I64_LOAD8_S:       return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_LOAD8_S>{});\n\tcase OpCode::I64_LOAD8_U:       return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_LOAD8_U>{});\n\tcase OpCode::I64_LOAD16_S:      return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_LOAD16_S>{});\n\tcase OpCode::I64_LOAD16_U:      return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_LOAD16_U>{});\n\tcase OpCode::I64_LOAD32_S:      return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_LOAD32_S>{});\n\tcase OpCode::I64_LOAD32_U:      return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_LOAD32_U>{});\n\t// store\n\tcase OpCode::I32_STORE:         return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_STORE>{});\n\tcase OpCode::I64_STORE:         return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_STORE>{});\n\tcase OpCode::F32_STORE:         return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_STORE>{});\n\tcase OpCode::F64_STORE:         return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_STORE>{});\n\t// i32 wrapping stores \n\tcase OpCode::I32_STORE8:        return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_STORE8>{});\n\tcase OpCode::I32_STORE16:       return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_STORE16>{});\n\t// i64 wrapping stores \n\tcase OpCode::I64_STORE8:        return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_STORE8>{});\n\tcase OpCode::I64_STORE16:       return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_STORE16>{});\n\tcase OpCode::I64_STORE32:       return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_STORE32>{});\n\t// misc\n\tcase OpCode::CURRENT_MEMORY:    return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::CURRENT_MEMORY>{});\n\tcase OpCode::GROW_MEMORY:       return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::GROW_MEMORY>{});\n\t/// CONST OPERATIONS\n\tcase OpCode::I32_CONST:         return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_CONST>{});\n\tcase OpCode::I64_CONST:         return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_CONST>{});\n\tcase OpCode::F32_CONST:         return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_CONST>{});\n\tcase OpCode::F64_CONST:         return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_CONST>{});\n\t/// COMPARISON OPERATIONS\n\t// i32 comparisons\n\tcase OpCode::I32_EQZ:           return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_EQZ>{});\n\tcase OpCode::I32_EQ:            return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_EQ>{});\n\tcase OpCode::I32_NE:            return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_NE>{});\n\tcase OpCode::I32_LT_S:          return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_LT_S>{});\n\tcase OpCode::I32_LT_U:          return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_LT_U>{});\n\tcase OpCode::I32_GT_S:          return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_GT_S>{});\n\tcase OpCode::I32_GT_U:          return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_GT_U>{});\n\tcase OpCode::I32_LE_S:          return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_LE_S>{});\n\tcase OpCode::I32_LE_U:          return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_LE_U>{});\n\tcase OpCode::I32_GE_S:          return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_GE_S>{});\n\tcase OpCode::I32_GE_U:          return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_GE_U>{});\n\t// i64 comparisons\n\tcase OpCode::I64_EQZ:           return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_EQZ>{});\n\tcase OpCode::I64_EQ:            return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_EQ>{});\n\tcase OpCode::I64_NE:            return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_NE>{});\n\tcase OpCode::I64_LT_S:          return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_LT_S>{});\n\tcase OpCode::I64_LT_U:          return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_LT_U>{});\n\tcase OpCode::I64_GT_S:          return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_GT_S>{});\n\tcase OpCode::I64_GT_U:          return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_GT_U>{});\n\tcase OpCode::I64_LE_S:          return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_LE_S>{});\n\tcase OpCode::I64_LE_U:          return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_LE_U>{});\n\tcase OpCode::I64_GE_S:          return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_GE_S>{});\n\tcase OpCode::I64_GE_U:          return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_GE_U>{});\n\t// f32 comparisons\n\tcase OpCode::F32_EQ:            return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_EQ>{});\n\tcase OpCode::F32_NE:            return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_NE>{});\n\tcase OpCode::F32_LT:            return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_LT>{});\n\tcase OpCode::F32_GT:            return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_GT>{});\n\tcase OpCode::F32_LE:            return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_LE>{});\n\tcase OpCode::F32_GE:            return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_GE>{});\n\t// f64 comparisons\n\tcase OpCode::F64_EQ:            return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_EQ>{});\n\tcase OpCode::F64_NE:            return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_NE>{});\n\tcase OpCode::F64_LT:            return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_LT>{});\n\tcase OpCode::F64_GT:            return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_GT>{});\n\tcase OpCode::F64_LE:            return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_LE>{});\n\tcase OpCode::F64_GE:            return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_GE>{});\n\t/// NUMERIC OPERATIONS\n\t// i32 operations\n\tcase OpCode::I32_CLZ:           return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_CLZ>{});\n\tcase OpCode::I32_CTZ:           return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_CTZ>{});\n\tcase OpCode::I32_POPCNT:        return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_POPCNT>{});\n\tcase OpCode::I32_ADD:           return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_ADD>{});\n\tcase OpCode::I32_SUB:           return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_SUB>{});\n\tcase OpCode::I32_MUL:           return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_MUL>{});\n\tcase OpCode::I32_DIV_S:         return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_DIV_S>{});\n\tcase OpCode::I32_DIV_U:         return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_DIV_U>{});\n\tcase OpCode::I32_REM_S:         return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_REM_S>{});\n\tcase OpCode::I32_REM_U:         return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_REM_U>{});\n\tcase OpCode::I32_AND:           return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_AND>{});\n\tcase OpCode::I32_OR:            return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_OR>{});\n\tcase OpCode::I32_XOR:           return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_XOR>{});\n\tcase OpCode::I32_SHL:           return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_SHL>{});\n\tcase OpCode::I32_SHR_S:         return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_SHR_S>{});\n\tcase OpCode::I32_SHR_U:         return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_SHR_U>{});\n\tcase OpCode::I32_ROTL:          return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_ROTL>{});\n\tcase OpCode::I32_ROTR:          return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_ROTR>{});\n\t// i64 operations\n\tcase OpCode::I64_CLZ:           return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_CLZ>{});\n\tcase OpCode::I64_CTZ:           return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_CTZ>{});\n\tcase OpCode::I64_POPCNT:        return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_POPCNT>{});\n\tcase OpCode::I64_ADD:           return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_ADD>{});\n\tcase OpCode::I64_SUB:           return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_SUB>{});\n\tcase OpCode::I64_MUL:           return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_MUL>{});\n\tcase OpCode::I64_DIV_S:         return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_DIV_S>{});\n\tcase OpCode::I64_DIV_U:         return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_DIV_U>{});\n\tcase OpCode::I64_REM_S:         return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_REM_S>{});\n\tcase OpCode::I64_REM_U:         return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_REM_U>{});\n\tcase OpCode::I64_AND:           return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_AND>{});\n\tcase OpCode::I64_OR:            return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_OR>{});\n\tcase OpCode::I64_XOR:           return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_XOR>{});\n\tcase OpCode::I64_SHL:           return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_SHL>{});\n\tcase OpCode::I64_SHR_S:         return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_SHR_S>{});\n\tcase OpCode::I64_SHR_U:         return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_SHR_U>{});\n\tcase OpCode::I64_ROTL:          return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_ROTL>{});\n\tcase OpCode::I64_ROTR:          return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_ROTR>{});\n\t// f32 operations\n\tcase OpCode::F32_ABS:           return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_ABS>{});\n\tcase OpCode::F32_NEG:           return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_NEG>{});\n\tcase OpCode::F32_CEIL:          return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_CEIL>{});\n\tcase OpCode::F32_FLOOR:         return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_FLOOR>{});\n\tcase OpCode::F32_TRUNC:         return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_TRUNC>{});\n\tcase OpCode::F32_NEAREST:       return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_NEAREST>{});\n\tcase OpCode::F32_SQRT:          return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_SQRT>{});\n\tcase OpCode::F32_ADD:           return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_ADD>{});\n\tcase OpCode::F32_SUB:           return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_SUB>{});\n\tcase OpCode::F32_MUL:           return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_MUL>{});\n\tcase OpCode::F32_DIV:           return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_DIV>{});\n\tcase OpCode::F32_MIN:           return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_MIN>{});\n\tcase OpCode::F32_MAX:           return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_MAX>{});\n\tcase OpCode::F32_COPYSIGN:      return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_COPYSIGN>{});\n\t// f64 operations\n\tcase OpCode::F64_ABS:           return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_ABS>{});\n\tcase OpCode::F64_NEG:           return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_NEG>{});\n\tcase OpCode::F64_CEIL:          return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_CEIL>{});\n\tcase OpCode::F64_FLOOR:         return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_FLOOR>{});\n\tcase OpCode::F64_TRUNC:         return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_TRUNC>{});\n\tcase OpCode::F64_NEAREST:       return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_NEAREST>{});\n\tcase OpCode::F64_SQRT:          return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_SQRT>{});\n\tcase OpCode::F64_ADD:           return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_ADD>{});\n\tcase OpCode::F64_SUB:           return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_SUB>{});\n\tcase OpCode::F64_MUL:           return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_MUL>{});\n\tcase OpCode::F64_DIV:           return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_DIV>{});\n\tcase OpCode::F64_MIN:           return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_MIN>{});\n\tcase OpCode::F64_MAX:           return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_MAX>{});\n\tcase OpCode::F64_COPYSIGN:      return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_COPYSIGN>{});\n\t/// CONVERSION OPERATIONS\n\tcase OpCode::I32_WRAP_I64:      return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_WRAP_I64>{});\n\t// float-to-int32 tuncating conversion\n\tcase OpCode::I32_TRUNC_S_F32:   return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_TRUNC_S_F32>{});\n\tcase OpCode::I32_TRUNC_U_F32:   return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_TRUNC_U_F32>{});\n\tcase OpCode::I32_TRUNC_S_F64:   return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_TRUNC_S_F64>{});\n\tcase OpCode::I32_TRUNC_U_F64:   return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_TRUNC_U_F64>{});\n\t// int32-to-int64 extending conversion\n\tcase OpCode::I64_EXTEND_S_I32:  return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_EXTEND_S_I32>{});\n\tcase OpCode::I64_EXTEND_U_I32:  return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_EXTEND_U_I32>{});\n\t// float-to-int64 truncating conversion\n\tcase OpCode::I64_TRUNC_S_F32:   return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_TRUNC_S_F32>{});\n\tcase OpCode::I64_TRUNC_U_F32:   return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_TRUNC_U_F32>{});\n\tcase OpCode::I64_TRUNC_S_F64:   return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_TRUNC_S_F64>{});\n\tcase OpCode::I64_TRUNC_U_F64:   return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_TRUNC_U_F64>{});\n\t// int-to-float32 conversion\n\tcase OpCode::F32_CONVERT_S_I32: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_CONVERT_S_I32>{});\n\tcase OpCode::F32_CONVERT_U_I32: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_CONVERT_U_I32>{});\n\tcase OpCode::F32_CONVERT_S_I64: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_CONVERT_S_I64>{});\n\tcase OpCode::F32_CONVERT_U_I64: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_CONVERT_U_I64>{});\n\t// float64-to-float32 demoting conversion\n\tcase OpCode::F32_DEMOTE_F64:    return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_DEMOTE_F64>{});\n\t// int-to-float64 conversion\n\tcase OpCode::F64_CONVERT_S_I32: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_CONVERT_S_I32>{});\n\tcase OpCode::F64_CONVERT_U_I32: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_CONVERT_U_I32>{});\n\tcase OpCode::F64_CONVERT_S_I64: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_CONVERT_S_I64>{});\n\tcase OpCode::F64_CONVERT_U_I64: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_CONVERT_U_I64>{});\n\t// float32-to-float64 promoting conversion\n\tcase OpCode::F64_PROMOTE_F32:   return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_PROMOTE_F32>{});\n\tdefault:                        assert(false);\n\t}\n}\n\ntemplate <LanguageType LT>\nusing language_type_constant_t = std::integral_constant<LanguageType, LT>;\n\ntemplate <class Vis>\ndecltype(auto) visit_opcode(Vis&& visitor) {\n\treturn visit_opcode_template<language_type_constant_t>(visitor);\n}\n\ninline constexpr const std::array<OpCode, 168u> all_opcodes {\n\tOpCode::UNREACHABLE, \n\tOpCode::NOP, \n\tOpCode::BLOCK, \n\tOpCode::LOOP, \n\tOpCode::IF, \n\tOpCode::ELSE, \n\tOpCode::END, \n\tOpCode::BR, \n\tOpCode::BR_IF, \n\tOpCode::BR_TABLE, \n\tOpCode::RETURN, \n\tOpCode::CALL, \n\tOpCode::CALL_INDIRECT, \n\tOpCode::DROP, \n\tOpCode::SELECT, \n\tOpCode::GET_LOCAL, \n\tOpCode::SET_LOCAL, \n\tOpCode::TEE_LOCAL, \n\tOpCode::GET_GLOBAL, \n\tOpCode::SET_GLOBAL, \n\tOpCode::I32_LOAD, \n\tOpCode::I64_LOAD, \n\tOpCode::F32_LOAD, \n\tOpCode::F64_LOAD, \n\tOpCode::I32_LOAD8_S, \n\tOpCode::I32_LOAD8_U, \n\tOpCode::I32_LOAD16_S, \n\tOpCode::I32_LOAD16_U, \n\tOpCode::I64_LOAD8_S, \n\tOpCode::I64_LOAD8_U, \n\tOpCode::I64_LOAD16_S, \n\tOpCode::I64_LOAD16_U, \n\tOpCode::I64_LOAD32_S, \n\tOpCode::I64_LOAD32_U, \n\tOpCode::I32_STORE, \n\tOpCode::I64_STORE, \n\tOpCode::F32_STORE, \n\tOpCode::F64_STORE, \n\tOpCode::I32_STORE8, \n\tOpCode::I32_STORE16, \n\tOpCode::I64_STORE8, \n\tOpCode::I64_STORE16, \n\tOpCode::I64_STORE32, \n\tOpCode::CURRENT_MEMORY, \n\tOpCode::GROW_MEMORY, \n\tOpCode::I32_CONST, \n\tOpCode::I64_CONST, \n\tOpCode::F32_CONST, \n\tOpCode::F64_CONST, \n\tOpCode::I32_EQZ, \n\tOpCode::I32_EQ, \n\tOpCode::I32_NE, \n\tOpCode::I32_LT_S, \n\tOpCode::I32_LT_U, \n\tOpCode::I32_GT_S, \n\tOpCode::I32_GT_U, \n\tOpCode::I32_LE_S, \n\tOpCode::I32_LE_U, \n\tOpCode::I32_GE_S, \n\tOpCode::I32_GE_U, \n\tOpCode::I64_EQZ, \n\tOpCode::I64_EQ, \n\tOpCode::I64_NE, \n\tOpCode::I64_LT_S, \n\tOpCode::I64_LT_U, \n\tOpCode::I64_GT_S, \n\tOpCode::I64_GT_U, \n\tOpCode::I64_LE_S, \n\tOpCode::I64_LE_U, \n\tOpCode::I64_GE_S, \n\tOpCode::I64_GE_U, \n\tOpCode::F32_EQ, \n\tOpCode::F32_NE, \n\tOpCode::F32_LT, \n\tOpCode::F32_GT, \n\tOpCode::F32_LE, \n\tOpCode::F32_GE, \n\tOpCode::F64_EQ, \n\tOpCode::F64_NE, \n\tOpCode::F64_LT, \n\tOpCode::F64_GT, \n\tOpCode::F64_LE, \n\tOpCode::F64_GE, \n\tOpCode::I32_CLZ, \n\tOpCode::I32_CTZ, \n\tOpCode::I32_POPCNT, \n\tOpCode::I32_ADD, \n\tOpCode::I32_SUB, \n\tOpCode::I32_MUL, \n\tOpCode::I32_DIV_S, \n\tOpCode::I32_DIV_U, \n\tOpCode::I32_REM_S, \n\tOpCode::I32_REM_U, \n\tOpCode::I32_AND, \n\tOpCode::I32_OR, \n\tOpCode::I32_XOR, \n\tOpCode::I32_SHL, \n\tOpCode::I32_SHR_S, \n\tOpCode::I32_SHR_U, \n\tOpCode::I32_ROTL, \n\tOpCode::I32_ROTR, \n\tOpCode::I64_CLZ, \n\tOpCode::I64_CTZ, \n\tOpCode::I64_POPCNT, \n\tOpCode::I64_ADD, \n\tOpCode::I64_SUB, \n\tOpCode::I64_MUL, \n\tOpCode::I64_DIV_S, \n\tOpCode::I64_DIV_U, \n\tOpCode::I64_REM_S, \n\tOpCode::I64_REM_U, \n\tOpCode::I64_AND, \n\tOpCode::I64_OR, \n\tOpCode::I64_XOR, \n\tOpCode::I64_SHL, \n\tOpCode::I64_SHR_S, \n\tOpCode::I64_SHR_U, \n\tOpCode::I64_ROTL, \n\tOpCode::I64_ROTR, \n\tOpCode::F32_ABS, \n\tOpCode::F32_NEG, \n\tOpCode::F32_CEIL, \n\tOpCode::F32_FLOOR, \n\tOpCode::F32_TRUNC, \n\tOpCode::F32_NEAREST, \n\tOpCode::F32_SQRT, \n\tOpCode::F32_ADD, \n\tOpCode::F32_SUB, \n\tOpCode::F32_MUL, \n\tOpCode::F32_DIV, \n\tOpCode::F32_MIN, \n\tOpCode::F32_MAX, \n\tOpCode::F32_COPYSIGN, \n\tOpCode::F64_ABS, \n\tOpCode::F64_NEG, \n\tOpCode::F64_CEIL, \n\tOpCode::F64_FLOOR, \n\tOpCode::F64_TRUNC, \n\tOpCode::F64_NEAREST, \n\tOpCode::F64_SQRT, \n\tOpCode::F64_ADD, \n\tOpCode::F64_SUB, \n\tOpCode::F64_MUL, \n\tOpCode::F64_DIV, \n\tOpCode::F64_MIN, \n\tOpCode::F64_MAX, \n\tOpCode::F64_COPYSIGN, \n\tOpCode::I32_WRAP_I64, \n\tOpCode::I32_TRUNC_S_F32, \n\tOpCode::I32_TRUNC_U_F32, \n\tOpCode::I32_TRUNC_S_F64, \n\tOpCode::I32_TRUNC_U_F64, \n\tOpCode::I64_EXTEND_S_I32, \n\tOpCode::I64_EXTEND_U_I32, \n\tOpCode::I64_TRUNC_S_F32, \n\tOpCode::I64_TRUNC_U_F32, \n\tOpCode::I64_TRUNC_S_F64, \n\tOpCode::I64_TRUNC_U_F64, \n\tOpCode::F32_CONVERT_S_I32, \n\tOpCode::F32_CONVERT_U_I32, \n\tOpCode::F32_CONVERT_S_I64, \n\tOpCode::F32_CONVERT_U_I64, \n\tOpCode::F32_DEMOTE_F64, \n\tOpCode::F64_CONVERT_S_I32, \n\tOpCode::F64_CONVERT_U_I32, \n\tOpCode::F64_CONVERT_S_I64, \n\tOpCode::F64_CONVERT_U_I64, \n\tOpCode::F64_PROMOTE_F32\n};\n\n\nnamespace detail {\n\nconst std::bitset<256>& opcode_mask()\n{\n\tstatic const std::bitset<256> bs {[]() -> std::bitset<256> {\n\t\tusing int_type = std::underlying_type_t<OpCode>;\n\t\tstd::bitset<256> tmp;\n\t\tfor(OpCode op: all_opcodes)\n\t\t\ttmp.set(static_cast<std::size_t>(op));\n\t\treturn tmp;\n\t}()};\n\treturn bs;\n}\n\n\nconst std::array<const char*, 256>& opcode_names()\n{\n\tstatic const std::array<const char*, 256> names { [](){ // immediately-invoked lambda\n\t\tstd::array<const char*, 256> tmp;\n\t\ttmp.fill(nullptr);\n\n\t\tusing int_type = std::underlying_type_t<OpCode>;\n\n\t\ttmp[static_cast<int_type>(OpCode::BLOCK)]               = \"block\";\n\t\ttmp[static_cast<int_type>(OpCode::LOOP)]                = \"loop\";\n\t\ttmp[static_cast<int_type>(OpCode::BR)]                  = \"br\";\n\t\ttmp[static_cast<int_type>(OpCode::BR_IF)]               = \"br_if\";\n\t\ttmp[static_cast<int_type>(OpCode::BR_TABLE)]            = \"br_table\";\n\t\ttmp[static_cast<int_type>(OpCode::IF)]                  = \"if\";\n\t\ttmp[static_cast<int_type>(OpCode::ELSE)]                = \"else\";\n\t\ttmp[static_cast<int_type>(OpCode::END)]                 = \"end\";\n\t\ttmp[static_cast<int_type>(OpCode::RETURN)]              = \"return\";\n\t\ttmp[static_cast<int_type>(OpCode::UNREACHABLE)]         = \"unreachable\";\n\n\t\ttmp[static_cast<int_type>(OpCode::NOP)]                 = \"nop\";\n\t\ttmp[static_cast<int_type>(OpCode::DROP)]                = \"drop\";\n\t\ttmp[static_cast<int_type>(OpCode::I32_CONST)]           = \"i32.const\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_CONST)]           = \"i64.const\";\n\t\ttmp[static_cast<int_type>(OpCode::F32_CONST)]           = \"f32.const\";\n\t\ttmp[static_cast<int_type>(OpCode::F64_CONST)]           = \"f64.const\";\n\t\ttmp[static_cast<int_type>(OpCode::GET_LOCAL)]           = \"get_local\";\n\t\ttmp[static_cast<int_type>(OpCode::SET_LOCAL)]           = \"set_local\";\n\t\ttmp[static_cast<int_type>(OpCode::TEE_LOCAL)]           = \"tee_local\";\n\t\ttmp[static_cast<int_type>(OpCode::GET_GLOBAL)]          = \"get_global\";\n\t\ttmp[static_cast<int_type>(OpCode::SET_GLOBAL)]          = \"set_global\";\n\t\ttmp[static_cast<int_type>(OpCode::SELECT)]              = \"select\";\n\t\ttmp[static_cast<int_type>(OpCode::CALL)]                = \"call\";\n\t\ttmp[static_cast<int_type>(OpCode::CALL_INDIRECT)]       = \"call_indirect\";\n\n\t\ttmp[static_cast<int_type>(OpCode::I32_ADD)]             = \"i32.add\";\n\t\ttmp[static_cast<int_type>(OpCode::I32_SUB)]             = \"i32.sub\";\n\t\ttmp[static_cast<int_type>(OpCode::I32_MUL)]             = \"i32.mul\";\n\t\ttmp[static_cast<int_type>(OpCode::I32_DIV_S)]           = \"i32.div_s\";\n\t\ttmp[static_cast<int_type>(OpCode::I32_DIV_U)]           = \"i32.div_u\";\n\t\ttmp[static_cast<int_type>(OpCode::I32_REM_S)]           = \"i32.rem_s\";\n\t\ttmp[static_cast<int_type>(OpCode::I32_REM_U)]           = \"i32.rem_u\";\n\t\ttmp[static_cast<int_type>(OpCode::I32_AND)]             = \"i32.and\";\n\t\ttmp[static_cast<int_type>(OpCode::I32_OR)]              = \"i32.or\";\n\t\ttmp[static_cast<int_type>(OpCode::I32_XOR)]             = \"i32.xor\";\n\t\ttmp[static_cast<int_type>(OpCode::I32_SHL)]             = \"i32.shl\";\n\t\ttmp[static_cast<int_type>(OpCode::I32_SHR_S)]           = \"i32.shr_s\";\n\t\ttmp[static_cast<int_type>(OpCode::I32_SHR_U)]           = \"i32.shr_u\";\n\t\ttmp[static_cast<int_type>(OpCode::I32_ROTL)]            = \"i32.rotl\";\n\t\ttmp[static_cast<int_type>(OpCode::I32_ROTR)]            = \"i32.rotr\";\n\t\ttmp[static_cast<int_type>(OpCode::I32_CLZ)]             = \"i32.clz\";\n\t\ttmp[static_cast<int_type>(OpCode::I32_CTZ)]             = \"i32.ctz\";\n\t\ttmp[static_cast<int_type>(OpCode::I32_POPCNT)]          = \"i32.popcnt\";\n\t\ttmp[static_cast<int_type>(OpCode::I32_EQZ)]             = \"i32.eqz\";\n\n\t\ttmp[static_cast<int_type>(OpCode::I64_ADD)]             = \"i64.add\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_SUB)]             = \"i64.sub\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_MUL)]             = \"i64.mul\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_DIV_S)]           = \"i64.div_s\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_DIV_U)]           = \"i64.div_u\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_REM_S)]           = \"i64.rem_s\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_REM_U)]           = \"i64.rem_u\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_AND)]             = \"i64.and\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_OR)]              = \"i64.or\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_XOR)]             = \"i64.xor\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_SHL)]             = \"i64.shl\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_SHR_S)]           = \"i64.shr_s\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_SHR_U)]           = \"i64.shr_u\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_ROTL)]            = \"i64.rotl\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_ROTR)]            = \"i64.rotr\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_CLZ)]             = \"i64.clz\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_CTZ)]             = \"i64.ctz\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_POPCNT)]          = \"i64.popcnt\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_EQZ)]             = \"i64.eqz\";\n\n\t\ttmp[static_cast<int_type>(OpCode::F32_ADD)]             = \"f32.add\";\n\t\ttmp[static_cast<int_type>(OpCode::F32_SUB)]             = \"f32.sub\";\n\t\ttmp[static_cast<int_type>(OpCode::F32_MUL)]             = \"f32.mul\";\n\t\ttmp[static_cast<int_type>(OpCode::F32_DIV)]             = \"f32.div\";\n\t\ttmp[static_cast<int_type>(OpCode::F32_SQRT)]            = \"f32.sqrt\";\n\t\ttmp[static_cast<int_type>(OpCode::F32_MIN)]             = \"f32.min\";\n\t\ttmp[static_cast<int_type>(OpCode::F32_MAX)]             = \"f32.max\";\n\t\ttmp[static_cast<int_type>(OpCode::F32_CEIL)]            = \"f32.ceil\";\n\t\ttmp[static_cast<int_type>(OpCode::F32_FLOOR)]           = \"f32.floor\";\n\t\ttmp[static_cast<int_type>(OpCode::F32_TRUNC)]           = \"f32.trunc\";\n\t\ttmp[static_cast<int_type>(OpCode::F32_NEAREST)]         = \"f32.nearest\";\n\t\ttmp[static_cast<int_type>(OpCode::F32_ABS)]             = \"f32.abs\";\n\t\ttmp[static_cast<int_type>(OpCode::F32_NEG)]             = \"f32.neg\";\n\t\ttmp[static_cast<int_type>(OpCode::F32_COPYSIGN)]        = \"f32.copysign\";\n\n\t\ttmp[static_cast<int_type>(OpCode::F64_ADD)]             = \"f64.add\";\n\t\ttmp[static_cast<int_type>(OpCode::F64_SUB)]             = \"f64.sub\";\n\t\ttmp[static_cast<int_type>(OpCode::F64_MUL)]             = \"f64.mul\";\n\t\ttmp[static_cast<int_type>(OpCode::F64_DIV)]             = \"f64.div\";\n\t\ttmp[static_cast<int_type>(OpCode::F64_SQRT)]            = \"f64.sqrt\";\n\t\ttmp[static_cast<int_type>(OpCode::F64_MIN)]             = \"f64.min\";\n\t\ttmp[static_cast<int_type>(OpCode::F64_MAX)]             = \"f64.max\";\n\t\ttmp[static_cast<int_type>(OpCode::F64_CEIL)]            = \"f64.ceil\";\n\t\ttmp[static_cast<int_type>(OpCode::F64_FLOOR)]           = \"f64.floor\";\n\t\ttmp[static_cast<int_type>(OpCode::F64_TRUNC)]           = \"f64.trunc\";\n\t\ttmp[static_cast<int_type>(OpCode::F64_NEAREST)]         = \"f64.nearest\";\n\t\ttmp[static_cast<int_type>(OpCode::F64_ABS)]             = \"f64.abs\";\n\t\ttmp[static_cast<int_type>(OpCode::F64_NEG)]             = \"f64.neg\";\n\t\ttmp[static_cast<int_type>(OpCode::F64_COPYSIGN)]        = \"f64.copysign\";\n\n\t\ttmp[static_cast<int_type>(OpCode::I32_EQ)]              = \"i32.eq\";\n\t\ttmp[static_cast<int_type>(OpCode::I32_NE)]              = \"i32.ne\";\n\t\ttmp[static_cast<int_type>(OpCode::I32_LT_S)]            = \"i32.lt_s\";\n\t\ttmp[static_cast<int_type>(OpCode::I32_LT_U)]            = \"i32.lt_u\";\n\t\ttmp[static_cast<int_type>(OpCode::I32_GT_S)]            = \"i32.gt_s\";\n\t\ttmp[static_cast<int_type>(OpCode::I32_GT_U)]            = \"i32.gt_u\";\n\t\ttmp[static_cast<int_type>(OpCode::I32_LE_S)]            = \"i32.le_s\";\n\t\ttmp[static_cast<int_type>(OpCode::I32_LE_U)]            = \"i32.le_u\";\n\t\ttmp[static_cast<int_type>(OpCode::I32_GE_S)]            = \"i32.ge_s\";\n\t\ttmp[static_cast<int_type>(OpCode::I32_GE_U)]            = \"i32.ge_u\";\n\n\t\ttmp[static_cast<int_type>(OpCode::I64_EQ)]              = \"i64.eq\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_NE)]              = \"i64.ne\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_LT_S)]            = \"i64.lt_s\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_LT_U)]            = \"i64.lt_u\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_GT_S)]            = \"i64.gt_s\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_GT_U)]            = \"i64.gt_u\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_LE_S)]            = \"i64.le_s\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_LE_U)]            = \"i64.le_u\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_GE_S)]            = \"i64.ge_s\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_GE_U)]            = \"i64.ge_u\";\n\n\t\ttmp[static_cast<int_type>(OpCode::F32_EQ)]              = \"f32.eq\";\n\t\ttmp[static_cast<int_type>(OpCode::F32_NE)]              = \"f32.ne\";\n\t\ttmp[static_cast<int_type>(OpCode::F32_LT)]              = \"f32.lt\";\n\t\ttmp[static_cast<int_type>(OpCode::F32_GT)]              = \"f32.gt\";\n\t\ttmp[static_cast<int_type>(OpCode::F32_LE)]              = \"f32.le\";\n\t\ttmp[static_cast<int_type>(OpCode::F32_GE)]              = \"f32.ge\";\n\n\t\ttmp[static_cast<int_type>(OpCode::F64_EQ)]              = \"f64.eq\";\n\t\ttmp[static_cast<int_type>(OpCode::F64_NE)]              = \"f64.ne\";\n\t\ttmp[static_cast<int_type>(OpCode::F64_LT)]              = \"f64.lt\";\n\t\ttmp[static_cast<int_type>(OpCode::F64_GT)]              = \"f64.gt\";\n\t\ttmp[static_cast<int_type>(OpCode::F64_LE)]              = \"f64.le\";\n\t\ttmp[static_cast<int_type>(OpCode::F64_GE)]              = \"f64.ge\";\n\n\t\ttmp[static_cast<int_type>(OpCode::I32_WRAP)]            = \"i32.wrap/i64\";\n\t\ttmp[static_cast<int_type>(OpCode::I32_TRUNC_F32_S)]     = \"i32.trunc_s/f32\";\n\t\ttmp[static_cast<int_type>(OpCode::I32_TRUNC_F32_U)]     = \"i32.trunc_u/f32\";\n\t\ttmp[static_cast<int_type>(OpCode::I32_TRUNC_F64_S)]     = \"i32.trunc_s/f64\";\n\t\ttmp[static_cast<int_type>(OpCode::I32_TRUNC_F64_U)]     = \"i32.trunc_u/f64\";\n\t\ttmp[static_cast<int_type>(OpCode::I32_REINTERPRET_F32)] = \"i32.reinterpret/f32\";\n\n\t\ttmp[static_cast<int_type>(OpCode::I64_EXTEND_S)]        = \"i64.extend_s/i32\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_EXTEND_U)]        = \"i64.extend_u/i32\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_TRUNC_F32_S)]     = \"i64.trunc_s/f32\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_TRUNC_F32_U)]     = \"i64.trunc_u/f32\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_TRUNC_F64_S)]     = \"i64.trunc_s/f64\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_TRUNC_F64_U)]     = \"i64.trunc_u/f64\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_REINTERPRET_F64)] = \"i64.reinterpret/f64\";\n\n\t\ttmp[static_cast<int_type>(OpCode::F32_DEMOTE)]          = \"f32.demote/f64\";\n\t\ttmp[static_cast<int_type>(OpCode::F32_CONVERT_I32_S)]   = \"f32.convert_s/i32\";\n\t\ttmp[static_cast<int_type>(OpCode::F32_CONVERT_I32_U)]   = \"f32.convert_u/i32\";\n\t\ttmp[static_cast<int_type>(OpCode::F32_CONVERT_I64_S)]   = \"f32.convert_s/i64\";\n\t\ttmp[static_cast<int_type>(OpCode::F32_CONVERT_I64_U)]   = \"f32.convert_u/i64\";\n\t\ttmp[static_cast<int_type>(OpCode::F32_REINTERPRET_I32)] = \"f32.reinterpret/i32\";\n\n\t\ttmp[static_cast<int_type>(OpCode::F64_PROMOTE)]         = \"f64.promote\";\n\t\ttmp[static_cast<int_type>(OpCode::F64_CONVERT_I32_S)]   = \"f64.convert_s/i32\";\n\t\ttmp[static_cast<int_type>(OpCode::F64_CONVERT_I32_U)]   = \"f64.convert_u/i32\";\n\t\ttmp[static_cast<int_type>(OpCode::F64_CONVERT_I64_S)]   = \"f64.convert_s/i64\";\n\t\ttmp[static_cast<int_type>(OpCode::F64_CONVERT_I64_U)]   = \"f64.convert_u/i64\";\n\t\ttmp[static_cast<int_type>(OpCode::F64_REINTERPRET_I64)] = \"f64.reinterpret/i64\";\n\n\t\ttmp[static_cast<int_type>(OpCode::I32_LOAD)]            = \"i32.load\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_LOAD)]            = \"i64.load\";\n\t\ttmp[static_cast<int_type>(OpCode::F32_LOAD)]            = \"f32.load\";\n\t\ttmp[static_cast<int_type>(OpCode::F64_LOAD)]            = \"f64.load\";\n\t\ttmp[static_cast<int_type>(OpCode::I32_LOAD8_S)]         = \"i32.load8_s\";\n\t\ttmp[static_cast<int_type>(OpCode::I32_LOAD8_U)]         = \"i32.load8_u\";\n\t\ttmp[static_cast<int_type>(OpCode::I32_LOAD16_S)]        = \"i32.load16_s\";\n\t\ttmp[static_cast<int_type>(OpCode::I32_LOAD16_U)]        = \"i32.load16_u\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_LOAD8_S)]         = \"i64.load8_s\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_LOAD8_U)]         = \"i64.load8_u\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_LOAD16_S)]        = \"i64.load16_s\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_LOAD16_U)]        = \"i64.load16_u\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_LOAD32_S)]        = \"i64.load32_s\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_LOAD32_U)]        = \"i64.load32_u\";\n\t\ttmp[static_cast<int_type>(OpCode::I32_STORE)]           = \"i32.store\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_STORE)]           = \"i64.store\";\n\t\ttmp[static_cast<int_type>(OpCode::F32_STORE)]           = \"f32.store\";\n\t\ttmp[static_cast<int_type>(OpCode::F64_STORE)]           = \"f64.store\";\n\t\ttmp[static_cast<int_type>(OpCode::I32_STORE8)]          = \"i32.store8\";\n\t\ttmp[static_cast<int_type>(OpCode::I32_STORE16)]         = \"i32.store16\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_STORE8)]          = \"i64.store8\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_STORE16)]         = \"i64.store16\";\n\t\ttmp[static_cast<int_type>(OpCode::I64_STORE32)]         = \"i64.store32\";\n\n\t\ttmp[static_cast<int_type>(OpCode::GROW_MEMORY)]         = \"grow_memory\";\n\t\ttmp[static_cast<int_type>(OpCode::CURRENT_MEMORY)]      = \"current_memory\";\n\n\t\treturn tmp;\n\t}()/* invoke lambda */}; /* names */\n\treturn names;\n}\n\n} /* namespace detail */\n\nstd::ostream& operator<<(std::ostream& os, OpCode oc)\n{\n\tconst char* name = detail::opcode_names()[static_cast<unsigned>(oc)];\n\tif(not name)\n\t{\n\t\tos << \"bad_opcode(0x\" << std::hex << std::setw(2) << std::setfill('0');\n\t\tos << static_cast<unsigned>(oc) << ')';\n\t}\n\telse\n\t{\n\t\tos << name;\n\t}\n\treturn os;\n}\n\n[[gnu::pure]]\ninline bool opcode_exists(std::underlying_type_t<OpCode> oc)\n{ return detail::opcode_mask().test(oc); }\n\nnamespace detail {\n\ntemplate <class It>\n[[gnu::pure]]\nstd::tuple<wasm_uint32_t, wasm_uint32_t, It> read_memory_immediate(It first, It last)\n{\n\talignas(wasm_uint32_t) char buff1[sizeof(wasm_uint32_t)];\n\talignas(wasm_uint32_t) char buff2[sizeof(wasm_uint32_t)];\n\twasm_uint32_t flags;\n\twasm_uint32_t offset;\n\tfor(auto& chr: buff1)\n\t{\n\t\tassert(first != last);\n\t\tchr = *first++;\n\t}\n\tfor(auto& chr: buff2)\n\t{\n\t\tassert(first != last);\n\t\tchr = *first++;\n\t}\n\tstd::memcpy(&flags, buff1, sizeof(flags));\n\tstd::memcpy(&offset, buff1, sizeof(offset));\n\treturn std::make_tuple(flags, offset, first);\n}\n\ntemplate <class T, class It>\n[[gnu::pure]]\nstd::pair<T, It> read_serialized_immediate(It first, It last)\n{\n\tstatic_assert(std::is_trivially_copyable_v<T>);\n\tT value;\n\talignas(T) char buff[sizeof(T)];\n\tfor(auto& chr: buff)\n\t{\n\t\tassert(first != last);\n\t\tchr = *first++;\n\t}\n\tstd::memcpy(&value, buff, sizeof(value));\n\treturn std::make_pair(value, first);\n}\n\n} /* namespace detail */\n\nstruct BadOpcodeError:\n\tpublic std::logic_error\n{\n\tBadOpcodeError(OpCode op, const char* msg):\n\t\tstd::logic_error(msg),\n\t\topcode(op)\n\t{\n\n\t}\n\t\n\tconst OpCode opcode;\n};\n\ntemplate <class It, class Visitor>\ndecltype(auto) visit_opcode(Visitor visitor, It first, It last)\n{\n\tassert(first != last);\n\tOpCode op;\n\tauto pos = first;\n\tusing value_type = typename std::iterator_traits<It>::value_type;\n\tusing underlying_type = std::underlying_type_t<OpCode>;\n\tif constexpr(not std::is_same_v<value_type, OpCode>)\n\t{\n\t\tvalue_type opcode = *pos++;\n\t\top = static_cast<OpCode>(opcode);\n\t\tassert(static_cast<value_type>(op) == opcode);\n\t}\n\telse\n\t{\n\t\top = *pos++;\n\t}\n\n\t// Handling the invalid opcode case is optional.\n\tif constexpr(std::is_invocable_v<Visitor, OpCode, std::nullopt_t>)\n\t{\n\t\tif(not opcode_exists(static_cast<underlying_type>(op)))\n\t\t{\n\t\t\treturn visitor(\n\t\t\t\tfirst, \n\t\t\t\tlast,\n\t\t\t\tpos,\n\t\t\t\top,\n\t\t\t\tBadOpcodeError(op, \"Given op is not a valid WASM opcode.\")\n\t\t\t);\n\t\t}\n\t}\n\telse\n\t{\n\t\tif(not opcode_exists(static_cast<underlying_type>(op)))\n\t\t\tassert(false);\n\t}\n\t\n\tif(op >= OpCode::I32_LOAD and op <= OpCode::I64_STORE32)\n\t{\n\t\twasm_uint32_t flags, offset;\n\t\tstd::tie(flags, offset, pos) = detail::read_memory_immediate(pos, last);\n\t\treturn visitor(first, last, pos, op, flags, offset);\n\t}\n\telse if(\n\t\t(op >= OpCode::GET_LOCAL and op <= OpCode::SET_GLOBAL)\n\t\tor (op == OpCode::CALL or op == OpCode::CALL_INDIRECT)\n\t\tor (op == OpCode::BR or op == OpCode::BR_IF)\n\t\tor (op == OpCode::ELSE)\n\t)\n\t{\n\t\twasm_uint32_t value;\n\t\tstd::tie(value, pos) = detail::read_serialized_immediate<wasm_uint32_t>(pos, last);\n\t\treturn visitor(first, last, pos, op, value);\n\t}\n\telse if(op == OpCode::BLOCK or op == OpCode::IF)\n\t{\n\t\tassert(first != last);\n\t\tLanguageType tp = static_cast<LanguageType>(*first++);\n\t\twasm_uint32_t label;\n\t\tstd::tie(label, pos) = detail::read_serialized_immediate<wasm_uint32_t>(pos, last);\n\t\treturn visitor(first, last, pos, op, tp, label);\n\t}\n\telse if(op == OpCode::LOOP)\n\t{\n\t\tassert(first != last);\n\t\tLanguageType tp = static_cast<LanguageType>(*first++);\n\t\treturn visitor(first, last, pos, op, tp);\n\t}\n\telse if(op == OpCode::BR_TABLE)\n\t{\n\t\twasm_uint32_t len;\n\t\tstd::tie(len, pos) = detail::read_serialized_immediate<wasm_uint32_t>(pos, last);\n\t\tauto base = pos;\n\t\tstd::advance(pos, (1 + len) * sizeof(wasm_uint32_t));\n\t\treturn visitor(first, last, pos, op, base, len);\n\t}\n\t\n\tswitch(op)\n\t{\n\tcase OpCode::I32_CONST: {\n\t\twasm_sint32_t v;\n\t\tstd::tie(v, pos) = detail::read_serialized_immediate<wasm_sint32_t>(pos, last);\n\t\treturn visitor(first, last, pos, op, v);\n\t\tbreak;\n\t}\n\tcase OpCode::I64_CONST: {\n\t\twasm_sint64_t v;\n\t\tstd::tie(v, pos) = detail::read_serialized_immediate<wasm_sint64_t>(pos, last);\n\t\treturn visitor(first, last, pos, op, v);\n\t\tbreak;\n\t}\n\tcase OpCode::F32_CONST: {\n\t\twasm_float32_t v;\n\t\tstd::tie(v, pos) = detail::read_serialized_immediate<wasm_float32_t>(pos, last);\n\t\treturn visitor(first, last, pos, op, v);\n\t\tbreak;\n\t}\n\tcase OpCode::F64_CONST: {\t\n\t\twasm_float64_t v;\n\t\tstd::tie(v, pos) = detail::read_serialized_immediate<wasm_float64_t>(pos, last);\n\t\treturn visitor(first, last, pos, op, v);\n\t\tbreak;\n\t}\n\tdefault:\n\t\treturn visitor(op, first, pos, last);\n\t}\n\tassert(false and \"Internal Error: All cases should have been handled by this point.\");\n}\n\nstruct MemoryImmediate:\n\tpublic std::pair<const wasm_uint32_t, const wasm_uint32_t>\n{\n\tusing std::pair<const wasm_uint32_t, const wasm_uint32_t>::pair;\n};\n\nwasm_uint32_t flags(const MemoryImmediate& immed)\n{ return immed.first; }\n\nwasm_uint32_t offset(const MemoryImmediate& immed)\n{ return immed.second; }\n\nstruct BlockImmediate:\n\tpublic std::pair<const LanguageType, const wasm_uint32_t>\n{\n\tusing std::pair<const LanguageType, const wasm_uint32_t>::pair;\n};\n\ngsl::span<const LanguageType> signature(const BlockImmediate& immed)\n{\n\tif(immed.first == LanguageType::BLOCK)\n\t\treturn gsl::span<const LanguageType>();\n\treturn gsl::span<const LanguageType>(&(immed.first), 1u);\n}\n\nstd::size_t arity(const BlockImmediate& immed)\n{ return signature(immed).size(); }\n\nwasm_uint32_t offset(const BlockImmediate& immed)\n{ return immed.second; }\n\nstruct IfImmediate:\n\tpublic std::tuple<const LanguageType, const wasm_uint32_t, const wasm_uint32_t>\n{\n\tusing std::tuple<const LanguageType, const wasm_uint32_t, const wasm_uint32_t>::pair;\n};\n\nwasm_uint32_t else_offset(const IfImmediate& immed)\n{ return std::get<2u>(immed); }\n\nwasm_uint32_t end_offset(const IfImmediate& immed)\n{ return std::get<1u>(immed); }\n\ngsl::span<const LanguageType> signature(const IfImmediate& immed)\n{ \n\tif(std::get<0u>(immed) == LanguageType::BLOCK)\n\t\treturn gsl::span<const LanguageType>();\n\treturn gsl::span<const LanguageType>(&(std::get<0u>(immed)), 1u);\n}\n\nstd::size_t arity(const IfImmediate& immed)\n{ return signature(immed).size(); }\n\nstruct BranchTableImmediate\n{\n\ttemplate <class ... T>\n\tBranchTableImmediate(T&& ... args):\n\t\ttable_(std::forward<T>(args)...)\n\t{\n\t\t\n\t}\n\n\twasm_uint32_t at(wasm_uint32_t idx) const\n\t{\n\t\tidx = std::min(std::size_t(table_.size() - 1u), std::size_t(idx));\n\t\twasm_uint32_t depth;\n\t\tstd::memcpy(&depth, table_.data() + idx, sizeof(depth));\n\t\treturn depth;\n\t}\n\nprivate:\n\tconst gsl::span<const char[sizeof(wasm_uint32_t)]> table_;\n};\n\nstruct WasmInstruction\n{\n\tusing null_immediate_type         = std::monostate;\n\tusing i32_immediate_type          = wasm_sint32_t;\n\tusing i64_immediate_type          = wasm_sint64_t;\n\tusing f32_immediate_type          = wasm_float32_t;\n\tusing f64_immediate_type          = wasm_float64_t;\n\tusing offset_immediate_type       = wasm_uint32_t;\n\tusing memory_immediate_type       = MemoryImmediate;\n\tusing block_immediate_type        = BlockImmediate;\n\tusing loop_immediate_type         = LanguageType;\n\tusing branch_table_immediate_type = BranchTableImmediate;\n\n\tunion immediate_type\n\t{\n\t\t// no immediate (most instructions)\n\t\tnull_immediate_type         null_immed;\n\t\t// i32.const\n\t\ti32_immediate_type          i32_immed;\n\t\t// i64.const\n\t\ti64_immediate_type          i64_immed;\n\t\t// f32.const\n\t\tf32_immediate_type          f32_immed;\n\t\t// f64.const\n\t\tf64_immediate_type          f64_immed;\n\t\t// offset: br, br_if, else (precomputed jump), call, call_indirect\n\t\t//         get_local, set_local, tee_local, get_global, set_global\n\t\toffset_immediate_type       offset_immed;\n\t\t// memory immediate: i32.load (0x28) through i64.store32 (0x3e)\n\t\tmemory_immediate_type       memory_immed;\n\t\t// block immediate (signature + precomputed jump): if, block\n\t\tblock_immediate_type        block_immed;\n\t\t// loop (signature)\n\t\tloop_immediate_type         loop_immed;\n\t\t// branch table unaligned array of offset_immediate_type (native byte order)\n\t\t// branch depths + one default depth.  \n\t\tbranch_table_immediate_type br_table_immed;\n\t};\n\n\tusing tagged_immediate_type = std::variant<\n\t\tnull_immediate_type,\n\t\ti32_immediate_type,\n\t\ti64_immediate_type,\n\t\tf32_immediate_type,\n\t\tf64_immediate_type,\n\t\toffset_immediate_type,\n\t\tmemory_immediate_type,\n\t\tblock_immediate_type,\n\t\tloop_immediate_type,\n\t\tbranch_table_immediate_type\n\t>;\n\n\nprivate:\n\ttemplate <class T>\n\tstruct Tag{};\n\n\tvoid _assert_invariants() const\n\t{\n\t\tassert(opcode_exists(opcode));\n\t\tassert(source.size() >= 1u);\n\t\tif(not validate(null_immediate_type{}))\n\t\t\tassert(source.size() > 1u);\n\t}\n\n\tbool validate(Tag<null_immediate_type>) const\n\t{\n\t\t_assert_invariants();\n\t\treturn ((opcode > OpCode::I32_EQZ) \n\t\t\tor (opcode == OpCode::UNREACHABLE)\n\t\t\tor (opcode == OpCode::NOP)\n\t\t\tor (opcode == OpCode::ELSE)\n\t\t\tor (opcode == OpCode::END)\n\t\t\tor (opcode == OpCode::RETURN)\n\t\t\tor (opcode == OpCode::DROP)\n\t\t\tor (opcode == OpCode::SELECT)\n\t\t\tor (opcode == OpCode::CURRENT_MEMORY)\n\t\t\tor (opcode == OpCode::GROW_MEMORY)\n\t\t);\n\t}\n\t\n\tbool validate(Tag<offset_immediate_type>) const\n\t{\n\t\t_assert_invariants();\n\t\treturn ((op >= OpCode::GET_LOCAL and op <= OpCode::SET_GLOBAL)\n\t\t\tor (op >= OpCode::CALL and op <= OpCode::CALL_INDIRECT)\n\t\t\tor (op >= OpCode::BR and op <= OpCode::BR_IF)\n\t\t\tor (op == OpCode::ELSE)\n\t\t);\n\t}\n\n\tbool validate(Tag<i32_immediate_type>) const\n\t{\n\t\t_assert_invariants();\n\t\treturn (opcode == OpCode::I32_CONST);\n\t}\n\n\tbool validate(Tag<i64_immediate_type>) const\n\t{\n\t\t_assert_invariants();\n\t\treturn (opcode == OpCode::I64_CONST);\n\t}\n\n\tbool validate(Tag<f32_immediate_type>) const\n\t{\n\t\t_assert_invariants();\n\t\treturn (opcode == OpCode::F32_CONST);\n\t}\n\n\tbool validate(Tag<f64_immediate_type>) const\n\t{\n\t\t_assert_invariants();\n\t\treturn (opcode == OpCode::F64_CONST);\n\t}\n\n\tbool validate(Tag<memory_immediate_type>) const\n\t{\n\t\t_assert_invariants();\n\t\treturn (opcode >= OpCode::I32_LOAD)\n\t\t\tand (opcode >= OpCode::I64_STORE32);\n\t}\n\n\tbool validate(Tag<block_immediate_type>) const\n\t{\n\t\t_assert_invariants();\n\t\treturn (opcode == OpCode::BLOCK)\n\t\t\tor (opcode == OpCode::IF);\n\t}\n\n\tbool validate(Tag<branch_table_immediate_type>) const\n\t{\n\t\t_assert_invariants();\n\t\treturn (opcode == OpCode::BR_TABLE);\n\t}\n\n\tbool validate(Tag<loop_immediate_type>) const\n\t{\n\t\t_assert_invariants();\n\t\treturn (opcode == OpCode::LOOP);\n\t}\n\n\ttemplate <class T>\n\tvoid assert_valid(Tag<T>) const\n\t{\n\t\tassert(validate(Tag<T>{}));\n\t}\n\n\tWasmInstruction(std::string_view src, OpCode op, const char* end_pos, null_immediate_type null_immed):\n\t\tsource(src), opcode(op), end(end_pos), raw_immediate_{null_immed}\n\t{ assert_valid(Tag<null_immediate_type>{}); }\n\n\tWasmInstruction(std::string_view src, OpCode op, const char* end_pos, i32_immediate_type i32_immed):\n\t\tsource(src), opcode(op), end(end_pos), raw_immediate_{i32_immed}\n\t{ assert_valid(Tag<i32_immediate_type>{}); }\n\n\tWasmInstruction(std::string_view src, OpCode op, const char* end_pos, i64_immediate_type i64_immed):\n\t\tsource(src), opcode(op), end(end_pos), raw_immediate_{i64_immed}\n\t{ assert_valid(Tag<i64_immediate_type>{}); }\n\n\tWasmInstruction(std::string_view src, OpCode op, const char* end_pos, f32_immediate_type f32_immed):\n\t\tsource(src), opcode(op), end(end_pos), raw_immediate_{f32_immed}\n\t{ asser_valid(Tag<f32_immediate_type>{}); }\n\n\tWasmInstruction(std::string_view src, OpCode op, const char* end_pos, f64_immediate_type f64_immed):\n\t\tsource(src), opcode(op), end(end_pos), raw_immediate_{f64_immed}\n\t{ assert_valid(Tag<f64_immediate_type>{}); }\n\n\tWasmInstruction(std::string_view src, OpCode op, const char* end_pos, offset_immediate_type offset_immed):\n\t\tsource(src), opcode(op), end(end_pos), raw_immediate_{offset_immed}\n\t{ assert_valid(Tag<offset_immediate_type>{}); }\n\n\tWasmInstruction(std::string_view src, OpCode op, const char* end_pos, loop_immediate_type loop_immed):\n\t\tsource(src), opcode(op), end(end_pos), raw_immediate_{loop_immed}\n\t{ assert_valid(Tag<loop_immediate_type>{}); }\n\n\tWasmInstruction(std::string_view src, OpCode op, const char* end_pos, memory_immediate_type memory_immed):\n\t\tsource(src), opcode(op), end(end_pos), raw_immediate_{memory_immed}\n\t{ assert_valid(Tag<memory_immediate_type>{}); }\n\n\tWasmInstruction(std::string_view src, OpCode op, const char* end_pos, block_immediate_type block_immed):\n\t\tsource(src), opcode(op), end(end_pos), raw_immediate_{block_immed}\n\t{ assert_valid(Tag<loop_immediate_type>{}); }\n\n\tWasmInstruction(std::string_view src, OpCode op, const char* end_pos, branch_table_immediate_type br_table_immed):\n\t\tsource(src), opcode(op), end(end_pos), raw_immediate_{br_table_immed}\n\t{ assert_valid(Tag<branch_table_immediate_type>{}); }\n\npublic:\n\n\tconst immediate_type& raw_immediate() const\n\t{ return raw_immediate_; }\n\n\tconst offset_immediate_type& offset_immed() \n\n\ttagged_immediate_type tagged_immediate() const\n\t{\n\t\t// This if() covers 20-something ops.\n\t\tif(opcode >= OpCode::I32_LOAD and opcode <= I64_STORE32)\n\t\t{\n\t\t\treturn tagged_immediate_type(\n\t\t\t\tstd::in_place_type<memory_immediate_type>,\n\t\t\t\traw().memory_immed\n\t\t\t);\n\t\t}\n\t\tswitch(opcode)\n\t\t{\n\t\t// case for ops with no immediate\n\t\tdefault:\n\t\t\tassert(opcode_exists(static_cast<std::size_t>(opcode)));\n\t\t\treturn tagged_immediate_type(\n\t\t\t\tstd::in_place_type<null_immediate_type>,\n\t\t\t\traw().null_immed\n\t\t\t);\n\t\t// cases for block immediate\n\t\tcase OpCode::BLOCK: [[fallthrough]];\n\t\tcase OpCode::IF:\n\t\t\treturn tagged_immediate_type(\n\t\t\t\tstd::in_place_type<block_immediate_type>,\n\t\t\t\traw().block_immed\n\t\t\t);\n\t\t// cases for uint32 immediate\n\t\tcase OpCode::ELSE:          [[fallthrough]];\n\t\tcase OpCode::BR:            [[fallthrough]];\n\t\tcase OpCode::BR_IF:         [[fallthrough]];\n\t\tcase OpCode::CALL:          [[fallthrough]];\n\t\tcase OpCode::CALL_INDIRECT: [[fallthrough]];\n\t\tcase OpCode::GET_LOCAL:     [[fallthrough]];\n\t\tcase OpCode::SET_LOCAL:     [[fallthrough]];\n\t\tcase OpCode::TEE_LOCAL:     [[fallthrough]];\n\t\tcase OpCode::GET_GLOBAL:    [[fallthrough]];\n\t\tcase OpCode::SET_GLOBAL:\n\t\t\treturn tagged_immediate_type(\n\t\t\t\tstd::in_place_type<offset_immediate_type>,\n\t\t\t\traw().offset_immed\n\t\t\t);\n\t\t// case for loop immediate\n\t\tcase OpCode::LOOP:\n\t\t\treturn tagged_immediate_type(\n\t\t\t\tstd::in_place_type<loop_immediate_type>,\n\t\t\t\traw().loop_immed\n\t\t\t);\n\t\t// case for loop immediate\n\t\tcase OpCode::LOOP:\n\t\t\treturn tagged_immediate_type(\n\t\t\t\tstd::in_place_type<loop_immediate_type>,\n\t\t\t\traw().loop_immed\n\t\t\t);\n\t\t// case for br_table immediate\n\t\tcase OpCode::BR_TABLE:\n\t\t\treturn tagged_immediate_type(\n\t\t\t\tstd::in_place_type<branch_table_immediate_type>,\n\t\t\t\traw().br_table_immed\n\t\t\t);\n\t\t// case for i32.const immediate\n\t\tcase OpCode::I32_CONST:\n\t\t\treturn tagged_immediate_type(\n\t\t\t\tstd::in_place_type<i32_immediate_type>,\n\t\t\t\traw().i32_immed\n\t\t\t);\n\t\t// case for i64.const immediate\n\t\tcase OpCode::I64_CONST:\n\t\t\treturn tagged_immediate_type(\n\t\t\t\tstd::in_place_type<i64_immediate_type>,\n\t\t\t\traw().i64_immed\n\t\t\t);\n\t\t// case for f32.const immediate\n\t\tcase OpCode::F32_CONST:\n\t\t\treturn tagged_immediate_type(\n\t\t\t\tstd::in_place_type<f32_immediate_type>,\n\t\t\t\traw().f32_immed\n\t\t\t);\n\t\t// case for f64.const immediate\n\t\tcase OpCode::F64_CONST:\n\t\t\treturn tagged_immediate_type(\n\t\t\t\tstd::in_place_type<f64_immediate_type>,\n\t\t\t\traw().f64_immed\n\t\t\t);\n\t\t}\n\t\tassert(false);\n\t}\n\n\t\n\tOpCode opcode() const\n\t{ return opcode_; }\n\n\tstd::string_view source() const\n\t{ return source_; }\n\n\tstd::string_view full_source() const\n\t{ return std::string_view(source().data(), end_ - source().data()); }\n\n\tconst char* end_pos() const\n\t{ return end_; }\n\n\tconst char* pos() const\n\t{ return source().data(); }\n\n\tCodeView after() const\n\t{\n\t\tassert(pos() < end_pos());\n\t\tassert(static_cast<std::size_t>(end_pos() - pos()) < source().size());\n\t\tauto source_end = source().data() + source().size()\n\t\treturn CodeView(source_end, end_pos() - source_end);\n\t}\n\n\ttemplate <class CallStackType>\n\tCodeView execute(WasmModule& module, CallStackType& call_stack) \n\t{\n\t\tswitch(opcode)\n\t\t{\n\t\tcase OpCode::UNREACHABLE:\n\t\t\tassert_valid(Tag<null_immediate_type>{});\n\t\t\top_func<OpCode::UNREACHABLE>();\n\t\t\tbreak;\n\t\tcase OpCode::NOP:\n\t\t\tassert_valid(Tag<null_immediate_type>{});\n\t\t\top_func<OpCode::NOP>();\n\t\t\tbreak;\n\t\tcase OpCode::BLOCK:\n\t\t\tassert_valid(Tag<block_immediate_type>{});\n\t\t\top_func<OpCode::BLOCK>();\n\t\t\tbreak;\n\t\tcase OpCode::LOOP:\n\t\t\tassert_valid(Tag<loop_immediate_type>{});\n\t\t\top_func<OpCode::LOOP>();\n\t\t\tbreak;\n\t\tcase OpCode::IF:\n\t\t\tassert_valid(Tag<block_immediate_type>{});\n\t\t\top_func<OpCode::IF>();\n\t\t\tbreak;\n\t\tcase OpCode::ELSE:\n\t\t\tassert_valid(Tag<offset_immediate_type>{});\n\t\t\top_func<OpCode::ELSE>();\n\t\t\tbreak;\n\t\tcase OpCode::END:\n\t\t\tassert_valid(Tag<null_immediate_type>{});\n\t\t\top_func<OpCode::END>(\n\t\t\t\tcurrent_frame(call_stack), raw_immediate().offset_immed, *this\n\t\t\t);\n\t\t\tbreak;\n\t\tcase OpCode::BR:\n\t\t\tassert_valid(Tag<offset_immediate_type>{});\n\t\t\top_func<OpCode::BR>(\n\t\t\t\tcurrent_frame(call_stack), raw_immediate().offset_immed, *this\n\t\t\t);\n\t\t\tbreak;\n\t\tcase OpCode::BR_IF:\n\t\t\tassert_valid(Tag<offset_immediate_type>{});\n\t\t\top_func<OpCode::BR_IF>(\n\t\t\t\tcurrent_frame(call_stack), raw_immediate().offset_immed, *this\n\t\t\t);\n\t\t\tbreak;\n\t\tcase OpCode::BR_TABLE:\n\t\t\tassert_valid(Tag<branch_table_immediate_type>{});\n\t\t\top_func<OpCode::BR_TABLE>(\n\t\t\t\tcall_stack, raw_immediate().branch_table_immed, *this\n\t\t\t);\n\t\t\tbreak;\n\t\tcase OpCode::RETURN:\n\t\t\tassert_valid(Tag<null_immediate_type>{});\n\t\t\top_func<OpCode::RETURN>(call_stack);\n\t\t\tbreak;\n\t\tcase OpCode::CALL:\n\t\t\tassert_valid(Tag<offset_immediate_type>{});\n\t\t\top_func<OpCode::CALL>(\n\t\t\t\tcall_stack, module, raw_immediate().offset_immed, *this\n\t\t\t);\n\t\t\tbreak;\n\t\tcase OpCode::CALL_INDIRECT:\n\t\t\tassert_valid(Tag<offset_immediate_type>{});\n\t\t\top_func<OpCode::CALL_INDIRECT>(\n\t\t\t\tcall_stack, module, raw_immediate().offset_immed, *this\n\t\t\t);\n\t\t\tbreak;\n\t\tcase OpCode::DROP:\n\t\t\tassert_valid(Tag<null_immediate_type>{});\n\t\t\top_func<OpCode::DROP>(current_frame(call_stack));\n\t\t\tbreak;\n\t\tcase OpCode::SELECT:\n\t\t\tassert_valid(Tag<null_immediate_type>{});\n\t\t\top_func<OpCode::SELECT>(current_frame(call_stack));\n\t\t\tbreak;\n\t\tcase OpCode::GET_LOCAL:\n\t\t\tassert_valid(Tag<offset_immediate_type>{});\n\t\t\top_func<OpCode::GET_LOCAL>(\n\t\t\t\tcurrent_frame(call_stack), raw_immediate().offset_immed, \n\t\t\t);\n\t\t\tbreak;\n\t\tcase OpCode::SET_LOCAL:\n\t\t\tassert_valid(Tag<offset_immediate_type>{});\n\t\t\top_func<OpCode::SET_LOCAL>(\n\t\t\t\tcurrent_frame(call_stack), raw_immediate().offset_immed, \n\t\t\t);\n\t\t\tbreak;\n\t\tcase OpCode::TEE_LOCAL:\n\t\t\tassert_valid(Tag<offset_immediate_type>{});\n\t\t\top_func<OpCode::TEE_LOCAL>(\n\t\t\t\tcurrent_frame(call_stack), raw_immediate().offset_immed\n\t\t\t);\n\t\t\tbreak;\n\t\tcase OpCode::GET_GLOBAL:\n\t\t\tassert_valid(Tag<offset_immediate_type>{});\n\t\t\top_func<OpCode::GET_GLOBAL>(\n\t\t\t\tcurrent_frame(call_stack), module, raw_immediate().offset_immed, \n\t\t\t);\n\t\t\tbreak;\n\t\tcase OpCode::SET_GLOBAL:\n\t\t\tassert_valid(Tag<offset_immediate_type>{});\n\t\t\top_func<OpCode::SET_GLOBAL>(\n\t\t\t\tcurrent_frame(call_stack), module, raw_immediate().offset_immed, \n\t\t\t);\n\t\t\tbreak;\n\n\t\t/// MEMORY OPS\n\t\t// load\n\t\tcase OpCode::I32_LOAD:\n\t\t\tassert_valid(Tag<memory_immediate_type>{});\n\t\t\tconst auto& immed = raw_immediate().memory_immed;\n\t\t\top_func<OpCode::I32_LOAD>(\n\t\t\t\tcurrent_frame(call_stack), module, flags(immed), offset(immed)\n\t\t\t);\n\t\t\tbreak;\n\t\tcase OpCode::I64_LOAD:\n\t\t\tassert_valid(Tag<memory_immediate_type>{});\n\t\t\tconst auto& immed = raw_immediate().memory_immed;\n\t\t\top_func<OpCode::I64_LOAD>(\n\t\t\t\tcurrent_frame(call_stack), module, flags(immed), offset(immed)\n\t\t\t);\n\t\t\tbreak;\n\t\tcase OpCode::F32_LOAD:\n\t\t\tassert_valid(Tag<memory_immediate_type>{});\n\t\t\tconst auto& immed = raw_immediate().memory_immed;\n\t\t\top_func<OpCode::F32_LOAD>(\n\t\t\t\tcurrent_frame(call_stack), module, flags(immed), offset(immed)\n\t\t\t);\n\t\t\tbreak;\n\t\tcase OpCode::F64_LOAD:\n\t\t\tassert_valid(Tag<memory_immediate_type>{});\n\t\t\tconst auto& immed = raw_immediate().memory_immed;\n\t\t\top_func<OpCode::F64_LOAD>(\n\t\t\t\tcurrent_frame(call_stack), module, flags(immed), offset(immed)\n\t\t\t);\n\t\t\tbreak;\n\t\t// i32 extending loads\n\t\tcase OpCode::I32_LOAD8_S:\n\t\t\tassert_valid(Tag<memory_immediate_type>{});\n\t\t\tconst auto& immed = raw_immediate().memory_immed;\n\t\t\top_func<OpCode::I32_LOAD8_S>(\n\t\t\t\tcurrent_frame(call_stack), module, flags(immed), offset(immed)\n\t\t\t);\n\t\t\tbreak;\n\t\tcase OpCode::I32_LOAD8_U:\n\t\t\tassert_valid(Tag<memory_immediate_type>{});\n\t\t\tconst auto& immed = raw_immediate().memory_immed;\n\t\t\top_func<OpCode::I32_LOAD8_U>(\n\t\t\t\tcurrent_frame(call_stack), module, flags(immed), offset(immed)\n\t\t\t);\n\t\t\tbreak;\n\t\tcase OpCode::I32_LOAD16_S:\n\t\t\tassert_valid(Tag<memory_immediate_type>{});\n\t\t\tconst auto& immed = raw_immediate().memory_immed;\n\t\t\top_func<OpCode::I32_LOAD16_S>(\n\t\t\t\tcurrent_frame(call_stack), module, flags(immed), offset(immed)\n\t\t\t);\n\t\t\tbreak;\n\t\tcase OpCode::I32_LOAD16_U:\n\t\t\tassert_valid(Tag<memory_immediate_type>{});\n\t\t\tconst auto& immed = raw_immediate().memory_immed;\n\t\t\top_func<OpCode::I32_LOAD16_U>(\n\t\t\t\tcurrent_frame(call_stack), module, flags(immed), offset(immed)\n\t\t\t);\n\t\t\tbreak;\n\t\t// i64 extending loads\n\t\tcase OpCode::I64_LOAD8_S:\n\t\t\tassert_valid(Tag<memory_immediate_type>{});\n\t\t\tconst auto& immed = raw_immediate().memory_immed;\n\t\t\top_func<OpCode::I64_LOAD8_S>(\n\t\t\t\tcurrent_frame(call_stack), module, flags(immed), offset(immed)\n\t\t\t);\n\t\t\tbreak;\n\t\tcase OpCode::I64_LOAD8_U:\n\t\t\tassert_valid(Tag<memory_immediate_type>{});\n\t\t\tconst auto& immed = raw_immediate().memory_immed;\n\t\t\top_func<OpCode::I64_LOAD8_U>(\n\t\t\t\tcurrent_frame(call_stack), module, flags(immed), offset(immed)\n\t\t\t);\n\t\t\tbreak;\n\t\tcase OpCode::I64_LOAD16_S:\n\t\t\tassert_valid(Tag<memory_immediate_type>{});\n\t\t\tconst auto& immed = raw_immediate().memory_immed;\n\t\t\top_func<OpCode::I64_LOAD16_S>(\n\t\t\t\tcurrent_frame(call_stack), module, flags(immed), offset(immed)\n\t\t\t);\n\t\t\tbreak;\n\t\tcase OpCode::I64_LOAD16_U:\n\t\t\tassert_valid(Tag<memory_immediate_type>{});\n\t\t\tconst auto& immed = raw_immediate().memory_immed;\n\t\t\top_func<OpCode::I64_LOAD16_U>(\n\t\t\t\tcurrent_frame(call_stack), module, flags(immed), offset(immed)\n\t\t\t);\n\t\t\tbreak;\n\t\tcase OpCode::I64_LOAD32_S:\n\t\t\tassert_valid(Tag<memory_immediate_type>{});\n\t\t\tconst auto& immed = raw_immediate().memory_immed;\n\t\t\top_func<OpCode::I64_LOAD32_S>(\n\t\t\t\tcurrent_frame(call_stack), module, flags(immed), offset(immed)\n\t\t\t);\n\t\t\tbreak;\n\t\tcase OpCode::I64_LOAD32_U:\n\t\t\tassert_valid(Tag<memory_immediate_type>{});\n\t\t\tconst auto& immed = raw_immediate().memory_immed;\n\t\t\top_func<OpCode::I64_LOAD32_U>(\n\t\t\t\tcurrent_frame(call_stack), module, flags(immed), offset(immed)\n\t\t\t);\n\t\t\tbreak;\n\t\t// store\n\t\tcase OpCode::I32_STORE:\n\t\t\tassert_valid(Tag<memory_immediate_type>{});\n\t\t\tconst auto& immed = raw_immediate().memory_immed;\n\t\t\top_func<OpCode::I32_STORE>(\n\t\t\t\tcurrent_frame(call_stack), module, flags(immed), offset(immed)\n\t\t\t);\n\t\t\tbreak;\n\t\tcase OpCode::I64_STORE:\n\t\t\tassert_valid(Tag<memory_immediate_type>{});\n\t\t\tconst auto& immed = raw_immediate().memory_immed;\n\t\t\top_func<OpCode::I64_STORE>(\n\t\t\t\tcurrent_frame(call_stack), module, flags(immed), offset(immed)\n\t\t\t);\n\t\t\tbreak;\n\t\tcase OpCode::F32_STORE:\n\t\t\tassert_valid(Tag<memory_immediate_type>{});\n\t\t\tconst auto& immed = raw_immediate().memory_immed;\n\t\t\top_func<OpCode::F32_STORE>(\n\t\t\t\tcurrent_frame(call_stack), module, flags(immed), offset(immed)\n\t\t\t);\n\t\t\tbreak;\n\t\tcase OpCode::F64_STORE:\n\t\t\tassert_valid(Tag<memory_immediate_type>{});\n\t\t\tconst auto& immed = raw_immediate().memory_immed;\n\t\t\top_func<OpCode::F64_STORE>(\n\t\t\t\tcurrent_frame(call_stack), module, flags(immed), offset(immed)\n\t\t\t);\n\t\t\tbreak;\n\t\t// i32 wrapping stores \n\t\tcase OpCode::I32_STORE8:\n\t\t\tassert_valid(Tag<memory_immediate_type>{});\n\t\t\tconst auto& immed = raw_immediate().memory_immed;\n\t\t\top_func<OpCode::I32_STORE8>(\n\t\t\t\tcurrent_frame(call_stack), module, flags(immed), offset(immed)\n\t\t\t);\n\t\t\tbreak;\n\t\tcase OpCode::I32_STORE16:\n\t\t\tassert_valid(Tag<memory_immediate_type>{});\n\t\t\tconst auto& immed = raw_immediate().memory_immed;\n\t\t\top_func<OpCode::I32_STORE16>(\n\t\t\t\tcurrent_frame(call_stack), module, flags(immed), offset(immed)\n\t\t\t);\n\t\t\tbreak;\n\t\t// i64 wrapping stores \n\t\tcase OpCode::I64_STORE8:\n\t\t\tassert_valid(Tag<memory_immediate_type>{});\n\t\t\tconst auto& immed = raw_immediate().memory_immed;\n\t\t\top_func<OpCode::I64_STORE8>(\n\t\t\t\tcurrent_frame(call_stack), module, flags(immed), offset(immed)\n\t\t\t);\n\t\t\tbreak;\n\t\tcase OpCode::I64_STORE16:\n\t\t\tassert_valid(Tag<memory_immediate_type>{});\n\t\t\tconst auto& immed = raw_immediate().memory_immed;\n\t\t\top_func<OpCode::I64_STORE16>(\n\t\t\t\tcurrent_frame(call_stack), module, flags(immed), offset(immed)\n\t\t\t);\n\t\t\tbreak;\n\t\tcase OpCode::I64_STORE32:\n\t\t\tassert_valid(Tag<memory_immediate_type>{});\n\t\t\tconst auto& immed = raw_immediate().memory_immed;\n\t\t\top_func<OpCode::I64_STORE32>(\n\t\t\t\tcurrent_frame(call_stack), module, flags(immed), offset(immed)\n\t\t\t);\n\t\t\tbreak;\n\t\t// misc\n\t\tcase OpCode::CURRENT_MEMORY:\n\t\t\tassert_valid(Tag<null_immediate_type>{});\n\t\t\top_func<OpCode::CURRENT_MEMORY>(current_frame(call_stack), module);\n\t\t\tbreak;\n\t\tcase OpCode::GROW_MEMORY:\n\t\t\tassert_valid(Tag<null_immediate_type>{});\n\t\t\top_func<OpCode::GROW_MEMORY>(current_frame(call_stack), module);\n\t\t\tbreak;\n\t\t/// CONST OPERATIONS\n\t\tcase OpCode::I32_CONST:\n\t\t\tassert_valid(Tag<i32_immediate_type>{});\n\t\t\top_func<OpCode::I32_CONST>(current_frame(call_stack), raw_immediate().i32_immed);\n\t\t\tbreak;\n\t\tcase OpCode::I64_CONST:\n\t\t\tassert_valid(Tag<i64_immediate_type>{});\n\t\t\top_func<OpCode::I64_CONST>(current_frame(call_stack), raw_immediate().i64_immed);\n\t\t\tbreak;\n\t\tcase OpCode::F32_CONST:\n\t\t\tassert_valid(Tag<f32_immediate_type>{});\n\t\t\top_func<OpCode::F32_CONST>(current_frame(call_stack), raw_immediate().f32_immed);\n\t\t\tbreak;\n\t\tcase OpCode::F64_CONST:\n\t\t\tassert_valid(Tag<f64_immediate_type>{});\n\t\t\top_func<OpCode::F64_CONST>(current_frame(call_stack), raw_immediate().f32_immed);\n\t\t\tbreak;\n\t\t/// COMPARISON OPERATIONS\n\t\t// i32 comparisons\n\t\tcase OpCode::I32_EQZ:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I32_EQZ>(current_frame(call_stack));\n\t\t\tbreak;\n\t\tcase OpCode::I32_EQ:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I32_EQ>(current_frame(call_stack));\n\t\t\tbreak;\n\t\tcase OpCode::I32_NE:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I32_NE>(current_frame(call_stack));\n\t\t\tbreak;\n\t\tcase OpCode::I32_LT_S:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I32_LT_S>(current_frame(call_stack));\n\t\t\tbreak;\n\t\tcase OpCode::I32_LT_U:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I32_LT_U>(current_frame(call_stack));\n\t\t\tbreak;\n\t\tcase OpCode::I32_GT_S:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I32_GT_S>(current_frame(call_stack));\n\t\t\tbreak;\n\t\tcase OpCode::I32_GT_U:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I32_GT_U>(current_frame(call_stack));\n\t\t\tbreak;\n\t\tcase OpCode::I32_LE_S:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I32_LE_S>(current_frame(call_stack));\n\t\t\tbreak;\n\t\tcase OpCode::I32_LE_U:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I32_LE_U>(current_frame(call_stack));\n\t\t\tbreak;\n\t\tcase OpCode::I32_GE_S:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I32_GE_S>(current_frame(call_stack));\n\t\t\tbreak;\n\t\tcase OpCode::I32_GE_U:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I32_GE_U>(current_frame(call_stack));\n\t\t\tbreak;\n\t\t// i64 comparisons\n\t\tcase OpCode::I64_EQZ:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I64_EQZ>(current_frame(call_stack));\n\t\t\tbreak;\n\t\tcase OpCode::I64_EQ:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I64_EQ>(current_frame(call_stack));\n\t\t\tbreak;\n\t\tcase OpCode::I64_NE:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I64_NE>(current_frame(call_stack));\n\t\t\tbreak;\n\t\tcase OpCode::I64_LT_S:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I64_LT_S>(current_frame(call_stack));\n\t\t\tbreak;\n\t\tcase OpCode::I64_LT_U:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I64_LT_U>(current_frame(call_stack));\n\t\t\tbreak;\n\t\tcase OpCode::I64_GT_S:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I64_GT_S>(current_frame(call_stack));\n\t\t\tbreak;\n\t\tcase OpCode::I64_GT_U:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I64_GT_U>(current_frame(call_stack));\n\t\t\tbreak;\n\t\tcase OpCode::I64_LE_S:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I64_LE_S>(current_frame(call_stack));\n\t\t\tbreak;\n\t\tcase OpCode::I64_LE_U:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I64_LE_U>(current_frame(call_stack));\n\t\t\tbreak;\n\t\tcase OpCode::I64_GE_S:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I64_GE_S>(current_frame(call_stack));\n\t\t\tbreak;\n\t\tcase OpCode::I64_GE_U:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I64_GE_U>(current_frame(call_stack));\n\t\t\tbreak;\n\t\t// f32 comparisons\n\t\tcase OpCode::F32_EQ:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F32_EQ>(current_frame(call_stack));\n\t\t\tbreak;\n\t\tcase OpCode::F32_NE:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F32_NE>(current_frame(call_stack));\n\t\t\tbreak;\n\t\tcase OpCode::F32_LT:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F32_LT>(current_frame(call_stack));\n\t\t\tbreak;\n\t\tcase OpCode::F32_GT:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F32_GT>(current_frame(call_stack));\n\t\t\tbreak;\n\t\tcase OpCode::F32_LE:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F32_LE>(current_frame(call_stack));\n\t\t\tbreak;\n\t\tcase OpCode::F32_GE:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F32_GE>(current_frame(call_stack));\n\t\t\tbreak;\n\t\t// f64 comparisons\n\t\tcase OpCode::F64_EQ:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F64_EQ>(current_frame(call_stack));\n\t\t\tbreak;\n\t\tcase OpCode::F64_NE:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F64_NE>(current_frame(call_stack));\n\t\t\tbreak;\n\t\tcase OpCode::F64_LT:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F64_LT>(current_frame(call_stack));\n\t\t\tbreak;\n\t\tcase OpCode::F64_GT:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F64_GT>(current_frame(call_stack));\n\t\t\tbreak;\n\t\tcase OpCode::F64_LE:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F64_LE>(current_frame(call_stack));\n\t\t\tbreak;\n\t\tcase OpCode::F64_GE:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F64_GE>(current_frame(call_stack));\n\t\t\tbreak;\n\t\t/// NUMERIC OPERATIONS\n\t\t// i32 operations\n\t\tcase OpCode::I32_CLZ:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I32_CLZ>();\n\t\t\tbreak;\n\t\tcase OpCode::I32_CTZ:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I32_CTZ>();\n\t\t\tbreak;\n\t\tcase OpCode::I32_POPCNT:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I32_POPCNT>();\n\t\t\tbreak;\n\t\tcase OpCode::I32_ADD:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I32_ADD>();\n\t\t\tbreak;\n\t\tcase OpCode::I32_SUB:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I32_SUB>();\n\t\t\tbreak;\n\t\tcase OpCode::I32_MUL:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I32_MUL>();\n\t\t\tbreak;\n\t\tcase OpCode::I32_DIV_S:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I32_DIV_S>();\n\t\t\tbreak;\n\t\tcase OpCode::I32_DIV_U:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I32_DIV_U>();\n\t\t\tbreak;\n\t\tcase OpCode::I32_REM_S:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I32_REM_S>();\n\t\t\tbreak;\n\t\tcase OpCode::I32_REM_U:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I32_REM_U>();\n\t\t\tbreak;\n\t\tcase OpCode::I32_AND:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I32_AND>();\n\t\t\tbreak;\n\t\tcase OpCode::I32_OR:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I32_OR>();\n\t\t\tbreak;\n\t\tcase OpCode::I32_XOR:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I32_XOR>();\n\t\t\tbreak;\n\t\tcase OpCode::I32_SHL:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I32_SHL>();\n\t\t\tbreak;\n\t\tcase OpCode::I32_SHR_S:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I32_SHR_S>();\n\t\t\tbreak;\n\t\tcase OpCode::I32_SHR_U:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I32_SHR_U>();\n\t\t\tbreak;\n\t\tcase OpCode::I32_ROTL:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I32_ROTL>();\n\t\t\tbreak;\n\t\tcase OpCode::I32_ROTR:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I32_ROTR>();\n\t\t\tbreak;\n\t\t// i64 operations\n\t\tcase OpCode::I64_CLZ:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I64_CLZ>();\n\t\t\tbreak;\n\t\tcase OpCode::I64_CTZ:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I64_CTZ>();\n\t\t\tbreak;\n\t\tcase OpCode::I64_POPCNT:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I64_POPCNT>();\n\t\t\tbreak;\n\t\tcase OpCode::I64_ADD:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I64_ADD>();\n\t\t\tbreak;\n\t\tcase OpCode::I64_SUB:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I64_SUB>();\n\t\t\tbreak;\n\t\tcase OpCode::I64_MUL:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I64_MUL>();\n\t\t\tbreak;\n\t\tcase OpCode::I64_DIV_S:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I64_DIV_S>();\n\t\t\tbreak;\n\t\tcase OpCode::I64_DIV_U:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I64_DIV_U>();\n\t\t\tbreak;\n\t\tcase OpCode::I64_REM_S:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I64_REM_S>();\n\t\t\tbreak;\n\t\tcase OpCode::I64_REM_U:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I64_REM_U>();\n\t\t\tbreak;\n\t\tcase OpCode::I64_AND:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I64_AND>();\n\t\t\tbreak;\n\t\tcase OpCode::I64_OR:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I64_OR>();\n\t\t\tbreak;\n\t\tcase OpCode::I64_XOR:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I64_XOR>();\n\t\t\tbreak;\n\t\tcase OpCode::I64_SHL:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I64_SHL>();\n\t\t\tbreak;\n\t\tcase OpCode::I64_SHR_S:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I64_SHR_S>();\n\t\t\tbreak;\n\t\tcase OpCode::I64_SHR_U:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I64_SHR_U>();\n\t\t\tbreak;\n\t\tcase OpCode::I64_ROTL:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I64_ROTL>();\n\t\t\tbreak;\n\t\tcase OpCode::I64_ROTR:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I64_ROTR>();\n\t\t\tbreak;\n\t\t// f32 operations\n\t\tcase OpCode::F32_ABS:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F32_ABS>();\n\t\t\tbreak;\n\t\tcase OpCode::F32_NEG:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F32_NEG>();\n\t\t\tbreak;\n\t\tcase OpCode::F32_CEIL:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F32_CEIL>();\n\t\t\tbreak;\n\t\tcase OpCode::F32_FLOOR:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F32_FLOOR>();\n\t\t\tbreak;\n\t\tcase OpCode::F32_TRUNC:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F32_TRUNC>();\n\t\t\tbreak;\n\t\tcase OpCode::F32_NEAREST:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F32_NEAREST>();\n\t\t\tbreak;\n\t\tcase OpCode::F32_SQRT:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F32_SQRT>();\n\t\t\tbreak;\n\t\tcase OpCode::F32_ADD:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F32_ADD>();\n\t\t\tbreak;\n\t\tcase OpCode::F32_SUB:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F32_SUB>();\n\t\t\tbreak;\n\t\tcase OpCode::F32_MUL:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F32_MUL>();\n\t\t\tbreak;\n\t\tcase OpCode::F32_DIV:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F32_DIV>();\n\t\t\tbreak;\n\t\tcase OpCode::F32_MIN:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F32_MIN>();\n\t\t\tbreak;\n\t\tcase OpCode::F32_MAX:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F32_MAX>();\n\t\t\tbreak;\n\t\tcase OpCode::F32_COPYSIGN:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F32_COPYSIGN>();\n\t\t\tbreak;\n\t\t// f64 operations\n\t\tcase OpCode::F64_ABS:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F64_ABS>();\n\t\t\tbreak;\n\t\tcase OpCode::F64_NEG:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F64_NEG>();\n\t\t\tbreak;\n\t\tcase OpCode::F64_CEIL:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F64_CEIL>();\n\t\t\tbreak;\n\t\tcase OpCode::F64_FLOOR:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F64_FLOOR>();\n\t\t\tbreak;\n\t\tcase OpCode::F64_TRUNC:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F64_TRUNC>();\n\t\t\tbreak;\n\t\tcase OpCode::F64_NEAREST:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F64_NEAREST>();\n\t\t\tbreak;\n\t\tcase OpCode::F64_SQRT:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F64_SQRT>();\n\t\t\tbreak;\n\t\tcase OpCode::F64_ADD:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F64_ADD>();\n\t\t\tbreak;\n\t\tcase OpCode::F64_SUB:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F64_SUB>();\n\t\t\tbreak;\n\t\tcase OpCode::F64_MUL:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F64_MUL>();\n\t\t\tbreak;\n\t\tcase OpCode::F64_DIV:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F64_DIV>();\n\t\t\tbreak;\n\t\tcase OpCode::F64_MIN:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F64_MIN>();\n\t\t\tbreak;\n\t\tcase OpCode::F64_MAX:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F64_MAX>();\n\t\t\tbreak;\n\t\tcase OpCode::F64_COPYSIGN:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F64_COPYSIGN>();\n\t\t\tbreak;\n\t\t/// CONVERSION OPERATIONS\n\t\tcase OpCode::I32_WRAP_I64:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I32_WRAP_I64>();\n\t\t\tbreak;\n\t\t// float-to-int32 tuncating conversion\n\t\tcase OpCode::I32_TRUNC_S_F32:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I32_TRUNC_S_F32>();\n\t\t\tbreak;\n\t\tcase OpCode::I32_TRUNC_U_F32:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I32_TRUNC_U_F32>();\n\t\t\tbreak;\n\t\tcase OpCode::I32_TRUNC_S_F64:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I32_TRUNC_S_F64>();\n\t\t\tbreak;\n\t\tcase OpCode::I32_TRUNC_U_F64:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I32_TRUNC_U_F64>();\n\t\t\tbreak;\n\t\t// int32-to-int64 extending conversion\n\t\tcase OpCode::I64_EXTEND_S_I32:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I64_EXTEND_S_I32>();\n\t\t\tbreak;\n\t\tcase OpCode::I64_EXTEND_U_I32:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I64_EXTEND_U_I32>();\n\t\t\tbreak;\n\t\t// float-to-int64 truncating conversion\n\t\tcase OpCode::I64_TRUNC_S_F32:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I64_TRUNC_S_F32>();\n\t\t\tbreak;\n\t\tcase OpCode::I64_TRUNC_U_F32:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I64_TRUNC_U_F32>();\n\t\t\tbreak;\n\t\tcase OpCode::I64_TRUNC_S_F64:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I64_TRUNC_S_F64>();\n\t\t\tbreak;\n\t\tcase OpCode::I64_TRUNC_U_F64:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::I64_TRUNC_U_F64>();\n\t\t\tbreak;\n\t\t// int-to-float32 conversion\n\t\tcase OpCode::F32_CONVERT_S_I32:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F32_CONVERT_S_I32>();\n\t\t\tbreak;\n\t\tcase OpCode::F32_CONVERT_U_I32:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F32_CONVERT_U_I32>();\n\t\t\tbreak;\n\t\tcase OpCode::F32_CONVERT_S_I64:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F32_CONVERT_S_I64>();\n\t\t\tbreak;\n\t\tcase OpCode::F32_CONVERT_U_I64:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F32_CONVERT_U_I64>();\n\t\t\tbreak;\n\t\t// float64-to-float32 demoting conversion\n\t\tcase OpCode::F32_DEMOTE_F64:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F32_DEMOTE_F64>();\n\t\t\tbreak;\n\t\t// int-to-float64 conversion\n\t\tcase OpCode::F64_CONVERT_S_I32:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F64_CONVERT_S_I32>();\n\t\t\tbreak;\n\t\tcase OpCode::F64_CONVERT_U_I32:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F64_CONVERT_U_I32>();\n\t\t\tbreak;\n\t\tcase OpCode::F64_CONVERT_S_I64:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F64_CONVERT_S_I64>();\n\t\t\tbreak;\n\t\tcase OpCode::F64_CONVERT_U_I64:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F64_CONVERT_U_I64>();\n\t\t\tbreak;\n\t\t// float32-to-float64 promoting conversion\n\t\tcase OpCode::F64_PROMOTE_F32:\n\t\t\tassert_valid(Tag<null_immediate_tag>{});\n\t\t\top_func<OpCode::F64_PROMOTE_F32>();\n\t\t\tbreak;\n\t\t}\n\t}\n\t\nprivate:\n\t\n\tvoid _assert_invariants() const\n\t{\n\t\tassert(opcode_exists(opcode()));\n\t\tassert(end_pos() > source().data());\n\t\tassert(source().size() > 0u);\n\t\tstd::visit(\n\t\t\t[](const auto& immed) {\n\t\t\t\tusing immed_type = std::decay_t<decltype(immed)>;\n\t\t\t\tassert(validate(Tag<immed_type>{}));\n\t\t\t},\n\t\t\ttagged_immediate()\n\t\t);\n\t\t\n\t}\n\n\tstd::pair<CodeView, const char*> jump_over_if() const\n\t{\n\t\tassert_valid(Tag<block_immediate_type>{});\n\t\tassert(opcode() == OpCode::IF);\n\t\twasm_uint32_t ofs = raw_immediate().block_immed;\n\t\tassert(ofs > 0u);\n\t\tassert(end_pos() > source().data());\n\t\tauto dist = static_cast<std::size_t>(end_pos() - source().data());\n\t\tassert(ofs < dist);\n\t\tauto dest_pos = source().data() + ofs;\n\t\tconstexpr auto end_op = static_cast<unsigned char>(OpCode::END);\n\t\tconstexpr auto else_op = static_cast<unsigned char>(OpCode::ELSE);\n\t\tif(dest_pos[-1] == end_op)\n\t\t{\n\t\t\treturn std::make_pair(CodeView(dest_pos, end_pos()), nullptr);\n\t\t}\n\t\telse \n\t\t{\n\t\t\tassert(dest_pos[-(1 + static_cast<std::ptrdiff_t>(sizeof(ofs)))] == else_op);\n\t\t\tauto else_pos = dest_pos - (1 + static_cast<std::ptrdiff_t>(sizeof(ofs)));\n\t\t\tstd::memcpy(&ofs, else_pos + 1, sizeof(ofs));\n\t\t\treturn std::make_pair(CodeView(dest_pos, end_pos()), else_pos + ofs);\n\t\t}\n\t}\n\n\tCodeView branch_to(const char* pos) const\n\t{\n\t\tassert(pos[-1] == static_cast<char>(OpCode::END));\n\t\tassert(pos > source().data());\n\t\tassert(pos < end_pos());\n\t\treturn CodeView(pos, end_pos());\n\t}\n\n\tCodeView jump_over_else() const\n\t{\n\t\tassert_valid(Tag<offset_immediate_tag>{});\n\t\tassert(opcode() == OpCode::ELSE);\n\t\twasm_uint32_t ofs = raw_immediate().block_immed;\n\t\tassert(ofs > 0u);\n\t\tassert(end_pos() > source().data());\n\t\tauto dist = static_cast<std::size_t>(end_pos() - source().data());\n\t\tassert(ofs < dist);\n\t\tauto dest_pos = source().data() + ofs;\n\t\tassert(dest_pos[-1] == static_cast<char>(OpCode::END));\n\t\treturn CodeView(dest_pos, end_pos());\n\t}\n\n\tusing null_immediate_type         = std::monostate;\n\tusing i32_immediate_type          = wasm_sint32_t;\n\tusing i64_immediate_type          = wasm_sint64_t;\n\tusing f32_immediate_type          = wasm_float32_t;\n\tusing f64_immediate_type          = wasm_float64_t;\n\tusing offset_immediate_type       = wasm_uint32_t;\n\tusing memory_immediate_type       = MemoryImmediate;\n\tusing block_immediate_type        = BlockImmediate;\n\tusing loop_immediate_type         = LanguageType;\n\tusing branch_table_immediate_type = BranchTableImmediate;\n\n\tconst i32_immediate_type& i32_immed() const;\n\tconst i64_immediate_type& i64_immed() const;\n\tconst f32_immediate_type& f32_immed() const;\n\tconst f64_immediate_type& f64_immed() const;\n\tconst offset_immediate_type& offset_immed() const;\n\tconst memory_immediate_type& memory_immed() const;\n\tconst memory_immediate_type& memory_immed() const;\n\n\tconst OpCode& opcode() const\n\t{\n\t\tassert(source_.data().size() > 0u);\n\t\tassert(opcode_exists(source_.data().front()));\n\t\treturn source_.data().front();\n\t}\n\n\n\tstruct LazyImmediate {\n\t\tstd::size_t consumed;\n\t\timmediate_type;\n\t};\n\t/// Code from which this instruction was decoded.\n\tconst CodeView source_;\n\t/// Raw union of possible immediate operand alternatives, discriminated by 'this->opcode'.\n\tstd::optional<const LazyImmediate> immediate_;\n};\n\nstruct CodeView\n{\n\tstruct Iterator;\n\tusing value_type = WasmInstruction;\n\tusing pointer = WasmInstruction*;\n\tusing const_pointer = const WasmInstruction*;\n\tusing reference = WasmInstruction&;\n\tusing const_reference = WasmInstruction&;\n\tusing size_type = std::string_view::size_type;\n\tusing difference_type = std::string_view::difference_type;\n\tusing iterator = Iterator;\n\tusing const_iterator = iterator;\n\nprivate:\n\n\ttemplate <LanguageType LT, LanguageType ... V>\n\tstatic constexpr const bool match_one_of_v\n\t\t= ((LT == V) or ...);\n\n\n\n\tstruct InstructionVisitor {\n\n\t\ttemplate <class ... T>\n\t\tWasmInstruction operator()(\n\t\t\tconst char* first,\n\t\t\tconst char* last,\n\t\t\tconst char* pos,\n\t\t\tOpCode op,\n\t\t\tT&& ... args\n\t\t)\n\t\t{\n\t\t\tassert(first < pos);\n\t\t\tassert(pos <= last);\n\t\t\treturn make_instr(\n\t\t\t\tstd::string_view(first, pos - first),\n\t\t\t\top,\n\t\t\t\tlast,\n\t\t\t\tstd::forward<T>(args)...\n\t\t\t);\n\t\t}\n\n\n\tprivate:\n\t\t\n\t\t\n\t\t// Overload for instructions with immediate operands\n\t\tWasmInstruction make_instr(std::string_view view, OpCode op, const char* last)\n\t\t{ return WasmInstruction(view, op, last, std::monostate()); }\n\n\t\ttemplate <\n\t\t\tclass T,\n\t\t\t/* enable overloads for the simple alternatives. */\n\t\t\tclass = std::enable_if_t<\n\t\t\t\tstd::disjunction_v<\n\t\t\t\t\tstd::is_same_v<std::decay_t<T>, wasm_uint32_t>,\n\t\t\t\t\tstd::is_same_v<std::decay_t<T>, wasm_sint32_t>,\n\t\t\t\t\tstd::is_same_v<std::decay_t<T>, wasm_sint64_t>,\n\t\t\t\t\tstd::is_same_v<std::decay_t<T>, wasm_float32_t>,\n\t\t\t\t\tstd::is_same_v<std::decay_t<T>, wasm_float64_t>\n\t\t\t\t>\n\t\t\t>\n\t\t>\n\t\tWasmInstruction make_instr(std::string_view view, OpCode op, const char* last, T&& arg)\n\t\t{ return WasmInstruction(view, op, last, std::forward<T>(arg)); }\n\n\t\t/// Loop overload\n\t\tWasmInstruction make_instr(std::string_view view, OpCode op, const char* last, LanguageType tp)\n\t\t{ return WasmInstruction(view, op, last, tp); }\n\n\t\t/// Branch table overload\n\t\tWasmInstruction make_instr(std::string_view view, OpCode op, const char* last, const char* base, wasm_uint32_t len)\n\t\t{\n\t\t\tassert(last > base);\n\t\t\tstd::size_t byte_count = base - last;\n\t\t\tstd::size_t bytes_needed = sizeof(wasm_uint32_t) * (len + 1u);\n\t\t\tassert(byte_count >= bytes_needed);\n\t\t\t// the table and 'view' should end at the same byte address\n\t\t\tassert(view.data() + view.size() == (base + (len + 1u) * sizeof(wasm_uint32_t)));\n\t\t\tusing buffer_type = const char[sizeof(wasm_uint32_t)];\n\t\t\tauto table = gsl::span<buffer_type>(reinterpret_cast<buffer_type*>(base), len + 1u);\n\t\t\treturn WasmInstruction(view, op, last, table);\n\t\t}\n\n\t\t/// Block overload\n\t\tWasmInstruction make_instr(std::string_view view, OpCode op, const char* last, LanguageType tp, wasm_uint32_t label)\n\t\t{ return WasmInstruction(view, op, last, BlockImmediate(tp, label)); }\n\n\t\t/// Memory overload\n\t\tWasmInstruction make_instr(std::string_view view, OpCode op, const char* last, wasm_uint32_t flags, wasm_uint32_t offset)\n\t\t{ return WasmInstruction(view, op, last, MemoryImmediate(flags, offset)); }\n\n\t\t/// Invalid opcode overload\n\t\t[[noreturn]]\n\t\tWasmInstruction make_instr(std::string_view, OpCode, const char*, const BadOpCodeError& err)\n\t\t{ throw err; }\n\n\t};\n\npublic:\n\t\n\tstruct Iterator {\n\t\tusing value_type = CodeView::value_type;\n\t\tusing difference_type = CodeView::difference_type;\n\t\tusing pointer = CodeView::pointer;\n\t\tusing reference = CodeView::value_type;\n\t\tusing iterator_category = std::input_iterator_tag;\n\t\t\n\t\tfriend bool operator==(const Iterator& left, const Iterator& right)\n\t\t{ return left.code_ == right.code_; }\n\t\t\n\t\tfriend bool operator!=(const Iterator& left, const Iterator& right)\n\t\t{ return not (left == right); }\n\tprivate:\n\t\tgsl::not_null<CodeView*> code_;\n\t};\n\n\tCodeView(const WasmFunction& func):\n\t\tfunction_(&func),\n\t\tcode_(code(func))\n\t{\n\t\t\n\t}\n\n\tconst WasmFunction* function() const\n\t{ return function_; }\n\n\tOpCode current_op() const\n\t{\n\t\tassert(ready());\n\t\treturn static_cast<WasmInstruction>(code_.front());\n\t}\n\n\tbool done() const\n\t{ return not code_.empty(); }\n\n\tconst char* pos() const\n\t{ return code_.data(); }\n\n\tvoid advance(const CodeView& other)\n\t{\n\t\tassert(function() == other.function());\n\t\tassert(ready());\n\t\tassert(code_.data() + code_.size() == other.code_.data() + other.code_.size());\n\t\tassert(code_.data() < other.code_.data());\n\t\tcode_ = other.code_;\n\t}\n\n\tstd::optional<WasmInstruction> next_instruction() const\n\t{\n\t\tif(code_.size() == 0)\n\t\t\treturn std::nullopt;\n\t\treturn visit_opcode(\n\t\t\topcode(),\n\t\t\t[&](auto opcode) {\n\t\t\t\treturn visit_op_impl(\n\t\t\t\t\t[&](auto first, auto pos, auto last, auto op, auto&& immed) {\n\t\t\t\t\t\treturn WasmInstruction(*this, pos, std::forward<decltype(immed)>(immed));\n\t\t\t\t\t},\n\t\t\t\t\topcode\n\t\t\t\t);\n\t\t\t}\n\t\t);\n\t}\n\n\tstd::optional<CodeView> advance(\n\t\tWasmModule& module,\n\t\tWasmCallStack<T>& call_stack\n\t)\n\t{\n\t\tif(code_.size() == 0)\n\t\t\treturn std::nullopt;\n\t\tauto vis = [&](auto first, auto pos, auto last, auto op, const auto& immed) {\n\t\t\treturn dispatch(call_stack, module, first, pos, last, op, immed);\n\t\t};\n\t}\n\n\tCodeView jump(wasm_uint32_t jump_dist) const\n\t{\n\t\tusing pair_type = std::pair<CodeView, std::optional<CodeView>>;\n\t\tassert(jump_dist > 0u);\n\t\tassert(code_.size() > jump_dist);\n\t\tCodeView dest = *this;\n\t\tdest.code_.remove_prefix(jump_dist);\n\t\treturn dest;\n\t}\n\t\nprivate:\n\ttemplate <class T, OpCode Op, class ImmediateType>\n\tCodeView dispatch(\n\t\tWasmCallStack<T>& call_stack,\n\t\tWasmModule& module,\n\t\tconst char* first,\n\t\tconst char* pos,\n\t\tconst char* last,\n\t\tstd::integral_constant<OpCode, Op> op,\n\t\tconst ImmediateType& immed\n\t)\n\t{\n\t\tauto after = *this;\n\t\tafter.code_.remove_prefix(pos - first);\n\t\treturn op_func<Op>(call_stack, module, *this, after, immed);\n\t}\n\n\ttemplate <class Vis, class T, OpCode Op>\n\tdecltype(auto) visit_op_impl(Vis&& visitor, std::integral_constant<OpCode, Op> op) {\n\t\tauto first = code_.data();\n\t\tauto last = first + code_.size();\n\n\t\tassert(first < last);\n\t\tassert(*first == Op);\n\n\t\tif constexpr(op >= OpCode::I32_LOAD and op <= OpCode::I64_STORE32)\n\t\t{\n\t\t\tauto [flags, offset, pos] = detail::read_memory_immediate(first + 1u, last);\n\t\t\treturn std::invoke(\n\t\t\t\tstd::forward<Vis>(visitor),\n\t\t\t\tfirst, pos, last, op, MemoryImmediateType(flags, offset)\n\t\t\t);\n\t\t}\n\t\telse if constexpr(\n\t\t\t(op >= OpCode::GET_LOCAL and op <= OpCode::SET_GLOBAL)\n\t\t\tor op == OpCode::CALL\n\t\t\tor op == OpCode::CALL_INDIRECT\n\t\t\tor op == OpCode::BR\n\t\t\tor op == OpCode::BR_IF\n\t\t\tor op == OpCode::ELSE\n\t\t)\n\t\t{\n\t\t\tauto [value, pos] = detail::read_serialized_immediate<wasm_uint32_t>(first + 1u, last);\n\t\t\treturn std::invoke(\n\t\t\t\tstd::forward<Vis>(visitor), first, pos, last, op, value\n\t\t\t);\n\t\t}\n\t\telse if constexpr(op == OpCode::BLOCK)\n\t\t{\n\t\t\tauto pos = first + 1u;\n\t\t\tassert(pos < last);\n\t\t\tLanguageType tp = static_cast<LanguageType>(*pos++);\n\t\t\twasm_uint32_t label;\n\t\t\tstd::tie(label, pos) = detail::read_serialized_immediate<wasm_uint32_t>(pos, last);\n\t\t\treturn std::invoke(\n\t\t\t\tstd::forward<Vis>(visitor),\n\t\t\t\tfirst, pos, last, op, BlockImmediate(tp, label)\n\t\t\t);\n\t\t}\n\t\telse if constexpr(op == OpCode::IF)\n\t\t{\n\t\t\tauto pos = first + 1u;\n\t\t\tassert(pos < last);\n\t\t\tLanguageType tp = static_cast<LanguageType>(*pos++);\n\t\t\twasm_uint32_t end_label;\n\t\t\twasm_uint32_t else_label;\n\t\t\tstd::tie(end_label, pos) = detail::read_serialized_immediate<wasm_uint32_t>(pos, last);\n\t\t\tstd::tie(else_label, pos) = detail::read_serialized_immediate<wasm_uint32_t>(pos, last);\n\t\t\treturn std::invoke(\n\t\t\t\tstd::forward<Vis>(visitor),\n\t\t\t\tfirst, pos, last, op, IfImmediate(tp, end_label, else_label)\n\t\t\t);\n\t\t}\n\t\telse if constexpr(op == OpCode::LOOP)\n\t\t{\n\t\t\tauto pos = first + 1u;\n\t\t\tassert(pos < last);\n\t\t\tLanguageType tp = static_cast<LanguageType>(*pos++);\n\t\t\treturn std::invoke(\n\t\t\t\tstd::forward<Vis>(visitor),\n\t\t\t\tfirst, pos, last, op, BlockImmediate(tp, label)\n\t\t\t);\n\t\t}\n\t\telse if constexpr(op == OpCode::BR_TABLE)\n\t\t{\n\t\t\twasm_uint32_t len;\n\t\t\tstd::tie(len, pos) = detail::read_serialized_immediate<wasm_uint32_t>(pos, last);\n\t\t\tauto table_base = pos;\n\t\t\tauto table_size = (1u + len);\n\t\t\tassert(last - pos > table_size);\n\t\t\tstd::advance(pos, table_size * sizeof(wasm_uint32_t));\n\t\t\tusing table_elem_type = const char[sizeof(wasm_uint32_t)];\n\t\t\tauto table = gsl::span<table_elem_type>(\n\t\t\t\treinterpret_cast<table_elem_type*>(table_base),\n\t\t\t\ttable_size\n\t\t\t);\n\t\t\treturn std::invoke(\n\t\t\t\tstd::forward<Vis>(visitor),\n\t\t\t\tfirst, pos, last, op, table\n\t\t\t);\n\t\t}\n\t\telse if constexpr(Op == OpCode::I32_CONST)\n\t\t{\n\t\t\tauto [v, pos] = detail::read_serialized_immediate<wasm_sint32_t>(first + 1u, last);\n\t\t\treturn std::invoke(\n\t\t\t\tstd::forward<Vis>(visitor),\n\t\t\t\tfirst, pos, last, op, table\n\t\t\t);\n\t\t}\n\t\telse if constexpr(Op == OpCode::I64_CONST)\n\t\t{\n\t\t\tauto [v, pos] = detail::read_serialized_immediate<wasm_sint64_t>(first + 1u, last);\n\t\t\treturn std::invoke(\n\t\t\t\tstd::forward<Vis>(visitor),\n\t\t\t\tfirst, pos, last, op, table\n\t\t\t);\n\t\t}\n\t\telse if constexpr(Op == OpCode::F32_CONST)\n\t\t{\n\t\t\tauto [v, pos] = detail::read_serialized_immediate<wasm_float32_t>(first + 1u, last);\n\t\t\treturn std::invoke(\n\t\t\t\tstd::forward<Vis>(visitor),\n\t\t\t\tfirst, pos, last, op, table\n\t\t\t);\n\t\t}\n\t\telse if constexpr(Op == OpCode::F64_CONST)\n\t\t{\n\t\t\tauto [v, pos] = detail::read_serialized_immediate<wasm_float64_t>(first + 1u, last);\n\t\t\treturn std::invoke(\n\t\t\t\tstd::forward<Vis>(visitor),\n\t\t\t\tfirst, pos, last, op, table\n\t\t\t);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tassert(opcode_exists(Op));\n\t\t\treturn std::invoke(\n\t\t\t\tstd::forward<Vis>(visitor),\n\t\t\t\tfirst, pos, last, op, std::monostate{}\n\t\t\t);\n\t\t}\n\t}\n \n\tbool ready() const\n\t{\n\t\tif(done())\n\t\t\treturn false;\n\t\tassert(opcode_exists(code_.front()));\n\t\treturn true;\n\t}\n\n\tconst WasmFunction* function_;\n\tstd::string_view code_;\n};\n\n\n} /* namespace opc */\n} /* namespace wasm */\n\n\n\n\n\n#endif /* WASM_INSTRUCTION_H */\n", "meta": {"hexsha": "5a6a27cdd1d2e69aae453730dd1a9071d370df11", "size": 95361, "ext": "h", "lang": "C", "max_stars_repo_path": "include/WasmInstruction.h", "max_stars_repo_name": "tvanslyke/wasm-cpp", "max_stars_repo_head_hexsha": "8a56c1706e2723ece36e3642bae9e36792dbd7b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/WasmInstruction.h", "max_issues_repo_name": "tvanslyke/wasm-cpp", "max_issues_repo_head_hexsha": "8a56c1706e2723ece36e3642bae9e36792dbd7b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/WasmInstruction.h", "max_forks_repo_name": "tvanslyke/wasm-cpp", "max_forks_repo_head_hexsha": "8a56c1706e2723ece36e3642bae9e36792dbd7b2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.9310474755, "max_line_length": 123, "alphanum_fraction": 0.6868845755, "num_tokens": 29444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618332444286, "lm_q2_score": 0.0255652143408834, "lm_q1q2_score": 0.011587735919435566}}
{"text": "/* matrix/gsl_matrix_complex_long_double.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_MATRIX_COMPLEX_LONG_DOUBLE_H__\n#define __GSL_MATRIX_COMPLEX_LONG_DOUBLE_H__\n\n#if !defined( GSL_FUN )\n#  if !defined( GSL_DLL )\n#    define GSL_FUN extern\n#  elif defined( BUILD_GSL_DLL )\n#    define GSL_FUN extern __declspec(dllexport)\n#  else\n#    define GSL_FUN extern __declspec(dllimport)\n#  endif\n#endif\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_complex.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_vector_complex_long_double.h>\n#include <gsl/gsl_blas_types.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size1;\n  size_t size2;\n  size_t tda;\n  long double * data;\n  gsl_block_complex_long_double * block;\n  int owner;\n} gsl_matrix_complex_long_double ;\n\ntypedef struct\n{\n  gsl_matrix_complex_long_double matrix;\n} _gsl_matrix_complex_long_double_view;\n\ntypedef _gsl_matrix_complex_long_double_view gsl_matrix_complex_long_double_view;\n\ntypedef struct\n{\n  gsl_matrix_complex_long_double matrix;\n} _gsl_matrix_complex_long_double_const_view;\n\ntypedef const _gsl_matrix_complex_long_double_const_view gsl_matrix_complex_long_double_const_view;\n\n\n/* Allocation */\n\nGSL_FUN gsl_matrix_complex_long_double * \ngsl_matrix_complex_long_double_alloc (const size_t n1, const size_t n2);\n\nGSL_FUN gsl_matrix_complex_long_double * \ngsl_matrix_complex_long_double_calloc (const size_t n1, const size_t n2);\n\nGSL_FUN gsl_matrix_complex_long_double * \ngsl_matrix_complex_long_double_alloc_from_block (gsl_block_complex_long_double * b, \n                                           const size_t offset, \n                                           const size_t n1, const size_t n2, const size_t d2);\n\nGSL_FUN gsl_matrix_complex_long_double * \ngsl_matrix_complex_long_double_alloc_from_matrix (gsl_matrix_complex_long_double * b,\n                                            const size_t k1, const size_t k2,\n                                            const size_t n1, const size_t n2);\n\nGSL_FUN gsl_vector_complex_long_double * \ngsl_vector_complex_long_double_alloc_row_from_matrix (gsl_matrix_complex_long_double * m,\n                                                const size_t i);\n\nGSL_FUN gsl_vector_complex_long_double * \ngsl_vector_complex_long_double_alloc_col_from_matrix (gsl_matrix_complex_long_double * m,\n                                                const size_t j);\n\nGSL_FUN void gsl_matrix_complex_long_double_free (gsl_matrix_complex_long_double * m);\n\n/* Views */\n\nGSL_FUN _gsl_matrix_complex_long_double_view \ngsl_matrix_complex_long_double_submatrix (gsl_matrix_complex_long_double * m, \n                            const size_t i, const size_t j, \n                            const size_t n1, const size_t n2);\n\nGSL_FUN _gsl_vector_complex_long_double_view \ngsl_matrix_complex_long_double_row (gsl_matrix_complex_long_double * m, const size_t i);\n\nGSL_FUN _gsl_vector_complex_long_double_view \ngsl_matrix_complex_long_double_column (gsl_matrix_complex_long_double * m, const size_t j);\n\nGSL_FUN _gsl_vector_complex_long_double_view \ngsl_matrix_complex_long_double_diagonal (gsl_matrix_complex_long_double * m);\n\nGSL_FUN _gsl_vector_complex_long_double_view \ngsl_matrix_complex_long_double_subdiagonal (gsl_matrix_complex_long_double * m, const size_t k);\n\nGSL_FUN _gsl_vector_complex_long_double_view \ngsl_matrix_complex_long_double_superdiagonal (gsl_matrix_complex_long_double * m, const size_t k);\n\nGSL_FUN _gsl_vector_complex_long_double_view\ngsl_matrix_complex_long_double_subrow (gsl_matrix_complex_long_double * m,\n                                 const size_t i, const size_t offset,\n                                 const size_t n);\n\nGSL_FUN _gsl_vector_complex_long_double_view\ngsl_matrix_complex_long_double_subcolumn (gsl_matrix_complex_long_double * m,\n                                    const size_t j, const size_t offset,\n                                    const size_t n);\n\nGSL_FUN _gsl_matrix_complex_long_double_view\ngsl_matrix_complex_long_double_view_array (long double * base,\n                             const size_t n1, \n                             const size_t n2);\n\nGSL_FUN _gsl_matrix_complex_long_double_view\ngsl_matrix_complex_long_double_view_array_with_tda (long double * base, \n                                      const size_t n1, \n                                      const size_t n2,\n                                      const size_t tda);\n\nGSL_FUN _gsl_matrix_complex_long_double_view\ngsl_matrix_complex_long_double_view_vector (gsl_vector_complex_long_double * v,\n                              const size_t n1, \n                              const size_t n2);\n\nGSL_FUN _gsl_matrix_complex_long_double_view\ngsl_matrix_complex_long_double_view_vector_with_tda (gsl_vector_complex_long_double * v,\n                                       const size_t n1, \n                                       const size_t n2,\n                                       const size_t tda);\n\n\nGSL_FUN _gsl_matrix_complex_long_double_const_view \ngsl_matrix_complex_long_double_const_submatrix (const gsl_matrix_complex_long_double * m, \n                                  const size_t i, const size_t j, \n                                  const size_t n1, const size_t n2);\n\nGSL_FUN _gsl_vector_complex_long_double_const_view \ngsl_matrix_complex_long_double_const_row (const gsl_matrix_complex_long_double * m, \n                            const size_t i);\n\nGSL_FUN _gsl_vector_complex_long_double_const_view \ngsl_matrix_complex_long_double_const_column (const gsl_matrix_complex_long_double * m, \n                               const size_t j);\n\nGSL_FUN _gsl_vector_complex_long_double_const_view\ngsl_matrix_complex_long_double_const_diagonal (const gsl_matrix_complex_long_double * m);\n\nGSL_FUN _gsl_vector_complex_long_double_const_view \ngsl_matrix_complex_long_double_const_subdiagonal (const gsl_matrix_complex_long_double * m, \n                                    const size_t k);\n\nGSL_FUN _gsl_vector_complex_long_double_const_view \ngsl_matrix_complex_long_double_const_superdiagonal (const gsl_matrix_complex_long_double * m, \n                                      const size_t k);\n\nGSL_FUN _gsl_vector_complex_long_double_const_view\ngsl_matrix_complex_long_double_const_subrow (const gsl_matrix_complex_long_double * m,\n                                       const size_t i, const size_t offset,\n                                       const size_t n);\n\nGSL_FUN _gsl_vector_complex_long_double_const_view\ngsl_matrix_complex_long_double_const_subcolumn (const gsl_matrix_complex_long_double * m,\n                                          const size_t j, const size_t offset,\n                                          const size_t n);\n\nGSL_FUN _gsl_matrix_complex_long_double_const_view\ngsl_matrix_complex_long_double_const_view_array (const long double * base,\n                                   const size_t n1, \n                                   const size_t n2);\n\nGSL_FUN _gsl_matrix_complex_long_double_const_view\ngsl_matrix_complex_long_double_const_view_array_with_tda (const long double * base, \n                                            const size_t n1, \n                                            const size_t n2,\n                                            const size_t tda);\n\nGSL_FUN _gsl_matrix_complex_long_double_const_view\ngsl_matrix_complex_long_double_const_view_vector (const gsl_vector_complex_long_double * v,\n                                    const size_t n1, \n                                    const size_t n2);\n\nGSL_FUN _gsl_matrix_complex_long_double_const_view\ngsl_matrix_complex_long_double_const_view_vector_with_tda (const gsl_vector_complex_long_double * v,\n                                             const size_t n1, \n                                             const size_t n2,\n                                             const size_t tda);\n\n/* Operations */\n\nGSL_FUN void gsl_matrix_complex_long_double_set_zero (gsl_matrix_complex_long_double * m);\nGSL_FUN void gsl_matrix_complex_long_double_set_identity (gsl_matrix_complex_long_double * m);\nGSL_FUN void gsl_matrix_complex_long_double_set_all (gsl_matrix_complex_long_double * m, gsl_complex_long_double x);\n\nGSL_FUN int gsl_matrix_complex_long_double_fread (FILE * stream, gsl_matrix_complex_long_double * m) ;\nGSL_FUN int gsl_matrix_complex_long_double_fwrite (FILE * stream, const gsl_matrix_complex_long_double * m) ;\nGSL_FUN int gsl_matrix_complex_long_double_fscanf (FILE * stream, gsl_matrix_complex_long_double * m);\nGSL_FUN int gsl_matrix_complex_long_double_fprintf (FILE * stream, const gsl_matrix_complex_long_double * m, const char * format);\n\nGSL_FUN int gsl_matrix_complex_long_double_memcpy(gsl_matrix_complex_long_double * dest, const gsl_matrix_complex_long_double * src);\nGSL_FUN int gsl_matrix_complex_long_double_swap(gsl_matrix_complex_long_double * m1, gsl_matrix_complex_long_double * m2);\nGSL_FUN int gsl_matrix_complex_long_double_tricpy(CBLAS_UPLO_t Uplo, CBLAS_DIAG_t Diag, gsl_matrix_complex_long_double * dest, const gsl_matrix_complex_long_double * src);\n\nGSL_FUN int gsl_matrix_complex_long_double_swap_rows(gsl_matrix_complex_long_double * m, const size_t i, const size_t j);\nGSL_FUN int gsl_matrix_complex_long_double_swap_columns(gsl_matrix_complex_long_double * m, const size_t i, const size_t j);\nGSL_FUN int gsl_matrix_complex_long_double_swap_rowcol(gsl_matrix_complex_long_double * m, const size_t i, const size_t j);\n\nGSL_FUN int gsl_matrix_complex_long_double_transpose (gsl_matrix_complex_long_double * m);\nGSL_FUN int gsl_matrix_complex_long_double_transpose_memcpy (gsl_matrix_complex_long_double * dest, const gsl_matrix_complex_long_double * src);\nGSL_FUN int gsl_matrix_complex_long_double_transpose_tricpy(CBLAS_UPLO_t Uplo_src, CBLAS_DIAG_t Diag, gsl_matrix_complex_long_double * dest, const gsl_matrix_complex_long_double * src);\n\nGSL_FUN int gsl_matrix_complex_long_double_conjtrans_memcpy (gsl_matrix_complex_long_double * dest, const gsl_matrix_complex_long_double * src);\n\nGSL_FUN int gsl_matrix_complex_long_double_equal (const gsl_matrix_complex_long_double * a, const gsl_matrix_complex_long_double * b);\n\nGSL_FUN int gsl_matrix_complex_long_double_isnull (const gsl_matrix_complex_long_double * m);\nGSL_FUN int gsl_matrix_complex_long_double_ispos (const gsl_matrix_complex_long_double * m);\nGSL_FUN int gsl_matrix_complex_long_double_isneg (const gsl_matrix_complex_long_double * m);\nGSL_FUN int gsl_matrix_complex_long_double_isnonneg (const gsl_matrix_complex_long_double * m);\n\nGSL_FUN int gsl_matrix_complex_long_double_add (gsl_matrix_complex_long_double * a, const gsl_matrix_complex_long_double * b);\nGSL_FUN int gsl_matrix_complex_long_double_sub (gsl_matrix_complex_long_double * a, const gsl_matrix_complex_long_double * b);\nGSL_FUN int gsl_matrix_complex_long_double_mul_elements (gsl_matrix_complex_long_double * a, const gsl_matrix_complex_long_double * b);\nGSL_FUN int gsl_matrix_complex_long_double_div_elements (gsl_matrix_complex_long_double * a, const gsl_matrix_complex_long_double * b);\nGSL_FUN int gsl_matrix_complex_long_double_scale (gsl_matrix_complex_long_double * a, const gsl_complex_long_double x);\nGSL_FUN int gsl_matrix_complex_long_double_scale_rows (gsl_matrix_complex_long_double * a, const gsl_vector_complex_long_double * x);\nGSL_FUN int gsl_matrix_complex_long_double_scale_columns (gsl_matrix_complex_long_double * a, const gsl_vector_complex_long_double * x);\nGSL_FUN int gsl_matrix_complex_long_double_add_constant (gsl_matrix_complex_long_double * a, const gsl_complex_long_double x);\nGSL_FUN int gsl_matrix_complex_long_double_add_diagonal (gsl_matrix_complex_long_double * a, const gsl_complex_long_double x);\n\n/***********************************************************************/\n/* The functions below are obsolete                                    */\n/***********************************************************************/\nGSL_FUN int gsl_matrix_complex_long_double_get_row(gsl_vector_complex_long_double * v, const gsl_matrix_complex_long_double * m, const size_t i);\nGSL_FUN int gsl_matrix_complex_long_double_get_col(gsl_vector_complex_long_double * v, const gsl_matrix_complex_long_double * m, const size_t j);\nGSL_FUN int gsl_matrix_complex_long_double_set_row(gsl_matrix_complex_long_double * m, const size_t i, const gsl_vector_complex_long_double * v);\nGSL_FUN int gsl_matrix_complex_long_double_set_col(gsl_matrix_complex_long_double * m, const size_t j, const gsl_vector_complex_long_double * v);\n/***********************************************************************/\n\n/* inline functions if you are using GCC */\n\nGSL_FUN INLINE_DECL gsl_complex_long_double gsl_matrix_complex_long_double_get(const gsl_matrix_complex_long_double * m, const size_t i, const size_t j);\nGSL_FUN INLINE_DECL void gsl_matrix_complex_long_double_set(gsl_matrix_complex_long_double * m, const size_t i, const size_t j, const gsl_complex_long_double x);\n\nGSL_FUN INLINE_DECL gsl_complex_long_double * gsl_matrix_complex_long_double_ptr(gsl_matrix_complex_long_double * m, const size_t i, const size_t j);\nGSL_FUN INLINE_DECL const gsl_complex_long_double * gsl_matrix_complex_long_double_const_ptr(const gsl_matrix_complex_long_double * m, const size_t i, const size_t j);\n\n#ifdef HAVE_INLINE\n\nINLINE_FUN \ngsl_complex_long_double\ngsl_matrix_complex_long_double_get(const gsl_matrix_complex_long_double * m, \n                     const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      gsl_complex_long_double zero = {{0,0}};\n\n      if (i >= m->size1)\n        {\n          GSL_ERROR_VAL(\"first index out of range\", GSL_EINVAL, zero) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_VAL(\"second index out of range\", GSL_EINVAL, zero) ;\n        }\n    }\n#endif\n  return *(gsl_complex_long_double *)(m->data + 2*(i * m->tda + j)) ;\n} \n\nINLINE_FUN \nvoid\ngsl_matrix_complex_long_double_set(gsl_matrix_complex_long_double * m, \n                     const size_t i, const size_t j, const gsl_complex_long_double x)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_VOID(\"first index out of range\", GSL_EINVAL) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_VOID(\"second index out of range\", GSL_EINVAL) ;\n        }\n    }\n#endif\n  *(gsl_complex_long_double *)(m->data + 2*(i * m->tda + j)) = x ;\n}\n\nINLINE_FUN \ngsl_complex_long_double *\ngsl_matrix_complex_long_double_ptr(gsl_matrix_complex_long_double * m, \n                             const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n        }\n    }\n#endif\n  return (gsl_complex_long_double *)(m->data + 2*(i * m->tda + j)) ;\n} \n\nINLINE_FUN \nconst gsl_complex_long_double *\ngsl_matrix_complex_long_double_const_ptr(const gsl_matrix_complex_long_double * m, \n                                   const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n        }\n    }\n#endif\n  return (const gsl_complex_long_double *)(m->data + 2*(i * m->tda + j)) ;\n} \n\n#endif /* HAVE_INLINE */\n\n__END_DECLS\n\n#endif /* __GSL_MATRIX_COMPLEX_LONG_DOUBLE_H__ */\n", "meta": {"hexsha": "79212ab8e6a0e2203c5289c88ff6fc6d99f322d5", "size": 16592, "ext": "h", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_matrix_complex_long_double.h", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_matrix_complex_long_double.h", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_matrix_complex_long_double.h", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.9647696477, "max_line_length": 185, "alphanum_fraction": 0.7220347155, "num_tokens": 3702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632157796989345, "lm_q2_score": 0.027169233308022084, "lm_q1q2_score": 0.011582830416108164}}
{"text": "/*\nCopyright (c) 2015, Patrick Weltevrede\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n#include <stdio.h>\n#include <math.h>\n#include <string.h>\n#include <stdlib.h>\n#include <gsl/gsl_sort.h>\n#include \"psrsalsa.h\"\nint main(int argc, char **argv)\n{\n  int read_log, centered_at_zero, file_column1, file_column2, colspecified, polspecified, filename, truncate, cdf, select;\n  long ndata, i, j, k, nrbins, nrbinsy, *distr;\n  float *cmap, *distr_float;\n  double *data_x, *data_y, min_x_data, max_x_data, min_y_data, max_y_data;\n  double min_x, max_x, min_y, max_y, dx, dy, x, y, s, rangex_min, rangex_max, rangey_min, rangey_max, extra_phase, select1, select2;\n  int nrbins_specified, dx_specified, dy_specified, output_sigma, output_fraction, nrbins_specifiedy, twoDmode, showGraphics, rangex_set, rangey_set, plotlog, file_column2_defined, xlabelset, linewidth;\n  char title[500], *filename_ptr, output_suffix[100], *oname;\n  FILE *ofile;\n  double min, max;\n  psrsalsaApplication application;\n  datafile_definition datain;\n  pgplot_options_definition pgplot_options;\n  pgplot_clear_options(&pgplot_options);\n  initApplication(&application, \"pdist\", \"[options] inputfile(s)\");\n  application.switch_verbose = 1;\n  application.switch_debug = 1;\n  application.switch_iformat = 1;\n  application.switch_formatlist = 1;\n  application.switch_device = 1;\n  application.switch_cmap = 1;\n  application.switch_cmaplist = 1;\n  nrbins_specified = 0;\n  nrbins_specifiedy = 0;\n  dx_specified = 0;\n  dy_specified = 0;\n  output_sigma = 0;\n  output_fraction = 0;\n  read_log = 0;\n  twoDmode = 0;\n  centered_at_zero = 1;\n  extra_phase = 0;\n  showGraphics = 0;\n  xlabelset = 0;\n  sprintf(title, \"Distribution\");\n  rangex_set = 0;\n  rangey_set = 0;\n  file_column1 = 1;\n  file_column2 = 2;\n  colspecified = 0;\n  polspecified = 0;\n  plotlog = 0;\n  file_column2_defined = 1;\n  application.cmap = PPGPLOT_HEAT;\n  strcpy(output_suffix, \"hist\");\n  filename = 0;\n  truncate = 0;\n  cdf = 0;\n  select = 0;\n  linewidth = 1;\n  if(argc < 2) {\n    printf(\"Program to generate or plot a histogram by binning data. Also a cummulative\\n\");\n    printf(\"distribution can be generated. Usage:\\n\\n\");\n    printApplicationHelp(&application);\n    printf(\"Input options:\\n\");\n    printf(\"-2               Turn on 2D mode: Read in two columns of data, resulting in the\\n\");\n    printf(\"                 distribution N(x,y) rathern than N(x).\\n\");\n    printf(\"-col \\\"c1 c2\\\"     Specify two column numbers (counting from 1) to be used.\\n\");\n    printf(\"                 Without the -2 option only one value needs to be specified.\\n\");\n    printf(\"                 This option implies the input files are ascii files with each\\n\");\n    printf(\"                 line having an equal number of columns. Lines starting with a #\\n\");\n    printf(\"                 will be ignored.\\n\");\n    printf(\"-pol \\\"p1 p2\\\"     This option implies that the input file is recognized as a\\n\");\n    printf(\"                 pulsar format. Polarization p1 (and p2 in 2D mode), counting\\n\");\n    printf(\"                 from zero, are used (all bins, freqs and subints). The default\\n\");\n    printf(\"                 default is \\\"0 1\\\", or the integrated onpulse pulse energy for\\n\");\n    printf(\"                 penergy output files in mode 1.\\n\");\n    printf(\"\\nOutput options:\\n\");\n    printf(\"-ext             Specify suffix, default is '%s'\\n\", output_suffix);\n    printf(\"-output filename Write output to this file [def=.%s extension].\\n\", output_suffix);\n    printf(\"-frac            Output fraction of counts per bin rather than counts.\\n\");\n    printf(\"-sigma           Generate extra column with the sqrt of the nr of counts.\\n\");\n    printf(\"\\nDistribution options:\\n\");\n    printf(\"-cdf             The cummulative distribution is generated. Use no -dx or -n.\\n\");\n    printf(\"-dx value        Specify bin width (can also use -n).\\n\");\n    printf(\"-dy value        Specify bin width used for the second column if -2 is used.\\n\");\n    printf(\"-log             The base-10 log of the input values is used.\\n\");\n    printf(\"-n nr            The range of input values is divided in nr bins.\\n\");\n    printf(\"-nx nr           Same as -n\\n\");\n    printf(\"-ny nr           Similar to -nx, but now for the second column if -2 is used.\\n\");\n    printf(\"-rangex \\\"x1 x2\\\"  The range of bins produced in output will cover x1..x2, which\\n\");\n    printf(\"                 should include all input values (see also -trunc). It therefore\\n\");\n    printf(\"                 allows more bins to be generated than strictly necessary.\\n\");\n    printf(\"-rangey          As -rangex, but now for second input column.\\n\");\n    printf(\"-select \\\"v1 v2\\\"  Enabling this option will no longer result in a distribution.\\n\");\n    printf(\"                 Instead all samples within the range of values specified with\\n\");\n    printf(\"                 v1 and v2 will be outputted as two columns: the sample number\\n\");\n    printf(\"                 and the value.\\n\");\n    printf(\"-trunc           Modifies behaviour of -rangex and -rangey. Values outside the\\n\");\n    printf(\"                 specified range are set to the extremes of the range.\\n\");\n    printf(\"-zero            By default one of the bins will be centred at zero. This option\\n\");\n    printf(\"                 results in the edge of a bin to coincides with zero. In both\\n\");\n    printf(\"                 cases the reported locations of the bins are their centres.\\n\");\n    printf(\"                 This means that in gnuplot you want to use \\\"with histeps\\\".\\n\");\n    printf(\"-zeroshift off   Put in an extra offset off to where zero would fall with\\n\");\n    printf(\"                 respect to a bin. -zero is equivalent to -zeroshift 0.5. \\n\");\n    printf(\"\\nPlot options:\\n\");\n    printf(\"-plot            Plot the distribution rather than writing output to file.\\n\");\n    printf(\"-plotlog         The log10 of the counts is plotted (implies -plot and bins with\\n\");\n    printf(\"                 zero counts are set to 1).\\n\");\n    printf(\"-overplot        Like plot, but multiple input files are overplotted. The ranges\\n\");\n    printf(\"                 are determined by first input file.\\n\");\n    printf(\"-title  'title'  Set the title of the plot.\\n\");\n    printf(\"-xlabel 'label'  Set label on horizontal axis.\\n\");\n    printf(\"-labels           \\\"label_ch label_lw label_f box_ch box_lw box_f\\\"\\n\");\n    printf(\"                  default is \\\"%.1f %d %d %.1f %d %d\\\"\\n\", pgplot_options.box.label_ch, pgplot_options.box.label_lw, pgplot_options.box.label_f, pgplot_options.box.box_labelsize, pgplot_options.box.box_lw, pgplot_options.box.box_f);\n    printf(\"-lw              Set line width of the histogram.\\n\");\n    printf(\"-vp              \\\"left right bottom top\\\"\\n\");\n    printf(\"                 Modify the dimensions of the plot. Default is \\\"%.2f %.2f %.2f %.2f\\\"\\n\", pgplot_options.viewport.dxplot, pgplot_options.viewport.xsize, pgplot_options.viewport.dyplot, pgplot_options.viewport.ysize);\n    printf(\"\\n\");\n    printf(\"Please use the appropriate citation when using results of this software in your publications:\\n\\n\");\n    printf(\"More information about fitting distributions (in the context of pulse energies) can be found in:\\n\");\n    printf(\" - Weltevrede et al. 2006, A&A, 458, 269\\n\\n\");\n    printCitationInfo();\n    terminateApplication(&application);\n    return 0;\n  }else {\n    for(i = 1; i < argc; i++) {\n      int index;\n      index = i;\n      if(processCommandLine(&application, argc, argv, &index)) {\n i = index;\n      }else if(strcmp(argv[i], \"-2\") == 0) {\n twoDmode = 1;\n      }else if(strcmp(argv[i], \"-plot\") == 0) {\n showGraphics = 1;\n      }else if(strcmp(argv[i], \"-overplot\") == 0) {\n showGraphics = 2;\n      }else if(strcmp(argv[i], \"-plotlog\") == 0) {\n plotlog = 1;\n if(showGraphics == 0)\n   showGraphics = 1;\n      }else if(strcmp(argv[i], \"-xlabel\") == 0) {\n xlabelset = i+1;\n i++;\n      }else if(strcmp(argv[i], \"-title\") == 0) {\n strcpy(title, argv[i+1]);\n i++;\n      }else if(strcmp(argv[i], \"-output\") == 0) {\n filename = i+1;\n i++;\n      }else if(strcmp(argv[i], \"-ext\") == 0) {\n strcpy(output_suffix, argv[i+1]);\n i++;\n      }else if(strcmp(argv[i], \"-labels\") == 0) {\n if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, \"%f %d %d %f %d %d\", &(pgplot_options.box.label_ch), &(pgplot_options.box.label_lw), &(pgplot_options.box.label_f), &(pgplot_options.box.box_labelsize), &(pgplot_options.box.box_lw), &(pgplot_options.box.box_f), NULL) == 0) {\n   printerror(application.verbose_state.debug, \"ERROR pdist: Cannot parse '%s' option.\", argv[i]);\n   return 0;\n }\n i++;\n      }else if(strcmp(argv[i], \"-lw\") == 0) {\n if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, \"%d\", &linewidth, NULL) == 0) {\n   printerror(application.verbose_state.debug, \"ERROR pdist: Cannot parse '%s' option.\", argv[i]);\n   return 0;\n }\n i++;\n      }else if(strcmp(argv[i], \"-vp\") == 0) {\n if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, \"%f %f %f %f\", &(pgplot_options.viewport.dxplot), &(pgplot_options.viewport.xsize), &(pgplot_options.viewport.dyplot), &(pgplot_options.viewport.ysize), NULL) == 0) {\n   printerror(application.verbose_state.debug, \"ERROR pdist: Cannot parse '%s' option.\", argv[i]);\n   return 0;\n }\n i++;\n      }else if(strcmp(argv[i], \"-col\") == 0 || strcmp(argv[i], \"-pol\") == 0) {\n if(strcmp(argv[i], \"-pol\") == 0)\n   polspecified = 1;\n else\n   colspecified = 1;\n int ret;\n ret = parse_command_string(application.verbose_state, argc, argv, i+1, 0, 1, \"%d %d\", &file_column1, &file_column2, NULL);\n file_column2_defined = 0;\n if(ret == 2) {\n   file_column2_defined = 1;\n }else if(ret == 0) {\n   printerror(application.verbose_state.debug, \"ERROR pdist: Cannot parse %s option, need 1 or 2 integer values.\\n\", argv[i]);\n   return 0;\n }\n i++;\n      }else if(strcmp(argv[i], \"-n\") == 0 || strcmp(argv[i], \"-nx\") == 0) {\n if(dx_specified) {\n   printerror(application.verbose_state.debug, \"Cannot use -n and -dx option simultaniously.\\n\");\n   return 0;\n }\n nrbins_specified = 1;\n if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, \"%ld\", &nrbins, NULL) == 0) {\n   printerror(application.verbose_state.debug, \"ERROR pdist: Cannot parse '%s' option.\", argv[i]);\n   return 0;\n }\n i++;\n      }else if(strcmp(argv[i], \"-ny\") == 0) {\n if(dy_specified) {\n   printerror(application.verbose_state.debug, \"Cannot use -ny and -dy option simultaniously.\\n\");\n   return 0;\n }\n nrbins_specifiedy = 1;\n if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, \"%ld\", &nrbinsy, NULL) == 0) {\n   printerror(application.verbose_state.debug, \"ERROR pdist: Cannot parse '%s' option.\", argv[i]);\n   return 0;\n }\n i++;\n      }else if(strcmp(argv[i], \"-dx\") == 0) {\n if(nrbins_specified) {\n   printerror(application.verbose_state.debug, \"Cannot use -n and -dx option simultaniously.\\n\");\n   return 0;\n }\n dx_specified = 1;\n if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, \"%lf\", &dx, NULL) == 0) {\n   printerror(application.verbose_state.debug, \"ERROR pdist: Cannot parse '%s' option.\", argv[i]);\n   return 0;\n }\n i++;\n      }else if(strcmp(argv[i], \"-dy\") == 0) {\n if(nrbins_specifiedy) {\n   printerror(application.verbose_state.debug, \"Cannot use -ny and -dy option simultaniously.\\n\");\n   return 0;\n }\n dy_specified = 1;\n if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, \"%lf\", &dy, NULL) == 0) {\n   printerror(application.verbose_state.debug, \"ERROR pdist: Cannot parse '%s' option.\", argv[i]);\n   return 0;\n }\n i++;\n      }else if(strcmp(argv[i], \"-rangex\") == 0) {\n rangex_set = 1;\n if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, \"%lf %lf\", &rangex_min, &rangex_max, NULL) == 0) {\n   printerror(application.verbose_state.debug, \"ERROR pdist: Cannot parse '%s' option.\", argv[i]);\n   return 0;\n }\n i++;\n      }else if(strcmp(argv[i], \"-rangey\") == 0) {\n rangey_set = 1;\n if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, \"%lf %lf\", &rangey_min, &rangey_max, NULL) == 0) {\n   printerror(application.verbose_state.debug, \"ERROR pdist: Cannot parse '%s' option.\", argv[i]);\n   return 0;\n }\n i++;\n      }else if(strcmp(argv[i], \"-select\") == 0) {\n select = 1;\n if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, \"%lf %lf\", &select1, &select2, NULL) == 0) {\n   printerror(application.verbose_state.debug, \"ERROR pdist: Cannot parse '%s' option.\", argv[i]);\n   return 0;\n }\n i++;\n      }else if(strcmp(argv[i], \"-trunc\") == 0) {\n truncate = 1;\n      }else if(strcmp(argv[i], \"-sigma\") == 0) {\n output_sigma = 1;\n      }else if(strcmp(argv[i], \"-log\") == 0) {\n read_log = 1;\n      }else if(strcmp(argv[i], \"-zero\") == 0) {\n centered_at_zero = 0;\n      }else if(strcmp(argv[i], \"-zeroshift\") == 0) {\n if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, \"%lf\", &extra_phase, NULL) == 0) {\n   printerror(application.verbose_state.debug, \"ERROR pdist: Cannot parse '%s' option.\", argv[i]);\n   return 0;\n }\n i++;\n      }else if(strcmp(argv[i], \"-frac\") == 0) {\n output_fraction = 1;\n      }else if(strcmp(argv[i], \"-cdf\") == 0) {\n cdf = 1;\n      }else {\n if(argv[i][0] == '-') {\n   printerror(application.verbose_state.debug, \"pdist: Unknown option: %s\\n\\nRun pdist without command line arguments to show help\", argv[i]);\n   terminateApplication(&application);\n   return 0;\n }else {\n   if(applicationAddFilename(i, application.verbose_state) == 0)\n     return 0;\n }\n      }\n    }\n  }\n  if(applicationFilenameList_checkConsecutive(argv, application.verbose_state) == 0) {\n    return 0;\n  }\n  if(numberInApplicationFilenameList(&application, argv, application.verbose_state) == 0) {\n    printerror(application.verbose_state.debug, \"ERROR pdist: No files specified\");\n    return 0;\n  }\n  if(select) {\n    if(twoDmode) {\n      printerror(application.verbose_state.debug, \"ERROR pdist: The -2 option cannot be used with -select.\\n\");\n      return 0;\n    }\n    if(cdf) {\n      printerror(application.verbose_state.debug, \"ERROR pdist: The -cdf option cannot be used with -select.\\n\");\n      return 0;\n    }\n    if(showGraphics) {\n      printerror(application.verbose_state.debug, \"ERROR pdist: No plots can be generated when using -select.\\n\");\n      return 0;\n    }\n    if(output_fraction) {\n      printerror(application.verbose_state.debug, \"ERROR pdist: The -frac option cannot be used with -select.\\n\");\n      return 0;\n    }\n    if(output_sigma) {\n      printerror(application.verbose_state.debug, \"ERROR pdist: The -sigma option cannot be used with -select.\\n\");\n      return 0;\n    }\n  }\n  if(cdf) {\n    if(nrbins_specified || dx_specified) {\n      printerror(application.verbose_state.debug, \"ERROR pdist: For a cdf -n and -dx should not be used.\\n\");\n      return 0;\n    }\n    if(twoDmode) {\n      printerror(application.verbose_state.debug, \"ERROR pdist: For a cdf only one input column is expected.\\n\");\n      return 0;\n    }\n    if(output_sigma) {\n      printerror(application.verbose_state.debug, \"ERROR pdist: For a cdf -sigma is not supported.\\n\");\n      return 0;\n    }\n    if(rangex_set || rangey_set || truncate) {\n      printerror(application.verbose_state.debug, \"ERROR pdist: For a cdf the -rangex and -rangey options are not supported.\\n\");\n      return 0;\n    }\n  }else {\n    if(select == 0) {\n      if(nrbins_specified == 0 && dx_specified == 0) {\n printerror(application.verbose_state.debug, \"ERROR pdist: Specify resolution with the -n or -dx option.\\n\");\n return 0;\n      }\n      if(twoDmode) {\n if(nrbins_specifiedy == 0 && dy_specified == 0) {\n printerror(application.verbose_state.debug, \"ERROR pdist: Specify resolution with the -ny or -dy option.\\n\");\n return 0;\n }\n      }\n    }\n  }\n  int initial_iformat, currentfile;\n  currentfile = 1;\n  initial_iformat = application.iformat;\n  while((filename_ptr = getNextFilenameFromList(&application, argv, application.verbose_state)) != NULL) {\n    application.iformat = initial_iformat;\n    if(application.iformat <= 0 && colspecified == 0) {\n      application.iformat = guessPSRData_format(filename_ptr, 1, application.verbose_state);\n      if(application.iformat == -2 || application.iformat == -3)\n return 0;\n    }\n    if(colspecified)\n      application.iformat = -1;\n    if(polspecified && application.iformat <= 0) {\n      printerror(application.verbose_state.debug, \"ERROR pdist: Input file cannot be opened. Please check if file %s exists and otherwise specify the correct input format with the -iformat option if the format is supported, but not automatically recognized. Data is not recognized as pulsar data, but -pol was used. Use -col for ascii files.\\n\", filename_ptr);\n      return 0;\n    }\n    if(application.iformat > 0) {\n      verbose_definition verbose;\n      cleanVerboseState(&verbose);\n      copyVerboseState(application.verbose_state, &verbose);\n      if(application.iformat == PSRCHIVE_ASCII_format) {\n if(verbose.debug == 0)\n   verbose.verbose = 0;\n      }\n      i = openPSRData(&datain, filename_ptr, application.iformat, 0, 1, 1, verbose);\n      if(i == 0) {\n printerror(application.verbose_state.debug, \"ERROR pdist: Error opening data\");\n return 0;\n      }\n      if(polspecified == 0) {\n file_column1 = 0;\n file_column2 = 1;\n      }\n      if(application.iformat == PSRCHIVE_ASCII_format && datain.gentype == GENTYPE_PENERGY) {\n if(application.verbose_state.verbose)\n   printf(\"The file is a penergy file generated in mode 1.\\n\");\n if(polspecified == 0) {\n   printwarning(application.verbose_state.debug, \"WARNING pdist: -pol not specified, default in the integrated on-pulse energy (-pol 2)\");\n   file_column1 = 2;\n }\n      }\n      if(application.verbose_state.verbose)\n printf(\"Loading %ld points\", datain.NrSubints*datain.NrFreqChan*datain.NrBins);\n      if(twoDmode)\n printf(\" times two input polarizations\");\n      printf(\"\\n\");\n      data_x = malloc(datain.NrSubints*datain.NrFreqChan*datain.NrBins*sizeof(double));\n      data_y = malloc(datain.NrSubints*datain.NrFreqChan*datain.NrBins*sizeof(double));\n      if(data_x == NULL || data_y == NULL) {\n printerror(application.verbose_state.debug, \"ERROR pdist: Memory allocation error.\\n\");\n return 0;\n      }\n      long subintnr, freqnr, binnr;\n      long double total_x, total_y;\n      ndata = 0;\n      total_x = 0;\n      total_y = 0;\n      min_x_data = max_x_data = 0;\n      for(subintnr = 0; subintnr < datain.NrSubints; subintnr++) {\n for(freqnr = 0; freqnr < datain.NrFreqChan; freqnr++) {\n   for(binnr = 0; binnr < datain.NrBins; binnr++) {\n     float dummy_float;\n     if(readPulsePSRData(&datain, subintnr, file_column1, freqnr, binnr, 1, &dummy_float, application.verbose_state) == 0) {\n       printerror(application.verbose_state.debug, \"ERROR pdist: Read error, shouldn't happen.\\n\");\n       return 0;\n     }\n     data_x[ndata] = dummy_float;\n     if(read_log) {\n       if(data_x[ndata] <= 0) {\n  printerror(application.verbose_state.debug, \"ERROR pdist: Cannot take logarithm of a value <= 0.\\n\");\n  return 0;\n       }\n       data_x[ndata] = log10(data_x[ndata]);\n     }\n     if(data_x[ndata] > max_x_data || ndata == 0) {\n       max_x_data = data_x[ndata];\n     }\n     if(data_x[ndata] < min_x_data || ndata == 0) {\n       min_x_data = data_x[ndata];\n     }\n     total_x += data_x[ndata];\n     if(twoDmode) {\n       if(readPulsePSRData(&datain, subintnr, file_column2, freqnr, binnr, 1, &dummy_float, application.verbose_state) == 0) {\n  printerror(application.verbose_state.debug, \"ERROR pdist: Read error, shouldn't happen.\\n\");\n  return 0;\n       }\n       data_y[ndata] = dummy_float;\n       if(read_log) {\n  if(data_y[ndata] <= 0) {\n    printerror(application.verbose_state.debug, \"ERROR pdist: Cannot take logarithm of a value <= 0.\\n\");\n    return 0;\n  }\n  data_y[ndata] = log10(data_y[ndata]);\n       }\n       if(ndata == 0) {\n  max_y_data = data_y[ndata];\n  min_y_data = data_y[ndata];\n       }\n       if(data_y[ndata] > max_y_data) {\n  max_y_data = data_y[ndata];\n       }\n       if(data_y[ndata] < min_y_data) {\n  min_y_data = data_y[ndata];\n       }\n       total_y += data_y[ndata];\n     }\n     ndata++;\n   }\n }\n      }\n      if(application.verbose_state.verbose) {\n printf(\"xrange = %e ... %e\\n\", min_x_data, max_x_data);\n printf(\"average = %Le\\n\", total_x/(long double)ndata);\n if(twoDmode) {\n   printf(\"yrange = %e ... %e\\n\", min_y_data, max_y_data);\n   printf(\"average = %Le\\n\", total_y/(long double)ndata);\n }\n      }\n      closePSRData(&datain, 0, application.verbose_state);\n    }else {\n      int skiplines = 0;\n      if(twoDmode) {\n if(application.verbose_state.verbose)\n   fprintf(stdout, \"Loading x values from ascii file\\n\");\n if(read_ascii_column_double(filename_ptr, skiplines, '#', -1, 1, &ndata, file_column1, 1.0, read_log, &data_x, &min_x_data, &max_x_data, NULL, application.verbose_state, 1) == 0) {\n   printerror(application.verbose_state.debug, \"ERROR pdist: cannot load file.\\n\");\n   if(colspecified) {\n     printwarning(application.verbose_state.debug, \"WARNING pdist: Using the -col option implies the input file is a simple ascii file. For penergy output (in mode 1), or an other recognized pulsar format, use the -pol option instead.\\n\");\n   }\n   return 0;\n }\n if(application.verbose_state.verbose)\n   fprintf(stdout, \"Loading y values from ascii file\\n\");\n if(file_column2_defined == 0) {\n   printerror(application.verbose_state.debug, \"In 2D mode, two input columns should be specified with the -col option.\\n\");\n   return 0;\n }\n if(read_ascii_column_double(filename_ptr, skiplines, '#', -1, 1, &ndata, file_column2, 1.0, read_log, &data_y, &min_y_data, &max_y_data, NULL, application.verbose_state, 1) == 0) {\n   printerror(application.verbose_state.debug, \"ERROR pdist: cannot load file.\\n\");\n   if(colspecified) {\n     printwarning(application.verbose_state.debug, \"WARNING pdist: Using the -col option implies the input file is a simple ascii file. For penergy output (in mode 1), or an other recognized pulsar format, use the -pol option instead.\\n\");\n   }\n   return 0;\n }\n      }else {\n if(application.verbose_state.verbose)\n   fprintf(stdout, \"Loading values from ascii file\\n\");\n if(read_ascii_column_double(filename_ptr, skiplines, '#', -1, 1, &ndata, file_column1, 1.0, read_log, &data_x, &min_x_data, &max_x_data, NULL, application.verbose_state, 1) == 0) {\n   printerror(application.verbose_state.debug, \"ERROR pdist: cannot load file.\\n\");\n   if(colspecified) {\n     printwarning(application.verbose_state.debug, \"WARNING pdist: Using the -col option implies the input file is a simple ascii file. For penergy output (in mode 1), or an other recognized pulsar format, use the -pol option instead.\\n\");\n   }\n   return 0;\n }\n data_y = malloc(ndata*sizeof(double));\n if(data_y == NULL) {\n   printerror(application.verbose_state.debug, \"ERROR pdist: Memory allocation error.\\n\");\n   return 0;\n }\n      }\n    }\n    if(cdf == 0 && select == 0) {\n      switch(set_binning_histogram(min_x_data, max_x_data, rangex_set, rangex_min, rangex_max, nrbins_specified, nrbins, centered_at_zero, extra_phase, &min_x, &max_x, &dx, application.verbose_state)) {\n      case 0: break;\n      case 1:\n      case 2: return 0;\n      default: {\n printerror(application.verbose_state.debug, \"ERROR pdist: Unknown return value for call to set_binning_histogram.\\n\");\n return 0;\n      }\n      }\n      if(rangex_set) {\n if(min_x > min_x_data || max_x < max_x_data) {\n   if(truncate == 0) {\n     printerror(application.verbose_state.debug, \"ERROR pdist: Values are outside specified -rangex option. You may want to use -trunc?\\n\");\n     return 0;\n   }\n }\n      }\n      if(twoDmode) {\n switch(set_binning_histogram(min_y_data, max_y_data, rangey_set, rangey_min, rangey_max, nrbins_specifiedy, nrbinsy, centered_at_zero, extra_phase, &min_y, &max_y, &dy, application.verbose_state)) {\n case 0: break;\n case 1:\n case 2: return 0;\n default: {\n   printerror(application.verbose_state.debug, \"ERROR pdist: Unknown return value for call to set_binning_histogram.\\n\");\n   return 0;\n }\n }\n if(application.verbose_state.verbose) {\n   fprintf(stdout, \"Going to use binsize dx=%e and dy=%e.\\n\", dx, dy);\n }\n      }\n      if(rangey_set) {\n if(min_y > min_y_data || max_y < max_y_data) {\n   if(truncate == 0) {\n     printerror(application.verbose_state.debug, \"ERROR pdist: Values are outside specified -rangey option. You may want to use -trunc?\\n\");\n     return 0;\n   }\n }\n      }\n    }\n    if(cdf == 0) {\n      if(truncate) {\n if(rangex_set) {\n   for(i = 0; i < ndata; i++) {\n     if(data_x[i] < min_x)\n       data_x[i] = min_x;\n     if(data_x[i] > max_x)\n       data_x[i] = max_x;\n   }\n }\n if(rangey_set) {\n   for(i = 0; i < ndata; i++) {\n     if(data_y[i] < min_y)\n       data_y[i] = min_y;\n     if(data_y[i] > max_y)\n       data_y[i] = max_y;\n   }\n }\n      }\n    }\n    if(cdf == 0 && select == 0)\n      nrbins = calculate_bin_number(max_x, dx, min_x, centered_at_zero, extra_phase) + 1;\n    else\n      nrbins = ndata;\n    if(select == 0)\n      fprintf(stdout, \"Distribution will have %ld bins.\\n\", nrbins);\n    if(twoDmode) {\n      nrbinsy = calculate_bin_number(max_y, dy, min_y, centered_at_zero, extra_phase)+ 1;\n      fprintf(stdout, \"Distribution will have %ld y-bins.\\n\", nrbinsy);\n    }else {\n      nrbinsy = 1;\n    }\n    distr = (long *)malloc(nrbins*nrbinsy*sizeof(long));\n    if(distr == NULL) {\n      printerror(application.verbose_state.debug, \"ERROR pdist: Cannot allocate memory.\\n\");\n      return 0;\n    }\n    for(i = 0; i < nrbins*nrbinsy; i++)\n      distr[i] = 0;\n    if(showGraphics) {\n      pgplot_options.box.drawtitle = 1;\n      strcpy(pgplot_options.box.title, title);\n      if(xlabelset) {\n strcpy(pgplot_options.box.xlabel, argv[xlabelset]);\n      }else {\n if(read_log)\n   strcpy(pgplot_options.box.xlabel, \"log X\");\n else\n   strcpy(pgplot_options.box.xlabel, \"X\");\n      }\n      if(twoDmode) {\n if(read_log)\n   strcpy(pgplot_options.box.ylabel, \"log Y\");\n else\n   strcpy(pgplot_options.box.ylabel, \"Y\");\n      }else {\n if(plotlog)\n   strcpy(pgplot_options.box.ylabel, \"log N\");\n else\n   strcpy(pgplot_options.box.ylabel, \"N\");\n      }\n      strcpy(pgplot_options.viewport.plotDevice, application.pgplotdevice);\n      if(showGraphics == 2) {\n pgplot_options.viewport.dontclose = 1;\n      }\n      if(currentfile > 1 && showGraphics == 2) {\n pgplot_options.viewport.noclear = 1;\n pgplot_options.viewport.dontopen = 1;\n pgplot_options.box.drawbox = 0;\n pgplot_options.box.drawtitle = 0;\n pgplot_options.box.drawlabels = 0;\n      }\n    }else {\n      if(filename != 0) {\n oname = (char *) calloc(strlen(argv[filename])+1, 1);\n      }else {\n oname = (char *) calloc(strlen(filename_ptr)+strlen(output_suffix)+2, 1);\n      }\n      if(oname == NULL) {\n printerror(application.verbose_state.debug, \"ERROR pdist: Memory allocation error.\\n\");\n return 0;\n      }\n      if(filename != 0) {\n strcpy(oname, argv[filename]);\n      }else {\n sprintf(oname,\"%s.%s\", filename_ptr, output_suffix);\n      }\n      printf(\"Output Ascii to %s\\n\",oname);\n      ofile = fopen(oname,\"w+\");\n      if(ofile == NULL) {\n printerror(application.verbose_state.debug, \"ERROR pdist: Cannot open '%s'\", oname);\n perror(\"\");\n return 0;\n      }\n    }\n    if(twoDmode) {\n      for(i = 0; i < ndata; i++) {\n j = calculate_bin_number(data_x[i], dx, min_x, centered_at_zero, extra_phase);\n k = calculate_bin_number(data_y[i], dy, min_y, centered_at_zero, extra_phase);\n if(j < 0 || j >= nrbins) {\n   printerror(application.verbose_state.debug, \"BUG!\\n\");\n   return 0;\n }\n if(k < 0 || k >= nrbinsy) {\n   printerror(application.verbose_state.debug, \"BUG!\\n\");\n   return 0;\n }\n distr[k*nrbins+j] += 1;\n      }\n      for(i = 0; i < nrbins; i++) {\n for(j = 0; j < nrbinsy; j++) {\n   x = calculate_bin_location(i, dx, min_x, centered_at_zero, extra_phase);\n   y = calculate_bin_location(j, dy, min_y, centered_at_zero, extra_phase);\n   if(!showGraphics) {\n       fprintf(ofile, \"%e %e\", x, y);\n     if(!output_fraction)\n       fprintf(ofile, \" %ld\", distr[j*nrbins+i]);\n     else\n       fprintf(ofile, \" %e\", distr[j*nrbins+i]/(double)ndata);\n     if(output_sigma) {\n       if(distr[j*nrbins+i] == 0)\n  s = 1;\n       else\n  s = sqrt(distr[j*nrbins+i]);\n       if(output_fraction)\n  s /= (double)ndata;\n  fprintf(ofile, \" %e\", s);\n     }\n   }\n   if(!showGraphics) {\n     fprintf(ofile, \"\\n\");\n   }\n }\n      }\n      if(showGraphics) {\n cmap = (float *)malloc(nrbins*nrbinsy*sizeof(float));\n if(cmap == NULL) {\n   printerror(application.verbose_state.debug, \"Cannot allocate memory.\\n\");\n   return 0;\n }\n if(plotlog) {\n   if(distr[0] > 0) {\n     min = log10(distr[0]);\n     max = log10(distr[0]);\n   }else {\n     min = max = 0;\n   }\n }else {\n   min = distr[0];\n   max = distr[0];\n }\n for(i = 0; i < nrbins; i++) {\n   for(j = 0; j <nrbinsy; j++) {\n     if(plotlog) {\n       if(distr[i*nrbinsy+j] > 0)\n  cmap[i*nrbinsy+j] = log10(distr[i*nrbinsy+j]);\n       else\n  cmap[i*nrbinsy+j] = 0;\n     }\n     else\n       cmap[i*nrbinsy+j] = distr[i*nrbinsy+j];\n     if(cmap[i*nrbinsy+j] > max)\n       max = cmap[i*nrbinsy+j];\n     if(cmap[i*nrbinsy+j] < min)\n       min = cmap[i*nrbinsy+j];\n   }\n }\n printf(\"Count range: %f to %f\\n\", min, max);\n int showwedge = 0;\n if(pgplotMap(&pgplot_options, cmap, nrbins, nrbinsy,\n       calculate_bin_location(0, dx, min_x, centered_at_zero, extra_phase),\n       calculate_bin_location(0, dx, max_x, centered_at_zero, extra_phase),\n       calculate_bin_location(0, dx, min_x, centered_at_zero, extra_phase)-0.5*dx,\n       calculate_bin_location(0, dx, max_x, centered_at_zero, extra_phase)+0.5*dx,\n       calculate_bin_location(0, dy, min_y, centered_at_zero, extra_phase),\n       calculate_bin_location(0, dy, max_y, centered_at_zero, extra_phase),\n       calculate_bin_location(0, dy, min_y, centered_at_zero, extra_phase)-0.5*dy,\n       calculate_bin_location(0, dy, max_y, centered_at_zero, extra_phase)+0.5*dy,\n       application.cmap, 0, 0, 0, NULL, 0, 0, 1.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, showwedge, 0, 0, application.verbose_state) == 0) {\n   printerror(application.verbose_state.debug, \"ERROR pdist: Plotting failed.\\n\");\n   return 0;\n }\n free(cmap);\n      }\n    }else {\n      if(select) {\n nrbins = 0;\n for(i = 0; i < ndata; i++) {\n   if(data_x[i] >= select1 && data_x[i] <= select2) {\n     nrbins++;\n   }\n }\n j = 0;\n for(i = 0; i < ndata; i++) {\n   if(data_x[i] >= select1 && data_x[i] <= select2) {\n     distr[j] = i;\n     data_y[j] = data_x[i];\n     j++;\n   }\n }\n      }else {\n if(cdf == 0) {\n   for(i = 0; i < ndata; i++) {\n     j = calculate_bin_number(data_x[i], dx, min_x, centered_at_zero, extra_phase);\n     if(j < 0 || j >= nrbins) {\n       printerror(application.verbose_state.debug, \"BUG! bin number %ld outside range.\\n\", j);\n       exit(0);\n     }\n     distr[j] += 1;\n   }\n }else {\n   gsl_sort(data_x, 1, ndata);\n   for(i = 0; i < ndata; i++) {\n     data_y[i] = (i+1)/(double)(ndata);\n   }\n }\n      }\n      if(!showGraphics) {\n for(i = 0; i < nrbins; i++) {\n   x = i*dx;\n     if(cdf == 0) {\n       if(select == 0) {\n  fprintf(ofile, \"%e\", calculate_bin_location(i, dx, min_x, centered_at_zero, extra_phase));\n       }else {\n  fprintf(ofile, \"%ld\", distr[i]);\n       }\n     }else {\n       fprintf(ofile, \"%e\", data_x[i]);\n     }\n   if(!output_fraction) {\n       if(cdf == 0) {\n  if(select == 0) {\n    fprintf(ofile, \" %ld\", distr[i]);\n  }else {\n    fprintf(ofile, \" %e\", data_y[i]);\n  }\n       }else {\n  fprintf(ofile, \" %e\", data_y[i]);\n       }\n   }else {\n       if(cdf == 0) {\n  fprintf(ofile, \" %e\", distr[i]/(double)ndata);\n       }else {\n  fprintf(ofile, \" %e\", data_y[i]);\n       }\n   }\n   if(output_sigma) {\n     if(distr[i] == 0)\n       s = 1;\n     else\n       s = sqrt(distr[i]);\n     if(output_fraction)\n       s /= (double)ndata;\n     fprintf(ofile, \" %e\", s);\n   }\n   fprintf(ofile, \"\\n\");\n }\n      }else {\n float *distr_x_float;\n distr_float = malloc(nrbins*sizeof(float));\n if(distr_float == NULL) {\n   printerror(application.verbose_state.debug, \"ERROR pdist: Cannot allocate memory\\n\");\n   return 0;\n }\n if(cdf == 0) {\n   for(i = 0; i < nrbins; i++) {\n     distr_float[i] = distr[i];\n     if(output_fraction)\n       distr_float[i] /= (double)ndata;\n     if(plotlog) {\n       if(distr[i] > 0) {\n  distr_float[i] = log10(distr_float[i]);\n       }else {\n  if(output_fraction) {\n    distr_float[i] = log10(1.0/(float)ndata);\n  }else {\n    distr_float[i] = 0;\n  }\n       }\n     }\n   }\n }else {\n   distr_x_float = malloc(nrbins*sizeof(float));\n   if(distr_x_float == NULL) {\n     printerror(application.verbose_state.debug, \"ERROR pdist: Cannot allocate memory\\n\");\n     return 0;\n   }\n   for(i = 0; i < nrbins; i++) {\n     distr_float[i] = data_y[i];\n     distr_x_float[i] = data_x[i];\n   }\n }\n int forceMinZero, dontsetranges, colour;\n forceMinZero = 1;\n if(plotlog)\n   forceMinZero = 0;\n dontsetranges = 0;\n colour = 1;\n if(showGraphics == 2) {\n   if(currentfile > 1)\n     dontsetranges = 1;\n   colour = currentfile;\n }\n if(cdf == 0) {\n   if(pgplotGraph1(&pgplot_options, distr_float, NULL, NULL, nrbins,\n     calculate_bin_location(0, dx, min_x, centered_at_zero, extra_phase),\n     calculate_bin_location(nrbins-1, dx, min_x, centered_at_zero, extra_phase),\n     dontsetranges,\n     calculate_bin_location(0, dx, min_x, centered_at_zero, extra_phase) - dx,\n     calculate_bin_location(nrbins-1, dx, min_x, centered_at_zero, extra_phase) + dx,\n     0, 0, forceMinZero, 1, 0, linewidth, 0, colour, 1, NULL, -1, application.verbose_state) == 0) {\n     printerror(application.verbose_state.debug, \"ERROR pdist: Cannot plot graph\\n\");\n     return 0;\n   }\n }else {\n   if(pgplotGraph1(&pgplot_options, distr_float, distr_x_float, NULL, nrbins,\n     0,\n     0,\n     dontsetranges,\n     0,\n     0,\n     0, 0, forceMinZero, 1*0, 0, linewidth, 0, colour, 1, NULL, -1, application.verbose_state) == 0) {\n     printerror(application.verbose_state.debug, \"ERROR pdist: Cannot plot graph\\n\");\n     return 0;\n   }\n   free(distr_x_float);\n }\n free(distr_float);\n      }\n    }\n    free(data_x);\n    free(data_y);\n    free(distr);\n    if(showGraphics == 0) {\n      fclose(ofile);\n      free(oname);\n    }\n    if(showGraphics == 1) {\n      if(currentfile != numberInApplicationFilenameList(&application, argv, application.verbose_state)) {\n i = pgplot_device_type(application.pgplotdevice, application.verbose_state);\n if(i < 3 || i > 10) {\n   printf(\"Press a key to continue\\n\");\n   fflush(stdout);\n   pgetch();\n }\n      }\n    }\n    currentfile += 1;\n  }\n  if(showGraphics == 2) {\n    ppgend();\n  }\n  terminateApplication(&application);\n  return 0;\n}\n", "meta": {"hexsha": "31f0ad265cd5b1a5ecf2e926704a3cffcd624b44", "size": 35926, "ext": "c", "lang": "C", "max_stars_repo_path": "src/prog/pdist.c", "max_stars_repo_name": "David-McKenna/psrsalsa", "max_stars_repo_head_hexsha": "e5074b552d1c404123dee058d5cee79ea230b5a9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/prog/pdist.c", "max_issues_repo_name": "David-McKenna/psrsalsa", "max_issues_repo_head_hexsha": "e5074b552d1c404123dee058d5cee79ea230b5a9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/prog/pdist.c", "max_forks_repo_name": "David-McKenna/psrsalsa", "max_forks_repo_head_hexsha": "e5074b552d1c404123dee058d5cee79ea230b5a9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.3925438596, "max_line_length": 755, "alphanum_fraction": 0.6419306352, "num_tokens": 10204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.023330766177010947, "lm_q1q2_score": 0.011574249137243966}}
{"text": "/* histogram/ntuple.h\n * \n * Copyright (C) 2000 Simone Piccardi\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\n */\n\n/* Jan/2001 Modified by Brian Gough. Minor changes for GSL */\n\n#ifndef __GSL_NTUPLE_H__\n#define __GSL_NTUPLE_H__\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_histogram.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct {\n    FILE * file;\n    void * ntuple_data;\n    size_t size;\n} gsl_ntuple;\n\ntypedef struct {\n  int (* function) (void * ntuple_data, void * params);\n  void * params;\n} gsl_ntuple_select_fn;\n\ntypedef struct {\n  double (* function) (void * ntuple_data, void * params);\n  void * params;\n} gsl_ntuple_value_fn;\n\ngsl_ntuple * \ngsl_ntuple_open (char * filename, void * ntuple_data, size_t size);\n\ngsl_ntuple * \ngsl_ntuple_create (char * filename, void * ntuple_data, size_t size);\n\nint gsl_ntuple_write (gsl_ntuple * ntuple);\nint gsl_ntuple_read (gsl_ntuple * ntuple);\n\nint gsl_ntuple_bookdata (gsl_ntuple * ntuple);  /* synonym for write */\n\nint gsl_ntuple_project (gsl_histogram * h, gsl_ntuple * ntuple, \n                        gsl_ntuple_value_fn *value_func,\n                        gsl_ntuple_select_fn *select_func);\n\nint gsl_ntuple_close (gsl_ntuple * ntuple);\n\n__END_DECLS\n\n#endif /* __GSL_NTUPLE_H__ */\n\n\n\n\n", "meta": {"hexsha": "14789a4c85e3193746c6433c66148302a50c97e0", "size": 2149, "ext": "h", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/ntuple/gsl_ntuple.h", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/ntuple/gsl_ntuple.h", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/ntuple/gsl_ntuple.h", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 25.8915662651, "max_line_length": 81, "alphanum_fraction": 0.721265705, "num_tokens": 561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3242353989809524, "lm_q2_score": 0.035678554851026084, "lm_q1q2_score": 0.011568250467186236}}
{"text": "#ifndef ARRUS_CORE_DEVICES_TXRXPARAMETERS_H\n#define ARRUS_CORE_DEVICES_TXRXPARAMETERS_H\n\n#include <gsl/gsl>\n#include <utility>\n#include <ostream>\n\n#include \"arrus/core/api/common/Interval.h\"\n#include \"arrus/core/api/common/Tuple.h\"\n#include \"arrus/core/api/common/types.h\"\n#include \"arrus/common/format.h\"\n#include \"arrus/core/common/collections.h\"\n#include \"arrus/core/api/ops/us4r/Pulse.h\"\n\nnamespace arrus::devices {\n\nclass TxRxParameters {\npublic:\n    static const TxRxParameters US4OEM_NOP;\n\n    static TxRxParameters createRxNOPCopy(const TxRxParameters& op) {\n        return TxRxParameters(\n            op.txAperture,\n            op.txDelays,\n            op.txPulse,\n            BitMask(op.rxAperture.size(), false),\n            op.rxSampleRange,\n            op.rxDecimationFactor,\n            op.pri,\n            op.rxPadding\n        );\n    }\n\n    /**\n     *\n     * ** tx aperture, tx delays and rx aperture should have the same size\n     * (tx delays is NOT limited to the tx aperture active elements -\n     * the whole array must be provided).**\n     *\n     * @param txAperture\n     * @param txDelays\n     * @param txPulse\n     * @param rxAperture\n     * @param rxSampleRange [start, end) range of samples to acquire, starts from 0\n     * @param rxDecimationFactor\n     * @param pri\n     * @param rxPadding how many 0-channels padd from the left and right\n     */\n    TxRxParameters(std::vector<bool> txAperture,\n                   std::vector<float> txDelays,\n                   const ops::us4r::Pulse &txPulse,\n                   std::vector<bool> rxAperture,\n                   Interval<uint32> rxSampleRange,\n                   uint32 rxDecimationFactor, float pri,\n                   Tuple<ChannelIdx> rxPadding = {0, 0})\n        : txAperture(std::move(txAperture)), txDelays(std::move(txDelays)),\n          txPulse(txPulse),\n          rxAperture(std::move(rxAperture)), rxSampleRange(std::move(rxSampleRange)),\n          rxDecimationFactor(rxDecimationFactor), pri(pri),\n          rxPadding(std::move(rxPadding)){}\n\n    [[nodiscard]] const std::vector<bool> &getTxAperture() const {\n        return txAperture;\n    }\n\n    [[nodiscard]] const std::vector<float> &getTxDelays() const {\n        return txDelays;\n    }\n\n    [[nodiscard]] const ops::us4r::Pulse &getTxPulse() const {\n        return txPulse;\n    }\n\n    [[nodiscard]] const std::vector<bool> &getRxAperture() const {\n        return rxAperture;\n    }\n\n    [[nodiscard]] const Interval<uint32> &getRxSampleRange() const {\n        return rxSampleRange;\n    }\n\n    [[nodiscard]] uint32 getNumberOfSamples() const {\n        return rxSampleRange.end() - rxSampleRange.start();\n    }\n\n    [[nodiscard]] int32 getRxDecimationFactor() const {\n        return rxDecimationFactor;\n    }\n\n    [[nodiscard]] float getPri() const {\n        return pri;\n    }\n\n    [[nodiscard]] const Tuple<ChannelIdx> &getRxPadding() const {\n        return rxPadding;\n    }\n\n    [[nodiscard]] bool isNOP() const  {\n        auto atLeastOneTxActive = ::arrus::reduce(\n            std::begin(txAperture),\n            std::end(txAperture),\n            false, [](auto a, auto b) {return a | b;});\n        auto atLeastOneRxActive = ::arrus::reduce(\n            std::begin(rxAperture),\n            std::end(rxAperture),\n            false, [](auto a, auto b) {return a | b;});\n        return !atLeastOneTxActive && !atLeastOneRxActive;\n    }\n\n    [[nodiscard]] bool isRxNOP() const {\n        auto atLeastOneRxActive = ::arrus::reduce(\n            std::begin(rxAperture),\n            std::end(rxAperture),\n            false, [](auto a, auto b) {return a | b;});\n        return !atLeastOneRxActive;\n    }\n\n    friend std::ostream &\n    operator<<(std::ostream &os, const TxRxParameters &parameters) {\n        os << \"Tx/Rx: \";\n        os << \"TX: \";\n        os << \"aperture: \" << ::arrus::toString(parameters.getTxAperture())\n           << \", delays: \" << ::arrus::toString(parameters.getTxDelays())\n           << \", center frequency: \" << parameters.getTxPulse().getCenterFrequency()\n           << \", n. periods: \" << parameters.getTxPulse().getNPeriods()\n           << \", inverse: \" << parameters.getTxPulse().isInverse();\n        os << \"; RX: \";\n        os << \"aperture: \" << ::arrus::toString(parameters.getRxAperture());\n        os << \"sample range: \" << parameters.getRxSampleRange().start() << \", \"\n           << parameters.getRxSampleRange().end();\n        os << \", fs divider: \" << parameters.getRxDecimationFactor();\n        os << std::endl;\n        return os;\n    }\n\n    bool operator==(const TxRxParameters &rhs) const {\n        return txAperture == rhs.txAperture &&\n               txDelays == rhs.txDelays &&\n               txPulse == rhs.txPulse &&\n               rxAperture == rhs.rxAperture &&\n               rxSampleRange == rhs.rxSampleRange &&\n               rxDecimationFactor == rhs.rxDecimationFactor &&\n               pri == rhs.pri;\n    }\n\n    bool operator!=(const TxRxParameters &rhs) const {\n        return !(rhs == *this);\n    }\nprivate:\n    ::std::vector<bool> txAperture;\n    ::std::vector<float> txDelays;\n    ::arrus::ops::us4r::Pulse txPulse;\n    ::std::vector<bool> rxAperture;\n    // TODO change to a simple pair\n    Interval<uint32> rxSampleRange;\n    int32 rxDecimationFactor;\n    float pri;\n    Tuple<ChannelIdx> rxPadding;\n};\n\n\nusing TxRxParamsSequence = std::vector<TxRxParameters>;\n\n/**\n * Returns the number of actual ops, that is, a the number of ops excluding RxNOPs.\n */\nuint16 getNumberOfNoRxNOPs(const TxRxParamsSequence &seq);\n\n}\n\n#endif //ARRUS_CORE_DEVICES_TXRXPARAMETERS_H\n", "meta": {"hexsha": "fb53f16aee4c6e9aa0e8ea05b202f1cf6e54075c", "size": 5556, "ext": "h", "lang": "C", "max_stars_repo_path": "arrus/core/devices/TxRxParameters.h", "max_stars_repo_name": "us4useu/arrus", "max_stars_repo_head_hexsha": "10487b09f556e327ddb1bec28fbaccf3b8b08064", "max_stars_repo_licenses": ["BSL-1.0", "MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2021-02-04T19:56:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T09:41:51.000Z", "max_issues_repo_path": "arrus/core/devices/TxRxParameters.h", "max_issues_repo_name": "us4useu/arrus", "max_issues_repo_head_hexsha": "10487b09f556e327ddb1bec28fbaccf3b8b08064", "max_issues_repo_licenses": ["BSL-1.0", "MIT"], "max_issues_count": 60.0, "max_issues_repo_issues_event_min_datetime": "2020-11-06T04:59:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T17:39:06.000Z", "max_forks_repo_path": "arrus/core/devices/TxRxParameters.h", "max_forks_repo_name": "us4useu/arrus", "max_forks_repo_head_hexsha": "10487b09f556e327ddb1bec28fbaccf3b8b08064", "max_forks_repo_licenses": ["BSL-1.0", "MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-07-22T16:13:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T08:53:31.000Z", "avg_line_length": 32.3023255814, "max_line_length": 85, "alphanum_fraction": 0.6011519078, "num_tokens": 1405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3998116407397951, "lm_q2_score": 0.028870906737393162, "lm_q1q2_score": 0.011542924592322765}}
{"text": "/* Copyright 2013 Perttu Luukko\n\n * This file is part of libeemd.\n\n * libeemd is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * libeemd is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n\n * You should have received a copy of the GNU General Public License\n * along with libeemd.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#ifndef _EEMD_H_\n#define _EEMD_H_\n\n#ifndef EEMD_DEBUG\n#define EEMD_DEBUG 0\n#endif\n\n#if EEMD_DEBUG == 0\n#ifndef NDEBUG\n#define NDEBUG\n#endif\n#endif\n\n#include <assert.h>\n#include <limits.h>\n#include <string.h>\n#include <math.h>\n#include <stdbool.h>\n#include <gsl/gsl_statistics_double.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_poly.h>\n\n#ifdef _OPENMP\n#include <omp.h>\n#endif\n\n// Possible error codes returned by functions eemd, ceemdan and\n// emd_evaluate_spline\ntypedef enum {\n\tEMD_SUCCESS = 0,\n\t// Errors from invalid parameters\n\tEMD_INVALID_ENSEMBLE_SIZE = 1,\n\tEMD_INVALID_NOISE_STRENGTH = 2,\n\tEMD_NOISE_ADDED_TO_EMD = 3,\n\tEMD_NO_NOISE_ADDED_TO_EEMD = 4,\n\tEMD_NO_CONVERGENCE_POSSIBLE = 5,\n\tEMD_NOT_ENOUGH_POINTS_FOR_SPLINE = 6,\n\tEMD_INVALID_SPLINE_POINTS = 7,\n\t// Other errors\n\tEMD_GSL_ERROR = 8\n} libeemd_error_code;\n\n// Helper functions to print an error message if an error occured\nvoid emd_report_if_error(libeemd_error_code err);\nvoid emd_report_to_file_if_error(FILE* file, libeemd_error_code err);\n\n// Main EEMD decomposition routine as described in:\n//   Z. Wu and N. Huang,\n//   Ensemble Empirical Mode Decomposition: A Noise-Assisted Data Analysis\n//   Method, Advances in Adaptive Data Analysis,\n//   Vol. 1, No. 1 (2009) 1\u201341\n//\n// Parameters 'input' and 'N' denote the input data and its length,\n// respectively. Output from the routine is written to array 'output', which\n// needs to be able to store at least N*M doubles, where M is the number of\n// Intrinsic Mode Functions (IMFs) to compute. If M is set to zero, a value of\n// M = emd_num_imfs(N) will be used, which corresponds to a maximal number of\n// IMFs. Note that the final residual is also counted as an IMF in this\n// respect, so you most likely want at least num_imfs=2. The following\n// parameters are the ensemble size and the relative noise standard deviation,\n// respectively. These are followed by the parameters for the stopping\n// criterion. The stopping parameter can be defined by a S-number (see the\n// article for details) or a fixed number of siftings. If both are specified,\n// the sifting ends when either criterion is fulfilled. The final parameter is\n// the seed given to the random number generator. A value of zero denotes a\n// RNG-specific default value.\nlibeemd_error_code eemd(double const* restrict input, size_t N,\n\t\tdouble* restrict output, size_t M,\n\t\tunsigned int ensemble_size, double noise_strength, unsigned int\n\t\tS_number, unsigned int num_siftings, unsigned long int rng_seed);\n\n// A complete variant of EEMD as described in:\n//   M. Torres et al,\n//   A Complete Ensemble Empirical Mode Decomposition with Adaptive Noise\n//   IEEE Int. Conf. on Acoust., Speech and Signal Proc. ICASSP-11,\n//   (2011) 4144-4147\n//\n// Parameters are identical to routine eemd\nlibeemd_error_code ceemdan(double const* restrict input, size_t N,\n\t\tdouble* restrict output, size_t M,\n\t\tunsigned int ensemble_size, double noise_strength, unsigned int\n\t\tS_number, unsigned int num_siftings, unsigned long int rng_seed);\n\n// A method for finding the local minima and maxima from input data specified\n// with parameters x and N. The memory for storing the coordinates of the\n// extrema and their number are passed as the rest of the parameters. The\n// arrays for the coordinates must be at least size N. The method also counts\n// the number of zero crossings in the data, and saves the results into the\n// pointer given as num_zero_crossings_ptr.\nvoid emd_find_extrema(double const* restrict x, size_t N,\n\t\tdouble* restrict maxx, double* restrict maxy, size_t* num_max_ptr,\n\t\tdouble* restrict minx, double* restrict miny, size_t* num_min_ptr,\n\t\tsize_t* num_zero_crossings_ptr);\n\n// Return the number of IMFs that can be extracted from input data of length N,\n// including the final residual.\nsize_t emd_num_imfs(size_t N);\n\n// This routine evaluates a cubic spline with nodes defined by the arrays x and\n// y, each of length N. The spline is evaluated using the not-a-node end point\n// conditions (same as Matlab). The y values of the spline curve will be\n// evaluated at integer points from 0 to x[N-1], and these y values will be\n// written to the array spline_y. The endpoint x[N-1] is assumed to be an\n// integer, and the x values are assumed to be in ascending order, with x[0]\n// equal to 0. The workspace required is 5*N-10 doubles, except that N==2\n// requires no extra memory. For N<=3 the routine falls back to polynomial\n// interpolation, same as Matlab.\n//\n// This routine is mainly exported so that it can be tested separately to\n// produce identical results to the Matlab routine 'spline'.\nlibeemd_error_code emd_evaluate_spline(double const* restrict x, double const* restrict y,\n\t\tsize_t N, double* restrict spline_y, double* spline_workspace);\n\n#endif // _EEMD_H_\n", "meta": {"hexsha": "303b9bfc6bbcd23bdb601ce2d4fca467a1c4205f", "size": 5553, "ext": "h", "lang": "C", "max_stars_repo_path": "ni/src/lib/nfp/eemd.h", "max_stars_repo_name": "tenomoto/ncl", "max_stars_repo_head_hexsha": "a87114a689a1566e9aa03d85bcf6dc7325b47633", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 210.0, "max_stars_repo_stars_event_min_datetime": "2016-11-24T09:05:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T19:15:32.000Z", "max_issues_repo_path": "ni/src/lib/nfp/eemd.h", "max_issues_repo_name": "tenomoto/ncl", "max_issues_repo_head_hexsha": "a87114a689a1566e9aa03d85bcf6dc7325b47633", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 156.0, "max_issues_repo_issues_event_min_datetime": "2017-09-22T09:56:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T07:02:21.000Z", "max_forks_repo_path": "ni/src/lib/nfp/eemd.h", "max_forks_repo_name": "tenomoto/ncl", "max_forks_repo_head_hexsha": "a87114a689a1566e9aa03d85bcf6dc7325b47633", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 58.0, "max_forks_repo_forks_event_min_datetime": "2016-12-14T00:15:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T09:13:00.000Z", "avg_line_length": 40.8308823529, "max_line_length": 90, "alphanum_fraction": 0.7612101567, "num_tokens": 1440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.399811640739795, "lm_q2_score": 0.028870906215156315, "lm_q1q2_score": 0.011542924383526392}}
{"text": "#ifndef COMMON_HEADER_H\n#define COMMON_HEADER_H\n//Include Standard Headers\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <stdarg.h>\n#include <stdint.h>\n#include <stdbool.h>\n//Math Libraries\n\n//#include <math.h>\n#include <limits.h>\n//#include <gsl/gsl_sf_bessel.h>\n//RNG Libraries:\n#include <linux/random.h>\n\n//POSIX libraries:\n#include <unistd.h>\n#include <pthread.h>\n\n//Ncurses\n//#include <ncurses.h>\n#endif\n", "meta": {"hexsha": "224e52c60bf05527712a9fe4e3aaa2ad88ebf72c", "size": 450, "ext": "h", "lang": "C", "max_stars_repo_path": "Third Edition/Chapter 2/common_header.h", "max_stars_repo_name": "ucarlos/ucarlos-computer-systems-solutions", "max_stars_repo_head_hexsha": "b60cbc404bf3f24b4b70e03d1ea5ce46df7900e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Third Edition/Chapter 2/common_header.h", "max_issues_repo_name": "ucarlos/ucarlos-computer-systems-solutions", "max_issues_repo_head_hexsha": "b60cbc404bf3f24b4b70e03d1ea5ce46df7900e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Third Edition/Chapter 2/common_header.h", "max_forks_repo_name": "ucarlos/ucarlos-computer-systems-solutions", "max_forks_repo_head_hexsha": "b60cbc404bf3f24b4b70e03d1ea5ce46df7900e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.3076923077, "max_line_length": 32, "alphanum_fraction": 0.7222222222, "num_tokens": 117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.23934935817440725, "lm_q2_score": 0.04813677060456063, "lm_q1q2_score": 0.011521505148790261}}
{"text": "#include <qdm.h>\n\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_randist.h>\n#include <hdf5.h>\n#include <hdf5_hl.h>\n\nstatic\nvoid\nqdm_mcmc_workspace_init(\n    qdm_mcmc *mcmc\n)\n{\n  mcmc->w.xi      = gsl_vector_calloc(mcmc->p.xi->size);\n  mcmc->w.xi_acc  = gsl_vector_calloc(mcmc->p.xi->size);\n  mcmc->w.xi_p    = gsl_vector_calloc(mcmc->p.xi->size);\n  mcmc->w.xi_tune = gsl_vector_calloc(mcmc->p.xi->size);\n\n  gsl_vector_memcpy(mcmc->w.xi,   mcmc->p.xi);\n  gsl_vector_memcpy(mcmc->w.xi_p, mcmc->p.xi);\n\n  gsl_vector_set_all(mcmc->w.xi_tune, mcmc->p.xi_tune_sd);\n\n  mcmc->w.ll   = gsl_vector_calloc(mcmc->p.ll->size);\n  mcmc->w.ll_p = gsl_vector_calloc(mcmc->p.ll->size);\n\n  gsl_vector_memcpy(mcmc->w.ll,   mcmc->p.ll);\n  gsl_vector_memcpy(mcmc->w.ll_p, mcmc->p.ll);\n\n  mcmc->w.tau   = gsl_vector_calloc(mcmc->p.tau->size);\n  mcmc->w.tau_p = gsl_vector_calloc(mcmc->p.tau->size);\n\n  gsl_vector_memcpy(mcmc->w.tau,   mcmc->p.tau);\n  gsl_vector_memcpy(mcmc->w.tau_p, mcmc->p.tau);\n\n  mcmc->w.theta        = gsl_matrix_calloc(mcmc->p.theta->size1, mcmc->p.theta->size2);\n  mcmc->w.theta_acc    = gsl_matrix_calloc(mcmc->p.theta->size1, mcmc->p.theta->size2);\n  mcmc->w.theta_p      = gsl_matrix_calloc(mcmc->p.theta->size1, mcmc->p.theta->size2);\n  mcmc->w.theta_star   = gsl_matrix_calloc(mcmc->p.theta->size1, mcmc->p.theta->size2);\n  mcmc->w.theta_star_p = gsl_matrix_calloc(mcmc->p.theta->size1, mcmc->p.theta->size2);\n  mcmc->w.theta_tune   = gsl_matrix_calloc(mcmc->p.theta->size1, mcmc->p.theta->size2);\n\n  gsl_matrix_memcpy(mcmc->w.theta,      mcmc->p.theta);\n  gsl_matrix_memcpy(mcmc->w.theta_star, mcmc->p.theta);\n\n  gsl_matrix_set_all(mcmc->w.theta_tune, mcmc->p.theta_tune_sd);\n}\n\nstatic\nvoid\nqdm_mcmc_workspace_fini(\n    qdm_mcmc *mcmc\n)\n{\n  gsl_vector_free(mcmc->w.xi);\n  gsl_vector_free(mcmc->w.xi_acc);\n  gsl_vector_free(mcmc->w.xi_p);\n  gsl_vector_free(mcmc->w.xi_tune);\n\n  gsl_vector_free(mcmc->w.ll);\n  gsl_vector_free(mcmc->w.ll_p);\n\n  gsl_vector_free(mcmc->w.tau);\n  gsl_vector_free(mcmc->w.tau_p);\n\n  gsl_matrix_free(mcmc->w.theta);\n  gsl_matrix_free(mcmc->w.theta_acc);\n  gsl_matrix_free(mcmc->w.theta_p);\n  gsl_matrix_free(mcmc->w.theta_star);\n  gsl_matrix_free(mcmc->w.theta_star_p);\n  gsl_matrix_free(mcmc->w.theta_tune);\n\n  mcmc->w.xi      = NULL;\n  mcmc->w.xi_acc  = NULL;\n  mcmc->w.xi_p    = NULL;\n  mcmc->w.xi_tune = NULL;\n\n  mcmc->w.ll   = NULL;\n  mcmc->w.ll_p = NULL;\n\n  mcmc->w.tau   = NULL;\n  mcmc->w.tau_p = NULL;\n\n  mcmc->w.theta        = NULL;\n  mcmc->w.theta_acc    = NULL;\n  mcmc->w.theta_p      = NULL;\n  mcmc->w.theta_star   = NULL;\n  mcmc->w.theta_star_p = NULL;\n  mcmc->w.theta_tune   = NULL;\n}\n\nstatic\nvoid\nqdm_mcmc_results_init(\n    qdm_mcmc *mcmc\n)\n{\n  mcmc->r.s = mcmc->p.iter / mcmc->p.thin;\n\n  mcmc->r.theta      = qdm_ijk_calloc(mcmc->p.theta->size1, mcmc->p.theta->size2, mcmc->r.s);\n  mcmc->r.theta_star = qdm_ijk_calloc(mcmc->p.theta->size1, mcmc->p.theta->size2, mcmc->r.s);\n\n  mcmc->r.ll  = qdm_ijk_calloc(1, mcmc->p.ll->size, mcmc->r.s);\n  mcmc->r.tau = qdm_ijk_calloc(1, mcmc->p.tau->size, mcmc->r.s);\n\n  mcmc->r.xi = qdm_ijk_calloc(1, mcmc->p.xi->size, mcmc->r.s);\n}\n\nstatic\nvoid\nqdm_mcmc_results_fini(\n    qdm_mcmc *mcmc\n)\n{\n  qdm_ijk_free(mcmc->r.theta);\n  qdm_ijk_free(mcmc->r.theta_star);\n\n  qdm_ijk_free(mcmc->r.ll);\n  qdm_ijk_free(mcmc->r.tau);\n\n  qdm_ijk_free(mcmc->r.xi);\n\n  mcmc->r.theta      = NULL;\n  mcmc->r.theta_star = NULL;\n\n  mcmc->r.ll  = NULL;\n  mcmc->r.tau = NULL;\n\n  mcmc->r.xi = NULL;\n}\n\nqdm_mcmc *\nqdm_mcmc_alloc(\n    qdm_mcmc_parameters p\n)\n{\n  qdm_mcmc *mcmc = malloc(sizeof(qdm_mcmc));\n\n  mcmc->p = p;\n\n  qdm_mcmc_workspace_init(mcmc);\n  qdm_mcmc_results_init(mcmc);\n\n  return mcmc;\n}\n\nvoid\nqdm_mcmc_free(\n    qdm_mcmc *mcmc\n)\n{\n  if (mcmc == NULL) {\n    return;\n  }\n\n  qdm_mcmc_results_fini(mcmc);\n  qdm_mcmc_workspace_fini(mcmc);\n\n  free(mcmc);\n}\n\nint\nqdm_mcmc_run(\n    qdm_mcmc *mcmc\n)\n{\n  int status = 0;\n\n  for (size_t i = 0; i < mcmc->p.burn; i++) {\n    status = qdm_mcmc_next(mcmc);\n    if (status != 0) {\n      goto cleanup;\n    }\n\n    if (i % mcmc->p.acc_check == 0) {\n      qdm_mcmc_update_tune(mcmc);\n    }\n  }\n\n  for (size_t i = 0; i < mcmc->p.iter; i++) {\n    status = qdm_mcmc_next(mcmc);\n    if (status != 0) {\n      goto cleanup;\n    }\n\n    if (i % mcmc->p.thin == 0) {\n      status = qdm_mcmc_save(mcmc, i / mcmc->p.thin);\n      if (status != 0) {\n        goto cleanup;\n      }\n    }\n  }\n\ncleanup:\n  return status;\n}\n\nint\nqdm_mcmc_next(\n    qdm_mcmc *mcmc\n)\n{\n  int status = 0;\n\n  status = qdm_mcmc_update_theta(mcmc);\n  if (status != 0) {\n    goto cleanup;\n  }\n\n  status = qdm_mcmc_update_xi(mcmc);\n  if (status != 0) {\n    goto cleanup;\n  }\n\ncleanup:\n  return status;\n}\n\nvoid\nqdm_mcmc_update_tune(\n    qdm_mcmc *mcmc\n)\n{\n  for (size_t p = 0; p < mcmc->w.theta->size1; p++) {\n    for (size_t m = 0; m < mcmc->w.theta->size2; m++) {\n      if (gsl_matrix_get(mcmc->w.theta_acc, p, m) / (double)mcmc->p.acc_check > 0.5) {\n        gsl_matrix_set(mcmc->w.theta_tune, p, m, gsl_min(gsl_matrix_get(mcmc->w.theta_tune, p, m) * 1.2, 5));\n      }\n\n      if (gsl_matrix_get(mcmc->w.theta_acc, p, m) / (double)mcmc->p.acc_check < 0.3) {\n        gsl_matrix_set(mcmc->w.theta_tune, p, m, gsl_matrix_get(mcmc->w.theta_tune, p, m) * 0.8);\n      }\n    }\n  }\n\n  if (gsl_vector_get(mcmc->w.xi_acc, 0) / mcmc->p.acc_check > 0.5) {\n    gsl_vector_set(mcmc->w.xi_tune, 0, gsl_min(gsl_vector_get(mcmc->w.xi_tune, 0) * 1.2, 5));\n  }\n  if (gsl_vector_get(mcmc->w.xi_acc, 0) / mcmc->p.acc_check < 0.3) {\n    gsl_vector_set(mcmc->w.xi_tune, 0, gsl_vector_get(mcmc->w.xi_tune, 0) * 0.8);\n  }\n\n  if (gsl_vector_get(mcmc->w.xi_acc, 1) / mcmc->p.acc_check > 0.5) {\n    gsl_vector_set(mcmc->w.xi_tune, 1, gsl_min(gsl_vector_get(mcmc->w.xi_tune, 1) * 1.2, 5));\n  }\n  if (gsl_vector_get(mcmc->w.xi_acc, 1) / mcmc->p.acc_check < 0.3) {\n    gsl_vector_set(mcmc->w.xi_tune, 1, gsl_vector_get(mcmc->w.xi_tune, 1) * 0.8);\n  }\n\n  /* Reset the acceptance counter. */\n  gsl_matrix_set_zero(mcmc->w.theta_acc);\n  gsl_vector_set_zero(mcmc->w.xi_acc);\n}\n\nint\nqdm_mcmc_update_theta(\n    qdm_mcmc *mcmc\n)\n{\n  int status = 0;\n\n  /* Update the mth spline. */\n  size_t p_max = mcmc->w.theta->size1;\n  if (mcmc->p.truncate) {\n    p_max = 1;\n  }\n\n  for (size_t p = 0; p < p_max; p++) {\n    for (size_t m = 0; m < mcmc->w.theta->size2; m++) {\n      /* Propose new theta star. */\n      status = gsl_matrix_memcpy(mcmc->w.theta_star_p, mcmc->w.theta_star);\n      if (status != 0) {\n        goto cleanup;\n      }\n\n      double proposal =\n        gsl_matrix_get(mcmc->w.theta_tune, p, m) *\n        gsl_ran_ugaussian(mcmc->p.rng) +\n        gsl_matrix_get(mcmc->w.theta_star, p, m);\n\n      gsl_matrix_set(mcmc->w.theta_star_p, p, m, proposal);\n\n      gsl_matrix_memcpy(mcmc->w.theta_p, mcmc->w.theta_star_p);\n      qdm_theta_matrix_constrain(mcmc->w.theta_p, mcmc->p.theta_min);\n\n      for (size_t i = 0; i < mcmc->p.y->size; i++) {\n        qdm_logl_3(\n            gsl_vector_ptr(mcmc->w.ll_p, i),\n            gsl_vector_ptr(mcmc->w.tau_p, i),\n\n            gsl_vector_get(mcmc->p.x, i),\n            gsl_vector_get(mcmc->p.y, i),\n\n            mcmc->p.t,\n            mcmc->w.xi,\n\n            mcmc->w.theta_p\n        );\n      }\n\n      double ratio = qdm_vector_sum(mcmc->w.ll_p) - qdm_vector_sum(mcmc->w.ll);\n\n      if (log(gsl_rng_uniform(mcmc->p.rng)) < ratio) {\n        status = gsl_matrix_memcpy(mcmc->w.theta_star, mcmc->w.theta_star_p);\n        if (status != 0) {\n          goto cleanup;\n        }\n\n        status = gsl_matrix_memcpy(mcmc->w.theta, mcmc->w.theta_p);\n        if (status != 0) {\n          goto cleanup;\n        }\n\n        status = gsl_vector_memcpy(mcmc->w.ll, mcmc->w.ll_p);\n        if (status != 0) {\n          goto cleanup;\n        }\n\n        status = gsl_vector_memcpy(mcmc->w.tau, mcmc->w.tau_p);\n        if (status != 0) {\n          goto cleanup;\n        }\n\n        gsl_matrix_set(mcmc->w.theta_acc, p, m, gsl_matrix_get(mcmc->w.theta_acc, p, m) + 1);\n      }\n    }\n  }\n\ncleanup:\n  return status;\n}\n\nint\nqdm_mcmc_update_xi(\n    qdm_mcmc *mcmc\n)\n{\n  int status = 0;\n\n  /* Update xi_low. */\n  {\n    double xi_low = gsl_vector_get(mcmc->w.xi, 0);\n    double xi_low_p = exp(log(xi_low) + gsl_vector_get(mcmc->w.xi_tune, 0) * gsl_ran_ugaussian(mcmc->p.rng));\n\n    gsl_vector_memcpy(mcmc->w.xi_p, mcmc->w.xi);\n    gsl_vector_set(mcmc->w.xi_p, 0, xi_low_p);\n\n    for (size_t i = 0; i < mcmc->p.y->size; i++) {\n      qdm_logl_3(\n          gsl_vector_ptr(mcmc->w.ll_p, i),\n          gsl_vector_ptr(mcmc->w.tau_p, i),\n\n          gsl_vector_get(mcmc->p.x, i),\n          gsl_vector_get(mcmc->p.y, i),\n\n          mcmc->p.t,\n          mcmc->w.xi_p,\n\n          mcmc->w.theta\n      );\n    }\n\n    double ratio = -0.5 * (1 / mcmc->p.xi_prior_var) *  pow(log(xi_low_p) - mcmc->p.xi_prior_mean, 2) +\n                    0.5 * (1 / mcmc->p.xi_prior_var) * (pow(log(xi_low  ) - mcmc->p.xi_prior_mean, 2) + qdm_vector_sum(mcmc->w.ll_p) - qdm_vector_sum(mcmc->w.ll));\n    if (log(gsl_rng_uniform(mcmc->p.rng)) < ratio) {\n      gsl_vector_set(mcmc->w.xi, 0, xi_low_p);\n\n      status = gsl_vector_memcpy(mcmc->w.ll, mcmc->w.ll_p);\n      if (status != 0) {\n        goto cleanup;\n      }\n\n      gsl_vector_set(mcmc->w.xi_acc, 0, gsl_vector_get(mcmc->w.xi_acc, 0) + 1);\n    }\n  }\n\n  /* Update xi_high. */\n  {\n    double xi_high = gsl_vector_get(mcmc->w.xi, 1);\n    double xi_high_p = exp(log(xi_high) + gsl_vector_get(mcmc->w.xi_tune, 1) * gsl_ran_ugaussian(mcmc->p.rng));\n\n    gsl_vector_memcpy(mcmc->w.xi_p, mcmc->w.xi);\n    gsl_vector_set(mcmc->w.xi_p, 1, xi_high_p);\n\n    for (size_t i = 0; i < mcmc->p.y->size; i++) {\n      qdm_logl_3(\n          gsl_vector_ptr(mcmc->w.ll_p, i),\n          gsl_vector_ptr(mcmc->w.tau_p, i),\n\n          gsl_vector_get(mcmc->p.x, i),\n          gsl_vector_get(mcmc->p.y, i),\n\n          mcmc->p.t,\n          mcmc->w.xi_p,\n\n          mcmc->w.theta\n      );\n    }\n\n    double ratio = -0.5 * (1 / mcmc->p.xi_prior_var) *  pow(log(xi_high_p) - mcmc->p.xi_prior_mean, 2) +\n                    0.5 * (1 / mcmc->p.xi_prior_var) * (pow(log(xi_high  ) - mcmc->p.xi_prior_mean, 2) + qdm_vector_sum(mcmc->w.ll_p) - qdm_vector_sum(mcmc->w.ll));\n    if (log(gsl_rng_uniform(mcmc->p.rng)) < ratio) {\n      gsl_vector_set(mcmc->w.xi, 1, xi_high_p);\n\n      status = gsl_vector_memcpy(mcmc->w.ll, mcmc->w.ll_p);\n      if (status != 0) {\n        goto cleanup;\n      }\n\n      gsl_vector_set(mcmc->w.xi_acc, 1, gsl_vector_get(mcmc->w.xi_acc, 1) + 1);\n    }\n  }\n\ncleanup:\n  return status;\n}\n\nint\nqdm_mcmc_save(\n    qdm_mcmc *mcmc,\n    size_t k\n)\n{\n  int status = 0;\n\n  {\n    gsl_matrix_view m = qdm_ijk_get_ij(mcmc->r.theta, k);\n\n    status = gsl_matrix_memcpy(&m.matrix, mcmc->w.theta);\n    if (status != 0) {\n      goto cleanup;\n    }\n  }\n\n  {\n    gsl_matrix_view m = qdm_ijk_get_ij(mcmc->r.theta_star, k);\n\n    status = gsl_matrix_memcpy(&m.matrix, mcmc->w.theta_star);\n    if (status != 0) {\n      goto cleanup;\n    }\n  }\n\n  {\n    gsl_matrix_view m = qdm_ijk_get_ij(mcmc->r.ll, k);\n\n    status = gsl_matrix_set_row(&m.matrix, 0, mcmc->w.ll);\n    if (status != 0) {\n      goto cleanup;\n    }\n  }\n\n  {\n    gsl_matrix_view m = qdm_ijk_get_ij(mcmc->r.tau, k);\n\n    status = gsl_matrix_set_row(&m.matrix, 0, mcmc->w.tau);\n    if (status != 0) {\n      goto cleanup;\n    }\n  }\n\n  {\n    gsl_matrix_view m = qdm_ijk_get_ij(mcmc->r.xi, k);\n\n    status = gsl_matrix_set_row(&m.matrix, 0, mcmc->w.xi);\n    if (status != 0) {\n      goto cleanup;\n    }\n  }\n\ncleanup:\n  return status;\n}\n\nint\nqdm_mcmc_write(\n    hid_t id,\n    const qdm_mcmc *mcmc\n)\n{\n  int status = 0;\n\n  status = qdm_ijk_write(id, \"theta\", mcmc->r.theta);\n  if (status != 0) {\n    goto cleanup;\n  }\n\n  status = qdm_ijk_write(id, \"theta_star\", mcmc->r.theta_star);\n  if (status != 0) {\n    goto cleanup;\n  }\n\n  status = qdm_ijk_write(id, \"ll\", mcmc->r.ll);\n  if (status != 0) {\n    goto cleanup;\n  }\n\n  status = qdm_ijk_write(id, \"tau\", mcmc->r.tau);\n  if (status != 0) {\n    goto cleanup;\n  }\n\n  status = qdm_ijk_write(id, \"xi\", mcmc->r.xi);\n  if (status != 0) {\n    goto cleanup;\n  }\n\ncleanup:\n  return status;\n}\n\nint\nqdm_mcmc_read(\n    hid_t id,\n    qdm_mcmc **mcmc\n)\n{\n  int status = 0;\n\n  *mcmc = malloc(sizeof(qdm_mcmc));\n\n  status = qdm_ijk_read(id, \"theta\", &(*mcmc)->r.theta);\n  if (status != 0) {\n    goto cleanup;\n  }\n\n  status = qdm_ijk_read(id, \"theta_star\", &(*mcmc)->r.theta_star);\n  if (status != 0) {\n    goto cleanup;\n  }\n\n  status = qdm_ijk_read(id, \"ll\", &(*mcmc)->r.ll);\n  if (status != 0) {\n    goto cleanup;\n  }\n\n  status = qdm_ijk_read(id, \"tau\", &(*mcmc)->r.tau);\n  if (status != 0) {\n    goto cleanup;\n  }\n\n  status = qdm_ijk_read(id, \"xi\", &(*mcmc)->r.xi);\n  if (status != 0) {\n    goto cleanup;\n  }\n\n  (*mcmc)->r.s = (*mcmc)->r.theta->size3;\n\ncleanup:\n  return status;\n}\n", "meta": {"hexsha": "c9bece99e5317496e5efc4c5a813b9fed28f439e", "size": 12694, "ext": "c", "lang": "C", "max_stars_repo_path": "src/mcmc.c", "max_stars_repo_name": "calebcase/qdm", "max_stars_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mcmc.c", "max_issues_repo_name": "calebcase/qdm", "max_issues_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-03-06T18:09:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-22T20:22:53.000Z", "max_forks_repo_path": "src/mcmc.c", "max_forks_repo_name": "calebcase/qdm", "max_forks_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9963768116, "max_line_length": 164, "alphanum_fraction": 0.6002835986, "num_tokens": 4587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3812195662561499, "lm_q2_score": 0.030214587613180036, "lm_q1q2_score": 0.011518391984504932}}
{"text": "#ifndef H_LASER_DATA_JSON\n#define H_LASER_DATA_JSON\n\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_vector.h>\n\n#include <json-c/json.h>\n#include <json-c/json_more_utils.h>\n\n#include \"laser_data.h\"\n#include \"algos.h\"\n\n/* Laserdata to/from json */\n\nJO ld_to_json(LDP);\nLDP json_to_ld(JO);\n\nJO corr_to_json(struct correspondence*, int n);\nint json_to_corr(JO jo, struct correspondence*, int n);\n\nLDP ld_from_json_stream(FILE*);\nLDP ld_from_json_string(const char*s);\nvoid ld_write_as_json(LDP ld, FILE * stream);\n\n\n/* Other stuff to/from json */\n\nJO matrix_to_json(gsl_matrix*m);\nJO vector_to_json(gsl_vector*v);\nJO result_to_json(struct sm_params*p, struct sm_result *r);\n\n#endif\n", "meta": {"hexsha": "8e1dfe53bbf7c42614a726f4f93317751eadc797", "size": 677, "ext": "h", "lang": "C", "max_stars_repo_path": "csm/sm/csm/laser_data_json.h", "max_stars_repo_name": "ozaslan/basics", "max_stars_repo_head_hexsha": "509223ef116f307d443e9a058923ad42f0c507e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "csm/sm/csm/laser_data_json.h", "max_issues_repo_name": "ozaslan/basics", "max_issues_repo_head_hexsha": "509223ef116f307d443e9a058923ad42f0c507e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "csm/sm/csm/laser_data_json.h", "max_forks_repo_name": "ozaslan/basics", "max_forks_repo_head_hexsha": "509223ef116f307d443e9a058923ad42f0c507e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.5151515152, "max_line_length": 59, "alphanum_fraction": 0.7592319055, "num_tokens": 182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.43014734858584286, "lm_q2_score": 0.026759285998981808, "lm_q1q2_score": 0.011510435922512292}}
{"text": "/* ode-initval/odeiv.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n/* Author:  G. Jungman\n */\n#include <config.h>\n#include <stdlib.h>\n#include <gsl/gsl_errno.h>\n#include \"gsl_odeiv.h\"\n\ngsl_odeiv_step * \ngsl_odeiv_step_alloc(const gsl_odeiv_step_type * T, size_t dim)\n{\n  gsl_odeiv_step *s = (gsl_odeiv_step *) malloc (sizeof (gsl_odeiv_step));\n\n  if (s == 0)\n    {\n      GSL_ERROR_NULL (\"failed to allocate space for ode struct\", GSL_ENOMEM);\n    };\n\n  s->type = T;\n  s->dimension = dim;\n\n  s->state = s->type->alloc(dim);\n\n  if (s->state == 0)\n    {\n      free (s);\t\t/* exception in constructor, avoid memory leak */\n\n      GSL_ERROR_NULL (\"failed to allocate space for ode state\",\tGSL_ENOMEM);\n    };\n    \n  return s;\n}\n\nconst char *\ngsl_odeiv_step_name(const gsl_odeiv_step * s)\n{\n  return s->type->name;\n}\n\nunsigned int\ngsl_odeiv_step_order(const gsl_odeiv_step * s)\n{\n  return s->type->order(s->state);\n}\n\nint\ngsl_odeiv_step_apply(\n  gsl_odeiv_step * s,\n  double t,\n  double h,\n  double y[],\n  double yerr[],\n  const double dydt_in[],\n  double dydt_out[],\n  const gsl_odeiv_system * dydt)\n{\n  return s->type->apply(s->state, s->dimension, t, h, y, yerr, dydt_in, dydt_out, dydt);\n}\n\nint\ngsl_odeiv_step_reset(gsl_odeiv_step * s)\n{\n  return s->type->reset(s->state, s->dimension);\n}\n\nvoid\ngsl_odeiv_step_free(gsl_odeiv_step * s)\n{\n  s->type->free(s->state);\n  free(s);\n}\n", "meta": {"hexsha": "96999e3acc83410549d6ef7833c06e15ecffc8e3", "size": 2103, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/ode-initval/step.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/ode-initval/step.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/ode-initval/step.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 23.3666666667, "max_line_length": 88, "alphanum_fraction": 0.6885401807, "num_tokens": 632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250463481418826, "lm_q2_score": 0.027169228434084505, "lm_q1q2_score": 0.011479124937726133}}
{"text": "/*\n * Copyright (c) 2011-2013  University of Texas at Austin. All rights reserved.\n *\n * $COPYRIGHT$\n *\n * Additional copyrights may follow\n *\n * This file is part of PerfExpert.\n *\n * PerfExpert is free software: you can redistribute it and/or modify it under\n * the terms of the The University of Texas at Austin Research License\n * \n * PerfExpert is distributed in the hope that it will be useful, but WITHOUT ANY\n * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR\n * A PARTICULAR PURPOSE.\n * \n * Authors: Leonardo Fialho and Ashay Rane\n *\n * $HEADER$\n */\n\n#ifndef HISTOGRAM_H_\n#define HISTOGRAM_H_\n\n#include <algorithm>\n#include <gsl/gsl_histogram.h>\n\n#include \"analysis_defs.h\"\n\nbool pair_sort(const pair_t& p1, const pair_t& p2);\n\nint flatten_and_sort_histogram(gsl_histogram*& hist, pair_list_t& pair_list);\n\nint create_histogram_if_null(gsl_histogram*& hist, size_t bins);\n\n#endif  /* HISTOGRAM_H_ */\n", "meta": {"hexsha": "019cfa5c7ffb6d0fc74e9461bb97ddf7b1c6fc43", "size": 939, "ext": "h", "lang": "C", "max_stars_repo_path": "tools/macpo/analyze/include/histogram.h", "max_stars_repo_name": "roystgnr/perfexpert", "max_stars_repo_head_hexsha": "a03b13db9ac83e992e1c5cc3b6e45e52c266fe30", "max_stars_repo_licenses": ["BSD-4-Clause-UC"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2015-05-05T15:54:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-27T16:23:36.000Z", "max_issues_repo_path": "tools/macpo/analyze/include/histogram.h", "max_issues_repo_name": "roystgnr/perfexpert", "max_issues_repo_head_hexsha": "a03b13db9ac83e992e1c5cc3b6e45e52c266fe30", "max_issues_repo_licenses": ["BSD-4-Clause-UC"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2015-10-07T20:52:05.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-18T16:08:41.000Z", "max_forks_repo_path": "tools/macpo/analyze/include/histogram.h", "max_forks_repo_name": "roystgnr/perfexpert", "max_forks_repo_head_hexsha": "a03b13db9ac83e992e1c5cc3b6e45e52c266fe30", "max_forks_repo_licenses": ["BSD-4-Clause-UC"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2015-01-23T15:41:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-18T03:53:19.000Z", "avg_line_length": 25.3783783784, "max_line_length": 80, "alphanum_fraction": 0.7465388711, "num_tokens": 231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36296921930155557, "lm_q2_score": 0.03161876932181089, "lm_q1q2_score": 0.011476640016013675}}
{"text": "/* vector/gsl_vector_short.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_VECTOR_SHORT_H__\n#define __GSL_VECTOR_SHORT_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_block_short.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size;\n  size_t stride;\n  short *data;\n  gsl_block_short *block;\n  int owner;\n} \ngsl_vector_short;\n\ntypedef struct\n{\n  gsl_vector_short vector;\n} _gsl_vector_short_view;\n\ntypedef _gsl_vector_short_view gsl_vector_short_view;\n\ntypedef struct\n{\n  gsl_vector_short vector;\n} _gsl_vector_short_const_view;\n\ntypedef const _gsl_vector_short_const_view gsl_vector_short_const_view;\n\n\n/* Allocation */\n\ngsl_vector_short *gsl_vector_short_alloc (const size_t n);\ngsl_vector_short *gsl_vector_short_calloc (const size_t n);\n\ngsl_vector_short *gsl_vector_short_alloc_from_block (gsl_block_short * b,\n                                                     const size_t offset, \n                                                     const size_t n, \n                                                     const size_t stride);\n\ngsl_vector_short *gsl_vector_short_alloc_from_vector (gsl_vector_short * v,\n                                                      const size_t offset, \n                                                      const size_t n, \n                                                      const size_t stride);\n\nvoid gsl_vector_short_free (gsl_vector_short * v);\n\n/* Views */\n\n_gsl_vector_short_view \ngsl_vector_short_view_array (short *v, size_t n);\n\n_gsl_vector_short_view \ngsl_vector_short_view_array_with_stride (short *base,\n                                         size_t stride,\n                                         size_t n);\n\n_gsl_vector_short_const_view \ngsl_vector_short_const_view_array (const short *v, size_t n);\n\n_gsl_vector_short_const_view \ngsl_vector_short_const_view_array_with_stride (const short *base,\n                                               size_t stride,\n                                               size_t n);\n\n_gsl_vector_short_view \ngsl_vector_short_subvector (gsl_vector_short *v, \n                            size_t i, \n                            size_t n);\n\n_gsl_vector_short_view \ngsl_vector_short_subvector_with_stride (gsl_vector_short *v, \n                                        size_t i,\n                                        size_t stride,\n                                        size_t n);\n\n_gsl_vector_short_const_view \ngsl_vector_short_const_subvector (const gsl_vector_short *v, \n                                  size_t i, \n                                  size_t n);\n\n_gsl_vector_short_const_view \ngsl_vector_short_const_subvector_with_stride (const gsl_vector_short *v, \n                                              size_t i, \n                                              size_t stride,\n                                              size_t n);\n\n/* Operations */\n\nshort gsl_vector_short_get (const gsl_vector_short * v, const size_t i);\nvoid gsl_vector_short_set (gsl_vector_short * v, const size_t i, short x);\n\nshort *gsl_vector_short_ptr (gsl_vector_short * v, const size_t i);\nconst short *gsl_vector_short_const_ptr (const gsl_vector_short * v, const size_t i);\n\nvoid gsl_vector_short_set_zero (gsl_vector_short * v);\nvoid gsl_vector_short_set_all (gsl_vector_short * v, short x);\nint gsl_vector_short_set_basis (gsl_vector_short * v, size_t i);\n\nint gsl_vector_short_fread (FILE * stream, gsl_vector_short * v);\nint gsl_vector_short_fwrite (FILE * stream, const gsl_vector_short * v);\nint gsl_vector_short_fscanf (FILE * stream, gsl_vector_short * v);\nint gsl_vector_short_fprintf (FILE * stream, const gsl_vector_short * v,\n                              const char *format);\n\nint gsl_vector_short_memcpy (gsl_vector_short * dest, const gsl_vector_short * src);\n\nint gsl_vector_short_reverse (gsl_vector_short * v);\n\nint gsl_vector_short_swap (gsl_vector_short * v, gsl_vector_short * w);\nint gsl_vector_short_swap_elements (gsl_vector_short * v, const size_t i, const size_t j);\n\nshort gsl_vector_short_max (const gsl_vector_short * v);\nshort gsl_vector_short_min (const gsl_vector_short * v);\nvoid gsl_vector_short_minmax (const gsl_vector_short * v, short * min_out, short * max_out);\n\nsize_t gsl_vector_short_max_index (const gsl_vector_short * v);\nsize_t gsl_vector_short_min_index (const gsl_vector_short * v);\nvoid gsl_vector_short_minmax_index (const gsl_vector_short * v, size_t * imin, size_t * imax);\n\nint gsl_vector_short_add (gsl_vector_short * a, const gsl_vector_short * b);\nint gsl_vector_short_sub (gsl_vector_short * a, const gsl_vector_short * b);\nint gsl_vector_short_mul (gsl_vector_short * a, const gsl_vector_short * b);\nint gsl_vector_short_div (gsl_vector_short * a, const gsl_vector_short * b);\nint gsl_vector_short_scale (gsl_vector_short * a, const double x);\nint gsl_vector_short_add_constant (gsl_vector_short * a, const double x);\n\nint gsl_vector_short_isnull (const gsl_vector_short * v);\n\n#ifdef HAVE_INLINE\n\nextern inline\nshort\ngsl_vector_short_get (const gsl_vector_short * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_VAL (\"index out of range\", GSL_EINVAL, 0);\n    }\n#endif\n  return v->data[i * v->stride];\n}\n\nextern inline\nvoid\ngsl_vector_short_set (gsl_vector_short * v, const size_t i, short x)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_VOID (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  v->data[i * v->stride] = x;\n}\n\nextern inline\nshort *\ngsl_vector_short_ptr (gsl_vector_short * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return (short *) (v->data + i * v->stride);\n}\n\nextern inline\nconst short *\ngsl_vector_short_const_ptr (const gsl_vector_short * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return (const short *) (v->data + i * v->stride);\n}\n\n\n#endif /* HAVE_INLINE */\n\n__END_DECLS\n\n#endif /* __GSL_VECTOR_SHORT_H__ */\n\n\n", "meta": {"hexsha": "e73de3a78e7906a263672561468cc28a78ad68c3", "size": 7070, "ext": "h", "lang": "C", "max_stars_repo_path": "extern/include/gsl/gsl_vector_short.h", "max_stars_repo_name": "andrewkern/segSiteHMM", "max_stars_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "extern/include/gsl/gsl_vector_short.h", "max_issues_repo_name": "andrewkern/segSiteHMM", "max_issues_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "extern/include/gsl/gsl_vector_short.h", "max_forks_repo_name": "andrewkern/segSiteHMM", "max_forks_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1453744493, "max_line_length": 94, "alphanum_fraction": 0.6719943423, "num_tokens": 1651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3629692055196168, "lm_q2_score": 0.031618765557674414, "lm_q1q2_score": 0.011476638213980105}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n \r\n#ifndef batch_8317ae94_87f4_4cc2_8dab_1eef2919a461_h\r\n#define batch_8317ae94_87f4_4cc2_8dab_1eef2919a461_h\r\n\r\n#include <ariel/config.h>\r\n#include <gslib/rtree.h>\r\n#include <ariel/loopblinn.h>\r\n\r\n__ariel_begin__\r\n\r\nstruct bat_triangle;\r\nstruct bat_line;\r\nstruct bat_batch;\r\n\r\ntypedef vector<bat_triangle*> bat_triangles;\r\ntypedef vector<bat_line*> bat_lines;\r\ntypedef rtree_entity<bat_triangle*> bat_rtree_entity;\r\ntypedef rtree_node<bat_rtree_entity> bat_rtree_node;\r\ntypedef _tree_allocator<bat_rtree_node> bat_rtree_alloc;\r\ntypedef tree<bat_rtree_entity, bat_rtree_node, bat_rtree_alloc> bat_tree;\r\ntypedef rtree<bat_rtree_entity, quadratic_split_alg<16, 6, bat_tree>, bat_rtree_node, bat_rtree_alloc> bat_rtree;\r\ntypedef vector<bat_batch*> bat_batches;\r\n\r\nenum bat_type\r\n{\r\n    bf_start,\r\n    bf_cr = bf_start,       /* pt, cr */\r\n    bf_klm_cr,              /* pt, klm, cr */\r\n    bf_klm_tex,             /* pt, klm, tex */\r\n    bf_end = bf_klm_tex,\r\n\r\n    bs_start,\r\n    bs_coef_cr = bs_start,  /* pt, coef, cr */\r\n    bs_coef_tex,            /* pt, coef, tex */\r\n    bs_end = bs_coef_tex,\r\n};\r\n\r\nstruct bat_triangle\r\n{\r\n    lb_joint*           _joints[3];\r\n    vec2                _reduced[3];        /* get a reduced triangle so that no overlapping caused by error would be detected. */\r\n    float               _zorder;\r\n    bool                _is_reduced;\r\n\r\npublic:\r\n    bat_triangle();\r\n    bat_triangle(lb_joint* i, lb_joint* j, lb_joint* k);\r\n    ~bat_triangle() {}\r\n    void make_rect(rectf& rc) const;\r\n    void set_joint(int i, lb_joint* p) { _joints[i] = p; }\r\n    lb_joint* get_joint(int i) const { return _joints[i]; }\r\n    const vec2& get_point(int i) const { return _joints[i]->get_point(); }\r\n    void* get_lb_binding(int i) const { return _joints[i]->get_binding(); }\r\n    bat_type decide(uint brush_tag) const;\r\n    bool has_klm_coords() const;\r\n    const vec2& get_reduced_point(int i) const;\r\n    bool is_overlapped(const bat_triangle& other) const;\r\n    void ensure_make_reduced();\r\n    void set_zorder(float z) { _zorder = z; }\r\n    float get_zorder() const { return _zorder; }\r\n    void get_center(vec2& c) const;\r\n    void tracing() const;\r\n    void trace_reduced_points() const;\r\n};\r\n\r\nstruct bat_line\r\n{\r\n    vec2                _points[2];\r\n    vec2                _contourpt[4];      /* calculated contour pts */\r\n    lb_joint*           _srcjs[2];\r\n    vec3                _coef;\r\n    float               _width;\r\n    float               _zorder;\r\n    uint                _tag;               /* pen tag */\r\n    bool                _half;              /* is half line? */\r\n    bool                _recalc;            /* need recalculation? */\r\n\r\npublic:\r\n    bat_line();\r\n    void set_start_point(const vec2& p) { _points[0] = p; }\r\n    void set_end_point(const vec2& p) { _points[1] = p; }\r\n    void set_source_joint(int i, lb_joint* j) { _srcjs[i] = j; }\r\n    lb_joint* get_source_joint(int i) const { return _srcjs[i]; }\r\n    const vec2& get_start_point() const { return _points[0]; }\r\n    const vec2& get_end_point() const { return _points[1]; }\r\n    void set_pen_tag(uint t) { _tag = t; }\r\n    void setup_coef();\r\n    void set_coef(const vec3& c) { _coef = c; }\r\n    const vec3& get_coef() const { return _coef; }\r\n    void set_zorder(float z) { _zorder = z; }\r\n    float get_zorder() const { return _zorder; }\r\n    void set_line_width(float w) { _width = w; }\r\n    float get_line_width() const { return _width; }\r\n    void set_half_line(bool hl) { _half = hl; }\r\n    bool is_half_line() const { return _half; }\r\n    bat_type decide() const;\r\n    void get_bound_rect(rectf& rc) const;\r\n    int clip_triangle(bat_line output[2], const bat_triangle* triangle) const;\r\n    void calc_contour_points();\r\n    const vec2& get_contour_point(int i) const { return _contourpt[i]; }\r\n    void set_contour_point(int i, const vec2& p) { _contourpt[i] = p; }\r\n    bool set_need_recalc(bool b) { _recalc = b; }\r\n    bool need_recalc() const { return _recalc; }\r\n    void trim_contour(bat_line& line);\r\n    void tracing() const;\r\n\r\npublic:\r\n    static bat_line* create_line(lb_joint* i, lb_joint* j, float w, float z, uint t, bool half);\r\n    static bat_line* create_half_line(lb_joint* i, lb_joint* j, const vec2& p1, const vec2& p2, float w, float z, uint t);\r\n};\r\n\r\nstruct bat_batch\r\n{\r\n    bat_type            _type;\r\n\r\npublic:\r\n    bat_batch(bat_type t): _type(t) {}\r\n    virtual ~bat_batch() {}\r\n    bat_type get_type() const { return _type; }\r\n};\r\n\r\nstruct bat_fill_batch:\r\n    public bat_batch\r\n{\r\n    bat_rtree           _rtree;\r\n\r\npublic:\r\n    bat_fill_batch(bat_type t): bat_batch(t) {}\r\n    bat_rtree& get_rtree() { return _rtree; }\r\n    const bat_rtree& const_rtree() const { return _rtree; }\r\n};\r\n\r\nstruct bat_stroke_batch:\r\n    public bat_batch\r\n{\r\n    bat_lines           _lines;\r\n\r\npublic:\r\n    bat_stroke_batch(bat_type t): bat_batch(t) {}\r\n    void add_line(bat_line* p) { _lines.push_back(p); }\r\n    bat_lines& get_lines() { return _lines; }\r\n    const bat_lines& const_lines() const { return _lines; }\r\n};\r\n\r\nstruct bat_stroke_host_batch:\r\n    public bat_stroke_batch\r\n{\r\npublic:\r\n    bat_stroke_host_batch(bat_type t): bat_stroke_batch(t) {}\r\n    virtual ~bat_stroke_host_batch();\r\n};\r\n\r\nclass batch_processor\r\n{\r\npublic:\r\n    typedef bat_batches::iterator bat_iter;\r\n    typedef bat_batches::const_iterator bat_const_iter;\r\n    typedef bat_batches::reverse_iterator bat_reversed_iter;\r\n    friend class rose;\r\n\r\npublic:\r\n    batch_processor();\r\n    ~batch_processor();\r\n    void set_antialias(bool b) { _antialias = b; }\r\n    bool is_aa_enabled() const { return _antialias; }\r\n    void add_non_tex_polygon(lb_polygon* poly, float z, uint brush_tag);\r\n    bat_batch* add_tex_polygons(lb_polygon_list& polys, float z);\r\n    bat_line* add_line(lb_joint* i, lb_joint* j, float w, float z, uint pen_tag);\r\n    bat_line* add_aa_border(lb_joint* i, lb_joint* j, float z, uint pen_tag);\r\n    void finish_batching();\r\n    bat_batches& get_batches() { return _batches; }\r\n    void clear_batches();\r\n\r\nprotected:\r\n    bat_triangles       _triangles;\r\n    bat_lines           _lines;\r\n    bat_batches         _batches;\r\n    bool                _antialias;\r\n\r\nprotected:\r\n    template<class _batch>\r\n    _batch* create_batch(bat_type t);\r\n    bat_triangle* create_triangle(lb_joint* i, lb_joint* j, lb_joint* k, float z);\r\n    bat_line* create_line(lb_joint* i, lb_joint* j, float w, float z, uint t, bool half);\r\n    bat_line* create_half_line(lb_joint* i, lb_joint* j, const vec2& p1, const vec2& p2, float w, float z, uint t);\r\n    void add_triangle(lb_joint* i, lb_joint* j, lb_joint* k, bool b[3], float z, uint brush_tag);\r\n    void collect_aa_borders(bat_triangle* triangle, bool b[3], uint pen_tag);\r\n    void proceed_line_batch();\r\n    void gather_tex_triangles(bat_triangles& triangles, lb_polygon* poly, float z);\r\n    bat_batch* find_containable_tex_batch(const bat_triangles& triangles);\r\n    bat_stroke_batch* find_associated_tex_stroke_batch(const bat_batch* bat);\r\n};\r\n\r\n__ariel_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "3d91c886dd68b125ff192ec9a86cb579171ffc18", "size": 8311, "ext": "h", "lang": "C", "max_stars_repo_path": "include/ariel/batch.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/ariel/batch.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ariel/batch.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 37.269058296, "max_line_length": 131, "alphanum_fraction": 0.6624954879, "num_tokens": 2197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.02976009448379241, "lm_q1q2_score": 0.011455021787801016}}
{"text": "/* -*- linux-c -*- */\n/* triple.c\n\n   Copyright (C) 2002-2004 John M. Fregeau\n   \n   This program is free software; you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation; either version 2 of the License, or\n   (at your option) any later version.\n   \n   This program is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n   \n   You should have received a copy of the GNU General Public License\n   along with this program; if not, write to the Free Software\n   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n*/\n\n#include <stdio.h>\n#include <stddef.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <time.h>\n#include <getopt.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_rng.h>\n#include \"fewbody.h\"\n#include \"triple.h\"\n\n/* print the usage */\nvoid print_usage(FILE *stream)\n{\n\tfprintf(stream, \"USAGE:\\n\");\n\tfprintf(stream, \"  triple [options...]\\n\");\n\tfprintf(stream, \"\\n\");\n\tfprintf(stream, \"OPTIONS:\\n\");\n\tfprintf(stream, \"  -m --m000 <m000/MSUN>        : set mass of star 0 of inner binary of triple [%.6g]\\n\", FB_M000/FB_CONST_MSUN);\n\tfprintf(stream, \"  -n --m001 <m001/MSUN>        : set mass of star 1 of inner binary of triple [%.6g]\\n\", FB_M001/FB_CONST_MSUN);\n\tfprintf(stream, \"  -o --m01 <m01/MSUN>          : set mass of outer star of triple [%.6g]\\n\", FB_M01/FB_CONST_MSUN);\n\tfprintf(stream, \"  -r --r000 <r000/RSUN>        : set radius of star 0 of inner binary of triple [%.6g]\\n\", FB_R000/FB_CONST_RSUN);\n\tfprintf(stream, \"  -g --r001 <r001/RSUN>        : set radius of star 1 of inner binary of triple [%.6g]\\n\", FB_R001/FB_CONST_RSUN);\n\tfprintf(stream, \"  -i --r01 <r01/RSUN>          : set radius of outer star of triple [%.6g]\\n\", FB_R01/FB_CONST_RSUN);\n\tfprintf(stream, \"  -a --a00 <a00/AU>            : set inner semimajor axis of triple [%.6g]\\n\", FB_A00/FB_CONST_AU);\n\tfprintf(stream, \"  -Q --a0 <a0/AU>              : set outer semimajor axis of triple [%.6g]\\n\", FB_A0/FB_CONST_AU);\n\tfprintf(stream, \"  -e --e00 <e00>               : set inner eccentricity of triple [%.6g]\\n\", FB_E00);\n\tfprintf(stream, \"  -F --e0 <e0>                 : set outer eccentricity of triple [%.6g]\\n\", FB_E0);\n\tfprintf(stream, \"  -t --tstop <tstop/t_dyn>     : set stopping time [%.6g]\\n\", FB_TSTOP);\n\tfprintf(stream, \"  -D --dt <dt/t_dyn>           : set approximate output dt [%.6g]\\n\", FB_DT);\n\tfprintf(stream, \"  -c --tcpustop <tcpustop/sec> : set cpu stopping time [%.6g]\\n\", FB_TCPUSTOP);\n\tfprintf(stream, \"  -A --absacc <absacc>         : set integrator's absolute accuracy [%.6g]\\n\", FB_ABSACC);\n\tfprintf(stream, \"  -R --relacc <relacc>         : set integrator's relative accuracy [%.6g]\\n\", FB_RELACC);\n\tfprintf(stream, \"  -N --ncount <ncount>         : set number of integration steps between calls\\n\");\n\tfprintf(stream, \"                                 to fb_classify() [%d]\\n\", FB_NCOUNT);\n\tfprintf(stream, \"  -z --tidaltol <tidaltol>     : set tidal tolerance [%.6g]\\n\", FB_TIDALTOL);\n\tfprintf(stream, \"  -x --fexp <f_exp>            : set expansion factor of merger product [%.6g]\\n\", FB_FEXP);\n\tfprintf(stream, \"  -k --ks                      : turn K-S regularization on or off [%d]\\n\", FB_KS);\n\tfprintf(stream, \"  -s --seed                    : set random seed [%ld]\\n\", FB_SEED);\n\tfprintf(stream, \"  -d --debug                   : turn on debugging\\n\");\n\tfprintf(stream, \"  -V --version                 : print version info\\n\");\n\tfprintf(stream, \"  -h --help                    : display this help text\\n\");\n}\n\n/* calculate the units used */\nint calc_units(fb_obj_t *obj[1], fb_units_t *units)\n{\n\tdouble m0, m00, m01, m000, m001, a00, a0;\n\n\tm0 = obj[0]->m;\n\tm00 = obj[0]->obj[0]->m;\n\tm01 = obj[0]->obj[1]->m;\n\tm000 = obj[0]->obj[0]->obj[0]->m;\n\tm001 = obj[0]->obj[0]->obj[1]->m;\n\n\ta0 = obj[0]->a;\n\ta00 = obj[0]->obj[0]->a;\n\t\n\t/* Unit of velocity is approximate relative orbital speed of inner binary,\n\t   unit of length is semimajor axis of inner binary; \n\t   therefore, unit of time is approximately 1 inner orbital period. */\n\tunits->v = sqrt(FB_CONST_G*(m000+m001)/a00);\n\tunits->l = a00;\n\tunits->t = units->l / units->v;\n\tunits->m = units->l * fb_sqr(units->v) / FB_CONST_G;\n\tunits->E = units->m * fb_sqr(units->v);\n\t\n\treturn(0);\n}\n\n/* the main attraction */\nint main(int argc, char *argv[])\n{\n\tint i, j;\n\tunsigned long int seed;\n\tdouble m000, m001, m01, r000, r001, r01, a00, a0, e00, e0;\n\tdouble Ei, Lint[3], Li[3], t;\n\tfb_hier_t hier;\n\tfb_input_t input;\n\tfb_ret_t retval;\n\tfb_units_t units;\n\tchar string1[FB_MAX_STRING_LENGTH], string2[FB_MAX_STRING_LENGTH];\n\tgsl_rng *rng;\n\tconst gsl_rng_type *rng_type=gsl_rng_mt19937;\n\tconst char *short_opts = \"m:n:o:r:g:i:a:Q:e:F:t:D:c:A:R:N:z:x:k:s:dVh\";\n\tconst struct option long_opts[] = {\n\t\t{\"m000\", required_argument, NULL, 'm'},\n\t\t{\"m001\", required_argument, NULL, 'n'},\n\t\t{\"m01\", required_argument, NULL, 'o'},\n\t\t{\"r000\", required_argument, NULL, 'r'},\n\t\t{\"r001\", required_argument, NULL, 'g'},\n\t\t{\"r01\", required_argument, NULL, 'i'},\n\t\t{\"a00\", required_argument, NULL, 'a'},\n\t\t{\"a0\", required_argument, NULL, 'Q'},\n\t\t{\"e00\", required_argument, NULL, 'e'},\n\t\t{\"e0\", required_argument, NULL, 'F'},\n\t\t{\"tstop\", required_argument, NULL, 't'},\n\t\t{\"dt\", required_argument, NULL, 'D'},\n\t\t{\"tcpustop\", required_argument, NULL, 'c'},\n\t\t{\"absacc\", required_argument, NULL, 'A'},\n\t\t{\"relacc\", required_argument, NULL, 'R'},\n\t\t{\"ncount\", required_argument, NULL, 'N'},\n\t\t{\"tidaltol\", required_argument, NULL, 'z'},\n\t\t{\"fexp\", required_argument, NULL, 'x'},\n\t\t{\"ks\", required_argument, NULL, 'k'},\n\t\t{\"seed\", required_argument, NULL, 's'},\n\t\t{\"debug\", no_argument, NULL, 'd'},\n\t\t{\"version\", no_argument, NULL, 'V'},\n\t\t{\"help\", no_argument, NULL, 'h'},\n\t\t{NULL, 0, NULL, 0}\n\t};\n\n\t/* set parameters to default values */\n\tm000 = FB_M000;\n\tm001 = FB_M001;\n\tm01 = FB_M01;\n\tr000 = FB_R000;\n\tr001 = FB_R001;\n\tr01 = FB_R01;\n\ta00 = FB_A00;\n\ta0 = FB_A0;\n\te00 = FB_E00;\n\te0 = FB_E0;\n\tinput.ks = FB_KS;\n\tinput.tstop = FB_TSTOP;\n\tinput.Dflag = 0;\n\tinput.dt = FB_DT;\n\tinput.tcpustop = FB_TCPUSTOP;\n\tinput.absacc = FB_ABSACC;\n\tinput.relacc = FB_RELACC;\n\tinput.ncount = FB_NCOUNT;\n\tinput.tidaltol = FB_TIDALTOL;\n\tinput.fexp = FB_FEXP;\n\tseed = FB_SEED;\n\tfb_debug = FB_DEBUG;\n\t\n\twhile ((i = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1) {\n\t\tswitch (i) {\n\t\tcase 'm':\n\t\t\tm000 = atof(optarg) * FB_CONST_MSUN;\n\t\t\tbreak;\n\t\tcase 'n':\n\t\t\tm001 = atof(optarg) * FB_CONST_MSUN;\n\t\t\tbreak;\n\t\tcase 'o':\n\t\t\tm01 = atof(optarg) * FB_CONST_MSUN;\n\t\t\tbreak;\n\t\tcase 'r':\n\t\t\tr000 = atof(optarg) * FB_CONST_RSUN;\n\t\t\tbreak;\n\t\tcase 'g':\n\t\t\tr001 = atof(optarg) * FB_CONST_RSUN;\n\t\t\tbreak;\n\t\tcase 'i':\n\t\t\tr01 = atof(optarg) * FB_CONST_RSUN;\n\t\t\tbreak;\n\t\tcase 'a':\n\t\t\ta00 = atof(optarg) * FB_CONST_AU;\n\t\t\tbreak;\n\t\tcase 'Q':\n\t\t\ta0 = atof(optarg) * FB_CONST_AU;\n\t\t\tbreak;\n\t\tcase 'e':\n\t\t\te00 = atof(optarg);\n\t\t\tif (e00 >= 1.0) {\n\t\t\t\tfprintf(stderr, \"e00 must be less than 1\\n\");\n\t\t\t\treturn(1);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'F':\n\t\t\te0 = atof(optarg);\n\t\t\tif (e0 >= 1.0) {\n\t\t\t\tfprintf(stderr, \"e0 must be less than 1\\n\");\n\t\t\t\treturn(1);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 't':\n\t\t\tinput.tstop = atof(optarg);\n\t\t\tbreak;\n\t\tcase 'D':\n\t\t\tinput.Dflag = 1;\n\t\t\tinput.dt = atof(optarg);\n\t\t\tbreak;\n\t\tcase 'c':\n\t\t\tinput.tcpustop = atof(optarg);\n\t\t\tbreak;\n\t\tcase 'A':\n\t\t\tinput.absacc = atof(optarg);\n\t\t\tbreak;\n\t\tcase 'R':\n\t\t\tinput.relacc = atof(optarg);\n\t\t\tbreak;\n\t\tcase 'N':\n\t\t\tinput.ncount = atoi(optarg);\n\t\t\tbreak;\n\t\tcase 'z':\n\t\t\tinput.tidaltol = atof(optarg);\n\t\t\tbreak;\n\t\tcase 'x':\n\t\t\tinput.fexp = atof(optarg);\n\t\t\tbreak;\n\t\tcase 'k':\n\t\t\tinput.ks = atoi(optarg);\n\t\t\tbreak;\n\t\tcase 's':\n\t\t\tseed = atol(optarg);\n\t\t\tbreak;\n\t\tcase 'd':\n\t\t\tfb_debug = 1;\n\t\t\tbreak;\n\t\tcase 'V':\n\t\t\tfb_print_version(stdout);\n\t\t\treturn(0);\n\t\tcase 'h':\n\t\t\tfb_print_version(stdout);\n\t\t\tfprintf(stdout, \"\\n\");\n\t\t\tprint_usage(stdout);\n\t\t\treturn(0);\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n\t\n\t/* check to make sure there was nothing crazy on the command line */\n\tif (optind < argc) {\n\t\tprint_usage(stdout);\n\t\treturn(1);\n\t}\n\n\t/* initialize a few things for integrator */\n\tt = 0.0;\n\thier.nstarinit = 3;\n\thier.nstar = 3;\n\tfb_malloc_hier(&hier);\n\tfb_init_hier(&hier);\n\n\t/* put stuff in log entry */\n\tsnprintf(input.firstlogentry, FB_MAX_LOGENTRY_LENGTH, \"  command line:\");\n\tfor (i=0; i<argc; i++) {\n\t\tsnprintf(&(input.firstlogentry[strlen(input.firstlogentry)]), \n\t\t\t FB_MAX_LOGENTRY_LENGTH-strlen(input.firstlogentry), \" %s\", argv[i]);\n\t}\n\tsnprintf(&(input.firstlogentry[strlen(input.firstlogentry)]),\n\t\t FB_MAX_LOGENTRY_LENGTH-strlen(input.firstlogentry), \"\\n\");\n\t\n\t/* print out values of paramaters */\n\tfprintf(stderr, \"PARAMETERS:\\n\");\n\tfprintf(stderr, \"  ks=%d  seed=%ld\\n\", input.ks, seed);\n\tfprintf(stderr, \"  a00=%.6g AU  e00=%.6g  m000=%.6g MSUN  m001=%.6g MSUN  r000=%.6g RSUN  r001=%.6g RSUN\\n\", \\\n\t\ta00/FB_CONST_AU, e00, m000/FB_CONST_MSUN, m001/FB_CONST_MSUN, r000/FB_CONST_RSUN, r001/FB_CONST_RSUN);\n\tfprintf(stderr, \"  a0=%.6g AU  e0=%.6g  m01=%.6g MSUN  r01=%.6g RSUN\\n\", \\\n\t\ta0/FB_CONST_AU, e0, m01/FB_CONST_MSUN, r01/FB_CONST_RSUN);\n\tfprintf(stderr, \"  tstop=%.6g  tcpustop=%.6g\\n\", \\\n\t\tinput.tstop, input.tcpustop);\n\tfprintf(stderr, \"  tidaltol=%.6g  abs_acc=%.6g  rel_acc=%.6g  ncount=%d  fexp=%.6g\\n\\n\", \\\n\t\tinput.tidaltol, input.absacc, input.relacc, input.ncount, input.fexp);\n\n\t/* initialize GSL rng */\n\tgsl_rng_env_setup();\n\trng = gsl_rng_alloc(rng_type);\n\tgsl_rng_set(rng, seed);\n\n\t/* create hierarchies */\n\thier.narr[2] = 1;\n\thier.narr[3] = 1;\n\t/* inner binary of triple */\n\thier.hier[hier.hi[2]+0].obj[0] = &(hier.hier[hier.hi[1]+0]);\n\thier.hier[hier.hi[2]+0].obj[1] = &(hier.hier[hier.hi[1]+1]);\n\thier.hier[hier.hi[2]+0].t = t;\n\t/* outer binary of triple */\n\thier.hier[hier.hi[3]+0].obj[0] = &(hier.hier[hier.hi[2]+0]);\n\thier.hier[hier.hi[3]+0].obj[1] = &(hier.hier[hier.hi[1]+2]);\n\thier.hier[hier.hi[3]+0].t = t;\n\n\t/* give the objects some properties */\n\tfor (j=0; j<hier.nstar; j++) {\n\t\thier.hier[hier.hi[1]+j].ncoll = 1;\n\t\thier.hier[hier.hi[1]+j].id[0] = j;\n\t\tsnprintf(hier.hier[hier.hi[1]+j].idstring, FB_MAX_STRING_LENGTH, \"%d\", j);\n\t\thier.hier[hier.hi[1]+j].n = 1;\n\t\thier.hier[hier.hi[1]+j].obj[0] = NULL;\n\t\thier.hier[hier.hi[1]+j].obj[1] = NULL;\n\t\thier.hier[hier.hi[1]+j].Eint = 0.0;\n\t\thier.hier[hier.hi[1]+j].Lint[0] = 0.0;\n\t\thier.hier[hier.hi[1]+j].Lint[1] = 0.0;\n\t\thier.hier[hier.hi[1]+j].Lint[2] = 0.0;\n\t}\n\n\thier.hier[hier.hi[1]+0].R = r000;\n\thier.hier[hier.hi[1]+1].R = r001;\n\thier.hier[hier.hi[1]+2].R = r01;\n\n\thier.hier[hier.hi[1]+0].m = m000;\n\thier.hier[hier.hi[1]+1].m = m001;\n\thier.hier[hier.hi[1]+2].m = m01;\n\n\thier.hier[hier.hi[2]+0].m = m000 + m001;\n\thier.hier[hier.hi[3]+0].m = m000 + m001 + m01;\n\n\thier.hier[hier.hi[2]+0].a = a00;\n\thier.hier[hier.hi[3]+0].a = a0;\n\t\n\thier.hier[hier.hi[2]+0].e = e00;\n\thier.hier[hier.hi[3]+0].e = e0;\n\n\thier.nobj = 1;\n\thier.obj[0] = &(hier.hier[hier.hi[3]+0]);\n\thier.obj[1] = NULL;\n\thier.obj[2] = NULL;\n\n\t/* get the units and normalize */\n\tcalc_units(hier.obj, &units);\n\tfb_normalize(&hier, units);\n\t\n\t/* place triple at origin */\n\tfor (j=0; j<3; j++) {\n\t\thier.obj[0]->x[j] = 0.0;\n\t\thier.obj[0]->v[j] = 0.0;\n\t}\n\n\t/* randomize binary orientations and downsync */\n\tfb_randorient(&(hier.hier[hier.hi[3]+0]), rng);\n\tfb_downsync(&(hier.hier[hier.hi[3]+0]), t);\n\tfb_randorient(&(hier.hier[hier.hi[2]+0]), rng);\n\tfb_downsync(&(hier.hier[hier.hi[2]+0]), t);\n\n\tfprintf(stderr, \"UNITS:\\n\");\n\tfprintf(stderr, \"  v=%.6g km/s  l=%.6g AU  t=t_dyn=%.6g yr\\n\", \\\n\t\tunits.v/1.0e5, units.l/FB_CONST_AU, units.t/FB_CONST_YR);\n\tfprintf(stderr, \"  M=%.6g M_sun  E=%.6g erg\\n\\n\", units.m/FB_CONST_MSUN, units.E);\n\t\n\t/* trickle down properties (not sure if this is actually needed here, but it doesn't harm anything) */\n\tfb_trickle(&hier, t);\n\n\t/* store the initial energy and angular momentum*/\n\tEi = fb_petot(&(hier.hier[hier.hi[1]]), hier.nstar) + fb_ketot(&(hier.hier[hier.hi[1]]), hier.nstar) +\n\t\tfb_einttot(&(hier.hier[hier.hi[1]]), hier.nstar);\n\tfb_angmom(&(hier.hier[hier.hi[1]]), hier.nstar, Li);\n\tfb_angmomint(&(hier.hier[hier.hi[1]]), hier.nstar, Lint);\n\tfor (j=0; j<3; j++) {\n\t\tLi[j] += Lint[j];\n\t}\n\n\t/* integrate along */\n\tfb_dprintf(\"calling fewbody()...\\n\");\n\t\n\t/* call fewbody! */\n\tretval = fewbody(input, &hier, &t);\n\n\t/* print information to screen */\n\tfprintf(stderr, \"OUTCOME:\\n\");\n\tif (retval.retval == 1) {\n\t\tfprintf(stderr, \"  encounter complete:  t=%.6g (%.6g yr)  %s  (%s)\\n\\n\",\n\t\t\tt, t * units.t/FB_CONST_YR,\n\t\t\tfb_sprint_hier(hier, string1),\n\t\t\tfb_sprint_hier_hr(hier, string2));\n\t} else {\n\t\tfprintf(stderr, \"  encounter NOT complete:  t=%.6g (%.6g yr)  %s  (%s)\\n\\n\",\n\t\t\tt, t * units.t/FB_CONST_YR,\n\t\t\tfb_sprint_hier(hier, string1),\n\t\t\tfb_sprint_hier_hr(hier, string2));\n\t}\n\n\tfb_dprintf(\"there were %ld integration steps\\n\", retval.count);\n\tfb_dprintf(\"fb_classify() was called %ld times\\n\", retval.iclassify);\n\t\n\tfprintf(stderr, \"FINAL:\\n\");\n\tfprintf(stderr, \"  t_final=%.6g (%.6g yr)  t_cpu=%.6g s\\n\", \\\n\t\tt, t*units.t/FB_CONST_YR, retval.tcpu);\n\n\tfprintf(stderr, \"  L0=%.6g  DeltaL/L0=%.6g  DeltaL=%.6g\\n\", fb_mod(Li), retval.DeltaLfrac, retval.DeltaL);\n\tfprintf(stderr, \"  E0=%.6g  DeltaE/E0=%.6g  DeltaE=%.6g\\n\", Ei, retval.DeltaEfrac, retval.DeltaE);\n\tfprintf(stderr, \"  Rmin=%.6g (%.6g RSUN)  Rmin_i=%d  Rmin_j=%d\\n\", \\\n\t\tretval.Rmin, retval.Rmin*units.l/FB_CONST_RSUN, retval.Rmin_i, retval.Rmin_j);\n\tfprintf(stderr, \"  Nosc=%d (%s)\\n\", retval.Nosc, (retval.Nosc>=1?\"resonance\":\"non-resonance\"));\n\t\n\t/* free GSL stuff */\n\tgsl_rng_free(rng);\n\n\t/* free our own stuff */\n\tfb_free_hier(hier);\n\n\t/* done! */\n\treturn(0);\n}\n", "meta": {"hexsha": "121c82a7c67101757b39ce356a314ad15261a818", "size": 13673, "ext": "c", "lang": "C", "max_stars_repo_path": "ext/fewbod/fewbody-0.26/triple.c", "max_stars_repo_name": "gnodvi/cosmos", "max_stars_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c", "max_stars_repo_licenses": ["PSF-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ext/fewbod/fewbody-0.26/triple.c", "max_issues_repo_name": "gnodvi/cosmos", "max_issues_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c", "max_issues_repo_licenses": ["PSF-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-13T20:35:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-13T20:35:46.000Z", "max_forks_repo_path": "ext/fewbod/fewbody-0.26/triple.c", "max_forks_repo_name": "gnodvi/cosmos", "max_forks_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c", "max_forks_repo_licenses": ["PSF-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5945945946, "max_line_length": 132, "alphanum_fraction": 0.624734879, "num_tokens": 4787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681662740417, "lm_q2_score": 0.02887090882634064, "lm_q1q2_score": 0.011434847917513782}}
{"text": "/* -*- linux-c -*- */\n/* fewbody.h\n\n   Copyright (C) 2002-2004 John M. Fregeau\n   \n   This program is free software; you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation; either version 2 of the License, or\n   (at your option) any later version.\n   \n   This program is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n   \n   You should have received a copy of the GNU General Public License\n   along with this program; if not, write to the Free Software\n   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n*/\n\n#ifndef _FEWBODY_H\n#define _FEWBODY_H 1\n\n#include <stdio.h>\n#include <gsl/gsl_nan.h>\n#include <gsl/gsl_rng.h>\n\n/* version information */\n#define FB_VERSION \"0.26\"\n#define FB_NICK \"Oblivion\"\n#define FB_DATE \"Mon Sep  6 09:05:47 EDT 2010\"\n\n/* dimensionless constants */\n#define FB_CONST_PI 3.141592653589793238462643\n\n/* constants, in cgs units */\n#define FB_CONST_MSUN 1.989e+33\n#define FB_CONST_RSUN 6.9599e+10\n#define FB_CONST_C 2.99792458e+10\n#define FB_CONST_G 6.67259e-8\n#define FB_CONST_AU 1.496e+13\n#define FB_CONST_PARSEC 3.0857e+18\n#define FB_CONST_YR 3.155693e+7\n\n/* these usually shouldn't need to be changed */\n#define FB_H 1.0e-2\n#define FB_SSTOP GSL_POSINF\n#define FB_AMIN GSL_POSINF\n#define FB_RMIN GSL_POSINF\n#define FB_ROOTSOLVER_MAX_ITER 100\n#define FB_ROOTSOLVER_ABS_ACC 1.0e-11\n#define FB_ROOTSOLVER_REL_ACC 1.0e-11\n#define FB_MAX_STRING_LENGTH 2048\n#define FB_MAX_LOGENTRY_LENGTH (32 * FB_MAX_STRING_LENGTH)\n\n/* a struct containing the units used */\ntypedef struct{\n\tdouble v; /* velocity */\n\tdouble l; /* length */\n\tdouble t; /* time */\n\tdouble m; /* mass */\n\tdouble E; /* energy */\n} fb_units_t;\n\n/* the fundamental object */\ntypedef struct fb_obj{\n\tint ncoll; /* total number of stars collided together in this star */\n\tlong *id; /* numeric id array */\n\tchar idstring[FB_MAX_STRING_LENGTH]; /* string id */\n\tdouble m; /* mass */\n\tdouble R; /* radius */\n\tdouble Eint; /* internal energy (used to check energy conservation) */\n\tdouble Lint[3]; /* internal ang mom (used to check ang mom conservation) */\n\tdouble x[3]; /* position */\n\tdouble v[3]; /* velocity */\n\tint n; /* total number of stars in hierarchy */\n\tstruct fb_obj *obj[2]; /* pointers to children */\n\tdouble a; /* semimajor axis */\n\tdouble e; /* eccentricity */\n\tdouble Lhat[3]; /* angular momentum vector */\n\tdouble Ahat[3]; /* Runge-Lenz vector */\n\tdouble t; /* time at which node was upsynced */\n\tdouble mean_anom; /* mean anomaly when node was upsynced */\n} fb_obj_t;\n\n/* parameters for the K-S integrator */\ntypedef struct{\n\tint nstar; /* number of actual stars */\n\tint kstar; /* nstar*(nstar-1)/2, number of separations */\n\tdouble *m; /* m[nstar] */\n\tdouble *M; /* M[kstar] */\n\tdouble **amat; /* amat[nstar][kstar] */\n\tdouble **Tmat; /* Tmat[kstar][kstar] */\n\tdouble Einit; /* initial energy used in integration scheme */\n} fb_ks_params_t;\n\n/* parameters for the non-regularized integrator */\ntypedef struct{\n\tint nstar; /* number of actual stars */\n\tdouble *m; /* m[nstar] */\n} fb_nonks_params_t;\n\n/* the hierarchy data structure */\ntypedef struct{\n\tint nstarinit; /* initial number of stars (may not equal nstar if there are collisions) */\n\tint nstar; /* number of stars */\n\tint nobj; /* number of binary trees */\n\tint *hi; /* hierarchical index array */\n\tint *narr; /* narr[i] = number of hierarchical objects with i elements */\n\tfb_obj_t *hier; /* memory location of hierarchy information */\n\tfb_obj_t **obj; /* array of pointers to top nodes of binary trees */\n} fb_hier_t;\n\n/* input parameters */\ntypedef struct{\n\tint ks; /* 0=no regularization, 1=K-S regularization */\n\tdouble tstop; /* stopping time, in units of t_dyn */\n\tint Dflag; /* 0=don't print to stdout, 1=print to stdout */\n\tdouble dt; /* time interval between printouts will always be greater than this value */\n\tdouble tcpustop; /* cpu stopping time, in units of seconds */\n\tdouble absacc; /* absolute accuracy of the integrator */\n\tdouble relacc; /* relative accuracy of the integrator */\n\tint ncount; /* number of integration steps between each call to fb_classify() */\n\tdouble tidaltol; /* tidal tolerance */\n\tchar firstlogentry[FB_MAX_LOGENTRY_LENGTH]; /* first entry to put in printout log */\n\tdouble fexp; /* expansion factor for a merger product: R = f_exp (R_1+R_2) */\n} fb_input_t;\n\n/* return parameters */\ntypedef struct{\n\tlong count; /* number of integration steps */\n\tint retval; /* return value; 1=success, 0=failure */\n\tlong iclassify; /* number of times classify was called */\n\tdouble tcpu; /* cpu time taken */\n\tdouble DeltaE; /* change in energy */\n\tdouble DeltaEfrac; /* change in energy, as a fraction of initial energy */\n\tdouble DeltaL; /* change in ang. mom. */\n\tdouble DeltaLfrac; /* change in ang. mom., as a fraction of initial ang. mom. */\n\tdouble Rmin; /* minimum distance of close approach during interaction */\n\tint Rmin_i; /* index of star i participating in minimum close approach */\n\tint Rmin_j; /* index of star j participating in minimum close approach */\n\tint Nosc; /* number of oscillations of the quantity s^2 (McMillan & Hut 1996) (Nosc=Nmin-1, so resonance if Nosc>=1) */\n} fb_ret_t;\n\n/* fewbody.c */\nfb_ret_t fewbody(fb_input_t input, fb_hier_t *hier, double *t);\n\n/* fewbody_classify.c */\nint fb_classify(fb_hier_t *hier, double t, double tidaltol);\nint fb_is_stable(fb_obj_t *obj);\nint fb_is_stable_binary(fb_obj_t *obj);\nint fb_is_stable_triple(fb_obj_t *obj);\nint fb_is_stable_quad(fb_obj_t *obj);\nint fb_mardling(fb_obj_t *obj, int ib, int is);\n\n/* fewbody_coll.c */\nint fb_is_collision(double r, double R1, double R2);\nint fb_collide(fb_hier_t *hier, double f_exp);\nvoid fb_merge(fb_obj_t *obj1, fb_obj_t *obj2, int nstarinit, double f_exp);\n\n/* fewbody_hier.c */\nvoid fb_malloc_hier(fb_hier_t *hier);\nvoid fb_init_hier(fb_hier_t *hier);\nvoid fb_free_hier(fb_hier_t hier);\nvoid fb_trickle(fb_hier_t *hier, double t);\nvoid fb_elkcirt(fb_hier_t *hier, double t);\nint fb_create_indices(int *hi, int nstar);\nint fb_n_hier(fb_obj_t *obj);\nchar *fb_sprint_hier(fb_hier_t hier, char string[FB_MAX_STRING_LENGTH]);\nchar *fb_sprint_hier_hr(fb_hier_t hier, char string[FB_MAX_STRING_LENGTH]);\nvoid fb_upsync(fb_obj_t *obj, double t);\nvoid fb_randorient(fb_obj_t *obj, gsl_rng *rng);\nvoid fb_downsync(fb_obj_t *obj, double t);\nvoid fb_objcpy(fb_obj_t *obj1, fb_obj_t *obj2);\n\n/* fewbody_int.c */\nvoid fb_malloc_ks_params(fb_ks_params_t *ks_params);\nvoid fb_init_ks_params(fb_ks_params_t *ks_params, fb_hier_t hier);\nvoid fb_free_ks_params(fb_ks_params_t ks_params);\nvoid fb_malloc_nonks_params(fb_nonks_params_t *nonks_params);\nvoid fb_init_nonks_params(fb_nonks_params_t *nonks_params, fb_hier_t hier);\nvoid fb_free_nonks_params(fb_nonks_params_t nonks_params);\n\n/* fewbody_io.c */\nvoid fb_print_version(FILE *stream);\nvoid fb_print_story(fb_obj_t *star, int nstar, double t, char *logentry);\n\n/* fewbody_isolate.c */\nint fb_collapse(fb_hier_t *hier, double t, double tidaltol);\nint fb_expand(fb_hier_t *hier, double t, double tidaltol);\n\n/* fewbody_ks.c */\ndouble fb_ks_dot(double x[4], double y[4]);\ndouble fb_ks_mod(double x[4]);\nvoid fb_calc_Q(double q[4], double Q[4]);\nvoid fb_calc_ksmat(double Q[4], double Qmat[4][4]);\nvoid fb_calc_amat(double **a, int nstar, int kstar);\nvoid fb_calc_Tmat(double **a, double *m, double **T, int nstar, int kstar);\nint fb_ks_func(double s, const double *y, double *f, void *params);\ndouble fb_ks_Einit(const double *y, fb_ks_params_t params);\nvoid fb_euclidean_to_ks(fb_obj_t **star, double *y, int nstar, int kstar);\nvoid fb_ks_to_euclidean(double *y, fb_obj_t **star, int nstar, int kstar);\n\n/* fewbody_nonks.c */\nint fb_nonks_func(double t, const double *y, double *f, void *params);\nint fb_nonks_jac(double t, const double *y, double *dfdy, double *dfdt, void *params);\nvoid fb_euclidean_to_nonks(fb_obj_t **star, double *y, int nstar);\nvoid fb_nonks_to_euclidean(double *y, fb_obj_t **star, int nstar);\n\n/* fewbody_scat.c */\nvoid fb_init_scattering(fb_obj_t *obj0, fb_obj_t *obj1, double vinf, double b, double rtid);\nvoid fb_normalize(fb_hier_t *hier, fb_units_t units);\n\n/* fewbody_utils.c */\ndouble *fb_malloc_vector(int n);\ndouble **fb_malloc_matrix(int nr, int nc);\nvoid fb_free_vector(double *v);\nvoid fb_free_matrix(double **m);\ndouble fb_sqr(double x);\ndouble fb_cub(double x);\ndouble fb_dot(double x[3], double y[3]);\ndouble fb_mod(double x[3]);\nint fb_cross(double x[3], double y[3], double z[3]);\nint fb_angmom(fb_obj_t *star, int nstar, double L[3]);\nvoid fb_angmomint(fb_obj_t *star, int nstar, double L[3]);\ndouble fb_einttot(fb_obj_t *star, int nstar);\ndouble fb_petot(fb_obj_t *star, int nstar);\ndouble fb_ketot(fb_obj_t *star, int nstar);\ndouble fb_outerpetot(fb_obj_t **obj, int nobj);\ndouble fb_outerketot(fb_obj_t **obj, int nobj);\ndouble fb_kepler(double e, double mean_anom);\ndouble fb_keplerfunc(double mean_anom, void *params);\ndouble fb_reltide(fb_obj_t *bin, fb_obj_t *single, double r);\n\n/* fewbody_ui.c */\nint fbui_new_hier(fb_hier_t *hier, int n);\nint fbui_delete_hier(fb_hier_t *hier);\nfb_obj_t *fbui_hierarchy_element(fb_hier_t *hier, int n, int m);\nfb_obj_t *fbui_hierarchy_single(fb_hier_t *hier, int m);\nfb_obj_t *fbui_hierarchy_binary(fb_hier_t *hier, int m);\nfb_obj_t *fbui_hierarchy_triple(fb_hier_t *hier, int m);\nfb_obj_t *fbui_hierarchy_quadruple(fb_hier_t *hier, int m);\nfb_obj_t *fbui_hierarchy_quintuple(fb_hier_t *hier, int m);\nfb_obj_t *fbui_hierarchy_sextuple(fb_hier_t *hier, int m);\nfb_obj_t *fbui_hierarchy_septuple(fb_hier_t *hier, int m);\nfb_obj_t *fbui_hierarchy_octuple(fb_hier_t *hier, int m);\nfb_obj_t *fbui_hierarchy_nonuple(fb_hier_t *hier, int m);\nfb_obj_t *fbui_hierarchy_decuple(fb_hier_t *hier, int m);\nint fbui_make_pair(fb_obj_t *parentobj, fb_obj_t *obj1, fb_obj_t *obj2);\nint fbui_initialize_single(fb_obj_t *single, long id, char idstring[FB_MAX_STRING_LENGTH]);\nfb_obj_t *fbui_tree(fb_hier_t *hier, int n);\nint fbui_obj_ncoll_set(fb_obj_t *obj, int ncoll);\nint fbui_obj_ncoll_get(fb_obj_t *obj);\nint fbui_obj_id_set(fb_obj_t *obj, int index, long id);\nlong fbui_obj_id_get(fb_obj_t *obj, int index);\nint fbui_obj_idstring_set(fb_obj_t *obj, char idstring[FB_MAX_STRING_LENGTH]);\nchar *fbui_obj_idstring_get(fb_obj_t *obj);\nint fbui_obj_mass_set(fb_obj_t *obj, double mass);\ndouble fbui_obj_mass_get(fb_obj_t *obj);\nint fbui_obj_radius_set(fb_obj_t *obj, double radius);\ndouble fbui_obj_radius_get(fb_obj_t *obj);\nint fbui_obj_Eint_set(fb_obj_t *obj, double Eint);\ndouble fbui_obj_Eint_get(fb_obj_t *obj);\nint fbui_obj_Lint_set(fb_obj_t *obj, double Lint[3]);\nint fbui_obj_Linti_set(fb_obj_t *obj, double Lint0, double Lint1, double Lint2);\ndouble *fbui_obj_Lint_get(fb_obj_t *obj);\nint fbui_obj_x_set(fb_obj_t *obj, double x[3]);\nint fbui_obj_xi_set(fb_obj_t *obj, double x0, double x1, double x2);\ndouble *fbui_obj_x_get(fb_obj_t *obj);\nint fbui_obj_v_set(fb_obj_t *obj, double v[3]);\nint fbui_obj_vi_set(fb_obj_t *obj, double v0, double v1, double v2);\ndouble *fbui_obj_v_get(fb_obj_t *obj);\nint fbui_obj_n_set(fb_obj_t *obj, int n);\nint fbui_obj_n_get(fb_obj_t *obj);\nint fbui_obj_obj_set(fb_obj_t *obj, int i, fb_obj_t *objtopointto);\nint fbui_obj_left_child_set(fb_obj_t *obj, fb_obj_t *objtopointto);\nint fbui_obj_right_child_set(fb_obj_t *obj, fb_obj_t *objtopointto);\nfb_obj_t *fbui_obj_obj_get(fb_obj_t *obj, int i);\nfb_obj_t *fbui_obj_left_child_get(fb_obj_t *obj);\nfb_obj_t *fbui_obj_right_child_get(fb_obj_t *obj);\nint fbui_obj_a_set(fb_obj_t *obj, double a);\ndouble fbui_obj_a_get(fb_obj_t *obj);\nint fbui_obj_e_set(fb_obj_t *obj, double e);\ndouble fbui_obj_e_get(fb_obj_t *obj);\nint fbui_obj_Lhat_set(fb_obj_t *obj, double Lhat[3]);\nint fbui_obj_Lhati_set(fb_obj_t *obj, double Lhat0, double Lhat1, double Lhat2);\ndouble *fbui_obj_Lhat_get(fb_obj_t *obj);\nint fbui_obj_Ahat_set(fb_obj_t *obj, double Ahat[3]);\nint fbui_obj_Ahati_set(fb_obj_t *obj, double Ahat0, double Ahat1, double Ahat2);\ndouble *fbui_obj_Ahat_get(fb_obj_t *obj);\nint fbui_obj_t_set(fb_obj_t *obj, double t);\ndouble fbui_obj_t_get(fb_obj_t *obj);\nint fbui_obj_mean_anom_set(fb_obj_t *obj, double mean_anom);\ndouble fbui_obj_mean_anom_get(fb_obj_t *obj);\n\n/* macros */\n/* The variadic macro syntax here conforms to the C99 standard, but for some\n   reason won't compile on Mac OSX with gcc. */\n/* #define fb_dprintf(...) if (fb_debug) fprintf(stderr, __VA_ARGS__) */\n/* The variadic macro syntax here is the old gcc standard, and compiles on\n   Mac OSX with gcc. */\n#define fb_dprintf(args...) if (fb_debug) fprintf(stderr, args)\n#define FB_MIN(a, b) ((a)<=(b)?(a):(b))\n#define FB_MAX(a, b) ((a)>=(b)?(a):(b))\n#define FB_DELTA(i, j) ((i)==(j)?1:0)\n#define FB_KS_K(i, j, nstar) ((i)*(nstar)-((i)+1)*((i)+2)/2+(j))\n\n/* there is just one global variable */\nextern int fb_debug;\n\n#endif /* fewbody.h */\n", "meta": {"hexsha": "a4b4a5dcef440b54f73a6fa2831aca74a7887d88", "size": 12990, "ext": "h", "lang": "C", "max_stars_repo_path": "ext/fewbod/fewbody-0.26/fewbody.h", "max_stars_repo_name": "gnodvi/cosmos", "max_stars_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c", "max_stars_repo_licenses": ["PSF-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ext/fewbod/fewbody-0.26/fewbody.h", "max_issues_repo_name": "gnodvi/cosmos", "max_issues_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c", "max_issues_repo_licenses": ["PSF-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-13T20:35:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-13T20:35:46.000Z", "max_forks_repo_path": "ext/fewbod/fewbody-0.26/fewbody.h", "max_forks_repo_name": "gnodvi/cosmos", "max_forks_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c", "max_forks_repo_licenses": ["PSF-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.6346153846, "max_line_length": 120, "alphanum_fraction": 0.7469591994, "num_tokens": 3867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.024053552938151732, "lm_q1q2_score": 0.011369717027879186}}
{"text": "/* -*- linux-c -*- */\n/* cluster.c\n\n   Copyright (C) 2002-2004 John M. Fregeau\n   \n   This program is free software; you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation; either version 2 of the License, or\n   (at your option) any later version.\n   \n   This program is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n   \n   You should have received a copy of the GNU General Public License\n   along with this program; if not, write to the Free Software\n   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n*/\n\n#include <stdio.h>\n#include <stddef.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <time.h>\n#include <getopt.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_roots.h>\n#include \"fewbody.h\"\n#include \"cluster.h\"\n\n/* print the usage */\nvoid print_usage(FILE *stream)\n{\n\tfprintf(stream, \"USAGE:\\n\");\n\tfprintf(stream, \"  cluster [options...]\\n\");\n\tfprintf(stream, \"\\n\");\n\tfprintf(stream, \"OPTIONS:\\n\");\n\tfprintf(stream, \"  -n --n <n>                    : set number of stars in cluster [%d]\\n\", FB_N);\n\tfprintf(stream, \"  -m --m <m/MSUN>               : set mass of each star [%.6g]\\n\", FB_M/FB_CONST_MSUN);\n\tfprintf(stream, \"  -r --r <r/RSUN>               : set radius of each star [%.6g]\\n\", FB_R/FB_CONST_RSUN);\n\tfprintf(stream, \"  -S --sigma <sigma/(km/s)>     : set central velocity dispersion [%.6g]\\n\", FB_SIGMA/1.0e5);\n\tfprintf(stream, \"  -T --rmax <rmax/PARSEC>       : set truncation radius [%.6g]\\n\", FB_RMAX/FB_CONST_PARSEC);\n\tfprintf(stream, \"  -t --tstop <tstop/t_dyn>      : set stopping time [%.6g]\\n\", FB_TSTOP);\n\tfprintf(stream, \"  -P --tphysstop <tphysstop/yr> : set physical stopping time [%.6g]\\n\", FB_TPHYSSTOP/FB_CONST_YR);\n\tfprintf(stream, \"  -D --dt <dt/t_dyn>            : set approximate output dt [%.6g]\\n\", FB_DT);\n\tfprintf(stream, \"  -c --tcpustop <tcpustop/sec>  : set cpu stopping time [%.6g]\\n\", FB_TCPUSTOP);\n\tfprintf(stream, \"  -A --absacc <absacc>          : set integrator's absolute accuracy [%.6g]\\n\", FB_ABSACC);\n\tfprintf(stream, \"  -R --relacc <relacc>          : set integrator's relative accuracy [%.6g]\\n\", FB_RELACC);\n\tfprintf(stream, \"  -N --ncount <ncount>          : set number of integration steps between calls\\n\");\n\tfprintf(stream, \"                                  to fb_classify() [%d]\\n\", FB_NCOUNT);\n\tfprintf(stream, \"  -z --tidaltol <tidaltol>      : set tidal tolerance [%.6g]\\n\", FB_TIDALTOL);\n\tfprintf(stream, \"  -x --fexp <f_exp>             : set expansion factor of merger product [%.6g]\\n\", FB_FEXP);\n\tfprintf(stream, \"  -k --ks                       : turn K-S regularization on or off [%d]\\n\", FB_KS);\n\tfprintf(stream, \"  -s --seed                     : set random seed [%ld]\\n\", FB_SEED);\n\tfprintf(stream, \"  -d --debug                    : turn on debugging\\n\");\n\tfprintf(stream, \"  -V --version                  : print version info\\n\");\n\tfprintf(stream, \"  -h --help                     : display this help text\\n\");\n}\n\n/* calculate the units used (N-body units) */\nvoid calc_units(fb_hier_t hier, fb_units_t *units)\n{\n\tint i, j, k;\n\tdouble petot, ketot, r[3];\n\n\t/* the unit of mass is defined so that M_tot=1 */\n\tunits->m = 0.0;\n\tfor (i=0; i<hier.nstar; i++) {\n\t\tunits->m += hier.hier[hier.hi[1]+i].m;\n\t}\n\n\t/* calculate total potential and kinetic energy */\n\tpetot = 0.0;\n\tfor (i=0; i<hier.nstar-1; i++) {\n\t\tfor (j=i+1; j<hier.nstar; j++) {\n\t\t\tfor (k=0; k<3; k++) {\n\t\t\t\tr[k] = hier.hier[hier.hi[1]+j].x[k] - hier.hier[hier.hi[1]+i].x[k];\n\t\t\t}\n\t\t\tpetot += - FB_CONST_G * hier.hier[hier.hi[1]+i].m * hier.hier[hier.hi[1]+j].m / fb_mod(r);\n\t\t}\n\t}\n\n\tketot = 0.0;\n\tfor (i=0; i<hier.nstar; i++) {\n\t\tketot += 0.5 * hier.hier[hier.hi[1]+i].m * fb_dot(hier.hier[hier.hi[1]+i].v, hier.hier[hier.hi[1]+i].v);\n\t}\n\t\n\t/* the unit of energy is defined so that E=-1/4 */\n\tunits->E = -4.0 * (petot + ketot);\n\t\n\t/* with G=1, all other units are derived */\n\tunits->t = FB_CONST_G * pow(units->m, 2.5) * pow(units->E, -1.5);\n\tunits->l = FB_CONST_G * fb_sqr(units->m) / units->E;\n\tunits->v = units->l / units->t;\n}\n\n/* f_0-f(v/v_esc) for the Plummer model */\ndouble fv(double v, void *params)\n{\n\tdouble f;\n\t\n\tf = ((double *)params)[0];\n\treturn(f - 512.0/(7.0*FB_CONST_PI) * (sqrt(1.0-fb_sqr(v))*(-7.0*v/256.0 + 121.0*fb_cub(v)/384.0 - 263.0*fb_sqr(v)*fb_cub(v)/480.0 + 31.0*v*fb_sqr(fb_cub(v))/80.0 - fb_cub(fb_cub(v))/10.0) + 7.0*asin(v)/256.0));\n}\n\n/* get speed from Plummer distribution */\ndouble vf(double f)\n{\n\tint status, iter;\n\tdouble v, params[1];\n\tgsl_function F;\n\tconst gsl_root_fsolver_type *T;\n\tgsl_root_fsolver *s;\n\t\n\t/* set up the root solver */\n\tF.function = &fv;\n\tF.params = &params;\n\n\t/* set the parameters */\n\tparams[0] = f;\n\n\tT = gsl_root_fsolver_brent;\n\ts = gsl_root_fsolver_alloc(T);\n\tgsl_root_fsolver_set(s, &F, 0.0, 1.0);\n\t\n\t/* get v/v_esc by root-finding */\n\titer = 0;\n\tdo {\n\t\titer++;\n\t\tgsl_root_fsolver_iterate(s);\n\t\tstatus = gsl_root_test_interval(gsl_root_fsolver_x_lower(s), gsl_root_fsolver_x_upper(s), \\\n\t\t\t\t\t\tFB_ROOTSOLVER_ABS_ACC, FB_ROOTSOLVER_REL_ACC);\n\t} while (status == GSL_CONTINUE && iter < FB_ROOTSOLVER_MAX_ITER);\n\n\tif (iter >= FB_ROOTSOLVER_MAX_ITER) {\n\t\tfprintf(stderr, \"Root finder failed to converge.\\n\");\n\t\texit(1);\n\t}\n\n\t/* we've got the root */\n\tv = gsl_root_fsolver_root(s);\n\t\n\t/* free memory associated with root solver */\n\tgsl_root_fsolver_free(s);\n\n\treturn(v);\n}\n\n/* the main attraction */\nint main(int argc, char *argv[])\n{\n\tint i, j, n;\n\tunsigned long int seed;\n\tdouble tphysstop, m, r, Ei, Li[3], Lint[3], t, M, a, sigma, rmax, Xmax, radius, v, theta, phi, xcm[3], vcm[3];\n\tfb_hier_t hier;\n\tfb_input_t input;\n\tfb_ret_t retval;\n\tfb_units_t units;\n\tchar string1[FB_MAX_STRING_LENGTH], string2[FB_MAX_STRING_LENGTH];\n\tgsl_rng *rng;\n\tconst gsl_rng_type *rng_type=gsl_rng_mt19937;\n\tconst char *short_opts = \"n:m:r:S:T:t:P:D:c:A:R:N:z:x:k:s:dVh\";\n\tconst struct option long_opts[] = {\n\t\t{\"n\", required_argument, NULL, 'n'},\n\t\t{\"m\", required_argument, NULL, 'm'},\n\t\t{\"r\", required_argument, NULL, 'r'},\n\t\t{\"sigma\", required_argument, NULL, 'S'},\n\t\t{\"rmax\", required_argument, NULL, 'T'},\n\t\t{\"tstop\", required_argument, NULL, 't'},\n\t\t{\"tphysstop\", required_argument, NULL, 'P'},\n\t\t{\"dt\", required_argument, NULL, 'D'},\n\t\t{\"tcpustop\", required_argument, NULL, 'c'},\n\t\t{\"absacc\", required_argument, NULL, 'A'},\n\t\t{\"relacc\", required_argument, NULL, 'R'},\n\t\t{\"ncount\", required_argument, NULL, 'N'},\n\t\t{\"tidaltol\", required_argument, NULL, 'z'},\n\t\t{\"fexp\", required_argument, NULL, 'x'},\n\t\t{\"ks\", required_argument, NULL, 'k'},\n\t\t{\"seed\", required_argument, NULL, 's'},\n\t\t{\"debug\", no_argument, NULL, 'd'},\n\t\t{\"version\", no_argument, NULL, 'V'},\n\t\t{\"help\", no_argument, NULL, 'h'},\n\t\t{NULL, 0, NULL, 0}\n\t};\n\n\t/* set parameters to default values */\n\tn = FB_N;\n\tm = FB_M;\n\tr = FB_R;\n\tsigma = FB_SIGMA;\n\trmax = FB_RMAX;\n\tinput.ks = FB_KS;\n\tinput.tstop = FB_TSTOP;\n\ttphysstop = FB_TPHYSSTOP;\n\tinput.Dflag = 0;\n\tinput.dt = FB_DT;\n\tinput.tcpustop = FB_TCPUSTOP;\n\tinput.absacc = FB_ABSACC;\n\tinput.relacc = FB_RELACC;\n\tinput.ncount = FB_NCOUNT;\n\tinput.tidaltol = FB_TIDALTOL;\n\tinput.fexp = FB_FEXP;\n\tseed = FB_SEED;\n\tfb_debug = FB_DEBUG;\n\t\n\twhile ((i = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1) {\n\t\tswitch (i) {\n\t\tcase 'n':\n\t\t\tn = atoi(optarg);\n\t\t\tbreak;\n\t\tcase 'm':\n\t\t\tm = atof(optarg) * FB_CONST_MSUN;\n\t\t\tbreak;\n\t\tcase 'r':\n\t\t\tr = atof(optarg) * FB_CONST_RSUN;\n\t\t\tbreak;\n\t\tcase 'S':\n\t\t\tsigma = atof(optarg) * 1.0e5;\n\t\t\tbreak;\n\t\tcase 'T':\n\t\t\trmax = atof(optarg) * FB_CONST_PARSEC;\n\t\t\tbreak;\n\t\tcase 't':\n\t\t\tinput.tstop = atof(optarg);\n\t\t\tbreak;\n\t\tcase 'P':\n\t\t\ttphysstop = atof(optarg) * FB_CONST_YR;\n\t\t\tbreak;\n\t\tcase 'D':\n\t\t\tinput.Dflag = 1;\n\t\t\tinput.dt = atof(optarg);\n\t\t\tbreak;\n\t\tcase 'c':\n\t\t\tinput.tcpustop = atof(optarg);\n\t\t\tbreak;\n\t\tcase 'A':\n\t\t\tinput.absacc = atof(optarg);\n\t\t\tbreak;\n\t\tcase 'R':\n\t\t\tinput.relacc = atof(optarg);\n\t\t\tbreak;\n\t\tcase 'N':\n\t\t\tinput.ncount = atoi(optarg);\n\t\t\tbreak;\n\t\tcase 'z':\n\t\t\tinput.tidaltol = atof(optarg);\n\t\t\tbreak;\n\t\tcase 'x':\n\t\t\tinput.fexp = atof(optarg);\n\t\t\tbreak;\n\t\tcase 'k':\n\t\t\tinput.ks = atoi(optarg);\n\t\t\tbreak;\n\t\tcase 's':\n\t\t\tseed = atol(optarg);\n\t\t\tbreak;\n\t\tcase 'd':\n\t\t\tfb_debug = 1;\n\t\t\tbreak;\n\t\tcase 'V':\n\t\t\tfb_print_version(stdout);\n\t\t\treturn(0);\n\t\tcase 'h':\n\t\t\tfb_print_version(stdout);\n\t\t\tfprintf(stdout, \"\\n\");\n\t\t\tprint_usage(stdout);\n\t\t\treturn(0);\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n\t\n\t/* check to make sure there was nothing crazy on the command line */\n\tif (optind < argc) {\n\t\tprint_usage(stdout);\n\t\treturn(1);\n\t}\n\n\t/* set up parameters for Plummer model */\n\tM = ((double) n) * m;\n\ta = FB_CONST_G * M / (6.0*fb_sqr(sigma));\n\tXmax = pow(1.0+fb_sqr(a/rmax), -1.5);\n\t\n\t/* initialize a few things for integrator */\n\tt = 0.0;\n\thier.nstarinit = n;\n\thier.nstar = n;\n\tfb_malloc_hier(&hier);\n\tfb_init_hier(&hier);\n\n\t/* put stuff in log entry */\n\tsnprintf(input.firstlogentry, FB_MAX_LOGENTRY_LENGTH, \"  command line:\");\n\tfor (i=0; i<argc; i++) {\n\t\tsnprintf(&(input.firstlogentry[strlen(input.firstlogentry)]), \n\t\t\t FB_MAX_LOGENTRY_LENGTH-strlen(input.firstlogentry), \" %s\", argv[i]);\n\t}\n\tsnprintf(&(input.firstlogentry[strlen(input.firstlogentry)]),\n\t\t FB_MAX_LOGENTRY_LENGTH-strlen(input.firstlogentry), \"\\n\");\n\t\n\t/* print out values of paramaters */\n\tfprintf(stderr, \"PARAMETERS:\\n\");\n\tfprintf(stderr, \"  ks=%d  seed=%ld\\n\", input.ks, seed);\n\tfprintf(stderr, \"  M=%.6g MSUN  sigma=%.6g km/s  a=%.6g PARSEC  rmax=%.6g PARSEC  rmax/a=%.6g\\n\",\n\t\tM/FB_CONST_MSUN, sigma/1.0e5, a/FB_CONST_PARSEC, rmax/FB_CONST_PARSEC, rmax/a);\n\tfprintf(stderr, \"  n=%d  m=%.6g MSUN  r=%.6g RSUN  tstop=%.6g  tphysstop=%.6g yr  tcpustop=%.6g\\n\", \\\n\t\tn, m/FB_CONST_MSUN, r/FB_CONST_RSUN, input.tstop, tphysstop/FB_CONST_YR, input.tcpustop);\n\tfprintf(stderr, \"  tidaltol=%.6g  abs_acc=%.6g  rel_acc=%.6g  ncount=%d  fexp=%.6g\\n\\n\", \\\n\t\tinput.tidaltol, input.absacc, input.relacc, input.ncount, input.fexp);\n\n\t/* initialize GSL rng */\n\tgsl_rng_env_setup();\n\trng = gsl_rng_alloc(rng_type);\n\tgsl_rng_set(rng, seed);\n\n\t/* prepare to calculate the center of mass position and velocity */\n\tfor (i=0; i<3; i++) {\n\t\txcm[i] = 0.0;\n\t\tvcm[i] = 0.0;\n\t}\n\n\t/* give the objects some properties */\n\tfor (j=0; j<hier.nstar; j++) {\n\t\thier.hier[hier.hi[1]+j].ncoll = 1;\n\t\thier.hier[hier.hi[1]+j].id[0] = j;\n\t\tsnprintf(hier.hier[hier.hi[1]+j].idstring, FB_MAX_STRING_LENGTH, \"%d\", j);\n\t\thier.hier[hier.hi[1]+j].n = 1;\n\t\thier.hier[hier.hi[1]+j].obj[0] = NULL;\n\t\thier.hier[hier.hi[1]+j].obj[1] = NULL;\n\t\thier.hier[hier.hi[1]+j].Eint = 0.0;\n\t\thier.hier[hier.hi[1]+j].Lint[0] = 0.0;\n\t\thier.hier[hier.hi[1]+j].Lint[1] = 0.0;\n\t\thier.hier[hier.hi[1]+j].Lint[2] = 0.0;\n\t\thier.hier[hier.hi[1]+j].m = m;\n\t\thier.hier[hier.hi[1]+j].R = r;\n\t\t\n\t\t/* draw radius from Plummer distribution */\n\t\tradius = a / sqrt(pow(Xmax*gsl_rng_uniform(rng), -2.0/3.0)-1.0);\n\t\ttheta = acos(2.0 * gsl_rng_uniform(rng) - 1.0);\n\t\tphi = 2.0 * FB_CONST_PI * gsl_rng_uniform(rng);\n\t\thier.hier[hier.hi[1]+j].x[0] = radius * sin(theta) * cos(phi);\n\t\thier.hier[hier.hi[1]+j].x[1] = radius * sin(theta) * sin(phi);\n\t\thier.hier[hier.hi[1]+j].x[2] = radius * cos(theta);\n\n\t\t/* draw velocity from Plummer distribution */\n\t\tv = vf(gsl_rng_uniform(rng)) * sqrt(2.0*FB_CONST_G*M/(a*sqrt(1.0+fb_sqr(radius/a))));\n\t\ttheta = acos(2.0 * gsl_rng_uniform(rng) - 1.0);\n\t\tphi = 2.0 * FB_CONST_PI * gsl_rng_uniform(rng);\n\t\thier.hier[hier.hi[1]+j].v[0] = v * sin(theta) * cos(phi);\n\t\thier.hier[hier.hi[1]+j].v[1] = v * sin(theta) * sin(phi);\n\t\thier.hier[hier.hi[1]+j].v[2] = v * cos(theta);\n\t\t\n\t\t/* calculate center of mass position and velocity */\n\t\tfor (i=0; i<3; i++) {\n\t\t\txcm[i] += hier.hier[hier.hi[1]+j].x[i] / ((double) n);\n\t\t\tvcm[i] += hier.hier[hier.hi[1]+j].v[i] / ((double) n);\n\t\t}\n\t}\n\t\n\t/* transform to center of mass frame */\n\tfor (j=0; j<hier.nstar; j++) {\n\t\tfor (i=0; i<3; i++) {\n\t\t\thier.hier[hier.hi[1]+j].x[i] -= xcm[i];\n\t\t\thier.hier[hier.hi[1]+j].v[i] -= vcm[i];\n\t\t}\n\t}\n\n\t/* get the units and normalize */\n\tcalc_units(hier, &units);\n\tfb_normalize(&hier, units);\n\t\n\t/* reset input.tstop if necessary, based on the value of tphysstop */\n\tif (tphysstop/units.t < input.tstop) {\n\t\tinput.tstop = tphysstop/units.t;\n\t\tfb_dprintf(\"decreasing tstop in accord with tphysstop: tstop=%.6g\\n\", input.tstop);\n\t}\n\n\tfb_dprintf(\"virial ratio: q=%.6g\\n\", -fb_ketot(&(hier.hier[hier.hi[1]]), hier.nstar)/fb_petot(&(hier.hier[hier.hi[1]]), hier.nstar));\n\n\tfprintf(stderr, \"UNITS:\\n\");\n\tfprintf(stderr, \"  v=%.6g km/s  l=%.6g AU  t=t_dyn=%.6g yr\\n\", \\\n\t\tunits.v/1.0e5, units.l/FB_CONST_AU, units.t/FB_CONST_YR);\n\tfprintf(stderr, \"  M=%.6g M_sun  E=%.6g erg\\n\\n\", units.m/FB_CONST_MSUN, units.E);\n\n\t/* calculate the initial energy and angular momentum, for bookkeeping */\n\tEi = fb_petot(&(hier.hier[hier.hi[1]]), hier.nstar) + fb_ketot(&(hier.hier[hier.hi[1]]), hier.nstar) +\n\t\tfb_einttot(&(hier.hier[hier.hi[1]]), hier.nstar);\n\tfb_angmom(&(hier.hier[hier.hi[1]]), hier.nstar, Li);\n\tfb_angmomint(&(hier.hier[hier.hi[1]]), hier.nstar, Lint);\n\tfor (j=0; j<3; j++) {\n\t\tLi[j] += Lint[j];\n\t}\n\n\t/* integrate along */\n\tfb_dprintf(\"calling fewbody()...\\n\");\n\t\n\t/* call fewbody! */\n\tretval = fewbody(input, &hier, &t);\n\n\t/* print information to screen */\n\tfprintf(stderr, \"OUTCOME:\\n\");\n\tif (retval.retval == 1) {\n\t\tfprintf(stderr, \"  encounter complete:  t=%.6g (%.6g yr)  %s  (%s)\\n\\n\",\n\t\t\tt, t * units.t/FB_CONST_YR,\n\t\t\tfb_sprint_hier(hier, string1),\n\t\t\tfb_sprint_hier_hr(hier, string2));\n\t} else {\n\t\tfprintf(stderr, \"  encounter NOT complete:  t=%.6g (%.6g yr)  %s  (%s)\\n\\n\",\n\t\t\tt, t * units.t/FB_CONST_YR,\n\t\t\tfb_sprint_hier(hier, string1),\n\t\t\tfb_sprint_hier_hr(hier, string2));\n\t}\n\n\tfb_dprintf(\"there were %ld integration steps\\n\", retval.count);\n\tfb_dprintf(\"fb_classify() was called %ld times\\n\", retval.iclassify);\n\t\n\tfprintf(stderr, \"FINAL:\\n\");\n\tfprintf(stderr, \"  t_final=%.6g (%.6g yr)  t_cpu=%.6g s\\n\", \\\n\t\tt, t*units.t/FB_CONST_YR, retval.tcpu);\n\n\tfprintf(stderr, \"  L0=%.6g  DeltaL/L0=%.6g  DeltaL=%.6g\\n\", fb_mod(Li), retval.DeltaLfrac, retval.DeltaL);\n\tfprintf(stderr, \"  E0=%.6g  DeltaE/E0=%.6g  DeltaE=%.6g\\n\", Ei, retval.DeltaEfrac, retval.DeltaE);\n\tfprintf(stderr, \"  Rmin=%.6g (%.6g RSUN)  Rmin_i=%d  Rmin_j=%d\\n\", \\\n\t\tretval.Rmin, retval.Rmin*units.l/FB_CONST_RSUN, retval.Rmin_i, retval.Rmin_j);\n\tfprintf(stderr, \"  Nosc=%d (%s)\\n\", retval.Nosc, (retval.Nosc>=1?\"resonance\":\"non-resonance\"));\n\t\n\t/* free GSL stuff */\n\tgsl_rng_free(rng);\n\n\t/* free our own stuff */\n\tfb_free_hier(hier);\n\n\t/* done! */\n\treturn(0);\n}\n", "meta": {"hexsha": "c8f3d1f8bd175a8ec2e0a3af02c0698dc93d7964", "size": 14612, "ext": "c", "lang": "C", "max_stars_repo_path": "ext/fewbod/fewbody-0.26/cluster.c", "max_stars_repo_name": "gnodvi/cosmos", "max_stars_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c", "max_stars_repo_licenses": ["PSF-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ext/fewbod/fewbody-0.26/cluster.c", "max_issues_repo_name": "gnodvi/cosmos", "max_issues_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c", "max_issues_repo_licenses": ["PSF-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-13T20:35:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-13T20:35:46.000Z", "max_forks_repo_path": "ext/fewbod/fewbody-0.26/cluster.c", "max_forks_repo_name": "gnodvi/cosmos", "max_forks_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c", "max_forks_repo_licenses": ["PSF-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3607305936, "max_line_length": 211, "alphanum_fraction": 0.6272926362, "num_tokens": 5080, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41111086923216794, "lm_q2_score": 0.027585280627935107, "lm_q1q2_score": 0.011340608696963685}}
{"text": "#ifndef REACHOBJMULTIDEMO_H\n#define REACHOBJMULTIDEMO_H\n\n#include <cstdlib>\n#include <ctime>\n#include <vector>\n\n#include <yarp/sig/all.h>\n#include <yarp/os/all.h>\n#include <yarp/dev/all.h>\n#include <yarp/math/Math.h>\n\n#include <iCub/iKin/iKinFwd.h>\n#include <iCub/ctrl/math.h>\n\n#include <gsl/gsl_math.h>\n\n#include \"reachObjMultiDemo_IDL.h\"\n\nclass reachObjMultiDemo : public yarp::os::RFModule, public reachObjMultiDemo_IDL\n{\nprotected:\n    yarp::os::RpcServer             rpcPort;\n\n    yarp::dev::IPositionControl*    posArm;\n    yarp::dev::IVelocityControl*    velArm;\n    yarp::dev::ITorqueControl *     itrqArm;\n    yarp::dev::IEncoders*           encsArm;\n    yarp::dev::IControlMode*        iCtrlArm;\n    yarp::dev::IControlLimits*      iCtrlLimArm;\n\n    yarp::dev::IPositionControl*    posRightArm;\n    yarp::dev::IVelocityControl*    velRightArm;\n    yarp::dev::ITorqueControl*      itrqRightArm;\n    yarp::dev::IEncoders*           encsRightArm;\n    yarp::dev::IControlMode*        iCtrlRightArm;\n    yarp::dev::IControlLimits*      iCtrlLimRightArm;\n\n    yarp::dev::IPositionControl*    posTorso;\n    yarp::dev::IVelocityControl*    velTorso;\n    yarp::dev::ITorqueControl*      itrqTorso;\n    yarp::dev::IEncoders*           encsTorso;\n    yarp::dev::IControlMode*        iCtrlTorso;\n    yarp::dev::IControlLimits*      iCtrlLimTorso;\n\n    iCub::iKin::iCubArm*            arm;\n    yarp::sig::Vector               qA;\n\n    yarp::dev::IGazeControl*        igaze;\n    int                             contextGaze;\n    yarp::dev::ICartesianControl   *iCartCtrlR;\n    yarp::dev::ICartesianControl   *iCartCtrl;\n\n    yarp::dev::PolyDriver           torsoDev;\n    yarp::dev::PolyDriver           rightArmDev;\n    yarp::dev::PolyDriver           headDev;\n\n    yarp::dev::PolyDriver           rightCartDev;\n\n    yarp::sig::Vector               encodersRightArm;\n    yarp::sig::Vector               encodersTorso;\n\n    std::string part;               //!< Should be \"left_arm\" or \"right_arm\"\n    std::string robot;              //!< Should be \"icub\" or \"icubSim\"\n    double      period;\n    std::string name;\n    bool        changeTipFrame;     //!<\n    bool        useFakeTarget;\n    bool        useHandAngle;\n    yarp::sig::Vector               fakeTarget;\n    double                          tiltAngle, yawAngle;\n\n\n    yarp::sig::Vector   new_command_arm;\n    yarp::sig::Vector   new_command_head;\n    double              start_command_arm[16];  //!< Start command for the 16 arm joints\n    double              away_command_arm[16];   //!< Away command for the 16 arm joints\n    yarp::sig::Vector   start_command_head;     //!< Target for head in start position\n    double              neck_range_min[3];\n    double              neck_range_max[3];\n    double              minLimArm[16];\n    double              maxLimArm[16];\n\n    bool                hasCommand;\n    bool                hasTarget;\n\n    yarp::os::BufferedPort<yarp::os::Bottle>    cmdJointsPort;\n    yarp::os::Bottle                            *cmdJointsBottle;\n    yarp::sig::Vector                           cmdJointsAng;\n\n    yarp::os::BufferedPort<yarp::os::Bottle>    objPosDimPort;\n    yarp::os::Bottle                            *objPoseDimBottle;\n    yarp::sig::Vector                           objPoseDim;\n\n    yarp::os::BufferedPort<yarp::os::Bottle>    tactilePort;\n    yarp::os::Bottle                            *tactileBottle;\n\n\n    yarp::os::BufferedPort<yarp::os::Bottle>    targetDumpedData;             //!< buffered port of dumped target data\n    yarp::os::Stamp                             ts;\n\n    yarp::sig::Vector                           joints_arm_min, joints_arm_max;\n\n    yarp::os::RpcClient     rpcToMotorBabbling;\n    yarp::os::RpcClient     rpcToLearning;\n\n    bool    init_right_arm(); //!< Create PolyDriver for left arm\n    bool    initRobot();\n//    bool    moveHeadToStartPos(bool ranPos);\n    bool    moveHeadToCentralPos();\n    bool    moveArmToStartPos(const std::string &partName);\n    bool    moveArmAway(const std::string &partName);\n    bool    gotoStartPos(bool moveAway);\n    bool    reachTarget();\n\n    void    updateArmChain(const yarp::sig::Vector &q, yarp::sig::Vector &xEE_t);\n\n    bool    sendCmdBabbling();\n    bool    sendCmdLearningPredict();\n    bool    sendCmdLearningMove(const int &id, const std::string &partName);\n\n    std::vector<int> reprTaxelsForearm_sim =\n    {3, 15, 27, 39, 51, 75, 87, 183,\n    207, 255, 291, 303, 315, 339, 351}; //23 taxels\n\n    std::vector<int> reprTaxelsHandL =\n    {3, 15, 27, 39, 51, 99, 101, 109, 122, 134};\n\n    std::vector<int> reprTaxelsHandR =\n    {3, 15, 39, 51, 101, 118, 137};\n\npublic:\n    bool    configure(yarp::os::ResourceFinder &rf);\n    bool    interruptModule();\n    bool    close();\n    bool    attach(yarp::os::RpcServer &source);\n    double  getPeriod();\n    bool    updateModule();\n//    reachBallDemo();\n\n\n    //Thrift\n    bool home_arms()\n    {\n        bool ok = false;\n//        ok = moveArmToStartPos(\"left\");\n        ok = moveArmToStartPos(\"right\");\n        if (ok)\n            yDebug(\"[%s] Moved all arms home sucessfully!!\",name.c_str());\n        else\n            yDebug(\"[%s] Failed moving all arms home!!\",name.c_str());\n        return ok;\n    }\n\n    bool home_all()\n    {\n        bool ok = false;\n        ok = moveHeadToCentralPos();\n        ok = ok & home_arms();\n        if (ok)\n            yDebug(\"[%s] Moved all parts home sucessfully!!\",name.c_str());\n        else\n            yDebug(\"[%s] Failed moving all parts home!!\",name.c_str());\n        return ok;\n    }\n\n    bool reach(bool _useCalib)\n    {\n        yDebug(\"[%s] Start reaching the target\",name.c_str());\n        hasCommand = true;\n//        if (hasTarget)\n//            return reachTarget();\n//        else\n//        {\n//            yWarning(\"[%s] No target\", name.c_str());\n//            return false;\n//        }\n    }\n\n    bool babble_then_reach(int32_t _id, const std::string &_part)\n    {\n        bool ok = sendCmdBabbling();\n        yarp::os::Time::delay(3);\n        ok = ok & sendCmdLearningPredict();\n        yarp::os::Time::delay(1);\n\n        if (_id==-1)    // reach all taxel of part\n        {\n//            if (_part==\"b\" or _part==\"both\")\n//            {\n//                for (int i=0; i<=reprTaxelsHandR.size(); i++)\n//                {\n//                    sendCmdLearningMove(reprTaxelsHandR[i], \"h\");\n\n//                }\n//            }\n//            else if (_part==\"h\" or _part==\"hand\")\n//            {\n\n//            }\n//            else if (_part==\"a\" or _part==\"arm\")\n//            {\n\n//            }\n        }\n        else\n            ok = ok & sendCmdLearningMove(_id,_part);\n        return ok;\n    }\n\n    bool set_tilt_angle(const double _ang)\n    {\n        tiltAngle = _ang;\n        return true;\n    }\n\n    double get_tilt_angle()\n    {\n        return tiltAngle;\n    }\n\n    bool set_yaw_angle(const double _ang)\n    {\n        yawAngle = _ang;\n        return true;\n    }\n\n    double get_yaw_angle()\n    {\n        return yawAngle;\n    }\n\n    bool enable_hand_angle()\n    {\n        useHandAngle = true;\n        return true;\n    }\n\n    bool disable_hand_angle()\n    {\n        useHandAngle = false;\n        return true;\n    }\n\n};\n\n#endif // REACHBALLDEMO_H\n", "meta": {"hexsha": "82b027f4ebe908cf6612325d37bde4ba02efbcfe", "size": 7231, "ext": "h", "lang": "C", "max_stars_repo_path": "modules/reachObjMultiDemo/reachObjMultiDemo.h", "max_stars_repo_name": "robotology/visuomotor-learning", "max_stars_repo_head_hexsha": "d9e3919b8ff69ea9e4652ee882f323d5786b74af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-02-01T16:04:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-16T11:38:25.000Z", "max_issues_repo_path": "modules/reachObjMultiDemo/reachObjMultiDemo.h", "max_issues_repo_name": "robotology/visuomotor-learning", "max_issues_repo_head_hexsha": "d9e3919b8ff69ea9e4652ee882f323d5786b74af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/reachObjMultiDemo/reachObjMultiDemo.h", "max_forks_repo_name": "robotology/visuomotor-learning", "max_forks_repo_head_hexsha": "d9e3919b8ff69ea9e4652ee882f323d5786b74af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1572580645, "max_line_length": 118, "alphanum_fraction": 0.5487484442, "num_tokens": 1983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879064146934857, "lm_q2_score": 0.024053554075016234, "lm_q1q2_score": 0.011276081044444523}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <iniparser.h>\n#include \"parmt_utils.h\"\n#include \"prepmt/prepmt_dataArchive.h\"\n#include \"prepmt/prepmt_greens.h\"\n#include \"prepmt/prepmt_hudson96.h\"\n#include \"prepmt/prepmt_commands.h\"\n#ifdef PARMT_USE_INTEL\n#include <mkl_cblas.h>\n#else\n#include <cblas.h>\n#endif\n#include \"ispl/process.h\"\n#include \"iscl/array/array.h\"\n#include \"iscl/fft/fft.h\"\n#include \"iscl/memory/memory.h\"\n#include \"iscl/os/os.h\"\n#include \"iscl/signal/convolve.h\"\n#include \"iscl/signal/filter.h\"\n\nstatic int getPrimaryArrival(const struct sacHeader_struct hdr,\n                             double *time, char phaseName[8]);\nstatic int getPrimaryArrivalNoPolarity(const struct sacHeader_struct hdr,\n                                       double *time, char phaseName[8]);\nstatic void shiftGreens(const int npgrns, const int lag,\n                        double *__restrict__ G, double *__restrict__ work);\n\n\n//============================================================================//\n/*!\n * @brief Converts the fundamental faults Green's functions to Green's\n *        functions that can be used by parmt.\n *\n * @param[in] nobs      Number of observations.\n * @param[in] obs       Observed waveforms to contextualize.  This is an \n *                      array of length [nobs].\n * @param[in] ndepth    Number of depths.\n * @param[in] ntstar    Number of t*s'.\n * @param[in] ffGrns    Fundamental fault Green's functions for every t* and\n *                      depth in the grid search for each observation.  This\n *                      is an array of dimension [nobs x ndepth x ntstar x 10]. \n *\n * @param[in,out] grns  Holds space for Green's functions.\n *                      Contains the Green's functions that can be applied to\n *                      a moment tensor to produce a synthetic for every t*\n *                      and depth in the grid search for each observation.\n *                      This is an array of length [nobs x ndepth x ntstar x 6].\n *\n * @result 0 indicates success.\n *\n * @author Ben Baker, ISTI\n *\n */\nint prepmt_greens_ffGreensToGreens(const int nobs,\n                                   const struct sacData_struct *obs,\n                                   const int ndepth,\n                                   const int ntstar,\n                                   const struct sacData_struct *ffGrns,\n                                   struct sacData_struct *grns)\n{\n    char knetwk[8], kstnm[8], kcmpnm[8], khole[8], phaseName[8],\n         phaseNameGrns[8];\n    double az, baz, cmpaz, cmpinc, cmpincSEED, epoch, epochNew,\n           evla, evlo, o, pick, pickTime, pickTimeGrns, stel, stla, stlo;\n    int indices[6], i, icomp, id, ierr, idx, iobs, it, kndx, l, npts;\n    const char *kcmpnms[6] = {\"GXX\\0\", \"GYY\\0\", \"GZZ\\0\",\n                              \"GXY\\0\", \"GXZ\\0\", \"GYZ\\0\"};\n/*\n    const double xmom = 1.0;     // no confusing `relative' magnitudes \n    const double xcps = 1.e-20;  // convert dyne-cm mt to output cm\n    const double cm2m = 1.e-2;   // cm to meters\n    const double dcm2nm = 1.e+7; // magnitudes intended to be specified in\n                                 // Dyne-cm but I work in N-m\n    // Given a M0 in Newton-meters get a seismogram in meters\n    const double xscal = xmom*xcps*cm2m*dcm2nm;\n*/\n    const int nTimeVars = 11; \n    const enum sacHeader_enum pickVars[11]\n       = {SAC_FLOAT_A,\n          SAC_FLOAT_T0, SAC_FLOAT_T1, SAC_FLOAT_T2, SAC_FLOAT_T3,\n          SAC_FLOAT_T4, SAC_FLOAT_T5, SAC_FLOAT_T6, SAC_FLOAT_T7,\n          SAC_FLOAT_T8, SAC_FLOAT_T9};\n    //memset(grns, 0, sizeof(struct tdSearchGreens_struct));\n    for (iobs=0; iobs<nobs; iobs++)\n    {\n        ierr = 0;\n        ierr += sacio_getFloatHeader(SAC_FLOAT_AZ,\n                                     obs[iobs].header, &az);\n        ierr += sacio_getFloatHeader(SAC_FLOAT_BAZ,\n                                     obs[iobs].header, &baz);\n        ierr += sacio_getFloatHeader(SAC_FLOAT_CMPINC,\n                                     obs[iobs].header, &cmpinc);\n        ierr += sacio_getFloatHeader(SAC_FLOAT_CMPAZ,\n                                     obs[iobs].header, &cmpaz);\n        ierr += sacio_getFloatHeader(SAC_FLOAT_EVLA,\n                                     obs[iobs].header, &evla);\n        ierr += sacio_getFloatHeader(SAC_FLOAT_EVLO,\n                                     obs[iobs].header, &evlo);\n        ierr += sacio_getFloatHeader(SAC_FLOAT_STLA,\n                                     obs[iobs].header, &stla);\n        ierr += sacio_getFloatHeader(SAC_FLOAT_STLO,\n                                     obs[iobs].header, &stlo);\n        ierr += sacio_getCharacterHeader(SAC_CHAR_KNETWK,\n                                         obs[iobs].header, knetwk);\n        ierr += sacio_getCharacterHeader(SAC_CHAR_KSTNM,\n                                         obs[iobs].header, kstnm);\n        ierr += sacio_getCharacterHeader(SAC_CHAR_KCMPNM,\n                                         obs[iobs].header, kcmpnm);\n        if (ierr != 0)\n        {\n            fprintf(stderr, \"%s: Error reading header variables\\n\", __func__);\n            break;\n        }\n        // This one isn't critical but it would be nice to have\n        sacio_getFloatHeader(SAC_FLOAT_STEL,\n                             obs[iobs].header, &stel);\n        // Station location code is not terribly important\n        sacio_getCharacterHeader(SAC_CHAR_KHOLE, obs[iobs].header, khole);\n        cmpincSEED = cmpinc - 90.0; // SAC to SEED convention\n        // Get the primary arrival\n        ierr = sacio_getEpochalStartTime(obs[iobs].header, &epoch);\n        if (ierr != 0)\n        {\n            fprintf(stderr, \"%s: Error getting start time\\n\", __func__);\n            break;\n        }\n        ierr += getPrimaryArrivalNoPolarity(obs[iobs].header, &pickTime,\n                                            phaseName);\n        //ierr += getPrimaryArrival(obs[iobs].header, &pickTime, phaseName);\n        if (ierr != 0)\n        {\n            fprintf(stderr, \"%s: Error getting primary pick\\n\", __func__);\n            break;\n        }\n        // Need to figure out the component\n        ierr = parmt_utils_getComponent(kcmpnm, cmpinc, &icomp);\n        if (ierr != 0)\n        {\n            fprintf(stderr, \"%s: Error getting component\\n\", __func__);\n            break;\n        }\n/*\n        icomp = 1;\n        if (fabs(cmpinc - 0.0) < 1.e-4 || fabs(cmpinc - 180.0) < 1.e-4)\n        {\n            if (kcmpnm[2] == 'Z' || kcmpnm[2] == 'z' || kcmpnm[2] == '1')\n            {\n                icomp = 1;\n            }\n            else\n            {\n                fprintf(stderr, \"%s: cmpinc is 0 but channel=%s isn't vertical\",\n                        __func__, kcmpnm);\n            }\n        }\n        else if (fabs(cmpinc - 90.0) < 1.e-4)\n        {\n            icomp = 2;\n            if (kcmpnm[2] == 'N' || kcmpnm[2] == 'n' ||\n                kcmpnm[2] == '1' || kcmpnm[2] == '2')\n            {\n                icomp = 2;\n            }\n            else if (kcmpnm[2] == 'N' || kcmpnm[2] == 'n' ||\n                     kcmpnm[2] == '2' || kcmpnm[2] == '3') \n            {\n                icomp = 3;\n            }\n            else\n            {\n                fprintf(stderr, \"%s: cmpinc is 90 but channel=%s is weird\",\n                        __func__, kcmpnm);\n                return -1;\n            }\n        }\n*/\n        /*\n        else if (kcmpnm[2] == 'E' || kcmpnm[2] == 'e' || kcmpnm[2] == '3')\n        {\n            icomp = 3;\n        }\n        */\n/*\n        else\n        {\n            fprintf(stderr, \"%s: Can't classify component %s with cmpinc=%f\\n\",\n                    __func__, kcmpnm, cmpinc);\n        }\n*/\n        // Process all Green's functions in this block\n        for (id=0; id<ndepth; id++)\n        {\n            for (it=0; it<ntstar; it++)\n            {\n                idx = prepmt_hudson96_observationDepthTstarToIndex(\n                             ndepth, ntstar, iobs, id, it);\n                kndx = 10*idx;\n                sacio_getFloatHeader(SAC_FLOAT_O, ffGrns[kndx].header, &o);\n                getPrimaryArrival(ffGrns[kndx].header,\n                                  &pickTimeGrns, phaseNameGrns);\n                if (strcasecmp(phaseNameGrns, phaseName) != 0)\n                {\n                    fprintf(stdout, \"%s: Phase name mismatch %s %s\\n\",\n                            __func__, phaseName, phaseNameGrns);\n                }\n                npts = ffGrns[kndx].npts;\n                ierr = prepmt_greens_getHudson96GreensFunctionsIndices(\n                                 nobs, ntstar, ndepth,\n                                 iobs, it, id,\n                                 indices);\n                /*\n                indx = prepmt_greens_getHudson96GreensFunctionIndex(G11_GRNS,\n                                                            nobs, ntstar, ndepth,\n                                                            iobs, it, id);\n                */\n                for (i=0; i<6; i++)\n                {\n                    sacio_copy(ffGrns[kndx], &grns[indices[i]]);\n                    if (obs[iobs].pz.lhavePZ)\n                    {\n                        sacio_copyPolesAndZeros(obs[iobs].pz,\n                                                &grns[indices[i]].pz);\n                    }\n                    sacio_setFloatHeader(SAC_FLOAT_AZ, az,\n                                         &grns[indices[i]].header);\n                    sacio_setFloatHeader(SAC_FLOAT_BAZ, baz,\n                                         &grns[indices[i]].header);\n                    sacio_setFloatHeader(SAC_FLOAT_CMPAZ, cmpaz,\n                                         &grns[indices[i]].header);\n                    sacio_setFloatHeader(SAC_FLOAT_CMPINC, cmpinc,\n                                         &grns[indices[i]].header);\n                    sacio_setFloatHeader(SAC_FLOAT_EVLA, evla,\n                                         &grns[indices[i]].header);\n                    sacio_setFloatHeader(SAC_FLOAT_EVLO, evlo,\n                                         &grns[indices[i]].header);\n                    sacio_setFloatHeader(SAC_FLOAT_STLA, stla,\n                                         &grns[indices[i]].header);\n                    sacio_setFloatHeader(SAC_FLOAT_STLO, stlo,\n                                         &grns[indices[i]].header);\n                    sacio_setFloatHeader(SAC_FLOAT_STEL, stel,\n                                         &grns[indices[i]].header); \n                    sacio_setCharacterHeader(SAC_CHAR_KNETWK, knetwk,\n                                             &grns[indices[i]].header);\n                    sacio_setCharacterHeader(SAC_CHAR_KSTNM, kstnm,\n                                             &grns[indices[i]].header);\n                    sacio_setCharacterHeader(SAC_CHAR_KHOLE, khole,\n                                             &grns[indices[i]].header);\n                    sacio_setCharacterHeader(SAC_CHAR_KCMPNM, kcmpnms[i],\n                                             &grns[indices[i]].header);\n                    sacio_setCharacterHeader(SAC_CHAR_KEVNM, \"SYNTHETIC\\0\",\n                                             &grns[indices[i]].header);\n                    // Set the start time by aligning on the arrival\n                    epochNew = epoch + (pickTime - o) - pickTimeGrns;\n                    sacio_setEpochalStartTime(epochNew,\n                                              &grns[indices[i]].header);\n                    // Update the pick times\n                    for (l=0; l<nTimeVars; l++)\n                    {\n                        ierr = sacio_getFloatHeader(pickVars[l],\n                                                    grns[indices[i]].header,\n                                                    &pick);\n                        if (ierr == 0)\n                        {\n                            pick = pick + o;\n                            sacio_setFloatHeader(pickVars[l],\n                                                 pick,\n                                                 &grns[indices[i]].header);\n                        }\n                    } \n                }\n                //printf(\"%d %d\\n\", kndx, indices[0]);\n                //printf(\"%e\\n\", array_max64f(npts, ffGrns[kndx+0].data));\n                ierr = parmt_utils_ff2mtGreens64f(npts, icomp,\n                                                  az, baz,\n                                                  cmpaz, cmpincSEED,\n                                                  ffGrns[kndx+0].data,\n                                                  ffGrns[kndx+1].data,\n                                                  ffGrns[kndx+2].data,\n                                                  ffGrns[kndx+3].data,\n                                                  ffGrns[kndx+4].data,\n                                                  ffGrns[kndx+5].data,\n                                                  ffGrns[kndx+6].data,\n                                                  ffGrns[kndx+7].data,\n                                                  ffGrns[kndx+8].data,\n                                                  ffGrns[kndx+9].data,\n                                                  grns[indices[0]].data,\n                                                  grns[indices[1]].data,\n                                                  grns[indices[2]].data,\n                                                  grns[indices[3]].data,\n                                                  grns[indices[4]].data,\n                                                  grns[indices[5]].data);\n                if (ierr != 0)\n                {\n                    fprintf(stderr, \"%s: Failed to rotate Greens functions\\n\",\n                            __func__);\n                }\n                // Fix the characteristic magnitude scaling in CPS \n                // N.B. this is done early now\n                /*\n                for (i=0; i<6; i++)\n                {\n                    cblas_dscal(npts, xscal, grns[indices[i]].data, 1); \n                    //printf(\"%d %d %e\\n\", kndx, indices[i],\n                    //          array_max64f(npts,grns[indices[i]].data));\n                }\n                */\n            }\n        }\n    }\n    return 0;\n}\n//============================================================================//\n/*!\n * @brief Convenience function which returns the index of the Green's\n *        function on the Green's function structure.\n *\n * @param[in] GMT_TERM    Name of the desired Green's function:\n *                        (G11_TERM, G22_TERM, ..., G23_TERM).\n * @param[in] nobs        Number of observations.\n * @param[in] ntstar      Number of t*'s.\n * @param[in] ndepth      Number of depths.\n * @param[in] iobs        Desired observation number (C numbering).\n * @param[in] itstar      Desired t* (C numbering).\n * @param[in] idepth      Desired depth (C numbering).\n *\n * @result Negative indicates failure.  Otherwise, this is the index in \n *         grns.grns corresponding to the desired \n *         (iobs, idepth, itstar, G??_GRNS) coordinate.\n *\n * @author Ben Baker, ISTI\n *\n */\nint prepmt_greens_getHudson96GreensFunctionIndex(\n    const enum prepmtGreens_enum GMT_TERM,\n    const int nobs, const int ntstar, const int ndepth,\n    const int iobs, const int itstar, const int idepth)\n{\n    int igx, indx, ngrns;\n    ngrns = 6*nobs*ntstar*ndepth;\n    indx =-1;\n    igx = (int) GMT_TERM - 1;\n    if (igx < 0 || igx > 5)\n    {\n        fprintf(stderr, \"%s: Can't classify Green's functions index\\n\",\n                __func__);\n        return indx;\n    }\n    indx = iobs*(6*ntstar*ndepth)\n         + idepth*(6*ntstar)\n         + itstar*6\n         + igx;\n    if (indx < 0 || indx >= ngrns)\n    {\n        fprintf(stderr, \"%s: indx out of bounds - segfault is coming\\n\",\n                __func__);\n        return -1;\n    }\n    return indx;\n}\n//============================================================================//\n/*!\n * @brief Repicks the Green's functions onset time with an STA/LTA picker.\n *\n * @param[in] sta        Short term average window length (seconds).\n * @param[in] lta        Long term average window length (seconds).\n * @param[in] threshPct  Percentage of max STA/LTA after which an arrival\n *                       is declared.\n * @param[in] nobs       Number of observations.\n * @param[in] ntstar     Number of t*'s.\n * @param[in] ndepth     Number of depths.\n * @param[in] iobs       C numbered observation index.\n * @param[in] itstar     C numbered t* index.\n * @param[in] idepth     C numbered depth index.\n *\n * @param[in,out] grns   On input contains the Green's functions.\n *                       On output the first defined arrival time has been\n *                       modified with an STA/LTA picker.  The header variable\n *                       to be modified is most likely SAC_FLOAT_A.\n *                       This is an array of dimension [6]. \n *\n * @brief 0 indicates success.\n *\n * @author Ben Baker, ISTI\n *\n */\nint prepmt_greens_repickGreensWithSTALTA(\n    const double sta, const double lta, const double threshPct,\n    struct sacData_struct *grns)\n{\n    struct stalta_struct stalta;\n    enum sacHeader_enum pickHeader;\n    double *charFn, *g, *Gxx, *Gyy, *Gzz, *Gxy, *Gxz, *Gyz,\n           *gxxPad, *gyyPad, *gzzPad, *gxyPad, *gxzPad, *gyzPad,\n           apick, charMax, dt, tpick;\n    int ierr, k, npts, nlta, npad, nsta, nwork, prePad;\n    const int nTimeVars = 11;\n    const enum sacHeader_enum pickVars[11]\n       = {SAC_FLOAT_A,\n          SAC_FLOAT_T0, SAC_FLOAT_T1, SAC_FLOAT_T2, SAC_FLOAT_T3,\n          SAC_FLOAT_T4, SAC_FLOAT_T5, SAC_FLOAT_T6, SAC_FLOAT_T7,\n          SAC_FLOAT_T8, SAC_FLOAT_T9};\n    // Check STA/LTA \n    ierr = 0;\n    memset(&stalta, 0, sizeof(struct stalta_struct));\n    if (lta < sta || sta < 0.0)\n    {\n        if (lta < sta){fprintf(stderr, \"%s: Error lta < sta\\n\", __func__);}\n        if (sta < 0.0){fprintf(stderr, \"%s: Error sta is < 0\\n\", __func__);}\n        return -1;\n    }\n    ierr = sacio_getIntegerHeader(SAC_INT_NPTS,\n                                  grns[0].header, &npts);\n    if (ierr != 0 || npts < 1)\n    {\n        if (ierr != 0)\n        {\n            fprintf(stderr, \"%s: Error getting number of points from header\\n\",\n                    __func__);\n        }\n        else\n        {\n            fprintf(stderr, \"%s: Error no data points\\n\", __func__);\n        }\n        return -1;\n    }\n    ierr = sacio_getFloatHeader(SAC_FLOAT_DELTA,\n                                grns[0].header, &dt);\n    if (ierr != 0 || dt <= 0.0)\n    {\n        if (ierr != 0){fprintf(stderr, \"%s: failed to get dt\\n\", __func__);}\n        if (dt <= 0.0)\n        {\n            fprintf(stderr, \"%s: invalid sampling period\\n\", __func__);\n        }\n        return -1;\n    }\n    // Define the windows\n    nsta = (int) (sta/dt + 0.5);\n    nlta = (int) (lta/dt + 0.5);\n    prePad = MAX(64, fft_nextpow2(nlta, &ierr));\n    npad = prePad + npts;\n    // Set space\n    gxxPad = memory_calloc64f(npad);\n    gyyPad = memory_calloc64f(npad);\n    gzzPad = memory_calloc64f(npad);\n    gxyPad = memory_calloc64f(npad);\n    gxzPad = memory_calloc64f(npad);\n    gyzPad = memory_calloc64f(npad);\n    charFn = memory_calloc64f(npad);\n    // Reference pointers\n    Gxx = grns[0].data;\n    Gyy = grns[1].data;\n    Gzz = grns[2].data;\n    Gxy = grns[3].data;\n    Gxz = grns[4].data;\n    Gyz = grns[5].data;\n    // Pre-pad signals\n    array_set64f_work(prePad, Gxx[0], gxxPad);\n    array_set64f_work(prePad, Gyy[0], gyyPad);\n    array_set64f_work(prePad, Gzz[0], gzzPad); \n    array_set64f_work(prePad, Gxy[0], gxyPad);\n    array_set64f_work(prePad, Gxz[0], gxzPad);\n    array_set64f_work(prePad, Gyz[0], gyzPad);\n    // Copy rest of array\n    array_copy64f_work(npts, Gxx, &gxxPad[prePad]);\n    array_copy64f_work(npts, Gyy, &gyyPad[prePad]);\n    array_copy64f_work(npts, Gzz, &gzzPad[prePad]);\n    array_copy64f_work(npts, Gxy, &gxyPad[prePad]);\n    array_copy64f_work(npts, Gxz, &gxzPad[prePad]);\n    array_copy64f_work(npts, Gyz, &gyzPad[prePad]);\n    // apply the sta/lta\n    for (k=0; k<6; k++)\n    {\n        g = NULL;\n        if (k == 0)\n        {\n            g = gxxPad;\n        }\n        else if (k == 1)\n        {\n            g = gyyPad;\n        }\n        else if (k == 2)\n        {\n            g = gzzPad;\n        }\n        else if (k == 3)\n        {\n            g = gxyPad;\n        }\n        else if (k == 4)\n        {\n            g = gxzPad;\n        }\n        else if (k == 5)\n        {\n            g = gyzPad;\n        }\n        ierr = stalta_setShortAndLongTermAverage(nsta, nlta, &stalta);\n        if (ierr != 0)\n        {\n            fprintf(stderr, \"%s: Error setting STA/LTA\\n\", __func__);\n            break;\n        }\n        ierr = stalta_setData64f(npad, g, &stalta);\n        if (ierr != 0)\n        {\n            fprintf(stderr, \"%s: Error setting data\\n\", __func__);\n            break;\n        }\n        ierr = stalta_applySTALTA(&stalta);\n        if (ierr != 0)\n        {\n            fprintf(stderr, \"%s: Error applying STA/LTA\\n\", __func__);\n            break;\n        }\n        ierr = stalta_getData64f(stalta, npad, &nwork, g);\n        if (ierr != 0)\n        {\n            fprintf(stderr, \"%s: Error getting result\\n\", __func__);\n            break;\n        }\n        cblas_daxpy(npad, 1.0, g, 1, charFn, 1);\n        stalta_resetInitialConditions(&stalta);\n        stalta_resetFinalConditions(&stalta);\n        g = NULL;\n    }\n    // Compute the pick time\n    charMax = array_max64f(npts, &charFn[prePad], &ierr);\n    tpick =-1.0;\n    for (k=prePad; k<npad; k++)\n    {\n        if (charFn[k] > 0.01*threshPct*charMax)\n        {\n            tpick = (double) (k - prePad)*dt;\n            break;\n        }\n    }\n    if (tpick ==-1.0)\n    {\n        tpick = (double) (array_argmax64f(npad, charFn, &ierr) - prePad)*dt;\n    }\n    // Overwrite the pick\n    pickHeader = SAC_UNKNOWN_HDRVAR;\n    for (k=0; k<nTimeVars; k++)\n    {\n        if (sacio_getFloatHeader(pickVars[k], grns[k].header, &apick) == 0)\n        {\n            pickHeader = pickVars[k];\n            break;\n         }\n    } \n    if (pickHeader == SAC_UNKNOWN_HDRVAR)\n    {\n        fprintf(stdout, \"%s: Could not locate primary arrival - assume A\\n\",\n                __func__);\n        pickHeader = SAC_FLOAT_A;\n    } \n//printf(\"%f %f\\n\", tpick, apick);\n    //double apick;\n    //sacio_getFloatHeader(SAC_FLOAT_A, grns[0].header, &apick);\n    for (k=0; k<6; k++)\n    {\n        sacio_setFloatHeader(pickHeader, tpick,\n                             &grns[k].header);\n    }\n    // Dereference pointers and free space\n    Gxx = NULL;\n    Gyy = NULL;\n    Gzz = NULL;\n    Gxy = NULL;\n    Gxz = NULL;\n    Gyz = NULL;\n    memory_free64f(&gxxPad);\n    memory_free64f(&gyyPad);\n    memory_free64f(&gzzPad);\n    memory_free64f(&gxyPad);\n    memory_free64f(&gxzPad);\n    memory_free64f(&gyzPad);\n    memory_free64f(&charFn);\n    stalta_free(&stalta);\n    return ierr;\n}\n//============================================================================//\nint prepmt_greens_processHudson96Greens(\n    const int nobs, const int ntstar, const int ndepth,\n    const struct prepmtCommands_struct cmds,\n    struct sacData_struct *grns)\n{\n    struct serialCommands_struct commands;\n    struct parallelCommands_struct parallelCommands;\n    double *G, dt, dt0, epoch, epoch0, time;\n    int *dataPtr, indices[6], \n        i, i0, i1, i2, ierr, iobs, idep, it, kndx, l, npts, npts0, nq,\n        nwork, ny, ns, nsuse;\n    bool lnewDt, lnewStartTime;\n    const int nTimeVars = 12;\n    const enum sacHeader_enum timeVars[12]\n       = {SAC_FLOAT_A, SAC_FLOAT_O, \n          SAC_FLOAT_T0, SAC_FLOAT_T1, SAC_FLOAT_T2, SAC_FLOAT_T3,\n          SAC_FLOAT_T4, SAC_FLOAT_T5, SAC_FLOAT_T6, SAC_FLOAT_T7,\n          SAC_FLOAT_T8, SAC_FLOAT_T9};\n    const int spaceInquiry =-1;\n    // Loop on the observations\n    ns = ndepth*ntstar*6;\n    dataPtr = memory_calloc32i(ns);\n    for (iobs=0; iobs<nobs; iobs++)\n    {\n        // Set the processing structure\n        memset(&parallelCommands, 0,\n               sizeof(struct parallelCommands_struct)); \n               memset(&commands, 0, sizeof(struct serialCommands_struct));\n        kndx = prepmt_greens_getHudson96GreensFunctionIndex(G11_GRNS,\n                                                      nobs, ntstar, ndepth,\n                                                      iobs, 0, 0);\n        // Parse the commands\n        ierr = process_stringsToSerialCommandsOptions(\n                                      cmds.cmds[iobs].ncmds,\n                                      (const char **) cmds.cmds[iobs].cmds,\n                                      &commands);\n        if (ierr != 0)\n        {\n            fprintf(stderr, \"%s: Error setting serial command string\\n\",\n                    __func__);\n            goto ERROR;\n        }\n        // Determine some characteristics of the processing\n        sacio_getEpochalStartTime(grns[kndx].header, &epoch0);\n        sacio_getFloatHeader(SAC_FLOAT_DELTA, grns[kndx].header, &dt0);\n        lnewDt = false;\n        lnewStartTime = false;\n        epoch = epoch0;\n        dt = dt0;\n        for (i=0; i<commands.ncmds; i++)\n        {\n            if (commands.commands[i].type == CUT_COMMAND)\n            {\n                i0 = commands.commands[i].cut.i0;\n                epoch = epoch + (double) i0*dt;\n                lnewStartTime = true;\n            }\n            if (commands.commands[i].type == DOWNSAMPLE_COMMAND)\n            {\n                nq = commands.commands[i].downsample.nq;\n                dt = dt*(double) nq;\n                lnewDt = true;\n            }\n            if (commands.commands[i].type == DECIMATE_COMMAND)\n            {\n                nq = commands.commands[i].decimate.nqAll;\n                dt = dt*(double) nq;\n                lnewDt = true;\n            }\n        }\n        // Set the commands on the parallel processing structure\n        ierr = process_setCommandOnAllParallelCommands(ns, commands,\n                                                       &parallelCommands);\n        if (ierr != 0)\n        {\n            fprintf(stderr, \"%s: Error setting the parallel commands\\n\",\n                    __func__);\n            goto ERROR;\n        }\n        // Get the data\n        dataPtr[0] = 0;\n        for (idep=0; idep<ndepth; idep++)\n        {\n            for (it=0; it<ntstar; it++)\n            {\n                kndx = prepmt_greens_getHudson96GreensFunctionIndex(G11_GRNS,\n                                                          nobs, ntstar, ndepth,\n                                                          iobs, idep, it);\n                ierr = sacio_getIntegerHeader(SAC_INT_NPTS,\n                                              grns[kndx].header, &npts);\n                if (ierr != 0)\n                {\n                    fprintf(stderr, \"%s: Error getting npts\\n\", __func__);\n                    goto ERROR;\n                }\n                i1 = idep*6*ntstar + it*6 + 0;\n                i2 = i1 + 6;\n                for (i=i1; i<i2; i++)\n                {\n                    dataPtr[i+1] = dataPtr[i] + npts;\n                }\n            }\n        }\n        nwork = dataPtr[6*ndepth*ntstar];\n        if (nwork < 1)\n        {\n            fprintf(stderr, \"%s: Invalid workspace size: %d\\n\",\n                    __func__, nwork);\n            ierr = 1;\n            goto ERROR;\n        } \n        G = memory_calloc64f(nwork);\n        for (idep=0; idep<ndepth; idep++)\n        {\n            for (it=0; it<ntstar; it++)\n            {\n                ierr = prepmt_greens_getHudson96GreensFunctionsIndices(\n                                        nobs, ntstar, ndepth,\n                                        iobs, it, idep, indices);\n                if (ierr != 0)\n                {\n                    fprintf(stderr, \"%s: Error getting index\\n\", __func__);\n                    goto ERROR;\n                }\n                for (i=0; i<6; i++)\n                {\n                    i1 = idep*6*ntstar + it*6 + i;\n                    //if (i == 0){printf(\"fill: %d %d %d %e\\n\", i1, indices[i], dataPtr[i1], array_max64f(grns[indices[i]].npts, grns[indices[i]].data));}\n\n                    cblas_dcopy(grns[indices[i]].npts, \n                                grns[indices[i]].data, 1, &G[dataPtr[i1]], 1);\n                }\n            }\n        }\n        // Set the data\n        ierr =  process_setParallelCommandsData64f(ns, dataPtr,\n                                                   G, &parallelCommands);\n        if (ierr != 0)\n        {\n            fprintf(stderr, \"%s: Error setting data\\n\", __func__);\n            goto ERROR;\n        }\n        // Apply the commands\n        ierr = process_applyParallelCommands(&parallelCommands);\n        if (ierr != 0)\n        {\n            fprintf(stderr, \"%s: Error processing data\\n\", __func__);\n            goto ERROR;\n        }\n        // Get the data\n        ierr = process_getParallelCommandsData64f(parallelCommands,\n                                                  spaceInquiry, spaceInquiry,\n                                                  &ny, &nsuse,\n                                                  dataPtr, G);\n        if (ny < nwork)\n        {\n            memory_free64f(&G);\n            G = memory_calloc64f(ny);\n        }\n        ny = nwork;\n        ierr = process_getParallelCommandsData64f(parallelCommands,\n                                                  nwork, ns,\n                                                  &ny, &nsuse, dataPtr, G);\n        //printf(\"%d\\n\", nsuse);\n        if (ierr != 0)\n        {\n            fprintf(stderr, \"%s: Error getting data\\n\", __func__);\n            goto ERROR;\n        }\n        // Unpack the data\n        for (idep=0; idep<ndepth; idep++)\n        {\n            for (it=0; it<ntstar; it++)\n            {\n                ierr = prepmt_greens_getHudson96GreensFunctionsIndices(\n                                        nobs, ntstar, ndepth,\n                                        iobs, it, idep, indices);\n                if (ierr != 0)\n                {\n                    fprintf(stderr, \"%s: Error getting index\\n\", __func__);\n                    goto ERROR;\n                }\n                for (i=0; i<6; i++)\n                {\n                    i1 = idep*6*ntstar + it*6 + i;\n                    sacio_getIntegerHeader(SAC_INT_NPTS,  \n                                           grns[indices[i]].header, &npts0);\n                    npts = dataPtr[i1+1] - dataPtr[i1];\n                    // Resize event\n                    if (npts != npts0)\n                    {\n                        sacio_freeData(&grns[indices[i]]);\n                        grns[indices[i]].data = sacio_malloc64f(npts);\n                        grns[indices[i]].npts = npts;\n                        sacio_setIntegerHeader(SAC_INT_NPTS, npts,\n                                               &grns[indices[i]].header);\n                        ierr = array_copy64f_work(npts,\n                                                  &G[dataPtr[i1]],\n                                                  grns[indices[i]].data);\n                    }\n                    else\n                    {\n                        ierr = array_copy64f_work(npts,\n                                                  &G[dataPtr[i1]],\n                                                  grns[indices[i]].data);\n                        //if (i == 0){printf(\"%d %d %e\\n\", iobs, indices[i], array_max64f(grns[indices[i]].npts, grns[indices[i]].data));}\n                    }\n                }\n                // Update the times\n                if (lnewStartTime)\n                {\n                    for (i=0; i<6; i++)\n                    {\n                        // Update the picks\n                        for (l=0; l<nTimeVars; l++)\n                        {\n                            ierr = sacio_getFloatHeader(timeVars[l],\n                                          grns[indices[i]].header, &time);\n                            if (ierr == 0)\n                            {\n                                time = time + epoch0; // Turn to real time\n                                time = time - epoch;  // Relative to new time\n                                sacio_setFloatHeader(timeVars[l], time,\n                                                    &grns[indices[i]].header);\n                            }\n                        } // Loop on picks\n                        sacio_setEpochalStartTime(epoch,\n                                                  &grns[indices[i]].header);\n                    } // Loop on signals\n                }\n                // Update the sampling period\n                if (lnewDt)\n                {\n                    for (i=0; i<6; i++)\n                    {\n                        sacio_setFloatHeader(SAC_FLOAT_DELTA, dt,\n                                             &grns[indices[i]].header);\n                    }\n                }\n            } // Loop on t*\n        } // Loop on depths\n        process_freeSerialCommands(&commands);\n        process_freeParallelCommands(&parallelCommands);\n        memory_free64f(&G);\n    }\nERROR:;\n    memory_free32i(&dataPtr);\n    return 0;\n}\n//============================================================================//\n/*!\n * @brief Writes a Green's functions archive that is appropriate for parmt.\n *\n * @param[in] archiveName   Name of archive file to write.\n * @param[in] nwaves        Number of waveforms.\n * @param[in] ndepths       Number of depths in grid-search.\n * @param[in] evla          Event latitude (degrees).\n * @param[in] evlo          Event longitude (degrees).\n * @param[in] depths        Depths (km) in grid search.  This is an array of\n *                          dimension [ndepths].\n * @param[in] sac           SAC observations to write.  This is an array of\n *                          dimension [nwaves].\n * @param[in] sacGrns       Corresponding Green's functions to write.  This\n *                          is an array of dimension [6 x ndepths x nwaves]\n *                          where the fastest dimension is 6 and the slowest\n *                          dimension is nwaves.  Each Green's function \n *                          group for the waveform, depth pair is packed:\n *                          \\f$ \\{ G_{xx}, G_{yy}, G_{zz},\n *                                 G_{xy}, G_{xz}, G_{yz} \\} \\f$.\n *\n * @result 0 indicates success. \n *\n * @author Ben Baker\n *\n */\nint prepmt_greens_writeArchive(const char *archiveName, //const char *archiveDir, const char *projnm,\n                               const int nwaves, const int ndepths,\n                               const double evla, const double evlo,\n                               const double *__restrict__ depths,\n                               const struct sacData_struct *sac,\n                               const struct sacData_struct *sacGrns)\n{\n    int id, ierr, indx, k;\n    hid_t h5fl;\n    // initialize the archive\n    ierr = prepmt_dataArchive_createArchive(archiveName, //archiveDir, projnm,\n                                            ndepths, evla, evlo, depths);\n    if (ierr != 0)\n    {\n         fprintf(stderr, \"%s: Error creating archive\\n\", __func__);\n         return -1;\n    }\n    // open it for writing\n    h5fl = prepmt_dataArchive_openArchive(archiveName, &ierr); //archiveDir, projnm, &ierr);\n    // write each observation and greens fns\n    for (k=0; k<nwaves; k++)\n    {\n        ierr = prepmt_dataArchive_addObservation(h5fl, sac[k]);\n        for (id=0; id<ndepths; id++)\n        {\n            indx = k*ndepths*6 + id*6;\n            ierr = prepmt_dataArchive_addGreensFunctions(h5fl, sac[k],\n                                              sacGrns[indx+0], sacGrns[indx+1],\n                                              sacGrns[indx+2], sacGrns[indx+3],\n                                              sacGrns[indx+4], sacGrns[indx+5]);\n            //printf(\"%f %e\\n\", sacGrns[indx+0].header.evdp, sacGrns[indx+0].data[12]);\n            if (ierr != 0){return -1;}\n        }\n    }\n    prepmt_dataArchive_closeArchive(h5fl);\n    return ierr;\n}\n//============================================================================//\nint prepmt_greens_cutHudson96FromData(const int nobs,\n                                      const struct sacData_struct *data,\n                                      const int ndepth, const int ntstar,\n                                      struct sacData_struct *grns)\n{\n    char **newCmds;\n    struct prepmtModifyCommands_struct options;\n    double cut0, dt, epoch, epochData;\n    int i, ierr, idep, indx, iobs, it, npts;\n    const int ncmds = 2;\n    //const char *cmds[2] = {\"cut\\0\", \"demean\\0\"};\n    struct prepmtCommands_struct prepMTcmds;\n    newCmds = (char **) calloc(2, sizeof(char *));\n    for (i=0; i<2; i++)\n    {\n        newCmds[i] = (char *) calloc(MAX_CMD_LEN, sizeof(char));\n    }\n    strcpy(newCmds[1], \"demean\\0\");\n\n    prepMTcmds.cmds = (struct prepmtCommandsChars_struct *)\n                      calloc(1, sizeof(struct prepmtCommandsChars_struct)); \n    prepMTcmds.cmds[0].ncmds = ncmds;\n    memset(&options, 0, sizeof(struct prepmtModifyCommands_struct));\n    for (iobs=0; iobs<nobs; iobs++)\n    { \n        // Get the primary pick\n        ierr = sacio_getEpochalStartTime(data[iobs].header, &epoch);\n        if (ierr != 0)\n        {\n            fprintf(stderr, \"%s: Error getting start time\\n\", __func__);\n            break;\n        }\n        epochData = epoch;\n        sacio_getFloatHeader(SAC_FLOAT_DELTA, data[iobs].header, &dt);\n        sacio_getIntegerHeader(SAC_INT_NPTS, data[iobs].header, &npts); \n        cut0 = epoch;\n        //cut1 = cut0 + dt*(double) (npts - 1);\n        for (idep=0; idep<ndepth; idep++)\n        {\n            for (it=0; it<ntstar; it++)\n            {\n                indx = prepmt_greens_getHudson96GreensFunctionIndex(G11_GRNS,\n                                                           nobs, ntstar, ndepth,\n                                                           iobs, it, idep);\n//printf(\"%d %d %d %d\\n\", iobs, it, idep, indx);\n                sacio_getEpochalStartTime(grns[indx].header, &epoch);\n                if (cut0 - epoch < 0.0)\n                {\n                    fprintf(stdout, \"%s: Cut may be funky\\n\", __func__);\n                }\n                options.cut0 = fmax(0.0, cut0 - epoch);\n                options.cut1 = options.cut0 + dt*(double) (npts - 1);\n/*\n                newCmds = prepmt_commands_modifyCommands(ncmds, cmds,\n                                                         options, grns[indx],\n                                                         &ierr);\n*/\n                ierr = cut_cutEpochalTimesToString(grns[indx].header.delta,\n                                                   0.0,\n                                                   options.cut0,\n                                                   options.cut1,\n                                                   newCmds[0]);\n                //strcpy(newCmds[1], \"demean\");\n                //printf(\"%s %f\\n\", newCmds[0], grns[indx].header.delta);\n                prepMTcmds.cmds[0].cmds = newCmds;\n                ierr = prepmt_greens_processHudson96Greens(1, 1, 1,\n                                                           prepMTcmds,\n                                                           &grns[indx]);\n                // Enforce the epochal time\n                for (i=0; i<6; i++)\n                {\n                    sacio_setEpochalStartTime(epochData, &grns[indx+i].header);\n                }\n//printf(\"%d %e\\n\", indx, array_max64f(grns[indx].npts, grns[indx].data));\n                for (i=0; i<ncmds; i++)\n                {\n               //     free(newCmds[i]);\n                }\n                //free(newCmds);\n            }\n        }\n    } \n    for (i=0; i<2; i++)\n    {\n        free(newCmds[i]);\n    }\n    free(newCmds[i]);\n    free(prepMTcmds.cmds);\n    return 0; \n}\n//============================================================================//\n/*!\n * @brief Convenience function for extracting the: \n *        \\$ \\{ G_{xx}, G_{yy}, G_{zz}, G_{xy}, G_{xz}, G_{yz} \\} \\$\n *        Green's functions indices for the observation, t*, and depth.\n *\n * @param[in] nobs      Total number of observations.\n * @param[in] ntstar    Total number of t*.\n * @param[in] ndepth    Total number of depths.\n * @param[in] iobs      Observation number.  This is C indexed.\n * @param[in] itstar    t* index.  This is C indexed.\n * @param[in] idepth    Depth index.  This is C indexed.\n * @param[in] grns      Contains the Green's functions.\n * @param[out] indices  Contains the Green's functions indices defining\n *                      the indices that return the:\n *                       \\$ \\{ G_{xx}, G_{yy}, G_{zz}, \n *                             G_{xy}, G_{xz}, G_{yz} \\} \\$\n *                      for this observation, t*, and depth. \n *\n * @result 0 indicates success.\n *\n * @author Ben Baker, ISTI\n *\n */\nint prepmt_greens_getHudson96GreensFunctionsIndices(\n    const int nobs, const int ntstar, const int ndepth,\n    const int iobs, const int itstar, const int idepth,\n    int indices[6])\n{\n    int i, ierr;\n    const enum prepmtGreens_enum mtTerm[6] = \n       {G11_GRNS, G22_GRNS, G33_GRNS, G12_GRNS, G13_GRNS, G23_GRNS};\n    ierr = 0;\n    for (i=0; i<6; i++)\n    {\n        indices[i] = prepmt_greens_getHudson96GreensFunctionIndex(mtTerm[i],\n                                                          nobs, ntstar, ndepth,\n                                                          iobs, itstar, idepth);\n        if (indices[i] < 0){ierr = ierr + 1;}\n    }\n    if (ierr != 0)\n    {\n        fprintf(stderr, \"%s: Error getting indices (obs,t*,depth)=(%d,%d,%d)\\n\",\n                __func__, iobs, itstar, idepth);\n    }\n    return ierr;\n}\n//============================================================================//\n/*!\n * @brief Aligns the Green's functions to the data via cross-correlation.\n *\n * @param[in] data          Holds the observed data.\n * @param[in] luseEnvelope  If true then cross-correlate the envelopes of\n *                          the waveforms. \\n\n *                          Otherwise, cross-correlate the waveforms\n *                          themselves.  In this case the absolute values\n *                          of the cross-correlation are used.\n * @param[in] lnorm         If true then use a normalized cross-correlation\n *                          so that all waveforms can contribute equally. \\n\n *                          Otherwise, use the non-normalized cross-correlation.\n * @param[in] maxTimLag     Max time lag (seconds) allowed in cross-correlation.\n *\n * @param[in,out] grns      On input contains the Green's functions to \n *                          align to the data.\n *                          On output contains the Green's functions which\n *                          have been aligned to the data via cross-correlation.\n *\n * @result 0 indicates success.\n *\n * @author Ben Baker, ISTI\n *\n */\nint prepmt_greens_xcAlignGreensToData(const struct sacData_struct data,\n                                      const bool luseEnvelope, const bool lnorm,\n                                      const double maxTimeLag,\n                                      struct sacData_struct *grns)\n{\n    double *dataPad, *Gxx, *Gyy, *Gzz, *Gxy, *Gxz, *Gyz, *xc,\n           dt, dtGrns, epochData, epochGrns;\n    int ierr, insertData, lxc, maxShift, npadData, npts, npgrns;\n    ierr = 0;\n    sacio_getIntegerHeader(SAC_INT_NPTS, data.header, &npts);\n    sacio_getIntegerHeader(SAC_INT_NPTS, grns[0].header, &npgrns);\n    if (npts < 1 || npgrns < 1)\n    {\n        fprintf(stderr, \"%s: Error no data\\n\", __func__);\n        fprintf(stderr, \"%s: Error no grns functions\\n\", __func__);\n        return -1;\n    }\n    sacio_getFloatHeader(SAC_FLOAT_DELTA, data.header, &dt);\n    sacio_getFloatHeader(SAC_FLOAT_DELTA, data.header, &dtGrns);\n    if (fabs(dt - dtGrns) > 1.e-6 || dt <= 0.0)\n    {\n        if (dt <= 0.0){fprintf(stderr, \"%s: dt is invalid\\n\", __func__);}\n        if (fabs(dt - dtGrns) > 1.e-6)\n        {\n            fprintf(stderr, \"%s: dt is inconsistent\\n\", __func__);\n        }\n        return -1;\n    }\n    // Need a common reference - choose the start time\n    ierr = sacio_getEpochalStartTime(data.header,    &epochData);\n    if (ierr != 0)\n    {\n        fprintf(stderr, \"%s: Error getting data start time\\n\", __func__);\n        return -1;\n    }\n    ierr = sacio_getEpochalStartTime(grns[0].header, &epochGrns);\n    if (ierr != 0)\n    {\n        fprintf(stderr, \"%s: Error getting grns start time\\n\", __func__);\n        return -1;\n    }\n    if (epochData < epochGrns)\n    {\n        fprintf(stderr, \"%s: epochData < epochGrns not programmed\\n\", __func__);\n        return -1;\n    }\n    // Insert the data in a epochal time aligned array\n    insertData = (int) ((epochData - epochGrns)/dt + 0.5);\n    npadData = insertData + npts;\n    //printf(\"%d %d\\n\", insertData, npts);\n    dataPad = memory_calloc64f(npadData);\n    array_copy64f_work(npts, data.data, &dataPad[insertData]);\n    // Create pointers to Green's functions \n    Gxx = grns[0].data;\n    Gyy = grns[1].data;\n    Gzz = grns[2].data;\n    Gxy = grns[3].data;\n    Gxz = grns[4].data;\n    Gyz = grns[5].data;\n    // Compute hte max lag\n    maxShift =-1;\n    if (maxTimeLag >= 0.0){maxShift = (int) (maxTimeLag/dt + 0.5);}\n//printf(\"%d %f %f\\n\", maxShift, maxTimeLag/dt, maxTimeLag);\n    // Align\n    lxc = npadData + npgrns - 1; //npts + npgrns - 1;\n    xc = memory_calloc64f(lxc);\n    ierr = prepmt_greens_xcAlignGreensToData_work(npadData, dataPad, //data.data,\n                                                  npgrns, luseEnvelope, lnorm,\n                                                  maxShift,\n                                                  Gxx, Gyy, Gzz,\n                                                  Gxy, Gxz, Gyz,\n                                                  lxc, xc);\n    memory_free64f(&xc);\n    memory_free64f(&dataPad);\n    // Dereference pointers\n    Gxx = NULL;\n    Gyy = NULL;\n    Gzz = NULL;\n    Gxy = NULL;\n    Gxz = NULL;\n    Gyz = NULL;\n    return ierr;\n}\n//============================================================================//\nint prepmt_greens_xcAlignGreensToData_work(\n    const int npts, double *__restrict__ data,\n    const int npgrns,\n    const bool luseEnvelope, const bool lnorm,\n    const int maxShift,\n    double *__restrict__ Gxx,\n    double *__restrict__ Gyy,\n    double *__restrict__ Gzz,\n    double *__restrict__ Gxy,\n    double *__restrict__ Gxz,\n    double *__restrict__ Gyz,\n    const int lxc, double *__restrict__ xc)\n{\n    double *dwork, *Gwork, *xcorrWork, egrns, esig, xdiv;\n    int i, ierr, ierr1, kmt, l1, l2, lag, lcref, nlag;\n    //------------------------------------------------------------------------//\n    ierr = 0;\n    lcref = npgrns + npts - 1;\n    if (lcref > lxc){return -1;}\n    xcorrWork = memory_calloc64f(lcref);\n    array_zeros64f_work(lxc, xc);\n    if (luseEnvelope)\n    {\n        Gwork = memory_calloc64f(npgrns);\n        dwork = memory_calloc64f(npts);\n        ierr = signal_filter_envelope64f_work(npts, data, dwork);\n        esig = cblas_dnrm2(npts, dwork, 1);\n    }\n    else\n    {\n        Gwork = NULL;\n        dwork = data;\n        esig = cblas_dnrm2(npts, data, 1);\n    }\n    // Loop on the Green's functions\n    for (kmt=0; kmt<6; kmt++)\n    {\n        if (kmt == 0)\n        {\n            if (!luseEnvelope)\n            {\n                Gwork = Gxx;\n            }\n            else\n            {\n                signal_filter_envelope64f_work (npgrns, Gxx, Gwork);\n            }\n        }\n        else if (kmt == 1)\n        {\n            if (!luseEnvelope)\n            {\n                Gwork = Gyy;\n            }\n            else\n            {\n                signal_filter_envelope64f_work (npgrns, Gyy, Gwork);\n            }\n        }\n        else if (kmt == 2)\n        {\n            if (!luseEnvelope)\n            {\n                Gwork = Gzz;\n            }\n            else\n            {\n                signal_filter_envelope64f_work (npgrns, Gzz, Gwork);\n            }\n        }\n        else if (kmt == 3)\n        {\n            if (!luseEnvelope)\n            {\n                Gwork = Gxy;\n            }\n            else\n            {\n                signal_filter_envelope64f_work (npgrns, Gxy, Gwork);\n            }\n        }\n        else if (kmt == 4)\n        {\n            if (!luseEnvelope)\n            {\n                Gwork = Gxz;\n            }\n            else\n            {\n                signal_filter_envelope64f_work (npgrns, Gxz, Gwork);\n            }\n        }\n        else\n        {\n            if (!luseEnvelope)\n            {\n                Gwork = Gyz;\n            }\n            else\n            {\n                signal_filter_envelope64f_work (npgrns, Gyz, Gwork);\n            }\n        }\n        egrns = cblas_dnrm2(npgrns, Gwork, 1);\n        ierr1 = signal_convolve_correlate64f_work(npts, dwork,\n                                                  npgrns,\n                                                  Gwork,\n                                                  CONVCOR_FULL,\n                                                  lcref, xcorrWork);\n        if (ierr1 != 0)\n        {\n            if (ierr1 != 0)\n            {\n                fprintf(stderr, \"%s: Error correlating kmt %d\\n\",\n                        __func__, kmt);\n            }\n            ierr = ierr + 1;\n        }\n        // sum in the result - absolute value handles polarity\n        else\n        {\n            xdiv = 1.0;\n            if (lnorm){xdiv = 1.0/(esig*egrns);}\n            if (luseEnvelope)\n            {\n                #pragma omp simd\n                for (i=0; i<lcref; i++)\n                {\n                    xc[i] = xc[i] + xcorrWork[i]*xdiv;\n                }\n            }\n            else\n            {\n                #pragma omp simd\n                for (i=0; i<lcref; i++)\n                {\n                    xc[i] = xc[i] + fabs(xcorrWork[i]*xdiv);\n//if (kmt == 5){printf(\"%e\\n\", xc[i]);}\n                }\n            }\n        }\n    } // Loop on green's functions\n    // Compute the lag where the times range from [-npgrns:npts].  Hence,\n    // lag = npgrns is the unlagged cross-correlation. \n    if (maxShift < 0)\n    {\n        lag = array_argmax64f(lcref, xc, &ierr);\n    }\n    else\n    {\n        l1 = MAX(0, npgrns - maxShift);\n        l2 = MIN(lcref - 1, npgrns + maxShift);\n        nlag = l2 - l1 + 1;\n        lag = l1 + array_argmax64f(nlag, &xc[l1], &ierr); \n    }\n    lag =-npgrns + lag;\n    //printf(\"%d %d %d\\n\", lag, npgrns, npts);\n/*\nfor (i=0; i<npts; i++)\n{\nprintf(\"%e\\n\", data[i]);\n}\nfor (i=0; i<npgrns; i++)\n{\nprintf(\"%e %e %e %e %e %e\\n\", Gxx[i], Gyy[i], Gzz[i], Gxy[i], Gxz[i], Gyz[i]); \n}\nfor (i=0; i<lcref; i++)\n{\nprintf(\"%d %e\\n\",-npgrns+i, xc[i]); \n}\nprintf(\"%d\\n\", lag);\n*/\n//getchar();\n    // Shift the greens' functions\n    array_zeros64f_work(lcref, xcorrWork);\n    shiftGreens(npgrns, lag, Gxx, xcorrWork);\n    shiftGreens(npgrns, lag, Gyy, xcorrWork);\n    shiftGreens(npgrns, lag, Gzz, xcorrWork);\n    shiftGreens(npgrns, lag, Gxy, xcorrWork);\n    shiftGreens(npgrns, lag, Gxz, xcorrWork);\n    shiftGreens(npgrns, lag, Gyz, xcorrWork);\n    if (luseEnvelope)\n    {\n        memory_free64f(&Gwork);\n        memory_free64f(&dwork);\n    }\n    else\n    {\n        dwork = NULL;\n        Gwork = NULL;\n    }\n    memory_free64f(&xcorrWork);\n    return 0;\n}\n//============================================================================//\n/*!\n * @brief Utility function for use after the Green's functions have been \n *        manually aligned to issue a measure of the alignment quality.\n *\n * @param[in] npts          Number of points in data and Green's functions.\n * @param[in] luseEnvelope  If true then cross-correlate the envelopes of\n *                          the waveforms. \\n\n *                          Otherwise, cross-correlate the waveforms\n *                          themselves.  In this case the absolute values\n *                          of the cross-correlation are used.\n * @param[in] lnorm         If true then use a normalized cross-correlation\n *                          so that all waveforms can contribute equally. \\n\n *                          Otherwise, use the non-normalized cross-correlation.\n * @param[in] data          Observed waveforms.  This is an array of dimension\n *                          [npts].\n * @param[in] Gxx           Aligned Gxx Green's function.  This is an array of\n *                          dimension [npts].\n * @param[in] Gyy           Aligned Gyy Green's function.  This is an array of\n *                          dimension [npts].\n * @param[in] Gzz           Aligned Gzz Green's function.  This is an array of\n *                          dimension [npts].\n * @param[in] Gxy           Aligned Gxy Green's function.  This is an array of\n *                          dimension [npts].\n * @param[in] Gxz           Aligned Gxz Green's function.  This is an array of\n *                          dimension [npts].\n * @param[in] Gyz           Aligned Gyz Green's function.  This is an array of\n *                          dimension [npts].\n *\n * @param[out] ierr         0 indicates success.\n *\n * @result The zero-lag cross-correlation score of the Green's function to \n *         data alignment.\n *\n * @author Ben Baker, ISTI\n *\n */\ndouble prepmt_greens_scoreXCAlignment(const int npts,\n                                      const bool luseEnvelope,\n                                      const bool lnorm,\n                                      const double *__restrict__ data,\n                                      const double *__restrict__ Gxx,\n                                      const double *__restrict__ Gyy,\n                                      const double *__restrict__ Gzz,\n                                      const double *__restrict__ Gxy,\n                                      const double *__restrict__ Gxz,\n                                      const double *__restrict__ Gyz,\n                                      int *ierr)\n{\n    double *dwork, *Gwork, egrns, esig, xcStack, xdiv;\n    const double *G;\n    int i;\n    enum isclError_enum isclError;\n    *ierr = 0;\n    xcStack = 0.0;\n    dwork = NULL;\n    G = NULL;\n    Gwork = memory_calloc64f(npts);\n    if (luseEnvelope)\n    {\n        dwork = signal_filter_envelope64f(npts, data, &isclError);\n        if (isclError != ISCL_SUCCESS)\n        {\n            fprintf(stderr, \"%s: Error computing data envelope\\n\", __func__);\n            *ierr = 1;\n            return xcStack;\n        }\n        esig = cblas_dnrm2(npts, dwork, 1);\n    }\n    else\n    {\n        dwork = array_copy64f(npts, data, &isclError);\n        if (isclError != ISCL_SUCCESS)\n        {\n            fprintf(stderr, \"%s: Error copying data\\n\", __func__);\n            *ierr = 1; \n            return xcStack;\n        }\n        esig = cblas_dnrm2(npts, data, 1);\n    }\n    for (i=0; i<6; i++)\n    {\n        if (i == 0)\n        {\n            G = Gxx;\n        }\n        else if (i == 1)\n        {\n            G = Gyy;\n        }\n        else if (i == 2)\n        {\n            G = Gzz;\n        }\n        else if (i == 3)\n        {\n            G = Gxy;\n        }\n        else if (i == 4)\n        {\n            G = Gxz;\n        }\n        else if (i == 5)\n        {\n            G = Gyz;\n        }\n        if (luseEnvelope)\n        {\n            isclError = signal_filter_envelope64f_work(npts, G, Gwork);\n            if (isclError != ISCL_SUCCESS)\n            {\n                fprintf(stderr, \"%s: Error computing Grns envelope\\n\",\n                        __func__);\n                *ierr = 1; \n                return xcStack;\n            }\n        }\n        else\n        {\n            isclError = array_copy64f_work(npts, G, Gwork);\n            if (isclError != ISCL_SUCCESS)\n            {\n                fprintf(stderr, \"%s: Error copying G to Gwork\\n\", __func__);\n                *ierr = 1;\n                return xcStack;\n            }\n        }\n        egrns = cblas_dnrm2(npts, Gwork, 1);\n        xdiv = 1.0;\n        if (lnorm){xdiv = 1.0/(esig*egrns);}\n        xdiv = xdiv*1.0/6.0; // Normalization term for sum\n        if (luseEnvelope)\n        {\n            xcStack = xcStack + xdiv*cblas_ddot(npts, dwork, 1, Gwork, 1);\n        }\n        else\n        {\n            xcStack = xcStack + xdiv*fabs(cblas_ddot(npts, dwork, 1, Gwork, 1));\n        }\n        G = NULL;\n    }\n    memory_free64f(&dwork);\n    memory_free64f(&Gwork);\n    return xcStack;\n}\n//============================================================================//\nstatic int getPrimaryArrival(const struct sacHeader_struct hdr,\n                             double *time, char phaseName[8])\n{\n    const enum sacHeader_enum timeVars[11]\n       = {SAC_FLOAT_A,\n          SAC_FLOAT_T0, SAC_FLOAT_T1, SAC_FLOAT_T2, SAC_FLOAT_T3,\n          SAC_FLOAT_T4, SAC_FLOAT_T5, SAC_FLOAT_T6, SAC_FLOAT_T7,\n          SAC_FLOAT_T8, SAC_FLOAT_T9};\n    const enum sacHeader_enum timeVarNames[11]\n       = {SAC_CHAR_KA,\n          SAC_CHAR_KT0, SAC_CHAR_KT1, SAC_CHAR_KT2, SAC_CHAR_KT3,\n          SAC_CHAR_KT4, SAC_CHAR_KT5, SAC_CHAR_KT6, SAC_CHAR_KT7,\n          SAC_CHAR_KT8, SAC_CHAR_KT9};\n    int i, ifound1, ifound2; \n    memset(phaseName, 0, 8*sizeof(char));\n    for (i=0; i<11; i++)\n    {\n        ifound1 = sacio_getFloatHeader(timeVars[i], hdr, time);\n        ifound2 = sacio_getCharacterHeader(timeVarNames[i], hdr, phaseName); \n        if (ifound1 == 0 && ifound2 == 0){return 0;}\n    }\n    fprintf(stderr, \"%s: Failed to get primary pick\\n\", __func__);\n    *time =-12345.0;\n    memset(phaseName, 0, 8*sizeof(char));\n    strcpy(phaseName, \"-12345\"); \n    return -1;\n}\n//============================================================================//\nstatic int getPrimaryArrivalNoPolarity(const struct sacHeader_struct hdr,\n                                       double *time, char phaseName[8])\n{\n    int ierr;\n    size_t lenos;\n    ierr = getPrimaryArrival(hdr, time, phaseName);\n    if (ierr == 0)\n    {\n        lenos = strlen(phaseName);\n        if (lenos > 0)\n        {\n            if (phaseName[lenos-1] == '+' || phaseName[lenos-1] == '-')\n            {\n                phaseName[lenos-1] = '\\0';\n            }\n        }\n    }\n    return ierr;\n}\n//============================================================================//\nstatic void shiftGreens(const int npgrns, const int lag,\n                        double *__restrict__ G, double *__restrict__ work)\n{\n    int ncopy; \n    if (lag == 0){return;}\n    array_copy64f_work(npgrns, G, work);\n    array_zeros64f_work(npgrns, G);\n    if (lag > 0)\n    {\n        ncopy = npgrns - lag;\n        array_copy64f_work(ncopy, work, &G[lag]);\n    }\n    else\n    {\n        ncopy = npgrns + lag;\n        array_copy64f_work(ncopy, &work[-lag], G);\n    }\n    return;\n}\n", "meta": {"hexsha": "fa76bdcee250062b2a7319dc2628eb548cf8782c", "size": 58801, "ext": "c", "lang": "C", "max_stars_repo_path": "prepmt/greens.c", "max_stars_repo_name": "bakerb845/parmt", "max_stars_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_stars_repo_licenses": ["Intel"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "prepmt/greens.c", "max_issues_repo_name": "bakerb845/parmt", "max_issues_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_issues_repo_licenses": ["Intel"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "prepmt/greens.c", "max_forks_repo_name": "bakerb845/parmt", "max_forks_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_forks_repo_licenses": ["Intel"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8628461043, "max_line_length": 154, "alphanum_fraction": 0.466284587, "num_tokens": 14695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489883132727684, "lm_q2_score": 0.02716922917255984, "lm_q1q2_score": 0.011272481431758035}}
{"text": "/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*\n**                                                                                  **\n** This file forms part of the Underworld geophysics modelling application.         **\n**                                                                                  **\n** For full license and copyright information, please refer to the LICENSE.md file  **\n** located at the project root, or contact the authors.                             **\n**                                                                                  **\n**~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/\n#include <petsc.h>\n#include <petscmat.h>\n#include <petscvec.h>\n#include <petscksp.h>\n#include <petscpc.h>\n\n#include \"common-driver-utils.h\"\n#include \"pc_GtKG.h\"\n#include \"pc_ScaledGtKG.h\"\n\n\nPetscErrorCode BSSCR_PetscExtStokesSolversInitialize( void )\n{\n    Stg_PCRegister( \"gtkg\", \"Solvers/KSPSolvers/src/BSSCR\", \"BSSCR_PCCreate_GtKG\", BSSCR_PCCreate_GtKG );\n\t//Stg_PCRegister( \"bfbt\", \"Solvers/KSPSolvers/src/BSSCR\", \"BSSCR_PCCreate_GtKG\", BSSCR_PCCreate_GtKG );\n\tPetscFunctionReturn(0);\n}\n\n\nPetscErrorCode BSSCR_PetscExtStokesSolversFinalize( void )\n{\n\t\n#if ((PETSC_VERSION_MAJOR==3) && (PETSC_VERSION_MINOR>=4))\n//  PCFinalizePackage();\n#else\n//  PCRegisterDestroy();\n#endif\n\t\n\tPetscFunctionReturn(0);\n}\n\n\n\n", "meta": {"hexsha": "af15d567552560b1fb889d6b53a0b43d074ee756", "size": 1407, "ext": "c", "lang": "C", "max_stars_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/register_stokes_solvers.c", "max_stars_repo_name": "longgangfan/underworld2", "max_stars_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 116.0, "max_stars_repo_stars_event_min_datetime": "2015-09-28T10:30:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T04:12:38.000Z", "max_issues_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/register_stokes_solvers.c", "max_issues_repo_name": "longgangfan/underworld2", "max_issues_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 561.0, "max_issues_repo_issues_event_min_datetime": "2015-09-29T06:05:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T23:37:29.000Z", "max_forks_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/register_stokes_solvers.c", "max_forks_repo_name": "longgangfan/underworld2", "max_forks_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 68.0, "max_forks_repo_forks_event_min_datetime": "2015-12-14T21:57:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-25T04:54:26.000Z", "avg_line_length": 33.5, "max_line_length": 105, "alphanum_fraction": 0.4989339019, "num_tokens": 467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326184801538616, "lm_q2_score": 0.024798161907285888, "lm_q1q2_score": 0.011240060693481154}}
{"text": "/* $Id$      */\n/*--------------------------------------------------------------------*/\n/*;  Copyright (C) 2013                                               */\n/*;  Associated Universities, Inc. Washington DC, USA.                */\n/*;                                                                   */\n/*;  This program is free software; you can redistribute it and/or    */\n/*;  modify it under the terms of the GNU General Public License as   */\n/*;  published by the Free Software Foundation; either version 2 of   */\n/*;  the License, or (at your option) any later version.              */\n/*;                                                                   */\n/*;  This program is distributed in the hope that it will be useful,  */\n/*;  but WITHOUT ANY WARRANTY; without even the implied warranty of   */\n/*;  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the    */\n/*;  GNU General Public License for more details.                     */\n/*;                                                                   */\n/*;  You should have received a copy of the GNU General Public        */\n/*;  License along with this program; if not, write to the Free       */\n/*;  Software Foundation, Inc., 675 Massachusetts Ave, Cambridge,     */\n/*;  MA 02139, USA.                                                   */\n/*;                                                                   */\n/*;Correspondence about this software should be addressed as follows: */\n/*;         Internet email: bcotton@nrao.edu.                         */\n/*;         Postal address: William Cotton                            */\n/*;                         National Radio Astronomy Observatory      */\n/*;                         520 Edgemont Road                         */\n/*;                         Charlottesville, VA 22903-2475 USA        */\n/*--------------------------------------------------------------------*/\n#ifndef OBITRMFIT_H \n#define OBITRMFIT_H \n\n#include \"Obit.h\"\n#include \"ObitErr.h\"\n#include \"ObitImage.h\"\n#include \"ObitBeamShape.h\"\n#include \"ObitThread.h\"\n#include \"ObitInfoList.h\"\n#ifdef HAVE_GSL\n#include <gsl/gsl_multifit_nlin.h>\n#endif /* HAVE_GSL */ \n\n/*-------- Obit:  Merx mollis mortibus nuper ------------------*/\n/**\n * \\file ObitRMFit.h\n *\n * ObitRMFit Class for fitting rotatioin measures (RM) to Stokes Q and U image pixels\n *\n * This class does least squares fitting of RM and EVPA at 0 lambda^2\n * Either an image cube or a set of single plane images at arbitrary \n * lambda squares may be fitted.\n * The result is an image cube of RM and  EVPA at 0 lambda^2 as the planes.\n * The function ObitRMFitEval will evaluate this fit and return an image\n * with the flux densities at the desired frequencies.\n * \n * \\section ObitRMFitaccess Creators and Destructors\n * An ObitRMFit will usually be created using ObitRMFitCreate which allows \n * specifying a name for the object as well as other information.\n *\n * A copy of a pointer to an ObitRMFit should always be made using the\n * #ObitRMFitRef function which updates the reference count in the object.\n * Then whenever freeing an ObitRMFit or changing a pointer, the function\n * #ObitRMFitUnref will decrement the reference count and destroy the object\n * when the reference count hits 0.\n * There is no explicit destructor.\n */\n\n/*--------------Class definitions-------------------------------------*/\n/** ObitRMFit Class structure. */\ntypedef struct {\n#include \"ObitRMFitDef.h\"   /* this class definition */\n} ObitRMFit;\n\n/*----------------- Macroes ---------------------------*/\n/** \n * Macro to unreference (and possibly destroy) an ObitRMFit\n * returns a ObitRMFit*.\n * in = object to unreference\n */\n#define ObitRMFitUnref(in) ObitUnref (in)\n\n/** \n * Macro to reference (update reference count) an ObitRMFit.\n * returns a ObitRMFit*.\n * in = object to reference\n */\n#define ObitRMFitRef(in) ObitRef (in)\n\n/** \n * Macro to determine if an object is the member of this or a \n * derived class.\n * Returns TRUE if a member, else FALSE\n * in = object to reference\n */\n#define ObitRMFitIsA(in) ObitIsA (in, ObitRMFitGetClass())\n\n/*---------------Public functions---------------------------*/\n/** Public: Class initializer. */\nvoid ObitRMFitClassInit (void);\n\n/** Public: Default Constructor. */\nObitRMFit* newObitRMFit (gchar* name);\n\n/** Public: Create/initialize ObitRMFit structures */\nObitRMFit* ObitRMFitCreate (gchar* name, olong nterm);\n/** Typedef for definition of class pointer structure */\ntypedef ObitRMFit* (*ObitRMFitCreateFP) (gchar* name, \n\t\t\t\t\t\t     olong nterm);\n\n/** Public: ClassInfo pointer */\ngconstpointer ObitRMFitGetClass (void);\n\n/** Public: Copy (deep) constructor. */\nObitRMFit* ObitRMFitCopy  (ObitRMFit *in, ObitRMFit *out, ObitErr *err);\n\n/** Public: Copy structure. */\nvoid ObitRMFitClone (ObitRMFit *in, ObitRMFit *out, ObitErr *err);\n\n/** Public: Fit spectrum to an image cube */\nvoid ObitRMFitCube (ObitRMFit* in, ObitImage *inQImage, ObitImage *inUImage, \n\t\t    ObitImage *outImage, ObitErr *err);\n/** Typedef for definition of class pointer structure */\ntypedef void(*ObitRMFitCubeFP) (ObitRMFit* in, \n\t\t\t\tObitImage *inQImage, ObitImage *inUImage, \n\t\t\t\tObitImage *outImage, ObitErr *err);\n\n/** Public: Fit spectrum to an array of images */\nvoid ObitRMFitImArr (ObitRMFit* in, olong nimage, \n\t\t     ObitImage **imQArr, ObitImage **imUArr, \n\t\t     ObitImage *outImage, ObitErr *err);\n/** Typedef for definition of class pointer structure */\ntypedef void(*ObitRMFitImArrFP) (ObitRMFit* in, olong nimage, \n\t\t\t\t ObitImage **imQArr, ObitImage **imUArr, \n\t\t\t\t ObitImage *outImage, ObitErr *err);\n\n\n/** Public: Fit single spectrum */\nofloat* ObitRMFitSingle (olong nlamb2, olong nterm, odouble refLamb2, odouble *lamb2, \n\t\t\t ofloat *qflux, ofloat *qsigma, ofloat *uflux, ofloat *usigma, \n\t\t\t ObitErr *err);\n/** Typedef for definition of class pointer structure */\ntypedef ofloat*(*ObitRMFitSingleFP) (olong nlamb2, olong nterm, odouble refLamb2, odouble *lamb2,\n\t\t\t\t     ofloat *qflux, ofloat *qsigma, ofloat *uflux, ofloat *usigma,\n\t\t\t\t     ObitErr *err);\n\n/** Public: Make fitting arg structure */\ngpointer ObitRMFitMakeArg (olong nlamb2, olong nterm, \n\t\t\t   odouble refLamb2, odouble *lamb2, \n\t\t\t   ofloat **out, ObitErr *err);\n\n/** Public: Fit single RM using arg */\nvoid ObitRMFitSingleArg (gpointer arg,\n\t\t\t ofloat *qflux, ofloat *qsigma, \n\t\t\t ofloat *uflux, ofloat *usigma,\n\t\t\t ofloat *out);\n\n/** Public: Kill fitting arg structure */\nvoid ObitRMFitKillArg (gpointer arg);\n/*----------- ClassInfo Structure -----------------------------------*/\n/**\n * ClassInfo Structure.\n * Contains class name, a pointer to any parent class\n * (NULL if none) and function pointers.\n */\ntypedef struct  {\n#include \"ObitRMFitClassDef.h\"\n} ObitRMFitClassInfo; \n\n#endif /* OBITFRMFIT_H */ \n", "meta": {"hexsha": "714d54462a6b48faf1e612dbbbf5f1ba7de04f0c", "size": 6785, "ext": "h", "lang": "C", "max_stars_repo_path": "ObitSystem/Obit/include/ObitRMFit.h", "max_stars_repo_name": "sarrvesh/Obit", "max_stars_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-08-26T06:53:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-20T01:08:59.000Z", "max_issues_repo_path": "ObitSystem/Obit/include/ObitRMFit.h", "max_issues_repo_name": "sarrvesh/Obit", "max_issues_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ObitSystem/Obit/include/ObitRMFit.h", "max_forks_repo_name": "sarrvesh/Obit", "max_forks_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-08-29T15:12:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:16:08.000Z", "avg_line_length": 40.3869047619, "max_line_length": 97, "alphanum_fraction": 0.6097273397, "num_tokens": 1713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40733340004593027, "lm_q2_score": 0.02758528462507248, "lm_q1q2_score": 0.011236407777565498}}
{"text": "#include \"tools.h\"\n\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n\ngsl_rng **_random = NULL;\n\ndouble tool_get_time()\n{\n    struct timeval t;\n    gettimeofday(&t, NULL);\n    return (double)t.tv_sec + (double)t.tv_usec * 1e-6;\n}\n\ndouble tool_cut(double x)\n{\n    if (x <= 0.0)\n        return 0.0;\n    if (x >= 1.0)\n        return 1.0;\n    return x;\n}\n\nvoid print_array(double c[], int l)\n{\n    for (int i = 0; i < l - 1; i++)\n    {\n        printf(\"%.3f \", c[i]);\n    }\n    printf(\"%.3f\\n\", c[l - 1]);\n}\n\nvoid print_array_b(bool c[], int l)\n{\n    for (int i = 0; i < l - 1; i++)\n    {\n        printf(\"%d,\", c[i] ? 1 : 0);\n    }\n    printf(\"%d\\n\", c[l - 1] ? 1 : 0);\n}\n\nvoid print_array_i(int c[], int l)\n{\n    for (int i = 0; i < l - 1; i++)\n    {\n        printf(\"%d,\", c[i]);\n    }\n    printf(\"%d\\n\", c[l - 1]);\n}\n\nvoid print_array_ui(unsigned int c[], int l)\n{\n    for (int i = 0; i < l - 1; i++)\n    {\n        printf(\"%u,\", c[i]);\n    }\n    printf(\"%u\\n\", c[l - 1]);\n}\n\nvoid print_array_2d(bool **c, int xlen, int ylen)\n{\n    for (int x = 0; x < xlen; x++)\n    {\n        for (int y = 0; y < ylen; y++)\n        {\n            printf(\"%d,\", c[x][y]);\n        }\n        puts(\"\");\n    }\n}\n\nvoid print_array_2d_d(double **c, int xlen, int ylen)\n{\n    for (int x = 0; x < xlen; x++)\n    {\n        for (int y = 0; y < ylen; y++)\n        {\n            printf(\"%.2f,\", c[x][y]);\n        }\n        puts(\"\");\n    }\n}\n\nvoid tool_free_array_d(double **a, int xlen)\n{\n    for (int x = 0; x < xlen; x++)\n    {\n        free(a[x]);\n    }\n    free(a);\n}\n\nvoid tool_free_array_b(bool **a, int xlen)\n{\n    for (int x = 0; x < xlen; x++)\n    {\n        free(a[x]);\n    }\n    free(a);\n}\n\nvoid tool_free_array_ui(unsigned int **a, int xlen)\n{\n    for (int x = 0; x < xlen; x++)\n    {\n        free(a[x]);\n    }\n    free(a);\n}\n\nbool **tool_alloc_array_b(int xlen, int ylen)\n{\n\n    bool **a = (bool **)malloc(xlen * sizeof(bool *));\n    for (int x = 0; x < xlen; x++)\n    {\n        a[x] = (bool *)calloc((size_t)ylen, sizeof(bool));\n    }\n    return a;\n}\n\nunsigned int **tool_alloc_array_ui(int xlen, int ylen)\n{\n\n    unsigned int **a = (unsigned int **)malloc(xlen * sizeof(unsigned int *));\n    for (int x = 0; x < xlen; x++)\n    {\n        a[x] = (unsigned int *)calloc((size_t)ylen, sizeof(unsigned int));\n    }\n    return a;\n}\n\ndouble **tool_alloc_array_d(int xlen, int ylen)\n{\n    double **a = (double **)malloc(xlen * sizeof(double *));\n    for (int x = 0; x < xlen; x++)\n    {\n        a[x] = (double *)calloc((size_t)ylen, sizeof(double));\n    }\n    return a;\n}\n\nvoid tool_array_bool_to_double(double *res, bool *src, int len)\n{\n    for (int i = 0; i < len; i++)\n    {\n        res[i] = src[i] ? 1.0 : 0.0;\n    }\n}\n\nvoid tool_round(double **a, int xlen, int ylen)\n{\n    for (int x = 0; x < xlen; x++)\n        for (int y = 0; y < ylen; y++)\n            a[x][y] = round(a[x][y]);\n}\n\nstatic int tool_current_thread()\n{\n#ifdef _USE_OPENMP\n    return omp_get_thread_num();\n#else\n    return 0;\n#endif\n}\n\ndouble tool_rand()\n{\n    return gsl_rng_uniform(_random[tool_current_thread()]);\n}\n\n/*\n * Returns random int from [min, max-1]\n */\nint tool_rand_i(int min, int max)\n{\n    return min + gsl_rng_uniform_int(_random[tool_current_thread()], max - min);\n}\n\nvoid tool_fill_random1(double *a, int xlen, bool deterministic)\n{\n    for (int x = 0; x < xlen; x++)\n    {\n        a[x] = tool_rand();\n        if (deterministic)\n        {\n            a[x] = a[x] > 0.5 ? 1 : 0;\n        }\n    }\n}\n\nvoid tool_fill_random1ui(unsigned int *a, int xlen, int min, int max)\n{\n    for (int x = 0; x < xlen; x++)\n    {\n        a[x] = (unsigned int)tool_rand_i(min, max);\n    }\n}\n\nvoid tool_fill_random1i(int *a, int xlen, int min, int max)\n{\n    for (int x = 0; x < xlen; x++)\n    {\n        a[x] = tool_rand_i(min, max);\n    }\n}\n\nvoid tool_fill_random1b(bool *a, int xlen)\n{\n    for (int x = 0; x < xlen; x++)\n    {\n        a[x] = tool_rand() < 0.5;\n    }\n}\n\nvoid tool_fill_random(double **a, int xlen, int ylen, bool deterministic)\n{\n    for (int x = 0; x < xlen; x++)\n    {\n        for (int y = 0; y < ylen; y++)\n        {\n            a[x][y] = tool_rand();\n            if (deterministic)\n            {\n                a[x][y] = a[x][y] > 0.5 ? 1 : 0;\n            }\n        }\n    }\n}\n\nvoid tool_fill_random_d(double **a, int xlen, int ylen)\n{\n    for (int x = 0; x < xlen; x++)\n    {\n        for (int y = 0; y < ylen; y++)\n        {\n            a[x][y] = tool_rand(); // < 0.5 ? 1 : 0;\n        }\n    }\n}\n\nvoid tool_fill_random_b(bool **a, int xlen, int ylen)\n{\n    for (int x = 0; x < xlen; x++)\n    {\n        double p = tool_rand();\n        for (int y = 0; y < ylen; y++)\n        {\n            a[x][y] = tool_rand() <= p;\n        }\n    }\n}\n\nvoid tool_fill_random_ui(unsigned int **a, int xlen, int ylen, int min, int max)\n{\n    for (int x = 0; x < xlen; x++)\n    {\n        for (int y = 0; y < ylen; y++)\n        {\n            a[x][y] = (unsigned int)tool_rand_i(min, max);\n        }\n    }\n}\n\ndouble tool_sum(double **a, int xlen, int ylen)\n{\n    double res = 0;\n    for (int x = 0; x < xlen; x++)\n        for (int y = 0; y < ylen; y++)\n            res += a[x][y];\n    return res;\n}\n\nint tool_foldedSize(int s, int r)\n{\n    return s + 2 * r;\n}\n\nvoid tool_fold(bool *f_res, bool *u_src, int u_len, int r)\n{\n    memcpy(f_res + r, u_src, (size_t)u_len * sizeof(bool));\n    memcpy(f_res, u_src + u_len - r, (size_t)r * sizeof(bool));\n    memcpy(f_res + r + u_len, u_src, (size_t)r * sizeof(bool));\n}\n\nvoid tool_fold_d(double *f_res, double *u_src, int u_len, int r)\n{\n    memcpy(f_res + r, u_src, (size_t)u_len * sizeof(double));\n    memcpy(f_res, u_src + u_len - r, (size_t)r * sizeof(double));\n    memcpy(f_res + r + u_len, u_src, (size_t)r * sizeof(double));\n}\n\nvoid tool_unfold(bool u_res[], bool f_src[], int f_len, int r)\n{\n    memcpy(u_res, f_src + r, (size_t)(f_len - 2 * r) * sizeof(bool));\n}\n\nvoid tool_unfold_d(double u_res[], double f_src[], int f_len, int r)\n{\n    memcpy(u_res, f_src + r, (size_t)(f_len - 2 * r) * sizeof(double));\n}\n\nvoid tool_add(double **res, bool **src, int xlen, int ylen)\n{\n    for (int x = 0; x < xlen; x++)\n        for (int y = 0; y < ylen; y++)\n            res[x][y] += src[x][y] ? 1.0 : 0.0;\n}\n\nvoid tool_mult(double **a, double c, int xlen, int ylen)\n{\n    for (int x = 0; x < xlen; x++)\n        for (int y = 0; y < ylen; y++)\n            a[x][y] *= c;\n}\n\nvoid tool_abs_subst(double **res, bool **a, double **b, int xlen, int ylen)\n{\n    for (int x = 0; x < xlen; x++)\n        for (int y = 0; y < ylen; y++)\n        {\n            res[x][y] = fabs((a[x][y] ? 1.0 : 0.0) - b[x][y]);\n        }\n}\n\ndouble tool_1d_max(double *a, int len)\n{\n    double max = 0.0;\n    for (int i = 0; i < len; i++)\n    {\n        if (a[i] > max)\n            max = a[i];\n    }\n    return max;\n}\n\nint tool_differences(bool **a, bool **b, int xlen, int ylen)\n{\n    int result = 0;\n    for (int x = 0; x < xlen; x++)\n    {\n        for (int y = 0; y < ylen; y++)\n        {\n            if (a[x][y] && !b[x][y])\n                result++;\n            if (!a[x][y] && b[x][y])\n                result++;\n        }\n    }\n    return result;\n}\n\nstatic int tool_num_threads()\n{\n#ifdef _USE_OPENMP\n    return omp_get_num_threads();\n#else\n    return 1;\n#endif\n}\n\nvoid tool_fake_random()\n{\n    int threads = 0;\n#ifdef _USE_OPENMP\n#pragma omp parallel\n#pragma omp master\n#endif\n    {\n        threads = tool_num_threads();\n        const gsl_rng_type *T;\n        gsl_rng_env_setup();\n        T = gsl_rng_default;\n        _random = (gsl_rng **)malloc(threads * sizeof(gsl_rng *));\n        for (int i = 0; i < threads; i++)\n        {\n            _random[i] = gsl_rng_alloc(T);\n            gsl_rng_set(_random[i], 1234567890);\n        }\n    }\n}\n\nvoid tool_init_random()\n{\n    int threads = 0;\n#ifdef _USE_OPENMP\n#pragma omp parallel\n#pragma omp master\n#endif\n    {\n        if (_random == NULL)\n        {\n            threads = tool_num_threads();\n\n#ifndef _USE_RAND\n#ifdef __APPLE__\n            srandomdev();\n#else\n            srandom((unsigned int)tool_get_time());\n#endif\n#else\n            srand((unsigned int)tool_get_time());\n#endif\n\n            const gsl_rng_type *T;\n\n            gsl_rng_env_setup();\n\n            T = gsl_rng_default;\n\n            _random = (gsl_rng **)malloc(threads * sizeof(gsl_rng *));\n            for (int i = 0; i < threads; i++)\n            {\n                _random[i] = gsl_rng_alloc(T);\n                unsigned long int seed;\n#ifdef _USE_RAND\n                seed = (unsigned long int)rand();\n#else\n                seed = (unsigned long int)random();\n#endif\n                gsl_rng_set(_random[i], seed);\n            }\n        }\n    }\n}\n\ndouble tool_rand_gauss(double sigma)\n{\n    return gsl_ran_gaussian_ziggurat(_random[tool_current_thread()], sigma);\n}\n\nint tool_cap(int a, int min, int max)\n{\n    if (a > max)\n        return max;\n    if (a < min)\n        return min;\n    return a;\n}\n\nvoid tool_range(int *result, int start, int len)\n{\n    for (int i = start; i < start + len; i++)\n    {\n        result[i - start] = i;\n    }\n}\n\nint *tool_alloc_range(int start, int len)\n{\n    int *a = (int *)malloc(sizeof(int) * len);\n    tool_range(a, start, len);\n    return a;\n}\n\n#ifdef __APPLE__\nint _compr(void *f, const void *a, const void *b)\n{\n#else\nint _compr(const void *a, const void *b, void *f)\n{\n#endif\n    double *fitness = (double *)f;\n    int i1 = (int)(*(int *)a);\n    int i2 = (int)(*(int *)b);\n    double diff = fitness[i1] - fitness[i2];\n    if (diff == 0.0)\n        return 0;\n    if (diff > 0.0)\n        return 1;\n    return -1;\n}\n\nint *tool_sort_fitness_index(int *index, double *fitness, int count)\n{\n#ifdef __APPLE__\n    qsort_r(index, count, sizeof(int), fitness, _compr);\n#else\n    qsort_r(index, count, sizeof(int), _compr, fitness);\n#endif\n    return index;\n}\n\n#ifdef __APPLE__\nint _compr_int(void *f, const void *a, const void *b)\n{\n#else\nint _compr_int(const void *a, const void *b, void *f)\n{\n#endif\n    int *fitness = (int *)f;\n    int i1 = (int)(*(int *)a);\n    int i2 = (int)(*(int *)b);\n    int diff = fitness[i1] - fitness[i2];\n    if (diff == 0)\n        return 0;\n    if (diff > 0)\n        return 1;\n    return -1;\n}\n\nint *tool_sort_index_int(int *index, int *array, int count)\n{\n#ifdef __APPLE__\n    qsort_r(index, count, sizeof(int), array, _compr_int);\n#else\n    qsort_r(index, count, sizeof(int), _compr_int, array);\n#endif\n    return index;\n}\n\nbool tool_row_cmp(bool *r1, bool *r2, int len)\n{\n    for (int i = 0; i < len; i++)\n    {\n        if (r1[i] != r2[i])\n            return false;\n    }\n    return true;\n}\n\ndouble tool_avg(double *a, int len)\n{\n    double result = 0;\n    for (int i = 0; i < len; i++)\n        result += a[i];\n    return result / len;\n}\n\ndouble tool_max(double *a, int len)\n{\n    double result = a[0];\n    for (int i = 1; i < len; i++)\n    {\n        if (result < a[i])\n            result = a[i];\n    }\n    return result;\n}\n\nint tool_max_i(int *a, int len)\n{\n    int result = a[0];\n    for (int i = 1; i < len; i++)\n    {\n        if (result < a[i])\n            result = a[i];\n    }\n    return result;\n}\n\ndouble tool_min(double *a, int len)\n{\n    double result = a[0];\n    for (int i = 1; i < len; i++)\n    {\n        if (result > a[i])\n            result = a[i];\n    }\n    return result;\n}\n\nint tool_min_i(int *a, int len)\n{\n    int result = a[0];\n    for (int i = 1; i < len; i++)\n    {\n        if (result > a[i])\n            result = a[i];\n    }\n    return result;\n}\n\ndouble tool_max_ix(double *a, int len, int *id)\n{\n    double result = a[0];\n    (*id) = 0;\n    for (int i = 1; i < len; i++)\n    {\n        if (result < a[i])\n        {\n            result = a[i];\n            (*id) = i;\n        }\n    }\n    return result;\n}\n\ndouble tool_min_ix(double *a, int len, int *id)\n{\n    double result = a[0];\n    (*id) = 0;\n    for (int i = 1; i < len; i++)\n    {\n        if (result > a[i])\n        {\n            result = a[i];\n            (*id) = i;\n        }\n    }\n    return result;\n}\n\ndouble tool_1d_sum(double *a, int len)\n{\n    double result = 0;\n    for (int i = 0; i < len; i++)\n    {\n        result += a[i];\n    }\n    return result;\n}\n\nbool tool_compar_b(bool *a, bool *b, int len)\n{\n    for (int i = 0; i < len; i++)\n    {\n        if (a[i] != b[i])\n            return false;\n    }\n    return true;\n}\n\nbool tool_compar_d(double *a, double *b, int len)\n{\n    for (int i = 0; i < len; i++)\n    {\n        if (a[i] != b[i])\n            return false;\n    }\n    return true;\n}\n", "meta": {"hexsha": "ffb248a34bd9cc57a97590161145bb468f978d19", "size": 12406, "ext": "c", "lang": "C", "max_stars_repo_path": "tools.c", "max_stars_repo_name": "houp/identify", "max_stars_repo_head_hexsha": "5ae521201fa3d22306079694f3d9484d17be68e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tools.c", "max_issues_repo_name": "houp/identify", "max_issues_repo_head_hexsha": "5ae521201fa3d22306079694f3d9484d17be68e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tools.c", "max_forks_repo_name": "houp/identify", "max_forks_repo_head_hexsha": "5ae521201fa3d22306079694f3d9484d17be68e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.5987361769, "max_line_length": 80, "alphanum_fraction": 0.5024987909, "num_tokens": 3982, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32423541204073586, "lm_q2_score": 0.03461883834117344, "lm_q1q2_score": 0.011224653313921995}}
{"text": "#include <stdio.h>\n#include <cblas.h>\n#include <sys/time.h>\n#include <stdlib.h>\n#include <omp.h>\n\n\n#define NUM 64\n\n#define GEMM_K 320\n#define GEMM_N 4096\n#define GEMM_M 256\n\nvoid PACKA(float* A, float* Ac, long M, long K, long LK)\n{\n\tlong ii, jj, kk;\n\tfor( ii = 0 ; ii < M; ii = ii + 8)\n\t{\n\n\n\t\tfloat *temp = A + ii * LK + kk;\n\n\t\tasm volatile(\n\t\t\t\t\"\tldr\t\tx0, %[Ac]\t\t\t\t\t\t\t\\n\"\n\t\t\t\t\"\tldr\t\tx1, %[K]\t\t\t\t\t\t\t\\n\"\n\t\t\t\t\"\tldr\t\tx2, %[temp]\t\t\t\t\t\t\\n\"\n\t\t\t\t\"\tldr\t\tx30, %[LK]\t\t\t\t\t\t\\n\"\n\n\t\t\t\t\"\tadd\t\tx3, x2, x30, lsl #2\t\t\\n\"\n\t\t\t\t\"\tadd\t\tx4, x2, x30, lsl #3\t\t\\n\"\n\t\t\t\t\"\tadd\t\tx5, x3, x30, lsl #3\t\t\\n\"\n\t\t\t\t\"\tadd\t\tx6, x4, x30, lsl #3\t\t\\n\"\n\t\t\t\t\"\tadd\t\tx7, x5, x30, lsl #3\t\t\\n\"\n\t\t\t\t\"\tadd\t\tx8, x6, x30, lsl #3\t\t\\n\"\n\t\t\t\t\"\tadd\t\tx9, x7, x30, lsl #3\t\t\\n\"\n\n\n\n\t\t\t\t\"\tlsr\t\tx21, x1, #3\t\t\t\t\t\t\\n\"\n\t\t\t\t\"\tcmp\t\tx21, #0\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\t\"\tbeq\t\tPACKA_END\t\t\t\t\t\t\t\\n\"\n\n\t\t\t\t\"PACKA:\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\n\t\t\t\t\"\tprfm\tPLDL1KEEP, [x2, #128]\t\\n\"\n\t\t\t\t\"\tprfm\tPLDL1KEEP, [x3, #128]\t\\n\"\n\n\t\t\t\t\"\tldr\t\tq0, [x2], #16\t\t\t\t\t\\n\"\n\t\t\t\t\"\tldr\t\tq1, [x3], #16\t\t\t\t\t\\n\"\n\t\t\t\t\"\tldr\t\tq2, [x4], #16\t\t\t\t\t\\n\"\n\t\t\t\t\"\tldr\t\tq3, [x5], #16\t\t\t\t\t\\n\"\n\n\t\t\t\t\"\tprfm\tPLDL1KEEP, [x4, #128]\t\\n\"\n\t\t\t\t\"\tprfm\tPLDL1KEEP, [x5, #128]\t\\n\"\n\n\t\t\t\t\"\tst4\t\t{v0.s, v1.s, v2.s, v3.s}[0], [x0], #16\t\\n\"\n\n\t\t\t\t\"\tldr\t\tq4, [x6], #16\t\t\t\t\t\\n\"\n\t\t\t\t\"\tldr\t\tq5, [x7], #16\t\t\t\t\t\\n\"\n\t\t\t\t\"\tldr\t\tq6, [x8], #16\t\t\t\t\t\\n\"\n\t\t\t\t\"\tldr\t\tq7, [x9], #16\t\t\t\t\t\\n\"\n\n\t\t\t\t\"\tst4\t\t{v4.s, v5.s, v6.s, v7.s}[0], [x0], #16\t\\n\"\n\n\t\t\t\t\"\tprfm\tPLDL1KEEP, [x6, #128]\t\\n\"\n\t\t\t\t\"\tprfm\tPLDL1KEEP, [x7, #128]\t\\n\"\n\n\t\t\t\t\"\tldr\t\tq8, [x2], #16\t\t\t\t\t\\n\"\n\t\t\t\t\"\tst4\t\t{v0.s, v1.s, v2.s, v3.s}[1], [x0], #16\t\\n\"\n\t\t\t\t\"\tldr\t\tq9, [x3], #16\t\t\t\t\t\\n\"\n\t\t\t\t\"\tst4\t\t{v4.s, v5.s, v6.s, v7.s}[1], [x0], #16\t\\n\"\n\t\t\t\t\"\tldr\t\tq10, [x4], #16\t\t\t\t\\n\"\n\t\t\t\t\"\tst4\t\t{v0.s, v1.s, v2.s, v3.s}[2], [x0], #16\t\\n\"\n\t\t\t\t\"\tldr\t\tq11, [x5], #16\t\t\t\t\\n\"\n\t\t\t\t\"\tst4\t\t{v4.s, v5.s, v6.s, v7.s}[2], [x0], #16\t\\n\"\n\n\t\t\t\t\"\tprfm\tPLDL1KEEP, [x8, #128]\t\\n\"\n\t\t\t\t\"\tprfm\tPLDL1KEEP, [x9, #128]\t\\n\"\n\n\n\t\t\t\t\"\tldr\t\tq12, [x6], #16\t\t\t\t\\n\"\n\t\t\t\t\"\tst4\t\t{v0.s, v1.s, v2.s, v3.s}[3], [x0], #16\t\t\\n\"\n\t\t\t\t\"\tldr\t\tq13, [x7], #16\t\t\t\t\\n\"\n\t\t\t\t\"\tst4\t\t{v4.s, v5.s, v6.s, v7.s}[3], [x0], #16\t\t\\n\"\n\t\t\t\t\"\tldr\t\tq14, [x8], #16\t\t\t\t\\n\"\n\t\t\t\t\"\tst4\t\t{v8.s, v9.s, v10.s, v11.s}[0], [x0], #16\t\\n\"\n\t\t\t\t\"\tldr\t\tq15, [x9], #16\t\t\t\t\\n\"\n\t\t\t\t\"\tst4\t\t{v12.s, v13.s, v14.s, v15.s}[0], [x0], #16\t\\n\"\n\n\t\t\t\t\"\tsubs\tx21, x21, #1\t\t\t\t\t\\n\"\n\n\t\t\t\t\"\tst4\t\t{v8.s, v9.s, v10.s, v11.s}[1], [x0], #16\t\\n\"\n\t\t\t\t\"\tst4\t\t{v12.s, v13.s, v14.s, v15.s}[1], [x0], #16\t\\n\"\n\t\t\t\t\"\tst4\t\t{v8.s, v9.s, v10.s, v11.s}[2], [x0], #16\t\\n\"\n\t\t\t\t\"\tst4\t\t{v12.s, v13.s, v14.s, v15.s}[2], [x0], #16\t\\n\"\n\t\t\t\t\"\tst4\t\t{v8.s, v9.s, v10.s, v11.s}[3], [x0], #16\t\\n\"\n\t\t\t\t\"\tst4\t\t{v12.s, v13.s, v14.s, v15.s}[3], [x0], #16\t\\n\"\n\n\t\t\t\t\"\tbgt\t\tPACKA \t\t\t\t\t\t\\n\"\n\n\t\t\t\t\"\tands\tx22, x1, #7\t\t\t\t\\n\"\n\t\t\t\t\"\tbeq\t\tPACKA_END\t\t\t\t\t\\n\"\n\n\t\t\t\t\"\tcmp\t\tx22, #4\t\t\t\t\t\t\\n\"\n\t\t\t\t\"\tblt \tK1_PACKA\t\t\t\t\t\\n\"\n\n\n\t\t\t\t\"K4_PACKA:\t\t\t\t\t\t\t\t\\n\"\n\n\t\t\t\t\"\tldr\t\tq0, [x2], #16\t\t\t\\n\"\n\t\t\t\t\"\tldr\t\tq1, [x3], #16\t\t\t\\n\"\n\t\t\t\t\"\tldr\t\tq2, [x4], #16\t\t\t\\n\"\n\t\t\t\t\"\tldr\t\tq3, [x5], #16\t\t\t\\n\"\n\n\t\t\t\t\"\tst4\t\t{v0.s, v1.s, v2.s, v3.s}[0], [x0], #16\t\\n\"\n\t\t\t\t\"\tldr\t\tq4, [x6], #16\t\t\t\\n\"\n\t\t\t\t\"\tst4\t\t{v0.s, v1.s, v2.s, v3.s}[1], [x0], #16\t\\n\"\n\t\t\t\t\"\tldr\t\tq5, [x7], #16\t\t\t\\n\"\n\t\t\t\t\"\tst4\t\t{v0.s, v1.s, v2.s, v3.s}[2], [x0], #16\t\\n\"\n\t\t\t\t\"\tldr\t\tq6, [x8], #16\t\t\t\\n\"\n\t\t\t\t\"\tst4\t\t{v0.s, v1.s, v2.s, v3.s}[3], [x0], #16\t\\n\"\n\t\t\t\t\"\tldr\t\tq7, [x9], #16\t\t\t\\n\"\n\n\t\t\t\t\"\tst4\t\t{v4.s, v5.s, v6.s, v7.s}[0], [x0], #16\t\\n\"\n\t\t\t\t\"\tst4\t\t{v4.s, v5.s, v6.s, v7.s}[1], [x0], #16\t\\n\"\n\t\t\t\t\"\tst4\t\t{v4.s, v5.s, v6.s, v7.s}[2], [x0], #16\t\\n\"\n\t\t\t\t\"\tst4\t\t{v4.s, v5.s, v6.s, v7.s}[3], [x0], #16\t\\n\"\n\n\t\t\t\t\"\tsubs\tx22, x22, #4\t\t\t\\n\"\n\t\t\t\t\"\tbeq\t\tPACKA_END\t\t\t\t\t\\n\"\n\n\t\t\t\t\"K1_PACKA:\t\t\t\t\t\t\t\t\\n\"\n\n\t\t\t\t\"\tldr\t\ts0, [x2], #4\t\t\t\\n\"\n\t\t\t\t\"\tldr\t\ts1, [x3], #4\t\t\t\\n\"\n\t\t\t\t\"\tldr\t\ts2, [x4], #4\t\t\t\\n\"\n\t\t\t\t\"\tldr\t\ts3, [x5], #4\t\t\t\\n\"\n\n\t\t\t\t\"\tsubs \tx22, x22, #1\t\t\t\\n\"\n\n\t\t\t\t\"\tst4\t\t{v0.s, v1.s, v2.s, v3.s}[0], [x0], #16\t\\n\"\n\t\t\t\t\"\tldr\t\ts4, [x6], #4\t\t\t\\n\"\n\t\t\t\t\"\tldr\t\ts5, [x7], #4\t\t\t\\n\"\n\t\t\t\t\"\tldr\t\ts6, [x8], #4\t\t\t\\n\"\n\t\t\t\t\"\tldr\t\ts7, [x9], #4\t\t\t\\n\"\n\n\t\t\t\t\"\tst4\t\t{v4.s, v5.s, v6.s, v7.s}[0], [x0], #16\t\\n\"\n\n\t\t\t\t\"\tbgt\t\tK1_PACKA\t\t\t\t\\n\"\n\n\n\n\t\t\t\t\"PACKA_END:\t\t\t\t\t\t\t\\n\"\n\n\t\t\t\t:\n\t\t\t\t:\n\t\t\t\t[temp] \"m\" (temp),\n\t\t\t\t[Ac] \"m\" (Ac),\n\t\t\t\t[K] \"m\" (K),\n\t\t\t\t[LK] \"m\" (LK)\n\t\t\t\t:\"x0\", \"x1\", \"x2\", \"x3\", \"x4\", \"x5\", \"x6\", \"x7\", \"x8\",\n\t\t\t\t\"x9\", \"x10\", \"x11\", \"x12\", \"x13\",\"x14\", \"x15\", \"x16\",\n\t\t\t\t\"x17\", \"x18\", \"x19\", \"x20\", \"x21\", \"x22\", \"x23\", \"x24\",\"x25\",\n\t\t\t\t\"x26\", \"x27\", \"x28\", \"x29\", \"x30\",\n\t\t\t\t\"v0\", \"v1\", \"v2\", \"v3\", \"v4\", \"v5\", \"v6\", \"v7\",\n\t\t\t\t\"v8\", \"v9\", \"v10\", \"v11\", \"v12\", \"v13\", \"v14\", \"v15\",\n\t\t\t\t\"v16\", \"v17\", \"v18\", \"v19\", \"v20\", \"v21\", \"v22\", \"v23\",\n\t\t\t\t\"v24\", \"v25\", \"v26\", \"v27\", \"v28\", \"v29\", \"v30\", \"v31\"\n\n\t\t);\n\n\t\tAc = Ac + K * 8;\n\n\t}\n\n}\n\n\nvoid Sin_PACK(float* A, float* Ac, long M, long K, long LK)\n{\n\tlong ii, jj, kk;\n\tlong Kc;\n\n\n\tfor( kk =0 ; kk < K; kk = kk + Kc)\n\t{\n\t\t\n\t\tKc = GEMM_K;\n\t\tif(K - kk < GEMM_K)\n\t\t\tKc= K - kk;\n\n\t\tfor( ii = 0 ; ii < M; ii = ii + 8)\n\t\t{\n\n\n\t\t\tfloat *temp = A + ii * LK + kk;\n\n\t\t\tasm volatile(\n\t\t\t\t\t\"\tldr\t\tx0, %[Ac]\t\t\t\t\t\t\t\\n\"\n\t\t\t\t\t\"\tldr\t\tx1, %[Kc]\t\t\t\t\t\t\t\\n\"\n\t\t\t\t\t\"\tldr\t\tx2, %[temp]\t\t\t\t\t\t\\n\"\n\t\t\t\t\t\"\tldr\t\tx30, %[LK]\t\t\t\t\t\t\\n\"\n\n\t\t\t\t\t\"\tadd\t\tx3, x2, x30, lsl #2\t\t\\n\"\n\t\t\t\t\t\"\tadd\t\tx4, x2, x30, lsl #3\t\t\\n\"\n\t\t\t\t\t\"\tadd\t\tx5, x3, x30, lsl #3\t\t\\n\"\n\t\t\t\t\t\"\tadd\t\tx6, x4, x30, lsl #3\t\t\\n\"\n\t\t\t\t\t\"\tadd\t\tx7, x5, x30, lsl #3\t\t\\n\"\n\t\t\t\t\t\"\tadd\t\tx8, x6, x30, lsl #3\t\t\\n\"\n\t\t\t\t\t\"\tadd\t\tx9, x7, x30, lsl #3\t\t\\n\"\n\n\n\n\t\t\t\t\t\"\tlsr\t\tx21, x1, #3\t\t\t\t\t\t\\n\"\n\t\t\t\t\t\"\tcmp\t\tx21, #0\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\t\t\"\tbeq\t\tSin_PACKA_END\t\t\t\t\t\\n\"\n\n\t\t\t\t\t\"Sin_PACKA:\t\t\t\t\t\t\t\t\t\t\\n\"\n\n\t\t\t\t\t\"\tprfm\tPLDL1KEEP, [x2, #128]\t\\n\"\n\t\t\t\t\t\"\tprfm\tPLDL1KEEP, [x3, #128]\t\\n\"\n\n\t\t\t\t\t\"\tldr\t\tq0, [x2], #16\t\t\t\t\t\\n\"\n\t\t\t\t\t\"\tldr\t\tq1, [x3], #16\t\t\t\t\t\\n\"\n\t\t\t\t\t\"\tldr\t\tq2, [x4], #16\t\t\t\t\t\\n\"\n\t\t\t\t\t\"\tldr\t\tq3, [x5], #16\t\t\t\t\t\\n\"\n\n\t\t\t\t\t\"\tprfm\tPLDL1KEEP, [x4, #128]\t\\n\"\n\t\t\t\t\t\"\tprfm\tPLDL1KEEP, [x5, #128]\t\\n\"\n\n\t\t\t\t\t\"\tst4\t\t{v0.s, v1.s, v2.s, v3.s}[0], [x0], #16\t\\n\"\n\n\t\t\t\t\t\"\tldr\t\tq4, [x6], #16\t\t\t\t\t\\n\"\n\t\t\t\t\t\"\tldr\t\tq5, [x7], #16\t\t\t\t\t\\n\"\n\t\t\t\t\t\"\tldr\t\tq6, [x8], #16\t\t\t\t\t\\n\"\n\t\t\t\t\t\"\tldr\t\tq7, [x9], #16\t\t\t\t\t\\n\"\n\n\t\t\t\t\t\"\tst4\t\t{v4.s, v5.s, v6.s, v7.s}[0], [x0], #16\t\\n\"\n\n\t\t\t\t\t\"\tprfm\tPLDL1KEEP, [x6, #128]\t\\n\"\n\t\t\t\t\t\"\tprfm\tPLDL1KEEP, [x7, #128]\t\\n\"\n\n\t\t\t\t\t\"\tldr\t\tq8, [x2], #16\t\t\t\t\t\\n\"\n\t\t\t\t\t\"\tst4\t\t{v0.s, v1.s, v2.s, v3.s}[1], [x0], #16\t\\n\"\n\t\t\t\t\t\"\tldr\t\tq9, [x3], #16\t\t\t\t\t\\n\"\n\t\t\t\t\t\"\tst4\t\t{v4.s, v5.s, v6.s, v7.s}[1], [x0], #16\t\\n\"\n\t\t\t\t\t\"\tldr\t\tq10, [x4], #16\t\t\t\t\\n\"\n\t\t\t\t\t\"\tst4\t\t{v0.s, v1.s, v2.s, v3.s}[2], [x0], #16\t\\n\"\n\t\t\t\t\t\"\tldr\t\tq11, [x5], #16\t\t\t\t\\n\"\n\t\t\t\t\t\"\tst4\t\t{v4.s, v5.s, v6.s, v7.s}[2], [x0], #16\t\\n\"\n\n\t\t\t\t\t\"\tprfm\tPLDL1KEEP, [x8, #128]\t\\n\"\n\t\t\t\t\t\"\tprfm\tPLDL1KEEP, [x9, #128]\t\\n\"\n\n\n\t\t\t\t\t\"\tldr\t\tq12, [x6], #16\t\t\t\t\\n\"\n\t\t\t\t\t\"\tst4\t\t{v0.s, v1.s, v2.s, v3.s}[3], [x0], #16\t\t\\n\"\n\t\t\t\t\t\"\tldr\t\tq13, [x7], #16\t\t\t\t\\n\"\n\t\t\t\t\t\"\tst4\t\t{v4.s, v5.s, v6.s, v7.s}[3], [x0], #16\t\t\\n\"\n\t\t\t\t\t\"\tldr\t\tq14, [x8], #16\t\t\t\t\\n\"\n\t\t\t\t\t\"\tst4\t\t{v8.s, v9.s, v10.s, v11.s}[0], [x0], #16\t\\n\"\n\t\t\t\t\t\"\tldr\t\tq15, [x9], #16\t\t\t\t\\n\"\n\t\t\t\t\t\"\tst4\t\t{v12.s, v13.s, v14.s, v15.s}[0], [x0], #16\t\\n\"\n\n\t\t\t\t\t\"\tsubs\tx21, x21, #1\t\t\t\t\t\\n\"\n\n\t\t\t\t\t\"\tst4\t\t{v8.s, v9.s, v10.s, v11.s}[1], [x0], #16\t\\n\"\n\t\t\t\t\t\"\tst4\t\t{v12.s, v13.s, v14.s, v15.s}[1], [x0], #16\t\\n\"\n\t\t\t\t\t\"\tst4\t\t{v8.s, v9.s, v10.s, v11.s}[2], [x0], #16\t\\n\"\n\t\t\t\t\t\"\tst4\t\t{v12.s, v13.s, v14.s, v15.s}[2], [x0], #16\t\\n\"\n\t\t\t\t\t\"\tst4\t\t{v8.s, v9.s, v10.s, v11.s}[3], [x0], #16\t\\n\"\n\t\t\t\t\t\"\tst4\t\t{v12.s, v13.s, v14.s, v15.s}[3], [x0], #16\t\\n\"\n\n\t\t\t\t\t\"\tbgt\t\tSin_PACKA \t\t\t\t\\n\"\n\n\t\t\t\t\t\"\tands\tx22, x1, #7\t\t\t\t\\n\"\n\t\t\t\t\t\"\tbeq\t\tSin_PACKA_END\t\t\t\\n\"\n\n\t\t\t\t\t\"\tcmp\t\tx22, #4\t\t\t\t\t\t\\n\"\n\t\t\t\t\t\"\tblt \tSin_K1_PACKA\t\t\t\\n\"\n\n\n\t\t\t\t\t\"Sin_K4_PACKA:\t\t\t\t\t\t\\n\"\n\n\t\t\t\t\t\"\tldr\t\tq0, [x2], #16\t\t\t\\n\"\n\t\t\t\t\t\"\tldr\t\tq1, [x3], #16\t\t\t\\n\"\n\t\t\t\t\t\"\tldr\t\tq2, [x4], #16\t\t\t\\n\"\n\t\t\t\t\t\"\tldr\t\tq3, [x5], #16\t\t\t\\n\"\n\n\t\t\t\t\t\"\tst4\t\t{v0.s, v1.s, v2.s, v3.s}[0], [x0], #16\t\\n\"\n\t\t\t\t\t\"\tldr\t\tq4, [x6], #16\t\t\t\\n\"\n\t\t\t\t\t\"\tst4\t\t{v0.s, v1.s, v2.s, v3.s}[1], [x0], #16\t\\n\"\n\t\t\t\t\t\"\tldr\t\tq5, [x7], #16\t\t\t\\n\"\n\t\t\t\t\t\"\tst4\t\t{v0.s, v1.s, v2.s, v3.s}[2], [x0], #16\t\\n\"\n\t\t\t\t\t\"\tldr\t\tq6, [x8], #16\t\t\t\\n\"\n\t\t\t\t\t\"\tst4\t\t{v0.s, v1.s, v2.s, v3.s}[3], [x0], #16\t\\n\"\n\t\t\t\t\t\"\tldr\t\tq7, [x9], #16\t\t\t\\n\"\n\n\t\t\t\t\t\"\tst4\t\t{v4.s, v5.s, v6.s, v7.s}[0], [x0], #16\t\\n\"\n\t\t\t\t\t\"\tst4\t\t{v4.s, v5.s, v6.s, v7.s}[1], [x0], #16\t\\n\"\n\t\t\t\t\t\"\tst4\t\t{v4.s, v5.s, v6.s, v7.s}[2], [x0], #16\t\\n\"\n\t\t\t\t\t\"\tst4\t\t{v4.s, v5.s, v6.s, v7.s}[3], [x0], #16\t\\n\"\n\n\t\t\t\t\t\"\tsubs\tx22, x22, #4\t\t\t\\n\"\n\t\t\t\t\t\"\tbeq\t\tSin_PACKA_END\t\t\t\\n\"\n\n\t\t\t\t\t\"Sin_K1_PACKA:\t\t\t\t\t\t\\n\"\n\n\t\t\t\t\t\"\tldr\t\ts0, [x2], #4\t\t\t\\n\"\n\t\t\t\t\t\"\tldr\t\ts1, [x3], #4\t\t\t\\n\"\n\t\t\t\t\t\"\tldr\t\ts2, [x4], #4\t\t\t\\n\"\n\t\t\t\t\t\"\tldr\t\ts3, [x5], #4\t\t\t\\n\"\n\n\t\t\t\t\t\"\tsubs \tx22, x22, #1\t\t\t\\n\"\n\n\t\t\t\t\t\"\tst4\t\t{v0.s, v1.s, v2.s, v3.s}[0], [x0], #16\t\\n\"\n\t\t\t\t\t\"\tldr\t\ts4, [x6], #4\t\t\t\\n\"\n\t\t\t\t\t\"\tldr\t\ts5, [x7], #4\t\t\t\\n\"\n\t\t\t\t\t\"\tldr\t\ts6, [x8], #4\t\t\t\\n\"\n\t\t\t\t\t\"\tldr\t\ts7, [x9], #4\t\t\t\\n\"\n\n\t\t\t\t\t\"\tst4\t\t{v4.s, v5.s, v6.s, v7.s}[0], [x0], #16\t\\n\"\n\n\t\t\t\t\t\"\tbgt\t\tSin_K1_PACKA\t\t\t\\n\"\n\n\n\n\t\t\t\t\t\"Sin_PACKA_END:\t\t\t\t\t\t\\n\"\n\n\t\t\t\t\t:\n\t        :\n\t      \t\t[temp] \"m\" (temp),\n\t      \t\t[Ac] \"m\" (Ac),\n\t      \t\t[Kc] \"m\" (Kc),\n\t      \t\t[LK] \"m\" (LK)\n\t        :\"x0\", \"x1\", \"x2\", \"x3\", \"x4\", \"x5\", \"x6\", \"x7\", \"x8\",\n\t        \"x9\", \"x10\", \"x11\", \"x12\", \"x13\",\"x14\", \"x15\", \"x16\",\n\t        \"x17\", \"x18\", \"x19\", \"x20\", \"x21\", \"x22\", \"x23\", \"x24\",\"x25\",\n\t        \"x26\", \"x27\", \"x28\", \"x29\", \"x30\",\n\t        \"v0\", \"v1\", \"v2\", \"v3\", \"v4\", \"v5\", \"v6\", \"v7\",\n\t        \"v8\", \"v9\", \"v10\", \"v11\", \"v12\", \"v13\", \"v14\", \"v15\",\n\t        \"v16\", \"v17\", \"v18\", \"v19\", \"v20\", \"v21\", \"v22\", \"v23\",\n\t        \"v24\", \"v25\", \"v26\", \"v27\", \"v28\", \"v29\", \"v30\", \"v31\"\n\n\t\t\t);\n\n\t\t\tAc = Ac + Kc * 8;\n\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "a67e3da7875dca2341a19abf0efcc6f862fe714e", "size": 9253, "ext": "h", "lang": "C", "max_stars_repo_path": "NN_LIB/PACK.h", "max_stars_repo_name": "AnonymousYWL/MYLIB", "max_stars_repo_head_hexsha": "2497123bf3bfd12f215b428ae83afd223cd072fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2021-06-04T14:39:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T10:45:29.000Z", "max_issues_repo_path": "NN_LIB/PACK.h", "max_issues_repo_name": "ProgrammerAnonymousWLY/MYLIB", "max_issues_repo_head_hexsha": "2497123bf3bfd12f215b428ae83afd223cd072fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-06-23T17:16:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-23T17:16:12.000Z", "max_forks_repo_path": "NN_LIB/PACK.h", "max_forks_repo_name": "ProgrammerAnonymousWLY/MYLIB", "max_forks_repo_head_hexsha": "2497123bf3bfd12f215b428ae83afd223cd072fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-06-04T14:40:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-07T07:51:15.000Z", "avg_line_length": 26.2869318182, "max_line_length": 70, "alphanum_fraction": 0.37857992, "num_tokens": 5224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833804028559, "lm_q2_score": 0.02297737070451605, "lm_q1q2_score": 0.011219468240370647}}
{"text": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n#pragma once\n\n#include \"Data\\Types.h\"\n#include \"MageSettings.h\"\n#include \"Image\\ORBDescriptor.h\"\n#include \"BaseFeatureMatcher.h\"\n\n#include <vector>\n#include <gsl\\gsl>\n#include <memory>\n  \nnamespace mage\n{\n    class Keyframe;\n    class AnalyzedImage;\n\n    class BaseBow\n    {\n    public:\n        struct QueryMatch\n        {\n            Id<Keyframe> Id;\n            float Score;\n\n            operator mage::Id<Keyframe>() const\n            {\n                return Id;\n            }\n        };\n\n        BaseBow(const BagOfWordsSettings& settings)\n            :m_settings{ settings }\n        {}\n\n        virtual ~BaseBow() {}\n\n        virtual void AddTrainingDescriptors(gsl::span<const ORBDescriptor>) {}\n\n        virtual void AddImage(const Id<Keyframe>, const AnalyzedImage& image) = 0;\n\n        virtual void RemoveImage(const Id<Keyframe>) = 0;\n\n        virtual size_t QueryFeatures(const ORBDescriptor& descriptor, const Id<Keyframe>& keyframe, std::vector<ptrdiff_t>& features) const = 0;\n\n        virtual std::unique_ptr<BaseFeatureMatcher> CreateFeatureMatcher(const Id<Keyframe>& id, gsl::span<const ORBDescriptor> features) const = 0;\n        \n        virtual std::unique_ptr<BaseBow> CreateTemporaryBow() const = 0;\n\n        virtual std::vector<QueryMatch> QueryUnknownImage(gsl::span<const ORBDescriptor> descriptors, size_t maxResults) const = 0;\n\n        virtual void Clear() = 0;\n\n        virtual bool IsTrainingDone() const { return true;}\n\n    protected:\n        const BagOfWordsSettings& m_settings;\n    };\n}\n", "meta": {"hexsha": "ad69898818294baf95bb5cefba9a22a34192770e", "size": 1600, "ext": "h", "lang": "C", "max_stars_repo_path": "Core/MAGESLAM/Source/BoW/BaseBow.h", "max_stars_repo_name": "syntheticmagus/mageslam", "max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z", "max_issues_repo_path": "Core/MAGESLAM/Source/BoW/BaseBow.h", "max_issues_repo_name": "syntheticmagus/mageslam", "max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z", "max_forks_repo_path": "Core/MAGESLAM/Source/BoW/BaseBow.h", "max_forks_repo_name": "syntheticmagus/mageslam", "max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z", "avg_line_length": 25.8064516129, "max_line_length": 148, "alphanum_fraction": 0.641875, "num_tokens": 363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936413143782797, "lm_q2_score": 0.031143833344941297, "lm_q1q2_score": 0.011191976619649293}}
{"text": "#ifndef __GSL_PERMUTE_MATRIX_H__\n#define __GSL_PERMUTE_MATRIX_H__\n\n#include <gsl/gsl_permute_matrix_complex_long_double.h>\n#include <gsl/gsl_permute_matrix_complex_double.h>\n#include <gsl/gsl_permute_matrix_complex_float.h>\n\n#include <gsl/gsl_permute_matrix_long_double.h>\n#include <gsl/gsl_permute_matrix_double.h>\n#include <gsl/gsl_permute_matrix_float.h>\n\n#include <gsl/gsl_permute_matrix_ulong.h>\n#include <gsl/gsl_permute_matrix_long.h>\n\n#include <gsl/gsl_permute_matrix_uint.h>\n#include <gsl/gsl_permute_matrix_int.h>\n\n#include <gsl/gsl_permute_matrix_ushort.h>\n#include <gsl/gsl_permute_matrix_short.h>\n\n#include <gsl/gsl_permute_matrix_uchar.h>\n#include <gsl/gsl_permute_matrix_char.h>\n\n#endif /* __GSL_PERMUTE_MATRIX_H__ */\n", "meta": {"hexsha": "aa8e67211e3a6c7a29b7dff93e5b509ee133df8b", "size": 733, "ext": "h", "lang": "C", "max_stars_repo_path": "315/gsltest/gsl/include/gsl/gsl_permute_matrix.h", "max_stars_repo_name": "shi-bash-cmd/qtTest", "max_stars_repo_head_hexsha": "3eb0cf4b8fcfa2c36e133e4df2b2a3e6d2d3e589", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-12-18T16:35:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-14T07:38:05.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/permutation/gsl_permute_matrix.h", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/permutation/gsl_permute_matrix.h", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-12-20T16:50:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-13T05:31:07.000Z", "avg_line_length": 29.32, "max_line_length": 55, "alphanum_fraction": 0.8362892224, "num_tokens": 207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3923368301671084, "lm_q2_score": 0.02843603602953799, "lm_q1q2_score": 0.011156504238346623}}
{"text": "#ifndef __GSL_SORT_VECTOR_H__\n#define __GSL_SORT_VECTOR_H__\n\n#include <gsl/gsl_sort_vector_long_double.h>\n#include <gsl/gsl_sort_vector_double.h>\n#include <gsl/gsl_sort_vector_float.h>\n\n#include <gsl/gsl_sort_vector_ulong.h>\n#include <gsl/gsl_sort_vector_long.h>\n\n#include <gsl/gsl_sort_vector_uint.h>\n#include <gsl/gsl_sort_vector_int.h>\n\n#include <gsl/gsl_sort_vector_ushort.h>\n#include <gsl/gsl_sort_vector_short.h>\n\n#include <gsl/gsl_sort_vector_uchar.h>\n#include <gsl/gsl_sort_vector_char.h>\n\n#endif /* __GSL_SORT_VECTOR_H__ */\n", "meta": {"hexsha": "d65a9ee9bb97679e47bd3ebd5f85f187f240d593", "size": 533, "ext": "h", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/sort/gsl_sort_vector.h", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 77.0, "max_stars_repo_stars_event_min_datetime": "2015-01-18T00:45:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-24T22:20:56.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/sort/gsl_sort_vector.h", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/sort/gsl_sort_vector.h", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 25.380952381, "max_line_length": 44, "alphanum_fraction": 0.8161350844, "num_tokens": 150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.28140560742914383, "lm_q2_score": 0.03963884051909871, "lm_q1q2_score": 0.011154591994063932}}
{"text": "#pragma once\n#include <gsl/span>\n#include \"halley/core/api/audio_api.h\"\n#include \"audio_buffer.h\"\n\n#if defined(_M_X64) || defined(__x86_64__)\n#define HAS_SSE\n#if !defined(__linux__)\n#define HAS_AVX\n#endif\n#endif\n\n#if defined(_M_IX86) || defined(__i386)\n// Might not be available, but do we really care about such old processors?\n#define HAS_SSE\n#endif\n\nnamespace Halley\n{\n\tclass AudioMixer\n\t{\n\tpublic:\n\t\tvirtual ~AudioMixer() {}\n\n\t\tvirtual void mixAudio(gsl::span<const AudioSamplePack> src, gsl::span<AudioSamplePack> dst, float gainStart, float gainEnd);\n\t\tvirtual void interleaveChannels(gsl::span<AudioSamplePack> dst, gsl::span<AudioBuffer*> src);\n\t\tvirtual void compressRange(gsl::span<AudioSamplePack> buffer);\n\t\tstatic std::unique_ptr<AudioMixer> makeMixer();\n\t};\n}\n", "meta": {"hexsha": "2610a6677c681ac4e58f30f7a57a18fa0dd8c600", "size": 774, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engine/audio/src/audio_mixer.h", "max_stars_repo_name": "lye/halley", "max_stars_repo_head_hexsha": "16b6c9783e4b21377f902a9d02366c1f19450a21", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T20:23:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T20:23:45.000Z", "max_issues_repo_path": "src/engine/audio/src/audio_mixer.h", "max_issues_repo_name": "lye/halley", "max_issues_repo_head_hexsha": "16b6c9783e4b21377f902a9d02366c1f19450a21", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engine/audio/src/audio_mixer.h", "max_forks_repo_name": "lye/halley", "max_forks_repo_head_hexsha": "16b6c9783e4b21377f902a9d02366c1f19450a21", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9677419355, "max_line_length": 126, "alphanum_fraction": 0.7532299742, "num_tokens": 208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35220179564702847, "lm_q2_score": 0.03161876578580388, "lm_q1q2_score": 0.011136186085902954}}
{"text": "\ufeff#pragma once\n#include \"Hypo/Graphics/Exports.h\"\n#include \"Hypo/System/DataTypes/ObjPtr.h\"\n#include \"Hypo/Window/Context/GraphicsContext.h\"\n#include <gsl/span>\n\nnamespace Hypo\n{\n\n\n\tenum class TextureType\n\t{\n\t\tNone,\n\t\tRgb,\n\t\tRgba,\n\t\tsRgb,\n\t\tsRgba,\n\t\tStencil,\n\t\tDepth\n\t};\n\n\tHYPO_GRAPHICS_API uInt32 GetTexturePixelSize(TextureType type);\n\tHYPO_GRAPHICS_API uInt32 GetTextureSize(uInt32 width, uInt32 height, TextureType type);\n\n\tclass TextureData\n\t{\n\tpublic:\n\t\tTextureData(uInt32 width, uInt32 height, TextureType type);\n\n\t\tTextureData(uInt32 width, uInt32 height, TextureType type, std::vector<Byte> pixels);\n\n\t\tTextureData() = default;\n\t\tTextureData(const TextureData&) = default;\n\n\t\tuInt32 GetWidth() const { return m_Width; }\n\t\tuInt32 GetHeight() const { return m_Height; }\n\t\tTextureType GetType()const { return m_Type; }\n\t\tuInt32 GetPixelsSize() const { return m_Pixels.size(); }\n\t\tconst std::vector<Byte>& GetPixels() const { return m_Pixels; }\n\tprivate:\n\t\tuInt32 m_Width = 0;\n\t\tuInt32 m_Height = 0;\n\t\tTextureType m_Type = TextureType::None;\n\t\tstd::vector<Byte> m_Pixels;\n\t};\n\n\tHYPO_GRAPHICS_API TextureData TextureFromFile(std::string path);\n}\n\n\n\n\n\n\n", "meta": {"hexsha": "62f9a1c2b44d4e42106240b7f86ec072a10c2241", "size": 1155, "ext": "h", "lang": "C", "max_stars_repo_path": "HypoGraphics/src/Hypo/Graphics/Texture/TextureAsset.h", "max_stars_repo_name": "TheodorLindberg/Hypo", "max_stars_repo_head_hexsha": "67107bf14671711ab5979e2af8c7ead6ee043805", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HypoGraphics/src/Hypo/Graphics/Texture/TextureAsset.h", "max_issues_repo_name": "TheodorLindberg/Hypo", "max_issues_repo_head_hexsha": "67107bf14671711ab5979e2af8c7ead6ee043805", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HypoGraphics/src/Hypo/Graphics/Texture/TextureAsset.h", "max_forks_repo_name": "TheodorLindberg/Hypo", "max_forks_repo_head_hexsha": "67107bf14671711ab5979e2af8c7ead6ee043805", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.0, "max_line_length": 88, "alphanum_fraction": 0.7324675325, "num_tokens": 334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30735801686526387, "lm_q2_score": 0.036220051963683664, "lm_q1q2_score": 0.011132523342314618}}
{"text": "// Import a generic GeoTIFF (a projected GeoTIFF flavor), including\n// projection data from its metadata file (ERDAS MIF HFA .aux file) into\n// our own ASF Tools format (.img, .meta)\n//\n// NOTE:\n// 1. At this time, only supports Albers Equal Area Conic, Lambert Azimuthal\n//    Equal Area, Lambert Conformal Conic, Polar Stereographic, and UTM\n// 2. There may be some data duplication between the GeoTIFF tag contents\n//    in the TIFF file and the data contents of the metadata (.aux) file.\n// 3. Data and parameters found in the metadata (.aux) file supercede the\n//    data and parameter values found in the TIFF file\n//\n\n#include <assert.h>\n#include <ctype.h>\n#include <stdarg.h>\n\n#include \"float_image.h\"\n#include \"asf_tiff.h\"\n\n#include <gsl/gsl_math.h>\n\n#include <uint8_image.h>\n#include <spheroids.h>\n#include <proj.h>\n#include <libasf_proj.h>\n\n#include \"asf.h\"\n#include \"asf_meta.h\"\n#include \"asf_nan.h\"\n#include \"asf_import.h\"\n#include \"asf_raster.h\"\n#include \"asf_tiff.h\"\n#include \"geo_tiffp.h\"\n#include \"geo_keyp.h\"\n\n#include \"projected_image_import.h\"\n#include \"tiff_to_float_image.h\"\n#include \"tiff_to_byte_image.h\"\n#include \"write_meta_and_img.h\"\n#include \"import_generic_geotiff.h\"\n#include \"arcgis_geotiff_support.h\"\n#include \"geotiff_support.h\"\n\n#define BAD_VALUE_SCAN_ON\n\n#define FLOAT_COMPARE_TOLERANCE(a, b, t) (fabs (a - b) <= t ? 1: 0)\n#define IMPORT_GENERIC_FLOAT_MICRON 0.000000001\n#ifdef  FLOAT_EQUIVALENT\n#undef  FLOAT_EQUIVALENT\n#endif\n#define FLOAT_EQUIVALENT(a, b) (FLOAT_COMPARE_TOLERANCE \\\n                                (a, b, IMPORT_GENERIC_FLOAT_MICRON))\n#define FLOAT_TOLERANCE 0.00001\n\n#define DEFAULT_UTM_SCALE_FACTOR     0.9996\n\n#define DEFAULT_SCALE_FACTOR         1.0\n#define UNKNOWN_PROJECTION_TYPE       -1\n\n#define NAD27_DATUM_STR   \"NAD27\"\n#define NAD83_DATUM_STR   \"NAD83\"\n#define HARN_DATUM_STR    \"HARN\"\n#define WGS84_DATUM_STR   \"WGS84\"\n#define HUGHES_DATUM_STR  \"HUGHES\"\n\n#define USER_DEFINED_PCS             32767\n#define USER_DEFINED_KEY             32767\n#define BAND_NAME_LENGTH  12\n\n#define TIFFTAG_GDAL_NODATA          42113\n\n#ifdef USHORT_MAX\n#undef USHORT_MAX\n#endif\n#define USHORT_MAX  65535\n\n#ifdef MAX_RGB\n#undef MAX_RGB\n#endif\n#define MAX_RGB  255\n\n// Do not change the BAND_ID_STRING.  It will break ingest of legacy TIFFs exported with this\n// string in their citation strings.  If you are changing the citation string to have some _other_\n// identifying string, then use a _new_ definition rather than replace what is in this one.\n// Then, make sure that your code supports both the legacy string and the new string.\n// Also see the export library string definitions (which MUST match these here) and\n// for associated code that needs to reflect the changes you are making here.\n#define BAND_ID_STRING \"Color Channel (Band) Contents in RGBA+ order\"\n\nspheroid_type_t SpheroidName2spheroid(char *sphereName);\nvoid check_projection_parameters(meta_projection *mp);\nint  band_float_image_write(FloatImage *oim, meta_parameters *meta_out,\n                            const char *outBaseName, int num_bands, int *ignore);\nint  band_byte_image_write(UInt8Image *oim_b, meta_parameters *meta_out,\n                           const char *outBaseName, int num_bands, int *ignore);\nint check_for_vintage_asf_utm_geotiff(const char *citation, int *geotiff_data_exists,\n                                      short *model_type, short *raster_type, short *linear_units);\nint check_for_datum_in_string(const char *citation, datum_type_t *datum);\nint check_for_ellipse_definition_in_geotiff(GTIF *input_gtif, spheroid_type_t *spheroid);\nint vintage_utm_citation_to_pcs(const char *citation, int *zone, char *hem, datum_type_t *datum, short *pcs);\nstatic int UTM_2_PCS(short *pcs, datum_type_t datum, unsigned long zone, char hem);\nvoid classify_geotiff(GTIF *input_gtif, short *model_type, short *raster_type, short *linear_units, short *angular_units,\n                      int *geographic_geotiff, int *geocentric_geotiff, int *map_projected_geotiff,\n                      int *geotiff_data_exists);\nchar *angular_units_to_string(short angular_units);\nchar *linear_units_to_string(short linear_units);\nvoid get_look_up_table_name(char *citation, char **look_up_table);\n\n// Import an ERDAS ArcGIS GeoTIFF (a projected GeoTIFF flavor), including\n// projection data from its metadata file (ERDAS MIF HFA .aux file) into\n// our own ASF Tools format (.img, .meta)\n//\nvoid import_generic_geotiff (const char *inFileName, const char *outBaseName, ...)\n{\n  TIFF *input_tiff;\n  meta_parameters *meta;\n  data_type_t data_type;\n  int is_scanline_format;\n  int is_palette_color_tiff;\n  short num_bands;\n  short int bits_per_sample, sample_format, planar_config;\n  va_list ap;\n  char image_data_type[256];\n  char *pTmpChar;\n  int ignore[MAX_BANDS]; // Array of band flags ...'1' if a band is to be ignored (empty band)\n                         // Do NOT allocate less than MAX_BANDS bands since other tools will\n                         // receive the 'ignore' array and may assume there are MAX_BANDS in\n                         // the array, e.g. read_tiff_meta() in the asf_view tool.\n\n  // Open the input tiff file.\n  TIFFErrorHandler oldHandler;\n  oldHandler = TIFFSetWarningHandler(NULL);\n  input_tiff = XTIFFOpen (inFileName, \"r\");\n  if (input_tiff == NULL)\n    asfPrintError (\"Error opening input TIFF file:\\n    %s\\n\", inFileName);\n\n  if (get_tiff_data_config(input_tiff,\n                           &sample_format,    // TIFF type (uint == 1, int == 2, float == 3)\n                           &bits_per_sample,  // 8, 16, or 32\n                           &planar_config,    // Contiguous == 1 (RGB or RGBA) or separate == 2 (separate bands)\n                           &data_type,        // ASF datatype, (BYTE, INTEGER16, INTEGER32, or REAL32 ...no complex)\n                           &num_bands,        // Initial number of bands\n                           &is_scanline_format,\n                           &is_palette_color_tiff,\n                           REPORT_LEVEL_WARNING))\n  {\n    // Failed to determine tiff info or tiff info was bad\n    char msg[1024];\n    tiff_type_t t;\n    get_tiff_type(input_tiff, &t);\n    sprintf(msg, \"FOUND TIFF tag data as follows:\\n\"\n        \"         Sample Format: %s\\n\"\n        \"       Bits per Sample: %d\\n\"\n        \"  Planar Configuration: %s\\n\"\n        \"       Number of Bands: %d\\n\"\n        \"                Format: %s\\n\"\n        \"              Colormap: %s\\n\",\n        (sample_format == SAMPLEFORMAT_UINT) ? \"Unsigned Integer\" :\n        (sample_format == SAMPLEFORMAT_INT) ? \"Signed Integer\" :\n        (sample_format == SAMPLEFORMAT_IEEEFP) ? \"Floating Point\" : \"Unknown or Unsupported\",\n        bits_per_sample,\n        (planar_config == PLANARCONFIG_CONTIG) ? \"Contiguous (chunky RGB or RGBA etc) / Interlaced\" :\n          (planar_config == PLANARCONFIG_SEPARATE) ? \"Separate planes (band-sequential)\" :\n            \"Unknown or unrecognized\",\n        num_bands,\n        t.format == SCANLINE_TIFF ? \"SCANLINE TIFF\" :\n        t.format == STRIP_TIFF    ? \"STRIP TIFF\"    :\n        t.format == TILED_TIFF    ? \"TILED TIFF\"    : \"UNKNOWN\",\n        is_palette_color_tiff ? \"PRESENT\" : \"NOT PRESENT\");\n    switch (t.format) {\n      case STRIP_TIFF:\n        sprintf(msg, \"%s\"\n                \"        Rows per Strip: %d\\n\",\n                msg, t.rowsPerStrip);\n        break;\n      case TILED_TIFF:\n        sprintf(msg, \"%s\"\n                \"            Tile Width: %d\\n\"\n                \"           Tile Height: %d\\n\",\n                msg, t.tileWidth, t.tileLength);\n        break;\n      case SCANLINE_TIFF:\n      default:\n        break;\n    }\n    asfPrintWarning(msg);\n\n    XTIFFClose(input_tiff);\n    asfPrintError(\"  Unsupported TIFF type found or required TIFF tags are missing\\n\"\n        \"    in TIFF File \\\"%s\\\"\\n\\n\"\n        \"  TIFFs must contain the following:\\n\"\n        \"        Sample format: Unsigned or signed integer or IEEE floating point data\\n\"\n        \"                       (ASF is not yet supporting TIFF files with complex number type data),\\n\"\n        \"        Planar config: Contiguous (Greyscale, RGB, or RGBA) or separate planes (band-sequential.)\\n\"\n        \"      Bits per sample: 8, 16, or 32\\n\"\n        \"      Number of bands: 1 through %d bands allowed.\\n\"\n        \"               Format: Scanline, strip, or tiled\\n\"\n        \"             Colormap: Present or not present (only valid for 1-band images)\\n\",\n        inFileName, MAX_BANDS);\n  }\n  XTIFFClose(input_tiff);\n\n  // Get the image data type from the variable arguments list\n  va_start(ap, outBaseName);\n  pTmpChar = (char *)va_arg(ap, char *);\n  va_end(ap);\n\n  // Read the metadata (map-projection data etc) from the TIFF\n  asfPrintStatus(\"\\nImporting TIFF/GeoTIFF image to ASF Internal format...\\n\\n\");\n  int i;\n  for (i=0; i<MAX_BANDS; i++) ignore[i]=0; // Default to ignoring no bands\n  if (pTmpChar != NULL) {\n    strcpy(image_data_type, pTmpChar);\n    meta = read_generic_geotiff_metadata(inFileName, ignore, image_data_type);\n  }\n  else {\n    meta = read_generic_geotiff_metadata(inFileName, ignore, NULL);\n  }\n\n  // Write the Metadata file\n  meta_write(meta, outBaseName);\n\n  // Write the binary file\n  input_tiff = XTIFFOpen (inFileName, \"r\");\n  if (input_tiff == NULL)\n    asfPrintError (\"Error opening input TIFF file:\\n    %s\\n\", inFileName);\n  if (geotiff_band_image_write(input_tiff, meta, outBaseName, num_bands, ignore,\n                               bits_per_sample, sample_format, planar_config))\n  {\n    XTIFFClose(input_tiff);\n    meta_free(meta);\n    meta=NULL;\n    asfPrintError(\"Unable to write binary image...\\n    %s\\n\", outBaseName);\n  }\n  XTIFFClose(input_tiff);\n  if (meta) meta_free(meta);\n}\n\nmeta_parameters * read_generic_geotiff_metadata(const char *inFileName, int *ignore, ...)\n{\n  int geotiff_data_exists;\n  short num_bands;\n  char *bands[MAX_BANDS]; // list of band IDs\n  int band_num = 0;\n  int count;\n  int read_count;\n  int ret;\n  short model_type=-1;\n  short raster_type=-1;\n  short linear_units=-1;\n  short angular_units=-1;\n  double scale_factor;\n  char no_data[25];\n  TIFF *input_tiff;\n  GTIF *input_gtif;\n  meta_parameters *meta_out; // Return value\n  data_type_t data_type;\n  datum_type_t datum;\n  va_list ap;\n\n  /***** INITIALIZE PARAMETERS *****/\n  /*                               */\n  // Create a new metadata object for the image.\n  meta_out = raw_init ();\n  meta_out->optical = NULL;\n  meta_out->thermal = NULL;\n  meta_out->projection = meta_projection_init ();\n  meta_out->stats = NULL; //meta_stats_init ();\n  meta_out->state_vectors = NULL;\n  meta_out->location = meta_location_init ();\n  meta_out->colormap = NULL; // Updated below if palette color TIFF\n  // Don't set any of the deprecated structure elements.\n  meta_out->stVec = NULL;\n  meta_out->geo = NULL;\n  meta_out->ifm = NULL;\n  meta_out->info = NULL;\n  datum = UNKNOWN_DATUM;\n\n  // Set up convenience pointers\n  meta_general *mg = meta_out->general;\n  meta_projection *mp = meta_out->projection;\n  meta_location *ml = meta_out->location;\n  // FIXME:\n  // The following function works perfectly fine when called from asf_view.\n  // However, over here it resulted in a segmentation fault. Did not get the\n  // time to find a solution before the release. - RG\n  //meta_out->insar = populate_insar_metadata(inFileName);\n\n  // Init\n  mp->spheroid = UNKNOWN_SPHEROID; // meta_projection_init() 'should' initialize this, but doesn't\n\n  // Open the input tiff file.\n  input_tiff = XTIFFOpen (inFileName, \"r\");\n  if (input_tiff == NULL) {\n    asfPrintError(\"Error opening input TIFF file:\\n  %s\\n\", inFileName);\n  }\n\n  // Open the structure that contains the geotiff keys.\n  input_gtif = GTIFNew (input_tiff);\n  if (input_gtif == NULL) {\n    asfPrintError(\"Error reading GeoTIFF keys from input TIFF file:\\n  %s\\n\", inFileName);\n  }\n\n\n  /***** GET WHAT WE CAN FROM THE TIFF FILE *****/\n  /*                                            */\n  // Malloc the band names and give them numeric names as defaults\n  // (Updated from citation string later ...if the info exists)\n  for (band_num = 0; band_num < MAX_BANDS; band_num++) {\n    bands[band_num] = MALLOC(sizeof(char) * (BAND_NAME_LENGTH+1));\n    sprintf (bands[band_num], \"%02d\", band_num+1);\n  }\n\n  // The data type returned is an ASF data type, e.g. BYTE or REAL32 etc\n  //\n  // The number of bands returned is based on the samples (values) per\n  // pixel stored in the TIFF tags ...but some bands may be blank or ignored.\n  // Later on, band-by-band statistics will determine if individual bands should\n  // be ignored (not imported to an img file) and if the citation string contains\n  // a band ID list, then any band marked with the word 'Empty' will also be ignored.\n  // the number of bands will be updated to reflect these findings.\n  //\n  short sample_format;    // TIFFTAG_SAMPLEFORMAT\n  short bits_per_sample;  // TIFFTAG_BITSPERSAMPLE\n  short planar_config;    // TIFFTAG_PLANARCONFIG\n  int is_scanline_format; // False if tiled or strips > 1 TIFF file format\n  int is_palette_color_tiff;\n  ret = get_tiff_data_config(input_tiff,\n                             &sample_format, // TIFF type (uint, int, float)\n                             &bits_per_sample, // 8, 16, or 32\n                             &planar_config, // Contiguous (RGB or RGBA) or separate (band sequential, not interlaced)\n                             &data_type, // ASF datatype, (BYTE, INTEGER16, INTEGER32, or REAL32 ...no complex\n                             &num_bands, // Initial number of bands\n                             &is_scanline_format,\n                             &is_palette_color_tiff,\n                             REPORT_LEVEL_WARNING);\n\n  if (ret != 0) {\n    char msg[1024];\n    tiff_type_t t;\n    get_tiff_type(input_tiff, &t);\n    sprintf(msg, \"FOUND TIFF tag data as follows:\\n\"\n        \"         Sample Format: %s\\n\"\n        \"       Bits per Sample: %d\\n\"\n        \"  Planar Configuration: %s\\n\"\n        \"       Number of Bands: %d\\n\"\n        \"                Format: %s\\n\",\n        (sample_format == SAMPLEFORMAT_UINT) ? \"Unsigned Integer\" :\n          (sample_format == SAMPLEFORMAT_INT) ? \"Signed Integer\" :\n            (sample_format == SAMPLEFORMAT_IEEEFP) ? \"Floating Point\" : \"Unknown or Unsupported\",\n        bits_per_sample,\n        (planar_config == PLANARCONFIG_CONTIG) ? \"Contiguous (chunky RGB or RGBA etc) / Interlaced\" :\n          (planar_config == PLANARCONFIG_SEPARATE) ? \"Separate planes (band-sequential)\" :\n            \"Unknown or unrecognized\",\n        num_bands,\n        t.format == SCANLINE_TIFF ? \"SCANLINE TIFF\" :\n        t.format == STRIP_TIFF ? \"STRIP TIFF\" :\n        t.format == TILED_TIFF ? \"TILED TIFF\" : \"UNKNOWN\");\n    switch (t.format) {\n      case STRIP_TIFF:\n        sprintf(msg, \"%s\"\n                \"        Rows per Strip: %d\\n\",\n                msg, t.rowsPerStrip);\n        break;\n      case TILED_TIFF:\n        sprintf(msg, \"%s\"\n                \"            Tile Width: %d\\n\"\n                \"           Tile Height: %d\\n\",\n                msg, t.tileWidth, t.tileLength);\n        break;\n      case SCANLINE_TIFF:\n      default:\n        break;\n    }\n    asfPrintWarning(msg);\n\n    asfPrintError(\"  Unsupported TIFF type found or required TIFF tags are missing\\n\"\n        \"    in TIFF File \\\"%s\\\"\\n\\n\"\n        \"  TIFFs must contain the following:\\n\"\n        \"        Sample format: Unsigned or signed integer or IEEE floating point data\\n\"\n        \"                       (ASF is not yet supporting TIFF files with complex number type data),\\n\"\n        \"        Planar config: Contiguous (Greyscale, RGB, or RGBA) or separate planes (band-sequential.)\\n\"\n        \"      Bits per sample: 8, 16, or 32\\n\"\n        \"      Number of bands: 1 through %d bands allowed.\\n\"\n        \"               Format: Scanline, strip, or tiled\\n\",\n        inFileName, MAX_BANDS);\n  }\n  asfPrintStatus(\"\\n   Found %d-banded Generic GeoTIFF with %d-bit %s type data\\n\"\n      \"        (Note: Empty or missing bands will be ignored)\\n\",\n                 num_bands, bits_per_sample,\n      (sample_format == SAMPLEFORMAT_UINT)   ? \"Unsigned Integer\" :\n      (sample_format == SAMPLEFORMAT_INT)    ? \"Signed Integer\"   :\n      (sample_format == SAMPLEFORMAT_IEEEFP) ? \"Floating Point\"   : \"Unknown or Unsupported\");\n\n  char *citation = NULL;\n  int citation_length;\n  int typeSize;\n  tagtype_t citation_type;\n  citation_length = GTIFKeyInfo(input_gtif, GTCitationGeoKey, &typeSize, &citation_type);\n  if (citation_length > 0) {\n    citation = MALLOC ((citation_length) * typeSize);\n    GTIFKeyGet (input_gtif, GTCitationGeoKey, citation, 0, citation_length);\n    asfPrintStatus(\"\\nCitation: %s\\n\\n\", citation);\n  }\n  else {\n    citation_length = GTIFKeyInfo(input_gtif, PCSCitationGeoKey, &typeSize, &citation_type);\n    if (citation_length > 0) {\n      citation = MALLOC ((citation_length) * typeSize);\n      GTIFKeyGet (input_gtif, PCSCitationGeoKey, citation, 0, citation_length);\n      asfPrintStatus(\"\\nCitation: %s\\n\\n\", citation);\n    }\n    else {\n      asfPrintStatus(\"\\nCitation: The GeoTIFF citation string is MISSING (Not req'd)\\n\\n\");\n    }\n  }\n\n  // If this is a single-band TIFF with an embedded RGB colormap, then\n  // grab it for the metadata and write it out as an ASF LUT file\n  if (is_palette_color_tiff) {\n      // Produce metadata\n      char *look_up_table = NULL;\n      unsigned short *red = NULL;\n      unsigned short *green = NULL;\n      unsigned short *blue = NULL;\n      int i;\n      int map_size = 1<<bits_per_sample;\n\n      asfRequire(map_size > 0 && map_size <= 256, \"Invalid colormap size\\n\");\n\n      asfPrintStatus(\"\\nFound single-band TIFF with embedded RGB colormap\\n\\n\");\n      meta_colormap *mc = meta_out->colormap = meta_colormap_init();\n\n      get_look_up_table_name(citation, &look_up_table);\n      strcpy(mc->look_up_table, look_up_table ? look_up_table : MAGIC_UNSET_STRING);\n      FREE(look_up_table);\n\n      read_count = TIFFGetField(input_tiff, TIFFTAG_COLORMAP, &red, &green, &blue);\n      if (!read_count) {\n          asfPrintWarning(\"TIFF appears to be a palette-color TIFF, but the embedded\\n\"\n                  \"color map (TIFFTAG_COLORMAP) appears to be missing.  Ingest\\n\"\n                  \"will continue, but as a non-RGB single-band greyscale image.\\n\");\n          FREE(mc->look_up_table);\n          FREE(mc);\n      }\n      else {\n          // Populate the RGB colormap\n\tchar band_str[255];\n\tstrcpy(band_str, bands[0]);\n\tfor (i=1; i<num_bands; i++)\n\t  sprintf(band_str, \",%s\", bands[i]);\n\tstrcpy(mc->band_id, band_str);\n          mc->num_elements = map_size;\n          mc->rgb = (meta_rgb *)CALLOC(map_size, sizeof(meta_rgb));\n          for (i=0; i<map_size; i++) {\n              mc->rgb[i].red   = (unsigned char)((red[i]/(float)USHORT_MAX)*(float)MAX_RGB);\n              mc->rgb[i].green = (unsigned char)((green[i]/(float)USHORT_MAX)*(float)MAX_RGB);\n              mc->rgb[i].blue  = (unsigned char)((blue[i]/(float)USHORT_MAX)*(float)MAX_RGB);\n          }\n      }\n      // NOTE: Do NOT free the red/green/blue arrays ...this will result in a\n      // glib double-free error when the TIFF file is closed.\n\n      // Now that we have good metadata, produce the LUT\n      char *lut_file = appendExt(inFileName, \".lut\");\n      asfPrintStatus(\"\\nSTORING TIFF file embedded color map in look up table file:\\n    %s\\n\", lut_file);\n      FILE *lutFP = (FILE *)FOPEN(lut_file, \"wt\");\n      fprintf(lutFP, \"# Look up table type: %s\\n\", mc->look_up_table);\n      fprintf(lutFP, \"# Originating source: %s\\n\", inFileName);\n      fprintf(lutFP, \"# Index   Red   Green   Blue\\n\");\n      for (i=0; i<map_size; i++) {\n          fprintf(lutFP, \"%03d    %03d    %03d    %03d\\n\",\n                  i, mc->rgb[i].red, mc->rgb[i].green, mc->rgb[i].blue);\n      }\n      fprintf(lutFP, \"\\n\");\n      FCLOSE(lutFP);\n      FREE(lut_file);\n  }\n\n  // Get the tie point which defines the mapping between raster\n  // coordinate space and geographic coordinate space.  Although\n  // geotiff theoretically supports multiple tie points, we don't\n  // (rationale: ArcView currently doesn't either, and multiple tie\n  // points don't make sense with the pixel scale option, which we\n  // need).\n  // NOTE: Since neither ERDAS or ESRI store tie points in the .aux\n  // file associated with their geotiffs, it is _required_ that they\n  // are found in their tiff files.\n  double *tie_point = NULL;\n  (input_gtif->gt_methods.get)(input_gtif->gt_tif, GTIFF_TIEPOINTS, &count,\n                               &tie_point);\n  if (count != 6) {\n    asfPrintError (\"GeoTIFF file does not contain tie points\\n\");\n  }\n  // Get the scale factors which define the scale relationship between\n  // raster pixels and geographic coordinate space.\n  double *pixel_scale = NULL;\n  (input_gtif->gt_methods.get)(input_gtif->gt_tif, GTIFF_PIXELSCALE, &count,\n                               &pixel_scale);\n  if (count != 3) {\n    asfPrintError (\"GeoTIFF file does not contain pixel scale parameters\\n\");\n  }\n  if (pixel_scale[0] <= 0.0 || pixel_scale[1] <= 0.0) {\n    asfPrintError (\"GeoTIFF file contains invalid pixel scale parameters\\n\");\n  }\n\n  // CHECK TO SEE IF THE GEOTIFF CONTAINS USEFUL DATA:\n  //  If the tiff file contains geocoded information, then the model type\n  // will be ModelTypeProjected.\n  // FIXME: Geographic (lat/long) type geotiffs with decimal degrees are\n  // supported, but arc-sec are not yet ...\n\n  int geographic_geotiff, map_projected_geotiff, geocentric_geotiff;\n  classify_geotiff(input_gtif, &model_type, &raster_type, &linear_units, &angular_units,\n                   &geographic_geotiff, &geocentric_geotiff, &map_projected_geotiff,\n                   &geotiff_data_exists);\n  asfPrintStatus (\"Input GeoTIFF key GTModelTypeGeoKey is %s\\n\",\n                  (model_type == ModelTypeGeographic) ? \"ModelTypeGeographic\" :\n                  (model_type == ModelTypeGeocentric) ? \"ModelTypeGeocentric\" :\n                  (model_type == ModelTypeProjected)  ? \"ModelTypeProjected\"  : \"Unknown\");\n  asfPrintStatus (\"Input GeoTIFF key GTRasterTypeGeoKey is %s\\n\",\n                  (raster_type == RasterPixelIsArea)  ? \"RasterPixelIsArea\" : \"(Unsupported type)\");\n  if (map_projected_geotiff) {\n      asfPrintStatus (\"Input GeoTIFF key ProjLinearUnitsGeoKey is %s\\n\",\n                      (linear_units == Linear_Meter)                  ? \"Linear_Meter\"                  :\n\t\t      (linear_units == Linear_Foot)                   ? \"Linear_Foot\"                   :\n\t\t      (linear_units == Linear_Foot_US_Survey)         ? \"Linear_Foot_US_Survey\"         :\n\t\t      (linear_units == Linear_Foot_Modified_American) ? \"Linear_Foot_Modified_American\" :\n\t\t      (linear_units == Linear_Foot_Clarke)            ? \"Linear_Foot_Clarke\"            :\n\t\t      (linear_units == Linear_Foot_Indian)            ? \"Linear_Foot_Indian\"            :\n                                                                        \"(Unsupported type of linear units)\");\n  }\n  else if (geographic_geotiff) {\n      asfPrintStatus (\"Input GeoTIFF key GeogAngularUnitsGeoKey is %s\\n\",\n                      (angular_units == Angular_Arc_Second)  ? \"Angular_Arc_Second\" :\n                      (angular_units == Angular_Degree)      ? \"Angular_Degree\"     :\n                                                               \"(Unsupported type of angular units)\");\n  }\n  else {\n      asfPrintError (\"Cannot determine type of linear or angular units in GeoTIFF\\n\");\n  }\n  /***** READ PROJECTION PARAMETERS FROM TIFF IF GEO DATA EXISTS                 *****/\n  /***** THEN READ THEM FROM THE METADATA (.AUX) FILE TO SUPERCEDE IF THEY EXIST *****/\n  /*                                                                                 */\n  /*                                                */\n  // import_arcgis_geotiff() would not be called (see detect_geotiff_flavor())\n  // unless the model_type is either unknown or is ModelTypeProjected.  If\n  // ModelTypeProjected, then there are projection parameters inside the\n  // GeoTIFF file.  If not, then they must be parsed from the complementary\n  // ArcGIS metadata (.aux) file\n  // Read the model type from the GeoTIFF file ...expecting that it is\n  // unknown, but could possibly be ModelTypeProjection\n  //\n  // Start of reading projection parameters from geotiff\n  if (model_type == ModelTypeProjected && geotiff_data_exists) {\n    char hemisphere;\n    projection_type_t projection_type=UNKNOWN_PROJECTION;\n    unsigned long pro_zone; // UTM zone (UTM only)\n    short proj_coords_trans = UNKNOWN_PROJECTION_TYPE;\n    short pcs;\n    short geokey_datum;\n    double false_easting = MAGIC_UNSET_DOUBLE;\n    double false_northing = MAGIC_UNSET_DOUBLE;\n    double lonOrigin = MAGIC_UNSET_DOUBLE;\n    double latOrigin = MAGIC_UNSET_DOUBLE;\n    double stdParallel1 = MAGIC_UNSET_DOUBLE;\n    double stdParallel2 = MAGIC_UNSET_DOUBLE;\n    double lonPole = MAGIC_UNSET_DOUBLE;\n\n    //////// ALL PROJECTIONS /////////\n    // Set the projection block data that we know at this point\n    if (tie_point[0] != 0 || tie_point[1] != 0 || tie_point[2] != 0) {\n      // NOTE: To support tie points at other locations, or a set of other locations,\n      // then things rapidly get more complex ...and a transformation must either be\n      // derived or provided (and utilized etc).  We're not at that point yet...\n      //\n      asfPrintError(\"Unsupported initial tie point type.  Initial tie point must be for\\n\"\n          \"raster location (0,0) in the image.\\n\");\n    }\n    mp->startX = tie_point[3];\n    mp->startY = tie_point[4];\n    if (pixel_scale[0] < 0 ||\n        pixel_scale[1] < 0) {\n      asfPrintWarning(\"Unexpected negative pixel scale values found in GeoTIFF file.\\n\"\n          \"Continuing ingest, but defaulting perX to fabs(x pixel scale) and\\n\"\n          \"perY to (-1)*fabs(y pixel scale)... Results may vary.\");\n    }\n    mp->perX = fabs(pixel_scale[0]);\n    mp->perY = -(fabs(pixel_scale[1]));\n    mp->height = 0.0;\n    if (linear_units == Linear_Meter) {\n      strcpy(mp->units, \"meters\");\n    }\n    else if (linear_units == Linear_Foot ||\n\t     linear_units == Linear_Foot_US_Survey ||\n\t     linear_units == Linear_Foot_Modified_American ||\n\t     linear_units == Linear_Foot_Clarke ||\n\t     linear_units == Linear_Foot_Indian)\n      strcpy(mp->units, \"feet\");\n    else {\n      asfPrintError(\"Unsupported linear unit found in map-projected GeoTIFF.  Only meters and feet are currently supported.\\n\");\n    }\n\n    ///////// STANDARD UTM (PCS CODE) //////////\n    // Get datum and zone as appropriate\n    read_count = GTIFKeyGet (input_gtif, ProjectedCSTypeGeoKey, &pcs, 0, 1);\n\n    // Quick hack for Rick's State Plane data\n    // Only supports State Plane \n    if (read_count && pcs >= 26931 && pcs <=26940) {\n      mp->type = STATE_PLANE;\n      projection_type = STATE_PLANE;\n      proj_coords_trans = CT_TransverseMercator;\n      datum = mp->datum = NAD83_DATUM;\n      mp->spheroid = GRS1980_SPHEROID;\n    }\n\n    if (!read_count) {\n      // Check to see if this is a vintage ASF UTM geotiff (they only had the UTM\n      // description in the UTM string rather than in the ProejctedCSTypeGeoKey)\n      int sleepy;\n      datum_type_t dopey;\n      char sneezy;\n      read_count = vintage_utm_citation_to_pcs(citation, &sleepy, &sneezy, &dopey, &pcs);\n    }\n    if (read_count == 1 && PCS_2_UTM(pcs, &hemisphere, &datum, &pro_zone)) {\n      mp->type = UNIVERSAL_TRANSVERSE_MERCATOR;\n      mp->hem = hemisphere;\n      mp->param.utm.zone = pro_zone;\n      mp->param.utm.false_easting = 500000.0;\n      if (hemisphere == 'N') {\n        mp->param.utm.false_northing = 0.0;\n      }\n      else {\n        mp->param.utm.false_northing = 10000000.0;\n      }\n      mp->param.utm.lat0 = 0.0;\n      mp->param.utm.lon0 = utm_zone_to_central_meridian(pro_zone);\n      if (datum != UNKNOWN_DATUM) {\n        mp->datum = datum;\n      }\n      else {\n        asfPrintError(\"Unsupported or unknown datum found in GeoTIFF file.\\n\");\n      }\n      char msg[256];\n      sprintf(msg,\"UTM scale factor defaulting to %0.4lf\\n\", DEFAULT_UTM_SCALE_FACTOR);\n      asfPrintStatus(msg);\n      mp->param.utm.scale_factor = DEFAULT_UTM_SCALE_FACTOR;\n    }\n    ////////// ALL OTHER PROJECTION TYPES - INCLUDING GCS/USER-DEFINED UTMS /////////\n    else if (projection_type != STATE_PLANE) { // Hack !!!!\n\n      // Not recognized as a supported UTM PCS or was a user-defined or unknown type of PCS...\n      //\n      // The ProjCoordTransGeoKey will be true if the PCS was user-defined or if the PCS was\n      // not in the geotiff file... or so the standard says.  If the ProjCoordTransGeoKey is\n      // false, it means that an unsupported (by us) UTM or State Plane projection was\n      // discovered (above.)  All other projection types make use of the ProjCoordTransGeoKey\n      // geokey.\n\n      ////// GCS-CODE DEFINED UTM ///////\n      // Check for a user-defined UTM projection (A valid UTM code may be in\n      // ProjectionGeoKey, although this is not typical)\n      read_count = GTIFKeyGet (input_gtif, ProjectionGeoKey, &pcs, 0, 0);\n      if (read_count == 1 && PCS_2_UTM(pcs, &hemisphere, &datum, &pro_zone)) {\n        mp->type = UNIVERSAL_TRANSVERSE_MERCATOR;\n        mp->hem = hemisphere;\n        mp->param.utm.zone = pro_zone;\n        mp->param.utm.false_easting = 500000.0;\n        if (hemisphere == 'N') {\n          mp->param.utm.false_northing = 0.0;\n        }\n        else {\n          mp->param.utm.false_northing = 10000000.0;\n        }\n        mp->param.utm.lat0 = utm_zone_to_central_meridian(pro_zone);\n        mp->param.utm.lon0 = 0.0;\n        if (datum != UNKNOWN_DATUM) {\n          mp->datum = datum;\n        }\n        else if (pcs/100 == 160 || pcs/100 == 161) {\n            // With user-defined UTMs (16001-16060, 16101-16160 in ProjectionGeoKey\n            // the zone and hemisphere is defined, but not the datum... We should try\n            // to determine the datum as follows:\n            //\n            // Read GeographicTypeGeoKey:\n            //\n            // GeographicTypeGeoKey, If the code is recognized, assign as appropriate.\n            //                       If the code is 32676 (user-defined ...which also often\n            //                         means \"undefined\" rather than \"user defined\") then\n            //                         check to see if the datum is specifically defined\n            //                         elsewhere:\n            //                         - Check GeogGeodeticDatumGeoKey\n            //                         - Check PCSCitationGeoKey, GeogCitationGeoKey, and\n            //                           GTCitationGeoKey to see if it is textually described\n            //                         - Check to see if semi-major and inv. flattening (etc)\n            //                           is defined and then do a best-fit to determine a\n            //                           ellipsoid\n            //                         - Default to WGS-84 (if GeographicTypeGeoKey is\n            //                           160xx or 161xx format), else error out\n            //\n            //asfPrintError(\"Unsupported or unknown datum found in GeoTIFF file.\\n\");https://rt/Ticket/Display.html?id=7763\n            short gcs;\n            read_count = GTIFKeyGet (input_gtif, GeographicTypeGeoKey, &gcs, 0, 1);\n            if (read_count == 1) {\n                switch(geokey_datum){\n                    case GCS_WGS_84:\n                    case GCSE_WGS84:\n                        datum = WGS84_DATUM;\n                        break;\n                    case GCS_NAD27:\n                        datum = NAD27_DATUM;\n                        break;\n                    case GCS_NAD83:\n                        datum = NAD83_DATUM;\n                        break;\n\t\t    case GCS_ED50:\n\t\t      datum = ED50_DATUM;\n\t\t      break;\n\t\t    case GCS_SAD69:\n\t\t      datum = SAD69_DATUM;\n\t\t      break;\n                    default:\n                        datum = UNKNOWN_DATUM;\n                        break;\n                }\n            }\n            if (datum == UNKNOWN_DATUM) {\n                // The datum is not typically stored in GeogGeodeticDatumGeoKey, but some s/w\n                // does put it there\n                read_count = GTIFKeyGet (input_gtif, GeogGeodeticDatumGeoKey, &geokey_datum, 0, 1);\n                if (read_count == 1) {\n                    switch(geokey_datum){\n                        case Datum_WGS84:\n                            datum = WGS84_DATUM;\n                            break;\n                        case Datum_North_American_Datum_1927:\n                            datum = NAD27_DATUM;\n                            break;\n                        case Datum_North_American_Datum_1983:\n                            datum = NAD83_DATUM;\n                            break;\n\t\t        case 6655: // ITRF97\n\t\t\t  datum = ITRF97_DATUM;\n\t\t\t  break;\n\t\t        case 6054: // HUGHES80\n\t\t\t  datum = HUGHES_DATUM;\n\t\t\t  break;\n                        default:\n                            datum = UNKNOWN_DATUM;\n                            break;\n                    }\n                }\n            }\n            if (datum == UNKNOWN_DATUM) {\n                // Try citation strings to see if the datum was textually described\n                char *citation = NULL;\n                int citation_length;\n                int typeSize;\n                tagtype_t citation_type;\n                citation_length = GTIFKeyInfo(input_gtif, GeogCitationGeoKey, &typeSize, &citation_type);\n                if (citation_length > 0) {\n                    citation = MALLOC ((citation_length) * typeSize);\n                    GTIFKeyGet (input_gtif, GeogCitationGeoKey, citation, 0, citation_length);\n                    check_for_datum_in_string(citation, &datum);\n                    FREE(citation);\n                }\n                if (datum == UNKNOWN_DATUM) {\n                    citation_length = GTIFKeyInfo(input_gtif, GTCitationGeoKey, &typeSize, &citation_type);\n                    if (citation_length > 0) {\n                        citation = MALLOC ((citation_length) * typeSize);\n                        GTIFKeyGet (input_gtif, GTCitationGeoKey, citation, 0, citation_length);\n                        check_for_datum_in_string(citation, &datum);\n                        FREE(citation);\n                    }\n                }\n                if (datum == UNKNOWN_DATUM) {\n                    citation_length = GTIFKeyInfo(input_gtif, PCSCitationGeoKey, &typeSize, &citation_type);\n                    if (citation_length > 0) {\n                        citation = MALLOC ((citation_length) * typeSize);\n                        GTIFKeyGet (input_gtif, PCSCitationGeoKey, citation, 0, citation_length);\n                        check_for_datum_in_string(citation, &datum);\n                        FREE(citation);\n                    }\n                }\n                if (datum == UNKNOWN_DATUM) {\n                    spheroid_type_t spheroid;\n                    check_for_ellipse_definition_in_geotiff(input_gtif, &spheroid);\n                    switch (spheroid) {\n                        case BESSEL_SPHEROID:\n                        case CLARKE1866_SPHEROID:\n                        case CLARKE1880_SPHEROID:\n                        case GEM6_SPHEROID:\n                        case GEM10C_SPHEROID:\n                        case GRS1980_SPHEROID:\n                        case INTERNATIONAL1924_SPHEROID:\n                        case INTERNATIONAL1967_SPHEROID:\n                        case WGS72_SPHEROID:\n                        case WGS84_SPHEROID:\n                        case HUGHES_SPHEROID:\n                        case UNKNOWN_SPHEROID:\n                        default:\n                            datum = UNKNOWN_DATUM;\n                            break;\n                    }\n                }\n                if (datum == UNKNOWN_DATUM) {\n                    // If all else fails, make it a WGS-84 and spit out a warning\n                    datum = WGS84_DATUM;\n                    mp->datum = datum;\n                    asfPrintWarning(\"Could not determine datum type from GeoTIFF, but since this\\n\"\n                            \"is a EPSG 160xx/161xx type UTM projection (WGS84 typ.),\\n\"\n                            \"a WGS84 datum type is assumed.\\n\");\n                }\n            }\n        }\n        char msg[256];\n        sprintf(msg,\"UTM scale factor defaulting to %0.4lf\\n\", DEFAULT_UTM_SCALE_FACTOR);\n        asfPrintStatus(msg);\n        mp->param.utm.scale_factor = DEFAULT_UTM_SCALE_FACTOR;\n      }\n      /////// OTHER PROJECTION DEFINITIONS - INCLUDING USER-DEFINED UTMS///////\n      else {\n        // Some other type of projection may exist, including a projection-coordinate-transformation\n        // UTM (although that is not typical)\n\n        // Get the projection coordinate transformation key (identifies the projection type)\n        read_count = GTIFKeyGet (input_gtif, ProjCoordTransGeoKey, &proj_coords_trans, 0, 1);\n        if (read_count != 1 || proj_coords_trans == UNKNOWN_PROJECTION_TYPE) {\n          asfPrintWarning(\"Unable to determine type of projection coordinate system in GeoTIFF file\\n\");\n        }\n\n        // Attempt to find a defined datum (the standard says to store it in GeographicTypeGeoKey)\n        read_count = GTIFKeyGet (input_gtif, GeographicTypeGeoKey, &geokey_datum, 0, 1);\n        if (read_count == 1) {\n          switch(geokey_datum){\n            case GCS_WGS_84:\n            case GCSE_WGS84:\n              datum = WGS84_DATUM;\n              break;\n            case GCS_NAD27:\n              datum = NAD27_DATUM;\n              break;\n            case GCS_NAD83:\n              datum = NAD83_DATUM;\n              break;\n\t    case GCS_ED50:\n\t      datum = ED50_DATUM;\n\t      break;\n\t    case GCS_SAD69:\n\t      datum = SAD69_DATUM;\n\t      break;\n            default:\n              datum = UNKNOWN_DATUM;\n              break;\n          }\n        }\n        if (datum == UNKNOWN_DATUM) {\n          // The datum is not typically stored in GeogGeodeticDatumGeoKey, but some s/w\n          // does put it there\n          read_count = GTIFKeyGet (input_gtif, GeogGeodeticDatumGeoKey, &geokey_datum, 0, 1);\n          if (read_count == 1) {\n            switch(geokey_datum){\n              case Datum_WGS84:\n                datum = WGS84_DATUM;\n                break;\n              case Datum_North_American_Datum_1927:\n                datum = NAD27_DATUM;\n                break;\n              case Datum_North_American_Datum_1983:\n                datum = NAD83_DATUM;\n                break;\n\t      case 6655: // ITRF97\n\t\tdatum = ITRF97_DATUM;\n\t\tbreak;\n\t      case 6054: // HUGHES80\n\t\tdatum = HUGHES_DATUM;\n\t\tbreak;\n              default:\n                datum = UNKNOWN_DATUM;\n                break;\n            }\n          }\n        }\n        // Hughes datum support ...The Hughes-1980 datum is user-defined and the\n        // typically defined by the major and inv-flattening\n        // FIXME: There are several ways of representing otherwise-undefined datum\n        // datum types ...maybe consider supporting those?  (Probably not...)\n        // FIXME: Found out that there is an EPSG GCS code for NSIDC SSM/I polar\n        // stereo ...for PS using Hughes, we should write this numeric value out\n        // and avoid using a user-defined datum (technically there is no such thing as\n        // a 'hughes datum' ...it's an earth-centered reference spheroid and the datum\n        // is undetermined.  Sigh... works exactly the same either way blah blah blah.)\n        if (datum == UNKNOWN_DATUM) {\n          short int ellipsoid_key;\n          read_count = GTIFKeyGet(input_gtif, GeogEllipsoidGeoKey, &ellipsoid_key, 0, 1);\n          if (read_count && ellipsoid_key == USER_DEFINED_KEY) {\n            double semi_major = 0.0;\n            double semi_minor = 0.0;\n            double inv_flattening = 0.0;\n            double hughes_semiminor = HUGHES_SEMIMAJOR * (1.0 - 1.0/HUGHES_INV_FLATTENING);\n            read_count = GTIFKeyGet(input_gtif, GeogSemiMajorAxisGeoKey, &semi_major, 0, 1);\n            read_count += GTIFKeyGet(input_gtif, GeogInvFlatteningGeoKey, &inv_flattening, 0, 1);\n            read_count += GTIFKeyGet(input_gtif, GeogSemiMinorAxisGeoKey, &semi_minor, 0, 1);\n            if (read_count >= 2 &&\n                     semi_major != USER_DEFINED_KEY &&\n                     inv_flattening != USER_DEFINED_KEY &&\n                     FLOAT_COMPARE_TOLERANCE(semi_major, HUGHES_SEMIMAJOR, FLOAT_TOLERANCE) &&\n                     FLOAT_COMPARE_TOLERANCE(inv_flattening, HUGHES_INV_FLATTENING, FLOAT_TOLERANCE))\n            {\n              datum = HUGHES_DATUM;\n            }\n            else if (read_count >= 2 &&\n                     semi_major != USER_DEFINED_KEY &&\n                     semi_minor != USER_DEFINED_KEY &&\n                     FLOAT_COMPARE_TOLERANCE(semi_major, HUGHES_SEMIMAJOR, FLOAT_TOLERANCE) &&\n                     FLOAT_COMPARE_TOLERANCE(semi_minor, hughes_semiminor, FLOAT_TOLERANCE))\n            {\n              datum = HUGHES_DATUM;\n            }\n            else if (read_count >= 2 &&\n                     semi_minor != USER_DEFINED_KEY &&\n                     inv_flattening != USER_DEFINED_KEY &&\n                     FLOAT_COMPARE_TOLERANCE(semi_minor, hughes_semiminor, FLOAT_TOLERANCE) &&\n                     FLOAT_COMPARE_TOLERANCE(inv_flattening, HUGHES_INV_FLATTENING, FLOAT_TOLERANCE))\n            {\n              datum = HUGHES_DATUM;\n            }\n\t    else if (read_count >=2 && \n\t\t     FLOAT_COMPARE_TOLERANCE(semi_minor, semi_major, \n\t\t\t\t\t     FLOAT_TOLERANCE)) {\n\t      mp->spheroid = SPHERE;\n\t      mp->re_major = semi_major;\n\t      mp->re_minor = semi_minor;\n\t      datum = UNKNOWN_DATUM;\n\t    }\n            else {\n              datum = UNKNOWN_DATUM;\n            }\n          }\n          else {\n            datum = UNKNOWN_DATUM;\n          }\n        }\n        if (datum == UNKNOWN_DATUM && mp->spheroid != SPHERE) {\n          asfPrintWarning(\"Unable to determine datum type from GeoTIFF file\\n\"\n                        \"Defaulting to WGS-84 ...This may result in projection errors\\n\");\n          datum = WGS84_DATUM;\n        }\n        // Take whatever datum we have at this point\n        mp->datum = datum;\n\n        // Base on the type of projection coordinate transformation, e.g. type of projection,\n        // retrieve the rest of the projection parameters\n        projection_type = UNKNOWN_PROJECTION;\n        scale_factor = DEFAULT_SCALE_FACTOR;\n        switch(proj_coords_trans) {\n          case CT_TransverseMercator:\n          case CT_TransvMercator_Modified_Alaska:\n          case CT_TransvMercator_SouthOriented:\n            read_count = GTIFKeyGet (input_gtif, ProjFalseEastingGeoKey, &false_easting, 0, 1);\n            if (read_count != 1) {\n              asfPrintStatus(\"No false easting in ProjFalseEastingGeoKey ...OK for a UTM\\n\");\n            }\n            read_count = GTIFKeyGet (input_gtif, ProjFalseNorthingGeoKey, &false_northing, 0, 1);\n            if (read_count != 1) {\n              asfPrintStatus(\"No false northing in ProjFalseNorthingGeoKey ...OK for a UTM\\n\");\n            }\n            read_count = GTIFKeyGet (input_gtif, ProjNatOriginLongGeoKey, &lonOrigin, 0, 1);\n            if (read_count != 1) {\n              asfPrintStatus(\"No center longitude in ProjNatOriginLongGeoKey ...OK for a UTM\\n\");\n            }\n            read_count = GTIFKeyGet (input_gtif, ProjNatOriginLatGeoKey, &latOrigin, 0, 1);\n            if (read_count != 1) {\n              asfPrintStatus(\"No center latitude in ProjNatOriginLatGeoKey ...OK for a UTM\\n\");\n            }\n            else {\n              latOrigin = 0.0;\n            }\n            read_count = GTIFKeyGet (input_gtif, ProjScaleAtNatOriginGeoKey, &scale_factor, 0, 1);\n            if (read_count == 0) {\n              scale_factor = DEFAULT_UTM_SCALE_FACTOR;\n\n              char msg[256];\n              sprintf(msg,\"UTM scale factor defaulting to %0.4lf ...OK for a UTM\\n\", scale_factor);\n              asfPrintStatus(msg);\n            }\n            mp->type = UNIVERSAL_TRANSVERSE_MERCATOR;\n            mp->hem = (false_northing == 0.0) ? 'N' : (false_northing == 10000000.0) ? 'S' : '?';\n            mp->param.utm.zone = utm_zone(lonOrigin);\n            mp->param.utm.false_easting = false_easting;\n            mp->param.utm.false_northing = false_northing;\n            mp->param.utm.lat0 = latOrigin;\n            mp->param.utm.lon0 = lonOrigin;\n            mp->param.utm.scale_factor = scale_factor;\n            check_projection_parameters(mp);\n            break;\n          // Albers Conical Equal Area case IS tested\n          case CT_AlbersEqualArea:\n            read_count = GTIFKeyGet (input_gtif, ProjStdParallel1GeoKey, &stdParallel1, 0, 1);\n            if (read_count != 1) {\n              asfPrintWarning(\n                      \"Unable to determine first standard parallel from GeoTIFF file\\n\"\n                  \"using ProjStdParallel1GeoKey\\n\");\n            }\n            read_count = GTIFKeyGet (input_gtif, ProjStdParallel2GeoKey, &stdParallel2, 0, 1);\n            if (read_count != 1) {\n              asfPrintWarning(\n                      \"Unable to determine second standard parallel from GeoTIFF file\\n\"\n                  \"using ProjStdParallel2GeoKey\\n\");\n            }\n            read_count = GTIFKeyGet (input_gtif, ProjFalseEastingGeoKey, &false_easting, 0, 1);\n            if (read_count != 1) {\n              asfPrintWarning(\n                      \"Unable to determine false easting from GeoTIFF file\\n\"\n                  \"using ProjFalseEastingGeoKey\\n\");\n            }\n            read_count = GTIFKeyGet (input_gtif, ProjFalseNorthingGeoKey, &false_northing, 0, 1);\n            if (read_count != 1) {\n              asfPrintWarning(\n                      \"Unable to determine false northing from GeoTIFF file\\n\"\n                  \"using ProjFalseNorthingGeoKey\\n\");\n            }\n            read_count = GTIFKeyGet (input_gtif, ProjNatOriginLongGeoKey, &lonOrigin, 0, 1);\n            if (read_count != 1) {\n              asfPrintWarning(\"Unable to determine center longitude from GeoTIFF file\\n\"\n                  \"using ProjNatOriginLongGeoKey.  Trying ProjCenterLongGeoKey...\\n\");\n              read_count = GTIFKeyGet (input_gtif, ProjCenterLongGeoKey, &lonOrigin, 0, 1);\n              if (read_count != 1) {\n                asfPrintWarning(\"Unable to determine center longitude from GeoTIFF file\\n\"\n                    \"using ProjCenterLongGeoKey as well...\\n\");\n              }\n              else {\n                asfPrintStatus(\"\\nFound center longitude from ProjCenterLongGeoKey in GeoTIFF\"\n                               \"file...\\n\\n\");\n              }\n            }\n            read_count = GTIFKeyGet (input_gtif, ProjNatOriginLatGeoKey, &latOrigin, 0, 1);\n            if (read_count != 1) {\n              asfPrintWarning(\n                      \"Unable to determine center latitude from GeoTIFF file\\n\"\n                  \"using ProjNatOriginLatGeoKey\\n\");\n            }\n            mp->type = ALBERS_EQUAL_AREA;\n            mp->hem = (latOrigin > 0.0) ? 'N' : 'S';\n            mp->param.albers.std_parallel1 = stdParallel1;\n            mp->param.albers.std_parallel2 = stdParallel2;\n            mp->param.albers.center_meridian = lonOrigin;\n            mp->param.albers.orig_latitude = latOrigin;\n            mp->param.albers.false_easting = false_easting;\n            mp->param.albers.false_northing = false_northing;\n            check_projection_parameters(mp);\n            break;\n          // FIXME: The Lambert Conformal Conic 1-Std Parallel case is UNTESTED\n          case CT_LambertConfConic_1SP:\n            read_count = GTIFKeyGet (input_gtif, ProjFalseEastingGeoKey, &false_easting, 0, 1);\n            if (read_count != 1) {\n              asfPrintWarning(\n                        \"Unable to determine false easting from GeoTIFF file\\n\"\n                  \"using ProjFalseEastingGeoKey.  Assuming 0.0 meters and continuing...\\n\");\n              false_easting = 0.0;\n            }\n            read_count = GTIFKeyGet (input_gtif, ProjFalseNorthingGeoKey, &false_northing, 0, 1);\n            if (read_count != 1) {\n              asfPrintWarning(\n                      \"Unable to determine false northing from GeoTIFF file\\n\"\n                      \"using ProjFalseNorthingGeoKey.  Assuming 0.0 meters and continuing...\\n\");\n              false_northing = 0.0;\n            }\n            read_count = GTIFKeyGet (input_gtif, ProjNatOriginLongGeoKey, &lonOrigin, 0, 1);\n            if (read_count != 1) {\n              asfPrintWarning(\n                      \"Unable to determine center longitude from GeoTIFF file\\n\"\n                  \"using ProjNatOriginLongGeoKey\\n\");\n            }\n            read_count = GTIFKeyGet (input_gtif, ProjNatOriginLatGeoKey, &latOrigin, 0, 1);\n            if (read_count != 1) {\n              asfPrintWarning(\n                      \"Unable to determine center latitude from GeoTIFF file\\n\"\n                  \"using ProjNatOriginLatGeoKey\\n\");\n            }\n            read_count = GTIFKeyGet (input_gtif, ProjScaleAtNatOriginGeoKey, &scale_factor, 0, 1);\n            if (read_count != 1) {\n              scale_factor = DEFAULT_SCALE_FACTOR;\n\n              char msg[256];\n              sprintf(msg,\n                      \"Lambert Conformal Conic scale factor from ProjScaleAtNatOriginGeoKey not found in GeoTIFF ...defaulting to %0.4lf\\n\",\n                      scale_factor);\n              asfPrintWarning(msg);\n            }\n            mp->type = LAMBERT_CONFORMAL_CONIC;\n            mp->hem = (latOrigin > 0.0) ? 'N' : 'S';\n            mp->param.lamcc.plat1 = latOrigin;\n            mp->param.lamcc.plat2 = latOrigin;\n            mp->param.lamcc.lat0 = latOrigin;\n            mp->param.lamcc.lon0 = lonOrigin;\n            mp->param.lamcc.false_easting = false_easting;\n            mp->param.lamcc.false_northing = false_northing;\n            mp->param.lamcc.scale_factor = scale_factor;\n            check_projection_parameters(mp);\n            break;\n          case CT_LambertConfConic_2SP:\n            read_count = GTIFKeyGet (input_gtif, ProjStdParallel1GeoKey, &stdParallel1, 0, 1);\n            if (read_count != 1) {\n              asfPrintWarning(\n                      \"Unable to determine first standard parallel from GeoTIFF file\\n\"\n                  \"using ProjStdParallel1GeoKey\\n\");\n            }\n            read_count = GTIFKeyGet (input_gtif, ProjStdParallel2GeoKey, &stdParallel2, 0, 1);\n            if (read_count != 1) {\n              asfPrintWarning(\n                      \"Unable to determine second standard parallel from GeoTIFF file\\n\"\n                  \"using ProjStdParallel2GeoKey\\n\");\n            }\n            read_count = GTIFKeyGet (input_gtif, ProjFalseEastingGeoKey, &false_easting, 0, 1);\n            if (read_count != 1) {\n              asfPrintWarning(\n                      \"Unable to determine false easting from GeoTIFF file\\n\"\n                      \"using ProjFalseEastingGeoKey.  Assuming 0.0 meters and continuing...\\n\");\n              false_easting = 0.0;\n            }\n            read_count = GTIFKeyGet (input_gtif, ProjFalseNorthingGeoKey, &false_northing, 0, 1);\n            if (read_count != 1) {\n              asfPrintWarning(\n                      \"Unable to determine false northing from GeoTIFF file\\n\"\n                      \"using ProjFalseNorthingGeoKey.  Assuming 0.0 meters and continuing...\\n\");\n              false_northing = 0.0;\n            }\n            read_count = GTIFKeyGet (input_gtif, ProjFalseOriginLongGeoKey, &lonOrigin, 0, 1);\n            if (read_count != 1) {\n              asfPrintWarning(\n                      \"Unable to determine center longitude from GeoTIFF file\\n\"\n                  \"using ProjFalseOriginLongGeoKey\\n\");\n            }\n            read_count = GTIFKeyGet (input_gtif, ProjFalseOriginLatGeoKey, &latOrigin, 0, 1);\n            if (read_count != 1) {\n              asfPrintWarning(\n                      \"Unable to determine center latitude from GeoTIFF file\\n\"\n                  \"using ProjFalseOriginLatGeoKey\\n\");\n            }\n            mp->type = LAMBERT_CONFORMAL_CONIC;\n            mp->hem = (latOrigin > 0.0) ? 'N' : 'S';\n            mp->param.lamcc.plat1 = stdParallel1;\n            mp->param.lamcc.plat2 = stdParallel2;\n            mp->param.lamcc.lat0 = latOrigin;\n            mp->param.lamcc.lon0 = lonOrigin;\n            mp->param.lamcc.false_easting = false_easting;\n            mp->param.lamcc.false_northing = false_northing;\n            mp->param.lamcc.scale_factor = scale_factor;\n            check_projection_parameters(mp);\n            break;\n          case CT_PolarStereographic:\n            read_count = GTIFKeyGet (input_gtif, ProjNatOriginLatGeoKey, &latOrigin, 0, 1);\n            if (read_count != 1) {\n              asfPrintWarning(\n                      \"Unable to determine center latitude from GeoTIFF file\\n\"\n                  \"using ProjNatOriginLatGeoKey\\n\");\n            }\n            read_count = GTIFKeyGet (input_gtif, ProjStraightVertPoleLongGeoKey, &lonPole, 0, 1);\n            if (read_count != 1) {\n              asfPrintWarning(\n                      \"Unable to determine vertical pole longitude from GeoTIFF file\\n\"\n                  \"using ProjStraightVertPoleLongGeoKey\\n\");\n            }\n            read_count = GTIFKeyGet (input_gtif, ProjFalseEastingGeoKey, &false_easting, 0, 1);\n            if (read_count != 1) {\n              asfPrintWarning(\n                      \"Unable to determine false easting from GeoTIFF file\\n\"\n                  \"using ProjFalseEastingGeoKey\\n\");\n            }\n            read_count = GTIFKeyGet (input_gtif, ProjFalseNorthingGeoKey, &false_northing, 0, 1);\n            if (read_count != 1) {\n              asfPrintWarning(\n                      \"Unable to determine false northing from GeoTIFF file\\n\"\n                  \"using ProjFalseNorthingGeoKey\\n\");\n            }\n            // NOTE: The scale_factor exists in the ProjScaleAtNatOriginGeoKey, but we do not\n            // use it, e.g. it is not current written to the meta data file with meta_write().\n            mp->type = POLAR_STEREOGRAPHIC;\n            mp->hem = (latOrigin > 0) ? 'N' : 'S';\n            mp->param.ps.slat = latOrigin;\n            mp->param.ps.slon = lonPole;\n            mp->param.ps.is_north_pole = (mp->hem == 'N') ? 1 : 0;\n            mp->param.ps.false_easting = false_easting;\n            mp->param.ps.false_northing = false_northing;\n            check_projection_parameters(mp);\n            break;\n          case CT_LambertAzimEqualArea:\n            read_count = GTIFKeyGet (input_gtif, ProjFalseEastingGeoKey, &false_easting, 0, 1);\n            if (read_count != 1) {\n              asfPrintWarning(\n                      \"Unable to determine false easting from GeoTIFF file\\n\"\n                  \"using ProjFalseEastingGeoKey\\n\");\n            }\n            read_count = GTIFKeyGet (input_gtif, ProjFalseNorthingGeoKey, &false_northing, 0, 1);\n            if (read_count != 1) {\n              asfPrintWarning(\n                      \"Unable to determine false northing from GeoTIFF file\\n\"\n                  \"using ProjFalseNorthingGeoKey\\n\");\n            }\n            read_count = GTIFKeyGet (input_gtif, ProjCenterLongGeoKey, &lonOrigin, 0, 1);\n            if (read_count != 1) {\n              asfPrintWarning(\n                      \"Unable to determine center longitude from GeoTIFF file\\n\"\n                  \"using ProjCenterLongGeoKey\\n\");\n            }\n            read_count = GTIFKeyGet (input_gtif, ProjCenterLatGeoKey, &latOrigin, 0, 1);\n            if (read_count != 1) {\n              asfPrintWarning(\n                      \"Unable to determine center latitude from GeoTIFF file\\n\"\n                  \"using ProjCenterLatGeoKey\\n\");\n            }\n            mp->type = LAMBERT_AZIMUTHAL_EQUAL_AREA;\n            mp->hem = (latOrigin > 0) ? 'N' : 'S';\n            mp->param.lamaz.center_lon = lonOrigin;\n            mp->param.lamaz.center_lat = latOrigin;\n            mp->param.lamaz.false_easting = false_easting;\n            mp->param.lamaz.false_northing = false_northing;\n            check_projection_parameters(mp);\n            break;\n\t  case CT_Equirectangular:\n            read_count = GTIFKeyGet (input_gtif, ProjNatOriginLatGeoKey, &latOrigin, 0, 1);\n            if (read_count != 1) {\n              asfPrintWarning(\n                      \"Unable to determine center latitude from GeoTIFF file\\n\"\n                  \"using ProjNatOriginLatGeoKey\\n\");\n            }\n            read_count = GTIFKeyGet (input_gtif, ProjNatOriginLongGeoKey, &lonOrigin, 0, 1);\n            if (read_count != 1) {\n              asfPrintWarning(\n                      \"Unable to determine center longitude from GeoTIFF file\\n\"\n                  \"using ProjNatOriginLongGeoKey\\n\");\n            }\n            read_count = GTIFKeyGet (input_gtif, ProjFalseEastingGeoKey, &false_easting, 0, 1);\n            if (read_count != 1) {\n              asfPrintWarning(\n                      \"Unable to determine false easting from GeoTIFF file\\n\"\n                  \"using ProjFalseEastingGeoKey\\n\");\n            }\n            read_count = GTIFKeyGet (input_gtif, ProjFalseNorthingGeoKey, &false_northing, 0, 1);\n            if (read_count != 1) {\n              asfPrintWarning(\n                      \"Unable to determine false northing from GeoTIFF file\\n\"\n                  \"using ProjFalseNorthingGeoKey\\n\");\n            }\n            mp->type = EQUI_RECTANGULAR;\n            mp->hem = (latOrigin > 0.0) ? 'N' : 'S';\n            mp->param.eqr.orig_latitude = latOrigin;\n            mp->param.eqr.central_meridian = lonOrigin;\n            mp->param.eqr.false_easting = false_easting;\n            mp->param.eqr.false_northing = false_northing;\n            check_projection_parameters(mp);\n\t    break;\n\t  case CT_Mercator:\n            read_count = GTIFKeyGet (input_gtif, ProjNatOriginLatGeoKey, &latOrigin, 0, 1);\n            if (read_count != 1) {\n              asfPrintWarning(\n                      \"Unable to determine center latitude from GeoTIFF file\\n\"\n                  \"using ProjNatOriginLatGeoKey\\n\");\n            }\n            read_count = GTIFKeyGet (input_gtif, ProjNatOriginLongGeoKey, &lonOrigin, 0, 1);\n            if (read_count != 1) {\n              asfPrintWarning(\n                      \"Unable to determine center longitude from GeoTIFF file\\n\"\n                  \"using ProjNatOriginLongGeoKey\\n\");\n            }\n            read_count = GTIFKeyGet (input_gtif, ProjFalseEastingGeoKey, &false_easting, 0, 1);\n            if (read_count != 1) {\n              asfPrintWarning(\n                      \"Unable to determine false easting from GeoTIFF file\\n\"\n                  \"using ProjFalseEastingGeoKey\\n\");\n            }\n            read_count = GTIFKeyGet (input_gtif, ProjFalseNorthingGeoKey, &false_northing, 0, 1);\n            if (read_count != 1) {\n              asfPrintWarning(\n                      \"Unable to determine false northing from GeoTIFF file\\n\"\n                  \"using ProjFalseNorthingGeoKey\\n\");\n            }\n            // FIXME: convert scale factor into standard parallel\n            mp->type = MERCATOR;\n            mp->hem = (latOrigin > 0.0) ? 'N' : 'S';\n            mp->param.mer.orig_latitude = latOrigin;\n            mp->param.mer.central_meridian = lonOrigin;\n            mp->param.mer.false_easting = false_easting;\n            mp->param.mer.false_northing = false_northing;\n            check_projection_parameters(mp);\n\t    break;\n\t  case CT_Sinusoidal:\n            read_count = GTIFKeyGet (input_gtif, ProjCenterLongGeoKey, \n\t\t\t\t     &lonOrigin, 0, 1);\n            if (read_count != 1) {\n              asfPrintWarning(\"Unable to determine center longitude from \"\n\t\t\t      \"GeoTIFF file\\nusing ProjCenterLongGeoKey\\n\");\n            }\n            read_count = GTIFKeyGet (input_gtif, ProjFalseEastingGeoKey, \n\t\t\t\t     &false_easting, 0, 1);\n            if (read_count != 1) {\n              asfPrintWarning(\"Unable to determine false easting from GeoTIFF \"\n\t\t\t      \"file\\nusing ProjFalseEastingGeoKey\\n\");\n            }\n            read_count = GTIFKeyGet (input_gtif, ProjFalseNorthingGeoKey, \n\t\t\t\t     &false_northing, 0, 1);\n            if (read_count != 1) {\n              asfPrintWarning(\"Unable to determine false northing from GeoTIFF\"\n\t\t\t      \" file\\nusing ProjFalseNorthingGeoKey\\n\");\n            }\n\t    mp->type = SINUSOIDAL;\n\t    mp->hem = mg->center_latitude > 0.0 ? 'N' : 'S';\n\t    mp->param.sin.longitude_center = lonOrigin;\n\t    mp->param.sin.false_easting = false_easting;\n\t    mp->param.sin.false_northing = false_northing;\n\t    mp->param.sin.sphere = mp->re_major;\n            check_projection_parameters(mp);\n      \t    break;\n          default:\n            asfPrintWarning(\n                \"Unable to determine projection type from GeoTIFF file\\n\"\n                \"using ProjectedCSTypeGeoKey or ProjCoordTransGeoKey\\n\");\n            asfPrintWarning(\"Projection parameters missing in the GeoTIFF\\n\"\n                \"file.  Projection parameters may be incomplete unless\\n\"\n                \"they are found in the associated .aux file (if it exists.)\\n\");\n            break;\n        }\n      }\n    } // End of if UTM else OTHER projection type\n  } // End of reading projection parameters from geotiff ...if it existed\n  else if (model_type == ModelTypeGeographic && geotiff_data_exists) {\n    // Set the projection block data that we know at this point\n    if (tie_point[0] != 0 || tie_point[1] != 0 || tie_point[2] != 0) {\n      // NOTE: To support tie points at other locations, or a set of other locations,\n      // then things rapidly get more complex ...and a transformation must either be\n      // derived or provided (and utilized etc).  We're not at that point yet...\n      //\n      asfPrintError(\"Unsupported initial tie point type.  Initial tie point must be for\\n\"\n          \"raster location (0,0) in the image.\\n\");\n    }\n    short geographic_type;\n    read_count\n        = GTIFKeyGet (input_gtif, GeographicTypeGeoKey, &geographic_type, 0, 1);\n    asfRequire (read_count == 1, \"GTIFKeyGet failed.\\n\");\n    datum = UNKNOWN_DATUM;\n    switch ( geographic_type ) {\n      case GCS_WGS_84:\n        datum = WGS84_DATUM;\n        break;\n      case GCS_NAD27:\n        datum = NAD27_DATUM;\n        break;\n      case GCS_NAD83:\n        datum = NAD83_DATUM;\n        break;\n      default:\n        asfPrintError (\"Unsupported GeographicTypeGeoKey value in GeoTIFF file\");\n        break;\n    }\n    spheroid_type_t spheroid = datum_spheroid (datum);\n\n    // NOTE: For geographic geotiffs, all angular units are converted to decimal\n    // degrees upon ingest, hence the setting of mp->units to \"degrees\" here.\n    // the angular_units variable contains, at this point, the type of unit that is\n    // used within the geotiff itself, i.e. Angular_Arc_Second, Angular_Degree, etc.\n    strcpy (mp->units, \"degrees\");\n    mp->type = LAT_LONG_PSEUDO_PROJECTION;\n    mp->hem = mg->center_latitude > 0.0 ? 'N' : 'S';\n    mp->spheroid = spheroid;\n\n    // These fields should be the same as the ones in the general block.\n    mp->re_major = mg->re_major;\n    mp->re_minor = mg->re_minor;\n\n    mp->datum = datum;\n    mp->height = 0.0; // Set to the mean from the statistics later (for DEMs)\n  }\n  else if (!geotiff_data_exists) {\n    asfPrintWarning(\"Projection parameters missing in the GeoTIFF\\n\"\n                \"file.  Projection parameters may be incomplete unless.\\n\"\n                \"they are found in the associated .aux file (if it exists.)\\n\");\n  }\n\n  /*****************************************************/\n  /***** CHECK TO SEE IF THIS IS AN ARCGIS GEOTIFF *****/\n  /*                                                   */\n  if (model_type == ModelTypeProjected && isArcgisGeotiff(inFileName)) {\n    // If the TIFF is an ArcGIS / IMAGINE GeoTIFF, then read the\n    // projection parameters from the aux file (if it exists)\n    asfPrintStatus(\"Checking ArcGIS GeoTIFF auxiliary file (.aux) for\\n\"\n        \"projection parameters...\\n\");\n    int ret = readArcgisAuxProjectionParameters(inFileName, mp);\n    if (mp->datum != UNKNOWN_DATUM) {\n      datum = mp->datum;\n    }\n    if (ret == 0) {\n      asfPrintStatus(\"\\nSUCCESS ...Found projection parameters in the .aux file.\\n\"\n          \"(These will supercede any found in the TIFF - which should have been\\n\"\n          \" the same anyway.)\\n\\n\");\n    }\n  }\n  /*                                                   */\n  /*****************************************************/\n\n  asfPrintStatus(\"\\nLoading input TIFF/GeoTIFF file into %d-banded %s image structure...\\n\\n\",\n                 num_bands, (data_type == BYTE) ? \"8-bit byte\" :\n                            (data_type == INTEGER16) ? \"16-bit integer\" :\n                            (data_type == INTEGER32) ? \"32-bit integer\" :\n                            (data_type == REAL32)    ? \"32-bit float\"   : \"unknown(?)\");\n\n  // Get the raster width and height of the image.\n  uint32 width;\n  uint32 height;\n\n  TIFFGetField(input_tiff, TIFFTAG_IMAGELENGTH, &height);\n  TIFFGetField(input_tiff, TIFFTAG_IMAGEWIDTH, &width);\n  if (height <= 0 || width <= 0) {\n    asfPrintError(\"Invalid height and width parameters in TIFF file,\\n\"\n        \"Height = %ld, Width = %ld\\n\", height, width);\n  }\n\n  /***** FILL IN THE REST OF THE META DATA (Projection parms should already exist) *****/\n  /*                                                                                   */\n  char image_data_type[256];\n  mg->data_type = data_type;\n  int is_usgs_seamless_geotiff = 0;\n  if (angular_units == Angular_Degree &&\n      citation && strncmp(citation, \"IMAGINE GeoTIFF Support\", 23) == 0) {\n    // This is a good guess since the only source of lat/long geotiffs that I know of\n    // are the USGS Seamless Server geotiffs.  Note that the image_data_type setting\n    // will be overridden by the parameter list if the caller specified something.\n    //\n    // Note that even if this guess is wrong, it should still work fine for other\n    // angular degree geotiffs except that the image_data_type and sensor string may\n    // be misleading ...this won't affect processing by any of our tools.\n    asfPrintStatus(\"\\nGeoTIFF contains lat/long in decimal degrees.  Assuming this is a\\n\"\n            \"USGS Seamless Server (or compatible) type of DEM GeoTIFF with pixel\\n\"\n            \"size of 30, 60, 90, or 190 meters, i.e. SRTM, NED, DTED, etcetera...\\n\");\n    strcpy(mg->sensor, \"USGS Seamless data (e.g., NED, SRTM)\");\n    strcpy(image_data_type, \"DEM\");\n    mg->image_data_type = DEM;\n    is_usgs_seamless_geotiff = 1;\n  }\n  else if (angular_units == Angular_Degree ||\n           angular_units == Angular_Arc_Second)\n  {\n    // All other angular units\n      asfPrintStatus(\"\\nGeoTIFF contains lat/long in %s.  Assuming this is a\\n\"\n              \"USGS Seamless Server (or compatible) type of DEM GeoTIFF with pixel\\n\"\n              \"size of 30, 60, 90, 190 meters, i.e. SRTM, NED, DTED, etcetera...\\n\",\n              angular_units_to_string(angular_units));\n      strcpy(mg->sensor, \"USGS Seamless data (e.g., NED, SRTM)\");\n      is_usgs_seamless_geotiff = 1; // This will turn on conversion of pixel size from degrees to meters\n  }\n  else {\n      strcpy(mg->sensor, \"GEOTIFF\");\n      strcpy(mg->sensor_name, \"GEOTIFF\");\n  }\n  strcpy(mg->basename, inFileName);\n\n  // Get the image data type from the variable arguments list\n  char *pTmpChar=NULL;\n  va_start(ap, ignore); // 'ignore' is the last argument before \", ...\"\n  pTmpChar = (char *)va_arg(ap, char *);\n  if (pTmpChar != NULL &&\n      strlen(pTmpChar) >= 3 &&\n      (strncmp(uc(pTmpChar), \"DEM\", 3) == 0 ||\n       strncmp(uc(pTmpChar), \"MASK\", 4) == 0))\n  {\n    strcpy(image_data_type, uc(pTmpChar));\n  }\n  else {\n    if (is_usgs_seamless_geotiff) {\n      strcpy(image_data_type, \"DEM\");\n    }\n    else if (geotiff_data_exists) {\n      strcpy(image_data_type, \"GEOCODED_IMAGE\");\n    }\n    else {\n      strcpy(image_data_type, \"IMAGE\");\n    }\n  }\n  va_end(ap);\n  if (strncmp(image_data_type, \"DEM\", 3) == 0) {\n    mg->image_data_type = DEM;\n  }\n  else if (strncmp(image_data_type, \"MASK\", 4) == 0) {\n    mg->image_data_type = MASK;\n  }\n  else if (strncmp(image_data_type, \"AMPLITUDE_IMAGE\", 15) == 0) {\n    mg->image_data_type = AMPLITUDE_IMAGE;\n  }\n  else if (strncmp(image_data_type, \"GEOCODED_IMAGE\", 15) == 0) {\n    mg->image_data_type = GEOCODED_IMAGE;\n  }\n  else if (strncmp(image_data_type, \"IMAGE\", 5) == 0) {\n    mg->image_data_type = IMAGE;\n  }\n\n  mg->line_count = height;\n  mg->sample_count = width;\n\n  mg->start_line = 0;\n  mg->start_sample = 0;\n\n  float base_x_pixel_scale = pixel_scale[0];\n  float base_y_pixel_scale = pixel_scale[1];\n  if (is_usgs_seamless_geotiff) {\n    int x_pixel_size_meters = MAGIC_UNSET_INT;\n    int y_pixel_size_meters = MAGIC_UNSET_INT;\n    // Convert angular units to decimal degrees if necessary\n      switch(angular_units) {\n          case Angular_Arc_Second:\n              base_x_pixel_scale *= ARCSECONDS2DEGREES;\n              base_y_pixel_scale *= ARCSECONDS2DEGREES;\n              break;\n          case Angular_Degree:\n          default:\n              break;\n      }\n\n      // Convert decimal degrees to (approximate) pixel resolution in meters\n      // (per STRM & DTED standards)\n      //  30m = 1 arcsec = 0.0002777777 degrees,\n      //  60m = 2 arcsec = 0.0005555555 degrees,\n      //  90m = 3 arcsec = 0.0008333333 degrees,\n      // 180m = 6 arcsec = 0.0016666667 degrees,\n      if (FLOAT_COMPARE_TOLERANCE(base_x_pixel_scale, 0.0002777, 0.000001)) {\n          x_pixel_size_meters = 30.0;\n      }\n      else if (FLOAT_COMPARE_TOLERANCE(base_x_pixel_scale, 0.0005555, 0.000001)) {\n          x_pixel_size_meters = 60.0;\n      }\n      else if (FLOAT_COMPARE_TOLERANCE(base_x_pixel_scale, 0.0008333, 0.000001)) {\n          x_pixel_size_meters = 90.0;\n      }\n      else if (FLOAT_COMPARE_TOLERANCE(base_x_pixel_scale, 0.0016667, 0.000001)) {\n          x_pixel_size_meters = 180.0;\n      }\n      else {\n          // If not a standard size, then hack-calc it...\n          //\n          // We are supposed to put {x,y}_pixel_size in meters, so we need to convert\n          // the pixel scale in degrees to meters ...and we don't have platform position\n          // or height information!\n          //\n          // So, we are cheating a bit here, forcing the result to be to the nearest\n          // 10m.  This is ok since USGS DEMs are in 30, 60, or 90 meters.  And if this\n          // cheat is wrong ...it should still be ok since the one where accuracy is\n          // important is the value in the projection block, this one is used by geocode\n          // when deciding how large the pixels should be in the output.\n          x_pixel_size_meters = 10*(int)(11131.95 * pixel_scale[0] + .5);\n              // Sanity check on the pixel size cheat...\n          if (x_pixel_size_meters != 30 &&\n              x_pixel_size_meters != 60 &&\n              x_pixel_size_meters != 90 &&\n              x_pixel_size_meters != 180)\n          {\n              asfPrintWarning(\"Unexpected x pixel size: %dm.\\n\"\n                      \"USGS Seamless/NED/DTED data should be 30, 60, 90, or 180m\\n\", x_pixel_size_meters);\n          }\n      }\n      if (FLOAT_COMPARE_TOLERANCE(base_y_pixel_scale, 0.0002777, 0.000001)) {\n          y_pixel_size_meters = 30.0;\n      }\n      else if (FLOAT_COMPARE_TOLERANCE(base_y_pixel_scale, 0.0005555, 0.000001)) {\n          y_pixel_size_meters = 60.0;\n      }\n      else if (FLOAT_COMPARE_TOLERANCE(base_y_pixel_scale, 0.0008333, 0.000001)) {\n          y_pixel_size_meters = 90.0;\n      }\n      else if (FLOAT_COMPARE_TOLERANCE(base_y_pixel_scale, 0.0016667, 0.000001)) {\n          y_pixel_size_meters = 180.0;\n      }\n      else {\n          y_pixel_size_meters = 10*(int)(11131.95 * pixel_scale[1] + .5);\n          if (y_pixel_size_meters != 30 &&\n              y_pixel_size_meters != 60 &&\n              y_pixel_size_meters != 90 &&\n              y_pixel_size_meters != 180)\n          {\n              asfPrintWarning(\"Unexpected y pixel size: %dm.\\n\"\n                      \"USGS Seamless/NED/DTED data should be 30, 60, 90, or 180m\\n\", y_pixel_size_meters);\n          }\n      }\n\n      mg->x_pixel_size = x_pixel_size_meters;\n      mg->y_pixel_size = y_pixel_size_meters;\n  }\n  else if (linear_units == Linear_Foot ||\n\t   linear_units == Linear_Foot_US_Survey ||\n\t   linear_units == Linear_Foot_Modified_American ||\n\t   linear_units == Linear_Foot_Clarke ||\n\t   linear_units == Linear_Foot_Indian) {\n    // Hack: The exact number for unit 'ft' needs to be extracted from the file\n    base_x_pixel_scale *= 0.3048;\n    base_y_pixel_scale *= 0.3048;\n    mg->x_pixel_size = base_x_pixel_scale;\n    mg->y_pixel_size = base_y_pixel_scale;\n    asfPrintWarning(\"Units converted from feet to meters by adjusting the pixel size.\\n\"\n\t\t    \"Azimuth pixel size changed from %.3lf ft to %.3lf m.\\n\"\n\t\t    \"Range pixel size changed from %.3lf ft to %.3lf m.\\n\", \n\t\t    pixel_scale[0], base_x_pixel_scale, pixel_scale[1], base_y_pixel_scale);\n  }\n  else {\n      mg->x_pixel_size = pixel_scale[0];\n      mg->y_pixel_size = pixel_scale[1];\n  }\n\n  // For now we are going to insist that the meters per pixel in the\n  // X and Y directions are identical(ish).  I believe asf_geocode at\n  // least would work for non-square pixel dimensions, with the\n  // caveats that output pixels would still be square, and would have\n  // default size derived solely from the input pixel size\n  if (fabs(mg->x_pixel_size - mg->y_pixel_size) > 0.0001) {\n    char msg[256];\n    sprintf(msg, \"Pixel size is (x,y): (%lf, %lf)\\n\", mg->x_pixel_size, mg->y_pixel_size);\n    asfPrintStatus(msg);\n    asfPrintWarning(\"Found non-square pixels: x versus y pixel size differs\\n\"\n        \"by more than 0.0001 <units>\\n\");\n  }\n\n  // Image raster coordinates of tie point.\n  double raster_tp_x = tie_point[0];\n  double raster_tp_y = tie_point[1]; // Note: [2] is zero for 2D space\n\n  // Coordinates of tie point in projection space.\n  // NOTE: These are called tp_lon and tp_lat ...but the tie points\n  // will be in either linear units (meters typ.) *OR* lat/long depending\n  // on what type of image data is in the file, e.g. map-projected geographic or\n  // geocentric respectively (but we only support map-projected at this point.)\n  double tp_lon = tie_point[3]; // x\n  double tp_lat = tie_point[4]; // y, Note: [5] is zero for 2D space\n\n  // Calculate center of image data ...using linear meters or decimal degrees\n  double center_x = MAGIC_UNSET_DOUBLE;\n  double center_y = MAGIC_UNSET_DOUBLE;\n  if (linear_units == Linear_Meter ||\n      linear_units == Linear_Foot ||\n      linear_units == Linear_Foot_US_Survey ||\n      linear_units == Linear_Foot_Modified_American ||\n      linear_units == Linear_Foot_Clarke ||\n      linear_units == Linear_Foot_Indian) {\n      // NOTE: center_x and center_y are in meters (map projection coordinates)\n      // and are converted to lat/lon for center latitude/longitude below.  Therefore,\n      // since geographic geotiffs already contain angular measure, they don't need\n      // a center_x, center_y calculated.\n      // FIXME: Is tp_lon and tp_lat in degrees or meters for this case?\n      center_x = (width / 2.0 - raster_tp_x) * base_x_pixel_scale + tp_lon;\n      center_y = (height / 2.0 - raster_tp_y) * (-base_y_pixel_scale) + tp_lat;\n  }\n\n  // If the datum and/or spheroid are unknown at this point, then fill\n  // them out, and the major/minor axis, as best we can.\n  if (datum != UNKNOWN_DATUM && mp->spheroid == UNKNOWN_SPHEROID) {\n      // Guess the spheroid from the type of datum (a fairly safe guess)\n      mp->spheroid = datum_spheroid(mp->datum);\n  }\n  if (datum == UNKNOWN_DATUM && mp->spheroid != UNKNOWN_SPHEROID) {\n      // Can't guess a datum, so leave it be\n      datum = spheroid_datum(mp->spheroid);\n  }\n  if (datum == UNKNOWN_DATUM && mp->spheroid == UNKNOWN_SPHEROID && mp &&\n      mp->re_major != MAGIC_UNSET_DOUBLE && mp->re_minor != MAGIC_UNSET_DOUBLE)\n  {\n      // If neither the datum nor spheroid are known, try to derive them from\n      // the axis lengths in the map projection record\n      mp->spheroid = axis_to_spheroid(mp->re_major, mp->re_minor);\n      datum = spheroid_datum(mp->spheroid);\n  }\n  if (mp->spheroid != UNKNOWN_SPHEROID) {\n      spheroid_axes_lengths (mp->spheroid, &mg->re_major, &mg->re_minor);\n  }\n\n  if (isArcgisGeotiff(inFileName)        &&\n      mp->re_major != MAGIC_UNSET_DOUBLE &&\n      mp->re_minor != MAGIC_UNSET_DOUBLE)\n  {\n    // The ArcGIS metadata reader sets the projection parms, not the general\n    // block parms, so copy them over...\n    mg->re_major = mp->re_major;\n    mg->re_minor = mp->re_minor;\n  }\n\n  if (!isArcgisGeotiff(inFileName) &&\n      (mp->startX == MAGIC_UNSET_DOUBLE ||\n      mp->startY == MAGIC_UNSET_DOUBLE ||\n      mp->perX == MAGIC_UNSET_DOUBLE ||\n      mp->perY == MAGIC_UNSET_DOUBLE))\n  {\n    mp->startX = (0.0 - raster_tp_x) * mg->x_pixel_size + tp_lon;\n    mp->startY = (0.0 - raster_tp_y) * (-mg->y_pixel_size) + tp_lat;\n    mp->perX = mg->x_pixel_size;\n    mp->perY = -mg->y_pixel_size;\n  }\n  else if (is_usgs_seamless_geotiff) {\n      if (linear_units == Linear_Meter) {\n          // FIXME: Is tp_lon and tp_lat in degrees or meters for this case?\n          mp->startX = (0.0 - raster_tp_x) * base_x_pixel_scale + tp_lon;\n          mp->startY = (0.0 - raster_tp_y) * (-base_y_pixel_scale) + tp_lat;\n      }\n      else if (angular_units == Angular_Degree) {\n          mp->startX = (0.0 - raster_tp_x) * base_x_pixel_scale + tp_lon;\n          mp->startY = (0.0 - raster_tp_y) * (-base_y_pixel_scale) + tp_lat;\n      }\n      else if (angular_units == Angular_Arc_Second) {\n          mp->startX = (0.0 - raster_tp_x) * (base_x_pixel_scale * ARCSECONDS2DEGREES) + tp_lon;\n          mp->startY = (0.0 - raster_tp_y) * (-(base_y_pixel_scale * ARCSECONDS2DEGREES)) + tp_lat;\n      }\n      mp->perX = pixel_scale[0];\n      mp->perY = -pixel_scale[1];\n  }\n\n  // These fields should be the same as the ones in the general block.\n  mp->re_major = mg->re_major;\n  mp->re_minor = mg->re_minor;\n\n  // Fill out the number of bands and the band names\n  strcpy(mg->bands, \"\");\n  mg->band_count = num_bands;\n  int *empty = (int*)CALLOC(num_bands, sizeof(int)); // Defaults to 'no empty bands'\n  char *band_str;\n  band_str = (char*)MALLOC(100*sizeof(char)); // '100' is the array length of mg->bands (see asf_meta.h) ...yes, I know.\n  int num_found_bands;\n  char *tmp_citation = (citation != NULL) ? STRDUP(citation) : NULL;\n  int is_asf_geotiff = 0;\n  if (tmp_citation) is_asf_geotiff = strstr(tmp_citation, \"Alaska Satellite Fac\") ? 1 : 0;\n  get_bands_from_citation(&num_found_bands, &band_str, empty, tmp_citation, num_bands);\n  meta_statistics *stats = NULL;\n  double mask_value = MAGIC_UNSET_DOUBLE;\n  if (!is_asf_geotiff) {\n    asfPrintStatus(\"\\nNo ASF-exported band names found in GeoTIFF citation tag.\\n\"\n        \"Band names will be assigned in numerical order.\\n\");\n\n    // Look for a non-standard GDAL tag that contains the no data value\n    void *data;\n    uint16 *counter;\n    int ret = TIFFGetField(input_tiff, TIFFTAG_GDAL_NODATA, &counter, &data);\n    if (ret)\n      mg->no_data = atof((char *)data);\n    else\n      mg->no_data = MAGIC_UNSET_DOUBLE;\n  }\n  else {\n    // This is an ASF GeoTIFF so we must check to see if any bands are empty (blank)\n    // Since some blank-band GeoTIFFs exported by ASF tools do NOT have the list of\n    // bands placed in the citation string, we will need to make a best-guess based\n    // on band statistics... but only if the citation isn't cooperating.\n    if (num_found_bands < 1) {\n      asfPrintStatus(\"\\nGathering image statistics (per available band)...\\n\");\n      switch(meta_out->general->data_type) {\n        case BYTE:\n        case INTEGER16:\n        case INTEGER32:\n          mask_value = UINT8_IMAGE_DEFAULT_MASK;\n          break;\n        case REAL32:\n          mask_value = FLOAT_IMAGE_DEFAULT_MASK;\n          break;\n        default:\n          mask_value = 0.0;\n          break;\n      }\n      mg->no_data = mask_value;\n      // If there are no band names in the citation, then collect stats and check for empty\n      // bands that way\n      stats = meta_statistics_init(num_bands);\n      int is_dem = (mg->image_data_type == DEM) ? 1 : 0;\n      if(!stats) asfPrintError(\"Out of memory.  Cannot allocate statistics struct.\\n\");\n      int ii, nb;\n      for (ii=0, nb=num_bands; ii<num_bands; ii++) {\n        int ret;\n        ret = tiff_image_band_statistics(input_tiff, meta_out,\n                                      &stats->band_stats[ii], is_dem,\n                                      num_bands, ii,\n                                      bits_per_sample, sample_format,\n                                      planar_config, 0, mask_value);\n        if (ret != 0 ||\n            (stats->band_stats[ii].mean == stats->band_stats[ii].min &&\n             stats->band_stats[ii].mean == stats->band_stats[ii].max &&\n             stats->band_stats[ii].mean == stats->band_stats[ii].std_deviation)) {\n          // Band data is blank, e.g. no variation ...all pixels the same\n          asfPrintStatus(\"\\nFound empty band (see statistics below):\\n\"\n              \"   min = %f\\n\"\n              \"   max = %f\\n\"\n              \"  mean = %f\\n\"\n              \"  sdev = %f\\n\\n\",\n              stats->band_stats[ii].min,\n              stats->band_stats[ii].max,\n              stats->band_stats[ii].mean,\n              stats->band_stats[ii].std_deviation);\n          ignore[ii] = 1; // EMPTY BAND FOUND\n          nb--;\n        }\n        else {\n          ignore[ii] = 0;\n          asfPrintStatus(\"\\nBand Statistics:\\n\"\n              \"   min = %f\\n\"\n              \"   max = %f\\n\"\n              \"  mean = %f\\n\"\n              \"  sdev = %f\\n\\n\",\n            stats->band_stats[ii].min,\n            stats->band_stats[ii].max,\n            stats->band_stats[ii].mean,\n            stats->band_stats[ii].std_deviation);\n        }\n      }\n    }\n  }\n\n  if (is_usgs_seamless_geotiff) {\n    // USGS Seamless geotiffs are DEMs, which means they are one-banded and the mean\n    // data value is the average height in the image ...we need to calculate the stats\n    // in this case, so we can populate mp->mean properly.\n    // NOTE: Even though USGS DEMs are one-banded, this code is written generically for\n    // any number of bands in an arcsec or angular degrees lat/long geotiff\n    asfPrintStatus(\"\\nCalculating average height for USGS Seamless (SRTM, NED, etc) or DTED DEM...\\n\\n\");\n    stats = meta_statistics_init(num_bands);\n    int is_dem = (mg->image_data_type == DEM) ? 1 : 0;\n    if(!stats) asfPrintError(\"Out of memory.  Cannot allocate statistics struct.\\n\");\n    int ii, nb;\n    int ret = 0;\n    for (ii=0, nb=num_bands; ii<num_bands; ii++) {\n      ret = tiff_image_band_statistics(input_tiff, meta_out,\n                                       &stats->band_stats[ii], is_dem,\n                                       num_bands, ii,\n                                       bits_per_sample, sample_format,\n                                       planar_config, 0, mask_value);\n      asfPrintStatus(\"\\nBand Statistics:\\n\"\n                     \"   min = %f\\n\"\n                     \"   max = %f\\n\"\n                     \"  mean = %f\\n\"\n                     \"  sdev = %f\\n\\n\",\n                     stats->band_stats[ii].min,\n                     stats->band_stats[ii].max,\n                     stats->band_stats[ii].mean,\n                     stats->band_stats[ii].std_deviation);\n      // Empty band?\n      if (ret != 0) {\n          asfPrintWarning(\"USGS Seamless (NED, SRTM, etc) or DTED DEM band %d appears to have no data.\\n\"\n                  \"Setting the average height to 0.0m and continuing...\\n\", ii+1);\n          mp->height = 0.0;\n          ignore[ii] = 1;\n      }\n      else {\n          mp->height = stats->band_stats[0].mean;\n          ignore[ii] = 0;\n      }\n    }\n  }\n\n  if ( num_found_bands > 0 && strlen(band_str) > 0) {\n    // If a valid list of bands were in the citation string, then let the empty[] array,\n    // which indicates which bands in the TIFF were listed as 'empty' overrule the\n    // ignore[] array since it was just a best-guess based on band statistics\n    //\n    // Note:  The ignore[] array will be used when writing the binary file so that empty\n    // bands in the TIFF won't be written to the output file\n    int band_no, num_empty = 0;\n    for (band_no=0; band_no<num_bands; band_no++) {\n      ignore[band_no] = empty[band_no];\n      num_empty += ignore[band_no] ? 1 : 0;\n    }\n\n    // Note: mg->band_count is set to the number of found bands after the\n    // binary file is written ...if you do it before, then put_band_float_line()\n    // will fail.\n    strcpy(mg->bands, band_str);\n    mg->band_count -= num_empty;\n  }\n  else {\n    // Use the default band names if none were found in the citation string\n    // Note: For the case where there is no list of band names\n    // in the citation string, we are either importing somebody\n    // else's geotiff, or we are importing one of our older ones.\n    // The only way, in that case, to know if a band is empty is\n    // to rely on the band statistics from above.  The results\n    // of this analysis is stored in the 'ignore[<band_no>]' array.\n\n    // Note: num_bands is from the samples per pixel TIFF tag and is\n    // the maximum number of valid (non-ignored) bands in the file\n    int band_no, tmp_num_bands = num_bands;\n    for (band_no=0; band_no<tmp_num_bands; band_no++) {\n      if (ignore[band_no]) {\n        // Decrement the band count for each ignored band\n        num_bands--;\n      }\n      else {\n        // Band is not ignored, so give it a band name\n        if (band_no == 0) {\n          sprintf(mg->bands, \"%s\", bands[band_no]);\n        }\n        else {\n          sprintf(mg->bands, \"%s,%s\", mg->bands, bands[band_no]);\n        }\n      }\n    }\n    mg->band_count = num_bands;\n  }\n  FREE(band_str);\n  if (mg->band_count <= 0 || strlen(mg->bands) <= 0) {\n    asfPrintError(\"GeoTIFF file must contain at least one non-empty color channel (band)\\n\");\n  }\n\n  // Populate band stats if it makes sense\n  if (((is_asf_geotiff && num_found_bands < 1) || is_usgs_seamless_geotiff) && stats) {\n    // If this is an ASF GeoTIFF and no band names were found in the citation string,\n    // then we HAD to have tried to identify blank bands with statistics ...if so, then\n    // we may as well save the stats results in the metadata so some other processing\n    // step can use them if it needs them (without having to recalculate them)\n    //\n    char **band_names=NULL;\n    if (strlen(mg->bands) && strncmp(mg->bands, MAGIC_UNSET_STRING, strlen(MAGIC_UNSET_STRING)) != 0) {\n      band_names = extract_band_names(mg->bands, mg->band_count);\n    }\n    int bn;\n    meta_out->stats = meta_statistics_init(num_bands);\n    meta_statistics *mst = meta_out->stats;\n    if (mst) {\n      int ii;\n      for (ii=0, bn=0; ii<num_bands; ii++) {\n        if (!ignore[ii]) {\n          if (band_names && band_names[bn] != NULL) {\n            strcpy(mst->band_stats[bn].band_id, band_names[bn]);\n          }\n          else {\n            sprintf(mst->band_stats[bn].band_id, \"%02d\", bn + 1);\n          }\n          mst->band_stats[bn].min = stats->band_stats[ii].min;\n          mst->band_stats[bn].max = stats->band_stats[ii].max;\n          mst->band_stats[bn].mean = stats->band_stats[ii].mean;\n          mst->band_stats[bn].rmse = meta_is_valid_double(stats->band_stats[ii].rmse) ?\n              stats->band_stats[ii].rmse : stats->band_stats[ii].std_deviation;\n          mst->band_stats[bn].std_deviation = stats->band_stats[ii].std_deviation;\n          mst->band_stats[bn].mask = mask_value;\n          bn++;\n        }\n      }\n    }\n    else asfPrintError(\"Out of memory.  Cannot allocate statistics struct.\\n\");\n  }\n\n  // Calculate the center latitude and longitude now that the projection\n  // parameters are stored.\n  double center_latitude;\n  double center_longitude;\n  double dummy_var;\n  meta_projection proj;\n\n  // Copy all fields just in case of future code rearrangements...\n  if (!is_usgs_seamless_geotiff) {\n    copy_proj_parms (&proj, mp);\n    proj_to_latlon(&proj,center_x, center_y, 0.0,\n      &center_latitude, &center_longitude, &dummy_var);\n    mg->center_latitude = R2D*center_latitude;\n    mg->center_longitude = R2D*center_longitude;\n  }\n  else {\n    mg->center_latitude = (height / 2.0 - raster_tp_y) * mp->perY + tp_lat;\n    mg->center_longitude = (width / 2.0 - raster_tp_x) * mp->perX + tp_lon;\n    mp->hem = (mg->center_latitude > 0.0) ? 'N' : 'S';\n  }\n\n  // Set up the location block\n  if (is_usgs_seamless_geotiff) {\n    ml->lon_start_near_range = mp->startX;\n    ml->lat_start_near_range = mp->startY;\n    ml->lon_start_far_range = mp->startX + mp->perX * width;\n    ml->lat_start_far_range = mp->startY;\n    ml->lon_end_near_range = mp->startX;\n    ml->lat_end_near_range = mp->startY + mp->perY * height;\n    ml->lon_end_far_range = mp->startX + mp->perX * width;\n    ml->lat_end_far_range = mp->startY + mp->perY * height;\n  }\n  else {\n    double lat, lon;\n    proj_to_latlon(&proj, mp->startX, mp->startY, 0.0,\n                  &lat, &lon, &dummy_var);\n    ml->lat_start_near_range = R2D*lat;\n    ml->lon_start_near_range = R2D*lon;\n\n    proj_to_latlon(&proj, mp->startX + mp->perX * width, mp->startY, 0.0,\n                  &lat, &lon, &dummy_var);\n    ml->lat_start_far_range = R2D*lat;\n    ml->lon_start_far_range = R2D*lon;\n\n    proj_to_latlon(&proj, mp->startX, mp->startY + mp->perY * height, 0.0,\n                  &lat, &lon, &dummy_var);\n    ml->lat_end_near_range = R2D*lat;\n    ml->lon_end_near_range = R2D*lon;\n\n    proj_to_latlon(&proj, mp->startX + mp->perX * width, mp->startY + mp->perY * height, 0.0,\n                  &lat, &lon, &dummy_var);\n    ml->lat_end_far_range = R2D*lat;\n    ml->lon_end_far_range = R2D*lon;\n  }\n\n  // Clean up\n  GTIFFree(input_gtif);\n  XTIFFClose(input_tiff);\n  if(stats)FREE(stats);\n  FREE (tmp_citation);\n  FREE (citation);\n    FREE (tie_point);\n    FREE (pixel_scale);\n  for (band_num = 0; band_num < MAX_BANDS; band_num++) {\n    FREE(bands[band_num]);\n  }\n\n  return meta_out;\n}\n\n// Checking routine for projection parameter input.\nvoid check_projection_parameters(meta_projection *mp)\n{\n  project_parameters_t *pp = &mp->param;\n\n// FIXME: Hughes datum stuff commented out for now ...until Hughes is implemented in the trunk\n   if (mp->datum == HUGHES_DATUM && mp->type != POLAR_STEREOGRAPHIC) {\n     asfPrintError(\"Hughes ellipsoid is only supported for polar stereographic projections.\\n\");\n   }\n\n  switch (mp->type) {\n    case UNIVERSAL_TRANSVERSE_MERCATOR:\n      // Tests for outside of allowed ranges errors:\n      //\n      // Valid UTM projections:\n      //\n      //   WGS84 + zone 1 thru 60 + N or S hemisphere\n      //   NAD83 + zone 2 thru 23 + N hemisphere\n      //   NAD27 + zone 2 thru 22 + N hemisphere\n      //\n      if (!meta_is_valid_int(pp->utm.zone)) {\n        asfPrintError(\"Invalid zone number found (%d).\\n\", pp->utm.zone);\n      }\n      if (!meta_is_valid_double(pp->utm.lat0) || pp->utm.lat0 != 0.0) {\n        asfPrintWarning(\"Invalid Latitude of Origin found (%.4f).\\n\"\n            \"Setting Latitude of Origin to 0.0\\n\", pp->utm.lat0);\n        pp->utm.lat0 = 0.0;\n      }\n      if (pp->utm.lon0 != utm_zone_to_central_meridian(pp->utm.zone)) {\n        asfPrintWarning(\"Invalid Longitude of Origin (%.4f) found\\n\"\n            \"for the given zone (%d).\\n\"\n            \"Setting Longitude of Origin to %f for zone %d\\n\",\n            utm_zone_to_central_meridian(pp->utm.zone),\n            pp->utm.zone);\n        pp->utm.lon0 = utm_zone_to_central_meridian(pp->utm.zone);\n      }\n      switch(mp->datum) {\n        case NAD27_DATUM:\n          if (pp->utm.zone < 2 || pp->utm.zone > 22) {\n            asfPrintError(\"Zone '%d' outside the supported range (2 to 22) for NAD27...\\n\"\n                \"  WGS 84, Zone 1 thru 60, Latitudes between -90 and +90\\n\"\n                \"  NAD83,  Zone 2 thru 23, Latitudes between   0 and +90\\n\"\n                \"  NAD27,  Zone 2 thru 22, Latitudes between   0 and +90\\n\\n\",\n                pp->utm.zone);\n          }\n          break;\n        case NAD83_DATUM:\n          if (pp->utm.zone < 2 || pp->utm.zone > 23) {\n            asfPrintError(\"Zone '%d' outside the supported range (2 to 23) for NAD83...\\n\"\n                \"  WGS 84, Zone 1 thru 60, Latitudes between -90 and +90\\n\"\n                \"  NAD83,  Zone 2 thru 23, Latitudes between   0 and +90\\n\"\n                \"  NAD27,  Zone 2 thru 22, Latitudes between   0 and +90\\n\\n\",\n                pp->utm.zone);\n          }\n          break;\n        case WGS84_DATUM:\n          if (pp->utm.zone < 1 || pp->utm.zone > 60) {\n            asfPrintError(\"Zone '%d' outside the valid range of (1 to 60) for WGS-84\\n\", pp->utm.zone);\n          }\n          break;\n        case ITRF97_DATUM:\n          if (pp->utm.zone < 1 || pp->utm.zone > 60) {\n            asfPrintError(\"Zone '%d' outside the valid range of (1 to 60) for ITRF-97\\n\", pp->utm.zone);\n          }\n          break;\n        default:\n          asfPrintError(\"Unrecognized or unsupported datum found in projection parameters.\\n\");\n          break;\n      }\n      if (!meta_is_valid_double(pp->utm.lon0) || pp->utm.lon0 < -180 || pp->utm.lon0 > 180) {\n        asfPrintError(\"Longitude of Origin (%.4f) undefined or outside the defined range \"\n            \"(-180 deg to 180 deg)\\n\", pp->utm.lon0);\n      }\n      if (!meta_is_valid_double(pp->utm.lat0) || pp->utm.lat0 != 0.0) {\n        asfPrintError(\"Latitude of Origin (%.4f) undefined or invalid (should be 0.0)\\n\",\n            pp->utm.lat0);\n      }\n      if (!meta_is_valid_double(pp->utm.scale_factor) || !FLOAT_EQUIVALENT(pp->utm.scale_factor, 0.9996)) {\n        asfPrintError(\"Scale factor (%.4f) undefined or different from default value (0.9996)\\n\",\n                    pp->utm.scale_factor);\n      }\n      if (!meta_is_valid_double(pp->utm.false_easting) || !FLOAT_EQUIVALENT(pp->utm.false_easting, 500000)) {\n        asfPrintError(\"False easting (%.1f) undefined or different from default value (500000)\\n\",\n                    pp->utm.false_easting);\n      }\n      if (mp->hem == 'N') {\n        if (!meta_is_valid_double(pp->utm.false_northing) || !FLOAT_EQUIVALENT(pp->utm.false_northing, 0)) {\n          asfPrintError(\"False northing (%.1f) undefined or different from default value (0)\\n\",\n                      pp->utm.false_northing);\n        }\n      }\n      else {\n        if (!meta_is_valid_double(pp->utm.false_northing) || !FLOAT_EQUIVALENT(pp->utm.false_northing, 10000000)) {\n          asfPrintError(\"False northing (%.1f) undefined or different from default value (10000000)\\n\",\n                        pp->utm.false_northing);\n        }\n      }\n      break;\n\n    case POLAR_STEREOGRAPHIC:\n      // Outside range tests\n      if (!meta_is_valid_double(pp->ps.slat) || pp->ps.slat < -90 || pp->ps.slat > 90) {\n        asfPrintError(\"Latitude of origin (%.4f) undefined or outside the defined range \"\n            \"(-90 deg to 90 deg)\\n\", pp->ps.slat);\n      }\n      if (!meta_is_valid_double(pp->ps.slon) || pp->ps.slon < -180 || pp->ps.slon > 180) {\n        asfPrintError(\"Central meridian (%.4f) undefined or outside the defined range \"\n            \"(-180 deg to 180 deg)\\n\", pp->ps.slon);\n      }\n\n      // Distortion test - only areas with a latitude above 60 degrees North or\n      // below -60 degrees South are permitted\n      if (!meta_is_valid_int(pp->ps.is_north_pole) ||\n           (pp->ps.is_north_pole != 0 && pp->ps.is_north_pole != 1)) {\n        asfPrintError(\"Invalid north pole flag (%s) found.\\n\",\n                    pp->ps.is_north_pole == 0 ? \"SOUTH\" :\n                        pp->ps.is_north_pole == 1 ? \"NORTH\" : \"UNKNOWN\");\n      }\n      break;\n\n    case ALBERS_EQUAL_AREA:\n      // Outside range tests\n      if (!meta_is_valid_double(pp->albers.std_parallel1) ||\n           pp->albers.std_parallel1 < -90 ||\n           pp->albers.std_parallel1 > 90) {\n        asfPrintError(\"First standard parallel (%.4f) undefined or outside the defined range \"\n            \"(-90 deg to 90 deg)\\n\", pp->albers.std_parallel1);\n      }\n      if (!meta_is_valid_double(pp->albers.std_parallel2) ||\n           pp->albers.std_parallel2 < -90 ||\n           pp->albers.std_parallel2 > 90) {\n        asfPrintError(\"Second standard parallel (%.4f) undefined or outside the defined range \"\n            \"(-90 deg to 90 deg)\\n\", pp->albers.std_parallel2);\n      }\n      if (!meta_is_valid_double(pp->albers.center_meridian) ||\n           pp->albers.center_meridian < -180 ||\n           pp->albers.center_meridian > 180) {\n        asfPrintError(\"Central meridian (%.4f) undefined or outside the defined range \"\n            \"(-180 deg to 180 deg)\\n\", pp->albers.center_meridian);\n      }\n      if (!meta_is_valid_double(pp->albers.orig_latitude) ||\n           pp->albers.orig_latitude < -90 ||\n           pp->albers.orig_latitude > 90) {\n        asfPrintError(\"Latitude of origin (%.4f) undefined or outside the defined range \"\n            \"(-90 deg to 90 deg)\\n\", pp->albers.orig_latitude);\n      }\n      break;\n\n    case LAMBERT_CONFORMAL_CONIC:\n      // Outside range tests\n      if (!meta_is_valid_double(pp->lamcc.plat1) ||\n           pp->lamcc.plat1 < -90 || pp->lamcc.plat1 > 90) {\n        asfPrintError(\"First standard parallel (%.4f) undefined or outside the defined range \"\n            \"(-90 deg to 90 deg)\\n\", pp->lamcc.plat1);\n      }\n      if (!meta_is_valid_double(pp->lamcc.plat2) ||\n           pp->lamcc.plat2 < -90 || pp->lamcc.plat2 > 90) {\n        asfPrintError(\"Second standard parallel '%.4f' outside the defined range \"\n            \"(-90 deg to 90 deg)\\n\", pp->lamcc.plat2);\n      }\n      if (!meta_is_valid_double(pp->lamcc.lon0) ||\n           pp->lamcc.lon0 < -180 || pp->lamcc.lon0 > 180) {\n        asfPrintError(\"Central meridian '%.4f' outside the defined range \"\n            \"(-180 deg to 180 deg)\\n\", pp->lamcc.lon0);\n      }\n      if (!meta_is_valid_double(pp->lamcc.lat0) ||\n           pp->lamcc.lat0 < -90 || pp->lamcc.lat0 > 90) {\n        asfPrintError(\"Latitude of origin '%.4f' outside the defined range \"\n            \"(-90 deg to 90 deg)\\n\", pp->lamcc.lat0);\n      }\n      break;\n    case LAMBERT_AZIMUTHAL_EQUAL_AREA:\n      // Outside range tests\n      if (!meta_is_valid_double(pp->lamaz.center_lon) ||\n           pp->lamaz.center_lon < -180 || pp->lamaz.center_lon > 180) {\n        asfPrintError(\"Central meridian '%.4f' outside the defined range \"\n            \"(-180 deg to 180 deg)\\n\", pp->lamaz.center_lon);\n      }\n      if (!meta_is_valid_double(pp->lamaz.center_lat) ||\n           pp->lamaz.center_lat < -90 || pp->lamaz.center_lat > 90) {\n        asfPrintError(\"Latitude of origin '%.4f' outside the defined range \"\n            \"(-90 deg to 90 deg)\\n\", pp->lamaz.center_lat);\n      }\n      break;\n    case SINUSOIDAL:\n      if (!meta_is_valid_double(pp->sin.longitude_center) ||\n\t  pp->sin.longitude_center < -180 || \n\t  pp->sin.longitude_center > 180) {\n\tasfPrintError(\"Longitude center '%.4f' outside the defined range \"\n\t\t      \"(-180 deg to 180 deg)\\n\", pp->lamaz.center_lon);\n      }\n      break;      \n      \n    default:\n      break;\n  }\n}\n\nint  band_float_image_write(FloatImage *oim, meta_parameters *omd,\n                            const char *outBaseName, int num_bands,\n                            int *ignore)\n{\n  char *outName;\n  int row, col, band, offset;\n  float *buf;\n\n  buf = (float*)MALLOC(sizeof(float)*omd->general->sample_count);\n  outName = (char*)MALLOC(sizeof(char)*strlen(outBaseName) + 5);\n  strcpy(outName, outBaseName);\n  append_ext_if_needed(outName, \".img\", \".img\");\n  offset = omd->general->line_count;\n\n  for (band=0; band < num_bands; band++) {\n    if (num_bands > 1) {\n      asfPrintStatus(\"Writing band %02d...\\n\", band+1);\n    }\n    else\n    {\n      asfPrintStatus(\"Writing binary image...\\n\");\n    }\n    FILE *fp=(FILE*)FOPEN(outName, band > 0 ? \"ab\" : \"wb\");\n    if (fp == NULL) return 1;\n    if (!ignore[band]) {\n      for (row=0; row < omd->general->line_count; row++) {\n        asfLineMeter(row, omd->general->line_count);\n        for (col=0; col < omd->general->sample_count; col++) {\n          buf[col] = float_image_get_pixel(oim, col, row+(offset*band));\n        }\n        put_float_line(fp, omd, row, buf);\n      }\n    }\n    else {\n      asfPrintStatus(\"  Empty band found ...ignored\\n\");\n    }\n    FCLOSE(fp);\n  }\n  FREE(buf);\n  FREE(outName);\n\n  return 0;\n}\n\nint  band_byte_image_write(UInt8Image *oim_b, meta_parameters *omd,\n                           const char *outBaseName, int num_bands,\n                           int *ignore)\n{\n  char *outName;\n  int row, col, band, offset;\n  float *buf;\n\n  buf = (float*)MALLOC(sizeof(float)*omd->general->sample_count);\n  outName = (char*)MALLOC(sizeof(char)*strlen(outBaseName) + 5);\n  strcpy(outName, outBaseName);\n  append_ext_if_needed(outName, \".img\", \".img\");\n  offset = omd->general->line_count;\n\n  for (band=0; band < num_bands; band++) {\n    if (num_bands > 1) {\n      asfPrintStatus(\"Writing band %02d...\\n\", band+1);\n    }\n    else\n    {\n      asfPrintStatus(\"Writing binary image...\\n\");\n    }\n    FILE *fp=(FILE*)FOPEN(outName, band > 0 ? \"ab\" : \"wb\");\n    if (fp == NULL) return 1;\n    if (!ignore[band]) {\n      for (row=0; row < omd->general->line_count; row++) {\n        asfLineMeter(row, omd->general->line_count);\n        for (col=0; col < omd->general->sample_count; col++) {\n          int curr_row = row+(offset*band);\n          buf[col] = (float)uint8_image_get_pixel(oim_b, col, curr_row); //row+(offset*band));\n        }\n        put_float_line(fp, omd, row, buf);\n      }\n    }\n    else {\n      asfPrintStatus(\"  Empty band found ...ignored\\n\");\n    }\n    FCLOSE(fp);\n  }\n  FREE(buf);\n  FREE(outName);\n\n  return 0;\n}\n\nint tiff_image_band_statistics (TIFF *tif, meta_parameters *omd,\n                                meta_stats *stats, int is_dem,\n                                int num_bands, int band_no,\n                                short bits_per_sample, short sample_format,\n                                short planar_config,\n                                int use_mask_value, double mask_value)\n{\n  tiff_type_t tiffInfo;\n\n  // Determine what type of TIFF this is (scanline/strip/tiled)\n  get_tiff_type(tif, &tiffInfo);\n  if (tiffInfo.imageCount > 1) {\n    asfPrintWarning(\"Found multi-image TIFF file.  Statistics will only be\\n\"\n        \"calculated from the bands in the first image in the file\\n\");\n  }\n  if (tiffInfo.imageCount < 1) {\n    asfPrintError (\"TIFF file contains zero images\\n\");\n  }\n  if (tiffInfo.format != SCANLINE_TIFF &&\n      tiffInfo.format != STRIP_TIFF    &&\n      tiffInfo.format != TILED_TIFF)\n  {\n    asfPrintError(\"Unrecognized TIFF type\\n\");\n  }\n  if (tiffInfo.volume_tiff) {\n    asfPrintError(\"Multi-dimensional TIFF found ...only 2D TIFFs are supported.\\n\");\n  }\n\n  // Minimum and maximum sample values as integers.\n  double fmin = FLT_MAX;\n  double fmax = -FLT_MAX;\n  double cs=0.0; // Current sample value\n\n  stats->mean = 0.0;\n  double s = 0.0;\n  uint32 scanlineSize = 0;\n  uint32 sample_count = 0;      // Samples considered so far.\n  uint32 ii, jj;\n  scanlineSize = TIFFScanlineSize(tif);\n  if (scanlineSize <= 0) {\n    return 1;\n  }\n  if (num_bands > 1 &&\n      planar_config != PLANARCONFIG_CONTIG &&\n      planar_config != PLANARCONFIG_SEPARATE)\n  {\n    return 1;\n  }\n  tdata_t *buf = _TIFFmalloc(scanlineSize);\n\n  // If there is a mask value we are supposed to ignore,\n  if ( use_mask_value ) {\n    // iterate over all rows in the TIFF\n    for ( ii = 0; ii < omd->general->line_count; ii++ )\n    {\n      asfPercentMeter((double)ii/(double)omd->general->line_count);\n      // Get a data line from the TIFF\n      switch (tiffInfo.format) {\n        case SCANLINE_TIFF:\n          if (planar_config == PLANARCONFIG_CONTIG || num_bands == 1) {\n            TIFFReadScanline(tif, buf, ii, 0);\n          }\n          else {\n            // Planar configuration is band-sequential\n            TIFFReadScanline(tif, buf, ii, band_no);\n          }\n          break;\n        case STRIP_TIFF:\n          ReadScanline_from_TIFF_Strip(tif, buf, ii, band_no);\n          break;\n        case TILED_TIFF:\n//          if (planar_config == PLANARCONFIG_CONTIG || num_bands == 1) {\n//            ReadScanline_from_TIFF_TileRow(tif, buf, ii, 0);\n//          }\n//          else {\n            // Planar configuration is band-sequential\n          ReadScanline_from_TIFF_TileRow(tif, buf, ii, band_no);\n//          }\n          break;\n        default:\n          asfPrintError(\"Invalid TIFF format found.\\n\");\n          break;\n      }\n      for (jj = 0 ; jj < omd->general->sample_count; jj++ ) {\n        // iterate over each pixel sample in the scanline\n        switch(bits_per_sample) {\n          case 8:\n            switch(sample_format) {\n              case SAMPLEFORMAT_UINT:\n                if (planar_config == PLANARCONFIG_CONTIG && num_bands > 1) {\n                  cs = (double)(((uint8*)(buf))[(jj*num_bands)+band_no]);   // Current sample.\n                }\n                else {\n                  // Planar configuration is band-sequential or single-banded\n                  cs = (double)(((uint8*)(buf))[jj]);\n                }\n                break;\n              case SAMPLEFORMAT_INT:\n                if (planar_config == PLANARCONFIG_CONTIG && num_bands > 1) {\n                  cs = (double)(((int8*)(buf))[(jj*num_bands)+band_no]);   // Current sample.\n                }\n                else {\n                  // Planar configuration is band-sequential or single-banded\n                  cs = (double)(((int8*)(buf))[jj]);   // Current sample.\n                }\n                break;\n              default:\n                // There is no such thing as an IEEE 8-bit floating point\n                asfPrintError(\"Unexpected data type in GeoTIFF ...Cannot calculate statistics.\\n\");\n                return 1;\n                break;\n            }\n            if ( !isnan(mask_value) && (gsl_fcmp (cs, mask_value, 0.00000000001) == 0 ) ) {\n              continue;\n            }\n            break;\n          case 16:\n            switch(sample_format) {\n              case SAMPLEFORMAT_UINT:\n                if (planar_config == PLANARCONFIG_CONTIG && num_bands > 1) {\n                  cs = (double)(((uint16*)(buf))[(jj*num_bands)+band_no]);   // Current sample.\n                }\n                else {\n                  // Planar configuration is band-sequential or single-banded\n                  cs = (double)(((uint16*)(buf))[jj]);   // Current sample.\n                }\n                break;\n              case SAMPLEFORMAT_INT:\n                if (planar_config == PLANARCONFIG_CONTIG && num_bands > 1) {\n                  cs = (double)(((int16*)(buf))[(jj*num_bands)+band_no]);   // Current sample.\n                }\n                else {\n                  // Planar configuration is band-sequential or single-banded\n                  cs = (double)(((uint16*)(buf))[jj]);   // Current sample.\n                }\n                break;\n              default:\n                // There is no such thing as an IEEE 16-bit floating point\n                asfPrintError(\"Unexpected data type in TIFF/GeoTIFF ...Cannot calculate statistics.\\n\");\n                return 1;\n                break;\n            }\n            if ( !isnan(mask_value) && (gsl_fcmp (cs, mask_value, 0.00000000001) == 0 ) ) {\n              continue;\n            }\n            break;\n          case 32:\n            switch(sample_format) {\n              case SAMPLEFORMAT_UINT:\n                if (planar_config == PLANARCONFIG_CONTIG && num_bands > 1) {\n                  cs = (double)(((uint32*)(buf))[(jj*num_bands)+band_no]);   // Current sample.\n                }\n                else {\n                  // Planar configuration is band-sequential or single-banded\n                  cs = (double)(((uint32*)(buf))[jj]);   // Current sample.\n                }\n                break;\n              case SAMPLEFORMAT_INT:\n                if (planar_config == PLANARCONFIG_CONTIG && num_bands > 1) {\n                  cs = (double)(((long*)(buf))[(jj*num_bands)+band_no]);   // Current sample.\n                }\n                else {\n                  // Planar configuration is band-sequential or single-banded\n                  cs = (double)(((long*)(buf))[jj]);   // Current sample.\n                }\n                break;\n              case SAMPLEFORMAT_IEEEFP:\n                if (planar_config == PLANARCONFIG_CONTIG && num_bands > 1) {\n                  cs = (double)(((float*)(buf))[(jj*num_bands)+band_no]);   // Current sample.\n                }\n                else {\n                  // Planar configuration is band-sequential or single-banded\n                  cs = (double)(((float*)(buf))[jj]);   // Current sample.\n                }\n                if (is_dem && cs < -10e10) {\n                  // Bad value removal for DEMs (really an adjustment, not a removal)\n                  // -> This only applies to USGS Seamless DEMs and REAL32 data type <-\n                  cs = -999.0;\n                }\n                break;\n              default:\n                asfPrintError(\"Unexpected data type in GeoTIFF ...Cannot calculate statistics.\\n\");\n                return 1;\n                break;\n            }\n            if ( !isnan(mask_value) && (gsl_fcmp (cs, mask_value, 0.00000000001) == 0 ) ) {\n              continue;\n            }\n            break;\n        }\n        if ( G_UNLIKELY (cs < fmin) ) { fmin = cs; }\n        if ( G_UNLIKELY (cs > fmax) ) { fmax = cs; }\n        double old_mean = stats->mean;\n        stats->mean += (cs - stats->mean) / (sample_count + 1);\n        s += (cs - old_mean) * (cs - stats->mean);\n        sample_count++;\n      }\n    }\n    asfPercentMeter(1.0);\n  }\n  else {\n    // There is no mask value to ignore, so we do the same as the\n    // above loop, but without the possible continue statement.\n    for ( ii = 0; ii < omd->general->line_count; ii++ )\n    {\n      asfPercentMeter((double)ii/(double)omd->general->line_count);\n      // Get a data line from the TIFF\n      switch (tiffInfo.format) {\n        case SCANLINE_TIFF:\n          if (planar_config == PLANARCONFIG_CONTIG || num_bands == 1) {\n            TIFFReadScanline(tif, buf, ii, 0);\n          }\n          else {\n            // Planar configuration is band-sequential\n            TIFFReadScanline(tif, buf, ii, band_no);\n          }\n          break;\n        case STRIP_TIFF:\n          ReadScanline_from_TIFF_Strip(tif, buf, ii, band_no);\n          break;\n        case TILED_TIFF:\n            // Planar configuration is band-sequential\n          ReadScanline_from_TIFF_TileRow(tif, buf, ii, band_no);\n          break;\n        default:\n          asfPrintError(\"Invalid TIFF format found.\\n\");\n          break;\n      }\n      for (jj = 0 ; jj < omd->general->sample_count; jj++ ) {\n        // iterate over each pixel sample in the scanline\n        switch(bits_per_sample) {\n          case 8:\n            switch(sample_format) {\n              case SAMPLEFORMAT_UINT:\n                if (planar_config == PLANARCONFIG_CONTIG && num_bands > 1) {\n                  cs = (double)(((uint8*)(buf))[(jj*num_bands)+band_no]);   // Current sample.\n                }\n                else {\n                  // Planar configuration is band-sequential or single-banded\n                  cs = (double)(((uint8*)(buf))[jj]);\n                }\n                break;\n              case SAMPLEFORMAT_INT:\n                if (planar_config == PLANARCONFIG_CONTIG && num_bands > 1) {\n                  cs = (double)(((int8*)(buf))[(jj*num_bands)+band_no]);   // Current sample.\n                }\n                else {\n                  // Planar configuration is band-sequential or single-banded\n                  cs = (double)(((int8*)(buf))[jj]);   // Current sample.\n                }\n                break;\n              default:\n                // There is no such thing as an IEEE 8-bit floating point\n                asfPrintError(\"Unexpected data type in GeoTIFF ...Cannot calculate statistics.\\n\");\n                return 1;\n                break;\n            }\n            break;\n          case 16:\n            switch(sample_format) {\n              case SAMPLEFORMAT_UINT:\n                if (planar_config == PLANARCONFIG_CONTIG && num_bands > 1) {\n                  cs = (double)(((uint16*)(buf))[(jj*num_bands)+band_no]);   // Current sample.\n                }\n                else {\n                  // Planar configuration is band-sequential or single-banded\n                  cs = (double)(((uint16*)(buf))[jj]);   // Current sample.\n                }\n                break;\n              case SAMPLEFORMAT_INT:\n                if (planar_config == PLANARCONFIG_CONTIG && num_bands > 1) {\n                  cs = (double)(((int16*)(buf))[(jj*num_bands)+band_no]);   // Current sample.\n                }\n                else {\n                  // Planar configuration is band-sequential or single-banded\n                  cs = (double)(((uint16*)(buf))[jj]);   // Current sample.\n                }\n                break;\n              default:\n                // There is no such thing as an IEEE 16-bit floating point\n                asfPrintError(\"Unexpected data type in GeoTIFF ...Cannot calculate statistics.\\n\");\n                return 1;\n                break;\n            }\n            break;\n          case 32:\n            switch(sample_format) {\n              case SAMPLEFORMAT_UINT:\n                if (planar_config == PLANARCONFIG_CONTIG && num_bands > 1) {\n                  cs = (double)(((uint32*)(buf))[(jj*num_bands)+band_no]);   // Current sample.\n                }\n                else {\n                  // Planar configuration is band-sequential or single-banded\n                  cs = (double)(((uint32*)(buf))[jj]);   // Current sample.\n                }\n                break;\n              case SAMPLEFORMAT_INT:\n                if (planar_config == PLANARCONFIG_CONTIG && num_bands > 1) {\n                  cs = (double)(((long*)(buf))[(jj*num_bands)+band_no]);   // Current sample.\n                }\n                else {\n                  // Planar configuration is band-sequential or single-banded\n                  cs = (double)(((long*)(buf))[jj]);   // Current sample.\n                }\n                break;\n              case SAMPLEFORMAT_IEEEFP:\n                if (planar_config == PLANARCONFIG_CONTIG && num_bands > 1) {\n                  cs = (double)(((float*)(buf))[(jj*num_bands)+band_no]);   // Current sample.\n                }\n                else {\n                  // Planar configuration is band-sequential or single-banded\n                  cs = (double)(((float*)(buf))[jj]);   // Current sample.\n                }\n                if (is_dem && cs < -10e10) {\n                  // Bad value removal for DEMs (really an adjustment, not a removal)\n                  // -> This only applies to USGS Seamless DEMs and REAL32 data type <-\n                  cs = -999.0;\n                }\n                break;\n              default:\n                asfPrintError(\"Unexpected data type in GeoTIFF ...Cannot calculate statistics.\\n\");\n                return 1;\n                break;\n            }\n            break;\n          default:\n            asfPrintError(\"Unexpected data type in GeoTIFF ...Cannot calculate statistics.\\n\");\n            return 1;\n            break;\n        }\n        if ( G_UNLIKELY (cs < fmin) ) { fmin = cs; }\n        if ( G_UNLIKELY (cs > fmax) ) { fmax = cs; }\n        double old_mean = stats->mean;\n        stats->mean += (cs - stats->mean) / (sample_count + 1);\n        s += (cs - old_mean) * (cs - stats->mean);\n        sample_count++;\n      }\n    }\n    asfPercentMeter(1.0);\n  }\n  if (buf) _TIFFfree(buf);\n\n  // Verify the new extrema have been found.\n  //if (fmin == FLT_MAX || fmax == -FLT_MAX)\n  if (gsl_fcmp (fmin, FLT_MAX, 0.00000000001) == 0 ||\n      gsl_fcmp (fmax, -FLT_MAX, 0.00000000001) == 0)\n    return 1;\n\n  stats->min = fmin;\n  stats->max = fmax;\n  stats->std_deviation = sqrt (s / (sample_count - 1));\n\n  // The new extrema had better be in the range supported range\n  if (fabs(stats->mean) > FLT_MAX || fabs(stats->std_deviation) > FLT_MAX)\n    return 1;\n\n  return 0;\n}\n\nint  geotiff_band_image_write(TIFF *tif, meta_parameters *omd,\n                              const char *outBaseName, int num_bands,\n                              int *ignore, short bits_per_sample,\n                              short sample_format, short planar_config)\n{\n  char *outName;\n  int num_ignored;\n  uint32 row, col, band;\n  float *buf;\n  tsize_t scanlineSize;\n\n  // Determine what type of TIFF this is (scanline/strip/tiled)\n  tiff_type_t tiffInfo;\n  get_tiff_type(tif, &tiffInfo);\n  if (tiffInfo.imageCount > 1) {\n    asfPrintWarning(\"Found multi-image TIFF file.  Only the first image in the file\\n\"\n                   \"will be exported.\\n\");\n  }\n  if (tiffInfo.imageCount < 1) {\n    asfPrintError (\"TIFF file contains zero images\\n\");\n  }\n  if (tiffInfo.format != SCANLINE_TIFF &&\n      tiffInfo.format != STRIP_TIFF    &&\n      tiffInfo.format != TILED_TIFF)\n  {\n    asfPrintError(\"Unrecognized TIFF type\\n\");\n  }\n  if (tiffInfo.volume_tiff) {\n    asfPrintError(\"Multi-dimensional TIFF found ...only 2D TIFFs are supported.\\n\");\n  }\n\n  buf = (float*)MALLOC(sizeof(float)*omd->general->sample_count);\n  outName = (char*)MALLOC(sizeof(char)*strlen(outBaseName) + 5);\n  strcpy(outName, outBaseName);\n  append_ext_if_needed(outName, \".img\", \".img\");\n  if (num_bands > 1 &&\n      planar_config != PLANARCONFIG_CONTIG &&\n      planar_config != PLANARCONFIG_SEPARATE)\n  {\n    asfPrintError(\"Unexpected planar configuration found in TIFF file\\n\");\n  }\n\n  scanlineSize = TIFFScanlineSize(tif);\n  if (scanlineSize <= 0) {\n    return 1;\n  }\n  tdata_t *tif_buf = _TIFFmalloc(scanlineSize);\n  if (!tif_buf) {\n    asfPrintError(\"Cannot allocate buffer for reading TIFF lines\\n\");\n  }\n\n  for (band=0, num_ignored=0; band < num_bands; band++) {\n    if (num_bands > 1) {\n      asfPrintStatus(\"\\nWriting band %02d...\\n\", band+1);\n    }\n    else\n    {\n      asfPrintStatus(\"\\nWriting binary image...\\n\");\n    }\n    FILE *fp=(FILE*)FOPEN(outName, band > 0 ? \"ab\" : \"wb\");\n    if (fp == NULL) return 1;\n    if (!ignore[band]) {\n      for (row=0; row < omd->general->line_count; row++) {\n        asfLineMeter(row, omd->general->line_count);\n        switch (tiffInfo.format) {\n          case SCANLINE_TIFF:\n            if (planar_config == PLANARCONFIG_CONTIG || num_bands == 1) {\n              TIFFReadScanline(tif, tif_buf, row, 0);\n            }\n            else {\n            // Planar configuration is band-sequential\n              TIFFReadScanline(tif, tif_buf, row, band);\n            }\n            break;\n          case STRIP_TIFF:\n            ReadScanline_from_TIFF_Strip(tif, tif_buf, row, band);\n            break;\n          case TILED_TIFF:\n            // Planar configuration is band-sequential\n            ReadScanline_from_TIFF_TileRow(tif, tif_buf, row, band);\n            break;\n          default:\n            asfPrintError(\"Invalid TIFF format found.\\n\");\n            break;\n        }\n        for (col=0; col < omd->general->sample_count; col++) {\n          switch (bits_per_sample) {\n            case 8:\n              switch(sample_format) {\n                case SAMPLEFORMAT_UINT:\n                  ((float*)buf)[col] = (float)(((uint8*)tif_buf)[col]);\n                  break;\n                case SAMPLEFORMAT_INT:\n                  ((float*)buf)[col] = (float)(((int8*)tif_buf)[col]);\n                  break;\n                default:\n                  // No such thing as an 8-bit IEEE float\n                  asfPrintError(\"Unexpected data type in TIFF file ...cannot write ASF-internal\\n\"\n                      \"format file.\\n\");\n                  break;\n              }\n              break;\n            case 16:\n              switch(sample_format) {\n                case SAMPLEFORMAT_UINT:\n                  ((float*)buf)[col] = (float)(((uint16*)tif_buf)[col]);\n                  break;\n                case SAMPLEFORMAT_INT:\n                  ((float*)buf)[col] = (float)(((int16*)tif_buf)[col]);\n                  break;\n                default:\n                  // No such thing as an 16-bit IEEE float\n                  asfPrintError(\"Unexpected data type in TIFF file ...cannot write ASF-internal\\n\"\n                      \"format file.\\n\");\n                  break;\n              }\n              break;\n            case 32:\n              switch(sample_format) {\n                case SAMPLEFORMAT_UINT:\n                  ((float*)buf)[col] = (float)(((uint32*)tif_buf)[col]);\n                  break;\n                case SAMPLEFORMAT_INT:\n                  ((float*)buf)[col] = (float)(((long*)tif_buf)[col]);\n                  break;\n                case SAMPLEFORMAT_IEEEFP:\n                  ((float*)buf)[col] = (float)(((float*)tif_buf)[col]);\n                  break;\n                default:\n                  asfPrintError(\"Unexpected data type in TIFF file ...cannot write ASF-internal\\n\"\n                      \"format file.\\n\");\n                  break;\n              }\n              break;\n            default:\n              asfPrintError(\"Unexpected data type in TIFF file ...cannot write ASF-internal\\n\"\n                  \"format file.\\n\");\n              break;\n          }\n        }\n        put_band_float_line(fp, omd, band - num_ignored, (int)row, buf);\n      }\n    }\n    else {\n      asfPrintStatus(\"  Empty band found ...ignored\\n\");\n      num_ignored++;\n    }\n    FCLOSE(fp);\n  }\n  FREE(buf);\n  FREE(outName);\n  if (tif_buf) _TIFFfree(tif_buf);\n\n  return 0;\n}\n\nvoid ReadScanline_from_TIFF_Strip(TIFF *tif, tdata_t buf, unsigned long row, int band)\n{\n  int read_count;\n  tiff_type_t t;\n  tdata_t sbuf=NULL;\n  tstrip_t strip;\n  uint32 strip_row; // The row within the strip that contains the requested data row\n\n  if (tif == NULL) {\n    asfPrintError(\"TIFF file not open for read\\n\");\n  }\n\n  get_tiff_type(tif, &t);\n  uint32 strip_size = TIFFStripSize(tif);\n  sbuf = _TIFFmalloc(strip_size);\n\n  short planar_config;    // TIFFTAG_PLANARCONFIG\n  read_count = TIFFGetField(tif, TIFFTAG_PLANARCONFIG, &planar_config);\n  if (read_count < 1) {\n    asfPrintError(\"Cannot determine planar configuration from TIFF file.\\n\");\n  }\n  short samples_per_pixel;\n  read_count = TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &samples_per_pixel); // Number of bands\n  if (read_count < 1) {\n    asfPrintError(\"Could not read the number of samples per pixel from TIFF file.\\n\");\n  }\n  if (band < 0 || band > samples_per_pixel - 1) {\n    asfPrintError(\"Invalid band number (%d).  Band number should range from %d to %d.\\n\",\n                  0, samples_per_pixel - 1);\n  }\n  uint32 height;\n  read_count = TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &height); // Number of rows\n  if (read_count < 1) {\n    asfPrintError(\"Could not read the number of lines from TIFF file.\\n\");\n  }\n  uint32 width;\n  read_count = TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &width); // Number of pixels per row\n  if (read_count < 1) {\n    asfPrintError(\"Could not read the number of pixels per line from TIFF file.\\n\");\n  }\n  short bits_per_sample;\n  read_count = TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &bits_per_sample);\n  if (read_count < 1) {\n      asfPrintError(\"Could not read the bits per sample from TIFF file.\\n\");\n  }\n  short sample_format;\n  read_count = TIFFGetField(tif, TIFFTAG_SAMPLEFORMAT, &sample_format); // int or float, signed or unsigned\n  if (read_count < 1) {\n      switch(bits_per_sample) {\n          case 8:\n              sample_format = SAMPLEFORMAT_UINT;\n              break;\n          case 16:\n              sample_format = SAMPLEFORMAT_INT;\n              break;\n          case 32:\n              sample_format = SAMPLEFORMAT_IEEEFP;\n              break;\n          default:\n              asfPrintError(\"Could not read the sample format (data type) from TIFF file.\\n\");\n              break;\n      }\n  }\n  short orientation;\n  read_count = TIFFGetField(tif, TIFFTAG_ORIENTATION, &orientation); // top-left, left-top, bot-right, etc\n  if (read_count < 1) {\n    orientation = ORIENTATION_TOPLEFT;\n    read_count = 1;\n  }\n  if (read_count && orientation != ORIENTATION_TOPLEFT) {\n    asfPrintError(\"Unsupported orientation found (%s)\\n\",\n                  orientation == ORIENTATION_TOPRIGHT ? \"TOP RIGHT\" :\n                  orientation == ORIENTATION_BOTRIGHT ? \"BOTTOM RIGHT\" :\n                  orientation == ORIENTATION_BOTLEFT  ? \"BOTTOM LEFT\" :\n                  orientation == ORIENTATION_LEFTTOP  ? \"LEFT TOP\" :\n                  orientation == ORIENTATION_RIGHTTOP ? \"RIGHT TOP\" :\n                  orientation == ORIENTATION_RIGHTBOT ? \"RIGHT BOTTOM\" :\n                  orientation == ORIENTATION_LEFTBOT  ? \"LEFT BOTTOM\" : \"UNKNOWN\");\n  }\n  // Check for valid row number\n  if (row < 0 || row >= height) {\n    asfPrintError(\"Invalid row number (%d) found.  Valid range is 0 through %d\\n\",\n                  row, height - 1);\n  }\n\n  // Reading a contiguous RGB strip results in a strip (of several rows) with rgb data\n  // in each row, but reading a strip from a file with separate color planes results in\n  // a strip with just the one color in each strip (and row)\n  strip     = TIFFComputeStrip(tif, row, band);\n  strip_row = row - (strip * t.rowsPerStrip);\n  tsize_t stripSize = TIFFStripSize(tif);\n  uint32 bytes_per_sample = (bits_per_sample / 8);\n\n  // This returns a decoded strip which contains 1 or more rows.  The index calculated\n  // below needs to take the row into account ...the strip_row is the row within a strip\n  // assuming the first row in a strip is '0'.\n  tsize_t bytes_read = TIFFReadEncodedStrip(tif, strip, sbuf, (tsize_t) -1);\n  if (read_count &&\n      bytes_read > 0)\n  {\n    uint32 col;\n    uint32 idx = 0;\n    for (col = 0; col < width && (idx * bytes_per_sample) < stripSize; col++) {\n      // NOTE: t.scanlineSize is in bytes (not pixels)\n      if (planar_config == PLANARCONFIG_SEPARATE) {\n        idx = strip_row * (t.scanlineSize / bytes_per_sample) + col*samples_per_pixel;\n      }\n      else {\n        // PLANARCONFIG_CONTIG\n        idx = strip_row * (t.scanlineSize / bytes_per_sample) + col*samples_per_pixel + band;\n      }\n      if (idx * bytes_per_sample >= stripSize)\n        continue; // Prevents over-run if last strip or scanline (within a strip) is not complete\n      switch (bits_per_sample) {\n        case 8:\n          switch (sample_format) {\n            case SAMPLEFORMAT_UINT:\n              ((uint8*)buf)[col] = (uint8)(((uint8*)sbuf)[idx]);\n              break;\n            case SAMPLEFORMAT_INT:\n              ((int8*)buf)[col] = (int8)(((int8*)sbuf)[idx]);\n              break;\n            default:\n              asfPrintError(\"Unexpected data type in TIFF file\\n\");\n              break;\n          }\n          break;\n        case 16:\n          switch (sample_format) {\n            case SAMPLEFORMAT_UINT:\n              ((uint16*)buf)[col] = (uint16)(((uint16*)sbuf)[idx]);\n              break;\n            case SAMPLEFORMAT_INT:\n              ((int16*)buf)[col] = (int16)(((int16*)sbuf)[idx]);\n              break;\n            default:\n              asfPrintError(\"Unexpected data type in TIFF file\\n\");\n              break;\n          }\n          break;\n        case 32:\n          switch (sample_format) {\n            case SAMPLEFORMAT_UINT:\n              ((uint32*)buf)[col] = (uint32)(((uint32*)sbuf)[idx]);\n              break;\n            case SAMPLEFORMAT_INT:\n              ((long*)buf)[col] = (long)(((long*)sbuf)[idx]);\n              break;\n            case SAMPLEFORMAT_IEEEFP:\n              ((float*)buf)[col] = (float)(((float*)sbuf)[idx]);\n              break;\n            default:\n              asfPrintError(\"Unexpected data type in TIFF file\\n\");\n              break;\n          }\n          break;\n        default:\n          asfPrintError(\"Usupported bits per sample found in TIFF file\\n\");\n          break;\n      }\n    }\n  }\n\n  if (sbuf)\n    _TIFFfree(sbuf);\n}\n\nvoid ReadScanline_from_TIFF_TileRow(TIFF *tif, tdata_t buf, unsigned long row, int band)\n{\n  int read_count;\n  tiff_type_t t;\n  tdata_t tbuf=NULL;\n\n  if (tif == NULL) {\n    asfPrintError(\"TIFF file not open for read\\n\");\n  }\n\n  get_tiff_type(tif, &t);\n  if (t.format != TILED_TIFF) {\n    asfPrintError(\"Programmer error: ReadScanline_from_TIFF_TileRow() called when the TIFF file\\n\"\n        \"was not a tiled TIFF.\\n\");\n  }\n  tsize_t tileSize = TIFFTileSize(tif);\n  if (tileSize > 0) {\n    tbuf = _TIFFmalloc(tileSize);\n    if (tbuf == NULL) {\n      asfPrintError(\"Unable to allocate tiled TIFF scanline buffer\\n\");\n    }\n  }\n  else {\n    asfPrintError(\"Invalid TIFF tile size in tiled TIFF.\\n\");\n  }\n\n  short planar_config;    // TIFFTAG_PLANARCONFIG\n  read_count = TIFFGetField(tif, TIFFTAG_PLANARCONFIG, &planar_config);\n  if (read_count < 1) {\n    asfPrintError(\"Cannot determine planar configuration from TIFF file.\\n\");\n  }\n\n  short samples_per_pixel;\n  read_count = TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &samples_per_pixel); // Number of bands\n  if (read_count < 1) {\n    asfPrintError(\"Could not read the number of samples per pixel from TIFF file.\\n\");\n  }\n  if (band < 0 || band > samples_per_pixel - 1) {\n    asfPrintError(\"Invalid band number (%d).  Band number should range from %d to %d.\\n\",\n                  0, samples_per_pixel - 1);\n  }\n  uint32 height;\n  read_count = TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &height); // Number of bands\n  if (read_count < 1) {\n    asfPrintError(\"Could not read the number of lines from TIFF file.\\n\");\n  }\n  uint32 width;\n  read_count = TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &width); // Number of bands\n  if (read_count < 1) {\n    asfPrintError(\"Could not read the number of pixels per line from TIFF file.\\n\");\n  }\n  short bits_per_sample;\n  read_count = TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &bits_per_sample); // Number of bands\n  if (read_count < 1) {\n      asfPrintError(\"Could not read the bits per sample from TIFF file.\\n\");\n  }\n  short sample_format;\n  read_count = TIFFGetField(tif, TIFFTAG_SAMPLEFORMAT, &sample_format); // Number of bands\n  if (read_count < 1) {\n      switch(bits_per_sample) {\n          case 8:\n              sample_format = SAMPLEFORMAT_UINT;\n              break;\n          case 16:\n              sample_format = SAMPLEFORMAT_INT;\n              break;\n          case 32:\n              sample_format = SAMPLEFORMAT_IEEEFP;\n              break;\n          default:\n              asfPrintError(\"Could not read the sample format (data type) from TIFF file.\\n\");\n              break;\n      }\n  }\n  short orientation;\n  read_count = TIFFGetField(tif, TIFFTAG_ORIENTATION, &orientation); // top-left, left-top, bot-right, etc\n  if (read_count < 1) {\n    orientation = ORIENTATION_TOPLEFT;\n  }\n  if (read_count && orientation != ORIENTATION_TOPLEFT) {\n    asfPrintError(\"Unsupported orientation found (%s)\\n\",\n                  orientation == ORIENTATION_TOPRIGHT ? \"TOP RIGHT\" :\n                  orientation == ORIENTATION_BOTRIGHT ? \"BOTTOM RIGHT\" :\n                  orientation == ORIENTATION_BOTLEFT  ? \"BOTTOM LEFT\" :\n                  orientation == ORIENTATION_LEFTTOP  ? \"LEFT TOP\" :\n                  orientation == ORIENTATION_RIGHTTOP ? \"RIGHT TOP\" :\n                  orientation == ORIENTATION_RIGHTBOT ? \"RIGHT BOTTOM\" :\n                  orientation == ORIENTATION_LEFTBOT  ? \"LEFT BOTTOM\" : \"UNKNOWN\");\n  }\n  // Check for valid row number\n  if (row < 0 || row >= height) {\n    asfPrintError(\"Invalid row number (%d) found.  Valid range is 0 through %d\\n\",\n                  row, height - 1);\n  }\n  // Develop a buffer with a line of data from a single band in it\n//  ttile_t tile;\n  uint32 bytes_per_sample = bits_per_sample / 8;\n  uint32 row_in_tile;\n\n  if (width > 0 &&\n      height > 0 &&\n      samples_per_pixel > 0 &&\n      bits_per_sample % 8 == 0 &&\n      t.tileWidth > 0 &&\n      t.tileLength > 0)\n  {\n    uint32 tile_col;\n    uint32 buf_col;\n    uint32 bytes_read;\n    for (tile_col = 0, buf_col = 0;\n         tile_col < width;\n         tile_col += t.tileWidth)\n    {\n      // NOTE:  t.tileLength and t.tileWidth are in pixels (not bytes)\n      // NOTE:  TIFFReadTile() is a wrapper over TIFFComputeTile() and\n      //        TIFFReadEncodedTile() ...in other words, it automatically\n      //        takes into account whether the file has contigious (interlaced)\n      //        color bands or separate color planes, and automagically\n      //        decompresses the tile during the read.  The return below,\n      //        is an uncompressed tile in raster format (row-order 2D array\n      //        in memory.)\n      bytes_read = TIFFReadTile(tif, tbuf, tile_col, row, 0, band);\n      uint32 num_preceding_tile_rows = floor(row / t.tileLength);\n      row_in_tile = row - (num_preceding_tile_rows * t.tileLength);\n      uint32 i;\n      uint32 idx = 0;\n      for (i = 0; i < t.tileWidth && buf_col < width && (idx * bytes_per_sample) < tileSize; i++) {\n        if (planar_config == PLANARCONFIG_SEPARATE) {\n          idx = row_in_tile * t.tileWidth + i;\n        }\n        else {\n          // PLANARCONFIG_CONTIG\n          idx = row_in_tile * (t.tileWidth * samples_per_pixel) + i * samples_per_pixel + band;\n        }\n        switch (bits_per_sample) {\n          case 8:\n            switch (sample_format) {\n              case SAMPLEFORMAT_UINT:\n                ((uint8*)buf)[buf_col] = ((uint8*)tbuf)[idx];\n                buf_col++;\n                break;\n              case SAMPLEFORMAT_INT:\n                ((int8*)buf)[buf_col] = ((int8*)tbuf)[idx];\n                buf_col++;\n                break;\n              default:\n                asfPrintError(\"Unexpected data type in TIFF file\\n\");\n                break;\n            }\n            break;\n          case 16:\n            switch (sample_format) {\n              case SAMPLEFORMAT_UINT:\n                ((uint16*)buf)[buf_col] = ((uint16*)tbuf)[idx];\n                buf_col++;\n                break;\n              case SAMPLEFORMAT_INT:\n                ((int16*)buf)[buf_col] = ((int16*)tbuf)[idx];\n                buf_col++;\n                break;\n              default:\n                asfPrintError(\"Unexpected data type in TIFF file\\n\");\n                break;\n            }\n            break;\n          case 32:\n            switch (sample_format) {\n              case SAMPLEFORMAT_UINT:\n                ((uint32*)buf)[buf_col] = ((uint32*)tbuf)[idx];\n                buf_col++;\n                break;\n              case SAMPLEFORMAT_INT:\n                ((int32*)buf)[buf_col] = ((int32*)tbuf)[idx];\n                buf_col++;\n                break;\n              case SAMPLEFORMAT_IEEEFP:\n                ((float*)buf)[buf_col] = ((float*)tbuf)[idx];\n                buf_col++;\n                break;\n              default:\n                asfPrintError(\"Unexpected data type in TIFF file\\n\");\n                break;\n            }\n            break;\n          default:\n            asfPrintError(\"Usupported bits per sample found in TIFF file\\n\");\n            break;\n        }\n      }\n    }\n  }\n\n  if (tbuf) _TIFFfree(tbuf);\n}\n\nint check_for_vintage_asf_utm_geotiff(const char *citation, int *geotiff_data_exists,\n                                      short *model_type, short *raster_type, short *linear_units)\n{\n  int ret=0;\n  int zone=0, is_utm=0;\n  datum_type_t datum=UNKNOWN_DATUM;\n  char hem='\\0';\n\n  if (citation && strstr(citation, \"Alaska Satellite Facility\")) {\n    short pcs=0;\n    is_utm = vintage_utm_citation_to_pcs(citation, &zone, &hem, &datum, &pcs);\n  }\n  if (is_utm &&\n      zone >=1 && zone <= 60 &&\n      (hem == 'N' || hem == 'S') &&\n      datum == WGS84_DATUM)\n  {\n    *model_type = ModelTypeProjected;\n    *raster_type = RasterPixelIsArea;\n    *linear_units = Linear_Meter;\n    *geotiff_data_exists = 1;\n    ret = 3; // As though the three geokeys were read successfully\n  }\n\n  return ret;\n}\n\n// Copied from libasf_import:keys.c ...Didn't want to introduce a dependency on\n// the export library or vice versa\nstatic int UTM_2_PCS(short *pcs, datum_type_t datum, unsigned long zone, char hem)\n{\n  // The GeoTIFF standard defines the UTM zones numerically in a way that\n  // let's us pick off the data mathematically (NNNzz where zz is the zone\n  // number):\n  //\n  // For NAD83 datums, Zones 3N through 23N, NNN == 269\n  // For NAD27 datums, Zones 3N through 22N, NNN == 267\n  // For WGS72 datums, Zones 1N through 60N, NNN == 322\n  // For WGS72 datums, Zones 1S through 60S, NNN == 323\n  // For WGS84 datums, Zones 1N through 60N, NNN == 326\n  // For WGS84 datums, Zones 1S through 60S, NNN == 327\n  // For user-defined and unsupported UTM projections, NNN can be\n  //   a variety of other numbers (see the GeoTIFF Standard)\n  //\n  // NOTE: For NAD27 and NAD83, only the restricted range of zones\n  // above is supported by the GeoTIFF standard.\n  //\n  // NOTE: For ALOS's ITRF97 datum, note that it is based on\n  // WGS84 and subsituting WGS84 for ITRF97 because the GeoTIFF\n  // standard does not contain a PCS for ITRF97 (or any ITRFxx)\n  // will result in errors of less than one meter.  So when\n  // writing GeoTIFFs, we choose to use WGS84 when ITRF97 is\n  // desired.\n  //\n\n  const short NNN_NAD27N = 267;\n  const short NNN_NAD83N = 269;\n  //const short NNN_WGS72N = 322; // Currently unsupported\n  //const short NNN_WGS72S = 323; // Currently unsupported\n  const short NNN_WGS84N = 326;\n  const short NNN_WGS84S = 327;\n  char uc_hem;\n  int supportedUTM;\n  int valid_Zone_and_Datum_and_Hemisphere;\n\n  // Substitute WGS84 for ITRF97 per comment above\n  if (datum == ITRF97_DATUM) {\n    datum = WGS84_DATUM;\n  }\n\n  // Check for valid datum, hemisphere, and zone combination\n  uc_hem = toupper(hem);\n  valid_Zone_and_Datum_and_Hemisphere =\n      (\n      (datum == NAD27_DATUM && uc_hem == 'N' && zone >= 3 && zone <= 22) ||\n      (datum == NAD83_DATUM && uc_hem == 'N' && zone >= 3 && zone <= 23) ||\n      (datum == WGS84_DATUM                  && zone >= 1 && zone <= 60)\n      ) ? 1 : 0;\n\n  // Build the key for ProjectedCSTypeGeoKey, GCS_WGS84 etc\n  if (valid_Zone_and_Datum_and_Hemisphere) {\n    supportedUTM = 1;\n    switch (datum) {\n      case NAD27_DATUM:\n        *pcs = (short)zone + NNN_NAD27N * 100;\n        break;\n      case NAD83_DATUM:\n        *pcs = (short)zone + NNN_NAD83N * 100;\n        break;\n      case WGS84_DATUM:\n        if (uc_hem == 'N') {\n          *pcs = (short)zone + NNN_WGS84N * 100;\n        }\n        else {\n          *pcs = (short)zone + NNN_WGS84S * 100;\n        }\n        break;\n      default:\n        supportedUTM = 0;\n        *pcs = 0;\n        break;\n    }\n  }\n  else {\n    supportedUTM = 0;\n    *pcs = 0;\n  }\n\n  return supportedUTM;\n}\n\n// If the UTM description is in citation, then pick the data out and return it\nint vintage_utm_citation_to_pcs(const char *citation, int *zone, char *hem, datum_type_t *datum, short *pcs)\n{\n  int is_utm=0;\n  int found_zone=0, found_utm=0;\n\n  *zone=0;\n  *hem='\\0';\n  *datum=UNKNOWN_DATUM;\n  *pcs=0;\n\n  if (citation && strstr(citation, \"Alaska Satellite Facility\")) {\n    char *s = STRDUP(citation);\n    char *tokp;\n\n    tokp = strtok(s, \" \");\n    do\n    {\n      if (strncmp(uc(tokp),\"UTM\",3) == 0) {\n        found_utm = 1;\n        found_zone=0;\n      }\n      else if (strncmp(uc(tokp),\"ZONE\",1) == 0) {\n        if (*zone == 0) found_zone=1;\n      }\n      else if (found_zone && isdigit((int)*tokp)) {\n        *zone = (int)strtol(tokp,(char**)NULL,10);\n        found_zone=0;\n      }\n      else if (strlen(tokp) == 1 && (*(uc(tokp)) == 'N' || *(uc(tokp)) == 'S')) {\n        *hem = *(uc(tokp)) == 'N' ? 'N' : 'S';\n        found_zone=0;\n      }\n      else if (strncmp(uc(tokp),\"WGS84\",5) == 0) {\n        *datum = WGS84_DATUM;\n        found_zone=0;\n      }\n    } while (tokp && (tokp = strtok(NULL, \" \")));\n\n    if (s) FREE (s);\n  }\n  if (found_utm &&\n      *zone >=1 && *zone <= 60 &&\n      (*hem == 'N' || *hem == 'S') &&\n      *datum == WGS84_DATUM)\n  {\n    is_utm=1;\n    UTM_2_PCS(pcs, *datum, *zone, *hem);\n  }\n  else {\n    is_utm = 0;\n    *zone=0;\n    *hem='\\0';\n    *datum=UNKNOWN_DATUM;\n    *pcs=0;\n  }\n\n  return is_utm;\n}\n\nvoid classify_geotiff(GTIF *input_gtif,\n                      short *model_type, short *raster_type, short *linear_units, short *angular_units,\n                      int *geographic_geotiff, int *geocentric_geotiff, int *map_projected_geotiff,\n                      int *geotiff_data_exists)\n{\n    int read_count, vintage_asf_utm;\n    char *citation = NULL;\n    int citation_length;\n    int typeSize;\n    tagtype_t citation_type;\n\n    ////// Defaults //////\n    *model_type = *raster_type = *linear_units = *angular_units = -1; // Invalid value\n    *geographic_geotiff = *geocentric_geotiff = *map_projected_geotiff = *geotiff_data_exists = 0; // Fails\n\n    ////////////////////////////////////////////////////////////////////////////////////////\n    // Check for a vintage ASF type of geotiff (all projection info is in the citation, and the\n    // normal projection geokeys are left unpopulated)\n    citation_length = GTIFKeyInfo(input_gtif, GTCitationGeoKey, &typeSize, &citation_type);\n    if (citation_length > 0) {\n        citation = MALLOC ((citation_length) * typeSize);\n        GTIFKeyGet (input_gtif, GTCitationGeoKey, citation, 0, citation_length);\n    }\n    else {\n        citation_length = GTIFKeyInfo(input_gtif, PCSCitationGeoKey, &typeSize, &citation_type);\n        if (citation_length > 0) {\n            citation = MALLOC ((citation_length) * typeSize);\n            GTIFKeyGet (input_gtif, PCSCitationGeoKey, citation, 0, citation_length);\n        }\n    }\n    if (citation != NULL && strlen(citation) > 0) {\n        vintage_asf_utm = check_for_vintage_asf_utm_geotiff(citation, geotiff_data_exists,\n                model_type, raster_type, linear_units);\n        if (vintage_asf_utm) {\n            // Found a vintage ASF UTM geotiff\n            *geographic_geotiff    = *geocentric_geotiff  = 0;\n            *map_projected_geotiff = *geotiff_data_exists = 1;\n            return;\n        }\n    }\n    FREE(citation);\n\n    ////////////////////////////////////////////////////////////////////////////////////////\n    // Check for other types of geotiffs...\n    //\n    // Read the basic (normally required) classification parameters ...bail if we hit any\n    // unsupported types\n    int m = 0, r = 0, l = 0, a = 0;\n    m = GTIFKeyGet (input_gtif, GTModelTypeGeoKey, model_type, 0, 1);\n    if (m && *model_type == ModelTypeGeocentric) {\n        asfPrintError(\"Geocentric (x, y, z) GeoTIFFs are unsupported (so far.)\\n\");\n    }\n    if (m && *model_type != ModelTypeProjected && *model_type != ModelTypeGeographic) {\n        asfPrintError(\"Unrecognized type of GeoTIFF encountered.  Must be map-projected\\n\"\n                \"or geogaphic (lat/long)\\n\");\n    }\n    r = GTIFKeyGet (input_gtif, GTRasterTypeGeoKey, raster_type, 0, 0);\n    if (r && *raster_type != RasterPixelIsArea) {\n        asfPrintWarning(\"GeoTIFFs with 'point' type raster pixels are unsupported (so far.)\\nContinuing, however geolocations may be off by up to a pixel.\\n\");\n    }\n    if (m && *model_type == ModelTypeProjected) {\n        l = GTIFKeyGet (input_gtif, ProjLinearUnitsGeoKey, linear_units, 0, 1);\n    }\n    if (m && *model_type == ModelTypeGeographic) {\n        a = GTIFKeyGet (input_gtif, GeogAngularUnitsGeoKey, angular_units, 0, 1);\n    }\n    if (a &&\n        *angular_units != Angular_Arc_Second    &&\n        *angular_units != Angular_Degree)\n    {\n        // Temporarily choose not to support arcsec geotiffs ...needs more testing\n        asfPrintError(\"Found a Geographic (lat/lon) GeoTIFF with an unsupported type of angular\\n\"\n                \"units (%s) in it.\\n\", angular_units_to_string(*angular_units));\n    }\n    if (l && (*linear_units != Linear_Meter &&\n\t      *linear_units != Linear_Foot &&\n\t      *linear_units != Linear_Foot_US_Survey &&\n\t      *linear_units != Linear_Foot_Modified_American &&\n\t      *linear_units != Linear_Foot_Clarke &&\n\t      *linear_units != Linear_Foot_Indian)) {\n        // Linear units was populated but wasn't a supported type...\n        asfPrintError(\"Found a map-projected GeoTIFF with an unsupported type of linear\\n\"\n                \"units (%s) in it.\\n\", linear_units_to_string(*linear_units));\n    }\n    read_count = m + r + l + a;\n\n    //////////////////////////////////////////////////////////////////////////////////////////\n    // Attempt to classify the geotiff as a geographic, geocentric, or map-projected geotiff\n    // and try to fill in missing information if necessary\n\n    // Case: 3 valid keys found\n    if (read_count == 3) {\n        // Check for map-projected geotiff\n        if (m && *model_type == ModelTypeProjected)\n        {\n            ////////\n            // GeoTIFF is map-projected\n            if (!r ||\n                (r &&\n                 *raster_type != RasterPixelIsArea &&\n                 *raster_type != RasterPixelIsPoint))\n            {\n                asfPrintWarning(\"Invalid raster type found.\\n\"\n                                \"Guessing RasterPixelIsArea and continuing...\\n\");\n                r = 1;\n                *raster_type = RasterPixelIsArea;\n            }\n            if (r &&\n                *raster_type != RasterPixelIsArea)\n            {\n                asfPrintError(\"Only map-projected GeoTIFFs with pixels that represent area are supported.\");\n            }\n            if (a && !l) {\n                asfPrintWarning(\"Invalid map-projected GeoTIFF found ...angular units set to %s and\\n\"\n                        \"linear units were not set.  Guessing Linear_Meter units and continuing...\\n\",\n                        angular_units_to_string(*angular_units));\n                l = 1;\n                *linear_units = Linear_Meter;\n                a = 0;\n                *angular_units = -1;\n            }\n            if (l && (*linear_units == Linear_Meter ||\n\t\t      *linear_units == Linear_Foot ||\n\t\t      *linear_units == Linear_Foot_US_Survey ||\n\t\t      *linear_units == Linear_Foot_Modified_American ||\n\t\t      *linear_units == Linear_Foot_Clarke ||\n\t\t      *linear_units == Linear_Foot_Indian))\n            {\n                *geographic_geotiff    = *geocentric_geotiff  = 0;\n                *map_projected_geotiff = *geotiff_data_exists = 1;\n                return;\n            }\n            else {\n                asfPrintError(\"Only map-projected GeoTIFFs with linear meters or with a linear foot unit are supported.\\n\");\n            }\n        }\n        else if (m && *model_type == ModelTypeGeographic) {\n            ////////\n            // GeoTIFF is geographic (lat/long, degrees or arc-seconds (typ))\n            // Ignore *raster_type ...it might be set to 'area', but that would be meaningless\n            // *raster_type has no meaning in a lat/long GeoTIFF\n            if (l && !a) {\n                asfPrintWarning(\"Invalid Geographic (lat/lon) GeoTIFF found ...linear units set to %s and\\n\"\n                        \"angular units were not set.  Guessing Angular_Degree units and continuing...\\n\",\n                        linear_units_to_string(*linear_units));\n                a = 1;\n                *angular_units = Angular_Degree;\n                l = 0;\n                *linear_units = -1;\n            }\n            if (a &&\n                (*angular_units == Angular_Degree ||\n                 *angular_units == Angular_Arc_Second))\n            {\n                *geographic_geotiff    = *geotiff_data_exists = 1;\n                *map_projected_geotiff = *geocentric_geotiff  = 0;\n                return;\n            }\n            else {\n                asfPrintError(\"Found Geographic GeoTIFF with invalid or unsupported angular units (%s)\\n\"\n                        \"Only geographic GeoTIFFs with angular degrees are supported.\\n\",\n                        angular_units_to_string(*angular_units));\n            }\n        }\n        else {\n            // Should not get here\n            asfPrintError(\"Invalid or unsupported model type\\n\");\n        }\n    }\n    // Case: 2 valid keys found, 1 key missing\n    else if (read_count == 2) {\n        // Only found 2 of 3 necessary parameters ...let's try to guess the 3rd\n        if (*model_type != ModelTypeProjected  && *model_type != ModelTypeGeographic)\n        {\n            // The model type is unknown, raster_type and linear_units are both known and\n            // valid for their types\n            if (*raster_type == RasterPixelIsArea && *linear_units == Linear_Meter) {\n                // Guess map-projected\n                asfPrintWarning(\"Missing model type definition in GeoTIFF.  GeoTIFF contains area-type\\n\"\n                        \"pixels and linear meters ...guessing the GeoTIFF is map-projected and\\n\"\n                        \"attempting to continue...\\n\");\n                *model_type = ModelTypeProjected;\n                *geographic_geotiff    = *geocentric_geotiff  = 0;\n                *map_projected_geotiff = *geotiff_data_exists = 1;\n                return;\n            }\n            else if (*angular_units == Angular_Degree || *angular_units == Angular_Arc_Second) {\n                // Guess geographic\n                asfPrintWarning(\"Missing model type definition in GeoTIFF.  GeoTIFF contains angular\\n\"\n                        \"units ...guessing the GeoTIFF is geographic (lat/long) and\\n\"\n                        \"attempting to continue...\\n\");\n                *model_type = ModelTypeGeographic;\n                *geographic_geotiff    = *geotiff_data_exists = 1;\n                *map_projected_geotiff = *geocentric_geotiff  = 0;\n                return;\n            }\n            else {\n                asfPrintError(\"Found unsupported type of GeoTIFF or a GeoTIFF with too many missing keys.\\n\");\n            }\n        } // End of guessing because the ModelType was unknown - Check unknown raster_type case\n        else if (*raster_type != RasterPixelIsArea && *raster_type != RasterPixelIsPoint) {\n            // Raster type is missing ...let's take a guess.  Model type and linear\n            // units are both known and valid for their types\n            if (*model_type == ModelTypeProjected) {\n                if (*linear_units != Linear_Meter) {\n                    asfPrintError(\"Only meters are supported for map-projected GeoTIFFs\\n\");\n                }\n                // Guess pixel type is area\n                asfPrintWarning(\"Missing raster type in GeoTIFF, but since the GeoTIFF is map-projected,\\n\"\n                        \"guessing RasterPixelIsArea and attempting to continue...\\n\");\n                *raster_type = RasterPixelIsArea;\n                *geographic_geotiff    = *geocentric_geotiff  = 0;\n                *map_projected_geotiff = *geotiff_data_exists = 1;\n                return;\n            }\n            else if (*model_type == ModelTypeGeographic) {\n                // Guess pixel type is area\n                if (*angular_units != Angular_Degree && *angular_units != Angular_Arc_Second) {\n                    asfPrintError(\"Only angular degrees are supported for geographic GeoTIFFs\\n\");\n                }\n                *geographic_geotiff    = *geotiff_data_exists = 1;\n                *map_projected_geotiff = *geocentric_geotiff  = 0;\n                return;\n            }\n            else {\n                asfPrintError(\"Found geocentric (x, y, z) type of GeoTIFF ...currently unsupported.\\n\");\n            }\n        } // End of guessing because the RasterType was unknown\n        else if (*linear_units  != Linear_Meter   &&\n                 *angular_units != Angular_Degree &&\n                 *angular_units != Angular_Arc_Second)\n        {\n            // Pixel unit type is missing ...let's take a guess.  Model type and raster type are\n            // known and valid for their types\n            if (*model_type == ModelTypeProjected) {\n                if (*raster_type != RasterPixelIsArea) {\n                    asfPrintError(\"Map projected GeoTIFFs with pixels that represent something\\n\"\n                            \"other than area (meters etc) are not supported.\\n\");\n                }\n                // Looks like a valid map projection.  Guess linear meters for the units\n                asfPrintWarning(\"Missing linear units in GeoTIFF.  The GeoTIFF is map-projected and\\n\"\n                        \"pixels represent area.  Guessing linear meters for the units and attempting\\n\"\n                        \"to continue...\\n\");\n                *linear_units = Linear_Meter;\n                *angular_units = -1;\n                *geographic_geotiff    = *geocentric_geotiff  = 0;\n                *map_projected_geotiff = *geotiff_data_exists = 1;\n                return;\n            }\n            else if (*model_type == ModelTypeGeographic) {\n                // Looks like a valid geographic (lat/long) geotiff\n                asfPrintWarning(\"Found geographic type GeoTIFF with missing linear units setting.\\n\"\n                        \"Guessing angular degrees and attempting to continue...\\n\");\n                *angular_units = Angular_Degree;\n                *linear_units = -1;\n                *geographic_geotiff    = *geotiff_data_exists = 1;\n                *map_projected_geotiff = *geocentric_geotiff  = 0;\n                return;\n            }\n            else {\n                asfPrintError(\"Found geocentric (x, y, z) GeoTIFF... Geographic GeoTIFFs are\\n\"\n                        \"unsupported at this time.\\n\");\n            }\n        }\n    }\n    // Case: 1 valid key found, 2 keys missing\n    else if (read_count == 1) {\n        // Only found 1 of 3 necessary parameters ...let's try to guess the other 2 (dangerous ground!)\n        if (*model_type == ModelTypeProjected) {\n            // Only the model type is known ...guess the rest\n            asfPrintWarning(\"Both the raster type and linear units is missing in the GeoTIFF.  The model\\n\"\n                    \"type is map-projected, so guessing that the raster type is RasterPixelIsArea and\\n\"\n                    \"that the linear units are in meters ...attempting to continue\\n\");\n            *raster_type = RasterPixelIsArea;\n            *linear_units = Linear_Meter;\n            *angular_units = -1;\n            *geographic_geotiff    = *geocentric_geotiff  = 0;\n            *map_projected_geotiff = *geotiff_data_exists = 1;\n            return;\n        }\n        else if (*model_type == ModelTypeGeographic) {\n            // Only the model type is known ...guess the rest\n            asfPrintWarning(\"Both the raster type and linear units is missing in the GeoTIFF.  The model\\n\"\n                    \"type is geographic (lat/long), so guessing that the angular units are in decimal\\n\"\n                    \"degrees ...attempting to continue\\n\");\n            *angular_units = Angular_Degree;\n            *linear_units = -1;\n            *geographic_geotiff    = *geotiff_data_exists = 1;\n            *map_projected_geotiff = *geocentric_geotiff  = 0;\n            return;\n        }\n        else if (*model_type == ModelTypeGeocentric) {\n            asfPrintError(\"Geocentric (x, y, z) GeoTIFFs are not supported (yet.)\\n\");\n        }\n        else if (*raster_type == RasterPixelIsArea) {\n            // Only the raster type is known ...guess the rest\n            asfPrintWarning(\"Both the model type and linear units is missing in the GeoTIFF.  The raster\\n\"\n                    \"type is RasterPixelIsArea, so guessing that the model type is map-projected and\\n\"\n                    \"that the linear units are in meters ...attempting to continue\\n\");\n            *model_type = ModelTypeProjected;\n            *linear_units = Linear_Meter;\n            *angular_units = -1;\n            *geographic_geotiff    = *geocentric_geotiff  = 0;\n            *map_projected_geotiff = *geotiff_data_exists = 1;\n            return;\n        }\n        else if (*raster_type == RasterPixelIsPoint) {\n            // Only the raster type is known, but cannot guess the rest... bail.\n            asfPrintError(\"Found invalid or unsupported GeoTIFF.  Raster type is 'point' rather than\\n\"\n                    \"area.  The model type (map projected, geographic, geocentric) is unknown.\\n\"\n                    \"And the linear units are unknown.  Cannot guess what type of GeoTIFF this\\n\"\n                    \"is.  Aborting.\\n\");\n        }\n        else if (*linear_units == Linear_Meter) {\n            // Only linear units is known and it's meters.  Guess map projected and pixels are\n            // area pixels.\n            asfPrintWarning(\"Found GeoTIFF with undefined model and raster type.  Linear units\\n\"\n                    \"is defined to be meters.  Guessing that the GeoTIFF is map-projected and\\n\"\n                    \"that pixels represent area.  Attempting to continue...\\n\");\n            *model_type = ModelTypeProjected;\n            *raster_type = RasterPixelIsArea;\n            *geographic_geotiff    = *geocentric_geotiff  = 0;\n            *map_projected_geotiff = *geotiff_data_exists = 1;\n            return;\n        }\n        else if (*angular_units == Angular_Degree) {\n            // Only linear units is known and it's angular degrees.  Guess geographic and pixels\n            // type is 'who cares'\n            asfPrintWarning(\"Found GeoTIFF with undefined model and raster type.  Linear units\\n\"\n                    \"is defined to be angular degrees.  Guessing that the GeoTIFF is geographic.\\n\"\n                    \"Attempting to continue...\\n\");\n            *model_type = ModelTypeGeographic;\n            *geographic_geotiff    = *geotiff_data_exists = 1;\n            *map_projected_geotiff = *geocentric_geotiff  = 0;\n            return;\n        }\n        else if (*angular_units == Angular_Arc_Second) {\n            // Only linear units is known and it's angular degrees.  Guess geographic and pixels\n            // type is 'who cares'\n            asfPrintWarning(\"Found GeoTIFF with undefined model and raster type.  Linear units\\n\"\n                    \"is defined to be angular degrees.  Guessing that the GeoTIFF is geographic.\\n\"\n                    \"Attempting to continue...\\n\");\n            *model_type = ModelTypeGeographic;\n            *linear_units = -1;\n            *geographic_geotiff    = *geotiff_data_exists = 1;\n            *map_projected_geotiff = *geocentric_geotiff  = 0;\n            return;\n        }\n        else {\n            asfPrintError(\"Found unsupported or invalid GeoTIFF.  Model type and raster type\\n\"\n                    \"is undefined, and linear units are either undefined or of an unsupported\\n\"\n                    \"type.  Aborting...\\n\");\n        }\n    }\n    // Case: No valid keys found\n    else {\n        // All classification parameters are missing!\n        *geographic_geotiff    = *geocentric_geotiff  = 0;\n        *map_projected_geotiff = *geotiff_data_exists = 0;\n        return;\n    }\n}\n\n\nint check_for_datum_in_string(const char *citation, datum_type_t *datum)\n{\n    int ret = 0; // not found\n    return ret;\n}\n\nint check_for_ellipse_definition_in_geotiff(GTIF *input_gtif, spheroid_type_t *spheroid)\n{\n    int ret = 0; // failure\n    return ret;\n}\n\nchar *angular_units_to_string(short angular_units)\n{\n    return\n        (angular_units == Angular_Radian)            ? \"Angular_Radian\"          :\n        (angular_units == Angular_Degree)            ? \"Angular_Degree\"          :\n        (angular_units == Angular_Arc_Minute)        ? \"Angular_Arc_Minute\"      :\n        (angular_units == Angular_Arc_Second)        ? \"Angular_Arc_Second\"      :\n        (angular_units == Angular_Grad)              ? \"Angular_Grad\"            :\n        (angular_units == Angular_Gon)               ? \"Angular_Gon\"             :\n        (angular_units == Angular_DMS)               ? \"Angular_DMS\"             :\n        (angular_units == Angular_DMS_Hemisphere)    ? \"Angular_DMS_Hemisphere\"  :\n                                                        \"Unrecognized unit\";\n}\n\nchar *linear_units_to_string(short linear_units)\n{\n    return\n        (linear_units == Linear_Foot)                        ? \"Linear_Foot\"                         :\n        (linear_units == Linear_Foot_US_Survey)              ? \"Linear_Foot_US_Survey\"               :\n        (linear_units == Linear_Foot_Modified_American)      ? \"Linear_Foot_Modified_American\"       :\n        (linear_units == Linear_Foot_Clarke)                 ? \"Linear_Foot_Clarke\"                  :\n        (linear_units == Linear_Foot_Indian)                 ? \"Linear_Foot_Indian\"                  :\n        (linear_units == Linear_Link)                        ? \"Linear_Link\"                         :\n        (linear_units == Linear_Link_Benoit)                 ? \"Linear_Link_Benoit\"                  :\n        (linear_units == Linear_Link_Sears)                  ? \"Linear_Link_Sears\"                   :\n        (linear_units == Linear_Chain_Benoit)                ? \"Linear_Chain_Benoit\"                 :\n        (linear_units == Linear_Chain_Sears)                 ? \"Linear_Chain_Sears\"                  :\n        (linear_units == Linear_Yard_Sears)                  ? \"Linear_Yard_Sears\"                   :\n        (linear_units == Linear_Yard_Indian)                 ? \"Linear_Yard_Indian\"                  :\n        (linear_units == Linear_Fathom)                      ? \"Linear_Fathom\"                       :\n        (linear_units == Linear_Mile_International_Nautical) ? \"Linear_Mile_International_Nautical\"  :\n                                                                \"Unrecognized unit\";\n}\n\nvoid get_look_up_table_name(char *citation, char **look_up_table)\n{\n    *look_up_table = (char *)MALLOC(256 * sizeof(char));\n    strcpy(*look_up_table, \"UNKNOWN\");\n}\n\n", "meta": {"hexsha": "004e54c3fad96da70085d111d6a24d639c924375", "size": 161520, "ext": "c", "lang": "C", "max_stars_repo_path": "src/libasf_import/import_generic_geotiff.c", "max_stars_repo_name": "glshort/MapReady", "max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z", "max_issues_repo_path": "src/libasf_import/import_generic_geotiff.c", "max_issues_repo_name": "glshort/MapReady", "max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libasf_import/import_generic_geotiff.c", "max_forks_repo_name": "glshort/MapReady", "max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z", "avg_line_length": 42.9460249934, "max_line_length": 159, "alphanum_fraction": 0.5794700347, "num_tokens": 41451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769844, "lm_q2_score": 0.022977368864643504, "lm_q1q2_score": 0.01112977986711938}}
{"text": "/**\n* Copyright 2016 BitTorrent Inc.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n*    http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*/\n#pragma once\n\n#include <scraps/config.h>\n\n#include <scraps/Byte.h>\n\n#if SCRAPS_APPLE\n    #include <scraps/apple/SHA256.h>\n    namespace scraps { using SHA256 = apple::SHA256; }\n#else\n    #include <scraps/sodium/SHA256.h>\n    namespace scraps { using SHA256 = sodium::SHA256; }\n#endif\n\n#include <gsl.h>\n\nnamespace scraps {\n\ntemplate <typename BaseByteType>\nstruct SHA256ByteTag {};\n\ntemplate <typename BaseByteType>\nusing SHA256Byte = StrongByte<SHA256ByteTag<BaseByteType>>;\n\ntemplate <typename ByteT, std::ptrdiff_t N>\nstd::array<SHA256Byte<std::remove_const_t<ByteT>>, SHA256::kHashSize>\nGetSHA256(gsl::span<ByteT, N> data) {\n    std::array<SHA256Byte<std::remove_const_t<ByteT>>, SHA256::kHashSize> ret;\n\n    SHA256 sha256;\n    sha256.update(data.data(), data.size());\n    sha256.finish(ret.data());\n\n    return ret;\n}\n\n} // namespace scraps\n", "meta": {"hexsha": "8752d9df521db540619179c02eb642c141df8b81", "size": 1430, "ext": "h", "lang": "C", "max_stars_repo_path": "include/scraps/SHA256.h", "max_stars_repo_name": "carlbrown/scraps", "max_stars_repo_head_hexsha": "78925a738540415ec04b9cbe23cb319421f44978", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/scraps/SHA256.h", "max_issues_repo_name": "carlbrown/scraps", "max_issues_repo_head_hexsha": "78925a738540415ec04b9cbe23cb319421f44978", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/scraps/SHA256.h", "max_forks_repo_name": "carlbrown/scraps", "max_forks_repo_head_hexsha": "78925a738540415ec04b9cbe23cb319421f44978", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9811320755, "max_line_length": 78, "alphanum_fraction": 0.7314685315, "num_tokens": 368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3738758227716966, "lm_q2_score": 0.02976009211734845, "lm_q1q2_score": 0.011126578926135134}}
{"text": "/* permutation/gsl_permutation.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#ifndef __GSL_PERMUTATION_H__\n#define __GSL_PERMUTATION_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_errno.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\nstruct gsl_permutation_struct\n{\n  size_t size;\n  size_t *data;\n};\n\ntypedef struct gsl_permutation_struct gsl_permutation;\n\ngsl_permutation *gsl_permutation_alloc (const size_t n);\ngsl_permutation *gsl_permutation_calloc (const size_t n);\nvoid gsl_permutation_init (gsl_permutation * p);\nvoid gsl_permutation_free (gsl_permutation * p);\n\nint gsl_permutation_fread (FILE * stream, gsl_permutation * p);\nint gsl_permutation_fwrite (FILE * stream, const gsl_permutation * p);\nint gsl_permutation_fscanf (FILE * stream, gsl_permutation * p);\nint gsl_permutation_fprintf (FILE * stream, const gsl_permutation * p, const char *format);\n\nsize_t gsl_permutation_size (const gsl_permutation * p);\nsize_t * gsl_permutation_data (const gsl_permutation * p);\n\nsize_t gsl_permutation_get (const gsl_permutation * p, const size_t i);\nint gsl_permutation_swap (gsl_permutation * p, const size_t i, const size_t j);\n\nint gsl_permutation_valid (gsl_permutation * p);\nvoid gsl_permutation_reverse (gsl_permutation * p);\nint gsl_permutation_inverse (gsl_permutation * inv, const gsl_permutation * p);\nint gsl_permutation_next (gsl_permutation * p);\nint gsl_permutation_prev (gsl_permutation * p);\n\nextern int gsl_check_range;\n\n#ifdef HAVE_INLINE\n\nextern inline\nsize_t\ngsl_permutation_get (const gsl_permutation * p, const size_t i)\n{\n#ifndef GSL_RANGE_CHECK_OFF\n  if (i >= p->size)\n    {\n      GSL_ERROR_VAL (\"index out of range\", GSL_EINVAL, 0);\n    }\n#endif\n  return p->data[i];\n}\n\n#endif /* HAVE_INLINE */\n\n__END_DECLS\n\n#endif /* __GSL_PERMUTATION_H__ */\n", "meta": {"hexsha": "6f3a413c157afc869156b6b0a86980bbd34eee61", "size": 2665, "ext": "h", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/permutation/gsl_permutation.h", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/permutation/gsl_permutation.h", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/permutation/gsl_permutation.h", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 29.6111111111, "max_line_length": 91, "alphanum_fraction": 0.7651031895, "num_tokens": 695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24508500210441883, "lm_q2_score": 0.04535257926399331, "lm_q1q2_score": 0.011115236984356623}}
{"text": "/*\nCopyright (c) 2011-2013, UT-Battelle, LLC\nAll rights reserved\n\n[PsimagLite, Version 1.0.0]\n[by G.A., Oak Ridge National Laboratory]\n\nUT Battelle Open Source Software License 11242008\n\nOPEN SOURCE LICENSE\n\nSubject to the conditions of this License, each\ncontributor to this software hereby grants, free of\ncharge, to any person obtaining a copy of this software\nand associated documentation files (the \"Software\"), a\nperpetual, worldwide, non-exclusive, no-charge,\nroyalty-free, irrevocable copyright license to use, copy,\nmodify, merge, publish, distribute, and/or sublicense\ncopies of the Software.\n\n1. Redistributions of Software must retain the above\ncopyright and license notices, this list of conditions,\nand the following disclaimer.  Changes or modifications\nto, or derivative works of, the Software should be noted\nwith comments and the contributor and organization's\nname.\n\n2. Neither the names of UT-Battelle, LLC or the\nDepartment of Energy nor the names of the Software\ncontributors may be used to endorse or promote products\nderived from this software without specific prior written\npermission of UT-Battelle.\n\n3. The software and the end-user documentation included\nwith the redistribution, with or without modification,\nmust include the following acknowledgment:\n\n\"This product includes software produced by UT-Battelle,\nLLC under Contract No. DE-AC05-00OR22725  with the\nDepartment of Energy.\"\n\n*********************************************************\nDISCLAIMER\n\nTHE SOFTWARE IS SUPPLIED BY THE COPYRIGHT HOLDERS AND\nCONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\nWARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\nPARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\nCOPYRIGHT OWNER, CONTRIBUTORS, UNITED STATES GOVERNMENT,\nOR THE UNITED STATES DEPARTMENT OF ENERGY BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\nDAMAGE.\n\nNEITHER THE UNITED STATES GOVERNMENT, NOR THE UNITED\nSTATES DEPARTMENT OF ENERGY, NOR THE COPYRIGHT OWNER, NOR\nANY OF THEIR EMPLOYEES, REPRESENTS THAT THE USE OF ANY\nINFORMATION, DATA, APPARATUS, PRODUCT, OR PROCESS\nDISCLOSED WOULD NOT INFRINGE PRIVATELY OWNED RIGHTS.\n\n*********************************************************\n\n*/\n/** \\ingroup PsimagLite */\n/*@{*/\n\n/*! \\file GslWrapper.h\n *\n *  Wrapper for GSL functions and types\n */\n\n#ifndef GSL_WRAPPER_H_\n#define GSL_WRAPPER_H_\n\n#ifdef USE_GSL\n#include <gsl/gsl_integration.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_sf_result.h>\n#include <gsl/gsl_sf_gamma.h>\n#include <gsl/gsl_sf_expint.h>\n#endif\n\n#include <stdexcept>\n#include \"Vector.h\"\n\nnamespace PsimagLite {\n\n#ifndef USE_GSL\nclass GslWrapper {\npublic:\n\ttypedef int DummyType;\n\ttypedef DummyType gsl_integration_workspace;\n\ttypedef double (* GslWrapperFunctionType) (double, void * );\n\ttypedef struct {\n\t\tdouble val;\n\t\tdouble err;\n\t} gsl_sf_result;\n\n\ttypedef void (* gsl_error_handler_t) (const char *,const char *,int,int);\n\n\tstruct gsl_function {\n\t\tGslWrapperFunctionType function;\n\t\tvoid * params;\n\t};\n\n\tgsl_error_handler_t  gsl_set_error_handler (gsl_error_handler_t) const\n\t{\n\n\t\tthereSnoGsl();\n\t\tgsl_error_handler_t *fx = new gsl_error_handler_t();\n\n\t\treturn *fx;\n\t}\n\n\tgsl_integration_workspace * gsl_integration_workspace_alloc (SizeType) const\n\t{\n\t\tthereSnoGsl();\n\t\tint* x = new int;\n\t\treturn x;\n\t}\n\n\tvoid gsl_integration_workspace_free (gsl_integration_workspace*) const\n\t{\n\t\tthereSnoGsl();\n\t}\n\n\tint gsl_integration_qag(const gsl_function*,\n\t                        double,\n\t                        double,\n\t                        double,\n\t                        double,\n\t                        size_t,\n\t                        int,\n\t                        gsl_integration_workspace*,\n\t                        double*,\n\t                        double*) const\n\t{\n\t\tthereSnoGsl();\n\t\treturn 0;\n\t}\n\n\tint gsl_integration_qagiu(gsl_function*,\n\t                          double,\n\t                          double,\n\t                          double,\n\t                          size_t ,\n\t                          gsl_integration_workspace*,\n\t                          double*,\n\t                          double*) const\n\t{\n\t\tthereSnoGsl();\n\t\treturn 0;\n\t}\n\n\tint gsl_integration_qagp (const gsl_function*,\n\t                          double*,\n\t                          SizeType,\n\t                          double,\n\t                          double,\n\t                          SizeType,\n\t                          gsl_integration_workspace*,\n\t                          double*,\n\t                          double*) const\n\t{\n\t\tthereSnoGsl();\n\t\treturn 0;\n\t}\n\n\tint gsl_integration_qagi(gsl_function*,\n\t                         double,\n\t                         double,\n\t                         size_t,\n\t                         gsl_integration_workspace*,\n\t                         double*,\n\t                         double*) const\n\t{\n\t\tthereSnoGsl();\n\t\treturn 0;\n\t}\n\n\tvoid printError(int) const\n\t{\n\t\tthereSnoGsl();\n\t}\n\n\tint gsl_sf_lngamma_complex_e(double,\n\t                             double,\n\t                             gsl_sf_result*,\n\t                             gsl_sf_result*) const\n\t{\n\t\tthereSnoGsl();\n\t\treturn 0;\n\t}\n\n\tint gsl_sf_Ci_e(double, gsl_sf_result*)\n\t{\n\t\tthereSnoGsl();\n\t\treturn 0;\n\t}\n\nprivate:\n\n\tvoid thereSnoGsl() const\n\t{\n\t\tthrow RuntimeError(\"You need to compile with the GSL\\n\");\n\t}\n\n}; // class GslWrapper\n\n#else\n\nclass GslWrapper {\npublic:\n\n\ttypedef ::gsl_integration_workspace gsl_integration_workspace;\n\ttypedef ::gsl_function gsl_function;\n\ttypedef ::gsl_sf_result gsl_sf_result;\n\n\tvoid printError(int status) const\n\t{\n\t\tstd::cerr<<\"GslWrapper: error: \"<<gsl_strerror(status)<<\"\\n\";\n\t}\n\n\tgsl_error_handler_t * gsl_set_error_handler (gsl_error_handler_t * new_handler) const\n\t{\n\t\treturn ::gsl_set_error_handler(new_handler);\n\t}\n\n\tgsl_integration_workspace * gsl_integration_workspace_alloc (SizeType n) const\n\t{\n\t\treturn ::gsl_integration_workspace_alloc(n);\n\t}\n\n\tvoid gsl_integration_workspace_free (gsl_integration_workspace * w) const\n\t{\n\t\treturn ::gsl_integration_workspace_free(w);\n\t}\n\n\tint gsl_integration_qagi(gsl_function* f,\n\t                         double epsabs,\n\t                         double epsrel,\n\t                         size_t limit,\n\t                         gsl_integration_workspace* workspace,\n\t                         double* result,\n\t                         double* abserr) const\n\t{\n\t\treturn ::gsl_integration_qagi(f,epsabs,epsrel,limit,workspace,result,abserr);\n\t}\n\n\tint gsl_integration_qagiu(gsl_function* f,\n\t                          double a,\n\t                          double epsabs,\n\t                          double epsrel,\n\t                          size_t limit,\n\t                          gsl_integration_workspace* workspace,\n\t                          double* result,\n\t                          double* abserr) const\n\t{\n\t\treturn ::gsl_integration_qagiu(f,a,epsabs,epsrel,limit,workspace,result,abserr);\n\t}\n\n\tint gsl_integration_qagp (const gsl_function * f,\n\t                          double * pts,\n\t                          SizeType npts,\n\t                          double epsabs,\n\t                          double epsrel,\n\t                          SizeType limit,\n\t                          gsl_integration_workspace * workspace,\n\t                          double * result,\n\t                          double * abserr) const\n\t{\n\t\treturn ::gsl_integration_qagp(f,\n\t\t                              pts,\n\t\t                              npts,\n\t\t                              epsabs,\n\t\t                              epsrel,\n\t\t                              limit,\n\t\t                              workspace,\n\t\t                              result,\n\t\t                              abserr);\n\t}\n\n\tint gsl_integration_qag(const gsl_function * f,\n\t                        double a,\n\t                        double b,\n\t                        double epsabs,\n\t                        double epsrel,\n\t                        size_t limit,\n\t                        int key,\n\t                        gsl_integration_workspace* workspace,\n\t                        double* result,\n\t                        double* abserr) const\n\t{\n\t\treturn ::gsl_integration_qag(f,\n\t\t                             a,\n\t\t                             b,\n\t\t                             epsabs,\n\t\t                             epsrel,\n\t\t                             limit,\n\t\t                             key,\n\t\t                             workspace,\n\t\t                             result,\n\t\t                             abserr);\n\t}\n\n\tint gsl_sf_lngamma_complex_e(double zr,\n\t                             double zi,\n\t                             gsl_sf_result* lnr,\n\t                             gsl_sf_result* arg) const\n\t{\n\t\treturn ::gsl_sf_lngamma_complex_e(zr, zi, lnr, arg);\n\t}\n\n\tint gsl_sf_Ci_e(double x, gsl_sf_result* result) const\n\t{\n\t\treturn ::gsl_sf_Ci_e(x,result);\n\t}\n\n}; // class GslWrapper\n\n#endif\n\n} // namespace PsimagLite\n\n/*@}*/\n#endif // GSL_WRAPPER_H_\n\n", "meta": {"hexsha": "3163b69288037ee8eeecfa31f9c43667198ea848", "size": 9324, "ext": "h", "lang": "C", "max_stars_repo_path": "src/GslWrapper.h", "max_stars_repo_name": "g1257/PsimagLite", "max_stars_repo_head_hexsha": "1cdeb4530c66cd41bd0c59af9ad2ecb1069ca010", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2015-08-19T16:06:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-05T02:37:47.000Z", "max_issues_repo_path": "src/GslWrapper.h", "max_issues_repo_name": "npatel37/PsimagLiteORNL", "max_issues_repo_head_hexsha": "ffa0ffad75c5db218a9edea1a9581fed98c2648f", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2016-02-02T20:28:21.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-08T22:56:12.000Z", "max_forks_repo_path": "src/GslWrapper.h", "max_forks_repo_name": "npatel37/PsimagLiteORNL", "max_forks_repo_head_hexsha": "ffa0ffad75c5db218a9edea1a9581fed98c2648f", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-04-29T17:28:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-22T03:33:19.000Z", "avg_line_length": 27.8328358209, "max_line_length": 86, "alphanum_fraction": 0.5708923209, "num_tokens": 1957, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2974699426047947, "lm_q2_score": 0.037326886273225016, "lm_q1q2_score": 0.011103626717311944}}
{"text": "#include <gsl/gsl_math.h>\n#include \"gsl_cblas.h\"\n#include \"cblas.h\"\n\nvoid\ncblas_cswap (const int N, void *X, const int incX, void *Y, const int incY)\n{\n#define BASE float\n#include \"source_swap_c.h\"\n#undef BASE\n}\n", "meta": {"hexsha": "a965a3ce622e77632bac3d2e5a7a99e71dcbcbd5", "size": 212, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/cblas/cswap.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/cblas/cswap.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/cblas/cswap.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 17.6666666667, "max_line_length": 75, "alphanum_fraction": 0.7169811321, "num_tokens": 68, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4073334144352605, "lm_q2_score": 0.027169229074096465, "lm_q1q2_score": 0.011066934846325463}}
{"text": "/* matrix/gsl_matrix_long.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_MATRIX_LONG_H__\n#define __GSL_MATRIX_LONG_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_vector_long.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size1;\n  size_t size2;\n  size_t tda;\n  long * data;\n  gsl_block_long * block;\n  int owner;\n} gsl_matrix_long;\n\ntypedef struct\n{\n  gsl_matrix_long matrix;\n} _gsl_matrix_long_view;\n\ntypedef _gsl_matrix_long_view gsl_matrix_long_view;\n\ntypedef struct\n{\n  gsl_matrix_long matrix;\n} _gsl_matrix_long_const_view;\n\ntypedef const _gsl_matrix_long_const_view gsl_matrix_long_const_view;\n\n/* Allocation */\n\nGSL_EXPORT\ngsl_matrix_long *\ngsl_matrix_long_alloc (const size_t n1, const size_t n2);\n\nGSL_EXPORT\ngsl_matrix_long *\ngsl_matrix_long_calloc (const size_t n1, const size_t n2);\n\nGSL_EXPORT\ngsl_matrix_long *\ngsl_matrix_long_alloc_from_block (gsl_block_long * b,\n                                   const size_t offset,\n                                   const size_t n1,\n                                   const size_t n2,\n                                   const size_t d2);\n\nGSL_EXPORT\ngsl_matrix_long *\ngsl_matrix_long_alloc_from_matrix (gsl_matrix_long * m,\n                                    const size_t k1,\n                                    const size_t k2,\n                                    const size_t n1,\n                                    const size_t n2);\n\nGSL_EXPORT\ngsl_vector_long *\ngsl_vector_long_alloc_row_from_matrix (gsl_matrix_long * m,\n                                        const size_t i);\n\nGSL_EXPORT\ngsl_vector_long *\ngsl_vector_long_alloc_col_from_matrix (gsl_matrix_long * m,\n                                        const size_t j);\n\nGSL_EXPORT void gsl_matrix_long_free (gsl_matrix_long * m);\n\n/* Views */\n\nGSL_EXPORT\n_gsl_matrix_long_view\ngsl_matrix_long_submatrix (gsl_matrix_long * m,\n                            const size_t i, const size_t j,\n                            const size_t n1, const size_t n2);\n\nGSL_EXPORT\n_gsl_vector_long_view\ngsl_matrix_long_row (gsl_matrix_long * m, const size_t i);\n\nGSL_EXPORT\n_gsl_vector_long_view\ngsl_matrix_long_column (gsl_matrix_long * m, const size_t j);\n\nGSL_EXPORT\n_gsl_vector_long_view\ngsl_matrix_long_diagonal (gsl_matrix_long * m);\n\nGSL_EXPORT\n_gsl_vector_long_view\ngsl_matrix_long_subdiagonal (gsl_matrix_long * m, const size_t k);\n\nGSL_EXPORT\n_gsl_vector_long_view\ngsl_matrix_long_superdiagonal (gsl_matrix_long * m, const size_t k);\n\nGSL_EXPORT\n_gsl_matrix_long_view\ngsl_matrix_long_view_array (long * base,\n                             const size_t n1,\n                             const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_long_view\ngsl_matrix_long_view_array_with_tda (long * base,\n                                      const size_t n1,\n                                      const size_t n2,\n                                      const size_t tda);\n\n\nGSL_EXPORT\n_gsl_matrix_long_view\ngsl_matrix_long_view_vector (gsl_vector_long * v,\n                              const size_t n1,\n                              const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_long_view\ngsl_matrix_long_view_vector_with_tda (gsl_vector_long * v,\n                                       const size_t n1,\n                                       const size_t n2,\n                                       const size_t tda);\n\n\nGSL_EXPORT\n_gsl_matrix_long_const_view\ngsl_matrix_long_const_submatrix (const gsl_matrix_long * m,\n                                  const size_t i, const size_t j,\n                                  const size_t n1, const size_t n2);\n\nGSL_EXPORT\n_gsl_vector_long_const_view\ngsl_matrix_long_const_row (const gsl_matrix_long * m,\n                            const size_t i);\n\nGSL_EXPORT\n_gsl_vector_long_const_view\ngsl_matrix_long_const_column (const gsl_matrix_long * m,\n                               const size_t j);\n\nGSL_EXPORT\n_gsl_vector_long_const_view\ngsl_matrix_long_const_diagonal (const gsl_matrix_long * m);\n\nGSL_EXPORT\n_gsl_vector_long_const_view\ngsl_matrix_long_const_subdiagonal (const gsl_matrix_long * m,\n                                    const size_t k);\n\nGSL_EXPORT\n_gsl_vector_long_const_view\ngsl_matrix_long_const_superdiagonal (const gsl_matrix_long * m,\n                                      const size_t k);\n\nGSL_EXPORT\n_gsl_matrix_long_const_view\ngsl_matrix_long_const_view_array (const long * base,\n                                   const size_t n1,\n                                   const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_long_const_view\ngsl_matrix_long_const_view_array_with_tda (const long * base,\n                                            const size_t n1,\n                                            const size_t n2,\n                                            const size_t tda);\n\nGSL_EXPORT\n_gsl_matrix_long_const_view\ngsl_matrix_long_const_view_vector (const gsl_vector_long * v,\n                                    const size_t n1,\n                                    const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_long_const_view\ngsl_matrix_long_const_view_vector_with_tda (const gsl_vector_long * v,\n                                             const size_t n1,\n                                             const size_t n2,\n                                             const size_t tda);\n\n/* Operations */\n\nGSL_EXPORT long   gsl_matrix_long_get(const gsl_matrix_long * m, const size_t i, const size_t j);\nGSL_EXPORT void    gsl_matrix_long_set(gsl_matrix_long * m, const size_t i, const size_t j, const long x);\n\nGSL_EXPORT long * gsl_matrix_long_ptr(gsl_matrix_long * m, const size_t i, const size_t j);\nGSL_EXPORT const long * gsl_matrix_long_const_ptr(const gsl_matrix_long * m, const size_t i, const size_t j);\n\nGSL_EXPORT void gsl_matrix_long_set_zero (gsl_matrix_long * m);\nGSL_EXPORT void gsl_matrix_long_set_identity (gsl_matrix_long * m);\nGSL_EXPORT void gsl_matrix_long_set_all (gsl_matrix_long * m, long x);\n\nGSL_EXPORT int gsl_matrix_long_fread (FILE * stream, gsl_matrix_long * m) ;\nGSL_EXPORT int gsl_matrix_long_fwrite (FILE * stream, const gsl_matrix_long * m) ;\nGSL_EXPORT int gsl_matrix_long_fscanf (FILE * stream, gsl_matrix_long * m);\nGSL_EXPORT int gsl_matrix_long_fprintf (FILE * stream, const gsl_matrix_long * m, const char * format);\n\nGSL_EXPORT int gsl_matrix_long_memcpy(gsl_matrix_long * dest, const gsl_matrix_long * src);\nGSL_EXPORT int gsl_matrix_long_swap(gsl_matrix_long * m1, gsl_matrix_long * m2);\n\nGSL_EXPORT int gsl_matrix_long_swap_rows(gsl_matrix_long * m, const size_t i, const size_t j);\nGSL_EXPORT int gsl_matrix_long_swap_columns(gsl_matrix_long * m, const size_t i, const size_t j);\nGSL_EXPORT int gsl_matrix_long_swap_rowcol(gsl_matrix_long * m, const size_t i, const size_t j);\nGSL_EXPORT int gsl_matrix_long_transpose (gsl_matrix_long * m);\nGSL_EXPORT int gsl_matrix_long_transpose_memcpy (gsl_matrix_long * dest, const gsl_matrix_long * src);\n\nGSL_EXPORT long gsl_matrix_long_max (const gsl_matrix_long * m);\nGSL_EXPORT long gsl_matrix_long_min (const gsl_matrix_long * m);\nGSL_EXPORT void gsl_matrix_long_minmax (const gsl_matrix_long * m, long * min_out, long * max_out);\n\nGSL_EXPORT void gsl_matrix_long_max_index (const gsl_matrix_long * m, size_t * imax, size_t *jmax);\nGSL_EXPORT void gsl_matrix_long_min_index (const gsl_matrix_long * m, size_t * imin, size_t *jmin);\nGSL_EXPORT void gsl_matrix_long_minmax_index (const gsl_matrix_long * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);\n\nGSL_EXPORT int gsl_matrix_long_isnull (const gsl_matrix_long * m);\n\nGSL_EXPORT int gsl_matrix_long_add (gsl_matrix_long * a, const gsl_matrix_long * b);\nGSL_EXPORT int gsl_matrix_long_sub (gsl_matrix_long * a, const gsl_matrix_long * b);\nGSL_EXPORT int gsl_matrix_long_mul_elements (gsl_matrix_long * a, const gsl_matrix_long * b);\nGSL_EXPORT int gsl_matrix_long_div_elements (gsl_matrix_long * a, const gsl_matrix_long * b);\nGSL_EXPORT int gsl_matrix_long_scale (gsl_matrix_long * a, const double x);\nGSL_EXPORT int gsl_matrix_long_add_constant (gsl_matrix_long * a, const double x);\nGSL_EXPORT int gsl_matrix_long_add_diagonal (gsl_matrix_long * a, const double x);\n\n/***********************************************************************/\n/* The functions below are obsolete                                    */\n/***********************************************************************/\nGSL_EXPORT int gsl_matrix_long_get_row(gsl_vector_long * v, const gsl_matrix_long * m, const size_t i);\nGSL_EXPORT int gsl_matrix_long_get_col(gsl_vector_long * v, const gsl_matrix_long * m, const size_t j);\nGSL_EXPORT int gsl_matrix_long_set_row(gsl_matrix_long * m, const size_t i, const gsl_vector_long * v);\nGSL_EXPORT int gsl_matrix_long_set_col(gsl_matrix_long * m, const size_t j, const gsl_vector_long * v);\n \n/* inline functions if you are using GCC */\n\n#ifdef HAVE_INLINE\nextern inline \nlong\ngsl_matrix_long_get(const gsl_matrix_long * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_VAL(\"first index out of range\", GSL_EINVAL, 0) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_VAL(\"second index out of range\", GSL_EINVAL, 0) ;\n    }\n#endif\n  return m->data[i * m->tda + j] ;\n} \n\nextern inline \nvoid\ngsl_matrix_long_set(gsl_matrix_long * m, const size_t i, const size_t j, const long x)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_VOID(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_VOID(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  m->data[i * m->tda + j] = x ;\n}\n\nextern inline \nlong *\ngsl_matrix_long_ptr(gsl_matrix_long * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  return (long *) (m->data + (i * m->tda + j)) ;\n} \n\nextern inline \nconst long *\ngsl_matrix_long_const_ptr(const gsl_matrix_long * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  return (const long *) (m->data + (i * m->tda + j)) ;\n} \n\n#endif\n\n__END_DECLS\n\n#endif /* __GSL_MATRIX_LONG_H__ */\n", "meta": {"hexsha": "5344f4aafce92e8f5f09d82ce1697697776d77ba", "size": 11396, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/gsl/include/gsl/gsl_matrix_long.h", "max_stars_repo_name": "dynaryu/vaws", "max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/gsl/include/gsl/gsl_matrix_long.h", "max_issues_repo_name": "dynaryu/vaws", "max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/gsl/include/gsl/gsl_matrix_long.h", "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2244897959, "max_line_length": 133, "alphanum_fraction": 0.6735696736, "num_tokens": 2791, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3886180125441397, "lm_q2_score": 0.02843603139812985, "lm_q1q2_score": 0.011050754006583976}}
{"text": "#ifndef __GSL_PERMUTE_H__\n#define __GSL_PERMUTE_H__\n\n#include <gsl/gsl_permute_complex_long_double.h>\n#include <gsl/gsl_permute_complex_double.h>\n#include <gsl/gsl_permute_complex_float.h>\n\n#include <gsl/gsl_permute_long_double.h>\n#include <gsl/gsl_permute_double.h>\n#include <gsl/gsl_permute_float.h>\n\n#include <gsl/gsl_permute_ulong.h>\n#include <gsl/gsl_permute_long.h>\n\n#include <gsl/gsl_permute_uint.h>\n#include <gsl/gsl_permute_int.h>\n\n#include <gsl/gsl_permute_ushort.h>\n#include <gsl/gsl_permute_short.h>\n\n#include <gsl/gsl_permute_uchar.h>\n#include <gsl/gsl_permute_char.h>\n\n#endif /* __GSL_PERMUTE_H__ */\n", "meta": {"hexsha": "c15f062731acb7d31aed83822010206fd4a7c649", "size": 614, "ext": "h", "lang": "C", "max_stars_repo_path": "gsl-2.6/gsl/gsl_permute.h", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gsl-2.6/gsl/gsl_permute.h", "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gsl-2.6/gsl/gsl_permute.h", "max_forks_repo_name": "ielomariala/Hex-Game", "max_forks_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-30T20:40:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-30T20:40:25.000Z", "avg_line_length": 24.56, "max_line_length": 48, "alphanum_fraction": 0.8045602606, "num_tokens": 190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.359364131437828, "lm_q2_score": 0.03067580381531843, "lm_q1q2_score": 0.011023783594249117}}
{"text": "//  This matrix class is a C++ wrapper for the GNU Scientific Library\n//  Copyright (C)  ULP-IPB Strasbourg\n\n//  This program is free software; you can redistribute it and/or modify\n//  it under the terms of the GNU General Public License as published by\n//  the Free Software Foundation; either version 2 of the License, or\n//  (at your option) any later version.\n\n//  This program is distributed in the hope that it will be useful,\n//  but WITHOUT ANY WARRANTY; without even the implied warranty of\n//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n//  GNU General Public License for more details.\n\n//  You should have received a copy of the GNU General Public License\n//  along with this program; if not, write to the Free Software\n//  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\n#ifndef _vector_#type#_h\n#define _vector_#type#_h\n\n#ifdef __HP_aCC\n#include <iostream.h>\n#else \n#include <iostream>\n#endif\n\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_vector#typeext#.h>\n#include <gsl/gsl_blas.h>\n#include <gslwrap/vector_double.h>\n\n//#define NDEBUG 0\n\n#include <assert.h>\nnamespace gsl\n{\n\n#ifndef __HP_aCC\n\tusing std::ostream;\n//using std::string;\n//using std::runtime_error;\n#endif\n\nclass vector#typeext#_view;\n\nclass vector#typeext#\n{\nprotected:\n\tgsl_vector#typeext# *gsldata;\n\tvoid free(){if(gsldata) gsl_vector#typeext#_free(gsldata);gsldata=NULL;}\n\tvoid alloc(size_t n) {gsldata=gsl_vector#typeext#_alloc(n);}\n\tvoid calloc(size_t n){gsldata=gsl_vector#typeext#_calloc(n);}\npublic:\n\ttypedef #type# value_type;\n\tvector#typeext#() : gsldata(NULL) {;}\n\tvector#typeext#( const vector#typeext# &other ):gsldata(NULL) {copy(other);}\n\ttemplate<class oclass>\n\tvector#typeext#( const oclass &other ):gsldata(NULL) {copy(other);}\n\t~vector#typeext#(){free();}\n\tvector#typeext#(const size_t& n,bool clear=true)\n\t{\n\t\tif(clear){this->calloc(n);}\n\t\telse     {this->alloc(n);}\n\t}\n\tvector#typeext#(const int& n,bool clear=true)\n\t{\n\t\tif(clear){this->calloc(n);}\n\t\telse     {this->alloc(n);}\n\t}\n\t\n\tvoid resize(size_t n);\n\n\ttemplate <class oclass>\n\t\tvoid copy(const oclass &other)\n\t\t{\n\t\t\tif ( static_cast<const void *>( this ) == static_cast<const void *>( &other ) )\n\t\t\t\treturn;\n\n\t\t\tif (!other.is_set())\n\t\t\t{\n\t\t\t\tgsldata=NULL;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tresize(other.size());\n\t\t\tfor (size_t i=0;i<size();i++)\n\t\t\t{\n\t\t\t\tgsl_vector#typeext#_set(gsldata, i, (#type#)other[i]);\n\t\t\t}\n\t\t}\n\tvoid copy(const vector#typeext#& other);\n\tbool is_set() const{if (gsldata) return true; else return false;}\n//\tvoid clone(vector#typeext#& other);\n\t\n//\tsize_t size() const {if (!gsldata) {cout << \"vector#typeext#::size vector not initialized\" << endl; exit(-1);}return gsldata->size;}\n\tsize_t size() const {assert (gsldata); return gsldata->size;}\n\n\t/** for interfacing with gsl c */\n/*  \tgsl_vector#typeext#       *gslobj()       {if (!gsldata){cout << \"vector#typeext#::gslobj ERROR, data not initialized!! \" << endl; exit(-1);}return gsldata;} */\n/*  \tconst gsl_vector#typeext# *gslobj() const {if (!gsldata){cout << \"vector#typeext#::gslobj ERROR, data not initialized!! \" << endl; exit(-1);}return gsldata;} */\n\tgsl_vector#typeext#       *gslobj()       {assert(gsldata);return gsldata;}\n\tconst gsl_vector#typeext# *gslobj() const {assert(gsldata);return gsldata;}\n\n\n\tstatic vector#typeext#_view create_vector_view( const gsl_vector#typeext#_view &other );\n\n// ********Accessing vector elements\n\n//  Unlike FORTRAN compilers, C compilers do not usually provide support for range checking of vectors and matrices (2). However, the functions gsl_vector#typeext#_get and gsl_vector#typeext#_set can perform range checking for you and report an error if you attempt to access elements outside the allowed range. \n\n//  The functions for accessing the elements of a vector or matrix are defined in `gsl_vector#typeext#.h' and declared extern inline to eliminate function-call overhead. If necessary you can turn off range checking completely without modifying any source files by recompiling your program with the preprocessor definition GSL_RANGE_CHECK_OFF. Provided your compiler supports inline functions the effect of turning off range checking is to replace calls to gsl_vector#typeext#_get(v,i) by v->data[i*v->stride] and and calls to gsl_vector#typeext#_set(v,i,x) by v->data[i*v->stride]=x. Thus there should be no performance penalty for using the range checking functions when range checking is turned off. \n\n//      This function returns the i-th element of a vector v. If i lies outside the allowed range of 0 to n-1 then the error handler is invoked and 0 is returned. \n\t#type# get(size_t i) const {return gsl_vector#typeext#_get(gsldata,i);}\n\n//      This function sets the value of the i-th element of a vector v to x. If i lies outside the allowed range of 0 to n-1 then the error handler is invoked. \n\tvoid  set(size_t i,#type# x){gsl_vector#typeext#_set(gsldata,i,x);}\n\n//      These functions return a pointer to the i-th element of a vector v. If i lies outside the allowed range of 0 to n-1 then the error handler is invoked\n\t#type#       &operator[](size_t i)       { return *gsl_vector#typeext#_ptr(gsldata,i);}\n\tconst #type# &operator[](size_t i) const { return *gsl_vector#typeext#_ptr(gsldata,i);}\n\n\t#type#       &operator()(size_t i)       { return *gsl_vector#typeext#_ptr(gsldata,i);}\n\tconst #type# &operator()(size_t i) const { return *gsl_vector#typeext#_ptr(gsldata,i);}\n\n\n//  ***** Initializing vector elements\n\n//      This function sets all the elements of the vector v to the value x. \n\tvoid set_all(#type# x){gsl_vector#typeext#_set_all (gsldata,x);}\n//      This function sets all the elements of the vector v to zero. \n\tvoid set_zero(){gsl_vector#typeext#_set_zero (gsldata);}\n\n//      This function makes a basis vector by setting all the elements of the vector v to zero except for the i-th element which is set to one. \n\tint set_basis (size_t i) {return gsl_vector#typeext#_set_basis (gsldata,i);}\n\n//  **** Reading and writing vectors\n\n//  The library provides functions for reading and writing vectors to a file as binary data or formatted text. \n\n\n//      This function writes the elements of the vector v to the stream stream in binary format. The return value is 0 for success and GSL_EFAILED if there was a problem writing to the file. Since the data is written in the native binary format it may not be portable between different architectures. \n\tint fwrite (FILE * stream) const {return gsl_vector#typeext#_fwrite (stream, gsldata);}\n\n//      This function reads into the vector v from the open stream stream in binary format. The vector v must be preallocated with the correct length since the function uses the size of v to determine how many bytes to read. The return value is 0 for success and GSL_EFAILED if there was a problem reading from the file. The data is assumed to have been written in the native binary format on the same architecture. \n\tint fread (FILE * stream) {return gsl_vector#typeext#_fread (stream, gsldata);}\n\n\tvoid load( const char *filename );\n\t///\n\tvoid save( const char *filename ) const;\n\n//      This function writes the elements of the vector v line-by-line to the stream stream using the format specifier format, which should be one of the %g, %e or %f formats for floating point numbers and %d for integers. The function returns 0 for success and GSL_EFAILED if there was a problem writing to the file. \n\tint fprintf (FILE * stream, const char * format) const {return gsl_vector#typeext#_fprintf (stream, gsldata,format) ;}\n\n//      This function reads formatted data from the stream stream into the vector v. The vector v must be preallocated with the correct length since the function uses the size of v to determine how many numbers to read. The function returns 0 for success and GSL_EFAILED if there was a problem reading from the file. \n\tint fscanf (FILE * stream)  {return gsl_vector#typeext#_fscanf (stream, gsldata); }\n\n\n\n\n//  ******* Vector views\n\n//  In addition to creating vectors from slices of blocks it is also possible to slice vectors and create vector views. For example, a subvector of another vector can be described with a view, or two views can be made which provide access to the even and odd elements of a vector. \n\n//  A vector view is a temporary object, stored on the stack, which can be used to operate on a subset of vector elements. Vector views can be defined for both constant and non-constant vectors, using separate types that preserve constness. A vector view has the type gsl_vector#typeext#_view and a constant vector view has the type gsl_vector#typeext#_const_view. In both cases the elements of the view can be accessed as a gsl_vector#typeext# using the vector component of the view object. A pointer to a vector of type gsl_vector#typeext# * or const gsl_vector#typeext# * can be obtained by taking the address of this component with the & operator. \n\n//      These functions return a vector view of a subvector of another vector v. The start of the new vector is offset by offset elements from the start of the original\n//      vector. The new vector has n elements. Mathematically, the i-th element of the new vector v' is given by, \n\n//      v'(i) = v->data[(offset + i)*v->stride]\n\n//      where the index i runs from 0 to n-1. \n\n//      The data pointer of the returned vector struct is set to null if the combined parameters (offset,n) overrun the end of the original vector. \n\n//      The new vector is only a view of the block underlying the original vector, v. The block containing the elements of v is not owned by the new vector. When the\n//      new vector goes out of scope the original vector v and its block will continue to exist. The original memory can only be deallocated by freeing the original vector.\n//      Of course, the original vector should not be deallocated while the new vector is still in use. \n\n//      The function gsl_vector#typeext#_const_subvector is equivalent to gsl_vector#typeext#_subvector but can be used for vectors which are declared const. \n\tvector#typeext#_view subvector (size_t offset, size_t n);\n\tconst vector#typeext#_view subvector (size_t offset, size_t n) const;\n//\tvector#typeext#_const_view subvector (size_t offset, size_t n) const;\n\n//  \tclass view\n//  \t{\n//  \t\tgsl_vector#typeext#_view *gsldata;\n//  \tpublic:\n//  \t\tview();\n//  \t};\n//  \tview subvector(size_t offset, size_t n)\n//  \t{\n//  \t\treturn view(gsl_vector#typeext#_subvector(gsldata,offset,n);\n//  \t}\n//  \tconst view subvector(size_t offset, size_t n) const\n//  \t{\n//  \t\treturn view(gsl_vector#typeext#_const_subvector(gsldata,offset,n);\n//  \t}\n\n\n\n//  Function: gsl_vector#typeext# gsl_vector#typeext#_subvector_with_stride (gsl_vector#typeext# *v, size_t offset, size_t stride, size_t n) \n//  Function: gsl_vector#typeext#_const_view gsl_vector#typeext#_const_subvector_with_stride (const gsl_vector#typeext# * v, size_t offset, size_t stride, size_t n) \n//      These functions return a vector view of a subvector of another vector v with an additional stride argument. The subvector is formed in the same way as for\n//      gsl_vector#typeext#_subvector but the new vector has n elements with a step-size of stride from one element to the next in the original vector. Mathematically,\n//      the i-th element of the new vector v' is given by, \n\n//      v'(i) = v->data[(offset + i*stride)*v->stride]\n\n//      where the index i runs from 0 to n-1. \n\n//      Note that subvector views give direct access to the underlying elements of the original vector. For example, the following code will zero the even elements of the\n//      vector v of length n, while leaving the odd elements untouched, \n\n//      gsl_vector#typeext#_view v_even = gsl_vector#typeext#_subvector_with_stride (v, 0, 2, n/2);\n//      gsl_vector#typeext#_set_zero (&v_even.vector);\n\n//      A vector view can be passed to any subroutine which takes a vector argument just as a directly allocated vector would be, using &view.vector. For example, the\n//      following code computes the norm of odd elements of v using the BLAS routine DNRM2, \n\n//      gsl_vector#typeext#_view v_odd = gsl_vector#typeext#_subvector_with_stride (v, 1, 2, n/2);\n//      double r = gsl_blas_dnrm2 (&v_odd.vector);\n\n//      The function gsl_vector#typeext#_const_subvector_with_stride is equivalent to gsl_vector#typeext#_subvector_with_stride but can be used for\n//      vectors which are declared const. \n\n//  Function: gsl_vector#typeext#_view gsl_vector#typeext#_complex_real (gsl_vector#typeext#_complex *v) \n//  Function: gsl_vector#typeext#_const_view gsl_vector#typeext#_complex_const_real (const gsl_vector#typeext#_complex *v) \n//      These functions return a vector view of the real parts of the complex vector v. \n\n//      The function gsl_vector#typeext#_complex_const_real is equivalent to gsl_vector#typeext#_complex_real but can be used for vectors which are declared\n//      const. \n\n//  Function: gsl_vector#typeext#_view gsl_vector#typeext#_complex_imag (gsl_vector#typeext#_complex *v) \n//  Function: gsl_vector#typeext#_const_view gsl_vector#typeext#_complex_const_imag (const gsl_vector#typeext#_complex *v) \n//      These functions return a vector view of the imaginary parts of the complex vector v. \n\n//      The function gsl_vector#typeext#_complex_const_imag is equivalent to gsl_vector#typeext#_complex_imag but can be used for vectors which are declared\n//      const. \n\n//  Function: gsl_vector#typeext#_view gsl_vector#typeext#_view_array (double *base, size_t n) \n//  Function: gsl_vector#typeext#_const_view gsl_vector#typeext#_const_view_array (const double *base, size_t n) \n//      These functions return a vector view of an array. The start of the new vector is given by base and has n elements. Mathematically, the i-th element of the new\n//      vector v' is given by, \n\n//      v'(i) = base[i]\n\n//      where the index i runs from 0 to n-1. \n\n//      The array containing the elements of v is not owned by the new vector view. When the view goes out of scope the original array will continue to exist. The\n//      original memory can only be deallocated by freeing the original pointer base. Of course, the original array should not be deallocated while the view is still in use. \n\n//      The function gsl_vector#typeext#_const_view_array is equivalent to gsl_vector#typeext#_view_array but can be used for vectors which are declared const. \n\n//  Function: gsl_vector#typeext#_view gsl_vector#typeext#_view_array_with_stride (double * base, size_t stride, size_t n) \n//  Function: gsl_vector#typeext#_const_view gsl_vector#typeext#_const_view_array_with_stride (const double * base, size_t stride, size_t n) \n//      These functions return a vector view of an array base with an additional stride argument. The subvector is formed in the same way as for\n//      gsl_vector#typeext#_view_array but the new vector has n elements with a step-size of stride from one element to the next in the original array. Mathematically,\n//      the i-th element of the new vector v' is given by, \n\n//      v'(i) = base[i*stride]\n\n//      where the index i runs from 0 to n-1. \n\n//      Note that the view gives direct access to the underlying elements of the original array. A vector view can be passed to any subroutine which takes a vector\n//      argument just as a directly allocated vector would be, using &view.vector. \n\n//      The function gsl_vector#typeext#_const_view_array_with_stride is equivalent to gsl_vector#typeext#_view_array_with_stride but can be used for\n//      arrays which are declared const. \n\n\n//  ************* Copying vectors\n\n//  Common operations on vectors such as addition and multiplication are available in the BLAS part of the library (see section BLAS Support). However, it is useful to have a small number of utility functions which do not require the full BLAS code. The following functions fall into this category. \n\n//      This function copies the elements of the vector src into the vector dest.\n\tvector#typeext#& operator=(const vector#typeext#& other){copy(other);return (*this);}\n\n//  Function: int gsl_vector#typeext#_swap (gsl_vector#typeext# * v, gsl_vector#typeext# * w) \n//      This function exchanges the elements of the vectors v and w by copying. The two vectors must have the same length. \n\n//  ***** Exchanging elements\n\n//  The following function can be used to exchange, or permute, the elements of a vector. \n\n//  Function: int gsl_vector#typeext#_swap_elements (gsl_vector#typeext# * v, size_t i, size_t j) \n//      This function exchanges the i-th and j-th elements of the vector v in-place. \n\tint swap_elements (size_t i, size_t j) {return gsl_vector#typeext#_swap_elements (gsldata, i,j);}\n\n//  Function: int gsl_vector#typeext#_reverse (gsl_vector#typeext# * v) \n//      This function reverses the order of the elements of the vector v. \n\tint reverse () {return  gsl_vector#typeext#_reverse (gsldata) ;}\n\n// ******* Vector operations\n\n//  The following operations are only defined for real vectors. \n\n//      This function adds the elements of vector b to the elements of vector a, a'_i = a_i + b_i. The two vectors must have the same length. \n\tint operator+=(const vector#typeext# &other) {return gsl_vector#typeext#_add (gsldata, other.gsldata);}\n\n//      This function subtracts the elements of vector b from the elements of vector a, a'_i = a_i - b_i. The two vectors must have the same length. \n\tint operator-=(const vector#typeext# &other) {return gsl_vector#typeext#_sub (gsldata, other.gsldata);}\n\n//  Function: int gsl_vector#typeext#_mul (gsl_vector#typeext# * a, const gsl_vector#typeext# * b) \n//      This function multiplies the elements of vector a by the elements of vector b, a'_i = a_i * b_i. The two vectors must have the same length. \n\tint operator*=(const vector#typeext# &other) {return gsl_vector#typeext#_mul (gsldata, other.gsldata);}\n\n//      This function divides the elements of vector a by the elements of vector b, a'_i = a_i / b_i. The two vectors must have the same length. \n\tint operator/=(const vector#typeext# &other) {return gsl_vector#typeext#_div (gsldata, other.gsldata);}\n\n//      This function multiplies the elements of vector a by the constant factor x, a'_i = x a_i. \n\tint operator*=(#type# x) {return gsl_vector#typeext#_scale (gsldata, x);}\n\n//  Function: int gsl_vector#typeext#_add_constant (gsl_vector#typeext# * a, const double x) \n//      This function adds the constant value x to the elements of the vector a, a'_i = a_i + x. \n\tint operator+=(#type# x) {return gsl_vector#typeext#_add_constant (gsldata,x);}\n\n//      This function multiplies the elements of vector a by the constant factor x, a'_i = x a_i. \n\tint operator/=(#type# x) {return gsl_vector#typeext#_scale (gsldata, 1/x);}\n\n// bool operators:\n\tbool operator==(const vector#typeext#& other) const;\n\tbool operator!=(const vector#typeext#& other) const { return (!((*this)==other));}\n\n// stream output:\n//\tfriend ostream& operator<< ( ostream& os, const vector#typeext#& vect );\n\t/** returns sum of all the vector elements. */\n    #type# sum() const;\n\t// returns sqrt(v.t*v);\n    double norm2() const;\n\n\n// **** Finding maximum and minimum elements of vectors\n\n//      This function returns the maximum value in the vector v. \n    double max() const{return gsl_vector#typeext#_max (gsldata) ;}\n\n//  Function: double gsl_vector#typeext#_min (const gsl_vector#typeext# * v) \n//      This function returns the minimum value in the vector v. \n    double min() const{return gsl_vector#typeext#_min (gsldata) ;}\n\n//  Function: void gsl_vector#typeext#_minmax (const gsl_vector#typeext# * v, double * min_out, double * max_out) \n//      This function returns the minimum and maximum values in the vector v, storing them in min_out and max_out. \n\n//      This function returns the index of the maximum value in the vector v. When there are several equal maximum elements then the lowest index is returned. \n\tsize_t max_index(){return gsl_vector#typeext#_max_index (gsldata);}\n\n//  Function: size_t gsl_vector#typeext#_min_index (const gsl_vector#typeext# * v) \n//      This function returns the index of the minimum value in the vector v. When there are several equal minimum elements then the lowest index is returned. \n\tsize_t min_index(){return gsl_vector#typeext#_min_index (gsldata);}\n\n//  Function: void gsl_vector#typeext#_minmax_index (const gsl_vector#typeext# * v, size_t * imin, size_t * imax) \n//      This function returns the indices of the minimum and maximum values in the vector v, storing them in imin and imax. When there are several equal minimum\n//      or maximum elements then the lowest indices are returned. \n\n//  Vector properties\n\n//  Function: int gsl_vector#typeext#_isnull (const gsl_vector#typeext# * v) \n//      This function returns 1 if all the elements of the vector v are zero, and 0 otherwise. };\n\tbool isnull(){return gsl_vector#typeext#_isnull (gsldata);}\n};\n\n// When you add create a view it will stick to its with the view until you call change_view\n// ex:\n// matrix_float m(5,5);\n// vector_float v(5); \n// // ... \n// m.column(3) = v; //the 3rd column of the matrix m will equal v. \nclass vector#typeext#_view : public vector#typeext#\n{\n public:\n\tvector#typeext#_view(const vector#typeext#&     other) :vector#typeext#(){init(other);}\n\tvector#typeext#_view(const vector#typeext#_view& other):vector#typeext#(){init(other);}\n\tvector#typeext#_view(const gsl_vector#typeext#& gsl_other) : vector#typeext#() {init_with_gsl_vector(gsl_other);}\n\n\tvoid init(const vector#typeext#& other);\n\tvoid init_with_gsl_vector(const gsl_vector#typeext#& gsl_other);\n\tvoid change_view(const vector#typeext#& other){init(other);}\n private:\n};\n\nostream& operator<< ( ostream& os, const vector#typeext# & vect );\n\n\n// vector_type<>::type is a template interface to vector_?\n// it is usefull for in templated situations for getting the correct vector type\n#define tmp_type_is#typeext#\n#ifdef tmp_type_is\ntypedef vector vector_double;\ntemplate<class T> \nstruct vector_type  {typedef vector_double   type;};\n\ntemplate<class T> \nstruct value_type  {typedef double   type;};\n\n#else\ntemplate<> struct vector_type<#type#> {typedef vector#typeext# type;};\n#endif\n#undef tmp_type_is#typeext#\n\n}\n#endif// _vector_#type#_h\n", "meta": {"hexsha": "f421ee0b7eb1b986147496102a95e3b1a0eeac78", "size": 22209, "ext": "h", "lang": "C", "max_stars_repo_path": "src/gslwrap/vector_source.h", "max_stars_repo_name": "entn-at/GlottDNN", "max_stars_repo_head_hexsha": "b7db669d7f34da92ab34742d75a8ba3c70763a65", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gslwrap/vector_source.h", "max_issues_repo_name": "entn-at/GlottDNN", "max_issues_repo_head_hexsha": "b7db669d7f34da92ab34742d75a8ba3c70763a65", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gslwrap/vector_source.h", "max_forks_repo_name": "entn-at/GlottDNN", "max_forks_repo_head_hexsha": "b7db669d7f34da92ab34742d75a8ba3c70763a65", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.2462686567, "max_line_length": 702, "alphanum_fraction": 0.7351524157, "num_tokens": 5758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3702253786982541, "lm_q2_score": 0.029760095667014458, "lm_q1q2_score": 0.0110179426884167}}
{"text": "/*\n * The MIT License is a permissive free software license, which permits reuse\n * within both open source and proprietary software. The software is licensed\n * as is, and no warranty is given as to fitness for purpose or absence of\n * infringement of third parties' rights, such as patents. Generally use for\n * research activities is allowed regardless of any third party patents, but\n * commercial use may be subject to a separate license.\n *\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2015 Tuomo Raitio\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *\n *\n *\n * <><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>\n *                  GlottHMM Speech Synthesis\n * <><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>\n *\n * This program reads speech parameters and a glottal pulse/\n * pulse library, and synthesizes speech from them.\n *\n * This program has been written in Aalto University,\n * Department of Signal Processign and Acoustics, Espoo, Finland\n *\n * Main author: Tuomo Raitio\n * Acknowledgements: Antti Suni, Paavo Alku, Martti Vainio\n *\n * File SynthesisFunctions.c\n * Version: 1.1\n *\n */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <time.h>\n#include <string.h>\n#include <sndfile.h> \t\t\t\t/* Read and write wav */\n#include <gsl/gsl_vector.h>\t\t\t/* GSL, Vector */\n#include <gsl/gsl_matrix.h>\t\t\t/* GSL, Matrix */\n#include <gsl/gsl_fft_real.h>\t\t/* GSL, FFT */\n#include <gsl/gsl_fft_complex.h>\t/* GSL, FFT complex */\n#include <gsl/gsl_fft_halfcomplex.h>/* GSL, FFT halfcomplex */\n#include <gsl/gsl_permutation.h>\t/* GSL, Permutations */\n#include <gsl/gsl_linalg.h>\t\t\t/* GSL, Linear algebra */\n#include <gsl/gsl_spline.h>\t\t\t/* GSL, Interpolation */\n#include <gsl/gsl_errno.h>\t\t\t/* GSL, Error handling */\n#include <gsl/gsl_poly.h>\t\t\t/* GSL, Polynomials */\n#include <gsl/gsl_sort_double.h>\t/* GSL, Sort double */\n#include <gsl/gsl_sort_vector.h>\t/* GSL, Sort vector */\n#include <gsl/gsl_complex.h>\t\t/* GSL, Complex numbers */\n#include <gsl/gsl_complex_math.h>\t/* GSL, Arithmetic operations for complex numbers */\n#include <gsl/gsl_rng.h>\t\t\t/* GSL, Random number generation */\n#include <gsl/gsl_randist.h>\t\t/* GSL, Random number generation */\n#include <libconfig.h>\n#include \"SynthesisFunctions.h\"\n\n\n\n\n\n\n\n\n\n\n/**\n * Function Check_command_line\n *\n * Checks command line formant and prints instructions\n *\n * @param argc number of input arguments\n */\nint Check_command_line(int argc) {\n\n\tif (argc < 3 || argc > 4) {\n\n\t\t/* Incorrect command line, print instructions */\n\t\tprintf(\"\\n<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>\\n\");\n\t\tprintf(\"             GlottHMM - Speech Synthesizer (%s)\\n\",VERSION);\n\t\tprintf(\"<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>\\n\\n\");\n\t\tprintf(\"Description:\\n\\n\");\n\t\tprintf(\"    Synthesis of speech signal according to speech parameters.\\n\\n\");\n\t\tprintf(\"Usage:\\n\\n\");\n\t\tprintf(\"    Synthesis file_name config_default config_user\\n\\n\");\n\t\tprintf(\"\tfile_name       - File name without extensions (.wav, .lab)\\n\");\n\t\tprintf(\"\tconfig_default  - Default config file name\\n\");\n\t\tprintf(\"\tconfig_user     - User config file name (OPTIONAL)\\n\\n\");\n\t\tprintf(\"    Synthesized speech signal is saved to \\\"file_name.syn.wav\\\".\\n\\n\");\n\t\tprintf(\"Version:\\n\\n\");\n\t\tprintf(\"    %s (%s)\\n\\n\",VERSION,DATE);\n\t\treturn EXIT_FAILURE;\n\t} else {\n\n\t\t/* Correct command line, print program title */\n\t\tprintf(\"\\n<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>\\n\");\n\t\tprintf(\"                  Speech Synthesizer (%s)\\n\",VERSION);\n\t\tprintf(\"<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>\\n\\n\");\n\t\treturn EXIT_SUCCESS;\n\t}\n}\n\n\n\n\n/**\n * Function Read_config\n *\n * Read configuration file\n *\n * @param filename name of the configuration file\n * @return conf pointer to configuration structure\n */\nstruct config_t *Read_config(char *filename) {\n\n\tstruct config_t *conf = (struct config_t *)malloc(sizeof(struct config_t));\n\tconfig_init(conf);\n\tif(config_read_file(conf,filename) != CONFIG_TRUE) {\n\t\tprintf(\"\\nError reading configuration file \\\"%s\\\", line %i\\n\",filename,config_error_line(conf));\n\t\tprintf(\"%s\\n\",config_error_text(conf));\n\t\tconfig_destroy(conf);\n\t\tfree(conf);\n\t\treturn NULL;\n\t}\n\treturn conf;\n}\n\n\n\n\n\n\n\n/**\n * Function Assign_config_parameters\n *\n * Assign configuration parameters to variables. Destroy and free config file.\n *\n * @param conf config file\n * @param params parameter structure\n */\nint Assign_config_parameters(const char *filename, struct config_t *conf, PARAM *params, int conf_type) {\n\n\tint i,bool,multisyn_old = 0,synlistlen_old = 0;\n\tlong int ival;\n\tdouble fval;\n\tconst char *tmp;\n\tconst config_setting_t *paramweights_conf;\n\tconst config_setting_t *dnn_dim_conf;\n\n\t/* For synthesis list */\n\tif(conf_type == DEF_CONF) {\n\t\tmultisyn_old = 0;\n\t\tsynlistlen_old = 0;\n\t} else if(conf_type == USR_CONF) {\n\t\tmultisyn_old = params->multisyn;\n\t\tsynlistlen_old = params->synlistlen;\n\t}\n\n\t/* Assign configuration file parameters */\n\tif(config_lookup(conf,SAMPLING_FREQUENCY) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\", SAMPLING_FREQUENCY);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,SAMPLING_FREQUENCY) != NULL) {\n\t\tconfig_lookup_int(conf, SAMPLING_FREQUENCY,&ival);\n\t\tparams->FS = (int)ival;\n\t}\n\tif(config_lookup(conf,FRAME_LENGTH) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\", FRAME_LENGTH);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,FRAME_LENGTH) != NULL) {\n\t\tconfig_lookup_float(conf, FRAME_LENGTH,&fval);\n\t\tparams->frame_length_ms = fval;\n\t}\n\tif(config_lookup(conf,FRAME_SHIFT) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\", FRAME_SHIFT);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,FRAME_SHIFT) != NULL) {\n\t\tconfig_lookup_float(conf, FRAME_SHIFT,&fval);\n\t\tparams->shift_ms = fval;\n\t}\n\tif(config_lookup(conf,F0_FRAME_LENGTH) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\", F0_FRAME_LENGTH);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,F0_FRAME_LENGTH) != NULL) {\n\t\tconfig_lookup_float(conf, F0_FRAME_LENGTH,&fval);\n\t\tparams->f0_frame_length_ms = fval;\n\t}\n\tif(config_lookup(conf,LPC_ORDER) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\",LPC_ORDER);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,LPC_ORDER) != NULL) {\n\t\tconfig_lookup_int(conf,LPC_ORDER,&ival);\n\t\tparams->lpc_order_vt = (int)ival;\n\t}\n\tif(config_lookup(conf,LPC_ORDER_SOURCE) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\",LPC_ORDER_SOURCE);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,LPC_ORDER_SOURCE) != NULL) {\n\t\tconfig_lookup_int(conf,LPC_ORDER_SOURCE,&ival);\n\t\tparams->lpc_order_gl = (int)ival;\n\t}\n\tif(config_lookup(conf,WARPING_VT) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\",WARPING_VT);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,WARPING_VT) != NULL) {\n\t\tconfig_lookup_float(conf,WARPING_VT,&fval);\n\t\tparams->lambda_vt = fval;\n\t}\n\tif(config_lookup(conf,WARPING_GL) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\",WARPING_GL);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,WARPING_GL) != NULL) {\n\t\tconfig_lookup_float(conf,WARPING_GL,&fval);\n\t\tparams->lambda_gl = fval;\n\t}\n\tif(config_lookup(conf,DIFFERENTIAL_LSF) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\", DIFFERENTIAL_LSF);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,DIFFERENTIAL_LSF) != NULL) {\n\t\tconfig_lookup_bool(conf, DIFFERENTIAL_LSF,&bool);\n\t\tparams->differential_lsf = bool;\n\t}\n\tif(config_lookup(conf,USE_PULSE_LIBRARY) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\",USE_PULSE_LIBRARY);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,USE_PULSE_LIBRARY) != NULL) {\n\t\tconfig_lookup_bool(conf,USE_PULSE_LIBRARY,&bool);\n\t\tparams->use_pulselib = bool;\n\t}\n\tif(config_lookup(conf,NUMBER_OF_PULSE_CANDIDATES) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\",NUMBER_OF_PULSE_CANDIDATES);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,NUMBER_OF_PULSE_CANDIDATES) != NULL) {\n\t\tconfig_lookup_int(conf,NUMBER_OF_PULSE_CANDIDATES,&ival);\n\t\tparams->n_pulsecandidates = (int)ival;\n\t}\n\tif(config_lookup(conf,CONCATENATION_COST) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\",CONCATENATION_COST);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,CONCATENATION_COST) != NULL) {\n\t\tconfig_lookup_float(conf,CONCATENATION_COST,&fval);\n\t\tparams->concatenation_cost = fval;\n\t}\n\tif(config_lookup(conf,PULSE_ERROR_BIAS) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\",PULSE_ERROR_BIAS);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,PULSE_ERROR_BIAS) != NULL) {\n\t\tconfig_lookup_float(conf,PULSE_ERROR_BIAS,&fval);\n\t\tparams->pulse_error_bias = fval;\n\t}\n\tif(config_lookup(conf,TARGET_COST) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\",TARGET_COST);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,TARGET_COST) != NULL) {\n\t\tconfig_lookup_float(conf,TARGET_COST,&fval);\n\t\tparams->target_cost = fval;\n\t}\n\tif(config_lookup(conf,USE_PULSE_CLUSTERING) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\",USE_PULSE_CLUSTERING);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,USE_PULSE_CLUSTERING) != NULL) {\n\t\tconfig_lookup_bool(conf,USE_PULSE_CLUSTERING,&bool);\n\t\tparams->pulse_clustering = bool;\n\t}\n\tif(config_lookup(conf,USE_PULSE_INTERPOLATION) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\",USE_PULSE_INTERPOLATION);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,USE_PULSE_INTERPOLATION) != NULL) {\n\t\tconfig_lookup_bool(conf,USE_PULSE_INTERPOLATION,&bool);\n\t\tparams->pulse_interpolation = bool;\n\t}\n\tif(config_lookup(conf,MAX_PULSES_IN_CLUSTER) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\",MAX_PULSES_IN_CLUSTER);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,MAX_PULSES_IN_CLUSTER) != NULL) {\n\t\tconfig_lookup_int(conf,MAX_PULSES_IN_CLUSTER,&ival);\n\t\tparams->max_pulses_in_cluster = (int)ival;\n\t}\n\tif(config_lookup(conf,NOISE_GAIN_VOICED) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\",NOISE_GAIN_VOICED);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,NOISE_GAIN_VOICED) != NULL) {\n\t\tconfig_lookup_float(conf,NOISE_GAIN_VOICED,&fval);\n\t\tparams->noise_gain_voiced = fval;\n\t}\n\tif(config_lookup(conf,USE_HMM) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\",USE_HMM);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,USE_HMM) != NULL) {\n\t\tconfig_lookup_bool(conf,USE_HMM,&bool);\n\t\tparams->use_hmm = bool;\n\t}\n\tif(config_lookup(conf,POSTFILTER_COEFFICIENT) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\",POSTFILTER_COEFFICIENT);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,POSTFILTER_COEFFICIENT) != NULL) {\n\t\tconfig_lookup_float(conf,POSTFILTER_COEFFICIENT,&fval);\n\t\tparams->postfilter_alpha = fval;\n\t}\n\tif(config_lookup(conf,PITCH) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\",PITCH);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,PITCH) != NULL) {\n\t\tconfig_lookup_float(conf,PITCH,&fval);\n\t\tparams->pitch = fval;\n\t}\n\tif(config_lookup(conf,SPEED) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\",SPEED);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,SPEED) != NULL) {\n\t\tconfig_lookup_float(conf,SPEED,&fval);\n\t\tparams->speed = fval;\n\t}\n\tif(config_lookup(conf,GAIN_UNVOICED) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\",GAIN_UNVOICED);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,GAIN_UNVOICED) != NULL) {\n\t\tconfig_lookup_float(conf,GAIN_UNVOICED,&fval);\n\t\tparams->gain_unvoiced = fval;\n\t}\n\tif(config_lookup(conf,FILTER_UPDATE_INTERVAL_VT) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\",FILTER_UPDATE_INTERVAL_VT);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,FILTER_UPDATE_INTERVAL_VT) != NULL) {\n\t\tconfig_lookup_float(conf,FILTER_UPDATE_INTERVAL_VT,&fval);\n\t\tparams->filter_update_interval_vt_ms = fval;\n\t}\n\tif(config_lookup(conf,FILTER_UPDATE_INTERVAL_GL) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\",FILTER_UPDATE_INTERVAL_GL);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,FILTER_UPDATE_INTERVAL_GL) != NULL) {\n\t\tconfig_lookup_float(conf,FILTER_UPDATE_INTERVAL_GL,&fval);\n\t\tparams->filter_update_interval_gl_ms = fval;\n\t}\n\tif(config_lookup(conf,GLFLOWSP_SMOOTH_LEN) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\",GLFLOWSP_SMOOTH_LEN);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,GLFLOWSP_SMOOTH_LEN) != NULL) {\n\t\tconfig_lookup_int(conf,GLFLOWSP_SMOOTH_LEN,&ival);\n\t\tparams->glflowsp_smooth_len = (int)ival;\n\t}\n\tif(config_lookup(conf,LSF_SMOOTH_LEN) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\",LSF_SMOOTH_LEN);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,LSF_SMOOTH_LEN) != NULL) {\n\t\tconfig_lookup_int(conf,LSF_SMOOTH_LEN,&ival);\n\t\tparams->lsf_smooth_len = (int)ival;\n\t}\n\tif(config_lookup(conf,HARMONICS_SMOOTH_LEN) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\",HARMONICS_SMOOTH_LEN);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,HARMONICS_SMOOTH_LEN) != NULL) {\n\t\tconfig_lookup_int(conf,HARMONICS_SMOOTH_LEN,&ival);\n\t\tparams->harmonics_smooth_len = (int)ival;\n\t}\n\tif(config_lookup(conf,GAIN_SMOOTH_LEN) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\",GAIN_SMOOTH_LEN);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,GAIN_SMOOTH_LEN) != NULL) {\n\t\tconfig_lookup_int(conf,GAIN_SMOOTH_LEN,&ival);\n\t\tparams->gain_smooth_len = (int)ival;\n\t}\n\tif(config_lookup(conf,NORM_GAIN_SMOOTH_V_LEN) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\",NORM_GAIN_SMOOTH_V_LEN);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,NORM_GAIN_SMOOTH_V_LEN) != NULL) {\n\t\tconfig_lookup_int(conf,NORM_GAIN_SMOOTH_V_LEN,&ival);\n\t\tparams->norm_gain_smooth_v_len = (int)ival;\n\t}\n\tif(config_lookup(conf,NORM_GAIN_SMOOTH_UV_LEN) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\",NORM_GAIN_SMOOTH_UV_LEN);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,NORM_GAIN_SMOOTH_UV_LEN) != NULL) {\n\t\tconfig_lookup_int(conf,NORM_GAIN_SMOOTH_UV_LEN,&ival);\n\t\tparams->norm_gain_smooth_uv_len = (int)ival;\n\t}\n\tif(config_lookup(conf,GAIN_UNVOICED_FRAME_LENGTH) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\",GAIN_UNVOICED_FRAME_LENGTH);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,GAIN_UNVOICED_FRAME_LENGTH) != NULL) {\n\t\tconfig_lookup_float(conf,GAIN_UNVOICED_FRAME_LENGTH,&fval);\n\t\tparams->gain_unvoiced_frame_length_ms = fval;\n\t}\n\tif(config_lookup(conf,GAIN_VOICED_FRAME_LENGTH) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\",GAIN_VOICED_FRAME_LENGTH);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,GAIN_VOICED_FRAME_LENGTH) != NULL) {\n\t\tconfig_lookup_float(conf,GAIN_VOICED_FRAME_LENGTH,&fval);\n\t\tparams->gain_voiced_frame_length_ms = fval;\n\t}\n\tif(config_lookup(conf,HNR_SMOOTH_LEN) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\",HNR_SMOOTH_LEN);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,HNR_SMOOTH_LEN) != NULL) {\n\t\tconfig_lookup_int(conf,HNR_SMOOTH_LEN,&ival);\n\t\tparams->hnr_smooth_len = (int)ival;\n\t}\n\tif(config_lookup(conf,HNR_CHANNELS) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\", HNR_CHANNELS);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,HNR_CHANNELS) != NULL) {\n\t\tconfig_lookup_int(conf, HNR_CHANNELS,&ival);\n\t\tparams->hnr_channels = (int)ival;\n\t}\n\tif(config_lookup(conf,NOISE_LOW_FREQ_LIMIT) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\", NOISE_LOW_FREQ_LIMIT);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,NOISE_LOW_FREQ_LIMIT) != NULL) {\n\t\tconfig_lookup_float(conf, NOISE_LOW_FREQ_LIMIT,&fval);\n\t\tparams->noise_low_freq_limit = fval;\n\t}\n\tif(config_lookup(conf,ADD_NOISE_PULSELIB) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\", ADD_NOISE_PULSELIB);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,ADD_NOISE_PULSELIB) != NULL) {\n\t\tconfig_lookup_bool(conf, ADD_NOISE_PULSELIB,&bool);\n\t\tparams->add_noise_pulselib = bool;\n\t}\n\tif(config_lookup(conf,USE_HARMONIC_MODIFICATION) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\", USE_HARMONIC_MODIFICATION);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,USE_HARMONIC_MODIFICATION) != NULL) {\n\t\tconfig_lookup_bool(conf, USE_HARMONIC_MODIFICATION,&bool);\n\t\tparams->use_harmonic_modification = bool;\n\t}\n\tif(config_lookup(conf,NUMBER_OF_HARMONICS) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\", NUMBER_OF_HARMONICS);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,NUMBER_OF_HARMONICS) != NULL) {\n\t\tconfig_lookup_int(conf, NUMBER_OF_HARMONICS,&ival);\n\t\tparams->number_of_harmonics = (int)ival;\n\t}\n\tif(config_lookup(conf,HP_FILTER_F0) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\", HP_FILTER_F0);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,HP_FILTER_F0) != NULL) {\n\t\tconfig_lookup_bool(conf, HP_FILTER_F0,&bool);\n\t\tparams->hpfiltf0 = bool;\n\t}\n\tif(config_lookup(conf,WAVEFORM_SAMPLES) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\", WAVEFORM_SAMPLES);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,WAVEFORM_SAMPLES) != NULL) {\n\t\tconfig_lookup_int(conf, WAVEFORM_SAMPLES,&ival);\n\t\tparams->waveform_samples = (int)ival;\n\t}\n\tif(config_lookup(conf,NOISE_ROBUST_SPEECH) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\", NOISE_ROBUST_SPEECH);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,NOISE_ROBUST_SPEECH) != NULL) {\n\t\tconfig_lookup_bool(conf, NOISE_ROBUST_SPEECH,&bool);\n\t\tparams->noise_robust_speech = bool;\n\t}\n\tif(config_lookup(conf,SEPARATE_VOICED_UNVOICED_SPECTRUM) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\", SEPARATE_VOICED_UNVOICED_SPECTRUM);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,SEPARATE_VOICED_UNVOICED_SPECTRUM) != NULL) {\n\t\tconfig_lookup_bool(conf, SEPARATE_VOICED_UNVOICED_SPECTRUM,&bool);\n\t\tparams->sep_vuv_spectrum = bool;\n\t}\n\tif(config_lookup(conf,SYNTHESIZE_MULTIPLE_FILES) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\", SYNTHESIZE_MULTIPLE_FILES);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,SYNTHESIZE_MULTIPLE_FILES) != NULL) {\n\t\tconfig_lookup_bool(conf, SYNTHESIZE_MULTIPLE_FILES,&bool);\n\t\tparams->multisyn = bool;\n\t}\n\tif(config_lookup(conf,USE_TILT) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\", USE_TILT);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,USE_TILT) != NULL) {\n\t\tconfig_lookup_bool(conf, USE_TILT,&bool);\n\t\tparams->use_tilt = bool;\n\t}\n\tif(config_lookup(conf,USE_HNR) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\", USE_HNR);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,USE_HNR) != NULL) {\n\t\tconfig_lookup_bool(conf, USE_HNR,&bool);\n\t\tparams->use_hnr = bool;\n\t}\n\tif(config_lookup(conf,USE_HARMONICS) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\", USE_HARMONICS);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,USE_HARMONICS) != NULL) {\n\t\tconfig_lookup_bool(conf, USE_HARMONICS,&bool);\n\t\tparams->use_harmonics = bool;\n\t}\n\tif(config_lookup(conf,USE_H1H2) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\", USE_H1H2);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,USE_H1H2) != NULL) {\n\t\tconfig_lookup_bool(conf, USE_H1H2,&bool);\n\t\tparams->use_h1h2 = bool;\n\t}\n\tif(config_lookup(conf,USE_NAQ) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\", USE_NAQ);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,USE_NAQ) != NULL) {\n\t\tconfig_lookup_bool(conf, USE_NAQ,&bool);\n\t\tparams->use_naq = bool;\n\t}\n\tif(config_lookup(conf,USE_WAVEFORM) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\", USE_WAVEFORM);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,USE_WAVEFORM) != NULL) {\n\t\tconfig_lookup_bool(conf, USE_WAVEFORM,&bool);\n\t\tparams->use_waveform = bool;\n\t}\n\tif(config_lookup(conf,WRITE_EXCITATION_TO_WAV) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\", WRITE_EXCITATION_TO_WAV);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,WRITE_EXCITATION_TO_WAV) != NULL) {\n\t\tconfig_lookup_bool(conf, WRITE_EXCITATION_TO_WAV,&bool);\n\t\tparams->write_excitation_to_wav = bool;\n\t}\n\tif(config_lookup(conf,JITTER) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\", JITTER);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,JITTER) != NULL) {\n\t\tconfig_lookup_float(conf,JITTER,&fval);\n\t\tparams->jitter = fval;\n\t}\n\tif (config_lookup(conf, NOISE_REDUCTION_SYNTHESIS) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read default configuration \\\"%s\\\".\\n\", NOISE_REDUCTION_SYNTHESIS);\n\t\treturn EXIT_FAILURE;\n\t} else if (config_lookup(conf, NOISE_REDUCTION_SYNTHESIS) != NULL) {\n\t\tconfig_lookup_bool(conf, NOISE_REDUCTION_SYNTHESIS,&bool);\n\t\tparams->noise_reduction_synthesis = bool;\n\t}\n\tif (config_lookup(conf, NOISE_REDUCTION_LIMIT_DB) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read default configuration \\\"%s\\\".\\n\", NOISE_REDUCTION_LIMIT_DB);\n\t\treturn EXIT_FAILURE;\n\t} else if (config_lookup(conf, NOISE_REDUCTION_LIMIT_DB) != NULL) {\n\t\tconfig_lookup_float(conf, NOISE_REDUCTION_LIMIT_DB,&fval);\n\t\tparams->noise_reduction_limit_db = fval;\n\t}\n\tif (config_lookup(conf, NOISE_REDUCTION_DB) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read default configuration \\\"%s\\\".\\n\", NOISE_REDUCTION_DB);\n\t\treturn EXIT_FAILURE;\n\t} else if (config_lookup(conf, NOISE_REDUCTION_DB) != NULL) {\n\t\tconfig_lookup_float(conf, NOISE_REDUCTION_DB,&fval);\n\t\tparams->noise_reduction_db = fval;\n\t}\n\tif (config_lookup(conf, NORMALIZE_PULSELIB) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read default configuration \\\"%s\\\".\\n\", NORMALIZE_PULSELIB);\n\t\treturn EXIT_FAILURE;\n\t} else if (config_lookup(conf, NORMALIZE_PULSELIB) != NULL) {\n\t\tconfig_lookup_bool(conf, NORMALIZE_PULSELIB,&bool);\n\t\tparams->normalize_pulselib = bool;\n\t}\n\tif (config_lookup(conf, ADAPT_TO_PULSELIB) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read default configuration \\\"%s\\\".\\n\", ADAPT_TO_PULSELIB);\n\t\treturn EXIT_FAILURE;\n\t} else if (config_lookup(conf, ADAPT_TO_PULSELIB) != NULL) {\n\t\tconfig_lookup_bool(conf, ADAPT_TO_PULSELIB,&bool);\n\t\tparams->adapt_to_pulselib = bool;\n\t}\n\tif (config_lookup(conf, ADAPT_COEFF) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read default configuration \\\"%s\\\".\\n\", ADAPT_COEFF);\n\t\treturn EXIT_FAILURE;\n\t} else if (config_lookup(conf, ADAPT_COEFF) != NULL) {\n\t\tconfig_lookup_float(conf, ADAPT_COEFF,&fval);\n\t\tparams->adapt_coeff = fval;\n\t}\n\tif (config_lookup(conf, USE_PULSELIB_LSF) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read default configuration \\\"%s\\\".\\n\", USE_PULSELIB_LSF);\n\t\treturn EXIT_FAILURE;\n\t} else if (config_lookup(conf, USE_PULSELIB_LSF) != NULL) {\n\t\tconfig_lookup_bool(conf, USE_PULSELIB_LSF,&bool);\n\t\tparams->use_pulselib_lsf = bool;\n\t}\n\tif (config_lookup(conf, AVERAGE_N_ADJACENT_PULSES) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read default configuration \\\"%s\\\".\\n\", AVERAGE_N_ADJACENT_PULSES);\n\t\treturn EXIT_FAILURE;\n\t} else if (config_lookup(conf, AVERAGE_N_ADJACENT_PULSES) != NULL) {\n\t\tconfig_lookup_int(conf, AVERAGE_N_ADJACENT_PULSES,&ival);\n\t\tparams->average_n_adjacent_pulses = (int)ival;\n\t}\n\tif (config_lookup(conf, LOG_F0) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read default configuration \\\"%s\\\".\\n\", LOG_F0);\n\t\treturn EXIT_FAILURE;\n\t} else if (config_lookup(conf, LOG_F0) != NULL) {\n\t\tconfig_lookup_bool(conf, LOG_F0,&bool);\n\t\tparams->logf0 = bool;\n\t}\n\tif (config_lookup(conf, USE_DNN_PULSEGEN) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read default configuration \\\"%s\\\".\\n\", USE_DNN_PULSEGEN);\n\t\treturn EXIT_FAILURE;\n\t} else if (config_lookup(conf, USE_DNN_PULSEGEN) != NULL) {\n\t\tconfig_lookup_bool(conf, USE_DNN_PULSEGEN,&bool);\n\t\tparams->use_dnn_pulsegen = bool;\n\t}\n\tif (config_lookup(conf, USE_DNN_PULSELIB_SEL) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read default configuration \\\"%s\\\".\\n\", USE_DNN_PULSELIB_SEL);\n\t\treturn EXIT_FAILURE;\n\t} else if (config_lookup(conf, USE_DNN_PULSELIB_SEL) != NULL) {\n\t\tconfig_lookup_bool(conf, USE_DNN_PULSELIB_SEL,&bool);\n\t\tparams->use_dnn_pulselib_sel = bool;\n\t}\n\tif (config_lookup(conf, USE_DNN_SPECMATCH) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read default configuration \\\"%s\\\".\\n\", USE_DNN_SPECMATCH);\n\t\treturn EXIT_FAILURE;\n\t} else if (config_lookup(conf, USE_DNN_SPECMATCH) != NULL) {\n\t\tconfig_lookup_bool(conf, USE_DNN_SPECMATCH,&bool);\n\t\tparams->use_dnn_specmatch = bool;\n\t}\n\tif (config_lookup(conf, DNN_INPUT_NORMALIZED) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read default configuration \\\"%s\\\".\\n\", DNN_INPUT_NORMALIZED);\n\t\treturn EXIT_FAILURE;\n\t} else if (config_lookup(conf, DNN_INPUT_NORMALIZED) != NULL) {\n\t\tconfig_lookup_bool(conf, DNN_INPUT_NORMALIZED,&bool);\n\t\tparams->dnn_input_normalized = bool;\n\t}\n\tif (config_lookup(conf, DNN_NUMBER_OF_STACKED_FRAMES) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read default configuration \\\"%s\\\".\\n\", DNN_NUMBER_OF_STACKED_FRAMES);\n\t\treturn EXIT_FAILURE;\n\t} else if (config_lookup(conf, DNN_NUMBER_OF_STACKED_FRAMES) != NULL) {\n\t\tconfig_lookup_int(conf, DNN_NUMBER_OF_STACKED_FRAMES,&ival);\n\t\tparams->dnn_number_of_stacked_frames = (int)ival;\n\t}\n\tif (config_lookup(conf, HNR_COMPENSATION) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read default configuration \\\"%s\\\".\\n\", HNR_COMPENSATION);\n\t\treturn EXIT_FAILURE;\n\t} else if (config_lookup(conf, HNR_COMPENSATION) != NULL) {\n\t\tconfig_lookup_bool(conf, HNR_COMPENSATION,&bool);\n\t\tparams->hnr_compensation = bool;\n\t}\n\tif (config_lookup(conf, UNVOICED_PRE_EMPHASIS) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read default configuration \\\"%s\\\".\\n\", UNVOICED_PRE_EMPHASIS);\n\t\treturn EXIT_FAILURE;\n\t} else if (config_lookup(conf, UNVOICED_PRE_EMPHASIS) != NULL) {\n\t\tconfig_lookup_bool(conf, UNVOICED_PRE_EMPHASIS,&bool);\n\t\tparams->unvoiced_pre_emphasis = bool;\n\t}\n\n\t/* Pulse PCA as target cost */\n\tif (config_lookup(conf, USE_PULSE_PCA) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read default configuration \\\"%s\\\".\\n\", USE_PULSE_PCA);\n\t\treturn EXIT_FAILURE;\n\t} else if (config_lookup(conf, USE_PULSE_PCA) != NULL) {\n\t\tconfig_lookup_bool(conf, USE_PULSE_PCA,&bool);\n\t\tparams->use_pulse_pca = bool;\n\t}\n\n\t/* Pulse library PCA */\n\tif (config_lookup(conf, USE_PULSELIB_PCA) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read default configuration \\\"%s\\\".\\n\", USE_PULSELIB_PCA);\n\t\treturn EXIT_FAILURE;\n\t} else if (config_lookup(conf, USE_PULSELIB_PCA) != NULL) {\n\t\tconfig_lookup_bool(conf, USE_PULSELIB_PCA,&bool);\n\t\tparams->use_pulselib_pca = bool;\n\t}\n\tif (config_lookup(conf, PCA_ORDER) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read default configuration \\\"%s\\\".\\n\", PCA_ORDER);\n\t\treturn EXIT_FAILURE;\n\t} else if (config_lookup(conf, PCA_ORDER) != NULL) {\n\t\tconfig_lookup_int(conf, PCA_ORDER,&ival);\n\t\tparams->pca_order = (int)ival;\n\t}\n\tif (config_lookup(conf, PCA_ORDER_SYNTHESIS) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read default configuration \\\"%s\\\".\\n\", PCA_ORDER_SYNTHESIS);\n\t\treturn EXIT_FAILURE;\n\t} else if (config_lookup(conf, PCA_ORDER_SYNTHESIS) != NULL) {\n\t\tconfig_lookup_int(conf, PCA_ORDER_SYNTHESIS,&ival);\n\t\tparams->pca_order_synthesis = (int)ival;\n\t}\n\tif (config_lookup(conf, PCA_SPECTRAL_MATCHING) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read default configuration \\\"%s\\\".\\n\", PCA_SPECTRAL_MATCHING);\n\t\treturn EXIT_FAILURE;\n\t} else if (config_lookup(conf, PCA_SPECTRAL_MATCHING) != NULL) {\n\t\tconfig_lookup_bool(conf, PCA_SPECTRAL_MATCHING,&bool);\n\t\tparams->pca_spectral_matching = bool;\n\t}\n\tif (config_lookup(conf, PCA_PULSE_LENGTH) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read default configuration \\\"%s\\\".\\n\", PCA_PULSE_LENGTH);\n\t\treturn EXIT_FAILURE;\n\t} else if (config_lookup(conf, PCA_PULSE_LENGTH) != NULL) {\n\t\tconfig_lookup_int(conf, PCA_PULSE_LENGTH,&ival);\n\t\tparams->pca_pulse_length = (int)ival;\n\t}\n\tif (config_lookup(conf, TWO_PITCH_PERIOD_DIFF_PULSE) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read default configuration \\\"%s\\\".\\n\", TWO_PITCH_PERIOD_DIFF_PULSE);\n\t\treturn EXIT_FAILURE;\n\t} else if (config_lookup(conf, TWO_PITCH_PERIOD_DIFF_PULSE) != NULL) {\n\t\tconfig_lookup_bool(conf, TWO_PITCH_PERIOD_DIFF_PULSE,&bool);\n\t\tparams->two_pitch_period_diff_pulse = bool;\n\t}\n\n\t/* Read data format */\n\tif (config_lookup(conf, DATA_FORMAT) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\",DATA_FORMAT);\n\t\treturn EXIT_FAILURE;\n\t} else if (config_lookup(conf, DATA_FORMAT) != NULL) {\n\t\tconfig_lookup_string(conf,DATA_FORMAT,&tmp);\n\t\tif(strcmp(tmp,DATA_FORMAT_ASCII) == 0)\n\t\t\tparams->data_format = DATA_FORMAT_ID_ASCII;\n\t\telse if(strcmp(tmp,DATA_FORMAT_BINARY) == 0)\n\t\t\tparams->data_format = DATA_FORMAT_ID_BINARY;\n\t\telse {\n\t\t\tprintf(\"\\nError: Invalid configuration value \\\"%s\\\".\\n\", DATA_FORMAT);\n\t\t\treturn EXIT_FAILURE;\n\t\t}\n\t}\n\n\t/* Read formant enhancement method */\n\tif (config_lookup(conf, POSTFILTER_METHOD) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\",POSTFILTER_METHOD);\n\t\treturn EXIT_FAILURE;\n\t} else if (config_lookup(conf, POSTFILTER_METHOD) != NULL) {\n\t\tconfig_lookup_string(conf,POSTFILTER_METHOD,&tmp);\n\t\tif(strcmp(tmp,POSTFILTER_LSF) == 0)\n\t\t\tparams->postfilter_method = POSTFILTER_ID_LSF;\n\t\telse if(strcmp(tmp,POSTFILTER_LPC) == 0)\n\t\t\tparams->postfilter_method = POSTFILTER_ID_LPC;\n\t\telse if(strcmp(tmp,POSTFILTER_NONE) == 0)\n\t\t\tparams->postfilter_method = POSTFILTER_ID_NONE;\n\t\telse {\n\t\t\tprintf(\"\\nError: Invalid configuration value \\\"%s\\\".\\n\", POSTFILTER_METHOD);\n\t\t\treturn EXIT_FAILURE;\n\t\t}\n\t}\n\n\t/* Read parameter weights */\n\tparamweights_conf = config_lookup(conf,PARAMETER_WEIGHTS);\n\tif(paramweights_conf == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\", PARAMETER_WEIGHTS);\n\t\treturn EXIT_FAILURE;\n\t} else if(paramweights_conf != NULL) {\n\t\tif(conf_type == USR_CONF)\n\t\t\tgsl_vector_free(params->paramweights);\n\t\tparams->paramweights = gsl_vector_alloc(config_setting_length(paramweights_conf));\n\t\tfor(i=0;i<config_setting_length(paramweights_conf);i++)\n\t\t\tgsl_vector_set(params->paramweights,i,config_setting_get_float_elem(paramweights_conf, i));\n\t}\n\n\t/* Read DNN weight dimensions */\n\tdnn_dim_conf = config_lookup(conf,DNN_WEIGHT_DIMS);\n\tif(dnn_dim_conf == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\", DNN_WEIGHT_DIMS);\n\t\treturn EXIT_FAILURE;\n\t} else if(dnn_dim_conf != NULL) {\n\t\tif(conf_type == USR_CONF)\n\t\t\tgsl_vector_free(params->dnn_weight_dims);\n\t\tparams->dnn_weight_dims = gsl_vector_alloc(config_setting_length(dnn_dim_conf));\n\t\tfor(i=0;i<config_setting_length(dnn_dim_conf);i++)\n\t\t\tgsl_vector_set(params->dnn_weight_dims,i,config_setting_get_int_elem(dnn_dim_conf, i));\n\t}\n\n\t/* Read pulse filename */\n\tif(config_lookup(conf,GLOTTAL_PULSE_NAME) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\",GLOTTAL_PULSE_NAME);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,GLOTTAL_PULSE_NAME) != NULL) {\n\t\tif(conf_type == USR_CONF)\n\t\t\tfree(params->pulse_filename);\n\t\tconfig_lookup_string(conf,GLOTTAL_PULSE_NAME,&tmp);\n\t\tparams->pulse_filename = (char *)malloc((strlen(tmp)+1)*sizeof(char));\n\t\tstrcpy(params->pulse_filename,tmp);\n\t}\n\n\t/* Read pulse library filename */\n\tif(config_lookup(conf,PULSE_LIBRARY_NAME) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\",PULSE_LIBRARY_NAME);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,PULSE_LIBRARY_NAME) != NULL) {\n\t\tif(conf_type == USR_CONF)\n\t\t\tfree(params->pulselibrary_filename);\n\t\tconfig_lookup_string(conf,PULSE_LIBRARY_NAME,&tmp);\n\t\tparams->pulselibrary_filename = (char *)malloc((strlen(tmp)+1)*sizeof(char));\n\t\tstrcpy(params->pulselibrary_filename,tmp);\n\t}\n\n\t/* Read synthesis list filename */\n\tif(config_lookup(conf,SYNTHESIS_LIST) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\",SYNTHESIS_LIST);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,SYNTHESIS_LIST) != NULL) {\n\t\tif(conf_type == USR_CONF)\n\t\t\tfree(params->synlist_filename);\n\t\tconfig_lookup_string(conf,SYNTHESIS_LIST,&tmp);\n\t\tparams->synlist_filename = (char *)malloc((strlen(tmp)+1)*sizeof(char));\n\t\tstrcpy(params->synlist_filename,tmp);\n\t}\n\n\t/* Read DNN path */\n\tif(config_lookup(conf,DNN_WEIGHT_PATH) == NULL && conf_type == DEF_CONF) {\n\t\tprintf(\"\\nError: Could not read configuration \\\"%s\\\".\\n\",DNN_WEIGHT_PATH);\n\t\treturn EXIT_FAILURE;\n\t} else if(config_lookup(conf,DNN_WEIGHT_PATH) != NULL) {\n\t\tif(conf_type == USR_CONF)\n\t\t\tfree(params->dnnpath);\n\t\tconfig_lookup_string(conf,DNN_WEIGHT_PATH,&tmp);\n\t\tparams->dnnpath = (char *)malloc((strlen(tmp)+1)*sizeof(char));\n\t\tstrcpy(params->dnnpath,tmp);\n\t}\n\n\t/* Free memory if previously a synthesis list was allocated */\n\tif(conf_type == USR_CONF) {\n\t\tfor(i=0;i<synlistlen_old;i++)\n\t\t\tfree(params->synlist[i]);\n\t\tfree(params->synlist);\n\t}\n\n\t/* Create synthesis list */\n\tif(params->multisyn == 1) {\n\t\tif(ReadSynthesisList(params) == EXIT_FAILURE)\n\t\t\treturn EXIT_FAILURE;\n\t} else {\n\t\tparams->synlistlen = 1;\n\t\tparams->synlist = (char **)malloc(sizeof(char *));\n\t\tparams->synlist[0] = (char *)malloc((strlen(filename)+1)*sizeof(char));\n\t\tstrcpy(params->synlist[0],filename);\n\t}\n\n\t/* Convert milliseconds to samples */\n\tparams->frame_length = rint(params->FS*params->frame_length_ms/1000);\n\tparams->shift = rint(params->FS*params->shift_ms/1000);\n\tparams->f0_frame_length = rint(params->FS*params->f0_frame_length_ms/1000);\n\tparams->gain_voiced_frame_length = rint(params->FS*params->gain_voiced_frame_length_ms/1000);\n\tparams->gain_unvoiced_frame_length = rint(params->FS*params->gain_unvoiced_frame_length_ms/1000);\n\tparams->filter_update_interval_vt = GSL_MAX(rint(params->FS*params->filter_update_interval_vt_ms/1000),1);\n\tparams->filter_update_interval_gl = GSL_MAX(rint(params->FS*params->filter_update_interval_gl_ms/1000),1);\n\n\t/* Set time */\n\tif(conf_type == DEF_CONF)\n\t\tparams->time_temp = (double)clock();\n\n\t/* Free memory */\n\tconfig_destroy(conf);\n\tfree(conf);\n\n\treturn EXIT_SUCCESS;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n/**\n * Function ReadSynthesisList\n *\n * Read list of synthesis file names\n *\n * @param name filename\n * @return number of files in the list\n */\nint ReadSynthesisList(PARAM *params) {\n\n\tFILE *file;\n\tchar s[DEF_STRING_LEN];\n\tint ind;\n\n\t/* Open file */\n\tfile = fopen(params->synlist_filename, \"r\");\n\tif(!file) {\n\t\tprintf(\"Error opening synthesis list file \\\"%s\\\": %s\\n\", params->synlist_filename, strerror(errno));\n\t\treturn EXIT_FAILURE;\n\t}\n\n\t/* Read lines until EOF */\n\tind = 0;\n\twhile(fscanf(file,\"%s\",s) != EOF)\n\t\tind++;\n\n\t/* Allocate memory for strings */\n\tparams->synlistlen = ind;\n\tchar **filenames = (char **)malloc(ind*sizeof(char *));\n\n\t/* Read file names to array */\n\tfseek(file, 0, SEEK_SET);\n\tind = 0;\n\tchar *fn;\n\twhile(fscanf(file,\"%s\",s) != EOF) {\n\t\tfn = (char *)malloc((strlen(s)+1)*sizeof(char));\n\t\tstrcpy(fn,s);\n\t\tfilenames[ind] = fn;\n\t\tind++;\n\t}\n\tfclose(file);\n\n\t/* Set list to params */\n\tparams->synlist = filenames;\n\treturn EXIT_SUCCESS;\n}\n\n\n\n\n/**\n * Read_DNN_weights\n *\n * Read DNN pulse generation weights from file, check validity\n *\n */\nint Read_DNN_weights(PARAM *params, gsl_matrix **DNN_W) {\n\n\t/* Do not read if DNNs are not used */\n\tif(params->use_dnn_pulsegen == 0)\n\t\treturn EXIT_SUCCESS;\n\n\t/* Allocate weight matrices and read data from files */\n\tint i,numlayers = params->dnn_weight_dims->size/2;\n\tchar temp[DEF_STRING_LEN];\n\tchar num[20];\n\tFILE *wfile;\n\tfor(i=0;i<numlayers;i++) {\n\t\tDNN_W[i] = gsl_matrix_alloc(gsl_vector_get(params->dnn_weight_dims,2*i),gsl_vector_get(params->dnn_weight_dims,2*i+1));\n\t\tstrcpy(temp,params->dnnpath);\n\t\tstrcat(temp,FILENAME_DNN_W);\n\t\tsprintf(num,\"%d\",i+1);\n\t\tstrcat(temp,num);\n\t\twfile = fopen(temp, \"r\");\n\t\tif(wfile == NULL) {\n\t\t\tprintf(\"Error opening file \\\"%s\\\": %s\\n\",temp,strerror(errno));\n\t\t\treturn EXIT_FAILURE;\n\t\t}\n\t\tgsl_matrix_fscanf(wfile,DNN_W[i]);\n\t\tfclose(wfile);\n\t}\n\n\t/* Return */\n\treturn EXIT_SUCCESS;\n}\n\n\n/**\n * Read_input_minmax\n *\n * Read input data minimum and maximum for normalizing the input data for DNN pulse generation\n *\n */\nint Read_input_minmax(PARAM *params, gsl_vector **input_minmax) {\n\n\t/* Do not read if DNNs are not used */\n\tif(params->use_dnn_pulsegen == 0 || params->dnn_input_normalized == 0)\n\t\treturn EXIT_SUCCESS;\n\n\t/* Allocate weight matrices and read data from files */\n\tchar temp[DEF_STRING_LEN];\n\tchar num[20];\n\tFILE *datafile;\n\tinput_minmax[0] = gsl_vector_alloc(2*(gsl_vector_get(params->dnn_weight_dims,0)-1)/params->dnn_number_of_stacked_frames);\n\tstrcpy(temp,params->dnnpath);\n\tstrcat(temp,FILENAME_INPUT_MINMAX);\n\tdatafile = fopen(temp, \"r\");\n\tif(datafile == NULL) {\n\t\tprintf(\"Error opening file \\\"%s\\\": %s\\n\",temp,strerror(errno));\n\t\treturn EXIT_FAILURE;\n\t}\n\tgsl_vector_fscanf(datafile,input_minmax[0]);\n\tfclose(datafile);\n\n\t/* Return */\n\treturn EXIT_SUCCESS;\n}\n\n\n\n\n\n\n/**\n * Read_pulse_library\n *\n * Read pulse library from file, check validity\n *\n */\nint Read_pulse_library(PARAM *params,gsl_matrix **pulses,gsl_matrix **pulses_rs,gsl_matrix **plsf,gsl_matrix **ptilt,gsl_matrix **pharm,\n\t\tgsl_matrix **phnr,gsl_matrix **pwaveform, gsl_matrix **pca_pc,gsl_matrix **pca_w_lib,gsl_vector **stoch_env,gsl_vector **stoch_sp,gsl_vector **pgain, gsl_vector **ph1h2,\n\t\tgsl_vector **pnaq, gsl_vector **pca_mean, gsl_vector **pulse_lengths) {\n\n\t/* Do not read if pulse library is not used */\n\tif(params->use_pulselib == 0) {\n\t\tparams->n_pulsecandidates = 1;\n\t\tparams->pulsemaxlen = 1;\n\t\tparams->rspulsemaxlen = 1;\n\t\treturn EXIT_SUCCESS;\n\t}\n\n\t/* Initialize */\n\tprintf(\"\t- Loading pulse library...\\n\");\n\tdouble time1 = (double)clock();\n\tchar temp[DEF_STRING_LEN];\n\n\t/* Load params file for pulse library, */\n\tstrcpy(temp, params->pulselibrary_filename);\n\tFILE *plparams_file = fopen(strcat(temp,FILENAME_ENDING_INFO), \"r\");\n\tif(plparams_file == NULL) {\n\t\tprintf(\"\t- Pulse library \\\"%s\\\" was not found\\n\",params->pulselibrary_filename);\n\t\treturn EXIT_FAILURE;\n\t}\n\n\t/* Read pulse library parameterers */\n\tgsl_vector *plparams = gsl_vector_alloc(NPARAMS);\n\tgsl_vector_fscanf(plparams_file,plparams);\n\tparams->number_of_pulses = gsl_vector_get(plparams,9);\n\tparams->pulsemaxlen_ms = gsl_vector_get(plparams,10);\n\tparams->rspulsemaxlen_ms = gsl_vector_get(plparams,11);\n\n\t/* Convert milliseconds to samples */\n\tparams->pulsemaxlen = rint((double)params->FS*(double)params->pulsemaxlen_ms/1000.0);\n\tparams->rspulsemaxlen = rint(params->FS*params->rspulsemaxlen_ms/1000);\n\n\t/* Check compatibility with configuration parameters */\n\tif(params->lpc_order_vt != (int)gsl_vector_get(plparams,3)) {printf(\"\\nPulse library error: Different vocal tract LPC order\\n\\n\"); return EXIT_FAILURE;}\n\tif(params->lpc_order_gl != (int)gsl_vector_get(plparams,4)) {printf(\"\\nPulse library error: Different source LPC order\\n\\n\"); return EXIT_FAILURE;}\n\tif(params->hnr_channels != gsl_vector_get(plparams,7)) {printf(\"\\nPulse library error: Different number of HNR channels\\n\\n\"); return EXIT_FAILURE;}\n\tif(params->number_of_harmonics != gsl_vector_get(plparams,8)) {printf(\"\\nPulse library error: Different number of harmonics\\n\\n\"); return EXIT_FAILURE;}\n\tif(params->waveform_samples != gsl_vector_get(plparams,12)) {printf(\"\\nPulse library error: Different number of samples in Waveform\\n\\n\"); return EXIT_FAILURE;}\n\tif(params->FS != gsl_vector_get(plparams,13)) {printf(\"\\nPulse library error: Different sampling frequency\\n\\n\"); return EXIT_FAILURE;}\n\tif(params->data_format != (int)gsl_vector_get(plparams,14)) {printf(\"\\nPulse library error: Different data format (ascii/binary)\\n\\n\"); return EXIT_FAILURE;}\n\tif(params->number_of_pulses < params->n_pulsecandidates) {\n\t\tprintf(\"\t- Warning: Number of pulse candidates is greater than the total number of pulses.\\n\");\n\t\tprintf(\"\t       Number of pulse candidates changed to: %i.\\n\",params->number_of_pulses);\n\t\tparams->n_pulsecandidates = params->number_of_pulses;\n\t}\n\tgsl_vector_free(plparams);\n\tfclose(plparams_file);\n\n\t/* Allocate space for pulse library data */\n\t*(pulses) = gsl_matrix_alloc(params->number_of_pulses,params->pulsemaxlen);\n\t*(pulses_rs) = gsl_matrix_alloc(params->number_of_pulses,params->rspulsemaxlen);\n\t*(pulse_lengths) = gsl_vector_alloc(params->number_of_pulses);\n\t*(plsf) = gsl_matrix_calloc(params->number_of_pulses,params->lpc_order_vt);\n\t*(pgain) = gsl_vector_calloc(params->number_of_pulses);\n\tif(params->use_tilt == 1) *(ptilt) = gsl_matrix_calloc(params->number_of_pulses,params->lpc_order_gl);\n\telse *(ptilt) = NULL;\n\tif(params->use_harmonics == 1) *(pharm) = gsl_matrix_calloc(params->number_of_pulses,params->number_of_harmonics);\n\telse *(pharm) = NULL;\n\tif(params->use_hnr == 1) *(phnr) = gsl_matrix_calloc(params->number_of_pulses,params->hnr_channels);\n\telse *(phnr) = NULL;\n\tif(params->use_waveform == 1) *(pwaveform) = gsl_matrix_calloc(params->number_of_pulses,params->waveform_samples);\n\telse *(pwaveform) = NULL;\n\tif(params->use_h1h2 == 1) *(ph1h2) = gsl_vector_calloc(params->number_of_pulses);\n\telse *(ph1h2) = NULL;\n\tif(params->use_naq == 1) *(pnaq) = gsl_vector_calloc(params->number_of_pulses);\n\telse *(pnaq) = NULL;\n\n\t/* Load pulse data */\n\tstrcpy(temp, params->pulselibrary_filename);\n\tFILE *pulses_file = fopen(strcat(temp,FILENAME_ENDING_PULSELIB_PULSES), \"r\");\n\tif(pulses_file==NULL){printf(\"Error opening file \\\"%s\\\": %s\\n\",temp,strerror(errno));return EXIT_FAILURE;}\n\tstrcpy(temp, params->pulselibrary_filename);FILE *pulses_rs_file = fopen(strcat(temp,FILENAME_ENDING_PULSELIB_RSPULSES), \"r\");\n\tif(pulses_rs_file==NULL){printf(\"Error opening file \\\"%s\\\": %s\\n\",temp,strerror(errno));return EXIT_FAILURE;}\n\tstrcpy(temp, params->pulselibrary_filename);FILE *pulse_lengths_file = fopen(strcat(temp,FILENAME_ENDING_PULSELIB_PULSELENGTHS), \"r\");\n\tif(pulse_lengths_file==NULL){printf(\"Error opening file \\\"%s\\\": %s\\n\",temp,strerror(errno));return EXIT_FAILURE;}\n\tif(params->data_format == DATA_FORMAT_ID_ASCII) {\n\t\tgsl_matrix_fscanf(pulses_file,*(pulses));\n\t\tgsl_matrix_fscanf(pulses_rs_file,*(pulses_rs));\n\t\tgsl_vector_fscanf(pulse_lengths_file,*(pulse_lengths));\n\t} else if(params->data_format == DATA_FORMAT_ID_BINARY) {\n\t\tgsl_matrix_fread(pulses_file,*(pulses));\n\t\tgsl_matrix_fread(pulses_rs_file,*(pulses_rs));\n\t\tgsl_vector_fread(pulse_lengths_file,*(pulse_lengths));\n\t}\n\tfclose(pulses_file);\n\tfclose(pulses_rs_file);\n\tfclose(pulse_lengths_file);\n\n\t/* Load parameter data */\n\tstrcpy(temp, params->pulselibrary_filename);FILE *plsf_file = fopen(strcat(temp,FILENAME_ENDING_PULSELIB_LSF), \"r\");\n\tif(plsf_file==NULL){printf(\"Error opening file \\\"%s\\\": %s\\n\",temp,strerror(errno));return EXIT_FAILURE;}\n\tif(params->data_format == DATA_FORMAT_ID_ASCII) gsl_matrix_fscanf(plsf_file,*(plsf));\n\telse if(params->data_format == DATA_FORMAT_ID_BINARY) gsl_matrix_fread(plsf_file,*(plsf));\n\tfclose(plsf_file);\n\n\tstrcpy(temp, params->pulselibrary_filename);FILE *pgain_file = fopen(strcat(temp,FILENAME_ENDING_PULSELIB_GAIN), \"r\");\n\tif(pgain_file==NULL){printf(\"Error opening file \\\"%s\\\": %s\\n\",temp,strerror(errno));return EXIT_FAILURE;}\n\tif(params->data_format == DATA_FORMAT_ID_ASCII) gsl_vector_fscanf(pgain_file,*(pgain));\n\telse if(params->data_format == DATA_FORMAT_ID_BINARY) gsl_vector_fread(pgain_file,*(pgain));\n\tfclose(pgain_file);\n\n\tif(params->use_tilt == 1) {strcpy(temp, params->pulselibrary_filename);FILE *ptilt_file = fopen(strcat(temp,FILENAME_ENDING_PULSELIB_TILT), \"r\");\n\tif(ptilt_file==NULL){printf(\"Error opening file \\\"%s\\\": %s\\n\",temp,strerror(errno));return EXIT_FAILURE;}\n\tif(params->data_format == DATA_FORMAT_ID_ASCII)\tgsl_matrix_fscanf(ptilt_file,*(ptilt));\n\telse if(params->data_format == DATA_FORMAT_ID_BINARY) gsl_matrix_fread(ptilt_file,*(ptilt));\n\tfclose(ptilt_file);}\n\n\tif(params->use_harmonics == 1) {strcpy(temp, params->pulselibrary_filename);FILE *pharm_file = fopen(strcat(temp,FILENAME_ENDING_PULSELIB_HARM), \"r\");\n\tif(pharm_file==NULL){printf(\"Error opening file \\\"%s\\\": %s\\n\",temp,strerror(errno));return EXIT_FAILURE;}\n\tif(params->data_format == DATA_FORMAT_ID_ASCII)\tgsl_matrix_fscanf(pharm_file,*(pharm));\n\telse if(params->data_format == DATA_FORMAT_ID_BINARY) gsl_matrix_fread(pharm_file,*(pharm));\n\tfclose(pharm_file);}\n\n\tif(params->use_hnr == 1) {strcpy(temp, params->pulselibrary_filename);FILE *phnr_file = fopen(strcat(temp,FILENAME_ENDING_PULSELIB_HNR), \"r\");\n\tif(phnr_file==NULL){printf(\"Error opening file \\\"%s\\\": %s\\n\",temp,strerror(errno));return EXIT_FAILURE;}\n\tif(params->data_format == DATA_FORMAT_ID_ASCII)\tgsl_matrix_fscanf(phnr_file,*(phnr));\n\telse if(params->data_format == DATA_FORMAT_ID_BINARY) gsl_matrix_fread(phnr_file,*(phnr));\n\tfclose(phnr_file);}\n\n\tif(params->use_waveform == 1) {strcpy(temp, params->pulselibrary_filename);FILE *pwaveform_file = fopen(strcat(temp,FILENAME_ENDING_PULSELIB_WAVEFORM), \"r\");\n\tif(pwaveform_file==NULL){printf(\"Error opening file \\\"%s\\\": %s\\n\",temp,strerror(errno));return EXIT_FAILURE;}\n\tif(params->data_format == DATA_FORMAT_ID_ASCII)\tgsl_matrix_fscanf(pwaveform_file,*(pwaveform));\n\telse if(params->data_format == DATA_FORMAT_ID_BINARY) gsl_matrix_fread(pwaveform_file,*(pwaveform));\n\tfclose(pwaveform_file);}\n\n\tif(params->use_h1h2 == 1) {strcpy(temp, params->pulselibrary_filename);FILE *ph1h2_file = fopen(strcat(temp,FILENAME_ENDING_PULSELIB_H1H2), \"r\");\n\tif(ph1h2_file==NULL){printf(\"Error opening file \\\"%s\\\": %s\\n\",temp,strerror(errno));return EXIT_FAILURE;}\n\tif(params->data_format == DATA_FORMAT_ID_ASCII)\tgsl_vector_fscanf(ph1h2_file,*(ph1h2));\n\telse if(params->data_format == DATA_FORMAT_ID_BINARY) gsl_vector_fread(ph1h2_file,*(ph1h2));\n\tfclose(ph1h2_file);}\n\n\tif(params->use_naq == 1) {strcpy(temp, params->pulselibrary_filename);FILE *pnaq_file = fopen(strcat(temp,FILENAME_ENDING_PULSELIB_NAQ), \"r\");\n\tif(pnaq_file==NULL){printf(\"Error opening file \\\"%s\\\": %s\\n\",temp,strerror(errno));return EXIT_FAILURE;}\n\tif(params->data_format == DATA_FORMAT_ID_ASCII)\tgsl_vector_fscanf(pnaq_file,*(pnaq));\n\telse if(params->data_format == DATA_FORMAT_ID_BINARY) gsl_vector_fread(pnaq_file,*(pnaq));\n\tfclose(pnaq_file);}\n\n\t/* Normalize the sum of paramweights to one */\n\tdouble sum = 0;\n\tint i;\n\tfor(i=0;i<params->paramweights->size;i++)\n\t\tsum += gsl_vector_get(params->paramweights,i);\n\tfor(i=0;i<params->paramweights->size;i++)\n\t\tgsl_vector_set(params->paramweights,i,gsl_vector_get(params->paramweights,i)/sum);\n\n\t/* Allocate space for pulse library PCA parameters */\n\tif(params->use_pulselib_pca == 1) {\n\t\t*(pca_pc) = gsl_matrix_calloc(params->pca_pulse_length,params->pca_order);\n\t\t*(pca_mean) = gsl_vector_calloc(params->pca_pulse_length);\n\t\t*(stoch_env) = gsl_vector_calloc(params->rspulsemaxlen);\n\t\t*(stoch_sp) = gsl_vector_calloc(STOCH_SP_LPC_ORDER);\n\n\t\tstrcpy(temp, params->pulselibrary_filename);FILE *pca_pc_file = fopen(strcat(temp,FILENAME_ENDING_PULSELIB_PCA_PC), \"r\");\n\t\tif(pca_pc_file==NULL){printf(\"Error opening file \\\"%s\\\": %s\\n\",temp,strerror(errno));return EXIT_FAILURE;}\n\t\tif(params->data_format == DATA_FORMAT_ID_ASCII) gsl_matrix_fscanf(pca_pc_file,*(pca_pc));\n\t\telse if(params->data_format == DATA_FORMAT_ID_BINARY) gsl_matrix_fread(pca_pc_file,*(pca_pc));\n\t\tfclose(pca_pc_file);\n\n\t\tstrcpy(temp, params->pulselibrary_filename);FILE *pca_mean_file = fopen(strcat(temp,FILENAME_ENDING_PULSELIB_PCA_MEAN), \"r\");\n\t\tif(pca_mean_file==NULL){printf(\"Error opening file \\\"%s\\\": %s\\n\",temp,strerror(errno));return EXIT_FAILURE;}\n\t\tif(params->data_format == DATA_FORMAT_ID_ASCII) gsl_vector_fscanf(pca_mean_file,*(pca_mean));\n\t\telse if(params->data_format == DATA_FORMAT_ID_BINARY) gsl_vector_fread(pca_mean_file,*(pca_mean));\n\t\tfclose(pca_mean_file);\n\n\t\t//strcpy(temp, params->pulselibrary_filename);FILE *stoch_env_file = fopen(strcat(temp,FILENAME_ENDING_PULSELIB_STOCH_ENV), \"r\");\n\t\t//if(stoch_env_file==NULL){printf(\"Error opening file \\\"%s\\\": %s\\n\",temp,strerror(errno));return EXIT_FAILURE;}\n\t\t//if(params->data_format == DATA_FORMAT_ID_ASCII) gsl_vector_fscanf(stoch_env_file,*(stoch_env));\n\t\t//else if(params->data_format == DATA_FORMAT_ID_BINARY) gsl_vector_fread(stoch_env_file,*(stoch_env));\n\t\t//fclose(stoch_env_file);\n\n\t\t//strcpy(temp, params->pulselibrary_filename);FILE *stoch_sp_file = fopen(strcat(temp,FILENAME_ENDING_PULSELIB_STOCH_SP), \"r\");\n\t\t//if(stoch_sp_file==NULL){printf(\"Error opening file \\\"%s\\\": %s\\n\",temp,strerror(errno));return EXIT_FAILURE;}\n\t\t//if(params->data_format == DATA_FORMAT_ID_ASCII) gsl_vector_fscanf(stoch_sp_file,*(stoch_sp));\n\t\t//else if(params->data_format == DATA_FORMAT_ID_BINARY) gsl_vector_fread(stoch_sp_file,*(stoch_sp));\n\t\t//fclose(stoch_sp_file);\n\t} else {\n\t\t*(pca_pc) = NULL;\n\t\t*(pca_mean) = NULL;\n\t\t*(stoch_env) = NULL;\n\t\t*(stoch_sp) = NULL;\n\t}\n\n\t/* Allocate space for pulse PCA parameters */\n\tif(params->use_pulse_pca == 1) {\n\t\t*(pca_w_lib) = gsl_matrix_calloc(params->number_of_pulses,params->pca_order);\n\t\tstrcpy(temp, params->pulselibrary_filename);FILE *pca_w_lib_file = fopen(strcat(temp,FILENAME_ENDING_PULSELIB_PCA_W), \"r\");\n\t\tif(pca_w_lib_file==NULL){printf(\"Error opening file \\\"%s\\\": %s\\n\",temp,strerror(errno));return EXIT_FAILURE;}\n\t\tif(params->data_format == DATA_FORMAT_ID_ASCII) gsl_matrix_fscanf(pca_w_lib_file,*(pca_w_lib));\n\t\telse if(params->data_format == DATA_FORMAT_ID_BINARY) gsl_matrix_fread(pca_w_lib_file,*(pca_w_lib));\n\t\tfclose(pca_w_lib_file);\n\t} else {\n\t\t*(pca_w_lib) = NULL;\n\t}\n\n\t/* Print elapsed time */\n\tprintf(\"\t  (%1.2lf s)\\n\",((double)clock()-time1)/(double)CLOCKS_PER_SEC);\n\tparams->time_temp = (double)clock();\n\treturn EXIT_SUCCESS;\n}\n\n\n\n\n\n\n\n/**\n * Function ReadPulseFile\n *\n * Read pulse values from file\n *\n * @param name filename\n * @return vector containing the values\n */\ngsl_vector *ReadPulseFile(PARAM *params) {\n\n\tFILE *file;\n\tdouble values[1000];\n\tchar s[50];\n\tint i,ind;\n\n\t/* Open file */\n\tfile = fopen(params->pulse_filename, \"r\");\n\tif(!file) {\n\t\tprintf(\"Error opening pulse file \\\"%s\\\": %s\\n\", params->pulse_filename, strerror(errno));\n\t\treturn NULL;\n\t}\n\n\t/* Read lines until EOF */\n\tind = 0;\n\twhile(fscanf(file,\"%s\",s) != EOF) {\n\t\tvalues[ind] = atof(s);\n\t\tind++;\n\t}\n\n\t/* Copy values to vector and return vector pointer */\n\tgsl_vector *pulse = gsl_vector_alloc(ind);\n\tfor(i=0;i<ind;i++) {\n\t\tgsl_vector_set(pulse,i,values[i]);\n\t}\n\tfclose(file);\n\treturn pulse;\n}\n\n\n\n\n/**\n * Function Initialize_params\n *\n * Initialize params file\n *\n * @param params\n * @return synfilenumber\n */\nint Initialize_params(PARAM *params, int synfilenumber) {\n\n\t/* Initialize parameters for synthesizing new file */\n\tparams->synfilenumber = synfilenumber;\n\tparams->resynth = 0;\n\tparams->compcoeff = 1.0;\n\tparams->hnr_reestimated = 0;\n\tparams->pulse_tilt_decrease_coeff = 1;\n\n\t/* Modification for noise robust speech */\n\tNoise_robust_speech1(params);\n\n\t/* Count the number of frames */\n\tchar temp[DEF_STRING_LEN];\n\tstrcpy(temp, params->synlist[params->synfilenumber]);\n\tparams->n_frames = EvalFileLength(strcat(temp,FILENAME_ENDING_F0),params);\n\n\t/* Evaluate signal length */\n\tparams->signal_length = rint(params->n_frames*params->shift/params->speed);\n\n\t// For replicating the exact analysis-synthesis file length\n\t//int empty_frames = rint((params->frame_length/(double)params->shift - 1)/2);\n\t//int frames_orig = params->n_frames - 2*empty_frames;\n\t//params->signal_length = (frames_orig + params->frame_length/(double)params->shift/params->speed - 1.0)*(double)params->shift/params->speed;\n\n\t/* Return */\n\tif(params->n_frames == -1) {\n\t\treturn EXIT_FAILURE;\n\t}\n\tif(params->n_frames == 0) {\n\t\tprintf(\"\\nError: Zero length F0 vector\\n\\n\");\n\t\treturn EXIT_FAILURE;\n\t}\n\treturn EXIT_SUCCESS;\n}\n\n\n\n\n\n\n\n\n/**\n * Function EvalFileLength\n *\n * If file is in ASCII mode, read file and count the number of lines.\n * If file is in BINARY mode, read file size.\n *\n * @param name filename\n * @return number of parameters\n */\nint EvalFileLength(const char *name, PARAM *params) {\n\n\tFILE *file;\n\tchar s[50];\n\tint fileSize = 0;\n\n\t/* Open file */\n\tfile = fopen(name, \"r\");\n\tif(!file) {\n\t\tprintf(\"Error opening file \\\"%s\\\": %s\\n\", name, strerror(errno));\n\t\treturn -1;\n\t}\n\n\t/* Read lines until EOF */\n\tif(params->data_format == DATA_FORMAT_ID_ASCII) {\n\t\twhile(fscanf(file,\"%s\",s) != EOF)\n\t\t\tfileSize++;\n\t} else if(params->data_format == DATA_FORMAT_ID_BINARY) {\n\t\tfseek(file, 0, SEEK_END);\n\t\tfileSize = ftell(file)/sizeof(double);\n\t}\n\tfclose(file);\n\n\treturn fileSize;\n}\n\n\n\n\n\n\n/**\n * Function Print_synthesis_settings_start\n *\n * Print synthesis settings in the beginning\n *\n * @param params\n */\nvoid Print_synthesis_settings_start(PARAM *params) {\n\n\tprintf(\"Synthesis of %s\\n\",params->synlist[0]);\n}\n\n\n\n/**\n * Function Print_synthesis_settings_middle\n *\n * Print synthesis settings in progress\n *\n * @param params\n */\nvoid Print_synthesis_settings_middle(PARAM *params) {\n\n\tif(params->synfilenumber > 0) {\n\t\tprintf(\"Synthesis of %s\\n\",params->synlist[params->synfilenumber]);\n\t}\n}\n\n\n\n\n/**\n * Function Print_synthesis_settings_end\n *\n * Print synthesis settings in the end\n *\n * @param filename\n * @param params\n\n */\nvoid Print_synthesis_settings_end(PARAM *params, double time1) {\n\n\t/* Speech file name */\n\tchar temp[DEF_STRING_LEN];\n\tstrcpy(temp, params->synlist[params->synfilenumber]);\n\tstrcat(temp,FILENAME_ENDING_SYNTHESIS);\n\n\t/* Print at the end of synthesis of one file */\n\tif(params->multisyn == 1) {\n\t\tprintf(\"\t  (%1.2lf s)\\n\",((double)clock()-params->time_temp)/(double)CLOCKS_PER_SEC);\n\t\tprintf(\"\t- Finished synthesis of %s\\n\\n\",temp);\n\t}\n\n\t/* Print at the of the program */\n\tif(params->synfilenumber == params->synlistlen-1) {\n\t\tif(params->multisyn == 0) {\n\t\t\tprintf(\"\t  (%1.2lf s)\\n\",((double)clock()-params->time_temp)/(double)CLOCKS_PER_SEC);\n\t\t\tprintf(\"\t- Finished synthesis.\\n\\n\");\n\t\t\tprintf(\"Elapsed time: %1.2lf seconds.\\n\",((double)clock()-time1)/(double)CLOCKS_PER_SEC);\n\t\t\tprintf(\"Synthesized speech saved to file \\\"%s\\\".\\n\\n\",temp);\n\t\t} else {\n\t\t\tprintf(\"Finished synthesis of files:\\n\\n\");\n\t\t\tint i;\n\t\t\tfor(i=0;i<params->synlistlen;i++)\n\t\t\t\tprintf(\"   %s\\n\",params->synlist[i]);\n\t\t\tdouble t = ((double)clock()-time1)/(double)CLOCKS_PER_SEC;\n\t\t\tprintf(\"\\nTotal elapsed time: %1.2lf seconds (average %1.2lf seconds per file).\\n\\n\",t,t/(double)params->synlistlen);\n\t\t}\n\t}\n}\n\n\n\n\n\n/**\n * Function Compatibility_check\n *\n * Check the compatibility with configuration and pulse library parameters\n *\n * @param params\n */\nint Compatibility_check(PARAM *params) {\n\n\t/* Initialize */\n\tchar temp[DEF_STRING_LEN];\n\tFILE *parameter_file;\n\n\t/* Open parameter file */\n\tstrcpy(temp, params->synlist[params->synfilenumber]);\n\tparameter_file = fopen(strcat(temp,FILENAME_ENDING_INFO), \"r\");\n\n\t/* If parameter file is found, check compatibility */\n\tif(parameter_file == NULL) {\n\t\tif(params->use_hmm == 0)\n\t\t\tprintf(\"\\\"%s\\\" was not found, proceed without compatibility check.\\n\\n\",temp);\n\t\tif(parameter_file != NULL)\n\t\t\tfclose(parameter_file);\n\t} else {\n\t\tgsl_vector *parameters = gsl_vector_alloc(NPARAMS);\n\t\tgsl_vector_fscanf(parameter_file,parameters);\n\t\tif(params->frame_length_ms != gsl_vector_get(parameters,0)) {printf(\"\\nWarning: Different frame length in analysis and synthesis\\n\\n\");}\n\t\tif(params->shift_ms != gsl_vector_get(parameters,1)) {printf(\"\\nWarning: Different shift length in analysis and synthesis\\n\\n\");}\n\t\tif(params->n_frames != (int)gsl_vector_get(parameters,2)) {printf(\"\\nWarning: infofile indicates a different number of frames compared to actual files\\n\\n\");}\n\t\tif(params->n_frames < 1) {printf(\"\\nError: Zero-length input parameters\\n\\n\");return EXIT_FAILURE;}\n\t\tif(params->lpc_order_vt != (int)gsl_vector_get(parameters,3)) {printf(\"\\nError: Different vocal tract LPC order in analysis and synthesis\\n\\n\"); return EXIT_FAILURE;}\n\t\tif(params->lpc_order_gl != (int)gsl_vector_get(parameters,4)) {printf(\"\\nError: Different source LPC order in analysis and synthesis\\n\\n\"); return EXIT_FAILURE;}\n\t\tif(params->lambda_gl != gsl_vector_get(parameters,6)) {printf(\"\\nError: Different source warping coefficient in analysis and synthesis\\n\\n\"); return EXIT_FAILURE;}\n\t\tif(params->hnr_channels != gsl_vector_get(parameters,7)) {printf(\"\\nError: Different number of HNR channels in analysis and synthesis\\n\\n\"); return EXIT_FAILURE;}\n\t\tif(params->number_of_harmonics != gsl_vector_get(parameters,8)) {printf(\"\\nError: Different number of harmonics in analysis and synthesis\\n\\n\"); return EXIT_FAILURE;}\n\t\tif(params->lambda_vt != gsl_vector_get(parameters,5)) {printf(\"\\nWarning: Different vocal tract warping coefficient in analysis and synthesis\\n\\n\");}\n\t\tif(params->FS != gsl_vector_get(parameters,13)) {printf(\"\\nWarning: Different sampling frequency in analysis and synthesis\\n\\n\");}\n\t\tif(params->gain_voiced_frame_length_ms > params->frame_length_ms || params->gain_unvoiced_frame_length_ms > params->frame_length_ms) {printf(\"\\nError: Voiced/unvoiced frame length must be less or equal to frame length\\n\\n\"); return EXIT_FAILURE;}\n\t\tif(params->data_format != (int)gsl_vector_get(parameters,14)) {printf(\"\\nError: Different data format (ascii/binary)\\n\\n\"); return EXIT_FAILURE;}\n\t\tgsl_vector_free(parameters);\n\t\tfclose(parameter_file);\n\t}\n\n\t/* Check compatibility with used parameters and synthesis method */\n\tif(params->use_pulselib == 0) {\n\t\tif(params->use_tilt == 0) {printf(\"\\nError: Spectral tilt (LSFsource) must be used with single pulse technique.\\n\\n\");return EXIT_FAILURE;}\n\t\tif(params->use_hnr == 0) {printf(\"\\nError: Harmonic to noise ratio (HNR) must be used with single pulse technique.\\n\\n\");return EXIT_FAILURE;}\n\t\tif(params->use_harmonic_modification == 1 && params->use_harmonics == 0) {printf(\"\\nError: Harmonics must be used with harmonic modification of the pulse.\\n\\n\");return EXIT_FAILURE;}\n\t}\n\n\t/* Check compatibility with PCA/ICA */\n\tif(params->use_pulselib_pca == 1 && params->use_pulselib == 0) {printf(\"\\nError: Pulse library must be used with PCA/ICA based pulse reconstruction.\\n\\n\");return EXIT_FAILURE;}\n\n\treturn EXIT_SUCCESS;\n}\n\n\n\n\n\n/**\n * Function Allocate_params\n *\n * Allocate synthesis parameters\n *\n * @param params\n */\nvoid Allocate_params(gsl_vector **excitation_voiced, gsl_vector **excitation_unvoiced, gsl_vector **resynthesis_pulse_index,\n\t\tgsl_vector **gain_new, gsl_matrix **glflowsp_new, gsl_matrix **hnr_new, PARAM *params) {\n\n\t/* Allocate */\n\t*(excitation_voiced) = gsl_vector_calloc(params->signal_length);\n\t*(excitation_unvoiced) = gsl_vector_calloc(params->signal_length);\n\t*(gain_new) = gsl_vector_calloc(params->n_frames);\n\t*(hnr_new) = gsl_matrix_calloc(params->n_frames,params->hnr_channels);\n\t*(glflowsp_new) = gsl_matrix_calloc(params->n_frames,params->lpc_order_gl);\n\t*(resynthesis_pulse_index) = gsl_vector_calloc(params->n_frames);\n}\n\n\n\n\n\n\n\n\n\n/**\n * Function Read_synthesis_parameters\n *\n * Allocate and read synthesis parameters\n *\n * @param params\n */\nint Read_synthesis_parameters(gsl_vector **gain, gsl_vector **fundf, gsl_matrix **LSF, gsl_matrix **LSF2, gsl_matrix **glflowsp,\n\t\tgsl_matrix **hnr, gsl_matrix **harmonics, gsl_matrix **waveform, gsl_vector **h1h2, gsl_vector **naq, gsl_matrix **pca_w, PARAM *params) {\n\n\t/* Initialize */\n\tchar temp[DEF_STRING_LEN];\n\n\t/* Define variables */\n\tFILE *LSF_file = NULL,*LSF2_file = NULL,*Gain_file = NULL,*F0_file = NULL,*LSFsource_file = NULL,*hnr_file = NULL;\n\tFILE *harmonics_file = NULL,*waveform_file = NULL,*h1h2_file = NULL,*naq_file = NULL;\n\n\t/* Allocate memory for variables (affected by differential LSFs processing) */\n\tif(params->differential_lsf == 1)\n\t\t*(LSF) = gsl_matrix_alloc(params->n_frames,params->lpc_order_vt+1);\n\telse\n\t\t*(LSF) = gsl_matrix_alloc(params->n_frames,params->lpc_order_vt);\n\tif(params->use_tilt == 1)\n\t\tif(params->differential_lsf == 1)\n\t\t\t*(glflowsp) = gsl_matrix_alloc(params->n_frames,params->lpc_order_gl+1);\n\t\telse\n\t\t\t*(glflowsp) = gsl_matrix_alloc(params->n_frames,params->lpc_order_gl);\n\telse\n\t\t*(glflowsp) = NULL;\n\tif(params->sep_vuv_spectrum == 1)\n\t\tif(params->differential_lsf == 1)\n\t\t\t*(LSF2) = gsl_matrix_alloc(params->n_frames,params->lpc_order_vt+1);\n\t\telse\n\t\t\t*(LSF2) = gsl_matrix_alloc(params->n_frames,params->lpc_order_vt);\n\telse\n\t\t*(LSF2) = NULL;\n\n\t/* Allocate memory for variables */\n\t*(gain) = gsl_vector_alloc(params->n_frames);\n\t*(fundf) = gsl_vector_alloc(params->n_frames);\n\tif(params->use_hnr == 1) *(hnr) = gsl_matrix_alloc(params->n_frames,params->hnr_channels);\n\telse *(hnr) = NULL;\n\tif(params->use_harmonics == 1) *(harmonics) = gsl_matrix_alloc(params->n_frames,params->number_of_harmonics);\n\telse *(harmonics) = NULL;\n\tif(params->use_waveform == 1) *(waveform) = gsl_matrix_alloc(params->n_frames,params->waveform_samples);\n\telse *(waveform) = NULL;\n\tif(params->use_h1h2 == 1) *(h1h2) = gsl_vector_alloc(params->n_frames);\n\telse *(h1h2) = NULL;\n\tif(params->use_naq == 1) *(naq) = gsl_vector_alloc(params->n_frames);\n\telse *(naq) = NULL;\n\n\n\t/* Open files */\n\tstrcpy(temp, params->synlist[params->synfilenumber]);LSF_file = fopen(strcat(temp,FILENAME_ENDING_LSF), \"r\");\n\tif(LSF_file==NULL){printf(\"Error opening file \\\"%s\\\": %s\\n\",temp,strerror(errno));return EXIT_FAILURE;}\n\tstrcpy(temp, params->synlist[params->synfilenumber]);Gain_file = fopen(strcat(temp,FILENAME_ENDING_GAIN), \"r\");\n\tif(Gain_file==NULL){printf(\"Error opening file \\\"%s\\\": %s\\n\",temp,strerror(errno));return EXIT_FAILURE;}\n\tstrcpy(temp, params->synlist[params->synfilenumber]);F0_file = fopen(strcat(temp,FILENAME_ENDING_F0), \"r\");\n\tif(F0_file==NULL){printf(\"Error opening file \\\"%s\\\": %s\\n\",temp,strerror(errno));return EXIT_FAILURE;}\n\tif(params->use_tilt == 1) {strcpy(temp, params->synlist[params->synfilenumber]);LSFsource_file = fopen(strcat(temp,FILENAME_ENDING_LSFSOURCE), \"r\");\n\t\tif(LSFsource_file==NULL){printf(\"Error opening file \\\"%s\\\": %s\\n\",temp,strerror(errno));return EXIT_FAILURE;}}\n\tif(params->use_hnr == 1) {strcpy(temp, params->synlist[params->synfilenumber]);hnr_file = fopen(strcat(temp,FILENAME_ENDING_HNR), \"r\");\n\t\tif(hnr_file==NULL){printf(\"Error opening file \\\"%s\\\": %s\\n\",temp,strerror(errno));return EXIT_FAILURE;}}\n\tif(params->use_harmonics == 1) {strcpy(temp, params->synlist[params->synfilenumber]);harmonics_file = fopen(strcat(temp,FILENAME_ENDING_HARMONICS), \"r\");\n\t\tif(harmonics_file==NULL){printf(\"Error opening file \\\"%s\\\": %s\\n\",temp,strerror(errno));return EXIT_FAILURE;}}\n\tif(params->use_waveform == 1) {strcpy(temp, params->synlist[params->synfilenumber]);waveform_file = fopen(strcat(temp,FILENAME_ENDING_WAVEFORM), \"r\");\n\t\tif(waveform_file==NULL){printf(\"Error opening file \\\"%s\\\": %s\\n\",temp,strerror(errno));return EXIT_FAILURE;}}\n\tif(params->use_h1h2 == 1) {strcpy(temp, params->synlist[params->synfilenumber]);h1h2_file = fopen(strcat(temp,FILENAME_ENDING_H1H2), \"r\");\n\t\tif(h1h2_file==NULL){printf(\"Error opening file \\\"%s\\\": %s\\n\",temp,strerror(errno));return EXIT_FAILURE;}}\n\tif(params->use_naq == 1) {strcpy(temp, params->synlist[params->synfilenumber]);naq_file = fopen(strcat(temp,FILENAME_ENDING_NAQ), \"r\");\n\t\tif(naq_file==NULL){printf(\"Error opening file \\\"%s\\\": %s\\n\",temp,strerror(errno));return EXIT_FAILURE;}}\n\tif(params->sep_vuv_spectrum == 1) {strcpy(temp, params->synlist[params->synfilenumber]);LSF2_file = fopen(strcat(temp,FILENAME_ENDING_LSF2), \"r\");\n\t\tif(LSF2_file==NULL){printf(\"Error opening file \\\"%s\\\": %s.\\nSet configuration parameter SEPARATE_VOICED_UNVOICED_SPECTRUM to zero if single spectrum is used.\\n\",temp,strerror(errno));return EXIT_FAILURE;}}\n\n\t/* Read parameters from files */\n\tif(params->data_format == DATA_FORMAT_ID_ASCII) {\n\t\tgsl_vector_fscanf(Gain_file,*(gain));\n\t\tgsl_vector_fscanf(F0_file,*(fundf));\n\t\tgsl_matrix_fscanf(LSF_file,*(LSF));\n\t\tif(params->use_tilt == 1) gsl_matrix_fscanf(LSFsource_file,*(glflowsp));\n\t\tif(params->use_hnr == 1) gsl_matrix_fscanf(hnr_file,*(hnr));\n\t\tif(params->use_harmonics == 1) gsl_matrix_fscanf(harmonics_file,*(harmonics));\n\t\tif(params->use_waveform == 1) gsl_matrix_fscanf(waveform_file,*(waveform));\n\t\tif(params->use_h1h2 == 1) gsl_vector_fscanf(h1h2_file,*(h1h2));\n\t\tif(params->use_naq == 1) gsl_vector_fscanf(naq_file,*(naq));\n\t\tif(params->sep_vuv_spectrum == 1) gsl_matrix_fscanf(LSF2_file,*(LSF2));\n\t} else if(params->data_format == DATA_FORMAT_ID_BINARY) {\n\t\tgsl_vector_fread(Gain_file,*(gain));\n\t\tgsl_vector_fread(F0_file,*(fundf));\n\t\tgsl_matrix_fread(LSF_file,*(LSF));\n\t\tif(params->use_tilt == 1) gsl_matrix_fread(LSFsource_file,*(glflowsp));\n\t\tif(params->use_hnr == 1) gsl_matrix_fread(hnr_file,*(hnr));\n\t\tif(params->use_harmonics == 1) gsl_matrix_fread(harmonics_file,*(harmonics));\n\t\tif(params->use_waveform == 1) gsl_matrix_fread(waveform_file,*(waveform));\n\t\tif(params->use_h1h2 == 1) gsl_vector_fread(h1h2_file,*(h1h2));\n\t\tif(params->use_naq == 1) gsl_vector_fread(naq_file,*(naq));\n\t\tif(params->sep_vuv_spectrum == 1) gsl_matrix_fread(LSF2_file,*(LSF2));\n\t}\n\n\t/* Close files */\n\tfclose(F0_file);\n\tfclose(LSF_file);\n\tfclose(Gain_file);\n\tif(params->use_tilt == 1) fclose(LSFsource_file);\n\tif(params->use_hnr == 1) fclose(hnr_file);\n\tif(params->use_harmonics == 1)fclose(harmonics_file);\n\tif(params->use_waveform == 1) fclose(waveform_file);\n\tif(params->use_h1h2 == 1) fclose(h1h2_file);\n\tif(params->use_naq == 1) fclose(naq_file);\n\tif(params->sep_vuv_spectrum == 1) fclose(LSF2_file);\n\n\t/* Read pulse library PCA weights */\n\tif(params->use_pulselib_pca == 1 || params->use_pulse_pca == 1) {\n\n\t\t/* Initialize */\n\t\tFILE *pca_w_file;\n\t\t*(pca_w) = gsl_matrix_calloc(params->n_frames,params->pca_order);\n\n\t\t/* Load only if PC weights are used in synthesis of the mean pulse */\n\t\tif(params->use_pulselib_pca == 1 && params->pca_order_synthesis > 0 && params->use_dnn_pulsegen == 0) {\n\t\t\tstrcpy(temp, params->synlist[params->synfilenumber]);\n\t\t\tpca_w_file = fopen(strcat(temp,FILENAME_ENDING_PULSELIB_PCA_W), \"r\");\n\t\t\tif(pca_w_file==NULL) {\n\t\t\t\tprintf(\"Error opening file \\\"%s\\\": %s\\n\",temp,strerror(errno));\n\t\t\t\treturn EXIT_FAILURE;\n\t\t\t}\n\t\t\tif(params->data_format == DATA_FORMAT_ID_ASCII) {\n\t\t\t\tgsl_matrix_fscanf(pca_w_file,*(pca_w));\n\t\t\t} else if(params->data_format == DATA_FORMAT_ID_BINARY) {\n\t\t\t\tgsl_matrix_fread(pca_w_file,*(pca_w));\n\t\t\t}\n\t\t\tfclose(pca_w_file);\n\t\t}\n\t}\n\treturn EXIT_SUCCESS;\n}\n\n\n\n\n\n\n/**\n * Function Print_elapsed_time\n *\n * Print elapsed time\n *\n * @param\n */\nvoid Print_elapsed_time(PARAM *params) {\n\n\tprintf(\"\t  (%1.2lf s)\\n\",((double)clock()-params->time_temp)/(double)CLOCKS_PER_SEC);\n\tparams->time_temp = (double)clock();\n}\n\n\n/**\n * Function Pulse_clustering\n *\n * Read file and count the number of lines\n *\n * @param pulse_clus_id pointer to pulse cluster ids\n * @param pulse_clusters pointer to pulse clusters\n * @param params paramteres structure\n * @param synfilenumber\n * @return\n */\nint Pulse_clustering(gsl_vector **pulse_clus_id_POINTER, gsl_matrix **pulse_clusters_POINTER, PARAM *params) {\n\n\tif(params->pulse_clustering == 1) {\n\n\t\t/* Initialize */\n\t\tgsl_vector *pulse_clus_id;\n\t\tgsl_matrix *pulse_clusters;\n\t\tFILE *pulse_clus_id_file;\n\t\tchar temp[DEF_STRING_LEN];\n\t\tint i,j;\n\n\t\t/* Read cluster ids per frame */\n\t\tstrcpy(temp, params->synlist[params->synfilenumber]);pulse_clus_id_file = fopen(strcat(temp,FILENAME_ENDING_PULSECLUSTER), \"r\");\n\t\tif(pulse_clus_id_file==NULL){printf(\"Error opening file \\\"%s\\\": %s\\n\",temp,strerror(errno));return EXIT_FAILURE;}\n\t\tpulse_clus_id = gsl_vector_alloc(params->n_frames);\n\t\tif(params->data_format == DATA_FORMAT_ID_ASCII)\n\t\t\tgsl_vector_fscanf(pulse_clus_id_file, pulse_clus_id);\n\t\telse if(params->data_format == DATA_FORMAT_ID_BINARY)\n\t\t\tgsl_vector_fread(pulse_clus_id_file, pulse_clus_id);\n\t\tfclose(pulse_clus_id_file);\n\n\t\t/* Read clusters that are used in utterance */\n\t\tpulse_clusters = gsl_matrix_alloc((int)(gsl_vector_max(pulse_clus_id)+1), params->max_pulses_in_cluster);\n\t\tgsl_matrix_set_all(pulse_clusters, -1);\n\t\tfor(i=0;i<pulse_clus_id->size;i++) {\n\n\t\t\tsprintf(temp, \"%s_clusters/%d\", params->pulselibrary_filename, (int)gsl_vector_get(pulse_clus_id, i));\n\t\t\tint n_p = EvalFileLength(temp,params);\n\t\t\tFILE *cluster_file = fopen(temp, \"r\");\n\t\t\tif(cluster_file==NULL) {printf(\"Error opening file \\\"%s\\\": %s\\n\",temp,strerror(errno));return EXIT_FAILURE;}\n\n\t\t\t/* Allocate correctly sized vector */\n\t\t\tgsl_vector *temp_v;\n\t\t\tif(n_p > 0) {\n\t\t\t\ttemp_v = gsl_vector_alloc(n_p);\n\t\t\t\tcluster_file = fopen(temp, \"r\");\n\t\t\t\tif(params->data_format == DATA_FORMAT_ID_ASCII)\n\t\t\t\t\tgsl_vector_fscanf(cluster_file, temp_v);\n\t\t\t\telse if(params->data_format == DATA_FORMAT_ID_BINARY)\n\t\t\t\t\tgsl_vector_fread(cluster_file, temp_v);\n\t\t\t\tfclose(cluster_file);\n\n\t\t\t\t/* Add clusters to matrix (terribly sparse) */\n\t\t\t\tfor(j=0;j<temp_v->size;j++) {\n\t\t\t\t\tif(j == params->max_pulses_in_cluster) break;\n\t\t\t\t\tgsl_matrix_set(pulse_clusters, gsl_vector_get(pulse_clus_id, i), j,  gsl_vector_get(temp_v, j));\n\t\t\t\t}\n\t\t\t\tgsl_vector_free(temp_v);\n\t\t\t}\n\t\t}\n\n\t\t/* Set pointers */\n\t\t*(pulse_clus_id_POINTER) = pulse_clus_id;\n\t\t*(pulse_clusters_POINTER) = pulse_clusters;\n\t\treturn EXIT_SUCCESS;\n\t}\n\treturn EXIT_SUCCESS;\n}\n\n\n\n\n\n/**\n * Function LSF_fix_vector\n *\n * Check the validity of LSF and fix found errors (vector)\n *\n * @param lsf vector\n */\nvoid LSF_fix_vector(gsl_vector *lsf) {\n\n\tint i,ok = 0;\n\tdouble mean;\n\tint flag_neg = 0;\n\tint flag_zero = 0;\n\tint flag_pi = 0;\n\tint flag_piplus = 0;\n\tint flag_nan = 0;\n\tint flag_dec = 0;\n\tint flag_close = 0;\n\n\t/* Repeat until LSF is fixed */\n\twhile(ok == 0) {\n\n\t\t/* Set ok */\n\t\tok = 1;\n\n\t\t/* Check and correct values less than zero or greater than pi */\n\t\tfor(i=0;i<lsf->size;i++) {\n\t\t\tif(gsl_vector_get(lsf,i) < 0) {\n\t\t\t\tgsl_vector_set(lsf,i,LSF_EPSILON);\n\t\t\t\tflag_neg++;\n\t\t\t\tok = 0;\n\t\t\t} else if(gsl_vector_get(lsf,i) < LSF_EPSILON) {\n\t\t\t\tgsl_vector_set(lsf,i,LSF_EPSILON);\n\t\t\t\tflag_zero++;\n\t\t\t\tok = 0;\n\t\t\t} else if(gsl_vector_get(lsf,i) > M_PI) {\n\t\t\t\tgsl_vector_set(lsf,i,M_PI-LSF_EPSILON);\n\t\t\t\tflag_piplus++;\n\t\t\t\tok = 0;\n\t\t\t} else if(gsl_vector_get(lsf,i) > M_PI-LSF_EPSILON) {\n\t\t\t\tgsl_vector_set(lsf,i,M_PI-LSF_EPSILON);\n\t\t\t\tflag_pi++;\n\t\t\t\tok = 0;\n\t\t\t}\n\t\t\tif(gsl_isnan(gsl_vector_get(lsf,i))) {\n\t\t\t\tif(i == 0)\n\t\t\t\t\tgsl_vector_set(lsf,i,LSF_EPSILON);\n\t\t\t\telse if(i == lsf->size-1)\n\t\t\t\t\tgsl_vector_set(lsf,i,M_PI-LSF_EPSILON);\n\t\t\t\telse\n\t\t\t\t\tgsl_vector_set(lsf,i,(gsl_vector_get(lsf,i-1)+gsl_vector_get(lsf,i+1))/2.0);\n\t\t\t\tflag_nan++;\n\t\t\t\tok = 0;\n\t\t\t}\n\t\t}\n\n\t\t/* Check and correct non-increasing values or coefficients too close */\n\t\tfor(i=0;i<lsf->size-1;i++) {\n\t\t\tif(gsl_vector_get(lsf,i) > gsl_vector_get(lsf,i+1)) {\n\t\t\t\tmean = (gsl_vector_get(lsf,i)+gsl_vector_get(lsf,i+1))/2.0;\n\t\t\t\tgsl_vector_set(lsf,i,mean - LSF_EPSILON/2.0);\n\t\t\t\tgsl_vector_set(lsf,i+1,mean + LSF_EPSILON/2.0);\n\t\t\t\tflag_dec++;\n\t\t\t\tok = 0;\n\t\t\t} else if(gsl_vector_get(lsf,i) > gsl_vector_get(lsf,i+1)-LSF_EPSILON/10.0) {\n\t\t\t\tmean = (gsl_vector_get(lsf,i)+gsl_vector_get(lsf,i+1))/2.0;\n\t\t\t\tgsl_vector_set(lsf,i,mean - LSF_EPSILON/2.0);\n\t\t\t\tgsl_vector_set(lsf,i+1,mean + LSF_EPSILON/2.0);\n\t\t\t\tflag_close++;\n\t\t\t\tok = 0;\n\t\t\t}\n\t\t}\n\t}\n\n\t/* Report */\n\tif(flag_dec > 0)\n\t\tprintf(\"Warning: %i decreasing LSFs -> Fixed!\\n\",flag_dec);\n\tif(flag_neg > 0)\n\t\tprintf(\"Warning: %i negative LSFs -> Fixed!\\n\",flag_neg);\n\tif(flag_piplus > 0)\n\t\tprintf(\"Warning: %i LSFs greater than Pi -> Fixed!\\n\",flag_piplus);\n\tif(flag_zero > 0)\n\t\tprintf(\"Warning: %i LSFs too close to 0 -> Fixed!\\n\",flag_zero);\n\tif(flag_piplus > 0)\n\t\tprintf(\"Warning: %i LSFs greater than Pi -> Fixed!\\n\",flag_pi);\n\tif(flag_close > 0)\n\t\tprintf(\"Warning: %i LSFs too close to each other -> Fixed!\\n\",flag_close);\n\tif(flag_nan > 0)\n\t\tprintf(\"Warning: %i NaN LSF value(s) -> Fixed!\\n\",flag_nan);\n}\n\n\n\n\n\n/**\n * Function LSF_fix_matrix\n *\n * Check the validity of LSF and fix found errors\n *\n * @param lsf matrix\n */\nvoid LSF_fix_matrix(gsl_matrix *lsf) {\n\n\tint n,i,ok = 0;\n\tdouble mean;\n\tint flag_neg = 0;\n\tint flag_zero = 0;\n\tint flag_pi = 0;\n\tint flag_piplus = 0;\n\tint flag_nan = 0;\n\tint flag_dec = 0;\n\tint flag_close = 0;\n\n\t/* Repeat until LSF is fixed */\n\twhile(ok == 0) {\n\n\t\t/* Set ok */\n\t\tok = 1;\n\n\t\t/* Check and correct values less than zero or greater than pi */\n\t\tfor(n=0;n<lsf->size1;n++) {\n\t\t\tfor(i=0;i<lsf->size2;i++) {\n\t\t\t\tif(gsl_matrix_get(lsf,n,i) < 0) {\n\t\t\t\t\tgsl_matrix_set(lsf,n,i,LSF_EPSILON);\n\t\t\t\t\tflag_neg++;\n\t\t\t\t\tok = 0;\n\t\t\t\t} else if(gsl_matrix_get(lsf,n,i) < LSF_EPSILON) {\n\t\t\t\t\tgsl_matrix_set(lsf,n,i,LSF_EPSILON);\n\t\t\t\t\tflag_zero++;\n\t\t\t\t\tok = 0;\n\t\t\t\t} else if(gsl_matrix_get(lsf,n,i) > M_PI) {\n\t\t\t\t\tgsl_matrix_set(lsf,n,i,M_PI-LSF_EPSILON);\n\t\t\t\t\tflag_piplus++;\n\t\t\t\t\tok = 0;\n\t\t\t\t} else if(gsl_matrix_get(lsf,n,i) > M_PI-LSF_EPSILON) {\n\t\t\t\t\tgsl_matrix_set(lsf,n,i,M_PI-LSF_EPSILON);\n\t\t\t\t\tflag_pi++;\n\t\t\t\t\tok = 0;\n\t\t\t\t}\n\t\t\t\tif(gsl_isnan(gsl_matrix_get(lsf,n,i))) {\n\t\t\t\t\tif(i == 0)\n\t\t\t\t\t\tgsl_matrix_set(lsf,n,i,LSF_EPSILON);\n\t\t\t\t\telse if(i == lsf->size2-1)\n\t\t\t\t\t\tgsl_matrix_set(lsf,n,i,M_PI-LSF_EPSILON);\n\t\t\t\t\telse\n\t\t\t\t\t\tgsl_matrix_set(lsf,n,i,(gsl_matrix_get(lsf,n,i-1)+gsl_matrix_get(lsf,n,i+1))/2.0);\n\t\t\t\t\tflag_nan++;\n\t\t\t\t\tok = 0;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/* Check and correct non-increasing values or coefficients too close */\n\t\t\tfor(i=0;i<lsf->size2-1;i++) {\n\t\t\t\tif(gsl_matrix_get(lsf,n,i) > gsl_matrix_get(lsf,n,i+1)) {\n\t\t\t\t\tmean = (gsl_matrix_get(lsf,n,i)+gsl_matrix_get(lsf,n,i+1))/2.0;\n\t\t\t\t\tgsl_matrix_set(lsf,n,i,mean - LSF_EPSILON/2.0);\n\t\t\t\t\tgsl_matrix_set(lsf,n,i+1,mean + LSF_EPSILON/2.0);\n\t\t\t\t\tflag_dec++;\n\t\t\t\t\tok = 0;\n\t\t\t\t} else if(gsl_matrix_get(lsf,n,i) > gsl_matrix_get(lsf,n,i+1)-LSF_EPSILON/10.0) {\n\t\t\t\t\tmean = (gsl_matrix_get(lsf,n,i)+gsl_matrix_get(lsf,n,i+1))/2.0;\n\t\t\t\t\tgsl_matrix_set(lsf,n,i,mean - LSF_EPSILON/2.0);\n\t\t\t\t\tgsl_matrix_set(lsf,n,i+1,mean + LSF_EPSILON/2.0);\n\t\t\t\t\tflag_close++;\n\t\t\t\t\tok = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/* Report */\n\tif(flag_dec > 0)\n\t\tprintf(\"Warning: %i decreasing LSFs -> Fixed!\\n\",flag_dec);\n\tif(flag_neg > 0)\n\t\tprintf(\"Warning: %i negative LSFs -> Fixed!\\n\",flag_neg);\n\tif(flag_piplus > 0)\n\t\tprintf(\"Warning: %i LSFs greater than Pi -> Fixed!\\n\",flag_piplus);\n\tif(flag_zero > 0)\n\t\tprintf(\"Warning: %i LSFs too close to 0 -> Fixed!\\n\",flag_zero);\n\tif(flag_pi > 0)\n\t\tprintf(\"Warning: %i LSFs too close to Pi -> Fixed!\\n\",flag_pi);\n\tif(flag_close > 0)\n\t\tprintf(\"Warning: %i LSFs too close to each other -> Fixed!\\n\",flag_close);\n\tif(flag_nan > 0)\n\t\tprintf(\"Warning: %i NaN LSF value(s) -> Fixed!\\n\",flag_nan);\n}\n\n\n\n\n\n/**\n * Function Merge_voiced_unvoiced_spectra\n *\n * Merge voiced and unvoiced spectra, i.e., replace unvoiced spectrum of LSF with LSF2 if two spectra is used\n *\n * @param LSF\n * @param LSF2\n * @param params\n */\nvoid Merge_voiced_unvoiced_spectra(gsl_matrix *LSF, gsl_matrix *LSF2, gsl_vector *fundf, PARAM *params) {\n\n\tint i,j;\n\tif(params->sep_vuv_spectrum == 1)\n\t\tfor(i=0; i<params->n_frames; i++)\n\t\t\tif(gsl_vector_get(fundf, i) == 0)\n\t\t\t\tfor(j=0; j<LSF->size2; j++)\n\t\t\t\t\tgsl_matrix_set(LSF, i, j, gsl_matrix_get(LSF2, i, j));\n}\n\n\n\n\n/**\n * Function Integrate_LSFs\n *\n * Integrate line spectral frequency (LSF) based parameters if differential LSFs are used.\n * First raise to the power of 2, integrate, scale according to the distance to PI.\n *\n * @param LSF\n * @param LSF2\n * @param params\n */\nvoid Integrate_LSFs(gsl_matrix **LSFd, PARAM *params) {\n\n\tif(params->differential_lsf == 0)\n\t\treturn;\n\n\t/* Initialize */\n\tint i,k;\n\tdouble len_orig,len_new,c;\n\tgsl_matrix *LSF = gsl_matrix_calloc((*LSFd)->size1,(*LSFd)->size2-1);\n\n\t/* Remove sqrt */\n\tfor(i=0;i<LSF->size1;i++) {\n\t\tfor(k=0;k<LSF->size2;k++)\n\t\t\tgsl_matrix_set(*LSFd,i,k,pow(gsl_matrix_get(*LSFd,i,k),2));\n\n\t\t/* Set initial LSF */\n\t\tgsl_matrix_set(LSF,i,0,gsl_matrix_get(*LSFd,i,0));\n\t}\n\n\t/* Integrate */\n\tfor(i=0;i<LSF->size1;i++)\n\t\tfor(k=1;k<LSF->size2;k++)\n\t\t\tgsl_matrix_set(LSF,i,k,gsl_matrix_get(*LSFd,i,k) + gsl_matrix_get(LSF,i,k-1));\n\n\t/* Scale LSFs according to the last coefficient so that the distance to PI matches */\n\tfor(i=0;i<LSF->size1;i++) {\n\t\tlen_orig = M_PI - pow(gsl_matrix_get(*LSFd,i,(*LSFd)->size2-1),2);\n\t\tlen_new = gsl_matrix_get(LSF,i,LSF->size2-1);\n\t\tc = len_orig/len_new;\n\t\tfor(k=0;k<LSF->size2;k++)\n\t\t\tgsl_matrix_set(LSF,i,k,gsl_matrix_get(LSF,i,k)*c);\n\t}\n\n\t/* Free old matrix */\n\tgsl_matrix_free(*(LSFd));\n\n\t/* Set pointer to new matrix */\n\t*(LSFd) = LSF;\n}\n\n\n\n/**\n * Function Noise_robust_speech1\n *\n * Modification for noise robust speech synthesis (1st stage)\n *\n * @param pulse_clus_id pointer to pulse cluster ids\n * @param pulse_clusters pointer to pulse clusters\n * @param params paramteres structure\n * @param synfilenumber\n * @return\n */\nvoid Noise_robust_speech1(PARAM *params) {\n\n\tif(params->noise_robust_speech == 0)\n\t\treturn;\n\n\t/* Modifications */\n\tparams->hpfiltf0 = 1;\n\tparams->postfilter_alpha = 0.15;        // 0<c<1, 1:OFF\n\tparams->compcoeff = 0.2;                // 0<c<1, 1:OFF\n\n\t/* Pitch and speed */\n\tparams->pitch = 1.4;\n\tparams->speed = 0.8;\n}\n\n\n\n/**\n * Function Noise_robust_speech2\n *\n * Modification for noise robust speech synthesis (2nd stage)\n *\n * @param pulse_clus_id pointer to pulse cluster ids\n * @param pulse_clusters pointer to pulse clusters\n * @param params paramteres structure\n * @param synfilenumber\n * @return\n */\nvoid Noise_robust_speech2(gsl_vector *gain, gsl_matrix *harmonics, PARAM *params) {\n\n\tif(params->noise_robust_speech == 0)\n\t\treturn;\n\n\t/* Modify harmonics */\n\tif(params->use_harmonics == 1)\n\t\tModify_harmonics(harmonics,0.5); \t\t\t// 0<c<1, 1:OFF\n\telse {\n\t\tparams->pulse_tilt_decrease_coeff = 0.5; \t// 0<c<1, 1:OFF\n\t\tparams->use_harmonic_modification = 1;\n\t}\n\n\t/* Compression of gain */\n\tif(params->use_pulselib == 1) {\n\t\tint i;\n\t\tdouble compression = 0.99; // The lower the number, the more compression will take effect\n\t\tdouble addition = 9;       // dB, rises the baseline gain\n\t\tdouble mingain = gsl_vector_min(gain);\n\t\tfor(i=0;i<gain->size;i++)\n\t\t\tgsl_vector_set(gain,i,pow(gsl_vector_get(gain,i) - mingain, compression) + addition + mingain);\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n/**\n * Function CreateExcitation\n *\n * Creates excitation...\n *\n * @param ...\n *\n */\nvoid CreateExcitation(PARAM *params,gsl_vector *excitation_voiced,gsl_vector *excitation_unvoiced,gsl_vector *fundf,gsl_vector *gain,\n\t      gsl_matrix *lsf,gsl_matrix *glflowsp,gsl_matrix *hnr,gsl_matrix *harmonics,gsl_matrix *waveform,gsl_vector *h1h2,\n\t      gsl_vector *naq,gsl_vector *original_pulse,gsl_matrix *pulses,gsl_matrix *pulses_rs,gsl_vector *pulse_lengths,\n\t      gsl_vector *pgain,gsl_matrix *plsf,gsl_matrix *ptilt,gsl_matrix *phnr,gsl_matrix *pharm,gsl_matrix *pwaveform,\n\t      gsl_vector *ph1h2, gsl_vector *pnaq,gsl_vector *resynthesis_pulse_index,gsl_vector *pulse_clus_id,\n\t      gsl_matrix *pulse_clusters,gsl_vector *oldgain,gsl_matrix *glflowsp_new,gsl_matrix *hnr_new,\n\t      gsl_vector *pca_mean, gsl_matrix *pca_pc, gsl_matrix *pca_w, gsl_matrix *pca_w_lib, gsl_vector *stoch_env, gsl_vector *stoch_sp,\n\t      gsl_matrix **DNN_W, gsl_vector **input_minmax, gsl_vector *dnnpulseindices, gsl_vector *dnnpulses) {\n\n\t/* Clear parameters (if resynth) */\n\tgsl_vector_set_zero(excitation_voiced);\n\tgsl_vector_set_zero(excitation_unvoiced);\n\tgsl_matrix_set_zero(glflowsp_new);\n\n\t/* Allocate memory */\n\tint sample_index = 0,frame_index_old = 0;\n\tint frame_index_center,frame_index,i,j,N,NN,pulseind = 0;\n\tdouble ngain_uv,gain_v,sum,sum_d,modg;\n\tint end_flag = 0;\n\tgsl_vector *noise;\n\tgsl_vector *pulse_train;\n\tgsl_vector *inds = gsl_vector_alloc(params->n_pulsecandidates);\n\tgsl_vector *inds_next = gsl_vector_alloc(params->n_pulsecandidates);\n\tgsl_vector *eparam = gsl_vector_alloc(params->n_pulsecandidates);\n\tgsl_vector *eparam_next = gsl_vector_alloc(params->n_pulsecandidates);\n\tgsl_vector *epulse = gsl_vector_alloc(params->n_pulsecandidates);\n\tgsl_vector *efinal = gsl_vector_alloc(params->n_pulsecandidates);\n\tgsl_vector *prevpulse = gsl_vector_alloc(params->rspulsemaxlen);\n\n\t/* Modulation */\n\tint mod_pulse_index = 0;\n\tdouble mod_pulse_gain = 0.0;\n\n\t/* DNN */\n\tint dnnpind = 0;\n\tint dnnpulseind = 0;\n\n\n\t/***********************************************************/\n\t/* Create excitation: loop until signal length is reached  */\n\t/***********************************************************/\n\n\twhile(sample_index < params->signal_length) {\n\n\t\t/* Define current time index */\n\t\tframe_index = floor(params->n_frames*(sample_index/(double)params->signal_length));\n\t\tif(frame_index > params->n_frames-1) {frame_index = params->n_frames-1;}\n\n\n\t\t/****************************************************/\n\t\t/* 1. Segment is voiced                             */\n\t\t/****************************************************/\n\n\t\tif(gsl_vector_get(fundf,frame_index) != 0) {\n\n\n\t\t\t/****************************************************/\n\t\t\t/* Interpolate one pulse (original implementation)  */\n\t\t\t/****************************************************/\n\n\t\t\tif(params->use_pulselib == 0 && params->use_pulselib_pca == 0 && params->use_dnn_pulsegen == 0) {\n\n\t\t\t\t/* Interpolate the original pulse according to T0 (N), use cubic spline interpolation */\n\t\t\t\tN = rint(params->FS/gsl_vector_get(fundf,frame_index)/params->pitch);\n\t\t\t\tgsl_vector *pulse;\n\t\t\t\tif(params->two_pitch_period_diff_pulse == 0)\n\t\t\t\t\tpulse = gsl_vector_calloc(N);\n\t\t\t\telse\n\t\t\t\t\tpulse = gsl_vector_calloc(2*N);\n\t\t\t\tInterpolate(original_pulse,pulse);\n\n\t\t\t\t/* Create synthetic pulse train */\n\t\t\t\tif(params->two_pitch_period_diff_pulse == 0)\n\t\t\t\t\tpulse_train = Create_pulse_train(pulse,original_pulse,hnr,fundf,harmonics,frame_index,sample_index,params);\n\t\t\t\telse {\n\t\t\t\t\tpulse_train = Create_pulse_train_diff(pulse,original_pulse,hnr,fundf,harmonics,frame_index,sample_index,params);\n\t\t\t\t\tIntegrate(pulse_train,LEAK);\n\t\t\t\t}\n\n\t\t\t\t/* Re-estimate HNR */\n\t\t\t\tif(params->hnr_reestimated == 0) {\n\t\t\t\t\tUpper_lower_envelope(pulse_train, hnr_new, gsl_vector_get(fundf,frame_index), frame_index, params);\n\t\t\t\t\tFillHNRValues(hnr_new,frame_index_old,frame_index);\n\t\t\t\t\tframe_index_old = frame_index;\n\t\t\t\t\tgsl_vector_free(pulse_train);\n\t\t\t\t} else { /* Add noise and analyse pulse train spectrum */\n\t\t\t\t\tif(params->two_pitch_period_diff_pulse == 1)\n\t\t\t\t\t\tIntegrate(pulse,LEAK);\n\t\t\t\t\tPhase_manipulation(pulse,hnr,harmonics,frame_index,params);\n\t\t\t\t\tif(params->two_pitch_period_diff_pulse == 1) {\n\t\t\t\t\t\tDifferentiate(pulse,LEAK);\n\t\t\t\t\t\tgsl_vector_set(pulse,0,0); // Fix DC error\n\t\t\t\t\t}\n\t\t\t\t\tAnalyse_pulse_train_spectrum(pulse_train,glflowsp_new,N,sample_index,frame_index,params);\n\t\t\t\t\tframe_index_old = frame_index;\n\t\t\t\t\tgsl_vector_free(pulse_train);\n\t\t\t\t}\n\n\t\t\t\t/* Add jitter */\n\t\t\t\tint N_orig = N;\n\t\t\t\tif(params->jitter > 0) {\n\t\t\t\t\tN = N + rint(RAND()*N*params->jitter);\n\t\t\t\t\tgsl_vector *pulse_jitter;\n\t\t\t\t\tif(params->two_pitch_period_diff_pulse == 0)\n\t\t\t\t\t\tpulse_jitter = gsl_vector_alloc(N);\n\t\t\t\t\telse\n\t\t\t\t\t\tpulse_jitter = gsl_vector_alloc(2*N);\n\t\t\t\t\tInterpolate(pulse,pulse_jitter);\n\t\t\t\t\tgsl_vector_free(pulse);\n\t\t\t\t\tpulse = pulse_jitter;\n\t\t\t\t}\n\n\t\t\t\t/* Truncate pulse for unvoiced sections */\n\t\t\t\tif(params->two_pitch_period_diff_pulse == 0) {\n\t\t\t\t\tpulse = Truncate_pulse(pulse,fundf,sample_index,frame_index,params);\n\t\t\t\t\tN_orig = pulse->size;\n\t\t\t\t\tN = pulse->size;\n\t\t\t\t}\n\n\t\t\t\t/* Prevent going over signal length */\n\t\t\t\tif(params->two_pitch_period_diff_pulse == 0) {\n\t\t\t\t\tif(sample_index+N > params->signal_length) {\n\t\t\t\t\t\tgsl_vector_free(pulse);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t/* Normalize gain according to one pitch period */\n\t\t\t\tif(params->two_pitch_period_diff_pulse == 0) {\n\t\t\t\t\tgsl_vector *pulse_d = gsl_vector_alloc(pulse->size);\n\t\t\t\t\tgsl_vector_memcpy(pulse_d,pulse);\n\t\t\t\t\tLipRadiation(pulse_d);\n\t\t\t\t\tsum_d = 0;\n\t\t\t\t\tfor(i=0;i<N;i++)\n\t\t\t\t\t\tsum_d = sum_d + gsl_vector_get(pulse_d,i)*gsl_vector_get(pulse_d,i);\n\t\t\t\t\tgsl_vector_free(pulse_d);\n\t\t\t\t} else {\n\t\t\t\t\tsum = 0;\n\t\t\t\t\tfor(j=0;j<pulse->size;j++)\n\t\t\t\t\t\tsum = sum + gsl_vector_get(pulse,j)*gsl_vector_get(pulse,j);\n\t\t\t\t}\n\n\t\t\t\t/* Evaluate gain */\n\t\t\t\tif(params->two_pitch_period_diff_pulse == 0) {\n\t\t\t\t\tframe_index_center = GSL_MIN(floor(params->n_frames*((sample_index + 0.5*N_orig)/(double)params->signal_length)),params->n_frames-1);\n\t\t\t\t\tgain_v = sqrt(N*E_REF*powf(10.0,gsl_vector_get(gain,frame_index_center)/10.0)/sum_d);\n\t\t\t\t} else\n\t\t\t\t\tgain_v = sqrt(pulse->size*E_REF*powf(10.0,gsl_vector_get(gain,frame_index)/10.0)/(sum/0.375));\n\n\t\t\t\t/* Modulation */\n\t\t\t\tmodg = 1 + sin(M_PI*mod_pulse_index/2.0)*mod_pulse_gain;\n\t\t\t\tgain_v = modg*gain_v;\n\t\t\t\tmod_pulse_index++;\n\n\t\t\t\t/* Set pulse to excitation */\n\t\t\t\tif(params->two_pitch_period_diff_pulse == 0) {\n\t\t\t\t\tfor(i=0;i<N;i++)\n\t\t\t\t\t\tgsl_vector_set(excitation_voiced, sample_index+i, gain_v*(gsl_vector_get(pulse,i) - gsl_vector_get(pulse,0)));\n\t\t\t\t} else {\n\t\t\t\t\tfor(j=0;j<pulse->size;j++) {\n\t\t\t\t\t\tgsl_vector_set(excitation_voiced,GSL_MIN(GSL_MAX(sample_index+j-rint(pulse->size/2),0),excitation_voiced->size-1),\n\t\t\t\t\t\t   gsl_vector_get(excitation_voiced,GSL_MIN(GSL_MAX(sample_index+j-rint(pulse->size/2),0),excitation_voiced->size-1)) +\n\t\t\t\t\t\t   gain_v*gsl_vector_get(pulse,j));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t/* Free memory */\n\t\t\t\tgsl_vector_free(pulse);\n\n\t\t\t\t/* Increment sample index */\n\t\t\t\tsample_index += N_orig;\n\n\n\t\t\t} else if(params->use_pulselib_pca == 0 && params->use_dnn_pulsegen == 0) {\n\n\n\t\t\t\t/*******************************************/\n\t\t\t\t/* Use voice source unit selection         */\n\t\t\t\t/*******************************************/\n\n\t\t\t\t/* Get the length of voiced section in frames and pulses */\n\t\t\t\tint cur_frame_index = frame_index;\n\t\t\t\tint cur_sample_index = sample_index;\n\t\t\t\tint n_pulses_in_section = 0;\n\t\t\t\tdouble mf0 = 0;\n\t\t\t\twhile(1) {\n\t\t\t\t\tif(cur_frame_index > params->n_frames-1) {\n\t\t\t\t\t\tend_flag = 1;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tn_pulses_in_section++;\n\t\t\t\t\tmf0 += gsl_vector_get(fundf,cur_frame_index);\n\t\t\t\t\tN = rint(params->FS/gsl_vector_get(fundf,cur_frame_index)/params->pitch);\n\t\t\t\t\tcur_frame_index = floor(params->n_frames*((cur_sample_index+N)/(double)params->signal_length));\n\t\t\t\t\tcur_sample_index += N;\n\t\t\t\t\tif(cur_frame_index > params->n_frames-1) {\n\t\t\t\t\t\tend_flag = 1;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tif(gsl_vector_get(fundf,cur_frame_index) == 0 || gsl_vector_get(fundf,GSL_MIN(floor(params->n_frames*((cur_sample_index + rint(0.5*params->FS/gsl_vector_get(fundf,cur_frame_index)/params->pitch))/(double)params->signal_length)),params->n_frames-1)) == 0)\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\t/* Evaluate mean f0 for the voiced section */\n\t\t\t\tmf0 = mf0/(double)n_pulses_in_section;\n\n\t\t\t\t/* Variables for Viterbi */\n\t\t\t\tgsl_matrix *v_trellis;\n\t\t\t\tgsl_matrix *v_indices;\n\t\t\t\tgsl_vector *final_pulses = gsl_vector_alloc(n_pulses_in_section);\n\n\t\t\t\t/* If pulse indices not known */\n\t\t\t\tif(params->resynth == 0) {\n\n\t\t\t\t\t/* Print number of pulses in voiced section */\n\t\t\t\t\t//printf(\"              Voiced section: %i pulse(s)\\n\",n_pulses_in_section);\n\n\t\t\t\t\t/* Allocate lattices for viterbi */\n\t\t\t\t\tv_trellis = gsl_matrix_alloc(n_pulses_in_section, params->n_pulsecandidates+1); // Onko oikein +1?\n\t\t\t\t\tv_indices = gsl_matrix_alloc(n_pulses_in_section, params->n_pulsecandidates+1);\n\t\t\t\t\tgsl_matrix_set_all(v_trellis, BIGGER_POS_NUMBER);\n\t\t\t\t\tgsl_matrix_set_all(v_indices, 1);\n\n\t\t\t\t\t/* Populate targets according to lowest target error */\n\t\t\t\t\tcur_frame_index = frame_index;\n\t\t\t\t\tcur_sample_index = sample_index;\n\t\t\t\t\tfor(i=0;i<n_pulses_in_section;i++) {\n\t\t\t\t\t\tgsl_vector_view inds = gsl_matrix_row(v_indices,i);\n\t\t\t\t\t\tgsl_vector_view eparam = gsl_matrix_row(v_trellis,i);\n\t\t\t\t\t\tEvaluate_target_error(lsf,glflowsp,harmonics,hnr,waveform,h1h2,naq,oldgain,fundf,plsf,ptilt,pharm,phnr,pwaveform,ph1h2,pnaq,\n\t\t\t\t\t\t\t\tpgain,pca_w,pca_w_lib,pulse_lengths,cur_frame_index,&inds.vector,&eparam.vector,pulse_clus_id,pulse_clusters,params);\n\t\t\t\t\t\tN = rint(params->FS/gsl_vector_get(fundf,cur_frame_index)/params->pitch);\n\t\t\t\t\t\tcur_frame_index = floor(params->n_frames*((cur_sample_index+N)/(double)params->signal_length));\n\t\t\t\t\t\tcur_sample_index += N;\n\t\t\t\t\t}\n\t\t\t\t\tif(n_pulses_in_section > 1) {\n\n\t\t\t\t\t\t/* Viterbi, forward */\n\t\t\t\t\t\t/* Cumulative score */\n\t\t\t\t\t\tgsl_matrix *v_scores = gsl_matrix_alloc(n_pulses_in_section, params->n_pulsecandidates+1);\n\t\t\t\t\t\tgsl_matrix_set_all(v_scores, BIGGER_POS_NUMBER);\n\n\t\t\t\t\t\t/* Best node indices leading to each node */\n\t\t\t\t\t\tgsl_matrix *v_best = gsl_matrix_alloc(n_pulses_in_section, params->n_pulsecandidates+1);\n\t\t\t\t\t\tgsl_matrix_set_all(v_best, -1);\n\n\t\t\t\t\t\t/* Evaluate concatenation error */\n\t\t\t\t\t\tcur_frame_index = frame_index;\n\t\t\t\t\t\tcur_sample_index = sample_index;\n\t\t\t\t\t\tint dist_to_unvoiced;\n\t\t\t\t\t\tdouble additional_cost;\n\t\t\t\t\t\tfor(i=0;i<n_pulses_in_section-1;i++) {\n\t\t\t\t\t\t\tgsl_vector_view inds = gsl_matrix_row(v_indices,i);\n\t\t\t\t\t\t\tgsl_vector_view inds_next = gsl_matrix_row(v_indices,i+1);\n\t\t\t\t\t\t\tgsl_vector_view eparam = gsl_matrix_row(v_trellis,i);\n\t\t\t\t\t\t\tgsl_vector_view eparam_next = gsl_matrix_row(v_trellis,i+1);\n\n\t\t\t\t\t\t\t/* Define distance to unvoiced */\n\t\t\t\t\t\t\tdist_to_unvoiced = i+1;\n\n\t\t\t\t\t\t\t/* Define additional cost (consisting of HNR and F0) */\n\t\t\t\t\t\t\tif(params->use_hnr == 1) {\n\t\t\t\t\t\t\t\tadditional_cost = 0;\n\t\t\t\t\t\t\t\tfor(j=0;j<hnr->size2;j++)\n\t\t\t\t\t\t\t\t\tadditional_cost += 1.0-pow(10,gsl_matrix_get(hnr,cur_frame_index,j)/20.0);\n\t\t\t\t\t\t\t\tadditional_cost = powf(additional_cost/hnr->size2,3.0);\n\t\t\t\t\t\t\t} else\n\t\t\t\t\t\t\t\tadditional_cost = 1;\n\t\t\t\t\t\t\tadditional_cost *= gsl_vector_get(fundf, frame_index)/120.0; // Add cost if high f0 (many concatenation points)\n\n\t\t\t\t\t\t\t/* Evaluate concatenation cost */\n\t\t\t\t\t\t\tEvaluate_concatenation_error_viterbi(&eparam.vector,&eparam_next.vector,&inds.vector,&inds_next.vector,\n\t\t\t\t\t\t\t\t\tpulses_rs, v_scores, v_best, i, dist_to_unvoiced, additional_cost, params);\n\t\t\t\t\t\t\tN = rint(params->FS/gsl_vector_get(fundf,cur_frame_index)/params->pitch);\n\t\t\t\t\t\t\tcur_frame_index = floor(params->n_frames*((cur_sample_index+N)/(double)params->signal_length));\n\t\t\t\t\t\t\tcur_sample_index += N;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t/* Viterbi, get best path by backtracking */\n\t\t\t\t\t\tdouble best_sc = BIGGER_POS_NUMBER;\n\t\t\t\t\t\tint best_i = -1;\n\t\t\t\t\t\tfor(i=0;i<params->n_pulsecandidates;i++) {\n\t\t\t\t\t\t\tif(gsl_matrix_get(v_scores,n_pulses_in_section-1, i) < best_sc) {\n\t\t\t\t\t\t\t\tbest_sc = gsl_matrix_get(v_scores, n_pulses_in_section-1,i);\n\t\t\t\t\t\t\t\tbest_i = i;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tgsl_vector_set(final_pulses, n_pulses_in_section-1, gsl_matrix_get(v_indices, n_pulses_in_section-1, best_i));\n\t\t\t\t\t\tfor(i=n_pulses_in_section-2;i>= 0;i--) {\n\t\t\t\t\t\t\tgsl_vector_set(final_pulses, i, gsl_matrix_get(v_indices, i+1, best_i));\n\t\t\t\t\t\t\tbest_i = (int)gsl_matrix_get(v_best, i+1,best_i);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t/* Free viterbi structures */\n\t\t\t\t\t\tgsl_matrix_free(v_best);\n\t\t\t\t\t\tgsl_matrix_free(v_scores);\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\t/* Only one pulse in section */\n\t\t\t\t\t\tgsl_vector_set(final_pulses,0,gsl_matrix_get(v_indices,0,i)); // TODO: Should be best_i(i) ?\n\t\t\t\t\t}\n\n\t\t\t\t\t/* Free viterbi structures */\n\t\t\t\t\tgsl_matrix_free(v_trellis);\n\t\t\t\t\tgsl_matrix_free(v_indices);\n\n\n\t\t\t\t} /* After this, same for resynthesis */\n\n\t\t\t\t/* Make pulse train */\n\t\t\t\tdouble prev_f0 = 0.0;\n\t\t\t\tfor(i=0;i<=n_pulses_in_section-1;i++) {\n\n\t\t\t\t\t/* Define pulse index */\n\t\t\t\t\tif(params->resynth == 0) {\n\t\t\t\t\t\tpulseind = (int)gsl_vector_get(final_pulses, i);\n\t\t\t\t\t\tgsl_vector_set(resynthesis_pulse_index,frame_index,gsl_vector_get(final_pulses,i));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tpulseind = gsl_vector_get(resynthesis_pulse_index, frame_index);\n\t\t\t\t\t}\n\n\t\t\t\t\t/* Print pulse index */\n\t\t\t\t\t//if(params->resynth == 0)\n\t\t\t\t\t//\tprintf(\"%i\\n\",pulseind);\n\n\t\t\t\t\t/* Get pulse length and f0 shift */\n\t\t\t\t\tdouble f0 = gsl_vector_get(fundf,frame_index);\n\t\t\t\t\tif(f0 == 0) f0 = prev_f0;\n\t\t\t\t\tif(f0 == 0) f0 = mf0;\n\t\t\t\t\tN = rint(params->FS/f0/params->pitch);\n\t\t\t\t\tNN = gsl_vector_get(pulse_lengths,pulseind);\n\n\t\t\t\t\t/* Get pulse to vector */\n\t\t\t\t\tgsl_vector *pulse;\n\t\t\t\t\tif(params->pulse_interpolation == 0) {\n\t\t\t\t\t\tif(sample_index+rint(NN/2) > params->signal_length)\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tpulse = gsl_vector_alloc(NN);\n\t\t\t\t\t\tfor(j=0;j<NN;j++)\n\t\t\t\t\t\t\tgsl_vector_set(pulse,j,gsl_matrix_get(pulses,pulseind,j));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif(sample_index+N > params->signal_length)\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tgsl_vector *pulse_orig = gsl_vector_calloc(NN);\n\t\t\t\t\t\tpulse = gsl_vector_calloc(2*N);\n\t\t\t\t\t\tfor(j=0;j<NN;j++)\n\t\t\t\t\t\t\tgsl_vector_set(pulse_orig,j,gsl_matrix_get(pulses,pulseind,j));\n\t\t\t\t\t\tInterpolate(pulse_orig,pulse);\n\t\t\t\t\t\tgsl_vector_free(pulse_orig);\n\t\t\t\t\t\tNN = 2*N;\n\t\t\t\t\t}\n\n\t\t\t\t\t/* Average pulses */\n\t\t\t\t\tAverage_pulses(pulse, fundf, resynthesis_pulse_index, pulses, pulse_lengths, frame_index, params);\n\n\t\t\t\t\t/* Add jitter */\n\t\t\t\t\tif(params->jitter > 0) {\n\t\t\t\t\t\tNN = pulse->size + rint(RAND()*2*N*params->jitter);\n\t\t\t\t\t\tgsl_vector *pulse_jitter = gsl_vector_alloc(NN);\n\t\t\t\t\t\tInterpolate(pulse,pulse_jitter);\n\t\t\t\t\t\tgsl_vector_free(pulse);\n\t\t\t\t\t\tpulse = pulse_jitter;\n\t\t\t\t\t}\n\n\t\t\t\t\t/* Phase manipulation of the library pulse */\n\t\t\t\t\tif(params->add_noise_pulselib == 1 && params->resynth == 1) {\n\t\t\t\t\t\tIntegrate(pulse, LEAK);\n\t\t\t\t\t\tPhase_manipulation(pulse,hnr,harmonics,frame_index,params);\n\t\t\t\t\t\tDifferentiate(pulse,LEAK);\n\t\t\t\t\t\tgsl_vector_set(pulse,0,0); // Fix DC error\n\t\t\t\t\t}\n\n\t\t\t\t\t/* Evaluate gain */\n\t\t\t\t\tsum = 0;\n\t\t\t\t\tfor(j=0;j<NN;j++)\n\t\t\t\t\t\tsum = sum + gsl_vector_get(pulse,j)*gsl_vector_get(pulse,j);\n\t\t\t\t\tgain_v = sqrt(NN*E_REF*powf(10.0,gsl_vector_get(gain,frame_index)/10.0)/(sum/0.375));\n\n\t\t\t\t\t/* Modulation */\n\t\t\t\t\tmodg = 1 + sin(M_PI*mod_pulse_index/2.0)*mod_pulse_gain;\n\t\t\t\t\tgain_v = modg*gain_v;\n\t\t\t\t\tmod_pulse_index++;\n\n\t\t\t\t\t/* Set pulse to excitation (OLA) */\n\t\t\t\t\tfor(j=0;j<NN;j++) {\n\t\t\t\t\t\tgsl_vector_set(excitation_voiced,GSL_MIN(GSL_MAX(sample_index+j-rint(NN/2),0),excitation_voiced->size-1),\n\t\t\t\t\t\t   gsl_vector_get(excitation_voiced,GSL_MIN(GSL_MAX(sample_index+j-rint(NN/2),0),excitation_voiced->size-1)) +\n\t\t\t\t\t\t   gain_v*gsl_vector_get(pulse,j));\n\t\t\t\t\t}\n\t\t\t\t\tgsl_vector_free(pulse);\n\n\t\t\t\t\t/* Go directly to the beginning of unvoiced segent if pulse exceeds the boundary */\n\t\t\t\t\tint frame_index_tmp = frame_index;\n\t\t\t\t\tint next_unvoiced_sample = sample_index;\n\t\t\t\t\twhile(gsl_vector_get(fundf,frame_index_tmp) > 0) {\n\t\t\t\t\t\tframe_index_tmp = floor(params->n_frames*((next_unvoiced_sample)/(double)params->signal_length));\n\t\t\t\t\t\tnext_unvoiced_sample++;\n\t\t\t\t\t}\n\t\t\t\t\tN = GSL_MIN(N, next_unvoiced_sample-sample_index);\n\n\t\t\t\t\t/* Previous F0, increment sample index */\n\t\t\t\t\tprev_f0 = gsl_vector_get(fundf, frame_index);\n\t\t\t\t\tsample_index += N;\n\t\t\t\t\tframe_index = floor(params->n_frames*((sample_index)/(double)params->signal_length));\n\t\t\t\t}\n\n\t\t\t\t/* Free memory */\n\t\t\t\tgsl_vector_free(final_pulses);\n\n\t\t\t\t/* Stop in the end */\n\t\t\t\tif(end_flag == 1)\n\t\t\t\t\tbreak;\n\t    \t\t}\n\n\n\t\t\t/****************************************/\n\t\t\t/* Construct pulses from PCA parameters */\n\t\t\t/****************************************/\n\n\t\t\telse if(params->use_pulselib_pca == 1 && params->use_dnn_pulsegen == 0) {\n\n\t    \t\t\t/* Allocate PCA pulse */\n\t    \t\t\tgsl_vector *pca_pulse = gsl_vector_calloc(params->pca_pulse_length);\n\n\t    \t\t\t/* Define pulse from PC and weights */\n\t    \t\t\tif(params->pca_order_synthesis < 0 || params->pca_order_synthesis > params->pca_order) {\n\t    \t\t\t\tprintf(\"PCA_ORDER_SYNTHESIS must be between 0 and PCA_ORDER. PCA_ORDER_SYNTHESIS set to PCA_ORDER.\\n\");\n\t    \t\t\t\tparams->pca_order_synthesis = params->pca_order;\n\t    \t\t\t}\n\t    \t\t\tfor(i=0;i<params->pca_order_synthesis;i++)\n\t    \t\t\t\tfor(j=0;j<params->pca_pulse_length;j++)\n\t    \t\t\t\t\tgsl_vector_set(pca_pulse,j,gsl_vector_get(pca_pulse,j) + gsl_matrix_get(pca_w,frame_index,i)*gsl_matrix_get(pca_pc,j,i));\n\n\t    \t\t\t/* Add mean */\n\t    \t\t\tfor(i=0;i<params->pca_pulse_length;i++)\n\t    \t\t\t\tgsl_vector_set(pca_pulse,i,gsl_vector_get(pca_pulse,i) + gsl_vector_get(pca_mean,i));\n\n\t    \t\t\t/* Define pulse length, add jitter */\n\t    \t\t\tN = rint(params->FS/gsl_vector_get(fundf,frame_index)/params->pitch);\n\t\t\t\tNN = 2*N;\n\t\t\t\tif(params->jitter > 0)\n\t\t\t\t\tNN = rint(NN*(1.0 + RAND()*params->jitter));\n\t\t\t\tif(sample_index+NN/2.0 > params->signal_length) {\n\t\t\t\t\tgsl_vector_free(pca_pulse);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\t/* Allocate and interpolate pulse */\n\t\t\t\tgsl_vector *pulse = gsl_vector_alloc(NN);\n\t\t\t\tInterpolate(pca_pulse,pulse);\n\n\t\t\t\t/* Add noise */\n\t\t\t\tIntegrate(pulse,LEAK);\n\t\t\t\tPhase_manipulation(pulse,hnr,harmonics,frame_index,params);\n\t\t\t\tDifferentiate(pulse,LEAK);\n\t\t\t\tgsl_vector_set(pulse,0,0); // Fix DC error\n\n\t\t\t\t/* Create synthetic pulse train, analyse pulse train spectrum */\n\t\t\t\tpulse_train = Create_pulse_train_diff(pulse,pca_pulse,hnr,fundf,harmonics,frame_index,sample_index,params);\n\t\t\t\tIntegrate(pulse_train,LEAK);\n\t\t\t\tAnalyse_pulse_train_spectrum(pulse_train,glflowsp_new,N,sample_index,frame_index,params);\n\t\t\t\tframe_index_old = frame_index;\n\t\t\t\tgsl_vector_free(pulse_train);\n\n\t\t\t\t/* Evaluate gain */\n\t\t\t\tsum = 0;\n\t\t\t\tfor(j=0;j<NN;j++)\n\t\t\t\t\tsum = sum + gsl_vector_get(pulse,j)*gsl_vector_get(pulse,j);\n\t\t\t\tgain_v = sqrt(NN*E_REF*powf(10.0,gsl_vector_get(gain,frame_index)/10.0)/(sum/0.375));\n\n\t\t\t\t/* Modulation (NOT USED) */\n\t\t\t\tmodg = 1;\n\t\t\t\tgain_v = modg*gain_v;\n\t\t\t\tmod_pulse_index++;\n\n\t\t\t\t/* Set pulse to excitation (OLA) */\n\t\t\t\tfor(j=0;j<NN;j++) {\n\t\t\t\t\tgsl_vector_set(excitation_voiced,GSL_MIN(GSL_MAX(sample_index+j-rint(NN/2),0),excitation_voiced->size-1),\n\t\t\t\t\t   gsl_vector_get(excitation_voiced,GSL_MIN(GSL_MAX(sample_index+j-rint(NN/2),0),excitation_voiced->size-1)) +\n\t\t\t\t\t   gain_v*gsl_vector_get(pulse,j));\n\t\t\t\t}\n\n\t\t\t\t/* Free memory */\n\t\t\t\tgsl_vector_free(pulse);\n\t\t\t\tgsl_vector_free(pca_pulse);\n\n\t\t\t\t/* Increment sample index */\n\t\t\t\tsample_index += N;\n\t\t\t}\n\t\t\t\n\n\t\t\t/****************************************/\n\t\t\t/* DNN pulse generation                 */\n\t\t\t/****************************************/\n\n\t\t\t// LOWER FOR DNN-PCA (switch commenting)\n\t\t\telse if(params->use_pulselib_pca == 0 && params->use_dnn_pulsegen == 1) {\n\t\t\t//else if(params->use_pulselib_pca == 1 && params->use_dnn_pulsegen == 1) {\n\n\t\t\t\t/* Generate pulse from DNNs */\n\t\t\t\tN = rint(params->FS/gsl_vector_get(fundf,frame_index)/params->pitch);\n\t\t\t\tgsl_vector *pulse = gsl_vector_calloc(2*N);\n\n\t\t\t\t/* If first synthesis, generate DNN pulse and search for closest library pulse (index) */\n\t\t\t\tif(params->resynth == 0) {\n\n\t\t\t\t\t/* Generate DNN pulse */\n\t\t\t\t\t/* FOR DNN-PCA, switch comments below and in Generate_excitation, set one switch as well */\n\t\t\t\t\tGenerate_DNN_pulse(pulse,fundf,gain,naq,h1h2,hnr,glflowsp,lsf,DNN_W,input_minmax,frame_index,params);\n\t\t\t\t\t//Generate_DNN_pulse_PCA(pulse,fundf,gain,naq,h1h2,hnr,glflowsp,lsf,DNN_W,pca_pc,frame_index,params);\n\n\t\t\t\t\t/* Select between using DNN pulse itself, or selecting a natural pulse from library */\n\t\t\t\t\tif(params->use_dnn_pulselib_sel == 0) {\n\n\t\t\t\t\t\t/* Use DNN pulse and save it to memory */\n\t\t\t\t\t\tfor(i=0;i<pulse->size;i++)\n\t\t\t\t\t\t\tgsl_vector_set(dnnpulses,dnnpulseind+i,gsl_vector_get(pulse,i));\n\t\t\t\t\t\tdnnpulseind += pulse->size;\n\t\t\t\t\t\tdnnpind++;\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\t/* Select pulse from library, resample DNN pulse and normalize energy */\n\t\t\t\t\t\tgsl_vector *dnn_pulse_rs = gsl_vector_alloc(pulses_rs->size2);\n\t\t\t\t\t\tInterpolate(pulse,dnn_pulse_rs);\n\t\t\t\t\t\tdouble e = 0;\n\t\t\t\t\t\tfor(i=0;i<dnn_pulse_rs->size;i++)\n\t\t\t\t\t\t\te += gsl_vector_get(dnn_pulse_rs,i)*gsl_vector_get(dnn_pulse_rs,i);\n\t\t\t\t\t\te = sqrt(e);\n\t\t\t\t\t\tfor(i=0;i<dnn_pulse_rs->size;i++)\n\t\t\t\t\t\t\tgsl_vector_set(dnn_pulse_rs,i,gsl_vector_get(dnn_pulse_rs,i)/e);\n\t\t\t\n\t\t\t\t\t\t/* Search for a best matching pulse from pulse library */\n\t\t\t\t\t\tgsl_vector *error = gsl_vector_calloc(pulses_rs->size1);\n\t\t\t\t\t\tfor(i=0;i<error->size;i++)\n\t\t\t\t\t\t\tfor(j=0;j<dnn_pulse_rs->size;j++)\n\t\t\t\t\t\t\t\tgsl_vector_set(error,i,gsl_vector_get(error,i) + powf(gsl_matrix_get(pulses_rs,i,j)\n\t\t\t\t\t\t\t\t\t - gsl_vector_get(dnn_pulse_rs,j),2));\n\n \t\t\t\t\t\t/* Save pulse index */\n\t\t\t\t\t\tgsl_vector_set(dnnpulseindices,dnnpind,gsl_vector_min_index(error));\n\n\t\t\t\t\t\t/* Free memory */\n\t\t\t\t\t\tgsl_vector_free(error);\n\t\t\t\t\t\tgsl_vector_free(dnn_pulse_rs);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\n\t\t\t\t\t/* Load DNN pulse from memory in resynthesis */\n\t\t\t\t\tif(params->use_dnn_pulselib_sel == 0) {\n\n\t\t\t\t\t\t/* Load DNN pulse from memory */\n\t\t\t\t\t\tfor(i=0;i<pulse->size;i++)\n\t\t\t\t\t\t\tgsl_vector_set(pulse,i,gsl_vector_get(dnnpulses,dnnpulseind+i));\n\t\t\t\t\t\tdnnpulseind += pulse->size;\n\t\t\t\t\t\tdnnpind++;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t/* If pulse selection is used, get pulse from library according to index */\n\t\t\t\tif(params->use_dnn_pulselib_sel == 1) {\t\n\t\t\t\t\tgsl_vector *libpulse_orig = gsl_vector_alloc(gsl_vector_get(pulse_lengths,gsl_vector_get(dnnpulseindices,dnnpind)));\n\t\t\t\t\tfor(i=0;i<libpulse_orig->size;i++)\n\t\t\t\t\t\tgsl_vector_set(libpulse_orig,i,gsl_matrix_get(pulses,gsl_vector_get(dnnpulseindices,dnnpind),i));\n\t\t\t\t\tInterpolate(libpulse_orig,pulse);\n\t\t\t\t\t//if(params->resynth == 0)\n\t\t\t\t\t//\tprintf(\"%i\\n\",(int)gsl_vector_get(dnnpulseindices,dnnpind));\n\t\t\t\t\tgsl_vector_free(libpulse_orig);\n\t\t\t\t\tdnnpind++;\n\t\t\t\t}\n\n\t\t\t\t/* Evaluate voice source spectrum */\n\t\t\t\tgsl_vector *tmp_pulse = gsl_vector_alloc(pulse->size);\n\t\t\t\tgsl_vector_memcpy(tmp_pulse,pulse);\n\t\t\t\tpulse_train = Create_pulse_train_diff(pulse,tmp_pulse,hnr,fundf,harmonics,frame_index,sample_index,params);\n\t\t\t\tIntegrate(pulse_train,LEAK);\n\t\t\t\tgsl_vector_free(tmp_pulse);\n\n\t\t\t\t/* Re-estimate HNR */\n\t\t\t\tif(params->hnr_reestimated == 0) {\n\t\t\t\t\tUpper_lower_envelope(pulse_train, hnr_new, gsl_vector_get(fundf,frame_index), frame_index, params);\n\t\t\t\t\tFillHNRValues(hnr_new,frame_index_old,frame_index);\n\t\t\t\t\tframe_index_old = frame_index;\n\t\t\t\t\tgsl_vector_free(pulse_train);\n\t\t\t\t} else { /* Add noise and analyse pulse train spectrum */\n\t\t\t\t\tIntegrate(pulse,LEAK);\n\t\t\t\t\tPhase_manipulation(pulse,hnr,harmonics,frame_index,params);\n\t\t\t\t\tDifferentiate(pulse,LEAK);\n\t\t\t\t\tgsl_vector_set(pulse,0,0); // Fix DC error\n\t\t\t\t\tAnalyse_pulse_train_spectrum(pulse_train,glflowsp_new,N,sample_index,frame_index,params);\n\t\t\t\t\tframe_index_old = frame_index;\n\t\t\t\t\tgsl_vector_free(pulse_train);\n\t\t\t\t}\n\n\t\t\t\t/* Evaluate gain */\n\t\t\t\tsum = 0;\n\t\t\t\tfor(j=0;j<pulse->size;j++)\n\t\t\t\t\tsum = sum + gsl_vector_get(pulse,j)*gsl_vector_get(pulse,j);\n\t\t\t\tgain_v = sqrt(pulse->size*E_REF*powf(10.0,gsl_vector_get(gain,frame_index)/10.0)/(sum/0.375));\n\n\t\t\t\t/* Set pulse to excitation (OLA) */\n\t\t\t\tfor(j=0;j<pulse->size;j++) {\n\t\t\t\t\tgsl_vector_set(excitation_voiced,GSL_MIN(GSL_MAX(sample_index+j-rint(pulse->size/2),0),excitation_voiced->size-1),\n\t\t\t\t\t   gsl_vector_get(excitation_voiced,GSL_MIN(GSL_MAX(sample_index+j-rint(pulse->size/2),0),excitation_voiced->size-1)) +\n\t\t\t\t\t   gain_v*gsl_vector_get(pulse,j));\n\t\t\t\t}\n\n\t\t\t\t/* Free memory */\n\t\t\t\tgsl_vector_free(pulse);\n\n\t\t\t\t/* Increment sample index */\n\t\t\t\tsample_index += N;\n\n\t\t\t} // End single pulse / source unit selection / PCA pulse / DNN pulsegen\n\n\t\t} else {\n\n\t\t\t/****************************************************/\n\t\t\t/* 2. Segment is unvoiced                           */\n\t\t\t/****************************************************/\n\n\n\t    \t/* Allocate noise vector */\n\t\t\tif(sample_index + params->shift/params->speed < params->signal_length)\n\t\t\t\tnoise = gsl_vector_alloc(params->shift/params->speed);\n\t\t\telse\n\t\t\t\tnoise = gsl_vector_alloc(params->signal_length-sample_index);\n\n\t\t\t/* Create noise excitation */\n\t\t\tdouble sum = 0;\n\t\t\tfor(i=0;i<noise->size;i++) {\n\t\t\t\tgsl_vector_set(noise,i,RAND());\n\t\t\t\tsum += gsl_vector_get(noise,i)*gsl_vector_get(noise,i);\n\t\t\t}\n\n\t\t\t/* Add noise to voiced excitation */\n\t\t\tframe_index_center = GSL_MIN(floor(params->n_frames*((sample_index + 0.5*params->shift/params->speed)/(double)params->signal_length)),params->n_frames-1);\n\t\t\tngain_uv = params->gain_unvoiced*sqrt(params->shift/params->speed*E_REF*powf(10.0,gsl_vector_get(gain,frame_index_center)/10.0)/sum);\n\t\t\tfor(i=0;i<noise->size;i++)\n\t\t\t\tgsl_vector_set(excitation_unvoiced, sample_index+i, ngain_uv*gsl_vector_get(noise,i));\n\t\t\tgsl_vector_free(noise);\n\n\t\t\t/* Set synthetic source spectrum the same as original when unvoiced (FLAT FOR TESTING) */\n\t\t\tFillUnvoicedSyntheticSourceSpectrum(glflowsp,glflowsp_new,frame_index,frame_index_old);\n\t\t\t//FillUnvoicedSyntheticSourceSpectrum_FLAT(glflowsp,glflowsp_new,frame_index,frame_index_old);\n\n\t\t\t/* Update, increment sample index */\n\t\t\tframe_index_old = frame_index;\n\t\t\tsample_index += rint(params->shift/params->speed);\n\t\t}\n\t}\n\n\t/* Free memory */\n\tgsl_vector_free(prevpulse);\n\tgsl_vector_free(inds);\n\tgsl_vector_free(inds_next);\n\tgsl_vector_free(eparam);\n\tgsl_vector_free(eparam_next);\n\tgsl_vector_free(efinal);\n\tgsl_vector_free(epulse);\n}\n\n\n\n\n\n\n\n/**\n * Generate_DNN_pulse\n *\n * Generate glottal flow pulse from DNN through mapping of the synthesis parameters to the pulse waveform.\n *\n */\nvoid Generate_DNN_pulse(gsl_vector *pulse, gsl_vector *fundf, gsl_vector *gain, gsl_vector *naq, gsl_vector *h1h2,\n\tgsl_matrix *hnr, gsl_matrix *glflowsp, gsl_matrix *lsf, gsl_matrix **DNN_W, gsl_vector **input_minmax, int index, PARAM *params) {\n\n\t/* Initialize */\n\tint i,j,L,numlayers = params->dnn_weight_dims->size/2;\n\n\t/* Allocate memory */\n\tgsl_vector *inputdata = gsl_vector_calloc(DNN_W[0]->size1);\n\tgsl_vector **WProbs = (gsl_vector**)malloc((numlayers-1)*sizeof(gsl_vector*));\n\tfor(i=0;i<numlayers-1;i++)\n\t\tWProbs[i] = gsl_vector_calloc(DNN_W[i]->size2+1);\n\tgsl_vector *pulse_tmp = gsl_vector_calloc(DNN_W[numlayers-1]->size2);\n\n\t/* Assign input data to vector [F0 Gain HNR LSFsource LSF (Bias)] */\n\t/* Dimensions = [1 1 5 10 30 (1)] = 47 (+1) */\n\tint NPAR = 47;\n\tint f,cur_index,stack = 0;\n\tint lim1 = -floor(params->dnn_number_of_stacked_frames/2.0);\n\tint lim2 = ceil(params->dnn_number_of_stacked_frames/2.0);\n\tfor(f=lim1;f<lim2;f++) {\n\n\t\t/* Evaluate current frame */\n\t\tcur_index = GSL_MIN(GSL_MAX(index+f,0),params->n_frames-1);\n\n\t\t/* Assign parameters */\n\t\tgsl_vector_set(inputdata,0+stack*NPAR,gsl_vector_get(fundf,cur_index));   \t\t\t// F0\n\t\tgsl_vector_set(inputdata,1+stack*NPAR,gsl_vector_get(gain,cur_index));    \t \t\t// Gain\n\t\tfor(i=0;i<5;i++)\n\t\t\tgsl_vector_set(inputdata,2+stack*NPAR+i,gsl_matrix_get(hnr,cur_index,i));      \t// HNR\n\t\tfor(i=0;i<10;i++)\n\t\t\tgsl_vector_set(inputdata,7+stack*NPAR+i,gsl_matrix_get(glflowsp,cur_index,i)); \t// LSFsource\n\t\tfor(i=0;i<30;i++)\n\t\t\tgsl_vector_set(inputdata,17+stack*NPAR+i,gsl_matrix_get(lsf,cur_index,i));     \t// LSF\n\n\t\t/* Normalize input data to values between [0.1,0.9] (if done so in DNN training) */\n\t\t/* data_norm = 0.1 + 0.8*(data - min)/(max - min); */\n\t\tif(params->dnn_input_normalized == 1) {\n\t\t\tdouble min,max;\n\t\t\tfor(i=0;i<NPAR;i++) {\n\t\t\t\tmin = gsl_vector_get(input_minmax[0],i);\n\t\t\t\tmax = gsl_vector_get(input_minmax[0],i+NPAR);\n\t\t\t\tgsl_vector_set(inputdata,i+stack*NPAR, 0.1 + 0.8*(gsl_vector_get(inputdata,i+stack*NPAR) - min)/(max-min));\n\t\t\t}\n\t\t}\n\n\t\t/* Increment stack */\n\t\tstack++;\n\t}\n\n\t/* Set the bias at the end of the vector */\n\tgsl_vector_set(inputdata,inputdata->size-1,1);\n\n\t/* Evaluate WProbs[0] = 1./(1 + exp(-data*DNN_W[0])) (sigmoid layer) */\n\tfor(i=0;i<DNN_W[0]->size2;i++) {\n\t\tfor(j=0;j<DNN_W[0]->size1;j++)\n\t\t\tgsl_vector_set(WProbs[0],i,gsl_vector_get(WProbs[0],i) + gsl_vector_get(inputdata,j)*gsl_matrix_get(DNN_W[0],j,i));\n\t\tgsl_vector_set(WProbs[0],i,1.0/(1.0 + exp(-gsl_vector_get(WProbs[0],i))));\n\t}\n\tgsl_vector_set(WProbs[0],WProbs[0]->size-1,1); // Set bias term\n\n\t/* Evaluate WPprobs[i] = 1./(1 + exp(-WProbs[i-1]*DNN_W[i])) (sigmoid layer) */\n\tfor(L=1;L<numlayers-1;L++) {\n\t\tfor(i=0;i<DNN_W[L]->size2;i++) {\n\t\t\tfor(j=0;j<DNN_W[L]->size1;j++)\n\t\t\t\tgsl_vector_set(WProbs[L],i,gsl_vector_get(WProbs[L],i) + gsl_vector_get(WProbs[L-1],j)*gsl_matrix_get(DNN_W[L],j,i));\n\t\t\tgsl_vector_set(WProbs[L],i,1.0/(1.0 + exp(-gsl_vector_get(WProbs[L],i))));\n\t\t}\n\t\tgsl_vector_set(WProbs[L],WProbs[L]->size-1,1); // Set bias term\n\t}\n\n\t/* Evaluate pulses = WProbs[end]*DNN_W[end] (linear layer) */\n\tfor(i=0;i<DNN_W[numlayers-1]->size2;i++)\n\t\tfor(j=0;j<DNN_W[numlayers-1]->size1;j++)\n\t\t\tgsl_vector_set(pulse_tmp,i,gsl_vector_get(pulse_tmp,i) + gsl_vector_get(WProbs[numlayers-2],j)*gsl_matrix_get(DNN_W[numlayers-1],j,i));\n\n\t/* Interpolate pulse to desired length */\n\tInterpolate(pulse_tmp,pulse);\n\n\t/* Free memory */\n\tgsl_vector_free(inputdata);\n\tfor(i=0;i<numlayers-1;i++)\n\t\tgsl_vector_free(WProbs[i]);\n\tfree(WProbs);\n\tgsl_vector_free(pulse_tmp);\n}\n\n\n\n\n\n\n\n/**\n * Generate_DNN_pulse_PCA\n *\n * Generate glottal flow pulse by mapping the synthesis parameters to the PC weights and then reconstructing the pulse through PC weights and PCs.\n *\n */\nvoid Generate_DNN_pulse_PCA(gsl_vector *pulse, gsl_vector *fundf, gsl_vector *gain, gsl_vector *naq, gsl_vector *h1h2,\n\tgsl_matrix *hnr, gsl_matrix *glflowsp, gsl_matrix *lsf, gsl_matrix **DNN_W, gsl_vector **input_minmax, gsl_matrix *pca_pc, int index, PARAM *params) {\n\n\t/* Initialize */\n\tint i,j,L,numlayers = params->dnn_weight_dims->size/2;\n\n\t/* Allocate memory */\n\tgsl_vector *inputdata = gsl_vector_calloc(DNN_W[0]->size1);\n\tgsl_vector **WProbs = (gsl_vector**)malloc((numlayers-1)*sizeof(gsl_vector*));\n\tfor(i=0;i<numlayers-1;i++)\n\t\tWProbs[i] = gsl_vector_calloc(DNN_W[i]->size2+1);\n\tgsl_vector *pcw = gsl_vector_calloc(DNN_W[numlayers-1]->size2);\n\n\t/***** NORMAL *****/\n\t/* Assign input data to vector [F0 Gain HNR LSFsource LSF Bias] */\n\t/* Dimensions = [1 1 5 10 30 1] = 48 */\n\tgsl_vector_set(inputdata,0,gsl_vector_get(fundf,index));    // F0\n\tgsl_vector_set(inputdata,1,gsl_vector_get(gain,index));     // Gain\n\tfor(i=0;i<5;i++)\n\t\tgsl_vector_set(inputdata,2+i,gsl_matrix_get(hnr,index,i));      // HNR\n\tfor(i=0;i<10;i++)\n\t\tgsl_vector_set(inputdata,7+i,gsl_matrix_get(glflowsp,index,i)); // LSFsource\n\tfor(i=0;i<30;i++)\n\t\tgsl_vector_set(inputdata,17+i,gsl_matrix_get(lsf,index,i));     // LSF\n\tgsl_vector_set(inputdata,47,1);                                         // Bias\n\n\t/***** INCLUDING NAQ AND H1H2 *****/\n\t/* Assign input data to vector [F0 Gain NAQ H1H2 HNR LSFsource LSF Bias] */\n\t/* Dimensions = [1 1 1 1 5 10 30 1] = 50 \n\tgsl_vector_set(inputdata,0,gsl_vector_get(fundf,index));    // F0\n\tgsl_vector_set(inputdata,1,gsl_vector_get(gain,index));     // Gain\n\tgsl_vector_set(inputdata,2,gsl_vector_get(naq,index));      // NAQ\n\tgsl_vector_set(inputdata,3,gsl_vector_get(h1h2,index));     // H1H2\n\tfor(i=0;i<5;i++)\n\t\tgsl_vector_set(inputdata,4+i,gsl_matrix_get(hnr,index,i));      // HNR\n\tfor(i=0;i<10;i++)\n\t\tgsl_vector_set(inputdata,9+i,gsl_matrix_get(glflowsp,index,i)); // LSFsource\n\tfor(i=0;i<30;i++)\n\t\tgsl_vector_set(inputdata,19+i,gsl_matrix_get(lsf,index,i));     // LSF\n\tgsl_vector_set(inputdata,49,1);                                         // Bias\n\t*/\n\n\t/* Evaluate WProbs[0] = 1./(1 + exp(-data*DNN_W[0])) (sigmoid layer) */\n\tfor(i=0;i<DNN_W[0]->size2;i++) {\n\t\tfor(j=0;j<DNN_W[0]->size1;j++)\n\t\t\tgsl_vector_set(WProbs[0],i,gsl_vector_get(WProbs[0],i) + gsl_vector_get(inputdata,j)*gsl_matrix_get(DNN_W[0],j,i));\n\t\tgsl_vector_set(WProbs[0],i,1.0/(1.0 + exp(-gsl_vector_get(WProbs[0],i))));\n\t}\n\tgsl_vector_set(WProbs[0],WProbs[0]->size-1,1); // Set bias term\n\n\t/* Evaluate WPprobs[i] = 1./(1 + exp(-WProbs[i-1]*DNN_W[i])) (sigmoid layer) */\n\tfor(L=1;L<numlayers-1;L++) {\n\t\tfor(i=0;i<DNN_W[L]->size2;i++) {\n\t\t\tfor(j=0;j<DNN_W[L]->size1;j++)\n\t\t\t\tgsl_vector_set(WProbs[L],i,gsl_vector_get(WProbs[L],i) + gsl_vector_get(WProbs[L-1],j)*gsl_matrix_get(DNN_W[L],j,i));\n\t\t\tgsl_vector_set(WProbs[L],i,1.0/(1.0 + exp(-gsl_vector_get(WProbs[L],i))));\n\t\t}\n\t\tgsl_vector_set(WProbs[L],WProbs[L]->size-1,1); // Set bias term\n\t}\n\n\t/* Evaluate pulses = WProbs[end]*DNN_W[end] (linear layer) */\n\tfor(i=0;i<DNN_W[numlayers-1]->size2;i++)\n\t\tfor(j=0;j<DNN_W[numlayers-1]->size1;j++)\n\t\t\tgsl_vector_set(pcw,i,gsl_vector_get(pcw,i) + gsl_vector_get(WProbs[numlayers-2],j)*gsl_matrix_get(DNN_W[numlayers-1],j,i));\n\n\t/* Allocate PCA pulse */\n\tgsl_vector *pca_pulse = gsl_vector_calloc(params->pca_pulse_length);\n\n\t/* Define pulse from PC and weights */\n\tif(params->pca_order_synthesis < 0 || params->pca_order_synthesis > params->pca_order) {\n\t\tprintf(\"PCA_ORDER_SYNTHESIS must be between 0 and PCA_ORDER. PCA_ORDER_SYNTHESIS set to PCA_ORDER.\\n\");\n\t\tparams->pca_order_synthesis = params->pca_order;\n\t}\n\tfor(i=0;i<params->pca_order_synthesis;i++)\n\t\tfor(j=0;j<params->pca_pulse_length;j++)\n\t\t\tgsl_vector_set(pca_pulse,j,gsl_vector_get(pca_pulse,j) + gsl_vector_get(pcw,i)*gsl_matrix_get(pca_pc,j,i));\n\n\t/* Interpolate pulse to desired length */\n\tInterpolate(pca_pulse,pulse);\n\n\t/* Free memory */\n\tgsl_vector_free(inputdata);\n\tfor(i=0;i<numlayers-1;i++)\n\t\tgsl_vector_free(WProbs[i]);\n\tfree(WProbs);\n\tgsl_vector_free(pcw);\n\tgsl_vector_free(pca_pulse);\n}\n\n\n\n\n\n\n/**\n * Shift_right_and_add\n *\n * Shift all the elements of the vector one index to the right, and add the new value in the beginning.\n *\n * @param vector\n * @param value\n */\nvoid Shift_right_and_add(gsl_vector *vector, double value) {\n\n\tint i;\n\tfor(i=vector->size-1;i>0;i--)\n\t\tgsl_vector_set(vector,i,gsl_vector_get(vector,i-1));\n\tgsl_vector_set(vector,0,value);\n}\n\n\n\n\n/**\n * Truncate_pulse\n *\n * Truncate pulse for unvoiced regions\n *\n * @param pulse\n * @param fundf\n * @param sample_index\n * @param frame_index\n * @param params\n */\ngsl_vector *Truncate_pulse(gsl_vector *pulse, gsl_vector *fundf, int sample_index, int frame_index, PARAM *params) {\n\n\t/* Initialize */\n\tint sample_index_tmp,frame_index_tmp,i = 1,edit_flag = 0;\n\tint uvshift = rint(params->shift/params->speed);\n\n\t/* Find unvoiced */\n\twhile(i*uvshift < pulse->size) {\n\t\tsample_index_tmp = sample_index + i*uvshift;\n\t\tframe_index_tmp = floor(params->n_frames*(sample_index_tmp/(double)params->signal_length));\n\t\tif(frame_index_tmp > fundf->size-1)\n\t\t\tbreak;\n\t\tif(gsl_vector_get(fundf,frame_index_tmp) == 0) {\n\t\t\tedit_flag = 1;\n\t\t\tbreak;\n\t\t}\n\t\ti = i + 1;\n\t}\n\n\t/* Truncate */\n\tif(edit_flag == 1) {\n\t\tgsl_vector *pulse_short = gsl_vector_alloc(i*uvshift);\n\t\tfor(i=0;i<pulse_short->size;i++)\n\t\t\tgsl_vector_set(pulse_short,i,gsl_vector_get(pulse,i)*HANN(pulse_short->size+i,2*pulse_short->size));\n\t\tgsl_vector_free(pulse);\n\t\tpulse = pulse_short;\n\t}\n\n\t/* Return */\n\treturn pulse;\n}\n\n\n\n\n\n/**\n * Average_pulses\n *\n * Average adjacent pulses in time and quality\n *\n * @param ...\n */\nvoid Average_pulses(gsl_vector *pulse, gsl_vector *fundf, gsl_vector *resynthesis_pulse_index, gsl_matrix *pulses, gsl_vector *pulse_lengths, int frame_index, PARAM *params) {\n\n\t/* Perform only in resynthesis */\n\tif(params->resynth == 0)\n\t\treturn;\n\n\t/* Sanity check, the number of pulses must be odd */\n\tif(params->average_n_adjacent_pulses < 2)\n\t\tparams->average_n_adjacent_pulses = 1;\n\tif(params->average_n_adjacent_pulses%2 == 0)\n\t\tparams->average_n_adjacent_pulses++;\n\n\t/* Initialize */\n\tint j,k,N = pulse->size;\n\tgsl_matrix *adjacent_pulses = gsl_matrix_alloc(params->average_n_adjacent_pulses,N);\n\tgsl_vector *pulse_N = gsl_vector_alloc(N);\n\tgsl_vector *pulse_temp;\n\n\t/* Fill pulse matrix with the original pulse */\n\tInterpolate(pulse,pulse_N);\n\tfor(j=0;j<params->average_n_adjacent_pulses;j++)\n\t\tfor(k=0;k<N;k++)\n\t\t\tgsl_matrix_set(adjacent_pulses,j,k,gsl_vector_get(pulse_N,k));\n\n\t/* Fill possible earlier pulses */\n\tj = 1;\n\tint added_pulses = 0;\n\twhile(frame_index-j >= 0 && gsl_vector_get(fundf,frame_index-j) > 0 && added_pulses != floor(params->average_n_adjacent_pulses/2)) {\n\t\tif(gsl_vector_get(resynthesis_pulse_index,frame_index-j) != 0) {\n\t\t\tint pulseind_back = gsl_vector_get(resynthesis_pulse_index,frame_index-j);\n\t\t\tint pulselen = gsl_vector_get(pulse_lengths,pulseind_back);\n\t\t\tpulse_temp = gsl_vector_alloc(pulselen);\n\t\t\tfor(k=0;k<pulselen;k++)\n\t\t\t\tgsl_vector_set(pulse_temp,k,gsl_matrix_get(pulses,pulseind_back,k));\n\t\t\tInterpolate(pulse_temp,pulse_N);\n\t\t\tgsl_vector_free(pulse_temp);\n\t\t\tfor(k=0;k<N;k++)\n\t\t\t\tgsl_matrix_set(adjacent_pulses,floor(params->average_n_adjacent_pulses/2)-added_pulses-1,k,gsl_vector_get(pulse_N,k));\n\t\t\tadded_pulses++;\n\t\t}\n\t\tj++;\n\t}\n\n\t/* Fill possible latter pulses */\n\tj = 1;\n\tadded_pulses = 0;\n\twhile(frame_index+j < params->n_frames && gsl_vector_get(fundf,frame_index+j) > 0 && added_pulses != floor(params->average_n_adjacent_pulses/2)) {\n\t\tif(gsl_vector_get(resynthesis_pulse_index,frame_index+j) != 0) {\n\t\t\tint pulseind_forward = gsl_vector_get(resynthesis_pulse_index,frame_index+j);\n\t\t\tint pulselen = gsl_vector_get(pulse_lengths,pulseind_forward);\n\t\t\tpulse_temp = gsl_vector_alloc(pulselen);\n\t\t\tfor(k=0;k<pulselen;k++)\n\t\t\t\tgsl_vector_set(pulse_temp,k,gsl_matrix_get(pulses,pulseind_forward,k));\n\t\t\tInterpolate(pulse_temp,pulse_N);\n\t\t\tgsl_vector_free(pulse_temp);\n\t\t\tfor(k=0;k<N;k++)\n\t\t\t\tgsl_matrix_set(adjacent_pulses,floor(params->average_n_adjacent_pulses/2)+added_pulses+1,k,gsl_vector_get(pulse_N,k));\n\t\t\tadded_pulses++;\n\t\t}\n\t\tj++;\n\t}\n\n\t/* Average adjacent pulses to pulse */\n\tgsl_vector_set_zero(pulse);\n\tfor(k=0;k<N;k++)\n\t\tfor(j=0;j<params->average_n_adjacent_pulses;j++)\n\t\t\tgsl_vector_set(pulse,k,gsl_vector_get(pulse,k) + gsl_matrix_get(adjacent_pulses,j,k)/params->average_n_adjacent_pulses);\n\n\t/* Free memory */\n\tgsl_vector_free(pulse_N);\n\tgsl_matrix_free(adjacent_pulses);\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n/**\n * Function Fill_pulse_indices\n *\n * Fill pulse indices with 0 values with nearest pulsi indices\n *\n * @param ...\n */\nvoid Fill_pulse_indices(gsl_vector *ind) {\n\n\tint i,k,k1,k2;\n\n\t/* Copy original vector */\n\tgsl_vector *ind_new = gsl_vector_alloc(ind->size);\n\tgsl_vector_memcpy(ind_new,ind);\n\n\t/* Fill */\n\tfor(i=0;i<ind->size;i++) {\n\t\tif(gsl_vector_get(ind,i) == 0) {\n\n\t\t\t/* If gap is found, find the nearest non-zero value */\n\t\t\tif(gsl_vector_get(ind,i) == 0) {\n\t\t\t\tk1 = i+1;\n\t\t\t\twhile(k1 < ind->size-1 && gsl_vector_get(ind,k1) == 0)\n\t\t\t\t\tk1++;\n\t\t\t\tk2 = i-1;\n\t\t\t\twhile(k2 > 0 && gsl_vector_get(ind,k2) == 0)\n\t\t\t\t\tk2--;\n\t\t\t\tif(fabs(k1-i) < fabs(k2-i)) {\n\t\t\t\t\tif(k1 < ind->size-1)\n\t\t\t\t\t\tk = k1;\n\t\t\t\t\telse\n\t\t\t\t\t\tk = k2;\n\t\t\t\t} else {\n\t\t\t\t\tif(k2 > 0)\n\t\t\t\t\t\tk = k2;\n\t\t\t\t\telse\n\t\t\t\t\t\tk = k1;\n\t\t\t\t}\n\n\t\t\t\t/* Sanity check */\n\t\t\t\tif(k < 0 || k > ind->size-1)\n\t\t\t\t\tbreak;\n\n\t\t\t\t/* Fill the gap with the nearest found non-zero value */\n\t\t\t\tgsl_vector_set(ind_new,i,gsl_vector_get(ind,k));\n\t\t\t}\n\t\t}\n\t}\n\n\t/* Copy fixed vector to the original one and free memory */\n\tgsl_vector_memcpy(ind,ind_new);\n\tgsl_vector_free(ind_new);\n}\n\n\n\n\n\n\n\n\n\n\n\n/**\n * Function Evaluate_target_error\n *\n * Evaluate error between target parameters and pulse parameters.\n *\n * @param ...\n */\nvoid Evaluate_target_error(gsl_matrix *lsf, gsl_matrix *glflowsp, gsl_matrix *harmonics, gsl_matrix *hnr_i, gsl_matrix *waveform, gsl_vector *h1h2, gsl_vector *naq, gsl_vector *gain, gsl_vector *fundf,\n\t\tgsl_matrix *plsf, gsl_matrix *ptilt, gsl_matrix *pharm, gsl_matrix *phnr, gsl_matrix *pwaveform, gsl_vector *ph1h2, gsl_vector *pnaq, gsl_vector *pgain, gsl_matrix *pca_w, gsl_matrix *pca_w_lib, gsl_vector *pulse_lengths,\n\t\tint frame_index, gsl_vector *inds, gsl_vector *eparam, gsl_vector *pulse_clus_id, gsl_matrix *pulse_clusters, PARAM *params) {\n\n\tint i,j,k,use_clusters = 0,npulses = params->number_of_pulses;\n\tint n_pulsecandidates = params->n_pulsecandidates;\n\tint nparams = params->paramweights->size;\n\tdouble m,std;\n\tgsl_vector_view cur_pulses;\n\tgsl_vector *lsfw = gsl_vector_calloc(lsf->size2);\n\tgsl_vector *lsfsourcew = gsl_vector_calloc(glflowsp->size2);\n\tgsl_vector_set_all(eparam, BIGGER_POS_NUMBER);\n\n\t/* Use pulse clusters */\n\tif(params->pulse_clustering == 1) {\n\n\t\tuse_clusters = 1;\n\t\tcur_pulses = gsl_matrix_row(pulse_clusters, (int)(gsl_vector_get(pulse_clus_id, frame_index)));\n\n\t\t/* Get number of pulses in cluster (awkward) */\n\t\tnpulses = 0;\n\t\tfor(i=0;i<(&cur_pulses.vector)->size;i++) {\n\t\t\tif((int)gsl_vector_get(&cur_pulses.vector, i) == -1)\n\t\t\t\tbreak;\n\t\t\tnpulses++;\n\t\t}\n\t\tif(npulses == 0) {\n\t\t\tuse_clusters = 0;\n\t\t\tnpulses = params->number_of_pulses;\n\t\t}\n\t\tif(params->n_pulsecandidates > npulses){\n\t\t\tn_pulsecandidates = npulses;\n\t\t}\n\t}\n\n\t/* Evaluate LSF weighting vector */\n\tfor(i=1;i<lsf->size2-1;i++)\n\t\tgsl_vector_set(lsfw,i,1.0/(gsl_matrix_get(lsf,frame_index,i)-gsl_matrix_get(lsf,frame_index,i-1)) + 1.0/(gsl_matrix_get(lsf,frame_index,i+1)-gsl_matrix_get(lsf,frame_index,i)));\n\tdouble mean = Mean(lsfw);\n\tgsl_vector_set(lsfw,0,mean);\n\tgsl_vector_set(lsfw,lsfw->size-1,mean);\n\n\t/* Evaluate source LSF weighting vector */\n\tfor(i=1;i<glflowsp->size2-1;i++)\n\t\tgsl_vector_set(lsfsourcew,i,1.0/(gsl_matrix_get(glflowsp,frame_index,i)-gsl_matrix_get(glflowsp,frame_index,i-1)) + 1.0/(gsl_matrix_get(glflowsp,frame_index,i+1)-gsl_matrix_get(glflowsp,frame_index,i)));\n\tmean = Mean(lsfsourcew);\n\tgsl_vector_set(lsfsourcew,0,gsl_vector_get(lsfsourcew,1));\n\tgsl_vector_set(lsfsourcew,lsfsourcew->size-1,mean);\n\n\t/* Initialize */\n\tgsl_matrix *error = gsl_matrix_calloc(npulses,nparams);\n\tgsl_vector *E = gsl_vector_calloc(npulses);\n\tgsl_permutation *p = gsl_permutation_alloc(E->size);\n\n\t/* FOR PULSE CLUSTERS! */\n\tif(use_clusters == 1) {\n\n\t\t/* Evaluate absolute error of every parameter: 0: LSF, 1:tilt, 2:harm, 3:hnr, 4:gain, 5:f0, 6:waveform, 7: h1h2, 8: naq*/\n\t\tfor(k=0;k<npulses;k++){\n\t\t\ti = (int)gsl_vector_get((&cur_pulses.vector), k);\n\t\t\tif(i == -1)\n\t\t\t\tbreak;\n\n\t\t\t/* LSF */\n\t\t\tif(gsl_vector_get(params->paramweights,0) > 0) {\n\t\t\t\tfor(j=0;j<plsf->size2;j++)\n\t\t\t\t\tgsl_matrix_set(error,k,0, gsl_matrix_get(error,k,0) + gsl_vector_get(lsfw,j)*powf(gsl_matrix_get(lsf,frame_index,j)-gsl_matrix_get(plsf,i,j),2));\n\t\t\t\tgsl_matrix_set(error,k,0,sqrt(gsl_matrix_get(error,k,0)));\n\t\t\t}\n\n\t\t\t/* Tilt */\n\t\t\tif(gsl_vector_get(params->paramweights,1) > 0 && params->use_tilt == 1) {\n\t\t\t\tfor(j=0;j<ptilt->size2;j++)\n\t\t\t\t  gsl_matrix_set(error,k,1, gsl_matrix_get(error,k,1) + gsl_vector_get(lsfsourcew,j)*powf(gsl_matrix_get(glflowsp,frame_index,j)-gsl_matrix_get(ptilt,i,j),2));\n\t\t\t\tgsl_matrix_set(error,k,1,sqrt(gsl_matrix_get(error,k,1)));\n\t\t\t}\n\n\t\t\t/* Harmonics */\n\t\t\tif(gsl_vector_get(params->paramweights,2) > 0 && params->use_harmonics == 1) {\n\t\t\t\tfor(j=0;j<pharm->size2;j++)\n\t\t\t\t  gsl_matrix_set(error,k,2, gsl_matrix_get(error,k,2) + powf(gsl_matrix_get(harmonics,frame_index,j)-gsl_matrix_get(pharm,i,j),2));\n\t\t\t\tgsl_matrix_set(error,k,2,sqrt(gsl_matrix_get(error,k,2)));\n\t\t\t}\n\n\t\t\t/* HNR */\n\t\t\tif(gsl_vector_get(params->paramweights,3) > 0 && params->use_hnr == 1) {\n\t\t\t\tfor(j=0;j<phnr->size2;j++)\n\t\t\t\t  gsl_matrix_set(error,k,3, gsl_matrix_get(error,k,3) + powf(gsl_matrix_get(hnr_i,frame_index,j)-gsl_matrix_get(phnr,i,j),2));\n\t\t\t\tgsl_matrix_set(error,k,3,sqrt(gsl_matrix_get(error,k,3)));\n\t\t\t}\n\n\t\t\t/* Gain */\n\t\t\tif(gsl_vector_get(params->paramweights,4) > 0) {\n\t\t\t\tgsl_matrix_set(error,k,4,fabs(gsl_vector_get(gain,frame_index)-gsl_vector_get(pgain,i)));\n\t\t\t}\n\n\t\t\t/* F0 */\n\t\t\tif(gsl_vector_get(params->paramweights,5) > 0) {\n\t\t\t\tgsl_matrix_set(error,k,5,fabs(gsl_vector_get(fundf,frame_index)*params->pitch-2.0*params->FS/gsl_vector_get(pulse_lengths,i)));\n\t\t\t}\n\n\t\t\t/* Waveform */\n\t\t\tif(gsl_vector_get(params->paramweights,6) > 0 && params->use_waveform == 1) {\n\t\t\t\tfor(j=0;j<pwaveform->size2;j++)\n\t\t\t\t  gsl_matrix_set(error,k,6, gsl_matrix_get(error,k,6) + powf(gsl_matrix_get(waveform,frame_index,j)-gsl_matrix_get(pwaveform,i,j),2));\n\t\t\t\tgsl_matrix_set(error,k,6,sqrt(gsl_matrix_get(error,k,6)));\n\t\t\t}\n\n\t\t\t/* H1H2 */\n\t\t\tif(gsl_vector_get(params->paramweights,7) > 0 && params->use_h1h2 == 1) {\n\t\t\t\tgsl_matrix_set(error,k,7,fabs(gsl_vector_get(h1h2,frame_index)-gsl_vector_get(ph1h2,i)));\n\t\t\t}\n\n\t\t\t/* NAQ */\n\t\t\tif(gsl_vector_get(params->paramweights,8) > 0 && params->use_naq == 1) {\n\t\t\t\tgsl_matrix_set(error,k,8,fabs(gsl_vector_get(naq,frame_index)-gsl_vector_get(pnaq,i)));\n\t\t\t}\n\n\t\t\t/* PCA */\n\t\t\tif(gsl_vector_get(params->paramweights,9) > 0 && params->use_pulselib_pca == 1) {\n\t\t\t\tfor(j=0;j<pca_w->size2;j++)\n\t\t\t\t  gsl_matrix_set(error,k,9, gsl_matrix_get(error,k,9) + powf(gsl_matrix_get(pca_w,frame_index,j)-gsl_matrix_get(pca_w_lib,i,j),2));\n\t\t\t\tgsl_matrix_set(error,k,9,sqrt(gsl_matrix_get(error,k,9)));\n\t\t\t}\n\t\t}\n\n\t\t/* Normalize error of every parameter (subtract mean and divide by standard deviation) and weight */\n\t\tfor(i=0;i<nparams;i++) {\n\t\t\tif(gsl_vector_get(params->paramweights,i) > 0) {\n\n\t\t\t\t/* Evaluate mean of each error */\n\t\t\t\tm = 0;\n\t\t\t\tfor(j=0;j<npulses;j++)\n\t\t\t\t\tm += gsl_matrix_get(error,j,i);\n\t\t\t\tm = m/npulses;\n\n\t\t\t\t/* Evaluate standard deviation or each error */\n\t\t\t\tstd = 0;\n\t\t\t\tfor(j=0;j<npulses;j++)\n\t\t\t\t\tstd += (gsl_matrix_get(error,j,i)-m)*(gsl_matrix_get(error,j,i)-m);\n\t\t\t\tstd = sqrt(std/(npulses-1));\n\t\t\t\tif(std == 0)\n\t\t\t\t\tstd = 1;\n\n\t\t\t\t/* Weight */\n\t\t\t\tfor(j=0;j<npulses;j++)\n\t\t\t\t\tgsl_matrix_set(error,j,i,(gsl_matrix_get(error,j,i)-m)/std*gsl_vector_get(params->paramweights, i));\n\t\t\t}\n\t\t}\n\n\t\t/* Evaluate total error */\n\t\tdouble min_err = BIG_POS_NUMBER;\n\t\tint min_i = 0;\n\t\tgsl_vector *avg_err = gsl_vector_alloc(nparams);\n\t\tgsl_vector_set_zero(avg_err);\n\t\tfor(i=0;i<npulses;i++){\n\t\t\tfor(j=0;j<nparams;j++){\n\t\t\t\tgsl_vector_set(E,i,gsl_vector_get(E,i) + gsl_matrix_get(error,i,j));\n\t\t\t\tgsl_vector_set(avg_err, j, gsl_vector_get(avg_err, j) + gsl_matrix_get(error,i,j));\n\t\t\t}\n\t\t\tif (gsl_vector_get(E,i) < min_err){\n\t\t\t\tmin_err = gsl_vector_get(E,i);\n\t\t\t\tmin_i = i;\n\t\t\t}\n\t\t}\n\t\tgsl_vector_free(avg_err);\n\t\tgsl_sort_vector_index(p,E);\n\t\tfor(i=0;i<n_pulsecandidates;i++) {\n\t\t\tgsl_vector_set(inds,i,gsl_permutation_get(p,i));\n\t\t\tgsl_vector_set(eparam,i,gsl_vector_get(E,gsl_vector_get(inds,i)));\n\t\t\tgsl_vector_set(inds,i,(int)gsl_vector_get(&cur_pulses.vector,gsl_permutation_get(p,i)));\n\t\t}\n\n\t\t/* Add best candidates to cluster of next frame */\n\t\tif(gsl_vector_get(pulse_clus_id, frame_index) != gsl_vector_get(pulse_clus_id, frame_index+1)) {\n\t\t\tif(npulses > 1000)\n\t\t\t\tnpulses = 1000;\n\t\t\tfor(i=0;i<n_pulsecandidates;i++) {\n\t\t\t\tgsl_matrix_set(pulse_clusters, (int)(gsl_vector_get(pulse_clus_id, frame_index+1)), npulses+i, gsl_vector_get(inds, i));\n\t\t\t}\n\t\t}\n\n\t\t/* Sanity check */\n\t\tint from_cluster = 0;\n\t\tfor(i=0;i<(&cur_pulses.vector)->size;i++) {\n\t\t\tif(gsl_vector_get(&cur_pulses.vector, i) == gsl_vector_get(inds, 0))\n\t\t\t\tfrom_cluster = 1;\n\t\t}\n\n\n\n\n\t} else { /* FOR NORMAL ERROR CALCULATION */\n\n\n\t\t// TODO: SET LIMITS FOR EACH PARAMETER THAT PREVENT SELECTING A PULSE!\n\t\t// TODO: MAE OR RMSE\n\n\t    /* Evaluate RMSE of every parameter: 0: LSF, 1:tilt, 2:harm, 3:hnr, 4:gain, 5:f0, 6:waveform, 7:h1h2, 8: naq */\n\t\tfor(i=0;i<npulses;i++) {\n\n\t\t\t/* LSF, with weighting */\n\t\t\tif(gsl_vector_get(params->paramweights,0) > 0) {\n\t\t\t\tfor(j=0;j<plsf->size2;j++)\n\t\t\t\t\tgsl_matrix_set(error,i,0, gsl_matrix_get(error,i,0) + gsl_vector_get(lsfw,j)*powf(gsl_matrix_get(lsf,frame_index,j)-gsl_matrix_get(plsf,i,j),2));\n\t\t\t\tgsl_matrix_set(error,i,0,sqrt(gsl_matrix_get(error,i,0)));\n\t\t\t}\n\n\t\t\t/* Tilt, with weighting */\n\t\t\tif(gsl_vector_get(params->paramweights,1) > 0 && params->use_tilt == 1) {\n\t\t\t\tfor(j=0;j<ptilt->size2;j++)\n\t\t\t\t\tgsl_matrix_set(error,i,1, gsl_matrix_get(error,i,1) + gsl_vector_get(lsfsourcew,j)*powf(gsl_matrix_get(glflowsp,frame_index,j)-gsl_matrix_get(ptilt,i,j),2));\n\t\t\t\tgsl_matrix_set(error,i,1,sqrt(gsl_matrix_get(error,i,1)));\n\t\t\t}\n\n\t\t\t/* Harmonics */\n\t\t\tif(gsl_vector_get(params->paramweights,2) > 0 && params->use_harmonics == 1) {\n\t\t\t\tfor(j=0;j<pharm->size2;j++)\n\t\t\t\t\tgsl_matrix_set(error,i,2, gsl_matrix_get(error,i,2) + powf(gsl_matrix_get(harmonics,frame_index,j)-gsl_matrix_get(pharm,i,j),2));\n\t\t\t\tgsl_matrix_set(error,i,2,sqrt(gsl_matrix_get(error,i,2)));\n\t\t\t}\n\n\t\t\t/* HNR */\n\t\t\tif(gsl_vector_get(params->paramweights,3) > 0 && params->use_hnr == 1) {\n\t\t\t\tfor(j=0;j<phnr->size2;j++)\n\t\t\t\t\tgsl_matrix_set(error,i,3, gsl_matrix_get(error,i,3) + powf(gsl_matrix_get(hnr_i,frame_index,j)-gsl_matrix_get(phnr,i,j),2));\n\t\t\t\tgsl_matrix_set(error,i,3,sqrt(gsl_matrix_get(error,i,3)));\n\t\t\t}\n\n\t\t\t/* Gain */\n\t\t\tif(gsl_vector_get(params->paramweights,4) > 0) {\n\t\t\t\tgsl_matrix_set(error,i,4,fabs(gsl_vector_get(gain,frame_index)-gsl_vector_get(pgain,i)));\n\t\t\t}\n\n\t\t\t/* F0 */\n\t\t\tif(gsl_vector_get(params->paramweights,5) > 0) {\n\t\t\t\tgsl_matrix_set(error,i,5,fabs(gsl_vector_get(fundf,frame_index)*params->pitch-2.0*params->FS/gsl_vector_get(pulse_lengths,i)));\n\t\t\t}\n\n\t\t\t/* Waveform */\n\t\t\tif(gsl_vector_get(params->paramweights,6) > 0 && params->use_waveform == 1) {\n\t\t\t\tfor(j=0;j<pwaveform->size2;j++)\n\t\t\t\t  gsl_matrix_set(error,i,6, gsl_matrix_get(error,i,6) + powf(gsl_matrix_get(waveform,frame_index,j)-gsl_matrix_get(pwaveform,i,j),2));\n\t\t\t\tgsl_matrix_set(error,i,6,sqrt(gsl_matrix_get(error,i,6)));\n\t\t\t}\n\n\t\t\t/* H1H2 */\n\t\t\tif(gsl_vector_get(params->paramweights,7) > 0 && params->use_h1h2 == 1) {\n\t\t\t\tgsl_matrix_set(error,i,7,fabs(gsl_vector_get(h1h2,frame_index)-gsl_vector_get(ph1h2,i)));\n\t\t\t}\n\n\t\t\t/* Gain */\n\t\t\tif(gsl_vector_get(params->paramweights,8) > 0 && params->use_naq == 1) {\n\t\t\t\tgsl_matrix_set(error,i,8,fabs(gsl_vector_get(naq,frame_index)-gsl_vector_get(pnaq,i)));\n\t\t\t}\n\n\t\t\t/* PCA */\n\t\t\tif(gsl_vector_get(params->paramweights,9) > 0 && params->use_pulse_pca == 1) {\n\t\t\t\tfor(j=0;j<pca_w->size2;j++)\n\t\t\t\t  gsl_matrix_set(error,i,9, gsl_matrix_get(error,i,9) + powf(gsl_matrix_get(pca_w,frame_index,j)-gsl_matrix_get(pca_w_lib,i,j),2));\n\t\t\t\tgsl_matrix_set(error,i,9,sqrt(gsl_matrix_get(error,i,9)));\n\t\t\t}\n\t\t}\n\n\t    /* Normalize error of every parameter (subtract mean and divide by standard deviation) and weight */\n\t    for(i=0;i<nparams;i++) {\n\t    \tif(gsl_vector_get(params->paramweights,i) > 0) {\n\n\t\t\t\t/* Evaluate mean error of each parameter */\n\t\t\t\tm = 0;\n\t\t\t\tfor(j=0;j<npulses;j++)\n\t\t\t\t\tm += gsl_matrix_get(error,j,i);\n\t\t\t\tm = m/npulses;\n\n\t\t\t\t/* Evaluate standard deviation of error of each parameter */\n\t\t\t\tstd = 0;\n\t\t\t\tfor(j=0;j<npulses;j++)\n\t\t\t\t\tstd += (gsl_matrix_get(error,j,i)-m)*(gsl_matrix_get(error,j,i)-m);\n\t\t\t\tstd = sqrt(std/(npulses-1));\n\t\t\t\tif(std == 0)\n\t\t\t\t\tstd = 1;\n\n\t\t\t\t/* Normalize and weight */\n\t\t\t\tfor(j=0;j<npulses;j++)\n\t\t\t\t\tgsl_matrix_set(error,j,i,(gsl_matrix_get(error,j,i)-m)/std*gsl_vector_get(params->paramweights,i));\n\t    \t}\n\t    }\n\n\t    /* Evaluate total error, apply penalty for gross errors */\n\t    // TODO: DOES THIS YIELD BETTER QUALITY?\n\t    double gross_error_penalty_limit = 0; // For normally distributed data (mean = 0, sigma = 1)\n\t    double gross_error_penalty = 1.0;\n\t\tfor(i=0;i<npulses;i++) {\n\t\t\tfor(j=0;j<nparams;j++) {\n\t\t\t\tgsl_vector_set(E,i,gsl_vector_get(E,i) + gsl_matrix_get(error,i,j));\n\t\t\t\tif(gsl_matrix_get(error,i,j) > gross_error_penalty_limit)\n\t\t\t\t\tgsl_vector_set(E,i,gsl_vector_get(E,i) + gross_error_penalty);\n\t\t\t}\n\t\t}\n\n\t\t/* Select best candidates according to lowest target error and compare\n\t\t * them to the previous pulse */\n\t\tgsl_sort_vector_index(p,E);\n\t\tfor(i=0;i<n_pulsecandidates;i++) {\n\t\t\tgsl_vector_set(inds,i,gsl_permutation_get(p,i));\n\t\t\tgsl_vector_set(eparam,i,gsl_vector_get(E,gsl_vector_get(inds,i)));\n\t\t}\n\t}\n\n\t/* Free memory */\n\tgsl_matrix_free(error);\n\tgsl_vector_free(E);\n\tgsl_vector_free(lsfw);\n\tgsl_vector_free(lsfsourcew);\n\tgsl_permutation_free(p);\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n/**\n * Function Evaluate_concatenation_error_viterbi\n *\n * Eval concatenation error for viterbi pulse search\n *\n * @param ...\n */\nvoid Evaluate_concatenation_error_viterbi(gsl_vector *target, gsl_vector* target_next, gsl_vector *inds, gsl_vector *inds_next,gsl_matrix *pulses_rs,\n\t\tgsl_matrix *v_scores, gsl_matrix *v_best, int index, int dist_to_unvoiced, double additional_cost, PARAM *params) {\n\n\tint i, j, k = 0, num_skipped = 0;\n\tdouble e = 0,ccost;\n\t//double em = 0;\n\n\t/* Define concatenation cost according to distance to unvoiced and HNR */\n\tccost = params->concatenation_cost*additional_cost*(1.0-(1.0/sqrt((double)(dist_to_unvoiced))));\n\n\t/* Current pulses */\n\tfor(i=0;i<params->n_pulsecandidates;i++) {\n\n\t\t/* Next pulses */\n\t\tfor(j=0;j<params->n_pulsecandidates;j++){\n\n\t\t\t/* Possible optimization: skip comparison if highly unlikely to beat the best score */\n\t\t\tif(index > 0) {\n\t\t\t\tdouble current_best = gsl_matrix_get(v_scores, index+1, j);\n\t\t\t\tif(ccost * 0.1 + params->target_cost * gsl_vector_get(target,i) + gsl_matrix_get(v_scores,index,i) >= current_best) {\n\t\t\t\t\tnum_skipped++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t    \t/* Compare downsampled waveforms */\n\t\t\te = 0;\n\t\t\tfor(k = 0;k<pulses_rs->size2;k++){\n\t\t\t\te += powf(gsl_matrix_get(pulses_rs,gsl_vector_get(inds,i),k) - gsl_matrix_get(pulses_rs,gsl_vector_get(inds_next,j),k),2);\n\t\t\t}\n\t\t\te = sqrt(e);\n\n\t\t\t/* Bias against same pulse */\n\t\t\tif(e == 0) e = params->pulse_error_bias;\n\n\t\t\t/* Combine the two error measures */\n\t\t\t//e = (e + em)/2.0;\n\n\t\t\t/* Evaluate combined score */\n\t\t\tdouble combined_score;\n\t\t\tif(index == 0) {\n\t\t\t\tcombined_score  = params->target_cost * gsl_vector_get(target,i);\n\t\t\t\tgsl_matrix_set(v_scores, index,i, combined_score);\n\t\t\t} else\n\t\t\t\tcombined_score = ccost * e + params->target_cost * gsl_vector_get(target,i) + gsl_matrix_get(v_scores, index, i);\n\n\t\t\t/* Set scores and indices */\n\t\t\tif(combined_score < gsl_matrix_get(v_scores, index+1, j)) {\n\t\t\t\tgsl_matrix_set(v_scores, index+1, j, combined_score);\n\t\t\t\tgsl_matrix_set(v_best, index+1, j, i);\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n/**\n * Function Reestimate_hnr\n *\n * Re-estimate HNR for pulse library\n *\n * @param excitation_voiced\n * @param excitation_unvoiced\n * @param hnr HNR matrix\n * @param fundf F0 vector\n * @param params\n */\nvoid Reestimate_hnr(gsl_vector *excitation_voiced, gsl_vector *excitation_unvoiced, gsl_matrix *hnr, gsl_vector *fundf, PARAM *params) {\n\n\t/* Only if pulse library and harmonics are used */\n\tif(params->use_pulselib == 0 && params->use_hnr == 1)\n\t\treturn;\n\n\t/* Integrate voiced excitation signal */\n\tint i;\n\tgsl_vector *excitation_voiced_flow = gsl_vector_alloc(excitation_voiced->size);\n\tgsl_vector_memcpy(excitation_voiced_flow,excitation_voiced);\n\tfor(i=1;i<excitation_voiced_flow->size;i++)\n\t\tgsl_vector_set(excitation_voiced_flow,i,gsl_vector_get(excitation_voiced_flow,i-1)*LEAK + gsl_vector_get(excitation_voiced_flow,i));\n\n\t/* Evaluate HNR */\n\tHNR_eval_vu(excitation_voiced_flow, excitation_unvoiced, hnr, fundf, params);\n\tSmooth_matrix(hnr,params->hnr_smooth_len);\n\tgsl_vector_free(excitation_voiced_flow);\n}\n\n\n\n\n\n\n\n/**\n * Function HNR_compensation\n *\n * Compensate HNR values based on the new values\n *\n * @param hnr old HNR values\n * @param hnr_new new HNR values\n */\nvoid HNR_compensation(gsl_matrix *hnr, gsl_matrix *hnr_new, PARAM *params) {\n\n\t/* Set params */\n\tparams->hnr_reestimated = 1;\n\n\t/* Return if HNR compensation is not used, or HNR is not used, or pulse library is used */\n\tif(params->hnr_compensation == 0 || hnr == NULL || params->use_pulselib == 1)\n\t\treturn;\n\n\t/* Make compensation based on the estimated HNR of synthesized excitation */\n\tSmooth_matrix(hnr_new,params->hnr_smooth_len);\n\tint i,j;\n\tfor(j=0;j<hnr->size1;j++) {\n\t\tfor(i=0;i<hnr->size2;i++)\n\t\t\tgsl_matrix_set(hnr,j,i,gsl_matrix_get(hnr,j,i) + gsl_matrix_get(hnr,j,i) - gsl_matrix_get(hnr_new,j,i));\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n\n/**\n * Function HNR_eval_vu\n *\n * Evaluate HNR of signal (voiced/unvoiced)\n *\n * @param signal_v input signal voiced\n * @param signal_uv input signal unvoiced\n * @param hnr HNR matrix\n * @param fundf fundamental frequency\n * @param frame_length frame length in samples\n * @paran shift shift length in samples\n * @param speed synthesis speed\n *\n */\nvoid HNR_eval_vu(gsl_vector *signal_v,gsl_vector *signal_uv,gsl_matrix *hnr,gsl_vector *fundf, PARAM *params) {\n\n\tint i,j,add = rint((params->f0_frame_length/(double)params->shift/params->speed-1.0)*params->shift/params->speed/2.0);\n\tgsl_vector *frame = gsl_vector_alloc(rint(params->f0_frame_length/params->speed));\n\tgsl_vector *signal = gsl_vector_calloc(signal_v->size);\n\tgsl_vector_add(signal,signal_v);\n\tgsl_vector_add(signal,signal_uv);\n\n\t/* Zeropad signal */\n\tgsl_vector *signal_zp = gsl_vector_calloc(signal->size + 2*add);\n\tfor(i=0;i<signal->size;i++)\n\t\tgsl_vector_set(signal_zp,i+add,gsl_vector_get(signal,i));\n\n\t/* Window and calculate glottal flow spectrum */\n\tfor(i=0;i<hnr->size1;i++) {\n\t\tfor(j=rint(i*params->shift/params->speed);j<GSL_MIN(rint(i*params->shift/params->speed+params->f0_frame_length/params->speed),signal_zp->size-1);j++) {\n\t\t\tgsl_vector_set(frame,GSL_MIN(j-rint(i*params->shift/params->speed),frame->size-1),gsl_vector_get(signal_zp,j));\n\t\t}\n\t\tUpper_lower_envelope(frame, hnr, gsl_vector_get(fundf,i), i, params);\n\t}\n\tgsl_vector_free(frame);\n\tgsl_vector_free(signal_zp);\n\tgsl_vector_free(signal);\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n/**\n * Function Phase_manipulation\n *\n * Modify the phase and magnitude of the pulse to create noise.\n * The modified pulse is saved inplace to pulse.\n *\n * @param pulse original pulse\n * @param hnr HNR matrix\n * @param harmonics harmonic magnitudes\n * @param index current frame index\n * @param params parameter structure\n */\nvoid Phase_manipulation(gsl_vector *pulse, gsl_matrix *hnr, gsl_matrix *harmonics, int index, PARAM *params) {\n\n\t/* Initialize */\n\tint i,n = pulse->size;\n\tdouble data[n];\n\n\t/* Set pulse data to array \"data\" */\n\tfor(i=0;i<n;i++)\n\t\tdata[i] = gsl_vector_get(pulse,i);\n\n\t/* FFT */\n\tgsl_fft_real_wavetable *wreal = gsl_fft_real_wavetable_alloc(n);\n\tgsl_fft_real_workspace *work = gsl_fft_real_workspace_alloc(n);\n\tgsl_fft_real_transform(data,1,n,wreal,work);\n\tgsl_fft_real_wavetable_free(wreal);\n\n\t/* Extract real and imaginary parts to vectors */\n\tdouble x[2*n];\n\tgsl_complex_packed_array complex_coefficients = x;\n\tgsl_vector *real = gsl_vector_alloc(n);\n\tgsl_vector *imag = gsl_vector_alloc(n);\n\tgsl_fft_halfcomplex_unpack(data,complex_coefficients,1,n);\n\tfor(i=0;i<n;i++) {\n\t\tgsl_vector_set(real,i,REAL(complex_coefficients,i));\n\t\tgsl_vector_set(imag,i,IMAG(complex_coefficients,i));\n\t}\n\n\t/* Get HNR values in ERB scale to vector, convert to Hz scale */\n\tgsl_vector *hnr_values_erb = gsl_vector_alloc(params->hnr_channels);\n\tgsl_vector *hnr_values = gsl_vector_alloc(ceil((imag->size-1)/2.0));\n\tfor(i=0;i<params->hnr_channels;i++)\n\t\tgsl_vector_set(hnr_values_erb,i,gsl_matrix_get(hnr,index,i));\n\tConvert_ERB2Hz(hnr_values_erb,hnr_values,params);\n\n\t/* Noise power equals to pulse power minus the difference between harmonics and noise (indicated by HNR values) */\n\tgsl_vector *pulse_power = gsl_vector_alloc(hnr_values->size);\n\tfor(i=0;i<hnr_values->size;i++)\n\t\tgsl_vector_set(pulse_power, i, 20*log10(sqrt(pow(gsl_vector_get(real,i+1), 2) + pow(gsl_vector_get(imag,i+1), 2))));\n\tMA(pulse_power,11);\n\tfor(i=0;i<hnr_values->size;i++)\n\t\tgsl_vector_set(hnr_values, i, gsl_vector_get(hnr_values,i) + gsl_vector_get(pulse_power,i));\n\tgsl_vector_free(hnr_values_erb);\n\tgsl_vector_free(pulse_power);\n\n\t/* Convert HNR values from logarithmic scale to linear scale (actual noise amplitudes) */\n\tfor(i=0;i<hnr_values->size;i++)\n\t\tgsl_vector_set(hnr_values,i,pow(10,(gsl_vector_get(hnr_values,i)/20.0)));\n\n\t/* Modification of the amplitudes of the harmonics */\n\tif(params->use_harmonic_modification != 0) {\n\n\t\t/* Extract radius and phase */\n\t\tgsl_vector *radius = gsl_vector_alloc(imag->size);\n\t\tgsl_vector *phase = gsl_vector_alloc(imag->size);\n\t\tfor(i=0;i<radius->size;i++)\n\t\t\tgsl_vector_set(radius,i,sqrt(pow(gsl_vector_get(real,i),2) + pow(gsl_vector_get(imag,i),2)));\n\t\tfor(i=0;i<phase->size;i++)\n\t\t\tgsl_vector_set(phase,i,atan2(gsl_vector_get(imag,i),gsl_vector_get(real,i)));\n\n\t\t/* Get pulse magnitude */\n\t\tgsl_vector *magnitude = gsl_vector_alloc(radius->size);\n\t\tfor(i=0;i<magnitude->size;i++)\n\t\t\tgsl_vector_set(magnitude,i,20*log10(gsl_vector_get(radius,i)));\n\n\t\t/* Modify harmonics, use harmonics or modify by rule */\n\t\tif(params->use_harmonics == 1) { /* Use harmonics */\n\n\t\t\t/* Get harmonic log-magnitudes from matrix \"harmonics\" */\n\t\t\tgsl_vector *rnew = gsl_vector_alloc(params->number_of_harmonics+1);\n\t\t\tgsl_vector_set(rnew,0,20*log10(gsl_vector_get(radius,1)));\n\t\t\tfor(i=0;i<params->number_of_harmonics;i++)\n\t\t\t\tgsl_vector_set(rnew,i+1,gsl_matrix_get(harmonics,index,i) + gsl_vector_get(rnew,0));\n\n\t\t\t/* Modify pulse magnitude */\n\t\t\tdouble diff_mag = gsl_vector_get(rnew,params->number_of_harmonics)-20.0*log10(gsl_vector_get(radius,params->number_of_harmonics+1));\n\t\t\tfor(i=0;i<params->number_of_harmonics+1;i++)\n\t\t\t\tgsl_vector_set(magnitude,i+1,gsl_vector_get(rnew,i));\n\t\t\tfor(i=params->number_of_harmonics+2;i<magnitude->size;i++)\n\t\t\t\tgsl_vector_set(magnitude,i,gsl_vector_get(magnitude,i)+diff_mag);\n\n\t\t\t/* Free memory */\n\t\t\tgsl_vector_free(rnew);\n\n\t\t} else if(params->pulse_tilt_decrease_coeff < 1) { /* Decrease spectral tilt by rule */\n\n\t\t\t/* Modify magnitude */\n\t\t\tdouble m0 = gsl_vector_get(magnitude,0);\n\t\t\tfor(i=0;i<magnitude->size;i++)\n\t\t\t\tgsl_vector_set(magnitude,i,m0 + params->pulse_tilt_decrease_coeff*(gsl_vector_get(magnitude,i)-m0));\n\t\t}\n\n\t\t/* Set log-magnitude back to magnitude */\n\t\tfor(i=0;i<radius->size;i++)\n\t\t\tgsl_vector_set(radius,i,pow(10,gsl_vector_get(magnitude,i)/20.0));\n\n\t\t/* Reconstruct imag and real */\n\t\tfor(i=1;i<imag->size;i++) {\n\t\t\tgsl_vector_set(real,i,gsl_vector_get(radius,i)*cos(gsl_vector_get(phase,i)));\n\t\t\tgsl_vector_set(imag,i,gsl_vector_get(radius,i)*sin(gsl_vector_get(phase,i)));\n\t\t}\n\n\t\t/* Free memory */\n\t\tgsl_vector_free(radius);\n\t\tgsl_vector_free(phase);\n\t\tgsl_vector_free(magnitude);\n\t}\n\n\t/* Change noise low frequency limit from Hz to relative to FS */\n\tdouble noise_low_freq_limit_rel = params->noise_low_freq_limit/params->FS*2;\n\n\t/* Add noise by modifying both the magnitude and the phase of the spectrum of the pulse */\n\tfor(i=rint(noise_low_freq_limit_rel*hnr_values->size);i<hnr_values->size;i++) {\n\t\tgsl_vector_set(imag,i+1,gsl_vector_get(imag,i+1) + params->noise_gain_voiced*RAND()*gsl_vector_get(hnr_values,i));\n\t\tgsl_vector_set(real,i+1,gsl_vector_get(real,i+1) + params->noise_gain_voiced*RAND()*gsl_vector_get(hnr_values,i));\n\t}\n\n\t/* Copy the noise to the folded spectrum as well */\n\tif(imag->size%2 == 0) {\n\t\tfor(i=0;i<hnr_values->size;i++) {\n\t\t\tgsl_vector_set(imag,hnr_values->size+i,-gsl_vector_get(imag,hnr_values->size-i));\n\t\t\tgsl_vector_set(real,hnr_values->size+i,gsl_vector_get(real,hnr_values->size-i));\n\t\t}\n\t} else {\n\t\tfor(i=0;i<hnr_values->size;i++) {\n\t\t\tgsl_vector_set(imag,hnr_values->size+1+i,-gsl_vector_get(imag,hnr_values->size-i));\n\t\t\tgsl_vector_set(real,hnr_values->size+1+i,gsl_vector_get(real,hnr_values->size-i));\n\t\t}\n\t}\n\n\t/* Create halfcomplex data */\n\tdata[0] = gsl_vector_get(real,0);\n\tfor(i=1;i<n;i++) {\n\t\tif(i%2 == 1)\n\t\t\tdata[i] = gsl_vector_get(real,(i+1)/2);\n\t\telse\n\t\t\tdata[i] = gsl_vector_get(imag,i/2);\n\t}\n\n\t/* Inverse FFT */\n\tgsl_fft_halfcomplex_wavetable *whc = gsl_fft_halfcomplex_wavetable_alloc(n);\n\tgsl_fft_halfcomplex_inverse(data,1,n,whc,work);\n\tgsl_fft_halfcomplex_wavetable_free(whc);\n\tgsl_fft_real_workspace_free(work);\n\n\t/* Set data from array \"data\" to vector \"pulse\" */\n\tfor(i=0;i<n;i++)\n\t\tgsl_vector_set(pulse,i,data[i]);\n\n\t/* Free memory */\n\tgsl_vector_free(real);\n\tgsl_vector_free(imag);\n\tgsl_vector_free(hnr_values);\n}\n\n\n\n\n\n\n\n\n\n/**\n * Function Highpassfilter_fft\n *\n */\nvoid Highpassfilter_fft(gsl_vector *signal) {\n\n\t/* Initialize */\n\tint i,n = signal->size;\n\tdouble data[n];\n\n\t/* Set signal to array \"data\" */\n\tfor(i=0;i<n;i++)\n\t\tdata[i] = gsl_vector_get(signal,i);\n\n\t/* FFT */\n\tgsl_fft_real_wavetable *wreal = gsl_fft_real_wavetable_alloc(n);\n\tgsl_fft_real_workspace *work = gsl_fft_real_workspace_alloc(n);\n\tgsl_fft_real_transform(data,1,n,wreal,work);\n\tgsl_fft_real_wavetable_free(wreal);\n\n\t/* Extract real and imaginary parts to vectors */\n\tdouble x[2*n];\n\tgsl_complex_packed_array complex_coefficients = x;\n\tgsl_vector *real = gsl_vector_alloc(n);\n\tgsl_vector *imag = gsl_vector_alloc(n);\n\tgsl_fft_halfcomplex_unpack(data,complex_coefficients,1,n);\n\tfor(i=0;i<n;i++) {\n\t\tgsl_vector_set(real,i,REAL(complex_coefficients,i));\n\t\tgsl_vector_set(imag,i,IMAG(complex_coefficients,i));\n\t}\n\n\t/* Extract radius and phase */\n\tgsl_vector *radius = gsl_vector_alloc(imag->size);\n\tgsl_vector *phase = gsl_vector_alloc(imag->size);\n\tfor(i=0;i<radius->size;i++)\n\t\tgsl_vector_set(radius,i,sqrt(pow(gsl_vector_get(real,i),2) + pow(gsl_vector_get(imag,i),2)));\n\tfor(i=0;i<phase->size;i++)\n\t\tgsl_vector_set(phase,i,atan2(gsl_vector_get(imag,i),gsl_vector_get(real,i)));\n\n\t/* Modify radius for high-pass filtering: Remove first half of the spectrum */\n\tint Nrem = rint(radius->size/4);\n\tfor(i=0;i<Nrem;i++) {\n\t\tgsl_vector_set(radius,i+1,0);\n\t\tgsl_vector_set(radius,radius->size-1-i,0);\n\t}\n\n\t/* Reconstruct imag and real */\n\tfor(i=1;i<imag->size;i++) {\n\t\tgsl_vector_set(real,i,gsl_vector_get(radius,i)*cos(gsl_vector_get(phase,i)));\n\t\tgsl_vector_set(imag,i,gsl_vector_get(radius,i)*sin(gsl_vector_get(phase,i)));\n\t}\n\tgsl_vector_set(imag,0,0);\n\tgsl_vector_set(real,0,0);\n\n\t/* Create halfcomplex data */\n\tdata[0] = gsl_vector_get(real,0);\n\tfor(i=1;i<n;i++) {\n\t\tif(i%2 == 1)\n\t\t\tdata[i] = gsl_vector_get(real,(i+1)/2);\n\t\telse\n\t\t\tdata[i] = gsl_vector_get(imag,i/2);\n\t}\n\n\t/* Inverse FFT */\n\tgsl_fft_halfcomplex_wavetable *whc = gsl_fft_halfcomplex_wavetable_alloc(n);\n\tgsl_fft_halfcomplex_inverse(data,1,n,whc,work);\n\tgsl_fft_halfcomplex_wavetable_free(whc);\n\tgsl_fft_real_workspace_free(work);\n\n\t/* Set data from array \"data\" to vector \"signal\" */\n\tfor(i=0;i<n;i++)\n\t\tgsl_vector_set(signal,i,data[i]);\n\n\t/* Free memory */\n\tgsl_vector_free(radius);\n\tgsl_vector_free(phase);\n\tgsl_vector_free(real);\n\tgsl_vector_free(imag);\n}\n\n\n\n\n\n/**\n * Function Highpassfilter_fir\n *\n */\nvoid Highpassfilter_fir(gsl_vector *signal, gsl_vector *coeffs) {\n\n\t/* Initialize */\n\tint i,j,n = coeffs->size;\n\tdouble sum;\n\tgsl_vector *temp = gsl_vector_calloc(signal->size+round(coeffs->size/2.0)-1);\n\tgsl_vector *signal_temp = gsl_vector_calloc(signal->size+round(coeffs->size/2.0)-1);\n\tfor(i=0;i<signal->size;i++)\n\t\tgsl_vector_set(signal_temp,i,gsl_vector_get(signal,i));\n\n\t/* Filter signal */\n\tfor(i=0; i<signal_temp->size; i++) {\n\t\tsum = 0;\n\t\tfor(j=0; j<=GSL_MIN(i, n-1); j++)\n\t\t\tsum += gsl_vector_get(signal_temp,i-j)*gsl_vector_get(coeffs,j);\n\t\tgsl_vector_set(temp, i, sum);\n\t}\n\n\t/* Copy \"temp\" samples to \"signal\" */\n\tfor(i=0; i<signal->size; i++)\n\t\tgsl_vector_set(signal, i, gsl_vector_get(temp, i+coeffs->size/2));\n\n\t/* Free memory */\n\tgsl_vector_free(temp);\n\tgsl_vector_free(signal_temp);\n}\n\n\n\n\n\n\n/**\n * Function Convert_ERB2Hz\n *\n * Convert vector scale from ERB to Hz\n *\n * @param vector_erb pointer to vector of ERB-scale HNR values\n * @param vector pointer to reconstructed HNR vector\n *\n */\nvoid Convert_ERB2Hz(gsl_vector *vector_erb, gsl_vector *vector, PARAM *params) {\n\n\tint i,j,hnr_channels = vector_erb->size;\n\tgsl_vector *erb = gsl_vector_alloc(vector->size);\n\n\t/* Evaluate ERB scale indices for vector */\n\tfor(i=0;i<vector->size;i++)\n\t\tgsl_vector_set(erb,i,log10(0.00437*(i/(vector->size-1.0)*(params->FS/2.0))+1.0)/log10(0.00437*(params->FS/2.0)+1.0)*(hnr_channels-SMALL_NUMBER));\n\n\t/* Evaluate values according to ERB rate, smooth */\n\tfor(i=0;i<vector->size;i++) {\n\t\tj = floor(gsl_vector_get(erb,i));\n\t\tgsl_vector_set(vector,i,gsl_vector_get(vector_erb,j));\n\t}\n\tMA(vector,3);\n\n\t/* Free memory */\n\tgsl_vector_free(erb);\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n/**\n * Function Upper_lower_envelope\n *\n * Extract the amount of aperiodicity according to smoothed upper and lower spectral envelopes.\n *\n * @param frame pointer to frame\n * @param hnr pointer to matrix where the results are saved\n * @param f0 fundamental frequency\n * @param index time index\n *\n */\nvoid Upper_lower_envelope(gsl_vector *frame, gsl_matrix *hnr, double f0, int index, PARAM *params) {\n\n\t/* Define FFT length */\n\tint FFT_LENGTH = MIN_FFT_LENGTH;\n\twhile(FFT_LENGTH < frame->size)\n\t\tFFT_LENGTH = FFT_LENGTH*2;\n\n\t/* Variables */\n\tint i,j,guess_index = 0,h_values_size,harmonic_search_range;\n\tint hnr_channels = hnr->size2;\n\tdouble ind[MAX_HARMONICS] = {0};\n\tdouble guess_index_double = 0;\n\tdouble data[FFT_LENGTH];\n\tdouble h_values[MAX_HARMONICS] = {0};\n\tdouble n_values[MAX_HARMONICS] = {0};\n\tgsl_vector *fft = gsl_vector_alloc(FFT_LENGTH/2);\n\tgsl_vector *find;\n\n\t/* Initialize data */\n\tfor(i=0;i<FFT_LENGTH;i++)\n\t\tdata[i] = 0;\n\n\t/* FFT (with windowing) */\n\tfor (i=0; i<frame->size; i++)\n\t\tdata[i] = gsl_vector_get(frame, i)*HANN(i,frame->size);\n\tgsl_fft_real_radix2_transform(data, 1, FFT_LENGTH);\n\tfor(i=1; i<FFT_LENGTH/2; i++)\n\t\tgsl_vector_set(fft, i, 20*log10(sqrt(pow(data[i], 2) + pow(data[FFT_LENGTH-i], 2))));\n\tgsl_vector_set(fft, 0, 20*log10(abs(data[0])));\n\n\t/* Set (possible) infinity values to zero */\n\tfor(i=0;i<fft->size;i++) {\n\t\tif(!gsl_finite(gsl_vector_get(fft,i)))\n\t\t\tgsl_vector_set(fft,i,MIN_LOG_POWER);\n\t}\n\n\t/* Find the indices and magnitudes of the harmonic peaks */\n\ti = 0;\n\twhile(1) {\n\n\t\t/* Define harmonics search range, decreasing to the higher frequencies */\n\t\tharmonic_search_range = GSL_MAX(HARMONIC_SEARCH_COEFF*f0/(params->FS/(double)FFT_LENGTH)*((fft->size-1-guess_index)/(double)(fft->size-1)),1.0);\n\t\tfind = gsl_vector_alloc(harmonic_search_range);\n\n\t\t/* Estimate the index of the i_th harmonic\n\t\t * Use an iterative estimation based on earlier values */\n\t\tif(i > 0) {\n\t\t\tguess_index_double = 0;\n\t\t\tfor(j=0;j<i;j++)\n\t\t\t\tguess_index_double += ind[j]/(j+1.0)*(i+1.0);\n\t\t\tguess_index = (int)GSL_MAX(guess_index_double/j - (harmonic_search_range-1)/2.0,0);\n\t\t} else\n\t\t\tguess_index = (int)GSL_MAX(f0/(params->FS/(double)FFT_LENGTH) - (harmonic_search_range-1)/2.0,0);\n\n\t\t/* Stop search if the end of the fft vector or the maximum number of harmonics is reached */\n\t\tif(guess_index + rint(HNR_UNCERTAINTY_COEFF*FFT_LENGTH) > fft->size-1 || i > MAX_HARMONICS-1) {\n\t\t\tgsl_vector_free(find);\n\t\t\tbreak;\n\t\t}\n\n\t\t/* Find the maximum of the i_th harmonic */\n\t\tfor(j=0; j<harmonic_search_range; j++) {\n\t\t\tif(guess_index+j < fft->size)\n\t\t\t\tgsl_vector_set(find, j, gsl_vector_get(fft, guess_index+j));\n\t\t\telse\n\t\t\t\tgsl_vector_set(find, j, BIG_NEG_NUMBER);\n\t\t}\n\t\tind[i] = guess_index + gsl_vector_max_index(find);\n\t\th_values[i] = gsl_vector_get(fft, ind[i]);\n\t\tgsl_vector_free(find);\n\t\ti++;\n\t}\n\th_values_size = i;\n\n\t/* Estimate the level of interharmonic noise */\n\tdouble ind_n[MAX_HARMONICS] = {0};\n\tfor(i=0;i<h_values_size-1;i++) {\n\n\t\t/* Evaluate value exactly between the harmonics */\n\t\tind_n[i] = rint((ind[i]+ind[i+1])/2.0);\n\t\tn_values[i] = gsl_vector_get(fft,ind_n[i]);\n\t}\n\n\t/* Postfilter and iterpolate vectors */\n\tgsl_vector *hnr_est = gsl_vector_alloc(h_values_size-1);\n\tgsl_vector *hnr_est_erb = gsl_vector_calloc(hnr_channels);\n\tfor(i=0;i<hnr_est->size;i++)\n\t\tgsl_vector_set(hnr_est,i,n_values[i]-h_values[i]);\n\tMedFilt3(hnr_est);\n\tConvert_Hz2ERB(hnr_est, hnr_est_erb, params);\n\n\t/* Set values to hnr matrix */\n\tfor(i=0;i<hnr_channels;i++)\n\t\tgsl_matrix_set(hnr,index,i,gsl_vector_get(hnr_est_erb,i));\n\n\t/* Free memory */\n\tgsl_vector_free(fft);\n\tgsl_vector_free(hnr_est);\n\tgsl_vector_free(hnr_est_erb);\n}\n\n\n\n\n\n\n\n\n\n\n/**\n * Function Convert_Hz2ERB\n *\n * Convert vector scale from Hz to ERB\n *\n * @param vector pointer to original HNR vector\n * @param vector_erb pointer to vector of ERB-scale HNR values\n *\n */\nvoid Convert_Hz2ERB(gsl_vector *vector, gsl_vector *vector_erb, PARAM *params) {\n\n\tint i,j,hnr_channels = vector_erb->size;\n\tgsl_vector *erb = gsl_vector_alloc(vector->size);\n\tgsl_vector *erb_sum = gsl_vector_calloc(hnr_channels);\n\n\t/* Evaluate ERB scale indices for vector */\n\tfor(i=0;i<vector->size;i++)\n\t\tgsl_vector_set(erb,i,log10(0.00437*(i/(vector->size-1.0)*(params->FS/2.0))+1.0)/log10(0.00437*(params->FS/2.0)+1.0)*(hnr_channels-SMALL_NUMBER));\n\n\t/* Evaluate values according to ERB rate */\n\tfor(i=0;i<vector->size;i++) {\n\t\tj = floor(gsl_vector_get(erb,i));\n\t\tgsl_vector_set(vector_erb,j,gsl_vector_get(vector_erb,j)+gsl_vector_get(vector,i));\n\t\tgsl_vector_set(erb_sum,j,gsl_vector_get(erb_sum,j)+1);\n\t}\n\n\t/* Average values */\n\tfor(i=0;i<hnr_channels;i++)\n\t\t\tgsl_vector_set(vector_erb,i,gsl_vector_get(vector_erb,i)/gsl_vector_get(erb_sum,i));\n\n\t/* Prevent NaN-values (due to division by zero) */\n\tfor(i=0;i<hnr_channels;i++) {\n\t\tif(gsl_vector_get(erb_sum,i) == 0) {\n\t\t\tj = 1;\n\t\t\twhile(gsl_vector_get(erb_sum,i+j) == 0)\n\t\t\t\tj++;\n\t\t\tgsl_vector_set(vector_erb,i,0.5*gsl_vector_get(vector_erb,i-1)+0.5*gsl_vector_get(vector_erb,i+j));\n\t\t}\n\t}\n\n\t/* Free memory */\n\tgsl_vector_free(erb);\n\tgsl_vector_free(erb_sum);\n}\n\n\n\n\n\n\n\n\n\n/**\n * Function Create_pulse_train\n *\n * Reconstruct voice source in a frame\n *\n * @param ...\n */\ngsl_vector *Create_pulse_train(gsl_vector *pulse, gsl_vector *original_pulse, gsl_matrix *hnr, gsl_vector *fundf, gsl_matrix *harmonics, int frame_index, int sample_index, PARAM *params) {\n\n\t/* Initialize */\n\tint i,frame_index_new,sample_index_new,N,pulse_start,pulse_end;\n\tgsl_vector *pulsetrain = gsl_vector_calloc(params->f0_frame_length+pulse->size);\n\tgsl_vector *pulse_copy = gsl_vector_alloc(pulse->size);\n\tint ptlen = pulsetrain->size;\n\n\t/* Set first pulse to pulsetrain in the middle of the frame */\n\tgsl_vector_memcpy(pulse_copy,pulse);\n\tPhase_manipulation(pulse_copy,hnr,harmonics,frame_index,params);\n\tfor(i=0;i<pulse->size;i++)\n\t\tgsl_vector_set(pulsetrain,i+ptlen/2.0-pulse->size/2.0,gsl_vector_get(pulse_copy,i));\n\tgsl_vector_free(pulse_copy);\n\tpulse_start = ptlen/2.0-pulse->size/2.0+1;\n\tpulse_end = ptlen/2.0-pulse->size/2.0+i-1;\n\n\t/* Set earlier pulses to pulsetrain */\n\tframe_index_new = frame_index;\n\tsample_index_new = sample_index;\n\tN = pulse->size;\n\twhile(1) {\n\t\tsample_index_new = GSL_MAX(sample_index_new - N,0);\n\t\tframe_index_new = GSL_MIN(rint(params->n_frames*((sample_index_new+0.5*N)/(double)params->signal_length)),params->n_frames-1);\n\t\tN = rint(params->FS/gsl_vector_get(fundf,frame_index_new)/params->pitch);\n\t\tif(gsl_vector_get(fundf,frame_index_new)/params->pitch == 0) {\n\t\t\tN = params->shift/params->speed;\n\t\t\tpulse_start = pulse_start-N;\n\t\t\tif(pulse_start-N >= 0)\n\t\t\t\tcontinue;\n\t\t\telse\n\t\t\t\tbreak;\n\t\t}\n\t\tgsl_vector *pulse_new = gsl_vector_alloc(N);\n\t\tInterpolate(original_pulse,pulse_new);\n\t\tPhase_manipulation(pulse_new,hnr,harmonics,frame_index_new,params);\n\t\tfor(i=0;i<N;i++)\n\t\t\tgsl_vector_set(pulsetrain,GSL_MAX(pulse_start-N+i,0),gsl_vector_get(pulse_new,i));\n\t\tpulse_start = pulse_start-N+1;\n\t\tgsl_vector_free(pulse_new);\n\t\tif(pulse_start < 0)\n\t\t\tbreak;\n\t}\n\n\t/* Set later pulses to pulsetrain */\n\tframe_index_new = frame_index;\n\tsample_index_new = sample_index;\n\tN = pulse->size;\n\twhile(1) {\n\t\tsample_index_new = GSL_MIN(sample_index_new + N,params->signal_length-1);\n\t\tframe_index_new = GSL_MIN(rint(params->n_frames*((sample_index_new-0.5*N)/(double)params->signal_length)),params->n_frames-1);\n\t\tN = rint(params->FS/gsl_vector_get(fundf,frame_index_new)/params->pitch);\n\t\tif(gsl_vector_get(fundf,frame_index_new)/params->pitch == 0) {\n\t\t\tN = params->shift/params->speed;\n\t\t\tpulse_end = pulse_end+N;\n\t\t\tif(pulse_end+N < pulsetrain->size)\n\t\t\t\tcontinue;\n\t\t\telse\n\t\t\t\tbreak;\n\t\t}\n\t\tgsl_vector *pulse_new = gsl_vector_alloc(N);\n\t\tInterpolate(original_pulse,pulse_new);\n\t\tPhase_manipulation(pulse_new,hnr,harmonics,frame_index_new,params);\n\t\tfor(i=0;i<N;i++) {\n\t\t\tif(pulse_end+i > pulsetrain->size-1)\n\t\t\t\tbreak;\n\t\t\tgsl_vector_set(pulsetrain,pulse_end+i,gsl_vector_get(pulse_new,i));\n\t\t}\n\t\tpulse_end = pulse_end+N-1;\n\t\tgsl_vector_free(pulse_new);\n\t\tif(pulse_end > pulsetrain->size-1)\n\t\t\tbreak;\n\t}\n\t/* Return result */\n\treturn pulsetrain;\n}\n\n\n\n/**\n * Function Create_pulse_train_diff\n *\n * Reconstruct voice source in a frame (for differentiated two-pitch-period pulses)\n *\n * @param ...\n */\ngsl_vector *Create_pulse_train_diff(gsl_vector *pulse, gsl_vector *original_pulse, gsl_matrix *hnr, gsl_vector *fundf, gsl_matrix *harmonics, int frame_index, int sample_index, PARAM *params) {\n\n\t/* Initialize */\n\tint i,frame_index_new,sample_index_new,N,pulse_start,pulse_end;\n\tgsl_vector *pulsetrain = gsl_vector_calloc(params->f0_frame_length+round(pulse->size/2));\n\tgsl_vector *pulse_copy = gsl_vector_alloc(pulse->size);\n\tint ptlen = pulsetrain->size;\n\n\t/* Add noise to pulse copy */\n\tgsl_vector_memcpy(pulse_copy,pulse);\n\tIntegrate(pulse_copy,LEAK);\n\tPhase_manipulation(pulse_copy,hnr,harmonics,frame_index,params);\n\tDifferentiate(pulse_copy,LEAK);\n\tgsl_vector_set(pulse_copy,0,0);\n\n\t/* Set first pulse to pulsetrain in the middle of the frame */\n\tfor(i=0;i<GSL_MIN(pulse->size,ptlen);i++)\n\t\tgsl_vector_set(pulsetrain,GSL_MAX(i+ptlen/2.0-pulse->size/2.0,0),gsl_vector_get(pulse_copy,i));\n\tgsl_vector_free(pulse_copy);\n\tpulse_start = ptlen/2.0-pulse->size/2.0+1;\n\tpulse_end = ptlen/2.0-pulse->size/2.0+i-1;\n\n\t/* Set earlier pulses to pulsetrain */\n\tframe_index_new = frame_index;\n\tsample_index_new = sample_index;\n\tN = pulse->size;\n\twhile(1) {\n\t\tsample_index_new = GSL_MAX(sample_index_new - round(N/2),0);\n\t\tframe_index_new = GSL_MIN(rint(params->n_frames*((sample_index_new+0.25*N)/(double)params->signal_length)),params->n_frames-1);\n\t\tN = rint(2.0*params->FS/gsl_vector_get(fundf,frame_index_new)/params->pitch);\n\t\tif(gsl_vector_get(fundf,frame_index_new)/params->pitch == 0) {\n\t\t\tN = params->shift/params->speed;\n\t\t\tpulse_start = pulse_start-N;\n\t\t\tif(pulse_start-N >= 0)\n\t\t\t\tcontinue;\n\t\t\telse\n\t\t\t\tbreak;\n\t\t}\n\t\tgsl_vector *pulse_new = gsl_vector_alloc(N);\n\t\tInterpolate(original_pulse,pulse_new);\n\n\t\t/* Add noise */\n\t\tIntegrate(pulse_new, LEAK);\n\t\tPhase_manipulation(pulse_new,hnr,harmonics,frame_index_new,params);\n\t\tDifferentiate(pulse_new,LEAK);\n\t\tgsl_vector_set(pulse_new,0,0); // Fix DC error\n\n\t\t/* Set to excitation */\n\t\tfor(i=0;i<N;i++)\n\t\t\tgsl_vector_set(pulsetrain,GSL_MAX(pulse_start-round(N/2)+i,0),gsl_vector_get(pulsetrain,GSL_MAX(pulse_start-round(N/2)+i,0)) + gsl_vector_get(pulse_new,i));\n\t\tpulse_start = pulse_start-round(N/2+1);\n\t\tgsl_vector_free(pulse_new);\n\t\tif(pulse_start < 0)\n\t\t\tbreak;\n\t}\n\n\t/* Set later pulses to pulsetrain */\n\tframe_index_new = frame_index;\n\tsample_index_new = sample_index;\n\tN = pulse->size;\n\twhile(1) {\n\t\tsample_index_new = GSL_MIN(sample_index_new + round(N/2),params->signal_length-1);\n\t\tframe_index_new = GSL_MIN(rint(params->n_frames*((sample_index_new-0.25*N)/(double)params->signal_length)),params->n_frames-1);\n\t\tN = rint(2*params->FS/gsl_vector_get(fundf,frame_index_new)/params->pitch);\n\t\tif(gsl_vector_get(fundf,frame_index_new)/params->pitch == 0) {\n\t\t\tN = params->shift/params->speed;\n\t\t\tpulse_end = pulse_end+N;\n\t\t\tif(pulse_end+N < pulsetrain->size)\n\t\t\t\tcontinue;\n\t\t\telse\n\t\t\t\tbreak;\n\t\t}\n\t\tgsl_vector *pulse_new = gsl_vector_alloc(N);\n\t\tInterpolate(original_pulse,pulse_new);\n\n\t\t/* Add noise */\n\t\tIntegrate(pulse_new, LEAK);\n\t\tPhase_manipulation(pulse_new,hnr,harmonics,frame_index_new,params);\n\t\tDifferentiate(pulse_new,LEAK);\n\t\tgsl_vector_set(pulse_new,0,0); // Fix DC error\n\n\t\t/* Set to excitation */\n\t\tfor(i=0;i<N;i++) {\n\t\t\tif(pulse_end-round(N/2)+i > pulsetrain->size-1 || pulse_end-round(N/2)+i < 0)\n\t\t\t\tbreak;\n\t\t\tgsl_vector_set(pulsetrain,pulse_end-round(N/2)+i,gsl_vector_get(pulsetrain,pulse_end-round(N/2)+i) + gsl_vector_get(pulse_new,i));\n\t\t}\n\t\tpulse_end = pulse_end+round(N/2)-1;\n\t\tgsl_vector_free(pulse_new);\n\t\tif(pulse_end > pulsetrain->size-1)\n\t\t\tbreak;\n\t}\n\n\t/* Return result */\n\treturn pulsetrain;\n}\n\n\n\n\n\n\n\n\n/**\n * Function Analyse_pulse_train_spectrum\n *\n * Analyse LP spectrum of the pulse train\n *\n * @param ...\n */\nvoid Analyse_pulse_train_spectrum(gsl_vector *pulse_train, gsl_matrix *glflowsp_new, int N, int sample_index, int frame_index, PARAM *params) {\n\n\tint i;\n\tgsl_vector *a;\n\n\t/* Apply pre-emphasis */\n\tif(USE_PRE_EMPH == 1) {\n\t\tgsl_vector *e_pulse_train = gsl_vector_alloc(pulse_train->size);\n\t\tgsl_vector_set(e_pulse_train,0,gsl_vector_get(pulse_train,0));\n\t\tfor(i=1;i<pulse_train->size;i++)\n\t\t\tgsl_vector_set(e_pulse_train,i,gsl_vector_get(pulse_train,i) - 0.99*gsl_vector_get(pulse_train,i-1));\n\t\ta = WLPC(e_pulse_train, params->lpc_order_gl, params->lambda_gl);\n\t\tgsl_vector_free(e_pulse_train);\n\t} else {\n\t\ta = WLPC(pulse_train, params->lpc_order_gl, params->lambda_gl);\n\t}\n\n\t/* Set spectrum to matrix, fill in empty values */\n\tfor(i=frame_index;i<GSL_MIN(floor(params->n_frames*((sample_index+N)/(double)params->signal_length)),params->n_frames);i++)\n\t\tConvert_to_LSF(glflowsp_new,a,i);\n\n\t/* Free memory */\n\tgsl_vector_free(a);\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n/**\n * Function Mean\n *\n * Evaluate mean of a vector\n *\n * @param vector pointer to vector\n * @return mean\n *\n */\ndouble Mean(gsl_vector *vector) {\n\n\tint i;\n\tdouble mean = 0;\n\tfor(i=0; i<vector->size; i++) {\n\t\tmean += gsl_vector_get(vector, i);\n\t}\n\treturn (mean/(double)vector->size);\n}\n\n/**\n * Function NonZeroMean\n *\n * Evaluate mean of a vector from elements that are not zeros\n *\n * @param vector pointer to vector\n * @return mean\n *\n */\ndouble NonZeroMean(gsl_vector *vector) {\n\n\tint i,ind = 0;\n\tdouble mean = 0;\n\tfor(i=0; i<vector->size; i++) {\n\t\tif(gsl_vector_get(vector,i) != 0) {\n\t\t\tmean += gsl_vector_get(vector, i);\n\t\t\tind++;\n\t\t}\n\t}\n\treturn (mean/(double)ind);\n}\n\n\n\n\n\n\n\n\n/**\n * Function FillHNRValues\n *\n * Fill missing HNR values\n *\n * @param hnr HNR values\n * @param frame_index_old old index\n * @param frame_index current index\n */\nvoid FillHNRValues(gsl_matrix *hnr, int frame_index_old, int frame_index) {\n\n\tint i,j;\n\tfor(i=frame_index_old+1;i<frame_index;i++) {\n\t\tfor(j=0;j<hnr->size2;j++)\n\t\t\tgsl_matrix_set(hnr,i,j,gsl_matrix_get(hnr,frame_index,j));\n\t}\n}\n\n\n\n\n\n\n/**\n * Function FillUnvoicedSyntheticSourceSpectrum\n *\n * Fill current and previous source spectrum values\n *\n * @param glflowsp original spectrum\n * @param glflowsp_new new spectrum\n * @param frame_index_old old index\n * @param frame_index current index\n */\nvoid FillUnvoicedSyntheticSourceSpectrum(gsl_matrix *glflowsp, gsl_matrix *glflowsp_new, int frame_index, int frame_index_old) {\n\n\tif(glflowsp == NULL)\n\t\treturn;\n\n\t/* Set */\n\tint i,j;\n\tfor(i=0;i<glflowsp->size2;i++)\n\t\tgsl_matrix_set(glflowsp_new, frame_index, i, gsl_matrix_get(glflowsp, frame_index, i));\n\tfor(j=frame_index_old+1;j<frame_index;j++) {\n\t\tif(gsl_matrix_get(glflowsp_new,j,0) == 0) {\n\t\t\tfor(i=0;i<glflowsp->size2;i++)\n\t\t\t\tgsl_matrix_set(glflowsp_new, j, i, gsl_matrix_get(glflowsp, j, i));\n\t\t}\n\t}\n\n\t/* Double check */\n\tif(frame_index+1 < glflowsp_new->size1)\n\t\tfor(i=0;i<glflowsp_new->size2;i++)\n\t\t\tgsl_matrix_set(glflowsp_new, frame_index+1, i, gsl_matrix_get(glflowsp, frame_index+1, i));\n}\n\n\n\n/**\n * Function FillUnvoicedSyntheticSourceSpectrum_FLAT\n *\n * Fill current and previous source spectrum values\n *\n * @param glflowsp original spectrum\n * @param glflowsp_new new spectrum\n * @param frame_index_old old index\n * @param frame_index current index\n */\nvoid FillUnvoicedSyntheticSourceSpectrum_FLAT(gsl_matrix *glflowsp, gsl_matrix *glflowsp_new, int frame_index, int frame_index_old) {\n\n\tif(glflowsp == NULL)\n\t\treturn;\n\n\t/* Set */\n\tint i,j;\n\tfor(i=0;i<glflowsp->size2;i++)\n\t\tgsl_matrix_set(glflowsp_new, frame_index, i, (i+1.0)*(M_PI/glflowsp->size2));\n\tfor(j=frame_index_old+1;j<frame_index;j++) {\n\t\tif(gsl_matrix_get(glflowsp_new,j,0) == 0) {\n\t\t\tfor(i=0;i<glflowsp->size2;i++)\n\t\t\t\tgsl_matrix_set(glflowsp_new, j, i, (i+1.0)*(M_PI/glflowsp->size2));\n\t\t}\n\t}\n\n\t/* Double check */\n\tif(frame_index+1 < glflowsp_new->size1)\n\t\tfor(i=0;i<glflowsp_new->size2;i++)\n\t\t\tgsl_matrix_set(glflowsp_new, frame_index+1, i, gsl_matrix_get(glflowsp, frame_index+1, i));\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n/**\n * Function MedFilt5_matrix\n *\n * 5-point median filtering for matrices.\n * Filter along the first dimension.\n *\n * @param frame pointer to matrix to be filtered\n *\n */\nvoid MedFilt5_matrix(gsl_matrix *matrix) {\n\n\tint i,j;\n\tgsl_vector *temp = gsl_vector_alloc(matrix->size1);\n\tfor(i=0;i<matrix->size2;i++) {\n\t\tfor(j=0;j<matrix->size1;j++) {\n\t\t\tgsl_vector_set(temp,j,gsl_matrix_get(matrix,j,i));\n\t\t}\n\t\tMedFilt5(temp);\n\t\tfor(j=0;j<matrix->size1;j++) {\n\t\t\tgsl_matrix_set(matrix,j,i,gsl_vector_get(temp,j));\n\t\t}\n\t}\n\tgsl_vector_free(temp);\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n/**\n * Function Modify_harmonics\n *\n * Modification of the harmonic information for speech in the presence of noise\n *\n * @param harmonics pointer to harmonics matrix\n * @param fundf pointer to F0 vector\n *\n */\nvoid Modify_harmonics(gsl_matrix *harmonics, double scale) {\n\n\t/* Decrease the tilt of the spectrum */\n\tgsl_matrix_scale(harmonics, scale);\n\n}\n\n\n\n\n\n/**\n * Function Compression\n *\n * Dynamic range compression\n * Nonlinear power of k, 0<k<1, and linear response below threshold\n *\n * @param signal pointer to signal\n *\n */\nvoid Compression(gsl_vector *signal, double k) {\n\n\t/* Check validity */\n\tif(k >= 1 || k <= 0)\n\t\treturn;\n\n\t/* Dynamic range compression */\n\tdouble th = powf((1.0/k),(1.0/(k-1.0))); // Point where the derivative of the curve is one -> start nonlinearity after this threshold\n\tdouble a = powf(th,k) - th;              // The difference at the the turning point\n\tint i;\n\tfor(i=0;i<signal->size;i++) {\n\t\tif(gsl_vector_get(signal,i) < -th)\n\t\t\tgsl_vector_set(signal,i,-powf(-gsl_vector_get(signal,i),k) + a);\n\t\telse if(gsl_vector_get(signal,i) > th)\n\t\t\tgsl_vector_set(signal,i,powf(gsl_vector_get(signal,i),k) - a);\n\t}\n\n\t/* Scale maximum to one */\n\tdouble absmax = GSL_MAX(gsl_vector_max(signal),-gsl_vector_min(signal));\n\tfor(i=0;i<signal->size;i++)\n\t\tgsl_vector_set(signal,i,WAV_SCALE*gsl_vector_get(signal,i)/absmax);\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n/**\n * Function MedFilt5\n *\n * 5-point median filtering\n *\n * @param frame pointer to vector to be filtered\n *\n */\nvoid MedFilt5(gsl_vector *frame) {\n\n\tint i,j,n = 5;\n\tdouble temp1 = gsl_vector_get(frame, 0);\n\tdouble temp2 = gsl_vector_get(frame,1);\n\tdouble temp3;\n\tgsl_vector *samples = gsl_vector_alloc(n);\n\n\tfor(i=0; i<frame->size-(n-1); i++) {\n\t\tfor(j=0; j<n; j++) {\n\t\t\tgsl_vector_set(samples, j, gsl_vector_get(frame, i+j));\n\t\t}\n\t\tgsl_sort_vector(samples);\n\t\ttemp3 = gsl_vector_get(samples, 2);\n\t\tgsl_vector_set(frame, i, temp1);\n\t\ttemp1 = temp2;\n\t\ttemp2 = temp3;\n\t}\n\tgsl_vector_free(samples);\n}\n\n\n\n\n/**\n * Function MedFilt3\n *\n * 3-point median filtering\n *\n * @param frame pointer to vector to be filtered\n *\n */\nvoid MedFilt3(gsl_vector *frame) {\n\n\tint i,j,n;\n\tdouble temp1 = 0;\n\tdouble temp2 = gsl_vector_get(frame, 0);\n\tn = 3;\n\tgsl_vector *samples = gsl_vector_alloc(n);\n\n\tfor(i=0; i<frame->size-2; i++) {\n\t\tfor(j=0; j<n; j++) {\n\t\t\tgsl_vector_set(samples, j, gsl_vector_get(frame, i+j));\n\t\t}\n\t\tgsl_sort_vector(samples);\n\t\ttemp1 = gsl_vector_get(samples, 1);\n\t\tgsl_vector_set(frame, i, temp2);\n\t\ttemp2 = temp1;\n\t}\n\tgsl_vector_free(samples);\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n/**\n * Function Smooth_interp_lsf\n *\n * Smooth and interpolate LSF-matrix\n *\n\n * @param LSF_interp pointer to interpolated LSF-matrix\n * @param LSF original LSF-matrix\n * @param signal_len signal length\n * @param use_hmm HMM-switch\n * @param lsf_smooth_len smoothing length in samples\n *\n */\nvoid Smooth_interp_lsf(gsl_matrix *LSF_i, gsl_matrix *LSF, int signal_len, int use_hmm, int lsf_smooth_len) {\n\n\tint i,j;\n\tgsl_vector *temp = gsl_vector_alloc(LSF->size1);\n\tgsl_vector *temp_i = gsl_vector_alloc(signal_len);\n\n\tfor(i=0;i<LSF->size2;i++) {\n\t\tfor(j=0;j<LSF->size1;j++) {\n\t\t\tgsl_vector_set(temp,j,gsl_matrix_get(LSF,j,i));\n\t\t}\n\n\t\t/* Smooth vectors in time */\n\t\tif(use_hmm == 0)\n\t\t\tMA(temp,lsf_smooth_len);\n\n\t\t/* Interpolate vector */\n\t\tInterpolate(temp,temp_i);\n\n\t\t/* Set smoothed and interpolated LSFs to matrices */\n\t\tfor(j=0;j<signal_len;j++) {\n\t\t\tgsl_matrix_set(LSF_i,j,i,gsl_vector_get(temp_i,j));\n\t\t}\n\t}\n\n\t/* Free memory */\n\tgsl_vector_free(temp);\n\tgsl_vector_free(temp_i);\n}\n\n\n\n\n\n/**\n * Function Filter_excitation\n *\n * Filter excitation (normal/warped)\n *\n * @param excitation excitation\n * @param LSF lsf matrix\n * @param params\n *\n */\nvoid Filter_excitation(gsl_vector *excitation, gsl_matrix *LSF, PARAM *params) {\n\n\t/* Normal filtering */\n\tif(params->lambda_vt == 0) {\n\n\t\tint i,j;\n\t\tdouble sum;\n\n\t\tgsl_vector *A = gsl_vector_alloc(params->lpc_order_vt+1);\n\t\tfor(i=0;i<params->signal_length;i++) {\n\n\t\t\t/* Update filter coeffs: convert LSF to poly */\n\t\t\tif(i%params->filter_update_interval_vt == 0) {\n\t\t        lsf2poly(LSF,A,i,params->use_hmm);\n\t\t\t\tfor(j=0;j<params->lpc_order_vt+1;j++) {\n\t\t\t\t\tgsl_vector_set(A,j,gsl_vector_get(A,j)*(-1));\n\t\t\t\t}\n\t\t\t\tgsl_vector_set(A,0,1);\n\t\t\t}\n\n\t\t\t/* Filter */\n\t        sum = 0;\n\t        for(j=0;j<GSL_MIN(params->lpc_order_vt+1,i);j++) {\n\t        \tsum += gsl_vector_get(excitation,i-j)*gsl_vector_get(A,j);\n\t        }\n\t        gsl_vector_set(excitation,i,sum);\n\t\t}\n\t\tgsl_vector_free(A);\n\n\t/* Warped filtering */\n\t} else {\n\n\t\tint i,q,mlen;\n\t    long int o;\n\t    double xr,x,ffr,tmpr,Bb;\n\t    double *sigma;\n\t    long int len = params->signal_length;\n\t    int adim = 1;\n\t    int bdim = LSF->size2 + 1;\n\t    double *Ar = (double *)calloc(adim,sizeof(double));\n\t    double *Br = (double *)calloc(bdim,sizeof(double));\n\t    double *ynr = (double *)calloc(excitation->size,sizeof(double));\n\t    double *rsignal = (double *)calloc(excitation->size,sizeof(double));\n\t    double *rmem = (double *)calloc(GSL_MAX(adim,bdim)+2,sizeof(double));\n\t    gsl_vector *B = gsl_vector_alloc(bdim);\n\n\t    /* Set excitation to array */\n\t    for(i=0;i<len;i++) {\n\t\t\trsignal[i] = gsl_vector_get(excitation,i);\n\t\t}\n\n\t    /* Initialize */\n\t    Ar[0] = 1;\n\t    Bb = 0;\n\t    sigma = NFArray(bdim+2);\n\t    if(adim >= bdim)\n\t    \tmlen = adim;\n\t    else\n\t    \tmlen = bdim + 1;\n\n\t    /* Warped filtering */\n\t    for(o=0;o<len;o++) {\n\n\t    \t/* Update filter coefficients */\n\t    \tif(o%params->filter_update_interval_vt == 0) {\n\t    \t\tlsf2poly(LSF,B,o,params->use_hmm);\n\t    \t\tfor(i=0;i<bdim;i++) {\n\t    \t\t\tBr[i] = gsl_vector_get(B,i);\n\t    \t\t}\n\t    \t\talphas2sigmas(Br,sigma,params->lambda_vt,bdim-1);\n\t    \t\tBb = 1/Br[0];\n\t    \t}\n\n\t    \txr = rsignal[o]*Bb;\n\n\t    \t/* Update feedbackward sum */\n\t    \tfor(q=0;q<bdim;q++) {\n\t    \t\txr -= sigma[q]*rmem[q];\n\t    \t}\n\t    \txr = xr/sigma[bdim];\n\t    \tx = xr*Ar[0];\n\n\t    \t/* Update inner states */\n\t    \tfor(q=0;q<mlen;q++) {\n\t    \t\ttmpr = rmem[q] + params->lambda_vt*(rmem[q+1] - xr);\n\t    \t\trmem[q] = xr;\n\t    \t\txr = tmpr;\n\t    \t}\n\n\t    \t/* Update feedforward sum */\n\t    \tfor(q=0,ffr=0.0;q<adim-1;q++) {\n\t    \t\tffr += Ar[q+1]*rmem[q+1];\n\t    \t}\n\n\t       /* Update output */\n\t       ynr[o] = x + ffr;\n\t\t}\n\n\t    /* Set output to vector */\n\t    for(i=0;i<len;i++) {\n\t    \tgsl_vector_set(excitation,i,ynr[i]);\n\t    }\n\n\t    /* Free memory */\n\t\tfree(ynr);\n\t\tfree(rsignal);\n\t\tfree(Ar);\n\t\tfree(Br);\n\t\tfree(rmem);\n\t\tfree(sigma);\n\t\tgsl_vector_free(B);\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n/**\n * Function LipRadiation\n *\n * Lip radiation\n *\n * @param excitation_voiced excitation\n *\n */\nvoid LipRadiation(gsl_vector *excitation_voiced) {\n\n\tint i,j;\n\tdouble coeffs[2] = {1,-LIP_RADIATION};\n\tdouble sum;\n\tgsl_vector *temp = gsl_vector_alloc(excitation_voiced->size);\n\tgsl_vector_memcpy(temp, excitation_voiced);\n\n\tfor(i=0; i<excitation_voiced->size; i++) {\n\t\tsum = 0;\n\t\tfor(j=0; j<=GSL_MIN(i, 1); j++) {\n\t\t\tsum += gsl_vector_get(excitation_voiced, i-j)*coeffs[j];\n\t\t}\n\t\tgsl_vector_set(temp, i, sum);\n\t}\n\tfor(i=0; i<excitation_voiced->size; i++) {\n\t\tgsl_vector_set(excitation_voiced, i, gsl_vector_get(temp, i));\n\t}\n\tgsl_vector_free(temp);\n}\n\n\n\n\n/**\n * Function Differentiate\n *\n * Differentiate signal with leak\n *\n * @param signal signal to be differentiated\n * @param leak leaky parameter (e.g. 0.99)\n *\n */\nvoid Differentiate(gsl_vector *signal, double leak) {\n\n\tint i,j;\n\tdouble coeffs[2] = {1,-leak};\n\tdouble sum;\n\tgsl_vector *temp = gsl_vector_alloc(signal->size);\n\tgsl_vector_memcpy(temp, signal);\n\n\tfor(i=0; i<signal->size; i++) {\n\t\tsum = 0;\n\t\tfor(j=0; j<=GSL_MIN(i, 1); j++) {\n\t\t\tsum += gsl_vector_get(signal, i-j)*coeffs[j];\n\t\t}\n\t\tgsl_vector_set(temp, i, sum);\n\t}\n\tfor(i=0; i<signal->size; i++) {\n\t\tgsl_vector_set(signal, i, gsl_vector_get(temp, i));\n\t}\n\tgsl_vector_free(temp);\n}\n\n\n\n\n\n\n\n\n/**\n * Function Differentiate_noleak\n *\n * Differentiate signal (no leakage)\n *\n * @param signal signal to be differentiated\n *\n */\nvoid Differentiate_noleak(gsl_vector *signal) {\n\n\tint i,j;\n\tdouble coeffs[2] = {1,-1};\n\tdouble sum;\n\tgsl_vector *temp = gsl_vector_alloc(signal->size);\n\tgsl_vector_memcpy(temp, signal);\n\n\tfor(i=0; i<signal->size; i++) {\n\t\tsum = 0;\n\t\tfor(j=0; j<=GSL_MIN(i, 1); j++) {\n\t\t\tsum += gsl_vector_get(signal, i-j)*coeffs[j];\n\t\t}\n\t\tgsl_vector_set(temp, i, sum);\n\t}\n\tfor(i=0; i<signal->size; i++) {\n\t\tgsl_vector_set(signal, i, gsl_vector_get(temp, i));\n\t}\n\tgsl_vector_free(temp);\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n/**\n * Function Evaluate_new_gain\n *\n * Evaluate new gain for synthesis by comparing synthetic and original gains\n *\n * @param gain original gain\n * @param gain_new new gain\n * @param params\n */\nvoid Evaluate_new_gain(gsl_vector *signal, gsl_vector *gain_new, gsl_vector *gain, gsl_vector *fundf, PARAM *params) {\n\n\t/* Estimate the gain of the synthetic signal */\n\tGain_eval(signal,gain_new,fundf,params);\n\tMA_voiced(gain_new,fundf,params->norm_gain_smooth_v_len);\n\tMA_unvoiced(gain_new,fundf,params->norm_gain_smooth_uv_len);\n\n\t/* Evaluate new gain for synthesis by comparing synthetic and original gains */\n\tModify_gain(gain_new,gain);\n}\n\n\n\n\n/**\n * Function Gain_eval\n *\n * Evaluate gain of a signal\n *\n * @param signal input signal\n * @param gain gain vector\n * @param fundf F0 vector\n * @param params\n *\n */\nvoid Gain_eval(gsl_vector *signal, gsl_vector *gain, gsl_vector *fundf, PARAM *params) {\n\n\tint i,j;\n\tgsl_vector *frame = gsl_vector_alloc(rint(params->frame_length/params->speed));\n\tint add = rint((params->frame_length/(double)params->shift/params->speed-1.0)*params->shift/params->speed/2.0);\n\n\t/* Zeropad signal */\n\tgsl_vector *signal_zp = gsl_vector_calloc(signal->size + 2*add);\n\tfor(i=0;i<signal->size;i++)\n\t\tgsl_vector_set(signal_zp,i+add,gsl_vector_get(signal,i));\n\n\t/* Calculate gain vector */\n\tfor(i=0;i<gain->size;i++) {\n\t\tfor(j=rint(i*params->shift/params->speed);j<GSL_MIN(rint(i*params->shift/params->speed+params->frame_length/params->speed),signal_zp->size-1);j++) {\n\t\t\tgsl_vector_set(frame,GSL_MIN(j-rint(i*params->shift/params->speed),frame->size-1),gsl_vector_get(signal_zp,j));\n\t\t}\n\t\tif(gsl_vector_get(fundf,i) > 0)\n\t\t\tuvGain(frame,gain,i,NO_WINDOWING,rint(params->gain_voiced_frame_length/params->speed));\n\t\telse\n\t\t\tuvGain(frame,gain,i,NO_WINDOWING,rint(params->gain_unvoiced_frame_length/params->speed));\n\t}\n\tgsl_vector_free(frame);\n\tgsl_vector_free(signal_zp);\n}\n\n\n\n\n\n\n\n/**\n * Function Modify_gain\n *\n * Compare gain (gain) and synthetic gain (gain_new), and normalize the result inplace to gain_new\n *\n * @param gain_new synthetic gain\n * @param gain original gain\n *\n */\nvoid Modify_gain(gsl_vector *gain_new, gsl_vector *gain) {\n\n\tint i;\n\tfor(i=0;i<gain->size;i++) {\n\t\tgsl_vector_set(gain_new,i,gsl_vector_get(gain,i) + gsl_vector_get(gain,i) - gsl_vector_get(gain_new,i));\n\t}\n}\n\n\n\n\n/**\n * Function Noise_reduction\n *\n * Reduce noise by reducing the gain of low level parts of the signal\n *\n * @param gain vector\n * @param params\n */\nvoid Noise_reduction(gsl_vector *gain, PARAM *params) {\n\n\t/* Apply noise reduction */\n\tif(params->noise_reduction_synthesis == 1) {\n\t\tint i;\n\t\tfor(i=0;i<gain->size;i++)\n\t\t\tif(gsl_vector_get(gain,i) < params->noise_reduction_limit_db)\n\t\t\t\tgsl_vector_set(gain,i,gsl_vector_get(gain,i)-params->noise_reduction_db);\n\t}\n}\n\n\n/**\n * Function uvGain\n *\n * Calculate energy from potentially unvoiced frames (shorter window)\n *\n * @param frame pointer to the samples\n * @param gain vector for results\n * @param index time index\n * @param windowing switch for using windowing\n * @param unvoiced_frame_length\n */\nvoid uvGain(gsl_vector *frame, gsl_vector *gain, int index, int windowing, int unvoiced_frame_length) {\n\n\tint i,cntr;\n\tdouble sum;\n\tgsl_vector *uvframe = gsl_vector_alloc(unvoiced_frame_length);\n\n\t/* Take shorter frame for unvoiced analysis */\n\tcntr = rint((frame->size-unvoiced_frame_length)/2.0);\n\tfor(i=0;i<unvoiced_frame_length;i++)\n\t\tgsl_vector_set(uvframe,i,gsl_vector_get(frame,i+cntr));\n\n\t/* Windowing switch */\n\tif(windowing == 1) {\n\n\t\t/* Windowing */\n\t\tfor(i=0;i<uvframe->size;i++)\n\t\t\tgsl_vector_set(uvframe,i,gsl_vector_get(uvframe,i)*HANN(i,uvframe->size));\n\n\t\t/* Evaluate gain of uvframe, normalize energy per sample basis */\n\t\tsum = 0;\n\t\tfor(i=0;i<uvframe->size;i++) {\n\t\t\tsum = sum + gsl_vector_get(uvframe,i)*gsl_vector_get(uvframe,i);\n\t\t}\n\t\tgsl_vector_set(gain, index, 10.0*log10((8.0/3.0)*sum/E_REF/((double)(uvframe->size))));\n\n\t} else {\n\n\t\t/* Evaluate gain of frame, normalize energy per sample basis */\n\t\tsum = 0;\n\t\tfor(i=0;i<uvframe->size;i++) {\n\t\t\tsum = sum + gsl_vector_get(uvframe,i)*gsl_vector_get(uvframe,i);\n\t\t}\n\t\tgsl_vector_set(gain, index, 10.0*log10(sum/E_REF/((double)(uvframe->size))));\n\t}\n\n\t/* Ensure non-infinity values */\n\tif(isinf(gsl_vector_get(gain,index)) != 0)\n\t\tgsl_vector_set(gain,index,MIN_LOG_POWER);\n\n\t/* Free memory */\n\tgsl_vector_free(uvframe);\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n/**\n * Function Smooth_matrix\n *\n * Moving average smoothing for matrix parameters\n *\n * @param matrix matrix to smooth\n * @param len smoothing length in samples\n *\n */\nvoid Smooth_matrix(gsl_matrix *matrix, int len) {\n\n\tif(matrix == NULL)\n\t\treturn;\n\n\tint i,j;\n\tgsl_vector *temp = gsl_vector_alloc(matrix->size1);\n\tfor(i=0;i<matrix->size2;i++) {\n\t\tfor(j=0;j<matrix->size1;j++) {\n\t\t\tgsl_vector_set(temp,j,gsl_matrix_get(matrix,j,i));\n\t\t}\n\t\tMA(temp,len);\n\t\tfor(j=0;j<matrix->size1;j++) {\n\t\t\tgsl_matrix_set(matrix,j,i,gsl_vector_get(temp,j));\n\t\t}\n\t}\n\tgsl_vector_free(temp);\n}\n\n\n\n\n\n\n\n/**\n * Function Spectral_match\n *\n * Match the synthetic excitation spectrum to real one (normal/warped)\n *\n * @param signal excitation vector\n * @param flow original glottal flow spectrum\n * @param flow_new synthetic glottal flow spectrum\n * @param\n *\n */\nvoid Spectral_match(gsl_vector *signal, gsl_matrix *flow, gsl_matrix *flow_new, PARAM *params) {\n\n\t/* Do not perform if noise robust speech is used */\n\tif(params->noise_robust_speech == 1)\n\t\treturn;\n\n\t/* Normal filtering */\n\tif(params->lambda_gl == 0) {\n\n\t\tint i,j;\n\t\tdouble sum;\n\n\t\t/* Check compatibility */\n\t\tif(params->lpc_order_gl < MIN_P_TILT) {\n\t\t\tprintf(\"\\n\tWarning: The degree of spectral model is too low - spectral matching is not performed!\\n\\n\");\n\t\t\treturn;\n\t\t}\n\n\t\t/* Smooth and interpolate glottal flow spectra */\n\t\tgsl_matrix *flow_i = gsl_matrix_alloc(params->signal_length,params->lpc_order_gl);\n\t\tgsl_matrix *flow_new_i = gsl_matrix_alloc(params->signal_length,params->lpc_order_gl);\n\t\tSmooth_interp_lsf(flow_i,flow,params->signal_length,params->use_hmm,params->glflowsp_smooth_len);\n\t\tSmooth_interp_lsf(flow_new_i,flow_new,params->signal_length,0,params->glflowsp_smooth_len); // Smooth always flow_new\n\n\t\t/* Initialize spectral correction */\n\t\tgsl_vector *A = gsl_vector_alloc(params->lpc_order_gl+1);\n\t\tgsl_vector *B = gsl_vector_alloc(params->lpc_order_gl+1);\n\t\tgsl_vector *signal_orig = gsl_vector_alloc(params->signal_length);\n\t\tgsl_vector_memcpy(signal_orig, signal);\n\n\t\t/* Spectral correction */\n\t\tfor(i=0;i<params->signal_length;i++) {\n\n\t\t\t/* Update filter coeffs: convert LSF to poly */\n\t\t\tif(i%params->filter_update_interval_gl == 0) {\n\t\t        lsf2poly(flow_new_i,A,i,params->use_hmm);\n\t\t        lsf2poly(flow_i,B,i,params->use_hmm);\n\t\t\t\tgsl_vector_set(B,0,0);\n\t\t\t}\n\n\t\t\t/* Filter */\n\t    \tsum = 0;\n\t    \tfor(j=0;j<GSL_MIN(params->lpc_order_gl+1,i);j++) {\n\t    \t\tsum += gsl_vector_get(signal_orig,i-j)*gsl_vector_get(A,j) - gsl_vector_get(signal,i-j)*gsl_vector_get(B,j);\n\t    \t}\n\t    \tgsl_vector_set(signal,i,sum);\n\t\t}\n\n\t\t/* Free memory */\n\t\tgsl_matrix_free(flow_new_i);\n\t\tgsl_matrix_free(flow_i);\n\t\tgsl_vector_free(signal_orig);\n\t\tgsl_vector_free(A);\n\t\tgsl_vector_free(B);\n\n\n\t/* Warped filtering */\n\t} else {\n\n\t\t/* Check compatibility */\n\t\tif(params->lpc_order_gl+1 < MIN_P_TILT-1) {\n\t\t\tprintf(\"\\n  Warning: The degree of spectral model is too low - spectral matching is not performed!\\n\\n\");\n\t\t\treturn;\n\t\t}\n\n\t\tint i,q,mlen;\n\t    long int o;\n\t    double xr,x,ffr,tmpr,Bb;\n\t    double *sigma;\n\t    long int len = params->signal_length;\n\t    int adim = params->lpc_order_gl + 1;\n\t    int bdim = params->lpc_order_gl + 1;\n\t    double *Ar = (double *)calloc(adim,sizeof(double));\n\t    double *Br = (double *)calloc(bdim,sizeof(double));\n\t    double *ynr = (double *)calloc(len,sizeof(double));\n\t    double *rsignal = (double *)calloc(len,sizeof(double));\n\t    double *rmem = (double *)calloc((bdim+2),sizeof(double));\n\t    gsl_vector *A = gsl_vector_alloc(adim);\n\t    gsl_vector *B = gsl_vector_alloc(bdim);\n\n\t\t/* Smooth and interpolate glottal flow spectrums */\n\t\tgsl_matrix *flow_i = gsl_matrix_alloc(params->signal_length,params->lpc_order_gl);\n\t\tgsl_matrix *flow_new_i = gsl_matrix_alloc(params->signal_length,params->lpc_order_gl);\n\t\tSmooth_interp_lsf(flow_i,flow,len,params->use_hmm,params->glflowsp_smooth_len);\n\t\tSmooth_interp_lsf(flow_new_i,flow_new,len,0,params->glflowsp_smooth_len); // Smooth always flow_new\n\n\t    /* Set signal to array */\n\t    for(i=0;i<len;i++) {\n\t\t\trsignal[i] = gsl_vector_get(signal,i);\n\t\t}\n\n\t    /* Initialize */\n\t    sigma = NFArray(bdim+2);\n\t    Bb = 0;\n\t    if(adim >= bdim)\n\t    \tmlen = adim;\n\t    else\n\t    \tmlen = bdim + 1;\n\n\t    /* Warped filtering */\n\t    for(o=0;o<len;o++) {\n\n\t    \t/* Update filter coefficients */\n\t    \tif(o%params->filter_update_interval_gl == 0) {\n\t    \t\tlsf2poly(flow_new_i,A,o,params->use_hmm);\n\t    \t\tlsf2poly(flow_i,B,o,params->use_hmm);\n\t    \t\tfor(i=0;i<adim;i++) {\n\t    \t\t\tAr[i] = gsl_vector_get(A,i);\n\t    \t\t}\n\t    \t\tfor(i=0;i<bdim;i++) {\n\t    \t\t\tBr[i] = gsl_vector_get(B,i);\n\t    \t\t}\n\t    \t\talphas2sigmas(Br,sigma,params->lambda_gl,bdim-1);\n\t    \t\tBb = 1/Br[0];\n\t    \t}\n\n\t    \txr = rsignal[o]*Bb;\n\n\t    \t/* Update feedbackward sum */\n\t    \tfor(q=0;q<bdim;q++) {\n\t    \t\txr -= sigma[q]*rmem[q];\n\t    \t}\n\t    \txr = xr/sigma[bdim];\n\t    \tx = xr*Ar[0];\n\n\t    \t/* Update inner states */\n\t    \tfor(q=0;q<mlen;q++) {\n\t    \t\ttmpr = rmem[q] + params->lambda_gl*(rmem[q+1] - xr);\n\t    \t\trmem[q] = xr;\n\t    \t\txr = tmpr;\n\t    \t}\n\n\t    \t/* Update feedforward sum */\n\t    \tfor(q=0,ffr=0.0;q<adim-1;q++) {\n\t    \t\tffr += Ar[q+1]*rmem[q+1];\n\t    \t}\n\n\t       /* Update output */\n\t       ynr[o] = x + ffr;\n\t\t}\n\n\t    /* Set output to vector */\n\t    for(i=0;i<len;i++) {\n\t    \tgsl_vector_set(signal,i,ynr[i]);\n\t    }\n\n\t    /* Free memory */\n\t\tfree(ynr);\n\t\tfree(rsignal);\n\t\tfree(Ar);\n\t\tfree(Br);\n\t\tfree(rmem);\n\t\tfree(sigma);\n\t\tgsl_matrix_free(flow_i);\n\t\tgsl_matrix_free(flow_new_i);\n\t\tgsl_vector_free(A);\n\t\tgsl_vector_free(B);\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n/**\n * Function alphas2sigmas\n *\n * Convert alhas to sigmas.\n *\n * @param alp alphas\n * @param sigm sigmas\n * @param lambda warping coefficient\n * @param dim dimension\n *\n */\nvoid alphas2sigmas(double *alp, double *sigm, double lambda, int dim) {\n\n\tint q;\n\tdouble S=0,Sp;\n\n\tsigm[dim] = lambda*alp[dim]/alp[0];\n\tSp = alp[dim]/alp[0];\n\tfor(q=dim;q>1;q--) {\n\t\tS = alp[q-1]/alp[0] - lambda*Sp;\n\t\tsigm[q-1] = lambda*S + Sp;\n\t\tSp = S;\n\t}\n\tsigm[0] = S;\n\tsigm[dim+1] = 1 - lambda*S;\n}\n\n\n/**\n * Function NFArray\n *\n * Create array.\n *\n * @param size\n * @return array\n *\n */\ndouble *NFArray(int size) {\n\n\tdouble *p;\n\tp = (double *)calloc(sizeof(*p),size);\n\treturn p;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n/**\n * Function Scale_signal\n *\n * Scale signal if maximum value is greater than 1.0\n *\n * @param signal\n */\nvoid Scale_signal(gsl_vector *signal, int mode) {\n\n\t/* Evaluate the absolute maximum of the signal */\n\tint i;\n\tdouble absmax = GSL_MAX(gsl_vector_max(signal),-gsl_vector_min(signal));\n\n\t/* Scale maximum to one if absmax is greater than one */\n\tif(mode == SCALE_IF_GREATER_THAN_ONE && absmax > 1.0) {\n\t\tprintf(\"\t\tMaximum value of the signal (%1.3lf) is greater than 1.0. Signal values rescaled!\\n\",absmax);\n\t\tabsmax = WAV_SCALE/absmax;\n\t\tfor(i=0;i<signal->size;i++)\n\t\t\tgsl_vector_set(signal,i,gsl_vector_get(signal,i)*absmax);\n\t}\n\n\t/* Scale absmax of signal to one */\n\tif(mode == FORCE_MAX_TO_ONE) {\n\t\tabsmax = WAV_SCALE/absmax;\n\t\tfor(i=0;i<signal->size;i++)\n\t\t\tgsl_vector_set(signal,i,gsl_vector_get(signal,i)*absmax);\n\t}\n}\n\n\n\n\n\n/**\n * Function Save_signal_to_file\n *\n * Save signal to file\n *\n * @param signal\n * @param params\n */\nint Save_signal_to_file(gsl_vector *signal, PARAM *params, char *alternative_filename_ending) {\n\n\t/* Copy values to array */\n\tdouble *samples = (double *)calloc(params->signal_length, sizeof(double));\n\tint i;\n\tfor(i=0;i<params->signal_length;i++)\n\t\tsamples[i] = gsl_vector_get(signal,i);\n\n\t/* Save synthesized speech to wav-file */\n\tSNDFILE *soundfile;\n\tSF_INFO sfinfo;\n\tsfinfo.samplerate = params->FS;\n\tsfinfo.channels = 1;\n\tsfinfo.format = SF_FORMAT_WAV | SF_FORMAT_PCM_16;\n\tchar temp[DEF_STRING_LEN];\n\tstrcpy(temp, params->synlist[params->synfilenumber]);\n\n\t/* Open file with default ending or givend ending */\n\tif(alternative_filename_ending == NULL)\n\t\tsoundfile = sf_open(strcat(temp,FILENAME_ENDING_SYNTHESIS), SFM_WRITE, &sfinfo);\n\telse\n\t\tsoundfile = sf_open(strcat(temp,alternative_filename_ending), SFM_WRITE, &sfinfo);\n\n\t/* Check if success */\n\tif(soundfile==NULL) {\n\t\tprintf(\"\\n\\nError creating file \\\"%s\\\": %s\\n\\n\",temp,strerror(errno));\n\t\treturn EXIT_FAILURE;\n\t}\n\n\t/* Write to file */\n\tsf_write_double(soundfile, samples, params->signal_length);\n\n\t/* Free memory */\n\tfree(samples);\n\tsf_close(soundfile);\n\n\treturn EXIT_SUCCESS;\n}\n\n\n\n\n\n\n\n\n/**\n * Function WLPC\n *\n * Calculate Warped Linear Prediction (WLP) coefficients using\n * autocorrelation method.\n *\n * @param frame pointer to the samples\n * @param a pointer to coefficiets\n * @param p LPC degree\n * @param lambda warping coefficient\n * @return pointer to the WLP-coefficients\n */\ngsl_vector *WLPC(gsl_vector *frame, int p, double lambda) {\n\n\tint i,j,s;\n\tdouble win = 0;\n\tgsl_vector *a = gsl_vector_alloc(p+1);\n\tgsl_vector *wframe = gsl_vector_alloc(frame->size);\n\tgsl_vector *a_temp = gsl_vector_calloc(p);\n\tgsl_vector *r = gsl_vector_calloc(p+1);\n\tgsl_vector *b = gsl_vector_alloc(p);\n\tgsl_matrix *R = gsl_matrix_alloc (p, p);\n\tgsl_permutation *perm = gsl_permutation_alloc(p);\n\n\t/* Windowing (choose window) */\n\tfor(i=0; i<frame->size; i++) {\n\t\tif (WIN_TYPE == HANN_WIN) win = HANN(i,frame->size);\n\t\telse if (WIN_TYPE == BLACKMAN_WIN) win = BLACKMAN(i,frame->size);\n\t\telse if (WIN_TYPE == HAMMING_WIN) win = HAMMING(i,frame->size);\n\t\telse win = 1.0;\n\t\tgsl_vector_set(wframe, i, gsl_vector_get(frame, i)*win);\n\t}\n\n\t/* Copy warped frame */\n\tgsl_vector *wframe_w = gsl_vector_alloc(wframe->size);\n\tgsl_vector_memcpy(wframe_w,wframe);\n\n\t/* Set r(0) */\n\tfor(i=0;i<wframe->size;i++) {\n\t\tgsl_vector_set(r, 0, gsl_vector_get(r,0) + gsl_vector_get(wframe,i)*gsl_vector_get(wframe,i));\n\t}\n\n\t/* Evaluate r */\n\tfor(i=1;i<p+1;i++) {\n\t\tAllPassDelay(wframe_w,lambda);\n\t\tfor(j=0;j<wframe->size;j++) {\n\t\t\tgsl_vector_set(r, i, gsl_vector_get(r,i) + gsl_vector_get(wframe,j)*gsl_vector_get(wframe_w,j));\n\t\t}\n\t}\n\n\t/* Autocorrelation matrix (Toeplitz) */\n\tfor(i=0; i<p;i++) {\n\t    for(j=0; j<p; j++) {\n\t        gsl_matrix_set(R, i, j, gsl_vector_get(r, abs(i-j)));\n\t    }\n\t}\n\n\t/* Vector b */\n\tfor(i=1; i<p+1; i++) {\n\t\tgsl_vector_set(b, i-1, gsl_vector_get(r, i));\n\t}\n\n\t/* Ra=r solver (LU-decomposition) */\n\tgsl_linalg_LU_decomp(R, perm, &s);\n\tgsl_linalg_LU_solve(R, perm, b, a_temp);\n\n\t/* Construct vector a and return */\n\tfor(i=1;i<p+1;i++) {\n\t\tgsl_vector_set(a, i, -1.0*gsl_vector_get(a_temp,i-1));\n\t}\n\tgsl_vector_set(a,0,1);\n\n\t/* Replace NaN-values with zeros in case of all-zero frames */\n\tfor(i=0;i<a->size;i++) {\n\t\tif(gsl_isnan(gsl_vector_get(a,i)))\n\t\t\tgsl_vector_set(a,i,0);\n\t}\n\n\t/* Free memory */\n\tgsl_vector_free(wframe);\n\tgsl_vector_free(wframe_w);\n\tgsl_vector_free(a_temp);\n\tgsl_vector_free(r);\n\tgsl_vector_free(b);\n\tgsl_matrix_free(R);\n\tgsl_permutation_free(perm);\n\n\treturn a;\n}\n\n\n\n\n\n/**\n * Function AllPassDelay\n *\n * All pass delay filter for WLPC.\n *\n * @param signal pointer to the samples\n * @param lambda all-pass filter coefficient\n */\nvoid AllPassDelay(gsl_vector *signal, double lambda) {\n\n\tint i,j,n=2;\n\tdouble sum;\n\n\t/* Create coefficient arrays: B = [-lambda 1], A = [1 -lambda] */\n\tdouble B[2] = {-lambda,1.0};\n\tdouble A[2] = {0,lambda};\n\n\t/* Zeropad the beginning of the signal */\n\tgsl_vector *signal_zp = gsl_vector_calloc(signal->size+n);\n\tfor(i=n;i<signal_zp->size;i++) {\n\t\tgsl_vector_set(signal_zp,i,gsl_vector_get(signal,i-n));\n\t}\n\n\t/* Copy vector signal */\n\tgsl_vector *signal_zp_orig = gsl_vector_alloc(signal_zp->size);\n\tgsl_vector_memcpy(signal_zp_orig,signal_zp);\n\n\t/* Filter */\n\tfor(i=n;i<signal_zp->size;i++) {\n    \tsum = 0;\n    \tfor(j=0;j<n;j++) {\n    \t\tsum += gsl_vector_get(signal_zp_orig,i-j)*B[j] + gsl_vector_get(signal_zp,i-j)*A[j];\n    \t}\n    \tgsl_vector_set(signal_zp,i,sum);\n\t}\n\n\t/* Remove zeropadding from the signal */\n\tfor(i=n;i<signal_zp->size;i++) {\n\t\tgsl_vector_set(signal,i-n,gsl_vector_get(signal_zp,i));\n\t}\n\n\t/* Free memory */\n\tgsl_vector_free(signal_zp);\n\tgsl_vector_free(signal_zp_orig);\n}\n\n\n\n\n\n/**\n * Function SWLP\n *\n * Calculate Stabilized Weighted Linear Prediction (SWLP) coefficients\n * (unstabilized can be evaluated by switching \"stabilized\" to zero)\n *\n * @param frame pointer to the samples\n * @param a pointer to coefficiets\n * @param p LPC degree\n * @param M weighting window length\n * @param lag lag of the weighting window\n */\nvoid SWLP(gsl_vector *frame, gsl_vector *a, int M, int lag, int weighting, gsl_vector *fundf, int FS, int index, gsl_vector *glottsig, int stabilized) {\n\n\tint i,j,k,s,p = a->size-1;\n\tdouble win = 0,sum = 0;\n\tgsl_vector *wframe = gsl_vector_alloc(frame->size);\n\tgsl_vector *weight = gsl_vector_calloc(frame->size+p);\n\n\t/* Windowing (choose window) */\n\tfor(i=0; i<frame->size; i++) {\n\t\tif (WIN_TYPE == HANN_WIN) win = HANN(i,frame->size);\n\t\telse if (WIN_TYPE == BLACKMAN_WIN) win = BLACKMAN(i,frame->size);\n\t\telse if (WIN_TYPE == HAMMING_WIN) win = HAMMING(i,frame->size);\n\t\telse win = 1.0;\n\t\tgsl_vector_set(wframe, i, gsl_vector_get(frame, i)*win);\n\t}\n\n\t/* Evaluate weighting function */\n\tif(weighting == 0)\n\t\tEval_STE_weight(wframe,weight,M,lag);\n\telse\n\t\tEval_GCI_weight(glottsig,weight,fundf,FS,index);\n\n\t/* Create partial weights */\n\tgsl_matrix *Z = gsl_matrix_calloc(wframe->size+p,p+1); // Partial weights\n\tgsl_matrix *Y = gsl_matrix_calloc(wframe->size+p,p+1); // Delayed and weighted versions of the signal\n\tfor(i=0;i<weight->size;i++)\n\t\tgsl_matrix_set(Z,i,0,sqrt(gsl_vector_get(weight,i)));\n\tfor(i=0;i<wframe->size;i++)\n\t\tgsl_matrix_set(Y,i,0,gsl_vector_get(wframe,i)*sqrt(gsl_vector_get(weight,i)));\n\tfor(i=0;i<p;i++) {\n\t\tif(stabilized == 1) {\n\t\t\tfor(j=i+1;j<Z->size1;j++) {\n\t\t\t\tgsl_matrix_set(Z,j,i+1,GSL_MAX(sqrt(gsl_vector_get(weight,j)/gsl_vector_get(weight,j-1)),1)*gsl_matrix_get(Z,j-1,i));\n\t\t\t}\n\t\t} else {\n\t\t\tfor(j=i+1;j<Z->size1;j++) {\n\t\t\t\tgsl_matrix_set(Z,j,i+1,sqrt(gsl_vector_get(weight,j)));\n\t\t\t}\n\t\t}\n\t\tfor(j=0;j<wframe->size;j++) {\n\t\t\tgsl_matrix_set(Y,j+i+1,i+1,gsl_matrix_get(Z,j+i+1,i+1)*gsl_vector_get(wframe,j));\n\t\t}\n\t}\n\n\t/* Autocorrelation matrix R (R = (YT*Y)/N, size p*p) and vector b (size p) */\n\tgsl_matrix *R = gsl_matrix_calloc(p,p);\n\tgsl_vector *b = gsl_vector_calloc(p);\n\tfor(i=0;i<Y->size2;i++) {\n\t\tfor(j=0;j<Y->size2;j++) {\n\t\t\tif(i > 0 && j > 0) {\n\t\t\t\tfor(k=0;k<Y->size1;k++) {\n\t\t\t\t\tgsl_matrix_set(R,i-1,j-1,gsl_matrix_get(R,i-1,j-1) + gsl_matrix_get(Y,k,i)*gsl_matrix_get(Y,k,j));\n\t\t\t\t}\n\t\t\t\tgsl_matrix_set(R,i-1,j-1,gsl_matrix_get(R,i-1,j-1)/wframe->size);\n\t\t\t}\n\t\t\tif(i > 0 && j == 0) {\n\t\t\t\tfor(k=0;k<Y->size1;k++)\n\t\t\t\t\tgsl_vector_set(b,i-1,gsl_vector_get(b,i-1) + gsl_matrix_get(Y,k,i)*gsl_matrix_get(Y,k,j));\n\t\t\t\tgsl_vector_set(b,i-1,gsl_vector_get(b,i-1)/wframe->size);\n\t\t\t\tsum += gsl_vector_get(b,i-1);\n\t\t\t}\n\t\t}\n\t}\n\n\t/* Ra=r solver (LU-decomposition) (Do not evaluate LU if sum = 0) */\n\tgsl_vector *a_temp = gsl_vector_calloc(p);\n\tgsl_permutation *perm = gsl_permutation_alloc(p);\n\tif(sum != 0) {\n\t\tgsl_linalg_LU_decomp(R, perm, &s);\n\t\tgsl_linalg_LU_solve(R, perm, b, a_temp);\n\t}\n\n\t/* Set LP-coefficients to vector \"a\" */\n\tfor(i=1; i<a->size; i++) {\n\t\tgsl_vector_set(a, i, (-1)*gsl_vector_get(a_temp, i-1));\n\t}\n\tgsl_vector_set(a, 0, 1);\n\n\t/* Stabilize through LSFs if the method itself is not guaranteed to produce a stable filter */\n\tif(stabilized == 0)\n\t\tLSF_stabilize(a);\n\n\t/* Free memory */\n\tgsl_vector_free(weight);\n\tgsl_vector_free(wframe);\n\tgsl_matrix_free(Z);\n\tgsl_matrix_free(Y);\n\tgsl_matrix_free(R);\n\tgsl_vector_free(b);\n\tgsl_vector_free(a_temp);\n\tgsl_permutation_free(perm);\n}\n\n\n\n\n\n\n\n/**\n * Function LSF_stabilize\n *\n * Check the validity of polynomial through LSFs and fix found errors\n *\n * @param lsf vector\n */\nvoid LSF_stabilize(gsl_vector *a) {\n\n\tgsl_vector *lsf = gsl_vector_calloc(a->size-1);\n\tConvert_vector_to_LSF(a, lsf);\n\tLSF_fix_vector(lsf);\n\tlsf_vector2poly(lsf,a);\n}\n\n\n\n\n/**\n * Function Convert_vector_to_LSF\n *\n * Convert LPC-coefficients to Line Spectrum Frequencies (LSF)\n * Maximum LPC-polynomial degree is 36!\n *\n *\n * @param a pointer to LPC-vector\n * @param LSF pointer to the LSF matrix\n *\n */\nvoid Convert_vector_to_LSF(gsl_vector *a, gsl_vector *LSF) {\n\n\tint i,n;\n\n\t/* Count the number of nonzero elements in \"a\" */\n\tn = 0;\n\tfor(i=0; i<a->size; i++) {\n\t\tif(gsl_vector_get(a, i) != 0) {\n\t\t\tn++;\n\t\t}\n\t}\n\n\t/* In case of only one non-zero element */\n\tif(n == 1) {\n\t\tfor(i=0; i<LSF->size; i++)\n\t\t\tgsl_vector_set(LSF, i, (i+1)*M_PI/LSF->size);\n\t\treturn;\n\t}\n\n\tgsl_vector *aa = gsl_vector_calloc(n+1);\n\tgsl_vector *flip_aa = gsl_vector_calloc(n+1);\n\tgsl_vector *p = gsl_vector_calloc(n+1);\n\tgsl_vector *q = gsl_vector_calloc(n+1);\n\n\t/* Construct vectors aa=[a 0] and flip_aa=[0 flip(a)] */\n\tfor(i=0; i<n; i++) {\n\t\tgsl_vector_set(aa, i, gsl_vector_get(a, i));\n\t\tgsl_vector_set(flip_aa, flip_aa->size-1-i, gsl_vector_get(a, i));\n\t}\n\n\t/* Construct vectors p and q */\n\tfor(i=0; i<n+1; i++) {\n\t\tgsl_vector_set(p, i, gsl_vector_get(aa, i) + gsl_vector_get(flip_aa, i));\n\t\tgsl_vector_set(q, i, gsl_vector_get(aa, i) - gsl_vector_get(flip_aa, i));\n\t}\n\n\t/* Remove trivial zeros */\n\tif((n+1)%2 == 0) {\n\t\tdouble y;\n\t\t/* Deconvolve p with [1 1] */\n\t\ty = 0;\n\t\tfor(i=0; i<p->size; i++) {\n    \t\tgsl_vector_set(p, i, gsl_vector_get(p, i)-y);\n    \t\ty = gsl_vector_get(p, i);\n\t\t}\n\t\tgsl_vector_set(p, p->size-1, 0);\n\t\t/* Deconvolve q with [1 -1] */\n\t\ty = 0;\n\t\tfor(i=0; i<q->size; i++) {\n    \t\tgsl_vector_set(q, i, gsl_vector_get(q, i)+y);\n    \t\ty = gsl_vector_get(q, i);\n\t\t}\n\t\tgsl_vector_set(q, q->size-1, 0);\n\t} else {\n\t\tdouble y;\n\t\t/* Deconvolve q with [1 1] */\n\t\ty = 0;\n\t\tfor(i=0; i<q->size; i++) {\n    \t\tgsl_vector_set(q, i, gsl_vector_get(q, i)-y);\n    \t\ty = gsl_vector_get(q, i);\n\t\t}\n\t\t/* Deconvolve q with [1 -1] */\n\t\ty = 0;\n\t\tfor(i=0; i<q->size; i++) {\n    \t\tgsl_vector_set(q, i, gsl_vector_get(q, i)+y);\n    \t\ty = gsl_vector_get(q, i);\n\t\t}\n\t\tgsl_vector_set(q, q->size-1, 0);\n\t\tgsl_vector_set(q, q->size-2, 0);\n\t}\n\n\t/* Count the number of nonzero elements in \"p\" and \"q\" */\n\tint n_p = 0;\n\tint n_q = 0;\n\tfor(i=0; i<p->size; i++) {\n\t\tif(gsl_vector_get(p, i) != 0)\n\t\t\tn_p++;\n\t\tif(gsl_vector_get(q, i) != 0)\n\t\t\tn_q++;\n\t}\n\n\t/* Take the last half of \"p\" and \"q\" to vectors \"TP\" and \"TQ\" */\n\tgsl_vector *TP = gsl_vector_alloc((n_p+1)/2);\n\tgsl_vector *TQ = gsl_vector_alloc((n_q+1)/2);\n\tfor(i=0; i<TP->size; i++) {\n\t\tgsl_vector_set(TP, i, gsl_vector_get(p, i+(n_p-1)/2));\n\t}\n\tfor(i=0; i<TQ->size; i++) {\n\t\tgsl_vector_set(TQ, i, gsl_vector_get(q, i+(n_q-1)/2));\n\t}\n\n\t/* Chebyshev transform */\n\tChebyshev(TP);\n\tChebyshev(TQ);\n\n\t/* Initialize root arrays */\n\tint nroots_TP = 2*(TP->size-1);\n\tint nroots_TQ = 2*(TQ->size-1);\n\tdouble TP_coeffs[TP->size];\n\tdouble TQ_coeffs[TQ->size];\n\tdouble TP_roots[nroots_TP];\n\tdouble TQ_roots[nroots_TQ];\n\n\t/* Copy coefficients to arrays */\n    for(i=0; i<TP->size; i++) {\n    \tTP_coeffs[i] = gsl_vector_get(TP, i);\n    }\n    for(i=0; i<TQ->size; i++) {\n    \tTQ_coeffs[i] = gsl_vector_get(TQ, i);\n    }\n\n\t/* Solve roots */\n    gsl_poly_complex_workspace *w_TP = gsl_poly_complex_workspace_alloc(TP->size);\n    gsl_poly_complex_workspace *w_TQ = gsl_poly_complex_workspace_alloc(TQ->size);\n    gsl_poly_complex_solve(TP_coeffs, TP->size, w_TP, TP_roots);\n    gsl_poly_complex_solve(TQ_coeffs, TQ->size, w_TQ, TQ_roots);\n\n\t/* Convert to LSF and sort */\n\tdouble sorted_LSF[(nroots_TP+nroots_TQ)/2];\n\tfor(i=0; i<nroots_TP; i=i+2) {\n\t\tsorted_LSF[i/2] = acos(TP_roots[i]/2);\n\t}\n\tfor(i=0; i<nroots_TQ; i=i+2) {\n\t\tsorted_LSF[(i+nroots_TP)/2] = acos(TQ_roots[i]/2);\n\t}\n\tgsl_sort(sorted_LSF, 1, (nroots_TP+nroots_TQ)/2);\n\n\t/* Copy LSFs to vector LSF */\n\tfor(i=0; i<(nroots_TP+nroots_TQ)/2; i++)\n\t\tgsl_vector_set(LSF, i, sorted_LSF[i]);\n\n\t/* Free memory */\n\tgsl_poly_complex_workspace_free(w_TP);\n    gsl_poly_complex_workspace_free(w_TQ);\n\tgsl_vector_free(aa);\n\tgsl_vector_free(flip_aa);\n\tgsl_vector_free(p);\n\tgsl_vector_free(q);\n\tgsl_vector_free(TP);\n\tgsl_vector_free(TQ);\n}\n\n\n\n\n\n\n/**\n * Function lsf_vector2poly\n *\n * Convert LSF vector to polynomial\n *\n * @param lsf_vector\n * @param poly\n * @param index\n * @param HMM switch for HMM\n */\nvoid lsf_vector2poly(gsl_vector *lsf_vector, gsl_vector *poly) {\n\n\tint i,l = lsf_vector->size;\n\tgsl_vector *fi_p = NULL, *fi_q = NULL;\n\n\t/* Create fi_p and fi_q */\n\tif(l%2 == 0) {\n\t\tfi_p = gsl_vector_alloc(l/2);\n\t\tfi_q = gsl_vector_alloc(l/2);\n\t\tfor(i=0;i<l;i=i+2) {\n\t\t\tgsl_vector_set(fi_p,i/2,gsl_vector_get(lsf_vector,i));\n\t\t}\n\t\tfor(i=1;i<l;i=i+2) {\n\t\t\tgsl_vector_set(fi_q,(i-1)/2,gsl_vector_get(lsf_vector,i));\n\t\t}\n\t} else {\n\t\tfi_p = gsl_vector_alloc((l+1)/2);\n\t\tfor(i=0;i<l;i=i+2) {\n\t\t\tgsl_vector_set(fi_p,i/2,gsl_vector_get(lsf_vector,i));\n\t\t}\n\t\tif((l-1)/2 > 0) {\n\t\t\tfi_q = gsl_vector_alloc((l-1)/2);\n\t\t\tfor(i=1;i<l-1;i=i+2) {\n\t\t\t\tgsl_vector_set(fi_q,(i-1)/2,gsl_vector_get(lsf_vector,i));\n\t\t\t}\n\t\t}\n\t}\n\n\t/* Construct vectors P and Q */\n\tgsl_vector *cp = gsl_vector_calloc(3);\n\tgsl_vector *cq = gsl_vector_calloc(3);\n\tgsl_vector_add_constant(cp,1);\n\tgsl_vector_add_constant(cq,1);\n\tgsl_vector *P = gsl_vector_alloc(1);\n\tgsl_vector *Q = gsl_vector_alloc(1);\n\tgsl_vector_set(P,0,1);\n\tgsl_vector_set(Q,0,1);\n\tfor(i=0;i<fi_p->size;i++) {\n\t\tgsl_vector_set(cp,1,-2*cos(gsl_vector_get(fi_p,i)));\n\t\tP = Conv(P,cp);\n\t}\n\tif((l-1)/2 > 0) {\n\t\tfor(i=0;i<fi_q->size;i++) {\n\t\t\tgsl_vector_set(cq,1,-2*cos(gsl_vector_get(fi_q,i)));\n\t\t\tQ = Conv(Q,cq);\n\t\t}\n\t}\n\n\t/* Add trivial zeros */\n\tif(l%2 == 0) {\n\t\tgsl_vector *conv = gsl_vector_calloc(2);\n\t\tgsl_vector_add_constant(conv,1);\n\t\tP = Conv(P,conv);\n\t\tgsl_vector_set(conv,0,-1);\n    \tQ = Conv(Q,conv);\n    \tgsl_vector_free(conv);\n\t} else {\n\t\tgsl_vector *conv = gsl_vector_calloc(3);\n\t\tgsl_vector_set(conv,0,-1);\n\t\tgsl_vector_set(conv,2,1);\n\t\tQ = Conv(Q,conv);\n\t\tgsl_vector_free(conv);\n\t}\n\n\t/* Construct polynomial */\n\tfor(i=1;i<P->size;i++) {\n\t\tgsl_vector_set(poly,P->size-i-1,0.5*(gsl_vector_get(P,i)+gsl_vector_get(Q,i)));\n\t}\n\n\t/* Free memory */\n\tgsl_vector_free(fi_p);\n\tif((l-1)/2 > 0)\n\t\tgsl_vector_free(fi_q);\n\tgsl_vector_free(cp);\n\tgsl_vector_free(cq);\n\tgsl_vector_free(P);\n\tgsl_vector_free(Q);\n}\n\n\n\n\n\n\n\n\n\n/**\n * Function Eval_STE_weight\n *\n * Evaluate short time energy (STE) function for SWLP weighting\n *\n * @param frame pointer to the frame\n * @param ste pointer to the STE function\n * @param M weighting window length\n * @param lag time lag of estimating the STE\n */\nvoid Eval_STE_weight(gsl_vector *frame, gsl_vector *ste, int M, int lag) {\n\n\tint i,j;\n\tfor(i=0;i<ste->size;i++) {\n\t\tfor(j=GSL_MAX(i-lag-M+1,0);j<GSL_MIN(i-lag+1,(int)frame->size);j++) {\n\t\t\tgsl_vector_set(ste,i,gsl_vector_get(ste,i) + gsl_vector_get(frame,j)*gsl_vector_get(frame,j));\n\t\t}\n\t\tgsl_vector_set(ste,i,gsl_vector_get(ste,i) + DBL_EPSILON);\n\t}\n}\n\n\n\n\n/**\n * Function Eval_GCI_weight\n *\n * Find GCIs (Glottal Closure Instants) and construct weighting for de-emphasizing GCIs in (S)WLP\n *\n * @param ...\n *\n */\nvoid Eval_GCI_weight(gsl_vector *glottsig, gsl_vector *weight, gsl_vector *fundf, int FS, int index) {\n\n\t/* Estimate glottal closure instants */\n\tgsl_vector *inds = Find_GCI(glottsig, fundf, FS, index);\n\n\t/* If unvoiced or GCIs not found, simply set weight to 1 */\n\tif(inds == NULL || gsl_vector_get(fundf,index) == 0) {\n\t\tif(inds != NULL)\n\t\t\tgsl_vector_free(inds);\n\t\tgsl_vector_set_all(weight,1);\n\t\treturn;\n\t}\n\n\t/* Algorithm parameters */\n\tdouble closed_time = 0.4;\n\tdouble gci_pos = 0.8;\n\tdouble deemph = 0.01;\n\n\t/* Initialize */\n\tint i,j;\n\tint csamples = rint(closed_time*FS/gsl_vector_get(fundf,index));\n\n\t/* Set weight according to GCIs */\n\tgsl_vector_set_all(weight,1);\n\tfor(i=0;i<inds->size;i++) {\n\t\tfor(j=0;j<csamples;j++) {\n\t\t\tgsl_vector_set(weight,GSL_MIN(GSL_MAX(gsl_vector_get(inds,i)-rint(csamples*gci_pos)+j,0),weight->size-1),deemph);\n\t\t}\n\t}\n\n\t/* Free memory */\n\tgsl_vector_free(inds);\n}\n\n\n\n\n\n\n\n/**\n * Function Find_GCI\n *\n * Find GCIs (Glottal Closure Instants)\n *\n * @param ...\n *\n */\ngsl_vector *Find_GCI(gsl_vector *frame_orig, gsl_vector *fundf, int FS, int index) {\n\n\tint i,j,min_ind,ind_ind,t0_tmp;\n\tdouble t0,min_val,temp;\n\tgsl_vector *indices = gsl_vector_calloc(100);\n\tgsl_vector *final_inds;\n\tgsl_vector *frame = gsl_vector_calloc(frame_orig->size);\n\tgsl_vector_memcpy(frame,frame_orig);\n\n\t/* Differentiate frame and find minimum */\n\tDifferentiate(frame,LEAK);\n\tmin_ind = gsl_vector_min_index(frame);\n\n\t/* Find t0 minima of the glottal waveform in order to find GCIs,\n\t * start evaluating from the mimina, first backward, then forward */\n\tt0 = FS/gsl_vector_get(fundf,index);\n\tgsl_vector_set(indices,50,min_ind);\n\tt0_tmp = min_ind;\n\tind_ind = 51;\n\n\t/* Backward */\n\ttemp = 0;\n\tind_ind = 51;\n\twhile(1) {\n\t\tt0_tmp = rint(gsl_vector_get(indices,ind_ind-1) - t0 - temp);\n\t\tif(t0_tmp < 0)\n\t\t\tbreak;\n\t\tmin_val = BIG_POS_NUMBER;\n\t\tfor(i=-20;i<21;i++) {\n\t\t\tif(gsl_vector_get(frame,GSL_MIN(GSL_MAX(t0_tmp + i,0),frame->size-1)) < min_val) {\n\t\t\t\tmin_val = gsl_vector_get(frame,GSL_MIN(GSL_MAX(t0_tmp + i,0),frame->size-1));\n\t\t\t\tgsl_vector_set(indices,ind_ind,GSL_MIN(GSL_MAX(t0_tmp + i,0),frame->size-1));\n\t\t\t}\n\t\t}\n\t\tif(gsl_vector_get(indices,ind_ind-1)-gsl_vector_get(indices,ind_ind) < t0/2.0) {\n\t\t\ttemp = temp + t0;\n\t\t} else {\n\t\t\tind_ind++;\n\t\t\ttemp = 0;\n\t\t}\n\t}\n\n\t/* Forward */\n\ttemp = 0;\n\tind_ind = 49;\n\twhile(1) {\n\t\tt0_tmp = rint(gsl_vector_get(indices,ind_ind+1) + t0 + temp);\n\t\tif(t0_tmp > frame->size-1)\n\t\t\tbreak;\n\t\tmin_val = BIG_POS_NUMBER;\n\t\tfor(i=-20;i<21;i++) {\n\t\t\tif(gsl_vector_get(frame,GSL_MIN(GSL_MAX(t0_tmp + i,0),frame->size-1)) < min_val) {\n\t\t\t\tmin_val = gsl_vector_get(frame,GSL_MIN(GSL_MAX(t0_tmp + i,0),frame->size-1));\n\t\t\t\tgsl_vector_set(indices,ind_ind,GSL_MIN(GSL_MAX(t0_tmp + i,0),frame->size-1));\n\t\t\t}\n\t\t}\n\t\tif(gsl_vector_get(indices,ind_ind)-gsl_vector_get(indices,ind_ind+1) < t0/2.0) {\n\t\t\ttemp = temp + t0;\n\t\t} else {\n\t\t\tind_ind--;\n\t\t\ttemp = 0;\n\t\t}\n\t}\n\n\t/* Sort indices */\n\tgsl_sort_vector(indices);\n\n\t/* Allocate vector for non-zero indices and return */\n\ti = 0;\n\twhile(gsl_vector_get(indices,indices->size-1-i) > 0)\n\t\ti += 1;\n\tif(i < 2) {\n\t\tgsl_vector_free(indices);\n\t\tgsl_vector_free(frame);\n\t\treturn NULL;\n\t} else {\n\t\tfinal_inds = gsl_vector_alloc(i);\n\t\tfor(j=0;j<i;j++)\n\t\t\tgsl_vector_set(final_inds,j,gsl_vector_get(indices,indices->size-i+j));\n\t\tgsl_vector_free(indices);\n\t\tgsl_vector_free(frame);\n\t\treturn final_inds;\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n/**\n * Function Interpolate\n *\n * Interpolates given vector to new vector of given length\n *\n * @param vector original vector\n * @param i_vector interpolated vector\n */\nvoid Interpolate(gsl_vector *vector, gsl_vector *i_vector) {\n\n\tint i,len = vector->size,length = i_vector->size;\n\n\t/* Read values to array */\n\tdouble x[len];\n\tdouble y[len];\n\tfor(i=0; i<len; i++) {\n\t\tx[i] = i;\n\t\ty[i] = gsl_vector_get(vector,i);\n\t}\n\tgsl_interp_accel *acc = gsl_interp_accel_alloc();\n    gsl_spline *spline = gsl_spline_alloc(gsl_interp_cspline,len);\n    gsl_spline_init(spline, x, y, len);\n    double xi;\n    i = 0;\n\n    /* New implementation (27.3.2009, bug fix 8.2.2010) */\n    /* Bug fix to GSL v.1.15, 26.1.2012 */\n    xi = x[0];\n    while(i<length) {\n    \tgsl_vector_set(i_vector,i,gsl_spline_eval(spline, xi, acc));\n    \txi += (len-1)/(double)(length-1);\n    \tif(xi > len-1)\n    \t\txi = len-1;\n    \ti++;\n    }\n\n    /* Free memory */\n    gsl_spline_free(spline);\n\tgsl_interp_accel_free(acc);\n}\n\n/**\n * Function Interpolate_matrix\n *\n * Interpolates given matrix to new matrix of given length\n *\n * @param matrix original matrix\n * @param imatrix interpolated matrix\n */\nvoid Interpolate_matrix(gsl_matrix *matrix, gsl_matrix *imatrix) {\n\n\tint i,j;\n\tgsl_vector *ivec = gsl_vector_alloc(imatrix->size1);\n\tfor(i=0;i<matrix->size2;i++) {\n\t\tgsl_vector_view column = gsl_matrix_column(matrix,i);\n\t\tInterpolate((gsl_vector *)(&column),ivec);\n\t\tfor(j=0;j<ivec->size;j++)\n\t\t\tgsl_matrix_set(imatrix,j,i,gsl_vector_get(ivec,j));\n\t}\n\tgsl_vector_free(ivec);\n}\n\n\n\n\n/**\n * Function Interpolate_lin\n *\n * Interpolates linearly given vector to new vector of given length\n *\n * @param vector original vector\n * @param i_vector interpolated vector\n */\nvoid Interpolate_lin(gsl_vector *vector, gsl_vector *i_vector) {\n\n\tint i,len = vector->size,length = i_vector->size;\n\n\t/* Read values to array */\n\tdouble x[len];\n\tdouble y[len];\n\tfor(i=0; i<len; i++) {\n\t\tx[i] = i;\n\t\ty[i] = gsl_vector_get(vector,i);\n\t}\n\tgsl_interp_accel *acc = gsl_interp_accel_alloc();\n\tgsl_spline *spline = gsl_spline_alloc(gsl_interp_linear, len);\n\tgsl_spline_init(spline, x, y, len);\n\tdouble xi;\n    i = 0;\n\n    /* New implementation (27.3.2009, bug fix 8.2.2010) */\n    /* Bug fix to GSL v.1.15, 26.1.2012 */\n    xi = x[0];\n    while(i<length) {\n    \tgsl_vector_set(i_vector,i,gsl_spline_eval(spline, xi, acc));\n    \txi += (len-1)/(double)(length-1);\n    \tif(xi > len-1)\n    \t\txi = len-1;\n    \ti++;\n    }\n\n    /* Free memory */\n    gsl_spline_free(spline);\n\tgsl_interp_accel_free(acc);\n}\n\n\n\n\n/**\n * Function Interpolate_fract\n *\n * Interpolates given vector to new vector of given fractional length\n *\n * @param vector original vector\n * @param i_vector interpolated vector\n * @param flen fractional length\n */\nvoid Interpolate_fract(gsl_vector *vector, gsl_vector *i_vector, double flen) {\n\n\tint i,len = vector->size,length = i_vector->size;\n\n\t/* Read values to array */\n\tdouble x[len];\n\tdouble y[len];\n\tfor(i=0; i<len; i++) {\n\t\tx[i] = i;\n\t\ty[i] = gsl_vector_get(vector,i);\n\t}\n\tgsl_interp_accel *acc = gsl_interp_accel_alloc();\n    gsl_spline *spline = gsl_spline_alloc(gsl_interp_cspline,len);\n    gsl_spline_init(spline, x, y, len);\n    double xi = x[0];\n    i = 0;\n    while(i<length) {\n    \tgsl_vector_set(i_vector,i,gsl_spline_eval(spline, xi, acc));\n    \txi += (len-1)/(flen-1.0);\n    \tif(xi > len-1)\n    \t\txi = len-1;\n    \ti++;\n    }\n\n    /* Free memory */\n    gsl_spline_free(spline);\n\tgsl_interp_accel_free(acc);\n}\n\n\n\n\n\n\n\n\n\n\n\n/**\n * Function Convert_to_LSF\n *\n * Converts the LPC-coefficients to Line Spectrum Frequencies (LSF)\n * Maximum LPC-polynomial degree is 36!\n *\n * @param LSF pointer to the LSF matrix\n * @param a pointer to LPC-vector\n * @param index time index\n *\n */\nvoid Convert_to_LSF(gsl_matrix *LSF, gsl_vector *a, int index) {\n\n\tint i,n;\n\n\t/* Count the number of nonzero elements in \"a\" */\n\tn = 0;\n\tfor(i=0; i<a->size; i++) {\n\t\tif(gsl_vector_get(a, i) != 0) {\n\t\t\tn++;\n\t\t}\n\t}\n\n\t/* In case of only one non-zero element */\n\tif(n == 1) {\n\t\tfor(i=0; i<LSF->size2; i++)\n\t\t\tgsl_matrix_set(LSF, index, i, (i+1)*M_PI/LSF->size2);\n\t\treturn;\n\t}\n\n\tgsl_vector *aa = gsl_vector_calloc(n+1);\n\tgsl_vector *flip_aa = gsl_vector_calloc(n+1);\n\tgsl_vector *p = gsl_vector_calloc(n+1);\n\tgsl_vector *q = gsl_vector_calloc(n+1);\n\n\t/* Construct vectors aa=[a 0] and flip_aa=[0 flip(a)] */\n\tfor(i=0; i<n; i++) {\n\t\tgsl_vector_set(aa, i, gsl_vector_get(a, i));\n\t\tgsl_vector_set(flip_aa, flip_aa->size-1-i, gsl_vector_get(a, i));\n\t}\n\n\t/* Construct vectors p and q */\n\tfor(i=0; i<n+1; i++) {\n\t\tgsl_vector_set(p, i, gsl_vector_get(aa, i) + gsl_vector_get(flip_aa, i));\n\t\tgsl_vector_set(q, i, gsl_vector_get(aa, i) - gsl_vector_get(flip_aa, i));\n\t}\n\n\t/* Remove trivial zeros */\n\tif((n+1)%2 == 0) {\n\t\tdouble y;\n\t\t/* Deconvolve p with [1 1] */\n\t\ty = 0;\n\t\tfor(i=0; i<p->size; i++) {\n    \t\tgsl_vector_set(p, i, gsl_vector_get(p, i)-y);\n    \t\ty = gsl_vector_get(p, i);\n\t\t}\n\t\tgsl_vector_set(p, p->size-1, 0);\n\t\t/* Deconvolve q with [1 -1] */\n\t\ty = 0;\n\t\tfor(i=0; i<q->size; i++) {\n    \t\tgsl_vector_set(q, i, gsl_vector_get(q, i)+y);\n    \t\ty = gsl_vector_get(q, i);\n\t\t}\n\t\tgsl_vector_set(q, q->size-1, 0);\n\t} else {\n\t\tdouble y;\n\t\t/* Deconvolve q with [1 1] */\n\t\ty = 0;\n\t\tfor(i=0; i<q->size; i++) {\n    \t\tgsl_vector_set(q, i, gsl_vector_get(q, i)-y);\n    \t\ty = gsl_vector_get(q, i);\n\t\t}\n\t\t/* Deconvolve q with [1 -1] */\n\t\ty = 0;\n\t\tfor(i=0; i<q->size; i++) {\n    \t\tgsl_vector_set(q, i, gsl_vector_get(q, i)+y);\n    \t\ty = gsl_vector_get(q, i);\n\t\t}\n\t\tgsl_vector_set(q, q->size-1, 0);\n\t\tgsl_vector_set(q, q->size-2, 0);\n\t}\n\n\t/* Count the number of nonzero elements in \"p\" and \"q\" */\n\tint n_p = 0;\n\tint n_q = 0;\n\tfor(i=0; i<p->size; i++) {\n\t\tif(gsl_vector_get(p, i) != 0)\n\t\t\tn_p++;\n\t\tif(gsl_vector_get(q, i) != 0)\n\t\t\tn_q++;\n\t}\n\n\t/* Take the last half of \"p\" and \"q\" to vectors \"TP\" and \"TQ\" */\n\tgsl_vector *TP = gsl_vector_alloc((n_p+1)/2);\n\tgsl_vector *TQ = gsl_vector_alloc((n_q+1)/2);\n\tfor(i=0; i<TP->size; i++) {\n\t\tgsl_vector_set(TP, i, gsl_vector_get(p, i+(n_p-1)/2));\n\t}\n\tfor(i=0; i<TQ->size; i++) {\n\t\tgsl_vector_set(TQ, i, gsl_vector_get(q, i+(n_q-1)/2));\n\t}\n\n\t/* Chebyshev transform */\n\tChebyshev(TP);\n\tChebyshev(TQ);\n\n\t/* Initialize root arrays */\n\tint nroots_TP = 2*(TP->size-1);\n\tint nroots_TQ = 2*(TQ->size-1);\n\tdouble TP_coeffs[TP->size];\n\tdouble TQ_coeffs[TQ->size];\n\tdouble TP_roots[nroots_TP];\n\tdouble TQ_roots[nroots_TQ];\n\n\t/* Copy coefficients to arrays */\n    for(i=0; i<TP->size; i++) {\n    \tTP_coeffs[i] = gsl_vector_get(TP, i);\n    }\n    for(i=0; i<TQ->size; i++) {\n    \tTQ_coeffs[i] = gsl_vector_get(TQ, i);\n    }\n\n\t/* Solve roots */\n    gsl_poly_complex_workspace *w_TP = gsl_poly_complex_workspace_alloc(TP->size);\n    gsl_poly_complex_workspace *w_TQ = gsl_poly_complex_workspace_alloc(TQ->size);\n    gsl_poly_complex_solve(TP_coeffs, TP->size, w_TP, TP_roots);\n    if(nroots_TQ > 0) {\n    \tgsl_poly_complex_solve(TQ_coeffs, TQ->size, w_TQ, TQ_roots);\n    }\n\n\t/* Convert to LSF and sort */\n\tdouble sorted_LSF[(nroots_TP+nroots_TQ)/2];\n\tfor(i=0; i<nroots_TP; i=i+2) {\n\t\tsorted_LSF[i/2] = acos(TP_roots[i]/2);\n\t}\n\tfor(i=0; i<nroots_TQ; i=i+2) {\n\t\tsorted_LSF[(i+nroots_TP)/2] = acos(TQ_roots[i]/2);\n\t}\n\tgsl_sort(sorted_LSF, 1, (nroots_TP+nroots_TQ)/2);\n\n\t/* Copy LSFs to vector LSF */\n\tfor(i=0; i<(nroots_TP+nroots_TQ)/2; i++)\n\t\tgsl_matrix_set(LSF, index, i, sorted_LSF[i]);\n\n\t/* Free memory */\n\tgsl_poly_complex_workspace_free(w_TP);\n    gsl_poly_complex_workspace_free(w_TQ);\n\tgsl_vector_free(aa);\n\tgsl_vector_free(flip_aa);\n\tgsl_vector_free(p);\n\tgsl_vector_free(q);\n\tgsl_vector_free(TP);\n\tgsl_vector_free(TQ);\n}\n\n\n\n\n\n\n\n\n\n/**\n * Function Chebyshev\n *\n * Chebyshev transformation\n *\n * @param T pointer to polynomial coefficients (result will be computed in-place)\n *\n */\nvoid Chebyshev(gsl_vector *T) {\n\n\tint i,j,s;\n\tgsl_matrix *C;\n\tgsl_vector *cheb = gsl_vector_alloc(T->size);\n\tgsl_matrix *inv_C = gsl_matrix_alloc(T->size, T->size);\n\tgsl_permutation *perm = gsl_permutation_alloc(T->size);\n\n\t/* Create C, matrix inversion through LU-decomposition */\n\tC = Construct_C(T->size);\n\tgsl_linalg_LU_decomp(C, perm, &s);\n\tgsl_linalg_LU_invert(C, perm, inv_C);\n\n\t/* Evaluate r = inv(C)'*T */\n\tdouble sum;\n\tfor(i=0; i<T->size; i++) {\n\t\tsum = 0;\n\t\tfor(j=0; j<T->size; j++)\n\t\t\tsum += gsl_matrix_get(inv_C, j, i)*gsl_vector_get(T, j);\n\t\tgsl_vector_set(cheb, i, sum);\n\t}\n\n\t/* Copy coefficients to T */\n\tfor(i=0; i<T->size; i++) {\n\t\tgsl_vector_set(T, i, gsl_vector_get(cheb, i));\n\t}\n\n\t/* Free memory */\n\tgsl_vector_free(cheb);\n\tgsl_matrix_free(C);\n\tgsl_matrix_free(inv_C);\n\tgsl_permutation_free(perm);\n}\n\n\n\n\n\n/**\n * Function Construct_C\n *\n * Construct data matrix C for Chebyshev transform\n *\n * @param size\n * @return C matrix\n *\n */\ngsl_matrix *Construct_C(int size) {\n\n\tint i,j;\n\tgsl_matrix *C = gsl_matrix_calloc(size,size);\n\tgsl_vector *tmp = gsl_vector_alloc(3);\n\tgsl_vector *f = gsl_vector_alloc(3);\n\n\t/* Set tmp and f */\n\tgsl_vector_set(tmp,0,1);\n\tgsl_vector_set(tmp,1,0);\n\tgsl_vector_set(tmp,2,1);\n\tgsl_vector_memcpy(f,tmp);\n\n\t/* Set diagonal to 1 */\n\tfor(i=0;i<size;i++)\n\t\tgsl_matrix_set(C,i,i,1);\n\n\t/* Construct C */\n\tfor(i=2;i<size;i++) {\n\t\tf = Conv(f,tmp);\n\t\tfor(j=0;j<i;j++)\n\t\t\tgsl_matrix_set(C,i,j,gsl_vector_get(f,(f->size-1)/2+j));\n\t}\n\n\t/* Free memory */\n\tgsl_vector_free(tmp);\n\tgsl_vector_free(f);\n\n\treturn C;\n}\n\n\n\n\n\n\n/**\n * Function MA\n *\n * Moving average smoothing (inplace)\n *\n * @param vector original vector\n * @param length smoothing length in samples\n */\nvoid MA(gsl_vector *vector, int length) {\n\n\tint i,j;\n\tdouble sum;\n\n\tif(length == 0)\n\t\treturn;\n\tif(length%2 == 0) {\n\t\tprintf(\"Warning: Span of the moving average filter must be odd.\\n\");\n\t\tprintf(\"         Span is changed to N-1.\\n\");\n\t\tlength = length - 1;\n\t}\n\tif(length < 2) {\n\t\tprintf(\"Warning: Span of the moving average filter must be at least 3.\\n\");\n\t\treturn;\n\t}\n\tif(vector->size < length)\n\t\treturn;\n\n\t/* Copy vector */\n\tgsl_vector *vector_orig = gsl_vector_alloc(vector->size);\n\tgsl_vector_memcpy(vector_orig,vector);\n\n\t/* Filter */\n\tfor(i=length;i<vector->size;i++) {\n    \tsum = 0;\n    \tfor(j=0;j<length;j++) {\n    \t\tsum += gsl_vector_get(vector_orig,i-j);\n    \t}\n    \tgsl_vector_set(vector,i-length/2,sum/length);\n\t}\n\n\t/* Fix the beginning */\n\tfor(i=1;i<length+1;i=i+2) {\n\t\tsum = 0;\n\t\tfor(j=0;j<i;j++) {\n\t\t\tsum += gsl_vector_get(vector_orig,j);\n\t\t}\n\t\tgsl_vector_set(vector,(i-1)/2,sum/i);\n\t}\n\n\t/* Fix the end */\n\tfor(i=1;i<length+1;i=i+2) {\n\t\tsum = 0;\n\t\tfor(j=0;j<i;j++) {\n\t\t\tsum += gsl_vector_get(vector_orig,vector->size-1-j);\n\t\t}\n\t\tgsl_vector_set(vector,vector->size-1-(i-1)/2,sum/i);\n\t}\n\n\t/* Free memory */\n\tgsl_vector_free(vector_orig);\n}\n\n\n\n\n\n\n\n\n/**\n * Function MA_voiced\n *\n * Moving average smoothing (inplace) for voiced regions (fundf > 0)\n *\n * @param vector original vector\n * @param fundf f0 vector\n * @param length smoothing length in samples for each sample\n */\nvoid MA_voiced(gsl_vector *vector, gsl_vector *fundf, int len) {\n\n\tint i,j,k;\n\tgsl_vector *temp;\n\tfor(i=0;i<vector->size;i++) {\n\t\tif(gsl_vector_get(fundf,i) > 0) {\n\t\t\tj = 0;\n\t\t\twhile(i+j < vector->size && gsl_vector_get(fundf,i+j) > 0)\n\t\t\t\tj++;\n\t\t\tif(j>2) {\n\t\t\t\ttemp = gsl_vector_alloc(j);\n\t\t\t\tfor(k=0;k<j;k++)\n\t\t\t\t\tgsl_vector_set(temp,k,gsl_vector_get(vector,i+k));\n\t\t\t\tMA(temp,len);\n\t\t\t\tfor(k=0;k<j;k++)\n\t\t\t\t\tgsl_vector_set(vector,i+k,gsl_vector_get(temp,k));\n\t\t\t\tgsl_vector_free(temp);\n\t\t\t}\n\t\t\ti = i + j;\n\t\t}\n\t}\n}\n\n\n\n\n/**\n * Function MA_unvoiced\n *\n * Moving average smoothing (inplace) for unvoiced regions (fundf = 0)\n *\n * @param vector original vector\n * @param fundf f0 vector\n * @param length smoothing length in samples for each sample\n */\nvoid MA_unvoiced(gsl_vector *vector, gsl_vector *fundf, int len) {\n\n\tint i,j,k;\n\tgsl_vector *temp;\n\tfor(i=0;i<vector->size;i++) {\n\t\tif(gsl_vector_get(fundf,i) == 0) {\n\t\t\tj = 0;\n\t\t\twhile(i+j < vector->size && gsl_vector_get(fundf,i+j) == 0)\n\t\t\t\tj++;\n\t\t\tif(j>2) {\n\t\t\t\ttemp = gsl_vector_alloc(j);\n\t\t\t\tfor(k=0;k<j;k++)\n\t\t\t\t\tgsl_vector_set(temp,k,gsl_vector_get(vector,i+k));\n\t\t\t\tMA(temp,len);\n\t\t\t\tfor(k=0;k<j;k++)\n\t\t\t\t\tgsl_vector_set(vector,i+k,gsl_vector_get(temp,k));\n\t\t\t\tgsl_vector_free(temp);\n\t\t\t}\n\t\t\ti = i + j;\n\t\t}\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n\n\n/**\n * Function lsf2poly\n *\n * Convert LSF to polynomial\n *\n * @param lsf_matrix\n * @param poly\n * @param index\n * @param HMM switch for HMM\n */\nvoid lsf2poly(gsl_matrix *lsf_matrix, gsl_vector *poly, int index, int HMM) {\n\n\tint i,l = lsf_matrix->size2;\n\tgsl_vector *lsf_vector = gsl_vector_calloc(l);\n\tgsl_vector *fi_p = NULL, *fi_q = NULL;\n\n\t/* Copy values to vector */\n\tfor(i=0;i<l;i++)\n\t\tgsl_vector_set(lsf_vector,i,gsl_matrix_get(lsf_matrix,index,i));\n\n\t/* Check the validity of LSF and fix found errors (HMM parameters) */\n\tif(HMM == 1) {\n\t\tLSF_fix_vector(lsf_vector);\n\t}\n\n\t/* Create fi_p and fi_q */\n\tif(l%2 == 0) {\n\t\tfi_p = gsl_vector_alloc(l/2);\n\t\tfi_q = gsl_vector_alloc(l/2);\n\t\tfor(i=0;i<l;i=i+2) {\n\t\t\tgsl_vector_set(fi_p,i/2,gsl_vector_get(lsf_vector,i));\n\t\t}\n\t\tfor(i=1;i<l;i=i+2) {\n\t\t\tgsl_vector_set(fi_q,(i-1)/2,gsl_vector_get(lsf_vector,i));\n\t\t}\n\t} else {\n\t\tfi_p = gsl_vector_alloc((l+1)/2);\n\t\tfor(i=0;i<l;i=i+2) {\n\t\t\tgsl_vector_set(fi_p,i/2,gsl_vector_get(lsf_vector,i));\n\t\t}\n\t\tif((l-1)/2 > 0) {\n\t\t\tfi_q = gsl_vector_alloc((l-1)/2);\n\t\t\tfor(i=1;i<l-1;i=i+2) {\n\t\t\t\tgsl_vector_set(fi_q,(i-1)/2,gsl_vector_get(lsf_vector,i));\n\t\t\t}\n\t\t}\n\t}\n\n\t/* Construct vectors P and Q */\n\tgsl_vector *cp = gsl_vector_calloc(3);\n\tgsl_vector *cq = gsl_vector_calloc(3);\n\tgsl_vector_add_constant(cp,1);\n\tgsl_vector_add_constant(cq,1);\n\tgsl_vector *P = gsl_vector_alloc(1);\n\tgsl_vector *Q = gsl_vector_alloc(1);\n\tgsl_vector_set(P,0,1);\n\tgsl_vector_set(Q,0,1);\n\tfor(i=0;i<fi_p->size;i++) {\n\t\tgsl_vector_set(cp,1,-2*cos(gsl_vector_get(fi_p,i)));\n\t\tP = Conv(P,cp);\n\t}\n\tif((l-1)/2 > 0) {\n\t\tfor(i=0;i<fi_q->size;i++) {\n\t\t\tgsl_vector_set(cq,1,-2*cos(gsl_vector_get(fi_q,i)));\n\t\t\tQ = Conv(Q,cq);\n\t\t}\n\t}\n\n\t/* Add trivial zeros */\n\tif(l%2 == 0) {\n\t\tgsl_vector *conv = gsl_vector_calloc(2);\n\t\tgsl_vector_add_constant(conv,1);\n\t\tP = Conv(P,conv);\n\t\tgsl_vector_set(conv,0,-1);\n    \tQ = Conv(Q,conv);\n    \tgsl_vector_free(conv);\n\t} else {\n\t\tgsl_vector *conv = gsl_vector_calloc(3);\n\t\tgsl_vector_set(conv,0,-1);\n\t\tgsl_vector_set(conv,2,1);\n\t\tQ = Conv(Q,conv);\n\t\tgsl_vector_free(conv);\n\t}\n\n\t/* Construct polynomial */\n\tfor(i=1;i<P->size;i++) {\n\t\tgsl_vector_set(poly,P->size-i-1,0.5*(gsl_vector_get(P,i)+gsl_vector_get(Q,i)));\n\t}\n\n\t/* Free memory */\n\tgsl_vector_free(lsf_vector);\n\tgsl_vector_free(fi_p);\n\tif((l-1)/2 > 0)\n\t\tgsl_vector_free(fi_q);\n\tgsl_vector_free(cp);\n\tgsl_vector_free(cq);\n\tgsl_vector_free(P);\n\tgsl_vector_free(Q);\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n/**\n * Function Conv\n *\n * Convolve two vectors\n *\n * @param conv1\n * @param conv2\n */\ngsl_vector *Conv(gsl_vector *conv1, gsl_vector *conv2) {\n\n\tint i,j,n = conv2->size;\n\tdouble sum;\n\tgsl_vector *result = gsl_vector_alloc(conv1->size+conv2->size-1);\n\tgsl_vector *temp = gsl_vector_calloc(conv1->size+conv2->size-1);\n\n\t/* Set coefficients to temp */\n\tfor(i=0;i<conv1->size;i++) {\n\t\tgsl_vector_set(temp,i,gsl_vector_get(conv1,i));\n\t}\n\n\t/* FIR-filter (Convolution) */\n\tfor(i=0;i<temp->size;i++) {\n\t\tsum = 0;\n\t\tfor(j=0; j<=GSL_MIN(i, n-1); j++) {\n\t\t\tsum += gsl_vector_get(temp, i-j)*gsl_vector_get(conv2,j);\n\t\t}\n\t\tgsl_vector_set(result, i, sum);\n\t}\n\n\t/* Free memory */\n\tgsl_vector_free(temp);\n\tgsl_vector_free(conv1);\n\n\treturn result;\n}\n\n\n\n\n\n\n\n\n\n\n/**\n * Function Postfilter\n *\n * Postfilter LSFs\n *\n * @param LSF\n * @param params\n */\nvoid Postfilter(gsl_matrix *LSF, PARAM *params) {\n\n\tif(params->postfilter_method == POSTFILTER_ID_LSF)\n\t\tLSF_Postfilter(LSF,params->postfilter_alpha);\n\telse if(params->postfilter_method == POSTFILTER_ID_LPC) {\n\t\tLPC_Postfilter(LSF, params->postfilter_alpha, params->frame_length);\n\t\tSmooth_matrix(LSF,3);\n\t}\n}\n\n\n\n\n\n\n\n\n\n/**\n * Function LSF_Postfilter\n *\n * Apply formant enhancement to LSFs\n *\n * @param lsf LSF-matrix\n * @param alpha postfilter coefficient alpha\n */\nvoid LSF_Postfilter(gsl_matrix *lsf, double alpha) {\n\n\tif(alpha > 0) {\n\t\tint i,j;\n\t\tdouble d[lsf->size2-1];\n\t\tfor(i=0;i<lsf->size1;i++) {\n\t\t\tfor(j=0;j<lsf->size2-1;j++) {\n\t\t\t\td[j] = alpha*(gsl_matrix_get(lsf,i,j+1) - gsl_matrix_get(lsf,i,j));\n\t\t\t\tif(j>0) {\n\t\t\t\t\tgsl_matrix_set(lsf,i,j, gsl_matrix_get(lsf,i,j-1) + d[j-1] + (pow(d[j-1],2)/(pow(d[j-1],2) + pow(d[j],2))) * ( gsl_matrix_get(lsf,i,j+1) - gsl_matrix_get(lsf,i,j-1) - d[j] - d[j-1] ) );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\n\n\n/**\n * Function LPC_Postfilter\n *\n * Enhance Formants by modifying the re-evaluated the LPC power spectrum,\n * and evaluating the LPC-coefficients again\n *\n * @param LSF pointer to the LSF matrix\n * @param gamma enhancement coefficient\n * @param frame_length\n */\nvoid LPC_Postfilter(gsl_matrix *LSF, double gamma, int frame_length) {\n\n\tint i,j,fi,s,nf,p = LSF->size2,n = POWER_SPECTRUM_FRAME_LEN;\n\tdouble A[n];\n\tdouble B[n];\n\tdouble data[n];\n\tgsl_vector *a = gsl_vector_alloc(p+1);\n\tgsl_vector *a_temp = gsl_vector_calloc(p);\n\tgsl_vector *r = gsl_vector_alloc(p+1);\n\tgsl_vector *rr = gsl_vector_alloc(n);\n\tgsl_vector *S = gsl_vector_alloc(n);\n\tgsl_vector *b = gsl_vector_alloc(p);\n\tgsl_matrix *R = gsl_matrix_alloc (p, p);\n\tgsl_vector *formants = gsl_vector_calloc(100);\n\tgsl_permutation *perm = gsl_permutation_alloc(p);\n\tgsl_complex ca;\n\tgsl_complex cb;\n\tgsl_fft_real_wavetable *wreal = gsl_fft_real_wavetable_alloc(n);\n\tgsl_fft_real_workspace *work = gsl_fft_real_workspace_alloc(n);\n\tgsl_fft_complex_wavetable *cwt = gsl_fft_complex_wavetable_alloc(n);\n\tgsl_fft_complex_workspace *cwork = gsl_fft_complex_workspace_alloc(n);\n\tdouble xa[2*n];\n\tdouble xb[2*n];\n\n\t/* Initialize B */\n\tB[0] = 1;\n\tfor(i=1;i<n;i++)\n\t\tB[i] = 0;\n\tgsl_fft_real_transform(B,1,n,wreal,work);\n\tgsl_complex_packed_array complex_coefficients_b = xb;\n\tgsl_fft_halfcomplex_unpack(B,complex_coefficients_b,1,n);\n\n\t/* Loop for every index of the LSF matrix */\n\tfor(fi=0;fi<LSF->size1;fi++) {\n\n\t\t/* Convert LSF to LPC */\n\t\tlsf2poly(LSF,a,fi,1);\n\n\t\t/* Evaluate power spectrum S, this assumes an all-pole model (B = 1) */\n\t\tfor(i=0;i<p+1;i++)\n\t\t\tA[i] = gsl_vector_get(a,i);\n\t\tfor(i=p+1;i<n;i++)\n\t\t\tA[i] = 0;\n\t\tgsl_fft_real_transform(A,1,n,wreal,work);\n\t\tgsl_complex_packed_array complex_coefficients_a = xa;\n\t\tgsl_fft_halfcomplex_unpack(A,complex_coefficients_a,1,n);\n\t\tfor(i=0;i<n;i++) {\n\t\t\tGSL_SET_COMPLEX(&ca, REAL(complex_coefficients_a,i), IMAG(complex_coefficients_a,i));\n\t\t\tGSL_SET_COMPLEX(&cb, REAL(complex_coefficients_b,i), IMAG(complex_coefficients_b,i));\n\t\t\tca = gsl_complex_div(cb, ca);\n\t\t\tgsl_vector_set(S,i,gsl_complex_abs2(ca));\n\t\t}\n\n\t\t/* Modification of the power spectrum S */\n\t\tGetFormants(S,formants,&nf);\n\t\tModPowerSpectrum(S,formants,nf,gamma);\n\n\t\t/* Construct autocorrelation r */\n\t\tfor(i=0;i<n;i++)\n\t\t\tdata[i] = gsl_vector_get(S,i);\n\t\tgsl_fft_real_unpack(data, complex_coefficients_a, 1, n);\n\n\t\tgsl_fft_complex_inverse(complex_coefficients_a, 1, n, cwt, cwork);\n\t\tfor(i=0;i<2*n;i = i + 2)\n\t\t\tgsl_vector_set(rr,i/2,xa[i]);\n\t\tfor(i=0;i<p+1;i++)\n\t\t\tgsl_vector_set(r,i,gsl_vector_get(rr,i));\n\n\t\t/* Construct LPC */\n\t\tfor(i=0; i<p;i++)\n\t\t\tfor(j=0; j<p; j++)\n\t\t\t\tgsl_matrix_set(R, i, j, gsl_vector_get(r, abs(i-j)));\n\t\tfor(i=1; i<p+1; i++)\n\t\t\tgsl_vector_set(b, i-1, gsl_vector_get(r, i));\n\t\tgsl_linalg_LU_decomp(R, perm, &s);\n\t\tgsl_linalg_LU_solve(R, perm, b, a_temp);\n\t\tfor(i=1; i<a->size; i++)\n\t\t\tgsl_vector_set(a, i, (-1.0)*gsl_vector_get(a_temp, i-1));\n\t\tgsl_vector_set(a, 0, 1);\n\t\tfor(i=0;i<a->size;i++)\n\t\t\tif(gsl_isnan(gsl_vector_get(a,i)))\n\t\t\t\tgsl_vector_set(a,i,0);\n\n\t\t/* Convert LPC back to LSF */\n\t\tConvert_to_LSF(LSF, a, fi);\n\t}\n\n\t/* Free memory */\n\tgsl_vector_free(formants);\n\tgsl_vector_free(a);\n\tgsl_vector_free(a_temp);\n\tgsl_vector_free(r);\n\tgsl_vector_free(rr);\n\tgsl_vector_free(S);\n\tgsl_vector_free(b);\n\tgsl_matrix_free(R);\n\tgsl_permutation_free(perm);\n\tgsl_fft_real_wavetable_free(wreal);\n\tgsl_fft_real_workspace_free(work);\n\tgsl_fft_complex_wavetable_free(cwt);\n\tgsl_fft_complex_workspace_free(cwork);\n}\n\n\n\n\n\n\n/**\n * Function ModPowerSpectrum\n *\n * Modify power spectrum in order to enhance formants\n *\n * @param s pointer to power spectrum vector\n * @param gamma enhancement coefficient\n */\nvoid ModPowerSpectrum(gsl_vector *s, gsl_vector *formants, int n, double gamma) {\n\n\tint i,j;\n\n\t/* Nonlinearity in power reduction depending on the width of the valley */\n\tdouble l = 150.0;\n\tdouble d = 40.0;\n\tdouble add = 0.5 + gamma;\n\tdouble c = 0.5;\n\tint dist;\n\tdouble mod;\n\n\t/* Modify spectrum between zero and the first formant */\n\tdist = gsl_vector_get(formants,0);\n\tmod = c*(-1.0/(1.0 + exp((-dist+l)/d))) + add;\n\tfor(i=0;i<gsl_vector_get(formants,0) - POWER_SPECTRUM_WIN;i++)\n\t\tgsl_vector_set(s,i,gsl_vector_get(s,i)*gamma);\n\n\t/* Modify spectrum between the last formant and FS/2 */\n\tdist = floor(s->size/2)-gsl_vector_get(formants,n-1);\n\tmod = c*(-1.0/(1.0 + exp((-dist+l)/d))) + add;\n\tfor(i=gsl_vector_get(formants,n-1) + POWER_SPECTRUM_WIN+1;i<s->size/2+1;i++)\n\t\tgsl_vector_set(s,i,gsl_vector_get(s,i)*gamma);\n\n\t/* Modify spectrum within a constant number of bins from the formant peaks */\n\tfor(i=0;i<n-1;i++) {\n\t\tdist = gsl_vector_get(formants,i+1) - gsl_vector_get(formants,i);\n\t\tmod = c*(-1.0/(1.0 + exp((-dist+l)/d))) + add;\n\t\tfor(j=gsl_vector_get(formants,i) + POWER_SPECTRUM_WIN+1;j<gsl_vector_get(formants,i+1) - POWER_SPECTRUM_WIN;j++)\n\t\t\tgsl_vector_set(s,j,gsl_vector_get(s,j)*gamma);\n\t}\n\n\t/* Reconstruct image spectrum */\n\tif((s->size)%2 == 0)\n\t\tfor(i=1;i<s->size/2;i++)\n\t\t\tgsl_vector_set(s,s->size-i,gsl_vector_get(s,i));\n\telse\n\t\tfor(i=1;i<ceil(s->size/2)+1;i++)\n\t\t\tgsl_vector_set(s,s->size-i,gsl_vector_get(s,i));\n}\n\n\n\n\n\n\n\n/**\n * Function GetFormants\n *\n * Get formant positions from smooth power spectrum\n *\n * @param s pointer to power spectrum vector\n * @param formants pointer to forman position vector\n */\nvoid GetFormants(gsl_vector *s, gsl_vector *formants, int *n) {\n\n\tint i,ind;\n\tgsl_vector *sd = gsl_vector_alloc(s->size);\n\n\t/* Differentiate s */\n\tgsl_vector_memcpy(sd,s);\n\tDifferentiate_noleak(sd);\n\n\t/* Find formant peaks */\n\tind = 0;\n\tfor(i=0;i<round(s->size/2)+1;i++) {\n\t\tif(gsl_vector_get(sd,i) >= 0 && gsl_vector_get(sd,i+1) <= 0) {\n\t\t\tgsl_vector_set(formants,ind,i);\n\t\t\tind++;\n\t\t}\n\t}\n\n\t/* Set the number of formants */\n\t(*n) = ind;\n\n\t/* Free memory */\n\tgsl_vector_free(sd);\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n/**\n * Function Hp_filt_f0\n *\n * High-pass filter speech below F0\n *\n * @param signal speech\n * @param fundf F0\n *\n */\nvoid Hp_filt_below_f0(gsl_vector *signal, gsl_vector *fundf, PARAM *params) {\n\n\tif(params->hpfiltf0 == 0)\n\t\treturn;\n\n\tint i,j,fnumber,use_hmm = 0,filter_update_interval = 1;\n\tdouble f0 = 0,lambda = 0,weight;\n\n\t/* Filter cut-off frequencies */\n\tdouble f[25] = {0,40,60,80,100,120,140,160,180,200,220,240,260,280,300,320,340,360,380,400,420,440,460,480,500};\n\n\t/* Denominator filter coefficients */\n\tdouble lsfa[24][7] =    {{0.012270374463510,   0.015772995424344,   0.024530703714270,   0.080413887423843,   0.400306289905254,   1.168999898025715,   2.132579893858550},\n\t\t\t\t\t\t\t {0.017920282072328,   0.022791623836745,   0.029864786258385,   0.055369341235469,   0.250523957519273,   1.092123690431822,   2.105116976227308},\n\t   \t\t\t\t\t     {0.021801057749634,   0.028684712190248,   0.034646162981531,   0.057546773586775,   0.246163207189489,   1.093903629649360,   2.108370657386230},\n\t   \t\t\t\t\t     {0.030330579315104,   0.038234559055245,   0.050121987909179,   0.091732027364528,   0.329220914237973,   1.125584823436989,   2.116231821108477},\n\t   \t\t\t\t\t     {0.034811643040824,   0.044349408406948,   0.053516371808008,   0.087458975943472,   0.308231588488585,   1.118896822551608,   2.116399287588925},\n\t   \t\t\t\t\t     {0.043917420002783,   0.054747497330268,   0.074390982686771,   0.143405359634844,   0.436338014468054,   1.182631435560068,   2.136140897442202},\n\t   \t\t\t\t\t     {0.045038897777332,   0.058258259000167,   0.068963787550062,   0.109221377061591,   0.344220168514159,   1.134851229904599,   2.124295109888979},\n\t   \t\t\t\t\t     {0.051022535502281,   0.065831379814600,   0.077573712097764,   0.121610480053570,   0.364861933549680,   1.146550846159653,   2.126584406920744},\n\t   \t\t\t\t\t     {0.057632798735370,   0.073608263773643,   0.086404993167967,   0.134181910858372,   0.384477060556410,   1.154156703313648,   2.134888076326625},\n\t   \t\t\t\t\t     {0.064123563307627,   0.081389884334947,   0.095130140196939,   0.146329709620344,   0.403020870485622,   1.163653230220413,   2.139554601837831},\n\t   \t\t\t\t\t     {0.070489123224552,   0.089082609042766,   0.103643756411925,   0.157832024397575,   0.420045784848692,   1.172254221962511,   2.139045944360825},\n\t   \t\t\t\t\t     {0.076847236579249,   0.096765479627175,   0.112050759011413,   0.168910344402175,   0.436071212884462,   1.181903820775476,   2.140464848942151},\n\t   \t\t\t\t\t     {0.083670629006476,   0.104607866948277,   0.120599031060558,   0.180042602015452,   0.451542294904885,   1.189290523546819,   2.144017570035968},\n\t   \t\t\t\t\t     {0.089932593812542,   0.112338083896512,   0.128836675422754,   0.190418798017626,   0.465709447605648,   1.200408605940246,   2.144702419538647},\n\t   \t\t\t\t\t     {0.097482721230326,   0.120403139593136,   0.137524292415345,   0.201381669315467,   0.480314653853837,   1.205081242188550,   2.149181575561907},\n\t   \t\t\t\t\t     {0.104600479029988,   0.128368705707085,   0.145929375571240,   0.211617389775297,   0.493657999260862,   1.212296579325581,   2.151596677897734},\n\t   \t\t\t\t\t     {0.112590768888632,   0.136542902549503,   0.154586373033906,   0.222085490310900,   0.506940958793273,   1.217511577523374,   2.163600455800026},\n\t   \t\t\t\t\t     {0.120305856730245,   0.144659614898539,   0.163016448320984,   0.231948743065545,   0.519466412869994,   1.224899556795356,   2.172566273838793},\n\t   \t\t\t\t\t     {0.126196196114728,   0.152429039122201,   0.170619462400073,   0.240153856910034,   0.529226373592494,   1.235527230693612,   2.155469675089261},\n\t   \t\t\t\t\t     {0.135957950019333,   0.160953029397963,   0.179571203980533,   0.250426168574974,   0.541985366804235,   1.235994160018460,   2.179609273087876},\n\t   \t\t\t\t\t     {0.144100745276714,   0.169162818316366,   0.187753461107828,   0.259137041396872,   0.552306542274397,   1.240620073961813,   2.183055012971304},\n\t   \t\t\t\t\t     {0.152457690627618,   0.177406803994366,   0.195849185376123,   0.267429744429561,   0.561963473760917,   1.244674940290760,   2.186392580112432},\n\t   \t\t\t\t\t     {0.161053099588424,   0.185684023980750,   0.203849642456801,   0.275267011545265,   0.570885488302771,   1.248003394526696,   2.189775517375000},\n\t   \t\t\t\t\t     {0.169933394492268,   0.193993666339236,   0.211740771952925,   0.282593310976812,   0.579087806020812,   1.250410947768047,   2.193033533970162}};\n\n\t/* Numerator filter coefficients */\n\tdouble lsfb[24][5] =    {{0.000030707852178,   0.003290687909261,   0.008730452554971,   0.008758594958107,   0.638065301730947},\n\t\t\t   \t\t\t\t {0.000345919101634,   0.007464820245500,   0.013446868902239,   0.013524918943862,   0.252043490985464},\n\t\t\t\t\t\t\t {0.009337032323646,   0.012733180521797,   0.018752843006707,   0.018887151908989,   0.124438874030317},\n\t\t\t   \t\t\t     {0.001750143943771,   0.014695620878432,   0.023413418898011,   0.023932233792984,   0.348241402501227},\n\t\t\t\t\t\t\t {0.007451258505131,   0.023588219512075,   0.028822776612533,   0.029638359563087,   0.209598248087015},\n\t\t\t   \t\t\t     {0.001262844775076,   0.019228486757771,   0.034126483729823,   0.034313458775845,   0.533669297472435},\n\t\t\t\t   \t\t\t {0.003966950786406,   0.027567085337588,   0.030762627018637,   0.041065592365883,   0.041079101614055},\n\t\t\t\t   \t\t\t {0.007300878835979,   0.031740322902411,   0.031817781139977,   0.047113960631324,   0.047413638436212},\n\t\t\t\t\t   \t\t {0.013297800640636,   0.036151790887025,   0.037029955814879,   0.053378560084371,   0.053478127353236},\n\t\t\t\t\t   \t\t {0.004245482517036,   0.040719988302241,   0.041791183344858,   0.059844792535173,   0.059931017064342},\n                             {0.013325335393929,   0.045481683243416,   0.046722772464647,   0.066520788321735,   0.066692797195485},\n\t                         {0.011043680418257,   0.050443635379848,   0.052305089861292,   0.073408015773066,   0.073456841095412},\n                             {0.010460216064980,   0.055656179782247,   0.056019990537994,   0.080510475101328,   0.080529142221492},\n\t                         {0.005042256738375,   0.060986479133597,   0.061700727238748,   0.087811525503098,   0.087832573628210},\n                             {0.021201154212601,   0.066716566424458,   0.070923784343375,   0.095350487083348,   0.095396267816331},\n\t                         {0.021743620358827,   0.072604498913997,   0.080230354225900,   0.103093601812379,   0.103095461338701},\n                             {0.010361144083279,   0.078885501870204,   0.081497400090665,   0.111068522558155,   0.111953788509510},\n\t                         {0.035482770544817,   0.085365388042439,   0.094373216452207,   0.119258245225241,   0.119606909976157},\n                             {0.008760915951485,   0.091788399421470,   0.093320007127655,   0.127626103353867,   0.127670078949185},\n\t                         {0.014865429114325,   0.099220356759925,   0.099842903153314,   0.136297513507208,   0.136872182683673},\n                             {0.010181473814981,   0.106654721678083,   0.107407671710693,   0.145160461404689,   0.145544940575618},\n\t                         {0.013092604335205,   0.114476964121103,   0.116199737975443,   0.154255878946170,   0.154357148101622},\n                             {0.019538269162167,   0.122717547053384,   0.127482889764472,   0.163581821500224,   0.164070219003255},\n\t\t\t\t\t\t\t {0.006517570557916,   0.131457491434920,   0.135046228721468,   0.173152990621689,   0.173468137485191}};\n\n\t/* Allocate filter matrices */\n\tgsl_matrix *LSFA = gsl_matrix_alloc(fundf->size,7);\n\tgsl_matrix *LSFB = gsl_matrix_alloc(fundf->size,5);\n\n\t/* Find appropriate filter coefficients according to F0 */\n\tfor(i=0;i<fundf->size;i++) {\n\n\t\t/* Fundamental frequency */\n\t\tif(gsl_vector_get(fundf,i) != 0)\n\t\t\tf0 = gsl_vector_get(fundf,i);\n\t\telse\n\t\t\tf0 = 40;\n\n\t\t/* Search for nearest upper cut-off frequency */\n\t\tfnumber = 0;\n\t\twhile(f[fnumber] < f0 && fnumber != 24)\n\t\t\tfnumber++;\n\n\t\t/* Determine weight */\n\t\tif(fnumber == 0)\n\t\t\tweight = 1;\n\t\telse if(fnumber == 24)\n\t\t\tweight = 0;\n\t\telse\n\t\t\tweight = (f[fnumber]-f0)/(f[fnumber]-f[fnumber-1]);\n\n\t\t/* Interpolate between two filters */\n\t\tfor(j=0;j<LSFA->size2;j++)\n\t\t\tgsl_matrix_set(LSFA, i, j, weight*lsfa[GSL_MAX(fnumber-2,0)][j] + (1.0-weight)*lsfa[GSL_MAX(fnumber-1,0)][j]);\n\t\tfor(j=0;j<LSFB->size2;j++)\n\t\t\tgsl_matrix_set(LSFB, i, j, weight*lsfb[GSL_MAX(fnumber-2,0)][j] + (1.0-weight)*lsfb[GSL_MAX(fnumber-1,0)][j]);\n\t}\n\n\t/* Initialize filter */\n\tint q,mlen;\n\tlong int o;\n\tdouble xr,x,ffr,tmpr,Bb;\n\tdouble *sigma;\n\tlong int len = signal->size;\n\tint bdim = LSFA->size2 + 1;\n\tint adim = LSFB->size2 + 1;\n\tdouble *Ar = (double *)calloc(adim,sizeof(double));\n\tdouble *Br = (double *)calloc(bdim,sizeof(double));\n\tdouble *ynr = (double *)calloc(signal->size,sizeof(double));\n\tdouble *rsignal = (double *)calloc(signal->size,sizeof(double));\n\tdouble *rmem = (double *)calloc((bdim+2),sizeof(double));\n\tgsl_vector *A = gsl_vector_alloc(adim);\n\tgsl_vector *B = gsl_vector_alloc(bdim);\n\tgsl_matrix *LSFA_i = gsl_matrix_alloc(params->signal_length,LSFA->size2);\n\tgsl_matrix *LSFB_i = gsl_matrix_alloc(params->signal_length,LSFB->size2);\n\n\t/* Smooth and interpolate */\n\tSmooth_interp_lsf(LSFA_i,LSFA,len,use_hmm,5);\n\tSmooth_interp_lsf(LSFB_i,LSFB,len,use_hmm,5);\n\n\t/* Set signal to array */\n\tfor(i=0;i<len;i++) {\n\t\trsignal[i] = gsl_vector_get(signal,i);\n\t}\n\n\t/* Initialize */\n\tsigma = NFArray(bdim+2);\n\tBb = 0;\n\tif(adim >= bdim)\n\t\tmlen = adim;\n\telse\n\t\tmlen = bdim + 1;\n\n\t/* Warped filtering */\n\tfor(o=0;o<len;o++) {\n\n\t\t/* Update filter coefficients */\n\t\tif(o%filter_update_interval == 0) {\n\t\t\tlsf2poly(LSFA_i,B,o,params->use_hmm);\n\t\t\tlsf2poly(LSFB_i,A,o,params->use_hmm);\n\t\t\tfor(i=0;i<adim;i++)\n\t\t\t\tAr[i] = gsl_vector_get(A,i);\n\t\t\tfor(i=0;i<bdim;i++)\n\t\t\t\tBr[i] = gsl_vector_get(B,i);\n\t\t\talphas2sigmas(Br,sigma,lambda,bdim-1);\n\t\t\tBb = 1/Br[0];\n\t\t}\n\n\t\txr = rsignal[o]*Bb;\n\n\t\t/* Update feedbackward sum */\n\t\tfor(q=0;q<bdim;q++) {\n\t\t\txr -= sigma[q]*rmem[q];\n\t\t}\n\t\txr = xr/sigma[bdim];\n\t\tx = xr*Ar[0];\n\n\t\t/* Update inner states */\n\t\tfor(q=0;q<mlen;q++) {\n\t\t\ttmpr = rmem[q] + lambda*(rmem[q+1] - xr);\n\t\t\trmem[q] = xr;\n\t\t\txr = tmpr;\n\t\t}\n\n\t\t/* Update feedforward sum */\n\t\tfor(q=0,ffr=0.0;q<adim-1;q++) {\n\t\t\tffr += Ar[q+1]*rmem[q+1];\n\t\t}\n\n\t   /* Update output */\n\t   ynr[o] = x + ffr;\n\t}\n\n\t/* Set output to vector */\n\tfor(i=0;i<len;i++) {\n\t\tgsl_vector_set(signal,i,ynr[i]);\n\t}\n\n\t/* Free memory */\n\tfree(ynr);\n\tfree(rsignal);\n\tfree(Ar);\n\tfree(Br);\n\tfree(rmem);\n\tfree(sigma);\n\tgsl_vector_free(A);\n\tgsl_vector_free(B);\n\tgsl_matrix_free(LSFA);\n\tgsl_matrix_free(LSFB);\n\tgsl_matrix_free(LSFA_i);\n\tgsl_matrix_free(LSFB_i);\n}\n\n\n\n\n\n\n\n\n\n\n\n/**\n * Function Evaluate_matrix_std\n *\n * Evaluate standard deviations of matrix\n *\n * @param std vector\n * @param data matrix\n */\nvoid Evaluate_matrix_std(gsl_vector *std, gsl_matrix *data) {\n\n\tint i,j;\n\tgsl_vector *mean = gsl_vector_calloc(data->size2);\n\n    /* Evaluate mean and std of matrix data */\n    for(i=0;i<data->size2;i++)\n    \tfor(j=0;j<data->size1;j++)\n    \t\tgsl_vector_set(mean,i,gsl_vector_get(mean,i) + gsl_matrix_get(data,j,i));\n    for(i=0;i<data->size2;i++)\n    \tgsl_vector_set(mean,i,gsl_vector_get(mean,i)/data->size1);\n    for(i=0;i<data->size2;i++)\n\t\tfor(j=0;j<data->size1;j++)\n\t\t\tgsl_vector_set(std,i,gsl_vector_get(std,i) + powf(gsl_matrix_get(data,j,i)-gsl_vector_get(mean,i),2));\n    for(i=0;i<data->size2;i++)\n\t\tgsl_vector_set(std,i,sqrt(gsl_vector_get(std,i)/(data->size1-1)));\n\n    /* Free memory */\n    gsl_vector_free(mean);\n}\n\n\n\n/**\n * Function Evaluate_vector_std\n *\n * Evaluate standard deviation of vector\n *\n * @param std\n * @param data\n */\nvoid Evaluate_vector_std(gsl_vector *std, gsl_vector *data) {\n\n\tint i;\n\tdouble mean = 0;\n\n    /* Evaluate mean and std of vector data */\n    for(i=0;i<data->size;i++)\n\t\tmean += gsl_vector_get(data,i);\n    mean = mean/data->size;\n    for(i=0;i<data->size;i++)\n    \tgsl_vector_set(std,0,gsl_vector_get(std,0) + powf(gsl_vector_get(data,i)-mean,2));\n\tgsl_vector_set(std,0,sqrt(gsl_vector_get(std,0)/(data->size-1)));\n}\n\n\n\n\n\n\n\n\n\n\n/**\n * Function ReadFileDouble\n *\n * Read double values from file\n *\n * @param name filename\n * @return vector containing the values\n */\ngsl_vector *ReadFileDouble(char *name) {\n\n\tFILE *file;\n\tint fileLen,n,i;\n\n\t/* Open file */\n\tfile = fopen(name, \"rb\"); // Open as binary\n\tif(!file) {\n\t\tprintf(\"Error opening file %s: %s\\n\", name, strerror(errno));\n\t\treturn NULL;\n\t}\n\n\t/* Get file length */\n\tfseek(file, 0, SEEK_END);\n\tfileLen = ftell(file);\n\tfseek(file, 0, SEEK_SET);\n\n\t/* Allocate memory */\n\tdouble *buffer = (double *)malloc(fileLen);\n\tif(!buffer) {\n\t\tprintf(\"Memory error!\\n\");\n        fclose(file);\n\t\treturn NULL;\n\t}\n\n\t/* Read file contents into buffer */\n\tn = fread(buffer, fileLen, 1, file);\n\tfclose(file);\n\n\t/* Set values to vector */\n\tgsl_vector *vector = gsl_vector_calloc(fileLen/sizeof(double));\n\tfor(i=0;i<fileLen/sizeof(double);i++) {\n\t\tgsl_vector_set(vector,i,buffer[i]);\n\t}\n\tfree(buffer);\n\treturn vector;\n}\n\n\n\n\n\n/**\n * Function ReadFileFloat\n *\n * Read float values from file\n *\n * @param name filename\n * @return vector containing the values\n */\ngsl_vector *ReadFileFloat(char *name) {\n\n\tFILE *file;\n\tint fileLen,n,i;\n\n\t/* Open file */\n\tfile = fopen(name, \"rb\"); // Open as binary\n\tif(!file) {\n\t\tprintf(\"Error opening file %s: %s\\n\", name, strerror(errno));\n\t\treturn NULL;\n\t}\n\n\t/* Get file length */\n\tfseek(file, 0, SEEK_END);\n\tfileLen = ftell(file);\n\tfseek(file, 0, SEEK_SET);\n\n\t/* Allocate memory */\n\tfloat *buffer = (float *)malloc(fileLen);\n\tif(!buffer) {\n\t\tprintf(\"Memory error!\\n\");\n        fclose(file);\n\t\treturn NULL;\n\t}\n\n\t/* Read file contents into buffer */\n\tn = fread(buffer, fileLen, 1, file);\n\tfclose(file);\n\n\t/* Set values to vector */\n\tgsl_vector *vector = gsl_vector_calloc(fileLen/sizeof(float));\n\tfor(i=0;i<fileLen/sizeof(float);i++) {\n\t\tgsl_vector_set(vector,i,buffer[i]);\n\t}\n\tfree(buffer);\n\treturn vector;\n}\n\n\n\n\n\n\n\n\n\n\n/**\n * Function Gain_normalization\n *\n * Normalize the gain of a signal.\n * Result is saved in-place to vector signal\n *\n * @param signal input signal\n * @param gain gain vector\n * @param frame_length frame length in samples\n * @param shift shift length in samples\n * @param speed syntesis speed\n * @param pitch synthesis pitch\n * @param gain_threshold threshold for gain normalization\n *\n */\nvoid Gain_normalization(gsl_vector *signal,\n\t\t\t\t\t\tgsl_vector *gain,\n\t\t\t\t\t\tint frame_length,\n\t\t\t\t\t\tint shift,\n\t\t\t\t\t\tdouble speed,\n\t\t\t\t\t\tdouble pitch,\n\t\t\t\t\t\tdouble gain_threshold) {\n\n\tint i,j;\n\tdouble sum;\n\tgsl_vector *norm = gsl_vector_calloc(gain->size);\n\tgsl_vector *norm_i = gsl_vector_alloc(signal->size);\n\n\t/* Calculate gain normalization vector */\n\tfor(i=0;i<gain->size;i++) {\n\t\tsum = 0;\n\t\tfor(j=i*shift/speed;j<i*shift/speed+frame_length/speed;j++) {\n\t\t\tsum += pow(gsl_vector_get(signal,GSL_MIN(signal->size-1,j))*HANN(j-i*shift/speed,frame_length),2);\n\t\t}\n\t\tif(sum < gain_threshold) {sum = gain_threshold;}\n\t\tgsl_vector_set(norm,i,sqrt((E_REF*powf(10.0,gsl_vector_get(gain,i)/10.0))/sum));\n\t}\n\n\t/* Linear interpolation */\n\tInterpolate_lin(norm,norm_i);\n\n\t/* Set gain */\n\tfor(i=0;i<signal->size;i++) {\n\t\tgsl_vector_set(signal,i,gsl_vector_get(signal,i)*gsl_vector_get(norm_i,i));\n\t}\n\n\t/* Free memory */\n\tgsl_vector_free(norm);\n\tgsl_vector_free(norm_i);\n}\n\n\n\n\n\n/**\n * Function LSF_MOD\n *\n * Modify LSF matrix\n *\n * @param matrix matrix to be modified\n *\n */\nvoid LSF_MOD(gsl_matrix *lsf) {\n\n\tint i,j;\n\tdouble d = 1.4;\n\tfor(i=0;i<lsf->size1;i++) {\n\t\tfor(j=0;j<lsf->size2;j++) {\n\t\t\tgsl_matrix_set(lsf,i,j, gsl_matrix_get(lsf,i,j)/d);\n\t\t}\n\t}\n\tLSF_fix_matrix(lsf);\n}\n\n\n\n\n\n\n\n\n/**\n * Function Integrate_matrix\n *\n * Integrate matrix\n *\n * @param matrix matrix to be integrated\n *\n */\nvoid Integrate_matrix(gsl_matrix *matrix) {\n\n\tint i,j;\n\tfor(i=0;i<matrix->size1;i++)\n\t\tfor(j=1;j<matrix->size2;j++)\n\t\t\tgsl_matrix_set(matrix,i,j,gsl_matrix_get(matrix,i,j-1) + gsl_matrix_get(matrix,i,j));\n}\n\n\n/**\n * Function Integrate\n *\n * Integrate vector\n *\n * @param vector to be integrated\n *\n */\nvoid Integrate(gsl_vector *vector, double leak) {\n\n\tint i;\n\tfor(i=1;i<vector->size;i++)\n\t\tgsl_vector_set(vector,i,gsl_vector_get(vector,i-1)*leak + gsl_vector_get(vector,i));\n}\n\n\n\n/**\n * Function Free_pulselib_variables\n *\n * Free pulse library variables\n *\n * @param\n */\nvoid Free_pulselib_variables(gsl_matrix *pulses, gsl_matrix *pulses_rs, gsl_matrix *pwaveform, gsl_vector *pulse_lengths,\n\t\tgsl_matrix *plsf, gsl_matrix *ptilt, gsl_matrix *pharm, gsl_matrix *phnr, gsl_vector *pgain, gsl_vector *ph1h2,\n\t\tgsl_vector *pnaq, gsl_vector *pca_mean, gsl_matrix *pca_pc, gsl_matrix *pca_w_lib, gsl_vector *stoch_env, gsl_vector *stoch_sp, PARAM *params) {\n\n\t/* Do not free if pulse library is not in use */\n\tif(params->use_pulselib == 0)\n\t\treturn;\n\n\t/* Free pulse library */\n\tgsl_matrix_free(pulses);\n\tgsl_matrix_free(pulses_rs);\n\tgsl_vector_free(pulse_lengths);\n\tgsl_matrix_free(plsf);\n\tgsl_vector_free(pgain);\n\tif(params->use_waveform == 1) gsl_matrix_free(pwaveform);\n\tif(params->use_tilt == 1) gsl_matrix_free(ptilt);\n\tif(params->use_harmonics == 1) gsl_matrix_free(pharm);\n\tif(params->use_hnr == 1) gsl_matrix_free(phnr);\n\tif(params->use_h1h2 == 1) gsl_vector_free(ph1h2);\n\tif(params->use_naq == 1) gsl_vector_free(pnaq);\n\n\t/* Free pulse library pca parameters */\n\tif(params->use_pulselib_pca == 1) {\n\t\tgsl_vector_free(pca_mean);\n\t\tgsl_matrix_free(pca_pc);\n\t}\n\n\t/* Free pulse pca parameters */\n\tif(params->use_pulse_pca == 1)\n\t\tgsl_matrix_free(pca_w_lib);\n}\n\n\n\n\n\n\n\n/**\n * Function Free_variables\n *\n * Free synthesis variables\n *\n * @param\n */\nvoid Free_variables(gsl_vector *original_pulse, gsl_vector *excitation_voiced, gsl_vector *excitation_unvoiced, gsl_vector *fundf, gsl_vector *gain,\n\t\tgsl_vector *gain_new, gsl_matrix *LSF, gsl_matrix *LSF2, gsl_matrix *LSF_interp, gsl_matrix *glflowsp, gsl_matrix *glflowsp_new,\n\t\tgsl_matrix *hnr, gsl_matrix *hnr_new, gsl_matrix *harmonics, gsl_matrix *waveform, gsl_vector *h1h2, gsl_vector *naq,\n\t\tgsl_vector *resynthesis_pulse_index, gsl_vector *pulse_clus_id, gsl_matrix *pulse_clusters, gsl_matrix *pca_w, \n\t\tgsl_matrix **DNN_W, gsl_vector **input_minmax, gsl_vector *dnnpulseindices, gsl_vector *dnnpulses, PARAM *params) {\n\n\t/* Free variables */\n\tgsl_vector_free(original_pulse);\n\tgsl_vector_free(excitation_voiced);\n\tgsl_vector_free(excitation_unvoiced);\n\tgsl_vector_free(fundf);\n\tgsl_vector_free(gain);\n\tgsl_vector_free(gain_new);\n\tgsl_matrix_free(LSF);\n\tgsl_matrix_free(glflowsp_new);\n\tgsl_matrix_free(hnr_new);\n\tgsl_vector_free(resynthesis_pulse_index);\n\tif(LSF_interp != NULL) gsl_matrix_free(LSF_interp);\n\tif(params->use_tilt == 1 && glflowsp != NULL) gsl_matrix_free(glflowsp);\n\tif(params->use_hnr == 1 && hnr != NULL) gsl_matrix_free(hnr);\n\tif(params->use_harmonics == 1 && harmonics != NULL) gsl_matrix_free(harmonics);\n\tif(params->use_waveform == 1 && waveform != NULL) gsl_matrix_free(waveform);\n\tif(params->use_h1h2 == 1 && h1h2 != NULL) gsl_vector_free(h1h2);\n\tif(params->use_naq == 1 && naq != NULL) gsl_vector_free(naq);\n\tif(params->sep_vuv_spectrum == 1 && LSF2 != NULL) gsl_matrix_free(LSF2);\n\tif(params->pulse_clustering == 1) {\n\t\tif(pulse_clus_id != NULL) gsl_vector_free(pulse_clus_id);\n\t\tif(pulse_clusters != NULL)gsl_matrix_free(pulse_clusters);\n\t}\n\n\t/* Free pulse library PCA weights */\n\tif(params->use_pulselib_pca == 1)\n\t\tgsl_matrix_free(pca_w);\n\n\t/* Free DNN weights if used */\n\tint i;\n\tif(params->use_dnn_pulsegen == 1) {\n\t\tfor(i=0;i<params->dnn_weight_dims->size/2;i++)\n\t\t\tgsl_matrix_free(DNN_W[i]);\n\t\tgsl_vector_free(dnnpulseindices);\n\t\tgsl_vector_free(dnnpulses);\n\t\tif(params->dnn_input_normalized == 1)\n\t\t\tgsl_vector_free(input_minmax[0]);\n\t}\n\tfree(DNN_W);\n\tfree(input_minmax);\n\n\t/* Free variables in param */\n\tfor(i=0;i<params->synlistlen;i++)\n\t\tfree(params->synlist[i]);\n\tfree(params->synlist);\n\tfree(params->synlist_filename);\n\tfree(params->dnnpath);\n\tfree(params->pulse_filename);\n\tfree(params->pulselibrary_filename);\n\tgsl_vector_free(params->paramweights);\n\tgsl_vector_free(params->dnn_weight_dims);\n}\n\n\n\n\n\n\n\n/**\n * Function Save_excitation_to_wav\n *\n * Save excitation vector to wav file\n *\n * @param excitation vector\n * @param params parameters\n */\nvoid Save_excitation_to_wav(gsl_vector *excitation, PARAM *params) {\n\n\tif(params->write_excitation_to_wav == 1) {\n\t\tgsl_vector *temp = gsl_vector_alloc(excitation->size);\n\t\tgsl_vector_memcpy(temp,excitation);\n\t\tScale_signal(temp,SCALE_IF_GREATER_THAN_ONE);\n\t\tSave_signal_to_file(temp,params,FILENAME_ENDING_EXCITATION);\n\t\tgsl_vector_free(temp);\n\t}\n}\n\n\n\n\n\n\n\n/**\n * Function Normalize_pulse_library_var\n *\n * Normalize pulse library parameters according to synthesis parameters (normalize mean and variance)\n *\n * @param pulse lib params\n * @param synthesis params\n */\nvoid Normalize_pulse_library_var(gsl_matrix *plsf,gsl_matrix *ptilt,gsl_matrix *pharm,gsl_matrix *phnr,gsl_matrix *pwaveform,\n\t\tgsl_vector *pgain,gsl_vector *ph1h2,gsl_vector *pnaq,gsl_matrix *lsf,gsl_matrix *tilt,gsl_matrix *harm,gsl_matrix *hnr,\n\t\tgsl_matrix *waveform,gsl_vector *gain,gsl_vector *h1h2,gsl_vector *naq, gsl_vector *fundf,PARAM *params) {\n\n\t/* Exit if pulse library is not used */\n\tif(params->use_pulselib == 0)\n\t\treturn;\n\n\t/* Exit if normalization is not set on */\n\tif(params->normalize_pulselib == 0)\n\t\treturn;\n\n\t/* Exit if adaptation to pulse library parameters is set on */\n\tif(params->adapt_to_pulselib == 1) {\n\t\tprintf(\"Warning: Pulse library normalization and adaptation to pulse library parameters cannot be used simultaneously!\\n\");\n\t\treturn;\n\t}\n\n\t/* Initialize */\n\tint i,j,k;\n\tdouble mean_lib,mean_par,std_lib,std_par;\n\n\t/* Normalize LSF */\n\tfor(i=0;i<lsf->size2;i++) {\n\n\t\t/* Evaluate means */\n\t\tmean_par = 0;\n\t\tmean_lib = 0;\n\t\tfor(j=0;j<plsf->size1;j++)\n\t\t\tmean_lib += gsl_matrix_get(plsf,j,i);\n\t\tk = 0;\n\t\tfor(j=0;j<lsf->size1;j++) {\n\t\t\tif(gsl_vector_get(fundf,j) > 0) {\n\t\t\t\tmean_par += gsl_matrix_get(lsf,j,i);\n\t\t\t\tk++;\n\t\t\t}\n\t\t}\n\t\tmean_lib = mean_lib/plsf->size1;\n\t\tmean_par = mean_par/k;\n\n\t\t/* Evaluate standard deviations */\n\t\tstd_par = 0;\n\t\tstd_lib = 0;\n\t\tfor(j=0;j<plsf->size1;j++)\n\t\t\tstd_lib += (gsl_matrix_get(plsf,j,i)-mean_lib)*(gsl_matrix_get(plsf,j,i)-mean_lib);\n\t\tstd_lib = sqrt(std_lib/(plsf->size1-1));\n\t\tif(std_lib == 0)\n\t\t\tstd_lib = 1;\n\t\tk = 0;\n\t\tfor(j=0;j<lsf->size1;j++) {\n\t\t\tif(gsl_vector_get(fundf,j) > 0) {\n\t\t\t\tstd_par += (gsl_matrix_get(lsf,j,i)-mean_par)*(gsl_matrix_get(lsf,j,i)-mean_par);\n\t\t\t\tk++;\n\t\t\t}\n\t\t}\n\t\tstd_par = sqrt(std_par/(k-1));\n\t\tif(std_par == 0)\n\t\t\tstd_par = 1;\n\n\t\t/* Normalize */\n\t\tfor(j=0;j<plsf->size1;j++)\n\t\t\tgsl_matrix_set(plsf,j,i,(gsl_matrix_get(plsf,j,i)-mean_lib)/std_lib*std_par + mean_par);\n\t}\n\n\t/* Normalize LSFsource */\n\tfor(i=0;i<tilt->size2;i++) {\n\n\t\t/* Evaluate means */\n\t\tmean_par = 0;\n\t\tmean_lib = 0;\n\t\tfor(j=0;j<ptilt->size1;j++)\n\t\t\tmean_lib += gsl_matrix_get(ptilt,j,i);\n\t\tk = 0;\n\t\tfor(j=0;j<tilt->size1;j++) {\n\t\t\tif(gsl_vector_get(fundf,j) > 0) {\n\t\t\t\tmean_par += gsl_matrix_get(tilt,j,i);\n\t\t\t\tk++;\n\t\t\t}\n\t\t}\n\t\tmean_lib = mean_lib/ptilt->size1;\n\t\tmean_par = mean_par/k;\n\n\t\t/* Evaluate standard deviations */\n\t\tstd_par = 0;\n\t\tstd_lib = 0;\n\t\tfor(j=0;j<ptilt->size1;j++)\n\t\t\tstd_lib += (gsl_matrix_get(ptilt,j,i)-mean_lib)*(gsl_matrix_get(ptilt,j,i)-mean_lib);\n\t\tstd_lib = sqrt(std_lib/(ptilt->size1-1));\n\t\tif(std_lib == 0)\n\t\t\tstd_lib = 1;\n\t\tk = 0;\n\t\tfor(j=0;j<tilt->size1;j++) {\n\t\t\tif(gsl_vector_get(fundf,j) > 0) {\n\t\t\t\tstd_par += (gsl_matrix_get(tilt,j,i)-mean_par)*(gsl_matrix_get(tilt,j,i)-mean_par);\n\t\t\t\tk++;\n\t\t\t}\n\t\t}\n\t\tstd_par = sqrt(std_par/(k-1));\n\t\tif(std_par == 0)\n\t\t\tstd_par = 1;\n\n\t\t/* Normalize */\n\t\tfor(j=0;j<ptilt->size1;j++)\n\t\t\tgsl_matrix_set(ptilt,j,i,(gsl_matrix_get(ptilt,j,i)-mean_lib)/std_lib*std_par + mean_par);\n\t}\n\n\t/* Normalize HNR */\n\tfor(i=0;i<hnr->size2;i++) {\n\n\t\t/* Evaluate means */\n\t\tmean_par = 0;\n\t\tmean_lib = 0;\n\t\tfor(j=0;j<phnr->size1;j++)\n\t\t\tmean_lib += gsl_matrix_get(phnr,j,i);\n\t\tk = 0;\n\t\tfor(j=0;j<hnr->size1;j++) {\n\t\t\tif(gsl_vector_get(fundf,j) > 0) {\n\t\t\t\tmean_par += gsl_matrix_get(hnr,j,i);\n\t\t\t\tk++;\n\t\t\t}\n\t\t}\n\t\tmean_lib = mean_lib/phnr->size1;\n\t\tmean_par = mean_par/k;\n\n\t\t/* Evaluate standard deviations */\n\t\tstd_par = 0;\n\t\tstd_lib = 0;\n\t\tfor(j=0;j<phnr->size1;j++)\n\t\t\tstd_lib += (gsl_matrix_get(phnr,j,i)-mean_lib)*(gsl_matrix_get(phnr,j,i)-mean_lib);\n\t\tstd_lib = sqrt(std_lib/(phnr->size1-1));\n\t\tif(std_lib == 0)\n\t\t\tstd_lib = 1;\n\t\tk = 0;\n\t\tfor(j=0;j<hnr->size1;j++) {\n\t\t\tif(gsl_vector_get(fundf,j) > 0) {\n\t\t\t\tstd_par += (gsl_matrix_get(hnr,j,i)-mean_par)*(gsl_matrix_get(hnr,j,i)-mean_par);\n\t\t\t\tk++;\n\t\t\t}\n\t\t}\n\t\tstd_par = sqrt(std_par/(k-1));\n\t\tif(std_par == 0)\n\t\t\tstd_par = 1;\n\n\t\t/* Normalize */\n\t\tfor(j=0;j<phnr->size1;j++)\n\t\t\tgsl_matrix_set(phnr,j,i,(gsl_matrix_get(phnr,j,i)-mean_lib)/std_lib*std_par + mean_par);\n\t}\n\n\t/* Normalize Harmonics */\n\tif(params->use_harmonics == 1) {\n\t\tfor(i=0;i<hnr->size2;i++) {\n\n\t\t\t/* Evaluate means */\n\t\t\tmean_par = 0;\n\t\t\tmean_lib = 0;\n\t\t\tfor(j=0;j<pharm->size1;j++)\n\t\t\t\tmean_lib += gsl_matrix_get(pharm,j,i);\n\t\t\tk = 0;\n\t\t\tfor(j=0;j<harm->size1;j++) {\n\t\t\t\tif(gsl_vector_get(fundf,j) > 0) {\n\t\t\t\t\tmean_par += gsl_matrix_get(harm,j,i);\n\t\t\t\t\tk++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tmean_lib = mean_lib/pharm->size1;\n\t\t\tmean_par = mean_par/k;\n\n\t\t\t/* Evaluate standard deviations */\n\t\t\tstd_par = 0;\n\t\t\tstd_lib = 0;\n\t\t\tfor(j=0;j<pharm->size1;j++)\n\t\t\t\tstd_lib += (gsl_matrix_get(pharm,j,i)-mean_lib)*(gsl_matrix_get(pharm,j,i)-mean_lib);\n\t\t\tstd_lib = sqrt(std_lib/(pharm->size1-1));\n\t\t\tif(std_lib == 0)\n\t\t\t\tstd_lib = 1;\n\t\t\tk = 0;\n\t\t\tfor(j=0;j<harm->size1;j++) {\n\t\t\t\tif(gsl_vector_get(fundf,j) > 0) {\n\t\t\t\t\tstd_par += (gsl_matrix_get(harm,j,i)-mean_par)*(gsl_matrix_get(harm,j,i)-mean_par);\n\t\t\t\t\tk++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tstd_par = sqrt(std_par/(k-1));\n\t\t\tif(std_par == 0)\n\t\t\t\tstd_par = 1;\n\n\t\t\t/* Normalize */\n\t\t\tfor(j=0;j<pharm->size1;j++)\n\t\t\t\tgsl_matrix_set(pharm,j,i,(gsl_matrix_get(pharm,j,i)-mean_lib)/std_lib*std_par + mean_par);\n\t\t}\n\t}\n\n\t/* Normalize Waveform */\n\tif(params->use_waveform == 1) {\n\t\tfor(i=0;i<hnr->size2;i++) {\n\n\t\t\t/* Evaluate means */\n\t\t\tmean_par = 0;\n\t\t\tmean_lib = 0;\n\t\t\tfor(j=0;j<pwaveform->size1;j++)\n\t\t\t\tmean_lib += gsl_matrix_get(pwaveform,j,i);\n\t\t\tk = 0;\n\t\t\tfor(j=0;j<waveform->size1;j++) {\n\t\t\t\tif(gsl_vector_get(fundf,j) > 0) {\n\t\t\t\t\tmean_par += gsl_matrix_get(waveform,j,i);\n\t\t\t\t\tk++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tmean_lib = mean_lib/pwaveform->size1;\n\t\t\tmean_par = mean_par/k;\n\n\t\t\t/* Evaluate standard deviations */\n\t\t\tstd_par = 0;\n\t\t\tstd_lib = 0;\n\t\t\tfor(j=0;j<pwaveform->size1;j++)\n\t\t\t\tstd_lib += (gsl_matrix_get(pwaveform,j,i)-mean_lib)*(gsl_matrix_get(pwaveform,j,i)-mean_lib);\n\t\t\tstd_lib = sqrt(std_lib/(pwaveform->size1-1));\n\t\t\tif(std_lib == 0)\n\t\t\t\tstd_lib = 1;\n\t\t\tk = 0;\n\t\t\tfor(j=0;j<waveform->size1;j++) {\n\t\t\t\tif(gsl_vector_get(fundf,j) > 0) {\n\t\t\t\t\tstd_par += (gsl_matrix_get(waveform,j,i)-mean_par)*(gsl_matrix_get(waveform,j,i)-mean_par);\n\t\t\t\t\tk++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tstd_par = sqrt(std_par/(k-1));\n\t\t\tif(std_par == 0)\n\t\t\t\tstd_par = 1;\n\n\t\t\t/* Normalize */\n\t\t\tfor(j=0;j<pwaveform->size1;j++)\n\t\t\t\tgsl_matrix_set(pwaveform,j,i,(gsl_matrix_get(pwaveform,j,i)-mean_lib)/std_lib*std_par + mean_par);\n\t\t}\n\t}\n\n\t/* Normalize Gain */\n\tmean_lib = Mean(pgain);\n\tk = 0;\n\tmean_par = 0;\n\tfor(i=0;i<gain->size;i++) {\n\t\tif(gsl_vector_get(fundf,i) > 0) {\n\t\t\tmean_par += gsl_vector_get(gain,i);\n\t\t\tk++;\n\t\t}\n\t}\n\tmean_par = mean_par/k;\n\tstd_par = 0;\n\tstd_lib = 0;\n\tfor(j=0;j<pgain->size;j++)\n\t\tstd_lib += (gsl_vector_get(pgain,j)-mean_lib)*(gsl_vector_get(pgain,j)-mean_lib);\n\tstd_lib = sqrt(std_lib/(pgain->size-1));\n\tif(std_lib == 0)\n\t\tstd_lib = 1;\n\tk = 0;\n\tfor(j=0;j<gain->size;j++) {\n\t\tif(gsl_vector_get(fundf,j) > 0) {\n\t\t\tstd_par += (gsl_vector_get(gain,j)-mean_par)*(gsl_vector_get(gain,j)-mean_par);\n\t\t\tk++;\n\t\t}\n\t}\n\tstd_par = sqrt(std_par/(k-1));\n\tif(std_par == 0)\n\t\tstd_par = 1;\n\tgsl_vector_add_constant(pgain,-mean_lib);\n\tgsl_vector_scale(pgain, std_par/std_lib);\n\tgsl_vector_add_constant(pgain,mean_par);\n\n\t/* Normalize H1H2 */\n\tif(params->use_h1h2 == 1) {\n\t\tmean_lib = Mean(ph1h2);\n\t\tk = 0;\n\t\tmean_par = 0;\n\t\tfor(i=0;i<h1h2->size;i++) {\n\t\t\tif(gsl_vector_get(fundf,i) > 0) {\n\t\t\t\tmean_par += gsl_vector_get(h1h2,i);\n\t\t\t\tk++;\n\t\t\t}\n\t\t}\n\t\tmean_par = mean_par/k;\n\t\tstd_par = 0;\n\t\tstd_lib = 0;\n\t\tfor(j=0;j<ph1h2->size;j++)\n\t\t\tstd_lib += (gsl_vector_get(ph1h2,j)-mean_lib)*(gsl_vector_get(ph1h2,j)-mean_lib);\n\t\tstd_lib = sqrt(std_lib/(ph1h2->size-1));\n\t\tif(std_lib == 0)\n\t\t\tstd_lib = 1;\n\t\tk = 0;\n\t\tfor(j=0;j<h1h2->size;j++) {\n\t\t\tif(gsl_vector_get(fundf,j) > 0) {\n\t\t\t\tstd_par += (gsl_vector_get(h1h2,j)-mean_par)*(gsl_vector_get(h1h2,j)-mean_par);\n\t\t\t\tk++;\n\t\t\t}\n\t\t}\n\t\tstd_par = sqrt(std_par/(k-1));\n\t\tif(std_par == 0)\n\t\t\tstd_par = 1;\n\t\tgsl_vector_add_constant(ph1h2,-mean_lib);\n\t\tgsl_vector_scale(ph1h2, std_par/std_lib);\n\t\tgsl_vector_add_constant(ph1h2,mean_par);\n\t}\n\n\t/* Normalize NAQ */\n\tif(params->use_naq == 1) {\n\t\tmean_lib = Mean(pnaq);\n\t\tk = 0;\n\t\tmean_par = 0;\n\t\tfor(i=0;i<naq->size;i++) {\n\t\t\tif(gsl_vector_get(fundf,i) > 0) {\n\t\t\t\tmean_par += gsl_vector_get(naq,i);\n\t\t\t\tk++;\n\t\t\t}\n\t\t}\n\t\tmean_par = mean_par/k;\n\t\tstd_par = 0;\n\t\tstd_lib = 0;\n\t\tfor(j=0;j<pnaq->size;j++)\n\t\t\tstd_lib += (gsl_vector_get(pnaq,j)-mean_lib)*(gsl_vector_get(pnaq,j)-mean_lib);\n\t\tstd_lib = sqrt(std_lib/(pnaq->size-1));\n\t\tif(std_lib == 0)\n\t\t\tstd_lib = 1;\n\t\tk = 0;\n\t\tfor(j=0;j<naq->size;j++) {\n\t\t\tif(gsl_vector_get(fundf,j) > 0) {\n\t\t\t\tstd_par += (gsl_vector_get(naq,j)-mean_par)*(gsl_vector_get(naq,j)-mean_par);\n\t\t\t\tk++;\n\t\t\t}\n\t\t}\n\t\tstd_par = sqrt(std_par/(k-1));\n\t\tif(std_par == 0)\n\t\t\tstd_par = 1;\n\t\tgsl_vector_add_constant(pnaq,-mean_lib);\n\t\tgsl_vector_scale(pnaq, std_par/std_lib);\n\t\tgsl_vector_add_constant(pnaq,mean_par);\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n/**\n * Function Adapt_synthesis_parameters_var\n *\n * Adapt synthesis parameters according to pulse library parameters (normalize mean and var)\n *\n * @param pulse lib params\n * @param synthesis params\n */\nvoid Adapt_synthesis_parameters_var(gsl_matrix *plsf,gsl_matrix *ptilt,gsl_matrix *pharm,gsl_matrix *phnr,gsl_matrix *pwaveform,\n\t\tgsl_vector *pgain,gsl_vector *ph1h2,gsl_vector *pnaq,gsl_matrix *lsf,gsl_matrix *tilt,gsl_matrix *harm,gsl_matrix *hnr,\n\t\tgsl_matrix *waveform,gsl_vector *gain,gsl_vector *h1h2,gsl_vector *naq,gsl_vector *fundf,gsl_vector *pulse_lengths,PARAM *params) {\n\n\n\t/* Exit if pulse library is not used */\n\tif(params->use_pulselib == 0)\n\t\treturn;\n\n\t/* Exit if adaptation is not set on */\n\tif(params->adapt_to_pulselib == 0)\n\t\treturn;\n\n\t/* Exit if pulse library normalization is set on */\n\tif(params->normalize_pulselib == 1) {\n\t\tprintf(\"Warning: Pulse library normalization and adaptation to pulse library parameters cannot be used simultaneously!\\n\");\n\t\treturn;\n\t}\n\n\t/* Initialize */\n\tint i,j,k;\n\tdouble mean_lib,mean_par,std_lib,std_par;\n\n\t/* Normalize LSF */\n\tfor(i=0;i<lsf->size2;i++) {\n\n\t\t/* Evaluate means */\n\t\tmean_par = 0;\n\t\tmean_lib = 0;\n\t\tfor(j=0;j<plsf->size1;j++)\n\t\t\tmean_lib += gsl_matrix_get(plsf,j,i);\n\t\tk = 0;\n\t\tfor(j=0;j<lsf->size1;j++) {\n\t\t\tif(gsl_vector_get(fundf,j) > 0) {\n\t\t\t\tmean_par += gsl_matrix_get(lsf,j,i);\n\t\t\t\tk++;\n\t\t\t}\n\t\t}\n\t\tmean_lib = mean_lib/plsf->size1;\n\t\tmean_par = mean_par/k;\n\n\t\t/* Evaluate standard deviations */\n\t\tstd_par = 0;\n\t\tstd_lib = 0;\n\t\tfor(j=0;j<plsf->size1;j++)\n\t\t\tstd_lib += (gsl_matrix_get(plsf,j,i)-mean_lib)*(gsl_matrix_get(plsf,j,i)-mean_lib);\n\t\tstd_lib = sqrt(std_lib/(plsf->size1-1));\n\t\tif(std_lib == 0)\n\t\t\tstd_lib = 1;\n\t\tk = 0;\n\t\tfor(j=0;j<lsf->size1;j++) {\n\t\t\tif(gsl_vector_get(fundf,j) > 0) {\n\t\t\t\tstd_par += (gsl_matrix_get(lsf,j,i)-mean_par)*(gsl_matrix_get(lsf,j,i)-mean_par);\n\t\t\t\tk++;\n\t\t\t}\n\t\t}\n\t\tstd_par = sqrt(std_par/(k-1));\n\t\tif(std_par == 0)\n\t\t\tstd_par = 1;\n\n\t\t/* Normalize */\n\t\tfor(j=0;j<lsf->size1;j++)\n\t\t\tif(gsl_vector_get(fundf,j) > 0)\n\t\t\t\tgsl_matrix_set(lsf,j,i,(gsl_matrix_get(lsf,j,i)-mean_par)/std_par*(std_lib*params->adapt_coeff + std_par*(1.0-params->adapt_coeff)) + params->adapt_coeff*mean_lib + (1.0-params->adapt_coeff)*mean_par);\n\t}\n\tLSF_fix_matrix(lsf);\n\n\t/* Normalize LSFsource */\n\tfor(i=0;i<tilt->size2;i++) {\n\n\t\t/* Evaluate means */\n\t\tmean_par = 0;\n\t\tmean_lib = 0;\n\t\tfor(j=0;j<ptilt->size1;j++)\n\t\t\tmean_lib += gsl_matrix_get(ptilt,j,i);\n\t\tk = 0;\n\t\tfor(j=0;j<tilt->size1;j++) {\n\t\t\tif(gsl_vector_get(fundf,j) > 0) {\n\t\t\t\tmean_par += gsl_matrix_get(tilt,j,i);\n\t\t\t\tk++;\n\t\t\t}\n\t\t}\n\t\tmean_lib = mean_lib/ptilt->size1;\n\t\tmean_par = mean_par/k;\n\n\t\t/* Evaluate standard deviations */\n\t\tstd_par = 0;\n\t\tstd_lib = 0;\n\t\tfor(j=0;j<ptilt->size1;j++)\n\t\t\tstd_lib += (gsl_matrix_get(ptilt,j,i)-mean_lib)*(gsl_matrix_get(ptilt,j,i)-mean_lib);\n\t\tstd_lib = sqrt(std_lib/(ptilt->size1-1));\n\t\tif(std_lib == 0)\n\t\t\tstd_lib = 1;\n\t\tk = 0;\n\t\tfor(j=0;j<tilt->size1;j++) {\n\t\t\tif(gsl_vector_get(fundf,j) > 0) {\n\t\t\t\tstd_par += (gsl_matrix_get(tilt,j,i)-mean_par)*(gsl_matrix_get(tilt,j,i)-mean_par);\n\t\t\t\tk++;\n\t\t\t}\n\t\t}\n\t\tstd_par = sqrt(std_par/(k-1));\n\t\tif(std_par == 0)\n\t\t\tstd_par = 1;\n\n\t\t/* Normalize */\n\t\tfor(j=0;j<tilt->size1;j++)\n\t\t\tif(gsl_vector_get(fundf,j) > 0)\n\t\t\t\tgsl_matrix_set(tilt,j,i,(gsl_matrix_get(tilt,j,i)-mean_par)/std_par*(std_lib*params->adapt_coeff + std_par*(1.0-params->adapt_coeff)) + params->adapt_coeff*mean_lib + (1.0-params->adapt_coeff)*mean_par);\n\t}\n\tLSF_fix_matrix(tilt);\n\n\t/* Normalize HNR */\n\tfor(i=0;i<hnr->size2;i++) {\n\n\t\t/* Evaluate means */\n\t\tmean_par = 0;\n\t\tmean_lib = 0;\n\t\tfor(j=0;j<phnr->size1;j++)\n\t\t\tmean_lib += gsl_matrix_get(phnr,j,i);\n\t\tk = 0;\n\t\tfor(j=0;j<hnr->size1;j++) {\n\t\t\tif(gsl_vector_get(fundf,j) > 0) {\n\t\t\t\tmean_par += gsl_matrix_get(hnr,j,i);\n\t\t\t\tk++;\n\t\t\t}\n\t\t}\n\t\tmean_lib = mean_lib/phnr->size1;\n\t\tmean_par = mean_par/k;\n\n\t\t/* Evaluate standard deviations */\n\t\tstd_par = 0;\n\t\tstd_lib = 0;\n\t\tfor(j=0;j<phnr->size1;j++)\n\t\t\tstd_lib += (gsl_matrix_get(phnr,j,i)-mean_lib)*(gsl_matrix_get(phnr,j,i)-mean_lib);\n\t\tstd_lib = sqrt(std_lib/(phnr->size1-1));\n\t\tif(std_lib == 0)\n\t\t\tstd_lib = 1;\n\t\tk = 0;\n\t\tfor(j=0;j<hnr->size1;j++) {\n\t\t\tif(gsl_vector_get(fundf,j) > 0) {\n\t\t\t\tstd_par += (gsl_matrix_get(hnr,j,i)-mean_par)*(gsl_matrix_get(hnr,j,i)-mean_par);\n\t\t\t\tk++;\n\t\t\t}\n\t\t}\n\t\tstd_par = sqrt(std_par/(k-1));\n\t\tif(std_par == 0)\n\t\t\tstd_par = 1;\n\n\t\t/* Normalize */\n\t\tfor(j=0;j<hnr->size1;j++)\n\t\t\tgsl_matrix_set(hnr,j,i,(gsl_matrix_get(hnr,j,i)-mean_par)/std_par*(std_lib*params->adapt_coeff + std_par*(1.0-params->adapt_coeff)) + params->adapt_coeff*mean_lib + (1.0-params->adapt_coeff)*mean_par);\n\t}\n\n\t/* Normalize Harmonics */\n\tif(params->use_harmonics == 1) {\n\t\tfor(i=0;i<hnr->size2;i++) {\n\n\t\t\t/* Evaluate means */\n\t\t\tmean_par = 0;\n\t\t\tmean_lib = 0;\n\t\t\tfor(j=0;j<pharm->size1;j++)\n\t\t\t\tmean_lib += gsl_matrix_get(pharm,j,i);\n\t\t\tk = 0;\n\t\t\tfor(j=0;j<harm->size1;j++) {\n\t\t\t\tif(gsl_vector_get(fundf,j) > 0) {\n\t\t\t\t\tmean_par += gsl_matrix_get(harm,j,i);\n\t\t\t\t\tk++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tmean_lib = mean_lib/pharm->size1;\n\t\t\tmean_par = mean_par/k;\n\n\t\t\t/* Evaluate standard deviations */\n\t\t\tstd_par = 0;\n\t\t\tstd_lib = 0;\n\t\t\tfor(j=0;j<pharm->size1;j++)\n\t\t\t\tstd_lib += (gsl_matrix_get(pharm,j,i)-mean_lib)*(gsl_matrix_get(pharm,j,i)-mean_lib);\n\t\t\tstd_lib = sqrt(std_lib/(pharm->size1-1));\n\t\t\tif(std_lib == 0)\n\t\t\t\tstd_lib = 1;\n\t\t\tk = 0;\n\t\t\tfor(j=0;j<harm->size1;j++) {\n\t\t\t\tif(gsl_vector_get(fundf,j) > 0) {\n\t\t\t\t\tstd_par += (gsl_matrix_get(harm,j,i)-mean_par)*(gsl_matrix_get(harm,j,i)-mean_par);\n\t\t\t\t\tk++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tstd_par = sqrt(std_par/(k-1));\n\t\t\tif(std_par == 0)\n\t\t\t\tstd_par = 1;\n\n\t\t\t/* Normalize */\n\t\t\tfor(j=0;j<harm->size1;j++)\n\t\t\t\tgsl_matrix_set(harm,j,i,(gsl_matrix_get(harm,j,i)-mean_par)/std_par*(std_lib*params->adapt_coeff + std_par*(1.0-params->adapt_coeff)) + params->adapt_coeff*mean_lib + (1.0-params->adapt_coeff)*mean_par);\n\t\t}\n\t}\n\n\t/* Normalize Waveform */\n\tif(params->use_waveform == 1) {\n\t\tfor(i=0;i<hnr->size2;i++) {\n\n\t\t\t/* Evaluate means */\n\t\t\tmean_par = 0;\n\t\t\tmean_lib = 0;\n\t\t\tfor(j=0;j<pwaveform->size1;j++)\n\t\t\t\tmean_lib += gsl_matrix_get(pwaveform,j,i);\n\t\t\tk = 0;\n\t\t\tfor(j=0;j<waveform->size1;j++) {\n\t\t\t\tif(gsl_vector_get(fundf,j) > 0) {\n\t\t\t\t\tmean_par += gsl_matrix_get(waveform,j,i);\n\t\t\t\t\tk++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tmean_lib = mean_lib/pwaveform->size1;\n\t\t\tmean_par = mean_par/k;\n\n\t\t\t/* Evaluate standard deviations */\n\t\t\tstd_par = 0;\n\t\t\tstd_lib = 0;\n\t\t\tfor(j=0;j<pwaveform->size1;j++)\n\t\t\t\tstd_lib += (gsl_matrix_get(pwaveform,j,i)-mean_lib)*(gsl_matrix_get(pwaveform,j,i)-mean_lib);\n\t\t\tstd_lib = sqrt(std_lib/(pwaveform->size1-1));\n\t\t\tif(std_lib == 0)\n\t\t\t\tstd_lib = 1;\n\t\t\tk = 0;\n\t\t\tfor(j=0;j<waveform->size1;j++) {\n\t\t\t\tif(gsl_vector_get(fundf,j) > 0) {\n\t\t\t\t\tstd_par += (gsl_matrix_get(waveform,j,i)-mean_par)*(gsl_matrix_get(waveform,j,i)-mean_par);\n\t\t\t\t\tk++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tstd_par = sqrt(std_par/(k-1));\n\t\t\tif(std_par == 0)\n\t\t\t\tstd_par = 1;\n\n\t\t\t/* Normalize */\n\t\t\tfor(j=0;j<waveform->size1;j++)\n\t\t\t\tgsl_matrix_set(waveform,j,i,(gsl_matrix_get(waveform,j,i)-mean_par)/std_par*(std_lib*params->adapt_coeff + std_par*(1.0-params->adapt_coeff)) + params->adapt_coeff*mean_lib + (1.0-params->adapt_coeff)*mean_par);\n\t\t}\n\t}\n\n\t/* Normalize Gain */\n\tmean_lib = Mean(pgain);\n\tk = 0;\n\tmean_par = 0;\n\tfor(i=0;i<gain->size;i++) {\n\t\tif(gsl_vector_get(fundf,i) > 0) {\n\t\t\tmean_par += gsl_vector_get(gain,i);\n\t\t\tk++;\n\t\t}\n\t}\n\tmean_par = mean_par/k;\n\tstd_par = 0;\n\tstd_lib = 0;\n\tfor(j=0;j<pgain->size;j++)\n\t\tstd_lib += (gsl_vector_get(pgain,j)-mean_lib)*(gsl_vector_get(pgain,j)-mean_lib);\n\tstd_lib = sqrt(std_lib/(pgain->size-1));\n\tif(std_lib == 0)\n\t\tstd_lib = 1;\n\tk = 0;\n\tfor(j=0;j<gain->size;j++) {\n\t\tif(gsl_vector_get(fundf,j) > 0) {\n\t\t\tstd_par += (gsl_vector_get(gain,j)-mean_par)*(gsl_vector_get(gain,j)-mean_par);\n\t\t\tk++;\n\t\t}\n\t}\n\tstd_par = sqrt(std_par/(k-1));\n\tif(std_par == 0)\n\t\tstd_par = 1;\n\tfor(i=0;i<gain->size;i++)\n\t\tif(gsl_vector_get(fundf,i) > 0) // only voiced\n\t\t\tgsl_vector_set(gain,i,(gsl_vector_get(gain,i)-mean_par)/std_par*(std_lib*params->adapt_coeff + std_par*(1.0-params->adapt_coeff)) + params->adapt_coeff*mean_lib + (1.0-params->adapt_coeff)*mean_par);\n\t//gsl_vector_add_constant(gain,-params->adapt_coeff*mean_par);\n\t//gsl_vector_scale(gain, (params->adapt_coeff*std_lib + (1.0-params->adapt_coeff)*std_par)/std_par);\n\t//gsl_vector_add_constant(gain,params->adapt_coeff*mean_lib + (1.0-params->adapt_coeff)*mean_par);\n\n\t/* Normalize H1H2 */\n\tif(params->use_h1h2 == 1) {\n\t\tmean_lib = Mean(ph1h2);\n\t\tk = 0;\n\t\tmean_par = 0;\n\t\tfor(i=0;i<h1h2->size;i++) {\n\t\t\tif(gsl_vector_get(fundf,i) > 0) {\n\t\t\t\tmean_par += gsl_vector_get(h1h2,i);\n\t\t\t\tk++;\n\t\t\t}\n\t\t}\n\t\tmean_par = mean_par/k;\n\t\tstd_par = 0;\n\t\tstd_lib = 0;\n\t\tfor(j=0;j<ph1h2->size;j++)\n\t\t\tstd_lib += (gsl_vector_get(ph1h2,j)-mean_lib)*(gsl_vector_get(ph1h2,j)-mean_lib);\n\t\tstd_lib = sqrt(std_lib/(ph1h2->size-1));\n\t\tif(std_lib == 0)\n\t\t\tstd_lib = 1;\n\t\tk = 0;\n\t\tfor(j=0;j<h1h2->size;j++) {\n\t\t\tif(gsl_vector_get(fundf,j) > 0) {\n\t\t\t\tstd_par += (gsl_vector_get(h1h2,j)-mean_par)*(gsl_vector_get(h1h2,j)-mean_par);\n\t\t\t\tk++;\n\t\t\t}\n\t\t}\n\t\tstd_par = sqrt(std_par/(k-1));\n\t\tif(std_par == 0)\n\t\t\tstd_par = 1;\n\t\tgsl_vector_add_constant(h1h2,-params->adapt_coeff*mean_par);\n\t\tgsl_vector_scale(h1h2, (params->adapt_coeff*std_lib + (1.0-params->adapt_coeff)*std_par)/std_par);\n\t\tgsl_vector_add_constant(h1h2,params->adapt_coeff*mean_lib + (1.0-params->adapt_coeff)*mean_par);\n\t}\n\n\t/* Normalize NAQ */\n\tif(params->use_naq == 1) {\n\t\tmean_lib = Mean(pnaq);\n\t\tk = 0;\n\t\tmean_par = 0;\n\t\tfor(i=0;i<naq->size;i++) {\n\t\t\tif(gsl_vector_get(fundf,i) > 0) {\n\t\t\t\tmean_par += gsl_vector_get(naq,i);\n\t\t\t\tk++;\n\t\t\t}\n\t\t}\n\t\tmean_par = mean_par/k;\n\t\tstd_par = 0;\n\t\tstd_lib = 0;\n\t\tfor(j=0;j<pnaq->size;j++)\n\t\t\tstd_lib += (gsl_vector_get(pnaq,j)-mean_lib)*(gsl_vector_get(pnaq,j)-mean_lib);\n\t\tstd_lib = sqrt(std_lib/(pnaq->size-1));\n\t\tif(std_lib == 0)\n\t\t\tstd_lib = 1;\n\t\tk = 0;\n\t\tfor(j=0;j<naq->size;j++) {\n\t\t\tif(gsl_vector_get(fundf,j) > 0) {\n\t\t\t\tstd_par += (gsl_vector_get(naq,j)-mean_par)*(gsl_vector_get(naq,j)-mean_par);\n\t\t\t\tk++;\n\t\t\t}\n\t\t}\n\t\tstd_par = sqrt(std_par/(k-1));\n\t\tif(std_par == 0)\n\t\t\tstd_par = 1;\n\t\tgsl_vector_add_constant(naq,-params->adapt_coeff*mean_par);\n\t\tgsl_vector_scale(naq, (params->adapt_coeff*std_lib + (1.0-params->adapt_coeff)*std_par)/std_par);\n\t\tgsl_vector_add_constant(naq,params->adapt_coeff*mean_lib + (1.0-params->adapt_coeff)*mean_par);\n\t}\n\n\t/* Normalize f0 */\n\tmean_lib = 0;\n\tfor(i=0;i<pulse_lengths->size;i++)\n\t\tmean_lib += log10(2.0*params->FS/gsl_vector_get(pulse_lengths,i));\n\tmean_lib = mean_lib/pulse_lengths->size;\n\tk = 0;\n\tmean_par = 0;\n\tfor(i=0;i<fundf->size;i++) {\n\t\tif(gsl_vector_get(fundf,i) > 0) {\n\t\t\tmean_par += log10(gsl_vector_get(fundf,i));\n\t\t\tk++;\n\t\t}\n\t}\n\tmean_par = mean_par/k;\n\tfor(i=0;i<fundf->size;i++)\n\t\tgsl_vector_set(fundf,i,pow(10,log10(gsl_vector_get(fundf,i)) + params->adapt_coeff*(-mean_par+mean_lib)));\n}\n\n\n\n\n\n/**\n * Select_LSFs_from_pulse_library\n *\n * Replace vocal tract LSFs with the closes LSFs from the pulse library\n *\n * @param lsf original LSFs\n * @param plsf pulse library LSFs\n * @param fundf fundamental frequency\n * @param params\n */\nvoid Select_LSFs_from_pulse_library(gsl_matrix *lsf, gsl_matrix *plsf, gsl_vector *fundf, int win, PARAM *params) {\n\n\tif(params->use_pulselib == 0)\n\t\treturn;\n\tif(params->use_pulselib_lsf == 0)\n\t\treturn;\n\n\tint i,j,k,n,minind;\n\tdouble mean_par, mean_lib;\n\tgsl_vector *error = gsl_vector_alloc(plsf->size1);\n\tgsl_matrix *lsf_tmp = gsl_matrix_alloc(lsf->size1,lsf->size2);\n\n\t/* Replace vocal tract LSFs with the closest LSFs from the pulse library */\n\tfor(i=0;i<lsf->size1;i++) {\n\t\tif(gsl_vector_get(fundf,i) > 0) {\n\t\t\tgsl_vector_set_zero(error);\n\t\t\tfor(n=0;n<plsf->size1;n++)\n\t\t\t\tfor(j=0;j<lsf->size2;j++)\n\t\t\t\t\tgsl_vector_set(error,n,gsl_vector_get(error,n) + powf(gsl_matrix_get(lsf,i,j)-gsl_matrix_get(plsf,n,j),2));\n\t\t\tminind = gsl_vector_min_index(error);\n\t\t\tfor(j=0;j<lsf->size2;j++)\n\t\t\t\tgsl_matrix_set(lsf_tmp,i,j,gsl_matrix_get(plsf,minind,j));\n\t\t}\n\t}\n\n\t/* Average between original LSFs and new LSFs from pulse library */\n\tfor(i=0;i<lsf->size2;i++) {\n\t\tfor(j=0;j<lsf->size1;j++) {\n\t\t\tif(gsl_vector_get(fundf,j) == 0)\n\t\t\t\tcontinue;\n\t\t\tn = 0;\n\t\t\tmean_par = 0;\n\t\t\tmean_lib = 0;\n\t\t\tfor(k=j-win;k<j+win;k++) {\n\t\t\t\tif(k > 0 && k < lsf->size1 && gsl_vector_get(fundf,k) > 0) {\n\t\t\t\t\tmean_lib += gsl_matrix_get(lsf_tmp,k,i);\n\t\t\t\t\tmean_par += gsl_matrix_get(lsf,k,i);\n\t\t\t\t\tn++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(n > 0) {\n\t\t\t\tmean_lib = mean_lib/n;\n\t\t\t\tmean_par = mean_par/n;\n\t\t\t\tgsl_matrix_set(lsf,j,i,gsl_matrix_get(lsf,j,i)-mean_par + mean_lib);\n\t\t\t}\n\t\t}\n\t}\n\n\t/* Free memory */\n\tgsl_vector_free(error);\n\tgsl_matrix_free(lsf_tmp);\n}\n\n\n\n\n\n\n\n/**\n * Function Convert_logF0_to_lin\n *\n * Convert fundamental frequency vector from natural logarithm to linear scale\n *\n * @param fundf\n * @param params\n */\nvoid Convert_logF0_to_lin(gsl_vector *fundf, PARAM *params) {\n\n\tif(params->logf0 == 0)\n\t\treturn;\n\n\tint i;\n\tfor(i=0;i<fundf->size;i++)\n\t\tgsl_vector_set(fundf,i,exp(gsl_vector_get(fundf,i)));\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n/*****************************************************************************/\n/*                          FUNCTIONS NOT IN USE                             */\n/*****************************************************************************/\n\n\n/**\n * Function Wrap\n *\n * Wrap phase angles between [-pi,pi].\n *\n * @param phase vector of phase values\n *\n */\nvoid Wrap(gsl_vector *phase) {\n\n\tint i;\n\tfor(i=0;i<phase->size;i++) {\n\t\twhile(gsl_vector_get(phase,i) < -M_PI)\n\t\t\tgsl_vector_set(phase,i,gsl_vector_get(phase,i) + 2*M_PI);\n\t\twhile(gsl_vector_get(phase,i) > M_PI)\n\t\t\tgsl_vector_set(phase,i,gsl_vector_get(phase,i) - 2*M_PI);\n\t}\n}\n\n\n\n\n/**\n * Function Unwrap\n *\n * Unwrap phase angles. Algorithm minimizes the incremental phase variation\n * by constraining it to the range [-pi,pi]\n *\n * @param phase vector of phase values\n *\n */\nvoid Unwrap(gsl_vector *phase) {\n\n\tint i;\n\tgsl_vector *dphase = gsl_vector_calloc(phase->size);\n\tgsl_vector *dphases = gsl_vector_calloc(phase->size);\n\n\t/* Evaluate incremental phase variation */\n\tfor(i=0;i<phase->size-1;i++)\n\t\tgsl_vector_set(dphase,i,gsl_vector_get(phase,i+1)-gsl_vector_get(phase,i));\n\n\t/* Evaluate equivalent phase variations in [-pi,pi) */\n\tfor(i=0;i<phase->size;i++)\n\t\tgsl_vector_set(dphases,i,((gsl_vector_get(dphase,i)+M_PI)/(2*M_PI)-floor((gsl_vector_get(dphase,i)+M_PI)/(2*M_PI)))*2*M_PI - M_PI);\n\n\t/* Preserve variation sign for pi vs. -pi */\n\tfor(i=0;i<phase->size;i++) {\n\t\tif(gsl_vector_get(dphases,i) == -M_PI && gsl_vector_get(dphase,i) > 0)\n\t\t\tgsl_vector_set(dphases,i,M_PI);\n\t}\n\n\t/* Incremental phase corrections */\n\tfor(i=0;i<phase->size;i++)\n\t\tgsl_vector_set(dphases,i,gsl_vector_get(dphases,i)-gsl_vector_get(dphase,i));\n\n\t/* Ignore correction when incr. variation is < CUTOFF, CUTOFF = M_PI */\n\tfor(i=0;i<phase->size;i++) {\n\t\tif(fabs(gsl_vector_get(dphase,i)) < M_PI)\n\t\t\tgsl_vector_set(dphases,i,0);\n\t}\n\n\t/* Integrate corrections */\n\tfor(i=1;i<phase->size;i++)\n\t\tgsl_vector_set(dphases,i,gsl_vector_get(dphases,i-1) + gsl_vector_get(dphases,i));\n\n\t/* Add correction to phase */\n\tfor(i=0;i<phase->size-1;i++)\n\t\tgsl_vector_set(phase,i+1,gsl_vector_get(phase,i+1) + gsl_vector_get(dphases,i));\n\n\t/* Free memory */\n\tgsl_vector_free(dphase);\n\tgsl_vector_free(dphases);\n}\n\n\n\n\n\n/**\n * Function Unwrap2\n *\n * Fine-tune unwrapped phase angles.\n *\n * @param phase vector of phase values\n * @param tol tolerance\n */\nvoid Unwrap2(gsl_vector *phase, double tol) {\n\n\tint i,j,sign;\n\tdouble diff;\n\n\tif(gsl_vector_get(phase,0) < gsl_vector_get(phase,phase->size-1))\n\t\tsign = -1;\n\telse\n\t\tsign = 1;\n\n\tfor(i=1;i<phase->size-1;i++) {\n\t\tdiff = gsl_vector_get(phase,i) - gsl_vector_get(phase,i+1);\n\t\tif(fabs(diff) > tol) {\n\t\t\tif(sign*diff > 0) {\n\t\t\t\tfor(j=i+1;j<phase->size;j++)\n\t\t\t\t\tgsl_vector_set(phase,j,gsl_vector_get(phase,j) + sign*M_PI);\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\n\n\n\n\n\n\n// TEST\nvoid Create_highband_excitation(gsl_vector *excitation_highband, gsl_matrix *erbgain, PARAM *params) {\n\n\t/////////////////////////\n\tint FS_high = 44100;\n\t//int FS_high = 16000;\n\t/////////////////////////\n\n\tint i,j,frame_index,sample_index = 0,erb_channels = erbgain->size2,signal_length = excitation_highband->size;\n\tdouble r = FS_high/(double)params->FS;\n\tgsl_vector *noise;\n\n\t/* Start loop */\n\twhile(sample_index < signal_length) {\n\n\t\tframe_index = floor(params->n_frames*(sample_index/(double)signal_length));\n\t\tif(frame_index > params->n_frames-1)\n\t\t\tframe_index = params->n_frames-1;\n\n\t\t/* Allocate noise vector */\n\t\tnoise = gsl_vector_calloc(rint(2.0*r*params->shift/params->speed));\n\n\n\n\n\t\t/**********************************/\n\t\t/*           Create noise         */\n\t\t/**********************************/\n\n\t\t/* Initialize */\n\t\tint n = noise->size;\n\t\tint n2 = ceil((n-1)/2.0);\n\t\tgsl_vector *real = gsl_vector_calloc(n);\n\t\tgsl_vector *imag = gsl_vector_calloc(n);\n\t\tgsl_vector *gain_values = gsl_vector_alloc(n2);\n\t\tgsl_vector *erb_inds = gsl_vector_alloc(n2);\n\n\t\t/* Evaluate ERB scale indices */\n\t\tfor(i=0;i<n2;i++)\n\t\t\tgsl_vector_set(erb_inds,i,log10(0.00437*(i/(n2-1.0)*(FS_high/2.0))+1.0)/log10(0.00437*(FS_high/2.0)+1.0)*(erb_channels-SMALL_NUMBER));\n\n\t\t/* Evaluate values according to ERB rate */\n\t\tfor(i=0;i<n2;i++) {\n\t\t\tj = floor(gsl_vector_get(erb_inds,i));\n\t\t\tgsl_vector_set(gain_values,i,gsl_matrix_get(erbgain,frame_index,j));\n\t\t}\n\n\t\t/* Convert HNR values from logarithmic scale to linear scale (actual noise amplitudes) */\n\t\tfor(i=0;i<n2;i++)\n\t\t\tgsl_vector_set(gain_values,i,pow(10,(gsl_vector_get(gain_values,i)/20.0)));\n\n\t\t/* Modify both the magnitude and the phase of the spectrum  */\n\t\tdouble lfl = 0.3628;\n\t\tfor(i=rint(lfl*n2);i<n2;i++) {\n\t\t\tgsl_vector_set(imag,i+1, RAND()*gsl_vector_get(gain_values,i));\n\t\t\tgsl_vector_set(real,i+1, RAND()*gsl_vector_get(gain_values,i));\n\t\t}\n\n\t\t/* Copy the noise to the folded spectrum as well */\n\t\tif(imag->size%2 == 0) {\n\t\t\tfor(i=0;i<n2;i++) {\n\t\t\t\tgsl_vector_set(imag,n2+i,-gsl_vector_get(imag,n2-i));\n\t\t\t\tgsl_vector_set(real,n2+i,gsl_vector_get(real,n2-i));\n\t\t\t}\n\t\t} else {\n\t\t\tfor(i=0;i<n2;i++) {\n\t\t\t\tgsl_vector_set(imag,n2+1+i,-gsl_vector_get(imag,n2-i));\n\t\t\t\tgsl_vector_set(real,n2+1+i,gsl_vector_get(real,n2-i));\n\t\t\t}\n\t\t}\n\n\t\t/* Create halfcomplex data */\n\t\tdouble data[n];\n\t\tdata[0] = gsl_vector_get(real,0);\n\t\tfor(i=1;i<n;i++) {\n\t\t\tif(i%2 == 1)\n\t\t\t\tdata[i] = gsl_vector_get(real,(i+1)/2);\n\t\t\telse\n\t\t\t\tdata[i] = gsl_vector_get(imag,i/2);\n\t\t}\n\n\t\t/* Inverse FFT */\n\t\tgsl_fft_real_workspace *work = gsl_fft_real_workspace_alloc(n);\n\t\tgsl_fft_halfcomplex_wavetable *whc = gsl_fft_halfcomplex_wavetable_alloc(n);\n\t\tgsl_fft_halfcomplex_inverse(data,1,n,whc,work);\n\t\tgsl_fft_halfcomplex_wavetable_free(whc);\n\t\tgsl_fft_real_workspace_free(work);\n\n\t\t/* Set data from array \"data\" to vector \"noise\" */\n\t\tfor(i=0;i<n;i++)\n\t\t\tgsl_vector_set(noise,i,data[i]);\n\n\t\t/* Free memory */\n\t\tgsl_vector_free(real);\n\t\tgsl_vector_free(imag);\n\t\tgsl_vector_free(gain_values);\n\t\tgsl_vector_free(erb_inds);\n\n\t\t/**********************************/\n\t\t/*      End of create noise       */\n\t\t/**********************************/\n\n\n\t\t/* Windown noise */\n\t\tfor(i=0;i<n;i++)\n\t\t\tgsl_vector_set(noise,i,gsl_vector_get(noise,i)*HANN(i,n));\n\n\t\t/* Set noise to excitation */\n\t\tint q = rint(0.25*n);\n\t\tint ind;\n\t\tfor(i=0;i<noise->size;i++) {\n\t\t\tind = GSL_MIN(GSL_MAX(sample_index+i-q,0),excitation_highband->size-1);\n\t\t\tgsl_vector_set(excitation_highband,ind,gsl_vector_get(excitation_highband,ind) + gsl_vector_get(noise,i));\n\t\t}\n\n\t\t/* Free memory */\n\t\tgsl_vector_free(noise);\n\n\t\t/* Increment sample index */\n\t\tsample_index += rint(r*params->shift/params->speed);\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n/*********************************************************************/\n/*                       TEST FUNCTIONS                              */\n/*********************************************************************/\n\n\n\n// TEST FUNCTION\n// PRINT VECTOR TO FILE: p1.dat\nvoid VPrint1(gsl_vector *vector) {\n\tFILE *f = fopen(\"p1.dat\", \"w\");\n\tgsl_vector_fprintf(f, vector, \"%.15f\");\n\tfclose(f);\n}\n\n// TEST FUNCTION\n// PRINT VECTOR TO FILE: p2.dat\nvoid VPrint2(gsl_vector *vector) {\n\tFILE *f = fopen(\"p2.dat\", \"w\");\n\tgsl_vector_fprintf(f, vector, \"%.15f\");\n\tfclose(f);\n}\n\n// TEST FUNCTION\n// PRINT VECTOR TO FILE: p3.dat\nvoid VPrint3(gsl_vector *vector) {\n\tFILE *f = fopen(\"p3.dat\", \"w\");\n\tgsl_vector_fprintf(f, vector, \"%.15f\");\n\tfclose(f);\n}\n\n// TEST FUNCTION\n// PRINT VECTOR TO FILE: p4.dat\nvoid VPrint4(gsl_vector *vector) {\n\tFILE *f = fopen(\"p4.dat\", \"w\");\n\tgsl_vector_fprintf(f, vector, \"%.15f\");\n\tfclose(f);\n}\n\n// TEST FUNCTION\n// PRINT VECTOR TO FILE: p5.dat\nvoid VPrint5(gsl_vector *vector) {\n\tFILE *f = fopen(\"p5.dat\", \"w\");\n\tgsl_vector_fprintf(f, vector, \"%.15f\");\n\tfclose(f);\n}\n\n// TEST FUNCTION\n// PRINT VECTOR TO FILE: p6.dat\nvoid VPrint6(gsl_vector *vector) {\n\tFILE *f = fopen(\"p6.dat\", \"w\");\n\tgsl_vector_fprintf(f, vector, \"%.15f\");\n\tfclose(f);\n}\n\n// TEST FUNCTION\n// PRINT VECTOR TO FILE: p7.dat\nvoid VPrint7(gsl_vector *vector) {\n\tFILE *f = fopen(\"p7.dat\", \"w\");\n\tgsl_vector_fprintf(f, vector, \"%.15f\");\n\tfclose(f);\n}\n\n// TEST FUNCTION\n// PRINT VECTOR TO FILE: p8.dat\nvoid VPrint8(gsl_vector *vector) {\n\tFILE *f = fopen(\"p8.dat\", \"w\");\n\tgsl_vector_fprintf(f, vector, \"%.15f\");\n\tfclose(f);\n}\n\n// TEST FUNCTION\n// PRINT VECTOR TO FILE: p9.dat\nvoid VPrint9(gsl_vector *vector) {\n\tFILE *f = fopen(\"p9.dat\", \"w\");\n\tgsl_vector_fprintf(f, vector, \"%.15f\");\n\tfclose(f);\n}\n\n// TEST FUNCTION\n// PRINT VECTOR TO FILE: p10.dat\nvoid VPrint10(gsl_vector *vector) {\n\tFILE *f = fopen(\"p10.dat\", \"w\");\n\tgsl_vector_fprintf(f, vector, \"%.15f\");\n\tfclose(f);\n}\n\n// TEST FUNCTION\n// PRINT VECTOR TO FILE: p11.dat\nvoid VPrint11(gsl_vector *vector) {\n\tFILE *f = fopen(\"p11.dat\", \"w\");\n\tgsl_vector_fprintf(f, vector, \"%.15f\");\n\tfclose(f);\n}\n\n// TEST FUNCTION\n// PRINT VECTOR TO FILE: p12.dat\nvoid VPrint12(gsl_vector *vector) {\n\tFILE *f = fopen(\"p12.dat\", \"w\");\n\tgsl_vector_fprintf(f, vector, \"%.15f\");\n\tfclose(f);\n}\n\n// TEST FUNCTION\n// PRINT MATRIX TO FILE: m1.dat\nvoid MPrint1(gsl_matrix *matrix) {\n\tFILE *f = fopen(\"m1.dat\", \"w\");\n\tgsl_matrix_fprintf(f, matrix, \"%.15f\");\n\tfclose(f);\n}\n\n// TEST FUNCTION\n// PRINT MATRIX TO FILE: m2.dat\nvoid MPrint2(gsl_matrix *matrix) {\n\tFILE *f = fopen(\"m2.dat\", \"w\");\n\tgsl_matrix_fprintf(f, matrix, \"%.15f\");\n\tfclose(f);\n}\n\n// TEST FUNCTION\n// PRINT MATRIX TO FILE: m3.dat\nvoid MPrint3(gsl_matrix *matrix) {\n\tFILE *f = fopen(\"m3.dat\", \"w\");\n\tgsl_matrix_fprintf(f, matrix, \"%.15f\");\n\tfclose(f);\n}\n\n// TEST FUNCTION\n// PRINT MATRIX TO FILE: m4.dat\nvoid MPrint4(gsl_matrix *matrix) {\n\tFILE *f = fopen(\"m4.dat\", \"w\");\n\tgsl_matrix_fprintf(f, matrix, \"%.15f\");\n\tfclose(f);\n}\n\n// TEST FUNCTION\n// PRINT MATRIX TO FILE: m5.dat\nvoid MPrint5(gsl_matrix *matrix) {\n\tFILE *f = fopen(\"m5.dat\", \"w\");\n\tgsl_matrix_fprintf(f, matrix, \"%.15f\");\n\tfclose(f);\n}\n\n// TEST FUNCTION\n// PRINT MATRIX TO FILE: m6.dat\nvoid MPrint6(gsl_matrix *matrix) {\n\tFILE *f = fopen(\"m6.dat\", \"w\");\n\tgsl_matrix_fprintf(f, matrix, \"%.15f\");\n\tfclose(f);\n}\n\n\n// TEST FUNCTION\n// PRINT ARRAY TO FILE: a1.dat\nvoid APrint1(double *array, int size) {\n\tint i;\n\tgsl_vector *vector = gsl_vector_alloc(size);\n\tfor(i=0;i<size;i++)\n\t\tgsl_vector_set(vector,i,array[i]);\n\tFILE *f = fopen(\"a1.dat\", \"w\");\n\tgsl_vector_fprintf(f, vector, \"%.15f\");\n\tfclose(f);\n\tgsl_vector_free(vector);\n}\n\n// TEST FUNCTION\n// PRINT ARRAY TO FILE: a2.dat\nvoid APrint2(double *array, int size) {\n\tint i;\n\tgsl_vector *vector = gsl_vector_alloc(size);\n\tfor(i=0;i<size;i++)\n\t\tgsl_vector_set(vector,i,array[i]);\n\tFILE *f = fopen(\"a2.dat\", \"w\");\n\tgsl_vector_fprintf(f, vector, \"%.15f\");\n\tfclose(f);\n\tgsl_vector_free(vector);\n}\n\n// TEST FUNCTION\n// PRINT ARRAY TO FILE: a3.dat\nvoid APrint3(double *array, int size) {\n\tint i;\n\tgsl_vector *vector = gsl_vector_alloc(size);\n\tfor(i=0;i<size;i++)\n\t\tgsl_vector_set(vector,i,array[i]);\n\tFILE *f = fopen(\"a3.dat\", \"w\");\n\tgsl_vector_fprintf(f, vector, \"%.15f\");\n\tfclose(f);\n\tgsl_vector_free(vector);\n}\n\n// TEST FUNCTION\n// PRINT ARRAY TO FILE: a4.dat\nvoid APrint4(double *array, int size) {\n\tint i;\n\tgsl_vector *vector = gsl_vector_alloc(size);\n\tfor(i=0;i<size;i++)\n\t\tgsl_vector_set(vector,i,array[i]);\n\tFILE *f = fopen(\"a4.dat\", \"w\");\n\tgsl_vector_fprintf(f, vector, \"%.15f\");\n\tfclose(f);\n\tgsl_vector_free(vector);\n}\n\n// TEST FUNCTION\n// PRINT ELAPSED TIME\nvoid TimePrint(double start_time) {\n\tprintf(\"\\n\\nElapsed time: %1.2lf seconds.\\n\\n\",((double)clock()-start_time)/(double)CLOCKS_PER_SEC);\n}\n\n// TEST FUNCTION\n// PAUSE\nvoid pause(int print) {\n\tif(print == 1)\n\t\tprintf(\"\\n\\nPAUSED - PRESS ENTER TO CONTINUE\\n\");\n\tgetchar();\n}\n\n// TEST FUNCTION\n// TEST FOR NANS AND INFS (MATRIX)\nint Find_matrix_NaN_Inf(gsl_matrix *m) {\n\n\tint i,j,err = 0;\n\tfor(i=0;i<m->size1;i++) {\n\t\tfor(j=0;j<m->size2;j++) {\n\t\t\tif(isnan(gsl_matrix_get(m,i,j)) == 1) {\n\t\t\t\tprintf(\"Warning: NaN value found!\\n\");\n\t\t\t\terr = 1;\n\t\t\t}\n\t\t\tif(isinf(gsl_matrix_get(m,i,j)) == 1) {\n\t\t\t\tprintf(\"Warning: Inf value found!\\n\");\n\t\t\t\terr = 1;\n\t\t\t}\n\t\t}\n\t}\n\treturn err;\n}\n\n// TEST FUNCTION\n// TEST FOR NANS AND INFS (VECTOR)\nint Find_vector_NaN_Inf(gsl_vector *v) {\n\n\tint i,err = 0;\n\tfor(i=0;i<v->size;i++) {\n\t\tif(isnan(gsl_vector_get(v,i)) == 1) {\n\t\t\tprintf(\"Warning: NaN value found!\\n\");\n\t\t\terr = 1;\n\t\t}\n\t\tif(isinf(gsl_vector_get(v,i)) == 1) {\n\t\t\tprintf(\"Warning: Inf value found!\\n\");\n\t\t\terr = 1;\n\t\t}\n\t}\n\treturn err;\n}\n\n", "meta": {"hexsha": "e23f9e98cfd132216bfc741f97f7629d87ab2f44", "size": 280131, "ext": "c", "lang": "C", "max_stars_repo_path": "src/SynthesisFunctions.c", "max_stars_repo_name": "mjansche/GlottHMM", "max_stars_repo_head_hexsha": "4dfe5eb0b6dacc227299acc29c6df8b030de82b8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2016-06-29T22:08:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-03T12:46:50.000Z", "max_issues_repo_path": "src/SynthesisFunctions.c", "max_issues_repo_name": "mjansche/GlottHMM", "max_issues_repo_head_hexsha": "4dfe5eb0b6dacc227299acc29c6df8b030de82b8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SynthesisFunctions.c", "max_forks_repo_name": "mjansche/GlottHMM", "max_forks_repo_head_hexsha": "4dfe5eb0b6dacc227299acc29c6df8b030de82b8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2016-08-03T12:08:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T09:17:33.000Z", "avg_line_length": 29.4100787402, "max_line_length": 259, "alphanum_fraction": 0.6823129179, "num_tokens": 87142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014734858584286, "lm_q2_score": 0.025565211788799124, "lm_q1q2_score": 0.010996808066987477}}
{"text": "\n#ifndef KGS_NULLSPACEQR_H\n#define KGS_NULLSPACEQR_H\n\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_vector.h>\n#include <string>\n\n#include \"math/QR.h\"\n#include \"math/Nullspace.h\"\n#include \"TransposeQR.h\"\n\n/**\n * An implementation of Nullspace backed by a QR decomposition\n */\nclass NullspaceQR: public Nullspace {\n public:\n  /** Will construct a nullspace using a QR (transpose) decomposition */\n  NullspaceQR(TransposeQR* qr);\n\n  ~NullspaceQR();\n\n  /** Update the Nullspace (and underlying SVD) to reflect an updated state of the matrix */\n  void updateFromMatrix() override;\n\nprivate:\n  TransposeQR* m_qr;                  ///< SVD underlying this nullspace\n\n  friend class Configuration;\n};\n\n\n#endif //KGS_nullptrSPACE_H\n", "meta": {"hexsha": "9e144ca69c2d76919d6c5c7d0d4755488b09925a", "size": 723, "ext": "h", "lang": "C", "max_stars_repo_path": "src/math/NullspaceQR.h", "max_stars_repo_name": "XiyuChenFAU/kgs_vibration_entropy", "max_stars_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-23T18:26:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-23T18:26:14.000Z", "max_issues_repo_path": "src/math/NullspaceQR.h", "max_issues_repo_name": "XiyuChenFAU/kgs_vibration_entropy", "max_issues_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2017-01-26T19:54:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-06T16:06:30.000Z", "max_forks_repo_path": "src/math/NullspaceQR.h", "max_forks_repo_name": "XiyuChenFAU/kgs_vibration_entropy", "max_forks_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.2647058824, "max_line_length": 92, "alphanum_fraction": 0.7219917012, "num_tokens": 180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.024798161276659476, "lm_q1q2_score": 0.01095267842601832}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef rbtree_ebcaa429_edae_4ac6_b9a5_2fe774778822_h\r\n#define rbtree_ebcaa429_edae_4ac6_b9a5_2fe774778822_h\r\n\r\n#include <assert.h>\r\n#include <gslib/std.h>\r\n\r\n__gslib_begin__\r\n\r\nstruct _rbtree_trait_copy {};\r\nstruct _rbtree_trait_detach {};\r\n\r\nenum rbtree_color\r\n{\r\n    rb_red,\r\n    rb_black,\r\n};\r\n\r\ntemplate<class _ty>\r\nstruct _rbtreenode_cpy_wrapper\r\n{\r\n    typedef _ty value;\r\n    typedef _rbtreenode_cpy_wrapper<_ty> myref;\r\n    typedef _rbtree_trait_copy tsf_behavior;\r\n    typedef rbtree_color color;\r\n\r\n    value               _value;\r\n    myref*              _left;\r\n    myref*              _right;\r\n    myref*              _parent;\r\n    color               _color;\r\n\r\n    myref()\r\n    {\r\n        _left = _right = _parent = nullptr;\r\n        _color = rb_black;\r\n    }\r\n    value* get_ptr() { return &_value; }\r\n    const value* const_ptr() const { return &_value; }\r\n    value& get_ref() { return _value; }\r\n    const value& const_ref() const { return _value; }\r\n    void born() {}\r\n    void kill() {}\r\n    template<class _ctor>\r\n    void born() {}\r\n    template<class _ctor>\r\n    void kill() {}\r\n    void copy(const myref* a) { get_ref() = a->const_ref(); }\r\n    void attach(myref* a) { assert(0); }\r\n    void swap_data(myref* a) { std::swap(_value, a->_value); }\r\n    void set_color(color c) { _color = c; }\r\n    color get_color() const { return _color; }\r\n    bool is_red() const { return _color == rb_red; }\r\n};\r\n\r\ntemplate<class _ty>\r\nstruct _rbtreenode_wrapper\r\n{\r\n    typedef _ty value;\r\n    typedef _rbtreenode_wrapper<_ty> myref;\r\n    typedef _rbtree_trait_detach tsf_behavior;\r\n    typedef rbtree_color color;\r\n\r\n    value*              _value;\r\n    myref*              _left;\r\n    myref*              _right;\r\n    myref*              _parent;\r\n    color               _color;\r\n\r\n    myref()\r\n    {\r\n        _left = _right = _parent = nullptr;\r\n        _value = nullptr;\r\n        _color = rb_black;\r\n    }\r\n    value* get_ptr() { return _value; }\r\n    const value* const_ptr() const { return _value; }\r\n    value& get_ref() { return *_value; }\r\n    const value& const_ref() const { return *_value; }\r\n    void copy(const myref* a) { get_ref() = a->const_ref(); }\r\n    void born() { !! }\r\n    template<class _ctor>\r\n    void born() { _value = new _ctor; }\r\n    void kill() { if(_value) { delete _value; _value = nullptr; } }\r\n    template<class _ctor>\r\n    void kill() { if(_value) { delete _value; _value = nullptr; } }\r\n    void attach(myref* a)\r\n    {\r\n        assert(a && a->_value);\r\n        kill();\r\n        _value = a->_value;\r\n        a->_value = nullptr;\r\n    }\r\n    void swap_data(myref* a) { gs_swap(_value, a->_value); }\r\n    void set_color(color c) { _color = c; }\r\n    color get_color() const { return _color; }\r\n    bool is_red() const { return _color == rb_red; }\r\n};\r\n\r\ntemplate<class _wrapper>\r\nstruct _rbtree_allocator\r\n{\r\n    typedef _wrapper wrapper;\r\n    static wrapper* born() { return new wrapper; }\r\n    static void kill(wrapper* w) { delete w; }\r\n};\r\n\r\ntemplate<class _val>\r\nstruct _rbtreenode_val\r\n{\r\n    typedef _val value;\r\n    typedef const _val const_value;\r\n    typedef _rbtreenode_val<_val> myref;\r\n    typedef rbtree_color color;\r\n\r\n    union\r\n    {\r\n        value*          _vptr;\r\n        const_value*    _cvptr;\r\n    };\r\n\r\n    myref() { _vptr = nullptr; }\r\n    value* get_wrapper() const { return _vptr; }\r\n    operator bool() const { return _vptr != nullptr; }\r\n    bool is_left() const { return (_cvptr && _cvptr->_parent) ? _cvptr->_parent->_left == _cvptr : false; }\r\n    bool is_right() const { return (_cvptr && _cvptr->_parent) ? _cvptr->_parent->_right == _cvptr : false; }\r\n    bool is_root() const { return _cvptr ? (!_cvptr->_parent) : false; }\r\n    bool is_leaf() const { return _cvptr ? (!_cvptr->_left && !_cvptr->_right) : false; }\r\n    int up_depth() const\r\n    {\r\n        int depth = 0;\r\n        for(value* p = _vptr; p; p = p->_parent, depth ++);\r\n        return depth;\r\n    }\r\n    int down_depth() const { return _down_depth(_vptr, 0); }\r\n    bool operator==(const value* v) const { return _vptr == v; }\r\n    bool operator!=(const value* v) const { return _vptr != v; }\r\n    color get_color() const { return _vptr->_color; }\r\n    void set_color(color c) { _vptr->_color = c; }\r\n    void swap_data(myref& a) { _vptr->swap_data(a._vptr); }\r\n\r\npublic:\r\n    static void connect_left_child(value* p, value* l)\r\n    {\r\n        assert(p);\r\n        p->_left = l;\r\n        if(l)\r\n            l->_parent = p;\r\n    }\r\n    static void connect_right_child(value* p, value* r)\r\n    {\r\n        assert(p);\r\n        p->_right = r;\r\n        if(r)\r\n            r->_parent = p;\r\n    }\r\n    static bool disconnect_parent_child(value* p, value* c)\r\n    {\r\n        assert(p && c && (c->_parent == p));\r\n        if(p->_left == c) {\r\n            p->_left = c->_parent = nullptr;\r\n            return true;\r\n        }\r\n        assert(p->_right == c);\r\n        p->_right = c->_parent = nullptr;\r\n        return false;\r\n    }\r\n\r\nprivate:\r\n    static int _down_depth(value* v, int ctr)\r\n    {\r\n        if(v == nullptr)\r\n            return ctr;\r\n        ctr ++;\r\n        return gs_max(_down_depth(v->_left, ctr), \r\n            _down_depth(v->_right, ctr)\r\n            );\r\n    }\r\n\r\nprotected:\r\n    value* vleft() const { return _vptr ? _vptr->_left : nullptr; }\r\n    value* vright() const { return _vptr ? _vptr->_right : nullptr; }\r\n    value* vparent() const { return _vptr ? _vptr->_parent : nullptr; }\r\n    value* vsibling() const\r\n    {\r\n        if(!_vptr || !_vptr->_parent)\r\n            return nullptr;\r\n        if(is_left())\r\n            return _vptr->_right;\r\n        else if(is_right())\r\n            return _vptr->_left;\r\n        assert(!\"unexpected.\");\r\n        return nullptr;\r\n    }\r\n    value* vroot() const\r\n    {\r\n        if(!_vptr)\r\n            return nullptr;\r\n        value* p = _vptr;\r\n        for( ; p->_parent; p = p->_parent);\r\n        return p;\r\n    }\r\n\r\nprotected:\r\n    template<class _lambda, class _value>\r\n    static void preorder_traversal(_lambda lam, _value* v)\r\n    {\r\n        assert(v);\r\n        lam(v);\r\n        if(v->_left)\r\n            preorder_traversal(lam, v->_left);\r\n        if(v->_right)\r\n            preorder_traversal(lam, v->_right);\r\n    }\r\n    template<class _lambda, class _value>\r\n    static void inorder_traversal(_lambda lam, _value* v)\r\n    {\r\n        assert(v);\r\n        if(v->_left)\r\n            inorder_traversal(lam, v->_left);\r\n        lam(v);\r\n        if(v->_right)\r\n            inorder_traversal(lam, v->_right);\r\n    }\r\n    template<class _lambda, class _value>\r\n    static void postorder_traversal(_lambda lam, _value* v)\r\n    {\r\n        assert(v);\r\n        if(v->_left)\r\n            postorder_traversal(lam, v->_left);\r\n        if(v->_right)\r\n            postorder_traversal(lam, v->-right);\r\n        lam(v);\r\n    }\r\n\r\npublic:\r\n    template<class _lambda>\r\n    void inorder_traversal(_lambda lam) { if(_vptr) inorder_traversal(lam, _vptr); }\r\n    template<class _lambda>\r\n    void inorder_traversal(_lambda lam) const { if(_cvptr) inorder_traversal(lam, _cvptr); }\r\n    template<class _lambda>\r\n    void preorder_traversal(_lambda lam) { if(_vptr) preorder_traversal(lam, _vptr); }\r\n    template<class _lambda>\r\n    void preorder_traversal(_lambda lam) const { if(_cvptr) preorder_traversal(lam, _cvptr); }\r\n    template<class _lambda>\r\n    void postorder_traversal(_lambda lam) { if(_vptr) postorder_traversal(lam, _vptr); }\r\n    template<class _lambda>\r\n    void postorder_traversal(_lambda lam) const { if(_cvptr) postorder_traversal(lam, _cvptr); }\r\n};\r\n\r\ntemplate<class _ty,\r\n    class _wrapper = _rbtreenode_cpy_wrapper<_ty> >\r\nclass _rbtree_const_iterator:\r\n    public _rbtreenode_val<_wrapper>\r\n{\r\npublic:\r\n    typedef _ty value;\r\n    typedef _wrapper wrapper;\r\n    typedef _rbtree_const_iterator<_ty, _wrapper> iterator;\r\n\r\npublic:\r\n    iterator(const wrapper* w = nullptr) { _cvptr = w; }\r\n    bool is_valid() const { return _cvptr != nullptr; }\r\n    const value* get_ptr() const { return _cvptr->const_ptr(); }\r\n    const value* operator->() const { return _cvptr->const_ptr(); }\r\n    const value& operator*() const { return _cvptr->const_ref(); }\r\n    iterator left() const { return iterator(vleft()); }\r\n    iterator right() const { return iterator(vright()); }\r\n    iterator parent() const { return iterator(vparent()); }\r\n    iterator sibling() const { return iterator(vsibling()); }\r\n    iterator root() const { return iterator(vroot()); }\r\n    bool operator==(const iterator& that) const { return _cvptr == that._cvptr; }\r\n    bool operator!=(const iterator& that) const { return _cvptr != that._cvptr; }\r\n};\r\n\r\ntemplate<class _ty,\r\n    class _wrapper = _rbtreenode_cpy_wrapper<_ty> >\r\nclass _rbtree_iterator:\r\n    public _rbtree_const_iterator<_ty, _wrapper>\r\n{\r\npublic:\r\n    typedef _ty value;\r\n    typedef _wrapper wrapper;\r\n    typedef _rbtree_const_iterator<_ty, _wrapper> const_iterator;\r\n    typedef _rbtree_const_iterator<_ty, _wrapper> superref;\r\n    typedef _rbtree_iterator<_ty, _wrapper> iterator;\r\n\r\npublic:\r\n    iterator(wrapper* w): superref(w) {}\r\n    value* get_ptr() const { return _vptr->get_ptr(); }\r\n    value* operator->() const { return _vptr->get_ptr(); }\r\n    value& operator*() const { return _vptr->get_ref(); }\r\n    bool operator==(const iterator& that) const { return _vptr == that._vptr; }\r\n    bool operator!=(const iterator& that) const { return _vptr != that._vptr; }\r\n    bool operator==(const const_iterator& that) const { return _vptr == that._vptr; }\r\n    bool operator!=(const const_iterator& that) const { return _vptr != that._vptr; }\r\n    operator const_iterator() { return const_iterator(_cvptr); }\r\n    void to_root() { _vptr = vroot(); }\r\n    void to_left() { _vptr = vleft(); }\r\n    void to_right() { _vptr = vright(); }\r\n    void to_sibling() { _vptr = vsibling(); }\r\n    void to_parent() { _vptr = vparent(); }\r\n    iterator left() const { return iterator(vleft()); }\r\n    iterator right() const { return iterator(vright()); }\r\n    iterator parent() const { return iterator(vparent()); }\r\n    iterator sibling() const { return iterator(vsibling()); }\r\n    iterator root() const { return iterator(vroot()); }\r\n};\r\n\r\ntemplate<class _ty,\r\n    class _wrapper = _rbtreenode_cpy_wrapper<_ty>,\r\n    class _alloc = _rbtree_allocator<_wrapper> >\r\nclass rbtree:\r\n    public _rbtreenode_val<_wrapper>\r\n{\r\npublic:\r\n    typedef _ty value;\r\n    typedef _wrapper wrapper;\r\n    typedef _alloc alloc;\r\n    typedef rbtree<value, wrapper, alloc> myref;\r\n    typedef _rbtree_const_iterator<_ty, _wrapper> const_iterator;\r\n    typedef _rbtree_iterator<_ty, _wrapper> iterator;\r\n    typedef rbtree_color color;\r\n\r\npublic:\r\n    rbtree() { _vptr = nullptr; }\r\n    ~rbtree() { clear(); }\r\n    void clear() { destroy(get_root()); }\r\n    void destroy(iterator i)\r\n    {\r\n        if(!i.is_valid())\r\n            return;\r\n        if(iterator p = i.parent())\r\n            disconnect_parent_child(p.get_wrapper(), i.get_wrapper());\r\n        else {\r\n            assert(is_root(i));\r\n            _vptr = nullptr;\r\n        }\r\n        _destroy(i);\r\n    }\r\n    void adopt(wrapper* w)\r\n    {\r\n        assert(!_vptr && \"use attach method.\");\r\n        _vptr = w;\r\n    }\r\n    iterator get_root() const { return iterator(_vptr); }\r\n    const_iterator const_root() const { return const_iterator(_cvptr); }\r\n    bool is_root(iterator i) const { return i ? (_vptr == i.get_wrapper()) : false; }\r\n    bool is_valid() const { return _cvptr != nullptr; }\r\n    bool is_mine(iterator i) const\r\n    {\r\n        if(!i.is_valid())\r\n            return false;\r\n        i.to_root();\r\n        return i.get_wrapper() == _vptr;\r\n    }\r\n    int depth() const { return _cvptr->down_depth(); }\r\n    void swap(myref& that) { gs_swap(_vptr, that._vptr); }\r\n    iterator find(const value& v) const { return find(get_root(), v); }\r\n    iterator find(iterator i, const value& v) const\r\n    {\r\n        if(!i) {\r\n            if(!is_valid())\r\n                return i;\r\n            i = get_root();\r\n        }\r\n        assert(i);\r\n        wrapper* f = _find(i.get_wrapper(), v);\r\n        assert(f);\r\n        if(!(f->const_ref() == v))\r\n            f = nullptr;\r\n        return iterator(f);\r\n    }\r\n    template<class _ctor = value>\r\n    iterator insert(const value& v)\r\n    {\r\n        wrapper* f = nullptr;\r\n        if(_vptr) {\r\n            f = _find(_vptr, v);\r\n            assert(f);\r\n            if(f->const_ref() == v)\r\n                return iterator(f);\r\n        }\r\n        wrapper* n = initval<_ctor, wrapper::tsf_behavior>::run(alloc::born(), v);\r\n        n->set_color(rb_red);\r\n        if(!f)\r\n            _vptr = n;\r\n        else {\r\n            (v < f->const_ref()) ? connect_left_child(f, n) :\r\n                connect_right_child(f, n);\r\n        }\r\n        _fix_insert(n);\r\n        return iterator(n);\r\n    }\r\n    void erase(iterator i)\r\n    {\r\n        assert(i);\r\n        wrapper* n = i.get_wrapper();\r\n        wrapper *c, *p;\r\n        rbtree_color cr;\r\n        if(!n->_left)\r\n            c = n->_right;\r\n        else if(!n->_right)\r\n            c = n->_left;\r\n        else {\r\n            wrapper* b = n, *l;\r\n            n = n->_right;\r\n            for(; l = n->_left; n = l);\r\n            if(!b->_parent)\r\n                _vptr = n;\r\n            else {\r\n                (b->_parent->_left == b) ? b->_parent->_left = n :\r\n                    b->_parent->_right = n;\r\n            }\r\n            c = n->_right;\r\n            p = n->_parent;\r\n            cr = n->_color;\r\n            if(p == b)\r\n                p = n;\r\n            else {\r\n                if(c)\r\n                    c->_parent = p;\r\n                p->_left = c;\r\n                n->_right = b->_right;\r\n                b->_right->_parent = n;\r\n            }\r\n            n->_parent = b->_parent;\r\n            n->_color = b->_color;\r\n            n->_left = b->_left;\r\n            b->_left->_parent = n;\r\n            if(cr == rb_black)\r\n                _fix_erase(c, p);\r\n            return;\r\n        }\r\n        p = n->_parent;\r\n        cr = n->_color;\r\n        if(c)\r\n            c->_parent = p;\r\n        if(!p)\r\n            _vptr = c;\r\n        else {\r\n            (p->_left == n) ? p->_left = c :\r\n                p->_right = c;\r\n        }\r\n        if(cr == rb_black)\r\n            _fix_erase(c, p);\r\n    }\r\n    void erase(const value& v)\r\n    {\r\n        if(iterator i = find(v))\r\n            erase(i);\r\n    }\r\n\r\n    /* The detach and attach methods, provide subtree operations */\r\n    myref& detach(myref& subtree, iterator i)\r\n    {\r\n        assert(i && is_mine(i));\r\n        if(subtree.is_valid())\r\n            subtree.clear();\r\n        detach<myref>(subtree, i);\r\n        return subtree;\r\n    }\r\n    template<class _cont>\r\n    void detach(_cont& cont)\r\n    {\r\n        cont.adopt(_vptr);\r\n        _vptr = nullptr;\r\n    }\r\n    template<class _cont>\r\n    void detach(_cont& cont, iterator i)\r\n    {\r\n        assert(i && is_mine(i));\r\n        if(i == get_root())\r\n            return detach(cont);\r\n        iterator p = i.parent();\r\n        assert(p);\r\n        disconnect_parent_child(p.get_wrapper(), i.get_wrapper());\r\n        cont.adopt(i.get_wrapper());\r\n    }\r\n    iterator attach(myref& subtree, iterator i)\r\n    {\r\n        assert(i && is_mine(i) && i.is_leaf());\r\n        if(i.is_root()) {\r\n            swap(subtree);\r\n            return get_root();\r\n        }\r\n        iterator p = i.parent();\r\n        assert(p);\r\n        bool leftp = disconnect_parent_child(p.get_wrapper(), i.get_wrapper());\r\n        gs_swap(subtree._vptr, i._vptr);\r\n        leftp ? connect_left_child(p.get_wrapper(), i.get_wrapper()) :\r\n            connect_right_child(p.get_wrapper(), i.get_wrapper());\r\n        subtree.clear();\r\n        return i;\r\n    }\r\n\r\npublic:\r\n    template<class _lambda>\r\n    void preorder_for_each(_lambda lam) { preorder_traversal([](wrapper* w) { lam(w->get_ptr()); }); }\r\n    template<class _lambda>\r\n    void preorder_const_for_each(_lambda lam) const { preorder_traversal([](const wrapper* w) { lam(w->const_ptr()); }); }\r\n    template<class _lambda>\r\n    void inorder_for_each(_lambda lam) { inorder_traversal([](wrapper* w) { lam(w->get_ptr()); }); }\r\n    template<class _lambda>\r\n    void inorder_const_for_each(_lambda lam) const { inorder_traversal([](const wrapper* w) { lam(w->const_ptr()); }); }\r\n    template<class _lambda>\r\n    void postorder_for_each(_lambda lam) { postorder_traversal([](wrapper* w) { lam(w->get_ptr()); }); }\r\n    template<class _lambda>\r\n    void postorder_const_for_each(_lambda lam) const { postorder_traversal([](const wrapper* w) { lam(w->const_ptr()); }); }\r\n\r\nprotected:\r\n    void _destroy(iterator i)\r\n    {\r\n        if(!i.is_valid())\r\n            return;\r\n        _destroy(i.left());\r\n        _destroy(i.right());\r\n        wrapper* w = i.get_wrapper();\r\n        w->kill();\r\n        alloc::kill(w);\r\n    }\r\n    wrapper* _find(wrapper* w, const value& v) const\r\n    {\r\n        assert(w);\r\n        wrapper* n = w;\r\n        for(;;) {\r\n            wrapper* m = nullptr;\r\n            const value& r = n->const_ref();\r\n            if(v < r)\r\n                m = n->_left;\r\n            else if(r < v)\r\n                m = n->_right;\r\n            if(!m)\r\n                return n;\r\n            n = m;\r\n        }\r\n        return nullptr;\r\n    }\r\n    void _left_rotate(wrapper* n)\r\n    {\r\n        assert(n);\r\n        wrapper* r = n->_right;\r\n        if(n->_right = r->_left)\r\n            r->_left->_parent = n;\r\n        r->_left = n;\r\n        if(!(r->_parent = n->_parent))\r\n            _vptr = r;\r\n        else {\r\n            (n == n->_parent->_right) ? n->_parent->_right = r :\r\n                n->_parent->_left = r;\r\n        }\r\n        n->_parent = r;\r\n    }\r\n    void _right_rotate(wrapper* n)\r\n    {\r\n        assert(n);\r\n        wrapper* l = n->_left;\r\n        if(n->_left = l->_right)\r\n            l->_right->_parent = n;\r\n        l->_right = n;\r\n        if(!(l->_parent = n->_parent))\r\n            _vptr = l;\r\n        else {\r\n            (n == n->_parent->_right) ? n->_parent->_right = l :\r\n                n->_parent->_left = l;\r\n        }\r\n        n->_parent = l;\r\n    }\r\n    void _fix_insert(wrapper* n)\r\n    {\r\n        assert(n);\r\n        wrapper *p, *g, *u;\r\n        while((p = n->_parent) && p->is_red()) {\r\n            g = p->_parent;\r\n            if(p == g->_left) {\r\n                u = g->_right;\r\n                if(u && u->is_red()) {\r\n                    u->set_color(rb_black);\r\n                    p->set_color(rb_black);\r\n                    g->set_color(rb_red);\r\n                    n = g;\r\n                }\r\n                else {\r\n                    if(p->_right == n) {\r\n                        _left_rotate(p);\r\n                        gs_swap(p, n);\r\n                    }\r\n                    p->set_color(rb_black);\r\n                    g->set_color(rb_red);\r\n                    _right_rotate(g);\r\n                }\r\n            }\r\n            else {\r\n                u = g->_left;\r\n                if(u && u->is_red()) {\r\n                    u->set_color(rb_black);\r\n                    p->set_color(rb_black);\r\n                    g->set_color(rb_red);\r\n                    n = g;\r\n                }\r\n                else {\r\n                    if(p->_left == n) {\r\n                        _right_rotate(p);\r\n                        gs_swap(p, n);\r\n                    }\r\n                    p->set_color(rb_black);\r\n                    g->set_color(rb_red);\r\n                    _left_rotate(g);\r\n                }\r\n            }\r\n        }\r\n        _vptr->set_color(rb_black);\r\n    }\r\n    void _fix_erase(wrapper* n, wrapper* p)\r\n    {\r\n        wrapper *s, *sl, *sr;\r\n        while((!n || !n->is_red()) && n != _vptr) {\r\n            if(p->_left == n) {\r\n                s = p->_right;\r\n                if(s->is_red()) {\r\n                    s->set_color(rb_black);\r\n                    p->set_color(rb_red);\r\n                    _left_rotate(p);\r\n                    s = p->_right;\r\n                }\r\n                if((!s->_left || !s->_left->is_red()) &&\r\n                    (!s->_right || !s->_right->is_red())\r\n                    ) {\r\n                    s->set_color(rb_red);\r\n                    n = p;\r\n                    p = n->_parent;\r\n                }\r\n                else {\r\n                    if(!s->_right || !s->_right->is_red()) {\r\n                        if(sl = s->_left)\r\n                            sl->set_color(rb_black);\r\n                        s->set_color(rb_red);\r\n                        _right_rotate(s);\r\n                        s = p->_right;\r\n                    }\r\n                    s->set_color(p->get_color());\r\n                    p->set_color(rb_black);\r\n                    if(sr = s->_right)\r\n                        sr->set_color(rb_black);\r\n                    _left_rotate(p);\r\n                    n = _vptr;\r\n                    break;\r\n                }\r\n            }\r\n            else {\r\n                s = p->_left;\r\n                if(s->is_red()) {\r\n                    s->set_color(rb_black);\r\n                    p->set_color(rb_red);\r\n                    _right_rotate(p);\r\n                    s = p->_left;\r\n                }\r\n                if((!s->_left || !s->_left->is_red()) &&\r\n                    (!s->_right || !s->_right->is_red())\r\n                    ) {\r\n                    s->set_color(rb_red);\r\n                    n = p;\r\n                    p = n->_parent;\r\n                }\r\n                else {\r\n                    if(!s->_left || !s->_left->is_red()) {\r\n                        if(sr = s->_right)\r\n                            sr->set_color(rb_black);\r\n                        s->set_color(rb_red);\r\n                        _left_rotate(s);\r\n                        s = p->_left;\r\n                    }\r\n                    s->set_color(p->get_color());\r\n                    p->set_color(rb_black);\r\n                    if(sl = s->_left)\r\n                        sl->set_color(rb_black);\r\n                    _right_rotate(p);\r\n                    n = _vptr;\r\n                    break;\r\n                }\r\n            }\r\n        }\r\n        if(n)\r\n            n->set_color(rb_black);\r\n    }\r\n\r\nprotected:\r\n    friend struct initval;\r\n    template<class _ctor, class _tsftrait>\r\n    struct initval;\r\n    template<class _ctor>\r\n    struct initval<_ctor, _rbtree_trait_copy>\r\n    {\r\n        static wrapper* run(wrapper* w, const value& v)\r\n        {\r\n            assert(w);\r\n            w->get_ref() = v;\r\n            return w;\r\n        }\r\n    };\r\n    template<class _ctor>\r\n    struct initval<_ctor, _rbtree_trait_detach>\r\n    {\r\n        static wrapper* run(wrapper* w, const value& v)\r\n        {\r\n            assert(w);\r\n            w->_value = &v;     /* or duplicate? */\r\n            return w;\r\n        }\r\n    };\r\n};\r\n\r\n__gslib_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "f4e49f8a14b7627cbedcaae14a1a4dda38fc716c", "size": 24051, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gslib/rbtree.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/gslib/rbtree.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gslib/rbtree.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 32.4137466307, "max_line_length": 125, "alphanum_fraction": 0.5089601264, "num_tokens": 5802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2309197735148081, "lm_q2_score": 0.04742587654349034, "lm_q1q2_score": 0.01095157267016404}}
{"text": "/*\n * Barcode\n * Copyright E.G.P. Bos and F.S. Kitaura\n *\n * Distributed under the terms of the MIT License.\n * The full license is in the file LICENSE, distributed with this software.\n */\n\n#pragma once\n\n#include \"struct_main.h\"\n#include <gsl/gsl_rng.h>\n#include \"define_opt.h\"\n\nvoid barcoderunner(struct DATA *data,gsl_rng * gBaseRand);\nvoid load_initial_fields(struct DATA *data, int resnum, gsl_rng *gBaseRand);\nunsigned int initial_iteration_number(struct DATA *data);\nvoid setup_random_test(struct DATA *data, real_prec *delta_lag, real_prec *delta_eul, unsigned int facL,\n                       real_prec *posx, real_prec *posy, real_prec *posz, gsl_rng *gBaseRand);\nvoid make_initial_guess(struct DATA *data, gsl_rng *gBaseRand);\n", "meta": {"hexsha": "faeefd5a63244df4a52a0fc03c8996d4f40e9388", "size": 737, "ext": "h", "lang": "C", "max_stars_repo_path": "barlib/include/barcoderunner.h", "max_stars_repo_name": "egpbos/barcode", "max_stars_repo_head_hexsha": "1127e12fa80075389c1d247d30b430b77becbbc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "barlib/include/barcoderunner.h", "max_issues_repo_name": "egpbos/barcode", "max_issues_repo_head_hexsha": "1127e12fa80075389c1d247d30b430b77becbbc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-12-13T10:44:12.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-13T10:44:12.000Z", "max_forks_repo_path": "barlib/include/barcoderunner.h", "max_forks_repo_name": "egpbos/barcode", "max_forks_repo_head_hexsha": "1127e12fa80075389c1d247d30b430b77becbbc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-02-11T06:56:47.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-11T06:56:47.000Z", "avg_line_length": 35.0952380952, "max_line_length": 104, "alphanum_fraction": 0.7435549525, "num_tokens": 185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.39606818053136394, "lm_q2_score": 0.02758528542450002, "lm_q1q2_score": 0.010925653807520076}}
{"text": "/* -----------------------------------------------------------------------------\n * Copyright 2021 Jonathan Haigh\n * SPDX-License-Identifier: MIT\n * ---------------------------------------------------------------------------*/\n\n#ifndef SQ_INCLUDE_GUARD_core_narrow_h_\n#define SQ_INCLUDE_GUARD_core_narrow_h_\n\n#include \"core/typeutil.h\"\n\n#include <concepts>\n#include <cstddef>\n#include <gsl/gsl>\n#include <string_view>\n\nnamespace sq {\n\n/**\n * Wrapper around gsl::narrow that provides better diags on failure.\n *\n * @param value value to convert\n * @param format_args optional arguments, passed to fmt::format that describe\n *        what kind of thing is being converted.\n *\n * E.g.\n *    narrow<int>(0.5, \"number of words in file {}\", path)\n * might throw an exception with a message like:\n *    number of words in file \"/some/file\" (0.5) does not fit in type int\n *\n * If the optional format_args args aren't given then the value's type is used\n * as a description instead. E.g.\n *    narrow<int>(0.5)\n * might throw an exception with a message like:\n *    float (0.5) does not fit in type int\n */\ntemplate <typename T, typename U, typename... FormatArgs>\nSQ_ND constexpr T narrow(U value, FormatArgs &&...format_args);\n\n/**\n * Convert an integral value to a gsl::index.\n *\n * Throws if the value can't be represented by a gsl::index.\n */\nSQ_ND constexpr gsl::index to_index(auto value, auto &&...format_args);\n\n/**\n * Convert an integral value to a std::size_t.\n *\n * Throws if the value can't be represented by a std::size_t.\n */\nSQ_ND constexpr std::size_t to_size(auto value, auto &&...format_args);\n\n} // namespace sq\n\n#include \"core/narrow.inl.h\"\n\n#endif // SQ_INCLUDE_GUARD_core_narrow_h_\n", "meta": {"hexsha": "cce2a0645b7805a25e66833acce08dcbe58ff498", "size": 1697, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/include/core/narrow.h", "max_stars_repo_name": "jonathanhaigh/sq", "max_stars_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-12T16:21:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-12T16:21:41.000Z", "max_issues_repo_path": "src/core/include/core/narrow.h", "max_issues_repo_name": "jonathanhaigh/sq", "max_issues_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 44.0, "max_issues_repo_issues_event_min_datetime": "2021-02-08T19:17:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-05T18:51:38.000Z", "max_forks_repo_path": "src/core/include/core/narrow.h", "max_forks_repo_name": "jonathanhaigh/sq", "max_forks_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2586206897, "max_line_length": 80, "alphanum_fraction": 0.6417206836, "num_tokens": 395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20434189993684584, "lm_q2_score": 0.053403327916637336, "lm_q1q2_score": 0.010912537489436073}}
{"text": "#include <gsl/gsl_combination.h>\n\n#include <caml/alloc.h>\n#include <caml/bigarray.h>\n#include <caml/memory.h>\n\nstatic void combi_of_val(gsl_combination *c, value vc)\n{\n    c->n = Int_val(Field(vc, 0));\n    c->k = Int_val(Field(vc, 1));\n    c->data = Data_bigarray_val(Field(vc, 2));\n}\n\nCAMLprim value ml_gsl_combination_init_first(value vc)\n{\n    gsl_combination c;\n    combi_of_val(&c, vc);\n    gsl_combination_init_first(&c);\n    return Val_unit;\n}\n\nCAMLprim value ml_gsl_combination_init_last(value vc)\n{\n    gsl_combination c;\n    combi_of_val(&c, vc);\n    gsl_combination_init_last(&c);\n    return Val_unit;\n}\n\nCAMLprim value ml_gsl_combination_valid(value vc)\n{\n    int r;\n    gsl_combination c;\n    combi_of_val(&c, vc);\n    r = gsl_combination_valid(&c);\n    return Val_not(Val_bool(r));\n}\n\nCAMLprim value ml_gsl_combination_next(value vc)\n{\n    gsl_combination c;\n    combi_of_val(&c, vc);\n    gsl_combination_next(&c);\n    return Val_unit;\n}\n\nCAMLprim value ml_gsl_combination_prev(value vc)\n{\n    gsl_combination c;\n    combi_of_val(&c, vc);\n    gsl_combination_prev(&c);\n    return Val_unit;\n}\n", "meta": {"hexsha": "f59dfd7656972c2f8bd298cd99d58ba50af13fd0", "size": 1106, "ext": "c", "lang": "C", "max_stars_repo_path": "lib/mlgsl_extra.c", "max_stars_repo_name": "nrlucaroni/pareto", "max_stars_repo_head_hexsha": "65dd093eddbd62740e615fd48da4f6de4fd528f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-12-06T08:05:19.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-06T08:05:19.000Z", "max_issues_repo_path": "lib/mlgsl_extra.c", "max_issues_repo_name": "nrlucaroni/pareto", "max_issues_repo_head_hexsha": "65dd093eddbd62740e615fd48da4f6de4fd528f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/mlgsl_extra.c", "max_forks_repo_name": "nrlucaroni/pareto", "max_forks_repo_head_hexsha": "65dd093eddbd62740e615fd48da4f6de4fd528f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.4814814815, "max_line_length": 54, "alphanum_fraction": 0.6980108499, "num_tokens": 326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34510527095787247, "lm_q2_score": 0.03161876681238652, "lm_q1q2_score": 0.010911803088142435}}
{"text": "#ifndef _EM_CTX_H_\n#define _EM_CTX_H_ 1\n\n#include \"em_defs.h\"\n\n#include <petsc.h>\n\n#include <set>\n#include <map>\n#include <memory>\n#include <vector>\n\nclass Mesh;\n\nstruct EMContext {\n  MPI_Comm world_comm, group_comm;\n  int world_size, world_rank, group_size, group_rank, group_id;\n\n  std::vector<Point> rx;\n  std::vector<double> tx;\n  std::vector<double> freqs;\n\n  Eigen::VectorXcd rsp, obs, obserr;\n  Eigen::VectorXi otype, fidx, tidx, ridx;\n\n  Point top_corners[4];\n  Eigen::VectorXd ztop[4], lsig[4];\n\n  std::shared_ptr<Mesh> original_mesh, mesh;\n\n  std::vector<int> relevant_edges;\n  std::pair<int, int> local_vertices, local_edges;\n\n  std::set<int> bdr_cells;\n\n  int aniso_form;\n  Eigen::MatrixXd rho;\n  Eigen::VectorXd lb, ub;\n  std::vector<std::string> rho_name;\n\n  Vec w;\n  Mat C, M, A, B;\n  KSP A_ksp, B_ksp;\n  PETScBlockVector s, csem_e, dual_e;\n  std::map<int, PETScBlockVector> mt_e;\n\n  PetscViewer LS_log;\n\n  Eigen::VectorXd csem_error;\n  std::map<int, Eigen::VectorXd> mt_error;\n\n  Mat G;\n  std::vector<PetscReal> v_coords;\n\n  PetscBool use_ams;\n  char iprefix[256], oprefix[256];\n  PetscReal max_rx_edge_length, refine_fraction, e_rtol, dual_rtol;\n  PetscInt max_adaptive_refinements, max_dofs, refine_strategy, n_groups, K_max_it, pc_threshold, inner_pc_type, direct_solver_type;\n\n  PetscClassId EMCTX_ID;\n  PetscLogEvent CreateLS, AssembleMat, AssembleRHS, SetupAMS, CreatePC, SolveLS, EstimateError,\n      RefineMesh, CalculateRSP;\n};\n\nPetscErrorCode create_context(EMContext *);\nPetscErrorCode destroy_context(EMContext *);\nPetscErrorCode process_options(EMContext *);\n\n#endif\n", "meta": {"hexsha": "9a61faf6faf8a7be30817dde506feb95f29e61d3", "size": 1596, "ext": "h", "lang": "C", "max_stars_repo_path": "src/em_ctx.h", "max_stars_repo_name": "emfem/emfem", "max_stars_repo_head_hexsha": "9129e28610d7fcb83a88021528575dfeaadad502", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-03T12:22:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-03T12:22:37.000Z", "max_issues_repo_path": "src/em_ctx.h", "max_issues_repo_name": "emfem/emfem", "max_issues_repo_head_hexsha": "9129e28610d7fcb83a88021528575dfeaadad502", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/em_ctx.h", "max_forks_repo_name": "emfem/emfem", "max_forks_repo_head_hexsha": "9129e28610d7fcb83a88021528575dfeaadad502", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8, "max_line_length": 132, "alphanum_fraction": 0.7387218045, "num_tokens": 472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632159254749036, "lm_q2_score": 0.025565212809632806, "lm_q1q2_score": 0.010899002238818158}}
{"text": "#include <bindings.cmacros.h>\n#include <gsl/gsl_multimin.h>\n\nBC_INLINE2(GSL_MULTIMIN_FN_EVAL,gsl_multimin_function*,gsl_vector*,double)\nBC_INLINE2(GSL_MULTIMIN_FN_EVAL_F,gsl_multimin_function_fdf*,gsl_vector*,double)\nBC_INLINE3VOID(GSL_MULTIMIN_FN_EVAL_DF,gsl_multimin_function_fdf*,gsl_vector*,gsl_vector*)\nBC_INLINE4VOID(GSL_MULTIMIN_FN_EVAL_F_DF,gsl_multimin_function_fdf*,gsl_vector*,double*,gsl_vector*)\n", "meta": {"hexsha": "8b844b96d107f49d7331c74498ada9c0414e30d3", "size": 409, "ext": "c", "lang": "C", "max_stars_repo_path": "bindings-gsl/src/Bindings/Gsl/MultidimensionalMinimization.c", "max_stars_repo_name": "flip111/bindings-dsl", "max_stars_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2015-04-29T00:31:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T09:29:03.000Z", "max_issues_repo_path": "bindings-gsl/src/Bindings/Gsl/MultidimensionalMinimization.c", "max_issues_repo_name": "flip111/bindings-dsl", "max_issues_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2015-01-04T06:32:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-07T09:49:12.000Z", "max_forks_repo_path": "bindings-gsl/src/Bindings/Gsl/MultidimensionalMinimization.c", "max_forks_repo_name": "flip111/bindings-dsl", "max_forks_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2015-01-03T20:43:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-10T19:31:38.000Z", "avg_line_length": 51.125, "max_line_length": 100, "alphanum_fraction": 0.8753056235, "num_tokens": 123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869689484852374, "lm_q2_score": 0.025957357951306048, "lm_q1q2_score": 0.01086826517268348}}
{"text": "/*\nCopyright 2017 Jiawei Chiu\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n#pragma once\n\n#include <algorithm>\n#include <array>\n#include <chrono>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <memory>\n#include <random>\n#include <sstream>\n#include <string>\n#include <vector>\n\n#include <gflags/gflags.h>\n#include <glog/logging.h>\n\n#include <cublas_v2.h>\n#include <cuda_runtime.h>\n#include <curand.h>\n#include <cusolverDn.h>\n#include <cusparse.h>\n\n// When BLAS functions are missing, we fallback on Eigen.\n#include <eigen3/Eigen/Core>\n#include <eigen3/Eigen/Dense>\n#include <eigen3/Eigen/SparseCore>\n\n#include <cublas_v2.h>\n// #include <magma_lapack.h>\n#include <magma_v2.h>\n\n#include <lapacke.h>\n\nnamespace gi {\n\nusing std::abs;\nusing std::cout;\nusing std::ifstream;\nusing std::istream;\nusing std::istringstream;\nusing std::max;\nusing std::min;\nusing std::ostream;\nusing std::ofstream;\nusing std::ostringstream;\nusing std::sqrt;\nusing std::string;\nusing std::unique_ptr;\nusing std::vector;\n\nvoid MainInit(int argc, char **argv);\n\nclass Timer {\npublic:\n  Timer();\n  void reset();\n  double elapsed() const;\n\nprivate:\n  typedef std::chrono::high_resolution_clock clock_;\n  typedef std::chrono::duration<double, std::ratio<1> > second_;\n  std::chrono::time_point<clock_> beg_;\n};\n\nstruct EngineOptions {\n  int omp_num_threads = 1;\n  int device = 0;      // For GPU device.\n  int num_streams = 4; // Number of CUDA streams.\n  int rng_seed = 56150941;\n};\n\n#define CUDA_CALL(x)                                                           \\\n  { CHECK_EQ(x, cudaSuccess) << \"CUDA error: \" << x; }\n\n#define CURAND_CALL(x)                                                         \\\n  { CHECK_EQ(x, CURAND_STATUS_SUCCESS) << \"CURAND error: \" << x; }\n\n#define CUBLAS_CALL(x)                                                         \\\n  { CHECK_EQ(x, CUBLAS_STATUS_SUCCESS) << \"CUBLAS error: \" << x; }\n\n#define CUSOLVER_CALL(x)                                                       \\\n  { CHECK_EQ(x, CUSOLVER_STATUS_SUCCESS) << \"CUSOLVER error: \" << x; }\n\n#define CUSPARSE_CALL(x)                                                       \\\n  { CHECK_EQ(x, CUSPARSE_STATUS_SUCCESS) << \"CUSPARSE error: \" << x; }\n\nclass Engine {\npublic:\n  Engine(const EngineOptions &opt);\n  ~Engine();\n\n  static Engine *instance() { return instance_; }\n  static cudaStream_t stream(int i) { return instance()->stream_[i]; }\n  static curandGenerator_t curand() { return instance()->curand_; }\n  static cublasHandle_t cublas() { return instance()->cublas_; }\n  static cusparseHandle_t cusparse() { return instance()->cusparse_; }\n  static cusparseMatDescr_t cusparse_desc() {\n    return instance()->cusparse_desc_;\n  }\n  static cusolverDnHandle_t cusolver_dn() { return instance()->cusolver_dn_; }\n  static std::mt19937 &rng() { return instance()->rng_; }\n  static float *device_s_one() { return instance()->device_s_one_; }\n  static float *device_s_zero() { return instance()->device_s_zero_; }\n\nprivate:\n  vector<cudaStream_t> stream_;\n  curandGenerator_t curand_;\n  cublasHandle_t cublas_;\n  cusparseHandle_t cusparse_;\n  cusparseMatDescr_t cusparse_desc_;\n  cusolverDnHandle_t cusolver_dn_;\n  std::mt19937 rng_;\n  float *device_s_one_;\n  float *device_s_zero_;\n\n  static Engine *instance_;\n};\n\n// Some convenience functions for GPU kernels.\n\n// Returns number of blocks and number of threads given n things to work on.\nvoid BlocksThreads(int max_blocks, int max_threads, int n, int *num_blocks,\n                   int *num_threads);\n}", "meta": {"hexsha": "636401312e8d5e74e20417daba7bd127b11e26ab", "size": 4033, "ext": "h", "lang": "C", "max_stars_repo_path": "base.h", "max_stars_repo_name": "tinkerstash/gpuimpute", "max_stars_repo_head_hexsha": "185609b9f2a8cfa45ee2054b0404bb03aaa71dad", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "base.h", "max_issues_repo_name": "tinkerstash/gpuimpute", "max_issues_repo_head_hexsha": "185609b9f2a8cfa45ee2054b0404bb03aaa71dad", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "base.h", "max_forks_repo_name": "tinkerstash/gpuimpute", "max_forks_repo_head_hexsha": "185609b9f2a8cfa45ee2054b0404bb03aaa71dad", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4014084507, "max_line_length": 80, "alphanum_fraction": 0.6741879494, "num_tokens": 984, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29098086621490676, "lm_q2_score": 0.03732688734412946, "lm_q1q2_score": 0.01086141001250103}}
{"text": "/* matrix/gsl_matrix_double.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_MATRIX_DOUBLE_H__\n#define __GSL_MATRIX_DOUBLE_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_vector_double.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size1;\n  size_t size2;\n  size_t tda;\n  double * data;\n  gsl_block * block;\n  int owner;\n} gsl_matrix;\n\ntypedef struct\n{\n  gsl_matrix matrix;\n} _gsl_matrix_view;\n\ntypedef _gsl_matrix_view gsl_matrix_view;\n\ntypedef struct\n{\n  gsl_matrix matrix;\n} _gsl_matrix_const_view;\n\ntypedef const _gsl_matrix_const_view gsl_matrix_const_view;\n\n/* Allocation */\n\nGSL_EXPORT\ngsl_matrix *\ngsl_matrix_alloc (const size_t n1, const size_t n2);\n\nGSL_EXPORT\ngsl_matrix *\ngsl_matrix_calloc (const size_t n1, const size_t n2);\n\nGSL_EXPORT\ngsl_matrix *\ngsl_matrix_alloc_from_block (gsl_block * b,\n                                   const size_t offset,\n                                   const size_t n1,\n                                   const size_t n2,\n                                   const size_t d2);\n\nGSL_EXPORT\ngsl_matrix *\ngsl_matrix_alloc_from_matrix (gsl_matrix * m,\n                                    const size_t k1,\n                                    const size_t k2,\n                                    const size_t n1,\n                                    const size_t n2);\n\nGSL_EXPORT\ngsl_vector *\ngsl_vector_alloc_row_from_matrix (gsl_matrix * m,\n                                        const size_t i);\n\nGSL_EXPORT\ngsl_vector *\ngsl_vector_alloc_col_from_matrix (gsl_matrix * m,\n                                        const size_t j);\n\nGSL_EXPORT void gsl_matrix_free (gsl_matrix * m);\n\n/* Views */\n\nGSL_EXPORT\n_gsl_matrix_view\ngsl_matrix_submatrix (gsl_matrix * m,\n                            const size_t i, const size_t j,\n                            const size_t n1, const size_t n2);\n\nGSL_EXPORT\n_gsl_vector_view\ngsl_matrix_row (gsl_matrix * m, const size_t i);\n\nGSL_EXPORT\n_gsl_vector_view\ngsl_matrix_column (gsl_matrix * m, const size_t j);\n\nGSL_EXPORT\n_gsl_vector_view\ngsl_matrix_diagonal (gsl_matrix * m);\n\nGSL_EXPORT\n_gsl_vector_view\ngsl_matrix_subdiagonal (gsl_matrix * m, const size_t k);\n\nGSL_EXPORT\n_gsl_vector_view\ngsl_matrix_superdiagonal (gsl_matrix * m, const size_t k);\n\nGSL_EXPORT\n_gsl_matrix_view\ngsl_matrix_view_array (double * base,\n                             const size_t n1,\n                             const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_view\ngsl_matrix_view_array_with_tda (double * base,\n                                      const size_t n1,\n                                      const size_t n2,\n                                      const size_t tda);\n\n\nGSL_EXPORT \n_gsl_matrix_view\ngsl_matrix_view_vector (gsl_vector * v,\n                              const size_t n1,\n                              const size_t n2);\n\nGSL_EXPORT \n_gsl_matrix_view\ngsl_matrix_view_vector_with_tda (gsl_vector * v,\n                                       const size_t n1,\n                                       const size_t n2,\n                                       const size_t tda);\n\n\nGSL_EXPORT\n_gsl_matrix_const_view\ngsl_matrix_const_submatrix (const gsl_matrix * m,\n                                  const size_t i, const size_t j,\n                                  const size_t n1, const size_t n2);\n\nGSL_EXPORT\n_gsl_vector_const_view\ngsl_matrix_const_row (const gsl_matrix * m,\n                            const size_t i);\n\nGSL_EXPORT\n_gsl_vector_const_view\ngsl_matrix_const_column (const gsl_matrix * m,\n                               const size_t j);\n\nGSL_EXPORT\n_gsl_vector_const_view\ngsl_matrix_const_diagonal (const gsl_matrix * m);\n\nGSL_EXPORT\n_gsl_vector_const_view\ngsl_matrix_const_subdiagonal (const gsl_matrix * m,\n                                    const size_t k);\n\nGSL_EXPORT\n_gsl_vector_const_view\ngsl_matrix_const_superdiagonal (const gsl_matrix * m,\n                                      const size_t k);\n\nGSL_EXPORT\n_gsl_matrix_const_view\ngsl_matrix_const_view_array (const double * base,\n                                   const size_t n1,\n                                   const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_const_view\ngsl_matrix_const_view_array_with_tda (const double * base,\n                                            const size_t n1,\n                                            const size_t n2,\n                                            const size_t tda);\n\nGSL_EXPORT\n_gsl_matrix_const_view\ngsl_matrix_const_view_vector (const gsl_vector * v,\n                                    const size_t n1,\n                                    const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_const_view\ngsl_matrix_const_view_vector_with_tda (const gsl_vector * v,\n                                             const size_t n1,\n                                             const size_t n2,\n                                             const size_t tda);\n\n/* Operations */\n\nGSL_EXPORT double   gsl_matrix_get(const gsl_matrix * m, const size_t i, const size_t j);\nGSL_EXPORT void    gsl_matrix_set(gsl_matrix * m, const size_t i, const size_t j, const double x);\n\nGSL_EXPORT double * gsl_matrix_ptr(gsl_matrix * m, const size_t i, const size_t j);\nGSL_EXPORT const double * gsl_matrix_const_ptr(const gsl_matrix * m, const size_t i, const size_t j);\n\nGSL_EXPORT void gsl_matrix_set_zero (gsl_matrix * m);\nGSL_EXPORT void gsl_matrix_set_identity (gsl_matrix * m);\nGSL_EXPORT void gsl_matrix_set_all (gsl_matrix * m, double x);\n\nGSL_EXPORT int gsl_matrix_fread (FILE * stream, gsl_matrix * m) ;\nGSL_EXPORT int gsl_matrix_fwrite (FILE * stream, const gsl_matrix * m) ;\nGSL_EXPORT int gsl_matrix_fscanf (FILE * stream, gsl_matrix * m);\nGSL_EXPORT int gsl_matrix_fprintf (FILE * stream, const gsl_matrix * m, const char * format);\n\nGSL_EXPORT int gsl_matrix_memcpy(gsl_matrix * dest, const gsl_matrix * src);\nGSL_EXPORT int gsl_matrix_swap(gsl_matrix * m1, gsl_matrix * m2);\n\nGSL_EXPORT int gsl_matrix_swap_rows(gsl_matrix * m, const size_t i, const size_t j);\nGSL_EXPORT int gsl_matrix_swap_columns(gsl_matrix * m, const size_t i, const size_t j);\nGSL_EXPORT int gsl_matrix_swap_rowcol(gsl_matrix * m, const size_t i, const size_t j);\nGSL_EXPORT int gsl_matrix_transpose (gsl_matrix * m);\nGSL_EXPORT int gsl_matrix_transpose_memcpy (gsl_matrix * dest, const gsl_matrix * src);\n\nGSL_EXPORT double gsl_matrix_max (const gsl_matrix * m);\nGSL_EXPORT double gsl_matrix_min (const gsl_matrix * m);\nGSL_EXPORT void gsl_matrix_minmax (const gsl_matrix * m, double * min_out, double * max_out);\n\nGSL_EXPORT void gsl_matrix_max_index (const gsl_matrix * m, size_t * imax, size_t *jmax);\nGSL_EXPORT void gsl_matrix_min_index (const gsl_matrix * m, size_t * imin, size_t *jmin);\nGSL_EXPORT void gsl_matrix_minmax_index (const gsl_matrix * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);\n\nGSL_EXPORT int gsl_matrix_isnull (const gsl_matrix * m);\n\nGSL_EXPORT int gsl_matrix_add (gsl_matrix * a, const gsl_matrix * b);\nGSL_EXPORT int gsl_matrix_sub (gsl_matrix * a, const gsl_matrix * b);\nGSL_EXPORT int gsl_matrix_mul_elements (gsl_matrix * a, const gsl_matrix * b);\nGSL_EXPORT int gsl_matrix_div_elements (gsl_matrix * a, const gsl_matrix * b);\nGSL_EXPORT int gsl_matrix_scale (gsl_matrix * a, const double x);\nGSL_EXPORT int gsl_matrix_add_constant (gsl_matrix * a, const double x);\nGSL_EXPORT int gsl_matrix_add_diagonal (gsl_matrix * a, const double x);\n\n/***********************************************************************/\n/* The functions below are obsolete                                    */\n/***********************************************************************/\nGSL_EXPORT int gsl_matrix_get_row(gsl_vector * v, const gsl_matrix * m, const size_t i);\nGSL_EXPORT int gsl_matrix_get_col(gsl_vector * v, const gsl_matrix * m, const size_t j);\nGSL_EXPORT int gsl_matrix_set_row(gsl_matrix * m, const size_t i, const gsl_vector * v);\nGSL_EXPORT int gsl_matrix_set_col(gsl_matrix * m, const size_t j, const gsl_vector * v);\n \n/* inline functions if you are using GCC */\n\n#ifdef HAVE_INLINE\nextern inline \ndouble\ngsl_matrix_get(const gsl_matrix * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_VAL(\"first index out of range\", GSL_EINVAL, 0) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_VAL(\"second index out of range\", GSL_EINVAL, 0) ;\n    }\n#endif\n  return m->data[i * m->tda + j] ;\n} \n\nextern inline \nvoid\ngsl_matrix_set(gsl_matrix * m, const size_t i, const size_t j, const double x)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_VOID(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_VOID(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  m->data[i * m->tda + j] = x ;\n}\n\nextern inline \ndouble *\ngsl_matrix_ptr(gsl_matrix * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  return (double *) (m->data + (i * m->tda + j)) ;\n} \n\nextern inline \nconst double *\ngsl_matrix_const_ptr(const gsl_matrix * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  return (const double *) (m->data + (i * m->tda + j)) ;\n} \n\n#endif\n\n__END_DECLS\n\n#endif /* __GSL_MATRIX_DOUBLE_H__ */\n", "meta": {"hexsha": "dc063943d49efec5a35b4120c6162d3fe35ba0a9", "size": 10573, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/gsl/include/gsl/gsl_matrix_double.h", "max_stars_repo_name": "dynaryu/vaws", "max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/gsl/include/gsl/gsl_matrix_double.h", "max_issues_repo_name": "dynaryu/vaws", "max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/gsl/include/gsl/gsl_matrix_double.h", "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8250728863, "max_line_length": 123, "alphanum_fraction": 0.6479712475, "num_tokens": 2616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38121956625615, "lm_q2_score": 0.028436030677688646, "lm_q1q2_score": 0.010840371280995041}}
{"text": "/* vector/gsl_vector_complex_long_double.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#ifndef __GSL_VECTOR_COMPLEX_LONG_DOUBLE_H__\n#define __GSL_VECTOR_COMPLEX_LONG_DOUBLE_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_complex.h>\n#include <gsl/gsl_vector_long_double.h>\n#include <gsl/gsl_vector_complex.h>\n#include <gsl/gsl_block_complex_long_double.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size;\n  size_t stride;\n  long double *data;\n  gsl_block_complex_long_double *block;\n  int owner;\n} gsl_vector_complex_long_double;\n\ntypedef struct\n{\n  gsl_vector_complex_long_double vector;\n} _gsl_vector_complex_long_double_view;\n\ntypedef _gsl_vector_complex_long_double_view gsl_vector_complex_long_double_view;\n\ntypedef struct\n{\n  gsl_vector_complex_long_double vector;\n} _gsl_vector_complex_long_double_const_view;\n\ntypedef const _gsl_vector_complex_long_double_const_view gsl_vector_complex_long_double_const_view;\n\n/* Allocation */\n\ngsl_vector_complex_long_double *gsl_vector_complex_long_double_alloc (const size_t n);\ngsl_vector_complex_long_double *gsl_vector_complex_long_double_calloc (const size_t n);\n\ngsl_vector_complex_long_double *\ngsl_vector_complex_long_double_alloc_from_block (gsl_block_complex_long_double * b, \n                                           const size_t offset, \n                                           const size_t n, \n                                           const size_t stride);\n\ngsl_vector_complex_long_double *\ngsl_vector_complex_long_double_alloc_from_vector (gsl_vector_complex_long_double * v, \n                                             const size_t offset, \n                                             const size_t n, \n                                             const size_t stride);\n\nvoid gsl_vector_complex_long_double_free (gsl_vector_complex_long_double * v);\n\n/* Views */\n\n_gsl_vector_complex_long_double_view\ngsl_vector_complex_long_double_view_array (long double *base,\n                                     size_t n);\n\n_gsl_vector_complex_long_double_view\ngsl_vector_complex_long_double_view_array_with_stride (long double *base,\n                                                 size_t stride,\n                                                 size_t n);\n\n_gsl_vector_complex_long_double_const_view\ngsl_vector_complex_long_double_const_view_array (const long double *base,\n                                           size_t n);\n\n_gsl_vector_complex_long_double_const_view\ngsl_vector_complex_long_double_const_view_array_with_stride (const long double *base,\n                                                       size_t stride,\n                                                       size_t n);\n\n_gsl_vector_complex_long_double_view\ngsl_vector_complex_long_double_subvector (gsl_vector_complex_long_double *base,\n                                         size_t i, \n                                         size_t n);\n\n\n_gsl_vector_complex_long_double_view \ngsl_vector_complex_long_double_subvector_with_stride (gsl_vector_complex_long_double *v, \n                                                size_t i, \n                                                size_t stride, \n                                                size_t n);\n\n_gsl_vector_complex_long_double_const_view\ngsl_vector_complex_long_double_const_subvector (const gsl_vector_complex_long_double *base,\n                                               size_t i, \n                                               size_t n);\n\n\n_gsl_vector_complex_long_double_const_view \ngsl_vector_complex_long_double_const_subvector_with_stride (const gsl_vector_complex_long_double *v, \n                                                      size_t i, \n                                                      size_t stride, \n                                                      size_t n);\n\n_gsl_vector_long_double_view\ngsl_vector_complex_long_double_real (gsl_vector_complex_long_double *v);\n\n_gsl_vector_long_double_view \ngsl_vector_complex_long_double_imag (gsl_vector_complex_long_double *v);\n\n_gsl_vector_long_double_const_view\ngsl_vector_complex_long_double_const_real (const gsl_vector_complex_long_double *v);\n\n_gsl_vector_long_double_const_view \ngsl_vector_complex_long_double_const_imag (const gsl_vector_complex_long_double *v);\n\n\n/* Operations */\n\ngsl_complex_long_double \ngsl_vector_complex_long_double_get (const gsl_vector_complex_long_double * v, const size_t i);\n\nvoid gsl_vector_complex_long_double_set (gsl_vector_complex_long_double * v, const size_t i,\n                                   gsl_complex_long_double z);\n\ngsl_complex_long_double \n*gsl_vector_complex_long_double_ptr (gsl_vector_complex_long_double * v, const size_t i);\n\nconst gsl_complex_long_double \n*gsl_vector_complex_long_double_const_ptr (const gsl_vector_complex_long_double * v, const size_t i);\n\nvoid gsl_vector_complex_long_double_set_zero (gsl_vector_complex_long_double * v);\nvoid gsl_vector_complex_long_double_set_all (gsl_vector_complex_long_double * v,\n                                       gsl_complex_long_double z);\nint gsl_vector_complex_long_double_set_basis (gsl_vector_complex_long_double * v, size_t i);\n\nint gsl_vector_complex_long_double_fread (FILE * stream,\n\t\t\t\t    gsl_vector_complex_long_double * v);\nint gsl_vector_complex_long_double_fwrite (FILE * stream,\n\t\t\t\t     const gsl_vector_complex_long_double * v);\nint gsl_vector_complex_long_double_fscanf (FILE * stream,\n\t\t\t\t     gsl_vector_complex_long_double * v);\nint gsl_vector_complex_long_double_fprintf (FILE * stream,\n\t\t\t\t      const gsl_vector_complex_long_double * v,\n\t\t\t\t      const char *format);\n\nint gsl_vector_complex_long_double_memcpy (gsl_vector_complex_long_double * dest, const gsl_vector_complex_long_double * src);\n\nint gsl_vector_complex_long_double_reverse (gsl_vector_complex_long_double * v);\n\nint gsl_vector_complex_long_double_swap (gsl_vector_complex_long_double * v, gsl_vector_complex_long_double * w);\nint gsl_vector_complex_long_double_swap_elements (gsl_vector_complex_long_double * v, const size_t i, const size_t j);\n\nint gsl_vector_complex_long_double_isnull (const gsl_vector_complex_long_double * v);\n\nextern int gsl_check_range;\n\n#ifdef HAVE_INLINE\n\nextern inline\ngsl_complex_long_double\ngsl_vector_complex_long_double_get (const gsl_vector_complex_long_double * v,\n\t\t\t      const size_t i)\n{\n#ifndef GSL_RANGE_CHECK_OFF\n  if (i >= v->size)\n    {\n      const gsl_complex_long_double zero = {{0, 0}};\n      GSL_ERROR_VAL (\"index out of range\", GSL_EINVAL, zero);\n    }\n#endif\n  return *GSL_COMPLEX_LONG_DOUBLE_AT (v, i);\n}\n\nextern inline\nvoid\ngsl_vector_complex_long_double_set (gsl_vector_complex_long_double * v,\n\t\t\t      const size_t i, gsl_complex_long_double z)\n{\n#ifndef GSL_RANGE_CHECK_OFF\n  if (i >= v->size)\n    {\n      GSL_ERROR_VOID (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  *GSL_COMPLEX_LONG_DOUBLE_AT (v, i) = z;\n}\n\nextern inline\ngsl_complex_long_double *\ngsl_vector_complex_long_double_ptr (gsl_vector_complex_long_double * v,\n\t\t\t      const size_t i)\n{\n#ifndef GSL_RANGE_CHECK_OFF\n  if (i >= v->size)\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return GSL_COMPLEX_LONG_DOUBLE_AT (v, i);\n}\n\nextern inline\nconst gsl_complex_long_double *\ngsl_vector_complex_long_double_const_ptr (const gsl_vector_complex_long_double * v,\n                                    const size_t i)\n{\n#ifndef GSL_RANGE_CHECK_OFF\n  if (i >= v->size)\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return GSL_COMPLEX_LONG_DOUBLE_AT (v, i);\n}\n\n\n#endif /* HAVE_INLINE */\n\n__END_DECLS\n\n#endif /* __GSL_VECTOR_COMPLEX_LONG_DOUBLE_H__ */\n", "meta": {"hexsha": "fdb6059904005b8e3f24106646bc9ec69b90497d", "size": 8554, "ext": "h", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/vector/gsl_vector_complex_long_double.h", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/vector/gsl_vector_complex_long_double.h", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/vector/gsl_vector_complex_long_double.h", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 34.7723577236, "max_line_length": 126, "alphanum_fraction": 0.7075052607, "num_tokens": 1783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.024053554381095146, "lm_q1q2_score": 0.010809490171561709}}
{"text": "///\n/// @file\n///\n/// @author Angelika Schwarz (angies@cs.umu.se), Ume\u00e5 University\n/// @author Mirko Myllykoski (mirkom@cs.umu.se), Ume\u00e5 University\n///\n/// @internal LICENSE\n///\n/// Copyright (c) 2019-2020, Ume\u00e5 Universitet\n///\n/// Redistribution and use in source and binary forms, with or without\n/// modification, are permitted provided that the following conditions are met:\n///\n/// 1. Redistributions of source code must retain the above copyright notice,\n///    this list of conditions and the following disclaimer.\n///\n/// 2. Redistributions in binary form must reproduce the above copyright notice,\n///    this list of conditions and the following disclaimer in the documentation\n///    and/or other materials provided with the distribution.\n///\n/// 3. Neither the name of the copyright holder nor the names of its\n///    contributors may be used to endorse or promote products derived from this\n///    software without specific prior written permission.\n///\n/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n/// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n/// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n/// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n/// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n/// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n/// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n/// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n/// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n/// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n/// POSSIBILITY OF SUCH DAMAGE.\n///\n\n#include <starneig_config.h>\n#include <starneig/configuration.h>\n#include <starneig/error.h>\n#include \"core.h\"\n#include \"typedefs.h\"\n#include \"robust.h\"\n#include \"cpu.h\"\n#include \"partition.h\"\n#include \"../../common/common.h\"\n#include \"../../common/node_internal.h\"\n#include \"../../common/matrix.h\"\n#include <starneig/sep_sm.h>\n#include <cblas.h>\n#include <stdlib.h>\n#include <starpu.h>\n#include <math.h>\n#include <float.h>\n\n\nstatic int search_multiplicities(int n, double *lambda, int *lambda_type)\n{\n    int multiplicity = 0;\n    for (int i = 0; i < n; i++) {\n        if (lambda_type[i] == 0) { // REAL\n            double real = lambda[i];\n            for (int j = i+1; j < n; j++) {\n                if (lambda_type[j] == 0 && lambda[j] == real) {\n                    multiplicity = 1;\n                    break;\n                }\n            }\n        }\n        else { // CMPLX\n            double real = lambda[i];\n            double imag = lambda[i+1];\n            for (int j = i+2; j < n; j++) {\n                if (lambda_type[j] == 1 && lambda_type[j+1]) {\n                    if (lambda[j] == real && lambda[j+1] == imag) {\n                        multiplicity = 1;\n                        break;\n                    }\n\n                    j++;\n                }\n            }\n            i++;\n        }\n    }\n\n    return multiplicity;\n}\n\n\nstatic starneig_error_t eigenvectors(\n    struct starneig_eigenvectors_conf const *_conf,\n    int n, int *selected,\n    double *S, int ldS,\n    double *Q, int ldQ,\n    double *Y, int ldY)\n{\n#define S(i,j) S[(i) + (j) * (size_t)ldS]\n#define Q(i,j) Q[(i) + (j) * (size_t)ldQ]\n#define X(i,j) X[(i) + (j) * (size_t)ldX]\n#define Y(i,j) Y[(i) + (j) * (size_t)ldY]\n\n    // use default configuration if necessary\n    struct starneig_eigenvectors_conf *conf;\n    struct starneig_eigenvectors_conf local_conf;\n    if (_conf == NULL)\n        starneig_eigenvectors_init_conf(&local_conf);\n    else\n        local_conf = *_conf;\n    conf = &local_conf;\n\n\n    //\n    // check mandatory arguments\n    //\n\n    if (selected == NULL) {\n        starneig_error(\"Eigenvalue selection bitmap is NULL. Exiting...\");\n        return STARNEIG_INVALID_ARGUMENTS;\n    }\n\n    int num_selected = starneig_eigvec_std_count_selected(n, selected);\n    if (num_selected == 0) {\n        starneig_error(\"Eigenvalue selection bitmap does not have any \"\n                       \"selected eigenvalues. Exiting...\");\n        return STARNEIG_INVALID_ARGUMENTS;\n    }\n\n    if (S == NULL) {\n        starneig_error(\"Matrix S is NULL. Exiting...\");\n        return STARNEIG_INVALID_ARGUMENTS;\n    }\n\n    if (Q == NULL) {\n        starneig_error(\"Matrix Q is NULL. Exiting...\");\n        return STARNEIG_INVALID_ARGUMENTS;\n    }\n\n    if (Y == NULL) {\n        starneig_error(\"Eigenvector matrix is NULL. Exiting...\");\n        return STARNEIG_INVALID_ARGUMENTS;\n    }\n\n\n    //\n    // check configuration\n    //\n\n    if (conf->tile_size == STARNEIG_EIGENVECTORS_DEFAULT_TILE_SIZE) {\n        double select_ratio = (double) num_selected/n;\n        conf->tile_size = MIN(MAX(240, sqrt(n)/sqrt(select_ratio)), 936);\n        starneig_message(\"Setting tile size to %d.\", conf->tile_size);\n    }\n\n    if (conf->tile_size <= 0) {\n        starneig_error(\"Tile size is %d. Exiting...\", conf->tile_size);\n        return STARNEIG_INVALID_CONFIGURATION;\n    }\n\n    //\n    // preprocess\n    //\n\n    // extract the eigenvalues and their type (1-by-1 or 2-by-2 block)\n    double *lambda = (double *) malloc((size_t)n * sizeof(double));\n    int *lambda_type = (int *) malloc((size_t)n * sizeof(int));\n    lambda[n-1] = S(n-1,n-1);\n    lambda_type[n-1] = 0;\n    for (int i = 0; i < n - 1; i++) {\n        if (S(i+1,i) != 0.0) {\n            // A 2-by-2 block in canonical Schur form has the shape\n            // [ S(i,i)      S(i,i+1)   ] = [ a b ]  or [ a -b ]\n            // [ S(i+1,i)    S(i+1,i+1) ]   [-c a ]     [ c  a ].\n            lambda_type[i] = 1;\n            lambda_type[i+1] = 1;\n            double real = S(i+1,i+1);\n            double imag = sqrt(fabs(S(i+1,i)))*sqrt(fabs(S(i,i+1)));\n            lambda[i] = real;\n            lambda[i+1] = imag;\n            i++;\n        }\n        else {\n            // 1-by-1 block\n            lambda_type[i] = 0;\n            lambda[i] = S(i,i);\n        }\n    }\n\n\n    //\n    // sanity check\n    //\n\n    starneig_error_t ret = STARNEIG_SUCCESS;\n    int illposed = search_multiplicities(n, lambda, lambda_type);\n    if (illposed) {\n        starneig_warning(\"Multiple eigenvalues detected.\\n\");\n        ret = STARNEIG_CLOSE_EIGENVALUES;\n    }\n\n\n\n    //\n    // overflow control\n    //\n\n    const double eps = DBL_EPSILON/2;\n    const double smlnum = MAX(2*DBL_MIN, DBL_MIN*((double)n/eps));\n\n\n    //\n    // partition\n    //\n\n    int num_tiles = (n+conf->tile_size-1)/conf->tile_size;\n    int *first_row = (int *) malloc((num_tiles+1)*sizeof(int));\n    int *first_col = (int *) malloc((num_tiles+1)*sizeof(int));\n    starneig_eigvec_std_partition(n, lambda_type, conf->tile_size, first_row);\n    starneig_eigvec_std_partition_selected(n, first_row, selected, num_tiles, first_col);\n\n\n    //\n    // workspace\n    //\n\n    int ldX = ldY;\n    double *X = (double *) malloc((size_t)ldX*num_selected*sizeof(double));\n\n    size_t num_segments = (size_t) num_tiles*num_selected;\n\n    double *Xnorms = (double *) malloc(num_segments*sizeof(double));\n#define Xnorms(col, tilerow) Xnorms[(col) + (tilerow) * (size_t)num_selected]\n\n    scaling_t *scales = (scaling_t*) malloc(num_segments*sizeof(scaling_t));\n#define scales(col, tilerow) scales[(col) + (tilerow) * (size_t)num_selected]\n    starneig_eigvec_std_init_scaling_factor(num_tiles*num_selected, scales);\n\n    double *Snorms =\n        (double *) malloc((size_t)num_tiles*num_tiles*sizeof(double));\n#define Snorms(i,j) Snorms[(i) + (j) * (size_t)num_tiles]\n\n    int *info = (int *) malloc((size_t)num_selected*sizeof(int));\n\n    // Copy all selected eigenvalue types to a compact memory representation.\n    int *selected_lambda_type = (int *) malloc((size_t)num_selected*sizeof(int));\n    int idx = 0;\n    for (int i = 0; i < n; i++) {\n        if (selected[i]) {\n            selected_lambda_type[idx] = lambda_type[i];\n            idx++;\n        }\n    }\n\n\n    //\n    // register\n    //\n\n    starpu_data_handle_t **S_tiles;\n    starpu_data_handle_t **Q_tiles;\n    starpu_data_handle_t **X_tiles;\n    starpu_data_handle_t **Y_tiles;\n    starpu_data_handle_t *selected_tiles;\n    starpu_data_handle_t *lambda_tiles;\n    starpu_data_handle_t *lambda_type_tiles;\n    starpu_data_handle_t *selected_lambda_type_tiles;\n    starpu_data_handle_t **Xnorms_tiles;\n    starpu_data_handle_t **scales_tiles;\n    starpu_data_handle_t **S_tiles_norms;\n    starpu_data_handle_t *info_tiles;\n    S_tiles = malloc(num_tiles*sizeof(starpu_data_handle_t *));\n    Q_tiles = malloc(num_tiles*sizeof(starpu_data_handle_t *));\n    X_tiles = malloc(num_tiles*sizeof(starpu_data_handle_t *));\n    Y_tiles = malloc(num_tiles*sizeof(starpu_data_handle_t *));\n    selected_tiles = malloc(num_tiles*sizeof(starpu_data_handle_t));\n    lambda_tiles = malloc(num_tiles*sizeof(starpu_data_handle_t));\n    lambda_type_tiles = malloc(num_tiles*sizeof(starpu_data_handle_t));\n    selected_lambda_type_tiles = malloc(num_tiles*sizeof(starpu_data_handle_t));\n    Xnorms_tiles = malloc(num_tiles*sizeof(starpu_data_handle_t *));\n    scales_tiles = malloc(num_tiles*sizeof(starpu_data_handle_t *));\n    S_tiles_norms = malloc(num_tiles*sizeof(starpu_data_handle_t *));\n    info_tiles = malloc(num_tiles*sizeof(starpu_data_handle_t));\n    for (int i = 0; i < num_tiles; i++) {\n        S_tiles[i] = malloc(num_tiles*sizeof(starpu_data_handle_t));\n        Q_tiles[i] = malloc(num_tiles*sizeof(starpu_data_handle_t));\n        X_tiles[i] = malloc(num_tiles*sizeof(starpu_data_handle_t));\n        Y_tiles[i] = malloc(num_tiles*sizeof(starpu_data_handle_t));\n        Xnorms_tiles[i] = malloc(num_tiles*sizeof(starpu_data_handle_t));\n        scales_tiles[i] = malloc(num_tiles*sizeof(starpu_data_handle_t));\n        S_tiles_norms[i] = malloc(num_tiles*sizeof(starpu_data_handle_t));\n\n        starpu_vector_data_register(\n            &selected_tiles[i],\n            STARPU_MAIN_RAM,\n            (uintptr_t)(&selected[first_row[i]]),\n            first_row[i+1]-first_row[i],\n            sizeof(int));\n\n        starpu_vector_data_register(\n            &lambda_tiles[i],\n            STARPU_MAIN_RAM,\n            (uintptr_t)(&lambda[first_row[i]]),\n            first_row[i+1]-first_row[i],\n            sizeof(double));\n\n        starpu_vector_data_register(\n            &lambda_type_tiles[i],\n            STARPU_MAIN_RAM,\n            (uintptr_t)(&lambda_type[first_row[i]]),\n            first_row[i+1]-first_row[i],\n            sizeof(int));\n\n        starpu_vector_data_register(\n            &selected_lambda_type_tiles[i],\n            STARPU_MAIN_RAM,\n            (uintptr_t)(&selected_lambda_type[first_col[i]]),\n            first_col[i+1]-first_col[i],\n            sizeof(int));\n\n        starpu_vector_data_register(\n            &info_tiles[i],\n            STARPU_MAIN_RAM,\n            (uintptr_t)(&info[first_col[i]]),\n            first_col[i+1]-first_col[i],\n            sizeof(int));\n\n        for (int j = 0; j < num_tiles; j++) {\n            if (i <= j) {\n                starpu_matrix_data_register(\n                    &S_tiles[i][j],\n                    STARPU_MAIN_RAM,\n                    (uintptr_t)(&S(first_row[i], first_row[j])),\n                    ldS,\n                    first_row[i+1]-first_row[i],\n                    first_row[j+1]-first_row[j],\n                    sizeof(double));\n\n                starpu_variable_data_register(\n                    &S_tiles_norms[i][j],\n                    STARPU_MAIN_RAM,\n                    (uintptr_t)(&Snorms(i,j)),\n                    sizeof(double));\n\n                starpu_matrix_data_register(\n                    &X_tiles[i][j],\n                    STARPU_MAIN_RAM,\n                    (uintptr_t)(&X(first_row[i], first_col[j])),\n                    ldX,\n                    first_row[i+1]-first_row[i],\n                    first_col[j+1]-first_col[j],\n                    sizeof(double));\n\n                starpu_vector_data_register(\n                    &Xnorms_tiles[i][j],\n                    STARPU_MAIN_RAM,\n                    (uintptr_t)(&Xnorms(first_col[j],i)),\n                    first_col[j+1]-first_col[j],\n                    sizeof(double));\n\n                starpu_vector_data_register(\n                    &scales_tiles[i][j],\n                    STARPU_MAIN_RAM,\n                    (uintptr_t)(&scales(first_col[j],i)),\n                    first_col[j+1]-first_col[j],\n                    sizeof(scaling_t));\n            }\n\n            starpu_matrix_data_register(\n                &Q_tiles[i][j],\n                STARPU_MAIN_RAM,\n                (uintptr_t)(&Q(first_row[i], first_row[j])),\n                ldQ,\n                first_row[i+1]-first_row[i],\n                first_row[j+1]-first_row[j],\n                sizeof(double));\n\n            starpu_matrix_data_register(\n                &Y_tiles[i][j],\n                STARPU_MAIN_RAM,\n                (uintptr_t)(&Y(first_row[i], first_col[j])),\n                ldY,\n                first_row[i+1]-first_row[i],\n                first_col[j+1]-first_col[j],\n                sizeof(double));\n        }\n    }\n\n\n    //\n    // insert tasks\n    //\n\n    starneig_eigvec_std_insert_backsolve_tasks(num_tiles,\n        S_tiles, S_tiles_norms, lambda_tiles, lambda_type_tiles,\n        X_tiles, scales_tiles, Xnorms_tiles, selected_tiles,\n        selected_lambda_type_tiles, info_tiles, smlnum,\n        STARPU_MAX_PRIO, STARPU_DEFAULT_PRIO);\n\n    starpu_task_wait_for_all();\n\n    starneig_eigvec_std_unify_scaling(num_tiles, first_row, first_col, scales, X, ldX,\n        lambda_type, selected);\n\n    starneig_eigvec_std_insert_backtransform_tasks(first_row, num_tiles,\n        Q_tiles, X_tiles, Y_tiles);\n\n\n    //\n    // evaluate reliability\n    //\n\n    for (int i = 0; i < num_selected; i++) {\n        if (info[i] != STARNEIG_SUCCESS) {\n            starneig_warning(\"Eigenvector column X(:,%d) was perturbed and \"\n                             \"cannot be trusted.\", i);\n            ret = STARNEIG_CLOSE_EIGENVALUES;\n        }\n    }\n\n    starpu_task_wait_for_all();\n\n\n    //\n    // clean up\n    //\n\n    for (int i = 0; i < num_tiles; i++) {\n        starpu_data_unregister(selected_tiles[i]);\n        starpu_data_unregister(lambda_tiles[i]);\n        starpu_data_unregister(lambda_type_tiles[i]);\n        starpu_data_unregister(selected_lambda_type_tiles[i]);\n        starpu_data_unregister(info_tiles[i]);\n        for (int j = 0; j < num_tiles; j++) {\n            if (i <= j) {\n                starpu_data_unregister(S_tiles[i][j]);\n                starpu_data_unregister(S_tiles_norms[i][j]);\n                starpu_data_unregister(X_tiles[i][j]);\n                starpu_data_unregister(Xnorms_tiles[i][j]);\n                starpu_data_unregister(scales_tiles[i][j]);\n            }\n            starpu_data_unregister(Q_tiles[i][j]);\n            starpu_data_unregister(Y_tiles[i][j]);\n        }\n        free(S_tiles[i]);\n        free(Q_tiles[i]);\n        free(X_tiles[i]);\n        free(Y_tiles[i]);\n        free(Xnorms_tiles[i]);\n        free(scales_tiles[i]);\n        free(S_tiles_norms[i]);\n    }\n    free(S_tiles);\n    free(Q_tiles);\n    free(X_tiles);\n    free(Y_tiles);\n    free(Xnorms_tiles);\n    free(scales_tiles);\n    free(selected_tiles);\n    free(lambda_tiles);\n    free(lambda_type_tiles);\n    free(selected_lambda_type_tiles);\n    free(info_tiles);\n    free(X);\n    free(Xnorms);\n    free(Snorms);\n    free(info);\n    free(scales);\n    free(lambda_type);\n    free(selected_lambda_type);\n    free(lambda);\n    free(first_row);\n    free(first_col);\n\n\n#undef Xnorms\n#undef Snorms\n#undef scales\n#undef S\n#undef Q\n#undef X\n#undef Y\n\n    return ret;\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n\n__attribute__ ((visibility (\"default\")))\nvoid starneig_eigenvectors_init_conf(struct starneig_eigenvectors_conf *conf) {\n    conf->tile_size = STARNEIG_EIGENVECTORS_DEFAULT_TILE_SIZE;\n}\n\n\n__attribute__ ((visibility (\"default\")))\nint starneig_SEP_SM_Eigenvectors_expert(\n    struct starneig_eigenvectors_conf *conf,\n    int n,\n    int selected[],\n    double S[], int ldS,\n    double Q[], int ldQ,\n    double X[], int ldX)\n{\n    CHECK_INIT();\n\n    starneig_node_set_blas_mode(STARNEIG_BLAS_MODE_SEQUENTIAL);\n    starneig_node_set_mode(STARNEIG_MODE_SM);\n    starneig_node_resume_starpu();\n\n    starneig_error_t ret = eigenvectors(\n        conf, n, selected, S, ldS, Q, ldQ, X, ldX);\n\n    starpu_task_wait_for_all();\n    starneig_node_pause_starpu();\n    starneig_node_set_mode(STARNEIG_MODE_OFF);\n    starneig_node_set_blas_mode(STARNEIG_BLAS_MODE_ORIGINAL);\n\n    return ret;\n}\n\n\n\n__attribute__ ((visibility (\"default\")))\nint starneig_SEP_SM_Eigenvectors(\n    int n,\n    int selected[],\n    double S[], int ldS,\n    double Q[], int ldQ,\n    double X[], int ldX)\n{\n    CHECK_INIT();\n    return starneig_SEP_SM_Eigenvectors_expert(\n        NULL, n, selected, S, ldS, Q, ldQ, X, ldX);\n}\n", "meta": {"hexsha": "df42b5f13a8d5456f1b294564150b8a90011c8d6", "size": 17103, "ext": "c", "lang": "C", "max_stars_repo_path": "src/eigenvectors/standard/interface.c", "max_stars_repo_name": "NLAFET/StarNEig", "max_stars_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2019-04-28T17:13:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-24T12:30:19.000Z", "max_issues_repo_path": "src/eigenvectors/standard/interface.c", "max_issues_repo_name": "NLAFET/StarNEig", "max_issues_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/eigenvectors/standard/interface.c", "max_forks_repo_name": "NLAFET/StarNEig", "max_forks_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-04-30T12:14:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-14T09:41:23.000Z", "avg_line_length": 31.8491620112, "max_line_length": 89, "alphanum_fraction": 0.591299772, "num_tokens": 4209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3522017684487511, "lm_q2_score": 0.03067580137836185, "lm_q1q2_score": 0.010804071494041681}}
{"text": "/* Odeint solver */\n#include <pygsl/utils.h>\n#include <pygsl/block_helpers.h>\n#include <pygsl/error_helpers.h>\n#include <Python.h>\n#include <gsl/gsl_odeiv.h>\n#include <gsl/gsl_errno.h>\n\nchar odeiv_module_doc[] = \"XXX odeiv module doc missing!\\n\";\n\nstatic char this_file[] = __FILE__;\nstatic PyObject *module = NULL; /* set by initodeiv */ \n\nstatic void\t\t\t/* generic instance destruction */\ngeneric_dealloc (PyObject *self)\n{\n  DEBUG_MESS(1, \" *** generic_dealloc %p\\n\", (void *) self);\n  PyMem_Free(self);\n}\n\ntypedef struct {\n     PyObject_HEAD\n     gsl_odeiv_step * step;\n     gsl_odeiv_system system;\n     PyObject *py_func;\n     PyObject *py_jac;\n     PyObject *arguments;\n     jmp_buf buffer;\n}\nPyGSL_odeiv_step;\n\ntypedef struct {\n  PyObject_HEAD\n  PyGSL_odeiv_step * step;\n  gsl_odeiv_control * control;\n} PyGSL_odeiv_control;\n\ntypedef struct {\n  PyObject_HEAD\n  PyGSL_odeiv_step * step;\n  PyGSL_odeiv_control * control;\n  gsl_odeiv_evolve * evolve;\n} PyGSL_odeiv_evolve;\n\ntypedef struct {\n  PyObject_HEAD\n  gsl_odeiv_step_type * step_type;\n} PyGSL_odeiv_step_type;\n\ntypedef struct {\n  PyObject_HEAD\n  gsl_odeiv_control_type * control_type;\n} PyGSL_odeiv_control_type;\n\n/*---------------------------------------------------------------------------\n * Declaration of the various Methods\n *---------------------------------------------------------------------------*/\n/*\n * stepper\n */\nstatic int \nPyGSL_odeiv_func(double t, const double y[], double f[], void *params);\nstatic int \nPyGSL_odeiv_jac(double t, const double y[], double *dfdy, double dfdt[], \n\t\tvoid *params);\nstatic PyObject *\nPyGSL_odeiv_step_apply(PyGSL_odeiv_step *self, PyObject *args);\nstatic PyObject *\nPyGSL_odeiv_step_reset(PyGSL_odeiv_step *self, PyObject *args);\nstatic void \nPyGSL_odeiv_step_free(PyGSL_odeiv_step * self);\nstatic PyObject *\nPyGSL_odeiv_step_name(PyGSL_odeiv_step *self, PyObject *args);\nstatic PyObject *\nPyGSL_odeiv_step_order(PyGSL_odeiv_step *self, PyObject *args);\n\n/*\n * control \n */\nstatic PyObject *\nPyGSL_odeiv_control_hadjust(PyGSL_odeiv_control *self, PyObject *args);\nstatic void \nPyGSL_odeiv_control_free(PyGSL_odeiv_control * self);\nstatic PyObject *\nPyGSL_odeiv_control_name(PyGSL_odeiv_control *self, PyObject *args);\n\n/*\n * evolve\n */\nstatic void \nPyGSL_odeiv_evolve_free(PyGSL_odeiv_evolve * self);\nstatic PyObject *\nPyGSL_odeiv_evolve_apply(PyGSL_odeiv_evolve *self, PyObject *args);\nstatic PyObject *\nPyGSL_odeiv_evolve_reset(PyGSL_odeiv_evolve *self, PyObject *args);\n/*---------------------------------------------------------------------------*/\n\nstatic char PyGSL_odeiv_step_type_doc[] = \"A odeiv step type\\n\";\nstatic char PyGSL_odeiv_control_type_doc[] = \"A odeiv control type\\n\";\nstatic char PyGSL_odeiv_evolve_type_doc[] = \"A odeiv evolve type\\n\";\n\n\n\n\n\n\n\n#define PyGSL_ODEIV_GENERIC_TYPE_PYTYPE_ALL                               \\\nstatic PyTypeObject PyGSL_ODEIV_GENERIC_TYPE_PYTYPE = {\t\t          \\\n  PyObject_HEAD_INIT(NULL)\t/* fix up the type slot in initodeiv */\t  \\\n  0,\t\t\t\t/* ob_size */\t\t\t\t  \\\n  PyGSL_ODEIV_GENERIC_TYPE_NAME,     \t/* tp_name */\t\t\t  \\\n  sizeof(PyGSL_ODEIV_GENERIC_TYPE),       /* tp_basicsize */\t\t  \\\n  0,\t\t\t\t/* tp_itemsize */\t\t\t  \\\n\t\t\t\t\t\t\t\t\t  \\\n  /* standard methods */\t\t\t\t\t\t  \\\n  (destructor)  generic_dealloc,   /* tp_dealloc  ref-count==0  */\t  \\\n  (printfunc)   0,\t\t   /* tp_print    \"print x\"     */\t  \\\n  (getattrfunc) 0,                 /* tp_getattr  \"x.attr\"      */\t  \\\n  (setattrfunc) 0,\t\t   /* tp_setattr  \"x.attr=v\"    */\t  \\\n  (cmpfunc)     0,\t\t   /* tp_compare  \"x > y\"       */\t  \\\n  (reprfunc)    0,                 /* tp_repr     `x`, print x  */\t  \\\n\t\t\t\t\t\t\t\t\t  \\\n  /* type categories */\t\t\t\t\t\t\t  \\\n  0,\t\t\t\t/* tp_as_number   +,-,*,/,%,&,>>,pow...*/ \\\n  0,\t\t\t\t/* tp_as_sequence +,[i],[i:j],len, ...*/  \\\n  0,\t\t\t\t/* tp_as_mapping  [key], len, ...*/\t  \\\n\t\t\t\t\t\t\t\t\t  \\\n  /* more methods */\t\t\t\t\t\t\t  \\\n  (hashfunc)     0,\t\t/* tp_hash    \"dict[x]\" */\t\t  \\\n  (ternaryfunc)  0,             /* tp_call    \"x()\"     */\t\t  \\\n  (reprfunc)     0,             /* tp_str     \"str(x)\"  */\t\t  \\\n  (getattrofunc) 0,\t\t/* tp_getattro */\t\t\t  \\\n  (setattrofunc) 0,\t\t/* tp_setattro */\t\t\t  \\\n  0,\t\t\t\t/* tp_as_buffer */\t\t\t  \\\n  0L,\t\t\t\t/* tp_flags */\t\t\t\t  \\\n  PyGSL_ODEIV_GENERIC_TYPE_DOC       /* tp_doc */                         \\\n};\n\n#define PyGSL_ODEIV_GENERIC_TYPE        PyGSL_odeiv_step_type\n#define PyGSL_ODEIV_GENERIC_TYPE_PYTYPE PyGSL_odeiv_step_type_pytype\n#define PyGSL_ODEIV_GENERIC_TYPE_NAME   \"PyGSL_odeiv_step_type\"\n#define PyGSL_ODEIV_GENERIC_TYPE_DOC    PyGSL_odeiv_step_type_doc\nPyGSL_ODEIV_GENERIC_TYPE_PYTYPE_ALL\n\n\n#undef PyGSL_ODEIV_GENERIC_TYPE       \n#undef PyGSL_ODEIV_GENERIC_TYPE_PYTYPE\n#undef PyGSL_ODEIV_GENERIC_TYPE_NAME  \n#undef PyGSL_ODEIV_GENERIC_TYPE_DOC   \n#define PyGSL_ODEIV_GENERIC_TYPE        PyGSL_odeiv_control_type\n#define PyGSL_ODEIV_GENERIC_TYPE_PYTYPE PyGSL_odeiv_control_type_pytype\n#define PyGSL_ODEIV_GENERIC_TYPE_NAME   \"PyGSL_odeiv_control_type\"\n#define PyGSL_ODEIV_GENERIC_TYPE_DOC    PyGSL_odeiv_control_type_doc\nPyGSL_ODEIV_GENERIC_TYPE_PYTYPE_ALL\n\n\n\n#define PyGSLOdeivStepType_Check(v)    ((v)->ob_type == &PyGSL_odeiv_step_type_pytype)\n#define PyGSLOdeivControlType_Check(v) ((v)->ob_type == &PyGSL_odeiv_control_type_pytype)\n#define PyGSLOdeivEvolveType_Check(v)  ((v)->ob_type == &PyGSL_odeiv_evolve_type_pytype)\n\n\n\n\n\n#define PyGSL_ODEIV_GENERIC_ALL                                                           \\\nstatic PyObject *\t\t\t\t\t\t\t\t\t  \\\nPyGSL_ODEIV_GENERIC_GETATTR(PyGSL_ODEIV_GENERIC *self, char *name)\t\t          \\\n{\t\t\t\t\t\t\t\t\t\t\t  \\\n     PyObject *tmp = NULL;\t\t\t\t\t\t\t\t  \\\n\t\t\t\t\t\t\t\t\t\t\t  \\\n     FUNC_MESS_BEGIN();\t\t\t\t\t\t\t\t\t  \\\n \t\t\t\t\t\t\t\t\t\t\t  \\\n     tmp = Py_FindMethod(PyGSL_ODEIV_GENERIC_METHODS, (PyObject *) self, name);\t          \\\n     if(NULL == tmp){\t  \t\t\t\t\t\t\t\t  \\\n\t  PyGSL_add_traceback(module, __FILE__, \"odeiv.__attr__\", __LINE__ - 1);\t  \\\n\t  return NULL;\t\t\t\t\t\t\t\t\t  \\\n     }\t\t\t\t\t\t\t\t\t\t\t  \\\n     return tmp;                                                                          \\\n}                                                                                         \\\nstatic PyTypeObject PyGSL_ODEIV_GENERIC_PYTYPE = {\t\t\t\t\t  \\\n  PyObject_HEAD_INIT(NULL)\t/* fix up the type slot in initcrng */\t\t\t  \\\n  0,\t\t\t\t/* ob_size */\t\t\t\t\t\t  \\\n  PyGSL_ODEIV_GENERIC_NAME,\t\t\t/* tp_name */\t\t\t          \\\n  sizeof(PyGSL_ODEIV_GENERIC),  /* tp_basicsize */\t\t\t\t\t  \\\n  0,\t\t\t\t/* tp_itemsize */\t\t\t\t\t  \\\n\t\t\t\t\t\t\t\t\t\t\t  \\\n  /* standard methods */\t\t\t\t\t\t\t\t  \\\n  (destructor)  PyGSL_ODEIV_GENERIC_DELETE,       /* tp_dealloc  ref-count==0  */\t  \\\n  (printfunc)   0,\t\t                      /* tp_print    \"print x\"     */\t  \\\n  (getattrfunc) PyGSL_ODEIV_GENERIC_GETATTR,       /* tp_getattr  \"x.attr\"      */\t  \\\n  (setattrfunc) 0,\t\t   /* tp_setattr  \"x.attr=v\"    */\t\t\t  \\\n  (cmpfunc)     0,\t\t   /* tp_compare  \"x > y\"       */\t\t\t  \\\n  (reprfunc)    0,                 /* tp_repr     `x`, print x  */\t\t\t  \\\n\t\t\t\t\t\t\t\t\t\t\t  \\\n  /* type categories */\t\t\t\t\t\t\t\t\t  \\\n  0,\t\t\t\t/* tp_as_number   +,-,*,/,%,&,>>,pow...*/\t\t  \\\n  0,\t\t\t\t/* tp_as_sequence +,[i],[i:j],len, ...*/\t\t  \\\n  0,\t\t\t\t/* tp_as_mapping  [key], len, ...*/\t\t\t  \\\n\t\t\t\t\t\t\t\t\t\t\t  \\\n  /* more methods */\t\t\t\t\t\t\t\t\t  \\\n  (hashfunc)     0,\t\t/* tp_hash    \"dict[x]\" */\t\t\t\t  \\\n  (ternaryfunc)  0,             /* tp_call    \"x()\"     */\t\t\t\t  \\\n  (reprfunc)     0,             /* tp_str     \"str(x)\"  */\t\t\t\t  \\\n  (getattrofunc) 0,\t\t/* tp_getattro */\t\t\t\t\t  \\\n  (setattrofunc) 0,\t\t/* tp_setattro */\t\t\t\t\t  \\\n  0,\t\t\t\t/* tp_as_buffer */\t\t\t\t\t  \\\n  0L,\t\t\t\t/* tp_flags */\t\t\t\t\t\t  \\\n  PyGSL_ODEIV_GENERIC_DOC       /* doc */                                                 \\\n};                                                                                        \n\n\n#define PyGSL_ODEIV_GENERIC            PyGSL_odeiv_step\n#define PyGSL_ODEIV_GENERIC_NAME      \"PyGSL_odeiv_step\"\n#define PyGSL_ODEIV_GENERIC_PYTYPE     PyGSL_odeiv_step_pytype\n#define PyGSL_ODEIV_GENERIC_DOC        PyGSL_odeiv_step_doc\n#define PyGSL_ODEIV_GENERIC_GETATTR    PyGSL_odeiv_step_getattr\n#define PyGSL_ODEIV_GENERIC_METHODS    PyGSL_odeiv_step_methods\n#define PyGSL_ODEIV_GENERIC_DELETE     PyGSL_odeiv_step_free\nPyGSL_ODEIV_GENERIC_ALL\n/**/;\n#undef PyGSL_ODEIV_GENERIC       \n#undef PyGSL_ODEIV_GENERIC_NAME  \n#undef PyGSL_ODEIV_GENERIC_PYTYPE\n#undef PyGSL_ODEIV_GENERIC_DOC   \n#undef PyGSL_ODEIV_GENERIC_GETATTR\n#undef PyGSL_ODEIV_GENERIC_METHODS\n#undef PyGSL_ODEIV_GENERIC_DELETE\n#define PyGSL_ODEIV_GENERIC            PyGSL_odeiv_control\n#define PyGSL_ODEIV_GENERIC_NAME      \"PyGSL_odeiv_control\"\n#define PyGSL_ODEIV_GENERIC_PYTYPE     PyGSL_odeiv_control_pytype\n#define PyGSL_ODEIV_GENERIC_DOC        PyGSL_odeiv_control_doc\n#define PyGSL_ODEIV_GENERIC_GETATTR    PyGSL_odeiv_control_getattr\n#define PyGSL_ODEIV_GENERIC_METHODS    PyGSL_odeiv_control_methods\n#define PyGSL_ODEIV_GENERIC_DELETE     PyGSL_odeiv_control_free\nPyGSL_ODEIV_GENERIC_ALL\n/**/;\n#undef PyGSL_ODEIV_GENERIC       \n#undef PyGSL_ODEIV_GENERIC_NAME  \n#undef PyGSL_ODEIV_GENERIC_PYTYPE\n#undef PyGSL_ODEIV_GENERIC_DOC   \n#undef PyGSL_ODEIV_GENERIC_GETATTR\n#undef PyGSL_ODEIV_GENERIC_METHODS\n#undef PyGSL_ODEIV_GENERIC_DELETE\n#define PyGSL_ODEIV_GENERIC            PyGSL_odeiv_evolve\n#define PyGSL_ODEIV_GENERIC_NAME      \"PyGSL_odeiv_evolve\"\n#define PyGSL_ODEIV_GENERIC_PYTYPE     PyGSL_odeiv_evolve_pytype\n#define PyGSL_ODEIV_GENERIC_DOC        PyGSL_odeiv_evolve_doc\n#define PyGSL_ODEIV_GENERIC_GETATTR    PyGSL_odeiv_evolve_getattr\n#define PyGSL_ODEIV_GENERIC_METHODS    PyGSL_odeiv_evolve_methods\n#define PyGSL_ODEIV_GENERIC_DELETE     PyGSL_odeiv_evolve_free\nPyGSL_ODEIV_GENERIC_ALL\n/**/;\n\n\n\n\n\nstatic void \nPyGSL_odeiv_step_free(PyGSL_odeiv_step * self)\n{\n     assert(PyGSL_ODEIV_STEP_Check(self));\n     Py_DECREF(self->py_func);\n     Py_XDECREF(self->py_jac);\n     Py_DECREF(self->arguments);\n     gsl_odeiv_step_free(self->step);\n     PyMem_Free(self);\n}\n\nstatic PyObject *\nPyGSL_odeiv_step_reset(PyGSL_odeiv_step *self, PyObject *args)\n{\n     assert(PyGSL_ODEIV_STEP_Check(self));\n     gsl_odeiv_step_reset(self->step);\n     Py_INCREF(Py_None);\n     return Py_None;\n}\n\nstatic PyObject *\nPyGSL_odeiv_step_name(PyGSL_odeiv_step *self, PyObject *args)\n{\n     assert(PyGSL_ODEIV_STEP_Check(self));\n     return PyString_FromString(gsl_odeiv_step_name(self->step));\n}\n\n{\n     assert(PyGSL_ODEIV_STEP_Check(self));\n     return PyInt_FromLong((long) gsl_odeiv_step_order(self->step));\n}\n\n\n/* --------------------------------------------------------------------------- */\n/* control_hadjust needs a few arrays */\n/*\nextern int \ngsl_odeiv_control_hadjust (gsl_odeiv_control * c, gsl_odeiv_step * s, \n\t\t\t   const double y0[],  const double yerr[], \n\t\t\t   const double dydt[], double * h);\n*/\n\n\nstatic void \nPyGSL_odeiv_control_free(PyGSL_odeiv_control * self)\n{\n     assert(PyGSL_ODEIV_CONTROL_Check(self));\n     Py_DECREF(self->step);\n     //gsl_odeiv_control_free(self->control);\n     PyMem_Free(self);\n}\n\nstatic PyObject *\nPyGSL_odeiv_control_name(PyGSL_odeiv_control *self, PyObject *args)\n{\n     assert(PyGSL_ODEIV_CONTROL_Check(self));\n     return PyString_FromString(gsl_odeiv_control_name(self->control));\n}\n\nstatic void \nPyGSL_odeiv_evolve_free(PyGSL_odeiv_evolve * self)\n{\n     assert(PyGSL_ODEIV_EVOLVE_Check(self));\n     Py_DECREF(self->step);\n     Py_DECREF(self->control);\n     gsl_odeiv_evolve_free(self->evolve);\n     PyMem_Free(self);\n}\n\nstatic PyObject *\nPyGSL_odeiv_evolve_reset(PyGSL_odeiv_evolve *self, PyObject *args)\n{\n     assert(PyGSL_ODEIV_EVOLVE_Check(self));\n     gsl_odeiv_evolve_reset(self->evolve);\n     Py_INCREF(Py_None);\n     return Py_None;\n}\n\n\n#if 0\nstatic\nvoid create_odeiv_step_types(PyObject *module_dict)\n{\n\n     PyGSL_odeiv_step_type *a_odeiv_step = NULL;\n     PyObject *item=NULL;\n\n     gsl_odeiv_step_type ** thistype;\n     gsl_odeiv_step_type const * const step_types[]  ={\n\t  gsl_odeiv_step_rk2,\n\t  gsl_odeiv_step_rk4,\n\t  gsl_odeiv_step_rkf45,\n\t  gsl_odeiv_step_rkck,\n\t  gsl_odeiv_step_rk8pd,\n\t  gsl_odeiv_step_rk2imp,\n\t  gsl_odeiv_step_rk4imp,\n\t  gsl_odeiv_step_bsimp,\n\t  gsl_odeiv_step_gear1,\n\t  gsl_odeiv_step_gear2,\n\t  NULL\n     };\n\n     FUNC_MESS_BEGIN();\n\n     thistype = (gsl_odeiv_step_type **) step_types;\n     while((*thistype) != NULL){\n\t  a_odeiv_step =  PyObject_NEW(PyGSL_odeiv_step_type, &PyGSL_odeiv_step_type_pytype);\n\t  assert(a_odeiv_step);\n\t  a_odeiv_step->step_type = (gsl_odeiv_step_type *) *thistype;\n\t  item = PyString_FromString((*thistype)->name);\n\t  DEBUG_MESS(2, \"Preparing step type -->%s<--\", PyString_AsString(item));\n\t  PyGSL_clear_name(PyString_AsString(item), PyString_Size(item));\n\t  DEBUG_MESS(2, \"Adding step type -->%s<--\",  PyString_AsString(item));\n\t  assert(item);\n\t  PyDict_SetItem(module_dict, item, (PyObject *) a_odeiv_step);\n\t  /* Py_DECREF(item); */\n\t  item = NULL;\t  \n\t  thistype++;\n\n     }\n     FUNC_MESS_END();\n}\n#endif\n\n\nstatic PyMethodDef PyGSL_odeiv_module_functions[] = {\n     {\"step_rk2\",    PyGSL_odeiv_step_init_rk2,    METH_VARARGS|METH_KEYWORDS, NULL},\n     {\"step_rk4\",    PyGSL_odeiv_step_init_rk4,    METH_VARARGS|METH_KEYWORDS, NULL},\n     {\"step_rkf45\",  PyGSL_odeiv_step_init_rkf45,  METH_VARARGS|METH_KEYWORDS, NULL},\n     {\"step_rkck\",   PyGSL_odeiv_step_init_rkck,   METH_VARARGS|METH_KEYWORDS, NULL},\n     {\"step_rk8pd\",  PyGSL_odeiv_step_init_rk8pd,  METH_VARARGS|METH_KEYWORDS, NULL},\n     {\"step_rk2imp\", PyGSL_odeiv_step_init_rk2imp, METH_VARARGS|METH_KEYWORDS, NULL},\n     {\"step_rk4imp\", PyGSL_odeiv_step_init_rk4imp, METH_VARARGS|METH_KEYWORDS, NULL},\n     {\"step_bsimp\",  PyGSL_odeiv_step_init_bsimp,  METH_VARARGS|METH_KEYWORDS, NULL},\n     {\"step_gear1\",  PyGSL_odeiv_step_init_gear1,  METH_VARARGS|METH_KEYWORDS, NULL},\n     {\"step_gear2\",  PyGSL_odeiv_step_init_gear2,  METH_VARARGS|METH_KEYWORDS, NULL},\n     {\"control_standard_new\", PyGSL_odeiv_control_init_standard_new, METH_VARARGS, NULL},\n     {\"control_y_new\",        PyGSL_odeiv_control_init_y_new,        METH_VARARGS, NULL},\n     {\"control_yp_new\",       PyGSL_odeiv_control_init_yp_new,       METH_VARARGS, NULL},\n     {\"evolve\", PyGSL_odeiv_evolve_init, METH_VARARGS, NULL},\n     {NULL, NULL, 0}        /* Sentinel */\n};\n\nvoid \ninitodeiv(void)\n{\n     PyObject *m=NULL, *item=NULL, *dict=NULL;\n\n     FUNC_MESS_BEGIN();\n     fprintf(stderr, \"Compiled at %s %s\\n\", __DATE__, __TIME__);\n     m = Py_InitModule(\"odeiv\", PyGSL_odeiv_module_functions);\n     assert(m);\n     module = m;\n     import_array();\n     init_pygsl();\n\n     PyGSL_odeiv_step_type_pytype.ob_type = &PyType_Type;\n     PyGSL_odeiv_control_type_pytype.ob_type = &PyType_Type;\n\n     PyGSL_odeiv_step_pytype.ob_type = &PyType_Type;\n     PyGSL_odeiv_control_pytype.ob_type = &PyType_Type;\n     PyGSL_odeiv_evolve_pytype.ob_type = &PyType_Type;\n\n     dict = PyModule_GetDict(m);\n     /* create_odeiv_step_types(dict); */\n     if(!dict)\n\t  goto fail;\n     \n     if (!(item = PyString_FromString(odeiv_module_doc))){\n\t  PyErr_SetString(PyExc_ImportError, \n\t\t\t  \"I could not generate module doc string!\");\n\t  goto fail;\n     }\n     if (PyDict_SetItemString(dict, \"__doc__\", item) != 0){\n\t  PyErr_SetString(PyExc_ImportError, \n\t\t\t  \"I could not init doc string!\");\n\t  goto fail;\n     }\n     \n     FUNC_MESS_END();\n     return;\n fail:\n     FUNC_MESS(\"Fail\");\n     fprintf(stderr, \"Import of module odeiv failed!\\n\");\n}\n\n", "meta": {"hexsha": "639f8d785c9647ec0b184433c005d64be88bf22b", "size": 15219, "ext": "c", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/testing/src/solvers/old/odeiv_old.c", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/testing/src/solvers/old/odeiv_old.c", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/testing/src/solvers/old/odeiv_old.c", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 34.1233183857, "max_line_length": 91, "alphanum_fraction": 0.6543136868, "num_tokens": 4537, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36296920551961676, "lm_q2_score": 0.02976009534431753, "lm_q1q2_score": 0.01080199816331498}}
{"text": "/**\n * File: scaleback_utils.c\n * Subroutine for the WFC3 background scaling\n *\n */\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_multifit_nlin.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_sort.h>\n#include \"aXe_grism.h\"\n#include \"aXe_utils.h\"\n#include \"spc_FITScards.h\"\n#include \"spce_sect.h\"\n#include \"spce_fitting.h\"\n#include \"spce_is_in.h\"\n#include \"spc_back.h\"\n#include \"spce_pathlength.h\"\n#include \"trfit_utils.h\"\n#include \"nicback_utils.h\"\n#include \"scaleback_utils.h\"\n\n/**\n * Function: fit_to_FITScards\n * Fills the results of the fitting into a set of fits cards.\n *\n * Parameters:\n * @param bck_vals   - vector with the fit results\n * @param npixels    - dimension of all images\n *\n * Returns:\n * @return cards - the list of fits header cards\n */\nFITScards *fit_to_FITScards(const gsl_vector* bck_vals, const px_point npixels)\n{\n    char templt[FLEN_CARD];\n    int i=0,keytype, f_status=0;\n    int npix_tot;\n\n    FITScards *cards;\n\n    // allocate the cards\n    cards = allocate_FITScards(7);\n\n    // compute the number of pixels\n    npix_tot = npixels.x * npixels.y;\n\n    i=0;\n    sprintf(templt,\"SCALVAL = %e / computed scale value\", gsl_vector_get(bck_vals, 0));\n    fits_parse_template (templt, cards->cards[i++], &keytype, &f_status);\n    sprintf(templt,\"SCALERR = %e / error for scale value\", gsl_vector_get(bck_vals, 1));\n    fits_parse_template (templt, cards->cards[i++], &keytype, &f_status);\n    sprintf(templt,\"NPIXINI = %e / initial fill value\", gsl_vector_get(bck_vals, 2));\n    fits_parse_template (templt, cards->cards[i++], &keytype, &f_status);\n    sprintf(templt,\"NPIXFIN = %e / final fill value\", gsl_vector_get(bck_vals, 3));\n    fits_parse_template (templt, cards->cards[i++], &keytype, &f_status);\n    sprintf(templt,\"FRACINI = %e / initial fill value\", gsl_vector_get(bck_vals, 2) / (float)npix_tot);\n    fits_parse_template (templt, cards->cards[i++], &keytype, &f_status);\n    sprintf(templt,\"FRACFIN = %e / final fill value\", gsl_vector_get(bck_vals, 3) / (float)npix_tot);\n    fits_parse_template (templt, cards->cards[i++], &keytype, &f_status);\n    sprintf(templt,\"NITER = %d / number of iterations\", (int)gsl_vector_get(bck_vals, 4));\n    fits_parse_template (templt, cards->cards[i++], &keytype, &f_status);\n\n    // return the filled cards\n    return cards;\n}\n\n/**\n * Function: make_scale_back\n * Loads the various image data inputs and performs a fit using a kappa-sigma\n * clipping iteration. Then a scaled version of one of the input images\n * is produced and written to disk. Optionally, an ASCII list with the\n * pixel values before the fitting is produced.\n *\n * Parameters:\n * @param grism_image - full pathname to the grism image\n * @param grism_mask  - full pathname to the mask image\n * @param conf_file   - full pathname to the configuration file\n * @param scale_image - full pathname to the scaling (=master sky) image\n * @param bck_image   - full pathname to the scaled (=background) image\n * @param plist_name  - full pathname to the pixel list\n * @param scale_to_master - integer/boolean to specify what should be scaled as output\n * @param make_plis   - integer/boolean to request a pixel list as output\n *\n * Returns:\n * @return -\n */\nvoid\nmake_scale_back(char grism_image[], const char grism_mask[], char conf_file[],\n\t\tconst char scale_image[], char bck_image[], const char plist_name[],\n\t\tconst int scale_to_master, const int make_plis)\n{\n  px_point npixels;\n\n  gsl_matrix *gr_img;\n  gsl_matrix *gr_dqval;\n  gsl_matrix *gr_mask;\n  gsl_matrix *sc_img;\n  gsl_matrix *bck_img;\n\n  gsl_vector *bck_vals;\n\n  fitbck_data *fbck_data;\n  //int f_status=0;\n\n  FITScards *cards;\n\n  aperture_conf  *conf;\n\n  char  ID[MAXCHAR];\n\n  // fix the extension name\n  sprintf (ID, \"BCK\");\n\n  // read the configuration file\n  // determine all extensions\n  conf = get_aperture_descriptor(conf_file);\n  get_extension_numbers(grism_image, conf, conf->optkey1, conf->optval1);\n\n  // load the scale image\n  fprintf(stdout,\"Loading DATA from: %s...\", scale_image);\n  sc_img = FITSimage_to_gsl(scale_image, 1, 1);\n  fprintf(stdout,\". Done.\\n\");\n\n  // load the grism image\n  fprintf(stdout,\"Loading DATA from: %s...\", grism_image);\n  gr_img = FITSimage_to_gsl(grism_image, conf->science_numext, 1);\n  fprintf(stdout,\". Done.\\n\");\n\n  if (conf->dq_numext < 0)\n    {\n    // allocate the space for the dq-image\n    // set all values to 0.0\n    gr_dqval = gsl_matrix_alloc(gr_img->size1, gr_img->size2);\n    gsl_matrix_set_all (gr_dqval, 0.0);\n    }\n  else\n    {\n    // load the scale dq values\n    fprintf(stdout,\"Loading DQ from: %s...\", grism_image);\n    gr_dqval = FITSimage_to_gsl(grism_image, conf->dq_numext, 1);\n    fprintf(stdout,\". Done.\\n\");\n    }\n\n  // load the grism mask\n  fprintf(stdout,\"Loading DATA from: %s...\", grism_mask);\n  gr_mask = FITSimage_to_gsl(grism_mask, 2, 1);\n  fprintf(stdout,\". Done.\\n\");\n\n  // get the number of pixels\n  npixels.x = sc_img->size1;\n  npixels.y = sc_img->size2;\n\n  // report the number of pixels\n  //fprintf(stdout,\"Loading DATA from: %i pix\\n\", npixels.x * npixels.y);\n\n  // allocate memory for the fit data\n  fbck_data = alloc_fitbck_data(npixels.x * npixels.y);\n\n  // fill the data into the structure\n  if (scale_to_master)\n    fill_cont_data(gr_img, gr_dqval, gr_mask, sc_img, fbck_data, conf->dqmask);\n  else\n    fill_mask_data(gr_img, gr_dqval, gr_mask, sc_img, fbck_data, conf->dqmask);\n\n\n  // make a pixel list if desired\n  if (make_plis)\n    print_plis(fbck_data, plist_name);\n\n  // make the fit\n  bck_vals = make_ksig_scalefit(fbck_data);\n\n  // report the result of the fit onto the screen\n  fprintf(stdout, \"\\nScale result image %s : c0 = %f +- %f\", grism_image, gsl_vector_get(bck_vals, 0), gsl_vector_get(bck_vals, 1));\n  fprintf(stdout, \"\\nInitial fill factor: %.1f%%, final: %.1f%%\", 100.0 * gsl_vector_get(bck_vals, 2) / ((float)npixels.x * (float)npixels.y), 100.0 *gsl_vector_get(bck_vals, 3) / ((float)npixels.x * (float)npixels.y));\n  fprintf(stdout, \"\\nNumber of iterations: % 2i\\n\\n\", (int)gsl_vector_get(bck_vals, 4));\n\n  if (scale_to_master)\n    bck_img = compute_scale_grism(gr_img, gr_dqval, gr_mask, conf->dqmask, bck_vals);\n  else\n    bck_img = compute_scale_master(sc_img, bck_vals);\n\n  // write the background image to a file\n  fprintf(stdout,\"Writing data to: %s...\", bck_image);\n  gsl_to_FITSimage (bck_img, bck_image, 1, ID);\n  cards = fit_to_FITScards(bck_vals, npixels);\n  put_FITS_cards(bck_image, 1, cards);\n  fprintf(stdout,\". Done.\\n\");\n\n  // release memory\n  free_fitbck_data(fbck_data);\n  free_FITScards(cards);\n  gsl_matrix_free(sc_img);\n  gsl_matrix_free(gr_img);\n  gsl_matrix_free(gr_dqval);\n  gsl_matrix_free(gr_mask);\n  gsl_matrix_free(bck_img);\n  gsl_vector_free(bck_vals);\n  free_aperture_conf(conf);\n}\n\n/**\n * Function: print_plis\n * Prints the content of a pixel list structure\n * to an ASCII file.\n *\n * Parameters:\n * @param fbck_data  - the list of pixel values\n * @param plist_name - full pathname to the pixel list\n *\n * Returns:\n * @return -\n */\nvoid\nprint_plis(const fitbck_data *fbck_data, const char plist_name[])\n{\n    int index=0;\n    char Buffer[10240];\n    FILE *fout;\n\n    // open the pixel list\n    fout = fopen(plist_name, \"w\");\n\n    // go over all data values\n    for (index=0; index < fbck_data->n_data; index++)\n      {\n      // put the values into the buffer\n      sprintf (Buffer, \"%i %i %e %e\\n\",fbck_data->x_pos[index], fbck_data->y_pos[index],\n          fbck_data->x_values[index], fbck_data->y_values[index]);\n\n      // push the buffer to the  file\n      fputs (Buffer, fout);\n      }\n\n    // close the pixel file\n    fclose(fout);\n}\n\n\n/**\n * Function: compute_scale_grism\n * Computes a scaled version of the input grism images, using the\n * scale given as input. Pixels masked in other images are given\n * a fixed value.\n *\n * Parameters:\n * @param gr_img  - the list of pixel values\n * @param gr_dqval - full pathname to the pixel list\n * @param gr_mask - full pathname to the pixel list\n * @param bck_vals - full pathname to the pixel list\n *\n * Returns:\n * @return bck_img - the scaled grism image\n */\ngsl_matrix *\ncompute_scale_grism(gsl_matrix *gr_img, gsl_matrix *gr_dqval, gsl_matrix *gr_mask,\n\t\tint dqmask, gsl_vector *bck_vals)\n{\n    gsl_matrix *bck_img;\n\n    int ii, jj;\n    double scale=0.0;\n\n    // get the scale\n    scale = gsl_vector_get(bck_vals, 0);\n\n    // allocate the space for the background image\n    bck_img = gsl_matrix_alloc(gr_img->size1, gr_img->size2);\n\n    // go over each row\n    for (ii=0; ii < (int)gr_img->size1; ii++)\n      // go over each column\n      for (jj=0; jj < (int)gr_img->size2; jj++)\n        // compute and set the value in the background image\n        if (gsl_matrix_get(gr_mask, ii, jj) > 0.0 ||\n            (int)gsl_matrix_get(gr_dqval, ii, jj) & dqmask)\n          gsl_matrix_set(bck_img, ii, jj, MASK_VALUE);\n        else\n          // using the fit values only\n          gsl_matrix_set(bck_img, ii, jj, gsl_matrix_get(gr_img, ii, jj) * scale);\n\n    // return the background image\n    return bck_img;\n}\n\n/**\n * Function: compute_scale_master\n * Computes a scaled version of the scaling (=master sky) image,\n * using the scale given as input.\n *\n * Parameters:\n * @param sc_img  - the list of pixel valuessc_img\n * @param bck_vals - full pathname to the pixel list\n *\n * Returns:\n * @return bck_img - the scaled grism image\n */\ngsl_matrix *\ncompute_scale_master(const gsl_matrix *sc_img, const gsl_vector *bck_vals)\n{\n    gsl_matrix *bck_img;\n\n    int ii, jj;\n    double scale=0.0;\n\n    // get the scale\n    scale = gsl_vector_get(bck_vals, 0);\n\n    // allocate the space for the background image\n    bck_img = gsl_matrix_alloc(sc_img->size1, sc_img->size2);\n\n    // go over each row\n    for (ii=0; ii < (int)sc_img->size1; ii++)\n      // go over each column\n      for (jj=0; jj < (int)sc_img->size2; jj++)\n        // scale the master sky\n        gsl_matrix_set(bck_img, ii, jj, gsl_matrix_get(sc_img, ii, jj) * scale);\n\n    // return the background image\n    return bck_img;\n}\n\n/**\n * Function: fill_mask_data\n * Fills the pixel value structure with the data for the x/y-positions,\n * the grism image and the scaling image values and a weigth. dq-flagged\n * pixels and masked pixel are neglected. The mask is supposed to be a background\n * mask where pixel with a value < 900000 shall be neglected.\n * The weights are initially all set to 1.\n *\n * Parameters:\n * @param gr_img    - the grism image array\n * @param gr_dqval  - the dq-value array\n * @param gr_mask   - the grism mask array\n * @param sc_img    - the scaling image array\n * @param fbck_data - the pixel list structure\n * @param dqmask    - dq value from the configuration file\n *\n * Returns:\n * @return -\n */\nvoid\nfill_mask_data(gsl_matrix *gr_img, gsl_matrix *gr_dqval, gsl_matrix *gr_mask,\n\t\tgsl_matrix *sc_img, fitbck_data *fbck_data, int dqmask)\n{\n    int ix=0;\n    int iy=0;\n    int index=0;\n\n    // intitialize the index for\n    // the fit_data structure\n    index = 0;\n\n    // go over all pixels\n    // in the grism image\n    for (ix=0; ix < (int)sc_img->size1; ix++)\n      {\n      for (iy=0; iy < (int)sc_img->size2; iy++)\n        {\n        // set the scale image pixel as independent variable\n        fbck_data->x_values[index] = gsl_matrix_get(gr_img, ix, iy);\n\n        // set the grism image pixel as dependent variable\n        fbck_data->y_values[index] = gsl_matrix_get(sc_img, ix, iy);;\n\n        // set the x- and y-positions\n        fbck_data->x_pos[index] = ix;\n        fbck_data->y_pos[index] = iy;\n\n        // check whether the pixel was masked out\n        // or is part of an object\n        if (gsl_matrix_get(sc_img, ix, iy) < 0.0 ||\n            gsl_matrix_get(gr_mask, ix, iy) < -900000.0 ||\n            ((int)gsl_matrix_get(gr_dqval, ix, iy) & dqmask))\n          {\n          continue;\n          }\n        else\n          {\n          // give the pixel full weight\n          //x,y,value_back,value_grism_imag\n          fbck_data->e_values[index] = 1.0;\n\n          // enhance the counter\n          index++;\n          }\n        }\n      }\n\n    fbck_data->n_data = index;\n    fprintf(stdout, \"\\nNumber of pixels in structure: %i\\n\\n\", fbck_data->n_data);\n\n    if (fbck_data->n_data < 1)\n      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n          \"aXe_SCALEBCK: no data left to determine the scale!\\n\");\n}\n\n/**\n * Function: fill_cont_data\n * Fills the pixel value structure with the data for the x/y-positions,\n * the grism image and the scaling image values and a weigth. dq-flagged\n * pixels and masked pixel are neglected. The mask is supposed to be a geometric\n * contamination where pixel with a value > 0 shall be neglected.\n * The weights are initially all set to 1.\n *\n * Parameters:\n * @param gr_img    - the grism image array\n * @param gr_dqval  - the dq-value array\n * @param gr_mask   - the grism mask array\n * @param sc_img    - the scaling image array\n * @param fbck_data - the pixel list structure\n *\n * Returns:\n * @return -\n */\nvoid\nfill_cont_data(gsl_matrix *gr_img, gsl_matrix *gr_dqval, gsl_matrix *gr_mask,\n                gsl_matrix *sc_img, fitbck_data *fbck_data, int dqmask)\n{\n    int ix=0;\n    int iy=0;\n    int index=0;\n\n    // intitialize the index for\n    // the fit_data structure\n    index = 0;\n\n    // go over all pixels\n    // in the grism image\n    for (ix=0; ix < (int)sc_img->size1; ix++)\n      {\n      for (iy=0; iy < (int)sc_img->size2; iy++)\n        {\n        // set the scale image pixel as independent variable\n        fbck_data->x_values[index] = gsl_matrix_get(sc_img, ix, iy);\n\n        // set the grism image pixel as dependent variable\n        fbck_data->y_values[index] = gsl_matrix_get(gr_img, ix, iy);;\n\n        // set the x- and y-positions\n        fbck_data->x_pos[index] = ix;\n        fbck_data->y_pos[index] = iy;\n\n        // check whether the pixel was masked out\n        // or is part of an object\n        if (gsl_matrix_get(sc_img, ix, iy) < 0.0 ||\n            gsl_matrix_get(gr_mask, ix, iy) > 0.0 ||\n            ((int)gsl_matrix_get(gr_dqval, ix, iy) & dqmask))\n          continue;\n        else\n          {\n          // give the pixel full weight\n          //x,y,value_back,value_grism_imag\n          fbck_data->e_values[index] = 1.0;\n\n          // enhance the counter\n          index++;\n          }\n        }\n      }\n\n    fbck_data->n_data = index;\n    fprintf(stdout, \"\\nNumber of pixels in structure: %i\\n\\n\", fbck_data->n_data);\n\n    if (fbck_data->n_data < 1)\n      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n          \"aXe_SCALEBCK: no data left to determine the scale!\\n\");\n}\n\n/**\n * Function: make_ksig_scalefit\n * Determines the scale from the values in the pixel value structure.\n * The results are determined iteratively while rejecting pixels via\n * kappa-sigma clipping to get robust measurements. The results are\n * the scale value, the standard deviation, the final number of\n * not rejected points and the number of iterations.\n *\n * Parameters:\n * @param fbck_data - the pixel value structure\n *\n * Returns:\n * @return bck_vals - a vector with the fit results\n */\ngsl_vector *\nmake_ksig_scalefit(fitbck_data *fbck_data)\n{\n  gsl_vector *bck_vals=NULL;\n\n  float old_scale;\n  int index=0;\n  int clipped=1;\n\n  bck_vals = gsl_vector_alloc(6);\n\n  // check whether iterations still\n  // must be done and whether\n  // the data was changed from clipping\n  old_scale= 1.0e+06;\n  while (index < N_BCKSCALE_ITER && clipped)\n    {\n\n    // make a non-weighted linear fit\n    get_bck_scale(fbck_data->x_values, fbck_data->y_values, fbck_data->e_values,\n        fbck_data->n_data, bck_vals);\n\n    // make a clipping iteration\n    clipped = clipp_scale_data(fbck_data, bck_vals, N_BCKSCALE_KAPPA);\n\n    // break the iteration if the scale change is below a certain threshold\n    if (fabs((gsl_vector_get(bck_vals, 0)-old_scale)/gsl_vector_get(bck_vals, 0)) < N_BCKSCALE_ACCUR)\n      clipped = 0;\n\n    // store the new scale\n    old_scale = gsl_vector_get(bck_vals, 0);\n\n    // inhance the clipping counter\n    index++;\n    }\n\n  // set the number of iterations\n  gsl_vector_set(bck_vals, 4, (double)index);\n\n  // return the fit result\n  return bck_vals;\n}\n\n/**\n * Function: get_bck_scale\n * Computes the scale value from the pixel values in two arrays.\n * The scale value is the median value of all input with weight.\n * Also the standard deviation, the total number of input and\n * the number of input with weight is returned.\n *\n * Parameters:\n * @param xs       - pixel values from one image\n * @param ys       - pixel values from second image\n * @param ws       - weight values\n * @param n_elem   - number of elements\n * @param bck_vals - vector for the result\n *\n * Returns:\n * @return -\n */\nvoid\nget_bck_scale(const double *xs, double *ys, double *ws,\n\t\t  const int n_elem, gsl_vector *bck_vals)\n{\n  int i, m;\n  double *tmp;\n  double median;\n  double stdev;\n\n  // allocate space for temporary vectors\n  tmp = (double *) malloc (n_elem * sizeof (double));\n\n  // initialize the array\n  for (i = 0; i < n_elem; i++)\n    tmp[i] = 0.0;\n\n  // fill the temporary vectors\n  // with scale values and weights\n  m = 0;\n  for (i = 0; i < n_elem; i++)\n  {\n    if (ws[i] > 0.0 && ys[i] != 0.0)\n      {\n      tmp[m] = xs[i] / ys[i];\n      m++;\n      }\n  }\n\n  // sort the vector\n  gsl_sort( tmp, 1, m);\n\n  // just confirm the sorting\n  for (i = 1; i < m; i++)\n    if (tmp[i] < tmp[i-1])\n      fprintf(stdout, \"Wrong: %f <--> %f\\n\", tmp[i],tmp[i-1]);\n\n  // take the home made median\n  median = tmp[(int)m/2];\n\n  // get the standard deviation\n  stdev = comp_stdev_from_array(tmp, m, median);\n\n  // put the results in the vector\n  gsl_vector_set(bck_vals, 0, median);\n  gsl_vector_set(bck_vals, 1, stdev);\n  gsl_vector_set(bck_vals, 2, (double)n_elem);\n  gsl_vector_set(bck_vals, 3, (double)m);\n\n  // release memory\n  free(tmp);\n}\n\n/**\n * Function: clipp_scale_data\n * Set the weight in the pixel value structure such as to clip\n * point that deviate from the mean/characteristic value by\n * more than the allowed amount.\n *\n * Parameters:\n * @param fbck_data - pixel values from one image\n * @param bck_vals  - vector for the result\n * @param kappa     - vector for the result\n *\n * Returns:\n * @return nclip - integer/boolean indicating new clipping\n */\nint\nclipp_scale_data(fitbck_data *fbck_data, const gsl_vector *bck_vals,\n\t\tconst float kappa)\n{\n    int index;\n    int nclip=0;\n    int newclip=0;\n    double mean;\n    //double stdev;\n    double absdev;\n\n    // get the mean value\n    mean = gsl_vector_get(bck_vals, 0);\n\n    // compute the maximum allowed deviation\n    absdev = kappa * gsl_vector_get(bck_vals, 1);\n\n    // go over all data values\n    for (index=0; index < fbck_data->n_data; index++)\n      {\n      // avoid zero values\n      if (fbck_data->y_values[index] != 0.0)\n        {\n        // check whether the actual value is outside the allowed range\n        if (fabs(mean - (fbck_data->x_values[index]/fbck_data->y_values[index])) > absdev)\n          {\n          // check and mark clip changes\n          if (fbck_data->e_values[index])\n            newclip = 1;\n\n          // set the weight, change the counter\n          fbck_data->e_values[index] = 0.0;\n          nclip++;\n          }\n        else\n          {\n          // set the weight\n          fbck_data->e_values[index] = 1.0;\n          }\n        }\n      else\n        {\n        // set the weight, change the counter\n        fbck_data->e_values[index] = 0.0;\n        nclip++;\n        }\n      }\n\n    // return the newclip indicator\n    return newclip;\n}\n", "meta": {"hexsha": "8bc6910772a8cc2a638f2ec41b76b5da94c1f8e6", "size": 19480, "ext": "c", "lang": "C", "max_stars_repo_path": "cextern/src/scaleback_utils.c", "max_stars_repo_name": "sosey/pyaxe", "max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cextern/src/scaleback_utils.c", "max_issues_repo_name": "sosey/pyaxe", "max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cextern/src/scaleback_utils.c", "max_forks_repo_name": "sosey/pyaxe", "max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4259818731, "max_line_length": 219, "alphanum_fraction": 0.657238193, "num_tokens": 5576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046348141882, "lm_q2_score": 0.025565216289747925, "lm_q1q2_score": 0.010801422372445683}}
{"text": "#ifndef __NEURALNETWORK_INCLUDED__\n#define __NEURALNETWORK_INCLUDED__\n\n#ifdef __APPLE__\n#include <Accelerate/Accelerate.h>\n#else\n#include <cblas.h>\n#endif\n\n#include <string>\n#include \"Frame.h\"\n\nusing namespace std;\n\nstruct Matrix {\n  double* data;\n  int rows;\n  int cols;\n};\n\nclass NeuralNetwork {\n public:\n  NeuralNetwork(string theta1_filename, string theta2_filename);\n  ~NeuralNetwork();\n\n  double* predict(Frame* frame);\n private:\n  Matrix theta1_;\n  Matrix theta2_;\n};\n\nMatrix read2DMatrixFromFile(string filename);\n\ndouble sigmoid(double x);\n\n#endif\n", "meta": {"hexsha": "b2385e4125ecf05c4b1f6c17fa371b94f5a2c271", "size": 557, "ext": "h", "lang": "C", "max_stars_repo_path": "NeuralNetwork.h", "max_stars_repo_name": "prateekralhan/Self-Driving-Car-wih-survillence-support-system", "max_stars_repo_head_hexsha": "175ba4d6f0fbb27a51d67342892014fa4eee02aa", "max_stars_repo_licenses": ["Apache-2.0", "BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NeuralNetwork.h", "max_issues_repo_name": "prateekralhan/Self-Driving-Car-wih-survillence-support-system", "max_issues_repo_head_hexsha": "175ba4d6f0fbb27a51d67342892014fa4eee02aa", "max_issues_repo_licenses": ["Apache-2.0", "BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NeuralNetwork.h", "max_forks_repo_name": "prateekralhan/Self-Driving-Car-wih-survillence-support-system", "max_forks_repo_head_hexsha": "175ba4d6f0fbb27a51d67342892014fa4eee02aa", "max_forks_repo_licenses": ["Apache-2.0", "BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.0540540541, "max_line_length": 64, "alphanum_fraction": 0.7540394973, "num_tokens": 130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.34158248603300034, "lm_q2_score": 0.031618768751487156, "lm_q1q2_score": 0.010800417635435529}}
{"text": "#pragma once\n\n#include <algorithm>\n#include <array>\n#include <cstdint>\n#include <initializer_list>\n#include <iterator>\n#include <sstream>\n#include <string>\n\n#include <absl/types/span.h>\n#include <gsl/gsl>\n\n#include \"chainerx/constant.h\"\n#include \"chainerx/error.h\"\n#include \"chainerx/optional_container_arg.h\"\n#include \"chainerx/stack_vector.h\"\n\nnamespace chainerx {\n\nclass Axes : public StackVector<int8_t, kMaxNdim> {\n    using BaseVector = StackVector<int8_t, kMaxNdim>;\n\npublic:\n    using const_iterator = BaseVector::const_iterator;\n    using const_reverse_iterator = BaseVector::const_reverse_iterator;\n    // TODO(niboshi): Declare other types required for this class to be a container.\n\n    Axes() = default;\n\n    ~Axes() = default;\n\n    // by iterators\n    template <typename InputIt>\n    Axes(InputIt first, InputIt last) {\n        if (std::distance(first, last) > kMaxNdim) {\n            throw DimensionError{\"too many dimensions: \", std::distance(first, last)};\n        }\n        insert(begin(), first, last);\n    }\n\n    // by span\n    explicit Axes(absl::Span<const int8_t> axes) : Axes{axes.begin(), axes.end()} {}\n\n    // by initializer list\n    Axes(std::initializer_list<int8_t> axes) : Axes{axes.begin(), axes.end()} {}\n\n    // copy\n    Axes(const Axes&) = default;\n    Axes& operator=(const Axes&) = default;\n\n    // move\n    Axes(Axes&&) = default;\n    Axes& operator=(Axes&&) = default;\n\n    std::string ToString() const;\n\n    int8_t ndim() const noexcept { return gsl::narrow_cast<int8_t>(size()); }\n\n    int8_t& operator[](int8_t index) {\n        if (!(0 <= index && static_cast<size_t>(index) < size())) {\n            throw DimensionError{\"index out of bounds\"};\n        }\n        return this->StackVector::operator[](index);\n    }\n\n    const int8_t& operator[](int8_t index) const {\n        if (!(0 <= index && static_cast<size_t>(index) < size())) {\n            throw DimensionError{\"index out of bounds\"};\n        }\n        return this->StackVector::operator[](index);\n    }\n\n    // span\n    absl::Span<const int8_t> span() const { return {*this}; }\n};\n\nstd::ostream& operator<<(std::ostream& os, const Axes& axes);\n\nusing OptionalAxes = OptionalContainerArg<Axes>;\n\nnamespace internal {\n\nbool IsAxesPermutation(const Axes& axes, int8_t ndim);\n\n// Normalizes possibly-negative axis to non-negative axis in [0, ndim).\n// If `axis` does not fit in [-ndim, ndim), DimensionError is thrown.\nint8_t NormalizeAxis(int8_t axis, int8_t ndim);\n\n// Resolves the axis argument of many operations.\n// Negative axes are converted to non-negative ones (by wrapping at ndim).\nAxes GetNormalizedAxes(const Axes& axis, int8_t ndim);\n\n// Resolves the axis argument of many operations.\n// Negative axes are converted to non-negative ones (by wrapping at ndim).\n// Axes are then sorted.\nAxes GetSortedAxes(const Axes& axis, int8_t ndim);\n\n// Resolves the axis argument of many operations.\n// Negative axes are converted to non-negative ones (by wrapping at ndim).\n// Axes are then sorted.\n// nullopt is converted to a vector of all axes.\nAxes GetSortedAxesOrAll(const OptionalAxes& axis, int8_t ndim);\n\n}  // namespace internal\n}  // namespace chainerx\n", "meta": {"hexsha": "c80b224338e1c8e5d2818658e0252d0de8db8869", "size": 3160, "ext": "h", "lang": "C", "max_stars_repo_path": "chainerx_cc/chainerx/axes.h", "max_stars_repo_name": "zaltoprofen/chainer", "max_stars_repo_head_hexsha": "3b03f9afc80fd67f65d5e0395ef199e9506b6ee1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3705.0, "max_stars_repo_stars_event_min_datetime": "2017-06-01T07:36:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T10:46:15.000Z", "max_issues_repo_path": "chainerx_cc/chainerx/axes.h", "max_issues_repo_name": "zaltoprofen/chainer", "max_issues_repo_head_hexsha": "3b03f9afc80fd67f65d5e0395ef199e9506b6ee1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5998.0, "max_issues_repo_issues_event_min_datetime": "2017-06-01T06:40:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T01:42:44.000Z", "max_forks_repo_path": "chainerx_cc/chainerx/axes.h", "max_forks_repo_name": "zaltoprofen/chainer", "max_forks_repo_head_hexsha": "3b03f9afc80fd67f65d5e0395ef199e9506b6ee1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1150.0, "max_forks_repo_forks_event_min_datetime": "2017-06-02T03:39:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T02:29:32.000Z", "avg_line_length": 29.5327102804, "max_line_length": 86, "alphanum_fraction": 0.6775316456, "num_tokens": 786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23091976292927183, "lm_q2_score": 0.04672495895795422, "lm_q1q2_score": 0.010789716445450745}}
{"text": "#pragma once\n\n#include \"datastructures/MortonIndex.h\"\n\n#include <fstream>\n#include <gsl/gsl>\n#include <iostream>\n#include <string>\n\nstruct OctreeIndexFileHeader\n{\n  const char magic[4] = { 'i', 'n', 'd', 'x' };\n  uint32_t levels_per_index;\n  size_t num_indices;\n};\n\ntemplate<unsigned int MaxLevels>\nvoid\nwrite_octree_indices_to_file(const std::string& file_path,\n                             gsl::span<MortonIndex<MaxLevels>> indices)\n{\n  OctreeIndexFileHeader header;\n  header.levels_per_index = MaxLevels;\n  header.num_indices = indices.size();\n\n  std::ofstream fs{ file_path, std::ios::out | std::ios::binary };\n  if (!fs.is_open()) {\n    std::cerr << \"Could not write index file \" << file_path << std::endl;\n    return;\n  }\n\n  fs.write(reinterpret_cast<char const*>(&header), sizeof(OctreeIndexFileHeader));\n  for (auto idx : indices) {\n    const auto idx_val = idx.get();\n    fs.write(reinterpret_cast<char const*>(&idx_val), sizeof(idx_val));\n  }\n\n  fs.flush();\n  fs.close();\n}\n\ntemplate<unsigned int MaxLevels>\nstd::vector<MortonIndex<MaxLevels>>\nread_octree_indices_from_file(const std::string& file_path)\n{\n  std::ifstream fs{ file_path, std::ios::in | std::ios::binary };\n  if (!fs.is_open()) {\n    std::cerr << \"Could not read index file \" << file_path << std::endl;\n    return {};\n  }\n\n  fs.unsetf(std::ios::skipws);\n\n  fs.seekg(0, std::ios::end);\n  auto fileSize = fs.tellg();\n  fs.seekg(0, std::ios::beg);\n\n  std::vector<char> rawData;\n  rawData.reserve(fileSize);\n\n  rawData.insert(rawData.begin(), std::istream_iterator<char>(fs), std::istream_iterator<char>());\n\n  const auto& header = *reinterpret_cast<OctreeIndexFileHeader const*>(rawData.data());\n\n  if (header.levels_per_index != MaxLevels) {\n    std::cerr << \"Reading octree index file with indices that contain \" << header.levels_per_index\n              << \" levels but requested to read into MortonIndexs with \" << MaxLevels\n              << \" levels instead!\" << std::endl;\n    return {};\n  }\n\n  auto indices_begin = rawData.data() + sizeof(OctreeIndexFileHeader);\n  const auto indices_end = rawData.data() + rawData.size();\n\n  using IndexType_t = typename MortonIndex<MaxLevels>::Store_t;\n  const auto index_binary_size = sizeof(IndexType_t);\n  std::vector<MortonIndex<MaxLevels>> indices;\n  indices.reserve(header.num_indices);\n  for (; indices_begin < indices_end; indices_begin += index_binary_size) {\n    indices.emplace_back(*reinterpret_cast<IndexType_t const*>(indices_begin));\n  }\n\n  return indices;\n}", "meta": {"hexsha": "2c78a086922c31a5bb727ef5cf6307ec5c3b3f5e", "size": 2486, "ext": "h", "lang": "C", "max_stars_repo_path": "schwarzwald/core/tiling/OctreeIndexWriter.h", "max_stars_repo_name": "igd-geo/schwarzwald", "max_stars_repo_head_hexsha": "e3e041f87c93985394444ee056ce8ba7ae62194b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2021-01-06T14:16:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T00:15:17.000Z", "max_issues_repo_path": "schwarzwald/core/tiling/OctreeIndexWriter.h", "max_issues_repo_name": "igd-geo/schwarzwald", "max_issues_repo_head_hexsha": "e3e041f87c93985394444ee056ce8ba7ae62194b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-25T08:37:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T06:28:06.000Z", "max_forks_repo_path": "schwarzwald/core/tiling/OctreeIndexWriter.h", "max_forks_repo_name": "igd-geo/schwarzwald", "max_forks_repo_head_hexsha": "e3e041f87c93985394444ee056ce8ba7ae62194b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T13:50:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T11:45:45.000Z", "avg_line_length": 29.5952380952, "max_line_length": 98, "alphanum_fraction": 0.6870474658, "num_tokens": 626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.02800752091022998, "lm_q1q2_score": 0.010780434935235231}}
{"text": "//\n//  particle.h\n//  EpiGenMCMC\n//\n//  Created by Lucy Li on 13/04/2016.\n//  Copyright (c) 2016 Lucy Li, Imperial College London. All rights reserved.\n//\n\n#ifndef __EpiGenMCMC__particle__\n#define __EpiGenMCMC__particle__\n\n#include <vector>\n#include <gsl/gsl_randist.h>\n#include \"trajectory.h\"\n\nclass Particle {\n    int num_particles;\n    int num_groups;\n    int num_time_steps;\n    std::vector <Trajectory*> trajectories;\n    std::vector <double> weights;\n    std::vector <double> normalised_weights;\n    std::vector <unsigned int> next_particles;\n    std::vector <int> parents;\n    std::vector <double> overall_traj; // Incidence: P1[Group1[T1, T2...], Group2[T1, T2...]...], P2[] ...\n    std::vector <double> overall_traj2; // Prevalence: P1[Group1[T1, T2...], Group2[T1, T2...]...], P2[] ...\n    std::vector <int> particle_ancestry;\n    std::vector <int> non_zero_particles;\n    std::vector <double> cumulative_weights;\n    std::vector <int> empty;\n    void replace(int, int);\n    void normalise();\npublic:\n    Particle();\n    Particle(int, Trajectory);\n    void start_particle_tracing(int, int);\n    void save_traj_to_matrix(int, int);\n    void save_traj_to_matrix(int, int, int);\n    void save_ancestry(int, int);\n    void save_ancestry(int, int, int);\n    void reset_parents();\n    int get_traj_random(gsl_rng *);\n    void retrace_traj(Trajectory&, gsl_rng *);\n    Trajectory* get_traj(int) const;\n    void set_weight(double, int, bool);\n    double get_weight(int);\n    double get_total_weight();\n    double get_ESS();\n    void reset_weights();\n    void resample(gsl_rng *);\n    void clear();\n};\n\n\n#endif /* defined(__EpiGenMCMC__particle__) */\n", "meta": {"hexsha": "0bed6e03b773ad1d35a9e7b22bd879bf92d13bef", "size": 1652, "ext": "h", "lang": "C", "max_stars_repo_path": "src/particle.h", "max_stars_repo_name": "lucymli/EpiGenMCMC", "max_stars_repo_head_hexsha": "a30e18196c34d7ebcdf7ff51bad55c412d0b0ec1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-04-01T09:55:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-09T16:14:41.000Z", "max_issues_repo_path": "src/particle.h", "max_issues_repo_name": "lucymli/EpiGenMCMC", "max_issues_repo_head_hexsha": "a30e18196c34d7ebcdf7ff51bad55c412d0b0ec1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-06-05T05:49:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-15T04:48:15.000Z", "max_forks_repo_path": "src/particle.h", "max_forks_repo_name": "lucymli/EpiGenMCMC", "max_forks_repo_head_hexsha": "a30e18196c34d7ebcdf7ff51bad55c412d0b0ec1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-03-13T16:20:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-16T22:17:38.000Z", "avg_line_length": 29.5, "max_line_length": 108, "alphanum_fraction": 0.6743341404, "num_tokens": 460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681662740417, "lm_q2_score": 0.02716923439111944, "lm_q1q2_score": 0.010760868844360305}}
{"text": "/* Some preprocessor magic for having fast inline functions. */\n#include <gsl/gsl_matrix.h>\n\n#ifndef INLINE\n#define INLINE static inline\n#endif\n#ifndef INLINE_DECL\n#define INLINE_DECL static inline\n#endif\n\n/* Some preprocessor magic for the \"restrict\" keyword:\n\thttp://www.cellperformance.com/mike_acton/2006/05/demystifying_the_restrict_keyw.html */\n#if __STDC_VERSION__ >= 199901\n#elif defined (__GNUC__) && __GNUC__ >= 2 && __GNUC_MINOR__ >= 91\n\t#define restrict __restrict__\n#else\n\t#define restrict\n#endif\n\n/* Some preprocessor magic for calling this library from C++ */\n\n#ifdef __cplusplus\n\t#define restrict /* nothing */\n#endif\n\n", "meta": {"hexsha": "5582dd51e70559ee8189568688c67ef732e25015", "size": 635, "ext": "h", "lang": "C", "max_stars_repo_path": "src/csm/sm/csm/restrict.h", "max_stars_repo_name": "alecone/ROS_project", "max_stars_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/csm/sm/csm/restrict.h", "max_issues_repo_name": "alecone/ROS_project", "max_issues_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/csm/sm/csm/restrict.h", "max_forks_repo_name": "alecone/ROS_project", "max_forks_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4230769231, "max_line_length": 89, "alphanum_fraction": 0.7637795276, "num_tokens": 151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3140505449918074, "lm_q2_score": 0.03410042644852396, "lm_q1q2_score": 0.010709257510611992}}
{"text": "/*******************************************************************************\nNAME: extract_rgb_palette\n\nALGORITHM DESCRIPTION:\n  Dumps RGB indexed color palette from graphics file to stdout\n\nISSUES:\n        Only color indexed TIFF files currently supported\n\n*******************************************************************************/\n#include \"asf.h\"\n#include \"asf_nan.h\"\n#include <math.h>\n#include <ctype.h>\n#include \"asf_raster.h\"\n#include \"typlim.h\"\n#include <float_image.h>\n#include <uint8_image.h>\n#include <geokeys.h>\n#include <geo_tiffp.h>\n#include <geo_keyp.h>\n#include <geotiff.h>\n#include <geotiffio.h>\n#include <tiff.h>\n#include <tiffio.h>\n#include <xtiffio.h>\n#include <gsl/gsl_math.h>\n#include \"geotiff_support.h\"\n#include \"extract_rgb_palette_help.h\"\n\n/**** TYPES ****/\ntypedef enum {\n  UNKNOWN_GRAPHICS_TYPE=0,\n  ASF_IMG,\n  JPEG,\n  PGM,\n  PPM,\n  PBM,\n  STD_TIFF,\n  GEO_TIFF,\n  BMP,\n  GIF,\n  PNG\n} graphics_file_t;\n\n#define MISSING_TIFF_DATA -1\ntypedef struct {\n  uint32 width;\n  uint32 height;\n  short sample_format;\n  short bits_per_sample;\n  short planar_config;\n  data_type_t data_type; // ASF data type\n  short num_bands;\n  int is_scanline_format;\n  int is_palette_color_tiff;\n} tiff_data_t;\n\n#define MISSING_GTIF_DATA -1\ntypedef struct {\n  int gtif_data_exists;\n  char *GTcitation;\n  char *PCScitation;\n  int tie_point_elements; // Number of tie point elements (usually a multiple of 6)\n  int num_tie_points; // Number of elements divided by 6 since (i,j,k) maps to (x,y,z)\n  double *tie_point;  // Usually only 1, but who knows what evil lurks in the hearts of men?\n  int pixel_scale_elements; // Usually a multiple of 3\n  int num_pixel_scales;\n  double *pixel_scale;  // Should always be 3 of these ...for ScaleX, ScaleY, and ScaleZ\n  short model_type;\n  short raster_type;\n  short linear_units;\n  double scale_factor;\n  datum_type_t datum;\n  char hemisphere;\n  unsigned long pro_zone; // UTM zone (UTM only)\n  short proj_coords_trans;\n  short pcs;\n  short geodetic_datum;\n  short geographic_datum;\n  double false_easting;\n  double false_northing;\n  double natLonOrigin;\n  double lonCenter;\n  double falseOriginLon;\n  double falseOriginLat;\n  double natLatOrigin;\n  double latCenter;\n  double stdParallel1;\n  double stdParallel2;\n  double lonPole;\n} geotiff_data_t;\n\n/**** PROTOTYPES ****/\ngraphics_file_t getGraphicsFileType (char *file);\nvoid graphicsFileType_toStr (graphics_file_t type, char *type_str);\nfloat get_maxval(data_type_t data_type);\nchar *data_type2str(data_type_t data_type);\nvoid get_tiff_info_from_file(char *file, tiff_data_t *t);\nvoid get_tiff_info(TIFF *tif, tiff_data_t *t);\nvoid get_geotiff_keys(char *file, geotiff_data_t *g);\nvoid dump_tiff_rgb_palette(char *inFile);\n\nint main(int argc, char **argv)\n{\n  char *inFile;\n  char msg[1024];\n  char type_str[255];\n\n  asfSplashScreen(argc, argv);\n\n  if (argc != 2) {\n      usage();\n      exit(1);\n  }\n  else {\n      check_for_help(argc, argv);\n  }\n\n  inFile=argv[1];\n\n  if (!fileExists(inFile)) {\n    sprintf(msg, \"File not found: %s\\n  => Did you forget to use the filename extension?\\n\", inFile);\n    asfPrintError(msg);\n  }\n  graphics_file_t type;\n  type = getGraphicsFileType(inFile);\n  if (type != STD_TIFF &&\n      type != GEO_TIFF )\n  {\n    graphicsFileType_toStr(type, type_str);\n    sprintf(msg, \"Graphics file type %s is not currently supported (Graphics file: %s)\\n\",\n            type_str, inFile);\n    asfPrintError(msg);\n  }\n\n  switch (type) {\n    case STD_TIFF:\n    case GEO_TIFF:\n      dump_tiff_rgb_palette(inFile);\n      break;\n    default:\n      sprintf(msg, \"Unrecognized image file type found.\\n\");\n      asfPrintError(msg);\n      break;\n  }\n\n  return (0);\n}\n\ngraphics_file_t getGraphicsFileType (char *file)\n{\n  FILE *fp = (FILE *)FOPEN(file, \"rb\");\n  uint8 magic[4];\n  graphics_file_t file_type = UNKNOWN_GRAPHICS_TYPE;\n  TIFF *itif = NULL;\n  GTIF *gtif = NULL;\n\n  if (fp != NULL) {\n    int i;\n\n    // Read the magic number from the file header\n    for (i=0; i<4; i++) {\n      magic[i] = (uint8)fgetc(fp);\n    }\n    if(fp) FCLOSE(fp);\n\n    // Check for a valid magic number combination\n    if (magic[0] == 0xFF && magic[1] == 0xD8) {\n      file_type = JPEG;\n    }\n    else if (magic[0] == 'P' && (magic[1] == '4' || magic[1] == '1')) {\n      file_type = PBM;\n    }\n    else if (magic[0] == 'P' && (magic[1] == '5' || magic[1] == '2')) {\n      file_type = PGM;\n    }\n    else if (magic[0] == 'P' && (magic[1] == '6' || magic[1] == '3')) {\n      file_type = PPM;\n    }\n    else if ((magic[0] == 'I' && magic[1] == 'I') || (magic[0] == 'M' && magic[1] == 'M')) {\n      file_type = STD_TIFF;\n\n      itif = XTIFFOpen(file, \"rb\");\n      if (itif != NULL) {\n        gtif = GTIFNew(itif);\n        if (gtif != NULL) {\n          double *tie_point = NULL;\n          double *pixel_scale = NULL;\n          short model_type, raster_type, linear_units;\n          int read_count, tie_points, pixel_scales;\n\n          (gtif->gt_methods.get)(gtif->gt_tif, GTIFF_TIEPOINTS, &tie_points, &tie_point);\n          (gtif->gt_methods.get)(gtif->gt_tif, GTIFF_PIXELSCALE, &pixel_scales, &pixel_scale);\n          read_count = GTIFKeyGet(gtif, GTModelTypeGeoKey, &model_type, 0, 1);\n          read_count += GTIFKeyGet(gtif, GTRasterTypeGeoKey, &raster_type, 0, 0);\n          read_count += GTIFKeyGet(gtif, ProjLinearUnitsGeoKey, &linear_units, 0, 1);\n\n          if (tie_points == 6 && pixel_scales == 3 && read_count == 3) {\n            file_type = GEO_TIFF;\n          }\n\n          if (tie_point != NULL) free(tie_point);\n          if (pixel_scale != NULL) free(pixel_scale);\n          GTIFFree(gtif);\n        }\n        XTIFFClose(itif);\n      }\n    }\n    else if (magic[0] == 'B' && magic[1] == 'M') {\n      file_type = BMP;\n    }\n    else if (magic[0] == 'G' && magic[1] == 'I' && magic[2] == 'F') {\n      file_type = GIF;\n    }\n    else if (magic[1] == 'P' && magic[2] == 'N' && magic[3] == 'G') {\n      file_type = PNG;\n    }\n    else {\n      file_type = UNKNOWN_GRAPHICS_TYPE;\n    }\n  }\n\n  return file_type;\n}\n\nvoid graphicsFileType_toStr (graphics_file_t type, char *type_str)\n{\n  switch (type) {\n    case ASF_IMG:\n      strcpy (type_str, \"ASF_IMG\");\n      break;\n    case JPEG:\n      strcpy (type_str, \"JPEG\");\n      break;\n    case PBM:\n      strcpy (type_str, \"PBM\");\n      break;\n    case PGM:\n      strcpy (type_str, \"PGM\");\n      break;\n    case PPM:\n      strcpy (type_str, \"PPM\");\n      break;\n    case STD_TIFF:\n      strcpy (type_str, \"TIFF\");\n      break;\n    case GEO_TIFF:\n      strcpy (type_str, \"GEOTIFF\");\n      break;\n    case BMP:\n      strcpy (type_str, \"BMP\");\n      break;\n    case GIF:\n      strcpy (type_str, \"GIF\");\n      break;\n    case PNG:\n      strcpy (type_str, \"PNG\");\n      break;\n    case UNKNOWN_GRAPHICS_TYPE:\n    default:\n      strcpy(type_str, \"UNRECOGNIZED\");\n      break;\n  }\n}\n\nfloat get_maxval(data_type_t data_type)\n{\n  float ret;\n\n  // Only non-complex types with 32 bits or less are supported\n  switch (data_type) {\n    case BYTE:\n      ret = powf(2, sizeof(unsigned char)) - 1.0;\n      break;\n    case INTEGER16:\n      ret = powf(2, sizeof(short int)) - 1.0;\n      break;\n    case INTEGER32:\n      ret = powf(2, sizeof(int)) - 1.0;\n      break;\n    case REAL32:\n      ret = MAXREAL;\n      break;\n    default:\n      ret = 0.0;\n      break;\n  }\n\n  return ret;\n}\n\n// User must free the returned string\nchar *data_type2str(data_type_t data_type)\n{\n  char *retstr = (char*)CALLOC(64, sizeof(char));\n\n  switch (data_type) {\n    case BYTE:\n      strcpy(retstr, \"BYTE\");\n      break;\n    case INTEGER16:\n      strcpy(retstr, \"INTEGER16\");\n      break;\n    case INTEGER32:\n      strcpy(retstr, \"INTEGER32\");\n      break;\n    case REAL32:\n      strcpy(retstr, \"REAL32\");\n      break;\n    case REAL64:\n      strcpy(retstr, \"REAL64\");\n      break;\n    case COMPLEX_BYTE:\n      strcpy(retstr, \"COMPLEX_BYTE\");\n      break;\n    case COMPLEX_INTEGER16:\n      strcpy(retstr, \"COMPLEX_INTEGER16\");\n      break;\n    case COMPLEX_INTEGER32:\n      strcpy(retstr, \"COMPLEX_INTEGER32\");\n      break;\n    case COMPLEX_REAL32:\n      strcpy(retstr, \"COMPLEX_REAL32\");\n      break;\n    case COMPLEX_REAL64:\n      strcpy(retstr, \"COMPLEX_REAL64\");\n      break;\n    default:\n      strcpy(retstr, \"UNKNOWN\");\n      break;\n  }\n\n  return retstr;\n}\n\nvoid get_tiff_info_from_file(char *file, tiff_data_t *t)\n{\n  TIFF *tif;\n\n  t->sample_format = MISSING_TIFF_DATA;\n  t->bits_per_sample = MISSING_TIFF_DATA;\n  t->planar_config = MISSING_TIFF_DATA;\n  t->data_type = 0;\n  t->num_bands = 0;\n  t->is_scanline_format = 0;\n  t->height = 0;\n  t->width = 0;\n\n  tif = XTIFFOpen(file, \"rb\");\n  if (tif != NULL) {\n    get_tiff_info(tif, t);\n  }\n\n  XTIFFClose(tif);\n}\n\nvoid get_tiff_info(TIFF *tif, tiff_data_t *t)\n{\n  get_tiff_data_config(tif,\n                       &t->sample_format,\n                       &t->bits_per_sample,\n                       &t->planar_config,\n                       &t->data_type,\n                       &t->num_bands,\n                       &t->is_scanline_format,\n                       &t->is_palette_color_tiff,\n                       REPORT_LEVEL_NONE);\n  TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &t->height);\n  TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &t->width);\n  if (t->planar_config != PLANARCONFIG_CONTIG &&\n      t->planar_config != PLANARCONFIG_SEPARATE &&\n      t->num_bands == 1)\n  {\n    t->planar_config = PLANARCONFIG_CONTIG;\n  }\n}\n\nvoid get_geotiff_keys(char *file, geotiff_data_t *g)\n{\n  TIFF *tif = XTIFFOpen(file, \"rb\");\n  GTIF *gtif = NULL;\n\n  // Init values to 'missing'\n  g->gtif_data_exists = 0;\n  g->GTcitation = NULL;   // Should be unallocated\n  g->PCScitation = NULL;  // Should be unallocated\n\n  // Read geotiff info\n  if (tif != NULL) {\n    gtif = GTIFNew(tif);\n    if (gtif != NULL) {\n      int count, read_count;\n      int citation_length;\n      int typeSize;\n      tagtype_t citation_type;\n\n      // Get citations\n      citation_length = GTIFKeyInfo(gtif, GTCitationGeoKey, &typeSize, &citation_type);\n      if (citation_length > 0) {\n        g->GTcitation = (char*)MALLOC(citation_length * typeSize);\n        GTIFKeyGet(gtif, GTCitationGeoKey, g->GTcitation, 0, citation_length);\n      }\n      else {\n        g->GTcitation = NULL;\n      }\n      citation_length = GTIFKeyInfo(gtif, PCSCitationGeoKey, &typeSize, &citation_type);\n      if (citation_length > 0) {\n        g->PCScitation = (char*)MALLOC(citation_length * typeSize);\n        GTIFKeyGet(gtif, PCSCitationGeoKey, g->PCScitation, 0, citation_length);\n      }\n      else {\n        g->PCScitation = NULL;\n      }\n      if ((g->GTcitation != NULL && strlen(g->GTcitation) > 0) ||\n           (g->PCScitation != NULL && strlen(g->PCScitation) > 0))\n      {\n        g->gtif_data_exists = 1;\n      }\n\n      // Get tie points and pixel scale\n      (gtif->gt_methods.get)(gtif->gt_tif, GTIFF_TIEPOINTS, &count, &g->tie_point);\n      if (count >= 6) {\n        g->gtif_data_exists = 1;\n        g->tie_point_elements = count;\n        g->num_tie_points = count / 6;\n      }\n      (gtif->gt_methods.get)(gtif->gt_tif, GTIFF_PIXELSCALE, &count, &g->pixel_scale);\n      if (count >= 3) {\n        g->gtif_data_exists = 1;\n        g->pixel_scale_elements = count;\n        g->num_pixel_scales = count / 3;\n      }\n\n      // Get model type, raster type, and linear units\n      read_count = GTIFKeyGet (gtif, GTModelTypeGeoKey, &g->model_type, 0, 1);\n      if (read_count >= 1) g->gtif_data_exists = 1;\n      read_count = GTIFKeyGet (gtif, GTRasterTypeGeoKey, &g->raster_type, 0, 0);\n      if (read_count >= 1) g->gtif_data_exists = 1;\n      read_count = GTIFKeyGet (gtif, ProjLinearUnitsGeoKey, &g->linear_units, 0, 1);\n      if (read_count >= 1) g->gtif_data_exists = 1;\n\n      // Get UTM related info if it exists\n      read_count = GTIFKeyGet(gtif, ProjectedCSTypeGeoKey, &g->pcs, 0, 1);\n      if (read_count == 1 && PCS_2_UTM(g->pcs, &g->hemisphere, &g->datum, &g->pro_zone)) {\n        g->gtif_data_exists = 1;\n      }\n      else {\n        read_count = GTIFKeyGet(gtif, ProjectionGeoKey, &g->pcs, 0, 1);\n        if (read_count == 1 && PCS_2_UTM(g->pcs, &g->hemisphere, &g->datum, &g->pro_zone)) {\n          g->gtif_data_exists = 1;\n        }\n        else {\n          g->hemisphere = '\\0';\n          g->datum = UNKNOWN_DATUM;\n          g->pro_zone = MISSING_GTIF_DATA;\n        }\n      }\n\n      // Get projection type (ProjCoordTransGeoKey) and other projection parameters\n      read_count = GTIFKeyGet(gtif, ProjCoordTransGeoKey, &g->proj_coords_trans, 0, 1);\n      if (read_count >= 1) g->gtif_data_exists = 1;\n      else g->proj_coords_trans = MISSING_GTIF_DATA;\n      read_count = GTIFKeyGet(gtif, GeographicTypeGeoKey, &g->geographic_datum, 0, 1);\n      if (read_count >= 1) g->gtif_data_exists = 1;\n      else g->geographic_datum = MISSING_GTIF_DATA;\n      read_count = GTIFKeyGet(gtif, GeogGeodeticDatumGeoKey, &g->geodetic_datum, 0, 1);\n      if (read_count >= 1) g->gtif_data_exists = 1;\n      else g->geodetic_datum = MISSING_GTIF_DATA;\n      read_count = GTIFKeyGet(gtif, ProjScaleAtNatOriginGeoKey, &g->scale_factor, 0, 1);\n      if (read_count >= 1) g->gtif_data_exists = 1;\n      else g->scale_factor = MISSING_GTIF_DATA;\n\n      // Get generic projection parameters (Note: projection type is defined by\n      // the g->proj_coords_trans value)\n      read_count = GTIFKeyGet (gtif, ProjFalseEastingGeoKey, &g->false_easting, 0, 1);\n      if (read_count >= 1) g->gtif_data_exists = 1;\n      else g->false_easting = MISSING_GTIF_DATA;\n      read_count = GTIFKeyGet (gtif, ProjFalseNorthingGeoKey, &g->false_northing, 0, 1);\n      if (read_count >= 1) g->gtif_data_exists = 1;\n      else g->false_northing = MISSING_GTIF_DATA;\n      read_count = GTIFKeyGet (gtif, ProjNatOriginLongGeoKey, &g->natLonOrigin, 0, 1);\n      if (read_count >= 1) g->gtif_data_exists = 1;\n      else g->natLonOrigin = MISSING_GTIF_DATA;\n      read_count = GTIFKeyGet (gtif, ProjNatOriginLatGeoKey, &g->natLatOrigin, 0, 1);\n      if (read_count >= 1) g->gtif_data_exists = 1;\n      else g->natLatOrigin = MISSING_GTIF_DATA;\n      read_count = GTIFKeyGet (gtif, ProjStdParallel1GeoKey, &g->stdParallel1, 0, 1);\n      if (read_count >= 1) g->gtif_data_exists = 1;\n      else g->stdParallel1 = MISSING_GTIF_DATA;\n      read_count = GTIFKeyGet (gtif, ProjStdParallel2GeoKey, &g->stdParallel2, 0, 1);\n      if (read_count >= 1) g->gtif_data_exists = 1;\n      else g->stdParallel2 = MISSING_GTIF_DATA;\n      read_count = GTIFKeyGet (gtif, ProjCenterLongGeoKey, &g->lonCenter, 0, 1);\n      if (read_count >= 1) g->gtif_data_exists = 1;\n      else g->lonCenter = MISSING_GTIF_DATA;\n      read_count = GTIFKeyGet (gtif, ProjCenterLatGeoKey, &g->latCenter, 0, 1);\n      if (read_count >= 1) g->gtif_data_exists = 1;\n      else g->latCenter = MISSING_GTIF_DATA;\n      read_count = GTIFKeyGet (gtif, ProjFalseOriginLongGeoKey, &g->falseOriginLon, 0, 1);\n      if (read_count >= 1) g->gtif_data_exists = 1;\n      else g->falseOriginLon = MISSING_GTIF_DATA;\n      read_count = GTIFKeyGet (gtif, ProjFalseOriginLatGeoKey, &g->falseOriginLat, 0, 1);\n      if (read_count >= 1) g->gtif_data_exists = 1;\n      else g->falseOriginLat = MISSING_GTIF_DATA;\n      read_count = GTIFKeyGet (gtif, ProjStraightVertPoleLongGeoKey, &g->lonPole, 0, 1);\n      if (read_count >= 1) g->gtif_data_exists = 1;\n      else g->lonPole = MISSING_GTIF_DATA;\n    }\n  }\n}\n\nvoid tiff_get_float_line(TIFF *tif, float *buf, int row, int band_no)\n{\n  tiff_data_t t;\n\n  get_tiff_info(tif, &t);\n  // Note: For single-plane (greyscale) images, planar_config may remain unset so\n  // we can't use it as a guide for checking TIFF validity...\n  if (t.sample_format == MISSING_TIFF_DATA ||\n      t.bits_per_sample == MISSING_TIFF_DATA ||\n      t.data_type == 0 ||\n      t.num_bands == MISSING_TIFF_DATA ||\n      t.is_scanline_format == MISSING_TIFF_DATA ||\n      t.height == 0 ||\n      t.width == 0)\n  {\n    asfPrintError(\"Cannot read tif file\\n\");\n  }\n\n  // Read a scanline\n  tsize_t scanlineSize = TIFFScanlineSize(tif);\n  tdata_t *tif_buf = _TIFFmalloc(scanlineSize);\n  if (t.planar_config == PLANARCONFIG_CONTIG || t.num_bands == 1) {\n    TIFFReadScanline(tif, tif_buf, row, 0);\n  }\n  else {\n    // Planar configuration is band-sequential\n    TIFFReadScanline(tif, tif_buf, row, band_no);\n  }\n\n  int col;\n  for (col=0; col<t.width; col++) {\n    switch(t.bits_per_sample) {\n      case 8:\n        switch(t.sample_format) {\n          case SAMPLEFORMAT_UINT:\n            if (t.planar_config == PLANARCONFIG_CONTIG && t.num_bands > 1) {\n              buf[col] = (float)(((uint8*)(tif_buf))[(col*t.num_bands)+band_no]);   // Current sample.\n            }\n            else {\n              // Planar configuration is band-sequential or single-banded\n              buf[col] = (float)(((uint8*)(tif_buf))[col]);\n            }\n            break;\n          case SAMPLEFORMAT_INT:\n            if (t.planar_config == PLANARCONFIG_CONTIG && t.num_bands > 1) {\n              buf[col] = (float)(((int8*)(tif_buf))[(col*t.num_bands)+band_no]);   // Current sample.\n            }\n            else {\n              // Planar configuration is band-sequential or single-banded\n              buf[col] = (float)(((int8*)(tif_buf))[col]);   // Current sample.\n            }\n            break;\n          default:\n            // There is no such thing as an IEEE 8-bit floating point\n            if (tif_buf) _TIFFfree(tif_buf);\n            if (tif) XTIFFClose(tif);\n            asfPrintError(\"tiff_get_float_line(): Unexpected data type in TIFF file.\\n\");\n            break;\n        }\n        break;\n      case 16:\n        switch(t.sample_format) {\n          case SAMPLEFORMAT_UINT:\n            if (t.planar_config == PLANARCONFIG_CONTIG && t.num_bands > 1) {\n              buf[col] = (float)(((uint16*)(tif_buf))[(col*t.num_bands)+band_no]);   // Current sample.\n            }\n            else {\n              // Planar configuration is band-sequential or single-banded\n              buf[col] = (float)(((uint16*)(tif_buf))[col]);   // Current sample.\n            }\n            break;\n          case SAMPLEFORMAT_INT:\n            if (t.planar_config == PLANARCONFIG_CONTIG && t.num_bands > 1) {\n              buf[col] = (float)(((int16*)(tif_buf))[(col*t.num_bands)+band_no]);   // Current sample.\n            }\n            else {\n              // Planar configuration is band-sequential or single-banded\n              buf[col] = (float)(((uint16*)(tif_buf))[col]);   // Current sample.\n            }\n            break;\n          default:\n            // There is no such thing as an IEEE 16-bit floating point\n            if (tif_buf) _TIFFfree(tif_buf);\n            if (tif) XTIFFClose(tif);\n            asfPrintError(\"tiff_get_float_line(): Unexpected data type in TIFF file.\\n\");\n            break;\n        }\n        break;\n      case 32:\n        switch(t.sample_format) {\n          case SAMPLEFORMAT_UINT:\n            if (t.planar_config == PLANARCONFIG_CONTIG && t.num_bands > 1) {\n              buf[col] = (float)(((uint32*)(tif_buf))[(col*t.num_bands)+band_no]);   // Current sample.\n            }\n            else {\n              // Planar configuration is band-sequential or single-banded\n              buf[col] = (float)(((uint32*)(tif_buf))[col]);   // Current sample.\n            }\n            break;\n          case SAMPLEFORMAT_INT:\n            if (t.planar_config == PLANARCONFIG_CONTIG && t.num_bands > 1) {\n              buf[col] = (float)(((long*)(tif_buf))[(col*t.num_bands)+band_no]);   // Current sample.\n            }\n            else {\n              // Planar configuration is band-sequential or single-banded\n              buf[col] = (float)(((long*)(tif_buf))[col]);   // Current sample.\n            }\n            break;\n          case SAMPLEFORMAT_IEEEFP:\n            if (t.planar_config == PLANARCONFIG_CONTIG && t.num_bands > 1) {\n              buf[col] = (float)(((float*)(tif_buf))[(col*t.num_bands)+band_no]);   // Current sample.\n            }\n            else {\n              // Planar configuration is band-sequential or single-banded\n              buf[col] = (float)(((float*)(tif_buf))[col]);   // Current sample.\n            }\n            break;\n          default:\n            if (tif_buf) _TIFFfree(tif_buf);\n            if (tif) XTIFFClose(tif);\n            asfPrintError(\"tiff_get_float_line(): Unexpected data type in TIFF file.\\n\");\n            break;\n        }\n        break;\n      default:\n        if (tif_buf) _TIFFfree(tif_buf);\n        if (tif) XTIFFClose(tif);\n        asfPrintError(\"tiff_get_float_line(): Unexpected data type in TIFF file.\\n\");\n        break;\n    }\n  }\n  if (tif_buf) {\n    _TIFFfree(tif_buf);\n  }\n}\n\nfloat tiff_image_get_float_pixel(TIFF *tif, int row, int col, int band_no)\n{\n  tiff_data_t t;\n  float cs;\n\n  get_tiff_info(tif, &t);\n  // Note: For single-plane (greyscale) images, planar_config may remain unset so\n  // we can't use it as a guide for checking TIFF validity...\n  if (t.sample_format == MISSING_TIFF_DATA ||\n      t.bits_per_sample == MISSING_TIFF_DATA ||\n      t.data_type == 0 ||\n      t.num_bands == MISSING_TIFF_DATA ||\n      t.is_scanline_format == MISSING_TIFF_DATA ||\n      t.height == 0 ||\n      t.width == 0)\n  {\n    asfPrintError(\"Cannot read tif file\\n\");\n  }\n\n  // Get a float line from the file\n  float *buf = (float*)MALLOC(t.width*sizeof(float));\n  tiff_get_float_line(tif, buf, row, band_no);\n  cs = buf[col];\n  FREE(buf);\n\n  // Return as float\n  return cs;\n}\n\nvoid dump_tiff_rgb_palette(char *inFile)\n{\n    TIFF *tiff = NULL;\n    tiff_data_t tiff_data;\n\n    get_tiff_info_from_file(inFile, &tiff_data);\n\n    tiff = XTIFFOpen(inFile, \"rb\");\n    if (!tiff) asfPrintError(\"Cannot open TIFF file (%s)\\n\", inFile);\n\n    int color;\n    int num_colors=(int)powl(2,tiff_data.bits_per_sample);\n    uint16* red=NULL;\n    uint16* green=NULL;\n    uint16* blue=NULL;\n    uint16 rmin, gmin, bmin, min;\n    uint16 rmax, gmax, bmax, max;\n\n    TIFFGetField(tiff, TIFFTAG_COLORMAP, &red, &green, &blue);\n    if (red == NULL || green == NULL || blue == NULL) asfPrintError(\"Cannot read palette from TIFF file (%s)\\n\", inFile);\n\n    rmin=gmin=bmin=min=65535; // Max uint16\n    rmax=gmax=bmax=max=0; // Min uint16\n    for (color=0; color<num_colors; color++) {\n        unsigned short r, g, b;\n\n        r=red[color];\n        g=green[color];\n        b=blue[color];\n\n        r = (unsigned short)(((float)r/65535)*255 + .5);\n        g = (unsigned short)(((float)g/65535)*255 + .5);\n        b = (unsigned short)(((float)b/65535)*255 + .5);\n\n        rmin = (r < rmin) ? r : rmin;\n        gmin = (g < gmin) ? g : gmin;\n        bmin = (b < bmin) ? b : bmin;\n        min = (r < min) ? r : min;\n        min = (g < min) ? g : min;\n        min = (b < min) ? b : min;\n\n        rmax = (r > rmax) ? r : rmax;\n        gmax = (g > gmax) ? g : gmax;\n        bmax = (b > bmax) ? b : bmax;\n        max = (r > max) ? r : max;\n        max = (g > max) ? g : max;\n        max = (b > max) ? b : max;\n    }\n    fprintf(stdout, \"# red min = %03d, green min = %03d, blue min = %03d, overall min = %03d\\n\",\n            rmin, gmin, bmin, min);\n    fprintf(stdout, \"# red max = %03d, green max = %03d, blue max = %03d, overall max = %03d\\n\",\n            rmax, gmax, bmax, max);\n    fprintf(stdout, \"# \\n# color\\tred\\tgreen\\tblue\\n\");\n    for (color=0; color<num_colors; color++) {\n        unsigned short r, g, b;\n\n        r=red[color];\n        g=green[color];\n        b=blue[color];\n\n        r = (unsigned short)(((float)r/65535)*255 + .5);\n        g = (unsigned short)(((float)g/65535)*255 + .5);\n        b = (unsigned short)(((float)b/65535)*255 + .5);\n        fprintf(stdout, \"%03d\\t%03d\\t%03d\\t%03d\\n\",\n                color, r, g, b);\n    }\n\n    XTIFFClose(tiff);\n}\n\n", "meta": {"hexsha": "e5fdae00743b45a481fc1c79ce6bd0347d17812e", "size": 23631, "ext": "c", "lang": "C", "max_stars_repo_path": "src/extract_rgb_palette/extract_rgb_palette.c", "max_stars_repo_name": "glshort/MapReady", "max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z", "max_issues_repo_path": "src/extract_rgb_palette/extract_rgb_palette.c", "max_issues_repo_name": "glshort/MapReady", "max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/extract_rgb_palette/extract_rgb_palette.c", "max_forks_repo_name": "glshort/MapReady", "max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z", "avg_line_length": 31.5922459893, "max_line_length": 121, "alphanum_fraction": 0.5935846981, "num_tokens": 6959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34864513533394575, "lm_q2_score": 0.030675804258401464, "lm_q1q2_score": 0.010694969927148008}}
{"text": "/* $Id$      */\n/*--------------------------------------------------------------------*/\n/*;  Copyright (C) 2012-2016                                          */\n/*;  Associated Universities, Inc. Washington DC, USA.                */\n/*;                                                                   */\n/*;  This program is free software; you can redistribute it and/or    */\n/*;  modify it under the terms of the GNU General Public License as   */\n/*;  published by the Free Software Foundation; either version 2 of   */\n/*;  the License, or (at your option) any later version.              */\n/*;                                                                   */\n/*;  This program is distributed in the hope that it will be useful,  */\n/*;  but WITHOUT ANY WARRANTY; without even the implied warranty of   */\n/*;  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the    */\n/*;  GNU General Public License for more details.                     */\n/*;                                                                   */\n/*;  You should have received a copy of the GNU General Public        */\n/*;  License along with this program; if not, write to the Free       */\n/*;  Software Foundation, Inc., 675 Massachusetts Ave, Cambridge,     */\n/*;  MA 02139, USA.                                                   */\n/*;                                                                   */\n/*;Correspondence about this software should be addressed as follows: */\n/*;         Internet email: bcotton@nrao.edu.                         */\n/*;         Postal address: William Cotton                            */\n/*;                         National Radio Astronomy Observatory      */\n/*;                         520 Edgemont Road                         */\n/*;                         Charlottesville, VA 22903-2475 USA        */\n/*--------------------------------------------------------------------*/\n#ifndef OBITPOLNCALFIT_H \n#define OBITPOLNCALFIT_H\n\n#include \"Obit.h\"\n#include \"ObitErr.h\"\n#include \"ObitUV.h\"\n#include \"ObitThread.h\"\n#include \"ObitInfoList.h\"\n#include \"ObitSource.h\"\n#include \"ObitSourceList.h\"\n#include \"ObitAntennaList.h\"\n#include \"ObitComplex.h\"\n#include \"ObitTableCP.h\"\n#include \"ObitTablePD.h\"\n#include \"ObitTableBP.h\"\n#ifdef HAVE_GSL\n#include <gsl/gsl_multifit_nlin.h>\n#endif /* HAVE_GSL */ \n\n/*-------- Obit:  Merx mollis mortibus nuper ------------------*/\n/**\n * \\file ObitPolnCalFit.h\n *\n * ObitPolnCalFit Class for fitting polarization calibration to UV data.\n *\n * This class does least squares fitting of a full nonlinear model\n * To instrumental polarization and calibration terms and optionally source \n * polarization parameters.\n * Results are stored in a combination of AIPS PD (instrumental poln),\n * AIPS CP (source poln) and AIPS BP (gain corrections including R-L phase).\n * \n * \\section ObitPolnCalFitaccess Creators and Destructors\n * An ObitPolnCalFit will usually be created using ObitPolnCalFitCreate which allows \n * specifying a name for the object as well as other information.\n *\n * A copy of a pointer to an ObitPolnCalFit should always be made using the\n * #ObitPolnCalFitRef function which updates the reference count in the object.\n * Then whenever freeing an ObitPolnCalFit or changing a pointer, the function\n * #ObitPolnCalFitUnref will decrement the reference count and destroy the object\n * when the reference count hits 0.\n * There is no explicit destructor.\n */\n/*---------------Private structures----------------*/\n/**\n * \\enum polnParmType\n * enum for I/O file type.\n * This specifies the type of underlying data file.\n */\nenum polnParmType {\n  /** Unspecified */\n  polnParmUnspec=0, \n  /** Source parameter */\n  polnParmSou,\n  /** Antenna parameter */\n  polnParmAnt,\n  /** Antenna gain */\n  polnParmGain,\n  /** Phase difference  */\n  polnParmPD\n}; /* end enum polnParmType */\n\n/** typedef for enum for polnParmType . */\ntypedef enum polnParmType PolnParmType;\n\n/* Threaded function argument */\ntypedef struct {\n  /* Obit error stack object */\n  ObitErr      *err;\n  /** thread    */\n  ObitThread    *thread;\n  /** thread number, >0 -> no threading   */\n  olong        ithread;\n  /** Do error analysis? */\n  gboolean doError;\n  /** First 0-rel datum in Data/Wt arrays */\n  olong lo;\n  /** Last 0-rel datum  in Data/Wt arrays */\n  olong hi;\n  /** selected antenna, 0-> all */\n  olong selAnt;\n  /** selected source, 0-> all */\n  olong selSou;\n /** Number of visibilities being fitted */\n  olong nvis;\n /** Number of data points being fitted (nvis*4) */\n  olong ndata;\n  /** Array of input data arrays, [10 x nvis]\n      each row: 2*parallactic angle (rad), blank, \n      RR_r, RR_i, LL_r, LL_i, RL_r, RL_i,  LR_r, LR_i   */\n  ofloat *inData;\n  /** Array of input data weights (~ 1/var), [4 x nvis]\n      each row: RR, LL, RL,  LR   */\n  ofloat *inWt;\n  /** Source no of visibility, in range [0,nsou-1] */\n  olong *souNo;\n  /** Antenna numbers  of visibility, in range [0,nant-1] */\n  olong *antNo;\n  /** Number of antennas */\n  olong nant;\n  /** Reference antenna */\n  olong refAnt;\n  /** Fit only reference antenna R-L phase */\n  gboolean doFitRL;\n  /** Fit global X & Y feed gains?: */\n  gboolean doFitGain;\n  /** Are the feeds circularly polarized? */\n  gboolean isCircFeed;\n  /** Reference frequency (Hz) */\n  odouble refFreq;\n  /** Current frequency (Hz) */\n  odouble curFreq;\n  /** R-L (or X-Y) phase difference */\n  odouble PD;\n  /** Error estimate R-L (or X-Y) phase difference */\n  odouble PDerr;\n  /** Fit Stokes I poln, per cal */\n  gboolean *doFitI;\n  /** Fit fit source linear poln, per cal */\n  gboolean *doFitPol;\n  /** Fit fit Stokes V poln, per cal */\n  gboolean *doFitV;\n  /** Antenna parameters 4 x nant, \n      each row: D1_r, D1_i, D2_r, D2_i */\n  odouble *antParm;\n  /** Antenna error estimates 4 x nant */ \n  odouble *antErr;\n  /** Antenna parameters fit flags, 4 x nant */\n  gboolean **antFit;\n  /** Antenna parameters number, 4 x nant */\n  olong **antPNumb;\n  /** Antenna gains 2 x nant, each row: Gain_X, gain_Y */\n  odouble *antGain;\n  /** Antenna gains error estimates 2 x nant */ \n  odouble *antGainErr;\n  /* Antenna parameters fit flags, 2 x nant */\n  gboolean **antGainFit;\n  /** Antenna gain parameters number, 2 x nant */\n  olong **antGainPNumb;\n  /** Number of calibrator sources */\n  olong nsou;\n  /** Source parameters 4 x nsou, \n     each row: I, Poln_amp, Poln_RL (rad), V */\n  odouble *souParm;\n  /** Source error estimates 4 x nsou, */\n  odouble *souErr;\n  /** Source parameters fit flags, 4 x nsou */\n  gboolean **souFit;\n  /** Source parameters number, 4 x nsou */\n  olong **souPNumb;\n  /** Source Ids in SU table, Data */\n  olong *souIDs;\n  /** Inverse Source Ids lookup, index of data source ID-1 \n      gives calibrator number */\n  olong *isouIDs;\n  /** Number of parameters being fitted */\n  olong nparam;\n  /** Number of valid parallel observations */\n  olong nPobs;\n  /** Number of valid cross pol observations */\n  olong nXobs;\n  /** Chi squared of fit */\n  ofloat ChiSq;\n  /** Sum of parallel residuals */\n  odouble sumParResid;\n  /** Sum of cross residuals */\n  odouble sumXResid;\n  /** Parameter type */\n  PolnParmType paramType;\n  /** Parameter number */\n  olong paramNumber;\n  /** Sum of first derivatives */\n  odouble sumDeriv;\n  /** Sum of second derivatives */\n  odouble sumDeriv2;\n  /** Sum of weights */\n  odouble sumWt;\n  /** Frequency of data */\n  odouble freq;\n  /** R-L Phase of calibrators (rad) at Freq */\n  ofloat *RLPhase;\n  /** Fractional polarization of calibrators */\n  ofloat *PPol;\n  /** Derivative of PPol (GHz) of calibrators */\n  ofloat *dPPol;\n  /** Central channel (1-rel) of fit */\n  olong Chan;\n  /** IF number (1-rel) */\n  olong IFno;\n  /** complex work arrays for antenna based parameters, max 100 ant */\n  dcomplex RS[100], RD[100], LS[100], LD[100],\n    RSc[100], RDc[100], LSc[100], LDc[100],\n    PR[100], PRc[100], PL[100], PLc[100];\n  odouble SR[100], DR[100], SL[100], DL[100];\n  /** Max antenna number */\n  olong maxAnt;\n  /** Solution method */\n  gchar solnType[5];\n} PolnFitArg;\n\n/*--------------Class definitions-------------------------------------*/\n/** ObitPolnCalFit Class structure. */\ntypedef struct {\n#include \"ObitPolnCalFitDef.h\"   /* this class definition */\n} ObitPolnCalFit;\n\n/*----------------- Macroes ---------------------------*/\n/** \n * Macro to unreference (and possibly destroy) an ObitPolnCalFit\n * returns a ObitPolnCalFit*.\n * in = object to unreference\n */\n#define ObitPolnCalFitUnref(in) ObitUnref (in)\n\n/** \n * Macro to reference (update reference count) an ObitPolnCalFit.\n * returns a ObitPolnCalFit*.\n * in = object to reference\n */\n#define ObitPolnCalFitRef(in) ObitRef (in)\n\n/** \n * Macro to determine if an object is the member of this or a \n * derived class.\n * Returns TRUE if a member, else FALSE\n * in = object to reference\n */\n#define ObitPolnCalFitIsA(in) ObitIsA (in, ObitPolnCalFitGetClass())\n\n/*---------------Public functions---------------------------*/\n/** Public: Class initializer. */\nvoid ObitPolnCalFitClassInit (void);\n\n/** Public: Default Constructor. */\nObitPolnCalFit* newObitPolnCalFit (gchar* name);\n\n/** Public: Create/initialize ObitPolnCalFit structures */\nObitPolnCalFit* ObitPolnCalFitCreate (gchar* name);\n/** Typedef for definition of class pointer structure */\ntypedef ObitPolnCalFit* (*ObitPolnCalFitCreateFP) (gchar* name);\n\n/** Public: ClassInfo pointer */\ngconstpointer ObitPolnCalFitGetClass (void);\n\n/** Public: Copy (deep) constructor. */\nObitPolnCalFit* ObitPolnCalFitCopy  (ObitPolnCalFit *in, \n\t\t\t\t     ObitPolnCalFit *out, ObitErr *err);\n\n/** Public: Copy structure. */\nvoid ObitPolnCalFitClone (ObitPolnCalFit *in, ObitPolnCalFit *out, \n\t\t\t  ObitErr *err);\n\n/** Public: Fit a UV data */\nvoid ObitPolnCalFitFit (ObitPolnCalFit* in, ObitUV *inUV, \n\t\t\tObitUV *outUV, ObitErr *err);\n/** Typedef for definition of class pointer structure */\ntypedef void(*ObitPolnCalFitFitFP) (ObitPolnCalFit* in, ObitUV *inUV, \n\t\t\t\t    ObitUV *outUV, ObitErr *err);\n\n/*----------- ClassInfo Structure -----------------------------------*/\n/**\n * ClassInfo Structure.\n * Contains class name, a pointer to any parent class\n * (NULL if none) and function pointers.\n */\ntypedef struct  {\n#include \"ObitPolnCalFitClassDef.h\"\n} ObitPolnCalFitClassInfo; \n\n#endif /* OBITPOLNCALFIT_H */ \n", "meta": {"hexsha": "60ce39bb7cbce3e25c07227615787366224491df", "size": 10297, "ext": "h", "lang": "C", "max_stars_repo_path": "ObitSystem/Obit/include/ObitPolnCalFit.h", "max_stars_repo_name": "sarrvesh/Obit", "max_stars_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-08-26T06:53:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-20T01:08:59.000Z", "max_issues_repo_path": "ObitSystem/Obit/include/ObitPolnCalFit.h", "max_issues_repo_name": "sarrvesh/Obit", "max_issues_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ObitSystem/Obit/include/ObitPolnCalFit.h", "max_forks_repo_name": "sarrvesh/Obit", "max_forks_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-08-29T15:12:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:16:08.000Z", "avg_line_length": 34.67003367, "max_line_length": 85, "alphanum_fraction": 0.6161988929, "num_tokens": 2766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36296921930155557, "lm_q2_score": 0.029312233295254998, "lm_q1q2_score": 0.01063943843516377}}
{"text": "#pragma once\n\n#include <gsl/span>\n\n#include <cstddef>\n\nnamespace imageview {\n\n// Class representing a color in RGB24 color space.\nclass RGB24 {\n public:\n  constexpr RGB24() noexcept = default;\n  // Construct an RGB24 color from the given channel components.\n  constexpr RGB24(unsigned char red, unsigned char green, unsigned char blue) noexcept\n      : red(red), green(green), blue(blue) {}\n\n  unsigned char red = 0;\n  unsigned char green = 0;\n  unsigned char blue = 0;\n};\n\n// Implementation of the PixelFormat concept for RGB24 pixel format.\n// In this pixel format the color is represented via 3 8-bit integers,\n// specifying the red, green and blue channels. When serializing to /\n// deserializing from  a byte array, the order of the channels is RGB (i.e.\n// not BGR).\nclass PixelFormatRGB24 {\n public:\n  using color_type = RGB24;\n  static constexpr int kBytesPerPixel = 3;\n\n  constexpr color_type read(gsl::span<const std::byte, kBytesPerPixel> data) const;\n\n  constexpr void write(const color_type& color, gsl::span<std::byte, kBytesPerPixel> data) const;\n};\n\nconstexpr bool operator==(const RGB24& lhs, const RGB24& rhs) {\n  return lhs.red == rhs.red && lhs.green == rhs.green && lhs.blue == rhs.blue;\n}\n\nconstexpr bool operator!=(const RGB24& lhs, const RGB24& rhs) { return !(lhs == rhs); }\n\nconstexpr PixelFormatRGB24::color_type PixelFormatRGB24::read(gsl::span<const std::byte, kBytesPerPixel> data) const {\n  return color_type(static_cast<unsigned char>(data[0]), static_cast<unsigned char>(data[1]),\n                    static_cast<unsigned char>(data[2]));\n}\n\nconstexpr void PixelFormatRGB24::write(const color_type& color, gsl::span<std::byte, kBytesPerPixel> data) const {\n  data[0] = static_cast<std::byte>(color.red);\n  data[1] = static_cast<std::byte>(color.green);\n  data[2] = static_cast<std::byte>(color.blue);\n}\n\n}  // namespace imageview\n", "meta": {"hexsha": "02317de13ff5be00a6ca8ad4d7c49d58b84dced6", "size": 1863, "ext": "h", "lang": "C", "max_stars_repo_path": "include/imageview/pixel_formats/PixelFormatRGB24.h", "max_stars_repo_name": "alexanderbelous/imageview", "max_stars_repo_head_hexsha": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/imageview/pixel_formats/PixelFormatRGB24.h", "max_issues_repo_name": "alexanderbelous/imageview", "max_issues_repo_head_hexsha": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/imageview/pixel_formats/PixelFormatRGB24.h", "max_forks_repo_name": "alexanderbelous/imageview", "max_forks_repo_head_hexsha": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8727272727, "max_line_length": 118, "alphanum_fraction": 0.71712292, "num_tokens": 468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2309197629292718, "lm_q2_score": 0.046033898309357744, "lm_q1q2_score": 0.010630136884307096}}
{"text": "/*\n *\n * Author : Pierre Schnizer <schnizer@users.sourceforge.net>\n * Date   : 5. October 2003\n * Only used to test the error handling of pygsl.\n */\n#include <Python.h>\n#include <gsl/gsl_errno.h>\n#include <pygsl/error_helpers.h>\n\nstatic char trigger_doc [] = \"Calls gsl_error with the passed error number\";\nstatic PyObject *module;\n\nstatic PyObject*\ntrigger(PyObject *self, PyObject *args)\n{\n\tint gsl_errno = GSL_SUCCESS;\n\n\tFUNC_MESS_BEGIN();\n\tif (0 == PyArg_ParseTuple(args, \"i\", &gsl_errno)){\n\t\tPyGSL_add_traceback(module, __FILE__, __FUNCTION__, __LINE__ - 1);\n\t\treturn NULL;\n\t}\n\t/*\n\t *\n\t * 25. October 2008\n\t * set the internal gsl_error_handler to off\n\t * \n\t */ \n\tpygsl_error(\"Just a test to see what pygsl is doing!\",\n\t\t  __FILE__, __LINE__, gsl_errno);\n\tif (PyGSL_ERROR_FLAG(gsl_errno) != GSL_SUCCESS){\t\n\t\tFUNC_MESS_FAILED();\n\t\treturn NULL;\n\t}\n\tFUNC_MESS_END();\n\tPy_INCREF(Py_None);\n\treturn (Py_None);\n}\n\nstatic PyMethodDef errortestMethods[] = {\n     /*densities*/\n     {\"trigger\", trigger, METH_VARARGS, trigger_doc},\n     {NULL, NULL, 0, NULL}\n};\n\n\nDL_EXPORT(void) initerrortest(void)\n{\n     PyObject  *m=NULL;\n     \n     m = Py_InitModule(\"errortest\", errortestMethods);\n     assert(m);\n     module = m;\n\n     init_pygsl();\n     \n     return;\n}\n\n", "meta": {"hexsha": "22ecfdb3e449eca322b126e60e43a6073c95cee8", "size": 1257, "ext": "c", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/src/errortestmodule.c", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/src/errortestmodule.c", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/src/errortestmodule.c", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 20.606557377, "max_line_length": 76, "alphanum_fraction": 0.6714399364, "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21733752104706247, "lm_q2_score": 0.04885777464048789, "lm_q1q2_score": 0.010618627624239672}}
{"text": "/* matrix/gsl_matrix_complex_float.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_MATRIX_COMPLEX_FLOAT_H__\n#define __GSL_MATRIX_COMPLEX_FLOAT_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_complex.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_vector_complex_float.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size1;\n  size_t size2;\n  size_t tda;\n  float * data;\n  gsl_block_complex_float * block;\n  int owner;\n} gsl_matrix_complex_float ;\n\ntypedef struct\n{\n  gsl_matrix_complex_float matrix;\n} _gsl_matrix_complex_float_view;\n\ntypedef _gsl_matrix_complex_float_view gsl_matrix_complex_float_view;\n\ntypedef struct\n{\n  gsl_matrix_complex_float matrix;\n} _gsl_matrix_complex_float_const_view;\n\ntypedef const _gsl_matrix_complex_float_const_view gsl_matrix_complex_float_const_view;\n\n\n/* Allocation */\n\nGSL_EXPORT\ngsl_matrix_complex_float *\ngsl_matrix_complex_float_alloc (const size_t n1, const size_t n2);\n\nGSL_EXPORT\ngsl_matrix_complex_float *\ngsl_matrix_complex_float_calloc (const size_t n1, const size_t n2);\n\nGSL_EXPORT\ngsl_matrix_complex_float *\ngsl_matrix_complex_float_alloc_from_block (gsl_block_complex_float * b,\n                                           const size_t offset,\n                                           const size_t n1, const size_t n2, const size_t d2);\n\nGSL_EXPORT\ngsl_matrix_complex_float *\ngsl_matrix_complex_float_alloc_from_matrix (gsl_matrix_complex_float * b,\n                                            const size_t k1, const size_t k2,\n                                            const size_t n1, const size_t n2);\n\nGSL_EXPORT\ngsl_vector_complex_float *\ngsl_vector_complex_float_alloc_row_from_matrix (gsl_matrix_complex_float * m,\n                                                const size_t i);\n\nGSL_EXPORT\ngsl_vector_complex_float *\ngsl_vector_complex_float_alloc_col_from_matrix (gsl_matrix_complex_float * m,\n                                                const size_t j);\n\nGSL_EXPORT void gsl_matrix_complex_float_free (gsl_matrix_complex_float * m);\n\n/* Views */\n\nGSL_EXPORT\n_gsl_matrix_complex_float_view\ngsl_matrix_complex_float_submatrix (gsl_matrix_complex_float * m,\n                            const size_t i, const size_t j,\n                            const size_t n1, const size_t n2);\n\nGSL_EXPORT\n_gsl_vector_complex_float_view\ngsl_matrix_complex_float_row (gsl_matrix_complex_float * m, const size_t i);\n\nGSL_EXPORT\n_gsl_vector_complex_float_view\ngsl_matrix_complex_float_column (gsl_matrix_complex_float * m, const size_t j);\n\nGSL_EXPORT\n_gsl_vector_complex_float_view\ngsl_matrix_complex_float_diagonal (gsl_matrix_complex_float * m);\n\nGSL_EXPORT\n_gsl_vector_complex_float_view\ngsl_matrix_complex_float_subdiagonal (gsl_matrix_complex_float * m, const size_t k);\n\nGSL_EXPORT\n_gsl_vector_complex_float_view\ngsl_matrix_complex_float_superdiagonal (gsl_matrix_complex_float * m, const size_t k);\n\nGSL_EXPORT\n_gsl_matrix_complex_float_view\ngsl_matrix_complex_float_view_array (float * base,\n                             const size_t n1,\n                             const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_complex_float_view\ngsl_matrix_complex_float_view_array_with_tda (float * base,\n                                      const size_t n1,\n                                      const size_t n2,\n                                      const size_t tda);\n\nGSL_EXPORT\n_gsl_matrix_complex_float_view\ngsl_matrix_complex_float_view_vector (gsl_vector_complex_float * v,\n                              const size_t n1,\n                              const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_complex_float_view\ngsl_matrix_complex_float_view_vector_with_tda (gsl_vector_complex_float * v,\n                                       const size_t n1,\n                                       const size_t n2,\n                                       const size_t tda);\n\n\nGSL_EXPORT\n_gsl_matrix_complex_float_const_view\ngsl_matrix_complex_float_const_submatrix (const gsl_matrix_complex_float * m,\n                                  const size_t i, const size_t j,\n                                  const size_t n1, const size_t n2);\n\nGSL_EXPORT\n_gsl_vector_complex_float_const_view\ngsl_matrix_complex_float_const_row (const gsl_matrix_complex_float * m,\n                            const size_t i);\n\nGSL_EXPORT\n_gsl_vector_complex_float_const_view\ngsl_matrix_complex_float_const_column (const gsl_matrix_complex_float * m,\n                               const size_t j);\n\nGSL_EXPORT\n_gsl_vector_complex_float_const_view\ngsl_matrix_complex_float_const_diagonal (const gsl_matrix_complex_float * m);\n\nGSL_EXPORT\n_gsl_vector_complex_float_const_view\ngsl_matrix_complex_float_const_subdiagonal (const gsl_matrix_complex_float * m,\n                                    const size_t k);\n\nGSL_EXPORT\n_gsl_vector_complex_float_const_view\ngsl_matrix_complex_float_const_superdiagonal (const gsl_matrix_complex_float * m,\n                                      const size_t k);\n\nGSL_EXPORT\n_gsl_matrix_complex_float_const_view\ngsl_matrix_complex_float_const_view_array (const float * base,\n                                   const size_t n1,\n                                   const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_complex_float_const_view\ngsl_matrix_complex_float_const_view_array_with_tda (const float * base,\n                                            const size_t n1,\n                                            const size_t n2,\n                                            const size_t tda);\n\nGSL_EXPORT\n_gsl_matrix_complex_float_const_view\ngsl_matrix_complex_float_const_view_vector (const gsl_vector_complex_float * v,\n                                    const size_t n1,\n                                    const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_complex_float_const_view\ngsl_matrix_complex_float_const_view_vector_with_tda (const gsl_vector_complex_float * v,\n                                             const size_t n1,\n                                             const size_t n2,\n                                             const size_t tda);\n\n/* Operations */\n\nGSL_EXPORT gsl_complex_float gsl_matrix_complex_float_get(const gsl_matrix_complex_float * m, const size_t i, const size_t j);\nGSL_EXPORT void gsl_matrix_complex_float_set(gsl_matrix_complex_float * m, const size_t i, const size_t j, const gsl_complex_float x);\n\nGSL_EXPORT gsl_complex_float * gsl_matrix_complex_float_ptr(gsl_matrix_complex_float * m, const size_t i, const size_t j);\nGSL_EXPORT const gsl_complex_float * gsl_matrix_complex_float_const_ptr(const gsl_matrix_complex_float * m, const size_t i, const size_t j);\n\nGSL_EXPORT void gsl_matrix_complex_float_set_zero (gsl_matrix_complex_float * m);\nGSL_EXPORT void gsl_matrix_complex_float_set_identity (gsl_matrix_complex_float * m);\nGSL_EXPORT void gsl_matrix_complex_float_set_all (gsl_matrix_complex_float * m, gsl_complex_float x);\n\nGSL_EXPORT int gsl_matrix_complex_float_fread (FILE * stream, gsl_matrix_complex_float * m) ;\nGSL_EXPORT int gsl_matrix_complex_float_fwrite (FILE * stream, const gsl_matrix_complex_float * m) ;\nGSL_EXPORT int gsl_matrix_complex_float_fscanf (FILE * stream, gsl_matrix_complex_float * m);\nGSL_EXPORT int gsl_matrix_complex_float_fprintf (FILE * stream, const gsl_matrix_complex_float * m, const char * format);\n\nGSL_EXPORT int gsl_matrix_complex_float_memcpy(gsl_matrix_complex_float * dest, const gsl_matrix_complex_float * src);\nGSL_EXPORT int gsl_matrix_complex_float_swap(gsl_matrix_complex_float * m1, gsl_matrix_complex_float * m2);\n\nGSL_EXPORT int gsl_matrix_complex_float_swap_rows(gsl_matrix_complex_float * m, const size_t i, const size_t j);\nGSL_EXPORT int gsl_matrix_complex_float_swap_columns(gsl_matrix_complex_float * m, const size_t i, const size_t j);\nGSL_EXPORT int gsl_matrix_complex_float_swap_rowcol(gsl_matrix_complex_float * m, const size_t i, const size_t j);\n\nGSL_EXPORT int gsl_matrix_complex_float_transpose (gsl_matrix_complex_float * m);\nGSL_EXPORT int gsl_matrix_complex_float_transpose_memcpy (gsl_matrix_complex_float * dest, const gsl_matrix_complex_float * src);\n\nGSL_EXPORT int gsl_matrix_complex_float_isnull (const gsl_matrix_complex_float * m);\n\nGSL_EXPORT int gsl_matrix_complex_float_add (gsl_matrix_complex_float * a, const gsl_matrix_complex_float * b);\nGSL_EXPORT int gsl_matrix_complex_float_sub (gsl_matrix_complex_float * a, const gsl_matrix_complex_float * b);\nGSL_EXPORT int gsl_matrix_complex_float_mul_elements (gsl_matrix_complex_float * a, const gsl_matrix_complex_float * b);\nGSL_EXPORT int gsl_matrix_complex_float_div_elements (gsl_matrix_complex_float * a, const gsl_matrix_complex_float * b);\nGSL_EXPORT int gsl_matrix_complex_float_scale (gsl_matrix_complex_float * a, const gsl_complex_float x);\nGSL_EXPORT int gsl_matrix_complex_float_add_constant (gsl_matrix_complex_float * a, const gsl_complex_float x);\nGSL_EXPORT int gsl_matrix_complex_float_add_diagonal (gsl_matrix_complex_float * a, const gsl_complex_float x);\n\n/***********************************************************************/\n/* The functions below are obsolete                                    */\n/***********************************************************************/\nGSL_EXPORT int gsl_matrix_complex_float_get_row(gsl_vector_complex_float * v, const gsl_matrix_complex_float * m, const size_t i);\nGSL_EXPORT int gsl_matrix_complex_float_get_col(gsl_vector_complex_float * v, const gsl_matrix_complex_float * m, const size_t j);\nGSL_EXPORT int gsl_matrix_complex_float_set_row(gsl_matrix_complex_float * m, const size_t i, const gsl_vector_complex_float * v);\nGSL_EXPORT int gsl_matrix_complex_float_set_col(gsl_matrix_complex_float * m, const size_t j, const gsl_vector_complex_float * v);\n\n#ifdef HAVE_INLINE\n\nextern inline \ngsl_complex_float\ngsl_matrix_complex_float_get(const gsl_matrix_complex_float * m, \n                     const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  gsl_complex_float zero = {{0,0}};\n\n  if (i >= m->size1)\n    {\n      GSL_ERROR_VAL(\"first index out of range\", GSL_EINVAL, zero) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_VAL(\"second index out of range\", GSL_EINVAL, zero) ;\n    }\n#endif\n  return *(gsl_complex_float *)(m->data + 2*(i * m->tda + j)) ;\n} \n\nextern inline \nvoid\ngsl_matrix_complex_float_set(gsl_matrix_complex_float * m, \n                     const size_t i, const size_t j, const gsl_complex_float x)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_VOID(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_VOID(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  *(gsl_complex_float *)(m->data + 2*(i * m->tda + j)) = x ;\n}\n\nextern inline \ngsl_complex_float *\ngsl_matrix_complex_float_ptr(gsl_matrix_complex_float * m, \n                             const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  return (gsl_complex_float *)(m->data + 2*(i * m->tda + j)) ;\n} \n\nextern inline \nconst gsl_complex_float *\ngsl_matrix_complex_float_const_ptr(const gsl_matrix_complex_float * m, \n                                   const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  return (const gsl_complex_float *)(m->data + 2*(i * m->tda + j)) ;\n} \n\n#endif /* HAVE_INLINE */\n\n__END_DECLS\n\n#endif /* __GSL_MATRIX_COMPLEX_FLOAT_H__ */\n", "meta": {"hexsha": "3f4a66e658bd75b6b435e641039b8d52e4a3ff7b", "size": 12641, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/gsl/include/gsl/gsl_matrix_complex_float.h", "max_stars_repo_name": "dynaryu/vaws", "max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/gsl/include/gsl/gsl_matrix_complex_float.h", "max_issues_repo_name": "dynaryu/vaws", "max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/gsl/include/gsl/gsl_matrix_complex_float.h", "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.399408284, "max_line_length": 140, "alphanum_fraction": 0.7110196978, "num_tokens": 2867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.0275852831261459, "lm_q1q2_score": 0.010617910484281285}}
{"text": "\n#pragma once\n\n#include <gsl/gsl>\n\nnamespace aas {\n\n\tstruct SkelBone;\n\n\t/**\n\t* Represents a sphere for cloth collision purposes.\n\t*/\n\tstruct CollisionSphere {\n\t\tint boneId;\n\t\tfloat radius;\n\t\tMatrix3x4 worldMatrix;\n\t\tMatrix3x4 worldMatrixInverse;\n\t\tstd::unique_ptr<CollisionSphere> next;\n\t};\n\n\t/**\n\t* Represents a cylinder for cloth collision purposes.\n\t*/\n\tstruct CollisionCylinder {\n\t\tint boneId;\n\t\tfloat radius;\n\t\tfloat height;\n\t\tMatrix3x4 worldMatrix;\n\t\tMatrix3x4 worldMatrixInverse;\n\t\tstd::unique_ptr<CollisionCylinder> next;\n\t};\n\n\tstruct CollisionGeometry {\n\t\tstd::unique_ptr<CollisionSphere> firstSphere;\n\t\tstd::unique_ptr<CollisionCylinder> firstCylinder;\n\t};\n\n\t/**\n\t * Extract the cloth collision information from a list of bones.\n\t * The information is parsed from the bone names.\n\t */\n\tCollisionGeometry FindCollisionGeometry(gsl::span<SkelBone> bones);\n\n}\n", "meta": {"hexsha": "19977e88318555ffefcc94c0f24514ddec6d7447", "size": 867, "ext": "h", "lang": "C", "max_stars_repo_path": "Infrastructure/src/aas/aas_cloth_collision.h", "max_stars_repo_name": "edoipi/TemplePlus", "max_stars_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 69.0, "max_stars_repo_stars_event_min_datetime": "2015-05-05T14:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T06:13:04.000Z", "max_issues_repo_path": "Infrastructure/src/aas/aas_cloth_collision.h", "max_issues_repo_name": "edoipi/TemplePlus", "max_issues_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 457.0, "max_issues_repo_issues_event_min_datetime": "2015-05-01T22:07:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T02:19:10.000Z", "max_forks_repo_path": "Infrastructure/src/aas/aas_cloth_collision.h", "max_forks_repo_name": "edoipi/TemplePlus", "max_forks_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2016-02-04T21:19:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T23:14:51.000Z", "avg_line_length": 19.2666666667, "max_line_length": 68, "alphanum_fraction": 0.7404844291, "num_tokens": 217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.027585282026933125, "lm_q1q2_score": 0.010617910061180938}}
{"text": "/*\n   Copyright [2017-2019] [IBM Corporation]\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n       http://www.apache.org/licenses/LICENSE-2.0\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\n\n#ifndef __NUPM_DAX_DATA_H__\n#define __NUPM_DAX_DATA_H__\n\n#include <libpmem.h>\n#include <city.h> /* CityHash */\n#include <common/pointer_cast.h>\n#include <common/string_view.h>\n#include <common/types.h>\n#include <common/utils.h>\n#include <boost/icl/split_interval_map.hpp>\n#include <gsl/span>\n#include <algorithm>\n#include <list>\n#include <stdexcept>\n\nnamespace\n{\n\tstd::uint64_t make_uuid(const common::string_view name_)\n\t{\n\t\tif ( 255 < name_.size() )\n\t\t{\n\t\t\tthrow std::invalid_argument(\"invalid file name (too long)\");\n\t\t}\n\t\tauto region_id = ::CityHash64(name_.begin(), name_.size());\n\t\tif (region_id == 0) throw std::invalid_argument(\"invalid region_id (and extreme bad luck!)\");\n\t\treturn region_id;\n\t}\n}\n\nnamespace nupm\n{\nstatic std::uint32_t constexpr DM_REGION_MAGIC = 0xC0070000;\nstatic unsigned constexpr DM_REGION_NAME_MAX_LEN = 1024;\nstatic std::uint32_t constexpr DM_REGION_VERSION = 3;\nstatic unsigned constexpr dm_region_log_grain_size = DM_REGION_LOG_GRAIN_SIZE; // log2 granularity (CMake default is 25, i.e. 32 MiB)\n\nclass DM_undo_log {\n  static constexpr unsigned MAX_LOG_COUNT = 4;\n  static constexpr unsigned MAX_LOG_SIZE  = 272;\n  struct log_entry_t {\n    byte   log[MAX_LOG_SIZE];\n    void * ptr;\n    size_t length; /* zero indicates log freed */\n  };\n\n  void log(void *ptr, size_t length)\n  {\n    assert(length > 0);\n    assert(ptr);\n\n    if (length > MAX_LOG_SIZE)\n      throw std::invalid_argument(\"log length exceeds max. space\");\n\n    for (unsigned i = 0; i < MAX_LOG_COUNT; i++) {\n      if (_log[i].length == 0) {\n        _log[i].length = length;\n        _log[i].ptr    = ptr;\n        pmem_memcpy_nodrain(_log[i].log, ptr, length);\n        // TODO\n        //memcpy(_log[i].log, ptr, length);\n        //mem_flush(&_log[i], sizeof(log_entry_t));\n        return;\n      }\n    }\n    throw API_exception(\"undo log full\");\n  }\n\n public:\n  template <typename T>\n    void log(T *ptr)\n    {\n      static_assert(sizeof *ptr <= MAX_LOG_SIZE, \"object too big to log\");\n      log(ptr, sizeof *ptr);\n    }\n\n  void clear_log()\n  {\n    for (unsigned i = 0; i < MAX_LOG_COUNT; i++) _log[i].length = 0;\n  }\n\n  void check_and_undo()\n  {\n    for (unsigned i = 0; i < MAX_LOG_COUNT; i++) {\n      if (_log[i].length > 0) {\n        PLOG(\"undo log being applied (ptr=%p, len=%lu).\", _log[i].ptr,\n             _log[i].length);\n        // TODO\n        pmem_memcpy_persist(_log[i].ptr, _log[i].log, _log[i].length);\n        //memcpy(_log[i].ptr, _log[i].log, _log[i].length);\n        //        mem_flush_nodrain(_log[i].ptr, _log[i].length);\n        _log[i].length = 0;\n      }\n    }\n  }\n\n private:\n  log_entry_t _log[MAX_LOG_COUNT];\n} __attribute__((packed));\n\nclass DM_region {\npublic:\n  /* \"grain\" is the unit of suballocation within a region. It is a fixed power\n   * of 2 common to all regions in the devdax namespace.\n   */\n  using grain_offset_t = uint32_t;\n  grain_offset_t offset_grain;\n  grain_offset_t length_grain;\n  uint64_t region_id;\n  /* File name. Saved and returned.\n   * Internal logic uses region_id (file name hash) to reduce code changes.\n   */\n  char file_name[256];\n\n public:\n  /* re-zeroing constructor */\n  DM_region() : offset_grain(0), length_grain(0), region_id(0) { assert(check_aligned(this, 8)); }\n\n  void initialize(size_t space_size, std::size_t grain_size)\n  {\n    offset_grain = 0;\n    length_grain = boost::numeric_cast<uint32_t>(space_size / grain_size);\n    region_id = 0; /* zero indicates free */\n  }\n\n  friend class DM_region_header;\n} __attribute__((packed));\n\n/* Note: \"region\" has at least two meanings:\n *  1. The space starting with, and described by, DM_region_header. ndctl calls this a namespace.\n e  2. The space described by DM_region\n */\nclass DM_region_header {\n private:\n  static constexpr uint16_t DEFAULT_MAX_REGIONS = 1024;\n  using string_view = common::string_view;\n\n  uint32_t    _magic;         // 4\n  uint32_t    _version;       // 8\n  uint64_t    _device_size;   // 16\n  uint32_t    _region_count;  // 20\n  uint16_t    _log_grain_size; // 22\n  uint16_t    _resvd;         // 24\n  uint8_t     _padding[40];   // 64\n  DM_undo_log _undo_log;\n\n  /*\n   * Following this data, there is\n   * 1. region_table_base, immediately following (this + 1)\n   * 2. arena_base, at ptr_cast<byte>(this) + grain_size. Code assumes\n   *    (but does not verify) that DM_region_header plus all DM_region\n   *    descriptors fit within a single grain.\n   *\n   * grain 0:\n   *    \"region_header\"\n   *    \"region_table\"\n   * grains 1 and following:\n   *    \"arena\"\n   */\n\n public:\n  auto grain_size() const { return std::size_t(1) << _log_grain_size; }\n\n  /* Rebuilding constructor */\n  DM_region_header(size_t device_size)\n    : _magic(DM_REGION_MAGIC)\n    , _version(DM_REGION_VERSION)\n    , _device_size(device_size)\n    , _region_count( (::pmem_flush(this, sizeof(DM_region_header)), DEFAULT_MAX_REGIONS) )\n    , _log_grain_size(dm_region_log_grain_size)\n    , _resvd()\n    , _undo_log()\n  {\n    (void)_resvd; // unused\n    (void)_padding; // unused\n    DM_region *region_p = region_table_base();\n    /* initialize first region with all capacity with size of space, and size of grain */\n    region_p->initialize(device_size - grain_size(), grain_size());\n    _undo_log.clear_log();\n    region_p++;\n\n    for (uint16_t r = 1; r < _region_count; r++) {\n      new (region_p) DM_region();\n      _undo_log.clear_log();\n      region_p++;\n    }\n    major_flush();\n  }\n\n  void check_undo_logs()\n  {\n    _undo_log.check_and_undo();\n  }\n\n  void debug_dump()\n  {\n    PINF(\"DM_region_header:\");\n    PINF(\n        \" magic [0x%8x]\\n version [%u]\\n device_size [%lu]\\n region_count [%u]\",\n        _magic, _version, _device_size, _region_count);\n    PINF(\" base [%p]\", common::p_fmt(this));\n\n    const auto regions = region_table_span();\n    for (auto const & reg : regions ) {\n      if (reg.region_id > 0) {\n        PINF(\" - USED: %lu (%lx-%lx)\", reg.region_id,\n             grain_to_bytes(reg.offset_grain),\n             grain_to_bytes(reg.offset_grain + reg.length_grain) - 1);\n        assert(reg.length_grain > 0);\n      }\n      else if (reg.length_grain > 0) {\n        PINF(\" - FREE: %lu (%lx-%lx)\", reg.region_id,\n             grain_to_bytes(reg.offset_grain),\n             grain_to_bytes(reg.offset_grain + reg.length_grain) - 1);\n      }\n    }\n  }\n\n  void *get_region(string_view name_, size_t *out_size)\n  {\n    auto region_id = make_uuid(name_);\n\n    const auto regions = region_table_span();\n    for (auto const & reg : regions ) {\n      if (reg.region_id == region_id) {\n#if 0\n        PLOG(\"%s: found matching region (%lx)\", __func__, region_id);\n#endif\n        if (out_size) *out_size = grain_to_bytes(reg.length_grain);\n        return arena_base() + grain_to_bytes(reg.offset_grain);\n      }\n    }\n    return nullptr; /* not found */\n  }\n\n  void erase_region(string_view name_)\n  {\n    auto region_id = make_uuid(name_);\n\n    const auto regions = region_table_span();\n    for (auto & reg : regions ) {\n      if (reg.region_id == region_id) {\n        reg.region_id = 0; /* power-fail atomic */\n        pmem_flush(&reg.region_id, sizeof(reg.region_id));\n        return;\n      }\n    }\n    throw std::runtime_error(\"region not found\");\n  }\n\n  void *allocate_region(string_view name_, DM_region::grain_offset_t size_in_grain)\n  {\n    auto region_id = make_uuid(name_);\n\n    const auto regions = region_table_span();\n    for (auto & reg : regions ) {\n      if (reg.region_id == region_id)\n        throw std::bad_alloc();\n    }\n\n    bool found = false;\n    for (DM_region & reg : regions)\n    {\n      /* If we have found a sufficiently large free region */\n      if (reg.region_id == 0 && reg.length_grain >= size_in_grain) {\n        if (reg.length_grain == size_in_grain) {\n          /* exact match */\n          void *rp = arena_base() + grain_to_bytes(reg.offset_grain);\n          /* write file name to region */\n          pmem_memcpy_persist(reg.file_name, name_.begin(), name_.size());\n          pmem_memcpy_persist(&reg.file_name[name_.size()], \"\\0\", 1);\n          // claim region\n          tx_atomic_write(&reg, region_id);\n          return rp;\n        }\n        else {\n          /* cut out */\n          const uint32_t new_offset = reg.offset_grain;\n\n          const auto changed_length = reg.length_grain - size_in_grain;\n          const auto changed_offset = reg.offset_grain + size_in_grain;\n\n\t  /* reg_n is the new region for unallocated space */\n          auto reg_n = std::find_if(regions.begin(), regions.end(), [] (const DM_region &r) { return r.region_id == 0 && r.length_grain == 0; });\n          if ( reg_n != regions.end() )\n          {\n            void *rp = arena_base() + grain_to_bytes(new_offset);\n            /* write file name to region */\n            pmem_memcpy_persist(reg.file_name, name_.begin(), name_.size());\n            pmem_memcpy_persist(&reg.file_name[name_.size()], \"\\0\", 1);\n            // claim region\n            tx_atomic_write(&*reg_n, boost::numeric_cast<uint16_t>(changed_offset), boost::numeric_cast<uint16_t>(changed_length), &reg,\n                            new_offset, size_in_grain, region_id);\n            return rp;\n          }\n        }\n      }\n    }\n    if (!found)\n      throw General_exception(\"no more regions (size in grain=%u)\", size_in_grain);\n\n    throw General_exception(\"no spare slots\");\n  }\n\n  size_t get_max_available() const\n  {\n    auto regions = region_table_span();\n    auto max_grain_element =\n      std::max_element(\n        regions.begin()\n\t, regions.end()\n        , [] (const DM_region &a, const DM_region &b) -> bool { return a.length_grain < b.length_grain; }\n      );\n    return grain_to_bytes( max_grain_element == regions.end() ? 0 : max_grain_element->length_grain);\n  }\n\n  inline size_t grain_to_bytes(unsigned grain) const { return size_t(grain) << _log_grain_size; }\n\n  inline void major_flush()\n  {\n    pmem_flush(this, sizeof(DM_region_header) + (sizeof(DM_region) * _region_count));\n  }\n\n  bool check_magic() const\n  {\n    return (_magic == DM_REGION_MAGIC) && (_version == DM_REGION_VERSION);\n  }\n\n  std::list<std::string> names_list()\n  {\n    std::list<std::string> nl;\n    auto regions = region_table_span();\n    for ( const auto &r : regions )\n    {\n      if ( 0 != r.region_id )\n      {\n        nl.push_back(std::string(r.file_name));\n      }\n    }\n    return nl;\n  }\n\n private:\n  void tx_atomic_write(DM_region *dst, uint64_t region_id)\n  {\n#pragma GCC diagnostic push\n#if 9 <= __GNUC__\n#pragma GCC diagnostic ignored \"-Waddress-of-packed-member\"\n#endif\n    _undo_log.log(&dst->region_id);\n#pragma GCC diagnostic pop\n    dst->region_id = region_id;\n    pmem_flush(&dst->region_id, sizeof(region_id));\n    _undo_log.clear_log();\n  }\n\n  void tx_atomic_write(DM_region *dst0, // offset0, size0, offset1, size1 all expressed in grains\n                       uint32_t   offset0,\n                       uint32_t   size0,\n                       DM_region *dst1,\n                       uint32_t   offset1,\n                       uint32_t   size1,\n                       uint64_t   region_id1)\n  {\n    _undo_log.log(dst0);\n    _undo_log.log(dst1);\n\n    dst0->offset_grain = offset0;\n    dst0->length_grain = size0;\n    pmem_flush(dst0, sizeof(DM_region));\n\n    dst1->region_id = region_id1;\n    dst1->offset_grain = offset1;\n    dst1->length_grain = size1;\n    pmem_flush(dst1, sizeof(DM_region));\n\n    _undo_log.clear_log();\n  }\n\n  inline unsigned char *arena_base()\n  {\n    return common::pointer_cast<unsigned char>(this) + grain_size();\n  }\n\n  /* region descriptors immediately follow the DM_region_header. */\n  inline DM_region *region_table_base() { return common::pointer_cast<DM_region>(this + 1); }\n  inline const DM_region *region_table_base() const { return common::pointer_cast<const DM_region>(this + 1); }\n  gsl::span<DM_region> region_table_span() { return gsl::span<DM_region>(region_table_base(), _region_count); }\n  gsl::span<const DM_region> region_table_span() const { return gsl::span<const DM_region>(region_table_base(), _region_count); }\n\n  inline DM_region *region(size_t idx)\n  {\n    if (idx >= _region_count) return nullptr;\n    DM_region *p = static_cast<DM_region *>(region_table_base());\n    return &p[idx];\n  }\n\n  void reset_header(size_t device_size)\n  {\n    _magic       = DM_REGION_MAGIC;\n    _version     = DM_REGION_VERSION;\n    _device_size = device_size;\n    pmem_flush(this, sizeof(DM_region_header));\n  }\n} __attribute__((packed));\n\n}  // namespace nupm\n\n#endif  //__NUPM_DAX_DATA_H__\n", "meta": {"hexsha": "63c868ab27529482edc980f1e473eec4c830b4ae", "size": 13039, "ext": "h", "lang": "C", "max_stars_repo_path": "src/lib/libnupm/src/dax_data.h", "max_stars_repo_name": "omriarad/mcas", "max_stars_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 60.0, "max_stars_repo_stars_event_min_datetime": "2020-04-28T08:15:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T10:35:15.000Z", "max_issues_repo_path": "src/lib/libnupm/src/dax_data.h", "max_issues_repo_name": "omriarad/mcas", "max_issues_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 66.0, "max_issues_repo_issues_event_min_datetime": "2020-09-03T23:40:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T20:34:52.000Z", "max_forks_repo_path": "src/lib/libnupm/src/dax_data.h", "max_forks_repo_name": "omriarad/mcas", "max_forks_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2019-11-02T06:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T01:56:42.000Z", "avg_line_length": 30.8250591017, "max_line_length": 145, "alphanum_fraction": 0.6418436997, "num_tokens": 3447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29746993014852224, "lm_q2_score": 0.035678548570655874, "lm_q1q2_score": 0.01061329535111366}}
{"text": "\ufeff// Copyright 2018-2019 TAP, Inc. All Rights Reserved.\n\n#pragma once\n\n#include \"targetver.h\"\n\n#define WIN32_LEAN_AND_MEAN\n#define NOMINMAX\n#include <Windows.h>\n\n#include <cstdint>\n#include <cassert>\n#include <cstdlib>\n#include <cstdio>\n#include <corecrt_math_defines.h>\n\n#include <array>\n#include <vector>\n#include <iostream>\n#include <sstream>\n#include <fstream>\n#include <map>\n#include <chrono>\n#include <filesystem>\n#include <thread>\n#include <string>\nusing namespace std::literals::string_literals;\n\n#pragma warning(disable : 4127)\n#pragma warning(disable : 4201)\n#define GLM_FORCE_RADIANS\n#define GLM_FORCE_DEPTH_ZERO_TO_ONE\n#include <glm/glm.hpp>\n#include <glm/gtc/quaternion.hpp>\n#include <glm/gtc/matrix_transform.hpp>\n#include <glm/gtc/type_ptr.hpp>\n#include <glm/gtx/string_cast.hpp>\n#pragma warning(default : 4201)\n#pragma warning(default : 4127)\n\n#pragma warning(disable : 4100)\n#pragma warning(disable : 4458)\n#include <gli/gli.hpp>\n#pragma warning(default : 4458)\n#pragma warning(default : 4100)\n\n#define VK_USE_PLATFORM_WIN32_KHR\n#include <vulkan/vulkan.h>\n\n#include <vulkan/vk_mem_alloc.h>\n\n#include <entt/entt.hpp>\n\n#include <gsl/gsl>\n", "meta": {"hexsha": "ec047ee08b5200476a76b3c3a1257d68428b91d8", "size": 1152, "ext": "h", "lang": "C", "max_stars_repo_path": "stdafx.h", "max_stars_repo_name": "noirhero/new_framework", "max_stars_repo_head_hexsha": "2252d14cbb502414de7b03d7daf659ce44a0116d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stdafx.h", "max_issues_repo_name": "noirhero/new_framework", "max_issues_repo_head_hexsha": "2252d14cbb502414de7b03d7daf659ce44a0116d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stdafx.h", "max_forks_repo_name": "noirhero/new_framework", "max_forks_repo_head_hexsha": "2252d14cbb502414de7b03d7daf659ce44a0116d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.9454545455, "max_line_length": 54, "alphanum_fraction": 0.7595486111, "num_tokens": 299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3557749071749625, "lm_q2_score": 0.029760094376226766, "lm_q1q2_score": 0.010587894814220202}}
{"text": "#pragma once\n\n#include <gsl\\gsl>\n#include <winrt\\Windows.Foundation.h>\n#include <d3d11.h>\n#include \"DrawableGameComponent.h\"\n#include \"MatrixHelper.h\"\n#include \"PointLight.h\"\n#include \"DepthMap.h\"\n#include \"Rectangle.h\"\n#include \"ProjectiveTextureMappingMaterial.h\"\n#include \"RenderStateHelper.h\"\n\nnamespace DirectX\n{\n\tclass SpriteBatch;\n}\n\nnamespace Library\n{\n\tclass ProxyModel;\n\tclass RenderableFrustum;\n\tclass DepthMapMaterial;\n}\n\nnamespace Rendering\n{\n\tclass ProjectiveTextureMappingDemo final : public Library::DrawableGameComponent\n\t{\n\tpublic:\n\t\tProjectiveTextureMappingDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera);\n\t\tProjectiveTextureMappingDemo(const ProjectiveTextureMappingDemo&) = delete;\n\t\tProjectiveTextureMappingDemo(ProjectiveTextureMappingDemo&&) = default;\n\t\tProjectiveTextureMappingDemo& operator=(const ProjectiveTextureMappingDemo&) = default;\t\t\n\t\tProjectiveTextureMappingDemo& operator=(ProjectiveTextureMappingDemo&&) = default;\n\t\t~ProjectiveTextureMappingDemo();\n\n\t\tProjectiveTextureMappingDrawModes DrawMode() const;\n\t\tconst std::string& DrawModeString() const;\n\t\tvoid SetDrawMode(ProjectiveTextureMappingDrawModes drawMode);\n\n\t\tfloat AmbientLightIntensity() const;\n\t\tvoid SetAmbientLightIntensity(float intensity);\n\n\t\tfloat PointLightIntensity() const;\n\t\tvoid SetPointLightIntensity(float intensity);\n\n\t\tfloat PointLightRadius() const;\n\t\tvoid SetPointLightRadius(float radius);\n\n\t\tconst DirectX::XMFLOAT3& ProjectorPosition() const;\n\t\tconst DirectX::XMVECTOR ProjectorPositionVector() const;\n\t\tvoid SetProjectorPosition(const DirectX::XMFLOAT3& position);\n\t\tvoid SetProjectorPosition(DirectX::FXMVECTOR position);\n\n\t\tconst DirectX::XMFLOAT3& ProjectorDirection() const;\n\t\tvoid RotateProjector(const DirectX::XMFLOAT2& amount);\n\n\t\tvirtual void Initialize() override;\n\t\tvirtual void Update(const Library::GameTime& gameTime) override;\n\t\tvirtual void Draw(const Library::GameTime& gameTime) override;\n\n\tprivate:\n\t\tinline static const std::uint32_t DepthMapWidth{ 1024 };\n\t\tinline static const std::uint32_t DepthMapHeight{ 1024 };\n\t\tstatic inline const RECT DepthMapDestinationRectangle{ 0, 512, 256, 768 };\n\t\t\t\t\n\t\tvoid DrawWithDepthMap();\n\t\tvoid DrawWithoutDepthMap();\t\t\n\t\tvoid UpdateTransforms(ProjectiveTextureMappingMaterial::VertexCBufferPerObject& transforms, DirectX::FXMMATRIX worldViewProjectionMatrix, DirectX::CXMMATRIX worldMatrix, DirectX::CXMMATRIX projectiveTextureMatrix);\n\t\tvoid InitializeProjectedTextureScalingMatrix(uint32_t textureWidth, uint32_t textureHeight);\n\n\t\tProjectiveTextureMappingMaterial::VertexCBufferPerObject mPlaneTransforms;\n\t\tProjectiveTextureMappingMaterial::VertexCBufferPerObject mTeapotTransforms;\n\t\tDirectX::XMFLOAT4X4 mPlaneWorldMatrix{ Library::MatrixHelper::Identity };\n\t\tDirectX::XMFLOAT4X4 mTeapotWorldMatrix{ Library::MatrixHelper::Identity };\n\t\tDirectX::XMFLOAT4X4 mProjectedTextureScalingMatrix{ Library::MatrixHelper::Zero };\n\t\tLibrary::PointLight mPointLight;\n\t\tLibrary::DepthMap mDepthMap;\n\t\tLibrary::RenderStateHelper mRenderStateHelper;\n\t\tstd::shared_ptr<ProjectiveTextureMappingMaterial> mMaterial;\n\t\tstd::shared_ptr<Library::DepthMapMaterial> mDepthMapMaterial;\n\t\twinrt::com_ptr<ID3D11Buffer> mPlaneVertexBuffer;\n\t\twinrt::com_ptr<ID3D11Buffer> mTeapotVertexBuffer;\n\t\twinrt::com_ptr<ID3D11Buffer> mTeapotPositionOnlyVertexBuffer;\n\t\twinrt::com_ptr<ID3D11Buffer> mTeapotIndexBuffer;\n\t\tstd::uint32_t mPlaneVertexCount{ 0 };\t\t\n\t\tstd::uint32_t mTeapotIndexCount{ 0 };\n\t\tstd::unique_ptr<Library::ProxyModel> mProxyModel;\n\t\tstd::unique_ptr<Library::Camera> mProjector;\n\t\tstd::unique_ptr<Library::RenderableFrustum> mRenderableProjectorFrustum;\n\t\tstd::unique_ptr<DirectX::SpriteBatch> mSpriteBatch;\n\t\tbool mUpdateMaterial{ true };\n\t};\n}", "meta": {"hexsha": "06e5dd84feea8d140350aa5ff68fa7aa17d8f081", "size": 3736, "ext": "h", "lang": "C", "max_stars_repo_path": "source/8.1_Projective_Texture_Mapping/ProjectiveTextureMappingDemo.h", "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/8.1_Projective_Texture_Mapping/ProjectiveTextureMappingDemo.h", "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/8.1_Projective_Texture_Mapping/ProjectiveTextureMappingDemo.h", "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.3263157895, "max_line_length": 216, "alphanum_fraction": 0.8091541756, "num_tokens": 932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.02161533504735041, "lm_q1q2_score": 0.01055440918737731}}
{"text": "#pragma once\n/*\n * (C) Copyright 2020-2021 UCAR\n *\n * This software is licensed under the terms of the Apache Licence Version 2.0\n * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.\n */\n/*! \\addtogroup ioda_cxx_variable\n *\n * @{\n * \\file FillPolicy.h\n * \\brief Default fill values for ioda files.\n */\n\n#include <gsl/gsl-lite.hpp>\n#include <memory>\n#include <string>\n\n#include \"ioda/Variables/Fill.h\"\n#include \"ioda/Exception.h\"\n#include \"ioda/defs.h\"\n\nnamespace ioda {\n\n/// \\brief This option describes the default fill values that will be used if the user does not\n/// manually specify a fill value.\n/// \\ingroup ioda_cxx_variable\nenum class FillValuePolicy {\n  HDF5,    ///< Set all fill values to zero or null strings.\n  NETCDF4  ///< Use NetCDF4 default fill values. This is the default option for ioda files.\n};\n\n/// \\brief Holds the different default fill values used in ioda files produced by different\n///   backends.\n/// \\ingroup ioda_cxx_variable\n/// \\details This matters for netCDF4 vs HDF5-produced files. They have different default\n///   fill values.\nnamespace FillValuePolicies {\ntemplate <class T>\nT HDF5_default() {\n  return 0;\n}\ntemplate <>\ninline std::string HDF5_default<std::string>() {\n  return std::string();\n}\n\n/// \\ingroup ioda_cxx_variable\n/// \\see netcdf.h, starting around line 62, for these values\n///   netcdf uses \"ints\" and \"shorts\", but these are all defined as fixed-width types.\ntemplate <class T>\nT netCDF4_default() {\n  return 0;\n}\ntemplate <>\ninline std::string netCDF4_default<std::string>() {\n  return std::string();\n}\ntemplate <>\ninline signed char netCDF4_default<signed char>() {\n  return static_cast<signed char>(-127);\n}\ntemplate <>\ninline char netCDF4_default<char>() {\n  return static_cast<char>(0);\n}\ntemplate <>\ninline int16_t netCDF4_default<int16_t>() {\n  return static_cast<int16_t>(-32767);\n}\ntemplate <>\ninline int32_t netCDF4_default<int32_t>() {\n  return -2147483647;\n}\ntemplate <>\ninline float netCDF4_default<float>() {\n  return 9.9692099683868690e+36f;\n}\ntemplate <>\ninline double netCDF4_default<double>() {\n  return 9.9692099683868690e+36;\n}\ntemplate <>\ninline unsigned char netCDF4_default<unsigned char>() {\n  return static_cast<unsigned char>(255);\n}\ntemplate <>\ninline uint16_t netCDF4_default<uint16_t>() {\n  return static_cast<unsigned short>(65535);\n}\ntemplate <>\ninline uint32_t netCDF4_default<uint32_t>() {\n  return 4294967295U;\n}\ntemplate <>\ninline int64_t netCDF4_default<int64_t>() {\n  return -9223372036854775806LL;\n}\ntemplate <>\ninline uint64_t netCDF4_default<uint64_t>() {\n  return 18446744073709551614ULL;\n}\n\n/// \\brief Applies the fill value policy. This sets default fill values when fill values are not\n///   already provided.\n/// \\ingroup ioda_cxx_variable\ntemplate <class T>\nvoid applyFillValuePolicy(FillValuePolicy pol, detail::FillValueData_t& fvd) {\n  if (fvd.set_) return;  // If already set, then do nothing.\n  if (pol == FillValuePolicy::HDF5)\n    detail::assignFillValue(fvd, HDF5_default<T>());\n  else if (pol == FillValuePolicy::NETCDF4)\n    detail::assignFillValue(fvd, netCDF4_default<T>());\n  else\n    throw Exception(\"Unsupported fill value policy.\", ioda_Here());\n}\n\n\n\n}  // namespace FillValuePolicies\n}  // namespace ioda\n\n/// @}\n\n", "meta": {"hexsha": "322fef2cc1eb48d40c67abd0bcc02510a57527aa", "size": 3253, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engines/ioda/include/ioda/Variables/FillPolicy.h", "max_stars_repo_name": "Gibies/ioda", "max_stars_repo_head_hexsha": "5bd372e548eb61d5f7b56a0b3d4cf0ca05e49e75", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-09T16:11:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-09T16:11:50.000Z", "max_issues_repo_path": "src/engines/ioda/include/ioda/Variables/FillPolicy.h", "max_issues_repo_name": "Gibies/ioda", "max_issues_repo_head_hexsha": "5bd372e548eb61d5f7b56a0b3d4cf0ca05e49e75", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engines/ioda/include/ioda/Variables/FillPolicy.h", "max_forks_repo_name": "Gibies/ioda", "max_forks_repo_head_hexsha": "5bd372e548eb61d5f7b56a0b3d4cf0ca05e49e75", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-06-09T16:12:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-14T09:19:25.000Z", "avg_line_length": 26.024, "max_line_length": 96, "alphanum_fraction": 0.7260989856, "num_tokens": 863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15610488959337063, "lm_q2_score": 0.06754669207816587, "lm_q1q2_score": 0.010544368909259486}}
{"text": "#pragma once\n\n#include <gsl-lite/gsl-lite.hpp>\n\n#include <boost/test/data/test_case.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include <cuda/runtime_api.hpp>\n\n#include <thrustshift/managed-vector.h>\n#include <thrustshift/copy.h>\n\nnamespace thrustshift {\n\ntemplate<class MemoryResource>\nvoid touch_all_memory_resource_pages(MemoryResource& memory_resource) {\n\tauto device = cuda::device::current::get();\n\tauto stream = device.default_stream();\n\n\tfor (const auto [k, v] : memory_resource.get_book()) {\n\t\tfor (const auto& page : v) {\n\t\t\tBOOST_TEST(!page.allocated);\n\t\t\tusing T = std::byte;\n\t\t\tconst size_t N = k.bytes / sizeof(T);\n\t\t\tmanaged_vector<T> dst(N);\n\t\t\tgsl_lite::span<T> src(\n\t\t\t    reinterpret_cast<T*>(page.ptr), N);\n\t\t\tasync::copy(stream, src, dst);\n\t\t\tstream.synchronize();\n\t\t\tfor (size_t i = 0; i < N; ++i) {\n\t\t\t\tdst[i] = src[i];\n\t\t\t}\n\t\t}\n\t}\n}\n\n}\n", "meta": {"hexsha": "1ac8a3cc1e31013f10c3c8e546244b9205fc0e8a", "size": 859, "ext": "h", "lang": "C", "max_stars_repo_path": "test/memory-resource-check.h", "max_stars_repo_name": "pauleonix/thrustshift", "max_stars_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-16T13:01:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T13:01:46.000Z", "max_issues_repo_path": "test/memory-resource-check.h", "max_issues_repo_name": "pauleonix/thrustshift", "max_issues_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-23T14:12:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-17T11:40:04.000Z", "max_forks_repo_path": "test/memory-resource-check.h", "max_forks_repo_name": "pauleonix/thrustshift", "max_forks_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.6052631579, "max_line_length": 71, "alphanum_fraction": 0.6752037253, "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29098086621490676, "lm_q2_score": 0.03622005404437219, "lm_q1q2_score": 0.010539342700182155}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <getopt.h>\n#include <iniparser.h>\n#include <limits.h>\n#include \"prepmt/prepmt.h\"\n#include \"ispl/process.h\"\n#include \"iscl/array/array.h\"\n#include \"iscl/memory/memory.h\"\n#include \"iscl/os/os.h\"\n#ifdef PARMT_USE_INTEL\n#include <mkl_cblas.h>\n#else\n#include <cblas.h>\n#endif\n\n#define PROGRAM_NAME \"xgrnsTeleB\"\n\nstatic void printUsage(void);\nstatic int parseArguments(int argc, char *argv[],\n                          char iniFile[PATH_MAX], char section[256]);\nstruct sacData_struct *\n    prepmt_grnsTeleB_readData(const char *archiveFile, int *nobs, int *ierr);\n\nint prepmt_grnsTeleB_readParameters(const char *iniFile,\n                                    const char *section,\n                                    char archiveFile[PATH_MAX],\n                                    char parmtDataFile[PATH_MAX],\n                                    bool *luseCrust1,\n                                    char crustDir[PATH_MAX],\n                                    bool *luseSourceModel,\n                                    char sourceModel[PATH_MAX],\n                                    bool *luseTstarTable,\n                                    double *defaultTstar,\n                                    char tstarTable[PATH_MAX],\n                                    bool *lrepickGrns,\n                                    double *staWin, double *ltaWin,\n                                    double *staltaThreshPct,\n                                    bool *lalignXC,\n                                    bool *luseEnvelope,\n                                    bool *lnormalizeXC,\n                                    double *maxXCtimeLag,\n                                    int *ndepth, double **depths);\nint prepmt_grnsTeleB_loadTstarTable(const char *tstarTable,\n                                    const double defaultTstar,\n                                    const int nobs,\n                                    struct sacData_struct *data,\n                                    double **tstars);\n\nint main(int argc, char **argv)\n{\n    char iniFile[PATH_MAX], archiveFile[PATH_MAX], tstarTable[PATH_MAX],\n         parmtDataFile[PATH_MAX], crustDir[PATH_MAX],\n         sourceModel[PATH_MAX], section[256];\n    struct prepmtCommands_struct cmds;\n    struct vmodel_struct *recmod, telmod, srcmod;\n    struct prepmtEventParms_struct event;\n    struct hudson96_parms_struct hudson96Parms;\n    struct hpulse96_parms_struct hpulse96Parms;\n    struct prepmtModifyCommands_struct options;\n    struct sacData_struct *sacData, *grns, *ffGrns, *locFF;\n    const char *hudsonSection = \"hudson96\\0\";\n    const char *hpulseSection = \"hpulse96\\0\";\n    const int ntstar = 1;\n    double *depths, *tstars, defaultTstar, ltaWin, maxXCtimeLag,\n           staltaThreshPct, staWin;\n    int i, ierr, iobs, k, kndx, ndepth, nobs;\n    bool lalignXC, lnormalizeXC, lrepickGrns, luseCrust1,\n         luseSourceModel, luseEnvelope, luseTstarTable;\n\n    iscl_init();\n    depths = NULL;\n    memset(&options, 0, sizeof(struct prepmtModifyCommands_struct));\n    ierr = parseArguments(argc, argv, iniFile, section);\n    if (ierr != 0)\n    {\n        if (ierr ==-2){return EXIT_FAILURE;}\n        return EXIT_SUCCESS;\n    }\n    // Load the event\n    ierr = prepmt_event_initializeFromIniFile(iniFile, &event);\n    if (ierr != 0)\n    {\n        printf(\"%s: Error reading event info\\n\", PROGRAM_NAME);\n        return EXIT_FAILURE;\n    }\n    // Read the forward modeling parameters\n    ierr = prepmt_hudson96_readHudson96Parameters(iniFile, hudsonSection,\n                                                  &hudson96Parms);\n    if (ierr != 0)\n    {\n        printf(\"%s: Failed to read hudson parameters\\n\", PROGRAM_NAME);\n        return EXIT_FAILURE;\n    }\n    ierr = prepmt_hpulse96_readHpulse96Parameters(iniFile, hpulseSection,\n                                                  &hpulse96Parms);\n    if (ierr != 0)\n    {\n        printf(\"%s: Failed to read hpulse parameters\\n\", PROGRAM_NAME);\n        return EXIT_FAILURE;\n    }\n    ierr = prepmt_grnsTeleB_readParameters(iniFile, section,\n                                           archiveFile,\n                                           parmtDataFile,\n                                           &luseCrust1, crustDir,\n                                           &luseSourceModel, sourceModel,\n                                           &luseTstarTable,\n                                           &defaultTstar,\n                                           tstarTable,\n                                           &lrepickGrns,\n                                           &staWin, &ltaWin, &staltaThreshPct,\n                                           &lalignXC, &luseEnvelope,\n                                           &lnormalizeXC, &maxXCtimeLag,\n                                           &ndepth, &depths);\n    if (ierr != 0)\n    {\n        printf(\"%s: Failed to read modeling parameters\\n\", PROGRAM_NAME);\n        return EXIT_FAILURE;\n    }\n    // Read how the default commands will be modified\n    options.iodva = hpulse96Parms.iodva;\n    options.ldeconvolution = false; // We are working with the greens fns \n    ierr = prepmt_prepData_getDefaultDTAndWindowFromIniFile(iniFile, section,\n                                                            &options.targetDt,\n                                                            &options.cut0,\n                                                            &options.cut1);\n    if (ierr != 0)\n    {\n        printf(\"%s: Failed to read default command info\\n\", PROGRAM_NAME);\n        return EXIT_FAILURE;\n    }\n    // Load the data\n//memset(archiveFile, 0, PATH_MAX*sizeof(char));\n//strcpy(archiveFile, \"windowedPData/observedWaveforms.h5\\0\");\n    printf(\"%s: Loading data...\\n\", PROGRAM_NAME);\n    sacData = prepmt_prepData_readArchivedWaveforms(archiveFile, &nobs, &ierr);\n    if (ierr != 0)\n    {\n        printf(\"%s: Error loading data\\n\", PROGRAM_NAME);\n        return EXIT_FAILURE;\n    }\n    if (luseTstarTable)\n    {\n        printf(\"%s: Loading tstar table...\\n\", PROGRAM_NAME);\n        ierr = prepmt_grnsTeleB_loadTstarTable(tstarTable, defaultTstar,\n                                               nobs, sacData, &tstars);\n        if (ierr != 0)\n        {\n            printf(\"%s: Failed to load t* table\\n\", PROGRAM_NAME);\n            return EXIT_FAILURE;\n        }\n    }\n    else\n    {\n        printf(\"%s: Using default tstar: %f\\n\", PROGRAM_NAME, defaultTstar); \n        tstars = array_set64f(nobs, defaultTstar, &ierr);\n    }\n    printf(\"%s: Reading pre-processing commands...\\n\", PROGRAM_NAME);\n    cmds = prepmt_commands_readFromIniFile(iniFile, section, nobs,\n                                           sacData, &ierr);\n    if (ierr != 0)\n    {\n        printf(\"%s: Error loading grns prep commands\\n\", PROGRAM_NAME);\n        return -1;\n    }\n    printf(\"%s: Loading velocity models...\\n\", PROGRAM_NAME);\n    recmod = (struct vmodel_struct *)\n             calloc((size_t) nobs, sizeof(struct vmodel_struct));\n    ierr = hudson96_getModels(nobs, sacData,\n                              luseCrust1, crustDir,\n                              luseSourceModel, sourceModel,\n                              &telmod, &srcmod, recmod);\n    if (ierr != 0)\n    {\n        printf(\"%s: Failed to load models\\n\", PROGRAM_NAME);\n        return EXIT_FAILURE;\n    }\n    printf(\"%s: Computing fundamental fault solutions...\\n\", PROGRAM_NAME);\n    ffGrns = (struct sacData_struct *)\n             calloc((size_t) (ndepth*nobs*ntstar*10),\n                    sizeof(struct sacData_struct));\n    for (k=0; k<nobs; k++)\n    {\n        locFF = prepmt_hudson96_computeGreensFF(hudson96Parms,\n                                                hpulse96Parms,\n                                                telmod, srcmod, recmod,\n                                                ntstar, &tstars[1],\n                                                ndepth, depths,\n                                                1, &sacData[k], &ierr);\n        for (i=0; i<10*ndepth; i++)\n        {\n            kndx = k*10*ndepth + i;\n            sacio_copy(locFF[i], &ffGrns[kndx]);\n            sacio_freeData(&locFF[i]);\n        }\n        free(locFF);\n    }\n    printf(\"%s: Contextualing Green's functions...\\n\", PROGRAM_NAME);\n    grns = (struct sacData_struct *)\n           calloc((size_t) (6*ndepth*nobs*ntstar),\n                  sizeof(struct sacData_struct));\n    ierr = prepmt_greens_ffGreensToGreens(nobs, sacData,\n                                          ndepth, ntstar, ffGrns, grns);\n    if (ierr != 0)\n    {\n        printf(\"%s: Error contextualizing Greens functions\\n\", PROGRAM_NAME);\n        return EXIT_FAILURE;\n    }\n    for (k=0; k<10*nobs*ndepth*ntstar; k++){sacio_freeData(&ffGrns[k]);}\n    free(ffGrns);\n    // Release memory\n    for (k=0; k<nobs; k++)\n    {\n        cps_utils_freeVmodelStruct(&recmod[k]);\n    }\n    free(recmod);\n    cps_utils_freeVmodelStruct(&srcmod);\n    cps_utils_freeVmodelStruct(&telmod);\n    // Process the Green's functions\n    printf(\"%s: Modifying Green's functions processing commands...\\n\",\n           PROGRAM_NAME);\n    for (k=0; k<cmds.nobs; k++)\n    {\n        ierr = prepmt_commands_modifyCommandsCharsStruct(options,\n                                                         sacData[k],\n                                                         &cmds.cmds[k]);\n        /*\n        for (int l=0; l<cmds.cmds[k].ncmds; l++)\n        {\n             printf(\"%s\\n\", cmds.cmds[k].cmds[l]);\n        }\n        printf(\"\\n\");\n        */\n        if (ierr != 0)\n        {\n            printf(\"%s: Failed to modify processing commands\\n\", PROGRAM_NAME);\n            return EXIT_FAILURE;\n        }\n    }\n    printf(\"%s: Processing Green's functions...\\n\", PROGRAM_NAME);\n    ierr = prepmt_greens_processHudson96Greens(nobs, ntstar, ndepth,\n                                               cmds, grns);\n    if (ierr != 0)\n    {\n        printf(\"%s: Error processing Green's functions\\n\", PROGRAM_NAME);\n        return EXIT_FAILURE;\n    }\n    // Repick the Green's functions with an STA/LTA\n    if (lrepickGrns)\n    {\n        printf(\"%s: Repicking Green's functions...\\n\", PROGRAM_NAME);\n        for (k=0; k<ndepth*ntstar*nobs*6; k=k+6)\n        {\n            ierr = prepmt_greens_repickGreensWithSTALTA(staWin, ltaWin,\n                                                        staltaThreshPct,\n                                                        &grns[k]);\n            if (ierr != 0)\n            {\n                printf(\"%s: Error repicking Green's functions\\n\", PROGRAM_NAME);\n                return EXIT_FAILURE;\n            }\n        }\n    }\n    // Shift \n    if (lalignXC)\n    {\n        printf(\"%s: Refining waveform alignment with cross-correlation\\n\",\n               PROGRAM_NAME);\n        for (iobs=0; iobs<nobs; iobs++)\n        {\n            for (k=0; k<ndepth*ntstar; k++)\n            {\n                kndx = iobs*ndepth*ntstar*6 + k*6;\n                ierr = prepmt_greens_xcAlignGreensToData(sacData[iobs],\n                                                         luseEnvelope,\n                                                         lnormalizeXC,\n                                                         maxXCtimeLag,\n                                                         &grns[kndx]);\n                if (ierr != 0)\n                {\n                    printf(\"%s: Error aligning with XC\\n\", PROGRAM_NAME);\n                    return EXIT_FAILURE;\n                }\n            }\n        }\n    }\n    // Trim\n    printf(\"%s: Windowing Green's functions to data\\n\", PROGRAM_NAME);\n    ierr = prepmt_greens_cutHudson96FromData(nobs, sacData,\n                                             ndepth, ntstar, grns);\n    if (ierr != 0)\n    {\n        printf(\"%s: Error trimming Green's functions\\n\", PROGRAM_NAME);\n        return EXIT_FAILURE;\n    }\n    // Dump archive\n/*\nsacio_writeTimeSeriesFile(\"test_gxx.sac\", grns[11*ndepth*6+6]);\nsacio_writeTimeSeriesFile(\"test_gyy.sac\", grns[11*ndepth*6+7]);\nsacio_writeTimeSeriesFile(\"test_gzz.sac\", grns[11*ndepth*6+8]);\nsacio_writeTimeSeriesFile(\"test_gxy.sac\", grns[11*ndepth*6+9]);\nsacio_writeTimeSeriesFile(\"test_gxz.sac\", grns[11*ndepth*6+10]);\nsacio_writeTimeSeriesFile(\"test_gyz.sac\", grns[11*ndepth*6+11]);\n*/\n    printf(\"%s: Writing archive: %s\\n\", PROGRAM_NAME, parmtDataFile);\n    ierr = prepmt_greens_writeArchive(parmtDataFile, //\"./\", \"pwave\",\n                                      nobs, ndepth,\n                                      event.latitude, event.longitude,\n                                      depths, sacData, grns);\n    if (ierr != 0)\n    {\n        printf(\"%s: Failed to write archive file\\n\", PROGRAM_NAME);\n        return EXIT_FAILURE;\n    }\n    // release rest of memory\n    for (k=0; k<nobs; k++){sacio_freeData(&sacData[k]);}\n    for (k=0; k<ndepth*ntstar*nobs*6; k++){sacio_freeData(&grns[k]);}\n    memory_free64f(&tstars);\n    free(grns);\n    free(sacData);\n    iscl_finalize();\n\n    return EXIT_SUCCESS;\n}\n//============================================================================//\n/*!\n * @brief Obtains the forward modeling t* values for each teleseismic\n *        waveform observation from a text file.\n *\n * @param[in] tstarTable    Name of tstar table.\n * @param[in] defaultTstar  Default t* if a piece of data cannot be found in\n *                          the table.\n * @param[in] nobs          Number of observations.\n * @param[in] data          List of teleseismic waveforms to map t* values to.\n *                          This is an array of dimension [nobs].\n *\n * @param[out] tstars       tstar values corresponding to each station.\n *                          If a SNCL in the data list cannot be found in the\n *                          tstarTable file then this tstar will be set to the\n *                          default value.\n *                          This is an array of length [nobs].\n *\n * @result 0 indicates success.\n *\n * @author Ben Baker\n *\n */\nint prepmt_grnsTeleB_loadTstarTable(const char *tstarTable,\n                                    const double defaultTstar,\n                                    const int nobs,\n                                    struct sacData_struct *data,\n                                    double **tstars)\n{\n    FILE *tsf;\n    char cline[64], search[64], item[64];\n    double *tstar, tin;\n    int i, ierr, k, nlines;\n    bool lfound;\n    *tstars = NULL;\n    tstar = NULL;\n    if (!os_path_isfile(tstarTable))\n    {\n        fprintf(stderr, \"%s: Error tstar table %s does not exist\\n\",\n                 __func__, tstarTable);\n        return -1;\n    }\n    if (nobs < 1 || data == NULL)\n    {\n        fprintf(stderr, \"%s: No data\\n\", __func__);\n        return -1;\n    }\n    // Initialize to default\n    tstar = array_set64f(nobs, defaultTstar, &ierr);\n    // Get number of lines in text file\n    tsf = fopen(tstarTable, \"r\");\n    nlines = 0;\n    while (fgets(cline, 64, tsf) != NULL){nlines = nlines + 1;}  \n    rewind(tsf);\n    // Loop through and match observations to tstar's in table\n    for (k=0; k<nobs; k++)\n    {\n        memset(search, 0, 64*sizeof(char));\n        sprintf(search, \"%s.%s.%s.%s\",\n                data[k].header.knetwk, data[k].header.kstnm,\n                data[k].header.kcmpnm, data[k].header.khole);\n        lfound = false;\n        for (i=0; i<nlines; i++)\n        {\n            memset(cline, 0, 64*sizeof(char));\n            memset(item,  0, 64*sizeof(char));\n            fgets(cline, 64, tsf);\n            sscanf(cline, \"%s %lf\\n\", item, &tin);\n            if (strcasecmp(search, item) == 0)\n            {\n                tstar[k] = defaultTstar; \n                lfound = true;\n                break;\n            }\n        }\n        if (!lfound)\n        {\n            fprintf(stderr, \"%s: Setting %s tstar to: %f\\n\",\n                    __func__, search, defaultTstar);\n        }\n        rewind(tsf);\n    }\n    fclose(tsf);\n    *tstars = tstar;\n    return 0;\n}\n//============================================================================//\n/*!\n * @brief TODO: delete this function. \n */\nint prepmt_grnsTeleB_windowHudson96(\n    const int nobs, const int ntstar, const int ndepth,\n    const struct sacData_struct *data,\n    struct sacData_struct *grns)\n{\n    double epoch, epochGrns;\n    int indices[6], idep, ierr, iobs, it;\n    for (iobs=0; iobs<nobs; iobs++)\n    {\n        // Figure out the origin time\n        ierr = sacio_getEpochalStartTime(data[iobs].header, &epoch);\n        if (ierr != 0)\n        {\n            fprintf(stderr, \"%s: Failed to get start time\\n\", __func__);\n            break;\n        }\n        for (idep=0; idep<ndepth; idep++)\n        {\n            for (it=0; it<ntstar; it++)\n            {\n                ierr = prepmt_greens_getHudson96GreensFunctionsIndices(\n                                        nobs, ntstar, ndepth,\n                                        iobs, it, idep, indices);\n                // Figure out the origin time\n                ierr = sacio_getEpochalStartTime(grns[indices[0]].header,\n                                                 &epochGrns);\n                if (ierr != 0)\n                {\n                    fprintf(stderr, \"%s: Failed to get start time\\n\", __func__);\n                    break;\n                }\n                // Fig\n            }\n        }\n    }\n    return 0;\n}\n//============================================================================//\n/*!\n * @brief Processes the Green's functions.\n *\n * @param[in,out] grns    On input contains the Green's functions for all\n *                        observations, depths, and t*'s as well as the\n *                        processing chains. \\n\n *                        On output contains the filtered Green's functions\n *                        for all observations, depths, and t*'s.\n *\n * @result 0 indicates success.\n *\n * @author Ben Baker, ISTI\n *\n */\nint prepmt_grnsTeleB_processHudson96Greens(\n    const int nobs, const int ntstar, const int ndepth,\n    const struct prepmtCommands_struct cmds,\n    struct sacData_struct *grns)\n{\n    struct serialCommands_struct commands;\n    struct parallelCommands_struct parallelCommands;\n    double *G, dt, dt0, epoch, epoch0, time;\n    int *dataPtr, indices[6], \n        i, i0, i1, i2, ierr, iobs, idep, it, kndx, l, npts, npts0, nq,\n        nwork, ny, ns, nsuse;\n    bool lnewDt, lnewStartTime;\n    const int nTimeVars = 12;\n    const enum sacHeader_enum timeVars[12]\n       = {SAC_FLOAT_A, SAC_FLOAT_O, \n          SAC_FLOAT_T0, SAC_FLOAT_T1, SAC_FLOAT_T2, SAC_FLOAT_T3,\n          SAC_FLOAT_T4, SAC_FLOAT_T5, SAC_FLOAT_T6, SAC_FLOAT_T7,\n          SAC_FLOAT_T8, SAC_FLOAT_T9};\n    const int spaceInquiry =-1;\n    // Loop on the observations\n    ns = ndepth*ntstar*6;\n    dataPtr = memory_calloc32i(ns);\n    for (iobs=0; iobs<nobs; iobs++)\n    {\n        // Set the processing structure\n        memset(&parallelCommands, 0,\n               sizeof(struct parallelCommands_struct)); \n               memset(&commands, 0, sizeof(struct serialCommands_struct));\n        kndx = prepmt_greens_getHudson96GreensFunctionIndex(G11_GRNS,\n                                                      nobs, ntstar, ndepth,\n                                                      iobs, 0, 0);\n        // Parse the commands\n        ierr = process_stringsToSerialCommandsOptions(\n                                      cmds.cmds[iobs].ncmds,\n                                      (const char **) cmds.cmds[iobs].cmds,\n                                      &commands);\n        if (ierr != 0)\n        {\n            fprintf(stderr, \"%s: Error setting serial command string\\n\",\n                    __func__);\n            goto ERROR;\n        }\n        // Determine some characteristics of the processing\n        sacio_getEpochalStartTime(grns[kndx].header, &epoch0);\n        sacio_getFloatHeader(SAC_FLOAT_DELTA, grns[kndx].header, &dt0);\n        lnewDt = false;\n        lnewStartTime = false;\n        epoch = epoch0;\n        dt = dt0;\n        for (i=0; i<commands.ncmds; i++)\n        {\n            if (commands.commands[i].type == CUT_COMMAND)\n            {\n                i0 = commands.commands[i].cut.i0;\n                epoch = epoch + (double) i0*dt;\n                lnewStartTime = true;\n            }\n            if (commands.commands[i].type == DOWNSAMPLE_COMMAND)\n            {\n                nq = commands.commands[i].downsample.nq;\n                dt = dt*(double) nq;\n                lnewDt = true;\n            }\n            if (commands.commands[i].type == DECIMATE_COMMAND)\n            {\n                nq = commands.commands[i].decimate.nqAll;\n                dt = dt*(double) nq;\n                lnewDt = true;\n            }\n        }\n        // Set the commands on the parallel processing structure\n        ierr = process_setCommandOnAllParallelCommands(ns, commands,\n                                                       &parallelCommands);\n        if (ierr != 0)\n        {\n            fprintf(stderr, \"%s: Error setting the parallel commands\\n\",\n                    __func__);\n            goto ERROR;\n        }\n        // Get the data\n        dataPtr[0] = 0;\n        for (idep=0; idep<ndepth; idep++)\n        {\n            for (it=0; it<ntstar; it++)\n            {\n                kndx = prepmt_greens_getHudson96GreensFunctionIndex(G11_GRNS,\n                                                          nobs, ntstar, ndepth,\n                                                          iobs, 0, 0);\n                ierr = sacio_getIntegerHeader(SAC_INT_NPTS,\n                                              grns[kndx].header, &npts);\n                if (ierr != 0)\n                {\n                    fprintf(stderr, \"%s: Error getting npts\\n\", __func__);\n                    goto ERROR;\n                }\n                i1 = idep*6*ntstar + it*6 + 0;\n                i2 = i1 + 6;\n                for (i=i1; i<i2; i++)\n                {\n                    dataPtr[i+1] = dataPtr[i] + npts;\n                }\n            }\n        }\n        nwork = dataPtr[6*ndepth*ntstar];\n        if (nwork < 1)\n        {\n            fprintf(stderr, \"%s: Invalid workspace size: %d\\n\",\n                    __func__, nwork);\n            ierr = 1;\n            goto ERROR;\n        } \n        G = memory_calloc64f(nwork);\n        for (idep=0; idep<ndepth; idep++)\n        {\n            for (it=0; it<ntstar; it++)\n            {\n                ierr = prepmt_greens_getHudson96GreensFunctionsIndices(\n                                        nobs, ntstar, ndepth,\n                                        iobs, it, idep, indices);\n                if (ierr != 0)\n                {\n                    fprintf(stderr, \"%s: Error getting index\\n\", __func__);\n                    goto ERROR;\n                }\n                for (i=0; i<6; i++)\n                {\n                    i1 = idep*6*ntstar + it*6 + i;\n                    cblas_dcopy(grns[indices[i]].npts, \n                                grns[indices[i]].data, 1, &G[dataPtr[i1]], 1);\n                }\n            }\n        }\n        // Set the data\n        ierr =  process_setParallelCommandsData64f(ns, dataPtr,\n                                                   G, &parallelCommands);\n        if (ierr != 0)\n        {\n            fprintf(stderr, \"%s: Error setting data\\n\", __func__);\n            goto ERROR;\n        }\n        // Apply the commands\n        ierr = process_applyParallelCommands(&parallelCommands);\n        if (ierr != 0)\n        {\n            fprintf(stderr, \"%s: Error processing data\\n\", __func__);\n            goto ERROR;\n        }\n        // Get the data\n        ierr = process_getParallelCommandsData64f(parallelCommands,\n                                                  spaceInquiry, spaceInquiry,\n                                                  &ny, &nsuse,\n                                                  dataPtr, G);\n        if (ny < nwork)\n        {\n            memory_free64f(&G);\n            G = memory_calloc64f(ny);\n        }\n        ny = nwork;\n        ierr = process_getParallelCommandsData64f(parallelCommands,\n                                                  nwork, ns,\n                                                  &ny, &nsuse, dataPtr, G); \n        if (ierr != 0)\n        {\n            fprintf(stderr, \"%s: Error getting data\\n\", __func__);\n            goto ERROR;\n        }\n        // Unpack the data\n        for (idep=0; idep<ndepth; idep++)\n        {\n            for (it=0; it<ntstar; it++)\n            {\n                ierr = prepmt_greens_getHudson96GreensFunctionsIndices(\n                                        nobs, ntstar, ndepth,\n                                        iobs, it, idep, indices);\n                if (ierr != 0)\n                {\n                    fprintf(stderr, \"%s: Error getting index\\n\", __func__);\n                    goto ERROR;\n                }\n                for (i=0; i<6; i++)\n                {\n                    i1 = idep*6*ntstar + it*6 + i;\n                    sacio_getIntegerHeader(SAC_INT_NPTS,  \n                                           grns[indices[i]].header, &npts0);\n                    npts = dataPtr[i1+1] - dataPtr[i1];\n                    // Resize event\n                    if (npts != npts0)\n                    {\n                        sacio_freeData(&grns[indices[i]]);\n                        grns[indices[i]].data = sacio_malloc64f(npts);\n                        grns[indices[i]].npts = npts;\n                        sacio_setIntegerHeader(SAC_INT_NPTS, npts,\n                                               &grns[indices[i]].header);\n                        ierr = array_copy64f_work(npts,\n                                                  &G[dataPtr[i]],\n                                                  grns[indices[i]].data);\n                    }\n                    else\n                    {\n                        ierr = array_copy64f_work(npts,\n                                                  &G[dataPtr[i]],\n                                                  grns[indices[i]].data);\n                    }\n                    // Update the times\n                    if (lnewStartTime)\n                    {\n                        for (i=0; i<6; i++)\n                        {\n                            // Update the picks\n                            for (l=0; l<nTimeVars; l++)\n                            {\n                                ierr = sacio_getFloatHeader(timeVars[l],\n                                              grns[indices[i]].header, &time);\n                                if (ierr == 0)\n                                {\n                                    time = time + epoch0; // Turn to real time\n                                    time = time - epoch;  // Relative to new time\n                                    sacio_setFloatHeader(timeVars[l], time,\n                                                    &grns[indices[i]].header);\n                                }\n                            } // Loop on picks\n                            sacio_setEpochalStartTime(epoch,\n                                                      &grns[indices[i]].header);\n                        } // Loop on signals\n                    }\n                    // Update the sampling period\n                    if (lnewDt)\n                    {\n                        for (i=0; i<6; i++)\n                        {\n                            sacio_setFloatHeader(SAC_FLOAT_DELTA, dt,\n                                                 &grns[indices[i]].header);\n                        }\n                    }\n                } // Loop on Green's functions gxx, gyy, ...\n            } // Loop on t*\n        } // Loop on depths\n        process_freeSerialCommands(&commands);\n        process_freeParallelCommands(&parallelCommands);\n        memory_free64f(&G);\n    }\nERROR:;\n    memory_free32i(&dataPtr);\n    return 0;\n}\n//============================================================================//\n/*!\n * @brief Reads the teleseismic body wave Green's functions modeling parameters.\n *\n * @param[in] iniFile           Name of initialization file.\n * @param[in] section           Section of initalization file to read.  For\n *                              example, this may be prepmt:telePGrns.\n * @param[out] archiveFile      This is the HDF5 file with the observed waveforms.\n * @param[out] parmtDataFile    This is the name of the data archive file to\n *                              be used by parmt.\n * @param[out] luseCrust1       If true then the modeling may use crust1 \n *                              at the source and receiver (unless superseded\n *                              by a specified local model). \\n\n *                              Otherwise, use a local model or the global \n *                              ak135 earth model.\n * @param[out] crustDir         The crust1.0 directory.  This is only relevant\n *                              if luseCrust1 is true.\n * @param[out] luseSourceModel  If true then use a local source model.\n * @param[out] sourceModel      If luseSourceModel is true then this is the\n *                              filename with the local source model.\n * @param[out] luseTstarTable   If true then read the t* attenuation factors\n *                              from a table.\n * @param[out] defaultTstar     This is the default t* (e.g., 0.4).\n * @param[out] tstarTable       If luseTstarTable is true then this is the file\n *                              with the station/t* table pairings.\n * @param[out] lreprickGrns     If true then repick the Green's functions with\n *                              an STA/LTA function.  This is in the context of\n *                              severe attenutation which noticeably effect\n *                              theoretical arrival times.\n * @param[out] staWin           If repicking Green's functions then this\n *                              is the short term window (seconds).\n * @param[out] ltaWin           If repicking Green's functions then this\n *                              is the long term window (seconds).  \n * @param[out] staltaThreshPct  This is the fraction (0,1) after which an \n *                              arrival is declared in the STA/LTA repicking.\n * @param[out] lalignXC         If true the the Green's functions will be \n *                              re-aligned with cross-correlation.\n * @param[out] luseEnvelope     If true and lalignXC is true then the \n *                              Green's functions will be aligned based on \n *                              the cross-correlation of their envelopes.\n * @param[out] lnormalizeXC     If true then each Green's function is normalized\n *                              in the Green's function cross-correlation thus\n *                              Green's functions with larger amplitudes may \n *                              bias the result.\n * @param[out] maxXCtimeLag     This is the max time lag (seconds) available to\n *                              the waveform cross-correlation alignment.\n * @param[out] ndepth           Number of depths in modeling.\n * @param[in,out] depths        On input this is a NULL pointer.\n *                              On output this is a pointer to an array \n *                              of dimension [ndepth] with the modeling depths\n *                              (km).\n *\n * @result 0 indicates success.\n *\n * @author Ben Baker, ISTI\n *\n */\nint prepmt_grnsTeleB_readParameters(const char *iniFile,\n                                    const char *section,\n                                    char archiveFile[PATH_MAX],\n                                    char parmtDataFile[PATH_MAX],\n                                    bool *luseCrust1,\n                                    char crustDir[PATH_MAX],\n                                    bool *luseSourceModel,\n                                    char sourceModel[PATH_MAX],\n                                    bool *luseTstarTable,\n                                    double *defaultTstar,\n                                    char tstarTable[PATH_MAX],\n                                    bool *lrepickGrns,\n                                    double *staWin, double *ltaWin,\n                                    double *staltaThreshPct,\n                                    bool *lalignXC,\n                                    bool *luseEnvelope,\n                                    bool *lnormalizeXC,\n                                    double *maxXCtimeLag,\n                                    int *ndepth, double **depths)\n{\n    const char *s;\n    char vname[256];\n    dictionary *ini;\n    char *dirName;\n    double *deps, dmin, dmax;\n    int ierr;\n\n    ierr = 0;\n    deps = NULL;\n    memset(archiveFile, 0, PATH_MAX*sizeof(char));\n    memset(crustDir, 0, PATH_MAX*sizeof(char));\n    memset(sourceModel, 0, PATH_MAX*sizeof(char));\n    memset(tstarTable, 0, PATH_MAX*sizeof(char));\n    memset(parmtDataFile, 0, PATH_MAX*sizeof(char));\n    if (!os_path_isfile(iniFile))\n    {\n        fprintf(stderr, \"%s: Error ini file does not exist\\n\", __func__);\n        return -1;\n    }\n    ini = iniparser_load(iniFile);\n\n    memset(vname, 0, 256*sizeof(char));\n    sprintf(vname, \"%s:dataH5File\", section);\n    s = iniparser_getstring(ini, vname, NULL);\n    if (!os_path_isfile(s))\n    {\n        fprintf(stderr, \"%s: Data file %s does not exist\\n\", __func__, s);\n        ierr = 1;\n        goto ERROR;\n    }\n    strcpy(archiveFile, s);\n\n    memset(vname, 0, 256*sizeof(char));\n    sprintf(vname, \"%s:parmtDataFile\", section);\n    s = iniparser_getstring(ini, vname, \"bodyWave.h5\"); \n    strcpy(parmtDataFile, s);\n\n    dirName = os_dirname(parmtDataFile, &ierr);\n    if (!os_path_isdir(dirName))\n    {\n        ierr = os_makedirs(dirName);\n        if (ierr != 0)\n        {\n            fprintf(stderr, \"%s: Failed to make directory: %s\\n\",\n                    __func__, dirName);\n            goto ERROR;\n        }\n    }\n    memory_free8c(&dirName);\n\n    memset(vname, 0, 256*sizeof(char));\n    sprintf(vname, \"%s:lrepickGrns\", section);\n    *lrepickGrns = iniparser_getboolean(ini, vname, false);\n\n    memset(vname, 0, 256*sizeof(char));\n    sprintf(vname, \"%s:staWin\", section);\n    *staWin = iniparser_getdouble(ini, vname, 0.2);\n    if (*staWin <= 0.0)\n    {\n        fprintf(stderr, \"%s: Invalid STA length %f\\n\", __func__, *staWin);\n        ierr = 1;\n        goto ERROR;\n    }\n\n    memset(vname, 0, 256*sizeof(char));\n    sprintf(vname, \"%s:ltaWin\", section);\n    *ltaWin = iniparser_getdouble(ini, vname, 1.2);\n    if (*ltaWin <= *staWin)\n    {\n        fprintf(stderr, \"%s: Invalid LTA/STA lengths %f %f\\n\",\n                __func__, *staWin, *ltaWin);\n        ierr = 1;\n        goto ERROR;\n    }\n\n    memset(vname, 0, 256*sizeof(char));\n    sprintf(vname, \"%s:staltaThreshPct\", section);\n    *staltaThreshPct = iniparser_getdouble(ini, vname, 0.8);\n    if (*staltaThreshPct <= 0.0 || *staltaThreshPct > 1.0)\n    {\n        fprintf(stderr, \"%s: Invalid STA/LTA thresh pct %f\\n\",\n                 __func__, *staltaThreshPct);\n        ierr = 1;\n        goto ERROR;\n    }\n\n    memset(vname, 0, 256*sizeof(char));\n    sprintf(vname, \"%s:luseTstarTable\", section);\n    *luseTstarTable = iniparser_getboolean(ini, vname, false);\n    if (*luseTstarTable)\n    {\n        memset(vname, 0, 256*sizeof(char));\n        sprintf(vname, \"%s:tstarTable\", section);\n        s = iniparser_getstring(ini, vname, NULL);\n        if (!os_path_isfile(s))\n        {\n            fprintf(stderr, \"%s: tstar table %s doesn't exist\\n\",\n                    __func__, s);\n            ierr = 1;\n            goto ERROR;\n        }\n        strcpy(tstarTable, s);\n    }\n\n    memset(vname, 0, 256*sizeof(char));\n    strcpy(vname, \"precompute:ndepths\\0\");\n    *ndepth = iniparser_getint(ini, vname, 0);\n    if (*ndepth < 1)\n    {\n        fprintf(stderr, \"%s: Inadequate number of depths %d\\n\",\n                __func__, *ndepth);\n        ierr = 1;\n        goto ERROR;\n    }\n\n    memset(vname, 0, 256*sizeof(char));\n    strcpy(vname, \"precompute:depthMin\\0\");\n    dmin = iniparser_getdouble(ini, vname, -1.0);\n\n    memset(vname, 0, 256*sizeof(char));\n    strcpy(vname, \"precompute:depthMax\\0\");\n    dmax = iniparser_getdouble(ini, vname, -1.0);\n    if (dmin < 0.0 || dmin > dmax)\n    {\n        fprintf(stderr, \"%s: Invalid dmin/dmax %f %f\\n\", __func__, dmin, dmax);\n        ierr = 1;\n        goto ERROR;\n    }\n    deps = array_linspace64f(dmin, dmax, *ndepth, &ierr);\n\n    memset(vname, 0, 256*sizeof(char));\n    strcpy(vname, \"precompute:luseCrust1\\0\");\n    *luseCrust1 = iniparser_getboolean(ini, vname, true);\n    if (*luseCrust1)\n    {\n        memset(vname, 0, 256*sizeof(char));\n        strcpy(vname, \"precompute:crustDir\\0\");\n        s = iniparser_getstring(ini, vname, CPS_DEFAULT_CRUST1_DIRECTORY);\n        if (!os_path_isdir(s))\n        {\n            fprintf(stderr, \"%s: crust1.0 directory %s doesn't exist\\n\",\n                    __func__, s);\n            ierr = 1;\n            goto ERROR;\n        }\n        strcpy(crustDir, s);\n    }\n\n    memset(vname, 0, 256*sizeof(char));\n    strcpy(vname, \"precompute:luseSourceModel\\0\");\n    *luseSourceModel = iniparser_getboolean(ini, vname, false);\n    if (*luseSourceModel)\n    {\n        memset(vname, 0, 256*sizeof(char));\n        strcpy(vname, \"precompute:sourceModel\\0\");\n        s = iniparser_getstring(ini, vname, NULL);\n        if (!os_path_isfile(s))\n        {\n            fprintf(stderr, \"%s: Source model %s does not exist\\n\",\n                    __func__, s);\n            ierr = 1;\n            goto ERROR;\n        }\n        strcpy(sourceModel, s);\n    }\n       \n    memset(vname, 0, 256*sizeof(char));\n    sprintf(vname, \"%s:defaultTstar\", section); \n    *defaultTstar = iniparser_getdouble(ini, vname, 0.4);\n\n    memset(vname, 0, 256*sizeof(char));\n    sprintf(vname, \"%s:lalignXC\", section);\n    *lalignXC = iniparser_getboolean(ini, vname, false);\n\n    memset(vname, 0, 256*sizeof(char));\n    sprintf(vname, \"%s:luseEnvelope\", section);\n    *luseEnvelope = iniparser_getboolean(ini, vname, false);\n\n    memset(vname, 0, 256*sizeof(char));\n    sprintf(vname, \"%s:lnormalizeXC\", section);\n    *lnormalizeXC = iniparser_getboolean(ini, vname, false);\n\n    memset(vname, 0, 256*sizeof(char));\n    sprintf(vname, \"%s:maxXCtimeLag\", section);\n    *maxXCtimeLag = iniparser_getdouble(ini, vname, -1.0);\n \nERROR:;\n    *depths = deps;\n    iniparser_freedict(ini);\n    return ierr;\n}\n//============================================================================//\n/*!\n * @brief Utility function for reading the data for which the Green's functions\n *        will be generated.\n *\n * @param[in] archiveFile  Name of HDF5 archive file containing the\n *                         observations.\n *\n * @param[out] nobs        Number of observations.\n * @param[out] ierr        0 indicates success.\n *\n * @result The SAC data from the H5 archive for which the Green's functions\n *         will be created.  This is an array of dimension [nobs].\n *\n * @author Ben Baker, ISTI\n *\n */\nstruct sacData_struct *\n    prepmt_grnsTeleB_readData(const char *archiveFile, int *nobs, int *ierr)\n{\n    char **sacFiles;\n    hid_t groupID, fileID;\n    int i, nfiles;\n    struct sacData_struct *sacData;\n    *nobs = 0;\n    sacData = NULL;\n    if (!os_path_isfile(archiveFile))\n    {\n        fprintf(stderr, \"%s: Error archive file %s doesn't exist\\n\",\n                __func__, archiveFile);\n        *ierr = 1;\n        return sacData;\n    }\n    fileID = H5Fopen(archiveFile, H5F_ACC_RDONLY, H5P_DEFAULT); \n    groupID = H5Gopen2(fileID, \"/ObservedWaveforms\", H5P_DEFAULT);\n    sacFiles = sacioh5_getFilesInGroup(groupID, &nfiles, ierr);\n    if (*ierr != 0 || sacFiles == NULL)\n    {\n        fprintf(stderr, \"%s: Error getting names of SAC flies\\n\", __func__);\n        *ierr = 1;\n        return sacData;\n    }\n    sacData = sacioh5_readTimeSeriesList(nfiles, (const char **) sacFiles,\n                                         groupID, nobs, ierr);\n    if (*ierr != 0)\n    {\n        fprintf(stderr, \"%s: Errors while reading SAC files\\n\", __func__);\n    }\n    if (*nobs != nfiles)\n    {\n        fprintf(stderr, \"%s: Warning - subset of data was read\\n\", __func__);\n    }\n    // Clean up and close archive file\n    for (i=0; i<nfiles; i++)\n    {\n        if (sacFiles[i] != NULL){free(sacFiles[i]);}\n    }\n    free(sacFiles);\n    H5Gclose(groupID);\n    H5Fclose(fileID);\n    return sacData;\n}\n//============================================================================//\n/*!\n * @brief Parses the command line arguments for the ini file.\n *\n * @param[in] argc      Number of arguments input to the program.\n * @param[in] argv      Command line arguments.\n *\n * @param[out] iniFile  If the result is 0 then this is the ini file.\n * @param[out] section  Section of ini file to read.  The default is\n *                      prepmt:telePGrns. \n *\n * @result 0 indicates success. \\n\n *        -1 indicates the user inquired about the usage. \\n\n *        -2 indicates the command line argument is invalid.\n *\n * @author Ben Baker, ISTI\n *\n */\nstatic int parseArguments(int argc, char *argv[],\n                          char iniFile[PATH_MAX], char section[256])\n{\n    bool linFile, lsection;\n    linFile = false;\n    lsection = false;\n    memset(iniFile, 0, PATH_MAX*sizeof(char));\n    memset(section, 0, 256*sizeof(char));\n    while (true)\n    {\n        static struct option longOptions[] =\n        {\n            {\"help\", no_argument, 0, '?'},\n            {\"help\", no_argument, 0, 'h'},\n            {\"ini_file\", required_argument, 0, 'i'},\n            {\"section\", required_argument, 0, 's'},\n            {0, 0, 0, 0}\n        };\n        int c, optionIndex;\n        c = getopt_long(argc, argv, \"?hi:s:\",\n                        longOptions, &optionIndex);\n        if (c ==-1){break;}\n        if (c == 'i')\n        {\n            strcpy(iniFile, (const char *) optarg);\n            linFile = true;\n        }\n        else if (c == 's')\n        {\n            strcpy(section, (const char *) optarg);\n            lsection = true;\n        }\n        else if (c == 'h' || c == '?')\n        {\n            printUsage();\n            return -2;\n        }\n        else\n        {\n            printf(\"%s: Unknown options: %s\\n\",\n                   PROGRAM_NAME, argv[optionIndex]);\n        }\n    }\n    if (!linFile)\n    {\n        printf(\"%s: Error must specify ini file\\n\\n\", PROGRAM_NAME);\n        printUsage();\n        return -1;\n    }\n    else\n    {\n        if (!os_path_isfile(iniFile))\n        {\n            printf(\"%s: Error - ini file: %s does not exist\\n\",\n                   PROGRAM_NAME, iniFile);\n            return EXIT_FAILURE;\n        }\n    }\n    if (!lsection){strcpy(section, \"prepmt:telePGrns\\0\");}\n    return 0;\n}\n//============================================================================//\nstatic void printUsage(void)\n{\n    printf(\"Usage:\\n   %s -i ini_file\\n\\n\", PROGRAM_NAME);\n    printf(\"Required arguments:\\n\");\n    printf(\"    -i ini_file specifies the initialization file\\n\");\n    printf(\"\\n\");\n    printf(\"Optional arguments:\\n\");\n    printf(\"    -h displays this message\\n\");\n    printf(\"    -s section of ini file to read\\n\");\n    return;\n}\n", "meta": {"hexsha": "06d1d5c5af8518df9d0acc4b5c4e2973b8c7f5b9", "size": 43121, "ext": "c", "lang": "C", "max_stars_repo_path": "prepmt/grnsTeleB.c", "max_stars_repo_name": "bakerb845/parmt", "max_stars_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_stars_repo_licenses": ["Intel"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "prepmt/grnsTeleB.c", "max_issues_repo_name": "bakerb845/parmt", "max_issues_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_issues_repo_licenses": ["Intel"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "prepmt/grnsTeleB.c", "max_forks_repo_name": "bakerb845/parmt", "max_forks_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_forks_repo_licenses": ["Intel"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.0255731922, "max_line_length": 82, "alphanum_fraction": 0.4891584147, "num_tokens": 10240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39981165504266236, "lm_q2_score": 0.02635535102983882, "lm_q1q2_score": 0.010537176514470194}}
{"text": "//**************************************************************************\\\n//* This file is property of and copyright by the ALICE Project            *\\\n//* ALICE Experiment at CERN, All rights reserved.                         *\\\n//*                                                                        *\\\n//* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no>        *\\\n//*                  for The ALICE HLT Project.                            *\\\n//*                                                                        *\\\n//* Permission to use, copy, modify and distribute this software and its   *\\\n//* documentation strictly for non-commercial purposes is hereby granted   *\\\n//* without fee, provided that the above copyright notice appears in all   *\\\n//* copies and that both the copyright notice and this permission notice   *\\\n//* appear in the supporting documentation. The authors make no claims     *\\\n//* about the suitability of this software for any purpose. It is          *\\\n//* provided \"as is\" without express or implied warranty.                  *\\\n//**************************************************************************\n\n/// \\file GPUQA.h\n/// \\author David Rohr\n\n#ifndef GPUQA_H\n#define GPUQA_H\n\n#include \"GPUQAConfig.h\"\nstruct AliHLTTPCClusterMCWeight;\nclass TH1F;\nclass TH2F;\nclass TCanvas;\nclass TPad;\nclass TLegend;\nclass TPad;\nclass TH1;\nclass TFile;\nclass TH1D;\ntypedef short int Color_t;\n\n#if !defined(GPUCA_BUILD_QA) || defined(GPUCA_GPUCODE)\n\nnamespace GPUCA_NAMESPACE\n{\nnamespace gpu\n{\nclass GPUChainTracking;\n\nclass GPUQA\n{\n public:\n  GPUQA(GPUChainTracking* rec) {}\n  ~GPUQA() = default;\n\n  typedef structConfigQA configQA;\n\n  int InitQA() { return 1; }\n  void RunQA(bool matchOnly = false) {}\n  int DrawQAHistograms() { return 1; }\n  void SetMCTrackRange(int min, int max) {}\n  bool SuppressTrack(int iTrack) const { return false; }\n  bool SuppressHit(int iHit) const { return false; }\n  bool HitAttachStatus(int iHit) const { return false; }\n  int GetMCTrackLabel(unsigned int trackId) const { return -1; }\n  bool clusterRemovable(int cid, bool prot) const { return false; }\n  static bool QAAvailable() { return false; }\n};\n} // namespace gpu\n} // namespace GPUCA_NAMESPACE\n\n#else\n\n#include \"GPUTPCDef.h\"\n#include <cmath>\n\n#ifdef GPUCA_TPC_GEOMETRY_O2\n#include <gsl/span>\n#endif\n\nnamespace o2\n{\nclass MCCompLabel;\n}\n\nclass AliHLTTPCClusterMCLabel;\n\nnamespace GPUCA_NAMESPACE\n{\nnamespace gpu\n{\nclass GPUChainTracking;\nclass GPUTPCMCInfo;\n\nclass GPUQA\n{\n public:\n  GPUQA(GPUChainTracking* rec);\n  ~GPUQA();\n\n  typedef GPUQAConfig configQA;\n\n  int InitQA();\n  void RunQA(bool matchOnly = false);\n  int DrawQAHistograms();\n  void SetMCTrackRange(int min, int max);\n  bool SuppressTrack(int iTrack) const;\n  bool SuppressHit(int iHit) const;\n  bool HitAttachStatus(int iHit) const;\n  int GetMCTrackLabel(unsigned int trackId) const;\n  bool clusterRemovable(int cid, bool prot) const;\n  static bool QAAvailable() { return true; }\n\n private:\n  struct additionalMCParameters {\n    float pt, phi, theta, eta, nWeightCls;\n  };\n\n  struct additionalClusterParameters {\n    int attached, fakeAttached, adjacent, fakeAdjacent;\n    float pt;\n  };\n\n  void SetAxisSize(TH1F* e);\n  void SetLegend(TLegend* l);\n  double* CreateLogAxis(int nbins, float xmin, float xmax);\n  void ChangePadTitleSize(TPad* p, float size);\n  void DrawHisto(TH1* histo, char* filename, char* options);\n  void doPerfFigure(float x, float y, float size);\n  void GetName(char* fname, int k);\n  template <class T>\n  T* GetHist(T*& ee, std::vector<TFile*>& tin, int k, int nNewInput);\n\n#ifdef GPUCA_TPC_GEOMETRY_O2\n  using mcLabels_t = gsl::span<const o2::MCCompLabel>;\n  using mcLabel_t = o2::MCCompLabel;\n  using mcLabelI_t = mcLabel_t;\n  using mcInfo_t = GPUTPCMCInfo;\n  mcLabels_t GetMCLabel(unsigned int i);\n  mcLabel_t GetMCLabel(unsigned int i, unsigned int j);\n#else\n  using mcLabels_t = AliHLTTPCClusterMCLabel;\n  using mcLabel_t = AliHLTTPCClusterMCWeight;\n  struct mcLabelI_t {\n    int getTrackID() const { return AbsLabelID(track); }\n    int getEventID() const { return 0; }\n    bool isFake() const { return track < 0; }\n    bool isValid() const { return track != MC_LABEL_INVALID; }\n    void invalidate() { track = MC_LABEL_INVALID; }\n    void setFakeFlag(bool v = true) { track = v ? FakeLabelID(track) : AbsLabelID(track); }\n    void setNoise() { track = MC_LABEL_INVALID; }\n    bool operator==(const mcLabel_t& l);\n    bool operator!=(const mcLabel_t& l) { return !(*this == l); }\n    mcLabelI_t() = default;\n    mcLabelI_t(const mcLabel_t& l);\n    int track = MC_LABEL_INVALID;\n  };\n  using mcInfo_t = GPUTPCMCInfo;\n  const mcLabels_t& GetMCLabel(unsigned int i);\n  const mcLabel_t& GetMCLabel(unsigned int i, unsigned int j);\n  const mcInfo_t& GetMCTrack(const mcLabelI_t& label);\n  static int FakeLabelID(const int id);\n  static int AbsLabelID(const int id);\n#endif\n  template <class T>\n  static auto& GetMCTrackObj(T& obj, const mcLabelI_t& l);\n\n  unsigned int GetNMCCollissions();\n  unsigned int GetNMCTracks(int iCol);\n  unsigned int GetNMCLabels();\n  const mcInfo_t& GetMCTrack(unsigned int iTrk, unsigned int iCol);\n  const mcInfo_t& GetMCTrack(const mcLabel_t& label);\n  int GetMCLabelNID(const mcLabels_t& label);\n  int GetMCLabelNID(unsigned int i);\n  int GetMCLabelID(unsigned int i, unsigned int j);\n  int GetMCLabelCol(unsigned int i, unsigned int j);\n  static int GetMCLabelID(const mcLabels_t& label, unsigned int j);\n  static int GetMCLabelID(const mcLabel_t& label);\n  float GetMCLabelWeight(unsigned int i, unsigned int j);\n  float GetMCLabelWeight(const mcLabels_t& label, unsigned int j);\n  float GetMCLabelWeight(const mcLabel_t& label);\n  bool mcPresent();\n\n  static bool MCComp(const mcLabel_t& a, const mcLabel_t& b);\n\n  GPUChainTracking* mTracking;\n  const configQA& mConfig;\n\n  //-------------------------: Some compile time settings....\n  static const constexpr bool PLOT_ROOT = 0;\n  static const constexpr bool FIX_SCALES = 0;\n  static const constexpr bool PERF_FIGURE = 0;\n  static const constexpr float FIXED_SCALES_MIN[5] = {-0.05, -0.05, -0.2, -0.2, -0.5};\n  static const constexpr float FIXED_SCALES_MAX[5] = {0.4, 0.7, 5, 3, 6.5};\n  static const constexpr float LOG_PT_MIN = -1.;\n\n  const char* str_perf_figure_1 = \"ALICE Performance 2018/03/20\";\n  // const char* str_perf_figure_2 = \"2015, MC pp, #sqrt{s} = 5.02 TeV\";\n  const char* str_perf_figure_2 = \"2015, MC Pb-Pb, #sqrt{s_{NN}} = 5.02 TeV\";\n  //-------------------------\n\n  std::vector<mcLabelI_t> mTrackMCLabels;\n#ifdef GPUCA_TPC_GEOMETRY_O2\n  std::vector<std::vector<int>> mTrackMCLabelsReverse;\n  std::vector<std::vector<int>> mRecTracks;\n  std::vector<std::vector<int>> mFakeTracks;\n  std::vector<std::vector<additionalMCParameters>> mMCParam;\n  std::vector<std::vector<mcInfo_t>> mMCInfos;\n  std::vector<int> mNColTracks;\n#else\n  std::vector<int> mTrackMCLabelsReverse[1];\n  std::vector<int> mRecTracks[1];\n  std::vector<int> mFakeTracks[1];\n  std::vector<additionalMCParameters> mMCParam[1];\n#endif\n  std::vector<additionalClusterParameters> mClusterParam;\n  int mNTotalFakes = 0;\n\n  TH1F* mEff[4][2][2][5][2]; // eff,clone,fake,all - findable - secondaries - y,z,phi,eta,pt - work,result\n  TCanvas* mCEff[6];\n  TPad* mPEff[6][4];\n  TLegend* mLEff[6];\n\n  TH1F* mRes[5][5][2]; // y,z,phi,lambda,pt,ptlog res - param - res,mean\n  TH2F* mRes2[5][5];\n  TCanvas* mCRes[7];\n  TPad* mPRes[7][5];\n  TLegend* mLRes[6];\n\n  TH1F* mPull[5][5][2]; // y,z,phi,lambda,pt,ptlog res - param - res,mean\n  TH2F* mPull2[5][5];\n  TCanvas* mCPull[7];\n  TPad* mPPull[7][5];\n  TLegend* mLPull[6];\n\n  static constexpr int N_CLS_HIST = 8;\n  static constexpr int N_CLS_TYPE = 3;\n  enum CL_types { CL_attached = 0,\n                  CL_fake = 1,\n                  CL_att_adj = 2,\n                  CL_fakeAdj = 3,\n                  CL_tracks = 4,\n                  CL_physics = 5,\n                  CL_prot = 6,\n                  CL_all = 7 };\n  TH1D* mClusters[N_CLS_TYPE * N_CLS_HIST - 1]; // attached, fakeAttached, attach+adjacent, fakeAdjacent, physics, protected, tracks, all / count, rel, integral\n  TCanvas* mCClust[N_CLS_TYPE];\n  TPad* mPClust[N_CLS_TYPE];\n  TLegend* mLClust[N_CLS_TYPE];\n\n  long long int mNRecClustersRejected = 0, mNRecClustersTube = 0, mNRecClustersTube200 = 0, mNRecClustersLoopers = 0, mNRecClustersLowPt = 0, mNRecClusters200MeV = 0, mNRecClustersPhysics = 0, mNRecClustersProt = 0, mNRecClustersUnattached = 0, mNRecClustersTotal = 0, mNRecClustersHighIncl = 0,\n                mNRecClustersAbove400 = 0, mNRecClustersFakeRemove400 = 0, mNRecClustersFullFakeRemove400 = 0, mNRecClustersBelow40 = 0, mNRecClustersFakeProtect40 = 0;\n  double mNRecClustersUnaccessible = 0;\n\n  TH1F* mTracks;\n  TCanvas* mCTracks;\n  TPad* mPTracks;\n  TLegend* mLTracks;\n\n  TH1F* mNCl;\n  TCanvas* mCNCl;\n  TPad* mPNCl;\n  TLegend* mLNCl;\n\n  int mNEvents = 0;\n  bool mQAInitialized = false;\n  std::vector<std::vector<int>> mcEffBuffer;\n  std::vector<std::vector<int>> mcLabelBuffer;\n  std::vector<std::vector<bool>> mGoodTracks;\n  std::vector<std::vector<bool>> mGoodHits;\n\n  static constexpr float Y_MAX = 40;\n  static constexpr float Z_MAX = 100;\n  static constexpr float PT_MIN = GPUCA_MIN_TRACK_PT_DEFAULT;\n  static constexpr float PT_MIN2 = 0.1;\n  static constexpr float PT_MIN_PRIM = 0.1;\n  static constexpr float PT_MIN_CLUST = GPUCA_MIN_TRACK_PT_DEFAULT;\n  static constexpr float PT_MAX = 20;\n  static constexpr float ETA_MAX = 1.5;\n  static constexpr float ETA_MAX2 = 0.9;\n\n  static constexpr float MIN_WEIGHT_CLS = 40;\n  static constexpr float FINDABLE_WEIGHT_CLS = 70;\n\n  static constexpr int MC_LABEL_INVALID = -1e9;\n\n  static constexpr bool CLUST_HIST_INT_SUM = false;\n\n  static constexpr const int COLORCOUNT = 12;\n  Color_t* mColorNums;\n\n  static const constexpr char* EFF_TYPES[4] = {\"Rec\", \"Clone\", \"Fake\", \"All\"};\n  static const constexpr char* FINDABLE_NAMES[2] = {\"\", \"Findable\"};\n  static const constexpr char* PRIM_NAMES[2] = {\"Prim\", \"Sec\"};\n  static const constexpr char* PARAMETER_NAMES[5] = {\"Y\", \"Z\", \"#Phi\", \"#lambda\", \"Relative #it{p}_{T}\"};\n  static const constexpr char* PARAMETER_NAMES_NATIVE[5] = {\"Y\", \"Z\", \"sin(#Phi)\", \"tan(#lambda)\", \"q/#it{p}_{T} (curvature)\"};\n  static const constexpr char* VSPARAMETER_NAMES[6] = {\"Y\", \"Z\", \"Phi\", \"Eta\", \"Pt\", \"Pt_log\"};\n  static const constexpr char* EFF_NAMES[3] = {\"Efficiency\", \"Clone Rate\", \"Fake Rate\"};\n  static const constexpr char* EFFICIENCY_TITLES[4] = {\"Efficiency (Primary Tracks, Findable)\", \"Efficiency (Secondary Tracks, Findable)\", \"Efficiency (Primary Tracks)\", \"Efficiency (Secondary Tracks)\"};\n  static const constexpr double SCALE[5] = {10., 10., 1000., 1000., 100.};\n  static const constexpr double SCALE_NATIVE[5] = {10., 10., 1000., 1000., 1.};\n  static const constexpr char* XAXIS_TITLES[5] = {\"#it{y}_{mc} (cm)\", \"#it{z}_{mc} (cm)\", \"#Phi_{mc} (rad)\", \"#eta_{mc}\", \"#it{p}_{Tmc} (GeV/#it{c})\"};\n  static const constexpr char* AXIS_TITLES[5] = {\"#it{y}-#it{y}_{mc} (mm) (Resolution)\", \"#it{z}-#it{z}_{mc} (mm) (Resolution)\", \"#phi-#phi_{mc} (mrad) (Resolution)\", \"#lambda-#lambda_{mc} (mrad) (Resolution)\", \"(#it{p}_{T} - #it{p}_{Tmc}) / #it{p}_{Tmc} (%) (Resolution)\"};\n  static const constexpr char* AXIS_TITLES_NATIVE[5] = {\"#it{y}-#it{y}_{mc} (mm) (Resolution)\", \"#it{z}-#it{z}_{mc} (mm) (Resolution)\", \"sin(#phi)-sin(#phi_{mc}) (Resolution)\", \"tan(#lambda)-tan(#lambda_{mc}) (Resolution)\", \"q*(q/#it{p}_{T} - q/#it{p}_{Tmc}) (Resolution)\"};\n  static const constexpr char* AXIS_TITLES_PULL[5] = {\"#it{y}-#it{y}_{mc}/#sigma_{y} (Pull)\", \"#it{z}-#it{z}_{mc}/#sigma_{z} (Pull)\", \"sin(#phi)-sin(#phi_{mc})/#sigma_{sin(#phi)} (Pull)\", \"tan(#lambda)-tan(#lambda_{mc})/#sigma_{tan(#lambda)} (Pull)\",\n                                                      \"q*(q/#it{p}_{T} - q/#it{p}_{Tmc})/#sigma_{q/#it{p}_{T}} (Pull)\"};\n  static const constexpr char* CLUSTER_NAMES[N_CLS_HIST] = {\"Correctly attached clusters\", \"Fake attached clusters\", \"Attached + adjacent clusters\", \"Fake adjacent clusters\", \"Clusters of reconstructed tracks\", \"Used in Physics\", \"Protected\", \"All clusters\"};\n  static const constexpr char* CLUSTER_TITLES[N_CLS_TYPE] = {\"Clusters Pt Distribution / Attachment\", \"Clusters Pt Distribution / Attachment (relative to all clusters)\", \"Clusters Pt Distribution / Attachment (integrated)\"};\n  static const constexpr char* CLUSTER_NAMES_SHORT[N_CLS_HIST] = {\"Attached\", \"Fake\", \"AttachAdjacent\", \"FakeAdjacent\", \"FoundTracks\", \"Physics\", \"Protected\", \"All\"};\n  static const constexpr char* CLUSTER_TYPES[N_CLS_TYPE] = {\"\", \"Ratio\", \"Integral\"};\n  static const constexpr int COLORS_HEX[COLORCOUNT] = {0xB03030, 0x00A000, 0x0000C0, 0x9400D3, 0x19BBBF, 0xF25900, 0x7F7F7F, 0xFFD700, 0x07F707, 0x07F7F7, 0xF08080, 0x000000};\n\n  static const constexpr int CONFIG_DASHED_MARKERS = 0;\n\n  static const constexpr float AXES_MIN[5] = {-Y_MAX, -Z_MAX, 0.f, -ETA_MAX, PT_MIN};\n  static const constexpr float AXES_MAX[5] = {Y_MAX, Z_MAX, 2.f * M_PI, ETA_MAX, PT_MAX};\n  static const constexpr int AXIS_BINS[5] = {51, 51, 144, 31, 50};\n  static const constexpr int RES_AXIS_BINS[] = {1017, 113}; // Consecutive bin sizes, histograms are binned down until the maximum entry is 50, each bin size should evenly divide its predecessor.\n  static const constexpr float RES_AXES[5] = {1., 1., 0.03, 0.03, 1.0};\n  static const constexpr float RES_AXES_NATIVE[5] = {1., 1., 0.1, 0.1, 5.0};\n  static const constexpr float PULL_AXIS = 10.f;\n\n  int mMCTrackMin = -1, mMCTrackMax = -1;\n};\n\ninline bool GPUQA::SuppressTrack(int iTrack) const { return (mConfig.matchMCLabels.size() && !mGoodTracks[mNEvents][iTrack]); }\ninline bool GPUQA::SuppressHit(int iHit) const { return (mConfig.matchMCLabels.size() && !mGoodHits[mNEvents - 1][iHit]); }\ninline bool GPUQA::HitAttachStatus(int iHit) const { return (mClusterParam.size() && mClusterParam[iHit].fakeAttached ? (mClusterParam[iHit].attached ? 1 : 2) : 0); }\n\n} // namespace gpu\n} // namespace GPUCA_NAMESPACE\n\n#endif\n#endif\n", "meta": {"hexsha": "851c2c184bb9931083de09b7087cd6b7975626a9", "size": 13970, "ext": "h", "lang": "C", "max_stars_repo_path": "GPU/GPUTracking/Standalone/qa/GPUQA.h", "max_stars_repo_name": "mpoghos/AliRoot", "max_stars_repo_head_hexsha": "e81490f640ad6f2a6189f679de96b07a94304b58", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GPU/GPUTracking/Standalone/qa/GPUQA.h", "max_issues_repo_name": "mpoghos/AliRoot", "max_issues_repo_head_hexsha": "e81490f640ad6f2a6189f679de96b07a94304b58", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GPU/GPUTracking/Standalone/qa/GPUQA.h", "max_forks_repo_name": "mpoghos/AliRoot", "max_forks_repo_head_hexsha": "e81490f640ad6f2a6189f679de96b07a94304b58", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.462006079, "max_line_length": 295, "alphanum_fraction": 0.675948461, "num_tokens": 4221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23934933647101647, "lm_q2_score": 0.04401864735472289, "lm_q1q2_score": 0.010535834036704588}}
{"text": "#include <string.h>\n#include <alloca.h>\n#include <math.h>\n#include <mpi.h>\n\n#include <kdcount/kdtree.h>\n\n#include <fastpm/libfastpm.h>\n#include <gsl/gsl_rng.h>\n\n#include <fastpm/prof.h>\n#include <fastpm/logging.h>\n#include <fastpm/store.h>\n\n#include <fastpm/fof.h>\n\n#include \"pmpfft.h\"\n#include \"pm2lpt.h\"\n#include \"pmghosts.h\"\n#include \"vpm.h\"\n\n#include <fastpm/io.h>\n#include <fastpm/string.h>\n#include <bigfile-mpi.h>\n\n//#define FASTPM_FOF_DEBUG\n\nstruct FastPMFOFFinderPrivate {\n    int ThisTask;\n    int NTask;\n    double * boxsize;\n    MPI_Comm comm;\n};\n\n/* creating a kdtree struct\n * for store with np particles starting from start.\n * */\nstruct KDTreeNodeBuffer {\n    void * mem;\n    void * base;\n    char * ptr;\n    char * end;\n    struct KDTreeNodeBuffer * prev;\n};\n\n\nstatic void *\n_kdtree_buffered_malloc(void * userdata, size_t size)\n{\n    struct KDTreeNodeBuffer ** pbuffer = (struct KDTreeNodeBuffer**) userdata;\n\n    struct KDTreeNodeBuffer * buffer = *pbuffer;\n\n    if(buffer->base == NULL || buffer->ptr + size >= buffer->end) {\n        struct KDTreeNodeBuffer * newbuffer = malloc(sizeof(newbuffer[0]));\n        newbuffer->mem = buffer->mem;\n        size_t newsize = 1024 * 1024 * 4; /* 4 MB for each block */\n        if(newsize < size) {\n            newsize = size;\n        }\n        newbuffer->base = fastpm_memory_alloc(buffer->mem, \"KDTreeBase\", newsize, FASTPM_MEMORY_STACK);\n        newbuffer->ptr = newbuffer->base;\n        newbuffer->end = newbuffer->base + newsize;\n        newbuffer->prev = buffer;\n\n        *pbuffer = newbuffer;\n        buffer = newbuffer;\n    }\n\n    void * r = buffer->ptr;\n    buffer->ptr += size;\n    return r;\n}\n\nstatic void\n_kdtree_buffered_free(void * userdata, size_t size, void * ptr)\n{\n    /* do nothing; */\n}\n\nstatic \nKDNode *\n_create_kdtree (KDTree * tree, int thresh,\n    FastPMStore ** stores, int nstore,\n    double boxsize[])\n{\n    /* if boxsize is NULL the tree will be non-periodic. */\n    /* the allocator; started empty. */\n    struct KDTreeNodeBuffer ** pbuffer = malloc(sizeof(void*));\n    struct KDTreeNodeBuffer * headbuffer = malloc(sizeof(headbuffer[0]));\n    *pbuffer = headbuffer;\n\n    headbuffer->mem = stores[0]->mem;\n    headbuffer->base = NULL;\n    headbuffer->prev = NULL;\n\n    int s;\n    ptrdiff_t i;\n\n    tree->userdata = pbuffer;\n\n    tree->input.dims[0] = 0;\n\n    for(s = 0; s < nstore; s ++) {\n        tree->input.dims[0] += stores[s]->np;\n    }\n\n    tree->input.dims[1] = 3;\n\n    if(tree->input.dims[0] < stores[0]->np_upper) {\n        /* if the first store is big enough, use it for the tree */\n        tree->input.buffer = (void*) &stores[0]->x[0][0];\n    } else {\n        /* otherwise, allocate a big buffer and make a copy */\n        tree->input.buffer = _kdtree_buffered_malloc(pbuffer,\n                    tree->input.dims[0] * sizeof(stores[0]->x[0]));\n        memcpy(tree->input.buffer, &stores[0]->x[0][0], stores[0]->np * sizeof(stores[0]->x[0]));\n    }\n\n    i = stores[0]->np;\n\n    /* copy the other positions to the base pointer. */\n    for(s = 1; s < nstore; s ++) {\n        memcpy(((char*) tree->input.buffer) + i * sizeof(stores[0]->x[0]),\n                &stores[s]->x[0][0],\n                stores[s]->np * sizeof(stores[0]->x[0]));\n\n        i = i + stores[s]->np;\n    }\n\n    tree->input.strides[0] = sizeof(stores[0]->x[0]);\n    tree->input.strides[1] = sizeof(stores[0]->x[0][0]);\n    tree->input.elsize = sizeof(stores[0]->x[0][0]);\n    tree->input.cast = NULL;\n\n    tree->ind = _kdtree_buffered_malloc(pbuffer, tree->input.dims[0] * sizeof(tree->ind[0]));\n    for(i = 0; i < tree->input.dims[0]; i ++) {\n        tree->ind[i] = i;\n    }\n    tree->ind_size = tree->input.dims[0];\n\n    tree->malloc = _kdtree_buffered_malloc;\n    tree->free = _kdtree_buffered_free;\n\n    tree->thresh = thresh;\n\n    tree->boxsize = boxsize;\n\n    KDNode * root = kd_build(tree);\n    fastpm_info(\"Creating KDTree with %td nodes for %td particles\\n\", tree->size, tree->ind_size);\n    return root;\n}\n\nvoid \n_free_kdtree (KDTree * tree, KDNode * root)\n{\n    kd_free(root);\n    struct KDTreeNodeBuffer * buffer, *q, **pbuffer = tree->userdata;\n\n    for(buffer = *pbuffer; buffer; buffer = q) {\n        if(buffer->base)\n            fastpm_memory_free(buffer->mem, buffer->base);\n        q = buffer->prev;\n        free(buffer);\n    }\n    free(pbuffer);\n}\n\nvoid\nfastpm_fof_init(FastPMFOFFinder * finder, FastPMStore * store, PM * pm)\n{\n    finder->priv = malloc(sizeof(FastPMFOFFinderPrivate));\n    finder->p = store;\n    finder->pm = pm;\n\n    finder->event_handlers = NULL;\n\n    if (finder->periodic)\n        finder->priv->boxsize = pm_boxsize(pm);\n    else\n        finder->priv->boxsize = NULL;\n\n    finder->priv->comm = pm_comm(pm);\n    MPI_Comm comm = finder->priv->comm;\n    MPI_Comm_rank(comm, &finder->priv->ThisTask);\n    MPI_Comm_size(comm, &finder->priv->NTask);\n}\n\nstatic void\n_fof_local_find(FastPMFOFFinder * finder,\n            FastPMStore * p,\n            PMGhostData * pgd,\n            ptrdiff_t * head, double linkinglength)\n{\n    /* local find of p and the the ghosts */\n    KDTree tree;\n\n    FastPMStore * stores[2] = {p, pgd->p};\n\n    KDNode * root = _create_kdtree(&tree, finder->kdtree_thresh, stores, 2, finder->priv->boxsize);\n\n    kd_fof(root, linkinglength, head);\n\n    _free_kdtree(&tree, root);\n}\n\nstatic int\n_merge(uint64_t * src, ptrdiff_t isrc, uint64_t * dest, ptrdiff_t idest, ptrdiff_t * head)\n{\n    int merge = 0;\n    ptrdiff_t j = head[idest];\n    if(src[isrc] < dest[j]) {\n        merge = 1;\n    }\n\n    if(merge) {\n        dest[j] = src[isrc];\n    }\n    return merge;\n}\n\nstruct reduce_fof_data {\n    ptrdiff_t * head;\n    size_t nmerged;\n};\n\nstatic void\nFastPMReduceFOF(FastPMStore * src, ptrdiff_t isrc, FastPMStore * dest, ptrdiff_t idest, int ci, void * userdata)\n{\n\n    struct reduce_fof_data * data = userdata;\n\n    data->nmerged += _merge(src->minid, isrc, dest->minid, idest, data->head);\n}\n\n\nstatic void\n_fof_global_merge(\n    FastPMFOFFinder * finder,\n    FastPMStore * p,\n    PMGhostData * pgd,\n    uint64_t * minid,\n    ptrdiff_t * head\n)\n{\n    ptrdiff_t i;\n\n    MPI_Comm comm = finder->priv->comm;\n\n    size_t npmax = p->np;\n\n    MPI_Allreduce(MPI_IN_PLACE, &npmax, 1, MPI_LONG, MPI_MAX, comm);\n\n    /* initialize minid, used as a global tag of groups as we merge */\n    for(i = 0; i < p->np; i ++) {\n        /* assign unique ID to each particle; could use a better scheme with true offsets */\n        minid[i] = i + finder->priv->ThisTask * npmax;\n        #ifdef FASTPM_FOF_DEBUG\n        /* for debugging, overwrite the previous unique ID with the true ID of particles */\n        minid[i] = p->id[i];\n        #endif\n    }\n\n    /* send minid */\n    p->minid = minid; /* only send up to p->np */\n    pm_ghosts_send(pgd, COLUMN_MINID);\n    p->minid = NULL;\n\n    /* copy over to minid for storage; FIXME: allow overriding  */\n    for(i = 0; i < pgd->p->np; i ++) {\n        minid[i + p->np] = pgd->p->minid[i];\n    }\n\n    /* reduce the minid of the head items according to the local connection. */\n\n    while(1) {\n        size_t nmerge = 0;\n        for(i = 0; i < p->np + pgd->p->np; i ++) {\n            nmerge += _merge(minid, i, minid, i, head);\n        }\n        if(nmerge == 0) break;\n    }\n\n#ifdef FASTPM_FOF_DEBUG\n    {\n        FILE * fp = fopen(fastpm_strdup_printf(\"dump-pos-%d.f8\", finder->priv->ThisTask), \"w\");\n        fwrite(p->x, p->np, sizeof(double) * 3, fp);\n        fwrite(pgd->p->x, pgd->p->np, sizeof(double) * 3, fp);\n        fclose(fp);\n    }\n    {\n        FILE * fp = fopen(fastpm_strdup_printf(\"dump-id-%d.f8\", finder->priv->ThisTask), \"w\");\n        fwrite(p->id, p->np, sizeof(int64_t), fp);\n        fwrite(pgd->p->id, pgd->p->np, sizeof(int64_t) * 3, fp);\n        fclose(fp);\n    }\n\n#endif\n    int iter = 0;\n\n    while(1) {\n\n        /* prepare the communication buffer, every ghost has\n         * the minid and task of the current head. such that\n         * they will connect to the other ranks correctly */\n\n        for(i = 0; i < pgd->p->np; i ++) {\n            pgd->p->minid[i] = minid[head[i + p->np]];\n        }\n\n        /* at this point all items on ghosts have local minid and task, ready to reduce */\n\n        struct reduce_fof_data data = {\n            .head = head,\n            .nmerged = 0,\n        };\n\n        /* merge ghosts into the p, reducing the MINID on p */\n\n        p->minid = minid; /* only update up to p->np */\n        pm_ghosts_reduce(pgd, COLUMN_MINID, FastPMReduceFOF, &data);\n        p->minid = NULL;\n\n        size_t nmerged = data.nmerged;\n\n        /* at this point all items on p->fof with head[i] = i have present minid and task */\n\n        MPI_Allreduce(MPI_IN_PLACE, &nmerged, 1, MPI_LONG, MPI_SUM, comm);\n\n        MPI_Barrier(comm);\n\n        fastpm_info(\"FOF reduction iteration %d : merged %td crosslinks\\n\", iter, nmerged);\n\n        if(nmerged == 0) break;\n\n        for(i = 0; i < p->np + pgd->p->np; i ++) {\n            if(minid[i] < minid[head[i]]) {\n                fastpm_raise(-1, \"p->fof invariance is broken i = %td np = %td\\n\", i, p->np);\n            }\n        }\n\n        iter++;\n    }\n\n    /* previous loop only updated head[i]; now make sure every particles has the correct minid. */\n    for(i = 0; i < p->np + pgd->p->np; i ++) {\n        minid[i] = minid[head[i]];\n    }\n\n    #ifdef FASTPM_FOF_DEBUG\n    {\n    for(i = 0; i < p->np + pgd->p->np ; i ++) {\n        uint64_t id = i <p->np?p->id[i]:pgd->p->id[i - p->np];\n        if(minid[i] == 88) {\n            fastpm_ilog(INFO, \"%d MINID == %ld ID = %ld headminid == %ld i = %td / %td head=%td\", finder->priv->ThisTask,\n                minid[i], id, minid[head[i]], i, p->np, head[i]);\n        }\n        if(id == 88 || id == 96 || id == 152 || id == 160) {\n            fastpm_ilog(INFO, \"%d MINID == %ld ID = %ld headminid == %ld i = %td / %td head=%td\", finder->priv->ThisTask,\n                minid[i], id, minid[head[i]], i, p->np, head[i]);\n        }\n    }\n    }\n    #endif\n}\n\n/* set head[i] to hid*/\nstatic size_t\n_assign_halo_attr(FastPMFOFFinder * finder, PMGhostData * pgd, ptrdiff_t * head, size_t np, size_t np_ghosts, int nmin)\n{\n    ptrdiff_t * offset = fastpm_memory_alloc(finder->p->mem, \"FOFOffset\", sizeof(offset[0]) * (np + np_ghosts), FASTPM_MEMORY_STACK);\n    uint8_t * has_remote = fastpm_memory_alloc(finder->p->mem, \"FOFHasRemote\", sizeof(has_remote[0]) * (np + np_ghosts), FASTPM_MEMORY_STACK);\n    uint8_t * has_local = fastpm_memory_alloc(finder->p->mem, \"FOFHasLocal\", sizeof(has_local[0]) * (np + np_ghosts), FASTPM_MEMORY_STACK);\n\n    ptrdiff_t i;\n    for(i = 0; i < np + np_ghosts; i ++) {\n        offset[i] = 0;\n        has_remote[i] = 0;\n        has_local[i] = 0;\n    }\n\n    /* set offset to number of particles in the halo */\n    for(i = 0; i < np + np_ghosts; i ++) {\n        offset[head[i]] ++;\n    }\n\n    for(i = 0; i < np; i ++) {\n        has_local[head[i]] = 1;\n    }\n\n    /* if the group is connected to a remote component */\n    /* if the particle has a ghost, then */\n    pm_ghosts_has_ghosts(pgd, has_remote);\n\n    /* if connected to a particle that has ghost */\n    for(i = 0; i < np; i ++) {\n        if(has_remote[i]) has_remote[head[i]] = 1;\n    }\n\n    /* if connected to a ghost */\n    for(i = np; i < np + np_ghosts; i ++) {\n        has_remote[head[i]] = 1;\n    }\n\n    size_t it = 0;\n\n    /* assign attr index for groups at least contain 1 local particle */\n    for(i = 0; i < np + np_ghosts; i ++) {\n        if(has_local[i] && (has_remote[i] || offset[i] >= nmin)) {\n            offset[i] = it;\n            it ++;\n        } else {\n            offset[i] = -1;\n        }\n    }\n\n    size_t nhalos = it;\n\n    /* update head [i] to offset[head[i]], which stores the index in the halo store for this particle. */\n    for(i = 0; i < np + np_ghosts; i ++) {\n        head[i] = offset[head[i]];\n        /* this will not happen if nmin == 1 */\n        if(head[i] != -1 && head[i] > nhalos) {\n            fastpm_raise(-1, \"head[i] (%td) > nhalos (%td) This shall not happen.\\n\", head[i], nhalos);\n        }\n    }\n\n    fastpm_memory_free(finder->p->mem, has_local);\n    fastpm_memory_free(finder->p->mem, has_remote);\n    fastpm_memory_free(finder->p->mem, offset);\n\n    return it;\n}\nstatic double\nperiodic_add(double x, double wx, double y, double wy, double L)\n{\n    if(wx > 0) {\n        while(y - x > L / 2) y -= L;\n        while(y - x < -L / 2) y += L;\n\n        return wx * x + wy * y;\n    } else {\n        return wy * y;\n    }\n}\n\n/*\n * apply mask to a halo storage.\n * relable head, and halo->id\n * */\nstatic void\nfastpm_fof_subsample(FastPMFOFFinder * finder, FastPMStore * halos, FastPMParticleMaskType * mask, ptrdiff_t * head)\n{\n    /* mapping goes from the old head[i] value to the new head[i] value */\n    ptrdiff_t * mapping = fastpm_memory_alloc(finder->p->mem, \"FOFMapping\", sizeof(mapping[0]) * halos->np, FASTPM_MEMORY_STACK);\n\n    ptrdiff_t i;\n    for(i = 0; i < halos->np; i ++) {\n        mapping[i] = -1;\n        halos->id[i] = i;\n    }\n\n    /* remove non-contributing halo segments */\n    fastpm_store_subsample(halos, mask, halos);\n\n    for(i = 0; i < halos->np; i ++) {\n        mapping[halos->id[i]] = i;\n        halos->id[i] = i;\n    }\n\n    /* adjust head[i] */\n\n    for(i = 0; i < finder->p->np; i ++) {\n        if(head[i] >= 0) {\n            head[i] = mapping[head[i]];\n        }\n    }\n\n    fastpm_memory_free(finder->p->mem, mapping);\n}\n\nstatic void\nfastpm_fof_apply_length_cut(FastPMFOFFinder * finder, FastPMStore * halos, ptrdiff_t * head)\n{\n    MPI_Comm comm = finder->priv->comm;\n\n    FastPMParticleMaskType * mask = fastpm_memory_alloc(finder->p->mem, \"LengthMask\", sizeof(mask[0]) * halos->np, FASTPM_MEMORY_STACK);\n    ptrdiff_t i;\n    for(i = 0; i < halos->np; i ++) {\n        /* remove halos that are shorter than nmin */\n        if(halos->length[i] < finder->nmin) {\n            mask[i] = 0;\n        } else {\n            mask[i] = 1;\n        }\n    }\n    fastpm_fof_subsample(finder, halos, mask, head);\n    fastpm_memory_free(finder->p->mem, mask);\n\n    fastpm_info(\"After length cut we have %td halos (%td including ghost halos).\\n\", \n            fastpm_store_get_mask_sum(halos, comm),\n            fastpm_store_get_np_total(halos, comm));\n}\n\n/* first every undecided halo; then the real halo with particles */\nstatic int\nFastPMLocalSortByMinID(const int i1,\n                    const int i2,\n                    FastPMStore * p)\n{\n    int v1 = (p->minid[i1] < p->minid[i2]);\n    int v2 = (p->minid[i1] > p->minid[i2]);\n\n    return v2 - v1;\n}\n\nstatic int\nFastPMTargetMinID(FastPMStore * store, ptrdiff_t i, void * userdata)\n{\n    FastPMFOFFinder * finder = userdata;\n\n    const uint32_t GOLDEN32 = 2654435761ul;\n    /* const uint64_t GOLDEN64 = 11400714819323198549; */\n    /* may over flow, but should be okay here as the periodicity is ggt NTask */\n    int key = (store->minid[i] * GOLDEN32) % (unsigned) finder->priv->NTask;\n    return key;\n}\n\nstatic int\nFastPMTargetTask(FastPMStore * store, ptrdiff_t i, void * userdata)\n{\n    return store->task[i];\n}\n\n/* for debugging, move particles to a spatially unrelated rank */\nstatic int\nFastPMTargetFOF(FastPMStore * store, ptrdiff_t i, void * userdata)\n{\n#ifdef FASTPM_FOF_DEBUG\n    PM * pm = userdata;\n    int NTask;\n    MPI_Comm_size(pm_comm(pm), &NTask);\n    const uint32_t GOLDEN32 = 2654435761ul;\n    /* const uint64_t GOLDEN64 = 11400714819323198549; */\n    /* may over flow, but should be okay here as the periodicity is ggt NTask */\n    int key = (store->id[i] * GOLDEN32) % (unsigned) NTask;\n    return key;\n#else\n    return FastPMTargetPM(store, i, userdata);\n#endif\n}\n/*\n * This function group halos by halos->minid[i].\n *\n * All halos with the same minid will have the same attribute values afterwards, except\n * a few book keeping items named in this function (see comments inside)\n *\n * */\nstatic void\nfastpm_fof_reduce_halo_attrs(FastPMFOFFinder * finder, FastPMStore * halos,\n        void (* add_func) (FastPMFOFFinder * finder, FastPMStore * halo1, ptrdiff_t i1, FastPMStore * halo2, ptrdiff_t i2 ),\n        void (* reduce_func)(FastPMFOFFinder * finder, FastPMStore * halo1, ptrdiff_t i1)\n)\n{\n\n    ptrdiff_t i;\n\n    ptrdiff_t first = -1;\n    uint64_t lastminid = 0;\n\n    /* ind is the array to use to replicate items */\n    int * ind = fastpm_memory_alloc(finder->p->mem, \"HaloPermutation\", sizeof(ind[0]) * halos->np, FASTPM_MEMORY_STACK);\n\n    /* the following items will have mask[i] == 1, but we will mark some to 0 if\n     * they are not the principle (first) halos segment with this minid */\n    for(i = 0; i < halos->np + 1; i++) {\n        /* we use i == halos->np to terminate the last segment */\n        if(first == -1 || i == halos->np || lastminid != halos->minid[i]) {\n            if (first >= 0) {\n                /* a segment ended */\n                ptrdiff_t j;\n                for(j = first; j < i; j ++) {\n                    ind[j] = first;\n                }\n            }\n            if (i < halos->np) {\n                /* a segment started */\n                halos->mask[i] = 1;\n                lastminid = halos->minid[i];\n            }\n            /* starting a segment of the same halos */\n            first = i;\n        } else {\n            /* inside segment, simply add the ith halo to the first of the segment */\n            halos->mask[i] = 0;\n            add_func(finder, halos, first, halos, i);\n        }\n    }\n\n    /* use permute to replicate the first halo attr to the rest:\n     *\n     * we do not want to replicate\n     * - fof, as fof.task is the original mpi rank of the halo\n     * - id, as it is the original location of the halo on the original mpi rank. \n     * - mask, whether it is primary or not\n     *\n     * we need to replicate because otherwise when we return the head array on the\n     * original ranks will be violated.\n     *   */\n\n    FastPMStore save[1];\n\n    /* FIXME: add a method for this! */\n    memcpy(save->columns, halos->columns, sizeof(save->columns));\n\n    halos->minid = NULL;\n    halos->task = NULL;\n    halos->id = NULL;\n    halos->mask = NULL;\n\n    fastpm_store_permute(halos, ind);\n\n    memcpy(halos->columns, save->columns, sizeof(save->columns));\n\n    for(i = 0; i < halos->np; i++) {\n        reduce_func(finder, halos, i);\n    }\n\n    fastpm_memory_free(finder->p->mem, ind);\n}\n\n\nstatic void\nfastpm_fof_compute_halo_attrs(FastPMFOFFinder * finder, FastPMStore * halos,\n            ptrdiff_t * head,\n            void (*convert_func)(FastPMFOFFinder * finder, FastPMStore * p, ptrdiff_t i, FastPMStore * halos),\n            void (*add_func)(FastPMFOFFinder * finder, FastPMStore * halos, ptrdiff_t i1, FastPMStore * halos2, ptrdiff_t i2),\n            void (*reduce_func)(FastPMFOFFinder * finder, FastPMStore * halos, ptrdiff_t i)\n)\n{\n    MPI_Comm comm = finder->priv->comm;\n\n    FastPMStore h1[1];\n    fastpm_store_init(h1, \"FOF\", 1, halos->attributes, FASTPM_MEMORY_HEAP);\n    ptrdiff_t i;\n\n    for(i = 0; i < finder->p->np; i++) {\n        ptrdiff_t hid = head[i];\n        if(hid < 0) continue;\n\n\n        if(hid >= halos->np) {\n            fastpm_raise(-1, \"halo of a particle out of bounds (%td > %td)\\n\", hid, halos->np);\n        }\n\n        /* initialize h1 with existing halo attributes for this particle */\n        fastpm_store_take(halos, hid, h1, 0);\n\n        convert_func(finder, finder->p, i, h1);\n\n        add_func(finder, halos, hid, h1, 0);\n    }\n\n    fastpm_store_destroy(h1);\n    /* decompose halos by minid (gather); if all halo segments of the same minid are on the same rank, we can combine\n     * these into a single entry, then replicate for each particle to look up;\n     * halo segments that have no local particles are never exchanged to another rank. */\n    if(0 != fastpm_store_decompose(halos,\n            (fastpm_store_target_func) FastPMTargetMinID, finder, comm)) {\n\n        fastpm_raise(-1, \"out of space sending halos by MinID.\\n\");\n    }\n\n    /* now head[i] is no longer the halo attribute of particle i. */\n\n    /* to combine, first local sort by minid; those without local particles are moved to the beginning\n     * so we can easily skip them. */\n    fastpm_store_sort(halos, FastPMLocalSortByMinID);\n\n    /* reduce and update properties */\n    fastpm_fof_reduce_halo_attrs(finder, halos, add_func, reduce_func);\n\n    /* decompose halos by task (return) */\n    if (0 != fastpm_store_decompose(halos,\n            (fastpm_store_target_func) FastPMTargetTask, finder, comm)) {\n        fastpm_raise(-1, \"out of space for gathering halos this shall never happen.\\n\");\n    }\n    /* local sort by id (restore the order) */\n    fastpm_store_sort(halos, FastPMLocalSortByID);\n\n    /* now head[i] is again the halo attribute of particle i. */\n}\n\n/*\n * compute the attrs of the local halo segments based on local particles.\n * head : the hid of each particle; \n * fofsave : the minid of each particle (unique label of each halo)\n *\n * if a halo has no local particles,  halos->mask[i] is set to 0.\n * if a halo has any local particles, and halos->mask[i] is set to 1.\n * */\nstatic void\nfastpm_fof_remove_empty_halos(FastPMFOFFinder * finder, FastPMStore * halos, uint64_t * minid, ptrdiff_t * head)\n{\n\n    /* */\n    ptrdiff_t i;\n\n    /* set minid and task of the halo; all of the halo particles of the same minid needs to be reduced */\n    for(i = 0; i < finder->p->np; i++) {\n        /* set the minid of the halo; need to take care of the ghosts too.\n         * even though we do not add them to the attributes */\n        ptrdiff_t hid = head[i];\n\n        if(hid < 0) continue;\n\n        if(halos->mask[hid] == 0) {\n            /* halo will be reduced by minid */\n            halos->minid[hid] = minid[i];\n            halos->mask[hid] = 1;\n        } else {\n            if(halos->minid[hid] != minid[i]) {\n                fastpm_raise(-1, \"Consistency check failed after FOF global merge.\\n\");\n            }\n        }\n    }\n\n    /* halo will be returned to this task;\n     * we save ThisTask here.*/\n    for(i = 0; i < halos->np; i ++) {\n        halos->task[i] = finder->priv->ThisTask;\n    }\n\n    fastpm_fof_subsample(finder, halos, halos->mask, head);\n}\n\nstatic void\n_add_basic_halo_attrs(FastPMFOFFinder * finder, FastPMStore * halos, ptrdiff_t hid, FastPMStore * h1, ptrdiff_t i)\n{\n    double * boxsize = finder->priv->boxsize;\n\n    if(halos->aemit)\n        halos->aemit[hid] += h1->aemit[i];\n\n    int d;\n\n    for(d = 0; d < 3; d++) {\n        if(halos->v)\n            halos->v[hid][d] += h1->v[i][d];\n        if(halos->dx1)\n            halos->dx1[hid][d] += h1->dx1[i][d];\n        if(halos->dx2)\n            halos->dx2[hid][d] += h1->dx2[i][d];\n    }\n\n    if(halos->x) {\n        for(d = 0; d < 3; d++) {\n            if(boxsize) {\n                halos->x[hid][d] = periodic_add(\n                    halos->x[hid][d] / halos->length[hid], halos->length[hid],\n                    h1->x[i][d] / h1->length[i], h1->length[i], boxsize[d]);\n            } else {\n                halos->x[hid][d] += h1->x[i][d];\n            }\n        }\n    }\n\n    if(halos->q) {\n        for(d = 0; d < 3; d ++) {\n            if (boxsize) {\n                halos->q[hid][d] = periodic_add(\n                    halos->q[hid][d] / halos->length[hid], halos->length[hid],\n                    h1->q[i][d] / h1->length[i], h1->length[i], boxsize[d]);\n            } else {\n                halos->q[hid][d] += h1->q[i][d];\n            }\n        }\n    }\n    /* do this after the loop because x depends on the old length. */\n    halos->length[hid] += h1->length[i];\n}\n\n/* convert a particle to the first halo in the halo store */\nstatic void\n_convert_basic_halo_attrs(FastPMFOFFinder * finder, FastPMStore * p, ptrdiff_t i, FastPMStore * halos)\n{\n    int hid = 0;\n\n    int d;\n\n    double q[3];\n\n    if(halos->q && fastpm_store_has_q(p)) {\n        fastpm_store_get_q_from_id(p, p->id[i], q);\n    }\n    halos->length[hid] = 1;\n\n    for(d = 0; d < 3; d++) {\n        if(halos->x)\n            halos->x[hid][d] = p->x[i][d];\n        if(halos->v)\n            halos->v[hid][d] = p->v[i][d];\n        if(halos->dx1)\n            halos->dx1[hid][d] = p->dx1[i][d];\n        if(halos->dx2)\n            halos->dx2[hid][d] = p->dx2[i][d];\n        if(halos->q && fastpm_store_has_q(p)) {\n            halos->q[hid][d] = q[d];\n        }\n    }\n\n    if(halos->aemit)\n        halos->aemit[hid] = p->aemit[i];\n}\nstatic void\n_reduce_basic_halo_attrs(FastPMFOFFinder * finder, FastPMStore * halos, ptrdiff_t i)\n{\n    int d;\n    double n = halos->length[i];\n\n    for(d = 0; d < 3; d++) {\n        if(halos->x)\n            halos->x[i][d] /= n;\n        if(halos->v)\n            halos->v[i][d] /= n;\n        if(halos->dx1)\n            halos->dx1[i][d] /= n;\n        if(halos->dx2)\n            halos->dx2[i][d] /= n;\n        if(halos->q)\n            halos->q[i][d] /= n;\n    }\n    if(halos->aemit)\n        halos->aemit[i] /= n;\n}\n\nstatic void\n_add_extended_halo_attrs(FastPMFOFFinder * finder, FastPMStore * h1, ptrdiff_t i1, FastPMStore * h2, ptrdiff_t i2)\n{\n    int d;\n    if(h1->rvdisp) {\n        for(d = 0; d < 9; d ++) {\n            h1->rvdisp[i1][d] += h2->rvdisp[i2][d];\n        }\n    }\n    if(h1->vdisp) {\n        for(d = 0; d < 6; d ++) {\n            h1->vdisp[i1][d] += h2->vdisp[i2][d];\n        }\n    }\n    if(h1->rdisp) {\n        for(d = 0; d < 6; d ++) {\n            h1->rdisp[i1][d] += h2->rdisp[i2][d];\n        }\n    }\n}\n\nstatic void\n_convert_extended_halo_attrs(FastPMFOFFinder * finder, FastPMStore * p, ptrdiff_t i, FastPMStore * halos)\n{\n    int hid = 0;\n\n    int d;\n    double rrel[3];\n\n    for(d = 0; d < 3; d ++) {\n        rrel[d] = p->x[i][d] - halos->x[hid][d];\n\n        if(finder->priv->boxsize) {\n            double L = finder->priv->boxsize[d];\n            while(rrel[d] > L / 2) rrel[d] -= L;\n            while(rrel[d] < -L / 2) rrel[d] += L;\n        }\n    }\n\n    if(halos->vdisp) {\n        /* FIXME: add hubble expansion term based on aemit and hubble function? needs to modify Finder object */\n\n        double vrel[3];\n        for(d = 0; d < 3; d ++) {\n            vrel[d] = p->v[i][d] - halos->v[hid][d];\n        }\n        for(d = 0; d < 3; d ++) {\n            halos->vdisp[hid][d] = vrel[d] * vrel[d];\n            halos->vdisp[hid][d + 3] = vrel[d] * vrel[(d + 1) % 3];\n        }\n    }\n    if(halos->rvdisp) {\n        /* FIXME: add hubble expansion term based on aemit and hubble function? needs to modify Finder object */\n\n        double vrel[3];\n        for(d = 0; d < 3; d ++) {\n            vrel[d] = p->v[i][d] - halos->v[hid][d];\n        }\n        for(d = 0; d < 3; d ++) {\n            halos->rvdisp[hid][d] = rrel[d] * vrel[d];\n            halos->rvdisp[hid][d + 3] = rrel[d] * vrel[(d + 1) % 3];\n            halos->rvdisp[hid][d + 6] = rrel[d] * vrel[(d + 2) % 3];\n        }\n    }\n    if(halos->rdisp) {\n        for(d = 0; d < 3; d ++) {\n            halos->rdisp[hid][d] = rrel[d] * rrel[d];\n            halos->rdisp[hid][d + 3] = rrel[d] * rrel[(d + 1) % 3];\n        }\n    }\n}\nstatic void\n_reduce_extended_halo_attrs(FastPMFOFFinder * finder, FastPMStore * halos, ptrdiff_t hid)\n{\n    double n = halos->length[hid];\n    int d;\n    if(halos->rvdisp) {\n        for(d = 0; d < 9; d ++) {\n            halos->rvdisp[hid][d] /= n;\n        }\n    }\n    if(halos->vdisp) {\n        for(d = 0; d < 6; d ++) {\n            halos->vdisp[hid][d] /= n;\n        }\n    }\n    if(halos->rdisp) {\n        for(d = 0; d < 3; d ++) {\n            halos->rdisp[hid][d] /= n;\n        }\n    }\n}\n\n/* This function creates the storage object for halo segments that are local on this\n * rank. We store mnay attributes. We only allow a flucutation of 2 around avg_halos.\n * this should be OK, since we will only redistribute by the MinID, which are supposed\n * to be very uniform.\n * */\nstatic void\nfastpm_fof_create_local_halos(FastPMFOFFinder * finder, FastPMStore * halos, size_t nhalos)\n{\n\n    MPI_Comm comm = finder->priv->comm;\n\n    FastPMColumnTags attributes = finder->p->attributes;\n    attributes |= COLUMN_MASK;\n    attributes |= COLUMN_LENGTH | COLUMN_MINID | COLUMN_TASK;\n    attributes |= COLUMN_RDISP | COLUMN_VDISP | COLUMN_RVDISP;\n    attributes |= COLUMN_ACC; /* ACC used as the first particle position offset */\n    attributes &= ~COLUMN_POTENTIAL;\n    attributes &= ~COLUMN_DENSITY;\n    attributes &= ~COLUMN_TIDAL;\n\n    /* store initial position only for periodic case. non-periodic suggests light cone and\n     * we cannot infer q from ID sensibly. (crashes there) */\n    if(finder->priv->boxsize) {\n        attributes |= COLUMN_Q;\n    } else {\n        attributes &= ~COLUMN_Q;\n    }\n\n    double avg_halos;\n    double max_halos;\n    /* + 1 to ensure avg_halos > 0 */\n    MPIU_stats(comm, nhalos + 1, \"->\", &avg_halos, &max_halos);\n\n    fastpm_info(\"Allocating %d halos per rank for final catalog.\\n\", (size_t) max_halos * 2);\n\n    /* give it enough space for rebalancing. */\n    fastpm_store_init(halos, NULL, (size_t) (max_halos * 2),\n            attributes,\n            FASTPM_MEMORY_HEAP);\n\n    halos->np = nhalos;\n    halos->meta = finder->p->meta;\n\n    ptrdiff_t i;\n    for(i = 0; i < halos->np; i++) {\n        halos->id[i] = i;\n\n        halos->mask[i] = 0; /* unselect the halos ; will turn this only if any particle is used */\n        /* everthing should have been set to zero already by fastpm_store_init */\n    }\n}\n\n\nvoid\nfastpm_fof_execute(FastPMFOFFinder * finder, FastPMStore * halos)\n{\n    /* initial decompose -- reduce number of ghosts */\n    FastPMStore * p = finder->p;\n    PM * pm = finder->pm;\n    MPI_Comm comm = finder->priv->comm;\n\n    /* only do wrapping for periodic data */\n    if(finder->priv->boxsize)\n        fastpm_store_wrap(p, finder->priv->boxsize);\n\n    double npmax, npmin, npstd, npmean;\n\n    MPIU_stats(comm, p->np, \"<->s\", &npmin, &npmean, &npmax, &npstd);\n\n    fastpm_info(\"load balance before fof decompose : min = %g max = %g mean = %g std = %g\\n\",\n        npmin, npmax, npmean, npstd\n        );\n\n#if 1\n    /* still route particles to the pm pencils as if they are periodic. */\n    /* should still work (albeit use crazy memory) if we skip this. */\n    if(0 != fastpm_store_decompose(p,\n                (fastpm_store_target_func) FastPMTargetFOF, pm, comm)\n    ) {\n        fastpm_raise(-1, \"out of storage space decomposing for FOF\\n\");\n    }\n#endif\n    MPIU_stats(comm, p->np, \"<->s\", &npmin, &npmean, &npmax, &npstd);\n\n    fastpm_info(\"load balance after fof decompose : min = %g max = %g mean = %g std = %g\\n\",\n        npmin, npmax, npmean, npstd\n        );\n\n    /* create ghosts mesh size is usually > ll so we are OK here. */\n    double below[3], above[3];\n\n    int d;\n    for(d = 0; d < 3; d ++) {\n        /* bigger padding reduces number of iterations */\n        below[d] = -finder->linkinglength * 1;\n        above[d] = finder->linkinglength * 1;\n    }\n\n    PMGhostData * pgd = pm_ghosts_create_full(pm, p,\n            COLUMN_POS | COLUMN_ID | COLUMN_MINID,\n            below, above\n        );\n\n    pm_ghosts_send(pgd, COLUMN_POS);\n    pm_ghosts_send(pgd, COLUMN_ID);\n\n    size_t np_and_ghosts = p->np + pgd->p->np;\n\n    #ifdef FASTPM_FOF_DEBUG\n    fastpm_ilog(INFO, \"Rank %d has %td particles including ghost\\n\", finder->priv->ThisTask, np_and_ghosts);\n    #endif\n\n    ptrdiff_t * head = fastpm_memory_alloc(p->mem, \"FOFHead\",\n                    sizeof(head[0]) * np_and_ghosts, FASTPM_MEMORY_STACK);\n\n    FastPMStore savebuff[1];\n    fastpm_store_init(savebuff, p->name, np_and_ghosts, COLUMN_MINID, FASTPM_MEMORY_STACK);\n\n    _fof_local_find(finder, p, pgd, head, finder->linkinglength);\n\n    _fof_global_merge (finder, p, pgd, savebuff->minid, head);\n\n    /* assign halo attr entries. This will keep only candidates that can possibly reach to nmin */\n    size_t nsegments = _assign_halo_attr(finder, pgd, head, p->np, pgd->p->np, finder->nmin);\n\n    fastpm_info(\"Found %td halos segments >= %d particles; or cross linked. \\n\", nsegments, finder->nmin);\n    pm_ghosts_free(pgd);\n\n    /* create local halos and modify head to index the local halos */\n    fastpm_fof_create_local_halos(finder, halos, nsegments);\n    /* remove halos without any local particles */\n    fastpm_fof_remove_empty_halos(finder, halos, savebuff->minid, head);\n\n    fastpm_store_destroy(savebuff);\n\n    /* reduce the primary halo attrs */\n    fastpm_fof_compute_halo_attrs(finder, halos, head, _convert_basic_halo_attrs, _add_basic_halo_attrs, _reduce_basic_halo_attrs);\n\n    #ifdef FASTPM_FOF_DEBUG\n    {\n        int i;\n        for(i  = 0; i < halos->np; i ++) {\n            fastpm_ilog(INFO, \"Task = %d, Halo[%d] = %d mask=%d MINID=%ld\\n\", finder->priv->ThisTask, i, halos->length[i], halos->mask[i], halos->minid[i]);\n        }\n    }\n    #endif\n\n    /* apply length cut */\n    fastpm_fof_apply_length_cut(finder, halos, head);\n\n    /* reduce the primary halo attrs */\n    fastpm_fof_compute_halo_attrs(finder, halos, head, _convert_extended_halo_attrs, _add_extended_halo_attrs, _reduce_extended_halo_attrs);\n\n    /* the event is called with full halos, only those where mask==1 are primary\n     * the others are ghosts with the correct properties but shall not show up in the\n     * catalog.\n     * */\n    FastPMHaloEvent event[1];\n    event->halos = halos;\n    event->p = finder->p;\n    event->ihalo = head;\n\n    fastpm_emit_event(finder->event_handlers, FASTPM_EVENT_HALO,\n                    FASTPM_EVENT_STAGE_AFTER, (FastPMEvent*) event, finder);\n\n    fastpm_memory_free(finder->p->mem, head);\n\n    fastpm_store_subsample(halos, halos->mask, halos);\n\n    fastpm_info(\"After event: %td halos.\\n\", fastpm_store_get_np_total(halos, comm));\n}\n\nvoid\nfastpm_fof_destroy(FastPMFOFFinder * finder)\n{\n    fastpm_destroy_event_handlers(&finder->event_handlers);\n    free(finder->priv);\n}\n\n\n", "meta": {"hexsha": "ef5feb8e6ed9b5ebe1f746bfd31c2fba779b815d", "size": 33555, "ext": "c", "lang": "C", "max_stars_repo_path": "fastpm/libfastpm/fof.c", "max_stars_repo_name": "sbird/FastPMRunner", "max_stars_repo_head_hexsha": "f38f6e69c603fb699436b645fe7b4eb418ee82c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fastpm/libfastpm/fof.c", "max_issues_repo_name": "sbird/FastPMRunner", "max_issues_repo_head_hexsha": "f38f6e69c603fb699436b645fe7b4eb418ee82c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-04-19T23:01:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-24T05:51:04.000Z", "max_forks_repo_path": "fastpm/libfastpm/fof.c", "max_forks_repo_name": "sbird/FastPMRunner", "max_forks_repo_head_hexsha": "f38f6e69c603fb699436b645fe7b4eb418ee82c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-14T23:24:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-14T23:24:19.000Z", "avg_line_length": 30.2297297297, "max_line_length": 156, "alphanum_fraction": 0.5818208911, "num_tokens": 10178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.022286184565158445, "lm_q1q2_score": 0.010534311200863724}}
{"text": "/* matrix/gsl_matrix_long_double.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_MATRIX_LONG_DOUBLE_H__\n#define __GSL_MATRIX_LONG_DOUBLE_H__\n\n#if !defined( GSL_FUN )\n#  if !defined( GSL_DLL )\n#    define GSL_FUN extern\n#  elif defined( BUILD_GSL_DLL )\n#    define GSL_FUN extern __declspec(dllexport)\n#  else\n#    define GSL_FUN extern __declspec(dllimport)\n#  endif\n#endif\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_inline.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_vector_long_double.h>\n#include <gsl/gsl_blas_types.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size1;\n  size_t size2;\n  size_t tda;\n  long double * data;\n  gsl_block_long_double * block;\n  int owner;\n} gsl_matrix_long_double;\n\ntypedef struct\n{\n  gsl_matrix_long_double matrix;\n} _gsl_matrix_long_double_view;\n\ntypedef _gsl_matrix_long_double_view gsl_matrix_long_double_view;\n\ntypedef struct\n{\n  gsl_matrix_long_double matrix;\n} _gsl_matrix_long_double_const_view;\n\ntypedef const _gsl_matrix_long_double_const_view gsl_matrix_long_double_const_view;\n\n/* Allocation */\n\nGSL_FUN gsl_matrix_long_double * \ngsl_matrix_long_double_alloc (const size_t n1, const size_t n2);\n\nGSL_FUN gsl_matrix_long_double * \ngsl_matrix_long_double_calloc (const size_t n1, const size_t n2);\n\nGSL_FUN gsl_matrix_long_double * \ngsl_matrix_long_double_alloc_from_block (gsl_block_long_double * b, \n                                   const size_t offset, \n                                   const size_t n1, \n                                   const size_t n2, \n                                   const size_t d2);\n\nGSL_FUN gsl_matrix_long_double * \ngsl_matrix_long_double_alloc_from_matrix (gsl_matrix_long_double * m,\n                                    const size_t k1, \n                                    const size_t k2,\n                                    const size_t n1, \n                                    const size_t n2);\n\nGSL_FUN gsl_vector_long_double * \ngsl_vector_long_double_alloc_row_from_matrix (gsl_matrix_long_double * m,\n                                        const size_t i);\n\nGSL_FUN gsl_vector_long_double * \ngsl_vector_long_double_alloc_col_from_matrix (gsl_matrix_long_double * m,\n                                        const size_t j);\n\nGSL_FUN void gsl_matrix_long_double_free (gsl_matrix_long_double * m);\n\n/* Views */\n\nGSL_FUN _gsl_matrix_long_double_view \ngsl_matrix_long_double_submatrix (gsl_matrix_long_double * m, \n                            const size_t i, const size_t j, \n                            const size_t n1, const size_t n2);\n\nGSL_FUN _gsl_vector_long_double_view \ngsl_matrix_long_double_row (gsl_matrix_long_double * m, const size_t i);\n\nGSL_FUN _gsl_vector_long_double_view \ngsl_matrix_long_double_column (gsl_matrix_long_double * m, const size_t j);\n\nGSL_FUN _gsl_vector_long_double_view \ngsl_matrix_long_double_diagonal (gsl_matrix_long_double * m);\n\nGSL_FUN _gsl_vector_long_double_view \ngsl_matrix_long_double_subdiagonal (gsl_matrix_long_double * m, const size_t k);\n\nGSL_FUN _gsl_vector_long_double_view \ngsl_matrix_long_double_superdiagonal (gsl_matrix_long_double * m, const size_t k);\n\nGSL_FUN _gsl_vector_long_double_view\ngsl_matrix_long_double_subrow (gsl_matrix_long_double * m, const size_t i,\n                         const size_t offset, const size_t n);\n\nGSL_FUN _gsl_vector_long_double_view\ngsl_matrix_long_double_subcolumn (gsl_matrix_long_double * m, const size_t j,\n                            const size_t offset, const size_t n);\n\nGSL_FUN _gsl_matrix_long_double_view\ngsl_matrix_long_double_view_array (long double * base,\n                             const size_t n1, \n                             const size_t n2);\n\nGSL_FUN _gsl_matrix_long_double_view\ngsl_matrix_long_double_view_array_with_tda (long double * base, \n                                      const size_t n1, \n                                      const size_t n2,\n                                      const size_t tda);\n\n\nGSL_FUN _gsl_matrix_long_double_view\ngsl_matrix_long_double_view_vector (gsl_vector_long_double * v,\n                              const size_t n1, \n                              const size_t n2);\n\nGSL_FUN _gsl_matrix_long_double_view\ngsl_matrix_long_double_view_vector_with_tda (gsl_vector_long_double * v,\n                                       const size_t n1, \n                                       const size_t n2,\n                                       const size_t tda);\n\n\nGSL_FUN _gsl_matrix_long_double_const_view \ngsl_matrix_long_double_const_submatrix (const gsl_matrix_long_double * m, \n                                  const size_t i, const size_t j, \n                                  const size_t n1, const size_t n2);\n\nGSL_FUN _gsl_vector_long_double_const_view \ngsl_matrix_long_double_const_row (const gsl_matrix_long_double * m, \n                            const size_t i);\n\nGSL_FUN _gsl_vector_long_double_const_view \ngsl_matrix_long_double_const_column (const gsl_matrix_long_double * m, \n                               const size_t j);\n\nGSL_FUN _gsl_vector_long_double_const_view\ngsl_matrix_long_double_const_diagonal (const gsl_matrix_long_double * m);\n\nGSL_FUN _gsl_vector_long_double_const_view \ngsl_matrix_long_double_const_subdiagonal (const gsl_matrix_long_double * m, \n                                    const size_t k);\n\nGSL_FUN _gsl_vector_long_double_const_view \ngsl_matrix_long_double_const_superdiagonal (const gsl_matrix_long_double * m, \n                                      const size_t k);\n\nGSL_FUN _gsl_vector_long_double_const_view\ngsl_matrix_long_double_const_subrow (const gsl_matrix_long_double * m, const size_t i,\n                               const size_t offset, const size_t n);\n\nGSL_FUN _gsl_vector_long_double_const_view\ngsl_matrix_long_double_const_subcolumn (const gsl_matrix_long_double * m, const size_t j,\n                                  const size_t offset, const size_t n);\n\nGSL_FUN _gsl_matrix_long_double_const_view\ngsl_matrix_long_double_const_view_array (const long double * base,\n                                   const size_t n1, \n                                   const size_t n2);\n\nGSL_FUN _gsl_matrix_long_double_const_view\ngsl_matrix_long_double_const_view_array_with_tda (const long double * base, \n                                            const size_t n1, \n                                            const size_t n2,\n                                            const size_t tda);\n\nGSL_FUN _gsl_matrix_long_double_const_view\ngsl_matrix_long_double_const_view_vector (const gsl_vector_long_double * v,\n                                    const size_t n1, \n                                    const size_t n2);\n\nGSL_FUN _gsl_matrix_long_double_const_view\ngsl_matrix_long_double_const_view_vector_with_tda (const gsl_vector_long_double * v,\n                                             const size_t n1, \n                                             const size_t n2,\n                                             const size_t tda);\n\n/* Operations */\n\nGSL_FUN void gsl_matrix_long_double_set_zero (gsl_matrix_long_double * m);\nGSL_FUN void gsl_matrix_long_double_set_identity (gsl_matrix_long_double * m);\nGSL_FUN void gsl_matrix_long_double_set_all (gsl_matrix_long_double * m, long double x);\n\nGSL_FUN int gsl_matrix_long_double_fread (FILE * stream, gsl_matrix_long_double * m) ;\nGSL_FUN int gsl_matrix_long_double_fwrite (FILE * stream, const gsl_matrix_long_double * m) ;\nGSL_FUN int gsl_matrix_long_double_fscanf (FILE * stream, gsl_matrix_long_double * m);\nGSL_FUN int gsl_matrix_long_double_fprintf (FILE * stream, const gsl_matrix_long_double * m, const char * format);\n \nGSL_FUN int gsl_matrix_long_double_memcpy(gsl_matrix_long_double * dest, const gsl_matrix_long_double * src);\nGSL_FUN int gsl_matrix_long_double_swap(gsl_matrix_long_double * m1, gsl_matrix_long_double * m2);\nGSL_FUN int gsl_matrix_long_double_tricpy(CBLAS_UPLO_t Uplo, CBLAS_DIAG_t Diag, gsl_matrix_long_double * dest, const gsl_matrix_long_double * src);\n\nGSL_FUN int gsl_matrix_long_double_swap_rows(gsl_matrix_long_double * m, const size_t i, const size_t j);\nGSL_FUN int gsl_matrix_long_double_swap_columns(gsl_matrix_long_double * m, const size_t i, const size_t j);\nGSL_FUN int gsl_matrix_long_double_swap_rowcol(gsl_matrix_long_double * m, const size_t i, const size_t j);\nGSL_FUN int gsl_matrix_long_double_transpose (gsl_matrix_long_double * m);\nGSL_FUN int gsl_matrix_long_double_transpose_memcpy (gsl_matrix_long_double * dest, const gsl_matrix_long_double * src);\nGSL_FUN int gsl_matrix_long_double_transpose_tricpy (CBLAS_UPLO_t Uplo_src, CBLAS_DIAG_t Diag, gsl_matrix_long_double * dest, const gsl_matrix_long_double * src);\n\nGSL_FUN long double gsl_matrix_long_double_max (const gsl_matrix_long_double * m);\nGSL_FUN long double gsl_matrix_long_double_min (const gsl_matrix_long_double * m);\nGSL_FUN void gsl_matrix_long_double_minmax (const gsl_matrix_long_double * m, long double * min_out, long double * max_out);\n\nGSL_FUN void gsl_matrix_long_double_max_index (const gsl_matrix_long_double * m, size_t * imax, size_t *jmax);\nGSL_FUN void gsl_matrix_long_double_min_index (const gsl_matrix_long_double * m, size_t * imin, size_t *jmin);\nGSL_FUN void gsl_matrix_long_double_minmax_index (const gsl_matrix_long_double * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);\n\nGSL_FUN int gsl_matrix_long_double_equal (const gsl_matrix_long_double * a, const gsl_matrix_long_double * b);\n\nGSL_FUN int gsl_matrix_long_double_isnull (const gsl_matrix_long_double * m);\nGSL_FUN int gsl_matrix_long_double_ispos (const gsl_matrix_long_double * m);\nGSL_FUN int gsl_matrix_long_double_isneg (const gsl_matrix_long_double * m);\nGSL_FUN int gsl_matrix_long_double_isnonneg (const gsl_matrix_long_double * m);\n\nGSL_FUN int gsl_matrix_long_double_add (gsl_matrix_long_double * a, const gsl_matrix_long_double * b);\nGSL_FUN int gsl_matrix_long_double_sub (gsl_matrix_long_double * a, const gsl_matrix_long_double * b);\nGSL_FUN int gsl_matrix_long_double_mul_elements (gsl_matrix_long_double * a, const gsl_matrix_long_double * b);\nGSL_FUN int gsl_matrix_long_double_div_elements (gsl_matrix_long_double * a, const gsl_matrix_long_double * b);\nGSL_FUN int gsl_matrix_long_double_scale (gsl_matrix_long_double * a, const double x);\nGSL_FUN int gsl_matrix_long_double_scale_rows (gsl_matrix_long_double * a, const gsl_vector_long_double * x);\nGSL_FUN int gsl_matrix_long_double_scale_columns (gsl_matrix_long_double * a, const gsl_vector_long_double * x);\nGSL_FUN int gsl_matrix_long_double_add_constant (gsl_matrix_long_double * a, const double x);\nGSL_FUN int gsl_matrix_long_double_add_diagonal (gsl_matrix_long_double * a, const double x);\n\n/***********************************************************************/\n/* The functions below are obsolete                                    */\n/***********************************************************************/\nGSL_FUN int gsl_matrix_long_double_get_row(gsl_vector_long_double * v, const gsl_matrix_long_double * m, const size_t i);\nGSL_FUN int gsl_matrix_long_double_get_col(gsl_vector_long_double * v, const gsl_matrix_long_double * m, const size_t j);\nGSL_FUN int gsl_matrix_long_double_set_row(gsl_matrix_long_double * m, const size_t i, const gsl_vector_long_double * v);\nGSL_FUN int gsl_matrix_long_double_set_col(gsl_matrix_long_double * m, const size_t j, const gsl_vector_long_double * v);\n/***********************************************************************/\n\n/* inline functions if you are using GCC */\n\nGSL_FUN INLINE_DECL long double   gsl_matrix_long_double_get(const gsl_matrix_long_double * m, const size_t i, const size_t j);\nGSL_FUN INLINE_DECL void    gsl_matrix_long_double_set(gsl_matrix_long_double * m, const size_t i, const size_t j, const long double x);\nGSL_FUN INLINE_DECL long double * gsl_matrix_long_double_ptr(gsl_matrix_long_double * m, const size_t i, const size_t j);\nGSL_FUN INLINE_DECL const long double * gsl_matrix_long_double_const_ptr(const gsl_matrix_long_double * m, const size_t i, const size_t j);\n\n#ifdef HAVE_INLINE\nINLINE_FUN \nlong double\ngsl_matrix_long_double_get(const gsl_matrix_long_double * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_VAL(\"first index out of range\", GSL_EINVAL, 0) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_VAL(\"second index out of range\", GSL_EINVAL, 0) ;\n        }\n    }\n#endif\n  return m->data[i * m->tda + j] ;\n} \n\nINLINE_FUN \nvoid\ngsl_matrix_long_double_set(gsl_matrix_long_double * m, const size_t i, const size_t j, const long double x)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_VOID(\"first index out of range\", GSL_EINVAL) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_VOID(\"second index out of range\", GSL_EINVAL) ;\n        }\n    }\n#endif\n  m->data[i * m->tda + j] = x ;\n}\n\nINLINE_FUN \nlong double *\ngsl_matrix_long_double_ptr(gsl_matrix_long_double * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n        }\n    }\n#endif\n  return (long double *) (m->data + (i * m->tda + j)) ;\n} \n\nINLINE_FUN \nconst long double *\ngsl_matrix_long_double_const_ptr(const gsl_matrix_long_double * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n        }\n    }\n#endif\n  return (const long double *) (m->data + (i * m->tda + j)) ;\n} \n\n#endif\n\n__END_DECLS\n\n#endif /* __GSL_MATRIX_LONG_DOUBLE_H__ */\n", "meta": {"hexsha": "b14c07900ae0a519faf6e811b49cbd4015802b34", "size": 14980, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gsl/gsl_matrix_long_double.h", "max_stars_repo_name": "zhanghe9704/jspec2", "max_stars_repo_head_hexsha": "0073e0515b87610b7f88ad2b07fc7d23618c159a", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-28T08:20:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-28T08:20:20.000Z", "max_issues_repo_path": "include/gsl/gsl_matrix_long_double.h", "max_issues_repo_name": "zhanghe9704/jspec2", "max_issues_repo_head_hexsha": "0073e0515b87610b7f88ad2b07fc7d23618c159a", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gsl/gsl_matrix_long_double.h", "max_forks_repo_name": "zhanghe9704/jspec2", "max_forks_repo_head_hexsha": "0073e0515b87610b7f88ad2b07fc7d23618c159a", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-14T12:45:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-14T12:45:35.000Z", "avg_line_length": 40.9289617486, "max_line_length": 162, "alphanum_fraction": 0.700400534, "num_tokens": 3572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3276682876897044, "lm_q2_score": 0.03210070926341381, "lm_q1q2_score": 0.010518384437967836}}
{"text": "#ifndef _SPC_SPC_H\n\n#define _SPC_SPC_H\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <unistd.h>\n#include <string.h>\n\n#include <gsl/gsl_nan.h>\n#include <gsl/gsl_sys.h>\n\n#include \"aXe_grism.h\"\n#include \"aXe_utils.h\"\n#include \"fitsio.h\"\n\n#define SPCTOL 1.0e-5\n\n// interpolation type used for the\n// response function\n#define RESP_FUNC_INTERP_TYPE gsl_interp_linear\n\nextern spectrum *\nallocate_spectrum (const int numbin);\n\nextern void\nfree_spectrum (spectrum * const spec);\n\nextern void\nfprintf_spectrum (FILE * output, const spectrum * const sp);\n\nextern spectrum *\nsubtract_spectra (spectrum * a, spectrum * b);\n\nextern int\nget_ID_index_to_SPC (char filename[], char ID[]);\n\nextern void\nadd_ID_index_to_SPC (char filename[], char ID[], int hdunum);\n\nextern int\nadd_ID_to_SPC (char filename[], int N, char ID[]);\n\nextern int\nfind_ID_in_SPC (char filename[], char ID[]);\n\nextern void\ncreate_SPC (char filename[], int overwrite);\n\nextern int\nget_SPC_colnum (fitsfile * input, char colname[]);\n\nextern void\nadd_spectra_to_SPC (char filename[], spectrum * obj_spec,\n\t\t    spectrum * bck_spec, spectrum * sobj_spec,\n\t\t    int aperID, int beamID);\n\nextern void\nadd_data_to_SPC (spectrum * spec, char countcolname[],\n\t\t char errorcolname[], char weightcolname[], char ID[],\n\t\t char filename[], int hdunum, long N);\n\nextern spectrum *\ntrim_spectrum (spectrum * spc);\n\nextern spectrum *\nempty_counts_spectrum_copy (spectrum * a);\n\nextern void\nadd_ID_to_SPC_opened (fitsfile *output, int N, char ID[]);\n\nextern void\nadd_spectra_to_SPC_opened (fitsfile *input, spectrum * obj_spec,\n\t\t\t   spectrum * bck_spec, spectrum * sobj_spec,\n\t\t\t   int aperID, int beamID);\n\nextern void\nadd_data_to_SPC_opened (spectrum * spec, char countcolname[],\n\t\t\tchar errorcolname[], char weightcolname[],\n\t\t\tchar ID[], fitsfile *input, long N);\n\nextern fitsfile *\ncreate_SPC_opened (char filename[], int overwrite);\n\n#endif\n", "meta": {"hexsha": "ac41e157ab557557acca82d3e5a3c0eaeccba016", "size": 1910, "ext": "h", "lang": "C", "max_stars_repo_path": "cextern/src/spc_spc.h", "max_stars_repo_name": "sosey/pyaxe", "max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cextern/src/spc_spc.h", "max_issues_repo_name": "sosey/pyaxe", "max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cextern/src/spc_spc.h", "max_forks_repo_name": "sosey/pyaxe", "max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.9540229885, "max_line_length": 64, "alphanum_fraction": 0.7387434555, "num_tokens": 519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.411110869232168, "lm_q2_score": 0.02556521318084506, "lm_q1q2_score": 0.010510137012882892}}
{"text": "/*\nCopyright 2010-2011, D. E. Shaw Research.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n* Redistributions of source code must retain the above copyright\n  notice, this list of conditions, and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright\n  notice, this list of conditions, and the following disclaimer in the\n  documentation and/or other materials provided with the distribution.\n\n* Neither the name of D. E. Shaw Research nor the names of its\n  contributors may be used to endorse or promote products derived from\n  this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n#ifndef __r123_gslmicrorng_dot_h__\n#define __r123_gslmicrorng_dot_h__\n\n\n#include <gsl/gsl_rng.h>\n#include <string.h>\n\n/**   The macro: GSL_MICRORNG(NAME, CBRNGNAME) is the GSL\n   analog analog of the C++ r123::MicroURNG template.  It declares a gsl_rng\n   type named gsl_rng_NAME which uses the underlying CBRNGNAME\n   and can be invoked a limited number of times between calls to NAME_reset.\n\n   When the underlying CBRNG's \\c ctr_t is an \\ref arrayNxW \"r123arrayNxW\",\n   and the gsl_rng_NAME may called up to \\c N*2^32 times \n   between calls to \\c NAME_reset.\n\n   \\c NAME_reset takes a gsl_rng_NAME type, a counter and a key as arguments.\n   It restarts the micro-rng with a new base counter and key.\n\n   Note that you must call NAME_reset before the first use\n   of a gsl_rng.  NAME_reset is not called automatically by\n   gsl_rng_alloc().\n\n   @code\n   #include <Random123/threefry.h>\n   #include <Random123/gsl_microrng.h> // this file\n   GSL_MICRORNG(microcbrng, threefry4x64, 20)\t// creates gsl_rng_microcbrng\n\n   int main(int argc, char** argv) {\n\tgsl_rng *r = gsl_rng_alloc(gsl_rng_microcbrng);\n\tthreefry4x64_ctr_t c = {{}};\n\tthreefry4x64_key_t k = {{}};\n\n\tfor (...) {\n\t    c.v[0] = ??; //  some application variable\n\t    microcbrng_reset(r, c, k);\n\t    for (...) {\n\t\t// gaussian calls r several times.  It is safe for\n\t\t// r to be used upto 2^20 times in this loop\n\t\tsomething[i] = gsl_ran_gaussian(r, 1.5);\n\t    }\n\t}\n   }\n   @endcode\n   \n*/\n\n#define GSL_MICRORNG(NAME, CBRNGNAME)                                   \\\nconst gsl_rng_type *gsl_rng_##NAME;                                     \\\n                                                                        \\\ntypedef struct{                                                         \\\n    CBRNGNAME##_ctr_t ctr;                                              \\\n    CBRNGNAME##_ctr_t r;                                                \\\n    CBRNGNAME##_key_t key;                                              \\\n    R123_ULONG_LONG n;                                                  \\\n    int elem;                                                           \\\n} NAME##_state;                                                         \\\n                                                                        \\\nstatic unsigned long int NAME##_get(void *vstate){                      \\\n    NAME##_state *st = (NAME##_state *)vstate;                          \\\n    const int N=sizeof(st->ctr.v)/sizeof(st->ctr.v[0]);                 \\\n    if( st->elem == 0 ){                                                \\\n        CBRNGNAME##_ctr_t c = st->ctr;                                  \\\n        c.v[N-1] |= st->n<<(R123_W(CBRNGNAME##_ctr_t)-32);              \\\n        st->n++;                                                        \\\n        st->r = CBRNGNAME(c, st->key);                                  \\\n        st->elem = N;                                                   \\\n    }                                                                   \\\n    return 0xffffffff & st->r.v[--st->elem];                            \\\n}                                                                       \\\n                                                                        \\\nstatic double                                                           \\\nNAME##_get_double (void * vstate)                                       \\\n{                                                                       \\\n    return NAME##_get (vstate)/4294967296.;                             \\\n}                                                                       \\\n                                                                        \\\nstatic void NAME##_set(void *vstate, unsigned long int s){              \\\n    NAME##_state *st = (NAME##_state *)vstate;                          \\\n    st->elem = 0;                                                       \\\n    st->n = ~0; /* will abort if _reset is not called */                \\\n}                                                                       \\\n                                                                        \\\nstatic const gsl_rng_type NAME##_type = {                               \\\n    #NAME,                                                              \\\n    0xffffffffUL,                                                       \\\n    0,                                                                  \\\n    sizeof(NAME##_state),                                               \\\n    &NAME##_set,                                                        \\\n    &NAME##_get,                                                        \\\n    &NAME##_get_double                                                  \\\n};                                                                      \\\n                                                                        \\\nR123_STATIC_INLINE void NAME##_reset(const gsl_rng* gr, CBRNGNAME##_ctr_t c, CBRNGNAME##_key_t k) { \\\n    NAME##_state* state = (NAME##_state *)gr->state;                    \\\n    state->ctr = c;                                                     \\\n    state->key = k;                                                     \\\n    state->n = 0;                                                       \\\n    state->elem = 0;                                                    \\\n}                                                                       \\\n                                                                        \\\nconst gsl_rng_type *gsl_rng_##NAME = &NAME##_type\n\n#endif\n", "meta": {"hexsha": "370a60d598c1a04d4deb6fffb601d1043ea6c080", "size": 7040, "ext": "h", "lang": "C", "max_stars_repo_path": "include/philox-wrapper/external/Random123/gsl_microrng.h", "max_stars_repo_name": "havogt/philox-wrapper", "max_stars_repo_head_hexsha": "bf2ae2b575445ed225bba037815a3d90c2218ea7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/philox-wrapper/external/Random123/gsl_microrng.h", "max_issues_repo_name": "havogt/philox-wrapper", "max_issues_repo_head_hexsha": "bf2ae2b575445ed225bba037815a3d90c2218ea7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/philox-wrapper/external/Random123/gsl_microrng.h", "max_forks_repo_name": "havogt/philox-wrapper", "max_forks_repo_head_hexsha": "bf2ae2b575445ed225bba037815a3d90c2218ea7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.7647058824, "max_line_length": 101, "alphanum_fraction": 0.4352272727, "num_tokens": 1308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2689414213699951, "lm_q2_score": 0.039048294263872615, "lm_q1q2_score": 0.010501703761399727}}
{"text": "#include <stdlib.h>\n#include <gsl/vector/gsl_vector.h>\n#include <gsl/gsl_errno.h>\n\n\n\n#define BASE_DOUBLE\n#include <gsl/templates_on.h>\n#include <gsl/vector/prop_source.c>\n#include <gsl/templates_off.h>\n#undef BASE_DOUBLE\n\n", "meta": {"hexsha": "96e9400c201baae4e6a76a1b42d62d99b176c54a", "size": 222, "ext": "c", "lang": "C", "max_stars_repo_path": "Cartwheel/cartwheel-3d/gsl/vector/prop.c", "max_stars_repo_name": "MontyThibault/centre-of-mass-awareness", "max_stars_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Cartwheel/cartwheel-3d/gsl/vector/prop.c", "max_issues_repo_name": "MontyThibault/centre-of-mass-awareness", "max_issues_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cartwheel/cartwheel-3d/gsl/vector/prop.c", "max_forks_repo_name": "MontyThibault/centre-of-mass-awareness", "max_forks_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.0769230769, "max_line_length": 35, "alphanum_fraction": 0.7612612613, "num_tokens": 58, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046348141882, "lm_q2_score": 0.024798161637017424, "lm_q1q2_score": 0.010477338226511259}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <nlopt.h>\n\n// System definition and dimension\n\nint mysys = 0;\nint dim = 3;\n\n// Semi-empirical method and parameter variation range\n\nchar * method = \"pm7\";\ndouble pdev = 0.7;\n\n// Algorithm parameters\n\nnlopt_algorithm global_alg = NLOPT_GD_MLSL_LDS;\nnlopt_algorithm local_alg = NLOPT_LN_BOBYQA;\nint maxeval = 3;\ndouble minrms = 0.01;\ndouble tol = 0.001;\n\n//Define here  your system's input for MOPAC\n\nvoid gen_srpgeo(int ndat, double ** data) {\n\tlong length;\n\tchar * buffer = 0;\n\tchar procedure[0x100];\n\n\tswitch (mysys) {\n\tcase 0: {\n\t\t// Ar/C10H8\n\t\tFILE * fp = fopen(\"./naf_geo.xyz\", \"r\");\n\t\tif (!fp)\n\t\t\texit(EXIT_FAILURE);\n\t\tfseek(fp, 0L, SEEK_END);\n\t\tlength = ftell(fp);\n\t\trewind(fp);\n\t\tbuffer = (char *) malloc((length+1) * sizeof(char));\n\t\tif (buffer) {\n\t\t\tfread(buffer, sizeof(char), length, fp);\n\t\t}\n\t\tfclose(fp);\n\n\t\tfor (int i = 0; i < ndat; ++i) {\n\t\t\tchar buf[0x100];\n\t\t\tsnprintf(buf, sizeof(buf), \"./inp_semp/geo_%d.mop\", i);\n\t\t\tFILE * fq = fopen(buf, \"w\");\n\t\t\tstrcpy(procedure, method);\n\t\t\tstrcpy(procedure, \" charge=0 1scf EXTERNAL=mopac_parameter\\n\");\n\t\t\tfprintf(fq, \"%s\", procedure);\n\t\t\tfprintf(fq, \"Dumb title rule\\n\");\n\t\t\tfprintf(fq, \" \\n\");\n\t\t\tfprintf(fq, \"Ar %f %f %f\\n\", data[i][0], data[i][1], data[i][2]);\n\t\t\tfputs(buffer, fq);\n\t\t\tfprintf(fq, \" \");\n\t\t\tfclose(fq);\n\t\t}\n\t\tfree(buffer);\n\t}\n\n\tdefault:\n\t\tbreak;\n\t}\n}\n", "meta": {"hexsha": "8f1b0c610ac05c256ee5d15fac05277e7d32a312", "size": 1398, "ext": "h", "lang": "C", "max_stars_repo_path": "systems.h", "max_stars_repo_name": "Panadestein/srpt_c", "max_stars_repo_head_hexsha": "d6a0c6e898fb3b82d7f90ca92a654d101db0fc5f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "systems.h", "max_issues_repo_name": "Panadestein/srpt_c", "max_issues_repo_head_hexsha": "d6a0c6e898fb3b82d7f90ca92a654d101db0fc5f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "systems.h", "max_forks_repo_name": "Panadestein/srpt_c", "max_forks_repo_head_hexsha": "d6a0c6e898fb3b82d7f90ca92a654d101db0fc5f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.8656716418, "max_line_length": 68, "alphanum_fraction": 0.6280400572, "num_tokens": 466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046493573919, "lm_q2_score": 0.024798157492901308, "lm_q1q2_score": 0.010477336836247648}}
{"text": "#ifndef mooney_rivlin_h\n#define mooney_rivlin_h\n\n#include <petsc.h>\n#include \"../include/structs.h\"\n\n#ifndef PHYSICS_STRUCT_MR\n#define PHYSICS_STRUCT_MR\ntypedef struct Physics_MR_ *Physics_MR;\nstruct Physics_MR_ {\n  // Material properties for MR\n  CeedScalar mu_1;\n  CeedScalar mu_2;\n  CeedScalar lambda;\n};\n#endif // PHYSICS_STRUCT_MR\n\n// Create context object\nPetscErrorCode PhysicsContext_MR(MPI_Comm comm, Ceed ceed, Units *units,\n                                 CeedQFunctionContext *ctx);\nPetscErrorCode PhysicsSmootherContext_MR(MPI_Comm comm, Ceed ceed,\n    CeedQFunctionContext ctx, CeedQFunctionContext *ctx_smoother);\n\n// Process physics options - Mooney-Rivlin\nPetscErrorCode ProcessPhysics_MR(MPI_Comm comm, Physics_MR phys, Units units);\n\n#endif // mooney_rivlin_h\n", "meta": {"hexsha": "1ca82e829413f2372b30349cb2602247f265fc61", "size": 780, "ext": "h", "lang": "C", "max_stars_repo_path": "examples/solids/problems/mooney-rivlin.h", "max_stars_repo_name": "AdelekeBankole/libCEED", "max_stars_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 123.0, "max_stars_repo_stars_event_min_datetime": "2018-01-29T02:04:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T18:13:48.000Z", "max_issues_repo_path": "examples/solids/problems/mooney-rivlin.h", "max_issues_repo_name": "AdelekeBankole/libCEED", "max_issues_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 781.0, "max_issues_repo_issues_event_min_datetime": "2017-12-22T17:20:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T21:34:34.000Z", "max_forks_repo_path": "examples/solids/problems/mooney-rivlin.h", "max_forks_repo_name": "AdelekeBankole/libCEED", "max_forks_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2017-12-27T22:35:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:02:07.000Z", "avg_line_length": 27.8571428571, "max_line_length": 78, "alphanum_fraction": 0.7692307692, "num_tokens": 200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.373875808818685, "lm_q2_score": 0.028007518070639545, "lm_q1q2_score": 0.010471333471664295}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/stat.h>\n#include \"parmt_postProcess.h\"\n#ifdef PARMT_USE_INTEL\n#include <mkl_cblas.h>\n#else\n#include <cblas.h>\n#endif\n#include \"compearth.h\"\n#include \"iscl/array/array.h\"\n#include \"iscl/memory/memory.h\"\n#include \"iscl/os/os.h\"\n\n\nstatic void getBaseAndExp(const double val, double *base, int *exp);\nstatic void setFillColor(const int i, const int iopt, char color[32]);\n\n/*!\n * @brief Writes the global station distribution of stations, the\n *        station names, the epicenter or moment tensor, and, if\n *        desired, some indication of station polarity.\n */\nint postmt_gmtHelper_writeGlobalMap(\n    struct globalMapOpts_struct globalMap,\n    const int nobs, const struct sacData_struct *data)\n{\n    const char *fcnm = \"postmt_gmtHelper_writeGlobalMap\\0\";\n    FILE *ofl;\n    char *dirName, line[256], cpick[8];\n    int *pol, i, ierr, l, nw, nwd, nwu;\n    size_t lenos;\n    const char *forwardSlash = \"/\";\n    const int nTimeVars = 11;\n    const enum sacHeader_enum timeVarNames[11]\n       = {SAC_CHAR_KA,\n          SAC_CHAR_KT0, SAC_CHAR_KT1, SAC_CHAR_KT2, SAC_CHAR_KT3,\n          SAC_CHAR_KT4, SAC_CHAR_KT5, SAC_CHAR_KT6, SAC_CHAR_KT7,\n          SAC_CHAR_KT8, SAC_CHAR_KT9};\n\n    dirName = os_dirname(globalMap.outputScript, &ierr);\n    if (!os_path_isdir(dirName))\n    {\n        ierr = os_makedirs(dirName); \n        if (ierr != 0)\n        {\n            printf(\"%s: Failed to make output directory: %s\\n\", fcnm, dirName);\n            return -1;\n        }\n    }\n    memory_free8c(&dirName);\n\n    ofl = fopen(globalMap.outputScript, \"w\"); \n    fprintf(ofl, \"#!/bin/bash\\n\");\n    fprintf(ofl, \"outps=%s\\n\", globalMap.psFile);\n    fprintf(ofl, \"olat=%f\\n\", globalMap.evla);\n    fprintf(ofl, \"olon=%f\\n\", globalMap.evlo);\n    fprintf(ofl, \"J=-JH${olon}%s6i\\n\", forwardSlash);\n    fprintf(ofl, \"R=-Rg\\n\");\n    fprintf(ofl, \"gmt pscoast $J $R -B0g30 -Di -Ggray -P -K > ${outps}\\n\");\n    fprintf(ofl, \"ts=0.15i\\n\");\n  \n    fprintf(ofl, \"# Draw great circle arcs between source and receivers\\n\");\n    fprintf(ofl, \"gmt psxy $J $R -W1p -O -K << EOF >> ${outps}\\n\");\n    for (i=0; i<nobs; i++)\n    {   \n        fprintf(ofl, \"%8.3f %8.3f\\n\", data[i].header.stlo, data[i].header.stla);\n        fprintf(ofl, \"%8.3f %8.3f\\n\", globalMap.evlo, globalMap.evla);\n        if (i < nobs - 1){fprintf(ofl, \"\\n\");}\n    }   \n    fprintf(ofl, \"EOF\\n\");\n\n    fprintf(ofl, \"# Plot the moment tensor\\n\");\n    postmt_gmtHelper_makePsmecaLine(globalMap.basis, globalMap.mts,\n                                    globalMap.evla, globalMap.evlo,\n                                    globalMap.evdp, \"Optimum\\0\", line);\n    if (globalMap.lwantMT)\n    {\n        fprintf(ofl, \"gmt psmeca $J $R -Sm0.15i -M -N -Gblue -W0.5p,black -O -K << EOF >> ${outps}\\n\");\n        fprintf(ofl, \"%s\", line);\n        fprintf(ofl, \"EOF\\n\");\n    }\n    else\n    {\n        fprintf(ofl, \"# Plot the epicenter\\n\");\n        fprintf(ofl, \"gmt psxy $J $R -Sa${ts} -Gblue -Wblack -O -K << EOF >> ${outps}\\n\");\n        fprintf(ofl, \"%8.3f %8.3f\\n\", globalMap.evlo, globalMap.evla);\n        fprintf(ofl, \"EOF\\n\");\n    }\n\n    if (!globalMap.lwantPolarity)\n    {\n        fprintf(ofl, \"# Plot the stations\\n\");\n        fprintf(ofl, \"gmt psxy $J $R -St${ts} -Gred -Wblack -O -K << EOF >> ${outps}\\n\");\n        for (i=0; i<nobs; i++)\n        {\n            fprintf(ofl, \"%8.3f %8.3f %s\\n\", data[i].header.stlo,\n                    data[i].header.stla, data[i].header.kstnm);\n        }\n        fprintf(ofl, \"EOF\\n\");\n    }\n    else\n    {\n        // Get the polarities\n        nw = 0;\n        nwd = 0;\n        nwu = 0;\n        pol = (int *) calloc((size_t) nobs, sizeof(int));\n        for (i=0; i<nobs; i++)\n        {\n            memset(cpick, 0, 8*sizeof(char));\n            for (l=0; l<nTimeVars; l++)\n            {\n                ierr = sacio_getCharacterHeader(timeVarNames[l],\n                                                data[i].header, cpick);\n                if (ierr == 0){break;}\n            }\n            lenos = strlen(cpick);\n            if (lenos > 0)\n            {\n                if (cpick[lenos-1] == '+')\n                {\n                    nwu = nwu + 1;\n                    pol[i] = 1;\n                }\n                else if (cpick[lenos-1] == '-')\n                {\n                    nwd = nwd + 1;\n                    pol[i] =-1;\n                }\n                else\n                {\n                    nw = nw + 1;\n                }\n            }\n            else\n            {\n                nw = nw + 1;\n            }\n        }\n        // Write the unknowns\n        if (nw > 0)\n        {\n            fprintf(ofl, \"# Plot the indeterminant stations\\n\");\n            fprintf(ofl, \"gmt psxy $J $R -Ss${ts} -Gred -Wblack -O -K << EOF >> ${outps}\\n\");\n            for (i=0; i<nobs; i++)\n            {\n                if (pol[i] == 0)\n                {\n                    fprintf(ofl, \"%8.3f %8.3f %s\\n\", data[i].header.stlo,\n                            data[i].header.stla, data[i].header.kstnm);\n                }\n            }   \n            fprintf(ofl, \"EOF\\n\");\n        }\n        // Write the ups\n        if (nwu > 0)\n        {\n            fprintf(ofl, \"# Plot the upward stations\\n\");\n            fprintf(ofl, \"gmt psxy $J $R -St${ts} -Gred -Wblack -O -K << EOF >> ${outps}\\n\");\n            for (i=0; i<nobs; i++)\n            {\n                if (pol[i] == 1)\n                {\n                    fprintf(ofl, \"%8.3f %8.3f %s\\n\", data[i].header.stlo,\n                            data[i].header.stla, data[i].header.kstnm);\n                }\n            }\n            fprintf(ofl, \"EOF\\n\");\n        }\n        // Write the downs\n        if (nwd > 0)\n        {\n            fprintf(ofl, \"# Plot the down stations\\n\");\n            fprintf(ofl, \"gmt psxy $J $R -Si${ts} -Gred -Wblack -O -K << EOF >> ${outps}\\n\");\n            for (i=0; i<nobs; i++)\n            {\n                if (pol[i] ==-1)\n                {\n                    fprintf(ofl, \"%8.3f %8.3f %s\\n\", data[i].header.stlo,\n                            data[i].header.stla, data[i].header.kstnm);\n                }\n            }\n            fprintf(ofl, \"EOF\\n\");\n        }\n        free(pol);\n    }\n\n    fprintf(ofl, \"# Plot the station names\\n\");\n    fprintf(ofl, \"gmt pstext $J $R -F+f8p+a0+jCT -D0%s-4p -O << EOF >> ${outps}\\n\",\n            forwardSlash);\n    for (i=0; i<nobs; i++)\n    {\n        fprintf(ofl, \"%8.3f %8.3f %s\\n\", data[i].header.stlo,\n                data[i].header.stla, data[i].header.kstnm);\n    }\n    fprintf(ofl, \"EOF\\n\");\n    fprintf(ofl, \"gmt psconvert -A -Tj ${outps}\\n\");\n    fprintf(ofl, \"rm ${outps}\\n\");\n    fclose(ofl);\n    chmod(globalMap.outputScript, 0755);\n    return 0;\n}\n//============================================================================//\nint postmt_gmtHelper_writeThetaBoxes(const bool lappend, const bool lclose,\n                                     const char *outputScript,\n                                     const char *psFile,\n                                     const int nt,\n                                     const int ithetaOpt,\n                                     const double *__restrict__ thetas,\n                                     const double *__restrict__ thetaHist)\n{\n    FILE *ofl;\n    char color[32], app[8], more[8], shift[8];\n    double *cumTheta, *h, hAvg, thetaAvg, tmax;\n    int i, ierr;\n    const bool lwritePrior = true;\n    tmax = array_max64f(nt, thetaHist, &ierr);\n    // Compute h\n    h = memory_calloc64f(nt);\n    compearth_theta2h(nt, thetas, h);\n    thetaAvg = -30.0;\n    memset(app, 0, 8*sizeof(char));\n    memset(more, 0, 8*sizeof(char));\n    memset(shift, 0, 8*sizeof(char));\n    if (!lappend)\n    {\n        ofl = fopen(outputScript, \"w\");\n        fprintf(ofl, \"#!/bin/bash\\n\");\n        /*\n        fprintf(ofl, \"gmt gmtset FONT_LABEL 12p\\n\");\n        fprintf(ofl, \"gmt gmtset MAP_LABEL_OFFSET 0.1c\\n\");\n        */\n        fprintf(ofl, \"parms=\\\"--FONT_LABEL=10p --MAP_LABEL_OFFSET=0.1c --PROJ_LENGTH_UNIT=cm\\\"\\n\");\n        fprintf(ofl, \"psfl=%s\\n\", psFile);\n    }\n    else\n    {\n        ofl = fopen(outputScript, \"a\");\n        strcpy(app, \"-O\\0\");\n        strcpy(more, \">\\0\");\n        strcpy(shift, \"-Y4.0\\0\");\n    }\n    fprintf(ofl,\n/*\n            \"gmt psbasemap -JX5i/1i %s -R0/90/0/%.2f -Bg10a10:\\\"Dips (deg)\\\":/a%.2f:\\\"Likelihood\\\":WSn -P %s -K >%s ${psfl}\\n\",\n*/\n            \"gmt psbasemap -JX5i/1i %s -R0/90/0/%.2f -Bpxg10a10+l:\\\"Dips (deg)\\\" -Bpya%.2f+l:\\\"Likelihood\\\" -BWSnn -P %s -K ${parms} >%s ${psfl}\\n\",\n            shift, tmax*1.1, tmax*0.2, app, more);\n    setFillColor(0, ithetaOpt, color);\n    if (nt > 1)\n    {\n       fprintf(ofl, \"gmt psxy -R -J -Wblack %s -O -K << EOF >> ${psfl}\\n\", color);\n    }\n    else\n    {\n       fprintf(ofl, \"gmt psxy -R -J -Wblack %s -O << EOF >> ${psfl}\\n\", color);\n    }\n    fprintf(ofl, \"%f %f\\n\", 0.0, 0.0);\n    fprintf(ofl, \"%f %f\\n\", 0.0, thetaHist[0]);\n    for (i=0; i<nt-1; i++)\n    {\n        hAvg = 0.5*(h[i] + h[i+1]);\n        compearth_h2theta(1, &hAvg, &thetaAvg);\n        fprintf(ofl, \"%f %f\\n\", thetaAvg*180.0/M_PI, thetaHist[i]);\n        fprintf(ofl, \"%f %f\\n\", thetaAvg*180.0/M_PI, 0.0);\n        fprintf(ofl, \"EOF\\n\");\n        setFillColor(i+1, ithetaOpt, color);\n        if (i < nt - 2 || lwritePrior)\n        {\n            fprintf(ofl, \"gmt psxy -R -J -Wblack %s -O -K << EOF >> ${psfl}\\n\", color);\n        }\n        else\n        {\n            fprintf(ofl, \"gmt psxy -R -J -Wblack %s -O << EOF >> ${psfl}\\n\", color);\n        }\n        fprintf(ofl, \"%f %f\\n\", thetaAvg*180.0/M_PI, 0.0);\n        fprintf(ofl, \"%f %f\\n\", thetaAvg*180.0/M_PI, thetaHist[i+1]);\n    }\n    fprintf(ofl, \"%f %f\\n\", 90.0, thetaHist[nt-1]);\n    fprintf(ofl, \"%f %f\\n\", 90.0, 0.0);\n    fprintf(ofl, \"EOF\\n\");\n    // Write the prior distribution\n    if (lwritePrior)\n    {   \n        fprintf(ofl, \"gmt psxy -R -J -W1,black -O -K << EOF >> ${psfl}\\n\");\n        fprintf(ofl, \"%f %f\\n\", 00.0, 1.0/(double) nt);\n        fprintf(ofl, \"%f %f\\n\", 90.0, 1.0/(double) nt);\n        fprintf(ofl, \"EOF\\n\");\n    }\n    // Write the CDF\n/*\n    fprintf(ofl, \"gmt psbasemap -R0/90/0/1.05 -J -Bp0.2/a0.2:\\\"CDF\\\":E -O -K >> ${psfl}\\n\");\n*/\n    fprintf(ofl, \"gmt psbasemap -R0/90/0/1.05 -J -Bpx0.2 -Bpya0.2+l\\\"CDF\\\" -BE -O -K ${parms} >> ${psfl}\\n\");\n    cumTheta = array_cumsum64f(nt, thetaHist, &ierr);\n    if (lclose)\n    {\n        fprintf(ofl, \"gmt psxy -R -J -W1,blue -O << EOF >> ${psfl}\\n\");\n    }\n    else\n    {\n        fprintf(ofl, \"gmt psxy -R -J -W1,blue -O -K << EOF >> ${psfl}\\n\");\n    }\n    for (i=0; i<nt; i++)\n    {   \n        fprintf(ofl, \"%f %f\\n\", thetas[i]*180/M_PI, cumTheta[i]);\n    }   \n    fprintf(ofl, \"EOF\\n\");\n    if (lclose)\n    {\n        //fprintf(ofl, \"gmt psconvert -A -Tj ${psfl}\\n\");\n        //fprintf(ofl, \"rm ${psfl}\\n\");\n        fprintf(ofl, \"gmt psconvert -A -Tf ${psfl}\\n\");\n        fprintf(ofl, \"/bin/rm ${psfl}\\n\"); \n    }\n    memory_free64f(&cumTheta);\n    memory_free64f(&h);\n    fclose(ofl);\n    chmod(outputScript, 0755);\n    return 0;\n}\n//============================================================================//\nint postmt_gmtHelper_writeSigmaBoxes(const bool lappend, const bool lclose,\n                                     const char *outputScript,\n                                     const char *psFile,\n                                     const int ns,\n                                     const int isigmaOpt,\n                                     const double *__restrict__ sigmas,\n                                     const double *__restrict__ sigmaHist)\n{\n    FILE *ofl;\n    char color[32], app[8], more[8], shift[8];\n    double *cumSigma, ds, smax;\n    int i, ierr;\n    const bool lwritePrior = true;\n    smax = array_max64f(ns, sigmaHist, &ierr);\n    // Take averages\n    ds = 0.0;\n    memset(app, 0, 8*sizeof(char));\n    memset(more, 0, 8*sizeof(char));\n    memset(shift, 0, 8*sizeof(char));\n    if (!lappend)\n    {\n        ofl = fopen(outputScript, \"w\");\n        fprintf(ofl, \"#!/bin/bash\\n\");\n        /*\n        fprintf(ofl, \"gmt gmtset FONT_LABEL 12p\\n\");\n        fprintf(ofl, \"gmt gmtset MAP_LABEL_OFFSET 0.1c\\n\");\n        */\n        fprintf(ofl, \"parms=\\\"--FONT_LABEL=10p --MAP_LABEL_OFFSET=0.1c --PROJ_LENGTH_UNIT=cm\\\"\\n\");\n        fprintf(ofl, \"psfl=%s\\n\", psFile);\n    }\n    else\n    {\n        ofl = fopen(outputScript, \"a\");\n        strcpy(app, \"-O\\0\");\n        strcpy(more, \">\\0\");\n        strcpy(shift, \"-Y4.0\\0\");\n    }\n    fprintf(ofl,\n/*\n           \"gmt psbasemap -JX5i/1i %s -R-90/90/0/%.2f -Bg15a15:\\\"Slips (deg)\\\":/a%.2f:\\\"Likelihood\\\":WSn -P %s -K >%s ${psfl}\\n\",\n*/\n            \"gmt psbasemap -JX5i/1i %s -R-90/90/0/%.2f -Bpxg15a15+l\\\"Slips (deg)\\\" -Bpya%.2f+l\\\"Likelihood\\\" -BWSn -P %s -K ${parms} >%s ${psfl}\\n\",\n            shift, smax*1.1, smax*0.2, app, more);\n    setFillColor(0, isigmaOpt, color);\n    if (ns > 1)\n    {\n       fprintf(ofl, \"gmt psxy -R -J -Wblack %s -O -K << EOF >> ${psfl}\\n\", color);\n       ds = (sigmas[1] - sigmas[0])*180.0/M_PI;\n    }\n    else\n    {\n       fprintf(ofl, \"gmt psxy -R -J -Wblack %s -O << EOF >> ${psfl}\\n\", color);\n    }\n    fprintf(ofl, \"%.2f %f\\n\", -90.0, 0.0);\n    fprintf(ofl, \"%.2f %f\\n\", -90.0, sigmaHist[0]);\n    for (i=0; i<ns-1; i++)\n    {   \n        fprintf(ofl, \"%.2f %f\\n\", -90.0 + (double) (i+1)*ds, sigmaHist[i]);\n        fprintf(ofl, \"%.2f %f\\n\", -90.0 + (double) (i+1)*ds, 0.0);\n        fprintf(ofl, \"EOF\\n\");\n        setFillColor(i+1, isigmaOpt, color);\n        if (i < ns - 2 || lwritePrior)\n        {\n            fprintf(ofl, \"gmt psxy -R -J -Wblack %s -O -K << EOF >> ${psfl}\\n\", color);\n        }\n        else\n        {\n            fprintf(ofl, \"gmt psxy -R -J -Wblack %s -O << EOF >> ${psfl}\\n\", color);\n        }\n        fprintf(ofl, \"%.2f %f\\n\", -90.0 + (double) (i+1)*ds, 0.0);\n        fprintf(ofl, \"%.2f %f\\n\", -90.0 + (double) (i+1)*ds, sigmaHist[i+1]);\n    }\n    fprintf(ofl, \"%.2f %f\\n\", 90.0, sigmaHist[ns-1]);\n    fprintf(ofl, \"%.2f %f\\n\", 90.0, 0.0);\n    fprintf(ofl, \"EOF\\n\");\n    // Write the prior distribution\n    if (lwritePrior)\n    {   \n        fprintf(ofl, \"gmt psxy -R -J -W1,black -O -K << EOF >> ${psfl}\\n\");\n        fprintf(ofl, \"%f %f\\n\",-90.0, 1.0/(double) ns);\n        fprintf(ofl, \"%f %f\\n\", 90.0, 1.0/(double) ns);\n        fprintf(ofl, \"EOF\\n\");\n    }\n    // Write the CDF\n/*\n    fprintf(ofl, \"gmt psbasemap -R-90/90/0/1.05 -J -Bp0.2/a0.2:\\\"CDF\\\":E -O -K >> ${psfl}\\n\");\n*/\n    fprintf(ofl, \"gmt psbasemap -R-90/90/0/1.05 -J -Bpx0.2 -Bpya0.2+l\\\"CDF\\\" -BE -O -K ${parms} >> ${psfl}\\n\");\n    cumSigma = array_cumsum64f(ns, sigmaHist, &ierr);\n    if (lclose)\n    {\n        fprintf(ofl, \"gmt psxy -R -J -W1,blue -O << EOF >> ${psfl}\\n\");\n    }\n    else\n    {\n        fprintf(ofl, \"gmt psxy -R -J -W1,blue -O -K << EOF >> ${psfl}\\n\");\n    }\n    for (i=0; i<ns; i++)\n    {\n        fprintf(ofl, \"%f %f\\n\", sigmas[i]*180/M_PI, cumSigma[i]);\n    }   \n    fprintf(ofl, \"EOF\\n\");\n    if (lclose)\n    {    \n        //fprintf(ofl, \"gmt psconvert -A -Tj ${psfl}\\n\");\n        //fprintf(ofl, \"rm ${psfl}\\n\");\n        fprintf(ofl, \"gmt psconvert -A -Tf ${psfl}\\n\");\n        fprintf(ofl, \"/bin/rm ${psfl}\\n\");\n    }\n    memory_free64f(&cumSigma);\n    fclose(ofl);\n    chmod(outputScript, 0755);\n    return 0;\n}\n\n//============================================================================//\nint postmt_gmtHelper_writeKappaBoxes(const bool lappend, const bool lclose,\n                                     const char *outputScript,\n                                     const char *psFile,\n                                     const int nk,\n                                     const int kappaOpt,\n                                     const double *__restrict__ kappas,\n                                     const double *__restrict__ kappaHist)\n{\n    FILE *ofl;\n    char color[32], app[8], more[8], shift[8];\n    double *cumKappa, dk, kmax;\n    int i, ierr;\n    const bool lwritePrior = true;\n    kmax = array_max64f(nk, kappaHist, &ierr);\n    // Take averages\n    dk = 0.0;\n    memset(app, 0, 8*sizeof(char));\n    memset(more, 0, 8*sizeof(char));\n    memset(shift, 0, 8*sizeof(char));\n    if (!lappend)\n    {\n        ofl = fopen(outputScript, \"w\");\n        fprintf(ofl, \"#!/bin/bash\\n\");\n        /*\n        fprintf(ofl, \"gmt gmtset FONT_LABEL 12p\\n\");\n        fprintf(ofl, \"gmt gmtset MAP_LABEL_OFFSET 0.1c\\n\");\n        */\n        fprintf(ofl, \"parms=\\\"--FONT_LABEL=10p --MAP_LABEL_OFFSET=0.1c --PROJ_LENGTH_UNIT=cm\\\"\\n\");\n        fprintf(ofl, \"psfl=%s\\n\", psFile);\n    }\n    else\n    {\n        ofl = fopen(outputScript, \"a\");\n        strcpy(app, \"-O\\0\");\n        strcpy(more, \">\\0\");\n        strcpy(shift, \"-Y4.0\\0\");\n    }\n    fprintf(ofl,\n/*\n            \"gmt psbasemap -JX5i/1i %s -R0/360/0/%.2f -Bg30a30:\\\"Strike (deg)\\\":/a%.2f:\\\"Likelihood\\\":WSn -P %s -K >%s ${psfl}\\n\",\n*/\n            \"gmt psbasemap -JX5i/1i %s -R0/360/0/%.2f -Bpxg30a30+l\\\"Strike (deg)\\\" -Bpya%.2f+l\\\"Likelihood\\\" -BWSn -P %s -K ${parms} >%s ${psfl}\\n\",\n            shift, kmax*1.1, kmax*0.2, app, more);\n    setFillColor(0, kappaOpt, color);\n    if (nk > 1)\n    {\n       fprintf(ofl, \"gmt psxy -R -J -Wblack %s -O -K << EOF >> ${psfl}\\n\", color);\n       dk = (kappas[1] - kappas[0])*180.0/M_PI;\n    }\n    else\n    {\n       fprintf(ofl, \"gmt psxy -R -J -Wblack %s -O << EOF >> ${psfl}\\n\", color);\n    }\n    fprintf(ofl, \"%.2f %f\\n\", 0.0, 0.0);\n    fprintf(ofl, \"%.2f %f\\n\", 0.0, kappaHist[0]);\n    for (i=0; i<nk-1; i++)\n    {\n        fprintf(ofl, \"%.2f %f\\n\", 0.0 + (double) (i+1)*dk, kappaHist[i]);\n        fprintf(ofl, \"%.2f %f\\n\", 0.0 + (double) (i+1)*dk, 0.0);\n        fprintf(ofl, \"EOF\\n\");\n        setFillColor(i+1, kappaOpt, color);\n        if (i < nk - 2 || lwritePrior)\n        {\n            fprintf(ofl, \"gmt psxy -R -J -Wblack %s -O -K << EOF >> ${psfl}\\n\", color);\n        }\n        else\n        {\n            fprintf(ofl, \"gmt psxy -R -J -Wblack %s -O << EOF >> ${psfl}\\n\", color);\n        }\n        fprintf(ofl, \"%.2f %f\\n\", 0.0 + (double) (i+1)*dk, 0.0);\n        fprintf(ofl, \"%.2f %f\\n\", 0.0 + (double) (i+1)*dk, kappaHist[i+1]);\n    }   \n    fprintf(ofl, \"%.2f %f\\n\", 360.0, kappaHist[nk-1]);\n    fprintf(ofl, \"%.2f %f\\n\", 360.0, 0.0);\n    fprintf(ofl, \"EOF\\n\");\n    // Write the prior distribution\n    if (lwritePrior)\n    {   \n        fprintf(ofl, \"gmt psxy -R -J -W1,black -O -K << EOF >> ${psfl}\\n\");\n        fprintf(ofl, \"%f %f\\n\", 0.0,   1.0/(double) nk);\n        fprintf(ofl, \"%f %f\\n\", 360.0, 1.0/(double) nk);\n        fprintf(ofl, \"EOF\\n\");\n    }\n    // Write the CDF\n/*\n    fprintf(ofl, \"gmt psbasemap -R0/360/0/1.05 -J -Bp0.2/a0.2:\\\"CDF\\\":E -O -K >> ${psfl}\\n\");\n*/\n    fprintf(ofl, \"gmt psbasemap -R0/360/0/1.05 -J -Bpx0.2 -Bpya0.2+l\\\"CDF\\\" -BE -O -K ${parms} >> ${psfl}\\n\");\n    cumKappa = array_cumsum64f(nk, kappaHist, &ierr);\n    if (lclose)\n    {\n        fprintf(ofl, \"gmt psxy -R -J -W1,blue -O << EOF >> ${psfl}\\n\");\n    }\n    else\n    {\n        fprintf(ofl, \"gmt psxy -R -J -W1,blue -O -K << EOF >> ${psfl}\\n\");\n    }\n    for (i=0; i<nk; i++)\n    {   \n        fprintf(ofl, \"%f %f\\n\", kappas[i]*180.0/M_PI, cumKappa[i]);\n    }   \n    fprintf(ofl, \"EOF\\n\");\n    if (lclose)\n    {\n        //fprintf(ofl, \"gmt psconvert -A -Tj ${psfl}\\n\");\n        //fprintf(ofl, \"rm ${psfl}\\n\");\n        fprintf(ofl, \"gmt psconvert -A -Tf ${psfl}\\n\");\n        fprintf(ofl, \"/bin/rm ${psfl}\\n\");\n    }\n    memory_free64f(&cumKappa);\n    fclose(ofl);\n    chmod(outputScript, 0755);\n    return 0;\n}\n//============================================================================//\nint postmt_gmtHelper_writeDepthBoxes(const bool lappend, const bool lclose,\n                                     const char *outputScript,\n                                     const char *psFile,\n                                     const int nd,\n                                     const int idepOpt,\n                                     const double *__restrict__ deps,\n                                     const double *__restrict__ depHist)\n{\n    FILE *ofl;\n    char color[32], app[8], more[8], shift[8];\n    double *cumDep, dd, dmax, depMin, depMax;\n    int i, ierr;\n    const bool lwritePrior = true;\n    // Compute moment magnitudes \n    dmax = array_max64f(nd, depHist, &ierr);\n    dd = 0.1;\n    if (nd > 1){dd = deps[1] - deps[0];};\n    depMin = fmax(0.0, deps[0]    - dd/2.0);\n    depMax = fmax(0.0, deps[nd-1] + dd/2.0);\n    memset(app, 0, 8*sizeof(char));\n    memset(more, 0, 8*sizeof(char));\n    memset(shift, 0, 8*sizeof(char));\n    if (!lappend)\n    {\n        ofl = fopen(outputScript, \"w\");\n        fprintf(ofl, \"#!/bin/bash\\n\");\n        /*\n        fprintf(ofl, \"gmt gmtset FONT_LABEL 12p\\n\");\n        fprintf(ofl, \"gmt gmtset MAP_LABEL_OFFSET 0.1c\\n\");\n        */\n        fprintf(ofl, \"psfl=%s\\n\", psFile);\n    }\n    else\n    {\n        ofl = fopen(outputScript, \"a\");\n        strcpy(app, \"-O\\0\");\n        strcpy(more, \">\\0\");\n        strcpy(shift, \"-Y4.0\\0\");\n    }\n    fprintf(ofl,\n/*\n            \"gmt psbasemap -JX5i/1i %s -R%.1f/%.1f/0/%.2f -Bg%fa%f:\\\"Depths (km)\\\":/a%.2f:\\\"Likelihood\\\":WSn -P %s -K >%s ${psfl}\\n\",\n*/\n            \"gmt psbasemap -JX5i/1i %s -R%.1f/%.1f/0/%.2f -Bpxg%fa%f+l\\\"Depths (km)\\\" -Bpya%.2f+l\\\"Likelihood\\\" -BWSn -P %s -K ${parms} >%s ${psfl}\\n\",\n            shift, depMin, depMax, dmax*1.1, dd, (nd-1)*dd/5.0, dmax*0.2, app, more);\n    setFillColor(0, idepOpt, color);\n    if (nd > 1)\n    {\n       fprintf(ofl, \"gmt psxy -R -J -Wblack %s -O -K << EOF >> ${psfl}\\n\", color);\n    }\n    else\n    {\n       fprintf(ofl, \"gmt psxy -R -J -Wblack %s -O << EOF >> ${psfl}\\n\", color);\n    }\n    fprintf(ofl, \"%.2f %f\\n\", depMin, 0.0);\n    fprintf(ofl, \"%.2f %f\\n\", depMin, depHist[0]);\n    for (i=0; i<nd-1; i++)\n    {\n        fprintf(ofl, \"%.2f %f\\n\", depMin + (double) (i+1)*dd, depHist[i]);\n        fprintf(ofl, \"%.2f %f\\n\", depMin + (double) (i+1)*dd, 0.0);\n        fprintf(ofl, \"EOF\\n\");\n        setFillColor(i+1, idepOpt, color);\n        if (i < nd - 2 || lwritePrior)\n        {   \n            fprintf(ofl, \"gmt psxy -R -J -Wblack %s -O -K << EOF >> ${psfl}\\n\", color);\n        }\n        else\n        {   \n            fprintf(ofl, \"gmt psxy -R -J -Wblack %s -O << EOF >> ${psfl}\\n\", color);\n        }\n        fprintf(ofl, \"%.2f %f\\n\", depMin + (double) (i+1)*dd, 0.0);\n        fprintf(ofl, \"%.2f %f\\n\", depMin + (double) (i+1)*dd, depHist[i+1]);\n    }\n    fprintf(ofl, \"%.2f %f\\n\", depMax, depHist[nd-1]);\n    fprintf(ofl, \"%.2f %f\\n\", depMax, 0.0);\n    fprintf(ofl, \"EOF\\n\"); \n    // Write the prior distribution\n    if (lwritePrior) \n    {   \n        fprintf(ofl, \"gmt psxy -R -J -W1,black -O -K << EOF >> ${psfl}\\n\");\n        fprintf(ofl, \"%f %f\\n\", depMin, 1.0/(double) nd);\n        fprintf(ofl, \"%f %f\\n\", depMax, 1.0/(double) nd);\n        fprintf(ofl, \"EOF\\n\");\n    }\n    // Write the CDF\n/*\n    fprintf(ofl, \"gmt psbasemap -R%f/%f/0/1.05 -J -Bp0.2/a0.2:\\\"CDF\\\":E -O -K >> ${psfl}\\n\", depMin, depMax);\n*/\n    fprintf(ofl, \"gmt psbasemap -R%f/%f/0/1.05 -J -Bpx0.2 -Bpya0.2+l\\\"CDF\\\" -BE -O -K ${parms} >> ${psfl}\\n\", depMin, depMax);\n    cumDep = array_cumsum64f(nd, depHist, &ierr);\n    if (lclose)\n    {\n        fprintf(ofl, \"gmt psxy -R -J -W1,blue -O << EOF >> ${psfl}\\n\");\n    }\n    else\n    {\n        fprintf(ofl, \"gmt psxy -R -J -W1,blue -O -K << EOF >> ${psfl}\\n\");\n    }\n    for (i=0; i<nd; i++)\n    {\n        fprintf(ofl, \"%f %f\\n\", deps[i], cumDep[i]);\n    }\n    fprintf(ofl, \"EOF\\n\");\n    if (lclose)\n    {    \n        //fprintf(ofl, \"gmt psconvert -A -Tj ${psfl}\\n\");\n        //fprintf(ofl, \"rm ${psfl}\\n\");\n        fprintf(ofl, \"gmt psconvert -A -Tf ${psfl}\\n\");\n        fprintf(ofl, \"/bin/rm ${psfl}\\n\");\n    }\n    memory_free64f(&cumDep);\n    fclose(ofl);\n    chmod(outputScript, 0755);\n    return 0;\n}\n//============================================================================//\nint postmt_gmtHelper_writeMagnitudeBoxes(const bool lappend, const bool lclose,\n                                         const char *outputScript,\n                                         const char *psFile,\n                                         const int nm,\n                                         const int magOpt,\n                                         const double *__restrict__ M0s,\n                                         const double *__restrict__ magHist)\n{\n    FILE *ofl;\n    char color[32], app[8], more[8], shift[8];\n    double *cumMag, *Mw, dm, mmax, mwMin, mwMax;\n    int i, ierr;\n    const bool lwritePrior = true;\n    // Compute moment magnitudes \n    Mw = memory_calloc64f(nm);\n    mmax = array_max64f(nm, magHist, &ierr);\n    compearth_m02mw(nm, CE_KANAMORI_1978, M0s, Mw);\n    dm = 0.1;\n    if (nm > 1){dm = Mw[1] - Mw[0];};\n    mwMin = Mw[0] - dm/2.0;\n    mwMax = Mw[nm-1] + dm/2.0;\n    memset(app, 0, 8*sizeof(char));\n    memset(more, 0, 8*sizeof(char));\n    memset(shift, 0, 8*sizeof(char));\n    if (!lappend)\n    {\n        ofl = fopen(outputScript, \"w\");\n        fprintf(ofl, \"#!/bin/bash\\n\");\n        /*\n        fprintf(ofl, \"gmt gmtset FONT_LABEL 12p\\n\");\n        fprintf(ofl, \"gmt gmtset MAP_LABEL_OFFSET 0.1c\\n\");\n        */\n        fprintf(ofl, \"parms=\\\"--FONT_LABEL=10p --MAP_LABEL_OFFSET=0.1c --PROJ_LENGTH_UNIT=cm\\\"\\n\");\n        fprintf(ofl, \"psfl=%s\\n\", psFile);\n    }\n    else\n    {\n        ofl = fopen(outputScript, \"a\");\n        strcpy(app, \"-O\\0\");\n        strcpy(more, \">\\0\");\n        strcpy(shift, \"-Y4.0\\0\");\n    }\n    fprintf(ofl,\n/*\n            \"gmt psbasemap -JX5i/1i %s -R%.2f/%.2f/0/%.2f -Bg%fa%f:\\\"Magnitude (Mw)\\\":/a%.2f:\\\"Likelihood\\\":WSn -P %s -K >%s ${psfl}\\n\",\n*/\n            \"gmt psbasemap -JX5i/1i %s -R%.2f/%.2f/0/%.2f -Bpxg%fa%f+l\\\"Magnitude (Mw)\\\" -Bpya%.2f+l\\\"Likelihood\\\" -BWSn -P %s -K ${parms} >%s ${psfl}\\n\",\n            shift, mwMin, mwMax, mmax*1.1, dm, (nm-1)*dm/5.0, mmax*0.2, app, more);\n    setFillColor(0, magOpt, color);\n    if (nm > 1)\n    {\n       fprintf(ofl, \"gmt psxy -R -J -Wblack %s -O -K << EOF >> ${psfl}\\n\", color);\n    }\n    else\n    {\n       fprintf(ofl, \"gmt psxy -R -J -Wblack %s -O << EOF >> ${psfl}\\n\", color);\n    }   \n    fprintf(ofl, \"%.2f %f\\n\", mwMin, 0.0);\n    fprintf(ofl, \"%.2f %f\\n\", mwMin, magHist[0]);\n    for (i=0; i<nm-1; i++)\n    {\n        fprintf(ofl, \"%.2f %f\\n\", mwMin + (double) (i+1)*dm, magHist[i]);\n        fprintf(ofl, \"%.2f %f\\n\", mwMin + (double) (i+1)*dm, 0.0);\n        fprintf(ofl, \"EOF\\n\");\n        setFillColor(i+1, magOpt, color);\n        if (i < nm - 2 || lwritePrior)\n        {   \n            fprintf(ofl, \"gmt psxy -R -J -Wblack %s -O -K << EOF >> ${psfl}\\n\", color);\n        }\n        else\n        {\n            fprintf(ofl, \"gmt psxy -R -J -Wblack %s -O << EOF >> ${psfl}\\n\", color);\n        }\n        fprintf(ofl, \"%.2f %f\\n\", mwMin + (double) (i+1)*dm, 0.0);\n        fprintf(ofl, \"%.2f %f\\n\", mwMin + (double) (i+1)*dm, magHist[i+1]);\n    }\n    fprintf(ofl, \"%.2f %f\\n\", mwMax, magHist[nm-1]);\n    fprintf(ofl, \"%.2f %f\\n\", mwMax, 0.0);\n    fprintf(ofl, \"EOF\\n\");\n    // Write the prior distribution\n    if (lwritePrior)\n    {   \n        fprintf(ofl, \"gmt psxy -R -J -W1,black -O -K << EOF >> ${psfl}\\n\");\n        fprintf(ofl, \"%f %f\\n\", mwMin, 1.0/(double) nm);\n        fprintf(ofl, \"%f %f\\n\", mwMax, 1.0/(double) nm);\n        fprintf(ofl, \"EOF\\n\");\n    }\n    // Write the CDF\n/*\n    fprintf(ofl, \"gmt psbasemap -R%f/%f/0/1.05 -J -Bp0.2/a0.2:\\\"CDF\\\":E -O -K >> ${psfl}\\n\", mwMin, mwMax);\n*/\n    fprintf(ofl, \"gmt psbasemap -R%f/%f/0/1.05 -J -Bpx0.2 -Bpya0.2+l\\\"CDF\\\" -BE -O -K ${parms} >> ${psfl}\\n\", mwMin, mwMax);\n    cumMag = array_cumsum64f(nm, magHist, &ierr);\n    if (lclose)\n    {\n        fprintf(ofl, \"gmt psxy -R -J -W1,blue -O << EOF >> ${psfl}\\n\");\n    }\n    else\n    {\n        fprintf(ofl, \"gmt psxy -R -J -W1,blue -O -K << EOF >> ${psfl}\\n\");\n    }\n    for (i=0; i<nm; i++)\n    {\n        fprintf(ofl, \"%f %f\\n\", Mw[i], cumMag[i]);\n    }\n    fprintf(ofl, \"EOF\\n\");\n    if (lclose)\n    {    \n        //fprintf(ofl, \"gmt psconvert -A -Tj ${psfl}\\n\");\n        //fprintf(ofl, \"rm ${psfl}\\n\");\n    }\n    fclose(ofl);\n    memory_free64f(&cumMag);\n    memory_free64f(&Mw);\n    chmod(outputScript, 0755);\n    return 0;\n}\n//============================================================================//\nint postmt_gmtHelper_writeGammaBoxes(const bool lappend, const bool lclose,\n                                     const char *outputScript,\n                                     const char *psFile,\n                                     const int ng,\n                                     const int igammaOpt,\n                                     const double *__restrict__ gammas,\n                                     const double *__restrict__ gammaHist)\n{\n    FILE *ofl;\n    char color[32], app[8], more[8], shift[8];\n    double *cumGamma, *v, gmax, gammaAvg, vAvg;\n    int i, ierr;\n    const bool lwritePrior = true;\n    gmax = array_max64f(ng, gammaHist, &ierr);\n    // Compute v\n    v = memory_calloc64f(ng);\n    compearth_gamma2v(ng, gammas, v);\n    // Take averages\n    gammaAvg = -30.0;\n    memset(app, 0, 8*sizeof(char));\n    memset(shift, 0, 8*sizeof(char));\n    memset(more, 0, 8*sizeof(char));\n    if (!lappend)\n    {\n        ofl = fopen(outputScript, \"w\");\n        fprintf(ofl, \"#!/bin/bash\\n\");\n        /*\n        fprintf(ofl, \"gmt gmtset FONT_LABEL 12p\\n\");\n        fprintf(ofl, \"gmt gmtset MAP_LABEL_OFFSET 0.1c\\n\");\n        */\n        fprintf(ofl, \"parms=\\\"--FONT_LABEL=10p --MAP_LABEL_OFFSET=0.1c --PROJ_LENGTH_UNIT=cm\\\"\\n\");\n        fprintf(ofl, \"psfl=%s\\n\", psFile);\n    }\n    else\n    {\n        ofl = fopen(outputScript, \"a\");\n        strcpy(app, \"-O\\0\");\n        strcpy(more, \">\\0\");\n        strcpy(shift, \"-Y4.0\\0\");\n    }\n    fprintf(ofl,\n/*\n            \"gmt psbasemap -JX5i/1i %s -R-30/30/0/%.2f -Bg5a5:\\\"Longitude (deg)\\\":/a%.2f:\\\"Likelihood\\\":WSn -P %s -K >%s ${psfl}\\n\",\n*/\n            \"gmt psbasemap -JX5i/1i %s -R-30/30/0/%.2f -Bpxg5a5+l\\\"Longitude (deg)\\\" -Bpya%.2f+l\\\"Likelihood\\\" -BWSn -P %s -K ${parms} >%s ${psfl}\\n\",\n            shift, gmax*1.1, gmax*0.2, app, more);\n    setFillColor(0, igammaOpt, color);\n    if (ng > 1)\n    {\n       fprintf(ofl, \"gmt psxy -R -J -Wblack %s -O -K << EOF >> ${psfl}\\n\", color);\n    }\n    else\n    {\n       fprintf(ofl, \"gmt psxy -R -J -Wblack %s -O << EOF >> ${psfl}\\n\", color);\n    }\n    fprintf(ofl, \"%f %f\\n\", -30.0, 0.0);\n    fprintf(ofl, \"%f %f\\n\", -30.0, gammaHist[0]);\n    for (i=0; i<ng-1; i++)\n    {\n        vAvg = 0.5*(v[i] + v[i+1]);\n        compearth_v2gamma(1, &vAvg, &gammaAvg);\n        fprintf(ofl, \"%f %f\\n\", gammaAvg*180.0/M_PI, gammaHist[i]);\n        fprintf(ofl, \"%f %f\\n\", gammaAvg*180.0/M_PI, 0.0);\n        fprintf(ofl, \"EOF\\n\");\n        setFillColor(i+1, igammaOpt, color);\n        if (i < ng - 2 || lwritePrior)\n        {\n            fprintf(ofl, \"gmt psxy -R -J -Wblack %s -O -K << EOF >> ${psfl}\\n\", color);\n        }\n        else\n        {\n            fprintf(ofl, \"gmt psxy -R -J -Wblack %s -O << EOF >> ${psfl}\\n\", color);\n        }\n        fprintf(ofl, \"%f %f\\n\", gammaAvg*180.0/M_PI, 0.0);\n        fprintf(ofl, \"%f %f\\n\", gammaAvg*180.0/M_PI, gammaHist[i+1]);\n    }\n    fprintf(ofl, \"%f %f\\n\", 30.0, gammaHist[ng-1]);\n    fprintf(ofl, \"%f %f\\n\", 30.0, 0.0);\n    fprintf(ofl, \"EOF\\n\");\n    // Write the prior distribution\n    if (lwritePrior)\n    {\n        fprintf(ofl, \"gmt psxy -R -J -W1,black -O -K << EOF >> ${psfl}\\n\");\n        fprintf(ofl, \"%f %f\\n\",-30.0, 1.0/(double) ng);\n        fprintf(ofl, \"%f %f\\n\", 30.0, 1.0/(double) ng);\n        fprintf(ofl, \"EOF\\n\");\n    }\n    // Write the CDF\n/*\n    fprintf(ofl, \"gmt psbasemap -R-30/30/0/1.05 -J -Bp0.2/a0.2:\\\"CDF\\\":E -O -K >> ${psfl}\\n\");\n*/\n    fprintf(ofl, \"gmt psbasemap -R-30/30/0/1.05 -J -Bpx0.2 -Bpya0.2+l\\\"CDF\\\" -BE -O -K ${parms} >> ${psfl}\\n\");\n    cumGamma = array_cumsum64f(ng, gammaHist, &ierr);\n    if (lclose)\n    {\n        fprintf(ofl, \"gmt psxy -R -J -W1,blue -O << EOF >> ${psfl}\\n\");\n    }\n    else\n    {\n        fprintf(ofl, \"gmt psxy -R -J -W1,blue -O -K << EOF >> ${psfl}\\n\");\n    }\n    for (i=0; i<ng; i++)\n    {   \n        fprintf(ofl, \"%f %f\\n\", gammas[i]*180.0/M_PI, cumGamma[i]);\n    }   \n    fprintf(ofl, \"EOF\\n\");\n    if (lclose)\n    {    \n        //fprintf(ofl, \"gmt psconvert -A -Tj ${psfl}\\n\");\n        //fprintf(ofl, \"rm ${psfl}\\n\");\n        fprintf(ofl, \"gmt psconvert -A -Tf ${psfl}\\n\");\n        fprintf(ofl, \"/bin/rm ${psfl}\\n\");\n    }\n    memory_free64f(&cumGamma);\n    memory_free64f(&v);\n    fclose(ofl);\n    chmod(outputScript, 0755);\n    return 0;\n}\n//============================================================================//\nint postmt_gmtHelper_writeBetaBoxes(const bool lappend, const bool lclose,\n                                    const char *outputScript,\n                                    const char *psFile,\n                                    const int nb,\n                                    const int ibetaOpt,\n                                    const double *__restrict__ betas,\n                                    const double *__restrict__ betaHist)\n{\n    FILE *ofl;\n    char color[32], app[8], more[8], shift[8];\n    double *betaCum, *u, bmax, betaAvg, uAvg;\n    int i, ierr;\n    const bool lwritePrior = true;\n    bmax = array_max64f(nb, betaHist, &ierr);\n    // Compute u\n    u = memory_calloc64f(nb);\n    compearth_beta2u(nb, betas, u);\n    // Take averages\n    betaAvg = 0.0;\n    memset(app, 0, 8*sizeof(char));\n    memset(more, 0, 8*sizeof(char));\n    memset(shift, 0, 8*sizeof(char));\n    if (!lappend)\n    {\n        ofl = fopen(outputScript, \"w\");\n        fprintf(ofl, \"#!/bin/bash\\n\");\n        /*\n        fprintf(ofl, \"gmt gmtset FONT_LABEL 12p\\n\");\n        fprintf(ofl, \"gmt gmtset MAP_LABEL_OFFSET 0.1c\\n\");\n        */\n        fprintf(ofl, \"parms=\\\"--FONT_LABEL=10p --MAP_LABEL_OFFSET=0.1c --PROJ_LENGTH_UNIT=cm\\\"\\n\");\n        fprintf(ofl, \"psfl=%s\\n\", psFile);\n    }\n    else\n    {\n        ofl = fopen(outputScript, \"a\");\n        strcpy(app, \"-O\\0\");\n        strcpy(more, \">\\0\");\n        strcpy(shift, \"-Y4.0\\0\");\n    }\n    fprintf(ofl,\n/*\n            \"gmt psbasemap -JX5i/1i %s -R-90/90/0/%.3f -Bg15a15:\\\"Latitude (deg)\\\":/a%.2f:\\\"Likelihood\\\":WSn -P %s -K >%s ${psfl}\\n\",\n*/\n            \"gmt psbasemap -JX5i/1i %s -R-90/90/0/%.3f -Bpxg15a15+l\\\"Latitude (deg)\\\" -Bpya%.2f+l\\\"Likelihood\\\" -BWSn -P %s -K ${parms} >%s ${psfl}\\n\",\n            shift, bmax*1.1, bmax*0.2, app, more);\n    setFillColor(0, ibetaOpt, color);\n    if (nb > 1)\n    {\n       fprintf(ofl, \"gmt psxy -R -J -Wblack %s -O -K << EOF >> ${psfl}\\n\", color);\n    }\n    else\n    {\n       fprintf(ofl, \"gmt psxy -R -J -Wblack %s -O << EOF >> ${psfl}\\n\", color);\n    }\n    fprintf(ofl, \"%f %f\\n\", 90.0 - 0.0, 0.0);\n    fprintf(ofl, \"%f %f\\n\", 90.0 - 0.0, betaHist[0]); \n    for (i=0; i<nb-1; i++)\n    {\n        uAvg = 0.5*(u[i] + u[i+1]);\n        compearth_u2beta(1, &uAvg, &betaAvg);\n        //compearth_u2beta(1, 20, 2, &uAvg, 1.e-7, &betaAvg);\n        fprintf(ofl, \"%f %f\\n\", 90.0 - betaAvg*180.0/M_PI, betaHist[i]);\n        fprintf(ofl, \"%f %f\\n\", 90.0 - betaAvg*180.0/M_PI, 0.0);\n        fprintf(ofl, \"EOF\\n\");\n        setFillColor(i+1, ibetaOpt, color);\n        if (i < nb - 2 || lwritePrior)\n        {\n            fprintf(ofl, \"gmt psxy -R -J -Wblack %s -O -K << EOF >> ${psfl}\\n\", color);\n        }\n        else\n        {\n            fprintf(ofl, \"gmt psxy -R -J -Wblack %s -O << EOF >> ${psfl}\\n\", color);\n        }\n        fprintf(ofl, \"%f %f\\n\", 90.0 - betaAvg*180.0/M_PI, 0.0);\n        fprintf(ofl, \"%f %f\\n\", 90.0 - betaAvg*180.0/M_PI, betaHist[i+1]);\n    }\n    fprintf(ofl, \"%f %f\\n\", 90.0 - M_PI*180.0/M_PI, betaHist[nb-1]);\n    fprintf(ofl, \"%f %f\\n\", 90.0 - M_PI*180.0/M_PI, 0.0);\n    fprintf(ofl, \"EOF\\n\");\n    // Write the prior distribution\n    if (lwritePrior)\n    {\n        fprintf(ofl, \"gmt psxy -R -J -W1,black -O -K << EOF >> ${psfl}\\n\");\n        fprintf(ofl, \"%f %f\\n\",-90.0, 1.0/(double) nb);\n        fprintf(ofl, \"%f %f\\n\", 90.0, 1.0/(double) nb);\n        fprintf(ofl, \"EOF\\n\");\n    }\n    // Write the CDF \n/*\n    fprintf(ofl, \"gmt psbasemap -R-90/90/0/1.05 -J -Bp0.2/a0.2:\\\"CDF\\\":E -O -K >> ${psfl}\\n\");\n*/\n    fprintf(ofl, \"gmt psbasemap -R-90/90/0/1.05 -J -Bpx0.2 -Bpya0.2+l\\\"CDF\\\" -BE -O -K ${parms} >> ${psfl}\\n\");\n    betaCum = array_cumsum64f(nb, betaHist, &ierr);\n    if (lclose)\n    {\n        fprintf(ofl, \"gmt psxy -R -J -W1,blue -O << EOF >> ${psfl}\\n\");\n    }\n    else\n    {\n        fprintf(ofl, \"gmt psxy -R -J -W1,blue -O -K << EOF >> ${psfl}\\n\"); \n    }\n    for (i=0; i<nb; i++)\n    {\n        // the cdf is written backwards because i flip the axis to make it\n        // increase left to right; this is opposite of what colatitude wants\n        // to do\n        fprintf(ofl, \"%f %f\\n\", 90.0 - betas[i]*180.0/M_PI, betaCum[nb-1-i]);\n    }   \n    fprintf(ofl, \"EOF\\n\");\n    if (lclose)\n    {    \n        //fprintf(ofl, \"gmt psconvert -A -Tj ${psfl}\\n\");\n        //fprintf(ofl, \"rm ${psfl}\\n\");\n        fprintf(ofl, \"gmt psconvert -A -Tf ${psfl}\\n\");\n        fprintf(ofl, \"/bin/rm ${psfl}\\n\");\n    }\n    memory_free64f(&u);\n    memory_free64f(&betaCum);\n    fclose(ofl);\n    chmod(outputScript, 0755);\n    return 0;\n}\n//============================================================================//\nint postmt_gmtHelper_makeRegularHistograms(\n    const int nlocs, const int nm,\n    const int nb, const int ng, const int nk,\n    const int ns, const int nt,\n    const int nmt, const double *__restrict__ phi,\n    double **__restrict__ locHist,\n    double **__restrict__ magHist,\n    double **__restrict__ betaHist,\n    double **__restrict__ gammaHist,\n    double **__restrict__ kappaHist,\n    double **__restrict__ sigmaHist,\n    double **__restrict__ thetaHist)\n{\n    double *betaH, *gammaH, *kappaH, *locH, *magH, *sigmaH, *thetaH, xsum;\n    int ib, ierr, ig, ik, il, im, imt, is, it; \n    locH = memory_calloc64f(nlocs);\n    magH = memory_calloc64f(nm);\n    betaH = memory_calloc64f(nb);\n    gammaH = memory_calloc64f(ng);\n    kappaH = memory_calloc64f(nk);\n    sigmaH = memory_calloc64f(ns);\n    thetaH = memory_calloc64f(nt);\n    for (il=0; il<nlocs; il++)\n    {\n        for (im=0; im<nm; im++)\n        {\n            for (ib=0; ib<nb; ib++)\n            {\n                for (ig=0; ig<ng; ig++)\n                {\n                    for (ik=0; ik<nk; ik++)\n                    {\n                        for (is=0; is<ns; is++)\n                        {\n                            for (it=0; it<nt; it++)\n                            {\n                                imt = il*nm*nb*ng*nk*ns*nt\n                                    + im*nb*ng*nk*ns*nt\n                                    + ib*ng*nk*ns*nt\n                                    + ig*nk*ns*nt\n                                    + ik*ns*nt\n                                    + is*nt\n                                    + it;\n                                locH[il]   = locH[il]   + phi[imt];\n                                magH[im]   = magH[im]   + phi[imt];\n                                betaH[ib]  = betaH[ib]  + phi[imt];\n                                gammaH[ig] = gammaH[ig] + phi[imt];\n                                kappaH[ik] = kappaH[ik] + phi[imt];\n                                sigmaH[is] = sigmaH[is] + phi[imt];\n                                thetaH[it] = thetaH[it] + phi[imt];\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n    xsum = array_sum64f(nmt, phi, &ierr);\n    cblas_dscal(nlocs, 1.0/xsum, locH, 1);\n    cblas_dscal(nm, 1.0/xsum, magH, 1);\n    cblas_dscal(nb, 1.0/xsum, betaH, 1);\n    cblas_dscal(ng, 1.0/xsum, gammaH, 1);\n    cblas_dscal(nk, 1.0/xsum, kappaH, 1);\n    cblas_dscal(ns, 1.0/xsum, sigmaH, 1);\n    cblas_dscal(nt, 1.0/xsum, thetaH, 1);\n    *locHist = locH;\n    *magHist = magH;\n    *betaHist = betaH;\n    *gammaHist = gammaH;\n    *kappaHist = kappaH;\n    *sigmaHist = sigmaH;\n    *thetaHist = thetaH;\n    return 0;\n}\n//============================================================================//\nstatic void getBaseAndExp(const double val, double *base, int *exp)\n{\n    char cval[64], cexp[64], temp[64];\n    int i, k, l;\n    bool lp1;\n    memset(cval, 0, 64*sizeof(char));\n    memset(cexp, 0, 64*sizeof(char));\n    memset(temp, 0, 64*sizeof(char));\n    sprintf(temp, \"%04.2e\", val);\n    lp1 = true;\n    k = 0;\n    l = 0;\n    for (i=0; i<strlen(temp); i++)\n    {\n        if (temp[i] == 'e')\n        {\n            lp1 = false;\n            continue;\n        }\n        else\n        {\n            if (lp1)\n            {\n                cval[k] = temp[i];\n                k = k + 1;\n            }\n            else\n            {\n                cexp[l] = temp[i];\n                l = l + 1;\n            }\n        }   \n    }\n    *exp = atoi(cexp);\n    *base = atof(cval);\n    return;\n}\n\nstatic void getBaseAndExpMT(const double *mtIn, double *mtOut, int *expOut)\n{\n    double xfact;\n    int expWork, i;\n    getBaseAndExp(mtIn[0], &mtOut[0], expOut);\n    for (i=1; i<6; i++)\n    {\n        getBaseAndExp(mtIn[i], &mtOut[i], &expWork);\n        if (expWork > *expOut){*expOut = expWork;}\n    }\n    // Rescale\n    for (i=0; i<6; i++)\n    {\n        getBaseAndExp(mtIn[i], &mtOut[i], &expWork);\n        xfact = pow(10.0, expWork - *expOut);\n        mtOut[i] = mtOut[i]*xfact;\n    }\n    return;\n}\n\nint postmt_gmtHelper_makePsmecaLine(const enum compearthCoordSystem_enum basis,\n                                    const double *mt,\n                                    const double evla, const double evlo,\n                                    const double evdp, const char *evid,\n                                    char line[128])\n{\n    const char *fcnm = \"postmt_gmtHelper_makePsmecaLine\\0\";\n    double mtUSE[6], mtGMT[6];\n    int exp, ierr;\n    memset(line, 0, 128*sizeof(char));\n    ierr = compearth_convertMT(1, basis, CE_USE, mt, mtUSE);\n    if (ierr != 0)\n    {\n        printf(\"%s: Error switching basis\\n\", fcnm);\n        return -1;\n    }\n    getBaseAndExpMT(mtUSE, mtGMT, &exp);\n    sprintf(line, \"%f %f %f %f %f %f %f %f %f %d %s\\n\",\n            evlo, evla, evdp,\n            mtGMT[0], mtGMT[1], mtGMT[2], mtGMT[3], mtGMT[4], mtGMT[5],\n            exp, evid);\n    return 0;\n}\n\nstatic void setFillColor(const int i, const int iopt, char color[32])\n{\n    memset(color, 0, 32*sizeof(char));\n    if (i == iopt)\n    {\n        strcpy(color, \"-Gyellow\\0\");\n    }\n    else\n    {\n        strcpy(color, \"-Gred\\0\");\n    }\n    return;\n}\n//============================================================================//\n/*\n    sprintf(\"%7.2f %5.2f %f \\n\"< \n            evlo, evla, evdp,\n            mrr, mtt, mpp,  \n            \nColumns: lon lat depth mrr mtt mpp mrt mrp mtp iexp name\n-176.96 -29.25 48 7.68 0.09 -7.77 1.39 4.52 -3.26 26 X Y 010176A  \n*/\n", "meta": {"hexsha": "3e399673441403d6030ec5a9474807aa08a5f5f4", "size": 42477, "ext": "c", "lang": "C", "max_stars_repo_path": "postprocess/gmtHelper.c", "max_stars_repo_name": "bakerb845/parmt", "max_stars_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_stars_repo_licenses": ["Intel"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "postprocess/gmtHelper.c", "max_issues_repo_name": "bakerb845/parmt", "max_issues_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_issues_repo_licenses": ["Intel"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "postprocess/gmtHelper.c", "max_forks_repo_name": "bakerb845/parmt", "max_forks_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_forks_repo_licenses": ["Intel"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0181368508, "max_line_length": 154, "alphanum_fraction": 0.4724439108, "num_tokens": 14322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2720245510940225, "lm_q2_score": 0.03846618995154013, "lm_q1q2_score": 0.010463748053865103}}
{"text": "#ifndef __GSL_SORT_H__\n#define __GSL_SORT_H__\n\n#if !defined( GSL_FUN )\n#  if !defined( GSL_DLL )\n#    define GSL_FUN extern\n#  elif defined( BUILD_GSL_DLL )\n#    define GSL_FUN extern __declspec(dllexport)\n#  else\n#    define GSL_FUN extern __declspec(dllimport)\n#  endif\n#endif\n\n#include <gsl/gsl_sort_long_double.h>\n#include <gsl/gsl_sort_double.h>\n#include <gsl/gsl_sort_float.h>\n\n#include <gsl/gsl_sort_ulong.h>\n#include <gsl/gsl_sort_long.h>\n\n#include <gsl/gsl_sort_uint.h>\n#include <gsl/gsl_sort_int.h>\n\n#include <gsl/gsl_sort_ushort.h>\n#include <gsl/gsl_sort_short.h>\n\n#include <gsl/gsl_sort_uchar.h>\n#include <gsl/gsl_sort_char.h>\n\n#endif /* __GSL_SORT_H__ */\n", "meta": {"hexsha": "2632f67efcabfafdc484c725433c49d633a2f22f", "size": 668, "ext": "h", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_sort.h", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-28T08:20:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-28T08:20:20.000Z", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_sort.h", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_sort.h", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-14T12:45:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-14T12:45:35.000Z", "avg_line_length": 21.5483870968, "max_line_length": 48, "alphanum_fraction": 0.751497006, "num_tokens": 201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2598256379609837, "lm_q2_score": 0.040237943918413906, "lm_q1q2_score": 0.010454849448840177}}
{"text": "/**\n* Copyright 2016 BitTorrent Inc.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n*    http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*/\n#pragma once\n\n#include <scraps/config.h>\n\n#include <scraps/Byte.h>\n#include <scraps/Temp.h>\n#include <scraps/ByteArray.h>\n\n#include <gsl.h>\n\n#include <iterator>\n\nnamespace scraps {\n\nconstexpr signed char DecToHex(int c) {\n    if (c >= 0 && c < 16) {\n        return \"0123456789abcdef\"[c];\n    }\n    return -1;\n}\n\nconstexpr signed char DecToHex(const Byte& c) {\n    return DecToHex(c.value());\n}\n\ntemplate <typename CharT>\nconstexpr int8_t HexToDec(CharT c) {\n    if (c >= '0' && c <= '9') { return c - '0'; }\n    if (c >= 'a' && c <= 'f') { return c - 'a' + 10; }\n    if (c >= 'A' && c <= 'F') { return c - 'A' + 10; }\n    return -1;\n}\n\n/**\n * Returns a hex string representation of the input span. The output does not\n * include an \"0x\" prefix.\n *\n * example: ToHex(std::array<uint8_t, 1>{0xAB}) == \"AB\";\n */\ntemplate <typename T, std::ptrdiff_t... BytesDimension>\nstd::string ToHex(const gsl::span<T, BytesDimension...> range) {\n    std::string ret;\n\n    static_assert(sizeof(T) == 1, \"Input span type too large\");\n\n    ret.reserve(range.size() * 2 + 2);\n\n    for (auto& b : range) {\n        ret += DecToHex(b >> 4);\n        ret += DecToHex(b & 0x0F);\n    }\n\n    return ret;\n}\n\ntemplate <typename T, size_t N>\nstd::string ToHex(const std::array<T, N>& in) {\n    return ToHex(gsl::span<const T, N>{in});\n}\n\ntemplate <size_t N>\nstd::string ToHex(const ByteArray<N>& in) {\n    return ToHex(gsl::span<const unsigned char, N>{in.bytes});\n}\n\n/**\n * Fills a byte range from a range of hex characters. Returns true if the input\n * range is successfully converted to the output range. A prefix of \"0x\" or \"0X\"\n * is optional.\n */\ntemplate <typename HexCharT, std::ptrdiff_t HexExtent, typename ByteType, std::ptrdiff_t... BytesDimension>\nconstexpr bool ToBytes(const gsl::basic_string_span<const HexCharT, HexExtent> hex, const gsl::span<ByteType, BytesDimension...> bytes) {\n    auto prefixSize = 0;\n    if (hex.size() > 2 && hex[0] == '0' && (hex[1] == 'x' || hex[1] == 'X')) {\n        prefixSize += 2;\n    }\n    if (hex.size() - prefixSize != bytes.size() * 2) {\n        return false;\n    }\n    for (decltype(bytes.size()) i = 0; i < bytes.size(); ++i) {\n        auto hi = HexToDec(hex[i * 2 + prefixSize]);\n        auto lo = HexToDec(hex[i * 2 + 1 + prefixSize]);\n        if (hi < 0 || lo < 0) {\n            return false;\n        }\n        bytes[i] = ByteType{static_cast<uint8_t>((hi << 4) | lo)};\n    }\n    return true;\n}\n\ntemplate <typename CharT, typename T, size_t N>\nconstexpr bool ToBytes(const std::basic_string<CharT>& in, std::array<T, N>& out) {\n    return ToBytes(gsl::basic_string_span<const CharT>{in}, gsl::span<T, N>{out});\n}\n\n} // namespace scraps\n", "meta": {"hexsha": "8abb838292e3280d2306a5a208db86baf3ff960b", "size": 3246, "ext": "h", "lang": "C", "max_stars_repo_path": "include/scraps/hex.h", "max_stars_repo_name": "marakew/scraps", "max_stars_repo_head_hexsha": "6308c4c7bd61bf7822a6eea27c499faf6fe6e263", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/scraps/hex.h", "max_issues_repo_name": "marakew/scraps", "max_issues_repo_head_hexsha": "6308c4c7bd61bf7822a6eea27c499faf6fe6e263", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/scraps/hex.h", "max_forks_repo_name": "marakew/scraps", "max_forks_repo_head_hexsha": "6308c4c7bd61bf7822a6eea27c499faf6fe6e263", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9821428571, "max_line_length": 137, "alphanum_fraction": 0.629081947, "num_tokens": 937, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2598256379609837, "lm_q2_score": 0.04023793945855469, "lm_q1q2_score": 0.01045484829005441}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef loopblinn_875a5488_30b0_4449_b97a_e55c8d8a0db1_h\r\n#define loopblinn_875a5488_30b0_4449_b97a_e55c8d8a0db1_h\r\n\r\n#include <gslib/std.h>\r\n#include <gslib/rtree.h>\r\n#include <ariel/painterpath.h>\r\n#include <ariel/delaunay.h>\r\n\r\n__ariel_begin__\r\n\r\nclass lb_joint;\r\nclass lb_end_joint;\r\nclass lb_control_joint;\r\nclass lb_line;\r\nclass lb_polygon;\r\nclass lb_shrink_line;\r\nclass lb_shrink;\r\n\r\ntypedef vector<lb_joint*> lb_joint_list;\r\ntypedef vector<lb_line*> lb_line_list;\r\ntypedef vector<lb_polygon*> lb_polygon_list;\r\ntypedef vector<lb_shrink_line*> lb_shrink_lines;\r\ntypedef stack<lb_polygon*> lb_polygon_stack;\r\n\r\nenum lb_joint_type\r\n{\r\n    lbt_end_joint,\r\n    lbt_control_joint,\r\n};\r\n\r\n/*\r\n * The reason why the original point and the NDC(normalized device coordinate) point should\r\n * be separated was that we need the original point for the convenience of the error handling\r\n * works, and we need the NDC point to do the loopblinn calculations so that the float\r\n * point won't overflow.\r\n */\r\nclass __gs_novtable lb_joint abstract\r\n{\r\nprotected:\r\n    lb_line*            _prev;\r\n    lb_line*            _next;\r\n    vec2                _point;\r\n    vec2                _ndcpoint;\r\n    void*               _binding;\r\n\r\npublic:\r\n    lb_joint()\r\n    {\r\n        _prev = _next = nullptr;\r\n        _binding = nullptr;\r\n    }\r\n    virtual ~lb_joint() {}\r\n    virtual lb_joint_type get_type() const = 0;\r\n    virtual const vec2& get_point() const { return _point; }\r\n    virtual const vec2& get_ndc_point() const { return _ndcpoint; }\r\n\r\npublic:\r\n    void set_point(const vec2& p) { _point = p; }\r\n    void set_ndc_point(const vec2& p) { _ndcpoint = p; }\r\n    void set_prev_line(lb_line* p) { _prev = p; }\r\n    void set_next_line(lb_line* p) { _next = p; }\r\n    lb_line* get_prev_line() const { return _prev; }\r\n    lb_line* get_next_line() const { return _next; }\r\n    lb_joint* get_prev_joint() const;\r\n    lb_joint* get_next_joint() const;\r\n    bool is_adjacent_joint(const lb_joint* p) const { return p == get_prev_joint() || p == get_next_joint(); }\r\n    void set_binding(void* p) { _binding = p; }\r\n    void* get_binding() const { return _binding; }\r\n};\r\n\r\nclass lb_end_joint:\r\n    public lb_joint\r\n{\r\nprotected:\r\n    vec3                _klm[2];\r\n\r\npublic:\r\n    lb_end_joint() {}\r\n    lb_joint_type get_type() const override { return lbt_end_joint; }\r\n    bool prev_is_curve() const;\r\n    bool next_is_curve() const;\r\n    void set_klm(int i, const vec3& p) { _klm[i] = p; }\r\n    const vec3& get_klm(int i) const { return _klm[i]; }\r\n};\r\n\r\nclass lb_control_joint:\r\n    public lb_joint\r\n{\r\nprotected:\r\n    vec3                _klm;\r\n\r\npublic:\r\n    lb_control_joint() {}\r\n    lb_joint_type get_type() const override { return lbt_control_joint; }\r\n    void set_klm(const vec3& p) { _klm = p; }\r\n    const vec3& get_klm() const { return _klm; }\r\n};\r\n\r\nclass lb_line\r\n{\r\nprotected:\r\n    lb_joint*           _joint[2];\r\n    bool                _opened;\r\n\r\npublic:\r\n    lb_line()\r\n    {\r\n        _joint[0] = _joint[1] = nullptr;\r\n        _opened = false;\r\n    }\r\n    void set_opened(bool b) { _opened = b; }\r\n    bool is_opened() const { return _opened; }\r\n    void set_prev_joint(lb_joint* p) { _joint[0] = p; }\r\n    void set_next_joint(lb_joint* p) { _joint[1] = p; }\r\n    lb_joint* get_prev_joint() const { return _joint[0]; }\r\n    lb_joint* get_next_joint() const { return _joint[1]; }\r\n    lb_line* get_prev_line() const;\r\n    lb_line* get_next_line() const;\r\n    const vec2& get_prev_point() const { return _joint[0]->get_point(); }\r\n    const vec2& get_next_point() const { return _joint[1]->get_point(); }\r\n    static lb_line* get_line_between(lb_joint* j1, lb_joint* j2);\r\n};\r\n\r\nenum lb_span_type\r\n{\r\n    lst_linear,\r\n    lst_quad,\r\n    lst_cubic,\r\n};\r\n\r\nclass __gs_novtable lb_span abstract\r\n{\r\nprotected:\r\n    rectf               _rc;\r\n\r\npublic:\r\n    virtual ~lb_span() {}\r\n    virtual lb_span_type get_type() const = 0;\r\n    virtual bool can_split() const = 0;\r\n    virtual bool is_overlapped(const lb_span* span) const = 0;\r\n\r\npublic:\r\n    const rectf& get_rect() const { return _rc; }\r\n    float get_area() const { return _rc.width() * _rc.height(); }\r\n};\r\n\r\ntypedef vector<lb_span*> lb_span_list;\r\ntypedef rtree_entity<lb_span*> lb_rtree_entity;\r\ntypedef rtree_node<lb_rtree_entity> lb_rtree_node;\r\ntypedef _tree_allocator<lb_rtree_node> lb_rtree_alloc;\r\ntypedef tree<lb_rtree_entity, lb_rtree_node, lb_rtree_alloc> lb_tree;\r\ntypedef rtree<lb_rtree_entity, quadratic_split_alg<8, 3, lb_tree>, lb_rtree_node, lb_rtree_alloc> lb_rtree;\r\ntypedef delaunay_triangulation lb_triangulator;\r\n\r\n/*\r\n * The polygon should be decomposed to the form like boundary - holes,\r\n * this procedure could also be called flattening.\r\n * After we retrieve the boundary we need to create a shrink for the boundary\r\n * for including test, if necessary, so that we could decide if a sub path\r\n * (case : cw - ccw - {cw}?) was a new path that ends the previous boundary.\r\n */\r\nclass lb_polygon\r\n{\r\nprotected:\r\n    lb_line*            _boundary;\r\n    lb_line_list        _holes;\r\n    lb_rtree            _mytree;\r\n    lb_triangulator     _cdt;\r\n    dt_input_joints     _dtjoints;\r\n\r\npublic:\r\n    lb_polygon() { _boundary = nullptr; }\r\n    void set_boundary(lb_line* p) { _boundary = p; }\r\n    void add_hole(lb_line* p) { _holes.push_back(p); }\r\n    lb_line* get_boundary() const { return _boundary; }\r\n    const lb_line_list& get_holes() const { return _holes; }\r\n    bool is_inside(const vec2& p) const;\r\n    lb_rtree& get_rtree() { return _mytree; }\r\n    void convert_to_ndc(const mat3& m);\r\n    void create_dt_joints();\r\n    void pack_constraints();\r\n    void build_cdt();\r\n    lb_triangulator& get_cdt_result() { return _cdt; }\r\n    void tracing() const;\r\n    void trace_boundary() const;\r\n    void trace_last_hole() const;\r\n    void trace_holes() const;\r\n    void trace_rtree() const { _mytree.tracing(); }\r\n};\r\n\r\n/*\r\n * Notice that the path put into the loopblinn categorizer MUST be a simple polygon,\r\n * which means you should run a xor clip process before if you can't tell whether a\r\n * path was simple or complex.\r\n * Another point was that the path MUST be Winding rule.\r\n * You can also convert a path of OddEven rule to Winding by clipping.\r\n */\r\nclass loop_blinn_processor\r\n{\r\npublic:\r\n    loop_blinn_processor(float w, float h) { _width = w, _height = h; }\r\n    ~loop_blinn_processor();\r\n    void proceed(const painter_path& path);\r\n    lb_polygon_list& get_polygons() { return _polygons; }\r\n    lb_joint_list& get_joints() { return _joint_holdings; }\r\n    lb_line_list& get_lines() { return _line_holdings; }\r\n    void trace_polygons() const;\r\n    void trace_rtree() const;\r\n\r\nprotected:\r\n    float               _width;\r\n    float               _height;\r\n    lb_line_list        _line_holdings;\r\n    lb_joint_list       _joint_holdings;\r\n    lb_polygon_list     _polygons;\r\n    lb_span_list        _span_holdings;\r\n\r\nprotected:\r\n    template<class _joint>\r\n    lb_joint* create_joint(const vec2& p);\r\n    lb_line* create_line();\r\n    lb_polygon* create_polygon();\r\n    void flattening(const painter_path& path);\r\n    int flattening(const painter_path& path, int start, lb_polygon* parent, lb_polygon_stack& st);\r\n    int create_patch(lb_line*& line, const painter_path& path, int start);\r\n    lb_joint* create_segment(lb_joint* prev, const painter_path& path, int i);\r\n    void check_boundary(lb_polygon* poly);\r\n    void check_holes(lb_polygon* poly);\r\n    void check_span(lb_polygon* poly, lb_control_joint* joint);\r\n    void check_rtree(lb_polygon* poly);\r\n    void check_rtree_span(lb_polygon* poly, lb_span* span);\r\n    void split_quadratic(lb_line* line1, lb_line* line2, lb_joint* sp[5]);\r\n    void split_cubic(lb_line* line1, lb_line* line2, lb_line* line3, lb_joint* sp[7], float t);\r\n    int try_split_cubic(lb_line* line1, lb_line* line2, lb_line* line3, lb_joint* sp[7], float t);\r\n    lb_span* split_rtree_span(lb_span* span);\r\n    void split_span_recursively(lb_polygon* poly, lb_span* span);\r\n    void calc_klm_coords();\r\n    void calc_klm_coords(lb_polygon* poly);\r\n    void calc_klm_coords(lb_polygon* poly, lb_line* start);\r\n    lb_line* calc_klm_span(lb_polygon* poly, lb_line* line);\r\n};\r\n\r\nextern lb_line* lb_get_span(lb_line_list& span, lb_line* start);\r\nextern void lb_get_current_span(lb_line_list& span, lb_control_joint* joint);\r\n\r\n__ariel_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "2fcc2424bd41a7c868367ea512f5b8e90eb20396", "size": 9652, "ext": "h", "lang": "C", "max_stars_repo_path": "include/ariel/loopblinn.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/ariel/loopblinn.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ariel/loopblinn.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 34.9710144928, "max_line_length": 111, "alphanum_fraction": 0.6820348114, "num_tokens": 2529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3451052709578724, "lm_q2_score": 0.030214590342110485, "lm_q1q2_score": 0.010427214386895154}}
{"text": "#ifndef TREE_H\n#define TREE_H\n#include \"node.h\"\n#include <string>\n#include <vector>\n#include <gsl/gsl_rng.h>\n#include \"data.h\"\n\nusing namespace std;\n\nnamespace weakarg\n{\n\nextern gsl_rng * rng;\n\n/**\n    @brief Genealogy of the isolates under study\n*/\nclass Tree\n{\nprotected:\n    Node * root;///<Root node of the genealogy\n    std::vector<Node*> nodes;///<Vector of all the nodes in the genealogy\n    int n;///<Number of isolates\n    double ttotal;///<Sum of branch lengths\npublic:\n    Tree(std::string newick,bool isFilename=true,bool forceages=true);///<Creates a tree from a Newick file\n    Tree(int n);///< Creates a Coalescent tree by simulation\n    Tree(Tree *intree);///< Creates a copy of a tree via newick (== slow)\n    Tree(Data * data);///< Creates a UPGMA tree\n    Tree(const Tree& t);///< Copy constructor\n    void assign(const Tree& t);///< Copy a tree while allocating as little new storage as possible\n    ~Tree();\n    std::string newick(int p=6) const; ///<Returns a Newick description of the tree (precision options)\n    std::string newickNoInternalLabels(int p=6) const; ///<Returns a Newick description of the tree (precision options)\n    void makeFromNewick(std::string newick,bool forceages=false);///< Creates a tree from a newick string\n    inline int getN() const\n    {\n        return n;\n    }///<Returns the number of isolates\n    inline Node* getNode(int i) const\n    {\n        return nodes[i];\n    }///<Returns a node given its index\n    inline Node* getRoot() const\n    {\n        return root;\n    }///<Returns the root node\n    inline double getDist(int i) const\n    {\n        return nodes[i]->getDist();\n    }///<Returns the time of a node given its index\n    double prior() const; ///<Returns log-prior of the tree\n    inline double getTTotal() const\n    {\n        return ttotal;\n    }///<Returns the sum of branch lengths\n    void computeTTotal(); ///<Computes the sum of branch lengths\n    int getPoint(double * dist, std::vector<int> * samplespace=NULL) const; ///<Returns a point chosen uniformly at random on the tree, or uniformally on a subspace of specified clonal edges\n    std::vector<int> getAllChildren(int e);///<Returns a vector of the indices of the children of a given node\n    std::vector<int> getAllSampledSeqs(int e);///<Returns a vector of all the observed sequences of the children of a given node\n\n    void orderNodes(double dist=1);///<orders the list by age\n    int orderNodes(int which, double dist);///<places a node in a new place in the list\n    void swapFather(int a,int b);///<Swaps the father of two nodes\n    void swapNode(int a, int b);///<Swaps two nodes in the list\n    int getOldestReversedNode();///<Returns the oldest node that has been age reversed\n\n    void testNodeAges() const; ///<Tests node ages\n    double tavare() const;\n\n    inline int otherChild(int par,int onechild){\n\tif(getNode(par)->getLeft()->getId()==onechild) return(getNode(par)->getRight()->getId());\n\telse if(getNode(par)->getRight()->getId()==onechild) return(getNode(par)->getLeft()->getId());\n\telse{cerr<<\"Error in RecTree::otherChild: parent doesn't have a suitable child!\"<<endl;throw(\"unknown child error\");}\n    };\n    std::vector<int> getMinEdgeList(std::vector<int> seqs);\n    int getNextGroup(std::vector<int> *seqs);\n    bool isParentToOnly(int e, std::vector<int> seqs,std::vector<int> *which);\n\n};\n\n} // end namespace weakarg\n#endif\n", "meta": {"hexsha": "d627d86a5467e3dd75d6d3887940dd8a78dfe82a", "size": 3383, "ext": "h", "lang": "C", "max_stars_repo_path": "ClonOr_cpp/tree.h", "max_stars_repo_name": "fmedina7/ClonOr_cpp", "max_stars_repo_head_hexsha": "d1c2e0e0f7d2315bad99de80a15458cb4015ae1e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ClonOr_cpp/tree.h", "max_issues_repo_name": "fmedina7/ClonOr_cpp", "max_issues_repo_head_hexsha": "d1c2e0e0f7d2315bad99de80a15458cb4015ae1e", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ClonOr_cpp/tree.h", "max_forks_repo_name": "fmedina7/ClonOr_cpp", "max_forks_repo_head_hexsha": "d1c2e0e0f7d2315bad99de80a15458cb4015ae1e", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.8, "max_line_length": 190, "alphanum_fraction": 0.6837126811, "num_tokens": 852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326184801538616, "lm_q2_score": 0.022977372126235844, "lm_q1q2_score": 0.010414766152474882}}
{"text": "#ifndef SN3D_H\n#define SN3D_H\n\n#include <cassert>\n\n#ifndef __CUDA_ARCH__\n  // host code\n\n  #define __artis_assert(e) if (!(e)) { if (output_file != NULL) {(void)fprintf(output_file, \"[rank %d] %s:%d: failed assertion `%s' in function %s\\n\", globals::rank_global, __FILE__, __LINE__, #e, __PRETTY_FUNCTION__);} (void)fprintf(stderr, \"[rank %d] %s:%d: failed assertion `%s' in function %s\\n\", globals::rank_global, __FILE__, __LINE__, #e, __PRETTY_FUNCTION__); abort();}\n  //\n\n  #define assert_always(e) __artis_assert(e)\n\n  #if defined TESTMODE && TESTMODE\n    #define assert_testmodeonly(e) __artis_assert(e)\n  #else\n    #define\tassert_testmodeonly(e) ((void)0)\n  #endif\n\n  #define printout(...) fprintf(output_file, __VA_ARGS__)\n\n  #ifdef _OPENMP\n  #ifndef __CUDACC__\n    #define safeadd(var, val) _Pragma(\"omp atomic update\") \\\n    var += val\n  #else\n    #define safeadd(var, val) var += val\n  #endif\n  #else\n    #define safeadd(var, val) var += val\n  #endif\n\n#else\n  // device code\n\n  #define printout(...) printf (__VA_ARGS__)\n\n  #define assert_always(e) assert(e)\n\n  #if defined TESTMODE && TESTMODE\n    #define assert_testmodeonly(e) assert(e)\n  #else\n    #define\tassert_testmodeonly(e) ((void)0)\n  #endif\n\n\n  #define safeadd(var, val) atomicAdd(&var, val)\n\n#endif\n\n#define safeincrement(var) safeadd(var, 1)\n\n#include \"cuda.h\"\n\n#include <stdarg.h>  /// MK: needed for printout()\n#include <gsl/gsl_integration.h>\n\n#define DEBUG_ON\n// #define DO_TITER\n// #define FORCE_LTE\n\n#include \"globals.h\"\n#include \"types.h\"\n#include \"vectors.h\"\n\n#if (DETAILED_BF_ESTIMATORS_ON && !NO_LUT_PHOTOION)\n  #error Must use NO_LUT_PHOTOION with DETAILED_BF_ESTIMATORS_ON\n#endif\n\n#if !defined MPI_ON\n  // #define MPI_ON //only needed for debugging MPI, the makefile will switch this on\n#endif\n\n#ifdef MPI_ON\n  #include \"mpi.h\"\n#endif\n\n//#define _OPENMP\n#ifdef _OPENMP\n  #include \"omp.h\"\n#endif\n\n#define COOLING_UNDEFINED       -99\n\n#define RPKT_EVENTTYPE_BB 550\n#define RPKT_EVENTTYPE_CONT 551\n\nextern int tid;\nextern __managed__ bool use_cellhist;\nextern __managed__ bool neutral_flag;\n#ifndef __CUDA_ARCH__\nextern gsl_rng *rng;  // pointer for random number generator\n#else\nextern __device__ void *rng;\n#endif\nextern gsl_integration_workspace *gslworkspace;\nextern FILE *output_file;\nextern __managed__ int myGpuId;\n\n#ifdef _OPENMP\n  #pragma omp threadprivate(tid, myGpuId, use_cellhist, neutral_flag, rng, gslworkspace, output_file)\n#endif\n\n\ninline void gsl_error_handler_printout(const char *reason, const char *file, int line, int gsl_errno)\n{\n  if (gsl_errno != 18) // roundoff error\n  {\n    printout(\"WARNING: gsl (%s:%d): %s (Error code %d)\\n\", file, line, reason, gsl_errno);\n    // abort();\n  }\n}\n\n\ninline FILE *fopen_required(const char *filename, const char *mode)\n{\n  FILE *file = fopen(filename, mode);\n  if (file == NULL)\n  {\n    printout(\"ERROR: Could not open file '%s' for mode '%s'.\\n\", filename, mode);\n    abort();\n  }\n\n  return file;\n}\n\n\ninline int get_timestep(const double time)\n{\n  assert_always(time >= globals::tmin);\n  assert_always(time < globals::tmax);\n  for (int nts = 0; nts < globals::ntstep; nts++)\n  {\n    const double tsend = (nts < (globals::ntstep - 1)) ? globals::time_step[nts + 1].start : globals::tmax;\n    if (time >= globals::time_step[nts].start && time < tsend)\n    {\n      return nts;\n    }\n  }\n  assert_always(false); // could not find matching timestep\n\n  return -1;\n}\n\n\ninline double get_arrive_time(const PKT *pkt_ptr)\n/// We know that a packet escaped at \"escape_time\". However, we have\n/// to allow for travel time. Use the formula in Leon's paper. The extra\n/// distance to be travelled beyond the reference surface is ds = r_ref (1 - mu).\n{\n  return pkt_ptr->escape_time - (dot(pkt_ptr->pos, pkt_ptr->dir) / globals::CLIGHT_PROP);\n}\n\n\ninline double get_arrive_time_cmf(const PKT *pkt_ptr)\n{\n  return pkt_ptr->escape_time * sqrt(1. - (globals::vmax * globals::vmax / CLIGHTSQUARED));\n}\n\n\n__host__ __device__\ninline int get_max_threads(void)\n{\n#ifdef __CUDA_ARCH__\n  return MCUDATHREADS;\n#elif defined _OPENMP\n  return omp_get_max_threads();\n#else\n  return 1;\n#endif\n}\n\n\n__host__ __device__\ninline int get_num_threads(void)\n{\n#ifdef __CUDA_ARCH__\n  return blockDim.x * blockDim.y * blockDim.z;\n#elif defined _OPENMP\n  return omp_get_num_threads();\n#else\n  return 1;\n#endif\n}\n\n\n__host__ __device__\ninline int get_thread_num(void)\n{\n#ifdef __CUDA_ARCH__\n  return threadIdx.x + blockDim.x * blockIdx.x;\n#elif defined _OPENMP\n  return omp_get_thread_num();\n#else\n  return 0;\n#endif\n}\n\n\n#endif // SN3D_H\n", "meta": {"hexsha": "0eb47f63b2dff8dbcc78aa75b7ce129b010f1a6d", "size": 4539, "ext": "h", "lang": "C", "max_stars_repo_path": "sn3d.h", "max_stars_repo_name": "artis-mcrt/artis", "max_stars_repo_head_hexsha": "eeb4ba06353a34be949d9662ab300a78f852ebdb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-04-12T12:09:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T21:56:21.000Z", "max_issues_repo_path": "sn3d.h", "max_issues_repo_name": "artis-mcrt/artis", "max_issues_repo_head_hexsha": "eeb4ba06353a34be949d9662ab300a78f852ebdb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-11-17T09:37:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-17T15:03:17.000Z", "max_forks_repo_path": "sn3d.h", "max_forks_repo_name": "artis-mcrt/artis", "max_forks_repo_head_hexsha": "eeb4ba06353a34be949d9662ab300a78f852ebdb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5820895522, "max_line_length": 379, "alphanum_fraction": 0.70720423, "num_tokens": 1304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3242353859211693, "lm_q2_score": 0.03210070891617667, "lm_q1q2_score": 0.010408185743779661}}
{"text": "/*\n * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The OpenAirInterface Software Alliance licenses this file to You under\n * the OAI Public License, Version 1.1  (the \"License\"); you may not use this file\n * except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.openairinterface.org/?page_id=698\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *-------------------------------------------------------------------------------\n * For more information about the OpenAirInterface (OAI) Software Alliance:\n *      contact@openairinterface.org\n */\n\n/*! \\file oaisim.c\n * \\brief oaisim top level\n * \\author Navid Nikaein \n * \\date 2013-2015\n * \\version 1.0\n * \\company Eurecom\n * \\email: openair_tech@eurecom.fr\n * \\note\n * \\warning\n */\n\n#include <string.h>\n#include <math.h>\n#include <unistd.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include <cblas.h>\n#include <execinfo.h>\n\n#include \"event_handler.h\"\n#include \"SIMULATION/RF/defs.h\"\n#include \"PHY/types.h\"\n#include \"PHY/defs.h\"\n#include \"PHY/LTE_TRANSPORT/proto.h\"\n#include \"PHY/vars.h\"\n\n#include \"SIMULATION/ETH_TRANSPORT/proto.h\"\n\n//#ifdef OPENAIR2\n#include \"LAYER2/MAC/defs.h\"\n#include \"LAYER2/MAC/proto.h\"\n#include \"LAYER2/MAC/vars.h\"\n#include \"pdcp.h\"\n#include \"RRC/LITE/vars.h\"\n#include \"RRC/NAS/nas_config.h\"\n\n#include \"SCHED/defs.h\"\n#include \"SCHED/vars.h\"\n#include \"system.h\"\n\n\n#include \"PHY/TOOLS/lte_phy_scope.h\"\n\n\n#ifdef SMBV\n// Rohde&Schwarz SMBV100A vector signal generator\n#include \"PHY/TOOLS/smbv.h\"\nchar smbv_fname[] = \"smbv_config_file.smbv\";\nunsigned short smbv_nframes = 4; // how many frames to configure 1,..,4\nunsigned short config_frames[4] = {2,9,11,13};\nunsigned char smbv_frame_cnt = 0;\nuint8_t config_smbv = 0;\nchar smbv_ip[16];\n#endif\n\n#include \"flexran_agent.h\"\n\n\n#include \"oaisim_functions.h\"\n\n#include \"oaisim.h\"\n#include \"oaisim_config.h\"\n#include \"UTIL/OCG/OCG_extern.h\"\n#include \"cor_SF_sim.h\"\n#include \"UTIL/OMG/omg_constants.h\"\n#include \"UTIL/FIFO/pad_list.h\"\n#include \"enb_app.h\"\n\n#include \"../PROC/interface.h\"\n#include \"../PROC/channel_sim_proc.h\"\n#include \"../PROC/Tsync.h\"\n#include \"../PROC/Process.h\"\n\n#include \"UTIL/LOG/vcd_signal_dumper.h\"\n#include \"UTIL/OTG/otg_kpi.h\"\n#include \"assertions.h\"\n\n#if defined(ENABLE_ITTI)\n# include \"intertask_interface.h\"\n# include \"create_tasks.h\"\n#endif\n\n#include \"T.h\"\n\n/*\n  DCI0_5MHz_TDD0_t          UL_alloc_pdu;\n  DCI1A_5MHz_TDD_1_6_t      CCCH_alloc_pdu;\n  DCI2_5MHz_2A_L10PRB_TDD_t DLSCH_alloc_pdu1;\n  DCI2_5MHz_2A_M10PRB_TDD_t DLSCH_alloc_pdu2;\n*/\n\n#define UL_RB_ALLOC            computeRIV(lte_frame_parms->N_RB_UL,0,24)\n#define CCCH_RB_ALLOC          computeRIV(lte_frame_parms->N_RB_UL,0,3)\n#define RA_RB_ALLOC            computeRIV(lte_frame_parms->N_RB_UL,0,3)\n#define DLSCH_RB_ALLOC         0x1fff\n\n#define DECOR_DIST             100\n#define SF_VAR                 10\n\n//constant for OAISIM soft realtime calibration\n//#define SF_DEVIATION_OFFSET_NS 100000        /*= 0.1ms : should be as a number of UE */\n//#define SLEEP_STEP_US          100           /*  = 0.01ms could be adaptive, should be as a number of UE */\n//#define K                      2             /* averaging coefficient */\n//#define TARGET_SF_TIME_NS      1000000       /* 1ms = 1000000 ns */\n\nuint8_t usim_test = 0;\n\nframe_t frame = 0;\nchar stats_buffer[16384];\nchannel_desc_t *RU2UE[NUMBER_OF_RU_MAX][NUMBER_OF_UE_MAX][MAX_NUM_CCs];\nchannel_desc_t *UE2RU[NUMBER_OF_UE_MAX][NUMBER_OF_RU_MAX][MAX_NUM_CCs];\n//Added for PHY abstraction\nnode_desc_t *enb_data[NUMBER_OF_RU_MAX];\nnode_desc_t *ue_data[NUMBER_OF_UE_MAX];\n\npthread_cond_t sync_cond;\npthread_mutex_t sync_mutex;\nint sync_var=-1;\n\npthread_mutex_t subframe_mutex;\nint subframe_ru_mask=0,subframe_UE_mask=0;\n\nopenair0_config_t openair0_cfg[MAX_CARDS];\nuint32_t          downlink_frequency[MAX_NUM_CCs][4];\nint32_t           uplink_frequency_offset[MAX_NUM_CCs][4];\nopenair0_rf_map rf_map[MAX_NUM_CCs];\n\n#if defined(ENABLE_ITTI)\nvolatile int             start_eNB = 0;\nvolatile int             start_UE = 0;\n#endif\nvolatile int                    oai_exit = 0;\n\n\n//int32_t **rxdata;\n//int32_t **txdata;\n\nuint16_t sf_ahead=4;\nuint8_t nfapi_mode = 0;\n\n// Added for PHY abstraction\nextern node_list* ue_node_list;\nextern node_list* enb_node_list;\nextern int pdcp_period, omg_period;\n\nextern double **s_re, **s_im, **r_re, **r_im, **r_re0, **r_im0;\nint map1, map2;\nextern double **ShaF;\ndouble snr_dB, sinr_dB, snr_direction; //,sinr_direction;\nextern double snr_step;\nextern uint8_t set_sinr;\nextern uint8_t ue_connection_test;\nextern uint8_t set_seed;\nextern uint8_t target_dl_mcs;\nextern uint8_t target_ul_mcs;\nextern uint8_t abstraction_flag;\nextern uint8_t ethernet_flag;\nextern uint16_t Nid_cell;\n\n\ndouble cpuf;\n#include \"threads_t.h\"\nthreads_t threads= {-1,-1,-1,-1,-1,-1,-1};\n\n//#ifdef XFORMS\nint otg_enabled;\nint xforms=0;\n//#endif\n\ntime_stats_t oaisim_stats;\ntime_stats_t oaisim_stats_f;\ntime_stats_t dl_chan_stats;\ntime_stats_t ul_chan_stats;\n\n// this should reflect the channel models in openair1/SIMULATION/TOOLS/defs.h\nmapping small_scale_names[] = { \n  { \"custom\", custom }, { \"SCM_A\", SCM_A },\n  { \"SCM_B\", SCM_B   }, { \"SCM_C\", SCM_C },\n  { \"SCM_D\", SCM_D   }, { \"EPA\",   EPA   },\n  { \"EVA\",   EVA     }, { \"ETU\",   ETU   },\n  { \"MBSFN\", MBSFN },   { \"Rayleigh8\", Rayleigh8 },\n  { \"Rayleigh1\", Rayleigh1 }, { \"Rayleigh1_800\", Rayleigh1_800 },\n  { \"Rayleigh1_corr\", Rayleigh1_corr }, { \"Rayleigh1_anticorr\", Rayleigh1_anticorr },\n  { \"Rice8\", Rice8 }, { \"Rice1\", Rice1 }, { \"Rice1_corr\", Rice1_corr },\n  { \"Rice1_anticorr\", Rice1_anticorr }, { \"AWGN\", AWGN }, { NULL,-1 }\n};\n#if !defined(ENABLE_ITTI)\nstatic void *\nsigh (void *arg);\n#endif\nvoid\noai_shutdown (void);\n\nvoid reset_opp_meas_oaisim (void);\n\nvoid wait_eNBs(void)\n{\n  return;\n}\n\nvoid\nhelp (void)\n{\n  printf (\"Usage: oaisim -h -a -F -C tdd_config -K [log_file] -V [vcd_file] -R N_RB_DL -e -x transmission_mode -m target_dl_mcs -r(ate_adaptation) -n n_frames -s snr_dB -k ricean_factor -t max_delay -f forgetting factor -A channel_model -z cooperation_flag -u nb_local_ue -U UE mobility -b nb_local_enb -B eNB_mobility -M ethernet_flag -p nb_master -g multicast_group -l log_level -c ocg_enable -T traffic model -D multicast network device\\n\");\n\n  printf (\"-h provides this help message!\\n\");\n  printf (\"-a Activates PHY abstraction mode\\n\");\n  printf (\"-A set the multipath channel simulation,  options are: SCM_A, SCM_B, SCM_C, SCM_D, EPA, EVA, ETU, Rayleigh8, Rayleigh1, Rayleigh1_corr,Rayleigh1_anticorr, Rice8,, Rice1, AWGN \\n\");\n  printf (\"-b Set the number of local eNB\\n\");\n  printf (\"-B Set the mobility model for eNB, options are: STATIC, RWP, RWALK, \\n\");\n  printf (\"-c [1,2,3,4] Activate the config generator (OCG) to process the scenario descriptor, or give the scenario manually: -c template_1.xml \\n\");\n  printf (\"-C [0-6] Sets TDD configuration\\n\");\n  printf (\"-e Activates extended prefix mode\\n\");\n  printf (\"-E Random number generator seed\\n\");\n  printf (\"-f Set the forgetting factor for time-variation\\n\");\n  printf (\"-F Activates FDD transmission (TDD is default)\\n\");\n  printf (\"-g Set multicast group ID (0,1,2,3) - valid if M is set\\n\");\n  printf (\"-G Enable background traffic \\n\");\n  printf (\"-H Enable handover operation (default disabled) \\n\");\n  printf (\"-I Enable CLI interface (to connect use telnet localhost 1352)\\n\");\n  printf (\"-k Set the Ricean factor (linear)\\n\");\n  printf (\"-K [log_file] Enable ITTI logging into log_file\\n\");\n  printf (\"-l Set the global log level (8:trace, 7:debug, 6:info, 4:warn, 3:error) \\n\");\n  printf (\"-L [0-1] 0 to disable new link adaptation, 1 to enable new link adapatation\\n\");\n  printf (\"-m Gives a fixed DL mcs for eNB scheduler\\n\");\n  printf (\"-M Set the machine ID for Ethernet-based emulation\\n\");\n  printf (\"-n Set the number of frames for the simulation. 0 for no limit\\n\");\n  printf (\"-O [enb_conf_file] eNB configuration file name\\n\");\n  printf (\"-p Set the total number of machine in emulation - valid if M is set\\n\");\n  printf (\"-P [trace type] Enable protocol analyzer. Possible values for OPT:\\n\");\n  printf (\"    - wireshark: Enable tracing of layers above PHY using an UDP socket\\n\");\n  printf (\"    - pcap:      Enable tracing of layers above PHY to a pcap file\\n\");\n  printf (\"    - tshark:    Not implemented yet\\n\");\n  printf (\"-q Enable Openair performance profiler \\n\");\n  printf (\"-Q Activate and set the MBMS service: 0 : not used (default eMBMS disabled), 1: eMBMS and RRC Connection enabled, 2: eMBMS relaying and RRC Connection enabled, 3: eMBMS enabled, RRC Connection disabled, 4: eMBMS relaying enabled, RRC Connection disabled\\n\");\n  printf (\"-R [6,15,25,50,75,100] Sets N_RB_DL\\n\");\n  printf (\"-r Activates rate adaptation (DL for now)\\n\");\n  printf (\"-s snr_dB set a fixed (average) SNR, this deactivates the openair channel model generator (OCM)\\n\");\n  printf (\"-S snir_dB set a fixed (average) SNIR, this deactivates the openair channel model generator (OCM)\\n\");\n  printf (\"-t Gives a fixed UL mcs for eNB scheduler\\n\");\n  printf (\"-T activate the traffic generator. Valide options are m2m,scbr,mcbr,bcbr,auto_pilot,bicycle_race,open_arena,team_fortress,m2m_traffic,auto_pilot_l,auto_pilot_m,auto_pilot_h,auto_pilot_e,virtual_game_l,virtual_game_m,virtual_game_h,virtual_game_f,alarm_humidity,alarm_smoke,alarm_temperature,openarena_dl,openarena_ul,voip_g711,voip_g729,video_vbr_10mbps,video_vbr_4mbps,video_vbr_2mbp,video_vbr_768kbps,video_vbr_384kbps,video_vbr_192kpbs,background_users\\n\");\n  printf (\"-u Set the number of local UE\\n\");\n  printf (\"-U Set the mobility model for UE, options are: STATIC, RWP, RWALK\\n\");\n  printf (\"-V [vcd_file] Enable VCD dump into vcd_file\\n\");\n  printf (\"-w number of CBA groups, if not specified or zero, CBA is inactive\\n\");\n#ifdef SMBV\n  printf (\"-W IP address to connect to Rohde&Schwarz SMBV100A and configure SMBV from config file. -W0 uses default IP 192.168.12.201\\n\");\n#else\n  printf (\"-W [Rohde&Schwarz SMBV100A functions disabled. Recompile with SMBV=1]\\n\");\n#endif\n  printf (\"-x deprecated. Set the transmission mode in config file!\\n\");\n  printf (\"-y Set the number of receive antennas at the UE (1 or 2)\\n\");\n  printf (\"-Y Set the global log verbosity (none, low, medium, high, full) \\n\");\n  printf (\"-z Set the cooperation flag (0 for no cooperation, 1 for delay diversity and 2 for distributed alamouti\\n\");\n  printf (\"-Z Reserved\\n\");\n  printf (\"--xforms Activate the grapical scope\\n\");\n\n#if T_TRACER\n  printf (\"--T_port [port]    use given port\\n\");\n  printf (\"--T_nowait         don't wait for tracer, start immediately\\n\");\n  printf (\"--T_dont_fork      to ease debugging with gdb\\n\");\n#endif\n}\n\npthread_t log_thread;\n\nvoid\nlog_thread_init (void)\n{\n  //create log_list\n  //log_list_init(&log_list);\n#ifndef LOG_NO_THREAD\n\n  log_shutdown = 0;\n\n  if ((pthread_mutex_init (&log_lock, NULL) != 0)\n      || (pthread_cond_init (&log_notify, NULL) != 0)) {\n    return;\n  }\n\n  if (pthread_create (&log_thread, NULL, log_thread_function, (void*) NULL)\n      != 0) {\n    log_thread_finalize ();\n    return;\n  }\n\n#endif\n\n}\n\n//Call it after the last LOG call\nint\nlog_thread_finalize (void)\n{\n  int err = 0;\n\n#ifndef LOG_NO_THREAD\n\n  if (pthread_mutex_lock (&log_lock) != 0) {\n    return -1;\n  }\n\n  log_shutdown = 1;\n\n  /* Wake up LOG thread */\n  if ((pthread_cond_broadcast (&log_notify) != 0)\n      || (pthread_mutex_unlock (&log_lock) != 0)) {\n    err = -1;\n  }\n\n  if (pthread_join (log_thread, NULL) != 0) {\n    err = -1;\n  }\n\n  if (pthread_mutex_unlock (&log_lock) != 0) {\n    err = -1;\n  }\n\n  if (!err) {\n    //log_list_free(&log_list);\n    pthread_mutex_lock (&log_lock);\n    pthread_mutex_destroy (&log_lock);\n    pthread_cond_destroy (&log_notify);\n  }\n\n#endif\n\n  return err;\n}\n\n#if defined(ENABLE_ITTI)\nstatic void set_cli_start(module_id_t module_idP, uint8_t start)\n{\n  if (module_idP < NB_eNB_INST) {\n    oai_emulation.info.cli_start_enb[module_idP] = start;\n  } else {\n    oai_emulation.info.cli_start_ue[module_idP - NB_eNB_INST] = start;\n  }\n}\n#endif\n\n#ifdef OPENAIR2\nint omv_write(int pfd, node_list* enb_node_list, node_list* ue_node_list, Data_Flow_Unit omv_data)\n{\n  module_id_t i;\n  omv_data.end = 0;\n\n  //omv_data.total_num_nodes = NB_UE_INST + NB_eNB_INST;\n  for (i = 0; i < NB_eNB_INST; i++) {\n    if (enb_node_list != NULL) {\n      omv_data.geo[i].x = (enb_node_list->node->x_pos < 0.0) ? 0.0 : enb_node_list->node->x_pos;\n      omv_data.geo[i].y = (enb_node_list->node->y_pos < 0.0) ? 0.0 : enb_node_list->node->y_pos;\n      omv_data.geo[i].z = 1.0;\n      omv_data.geo[i].mobility_type = oai_emulation.info.omg_model_enb;\n      omv_data.geo[i].node_type = 0; //eNB\n      enb_node_list = enb_node_list->next;\n      omv_data.geo[i].Neighbors = 0;\n/*\n      for (j = NB_RU; j < NB_UE_INST + NB_RU; j++) {\n        if (is_UE_active (i, j - NB_RU) == 1) {\n          omv_data.geo[i].Neighbor[omv_data.geo[i].Neighbors] = j;\n          omv_data.geo[i].Neighbors++;\n          LOG_D(\n\t\tOMG,\n\t\t\"[RU %d][UE %d] is_UE_active(i,j) %d geo (x%d, y%d) num neighbors %d\\n\", i, j-NB_RU, is_UE_active(i,j-NB_RU), omv_data.geo[i].x, omv_data.geo[i].y, omv_data.geo[i].Neighbors);\n        }\n      }\n*/\n    }\n  }\n\n  for (i = NB_RU; i < NB_UE_INST + NB_RU; i++) {\n    if (ue_node_list != NULL) {\n      omv_data.geo[i].x = (ue_node_list->node->x_pos < 0.0) ? 0.0 : ue_node_list->node->x_pos;\n      omv_data.geo[i].y = (ue_node_list->node->y_pos < 0.0) ? 0.0 : ue_node_list->node->y_pos;\n      omv_data.geo[i].z = 1.0;\n      omv_data.geo[i].mobility_type = oai_emulation.info.omg_model_ue;\n      omv_data.geo[i].node_type = 1; //UE\n      //trial\n      omv_data.geo[i].state = 1;\n      omv_data.geo[i].rnti = 88;\n      omv_data.geo[i].connected_eNB = 0;\n      omv_data.geo[i].RSRP = 66;\n      omv_data.geo[i].RSRQ = 55;\n      omv_data.geo[i].Pathloss = 44;\n      omv_data.geo[i].RSSI[0] = 33;\n      omv_data.geo[i].RSSI[1] = 22;\n\n      if ((sizeof(omv_data.geo[0].RSSI) / sizeof(omv_data.geo[0].RSSI[0])) > 2) {\n        omv_data.geo[i].RSSI[2] = 11;\n      }\n\n      ue_node_list = ue_node_list->next;\n      omv_data.geo[i].Neighbors = 0;\n/*\n      for (j = 0; j < NB_RU; j++) {\n        if (is_UE_active (j, i - NB_RU) == 1) {\n          omv_data.geo[i].Neighbor[omv_data.geo[i].Neighbors] = j;\n          omv_data.geo[i].Neighbors++;\n          LOG_D(\n\t\tOMG,\n\t\t\"[UE %d][RU %d] is_UE_active  %d geo (x%d, y%d) num neighbors %d\\n\", i-NB_RU, j, is_UE_active(j,i-NB_RU), omv_data.geo[i].x, omv_data.geo[i].y, omv_data.geo[i].Neighbors);\n        }\n      }\n*/\n    }\n  }\n\n  LOG_E(OMG, \"pfd %d \\n\", pfd);\n\n  if (write (pfd, &omv_data, sizeof(struct Data_Flow_Unit)) == -1)\n    perror (\"write omv failed\");\n\n  return 1;\n}\n\nvoid omv_end(int pfd, Data_Flow_Unit omv_data)\n{\n  omv_data.end = 1;\n\n  if (write (pfd, &omv_data, sizeof(struct Data_Flow_Unit)) == -1)\n    perror (\"write omv failed\");\n}\n#endif\n\n#ifdef OPENAIR2\nint pfd[2]; // fd for omv : fixme: this could be a local var\n#endif\n\n#ifdef OPENAIR2\nstatic Data_Flow_Unit omv_data;\n#endif //ALU\nstatic module_id_t UE_inst = 0;\nstatic module_id_t eNB_inst = 0;\nstatic module_id_t ru_id;\n\nPacket_OTG_List_t *otg_pdcp_buffer;\n\ntypedef enum l2l1_task_state_e {\n  L2L1_WAITTING, L2L1_RUNNING, L2L1_TERMINATED,\n} l2l1_task_state_t;\n\nl2l1_task_state_t l2l1_state = L2L1_WAITTING;\n\nextern openair0_timestamp current_ru_rx_timestamp[NUMBER_OF_RU_MAX][MAX_NUM_CCs];\nextern openair0_timestamp current_UE_rx_timestamp[NUMBER_OF_UE_MAX][MAX_NUM_CCs];\nextern openair0_timestamp last_eNB_rx_timestamp[NUMBER_OF_eNB_MAX][MAX_NUM_CCs];\nextern openair0_timestamp last_UE_rx_timestamp[NUMBER_OF_UE_MAX][MAX_NUM_CCs];\n\n/*------------------------------------------------------------------------------*/\nvoid *\nl2l1_task (void *args_p)\n{\n\n  int CC_id;\n\n  // Framing variables\n  int32_t sf;\n\n  //char fname[64], vname[64];\n\n  //#ifdef XFORMS\n  // current status is that every UE has a DL scope for a SINGLE eNB (eNB_id=0)\n  // at eNB 0, an UL scope for every UE\n  FD_lte_phy_scope_ue *form_ue[MAX_NUM_CCs][NUMBER_OF_UE_MAX];\n  FD_lte_phy_scope_enb *form_enb[NUMBER_OF_UE_MAX];\n  char title[255];\n  char xname[32] = \"oaisim\";\n  int xargc = 1;\n  char *xargv[1];\n  //#endif\n\n#undef PRINT_STATS /* this undef is to avoid gcc warnings */\n#define PRINT_STATS\n#ifdef PRINT_STATS\n  //int len;\n  FILE *UE_stats[NUMBER_OF_UE_MAX];\n  FILE *UE_stats_th[NUMBER_OF_UE_MAX];\n  FILE *eNB_stats[NUMBER_OF_eNB_MAX];\n  FILE *eNB_avg_thr;\n  FILE *eNB_l2_stats;\n  char UE_stats_filename[255];\n  char eNB_stats_filename[255];\n  char UE_stats_th_filename[255];\n  char eNB_stats_th_filename[255];\n#endif\n\n\n  if (xforms==1) {\n    xargv[0] = xname;\n    fl_initialize (&xargc, xargv, NULL, 0, 0);\n    eNB_inst = 0;\n    for (UE_inst = 0; UE_inst < NB_UE_INST; UE_inst++) {\n      for (CC_id=0;CC_id<MAX_NUM_CCs;CC_id++) {\n\t// DL scope at UEs\n\tform_ue[CC_id][UE_inst] = create_lte_phy_scope_ue();\n\tsprintf (title, \"LTE DL SCOPE eNB %d to UE %d CC_id %d\", eNB_inst, UE_inst, CC_id);\n\tfl_show_form (form_ue[CC_id][UE_inst]->lte_phy_scope_ue, FL_PLACE_HOTSPOT, FL_FULLBORDER, title);\n\n\tif (PHY_vars_UE_g[UE_inst][CC_id]->use_ia_receiver == 1) {\n\t  fl_set_button(form_ue[CC_id][UE_inst]->button_0,1);\n\t  fl_set_object_label(form_ue[CC_id][UE_inst]->button_0, \"IA Receiver ON\");\n\t  fl_set_object_color(form_ue[CC_id][UE_inst]->button_0, FL_GREEN, FL_GREEN);\n\t}\n\t\n      }\n    }\n  }\n\n\n#ifdef PRINT_STATS\n\n  for (UE_inst=0; UE_inst<NB_UE_INST; UE_inst++) {\n    sprintf(UE_stats_filename,\"UE_stats%d.txt\",UE_inst);\n    UE_stats[UE_inst] = fopen (UE_stats_filename, \"w\");\n  }\n\n  for (eNB_inst=0; eNB_inst<NB_eNB_INST; eNB_inst++) {\n    sprintf(eNB_stats_filename,\"eNB_stats%d.txt\",eNB_inst);\n    eNB_stats[eNB_inst] = fopen (eNB_stats_filename, \"w\");\n  }\n\n  if(abstraction_flag==0) {\n    for (UE_inst=0; UE_inst<NB_UE_INST; UE_inst++) {\n      /* TODO: transmission_mode is defined per CC, we set 0 for now */\n      sprintf(UE_stats_th_filename,\"UE_stats_th%d_tx%d.txt\",UE_inst,oai_emulation.info.transmission_mode[0]);\n      UE_stats_th[UE_inst] = fopen (UE_stats_th_filename, \"w\");\n    }\n\n    /* TODO: transmission_mode is defined per CC, we set 0 for now */\n    sprintf(eNB_stats_th_filename,\"eNB_stats_th_tx%d.txt\",oai_emulation.info.transmission_mode[0]);\n    eNB_avg_thr = fopen (eNB_stats_th_filename, \"w\");\n  } else {\n    for (UE_inst=0; UE_inst<NB_UE_INST; UE_inst++) {\n      /* TODO: transmission_mode is defined per CC, we set 0 for now */\n      sprintf(UE_stats_th_filename,\"UE_stats_abs_th%d_tx%d.txt\",UE_inst,oai_emulation.info.transmission_mode[0]);\n      UE_stats_th[UE_inst] = fopen (UE_stats_th_filename, \"w\");\n    }\n\n    /* TODO: transmission_mode is defined per CC, we set 0 for now */\n    sprintf(eNB_stats_th_filename,\"eNB_stats_abs_th_tx%d.txt\",oai_emulation.info.transmission_mode[0]);\n    eNB_avg_thr = fopen (eNB_stats_th_filename, \"w\");\n  }\n\n#ifdef OPENAIR2\n  eNB_l2_stats = fopen (\"eNB_l2_stats.txt\", \"w\");\n  LOG_I(EMU,\"eNB_l2_stats=%p\\n\", eNB_l2_stats);\n#endif\n\n#endif\n\n#if defined(ENABLE_ITTI)\n  MessageDef *message_p = NULL;\n  const char *msg_name = NULL;\n  int result;\n\n  itti_mark_task_ready (TASK_L2L1);\n  LOG_I(EMU, \"TASK_L2L1 is READY\\n\");\n\n  if ((oai_emulation.info.nb_enb_local > 0) && \n      (oai_emulation.info.node_function[0] < NGFI_RAU_IF4p5)) {\n    /* Wait for the initialize message */\n    do {\n      if (message_p != NULL) {\n        result = itti_free (ITTI_MSG_ORIGIN_ID(message_p), message_p);\n        AssertFatal (result == EXIT_SUCCESS, \"Failed to free memory (%d)!\\n\", result);\n      }\n\n      itti_receive_msg (TASK_L2L1, &message_p);\n      msg_name = ITTI_MSG_NAME (message_p);\n      LOG_I(EMU, \"TASK_L2L1 received %s in state L2L1_WAITTING\\n\", msg_name);\n\n      switch (ITTI_MSG_ID(message_p)) {\n      case INITIALIZE_MESSAGE:\n        l2l1_state = L2L1_RUNNING;\n        start_eNB = 1;\n        break;\n\n      case ACTIVATE_MESSAGE:\n        set_cli_start(ITTI_MSG_INSTANCE (message_p), 1);\n        break;\n\n      case DEACTIVATE_MESSAGE:\n        set_cli_start(ITTI_MSG_INSTANCE (message_p), 0);\n        break;\n\n      case TERMINATE_MESSAGE:\n        l2l1_state = L2L1_TERMINATED;\n        break;\n\n      default:\n        LOG_E(EMU, \"Received unexpected message %s\\n\", ITTI_MSG_NAME(message_p));\n        break;\n      }\n    } while (l2l1_state == L2L1_WAITTING);\n\n    result = itti_free (ITTI_MSG_ORIGIN_ID(message_p), message_p);\n    AssertFatal (result == EXIT_SUCCESS, \"Failed to free memory (%d)!\\n\", result);\n  }\n\n#endif\n  module_id_t UE_id;\n\n  if (abstraction_flag == 1) {\n    for (UE_id = 0; UE_id < NB_UE_INST; UE_id++)\n      dl_phy_sync_success (UE_id, 0, 0,1);   //UE_id%NB_eNB_INST);\n  }\n  \n  start_meas (&oaisim_stats);\n\n  for (frame = 0;\n       (l2l1_state != L2L1_TERMINATED) && \n\t ((oai_emulation.info.n_frames_flag == 0) ||\n\t  (frame < oai_emulation.info.n_frames));\n       frame++) {\n\n#if defined(ENABLE_ITTI)\n\n    do {\n      // Checks if a message has been sent to L2L1 task\n      itti_poll_msg (TASK_L2L1, &message_p);\n\n      if (message_p != NULL) {\n        msg_name = ITTI_MSG_NAME (message_p);\n        LOG_I(EMU, \"TASK_L2L1 received %s\\n\", msg_name);\n\n        switch (ITTI_MSG_ID(message_p)) {\n        case ACTIVATE_MESSAGE:\n          set_cli_start(ITTI_MSG_INSTANCE (message_p), 1);\n          break;\n\n        case DEACTIVATE_MESSAGE:\n          set_cli_start(ITTI_MSG_INSTANCE (message_p), 0);\n          break;\n\n        case TERMINATE_MESSAGE:\n          l2l1_state = L2L1_TERMINATED;\n          break;\n\n        case MESSAGE_TEST:\n          break;\n\n        default:\n          LOG_E(EMU, \"Received unexpected message %s\\n\", ITTI_MSG_NAME(message_p));\n          break;\n        }\n\n        result = itti_free (ITTI_MSG_ORIGIN_ID(message_p), message_p);\n        AssertFatal (result == EXIT_SUCCESS, \"Failed to free memory (%d)!\\n\", result);\n      }\n    } while(message_p != NULL);\n\n#endif\n\n    //Run the aperiodic user-defined events\n    if (oai_emulation.info.oeh_enabled == 1)\n      execute_events (frame);\n\n    if (ue_connection_test == 1) {\n      if ((frame % 20) == 0) {\n        snr_dB += snr_direction;\n        sinr_dB -= snr_direction;\n      }\n\n      if (snr_dB == -20) {\n        snr_direction = snr_step;\n      } else if (snr_dB == 20) {\n        snr_direction = -snr_step;\n      }\n    }\n\n    oai_emulation.info.frame = frame;\n    //oai_emulation.info.time_ms += 1;\n    oai_emulation.info.time_s += 0.01; // emu time in s, each frame lasts for 10 ms // JNote: TODO check the coherency of the time and frame (I corrected it to 10 (instead of 0.01)\n\n    update_omg (frame); // frequency is defined in the omg_global params configurable by the user\n    update_omg_ocm ();\n\n#ifdef OPENAIR2\n\n    // check if pipe is still open\n    if ((oai_emulation.info.omv_enabled == 1)) {\n      omv_write (pfd[1], enb_node_list, ue_node_list, omv_data);\n    }\n\n#endif\n\n\n\n    for (sf = 0; sf < 10; sf++) {\n      LOG_D(EMU,\"************************* Subframe %d\\n\",sf);\n      start_meas (&oaisim_stats_f);\n\n      wait_for_slot_isr ();\n\n#if defined(ENABLE_ITTI)\n      itti_update_lte_time(frame % MAX_FRAME_NUMBER, sf<<1);\n#endif\n\n      oai_emulation.info.time_ms = frame * 10 + sf;\n\n#ifdef PROC\n\n    if(Channel_Flag==1)\n      Channel_Func(s_re2,s_im2,r_re2,r_im2,r_re02,r_im02,r_re0_d,r_im0_d,r_re0_u,r_im0_u,RU2UE,UE2RU,enb_data,ue_data,abstraction_flag,frame_parms,sf<<1);\n\n    if(Channel_Flag==0)\n#endif\n      { // SUBFRAME INNER PART\n#if defined(ENABLE_ITTI)\n        log_set_instance_type (LOG_INSTANCE_ENB);\n#endif\n\n\n\tCC_id=0;\n        int all_done=0;\n\n        while (all_done==0) {\n\n          pthread_mutex_lock(&subframe_mutex);\n          int subframe_ru_mask_local = subframe_ru_mask;\n          int subframe_UE_mask_local  = subframe_UE_mask;\n          pthread_mutex_unlock(&subframe_mutex);\n          LOG_D(EMU,\"Frame %d, Subframe %d, NB_RU %d, NB_UE %d: Checking masks %x,%x\\n\",frame,sf,NB_RU,NB_UE_INST,subframe_ru_mask_local,subframe_UE_mask_local);\n          if ((subframe_ru_mask_local == ((1<<NB_RU)-1)) &&\n              (subframe_UE_mask_local == ((1<<NB_UE_INST)-1)))\n             all_done=1;\n          else\n\t    usleep(1500);\n        }\n\n\n        //clear subframe masks for next round\n        pthread_mutex_lock(&subframe_mutex);\n        subframe_ru_mask=0;\n        subframe_UE_mask=0;\n        pthread_mutex_unlock(&subframe_mutex);\n\n        // increment timestamps\n\t/*\n        for (ru_id = oai_emulation.info.first_enb_local;\n             (ru_id\n              < (oai_emulation.info.first_enb_local\n                 + oai_emulation.info.nb_enb_local));\n             ru_id++) {\n\t*/\n\tfor (ru_id=0;ru_id<NB_RU;ru_id++) {\n\t  current_ru_rx_timestamp[ru_id][CC_id] += RC.ru[ru_id]->frame_parms.samples_per_tti;\n\t  LOG_D(EMU,\"RU %d/%d: TS %\"PRIi64\"\\n\",ru_id,CC_id,current_ru_rx_timestamp[ru_id][CC_id]);\n        }\n        for (UE_inst = 0; UE_inst<NB_UE_INST;UE_inst++) {\n\t  current_UE_rx_timestamp[UE_inst][CC_id] += PHY_vars_UE_g[UE_inst][CC_id]->frame_parms.samples_per_tti;\n\t  LOG_D(EMU,\"UE %d/%d: TS %\"PRIi64\"\\n\",UE_inst,CC_id,current_UE_rx_timestamp[UE_inst][CC_id]);\n        }\n\n        for (eNB_inst = oai_emulation.info.first_enb_local;\n             (eNB_inst\n              < (oai_emulation.info.first_enb_local\n                 + oai_emulation.info.nb_enb_local));\n             eNB_inst++) {\n          if (oai_emulation.info.cli_start_enb[eNB_inst] != 0) {\n        \n\t    /*\n\t    LOG_D(EMU,\n\t\t  \"PHY procedures eNB %d for frame %d, subframe %d TDD %d/%d Nid_cell %d\\n\",\n\t\t  eNB_inst,\n\t\t  frame % MAX_FRAME_NUMBER,\n\t\t  sf,\n\t\t  PHY_vars_eNB_g[eNB_inst][0]->frame_parms.frame_type,\n\t\t  PHY_vars_eNB_g[eNB_inst][0]->frame_parms.tdd_config,\n\t\t  PHY_vars_eNB_g[eNB_inst][0]->frame_parms.Nid_cell);\n            \n\t    */\n#ifdef OPENAIR2\n\t    //Application: traffic gen\n            update_otg_eNB (eNB_inst, oai_emulation.info.time_ms);\n\n            //IP/OTG to PDCP and PDCP to IP operation\n            //        pdcp_run (frame, 1, 0, eNB_inst); //PHY_vars_eNB_g[eNB_id]->Mod_id\n#endif\n           \n\n#ifdef PRINT_STATS\n\n            if((sf==9) && frame%10==0)\n              if(eNB_avg_thr)\n                fprintf(eNB_avg_thr,\"%d %d\\n\",RC.eNB[eNB_inst][0]->proc.proc_rxtx[sf&1].frame_tx,\n                        (RC.eNB[eNB_inst][0]->total_system_throughput)/((RC.eNB[eNB_inst][0]->proc.proc_rxtx[sf&1].frame_tx+1)*10));\n\t    /*\n            if (eNB_stats[eNB_inst]) {\n              len = dump_eNB_stats(RC.eNB[eNB_inst][0], stats_buffer, 0);\n              rewind (eNB_stats[eNB_inst]);\n              fwrite (stats_buffer, 1, len, eNB_stats[eNB_inst]);\n              fflush(eNB_stats[eNB_inst]);\n            }\n\t    */\n#ifdef OPENAIR2\n/*\n            if (eNB_l2_stats) {\n              len = dump_eNB_l2_stats (stats_buffer, 0);\n              rewind (eNB_l2_stats);\n              fwrite (stats_buffer, 1, len, eNB_l2_stats);\n              fflush(eNB_l2_stats);\n            }\n*/\n\n#endif\n#endif\n          }\n        }// eNB_inst loop\n\n\n#if defined(ENABLE_ITTI)\n        log_set_instance_type (LOG_INSTANCE_UE);\n#endif\n\n\n\tif ((sf == 0) && ((frame % MAX_FRAME_NUMBER) == 0) && (abstraction_flag == 0)\n\t    && (oai_emulation.info.n_frames == 1)) {\n\t  \n\t  write_output (\"dlchan0.m\",\n\t\t\t\"dlch0\",\n\t\t\t&(PHY_vars_UE_g[0][0]->common_vars.common_vars_rx_data_per_thread[0].dl_ch_estimates[0][0][0]),\n\t\t\t(6\n\t\t\t * (PHY_vars_UE_g[0][0]->frame_parms.ofdm_symbol_size)),\n\t\t\t1, 1);\n\t  write_output (\"dlchan1.m\",\n\t\t\t\"dlch1\",\n\t\t\t&(PHY_vars_UE_g[0][0]->common_vars.common_vars_rx_data_per_thread[0].dl_ch_estimates[1][0][0]),\n\t\t\t(6\n\t\t\t * (PHY_vars_UE_g[0][0]->frame_parms.ofdm_symbol_size)),\n\t\t\t1, 1);\n\t  write_output (\"dlchan2.m\",\n\t\t\t\"dlch2\",\n\t\t\t&(PHY_vars_UE_g[0][0]->common_vars.common_vars_rx_data_per_thread[0].dl_ch_estimates[2][0][0]),\n\t\t\t(6\n\t\t\t * (PHY_vars_UE_g[0][0]->frame_parms.ofdm_symbol_size)),\n\t\t\t1, 1);\n\t  write_output (\"pbch_rxF_comp0.m\",\n\t\t\t\"pbch_comp0\",\n\t\t\tPHY_vars_UE_g[0][0]->pbch_vars[0]->rxdataF_comp[0],\n\t\t\t6 * 12 * 4, 1, 1);\n\t  write_output (\"pbch_rxF_llr.m\", \"pbch_llr\",\n\t\t\tPHY_vars_UE_g[0][0]->pbch_vars[0]->llr,\n\t\t\t(PHY_vars_UE_g[0][0]->frame_parms.Ncp == 0) ? 1920 : 1728, 1,\n\t\t\t4);\n\t}\n    \n\tstop_meas (&oaisim_stats_f);\n      } // SUBFRAME INNER PART\n\n\n    }\n    update_ocm ();\n    /*\n    if ((frame >= 10) && (frame <= 11) && (abstraction_flag == 0)\n#ifdef PROC\n\t&&(Channel_Flag==0)\n#endif\n\t) {\n      sprintf (fname, \"UEtxsig%d.m\", frame % MAX_FRAME_NUMBER);\n      sprintf (vname, \"txs%d\", frame % MAX_FRAME_NUMBER);\n      write_output (fname,\n\t\t    vname,\n\t\t    PHY_vars_UE_g[0][0]->common_vars.txdata[0],\n\t\t    PHY_vars_UE_g[0][0]->frame_parms.samples_per_tti\n\t\t    * 10,\n\t\t    1, 1);\n      sprintf (fname, \"eNBtxsig%d.m\", frame % MAX_FRAME_NUMBER);\n      sprintf (vname, \"txs%d\", frame % MAX_FRAME_NUMBER);\n      write_output (fname,\n\t\t    vname,\n\t\t    PHY_vars_eNB_g[0][0]->common_vars.txdata[0][0],\n\t\t    PHY_vars_UE_g[0][0]->frame_parms.samples_per_tti\n\t\t    * 10,\n\t\t    1, 1);\n      sprintf (fname, \"eNBtxsigF%d.m\", frame % MAX_FRAME_NUMBER);\n      sprintf (vname, \"txsF%d\", frame % MAX_FRAME_NUMBER);\n      write_output (fname,\n\t\t    vname,\n\t\t    PHY_vars_eNB_g[0][0]->common_vars.txdataF[0][0],\n\t\t    PHY_vars_eNB_g[0][0]->frame_parms.symbols_per_tti\n\t\t    * PHY_vars_eNB_g[0][0]->frame_parms.ofdm_symbol_size,\n\t\t    1, 1);\n      sprintf (fname, \"UErxsig%d.m\", frame % MAX_FRAME_NUMBER);\n      sprintf (vname, \"rxs%d\", frame % MAX_FRAME_NUMBER);\n      write_output (fname,\n\t\t    vname,\n\t\t    PHY_vars_UE_g[0][0]->common_vars.rxdata[0],\n\t\t    PHY_vars_UE_g[0][0]->frame_parms.samples_per_tti\n\t\t    * 10,\n\t\t    1, 1);\n      sprintf (fname, \"eNBrxsig%d.m\", frame % MAX_FRAME_NUMBER);\n      sprintf (vname, \"rxs%d\", frame % MAX_FRAME_NUMBER);\n      write_output (fname,\n\t\t    vname,\n\t\t    PHY_vars_eNB_g[0][0]->common_vars.rxdata[0][0],\n\t\t    PHY_vars_UE_g[0][0]->frame_parms.samples_per_tti\n\t\t    * 10,\n\t\t    1, 1);\n    }\n    */\n    \n    //#ifdef XFORMS\n    if (xforms==1) {\n      eNB_inst = 0;\n      \n      for (UE_inst = 0; UE_inst < NB_UE_INST; UE_inst++) {\n\tfor (CC_id=0;CC_id<MAX_NUM_CCs;CC_id++) {\n\t  phy_scope_UE(form_ue[CC_id][UE_inst],\n\t\t   PHY_vars_UE_g[UE_inst][CC_id],\n\t\t   eNB_inst,\n\t\t   UE_inst,\n\t\t   7);\n\t}\n\tif (RC.eNB && RC.eNB[eNB_inst] && RC.eNB[eNB_inst][0] )\n\t  phy_scope_eNB(form_enb[UE_inst],\n\t\t\tRC.eNB[eNB_inst][0],\n\t\t\tUE_inst);\n\t\n      }\n    }\n    //#endif\n    \n#ifdef SMBV\n    \n    // Rohde&Schwarz SMBV100A vector signal generator\n    if ((frame % MAX_FRAME_NUMBER == config_frames[0]) || (frame % MAX_FRAME_NUMBER == config_frames[1]) || (frame % MAX_FRAME_NUMBER == config_frames[2]) || (frame % MAX_FRAME_NUMBER == config_frames[3])) {\n      smbv_frame_cnt++;\n    }\n    \n#endif\n    \n  } // frame loop\n\n  stop_meas (&oaisim_stats);\n  oai_shutdown ();\n  \n#ifdef PRINT_STATS\n  \n  for (UE_inst=0; UE_inst<NB_UE_INST; UE_inst++) {\n    if (UE_stats[UE_inst])\n      fclose (UE_stats[UE_inst]);\n    \n    if(UE_stats_th[UE_inst])\n      fclose (UE_stats_th[UE_inst]);\n  }\n  \n  for (eNB_inst=0; eNB_inst<NB_eNB_INST; eNB_inst++) {\n    if (eNB_stats[eNB_inst])\n      fclose (eNB_stats[eNB_inst]);\n  }\n  \n  if (eNB_avg_thr)\n    fclose (eNB_avg_thr);\n  \n  if (eNB_l2_stats)\n    fclose (eNB_l2_stats);\n  \n#endif\n  \n#if defined(ENABLE_ITTI)\n  itti_terminate_tasks(TASK_L2L1);\n#endif\n  \n  return NULL;\n}\n\n/*\n * The following two functions are meant to restart *the lte-softmodem* and are\n * here to make oaisim compile. A restart command from the controller will be\n * ignored in oaisim.\n */\nint stop_L1L2(int enb_id)\n{\n  LOG_W(FLEXRAN_AGENT, \"stop_L1L2() not supported in oaisim\\n\");\n  return 0;\n}\n\nint restart_L1L2(int enb_id)\n{\n  LOG_W(FLEXRAN_AGENT, \"restart_L1L2() not supported in oaisim\\n\");\n  return 0;\n}\n\n#if T_TRACER\nint T_wait = 1;       /* by default we wait for the tracer */\nint T_port = 2021;    /* default port to listen to to wait for the tracer */\nint T_dont_fork = 0;  /* default is to fork, see 'T_init' to understand */\n#endif\n\n\nvoid wait_RUs(void)\n{\n  int i;\n\n  // wait for all RUs to be configured over fronthaul\n  pthread_mutex_lock(&RC.ru_mutex);\n\n\n\n  while (RC.ru_mask>0) {\n    pthread_cond_wait(&RC.ru_cond,&RC.ru_mutex);\n  }\n\n  // copy frame parameters from RU to UEs\n  for (i=0;i<NB_UE_INST;i++) {\n    PHY_vars_UE_g[i][0]->frame_parms.N_RB_DL              = RC.ru[0]->frame_parms.N_RB_DL;\n    PHY_vars_UE_g[i][0]->frame_parms.N_RB_UL              = RC.ru[0]->frame_parms.N_RB_UL;\n    PHY_vars_UE_g[i][0]->frame_parms.nb_antennas_tx       = 1;\n    PHY_vars_UE_g[i][0]->frame_parms.nb_antennas_rx       = 1;\n    // set initially to 2, it will be revised after initial synchronization\n    PHY_vars_UE_g[i][0]->frame_parms.nb_antenna_ports_eNB = 2;\n    PHY_vars_UE_g[i][0]->frame_parms.tdd_config = 1;\n    PHY_vars_UE_g[i][0]->frame_parms.dl_CarrierFreq       = RC.ru[0]->frame_parms.dl_CarrierFreq;\n    PHY_vars_UE_g[i][0]->frame_parms.ul_CarrierFreq       = RC.ru[0]->frame_parms.ul_CarrierFreq;\n    PHY_vars_UE_g[i][0]->frame_parms.eutra_band           = RC.ru[0]->frame_parms.eutra_band;\n    LOG_I(PHY,\"Initializing UE %d frame parameters from RU information: N_RB_DL %d, p %d, dl_Carrierfreq %u, ul_CarrierFreq %u, eutra_band %d\\n\",\n\t  i,\n\t  PHY_vars_UE_g[i][0]->frame_parms.N_RB_DL,\n\t  PHY_vars_UE_g[i][0]->frame_parms.nb_antenna_ports_eNB,\n\t  PHY_vars_UE_g[i][0]->frame_parms.dl_CarrierFreq,\n\t  PHY_vars_UE_g[i][0]->frame_parms.ul_CarrierFreq,\n\t  PHY_vars_UE_g[i][0]->frame_parms.eutra_band);\n\n    current_UE_rx_timestamp[i][0] = RC.ru[0]->frame_parms.samples_per_tti + RC.ru[0]->frame_parms.ofdm_symbol_size + RC.ru[0]->frame_parms.nb_prefix_samples0;\n\n  }\n  \n  \n\n\n  for (ru_id=0;ru_id<RC.nb_RU;ru_id++) current_ru_rx_timestamp[ru_id][0] = RC.ru[ru_id]->frame_parms.samples_per_tti;\n\n  printf(\"RUs are ready, let's go\\n\");\n}\n\nvoid init_UE(int,int,int,int);\nvoid init_RU(const char*);\n\nvoid set_UE_defaults(int nb_ue) {\n\n  for (int UE_id = 0;UE_id<nb_ue;UE_id++) {\n    for (int CC_id = 0;CC_id<MAX_NUM_CCs;CC_id++) {\n      for (uint8_t i=0; i<RX_NB_TH_MAX; i++) {\n\tPHY_vars_UE_g[UE_id][CC_id]->pdcch_vars[i][0]->dciFormat      = 0;\n\tPHY_vars_UE_g[UE_id][CC_id]->pdcch_vars[i][0]->agregationLevel      = 0xFF;\n      }\n      PHY_vars_UE_g[UE_id][CC_id]->current_dlsch_cqi[0] = 10;\n    }\n  }\n}\n\n\nstatic void print_current_directory(void)\n{\n  char dir[8192]; /* arbitrary size (should be big enough) */\n  if (getcwd(dir, 8192) == NULL)\n    printf(\"ERROR getting working directory\\n\");\n  else\n    printf(\"working directory: %s\\n\", dir);\n}\n\nvoid init_devices(void);\n\nint main (int argc, char **argv)\n{\n\n  clock_t t;\n\n  print_current_directory();\n\n  start_background_system();\n\n#ifdef SMBV\n  // Rohde&Schwarz SMBV100A vector signal generator\n  strcpy(smbv_ip,DEFAULT_SMBV_IP);\n#endif\n\n#ifdef PROC\n  int node_id;\n  int port,Process_Flag=0,wgt,Channel_Flag=0,temp;\n#endif\n\n  //default parameters\n  oai_emulation.info.n_frames = MAX_FRAME_NUMBER; //1024;          //10;\n  oai_emulation.info.n_frames_flag = 0; //fixme\n  snr_dB = 30;\n\n  //Default values if not changed by the user in get_simulation_options();\n  pdcp_period = 1;\n  omg_period = 1;\n  //Clean ip rule table\n  for(int i =0; i<NUMBER_OF_UE_MAX; i++){\n      char command_line[100];\n      sprintf(command_line, \"while ip rule del table %d; do true; done\",i+201);\n      /* we don't care about return value from system(), but let's the\n       * compiler be silent, so let's do \"if (XX);\"\n       */\n      if (system(command_line)) /* nothing */;\n  }\n  // start thread for log gen\n  log_thread_init ();\n\n  init_oai_emulation (); // to initialize everything !!!\n\n  // get command-line options\n  get_simulation_options (argc, argv); //Command-line options\n\n#if T_TRACER\n  T_init(T_port, T_wait, T_dont_fork);\n#endif\n\n  // Initialize VCD LOG module\n  VCD_SIGNAL_DUMPER_INIT (oai_emulation.info.vcd_file);\n\n#if !defined(ENABLE_ITTI)\n  pthread_t tid;\n  int err;\n  sigset_t sigblock;\n  sigemptyset (&sigblock);\n  sigaddset (&sigblock, SIGHUP);\n  sigaddset (&sigblock, SIGINT);\n  sigaddset (&sigblock, SIGTERM);\n  sigaddset (&sigblock, SIGQUIT);\n  //sigaddset(&sigblock, SIGKILL);\n\n  if ((err = pthread_sigmask (SIG_BLOCK, &sigblock, NULL)) != 0) {\n    printf (\"SIG_BLOCK error\\n\");\n    return -1;\n  }\n\n  if (pthread_create (&tid, NULL, sigh, NULL)) {\n    printf (\"Pthread for tracing Signals is not created!\\n\");\n    return -1;\n  } else {\n    printf (\"Pthread for tracing Signals is created!\\n\");\n  }\n\n#endif\n  // configure oaisim with OCG\n  oaisim_config (); // config OMG and OCG, OPT, OTG, OLG\n\n  if (ue_connection_test == 1) {\n    snr_direction = -snr_step;\n    snr_dB = 20;\n    sinr_dB = -20;\n  }\n\n  pthread_cond_init(&sync_cond,NULL);\n  pthread_mutex_init(&sync_mutex, NULL);\n  pthread_mutex_init(&subframe_mutex, NULL);\n\n#ifdef OPENAIR2\n  init_omv ();\n#endif\n  //Before this call, NB_UE_INST and NB_eNB_INST are not set correctly\n  check_and_adjust_params ();\n\n  set_seed = oai_emulation.emulation_config.seed.value;\n\n  init_otg_pdcp_buffer ();\n\n  init_seed (set_seed);\n\n\n  init_RU(NULL);\n\n  init_devices ();\n\n  //  init_openair2 ();\n  //  init_openair0();\n\n\n\n\n  if (create_tasks_ue(oai_emulation.info.nb_ue_local) < 0) \n      exit(-1); // need a softer mode\n\n\n  printf(\"Waiting for RUs to get set up\\n\"); \n  wait_RUs();\n\n  init_UE(NB_UE_INST,0,0,1);\n\n  set_UE_defaults(NB_UE_INST);\n\n\n  init_ocm ();\n  printf(\"Sending sync to all threads\\n\");\n\n\n  pthread_mutex_lock(&sync_mutex);\n  sync_var=0;\n  pthread_cond_broadcast(&sync_cond);\n  pthread_mutex_unlock(&sync_mutex);\n\n#ifdef SMBV\n  // Rohde&Schwarz SMBV100A vector signal generator\n  smbv_init_config(smbv_fname, smbv_nframes);\n  smbv_write_config_from_frame_parms(smbv_fname, &PHY_vars_eNB_g[0][0]->frame_parms);\n#endif\n\n  /* #if defined (FLEXRAN_AGENT_SB_IF)\n  flexran_agent_start();\n  #endif */ \n\n  // add events to future event list: Currently not used\n  //oai_emulation.info.oeh_enabled = 1;\n  if (oai_emulation.info.oeh_enabled == 1)\n    schedule_events ();\n\n  // oai performance profiler is enabled\n  if (oai_emulation.info.opp_enabled == 1)\n    reset_opp_meas_oaisim ();\n\n  cpuf=get_cpu_freq_GHz();\n\n  init_time ();\n\n  init_slot_isr ();\n\n  t = clock ();\n\n  LOG_N(EMU,\n        \">>>>>>>>>>>>>>>>>>>>>>>>>>> OAIEMU initialization done <<<<<<<<<<<<<<<<<<<<<<<<<<\\n\\n\");\n\n#ifndef PACKAGE_VERSION\n#  define PACKAGE_VERSION \"UNKNOWN-EXPERIMENTAL\"\n#endif\n  LOG_I(EMU, \"Version: %s\\n\", PACKAGE_VERSION);\n\n#if defined(ENABLE_ITTI)\n\n  // Handle signals until all tasks are terminated\n  itti_wait_tasks_end();\n\n#else\n\n  if (oai_emulation.info.nb_enb_local > 0) {\n    eNB_app_task (NULL); // do nothing for the moment\n  }\n\n  l2l1_task (NULL);\n#endif\n  t = clock () - t;\n  LOG_I(EMU, \"Duration of the simulation: %f seconds\\n\",\n        ((float) t) / CLOCKS_PER_SEC);\n\n  LOG_N(EMU,\n        \">>>>>>>>>>>>>>>>>>>>>>>>>>> OAIEMU Ending <<<<<<<<<<<<<<<<<<<<<<<<<<\\n\\n\");\n\n  raise (SIGINT);\n  //  oai_shutdown ();\n\n  return (0);\n}\n\nvoid\nreset_opp_meas_oaisim (void)\n{\n  uint8_t eNB_id = 0, UE_id = 0;\n\n  reset_meas (&oaisim_stats);\n  reset_meas (&oaisim_stats_f); // frame\n\n  // init time stats here (including channel)\n  reset_meas (&dl_chan_stats);\n  reset_meas (&ul_chan_stats);\n\n  for (UE_id = 0; UE_id < NB_UE_INST; UE_id++) {\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->phy_proc[0]);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->phy_proc[1]);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->phy_proc_rx[0]);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->phy_proc_rx[1]);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->phy_proc_tx);\n\n    //    reset_meas (&PHY_vars_UE_g[UE_id][0]->ofdm_demod_stats);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->rx_dft_stats);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_channel_estimation_stats);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_freq_offset_estimation_stats);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_decoding_stats[0]);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_decoding_stats[1]);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_rate_unmatching_stats);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_turbo_decoding_stats);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_deinterleaving_stats);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_llr_stats);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_unscrambling_stats);\n\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_tc_init_stats);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_tc_alpha_stats);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_tc_beta_stats);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_tc_gamma_stats);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_tc_ext_stats);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_tc_intl1_stats);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_tc_intl2_stats);\n\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->tx_prach);\n\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->ofdm_mod_stats);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->ulsch_encoding_stats);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->ulsch_modulation_stats);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->ulsch_segmentation_stats);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->ulsch_rate_matching_stats);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->ulsch_turbo_encoding_stats);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->ulsch_interleaving_stats);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->ulsch_multiplexing_stats);\n\n\n    /*\n     * L2 functions\n     */\n\n    // UE MAC\n    reset_meas (&UE_mac_inst[UE_id].ue_scheduler); // total\n    reset_meas (&UE_mac_inst[UE_id].tx_ulsch_sdu); // inlcude rlc_data_req + mac header gen\n    reset_meas (&UE_mac_inst[UE_id].rx_dlsch_sdu); // include mac_rrc_data_ind or mac_rlc_status_ind+mac_rlc_data_ind and  mac header parser\n    reset_meas (&UE_mac_inst[UE_id].ue_query_mch);\n    reset_meas (&UE_mac_inst[UE_id].rx_mch_sdu); // include rld_data_ind+ parse mch header\n    reset_meas (&UE_mac_inst[UE_id].rx_si); // include rlc_data_ind + mac header parser\n\n    reset_meas (&UE_pdcp_stats[UE_id].pdcp_run);\n    reset_meas (&UE_pdcp_stats[UE_id].data_req);\n    reset_meas (&UE_pdcp_stats[UE_id].data_ind);\n    reset_meas (&UE_pdcp_stats[UE_id].apply_security);\n    reset_meas (&UE_pdcp_stats[UE_id].validate_security);\n    reset_meas (&UE_pdcp_stats[UE_id].pdcp_ip);\n    reset_meas (&UE_pdcp_stats[UE_id].ip_pdcp);\n\n    \n  }\n\n  for (eNB_id = 0; eNB_id < NB_eNB_INST; eNB_id++) {\n\n    for (UE_id = 0; UE_id < NB_UE_INST; UE_id++) {\n      reset_meas (&RU2UE[eNB_id][UE_id][0]->random_channel);\n      reset_meas (&RU2UE[eNB_id][UE_id][0]->interp_time);\n      reset_meas (&RU2UE[eNB_id][UE_id][0]->interp_freq);\n      reset_meas (&RU2UE[eNB_id][UE_id][0]->convolution);\n      reset_meas (&UE2RU[UE_id][eNB_id][0]->random_channel);\n      reset_meas (&UE2RU[UE_id][eNB_id][0]->interp_time);\n      reset_meas (&UE2RU[UE_id][eNB_id][0]->interp_freq);\n      reset_meas (&UE2RU[UE_id][eNB_id][0]->convolution);\n    }\n\n    reset_meas (&RC.eNB[eNB_id][0]->phy_proc);\n    reset_meas (&RC.eNB[eNB_id][0]->phy_proc_rx);\n    reset_meas (&RC.eNB[eNB_id][0]->phy_proc_tx);\n    reset_meas (&RC.eNB[eNB_id][0]->rx_prach);\n\n    reset_meas (&RC.eNB[eNB_id][0]->ofdm_mod_stats);\n    reset_meas (&RC.eNB[eNB_id][0]->dlsch_encoding_stats);\n    reset_meas (&RC.eNB[eNB_id][0]->dlsch_modulation_stats);\n    reset_meas (&RC.eNB[eNB_id][0]->dlsch_scrambling_stats);\n    reset_meas (&RC.eNB[eNB_id][0]->dlsch_rate_matching_stats);\n    reset_meas (&RC.eNB[eNB_id][0]->dlsch_turbo_encoding_stats);\n    reset_meas (&RC.eNB[eNB_id][0]->dlsch_interleaving_stats);\n\n    //    reset_meas (&RC.eNB[eNB_id][0]->ofdm_demod_stats);\n    //reset_meas(&RC.eNB[eNB_id]->rx_dft_stats);\n    //reset_meas(&RC.eNB[eNB_id]->ulsch_channel_estimation_stats);\n    //reset_meas(&RC.eNB[eNB_id]->ulsch_freq_offset_estimation_stats);\n    reset_meas (&RC.eNB[eNB_id][0]->ulsch_decoding_stats);\n    reset_meas (&RC.eNB[eNB_id][0]->ulsch_demodulation_stats);\n    reset_meas (&RC.eNB[eNB_id][0]->ulsch_rate_unmatching_stats);\n    reset_meas (&RC.eNB[eNB_id][0]->ulsch_turbo_decoding_stats);\n    reset_meas (&RC.eNB[eNB_id][0]->ulsch_deinterleaving_stats);\n    reset_meas (&RC.eNB[eNB_id][0]->ulsch_demultiplexing_stats);\n    reset_meas (&RC.eNB[eNB_id][0]->ulsch_llr_stats);\n    reset_meas (&RC.eNB[eNB_id][0]->ulsch_tc_init_stats);\n    reset_meas (&RC.eNB[eNB_id][0]->ulsch_tc_alpha_stats);\n    reset_meas (&RC.eNB[eNB_id][0]->ulsch_tc_beta_stats);\n    reset_meas (&RC.eNB[eNB_id][0]->ulsch_tc_gamma_stats);\n    reset_meas (&RC.eNB[eNB_id][0]->ulsch_tc_ext_stats);\n    reset_meas (&RC.eNB[eNB_id][0]->ulsch_tc_intl1_stats);\n    reset_meas (&RC.eNB[eNB_id][0]->ulsch_tc_intl2_stats);\n#ifdef LOCALIZATION\n    reset_meas(&RC.eNB[eNB_id][0]->localization_stats);\n#endif\n\n    /*\n     * L2 functions\n     */\n    // eNB MAC\n    reset_meas (&RC.mac[eNB_id]->eNB_scheduler); // total\n    reset_meas (&RC.mac[eNB_id]->schedule_si); // only schedule + tx\n    reset_meas (&RC.mac[eNB_id]->schedule_ra); // only ra\n    reset_meas (&RC.mac[eNB_id]->schedule_ulsch); // onlu ulsch\n    reset_meas (&RC.mac[eNB_id]->fill_DLSCH_dci); // only dci\n    reset_meas (&RC.mac[eNB_id]->schedule_dlsch_preprocessor); // include rlc_data_req + MAC header gen\n    reset_meas (&RC.mac[eNB_id]->schedule_dlsch); // include rlc_data_req + MAC header gen + pre-processor\n    reset_meas (&RC.mac[eNB_id]->schedule_mch); // only embms\n    reset_meas (&RC.mac[eNB_id]->rx_ulsch_sdu); // include rlc_data_ind + mac header parser\n\n    reset_meas (&eNB_pdcp_stats[eNB_id].pdcp_run);\n    reset_meas (&eNB_pdcp_stats[eNB_id].data_req);\n    reset_meas (&eNB_pdcp_stats[eNB_id].data_ind);\n    reset_meas (&eNB_pdcp_stats[eNB_id].apply_security);\n    reset_meas (&eNB_pdcp_stats[eNB_id].validate_security);\n    reset_meas (&eNB_pdcp_stats[eNB_id].pdcp_ip);\n    reset_meas (&eNB_pdcp_stats[eNB_id].ip_pdcp);\n\n  }\n}\n\nvoid\nprint_opp_meas_oaisim (void)\n{\n\n  uint8_t eNB_id = 0, UE_id = 0;\n\n  print_meas (&oaisim_stats, \"[OAI][total_exec_time]\", &oaisim_stats,\n              &oaisim_stats);\n  print_meas (&oaisim_stats_f, \"[OAI][SF_exec_time]\", &oaisim_stats,\n              &oaisim_stats_f);\n\n  print_meas (&dl_chan_stats, \"[DL][chan_stats]\", &oaisim_stats,\n              &oaisim_stats_f);\n  print_meas (&ul_chan_stats, \"[UL][chan_stats]\", &oaisim_stats,\n              &oaisim_stats_f);\n\n  for (UE_id = 0; UE_id < NB_UE_INST; UE_id++) {\n    for (ru_id = 0; ru_id < NB_RU; ru_id++) {\n      print_meas (&RU2UE[ru_id][UE_id][0]->random_channel,\n                  \"[DL][random_channel]\", &oaisim_stats, &oaisim_stats_f);\n      print_meas (&RU2UE[ru_id][UE_id][0]->interp_time,\n                  \"[DL][interp_time]\", &oaisim_stats, &oaisim_stats_f);\n      print_meas (&RU2UE[ru_id][UE_id][0]->interp_freq,\n                  \"[DL][interp_freq]\", &oaisim_stats, &oaisim_stats_f);\n      print_meas (&RU2UE[ru_id][UE_id][0]->convolution,\n                  \"[DL][convolution]\", &oaisim_stats, &oaisim_stats_f);\n\n      print_meas (&UE2RU[UE_id][ru_id][0]->random_channel,\n                  \"[UL][random_channel]\", &oaisim_stats, &oaisim_stats_f);\n      print_meas (&UE2RU[UE_id][ru_id][0]->interp_time,\n                  \"[UL][interp_time]\", &oaisim_stats, &oaisim_stats_f);\n      print_meas (&UE2RU[UE_id][ru_id][0]->interp_freq,\n                  \"[UL][interp_freq]\", &oaisim_stats, &oaisim_stats_f);\n      print_meas (&UE2RU[UE_id][ru_id][0]->convolution,\n                  \"[UL][convolution]\", &oaisim_stats, &oaisim_stats_f);\n    }\n  }\n\n  for (UE_id = 0; UE_id < NB_UE_INST; UE_id++) {\n    print_meas (&PHY_vars_UE_g[UE_id][0]->phy_proc[0], \"[UE][total_phy_proc[0]]\",\n                &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->phy_proc[1], \"[UE][total_phy_proc[1]]\",\n                &oaisim_stats, &oaisim_stats_f);\n\n\n    print_meas (&PHY_vars_UE_g[UE_id][0]->phy_proc_rx[0],\n                \"[UE][total_phy_proc_rx[0]]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->phy_proc_rx[1],\n                \"[UE][total_phy_proc_rx[1]]\", &oaisim_stats, &oaisim_stats_f);\n    //    print_meas (&PHY_vars_UE_g[UE_id][0]->ofdm_demod_stats,\n    //                \"[UE][ofdm_demod]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->rx_dft_stats, \"[UE][rx_dft]\",\n                &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_channel_estimation_stats,\n                \"[UE][channel_est]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_freq_offset_estimation_stats,\n                \"[UE][freq_offset]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_llr_stats, \"[UE][llr]\",\n                &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_unscrambling_stats,\n                \"[UE][unscrambling]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_decoding_stats[0],\n                \"[UE][decoding[0]]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_decoding_stats[1],\n                \"[UE][decoding[1]]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_rate_unmatching_stats,\n                \"[UE][rate_unmatching]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_deinterleaving_stats,\n                \"[UE][deinterleaving]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_turbo_decoding_stats,\n                \"[UE][turbo_decoding]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_tc_init_stats,\n                \"[UE][ |_tc_init]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_tc_alpha_stats,\n                \"[UE][ |_tc_alpha]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_tc_beta_stats,\n                \"[UE][ |_tc_beta]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_tc_gamma_stats,\n                \"[UE][ |_tc_gamma]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_tc_ext_stats,\n                \"[UE][ |_tc_ext]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_tc_intl1_stats,\n                \"[UE][ |_tc_intl1]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_tc_intl2_stats,\n                \"[UE][ |_tc_intl2]\", &oaisim_stats, &oaisim_stats_f);\n\n    print_meas (&PHY_vars_UE_g[UE_id][0]->phy_proc_tx,\n                \"[UE][total_phy_proc_tx]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->ofdm_mod_stats, \"[UE][ofdm_mod]\",\n                &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->ulsch_modulation_stats,\n                \"[UE][modulation]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->ulsch_encoding_stats,\n                \"[UE][encoding]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->ulsch_segmentation_stats,\n                \"[UE][segmentation]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->ulsch_rate_matching_stats,\n                \"[UE][rate_matching]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->ulsch_turbo_encoding_stats,\n                \"[UE][turbo_encoding]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->ulsch_interleaving_stats,\n                \"[UE][interleaving]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->ulsch_multiplexing_stats,\n                \"[UE][multiplexing]\", &oaisim_stats, &oaisim_stats_f);\n\n  }\n\n  for (eNB_id = 0; eNB_id < NB_eNB_INST; eNB_id++) {\n    print_meas (&RC.eNB[eNB_id][0]->phy_proc,\n                \"[eNB][total_phy_proc]\", &oaisim_stats, &oaisim_stats_f);\n\n    print_meas (&RC.eNB[eNB_id][0]->phy_proc_tx,\n                \"[eNB][total_phy_proc_tx]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&RC.eNB[eNB_id][0]->ofdm_mod_stats,\n                \"[eNB][ofdm_mod]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&RC.eNB[eNB_id][0]->dlsch_modulation_stats,\n                \"[eNB][modulation]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&RC.eNB[eNB_id][0]->dlsch_scrambling_stats,\n                \"[eNB][scrambling]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&RC.eNB[eNB_id][0]->dlsch_encoding_stats,\n                \"[eNB][encoding]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&RC.eNB[eNB_id][0]->dlsch_interleaving_stats,\n                \"[eNB][|_interleaving]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&RC.eNB[eNB_id][0]->dlsch_rate_matching_stats,\n                \"[eNB][|_rate_matching]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&RC.eNB[eNB_id][0]->dlsch_turbo_encoding_stats,\n                \"[eNB][|_turbo_encoding]\", &oaisim_stats, &oaisim_stats_f);\n\n    print_meas (&RC.eNB[eNB_id][0]->phy_proc_rx,\n                \"[eNB][total_phy_proc_rx]\", &oaisim_stats, &oaisim_stats_f);\n    //    print_meas (&RC.eNB[eNB_id][0]->ofdm_demod_stats,\n    //                \"[eNB][ofdm_demod]\", &oaisim_stats, &oaisim_stats_f);\n    //print_meas(&RC.eNB[eNB_id][0]->ulsch_channel_estimation_stats,\"[eNB][channel_est]\");\n    //print_meas(&RC.eNB[eNB_id][0]->ulsch_freq_offset_estimation_stats,\"[eNB][freq_offset]\");\n    //print_meas(&RC.eNB[eNB_id][0]->rx_dft_stats,\"[eNB][rx_dft]\");\n    print_meas (&RC.eNB[eNB_id][0]->ulsch_demodulation_stats,\n                \"[eNB][demodulation]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&RC.eNB[eNB_id][0]->ulsch_decoding_stats,\n                \"[eNB][decoding]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&RC.eNB[eNB_id][0]->ulsch_deinterleaving_stats,\n                \"[eNB][|_deinterleaving]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&RC.eNB[eNB_id][0]->ulsch_demultiplexing_stats,\n                \"[eNB][|_demultiplexing]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&RC.eNB[eNB_id][0]->ulsch_rate_unmatching_stats,\n                \"[eNB][|_rate_unmatching]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&RC.eNB[eNB_id][0]->ulsch_turbo_decoding_stats,\n                \"[eNB][|_turbo_decoding]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&RC.eNB[eNB_id][0]->ulsch_tc_init_stats,\n                \"[eNB][ |_tc_init]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&RC.eNB[eNB_id][0]->ulsch_tc_alpha_stats,\n                \"[eNB][ |_tc_alpha]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&RC.eNB[eNB_id][0]->ulsch_tc_beta_stats,\n                \"[eNB][ |_tc_beta]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&RC.eNB[eNB_id][0]->ulsch_tc_gamma_stats,\n                \"[eNB][ |_tc_gamma]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&RC.eNB[eNB_id][0]->ulsch_tc_ext_stats,\n                \"[eNB][ |_tc_ext]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&RC.eNB[eNB_id][0]->ulsch_tc_intl1_stats,\n                \"[eNB][ |_tc_intl1]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&RC.eNB[eNB_id][0]->ulsch_tc_intl2_stats,\n                \"[eNB][ |_tc_intl2]\", &oaisim_stats, &oaisim_stats_f);\n\n    print_meas (&RC.eNB[eNB_id][0]->rx_prach, \"[eNB][rx_prach]\",\n                &oaisim_stats, &oaisim_stats_f);\n\n#ifdef LOCALIZATION\n    print_meas(&RC.eNB[eNB_id][0]->localization_stats, \"[eNB][LOCALIZATION]\",&oaisim_stats,&oaisim_stats_f);\n#endif\n  }\n\n  for (UE_id = 0; UE_id < NB_UE_INST; UE_id++) {\n\n    print_meas (&UE_mac_inst[UE_id].ue_scheduler, \"[UE][mac_scheduler]\",\n                &oaisim_stats, &oaisim_stats_f);\n    print_meas (&UE_mac_inst[UE_id].tx_ulsch_sdu, \"[UE][tx_ulsch_sdu]\",\n                &oaisim_stats, &oaisim_stats_f);\n    print_meas (&UE_mac_inst[UE_id].rx_dlsch_sdu, \"[UE][rx_dlsch_sdu]\",\n                &oaisim_stats, &oaisim_stats_f);\n    print_meas (&UE_mac_inst[UE_id].ue_query_mch, \"[UE][query_MCH]\",\n                &oaisim_stats, &oaisim_stats_f);\n    print_meas (&UE_mac_inst[UE_id].rx_mch_sdu, \"[UE][rx_mch_sdu]\",\n                &oaisim_stats, &oaisim_stats_f);\n    print_meas (&UE_mac_inst[UE_id].rx_si, \"[UE][rx_si]\", &oaisim_stats,\n                &oaisim_stats_f);\n\n    print_meas (&UE_pdcp_stats[UE_id].pdcp_run, \"[UE][total_pdcp_run]\",\n                &oaisim_stats, &oaisim_stats_f);\n    print_meas (&UE_pdcp_stats[UE_id].data_req, \"[UE][DL][pdcp_data_req]\",\n                &oaisim_stats, &oaisim_stats_f);\n    print_meas (&UE_pdcp_stats[UE_id].data_ind, \"[UE][UL][pdcp_data_ind]\",\n                &oaisim_stats, &oaisim_stats_f);\n\n    print_meas (&UE_pdcp_stats[UE_id].apply_security,\n                \"[UE][DL][apply_security]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&UE_pdcp_stats[UE_id].validate_security,\n                \"[UE][UL][validate_security]\", &oaisim_stats,\n                &oaisim_stats_f);\n    print_meas (&UE_pdcp_stats[UE_id].ip_pdcp, \"[UE][DL][ip_pdcp]\",\n                &oaisim_stats, &oaisim_stats_f);\n    print_meas (&UE_pdcp_stats[UE_id].pdcp_ip, \"[UE][UL][pdcp_ip]\",\n                &oaisim_stats, &oaisim_stats_f);\n\n  }\n\n  for (eNB_id = 0; eNB_id < NB_eNB_INST; eNB_id++) {\n\n    print_meas (&RC.mac[eNB_id]->eNB_scheduler, \"[eNB][mac_scheduler]\",\n                &oaisim_stats, &oaisim_stats_f);\n    print_meas (&RC.mac[eNB_id]->schedule_si, \"[eNB][DL][SI]\",\n                &oaisim_stats, &oaisim_stats_f);\n    print_meas (&RC.mac[eNB_id]->schedule_ra, \"[eNB][DL][RA]\",\n                &oaisim_stats, &oaisim_stats_f);\n    print_meas (&RC.mac[eNB_id]->fill_DLSCH_dci,\n                \"[eNB][DL/UL][fill_DCI]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&RC.mac[eNB_id]->schedule_dlsch_preprocessor,\n                \"[eNB][DL][preprocessor]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&RC.mac[eNB_id]->schedule_dlsch,\n                \"[eNB][DL][schedule_tx_dlsch]\", &oaisim_stats,\n                &oaisim_stats_f);\n    print_meas (&RC.mac[eNB_id]->schedule_mch, \"[eNB][DL][mch]\",\n                &oaisim_stats, &oaisim_stats_f);\n    print_meas (&RC.mac[eNB_id]->schedule_ulsch, \"[eNB][UL][ULSCH]\",\n                &oaisim_stats, &oaisim_stats_f);\n    print_meas (&RC.mac[eNB_id]->rx_ulsch_sdu,\n                \"[eNB][UL][rx_ulsch_sdu]\", &oaisim_stats, &oaisim_stats_f);\n\n    print_meas (&eNB_pdcp_stats[eNB_id].pdcp_run, \"[eNB][pdcp_run]\",\n                &oaisim_stats, &oaisim_stats_f);\n    print_meas (&eNB_pdcp_stats[eNB_id].data_req,\n                \"[eNB][DL][pdcp_data_req]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&eNB_pdcp_stats[eNB_id].data_ind,\n                \"[eNB][UL][pdcp_data_ind]\", &oaisim_stats, &oaisim_stats_f);\n\n    print_meas (&eNB_pdcp_stats[eNB_id].apply_security,\n                \"[eNB][DL][apply_security]\", &oaisim_stats,\n                &oaisim_stats_f);\n    print_meas (&eNB_pdcp_stats[eNB_id].validate_security,\n                \"[eNB][UL][validate_security]\", &oaisim_stats,\n                &oaisim_stats_f);\n    print_meas (&eNB_pdcp_stats[eNB_id].ip_pdcp, \"[eNB][DL][ip_pdcp]\",\n                &oaisim_stats, &oaisim_stats_f);\n    print_meas (&eNB_pdcp_stats[eNB_id].pdcp_ip, \"[eNB][UL][pdcp_ip]\",\n                &oaisim_stats, &oaisim_stats_f);\n\n  }\n\n}\n\n#if !defined(ENABLE_ITTI)\nstatic void *\nsigh (void *arg)\n{\n\n  int signum;\n  sigset_t sigcatch;\n  sigemptyset (&sigcatch);\n  sigaddset (&sigcatch, SIGHUP);\n  sigaddset (&sigcatch, SIGINT);\n  sigaddset (&sigcatch, SIGTERM);\n  sigaddset (&sigcatch, SIGQUIT);\n\n  for (;;) {\n    sigwait (&sigcatch, &signum);\n\n    //sigwait(&sigblock, &signum);\n    switch (signum) {\n    case SIGHUP:\n    case SIGINT:\n    case SIGTERM:\n    case SIGQUIT:\n      fprintf (stderr, \"received signal %d \\n\", signum);\n      // no need for mutx: when ITTI not used, this variable is only accessed by this function\n      l2l1_state = L2L1_TERMINATED;\n      break;\n\n    default:\n      fprintf (stderr, \"Unexpected signal %d \\n\", signum);\n      exit (-1);\n      break;\n    }\n  }\n\n  pthread_exit (NULL);\n}\n#endif /* !defined(ENABLE_ITTI) */\n\nvoid\noai_shutdown (void)\n{\n  static int done = 0;\n\n  if (done)\n    return;\n\n  free (otg_pdcp_buffer);\n  otg_pdcp_buffer = 0;\n\n#ifdef SMBV\n\n  // Rohde&Schwarz SMBV100A vector signal generator\n  if (config_smbv) {\n    smbv_send_config (smbv_fname,smbv_ip);\n  }\n\n#endif\n\n  //Perform KPI measurements\n  if (oai_emulation.info.otg_enabled == 1){\n    LOG_N(EMU,\"calling OTG kpi gen .... \\n\");\n    kpi_gen ();\n  }\n  if (oai_emulation.info.opp_enabled == 1)\n    print_opp_meas_oaisim ();\n\n\n#ifdef PROC\n\n  if (abstraction_flag == 0 && Channel_Flag==0 && Process_Flag==0)\n#else\n    if (abstraction_flag == 0)\n#endif\n      {\n\t/*\n\t  #ifdef IFFT_FPGA\n\t  free(txdataF2[0]);\n\t  free(txdataF2[1]);\n\t  free(txdataF2);\n\t  free(txdata[0]);\n\t  free(txdata[1]);\n\t  free(txdata);\n\t  #endif\n\t*/\n\t/*\n\tfor (int i = 0; i < 2; i++) {\n\t  free (s_re[i]);\n\t  free (s_im[i]);\n\t  free (r_re[i]);\n\t  free (r_im[i]);\n\t}\n\n\tfree (s_re);\n\tfree (s_im);\n\tfree (r_re);\n\tfree (r_im);\n\ts_re = 0;\n\ts_im = 0;\n\tr_re = 0;\n\tr_im = 0;*/\n\n\tlte_sync_time_free ();\n      }\n\n  // added for PHY abstraction\n  if (oai_emulation.info.ocm_enabled == 1) {\n    for (eNB_inst = 0; eNB_inst < NUMBER_OF_eNB_MAX; eNB_inst++) {\n      free (enb_data[eNB_inst]);\n      enb_data[eNB_inst] = 0;\n    }\n\n    for (UE_inst = 0; UE_inst < NUMBER_OF_UE_MAX; UE_inst++) {\n      free (ue_data[UE_inst]);\n      ue_data[UE_inst] = 0;\n    }\n  } //End of PHY abstraction changes\n\n\n  // stop OMG\n  stop_mobility_generator (omg_param_list); //omg_param_list.mobility_type\n#ifdef OPENAIR2\n\n  if (oai_emulation.info.omv_enabled == 1)\n    omv_end (pfd[1], omv_data);\n\n#endif\n\n  if ((oai_emulation.info.ocm_enabled == 1) && (ethernet_flag == 0)\n      && (ShaF != NULL)) {\n    destroyMat (ShaF, map1, map2);\n    ShaF = 0;\n  }\n\n  if (opt_enabled == 1)\n    terminate_opt ();\n\n  if (oai_emulation.info.cli_enabled)\n    cli_server_cleanup ();\n\n  for (int i = 0; i < NUMBER_OF_eNB_MAX + NUMBER_OF_UE_MAX; i++)\n    if (oai_emulation.info.oai_ifup[i] == 1) {\n      char interfaceName[8];\n      snprintf (interfaceName, sizeof(interfaceName), \"oai%d\", i);\n      bringInterfaceUp (interfaceName, 0);\n    }\n\n  log_thread_finalize ();\n  logClean ();\n  VCD_SIGNAL_DUMPER_CLOSE ();\n\n  done = 1; // prevent next invokation of this function\n\n  LOG_N(EMU,\n        \">>>>>>>>>>>>>>>>>>>>>>>>>>> OAIEMU shutdown <<<<<<<<<<<<<<<<<<<<<<<<<<\\n\\n\");\n}\n\neNB_MAC_INST*\nget_eNB_mac_inst (module_id_t module_idP)\n{\n  return (RC.mac[module_idP]);\n}\n\nOAI_Emulation*\nget_OAI_emulation ()\n{\n  return &oai_emulation;\n}\n\n\n// dummy function declarations\n\nvoid *rrc_enb_task(void *args_p)\n{\n  return NULL;\n}\n\n", "meta": {"hexsha": "0008ba3bbde128740f20be36289ad2b419d018e9", "size": 62670, "ext": "c", "lang": "C", "max_stars_repo_path": "targets/SIMU/USER/oaisim.c", "max_stars_repo_name": "davidraditya/OAI-Powder", "max_stars_repo_head_hexsha": "a082c3e8af06cd7583c003a69ec517eb73d175b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "targets/SIMU/USER/oaisim.c", "max_issues_repo_name": "davidraditya/OAI-Powder", "max_issues_repo_head_hexsha": "a082c3e8af06cd7583c003a69ec517eb73d175b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "targets/SIMU/USER/oaisim.c", "max_forks_repo_name": "davidraditya/OAI-Powder", "max_forks_repo_head_hexsha": "a082c3e8af06cd7583c003a69ec517eb73d175b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8208310847, "max_line_length": 471, "alphanum_fraction": 0.6596936333, "num_tokens": 19663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2509127868852725, "lm_q2_score": 0.041462269898368875, "lm_q1q2_score": 0.010403413690789079}}
{"text": "// Copyright (c) 2013-2016 Anton Kozhevnikov, Thomas Schulthess\n// All rights reserved.\n// \n// Redistribution and use in source and binary forms, with or without modification, are permitted provided that \n// the following conditions are met:\n// \n// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the \n//    following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions \n//    and the following disclaimer in the documentation and/or other materials provided with the distribution.\n// \n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED \n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A \n// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR \n// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, \n// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER \n// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR \n// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n/** \\file sirius_internal.h\n *   \n *  \\brief Contains basic definitions and declarations.\n */\n\n#ifndef __SIRIUS_INTERNAL_H__\n#define __SIRIUS_INTERNAL_H__\n\n#include <omp.h>\n#include <signal.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <gsl/gsl_sf_bessel.h>\n#include <fftw3.h>\n#include <vector>\n#include <complex>\n#include <iostream>\n#include <algorithm>\n#include \"config.h\"\n#include \"communicator.hpp\"\n#include \"runtime.h\"\n#include \"sddk.hpp\"\n#include \"utils.h\"\n#ifdef __MAGMA\n#include \"GPU/magma.hpp\"\n#endif\n#include \"constants.h\"\n#include \"version.h\"\n#include \"simulation_context.h\"\n#include \"Beta_projectors/beta_projectors_base.h\"\n\n#ifdef __PLASMA\nextern \"C\" void plasma_init(int num_cores);\n#endif\n\n#ifdef __LIBSCI_ACC\nextern \"C\" void libsci_acc_init();\nextern \"C\" void libsci_acc_finalize();\n#endif\n\n/// Namespace of the SIRIUS library.\nnamespace sirius {\n\n    inline void initialize(bool call_mpi_init__ = true)\n    {\n        if (call_mpi_init__) {\n            Communicator::initialize();\n        }\n        if (mpi_comm_world().rank() == 0) {\n            printf(\"SIRIUS %i.%i, git hash: %s\\n\", major_version, minor_version, git_hash);\n        }\n\n        #ifdef __GPU\n        if (acc::num_devices()) {\n            acc::create_streams(omp_get_max_threads() + 1);\n            cublas::create_stream_handles();\n        }\n        #endif\n        #ifdef __MAGMA\n        magma::init();\n        #endif\n        #ifdef __PLASMA\n        plasma_init(omp_get_max_threads());\n        #endif\n        #ifdef __LIBSCI_ACC\n        libsci_acc_init();\n        #endif\n\n        assert(sizeof(int) == 4);\n        assert(sizeof(double) == 8);\n    }\n\n    inline void finalize(bool call_mpi_fin__ = true)\n    {\n        #ifdef __MAGMA\n        magma::finalize();\n        #endif\n        #ifdef __LIBSCI_ACC\n        libsci_acc_finalize();\n        #endif\n\n        Beta_projectors_base<1>::cleanup();\n        Beta_projectors_base<3>::cleanup();\n        Beta_projectors_base<9>::cleanup();\n\n        #ifdef __GPU\n        if (acc::num_devices()) {\n            cublas::destroy_stream_handles();\n            acc::destroy_streams();\n            acc::reset();\n        }\n        #endif\n        fftw_cleanup();\n\n        json dict;\n        dict[\"flat\"] = sddk::timer::serialize_timers();\n        dict[\"tree\"] = sddk::timer::serialize_timers_tree();\n        if (mpi_comm_world().rank() == 0) {\n            std::ofstream ofs(\"timers.json\", std::ofstream::out | std::ofstream::trunc);\n            ofs << dict.dump(4);\n        }\n\n        //sddk::timer::print_tree();\n        if (call_mpi_fin__) {\n            Communicator::finalize();\n        }\n\n    }\n\n     inline void terminate(int err_code__)\n     {\n        MPI_Abort(MPI_COMM_WORLD, err_code__);\n     }\n};\n\n#endif // __SIRIUS_INTERNAL_H__\n\n/** \n\\mainpage Welcome to SIRIUS\n\\section intro Introduction\nSIRIUS is a domain-specific library for electronic structure calculations. It supports full-potential linearized\naugmented plane wave (FP-LAPW) and pseudopotential plane wave (PP-PW) methods and is designed to work with codes\nsuch as Exciting, Elk and Quantum ESPRESSO.\n\\section install Installation\nFirst, you need to clone the source code:\n\\verbatim\ngit clone https://github.com/electronic-structure/SIRIUS.git\n\\endverbatim \n\nThen you need to create a configuration \\c json file where you specify your compiliers, compiler flags and libraries.\nExamples of such configuration files can be found in the <tt>./platforms/</tt> folder. The following variables have to be\nprovided:\n  - \\c MPI_CXX -- the MPI wrapper for the C++11 compiler (this is the main compiler for the library)\n  - \\c MPI_CXX_OPT -- the C++ compiler options for the library\n  - \\c MPI_FC -- the MPI wrapper for the Fortran compiler (used to build ELPA and SIRIUS F90 interface)\n  - \\c MPI_FC_OPT -- Fortran compiler options\n  - \\c CC -- plain C compilers (used to build the external libraries)\n  - \\c CXX -- plain C++ compiler (used to build the external libraries)\n  - \\c FC -- plain Fortran compiler (used to build the external libraries)\n  - \\c FCCPP -- Fortran preprocessor (usually 'cpp', required by LibXC package)\n  - \\c SYSTEM_LIBS -- list of the libraries, necessary for the linking (typically BLAS/LAPACK/ScaLAPACK, libstdc++ and Fortran run-time) \n  - \\c install -- list of packages to download, configure and build\n\nIn addition, the following variables can also be specified:\n  - \\c CUDA_ROOT -- path to the CUDA toolkit (if you compile with GPU support)\n  - \\c NVCC -- name of the CUDA C++ compiler (usually \\c nvcc)\n  - \\c NVCC_OPT -- CUDA compiler options\n  - \\c MAGMA_ROOT -- location of the compiled MAGMA library (if you compile with MAGMA support)\n\nBelow is an example of the configurtaion file for the Cray XC50 platform. Cray compiler wrappers for C/C++/Fortran are \nftn/cc/CC. The GNU compilers and MKL are used.\n\\verbatim\n{\n    \"comment\"     : \"MPI C++ compiler and options\",\n    \"MPI_CXX\"     : \"CC\",\n    \"MPI_CXX_OPT\" : \"-std=c++11 -Wall -Wconversion -fopenmp -D__SCALAPACK -D__ELPA -D__GPU -D__MAGMA -I$(MKLROOT)/include/fftw/\",\n\n    \"comment\"     : \"MPI Fortran compiler and oprions\",\n    \"MPI_FC\"      : \"ftn\",\n    \"MPI_FC_OPT\"  : \"-O3 -fopenmp -cpp\",\n\n    \"comment\"     : \"plain C compler\",\n    \"CC\"          : \"cc\",\n\n    \"comment\"     : \"plain C++ compiler\",\n    \"CXX\"         : \"CC\",\n\n    \"comment\"     : \"plain Fortran compiler\",\n    \"FC\"          : \"ftn\",\n\n    \"comment\"     : \"Fortran preprocessor\",\n    \"FCCPP\"       : \"cpp\",\n\n    \"comment\"     : \"location of CUDA toolkit\",\n    \"CUDA_ROOT\"   : \"$(CUDATOOLKIT_HOME)\",\n\n    \"comment\"     : \"CUDA compiler and options\",\n    \"NVCC\"        : \"nvcc\",\n    \"NVCC_OPT\"    : \"-arch=sm_60 -m64 -DNDEBUG\",\n\n    \"comment\"     : \"location of MAGMA library\",\n    \"MAGMA_ROOT\"  : \"$(HOME)/src/daint/magma-2.2.0\",\n\n    \"SYSTEM_LIBS\" : \"$(MKLROOT)/lib/intel64/libmkl_scalapack_lp64.a -Wl,--start-group  $(MKLROOT)/lib/intel64/libmkl_intel_lp64.a $(MKLROOT)/lib/intel64/libmkl_gnu_thread.a $(MKLROOT)/lib/intel64/libmkl_core.a $(MKLROOT)/lib/intel64/libmkl_blacs_intelmpi_lp64.a -Wl,--end-group -lpthread -lstdc++ -ldl\",\n\n    \"install\"     : [\"spg\", \"gsl\", \"xc\"]\n}\n\\endverbatim\nFFT library is part of the MKL. The corresponding C++ include directory is passed to the compiler: -I\\$(MKLROOT)/include/fftw/.\nThe \\c HDF5 library is installed as a module and handeled by the Cray wrappers. The remaining three libraries necessary for \nSIRIUS (spglib, GSL, libXC) are not available and have to be installed.\n\nOnce the configuration \\c json file is created, you can run\n\\verbatim\npython configure.py path/to/config.json\n\\endverbatim \n\nThe Python script will download and configure external packages, specified in the <tt>\"install\"</tt> list and create \nMakefile and make.inc files. That's it! The configuration is done and you can run\n\\verbatim\nmake\n\\endverbatim \n*/\n\n//! \\page stdvarname Standard variable names\n//!  \n//! Below is the list of standard names for some of the loop variables:\n//! \n//! l - index of orbital quantum number \\n\n//! m - index of azimutal quantum nuber \\n\n//! lm - combined index of (l,m) quantum numbers \\n\n//! ia - index of atom \\n\n//! ic - index of atom class \\n\n//! iat - index of atom type \\n\n//! ir - index of r-point \\n\n//! ig - index of G-vector \\n\n//! idxlo - index of local orbital \\n\n//! idxrf - index of radial function \\n\n//! xi - compbined index of lm and idxrf (product of angular and radial functions) \\n\n//! ik - index of k-point \\n\n//! itp - index of (theta, phi) spherical angles \\n\n//!\n//! The _loc suffix is often added to the variables to indicate that they represent the local fraction of the elements\n//! assigned to the given MPI rank.\n//!\n\n//! \\page coding Coding style\n//!     \n//! Below are some basic style rules that we follow:\n//!     - Page width is approximately 120 characters. Screens are wide nowdays and 80 characters is an \n//!       obsolete restriction. Going slightly over 120 characters is allowed if it is requird for the line continuity.\n//!     - Identation: 4 spaces (no tabs)\n//!     - Coments are inserted before the code with slash-star style starting with the lower case:\n//!       \\code{.cpp}\n//!           /* call a very important function */\n//!           do_something();\n//!       \\endcode\n//!     - Spaces between most operators:\n//!       \\code{.cpp}\n//!           if (i < 5) {\n//!               j = 5;\n//!           }\n//!\n//!           for (int k = 0; k < 3; k++)\n//!\n//!           int lm = l * l + l + m;\n//!\n//!           double d = std::abs(e);\n//!\n//!           int k = idx[3];\n//!       \\endcode\n//!     - Spaces between function arguments:\n//!       \\code{.cpp}\n//!           double d = some_func(a, b, c);\n//!       \\endcode\n//!       but not\n//!       \\code{.cpp}\n//!           double d=some_func(a,b,c);\n//!       \\endcode\n//!       or\n//!       \\code{.cpp}\n//!           double d = some_func( a, b, c );\n//!       \\endcode\n//!     - Spaces between template arguments, but not between <> brackets:\n//!       \\code{.cpp}\n//!           std::vector<std::array<int, 2>> vec;\n//!       \\endcode\n//!       but not\n//!       \\code{.cpp}\n//!           std::vector< std::array< int, 2 > > vec;\n//!       \\endcode\n//!     - Curly braces for classes and functions start form the new line:\n//!       \\code{.cpp}\n//!           class A\n//!           {\n//!               ....\n//!           };\n//!\n//!           inline int num_points()\n//!           {\n//!               return num_points_;\n//!           }\n//!       \\endcode\n//!     - Curly braces for if-statements, for-loops, switch-case statements, etc. start at the end of the line:\n//!       \\code{.cpp}\n//!           for (int i: {0, 1, 2}) {\n//!               some_func(i);\n//!           }\n//!\n//!           if (a == 0) {\n//!               printf(\"a is zero\");\n//!           } else {\n//!               printf(\"a is not zero\");\n//!           }\n//!\n//!           switch (i) {\n//!               case 1: {\n//!                   do_something();\n//!                   break;\n//!               case 2: {\n//!                   do_something_else();\n//!                   break;\n//!               }\n//!           }\n//!       \\endcode\n//!     - Even single line 'if' statements and 'for' loops must have the curly brackes:\n//!       \\code{.cpp}  \n//!           if (i == 4) {\n//!               some_variable = 5;\n//!           }\n//!\n//!           for (int k = 0; k < 10; k++) {\n//!               do_something(k);\n//!           }\n//!       \\endcode\n//!     - Reference and pointer symbols are part of type:\n//!       \\code{.cpp}\n//!           std::vector<double>& vec = make_vector();\n//!\n//!           double* ptr = &vec[0];\n//!\n//!           auto& atom = unit_cell().atom(ia);\n//!       \\endcode\n//!     - Const modifier follows the type declaration:\n//!       \\code{.cpp}\n//!           std::vector<int> const& idx() const\n//!           {\n//!               return idx_;\n//!           }\n//!       \\endcode\n//!     - Names of class members end with underscore:\n//!       \\code{.cpp}\n//!           class A\n//!           {\n//!               private:\n//!                   int lmax_;\n//!           };\n//!       \\endcode\n//!     - Setter method starts from set_, getter method is a variable name itself:\n//!       \\code{.cpp}\n//!           class A\n//!           {\n//!               private:\n//!                   int lmax_;\n//!               public:\n//!                   int lmax() const\n//!                   {\n//!                       return lmax_;\n//!                   }\n//!                   void set_lmax(int lmax__)\n//!                   {\n//!                       lmax_ = lmax__;\n//!                   }\n//!           };\n//!       \\endcode\n//!     - Single-line functions should not be flattened:\n//!       \\code{.cpp}\n//!           struct A\n//!           {\n//!               int lmax() const\n//!               {\n//!                   return lmax_;\n//!               }\n//!           };\n//!       \\endcode\n//!       but not\n//!       \\code{.cpp}\n//!           struct A\n//!           {\n//!               int lmax() const { return lmax_; }\n//!           };\n//!       \\endcode\n//!     - Header guards have a standard name: double underscore + file name in capital letters + double underscore\n//!       \\code{.cpp}\n//!           #ifndef __SIRIUS_INTERNAL_H__\n//!           #define __SIRIUS_INTERNAL_H__\n//!           ...\n//!           #endif // __SIRIUS_INTERNAL_H__\n//!       \\endcode\n//! We use clang-format utility to enforce the basic formatting style. Please have a look at .clang-format config file \n//! in the source root folder for the definitions.\n//!        \n//! Class naming convention.\n//!      \n//! Problem: all 'standard' naming conventions are not satisfactory. For example, we have a class \n//! which does a DFT ground state. Following the common naming conventions it could be named like this:\n//! DFTGroundState, DftGroundState, dft_ground_state. Last two are bad, because DFT (and not Dft or dft)\n//! is a well recognized abbreviation. First one is band because capital G adds to DFT and we automaticaly\n//! read DFTG round state.\n//! \n//! Solution: we can propose the following: DFTgroundState or DFT_ground_state. The first variant still \n//! doens't look very good because one of the words is captalized (State) and one (ground) - is not. So we pick \n//! the second variant: DFT_ground_state (by the way, this is close to the Bjarne Stroustrup's naiming convention,\n//! where he uses first capital letter and underscores, for example class Io_obj).\n//!\n//! Some other examples:\n//!     - class Ground_state (composed of two words) \n//!     - class FFT_interface (composed of an abbreviation and a word)\n//!     - class Interface_XC (composed of a word and abbreviation)\n//!     - class Spline (single word)\n//!     \n//! Exceptions are allowed if it makes sense. For example, low level utility classes like 'mdarray' (multi-dimentional\n//! array) or 'pstdout' (parallel standard output) are named with small letters. \n//!\n\n/** \\page fderiv Functional derivatives\n    \n    Definition:\n    \\f[\n      \\frac{dF[f+\\epsilon \\eta ]}{d \\epsilon}\\Bigg\\rvert_{\\epsilon = 0} := \\int \\frac{\\delta F[f]}{\\delta f(x')} \\eta(x') dx'\n    \\f]\n    Alternative definition is:\n    \\f[\n      \\frac{\\delta F[f(x)]}{\\delta f(x')} = \\lim_{\\epsilon \\to 0} \\frac{F[f(x) + \\epsilon \\delta(x-x')] - F[f(x)]}{\\epsilon}\n    \\f]\n\n\n*/\n", "meta": {"hexsha": "7b23ef7feb9d7f99b723efaaf038648089a799f6", "size": 15702, "ext": "h", "lang": "C", "max_stars_repo_path": "src/sirius_internal.h", "max_stars_repo_name": "ckae95/SIRIUS", "max_stars_repo_head_hexsha": "ecb7edb4f19577c85b0cec82aa6a0d5374ee1f33", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/sirius_internal.h", "max_issues_repo_name": "ckae95/SIRIUS", "max_issues_repo_head_hexsha": "ecb7edb4f19577c85b0cec82aa6a0d5374ee1f33", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sirius_internal.h", "max_forks_repo_name": "ckae95/SIRIUS", "max_forks_repo_head_hexsha": "ecb7edb4f19577c85b0cec82aa6a0d5374ee1f33", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.7676537585, "max_line_length": 303, "alphanum_fraction": 0.5975671889, "num_tokens": 3984, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25091278688527247, "lm_q2_score": 0.041462269158095026, "lm_q1q2_score": 0.010403413505044902}}
{"text": "// Licensed to the Apache Software Foundation (ASF) under one\n// or more contributor license agreements.  See the NOTICE file\n// distributed with this work for additional information\n// regarding copyright ownership.  The ASF licenses this file\n// to you under the Apache License, Version 2.0 (the\n// \"License\"); you may not use this file except in compliance\n// with the License.  You may obtain a copy of the License at\n\n//   http://www.apache.org/licenses/LICENSE-2.0\n\n// Unless required by applicable law or agreed to in writing,\n// software distributed under the License is distributed on an\n// \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n// KIND, either express or implied.  See the License for the\n// specific language governing permissions and limitations\n// under the License.\n\n#include <sys/time.h>\n#include <mpi.h>\n#include \"propagator.h\"\n#include \"options.h\"\n#include <time.h>\n#include <limits.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n#include \"f2c.h\"\n#include <gsl/gsl_statistics.h>\n#include \"gsl/gsl_sf_legendre.h\"\n\n/////////////////////////////////////////////////////////////////////////////////////////\n//\n//  Name:           initialize_constellation\n//  Purpose:        Initializes a constellation based on the period of the 1st spacecraft\n//  Assumptions:    None.\n//  References      Various\n//\n//  Change Log:\n//      |   Developer   |       Date    |   SCR     |   Notes\n//      | --------------|---------------|-----------|-------------------------------\n//      | J. Getchius   | 05/20/2015    |   ---     | Initial Implementation\n//      | C. Bussy-Virat| 07/23/2015    |   ---     | Initialization of ALL the orbital elements from the input file; Replace altitude by apogee altitude in the input file\n//\n/////////////////////////////////////////////////////////////////////////////////////////\nint initialize_constellation(CONSTELLATION_T *CONSTELLATION, OPTIONS_T       *OPTIONS, PARAMS_T        *PARAMS, GROUND_STATION_T *GROUND_STATION, int iDebugLevel, int iProc, int nProcs )\n\n{\n \n\n\n  double **r_alongtrack_all, **r_crosstrack_all, **r_radial_all, **bc_pert_all, **srp_pert_all;\n  double **v_alongtrack_all, **v_crosstrack_all, **v_radial_all;\n  // Declarations\t\n  double geodetic[3];\n  int bbb;\n  int m_time_span;\n\n  /* gsl_rng * r_gaussian_generator; */\n  /* long seed; */\n  /* r_gaussian_generator = gsl_rng_alloc(gsl_rng_mt19937); */\n\n  //  int start_ensemble;\n  double period;\n  int ccc;\n  double collision_equinoctial_sigma_in_diag_basis[6];\n  double collision_equinoctial_sigma_in_equinoctial_basis[6];\n\n  double collision_eci_sigma_in_diag_basis[6];\n  double collision_eci_sigma_in_eci_basis[6];\n  \n  /* double collision_x_eci_sigma, collision_y_eci_sigma, collision_z_eci_sigma, collision_vx_eci_sigma, collision_vy_eci_sigma, collision_vz_eci_sigma; */\n  /* double collision_x_eci_sigma_in_diag_basis, collision_y_eci_sigma_in_diag_basis, collision_z_eci_sigma_in_diag_basis, collision_vx_eci_sigma_in_diag_basis, collision_vy_eci_sigma_in_diag_basis, collision_vz_eci_sigma_in_diag_basis; */\n  /* int aaa_count; */\n  /* int swpc_forecast_day; */\n  /* double nb_index_in_81_days; */\n\n  //  int aaa_sigma;\n\n  int write_attitude_file = 0;\n  char time_attitude[256];\n  FILE *file_attitude[N_SATS];\n  char filename_attitude[N_SATS][256];\n  double et_initial_epoch, et_final_epoch;\n  int iground;\n  SpiceDouble       xform[6][6];\n  double estate[6], jstate[6];\n\n  int hhh;\n  char *next;\n  int find_file_name;\n \n  double altitude_perigee;\n  int index_altitude_right_below_perigee_save = 1000000000;\n\n  int iHeaderLength_gitm;\n  FILE *gitm_file;\n  int i,j,k;\n  int ggg;\n  double random_pitch_angular_velocity, random_roll_angular_velocity, random_yaw_angular_velocity;\n  int time_before_reset;\n  double inclination_sigma = 0;\n  double w_sigma = 0;\n  double long_an_sigma = 0;\n  double f_sigma = 0;\n  double eccentricity_sigma = 0;\n  double sma_sigma = 0;\n  int eee;\n  double et;\n  /* double T_J2000_to_ECEF[3][3]; */\n  /* double T_ECEF_to_J2000[3][3]; */\n  int ii,sss,nnn,aaa;\n  double radius_perigee;\n  FILE *gps_tle_file;\n\n  //  Begin Calcs\n  // Initialize Time\n  str2et_c(OPTIONS->initial_epoch, &et); // Convert a string representing an epoch to a double precision value representing the number of TDB seconds past the J2000 epoch corresponding to the input epoch (in /Users/cbv/cspice/src/cspice/str2et_c.c) (CBV)\n  OPTIONS->et_initial_epoch = et; // should have done that in load_options.c\n  str2et_c(OPTIONS->initial_epoch, &et_initial_epoch);\n  str2et_c(OPTIONS->final_epoch, &et_final_epoch);\n\n  r_alongtrack_all = malloc( OPTIONS->nb_satellites_not_including_gps * sizeof(double *) );\n  r_crosstrack_all = malloc( OPTIONS->nb_satellites_not_including_gps * sizeof(double *) );\n  r_radial_all = malloc( OPTIONS->nb_satellites_not_including_gps * sizeof(double *) );\n\n  v_alongtrack_all = malloc( OPTIONS->nb_satellites_not_including_gps * sizeof(double *) );\n  v_crosstrack_all = malloc( OPTIONS->nb_satellites_not_including_gps * sizeof(double *) );\n  v_radial_all = malloc( OPTIONS->nb_satellites_not_including_gps * sizeof(double *) );\n\n  bc_pert_all = malloc( OPTIONS->nb_satellites_not_including_gps * sizeof(double *) );\n srp_pert_all = malloc( OPTIONS->nb_satellites_not_including_gps * sizeof(double *) );\n\n\n  CONSTELLATION->et = et;\n  CONSTELLATION->aaa_sigma = malloc( OPTIONS->nb_satellites_not_including_gps * sizeof(int) );\n  CONSTELLATION->aaa_mod = malloc( OPTIONS->nb_satellites_not_including_gps * sizeof(int) );\n  CONSTELLATION->sum_sigma_for_f107_average = malloc( ( OPTIONS->nb_satellites_not_including_gps ) * sizeof( double * ) );\n  if (CONSTELLATION->sum_sigma_for_f107_average == NULL){\n    print_error_any_iproc(iProc, \"Not enough memory for sum_sigma_for_f107_average\");\n  }\n  if (OPTIONS->nb_ensembles_density) { // the user chose to run ensembles on the density using data from SWPC \n    if (OPTIONS->swpc_need_predictions){ // if future predictions of F10.7 and Ap (not only past observations)\n      CONSTELLATION->ensemble_array_per_iproc_f107_at_given_time = malloc( nProcs * sizeof( double *));\n      CONSTELLATION->ensemble_array_per_iproc_f107_at_given_time_sorted = malloc( nProcs * sizeof( double *));\n      CONSTELLATION->ensemble_array_per_iproc_ap_at_given_time = malloc( nProcs * sizeof( double *));\n      CONSTELLATION->ensemble_array_per_iproc_ap_at_given_time_sorted = malloc( nProcs * sizeof( double *));\n\n    }\n  }\n\n  CONSTELLATION->spacecraft = malloc( OPTIONS->n_satellites * sizeof(SPACECRAFT_T*) ); \n\n  if ( CONSTELLATION->spacecraft == NULL){\n    printf(\"***! Could not allow memory to CONSTELLATION->spacecraft. The program will stop. !***\\n\"); MPI_Finalize(); exit(0);\n  }\n\n\n\n\n  /*************************************************************************************/\n  /*************************************************************************************/\n  /*********************** SET THINGS UP FOR PARALLEL PROGRAMMING **********************/\n  /*************************************************************************************/\n  /*************************************************************************************/\n  /*   Things we set up here: */\n  /*   - which iProc runs which main sc / which sc is run by which iProc */\n\n  int nProcs_that_are_gonna_run_ensembles;\n  nProcs_that_are_gonna_run_ensembles = nProcs;\n  if ( nProcs > OPTIONS->nb_ensembles_min ){\n    nProcs_that_are_gonna_run_ensembles = OPTIONS->nb_ensembles_min;\n  }\n\n\n  // For each iProc, set up the first main sc (iStart_save[iProcf]) and the last main sc (iEnd_save[iProcf]) that it's going to run. iStart_save and iEnd_save are two arrays that have the same values for all procs (so if you're iProc 0 or iProc 1, you have value recorded for iStart_save[0] and iEnd_save[0] and the same value recorded for iStart_save[1] and iEnd_save[1]) -> they are not \"iProc-dependent\"\n  int *iStart_save, *iEnd_save;\n  int nscEachPe, nscLeft;\n  int iProcf;\n  nscEachPe = (OPTIONS->n_satellites)/nProcs;\n  nscLeft = (OPTIONS->n_satellites) - (nscEachPe * nProcs);\n\n  iStart_save = malloc( nProcs * sizeof(int));\n  iEnd_save = malloc( nProcs  * sizeof(int));\n  for (iProcf = 0; iProcf < nProcs; iProcf++){\n    iStart_save[iProcf] = 0;\n    iEnd_save[iProcf] = 0;\n  }\n  for (iProcf = 0; iProcf < nProcs; iProcf++){\n    for (i=0; i<iProcf; i++) {\n      iStart_save[iProcf] += nscEachPe;\n      if (i < nscLeft && iProcf > 0) iStart_save[iProcf]++;\n    }\n    iEnd_save[iProcf] = iStart_save[iProcf]+nscEachPe;\n    if (iProcf  < nscLeft) iEnd_save[iProcf]++;\n    iStart_save[iProcf] = iStart_save[iProcf];\n    iEnd_save[iProcf] = iEnd_save[iProcf];\n  }\n    \n  //    if (iProc == 0){\n  /*     for (iProcf = 0; iProcf < nProcs; iProcf++){ */\n  /*       printf(\"%d - %d\\n\", iStart_save[iProcf], iEnd_save[iProcf] - 1) ; */\n  /*     } */\n  //}\n\n  // For each main sc, start_ensemble is 0 if the iProc runs this main sc. start_ensemble is 1 is the iProc does not run this main sc. (so each iProc has a different array start_ensemble -> start_ensemble is \"iProc-dependent\") \n  int *start_ensemble;\n  start_ensemble = malloc(OPTIONS->n_satellites * sizeof(int));\n  for (ii = 0; ii < OPTIONS->n_satellites; ii++){\n    if ( (ii >= iStart_save[iProc]) & ( ii < iEnd_save[iProc]) ){\n      start_ensemble[ii] = 0;\n    }\n    else{\n      start_ensemble[ii] = 1;\n    }\n    //    printf(\"iProc %d | start_ensemble[%d] %d\\n\", iProc, ii, start_ensemble[ii]);\n  }\n\n\n  // array_sc is the array of sc (main and ensemble sc) run by this iProc. So array_sc is \"iProc-dependent\": each iProc has a different array array_sc. What array_sc has: the first elt is 0, whatever iProc it is (because it represents main sc. However, it does not mean that all iProc will run a main sc, this is decided later in the code (using start_ensemble)). The next elts (1, 2, ..., OPTIONS->nb_ensemble_min_per_proc) represent the ensemble sc run by this iProc. So for example if there are 20 ensembles and 2 iProc, array_sc is:\n  // for iProc 0: [0, 1, 2, 3, ..., 9, 10]\n  // for iProc 1: [0, 11, 12, 13, ..., 19, 20]\n  int ielt;\n  int *array_sc;\n  array_sc = malloc((OPTIONS->nb_ensemble_min_per_proc + 2) * sizeof(int)); // + 2 (and not + 1) because if there is no ensemble, we still want array_sc[1] to exist (because later in the code we call array_sc[start_ensemble[ii]], and start_ensemble[ii] = 1 if the iProc does not run main sc ii). \n  array_sc[0] = 0;\n  array_sc[1] = -1; // if there is no ensemble, we still want array_sc[1] to exist (because later in the code we call array_sc[start_ensemble[ii]], and start_ensemble[ii] = 1 if the iProc does not run main sc ii). We set to -1 because we want to make sure that if there is no ensemble, eee will never be equal to array_sc[1]. If there are ensembles, array_sc[1] is overwritten right below anyway\n\n  for ( ielt = 1; ielt < OPTIONS->nb_ensemble_min_per_proc + 1; ielt ++ ){\n    if (iProc < nProcs_that_are_gonna_run_ensembles){\n      array_sc[ielt] = iProc * OPTIONS->nb_ensemble_min_per_proc + ielt;\n    }\n    //   printf(\"iProc %d: array_sc[%d] = %d\\n\", iProc, ielt, array_sc[ielt]);\n  }\n\n\n\n  /*   nscEachPe = (OPTIONS->n_satellites)/nProcs; */\n  /*   nscLeft = (OPTIONS->n_satellites) - (nscEachPe * nProcs); */\n\n  /*   if (iProc == 0){ */\n  /*     printf(\"XXXXXXXXX\\nnscEachPe = %d | nscLeft = %d\\nXXXXXXXXX\\n\", nscEachPe, nscLeft); */\n  /*   } */\n\n  // for each main, which_iproc_is_running_main_sc is the iProc that runs it. For example, which_iproc_is_running_main_sc[3] is equal to the iProc that runs the main sc 3. So which_iproc_is_running_main_sc is the same array for all iProc -> which_iproc_is_running_main_sc is not \"iProc-dependent\"\n  int *which_iproc_is_running_main_sc;\n  which_iproc_is_running_main_sc = malloc( OPTIONS->n_satellites * sizeof(int));\n  for (ii = 0; ii < OPTIONS->n_satellites; ii++){\n    for (ccc = 0; ccc < nProcs; ccc++){\n      if ( ( ii >= iStart_save[ccc] ) && ( ii < iEnd_save[ccc]  ) ){\n\twhich_iproc_is_running_main_sc[ii] = ccc;\n      }  \n    }\n  }\n\n  /*   for (ii = 0; ii < OPTIONS->n_satellites; ii++){ */\n  /*     if (iProc == 0){ */\n  /*     printf(\"iProc %d | which_iproc_is_running_main_sc[%d] = %d\\n\", iProc, ii, which_iproc_is_running_main_sc[ii]); */\n  /*     } */\n  /*   } */\n\n  /*************************************************************************************/\n  /*************************************************************************************/\n  /****************** end of SET THINGS UP FOR PARALLEL PROGRAMMING ********************/\n  /*************************************************************************************/\n  /*************************************************************************************/\n\n\n\n  /*************************************************************************************/\n  /*************************************************************************************/\n  /*************************************************************************************/\n  /*************************************************************************************/\n  /*************************************************************************************/\n  /**************************** SPACECRAFTS OTHER THAN GPS *****************************/\n  /*************************************************************************************/\n  /*************************************************************************************/\n  /*************************************************************************************/\n  /*************************************************************************************/\n  /************************************************************************************/\n\n  if (iDebugLevel >= 1){\n    if (iProc == 0) printf(\"-- Number of spacecraft: %d\\n\", OPTIONS->n_satellites - OPTIONS->nb_gps);\n  }\n\n  for (ii = 0; ii < OPTIONS->n_satellites - OPTIONS->nb_gps; ii++){ // go through all main SC other than GPS\n\n    CONSTELLATION->aaa_sigma[ii] =  OPTIONS->aaa_sigma;\n        CONSTELLATION->aaa_mod[ii] =  OPTIONS->aaa_mod[ii];\n   \n    //  printf(\"ooooooooooooooooo %d %d\\n\",CONSTELLATION->aaa_mod[0], CONSTELLATION->aaa_mod[1]);\n    //    printf(\" CONSTELLATION->aaa_mod[%d] %d\\n\", ii,  CONSTELLATION->aaa_mod[ii]);\n    CONSTELLATION->spacecraft[ii] = malloc( ( OPTIONS->nb_ensembles_min + 1 ) * sizeof(SPACECRAFT_T) ); \nr_alongtrack_all[ii] = malloc( ( OPTIONS->nb_ensembles_min ) * sizeof(double) ); \nr_crosstrack_all[ii] = malloc( ( OPTIONS->nb_ensembles_min) * sizeof(double) ); \nr_radial_all[ii] = malloc( ( OPTIONS->nb_ensembles_min) * sizeof(double) ); \n\nv_alongtrack_all[ii] = malloc( ( OPTIONS->nb_ensembles_min ) * sizeof(double) ); \nv_crosstrack_all[ii] = malloc( ( OPTIONS->nb_ensembles_min) * sizeof(double) ); \nv_radial_all[ii] = malloc( ( OPTIONS->nb_ensembles_min) * sizeof(double) ); \n\n bc_pert_all[ii] = malloc( ( OPTIONS->nb_ensembles_min) * sizeof(double) ); \n srp_pert_all[ii] = malloc( ( OPTIONS->nb_ensembles_min) * sizeof(double) ); \n\n\n    if ( CONSTELLATION->spacecraft[ii] == NULL){\n      printf(\"***! Could not allow memory to CONSTELLATION->spacecraft[ii]. The program will stop. !***\\n\"); MPI_Finalize(); exit(0);\n    }\n\n    CONSTELLATION->sum_sigma_for_f107_average[ii] = malloc( ( OPTIONS->nb_ensemble_min_per_proc * nProcs + 1 ) * sizeof( double ) );\n    if (CONSTELLATION->sum_sigma_for_f107_average[ii] == NULL){\n      print_error_any_iproc(iProc, \"Not enough memory for sum_sigma_for_f107_average[ii]\");\n    }\n\n\n    // Initialize the ensemble parameters\n    srand (time (NULL));\n    // Initialize the ensemble parameters on COE\n    if (( OPTIONS->nb_ensembles > 0 ) && ( strcmp(OPTIONS->type_orbit_initialisation, \"oe\" ) == 0 )){ // if we run ensembles on the orbital elements\n      sma_sigma = OPTIONS->apogee_alt_sigma[ii] / ( 1 + OPTIONS->eccentricity[ii] );\n      inclination_sigma    = OPTIONS->inclination_sigma[ii] * DEG2RAD;\n      w_sigma               = OPTIONS->w_sigma[ii] * DEG2RAD;                                // argument of perigee (CBV)\n      long_an_sigma        = OPTIONS->long_an_sigma[ii] * DEG2RAD;                          // RAAN (CBV)\n      f_sigma               = OPTIONS->f_sigma[ii] * DEG2RAD;                                // true anomaly (CBV)\n      eccentricity_sigma    = OPTIONS->eccentricity_sigma[ii];\n    }\n\n    /*     if (iProc == 0){ */\n    /*       start_ensemble = 0; */\n    /*   } */\n    /*     else{ */\n    /*       start_ensemble = 1; */\n    /*     } */\n\n    //      for (eee = start_ensemble + iProc * OPTIONS->nb_ensemble_min_per_proc; eee< 1 + iProc * OPTIONS->nb_ensemble_min_per_proc + OPTIONS->nb_ensemble_min_per_proc ; eee++){ // go through all sc (including ensembels, if you run ensembles) other than GPS\n    for ( ielt = 0; ielt < OPTIONS->nb_ensemble_min_per_proc + 1; ielt ++ ){ // go through all sc (including ensembels, if you run ensembles) other than GPS. Each iProc runs OPTIONS->nb_ensemble_min_per_proc ensemble sc. But not all iProc run a main sc. If the iProc runs or not a main sc (and which main sc) is decided in the variable start_ensemble[ii]: if start_ensemble[ii] = 0 for this iProc, then this iProc runs main sc ii. If start_ensemble[ii] = 1 for this iProc, then this iProc does NOT run main sc ii. \n      eee = array_sc[ielt]; // eee represents the sc that is run: eee = 0 represents a main sc. eee > 0 represents an ensemble sc\n      if ( (  start_ensemble[ii] == 0 ) || ( ( start_ensemble[ii] != 0 ) && ( eee > 0 ) ) ){ // if main sc ii is run by this iProc OR  ( if this main sc is not run by this iProc and eee corresponds to an ensemble sc (so this iProc does not run main sc ii but runs an ensemble corresponding to main sc ii))\n\tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.isGPS = 0;\n\t/*             if (iProc == 0){ */\n\t/*       printf(\"iProc %d runs main sc %d and ensemble sc %d\\n\", iProc, ii, eee); */\n\t/*             } */\n\t/* if (iProc == 1){ */\n\t/* printf(\"iProc: %d | eee = %d | from %d to %d | ii = %d\\n\", iProc, eee, start_ensemble + iProc * OPTIONS->nb_ensemble_min_per_proc, iProc * OPTIONS->nb_ensemble_min_per_proc + OPTIONS->nb_ensemble_min_per_proc, ii); */\n\t/* } */\n\t/*************************************************************************************/\n\t/*************************************************************************************/\n\t/*************************************************************************************/\n\t/*************************************************************************************/\n\t/********************* INITIALIZE: et, r_i2cg_INRTL, v_i2cg_INRTL, OE ****************/\n\t/*************************************************************************************/\n\t/*************************************************************************************/\n\t/*************************************************************************************/\n\t/*************************************************************************************/\n\n\t/*************************************************************************************/\n\t/*************************************************************************************/\n\t/*************************************************************************************/\n\t/************** INITIALIZE: et, r_i2cg_INRTL, v_i2cg_INRTL, OE FOR MAIN SC ***********/\n\t/*************************************************************************************/\n\t/*************************************************************************************/\n\t/*************************************************************************************/\n\n\t//      if (eee == 0){ // eee = 0 represents the main spacecraft (eee > 0 is a sc from an ensemble)\n\tif ( (start_ensemble[ii] == 0) && (eee == 0)){ // if this iProc runs main sc ii and that eee corresponds to the main sc. eee = 0 represents the main spacecraft (eee > 0 is a sc from an ensemble). start_ensemble[ii] = 0 if main sc is run by this iProc\n\n\t  /*************************************************************************************/\n\t  /*************************************************************************************/\n\t  /********** INITIALIZE: et, r_i2cg_INRTL, v_i2cg_INRTL, OE FOR MAIN SC BY TLE ************/\n\t  /*************************************************************************************/\n\t  /*************************************************************************************/\n\n\t  if ( (strcmp( OPTIONS->type_orbit_initialisation, \"tle\" ) == 0 ) || (strcmp(OPTIONS->type_orbit_initialisation, \"tle_sgp4\" ) == 0 )){\n\t    if (iDebugLevel >= 1){\n\t      if (iProc == 0) printf(\"-- (initialize_constellation) Initializing et, r_i2cg_INRTL, v_i2cg_INRTL, orbital elements from TLE.\\n\");\n\t    }\n\n\t    /*** Convert the TLEs into inertial state (postion, velocity) ***/\n\t    // Initialize TLE parameters\n\t    SpiceInt frstyr = 1961; // do not really care about this line (as long as the spacecrafts are not flying after 2060)\n\t    //\t    SpiceDouble geophs[8];\n\t    int pp;\n\t    int lineln=0;\n\t    size_t len = 0;\n\t    char *line_temp = NULL;\n\t    //\t    SpiceDouble elems[10];\n\t    SpiceDouble state[6];\n\t    SpiceDouble epoch_sat; // epoch of TLE of the sat\n\t    char sat_tle_file_temp[256];\n\t    FILE *sat_tle_file;\n\t    ORBITAL_ELEMENTS_T OE_temp;\n\n\t    /* Set up the geophysical quantities.  At last check these were the values used by Space Command and SGP4 */\n\t    /* PARAMS->geophs[ 0 ] =    1.082616e-3;   // J2 */\n\t    /* PARAMS->geophs[ 1 ] =   -2.53881e-6;    // J3 */\n\t    /* PARAMS->geophs[ 2 ] =   -1.65597e-6;    // J4 */\n\t    /* PARAMS->geophs[ 3 ] =    7.43669161e-2; // KE */\n\t    /* PARAMS->geophs[ 4 ] =    120.0;         // QO */\n\t    /* PARAMS->geophs[ 5 ] =    78.0;          // SO */\n\t    /* PARAMS->geophs[ 6 ] =    6378.135;      // ER */\n\t    /* PARAMS->geophs[ 7 ] =    1.0;           // AE */\n\n\t    /* Read in the next two lines from the text file that contains the TLEs. */\n\t  //newstructure\n/* \t  strcpy(sat_tle_file_temp, OPTIONS->dir_input_tle); */\n/* \t  strcat(sat_tle_file_temp,\"/\"); */\n\t  strcpy(sat_tle_file_temp,\"\");\n\t  //newstructure\n\t    if ( OPTIONS->one_file_with_tle_of_all_sc == 0) { // one tle per file\n\t      strcat(sat_tle_file_temp,OPTIONS->tle_initialisation[ii]);\n\t      sat_tle_file = fopen(sat_tle_file_temp,\"r\");\n\t    }\n\t    else{ // all tles in one file\n\t      strcat(sat_tle_file_temp,OPTIONS->tle_initialisation[0]);\n\n\t      sat_tle_file = fopen(sat_tle_file_temp,\"r\");\n\t      for (bbb = 0; bbb < ii; bbb++){ // skip the TLEs of the sc before the current sc\n\t\tgetline( &line_temp, &len, sat_tle_file ); \n\t\tgetline( &line_temp, &len, sat_tle_file );\n\t      }\n\t    }\n\t  \n\t    // First line\n\t    getline( &line_temp, &len, sat_tle_file );\n\t    lineln = strlen(line_temp)-1;\n\t    SpiceChar line[2][lineln];\n\t    for (pp = 0; pp<lineln-1 ; pp++)\n\t      line[0][pp] = line_temp[pp];\n\t    line[0][ lineln-1 ] = '\\0';\n\t    // Second line\n\t    getline( &line_temp, &len, sat_tle_file );\n\t    for (pp = 0; pp<lineln-1 ; pp++)\n\t      line[1][pp] = line_temp[pp];\n\t    line[1][ lineln-1 ] = '\\0';\n\n\t    fclose(sat_tle_file);\n\t    // Convert the elements of the TLE into \"elems\" and \"epoch\" that can be then read by the SPICE routine ev2lin_ to convert into the inertial state\n\t    //\t    zzgetelm(frstyr, line, &epoch_sat,elems);\n\t      \t    getelm_c( frstyr, lineln, line, &epoch_sat, CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.elems );\n\n\t    CONSTELLATION->spacecraft[ii][0].INTEGRATOR.bstar = CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.elems[2];\n\n\n\t    // Now propagate the state using ev2lin_ to the epoch of interest\n\t    extern /* Subroutine */ int ev2lin_(SpiceDouble *, SpiceDouble *,\n\t\t\t\t\t\tSpiceDouble *, SpiceDouble *);\n\n\t    ev2lin_( &epoch_sat, PARAMS->geophs, CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.elems, state );\n\t    CONSTELLATION->spacecraft[ii][eee].et = epoch_sat;\n\t    CONSTELLATION->spacecraft[ii][eee].et_sc_initial = epoch_sat;\n\t    \n\n\t\t\t      \n\n\t    static doublereal  precm[36];\n\t        static doublereal invprc[36]\t/* was [6][6] */;\n\t\t    extern /* Subroutine */ int zzteme_(doublereal *, doublereal *);\n\t\t        extern /* Subroutine */ int invstm_(doublereal *, doublereal *);\n\t\t\t    extern /* Subroutine */ int  mxvg_(\n\t    doublereal *, doublereal *, integer *, integer *, doublereal *);\n\n\t        zzteme_(&CONSTELLATION->spacecraft[ii][eee].et, precm);\n\n/*     ...now convert STATE to J2000. Invert the state transformation */\n/*     operator (important to correctly do this). */\n\n    invstm_(precm, invprc);\n    static integer c__6 = 6;\n        static doublereal tmpsta[6];\n\t    mxvg_(invprc, state, &c__6, &c__6, tmpsta);\n    moved_(tmpsta, &c__6, state);\n\t    for (pp = 0; pp<3; pp++){\n\t      //\t      \t      \t      printf(\"%f \", state[pp]);\n\t      CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[pp] = state[pp];\n\t      CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[pp] = state[pp+3];\n\t    }\n\t    \t    /* printf(\"\\n\"); */\n\t    \t    /* for (pp = 0; pp<3; pp++){ */\n\t      \t    /*   \t      printf(\"%f \", state[pp+3]); */\n\t\t    /* } */\n\t    /* printf(\"\\n\"); */\n\t    /* MPI_Finalize();exit(0); */\n\t    \n\t    // Initialize the Keplerian Elements\n\t    cart2kep( &OE_temp, CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL, CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL, CONSTELLATION->spacecraft[ii][eee].et,  PARAMS->EARTH.GRAVITY.mu );\n\n\t    CONSTELLATION->spacecraft[ii][eee].OE.sma          =OE_temp.sma;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.eccentricity =OE_temp.eccentricity;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.inclination  =OE_temp.inclination;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.long_an      =OE_temp.long_an;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.w            =OE_temp.w;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.f            =OE_temp.f;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.tp           =OE_temp.tp;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.E            =OE_temp.E;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.ra            =OE_temp.ra;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.initial_an_to_sc = OE_temp.an_to_sc;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.w_ave_temp = OE_temp.w;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.w_ave = 9999.9999/RAD2DEG;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.sma_ave_temp = OE_temp.sma;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.sma_ave = 9999.9999;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.ecc_ave_temp = OE_temp.eccentricity;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.ecc_ave = 9999.9999;\n\n\t    CONSTELLATION->spacecraft[ii][eee].OE.ave_increm = 1;\n\t    CONSTELLATION->spacecraft[ii][eee].et_last_orbit = CONSTELLATION->spacecraft[ii][eee].et;\n\t    CONSTELLATION->spacecraft[ii][eee].orbit_number = 0;\n    \n\t    /* printf(\"ecc = %e | %e\\n\", CONSTELLATION->spacecraft[ii][eee].OE.eccentricity, elems[5]); */\n\t    /* exit(0); */\n\n\t    radius_perigee = CONSTELLATION->spacecraft[ii][eee].OE.sma * ( 1 - CONSTELLATION->spacecraft[ii][eee].OE.eccentricity );\n\t    if (radius_perigee < PARAMS->EARTH.radius){\n\t      printf(\"***! The orbit of satellite %d intersects the Earth (altitude of perigee = %f km). The program will stop. !***\\n\",ii, radius_perigee-PARAMS->EARTH.radius);\n\t      MPI_Finalize();\n\t      exit(0);\n\t    }\n\t    if (iDebugLevel >= 1){\n\t      if (iProc == 0) printf(\"-- (initialize_constellation) Done initializing et, r_i2cg_INRTL, v_i2cg_INRTL, orbital elements from TLE.\\n\");\n\t    }\n\n\t  }\n\n\t  /*************************************************************************************/\n\t  /*************************************************************************************/\n\t  /********** INITIALIZE: et, r_i2cg_INRTL, v_i2cg_INRTL, OE FOR MAIN SC BY COE ********/\n\t  /*************************************************************************************/\n\t  /*************************************************************************************/\n\n\t  if ( strcmp( OPTIONS->type_orbit_initialisation, \"oe\" ) == 0 ){\n\t    if (iDebugLevel >= 1){\n\t      if (iProc == 0) printf(\"-- (initialize_constellation) Initializing et, r_i2cg_INRTL, v_i2cg_INRTL, orbital elements from orbital elements.\\n\");\n\t    }\n\n\t    CONSTELLATION->spacecraft[ii][eee].et = et;\n\t    CONSTELLATION->spacecraft[ii][eee].et_sc_initial = et;\n\t    // Initialize the Keplerian Elements\n\t    CONSTELLATION->spacecraft[ii][eee].OE.sma            = ( PARAMS->EARTH.radius + OPTIONS->apogee_alt[ii] ) / ( 1 + OPTIONS->eccentricity[ii] ); // semi-major axis (CBV)\n\n\t    //    printf(\"sma = %f\\n\", CONSTELLATION->spacecraft[ii][eee].OE.sma);\n\t    radius_perigee = CONSTELLATION->spacecraft[ii][eee].OE.sma * ( 1 - OPTIONS->eccentricity[ii] );\n\t    if (radius_perigee < PARAMS->EARTH.radius){\n\t      printf(\"***! The orbit of satellite %d intersects the Earth (altitude of perigee = %f km). The program will stop. !***\\n\",ii, radius_perigee-PARAMS->EARTH.radius);\n\t      MPI_Finalize();\n\t      exit(0);\n\t    }\n    \n\t    CONSTELLATION->spacecraft[ii][eee].OE.inclination    = OPTIONS->inclination[ii] * DEG2RAD;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.w              = OPTIONS->w[ii] * DEG2RAD;                                // argument of perigee (CBV)\n\t    CONSTELLATION->spacecraft[ii][eee].OE.long_an        = OPTIONS->long_an[ii] * DEG2RAD;                          // RAAN (CBV)\n\t    CONSTELLATION->spacecraft[ii][eee].OE.f              = OPTIONS->f[ii] * DEG2RAD;                                // true anomaly (CBV)\n\t    CONSTELLATION->spacecraft[ii][eee].OE.eccentricity   = OPTIONS->eccentricity[ii];\n\t    CONSTELLATION->spacecraft[ii][eee].OE.initial_an_to_sc =  fmod(CONSTELLATION->spacecraft[ii][eee].OE.w + CONSTELLATION->spacecraft[ii][eee].OE.f, 2*M_PI);\n\n\t    // Initialize the inertial state\n\t    kep2cart(   CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL,\n\t\t\tCONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL,\n\t\t\t&PARAMS->EARTH.GRAVITY.mu,\n\t\t\t&CONSTELLATION->spacecraft[ii][eee].OE); // Computes the ECI coordinates based on the Keplerian inputs (orbital elements and mu) (in propagator.c) (CBV)\n\n\t    // !!!!!!!!!!!!!!!!!!!!!! REMOVE TWO LINES BELOW!!!!!!!!!  \n\n\t    /* //\t  for molniya */\n\t    /* CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[0] = -1529.8942870000; CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[1] =  -2672.8773570000; CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[2] =  -6150.1153400000; */\n\t    /* CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[0] =  8.7175180000; CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[1] =  -4.9897090000; CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[2] =  0.0000000000; */\n\n\t    /* \t  // for geo */\n\t    /* CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[0] = 36607.3548590000;  CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[1] =  -20921.7217480000; CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[2] = -0.0000000000; */\n\t    /* CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[0] = 1.5256360000;  CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[1] = 2.6694510000;  CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[2] =  0.0000000000; */\n\n\t    // for iss\n\t    /* CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[0] = -4467.3083710453;  CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[1] =  -5053.5032161387; CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[2] =  -427.6792780851; */\n\t    /* CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[0] = 3.8279470371;  CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[1] = -2.8757493806;  CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[2] =  -6.0045254246; */\n\n\t    // !!!!!!!!!!!!!!!!!!!!!! END OF REMOVE TWO LINES BELOW!!!!!!!!!\n\n\t    // Right ascension\n\t    CONSTELLATION->spacecraft[ii][eee].OE.ra =  atan2(CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[1], CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[0]);\n\t    if ( CONSTELLATION->spacecraft[ii][eee].OE.ra < 0){\n\t      CONSTELLATION->spacecraft[ii][eee].OE.ra = 2*M_PI + CONSTELLATION->spacecraft[ii][eee].OE.ra ;\n\t    }\n\n\n\n\t    // !!!!!!!!!!!!!!!!!!!!!!!!!! THE BLOCK BELOW IS TO INITIALIZE SATELLLITE 2 WITH THE CORRECT SPACING WITH RESPECT TO SATELLITE 1. IT IS JUST FOR A TRY, AND SHOULD BE REMOVED AND IMPLEMENTED IN THE CODE ITSELF. SO IF IT'S STILL HERE AFTER JUNE 10TH, 2016 THEN REMOVE IT!\n\t    /* if ( strcmp( OPTIONS->type_orbit_initialisation, \"oe\" ) == 0 ){ */\n\t    /*   if ( ii > 0){ */\n\t    /*     v_copy( CONSTELLATION->spacecraft[ii][0].r_i2cg_INRTL, CONSTELLATION->spacecraft[0][0].r_i2cg_INRTL); */\n\t    /*     v_copy( CONSTELLATION->spacecraft[ii][0].v_i2cg_INRTL, CONSTELLATION->spacecraft[0][0].v_i2cg_INRTL); */\n\n\t    /*     CONSTELLATION->spacecraft[ii][0].OE.sma            = ( PARAMS->EARTH.radius + OPTIONS->apogee_alt[0] ) / ( 1 + OPTIONS->eccentricity[0] ); // semi-major axis (CBV) */\n\n\t    /*     //    printf(\"sma = %f\\n\", CONSTELLATION->spacecraft[ii][0].OE.sma); */\n\t    /*     radius_perigee = CONSTELLATION->spacecraft[ii][0].OE.sma * ( 1 - OPTIONS->eccentricity[0] ); */\n\t    /*     if (radius_perigee < PARAMS->EARTH.radius){ */\n\t    /*       printf(\"The orbit of satellite %d intersects the Earth (altitude of perigee = %f km). The program will stop. !***\\n\",ii, radius_perigee-PARAMS->EARTH.radius); */\n\t    /*       exit(0); */\n\t    /*     } */\n    \n\t    /*     CONSTELLATION->spacecraft[ii][0].OE.inclination    = OPTIONS->inclination[0] * DEG2RAD; */\n\t    /*     CONSTELLATION->spacecraft[ii][0].OE.w              = OPTIONS->w[0] * DEG2RAD;                                // argument of perigee (CBV) */\n\t    /*     CONSTELLATION->spacecraft[ii][0].OE.long_an        = OPTIONS->long_an[0] * DEG2RAD;                          // RAAN (CBV) */\n\t    /*     CONSTELLATION->spacecraft[ii][0].OE.f              = OPTIONS->f[0] * DEG2RAD;                                // true anomaly (CBV) */\n\t    /*     CONSTELLATION->spacecraft[ii][0].OE.eccentricity   = OPTIONS->eccentricity[0]; */\n\t    /*     CONSTELLATION->spacecraft[ii][0].OE.ra =  atan2(CONSTELLATION->spacecraft[ii][0].r_i2cg_INRTL[1], CONSTELLATION->spacecraft[ii][0].r_i2cg_INRTL[0]); */\n\t    /*     if ( CONSTELLATION->spacecraft[ii][0].OE.ra < 0){ */\n\t    /*       CONSTELLATION->spacecraft[ii][0].OE.ra = 2*M_PI + CONSTELLATION->spacecraft[ii][0].OE.ra ; */\n\t    /*     } */\n\n\t    /*   } */\n\t    /* } */\n\t    // !!!!!!!!!!!!!!!!!!!!!!!!!! END OF THE BLOCK BELOW IS TO INITIALIZE SATELLLITE 2 WITH THE CORRECT SPACING WITH RESPECT TO SATELLITE 1. IT IS JUST FOR A TRY, AND SHOULD BE REMOVED AND IMPLEMENTED IN THE CODE ITSELF. SO IF IT'S STILL HERE AFTER JUNE 10TH, 2016 THEN REMOVE IT!\n\n\t    if (iDebugLevel >= 1){\n\t      if (iProc == 0) printf(\"-- (initialize_constellation) Done initializing et, r_i2cg_INRTL, v_i2cg_INRTL, orbital elements from orbital elements.\\n\");\n\t    }\n\n\t  } // end of initiliazing et, r_i2cg_INRTL, v_i2cg_INRTL, OE FOR MAIN SC BY COE\n\n\t  /*************************************************************************************/\n\t  /*************************************************************************************/\n\t  /** INITIALIZE: et, r_i2cg_INRTL, v_i2cg_INRTL, r_ecef2cg_ECEF, v_ecef2cg_ECEF, OE FOR MAIN SC BY ECEF STATE (position and velocity in ECEF) **/\n\t  /*************************************************************************************/\n\t  /*************************************************************************************/\n\n\t  if ( strcmp( OPTIONS->type_orbit_initialisation, \"state_ecef\" ) == 0 ){\n\t    if (iDebugLevel >= 1){\n\t      if (iProc == 0) printf(\"-- (initialize_constellation) Initializing et, r_i2cg_INRTL, v_i2cg_INRTL, r_ecef2cg_ECEF, v_ecef2cg_ECEF, orbital elements from ECEF state (position and velocity).\\n\");\n\t    }\n\n\t    CONSTELLATION->spacecraft[ii][eee].et = et;\n\t    CONSTELLATION->spacecraft[ii][eee].et_sc_initial = et;\n\n\t    // ECEF position and velocity\n\t    CONSTELLATION->spacecraft[ii][eee].r_ecef2cg_ECEF[0] = OPTIONS->x_ecef[ii];\n\t    CONSTELLATION->spacecraft[ii][eee].r_ecef2cg_ECEF[1] = OPTIONS->y_ecef[ii];\n\t    CONSTELLATION->spacecraft[ii][eee].r_ecef2cg_ECEF[2] = OPTIONS->z_ecef[ii];\n\t    CONSTELLATION->spacecraft[ii][eee].v_ecef2cg_ECEF[0] = OPTIONS->vx_ecef[ii];\n\t    CONSTELLATION->spacecraft[ii][eee].v_ecef2cg_ECEF[1] = OPTIONS->vy_ecef[ii];\n\t    CONSTELLATION->spacecraft[ii][eee].v_ecef2cg_ECEF[2] = OPTIONS->vz_ecef[ii];\n\n\t    // ECI position and velocity\n\t    estate[0] = CONSTELLATION->spacecraft[ii][eee].r_ecef2cg_ECEF[0];estate[1] = CONSTELLATION->spacecraft[ii][eee].r_ecef2cg_ECEF[1];estate[2] = CONSTELLATION->spacecraft[ii][eee].r_ecef2cg_ECEF[2];\n\t    estate[3] = CONSTELLATION->spacecraft[ii][eee].v_ecef2cg_ECEF[0];estate[4] = CONSTELLATION->spacecraft[ii][eee].v_ecef2cg_ECEF[1];estate[5] = CONSTELLATION->spacecraft[ii][eee].v_ecef2cg_ECEF[2];\n\t    sxform_c (  PARAMS->EARTH.earth_fixed_frame,  \"J2000\", CONSTELLATION->spacecraft[ii][eee].et,    xform  ); \n\t    mxvg_c   (  xform,       estate,   6,  6, jstate ); \n\t    CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[0] = jstate[0]; CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[1] = jstate[1]; CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[2] = jstate[2];\n\t    CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[0] = jstate[3]; CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[1] = jstate[4]; CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[2] = jstate[5];\n\t    /* pxform_c( PARAMS->EARTH.earth_fixed_frame, \"J2000\", CONSTELLATION->spacecraft[ii][eee].et, T_ECEF_to_J2000); */\n\t    /* m_x_v(CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL, T_ECEF_to_J2000, CONSTELLATION->spacecraft[ii][eee].r_ecef2cg_ECEF); */\n\t    /* m_x_v(CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL, T_ECEF_to_J2000, CONSTELLATION->spacecraft[ii][eee].v_ecef2cg_ECEF); */\n\n\t    // Orbital elements\n\t    cart2kep( &CONSTELLATION->spacecraft[ii][eee].OE, CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL, CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL, CONSTELLATION->spacecraft[ii][eee].et,  PARAMS->EARTH.GRAVITY.mu);\n\n\t    CONSTELLATION->spacecraft[ii][eee].OE.initial_an_to_sc = CONSTELLATION->spacecraft[ii][eee].OE.an_to_sc;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.w_ave_temp = CONSTELLATION->spacecraft[ii][eee].OE.w;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.w_ave = 9999.999999/RAD2DEG;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.sma_ave_temp = CONSTELLATION->spacecraft[ii][eee].OE.sma;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.sma_ave = 9999.999999;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.ecc_ave_temp = CONSTELLATION->spacecraft[ii][eee].OE.eccentricity;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.ecc_ave = 9999.999999;\n\n\t    CONSTELLATION->spacecraft[ii][eee].OE.ave_increm = 1;\n\t    CONSTELLATION->spacecraft[ii][eee].et_last_orbit = CONSTELLATION->spacecraft[ii][eee].et;\n\t    CONSTELLATION->spacecraft[ii][eee].orbit_number = 0;\n\n\n\t    radius_perigee = CONSTELLATION->spacecraft[ii][eee].OE.sma * ( 1 - CONSTELLATION->spacecraft[ii][eee].OE.eccentricity  );\n\t    if (radius_perigee < PARAMS->EARTH.radius){\n\t      printf(\"***! The orbit of satellite %d intersects the Earth (altitude of perigee = %f km). The program will stop. !***\\n\",ii, radius_perigee-PARAMS->EARTH.radius);\n\t      MPI_Finalize();\n\t      exit(0);\n\t    }\n\n\t    if (iDebugLevel >= 1){\n\t      if (iProc == 0) printf(\"-- (initialize_constellation) Done initializing et, r_i2cg_INRTL, v_i2cg_INRTL, r_ecef2cg_ECEF, v_ecef2cg_ECEF, orbital elements from ECEF state (position and velocity).\\n\");\n\t    }\n\n\t  } // end of initializing et, r_i2cg_INRTL, v_i2cg_INRTL, r_ecef2cg_ECEF, v_ecef2cg_ECEF, OE FOR MAIN SC BY ECEF STATE\n\n\n\t  /*************************************************************************************/\n\t  /*************************************************************************************/\n\t  /** INITIALIZE: et, r_i2cg_INRTL, v_i2cg_INRTL, OE FOR MAIN SC BY ECI STATE (position and velocity in ECI) **/\n\t  /*************************************************************************************/\n\t  /*************************************************************************************/\n\n\t  if ( strcmp( OPTIONS->type_orbit_initialisation, \"state_eci\" ) == 0 ){\n\t    if (iDebugLevel >= 1){\n\t      if (iProc == 0) printf(\"-- (initialize_constellation) Initializing et, r_i2cg_INRTL, v_i2cg_INRTL, orbital elements from ECI state (position and velocity).\\n\");\n\t    }\n\n\t    CONSTELLATION->spacecraft[ii][eee].et = et;\n\t    CONSTELLATION->spacecraft[ii][eee].et_sc_initial = et;\n\n\t    // ECI position and velocity\n\t    CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[0] = OPTIONS->x_eci[ii];\n\t    CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[1] = OPTIONS->y_eci[ii];\n\t    CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[2] = OPTIONS->z_eci[ii];\n\t    CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[0] = OPTIONS->vx_eci[ii];\n\t    CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[1] = OPTIONS->vy_eci[ii];\n\t    CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[2] = OPTIONS->vz_eci[ii];\n\n\t    // Orbital elements\n\t    cart2kep( &CONSTELLATION->spacecraft[ii][eee].OE, CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL, CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL, CONSTELLATION->spacecraft[ii][eee].et,  PARAMS->EARTH.GRAVITY.mu);\n\n\t    CONSTELLATION->spacecraft[ii][eee].OE.initial_an_to_sc = CONSTELLATION->spacecraft[ii][eee].OE.an_to_sc;\n\t    \n\t    CONSTELLATION->spacecraft[ii][eee].OE.w_ave_temp = CONSTELLATION->spacecraft[ii][eee].OE.w;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.w_ave = 9999.999999/RAD2DEG;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.sma_ave_temp = CONSTELLATION->spacecraft[ii][eee].OE.sma;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.sma_ave = 9999.999999;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.ecc_ave_temp = CONSTELLATION->spacecraft[ii][eee].OE.eccentricity;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.ecc_ave = 9999.999999;\n\n\t    CONSTELLATION->spacecraft[ii][eee].OE.ave_increm = 1;\n\t    CONSTELLATION->spacecraft[ii][eee].et_last_orbit = CONSTELLATION->spacecraft[ii][eee].et;\n\t    CONSTELLATION->spacecraft[ii][eee].orbit_number = 0;\n\n\n\t    radius_perigee = CONSTELLATION->spacecraft[ii][eee].OE.sma * ( 1 - CONSTELLATION->spacecraft[ii][eee].OE.eccentricity  );\n\t    if (radius_perigee < PARAMS->EARTH.radius){\n\t      printf(\"***! The orbit of satellite %d intersects the Earth (altitude of perigee = %f km). The program will stop. !***\\n\",ii, radius_perigee-PARAMS->EARTH.radius);\n\t      MPI_Finalize();\n\t      exit(0);\n\t    }\n\n\t    if (iDebugLevel >= 1){\n\t      if (iProc == 0) printf(\"-- (initialize_constellation) Done initializing et, r_i2cg_INRTL, v_i2cg_INRTL, r_ecef2cg_ECEF, v_ecef2cg_ECEF from ECI state (position and velocity).\\n\");\n\t    }\n\n\t  } // end of initializing et, r_i2cg_INRTL, v_i2cg_INRTL, r_ecef2cg_ECEF, v_ecef2cg_ECEF, OE FOR MAIN SC BY ECI STATE\n\n\n\t  /*************************************************************************************/\n\t  /*************************************************************************************/\n\t  /** INITIALIZE: et, r_i2cg_INRTL, v_i2cg_INRTL, OE FOR MAIN SC BY ECI STATE FROM COLLISION INPUT FILE (position and velocity in ECI) **/\n\t  /*************************************************************************************/\n\t  /*************************************************************************************/\n\n\t  if ( (strcmp( OPTIONS->type_orbit_initialisation, \"collision\" ) == 0 ) || (strcmp( OPTIONS->type_orbit_initialisation, \"collision_vcm\" ) == 0 )){\n\t    if (iDebugLevel >= 1){\n\t      if (iProc == 0) printf(\"-- (initialize_constellation) Initializing et, r_i2cg_INRTL, v_i2cg_INRTL, orbital elements from ECI state reead from the input collision file (position and velocity).\\n\");  }\n\n\n\t    if (strcmp( OPTIONS->type_orbit_initialisation, \"collision\" ) == 0 ){\n\t    CONSTELLATION->spacecraft[ii][eee].et_sc_initial = et;\n\t    CONSTELLATION->spacecraft[ii][eee].et = et;\n\t    }\n\t    else{\n\t    CONSTELLATION->spacecraft[ii][eee].et = OPTIONS->et_vcm[ii];\n\t      CONSTELLATION->spacecraft[ii][eee].et_sc_initial = OPTIONS->et_vcm[ii]; // the eoch time of the two VCMs are different\n/* \t      if ( (OPTIONS->et_vcm[ii] > OPTIONS->swpc_et_first_prediction) && (OPTIONS->swpc_need_predictions == 1)){// overwrite aaa_mod written before */\n/* previous_index( &OPTIONS->aaa_mod, OPTIONS->et_mod_f107_ap, OPTIONS->et_interpo[0] - OPTIONS->swpc_et_first_prediction, ( OPTIONS->nb_time_steps + (int)(( 2 * 24 * 3600. ) / OPTIONS->dt)));  */\n/* \t      CONSTELLATION->aaa_mod[ii] =  OPTIONS->aaa_mod + OPTIONS->et_vcm[ii] - CONSTE; */\n/* \t      } */\n/* \t      else{ */\n/* \t\tCONSTELLATION->aaa_mod[ii] =  0; */\n/* \t\t\" */\n\t    }\n\n\t    // ECI position and velocity\n\t    CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[0] = OPTIONS->x_eci[ii];\n\t    CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[1] = OPTIONS->y_eci[ii];\n\t    CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[2] = OPTIONS->z_eci[ii];\n\t    CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[0] = OPTIONS->vx_eci[ii];\n\t    CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[1] = OPTIONS->vy_eci[ii];\n\t    CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[2] = OPTIONS->vz_eci[ii];\n\n\t    // Orbital elements\n\t    cart2kep( &CONSTELLATION->spacecraft[ii][eee].OE, CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL, CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL, CONSTELLATION->spacecraft[ii][eee].et,  PARAMS->EARTH.GRAVITY.mu);\n\n\t    CONSTELLATION->spacecraft[ii][eee].OE.initial_an_to_sc = CONSTELLATION->spacecraft[ii][eee].OE.an_to_sc;\n\t    \n\t    CONSTELLATION->spacecraft[ii][eee].OE.w_ave_temp = CONSTELLATION->spacecraft[ii][eee].OE.w;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.w_ave = 9999.999999/RAD2DEG;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.sma_ave_temp = CONSTELLATION->spacecraft[ii][eee].OE.sma;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.sma_ave = 9999.999999;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.ecc_ave_temp = CONSTELLATION->spacecraft[ii][eee].OE.eccentricity;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.ecc_ave = 9999.999999;\n\n\t    CONSTELLATION->spacecraft[ii][eee].OE.ave_increm = 1;\n\t    CONSTELLATION->spacecraft[ii][eee].et_last_orbit = CONSTELLATION->spacecraft[ii][eee].et;\n\t    CONSTELLATION->spacecraft[ii][eee].orbit_number = 0;\n\n\n\t    radius_perigee = CONSTELLATION->spacecraft[ii][eee].OE.sma * ( 1 - CONSTELLATION->spacecraft[ii][eee].OE.eccentricity  );\n\t    if (radius_perigee < PARAMS->EARTH.radius){\n\t      printf(\"***! The orbit of satellite %d intersects the Earth (altitude of perigee = %f km). The program will stop. !***\\n\",ii, radius_perigee-PARAMS->EARTH.radius);\n\t      MPI_Finalize();\n\t      exit(0);\n\t    }\n\n\t    if (iDebugLevel >= 1){\n\t      if (iProc == 0) printf(\"-- (initialize_constellation) Initializing et, r_i2cg_INRTL, v_i2cg_INRTL, orbital elements from ECI state reead from the input collision file (position and velocity).\\n\");\n\t    }\n\n\t  } // end of initializing et, r_i2cg_INRTL, v_i2cg_INRTL, r_ecef2cg_ECEF, v_ecef2cg_ECEF, OE FOR MAIN SC BY ECI STATE FROM COLLISION INPUT FILE\n\n\n\t  /*************************************************************************************/\n\t  /*************************************************************************************/\n\t  /** INITIALIZE: et, r_i2cg_INRTL, v_i2cg_INRTL, OE FOR MAIN SC BY DEPLOYMENT **/\n\t  /*************************************************************************************/\n\t  /*************************************************************************************/\n\n\t  if ( strcmp( OPTIONS->type_orbit_initialisation, \"deployment\" ) == 0 ){\n\t    if (iDebugLevel >= 1){\n\t      if (iProc == 0) printf(\"-- (initialize_constellation) Initializing et, r_i2cg_INRTL, v_i2cg_INRTL, orbital elements from a deployment module.\\n\");\n\t    }\n\n\t    CONSTELLATION->spacecraft[ii][eee].et = et;\n\t    CONSTELLATION->spacecraft[ii][eee].et_sc_initial = et;\n\t  \n\t    // Convert the deployment module orbital elements in ECI coordinates\n\t    ORBITAL_ELEMENTS_T deployment_module_orbital_elements;\n\t    deployment_module_orbital_elements.sma            = ( PARAMS->EARTH.radius + OPTIONS->deployment_module_orbital_elements[ii][0] ) / ( 1 + OPTIONS->deployment_module_orbital_elements[ii][5] ); \n\t    radius_perigee = deployment_module_orbital_elements.sma * ( 1 - OPTIONS->deployment_module_orbital_elements[ii][5] );\n\t    if (radius_perigee < PARAMS->EARTH.radius){\n\t      printf(\"***! The orbit of satellite %d intersects the Earth (altitude of perigee = %f km). The program will stop. !***\\n\",ii, radius_perigee-PARAMS->EARTH.radius);\n\t      MPI_Finalize();\n\t      exit(0);\n\t    }    \n\t    deployment_module_orbital_elements.inclination    = OPTIONS->deployment_module_orbital_elements[ii][1] * DEG2RAD;\n\t    deployment_module_orbital_elements.w              = OPTIONS->deployment_module_orbital_elements[ii][2] * DEG2RAD; \n\t    deployment_module_orbital_elements.long_an        = OPTIONS->deployment_module_orbital_elements[ii][3] * DEG2RAD; \n\t    deployment_module_orbital_elements.f              = OPTIONS->deployment_module_orbital_elements[ii][4] * DEG2RAD; \n\t    deployment_module_orbital_elements.eccentricity   = OPTIONS->deployment_module_orbital_elements[ii][5];\n\t    //\t  printf(\"%f %f %f %f %f %f %f\\n\", OPTIONS->deployment_module_orbital_elements[ii][0], deployment_module_orbital_elements.sma,deployment_module_orbital_elements.inclination*RAD2DEG,deployment_module_orbital_elements.w,deployment_module_orbital_elements.long_an,deployment_module_orbital_elements.f,deployment_module_orbital_elements.eccentricity);\n\t    double eci_position_deployment_module[3]; double eci_velocity_deployment_module[3];\n\t    kep2cart(eci_position_deployment_module, eci_velocity_deployment_module, &PARAMS->EARTH.GRAVITY.mu, &deployment_module_orbital_elements);\n\n\t    // Convert the deployment velocity of the satellite from the deployment module LVLH coordinate system to ECI velocity\n\t    double velocity_satellte_deployed_lvlh[3]; double velocity_satellte_deployed_eci[3];\n\t    velocity_satellte_deployed_lvlh[0] = OPTIONS->deployment_speed[ii] * cos(OPTIONS->deployment_angle[ii]*DEG2RAD) / 1000.; // / 1000. because the input is in m/s but we want km/s\n\t    velocity_satellte_deployed_lvlh[1] = -OPTIONS->deployment_speed[ii] * sin(OPTIONS->deployment_angle[ii]*DEG2RAD) / 1000.; // \"-\" because LVLH _Y points to the left and we are considering that an angle of for example 30 degrees is counted from the in-track direction to the right (clockwise). If the sc is ejected to the left with an angle of for example 90 degrees, then deployment_angle is equal to 270 degrees\n\t    velocity_satellte_deployed_lvlh[2] = 0; // for now we assume the satellites are deployed in the LVLH_X/Y plane\n\t    double T_inrtl_2_lvlh_for_deployment[3][3]; \t  double T_lvlh_2_inrtl_for_deployment[3][3];\n\t    compute_T_inrtl_2_lvlh(T_inrtl_2_lvlh_for_deployment, eci_position_deployment_module, eci_velocity_deployment_module);\n\t    m_trans(T_lvlh_2_inrtl_for_deployment, T_inrtl_2_lvlh_for_deployment);\n\t    m_x_v(velocity_satellte_deployed_eci, T_lvlh_2_inrtl_for_deployment, velocity_satellte_deployed_lvlh);\n\t  \n\t    // Add deployment velocity of the satellite to the velocity of the deployment module (in ECI)\n\t    v_add(CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL, eci_velocity_deployment_module, velocity_satellte_deployed_eci);\n\n\t    // ECI position of the satellite is the same as the ECI position of the deployment module\n\t    v_copy(CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL, eci_position_deployment_module);\n\n\t    // Right ascension\n\t    CONSTELLATION->spacecraft[ii][eee].OE.ra =  atan2(CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[1], CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[0]);\n\t    if ( CONSTELLATION->spacecraft[ii][eee].OE.ra < 0){\n\t      CONSTELLATION->spacecraft[ii][eee].OE.ra = 2*M_PI + CONSTELLATION->spacecraft[ii][eee].OE.ra ;\n\t    }\n\n\t    // Orbital elements\n\t    cart2kep( &CONSTELLATION->spacecraft[ii][eee].OE, CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL, CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL, CONSTELLATION->spacecraft[ii][eee].et,  PARAMS->EARTH.GRAVITY.mu);\n\n\t    CONSTELLATION->spacecraft[ii][eee].OE.initial_an_to_sc = CONSTELLATION->spacecraft[ii][eee].OE.an_to_sc;\n\t    \n\t    CONSTELLATION->spacecraft[ii][eee].OE.w_ave_temp = CONSTELLATION->spacecraft[ii][eee].OE.w;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.w_ave = 9999.999999/RAD2DEG;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.sma_ave_temp = CONSTELLATION->spacecraft[ii][eee].OE.sma;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.sma_ave = 9999.999999;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.ecc_ave_temp = CONSTELLATION->spacecraft[ii][eee].OE.eccentricity;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.ecc_ave = 9999.999999;\n\n\t    CONSTELLATION->spacecraft[ii][eee].OE.ave_increm = 1;\n\t    CONSTELLATION->spacecraft[ii][eee].et_last_orbit = CONSTELLATION->spacecraft[ii][eee].et;\n\t    CONSTELLATION->spacecraft[ii][eee].orbit_number = 0;\n\n\n\t    radius_perigee = CONSTELLATION->spacecraft[ii][eee].OE.sma * ( 1 - CONSTELLATION->spacecraft[ii][eee].OE.eccentricity  );\n\t    if (radius_perigee < PARAMS->EARTH.radius){\n\t      printf(\"***! The orbit of satellite %d intersects the Earth (altitude of perigee = %f km). The program will stop. !***\\n\",ii, radius_perigee-PARAMS->EARTH.radius);\n\t      MPI_Finalize();\n\t      exit(0);\n\t    }\n\n\t    if (iDebugLevel >= 1){\n\t      if (iProc == 0) printf(\"-- (initialize_constellation) Done initializing et, r_i2cg_INRTL, v_i2cg_INRTL, orbital elements from a deployment module.\\n\");\n\t    }\n\n\t  } // end of initializing et, r_i2cg_INRTL, v_i2cg_INRTL, OE FOR MAIN SC BY DEPLOYMENT\n\n\n\n\t\n\t  for (ccc = 0; ccc < nProcs; ccc++){ // the iProc that runs main sc ii sends to the other iProc (that do not run main sc ii) the orbital elements of main sc ii\n\t    if (ccc != iProc){\n\t      MPI_Send(&CONSTELLATION->spacecraft[ii][0].OE.sma, 1, MPI_DOUBLE, ccc, 0, MPI_COMM_WORLD);\n\t      MPI_Send(&CONSTELLATION->spacecraft[ii][0].OE.eccentricity , 1, MPI_DOUBLE, ccc, 0, MPI_COMM_WORLD);\n\t      MPI_Send(&CONSTELLATION->spacecraft[ii][0].OE.inclination , 1, MPI_DOUBLE, ccc, 0, MPI_COMM_WORLD);\n\t      MPI_Send(&CONSTELLATION->spacecraft[ii][0].OE.w , 1, MPI_DOUBLE, ccc, 0, MPI_COMM_WORLD);\n\t      MPI_Send(&CONSTELLATION->spacecraft[ii][0].OE.long_an , 1, MPI_DOUBLE, ccc, 0, MPI_COMM_WORLD);\n\t      MPI_Send(&CONSTELLATION->spacecraft[ii][0].OE.f , 1, MPI_DOUBLE, ccc, 0, MPI_COMM_WORLD);\n\t      //   printf(\"iProc %d sends to iProc %d for ii = %d\\n\", iProc, ccc, ii);\n\t\n\t    }\n\t  }\n\n\t  /* \tif (nProcs > 1){ */\n\t  /* \t  for (ccc = 0; ccc < nProcs; ccc++){ */\n\t  /* \t    MPI_Send(&CONSTELLATION->spacecraft[ii][0].OE.sma, 1, MPI_DOUBLE, ccc, 0, MPI_COMM_WORLD); */\n\t  /* \t    MPI_Send(&CONSTELLATION->spacecraft[ii][0].OE.eccentricity , 1, MPI_DOUBLE, ccc, 0, MPI_COMM_WORLD); */\n\t  /* \t    MPI_Send(&CONSTELLATION->spacecraft[ii][0].OE.inclination , 1, MPI_DOUBLE, ccc, 0, MPI_COMM_WORLD); */\n\t  /* \t    MPI_Send(&CONSTELLATION->spacecraft[ii][0].OE.w , 1, MPI_DOUBLE, ccc, 0, MPI_COMM_WORLD); */\n\t  /* \t    MPI_Send(&CONSTELLATION->spacecraft[ii][0].OE.long_an , 1, MPI_DOUBLE, ccc, 0, MPI_COMM_WORLD); */\n\t  /* \t    MPI_Send(&CONSTELLATION->spacecraft[ii][0].OE.f , 1, MPI_DOUBLE, ccc, 0, MPI_COMM_WORLD); */\n\t  /* \t    //\t  printf(\"Sent to %d (out of %d)\\n\", ccc, nProcs); */\n\t  /* \t  } */\n\t  /* \t} */\n\n\n\n\t  /* \tif (iProc == 0) printf(\"BEFORE\\n\"); */\n\t  /*     MPI_Barrier(MPI_COMM_WORLD); */\n\t  /*     if (iProc == 0) printf(\"RIG after\\n\"); */\n\t  /* \t  MPI_Bcast(&CONSTELLATION->spacecraft[ii][0].OE.sma, 1, MPI_DOUBLE,  0, MPI_COMM_WORLD); */\n\t  /* \t  MPI_Bcast(&CONSTELLATION->spacecraft[ii][0].OE.eccentricity , 1, MPI_DOUBLE,  0, MPI_COMM_WORLD); */\n\t  /* \t  MPI_Bcast(&CONSTELLATION->spacecraft[ii][0].OE.inclination , 1, MPI_DOUBLE,  0, MPI_COMM_WORLD); */\n\t  /* \t  MPI_Bcast(&CONSTELLATION->spacecraft[ii][0].OE.w , 1, MPI_DOUBLE,  0, MPI_COMM_WORLD); */\n\t  /* \t  MPI_Bcast(&CONSTELLATION->spacecraft[ii][0].OE.long_an , 1, MPI_DOUBLE,  0, MPI_COMM_WORLD); */\n\t  /* \t  MPI_Bcast(&CONSTELLATION->spacecraft[ii][0].OE.f , 1, MPI_DOUBLE,  0, MPI_COMM_WORLD); */\n\t  /* \tif (iProc == 0) printf(\"AFTER\\n\"); */\n\t  if (iDebugLevel >= 1){\n\t    if (iProc == 0) printf(\"-- (initialize_constellation) Done initiliazing et, r_i2cg_INRTL, v_i2cg_INRTL, OE FOR MAIN SC by iProc 0 (voluntarily prnting all iProc here). (iProc %d)\\n\", iProc); \n\t  }\n\t}// end of initiliazing et, r_i2cg_INRTL, v_i2cg_INRTL, OE FOR MAIN SC BY COE and TLE\n\n\t/*************************************************************************************/\n\t/*************************************************************************************/\n\t/*************************************************************************************/\n\t/************** INITIALIZE: et, r_i2cg_INRTL, v_i2cg_INRTL, OE, number_of_collisions FOR ENSEMBLE SC ***********/\n\t/*************************************************************************************/\n\t/*************************************************************************************/\n\t/*************************************************************************************/\n\n\telse if ( ( start_ensemble[ii] != 0 ) && ( eee == array_sc[start_ensemble[ii]] ) ){// if this iProc is not runnning the main sc, then receives the orbital elements of main sc ii, which was run (and sent) by iProc which_iproc_is_running_main_sc[ii] (eee = array_sc[start_ensemble[ii]] is so that you receive only once)\n\n\t  MPI_Recv(&CONSTELLATION->spacecraft[ii][0].OE.sma, 1, MPI_DOUBLE, which_iproc_is_running_main_sc[ii], 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n\t  MPI_Recv(&CONSTELLATION->spacecraft[ii][0].OE.eccentricity, 1, MPI_DOUBLE, which_iproc_is_running_main_sc[ii], 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n\t  MPI_Recv(&CONSTELLATION->spacecraft[ii][0].OE.inclination, 1, MPI_DOUBLE, which_iproc_is_running_main_sc[ii], 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n\t  MPI_Recv(&CONSTELLATION->spacecraft[ii][0].OE.w, 1, MPI_DOUBLE, which_iproc_is_running_main_sc[ii], 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n\t  MPI_Recv(&CONSTELLATION->spacecraft[ii][0].OE.long_an, 1, MPI_DOUBLE, which_iproc_is_running_main_sc[ii], 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n\t  MPI_Recv(&CONSTELLATION->spacecraft[ii][0].OE.f, 1, MPI_DOUBLE, which_iproc_is_running_main_sc[ii], 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n\n\n\t  //\tprintf(\"iProc %d receives from iProc %d for ii = %d\\n\", iProc, which_iproc_is_running_main_sc[ii], ii);\n\t}\n\n\tif (eee > 0){ // here eee > 0 so we are initializing et, r_i2cg_INRTL, v_i2cg_INRTL, OE, number_of_collisions for the sc from an ensemble\n\t  /*       \tif (nProcs > 1){ */\n\t  /* \t  if ( iProc > 0){ */\n\t  /* \t    if (eee == start_ensemble + iProc * OPTIONS->nb_ensemble_min_per_proc){ // only receives this one time */\n\t  /*       MPI_Recv(&CONSTELLATION->spacecraft[ii][0].OE.sma, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); */\n\t  /*       MPI_Recv(&CONSTELLATION->spacecraft[ii][0].OE.eccentricity, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); */\n\t  /*       MPI_Recv(&CONSTELLATION->spacecraft[ii][0].OE.inclination, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); */\n\t  /*       MPI_Recv(&CONSTELLATION->spacecraft[ii][0].OE.w, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); */\n\t  /*       MPI_Recv(&CONSTELLATION->spacecraft[ii][0].OE.long_an, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); */\n\t  /*       MPI_Recv(&CONSTELLATION->spacecraft[ii][0].OE.f, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); */\n\t  /* \t    } */\n\t  /* \t  } */\n\t  /*       \t} */\n\t  if (iDebugLevel >= 1){\n\t    if (iProc == 0) printf(\"-- (initialize_constellation) Initializing et, r_i2cg_INRTL, v_i2cg_INRTL for ensemble spacecraft.\\n\");\n\t  }\n\n\t  if (strcmp( OPTIONS->type_orbit_initialisation, \"collision_vcm\" ) == 0 ){\n\t      CONSTELLATION->spacecraft[ii][eee].et_sc_initial = OPTIONS->et_vcm[ii]; // the eoch time of the two VCMs are different\n\t  CONSTELLATION->spacecraft[ii][eee].et = OPTIONS->et_vcm[ii];\n\t  }\n\t  else{\n\t    CONSTELLATION->spacecraft[ii][eee].et_sc_initial = et;\n\t  CONSTELLATION->spacecraft[ii][eee].et = CONSTELLATION->et;\n\t  }\n\t  // COLLISION\n\t  CONSTELLATION->spacecraft[ii][eee].number_of_collisions = 0;\n\t  // end of COLLISION\n\n\t  /*****************************************************************************************************************************/\n\t  /********************************************************* ENSEMBLES ON COE **************************************************/\n\t  /*****************************************************************************************************************************/\n\t  if (( OPTIONS->nb_ensembles > 0 ) && ( strcmp(OPTIONS->type_orbit_initialisation, \"oe\" ) == 0 )){ // initialize COE if we run ensembles on the COE\n\n\t    // Initiate the COE to each ensemble as the same COE as for the spacecraft\n\t    CONSTELLATION->spacecraft[ii][eee].OE.sma            = ( PARAMS->EARTH.radius + OPTIONS->apogee_alt[ii] ) / ( 1 + OPTIONS->eccentricity[ii] ); // semi-major axis (CBV)\n\n\t    CONSTELLATION->spacecraft[ii][eee].OE.inclination    = OPTIONS->inclination[ii] * DEG2RAD;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.w              = OPTIONS->w[ii] * DEG2RAD;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.long_an        = OPTIONS->long_an[ii] * DEG2RAD;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.f              = OPTIONS->f[ii] * DEG2RAD;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.eccentricity   = OPTIONS->eccentricity[ii];\n\t    // For each COE to ensemble, replace it by a random normal number\n\t    // eccentricity\n\t    if ( OPTIONS->coe_to_ensemble[ii][0] == 1 ) {\n\t      CONSTELLATION->spacecraft[ii][eee].OE.eccentricity = randn( OPTIONS->eccentricity[ii], eccentricity_sigma );\n\t      // printf(\"eccentricity = %f\\n\", CONSTELLATION->spacecraft[ii][eee].OE.eccentricity);\n\t    }\n\t    // true anomaly\n\t    if ( OPTIONS->coe_to_ensemble[ii][1] == 1 ) {\n\t      CONSTELLATION->spacecraft[ii][eee].OE.f = randn( OPTIONS->f[ii] * DEG2RAD, f_sigma );\n\t      // printf(\"true ano = %f\\n\", CONSTELLATION->spacecraft[ii][eee].OE.f * RAD2DEG);\n\t    }\n\t    // RAAN\n\t    if ( OPTIONS->coe_to_ensemble[ii][2] == 1 ){\n\t      CONSTELLATION->spacecraft[ii][eee].OE.long_an = randn( OPTIONS->long_an[ii] * DEG2RAD, long_an_sigma );\n\t      // printf(\"RANN = %f\\n\", CONSTELLATION->spacecraft[ii][eee].OE.long_an * RAD2DEG);\n\t    }\n\t    // argument of perigee\n\t    if ( OPTIONS->coe_to_ensemble[ii][3] == 1 ) {\n\t      CONSTELLATION->spacecraft[ii][eee].OE.w = randn( OPTIONS->w[ii] * DEG2RAD, w_sigma );\n\t      // printf(\"argument of perigee = %f\\n\", CONSTELLATION->spacecraft[ii][eee].OE.w * RAD2DEG);\n\t    }\n\t    // inclination\n\t    if ( OPTIONS->coe_to_ensemble[ii][4] == 1 ) {\n\t      CONSTELLATION->spacecraft[ii][eee].OE.inclination = randn( OPTIONS->inclination[ii] * DEG2RAD, inclination_sigma );\n\t      //\t  printf(\"inclination = %f\\n\",CONSTELLATION->spacecraft[ii][eee].OE.inclination * RAD2DEG);\n\t    }\n\t    // semi-major axis\n\t    if ( OPTIONS->coe_to_ensemble[ii][5] == 1 ) {\n\t      CONSTELLATION->spacecraft[ii][eee].OE.sma = randn( ( PARAMS->EARTH.radius + OPTIONS->apogee_alt[ii] ) / ( 1 + OPTIONS->eccentricity[ii] ), sma_sigma );\n\t      //\t  printf(\"sma = %f\\n\", CONSTELLATION->spacecraft[ii][eee].OE.sma );\n\t    }\n\t  }\n\n\t  else if (( OPTIONS->nb_ensembles > 0 ) && ( strcmp(OPTIONS->type_orbit_initialisation, \"state_eci\" ) == 0 )){ // initialize state eci and OE if we run ensembles on state eci\n\n\n\t    CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[0] = randn( OPTIONS->x_eci[ii], OPTIONS->x_eci_sigma[ii] );\n\t    CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[1] = randn( OPTIONS->y_eci[ii], OPTIONS->y_eci_sigma[ii] );\n\t    CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[2] = randn( OPTIONS->z_eci[ii], OPTIONS->z_eci_sigma[ii] );\n\n\t    CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[0] = randn( OPTIONS->vx_eci[ii], OPTIONS->vx_eci_sigma[ii] );\n\t    CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[1] = randn( OPTIONS->vy_eci[ii], OPTIONS->vy_eci_sigma[ii] );\n\t    CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[2] = randn( OPTIONS->vz_eci[ii], OPTIONS->vz_eci_sigma[ii] );\n\n\t    // Orbital elements\n\t    cart2kep( &CONSTELLATION->spacecraft[ii][eee].OE, CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL, CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL, CONSTELLATION->spacecraft[ii][eee].et,  PARAMS->EARTH.GRAVITY.mu);\n\n\t    CONSTELLATION->spacecraft[ii][eee].OE.initial_an_to_sc = CONSTELLATION->spacecraft[ii][eee].OE.an_to_sc;\n\t   \n\t    CONSTELLATION->spacecraft[ii][eee].OE.w_ave_temp = CONSTELLATION->spacecraft[ii][eee].OE.w;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.w_ave = 9999.999999/RAD2DEG;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.sma_ave_temp = CONSTELLATION->spacecraft[ii][eee].OE.sma;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.sma_ave = 9999.999999;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.ecc_ave_temp = CONSTELLATION->spacecraft[ii][eee].OE.eccentricity;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.ecc_ave = 9999.999999;\n\n\t    CONSTELLATION->spacecraft[ii][eee].OE.ave_increm = 1;\n\t    CONSTELLATION->spacecraft[ii][eee].et_last_orbit = CONSTELLATION->spacecraft[ii][eee].et;\n\t    CONSTELLATION->spacecraft[ii][eee].orbit_number = 0;\n\n\n\t    radius_perigee = CONSTELLATION->spacecraft[ii][eee].OE.sma * ( 1 - CONSTELLATION->spacecraft[ii][eee].OE.eccentricity  );\n\t    if (radius_perigee < PARAMS->EARTH.radius){\n\t      printf(\"***! The orbit of satellite %d intersects the Earth (altitude of perigee = %f km). The program will stop. !***\\n\",ii, radius_perigee-PARAMS->EARTH.radius);\n\t      MPI_Finalize();\n\t      exit(0);\n\t    }\n\n\t  }\n\n\t  else if (( OPTIONS->nb_ensembles > 0 ) && (( strcmp(OPTIONS->type_orbit_initialisation, \"collision\" ) == 0 ) || ( strcmp(OPTIONS->type_orbit_initialisation, \"collision_vcm\" ) == 0 ) )){ // initialize state eci and OE if we run ensembles on state eci from a collision input file\n\t    if ( strcmp(OPTIONS->type_orbit_initialisation, \"collision_vcm\" ) == 0 ){\n\t    // GOOD REFERENCE: http://www.prepacom.net/HEC2/math/cours/Changement%20de%20bases.pdf\n\t    // generate random uncertainties from teh eigenvalues. These uncertainties corresponds to the the basis of the principal axes of the ellipsoid\n\n\t    /* // !!!!!!! DELETE BLOCK BELOW AND UNCOMMENT THE ONE BELOW IT */\n\t    /* struct timeval t1; */\n\t    /* gettimeofday(&t1, NULL); */\n\t    /* seed = t1.tv_usec * t1.tv_sec;// time (NULL) + iProc; //\\* getpid(); */\n\t    /* gsl_rng_set (r_gaussian_generator, seed);                  // set seed */\n\t    /* collision_equinoctial_sigma_in_diag_basis[0] = gsl_ran_gaussian(r_gaussian_generator, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][0]  ) ); */\n\t    /* collision_equinoctial_sigma_in_diag_basis[1] = gsl_ran_gaussian(r_gaussian_generator, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][1]  ) ); */\n\t    /* collision_equinoctial_sigma_in_diag_basis[2] = gsl_ran_gaussian(r_gaussian_generator, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][2]  ) ); */\n\t    /* collision_equinoctial_sigma_in_diag_basis[3] = gsl_ran_gaussian(r_gaussian_generator, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][3]  ) ); */\n\t    /* collision_equinoctial_sigma_in_diag_basis[4] = gsl_ran_gaussian(r_gaussian_generator, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][4]  ) ); */\n\t    /* collision_equinoctial_sigma_in_diag_basis[5] = gsl_ran_gaussian(r_gaussian_generator, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][5]  ) ); */\n\n\t    collision_equinoctial_sigma_in_diag_basis[0] = randn( 0, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][0]  ) );\n\t    collision_equinoctial_sigma_in_diag_basis[1] = randn( 0, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][1]  ) );\n\t    collision_equinoctial_sigma_in_diag_basis[2] = randn( 0, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][2]  ) );\n\t    collision_equinoctial_sigma_in_diag_basis[3] = randn( 0, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][3]  ) );\n\t    collision_equinoctial_sigma_in_diag_basis[4] = randn( 0, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][4]  ) );\n\t    collision_equinoctial_sigma_in_diag_basis[5] = randn( 0, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][5]  ) );\n\t    /* collision_equinoctial_sigma_in_diag_basis[6] = randn( 0, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][6]  ) ); */\n\t    /* collision_equinoctial_sigma_in_diag_basis[7] = randn( 0, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][7]  ) ); */\n\t    /* collision_equinoctial_sigma_in_diag_basis[8] = randn( 0, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][8]  ) ); */\n\n\t    \n\t    // convert thes e unertainties rfom the ellipsoid basis to ECI p\n\t    m_x_v6( collision_equinoctial_sigma_in_equinoctial_basis, OPTIONS->rotation_matrix_for_diagonalization[ii], collision_equinoctial_sigma_in_diag_basis ); /// !!!!! maybe invert of rotation_matrix_for_diagonalization?\n\n\n\n/* \t    //\t  printf(\"\\n\"); */\n/* \t    for (ccc = 0; ccc < 6; ccc++){ */\n/* \t      collision_equinoctial_sigma_in_equinoctial_basis[ccc] = collision_equinoctial_sigma_in_equinoctial_basis[ccc] / 1000.; // / 1000. to convert the eigenvalues from m to km (or from m/s to km/s) */\n/* \t      //\t    printf(\"%15.10e %15.10e %d %d %d\\n\", collision_equinoctial_sigma_in_equinoctial_basis[ccc], OPTIONS->eigenvalue_covariance_matrix[ii][ccc] / 1000. ,eee, ccc, ii); */\n/* \t    } */\n\n\n\t    double af, ag, lequin, nequin, chi, psi;\n\t    double af_mean, ag_mean, lequin_mean, nequin_mean, chi_mean, psi_mean;\n\t    // calculate the mean equinotication elemnts (ie the eq elts of the mean psoiton and velcoity)\n\t    double mu = 398600.4418; // km^3/s^2 (ideally, should read from propagator.c -> load_params but the call to load_params is later)\n\t    double fr;\n\t    // fr is 1 for prograde orbits, -1 for retrograde orbits. !!!! this is a convention, but there are others that assume fr to be 1 all the time. make sure that the VCM was generated using the same convention\n\t    ORBITAL_ELEMENTS_T oe_temp;\n\t    double rvec[3], vvec[3];\n\t    rvec[0] = OPTIONS->x_eci[ii]; rvec[1] = OPTIONS->y_eci[ii]; rvec[2] = OPTIONS->z_eci[ii];\n\t    vvec[0] = OPTIONS->vx_eci[ii]; vvec[1] = OPTIONS->vy_eci[ii]; vvec[2] = OPTIONS->vz_eci[ii];\n\n\t    cart2kep(&oe_temp, rvec, vvec, OPTIONS->et_vcm[ii] , mu);\n\n\n\t    if (oe_temp.inclination <= M_PI/2.){\n\t      fr = 1;\n\t    }\n\t    else{\n\t      fr = -1;\n\t    }\n\n\t    cart_to_equin( &af_mean, &ag_mean, &lequin_mean, &nequin_mean, &chi_mean, &psi_mean,  mu,  fr, rvec, vvec); // r and v in km km/s\n\n\t    af = af_mean + collision_equinoctial_sigma_in_equinoctial_basis[0];\n\t    ag = ag_mean + collision_equinoctial_sigma_in_equinoctial_basis[1];\n\t    lequin = lequin_mean + collision_equinoctial_sigma_in_equinoctial_basis[2];\n\t    nequin = nequin_mean + collision_equinoctial_sigma_in_equinoctial_basis[3] * nequin_mean; // elemts of the covaraicen amtrix in the VCM were adimentionless, ie divied by their mean value. so need to multiply here\n\t    chi = chi_mean + collision_equinoctial_sigma_in_equinoctial_basis[4];\n\t    psi = psi_mean + collision_equinoctial_sigma_in_equinoctial_basis[5];\n\n\t    // bc and srp for the main sc will be calcucalted later\n\t    CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.bc_vcm = OPTIONS->bc_cdm[ii] +  randn( 0, (OPTIONS->bc_cdm_std[ii]));\n\t      //OPTIONS->bc_vcm[ii] +  randn( 0, sqrt(OPTIONS->covariance_matrix_equinoctial[ii][6][6])) *  OPTIONS->bc_vcm[ii];  // elemts of the covaraicen amtrix in the VCM were adimentionless, ie divied by their mean value. so need to multiply here\n\t    CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.srp_vcm = OPTIONS->srp_cdm[ii] +  randn( 0, (OPTIONS->srp_cdm_std[ii]));\n\n\t      //OPTIONS->srp_vcm[ii] + randn( 0, sqrt(OPTIONS->covariance_matrix_equinoctial[ii][8][8])) *  OPTIONS->srp_vcm[ii];  // elemts of the covaraicen amtrix in the VCM were adimentionless, ie divied by their mean value. so need to multiply here ([7] is for bdot)\n\t    CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.bc_vcm = CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.bc_vcm  / 1000. / 1000.; // OPTIONS->bc_vcm in m2/kg. convert in km2/kg \n\t    CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.srp_vcm = CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.srp_vcm  / 1000. / 1000.; // OPTIONS->srp_vcm in m2/kg. convert in km2/kg \n\t  \n\n\t    double rvec_pert[3], vvec_pert[3];\n\t    equin_to_cart(rvec_pert, vvec_pert, af, ag, lequin, nequin, chi, psi, mu, fr);\n\n\t    CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[0] = rvec_pert[0];\n\t    CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[1] = rvec_pert[1];\n\t    CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[2] = rvec_pert[2];\n\n\t    CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[0] = vvec_pert[0];\n\t    CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[1] = vvec_pert[1];\n\t    CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[2] = vvec_pert[2];\n\n/* \t    v_print(CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL, \"r_pert\"); */\n/* \t    v_print(rvec, \"r_mean\"); */\n\t    double dr_pert[3], dr_pert_lvlh[3];\n\t    double dv_pert[3], dv_pert_lvlh[3];\n\t    v_sub(dr_pert, CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL, rvec);\n\t    v_sub(dv_pert, CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL, vvec);\n      double T_inrtl_2_lvlh_pert[3][3];\n      compute_T_inrtl_2_lvlh(T_inrtl_2_lvlh_pert, rvec, vvec);\n      m_x_v(dr_pert_lvlh, T_inrtl_2_lvlh_pert, dr_pert);\n        m_x_v(dv_pert_lvlh, T_inrtl_2_lvlh_pert, dv_pert);\n/*     v_print(dr_pert_lvlh, \"dr_lvlh\"); */\n/*     v_print(dv_pert_lvlh, \"dv_lvlh\"); */\n    r_alongtrack_all[ii][eee] = dr_pert_lvlh[0]; r_crosstrack_all[ii][eee] = dr_pert_lvlh[1]; r_radial_all[ii][eee] = dr_pert_lvlh[2];\n        v_alongtrack_all[ii][eee] = dv_pert_lvlh[0]; v_crosstrack_all[ii][eee] = dv_pert_lvlh[1]; v_radial_all[ii][eee] = dv_pert_lvlh[2];\n\tbc_pert_all[ii][eee] = CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.bc_vcm;\n\tsrp_pert_all[ii][eee] = CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.srp_vcm;\n\t//\tbc_pert_all[ii][eee] = \n\t    /* if ( ( ii == 0 )  && ( eee == start_ensemble + iProc * OPTIONS->nb_ensemble_min_per_proc ) ){  */\n\t    /*   printf(\"delta_vx_eci: %.10e - delta_vx_diag: %.10e - eee: %d - iProc: %d - vxsigma: %e - total vx_eci: %.10e\\n\", collision_equinoctial_sigma_in_equinoctial_basis[3], collision_equinoctial_sigma_in_diag_basis[3]/1000., eee, iProc, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][3] )/1000., CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[0] ); */\n\t    /*   //\t    m_print6(OPTIONS->inverse_rotation_matrix_for_diagonalization[ii], \"OPTIONS->inverse_rotation_matrix_for_diagonalization[ii]\"); */\n\t    /*   } */\n\n\t    // This will be used to save position of sc in the time span of the TCA if collisions assessment is on\n\t    CONSTELLATION->spacecraft[ii][eee].ispan = 0;\n\n\t  \n\t  \n\t    // Orbital elements\n\t    cart2kep( &CONSTELLATION->spacecraft[ii][eee].OE, CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL, CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL, CONSTELLATION->spacecraft[ii][eee].et,  PARAMS->EARTH.GRAVITY.mu);\n\t    CONSTELLATION->spacecraft[ii][eee].OE.initial_an_to_sc = CONSTELLATION->spacecraft[ii][eee].OE.an_to_sc;\n\t    \n\t    CONSTELLATION->spacecraft[ii][eee].OE.w_ave_temp = CONSTELLATION->spacecraft[ii][eee].OE.w;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.w_ave = 9999.999999/RAD2DEG;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.sma_ave_temp = CONSTELLATION->spacecraft[ii][eee].OE.sma;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.sma_ave = 9999.999999;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.ecc_ave_temp = CONSTELLATION->spacecraft[ii][eee].OE.eccentricity;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.ecc_ave = 9999.999999;\n\n\t    CONSTELLATION->spacecraft[ii][eee].OE.ave_increm = 1;\n\t    CONSTELLATION->spacecraft[ii][eee].et_last_orbit = CONSTELLATION->spacecraft[ii][eee].et;\n\t    CONSTELLATION->spacecraft[ii][eee].orbit_number = 0;\n\n\n\t    radius_perigee = CONSTELLATION->spacecraft[ii][eee].OE.sma * ( 1 - CONSTELLATION->spacecraft[ii][eee].OE.eccentricity  );\n\t    if (radius_perigee < PARAMS->EARTH.radius){\n\t      printf(\"***! The orbit of satellite %d intersects the Earth (altitude of perigee = %f km). The program will stop. !***\\n\",ii, radius_perigee-PARAMS->EARTH.radius);\n\t      MPI_Finalize();\n\t      exit(0);\n\t    }\n\t  }\n\t    else if ( strcmp(OPTIONS->type_orbit_initialisation, \"collision\" ) == 0 ){\n\t    // GOOD REFERENCE: http://www.prepacom.net/HEC2/math/cours/Changement%20de%20bases.pdf\n\t    // generate random uncertainties from teh eigenvalues. These uncertainties corresponds to the the basis of the principal axes of the ellipsoid\n\n\t    /* // !!!!!!! DELETE BLOCK BELOW AND UNCOMMENT THE ONE BELOW IT */\n\t    /* struct timeval t1; */\n\t    /* gettimeofday(&t1, NULL); */\n\t    /* seed = t1.tv_usec * t1.tv_sec;// time (NULL) + iProc; //\\* getpid(); */\n\t    /* gsl_rng_set (r_gaussian_generator, seed);                  // set seed */\n\t    /* collision_eci_sigma_in_diag_basis[0] = gsl_ran_gaussian(r_gaussian_generator, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][0]  ) ); */\n\t    /* collision_eci_sigma_in_diag_basis[1] = gsl_ran_gaussian(r_gaussian_generator, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][1]  ) ); */\n\t    /* collision_eci_sigma_in_diag_basis[2] = gsl_ran_gaussian(r_gaussian_generator, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][2]  ) ); */\n\t    /* collision_eci_sigma_in_diag_basis[3] = gsl_ran_gaussian(r_gaussian_generator, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][3]  ) ); */\n\t    /* collision_eci_sigma_in_diag_basis[4] = gsl_ran_gaussian(r_gaussian_generator, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][4]  ) ); */\n\t    /* collision_eci_sigma_in_diag_basis[5] = gsl_ran_gaussian(r_gaussian_generator, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][5]  ) ); */\n\n\t    collision_eci_sigma_in_diag_basis[0] = randn( 0, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][0]  ) );\n\t    collision_eci_sigma_in_diag_basis[1] = randn( 0, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][1]  ) );\n\t    collision_eci_sigma_in_diag_basis[2] = randn( 0, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][2]  ) );\n\t    collision_eci_sigma_in_diag_basis[3] = randn( 0, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][3]  ) );\n\t    collision_eci_sigma_in_diag_basis[4] = randn( 0, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][4]  ) );\n\t    collision_eci_sigma_in_diag_basis[5] = randn( 0, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][5]  ) );\n\n\n\n\t    // convert thes e unertainties rfom the ellipsoid basis to ECI p\n\t    m_x_v6( collision_eci_sigma_in_eci_basis, OPTIONS->rotation_matrix_for_diagonalization[ii], collision_eci_sigma_in_diag_basis );\n\n\n\n\t    //\t  printf(\"\\n\");\n\t    for (ccc = 0; ccc < 6; ccc++){\n\t      collision_eci_sigma_in_eci_basis[ccc] = collision_eci_sigma_in_eci_basis[ccc] / 1000.; // / 1000. to convert the eigenvalues from m to km (or from m/s to km/s)\n\t      //\t    printf(\"%15.10e %15.10e %d %d %d\\n\", collision_eci_sigma_in_eci_basis[ccc], OPTIONS->eigenvalue_covariance_matrix[ii][ccc] / 1000. ,eee, ccc, ii);\n\t    }\n\n\n\t    CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[0] = OPTIONS->x_eci[ii] + collision_eci_sigma_in_eci_basis[0];\n\t    CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[1] = OPTIONS->y_eci[ii] + collision_eci_sigma_in_eci_basis[1];\n\t    CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[2] = OPTIONS->z_eci[ii] + collision_eci_sigma_in_eci_basis[2]; \n\n\t    CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[0] = OPTIONS->vx_eci[ii] + collision_eci_sigma_in_eci_basis[3];\n\t    CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[1] = OPTIONS->vy_eci[ii] + collision_eci_sigma_in_eci_basis[4];\n\t    CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[2] = OPTIONS->vz_eci[ii] + collision_eci_sigma_in_eci_basis[5];\n\n\t    /* if ( ( ii == 0 )  && ( eee == start_ensemble + iProc * OPTIONS->nb_ensemble_min_per_proc ) ){  */\n\t    /*   printf(\"delta_vx_eci: %.10e - delta_vx_diag: %.10e - eee: %d - iProc: %d - vxsigma: %e - total vx_eci: %.10e\\n\", collision_eci_sigma_in_eci_basis[3], collision_eci_sigma_in_diag_basis[3]/1000., eee, iProc, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][3] )/1000., CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[0] ); */\n\t    /*   //\t    m_print6(OPTIONS->inverse_rotation_matrix_for_diagonalization[ii], \"OPTIONS->inverse_rotation_matrix_for_diagonalization[ii]\"); */\n\t    /*   } */\n\n\t    // This will be used to save position of sc in the time span of the TCA if collisions assessment is on\n\t    CONSTELLATION->spacecraft[ii][eee].ispan = 0;\n\n\t  \n\t  \n\t    // Orbital elements\n\t    cart2kep( &CONSTELLATION->spacecraft[ii][eee].OE, CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL, CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL, CONSTELLATION->spacecraft[ii][eee].et,  PARAMS->EARTH.GRAVITY.mu);\n\n\n\t    radius_perigee = CONSTELLATION->spacecraft[ii][eee].OE.sma * ( 1 - CONSTELLATION->spacecraft[ii][eee].OE.eccentricity  );\n\t    if (radius_perigee < PARAMS->EARTH.radius){\n\t      printf(\"***! The orbit of satellite %d intersects the Earth (altitude of perigee = %f km). The program will stop. !***\\n\",ii, radius_perigee-PARAMS->EARTH.radius);\n\t      MPI_Finalize();\n\t      exit(0);\n\t    }\n\n\t    }\n\t    \n\t  } // end of initialize state eci and OE if we run ensembles on state eci from a collision input file\n\n\t  else { // initialize COE if we do not run ensembles on the orbital elements or on state eci (including collision case)\n\n\t    CONSTELLATION->spacecraft[ii][eee].OE.sma            = CONSTELLATION->spacecraft[ii][0].OE.sma; // semi-major axis (CBV)\n\n\t    //    printf(\"sma = %f\\n\", CONSTELLATION->spacecraft[ii][0].OE.sma);\n\t    radius_perigee = CONSTELLATION->spacecraft[ii][eee].OE.sma * ( 1 - CONSTELLATION->spacecraft[ii][0].OE.eccentricity );\n\t    if (radius_perigee < PARAMS->EARTH.radius){\n\t      printf(\"***! The orbit of satellite %d intersects the Earth (altitude of perigee = %f km). The program will stop. !***\\n\",ii, radius_perigee-PARAMS->EARTH.radius);\n\t      MPI_Finalize();\n\t      exit(0);\n\t    }\n\t    CONSTELLATION->spacecraft[ii][eee].OE.inclination    = CONSTELLATION->spacecraft[ii][0].OE.inclination ;\n\n\t    CONSTELLATION->spacecraft[ii][eee].OE.w              = CONSTELLATION->spacecraft[ii][0].OE.w ;                                // argument of perigee (CBV)\n\t    CONSTELLATION->spacecraft[ii][eee].OE.long_an        = CONSTELLATION->spacecraft[ii][0].OE.long_an ;                          // RAAN (CBV)\n\t    CONSTELLATION->spacecraft[ii][eee].OE.f              = CONSTELLATION->spacecraft[ii][0].OE.f ;                                // true anomaly (CBV)\n\n\t    CONSTELLATION->spacecraft[ii][eee].OE.eccentricity   = CONSTELLATION->spacecraft[ii][0].OE.eccentricity;\n\n\t  } // end of initialize COE if we do not run ensembles on the orbital elements or on state eci (including collision case)\n\t  if ( ( OPTIONS->nb_ensembles <= 0 ) || ( ( strcmp(OPTIONS->type_orbit_initialisation, \"state_eci\" ) != 0 ) && ( strcmp(OPTIONS->type_orbit_initialisation, \"collision\" ) != 0 )  && ( strcmp(OPTIONS->type_orbit_initialisation, \"collision_vcm\" ) != 0 ) ) ){ // intialize eci r/v if we do not run ensembles on state eci or on collision\n\n\t    // Initialize the inertial state\n\t    kep2cart(   CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL,\n\t\t\tCONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL,\n\t\t\t&PARAMS->EARTH.GRAVITY.mu,\n\t\t\t&CONSTELLATION->spacecraft[ii][eee].OE); // Computes the ECI coordinates based on the Keplerian inputs (orbital elements and mu) (in propagator.c) (CBV)\n\t\n\t    // Right ascension\n\t    CONSTELLATION->spacecraft[ii][eee].OE.ra =  atan2(CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[1], CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[0]);\n\t    if ( CONSTELLATION->spacecraft[ii][eee].OE.ra < 0){\n\t      CONSTELLATION->spacecraft[ii][eee].OE.ra = 2*M_PI + CONSTELLATION->spacecraft[ii][eee].OE.ra ;\n\t    }\n\n\t    if (iDebugLevel >= 1){\n\t      if (iProc == 0) printf(\"-- (initialize_constellation) Done initializing et, r_i2cg_INRTL, v_i2cg_INRTL for ensemble spacecraft.\\n\");\n\t    }\n\t  }  // end of intialize eci r/v if we do not run ensembles on state eci or on collision\n\t} // end of the initialization of et, r_i2cg_INRTL, v_i2cg_INRTL, OE, number_of_collisions for the sc from an ensemble\n      \n\t/*************************************************************************************/\n\t/*************************************************************************************/\n\t/************* COE AND TLE INITIALIZE for main SC and for ensemble SC:\n- r_ecef2cg_ECEF, v_ecef2cg_ECEF\n- geodetic\n- filename, filenameecef, filenameout, filenamepower for main SC ONLY\n- name_sat\n- INTEGRATOR: dt, nb_surfaces, mass, solar_cell_efficiency, degree, order, include_drag/solar_pressure/earth_pressure/moon/sun, Ap, Ap_hist, f107, f107A, density, initialize_geo_with_bstar, sc_main_nb, sc_ensemble_nb\n\t**************/\n\t/*************************************************************************************/\n\t/*************************************************************************************/\n\tif (iDebugLevel >= 1){\n\t  if (iProc == 0) printf(\"-- (initialize_constellation) Initializing r_ecef2cg_ECEF, v_ecef2cg_ECEF, geodetic, output file names, name_sat, dt, nb_surfaces, mass, solar_cell_efficiency, degree, order, include_drag/solar_pressure/earth_pressure/moon/sun, Ap, Ap_hist, f107, f107A, density, initialize_geo_with_bstar for all spacecraft.\\n\");\n\t}\n\tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.sc_main_nb = ii;\n\tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.sc_ensemble_nb = eee;\n\n\tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.initialize_geo_with_bstar = OPTIONS->initialize_geo_with_bstar;\n\n\tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.coll_vcm = OPTIONS->coll_vcm;\n\n\t// !!!! REMOVE BLOCK BELOW\n\t//\tOPTIONS->bc_vcm_std[ii] = 0.23 * OPTIONS->bc_vcm[ii];\n\t//OPTIONS->srp_vcm_std[ii] = 0;//0.23 * OPTIONS->srp_vcm[ii];\n\t// !!!! END OF REMOVE BLOCK BELOW\n\tif (eee == 0){ // bc_vcm and srp_vcm were calculated prevously (eigen value block). here only the main sc\n\t  ///\t CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.bc_vcm = OPTIONS->bc_vcm[ii] / 1000. / 1000.; // OPTIONS->bc_vcm in m2/kg. convert in km2/kg\n\t  //\t  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.srp_vcm = OPTIONS->srp_vcm[ii] / 1000. / 1000.; // OPTIONS->srp_vcm in m2/kg. convert in km2/kg\n\t CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.bc_vcm = OPTIONS->bc_cdm[ii] / 1000. / 1000.; // OPTIONS->bc_vcm in m2/kg. convert in km2/kg\n\t\t  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.srp_vcm = OPTIONS->srp_cdm[ii] / 1000. / 1000.; // OPTIONS->srp_vcm in m2/kg. convert in km2/kg\n\t\t  CONSTELLATION->spacecraft[ii][eee].already_output_cd_ensemble = 0;\n\t\t  CONSTELLATION->spacecraft[ii][eee].already_output_srp_ensemble = 0;\n\n\t  //\t  printf(\"MAIN %d %d %e (%e) %e (%e)\\n\", ii, eee, CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.bc_vcm * 1e6, OPTIONS->bc_vcm_std[ii], CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.srp_vcm  * 1e6, OPTIONS->srp_vcm_std[ii]);\n\t}\n\t\n/* \telse{ */\n\n/* \tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.bc_vcm = fabs(randn(OPTIONS->bc_vcm[ii], OPTIONS->bc_vcm_std[ii]));  */\n\n/* \t//\t  printf(\"bc sc[%d][%d] %e %e\\n\", ii, eee, CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.bc_vcm, OPTIONS->bc_vcm[ii]); */\n/* \t  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.bc_vcm = CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.bc_vcm  / 1000. / 1000.; // OPTIONS->bc_vcm in m2/kg. convert in km2/kg  */\n\n/* \t  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.srp_vcm = fabs(randn(OPTIONS->srp_vcm[ii], OPTIONS->srp_vcm_std[ii]));  */\n/* \t  //printf(\"srp sc[%d][%d] %e %e\\n\", ii, eee, CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.srp_vcm, OPTIONS->srp_vcm[ii]); */\n/* \t  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.srp_vcm = CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.srp_vcm  / 1000. / 1000.; // OPTIONS->srp_vcm in m2/kg. convert in km2/kg  */\n/* \t} */\n\n\n\t  // uncomment block below to ingore uncertainties in Bc or SRP\n\t /* CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.bc_vcm = OPTIONS->bc_vcm[ii] / 1000. / 1000.; // OPTIONS->bc_vcm in m2/kg. convert in km2/kg  */\n\t\n\t /*  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.srp_vcm = OPTIONS->srp_vcm[ii] / 1000. / 1000.; // OPTIONS->srp_vcm in m2/kg. convert in km2/kg  */\n\t /*  // end of uncomment block below to ingore uncertainties in Bc or SRP */\n\n\tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.et_vcm = OPTIONS->et_vcm[ii];\n\n\n/* \t// Initialize the geodetic state- */\n\n/* \tif (iDebugLevel >= 2){ */\n/* \t  if (iProc == 0) printf(\"--- (initialize_constellation) Initializing geodetic for all spacecraft.\\n\"); */\n/* \t} */\n\n\n/* \teci2lla(CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL , CONSTELLATION->spacecraft[ii][eee].et, geodetic ); */\n\n\t\n/* \tCONSTELLATION->spacecraft[ii][eee].GEODETIC.altitude = geodetic[2]; */\n/* \tCONSTELLATION->spacecraft[ii][eee].GEODETIC.latitude = geodetic[0]; */\n/* \tCONSTELLATION->spacecraft[ii][eee].GEODETIC.longitude = geodetic[1];  */\n/* \tif (iDebugLevel >= 2){ */\n/* \t  if (iProc == 0) printf(\"--- (initialize_constellation) Done initializing geodetic for all spacecraft.\\n\"); */\n/* \t} */\n\n\t// Initialize the planet fixed state\t\t\n\tif (iDebugLevel >= 2){\n\t  if (iProc == 0) printf(\"--- (initialize_constellation) Initializing r_ecef2cg_ECEF and v_ecef2cg_ECEF for all spacecraft.\\n\");\n\t}\n\tif ( strcmp( OPTIONS->type_orbit_initialisation, \"state_ecef\" ) != 0 ){ // already initialized if state_ecef chosen by user\n/* \t  geodetic_to_geocentric(PARAMS->EARTH.flattening,             */\n/* \t\t\t\t CONSTELLATION->spacecraft[ii][eee].GEODETIC.altitude, */\n/* \t\t\t\t CONSTELLATION->spacecraft[ii][eee].GEODETIC.latitude, */\n/* \t\t\t\t CONSTELLATION->spacecraft[ii][eee].GEODETIC.longitude, */\n/* \t\t\t\t PARAMS->EARTH.radius,        */\n/* \t\t\t\t CONSTELLATION->spacecraft[ii][eee].r_ecef2cg_ECEF) ; */\n/*   v_print(CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL, \"ECI\"); */\n/*   v_print(CONSTELLATION->spacecraft[ii][eee].r_ecef2cg_ECEF, \"ECEF\"); */\n/*  printf(\"(%f, %f) # %f\\n\", CONSTELLATION->spacecraft[ii][eee].GEODETIC.latitude*RAD2DEG, CONSTELLATION->spacecraft[ii][eee].GEODETIC.longitude*RAD2DEG, CONSTELLATION->spacecraft[ii][eee].GEODETIC.altitude); */\n\n\t  estate[0] = CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[0];estate[1] = CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[1];estate[2] = CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[2];\n\t  estate[3] = CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[0];estate[4] = CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[1];estate[5] = CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[2];\n\t  sxform_c (  \"J2000\", PARAMS->EARTH.earth_fixed_frame,  CONSTELLATION->spacecraft[ii][eee].et,    xform  );\n\t  mxvg_c   (  xform,       estate,   6,  6, jstate );\n\t  CONSTELLATION->spacecraft[ii][eee].r_ecef2cg_ECEF[0] = jstate[0]; CONSTELLATION->spacecraft[ii][eee].r_ecef2cg_ECEF[1] = jstate[1]; CONSTELLATION->spacecraft[ii][eee].r_ecef2cg_ECEF[2] = jstate[2];\n\t  CONSTELLATION->spacecraft[ii][eee].v_ecef2cg_ECEF[0] = jstate[3]; CONSTELLATION->spacecraft[ii][eee].v_ecef2cg_ECEF[1] = jstate[4]; CONSTELLATION->spacecraft[ii][eee].v_ecef2cg_ECEF[2] = jstate[5];\n /*  v_print(CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL, \"ECI\"); */\n /*  v_print(CONSTELLATION->spacecraft[ii][eee].r_ecef2cg_ECEF, \"ECEF\"); */\n /*  v_print(CONSTELLATION->spacecraft[ii][eee].v_ecef2cg_ECEF, \"velocity ECEF\"); */\n /* printf(\"(%f, %f) # %f\\n\", CONSTELLATION->spacecraft[ii][eee].GEODETIC.latitude*RAD2DEG, CONSTELLATION->spacecraft[ii][eee].GEODETIC.longitude*RAD2DEG, CONSTELLATION->spacecraft[ii][eee].GEODETIC.altitude); */\n\n\n\t}\n\n\n/*  double T_J2000_to_ECEF[3][3]; */\n/*  printf(\"CONSTELLATION->spacecraft[ii][eee].et = %f\\n\",CONSTELLATION->spacecraft[ii][eee].et); */\n/* \tpxform_c( \"J2000\", PARAMS->EARTH.earth_fixed_frame, CONSTELLATION->spacecraft[ii][eee].et, T_J2000_to_ECEF); // Return the matrix (here T_J2000_to_ECEF) that transforms position vectors from one specified frame (here J2000) to another (here ITRF93) at a specified epoch  (in /Users/cbv/cspice/src/cspice/pxform_c.c) (CBV) */\n\n/* \t  \tm_x_v(CONSTELLATION->spacecraft[ii][eee].r_ecef2cg_ECEF, T_J2000_to_ECEF, CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL); // multiply a matrix by a vector (in prop_math.c). So here we convert ECI (J2000) to ECEF coordinates (CBV) */\n/* \tv_print(CONSTELLATION->spacecraft[ii][eee].r_ecef2cg_ECEF,\"uu\"); */\n\n\tif (iDebugLevel >= 2){\n\t  if (iProc == 0) printf(\"--- (initialize_constellation) Done initializing r_ecef2cg_ECEF and v_ecef2cg_ECEF for all spacecraft.\\n\");\n\t}\n\n\n\tgeocentric_to_geodetic(\n\t\t\t       CONSTELLATION->spacecraft[ii][eee].r_ecef2cg_ECEF,\n\t\t\t       &PARAMS->EARTH.radius,\n\t\t\t       &PARAMS->EARTH.flattening,\n\t\t\t       &CONSTELLATION->spacecraft[ii][eee].GEODETIC.altitude,\n\t\t\t       &CONSTELLATION->spacecraft[ii][eee].GEODETIC.latitude,\n\t\t\t       &CONSTELLATION->spacecraft[ii][eee].GEODETIC.longitude ); // Computes lat/long/altitude based on ECEF coordinates and planet fixed state (planetary semimajor axis, flattening parameter) (in propagator.c) (CBV)\n\n\n\n\t// !!!!!!!!!!!!!!! ERASE\n\t/*       double x[6]; */\n\t/* double lt; */\n\t/*     spkez_c(10, CONSTELLATION->spacecraft[ii][eee].et, \"J2000\", \"NONE\", 399, x, &lt); //   Return the state (position and velocity) of a target bodyrelative to an observing body, optionally corrected for light time (planetary aberration) and stellar aberration. */\n\t/*     double sun_norm[3]; */\n\t/*     double sun[3]; */\n\t/*     sun[0] = x[0]; sun[1] = x[1]; sun[2] = x[2]; */\n\t/*     v_norm(sun_norm, sun); */\n\t/*     v_scale(sun_norm,sun_norm,6.878137e+03); */\n\t/*     v_print(sun_norm,\"sun_norm\"); */\n\t/*     v_print(CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL,\"CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL\"); */\n\t/*     v_print(CONSTELLATION->spacecraft[ii][eee].r_ecef2cg_ECEF,\"CONSTELLATION->spacecraft[ii][eee].r_ecef2cg_ECEF\"); */\n\t/*     printf(\"lat = %f| lon = %f| alt = %f\\n\", CONSTELLATION->spacecraft[ii][eee].GEODETIC.latitude*RAD2DEG, CONSTELLATION->spacecraft[ii][eee].GEODETIC.longitude*RAD2DEG,CONSTELLATION->spacecraft[ii][eee].GEODETIC.altitude); */\n\t/*     v_print(sun,\"sun\"); */\n\t/*     exit(0); */\n\t// !!!!!!!!!!!!!!! END OF ERASE\n \n\t// !!!!!!!!!!!!!!!!!!!!!!!!!! THE BLOCK BELOW IS TO INITIALIZE SATELLLITE 2 WITH THE CORRECT SPACING WITH RESPECT TO SATELLITE 1. IT IS JUST FOR A TRY, AND SHOULD BE REMOVED AND IMPLEMENTED IN THE CODE ITSELF. SO IF IT'S STILL HERE AFTER JUNE 10TH, 2016 THEN REMOVE IT!\n\t/* \tif ( strcmp( OPTIONS->type_orbit_initialisation, \"oe\" ) == 0 ){ */\n\t/* if (ii > 0){ */\n\t/* \t    v_copy( CONSTELLATION->spacecraft[ii][eee].r_ecef2cg_ECEF, CONSTELLATION->spacecraft[0][eee].r_ecef2cg_ECEF); */\n\t/* \t    v_copy( CONSTELLATION->spacecraft[ii][eee].v_ecef2cg_ECEF, CONSTELLATION->spacecraft[0][eee].v_ecef2cg_ECEF); */\n\t/* \t    CONSTELLATION->spacecraft[ii][eee].GEODETIC.altitude = CONSTELLATION->spacecraft[0][eee].GEODETIC.altitude ; */\n\t/* \t    CONSTELLATION->spacecraft[ii][eee].GEODETIC.latitude = CONSTELLATION->spacecraft[0][eee].GEODETIC.latitude ; */\n\t/* \t    CONSTELLATION->spacecraft[ii][eee].GEODETIC.longitude = CONSTELLATION->spacecraft[0][eee].GEODETIC.longitude ; */\n\t/* } */\n\t/* \t} */\n\t// !!!!!!!!!!!!!!!!!!!!!!!!!! END OF THE BLOCK BELOW IS TO INITIALIZE SATELLLITE 2 WITH THE CORRECT SPACING WITH RESPECT TO SATELLITE 1. IT IS JUST FOR A TRY, AND SHOULD BE REMOVED AND IMPLEMENTED IN THE CODE ITSELF. SO IF IT'S STILL HERE AFTER JUNE 10TH, 2016 THEN REMOVE IT!\n\t// Output file for each spacecraft\n\tif (iDebugLevel >= 2){\n\t  if (iProc == 0) printf(\"--- (initialize_constellation) Initializing the output file names and name_sat.\\n\");\n\t}\n\n\tif (eee == 0){ // filenames are only for the main sc \n\t  // COLLISION\n\t  strcpy(CONSTELLATION->filename_collision, OPTIONS->dir_output_run_name);\n\t  strcat( CONSTELLATION->filename_collision, \"/\");\n\t  strcat( CONSTELLATION->filename_collision,OPTIONS->filename_collision);\n\t  // end of COLLISION\n\n\t  strcpy(CONSTELLATION->spacecraft[ii][0].filename, OPTIONS->dir_output_run_name_sat_name[ii]);\n\t  strcat(CONSTELLATION->spacecraft[ii][0].filename, \"/\");\n\t  strcat(CONSTELLATION->spacecraft[ii][0].filename, OPTIONS->filename_output[ii]);\n\n\t  if (( strcmp( OPTIONS->type_orbit_initialisation, \"tle\" ) == 0) || (strcmp(OPTIONS->type_orbit_initialisation, \"tle_sgp4\" ) == 0 )){\n\t    strcpy(CONSTELLATION->spacecraft[ii][0].filenametle, OPTIONS->dir_output_run_name_sat_name[ii]);\n\t    strcat(CONSTELLATION->spacecraft[ii][0].filenametle, \"/\");\n\t    strcat(CONSTELLATION->spacecraft[ii][0].filenametle, \"TLE_\");\n\t    strcat(CONSTELLATION->spacecraft[ii][0].filenametle, OPTIONS->filename_output[ii]);\n\t  }\n\n\t  // Now CONSTELLATION->spacecraft[ii][0].filenameecef is moved to generate_ephemerides because we want iProc 0 to know CONSTELLATION->spacecraft[ii][0].filenameecef even for the main sc ii that it does not run (this is because iProc 0 will gather all ECEF files at the end of the propagation)\n\t  /* \tstrcpy(CONSTELLATION->spacecraft[ii][0].filenameecef, OPTIONS->dir_output_run_name_sat_name[ii]); */\n\t  /* \tstrcat(CONSTELLATION->spacecraft[ii][0].filenameecef, \"/\"); */\n\t  /* \tstrcat(CONSTELLATION->spacecraft[ii][0].filenameecef, \"ECEF_\"); */\n\t  /* \tstrcat(CONSTELLATION->spacecraft[ii][0].filenameecef, OPTIONS->filename_output[ii]); */\n\n\t  strcpy(CONSTELLATION->spacecraft[ii][0].filenameout, OPTIONS->dir_output_run_name_sat_name[ii]);\n\t  strcat(CONSTELLATION->spacecraft[ii][0].filenameout, \"/\");\n\t  strcat(CONSTELLATION->spacecraft[ii][0].filenameout, \"LLA_\");\n\t  strcat(CONSTELLATION->spacecraft[ii][0].filenameout,OPTIONS->filename_output[ii]);\n\n\n\t  strcpy(CONSTELLATION->spacecraft[ii][0].filenamerho, OPTIONS->dir_output_run_name_sat_name[ii]);\n\t  strcat(CONSTELLATION->spacecraft[ii][0].filenamerho, \"/\");\n\t  strcat(CONSTELLATION->spacecraft[ii][0].filenamerho, \"density_\");\n\t  strcat(CONSTELLATION->spacecraft[ii][0].filenamerho,OPTIONS->filename_output[ii]);\n\n\t  strcpy(CONSTELLATION->spacecraft[ii][0].filenameatt, OPTIONS->dir_output_run_name_sat_name[ii]);\n\t  strcat(CONSTELLATION->spacecraft[ii][0].filenameatt, \"/\");\n\t  strcat(CONSTELLATION->spacecraft[ii][0].filenameatt, \"attitude_\");\n\t  strcat(CONSTELLATION->spacecraft[ii][0].filenameatt,OPTIONS->filename_output[ii]);\n\n\n\t  strcpy(CONSTELLATION->spacecraft[ii][0].filenamekalman, OPTIONS->dir_output_run_name_sat_name[ii]);\n\t  strcat(CONSTELLATION->spacecraft[ii][0].filenamekalman, \"/\");\n\t  strcat(CONSTELLATION->spacecraft[ii][0].filenamekalman, \"kalman_\");\n\t  strcat(CONSTELLATION->spacecraft[ii][0].filenamekalman,OPTIONS->filename_output[ii]);\n\n\n\t  strcpy(CONSTELLATION->spacecraft[ii][0].filenamekalman_meas, OPTIONS->dir_output_run_name_sat_name[ii]);\n\t  strcat(CONSTELLATION->spacecraft[ii][0].filenamekalman_meas, \"/\");\n\t  strcat(CONSTELLATION->spacecraft[ii][0].filenamekalman_meas, \"meas_converted_kalman_\");\n\t  strcat(CONSTELLATION->spacecraft[ii][0].filenamekalman_meas,OPTIONS->filename_output[ii]);\n\n\t  strcpy(CONSTELLATION->spacecraft[ii][0].filename_kalman_init, OPTIONS->filename_kalman_init);\n\n\t  strcpy(CONSTELLATION->spacecraft[ii][0].INTEGRATOR.filename_given_output, OPTIONS->dir_output_run_name_sat_name[ii]);\n\t  strcat(CONSTELLATION->spacecraft[ii][0].INTEGRATOR.filename_given_output, \"/\");\n\t  strcat(CONSTELLATION->spacecraft[ii][0].INTEGRATOR.filename_given_output, \"given_output_\");\n\t  strcat(CONSTELLATION->spacecraft[ii][0].INTEGRATOR.filename_given_output,OPTIONS->filename_output[ii]);\n\n\n\t  if (OPTIONS->nb_ground_stations > 0){\n\t    for ( iground = 0; iground < OPTIONS->nb_ground_stations; iground ++){\n\t      strcpy(CONSTELLATION->spacecraft[ii][0].filename_coverage_ground_station[iground], OPTIONS->dir_output_run_name_sat_name_coverage[ii]);\n\t      strcat(CONSTELLATION->spacecraft[ii][0].filename_coverage_ground_station[iground], \"/\");\n\t      strcat(CONSTELLATION->spacecraft[ii][0].filename_coverage_ground_station[iground], OPTIONS->name_ground_station[iground]);\n\t      strcat(CONSTELLATION->spacecraft[ii][0].filename_coverage_ground_station[iground], \"_by_\");\n\t      strcat(CONSTELLATION->spacecraft[ii][0].filename_coverage_ground_station[iground],OPTIONS->filename_output[ii]);\n\t    }\n\t  }\n\n\n\t  if (OPTIONS->solar_cell_efficiency != -1){\n\t    strcpy(CONSTELLATION->spacecraft[ii][0].filenamepower, OPTIONS->dir_output_run_name_sat_name[ii]);\n\t    strcat(CONSTELLATION->spacecraft[ii][0].filenamepower, \"/\");\n\t    strcat(CONSTELLATION->spacecraft[ii][0].filenamepower, \"power_\");\n\t    strcat(CONSTELLATION->spacecraft[ii][0].filenamepower,OPTIONS->filename_output[ii]);\n\n\t    strcpy(CONSTELLATION->spacecraft[ii][0].filenameeclipse, OPTIONS->dir_output_run_name_sat_name[ii]);\n\t    strcat(CONSTELLATION->spacecraft[ii][0].filenameeclipse, \"/\");\n\t    strcat(CONSTELLATION->spacecraft[ii][0].filenameeclipse, \"eclipse_\");\n\t    strcat(CONSTELLATION->spacecraft[ii][0].filenameeclipse,OPTIONS->filename_output[ii]);\n\n\t  }\n\n\n\t} // end of eee = 0\n\n\t//\t    if (eee == start_ensemble + iProc * OPTIONS->nb_ensemble_min_per_proc){ // only receives it one time \n\tif (eee == array_sc[start_ensemble[ii]]){ // if eee is the first sc run by iProc for this given main sc ii\n\t  if (write_attitude_file == 1){\n\t    strcpy(filename_attitude[ii], OPTIONS->dir_output_run_name_sat_name[ii]);\n\t    strcat(filename_attitude[ii], \"/\");\n\t    strcat(filename_attitude[ii], \"attitude_\");\n\t    strcat(filename_attitude[ii],OPTIONS->filename_output[ii]);\n\t    file_attitude[ii] = NULL;\n\t    file_attitude[ii] = fopen(filename_attitude[ii], \"w+\");\n\t    if (file_attitude[ii] == NULL){\n\t      printf(\"***! Could not open the output file for the attitude called %s. The program will stop. !***\\n\", filename_attitude[ii]); MPI_Finalize(); exit(0);\n\t    }\n\t    fprintf(file_attitude[ii], \"This file shows the attitude of each ensemble spacecraft of the main spacecraft %s. One block per ensemble spacecraft. First line is the pitch, roll, and yaw angular velocities, as well as the order of rotation (pitch, roll, yaw). Recall that this order is the same for all ensemble spacecraft. Following lines show time vs pitch, roll, yaw (rotation of the body reference system with respect to the LVLH reference system). All angles are given in degrees.\\n\", OPTIONS->name_sat[ii]);\n\t  \n\t  }\n\t}\n\n\t// Name of each satellites\n\tstrcpy(CONSTELLATION->spacecraft[ii][eee].name_sat, \"\");\n\tstrcpy(CONSTELLATION->spacecraft[ii][eee].name_sat, OPTIONS->name_sat[ii]);\n\tif (iDebugLevel >= 2){\n\t  if (iProc == 0) printf(\"--- (initialize_constellation) Done initializing the output file names and name_sat.\\n\");\n\t}\n\n        // Compute the Orbital period of the first state\n\tif ( ( ii  == 0 ) && ( eee == 0 ) ){ // !!!!!!!!!! FOR NOW WORKS ONLY IF TWO REFERENCE SATELLIES ONLY \n\t  period = pow( CONSTELLATION->spacecraft[ii][0].OE.sma, 3.0);\n\t  period = period / PARAMS->EARTH.GRAVITY.mu;\n\t  period = 2.0 * M_PI * sqrt( period );\n\t  CONSTELLATION->collision_time_span =  period / 10. ;    // the time span is half of the orbit of the first sc (considered to be the primary sc)\n\t  //            ptd(CONSTELLATION->collision_time_span , \"old\");\n\t  // Actually, we re-evaluate the time span so it is an EVEN multiple of OPTIONS->dt (the closest possible to period/2)\n\t  if ( fmod(CONSTELLATION->collision_time_span, OPTIONS->dt) == 0 ){\n\t    if ( fmod( CONSTELLATION->collision_time_span / OPTIONS->dt, 2 )  == 1  ){ // if time span is an odd multiple of dt then remove dt from it to make it even\n\t      CONSTELLATION->collision_time_span = CONSTELLATION->collision_time_span - OPTIONS->dt;\n\t    }\n\t  }\n\t  else{\n\t    m_time_span = (int)( CONSTELLATION->collision_time_span / OPTIONS->dt );\n\t    if ( fmod( m_time_span, 2 ) == 1 ){\n\t      m_time_span = m_time_span + 1;\n\t      CONSTELLATION->collision_time_span = m_time_span * OPTIONS->dt;\n\t    }\n\t    else{\n\t      CONSTELLATION->collision_time_span = m_time_span * OPTIONS->dt;\n\t    }  \n\t  }\n\t  CONSTELLATION->collision_time_span = CONSTELLATION->collision_time_span + 2 * OPTIONS->dt; // for the reason why we add 2 * OPTIONS->dt, see comment \"ABOUT THE TIME SPAN\" at the end of generate_ephemerides\n\t  /* ptd(CONSTELLATION->collision_time_span , \"new\"); */\n\t  /* exitall(); */\n\t  // end of actually, we re-evaluate the time span so it is an EVEN multiple of OPTIONS->dt (the closest possible to period/2)\n\t  if (nProcs > 1){\n\t    for (ccc = 1; ccc < nProcs; ccc++){ // main sc 0 is for sure run by iProc 0, not matter how many main sc/ensemble sc/iProc there are\n\t      MPI_Send(&CONSTELLATION->collision_time_span, 1, MPI_DOUBLE, ccc, 0, MPI_COMM_WORLD);\n\t    }\n\t  }\n\t}\n      \tif (nProcs > 1){\n\t  if ( iProc > 0){\n\t    if ((ii == 0) && (eee == array_sc[start_ensemble[ii]])){ // only receives it one time  (array_sc[start_ensemble[ii]] is the first sc run by this iProc. Since main sc 0 is never run by iProc > 0, array_sc[start_ensemble[ii]] corresponds to the first ensemble sc run by this iProc)\n\t      MPI_Recv(&CONSTELLATION->collision_time_span, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n\t    }\n\t  }\n\t}\n\n\tif (iDebugLevel >= 2){\n\t  if (iProc == 0) printf(\"--- (initialize_constellation) Initializing dt, nb_surfaces, mass, solar_cell_efficiency, degree, order, include_drag/solar_pressure/earth_pressure/moon/sun, Ap, Ap_hist, f107, f107A, density, initialize_geo_with_bstar for all spacecraft.\\n\");\n\t}\n\n\t// Integrator\n\tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.dt            = OPTIONS->dt;\n\tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.dt_pos_neg            = OPTIONS->dt_pos_neg;\n\tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.nb_surfaces   = OPTIONS->n_surfaces;   // Number of surfaces on the SC\n\tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.nb_surfaces_eff   = OPTIONS->n_surfaces_eff;   // Number of surfaces on the SC\n\tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.mass          = OPTIONS->mass;         // Mass of spacecraft\n\tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.solar_cell_efficiency = OPTIONS->solar_cell_efficiency; // Solar cell efficiency\n\tstrcpy( CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.opengl_filename_solar_power, OPTIONS->opengl_filename_solar_power ); // Solar cell efficiency\n\tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.opengl = OPTIONS->opengl;\n\tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.opengl_power = OPTIONS->opengl_power;\n\tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.degree        = OPTIONS->degree;       // Gravity degree\n\tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.order         = OPTIONS->order;        // Gravity order\n\tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.include_drag  = OPTIONS->include_drag; // include drag (CBV)\n\tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.thrust  = OPTIONS->thrust;\n\tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.include_solar_pressure  = OPTIONS->include_solar_pressure; // include drag (CBV)\n\t\tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.include_earth_pressure  = OPTIONS->include_earth_pressure; // include drag (CBV)\n\tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.include_sun   = OPTIONS->include_sun;  // include Sun perturbations (CBV)\n\tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.include_moon  = OPTIONS->include_moon; // include Moon perturbations (CBV)\n\tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.density_mod = OPTIONS->density_mod; // // the desnity given by msis is multiplied by density_mod + density_amp * sin(2*pi*t/T + density_phase*T) where T is the orbital period  \n\tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.density_mod_amp = OPTIONS->density_mod_amp; \n\tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.density_mod_phase = OPTIONS->density_mod_phase; \n\n\n\tif ( CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.include_drag == 1 ){ // if the user wants to use drag\n\t  strcpy(CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.format_density_driver, OPTIONS->format_density_driver);\n\n\t  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.density = malloc( OPTIONS->nb_time_steps * 2 * sizeof(double) );\n\n\t  if (  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.density == NULL ){\n\t    printf(\"***! Could not allow memory space for  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.density \\n. The program will stop. !***\\n\");\n\t    MPI_Finalize();\n\t    exit(0);\n\t  }\n\n\n\t  if ( ( strcmp(OPTIONS->format_density_driver, \"density_file\") != 0 ) && ( strcmp(OPTIONS->format_density_driver, \"gitm\") != 0 ) ){ // the user chooses f107 and Ap for the density\n\t    if ( strcmp(OPTIONS->format_density_driver, \"static\") == 0 ){ // if the user chooses a constant f107 and Ap for the density  \n\n\t      CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.Ap_static            = OPTIONS->Ap_static;           // magnetic index(daily)\n\t      for (hhh = 0; hhh < 7; hhh++){\n\t\tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.Ap_hist_static[hhh]            = OPTIONS->Ap_hist_static[hhh];           // magnetic index(historical)\n\t      }\n\t      CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.f107_static          = OPTIONS->f107_static;         // Daily average of F10.7 flux\n\t      CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.f107A_static         = OPTIONS->f107A_static;        // 81 day average of F10.7 flux\n\n\t    }\n\t    else{  // if the user chooses a time-varying f107 and Ap for the density  \n\n\n\t      CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.Ap = malloc( OPTIONS->nb_time_steps * 2 * sizeof(double) ); // \"* 2.0\" because of the Runge Kunta order 4 method\n\t      if (OPTIONS->use_ap_hist == 1){\n\t\tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.Ap_hist = malloc(  7 * sizeof(double *) ); // historical ap\n\n\t\tfor (hhh = 0; hhh < 7; hhh++){\n\t\t  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.Ap_hist[hhh] = malloc(OPTIONS->nb_time_steps * 2 * sizeof(double ));\n\t\t}\n\t      }\n\n\t      CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.f107 = malloc( OPTIONS->nb_time_steps * 2 * sizeof(double) );\n\t      CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.f107A = malloc( OPTIONS->nb_time_steps * 2 * sizeof(double) );\n\n\t      if (  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.Ap == NULL ){\n\t\tprintf(\"***! Could not allow memory space for  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.Ap \\n. The program will stop. !***\\n\");\n\t\tMPI_Finalize();\n\t\texit(0);\n\t      }\n\t      if (OPTIONS->use_ap_hist == 1){\n\t\tif (  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.Ap_hist == NULL ){\n\t\t  printf(\"***! Could not allow memory space for  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.Ap_hist \\n. The program will stop. !***\\n\");\n\t\t  MPI_Finalize();\n\t\t  exit(0);\n\t\t}\n\t      }\n\t      if (  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.f107 == NULL ){\n\t\tprintf(\"***! Could not allow memory space for  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.f107 \\n. The program will stop. !***\\n\");\n\t\tMPI_Finalize();\n\t\texit(0);\n\t      }\n\t      if (  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.f107A == NULL ){\n\t\tprintf(\"***! Could not allow memory space for  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.f107A \\n. The program will stop. !***\\n\");\n\t\tMPI_Finalize();\n\t\texit(0);\n\t      }\n\t      /* for (aaa = 0; aaa< OPTIONS->nb_time_steps * 2; aaa++){  // \"* 2.0\" because of the Runge Kunta order 4 method */\n\t      /*   if ( OPTIONS->et_interpo[aaa] <= et_final_epoch + 0.01 ) {  */\n\t      /* \tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.Ap[aaa]            = OPTIONS->Ap[aaa];           // magnetic index(daily) */\n\t      /* \tif (OPTIONS->use_ap_hist == 1){ */\n\t      /* \t  for (hhh = 0; hhh < 7; hhh++){ */\n\t      /* \t    CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.Ap_hist[hhh][aaa]            = OPTIONS->Ap_hist[hhh][aaa];           // magnetic index(historical) */\n\t      /* \t  } */\n\t      /* \t} */\n\n\t      /* \tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.f107[aaa]          = OPTIONS->f107[aaa];         // Daily average of F10.7 flux */\n\n\t      /*   } */\n\t      /* } */\n\t      if ((strcmp(OPTIONS->test_omniweb_or_external_file, \"swpc_mod\") == 0) && (OPTIONS->swpc_need_predictions)){\n\t\tCONSTELLATION->sum_sigma_for_f107_average[ii][eee] = 0;\n\t      }\n\n\t      if (OPTIONS->nb_ensembles_density) { // the user chose to run ensembles on the density using data from SWPC \n\t\tif (OPTIONS->swpc_need_predictions){ // if future predictions of F10.7 and Ap (not only past observations)\n\t\t  CONSTELLATION->sum_sigma_for_f107_average[ii][eee] = 0;\n\n\t\t  if (eee == 1 + iProc * OPTIONS->nb_ensemble_min_per_proc){ // allocate memory for arrays only once per iProc  \n\t\t    CONSTELLATION->ensemble_array_per_iproc_f107_at_given_time[iProc] = malloc( OPTIONS->nb_ensemble_min_per_proc * sizeof( double ) ); \n\t\t    if (CONSTELLATION->ensemble_array_per_iproc_f107_at_given_time[iProc] == NULL){\n\t\t      printf(\"***! (propagate_spacecraft)(compute_drag) (generate_ensemble_f107_ap) There is not enough memory for CONSTELLATION->ensemble_array_per_iproc_f107_at_given_time[iProc]. The program will stop. !***\\n\"); MPI_Finalize();exit(0);\n\t\t    }\n\t\t    CONSTELLATION->ensemble_array_per_iproc_f107_at_given_time_sorted[iProc] = malloc( OPTIONS->nb_ensemble_min_per_proc *  sizeof( double ) ); \n\t\t    if (CONSTELLATION->ensemble_array_per_iproc_f107_at_given_time_sorted[iProc] == NULL){\n\t\t      printf(\"***! (propagate_spacecraft)(compute_drag) (generate_ensemble_f107_ap) There is not enough memory for CONSTELLATION->ensemble_array_per_iproc_f107_at_given_time_sorted[iProc]. The program will stop. !***\\n\"); MPI_Finalize();exit(0);\n\t\t    }\n\t\t    CONSTELLATION->ensemble_array_per_iproc_ap_at_given_time[iProc] = malloc( OPTIONS->nb_ensemble_min_per_proc * sizeof( double ) ); \n\t\t    if (CONSTELLATION->ensemble_array_per_iproc_ap_at_given_time[iProc] == NULL){\n\t\t      printf(\"***! (propagate_spacecraft)(compute_drag) (generate_ensemble_ap_ap) There is not enough memory for CONSTELLATION->ensemble_array_per_iproc_ap_at_given_time[iProc]. The program will stop. !***\\n\"); MPI_Finalize();exit(0);\n\t\t    }\n\t\t    CONSTELLATION->ensemble_array_per_iproc_ap_at_given_time_sorted[iProc] = malloc( OPTIONS->nb_ensemble_min_per_proc *  sizeof( double ) ); \n\t\t    if (CONSTELLATION->ensemble_array_per_iproc_ap_at_given_time_sorted[iProc] == NULL){\n\t\t      printf(\"***! (propagate_spacecraft)(compute_drag) (generate_ensemble_ap_ap) There is not enough memory for CONSTELLATION->ensemble_array_per_iproc_ap_at_given_time_sorted[iProc]. The program will stop. !***\\n\"); MPI_Finalize();exit(0);\n\t\t    }\n\t\t  } // end of allocate memory for arrays only once per iProc  \n\t\t} // end of if future predictions of F10.7 and Ap (not only past observations)\n\t      } // end of the user chose to run ensembles on the density using data from SWPC\n\n\t      /* if ( (OPTIONS->nb_ensembles_density) && (OPTIONS->swpc_need_predictions) && ( et_initial_epoch >= OPTIONS->swpc_et_first_prediction ) ) {  */\n\t      /* \t    // if the user chose to run ensembles on the density using data from SWPC  */\n\t      /* \t  \t    // if future predictions of F10.7 and Ap (not only past observations) (past values (value before the current time at running) are perfectly known (result from observations, not predictions)) */\n\t      /* \t    // only overwrite predictions of ensembles (not observations). OPTIONS->et_interpo[aaa] corresponds to the first say of predictions */\n\t      /*   start_ensemble_bis = 1; */\n\t      /*   nb_index_in_81_days =  81. * 24 * 3600 / (OPTIONS->dt/2.) + 1 ; */\n\t      /* \t    if ( eee == start_ensemble_bis + iProc * OPTIONS->nb_ensemble_min_per_proc){ // initialize array only once per iProc */\n\t      /* \t    // // Generate nb_ensembles_density normal random values */\n\t      /* \t    for ( eee_bis = 0; eee_bis < OPTIONS->nb_ensemble_min_per_proc; eee_bis++){ */\n\t      /* \t      CONSTELLATION->ensemble_array_per_iproc_f107_at_given_time[iProc][eee_bis]   = randn( OPTIONS->f107[0], OPTIONS->sigma_f107[CONSTELLATION->aaa_sigma]); */\n\t      /* \t      CONSTELLATION->ensemble_array_per_iproc_ap_at_given_time[iProc][eee_bis]   = randn(  OPTIONS->Ap[0], OPTIONS->sigma_ap[CONSTELLATION->aaa_sigma]); */\n\n\t      /* \t      /\\* if (eee_bis == 0){ *\\/ */\n\t      /* \t      /\\* etprint(OPTIONS->et_interpo[aaa], \"time\"); *\\/ */\n\t      /* \t      /\\* printf(\"Ap[%d]: %f | sigma_ap[%d]: %f \\n\",aaa, OPTIONS->Ap[aaa],CONSTELLATION->aaa_sigma, OPTIONS->sigma_ap[CONSTELLATION->aaa_sigma]); *\\/ */\n\t      /* \t      /\\* } *\\/ */\n\t      /* \t    } */\n\n\t      /* \t    // // Order values in ascending order */\n\t      /* \t    sort_asc_order(CONSTELLATION->ensemble_array_per_iproc_f107_at_given_time_sorted[iProc],  CONSTELLATION->ensemble_array_per_iproc_f107_at_given_time[iProc], OPTIONS->nb_ensemble_min_per_proc); */\n\t      /* \t    sort_asc_order(CONSTELLATION->ensemble_array_per_iproc_ap_at_given_time_sorted[iProc],  CONSTELLATION->ensemble_array_per_iproc_ap_at_given_time[iProc], OPTIONS->nb_ensemble_min_per_proc); */\n\n\n\t\n\n\t      /* \t      // Initialization of swpc_et_first_prediction for the calculation of F10.7A for an ensemble */\n\t      /* \t\t  if ( et_initial_epoch > OPTIONS->swpc_et_first_prediction){ // if the propagation starts in the future. Otherwise, sum_sigma_for_f107_average = 0 for all ensemble sc */\n\n\t      /* \t\t    if (  CONSTELLATION->sum_sigma_for_f107_average[ CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_main_nb][ CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_ensemble_nb] == 0 )  {// for the first time that variable et gets bigger than swpc_et_first_prediction (0.01 for numerical reasons)\t\t     */\n\t      /* \t\t   // initialize sum_sigma_for_f107_average as the sum of all sigma on F10.7 from first prediction to inital epoch. There is no mathematical logic in here. The exact solution would be to sum all the deviations between f107_ensemble and f107_refce from first prediciton until intial epoch, and sum them up. This is KIND OF similar. The reason I don't do the correct approach is that I did not calculate f107_ensemble for times before initial epoch */\n\t      /* \t\t      for (aaa_a = 0; aaa_a < CONSTELLATION->aaa_sigma; aaa_a++){ */\n\n\t      /* \t\t      CONSTELLATION->sum_sigma_for_f107_average[ CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_main_nb][ CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_ensemble_nb] = CONSTELLATION->sum_sigma_for_f107_average[ CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_main_nb][ CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_ensemble_nb] + OPTIONS->sigma_f107[aaa_a];\t\t     */\n\t      /* \t\t      //\t\t      ptd( OPTIONS->sigma_f107[aaa_a], \"s\"); */\n\t      /* \t\t      } */\n\n\t      /* \t\t      //\t\t      printf(\"eee_bis: %d | index: %d | iProc: %d | sum: %f\\n\",  CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_ensemble_nb, index_in_driver_interpolated, iProc, CONSTELLATION->sum_sigma_for_f107_average[ CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_main_nb][ CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_ensemble_nb]);exit(0); */\n\t\t   \n\t      /* \t\t    } // end of for the first time that variable et gets bigger than swpc_et_first_prediction */\n\t      /* \t\t  }// end of if the propagation starts in the future   */\n\t      /* \t      // End of initialization of swpc_et_first_prediction for the calculation of F10.7A for an ensemble */\n\n\t      /* \t  } // initialize array only once per iProc */\n\t      /* \t    else if ( CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_ensemble_nb == 0){ // also need to calculate f107 and ap for reference sc (no perturbation so directly equal to the values in the prediction files) */\n\t      /* \t     CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.Ap[0]            = OPTIONS->Ap[0];           // magnetic index(daily) */\n\t      /* \t    if (OPTIONS->use_ap_hist == 1){ */\n\t      /* \t      for (hhh = 0; hhh < 7; hhh++){ */\n\t      /* \t\t CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.Ap_hist[hhh][0]            = OPTIONS->Ap_hist[hhh][0];           // magnetic index(historical) */\n\t      /* \t      } */\n\t      /* \t    } */\n\n\t      /* \t     CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.f107[0]          = OPTIONS->f107[0];         // Daily average of F10.7 flux */\n\t      /* \t      /\\* print_test(); *\\/ */\n\t      /* \t      /\\* printf(\" CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.f107[%d]: %f\\n\", 0,  CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.f107[0]); *\\/ */\n\n\t      /* \t     CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.f107A[0]         = OPTIONS->f107A[0];        // 81 day average of F10.7 flux */\n\n\n\t      /* \t    } // end of also need to calculate f107 and ap for reference sc (no perturbation so directly equal to the values in the prediction files) */\n\t      /* \t    if ( CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_ensemble_nb != 0) { // don't overwrite previously written values of f107 and Ap for reference sc */\n\t      /* \t     CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.Ap[0]            = CONSTELLATION->ensemble_array_per_iproc_ap_at_given_time_sorted[iProc][ CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_ensemble_nb-1-iProc*OPTIONS->nb_ensemble_min_per_proc]; */\n\t      /* \t     CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.f107[0]          = CONSTELLATION->ensemble_array_per_iproc_f107_at_given_time_sorted[iProc][ CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_ensemble_nb-1-iProc*OPTIONS->nb_ensemble_min_per_proc];  */\n\t\n\t      /* \t    CONSTELLATION->sum_sigma_for_f107_average[ CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_main_nb][ CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_ensemble_nb] = CONSTELLATION->sum_sigma_for_f107_average[ CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_main_nb][ CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_ensemble_nb] +  (  CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.f107[0]  - OPTIONS->f107[0] ); */\n\t      /* \t     CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.f107A[0]         = OPTIONS->f107A[0] + CONSTELLATION->sum_sigma_for_f107_average[ CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_main_nb][ CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_ensemble_nb] / nb_index_in_81_days; // derivation of F10.7A considering uncerainties in F10.7 */\n\t      /* \t    //\t    printf(\"eee_bis: %d | index: %d | iProc: %d | sum: %f | 81: %f | opeion %f\\n\",  CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_ensemble_nb, index_in_driver_interpolated, iProc, CONSTELLATION->sum_sigma_for_f107_average[ CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_main_nb][ CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_ensemble_nb], nb_index_in_81_days, OPTIONS->dt); */\n\t      /* \t    //\t    print_test(); */\n\t      /* \t  /\\* if (iProc == 0){ *\\/ */\n\t      /* \t  /\\*   //\t    if (( CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_ensemble_nb == start_ensemble_bis + iProc * OPTIONS->nb_ensemble_min_per_proc + 1)){ *\\/ */\n\t      /* \t  /\\*   if (index_in_driver_interpolated == 4){ *\\/ */\n\t      /* \t  /\\*     printf(\"eee_bis: %d | f107:  %f | index: %d | iProc: %d\\n\",  CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_ensemble_nb,  CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.f107[index_in_driver_interpolated], index_in_driver_interpolated, iProc); *\\/ */\n\t      /* \t  /\\* } *\\/ */\n\t      /* \t  /\\* } *\\/ */\n\t      /* \t    } // end of don't overwrite previously written values of f107 and Ap for reference sc */\n\t      /* \t  } // end of: */\n\t      /* \t    // if the user chose to run ensembles on the density using data from SWPC AND */\n\t      /* \t  \t    // if future predictions of F10.7 and Ap (not only past observations) (past values (value before the current time at running) are perfectly known (result from observations, not predictions)) */\n\t      /* \t  // only overwrite predictions of ensembles (not observations). OPTIONS->et_interpo[aaa] corresponds to the first say of predictions */\n\t      /* \t  else{ // if we don't run ensembles on F10.7/Ap or that we run ensemble on F10.7/Ap but that the initial epoch is before the first prediction (so there is no uncertainty in F10.7/Ap because the initial epooch corresponds to an observation, not a prediction) */\n\t      /* \t    //\t    print_test(); */\n\t      /* \t     CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.Ap[0]            = OPTIONS->Ap[0];           // magnetic index(daily) */\n\t      /* \t    if (OPTIONS->use_ap_hist == 1){ */\n\t      /* \t      for (hhh = 0; hhh < 7; hhh++){ */\n\t      /* \t\t CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.Ap_hist[hhh][0]            = OPTIONS->Ap_hist[hhh][0];           // magnetic index(historical) */\n\t      /* \t      } */\n\t      /* \t    } */\n\n\t      /* \t     CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.f107[0]          = OPTIONS->f107[0];         // Daily average of F10.7 flux */\n\t      /* \t     CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.f107A[0]         = OPTIONS->f107A[0];        // 81 day average of F10.7 flux */\n\n\t      /* \t    //  \t    printf(\"%d %f %d %f\\n\",  CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_ensemble_nb,  CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.f107[index_in_driver_interpolated], index_in_driver_interpolated, OPTIONS->f107[index_in_driver_interpolated]); */\n\t      /* \t  } // end of if we don't run ensembles on F10.7/Ap or that we run ensemble on F10.7/Ap but that the initial epoch is before the first prediction (so there is no uncertainty in F10.7/Ap because the inital epoch corresponds to an observation, not a prediction) */\n\n\n\n\t    } // end of if the user chooses a time-varying f107 and Ap for the density \n\n\t  } // end of the user chooses f107 and Ap and Ap_hist for the density\n\n\t  else if ( strcmp(OPTIONS->format_density_driver, \"density_file\") == 0 ){ // the user chooses to directly input the density from a file\n\t    for (aaa = 0; aaa< OPTIONS->nb_time_steps * 2; aaa++){  // \"* 2.0\" because of the Runge Kunta order 4 method\n\t      if (OPTIONS->et_interpo[aaa] <= et_final_epoch + 0.01 ) {\n\t\tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.density[aaa]            = OPTIONS->density[aaa] * 1e9; // Convert from kg/m^3 to kg/km^3\n\t      }\n\t    }\n\n\t  } // end of  the user chooses to directly input the density from a file\n\n\t  else if ( strcmp(OPTIONS->format_density_driver, \"gitm\") == 0 ){ // the user chooses GITM\n\t    if ( (ii ==0) && (eee == 0) ) { // here we initialize ATMOSPHERE if gitm is chosen so it doesn't have to be done for all satellites, just the first one (since ATMOSPHERE is the same for all satellites/ensembles)\n\t      if (OPTIONS->nb_gitm_file < 1){\n\t\tprintf(\"***! No GITM file has been found. The program will stop. !***\\n\");\n\t\tMPI_Finalize();\n\t\texit(0);\n\t      }\n\t      else{\n\t\tfor (ggg = 0; ggg < OPTIONS->nb_gitm_file; ggg++){\n\n\t\t  PARAMS->ATMOSPHERE.nb_gitm_file = OPTIONS->nb_gitm_file;\n\t\t  strcpy(PARAMS->ATMOSPHERE.array_gitm_file[ggg], OPTIONS->array_gitm_file[ggg]);\n\t\t  PARAMS->ATMOSPHERE.array_gitm_date[ggg][0] = OPTIONS->array_gitm_date[ggg][0] ;\n\t\t  PARAMS->ATMOSPHERE.array_gitm_date[ggg][1]= OPTIONS->array_gitm_date[ggg][1] ;\n\t\t  PARAMS->ATMOSPHERE.is_first_step_of_run = 1;\n\t\t}\n\t\t// Read the first data file to get the number of lon/lat/alt and allocate memory accordingly\n\n\t\tgitm_file = fopen(PARAMS->ATMOSPHERE.array_gitm_file[0],\"rb\");\n\n\t\t// NLONS, NLATS, NALTS\n\t\tfseek(gitm_file, 20, SEEK_SET\t );\n\t\tfread(&PARAMS->ATMOSPHERE.nLons_gitm,sizeof(PARAMS->ATMOSPHERE.nLons_gitm),1,gitm_file);\n\t\tfread(&PARAMS->ATMOSPHERE.nLats_gitm,sizeof(PARAMS->ATMOSPHERE.nLats_gitm),1,gitm_file);\n\t\tfread(&PARAMS->ATMOSPHERE.nAlts_gitm,sizeof(PARAMS->ATMOSPHERE.nAlts_gitm),1,gitm_file);\n\t\tfseek(gitm_file , 4, SEEK_CUR\t );\n \n\t\t// Allocate for the GITM file which date is right BEFORE the epoch of the sc\n\n\t\tPARAMS->ATMOSPHERE.longitude_gitm = malloc(  PARAMS->ATMOSPHERE.nLons_gitm * sizeof(double **) );\n\t\tfor (i = 0; i < PARAMS->ATMOSPHERE.nLons_gitm; i++){\n\t\t  PARAMS->ATMOSPHERE.longitude_gitm[i] = malloc(PARAMS->ATMOSPHERE.nLats_gitm * sizeof(double *));\n\t\t  for (j = 0; j < PARAMS->ATMOSPHERE.nLats_gitm; j++){\n\t\t    PARAMS->ATMOSPHERE.longitude_gitm[i][j] = malloc(PARAMS->ATMOSPHERE.nAlts_gitm * sizeof(double));\n\t\t  }\n\t\t}\n\t\tPARAMS->ATMOSPHERE.latitude_gitm = malloc(  PARAMS->ATMOSPHERE.nLons_gitm * sizeof(double **) );\n\t\tfor (i = 0; i < PARAMS->ATMOSPHERE.nLons_gitm; i++){\n\t\t  PARAMS->ATMOSPHERE.latitude_gitm[i] = malloc(PARAMS->ATMOSPHERE.nLats_gitm * sizeof(double *));\n\t\t  for (j = 0; j < PARAMS->ATMOSPHERE.nLats_gitm; j++){\n\t\t    PARAMS->ATMOSPHERE.latitude_gitm[i][j] = malloc(PARAMS->ATMOSPHERE.nAlts_gitm * sizeof(double));\n\t\t  }\n\t\t}\n\t\tPARAMS->ATMOSPHERE.altitude_gitm = malloc(  PARAMS->ATMOSPHERE.nLons_gitm * sizeof(double **) );\n\t\tfor (i = 0; i < PARAMS->ATMOSPHERE.nLons_gitm; i++){\n\t\t  PARAMS->ATMOSPHERE.altitude_gitm[i] = malloc(PARAMS->ATMOSPHERE.nLats_gitm * sizeof(double *));\n\t\t  for (j = 0; j < PARAMS->ATMOSPHERE.nLats_gitm; j++){\n\t\t    PARAMS->ATMOSPHERE.altitude_gitm[i][j] = malloc(PARAMS->ATMOSPHERE.nAlts_gitm * sizeof(double));\n\t\t  }\n\t\t}\n\n\n\t\tPARAMS->ATMOSPHERE.density_gitm_right_before = malloc(  PARAMS->ATMOSPHERE.nLons_gitm * sizeof(double **) );\n\t\tfor (i = 0; i < PARAMS->ATMOSPHERE.nLons_gitm; i++){\n\t\t  PARAMS->ATMOSPHERE.density_gitm_right_before[i] = malloc(PARAMS->ATMOSPHERE.nLats_gitm * sizeof(double *));\n\t\t  for (j = 0; j < PARAMS->ATMOSPHERE.nLats_gitm; j++){\n\t\t    PARAMS->ATMOSPHERE.density_gitm_right_before[i][j] = malloc(PARAMS->ATMOSPHERE.nAlts_gitm * sizeof(double));\n\t\t  }\n\t\t}\n\n\t\tif (  PARAMS->ATMOSPHERE.longitude_gitm == NULL ){\n\t\t  printf(\"***! Could not allow memory for PARAMS->ATMOSPHERE.longitude_gitm. The program will stop. !***\\n\");\n\t\t  MPI_Finalize();\n\t\t  exit(0);\n\t\t}\n\t\tif (  PARAMS->ATMOSPHERE.latitude_gitm == NULL ){\n\t\t  printf(\"***! Could not allow memory for PARAMS->ATMOSPHERE.latitude_gitm. The program will stop. !***\\n\");\n\t\t  MPI_Finalize();\n\t\t  exit(0);\n\t\t}\n\t\tif (  PARAMS->ATMOSPHERE.altitude_gitm == NULL ){\n\t\t  printf(\"***! Could not allow memory for PARAMS->ATMOSPHERE.altitude_gitm. The program will stop. !***\\n\");\n\t\t  MPI_Finalize();\n\t\t  exit(0);\n\t\t}\n\n\t\tif (  PARAMS->ATMOSPHERE.density_gitm_right_before == NULL ){\n\t\t  printf(\"***! Could not allow memory for PARAMS->ATMOSPHERE.density_gitm_right_before. The program will stop. !***\\n\");\n\t\t  MPI_Finalize();\n\t\t  exit(0);\n\t\t}\n\t\t// Allocate for the GITM file which date is right AFTER the epoch of the sc\n\n\n\t\tPARAMS->ATMOSPHERE.density_gitm_right_after = malloc(  PARAMS->ATMOSPHERE.nLons_gitm * sizeof(double **) );\n\n\n\t\tPARAMS->ATMOSPHERE.density_gitm_right_after = malloc(  PARAMS->ATMOSPHERE.nLons_gitm * sizeof(double **) );\n\t\tfor (i = 0; i < PARAMS->ATMOSPHERE.nLons_gitm; i++){\n\t\t  PARAMS->ATMOSPHERE.density_gitm_right_after[i] = malloc(PARAMS->ATMOSPHERE.nLats_gitm * sizeof(double *));\n\t\t  for (j = 0; j < PARAMS->ATMOSPHERE.nLats_gitm; j++){\n\t\t    PARAMS->ATMOSPHERE.density_gitm_right_after[i][j] = malloc(PARAMS->ATMOSPHERE.nAlts_gitm * sizeof(double));\n\t\t  }\n\t\t}\n\n\n\t\tif (  PARAMS->ATMOSPHERE.density_gitm_right_after == NULL ){\n\t\t  printf(\"***! Could not allow memory for PARAMS->ATMOSPHERE.density_gitm_right_after. The program will stop. !***\\n\");\n\t\t  MPI_Finalize();\n\t\t  exit(0);\n\t\t}\n\n\t\t// Read the lon/lat/alt array (same for all files in the propagation) and nVars\n\t\t// NVARS\n\t\tfseek(gitm_file, 4, SEEK_CUR\t );\n\t\tfread(&PARAMS->ATMOSPHERE.nVars_gitm,sizeof(PARAMS->ATMOSPHERE.nVars_gitm),1,gitm_file);\n\t\tfseek(gitm_file, 4, SEEK_CUR\t );\n\t\tiHeaderLength_gitm = 8L + 4+4 +\t3*4 + 4+4 + 4 + 4+4 + PARAMS->ATMOSPHERE.nVars_gitm*40 + PARAMS->ATMOSPHERE.nVars_gitm*(4+4) +  7*4 + 4+4; \n\t\tfseek(gitm_file, iHeaderLength_gitm, SEEK_SET);\n\t\t// READ THE LONGITUDE\n\t\tfseek(gitm_file, 4, SEEK_CUR );\n\t\tfor (k = 0; k < PARAMS->ATMOSPHERE.nAlts_gitm; k++){\n\t\t  for (j = 0; j < PARAMS->ATMOSPHERE.nLats_gitm; j++){\n\t\t    for (i = 0; i < PARAMS->ATMOSPHERE.nLons_gitm; i++){\n\t\t      fread(&PARAMS->ATMOSPHERE.longitude_gitm[i][j][k], sizeof(PARAMS->ATMOSPHERE.longitude_gitm[i][j][k]), 1, gitm_file);\n\t\t    }\n\t\t  }\n\t\t}\n\t\tfseek(gitm_file, 4, SEEK_CUR );\n\t\t//printf(\"\\n %f\\n\", PARAMS->ATMOSPHERE.longitude_gitm[11][40][21]);\n     \n\n\t\t// READ THE LATITUDE\n\t\tfseek(gitm_file, 4, SEEK_CUR );\n\t\tfor (k = 0; k < PARAMS->ATMOSPHERE.nAlts_gitm; k++){\n\t\t  for (j = 0; j < PARAMS->ATMOSPHERE.nLats_gitm; j++){\n\t\t    for (i = 0; i < PARAMS->ATMOSPHERE.nLons_gitm; i++){\n\t\t      fread(&PARAMS->ATMOSPHERE.latitude_gitm[i][j][k], sizeof(PARAMS->ATMOSPHERE.latitude_gitm[i][j][k]), 1, gitm_file);\n\t\t    }\n\t\t  }\n\t\t}\n\t\tfseek(gitm_file, 4, SEEK_CUR );\n\t\t//     printf(\"\\n %f\\n\", PARAMS->ATMOSPHERE.latitude_gitm[11][40][21]);\n     \n\n\t\t// READ THE ALTITUDE\n\t\tfseek(gitm_file, 4, SEEK_CUR );\n\t\tfor (k = 0; k < PARAMS->ATMOSPHERE.nAlts_gitm; k++){\n\t\t  for (j = 0; j < PARAMS->ATMOSPHERE.nLats_gitm; j++){\n\t\t    for (i = 0; i < PARAMS->ATMOSPHERE.nLons_gitm; i++){\n\t\t      fread(&PARAMS->ATMOSPHERE.altitude_gitm[i][j][k], sizeof(PARAMS->ATMOSPHERE.altitude_gitm[i][j][k]), 1, gitm_file);\n\t\t      PARAMS->ATMOSPHERE.altitude_gitm[i][j][k] = PARAMS->ATMOSPHERE.altitude_gitm[i][j][k] / 1000.0; // conversion meters to kilometers\n\t\t    }\n\t\t  }\n\t\t}\n   \n\t\t//     printf(\"\\n %f\\n\", PARAMS->ATMOSPHERE.altitude_gitm[11][40][21]);\n\n\t\tfclose(gitm_file);\n\t      }\n\t      //  printf(\"%s | %d\\n\", PARAMS->ATMOSPHERE.array_gitm_file[ggg], ggg);\n\n\t    }\n\n\n\t    if (eee == 0){\n\t      // find the altitude that is right below the perigee altitude. Note: if the duration of the run is long (so that the sc looses a good amount of altitude, so like 6 months) then index_altitude_right_below_perigee is set to 0 so that we go over all the altitudes and not only the ones that start below the perigee calcualted at the initialization.\n\t      //if many main satellites with different altitude of the perigee, then take the min of these perigee to calculate index_altitude_right_below_perigee\n\t      int found_altitude_right_below_perigee = 0;\n\t      if ( et_final_epoch - et_initial_epoch < 6 * 31 * 24 * 3600.0 ){ // if the duration of the run is long (so that the sc looses a good amount of altitude, so like 6 months) then index_altitude_right_below_perigee is set to 0 so that we go over all the altitudes and not only the ones that start below the perigee calcualted at the initialization.\n\t\taltitude_perigee = radius_perigee - PARAMS->EARTH.radius;\n\t\tk = 0;\n\t\twhile ( (k < PARAMS->ATMOSPHERE.nAlts_gitm ) && (found_altitude_right_below_perigee == 0) ){\n\t\t  if (PARAMS->ATMOSPHERE.altitude_gitm[0][0][k] >= altitude_perigee){\n\t\t    if ( (k-1) < index_altitude_right_below_perigee_save ){\n\t\t      index_altitude_right_below_perigee_save = k-1;\n\t\t    } \n\t\t    found_altitude_right_below_perigee = 1;\n\t\t  }\n\t\t  k = k+1;\n\t\t}\n\t\tif (ii == OPTIONS->n_satellites - OPTIONS->nb_gps - 1){\n\t\t  PARAMS->ATMOSPHERE.index_altitude_right_below_perigee = index_altitude_right_below_perigee_save;\n\n\t\t}\n\t      }\n\t      else{\n\t\tPARAMS->ATMOSPHERE.index_altitude_right_below_perigee = 0;\n\t      }\n\t    }\n\t\n\t  } // end of the user chooses GITM\n\n\t} // end of if the user wants to use drag\n\tif (iDebugLevel >= 2){\n\t  if (iProc == 0) printf(\"--- (initialize_constellation) Done initializing dt, nb_surfaces, mass, solar_cell_efficiency, degree, order, include_drag/solar_pressure/earth_pressure/moon/sun, Ap, Ap_hist, f107, f107A, density, initialize_geo_with_bstar for all spacecraft.\\n\");\n\t}\n\n\n\tif (iDebugLevel >= 1){\n\t  if (iProc == 0) printf(\"-- (initialize_constellation) Done initializing r_ecef2cg_ECEF, geodetic, output file names, name_sat, dt, nb_surfaces, mass, solar_cell_efficiency, degree, order, include_drag/solar_pressure/earth_pressure/moon/sun, Ap, Ap_hist, f107, f107A, density, initialize_geo_with_bstar for all spacecraft.\\n\");\n\t}\n\n\t/*************************************************************************************/\n\t/*************************************************************************************/\n\t/************* END OF COE AND TLE INITIALIZE for main SC and for ensemble SC:\n- r_ecef2cg_ECEF\n- geodetic\n- filename, filenameecef, filenameout, filenamepower for main SC ONLY\n- name_sat\n- INTEGRATOR: dt, nb_surfaces, mass, solar_cell_efficiency, degree, order, include_drag/solar_pressure/earth_pressure/moon/sun, Ap, Ap_hist, f107, f107A, density, initialize_geo_with_bstar, sc_main_nb, sc_ensemble_nb\n\t**************/\n\t/*************************************************************************************/\n\t/*************************************************************************************/\n\n\n\n\t/*************************************************************************************/\n\t/*************************************************************************************/\n\t/*********************** COE AND TLE INITIALIZE: attitude ****************************/\n\t/*************************************************************************************/\n\t/*************************************************************************************/\n\tif (iDebugLevel >= 1){\n\t  if (iProc == 0) printf(\"-- (initialize_constellation) Initializing the attitude.\\n\");\n\t}\n\n\tif ( ( strcmp(OPTIONS->attitude_profile, \"ensemble_angular_velocity\") != 0 ) && ( strcmp(OPTIONS->attitude_profile, \"ensemble_initial_attitude\") != 0 ) ) { // if we do not run ensembles on the initial angular velocity\n\n\t  // Give memory to attitude variables\n\t  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.file_is_quaternion = OPTIONS->file_is_quaternion;\n\t\tif ( OPTIONS->file_is_quaternion == 0){\n\t  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.pitch = malloc( OPTIONS->nb_time_steps * 2 * sizeof(double) ); // \"* 2.0\" because of the Runge Kunta order 4 method\n\n\t  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.roll = malloc( OPTIONS->nb_time_steps * 2 * sizeof(double) );\n\t  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.yaw = malloc( OPTIONS->nb_time_steps * 2 * sizeof(double) );\n\t  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_pitch = malloc( OPTIONS->nb_time_steps * 2 * sizeof(double) ); \n\t  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_roll = malloc( OPTIONS->nb_time_steps * 2 * sizeof(double) );\n\t  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_yaw = malloc( OPTIONS->nb_time_steps * 2 * sizeof(double) );\n\t\t}\n\t\telse{\n\t  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.quaternion = malloc( OPTIONS->nb_time_steps * 2 * sizeof(double*) ); // \"* 2.0\" because of the Runge Kunta order 4 method\n\t  for (ccc = 0; ccc < OPTIONS->nb_time_steps * 2; ccc++){\n\t    CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.quaternion[ccc] = malloc( 4* sizeof(double) );\n\t  }\n\n\n\t\t}\n\t\t CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.index_in_attitude_interpolated_first = (int)( CONSTELLATION->spacecraft[ii][eee].et - OPTIONS->et_oldest_tle_epoch ) / OPTIONS->dt *2.;\n\t\t  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.index_in_driver_interpolated_first = (int)( CONSTELLATION->spacecraft[ii][eee].et - OPTIONS->et_oldest_tle_epoch ) / OPTIONS->dt * 2.;\n\n\t  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.index_in_attitude_interpolated = (int)( CONSTELLATION->spacecraft[ii][eee].et - OPTIONS->et_oldest_tle_epoch ) / OPTIONS->dt *2.;\n\t  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.index_in_driver_interpolated = (int)( CONSTELLATION->spacecraft[ii][eee].et - OPTIONS->et_oldest_tle_epoch ) / OPTIONS->dt * 2.;\n\t  //\t  printf(\"%d %d | %d %d | %d %d\\n\", ii, eee, CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.index_in_attitude_interpolated, CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.index_in_driver_interpolated, CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.index_in_attitude_interpolated_first , CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.index_in_driver_interpolated_first );\n\t\tif ( OPTIONS->file_is_quaternion == 1){\n\t  if (  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.quaternion == NULL ){\n\t    printf(\"***! Could not allow memory space for  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.quaternion \\n. The program will stop. !***\\n\");\n\t    MPI_Finalize();\n\t    exit(0);\n\t  }\n\t\t}\n\t\telse{\n\t  if (  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.pitch == NULL ){\n\t    printf(\"***! Could not allow memory space for  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.pitch \\n. The program will stop. !***\\n\");\n\t    MPI_Finalize();\n\t    exit(0);\n\t  }\n\t  if (  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.roll == NULL ){\n\t    printf(\"***! Could not allow memory space for  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.roll \\n. The program will stop. !***\\n\");\n\t    MPI_Finalize();\n\t    exit(0);\n\t  }\n\t  if (  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.yaw == NULL ){\n\t    printf(\"***! Could not allow memory space for  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.yaw \\n. The program will stop. !***\\n\");\n\t    MPI_Finalize();\n\t    exit(0);\n\t  }\n\t  if (  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_pitch == NULL ){\n\t    printf(\"***! Could not allow memory space for  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_pitch \\n. The program will stop. !***\\n\");\n\t    MPI_Finalize();\n\t    exit(0);\n\t  }\n\t  if (  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_roll == NULL ){\n\t    printf(\"***! Could not allow memory space for  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_roll \\n. The program will stop. !***\\n\");\n\t    MPI_Finalize();\n\t    exit(0);\n\t  }\n\t  if (  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_yaw == NULL ){\n\t    printf(\"***! Could not allow memory space for  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_yaw \\n. The program will stop. !***\\n\");\n\t    MPI_Finalize();\n\t    exit(0);\n\t  }\n\t\t}\n\t  strcpy(CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.attitude_profile, OPTIONS->attitude_profile); // nadir, sun_pointed, ...\n\t  /*************************************************************************************/\n\t  /******************* COE AND TLE INITIALIZE: attitude for main SC ********************/\n\t  /*************************************************************************************/\n\t  if (eee == 0){ // eee = 0 represents the main spacecraft (eee > 0 is a sc from an ensemble)\n\n\t    for (aaa = 0; aaa< OPTIONS->nb_time_steps * 2; aaa++){  // \"* 2.0\" because of the Runge Kunta order 4 method\n\t      if (OPTIONS->et_interpo[aaa] <= et_final_epoch + 0.01) {\n\t\tif ( OPTIONS->file_is_quaternion == 0){\n\n\t\tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.pitch[aaa] = OPTIONS->pitch[aaa];\n\t\tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.roll[aaa]  = OPTIONS->roll[aaa];\n\t\tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.yaw[aaa]   = OPTIONS->yaw[aaa];\n\t\tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_pitch[aaa] = OPTIONS->order_pitch[aaa];\n\t\tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_roll[aaa]  = OPTIONS->order_roll[aaa];\n\t\tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_yaw[aaa]   = OPTIONS->order_yaw[aaa];\n\t\t  }\n\t\telse{\n\n\t\tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.quaternion[aaa][0] = OPTIONS->quaternion[aaa][0];\n\n\t\tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.quaternion[aaa][1] = OPTIONS->quaternion[aaa][1];\n\t\tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.quaternion[aaa][2] = OPTIONS->quaternion[aaa][2];\n\t\tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.quaternion[aaa][3] = OPTIONS->quaternion[aaa][3];\n\n\t\t}\n\t      }\n\t    }\n\n\t  } // end of initializing the attitude for the main SC\n\n\t  /*************************************************************************************/\n\t  /******************* COE AND TLE INITIALIZE: attitude for ensemble SC ****************/\n\t  /*************************************************************************************/\n\n\t  /*****************************************************************************************************************************/\n\t  /**************************************************** ENSEMBLES ON ATTITUDE **************************************************/\n\t  /*****************************************************************************************************************************/\n\t  else{ // here eee > 0 so we are initializing the attitude for the sc from an ensemble\n\n\t    if (OPTIONS->nb_ensembles_attitude > 0){ // initialize the attitude if we run ensembles on the attitude. So it's not with ensemble_angular_velocity and not with ensemble_initial_attitude (these would have had to be put in section #ATTITUDE). But it corresponds to a drift of the sc from a reference attitude (specified in section #ATTITUDE (nadir, sun_pointed, ...)) for with a given time (set by time_before_reset) with a random angular velocity.\n\n\t      //\t    if (iProc == 0){\n\t      CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.pitch_sigma_ensemble = OPTIONS->pitch_sigma_ensemble;\n\t      CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.roll_sigma_ensemble = OPTIONS->roll_sigma_ensemble;\n\t      CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.yaw_sigma_ensemble = OPTIONS->yaw_sigma_ensemble;\n\t      //\t    }\n\n\t      //for (aaa = 0; aaa< OPTIONS->nb_time_steps * 2; aaa++){  // \"* 2.0\" because of the Runge Kunta order 4 method\n\t      //\t  last_aaa_previous_loop = 0;\n\t      aaa = 0;\n\t      if (write_attitude_file == 1){\n\t\tfprintf(file_attitude[ii], \"#START_ATTITUDE_ENSEMBLE for ensemble %d\\n\", eee);\n\t      }\n\n\n\t      while ( aaa < OPTIONS->nb_time_steps * 2 ){\n\t\t//\t\tprintf(\"%d %d %d || %f %f\\n\", iProc, aaa, OPTIONS->nb_time_steps * 2, OPTIONS->et_interpo[aaa], et_final_epoch);\n\t\tif (OPTIONS->et_interpo[aaa] <= et_final_epoch + 0.01 ) {\n\n\t\t  time_before_reset = 0;\n\t\t  // every OPTIONS->attitude_reset_delay seconds, the attitude is set equal to the attitude of the main spacecraft (nadir or sun pointed or from an atttitude file)\n\t\t  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.pitch[aaa] =  OPTIONS->pitch[aaa];\n\t\t  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.roll[aaa] = OPTIONS->roll[aaa];\n\t\t  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.yaw[aaa] = OPTIONS->yaw[aaa];\n\t\t  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_pitch[aaa] = OPTIONS->order_pitch[aaa];\n\t\t  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_roll[aaa]  = OPTIONS->order_roll[aaa];\n\t\t  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_yaw[aaa]   = OPTIONS->order_yaw[aaa];\n\t\t  // during OPTIONS->attitude_reset_delay seconds, the satellite's attitude changes with a constant random angular velocity\n\t\t  random_pitch_angular_velocity = randn( 0.0, OPTIONS->pitch_sigma_angular_velocity_ensemble);\n\t\t  random_roll_angular_velocity = randn( 0.0, OPTIONS->roll_sigma_angular_velocity_ensemble);\n\t\t  random_yaw_angular_velocity = randn( 0.0, OPTIONS->yaw_sigma_angular_velocity_ensemble);\n\t\t  if (write_attitude_file == 1){\n\t\t    if (aaa==0){\n\t\t      fprintf(file_attitude[ii], \"%e %e %e %d %d %d\\n\", random_pitch_angular_velocity, random_roll_angular_velocity, random_yaw_angular_velocity, CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_pitch[aaa], CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_roll[aaa],CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_yaw[aaa] );\t\t      \n\t\t    }\n\t\t    et2utc_c(OPTIONS->et_oldest_tle_epoch+aaa*OPTIONS->dt/2., \"ISOC\" ,0 ,255 , time_attitude);\n\t\t    fprintf(file_attitude[ii], \"%s %e %e %e\\n\", time_attitude,CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.pitch[aaa], CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.roll[aaa], CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.yaw[aaa]);\n\t\t  }\n\t\t  //\t\t    if (iProc == 0){\n/* \t\t      if ( (ii == 1) && (eee == array_sc[start_ensemble[ii]]) ){ */\n/* \t\t\tprintf(\"iProc %d | aaa = %d out of %d | time reset %f out of %f\\n\", iProc, aaa, OPTIONS->nb_time_steps * 2, time_before_reset * OPTIONS->dt / 2.0 , OPTIONS->attitude_reset_delay); */\n/* \t\t      } */\n\t\t      //}\n\n\n\t\t  while ( ( time_before_reset * OPTIONS->dt / 2.0 < ( OPTIONS->attitude_reset_delay - OPTIONS->dt / 2.0 ) ) && ( aaa < OPTIONS->nb_time_steps * 2 ) ){\n\t\t    time_before_reset = time_before_reset + 1 ;\n\t\t    aaa = aaa + 1;\n\n\t\t    /* \tif (iProc == 2){ */\n/* \t\t\t\t  printf(\"iProc %d | aaa = %d out of %d | time reset %f out of %f\\n\", iProc, aaa, OPTIONS->nb_time_steps * 2, time_before_reset * OPTIONS->dt / 2.0 , OPTIONS->attitude_reset_delay); */\n/* \t\t\t\t  \t  } */\n\n\t\t    if (aaa < OPTIONS->nb_time_steps * 2){\n\t\t      CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.pitch[aaa] = random_pitch_angular_velocity * time_before_reset * OPTIONS->dt / 2.0 + OPTIONS->pitch[aaa]; // the angular velocity is distributed as gaussian with a 0 rad/s mean and a standard deviation OPTIONS->pitch/roll/yaw_sigma_angular_velocity_ensemble chosen by the user. The attitude is calculated from this random angular velocity around the attitude of the main spacecraft (nadir or from an attitude file (FOR NOW NOT POSSIBLE TO RUN ENSEMBLES IF ATTITUDE IS SUN_POINTED)): OPTIONS->pitch/roll/yaw[aaa]\n\t\t      CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.roll[aaa] = random_roll_angular_velocity * time_before_reset * OPTIONS->dt / 2.0 + OPTIONS->roll[aaa];\n\t\t      CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.yaw[aaa] = random_yaw_angular_velocity * time_before_reset * OPTIONS->dt / 2.0 + OPTIONS->yaw[aaa];\n\t\t      CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_pitch[aaa] = OPTIONS->order_pitch[aaa];\n\t\t      CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_roll[aaa]  = OPTIONS->order_roll[aaa];\n\t\t      CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_yaw[aaa]   = OPTIONS->order_yaw[aaa];\n/* \t\t    if (iProc == 0){ */\n/* \t\t      if ( (ii == 0) && (eee == 1) ){ */\n/* \t\t\tprintf(\"IN iProc %d | aaa = %d out of %d | time reset %f out of %f | pitch %f\\n\", iProc, aaa, OPTIONS->nb_time_steps * 2, time_before_reset * OPTIONS->dt / 2.0 , OPTIONS->attitude_reset_delay, CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.pitch[aaa]); */\n/* \t\t      } */\n/* \t\t    } */\n\n\t\t      if (write_attitude_file == 1){\n\t\t\tif (fmod(aaa, 2) == 0){\n\t\t\t  et2utc_c(OPTIONS->et_oldest_tle_epoch+aaa*OPTIONS->dt/2., \"ISOC\" ,0 ,255 , time_attitude);\n\t\t\t  fprintf(file_attitude[ii], \"%s %e %e %e\\n\", time_attitude,CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.pitch[aaa], CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.roll[aaa], CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.yaw[aaa] );\n\t\t\t}\n\t\t      }\n\t\t  \n\t\t    }\n\t\t  } // end of while loop for the attitude with a constant random angular velocity\n\t\t  aaa = aaa + 1;\n\t\t  //last_aaa_previous_loop = aaa;\n\t\t}\n\t      } // end of initializing the attitude for the ensemble spacecrafts\n\t      if (write_attitude_file == 1){\n\t\tfprintf(file_attitude[ii], \"#END_ATTITUDE_ENSEMBLE\\n\\n\");\n\t      }\n\n\t    } // end of initialize the attitude if we run ensembles on the attitude\n\t  \n\t    else{ // initialize the attitude if we do not run ensembles on the attitude\n\t      // WE DON'T INITALIZE THE ATTIUDE HERE ANYMORE BUT IN THE FUNCTION SET_ATTITUDE CALLED IN PROPAGATE_SPACECRAFT. This is to avoid going through all time steps for all ensembles. Note that for all other cases, ie if we run any kind of ensembles on the attitude, the initialization of the attitude is still set in initialize_constellation (and not in propagate_spacecraft)\n\t      /* for (aaa = 0; aaa< OPTIONS->nb_time_steps * 2; aaa++){ */\n\t      /*   if (OPTIONS->et_interpo[aaa] <= et_final_epoch + 0.01 ) { */\n\t      /* \tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.pitch[aaa] = OPTIONS->pitch[aaa]; */\n\t      /* \tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.roll[aaa]  = OPTIONS->roll[aaa]; */\n\t      /* \tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.yaw[aaa]   = OPTIONS->yaw[aaa]; */\n\t      /* \tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_pitch[aaa] = OPTIONS->order_pitch[aaa]; */\n\t      /* \tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_roll[aaa]  = OPTIONS->order_roll[aaa]; */\n\t      /* \tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_yaw[aaa]   = OPTIONS->order_yaw[aaa]; */\n\t      /*   } */\n\t      /* } */\n\t      //end of  WE DON'T INITALIZE THE ATTIUDE HERE ANYMORE BUT IN THE FUNCTION SET_ATTITUDE CALLED IN PROPAGATE_SPACECRAFT\n\t    } // end of initialize the attitude if we do not run ensembles on the attitude\n\t  } // end of initializinf the attitude for the ensemble spacecraft\n\n\t} // end of if we do not run ensembles on the initial angular velocity\n\n\t/*********************************************************************************************************************************/\n\t/******************************************* ENSEMBLES ON INITIAL ANGULAR VELOCITY ***********************************************/\n\t/*********************************************************************************************************************************/\n\telse if ( strcmp(OPTIONS->attitude_profile, \"ensemble_angular_velocity\") == 0 ){  // if we run ensembles on the initial angular velocity. The attitude is defined by its initial angle (pitch; roll; yaw), the mean angular velocity (mean ang velo pitch; mean ang velo roll; mean ang velo yaw), and the standard deviation on the angular velo (sigma ang velo pitch; sigma ang velo roll; sigma ang velo yaw)\n\t  //\tif ( (eee == 0) && (ii == 0)){ // initialize attitude for main spacecraft if  we run ensembles on the initial angular velocity // !!!!!!!!!!!! for now works only if there one satellite in the constellation\n\t  if ( eee == 0){ // initialize attitude for main spacecraft if  we run ensembles on the initial angular velocity \n\t    strcpy(CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.attitude_profile, OPTIONS->attitude_profile); // here attitude_profile = \"ensemble_angular_velocity\"\n\t    // pitch\n\t    CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.pitch_ini_ensemble = OPTIONS->pitch_ini_ensemble;\n\t    CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.pitch_angular_velocity_ensemble = OPTIONS->pitch_mean_angular_velocity_ensemble;\n\t    CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.pitch_sigma_angular_velocity_ensemble = OPTIONS->pitch_sigma_angular_velocity_ensemble / 2.0;\n\t    // roll\n\t    CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.roll_ini_ensemble = OPTIONS->roll_ini_ensemble;\n\t    CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.roll_angular_velocity_ensemble = OPTIONS->roll_mean_angular_velocity_ensemble;\n\t    CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.roll_sigma_angular_velocity_ensemble = OPTIONS->roll_sigma_angular_velocity_ensemble / 2.0;\n\t    // yaw\n\t    CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.yaw_ini_ensemble = OPTIONS->yaw_ini_ensemble;\n\t    CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.yaw_angular_velocity_ensemble = OPTIONS->yaw_mean_angular_velocity_ensemble;\n\t    CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.yaw_sigma_angular_velocity_ensemble = OPTIONS->yaw_sigma_angular_velocity_ensemble / 2.0;\n\n\t  } // end of initialize attitude for main spacecraft if  we run ensembles on the initial angular velocity\n\t  //\telse if (ii == 0){ // initialize attitude for ensemble spacecraft if  we run ensembles on the initial angular velocity\n\t  else{ // initialize attitude for ensemble spacecraft if  we run ensembles on the initial angular velocity\n\t    strcpy(CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.attitude_profile, OPTIONS->attitude_profile); // here attitude_profile = \"ensemble_angular_velocity\"\n\t    // calculate the random angular velocity = normal distribution around the mean angular velocity OPTIONS->pitch/roll/yaw_mean_angular_velocity_ensemble with a standard deviation OPTIONS->pitch/roll/yaw_sigma_angular_velocity_ensemble\n\n\t    CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.pitch_angular_velocity_ensemble = randn( OPTIONS->pitch_mean_angular_velocity_ensemble, OPTIONS->pitch_sigma_angular_velocity_ensemble / 2.0);\n\t    CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.roll_angular_velocity_ensemble = randn( OPTIONS->roll_mean_angular_velocity_ensemble, OPTIONS->roll_sigma_angular_velocity_ensemble / 2.0);\n\t    CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.yaw_angular_velocity_ensemble = randn( OPTIONS->yaw_mean_angular_velocity_ensemble, OPTIONS->yaw_sigma_angular_velocity_ensemble / 2.0);\n\t     \n\t    //\t     fprintf(fp_temp, \"%f \\n\", CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.pitch_angular_velocity_ensemble);\n\t    CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.pitch_ini_ensemble = OPTIONS->pitch_ini_ensemble;\n\t    CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.roll_ini_ensemble = OPTIONS->roll_ini_ensemble;\n\t    CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.yaw_ini_ensemble = OPTIONS->yaw_ini_ensemble;\n\n\n\t    /* \t  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.pitch_angular_velocity_ensemble = randn( CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.pitch_angular_velocity_ensemble, CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.pitch_sigma_angular_velocity_ensemble); */\n\t    /* \t  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.roll_angular_velocity_ensemble = randn( CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.roll_angular_velocity_ensemble, CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.roll_sigma_angular_velocity_ensemble); */\n\t    /* \t  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.yaw_angular_velocity_ensemble = randn( CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.yaw_angular_velocity_ensemble, CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.yaw_sigma_angular_velocity_ensemble); */\n\t     \n\t    /* \t  //\t     fprintf(fp_temp, \"%f \\n\", CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.pitch_angular_velocity_ensemble); */\n\t    /* \t  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.pitch_ini_ensemble = CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.pitch_ini_ensemble; */\n\t    /* \t  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.roll_ini_ensemble = CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.roll_ini_ensemble; */\n\t    /* \t  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.yaw_ini_ensemble = CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.yaw_ini_ensemble; */\n\n\t  } // end of initialize attitude for ensemble spacecraft if  we run ensembles on the initial angular velocity\n\t} // end of if we run ensembles on the initial angular velocity\n\telse if ( strcmp(OPTIONS->attitude_profile, \"ensemble_initial_attitude\") == 0 ){ //if we run ensembles on the initial attitude. The ensembles all have different initial attitude but same constant angular velocities\n\t  //\tif ( (eee == 0) && (ii == 0)){ // initialize attitude for main spacecraft if we run ensembles on the initial attitude // !!!!!!!!!!!! for now works only if there one satellite in the constellation\n\t  if ( eee == 0 ){ // initialize attitude for main spacecraft if we run ensembles on the initial attitude \n\t    strcpy(CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.attitude_profile, OPTIONS->attitude_profile); // here attitude_profile = \"ensemble_initial_attitude\"\n\t    // the reference satellite has the same attitude as the mean attitude chosen by the user (first line of ###ENSEMBLES_INITIAL_ATTITUDE)\n\n\t    CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.pitch_for_attitude_ensemble = OPTIONS->pitch_mean_ensemble;\n\t    CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.roll_for_attitude_ensemble = OPTIONS->roll_mean_ensemble;\n\t    CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.yaw_for_attitude_ensemble = OPTIONS->yaw_mean_ensemble;\n\n\t    CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.pitch_angular_velocity_constant = OPTIONS->pitch_angular_velocity_constant;\n\t    CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.roll_angular_velocity_constant = OPTIONS->roll_angular_velocity_constant;\n\t    CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.yaw_angular_velocity_constant = OPTIONS->yaw_angular_velocity_constant;\n\t  \n\t  } // end of initialize attitude for main spacecraft if  we run ensembles on the initial angular velocity\n\t  //\telse if (ii == 0){ // initialize attitude for ensemble spacecraft if  we run ensembles on the initial angular velocity\n\t  else{ // initialize attitude for ensemble spacecraft if  we run ensembles on the initial angular velocity\n\n\t    strcpy(CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.attitude_profile, OPTIONS->attitude_profile); // here attitude_profile = \"ensemble_angular_velocity\"\n\t    // calculate the random angular velocity = normal distribution around the mean angular velocity OPTIONS->pitch/roll/yaw_mean_angular_velocity_ensemble with a standard deviation OPTIONS->pitch/roll/yaw_sigma_angular_velocity_ensemble\n\n\t    CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.pitch_for_attitude_ensemble = randn( OPTIONS->pitch_mean_ensemble, OPTIONS->pitch_sigma_for_ensemble_initial_attitude / 2.);\n\t    CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.roll_for_attitude_ensemble = randn( OPTIONS->roll_mean_ensemble, OPTIONS->roll_sigma_for_ensemble_initial_attitude / 2.);\n\t    CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.yaw_for_attitude_ensemble = randn( OPTIONS->yaw_mean_ensemble, OPTIONS->yaw_sigma_for_ensemble_initial_attitude / 2.);\n\n\t    CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.pitch_angular_velocity_constant = OPTIONS->pitch_angular_velocity_constant;\n\t    CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.roll_angular_velocity_constant = OPTIONS->roll_angular_velocity_constant;\n\t    CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.yaw_angular_velocity_constant = OPTIONS->yaw_angular_velocity_constant;\n\n\t  } // end of initialize attitude for ensemble spacecraft if  we run ensembles on the initial angular velocity\n      \n\t} // end of if we run ensembles on the initial attitude\n\tif (iDebugLevel >= 1){\n\t  if (iProc == 0) printf(\"-- (initialize_constellation) Done initializing the attitude.\\n\");\n\t}\n\n\n\t/*************************************************************************************/\n\t/*************************************************************************************/\n\t/********************** END OF COE AND TLE INITIALIZE: attitude **********************/\n\t/*************************************************************************************/\n\t/*************************************************************************************/\n    \n\t/*************************************************************************************/\n\t/*************************************************************************************/\n\t/*********************** COE AND TLE INITIALIZE: surface *****************************/\n\t/*************************************************************************************/\n\t/*************************************************************************************/\n\n\tif (iDebugLevel >= 1){\n\t  if (iProc == 0) printf(\"-- (initialize_constellation) Initializing the geometry.\\n\");\n\t}\n\n\tfor (sss = 0; sss < OPTIONS->n_surfaces; sss++){\n\n\t  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface[sss].area                  = OPTIONS->surface[sss].area / (1e10);\n\n\t  // !!!!!!!!!!!!!!!!!! TO ERASE\n\t  /* if (ii == 3 || ii == 7){ */\n\t  /*   \tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface[8].area                  = 5000.0 / (1e10); */\n\t  /* } */\n\t  // !!!!!!!!!!!!!!!!!! END OF TO ERASE\n\n\t  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface[sss].area_solar_panel      = OPTIONS->surface[sss].area_solar_panel / (1e10);\n\t  /*************************************************************************************/\n\t  /*********************** COE AND TLE INITIALIZE: ensembles on Cd *****************************/\n\t  /*************************************************************************************/\n\t  if (OPTIONS->nb_ensembles_cd > 0){ // if we run ensembles on Cd\n\t    if (eee == 0){\n\t      CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface[sss].Cd = OPTIONS->surface[sss].Cd * OPTIONS->cd_modification[ii];\n\t    }\n\t    else{\n\t      CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface[sss].Cd = randn( OPTIONS->surface[sss].Cd * OPTIONS->cd_modification[ii], OPTIONS->surface[sss].Cd_sigma);\n\t      //\t    \t    CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface[sss].Cd = OPTIONS->surface[sss].Cd * 2 * eee;  // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ERASE THIS LINE AND UNCOMMENT THE PREVIOUS ONE!!!\n\t    }\n\t\n\t  } // end of if we run ensembles on Cd\n\t  else{ // if we do not run ensembles on Cd\n\t    // new cd\n\t    if (OPTIONS->new_cd == 1){\n\t    CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface[sss].acco_coeff  = \n\t      OPTIONS->surface[sss].acco_coeff;        \n\t    }\n\t    else{\n\n\t    CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface[sss].Cd  =\n\t      OPTIONS->surface[sss].Cd * OPTIONS->cd_modification[ii];           // Coefficient of drag\n\t    }\n\t    // end of new cd\n\t    // !!!!!!!!!!!!!!!!!!!!!!!! ERASE THIS BLOCK BELOW\n\t    //if ( ( ii == 2 ) || ( ii == 7 ) ){\n\t    //CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface[sss].Cd                    = OPTIONS->surface[sss].Cd*6;\n\t    //}\n\t    // !!!!!!!!!!!!!!!!!!!!!!!! END OF ERASE THIS BLOCK BELOW\n\n\t  }// end of if we do not run ensembles on Cd\n\n\t  // !!!!!!!!!!! THIS BLOCK IS USING THE EQUATION FROM STK (http://www.agi.com/resources/help/online/stk/10.1/index.html?page=source%2Fhpop%2Fhpop-05.htm). UNCOMMENT THE BLOCK BELOW THAT USES VALLADO AND COMMENT THIS STK BLOCK IF YOU WANT TO USE VALLADO'S EQUATIONS. ALSO NEED TO CHANGE initialize_constellation.c AND load_options.c TO READ THE SPECULAR AND DIFFUSE REFLECIVITIES IF YOU WANT TO USE VALLADO'S EQUATIONS (SEE COMMENTS IN THESE CODES)\n\t  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface[sss].solar_radiation_coefficient  = OPTIONS->surface[sss].solar_radiation_coefficient;\n\t  // !!!!!!!!!!! END OF THIS BLOCK IS USING THE EQUATION FROM STK (http://www.agi.com/resources/help/online/stk/10.1/index.html?page=source%2Fhpop%2Fhpop-05.htm). UNCOMMENT THE BLOCK BELOW THAT USES VALLADO AND COMMENT THIS STK BLOCK IF YOU WANT TO USE VALLADO'S EQUATIONS. ALSO NEED TO CHANGE initialize_constellation.c AND load_options.c TO READ THE SPECULAR AND DIFFUSE REFLECIVITIES IF YOU WANT TO USE VALLADO'S EQUATIONS (SEE COMMENTS IN THESE CODES)\n\t  // !!!!!!!!!! THIS BLOCK USES VALLADO'S EQUATIONS. COMMENT IT AND UNCOMMENT THE BLOCK ABOVE THAT USES STK IF YOU WANT TO USE STK'S EQUATIONS. ALSO NEED TO CHANGE initialize_constellation.c AND load_options.c TO READ THE SPECULAR AND DIFFUSE REFLECIVITIES IF YOU WANT TO USE VALLADO'S EQUATIONS (SEE COMMENTS IN THESE CODES)\n\t  /* CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface[sss].specular_reflectivity = OPTIONS->surface[sss].specular_reflectivity; */\n\t  /* CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface[sss].diffuse_reflectivity  = OPTIONS->surface[sss].diffuse_reflectivity; */\n\t  // !!!!!!!!!! END OF THIS BLOCK USES VALLADO'S EQUATIONS. COMMENT IT AND UNCOMMENT THE BLOCK ABOVE THAT USES STK IF YOU WANT TO USE STK'S EQUATIONS. ALSO NEED TO CHANGE initialize_constellation.c AND load_options.c TO READ THE SPECULAR AND DIFFUSE REFLECIVITIES IF YOU WANT TO USE VALLADO'S EQUATIONS (SEE COMMENTS IN THESE CODES)\n\n\t  strcpy(CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface[sss].name_of_surface, OPTIONS->surface[sss].name_of_surface); //\n\n\t  for (nnn = 0; nnn < 3; nnn++){\n\t    CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface[sss].normal[nnn]         = OPTIONS->surface[sss].normal[nnn];           // normal vector in the SC reference system\n\t  }\n\t}\n\tfor (sss = 0; sss < OPTIONS->n_surfaces_eff; sss++){\n\n\t  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface_eff[sss].area                  = OPTIONS->surface_eff[sss].area / (1e10);\n\n\t  // !!!!!!!!!!!!!!!!!! TO ERASE\n\t  /* if (ii == 3 || ii == 7){ */\n\t  /*   \tCONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface[8].area                  = 5000.0 / (1e10); */\n\t  /* } */\n\t  // !!!!!!!!!!!!!!!!!! END OF TO ERASE\n\n\n\t  /*************************************************************************************/\n\t  /*********************** COE AND TLE INITIALIZE: ensembles on Cd *****************************/\n\t  /*************************************************************************************/\n\t  if (OPTIONS->nb_ensembles_cd > 0){ // if we run ensembles on Cd\n\t    if (eee == 0){\n\t      CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface_eff[sss].Cd = OPTIONS->surface[0].Cd * OPTIONS->cd_modification[ii]; // !!!!!!!!! assumes that for all effective have the same cd\n\t    }\n\t    else{\n\t      CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface_eff[sss].Cd = randn( OPTIONS->surface[0].Cd * OPTIONS->cd_modification[ii], OPTIONS->surface[0].Cd_sigma); // !!!!!!!!! assumes that for all effective have the same cd\n\t      //\t    \t    CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface[sss].Cd = OPTIONS->surface[sss].Cd * 2 * eee;  // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ERASE THIS LINE AND UNCOMMENT THE PREVIOUS ONE!!!\n\t    }\n\t\n\t  } // end of if we run ensembles on Cd\n\t  else{ // if we do not run ensembles on Cd\n\t    // new cd\n\t    if (OPTIONS->new_cd == 1){\n\t    CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface_eff[sss].acco_coeff  = \n\t      OPTIONS->surface[0].acco_coeff;        // !!!!!!!!! assumes that for all effective have the same acco_coeff\n\t    }\n\t    else{\n\n\t    CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface_eff[sss].Cd  =\n\t      OPTIONS->surface[0].Cd * OPTIONS->cd_modification[ii];           // Coefficient of drag\n\t    }\n\t    // end of new cd\n\t    // !!!!!!!!!!!!!!!!!!!!!!!! ERASE THIS BLOCK BELOW\n\t    //if ( ( ii == 2 ) || ( ii == 7 ) ){\n\t    //CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface[sss].Cd                    = OPTIONS->surface[sss].Cd*6;\n\t    //}\n\t    // !!!!!!!!!!!!!!!!!!!!!!!! END OF ERASE THIS BLOCK BELOW\n\n\t  }// end of if we do not run ensembles on Cd\n\n\t  // !!!!!!!!!!! THIS BLOCK IS USING THE EQUATION FROM STK (http://www.agi.com/resources/help/online/stk/10.1/index.html?page=source%2Fhpop%2Fhpop-05.htm). UNCOMMENT THE BLOCK BELOW THAT USES VALLADO AND COMMENT THIS STK BLOCK IF YOU WANT TO USE VALLADO'S EQUATIONS. ALSO NEED TO CHANGE initialize_constellation.c AND load_options.c TO READ THE SPECULAR AND DIFFUSE REFLECIVITIES IF YOU WANT TO USE VALLADO'S EQUATIONS (SEE COMMENTS IN THESE CODES)\n\t  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface_eff[sss].solar_radiation_coefficient  = OPTIONS->surface[0].solar_radiation_coefficient; // !!!!!!!!! assumes that for all effective have the same solar_radiation_coefficient\n\t  // !!!!!!!!!!! END OF THIS BLOCK IS USING THE EQUATION FROM STK (http://www.agi.com/resources/help/online/stk/10.1/index.html?page=source%2Fhpop%2Fhpop-05.htm). UNCOMMENT THE BLOCK BELOW THAT USES VALLADO AND COMMENT THIS STK BLOCK IF YOU WANT TO USE VALLADO'S EQUATIONS. ALSO NEED TO CHANGE initialize_constellation.c AND load_options.c TO READ THE SPECULAR AND DIFFUSE REFLECIVITIES IF YOU WANT TO USE VALLADO'S EQUATIONS (SEE COMMENTS IN THESE CODES)\n\t  // !!!!!!!!!! THIS BLOCK USES VALLADO'S EQUATIONS. COMMENT IT AND UNCOMMENT THE BLOCK ABOVE THAT USES STK IF YOU WANT TO USE STK'S EQUATIONS. ALSO NEED TO CHANGE initialize_constellation.c AND load_options.c TO READ THE SPECULAR AND DIFFUSE REFLECIVITIES IF YOU WANT TO USE VALLADO'S EQUATIONS (SEE COMMENTS IN THESE CODES)\n\t  /* CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface[sss].specular_reflectivity = OPTIONS->surface[sss].specular_reflectivity; */\n\t  /* CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface[sss].diffuse_reflectivity  = OPTIONS->surface[sss].diffuse_reflectivity; */\n\t  // !!!!!!!!!! END OF THIS BLOCK USES VALLADO'S EQUATIONS. COMMENT IT AND UNCOMMENT THE BLOCK ABOVE THAT USES STK IF YOU WANT TO USE STK'S EQUATIONS. ALSO NEED TO CHANGE initialize_constellation.c AND load_options.c TO READ THE SPECULAR AND DIFFUSE REFLECIVITIES IF YOU WANT TO USE VALLADO'S EQUATIONS (SEE COMMENTS IN THESE CODES)\n\n\t  strcpy(CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface_eff[sss].name_of_surface, \"Area effective - ignore name\"); //\n\n\t  for (nnn = 0; nnn < 3; nnn++){\n\t    CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface_eff[sss].normal[nnn]         = OPTIONS->surface_eff[sss].normal[nnn];           // normal vector in the SC reference system\n\t  }\n\t} // end of surface effective\n\t\n  if (OPTIONS->opengl == 1){\n  \n    CONSTELLATION->area_attitude_opengl_phi0 = OPTIONS->area_attitude_opengl_phi0;\n  CONSTELLATION->area_attitude_opengl_theta0 = OPTIONS->area_attitude_opengl_theta0;\n  CONSTELLATION->area_attitude_opengl_dtheta = OPTIONS->area_attitude_opengl_dtheta;\n  CONSTELLATION->area_attitude_opengl_dphi = OPTIONS->area_attitude_opengl_dphi;\n\n  int nb_phi, nb_theta;\n  nb_theta = (int)((180 - CONSTELLATION->area_attitude_opengl_theta0) / CONSTELLATION->area_attitude_opengl_dtheta ) + 1;// 180 is included (because different from theta = 0)    \n  nb_phi = (int)((360 - CONSTELLATION->area_attitude_opengl_phi0) / CONSTELLATION->area_attitude_opengl_dphi ) ; // 360 is not included (because same as phi = 0)\n\n\n  CONSTELLATION->area_attitude_opengl = NULL;\n  CONSTELLATION->area_attitude_opengl = malloc(nb_theta * sizeof(double **));\n  if ( CONSTELLATION->area_attitude_opengl == NULL){\n    printf(\"***! Could not allow memory to CONSTELLATION->area_attitude_opengl. The program will stop. !***\\n\"); MPI_Finalize(); exit(0);\n  }\n\n  CONSTELLATION->which_face_theta_phi = NULL;\n  CONSTELLATION->which_face_theta_phi = malloc(nb_theta * sizeof(int **));\n  if ( CONSTELLATION->which_face_theta_phi == NULL){\n    printf(\"***! Could not allow memory to CONSTELLATION->which_face_theta_phi. The program will stop. !***\\n\"); MPI_Finalize(); exit(0);\n  }\n\n\n  CONSTELLATION->area_attitude_opengl_total = NULL;\n  CONSTELLATION->area_attitude_opengl_total = malloc(nb_theta * sizeof(double *));\n  if ( CONSTELLATION->area_attitude_opengl_total == NULL){\n    printf(\"***! Could not allow memory to CONSTELLATION->area_attitude_opengl_total. The program will stop. !***\\n\"); MPI_Finalize(); exit(0);\n  }\n\n  if (( OPTIONS->solar_cell_efficiency != -1) && (OPTIONS->opengl_power == 1)){\n    CONSTELLATION->area_solar_panel_attitude_opengl = NULL;\n  CONSTELLATION->area_solar_panel_attitude_opengl = malloc(nb_theta * sizeof(double *));\n  if ( CONSTELLATION->area_solar_panel_attitude_opengl == NULL){\n    printf(\"***! Could not allow memory to CONSTELLATION->area_solar_panel_attitude_opengl. The program will stop. !***\\n\"); MPI_Finalize(); exit(0);\n  }\n  }\n\n\n  CONSTELLATION->nb_faces = OPTIONS->nb_faces;\n  CONSTELLATION->nb_faces_theta_phi = NULL;\n  CONSTELLATION->nb_faces_theta_phi = malloc(nb_theta * sizeof(double *));\n  if ( CONSTELLATION->nb_faces_theta_phi == NULL){\n    printf(\"***! Could not allow memory to CONSTELLATION->nb_faces_theta_phi. The program will stop. !***\\n\"); MPI_Finalize(); exit(0);\n  }\n\n  CONSTELLATION->normal_face = NULL;\n  CONSTELLATION->normal_face = malloc(OPTIONS->nb_faces * sizeof(double *));\n  if ( CONSTELLATION->normal_face == NULL){\n    printf(\"***! Could not allow memory to CONSTELLATION->normal_face. The program will stop. !***\\n\"); MPI_Finalize(); exit(0);\n  }\n\n  int itheta, iphi, iface, iface_here;\n  for (iface = 0; iface < OPTIONS->nb_faces; iface++){\n    CONSTELLATION->normal_face[iface] = malloc(3 * sizeof(double));\n    if ( CONSTELLATION->normal_face[iface] == NULL){\n      printf(\"***! Could not allow memory to CONSTELLATION->normal_face[iface]. The program will stop. !***\\n\"); MPI_Finalize(); exit(0);\n    }\n    CONSTELLATION->normal_face[iface][0] = OPTIONS->normal_face[iface][0];\n    CONSTELLATION->normal_face[iface][1] = OPTIONS->normal_face[iface][1];\n    CONSTELLATION->normal_face[iface][2] = OPTIONS->normal_face[iface][2];\n  }\n  \n  for (itheta = 0; itheta < nb_theta; itheta++){\n    CONSTELLATION->area_attitude_opengl[itheta] = malloc(nb_phi * sizeof(double *));\n  if ( CONSTELLATION->area_attitude_opengl[itheta] == NULL){\n    printf(\"***! Could not allow memory to CONSTELLATION->area_attitude_opengl[itheta]. The program will stop. !***\\n\"); MPI_Finalize(); exit(0);\n  }\n    CONSTELLATION->which_face_theta_phi[itheta] = malloc(nb_phi * sizeof(int *));\n  if ( CONSTELLATION->which_face_theta_phi[itheta] == NULL){\n    printf(\"***! Could not allow memory to CONSTELLATION->which_face_theta_phi[itheta]. The program will stop. !***\\n\"); MPI_Finalize(); exit(0);\n  }\n\n\n    CONSTELLATION->nb_faces_theta_phi[itheta] = malloc(nb_phi * sizeof(double));\n  if ( CONSTELLATION->nb_faces_theta_phi[itheta] == NULL){\n    printf(\"***! Could not allow memory to CONSTELLATION->nb_faces_theta_phi[itheta]. The program will stop. !***\\n\"); MPI_Finalize(); exit(0);\n  }\n\n\n\n    CONSTELLATION->area_attitude_opengl_total[itheta] = malloc(nb_phi * sizeof(double));\n  if ( CONSTELLATION->area_attitude_opengl_total[itheta] == NULL){\n    printf(\"***! Could not allow memory to CONSTELLATION->area_attitude_opengl_total[itheta]. The program will stop. !***\\n\"); MPI_Finalize(); exit(0);\n  }\n\n  if (( OPTIONS->solar_cell_efficiency != -1) && (OPTIONS->opengl_power == 1)){\n    CONSTELLATION->area_solar_panel_attitude_opengl[itheta] = malloc(nb_phi * sizeof(double));\n  if ( CONSTELLATION->area_solar_panel_attitude_opengl[itheta] == NULL){\n    printf(\"***! Could not allow memory to CONSTELLATION->area_solar_panel_attitude_opengl[itheta]. The program will stop. !***\\n\"); MPI_Finalize(); exit(0);\n  }\n  }\n\n    for (iphi = 0; iphi < nb_phi; iphi++){\n      CONSTELLATION->nb_faces_theta_phi[itheta][iphi]  = OPTIONS->nb_faces_theta_phi[itheta][iphi];\n      CONSTELLATION->area_attitude_opengl[itheta][iphi] = malloc(OPTIONS->nb_faces * sizeof(double)); \n      CONSTELLATION->which_face_theta_phi[itheta][iphi] = malloc(OPTIONS->nb_faces * sizeof(int)); \n  CONSTELLATION->area_attitude_opengl_total[itheta][iphi] = OPTIONS->area_attitude_opengl_total[itheta][iphi] / (1e10);\n\n  if (( OPTIONS->solar_cell_efficiency != -1) && (OPTIONS->opengl_power == 1)){\n    CONSTELLATION->area_solar_panel_attitude_opengl[itheta][iphi] = OPTIONS->area_solar_panel_attitude_opengl[itheta][iphi]/ (1e10);\n  }\n\n      for (iface = 0; iface < OPTIONS->nb_faces_theta_phi[itheta][iphi]; iface++){\n\tiface_here = OPTIONS->which_face_theta_phi[itheta][iphi][iface];\n\tCONSTELLATION->area_attitude_opengl[itheta][iphi][iface_here] = OPTIONS->area_attitude_opengl[itheta][iphi][iface_here] / (1e10);  // OPTIONS->area_attitude_opengl is in cm^2. Convert it here to km^2\n\tCONSTELLATION->which_face_theta_phi[itheta][iphi][iface] = OPTIONS->which_face_theta_phi[itheta][iphi][iface] ;\n      }\n    }\n  }\n\n  \n\n\n/*   for (itheta = 0; itheta < nb_theta; itheta++){ */\n/*     for (iphi = 0; iphi < nb_phi; iphi++){ */\n/*       printf(\"# %f %f %d\\n\", itheta * CONSTELLATION->area_attitude_opengl_dtheta + CONSTELLATION->area_attitude_opengl_theta0, iphi * CONSTELLATION->area_attitude_opengl_dphi + CONSTELLATION->area_attitude_opengl_phi0, CONSTELLATION->nb_faces_theta_phi[itheta][iphi]); */\n/*       for (iface = 0; iface < CONSTELLATION->nb_faces_theta_phi[itheta][iphi]; iface++){ */\n/* \tiface_here = CONSTELLATION->which_face_theta_phi[itheta][iphi][iface]; */\n/* \t  printf(\"%d %f\\n\", iface_here, CONSTELLATION->area_attitude_opengl[itheta][iphi][iface_here]*1e10); */\n/*       } */\n/*       printf(\"%f\\n\", CONSTELLATION->area_attitude_opengl_total[itheta][iphi]*1e10); */\n/*     } */\n/*   } */\n//  exitf();  \n\n\n\n/*   for (itheta = 0; itheta < nb_theta; itheta++){ */\n/*     for (iphi = 0; iphi < nb_phi; iphi++){ */\n/*             printf(\"ddd # %f %f %f\\n\", itheta * OPTIONS->area_attitude_opengl_dtheta + OPTIONS->area_attitude_opengl_theta0, iphi * OPTIONS->area_attitude_opengl_dphi + OPTIONS->area_attitude_opengl_phi0, OPTIONS->area_solar_panel_attitude_opengl[itheta][iphi]); */\n/*     } */\n/*   } */\n/*   exitf(); */\n\n  }\n\n\tif (iDebugLevel >= 1){\n\t  if (iProc == 0) printf(\"-- (initialize_constellation) Done initializing the geometry.\\n\");\n\t}\n\n\t/*************************************************************************************/\n\t/*************************************************************************************/\n\t/********************* END OF COE AND TLE INITIALIZE: surface ************************/\n\t/*************************************************************************************/\n\t/*************************************************************************************/\n\t//      printf(\"iProc: %d | eee = %d | from %d to %d | ii = %d\\n\", iProc, eee, start_ensemble_bis + iProc * OPTIONS->nb_ensemble_min_per_proc, iProc * OPTIONS->nb_ensemble_min_per_proc + OPTIONS->nb_ensemble_min_per_proc, ii);\n\n\n// the conversion of the acceleration from inrtl to lvlh is done in propagate_spacecraft but if init_flag = 1 the function propagate_spacecraft has not been called yet so the conversion inrtl to lvlh has not been done. Actually, the acceleration in the inertial frame has not been calculated yet either because it's calculated in propagate_spacecraft (with compute_dxdt)\n      double v_dummy[3];\n      double test_density;\n\n      if (eee == 0){\n\n\tCONSTELLATION->spacecraft[ii][0].INTEGRATOR.file_given_output = fopen( CONSTELLATION->spacecraft[ii][0].INTEGRATOR.filename_given_output, \"w+\" );\n      }\n      CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.write_given_output = 1;\n      //      printf(\"iProc %d start_ensemble[%d (%d)]: %d | dxdt\\n\", iProc, ii, eee, start_ensemble[ii]);\n\n  // the only case where the attitute needs to be set is  if there is no ensemble at all run on the attitude\n  if ( ( strcmp(OPTIONS->attitude_profile, \"ensemble_angular_velocity\") != 0 ) && ( strcmp(OPTIONS->attitude_profile, \"ensemble_initial_attitude\") != 0 ) ) { // if we do not run ensembles on the initial angular velocity\n\n    if (OPTIONS->nb_ensembles_attitude <= 0){ // if we dont' run ensembles of any kind on the attitude\n\n      if ( ( CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.solar_cell_efficiency != -1) || (GROUND_STATION->nb_ground_stations > 0) || ( CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.include_solar_pressure == 1) || ( CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.include_earth_pressure == 1)  || ( CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.include_drag == 1) ){ // these are the case where SpOCK uses the attitude\n\n\tif ( CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.isGPS == 0){ // no attitude to set up for GPS because we dont compute the drag, solar rariatin pressu,re, power, and gorund station coverage (attitude is needed for coverage because we calculate azimuth and levation angles form the spaceecraft reference system)\n\t  \n\t  set_attitude( CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude,  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.index_in_attitude_interpolated, OPTIONS,  CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.file_is_quaternion);\n\n\t}\n      }\n    }\n  }\n  // end of if the only case where the attitute needs to be set is the only case where it has not been set initially in initialize_constellation, which is if there is no ensemble at all run on the attitude\n\n      compute_dxdt( v_dummy, CONSTELLATION->spacecraft[ii][eee].a_i2cg_INRTL, &CONSTELLATION->spacecraft[ii][eee].et, CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL, CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL, PARAMS, &CONSTELLATION->spacecraft[ii][eee].INTEGRATOR, et_initial_epoch, OPTIONS->et_oldest_tle_epoch, &test_density, CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.index_in_attitude_interpolated, CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.index_in_driver_interpolated, CONSTELLATION, OPTIONS, iProc, iDebugLevel, &CONSTELLATION->spacecraft[ii][eee]);\n\n      double T_inrtl_2_lvlh[3][3];\n  compute_T_inrtl_2_lvlh(T_inrtl_2_lvlh, CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL, CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL);\n  m_x_v(CONSTELLATION->spacecraft[ii][eee].a_i2cg_LVLH, T_inrtl_2_lvlh, CONSTELLATION->spacecraft[ii][eee].a_i2cg_INRTL);\n\n\t\n      } // end of if main sc ii is run by this iProc OR  ( if this main sc is not run by this iProc and eee corresponds to an ensemble sc\n\n /* printf(\"%d\\n\", CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.nb_surfaces_eff); */\n /*  for (sss = 0; sss < CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.nb_surfaces_eff; sss++){ */\n /*    printf(\"normal[%d]: (%f, %f, %f) | total area: %f\\n\", sss, CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface_eff[sss].normal[0], CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface_eff[sss].normal[1], CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface_eff[sss].normal[2], CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface_eff[sss].area*1e10); */\n /*  } */\n /*  exitf(); */\n \n      \n    } // end go through all sc (including ensembels, if you run ensembles) other than GPS\n\n    if (write_attitude_file == 1){\n      fclose(file_attitude[ii]);\n    }\n    \n\n/* // the conversion of the acceleration from inrtl to lvlh is done in propagate_spacecraft but if init_flag = 1 the function propagate_spacecraft has not been called yet so the conversion inrtl to lvlh has not been done. Actually, the acceleration in the inertial frame has not been calculated yet either because it's calculated in propagate_spacecraft (with compute_dxdt) */\n/*       double v_dummy[3]; */\n/*       double test_density; */\n\n/*       if (eee == 0){ */\n\n/* \tCONSTELLATION->spacecraft[ii][0].INTEGRATOR.file_given_output = fopen( CONSTELLATION->spacecraft[ii][0].INTEGRATOR.filename_given_output, \"w+\" ); */\n/*       } */\n/*       CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.write_given_output = 1; */\n/*       printf(\"iProc %d start_ensemble[%d (%d)]: %d | dxdt\\n\", iProc, ii, eee, start_ensemble[ii]); */\n/*       compute_dxdt( v_dummy, CONSTELLATION->spacecraft[ii][eee].a_i2cg_INRTL, &CONSTELLATION->spacecraft[ii][eee].et, CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL, CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL, PARAMS, &CONSTELLATION->spacecraft[ii][eee].INTEGRATOR, et_initial_epoch, OPTIONS->et_oldest_tle_epoch, &test_density, CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.index_in_attitude_interpolated, CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.index_in_driver_interpolated, CONSTELLATION, OPTIONS, iProc, iDebugLevel, &CONSTELLATION->spacecraft[ii][eee]); */\n\n/*       double T_inrtl_2_lvlh[3][3]; */\n/*   compute_T_inrtl_2_lvlh(T_inrtl_2_lvlh, CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL, CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL); */\n/*   m_x_v(CONSTELLATION->spacecraft[ii][eee].a_i2cg_LVLH, T_inrtl_2_lvlh, CONSTELLATION->spacecraft[ii][eee].a_i2cg_INRTL); */\n\n    //  !!!!!!!!!!!!! below can be computed and printed only with  one iproc\n    if ((nProcs == 1) && (strcmp( OPTIONS->type_orbit_initialisation, \"collision_vcm\" ) == 0 )){\n    double std_r_alongtrack, std_r_crosstrack, std_r_radial, std_v_alongtrack, std_v_crosstrack, std_v_radial, std_bc, std_srp;\n    double mean_r_alongtrack, mean_r_crosstrack, mean_r_radial, mean_v_alongtrack, mean_v_crosstrack, mean_v_radial, mean_bc, mean_srp;\n\t     std_r_alongtrack =  gsl_stats_sd(r_alongtrack_all[ii], 1, ( OPTIONS->nb_ensembles_min  ) );\n\t     std_r_crosstrack =  gsl_stats_sd(r_crosstrack_all[ii], 1, ( OPTIONS->nb_ensembles_min  ) );\n\t     std_r_radial =  gsl_stats_sd(r_radial_all[ii], 1, ( OPTIONS->nb_ensembles_min  ) );\n\n\t     std_v_alongtrack =  gsl_stats_sd(v_alongtrack_all[ii], 1, ( OPTIONS->nb_ensembles_min  ) );\n\t     std_v_crosstrack =  gsl_stats_sd(v_crosstrack_all[ii], 1, ( OPTIONS->nb_ensembles_min  ) );\n\t     std_v_radial =  gsl_stats_sd(v_radial_all[ii], 1, ( OPTIONS->nb_ensembles_min  ) );\n\n\t     std_bc = gsl_stats_sd(bc_pert_all[ii], 1, ( OPTIONS->nb_ensembles_min  ) );\n\t     std_srp = gsl_stats_sd(srp_pert_all[ii], 1, ( OPTIONS->nb_ensembles_min  ) );\n\n\t     mean_r_alongtrack =  gsl_stats_mean(r_alongtrack_all[ii], 1, ( OPTIONS->nb_ensembles_min  ) );\n\t     mean_r_crosstrack =  gsl_stats_mean(r_crosstrack_all[ii], 1, ( OPTIONS->nb_ensembles_min  ) );\n\t     mean_r_radial =  gsl_stats_mean(r_radial_all[ii], 1, ( OPTIONS->nb_ensembles_min  ) );\n\n\t     mean_v_alongtrack =  gsl_stats_mean(v_alongtrack_all[ii], 1, ( OPTIONS->nb_ensembles_min  ) );\n\t     mean_v_crosstrack =  gsl_stats_mean(v_crosstrack_all[ii], 1, ( OPTIONS->nb_ensembles_min  ) );\n\t     mean_v_radial =  gsl_stats_mean(v_radial_all[ii], 1, ( OPTIONS->nb_ensembles_min  ) );\n\n\t     mean_bc = gsl_stats_mean(bc_pert_all[ii], 1, ( OPTIONS->nb_ensembles_min  ) );\n\t     mean_srp = gsl_stats_mean(srp_pert_all[ii], 1, ( OPTIONS->nb_ensembles_min  ) );\n\n\t     printf(\"\\nSC %d by iProc %d\\nSTD:\\n\",  ii, iProc);\n\t     printf(\"pos: %.4f (radial) %.4f (along) %.4f (cross) km\\n\", std_r_radial, std_r_alongtrack, std_r_crosstrack);\n\t     printf(\"vel: %.4e (radial) %.4e (along) %.4e (cross) km/s\\n\", std_v_radial, std_v_alongtrack, std_v_crosstrack );\n\t     //\t     printf(\"bc: %.4e (%.4e) | srp %.4e (%.4e) m2/kg\\n\", std_bc * 1e6, OPTIONS->bc_vcm[ii] * sqrt( OPTIONS->covariance_matrix_equinoctial[ii][6][6] ) , std_srp * 1e6 ,  OPTIONS->srp_vcm[ii] * sqrt( OPTIONS->covariance_matrix_equinoctial[ii][8][8] ) );  //i noticed that if the normalized variance in the vcm for bc or srp if very small (ie the std is very small compared to the mean vvalue) then my randm algoirthm can't compute distibutino to reprouce this very small std. it will run fine but the std will tend to be larger (by a factor 10 for sitnace). it deosnt really matter for wha ti want to do because if the std on bc is super small, its exact value doesnt matter too much (even by a factor 10)\n\n\t     printf(\"bc: %.4e (%.4e) | srp %.4e (%.4e) m2/kg\\n\", std_bc*std_bc * 1e12,  OPTIONS->bc_cdm_std[ii]*OPTIONS->bc_cdm_std[ii]  , std_srp*std_bc * 1e12 ,  OPTIONS->srp_cdm_std[ii] * OPTIONS->srp_cdm_std[ii] );  \n\n\t     printf(\"\\n MEAN:\\n\");\n\t     printf(\"pos: %.4e (radial) %.4e (along) %.4e (cross) m\\n\", mean_r_radial*1000, mean_r_alongtrack*1000, mean_r_crosstrack*1000);\n\t     printf(\"vel: %.4e (radial) %.4e (along) %.4e (cross) m/s\\n\", mean_v_radial*1000, mean_v_alongtrack*1000, mean_v_crosstrack*1000 );\n\t     //\t     printf(\"bc: %.4e (%.4e) | srp %.4e (%.4e) m2/kg\\n\", mean_bc * 1e6, OPTIONS->bc_vcm[ii] , mean_srp * 1e6 ,  OPTIONS->srp_vcm[ii]  );\n\t     printf(\"bc: %.4e (%.4e) | srp %.4e (%.4e) m2/kg\\n\", mean_bc * 1e6, OPTIONS->bc_cdm[ii] , mean_srp * 1e6 ,  OPTIONS->srp_cdm[ii]  );\n    }\n\n\n\n    \n  } // end of go through all main SC other than GPS\n\n\n  \n \n  /*************************************************************************************/\n  /*************************************************************************************/\n  /*************************************************************************************/\n  /*************************************************************************************/\n  /*************************************************************************************/\n  /*************************************** GPS *****************************************/\n  /*************************************************************************************/\n  /*************************************************************************************/\n  /*************************************************************************************/\n  /*************************************************************************************/\n  /*************************************************************************************/\n\n\n  if (iDebugLevel >= 1){\n    if (iProc == 0) printf(\"-- (initialize_constellation) Initializing the orbit for all GPS (%d GPS).\\n\", OPTIONS->nb_gps);\n  }\n\n\n  if (OPTIONS->nb_gps > 0){\n    gps_tle_file = fopen(OPTIONS->tle_constellation_gps_filename,\"r\");\n  }\n  \n\n  for (ii = OPTIONS->n_satellites - OPTIONS->nb_gps ; ii < OPTIONS->n_satellites; ii++){ // go over all GPS sc\n\n    CONSTELLATION->spacecraft[ii] = malloc( sizeof(SPACECRAFT_T) ); // no ensemble for GPS satellites\n    if ( start_ensemble[ii] == 0){ // if this iProc runs main sc ii  \n\n      CONSTELLATION->spacecraft[ii][0].INTEGRATOR.isGPS = 1;\n\n      /*** Convert the TLEs into inertial state (postion, velocity) ***/\n      SpiceInt frstyr = 1961; // do not really care about this line (as long as the spacecrafts are not flying after 2060)\n      //      SpiceDouble geophs[8];\n      int pp;\n      int lineln=0;\n      size_t len = 0;\n      char *line_temp = NULL;\n      //      SpiceDouble elems[10];\n      SpiceDouble state[6];      \n\n\n      if ( ii == iStart_save[iProc] ){\n\tfor (bbb = 0; bbb < ii - (OPTIONS->n_satellites - OPTIONS->nb_gps); bbb++){ // for the first time the iProc opens the TLE file, it needs to skip the TLEs of the GPS that it is not running\n\t  getline( &line_temp, &len, gps_tle_file ); \n\t  getline( &line_temp, &len, gps_tle_file );\n\t  getline( &line_temp, &len, gps_tle_file );\n\t}\n      }\n\n      /* /\\* Set up the geophysical quantities.  At last check these were the values used by Space Command and SGP4 *\\/ */\n      /* PARAMS->geophs[ 0 ] =    1.082616e-3;   // J2 */\n      /* PARAMS->geophs[ 1 ] =   -2.53881e-6;    // J3 */\n      /* PARAMS->geophs[ 2 ] =   -1.65597e-6;    // J4 */\n      /* PARAMS->geophs[ 3 ] =    7.43669161e-2; // KE */\n      /* PARAMS->geophs[ 4 ] =    120.0;         // QO */\n      /* PARAMS->geophs[ 5 ] =    78.0;          // SO */\n      /* PARAMS->geophs[ 6 ] =    6378.135;      // ER */\n      /* PARAMS->geophs[ 7 ] =    1.0;           // AE */\n\n      /* Read in the next two lines from the text file that contains the TLEs. */\n\n\n      // Skip the name of the GPS satellite that is being read\n      getline( &line_temp, &len, gps_tle_file );\n      //      printf(\"GPS %d by iProc %d:\\n<%s>\\n\",ii-(OPTIONS->n_satellites - OPTIONS->nb_gps),iProc , line_temp);\n      // First line\n      getline( &line_temp, &len, gps_tle_file );\n      lineln = strlen(line_temp)-1;\n      SpiceChar line[2][lineln];\n      for (pp = 0; pp<lineln-1 ; pp++)\n\tline[0][pp] = line_temp[pp];\n      line[0][ lineln-1 ] = '\\0';\n      // Second line\n      getline( &line_temp, &len, gps_tle_file );\n      for (pp = 0; pp<lineln-1 ; pp++)\n\tline[1][pp] = line_temp[pp];\n      line[1][ lineln-1 ] = '\\0';\n\n      // Convert the elements of the TLE into \"elems\" and \"epoch\" that can be then read by the SPICE routine ev2lin_ to convert into the inertial state\n      getelm_c( frstyr, lineln, line, &OPTIONS->epoch_gps[ii-(OPTIONS->n_satellites - OPTIONS->nb_gps )], CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.elems );\n      // Now propagate the state using ev2lin_ to the epoch of interest\n      extern /* Subroutine */ int ev2lin_(SpiceDouble *, SpiceDouble *,\n\t\t\t\t\t  SpiceDouble *, SpiceDouble *);\n\n      ev2lin_( &OPTIONS->epoch_gps[ii-(OPTIONS->n_satellites - OPTIONS->nb_gps )], PARAMS->geophs, CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.elems, state );\n\n            CONSTELLATION->spacecraft[ii][0].et = OPTIONS->epoch_gps[ii-(OPTIONS->n_satellites - OPTIONS->nb_gps )];\n      CONSTELLATION->spacecraft[ii][eee].et_sc_initial = OPTIONS->epoch_gps[ii-(OPTIONS->n_satellites - OPTIONS->nb_gps )];\n\n\t    static doublereal  precm[36];\n\t        static doublereal invprc[36]\t/* was [6][6] */;\n\t\t    extern /* Subroutine */ int zzteme_(doublereal *, doublereal *);\n\t\t        extern /* Subroutine */ int invstm_(doublereal *, doublereal *);\n\t\t\t    extern /* Subroutine */ int  mxvg_(\n\t    doublereal *, doublereal *, integer *, integer *, doublereal *);\n\n\t        zzteme_(&CONSTELLATION->spacecraft[ii][0].et, precm);\n\n/*     ...now convert STATE to J2000. Invert the state transformation */\n/*     operator (important to correctly do this). */\n\n    invstm_(precm, invprc);\n    static integer c__6 = 6;\n        static doublereal tmpsta[6];\n\t    mxvg_(invprc, state, &c__6, &c__6, tmpsta);\n    moved_(tmpsta, &c__6, state);\n\n\n      for (pp = 0; pp<3; pp++){\n\tCONSTELLATION->spacecraft[ii][0].r_i2cg_INRTL[pp] = state[pp];\n\tCONSTELLATION->spacecraft[ii][0].v_i2cg_INRTL[pp] = state[pp+3];\n      }\n\n      // Initialize the Keplerian Elements\n      ORBITAL_ELEMENTS_T OE_temp;\n      cart2kep( &OE_temp, CONSTELLATION->spacecraft[ii][0].r_i2cg_INRTL, CONSTELLATION->spacecraft[ii][0].v_i2cg_INRTL, CONSTELLATION->spacecraft[ii][0].et,  PARAMS->EARTH.GRAVITY.mu);\n\n\t    CONSTELLATION->spacecraft[ii][eee].OE.initial_an_to_sc = OE_temp.an_to_sc;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.w_ave_temp = OE_temp.w;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.w_ave = 9999.999999/RAD2DEG;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.sma_ave_temp = OE_temp.sma;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.sma_ave = 9999.999999;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.ecc_ave_temp = OE_temp.eccentricity;\n\t    CONSTELLATION->spacecraft[ii][eee].OE.ecc_ave = 9999.999999;\n\n\t    CONSTELLATION->spacecraft[ii][eee].OE.ave_increm = 1;\n\t    CONSTELLATION->spacecraft[ii][eee].et_last_orbit = CONSTELLATION->spacecraft[ii][eee].et;\n\t    CONSTELLATION->spacecraft[ii][eee].orbit_number = 0;\n\n\n      CONSTELLATION->spacecraft[ii][0].OE.sma          =OE_temp.sma;\n      CONSTELLATION->spacecraft[ii][0].OE.eccentricity =OE_temp.eccentricity;\n      CONSTELLATION->spacecraft[ii][0].OE.inclination  =OE_temp.inclination;\n      CONSTELLATION->spacecraft[ii][0].OE.long_an      =OE_temp.long_an;\n      CONSTELLATION->spacecraft[ii][0].OE.w            =OE_temp.w;\n      CONSTELLATION->spacecraft[ii][0].OE.f            =OE_temp.f;\n      CONSTELLATION->spacecraft[ii][0].OE.tp           =OE_temp.tp;\n      CONSTELLATION->spacecraft[ii][0].OE.E            =OE_temp.E;\n      CONSTELLATION->spacecraft[ii][0].OE.ra            =OE_temp.ra;\n\n      radius_perigee = CONSTELLATION->spacecraft[ii][0].OE.sma * ( 1 - CONSTELLATION->spacecraft[ii][0].OE.eccentricity );\n      if (radius_perigee < PARAMS->EARTH.radius){\n\tprintf(\"***! The orbit of satellite %d intersects the Earth (altitude of perigee = %f km). The program will stop. !***\\n\",ii, radius_perigee-PARAMS->EARTH.radius);\n\tMPI_Finalize();\n\texit(0);\n      }\n\n      //// !!!!!! WEIRD: In this block, I test if going back to cart then to kep gives the same OE. It does. BUT, the cart is different (meaning the next line finds different cart than the one calculated a bit above but still results in the same OE). The reason for that is still not clear and if has to be found in the future! Future tests will validate that these results are correct, though.\n      // Initialize the inertial state\n      /*       kep2cart(   CONSTELLATION->spacecraft[ii][0].r_i2cg_INRTL, CONSTELLATION->spacecraft[ii][0].v_i2cg_INRTL, */\n      /* \t\t  &PARAMS->EARTH.GRAVITY.mu, */\n      /* \t\t  &CONSTELLATION->spacecraft[ii][0].OE); // Computes the ECI coordinates based on the Keplerian inputs (orbital elements and mu) (in propagator.c) (CBV) */\n\n\n      /*       ORBITAL_ELEMENTS_T OE_temp2; */\n      /*       cart2kep( &OE_temp2, CONSTELLATION->spacecraft[ii][0].r_i2cg_INRTL, CONSTELLATION->spacecraft[ii][0].v_i2cg_INRTL, CONSTELLATION->spacecraft[ii][0].et ,  PARAMS->EARTH.GRAVITY.mu); */\n\n      /*       printf(\"\\nsma = %f | %f\\n\",CONSTELLATION->spacecraft[ii][0].OE.sma, OE_temp2.sma); */\n      /*       printf(\"inclination = %f | %f\\n\",CONSTELLATION->spacecraft[ii][0].OE.inclination*RAD2DEG, OE_temp2.inclination*RAD2DEG); */\n      /*       printf(\"eccentricity = %f | %f\\n\", CONSTELLATION->spacecraft[ii][0].OE.eccentricity, OE_temp2.eccentricity); */\n      /*       printf(\"long_an = %f | %f\\n\", CONSTELLATION->spacecraft[ii][0].OE.long_an, OE_temp2.long_an); */\n      /*       printf(\"w = %f | %f\\n\", CONSTELLATION->spacecraft[ii][0].OE.w*RAD2DEG, OE_temp2.w*RAD2DEG); */\n      /*       printf(\"tp = %f | %f\\n\", CONSTELLATION->spacecraft[ii][0].OE.tp, OE_temp2.tp); */\n      /*       printf(\"E = %f | %f\\n\", CONSTELLATION->spacecraft[ii][0].OE.E, OE_temp2.E); */\n\n\n/* \teci2lla(CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL , CONSTELLATION->spacecraft[ii][eee].et, geodetic ); */\n\t\n/* \tCONSTELLATION->spacecraft[ii][0].GEODETIC.altitude = geodetic[2]; */\n/* \tCONSTELLATION->spacecraft[ii][0].GEODETIC.latitude = geodetic[0]; */\n/* \tCONSTELLATION->spacecraft[ii][0].GEODETIC.longitude = geodetic[1];  */\n\n/* \t// Initialize the planet fixed state\t\t */\n\n/* \t  geodetic_to_geocentric(PARAMS->EARTH.flattening,             */\n/* \t\t\t\t CONSTELLATION->spacecraft[ii][0].GEODETIC.altitude, */\n/* \t\t\t\t CONSTELLATION->spacecraft[ii][0].GEODETIC.latitude, */\n/* \t\t\t\t CONSTELLATION->spacecraft[ii][0].GEODETIC.longitude, */\n/* \t\t\t\t PARAMS->EARTH.radius,        */\n/* \t\t\t\t CONSTELLATION->spacecraft[ii][0].r_ecef2cg_ECEF) ; */\n\n\n      // Initialize the planet fixed state\n      estate[0] = CONSTELLATION->spacecraft[ii][0].r_i2cg_INRTL[0];estate[1] = CONSTELLATION->spacecraft[ii][0].r_i2cg_INRTL[1];estate[2] = CONSTELLATION->spacecraft[ii][0].r_i2cg_INRTL[2];\n      estate[3] = CONSTELLATION->spacecraft[ii][0].v_i2cg_INRTL[0];estate[4] = CONSTELLATION->spacecraft[ii][0].v_i2cg_INRTL[1];estate[5] = CONSTELLATION->spacecraft[ii][0].v_i2cg_INRTL[2];\n      sxform_c (  \"J2000\", PARAMS->EARTH.earth_fixed_frame,  CONSTELLATION->spacecraft[ii][0].et,    xform  );\n      mxvg_c   (  xform,       estate,   6,  6, jstate );\n      CONSTELLATION->spacecraft[ii][0].r_ecef2cg_ECEF[0] = jstate[0]; CONSTELLATION->spacecraft[ii][0].r_ecef2cg_ECEF[1] = jstate[1]; CONSTELLATION->spacecraft[ii][0].r_ecef2cg_ECEF[2] = jstate[2];\n      CONSTELLATION->spacecraft[ii][0].v_ecef2cg_ECEF[0] = jstate[3]; CONSTELLATION->spacecraft[ii][0].v_ecef2cg_ECEF[1] = jstate[4]; CONSTELLATION->spacecraft[ii][0].v_ecef2cg_ECEF[2] = jstate[5];\n      /* pxform_c( \"J2000\", PARAMS->EARTH.earth_fixed_frame, CONSTELLATION->spacecraft[ii][0].et, T_J2000_to_ECEF); // Return the matrix (here T_J2000_to_ECEF) that transforms position vectors from one specified frame (here J2000) to another (here ITRF93) at a specified epoch  (in /Users/cbv/cspice/src/cspice/pxform_c.c) (CBV) */\n      /* m_x_v(CONSTELLATION->spacecraft[ii][0].r_ecef2cg_ECEF, T_J2000_to_ECEF, CONSTELLATION->spacecraft[ii][0].r_i2cg_INRTL); // multiply a matrix by a vector (in prop_math.c). So here we convert ECI (J2000) to ECEF coordinates (CBV) */\n        \n      // initialize the geodetic state-\n      geocentric_to_geodetic(\n\t\t\t     CONSTELLATION->spacecraft[ii][0].r_ecef2cg_ECEF,\n\t\t\t     &PARAMS->EARTH.radius,\n\t\t\t     &PARAMS->EARTH.flattening,\n\t\t\t     &CONSTELLATION->spacecraft[ii][0].GEODETIC.altitude,\n\t\t\t     &CONSTELLATION->spacecraft[ii][0].GEODETIC.latitude,\n\t\t\t     &CONSTELLATION->spacecraft[ii][0].GEODETIC.longitude ); // Computes lat/long/altitude based on ECEF coordinates and planet fixed state (planetary semimajor axis, flattening parameter) (in propagator.c) (CBV)\n        \n\n      // Output file for each spacecraft\n      strcpy(CONSTELLATION->spacecraft[ii][0].filename, OPTIONS->dir_output_run_name_sat_name[ii]);\n      strcat(CONSTELLATION->spacecraft[ii][0].filename, \"/\");\n      strcat(CONSTELLATION->spacecraft[ii][0].filename, OPTIONS->filename_output[ii]);\n    \n      // Now CONSTELLATION->spacecraft[ii][0].filenameecef is moved to generate_ephemerides because we want iProc 0 to know CONSTELLATION->spacecraft[ii][0].filenameecef even for the main sc ii that it does not run (this is because iProc 0 will gather all ECEF files at the end of the propagation)\n      /*     strcpy(CONSTELLATION->spacecraft[ii][0].filenameecef, OPTIONS->dir_output_run_name_sat_name[ii]); */\n      /*     strcat(CONSTELLATION->spacecraft[ii][0].filenameecef, \"/\"); */\n      /*     strcat(CONSTELLATION->spacecraft[ii][0].filenameecef, \"ECEF_\"); */\n      /*     strcat(CONSTELLATION->spacecraft[ii][0].filenameecef, OPTIONS->filename_output[ii]); */\n\n      strcpy(CONSTELLATION->spacecraft[ii][0].filenamerho, OPTIONS->dir_output_run_name_sat_name[ii]);\n      strcat(CONSTELLATION->spacecraft[ii][0].filenamerho, \"/\");\n      strcat(CONSTELLATION->spacecraft[ii][0].filenamerho, \"density_\");\n      strcat(CONSTELLATION->spacecraft[ii][0].filenamerho,OPTIONS->filename_output[ii]);\n\n\n      strcpy(CONSTELLATION->spacecraft[ii][0].filenameout, OPTIONS->dir_output_run_name_sat_name[ii]);\n      strcat(CONSTELLATION->spacecraft[ii][0].filenameout, \"/\");\n      strcat(CONSTELLATION->spacecraft[ii][0].filenameout, \"LLA_\");\n      strcat(CONSTELLATION->spacecraft[ii][0].filenameout,OPTIONS->filename_output[ii]);\n\n            strcpy(CONSTELLATION->spacecraft[ii][0].filenameatt, OPTIONS->dir_output_run_name_sat_name[ii]);\n      strcat(CONSTELLATION->spacecraft[ii][0].filenameatt, \"/\");\n      strcat(CONSTELLATION->spacecraft[ii][0].filenameatt, \"LLA_\");\n      strcat(CONSTELLATION->spacecraft[ii][0].filenameatt,OPTIONS->filename_output[ii]);\n\n      strcpy(CONSTELLATION->spacecraft[ii][0].filenamekalman, OPTIONS->dir_output_run_name_sat_name[ii]);\n      strcat(CONSTELLATION->spacecraft[ii][0].filenamekalman, \"/\");\n      strcat(CONSTELLATION->spacecraft[ii][0].filenamekalman, \"kalman_\");\n      strcat(CONSTELLATION->spacecraft[ii][0].filenamekalman,OPTIONS->filename_output[ii]);\n\n      strcpy(CONSTELLATION->spacecraft[ii][0].filenamekalman_meas, OPTIONS->dir_output_run_name_sat_name[ii]);\n      strcat(CONSTELLATION->spacecraft[ii][0].filenamekalman_meas, \"/\");\n      strcat(CONSTELLATION->spacecraft[ii][0].filenamekalman_meas, \"meas_converted_kalman_\");\n      strcat(CONSTELLATION->spacecraft[ii][0].filenamekalman_meas,OPTIONS->filename_output[ii]);\n      \n      strcpy(CONSTELLATION->spacecraft[ii][0].filename_kalman_init, OPTIONS->filename_kalman_init);\n      // I COMMENTED BELOW EBCAUSE I DON'T SEE ANY REASON TO COMPUTE THE GROUND STATION COVERAGE FOR GPS \n      /*     if (OPTIONS->nb_ground_stations > 0){ */\n      /*       for ( iground = 0; iground < OPTIONS->nb_ground_stations; iground ++){ */\n      /* \tstrcpy(CONSTELLATION->spacecraft[ii][0].filename_coverage_ground_station[iground], OPTIONS->dir_output_run_name_sat_name_coverage[ii]); */\n      /* \tstrcat(CONSTELLATION->spacecraft[ii][0].filename_coverage_ground_station[iground], \"/\"); */\n      /* \tstrcat(CONSTELLATION->spacecraft[ii][0].filename_coverage_ground_station[iground], OPTIONS->name_ground_station[iground]); */\n      /* \tstrcat(CONSTELLATION->spacecraft[ii][0].filename_coverage_ground_station[iground], \"_by_\"); */\n      /* \tstrcat(CONSTELLATION->spacecraft[ii][0].filename_coverage_ground_station[iground],OPTIONS->filename_output[ii]); */\n      /*       } */\n      /*     } */\n\n\n      // cbv COMMENTED THIS BLOCK ON APRIL 22 218 BECASESUE SOLAR POWER IS NOT COMPUTED FOR GPS\n/*       if (CONSTELLATION->spacecraft[ii][0].INTEGRATOR.solar_cell_efficiency != -1){ */\n/* \tstrcpy(CONSTELLATION->spacecraft[ii][0].filenamepower, OPTIONS->dir_output_run_name_sat_name[ii]); */\n/* \tstrcat(CONSTELLATION->spacecraft[ii][0].filenamepower, \"/\"); */\n/* \tstrcat(CONSTELLATION->spacecraft[ii][0].filenamepower, \"power_\"); */\n/* \tstrcat(CONSTELLATION->spacecraft[ii][0].filenamepower,OPTIONS->filename_output[ii]); */\n\n/* \tstrcpy(CONSTELLATION->spacecraft[ii][0].filenameeclipse, OPTIONS->dir_output_run_name_sat_name[ii]); */\n/* \tstrcat(CONSTELLATION->spacecraft[ii][0].filenameeclipse, \"/\"); */\n/* \tstrcat(CONSTELLATION->spacecraft[ii][0].filenameeclipse, \"eclipse_\"); */\n/* \tstrcat(CONSTELLATION->spacecraft[ii][0].filenameeclipse,OPTIONS->filename_output[ii]); */\n      \n/*       } */\n      // end of cbv COMMENTED THIS BLOCK ON APRIL 22 218 BECASESUE SOLAR POWER IS NOT COMPUTED FOR GPS\n\n      // Name of each satellite\n      strcpy(CONSTELLATION->spacecraft[ii][0].name_sat, \"\");\n      strcpy(CONSTELLATION->spacecraft[ii][0].name_sat, OPTIONS->gps_file_name[ii - (OPTIONS->n_satellites - OPTIONS->nb_gps)]);\n\n    \n      /*   // Compute the Orbital period of the first state */\n      /*       period = pow( CONSTELLATION->spacecraft[ii][0].OE.sma, 3.0); */\n      /*       period = period / PARAMS->EARTH.GRAVITY.mu; */\n      /*       period = 2.0 * M_PI * sqrt( period ); */\n    \n      // Integrator\n      CONSTELLATION->spacecraft[ii][0].INTEGRATOR.sc_main_nb = ii;\n      CONSTELLATION->spacecraft[ii][0].INTEGRATOR.sc_ensemble_nb = 0;\n\n      CONSTELLATION->spacecraft[ii][0].INTEGRATOR.dt            = OPTIONS->dt;\n      CONSTELLATION->spacecraft[ii][0].INTEGRATOR.dt_pos_neg            = OPTIONS->dt_pos_neg;\n      CONSTELLATION->spacecraft[ii][0].INTEGRATOR.nb_surfaces   = 1;\n      CONSTELLATION->spacecraft[ii][0].INTEGRATOR.nb_surfaces_eff   = 1;\n      CONSTELLATION->spacecraft[ii][0].INTEGRATOR.mass          = 1630.0; // Wikipedia...\n      CONSTELLATION->spacecraft[ii][0].INTEGRATOR.solar_cell_efficiency = -1; // do not care for now\n      CONSTELLATION->spacecraft[ii][0].INTEGRATOR.degree        = OPTIONS->degree;       // Gravity degree\n      CONSTELLATION->spacecraft[ii][0].INTEGRATOR.order         = OPTIONS->order;        // Gravity order\n      CONSTELLATION->spacecraft[ii][0].INTEGRATOR.include_drag  = 0;\n      CONSTELLATION->spacecraft[ii][0].INTEGRATOR.include_solar_pressure  = 0; // do not care for now\n            CONSTELLATION->spacecraft[ii][0].INTEGRATOR.include_earth_pressure  = 0; // do not care for now\n      CONSTELLATION->spacecraft[ii][0].INTEGRATOR.include_sun   = OPTIONS->include_sun;  // include Sun perturbations (CBV)\n      CONSTELLATION->spacecraft[ii][0].INTEGRATOR.include_moon  = OPTIONS->include_moon; // include Moon perturbations (CBV)\n      \n      CONSTELLATION->spacecraft[ii][0].INTEGRATOR.index_in_attitude_interpolated = 0; // do not care for now because the attitude is for the power, solar radiation pressure, earth_pressure, or drag. For GPS satellite, we do not compute these (the main reason is that the TLE do not give the geometry). However, we need to set it to 0 (like a regular spacecraft) because to compute coverage, the variable index_in_attitude_interpolated is used\n      CONSTELLATION->spacecraft[ii][0].INTEGRATOR.index_in_driver_interpolated = 0; // do not care for now because the attitude is for the power, solar radiation pressure, or drag. For GPS satellite, we do not compute these (the main reason is that the TLE do not give the geometry)\n\n\tCONSTELLATION->spacecraft[ii][0].INTEGRATOR.density_mod = OPTIONS->density_mod; // // the desnity given by msis is multiplied by density_mod + density_amp * sin(2*pi*t/T + density_phase*T) where T is the orbital period  \n\tCONSTELLATION->spacecraft[ii][0].INTEGRATOR.density_mod_amp = OPTIONS->density_mod_amp; \n\tCONSTELLATION->spacecraft[ii][0].INTEGRATOR.density_mod_phase = OPTIONS->density_mod_phase; \n\n    } // end of if this iProc runs main sc ii  \n  } // end of go over all GPS sc\n\n  if (OPTIONS->nb_gps > 0){\n    fclose(gps_tle_file);\n  }\n  if (iDebugLevel >= 1){\n    if (iProc == 0) printf(\"-- (initialize_constellation) Done initializing the orbit for all GPS (%d GPS).\\n\", OPTIONS->nb_gps);\n  }\n  \n  /* For the specular points computation */\n  if (OPTIONS->nb_gps > 0){\n\n    strcpy(CONSTELLATION->filename_CYGNSS_constellation_for_specular, OPTIONS->dir_output_run_name);\n    strcat(CONSTELLATION->filename_CYGNSS_constellation_for_specular, \"/CONSTELLATION_CYGNSS_for_run_\");\n    next = OPTIONS->filename_output[0];\n    find_file_name =  (int)(strchr(next, '.') - next);\n    strncat(CONSTELLATION->filename_CYGNSS_constellation_for_specular, next, find_file_name);\n    strcat(CONSTELLATION->filename_CYGNSS_constellation_for_specular, \".txt\");\n\n    strcpy(CONSTELLATION->filename_GPS_constellation_for_specular, OPTIONS->dir_output_run_name);\n    strcat(CONSTELLATION->filename_GPS_constellation_for_specular, \"/CONSTELLATION_GPS_for_run_\");\n    next = OPTIONS->filename_output[0];\n    find_file_name =  (int)(strchr(next, '.') - next);\n    strncat(CONSTELLATION->filename_GPS_constellation_for_specular, next, find_file_name);\n    strcat(CONSTELLATION->filename_GPS_constellation_for_specular, \".txt\");\n\n  }\n  /* end of for the specular points computation */\n\n\n\n  if (OPTIONS->nb_ground_stations > 0){\n    for (iground = 0; iground < OPTIONS->nb_ground_stations; iground++){\n      strcpy( GROUND_STATION->name_ground_station[iground], OPTIONS->name_ground_station[iground]);\n      GROUND_STATION->latitude_ground_station[iground] = OPTIONS->latitude_ground_station[iground] * DEG2RAD;\n      GROUND_STATION->longitude_ground_station[iground] = OPTIONS->longitude_ground_station[iground] * DEG2RAD;\n      GROUND_STATION->altitude_ground_station[iground] = OPTIONS->altitude_ground_station[iground];\n      GROUND_STATION->min_elevation_angle_ground_station[iground] = OPTIONS->min_elevation_angle_ground_station[iground] * DEG2RAD;\n      // Convert lla position of ground station into ECEF\n      geodetic_to_geocentric( PARAMS->EARTH.flattening, GROUND_STATION->altitude_ground_station[iground]/1000., GROUND_STATION->latitude_ground_station[iground], GROUND_STATION->longitude_ground_station[iground], PARAMS->EARTH.radius, GROUND_STATION->ecef_ground_station[iground]);\n\n    }\n    GROUND_STATION->nb_ground_stations = OPTIONS->nb_ground_stations;\n  }\n\n  /* if ( ( strcmp(OPTIONS->format_density_driver, \"density_file\") != 0 ) && ( strcmp(OPTIONS->format_density_driver, \"gitm\") != 0 ) ){ */\n  /*   if ( strcmp(OPTIONS->format_density_driver, \"dynamic\") == 0 ){  */\n\n  /*     /\\* free(OPTIONS->Ap); *\\/ */\n  /*     /\\* //\t    if (OPTIONS->use_ap_hist == 1){ *\\/ */\n  /*     /\\* free(OPTIONS->Ap_hist); *\\/ */\n  /*     /\\* //\t    } *\\/ */\n  /*     /\\* free(OPTIONS->f107); *\\/ */\n  /*     /\\* free(OPTIONS->f107A); *\\/ */\n\n  /*   } */\n  /* } */\n  /* else{ */\n  /*   free(OPTIONS->density); */\n  /* } */\n\n\n  /* free(OPTIONS->et_interpo); */\n  //    printf(\"uudpqw90jdwqdpwuuuuuu %f\\n\", CONSTELLATION->spacecraft[0][0].INTEGRATOR.attitude.pitch[0]);\n\n  return 0;\n\n\n}\n\n\n\ndouble randu ( double mu, double sigma) // source: http://phoxis.org/2013/05/04/plot-histogram-in-terminal/\n{\n  double U1;\n  struct timeval t1;\n  gettimeofday(&t1, NULL);\n  srand(t1.tv_usec * t1.tv_sec);\n\n  U1 = -1 + ((double) rand () / RAND_MAX) * 2;\n \n  return (mu + sigma * (double) U1);\n}\n\n\n\ndouble randn ( double mu, double sigma) // source: http://phoxis.org/2013/05/04/plot-histogram-in-terminal/\n{\n  double U1, U2, W, mult;\n  static double X1, X2;\n  static int call = 0;\n  struct timeval t1;\n  gettimeofday(&t1, NULL);\n  srand(t1.tv_usec * t1.tv_sec);\n  //\t  srand(time(NULL) + iProc); \n  if (call == 1)\n    {\n      call = !call;\n      return (mu + sigma * (double) X2);\n    }\n \n  do\n    {\n      U1 = -1 + ((double) rand () / RAND_MAX) * 2;\n      U2 = -1 + ((double) rand () / RAND_MAX) * 2;\n      W = pow (U1, 2) + pow (U2, 2);\n    }\n  while (W >= 1 || W == 0);\n \n  mult = sqrt ((-2 * log (W)) / W);\n  X1 = U1 * mult;\n  X2 = U2 * mult;\n \n  call = !call;\n \n  return (mu + sigma * (double) X1);\n}\n\n\ndouble randn_iproc (int iProc, double mu, double sigma) // source: http://phoxis.org/2013/05/04/plot-histogram-in-terminal/\n// note: the only difference with rand is that the seed here depends on iProc (the seed should actually also depends on iProcs in rand because it depends on the time with microsecond accuracy so each iProcs calls it at a different time)\n{\n  double U1, U2, W, mult;\n  static double X1, X2;\n  static int call = 0;\n  struct timeval t1;\n  gettimeofday(&t1, NULL);\n  srand(t1.tv_usec * t1.tv_sec + iProc);\n  //\t  srand(time(NULL) + iProc); \n  if (call == 1)\n    {\n      call = !call;\n      return (mu + sigma * (double) X2);\n    }\n \n  do\n    {\n      U1 = -1 + ((double) rand () / RAND_MAX) * 2;\n      U2 = -1 + ((double) rand () / RAND_MAX) * 2;\n      W = pow (U1, 2) + pow (U2, 2);\n    }\n  while (W >= 1 || W == 0);\n \n  mult = sqrt ((-2 * log (W)) / W);\n  X1 = U1 * mult;\n  X2 = U2 * mult;\n \n  call = !call;\n \n  return (mu + sigma * (double) X1);\n}\n\n\nint sign(double x){\n  if (x > 0) return 1;\n  if (x < 0) return -1;\n  return 0;\n}\n\n\n\n/*  LocalWords:  min\n */\n", "meta": {"hexsha": "8a87da88bbc6befd1754c4c55a6162206ca3934f", "size": 214819, "ext": "c", "lang": "C", "max_stars_repo_path": "src/initialize_constellation.c", "max_stars_repo_name": "splowitz1/spock-1", "max_stars_repo_head_hexsha": "855e5af02564a07118716ea8cb0b37f0a992df7b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-12-07T08:44:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-15T18:13:51.000Z", "max_issues_repo_path": "src/initialize_constellation.c", "max_issues_repo_name": "splowitz1/spock-1", "max_issues_repo_head_hexsha": "855e5af02564a07118716ea8cb0b37f0a992df7b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/initialize_constellation.c", "max_forks_repo_name": "splowitz1/spock-1", "max_forks_repo_head_hexsha": "855e5af02564a07118716ea8cb0b37f0a992df7b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-04-09T15:55:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-23T10:31:06.000Z", "avg_line_length": 66.4046367852, "max_line_length": 712, "alphanum_fraction": 0.6549094819, "num_tokens": 61609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38861802670584894, "lm_q2_score": 0.026759280662960457, "lm_q1q2_score": 0.010399138847307674}}
{"text": "#ifndef RECTREE_H\n#define RECTREE_H\n#include \"tree.h\"\n#include \"recedge.h\"\n#include \"weakarg.h\"\n#include \"mpiutils.h\"\n#include \"wargxml.h\"\n\n#include <gsl/gsl_randist.h>\n#define MAXNODES 100000\n\nusing namespace std;\n\nnamespace weakarg\n{\n\nclass Param;\n\n/**\n    @brief Recombinant tree using Tree class\n*/\n\nclass RecTree:public Tree\n{\n    friend class RecTreeAux;\nprotected:\n// Variables\n    std::vector<std::vector<int> > tabSons;///<Contains the branching order for the current local tree\n    std::vector<std::vector<double> > tabSonsDist;///<Contains the distances for the current local tree\n    std::vector<int> tabNode;///<Used only in makeLocalTree (made global for speed)\n    std::vector<int> tabRec;///<Used only in makeLocalTree (made global for speed)\n    std::vector<int> tabFather;///<Used only in makeLocalTree (made global for speed)\n    std::vector<double> age;///<Used only in makeLocalTree (made global for speed)\n    std::vector<int> tabEdge;///<Used only in makeLocalTree (made global for speed)\n    std::vector<bool> sameLTasPrev;///<Indicates for each site whether the local tree is the same as that of the previous site\n    unsigned int L;///< Number of sites in the sequences\n    std::vector<RecEdge *> edge;///< The recombinant edges\n// Functions\n    int randomActiveNode(std::vector<int> nodelist);///<Returns a random node id from a vector of indicators for alive (-1 for not alive at current time)\n    int getEdgeCoal(std::vector<int> nl,int k,double* time);///<Returns the node the recombinant edge is from and sets the time\n\n    int moveClonalFixFrom(std::vector<int> ornodes=std::vector<int>(0));///< Fixes all from times to be in to valid nodes and reinstates **the vector ornodes. returns the number of recedges moved to younger nodes - number moved to older nodes (or -1 if this is not calculated)\n\n    void updateEdgeTimes(int e,double reldist);///moves an edge when its node changes by proportion reldist\n    void scaleEdges(int which, double dist);///<Scales the recedges \"to\" on edge which by an amount dist\n    void fixFromTimes(int affedge,double dist);///<Fixes from times when we've moved edge affedge an amount dist\n    void fixToTimes(int which, double dist);///<Fixes \"to\" times when we've changed an node time implicitly\n\n    void swapEdge(int a, int b);///<Swaps two edges in the edge list (ordering only)\n    void swapEdgeTo(int a, int b);///<Swaps the edges going to *two specified --nodes--*\n\n    void orderEdges(int which);///<Checks that the edge which is in the correct place in the list (from 0.. which)\n\n    inline int orderNodes(int which, double dist)\n    {\n\treturn(orderNodes(which,dist,-1));\n    }///<places a node in a new place in the list (updated to account for recedges);\n    int orderNodes(int which, double dist, int oldwhich);///<places a node in a new place in the list (updated to account for recedges); a known position is a positive oldwhich...\n    void swapNode(int a, int b);///<Swaps two nodes in the list (updated to maintain recedges going to them)\n    int lastCommonAncestor(int s1,int s2);///< USES TABNODES AND TABFATHER!  Returns the last common ancestor index of the tabnodes ASSUMING the current local tree.\n    void makeLocalTreeKeepingFathers(unsigned int site);///< Makes a version of the local tree that has the fathers but is unoptimised\n    double pairwiseDist(int s1,int s2);///< Returns the pairwise distance between two sequences accounting for recombination.  SAME WARNINGS AS lastCommonAncestor!\npublic:\n\n// Constructors and destructors:\n    RecTree(unsigned int numsites,WargXml *infile,bool addedges=true,bool forceages=true,bool isfinal=true,std::streampos itstart=-1);///<Creates a tree from an output file\n\n    RecTree(unsigned int numsites,std::string newick,bool isFilename=true,bool forceages=true);///<Creates a tree from a Newick file\n    RecTree(int n,double rho,double delta,std::vector<int> blocks);///<Creates a Coalescent tree with recombinant edges by simulation\n    void dropEdges(double rho,double delta,vector<int> blocks);\n    RecTree(Data * data,double rho,double delta,vector<int> blocks);///<Creates UPGMA tree\n    RecTree(RecTree *intree,string newick,bool isFilename=false,bool forceages=true);/// Copies a rectree\n    RecTree(const RecTree& rt);///< Copy constructor\n    void assign(const RecTree& rt);\n    ~RecTree();\n// Part of the simulation initialisation:\n    void setBlock(unsigned int* gstart,unsigned int* gend,double delta,std::vector<int> *blocks);///<Sets the start and end positions of a recombinant block based on geometric distribution and independent blocks\n    int getEdgeCoal(double* time);///<Returns the node the recombinant edge is from and sets the time\n// Part of the likelihood/prior calculation:\n    double priorEdge(int e,Param * param) const;///<Returns the LOG prior of a given edge number in rectree\n    double priorEdge(RecEdge* edge0,Param * param) const;///FMA_CHANGES: Computes prior of edge not in rectree\n    double priorEdge(double tFrom,double tTo) const;///<Returns the UNLOGGED prior of a given edge\n    double prior(Param * param) const;///<Returns the value of the prior function\n\n    void makeLocalTree(unsigned int site,double thetaPerSite);///<Evaluates the local tree at the given site\n// Tests:\n    void testEdges() const;///<Tests recedges arrive in between the ages of the nodes they go to\n    void testTree();///<Checks ages increase in the tree for all sites.\n    inline bool sameLocalTreeAsPrev(unsigned int site) const\n    {\n        return sameLTasPrev[site];\n    }///<Returns true if the local tree of site is the same as that of site-1\n    void calcSameLTasPrev(unsigned int site);///<Estimate if the LT is the same as the previous one\n// Information functions:\n    inline Node * getRoot(){return(root);}\n    inline double getEdgeTimeAbsFrom(int e) const\n    {\n        return edge[e]->getTimeFrom()+nodes[edge[e]->getEdgeFrom()]->getAge();\n    }\n    ;///<Returns the absolute age of the origin of a recombinant edge\n    inline double getEdgeTimeAbsTo  (int e) const\n    {\n        return edge[e]->getTimeTo  ()+nodes[edge[e]->getEdgeTo  ()]->getAge();\n    }\n    ;///<Returns the absolute age of the destination of a recombinant edge\n    inline int getL() const\n    {\n        return L;\n    }///<Returns the total size of the alignment\n\n    inline RecEdge*getRecEdge(int w) const\n    {\n        return edge[w];\n    }///<Returns the w-th recombinant edge\n    inline int getSon (int i, unsigned int site,bool isLeft,double *dist) const\n    {\n        site=0;\n        *dist=tabSonsDist[i][isLeft];\n        return tabSons[i][isLeft];\n    };\n    ///<Returns the left daughter node for a given local site and node (NULL if no left daughter)\n    inline int affecting(unsigned int site) const\n    {\n        int a=0;\n        for (unsigned int i=0;i<edge.size();i++)\n            if (edge[i]->affectsSite(site))\n                a++;\n        return a;\n    }\n    ;///<Returns the number of edges affecting a site\n    inline int numRecEdge() const\n    {\n        return edge.size();\n    }///<Returns the number of recombinant edges\n    int numRecEdgeOnBranch(int b) const\n    {\n        int r=0;\n        for (unsigned int i=0;i<edge.size();i++)\n            if (edge[i]->getEdgeTo()==b)\n                r++;\n        return r;\n    }///<Returns the number of recedges on a given branch\n    std::vector<int> alive(double t) const;///<Returns the branches alive at a given time\n    bool isThere(int start,int end,int e,double time1,double time2) const;///<Returns yes if there is an edge with departure or arrival on branch e and between time1 and time2, and which affects material that intersects [start;end]\n    inline RecEdge* getEdge(int i) const\n    {\n        return(edge[i]);\n    }///<Returns the edge with index i\n    double getEdgeTreeTime(int i) const;///<Returns the time an edge spans in the tree\n    vector<int> getAffEdges(vector<int> * samplespace);///<Calculates the recedges relevent to a set of clonal edges\n    void updateList(int which, int newloc,vector<int> * list);///<Updates a list of edges when which was moved to newloc\n    int sampleEdge(vector<int> * samplespace=NULL);///<Samples a random edge that (optionally) interacts with a specific set of clonal edges\n// Modification functions:\n    void addEdgesFromFile(WargXml *infile,int siteoffset=0);///< adds edges to the rectree from the specified warg XML file (which is set to an iteration). Adds a \"siteoffset\" to add edges from different runs on different genes\n    int addRecEdge(double tfrom,double tto,unsigned int gstart,unsigned int gend,int edgefrom,int edgeto);///<Adds an recombination edge to the tree\n    int addRecEdge_FMA(double tfrom,double tto,unsigned int gstart,unsigned int gend,int edgefrom,int edgeto);///FMA_CHANGES: <Adds an recombination edge to the tree\n    int addRecEdge(unsigned int gstart,unsigned int gend,int edgefrom,int edgeto);///< Adds a recombination edge with random start and end times between given edges\n    int addRecEdge(std::string res,int sitesoffset=0);///<Add recedge from our output format\n    void remRecEdge(int which);///<Removes a recombinant edge\n    void setStart(int edge,int start);///<Sets the starting point of the given recedge\n    void setEnd(int edge,int end);///<Sets the ending point of the given recedge\n    void changeAge(int which,double dist);///<Changes the \"which\" node age, maintaining edge times\n    inline void changeEdgeNodeFrom(int e,int newnode)\n    {\n        edge[e]->setTimeFrom(getEdgeTimeAbsFrom(e)-getNode(newnode)->getAge(),newnode);\n    }///<changes the node to without changing the absolute time of the edge\n    inline void changeEdgeNodeTo(int e,int newnode)\n    {\n        edge[e]->setTimeTo(getEdgeTimeAbsTo(e)-getNode(newnode)->getAge(),newnode);\n    }///<changes the node to without changing the absolute time of the edge\n    void chooseNodePath(int which, double dist, vector<int> *listLR, vector<int> *affedges);///< Sets up a specified order for which nodes to swap when they are disordered\n    int moveNodeTime(int which, int *whichto,double dist,int oldwhich, vector<int> *listLR,  vector<int> *affedges);///<Updates the node list when the node which is moved a distance dist number of recedges moved to younger nodes - number moved to older nodes. edits affedges to make it the a vector of affected edges\n\n    void moveEdges(int e1,int e2,double t1=0.0,double t2=-1.0);///<Moves all edge events on e1 between absolute times t1..t2 onto edge e2, maintaining their absolute times (t2=-1 means no upper limit)\n// Information functions\n    std::vector<std::vector<double> > pairwiseDistanceMatrix(long site);///< returns a pairwise distance matrix for a given site\n\n};\n\n} // end namespace weakarg\n#endif\n", "meta": {"hexsha": "af7139ff3c6e895bee11ab3f7c06f23502d2824d", "size": 10712, "ext": "h", "lang": "C", "max_stars_repo_path": "ClonOr_cpp/rectree.h", "max_stars_repo_name": "fmedina7/ClonOr_cpp", "max_stars_repo_head_hexsha": "d1c2e0e0f7d2315bad99de80a15458cb4015ae1e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ClonOr_cpp/rectree.h", "max_issues_repo_name": "fmedina7/ClonOr_cpp", "max_issues_repo_head_hexsha": "d1c2e0e0f7d2315bad99de80a15458cb4015ae1e", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ClonOr_cpp/rectree.h", "max_forks_repo_name": "fmedina7/ClonOr_cpp", "max_forks_repo_head_hexsha": "d1c2e0e0f7d2315bad99de80a15458cb4015ae1e", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 58.8571428571, "max_line_length": 316, "alphanum_fraction": 0.7175130695, "num_tokens": 2640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.023330767620074855, "lm_q1q2_score": 0.010394546049888268}}
{"text": "// Copyright 2016-2018 Lauri Juvela and Manu Airaksinen\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#ifndef DEFINITIONS_H_\n#define DEFINITIONS_H_\n\n#include <gslwrap/vector_int.h>\n#include <gslwrap/vector_double.h>\n#include <gslwrap/matrix_double.h>\n\n/* Enums */\nenum DataType {ASCII, DOUBLE, FLOAT};\nenum SignalPolarity {POLARITY_DEFAULT, POLARITY_INVERT, POLARITY_DETECT};\nenum LpWeightingFunction {NONE, AME, STE};\nenum WindowingFunctionType {HANN, HAMMING, BLACKMAN, COSINE, HANNING, RECT, NUTTALL};\nenum ExcitationMethod {SINGLE_PULSE_EXCITATION, DNN_GENERATED_EXCITATION,\n   PULSES_AS_FEATURES_EXCITATION, EXTERNAL_EXCITATION, IMPULSE_EXCITATION};\n\n/* Structures */\nstruct Param\n{\n\tParam();\n\t~Param();\n\n  public:\n\tint fs;\n\tint frame_length;\n\tint frame_length_long;\n\tint frame_length_unvoiced;\n\tint frame_shift;\n\tint number_of_frames;\n\tint signal_length;\n\tint lpc_order_vt;\n\tint lpc_order_glot;\n\tint hnr_order;\n\tbool use_external_f0;\n\tstd::string external_f0_filename;\n\tbool use_external_gci;\n\tstd::string external_gci_filename;\n\tbool use_external_lsf_vt; // inverse filtering with external vocal tract filter\n\tstd::string external_lsf_vt_filename;\n\tbool use_external_excitation;\n\tstd::string external_excitation_filename;\n\n\tstd::string dnn_path_basename;\n\tstd::string data_directory;\n\tstd::string file_basename;\n\tstd::string file_path;\n\tbool save_to_datadir_root;\n\tDataType data_type;\n\tbool qmf_subband_analysis;\n\tSignalPolarity signal_polarity;\n\tdouble gif_pre_emphasis_coefficient;\n\tdouble unvoiced_pre_emphasis_coefficient;\n\tbool use_iterative_gif;\n\tLpWeightingFunction lp_weighting_function;\n\tint lpc_order_glot_iaif;\n\tdouble warping_lambda_vt;\n\tdouble ame_duration_quotient;\n\tdouble ame_position_quotient;\n\tWindowingFunctionType default_windowing_function;\n\tWindowingFunctionType psola_windowing_function;\n\tWindowingFunctionType paf_analysis_window;\n\n\tdouble max_pulse_len_diff;\n\tint paf_pulse_length;\n\tbool use_pulse_interpolation;\n\tbool use_highpass_filtering;\n\tbool use_waveforms_directly;\n\tbool use_paf_unvoiced_synthesis;\n\tbool use_velvet_unvoiced_paf;\n\tbool extract_f0;\n\tbool extract_gain;\n\tbool extract_lsf_vt;\n\tbool extract_lsf_glot;\n\tbool extract_hnr;\n\tbool extract_infofile;\n\tbool extract_glottal_excitation;\n\tbool extract_original_signal;\n\tbool extract_gci_signal;\n\tbool extract_pulses_as_features;\n\tbool use_paf_energy_normalization;\n\tint lpc_order_vt_qmf1;\n\tint lpc_order_vt_qmf2;\n\tdouble f0_max;\n\tdouble f0_min;\n\tdouble voicing_threshold;\n\tdouble zcr_threshold;\n\tdouble relative_f0_threshold;\n\tdouble speed_scale;\n\tdouble pitch_scale;\n\tbool use_postfiltering;\n\tbool use_spectral_matching;\n\tbool use_wsola;\n\tbool use_wsola_pitch_shift;\n\tbool noise_gated_synthesis;\n\tdouble noise_reduction_db;\n\tdouble noise_gate_limit_db;\n\tdouble postfilter_coefficient;\n\tdouble postfilter_coefficient_glot;\n\tbool use_trajectory_smoothing;\n\tint lsf_vt_smooth_len;\n\tint lsf_glot_smooth_len;\n\tint gain_smooth_len;\n\tint hnr_smooth_len;\n\tint filter_update_interval_vt;\n\tint filter_update_interval_specmatch;\n\tdouble noise_gain_unvoiced;\n\tdouble noise_gain_voiced;\n\tdouble noise_low_freq_limit_voiced;\n\t//double f0_check_range;\n\tExcitationMethod excitation_method;\n\tbool use_pitch_synchronous_analysis;\n\tbool use_generic_envelope;\n\n\t/* directory paths for storing parameters */\n\tstd::string dir_gain;\n\tstd::string dir_lsf;\n\tstd::string dir_lsfg;\n\tstd::string dir_hnr;\n\tstd::string dir_paf;\n\tstd::string dir_f0;\n\tstd::string dir_exc;\n\tstd::string dir_syn;\n\tstd::string dir_sp;\n\n\t/* extensions for parameter types */\n\tstd::string extension_gain;\n\tstd::string extension_lsf;\n\tstd::string extension_lsfg;\n\tstd::string extension_hnr;\n\tstd::string extension_paf;\n\tstd::string extension_f0;\n\tstd::string extension_exc;\n\tstd::string extension_src = \".src.wav\";\n\tstd::string extension_syn;\n\tstd::string extension_wav;\n\n\tstd::string wav_filename;\n\tstd::string default_config_filename;\n\tstd::string user_config_filename;\n};\n\n/* Define analysis data variable struct*/\nstruct AnalysisData {\n\tAnalysisData();\n\t~AnalysisData();\n\tint AllocateData(const Param &params);\n\tint SaveData(const Param &params);\npublic:\n\tgsl::vector signal;\n\tgsl::vector fundf;\n\tgsl::vector frame_energy;\n\tgsl::vector_int gci_inds;\n\tgsl::vector source_signal;\n   gsl::vector source_signal_iaif;\n\n\tgsl::matrix poly_vocal_tract;\n\tgsl::matrix lsf_vocal_tract;\n\tgsl::matrix poly_glot;\n\tgsl::matrix lsf_glot;\n\tgsl::matrix excitation_pulses;\n   gsl::matrix hnr_glot;\n\n\n\t/* QMF analysis specific */\n\t//gsl::matrix lsf_vt_qmf1;\n\t//gsl::matrix lsf_vt_qmf2;\n\t//gsl::vector gain_qmf;\n};\n\n\n/* Define analysis data variable struct*/\nstruct SynthesisData {\n   SynthesisData();\n   ~SynthesisData();\npublic:\n   gsl::vector signal;\n   gsl::vector fundf;\n   gsl::vector frame_energy;\n   gsl::vector excitation_signal;\n\n   gsl::matrix poly_vocal_tract;\n   gsl::matrix lsf_vocal_tract;\n   gsl::matrix poly_glot;\n   gsl::matrix lsf_glot;\n   gsl::matrix excitation_pulses;\n   gsl::matrix hnr_glot;\n   \n   gsl::matrix spectrum;\n   \n   /* QMF analysis specific */\n   //gsl::matrix lsf_vt_qmf1;\n   //gsl::matrix lsf_vt_qmf2;\n   //gsl::vector gain_qmf;\n};\n\n\n\n\n\n\n#endif\n", "meta": {"hexsha": "cef98e502efa6e08df407dd5d6666278b3aced0c", "size": 5619, "ext": "h", "lang": "C", "max_stars_repo_path": "src/glott/definitions.h", "max_stars_repo_name": "entn-at/GlottDNN", "max_stars_repo_head_hexsha": "b7db669d7f34da92ab34742d75a8ba3c70763a65", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/glott/definitions.h", "max_issues_repo_name": "entn-at/GlottDNN", "max_issues_repo_head_hexsha": "b7db669d7f34da92ab34742d75a8ba3c70763a65", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/glott/definitions.h", "max_forks_repo_name": "entn-at/GlottDNN", "max_forks_repo_head_hexsha": "b7db669d7f34da92ab34742d75a8ba3c70763a65", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1348837209, "max_line_length": 85, "alphanum_fraction": 0.791066026, "num_tokens": 1438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.023330766346783167, "lm_q1q2_score": 0.010394545482599216}}
{"text": "// Copyright 2011-2021 GameParadiso, Inc. All Rights Reserved.\n\n#pragma once\n\n#include <conio.h>\n\n#include <map>\n#include <unordered_set>\n#include <unordered_map>\n#include <ranges>\n#include <iostream>\n#include <sstream>\n#include <chrono>\n#include <random>\n#include <thread>\n\n#define FMT_HEADER_ONLY\n#include <fmt/format.h>\n\n#define GLM_FORCE_MESSAGES\n#define GLM_FORCE_INLINE\n#define GLM_FORCE_EXPLICIT_CTOR\n#define GLM_FORCE_ALIGNED_GENTYPES\n#define GLM_FORCE_INTRINSICS\n#include <glm/glm.hpp>\n#include <glm/vec3.hpp>\n#include <glm/vec4.hpp>\n#include <glm/mat4x4.hpp>\n#include <glm/gtc/quaternion.hpp>\n#include <glm/gtx/quaternion.hpp>\n#include <glm/ext/matrix_transform.hpp>\n#include <glm/ext/matrix_clip_space.hpp>\n#include <glm/gtx/matrix_decompose.hpp>\n#include <glm/ext/scalar_constants.hpp>\n#include <glm/gtc/type_aligned.hpp>\n\n#include <gsl/gsl>\n\n#include \"Mathmatics.h\"\n#include \"Util.h\"\n\nconstexpr uint32_t NumEntities = 50000;\n", "meta": {"hexsha": "64127b75d258137235153a0427fa4f26ade96614", "size": 938, "ext": "h", "lang": "C", "max_stars_repo_path": "pch.h", "max_stars_repo_name": "noirhero/MemoryChunkProfile", "max_stars_repo_head_hexsha": "3f5be50c65959a44c95f2955e1afb6ccd50b7ff2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pch.h", "max_issues_repo_name": "noirhero/MemoryChunkProfile", "max_issues_repo_head_hexsha": "3f5be50c65959a44c95f2955e1afb6ccd50b7ff2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pch.h", "max_forks_repo_name": "noirhero/MemoryChunkProfile", "max_forks_repo_head_hexsha": "3f5be50c65959a44c95f2955e1afb6ccd50b7ff2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.8139534884, "max_line_length": 62, "alphanum_fraction": 0.776119403, "num_tokens": 245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3040416749665474, "lm_q2_score": 0.034100424239886684, "lm_q1q2_score": 0.010367950102965}}
{"text": "/*\nMPCOTool:\nThe Multi-Purposes Calibration and Optimization Tool. A software to perform\ncalibrations or optimizations of empirical parameters.\n\nAUTHORS: Javier Burguete and Borja Latorre.\n\nCopyright 2012-2019, AUTHORS.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n    1. Redistributions of source code must retain the above copyright notice,\n        this list of conditions and the following disclaimer.\n\n    2. Redistributions in binary form must reproduce the above copyright notice,\n        this list of conditions and the following disclaimer in the\n        documentation and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY AUTHORS ``AS IS'' AND ANY EXPRESS OR IMPLIED\nWARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT\nSHALL AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\nBUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING\nIN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY\nOF SUCH DAMAGE.\n*/\n\n/**\n * \\file mpcotool.c\n * \\brief Main function source file.\n * \\authors Javier Burguete and Borja Latorre.\n * \\copyright Copyright 2012-2019, all rights reserved.\n */\n#define _GNU_SOURCE\n#include \"config.h\"\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <getopt.h>\n#include <math.h>\n#include <locale.h>\n#include <gsl/gsl_rng.h>\n#include <libxml/parser.h>\n#include <libintl.h>\n#include <glib.h>\n#include <json-glib/json-glib.h>\n#ifdef G_OS_WIN32\n#include <windows.h>\n#endif\n#if HAVE_MPI\n#include <mpi.h>\n#endif\n#if HAVE_GTK\n#include <gio/gio.h>\n#include <gtk/gtk.h>\n#endif\n#include \"genetic/genetic.h\"\n#include \"utils.h\"\n#include \"experiment.h\"\n#include \"variable.h\"\n#include \"input.h\"\n#include \"optimize.h\"\n#if HAVE_GTK\n#include \"interface.h\"\n#endif\n#include \"mpcotool.h\"\n\n#define DEBUG_MPCOTOOL 0        ///< Macro to debug main functions.\n\nGMutex mutex[1];                ///< GMutex struct.\nint ntasks;                     ///< Tasks number.\nunsigned int nthreads;          ///< Threads number.\n\n/**\n * Main function.\n *\n * \\return 0 on success, >0 on error.\n */\nint\nmpcotool (int argn,             ///< Arguments number.\n          char **argc)          ///< Arguments pointer.\n{\n  const struct option options[] = {\n    {\"seed\", required_argument, NULL, 's'},\n    {\"nthreads\", required_argument, NULL, 't'},\n    {NULL, 0, NULL, 0}\n  };\n#if HAVE_GTK\n  GtkApplication *application;\n  char *buffer;\n#endif\n  int o, option_index;\n\n  // Starting pseudo-random numbers generator\n#if DEBUG_MPCOTOOL\n  fprintf (stderr, \"mpcotool: starting pseudo-random numbers generator\\n\");\n#endif\n  optimize->rng = gsl_rng_alloc (gsl_rng_taus2);\n\n  // Allowing spaces in the XML data file\n#if DEBUG_MPCOTOOL\n  fprintf (stderr, \"mpcotool: allowing spaces in the XML data file\\n\");\n#endif\n  xmlKeepBlanksDefault (0);\n\n  // Starting MPI\n#if HAVE_MPI\n#if DEBUG_MPCOTOOL\n  fprintf (stderr, \"mpcotool: starting MPI\\n\");\n#endif\n  MPI_Init (&argn, &argc);\n  MPI_Comm_size (MPI_COMM_WORLD, &ntasks);\n  MPI_Comm_rank (MPI_COMM_WORLD, &optimize->mpi_rank);\n  printf (\"rank=%d tasks=%d\\n\", optimize->mpi_rank, ntasks);\n#else\n  ntasks = 1;\n#endif\n\n  // Getting threads number and pseudo-random numbers generator seed\n  nthreads_climbing = nthreads = cores_number ();\n  optimize->seed = DEFAULT_RANDOM_SEED;\n\n  // Parsing command line arguments\n  while (1)\n    {\n      o = getopt_long (argn, argc, \"s:t:\", options, &option_index);\n      if (o == -1)\n        break;\n      switch (o)\n        {\n        case 's':\n          optimize->seed = atol (optarg);\n          break;\n        case 't':\n          nthreads_climbing = nthreads = atoi (optarg);\n          break;\n        default:\n          printf (\"%s\\n%s\\n\", _(\"ERROR!\"), _(\"Unknown option\"));\n          return 1;\n        }\n    }\n  argn -= optind;\n\n  // Resetting result and variables file names\n#if DEBUG_MPCOTOOL\n  fprintf (stderr, \"mpcotool: resetting result and variables file names\\n\");\n#endif\n  input->result = input->variables = NULL;\n\n#if HAVE_GTK\n\n  // Setting local language and international floating point numbers notation\n  setlocale (LC_ALL, \"\");\n  setlocale (LC_NUMERIC, \"C\");\n  window->application_directory = g_get_current_dir ();\n  buffer = g_build_filename (window->application_directory, LOCALE_DIR, NULL);\n  bindtextdomain (PROGRAM_INTERFACE, buffer);\n  bind_textdomain_codeset (PROGRAM_INTERFACE, \"UTF-8\");\n  textdomain (PROGRAM_INTERFACE);\n\n  // Initing GTK+\n  gtk_disable_setlocale ();\n  application = gtk_application_new (\"es.csic.eead.auladei.sprinkler\",\n                                     G_APPLICATION_FLAGS_NONE);\n  g_signal_connect (application, \"activate\", G_CALLBACK (window_new), NULL);\n\n  // Opening the main window\n  g_application_run (G_APPLICATION (application), 0, NULL);\n\n  // Freeing memory\n  input_free ();\n  g_free (buffer);\n  gtk_widget_destroy (GTK_WIDGET (window->window));\n  g_object_unref (application);\n  g_free (window->application_directory);\n\n#else\n\n  // Checking syntax\n  if (argn < 1 || argn > 3)\n    {\n      printf (\"The syntax is:\\n\"\n              \"./mpcotoolbin [-nthreads x] [-seed s] data_file [result_file] \"\n              \"[variables_file]\\n\");\n      return 2;\n    }\n  if (argn > 1)\n    input->result = (char *) xmlStrdup ((xmlChar *) argc[optind + 1]);\n  if (argn == 2)\n    input->variables = (char *) xmlStrdup ((xmlChar *) argc[optind + 2]);\n\n  // Making optimization\n#if DEBUG_MPCOTOOL\n  fprintf (stderr, \"mpcotool: making optimization\\n\");\n#endif\n  if (input_open (argc[optind]))\n    optimize_open ();\n\n  // Freeing memory\n#if DEBUG_MPCOTOOL\n  fprintf (stderr, \"mpcotool: freeing memory and closing\\n\");\n#endif\n  optimize_free ();\n\n#endif\n\n  // Closing MPI\n#if HAVE_MPI\n  MPI_Finalize ();\n#endif\n\n  // Freeing memory\n  gsl_rng_free (optimize->rng);\n\n  // Closing\n  return 0;\n}\n", "meta": {"hexsha": "dd82af21ecf63664b272324cfe398bae3ceef6a7", "size": 6232, "ext": "c", "lang": "C", "max_stars_repo_path": "4.0.5/mpcotool.c", "max_stars_repo_name": "jburguete/mpcotool", "max_stars_repo_head_hexsha": "e8a6a9713d4ef73b0aa8a0a552d91117ebd22610", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-17T14:59:29.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-17T14:59:29.000Z", "max_issues_repo_path": "4.0.5/mpcotool.c", "max_issues_repo_name": "jburguete/mpcotool", "max_issues_repo_head_hexsha": "e8a6a9713d4ef73b0aa8a0a552d91117ebd22610", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-03-08T17:02:14.000Z", "max_issues_repo_issues_event_max_datetime": "2016-03-08T17:02:14.000Z", "max_forks_repo_path": "4.0.5/mpcotool.c", "max_forks_repo_name": "jburguete/mpcotool", "max_forks_repo_head_hexsha": "e8a6a9713d4ef73b0aa8a0a552d91117ebd22610", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0720720721, "max_line_length": 80, "alphanum_fraction": 0.6882220796, "num_tokens": 1562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24220562872535945, "lm_q2_score": 0.042722193280600056, "lm_q1q2_score": 0.010347555684054063}}
{"text": "//\n// Created by pedram pakseresht on 2/18/21.\n//\n\n// #include <petsc.h>\n\n#include <printf.h>\n#include <stdlib.h>\n\nvoid setNumber(double *zxy);\n\ntypedef struct{\n\n    double x;\n    double z;\n    int g[3];\n\n}Pstruct;\n\n\nvoid printStruct(Pstruct str) {\n\n    printf(\"print struct %f %f %d %d %d \\n\", str.x, str.z, str.g[0], str.g[1], str.g[2]);\n//    printf(\"print x %lf \\n\", str.z );\n//    printf(\"print x %lf \\n\", str.g[1] );\n\n};\n\n\nvoid setValues(){\n\n}\n\nint main( int argc, char *argv[] )\n{\n\n    Pstruct a;\n    a.x = 7.0;\n    a.z = 8.0;\n    a.g[0] = 1;\n    a.g[1] = 2;\n    a.g[2] = 3;\n\n    Pstruct b;\n    b.x = 5.0;\n    b.z = 4.0;\n    b.g[0] = 3;\n    b.g[1] = 1;\n    b.g[2] = 2;\n\n\n    printStruct(a);\n    printStruct(b);\n\n\n\n\n//    printf(\"x of b is %lf \\n\",b.x);\n//printf(\"size of struc %lu \\n\", sizeof(Pstruct));\n//printf(\"size of int %lu\", sizeof(int [4]));\n\n}\n\n\n\n\n", "meta": {"hexsha": "27ae140c9932b0dd16c4a85576e8f8378a9e182e", "size": 864, "ext": "c", "lang": "C", "max_stars_repo_path": "structExp.c", "max_stars_repo_name": "pakserep/ablateClient", "max_stars_repo_head_hexsha": "c7bb7cf4a4ec706170efd7c06bf8589e30ece47b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "structExp.c", "max_issues_repo_name": "pakserep/ablateClient", "max_issues_repo_head_hexsha": "c7bb7cf4a4ec706170efd7c06bf8589e30ece47b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "structExp.c", "max_forks_repo_name": "pakserep/ablateClient", "max_forks_repo_head_hexsha": "c7bb7cf4a4ec706170efd7c06bf8589e30ece47b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 12.8955223881, "max_line_length": 89, "alphanum_fraction": 0.5046296296, "num_tokens": 325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16238005288069604, "lm_q2_score": 0.06371499914110602, "lm_q1q2_score": 0.0103460449298263}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef texbatch_dfe6f3b4_430b_4424_98b6_d6b23235dc22_h\r\n#define texbatch_dfe6f3b4_430b_4424_98b6_d6b23235dc22_h\r\n\r\n#include <gslib/std.h>\r\n#include <ariel/type.h>\r\n#include <ariel/image.h>\r\n#include <ariel/rectpack.h>\r\n#include <ariel/rendersys.h>\r\n\r\n__ariel_begin__\r\n\r\ntypedef render_texture2d texture2d;\r\n\r\n#define _GS_BATCH_TEXTURE\r\n\r\n#if defined(_GS_BATCH_TEXTURE)\r\n#define location_key    texture2d*\r\n#elif defined(_GS_BATCH_IMAGE)\r\n#define location_key    const image*\r\n#endif\r\n\r\nclass tex_batcher\r\n{\r\npublic:\r\n    typedef unordered_map<location_key, rectf> location_map;\r\n\r\npublic:\r\n    tex_batcher();\r\n    bool is_empty() const { return _rect_packer.is_empty(); }\r\n    float get_width() const { return _rect_packer.get_width() + _gap; }\r\n    float get_height() const { return _rect_packer.get_height() + _gap; }\r\n    void add_image(const image* p);\r\n    void add_texture(texture2d* p);\r\n    void arrange();\r\n    const location_map& get_location_map() const { return _location_map; }\r\n    texture2d* create_texture(rendersys* rsys) const;\r\n    void create_packed_image(image& img) const;\r\n    void tracing() const;\r\n\r\nprotected:\r\n    rect_packer         _rect_packer;\r\n    location_map        _location_map;\r\n    float               _gap;\r\n\r\nprivate:\r\n    void prepare_input_list(rp_input_list& inputs);\r\n};\r\n\r\n__ariel_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "3f1d42137d390340375fa265457dd71c140989b7", "size": 2608, "ext": "h", "lang": "C", "max_stars_repo_path": "include/ariel/texbatch.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/ariel/texbatch.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ariel/texbatch.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 33.0126582278, "max_line_length": 82, "alphanum_fraction": 0.7254601227, "num_tokens": 626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31742627850202554, "lm_q2_score": 0.03258974605797164, "lm_q1q2_score": 0.010344841808507994}}
{"text": "#ifndef __SVM_MAIN_H__\n#define __SVM_MAIN_H__\n\n#define PY_SSIZE_T_CLEAN\n#include <Python.h>\n#include <stdlib.h>\n#include <gsl_vector.h>\n#include <gsl_multimin.h>\n#include \"common.h\"\n#include \"smo.h\"\n#include \"kernels.h\"\n\n// returns vector normal to hyperplane and margin width\nPyObject* __get_w_b(PyObject* elements, int k_type, double C);\ninput_data_t* process_input_data(PyObject* n_array, int k_type, double C);\n\n#endif  /* __SVM_MAIN_H__ */", "meta": {"hexsha": "5b19c449e8b50c05e8eaa310b4dbdff53a8935f0", "size": 444, "ext": "h", "lang": "C", "max_stars_repo_path": "Source/SVM/Include/svm_main.h", "max_stars_repo_name": "HARDIntegral/ADHD_Classifier", "max_stars_repo_head_hexsha": "f86c8eafa78ca241919d12134afe796c665f8021", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Source/SVM/Include/svm_main.h", "max_issues_repo_name": "HARDIntegral/ADHD_Classifier", "max_issues_repo_head_hexsha": "f86c8eafa78ca241919d12134afe796c665f8021", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/SVM/Include/svm_main.h", "max_forks_repo_name": "HARDIntegral/ADHD_Classifier", "max_forks_repo_head_hexsha": "f86c8eafa78ca241919d12134afe796c665f8021", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1176470588, "max_line_length": 74, "alphanum_fraction": 0.7702702703, "num_tokens": 120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.40356685373537454, "lm_q2_score": 0.02556521151038995, "lm_q1q2_score": 0.010317271974327455}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdarg.h>\n#include <math.h>\n\n#include <gsl/gsl_errno.h>\n\n#include \"ccl.h\"\n\n// Debug mode policy: whether to print error messages as they are raised.\n// Defualt is ON.\nstatic CCLDebugModePolicy _ccl_debug_mode_policy = CCL_DEBUG_MODE_ON;\n\n// Set debug mode policy\nvoid ccl_set_debug_policy(CCLDebugModePolicy debug_policy) {\n    _ccl_debug_mode_policy = debug_policy;\n}\n\n// Convenience function to handle warnings\nvoid ccl_raise_warning(int err, const char* msg, ...) {\n  char message[256];\n\n  va_list va;\n  va_start(va, msg);\n  vsnprintf(message, 250, msg, va);\n  va_end(va);\n\n  // For now just print warning to stderr if debug is enabled.\n  // TODO: Implement some kind of error stack that can be passed on to, e.g.,\n  // the python binding.\n  if (_ccl_debug_mode_policy == CCL_DEBUG_MODE_ON) {\n    fprintf(stderr, \"WARNING %d: %s\\n\", err, message);\n  }\n}\n\n// Convenience function to handle warnings\nvoid ccl_raise_gsl_warning(int gslstatus, const char* msg, ...) {\n  char message[256];\n\n  va_list va;\n  va_start(va, msg);\n  vsnprintf(message, 250, msg, va);\n  va_end(va);\n\n  ccl_raise_warning(gslstatus, \"%s: GSL ERROR: %s\", message, gsl_strerror(gslstatus));\n  return;\n}\n", "meta": {"hexsha": "4ffbb0552df9d5e6382173b4fabd8d0640780433", "size": 1223, "ext": "c", "lang": "C", "max_stars_repo_path": "src/ccl_error.c", "max_stars_repo_name": "Jappenn/CCL", "max_stars_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 91.0, "max_stars_repo_stars_event_min_datetime": "2017-07-14T02:45:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T08:55:54.000Z", "max_issues_repo_path": "src/ccl_error.c", "max_issues_repo_name": "Jappenn/CCL", "max_issues_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 703.0, "max_issues_repo_issues_event_min_datetime": "2017-07-07T16:27:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T14:40:10.000Z", "max_forks_repo_path": "src/ccl_error.c", "max_forks_repo_name": "Jappenn/CCL", "max_forks_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 54.0, "max_forks_repo_forks_event_min_datetime": "2017-07-12T13:08:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-06T13:12:10.000Z", "avg_line_length": 25.4791666667, "max_line_length": 86, "alphanum_fraction": 0.7154538021, "num_tokens": 334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2720245628973633, "lm_q2_score": 0.0378924274444757, "lm_q1q2_score": 0.010307671012703556}}
{"text": "/*************************************************************************\n\ndescription:\nThis file contains the class that can do the actual radiative transport, \nincluding routines for grid calculation, physics and the actual transport\n\nCopyright Jan-Pieter Paardekooper and Chael Kruip October 2011\n\nThis file is part of SimpleX.\n\nSimpleX is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nSimpleX is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with SimpleX.  If not, see <http://www.gnu.org/licenses/>.\n\n**************************************************************************/\n\n#ifndef SIMPLEX_H\n#define SIMPLEX_H\n\n#ifndef NOMPI\n#include \"mpi.h\"\n#endif\n\n#include \"rates.h\"\n#include \"Common.h\"\n#include \"Structs.h\"\n#include <gsl/gsl_rng.h>  //random number generator\n#include \"configfile.h\"   //keyvalue input file\n\n#ifdef HEAL_PIX\n  #include \"healpix_base.h\" //healpix header\n#endif\n\n\n#include \"tree_structures.h\" //octree\n#include \"hilbert.h\"         //hilbert curve\n\n#include \"h5w_serial.h\"      //hdf5 header\n\n\n#include <algorithm>\n\n#if defined(__cplusplus)\nextern \"C\"\n{\n#endif\n#include <stdio.h>\n#include <stdlib.h>\n#include <libqhull.h>\n#include <mem.h>\n#include <qset.h>\n#include <geom.h>\n#include <merge.h>\n#include <poly.h>\n#include <io.h>\n#include <stat.h>\n#if defined(__cplusplus)\n}\n#endif\n\nusing namespace std;\n\n#define VERTEX_ITERATOR vector< Vertex >::iterator\n#define SITE_ITERATOR vector< Site >::iterator\n#define SIMPL_ITERATOR vector< Simpl >::iterator\n\n//! Class in which all functions that work on the SimpleX grid are stored\n\n//! This is the main class of the simulation!\nclass SimpleX{\n\n  public:\n    //! constructor\n    SimpleX(const string& output_path = \".\", const string& data_path = \".\");\n    //! destructor\n    ~SimpleX();\n\n  //================ Grid Initilisation Functions ==================================//\n\n    //! Create triangulation\n\n    //! Initialize the simulation by creating/reading the vertex list and compute the triangulation\n    //! Result is a list of Sites and a list of Simplices\n    void init_triangulation(char* inputName);\n\n\n    //TEST\n    void reinit_triangulation();\n    //END TEST\n\n\n    //! Read in parameter file\n    void read_parameters( char* inputName );\n\n    //! Create orientations and mappings from correct header file\n    void set_direction_bins();\n\n    //! Create a simple homogeneous point distribution \n    \n    //! Points are placed using the gsl randoom number generator\n    void poisson_square();\n\n    //! Read in hdf5 file with site information\n    void read_vertex_list();\n  \n    //! Compute the largest index of all the vertices\n    unsigned long long int computeMaxId();\n    \n    //! Create boundary around computational domain\n\n    //! Width of the boundary is variable borderBox. \n    //! Number of points in the boundary is variable borderSites.\n    void create_boundary();\n\n\n    //!Create octree containing all vertices\n\n    //!Size of the tree depends on the number of subboxes used, which\n    //!is determined by the hilbert order m\n    void create_vertex_tree();\n\n    //! Decompose the domain\n\n    //! Count the number of sites contained in one subbox and add those until \n    //! number of points is approximately equal per processor\n    void decompose_domain();\n    \n    //! Assign the correct process to vertices\n    void assign_process();\n\n    //! Check if site is in unit domain\n    bool inDomain(const float& x, const float& y, const float& z, const unsigned int& rank);\n\n    //! Compute the triangulation\n\n    //! Call to QHull to perform the triangulation of vertices in one subbox\n    //! The result is a vector of simplices\n    //! Also, a check is done whether the subbox and domain boundaries are\n    //! sufficiently large. If not, subbox boundaries are extended. If the\n    //! boundary around the unity domain is too small, the code exits,\n    //! to avoid memory issues when this number would be increased\n    void compute_triangulation();\n\n    //! Create the sites array on which radiative transfer is performed\n\n    //! From the list of simplices the vertices relevant for this proc are selected and\n    //! put in the sites vector\n    void create_sites();\n\n    //! Give each site an id corresponding to place in local sites vector\n    void assign_site_ids();\n\n    //! Determine which sites use ballistic transport and which sites \n    //! should use direction conserving transport at the start of the\n    //! simulation. \n    void initiate_ballistic_sites();\n\n    //! Shuffle list of sites\n\n    //! This is necessary since the sites list is created from the simplices returned by QHull,\n    //! so they are ordered.\n    void shuffle_sites();\n\n\n  //================ Site Properties Functions ==================================//\n\n    //! Compute properties of the sites from the triangulation\n\n    //! Important properties like the neighbours, the volumes and \n    //! the most straight paths are computed\n    void compute_site_properties();\n\n    //! Compute the neighbours of vertex\n\n    //! Generate the neighbour vectors for each vertex from the simplex vector\n    //! Care should be taken so that no vertex is put twice in the neighbour list. \n    //! Also get rid of vertices in the sub box boundary that are not connected to a site\n    //! in the computational domain\n    void compute_neighbours();\n\n\n    //! Compute the volume of the Voronoi cell\n\n    //! Use the volumes of the simplices that the vertex is part of to compute\n    //! the volume of the Voronoi cell around the vertex\n    void compute_volumes();\n\n\n    //! Calculate the most straight paths for every incoming direction\n\n    //! Needed for fast radiative transport\n    void calculate_straight();\n\n    //! Identify the place of every ballistic site in neighbour array\n    //! of neighbouring site\n    void match_neighbours();\n \n    //! Compute the solid angles into which the intensity is distributed\n    void compute_solid_angles( const bool& rotate );\n\n\n    //! Check for cyclic connections in the grid and remove them if possible\n    void check_cyclic_connections();\n\n\n    //! Calculate mean distance to neighbours\n    void calculate_line_lengths();\n\n\n    //! Create list without border simplicesc\n    void remove_border_simplices();\n\n\n    //================ Grid Update Routines ============================//\n\n    //! Rotate the solid angles of the unit sphere \n    //! to avoid preferential directions\n    void rotate_solid_angles();\n\n    //! calculate normal distributed random numbers using the Box-Muller transformation\n    void randGauss( float& y1, float& y2 );\n\n    //! Store the intensities for use in later run, directions are kept.\n    void store_intensities();\n\n    //! Get the ballistic sites that have intensity to be stored\n    const vector< unsigned long int > get_ballistic_sites_to_store();\n\n    //! Store ballistic intensities in unit sphere tesselation\n    void store_ballistic_intensities( const vector< unsigned long int >& sites_to_store );\n\n    //! Return the intensities from the previous run\n    void return_intensities();\n\n    //! Return the intensities to ballistic sites\n    void return_ballistic_intensities();\n\n    //! Check which sites are ballistic and which not\n    //! according to user specified switch\n\n    //! Only used is case of combined transport\n    void check_ballistic_sites();\n\n    //! Create new sites array without the removed sites\n    void store_site_properties();\n\n    //! Create updated vertex list from site_properties vector\n    void create_new_vertex_list();\n\n\n    //================ Send Routines ===================================//\n   \n\n    //! Send vertices to processors\n    void send_vertices();\n\n    //! Send the domain decomposition to all procs\n    void send_dom_dec();\n\n    //! Fill the list of indices of sites that contain information to be send \n    //! to other procs\n    void fill_send_list();\n\n    //! Give every vertex its correct process (needed for vertices in boundary between procs)\n    void send_site_properties();\n\n    //! Give every ballistic site its correct neighbour information \n    \n    //! This is only needed for ballistic sites in boundary between procs, and is necessary because\n    //! the order of the neighbours in the neighbour vector is not the same among procs.\n    void send_neighbour_properties();\n\n    //! Send teh updated ballistic sites to all procs\n    void send_site_ballistics( const vector< unsigned long int >& sites_to_send );\n\n     //! Send the intensities among procs\n    void send_intensities();\n\n    //! Send site physics to all procs\n\n    //! In case sites change from proc send physics\n    void send_site_physics();\n\n    //! In case sites change from proc send intensities\n    void send_site_intensities();\n\n    //! Send stored intensities among procs\n    void send_stored_intensities();\n\n    //! Send the updated vertex list to all procs\n    void send_new_vertex_list();\n\n\n    //================ Physics Functions ==================================//\n\n\n    //! Compute all the physics needed to do radiative transport\n    void compute_physics( const unsigned int& run );\n\n    //! Initialize physical parameters\n    void initialise_physics_params();\n\n    //! Read metal line cooling data and initialize vectors\n    void read_metals();\n\n    //! set homogeneous number density. \n\n    //! Use only in combination with Poisson_Square()\n    void set_homogeneous_number_density( const float& nH );\n\n\n    //! Give the masses and fluxes that were read in to the sites\n\n    //! Use only in combination with read_vertex_list()\n    void assign_read_properties();\n\n    //! Give the updates sites their correct physical quantities from stored values\n    void return_physics();\n\n    //! Calculate the bounds of the frequency bins\n    vector<double> calc_freq_bounds( const double& lowerBound, const double& upperBound );\n\n    //! calculate effective cross section and spectrum of black body source\n    void black_body_source( const double& tempSource );\n\n    //! Compute the total number of atoms on this proc, used for output\n    void output_number_of_atoms();\n\n    //! Return mean optical depth of total grid\n    double output_optical_depth();\n\n    //! output relevant physical parameters to screen \n    void parameter_output( const unsigned int& run );\n    \n    //! Add more neighbours to vertices that have a flux, by adding the neighbours\n    //! of neighbours.\n    void make_source_isotropic();\n\n    //! calculate recombination\n    double recombine();\n\n    //! Rate of energy loss in cell\n    double cooling_rate( Site& site );\n\n    //! Rate of energy gain in cell\n    double heating_rate( const vector<double>& N_ion, const double& t_end );\n\n    //! compute mean molecular weight\n    double compute_mu( Site& );\n\n    //!Convert internal energy to temperature\n    double u_to_T( const double& u, const double& mu );\n\n    //!Convert temperature to internal energy\n    double T_to_u( const double& T, const double& mu );\n\n    //! update the temperature by including heating and cooling processes\n    double update_temperature( Site& site, const vector<double>& N_ion, const double& t_end );\n\n //================= Radiative Transfer Functions ======================//\n    \n    //! Solve the rate equation to determine ionisations and recombinations\n    vector<double> solve_rate_equation( Site& site );\n\n    //! Send source photons\n    void source_transport( Site& site );\n\n    //! Transport photons diffusely\n    void diffuse_transport( Site& site, vector<double>& N_out_total );\n\n    //! Redistribute intensity: actual radiative transport\n    void non_diffuse_transport( Site& site, vector<double>& N_out_total );\n\n    //! Call to do radiative transfer\n    void radiation_transport( const unsigned int& run );\n\n  //================== Output Functions ================================//\n\n\n    //! Call the output routines\n    void generate_output( const unsigned int& run );    \n\n    //! Write hdf5 output file\n    void write_hdf5_output(char* name, const unsigned int& run);\n    \n    //! calculate position of the I-Front for source in centre\n    double calc_IFront( const unsigned int& run );\n\n    //! calculate escape fraction\n    double calc_escape_fraction( const unsigned int& run, const unsigned int& times );\n\n\n    //================ Generic Functions ==============================//\n   \n    //! clear all temporary structures for the next run\n    void clear_temporary();\n    \n    //! Function to give diagnostic output about total number of photons in simulation\n    double count_photons();\n\n    //! return number of runs\n    const unsigned int& get_numRuns() const{ return numRuns; }\n  \n    //! Return number of outputs\n    const unsigned int& get_numOutputs() const{ return numOutputs; }\n\n\n    // ================ Public lists and variables ===================//\n\n    //! List of vertices that will be used to perform triangulation\n    vector< Vertex > vertices;\n\n    //! List of sites for doing radiative transfer\n    vector< Site > sites;\n\n    //! Vector holding the domain decomposition\n    vector< unsigned int > dom_dec;\n\n    //! List of sites from the previous run, whose properties are still needed\n    vector< Site_Update > site_properties;\n\n    //! List of entries in site_intensities array of every site\n    vector<unsigned long int> intens_ids;\n    //! List of site intensities from previous run, that are still needed\n    vector<float> site_intensities;\n\n    //! List of indices of sites needed for transport along procs\n    vector< unsigned long int > send_list;\n\n    //! List of site indices that might be removed\n    vector< unsigned long int > sites_marked_for_removal;\n    //! List of sites and properties to be updated\n    vector< Site_Remove > total_sites_marked_for_removal;\n\n    //! List of simplices that results from the QHull call\n    vector< Simpl > simplices;\n    //! Temporary list of neutral number densities that are read in\n    vector< float > temp_n_HI_list;\n    //! Temporary list of ionised number densities that are read in\n    vector< float > temp_n_HII_list;\n    //! Temporary list of fluxes that are read in\n    vector< float > temp_flux_list;\n    //! Temporary list of internalEnergies that are read in\n    vector< float > temp_u_list;\n    //! Temporary list of dudt that are read in\n    vector< float > temp_dudt_list;\n    //! Temporary list of clumping factors that are read in\n    vector< float > temp_clumping_list;\n    //! Temporary list of metallicity\n    vector<float> temp_metallicity_list;\n    \n    //! Cross section of hydrogen\n    vector<double> cross_H;\n    //! The photon excess energy used to heat the gas\n    vector<double> photon_excess_energy;  \n    //! The elemental abundances of metals (and Helium)\n    vector<double> abundances;\n    //! Vector of cooling curves\n    vector< cooling_curve > curves;\n\n    //! Variable used by random number generator\n    gsl_rng * ran;\n    //! Output to logfile\n    ofstream simpleXlog; \n    \n  protected:\n\n    unsigned long int numSites;            //!< Total number of sites in the simulation\n    unsigned long int origNumSites;        //!< Original number of sites\n    unsigned int borderSites;      //!< Number of sites in the boundary around computational domain\n    unsigned int hilbert_order;    //!< Hilbert order that determines the number of subboxes\n    unsigned int numSweeps;        //!< Number of grid sweeps during simulation\n    unsigned int numRuns;          //!< Number of runs of the simulation\n    unsigned int numOutputs;       //!< Number of outputs of the simulation\n    unsigned int numPixels;        //!< Number of pixels in HEALPix calculation\n    unsigned int numStraight;      //!< Number of straight directions\n    int randomSeed;                //!< Seed for random number generator\n    short dimension;               //!< Dimension of the simulation (default = 3)\n    string inputFileName;          //!< File which holds densities and fluxes to be read in\n    string dataPath;               //!< Path where the metal line cooling tables are\n    bool blackBody;                //!< Use blackbody for source spectrum?\n    bool recombination;            //!< Include recombination or not\n    bool rec_rad;                  //!< Include recombination radiation or not\n    bool coll_ion;                 //!< Include collisional ionisations?\n    bool heat_cool;                //!< Include heating and cooling?\n    bool metal_cooling;            //!< Include metal line cooling?\n    short int numFreq;             //!< Number of frequencies\n    short int freq_spacing;        //!< Spacing of the frequency bins\n    short RTmethod;                //!< Method for RT\n    bool diffuseTransport;         //!< Set this to 1 to do only ballistic transport\n    bool ballisticTransport;       //!< Set this to 1 to do only ballistic transport\n    bool dirConsTransport;         //!< Set this to 1 to do only direction conserving transport\n    bool combinedTransport;        //!< Set this to 1 to do combined transport\n    bool photon_conservation;      //!< Use temporal photon conservation scheme or not?\n    double subcycle_frac;          //!< Fraction of the characteristic time scale at which subcycling is done\n    double sizeBox;                //!< Size of the box in parsec\n    float borderBox;               //!< Size of boundary around computational domain\n    float padding_subbox;          //!< Subbox boundary in which extra points are triangulated\n    double simTime;                //!< Total simulation time in Myr\n    double time_conversion;        //!< Time conversion for output\n    double sourceTeff;             //!< Effective temperature of the sources in K\n    double gasIonTemp;             //!< Temperature of the ionised gas in K\n    double gasNeutralTemp;         //!< Temperature of the neutral gas in K\n    double switchTau;              //!< Optical depth below which ballistic transport is no longer trusted\n    double totalVolume;            //!< Total volume of all Voronoi cells added up\n    double totalAtoms;             //!< Total number of atoms in the simulation domain\n    int localMaxRes;               //!< Maximum resolution on the local processor\n    unsigned int COMM_RANK;        //!< Rank of this proc\n    unsigned int COMM_SIZE;        //!< Total number of procs\n    unsigned int chunk_size;       //!< Maximum size of chunks written in one piece to hdf5 file\n    unsigned int max_msg_to_send;  //!< Maximum number of messages to send in MPI call\n    unsigned long int vertex_id_max;    //!< Maximum vertex index\n    short int orientation_index;      //!< Orientation of the unit sphere tesselation\n    short int orientation_index_old;  //!< Orientation of the unit sphere tesselation in previous run\n    float euler_phi;               //!< Euler angle phi for random rotation of coordinate system\n    float euler_theta;             //!< Euler angle theta for random rotation of coordinate system\n    float euler_psi;               //!< Euler angle psi for random rotation of coordinate system\n    bool heal_pix;                 //!< Use heal_pix for associating directions and neighbours or not?\n    int num_ref_pix_HP;            //!< Number of pixels to use for associating neighbours in compute_solid_angles()\n    float straightAngle;           //!< Maximum angle allowed between straight direction and Delaunay direction.\n    bool straight_from_tess;       //!< In DCT, calculate straightest neighbours wrt Delaunay edge or direction bin?\n    double UNIT_L;                 //!< Unit length in box\n    double UNIT_M;                 //!< Unit mass in box, converts number density into number of atoms\n    double UNIT_I;                 //!< Unit number of ionising photons in box\n    double UNIT_T;                 //!< Time of 1 sweep in seconds\n    double UNIT_T_MYR;             //!< Time of 1 sweep in Myr\n    double UNIT_D;                 //!< Unit number density\n    double UNIT_V;                 //!< Unit volume\n    float straight_correction_factor; //!< Correction factor to correct for the fact that no straight lines exist on the grid\n    vertex_tree vert_tree;         //!< Octree that will contain the vertices\n    bool give_IFront;                   //!< Calculate IFront position for a source in centre?\n    ofstream IFront_output;        //!< Output of IFront data to file\n    float*** orient;               //!< Array to hold the direction bins\n    unsigned int*** maps;          //!< Array to hold the mappings between direction bins\n    unsigned int number_of_directions; //!< Number of discretizations of the unit sphere for DCT\n    unsigned int number_of_orientations;//!< Number of random rotations of the DCT discretization\n};\n\n#endif\n", "meta": {"hexsha": "97cba342ca031f998462c166ae25bcf6b40b29b2", "size": 21035, "ext": "h", "lang": "C", "max_stars_repo_path": "src/amuse/community/simplex/src/src/SimpleX.h", "max_stars_repo_name": "joshuawall/amuse", "max_stars_repo_head_hexsha": "c2034074ee76c08057c4faa96c32044ab40952e9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-04-09T09:06:08.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-09T09:06:08.000Z", "max_issues_repo_path": "src/amuse/community/simplex/src/src/SimpleX.h", "max_issues_repo_name": "joshuawall/amuse", "max_issues_repo_head_hexsha": "c2034074ee76c08057c4faa96c32044ab40952e9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/amuse/community/simplex/src/src/SimpleX.h", "max_forks_repo_name": "joshuawall/amuse", "max_forks_repo_head_hexsha": "c2034074ee76c08057c4faa96c32044ab40952e9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-19T04:41:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T02:11:17.000Z", "avg_line_length": 38.3151183971, "max_line_length": 125, "alphanum_fraction": 0.6711671024, "num_tokens": 4359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879064146934857, "lm_q2_score": 0.021948255434202448, "lm_q1q2_score": 0.010289136744132881}}
{"text": "#pragma once\n#include <vector>\n#include <array>\n#include <gsl/gsl>\n\n\n#pragma warning(push)\n#include <CppCoreCheck/Warnings.h>\n#pragma warning(disable: ALL_CPPCORECHECK_WARNINGS)\n#include <glm/glm.hpp>\n#define GLM_ENABLE_EXPERIMENTAL\n#include <glm/gtx/hash.hpp>\n#pragma warning(pop)\n\n#include <vulkan/vulkan.h>\n\n#include \"../utils/Utils.h\"\n#include \"./RenderUtils.h\"\n#include \"../Configuration.h\"\n\n#define VMA_USE_ALLOCATOR\n#ifdef VMA_USE_ALLOCATOR\n#pragma warning(push)\n#include <CppCoreCheck/Warnings.h>\n#pragma warning(disable: ALL_CPPCORECHECK_WARNINGS)\n#include \"vk_mem_alloc.h\"\n#pragma warning(pop)\n\n/**\nOur main unsigned in type to accomodate\nvulkan's needs\n*/\nusing uint = uint32_t;\n\n/**\nWrapps a Vulkan Buffer with allocation information tied to it\n*/\nstruct AllocatedBuffer {\n\tVkBuffer buffer{};\n\tVmaAllocation allocation{};\n\tVmaAllocationInfo allocation_info{};\n};\n\n/**\nWrapps a Vulkan Image with allocation information tied to it\n*/\nstruct AllocatedImage {\n\tVkImage image{};\n\tVmaAllocation allocation{};\n\tVmaAllocationInfo allocation_info{};\n};\n\n#else\n\n#pragma message ( \"This program is meant to currently use VMA allocation\" )\n#error Current code needs to use VMA allocation\n\nstruct AllocatedBuffer {\n\tVkBuffer buffer{};\n\tVkDeviceMemory memory{};\n};\n\nstruct AllocatedImage {\n\tVkImage image{};\n\tVkDeviceMemory memory{};\n};\n\n#endif\n\n\n/**\nWraps a Vulkan Command Buffer with relevant\ntype and state information tied to it\n*/\nstruct WrappedCommandBuffer {\n\tVkCommandBuffer buffer{};\n\tCommandType type{};\n\tbool recording{ false };\n};\n\n/**\nWraps a Vulkan Render Target with all the relevant information to\nrender to it like the image, memory, view, width, heigth and if it has\nbeen initializated.\n\nWe are not using an \"AllocatedImage\" because allocation of a render target\nis done with a custom method because of the special requirements of it being\na render target.\n*/\nstruct WrappedRenderTarget {\n\tVkImage image{};\n\tVkDeviceMemory memory{};\n\tVkImageView view{};\n\tuint width{};\n\tuint heigth{};\n\tbool init{ false };\n};\n\n/**\nStruct that holds dynamic configuration parameters of the renderer\n*/\nstruct RenderConfiguration {\n\tshort multisampling_samples{ config::initial_multisampling_samples };\n};\n\nstruct Vertex {\n\tglm::vec3 pos{};\n\tglm::vec3 color{};\n\tglm::vec2 tex_coord{};\n\n\tauto static getBindingDescription() noexcept ->VkVertexInputBindingDescription {\n\n\t\tauto binding_description = VkVertexInputBindingDescription{};\n\n\t\tbinding_description.binding = 0;\n\t\tbinding_description.stride = sizeof(Vertex);\n\t\tbinding_description.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;\n\n\t\treturn binding_description;\n\t}\n\n\tauto static getAttributeDescriptions() noexcept->std::array<VkVertexInputAttributeDescription, 3> {\n\n\t\tauto attribute_descriptions = std::array<VkVertexInputAttributeDescription, 3>{};\n\n\t\tattribute_descriptions[0].binding = 0;\n\t\tattribute_descriptions[0].location = 0;\n\t\tattribute_descriptions[0].format = VK_FORMAT_R32G32B32_SFLOAT;\n\t\tattribute_descriptions[0].offset = offsetof(Vertex, pos);\n\n\t\tattribute_descriptions[1].binding = 0;\n\t\tattribute_descriptions[1].location = 1;\n\t\tattribute_descriptions[1].format = VK_FORMAT_R32G32B32_SFLOAT;\n\t\tattribute_descriptions[1].offset = offsetof(Vertex, color);\n\n\t\tattribute_descriptions[2].binding = 0;\n\t\tattribute_descriptions[2].location = 2;\n\t\tattribute_descriptions[2].format = VK_FORMAT_R32G32_SFLOAT;\n\t\tattribute_descriptions[2].offset = offsetof(Vertex, tex_coord);\n\n\t\treturn attribute_descriptions;\n\t}\n\n\tauto operator==(const Vertex& other) const ->bool {\n\t\treturn\tpos == other.pos &&\n\t\t\t\tcolor == other.color &&\n\t\t\t\ttex_coord == other.tex_coord;\n\t}\n};\n\nnamespace std {\n\ttemplate<> struct hash<Vertex> {\n\t\tsize_t operator()(Vertex const& vertex) const {\n\t\t\treturn(\n\t\t\t\t(hash<glm::vec3>()(vertex.pos) ^\n\t\t\t\t(hash<glm::vec3>()(vertex.color) << 1)) >> 1) ^\n\t\t\t\t(hash<glm::vec2>()(vertex.tex_coord) << 1);\n\t\t}\n\t};\n}\n\n/*\nMVP model.\n\nhttp://www.opengl-tutorial.org/es/beginners-tutorials/tutorial-3-matrices/\nhttps://solarianprogrammer.com/2013/05/22/opengl-101-matrices-projection-view-model/\n*/\nstruct UniformBufferObject {\n\tglm::mat4 model{};\n\tglm::mat4 view{};\n\tglm::mat4 proj{};\n};\n\n\nstruct SimpleObjScene {\n\tstd::vector<Vertex> vertices;\n\tstd::vector<uint32_t> indices;\n\tAllocatedImage m_texture_image{};\n\tVkImageView m_texture_image_view{};\n};\n\n#if 0\n#pragma warning(push)\n#include <CppCoreCheck/Warnings.h>\n#pragma warning(disable: 26426)\nconst auto vertices = std::vector<Vertex>{\n\t{ { -0.5f, -0.5f, 0.0f },{ 1.0f, 0.0f, 0.0f }, { 1.0f, 0.0f} },\n\t{ {  0.5f, -0.5f, 0.0f },{ 0.0f, 1.0f, 0.0f }, { 0.0f, 0.0f } },\n\t{ {  0.5f,  0.5f, 0.0f },{ 0.0f, 0.0f, 1.0f }, { 0.0f, 1.0f } },\n\t{ { -0.5f,  0.5f, 0.0f },{ 1.0f, 1.0f, 1.0f }, { 1.0f, 1.0f } },\n\n\t{ { -0.5f, -0.5f, -0.5f },{ 1.0f, 0.0f, 0.0f },{ 1.0f, 0.0f } },\n\t{ {  0.5f, -0.5f, -0.5f },{ 0.0f, 1.0f, 0.0f },{ 0.0f, 0.0f } },\n\t{ {  0.5f,  0.5f, -0.5f },{ 0.0f, 0.0f, 1.0f },{ 0.0f, 1.0f } },\n\t{ { -0.5f,  0.5f, -0.5f },{ 1.0f, 1.0f, 1.0f },{ 1.0f, 1.0f } },\n};\n\nconst auto indices = std::vector<uint16_t>{\n\t0, 1, 2, 2, 3, 0,\n\t4, 5, 6, 6, 7, 4\n};\n#pragma warning(pop)\n#endif\n\n\n", "meta": {"hexsha": "e4fcef97090e6e5b8677f2809affe54310280cfe", "size": 5094, "ext": "h", "lang": "C", "max_stars_repo_path": "VR_ButNotReally/src/render/RenderData.h", "max_stars_repo_name": "Jazzzy/VR_ButNotReally", "max_stars_repo_head_hexsha": "82e0335ee86cc9cc32d784c4b1b55ab884ae0414", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "VR_ButNotReally/src/render/RenderData.h", "max_issues_repo_name": "Jazzzy/VR_ButNotReally", "max_issues_repo_head_hexsha": "82e0335ee86cc9cc32d784c4b1b55ab884ae0414", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "VR_ButNotReally/src/render/RenderData.h", "max_forks_repo_name": "Jazzzy/VR_ButNotReally", "max_forks_repo_head_hexsha": "82e0335ee86cc9cc32d784c4b1b55ab884ae0414", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7281553398, "max_line_length": 100, "alphanum_fraction": 0.7076953278, "num_tokens": 1551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.414898860266261, "lm_q2_score": 0.024798162718091307, "lm_q1q2_score": 0.010288729448433368}}
{"text": "//**************************************************************************\\\n//* This file is property of and copyright by the ALICE Project            *\\\n//* ALICE Experiment at CERN, All rights reserved.                         *\\\n//*                                                                        *\\\n//* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no>        *\\\n//*                  for The ALICE HLT Project.                            *\\\n//*                                                                        *\\\n//* Permission to use, copy, modify and distribute this software and its   *\\\n//* documentation strictly for non-commercial purposes is hereby granted   *\\\n//* without fee, provided that the above copyright notice appears in all   *\\\n//* copies and that both the copyright notice and this permission notice   *\\\n//* appear in the supporting documentation. The authors make no claims     *\\\n//* about the suitability of this software for any purpose. It is          *\\\n//* provided \"as is\" without express or implied warranty.                  *\\\n//**************************************************************************\n\n/// \\file GPUQA.h\n/// \\author David Rohr\n\n#ifndef GPUQA_H\n#define GPUQA_H\n\n#include \"GPUSettings.h\"\nstruct AliHLTTPCClusterMCWeight;\nclass TH1F;\nclass TH2F;\nclass TCanvas;\nclass TPad;\nclass TLegend;\nclass TPad;\nclass TH1;\nclass TFile;\nclass TH1D;\nclass TObjArray;\nclass TColor;\ntypedef short int Color_t;\n\n#if !defined(GPUCA_BUILD_QA) || defined(GPUCA_GPUCODE)\n\nnamespace GPUCA_NAMESPACE\n{\nnamespace gpu\n{\nclass GPUChainTracking;\n\nclass GPUQA\n{\n public:\n  GPUQA(GPUChainTracking* chain) {}\n  ~GPUQA() = default;\n\n  int InitQA(int tasks = 0) { return 1; }\n  void RunQA(bool matchOnly = false) {}\n  int DrawQAHistograms() { return 1; }\n  void SetMCTrackRange(int min, int max) {}\n  bool SuppressTrack(int iTrack) const { return false; }\n  bool SuppressHit(int iHit) const { return false; }\n  int HitAttachStatus(int iHit) const { return false; }\n  int GetMCTrackLabel(unsigned int trackId) const { return -1; }\n  bool clusterRemovable(int attach, bool prot) const { return false; }\n  static bool QAAvailable() { return false; }\n  static bool IsInitialized() { return false; }\n};\n} // namespace gpu\n} // namespace GPUCA_NAMESPACE\n\n#else\n\n#include \"GPUTPCDef.h\"\n#include <cmath>\n#include <vector>\n#include <memory>\n#ifdef GPUCA_TPC_GEOMETRY_O2\n#include <gsl/span>\n#endif\n\nnamespace o2\n{\nclass MCCompLabel;\nnamespace tpc\n{\nclass TrackTPC;\nstruct ClusterNativeAccess;\n} // namespace tpc\n} // namespace o2\n\nstruct AliHLTTPCClusterMCLabel;\n\nnamespace GPUCA_NAMESPACE::gpu\n{\nclass GPUChainTracking;\nclass GPUParam;\nstruct GPUTPCMCInfo;\nstruct GPUQAGarbageCollection;\n\nclass GPUQA\n{\n public:\n  GPUQA();\n  GPUQA(GPUChainTracking* chain, const GPUSettingsQA* config = nullptr, const GPUParam* param = nullptr);\n  ~GPUQA();\n\n  int InitQA(int tasks = -1);\n  void RunQA(bool matchOnly = false, const std::vector<o2::tpc::TrackTPC>* tracksExternal = nullptr, const std::vector<o2::MCCompLabel>* tracksExtMC = nullptr, const o2::tpc::ClusterNativeAccess* clNative = nullptr);\n  int DrawQAHistograms(TObjArray* qcout = nullptr);\n  void DrawQAHistogramsCleanup(); // Needed after call to DrawQAHistograms with qcout != nullptr when GPUSettingsQA.shipToQCAsCanvas = true to clean up the Canvases etc.\n  void SetMCTrackRange(int min, int max);\n  bool SuppressTrack(int iTrack) const;\n  bool SuppressHit(int iHit) const;\n  int HitAttachStatus(int iHit) const;\n  int GetMCTrackLabel(unsigned int trackId) const;\n  bool clusterRemovable(int attach, bool prot) const;\n  static bool QAAvailable() { return true; }\n  bool IsInitialized() { return mQAInitialized; }\n\n  const std::vector<TH1F>& getHistograms1D() const { return *mHist1D; }\n  const std::vector<TH2F>& getHistograms2D() const { return *mHist2D; }\n  const std::vector<TH1D>& getHistograms1Dd() const { return *mHist1Dd; }\n  void resetHists();\n  int loadHistograms(std::vector<TH1F>& i1, std::vector<TH2F>& i2, std::vector<TH1D>& i3, int tasks = -1);\n\n  static constexpr int N_CLS_HIST = 8;\n  static constexpr int N_CLS_TYPE = 3;\n\n  static constexpr int MC_LABEL_INVALID = -1e9;\n\n  enum QA_TASKS {\n    taskTrackingEff = 1,\n    taskTrackingRes = 2,\n    taskTrackingResPull = 4,\n    taskClusterAttach = 8,\n    taskTrackStatistics = 16,\n    taskClusterCounts = 32,\n    taskDefault = 63,\n    taskDefaultPostprocess = 31\n  };\n\n private:\n  struct additionalMCParameters {\n    float pt, phi, theta, eta, nWeightCls;\n  };\n\n  struct additionalClusterParameters {\n    int attached, fakeAttached, adjacent, fakeAdjacent;\n    float pt;\n  };\n\n  int InitQACreateHistograms();\n  int DoClusterCounts(unsigned long long int* attachClusterCounts, int mode = 0);\n  void PrintClusterCount(int mode, int& num, const char* name, unsigned long long int n, unsigned long long int normalization);\n\n  void SetAxisSize(TH1F* e);\n  void SetLegend(TLegend* l);\n  double* CreateLogAxis(int nbins, float xmin, float xmax);\n  void ChangePadTitleSize(TPad* p, float size);\n  void DrawHisto(TH1* histo, char* filename, char* options);\n  void doPerfFigure(float x, float y, float size);\n  void GetName(char* fname, int k);\n  template <class T>\n  T* GetHist(T*& ee, std::vector<std::unique_ptr<TFile>>& tin, int k, int nNewInput);\n\n#ifdef GPUCA_TPC_GEOMETRY_O2\n  using mcLabels_t = gsl::span<const o2::MCCompLabel>;\n  using mcLabel_t = o2::MCCompLabel;\n  using mcLabelI_t = mcLabel_t;\n  using mcInfo_t = GPUTPCMCInfo;\n  mcLabels_t GetMCLabel(unsigned int i);\n  mcLabel_t GetMCLabel(unsigned int i, unsigned int j);\n#else\n  using mcLabels_t = AliHLTTPCClusterMCLabel;\n  using mcLabel_t = AliHLTTPCClusterMCWeight;\n  struct mcLabelI_t {\n    int getTrackID() const { return AbsLabelID(track); }\n    int getEventID() const { return 0; }\n    long int getTrackEventSourceID() const { return getTrackID(); }\n    bool isFake() const { return track < 0; }\n    bool isValid() const { return track != MC_LABEL_INVALID; }\n    void invalidate() { track = MC_LABEL_INVALID; }\n    void setFakeFlag(bool v = true) { track = v ? FakeLabelID(track) : AbsLabelID(track); }\n    void setNoise() { track = MC_LABEL_INVALID; }\n    bool operator==(const mcLabel_t& l);\n    bool operator!=(const mcLabel_t& l) { return !(*this == l); }\n    mcLabelI_t() = default;\n    mcLabelI_t(const mcLabel_t& l);\n    int track = MC_LABEL_INVALID;\n  };\n  using mcInfo_t = GPUTPCMCInfo;\n  const mcLabels_t& GetMCLabel(unsigned int i);\n  const mcLabel_t& GetMCLabel(unsigned int i, unsigned int j);\n  const mcInfo_t& GetMCTrack(const mcLabelI_t& label);\n  static int FakeLabelID(const int id);\n  static int AbsLabelID(const int id);\n#endif\n  template <class T>\n  static auto& GetMCTrackObj(T& obj, const mcLabelI_t& l);\n\n  unsigned int GetNMCCollissions();\n  unsigned int GetNMCTracks(int iCol);\n  unsigned int GetNMCLabels();\n  const mcInfo_t& GetMCTrack(unsigned int iTrk, unsigned int iCol);\n  const mcInfo_t& GetMCTrack(const mcLabel_t& label);\n  int GetMCLabelNID(const mcLabels_t& label);\n  int GetMCLabelNID(unsigned int i);\n  int GetMCLabelID(unsigned int i, unsigned int j);\n  int GetMCLabelCol(unsigned int i, unsigned int j);\n  static int GetMCLabelID(const mcLabels_t& label, unsigned int j);\n  static int GetMCLabelID(const mcLabel_t& label);\n  float GetMCLabelWeight(unsigned int i, unsigned int j);\n  float GetMCLabelWeight(const mcLabels_t& label, unsigned int j);\n  float GetMCLabelWeight(const mcLabel_t& label);\n  const auto& GetClusterLabels();\n  bool mcPresent();\n\n  static bool MCComp(const mcLabel_t& a, const mcLabel_t& b);\n\n  GPUChainTracking* mTracking;\n  const GPUSettingsQA& mConfig;\n  const GPUParam& mParam;\n\n  const char* str_perf_figure_1 = \"ALICE Performance 2018/03/20\";\n  // const char* str_perf_figure_2 = \"2015, MC pp, #sqrt{s} = 5.02 TeV\";\n  const char* str_perf_figure_2 = \"2015, MC Pb-Pb, #sqrt{s_{NN}} = 5.02 TeV\";\n  //-------------------------\n\n  std::vector<mcLabelI_t> mTrackMCLabels;\n#ifdef GPUCA_TPC_GEOMETRY_O2\n  std::vector<std::vector<int>> mTrackMCLabelsReverse;\n  std::vector<std::vector<int>> mRecTracks;\n  std::vector<std::vector<int>> mFakeTracks;\n  std::vector<std::vector<additionalMCParameters>> mMCParam;\n  std::vector<std::vector<mcInfo_t>> mMCInfos;\n  std::vector<int> mNColTracks;\n#else\n  std::vector<int> mTrackMCLabelsReverse[1];\n  std::vector<int> mRecTracks[1];\n  std::vector<int> mFakeTracks[1];\n  std::vector<additionalMCParameters> mMCParam[1];\n#endif\n  std::vector<additionalClusterParameters> mClusterParam;\n  int mNTotalFakes = 0;\n\n  TH1F* mEff[4][2][2][5][2]; // eff,clone,fake,all - findable - secondaries - y,z,phi,eta,pt - work,result\n  TCanvas* mCEff[6];\n  TPad* mPEff[6][4];\n  TLegend* mLEff[6];\n\n  TH1F* mRes[5][5][2]; // y,z,phi,lambda,pt,ptlog res - param - res,mean\n  TH2F* mRes2[5][5];\n  TCanvas* mCRes[7];\n  TPad* mPRes[7][5];\n  TLegend* mLRes[6];\n\n  TH1F* mPull[5][5][2]; // y,z,phi,lambda,pt,ptlog res - param - res,mean\n  TH2F* mPull2[5][5];\n  TCanvas* mCPull[7];\n  TPad* mPPull[7][5];\n  TLegend* mLPull[6];\n\n  enum CL_types { CL_attached = 0,\n                  CL_fake = 1,\n                  CL_att_adj = 2,\n                  CL_fakeAdj = 3,\n                  CL_tracks = 4,\n                  CL_physics = 5,\n                  CL_prot = 6,\n                  CL_all = 7 };\n  TH1D* mClusters[N_CLS_TYPE * N_CLS_HIST - 1]; // attached, fakeAttached, attach+adjacent, fakeAdjacent, physics, protected, tracks, all / count, rel, integral\n  TCanvas* mCClust[N_CLS_TYPE];\n  TPad* mPClust[N_CLS_TYPE];\n  TLegend* mLClust[N_CLS_TYPE];\n\n  struct counts_t {\n    long long int nRejected = 0, nTube = 0, nTube200 = 0, nLoopers = 0, nLowPt = 0, n200MeV = 0, nPhysics = 0, nProt = 0, nUnattached = 0, nTotal = 0, nHighIncl = 0, nAbove400 = 0, nFakeRemove400 = 0, nFullFakeRemove400 = 0, nBelow40 = 0, nFakeProtect40 = 0, nMergedLooper = 0;\n    double nUnaccessible = 0;\n  } mClusterCounts;\n\n  TH1F* mTracks;\n  TCanvas* mCTracks;\n  TPad* mPTracks;\n  TLegend* mLTracks;\n\n  TH1F* mNCl;\n  TCanvas* mCNCl;\n  TPad* mPNCl;\n  TLegend* mLNCl;\n\n  std::vector<TH2F*> mHistClusterCount;\n\n  std::vector<TH1F>* mHist1D = nullptr;\n  std::vector<TH2F>* mHist2D = nullptr;\n  std::vector<TH1D>* mHist1Dd = nullptr;\n  bool mHaveExternalHists = false;\n  std::vector<TH1F**> mHist1D_pos{};\n  std::vector<TH2F**> mHist2D_pos{};\n  std::vector<TH1D**> mHist1Dd_pos{};\n  template <class T>\n  auto getHistArray();\n  template <class T, typename... Args>\n  void createHist(T*& h, const char* name, Args... args);\n\n  std::unique_ptr<GPUQAGarbageCollection> mGarbageCollector;\n  template <class T, typename... Args>\n  T* createGarbageCollected(Args... args);\n  void clearGarbagageCollector();\n\n  int mNEvents = 0;\n  bool mQAInitialized = false;\n  int mQATasks = 0;\n  std::vector<std::vector<int>> mcEffBuffer;\n  std::vector<std::vector<int>> mcLabelBuffer;\n  std::vector<std::vector<bool>> mGoodTracks;\n  std::vector<std::vector<bool>> mGoodHits;\n\n  static std::vector<TColor*> mColors;\n  static int initColors();\n\n  int mMCTrackMin = -1, mMCTrackMax = -1;\n\n  const o2::tpc::ClusterNativeAccess* mClNative = nullptr;\n};\n\ninline bool GPUQA::SuppressTrack(int iTrack) const { return (mConfig.matchMCLabels.size() && !mGoodTracks[mNEvents][iTrack]); }\ninline bool GPUQA::SuppressHit(int iHit) const { return (mConfig.matchMCLabels.size() && !mGoodHits[mNEvents - 1][iHit]); }\ninline int GPUQA::HitAttachStatus(int iHit) const { return (mClusterParam.size() && mClusterParam[iHit].fakeAttached ? (mClusterParam[iHit].attached ? 1 : 2) : 0); }\n\n} // namespace GPUCA_NAMESPACE::gpu\n\n#endif\n#endif\n", "meta": {"hexsha": "b861c1a5be077b1b9bef941d8e0763c576bf1fc6", "size": 11560, "ext": "h", "lang": "C", "max_stars_repo_path": "GPU/GPUTracking/Standalone/qa/GPUQA.h", "max_stars_repo_name": "iarsene/AliRoot", "max_stars_repo_head_hexsha": "52edd953c66dfddf00c80fc970409bbe6cfcc349", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GPU/GPUTracking/Standalone/qa/GPUQA.h", "max_issues_repo_name": "iarsene/AliRoot", "max_issues_repo_head_hexsha": "52edd953c66dfddf00c80fc970409bbe6cfcc349", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 21.0, "max_issues_repo_issues_event_min_datetime": "2017-10-25T10:01:30.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-09T06:03:12.000Z", "max_forks_repo_path": "GPU/GPUTracking/Standalone/qa/GPUQA.h", "max_forks_repo_name": "iarsene/AliRoot", "max_forks_repo_head_hexsha": "52edd953c66dfddf00c80fc970409bbe6cfcc349", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-12-15T09:46:36.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-15T09:46:36.000Z", "avg_line_length": 35.0303030303, "max_line_length": 277, "alphanum_fraction": 0.6823529412, "num_tokens": 3407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23370636758849894, "lm_q2_score": 0.04401864563031932, "lm_q1q2_score": 0.01028743777642728}}
{"text": "#pragma GCC diagnostic ignored \"-Wdeclaration-after-statement\"\n/*\n * ocl_model_maintenance.c\n *\n *  Created on: 09.02.2014\n *      Author: mheimel\n */\n\n#include \"ocl_model_maintenance.h\"\n\n#include <math.h>\n#include <stdlib.h>\n#include <sys/time.h>\n\n#include \"ocl_adaptive_bandwidth.h\"\n#include \"ocl_error_metrics.h\"\n#include \"ocl_estimator.h\"\n#include \"ocl_sample_maintenance.h\"\n#include \"ocl_utilities.h\"\n\n// Optimization routines.\n#include <nlopt.h>\n#include \"lbfgs/lbfgs.h\"\n\n#include \"catalog/pg_kdefeedback.h\"\n#include \"executor/spi.h\"\n#include \"optimizer/path/gpukde/ocl_estimator_api.h\"\n#include \"storage/lock.h\"\n\n// Global GUC variables\nbool kde_enable_bandwidth_optimization;\nint kde_bandwidth_optimization_feedback_window;\nextern int kde_bandwidth_representation;\n\nconst double learning_rate = 0.01f;\n\n// ############################################################\n// # Code for adaptive bandwidth optimization (online learning).\n// ############################################################\n\nvoid ocl_notifyModelMaintenanceOfSelectivity(\n    Oid relation, double selected, double allrows) {\n  CREATE_TIMER();\n\n  // Check if we have an estimator for this relation.\n  ocl_estimator_t* estimator = ocl_getEstimator(relation);\n  if (estimator == NULL) return;\n  if (!estimator->open_estimation) return;  // No registered estimation.\n\n  double selectivity = selected / allrows;\n  estimator->rows_in_table = allrows;\n  \n  // Notify the sample maintenance of this observation so it can track the sample quality.\n  ocl_notifySampleMaintenanceOfSelectivity(estimator, selectivity);\n\n  // Update the bandwidth using online learning.\n  ocl_runOnlineLearningStep(estimator, selectivity);\n\n  // Write the error to the log file.\n  ocl_reportErrorToLogFile(\n      relation, estimator->last_selectivity, selectivity,\n      estimator->rows_in_table);\n\n  // We are done.\n  estimator->open_estimation = false;\n  LOG_TIMER(\"Model Maintenance\");\n}\n\n// ############################################################\n// # Code for offline bandwidth optimization (batch learning).\n// ############################################################\n\n// Helper function to extract the n latest feedback records for the given\n// estimator from the catalogue. The function will only return tuples that\n// have feedback that matches the estimator's attributes.\n//\n// Returns the actual number of valid feedback records in the catalog.\nstatic unsigned int ocl_extractLatestFeedbackRecordsFromCatalog(\n    ocl_estimator_t* estimator, unsigned int requested_records,\n    kde_float_t* range_buffer, kde_float_t* selectivity_buffer) {\n  unsigned int current_tuple = 0;\n\n  // Open a new scan over the feedback table.\n  unsigned int i, j;\n  if (SPI_connect() != SPI_OK_CONNECT) {\n    fprintf(stderr, \"> Error connecting to Postgres Backend.\\n\");\n    return current_tuple;\n  }\n  char query_buffer[1024];\n  snprintf(query_buffer, 1024,\n           \"SELECT columns, ranges, alltuples, qualifiedtuples FROM \"\n           \"pg_kdefeedback WHERE \\\"table\\\" = %i ORDER BY \\\"timestamp\\\" DESC \"\n           \"LIMIT %i;\", estimator->table, requested_records);\n  if (SPI_execute(query_buffer, true, 0) != SPI_OK_SELECT) {\n    fprintf(stderr, \"> Error querying system table.\\n\");\n    return current_tuple;\n  }\n  SPITupleTable *spi_tuptable = SPI_tuptable;\n  unsigned int result_tuples = SPI_processed;\n  TupleDesc spi_tupdesc = spi_tuptable->tupdesc;\n  for (i = 0; i < result_tuples; ++i) {\n    bool isnull;\n    HeapTuple record_tuple = spi_tuptable->vals[i];\n    // First, check whether this record only covers columns that are part of the estimator.\n    unsigned int columns_in_record = DatumGetInt32(\n          SPI_getbinval(record_tuple, spi_tupdesc, 1, &isnull));\n    if ((columns_in_record | estimator->columns) != estimator->columns) continue;\n    // This is a valid record, initialize the range buffer.\n    unsigned int pos = current_tuple * 2 * estimator->nr_of_dimensions;\n    for (j=0; j<estimator->nr_of_dimensions; ++j) {\n      range_buffer[pos + 2*j] = -1.0 * INFINITY;\n      range_buffer[pos + 2*j + 1] = INFINITY;\n    }\n    // Now extract all clauses and isert them into the range buffer.\n    RQClause* clauses;\n    unsigned int nr_of_clauses = extract_clauses_from_buffer(DatumGetByteaP(\n        SPI_getbinval(record_tuple, spi_tupdesc, 2, &isnull)), &clauses);\n    for (j=0; j<nr_of_clauses; ++j) {\n      // First, locate the correct column position in the estimator.\n      int column_in_estimator = estimator->column_order[clauses[j].var];\n      // Re-Scale the bounds, add potential padding and write them to their position.\n      float8 lo = clauses[j].lobound;\n      if (clauses[j].loinclusive != EX) lo -= 0.001;\n      float8 hi = clauses[j].hibound;\n      if (clauses[j].hiinclusive != EX) hi += 0.001;\n      range_buffer[pos + 2*column_in_estimator] = lo;\n      range_buffer[pos + 2*column_in_estimator + 1] = hi;\n    }\n    // Finally, extract the selectivity and increase the tuple count.\n    double all_rows = DatumGetFloat8(\n        SPI_getbinval(record_tuple, spi_tupdesc, 3, &isnull));\n    double qualified_rows = DatumGetFloat8(\n        SPI_getbinval(record_tuple, spi_tupdesc, 4, &isnull));\n    selectivity_buffer[current_tuple++] = qualified_rows / all_rows;\n  }\n  // We are done :)\n  SPI_finish();\n  return current_tuple;\n}\n\n// Helper function that extracts feedback for the given estimator and\n// pushes it to the device.\nstatic unsigned int ocl_prepareFeedback(\n    ocl_estimator_t* estimator, cl_mem* device_ranges,\n    cl_mem* device_selectivities) {\n  cl_int err = CL_SUCCESS;\n  // First, we have to count how many matching feedback records are available\n  // for this estimator in the query feedback table.\n  if (SPI_connect() != SPI_OK_CONNECT) {\n    fprintf(stderr, \"> Error connecting to Postgres Backend.\\n\");\n    return 0;\n  }\n  char query_buffer[1024];\n  snprintf(query_buffer, 1024,\n           \"SELECT COUNT(*) FROM pg_kdefeedback WHERE \\\"table\\\" = %i;\",\n           estimator->table);\n  if (SPI_execute(query_buffer, true, 0) != SPI_OK_SELECT) {\n    fprintf(stderr, \"> Error querying system table.\\n\");\n    return 0;\n  }\n  SPITupleTable *tuptable = SPI_tuptable;\n  bool isnull;\n  unsigned int available_records = DatumGetInt32(\n      SPI_getbinval(tuptable->vals[0], tuptable->tupdesc, 1, &isnull));\n  SPI_finish();\n\n  if (available_records == 0) {\n    fprintf(stderr, \"> No feedback available for table %i\\n\", estimator->table);\n    return 0;\n  }\n\n  // Adjust the number of records according to the specified window size.\n  int used_records;\n  if (kde_bandwidth_optimization_feedback_window == -1)\n    used_records = available_records;\n  else\n    used_records = Min(available_records,\n                       kde_bandwidth_optimization_feedback_window);\n  fprintf(stderr, \"> Checking the %i latest feedback records.\\n\", used_records);\n\n  // Allocate arrays and fetch the actual feedback data.\n  kde_float_t* range_buffer = palloc(\n      sizeof(kde_float_t) * 2 * estimator->nr_of_dimensions * used_records);\n  kde_float_t* selectivity_buffer = palloc(sizeof(kde_float_t) * used_records);\n  unsigned int actual_records = ocl_extractLatestFeedbackRecordsFromCatalog(\n      estimator, used_records, range_buffer, selectivity_buffer);\n\n  // Now push the records to the device to prepare the actual optimization.\n  if (actual_records == 0) {\n    fprintf(stderr, \"> No valid feedback records found.\\n\");\n    return 0;\n  }\n  fprintf(stderr, \"> Found %i valid records, pushing to device.\\n\",\n          actual_records);\n  ocl_context_t* context = ocl_getContext();\n  *device_ranges = clCreateBuffer(\n      context->context, CL_MEM_READ_WRITE,\n      sizeof(kde_float_t) * 2 * actual_records * estimator->nr_of_dimensions,\n      NULL, &err);\n  Assert(err == CL_SUCCESS);\n  \n  err = clEnqueueWriteBuffer(\n      context->queue, *device_ranges, CL_FALSE, 0,\n      sizeof(kde_float_t) * 2 * actual_records * estimator->nr_of_dimensions,\n      range_buffer, 0, NULL, NULL);\n  estimator->stats->optimization_transfer_to_device++;\n  Assert(err == CL_SUCCESS);\n  \n  *device_selectivities = clCreateBuffer(\n      context->context, CL_MEM_READ_WRITE,\n      sizeof(kde_float_t) * actual_records, NULL, &err);\n  Assert(err == CL_SUCCESS);\n  \n  err = clEnqueueWriteBuffer(\n      context->queue, *device_selectivities, CL_FALSE, 0,\n      sizeof(kde_float_t) * actual_records, selectivity_buffer, 0, NULL, NULL);\n  estimator->stats->optimization_transfer_to_device++;\n  Assert(err == CL_SUCCESS);\n  \n  err = clFinish(context->queue);\n  Assert(err == CL_SUCCESS);\n  \n  pfree(range_buffer);\n  pfree(selectivity_buffer);\n  return actual_records;\n}\n\ntypedef struct {\n  ocl_estimator_t* estimator;\n  unsigned int nr_of_observations;\n  cl_mem observed_ranges;\n  cl_mem observed_selectivities;\n  // Temporary buffers.\n  size_t stride_size;\n  cl_mem gradient_accumulator_buffer;\n  cl_mem error_accumulator_buffer;\n  cl_mem gradient_buffer;\n  cl_mem error_buffer;\n  // Required event and accumulation buffers.\n  ocl_aggregation_descriptor_t** summation_descriptors;\n  cl_mem* summation_buffers;\n} optimization_config_t;\n\n/**\n * Counters for evaluations.\n */\nint evaluations;\ndouble start_error;\nstruct timeval opt_start;\n\n/*\n * Function to compute the gradient for a penalized objective function that will\n * add a strong penalty factor to negative bandwidth values. This function is\n * passed to nlopt to compute the gradient and evaluate the function.\n */\n\n/*\n * Callback function that computes the gradient and value for the objective\n * function at the current bandwidth.\n */\nstatic double computeGradient(\n    unsigned n, const double* bandwidth, double* gradient, void* params) {\n  unsigned int i;\n  cl_int err = CL_SUCCESS;\n  optimization_config_t* conf = (optimization_config_t*)params;\n  ocl_estimator_t* estimator = conf->estimator;\n  ocl_context_t* context = ocl_getContext();\n\n  evaluations++;\n\n  if (ocl_isDebug()) {\n    fprintf(stderr, \">>> Evaluation %i:\\n\\tCurrent bandwidth:\", evaluations);\n    for (i=0; i<n; ++i) fprintf(stderr, \" %e\", bandwidth[i]);\n    fprintf(stderr, \"\\n\");\n  }\n\n  // First, transfer the current bandwidth to the device. Note that we might\n  // need to cast the bandwidth to float first.\n  kde_float_t* fbandwidth = NULL;\n  cl_event input_transfer_event;\n  if (sizeof(kde_float_t) != sizeof(double)) {\n    fbandwidth = palloc(sizeof(kde_float_t) * estimator->nr_of_dimensions);\n    for (i = 0; i<estimator->nr_of_dimensions; ++i) {\n      fbandwidth[i] = bandwidth[i];\n    }\n    err = clEnqueueWriteBuffer(\n        context->queue, estimator->bandwidth_buffer, CL_FALSE,\n        0, sizeof(kde_float_t) * estimator->nr_of_dimensions,\n        fbandwidth, 0, NULL, &input_transfer_event);\n    estimator->stats->optimization_transfer_to_device++;\n    Assert(err == CL_SUCCESS);\n  } else {\n    err = clEnqueueWriteBuffer(\n        context->queue, estimator->bandwidth_buffer, CL_FALSE,\n        0, sizeof(kde_float_t) * estimator->nr_of_dimensions,\n        bandwidth, 0, NULL, &input_transfer_event);\n    estimator->stats->optimization_transfer_to_device++;\n    Assert(err == CL_SUCCESS);\n  }\n  // Prepare the kernel that computes a gradient for each observation.\n  cl_kernel gradient_kernel = ocl_getKernel(\n      ocl_getSelectedErrorMetric()->batch_kernel_name,\n      estimator->nr_of_dimensions);\n    // First, fix the local and global size. We identify the optimal local size\n    // by looking at available and required local memory and by ensuring that\n    // the local size is evenly divisible by the preferred workgroup multiple..\n  size_t local_size;\n  err = clGetKernelWorkGroupInfo(\n      gradient_kernel, context->device, CL_KERNEL_WORK_GROUP_SIZE,\n      sizeof(size_t), &local_size, NULL);\n  Assert(err == CL_SUCCESS);\n  \n  size_t available_local_memory;\n  err = clGetKernelWorkGroupInfo(\n      gradient_kernel, context->device, CL_KERNEL_LOCAL_MEM_SIZE,\n      sizeof(size_t), &available_local_memory, NULL);\n  Assert(err == CL_SUCCESS);\n  \n  available_local_memory = context->local_mem_size - available_local_memory;\n  local_size = Min(\n      local_size,\n      available_local_memory / (3 * sizeof(kde_float_t) * estimator->nr_of_dimensions));\n  size_t preferred_local_size_multiple;\n  err = clGetKernelWorkGroupInfo(\n      gradient_kernel, context->device,\n      CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE,\n      sizeof(size_t), &preferred_local_size_multiple, NULL);\n  Assert(err == CL_SUCCESS);\n  \n  local_size = preferred_local_size_multiple\n      * (local_size / preferred_local_size_multiple);\n  size_t global_size = local_size * (conf->nr_of_observations / local_size);\n  if (global_size < conf->nr_of_observations) global_size += local_size;\n    // Configure the kernel by setting all required parameters.\n  err |= clSetKernelArg(\n      gradient_kernel, 0, sizeof(cl_mem), &(estimator->sample_buffer));\n  err |= clSetKernelArg(\n      gradient_kernel, 1, sizeof(unsigned int), &(estimator->rows_in_sample));\n  err |= clSetKernelArg(\n      gradient_kernel, 2, sizeof(cl_mem), &(conf->observed_ranges));\n  err |= clSetKernelArg(\n      gradient_kernel, 3, sizeof(cl_mem), &(conf->observed_selectivities));\n  err |= clSetKernelArg(\n      gradient_kernel, 4, sizeof(unsigned int), &(conf->nr_of_observations));\n  err |= clSetKernelArg(\n      gradient_kernel, 5, sizeof(cl_mem), &(estimator->bandwidth_buffer));\n  err |= clSetKernelArg(\n      gradient_kernel, 6,\n      local_size * sizeof(kde_float_t) * estimator->nr_of_dimensions, NULL);\n  err |= clSetKernelArg(\n      gradient_kernel, 7,\n      local_size * sizeof(kde_float_t) * estimator->nr_of_dimensions, NULL);\n  err |= clSetKernelArg(\n      gradient_kernel, 8,\n      local_size * sizeof(kde_float_t) * estimator->nr_of_dimensions, NULL);\n  err |= clSetKernelArg(\n      gradient_kernel, 9, sizeof(cl_mem), &(conf->error_accumulator_buffer));\n  err |= clSetKernelArg(\n      gradient_kernel, 10, sizeof(cl_mem),\n      &(conf->gradient_accumulator_buffer));\n  unsigned int stride_elements = conf->stride_size / sizeof(kde_float_t);\n  err |= clSetKernelArg(\n      gradient_kernel, 11, sizeof(unsigned int), &stride_elements);\n  err |= clSetKernelArg(\n      gradient_kernel, 12, sizeof(unsigned int), &(estimator->rows_in_table));\n  err |= clSetKernelArg(\n      gradient_kernel, 13, sizeof(cl_mem), &(estimator->mean_buffer));\n  err |= clSetKernelArg(\n      gradient_kernel, 14, sizeof(cl_mem), &(estimator->sdev_buffer));\n  Assert(err == CL_SUCCESS);\n  \n  // Compute the gradient for each observation.\n  cl_event partial_gradient_event;\n  err = clEnqueueNDRangeKernel(\n      context->queue, gradient_kernel, 1, NULL, &global_size, &local_size, 1,\n      &input_transfer_event, &partial_gradient_event);\n  Assert(err == CL_SUCCESS);\n  \n  // Sum up the individual error contributions ...\n  cl_event* summation_events = palloc(\n      sizeof(cl_event) * (1 + estimator->nr_of_dimensions));\n\n  summation_events[0] = predefinedSumOfArray(\n      conf->summation_descriptors[0], partial_gradient_event);\n  // .. and the individual gradients.\n  for (i=0; i<estimator->nr_of_dimensions; ++i) {\n    summation_events[i + 1] = predefinedSumOfArray(\n        conf->summation_descriptors[i + 1], partial_gradient_event);\n  }\n  // Now transfer the gradient back to the device.\n  cl_event result_events[2];\n  kde_float_t* tmp_gradient = palloc(\n      sizeof(kde_float_t) * estimator->nr_of_dimensions);\n  err = clEnqueueReadBuffer(\n      context->queue, conf->gradient_buffer, CL_FALSE,\n      0, sizeof(kde_float_t) * estimator->nr_of_dimensions,\n      tmp_gradient, estimator->nr_of_dimensions + 1,\n      summation_events, &(result_events[0]));\n  estimator->stats->optimization_transfer_to_host++;\n  Assert(err == CL_SUCCESS);\n  \n  // As well as the error.\n  kde_float_t error;\n  err = clEnqueueReadBuffer(\n      context->queue, conf->error_buffer, CL_FALSE,\n      0, sizeof(kde_float_t), &error,\n      1, &(summation_events[0]),  &(result_events[1]));\n  estimator->stats->optimization_transfer_to_host++;\n  Assert(err == CL_SUCCESS);\n  \n  err = clWaitForEvents(2, result_events);\n  Assert(err == CL_SUCCESS);\n  \n  if (err != 0) {\n    fprintf(stderr, \"OpenCL functions failed to compute gradient.\\n\");\n  }\n  \n  error /= conf->nr_of_observations;\n  if (evaluations == 1) start_error = error;\n  struct timeval now; gettimeofday(&now, NULL);\n  long seconds = now.tv_sec - opt_start.tv_sec;\n  long useconds = now.tv_usec - opt_start.tv_usec;\n  long mtime = ((seconds) * 1000 + useconds / 1000.0) + 0.5;\n  // Ok, cool. Transfer the bandwidth back.\n  if (ocl_isDebug()) {\n    fprintf(\n        stderr, \"\\r\\tOptimization round %i. Current error: %f \"\n        \"(started at %f), took: %ld ms.\",\n        evaluations, error, start_error, mtime);\n  }\n  // Finally, cast back to double.\n  if (gradient) {\n    for (i = 0; i<estimator->nr_of_dimensions; ++i) {\n    // Apply the gradient normalization.\n      double h = bandwidth[i];\n      if(kde_bandwidth_representation == PLAIN_BW){\n          gradient[i] = tmp_gradient[i] * M_SQRT2 / (\n              sqrt(M_PI) * h * h * pow(2.0, estimator->nr_of_dimensions) *\n              conf->nr_of_observations * estimator->rows_in_sample);\n      }\n      else {\n          gradient[i] = tmp_gradient[i] * M_SQRT2 / (\n              sqrt(M_PI) * exp(h) * pow(2.0, estimator->nr_of_dimensions) *\n              conf->nr_of_observations * estimator->rows_in_sample);\n      }\n    }\n    if (ocl_isDebug()) {\n      fprintf(stderr, \"\\n\\tGradient:\");\n      for (i=0; i<n; ++i) fprintf(stderr, \" %e\", gradient[i]);\n      fprintf(stderr, \"\\n\");\n    }\n  }\n  // Ok, clean everything up.\n  for (i=0; i<estimator->nr_of_dimensions; ++i) {\n    err = clReleaseEvent(summation_events[i]);\n    Assert(err == CL_SUCCESS);\n  }\n  pfree(summation_events);\n  pfree(tmp_gradient);\n  if (fbandwidth) pfree(fbandwidth);\n  err |= clReleaseEvent(input_transfer_event);\n  err |= clReleaseEvent(partial_gradient_event);\n  err |= clReleaseEvent(result_events[0]);\n  err |= clReleaseEvent(result_events[1]);\n  err |= clReleaseKernel(gradient_kernel);\n  Assert(err == CL_SUCCESS);\n  \n  return error;\n}\n\nstatic void ocl_setScottsBandwidth(ocl_estimator_t* estimator) {\n  ocl_context_t* context = ocl_getContext();\n  cl_int err = CL_SUCCESS;\n  // First, we need to compute the variance for each dimension.\n  unsigned int i;\n  kde_float_t* variances = malloc(\n      sizeof(kde_float_t) * estimator->nr_of_dimensions);\n  cl_mem* buffers = malloc(sizeof(cl_mem) * estimator->nr_of_dimensions);\n  cl_mem averages = clCreateBuffer(\n      context->context, CL_MEM_READ_WRITE,\n      sizeof(kde_float_t) * estimator->nr_of_dimensions, NULL, &err);\n  Assert(err == CL_SUCCESS);\n  cl_event* events = malloc(sizeof(cl_event) * estimator->nr_of_dimensions);\n  size_t sample_size = estimator->rows_in_sample;\n  size_t dimensions = estimator->nr_of_dimensions;\n  for (i=0; i<estimator->nr_of_dimensions; ++i) {\n    // Allocate all required buffers.\n    buffers[i] = clCreateBuffer(\n        context->context, CL_MEM_READ_WRITE,\n        sizeof(kde_float_t) * estimator->rows_in_sample, NULL, &err);\n    Assert(err == CL_SUCCESS);\n    // First we extract all sample components for this dimension.\n    cl_kernel extractComponents = ocl_getKernel(\"extract_dimension\", 0);\n    err |= clSetKernelArg(\n        extractComponents, 0, sizeof(cl_mem), &(estimator->sample_buffer));\n    err |= clSetKernelArg(extractComponents, 1, sizeof(cl_mem), &(buffers[i]));\n    err |= clSetKernelArg(extractComponents, 2, sizeof(unsigned int), &i);\n    err |= clSetKernelArg(extractComponents, 3, sizeof(unsigned int),\n        &(estimator->nr_of_dimensions));\n    Assert(err == CL_SUCCESS);\n    \n    cl_event extraction_event;\n    err = clEnqueueNDRangeKernel(\n        context->queue, extractComponents, 1, NULL, &sample_size, NULL,\n        0, NULL, &extraction_event);\n    Assert(err == CL_SUCCESS);\n    // Now we sum them up, so we can compute the average.\n    cl_event average_summation_event = sumOfArray(\n        buffers[i], estimator->rows_in_sample, averages, i, extraction_event);\n    // Alright, we can compute the variance contributions from each point.\n    cl_kernel precomputeVariance = ocl_getKernel(\"precompute_variance\", 0);\n    err |= clSetKernelArg(precomputeVariance, 0, sizeof(cl_mem), &(buffers[i]));\n    err |= clSetKernelArg(precomputeVariance, 1, sizeof(cl_mem), &averages);\n    err |= clSetKernelArg(precomputeVariance, 2, sizeof(unsigned int), &i);\n    err |= clSetKernelArg(precomputeVariance, 3, sizeof(unsigned int),\n        &(estimator->rows_in_sample));\n    cl_event variance_event;\n    err = clEnqueueNDRangeKernel(\n        context->queue, precomputeVariance, 1, NULL, &sample_size, NULL,\n        1, &average_summation_event, &variance_event);\n    Assert(err == CL_SUCCESS);\n    \n    // We now sum up the single contributions to compute the variance.\n    cl_event variance_summation_event = sumOfArray(\n        buffers[i], estimator->rows_in_sample, averages, i, variance_event);\n    // Finally, we can compute and store the bandwidth for this value.\n    cl_kernel finalizeBandwidth = ocl_getKernel(\"set_scotts_bandwidth\", 0);\n    err |= clSetKernelArg(finalizeBandwidth, 0, sizeof(cl_mem), &averages);\n    err |= clSetKernelArg(finalizeBandwidth, 1, sizeof(cl_mem),\n        &(estimator->bandwidth_buffer));\n    err |= clSetKernelArg(finalizeBandwidth, 2, sizeof(unsigned int), &i);\n    err |= clSetKernelArg(finalizeBandwidth, 3, sizeof(unsigned int),\n        &(estimator->nr_of_dimensions));\n    err |= clSetKernelArg(finalizeBandwidth, 4, sizeof(unsigned int),\n        &(estimator->rows_in_sample));\n    Assert(err == CL_SUCCESS);\n    \n    err = clEnqueueNDRangeKernel(\n        context->queue, finalizeBandwidth, 1, NULL, &dimensions, NULL,\n        1, &variance_summation_event, &events[i]);\n    Assert(err == CL_SUCCESS);\n    // Clean up.\n    err = clReleaseMemObject(buffers[i]);\n    Assert(err == CL_SUCCESS);\n    \n    err |= clReleaseEvent(extraction_event);\n    err |= clReleaseEvent(average_summation_event);\n    err |= clReleaseEvent(variance_event);\n    err |= clReleaseEvent(variance_summation_event);\n    Assert(err == CL_SUCCESS);\n  }\n  err = clReleaseMemObject(averages);\n  Assert(err == CL_SUCCESS);\n  // Wait for the events to finalize:\n  err = clWaitForEvents(estimator->nr_of_dimensions, events);\n  Assert(err == CL_SUCCESS);\n  for (i=0; i<estimator->nr_of_dimensions; ++i) {\n    err = clReleaseEvent(events[i]);\n    Assert(err == CL_SUCCESS);\n  }\n  // Clean up.\n  free(variances);\n  free(events);\n}\n\nvoid ocl_runModelOptimization(ocl_estimator_t* estimator) {\n  if (estimator == NULL) return;\n  cl_int err = CL_SUCCESS;\n  // Set the rule-of-thumb bandwidth to initialize the estimator.\n  ocl_setScottsBandwidth(estimator);\n  // Now check if we do a full bandwidth optimization.\n  if (!kde_enable_bandwidth_optimization) return;\n  if (ocl_isDebug()) {\n    fprintf(\n        stderr, \"Beginning model optimization for estimator on table %i\\n\",\n        estimator->table);\n  }\n  // First, we need to fetch the feedback records for this table and push them\n  // to the device.\n  cl_mem device_ranges, device_selectivites;\n  unsigned int feedback_records = ocl_prepareFeedback(\n      estimator, &device_ranges, &device_selectivites);\n  if (feedback_records == 0) return;\n\n  // We need to transfer the bandwidth to the host.\n  kde_float_t* fbandwidth = palloc(\n      sizeof(kde_float_t) * estimator->nr_of_dimensions);\n  ocl_context_t* context = ocl_getContext();\n  err = clEnqueueReadBuffer(\n      context->queue, estimator->bandwidth_buffer, CL_TRUE, 0,\n      sizeof(kde_float_t) * estimator->nr_of_dimensions,\n      fbandwidth, 0, NULL, NULL);\n  estimator->stats->optimization_transfer_to_host++;\n  Assert(err == CL_SUCCESS);\n  // Cast to double (nlopt operates on double).\n  double* bandwidth = lbfgs_malloc(estimator->nr_of_dimensions);\n  unsigned int i;\n  for (i=0; i<estimator->nr_of_dimensions; ++i) {\n    bandwidth[i] = fbandwidth[i];\n  }\n  // Package all required buffers.\n  optimization_config_t params;\n  params.estimator = estimator;\n  params.nr_of_observations = feedback_records;\n  params.observed_ranges = device_ranges;\n  params.observed_selectivities = device_selectivites;\n  params.error_accumulator_buffer = clCreateBuffer(\n      context->context, CL_MEM_READ_WRITE,\n      sizeof(kde_float_t) * feedback_records, NULL, &err);\n  Assert(err == CL_SUCCESS);\n  // Allocate a buffer to hold temporary gradient contributions. This buffer\n  // will keep D contributions per observation. We store all contributions\n  // consecutively (i.e. 111222333444). For optimal performance, we therefore\n  // have to make sure that the consecutive regions (strides) have a size that\n  // is aligned to the required machine alignment.\n  params.stride_size = sizeof(kde_float_t) * feedback_records;\n  if ((params.stride_size * 8) % context->required_mem_alignment) {\n    // The stride size is misaligned, add some padding.\n    params.stride_size *= 8;\n    params.stride_size =\n        (1 + params.stride_size / context->required_mem_alignment)\n        * context->required_mem_alignment;\n    params.stride_size /= 8;\n  }\n  params.gradient_accumulator_buffer = clCreateBuffer(\n      context->context, CL_MEM_READ_WRITE,\n      estimator->nr_of_dimensions * params.stride_size,\n      NULL, &err);\n  Assert(err == CL_SUCCESS);\n  params.gradient_buffer = clCreateBuffer(\n      context->context, CL_MEM_READ_WRITE,\n      estimator->nr_of_dimensions * sizeof(kde_float_t), NULL, &err);\n  Assert(err == CL_SUCCESS);\n  params.error_buffer = clCreateBuffer(\n      context->context, CL_MEM_READ_WRITE, sizeof(kde_float_t), NULL, &err);\n  Assert(err == CL_SUCCESS);\n  // Prepare the summation buffers.\n  params.summation_descriptors = palloc(\n      sizeof(ocl_aggregation_descriptor_t) * (1 + estimator->nr_of_dimensions));\n  // Prepare the partial aggregations for the error.\n  params.summation_descriptors[0] = prepareSumDescriptor(\n      params.error_accumulator_buffer, params.nr_of_observations,\n      params.error_buffer, 0);\n  // .. and for each dimension.\n  params.summation_buffers = palloc(\n      sizeof(cl_mem) * estimator->nr_of_dimensions);\n  for (i=0; i<estimator->nr_of_dimensions; ++i) {\n    cl_buffer_region region;\n    region.size = params.stride_size;\n    region.origin = i * params.stride_size;\n    params.summation_buffers[i] = clCreateSubBuffer(\n        params.gradient_accumulator_buffer, CL_MEM_READ_ONLY,\n        CL_BUFFER_CREATE_TYPE_REGION, &region, &err);\n    Assert(err == CL_SUCCESS);\n    params.summation_descriptors[i + 1] = prepareSumDescriptor(\n        params.summation_buffers[i], params.nr_of_observations,\n        params.gradient_buffer, i);\n  }\n\n  // Ok, we are prepared. Call the optimization routine.\n  gettimeofday(&opt_start, NULL);\n  evaluations = 0;\n  fprintf(stderr, \"> Starting numerical optimization of the model.\\n\");\n  // Prepare the bound constraints.\n  double* lower_bounds = palloc(sizeof(double) * estimator->nr_of_dimensions);\n  double* upper_bounds = palloc(sizeof(double) * estimator->nr_of_dimensions);\n  if(kde_bandwidth_representation == LOG_BW){\n    for (i=0; i<estimator->nr_of_dimensions; ++i) {\n      lower_bounds[i] = log(1e-20);    // We never want to be negative.\n    }\n    for (i=0; i<estimator->nr_of_dimensions; ++i) {\n      upper_bounds[i] = log(4) + bandwidth[i];    // We never want to be negative.\n    }\n  }\n  else {\n    for (i=0; i<estimator->nr_of_dimensions; ++i) {\n      lower_bounds[i] = 1e-20;    // We never want to be negative.\n    }\n    for (i=0; i<estimator->nr_of_dimensions; ++i) {\n      upper_bounds[i] = 4 * bandwidth[i];\n    }    \n  }  \n  double tmp;\n  int nl_err;\n  // We start with a global optimization step.\n  nlopt_opt global_optimizer = nlopt_create(\n      NLOPT_GD_MLSL, estimator->nr_of_dimensions);\n  Assert(global_optimizer);\n  nl_err = nlopt_set_lower_bounds(global_optimizer, lower_bounds);\n  Assert(nl_err > 0 );\n  nl_err = nlopt_set_upper_bounds(global_optimizer, upper_bounds);\n  Assert(nl_err > 0 );\n  nl_err = nlopt_set_maxeval(global_optimizer, 120);\n  Assert(nl_err > 0 );\n  nl_err = nlopt_set_min_objective(global_optimizer, computeGradient, &params);\n  Assert(nl_err > 0 );\n  // Register a local LBFGS instance for the global optimizer.\n  nlopt_opt global_local_optimizer = nlopt_create(\n      NLOPT_LD_LBFGS, estimator->nr_of_dimensions);\n  nl_err = nlopt_set_maxeval(global_local_optimizer, 40);\n  Assert(nl_err > 0 );\n  nl_err = nlopt_set_local_optimizer(global_optimizer, global_local_optimizer);\n  Assert(nl_err > 0 );\n  fprintf(stderr, \"> Running global pre-optimization: \");\n  nl_err = nlopt_optimize(global_optimizer, bandwidth, &tmp);\n  Assert(nl_err > 0 );\n  fprintf(stderr, \" done (%i, %f)\\n\", nl_err, tmp);\n  // Prepare the local refinement.\n  nlopt_opt local_optimizer = nlopt_create(\n      NLOPT_LD_LBFGS, estimator->nr_of_dimensions);\n  nlopt_set_lower_bounds(local_optimizer, lower_bounds);\n  nlopt_set_min_objective(local_optimizer, computeGradient, &params);\n  nlopt_set_ftol_abs(local_optimizer, 1e-20);\n  nlopt_set_maxeval(local_optimizer, 100);\n  fprintf(stderr, \"> Running local refinement: \");\n  err = nlopt_optimize(local_optimizer, bandwidth, &tmp);\n  fprintf(stderr, \" done (%i, %f)\\n\", err, tmp);\n  if (ocl_isDebug()) {\n    if (err < 0) {\n      fprintf(stderr, \"\\nOptimization failed: %i!\", err);\n    } else {\n      fprintf(stderr, \"\\nNew bandwidth:\");\n      for ( i = 0; i < estimator->nr_of_dimensions ; ++i)\n        fprintf(stderr, \" %e\", bandwidth[i]);\n      fprintf(stderr, \"\\n\");\n    }\n  }\n  nlopt_destroy(local_optimizer);\n  // Transfer the bandwidth to the device.\n  for (i=0; i<estimator->nr_of_dimensions; ++i) {\n    fbandwidth[i] = bandwidth[i];\n  }\n  err = clEnqueueWriteBuffer(\n      context->queue, estimator->bandwidth_buffer, CL_TRUE, 0,\n      sizeof(kde_float_t) * estimator->nr_of_dimensions,\n      fbandwidth, 0, NULL, NULL);\n  estimator->stats->optimization_transfer_to_device++;\n  Assert(err == CL_SUCCESS);\n  // Clean up.\n  pfree(fbandwidth);\n  lbfgs_free(bandwidth);\n  for (i=0; i<estimator->nr_of_dimensions; ++i) {\n    err = clReleaseMemObject(params.summation_buffers[i]);\n    Assert(err == CL_SUCCESS);\n    releaseAggregationDescriptor(params.summation_descriptors[i + 1]);\n  }\n  releaseAggregationDescriptor(params.summation_descriptors[0]);\n  pfree(params.summation_descriptors);\n  pfree(params.summation_buffers);\n  err |= clReleaseMemObject(params.error_buffer);\n  err |= clReleaseMemObject(params.gradient_buffer);\n  err |= clReleaseMemObject(params.error_accumulator_buffer);\n  err |= clReleaseMemObject(params.gradient_accumulator_buffer);\n  err |= clReleaseMemObject(device_ranges);\n  err |= clReleaseMemObject(device_selectivites);\n  Assert(err == CL_SUCCESS);\n}\n", "meta": {"hexsha": "219fcefe57f852bd7be448f7cb57b8dc2f37279c", "size": 30660, "ext": "c", "lang": "C", "max_stars_repo_path": "src/backend/optimizer/path/gpukde/ocl_model_maintenance.c", "max_stars_repo_name": "sfu-db/feedback-kde", "max_stars_repo_head_hexsha": "96e2a861dbb285b268d712e9076b89d0da104e01", "max_stars_repo_licenses": ["PostgreSQL"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-13T05:39:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-13T05:39:12.000Z", "max_issues_repo_path": "src/backend/optimizer/path/gpukde/ocl_model_maintenance.c", "max_issues_repo_name": "sfu-db/feedback-kde", "max_issues_repo_head_hexsha": "96e2a861dbb285b268d712e9076b89d0da104e01", "max_issues_repo_licenses": ["PostgreSQL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/backend/optimizer/path/gpukde/ocl_model_maintenance.c", "max_forks_repo_name": "sfu-db/feedback-kde", "max_forks_repo_head_hexsha": "96e2a861dbb285b268d712e9076b89d0da104e01", "max_forks_repo_licenses": ["PostgreSQL"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-11-17T16:06:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-18T12:42:07.000Z", "avg_line_length": 40.4485488127, "max_line_length": 91, "alphanum_fraction": 0.7051532942, "num_tokens": 7751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215779698935, "lm_q2_score": 0.024053553462858417, "lm_q1q2_score": 0.010254548868068996}}
{"text": "#pragma once\n\n#include <stdlib.h>\n#include <unistd.h>\n#include <string.h>\n#include \"core/common.h\"\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_spline.h>\n\nvoid batch_linterp_continuous_axis(float** yy, double* x, size_t size, size_t stride, size_t count);\n\nvoid linterp_continuous_axis(float** yy, double* x, size_t size, double dt);\n\nvoid gsl_interp_continuous_axis(float** yy, double* x, size_t size, double dx, gsl_interp_accel **acc, gsl_spline **spline);\n\nvoid batch_gsl_interp_continuous_axis(float** yy, double* x, size_t size, size_t stride, size_t count);\n", "meta": {"hexsha": "169e591f5f7f29627c73d1fc47a41ba9ef27898a", "size": 565, "ext": "h", "lang": "C", "max_stars_repo_path": "core/interp.h", "max_stars_repo_name": "godsic/semargl-ng", "max_stars_repo_head_hexsha": "221910cb2f4e981e0d512744a1561c04dad26184", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-10-25T16:24:43.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-22T18:00:50.000Z", "max_issues_repo_path": "core/interp.h", "max_issues_repo_name": "godsic/semargl-ng", "max_issues_repo_head_hexsha": "221910cb2f4e981e0d512744a1561c04dad26184", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2017-04-22T14:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-02T14:31:15.000Z", "max_forks_repo_path": "core/interp.h", "max_forks_repo_name": "godsic/semargl-ng", "max_forks_repo_head_hexsha": "221910cb2f4e981e0d512744a1561c04dad26184", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-09-05T15:12:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-05T02:31:52.000Z", "avg_line_length": 33.2352941176, "max_line_length": 124, "alphanum_fraction": 0.7610619469, "num_tokens": 149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3998116407397951, "lm_q2_score": 0.025565213459254256, "lm_q1q2_score": 0.010221269939007536}}
{"text": "/*\n * Copyright 2020 Makani Technologies LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#ifndef SIM_MODELS_SENSORS_LOADCELL_H_\n#define SIM_MODELS_SENSORS_LOADCELL_H_\n\n#include <gsl/gsl_vector.h>\n#include <stdint.h>\n#include <functional>\n#include <vector>\n\n#include \"common/c_math/vec2.h\"\n#include \"common/c_math/vec3.h\"\n#include \"common/macros.h\"\n#include \"control/system_types.h\"\n#include \"sim/faults/faults.h\"\n#include \"sim/models/sensors/sensor.h\"\n#include \"sim/models/signals/measurement.h\"\n#include \"sim/sim_messages.h\"\n\nnamespace sim {\n\nvoid TetherForceToLoadcells(const WingParams &wing_params,\n                            const LoadcellParams loadcell_params[],\n                            const Vec3 &tether_force_b,\n                            double loadcell_forces[]);\n\n}  // namespace sim\n\nclass Loadcell : public Sensor {\n  friend class LoadcellTest;\n\n public:\n  Loadcell(const LoadcellParams *loadcell_params,\n           const LoadcellSimParams &loadcell_sim_params,\n           const WingParams &wing_params, FaultSchedule *faults);\n  ~Loadcell() {}\n\n  void UpdateSensorOutputs(SimSensorMessage *sensor_message,\n                           TetherUpMessage * /*tether_up*/) const override;\n  void Publish() const override;\n\n  void set_Fb_tether(const Vec3 &val) { Fb_tether_.set_val(val); }\n  void set_tether_released(bool val) { tether_released_.set_val(val); }\n\n private:\n  void DiscreteStepHelper(double t) override;\n\n  double tensions(int32_t i) const { return tensions_[i].recorded(); }\n  const Vec3 &Fb_tether() const { return Fb_tether_.val(); }\n\n  // Loadcell parameters.\n  const LoadcellParams *loadcell_params_;\n  const LoadcellSimParams &loadcell_sim_params_;\n  const WingParams &wing_params_;\n\n  // Input states.\n  State<Vec3> Fb_tether_;\n  State<bool> tether_released_;\n\n  // Discrete state.\n  std::vector<DiscreteState<double>> actual_tensions_;\n\n  // Sub-models.\n  std::vector<Measurement<double>> tensions_;\n\n  DISALLOW_COPY_AND_ASSIGN(Loadcell);\n};\n\n#endif  // SIM_MODELS_SENSORS_LOADCELL_H_\n", "meta": {"hexsha": "f22e813f8fe05771531f4e1994232713cd1d2d65", "size": 2543, "ext": "h", "lang": "C", "max_stars_repo_path": "sim/models/sensors/loadcell.h", "max_stars_repo_name": "leozz37/makani", "max_stars_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1178.0, "max_stars_repo_stars_event_min_datetime": "2020-09-10T17:15:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:59:35.000Z", "max_issues_repo_path": "sim/models/sensors/loadcell.h", "max_issues_repo_name": "leozz37/makani", "max_issues_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-22T05:22:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-22T05:22:35.000Z", "max_forks_repo_path": "sim/models/sensors/loadcell.h", "max_forks_repo_name": "leozz37/makani", "max_forks_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 107.0, "max_forks_repo_forks_event_min_datetime": "2020-09-10T17:29:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T09:00:14.000Z", "avg_line_length": 30.2738095238, "max_line_length": 75, "alphanum_fraction": 0.7227683838, "num_tokens": 606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2689414213699951, "lm_q2_score": 0.037892427308664316, "lm_q1q2_score": 0.0101908432595514}}
{"text": "#include <gsl/gsl_multiset.h>\n#include <gsl/gsl_errno.h>\n#include <stdio.h>\n\nint mgsl_multiset_fwrite(const char *filename, const gsl_multiset *p)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_multiset_fwrite(fp, p) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_multiset_fread(const char *filename, gsl_multiset *p)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_multiset_fread(fp, p) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_multiset_fprintf(const char *filename, const gsl_multiset *p, const char *format)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_multiset_fprintf(fp, p, format) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_multiset_fscanf(const char *filename, gsl_multiset *p)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_multiset_fscanf(fp, p) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n", "meta": {"hexsha": "8f6f994ce3ecd821dfe503473c85fefbc70f0a5d", "size": 1104, "ext": "c", "lang": "C", "max_stars_repo_path": "src/multiset.c", "max_stars_repo_name": "frithnanth/raku-Math-Libgsl-Multiset", "max_stars_repo_head_hexsha": "44a0425fed0c8f4a7ce2548efd5b71375467772b", "max_stars_repo_licenses": ["Artistic-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/multiset.c", "max_issues_repo_name": "frithnanth/raku-Math-Libgsl-Multiset", "max_issues_repo_head_hexsha": "44a0425fed0c8f4a7ce2548efd5b71375467772b", "max_issues_repo_licenses": ["Artistic-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/multiset.c", "max_forks_repo_name": "frithnanth/raku-Math-Libgsl-Multiset", "max_forks_repo_head_hexsha": "44a0425fed0c8f4a7ce2548efd5b71375467772b", "max_forks_repo_licenses": ["Artistic-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6, "max_line_length": 90, "alphanum_fraction": 0.7128623188, "num_tokens": 329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3522017684487511, "lm_q2_score": 0.02887090360397222, "lm_q1q2_score": 0.010168383306032439}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n//\n// Copyright (c) 2015 Microsoft Corporation. All rights reserved.\n//\n// This code is licensed under the MIT License (MIT).\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef BITVEC_H\n#define BITVEC_H\n\n#include <gsl/gsl_assert> // for Expects\n#include <gsl/gsl_util>   // for narrow_cast, narrow\n\nusing gsl::narrow_cast;\n\n#include <cstddef>  // for ptrdiff_t, size_t, nullptr_t\n#include <iterator> // for reverse_iterator, distance, random_access_...\n#include <memory>\n\n#ifdef _MSC_VER\n#pragma warning(push)\n\n// turn off some warnings that are noisy about our Expects statements\n#pragma warning(disable : 4127) // conditional expression is constant\n#pragma warning(disable : 4702) // unreachable code\n\n// Turn MSVC /analyze rules that generate too much noise. TODO: fix in the tool.\n#pragma warning(                                                               \\\n    disable : 26495) // uninitalized member when constructor calls constructor\n#pragma warning(                                                               \\\n    disable : 26446) // parser bug does not allow attributes on some templates\n\n#endif // _MSC_VER\n\nnamespace gb {\n\ntemplate <std::ptrdiff_t Extent> class bitvec {\n  public:\n\t// constants and types\n\tusing element_type = unsafe_bit_t;\n\tusing value_type = std::remove_cv_t<element_type>;\n\tusing index_type = std::ptrdiff_t;\n\tusing pointer = shared_ptr_unsynchronized<element_type>;\n\n\tusing iterator = details::span_iterator<bitvec<Extent>, false>;\n\tusing const_iterator = details::span_iterator<bitvec<Extent>, true>;\n\tusing reverse_iterator = std::reverse_iterator<iterator>;\n\tusing const_reverse_iterator = std::reverse_iterator<const_iterator>;\n\n\tusing size_type = index_type;\n\n\t// [bitvec.cons], bitvec constructors, copy, assignment, and destructor\n\ttemplate <bool Dependent = false,\n\t          // \"Dependent\" is needed to make \"std::enable_if_t<Dependent ||\n\t          // Extent <= 0>\" SFINAE, since \"std::enable_if_t<Extent <= 0>\" is\n\t          // ill-formed when Extent is greater than 0.\n\t          class = std::enable_if_t<(Dependent || Extent <= 0)>>\n\tbitvec() noexcept : storage_(nullptr, details::extent_type<0>()) {};\n\n\tbitvec(pointer ptr, index_type count) : storage_(ptr, count) {}\n\n\tbitvec(const bitvec &other) noexcept = default;\n\n\ttemplate <std::ptrdiff_t OtherExtent,\n\t          class = std::enable_if_t<OtherExtent == Extent ||\n\t                                   Extent == dynamic_extent>>\n\tbitvec(const bitvec<OtherExtent> &other)\n\t    : storage_(other.data(),\n\t               details::extent_type<OtherExtent>(other.size())) {}\n\n\t~bitvec() noexcept = default;\n\tbitvec &operator=(const bitvec &other) noexcept = default;\n\tinline void operator=(bool value) {\n\t\twrite(*this, value);\n\t};\n\n\ttemplate <std::ptrdiff_t OtherExtent>\n\tvoid operator&=(const bitvec<OtherExtent> &other) noexcept {\n\t\tstatic_assert(Extent == OtherExtent || Extent == dynamic_extent || OtherExtent == dynamic_extent,\n\t\t\t\"Mismatching operand sizes\");\n\t\t_and(*this, *this, other);\n\t};\n\ttemplate <std::ptrdiff_t OtherExtent>\n\tvoid operator|=(const bitvec<OtherExtent> &other) noexcept {\n\t\tstatic_assert(Extent == OtherExtent || Extent == dynamic_extent || OtherExtent == dynamic_extent,\n\t\t\t\"Mismatching operand sizes\");\n\t\t_or(*this, *this, other);\n\t};\n\ttemplate <std::ptrdiff_t OtherExtent>\n\tvoid operator^=(const bitvec<OtherExtent> &other) noexcept {\n\t\tstatic_assert(Extent == OtherExtent || Extent == dynamic_extent || OtherExtent == dynamic_extent,\n\t\t\t\"Mismatching operand sizes\");\n\t\t_xor(*this, *this, other);\n\t};\n\n\t// [bitvec.sub], bitvec subviews\n\ttemplate <std::ptrdiff_t Count> bitvec<Count> first() const {\n\t\tExpects(Count >= 0 && Count <= size());\n\t\treturn {data(), Count};\n\t}\n\n\ttemplate <std::ptrdiff_t Count = 1>\n\tGSL_SUPPRESS(bounds .1) // NO-FORMAT: attribute\n\tbitvec<Count> last() const {\n\t\tExpects(Count >= 0 && size() - Count >= 0);\n\t\treturn {data_plus(size() - Count), Count};\n\t}\n\n\ttemplate <std::ptrdiff_t Offset, std::ptrdiff_t Count = dynamic_extent>\n\tGSL_SUPPRESS(bounds .1) // NO-FORMAT: attribute\n\tauto subspan() const ->\n\t    typename details::calculate_subspan_type<Extent, Offset, Count>::type {\n\t\tExpects((Offset >= 0 && size() - Offset >= 0) &&\n\t\t        (Count == dynamic_extent ||\n\t\t         (Count >= 0 && Offset + Count <= size())));\n\n\t\treturn {data_plus(Offset),\n\t\t        Count == dynamic_extent ? size() - Offset : Count};\n\t}\n\n\ttemplate <std::ptrdiff_t Count>\n\tbitvec<Count> subspan(std::ptrdiff_t offset) const {\n\t\tExpects((offset >= 0 && size() - offset >= 0) &&\n\t\t        (Count == dynamic_extent ||\n\t\t         (Count >= 0 && offset + Count <= size())));\n\n\t\treturn {data_plus(offset),\n\t\t        Count == dynamic_extent ? size() - offset : Count};\n\t}\n\n\tbitvec<dynamic_extent> first(index_type count) const {\n\t\tExpects(count >= 0 && count <= size());\n\t\treturn {data(), count};\n\t}\n\n\tbitvec<dynamic_extent> last(index_type count) const {\n\t\treturn make_subspan(size() - count, dynamic_extent,\n\t\t                    subspan_selector<Extent>{});\n\t}\n\n\tbitvec<dynamic_extent> subspan(index_type offset,\n\t                             index_type count = dynamic_extent) const {\n\t\treturn make_subspan(offset, count, subspan_selector<Extent>{});\n\t}\n\n\t// [bitvec.obs], bitvec observers\n\tindex_type size() const noexcept { return storage_.size(); }\n\tindex_type size_bytes() const noexcept {\n\t\treturn size() * narrow_cast<index_type>(sizeof(element_type));\n\t}\n\tbool empty() const noexcept { return size() == 0; }\n\n\tbitvec<1> operator[](index_type idx) const { return {data_plus(idx), 1}; }\n\n\tpointer at(index_type idx) const {\n\t\tExpects(CheckRange(idx, idx < storage_.size()));\n\t\treturn data()[idx];\n\t}\n\tpointer operator()(index_type idx) const { return this->operator[](idx); }\n\tpointer data() const noexcept { return storage_.data(); }\n\telement_type *cptr() const noexcept { return storage_.data().get(); }\n\n\t// [bitvec.iter], bitvec iterator support\n\titerator begin() const noexcept { return {this, 0}; }\n\titerator end() const noexcept { return {this, size()}; }\n\n\tconst_iterator cbegin() const noexcept { return {this, 0}; }\n\tconst_iterator cend() const noexcept { return {this, size()}; }\n\n\treverse_iterator rbegin() const noexcept { return reverse_iterator{end()}; }\n\treverse_iterator rend() const noexcept { return reverse_iterator{begin()}; }\n\n\tconst_reverse_iterator crbegin() const noexcept {\n\t\treturn const_reverse_iterator{cend()};\n\t}\n\tconst_reverse_iterator crend() const noexcept {\n\t\treturn const_reverse_iterator{cbegin()};\n\t}\n\n#ifdef _MSC_VER\n\t// Tell MSVC how to unwrap spans in range-based-for\n\tpointer _Unchecked_begin() const noexcept { return data(); }\n\tpointer _Unchecked_end() const noexcept {\n\t\tGSL_SUPPRESS(bounds .1) // NO-FORMAT: attribute\n\t\treturn data() + size();\n\t}\n#endif // _MSC_VER\n\n  private:\n\tstatic constexpr bool CheckRange(index_type idx, index_type size) {\n\t\t// Optimization:\n\t\t//\n\t\t// idx >= 0 && idx < size\n\t\t// =>\n\t\t// static_cast<size_t>(idx) < static_cast<size_t>(size)\n\t\t//\n\t\t// because size >=0 by bitvec construction, and negative idx will\n\t\t// wrap around to a value always greater than size when casted.\n\n\t\t// check if we have enough space to wrap around\n\t\tif (sizeof(index_type) <= sizeof(size_t)) {\n\t\t\treturn narrow_cast<size_t>(idx) < narrow_cast<size_t>(size);\n\t\t} else {\n\t\t\treturn idx >= 0 && idx < size;\n\t\t}\n\t}\n\n\t// Needed to remove unnecessary null check in subspans\n\tstruct KnownNotNull {\n\t\tpointer p;\n\t};\n\n\t// this implementation detail class lets us take advantage of the\n\t// empty base class optimization to pay for only storage of a single\n\t// pointer in the case of fixed-size spans\n\ttemplate <class ExtentType> class storage_type : public ExtentType {\n\t  public:\n\t\t// KnownNotNull parameter is needed to remove unnecessary null check\n\t\t// in subspans and constructors from arrays\n\t\ttemplate <class OtherExtentType>\n\t\tstorage_type(KnownNotNull data, OtherExtentType ext)\n\t\t    : ExtentType(ext), data_(data.p) {\n\t\t\tExpects(ExtentType::size() >= 0);\n\t\t}\n\n\t\ttemplate <class OtherExtentType>\n\t\tstorage_type(pointer data, OtherExtentType ext)\n\t\t    : ExtentType(ext), data_(data) {\n\t\t\tExpects(ExtentType::size() >= 0);\n\t\t\tExpects(data || ExtentType::size() == 0);\n\t\t}\n\n\t\tpointer data() const noexcept { return data_; }\n\n\t  private:\n\t\tpointer data_;\n\t};\n\n\tstorage_type<details::extent_type<Extent>> storage_;\n\n\t// The rest is needed to remove unnecessary null check\n\t// in subspans and constructors from arrays\n\tbitvec(KnownNotNull ptr, index_type count) : storage_(ptr, count) {}\n\n\ttemplate <std::ptrdiff_t CallerExtent> class subspan_selector {};\n\n\ttemplate <std::ptrdiff_t CallerExtent>\n\tbitvec<dynamic_extent> make_subspan(index_type offset, index_type count,\n\t                                  subspan_selector<CallerExtent>) const {\n\t\tconst bitvec<dynamic_extent> tmp(*this);\n\t\treturn tmp.subspan(offset, count);\n\t}\n\n\tGSL_SUPPRESS(bounds .1) // NO-FORMAT: attribute\n\tbitvec<dynamic_extent> make_subspan(index_type offset, index_type count,\n\t                                  subspan_selector<dynamic_extent>) const {\n\t\tExpects(offset >= 0 && size() - offset >= 0);\n\n\t\tpointer p = data_plus(offset);\n\n\t\tif (count == dynamic_extent) {\n\t\t\treturn {KnownNotNull{p}, size() - offset};\n\t\t}\n\n\t\tExpects(count >= 0 && size() - offset >= count);\n\t\treturn {KnownNotNull{p}, count};\n\t}\n\n  private:\n\t// Implements `data() + offset` taking care of ownership.\n\tpointer data_plus(index_type offset) const {\n\t\tExpects(offset >= 0 && size() - offset >= 0);\n\n\t\t// Uses same ref counter as data()\n\t\treturn pointer(data(), data().get() + offset);\n\t}\n};\n\n} // namespace gb\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif // _MSC_VER\n\n#endif // BITVEC_H\n", "meta": {"hexsha": "8539417fa595770a79a44fa089a415e482730e30", "size": 10234, "ext": "h", "lang": "C", "max_stars_repo_path": "include/bitvec.h", "max_stars_repo_name": "CapacitorSet/FHE-tools", "max_stars_repo_head_hexsha": "1271f2d65b3390c7156606b266b93c5d23ed398a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-08-28T04:50:57.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-26T22:06:36.000Z", "max_issues_repo_path": "include/bitvec.h", "max_issues_repo_name": "CapacitorSet/Glovebox", "max_issues_repo_head_hexsha": "1271f2d65b3390c7156606b266b93c5d23ed398a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/bitvec.h", "max_forks_repo_name": "CapacitorSet/Glovebox", "max_forks_repo_head_hexsha": "1271f2d65b3390c7156606b266b93c5d23ed398a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6915254237, "max_line_length": 99, "alphanum_fraction": 0.67178034, "num_tokens": 2487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33111975283019596, "lm_q2_score": 0.030675801710674105, "lm_q1q2_score": 0.010157363880306513}}
{"text": "#ifndef LOGSPLINEPDF\n#define LOGSPLINEPDF\n\n#include <gsl/gsl_rng.h>\n\n#include \"splinetable.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\nvoid logsplinepdf_n_sample(double *result, int results, int burnin,\n    double *coords, int dim, struct splinetable *table, int derivatives,\n    double (* proposal)(void*), double (* proposal_pdf)(double, double, void*),\n    void *proposal_info, const gsl_rng *rng);\n\nvoid splinepdf_n_sample(double *result, int results, int burnin,\n    double *coords, int dim, struct splinetable *table, int derivatives,\n    double (* proposal)(void*), double (* proposal_pdf)(double, double, void*),\n    void *proposal_info, const gsl_rng *rng);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n", "meta": {"hexsha": "bcef366ce4cb67f641b56fa54c69c10b597d39ad", "size": 704, "ext": "h", "lang": "C", "max_stars_repo_path": "photospline/public/photospline/splinepdf.h", "max_stars_repo_name": "hschwane/offline_production", "max_stars_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-24T22:00:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-24T22:00:01.000Z", "max_issues_repo_path": "photospline/public/photospline/splinepdf.h", "max_issues_repo_name": "hschwane/offline_production", "max_issues_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "photospline/public/photospline/splinepdf.h", "max_forks_repo_name": "hschwane/offline_production", "max_forks_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-07-17T09:20:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-30T16:44:18.000Z", "avg_line_length": 26.0740740741, "max_line_length": 79, "alphanum_fraction": 0.7272727273, "num_tokens": 183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.02297737036999376, "lm_q1q2_score": 0.010148484233584453}}
{"text": "\n#pragma once\n\n#include <gsl/gsl>\n#include <string>\n#include <memory>\n#include <vector>\n#include <string_view>\n\n#include \"aas/aas_math.h\"\n\nnamespace aas {\n\n\tstruct MeshVertex {\n\t\tstatic constexpr size_t sMaxBoneAttachments = 6;\n\t\tDX::XMFLOAT4 pos;\n\t\tDX::XMFLOAT4 normal;\n\t\tDX::XMFLOAT2 uv;\n\t\tuint16_t padding;\n\t\tuint16_t attachmentCount;\n\t\tuint16_t attachmentBone[sMaxBoneAttachments];\n\t\tfloat attachmentWeight[sMaxBoneAttachments];\n\n\t\tbool IsAttachedTo(int bone_idx) const {\n\t\t\tfor (int i = 0; i < attachmentCount; i++) {\n\t\t\t\tif (attachmentBone[i] == bone_idx) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t};\n\n\tstruct MeshFace {\n\t\tstatic constexpr size_t sVertexCount = 3;\n\t\tint16_t material_idx;\n\t\tint16_t vertices[sVertexCount];\n\t};\n\n\tstruct MeshBone {\n\t\tint16_t flags;\n\t\tint16_t parent_id;\n\t\tchar name[48];\n\t\tMatrix3x4 full_world_inverse;\n\t};\n\n\tclass Mesh {\n\tpublic:\n\t\tMesh(std::string filename, std::vector<uint8_t> data);\n\n\t\tconst std::vector<std::string_view> &GetMaterials() const {\n\t\t\treturn materials_;\n\t\t}\n\n\t\tstd::string_view GetMaterial(int materialIdx) const {\n\t\t\treturn materials_[materialIdx];\n\t\t}\n\n\t\tgsl::span<MeshBone> GetBones() const {\n\t\t\treturn bones_;\n\t\t}\n\n\t\tconst MeshBone &GetBone(int boneIdx) const {\n\t\t\tExpects(boneIdx >= 0 && boneIdx < bones_.size());\n\t\t\treturn bones_[boneIdx];\n\t\t}\n\n\t\tgsl::span<MeshVertex> GetVertices() const {\n\t\t\treturn vertices_;\n\t\t}\n\n\t\tconst MeshVertex &GetVertex(int vertexIdx) const {\n\t\t\treturn vertices_[vertexIdx];\n\t\t}\n\n\t\tconst size_t GetVertexCount() const {\n\t\t\treturn vertices_.size();\n\t\t}\n\n\t\tMeshVertex &GetVertex(int vertexIdx) {\n\t\t\treturn vertices_[vertexIdx];\n\t\t}\n\n\t\tgsl::span<MeshFace> GetFaces() const {\n\t\t\treturn faces_;\n\t\t}\n\n\t\tconst MeshFace &GetFace(int faceIdx) const {\n\t\t\treturn faces_[faceIdx];\n\t\t}\n\n\t\tvoid RenormalizeClothVertices(int clothBoneId);\n\n\t\tconst std::string &GetFilename() const {\n\t\t\treturn filename_;\n\t\t}\n\n\tprivate:\n\t\tstd::string filename_;\n\t\tstd::vector<uint8_t> data_;\n\t\tstd::vector<std::string_view> materials_;\n\t\t\n\t\t// These are views into the data buffer\n\t\tgsl::span<MeshBone> bones_;\n\t\tgsl::span<MeshVertex> vertices_;\n\t\tgsl::span<MeshFace> faces_;\n\t};\n\n\tstd::unique_ptr<Mesh> LoadMeshFile(std::string_view filename);\n\n}\n", "meta": {"hexsha": "d2bda3e13db6dfa40fddc10e954432aca8250570", "size": 2215, "ext": "h", "lang": "C", "max_stars_repo_path": "Infrastructure/src/aas/aas_mesh.h", "max_stars_repo_name": "edoipi/TemplePlus", "max_stars_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 69.0, "max_stars_repo_stars_event_min_datetime": "2015-05-05T14:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T06:13:04.000Z", "max_issues_repo_path": "Infrastructure/src/aas/aas_mesh.h", "max_issues_repo_name": "edoipi/TemplePlus", "max_issues_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 457.0, "max_issues_repo_issues_event_min_datetime": "2015-05-01T22:07:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T02:19:10.000Z", "max_forks_repo_path": "Infrastructure/src/aas/aas_mesh.h", "max_forks_repo_name": "edoipi/TemplePlus", "max_forks_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2016-02-04T21:19:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T23:14:51.000Z", "avg_line_length": 19.7767857143, "max_line_length": 63, "alphanum_fraction": 0.6970654628, "num_tokens": 622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681662740417, "lm_q2_score": 0.025565214665694145, "lm_q1q2_score": 0.010125567693043718}}
{"text": "#include <bindings.cmacros.h>\n#include <gsl/gsl_multiroots.h>\n\nBC_INLINE3(GSL_MULTIROOT_FN_EVAL,gsl_multiroot_function*,gsl_vector*,gsl_vector*,int)\nBC_INLINE3(GSL_MULTIROOT_FN_EVAL_F,gsl_multiroot_function_fdf*,gsl_vector*,gsl_vector*,int)\nBC_INLINE3(GSL_MULTIROOT_FN_EVAL_DF,gsl_multiroot_function_fdf*,gsl_vector*,gsl_matrix*,int)\nBC_INLINE4(GSL_MULTIROOT_FN_EVAL_F_DF,gsl_multiroot_function_fdf*,gsl_vector*,gsl_vector*,gsl_matrix*,int)\n", "meta": {"hexsha": "f2a08612c0841becab8aea27862a8d69b9abd963", "size": 441, "ext": "c", "lang": "C", "max_stars_repo_path": "bindings-gsl/src/Bindings/Gsl/MultidimensionalRootFinding.c", "max_stars_repo_name": "flip111/bindings-dsl", "max_stars_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2015-04-29T00:31:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T09:29:03.000Z", "max_issues_repo_path": "bindings-gsl/src/Bindings/Gsl/MultidimensionalRootFinding.c", "max_issues_repo_name": "flip111/bindings-dsl", "max_issues_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2015-01-04T06:32:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-07T09:49:12.000Z", "max_forks_repo_path": "bindings-gsl/src/Bindings/Gsl/MultidimensionalRootFinding.c", "max_forks_repo_name": "flip111/bindings-dsl", "max_forks_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2015-01-03T20:43:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-10T19:31:38.000Z", "avg_line_length": 55.125, "max_line_length": 106, "alphanum_fraction": 0.8707482993, "num_tokens": 131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.35577489351363034, "lm_q2_score": 0.02843603500033612, "lm_q1q2_score": 0.010116827324194447}}
{"text": "#pragma once\n\n#include <gsl.h>\n\n#include \"types/MT3_MathChar.h\"\n#include \"types/MT3_Radical.h\"\n#include \"types/MT3_Accent.h\"\n#include \"types/MT3_VCenter.h\"\n#include \"types/MT3_Overline.h\"\n#include \"types/MT3_Underline.h\"\n#include \"types/MT3_GenFraction.h\"\n#include \"types/MT3_LeftRight.h\"\n#include \"types/MT3_Script.h\"\n#include \"types/MT3_BigOp.h\"\n#include \"types/MT3_SubBox.h\"\n#include \"types/MT3_MList.h\"\n#include \"types/MT3_Kind.h\"\n#include \"types/MT3_MPen.h\"\n#include \"types/MT3_MSpace.h\"\n#include \"types/MT3_Style.h\"\n#include \"types/MT3_Choice.h\"\n", "meta": {"hexsha": "1e19dabf72f39b7274e11879c070a7aead30ad19", "size": 552, "ext": "h", "lang": "C", "max_stars_repo_path": "include/math/MathTypes.h", "max_stars_repo_name": "robin33n/formulae-cxx", "max_stars_repo_head_hexsha": "4b691e515b30508fb5e29c68426bad51d9629e72", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-25T04:00:03.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-25T04:00:03.000Z", "max_issues_repo_path": "include/math/MathTypes.h", "max_issues_repo_name": "robin33n/formulae-cxx", "max_issues_repo_head_hexsha": "4b691e515b30508fb5e29c68426bad51d9629e72", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-09-25T11:10:39.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-26T11:32:00.000Z", "max_forks_repo_path": "include/math/MathTypes.h", "max_forks_repo_name": "robin33n/formulae-cxx", "max_forks_repo_head_hexsha": "4b691e515b30508fb5e29c68426bad51d9629e72", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0909090909, "max_line_length": 34, "alphanum_fraction": 0.7644927536, "num_tokens": 186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3775406687981454, "lm_q2_score": 0.026759282021220337, "lm_q1q2_score": 0.010102717230849715}}
{"text": "#include <gsl/gsl_chebyshev.h>\nconst struct _GSLMethods \nchebyshev_f   = { (void_m_t) gsl_cheb_free,   \n\t\t  /* gsl_multimin_fminimizer_restart */  (void_m_t) NULL,\n\t\t  NULL, NULL};\n\nstatic int\nPyGSL_cheb_init(PyGSL_Solver *self, PyObject *args, PyObject *kw)\n{\n     ;\n}\n", "meta": {"hexsha": "cb44e2c6c1736fdd91cc1670fb984d566f1f0a26", "size": 270, "ext": "c", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/testing/src/solvers/chebyshev.c", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/testing/src/solvers/chebyshev.c", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/testing/src/solvers/chebyshev.c", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 22.5, "max_line_length": 65, "alphanum_fraction": 0.7074074074, "num_tokens": 90, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3007455914759599, "lm_q2_score": 0.03358950698030741, "lm_q1q2_score": 0.010101896144178436}}
{"text": "#ifndef UTILS_STRINGS_ONE_AWAY_H_INCLUDED\n#define UTILS_STRINGS_ONE_AWAY_H_INCLUDED\n\n#include <string> // std::string\n#include <gsl/gsl>\n\nbool isOneAway(const std::string &, const std::string &);\n\n#endif", "meta": {"hexsha": "66c45af4f7eca129391903c33945d2fa632f6aca", "size": 203, "ext": "h", "lang": "C", "max_stars_repo_path": "src/utils/strings/one-away.h", "max_stars_repo_name": "tiagoinacio/algorithms_cpp", "max_stars_repo_head_hexsha": "af08794fd21f67ee603c3538bb07a4cd9b5bc999", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils/strings/one-away.h", "max_issues_repo_name": "tiagoinacio/algorithms_cpp", "max_issues_repo_head_hexsha": "af08794fd21f67ee603c3538bb07a4cd9b5bc999", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils/strings/one-away.h", "max_forks_repo_name": "tiagoinacio/algorithms_cpp", "max_forks_repo_head_hexsha": "af08794fd21f67ee603c3538bb07a4cd9b5bc999", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5555555556, "max_line_length": 57, "alphanum_fraction": 0.7832512315, "num_tokens": 54, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22270013882530887, "lm_q2_score": 0.045352582489776146, "lm_q1q2_score": 0.01010002641655942}}
{"text": "#include <bindings.cmacros.h>\n#include <gsl/gsl_odeiv2.h>\n\nBC_INLINE4(GSL_ODEIV_FN_EVAL,gsl_odeiv2_system*,double,double*,double*,int)\nBC_INLINE5(GSL_ODEIV_JA_EVAL,gsl_odeiv2_system*,double,double*,double*,double*,int)\n", "meta": {"hexsha": "93e4e76f5c8b358a32ce3e86ebf9234f6e3e3539", "size": 219, "ext": "c", "lang": "C", "max_stars_repo_path": "bindings-gsl/src/Bindings/Gsl/OrdinaryDifferentialEquations.c", "max_stars_repo_name": "flip111/bindings-dsl", "max_stars_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2015-04-29T00:31:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T09:29:03.000Z", "max_issues_repo_path": "bindings-gsl/src/Bindings/Gsl/OrdinaryDifferentialEquations.c", "max_issues_repo_name": "flip111/bindings-dsl", "max_issues_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2015-01-04T06:32:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-07T09:49:12.000Z", "max_forks_repo_path": "bindings-gsl/src/Bindings/Gsl/OrdinaryDifferentialEquations.c", "max_forks_repo_name": "flip111/bindings-dsl", "max_forks_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2015-01-03T20:43:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-10T19:31:38.000Z", "avg_line_length": 36.5, "max_line_length": 83, "alphanum_fraction": 0.8219178082, "num_tokens": 72, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3140505578320071, "lm_q2_score": 0.0321007069484996, "lm_q1q2_score": 0.010081244923978085}}
{"text": "/* vector/gsl_vector_float.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_VECTOR_FLOAT_H__\n#define __GSL_VECTOR_FLOAT_H__\n\n#if !defined( GSL_FUN )\n#  if !defined( GSL_DLL )\n#    define GSL_FUN extern\n#  elif defined( BUILD_GSL_DLL )\n#    define GSL_FUN extern __declspec(dllexport)\n#  else\n#    define GSL_FUN extern __declspec(dllimport)\n#  endif\n#endif\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_inline.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_block_float.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size;\n  size_t stride;\n  float *data;\n  gsl_block_float *block;\n  int owner;\n} \ngsl_vector_float;\n\ntypedef struct\n{\n  gsl_vector_float vector;\n} _gsl_vector_float_view;\n\ntypedef _gsl_vector_float_view gsl_vector_float_view;\n\ntypedef struct\n{\n  gsl_vector_float vector;\n} _gsl_vector_float_const_view;\n\ntypedef const _gsl_vector_float_const_view gsl_vector_float_const_view;\n\n\n/* Allocation */\n\nGSL_FUN gsl_vector_float *gsl_vector_float_alloc (const size_t n);\nGSL_FUN gsl_vector_float *gsl_vector_float_calloc (const size_t n);\n\nGSL_FUN gsl_vector_float *gsl_vector_float_alloc_from_block (gsl_block_float * b,\n                                                     const size_t offset, \n                                                     const size_t n, \n                                                     const size_t stride);\n\nGSL_FUN gsl_vector_float *gsl_vector_float_alloc_from_vector (gsl_vector_float * v,\n                                                      const size_t offset, \n                                                      const size_t n, \n                                                      const size_t stride);\n\nGSL_FUN void gsl_vector_float_free (gsl_vector_float * v);\n\n/* Views */\n\nGSL_FUN _gsl_vector_float_view \ngsl_vector_float_view_array (float *v, size_t n);\n\nGSL_FUN _gsl_vector_float_view \ngsl_vector_float_view_array_with_stride (float *base,\n                                         size_t stride,\n                                         size_t n);\n\nGSL_FUN _gsl_vector_float_const_view \ngsl_vector_float_const_view_array (const float *v, size_t n);\n\nGSL_FUN _gsl_vector_float_const_view \ngsl_vector_float_const_view_array_with_stride (const float *base,\n                                               size_t stride,\n                                               size_t n);\n\nGSL_FUN _gsl_vector_float_view \ngsl_vector_float_subvector (gsl_vector_float *v, \n                            size_t i, \n                            size_t n);\n\nGSL_FUN _gsl_vector_float_view \ngsl_vector_float_subvector_with_stride (gsl_vector_float *v, \n                                        size_t i,\n                                        size_t stride,\n                                        size_t n);\n\nGSL_FUN _gsl_vector_float_const_view \ngsl_vector_float_const_subvector (const gsl_vector_float *v, \n                                  size_t i, \n                                  size_t n);\n\nGSL_FUN _gsl_vector_float_const_view \ngsl_vector_float_const_subvector_with_stride (const gsl_vector_float *v, \n                                              size_t i, \n                                              size_t stride,\n                                              size_t n);\n\n/* Operations */\n\nGSL_FUN void gsl_vector_float_set_zero (gsl_vector_float * v);\nGSL_FUN void gsl_vector_float_set_all (gsl_vector_float * v, float x);\nGSL_FUN int gsl_vector_float_set_basis (gsl_vector_float * v, size_t i);\n\nGSL_FUN int gsl_vector_float_fread (FILE * stream, gsl_vector_float * v);\nGSL_FUN int gsl_vector_float_fwrite (FILE * stream, const gsl_vector_float * v);\nGSL_FUN int gsl_vector_float_fscanf (FILE * stream, gsl_vector_float * v);\nGSL_FUN int gsl_vector_float_fprintf (FILE * stream, const gsl_vector_float * v,\n                              const char *format);\n\nGSL_FUN int gsl_vector_float_memcpy (gsl_vector_float * dest, const gsl_vector_float * src);\n\nGSL_FUN int gsl_vector_float_reverse (gsl_vector_float * v);\n\nGSL_FUN int gsl_vector_float_swap (gsl_vector_float * v, gsl_vector_float * w);\nGSL_FUN int gsl_vector_float_swap_elements (gsl_vector_float * v, const size_t i, const size_t j);\n\nGSL_FUN float gsl_vector_float_max (const gsl_vector_float * v);\nGSL_FUN float gsl_vector_float_min (const gsl_vector_float * v);\nGSL_FUN void gsl_vector_float_minmax (const gsl_vector_float * v, float * min_out, float * max_out);\n\nGSL_FUN size_t gsl_vector_float_max_index (const gsl_vector_float * v);\nGSL_FUN size_t gsl_vector_float_min_index (const gsl_vector_float * v);\nGSL_FUN void gsl_vector_float_minmax_index (const gsl_vector_float * v, size_t * imin, size_t * imax);\n\nGSL_FUN int gsl_vector_float_add (gsl_vector_float * a, const gsl_vector_float * b);\nGSL_FUN int gsl_vector_float_sub (gsl_vector_float * a, const gsl_vector_float * b);\nGSL_FUN int gsl_vector_float_mul (gsl_vector_float * a, const gsl_vector_float * b);\nGSL_FUN int gsl_vector_float_div (gsl_vector_float * a, const gsl_vector_float * b);\nGSL_FUN int gsl_vector_float_scale (gsl_vector_float * a, const float x);\nGSL_FUN int gsl_vector_float_add_constant (gsl_vector_float * a, const double x);\nGSL_FUN int gsl_vector_float_axpby (const float alpha, const gsl_vector_float * x, const float beta, gsl_vector_float * y);\nGSL_FUN float gsl_vector_float_sum (const gsl_vector_float * a);\n\nGSL_FUN int gsl_vector_float_equal (const gsl_vector_float * u, \n                            const gsl_vector_float * v);\n\nGSL_FUN int gsl_vector_float_isnull (const gsl_vector_float * v);\nGSL_FUN int gsl_vector_float_ispos (const gsl_vector_float * v);\nGSL_FUN int gsl_vector_float_isneg (const gsl_vector_float * v);\nGSL_FUN int gsl_vector_float_isnonneg (const gsl_vector_float * v);\n\nGSL_FUN INLINE_DECL float gsl_vector_float_get (const gsl_vector_float * v, const size_t i);\nGSL_FUN INLINE_DECL void gsl_vector_float_set (gsl_vector_float * v, const size_t i, float x);\nGSL_FUN INLINE_DECL float * gsl_vector_float_ptr (gsl_vector_float * v, const size_t i);\nGSL_FUN INLINE_DECL const float * gsl_vector_float_const_ptr (const gsl_vector_float * v, const size_t i);\n\n#ifdef HAVE_INLINE\n\nINLINE_FUN\nfloat\ngsl_vector_float_get (const gsl_vector_float * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= v->size))\n    {\n      GSL_ERROR_VAL (\"index out of range\", GSL_EINVAL, 0);\n    }\n#endif\n  return v->data[i * v->stride];\n}\n\nINLINE_FUN\nvoid\ngsl_vector_float_set (gsl_vector_float * v, const size_t i, float x)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= v->size))\n    {\n      GSL_ERROR_VOID (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  v->data[i * v->stride] = x;\n}\n\nINLINE_FUN\nfloat *\ngsl_vector_float_ptr (gsl_vector_float * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= v->size))\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return (float *) (v->data + i * v->stride);\n}\n\nINLINE_FUN\nconst float *\ngsl_vector_float_const_ptr (const gsl_vector_float * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= v->size))\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return (const float *) (v->data + i * v->stride);\n}\n#endif /* HAVE_INLINE */\n\n__END_DECLS\n\n#endif /* __GSL_VECTOR_FLOAT_H__ */\n\n\n", "meta": {"hexsha": "fda772b4db0f4b886a877fc5c6c67b296d796bcc", "size": 8273, "ext": "h", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_vector_float.h", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-28T08:20:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-28T08:20:20.000Z", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_vector_float.h", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_vector_float.h", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-14T12:45:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-14T12:45:35.000Z", "avg_line_length": 34.0452674897, "max_line_length": 123, "alphanum_fraction": 0.690680527, "num_tokens": 2003, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3593641588823761, "lm_q2_score": 0.02800752080881603, "lm_q1q2_score": 0.010064899157840819}}
{"text": "/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*\n**                                                                                  **\n** This file forms part of the Underworld geophysics modelling application.         **\n**                                                                                  **\n** For full license and copyright information, please refer to the LICENSE.md file  **\n** located at the project root, or contact the authors.                             **\n**                                                                                  **\n**~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/\n\n#include <mpi.h>\n#include <petsc.h>\n#include <petscvec.h>\n#include <petscsnes.h>\n#include <Python.h>\n#include <StGermain/libStGermain/src/StGermain.h>\n#include <StgDomain/libStgDomain/src/StgDomain.h>\n#include <StgFEM/libStgFEM/src/StgFEM.h>\n#include \"StgFEM/Discretisation/src/Discretisation.h\"\n\n#include \"types.h\"\n\n#include \"SystemLinearEquations.h\"\n#include \"SLE_Solver.h\"\n#include <stdio.h>\n#include <stdlib.h>\n#include <assert.h>\n#include <string.h>\n\n#include \"StiffnessMatrix.h\"\n#include \"SolutionVector.h\"\n#include \"ForceVector.h\"\n#include \"FiniteElementContext.h\"\n\n\n/* Textual name of this class */\nconst Type SystemLinearEquations_Type = \"SystemLinearEquations\";\n\n/** Constructor */\nSystemLinearEquations* SystemLinearEquations_New(\n   Name                    name,\n   FiniteElementContext*   context,\n   SLE_Solver*             solver,\n   void*                   nlSolver,\n   Bool                    isNonLinear,\n   double                  nonLinearTolerance,\n   Iteration_Index         nonLinearMinIterations,\n   Iteration_Index         nonLinearMaxIterations,\n   Bool                    killNonConvergent,\n   EntryPoint_Register*    entryPoint_Register,\n   MPI_Comm                comm )\n{\n   SystemLinearEquations* self = _SystemLinearEquations_DefaultNew( name );\n\n   self->isConstructed = True;\n   _SystemLinearEquations_Init(\n      self,\n      solver,\n      nlSolver,\n      context,\n      False, /* TODO: A hack put in place for setting the convergence stream to 'off' if the SLE class is created from within the code, not via an xml */\n      isNonLinear,\n      nonLinearTolerance,\n      nonLinearMaxIterations,\n      killNonConvergent,\n      nonLinearMinIterations,\n      \"\",\n      \"\",\n      entryPoint_Register,\n      comm );\n\n   return self;\n}\n\n/* Creation implementation / Virtual constructor */\nSystemLinearEquations* _SystemLinearEquations_New(  SYSTEMLINEAREQUATIONS_DEFARGS  )\n{\n   SystemLinearEquations* self;\n\n   /* Allocate memory */\n   assert( _sizeOfSelf >= sizeof(SystemLinearEquations) );\n   /* The following terms are parameters that have been passed into this function but are being set before being passed onto the parent */\n   /* This means that any values of these parameters that are passed into this function are not passed onto the parent function\n      and so should be set to ZERO in any children of this class. */\n   nameAllocationType = NON_GLOBAL;\n\n   self = (SystemLinearEquations*) _Stg_Component_New(  STG_COMPONENT_PASSARGS  );\n\n   /* Virtual info */\n   self->_LM_Setup = _LM_Setup;\n   self->_matrixSetup = _matrixSetup;\n   self->_vectorSetup = _vectorSetup;\n   self->_updateSolutionOntoNodes = _updateSolutionOntoNodes;\n   self->_mgSelectStiffMats = _mgSelectStiffMats;\n\n   self->_sleFormFunction = NULL;\n\n   /* this guy defaults to true so that we run within the execute phase as default */\n   self->runatExecutePhase = True;\n   \n   self->solver_callback = NULL;\n\n   return self;\n}\n\nvoid _SystemLinearEquations_Init(\n   void*                   sle,\n   SLE_Solver*             solver,\n   void*                   nlSolver,\n   FiniteElementContext*   context,\n   Bool                    makeConvergenceFile,\n   Bool                    isNonLinear,\n   double                  nonLinearTolerance,\n   Iteration_Index         nonLinearMaxIterations,\n   Bool                    killNonConvergent,\n   Iteration_Index         nonLinearMinIterations,\n   Name                    nonLinearSolutionType,\n   Name                    optionsPrefix,\n   EntryPoint_Register*    entryPoint_Register,\n   MPI_Comm                comm )\n{\n   SystemLinearEquations*    self = (SystemLinearEquations*)sle;\n   char*                     filename;\n   char*                     optionsName;\n\n   self->extensionManager = ExtensionManager_New_OfExistingObject( self->name, self );\n\n   self->debug = Stream_RegisterChild( StgFEM_SLE_SystemSetup_Debug, self->type );\n   self->info =  Journal_MyStream( Info_Type, self );\n    /* Note: currently we're sending self->info to the master proc only so there's not too much\n      identical timing info printed. May want to fine-tune later so that some info does get\n       printed on all procs. */\n   Stream_SetPrintingRank( self->info, 0 );\n\n   self->makeConvergenceFile = makeConvergenceFile;\n   if ( context && self->makeConvergenceFile ) {\n      self->convergenceStream = Journal_Register( InfoStream_Type, (Name)\"Convergence Info\"  );\n      Stg_asprintf( &filename, \"Convergence.dat\" );\n      Stream_RedirectFile_WithPrependedPath( self->convergenceStream, context->outputPath, filename );\n      Stream_SetPrintingRank( self->convergenceStream, 0 );\n      Memory_Free( filename );\n      Journal_Printf( self->convergenceStream , \"Timestep\\tIteration\\tResidual\\tTolerance\\n\" );\n   }\n\n   self->comm = comm;\n   self->solver = solver;\n   self->nlSolver = (SNES)nlSolver;\n   self->stiffnessMatrices = Stg_ObjectList_New();\n   self->forceVectors = Stg_ObjectList_New();\n   self->solutionVectors = Stg_ObjectList_New();\n   self->context = context;\n\n   /* Init NonLinear Stuff */\n   self->nonLinearSolutionType = nonLinearSolutionType; /* This will never got propogated through to _Initialise->SetToNonLinear if we keep it in the loop */\n   if ( isNonLinear )\n      SystemLinearEquations_SetToNonLinear( self, True );\n   self->nonLinearTolerance        = nonLinearTolerance;\n   self->nonLinearMaxIterations    = nonLinearMaxIterations;\n   self->killNonConvergent         = killNonConvergent;\n   self->nonLinearMinIterations    = nonLinearMinIterations;\n   self->curResidual               = 0.0;\n   self->curSolveTime              = 0.0;\n                                /* _  /0 */\n   optionsName = Memory_Alloc_Array_Unnamed( char, strlen(optionsPrefix) + 1 + 1 );\n   sprintf( optionsName, \"%s_\", optionsPrefix );\n   self->optionsPrefix = optionsName;\n\n   /* BEGIN LUKE'S FRICTIONAL BCS BIT */\n   Stg_asprintf( &self->nlSetupEPName, \"%s-nlSetupEP\", self->name );\n   self->nlSetupEP = EntryPoint_New( self->nlSetupEPName, EntryPoint_2VoidPtr_CastType );\n   Stg_asprintf( &self->nlEPName, \"%s-nlEP\", self->name );\n   self->nlEP = EntryPoint_New( self->nlEPName, EntryPoint_2VoidPtr_CastType );\n   Stg_asprintf( &self->nlEPName, \"%s-postNlEP\", self->name );\n   self->postNlEP = EntryPoint_New( self->postNlEPName, EntryPoint_2VoidPtr_CastType );\n   Stg_asprintf( &self->nlConvergedEPName, \"%s-nlConvergedEP\", self->name );\n   self->nlConvergedEP = EntryPoint_New( self->nlConvergedEPName, EntryPoint_2VoidPtr_CastType );\n   /* END LUKE'S FRICTIONAL BCS BIT */\n   self->nlFormJacobian = False;\n   self->nlCurIterate = PETSC_NULL;\n\n   /* Initialise MG stuff. */\n   self->mgEnabled = False;\n   self->mgUpdate = True;\n   self->nMGHandles = 0;\n   self->mgHandles = NULL;\n\n   /* Create Execute Entry Point */\n   Stg_asprintf( &self->executeEPName, \"%s-execute\", self->name );\n   self->executeEP = EntryPoint_New( self->executeEPName, EntryPoint_2VoidPtr_CastType );\n\n   /* Add default hooks to Execute E.P. */\n   EntryPoint_Append( self->executeEP, \"BC_Setup\", SystemLinearEquations_BC_Setup, self->type);\n   EntryPoint_Append( self->executeEP, \"LM_Setup\", SystemLinearEquations_LM_Setup, self->type);\n   EntryPoint_Append( self->executeEP, \"IntegrationSetup\", SystemLinearEquations_IntegrationSetup, self->type );\n   EntryPoint_Append( self->executeEP, \"ZeroAllVectors\", SystemLinearEquations_ZeroAllVectors, self->type);\n   EntryPoint_Append( self->executeEP, \"MatrixSetup\", SystemLinearEquations_MatrixSetup, self->type);\n   EntryPoint_Append( self->executeEP, \"VectorSetup\", SystemLinearEquations_VectorSetup, self->type);\n   EntryPoint_Append( self->executeEP, \"ExecuteSolver\", SystemLinearEquations_ExecuteSolver, self->type);\n   EntryPoint_Append( self->executeEP, \"UpdateSolutionOntoNodes\",SystemLinearEquations_UpdateSolutionOntoNodes,self->type);\n\n   /* Create Integration Setup EP */\n   Stg_asprintf( &self->integrationSetupEPName, \"%s-integrationSetup\", self->name );\n   self->integrationSetupEP = EntryPoint_New( self->integrationSetupEPName, EntryPoint_Class_VoidPtr_CastType );\n\n   if ( entryPoint_Register )\n      EntryPoint_Register_Add( entryPoint_Register, self->executeEP );\n   self->entryPoint_Register = entryPoint_Register;\n\n   /* Add SLE to Context */\n   if ( context )\n      FiniteElementContext_AddSLE( context, self );\n}\n\nvoid _SystemLinearEquations_Delete( void* sle ) {\n   SystemLinearEquations* self = (SystemLinearEquations*)sle;\n\n   Journal_DPrintf( self->debug, \"In %s\\n\", __func__ );\n   Stream_IndentBranch( StgFEM_Debug );\n\n        Stg_Class_Delete(self->integrationSetupEP);\n\n   /* delete parent */\n   _Stg_Component_Delete( self );\n\n   Stream_UnIndentBranch( StgFEM_Debug );\n}\n\nvoid _SystemLinearEquations_Print( void* sle, Stream* stream ) {\n   SystemLinearEquations*      self = (SystemLinearEquations*)sle;\n\n   /* General info */\n   Journal_Printf( stream, \"SystemLinearEquations (ptr): %p\\n\", self );\n   _Stg_Component_Print( self, stream );\n\n   /* Virtual info */\n   Stg_Class_Print( self->stiffnessMatrices, stream );\n   Stg_Class_Print( self->forceVectors, stream );\n   Stg_Class_Print( self->solutionVectors, stream );\n\n   /* other info */\n   Journal_PrintPointer( stream, self->extensionManager );\n   Journal_Printf( stream, \"\\tcomm: %u\\n\", self->comm );\n   Journal_Printf( stream, \"\\tsolver (ptr): %p\\n\", self->solver );\n   Stg_Class_Print( self->solver, stream );\n}\n\nvoid* _SystemLinearEquations_Copy( void* sle, void* dest, Bool deep, Name nameExt, PtrMap* ptrMap ) {\n   SystemLinearEquations*   self = (SystemLinearEquations*)sle;\n   SystemLinearEquations*   newSLE;\n   PtrMap* map = ptrMap;\n   Bool    ownMap = False;\n\n   if( !map ) {\n      map = PtrMap_New( 10 );\n      ownMap = True;\n   }\n\n   newSLE = _Stg_Component_Copy( sle, dest, deep, nameExt, map );\n\n   /* Virtual methods */\n   newSLE->_LM_Setup = self->_LM_Setup;\n   newSLE->_matrixSetup = self->_matrixSetup;\n   newSLE->_vectorSetup = self->_vectorSetup;\n   newSLE->_mgSelectStiffMats = self->_mgSelectStiffMats;\n\n   newSLE->debug = Stream_RegisterChild( StgFEM_SLE_SystemSetup_Debug, newSLE->type );\n   newSLE->comm = self->comm;\n\n   if( deep ) {\n      newSLE->solver = (SLE_Solver*)Stg_Class_Copy( self->solver, NULL, deep, nameExt, map );\n      newSLE->stiffnessMatrices = (StiffnessMatrixList*)Stg_Class_Copy( self->stiffnessMatrices, NULL, deep, nameExt, map );\n      newSLE->forceVectors = (ForceVectorList*)Stg_Class_Copy( self->forceVectors, NULL, deep, nameExt, map );\n      newSLE->solutionVectors = (SolutionVectorList*)Stg_Class_Copy( self->solutionVectors, NULL, deep, nameExt, map );\n      if( (newSLE->extensionManager = PtrMap_Find( map, self->extensionManager )) == NULL ) {\n         newSLE->extensionManager = Stg_Class_Copy( self->extensionManager, NULL, deep, nameExt, map );\n         PtrMap_Append( map, self->extensionManager, newSLE->extensionManager );\n      }\n   }\n   else {\n      newSLE->solver = self->solver;\n      newSLE->stiffnessMatrices = self->stiffnessMatrices;\n      newSLE->forceVectors = self->forceVectors;\n      newSLE->solutionVectors = self->solutionVectors;\n   }\n\n   if( ownMap ) {\n      Stg_Class_Delete( map );\n   }\n\n   return newSLE;\n}\n\nvoid* _SystemLinearEquations_DefaultNew( Name name ) {\n   /* Variables set in this function */\n   SizeT                                                            _sizeOfSelf = sizeof(SystemLinearEquations);\n   Type                                                                    type = SystemLinearEquations_Type;\n   Stg_Class_DeleteFunction*                                            _delete = _SystemLinearEquations_Delete;\n   Stg_Class_PrintFunction*                                              _print = _SystemLinearEquations_Print;\n   Stg_Class_CopyFunction*                                                _copy = _SystemLinearEquations_Copy;\n   Stg_Component_DefaultConstructorFunction*                _defaultConstructor = _SystemLinearEquations_DefaultNew;\n   Stg_Component_ConstructFunction*                                  _construct = _SystemLinearEquations_AssignFromXML;\n   Stg_Component_BuildFunction*                                          _build = _SystemLinearEquations_Build;\n   Stg_Component_InitialiseFunction*                                _initialise = _SystemLinearEquations_Initialise;\n   Stg_Component_ExecuteFunction*                                      _execute = _SystemLinearEquations_Execute;\n   Stg_Component_DestroyFunction*                                      _destroy = _SystemLinearEquations_Destroy;\n   SystemLinearEquations_LM_SetupFunction*                            _LM_Setup = _SystemLinearEquations_LM_Setup;\n   SystemLinearEquations_MatrixSetupFunction*                      _matrixSetup = _SystemLinearEquations_MatrixSetup;\n   SystemLinearEquations_VectorSetupFunction*                      _vectorSetup = _SystemLinearEquations_VectorSetup;\n   SystemLinearEquations_UpdateSolutionOntoNodesFunc*  _updateSolutionOntoNodes = _SystemLinearEquations_UpdateSolutionOntoNodes;\n   SystemLinearEquations_MG_SelectStiffMatsFunc*             _mgSelectStiffMats = _SystemLinearEquations_MG_SelectStiffMats;\n\n   /* Variables that are set to ZERO are variables that will be set either by the current _New function or another parent _New function further up the hierachy */\n   AllocationType  nameAllocationType = NON_GLOBAL /* default value NON_GLOBAL */;\n\n   return _SystemLinearEquations_New(  SYSTEMLINEAREQUATIONS_PASSARGS  );\n}\n\nvoid _SystemLinearEquations_AssignFromXML( void* sle, Stg_ComponentFactory* cf, void* data ){\n   SystemLinearEquations*  self = (SystemLinearEquations*)sle;\n   SLE_Solver*             solver = NULL;\n   void*                   entryPointRegister = NULL;\n   FiniteElementContext*   context = NULL;\n   double                  nonLinearTolerance;\n   Iteration_Index         nonLinearMaxIterations;\n   Bool                    isNonLinear;\n   Bool                    killNonConvergent;\n   Bool                    makeConvergenceFile;\n   Iteration_Index         nonLinearMinIterations;\n   Name                     nonLinearSolutionType;\n   SNES                    nlSolver = NULL;\n   Name                     optionsPrefix;\n\n   solver = Stg_ComponentFactory_ConstructByKey( cf, self->name, (Dictionary_Entry_Key)SLE_Solver_Type, SLE_Solver, False, data  ) ;\n\n   makeConvergenceFile      = Stg_ComponentFactory_GetBool( cf, self->name, (Dictionary_Entry_Key)\"makeConvergenceFile\", False  );\n   isNonLinear               = Stg_ComponentFactory_GetBool( cf, self->name, (Dictionary_Entry_Key)\"isNonLinear\", False  );\n   nonLinearTolerance      = Stg_ComponentFactory_GetDouble( cf, self->name, (Dictionary_Entry_Key)\"nonLinearTolerance\", 0.01  );\n   nonLinearMaxIterations   = Stg_ComponentFactory_GetUnsignedInt( cf, self->name, (Dictionary_Entry_Key)\"nonLinearMaxIterations\", 500  );\n   killNonConvergent         = Stg_ComponentFactory_GetBool( cf, self->name, (Dictionary_Entry_Key)\"killNonConvergent\", True  );\n   nonLinearMinIterations    = Stg_ComponentFactory_GetUnsignedInt( cf, self->name, (Dictionary_Entry_Key)\"nonLinearMinIterations\", 1  );\n   nonLinearSolutionType   = Stg_ComponentFactory_GetString( cf, self->name, (Dictionary_Entry_Key)\"nonLinearSolutionType\", \"default\"  );\n   optionsPrefix            = Stg_ComponentFactory_GetString( cf, self->name, (Dictionary_Entry_Key)\"optionsPrefix\", \"\"  );\n\n   /* Read some value for Picard */\n   self->picard_form_function_type = Stg_ComponentFactory_GetString( cf, self->name, (Dictionary_Entry_Key)\"picard_FormFunctionType\", \"PicardFormFunction_KSPResidual\"  );\n\n   self->alpha            = Stg_ComponentFactory_GetDouble( cf, self->name, (Dictionary_Entry_Key)\"picard_alpha\", 1.0  );\n   self->rtol            = Stg_ComponentFactory_GetDouble( cf, self->name, (Dictionary_Entry_Key)\"picard_rtol\", 1.0e-8  );\n   self->abstol         = Stg_ComponentFactory_GetDouble( cf, self->name, (Dictionary_Entry_Key)\"picard_atol\", 1.0e-50  );\n   self->stol            = Stg_ComponentFactory_GetDouble( cf, self->name, (Dictionary_Entry_Key)\"picard_stol\", 1.0e-8  );\n   self->picard_monitor   = Stg_ComponentFactory_GetBool( cf, self->name, (Dictionary_Entry_Key)\"picard_ActivateMonitor\", False  );\n\n   context = Stg_ComponentFactory_ConstructByKey( cf, self->name, (Dictionary_Entry_Key)\"Context\", FiniteElementContext, False, data );\n   if( !context  )\n      context = Stg_ComponentFactory_ConstructByName( cf, (Name)\"context\", FiniteElementContext, False, data );\n\n    if( context ){\n        entryPointRegister = context->entryPoint_Register;\n        assert( entryPointRegister );\n    }\n\n   if( isNonLinear  ) {\n      SNESCreate( MPI_COMM_WORLD, &nlSolver );\n      self->linearSolveInitGuess = Stg_ComponentFactory_GetBool( cf, self->name, (Dictionary_Entry_Key)\"linearSolveInitialGuess\", False  );\n   }\n\n   _SystemLinearEquations_Init(\n      self,\n      solver,\n      nlSolver,\n      context,\n      makeConvergenceFile,\n      isNonLinear,\n      nonLinearTolerance,\n      nonLinearMaxIterations,\n      killNonConvergent,\n      nonLinearMinIterations,\n      nonLinearSolutionType,\n      optionsPrefix,\n      entryPointRegister,\n      MPI_COMM_WORLD );\n\n   VecCreate( self->comm, &self->X );\n   VecCreate( self->comm, &self->F );\n   MatCreate( self->comm, &self->A );\n   MatCreate( self->comm, &self->J );\n}\n\n/* Build */\nvoid _SystemLinearEquations_Build( void* sle, void* _context ) {\n   SystemLinearEquations*      self = (SystemLinearEquations*)sle;\n   Index            index;\n\n   Journal_DPrintf( self->debug, \"In %s\\n\", __func__ );\n   Stream_IndentBranch( StgFEM_Debug );\n\n   /* build the matrices */\n   for ( index = 0; index < self->stiffnessMatrices->count; index++ ) {\n      /* Update rowSize and colSize if boundary conditions have been applied */\n      Stg_Component_Build( self->stiffnessMatrices->data[index], _context, False );\n   }\n\n   /* and the vectors */\n   for ( index = 0; index < self->forceVectors->count; index++ ) {\n      /* Build the force vectors - includes updateing matrix size based on Dofs */\n      Stg_Component_Build( self->forceVectors->data[index], _context, False );\n   }\n\n   /* and the solutions */\n   for ( index = 0; index < self->solutionVectors->count; index++ ) {\n      /* Build the force vectors - includes updateing matrix size based on Dofs */\n      Stg_Component_Build( self->solutionVectors->data[index], _context, False );\n   }\n\n   /* lastly, the solver - if required */\n   if( self->solver )\n      Stg_Component_Build( self->solver, self, True );\n\n   Stream_UnIndentBranch( StgFEM_Debug );\n}\n\n\nvoid _SystemLinearEquations_Initialise( void* sle, void* _context ) {\n   SystemLinearEquations*               self = (SystemLinearEquations*)sle;\n   Index                  index;\n\n   Journal_DPrintf( self->debug, \"In %s\\n\", __func__ );\n   Stream_IndentBranch( StgFEM_Debug );\n\n   /* initialise the matrices */\n   for ( index = 0; index < self->stiffnessMatrices->count; index++ ) {\n      /* Update rowSize and colSize if boundary conditions have been applied */\n      Stg_Component_Initialise( self->stiffnessMatrices->data[index], _context, False );\n   }\n\n   /* and the vectors */\n   for ( index = 0; index < self->forceVectors->count; index++ ) {\n      /* Initialise the force vectors - includes updateing matrix size based on Dofs */\n      Stg_Component_Initialise( self->forceVectors->data[index], _context, False );\n   }\n\n   /* and the solutions */\n   for ( index = 0; index < self->solutionVectors->count; index++ ) {\n      /* Initialise the force vectors - includes updateing matrix size based on Dofs */\n      Stg_Component_Initialise( self->solutionVectors->data[index], _context, False );\n   }\n\n   /* Check to see if any of the components need to make the SLE non-linear */\n   SystemLinearEquations_CheckIfNonLinear( self );\n\n   /* Setup Location Matrix */\n   SystemLinearEquations_LM_Setup( self, _context );\n\n   /* lastly, the solver, if required */\n   if( self->solver )\n      Stg_Component_Initialise( self->solver, self, False );\n   Stream_UnIndentBranch( StgFEM_Debug );\n}\n\n\nvoid _SystemLinearEquations_Execute( void* sle, void* _context ) {\n   SystemLinearEquations*   self = (SystemLinearEquations*)sle;\n\n   Journal_DPrintf( self->debug, \"In %s\\n\", __func__ );\n   Stream_IndentBranch( StgFEM_Debug );\n\n   if(self->runatExecutePhase) _SystemLinearEquations_RunEP( sle, _context );\n\n   Stream_UnIndentBranch( StgFEM_Debug );\n}\n\nvoid _SystemLinearEquations_RunEP( void* sle, void* _context ) {\n   SystemLinearEquations*   self = (SystemLinearEquations*)sle;\n\n   _EntryPoint_Run_2VoidPtr( self->executeEP, sle, _context );\n}\n\nvoid SystemLinearEquations_ExecuteSolver( void* sle, void* _context ) {\n   SystemLinearEquations*   self = (SystemLinearEquations*)sle;\n   double wallTime;\n   /* Actually run the solver to get the new values into the SolutionVectors */\n\n   Journal_Printf(self->info,\"Linear solver (%s) \\n\",self->executeEPName);\n\n   wallTime = MPI_Wtime();\n   if( self->solver )\n      Stg_Component_Execute( self->solver, self, True );\n    \n   self->curSolveTime = MPI_Wtime() - wallTime;\n   Journal_Printf(self->info,\"Linear solver (%s), solution time %6.6e (secs)\\n\",self->executeEPName, self->curSolveTime);\n\n}\n\nvoid _SystemLinearEquations_Destroy( void* sle, void* _context ) {\n   SystemLinearEquations*   self = (SystemLinearEquations*)sle;\n\n   /* BEGIN LUKE'S FRICTIONAL BCS BIT */\n   Memory_Free( self->nlSetupEPName );\n   Memory_Free( self->nlEPName );\n   Memory_Free( self->postNlEPName );\n   Memory_Free( self->nlConvergedEPName );\n   /* END LUKE'S FRICTIONAL BCS BIT */\n   Memory_Free( self->executeEPName );\n\n   Stg_Class_Delete( self->extensionManager );\n\n   Stg_Class_Delete( self->stiffnessMatrices );\n   Stg_Class_Delete( self->forceVectors );\n   Stg_Class_Delete( self->solutionVectors );\n\n   Memory_Free( self->optionsPrefix );\n\n   Stg_VecDestroy(&self->X );\n   Stg_VecDestroy(&self->F );\n   Stg_MatDestroy(&self->A );\n   Stg_MatDestroy(&self->J );\n\n   /* Free the the MG handles. */\n   FreeArray( self->mgHandles );\n}\n\nvoid SystemLinearEquations_BC_Setup( void* sle, void* _context ) {\n   SystemLinearEquations*            self = (SystemLinearEquations*)sle;\n   Index                  index;\n\n   Journal_DPrintf( self->debug, \"In %s\\n\", __func__ );\n   for ( index = 0; index < self->solutionVectors->count; index++ ) {\n      SolutionVector_ApplyBCsToVariables( self->solutionVectors->data[index], _context );\n   }\n}\n\nvoid SystemLinearEquations_LM_Setup( void* sle, void* _context ) {\n   SystemLinearEquations*               self = (SystemLinearEquations*)sle;\n\n   self->_LM_Setup( self, _context );\n}\n\nvoid SystemLinearEquations_IntegrationSetup( void* sle, void* _context ) {\n   SystemLinearEquations*               self = (SystemLinearEquations*)sle;\n\n   _EntryPoint_Run_Class_VoidPtr( self->integrationSetupEP, _context );\n}\n\nvoid _SystemLinearEquations_LM_Setup( void* sle, void* _context ) {\n   SystemLinearEquations*               self = (SystemLinearEquations*)sle;\n   Index                  index;\n\n   Journal_DPrintf( self->debug, \"In %s\\n\", __func__ );\n   Stream_IndentBranch( StgFEM_Debug );\n   /* For each feVariable of each stiffness matrix, build the LM  */\n   for ( index = 0; index < self->stiffnessMatrices->count; index++ ) {\n      StiffnessMatrix*            sm = (StiffnessMatrix*)self->stiffnessMatrices->data[index];\n\n      FeEquationNumber_BuildLocationMatrix( sm->rowEqNum );\n      FeEquationNumber_BuildLocationMatrix( sm->colEqNum );\n   }\n   Stream_UnIndentBranch( StgFEM_Debug );\n}\n\nvoid SystemLinearEquations_MatrixSetup( void* sle, void* _context ) {\n   SystemLinearEquations*               self = (SystemLinearEquations*)sle;\n\n   self->_matrixSetup( self, _context );\n}\n\nvoid _SystemLinearEquations_MatrixSetup( void* sle, void* _context ) {\n   SystemLinearEquations*            self = (SystemLinearEquations*)sle;\n   FiniteElementContext*            context = (FiniteElementContext*)_context;\n   Index                  index;\n\n   Journal_DPrintf( self->debug, \"In %s\\n\", __func__ );\n   Stream_IndentBranch( StgFEM_Debug );\n   for ( index = 0; index < self->stiffnessMatrices->count; index++ ) {\n      StiffnessMatrix_Assemble( self->stiffnessMatrices->data[index], self, context );\n   }\n   Stream_UnIndentBranch( StgFEM_Debug );\n}\n\n\nvoid SystemLinearEquations_VectorSetup( void* sle, void* _context ) {\n   SystemLinearEquations*            self = (SystemLinearEquations*)sle;\n\n   self->_vectorSetup( self, _context );\n}\n\nvoid _SystemLinearEquations_VectorSetup( void* sle, void* _context ) {\n   SystemLinearEquations*            self = (SystemLinearEquations*)sle;\n   Index                  index;\n\n   Journal_DPrintf( self->debug, \"In %s\\n\", __func__ );\n   Stream_IndentBranch( StgFEM_Debug );\n   for ( index = 0; index < self->forceVectors->count; index++ ) {\n      ForceVector_Assemble( self->forceVectors->data[index] );\n   }\n   Stream_UnIndentBranch( StgFEM_Debug );\n}\n\nIndex _SystemLinearEquations_AddStiffnessMatrix( void* sle, StiffnessMatrix* stiffnessMatrix ) {\n   SystemLinearEquations*               self = (SystemLinearEquations*)sle;\n\n   return SystemLinearEquations_AddStiffnessMatrix( self, stiffnessMatrix );\n}\n\nStiffnessMatrix* _SystemLinearEquations_GetStiffnessMatrix( void* sle, Name stiffnessMatrixName ) {\n   SystemLinearEquations*               self = (SystemLinearEquations*)sle;\n\n   return SystemLinearEquations_GetStiffnessMatrix( self, stiffnessMatrixName );\n}\n\nIndex _SystemLinearEquations_AddForceVector( void* sle, ForceVector* forceVector ) {\n   SystemLinearEquations*               self = (SystemLinearEquations*)sle;\n\n   return SystemLinearEquations_AddForceVector( self, forceVector );\n}\n\nForceVector* _SystemLinearEquations_GetForceVector( void* sle, Name forceVectorName ) {\n   SystemLinearEquations*               self = (SystemLinearEquations*)sle;\n\n   return SystemLinearEquations_GetForceVector( self, forceVectorName );\n}\n\nIndex _SystemLinearEquations_AddSolutionVector( void* sle, SolutionVector* solutionVector ) {\n   SystemLinearEquations*               self = (SystemLinearEquations*)sle;\n\n   return SystemLinearEquations_AddSolutionVector( self, solutionVector );\n}\n\nSolutionVector* _SystemLinearEquations_GetSolutionVector( void* sle, Name solutionVectorName ) {\n   SystemLinearEquations*               self = (SystemLinearEquations*)sle;\n\n   return SystemLinearEquations_GetSolutionVector( self, solutionVectorName );\n}\n\nvoid SystemLinearEquations_SetCallback( void* sle, PyObject* func) {\n  SystemLinearEquations *self = (SystemLinearEquations*) sle;\n  \n  // Assign the PyObject - 'None' or callable function to solver_callback\n  if (func == Py_None) \n    self->solver_callback = NULL;\n  else {\n    // check if it's callable\n    if(!PyCallable_Check(func)){\n      PyErr_SetString( PyExc_ValueError, \"The callback function can't be called, please check if it's valid\");\n    }\n    self->solver_callback = func;\n  }                \n}\n\nvoid SystemLinearEquations_UpdateSolutionOntoNodes( void* sle, void* _context ) {\n   SystemLinearEquations*   self = (SystemLinearEquations*)sle;\n\n   self->_updateSolutionOntoNodes( self, _context );\n   \n   // execute the python callback if found\n   if( self->solver_callback ) {\n     if(!PyObject_CallObject(self->solver_callback, NULL )) {\n       // check if callback execution failed\n       PyErr_SetString( PyExc_RuntimeError, \"Failed to execute the callback function, please check if it's valid\");\n     }\n   }\n}\n\nvoid _SystemLinearEquations_UpdateSolutionOntoNodes( void* sle, void* _context ) {\n   SystemLinearEquations*   self = (SystemLinearEquations*)sle;\n   SolutionVector_Index   solnVec_I;\n   SolutionVector*      currentSolnVec;\n\n   for ( solnVec_I=0; solnVec_I < self->solutionVectors->count; solnVec_I++ ) {\n      currentSolnVec = (SolutionVector*)self->solutionVectors->data[solnVec_I];\n      SolutionVector_UpdateSolutionOntoNodes( currentSolnVec );\n   }\n}\n\nvoid SystemLinearEquations_ZeroAllVectors( void* sle, void* _context ) {\n   SystemLinearEquations*      self = (SystemLinearEquations*)sle;\n   Index                       index;\n\n   for ( index = 0; index < self->forceVectors->count; index++ )\n      ForceVector_Zero( self->forceVectors->data[index] );\n}\n\n/* need to do this before the SLE specific function to set up the\npre conditioners is called (beginning of solve) */\nvoid SystemLinearEquations_NewtonInitialise( void* _context, void* data ) {\n   FiniteElementContext*   context = (FiniteElementContext*)_context;\n    assert(0); // the following will need to be fixed to get the sle from elsewhere\n   SystemLinearEquations*   sle = (SystemLinearEquations*)context->slEquations->data[0];\n   SNES                     snes;\n   SNES                     oldSnes = sle->nlSolver;\n\n   /* don't assume that a snes is being used for initial guess, check for this!!! */\n   if( oldSnes && context->timeStep == 1 && !sle->linearSolveInitGuess )\n      Stg_SNESDestroy(&oldSnes );\n\n   SNESCreate( sle->comm, &snes );\n\n   sle->nlSolver = snes;\n   sle->_setFFunc( &sle->F, context );\n\n   SNESSetJacobian( snes, sle->J, sle->P, sle->_buildJ, sle->buildJContext );\n   SNESSetFunction( snes, sle->F, sle->_buildF, sle->buildFContext );\n\n   /* configure the KSP */\n   sle->_configureNLSolverFunc( snes, context );\n}\n\n/* do this after the pre conditoiners have been set up in the problem specific SLE */\nvoid SystemLinearEquations_NewtonExecute( void* sle, void* _context ) {\n   SystemLinearEquations*   self            = (SystemLinearEquations*) sle;\n   SNES         snes      = self->nlSolver;\n\n   SNESSetOptionsPrefix( snes, self->optionsPrefix );\n   SNESSetFromOptions( snes );\n   SNESSolve( snes, PETSC_NULL, self->X );\n}\n\n/* do this at end of solve step */\nvoid SystemLinearEquations_NewtonFinalise( void* _context, void* data ) {\n   FiniteElementContext*   context      = (FiniteElementContext*)_context;\n    assert(0); // the following will need to be fixed to get the sle from elsewhere\n   SystemLinearEquations*   sle             = (SystemLinearEquations*)context->slEquations->data[0];\n   SNES         snes      = sle->nlSolver;\n\n   sle->_updateOldFields( &sle->X, context );\n\n   Stg_SNESDestroy(&snes );\n}\n\nvoid SystemLinearEquations_NewtonMFFDExecute( void* sle, void* _context ) {\n   SystemLinearEquations*   self            = (SystemLinearEquations*) sle;\n   Vec             F;\n\n   VecDuplicate( SystemLinearEquations_GetSolutionVectorAt( self, 0 )->vector, &F );\n\n   /* creates the nonlinear solver */\n   if( self->nlSolver != PETSC_NULL )\n      Stg_SNESDestroy(&self->nlSolver );\n   SNESCreate( self->comm, &self->nlSolver );\n   SNESSetFunction( self->nlSolver, F, self->_buildF, _context );\n\n   // set J (jacobian)\n\n   // set F (residual vector)\n\n   // call non linear solver func (SNES wrapper)\n}\n\nvoid SystemLinearEquations_NonLinearExecute( void* sle, void* _context ) {\n   SystemLinearEquations*   self            = (SystemLinearEquations*) sle;\n   Vec                     previousVector;\n   Vec                     currentVector;\n   double                  residual;\n   double                  tolerance       = self->nonLinearTolerance;\n   Iteration_Index         maxIterations   = self->nonLinearMaxIterations;\n   Bool                    converged;\n   Stream*                 errorStream     = Journal_Register( Error_Type, (Name)self->type  );\n   double                  wallTime;\n   Iteration_Index         minIterations   = self->nonLinearMinIterations;\n   SLE_Solver*             solver;\n\n   PetscScalar      currVecNorm, prevVecNorm;\n\n   Journal_Printf( self->info, \"In %s\\n\", __func__ );\n   Stream_IndentBranch( StgFEM_Debug );\n\n   wallTime = MPI_Wtime();\n\n   /* First Solve */\n   /* setting the nonlinear stuff */\n   //START OF NONLINEAR ITERATION!!!!!\n   /* first get current timestep */\n        solver = self->solver;\n//    assert(0); // THE FOLLOWING WILL NEED TO BE FIXED.. NOT SURE WHY THE SOLVER NEEDS THE CURRENT TIMESTEP\n//   solver->currenttimestep = self->context->timeStep;\n   /* if current timestep is not the same as previous timestep, then reset all variables back to zero and update previous timestep */\n//   if(solver->currenttimestep != solver->previoustimestep){\n      //update prev timestep\n      solver->previoustimestep = solver->currenttimestep;\n      solver->nonlinearitsinitialtime = 0;\n      solver->nonlinearitsendtime = 0;\n      solver->totalnonlinearitstime = 0;\n      solver->totalnumnonlinearits = 0;\n      solver->avgtimenonlinearits = 0;\n      solver->inneritsinitialtime = 0;\n      solver->outeritsinitialtime = 0;\n      solver->inneritsendtime = 0;\n      solver->outeritsendtime = 0;\n      solver->totalinneritstime = 0;\n      solver->totalouteritstime = 0;\n      solver->totalnuminnerits = 0;\n      solver->totalnumouterits = 0;\n      solver->avgnuminnerits = 0;\n      solver->avgnumouterits = 0;\n      solver->avgtimeinnerits = 0;\n      solver->avgtimeouterits = 0;\n//   }\n\n   self->nonLinearIteration_I = 0;\n   Journal_Printf(self->info,\"\\nNon linear solver - iteration %d\\n\", self->nonLinearIteration_I);\n\n        /* More of Luke's stuff. I need an entry point for a non-linear setup operation. */\n        _EntryPoint_Run_2VoidPtr( self->nlSetupEP, sle, _context );\n\n   /*Don't know if we should include this but the timing of the outer and inner iterations starts here so it makes sense to count this one? */\n   solver->nonlinearitsinitialtime = MPI_Wtime();\n\n   self->linearExecute( self, _context );\n   self->hasExecuted = True;\n\n   solver->nonlinearitsendtime = MPI_Wtime();\n   solver->totalnonlinearitstime = solver->totalnonlinearitstime + (-solver->nonlinearitsinitialtime + solver->nonlinearitsendtime);\n   /* reset initial time and end time for inner its back to 0 - probs don't need to do this but just in case */\n   solver->nonlinearitsinitialtime = 0;\n   solver->nonlinearitsendtime = 0;\n   /*\n   ** Include an entry point to do some kind of post-non-linear-iteration operation. */\n   _EntryPoint_Run_2VoidPtr( self->postNlEP, sle, _context );\n\n   /* TODO - Give option which solution vector to test */\n   currentVector   = SystemLinearEquations_GetSolutionVectorAt( self, 0 )->vector;\n   VecDuplicate( currentVector, &previousVector );\n\n   for ( self->nonLinearIteration_I = 1 ; self->nonLinearIteration_I < maxIterations ; self->nonLinearIteration_I++ ) {\n      /* get initial wall time for nonlinear loop */\n      solver->nonlinearitsinitialtime = MPI_Wtime();\n\n      /*\n      ** BEGIN LUKE'S FRICTIONAL BCS BIT\n      **\n      ** Adding an interface for allowing other components to add some form of non-linearity to the system.\n      ** This is with a focus on frictional BCs, where we want to examine the stress field and modify\n      ** traction BCs to enforce friction rules. - Luke 18/07/2007\n      */\n\n      _EntryPoint_Run_2VoidPtr( self->nlEP, sle, _context );\n\n      /*\n      ** END LUKE'S FRICTIONAL BCS BIT\n      */\n\n\n      //Vector_CopyEntries( currentVector, previousVector );\n      VecCopy( currentVector, previousVector );\n\n      Journal_Printf(self->info,\"Non linear solver - iteration %d\\n\", self->nonLinearIteration_I);\n\n      self->linearExecute( self, _context );\n//      PetscPrintf( PETSC_COMM_WORLD, \"|Xn+1| = %12.12e \\n\", Vector_L2Norm(SystemLinearEquations_GetSolutionVectorAt(self,1)->vector) );\n\n      /* Calculate Residual */\n      VecAXPY( previousVector, -1.0, currentVector );\n      VecNorm( previousVector, NORM_2, &prevVecNorm );\n      VecNorm( currentVector, NORM_2, &currVecNorm );\n      residual = ((double)prevVecNorm) / ((double)currVecNorm);\n\n      self->curResidual = residual;\n\n                /*\n                ** Include an entry point to do some kind of post-non-linear-iteration operation. */\n      _EntryPoint_Run_2VoidPtr( self->postNlEP, sle, _context );\n\n      Journal_Printf( self->info, \"In func %s: Iteration %u of %u - Residual %.5g - Tolerance = %.5g\\n\",\n            __func__, self->nonLinearIteration_I, maxIterations, residual, tolerance );\n      if ( self->context && self->makeConvergenceFile ) {\n         Journal_Printf( self->convergenceStream, \"%d\\t\\t%d\\t\\t%.5g\\t\\t%.5g\\n\",\n                      self->context->timeStep, self->nonLinearIteration_I, residual, tolerance );\n      }\n\n      /* Check if residual is below tolerance */\n      converged = (residual < tolerance);\n\n      Journal_Printf(self->info,\"Non linear solver - Residual %.8e; Tolerance %.4e%s%s - %6.6e (secs)\\n\\n\", residual, tolerance,\n         (converged) ? \" - Converged\" : \" - Not converged\",\n         (self->nonLinearIteration_I < maxIterations) ? \"\" : \" - Reached iteration limit\",\n         MPI_Wtime() - wallTime );\n         //END OF NONLINEAR ITERATION LOOP!!!\n\n         /* add the outer loop iterations to the total outer iterations */\n         solver->totalnumnonlinearits += 1;\n         /*get wall time for end of outer loop*/\n         solver->nonlinearitsendtime = MPI_Wtime();\n         /* add time to total time inner its: */\n         solver->totalnonlinearitstime = solver->totalnonlinearitstime + (-solver->nonlinearitsinitialtime + solver->nonlinearitsendtime);\n         //printf(\"totalnumnonlinearits before converging is %d totalnonlinearitstime is %g, totalouteritstime is %g and totalinneritstime is %g\\n\",solver->totalnumnonlinearits,solver->totalnonlinearitstime,solver->totalouteritstime,solver->totalinneritstime);\n\n         /* reset initial time and end time for inner its back to 0 - probs don't need to do this but just in case */\n         solver->nonlinearitsinitialtime = 0;\n         solver->nonlinearitsendtime = 0;\n      if ( (converged) && (self->nonLinearIteration_I>=minIterations) ) {\n         int result, ierr;\n\n         /* Adding in another entry point so we can insert out own custom\n            convergeance checks. For example, with frictional boundary\n            conditions we need to ensure envery node was gone from the\n            original searching state to a fixed slipping or sticking state. */\n         _EntryPoint_Run_2VoidPtr( self->nlConvergedEP, _context, &converged );\n         ierr = MPI_Allreduce( &converged, &result, 1, MPI_INT, MPI_LOR, MPI_COMM_WORLD );\n         if( result )\n            break;\n      }\n   }\n\n   /* Print Info */\n   if ( converged ) {\n      Journal_Printf( self->info, \"In func %s: Converged after %u iterations.\\n\",\n            __func__, self->nonLinearIteration_I );\n   }\n   else {\n      Journal_Printf( errorStream, \"In func %s: Failed to converge after %u iterations.\\n\",\n            __func__, self->nonLinearIteration_I);\n      if ( self->killNonConvergent ) {\n         abort();\n      }\n   }\n\n   Stream_UnIndentBranch( StgFEM_Debug );\n\n   Stg_VecDestroy(&previousVector );\n\n   /*Set all the printout variables */\n        if( solver->totalnumnonlinearits ) {\n           solver->avgtimenonlinearits = (solver->totalnonlinearitstime - solver->totalouteritstime)/solver->totalnumnonlinearits;\n           solver->avgnumouterits = solver->totalnumouterits/solver->totalnumnonlinearits;\n        }\n        if( solver->totalnumouterits ) {\n           solver->avgnuminnerits = solver->totalnuminnerits/solver->totalnumouterits;\n           solver->avgtimeouterits = (solver->totalouteritstime - solver->totalinneritstime)/solver->totalnumouterits;\n        }\n        if( solver->totalnuminnerits )\n           solver->avgtimeinnerits = solver->totalinneritstime/solver->totalnuminnerits;\n   //printf(\"totalnumnonlinearits = %d, avgnumouterits %d, avgnuminnerits %d\\n\",solver->totalnumnonlinearits, solver->avgnumouterits, solver->avgnuminnerits);\n\n}\n\nvoid SystemLinearEquations_AddNonLinearSetupEP( void* sle, const char* name, EntryPoint_2VoidPtr_Cast func ) {\n   SystemLinearEquations* self = (SystemLinearEquations*)sle;\n\n   SystemLinearEquations_SetToNonLinear( self, True );\n   EntryPoint_Append( self->nlSetupEP, (char*)name, func, self->type );\n}\n\nvoid SystemLinearEquations_AddPostNonLinearEP( void* sle, const char* name, EntryPoint_2VoidPtr_Cast func ) {\n   SystemLinearEquations* self = (SystemLinearEquations*)sle;\n\n   EntryPoint_Append( self->postNlEP, (char*)name, func, self->type );\n}\n\nvoid SystemLinearEquations_AddNonLinearConvergedEP( void* sle,\n                      const char* name,\n                      EntryPoint_2VoidPtr_Cast func )\n{\n   SystemLinearEquations* self = (SystemLinearEquations*)sle;\n\n   SystemLinearEquations_SetToNonLinear( self, True );\n   EntryPoint_Append( self->nlConvergedEP, (char*)name, func, self->type );\n}\n\n/*\nComputes\n  F1 := A(x) x -b  = -r,\n  where r = b - A(x) x\n*/\n//void SystemLinearEquations_SNESPicardFormalResidual( void *someSLE, Vector *stg_X, Vector *stg_F, void *_context )\nvoid SystemLinearEquations_SNESPicardFormalResidual( void *someSLE, Vec X, Vec F, void *_context )\n{\n   SystemLinearEquations *sle = (SystemLinearEquations*)someSLE;\n       SLE_Solver            *solver = (SLE_Solver*)sle->solver;\n   abort();\n\n   solver->_formResidual( (void*)sle,  (void*)solver, F );\n}\n\n/*\nComputes\n  F2 := x - A(x)^{-1} b\n*/\n#if 0\nvoid SystemLinearEquations_SNESPicardKSPResidual( void *someSLE, Vector *stg_X, Vector *stg_F, void *_context )\n{\n        SystemLinearEquations *sle = (SystemLinearEquations*)someSLE;\n        SLE_Solver            *solver = (SLE_Solver*)sle->solver;\n        Vec                   F,X,Xcopy;\n        PetscReal norm;\n\n        F = StgVectorGetPetscVec( stg_F );\n        X = StgVectorGetPetscVec( stg_X );\n\n        VecDuplicate( X, &Xcopy );\n        VecCopy( X, Xcopy );\n\n        VecCopy( X, F );                        /* F <- X */\n//      VecNorm( X, NORM_2, &norm );\n//      PetscPrintf(PETSC_COMM_WORLD,\"  |X|_pre = %5.5e \\n\", norm );\n        sle->linearExecute( sle, _context );    /* X = A^{-1} b */\n        X = StgVectorGetPetscVec( stg_X );\n//      VecNorm( X, NORM_2, &norm );\n//      PetscPrintf(PETSC_COMM_WORLD,\"  |X|_post = %5.5e \\n\", norm );\n\n        VecAXPY( F, -1.0, X );                  /* F <- X - F */\n//      VecNorm( F, NORM_2, &norm );\n//      PetscPrintf(PETSC_COMM_WORLD,\"  |F|_post = %5.5e \\n\", norm );\n\n        VecCopy( Xcopy, X );\n        Stg_VecDestroy(&Xcopy );\n}\n#endif\n\n/*\nstg_X must not get modified by this function !!\n*/\nvoid SystemLinearEquations_SNESPicardKSPResidual( void *someSLE, Vec X, Vec F, void *_context )\n{\n        SystemLinearEquations *sle = (SystemLinearEquations*)someSLE;\n        SLE_Solver            *solver = (SLE_Solver*)sle->solver;\n   Vec         Xstar;\n   PetscReal norm,norms;\n\n   solver->_getSolution( sle, solver, &Xstar );\n\n   /* Map most current solution into stg object, vec->mesh  */\n   VecCopy( X, Xstar );  /* X* <- X */\n   /* Map onto nodes */\n   SystemLinearEquations_UpdateSolutionOntoNodes( someSLE, _context );\n\n   VecNorm( X, NORM_2, &norm );\n   VecNorm( Xstar, NORM_2, &norms );\n//   PetscPrintf(PETSC_COMM_WORLD,\"  |X| = %12.12e : |x*| = %12.12e <pre>\\n\", norm, norms );\n\n   sle->linearExecute( sle, _context );    /* X* = A^{-1} b */\n\n   VecNorm( X, NORM_2, &norm );\n   VecNorm( Xstar, NORM_2, &norms );\n//   PetscPrintf(PETSC_COMM_WORLD,\"  |X| = %12.12e : |x*| = %12.12e <post> \\n\", norm, norms );\n\n   VecWAXPY( F, -1.0, Xstar, X ); /* F = -X* + X  */\n}\n\nPetscErrorCode SLEComputeFunction( void *someSLE, Vec X, Vec F, void *_context )\n{\n        SystemLinearEquations *sle = (SystemLinearEquations*)someSLE;\n\n   if (sle->_sleFormFunction!=NULL) {\n      sle->_sleFormFunction( sle, X, F, _context );\n   }\n   else {\n      Stg_SETERRQ( PETSC_ERR_SUP, \"SLEComputeFunction in not valid\" );\n   }\n}\n\nvoid SLE_SNESMonitor( void *sle, PetscInt iter, PetscReal fnorm )\n{\n  PetscPrintf( PETSC_COMM_WORLD, \"  %.4d SLE_NS Function norm %12.12e    --------------------------------------------------------------------------------\\n\", iter, fnorm );\n}\n\nvoid SLE_SNESMonitor2( void *sle, PetscInt iter, PetscReal fnorm0, PetscReal fnorm, PetscReal dX, PetscReal X1 )\n{\n  if(iter==0) {\n    PetscPrintf( PETSC_COMM_WORLD, \"  SLE_NS  it       |F|              |F|/|F0|          |X1-X0|        |X1-X0|/|X1| \\n\" );\n  }\n  PetscPrintf( PETSC_COMM_WORLD,   \"  SLE_NS  %1.4d     %2.4e      %2.4e       %2.4e     %2.4e \\n\", iter, fnorm, fnorm/fnorm0, dX, dX/X1 );\n}\n\nvoid _monitor_progress( PetscReal initial, PetscReal target, PetscReal current, PetscReal *p )\n{\n  PetscReal p0;\n\n  p0 = log10(initial) - log10(target);\n  *p = 100.0 * ( 1.0 - (log10(current)-log10(target)) / p0 );\n}\n\nvoid SLE_SNESMonitorProgress( void *sle,\n  PetscInt iter,\n  PetscReal fnorm0, PetscReal fnorm, PetscReal dX, PetscReal X1,\n  PetscReal fatol, PetscReal frtol, PetscReal stol )\n{\n  PetscReal f_abs_s, f_abs_e, v1, p1;\n  PetscReal f_rel_s, f_rel_e, v2, p2;\n  PetscReal x_del_s, x_del_e, v3, p3;\n\n  if(iter==0) {\n    PetscPrintf( PETSC_COMM_WORLD, \"  SLE_NS  it       |F|                 |F|/|F0|             |X1-X0|/|X1| \\n\" );\n  }\n\n  f_abs_s = fnorm0;\n  f_abs_e = fatol;\n  v1 = fnorm;\n  _monitor_progress( f_abs_s, f_abs_e, v1, &p1 );\n\n  f_rel_s = fnorm0;\n  f_rel_e = fnorm0 * frtol;\n  v2 = fnorm;\n  _monitor_progress( f_rel_s, f_rel_e, v2, &p2 );\n\n  x_del_s = 1.0;\n  x_del_e = stol;\n  v3 = dX/X1;\n  _monitor_progress( x_del_s, x_del_e, v3, &p3 );\n\n  PetscPrintf( PETSC_COMM_WORLD,   \"  SLE_NS  %1.4d     %2.4e [%2.0f%%]     %2.4e [%2.0f%%]      %2.4e [%2.0f%%] \\n\", iter, fnorm,p1, fnorm/fnorm0,p2,  dX/X1,p3 );\n}\n\n\nvoid SLE_SNESConverged(\n   PetscReal snes_abstol, PetscReal snes_rtol, PetscReal snes_ttol, PetscReal snes_stol,\n   PetscInt it,PetscReal xnorm,PetscReal pnorm,PetscReal fnorm,SNESConvergedReason *reason )\n{\n  /* PetscErrorCode ierr; */\n\n  *reason = SNES_CONVERGED_ITERATING;\n\n  if (!it) {\n    /* set parameter for default relative tolerance convergence test */\n    snes_ttol = fnorm*snes_rtol;\n  }\n  if (fnorm != fnorm) {\n//    ierr = PetscInfo(snes,\"Failed to converged, function norm is NaN\\n\");CHKERRQ(ierr);\n    *reason = SNES_DIVERGED_FNORM_NAN;\n  } else if (fnorm < snes_abstol) {\n//    ierr = PetscInfo2(snes,\"Converged due to function norm %G < %G\\n\",fnorm,snes_abstol);CHKERRQ(ierr);\n    *reason = SNES_CONVERGED_FNORM_ABS;\n  }\n//  } else if (snes->nfuncs >= snes->max_funcs) {\n//    ierr = PetscInfo2(snes,\"Exceeded maximum number of function evaluations: %D > %D\\n\",snes->nfuncs,snes->max_funcs);CHKERRQ(ierr);\n//    *reason = SNES_DIVERGED_FUNCTION_COUNT;\n//  }\n\n  if (it && !*reason) {\n    if (fnorm <= snes_ttol) {\n//      ierr = PetscInfo2(snes,\"Converged due to function norm %G < %G (relative tolerance)\\n\",fnorm,snes_ttol);CHKERRQ(ierr);\n      *reason = SNES_CONVERGED_FNORM_RELATIVE;\n    } else if (pnorm < snes_stol*xnorm) {\n//      ierr = PetscInfo3(snes,\"Converged due to small update length: %G < %G * %G\\n\",pnorm,snes_stol,xnorm);CHKERRQ(ierr);\n#if( (PETSC_VERSION_MAJOR == 3 && PETSC_VERSION_MINOR <= 2) || PETSC_VERSION_MAJOR<3 )\n      *reason = SNES_CONVERGED_PNORM_RELATIVE;\n#else\n      *reason = SNES_CONVERGED_SNORM_RELATIVE;\n#endif\n\n    }\n  }\n}\n\n\n#if defined(PETSC_HAVE_ISINF) && defined(PETSC_HAVE_ISNAN)\n#define PetscIsInfOrNanScalar(a) (isinf(PetscAbsScalar(a)) || isnan(PetscAbsScalar(a)))\n#define PetscIsInfOrNanReal(a) (isinf(a) || isnan(a))\n#elif defined(PETSC_HAVE__FINITE) && defined(PETSC_HAVE__ISNAN)\n#if defined(PETSC_HAVE_FLOAT_H)\n#include \"float.h\"  /* windows defines _finite() in float.h */\n#endif\n#define PetscIsInfOrNanScalar(a) (!_finite(PetscAbsScalar(a)) || _isnan(PetscAbsScalar(a)))\n#define PetscIsInfOrNanReal(a) (!_finite(a) || _isnan(a))\n#else\n#define PetscIsInfOrNanScalar(a) ((a - a) != 0.0)\n#define PetscIsInfOrNanReal(a) ((a - a) != 0.0)\n#endif\n\n/*\nThis will be replaced by SNESPicard in petsc 2.4.0.\n*/\n\nPetscErrorCode SystemLinearEquations_PicardExecute( void *sle, void *_context )\n{\n  SystemLinearEquations *self = (SystemLinearEquations*)sle;\n  SLE_Solver            *solver = (SLE_Solver*)self->solver;\n\n  Vec            X, Y, F, Xstar,delta_X;\n  PetscReal      alpha = 1.0;\n  PetscReal      fnorm,norm_X,pnorm,fnorm0;\n  PetscInt       i;\n  PetscErrorCode ierr;\n  SNESConvergedReason snes_reason;\n\n  PetscReal snes_norm;\n  PetscInt snes_iter;\n\n  PetscReal snes_ttol, snes_rtol, snes_abstol, snes_stol;\n  PetscInt  snes_maxits;\n\n  PetscTruth monitor_flg;\n\n  /* setup temporary some vectors */\n  solver->_getSolution( self, solver, &Xstar );\n\n  VecDuplicate( Xstar, &X );\n  VecDuplicate( X, &F );\n  VecDuplicate( F, &Y );\n  VecDuplicate( F, &delta_X );\n\n  /* Get some values from dictionary */\n  snes_maxits =  (PetscInt)self->nonLinearMaxIterations;\n  snes_ttol   = 0.0;\n  snes_rtol   = (PetscReal)self->rtol;\n  snes_abstol = (PetscReal)self->abstol;\n  snes_stol   = (PetscReal)self->stol;\n  monitor_flg = PETSC_FALSE;\n  if (self->picard_monitor==True) { monitor_flg = PETSC_TRUE; }\n  alpha       = (PetscReal)self->alpha;\n\n  snes_reason = SNES_CONVERGED_ITERATING;\n\n  /* Map X <- X* */\n  VecCopy( Xstar, X );  // Vector_CopyEntries( currentVector, previousVector );\n\n  /* Get an initial guess if |X| ~ 0, by solving the linear problem  */\n  VecNorm( X, NORM_2, &norm_X );\n  if (norm_X <1.0e-20) {\n    if (monitor_flg==PETSC_TRUE)\n      PetscPrintf( PETSC_COMM_WORLD, \"SLE_Picard: Computing an initial guess for X from the linear problem\\n\");\n\n    self->linearExecute( sle, _context );    /* X* = A^{-1} b */\n    self->hasExecuted = True;\n\n    /* Map X <- X* */\n    VecCopy( Xstar, X );\n    VecNorm( X, NORM_2, &norm_X );\n  }\n\n\n  snes_iter = 0;\n  snes_norm = 0;\n\n  SLEComputeFunction( sle, X, F, _context );\n  ierr = VecNorm(F, NORM_2, &fnorm); CHKERRQ(ierr); /* fnorm <- ||F||  */\n  fnorm0 = fnorm;\n\n  if( PetscIsInfOrNanReal(fnorm) )\n     Stg_SETERRQ(PETSC_ERR_FP,\"Infinite or not-a-number generated in norm\");\n\n  snes_norm = fnorm;\n  if(monitor_flg==PETSC_TRUE) {\n  /*  SLE_SNESMonitor(sle,0,fnorm); */\n  /*  SLE_SNESMonitor2(sle,0,fnorm0,fnorm, norm_X, norm_X ); */\n    SLE_SNESMonitorProgress( sle, snes_iter,  fnorm0, fnorm, norm_X, norm_X, snes_abstol, snes_rtol, snes_stol );\n  }\n\n  /* set parameter for default relative tolerance convergence test */\n  snes_ttol = fnorm*snes_rtol;\n  /* test convergence */\n  SLE_SNESConverged( snes_abstol,snes_rtol,snes_ttol,snes_stol , 0,norm_X,0.0,fnorm,&snes_reason);\n\n  if (snes_reason)\n     return NULL;\n\n  for(i = 0; i < snes_maxits; i++) {\n    /* Update guess Y = X^n - F(X^n) */\n    ierr = VecWAXPY(Y, -1.0, F, X);\n    CHKERRQ(ierr);\n\n    VecCopy( X, delta_X );  /* delta_X <- X */\n\n    /* X^{n+1} = (1 - \\alpha) X^n + alpha Y */\n    ierr = VecAXPBY(X, alpha, 1 - alpha, Y);\n    CHKERRQ(ierr);\n\n    VecNorm( X, NORM_2, &norm_X );\n    VecAYPX( delta_X, -1.0, X );   /* delta_X <- Xn+1 - delta_X */\n    VecNorm( delta_X, NORM_2, &pnorm );\n\n    /* Compute F(X^{new}) */\n    SLEComputeFunction( sle, X, F, _context );\n    ierr = VecNorm(F, NORM_2, &fnorm);\n    CHKERRQ(ierr);\n\n    if( PetscIsInfOrNanReal(fnorm) )\n       Stg_SETERRQ(PETSC_ERR_FP,\"Infinite or not-a-number generated norm\");\n\n    /* Monitor convergence */\n    snes_iter = i+1;\n    snes_norm = fnorm;\n    if (monitor_flg==PETSC_TRUE) {\n    /*  SLE_SNESMonitor(sle,snes_iter,snes_norm); */\n    /*  SLE_SNESMonitor2(sle,snes_iter,fnorm0,fnorm, pnorm, norm_X ); */\n\n      SLE_SNESMonitorProgress( sle, snes_iter,  fnorm0, fnorm, pnorm, norm_X, snes_abstol, snes_rtol, snes_stol );\n    }\n\n    /* Test for convergence */\n    SLE_SNESConverged( snes_abstol,snes_rtol,snes_ttol,snes_stol , snes_iter,norm_X,pnorm,fnorm,&snes_reason);\n    if (snes_reason) break;\n  }\n\n  if (i == snes_maxits) {\n    if (!snes_reason) snes_reason = SNES_DIVERGED_MAX_IT;\n  }\n\n  /* If monitoring, report reason converged */\n\n  if (monitor_flg==PETSC_TRUE)\n    PetscPrintf( PETSC_COMM_WORLD, \"Nonlinear solve converged due to %s \\n\", SNESConvergedReasons[snes_reason] );\n\n  Stg_VecDestroy(&X );\n  Stg_VecDestroy(&F );\n  Stg_VecDestroy(&Y );\n  Stg_VecDestroy(&delta_X );\n\n  return NULL;\n\n}\n\n\n/* ////////////// */\n\nvoid SystemLinearEquations_AddNonLinearEP( void* sle, const char* name, EntryPoint_2VoidPtr_Cast func ) {\n   SystemLinearEquations* self = (SystemLinearEquations*)sle;\n\n   SystemLinearEquations_SetToNonLinear( self, True );\n   EntryPoint_Append( self->nlEP, (char*)name, func, self->type );\n}\n\n\nvoid SystemLinearEquations_SetNonLinearTolerance( void* sle, double tol ){\n   SystemLinearEquations*   self = (SystemLinearEquations*) sle;\n   self->nonLinearTolerance = tol;\n   // SystemLinearEquations_SetToNonLinear( self, True );\n}\n\nvoid SystemLinearEquations_SetToNonLinear( void* sle, Bool isNonLinear ) {\n   SystemLinearEquations*   self = (SystemLinearEquations*) sle;\n   Hook*         nonLinearInitHook   = NULL;\n   Hook*         nonLinearFinaliseHook   = NULL;\n   FiniteElementContext*   context         = NULL;\n\n    if (isNonLinear) {\n        if ( self->isNonLinear )\n            return;\n\n        self->isNonLinear = True;\n\n        self->linearExecute = self->_execute;\n        self->_execute = SystemLinearEquations_NonLinearExecute;\n\n        if( self->nonLinearSolutionType ) {\n            if( !strcmp( self->nonLinearSolutionType, \"default\" ) ) {\n                self->_execute = SystemLinearEquations_NonLinearExecute;\n            }\n\n            if( !strcmp( self->nonLinearSolutionType, \"MatrixFreeNewton\" ) )\n                self->_execute = SystemLinearEquations_NewtonMFFDExecute;\n\n            if( !strcmp( self->nonLinearSolutionType, \"Newton\" ) ) {\n                assert(0); // the following will need to be fixed cos no context\n                context = self->context;\n\n                nonLinearInitHook = Hook_New( \"NewtonInitialise\",\n                            SystemLinearEquations_NewtonInitialise, self->name );\n                _EntryPoint_PrependHook_AlwaysFirst( Context_GetEntryPoint( context, AbstractContext_EP_Solve ),\n                                    nonLinearInitHook );\n                nonLinearFinaliseHook = Hook_New( \"NewtonFinalise\",\n                            SystemLinearEquations_NewtonFinalise, self->name );\n                _EntryPoint_AppendHook_AlwaysLast( Context_GetEntryPoint( context, AbstractContext_EP_Solve ),\n                            nonLinearFinaliseHook );\n                self->_execute = SystemLinearEquations_NewtonExecute;\n            }\n\n            if (!strcmp( self->nonLinearSolutionType, \"Picard\") ) {\n                /* set function pointer for execute */\n                self->_execute = SystemLinearEquations_PicardExecute;\n\n                /* set form function */\n                if (!strcmp(self->picard_form_function_type,\"PicardFormFunction_KSPResidual\") ) {\n                    self->_sleFormFunction = SystemLinearEquations_SNESPicardKSPResidual;\n                }\n                else if (!strcmp(self->picard_form_function_type,\"PicardFormFunction_FormalResidual\") ) {\n                    self->_sleFormFunction = SystemLinearEquations_SNESPicardFormalResidual;\n                }\n                else {\n                     Stream *errorStream = Journal_Register( Error_Type, (Name)self->type  );\n\n                            Journal_Printf( errorStream, \"Unknown the Picard FormFunction type %s is unrecognised. .\\n\", self->picard_form_function_type );\n                    Journal_Printf( errorStream, \"Supported types include <PicardFormFunction_FormalResidual, PicardFormFunction_KSPResidual> \\n\" );\n                                abort();\n\n                }\n            }\n        }\n    } else\n    {\n        self->isNonLinear   = False;\n        self->linearExecute = _SystemLinearEquations_Execute;\n        self->_execute      = _SystemLinearEquations_Execute;\n    }\n}\n\nvoid SystemLinearEquations_CheckIfNonLinear( void* sle ) {\n   SystemLinearEquations*   self            = (SystemLinearEquations*) sle;\n   Index                   index;\n\n   for ( index = 0; index < self->stiffnessMatrices->count; index++ ) {\n      StiffnessMatrix* stiffnessMatrix = SystemLinearEquations_GetStiffnessMatrixAt( self, index );\n\n      if ( stiffnessMatrix->isNonLinear )\n         SystemLinearEquations_SetToNonLinear( self, True );\n\n      /* TODO CHECK FOR FORCE VECTORS */\n   }\n}\n\n/*\n** All the MG functions and their general implementations.\n*/\n\nvoid SystemLinearEquations_MG_Enable( void* _sle ) {\n   SystemLinearEquations*   self = (SystemLinearEquations*)_sle;\n\n   if( !self->isBuilt ) {\n      Journal_Printf(self->info, \"Warning: SLE has not been built, can't enable multi-grid.\\n\" );\n      return;\n   }\n\n   self->mgEnabled = True;\n}\n\n\nvoid SystemLinearEquations_MG_SelectStiffMats( void* _sle, unsigned* nSMs, StiffnessMatrix*** sms ) {\n   SystemLinearEquations*   self = (SystemLinearEquations*)_sle;\n\n   assert( self->_mgSelectStiffMats );\n   self->_mgSelectStiffMats( self, nSMs, sms );\n}\n\n\nvoid _SystemLinearEquations_MG_SelectStiffMats( void* _sle, unsigned* nSMs, StiffnessMatrix*** sms ) {\n   SystemLinearEquations*   self = (SystemLinearEquations*)_sle;\n\n   /*\n   ** As we have nothing else to go on, attempt to apply MG to all stiffness matrices in the list.\n   */\n\n   {\n      unsigned   sm_i;\n\n      *nSMs = 0;\n      for( sm_i = 0; sm_i < self->stiffnessMatrices->count; sm_i++ ) {\n         StiffnessMatrix*   sm = ((StiffnessMatrix**)self->stiffnessMatrices->data)[sm_i];\n\n         /* Add this one to the list. */\n         *sms = Memory_Realloc_Array( *sms, StiffnessMatrix*, (*nSMs) + 1 );\n         (*sms)[*nSMs] = sm;\n         (*nSMs)++;\n      }\n   }\n}\n\nvoid SystemLinearEquations_SetCustomRunPoint( void* sle, void* _context, const Name entryPointName ){\n   SystemLinearEquations*   self = (SystemLinearEquations*)sle;\n\n   /** set this flag to ensure we now do not run during the execute phase */\n   self->runatExecutePhase = False;\n   assert(0); // the following will need to be fixed or deprecated\n   EP_AppendClassHook( Context_GetEntryPoint( _context, entryPointName ), _SystemLinearEquations_RunEP, sle );\n\n}\n\nSystemLinearEquations_RunEPFunction* SystemLinearEquations_GetRunEPFunction(){\n   return _SystemLinearEquations_RunEP;\n}\n\nvoid SystemLinearEquations_SetRunDuringExecutePhase( void* sle, Bool setRunDuringExectutePhase ){\n   SystemLinearEquations*   self = (SystemLinearEquations*)sle;\n\n   self->runatExecutePhase = setRunDuringExectutePhase;\n}\n", "meta": {"hexsha": "ed6b17405b23e2d7fbbc031b072d95c1916a02b9", "size": 58488, "ext": "c", "lang": "C", "max_stars_repo_path": "underworld/libUnderworld/StgFEM/SLE/SystemSetup/src/SystemLinearEquations.c", "max_stars_repo_name": "rbeucher/underworld2", "max_stars_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "underworld/libUnderworld/StgFEM/SLE/SystemSetup/src/SystemLinearEquations.c", "max_issues_repo_name": "rbeucher/underworld2", "max_issues_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "underworld/libUnderworld/StgFEM/SLE/SystemSetup/src/SystemLinearEquations.c", "max_forks_repo_name": "rbeucher/underworld2", "max_forks_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.978127136, "max_line_length": 260, "alphanum_fraction": 0.6690090275, "num_tokens": 15886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33807712415000585, "lm_q2_score": 0.02976009609727703, "lm_q1q2_score": 0.01006120770299523}}
{"text": "#ifndef SOURCE_PRINTTOFILE_H_\n#define SOURCE_PRINTTOFILE_H_\n\n// *** release/print_to_file.h ***\n// Author: Kevin Wolz, date: 08/2018\n//\n// Utilities to write the results obtained by robustness_main into files. \n\n#include <iostream>\n#include <iomanip> \n#include <fstream>\n#include <string>\n#include <sstream>\n#include <vector>\n#include <stdlib.h>\n#include <sys/stat.h>\n\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_cblas.h> \n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n\n#include \"utils.h\"\n#include \"md5hash.h\"\n\n\n// Appends the robustness (and, if analytical output, pdf) value to a file.\nvoid WriteData(std::ofstream& datafile, double& robustness, double& pdf);\n\n// Appends the initial conditions of a run (e.g. dimensions of data, covariance\n// matrix etc.) to a file.\nvoid WriteMetadata(std::ofstream& metafile, const unsigned& datdim, \n                   gsl_matrix* covar_matrix, const unsigned& pardim, \n                   gsl_vector* prior_param_values, gsl_matrix* prior_matrix,\n                   gsl_matrix* g_matrix, const unsigned& num_samplings);\n\n// Appends the metadata about a run (e.g. data hash ID, filepaths, timestamp, \n// etc) to a file.\nvoid WriteLogs(std::ofstream& logfile, std::string& meta_filepath, \n               const int& op_mode, std::string& data_filepath, \n               const int& success);\n\n#endif // SOURCE_PRINTTOFILE_H_\n", "meta": {"hexsha": "0708587b33a011ab90d8a9dfdcbcb25d1dbf6e1b", "size": 1477, "ext": "h", "lang": "C", "max_stars_repo_path": "source/print_to_file.h", "max_stars_repo_name": "kevguitar/Robustness", "max_stars_repo_head_hexsha": "ab83a09a82fcc7f8ee10027b3ccb24194731b4ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/print_to_file.h", "max_issues_repo_name": "kevguitar/Robustness", "max_issues_repo_head_hexsha": "ab83a09a82fcc7f8ee10027b3ccb24194731b4ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/print_to_file.h", "max_forks_repo_name": "kevguitar/Robustness", "max_forks_repo_head_hexsha": "ab83a09a82fcc7f8ee10027b3ccb24194731b4ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7708333333, "max_line_length": 79, "alphanum_fraction": 0.7034529452, "num_tokens": 380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3040416623541848, "lm_q2_score": 0.033085975051752044, "lm_q1q2_score": 0.010059514855343777}}
{"text": "/* $Id$      */\n/*--------------------------------------------------------------------*/\n/*;  Copyright (C) 2008-2016                                          */\n/*;  Associated Universities, Inc. Washington DC, USA.                */\n/*;                                                                   */\n/*;  This program is free software; you can redistribute it and/or    */\n/*;  modify it under the terms of the GNU General Public License as   */\n/*;  published by the Free Software Foundation; either version 2 of   */\n/*;  the License, or (at your option) any later version.              */\n/*;                                                                   */\n/*;  This program is distributed in the hope that it will be useful,  */\n/*;  but WITHOUT ANY WARRANTY; without even the implied warranty of   */\n/*;  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the    */\n/*;  GNU General Public License for more details.                     */\n/*;                                                                   */\n/*;  You should have received a copy of the GNU General Public        */\n/*;  License along with this program; if not, write to the Free       */\n/*;  Software Foundation, Inc., 675 Massachusetts Ave, Cambridge,     */\n/*;  MA 02139, USA.                                                   */\n/*;                                                                   */\n/*;Correspondence about this software should be addressed as follows: */\n/*;         Internet email: bcotton@nrao.edu.                         */\n/*;         Postal address: William Cotton                            */\n/*;                         National Radio Astronomy Observatory      */\n/*;                         520 Edgemont Road                         */\n/*;                         Charlottesville, VA 22903-2475 USA        */\n/*--------------------------------------------------------------------*/\n#ifndef OBITSPECTRUMFIT_H \n#define OBITSPECTRUMFIT_H \n\n#include \"Obit.h\"\n#include \"ObitErr.h\"\n#include \"ObitImage.h\"\n#include \"ObitBeamShape.h\"\n#include \"ObitThread.h\"\n#include \"ObitInfoList.h\"\n#ifdef HAVE_GSL\n#include <gsl/gsl_multifit_nlin.h>\n#endif /* HAVE_GSL */ \n\n/*-------- Obit:  Merx mollis mortibus nuper ------------------*/\n/**\n * \\file ObitSpectrumFit.h\n *\n * ObitSpectrumFit Class for fitting spectra to image pixels\n *\n * This class does least squares fitting of log(s) as a polynomial in log($\\nu$).\n * Either an image cube or a set of single plane images at arbitrary \n * frequencies may be fitted.\n * The result is an image cube of Log(S) with multiples of powers of log($\\nu$)\n * as the planes.\n * The function ObitSpectrumFitEval will evaluate this fit and return an image\n * with the flux densities at the desired frequencies.\n * \n * \\section ObitSpectrumFitaccess Creators and Destructors\n * An ObitSpectrumFit will usually be created using ObitSpectrumFitCreate which allows \n * specifying a name for the object as well as other information.\n *\n * A copy of a pointer to an ObitSpectrumFit should always be made using the\n * #ObitSpectrumFitRef function which updates the reference count in the object.\n * Then whenever freeing an ObitSpectrumFit or changing a pointer, the function\n * #ObitSpectrumFitUnref will decrement the reference count and destroy the object\n * when the reference count hits 0.\n * There is no explicit destructor.\n */\n\n/*--------------Class definitions-------------------------------------*/\n/** ObitSpectrumFit Class structure. */\ntypedef struct {\n#include \"ObitSpectrumFitDef.h\"   /* this class definition */\n} ObitSpectrumFit;\n\n/*----------------- Macroes ---------------------------*/\n/** \n * Macro to unreference (and possibly destroy) an ObitSpectrumFit\n * returns a ObitSpectrumFit*.\n * in = object to unreference\n */\n#define ObitSpectrumFitUnref(in) ObitUnref (in)\n\n/** \n * Macro to reference (update reference count) an ObitSpectrumFit.\n * returns a ObitSpectrumFit*.\n * in = object to reference\n */\n#define ObitSpectrumFitRef(in) ObitRef (in)\n\n/** \n * Macro to determine if an object is the member of this or a \n * derived class.\n * Returns TRUE if a member, else FALSE\n * in = object to reference\n */\n#define ObitSpectrumFitIsA(in) ObitIsA (in, ObitSpectrumFitGetClass())\n\n/*---------------Public functions---------------------------*/\n/** Public: Class initializer. */\nvoid ObitSpectrumFitClassInit (void);\n\n/** Public: Default Constructor. */\nObitSpectrumFit* newObitSpectrumFit (gchar* name);\n\n/** Public: Create/initialize ObitSpectrumFit structures */\nObitSpectrumFit* ObitSpectrumFitCreate (gchar* name, olong nterm);\n/** Typedef for definition of class pointer structure */\ntypedef ObitSpectrumFit* (*ObitSpectrumFitCreateFP) (gchar* name, \n\t\t\t\t\t\t     olong nterm);\n\n/** Public: ClassInfo pointer */\ngconstpointer ObitSpectrumFitGetClass (void);\n\n/** Public: Copy (deep) constructor. */\nObitSpectrumFit* ObitSpectrumFitCopy  (ObitSpectrumFit *in, \n\t\t\t\t       ObitSpectrumFit *out, ObitErr *err);\n\n/** Public: Copy structure. */\nvoid ObitSpectrumFitClone (ObitSpectrumFit *in, ObitSpectrumFit *out, \n\t\t\t   ObitErr *err);\n\n/** Public: Fit spectrum to an image cube */\nvoid ObitSpectrumFitCube (ObitSpectrumFit* in, ObitImage *inImage, \n\t\t\t  ObitImage *outImage, ObitErr *err);\n/** Typedef for definition of class pointer structure */\ntypedef void(*ObitSpectrumFitCubeFP) (ObitSpectrumFit* in, ObitImage *inImage, \n\t\t\t\t      ObitImage *outImage, ObitErr *err);\n\n/** Public: Fit spectrum to an array of images */\nvoid ObitSpectrumFitImArr (ObitSpectrumFit* in, olong nimage, ObitImage **imArr, \n\t\t\t   ObitImage *outImage, ObitErr *err);\n/** Typedef for definition of class pointer structure */\ntypedef void(*ObitSpectrumFitImArrFP) (ObitSpectrumFit* in, olong nimage, ObitImage **imArr, \n\t\t\t   ObitImage *outImage, ObitErr *err);\n\n/* Do actual fitting */\nvoid ObitSpectrumFitter (ObitSpectrumFit* in, ObitErr *err);\ntypedef void(*ObitSpectrumFitterFP) (ObitSpectrumFit* in, ObitErr *err);\n\n/** Public: Evaluate spectrum */\nvoid ObitSpectrumFitEval (ObitSpectrumFit* in, ObitImage *inImage, \n\t\t\t  odouble outFreq, ObitImage *outImage, ObitErr *err);\n/** Typedef for definition of class pointer structure */\ntypedef void(*ObitSpectrumFitEvalFP) (ObitSpectrumFit* in, ObitImage *inImage, \n\t\t\t\t      odouble outFreq, ObitImage *outImage, \n\t\t\t\t      ObitErr *err);\n/** Private: Write output image */\nvoid ObitSpectrumWriteOutput (ObitSpectrumFit* in, ObitImage *outImage, \n\t\t\t      ObitErr *err);\ntypedef void (*ObitSpectrumWriteOutputFP) (ObitSpectrumFit* in, ObitImage *outImage, \n\t\t\t\t\t   ObitErr *err);\n/** Public: Fit single spectrum */\nofloat* ObitSpectrumFitSingle (olong nfreq, olong nterm, odouble refFreq, odouble *freq, \n\t\t\t       ofloat *flux, ofloat *sigma, gboolean doBrokePow, \n\t\t\t       ObitErr *err);\n/** Typedef for definition of class pointer structure */\ntypedef ofloat*(*ObitSpectrumFitSingleFP) (olong nfreq, olong nterm, odouble refFreq, \n\t\t\t\t\t   odouble *freq, ofloat *flux, ofloat *sigma, \n\t\t\t\t\t   gboolean doBrokePow, ObitErr *err);\n\n/** Public: Make fitting arg structure */\ngpointer ObitSpectrumFitMakeArg (olong nfreq, olong nterm, \n\t\t\t\t odouble refFreq, odouble *freq, \n\t\t\t\t gboolean doBrokePow, \n\t\t\t\t ofloat **out, ObitErr *err);\n\n/** Public: Fit single spectrum using arg */\nvoid ObitSpectrumFitSingleArg (gpointer arg, ofloat *flux, ofloat  *sigma,\n\t\t\t       ofloat *out);\n\n/** Public: Kill fitting arg structure */\nvoid ObitSpectrumFitKillArg (gpointer arg);\n/*----------- ClassInfo Structure -----------------------------------*/\n/**\n * ClassInfo Structure.\n * Contains class name, a pointer to any parent class\n * (NULL if none) and function pointers.\n */\ntypedef struct  {\n#include \"ObitSpectrumFitClassDef.h\"\n} ObitSpectrumFitClassInfo; \n\n#endif /* OBITFSPECTRUMFIT_H */ \n", "meta": {"hexsha": "91f694e692075bd9161528156fb7f9bc766c4857", "size": 7778, "ext": "h", "lang": "C", "max_stars_repo_path": "ObitSystem/Obit/include/ObitSpectrumFit.h", "max_stars_repo_name": "sarrvesh/Obit", "max_stars_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-08-26T06:53:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-20T01:08:59.000Z", "max_issues_repo_path": "ObitSystem/Obit/include/ObitSpectrumFit.h", "max_issues_repo_name": "sarrvesh/Obit", "max_issues_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ObitSystem/Obit/include/ObitSpectrumFit.h", "max_forks_repo_name": "sarrvesh/Obit", "max_forks_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-08-29T15:12:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:16:08.000Z", "avg_line_length": 42.7362637363, "max_line_length": 93, "alphanum_fraction": 0.6346104397, "num_tokens": 1926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31742626558767584, "lm_q2_score": 0.031618768295228174, "lm_q1q2_score": 0.010036627542436283}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <gsl/gsl_histogram.h>\n#include <gsl/gsl_histogram2d.h>\n#include <gsl/gsl_errno.h>\n\nint mgsl_histogram_fwrite(const char *filename, const gsl_histogram *h)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_histogram_fwrite(fp, h) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_histogram_fread(const char *filename, gsl_histogram *h)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_histogram_fread(fp, h) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_histogram_fprintf(const char *filename, const gsl_histogram *h, const char *range_format, const char *bin_format)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_histogram_fprintf(fp, h, range_format, bin_format) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_histogram_fscanf(const char *filename, gsl_histogram *h)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_histogram_fscanf(fp, h) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_histogram2d_fwrite(const char *filename, const gsl_histogram2d *h)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_histogram2d_fwrite(fp, h) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_histogram2d_fread(const char *filename, gsl_histogram2d *h)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_histogram2d_fread(fp, h) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_histogram2d_fprintf(const char *filename, const gsl_histogram2d *h, const char *range_format, const char *bin_format)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_histogram2d_fprintf(fp, h, range_format, bin_format) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_histogram2d_fscanf(const char *filename, gsl_histogram2d *h)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_histogram2d_fscanf(fp, h) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n", "meta": {"hexsha": "f8f3a850ce81db515eef0731f2ae8d367e6e5fa9", "size": 2330, "ext": "c", "lang": "C", "max_stars_repo_path": "src/histogram.c", "max_stars_repo_name": "frithnanth/raku-Math-Libgsl-Histograms", "max_stars_repo_head_hexsha": "7c17262fbc4e5cdf693a97291336a8d7d54c9eca", "max_stars_repo_licenses": ["Artistic-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/histogram.c", "max_issues_repo_name": "frithnanth/raku-Math-Libgsl-Histograms", "max_issues_repo_head_hexsha": "7c17262fbc4e5cdf693a97291336a8d7d54c9eca", "max_issues_repo_licenses": ["Artistic-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-02-05T09:15:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-05T09:15:08.000Z", "max_forks_repo_path": "src/histogram.c", "max_forks_repo_name": "frithnanth/raku-Math-Libgsl-Histograms", "max_forks_repo_head_hexsha": "7c17262fbc4e5cdf693a97291336a8d7d54c9eca", "max_forks_repo_licenses": ["Artistic-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-05T07:22:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-05T07:22:44.000Z", "avg_line_length": 29.8717948718, "max_line_length": 126, "alphanum_fraction": 0.7248927039, "num_tokens": 671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29421497216298875, "lm_q2_score": 0.03410042215395161, "lm_q1q2_score": 0.010032854754771036}}
{"text": "#include <bindings.cmacros.h>\n#include <gsl/gsl_math.h>\n\nBC_INLINE2(GSL_FN_EVAL,gsl_function*,double,double)\nBC_INLINE2(GSL_FN_FDF_EVAL_F,gsl_function_fdf*,double,double)\nBC_INLINE2(GSL_FN_FDF_EVAL_DF,gsl_function_fdf*,double,double)\nBC_INLINE3(GSL_FN_VEC_EVAL,gsl_function_vec*,double,double*,double)\nBC_INLINE4VOID(GSL_FN_FDF_EVAL_F_DF,gsl_function_fdf*,double,double*,double*)\n", "meta": {"hexsha": "466477ace05a07cd918df4873eb76b59226eee42", "size": 380, "ext": "c", "lang": "C", "max_stars_repo_path": "bindings-gsl/src/Bindings/Gsl/MathematicalFunctions.c", "max_stars_repo_name": "flip111/bindings-dsl", "max_stars_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2015-04-29T00:31:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T09:29:03.000Z", "max_issues_repo_path": "bindings-gsl/src/Bindings/Gsl/MathematicalFunctions.c", "max_issues_repo_name": "flip111/bindings-dsl", "max_issues_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2015-01-04T06:32:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-07T09:49:12.000Z", "max_forks_repo_path": "bindings-gsl/src/Bindings/Gsl/MathematicalFunctions.c", "max_forks_repo_name": "flip111/bindings-dsl", "max_forks_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2015-01-03T20:43:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-10T19:31:38.000Z", "avg_line_length": 42.2222222222, "max_line_length": 77, "alphanum_fraction": 0.8552631579, "num_tokens": 109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.34158249943831703, "lm_q2_score": 0.02931223371923813, "lm_q1q2_score": 0.010012546057937477}}
{"text": "#ifndef PHI_SVM\n#define PHI_SVM\n#include <float.h>\n#include <vector>\n#include <list>\n#include <fstream>\n#include <iostream>\n#include <cmath>\n#include <cassert>\n#include <cstring>\n#include <cstdlib>\n#include <sys/time.h>\n\n// BLAS dependency\n#ifdef USE_MKL\n#include <mkl.h>\n#else\ntypedef int MKL_INT;\n#if defined __APPLE__\n#include <Accelerate/Accelerate.h>\n#else\nextern \"C\" {\n#include <cblas.h>\n}\n#endif\n#endif\n\n#include <string>\n#include <boost/serialization/serialization.hpp>\n#include <boost/archive/binary_oarchive.hpp>\n#include <boost/archive/binary_iarchive.hpp>\n#include <boost/iostreams/stream.hpp>\n#include <boost/iostreams/device/back_inserter.hpp>\n\n#include <sstream>\n\nusing namespace std;\n\n#define BLOCKSIZE 256\n#define REDUCE0 0x00000001\n#define REDUCE1 0x00000002\n#define MAX_PITCH 262144\n#define MAX_POINTS (MAX_PITCH / sizeof(float) - 2)\n#define MAXITERATIONS 100000\n#define intDivideRoundUp(a, b) (a % b != 0) ? (a / b + 1) : (a / b)\n\nenum KernelType {\n  NEWLINEAR,\n  NEWGAUSSIAN,\n  NEWPRECOMPUTED\n};\n\nstruct Kernel_params {\n  float gamma;\n  float coef0;\n  int degree;\n  float b;\n  std::string kernel_type;\n};\n\nenum SelectionHeuristic {\n  FIRSTORDER,\n  SECONDORDER,\n  RANDOM,\n  ADAPTIVE\n};\n\nclass PhiSVMModel {\npublic:\n  int nSamples;\n  int nDimension;\n  float epsilon;\n  float bLow;\n  float bHigh;\n  float* alpha;\n  float* f;\n  float* kernelDiag;\n  float* data;\n  float* labels;\n  PhiSVMModel() { // default constructor for training from the scratch\n  }\n  PhiSVMModel(int maxPoints, int maxDimension) {  // constructor for getting an existing model\n    alpha = new float[maxPoints];\n    f = new float[maxPoints];\n    kernelDiag = new float[maxPoints];\n    data = new float[maxPoints*maxDimension];\n    labels = new float[maxPoints];\n  }\n  ~PhiSVMModel() {  // leave the data and labels to others to delete\n    delete alpha;\n    delete f;\n    delete kernelDiag;\n  }\n};\n\nclass NewCache {\n public:\n  NewCache(int nPointsIn, int cacheSizeIn);\n  ~NewCache();\n  void findData(const int index, int& offset, bool& compute);\n  void search(const int index, int& offset, bool& compute);\n  void printCache();\n  void printStatistics();\n\n private:\n  int nPoints;\n  int cacheSize;\n  class DirectoryEntry {\n   public:\n    enum {\n      NEVER,\n      EVICTED,\n      INCACHE\n    };\n    DirectoryEntry();\n    int status;\n    int location;\n    std::list<int>::iterator lruListEntry;\n  };\n\n  std::vector<DirectoryEntry> directory;\n  std::list<int> lruList;\n  int occupancy;\n  int hits;\n  int compulsoryMisses;\n  int capacityMisses;\n};\n\nclass Controller {\n public:\n  Controller(float initialGap, SelectionHeuristic currentMethodIn,\n             int samplingIntervalIn, int problemSize);\n  void addIteration(float gap);\n  void print();\n  SelectionHeuristic getMethod();\n\n private:\n  bool adaptive;\n  int samplingInterval;\n  std::vector<float> progress;\n  std::vector<int> method;\n  SelectionHeuristic currentMethod;\n  std::vector<float> rates;\n  int timeSinceInspection;\n  int inspectionPeriod;\n  int beginningOfEpoch;\n  int middleOfEpoch;\n  int currentInspectionPhase;\n  float filter(int begin, int end);\n  float findRate(struct timeval* start, struct timeval* finish, int beginning,\n                 int end);\n  struct timeval start;\n  struct timeval mid;\n  struct timeval finish;\n};\n\nbool hasTwoTypes(float* labels, int n);\n\nfloat crossValidation(float* data, int nPoints, int nDimension,\n                               int nFolds, float* labels, Kernel_params* kp,\n                               float cost, SelectionHeuristic heuristicMethod,\n                               float epsilon, float tolerance,\n                               float* transposedData, bool shuffle);\n\nfloat incrementalCrossValidation(PhiSVMModel** models, float* data, int nPoints, int nDimension,\n                               int nFolds, float* labels, Kernel_params* kp,\n                               float cost, SelectionHeuristic heuristicMethod,\n                               float epsilon, float tolerance,\n                               float* transposedData, int maxNPoints);\n\nvoid svmGroupClasses(int nPoints, float* labels, int** start_ret,\n                     int** count_ret, int* perm);\nPhiSVMModel* performTraining(float* data, int nPoints, int nDimension, float* labels,\n                     Kernel_params* kp, float cost,\n                     SelectionHeuristic heuristicMethod, float epsilon,\n                     float tolerance, float* transposedData, PhiSVMModel* curModel);\nPhiSVMModel* performOnlineTraining(int nOldPoints, Kernel_params* kp, float cost,\n                     SelectionHeuristic heuristicMethod, float epsilon,\n                     float tolerance, PhiSVMModel* curModel);\n\ntemplate <int Kernel>\nvoid firstOrder(float* devData, int devDataPitchInFloats,\n                float* devTransposedData, int devTransposedDataPitchInFloats,\n                float* devLabels, int nPoints, int nDimension, float epsilon,\n                float cEpsilon, float* devAlpha, float* devF, float alpha1Diff,\n                float alpha2Diff, int iLow, int iHigh, float parameterA,\n                float parameterB, float parameterC, float* devCache,\n                int devCachePitchInFloats, int iLowCacheIndex,\n                int iHighCacheIndex, float* devKernelDiag, void* devResult,\n                float cost, bool iLowCompute, bool iHighCompute, int nthreads);\nvoid launchFirstOrder(bool iLowCompute, bool iHighCompute, int kType,\n                      int nPoints, int nDimension, float* devData,\n                      int devDataPitchInFloats, float* devTransposedData,\n                      int devTransposedDataPitchInFloats, float* devLabels,\n                      float epsilon, float cEpsilon, float* devAlpha,\n                      float* devF, float sAlpha1Diff, float sAlpha2Diff,\n                      int iLow, int iHigh, float parameterA, float parameterB,\n                      float parameterC, float* devCache,\n                      int devCachePitchInFloats, int iLowCacheIndex,\n                      int iHighCacheIndex, float* devKernelDiag,\n                      void* devResult, float cost, int nthreads);\ntemplate <int Kernel>\nvoid secondOrder(float* devData, int devDataPitchInFloats,\n                 float* devTransposedData, int devTransposedDataPitchInFloats,\n                 float* devLabels, int nPoints, int nDimension, float epsilon,\n                 float cEpsilon, float* devAlpha, float* devF, float alpha1Diff,\n                 float alpha2Diff, int iLow, int iHigh, float parameterA,\n                 float parameterB, float parameterC, float* devCache,\n                 int devCachePitchInFloats, int iLowCacheIndex,\n                 int iHighCacheIndex, float* devKernelDiag, void* devResult,\n                 float cost, float bHigh, bool iHighCompute, int nthreads);\nvoid launchSecondOrder(bool iLowCompute, bool iHighCompute, int kType,\n                       int nPoints, int nDimension, float* devData,\n                       int devDataPitchInFloats, float* devTransposedData,\n                       int devTransposedDataPitchInFloats, float* devLabels,\n                       float epsilon, float cEpsilon, float* devAlpha,\n                       float* devF, float sAlpha1Diff, float sAlpha2Diff,\n                       int iLow, int iHigh, float parameterA, float parameterB,\n                       float parameterC, NewCache* kernelCache, float* devCache,\n                       int devCachePitchInFloats, int iLowCacheIndex,\n                       int iHighCacheIndex, float* devKernelDiag,\n                       void* devResult, float cost, int iteration,\n                       int nthreads);\ntemplate <int Kernel>\nvoid initializeArrays(float* devData, int devDataPitchInFloats, float* devCache,\n                      int devCachePitchInFloats, int nPoints, int nDimension,\n                      float parameterA, float parameterB, float parameterC,\n                      float* devKernelDiag, float* devAlpha, float* devF,\n                      float* devLabels, int nthreads);\nvoid launchInitialization(float* devData, int devDataPitchInFloats,\n                          float* devCache, int devCachePitchInFloats,\n                          int nPoints, int nDimension, int kType,\n                          float parameterA, float parameterB, float parameterC,\n                          float* devKernelDiag, float* devAlpha, float* devF,\n                          float* devLabels, int nthreads);\ntemplate <int Kernel>\nvoid takeFirstStep(void* devResult, float* devKernelDiag, float* devData,\n                   int devDataPitchInFloats, float* devCache,\n                   int devCachePitchInFloats, float* devAlpha, float cost,\n                   int nDimension, int iLow, int iHigh, float parameterA,\n                   float parameterB, float parameterC);\nvoid launchTakeFirstStep(void* devResult, float* devKernelDiag, float* devData,\n                         int devDataPitchInFloats, float* devCache,\n                         int devCachePitchInFloats, float* devAlpha, float cost,\n                         int nDimension, int iLow, int iHigh, int kType,\n                         float parameterA, float parameterB, float parameterC,\n                         int nthreads);\nvoid performClassification(float* data, int nData, int nDimension,\n                           Kernel_params* kp, float** p_result, PhiSVMModel* model);\nvoid computeKernels(float* devNorms, int devNormsPitchInFloats, float* devAlpha,\n                    int nPoints, int nSV, const KernelType kType, int degree,\n                    float b, float* devResult);\nfloat kernel(const float v, const int degree, const KernelType kType);\nvoid makeSelfDots(float* devSource, int devSourcePitchInFloats, float* devDest,\n                  int sourceCount, int sourceLength);\nvoid makeDots(float* devDots, int devDotsPitchInFloats, float* devSVDots,\n              float* devDataDots, int nSV, int nPoints);\n\nclass DumpModel {\nprivate:\n  friend class boost::serialization::access;\n  template<class Archive>\n  void serialize(Archive & ar, const unsigned int version) {\n    ar & nSamples;\n    ar & nDimension;\n    for (int i=0; i<nSamples*nDimension; i++) {\n      ar & trainingData[i];\n    }\n    ar & phiSVMModel->nSamples;  // redundant with Model::nSamples\n    ar & phiSVMModel->nDimension;  // for precomputed kernel, should be the same as nSamples\n    ar & phiSVMModel->epsilon;\n    ar & phiSVMModel->bLow;\n    ar & phiSVMModel->bHigh;\n    for (int i=0; i<phiSVMModel->nSamples; i++) {\n      ar & phiSVMModel->alpha[i];\n    }\n    for (int i=0; i<phiSVMModel->nSamples; i++) {\n      ar & phiSVMModel->f[i];\n    }\n    for (int i=0; i<phiSVMModel->nSamples; i++) {\n      ar & phiSVMModel->kernelDiag[i];\n    }\n    // the data here for precomputed kernel is the kernel matrix\n    for (int i=0; i<phiSVMModel->nSamples*phiSVMModel->nDimension; i++) {\n      ar & phiSVMModel->data[i];\n    }\n    for (int i=0; i<phiSVMModel->nSamples; i++) {\n      ar & phiSVMModel->labels[i];\n    }\n  }\npublic:\n  int nSamples;\n  int nDimension;\n  float* trainingData;\n  PhiSVMModel* phiSVMModel;\n  DumpModel() {}\n  DumpModel(int s, int d) {\n    nSamples = s;\n    nDimension = d;\n    trainingData = new float[s*d];\n    phiSVMModel = new PhiSVMModel(MAX_POINTS, MAX_POINTS);\n  }\n  ~DumpModel() {\n    //delete trainingData;\n    //delete phiSVMModel->data;\n    //delete phiSVMModel->labels;\n    //delete phiSVMModel;\n  }\n};\n\nstd::string serialize_DumpModel(DumpModel* model_ptr);\nDumpModel* deserialize_DumpModel(std::string, int, int);\nvoid DumpModelToDisk(std::string modelStr);\n#endif", "meta": {"hexsha": "b1c53dddc2937242824534496c91feb8c8d4bcb7", "size": 11591, "ext": "h", "lang": "C", "max_stars_repo_path": "deps/SVM-phi/phisvm.h", "max_stars_repo_name": "PrincetonUniversity/fcma-toolbox", "max_stars_repo_head_hexsha": "74f151d07d683fc2b1612b5b0e2cb29617b69c03", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T04:27:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-16T17:34:07.000Z", "max_issues_repo_path": "deps/SVM-phi/phisvm.h", "max_issues_repo_name": "PrincetonUniversity/fcma-toolbox", "max_issues_repo_head_hexsha": "74f151d07d683fc2b1612b5b0e2cb29617b69c03", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-08-17T01:05:36.000Z", "max_issues_repo_issues_event_max_datetime": "2017-07-27T08:11:14.000Z", "max_forks_repo_path": "deps/SVM-phi/phisvm.h", "max_forks_repo_name": "PrincetonUniversity/fcma-toolbox", "max_forks_repo_head_hexsha": "74f151d07d683fc2b1612b5b0e2cb29617b69c03", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-08-26T19:37:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-08T18:06:26.000Z", "avg_line_length": 36.9140127389, "max_line_length": 96, "alphanum_fraction": 0.6455008196, "num_tokens": 2811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.020332354604124525, "lm_q1q2_score": 0.010007343707418185}}
{"text": "/* \n * File:   particle.h\n * Author: adithya\n *\n * Created on December 15, 2014, 7:23 PM\n */\n\n#ifndef PARTICLE_H\n#define\tPARTICLE_H\n\n//#include \"myVector.h\"\n//#include \"quaternion.h\"\n//#include \"species.h\"\n//#include \"simulationParameters.h\"\n//\n//#include <fstream>\n//#include <sstream>\n//#include <vector>\n//\n//#include <gsl/gsl_rng.h>\n//#include <gsl/gsl_randist.h>\n\n#include \"myVector.h\"\n#include \"quaternion.h\"\n#include \"main.h\"\n\nclass particle \n{\npublic:\n    particle();\n    particle(const particle& orig);\n    virtual ~particle();\npublic:\n    int particleID;/**This ID helps identifying the particle in question*/\n    int speciesType;/**Is the species type of the particle, which in turn holds information about the particles' physical properties.*/\n    int particleType;/**Describes the type of the particle, 1 if a particle with a domain(eGFRD), 2 if LD*/\n    //std::vector < std::pair <int, int> > complexList;\n    \n    std::vector < std::pair <int, int> > complexList;/**Gives the list of all other particles (if any)\n                                                      connectected to this particle in a complex\n                                                      and the patches of the particle that are occupied*/\n    /**\n     * @memberVariableOfSpeciesClass is a vector that contains the\n     * the state of all patches\n     * for a substrate\n     * 0 is unphosphorylated\n     * 1 is phosphorylated\n     * for an enzyme its always 1\n     */\n    std::vector<int> patchState;\n    \n    myVector particlePosition;  /**3D position of the centre of the particle*/\n    myVector force;             /**force on the particle*/\n    \n    quaternion q;               /**The orientation of the particle in 3 dimensions*/\n    quaternion torque;          /**The torque of the particle*/\n    \n    std::vector<myVector> patchPos;          /** 3D position of the centre of the patch of the particle which is used to\n                                 visualize the rotation*/\n    \n    /*GREENS FUNCTIONS RELATED VARIABLES*/\n    myVector nextEscapePosition;/**The center of the particle when the particle escapes*/\n    myVector burstPosition;/**center of the particle when the domain bursts*/\n    double R;/**This is the radius of displacement of the particle from the original position, after bursting*/\n    \n     /*DOMAIN RELATED MEMBER VARIABLES*/\n    int nextReactionType;/**if 0 then nothing (just Brownian step)\n                            if 1 then monomolecular dissociation\n                            if 2 hopping\n                            if 3 phosphorylation/dephosphorylation*/\n    int nextEventType;/**If 0 its escape(from the domain)\n                         if 1 its reaction\n                         */\n    double nextEscapeTime;/**The time at which the next escape occurs*/\n    double nextReactionTime;/**The time at which the next reaction occurs\n                             minimum of dissociation time, hopping time and phosphorylation time*/\n    double nextEventTime;/**The time at which the next event occurs, the min of the above two values*/\n    double timeOfConstructionOfDomain;/**Global time at which the domain is constructed*/\n    double domainRadius;/**radius of the domain around the particle*/\n    \n    bool operator < (const particle temp) const\n    {\n        return (this->nextEventTime < temp.nextEventTime);\n    }\n    \n     /**Function prints out the particle class\n     */\n    friend std::ostream& operator<< (std::ostream &out, particle &part);\n    \n    \n    /**\n     This function draws a random position at the sphere of domain radius if the particle escapes\n     */\n    void drawNextEscapePosition();\n\n\n    /**\n     This function draws a new position for the particle if the domain is prematurely burst\n     */\n    void drawBurstPosition (double time);\n    \n\n    /**\n     This function gets a next event time and type using greens functions for a single domain\n     */\n    void drawNextEventTimeAndType ();\n    \n\n    \n    /**\n     This function builds a domain on the particle which calls the function\n\n     @param nearestNeighborDistance radius of the domain to be built\n     */\n    void buildADomain(double nearestNeighborDistance);\n    \n\n    /**\n     This function bursts the given domain it can be used for bursting a domain, moving a particle or converting a particle to a LD particle\n\n     @param instruction escape, burst or convert\n     */\n    void burstTheDomain(std::string instruction);\n    \n\n    /**\n     This dissociates a particle in a domain\n     */\n    void dissociateParticleFromDomain();\n    \n};/**Particle holds all information related to the particle in the simulation*/\n\n#endif\t/* PARTICLE_H */\n\n", "meta": {"hexsha": "6617dcc3a0fff797aed709a6c720d6975de45e1e", "size": 4658, "ext": "h", "lang": "C", "max_stars_repo_path": "programming/particle.h", "max_stars_repo_name": "adithyavijaykumar/adithyavijaykumar.github.io", "max_stars_repo_head_hexsha": "693d3bbd40588adb538209d606225b2d7c5f8df8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "programming/particle.h", "max_issues_repo_name": "adithyavijaykumar/adithyavijaykumar.github.io", "max_issues_repo_head_hexsha": "693d3bbd40588adb538209d606225b2d7c5f8df8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "programming/particle.h", "max_forks_repo_name": "adithyavijaykumar/adithyavijaykumar.github.io", "max_forks_repo_head_hexsha": "693d3bbd40588adb538209d606225b2d7c5f8df8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5037037037, "max_line_length": 140, "alphanum_fraction": 0.6423357664, "num_tokens": 1004, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.021287352103904835, "lm_q1q2_score": 0.009979311132003035}}
{"text": "#define _MAIN\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <gbpLib.h>\n#include <gbpHalos.h>\n#include <sys/stat.h>\n#include <gsl/gsl_errno.h>\n\n#define GADGET_BUFFER_SIZE_LOCAL 128 * SID_SIZE_OF_MEGABYTE\n\n#define _FILE_OFFSET_BITS 64\n\ntypedef struct params_info_local params_info_local;\nstruct params_info_local {\n    GBPREAL *x_array;\n    GBPREAL *y_array;\n    GBPREAL *z_array;\n    GBPREAL *vx_array;\n    GBPREAL *vy_array;\n    GBPREAL *vz_array;\n    size_t * ids_array;\n    size_t * halo_sort_index;\n    size_t   first_particle_offset;\n};\n\ndouble p_i_local(void *params, int i_coord, int j_particle);\ndouble p_i_local(void *params, int i_coord, int j_particle) {\n    double r_val;\n    size_t k_particle = ((params_info_local *)params)->halo_sort_index[((params_info_local *)params)->first_particle_offset + j_particle];\n    switch(i_coord) {\n        case 0:\n            r_val = ((params_info_local *)params)->x_array[k_particle];\n            break;\n        case 1:\n            r_val = ((params_info_local *)params)->y_array[k_particle];\n            break;\n        case 2:\n            r_val = ((params_info_local *)params)->z_array[k_particle];\n            break;\n    }\n    return (r_val);\n}\n\ndouble v_i_local(void *params, int i_coord, int j_particle);\ndouble v_i_local(void *params, int i_coord, int j_particle) {\n    double r_val;\n    size_t k_particle = ((params_info_local *)params)->halo_sort_index[((params_info_local *)params)->first_particle_offset + j_particle];\n    switch(i_coord) {\n        case 0:\n            r_val = ((params_info_local *)params)->vx_array[k_particle];\n            break;\n        case 1:\n            r_val = ((params_info_local *)params)->vy_array[k_particle];\n            break;\n        case 2:\n            r_val = ((params_info_local *)params)->vz_array[k_particle];\n            break;\n    }\n    return (r_val);\n}\n\nsize_t id_i_local(void *params, int j_particle);\nsize_t id_i_local(void *params, int j_particle) {\n    size_t k_particle = ((params_info_local *)params)->halo_sort_index[((params_info_local *)params)->first_particle_offset + j_particle];\n    return (((params_info_local *)params)->ids_array[k_particle]);\n}\n\nvoid read_gadget_binary_local(char *filename_root_in, int snapshot_number, plist_info *plist);\nvoid read_gadget_binary_local(char *filename_root_in, int snapshot_number, plist_info *plist) {\n    char **            pname;\n    char *             name_initpositions;\n    char               filename[SID_MAX_FILENAME_LENGTH];\n    char *             read_catalog;\n    size_t             i, j, k, l, jj;\n    size_t             i_list_offset[N_GADGET_TYPE];\n    size_t             n_particles_file;\n    size_t             n_particles_kept;\n    size_t             n_of_type_rank[N_GADGET_TYPE];\n    size_t             n_of_type[N_GADGET_TYPE];\n    int                n_type_used;\n    int                n_particles_all_in_groups;\n    int                n_particles_in_groups;\n    size_t             n_particles_rank;\n    size_t             n_particles_all;\n    size_t             i_p, i_p_temp;\n    size_t             id_min, id_max;\n    double             mass_array[N_GADGET_TYPE];\n    int                unused[GADGET_HEADER_SIZE];\n    size_t             n_all[N_GADGET_TYPE];\n    int                n_all_tmp[N_GADGET_TYPE];\n    int                flag_metals;\n    int                flag_ages;\n    int                flag_entropyICs;\n    double             expansion_factor;\n    double             h_Hubble;\n    double             box_size;\n    double             d_value;\n    double             d1_value;\n    double             d2_value;\n    double             d3_value;\n    float              f_value;\n    int                i_value;\n    int                i1_value;\n    int                i2_value;\n    int                i3_value;\n    int                n_warning;\n    GBPREAL *          x_array[N_GADGET_TYPE];\n    GBPREAL *          y_array[N_GADGET_TYPE];\n    GBPREAL *          z_array[N_GADGET_TYPE];\n    GBPREAL *          vx_array[N_GADGET_TYPE];\n    GBPREAL *          vy_array[N_GADGET_TYPE];\n    GBPREAL *          vz_array[N_GADGET_TYPE];\n    size_t *           id_array[N_GADGET_TYPE];\n    size_t *           id_list;\n    size_t *           id_list_offset;\n    size_t *           id_list_in;\n    size_t *           id_list_index;\n    size_t             n_id_list;\n    unsigned int       record_length_open;\n    unsigned int       record_length_close;\n    int                n_return;\n    size_t             s_load;\n    char *             keep;\n    int                n_keep[N_GADGET_TYPE];\n    int                flag_keep_IDs      = GBP_TRUE;\n    int                flag_multifile     = GBP_FALSE;\n    int                flag_multimass     = GBP_FALSE;\n    int                flag_file_type     = 0;\n    int                flag_filefound     = GBP_FALSE;\n    int                flag_gas           = GBP_FALSE;\n    int                flag_initpositions = GBP_FALSE;\n    int                flag_no_velocities = GBP_FALSE;\n    int                flag_LONGIDS       = GBP_FALSE;\n    int                flag_read_marked   = GBP_FALSE;\n    int                flag_read_catalog  = GBP_FALSE;\n    int                flag_all_read_all  = GBP_FALSE;\n    int                i_file;\n    int                i_rank;\n    int                n_files;\n    int                n_files_in;\n    double             x_scale;\n    double             y_scale;\n    double             z_scale;\n    double             x_offset;\n    double             y_offset;\n    double             z_offset;\n    double             x_period;\n    double             y_period;\n    double             z_period;\n    int                flag_xscale;\n    int                flag_yscale;\n    int                flag_zscale;\n    int                flag_xoffset;\n    int                flag_yoffset;\n    int                flag_zoffset;\n    int                flag_xperiod;\n    int                flag_yperiod;\n    int                flag_zperiod;\n    FILE *             fp;\n    void *             buffer;\n    size_t *           buffer_index = NULL;\n    void *             buffer_i;\n    size_t             id_search;\n    size_t             id_value;\n    size_t             n_buffer;\n    int                n_non_zero;\n    int                seed = 1073743;\n    int                read_mode;\n    int                mark_mode;\n    double             x_min_read;\n    double             x_max_read;\n    double             y_min_read;\n    double             y_max_read;\n    double             z_min_read;\n    double             z_max_read;\n    double             x_min_bcast;\n    double             x_max_bcast;\n    double             y_min_bcast;\n    double             y_max_bcast;\n    double             z_min_bcast;\n    double             z_max_bcast;\n    gadget_header_info header;\n\n    // Determine file format\n    n_files = 1;\n    for(i_file = 0; i_file < 3 && !flag_filefound; i_file++) {\n        if(i_file == 0)\n            sprintf(filename, \"%s/snapshot_%03d/snapshot_%03d\", filename_root_in, snapshot_number, snapshot_number);\n        else if(i_file == 1)\n            sprintf(filename, \"%s/snapshot_%03d\", filename_root_in, snapshot_number);\n        else if(i_file == 2)\n            sprintf(filename, \"%s_%03d\", filename_root_in, snapshot_number);\n        fp = fopen(filename, \"r\");\n        if(fp != NULL) {\n            flag_filefound = GBP_TRUE;\n            flag_multifile = GBP_FALSE;\n            flag_file_type = i_file;\n        }\n        // ... if that doesn't work, check for multi-file\n        else {\n            strcat(filename, \".0\");\n            fp = fopen(filename, \"r\");\n            if(fp != NULL) {\n                flag_filefound = GBP_TRUE;\n                flag_multifile = GBP_TRUE;\n                flag_file_type = i_file;\n            }\n        }\n    }\n\n    // A file was found ...\n    SID_log(\"Reading GADGET binary file {%s}...\", SID_LOG_OPEN | SID_LOG_TIMER, filename_root_in);\n    if(flag_filefound) {\n        pname = plist->species;\n\n        // Header record length\n        SID_log(\"Reading header...\", SID_LOG_OPEN);\n        SID_fread_verify(&record_length_open, 4, 1, fp);\n        if(record_length_open != GADGET_HEADER_SIZE)\n            SID_log_warning(\"Problem with GADGET record size (opening size of header is wrong)\", SID_ERROR_LOGIC);\n\n        // Read header\n        SID_fread_verify(&header, sizeof(gadget_header_info), 1, fp);\n\n        // Number of particles for each species in this file\n        for(i = 0; i < N_GADGET_TYPE; i++)\n            n_of_type[i] = (size_t)header.n_file[i];\n\n        // Expansion factor (or time)\n        expansion_factor = header.time;\n        ADaPS_store(&(plist->data), (void *)(&expansion_factor), \"expansion_factor\", ADaPS_SCALAR_DOUBLE);\n        ADaPS_store(&(plist->data), (void *)(&(header.time)), \"time\", ADaPS_SCALAR_DOUBLE);\n\n        // Redshift\n        d_value = (double)header.redshift;\n        ADaPS_store(&(plist->data), (void *)(&d_value), \"redshift\", ADaPS_SCALAR_DOUBLE);\n\n        // Number of particles for each species in all files\n        for(i = 0; i < N_GADGET_TYPE; i++)\n            n_all[i] = (size_t)header.n_all_lo_word[i];\n\n        // Number of files in this snapshot\n        ADaPS_store(&(plist->data), (void *)(&(header.n_files)), \"n_files\", ADaPS_SCALAR_INT);\n        if(flag_multifile)\n            n_files = header.n_files;\n\n        // Cosmology\n\n        // Omega_o\n        d_value = (double)header.Omega_M;\n        ADaPS_store(&(plist->data), (void *)(&d_value), \"Omega_M\", ADaPS_SCALAR_DOUBLE);\n\n        // Omega_Lambda\n        d_value = (double)header.Omega_Lambda;\n        ADaPS_store(&(plist->data), (void *)(&d_value), \"Omega_Lambda\", ADaPS_SCALAR_DOUBLE);\n\n        // Hubble parameter\n        h_Hubble = (double)header.h_Hubble;\n        if(h_Hubble < 1e-10)\n            h_Hubble = 1.;\n        box_size = header.box_size * plist->length_unit / h_Hubble;\n        ADaPS_store(&(plist->data), (void *)(&box_size), \"box_size\", ADaPS_SCALAR_DOUBLE);\n        ADaPS_store(&(plist->data), (void *)(&h_Hubble), \"h_Hubble\", ADaPS_SCALAR_DOUBLE);\n\n        for(i = 0; i < N_GADGET_TYPE; i++) {\n            mass_array[i] = header.mass_array[i];\n            if(header.n_all_hi_word[i] > 0)\n                n_all[i] += (((size_t)(header.n_all_hi_word[i])) << 32);\n        }\n\n        // Count the total number of particles\n        n_particles_all = 0;\n        for(i = 0, n_non_zero = 0; i < N_GADGET_TYPE; i++) {\n            if(n_all[i] > 0) {\n                n_particles_all += n_all[i];\n                n_non_zero++;\n            }\n        }\n\n        // List numbers of particles in the log output\n        SID_log(\"%lld\", SID_LOG_CONTINUE, n_particles_all);\n        if(n_non_zero > 0)\n            SID_log(\" (\", SID_LOG_CONTINUE, n_particles_all);\n        for(i = 0; i < N_GADGET_TYPE; i++) {\n            if(n_all[i] > 0) {\n                if(i == n_non_zero - 1) {\n                    if(n_non_zero > 1)\n                        SID_log(\"and %lld %s\", SID_LOG_CONTINUE, n_all[i], pname[i]);\n                    else\n                        SID_log(\"%lld %s\", SID_LOG_CONTINUE, n_all[i], pname[i]);\n                } else {\n                    if(n_non_zero > 1)\n                        SID_log(\"%lld %s, \", SID_LOG_CONTINUE, n_all[i], pname[i]);\n                    else\n                        SID_log(\"%lld %s\", SID_LOG_CONTINUE, n_all[i], pname[i]);\n                }\n            }\n        }\n        if(n_non_zero > 0)\n            SID_log(\") particles...\", SID_LOG_CONTINUE);\n        else\n            SID_log(\" particles...\", SID_LOG_CONTINUE);\n\n        // Check closing record length\n        SID_fread_verify(&record_length_close, 4, 1, fp);\n        if(record_length_open != record_length_close)\n            SID_log_warning(\"Problem with GADGET record size (close of header)\", SID_ERROR_LOGIC);\n\n        // Close file\n        fclose(fp);\n        SID_log(\"Done.\", SID_LOG_CLOSE);\n\n        // Store mass array\n        for(i = 0; i < N_GADGET_TYPE; i++) {\n            if(n_all[i] > 0) {\n                mass_array[i] *= plist->mass_unit / h_Hubble;\n                if(mass_array[i] != 0.) {\n                    d_value = mass_array[i];\n                    ADaPS_store(&(plist->data), (void *)(&d_value), \"mass_array_%s\", ADaPS_SCALAR_DOUBLE, plist->species[i]);\n                }\n            } else\n                mass_array[i] = 0.;\n        }\n\n        // Is this a multimass snapshot?\n        flag_multimass = GBP_FALSE;\n        for(i = 0; i < N_GADGET_TYPE; i++)\n            if(n_all[i] > 0 && mass_array[i] == 0.)\n                flag_multimass = GBP_TRUE;\n\n        // Is sph being used?\n        if(n_all[GADGET_TYPE_GAS] > 0)\n            flag_gas = GBP_TRUE;\n        else\n            flag_gas = GBP_FALSE;\n\n        // Fetch (and sort by id) local group particles\n        SID_log(\"Sorting group particle ids...\", SID_LOG_OPEN);\n        n_particles_rank          = ((size_t *)ADaPS_fetch(plist->data, \"n_particles_%03d\", snapshot_number))[0];\n        n_particles_all_in_groups = ((size_t *)ADaPS_fetch(plist->data, \"n_particles_all_%03d\", snapshot_number))[0];\n        id_list                   = (size_t *)ADaPS_fetch(plist->data, \"particle_ids_%03d\", snapshot_number);\n        merge_sort((void *)id_list, (size_t)n_particles_rank, &id_list_index, SID_SIZE_T, SORT_COMPUTE_INDEX, GBP_FALSE);\n        for(i = 0; i < N_GADGET_TYPE; i++)\n            n_of_type_rank[i] = 0;\n        n_of_type[GADGET_TYPE_DARK]      = n_particles_all_in_groups;\n        n_of_type_rank[GADGET_TYPE_DARK] = n_particles_rank;\n        SID_log(\"Done.\", SID_LOG_CLOSE);\n\n        // Check integretry of particle ids\n        SID_log(\"Checking integrity of group particle ids...\", SID_LOG_OPEN);\n        for(j = 1, n_warning = 0; j < n_particles_rank && n_warning < 10; j++) {\n            if(id_list[id_list_index[j]] == id_list[id_list_index[j - 1]] && n_warning < 100) {\n                fprintf(stderr, \"WARNING: group particle id=%zd is duplicated on rank=%d!\\n\", id_list[id_list_index[j]], SID.My_rank);\n                n_warning++;\n            }\n        }\n        if(n_warning > 0)\n            SID_exit_error(\"Error in group particle ids!\", SID_ERROR_LOGIC);\n        SID_log(\"Done.\", SID_LOG_CLOSE);\n\n        // Allocate data arrays\n        for(i = 0; i < N_GADGET_TYPE; i++) {\n            if(n_of_type_rank[i] > 0) {\n                id_array[i] = (size_t *)SID_malloc(sizeof(size_t) * (size_t)n_of_type_rank[i]);\n                x_array[i]  = (GBPREAL *)SID_malloc(sizeof(GBPREAL) * (size_t)n_of_type_rank[i]);\n                y_array[i]  = (GBPREAL *)SID_malloc(sizeof(GBPREAL) * (size_t)n_of_type_rank[i]);\n                z_array[i]  = (GBPREAL *)SID_malloc(sizeof(GBPREAL) * (size_t)n_of_type_rank[i]);\n                vx_array[i] = (GBPREAL *)SID_malloc(sizeof(GBPREAL) * (size_t)n_of_type_rank[i]);\n                vy_array[i] = (GBPREAL *)SID_malloc(sizeof(GBPREAL) * (size_t)n_of_type_rank[i]);\n                vz_array[i] = (GBPREAL *)SID_malloc(sizeof(GBPREAL) * (size_t)n_of_type_rank[i]);\n            }\n        }\n\n        // Set offsets\n        for(i = 0; i < N_GADGET_TYPE; i++)\n            i_list_offset[i] = 0;\n\n        // Read data\n        for(i_file = 0, n_particles_kept = 0; i_file < n_files; i_file++) {\n            if(n_files > 1)\n                SID_log(\"Reading file %d of %d...\", SID_LOG_OPEN | SID_LOG_TIMER, i_file + 1, n_files);\n            else\n                SID_log(\"Performing read...\", SID_LOG_OPEN | SID_LOG_TIMER);\n\n            if(flag_file_type == 0)\n                sprintf(filename, \"%s/snapshot_%03d/snapshot_%03d\", filename_root_in, snapshot_number, snapshot_number);\n            else if(flag_file_type == 1)\n                sprintf(filename, \"%s/snapshot_%03d\", filename_root_in, snapshot_number);\n            else if(flag_file_type == 2)\n                sprintf(filename, \"%s_%03d\", filename_root_in, snapshot_number);\n            if(flag_multifile)\n                sprintf(filename, \"%s.%d\", filename, i_file);\n\n            // Read header and set positions pointer\n            FILE *fp_positions;\n            if(SID.I_am_Master) {\n                fp_positions = fopen(filename, \"r\");\n                SID_fread_verify(&record_length_open, sizeof(int), 1, fp_positions);\n                SID_fread_verify(&header, sizeof(gadget_header_info), 1, fp_positions);\n                SID_fread_verify(&record_length_close, sizeof(int), 1, fp_positions);\n                if(record_length_open != record_length_close)\n                    SID_log_warning(\"Problem with GADGET record size (close of header)\", SID_ERROR_LOGIC);\n                SID_fread_verify(&record_length_open, sizeof(int), 1, fp_positions);\n            }\n            SID_Bcast(&header, sizeof(gadget_header_info), SID_CHAR, SID_MASTER_RANK, SID_COMM_WORLD);\n            for(i = 0, n_particles_file = 0; i < N_GADGET_TYPE; i++)\n                n_particles_file += (size_t)header.n_file[i];\n\n            // Set velocities pointer\n            FILE *fp_velocities;\n            if(SID.I_am_Master) {\n                fp_velocities = fopen(filename, \"r\");\n                SID_fread_verify(&record_length_open, sizeof(int), 1, fp_velocities);\n                fseeko(fp_velocities, (off_t)record_length_open, SEEK_CUR);\n                SID_fread_verify(&record_length_close, sizeof(int), 1, fp_velocities);\n                if(record_length_open != record_length_close)\n                    SID_log_warning(\"Problem with GADGET record size (close of header)\", SID_ERROR_LOGIC);\n                SID_fread_verify(&record_length_open, sizeof(int), 1, fp_velocities);\n                fseeko(fp_velocities, (off_t)record_length_open, SEEK_CUR);\n                SID_fread_verify(&record_length_close, sizeof(int), 1, fp_velocities);\n                if(record_length_open != record_length_close)\n                    SID_log_warning(\"Problem with GADGET record size (close of positions)\", SID_ERROR_LOGIC);\n                SID_fread_verify(&record_length_open, sizeof(int), 1, fp_velocities);\n            }\n\n            // Set IDs pointer\n            FILE *fp_IDs;\n            if(SID.I_am_Master) {\n                fp_IDs = fopen(filename, \"r\");\n                SID_fread_verify(&record_length_open, sizeof(int), 1, fp_IDs);\n                fseeko(fp_IDs, (off_t)record_length_open, SEEK_CUR);\n                SID_fread_verify(&record_length_close, sizeof(int), 1, fp_IDs);\n                if(record_length_open != record_length_close)\n                    SID_log_warning(\"Problem with GADGET record size (close of header)\", SID_ERROR_LOGIC);\n                SID_fread_verify(&record_length_open, sizeof(int), 1, fp_IDs);\n                fseeko(fp_IDs, (off_t)record_length_open, SEEK_CUR);\n                SID_fread_verify(&record_length_close, sizeof(int), 1, fp_IDs);\n                if(record_length_open != record_length_close)\n                    SID_log_warning(\"Problem with GADGET record size (close of positions)\", SID_ERROR_LOGIC);\n                SID_fread_verify(&record_length_open, sizeof(int), 1, fp_IDs);\n                fseeko(fp_IDs, (off_t)record_length_open, SEEK_CUR);\n                SID_fread_verify(&record_length_close, sizeof(int), 1, fp_IDs);\n                if(record_length_open != record_length_close)\n                    SID_log_warning(\"Problem with GADGET record size (close of velocities)\", SID_ERROR_LOGIC);\n                SID_fread_verify(&record_length_open, sizeof(int), 1, fp_IDs);\n                if((size_t)record_length_open / n_particles_file == sizeof(long long)) {\n                    SID_log(\"(long long IDs)...\", SID_LOG_CONTINUE);\n                    flag_LONGIDS = GBP_TRUE;\n                } else if((size_t)record_length_open / n_particles_file == sizeof(int)) {\n                    SID_log(\"(int IDs)...\", SID_LOG_CONTINUE);\n                    flag_LONGIDS = GBP_FALSE;\n                } else\n                    SID_exit_error(\n                            \"IDs record length (%d) does not set a sensible id byte size for the number of particles given in the header (%s)\",\n                            SID_ERROR_LOGIC, record_length_open, n_particles_file);\n            }\n            SID_Bcast(&flag_LONGIDS, 1, SID_INT, SID_MASTER_RANK, SID_COMM_WORLD);\n\n            // Allocate buffers\n            int      n_buffer_max = GBP_MIN(n_particles_file, 4 * 1024 * 1024);\n            GBPREAL *buffer_positions;\n            GBPREAL *buffer_velocities;\n            size_t * buffer_IDs;\n            buffer_positions  = (GBPREAL *)SID_malloc(3 * n_buffer_max * sizeof(GBPREAL));\n            buffer_velocities = (GBPREAL *)SID_malloc(3 * n_buffer_max * sizeof(GBPREAL));\n            buffer_IDs        = (size_t *)SID_malloc(n_buffer_max * sizeof(size_t));\n\n            // Perform read\n            int     i_buffer;\n            int     n_buffer_left;\n            int     n_buffer;\n            int     i_species;\n            int     i_particle;\n            int     j_particle;\n            int     i_list;\n            size_t *buffer_index = NULL;\n            for(i_species = 0, i_buffer = n_buffer_max, i_list = 0, n_buffer_left = n_particles_file; i_species < N_GADGET_TYPE; i_species++) {\n                n_keep[i_species] = 0;\n                if(header.n_file[i_species] > 0) {\n                    for(i_particle = 0; i_particle < header.n_file[i_species]; i_particle++) {\n                        // Perform a buffered read\n                        if(i_buffer >= n_buffer_max) {\n                            n_buffer = GBP_MIN(n_buffer_max, n_buffer_left);\n                            if(SID.I_am_Master) {\n                                SID_fread_verify(buffer_positions, sizeof(GBPREAL), 3 * n_buffer, fp_positions);\n                                SID_fread_verify(buffer_velocities, sizeof(GBPREAL), 3 * n_buffer, fp_velocities);\n                                if(!flag_LONGIDS) {\n                                    int *buffer_IDs_int = (int *)buffer_IDs;\n                                    SID_fread_verify(buffer_IDs_int, sizeof(int), n_buffer, fp_IDs);\n                                    for(j_particle = n_buffer - 1; j_particle >= 0; j_particle--)\n                                        buffer_IDs[j_particle] = (size_t)buffer_IDs_int[j_particle];\n                                } else\n                                    SID_fread_verify(buffer_IDs, sizeof(size_t), n_buffer, fp_IDs);\n                            }\n                            SID_Bcast(buffer_positions, 3 * n_buffer, SID_REAL, SID_MASTER_RANK, SID_COMM_WORLD);\n                            SID_Bcast(buffer_velocities, 3 * n_buffer, SID_REAL, SID_MASTER_RANK, SID_COMM_WORLD);\n                            SID_Bcast(buffer_IDs, n_buffer, SID_SIZE_T, SID_MASTER_RANK, SID_COMM_WORLD);\n                            SID_free(SID_FARG buffer_index);\n                            merge_sort(buffer_IDs, (size_t)n_buffer, &buffer_index, SID_SIZE_T, SORT_COMPUTE_INDEX, GBP_FALSE);\n                            n_buffer_left -= n_buffer;\n                            i_buffer = 0;\n                            i_list   = 0;\n                        }\n\n                        if(i_list < n_particles_rank) {\n                            // Move to the next particle\n                            size_t id_test;\n                            size_t j_buffer = buffer_index[i_buffer];\n                            id_test         = buffer_IDs[j_buffer];\n                            while(id_list[id_list_index[i_list]] < id_test && i_list < (n_particles_rank - 1))\n                                i_list++;\n\n                            // If we've found a particle, add it to the arrays\n                            if(id_list[id_list_index[i_list]] == id_test) {\n                                GBPREAL f1_value;\n                                GBPREAL f2_value;\n                                GBPREAL f3_value;\n                                GBPREAL f4_value;\n                                GBPREAL f5_value;\n                                GBPREAL f6_value;\n                                f1_value                                                          = ((GBPREAL *)buffer_positions)[3 * j_buffer + 0];\n                                f2_value                                                          = ((GBPREAL *)buffer_positions)[3 * j_buffer + 1];\n                                f3_value                                                          = ((GBPREAL *)buffer_positions)[3 * j_buffer + 2];\n                                f4_value                                                          = ((GBPREAL *)buffer_velocities)[3 * j_buffer + 0];\n                                f5_value                                                          = ((GBPREAL *)buffer_velocities)[3 * j_buffer + 1];\n                                f6_value                                                          = ((GBPREAL *)buffer_velocities)[3 * j_buffer + 2];\n                                id_array[i_species][n_keep[i_species] + i_list_offset[i_species]] = id_test;\n                                x_array[i_species][n_keep[i_species] + i_list_offset[i_species]] =\n                                    f1_value * (GBPREAL)(plist->length_unit / h_Hubble);\n                                y_array[i_species][n_keep[i_species] + i_list_offset[i_species]] =\n                                    f2_value * (GBPREAL)(plist->length_unit / h_Hubble);\n                                z_array[i_species][n_keep[i_species] + i_list_offset[i_species]] =\n                                    f3_value * (GBPREAL)(plist->length_unit / h_Hubble);\n                                vx_array[i_species][n_keep[i_species] + i_list_offset[i_species]] =\n                                    f4_value * (GBPREAL)(plist->velocity_unit * sqrt(expansion_factor));\n                                vy_array[i_species][n_keep[i_species] + i_list_offset[i_species]] =\n                                    f5_value * (GBPREAL)(plist->velocity_unit * sqrt(expansion_factor));\n                                vz_array[i_species][n_keep[i_species] + i_list_offset[i_species]] =\n                                    f6_value * (GBPREAL)(plist->velocity_unit * sqrt(expansion_factor));\n                                n_keep[i_species]++;\n                                n_particles_kept++;\n                                i_list++;\n                            }\n                        }\n                        i_buffer++;\n                    } // i_particle\n                }     // if n>0\n            }         // i_species\n\n            // Update offsets\n            for(i_species = 0; i_species < N_GADGET_TYPE; i_species++)\n                i_list_offset[i_species] += n_keep[i_species];\n\n            // Clean-up\n            SID_free(SID_FARG buffer_positions);\n            SID_free(SID_FARG buffer_velocities);\n            SID_free(SID_FARG buffer_IDs);\n            SID_free(SID_FARG buffer_index);\n            if(SID.I_am_Master) {\n                fclose(fp_positions);\n                fclose(fp_velocities);\n                fclose(fp_IDs);\n            }\n            SID_log(\"Done.\", SID_LOG_CLOSE);\n        } // i_file\n\n        // Check that the right number of particles have been read\n        if(n_particles_kept != n_particles_rank)\n            SID_log_warning(\"Rank %d did not receive the right number of particles (ie. %d!=%d)\",\n                            SID_ERROR_LOGIC,\n                            SID.My_rank,\n                            n_particles_kept,\n                            n_particles_rank);\n\n        // Store everything in the data structure...\n\n        //   ... particle counts ...\n        for(i = 0; i < N_GADGET_TYPE; i++) {\n            if(n_of_type[i] > 0) {\n                SID_Allreduce(&(n_of_type_rank[i]), &(n_of_type[i]), 1, SID_SIZE_T, SID_SUM, SID_COMM_WORLD);\n                ADaPS_store(&(plist->data), (void *)(&(n_of_type_rank[i])), \"n_%s\", ADaPS_SCALAR_SIZE_T, pname[i]);\n                ADaPS_store(&(plist->data), (void *)(&(n_of_type[i])), \"n_all_%s\", ADaPS_SCALAR_SIZE_T, pname[i]);\n            }\n        }\n        ADaPS_store(&(plist->data), (void *)(&n_particles_all), \"n_particles_all\", ADaPS_SCALAR_SIZE_T);\n\n        //   ... positions ...\n        for(i = 0; i < N_GADGET_TYPE; i++) {\n            if(n_of_type_rank[i] > 0) {\n                ADaPS_store(&(plist->data), (void *)x_array[i], \"x_%s\", ADaPS_DEFAULT, pname[i]);\n                ADaPS_store(&(plist->data), (void *)y_array[i], \"y_%s\", ADaPS_DEFAULT, pname[i]);\n                ADaPS_store(&(plist->data), (void *)z_array[i], \"z_%s\", ADaPS_DEFAULT, pname[i]);\n            }\n        }\n\n        //  ... velocities ...\n        for(i = 0; i < N_GADGET_TYPE; i++) {\n            if(n_of_type_rank[i] > 0) {\n                ADaPS_store(&(plist->data), (void *)vx_array[i], \"vx_%s\", ADaPS_DEFAULT, pname[i]);\n                ADaPS_store(&(plist->data), (void *)vy_array[i], \"vy_%s\", ADaPS_DEFAULT, pname[i]);\n                ADaPS_store(&(plist->data), (void *)vz_array[i], \"vz_%s\", ADaPS_DEFAULT, pname[i]);\n            }\n        }\n\n        //  ... ids ...\n        for(i = 0; i < N_GADGET_TYPE; i++) {\n            if(n_of_type_rank[i] > 0)\n                ADaPS_store(&(plist->data), (void *)id_array[i], \"id_%s\", ADaPS_DEFAULT, pname[i]);\n        }\n\n        SID_free(SID_FARG id_list_index);\n\n        SID_log(\"Done.\", SID_LOG_CLOSE);\n    } else\n        SID_exit_error(\"Could not find file with root {%s}\", SID_ERROR_IO_OPEN, filename_root_in);\n}\n\nint main(int argc, char *argv[]) {\n    plist_info plist;\n    char       filename_groups_root[256];\n    char       filename_out_root[256];\n    char       filename_snapshot_root[256];\n    char       filename_snapshot[256];\n    char *     filename_number;\n    char       filename_output_properties_dir[256];\n    char       filename_output_properties[256];\n    char       filename_output_profiles_dir[256];\n    char       filename_output_profiles[256];\n    char       filename_output_indices[256];\n    char       filename_output_indices_dir[256];\n    char       filename_output_properties_temp[256];\n    char       filename_output_profiles_temp[256];\n    char       filename_output_indices_temp[256];\n    char       group_text_prefix[4];\n    int        n_groups_process;\n    int        n_groups;\n    int        n_groups_all;\n    int        i_rank;\n    int        i_group;\n    int        i_file_lo;\n    int        i_file_hi;\n    int        i_file;\n    int        i_file_skip;\n    int        i_particle;\n    int        j_particle;\n    int        i_process;\n    int        n_particles;\n    int        n_particles_max;\n    GBPREAL *  x_array;\n    GBPREAL *  y_array;\n    GBPREAL *  z_array;\n    GBPREAL *  vx_array;\n    GBPREAL *  vy_array;\n    GBPREAL *  vz_array;\n    int *      n_particles_groups_process;\n    int *      n_particles_groups;\n    int *      n_particles_subgroups;\n    size_t *   group_offset;\n    size_t     n_particles_in_groups;\n    size_t *   ids_snapshot;\n    size_t *   ids_groups;\n    size_t *   ids_sort_index;\n    size_t *   ids_snapshot_sort_index;\n    size_t *   ids_groups_sort_index;\n    size_t     n_particles_snapshot;\n    int        i_value;\n    double     h_Hubble;\n    double     Omega_M;\n    double     Omega_b;\n    double     Omega_Lambda;\n    double     f_gas;\n    double     Omega_k;\n    double     sigma_8;\n    double     n_spec;\n    double     redshift;\n    double     expansion_factor;\n    double     box_size;\n    double     particle_mass;\n\n    int         r_val;\n    struct stat file_stats;\n    size_t      n_bytes;\n    size_t      n_bytes_buffer;\n    void *      buffer;\n\n    FILE *               fp_properties;\n    FILE *               fp_profiles;\n    FILE *               fp_indices;\n    halo_properties_info properties;\n    halo_profile_info    profile;\n    int                  n_temp;\n    int                  n_truncated_local;\n    int                  n_truncated;\n    int                  largest_truncated;\n    int                  largest_truncated_local;\n    int                  flag_write_properties = GBP_TRUE;\n    int                  flag_write_profiles   = GBP_TRUE;\n    int                  flag_write_indices    = GBP_TRUE;\n    int                  flag_manual_centre    = GBP_TRUE;\n\n    SID_Init(&argc, &argv, NULL);\n\n    // Fetch user inputs\n    strcpy(filename_snapshot_root, argv[1]);\n    strcpy(filename_groups_root, argv[2]);\n    strcpy(filename_out_root, argv[3]);\n    i_file_lo          = atoi(argv[4]);\n    i_file_hi          = atoi(argv[5]);\n    i_file_skip        = atoi(argv[6]);\n    flag_manual_centre = atoi(argv[7]);\n\n    if(!flag_manual_centre)\n        flag_write_indices = GBP_FALSE;\n    else\n        flag_write_indices = GBP_TRUE;\n\n    SID_log(\"Processing group/subgroup statistics for files #%d->#%d...\", SID_LOG_OPEN | SID_LOG_TIMER, i_file_lo, i_file_hi);\n    SID_log(\"Properties structure size=%d bytes\", SID_LOG_COMMENT, sizeof(halo_properties_info));\n    SID_log(\"Profiles   structure size=%d bytes\", SID_LOG_COMMENT, sizeof(halo_profile_bin_info));\n\n    for(i_file = i_file_lo; i_file <= i_file_hi; i_file += i_file_skip) {\n        filename_number = (char *)SID_malloc(sizeof(char) * 10);\n        sprintf(filename_number, \"%03d\", i_file);\n        SID_log(\"Processing file #%d...\", SID_LOG_OPEN | SID_LOG_TIMER, i_file);\n\n        // Read group and particle info\n        init_plist(&plist, NULL, GADGET_LENGTH, GADGET_MASS, GADGET_VELOCITY);\n        // sprintf(filename_number,\"read_catalog\");\n        ADaPS_store(&(plist.data), (void *)filename_number, \"read_catalog\", ADaPS_DEFAULT);\n        read_groups(filename_groups_root, i_file, READ_GROUPS_ALL, &plist, filename_number);\n        n_particles_in_groups = ((size_t *)ADaPS_fetch(plist.data, \"n_particles_%s\", filename_number))[0];\n        n_groups_all          = ((int *)ADaPS_fetch(plist.data, \"n_groups_all_%s\", filename_number))[0];\n        if(n_groups_all > 0) {\n            read_gadget_binary_local(filename_snapshot_root, i_file, &plist);\n            // read_gadget_binary(filename_snapshot_root,i_file,&plist,READ_GADGET_DEFAULT);\n            if(ADaPS_exist(plist.data, \"id_dark\")) {\n                n_particles_snapshot = ((size_t *)ADaPS_fetch(plist.data, \"n_dark\"))[0];\n                ids_snapshot         = (size_t *)ADaPS_fetch(plist.data, \"id_dark\");\n                ids_groups           = (size_t *)ADaPS_fetch(plist.data, \"particle_ids_%s\", filename_number);\n                particle_mass        = ((double *)ADaPS_fetch(plist.data, \"mass_array_dark\"))[0];\n                x_array              = (GBPREAL *)ADaPS_fetch(plist.data, \"x_dark\");\n                y_array              = (GBPREAL *)ADaPS_fetch(plist.data, \"y_dark\");\n                z_array              = (GBPREAL *)ADaPS_fetch(plist.data, \"z_dark\");\n                vx_array             = (GBPREAL *)ADaPS_fetch(plist.data, \"vx_dark\");\n                vy_array             = (GBPREAL *)ADaPS_fetch(plist.data, \"vy_dark\");\n                vz_array             = (GBPREAL *)ADaPS_fetch(plist.data, \"vz_dark\");\n            } else\n                n_particles_snapshot = 0;\n\n            // Initialize cosmology\n            cosmo_info *cosmo = NULL;\n            box_size          = ((double *)ADaPS_fetch(plist.data, \"box_size\"))[0];\n            h_Hubble          = ((double *)ADaPS_fetch(plist.data, \"h_Hubble\"))[0];\n            redshift          = ((double *)ADaPS_fetch(plist.data, \"redshift\"))[0];\n            expansion_factor  = ((double *)ADaPS_fetch(plist.data, \"expansion_factor\"))[0];\n            Omega_M           = ((double *)ADaPS_fetch(plist.data, \"Omega_M\"))[0];\n            Omega_Lambda      = ((double *)ADaPS_fetch(plist.data, \"Omega_Lambda\"))[0];\n            Omega_k           = 1. - Omega_Lambda - Omega_M;\n            Omega_b           = 0.; // not needed, so doesn't matter\n            f_gas             = Omega_b / Omega_M;\n            sigma_8           = 0.; // not needed, so doesn't matter\n            n_spec            = 0.; // not needed, so doesn't matter\n            char cosmo_name[16];\n            sprintf(cosmo_name, \"Gadget file's\");\n            init_cosmo(&cosmo, cosmo_name, Omega_Lambda, Omega_M, Omega_k, Omega_b, f_gas, h_Hubble, sigma_8, n_spec);\n\n            // Compute sort indices for ids in snapshot and group catalog\n            SID_log(\"Sorting IDs...\", SID_LOG_OPEN | SID_LOG_TIMER);\n            if(n_particles_snapshot > 0) {\n                merge_sort((void *)ids_snapshot, n_particles_snapshot, &ids_snapshot_sort_index, SID_SIZE_T, SORT_COMPUTE_INDEX, GBP_FALSE);\n                merge_sort((void *)ids_groups, n_particles_in_groups, &ids_groups_sort_index, SID_SIZE_T, SORT_COMPUTE_INDEX, GBP_FALSE);\n\n                // Create snapshot-indices for each particle in the group catalog\n                ids_sort_index = (size_t *)SID_malloc(sizeof(size_t) * n_particles_in_groups);\n                for(i_particle = 0, j_particle = 0; i_particle < n_particles_in_groups; i_particle++) {\n                    while(ids_snapshot[ids_snapshot_sort_index[j_particle]] < ids_groups[ids_groups_sort_index[i_particle]]) {\n                        j_particle++;\n                        if(j_particle >= n_particles_snapshot)\n                            SID_exit_error(\"There's a particle id in the group catalog that's not in the snapshot!\",\n                                           SID_ERROR_LOGIC);\n                    }\n                    ids_sort_index[ids_groups_sort_index[i_particle]] = ids_snapshot_sort_index[j_particle];\n                }\n            } else {\n                ids_snapshot_sort_index = NULL;\n                ids_groups_sort_index   = NULL;\n                ids_sort_index          = NULL;\n            }\n            SID_log(\"Done.\", SID_LOG_CLOSE);\n\n            // Create the output directory\n            if(SID.I_am_Master)\n                mkdir(filename_out_root, 02755);\n\n            // Print stats; groups first and then subgroups\n            for(i_process = 0; i_process < 2; i_process++) {\n                // Initialize a bunch of stuff depending on whether we are\n                //   computing group or subgroup properties\n                switch(i_process) {\n                    case 0:\n                        sprintf(group_text_prefix, \"\");\n                        break;\n                    case 1:\n                        sprintf(group_text_prefix, \"sub\");\n                        break;\n                }\n                n_groups     = ((int *)ADaPS_fetch(plist.data, \"n_%sgroups_%s\", group_text_prefix, filename_number))[0];\n                n_groups_all = ((int *)ADaPS_fetch(plist.data, \"n_%sgroups_all_%s\", group_text_prefix, filename_number))[0];\n\n                // Fetch some stuff\n                n_particles_groups = (int *)ADaPS_fetch(plist.data, \"n_particles_%sgroup_%s\", group_text_prefix, filename_number);\n                group_offset       = (size_t *)ADaPS_fetch(plist.data, \"particle_offset_%sgroup_%s\", group_text_prefix, filename_number);\n\n                // Create filenames, directories, etc\n                sprintf(filename_output_properties_temp, \"%s_%s.catalog_%sgroups_properties\", filename_out_root, filename_number, group_text_prefix);\n                sprintf(filename_output_profiles_temp, \"%s_%s.catalog_%sgroups_profiles\", filename_out_root, filename_number, group_text_prefix);\n                sprintf(filename_output_indices_temp, \"%s_%s.catalog_%sgroups_indices\", filename_out_root, filename_number, group_text_prefix);\n                if(SID.n_proc > 1) {\n                    // Create property filenames\n                    if(flag_write_properties) {\n                        char properties_root[SID_MAX_FILENAME_LENGTH];\n                        strcpy(properties_root, filename_output_properties_temp);\n                        strip_path(properties_root);\n                        strcpy(filename_output_properties_dir, filename_output_properties_temp);\n                        if(SID.I_am_Master)\n                            mkdir(filename_output_properties_dir, 02755);\n                        SID_Barrier(SID_COMM_WORLD);\n                        sprintf(filename_output_properties, \"%s/%s.%d\", filename_output_properties_dir, properties_root, SID.My_rank);\n                    }\n                    // Create profile filenames\n                    if(flag_write_profiles) {\n                        char profiles_root[SID_MAX_FILENAME_LENGTH];\n                        strcpy(profiles_root, filename_output_profiles_temp);\n                        strip_path(profiles_root);\n                        strcpy(filename_output_profiles_dir, filename_output_profiles_temp);\n                        if(SID.I_am_Master)\n                            mkdir(filename_output_profiles_dir, 02755);\n                        SID_Barrier(SID_COMM_WORLD);\n                        sprintf(filename_output_profiles, \"%s/%s.%d\", filename_output_profiles_dir, profiles_root, SID.My_rank);\n                    }\n                    // Create sort indices filenames\n                    if(flag_write_indices) {\n                        char indices_root[SID_MAX_FILENAME_LENGTH];\n                        strcpy(indices_root, filename_output_indices_temp);\n                        strip_path(indices_root);\n                        strcpy(filename_output_indices_dir, filename_output_indices_temp);\n                        if(SID.I_am_Master)\n                            mkdir(filename_output_indices_dir, 02755);\n                        SID_Barrier(SID_COMM_WORLD);\n                        sprintf(filename_output_indices, \"%s/%s.%d\", filename_output_indices_dir, indices_root, SID.My_rank);\n                    }\n                } else {\n                    strcpy(filename_output_properties, filename_output_properties_temp);\n                    strcpy(filename_output_profiles, filename_output_profiles_temp);\n                    strcpy(filename_output_indices, filename_output_indices_temp);\n                }\n                SID_Barrier(SID_COMM_WORLD); // This makes sure that any created directories are there before proceeding\n\n                // Open files\n                SID_log(\"Processing %sgroups...\", SID_LOG_OPEN | SID_LOG_TIMER, group_text_prefix);\n                if(flag_write_properties)\n                    fp_properties = fopen(filename_output_properties, \"w\");\n                else\n                    fp_properties = NULL;\n                if(flag_write_profiles)\n                    fp_profiles = fopen(filename_output_profiles, \"w\");\n                else\n                    fp_profiles = NULL;\n                if(flag_write_indices)\n                    fp_indices = fopen(filename_output_indices, \"w\");\n                else\n                    fp_indices = NULL;\n\n                // Write header\n                if(fp_properties != NULL) {\n                    fwrite(&(SID.My_rank), sizeof(int), 1, fp_properties);\n                    fwrite(&(SID.n_proc), sizeof(int), 1, fp_properties);\n                    fwrite(&n_groups, sizeof(int), 1, fp_properties);\n                    fwrite(&n_groups_all, sizeof(int), 1, fp_properties);\n                }\n                if(fp_profiles != NULL) {\n                    fwrite(&(SID.My_rank), sizeof(int), 1, fp_profiles);\n                    fwrite(&(SID.n_proc), sizeof(int), 1, fp_profiles);\n                    fwrite(&n_groups, sizeof(int), 1, fp_profiles);\n                    fwrite(&n_groups_all, sizeof(int), 1, fp_profiles);\n                }\n                if(fp_indices != NULL) {\n                    fwrite(&(SID.My_rank), sizeof(int), 1, fp_indices);\n                    fwrite(&(SID.n_proc), sizeof(int), 1, fp_indices);\n                    fwrite(&n_groups, sizeof(int), 1, fp_indices);\n                    fwrite(&n_groups_all, sizeof(int), 1, fp_indices);\n                }\n\n                // Turn off the gsl error handler\n                gsl_error_handler_t *original_handler;\n                original_handler = gsl_set_error_handler_off();\n\n                // Create and write the properties and profiles of each group/subgroup in turn\n\n                // Allocate some temporary arrays for particle positions/velocities\n                int     n_particles_alloc;\n                double *x;\n                double *y;\n                double *z;\n                double *vx;\n                double *vy;\n                double *vz;\n                double *R;\n                size_t *R_index = NULL;\n                calc_max(n_particles_groups, &n_particles_alloc, n_groups, SID_INT, CALC_MODE_DEFAULT);\n                x  = (double *)SID_malloc(sizeof(double) * n_particles_alloc);\n                y  = (double *)SID_malloc(sizeof(double) * n_particles_alloc);\n                z  = (double *)SID_malloc(sizeof(double) * n_particles_alloc);\n                vx = (double *)SID_malloc(sizeof(double) * n_particles_alloc);\n                vy = (double *)SID_malloc(sizeof(double) * n_particles_alloc);\n                vz = (double *)SID_malloc(sizeof(double) * n_particles_alloc);\n                R  = (double *)SID_malloc(sizeof(double) * n_particles_alloc);\n\n                params_info_local params;\n                params.ids_array       = ids_snapshot;\n                params.x_array         = x_array;\n                params.y_array         = y_array;\n                params.z_array         = z_array;\n                params.vx_array        = vx_array;\n                params.vy_array        = vy_array;\n                params.vz_array        = vz_array;\n                params.halo_sort_index = ids_sort_index;\n\n                for(i_group = 0, n_truncated_local = 0, largest_truncated_local = 0; i_group < n_groups; i_group++) {\n                    params.first_particle_offset = group_offset[i_group];\n                    if(compute_group_analysis(&properties,\n                                              &profile,\n                                              p_i_local,\n                                              v_i_local,\n                                              id_i_local,\n                                              &params,\n                                              box_size,\n                                              particle_mass,\n                                              n_particles_groups[i_group],\n                                              expansion_factor,\n                                              x,\n                                              y,\n                                              z,\n                                              vx,\n                                              vy,\n                                              vz,\n                                              R,\n                                              &R_index,\n                                              flag_manual_centre,\n                                              GBP_TRUE,\n                                              cosmo) != GBP_TRUE) {\n                        n_truncated_local++;\n                        largest_truncated_local = GBP_MAX(largest_truncated_local, n_particles_groups[i_group]);\n                    }\n                    write_group_analysis(fp_properties, fp_profiles, fp_indices, &properties, &profile, R_index, n_particles_groups[i_group]);\n\n                    SID_free(SID_FARG R_index);\n                }\n\n                // Free arrays\n                SID_free(SID_FARG x);\n                SID_free(SID_FARG y);\n                SID_free(SID_FARG z);\n                SID_free(SID_FARG vx);\n                SID_free(SID_FARG vy);\n                SID_free(SID_FARG vz);\n                SID_free(SID_FARG R);\n\n                if(fp_properties != NULL)\n                    fclose(fp_properties);\n                if(fp_profiles != NULL)\n                    fclose(fp_profiles);\n                if(fp_indices != NULL)\n                    fclose(fp_indices);\n                calc_sum_global(&n_truncated_local, &n_truncated, 1, SID_INT, CALC_MODE_DEFAULT, SID_COMM_WORLD);\n                calc_max_global(&largest_truncated_local, &largest_truncated, 1, SID_INT, CALC_MODE_DEFAULT, SID_COMM_WORLD);\n\n                // Restore the original handler\n                gsl_set_error_handler(original_handler);\n\n                SID_Barrier(SID_COMM_WORLD);\n                SID_log(\n                    \"Done. (f_truncated=%6.2lf%% largest=%d)\", SID_LOG_CLOSE, 100. * (double)n_truncated / (double)n_groups_all, largest_truncated);\n            }\n\n            // Clean-up\n            free_cosmo(&cosmo);\n            SID_free(SID_FARG ids_snapshot_sort_index);\n            SID_free(SID_FARG ids_groups_sort_index);\n            SID_free(SID_FARG ids_sort_index);\n        }\n        // If the group catalog or snapshot is empty, create an empty file\n        else {\n            SID_log(\"Creating empty analysis files...\", SID_LOG_OPEN);\n            if(SID.I_am_Master) {\n                for(i_process = 0; i_process < 2; i_process++) {\n                    switch(i_process) {\n                        case 0:\n                            sprintf(group_text_prefix, \"\");\n                            break;\n                        case 1:\n                            sprintf(group_text_prefix, \"sub\");\n                            break;\n                    }\n                    n_groups_all = 0;\n                    n_temp       = 1;\n                    if(flag_write_properties) {\n                        sprintf(\n                            filename_output_properties, \"%s_%s.catalog_%sgroups_properties\", filename_out_root, filename_number, group_text_prefix);\n                        fp_properties = fopen(filename_output_properties, \"w\");\n                        fwrite(&(SID.My_rank), sizeof(int), 1, fp_properties);\n                        fwrite(&n_temp, sizeof(int), 1, fp_properties);\n                        fwrite(&n_groups_all, sizeof(int), 1, fp_properties);\n                        fwrite(&n_groups_all, sizeof(int), 1, fp_properties);\n                        fclose(fp_properties);\n                    }\n                    if(flag_write_profiles) {\n                        sprintf(filename_output_profiles, \"%s_%s.catalog_%sgroups_profiles\", filename_out_root, filename_number, group_text_prefix);\n                        fp_profiles = fopen(filename_output_profiles, \"w\");\n                        fwrite(&(SID.My_rank), sizeof(int), 1, fp_profiles);\n                        fwrite(&n_temp, sizeof(int), 1, fp_profiles);\n                        fwrite(&n_groups_all, sizeof(int), 1, fp_profiles);\n                        fwrite(&n_groups_all, sizeof(int), 1, fp_profiles);\n                        fclose(fp_profiles);\n                    }\n                }\n            }\n            SID_log(\"Done.\", SID_LOG_CLOSE);\n        }\n        free_plist(&plist);\n        SID_log(\"Done.\", SID_LOG_CLOSE);\n    }\n\n    SID_log(\"Done.\", SID_LOG_CLOSE);\n    SID_Finalize();\n}\n", "meta": {"hexsha": "a2e494dd31ff356109cb2382aa63b68b301e93d7", "size": 50744, "ext": "c", "lang": "C", "max_stars_repo_path": "src/gbpAstro/gbpHalos/make_group_analysis.c", "max_stars_repo_name": "gbpoole/gbpCode", "max_stars_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-10-20T11:39:53.000Z", "max_stars_repo_stars_event_max_datetime": "2015-10-20T11:39:53.000Z", "max_issues_repo_path": "src/gbpAstro/gbpHalos/make_group_analysis.c", "max_issues_repo_name": "gbpoole/gbpCode", "max_issues_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-07-30T11:10:49.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-18T00:40:46.000Z", "max_forks_repo_path": "src/gbpAstro/gbpHalos/make_group_analysis.c", "max_forks_repo_name": "gbpoole/gbpCode", "max_forks_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-01-23T00:50:40.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-01T08:14:24.000Z", "avg_line_length": 48.8392685274, "max_line_length": 149, "alphanum_fraction": 0.531727889, "num_tokens": 11022, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295203152604, "lm_q2_score": 0.022286186756809365, "lm_q1q2_score": 0.009929154095417584}}
{"text": "/* matrix/gsl_matrix_float.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_MATRIX_FLOAT_H__\n#define __GSL_MATRIX_FLOAT_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_vector_float.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size1;\n  size_t size2;\n  size_t tda;\n  float * data;\n  gsl_block_float * block;\n  int owner;\n} gsl_matrix_float;\n\ntypedef struct\n{\n  gsl_matrix_float matrix;\n} _gsl_matrix_float_view;\n\ntypedef _gsl_matrix_float_view gsl_matrix_float_view;\n\ntypedef struct\n{\n  gsl_matrix_float matrix;\n} _gsl_matrix_float_const_view;\n\ntypedef const _gsl_matrix_float_const_view gsl_matrix_float_const_view;\n\n/* Allocation */\n\nGSL_EXPORT\ngsl_matrix_float *\ngsl_matrix_float_alloc (const size_t n1, const size_t n2);\n\nGSL_EXPORT\ngsl_matrix_float *\ngsl_matrix_float_calloc (const size_t n1, const size_t n2);\n\nGSL_EXPORT\ngsl_matrix_float *\ngsl_matrix_float_alloc_from_block (gsl_block_float * b,\n                                   const size_t offset,\n                                   const size_t n1,\n                                   const size_t n2,\n                                   const size_t d2);\n\nGSL_EXPORT\ngsl_matrix_float *\ngsl_matrix_float_alloc_from_matrix (gsl_matrix_float * m,\n                                    const size_t k1,\n                                    const size_t k2,\n                                    const size_t n1,\n                                    const size_t n2);\n\nGSL_EXPORT\ngsl_vector_float *\ngsl_vector_float_alloc_row_from_matrix (gsl_matrix_float * m,\n                                        const size_t i);\n\nGSL_EXPORT\ngsl_vector_float *\ngsl_vector_float_alloc_col_from_matrix (gsl_matrix_float * m,\n                                        const size_t j);\n\nGSL_EXPORT void gsl_matrix_float_free (gsl_matrix_float * m);\n\n/* Views */\n\nGSL_EXPORT\n_gsl_matrix_float_view\ngsl_matrix_float_submatrix (gsl_matrix_float * m,\n                            const size_t i, const size_t j,\n                            const size_t n1, const size_t n2);\n\nGSL_EXPORT\n_gsl_vector_float_view\ngsl_matrix_float_row (gsl_matrix_float * m, const size_t i);\n\nGSL_EXPORT\n_gsl_vector_float_view\ngsl_matrix_float_column (gsl_matrix_float * m, const size_t j);\n\nGSL_EXPORT\n_gsl_vector_float_view\ngsl_matrix_float_diagonal (gsl_matrix_float * m);\n\nGSL_EXPORT\n_gsl_vector_float_view\ngsl_matrix_float_subdiagonal (gsl_matrix_float * m, const size_t k);\n\nGSL_EXPORT\n_gsl_vector_float_view\ngsl_matrix_float_superdiagonal (gsl_matrix_float * m, const size_t k);\n\nGSL_EXPORT\n_gsl_matrix_float_view\ngsl_matrix_float_view_array (float * base,\n                             const size_t n1,\n                             const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_float_view\ngsl_matrix_float_view_array_with_tda (float * base,\n                                      const size_t n1,\n                                      const size_t n2,\n                                      const size_t tda);\n\n\nGSL_EXPORT\n_gsl_matrix_float_view\ngsl_matrix_float_view_vector (gsl_vector_float * v,\n                              const size_t n1,\n                              const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_float_view\ngsl_matrix_float_view_vector_with_tda (gsl_vector_float * v,\n                                       const size_t n1,\n                                       const size_t n2,\n                                       const size_t tda);\n\n\nGSL_EXPORT\n_gsl_matrix_float_const_view\ngsl_matrix_float_const_submatrix (const gsl_matrix_float * m,\n                                  const size_t i, const size_t j,\n                                  const size_t n1, const size_t n2);\n\nGSL_EXPORT\n_gsl_vector_float_const_view\ngsl_matrix_float_const_row (const gsl_matrix_float * m,\n                            const size_t i);\n\nGSL_EXPORT\n_gsl_vector_float_const_view\ngsl_matrix_float_const_column (const gsl_matrix_float * m,\n                               const size_t j);\n\nGSL_EXPORT\n_gsl_vector_float_const_view\ngsl_matrix_float_const_diagonal (const gsl_matrix_float * m);\n\nGSL_EXPORT\n_gsl_vector_float_const_view\ngsl_matrix_float_const_subdiagonal (const gsl_matrix_float * m, \n                                    const size_t k);\n\nGSL_EXPORT\n_gsl_vector_float_const_view\ngsl_matrix_float_const_superdiagonal (const gsl_matrix_float * m,\n                                      const size_t k);\n\nGSL_EXPORT\n_gsl_matrix_float_const_view\ngsl_matrix_float_const_view_array (const float * base,\n                                   const size_t n1,\n                                   const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_float_const_view\ngsl_matrix_float_const_view_array_with_tda (const float * base,\n                                            const size_t n1,\n                                            const size_t n2,\n                                            const size_t tda);\n\nGSL_EXPORT\n_gsl_matrix_float_const_view\ngsl_matrix_float_const_view_vector (const gsl_vector_float * v,\n                                    const size_t n1,\n                                    const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_float_const_view\ngsl_matrix_float_const_view_vector_with_tda (const gsl_vector_float * v,\n                                             const size_t n1,\n                                             const size_t n2,\n                                             const size_t tda);\n\n/* Operations */\n\nGSL_EXPORT float   gsl_matrix_float_get(const gsl_matrix_float * m, const size_t i, const size_t j);\nGSL_EXPORT void    gsl_matrix_float_set(gsl_matrix_float * m, const size_t i, const size_t j, const float x);\n\nGSL_EXPORT float * gsl_matrix_float_ptr(gsl_matrix_float * m, const size_t i, const size_t j);\nGSL_EXPORT const float * gsl_matrix_float_const_ptr(const gsl_matrix_float * m, const size_t i, const size_t j);\n\nGSL_EXPORT void gsl_matrix_float_set_zero (gsl_matrix_float * m);\nGSL_EXPORT void gsl_matrix_float_set_identity (gsl_matrix_float * m);\nGSL_EXPORT void gsl_matrix_float_set_all (gsl_matrix_float * m, float x);\n\nGSL_EXPORT int gsl_matrix_float_fread (FILE * stream, gsl_matrix_float * m) ;\nGSL_EXPORT int gsl_matrix_float_fwrite (FILE * stream, const gsl_matrix_float * m) ;\nGSL_EXPORT int gsl_matrix_float_fscanf (FILE * stream, gsl_matrix_float * m);\nGSL_EXPORT int gsl_matrix_float_fprintf (FILE * stream, const gsl_matrix_float * m, const char * format);\n\nGSL_EXPORT int gsl_matrix_float_memcpy(gsl_matrix_float * dest, const gsl_matrix_float * src);\nGSL_EXPORT int gsl_matrix_float_swap(gsl_matrix_float * m1, gsl_matrix_float * m2);\n\nGSL_EXPORT int gsl_matrix_float_swap_rows(gsl_matrix_float * m, const size_t i, const size_t j);\nGSL_EXPORT int gsl_matrix_float_swap_columns(gsl_matrix_float * m, const size_t i, const size_t j);\nGSL_EXPORT int gsl_matrix_float_swap_rowcol(gsl_matrix_float * m, const size_t i, const size_t j);\nGSL_EXPORT int gsl_matrix_float_transpose (gsl_matrix_float * m);\nGSL_EXPORT int gsl_matrix_float_transpose_memcpy (gsl_matrix_float * dest, const gsl_matrix_float * src);\n\nGSL_EXPORT float gsl_matrix_float_max (const gsl_matrix_float * m);\nGSL_EXPORT float gsl_matrix_float_min (const gsl_matrix_float * m);\nGSL_EXPORT void gsl_matrix_float_minmax (const gsl_matrix_float * m, float * min_out, float * max_out);\n\nGSL_EXPORT void gsl_matrix_float_max_index (const gsl_matrix_float * m, size_t * imax, size_t *jmax);\nGSL_EXPORT void gsl_matrix_float_min_index (const gsl_matrix_float * m, size_t * imin, size_t *jmin);\nGSL_EXPORT void gsl_matrix_float_minmax_index (const gsl_matrix_float * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);\n\nGSL_EXPORT int gsl_matrix_float_isnull (const gsl_matrix_float * m);\n\nGSL_EXPORT int gsl_matrix_float_add (gsl_matrix_float * a, const gsl_matrix_float * b);\nGSL_EXPORT int gsl_matrix_float_sub (gsl_matrix_float * a, const gsl_matrix_float * b);\nGSL_EXPORT int gsl_matrix_float_mul_elements (gsl_matrix_float * a, const gsl_matrix_float * b);\nGSL_EXPORT int gsl_matrix_float_div_elements (gsl_matrix_float * a, const gsl_matrix_float * b);\nGSL_EXPORT int gsl_matrix_float_scale (gsl_matrix_float * a, const double x);\nGSL_EXPORT int gsl_matrix_float_add_constant (gsl_matrix_float * a, const double x);\nGSL_EXPORT int gsl_matrix_float_add_diagonal (gsl_matrix_float * a, const double x);\n\n/***********************************************************************/\n/* The functions below are obsolete                                    */\n/***********************************************************************/\nGSL_EXPORT int gsl_matrix_float_get_row(gsl_vector_float * v, const gsl_matrix_float * m, const size_t i);\nGSL_EXPORT int gsl_matrix_float_get_col(gsl_vector_float * v, const gsl_matrix_float * m, const size_t j);\nGSL_EXPORT int gsl_matrix_float_set_row(gsl_matrix_float * m, const size_t i, const gsl_vector_float * v);\nGSL_EXPORT int gsl_matrix_float_set_col(gsl_matrix_float * m, const size_t j, const gsl_vector_float * v);\n \n/* inline functions if you are using GCC */\n\n#ifdef HAVE_INLINE\nextern inline \nfloat\ngsl_matrix_float_get(const gsl_matrix_float * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_VAL(\"first index out of range\", GSL_EINVAL, 0) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_VAL(\"second index out of range\", GSL_EINVAL, 0) ;\n    }\n#endif\n  return m->data[i * m->tda + j] ;\n} \n\nextern inline \nvoid\ngsl_matrix_float_set(gsl_matrix_float * m, const size_t i, const size_t j, const float x)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_VOID(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_VOID(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  m->data[i * m->tda + j] = x ;\n}\n\nextern inline \nfloat *\ngsl_matrix_float_ptr(gsl_matrix_float * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  return (float *) (m->data + (i * m->tda + j)) ;\n} \n\nextern inline \nconst float *\ngsl_matrix_float_const_ptr(const gsl_matrix_float * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  return (const float *) (m->data + (i * m->tda + j)) ;\n} \n\n#endif\n\n__END_DECLS\n\n#endif /* __GSL_MATRIX_FLOAT_H__ */\n", "meta": {"hexsha": "d1f912004027f52e84b7029e7142ad96415f9517", "size": 11597, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/gsl/include/gsl/gsl_matrix_float.h", "max_stars_repo_name": "dynaryu/vaws", "max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/gsl/include/gsl/gsl_matrix_float.h", "max_issues_repo_name": "dynaryu/vaws", "max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/gsl/include/gsl/gsl_matrix_float.h", "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8104956268, "max_line_length": 135, "alphanum_fraction": 0.6791411572, "num_tokens": 2792, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34864514886966624, "lm_q2_score": 0.028436035720777426, "lm_q1q2_score": 0.009914085907133594}}
{"text": "#ifndef QDM_MCMC_H\n#define QDM_MCMC_H 1\n\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_vector.h>\n#include <hdf5.h>\n\n#include \"ijk.h\"\n#include \"tau.h\"\n\ntypedef struct {\n  const gsl_rng *rng;\n\n  size_t burn;\n  size_t iter;\n  size_t thin;\n\n  size_t acc_check;\n  size_t spline_df;\n\n  const gsl_vector *xi;\n  const gsl_vector *ll;\n  const gsl_vector *tau;\n  const gsl_matrix *theta;\n\n  double xi_prior_mean;\n  double xi_prior_var;\n  double xi_tune_sd;\n\n  double theta_min;\n  double theta_tune_sd;\n\n  const gsl_vector *x;\n  const gsl_vector *y;\n\n  const qdm_tau *t;\n  const gsl_vector *m_knots;\n\n  bool truncate;\n} qdm_mcmc_parameters;\n\ntypedef struct {\n  gsl_vector *xi;\n  gsl_vector *xi_acc;\n  gsl_vector *xi_p;\n  gsl_vector *xi_tune;\n\n  gsl_vector *ll;\n  gsl_vector *ll_p;\n\n  gsl_vector *tau;\n  gsl_vector *tau_p;\n\n  gsl_matrix *theta;\n  gsl_matrix *theta_acc;\n  gsl_matrix *theta_p;\n  gsl_matrix *theta_star;\n  gsl_matrix *theta_star_p;\n  gsl_matrix *theta_tune;\n} qdm_mcmc_workspace;\n\ntypedef struct {\n  size_t s;\n\n  qdm_ijk *theta;\n  qdm_ijk *theta_star;\n\n  qdm_ijk *ll;\n  qdm_ijk *tau;\n\n  qdm_ijk *xi;\n} qdm_mcmc_results;\n\ntypedef struct {\n  qdm_mcmc_parameters p;\n  qdm_mcmc_workspace w;\n  qdm_mcmc_results r;\n} qdm_mcmc;\n\nqdm_mcmc *\nqdm_mcmc_alloc(\n    qdm_mcmc_parameters p\n);\n\nvoid\nqdm_mcmc_free(\n    qdm_mcmc *mcmc\n);\n\nint\nqdm_mcmc_run(\n    qdm_mcmc *mcmc\n);\n\nint\nqdm_mcmc_next(\n    qdm_mcmc *mcmc\n);\n\nint\nqdm_mcmc_update_theta(\n    qdm_mcmc *mcmc\n);\n\nint\nqdm_mcmc_update_xi(\n    qdm_mcmc *mcmc\n);\n\nvoid\nqdm_mcmc_update_tune(\n    qdm_mcmc *mcmc\n);\n\nint\nqdm_mcmc_save(\n    qdm_mcmc *mcmc,\n    size_t k\n);\n\nint\nqdm_mcmc_write(\n    hid_t id,\n    const qdm_mcmc *mcmc\n);\n\nint\nqdm_mcmc_read(\n    hid_t id,\n    qdm_mcmc **mcmc\n);\n\n#endif /* QDM_MCMC_H */\n", "meta": {"hexsha": "e1c53634f6fc4e09aa52a94ec934c9e93dc09ee0", "size": 1780, "ext": "h", "lang": "C", "max_stars_repo_path": "include/qdm/mcmc.h", "max_stars_repo_name": "calebcase/qdm", "max_stars_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/qdm/mcmc.h", "max_issues_repo_name": "calebcase/qdm", "max_issues_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-03-06T18:09:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-22T20:22:53.000Z", "max_forks_repo_path": "include/qdm/mcmc.h", "max_forks_repo_name": "calebcase/qdm", "max_forks_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.1851851852, "max_line_length": 28, "alphanum_fraction": 0.7056179775, "num_tokens": 609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33807711081162, "lm_q2_score": 0.029312232341292967, "lm_q1q2_score": 0.009909794821383254}}
{"text": "#include <math.h>\n#include <stdlib.h>\n#if !defined(__APPLE__)\n#include <malloc.h>\n#endif\n#include <stdio.h>\n#include <assert.h>\n#include <time.h>\n#include <string.h>\n#include <stdbool.h>\n\n#include <fftw3.h>\n\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_sf_erf.h>\n#include <gsl/gsl_integration.h>\n#include <gsl/gsl_spline.h>\n#include <gsl/gsl_sf_gamma.h>\n#include <gsl/gsl_sf_legendre.h>\n#include <gsl/gsl_sf_bessel.h>\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_eigen.h>\n#include <gsl/gsl_sf_expint.h>\n#include <gsl/gsl_deriv.h>\n#include <gsl/gsl_interp2d.h>\n#include <gsl/gsl_spline2d.h>\n\n#include \"../cosmolike_core/theory/basics.c\"\n#include \"../cosmolike_core/theory/structs.c\"\n#include \"../cosmolike_core/theory/parameters.c\"\n#include \"../cosmolike_core/emu17/P_cb/emu.c\"\n#include \"../cosmolike_core/theory/recompute.c\"\n#include \"../cosmolike_core/theory/cosmo3D.c\"\n#include \"../cosmolike_core/theory/redshift_spline.c\"\n#include \"../cosmolike_core/theory/halo.c\"\n#include \"../cosmolike_core/theory/HOD.c\"\n#include \"../cosmolike_core/theory/pt.c\"\n#include \"../cosmolike_core/theory/cosmo2D_fourier.c\"\n#include \"../cosmolike_core/theory/IA.c\"\n#include \"../cosmolike_core/theory/BAO.c\"\n#include \"../cosmolike_core/theory/external_prior.c\"\n#include \"../cosmolike_core/theory/covariances_3D.c\"\n#include \"../cosmolike_core/theory/covariances_fourier.c\"\n#include \"../cosmolike_core/theory/CMBxLSS_fourier.c\"\n#include \"../cosmolike_core/theory/covariances_CMBxLSS_fourier.c\"\n\n#include \"../cosmolike_core/theory/covariances_binned_simple.c\"\n#include \"../cosmolike_core/theory/run_covariances_fourier_binned_6x2pt.c\"\n\n#include \"init_LSSxCMB.c\"\n\n\nint main(int argc, char** argv)\n{\n  \n  int i,l,m,n,o,s,p,nl1,t,k;\n  char OUTFILE[400],filename[400],arg1[400],arg2[400];\n  \n  int N_scenarios=2;\n  double area_table[2]={12300.0,16500.0}; // Y1 corresponds to DESC SRD Y1, Y6 corresponds to assuming that we cover the full SO area=0.4*fsky and at a depth of 26.1 which is in a range of reasonable scenarios (see https://github.com/LSSTDESC/ObsStrat/tree/static/static )\n  double nsource_table[2]={11.0,23.0};\n  double nlens_table[2]={18.0,41.0};\n  \n  char survey_designation[2][200]={\"LSSTxSO_Y1\",\"LSSTxSO_Y6\"};\n  \n  char source_zfile[2][400]={\"src_LSSTY1\",\"src_LSSTY6\"};\n\n#ifdef ONESAMPLE\n  char lens_zfile[2][400]={\"src_LSSTY1\",\"src_LSSTY6\"};\n  nlens_table[0] = nsource_table[0];\n  nlens_table[1] = nsource_table[1];\n#else\n  char lens_zfile[2][400]={\"lens_LSSTY1\",\"lens_LSSTY6\"};\n#endif\n\n  int hit=atoi(argv[1]);\n  Ntable.N_a=100;\n  k=1;\n  \n  t = atoi(argv[2]);\n  \n  //RUN MODE setup\n  init_cosmo_runmode(\"emu\");\n  // init_binning_fourier(20,30.0,3000.0,3000.0,21.0,10,10);\n  init_binning_fourier(15,20.0,3000.0,3000.0,0.0,10,10);\n  init_survey(survey_designation[t],nsource_table[t],nlens_table[t],area_table[t]);\n  sprintf(arg1,\"zdistris/%s\",source_zfile[t]);\n  sprintf(arg2,\"zdistris/%s\",lens_zfile[t]); \n  init_galaxies(arg1,arg2,\"none\",\"none\",\"source_std\",\"LSST_gold\");\n  init_IA(\"none\",\"GAMA\"); \n  init_probes(\"6x2pt\");\n\n  if(t==0) init_cmb(\"so_Y1\");\n  if(t==1) init_cmb(\"so_Y5\");\n  cmb.fsky = survey.area*survey.area_conversion_factor/(4.*M_PI);\n  //set l-bins for shear, ggl, clustering, clusterWL\n\n  double lmin=like.lmin;\n  double lmax=like.lmax;\n  int Nell=like.Ncl;\n  int Ncl = Nell;\n  double logdl=(log(lmax)-log(lmin))/Nell;\n  double *ellmin, *dell;\n  ellmin=create_double_vector(0,Nell);\n  dell=create_double_vector(0,Nell-1);\n  double ellmax;\n  for(i=0; i<Nell ; i++){\n    ellmin[i]=exp(log(lmin)+(i+0.0)*logdl);\n    ellmax = exp(log(lmin)+(i+1.0)*logdl);\n    dell[i]=ellmax-ellmin[i];\n  }\n  ellmin[Nell] = ellmax;\n  like.ell = ellmin;\n\n  covparams.ng = 1;\n  covparams.cng= 0;\n\n  printf(\"----------------------------------\\n\");  \n  sprintf(survey.name,\"%s_area%le_ng%le_nl%le\",survey_designation[t],survey.area,survey.n_gal,survey.n_lens);\n  printf(\"area: %le n_source: %le n_lens: %le\\n\",survey.area,survey.n_gal,survey.n_lens);\n\n  // sprintf(covparams.outdir,\"/home/u17/timeifler/covparallel/\"); \n#ifdef ONESAMPLE\n  sprintf(covparams.outdir,\"out_cov_lsstxso_1sample/\");\n#else\n  sprintf(covparams.outdir,\"out_cov_lsstxso/\");\n  //sprintf(covparams.outdir,\"/halo_nobackup/cosmos/teifler/covparallel/\");\n#endif\n\n  printf(\"----------------------------------\\n\");  \n  if (like.shear_shear)\n  {\n    sprintf(OUTFILE,\"%s_ssss_cov_Ncl%d_Ntomo%d\",survey.name,Ncl,tomo.shear_Nbin);\n\n    for (l=0;l<tomo.shear_Npowerspectra; l++){\n      for (m=l;m<tomo.shear_Npowerspectra; m++){\n        if(k==hit){\n          sprintf(filename,\"%s%s_%d\",covparams.outdir,OUTFILE,k);\n          // if (fopen(filename, \"r\") != NULL){exit(1);}\n          run_cov_shear_shear_fourier_bin(OUTFILE,covparams.outdir,ellmin,Ncl,l,m,k);\n        }\n\n        k=k+1;\n      }\n    }\n  }\n  if (like.pos_pos)\n  {\n    sprintf(OUTFILE,\"%s_llll_cov_Ncl%d_Ntomo%d\",survey.name,Ncl,tomo.shear_Nbin);\n    for (l=0;l<tomo.clustering_Npowerspectra; l++){ \n      for (m=l;m<tomo.clustering_Npowerspectra; m++){\n        if(k==hit){\n          sprintf(filename,\"%s%s_%d\",covparams.outdir,OUTFILE,k);\n          // if (fopen(filename, \"r\") != NULL){exit(1);}\n          run_cov_clustering_fourier_bin(OUTFILE,covparams.outdir,ellmin,Ncl,l,m,k); \n        }        \n        k=k+1;\n      }\n    }\n  }\n  if (like.shear_pos)\n  {\n    sprintf(OUTFILE,\"%s_lsls_cov_Ncl%d_Ntomo%d\",survey.name,Ncl,tomo.shear_Nbin);\n    for (l=0;l<tomo.ggl_Npowerspectra; l++){\n      for (m=l;m<tomo.ggl_Npowerspectra; m++){\n        if(k==hit) {\n          sprintf(filename,\"%s%s_%d\",covparams.outdir,OUTFILE,k);\n          // if (fopen(filename, \"r\") != NULL){exit(1);}\n          run_cov_ggl_fourier_bin(OUTFILE,covparams.outdir,ellmin,Ncl,l,m,k);  \n        }        \n        k=k+1;\n      }\n    }\n  }\n  if (like.shear_pos && like.shear_shear)\n  {\n    sprintf(OUTFILE,\"%s_lsss_cov_Ncl%d_Ntomo%d\",survey.name,Ncl,tomo.shear_Nbin);\n    for (l=0;l<tomo.ggl_Npowerspectra; l++){\n      for (m=0;m<tomo.shear_Npowerspectra; m++){\n        if(k==hit) {\n          sprintf(filename,\"%s%s_%d\",covparams.outdir,OUTFILE,k);\n          // if (fopen(filename, \"r\") != NULL){exit(1);}\n          run_cov_ggl_shear_fourier_bin(OUTFILE,covparams.outdir,ellmin,Ncl,l,m,k);  \n        } \n        k=k+1;\n      }\n    }\n  }\n  if (like.pos_pos && like.shear_shear)\n  {\n    sprintf(OUTFILE,\"%s_llss_cov_Ncl%d_Ntomo%d\",survey.name,Ncl,tomo.shear_Nbin);\n    for (l=0;l<tomo.clustering_Npowerspectra; l++){\n      for (m=0;m<tomo.shear_Npowerspectra; m++){\n        if(k==hit) {\n          sprintf(filename,\"%s%s_%d\",covparams.outdir,OUTFILE,k);\n          // if (fopen(filename, \"r\") != NULL){exit(1);}\n          run_cov_clustering_shear_fourier_bin(OUTFILE,covparams.outdir,ellmin,Ncl,l,m,k);  \n        } \n        k=k+1;\n      }\n    }\n  }\n  if (like.pos_pos && like.shear_pos)\n  {\n    sprintf(OUTFILE,\"%s_llls_cov_Ncl%d_Ntomo%d\",survey.name,Ncl,tomo.shear_Nbin);\n    for (l=0;l<tomo.clustering_Npowerspectra; l++){\n      for (m=0;m<tomo.ggl_Npowerspectra; m++){\n        if(k==hit) {\n          sprintf(filename,\"%s%s_%d\",covparams.outdir,OUTFILE,k);\n          // if (fopen(filename, \"r\") != NULL){exit(1);}\n          run_cov_clustering_ggl_fourier_bin(OUTFILE,covparams.outdir,ellmin,Ncl,l,m,k);  \n        }\n        k=k+1;\n      }\n    }\n  }\n  if (like.gk && like.shear_shear)\n  {\n    sprintf(OUTFILE,\"%s_lkss_cov_Ncl%d_Ntomo%d\",survey.name,Ncl,tomo.shear_Nbin);\n    for (l=0;l<tomo.clustering_Nbin; l++){\n      for (m=0;m<tomo.shear_Npowerspectra; m++){\n        if(k==hit) {\n          sprintf(filename,\"%s%s_%d\",covparams.outdir,OUTFILE,k);\n          // if (fopen(filename, \"r\") != NULL){exit(1);}\n          run_cov_gk_shear_fourier_bin(OUTFILE,covparams.outdir,ellmin,Ncl,l,m,k);  \n        } \n        k=k+1;\n      }\n    }\n  }\n  if (like.ks && like.shear_shear)\n  {\n    sprintf(OUTFILE,\"%s_ksss_cov_Ncl%d_Ntomo%d\",survey.name,Ncl,tomo.shear_Nbin);\n    for (l=0;l<tomo.shear_Nbin; l++){\n      for (m=0;m<tomo.shear_Npowerspectra; m++){\n        if(k==hit) {\n          sprintf(filename,\"%s%s_%d\",covparams.outdir,OUTFILE,k);\n          // if (fopen(filename, \"r\") != NULL){exit(1);}\n          run_cov_ks_shear_fourier_bin(OUTFILE,covparams.outdir,ellmin,Ncl,l,m,k);  \n        } \n        k=k+1;\n      }\n    }\n  }\n  if (like.gk && like.shear_pos)\n  {\n    sprintf(OUTFILE,\"%s_lkls_cov_Ncl%d_Ntomo%d\",survey.name,Ncl,tomo.shear_Nbin);\n    for (l=0;l<tomo.clustering_Nbin; l++){\n      for (m=0;m<tomo.ggl_Npowerspectra; m++){\n        if(k==hit) {\n          sprintf(filename,\"%s%s_%d\",covparams.outdir,OUTFILE,k);\n          // if (fopen(filename, \"r\") != NULL){exit(1);}\n          run_cov_gk_ggl_fourier_bin(OUTFILE,covparams.outdir,ellmin,Ncl,l,m,k);  \n        }\n        k=k+1;\n      }\n    }\n  }\n  if (like.ks && like.shear_pos)\n  {\n    sprintf(OUTFILE,\"%s_ksls_cov_Ncl%d_Ntomo%d\",survey.name,Ncl,tomo.shear_Nbin);\n    for (l=0;l<tomo.shear_Nbin; l++){\n      for (m=0;m<tomo.ggl_Npowerspectra; m++){\n        if(k==hit) {\n          sprintf(filename,\"%s%s_%d\",covparams.outdir,OUTFILE,k);\n          // if (fopen(filename, \"r\") != NULL){exit(1);}\n          run_cov_ks_ggl_fourier_bin(OUTFILE,covparams.outdir,ellmin,Ncl,l,m,k);  \n        }\n        k=k+1;\n      }\n    }\n  }\n  if (like.gk && like.pos_pos)\n  {\n    sprintf(OUTFILE,\"%s_lkll_cov_Ncl%d_Ntomo%d\",survey.name,Ncl,tomo.shear_Nbin);\n    for (l=0;l<tomo.clustering_Nbin; l++){\n      for (m=0;m<tomo.clustering_Npowerspectra; m++){\n        if(k==hit) {\n          sprintf(filename,\"%s%s_%d\",covparams.outdir,OUTFILE,k);\n          // if (fopen(filename, \"r\") != NULL){exit(1);}\n          run_cov_gk_clustering_fourier_bin(OUTFILE,covparams.outdir,ellmin,Ncl,l,m,k);  \n        }\n        k=k+1;\n      }\n    }\n  }\n  if (like.ks && like.pos_pos)\n  {\n    sprintf(OUTFILE,\"%s_ksll_cov_Ncl%d_Ntomo%d\",survey.name,Ncl,tomo.shear_Nbin);\n    for (l=0;l<tomo.shear_Nbin; l++){\n      for (m=0;m<tomo.clustering_Npowerspectra; m++){\n        if(k==hit) {\n          sprintf(filename,\"%s%s_%d\",covparams.outdir,OUTFILE,k);\n          // if (fopen(filename, \"r\") != NULL){exit(1);}\n          run_cov_ks_clustering_fourier_bin(OUTFILE,covparams.outdir,ellmin,Ncl,l,m,k);  \n        }\n        k=k+1;\n      }\n    }\n  }\n  if (like.gk)\n  {\n    sprintf(OUTFILE,\"%s_lklk_cov_Ncl%d_Ntomo%d\",survey.name,Ncl,tomo.shear_Nbin);\n    for (l=0;l<tomo.clustering_Nbin; l++){\n      for (m=l;m<tomo.clustering_Nbin; m++){\n        if(k==hit) {\n          sprintf(filename,\"%s%s_%d\",covparams.outdir,OUTFILE,k);\n          // if (fopen(filename, \"r\") != NULL){exit(1);}\n          run_cov_gk_gk_fourier_bin(OUTFILE,covparams.outdir,ellmin,Ncl,l,m,k);  \n        }\n        k=k+1;\n      }\n    }\n  }\n  if (like.ks && like.gk)\n  {\n    sprintf(OUTFILE,\"%s_kslk_cov_Ncl%d_Ntomo%d\",survey.name,Ncl,tomo.shear_Nbin);\n    for (l=0;l<tomo.shear_Nbin; l++){\n      for (m=0;m<tomo.clustering_Nbin; m++){\n        if(k==hit) {\n          sprintf(filename,\"%s%s_%d\",covparams.outdir,OUTFILE,k);\n          // if (fopen(filename, \"r\") != NULL){exit(1);}\n          run_cov_ks_gk_fourier_bin(OUTFILE,covparams.outdir,ellmin,Ncl,l,m,k);  \n        }\n        k=k+1;\n      }\n    }\n  }\n  if (like.ks)\n  {\n    sprintf(OUTFILE,\"%s_ksks_cov_Ncl%d_Ntomo%d\",survey.name,Ncl,tomo.shear_Nbin);\n    for (l=0;l<tomo.shear_Nbin; l++){\n      for (m=l;m<tomo.shear_Nbin; m++){\n        if(k==hit) {\n          sprintf(filename,\"%s%s_%d\",covparams.outdir,OUTFILE,k);\n          // if (fopen(filename, \"r\") != NULL){exit(1);}\n          run_cov_ks_ks_fourier_bin(OUTFILE,covparams.outdir,ellmin,Ncl,l,m,k);  \n        }\n        k=k+1;\n      }\n    }\n  }\n  ////////\n\n  if (like.kk && like.shear_shear)\n  {\n    sprintf(OUTFILE,\"%s_kkss_cov_Ncl%d_Ntomo%d\",survey.name,Ncl,tomo.shear_Nbin);\n    for (m=0;m<tomo.shear_Npowerspectra; m++){\n      if(k==hit) {\n        sprintf(filename,\"%s%s_%d\",covparams.outdir,OUTFILE,k);\n        // if (fopen(filename, \"r\") != NULL){exit(1);}\n        run_cov_kk_shear_fourier_bin(OUTFILE,covparams.outdir,ellmin,Ncl,m,k);  \n      } \n      k=k+1;\n    }\n  }\n  if (like.kk && like.shear_pos)\n  {\n    sprintf(OUTFILE,\"%s_kkls_cov_Ncl%d_Ntomo%d\",survey.name,Ncl,tomo.shear_Nbin);\n    for (m=0;m<tomo.ggl_Npowerspectra; m++){\n      if(k==hit) {\n        sprintf(filename,\"%s%s_%d\",covparams.outdir,OUTFILE,k);\n        // if (fopen(filename, \"r\") != NULL){exit(1);}\n        run_cov_kk_ggl_fourier_bin(OUTFILE,covparams.outdir,ellmin,Ncl,m,k);  \n      }\n      k=k+1;\n    }\n  }\n  if (like.kk && like.pos_pos)\n  {\n    sprintf(OUTFILE,\"%s_kkll_cov_Ncl%d_Ntomo%d\",survey.name,Ncl,tomo.shear_Nbin);\n    for (m=0;m<tomo.clustering_Npowerspectra; m++){\n      if(k==hit) {\n        sprintf(filename,\"%s%s_%d\",covparams.outdir,OUTFILE,k);\n        // if (fopen(filename, \"r\") != NULL){exit(1);}\n        run_cov_kk_clustering_fourier_bin(OUTFILE,covparams.outdir,ellmin,Ncl,m,k);  \n      }\n      k=k+1;\n    }\n  }\n  if (like.kk && like.gk)\n  {\n    sprintf(OUTFILE,\"%s_kklk_cov_Ncl%d_Ntomo%d\",survey.name,Ncl,tomo.shear_Nbin);\n    for (m=0;m<tomo.clustering_Nbin; m++){\n      if(k==hit) {\n        sprintf(filename,\"%s%s_%d\",covparams.outdir,OUTFILE,k);\n        // if (fopen(filename, \"r\") != NULL){exit(1);}\n        run_cov_kk_gk_fourier_bin(OUTFILE,covparams.outdir,ellmin,Ncl,m,k);  \n      }\n      k=k+1;\n    }\n  }\n  if (like.kk && like.ks)\n  {\n    sprintf(OUTFILE,\"%s_kkks_cov_Ncl%d_Ntomo%d\",survey.name,Ncl,tomo.shear_Nbin);\n    for (m=0;m<tomo.shear_Nbin; m++){\n      if(k==hit) {\n        sprintf(filename,\"%s%s_%d\",covparams.outdir,OUTFILE,k);\n        // if (fopen(filename, \"r\") != NULL){exit(1);}\n        run_cov_kk_ks_fourier_bin(OUTFILE,covparams.outdir,ellmin,Ncl,m,k);  \n      }\n      k=k+1;\n    }\n  }\n  if (like.kk)\n  {\n    sprintf(OUTFILE,\"%s_kkkk_cov_Ncl%d_Ntomo%d\",survey.name,Ncl,tomo.shear_Nbin);\n    if(k==hit) {\n      sprintf(filename,\"%s%s_%d\",covparams.outdir,OUTFILE,k);\n      // if (fopen(filename, \"r\") != NULL){exit(1);}\n      run_cov_kk_kk_fourier_bin(OUTFILE,covparams.outdir,ellmin,Ncl,k);  \n    }\n    k=k+1;\n  }\n\n\n  printf(\"number of cov blocks for parallelization: %d\\n\",k-1); \n  printf(\"-----------------\\n\");\n  printf(\"PROGRAM EXECUTED\\n\");\n  printf(\"-----------------\\n\");\n  return 0;   \n}\n\n", "meta": {"hexsha": "11d9fb27cc98578126998edf86ed60a9ccc44b2d", "size": 14095, "ext": "c", "lang": "C", "max_stars_repo_path": "compute_covariances_fourier_binned.c", "max_stars_repo_name": "CosmoLike/LSSTxSO", "max_stars_repo_head_hexsha": "43dfce33112480e17878b2de3421775ec9df296c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "compute_covariances_fourier_binned.c", "max_issues_repo_name": "CosmoLike/LSSTxSO", "max_issues_repo_head_hexsha": "43dfce33112480e17878b2de3421775ec9df296c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "compute_covariances_fourier_binned.c", "max_forks_repo_name": "CosmoLike/LSSTxSO", "max_forks_repo_head_hexsha": "43dfce33112480e17878b2de3421775ec9df296c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1647058824, "max_line_length": 272, "alphanum_fraction": 0.6179496275, "num_tokens": 4740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378235137849365, "lm_q2_score": 0.022629198797146935, "lm_q1q2_score": 0.00990759533150473}}
{"text": "\ufeff/*! \\file deleter.h\n    \\brief gsl_interp_accel\u3068gsl_spline\u306e\u30c7\u30ea\u30fc\u30bf\u3092\u5ba3\u8a00\u30fb\u5b9a\u7fa9\u3057\u305f\u30d8\u30c3\u30c0\u30d5\u30a1\u30a4\u30eb\n\n    Copyright \u00a9 2015 @dc1394 All Rights Reserved.\n    This software is released under the BSD 2-Clause License.\n*/\n\n\n#ifndef _DELETER_H_\n#define _DELETER_H_\n\n#pragma once\n\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_spline.h>\n\nnamespace getdata {\n    //! A function.\n    /*!\n        gsl_interp_accel\u3078\u306e\u30dd\u30a4\u30f3\u30bf\u3092\u89e3\u653e\u3059\u308b\u30e9\u30e0\u30c0\u5f0f\n        \\param acc gsl_interp_accel\u3078\u306e\u30dd\u30a4\u30f3\u30bf\n    */\n    static auto const gsl_interp_accel_deleter = [](gsl_interp_accel * acc) {\n        gsl_interp_accel_free(acc);\n    };\n\n    //! A function.\n    /*!\n        gsl_spline\u3078\u306e\u30dd\u30a4\u30f3\u30bf\u3092\u89e3\u653e\u3059\u308b\u30e9\u30e0\u30c0\u5f0f\n        \\param spline gsl_spline\u3078\u306e\u30dd\u30a4\u30f3\u30bf\n    */\n    static auto const gsl_spline_deleter = [](gsl_spline * spline) {\n        gsl_spline_free(spline);\n    };\n}\n\n#endif  // _DELETER_H_\n", "meta": {"hexsha": "0bab56f063e03d45b799af313d5c2ec04be8b12b", "size": 811, "ext": "h", "lang": "C", "max_stars_repo_path": "getdata/deleter.h", "max_stars_repo_name": "dc1394/SchracVisualize", "max_stars_repo_head_hexsha": "0ac49e883a4f9b92a48d224350f3d1967a1dbfe7", "max_stars_repo_licenses": ["Intel", "X11", "OLDAP-2.2.1", "Unlicense"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-05-02T05:26:00.000Z", "max_stars_repo_stars_event_max_datetime": "2016-01-08T04:52:02.000Z", "max_issues_repo_path": "getdata/deleter.h", "max_issues_repo_name": "dc1394/SchracVisualize", "max_issues_repo_head_hexsha": "0ac49e883a4f9b92a48d224350f3d1967a1dbfe7", "max_issues_repo_licenses": ["Intel", "X11", "OLDAP-2.2.1", "Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "getdata/deleter.h", "max_forks_repo_name": "dc1394/SchracVisualize", "max_forks_repo_head_hexsha": "0ac49e883a4f9b92a48d224350f3d1967a1dbfe7", "max_forks_repo_licenses": ["Intel", "X11", "OLDAP-2.2.1", "Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.3421052632, "max_line_length": 77, "alphanum_fraction": 0.67324291, "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16238004477370327, "lm_q2_score": 0.06097517958516649, "lm_q1q2_score": 0.009901152391123932}}
{"text": "/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */\n/*\n *     Copyright 2018-Present Couchbase, Inc.\n *\n *   Use of this software is governed by the Business Source License included\n *   in the file licenses/BSL-Couchbase.txt.  As of the Change Date specified\n *   in that file, in accordance with the Business Source License, use of this\n *   software will be governed by the Apache License, Version 2.0, included in\n *   the file licenses/APL2.txt.\n */\n#pragma once\n\n#include <gsl/gsl-lite.hpp>\n#include <platform/sized_buffer.h>\n#include <array>\n#include <optional>\n#include <type_traits>\n\nnamespace cb::mcbp {\n\n/**\n * Helper code for encode and decode of LEB128 values.\n * - mcbp encodes collection-ID as an unsigned LEB128\n * - see https://en.wikipedia.org/wiki/LEB128\n */\n\n// Empty, non specialised version of the decoder class\ntemplate <class T, class Enable = void>\nclass unsigned_leb128 {};\n\n/**\n * For encoding a unsigned T leb128, class constructs from a T value and\n * provides a const_byte_buffer for access to the encoded\n */\ntemplate <class T>\nclass unsigned_leb128<\n        T,\n        typename std::enable_if<std::is_unsigned<T>::value>::type> {\npublic:\n    explicit unsigned_leb128(T in) {\n        while (in > 0) {\n            auto byte = gsl::narrow_cast<uint8_t>(in & 0x7full);\n            in >>= 7;\n\n            // In has more data?\n            if (in > 0) {\n                byte |= 0x80;\n                encodedData[encodedSize - 1] = byte;\n                // Increase the size\n                encodedSize++;\n            } else {\n                encodedData[encodedSize - 1] = byte;\n            }\n        }\n    }\n\n    cb::const_byte_buffer get() const {\n        return {encodedData.data(), encodedSize};\n    }\n\n    const uint8_t* begin() const {\n        return encodedData.data();\n    }\n\n    const uint8_t* end() const {\n        return encodedData.data() + encodedSize;\n    }\n\n    const uint8_t* data() const {\n        return encodedData.data();\n    }\n\n    size_t size() const {\n        return encodedSize;\n    }\n\n    constexpr static size_t getMaxSize() {\n        return maxSize;\n    }\n\n    /**\n     * decode returns the decoded T and a const_byte_buffer initialised with the\n     * data following the leb128 data.\n     *\n     * @param buf buffer containing a leb128 encoded value (of size T). This can\n     *            be a prefix on some other data, the decode will only process\n     *            up to the maximum number of bytes permitted for the type T.\n     *            E.g. uint32_t use 5 bytes maximum. buf.size must be >= 1\n     *\n     * @returns A std::pair where first is the decoded value and second is a\n     *          buffer initialised with the data following the leb128 data. Note\n     *          if the input buf was 100% only a leb128, the returned buffer\n     *          will point outside of the input buf, but size will be 0.\n     *\n     * @throws std::invalid_argument if the input is not a valid leb128, this\n     *         means decode processed 'getMaxSize' bytes without a stop byte.\n     */\n    static std::pair<T, cb::const_byte_buffer> decode(\n            cb::const_byte_buffer buf);\n\n    /**\n     * decodeCanonical returns the decoded value of type T and a\n     * const_byte_buffer initialised with the data following the leb128 data.\n     *\n     * This version does not throw an exception, but returns failure for two\n     * reasons.\n     *  - no-stop byte found\n     *  - non-canonical encoding was used, e.g. 0x81.00 instead of 0x01\n     *\n     * The caller will have to inspect the input to determine the error.\n     *\n     * @param buf buffer containing a leb128 encoded value (of size T). This can\n     *            be a prefix on some other data, the decode will only process\n     *            up to the maximum number of bytes permitted for the type T.\n     *            E.g. uint32_t use 5 bytes maximum. buf.size must be >= 1\n     *\n     * @returns On error a std::pair where the second buffer has a nullptr and\n     *          zero size, first is set to 0. On success a std::pair where first\n     *          is the decoded value and second is a buffer initialised with the\n     *          data following the leb128 data. Note if the input buf was 100%\n     *          only a leb128, the returned buffer will point outside of the\n     *          input buf, but size will be 0.\n     */\n    static std::pair<T, cb::const_byte_buffer> decodeCanonical(\n            cb::const_byte_buffer buf);\n\n    /**\n     * decodeNoThrow returns the decoded value of type T and a const_byte_buffer\n     * initialised with the data following the leb128 data.\n     *\n     * This version does not throw an exception, but returns failure if no-stop\n     * is byte found.\n     *\n     * @param buf buffer containing a leb128 encoded value (of size T). This can\n     *            be a prefix on some other data, the decode will only process\n     *            up to the maximum number of bytes permitted for the type T.\n     *            E.g. uint32_t use 5 bytes maximum. buf.size must be >= 1\n     *\n     * @returns On error a std::pair where the second buffer has a nullptr and\n     *          zero size, first is set to 0. On success a std::pair where first\n     *          is the decoded value and second is a buffer initialised with the\n     *          data following the leb128 data. Note if the input buf was 100%\n     *          only a leb128, the returned buffer will point outside of the\n     *          input buf, but size will be 0.\n     */\n    static std::pair<T, cb::const_byte_buffer> decodeNoThrow(\n            cb::const_byte_buffer buf);\n\nprotected:\n    struct NoThrow {};\n    /**\n     * decode returns the decoded value of type T and a const_byte_buffer\n     * initialised with the data following the leb128 data.\n     *\n     * This is the protected inner method used by the public decode, does not\n     * throw for bad input (allows public methods to decide error fate)\n     */\n    static std::pair<T, cb::const_byte_buffer> decode(cb::const_byte_buffer buf,\n                                                      NoThrow);\n\n    template <typename, typename>\n    friend class unsigned_leb128;\n\n    /**\n     * Test that a decoded value was encoded in the canonical format.\n     *\n     * The test works by examining the length and comparing against a constant.\n     * The constant is the maximum value that can be encoded as leb128 in\n     * 'encodedLength - 1' bytes.\n     *\n     * For example if the encodedLength was 2 and the value was less than or\n     * equal to 127, a non-canonical encoding was used, 127 and less can and\n     * must be encoded in only 1 byte.\n     *\n     * So the test when encoded length is 2 is that the value is greater than\n     * 127. If the encoded length is 3 the value must be greater than 16383 and\n     * so on.\n     *\n     * @param value The integer that was decoded\n     * @param encodedLength How many bytes the leb128 encoding used\n     */\n    static inline bool is_canonical(uint64_t value, size_t encodedLength);\n\nprivate:\n    // Larger T may need a larger array\n    static_assert(sizeof(T) <= 8, \"Class is only valid for uint 8/16/64\");\n\n    // value is large enough to store ~0 as leb128\n    static constexpr size_t maxSize = sizeof(T) + (((sizeof(T) + 1) / 8) + 1);\n    std::array<uint8_t, maxSize> encodedData{};\n    uint8_t encodedSize{1};\n};\n\n// Generate the maximum value that can be encoded in nbytes\n#define MAX_LEB128(nbytes) \\\n    ((0x7full << ((nbytes - 1) * 7)) | ((1ull << ((nbytes - 1) * 7)) - 1ull))\n\ntemplate <>\ninline bool unsigned_leb128<uint8_t>::is_canonical(uint64_t value,\n                                                   size_t encodedLength) {\n    return (encodedLength == 2 && value > MAX_LEB128(1)) || encodedLength == 1;\n}\n\ntemplate <>\ninline bool unsigned_leb128<uint16_t>::is_canonical(uint64_t value,\n                                                    size_t encodedLength) {\n    if (unsigned_leb128<uint8_t>::is_canonical(value, encodedLength)) {\n        return true;\n    }\n    return encodedLength == 3 && value > MAX_LEB128(2);\n}\n\ntemplate <>\ninline bool unsigned_leb128<uint32_t>::is_canonical(uint64_t value,\n                                                    size_t encodedLength) {\n    if (unsigned_leb128<uint16_t>::is_canonical(value, encodedLength)) {\n        return true;\n    }\n\n    switch (encodedLength) {\n    case 4:\n        return value > MAX_LEB128(3);\n    case 5:\n        return value > MAX_LEB128(4);\n    }\n\n    return false;\n}\n\ntemplate <>\ninline bool unsigned_leb128<uint64_t>::is_canonical(uint64_t value,\n                                                    size_t encodedLength) {\n    // We first have to ask if this is non-canonical for the lower size, e.g.\n    // u32. Each size asks the lower size first.\n    if (unsigned_leb128<uint32_t>::is_canonical(value, encodedLength)) {\n        return true;\n    }\n\n    switch (encodedLength) {\n    case 6:\n        return value > MAX_LEB128(5);\n    case 7:\n        return value > MAX_LEB128(6);\n    case 8:\n        return value > MAX_LEB128(7);\n    case 9:\n        return value > MAX_LEB128(8);\n    case 10:\n        return value > MAX_LEB128(9);\n    }\n\n    return false;\n}\n\ntemplate <class T>\nstd::pair<T, cb::const_byte_buffer>\nunsigned_leb128<T, typename std::enable_if<std::is_unsigned<T>::value>::type>::\n        decode(cb::const_byte_buffer buf, NoThrow) {\n    T rv = buf[0] & 0x7full;\n    size_t end = 0;\n    // Process up to the end of buf, or the max size for T, this ensures that\n    // bad input, e.g. no stop-byte avoids invalid shifts (where shift just\n    // keeps getting better). Primarily this gives us much better control over\n    // invalid input, e.g. 20 bytes of 0x80 with a stop byte, would of\n    // previously decoded to 0, but is really not valid input.\n    size_t size =\n            std::min(buf.size(), cb::mcbp::unsigned_leb128<T>::getMaxSize());\n    if ((buf[0] & 0x80) == 0x80ull) {\n        T shift = 7;\n        // shift in the remaining data\n        for (end = 1; end < size; end++) {\n            rv |= (buf[end] & 0x7full) << shift;\n            if ((buf[end] & 0x80ull) == 0) {\n                break; // no more\n            }\n            shift += 7;\n        }\n        // We should of stopped for a stop byte, not the end of the buffer or\n        // max encoding\n        if (end == size) {\n            return {0, cb::const_byte_buffer{}};\n        }\n    }\n    // Return the decoded value and a buffer for any remaining data\n    return {rv,\n            cb::const_byte_buffer{buf.data() + end + 1,\n                                  buf.size() - (end + 1)}};\n}\n\ntemplate <class T>\nstd::pair<T, cb::const_byte_buffer>\nunsigned_leb128<T, typename std::enable_if<std::is_unsigned<T>::value>::type>::\n        decode(cb::const_byte_buffer buf) {\n    if (buf.size() > 0) {\n        auto rv = unsigned_leb128<T>::decode(buf, NoThrow{});\n        if (rv.second.data()) {\n            return rv;\n        }\n    }\n    throw std::invalid_argument(\n            \"`unsigned_leb128::decode invalid leb128 of size:\" +\n            std::to_string(buf.size()));\n}\n\ntemplate <class T>\nstd::pair<T, cb::const_byte_buffer>\nunsigned_leb128<T, typename std::enable_if<std::is_unsigned<T>::value>::type>::\n        decodeCanonical(cb::const_byte_buffer buf) {\n    auto rv = unsigned_leb128<T>::decode(buf, NoThrow{});\n\n    if (rv.second.data() &&\n        !is_canonical(rv.first, size_t(rv.second.data() - buf.data()))) {\n        return {0, cb::const_byte_buffer{}};\n    }\n\n    return rv;\n}\n\ntemplate <class T>\nstd::pair<T, cb::const_byte_buffer>\nunsigned_leb128<T, typename std::enable_if<std::is_unsigned<T>::value>::type>::\n        decodeNoThrow(cb::const_byte_buffer buf) {\n    return unsigned_leb128<T>::decode(buf, NoThrow{});\n}\n\n/**\n * @return a buffer to the data after the leb128 prefix\n */\ntemplate <class T>\ntypename std::enable_if<std::is_unsigned<T>::value, cb::const_byte_buffer>::type\nskip_unsigned_leb128(cb::const_byte_buffer buf) {\n    return unsigned_leb128<T>::decode(buf).second;\n}\n\n/// @return the index of the stop byte within buf\nstatic inline std::optional<size_t> unsigned_leb128_get_stop_byte_index(\n        cb::const_byte_buffer buf) {\n    // If buf does not contain a stop-byte, invalid\n    size_t stopByte = 0;\n    for (auto c : buf) {\n        if ((c & 0x80ull) == 0) {\n            return stopByte;\n        }\n        stopByte++;\n    }\n    return {};\n}\n\n} // namespace cb::mcbp\n", "meta": {"hexsha": "c17bc6032735c037ab7049fa1b90a6a3bc9d1a4b", "size": 12427, "ext": "h", "lang": "C", "max_stars_repo_path": "include/mcbp/protocol/unsigned_leb128.h", "max_stars_repo_name": "nawazish-couchbase/kv_engine", "max_stars_repo_head_hexsha": "132f1bb04c9212bcac9e401d069aeee5f63ff1cd", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": 104.0, "max_stars_repo_stars_event_min_datetime": "2017-05-22T20:41:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T00:18:34.000Z", "max_issues_repo_path": "include/mcbp/protocol/unsigned_leb128.h", "max_issues_repo_name": "nawazish-couchbase/kv_engine", "max_issues_repo_head_hexsha": "132f1bb04c9212bcac9e401d069aeee5f63ff1cd", "max_issues_repo_licenses": ["MIT", "BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-11-14T08:12:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T11:14:17.000Z", "max_forks_repo_path": "include/mcbp/protocol/unsigned_leb128.h", "max_forks_repo_name": "nawazish-couchbase/kv_engine", "max_forks_repo_head_hexsha": "132f1bb04c9212bcac9e401d069aeee5f63ff1cd", "max_forks_repo_licenses": ["MIT", "BSD-3-Clause"], "max_forks_count": 71.0, "max_forks_repo_forks_event_min_datetime": "2017-05-22T20:41:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T10:34:32.000Z", "avg_line_length": 35.5057142857, "max_line_length": 80, "alphanum_fraction": 0.6142270862, "num_tokens": 3145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31742627850202554, "lm_q2_score": 0.031143831658843567, "lm_q1q2_score": 0.009885870581760279}}
{"text": "/**\n * Subroutines used mostly for working on catalogs\n * in the tasks SEX2GOL and GOL2AF.\n *\n * Howard Bushouse, STScI, 04-Mar-2011, version 1.4\n * Changed FATAL error to WARN3 when get_valid_entries returns no valid\n * magnitudes for an object.\n *\n */\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_interp.h>\n\n#include \"aXe_utils.h\"\n#include \"aXe_grism.h\"\n#include \"spc_cfg.h\"\n#include \"disp_conf.h\"\n#include \"aper_conf.h\"\n#include \"trace_conf.h\"\n#include \"spc_CD.h\"\n#include \"spc_wl_calib.h\"\n#include \"aper_conf.h\"\n#include \"specmodel_utils.h\"\n#include \"model_utils.h\"\n#include \"spc_fluxcube.h\"\n#include \"spc_model.h\"\n#include \"crossdisp_utils.h\"\n#include \"spc_utils.h\"\n#include \"spc_sex.h\"\n\n// define SQUARE\n#define SQR(x) ((x)*(x))\n\n/**\n *\n *  Function: create_SexObject\n *  Allocates and creates a SExtractor object from\n *  a line of a SExtractor catalog.\n *\n *  Parameters:\n *  @param  actinfo  - the header structure with the column names\n *  @param  line     - the line to be transformed into a SexObject\n *  @param  waves    - vector with the walelengths of the magnitude columns\n *  @param  cnums    - vector with the column numbers of the magnitude columns\n *  @param  magcol   - column number of the magnitude column selected\n *                     for mag_auto\n *  @param  fullinfo - deecides whether a column is optional or not\n *\n *  Returns:\n *  @return o        - the new created SexObject\n */\nSexObject *\ncreate_SexObject(const colinfo *actinfo, char *line, const gsl_vector * waves,\n                 const gsl_vector *  cnums, const px_point backwin_cols,\n                 const px_point modinfo_cols, const int magcol, const int fullinfo)\n{\n  gsl_vector *v;\n  gsl_vector *mags;\n  gsl_vector *wavs;\n  SexObject  *o;\n  int         i=0;\n  // transform the data in the line to a vector\n  lv1ws (line);\n  v = string_to_gsl_array (line);\n\n  // allocate space for the SexObject\n  o = (SexObject *) malloc (sizeof (SexObject));\n  if (o == NULL)\n    aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n                 \"create_SexObject: Could not allocate memory.\");\n\n  // succesively fill the data into the SexObject.\n  // for 'fullinfo=1' missing data results in an error.\n  // otherwise NaN is stored into the SexObject\n  o->number = (int) get_col_value (actinfo, \"NUMBER\", v, 1);\n\n  o->xy_image.x     = get_col_value (actinfo, \"X_IMAGE\", v,fullinfo);\n  o->xy_image.y     = get_col_value (actinfo, \"Y_IMAGE\", v,fullinfo);\n\n  o->xy_world.ra    = get_col_value (actinfo, \"X_WORLD\", v,1);\n  o->xy_world.dec   = get_col_value (actinfo, \"Y_WORLD\", v,1);\n\n  o->el_image.a     = get_col_value (actinfo, \"A_IMAGE\", v,fullinfo);\n  o->el_image.b     = get_col_value (actinfo, \"B_IMAGE\", v,fullinfo);\n  o->el_image.theta = get_col_value (actinfo, \"THETA_IMAGE\", v,fullinfo);\n\n  o->el_world.a     = get_col_value (actinfo, \"A_WORLD\", v,1);\n  o->el_world.b     = get_col_value (actinfo, \"B_WORLD\", v,1);\n\n  // Some clarification is needed for the next two lines.\n  // to have get_col_value and get_col_value2 is not\n  // satisfying!! PROBLEM\n  o->el_world.theta = get_col_value2 (actinfo, \"THETA_WORLD\", v,0);\n  if (o->el_world.theta <-900000){\n    //  o->el_world.theta = get_col_value (actinfo, \"THETA_WORLD\", v,0);\n    //  if (isnan(o->el_world.theta)){\n    o->el_world.theta = get_col_value (actinfo, \"THETA_SKY\", v,1);\n  }\n\n  if (backwin_cols.x !=-1)\n    {\n      o->backwindow.x  = get_col_value (actinfo, \"BACKWINDOW\", v,1);\n      o->backwindow.y  = -1;\n      // old code for FORS2-MXU\n      // o->backwindow.y     = get_col_value (actinfo, \"BACKWIN_LOW\", v,1);\n\n    }\n  else\n    {\n      o->backwindow.x     = -1;\n      o->backwindow.y     = -1;\n    }\n\n  // transfer the index for the model spectrum\n  if (modinfo_cols.x > -1)\n    o->modspec = (int)get_col_value(actinfo, \"MODSPEC\", v,1);\n  else\n    o->modspec = -1;\n\n  // transfer the index value for the object shape\n  if (modinfo_cols.y > -1)\n    o->modimage = (int)get_col_value(actinfo, \"MODIMAGE\", v,1);\n  else\n    o->modimage = -1;\n\n  // check whether the MAG_AUTO column exists\n  if ((int)waves->size == 1 && (int)gsl_vector_get (waves, 0) == 0)\n    {\n\n\n      // fill the MAG_AUTO value\n      // put the magnitude and wavelength vectors to NULL\n      o->magnitudes = NULL;\n      o->lambdas    = NULL;\n      o->mag_auto   = get_col_value (actinfo, \"MAG_AUTO\", v, 1);\n    }\n  else\n    {\n      // create the vectors for the magnitude values\n      mags = gsl_vector_alloc ((int)waves->size);\n      wavs = gsl_vector_alloc ((int)waves->size);\n\n      // fill the magnitude values into the vectors and store them in\n      // the SexObject.\n      for (i=0; i < (int)waves->size; i++){\n        gsl_vector_set(mags, i, gsl_vector_get (v, (int)gsl_vector_get (cnums, i)-1));\n        gsl_vector_set(wavs, i, gsl_vector_get (waves, i));\n      }\n\n      // fill the MAG_AUTO value\n      o->magnitudes = mags;\n      o->lambdas    = wavs;\n      o->mag_auto   = gsl_vector_get (v, magcol-1);\n    }\n\n  return o;\n}\n\n\n/**\n *  Function: SexObject_fprintf\n *  Function to print the attributes of a SexObbject\n *  to an output stream.\n *\n *  Paramters:\n *  @param output - an ouput file or stream\n *  @param o      - a pointer to a SexObject\n */\nvoid\nSexObject_fprintf (FILE * output, SexObject * o)\n{\n     fprintf (output, \"NUMBER: %d\\n\", o->number);\n\n     fprintf (output, \"X_IMAGE: %e\\n\", o->xy_image.x);\n     fprintf (output, \"Y_IMAGE: %e\\n\", o->xy_image.y);\n\n     fprintf (output, \"X_WORLD: %e\\n\", o->xy_world.ra);\n     fprintf (output, \"Y_WORLD: %e\\n\", o->xy_world.dec);\n\n     fprintf (output, \"A_IMAGE: %e\\n\", o->el_image.a);\n     fprintf (output, \"B_IMAGE: %e\\n\", o->el_image.b);\n     fprintf (output, \"THETA_IMAGE: %e\\n\", o->el_image.theta);\n\n     fprintf (output, \"A_WORLD: %e\\n\", o->el_world.a);\n     fprintf (output, \"B_WORLD: %e\\n\", o->el_world.b);\n     fprintf (output, \"THETA_WORLD: %e\\n\", o->el_world.theta);\n\n     fprintf (output, \"MAG_AUTO: %e\\n\", o->mag_auto);\n\n}\n\n\n/**\n *  Function: sobs_to_vout\n *  The function transforms a SexObject into\n *  a vector.\n *\n *  Parameters:\n *  @param  sobs - the SexObject to be transformed\n *\n *  Returns:\n *  @return vout - the vector with the Seobject data\n */\ngsl_vector *\nsobs_to_vout(const SexObject *sobs)\n{\n\n  int nentries, i;\n  int count=0;\n\n  // determine the size of the vector\n  if (sobs->magnitudes){\n    nentries = 11+sobs->magnitudes->size;\n  }\n  else{\n    nentries = 12;\n  }\n\n  if(sobs->backwindow.x != -1)\n    nentries = nentries+1;\n    // old FORS2-MXU code:\n    //nentries = nentries+2;\n\n  if(sobs->modspec != -1)\n    nentries++;\n  if(sobs->modimage != -1)\n    nentries++;\n\n  // allocate space for the vector\n  gsl_vector *vout = gsl_vector_alloc (nentries);\n\n  // fill the vector\n  gsl_vector_set (vout, count++, sobs->number);\n  gsl_vector_set (vout, count++, sobs->xy_world.ra);\n  gsl_vector_set (vout, count++, sobs->xy_world.dec);\n  gsl_vector_set (vout, count++, sobs->el_world.a);\n  gsl_vector_set (vout, count++, sobs->el_world.b);\n  gsl_vector_set (vout, count++, sobs->el_world.theta);\n  gsl_vector_set (vout, count++, sobs->xy_image.x);\n  gsl_vector_set (vout, count++, sobs->xy_image.y);\n  gsl_vector_set (vout, count++, sobs->el_image.a);\n  gsl_vector_set (vout, count++, sobs->el_image.b);\n  gsl_vector_set (vout, count++, sobs->el_image.theta);\n\n  if(sobs->backwindow.x != -1)\n    {\n      gsl_vector_set (vout, count++, sobs->backwindow.x);\n      // old code for FORS2-MXU\n      //gsl_vector_set (vout, count++, sobs->backwindow.y);\n    }\n\n  if(sobs->modspec != -1)\n      gsl_vector_set (vout, count++, sobs->modspec);\n\n  if(sobs->modimage != -1)\n      gsl_vector_set (vout, count++, sobs->modimage);\n\n  // see whether there is MAG_AUTO\n  if (sobs->magnitudes){\n    // fill in the magnitude values\n    for (i=0; i < (int)sobs->magnitudes->size; i++)\n      gsl_vector_set (vout, count++, gsl_vector_get(sobs->magnitudes, i));\n  }\n  else{\n    // fill in the MAG_AUTO value\n    gsl_vector_set (vout, count++, sobs->mag_auto);\n  }\n\n  // return the vector\n  return vout;\n}\n\n/**\n *  Function: catalog_to_wcs\n *  This function reads a sextractor catalog and using an input and an output\n *  CD matrix, converts the world ra and dec coordinates to the output CD\n *  matrix's image pixel coordinates. Non existing (i.e. NaN) world RA and\n *  DEC values are generated using\n *  the pixel coordinates and the input CD matrix\n *\n *  Parameters:\n *  @param - infile a pointer to a char array containing the name of the\n *         input catalog\n *  @param - outfile a pointer to a char array containing the name of the\n *         output catalog\n *  @param - from_wcs a pointer to an exisiting WoldCoor structure containing\n *         the input catalog CD matrix\n *  @param - to_wcs a pointer to an exisiting WoldCoor structure containing\n *         the output catalog CD matrix\n *  @param - overwrite_wcs if set to 1 then input wold coordinate are\n *         recomputed first using the from_wcs and the x,y image values\n *  @param - overwrite_img if set to 1 then the x,y coordinates of the input\n *         image are first computed using the from_wcs and the\n *          world ra and dec info\n */\nvoid\ncatalog_to_wcs (char grismfile[], int hdunum, char infile[], char outfile[],\n                struct WorldCoor *from_wcs, struct WorldCoor *to_wcs,\n                int distortion, int overwrite_wcs, int overwrite_img)\n{\n  FILE *fin, *fout;\n  gsl_vector *v;\n  gsl_vector *v_out;\n  gsl_vector *waves;\n  gsl_vector *cnums;\n  gsl_matrix *coeffs=NULL;\n  char Buffer[CATBUFFERSIZE];\n  char line[CATBUFFERSIZE], str[CATBUFFERSIZE];\n  int i, hasmags=0, magcencol = 0;\n  SexObject *o;\n  colinfo * actcatinfo;\n  px_point    pixmax;\n  px_point    backwin_cols;\n  px_point    modinfo_cols;\n\n\n  actcatinfo = get_sex_col_descr (infile);\n  hasmags = has_magnitudes(actcatinfo);\n  if (!hasmags)\n    {\n      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n                   \"No magnitudes in file %s\", infile);\n    }\n  else{\n    waves = gsl_vector_alloc (hasmags);\n    cnums = gsl_vector_alloc (hasmags);\n    hasmags = get_magcols(actcatinfo, waves, cnums);\n    magcencol = get_magauto_col(waves, cnums, 800.0);\n  }\n\n  backwin_cols = has_backwindow(actcatinfo);\n  modinfo_cols = has_modelinfo(actcatinfo);\n\n\n  if (!(fin = fopen (infile, \"r\")))\n    {\n      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n                   \"Cannot open catalog file %s\", infile);\n    }\n  if (!(fout = fopen (outfile, \"w\")))\n    {\n      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n                   \"Cannot open catalog file %s\", outfile);\n    }\n\n  if (check_worldcoo_input(actcatinfo, 0))\n    aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n                 \"Catalogue %s does not have all WCO columns\\n\", infile);\n\n  if (check_imagecoo_input(actcatinfo))\n    aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n                 \"Catalogue %s does not have all image coo columns\\n\", infile);\n\n  make_GOL_header(fout, actcatinfo, waves, cnums, backwin_cols, modinfo_cols);\n\n  if (distortion)\n    coeffs = get_crossdisp_matrix(grismfile, hdunum);\n\n  pixmax = get_npixels (grismfile, hdunum);\n\n  while (fgets (line, CATBUFFERSIZE, fin))\n    {\n      if (!(line_is_valid (actcatinfo, line)))\n        continue;\n       if (line[0] == ';')\n         continue;\n\n      /* Create a vector containing the information */\n      lv1ws (line);\n      v = string_to_gsl_array (line);\n\n      //      o = create_SexObject (sex_col_desc, line);\n      o = create_SexObject (actcatinfo, line, waves, cnums, backwin_cols, modinfo_cols, magcencol,  1);\n\n      if ( (from_wcs!=NULL)&&(to_wcs!=NULL) )\n        {\n          //      if (distortion){\n          //        fprintf(stdout, \"(%f,%f) &&-->&& \", o->xy_image.x, o->xy_image.y);\n          //        o->xy_image = undistort_point(coeffs, pixmax, o->xy_image);\n          //      }\n          fill_missing_WCS_coordinates (o, from_wcs, overwrite_wcs);\n          fill_missing_image_coordinates (o, from_wcs, overwrite_img);\n          compute_new_image_coordinates (o, to_wcs);\n          if (distortion){\n            o->xy_image = distort_point(coeffs, pixmax, o->xy_image);\n            //      fprintf(stdout, \"(%f,%f)\\n\\n\", o->xy_image.x, o->xy_image.y);\n          }\n        }\n\n      v_out = sobs_to_vout(o);\n\n      sprintf (Buffer, \"%8.5g \", gsl_vector_get (v_out, 0));\n      for (i = 1; i < (int)v_out->size; i++)\n        {\n          sprintf (str, \" %8.5g \", gsl_vector_get (v_out, i));\n          strcat (Buffer, str);\n        }\n      strcat (Buffer, \"\\n\");\n\n      fputs (Buffer, fout);\n\n      gsl_vector_free (v_out);\n      gsl_vector_free (v);\n  }\n\n  if (coeffs)\n    gsl_matrix_free(coeffs);\n\n  fclose (fin);\n  fclose (fout);\n}\n\n/**\n * Function:catalog_to_wcs_nodim\n * This function reads a sextractor catalog and using an input and an output\n * CD matrix, converts the world ra and dec coordinates to the output\n * CD matrix's image pixel coordinates. Non existing (i.e. NaN) world RA\n * and DEC values are generated using the pixel coordinates and the input\n * CD matrix\n *\n * Parameters:\n * @param infile    - a pointer to a char array containing the name of the\n *                    input catalog\n * @param outfile   - a pointer to a char array containing the name of the\n *                    output catalog\n * @param from_wcs  - a pointer to an exisiting WoldCoor structure containing\n *                    the input catalog CD matrix\n * @param to_wcs    - a pointer to an exisiting WoldCoor structure\n *                    containing the output catalog CD matrix\n * @param overwrite_wcs - if set to 1 then input wold coordinate are\n *                        recomputed first using the from_wcs and the\n *                        x,y image values\n * @param overwrite_img - if set to 1 then the x,y coordinates of the\n *                        input image are first computed using the\n *                        from_wcs and the world ra and dec info\n */\nvoid\ncatalog_to_wcs_nodim (char infile[], char outfile[],\n                      struct WorldCoor *grism_wcs, int overwrite_wcs,\n                      int overwrite_img)\n{\n  FILE *fin, *fout;\n  gsl_vector *v;\n  gsl_vector *v_out;\n  gsl_vector *waves;\n  gsl_vector *cnums;\n  char Buffer[CATBUFFERSIZE];\n  char line[CATBUFFERSIZE], str[CATBUFFERSIZE];\n  int i;\n  SexObject *o;\n  int compute_imcoos=0;\n  int th_sky=0;\n  int checksum, hasmags=0, magcencol=0;\n  colinfo * actcatinfo;\n  px_point    backwin_cols;\n  px_point    modinfo_cols;\n\n  actcatinfo = get_sex_col_descr (infile);\n  hasmags = has_magnitudes(actcatinfo);\n  if (!hasmags)\n    {\n      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n                   \"No magnitudes in file %s\", infile);\n    }\n  else{\n    waves = gsl_vector_alloc (hasmags);\n    cnums = gsl_vector_alloc (hasmags);\n    hasmags = get_magcols(actcatinfo, waves, cnums);\n    magcencol = get_magauto_col(waves, cnums, 800.0);\n  }\n\n  backwin_cols = has_backwindow(actcatinfo);\n  modinfo_cols = has_modelinfo(actcatinfo);\n\n  if (!(fin = fopen (infile, \"r\")))\n    {\n      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n                   \"Cannot open catalog file %s\", infile);\n    }\n  if (!(fout = fopen (outfile, \"w\")))\n    {\n      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n                   \"Cannot open catalog file %s\", outfile);\n    }\n\n  //  checksum = check_worldcoo_input(sex_col_desc);\n  th_sky=1;\n  checksum = check_worldcoo_input(actcatinfo, 1);\n  if (checksum)\n    aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n                 \"Catalogue %s does not have all necessary columns\\n\", infile);\n\n  //  if (check_imagecoo_input(sex_col_desc))\n  if (check_imagecoo_input(actcatinfo))\n    compute_imcoos=1;\n\n  make_GOL_header(fout, actcatinfo, waves, cnums, backwin_cols, modinfo_cols);\n\n  while (fgets (line, CATBUFFERSIZE, fin))\n    {\n\n      /* If line is not a valid catalog entry, just continue */\n      if (!(line_is_valid (actcatinfo, line)))\n        continue;\n\n      /* if line starts with \";\", just continue */\n      if (line[0] == ';')\n        continue;\n\n      /* Create a vector containing the information */\n      lv1ws (line);\n      v = string_to_gsl_array (line);\n\n      o = create_SexObject (actcatinfo, line, waves, cnums, backwin_cols, modinfo_cols, magcencol,  0);\n\n\n      if (compute_imcoos)\n        compute_new_image_sexobject (o, grism_wcs, th_sky);\n      v_out = sobs_to_vout(o);\n\n\n      sprintf (Buffer, \"%8.5g \", gsl_vector_get (v_out, 0));\n      for (i = 1; i < (int)v_out->size; i++)\n        {\n          sprintf (str, \" %8.5g \", gsl_vector_get (v_out, i));\n          strcat (Buffer, str);\n        }\n      strcat (Buffer, \"\\n\");\n\n      fputs (Buffer, fout);\n\n      gsl_vector_free (v_out);\n      gsl_vector_free (v);\n    }\n\n  fclose (fin);\n  fclose (fout);\n\n  free (actcatinfo);\n\n}\n\n/**\n * Function: SexMags_to_beamFlux\n * Fill an beam structure with the flux and shape information information\n * contained in a SexObject structure.\n *\n * Parameters:\n * @param sobj     - pointer to a  SexObject\n * @param actbeam  - the beam structure to be filled\n *\n * Returns:\n * @return -\n */\nvoid\nSexMags_to_beamFlux(SexObject * sobj, beam *actbeam)\n  {\n    int nvalid=0;\n    int jj=0;\n    int j=0;\n\n    double fval=0.0;\n\n    gsl_vector *flux;\n\n    // set 'default' shapes\n    actbeam->awidth  = -1.0;\n    actbeam->bwidth  = -1.0;\n    actbeam->aorient = -1.0;\n\n    // set a 'default' flux\n    actbeam->flux = NULL;\n\n    /* if flux/wavelength information exists */\n    if (sobj->magnitudes)\n      {\n\n        // get the number of valid entries in 'sobj->magnitudes'\n        nvalid = get_valid_entries(sobj->magnitudes);\n        if (!nvalid)\n          aXe_message (aXe_M_WARN3, __FILE__, __LINE__,\n                       \"No valid magnitude for object %i !\\n\", sobj->number);\n\n        // allocate the flux vector\n        flux = gsl_vector_alloc (2*(nvalid));\n\n        // initialize a counter\n        jj=0;\n\n        //  go over all magnidute values\n        for (j=0; j < (int)sobj->magnitudes->size; j++)\n          {\n            // check whether the current entry is valid\n            if (is_valid_entry(gsl_vector_get(sobj->magnitudes, j)))\n              {\n                // get the current entry, already converted to flux\n                fval = get_flambda_from_magab(gsl_vector_get(sobj->magnitudes, j), gsl_vector_get(sobj->lambdas, j));\n\n                // set the wavelength value and the flux value\n                gsl_vector_set(flux, 2*jj, gsl_vector_get(sobj->lambdas, j));\n                gsl_vector_set(flux, 2*jj+1, fval);\n\n                // enhance the counter\n                jj++;\n              }\n          }\n\n        // transfer the flux values\n        // to the beam\n        actbeam->flux = flux;\n\n        // transfer the shape values\n        // to the beam\n        actbeam->awidth  = sobj->el_image.a;\n        actbeam->bwidth  = sobj->el_image.b;\n        actbeam->aorient = sobj->el_image.theta;\n      }\n  }\n\n/**\n * Function: SexObject_to_slitgeom\n * Fill a beam structure with the optimized geometry information.\n * The quantities are computed from the object shape and\n * the trace angle.\n *\n * Parameters:\n * @param sobj        - pointer to a  SexObject\n * @param trace_angle - pointer to a  SexObject\n * @param actbeam     - the beam structure to be filled\n *\n * Returns:\n * @return -\n */\nvoid\nSexObject_to_slitgeom(const aperture_conf *conf, const SexObject * sobj,\n                      const double trace_angle, beam *actbeam)\n  {\n    double theta=0.0;\n    double orient=0.0;\n    double tmp_angle, cos_tmp_angle;\n    double A11, A12, A22;\n\n    d_point obj_size;\n\n    // convert the SExtractor angle to rad in the right quadrant\n    orient = (180.0 + sobj->el_image.theta) / 180.0 * M_PI;\n    while (orient > M_PI)\n      orient = orient - M_PI;\n\n    // compute angle between object\n    // orientation and trace\n    theta = orient - trace_angle;\n\n    // check the object size, possibly setting\n    // it to the size of point-like object\n    obj_size = check_object_size(conf, sobj, actbeam->ID);\n\n    /*\n    // determine the three matrix elements\n    A11 = SQR(cos(theta) / sobj->el_image.a) + SQR(sin(theta) / sobj->el_image.b);\n    A12 = cos(theta) * sin(theta) * (1.0/(SQR(sobj->el_image.a)) - 1.0/SQR(sobj->el_image.b));\n    A22 = SQR(sin(theta) / sobj->el_image.a) + SQR(cos(theta) / sobj->el_image.b);\n\n    // compute a temporary angle\n    // and its cosine\n    tmp_angle     = atan(A12 / A11);\n    cos_tmp_angle = cos(tmp_angle);\n\n    // compute the slit length\n    if (cos_tmp_angle > 0.01)\n      actbeam->slitgeom[0] = sqrt(A11)*sobj->el_image.a*sobj->el_image.b / cos_tmp_angle;\n    else\n      actbeam->slitgeom[0] = sqrt(A11)*sobj->el_image.a*sobj->el_image.b / 0.01;\n\n    // compute the slit orientation\n    actbeam->slitgeom[1] = tmp_angle + trace_angle + M_PI_2;\n\n    // compute the slit length\n    actbeam->slitgeom[2] = 1.0 / sqrt(A11);\n\n    // compute a modified B_IMAGE value, defined to keep the object area constant\n    actbeam->slitgeom[3] = sobj->el_image.a*sobj->el_image.b / actbeam->slitgeom[0];\n    */\n\n    // determine the three matrix elements\n    A11 = SQR(cos(theta) / obj_size.x) + SQR(sin(theta) / obj_size.y);\n    A12 = cos(theta) * sin(theta) * (1.0/(SQR(obj_size.x)) - 1.0/SQR(obj_size.y));\n    A22 = SQR(sin(theta) / obj_size.x) + SQR(cos(theta) / obj_size.y);\n\n    // compute a temporary angle\n    // and its cosine\n    tmp_angle     = atan(A12 / A11);\n    cos_tmp_angle = cos(tmp_angle);\n\n    // compute the slit length\n    if (cos_tmp_angle > 0.01)\n      actbeam->slitgeom[0] = sqrt(A11)*obj_size.x*obj_size.y / cos_tmp_angle;\n    else\n      actbeam->slitgeom[0] = sqrt(A11)*obj_size.x*obj_size.y / 0.01;\n\n    // compute the slit orientation\n    actbeam->slitgeom[1] = tmp_angle + trace_angle + M_PI_2;\n\n    // compute the slit width\n    actbeam->slitgeom[2] = 1.0 / sqrt(A11);\n\n    // compute a modified B_IMAGE value, defined to keep the object area constant\n    actbeam->slitgeom[3] = obj_size.x*obj_size.y / actbeam->slitgeom[0];\n  }\n\n/**\n * Function: fill_corner_ignore\n * The method computes and fills the beam corner information\n * and the the ignore flag into a beam structure.\n *\n * Parameters:\n * @param sobj     - pointer to a  SexObject\n * @param obs      - a pointer to the data array containing the image\n * @param conf     - pointer to the configuration structure\n * @param beamID   - the beam ID\n * @param dmag     - number of magnitudes to add to the magnitudes cutoffs\n * @param actbeam  - the beam structure to be filled\n *\n * Returns:\n * @return -\n */\nvoid\nfill_corner_ignore(SexObject * sobj, observation * const obs, aperture_conf *conf,\n                   int beamID, float dmag, beam *actbeam)\n  {\n    double mmag_extract;\n    double mmag_mark;\n\n    // get the extraction and the mark margnitudes\n    mmag_extract = conf->beam[beamID].mmag_extract + dmag;\n    mmag_mark    = conf->beam[beamID].mmag_mark    + dmag;\n\n    // make a default for the\n    // ignore flag\n    actbeam->ignore = 0;\n\n    /* magnitude cut */\n    // PROBLEM: there is a logical flaw inside\n    //          whhat happend when (mag > mag_mark) && (mag <  mmag_extract) ????\n    //          of course this has only relevance when mag_mark < mmag_extract\n    //      if ((sobj->mag_auto <= mmag_mark)&&(sobj->mag_auto <= mmag_extract))\n    // That's now an easy fix, but makes sense..\n    if (sobj->mag_auto <= mmag_extract)\n        actbeam->ignore = 0; // this object will be extracted\n\n    if ((sobj->mag_auto <= mmag_mark)&&(sobj->mag_auto > mmag_extract))\n        actbeam->ignore = 2; // this object will be not be extracted\n\n    if ((sobj->mag_auto > mmag_mark)&&(sobj->mag_auto > mmag_extract))\n        actbeam->ignore = 1; // this object will be ignored\n\n    // fill the boundary box values;\n    // returns if the beams is completely out of the image\n    if (!fill_object_bbox (obs, actbeam, 2, conf->beam[beamID].offset.dx0,\n                           conf->beam[beamID].offset.dx1))\n      actbeam->ignore = 1;\n  }\n\n/**\n * Function: set_extraction_parameters\n * The function computes and fills the extraction width and the\n * extraction orientation into a beam structure. Depending on the\n * input parameters and the object shape, different methods\n * are deployed.\n *\n * Parameters:\n * @param sobj     - pointer to a  SexObject\n * @param bck_mode - pointer for background mode\n * @param mfwhm    - the fwhm multiplicator constant to apply to\n *                   determine the width of the aperture box for the object.\n * @param dmag     - number of magnitudes to add to the magnitudes cutoffs\n * @param auto_reorient - if set then this task tries to optimize\n *                        the orientation of the\n *                        extraction slit - Should in general be left at 1 so that strange\n *                        geomety is avoided. If set to 2 the extraction is\n *                        forced to be vertical (90 deg.)\n * @param trace_angle - the trace angle\n * @param actbeam     - the beam structure to be filled\n *\n * Returns:\n * @return -\n */\nvoid\nset_extraction_parameters(SexObject * sobj, int bck_mode, float mfwhm,\n                          int auto_reorient, double trace_angle, beam *actbeam)\n  {\n    double orient;\n    double theta;\n    double theta_deg;\n    double trace_dist;\n    double dya;\n    double dyb;\n\n    //int iturn=0;\n\n    // convert the orientation to rad;\n    // turn into the right quadrant\n    orient = (180.0 + sobj->el_image.theta) / 180.0 * M_PI;\n    while (orient > M_PI)\n      orient = orient - M_PI;\n\n    // compute the relative between the trace angle\n    // and object orientation\n    theta = orient - trace_angle;\n\n    // convert theta to deg;\n    // convert it into the range:\n    // 0.0 < theta_deg < 180.0\n    theta_deg = theta / M_PI * 180.;\n    while (theta_deg < 0.0)\n      theta_deg += 180.0;\n    while (theta_deg > 180.0)\n      theta_deg -= 180.0;\n\n    // that's the 'normal', slanted extaction\n    if (auto_reorient == 0)\n      {\n        // take the major half axis value * mfwhm\n        // as width and its orientation\n        // as extraction direction\n        actbeam->width  = sobj->el_image.a * mfwhm;\n        actbeam->orient = orient;\n\n        // give a warning for small angles\n        // between the orientation direction and\n        // the trace angle.\n        if (fabs(theta_deg )< MIN_DIFFANGLE || fabs(theta_deg-180.0) < MIN_DIFFANGLE)\n          aXe_message (aXe_M_WARN4, __FILE__, __LINE__,\n                       \"aXe_GOL2AF: Object ID: %i : The angle between the extraction orientation and \"\n                       \"the trace is less than %5.2f degrees. You may get severe problems\"\n                       \" down to core dumps in the 1D extraction later on!\\n\", sobj->number, MIN_DIFFANGLE);\n      }\n    // thats the slanted, adjusted extraction\n    else if (auto_reorient == 1)\n      {\n        // use the optimized parameters\n        actbeam->width  = actbeam->slitgeom[0] * mfwhm;\n        actbeam->orient = actbeam->slitgeom[1];\n      }\n    // thats the perpendicular extraction\n    else if(auto_reorient == 2)\n      {\n        // extraction angle is prependicular to trace\n        actbeam->orient = trace_angle + M_PI_2;\n        if (mfwhm < 0.0)\n          {\n            // take the mfwhm value as width;\n            actbeam->width  = -1.0 * mfwhm;\n          }\n        else\n          {\n            // compute the projections of the major and minor\n            // half axis to the extraction direction\n            dya = fabs (sobj->el_image.a * sin (theta));\n            dyb = fabs (sobj->el_image.b * sin (M_PI_2 - theta));\n\n            // use the larger for extraction width\n            actbeam->width = mfwhm*MAX(dya,dyb);\n          }\n      }\n\n    // this piece of code was specifically added\n    // for NICMOS HLA, inorder to nelarge the background\n    // area around bright, point-like objects.\n    if (sobj->backwindow.x != -1 && bck_mode)\n      {\n        // compute the projected distance to the trace\n        trace_dist = sin(actbeam->orient - trace_angle) * actbeam->width;\n\n        // check whether the distance is too small\n        if (trace_dist < sobj->backwindow.x)\n          // elongate the width such that the projected distance\n          // equals the minimum value given in the SExobject\n          actbeam->width = sobj->backwindow.x / sin(actbeam->orient - trace_angle);\n      }\n  }\n\nd_point\ncheck_object_size(const aperture_conf *conf, const SexObject *sobj, const int beamID)\n  {\n    double obj_size = 0.0;\n\n    d_point ret;\n\n    // set the input values\n    // as default\n    ret.x = sobj->el_image.a;\n    ret.y = sobj->el_image.b;\n\n    // check whether a minimum\n    // size is defined\n    if (conf->pobjsize < 0.0)\n      // return the value\n      return ret;\n\n    // compute the object size\n    obj_size = sobj->el_image.a * sobj->el_image.b;\n\n    // check whether the object is point-like\n    if (obj_size < SQR(conf->pobjsize))\n      {\n        // transfer the point-like\n        // sizes to the return\n        ret.x = conf->pobjsize;\n        ret.y = conf->pobjsize;\n      }\n\n    // return the resulting\n    // object size\n    return ret;\n  }\n\n\n/**\n * Function: SexObject_to_beam\n * Fill an beam structure with the information contained in a SexObject\n * structure plus further information derived via the confiugration file.\n *\n * Parameters:\n * @param sobj     - pointer to a  SexObject\n * @param obs      - a pointer to the data array containing the image\n * @param conf     - pointer to the configuration structure\n * @param conffile - the name of the aperture configuration file\n * @param mfwhm    - the fwhm multiplicator constant to apply to\n *                   determine the width of the aperture box for the object.\n * @param dmag     - number of magnitudes to add to the magnitudes cutoffs\n * @param auto_reorient - if set then this task tries to optimize\n *                        the orientation of the\n *                        extraction slit - Should in general be left at 1 so that strange\n *                        geomety is avoided. If set to 2 the extraction is\n *                        forced to be vertical (90 deg.)\n * @param bck_mode - pointer for background mode\n * @param beamID   - the beam ID\n * @param actbeam  - the beam structure to be filled\n *\n * Returns:\n * @return -\n */\nvoid\nSexObject_to_beam(SexObject * sobj, observation * const obs, aperture_conf *conf,\n                  char conffile[], float mfwhm, float dmag, int auto_reorient,\n                  int bck_mode, int beamID, beam *actbeam)\n  {\n    double trace_angle;\n\n    d_point pixel;\n\n    tracestruct *trace;\n\n    // set the beam ID\n    actbeam->ID = conf->beam[beamID].ID;\n\n    // set the model template ID's\n    actbeam->modspec  = sobj->modspec;\n    actbeam->modimage = sobj->modimage;\n\n    // Adjust for posibly non (0,0) ref point of the 2D field dependence\n    // get the geometrical description of the trace at position \"pixel\"\n    pixel.x = sobj->xy_image.x - 1.0 - conf->refx;\n    pixel.y = sobj->xy_image.y - 1.0 - conf->refy;\n    trace = get_tracestruct_at_pos (conffile, conf->beam[beamID].ID, pixel);\n\n    // transfer trace information to the beam\n    actbeam->spec_trace = vector_to_trace_polyN(trace->pol);\n\n    // compute the local trace angle\n    trace_angle = atan2(actbeam->spec_trace->deriv (0, actbeam->spec_trace->data),1.0);\n\n    // set the reference point\n    actbeam->refpoint.x = sobj->xy_image.x - 1.0 + trace->offset.x;\n    actbeam->refpoint.y = sobj->xy_image.y - 1.0 + trace->offset.y;\n\n    // fill the flux and shape information\n    SexMags_to_beamFlux(sobj, actbeam);\n\n    // fill in the slit geometry\n    SexObject_to_slitgeom(conf, sobj, trace_angle, actbeam);\n\n    // actually set the extraction parameters\n    set_extraction_parameters(sobj,bck_mode,mfwhm, auto_reorient, trace_angle, actbeam);\n\n    // set the beam corners and the ignore flag\n    fill_corner_ignore(sobj, obs, conf, beamID, dmag, actbeam);\n  }\n\n/**\n * Function: SexObject_to_objectII\n * Fill an object structure with the information contained in a SexObject\n * structure This function uses a configuration file to compute the full\n * list of beams for each object.\n *\n * Parameters:\n * @param sobj     - pointer to a  SexObject\n * @param obs      - a pointer to the data array containing the image\n * @param conf     - pointer to the configuration structure\n * @param conffile - the name of the aperture configuration file\n * @param mfwhm    - the fwhm multiplicator constant to apply to\n *                   determine the width of the aperture box for the object.\n * @param dmag     - number of magnitudes to add to the magnitudes cutoffs\n * @param auto_reorient - if set then this task tries to optimize\n *                        the orientation of the\n *                        extraction slit - Should in general be left at 1 so that strange\n *                        geomety is avoided. If set to 2 the extraction is\n *                        forced to be vertical (90 deg.)\n * @param bck_mode - pointer for background mode\n *\n * Returns:\n * @return a pointer to a newly allocated object structure\n */\nobject * SexObject_to_objectII(SexObject * sobj, observation * const obs,\n                               aperture_conf *conf, char conffile[], float mfwhm, float dmag,\n                               int auto_reorient, int bck_mode)\n  {\n    int i=0;\n\n    object *ob;\n\n    // allocate an object\n    ob = (object *)malloc(sizeof(object));\n\n    // store the object specific\n    // information\n    ob->ID = sobj->number;\n    ob->nbeams = conf->nbeams;\n    ob->grism_obs = obs;\n\n    // go over all beams\n    for (i = 0; i < conf->nbeams; i++)\n        // fill the current beam\n        SexObject_to_beam(sobj, obs, conf, conffile, mfwhm, dmag, auto_reorient,\n                          bck_mode, i, &(ob->beams[i]));\n\n    // return the object\n    return ob;\n  }\n\n/**\n * Function: SexObject_to_object\n * Fill an object structure with the information contained in a SexObject\n * structure This function uses a configuration file to compute the full\n * list of beams for each object.\n *\n * Parameters:\n * @param sobj - pointer to a  SexObject\n * @param obs  - a pointer to the data array containing the image\n * @param conffile - the name of the aperture configuration file\n * @param maxmag  - upper magniture bound. If object has a magnitude\n *                  greater than this has its ignore flag set to 1,\n *                  zero otherwise.\n * @param mfwhm - the fwhm multiplicator constant to apply to\n *                determine the width of the aperture box for the object.\n * @param dmag - number of magnitudes to add to the magnitudes cutoffs\n * @param auto_reorient - if set then this task tries to optimize\n *                        the orientation of the\n *  extraction slit - Should in general be left at 1 so that strange\n *                    geomety is avoided. If set to 2 the extraction is\n *                    forced to be vertical (90 deg.)\n *\n * Returns:\n * @return a pointer to a newly allocated object structure\n *\n */\n// object *\n// SexObject_to_object (SexObject * sobj, observation * const obs,\n//                      aperture_conf *conf, char conffile[], float mfwhm,\n//                      float dmag,\n//                      //              char conffile[], float mfwhm, float dmag,\n//                      int auto_reorient, int bck_mode)\n// {\n//   int i, dx0, dx1;\n//   beam *b;\n//   object *ob = malloc (sizeof (object));\n//   d_point pixel;\n//   tracestruct *trace;\n//   //  aperture_conf *conf;\n//   float mmag_extract, mmag_mark;\n//   //  conf = get_aperture_descriptor (conffile);\n//   int j = 0, jj=0, nvalid=0;\n//   double fval=0.0;\n//   gsl_vector *flux;\n//   float aposang, paposang;\n//   float dya, dyb;\n//   int iturn;\n\n//   ob->ID = sobj->number;\n\n\n//   for (i = 0; i < conf->nbeams; i++)\n//     {\n//       dx0 = conf->beam[i].offset.dx0;\n//       dx1 = conf->beam[i].offset.dx1;\n//       mmag_extract = conf->beam[i].mmag_extract+dmag;\n//       mmag_mark = conf->beam[i].mmag_mark+dmag;\n//       b = &(ob->beams[i]);\n//       b->ID = conf->beam[i].ID;\n\n//       //---------------------------------------\n//       // some code for FORS2 MXU\n//       // b->backwindow.x = sobj->backwindow.x;\n//       // b->backwindow.y = sobj->backwindow.y;\n\n//       b->modspec  = sobj->modspec;\n//       b->modimage = sobj->modimage;\n\n//       /* Adjust for posibly non (0,0) ref point of the 2D field dependence */\n//       pixel.x = sobj->xy_image.x-1 - conf->refx;\n//       pixel.y = sobj->xy_image.y-1 - conf->refy;\n//       /* get the geometrical description of the trace at position \"pixel\" */\n//       trace =\n//         get_tracestruct_at_pos (conffile, conf->beam[i].ID, pixel);\n\n//       b->spec_trace = vector_to_trace_polyN ( trace->pol );\n\n//       b->width   = sobj->el_image.a * mfwhm;\n\n\n//       /* if flux/wavelength information exists */\n//       if (sobj->magnitudes)\n//         {\n\n//           // get the number of valid entries in 'sobj->magnitudes'\n//           nvalid = get_valid_entries(sobj->magnitudes);\n//           if (!nvalid)\n//             aXe_message (aXe_M_WARN3, __FILE__, __LINE__,\n//                          \"No valid magnitude for object %i !\\n\", sobj->number);\n\n//           // allocate the vector for the flux\n//           flux = gsl_vector_alloc (2*(nvalid));\n\n//           // fill the flux vector with values\n//           jj=0;\n//           for (j=0; j < (int)sobj->magnitudes->size; j++)\n//             {\n//               if (is_valid_entry(gsl_vector_get(sobj->magnitudes, j)))\n//                 {\n\n//                   fval = get_flambda_from_magab(gsl_vector_get(sobj->magnitudes, j), gsl_vector_get(sobj->lambdas, j));\n\n//                   gsl_vector_set(flux, 2*jj, gsl_vector_get(sobj->lambdas, j));\n//                   //              gsl_vector_set(flux, 2*jj+1, gsl_vector_get(sobj->magnitudes, j));\n//                   gsl_vector_set(flux, 2*jj+1, fval);\n//                   jj++;\n//                 }\n//             }\n//           b->flux = flux;\n\n//           /* fill the structual parameters of the object */\n//           b->awidth  = sobj->el_image.a;\n//           b->bwidth  = sobj->el_image.b;\n//           b->aorient = sobj->el_image.theta;\n//         }\n//       // if flux/wavelength information does not exists\n//       else\n//         {\n//           // set everything to dummy values\n//           b->flux = NULL;\n\n//           b->awidth  = -1.0;\n//           b->bwidth  = -1.0;\n//           b->aorient = -1.0;\n//         }\n\n//       /* Convert from SeXtractor angle reference point to aXe's */\n//       b->orient = (180 + sobj->el_image.theta) / 180. * M_PI;\n//       while (b->orient > M_PI)\n//         b->orient = b->orient - M_PI;\n\n//       // calculate the angle between\n//       // the extraction direction and the trace\n//       aposang =\n//         b->orient - atan2(b->spec_trace->deriv (0, b->spec_trace->data),1.0);\n\n//       // transform the angle to degrees\n//       paposang = aposang / M_PI * 180.;\n\n//       // give a warning for small angles\n//       // between the orientation direction and\n//       // the trace angle.\n//       // BUGFIX comparison should be to paposang not the logical comparison MLS\n//       if ( ( (fabs(paposang) < MIN_DIFFANGLE) || (fabs(paposang-180.0) < MIN_DIFFANGLE) ) && (auto_reorient == 0) )\n//         aXe_message (aXe_M_WARN4, __FILE__, __LINE__,\n//                      \"aXe_GOL2AF: Object ID: %i: The angle between the extraction orientation and \"\n//                      \"the trace is less than %5.2f degrees. You may get severe problems\"\n//                      \" down to core dumps in the 1D extraction later on!\\n\", ob->ID, MIN_DIFFANGLE);\n\n\n//        Case when the extraction angle is modified to that the extraction \n//       /* proceeds along the semi-axis which projects farther away from the\n//        * trace i.e. we avoid trying to extract spectra in a direction nearly\n//        * parallel the trace */\n//       if (auto_reorient==1)\n//         {\n\n//           aposang =\n//             b->orient - atan2(b->spec_trace->deriv (0,\n//                                                     b->spec_trace->data),1.0);\n\n//           /* February 2004 introduced to make a hardstop in the range for\n//              allowed angles. */\n//           if (aposang > 0.0){\n//             paposang = aposang / M_PI * 180.;\n//           }\n//           else{\n//             paposang = aposang / M_PI * 180. + 360.0;\n//           }\n//           if (paposang > 180.0)\n//             paposang = paposang-180.0;\n//           /* the hard stop is here */\n//           if (paposang > 30.0 && paposang < 150.0){\n//             iturn = 0;}\n//           else{\n//             iturn = 1;}\n//           /*end introduction */\n\n\n//           /* Compute how far each axes extends away from the trace */\n//           dya = fabs (sobj->el_image.a * sin (aposang));\n//           dyb = fabs (sobj->el_image.b * sin (M_PI / 2. - aposang));\n\n//           /* Select the broader of the two axes */\n//           if (dya > dyb && iturn == 0)\n//             {\n//               b->width = sobj->el_image.a * mfwhm;\n//             }\n//           else\n//             {\n//               b->width = sobj->el_image.b * mfwhm;\n//               b->orient = b->orient + M_PI / 2.;\n//             }\n//         }\n\n//         /* Case when we force the extraction to be vertical,\n//            the extraction width is recomputed */\n//       if (auto_reorient==2) {\n//         // new system for fixed extraction:\n//         //    - extraction direction perpendicular\n//         //      to the trace\n//         //    - the mfwhm is used as a fixed extraction widt in pixels\n//         b->orient =\n//           atan2(b->spec_trace->deriv (0,b->spec_trace->data),1.0)+ M_PI / 2.0;\n\n//         if (mfwhm < 0.0)\n//           {\n//             b->orient =\n//               atan2(b->spec_trace->deriv (0.0,b->spec_trace->data),1.0)+ M_PI / 2.0;\n//             b->width  = -mfwhm;\n\n//           }\n//         else\n//           {\n//             aposang = b->orient\n//               - atan2(b->spec_trace->deriv (0,b->spec_trace->data),1.0);\n\n//             /* Compute how far each axes extends away from the trace */\n//             dya = fabs (sobj->el_image.a * sin (aposang));\n//             dyb = fabs (sobj->el_image.b * sin (M_PI / 2. - aposang));\n//             b->width = mfwhm*MAX(dya,dyb);\n//             b->orient =\n//               atan2(b->spec_trace->deriv (0,b->spec_trace->data),1.0)+ M_PI / 2.0;\n//           }\n\n//       }\n\n//       if (sobj->backwindow.x != -1 && bck_mode)\n//         b->width = MAX(b->width, sobj->backwindow.x);\n\n//       /* On coordinate systems:\n//          the sexrtractor image positions are given in the iraf system,\n//          which means the value of the lower left pixel is associated\n//          with the coordinate (1.0,1.0).\n//          aXe works in a kind of 'matrix system', where the value of\n//          the lower left pixel is stored in the matrix indices (0,0)\n//          or (0.0,0.0) seen as a coordinate system.\n//          To transform into this system 1.0 is subracted from\n//          both sextractor coordinates.\n//        */\n//       b->refpoint.x = sobj->xy_image.x-1.0 + trace->offset.x;\n//       b->refpoint.y = sobj->xy_image.y-1.0 + trace->offset.y;\n\n//       /* magnitude cut */\n//       // PROBLEM: there is a logical flaw inside\n//       //          whhat happend when (mag > mag_mark) && (mag <  mmag_extract) ????\n//       //          of course this has only relevance when mag_mark < mmag_extract\n//       //      if ((sobj->mag_auto <= mmag_mark)&&(sobj->mag_auto <= mmag_extract))\n//       // That's now an easy fix, but makes sense..\n//       if (sobj->mag_auto <= mmag_extract)\n//         {\n//           b->ignore = 0; /* This object will be extracted */\n//         }\n//       if ((sobj->mag_auto <= mmag_mark)&&(sobj->mag_auto > mmag_extract))\n//         {\n//           b->ignore = 2; /* This object will be not be extracted */\n//         }\n//       if ((sobj->mag_auto > mmag_mark)&&(sobj->mag_auto > mmag_extract))\n//         {\n//           b->ignore = 1; /* This object will be ignored */\n//         }\n\n//       if (!fill_object_bbox (obs, b, 2, dx0, dx1))\n//         b->ignore = 1;\n\n//     b->slitgeom[0] = -1.0;\n//     b->slitgeom[1] = -1.0;\n//     b->slitgeom[2] = -1.0;\n//     b->slitgeom[3] = -1.0;\n//     }\n\n//   ob->nbeams = conf->nbeams;\n//   ob->grism_obs = obs;\n\n//   return ob;\n// }\n\n/**\n * Function: SexObjects_to_oblist\n * Produces an object list from the data contained in an array of SexObjects\n *\n * Parameters:\n * @param sobjs - an NULL terminated array containing pointers to SexObjects\n * @param obs - a pointer to the data array containing the image\n * @param conffile - the name of the aperture configuration file\n * @param mmag_extract - upper magniture bound. Any object with a magnitude greater than\n *  this has its ignore flag set to 1.\n * @param mmag_mark - upper magniture bound. Any object with a magnitude greater than\n *  this has its ignore flag set to 2.\n * @param mfwhm - the fwhm multiplicator constant to apply to determine the width of the\n *  aperture box for the object.\n * @param dmag - number of magnitudes to add to the magnitudes cutoffs\n * @param auto_reorient - if set to 1 then this task tries to optimize the orientation of the\n *  extraction slit. Should in general be left at 1 so that strange geomety is avoided. If set to 2\n *  the extraction is forced to be vertical (90 deg.)\n *\n *  Return:\n *  @return a pointer to a NULL terminated object array.\n */\nobject **\nSexObjects_to_oblist (SexObject ** sobjs, observation * const obs,\n                      aperture_conf *conf, char conffile[], float mfwhm,\n                      float dmag,\n                      //                      char conffile[], float mfwhm, float dmag,\n                      int auto_reorient, int bck_mode)\n{\n     int i, nobjs = 0;\n     object **oblist;\n\n     /* Find the number of SexObjects in sobjs */\n     while (sobjs[nobjs])\n          nobjs++;\n     /* Allocate enough room for a new object list */\n     oblist = (object **) malloc ((nobjs + 1) * sizeof (object *));\n\n     for (i = 0; i < nobjs; i++)\n       {\n         //fprintf(stdout, \"Using the old routine...\\n\");\n         oblist[i] =\n         SexObject_to_objectII(sobjs[i], obs, conf, conffile, mfwhm, dmag, auto_reorient, bck_mode);\n        }\n     oblist[nobjs] = NULL;\n\n     return oblist;\n}\n\n/**\n * Function: SexObjects_to_oblistII\n * Produces an object list from the data contained in an array of SexObjects\n *\n * Parameters:\n * @param sobjs - an NULL terminated array containing pointers to SexObjects\n * @param obs - a pointer to the data array containing the image\n * @param conffile - the name of the aperture configuration file\n * @param mmag_extract - upper magniture bound. Any object with a magnitude greater than\n *  this has its ignore flag set to 1.\n * @param mmag_mark - upper magniture bound. Any object with a magnitude greater than\n *  this has its ignore flag set to 2.\n * @param mfwhm - the fwhm multiplicator constant to apply to determine the width of the\n *  aperture box for the object.\n * @param dmag - number of magnitudes to add to the magnitudes cutoffs\n * @param auto_reorient - if set to 1 then this task tries to optimize the orientation of the\n *  extraction slit. Should in general be left at 1 so that strange geomety is avoided. If set to 2\n *  the extraction is forced to be vertical (90 deg.)\n *\n *  Return:\n *  @return a pointer to a NULL terminated object array.\n */\nobject **\nSexObjects_to_oblistII (SexObject ** sobjs, observation * const obs,\n                      aperture_conf *conf, char conffile[], float mfwhm,\n                      float dmag,\n                      int auto_reorient, int bck_mode)\n{\n     int i, nobjs = 0;\n     object **oblist;\n     fflush(stdout);\n     /* Find the number of SexObjects in sobjs */\n     while (sobjs[nobjs])\n          nobjs++;\n     /* Allocate enough room for a new object list */\n     oblist = (object **) malloc ((nobjs + 1) * sizeof (object *));\n\n     for (i = 0; i < nobjs; i++)\n       {\n         //fprintf(stdout, \"Using the new routine...\\n\");\n         oblist[i] =\n         SexObject_to_objectII(sobjs[i], obs, conf, conffile, mfwhm, dmag, auto_reorient, bck_mode);\n        }\n     oblist[nobjs] = NULL;\n     return oblist;\n}\n\n/**\n * Function: check_conf_for_slitlessgeom\n * The functions checks whether a smoothed flux conversion\n * is possible or not. In case that keywords in the configuration\n * files are missing, it is NOT possible, and 0 is returned.\n *\n * Parameters:\n * @param conf          - the configuarion file structure\n * @param auto_reorient - integer indicating the extraction method\n *\n * Returns\n * @return is_possible - the paramters used in the smoothing\n */\nint\ncheck_conf_for_slitlessgeom(const aperture_conf *conf, const int auto_reorient)\n//check_conf_for_slitlessgeom(const aperture_conf *conf, const int slitless_geom)\n  {\n    int is_possible=1;\n\n    if (auto_reorient == 1 && conf->pobjsize < 0.0)\n      // change the switch\n      is_possible = 0;\n\n    // return the pointer\n    return is_possible;\n  }\n\n\n/**\n * Function: fill_object_bbox\n * Fill up the aperture part of the beam of an object structure by looking at the trace polynomial\n * description associated with this object.\n *\n * Parameters:\n * @param obs - a pointer to the data array containing the image (used for bound checking)\n * @param b - A pointer to a beam whose aperture must be filled.\n * @param m_width - The width in pixel of the extraction box\n * @param dxmin - How far (in pixel) to follow the trace on the left side of the spectrum\n * @param dxmax - How far (in pixel) to follow the trace on the right hand side of the spectrum\n *\n * Returns:\n * @return 1 if bounding box appears to be valied (i.e. non-empty)\n */\nint\nfill_object_bbox (observation * const obs, beam * b, const float m_width,\n                  const int dxmin, const int dxmax)\n{\n     d_point pmin, pmax;\n     d_point pminl, pminh, pmaxl, pmaxh;\n     float w = b->width/2. * m_width + 2.0;\n     float wcos, wsin;\n     float area;\n\n     int xmin, xmax, xact;\n     double yact;\n\n     pmin.x = b->refpoint.x + dxmin;\n     pmin.y =\n          b->refpoint.y + b->spec_trace->func (dxmin, b->spec_trace->data);\n\n     pmax.x = b->refpoint.x + dxmax;\n     pmax.y =\n          b->refpoint.y + b->spec_trace->func (dxmax, b->spec_trace->data);\n\n\n     if (b->spec_trace->type > 1)\n       {\n         if (dxmin < dxmax)\n           {\n             xmin = dxmin;\n             xmax = dxmax;\n           }\n         else\n           {\n             xmin = dxmax;\n             xmax = dxmin;\n           }\n\n         for (xact = xmin; xact < xmax; xact++)\n           {\n             yact = b->refpoint.y + b->spec_trace->func (xact, b->spec_trace->data);\n\n             if (yact < pmin.y)\n               pmin.y = yact;\n             if (yact > pmax.y)\n               pmax.y = yact;\n           }\n         wcos = w * cos (b->orient);\n         wsin = w * sin (b->orient);\n\n         if (wcos > 0)\n           {\n             pmin.x = pmin.x - wcos;\n             pmax.x = pmax.x + wcos;\n           }\n         else\n           {\n             pmin.x = pmin.x + wcos;\n             pmax.x = pmax.x - wcos;\n           }\n         if (wsin > 0)\n           {\n             pmin.y = pmin.y - wsin;\n             pmax.y = pmax.y + wsin;\n           }\n         else\n           {\n             pmin.y = pmin.y + wsin;\n             pmax.y = pmax.y - wsin;\n           }\n         b->corners[0].x = pmin.x;\n         b->corners[0].y = pmin.y;\n\n         b->corners[1].x = pmax.x;\n         b->corners[1].y = pmin.y;\n\n         b->corners[2].x = pmax.x;\n         b->corners[2].y = pmax.y;\n\n         b->corners[3].x = pmin.x;\n         b->corners[3].y = pmax.y;\n       }\n     else\n       {\n\n         wcos = w * cos (b->orient);\n         wsin = w * sin (b->orient);\n\n         pminl.x = pmin.x - wcos;\n         pminl.y = pmin.y - wsin;\n\n         pminh.x = pmin.x + wcos;\n         pminh.y = pmin.y + wsin;\n\n         pmaxl.x = pmax.x - wcos;\n         pmaxl.y = pmax.y - wsin;\n\n         pmaxh.x = pmax.x + wcos;\n         pmaxh.y = pmax.y + wsin;\n\n         b->corners[0].x = pminl.x;\n         b->corners[0].y = pminl.y;\n\n         b->corners[1].x = pmaxl.x;\n         b->corners[1].y = pmaxl.y;\n\n         b->corners[2].x = pmaxh.x;\n         b->corners[2].y = pmaxh.y;\n\n         b->corners[3].x = pminh.x;\n         b->corners[3].y = pminh.y;\n       }\n\n     /* Compute the area of this aperture */\n     area =\n          0.5 * (abs (b->corners[0].y - b->corners[4].y) *\n                 abs (b->corners[0].x - b->corners[1].x) +\n                 abs (b->corners[2].y -\n                       b->corners[1].y) * abs (b->corners[3].x -\n                                               b->corners[2].x));\n     if (area == 0)\n       {\n            fprintf (stderr, \"aper debug: area is zero!\\n\");\n            return 0;\n       }\n     return 1;\n}\n\n/**\n * Function: size_of_sextractor_catalog\n * A utility function which parses a Sextractor catalog file,\n * and returns the number of valid catalog entries found in the file\n *\n * Parameters:\n * @param filename - a pointer pointing to a char array containing the\n *                   list of a sextractor object output catalog.\n *                   Ignores rows starting with a \";\"\n */\nint\nsize_of_sextractor_catalog (char filename[])\n{\n  FILE *input;\n  char Buffer[CATBUFFERSIZE];\n  gsl_vector *v;\n  int catsize;\n  int num = 0;\n  colinfo * actcatinfo;\n  actcatinfo = get_sex_col_descr (filename);\n  //  catalog_header = get_sex_col_descr (filename);\n  catsize = actcatinfo->numcols;\n  if (!(input = fopen (filename, \"r\")))\n    {\n      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n                   \"Could not open Sextractor catalog\" \"file %s,\\n\",\n                   filename);\n    }\n\n\n  while (fgets (Buffer, CATBUFFERSIZE, input))\n    {\n      if (Buffer[0] == ';')\n        continue;\n      lv1ws (Buffer);\n      v = string_to_gsl_array (Buffer);\n      if (v==NULL) continue;\n      if ((int)v->size == catsize)\n        num++;\n    }\n  return num;\n}\n\n\n/**\n * Function: get_SexObject_from_catalog\n * Parses a Sextractor 2.0 catalog file, and outputs a NULL terminated\n * array of SexObjects pointers. Ignores rows starting with a ;\n *\n * Parameters:\n * @param filename a pointer pointing to a char array containing the\n *                 list of a sextractor object output catalog\n *\n * Returns:\n * @return a pointer to an array of SeXObject pointer. NULL terminated\n */\nSexObject **\nget_SexObject_from_catalog (char filename[], const double lambda_mark)\n{\n  FILE *input;\n  char Buffer[CATBUFFERSIZE];\n  gsl_vector *v;\n  gsl_vector *waves;\n  gsl_vector *cnums;\n  size_t hasmags=0;\n  size_t nobjs;\n  size_t catsize;\n  int i;\n  size_t magcencol=0;\n  SexObject **sobjs, *sobj;\n  colinfo * actcatinfo;\n  px_point  backwin_cols;\n  px_point  modinfo_cols;\n\n  actcatinfo = get_sex_col_descr (filename);\n  hasmags = has_magnitudes(actcatinfo);\n  waves = gsl_vector_alloc (hasmags);\n  cnums = gsl_vector_alloc (hasmags);\n  hasmags = get_magcols(actcatinfo, waves, cnums);\n  magcencol = get_magauto_col(waves, cnums, lambda_mark);\n  backwin_cols = has_backwindow(actcatinfo);\n  modinfo_cols = has_modelinfo(actcatinfo);\n\n\n  //  catsize = count_keys (catalog_header);\n  catsize = actcatinfo->numcols;\n  nobjs = size_of_sextractor_catalog (filename);\n  if (!(input = fopen (filename, \"r\")))\n       {\n         aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n                      \"Could not open Sextractor catalog\" \"file %s,\\n\",\n                      filename);\n       }\n\n  /* Allocate enough room for nobjs+1 SexObject  pointers */\n  sobjs = (SexObject **) malloc ((nobjs + 1) * sizeof (SexObject *));\n  if (!sobjs)\n    {\n      aXe_message (aXe_M_FATAL, __FILE__, __LINE__, \"Out of memory. Couldn't allocate Sextractor Object\");\n    }\n\n  i = 0;\n  while (fgets (Buffer, CATBUFFERSIZE, input))\n    {\n      if (Buffer[0] == ';')\n        continue;\n      v = string_to_gsl_array (Buffer);\n      if (v==NULL) continue;\n      if (v->size == catsize)\n        {\n          // BIG BUG!!!\n          //               sobj = create_SexObject (catalog_header, Buffer);\n          sobj = create_SexObject (actcatinfo, Buffer, waves, cnums, backwin_cols, modinfo_cols, magcencol, 0);\n          sobjs[i++] = sobj;\n        }\n    }\n  sobjs[i] = NULL;\n  return sobjs;\n}\n\n/**\n * Function: el_to_ABC_world\n * Convert a wold coordinate ellipse into a set of 3 points on the\n * tangent plane point a is at pos of obj, semi major-axis end is point b,\n * semi minor axis is point c theta is measured from x-axis to semi-major\n * axis, counter clock wise.\n */\nvoid\nel_to_ABC_world (ellipse *el, sky_coord *a, sky_coord *b, sky_coord *c)\n{\n\n     a->ra = 0.0;\n     a->dec = 0.0;\n\n     b->ra = el->a * cos (el->theta / 180. * M_PI);\n     b->dec = el->a * sin (el->theta / 180. * M_PI);\n\n     c->ra = -1.0 * el->b * sin (el->theta / 180. * M_PI);\n     c->dec = el->b * cos (el->theta / 180. * M_PI);\n}\n\n/*\n * Function: el_to_ABC_world2\n *\n */\nvoid\nel_to_ABC_world2 (ellipse *el, sky_coord *a, sky_coord *b, sky_coord *c)\n{\n  b->ra  = a->ra  - (el->a * cos (el->theta / 180. * M_PI))/cos(a->dec / 180. * M_PI);\n  b->dec = a->dec + (el->a * sin (el->theta / 180. * M_PI));\n\n  c->ra  = a->ra  - (el->b * cos ((el->theta-90.0)/180.*M_PI))/cos(a->dec / 180. * M_PI);\n  c->dec = a->dec + (el->b * sin ((el->theta-90.0)/180.*M_PI));\n}\n\n/**\n * Function: ABC_image_to_el\n * Convert a set of three image coordinates into an elipse structure\n *\n */\nvoid\nABC_image_to_el (d_point *a, d_point *b, d_point *c, ellipse *el)\n{\n  if (b->x != 0.0)\n    {\n      el->theta = atan (b->y / b->x) / M_PI * 180.0;\n    }\n  else\n    {\n      el->theta = 90.0;\n    }\n\n  el->a = sqrt ((b->x - a->x) * (b->x - a->x) + (b->y - a->y) * (b->y - a->y));\n  el->b = sqrt ((c->x - a->x) * (c->x - a->x) + (c->y - a->y) * (c->y - a->y));\n}\n\n/**\n * Function: ABC_image_to_el2\n * Convert a set of three image coordinates into an elipse structure\n *\n */\nvoid\nABC_image_to_el2 (d_point *a, d_point *b, d_point *c, ellipse *el)\n{\n  el->theta = atan ((b->y - a->y )/ (b->x - a->x)) / M_PI * 180.0;\n\n  el->a = sqrt ((b->x - a->x) * (b->x - a->x) + (b->y - a->y) * (b->y - a->y));\n  el->b = sqrt ((c->x - a->x) * (c->x - a->x) + (c->y - a->y) * (c->y - a->y));\n}\n\n/**\n *  Function: fill_missing_WCS_coordinates\n *  Update a SexObject structure and replace all missing WCS coordinates\n *  by re-computing them using the world one and the from_wcs wcs.\n *  Re-computes:\n *      peak_world_x\n *     peak_world.y\n *       xy_world.x\n *      xy_world.y\n *      el_world.a\n *      el_world.b\n *      el_world.theta\n *\n *  @param o - a pointer to an exsting SexObject. Should have been checked for validity already\n *  @param from_wcs - a pointer to an existing  WoldCoord wcs structure\n */\nvoid\nfill_missing_WCS_coordinates (SexObject * o, struct WorldCoor *from_wcs, int overwrite)\n{\n  sky_coord as, bs, cs;\n  d_point a, b, c;\n  //int offscl;\n\n  /***************************************************************/\n  /* If the WCS coordinates are missing, generate them using     */\n  /* from_wcs and sextractor image coordinates                   */\n  /***************************************************************/\n\n  if ((overwrite) || (isnan (o->xy_world.ra)) || (isnan (o->xy_world.dec)))\n    {\n      /* recomputes xy_image  from the world values */\n      /*pix2wcs (from_wcs, o->xy_image.x, o->xy_image.y,\n               &(o->xy_world.ra),&(o->xy_world.dec), &offscl);\n      */\n      /* recomputes xy_image  from the world values */\n      // new version requested since wcstools-3.6\n      pix2wcs (from_wcs, o->xy_image.x, o->xy_image.y,\n               &(o->xy_world.ra),&(o->xy_world.dec));\n    }\n\n  if ((isnan (o->el_world.a)) || (isnan (o->el_world.b))\n      || (isnan (o->el_world.theta)) || (overwrite))\n    {\n\n      /* recomputes el_image them from the world values */\n\n      /* Note the following is an unconventional use of the et_to*()\n         routines since we store image coords in as, bs, and cs */\n      el_to_ABC_world (&(o->el_image), &as, &bs, &cs);  /* Convert ellipse into a set of 3 coordinates */\n\n      /* Compute the end point of the axes in the image coord system */\n      /*      pix2wcs (from_wcs, as.ra, as.dec, &(a.x), &(a.y), &offscl);\n      pix2wcs (from_wcs, bs.ra, bs.dec, &(b.x), &(b.y), &offscl);\n      pix2wcs (from_wcs, cs.ra, cs.dec, &(c.x), &(c.y), &offscl);\n      */\n      /* Compute the end point of the axes in the image coord system */\n      // new version requested since wcstools-3.6\n      pix2wcs (from_wcs, as.ra, as.dec, &(a.x), &(a.y));\n      pix2wcs (from_wcs, bs.ra, bs.dec, &(b.x), &(b.y));\n      pix2wcs (from_wcs, cs.ra, cs.dec, &(c.x), &(c.y));\n\n      ABC_image_to_el (&a, &b, &c, &(o->el_world));     /* convert 3 coordinates into ellipse */\n    }\n}\n\n/**\n * Function: fill_missing_image_coordinates\n *  Update a SexObject structure and replace all missing image coordinates\n *  by re-computing them using the world one and the from_wcs wcs.\n *  Re-computes:\n *      peak_image_x\n *      peak_image.y\n *      xy_image.x\n *      xy_image.y\n *      el_image.a\n *      el_image.b\n *      el_image.theta\n *\n * Parameters:\n * @param o - a pointer to an exsting SexObject. Should have been\n *            checked for validity already\n * @param from_wcs - a pointer to an existing  WoldCoord wcs structure\n */\nvoid\nfill_missing_image_coordinates (SexObject *o, struct WorldCoor *from_wcs, int overwrite)\n{\n  sky_coord as, bs, cs;\n  d_point a, b, c;\n  int offscl;\n\n\n  /************************/\n  /* If the image coordinates are missing, generate them using from_wcs and sextractor world\n     coordinates */\n  /************************/\n  if ((overwrite) || (isnan (o->xy_image.x)) || (isnan (o->xy_image.y)))\n    {\n      /* recomputes xy_image  from the world values */\n      wcs2pix (from_wcs, o->xy_world.ra, o->xy_world.dec,\n               &(o->xy_image.x), &(o->xy_image.y), &offscl);\n\n    }\n\n\n  if ((isnan (o->el_image.a)) || (isnan (o->el_image.b))\n      || (isnan (o->el_image.theta)) || (overwrite))\n    {\n\n      /* recomputes el_image them from the world values */\n\n      el_to_ABC_world (&(o->el_world), &as, &bs, &cs);  /* Convert ellipse into a set of 3 coordinates */\n\n      /* Compute the end point of the axes in the image coord system */\n      wcs2pix (from_wcs, as.ra, as.dec, &(a.x), &(a.y), &offscl);\n      wcs2pix (from_wcs, bs.ra, bs.dec, &(b.x), &(b.y), &offscl);\n      wcs2pix (from_wcs, cs.ra, cs.dec, &(c.x), &(c.y), &offscl);\n\n      /* DISABLED !!*/\n      //            ABC_image_to_el (&a, &b, &c, &(o->el_image));       /* convert 3 coordinates into ellipse */\n    }\n}\n\n/**\n * Function: fill_all_missing_image_coordinates\n * Replaces all NaN values in a set of SexObjects with ones computed\n * from the available information and the associated WCS.\n *\n * Parameters:\n * @param sobjs    - an NULL terminated array containing pointers to SexObjects\n * @param from_wcs - a pointer to an existing  WoldCoord wcs structure\n * @param overwrite - forces the re-computation of all image coordinates\n *\n */\nvoid\nfill_all_missing_image_coordinates (SexObject ** sobjs,\n                                    struct WorldCoor *from_wcs, int overwrite)\n{\n  int i, nobjs = 0;\n\n  /* Find the number of SexObjects in sobjs */\n  while (sobjs[nobjs])\n    nobjs++;\n\n  for (i = 0; i < nobjs; i++)\n    {\n      fill_missing_image_coordinates (sobjs[i], from_wcs, overwrite);\n    }\n\n}\n\n/**\n * Function: fill_all_missing_WCS_coordinates\n *  Replaces all NaN values in a set of SexObjects with ones computed from the\n *  available information and the associated WCS.\n *\n * Parameters:\n *  @param sobjs - an NULL terminated array containing pointers to SexObjects\n *  @param from_wcs - a pointer to an existing  WoldCoord wcs structure\n *  @param overwrite - forces the re-computation of all image coordinates\n *\n */\nvoid\nfill_all_missing_WCS_coordinates (SexObject ** sobjs,\n                                    struct WorldCoor *from_wcs, int overwrite)\n{\n  int i, nobjs = 0;\n\n  /* Find the number of SexObjects in sobjs */\n  while (sobjs[nobjs])\n    nobjs++;\n\n  for (i = 0; i < nobjs; i++)\n    {\n      fill_missing_WCS_coordinates (sobjs[i], from_wcs, overwrite);\n    }\n\n}\n\n/**\n * Function: compute_new_image_coordinates\n *  Function that uses the exisiting world coordinates of a SexObject to\n *  compute new pixel coordinates using a (new) WCS.\n *\n * Parameters:\n *  @param o - a pointer to an exsting SexObject. Should have been checked\n *   for validity already\n *  @param to_wcs - a pointer to an existing  WoldCoord wcs structure\n *\n */\nvoid\ncompute_new_image_coordinates (SexObject * o, struct WorldCoor *to_wcs)\n{\n  sky_coord as, bs, cs;\n  d_point a, b, c;\n  int offscl;\n\n\n  /******************************************************************/\n  /* uses the existing world coordinates of a SexObject to compute  */\n  /* new pixel coordinates using a (new) WCS.                       */\n  /*******************************************************************/\n\n  /* recomputes xy_image  from the world values */\n  wcs2pix (to_wcs, o->xy_world.ra, o->xy_world.dec, &(o->xy_image.x),\n           &(o->xy_image.y), &offscl);\n\n\n  /* recomputes el_image them from the world values */\n  el_to_ABC_world (&(o->el_world), &as, &bs, &cs);      /* Convert ellipse into a set of 3 coordinates */\n\n  /* Compute the end point of the axes in the image coord system */\n  wcs2pix (to_wcs, as.ra, as.dec, &(a.x), &(a.y), &offscl);\n  wcs2pix (to_wcs, bs.ra, bs.dec, &(b.x), &(b.y), &offscl);\n  wcs2pix (to_wcs, cs.ra, cs.dec, &(c.x), &(c.y), &offscl);\n\n\n  /* DISABLED */\n  //     ABC_image_to_el (&a, &b, &c, &(o->el_image));  /* convert 3 coordinates into ellipse */\n}\n\n/**\n * Function: compute_new_image_sexobject\n * Function that uses the exisiting world coordinates of a SexObject to\n * compute new pixel coordinates using a (new) WCS.\n *\n * Parameters:\n * @param o - a pointer to an exsting SexObject. Should have been checked\n *  for validity already\n *  @param to_wcs - a pointer to an existing  WoldCoord wcs structure\n */\nvoid\ncompute_new_image_sexobject (SexObject * o, struct WorldCoor *to_wcs, int th_sky)\n{\n  sky_coord  bs, cs;\n  d_point a, b, c;\n  int offscl;\n\n  /******************************************************************/\n  /* uses the existing world coordinates of a SexObject to compute  */\n  /* new pixel coordinates using a (new) WCS.                       */\n  /******************************************************************/\n\n  /* recomputes xy_image  from the world values */\n  wcs2pix (to_wcs, o->xy_world.ra, o->xy_world.dec, &(o->xy_image.x),\n           &(o->xy_image.y), &offscl);\n\n  /* Convert ellipse into a set of 3 coordinates */\n  el_to_ABC_world2 (&(o->el_world), &(o->xy_world), &bs, &cs);\n\n  /* Compute the end point of the axes in the image coord system */\n\n  wcs2pix (to_wcs, o->xy_world.ra, o->xy_world.dec, &(a.x), &(a.y), &offscl);\n  wcs2pix (to_wcs, bs.ra, bs.dec, &(b.x), &(b.y), &offscl);\n  wcs2pix (to_wcs, cs.ra, cs.dec, &(c.x), &(c.y), &offscl);\n\n\n  /* convert 3 coordinates into ellipse */\n  ABC_image_to_el2 (&a, &b, &c, &(o->el_image));\n  if (th_sky)\n    o->el_image.theta = o->el_image.theta - 90.0;\n}\n\n/**\n * Function: compute_all_new_image_coordinates\n * Replaces all SexObjects image coordinates with new ones computed using  the\n * the passed WCS.\n *\n * Parameters:\n * @param sobjs - a NULL terminated array containing pointers to SexObjects\n * @param to_wcs - a pointer to an existing  WoldCoord wcs structure\n */\nvoid\ncompute_all_new_image_coordinates (SexObject ** sobjs,\n                                   struct WorldCoor *to_wcs)\n{\n     int i, nobjs = 0;\n\n     /* Find the number of SexObjects in sobjs */\n     while (sobjs[nobjs])\n          nobjs++;\n\n     for (i = 0; i < nobjs; i++)\n       {\n            compute_new_image_coordinates (sobjs[i], to_wcs);\n       }\n\n}\n\n\n/**\n * Function: free_SexObjects\n *    Free a NULL terminated array of SexObject\n *\n * Parameters:\n *  @param sobjs - a NULL terminated array containing pointers to SexObjects\n *\n */\nvoid\nfree_SexObjects (SexObject ** sobjs)\n{\n  int i, nobjs = 0;\n\n  /* Find the number of SexObjects in sobjs */\n  while (sobjs[nobjs])\n    nobjs++;\n\n  for (i = 0; i < nobjs; i++)\n    {\n      if (sobjs[i]->magnitudes){\n        gsl_vector_free (sobjs[i]->lambdas);\n        gsl_vector_free (sobjs[i]->magnitudes);\n      }\n      free (sobjs[i]);\n      sobjs[i] = NULL;\n    }\n  free (sobjs);\n  sobjs = NULL;\n}\n", "meta": {"hexsha": "3448fc8fdf8cea18bbf4a89b7d21825cba4ee129", "size": 68488, "ext": "c", "lang": "C", "max_stars_repo_path": "cextern/src/spc_sex.c", "max_stars_repo_name": "sosey/pyaxe", "max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cextern/src/spc_sex.c", "max_issues_repo_name": "sosey/pyaxe", "max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cextern/src/spc_sex.c", "max_forks_repo_name": "sosey/pyaxe", "max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6911694511, "max_line_length": 122, "alphanum_fraction": 0.5981047775, "num_tokens": 19225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.021615330517336558, "lm_q1q2_score": 0.009881161225836389}}
{"text": "/* PETSC_DEPTRECATED causes parse erros in bindgen */\n#define PETSC_DEPRECATED(arg)\n/* Not sure how this is generated... */\n#define PETSC_BITS_PER_BYTE 8\n#include <petsc.h>\n", "meta": {"hexsha": "4d2e4489ce93668a1e804bc4ae9e7b5934c12b67", "size": 173, "ext": "h", "lang": "C", "max_stars_repo_path": "wrapper.h", "max_stars_repo_name": "tkonolige/petsc-bindgen-rust", "max_stars_repo_head_hexsha": "ec7d92db067964e36e1319619c8773ec210d66f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "wrapper.h", "max_issues_repo_name": "tkonolige/petsc-bindgen-rust", "max_issues_repo_head_hexsha": "ec7d92db067964e36e1319619c8773ec210d66f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "wrapper.h", "max_forks_repo_name": "tkonolige/petsc-bindgen-rust", "max_forks_repo_head_hexsha": "ec7d92db067964e36e1319619c8773ec210d66f8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8333333333, "max_line_length": 53, "alphanum_fraction": 0.7572254335, "num_tokens": 45, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25982564942392716, "lm_q2_score": 0.037892426222173245, "lm_q1q2_score": 0.009845424251424411}}
{"text": "#pragma once\n#include <gsl/gsl>\n#include <memory>\nclass BassEnhance;\nclass Eq_5band;\nclass Reverb;\n\nstruct Fx_Parameter {\n    const char *name;\n    int default_value;\n    enum Type { Integer, Boolean };\n    Type type;\n    enum Flag { HasSeparator = 1 };\n    unsigned flags;\n};\n\nclass Synth_Fx {\npublic:\n    Synth_Fx();\n    ~Synth_Fx();\n\n    void init(float sample_rate);\n    void clear();\n    void compute(float data[], unsigned nframes);\n\n    int get_parameter(size_t index) const;\n    void set_parameter(size_t index, int value);\n\n    static gsl::span<const Fx_Parameter> parameters();\n\n    enum {\n        P_Bass_Enhance,\n        P_Bass_Amount,\n        P_Bass_Tone,\n        P_Eq_Enable,\n        P_Eq_Low,\n        P_Eq_Mid_Low,\n        P_Eq_Mid,\n        P_Eq_Mid_High,\n        P_Eq_High,\n        P_Reverb_Enable,\n        P_Reverb_Amount,\n        P_Reverb_Size,\n        Parameter_Count,\n    };\n\nprivate:\n    std::unique_ptr<BassEnhance> be_;\n    std::unique_ptr<Eq_5band> eq_;\n    std::unique_ptr<Reverb> rev_;\n    bool be_enable_ = false;\n    bool eq_enable_ = false;\n    bool rev_enable_ = false;\n};\n", "meta": {"hexsha": "b497dc42768732c0456378be01ecb537afa17896", "size": 1102, "ext": "h", "lang": "C", "max_stars_repo_path": "sources/player/instruments/synth_fx.h", "max_stars_repo_name": "jpcima/smf-dsp", "max_stars_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2020-07-08T15:23:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T23:08:17.000Z", "max_issues_repo_path": "sources/player/instruments/synth_fx.h", "max_issues_repo_name": "jpcima/smf-dsp", "max_issues_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2020-07-05T23:59:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-16T20:44:07.000Z", "max_forks_repo_path": "sources/player/instruments/synth_fx.h", "max_forks_repo_name": "jpcima/smf-dsp", "max_forks_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-07-10T18:48:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-22T08:05:13.000Z", "avg_line_length": 20.0363636364, "max_line_length": 54, "alphanum_fraction": 0.6333938294, "num_tokens": 305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167300566462553, "lm_q2_score": 0.02228618415929719, "lm_q1q2_score": 0.009843205942432156}}
{"text": "/* rng/default.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 James Theiler, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_errno.h>\n\n/* The initial defaults are defined in the file mt.c, so we can get\n   access to the static parts of the default generator. */\n\nconst gsl_rng_type *\ngsl_rng_env_setup (void)\n{\n  unsigned long int seed = 0;\n  const char *p = getenv (\"GSL_RNG_TYPE\");\n\n  if (p)\n    {\n      const gsl_rng_type **t, **t0 = gsl_rng_types_setup ();\n\n      gsl_rng_default = 0;\n\n      /* check GSL_RNG_TYPE against the names of all the generators */\n\n      for (t = t0; *t != 0; t++)\n        {\n          if (strcmp (p, (*t)->name) == 0)\n            {\n              gsl_rng_default = *t;\n              break;\n            }\n        }\n\n      if (gsl_rng_default == 0)\n        {\n          int i = 0;\n\n          fprintf (stderr, \"GSL_RNG_TYPE=%s not recognized\\n\", p);\n          fprintf (stderr, \"Valid generator types are:\\n\");\n\n          for (t = t0; *t != 0; t++)\n            {\n              fprintf (stderr, \" %18s\", (*t)->name);\n\n              if ((++i) % 4 == 0)\n                {\n                  fputc ('\\n', stderr);\n                }\n            }\n\n          fputc ('\\n', stderr);\n\n          GSL_ERROR_VAL (\"unknown generator\", GSL_EINVAL, 0);\n        }\n\n      fprintf (stderr, \"GSL_RNG_TYPE=%s\\n\", gsl_rng_default->name);\n    }\n  else\n    {\n      gsl_rng_default = gsl_rng_mt19937;\n    }\n\n  p = getenv (\"GSL_RNG_SEED\");\n\n  if (p)\n    {\n      seed = strtoul (p, 0, 0);\n      fprintf (stderr, \"GSL_RNG_SEED=%lu\\n\", seed);\n    };\n\n  gsl_rng_default_seed = seed;\n\n  return gsl_rng_default;\n}\n", "meta": {"hexsha": "4b0f80d8749ce6724e34f3ad4a9b17f25fc2d6b4", "size": 2432, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/rng/default.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/rng/default.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/rng/default.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 25.8723404255, "max_line_length": 81, "alphanum_fraction": 0.5867598684, "num_tokens": 658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.320821300824607, "lm_q2_score": 0.030675799052176208, "lm_q1q2_score": 0.009841449755753419}}
{"text": "// Based on code found in https://github.com/deeplearning4j/libnd4j/blob/master/blas/cpu/NativeBlas.cpp\n\n#include <cblas.h>\n\n#ifdef _WIN32\n#include <Windows.h>\n#else\n#include <dlfcn.h>\n#endif\n\nstatic int maxThreads = -1;\nstatic int vendor = 0;\n\nstatic void blas_set_num_threads(int num) {\n    typedef void* (*void_int)(int);\n    typedef int* (*int_int)(int);\n    typedef int* (*int_int_int)(int, int);\n\n    maxThreads = num;\n#ifdef __MKL\n    // if we're linked against mkl - just go for it\n    MKL_Set_Num_Threads(num);\n    MKL_Domain_Set_Num_Threads(num, 0); // MKL_DOMAIN_ALL\n    MKL_Domain_Set_Num_Threads(num, 1); // MKL_DOMAIN_BLAS\n    MKL_Set_Num_Threads_Local(num);\n#elif __OPENBLAS\n#ifdef _WIN32\n    // for win32 we just check for mkl_rt.dll\n    HMODULE handle = LoadLibrary(\"mkl_rt.dll\");\n    if (handle != NULL) {\n        void_int mkl_global = (void_int) GetProcAddress(handle, \"MKL_Set_Num_Threads\");\n        if (mkl_global != NULL) {\n            mkl_global(num);\n\n            vendor = 3;\n\n            int_int_int mkl_domain = (int_int_int) GetProcAddress(handle, \"MKL_Domain_Set_Num_Threads\");\n            if (mkl_domain != NULL) {\n                mkl_domain(num, 0); // DOMAIN_ALL\n                mkl_domain(num, 1); // DOMAIN_BLAS\n            }\n\n            int_int mkl_local = (int_int) GetProcAddress(handle, \"MKL_Set_Num_Threads_Local\");\n            if (mkl_local != NULL) {\n                mkl_local(num);\n            }\n        } else {\n            printf(\"Unable to tune runtime. Please set OMP_NUM_THREADS manually.\\n\");\n        }\n        //FreeLibrary(handle);\n    } else {\n      // OpenBLAS path\n      handle = LoadLibrary(\"libopenblas.dll\");\n      if (handle != NULL) {\n        void_int oblas = (void_int) GetProcAddress(handle, \"openblas_set_num_threads\");\n        if (oblas != NULL) {\n            vendor = 2;\n            oblas(num);\n        } else {\n            printf(\"Unable to tune runtime. Please set OMP_NUM_THREADS manually.\\n\");\n        }\n        //FreeLibrary(handle);\n      } else {\n        printf(\"Unable to guess runtime. Please set OMP_NUM_THREADS manually.\\n\");\n      }\n    }\n#else\n    // it's possible to have MKL being loaded at runtime\n    void *handle = dlopen(\"libmkl_rt.so\", RTLD_NOW|RTLD_GLOBAL);\n    if (handle == NULL) {\n        handle = dlopen(\"libmkl_rt.dylib\", RTLD_NOW|RTLD_GLOBAL);\n    }\n    if (handle != NULL) {\n\n        // we call for openblas only if libmkl isn't loaded, and openblas_set_num_threads exists\n        void_int mkl_global = (void_int) dlsym(handle, \"MKL_Set_Num_Threads\");\n        if (mkl_global != NULL) {\n            // we're running against mkl\n            mkl_global((int) num);\n\n            vendor = 3;\n\n            int_int_int mkl_domain = (int_int_int) dlsym(handle, \"MKL_Domain_Set_Num_Threads\");\n            if (mkl_domain != NULL) {\n                mkl_domain(num, 0); // DOMAIN_ALL\n                mkl_domain(num, 1); // DOMAIN_BLAS\n            }\n\n            int_int mkl_local = (int_int) dlsym(handle, \"MKL_Set_Num_Threads_Local\");\n            if (mkl_local != NULL) {\n                mkl_local(num);\n            }\n        } else {\n            printf(\"Unable to tune runtime. Please set OMP_NUM_THREADS manually.\\n\");\n        }\n        dlclose(handle);\n    } else {\n        // we're falling back to bundled OpenBLAS opening libopenblas.so.0\n        handle = dlopen(\"libopenblas.so.0\", RTLD_NOW|RTLD_GLOBAL);\n        if (handle == NULL) {\n            handle = dlopen(\"libopenblas.so\", RTLD_NOW|RTLD_GLOBAL);\n        }\n        if (handle == NULL) {\n            handle = dlopen(\"libopenblas.dylib\", RTLD_NOW|RTLD_GLOBAL);\n        }\n\n        if (handle != NULL) {\n            void_int oblas = (void_int) dlsym(handle, \"openblas_set_num_threads\");\n            if (oblas != NULL) {\n                vendor = 2;\n                // we're running against openblas\n                oblas((int) num);\n            } else {\n                printf(\"Unable to tune runtime. Please set OMP_NUM_THREADS manually.\\n\");\n            }\n\n            dlclose(handle);\n        } else printf(\"Unable to guess runtime. Please set OMP_NUM_THREADS manually.\\n\");\n    }\n#endif\n\n#else\n    printf(\"Unable to guess runtime. Please set OMP_NUM_THREADS or equivalent manually.\\n\");\n#endif\n    fflush(stdout);\n}\n\n\nstatic int blas_get_num_threads() {\n    return maxThreads;\n}\n\n/**\n *  0 - Unknown\n *  1 - cuBLAS\n *  2 - OpenBLAS\n *  3 - MKL\n */\nstatic int blas_get_vendor() {\n    return vendor;\n}\n", "meta": {"hexsha": "1708246ea9426fa329624b6de003194ba798ad80", "size": 4442, "ext": "h", "lang": "C", "max_stars_repo_path": "openblas/src/main/resources/org/bytedeco/javacpp/include/blas_extra.h", "max_stars_repo_name": "MaxKelsen/javacpp-presets", "max_stars_repo_head_hexsha": "20a13b5220d6be33e37b6c8ed6ea30a35361fafc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-27T01:17:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-27T01:17:09.000Z", "max_issues_repo_path": "openblas/src/main/resources/org/bytedeco/javacpp/include/blas_extra.h", "max_issues_repo_name": "MaxKelsen/javacpp-presets", "max_issues_repo_head_hexsha": "20a13b5220d6be33e37b6c8ed6ea30a35361fafc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "openblas/src/main/resources/org/bytedeco/javacpp/include/blas_extra.h", "max_forks_repo_name": "MaxKelsen/javacpp-presets", "max_forks_repo_head_hexsha": "20a13b5220d6be33e37b6c8ed6ea30a35361fafc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-25T06:48:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T06:48:42.000Z", "avg_line_length": 31.2816901408, "max_line_length": 104, "alphanum_fraction": 0.589149032, "num_tokens": 1161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814501625211, "lm_q2_score": 0.022629202051658248, "lm_q1q2_score": 0.009820653922399345}}
{"text": "/* rng/rng.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 James Theiler, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_rng.h>\n\ngsl_rng *\ngsl_rng_alloc (const gsl_rng_type * T)\n{\n\n  gsl_rng *r = (gsl_rng *) malloc (sizeof (gsl_rng));\n\n  if (r == 0)\n    {\n      GSL_ERROR_VAL (\"failed to allocate space for rng struct\",\n                        GSL_ENOMEM, 0);\n    };\n\n  r->state = malloc (T->size);\n\n  if (r->state == 0)\n    {\n      free (r);         /* exception in constructor, avoid memory leak */\n\n      GSL_ERROR_VAL (\"failed to allocate space for rng state\",\n                        GSL_ENOMEM, 0);\n    };\n\n  r->type = T;\n\n  gsl_rng_set (r, gsl_rng_default_seed);        /* seed the generator */\n\n  return r;\n}\n\nint\ngsl_rng_memcpy (gsl_rng * dest, const gsl_rng * src)\n{\n  if (dest->type != src->type)\n    {\n      GSL_ERROR (\"generators must be of the same type\", GSL_EINVAL);\n    }\n\n  memcpy (dest->state, src->state, src->type->size);\n\n  return GSL_SUCCESS;\n}\n\ngsl_rng *\ngsl_rng_clone (const gsl_rng * q)\n{\n  gsl_rng *r = (gsl_rng *) malloc (sizeof (gsl_rng));\n\n  if (r == 0)\n    {\n      GSL_ERROR_VAL (\"failed to allocate space for rng struct\",\n                        GSL_ENOMEM, 0);\n    };\n\n  r->state = malloc (q->type->size);\n\n  if (r->state == 0)\n    {\n      free (r);         /* exception in constructor, avoid memory leak */\n\n      GSL_ERROR_VAL (\"failed to allocate space for rng state\",\n                        GSL_ENOMEM, 0);\n    };\n\n  r->type = q->type;\n\n  memcpy (r->state, q->state, q->type->size);\n\n  return r;\n}\n\nvoid\ngsl_rng_set (const gsl_rng * r, unsigned long int seed)\n{\n  (r->type->set) (r->state, seed);\n}\n\nunsigned long int\ngsl_rng_max (const gsl_rng * r)\n{\n  return r->type->max;\n}\n\nunsigned long int\ngsl_rng_min (const gsl_rng * r)\n{\n  return r->type->min;\n}\n\nconst char *\ngsl_rng_name (const gsl_rng * r)\n{\n  return r->type->name;\n}\n\nsize_t\ngsl_rng_size (const gsl_rng * r)\n{\n  return r->type->size;\n}\n\nvoid *\ngsl_rng_state (const gsl_rng * r)\n{\n  return r->state;\n}\n\nvoid\ngsl_rng_print_state (const gsl_rng * r)\n{\n  size_t i;\n  unsigned char *p = (unsigned char *) (r->state);\n  const size_t n = r->type->size;\n\n  for (i = 0; i < n; i++)\n    {\n      /* FIXME: we're assuming that a char is 8 bits */\n      printf (\"%.2x\", *(p + i));\n    }\n\n}\n\nvoid\ngsl_rng_free (gsl_rng * r)\n{\n  RETURN_IF_NULL (r);\n  free (r->state);\n  free (r);\n}\n", "meta": {"hexsha": "87ea74c134291a4669d008b6c9e23fd2fc016b20", "size": 3196, "ext": "c", "lang": "C", "max_stars_repo_path": "folding_libs/gsl-1.14/rng/rng.c", "max_stars_repo_name": "parasol-ppl/PPL_utils", "max_stars_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_issues_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/rng/rng.c", "max_issues_repo_name": "skair39/structured", "max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/rng/rng.c", "max_forks_repo_name": "skair39/structured", "max_forks_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 20.6193548387, "max_line_length": 81, "alphanum_fraction": 0.62077597, "num_tokens": 927, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2877678279774722, "lm_q2_score": 0.034100423871780486, "lm_q1q2_score": 0.009813004910693413}}
{"text": "/* bst/gsl_bst_rb.h\n * \n * Copyright (C) 2018 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_BST_RB_H__\n#define __GSL_BST_RB_H__\n\n#include <gsl/gsl_math.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\n#ifndef GSL_BST_RB_MAX_HEIGHT\n#define GSL_BST_RB_MAX_HEIGHT 48\n#endif\n\n/* red-black node */\nstruct gsl_bst_rb_node\n{\n  struct gsl_bst_rb_node *rb_link[2]; /* subtrees */\n  void *rb_data;                      /* pointer to data */\n  unsigned char rb_color;             /* color */\n};\n\n/* red-black tree data structure */\ntypedef struct\n{\n  struct gsl_bst_rb_node *rb_root;   /* tree's root */\n  gsl_bst_cmp_function *rb_compare;  /* comparison function */\n  void *rb_param;                    /* extra argument to |rb_compare| */\n  const gsl_bst_allocator *rb_alloc; /* memory allocator */\n  size_t rb_count;                   /* number of items in tree */\n  unsigned long rb_generation;       /* generation number */\n} gsl_bst_rb_table;\n\n/* red-black traverser structure */\ntypedef struct\n{\n  const gsl_bst_rb_table *rb_table;  /* tree being traversed */\n  struct gsl_bst_rb_node *rb_node;   /* current node in tree */\n  struct gsl_bst_rb_node *rb_stack[GSL_BST_RB_MAX_HEIGHT];\n                                     /* all the nodes above |rb_node| */\n  size_t rb_height;                  /* number of nodes in |rb_parent| */\n  unsigned long rb_generation;       /* generation number */\n} gsl_bst_rb_traverser;\n\n__END_DECLS\n\n#endif /* __GSL_BST_RB_H__ */\n", "meta": {"hexsha": "a581ffe16c38cedccdc57f1078811a040024e832", "size": 2336, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gsl/gsl_bst_rb.h", "max_stars_repo_name": "vinej/sml", "max_stars_repo_head_hexsha": "115c007926ca80d51a37cdf887b5252338d8bc8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/gsl/gsl_bst_rb.h", "max_issues_repo_name": "vinej/sml", "max_issues_repo_head_hexsha": "115c007926ca80d51a37cdf887b5252338d8bc8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gsl/gsl_bst_rb.h", "max_forks_repo_name": "vinej/sml", "max_forks_repo_head_hexsha": "115c007926ca80d51a37cdf887b5252338d8bc8d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5675675676, "max_line_length": 81, "alphanum_fraction": 0.6926369863, "num_tokens": 577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23934933647101647, "lm_q2_score": 0.04084571576400234, "lm_q1q2_score": 0.009776394965797698}}
{"text": "/*! \\file allvars.h\n *  \\brief declares global variables.\n *\n *  This file declares all global variables and structures. Further variables should be added here, and declared as\n *  \\e \\b extern. The actual existence of these variables is provided by the file \\ref allvars.cxx. To produce\n *  \\ref allvars.cxx from \\ref allvars.h, do the following:\n *\n *     \\arg Erase all \\#define's, typedef's, and enum's\n *     \\arg add \\#include \"allvars.h\", delete the \\#ifndef ALLVARS_H conditional\n *     \\arg delete all keywords 'extern'\n *     \\arg delete all struct definitions enclosed in {...}, e.g.\n *        \"extern struct global_data_all_processes {....} All;\"\n *        becomes \"struct global_data_all_processes All;\"\n */\n\n#ifndef ALLVARS_H\n#define ALLVARS_H\n\n#include <cstdio>\n#include <cstdlib>\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <cmath>\n#include <string>\n#include <vector>\n#include <set>\n#include <unordered_set>\n#include <algorithm>\n#include <map>\n#include <unordered_map>\n#include <bitset>\n#include <getopt.h>\n#include <sys/stat.h>\n#include <sys/timeb.h>\n#include <sys/time.h>\n#include <unistd.h>\n\n#include <gsl/gsl_heapsort.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_roots.h>\n\n\n///\\name Include for NBodyFramework library.\n//@{\n///nbody code\n#include <NBody.h>\n///Math code\n#include <NBodyMath.h>\n///Binary KD-Tree code\n#include <KDTree.h>\n///Extra routines that analyze a distribution of particles\n#include <Analysis.h>\n//@}\n\n// ///\\name for checking the endian of floats\n//#include <endianutils.h>\n\n///if using OpenMP API\n#ifdef USEOPENMP\n#include <omp.h>\n#endif\n#include \"ompvar.h\"\n\n///if using HDF API\n#ifdef USEHDF\n#include \"hdf5.h\"\n#endif\n\n///if using ADIOS API\n#ifdef USEADIOS\n#include \"adios.h\"\n#endif\n\n#include \"git_revision.h\"\n\n//#include \"swiftinterface.h\"\n//\n//using namespace Swift;\nusing namespace std;\nusing namespace Math;\nusing namespace NBody;\n\n//-- Structures and external variables\n\n/// \\defgroup PARTTYPES Particle types\n//@{\n#define  GASTYPE 0\n#define  DARKTYPE 1\n#define  DARK2TYPE 2\n#define  DARK3TYPE 3\n#define  STARTYPE 4\n#define  BHTYPE 5\n#define  WINDTYPE 6\n#define  NPARTTYPES 7\n//number of baryon types +1, to store all baryons\n#define  NBARYONTYPES 5\n//@}\n\n/// \\defgroup SEARCHTYPES Specify particle type to be searched, all, dm only, separate\n//@{\n#define  PSTALL 1\n#define  PSTDARK 2\n#define  PSTSTAR 3\n#define  PSTGAS 4\n#define  PSTBH 5\n#define  PSTNOBH 6\n//@}\n\n/// \\defgroup STRUCTURETYPES Specific structure type, allow for other types beside HALO\n//@{\n/// \\todo note that here I have set background group type to a halo structure type but that can be changed\n#define HALOSTYPE 10\n#define HALOCORESTYPE 5\n#define SUBSTYPE 10\n#define WALLSTYPE 1\n#define VOIDSTYPE 2\n#define FILAMENTSTYPE 3\n#define BGTYPE 10\n#define GROUPNOPARENT -1\n#define FOF3DTYPE 7\n#define FOF3DGROUP -2\n//@}\n\n/// \\defgroup FOFTYPES FOF search types\n//@{\n//subsets made\n///call \\ref FOFStreamwithprob\n#define  FOFSTPROB 1\n///6D FOF search but only with outliers\n#define  FOF6DSUBSET 7\n///like \\ref FOFStreamwithprob search but search is limited to nearest physical neighbours\n#define  FOFSTPROBNN 9\n///like \\ref FOFStreamwithprob search but here linking length adjusted by velocity offset, smaller lengths for larger velocity offsets\n#define  FOFSTPROBLX 10\n///like \\ref FOFSTPROBLX but for NN search\n#define  FOFSTPROBNNLX 11\n///like \\ref FOFSTPROBNN but there is not linking length applied just use nearest neighbours\n#define  FOFSTPROBNNNODIST 12\n//for iterative method with FOFStreamwithprob\n//#define  FOFSTPROBIT 13\n#define  FOFSTPROBSCALEELL 13\n//#define  FOFSTPROBIT 13\n#define  FOFSTPROBSCALEELLNN 14\n//solely phase-space tensor core growth substructure search\n#define  FOF6DCORE 6\n\n///phase-space FOF but no subset produced\n#define  FOFSTNOSUBSET 2\n///no subsets made, just 6d (with each 6dfof search using 3d fof velocity dispersion,)\n#define  FOF6DADAPTIVE 3\n///6d fof but only use single velocity dispersion from largest 3d fof object\n#define  FOF6D 4\n///3d search\n#define  FOF3D 5\n///baryon 6D FOF search\n#define FOFBARYON6D 0\n///baryon phase tensor search\n#define FOFBARYONPHASETENSOR 1\n//@}\n\n/// \\defgroup INTERATIVESEARCHPARAMS for iterative subsubstructure search\n//@{\n/// this is minimum particle number size for a subsearch to proceed whereby substructure split up into CELLSPLITNUM new cells\n#define  MINCELLSIZE 100\n#define  CELLSPLITNUM 8\n#define  MINSUBSIZE MINCELLSIZE*CELLSPLITNUM\n#define  MAXSUBLEVEL 8\n/// maximum fraction a cell can take of a halo\n#define  MAXCELLFRACTION 0.1\n//@}\n\n///\\defgroup GRIDTYPES Type of Grid structures\n//@{\n#define  PHYSENGRID 1\n#define  PHASEENGRID 2\n#define  PHYSGRID 3\n//@}\n\n/// \\name Max number of neighbouring cells used in interpolation of background velocity field.\n//@{\n\n//if cells were cubes this would be all the neighbours that full enclose the cube, 6 faces+20 diagonals\n//using daganoals may not be ideal. Furthermore, code using adaptive grid that if effectively produces\n//cell that are rectangular prisms. Furthermore, not all cells will share a boundary with another cell.\n//So just consider \"faces\".\n#define MAXNGRID 6\n\n//@}\n\n///\\defgroup INPUTTYPES defining types of input\n//@{\n#define  NUMINPUTS 5\n#define  IOGADGET 1\n#define  IOHDF 2\n#define  IOTIPSY 3\n#define  IORAMSES 4\n#define  IONCHILADA 5\n//@}\n\n\n///\\defgroup OUTPUTTYPES defining format types of output\n//@{\n#define OUTASCII 0\n#define OUTBINARY 1\n#define OUTHDF 2\n#define OUTADIOS 3\n//@}\n\n///\\defgroup CALCULATIONTYPES defining what is calculated\n//@{\n#define CALCAVERAGE 1\n#define CALCTOTAL 2\n#define CALCSTD 3\n#define CALCMEDIAN 4\n#define CALCMIN 5\n#define CALCMAX 6\n#define CALCLOGAVERAGE 7\n#define CALCLOGSTD 8\n#define CALCQUANTITYMASSWEIGHT 10\n#define CALCAVERAGEMASSWEIGHT 11\n#define CALCTOTALMASSWEIGHT 12\n#define CALCSTDMASSWEIGHT 13\n#define CALCMEDIANMASSWEIGHT 14\n#define CALCMINMASSWEIGHT 15\n#define CALCMAXMASSWEIGHT 16\n#define CALCLOGAVERAGEMASSWEIGHT 17\n#define CALCLOGSTDMASSWEIGHT 18\n#define CALCQUANTITYAPERTURETOTAL -1\n#define CALCQUANTITYAPERTUREAVERAGE -2\ntypedef double (*ExtraPropFunc)(double, double, double&);\n\n//@}\n\n/// \\name For Unbinding\n//@{\n\n///number below which just use PP calculation for potential, which occurs roughly at when n~2*log(n) (from scaling of n^2 vs n ln(n) for PP vs tree and factor of 2 is\n///for extra overhead in producing tree. For reasonable values of n (>100) this occurs at ~100. Here to account for extra memory need for tree, we use n=3*log(n) or 150\n#define UNBINDNUM 150\n#define POTPPCALCNUM 150\n#define POTOMPCALCNUM 1000\n///diferent methods for calculating approximate potential\n#define POTAPPROXMETHODTREE 0\n#define POTAPPROXMETHODRAND 1\n\n///when unbinding check to see if system is bound and least bound particle is also bound\n#define USYSANDPART 0\n///when unbinding check to see if least bound particle is also bound\n#define UPART 1\n///use the bulk centre of mass velocity to define velocity reference frame when determining if particle bound\n#define CMVELREF 0\n///use the particle at potential minimum. Issues if too few particles used as particles will move in and out of deepest point of the potential well\n#define POTREF 1\n///use Centre-of-mass to caculate Properties\n#define PROPREFCM 0\n///use most bound particle to calculate properties\n#define PROPREFMBP 1\n///use minimum potential particle to calculat properties\n#define PROPREFMINPOT 2\n\n//@}\n\n/// \\name For Tree potential calculation\n//@{\n\n///leafflag indicating in tree-calculation of potential, reached a leaf node that does not satisfy mono-pole approx\n#define leafflag 1\n///split flag means node not used as subcells are searched\n#define splitflag -1\n///cellflag means a node that is not necessarily a leaf node can be approximated by mono-pole\n#define cellflag 0\n\n//@}\n\n/// \\defgroup PROPLIMS Particle limits for calculating properties\n//@{\n#define PROPNFWMINNUM 100\n#define PROPCMMINNUM 10\n#define PROPROTMINNUM 10\n#define PROPMORPHMINNUM 10\n//@}\n\n/// \\defgroup PROPERTYCONSTANTS Useful constants related to calculating properties\n//@{\n/// if halo follows NFW profile, maximum ratio of half mass to virial mass one might\n/// expect for R200 (assuming the scale radius is inside this radius, giving a c>=1)\n#define NFWMAXRHALFRATIO 0.60668\n#define NFWMINRHALFRATIO 0.05\n#define NFWMINVMAXVVIRRATIO 36.0\n//@}\n\n\n///\\name halo id modifers used with current snapshot value to make temporally unique halo identifiers\n#ifdef LONGINT\n#define HALOIDSNVAL 1000000000000L\n#else\n#define HALOIDSNVAL 1000000\n#endif\n\n///\\defgroup radial profile parameters\n//@{\n#define PROFILERNORMPHYS 0\n#define PROFILERNORMR200CRIT 1\n#define PROFILERBINTYPELOG 0\n//@}\n\n///\\defgroup GASPARAMS Useful constants for gas\n//@{\n///mass of helium relative to hydrogen\n#define M_HetoM_H 4.0026\n//@}\n\n///\\defgroup PhysConstants Useful physical constants\n//@{\n#define Grav_in_kpc_kms_solarmasses 4.3022682e-6\n//@}\n\n\n/// Structure stores unbinding information\nstruct UnbindInfo\n{\n    ///\\name flag whether unbind groups, keep bg potential when unbinding, type of unbinding and reference frame\n    //@{\n    int unbindflag,bgpot,unbindtype,cmvelreftype;\n    //@}\n    ///boolean as to whether code calculate potentials or potentials are externally provided\n    bool icalculatepotential;\n    ///fraction of potential energy that kinetic energy is allowed to be and consider particle bound\n    Double_t Eratio;\n    ///minimum bound mass fraction\n    Double_t minEfrac;\n    ///when to recalculate kinetic energies if cmvel has changed enough\n    Double_t cmdelta;\n    ///maximum fraction of particles to remove when unbinding in one given unbinding step\n    Double_t maxunbindfrac;\n    ///Maximum fraction of particles that can be considered unbound before group removed entirely\n    Double_t maxunboundfracforiterativeunbind;\n    ///Max allowed unbound fraction to speed up unbinding\n    Double_t maxallowedunboundfrac;\n\n    ///minimum number of particles to use to calculate reference frame if using particles around deepest potential well as reference frame\n    Int_t Npotref;\n    ///fraction of number of particles to use to calculate reference frame if using particles around deepest potential well as reference frame\n    Double_t fracpotref;\n    ///\\name gravity and tree potential calculation;\n    //@{\n    int BucketSize;\n    Double_t TreeThetaOpen;\n    ///softening length\n    Double_t eps;\n    ///whether to calculate approximate potential energy\n    int iapproxpot;\n    ///fraction of particles to subsample\n    Double_t approxpotnumfrac;\n    ///fraction of particles to subsample\n    Double_t approxpotminnum;\n    ///method of subsampling to calculate potential\n    int approxpotmethod;\n    //@}\n    UnbindInfo(){\n        icalculatepotential=true;\n        unbindflag=0;\n        bgpot=1;\n        unbindtype=UPART;\n        cmvelreftype=CMVELREF;\n        cmdelta=0.02;\n        Eratio=1.0;\n        minEfrac=1.0;\n        BucketSize=8;\n        TreeThetaOpen=0.5;\n        eps=0.0;\n        Npotref=20;\n        fracpotref=1.0;\n        maxunbindfrac=0.5;\n        maxunboundfracforiterativeunbind=0.95;\n        maxallowedunboundfrac=0.025;\n        iapproxpot = 0;\n        approxpotnumfrac = 0.1;\n        approxpotminnum = 5000;\n        approxpotmethod = POTAPPROXMETHODTREE;\n    }\n};\n\n/// Structure stores information used when calculating bulk (sub)structure properties\n/// which is used in \\ref substructureproperties.cxx\nstruct PropInfo\n{\n    //interate till this much mass in contained in a spherical region to calculate cm quantities\n    Double_t cmfrac,cmadjustfac;\n\n    PropInfo(){\n        cmfrac=0.1;\n        cmadjustfac=0.7;\n    }\n};\n\n/* Structure to hold the location of a top-level cell. */\nstruct cell_loc {\n\n    /* Coordinates x,y,z */\n    double loc[3];\n\n};\n\n/// Options structure stores useful variables that have user determined values which are altered by \\ref GetArgs in \\ref ui.cxx\nstruct Options\n{\n\n    ///\\name git related info\n    //@{\n    string git_sha1;\n    //@}\n    ///\\name filenames\n    //@{\n    char *fname,*outname,*smname,*pname,*gname;\n    char *ramsessnapname;\n    //@}\n    ///input format\n    int inputtype;\n    ///number of snapshots\n    int num_files,snum;\n    ///if parallel reading, number of files read in parallel\n    int nsnapread;\n    ///for output, specify the formats, ie. many separate files\n    int iseparatefiles;\n    ///for output specify the format HDF, binary or ascii \\ref OUTHDF, \\ref OUTBINARY, \\ref OUTASCII\n    int ibinaryout;\n    ///for extended output allowing extraction of particles\n    int iextendedoutput;\n    /// output extra fields in halo properties\n    int iextrahalooutput;\n    /// calculate and output extra gas fields\n    int iextragasoutput;\n    /// calculate and output extra star fields\n    int iextrastaroutput;\n    /// calculate and output extra bh fields\n    int iextrabhoutput;\n    /// calculate and output extra interloper fields\n    int iextrainterloperoutput;\n    /// calculate subind like properties\n    int isubfindproperties;\n    ///for output, produce subfind like format\n    int isubfindoutput;\n    ///flag indicating that VR is running on the fly\n    bool iontheflyfinding;\n\n    ///disable particle id related output like fof.grp or catalog_group data. Useful if just want halo properties\n    ///and not interested in tracking. Code writes halo properties catalog and exits.\n    int inoidoutput;\n    ///return propery data in in comoving little h units instead of standard physical units\n    int icomoveunit;\n    /// input is a cosmological simulation so can use box sizes, cosmological parameters, etc to set scales\n    int icosmologicalin;\n    /// input buffer size when reading data\n    long long inputbufsize;\n    /// mpi paritcle buffer size when sending input particle information\n    long long mpiparticletotbufsize,mpiparticlebufsize;\n    /// mpi factor by which to multiple the memory allocated, ie: buffer region\n    /// to reduce likelihood of having to expand/allocate new memory\n    Double_t mpipartfac;\n    /// if using parallel output, number of mpi threads to group together\n    int mpinprocswritesize;\n\n    /// mpi number of top level cells used in decomposition\n    /// could be integrated into metis/parmetis eventually\n    /// here this is the number of cells in a singel dimension to total cells\n    /// is this to ^3\n    int mpinumtoplevelcells;\n\n    /// run FOF using OpenMP\n    int iopenmpfof;\n    /// size of openmp FOF region\n    int openmpfofsize;\n\n    ///\\name length,m,v,grav conversion units\n    //@{\n    Double_t lengthinputconversion, massinputconversion, energyinputconversion, internalenergyinputconversion, velocityinputconversion;\n    Double_t SFRinputconversion, metallicityinputconversion, stellarageinputconversion;\n    int istellaragescalefactor, isfrisssfr;\n    Double_t G;\n    Double_t lengthtokpc, velocitytokms, masstosolarmass, energyperunitmass, timetoseconds;\n    Double_t SFRtosolarmassperyear, stellaragetoyrs, metallicitytosolar;\n    //@}\n    ///period (comove)\n    Double_t p;\n    ///\\name scale factor, Hubunit, h, cosmology, virial density. These are used if linking lengths are scaled or trying to define virlevel using the cosmology\n    //@{\n    Double_t a,H,h;\n    Double_t Omega_m, Omega_b, Omega_cdm, Omega_Lambda, Omega_k, Omega_r, Omega_nu, Omega_de, w_de;\n    Double_t rhocrit, rhobg, virlevel, virBN98;\n    int comove;\n    /// to store the internal code unit to kpc and the distance^2 of 30 kpc, and 50 kpc\n    Double_t lengthtokpc30pow2, lengthtokpc50pow2;\n    //@}\n\n    ///to store number of each particle types so that if only searching one particle type, assumes order of gas, dark (halo, disk,bulge), star, special or sink for pfof tipsy style output\n    Int_t numpart[NPARTTYPES];\n\n    ///\\name parameters that control the local and average volumes used to calculate the local velocity density and the mean field, also the size of the leafnode in the kd-tree used when searching the tree for fof neighbours\n    //@{\n    int iLocalVelDenApproxCalcFlag;\n    int Nvel, Nsearch, Bsize;\n    Int_t Ncell;\n    Double_t Ncellfac;\n    //@}\n    ///minimum group size\n    int MinSize;\n    ///allows for field halos to have a different minimum size\n    int HaloMinSize;\n    ///Significance parameter for groups\n    Double_t siglevel;\n\n    ///whether to search for substructures at all\n    int iSubSearch;\n    ///type of search\n    int foftype,fofbgtype;\n    ///grid type, physical, physical+entropy splitting criterion, phase+entropy splitting criterion. Note that this parameter should not be changed from the default value\n    int gridtype;\n    ///flag indicating search all particle types or just dark matter\n    int partsearchtype;\n    ///flag indicating a separate baryonic search is run, looking for all particles that are associated in phase-space\n    ///with dark matter particles that belong to a structure\n    int iBaryonSearch;\n    /// FOF search for baryons\n    int ifofbaryonsearch;\n    ///flag indicating if move to CM frame for substructure search\n    int icmrefadjust;\n    /// flag indicating if CM is interated shrinking spheres\n    int iIterateCM;\n    /// flag to sort output particle lists by binding energy (or potential if not on)\n    int iSortByBindingEnergy;\n    /// what reference position to use when calculating Properties\n    int iPropertyReferencePosition;\n    /// what particle type is used to define reference position\n    int ParticleTypeForRefenceFrame;\n\n\n    ///threshold on particle ELL value, normalized logarithmic distance from predicted maxwellian velocity density.\n    Double_t ellthreshold;\n    ///\\name fofstream search parameters\n    //@{\n    Double_t thetaopen,Vratio,ellphys;\n    //@}\n    ///fof6d search parameters\n    Double_t ellvel;\n    ///scaling for ellphs and ellvel\n    Double_t ellxscale,ellvscale;\n    ///flag to use iterative method\n    int iiterflag;\n    ///\\name factors used to multiply the input values to find initial candidate particles and for mergering groups in interative search\n    //@{\n    Double_t ellfac,ellxfac,vfac,thetafac,nminfac;\n    Double_t fmerge;\n    //@}\n    ///factors to alter halo linking length search (related to substructure search)\n    //@{\n    Double_t ellhalophysfac,ellhalovelfac;\n    //@}\n    ///\\name parameters related to 3DFOF search & subsequent 6DFOF search\n    //@{\n    Double_t ellhalo3dxfac;\n    Double_t ellhalo6dxfac;\n    Double_t ellhalo6dvfac;\n    int iKeepFOF;\n    Int_t num3dfof;\n    //@}\n    //@{\n    ///\\name factors used to check for halo mergers, large background substructures and store the velocity scale when searching for associated baryon substructures\n    //@{\n    Double_t HaloMergerSize,HaloMergerRatio,HaloSigmaV,HaloVelDispScale,HaloLocalSigmaV;\n    Double_t fmergebg;\n    //@}\n    ///flag indicating a single halo is passed or must run search for FOF haloes\n    Int_t iSingleHalo;\n    ///flag indicating haloes are to be check for self-boundness after being searched for substructure\n    Int_t iBoundHalos;\n    /// store denv ratio statistics\n    //@{\n    int idenvflag;\n    Double_t denvstat[3];\n    //@}\n    ///verbose output flag\n    int iverbose;\n    ///whether or not to write a fof.grp tipsy like array file\n    int iwritefof;\n    ///whether mass properties for field objects are inclusive\n    int iInclusiveHalo;\n\n    ///if no mass value stored then store global mass value\n    Double_t MassValue;\n\n    ///structure that contains variables for unbinding\n    UnbindInfo uinfo;\n    ///structure that contains variables for property calculation\n    PropInfo pinfo;\n\n    ///effective resolution for zoom simulations\n    Int_t Neff;\n\n    ///if during substructure search, want to also search for larger substructures\n    //using the more time consuming local velocity calculations (partly in lieu of using the faster core search)\n    int iLargerCellSearch;\n\n    ///\\name extra stuff for halo merger check and identification of multiple halo core and flag for fully adaptive linking length using number density of candidate objects\n    //@{\n    /// run halo core search for mergers\n    int iHaloCoreSearch;\n    ///maximum sublevel at which we search for phase-space cores\n    int maxnlevelcoresearch;\n    ///parameters associated with phase-space search for cores of mergers\n    Double_t halocorexfac, halocorevfac, halocorenfac, halocoresigmafac;\n    ///x and v space linking lengths calculated for each object\n    int iAdaptiveCoreLinking;\n    ///use phase-space tensor core assignment\n    int iPhaseCoreGrowth;\n    ///number of iterations\n    int halocorenumloops;\n    ///factor by which one multiples the configuration space dispersion when looping for cores\n    Double_t halocorexfaciter;\n    ///factor by which one multiples the velocity space dispersion when looping for cores\n    Double_t halocorevfaciter;\n    ///factor by which one multiples the min num when looping for cores\n    Double_t halocorenumfaciter;\n    ///factor by which a core must be seperated from main core in phase-space in sigma units\n    Double_t halocorephasedistsig;\n    ///factor by which a substructure s must be closer than in phase-space to merger with another substructure in sigma units\n    Double_t coresubmergemindist;\n    ///whether substructure phase-space distance merge check is applied to background host halo as well.\n    int icoresubmergewithbg;\n    ///fraction of size a substructure must be of host to be considered a spurious dynamical substructure\n    Double_t minfracsubsizeforremoval;\n    ///Maximum allowed mean local velocity density ratio above which structure is considered highly unrelaxed.\n    Double_t maxmeanlocalvelratio;\n    //@}\n    ///for storing a snapshot value to make halo ids unique across snapshots\n    long long snapshotvalue;\n\n    ///\\name for reading gadget info with lots of extra sph, star and bh blocks\n    //@{\n    int gnsphblocks,gnstarblocks,gnbhblocks;\n    //@}\n\n    /// \\name Extra HDF flags indicating the existence of extra baryonic/dm particle types\n    //@{\n    /// input naming convention\n    int ihdfnameconvention;\n    /// input contains dm particles\n    int iusedmparticles;\n    /// input contains hydro/gas particles\n    int iusegasparticles;\n    /// input contains star particles\n    int iusestarparticles;\n    /// input contains black hole/sink particles\n    int iusesinkparticles;\n    /// input contains wind particles\n    int iusewindparticles;\n    /// input contains tracer particles\n    int iusetracerparticles;\n    /// input contains extra dark type particles\n    int iuseextradarkparticles;\n    //@}\n\n    /// if want full spherical overdensity, factor by which size is multiplied to get\n    ///bucket of particles\n    Double_t SphericalOverdensitySeachFac;\n    ///if want to the particle IDs that are within the SO overdensity of a halo\n    int iSphericalOverdensityPartList;\n    /// if want to include more than just field objects (halos) in full SO calculations\n    int SphericalOverdensitySeachMaxStructLevel;\n    /// flag to store whether SO calculations need extra properties\n    bool iSphericalOverdensityExtraFieldCalculations;\n    /// \\name Extra variables to store information useful in zoom simluations\n    //@{\n    /// store the lowest dark matter particle mass\n    Double_t zoomlowmassdm;\n    //@}\n\n    ///\\name extra runtime flags\n    //@{\n    ///scale lengths. Useful if searching single halo system and which to automatically scale linking lengths\n    int iScaleLengths;\n\n    /// \\name Swift/Metis related quantitites\n    //@{\n    //Swift::siminfo swiftsiminfo;\n\n    double spacedimension[3];\n\n    /* Number of top-level cells. */\n    int numcells;\n\n    /* Number of top-level cells in each dimension. */\n    int numcellsperdim;\n\n    /// minimum number of top-level cells\n    int minnumcellperdim;\n\n    /* Locations of top-level cells. */\n    cell_loc *cellloc;\n\n    /*! Top-level cell width. */\n    double cellwidth[3];\n\n    /*! Inverse of the top-level cell width. */\n    double icellwidth[3];\n\n    /*! Holds the node ID of each top-level cell. */\n    int *cellnodeids;\n\n    /// holds the order of cells based on z-curve decomposition;\n    vector<int> cellnodeorder;\n\n    /// holds the number of particles in a given top-level cell\n    vector<unsigned long long> cellnodenumparts;\n\n    /// allowed mesh based mpi decomposition load imbalance\n    float mpimeshimbalancelimit;\n\n\n    ///whether using mesh decomposition\n    bool impiusemesh;\n\n    //@}\n\n    /// \\name options related to calculation of aperture/profile\n    //@{\n    int iaperturecalc;\n    int aperturenum,apertureprojnum;\n    vector<Double_t> aperture_values_kpc;\n    vector<string> aperture_names_kpc;\n    vector<Double_t> aperture_proj_values_kpc;\n    vector<string> aperture_proj_names_kpc;\n    int iprofilecalc, iprofilenorm, iprofilebintype;\n    int profilenbins;\n    int iprofilecumulative;\n    string profileradnormstring;\n    vector<Double_t> profile_bin_edges;\n    Int_t profileminsize, profileminFOFsize;\n    //@}\n\n    /// \\name options related to calculation of arbitrary overdensities masses, radii, angular momentum\n    //@{\n    int SOnum;\n    vector<Double_t> SOthresholds_values_crit;\n    vector<string> SOthresholds_names_crit;\n    //@}\n\n    /// \\name options related to calculating star forming gas quantities\n    //@{\n    Double_t gas_sfr_threshold;\n    //@}\n\n    /// \\name options related to calculating detailed hydro/star/bh properties related to chemistry/feedbac, etc\n    //@{\n    ///stores the name of the field\n    vector<string> gas_internalprop_names;\n    vector<string> star_internalprop_names;\n    vector<string> bh_internalprop_names;\n\n    ///can also store the dimensional index of the field, useful when single data\n    ///set contains many related but different properties\n    vector<unsigned int> gas_internalprop_index;\n    vector<unsigned int> star_internalprop_index;\n    vector<unsigned int> bh_internalprop_index;\n    ///stores what is calculated\n    ///(1 is mass weighted average, 2 mass weighted total, etc\n    vector<int> gas_internalprop_function;\n    vector<int> star_internalprop_function;\n    vector<int> bh_internalprop_function;\n\n    vector<string> gas_chem_names;\n    vector<string> star_chem_names;\n    vector<string> bh_chem_names;\n    vector<unsigned int> gas_chem_index;\n    vector<unsigned int> star_chem_index;\n    vector<unsigned int> bh_chem_index;\n    vector<int> gas_chem_function;\n    vector<int> star_chem_function;\n    vector<int> bh_chem_function;\n\n    vector<string> gas_chemproduction_names;\n    vector<string> star_chemproduction_names;\n    vector<string> bh_chemproduction_names;\n    vector<unsigned int> gas_chemproduction_index;\n    vector<unsigned int> star_chemproduction_index;\n    vector<unsigned int> bh_chemproduction_index;\n    vector<int> gas_chemproduction_function;\n    vector<int> star_chemproduction_function;\n    vector<int> bh_chemproduction_function;\n\n    vector<string> extra_dm_internalprop_names;\n    vector<unsigned int> extra_dm_internalprop_index;\n    vector<int> extra_dm_internalprop_function;\n\n    ///store the output field name\n    vector<string> gas_internalprop_output_names;\n    vector<string> star_internalprop_output_names;\n    vector<string> bh_internalprop_output_names;\n    vector<string> gas_chem_output_names;\n    vector<string> star_chem_output_names;\n    vector<string> bh_chem_output_names;\n    vector<string> gas_chemproduction_output_names;\n    vector<string> star_chemproduction_output_names;\n    vector<string> bh_chemproduction_output_names;\n    vector<string> extra_dm_internalprop_output_names;\n\n    ///store conversion factor from input unit to output unit\n    vector<float> gas_internalprop_input_output_unit_conversion_factors;\n    vector<float> star_internalprop_input_output_unit_conversion_factors;\n    vector<float> bh_internalprop_input_output_unit_conversion_factors;\n    vector<float> gas_chem_input_output_unit_conversion_factors;\n    vector<float> star_chem_input_output_unit_conversion_factors;\n    vector<float> bh_chem_input_output_unit_conversion_factors;\n    vector<float> gas_chemproduction_input_output_unit_conversion_factors;\n    vector<float> star_chemproduction_input_output_unit_conversion_factors;\n    vector<float> bh_chemproduction_input_output_unit_conversion_factors;\n    vector<float> extra_dm_internalprop_input_output_unit_conversion_factors;\n\n    ///store output units\n    vector<string> gas_internalprop_output_units;\n    vector<string> star_internalprop_output_units;\n    vector<string> bh_internalprop_output_units;\n    vector<string> gas_chem_output_units;\n    vector<string> star_chem_output_units;\n    vector<string> bh_chem_output_units;\n    vector<string> gas_chemproduction_output_units;\n    vector<string> star_chemproduction_output_units;\n    vector<string> bh_chemproduction_output_units;\n    vector<string> extra_dm_internalprop_output_units;\n\n    ///some calculations are multistage and must be paired with\n    ///another calculation in the list. This is true of standard deviations\n    vector<int> gas_internalprop_index_paired_calc;\n    vector<int> star_internalprop_index_paired_calc;\n    vector<int> bh_internalprop_index_paired_calc;\n    vector<int> gas_chem_index_paired_calc;\n    vector<int> star_chem_index_paired_calc;\n    vector<int> bh_chem_index_paired_calc;\n    vector<int> gas_chemproduction_index_paired_calc;\n    vector<int> star_chemproduction_index_paired_calc;\n    vector<int> bh_chemproduction_index_paired_calc;\n    vector<int> extra_dm_internalprop_index_paired_calc;\n\n    ///whether some calculations are for extra properties are aperture calculations\n    bool gas_extraprop_aperture_calc;\n    bool star_extraprop_aperture_calc;\n    bool bh_extraprop_aperture_calc;\n    bool extra_dm_extraprop_aperture_calc;\n\n    ///easier to store information separately internally\n    vector<string> gas_internalprop_names_aperture;\n    vector<string> gas_chem_names_aperture;\n    vector<string> gas_chemproduction_names_aperture;\n    vector<string> star_internalprop_names_aperture;\n    vector<string> star_chem_names_aperture;\n    vector<string> star_chemproduction_names_aperture;\n    vector<string> bh_internalprop_names_aperture;\n    vector<string> bh_chem_names_aperture;\n    vector<string> bh_chemproduction_names_aperture;\n    vector<string> extra_dm_internalprop_names_aperture;\n\n    vector<unsigned int> gas_internalprop_index_aperture;\n    vector<unsigned int> gas_chem_index_aperture;\n    vector<unsigned int> gas_chemproduction_index_aperture;\n    vector<unsigned int> star_internalprop_index_aperture;\n    vector<unsigned int> star_chem_index_aperture;\n    vector<unsigned int> star_chemproduction_index_aperture;\n    vector<unsigned int> bh_internalprop_index_aperture;\n    vector<unsigned int> bh_chem_index_aperture;\n    vector<unsigned int> bh_chemproduction_index_aperture;\n    vector<unsigned int> extra_dm_internalprop_index_aperture;\n\n    vector<int> gas_internalprop_function_aperture;\n    vector<int> gas_chem_function_aperture;\n    vector<int> gas_chemproduction_function_aperture;\n    vector<int> star_internalprop_function_aperture;\n    vector<int> star_chem_function_aperture;\n    vector<int> star_chemproduction_function_aperture;\n    vector<int> bh_internalprop_function_aperture;\n    vector<int> bh_chem_function_aperture;\n    vector<int> bh_chemproduction_function_aperture;\n    vector<int> extra_dm_internalprop_function_aperture;\n\n    vector<string> gas_internalprop_output_units_aperture;\n    vector<string> star_internalprop_output_units_aperture;\n    vector<string> bh_internalprop_output_units_aperture;\n    vector<string> gas_chem_output_units_aperture;\n    vector<string> star_chem_output_units_aperture;\n    vector<string> bh_chem_output_units_aperture;\n    vector<string> gas_chemproduction_output_units_aperture;\n    vector<string> star_chemproduction_output_units_aperture;\n    vector<string> bh_chemproduction_output_units_aperture;\n    vector<string> extra_dm_internalprop_output_units_aperture;\n\n    vector<float> gas_internalprop_input_output_unit_conversion_factors_aperture;\n    vector<float> star_internalprop_input_output_unit_conversion_factors_aperture;\n    vector<float> bh_internalprop_input_output_unit_conversion_factors_aperture;\n    vector<float> gas_chem_input_output_unit_conversion_factors_aperture;\n    vector<float> star_chem_input_output_unit_conversion_factors_aperture;\n    vector<float> bh_chem_input_output_unit_conversion_factors_aperture;\n    vector<float> gas_chemproduction_input_output_unit_conversion_factors_aperture;\n    vector<float> star_chemproduction_input_output_unit_conversion_factors_aperture;\n    vector<float> bh_chemproduction_input_output_unit_conversion_factors_aperture;\n    vector<float> extra_dm_internalprop_input_output_unit_conversion_factors_aperture;\n\n    vector<string> gas_internalprop_output_names_aperture;\n    vector<string> gas_chem_output_names_aperture;\n    vector<string> gas_chemproduction_output_names_aperture;\n    vector<string> star_internalprop_output_names_aperture;\n    vector<string> star_chem_output_names_aperture;\n    vector<string> star_chemproduction_output_names_aperture;\n    vector<string> bh_internalprop_output_names_aperture;\n    vector<string> bh_chem_output_names_aperture;\n    vector<string> bh_chemproduction_output_names_aperture;\n    vector<string> extra_dm_internalprop_output_names_aperture;\n\n    //to store the unique names that are going to be loaded from the input\n    vector<string> gas_internalprop_unique_input_names;\n    vector<string> gas_chem_unique_input_names;\n    vector<string> gas_chemproduction_unique_input_names;\n    vector<string> star_internalprop_unique_input_names;\n    vector<string> star_chem_unique_input_names;\n    vector<string> star_chemproduction_unique_input_names;\n    vector<string> bh_internalprop_unique_input_names;\n    vector<string> bh_chem_unique_input_names;\n    vector<string> bh_chemproduction_unique_input_names;\n    vector<string> extra_dm_internalprop_unique_input_names;\n\n    vector<unsigned short> gas_internalprop_unique_input_indexlist;\n    vector<unsigned short> gas_chem_unique_input_indexlist;\n    vector<unsigned short> gas_chemproduction_unique_input_indexlist;\n    vector<unsigned short> star_internalprop_unique_input_indexlist;\n    vector<unsigned short> star_chem_unique_input_indexlist;\n    vector<unsigned short> star_chemproduction_unique_input_indexlist;\n    vector<unsigned short> bh_internalprop_unique_input_indexlist;\n    vector<unsigned short> bh_chem_unique_input_indexlist;\n    vector<unsigned short> bh_chemproduction_unique_input_indexlist;\n    vector<unsigned short> extra_dm_internalprop_unique_input_indexlist;\n\n    //@}\n\n    /// \\name memory related info\n    //@{\n    unsigned long long memuse_peak;\n    unsigned long long memuse_ave;\n    int memuse_nsamples;\n    bool memuse_log;\n    //@}\n\n    //silly flag to store whether input has little h's in it.\n    bool inputcontainslittleh;\n\n    Options()\n    {\n        lengthinputconversion = 1.0;\n        massinputconversion = 1.0;\n        velocityinputconversion = 1.0;\n        SFRinputconversion = 1.0;\n        metallicityinputconversion = 1.0;\n        energyinputconversion = 1.0;\n        stellarageinputconversion =1.0;\n        istellaragescalefactor = 1;\n        isfrisssfr = 0;\n\n        G = 0.0;\n        p = 0.0;\n\n        a = 1.0;\n        H = 0.;\n        h = 1.0;\n        Omega_m = 1.0;\n        Omega_Lambda = 0.0;\n        Omega_b = 0.0;\n        Omega_cdm = Omega_m;\n        Omega_k = 0;\n        Omega_r = 0.0;\n        Omega_nu = 0.0;\n        Omega_de = 0.0;\n        w_de = -1.0;\n        rhobg = 1.0;\n        virlevel = -1;\n        comove=0;\n        MassValue=-1.0;\n\n        inputtype=IOGADGET;\n\n        num_files=1;\n        nsnapread=1;\n\n        fname=outname=smname=pname=gname=outname=NULL;\n\n        Bsize=32;\n        Nvel=32;\n        Nsearch=256;\n        Ncellfac=0.01;\n\n        iSubSearch=1;\n        partsearchtype=PSTALL;\n        for (int i=0;i<NPARTTYPES;i++)numpart[i]=0;\n        foftype=FOFSTPROB;\n        gridtype=PHYSENGRID;\n        fofbgtype=FOF6D;\n        idenvflag=0;\n        iBaryonSearch=0;\n        icmrefadjust=1;\n        iIterateCM = 1;\n        iLocalVelDenApproxCalcFlag = 2 ;\n\n        Neff=-1;\n\n\n        ellthreshold=1.5;\n        thetaopen=0.05;\n        Vratio=1.25;\n        ellphys=0.2;\n        MinSize=20;\n        HaloMinSize=-1;\n        siglevel=2.0;\n        ellvel=0.5;\n        ellxscale=ellvscale=1.0;\n        ellhalophysfac=ellhalovelfac=1.0;\n        ellhalo6dxfac=1.0;\n        ellhalo6dvfac=1.25;\n        ellhalo3dxfac=-1.0;\n\n        iiterflag=0;\n        ellfac=2.5;\n        ellxfac=3.0;\n        vfac=1.0;\n        thetafac=1.0;\n        nminfac=0.5;\n        fmerge=0.25;\n\n        HaloMergerSize=10000;\n        HaloMergerRatio=0.2;\n        HaloVelDispScale=0;\n        fmergebg=0.5;\n        iSingleHalo=0;\n        iBoundHalos=0;\n        iInclusiveHalo=0;\n        iKeepFOF=0;\n        iSortByBindingEnergy=1;\n        iPropertyReferencePosition=PROPREFCM;\n        ParticleTypeForRefenceFrame=-1;\n\n        iLargerCellSearch=0;\n\n        iHaloCoreSearch=0;\n        iAdaptiveCoreLinking=0;\n        iPhaseCoreGrowth=1;\n        maxnlevelcoresearch=5;\n        halocorexfac=0.5;\n        halocorevfac=2.0;\n        halocorenfac=0.1;\n        halocoresigmafac=2.0;\n        halocorenumloops=3;\n        halocorexfaciter=0.75;\n        halocorevfaciter=0.75;\n        halocorenumfaciter=1.0;\n        halocorephasedistsig=2.0;\n        coresubmergemindist=0.0;\n        icoresubmergewithbg=0;\n        minfracsubsizeforremoval=0.75;\n        maxmeanlocalvelratio=0.5;\n\n        iverbose=0;\n        iwritefof=0;\n        iseparatefiles=0;\n        ibinaryout=0;\n        iextendedoutput=0;\n        isubfindoutput=0;\n        inoidoutput=0;\n        icomoveunit=0;\n        icosmologicalin=1;\n\n        iextrahalooutput=0;\n        iextragasoutput=0;\n        iextrastaroutput=0;\n        iextrainterloperoutput=0;\n        isubfindproperties=0;\n\n        iusedmparticles=1;\n        iusegasparticles=1;\n        iusestarparticles=1;\n        iusesinkparticles=1;\n        iusewindparticles=0;\n        iusetracerparticles=0;\n#ifdef HIGHRES\n        iuseextradarkparticles=1;\n#else\n        iuseextradarkparticles=0;\n#endif\n\n        snapshotvalue=0;\n\n        gnsphblocks=4;\n        gnstarblocks=2;\n        gnbhblocks=2;\n\n        iScaleLengths=0;\n\n        inputbufsize=1000000;\n\n        mpiparticletotbufsize=-1;\n        mpiparticlebufsize=-1;\n        mpinprocswritesize=1;\n#ifdef SWIFTINTERFACE\n        impiusemesh = true;\n#else\n        impiusemesh = true;\n        mpimeshimbalancelimit = 0.1;\n        minnumcellperdim = 8;\n#endif\n        cellnodeids = NULL;\n\n        lengthtokpc=-1.0;\n        velocitytokms=-1.0;\n        masstosolarmass=-1.0;\n#if defined(GASON) || defined(STARON) || defined(BHON)\n        SFRtosolarmassperyear=-1.0;\n        stellaragetoyrs=-1.0;\n        metallicitytosolar=-1.0;\n#endif\n\n\n        lengthtokpc30pow2=30.0*30.0;\n        lengthtokpc50pow2=50.0*50.0;\n\n        SphericalOverdensitySeachFac=2.5;\n        iSphericalOverdensityPartList=0;\n        SphericalOverdensitySeachMaxStructLevel = HALOSTYPE;\n        iSphericalOverdensityExtraFieldCalculations = false;\n\n        mpipartfac=0.1;\n#if USEHDF\n        ihdfnameconvention=-1;\n#endif\n        iaperturecalc=0;\n        aperturenum=0;\n        apertureprojnum=0;\n        SOnum=0;\n\n        iprofilecalc=0;\n        iprofilenorm=PROFILERNORMR200CRIT;\n        iprofilebintype=PROFILERBINTYPELOG;\n        iprofilecumulative=0;\n        profilenbins=0;\n        profileminsize = profileminFOFsize = 0;\n#ifdef USEOPENMP\n        iopenmpfof = 1;\n        openmpfofsize = ompfofsearchnum;\n#endif\n\n        iontheflyfinding = false;\n\n        memuse_peak = 0;\n        memuse_ave = 0;\n        memuse_nsamples = 0;\n        memuse_log = false;\n\n        inputcontainslittleh = true;\n\n    }\n    Options(Options &opt) = default;\n    Options& operator=(const Options&) = default;\n    Options& operator=(Options&&) = default;\n};\n\nstruct ConfigInfo{\n    //list the name of the info\n    vector<string> nameinfo;\n    vector<string> datainfo;\n    vector<string> datatype;\n\n    string python_type_string(bool &x){return string(\"bool\");}\n    string python_type_string(int &x){return string(\"int32\");}\n    string python_type_string(unsigned int &x){return string(\"uint32\");}\n    string python_type_string(long long &x){return string(\"int64\");}\n    string python_type_string(unsigned long long &x){return string(\"uint64\");}\n    string python_type_string(float &x){return string(\"float32\");}\n    string python_type_string(double &x){return string(\"float64\");}\n    string python_type_string(string &x){return string(\"str\");}\n\n    void AddEntry(string entryname){\n        nameinfo.push_back(entryname);\n        datainfo.push_back(\"\");\n        datatype.push_back(\"\");\n    }\n    template<typename T> void AddEntry(string entryname, T entry){\n        nameinfo.push_back(entryname);\n        datainfo.push_back(to_string(entry));\n        datatype.push_back(python_type_string(entry));\n    }\n    template<typename T> void AddEntry(string entryname, vector<T> entries){\n        if (entries.size() == 0) return;\n        T val = entries[0];\n        nameinfo.push_back(entryname);\n        string datastring=string(\"\");\n        for (auto &x:entries) {datastring+=to_string(x);datastring+=string(\",\");}\n        datainfo.push_back(datastring);\n        datatype.push_back(python_type_string(val));\n    }\n    template<typename T> void AddEntry(string entryname, vector<T> entries1, vector<T> entries2){\n        if (entries1.size() + entries2.size() == 0) return;\n        T val = entries1[0];\n        nameinfo.push_back(entryname);\n        string datastring=string(\"\");\n        for (auto &x:entries1) {datastring+=to_string(x);datastring+=string(\",\");}\n        for (auto &x:entries2) {datastring+=to_string(x);datastring+=string(\",\");}\n        datainfo.push_back(datastring);\n        datatype.push_back(python_type_string(val));\n    }\n    void AddEntry(string entryname, string entry){\n        nameinfo.push_back(entryname);\n        datainfo.push_back(entry);\n        datatype.push_back(python_type_string(entry));\n    }\n    void AddEntry(string entryname, vector<string> entries){\n        if (entries.size() == 0) return;\n        string val = entries[0];\n        nameinfo.push_back(entryname);\n        string datastring=string(\"\");\n        for (auto &x:entries) {datastring+=x;datastring+=string(\",\");}\n        datainfo.push_back(datastring);\n        datatype.push_back(python_type_string(val));\n    }\n    void AddEntry(string entryname, vector<string> entries1, vector<string> entries2){\n        if (entries1.size() + entries2.size() == 0) return;\n        string val = entries1[0];\n        nameinfo.push_back(entryname);\n        string datastring=string(\"\");\n        for (auto &x:entries1) {datastring+=x;datastring+=string(\",\");}\n        for (auto &x:entries2) {datastring+=x;datastring+=string(\",\");}\n        datainfo.push_back(datastring);\n        datatype.push_back(python_type_string(val));\n    }\n\n    ConfigInfo(Options &opt);\n};\n\nstruct SimInfo{\n    //list the name of the info\n    vector<string> nameinfo;\n    vector<string> datainfo;\n    vector<string> datatype;\n\n    string python_type_string(int &x){return string(\"int32\");}\n    string python_type_string(unsigned int &x){return string(\"uint32\");}\n    string python_type_string(long &x){return string(\"int64\");}\n    string python_type_string(unsigned long &x){return string(\"uint64\");}\n    string python_type_string(float &x){return string(\"float32\");}\n    string python_type_string(double &x){return string(\"float64\");}\n\n    SimInfo(Options &opt){\n        //if compiler is super old and does not have at least std 11 implementation to_string does not exist\n#ifndef OLDCCOMPILER\n        nameinfo.push_back(\"Cosmological_Sim\");\n        datainfo.push_back(to_string(opt.icosmologicalin));\n        datatype.push_back(python_type_string(opt.icosmologicalin));\n        if (opt.icosmologicalin) {\n            nameinfo.push_back(\"ScaleFactor\");\n            datainfo.push_back(to_string(opt.a));\n            datatype.push_back(python_type_string(opt.a));\n            nameinfo.push_back(\"h_val\");\n            datainfo.push_back(to_string(opt.h));\n            datatype.push_back(python_type_string(opt.h));\n            nameinfo.push_back(\"Omega_m\");\n            datainfo.push_back(to_string(opt.Omega_m));\n            datatype.push_back(python_type_string(opt.Omega_m));\n            nameinfo.push_back(\"Omega_Lambda\");\n            datainfo.push_back(to_string(opt.Omega_Lambda));\n            datatype.push_back(python_type_string(opt.Omega_Lambda));\n            nameinfo.push_back(\"Omega_cdm\");\n            datainfo.push_back(to_string(opt.Omega_cdm));\n            datatype.push_back(python_type_string(opt.Omega_cdm));\n            nameinfo.push_back(\"Omega_b\");\n            datainfo.push_back(to_string(opt.Omega_b));\n            datatype.push_back(python_type_string(opt.Omega_b));\n            nameinfo.push_back(\"w_of_DE\");\n            datainfo.push_back(to_string(opt.w_de));\n            datatype.push_back(python_type_string(opt.w_de));\n            nameinfo.push_back(\"Period\");\n            datainfo.push_back(to_string(opt.p));\n            datatype.push_back(python_type_string(opt.p));\n            nameinfo.push_back(\"Hubble_unit\");\n            datainfo.push_back(to_string(opt.H));\n            datatype.push_back(python_type_string(opt.H));\n        }\n        else{\n            nameinfo.push_back(\"Time\");\n            datainfo.push_back(to_string(opt.a));\n            datatype.push_back(python_type_string(opt.a));\n            nameinfo.push_back(\"Period\");\n            datainfo.push_back(to_string(opt.p));\n            datatype.push_back(python_type_string(opt.p));\n        }\n\n        //units\n        nameinfo.push_back(\"Length_unit\");\n        datainfo.push_back(to_string(opt.lengthinputconversion));\n        datatype.push_back(python_type_string(opt.lengthinputconversion));\n        nameinfo.push_back(\"Velocity_unit\");\n        datainfo.push_back(to_string(opt.velocityinputconversion));\n        datatype.push_back(python_type_string(opt.velocityinputconversion));\n        nameinfo.push_back(\"Mass_unit\");\n        datainfo.push_back(to_string(opt.massinputconversion));\n        datatype.push_back(python_type_string(opt.massinputconversion));\n        nameinfo.push_back(\"Gravity\");\n        datainfo.push_back(to_string(opt.G));\n        datatype.push_back(python_type_string(opt.G));\n#ifdef NOMASS\n        nameinfo.push_back(\"Mass_value\");\n        datainfo.push_back(to_string(opt.MassValue));\n        datatype.push_back(python_type_string(opt.MassValue));\n#endif\n\n#endif\n    }\n};\n\n\nstruct UnitInfo{\n    //list the name of the info\n    vector<string> nameinfo;\n    vector<string> datainfo;\n    vector<string> datatype;\n\n    string python_type_string(int &x){return string(\"int32\");}\n    string python_type_string(unsigned int &x){return string(\"uint32\");}\n    string python_type_string(long &x){return string(\"int64\");}\n    string python_type_string(unsigned long &x){return string(\"uint64\");}\n    string python_type_string(float &x){return string(\"float32\");}\n    string python_type_string(double &x){return string(\"float64\");}\n\n    UnitInfo(Options &opt){\n        //if compiler is super old and does not have at least std 11 implementation to_string does not exist\n#ifndef OLDCCOMPILER\n        nameinfo.push_back(\"Cosmological_Sim\");\n        datainfo.push_back(to_string(opt.icosmologicalin));\n        datatype.push_back(python_type_string(opt.icosmologicalin));\n        nameinfo.push_back(\"Comoving_or_Physical\");\n        datainfo.push_back(to_string(opt.icomoveunit));\n        datatype.push_back(python_type_string(opt.icomoveunit));\n        //units\n        nameinfo.push_back(\"Length_unit_to_kpc\");\n        datainfo.push_back(to_string(opt.lengthtokpc));\n        datatype.push_back(python_type_string(opt.lengthtokpc));\n        nameinfo.push_back(\"Velocity_unit_to_kms\");\n        datainfo.push_back(to_string(opt.velocitytokms));\n        datatype.push_back(python_type_string(opt.velocitytokms));\n        nameinfo.push_back(\"Mass_unit_to_solarmass\");\n        datainfo.push_back(to_string(opt.masstosolarmass));\n        datatype.push_back(python_type_string(opt.masstosolarmass));\n#if defined(GASON) || defined(STARON) || defined(BHON)\n        nameinfo.push_back(\"Metallicity_unit_to_solar\");\n        datainfo.push_back(to_string(opt.metallicitytosolar));\n        datatype.push_back(python_type_string(opt.metallicitytosolar));\n        nameinfo.push_back(\"SFR_unit_to_solarmassperyear\");\n        datainfo.push_back(to_string(opt.SFRtosolarmassperyear));\n        datatype.push_back(python_type_string(opt.SFRtosolarmassperyear));\n        nameinfo.push_back(\"Stellar_age_unit_to_yr\");\n        datainfo.push_back(to_string(opt.stellaragetoyrs));\n        datatype.push_back(python_type_string(opt.stellaragetoyrs));\n#endif\n#endif\n    }\n};\n\n/// N-dim grid cell\nstruct GridCell\n{\n    int ndim;\n    Int_t gid;\n    //middle of cell, and boundaries of cell\n    Double_t xm[6], xbl[6],xbu[6];\n    //mass, radial size of in cell\n    Double_t mass, rsize;\n    //number of particles in cell\n    Int_t nparts,*nindex;\n    //neighbouring grid cells and distance from cell centers\n    Int_t nnidcells[MAXNGRID];\n    Double_t nndist[MAXNGRID];\n    Double_t den;\n    GridCell(int N=3){\n        ndim=N;\n        nparts=0;\n        den=0;\n    }\n    ~GridCell(){\n        if (nparts>0)delete[] nindex;\n    }\n};\n\n/*! structure stores bulk properties like\n    \\f$ m,\\ (x,y,z)_{\\rm cm},\\ (vx,vy,vz)_{\\rm cm},\\ V_{\\rm max},\\ R_{\\rm max}, \\f$\n    which is calculated in \\ref substructureproperties.cxx\n*/\nstruct PropData\n{\n    ///\\name order in structure hierarchy and number of subhaloes\n    //@{\n    long long haloid,hostid,directhostid, hostfofid;\n    Int_t numsubs;\n    //@}\n\n    ///\\name properties of total object including DM, gas, stars, bh, etc\n    //@{\n    ///number of particles\n    Int_t num;\n    ///number of particles in FOF envelop\n    Int_t gNFOF,gN6DFOF;\n    ///centre of mass\n    Coordinate gcm, gcmvel;\n    ///Position of most bound particle, and also of particle with min potential\n    Coordinate gposmbp, gvelmbp, gposminpot, gvelminpot;\n    ///\\name physical properties regarding mass, size\n    //@{\n    Double_t gmass,gsize,gMvir,gRvir,gRcm,gRmbp,gRminpot,gmaxvel,gRmaxvel,gMmaxvel,gRhalfmass,gMassTwiceRhalfmass;\n    Double_t gM200c,gR200c,gM200m,gR200m,gMFOF,gM6DFOF,gM500c,gR500c,gMBN98,gRBN98;\n    //to store exclusive masses of halo ignoring substructure\n    Double_t gMvir_excl,gRvir_excl,gM200c_excl,gR200c_excl,gM200m_excl,gR200m_excl,gMBN98_excl,gRBN98_excl;\n    //to store halfmass radii of overdensity masses\n    Double_t gRhalf200c,gRhalf200m,gRhalfBN98;\n\n    //@}\n    ///\\name physical properties for shape/mass distribution\n    //@{\n    ///axis ratios\n    Double_t gq,gs;\n    ///eigenvector\n    Matrix geigvec;\n    //@}\n    ///\\name physical properties for velocity\n    //@{\n    ///velocity dispersion\n    Double_t gsigma_v;\n    ///dispersion tensor\n    Matrix gveldisp;\n    //@}\n    ///physical properties for dynamical state\n    Double_t Efrac,Pot,T;\n    ///physical properties for angular momentum\n    Coordinate gJ;\n    Coordinate gJ200m, gJ200c, gJBN98;\n    ///physical properties for angular momentum exclusive\n    Coordinate gJ200m_excl, gJ200c_excl, gJBN98_excl;\n    ///Keep track of position of least unbound particle and most bound particle pid and minimum potential\n    Int_t iunbound,ibound, iminpot;\n    ///Type of structure\n    int stype;\n    ///concentration (and related quantity used to calculate a concentration)\n    Double_t cNFW, VmaxVvir2;\n    Double_t cNFW200c, cNFW200m, cNFWBN98;\n    /// if fitting mass profiles with generalized NFW\n    Double_t NFWfitrs, NFWfitalpha, NFWfitbeta;\n    ///Bullock & Peebles spin parameters\n    Double_t glambda_B,glambda_P;\n    ///measure of rotational support\n    Double_t Krot;\n    //@}\n\n    ///\\name halo properties within RVmax\n    //@{\n    Double_t RV_q,RV_s;\n    Matrix RV_eigvec;\n    Double_t RV_sigma_v;\n    Matrix RV_veldisp;\n    Coordinate RV_J;\n    Double_t RV_lambda_B,RV_lambda_P;\n    Double_t RV_Krot;\n    //@}\n\n    ///\\name aperture quantities/ radial profiles\n    //@{\n    vector<unsigned int> aperture_npart;\n    vector<float> aperture_mass;\n    vector<float> aperture_veldisp;\n    vector<float> aperture_vrdisp;\n    vector<float> aperture_rhalfmass;\n    vector<Coordinate> aperture_mass_proj;\n    vector<Coordinate> aperture_rhalfmass_proj;\n    vector<Coordinate> aperture_L;\n    vector<unsigned int> profile_npart;\n    vector<unsigned int> profile_npart_inclusive;\n    vector<float> profile_mass;\n    vector<float> profile_mass_inclusive;\n    vector<Coordinate> profile_L;\n    #if defined(GASON) || defined(STARON) || defined(BHON)\n    vector<unsigned int> aperture_npart_dm;\n    vector<float> aperture_mass_dm;\n    vector<float> aperture_veldisp_dm;\n    vector<float> aperture_vrdisp_dm;\n    vector<float> aperture_rhalfmass_dm;\n    #endif\n    //@}\n\n    vector<Double_t> SO_mass, SO_radius;\n    vector<Coordinate> SO_angularmomentum;\n\n#ifdef GASON\n    ///\\name gas specific quantities\n    //@{\n    ///number of particles\n    int n_gas;\n    ///mass\n    Double_t M_gas, M_gas_rvmax, M_gas_30kpc, M_gas_50kpc, M_gas_500c;\n    ///mass in spherical overdensities\n    Double_t M_200crit_gas, M_200mean_gas, M_BN98_gas;\n    ///mass in spherical overdensities inclusive of all masses\n    Double_t M_200crit_excl_gas, M_200mean_excl_gas, M_BN98_excl_gas;\n    ///pos/vel info\n    Coordinate cm_gas,cmvel_gas;\n    ///velocity/angular momentum info\n    Double_t Krot_gas;\n    Coordinate L_gas;\n    ///physical properties for angular momentum (can be inclusive or exclusive )\n    Coordinate L_200crit_gas, L_200mean_gas, L_BN98_gas;\n    ///physical properties for angular momentum exclusiveto object\n    Coordinate L_200crit_excl_gas, L_200mean_excl_gas, L_BN98_excl_gas;\n    //dispersion\n    Matrix veldisp_gas;\n    ///morphology\n    Double_t MassTwiceRhalfmass_gas, Rhalfmass_gas, q_gas, s_gas;\n    Matrix eigvec_gas;\n    ///mass weighted sum of temperature, metallicty, star formation rate\n    Double_t Temp_gas, Z_gas, SFR_gas;\n    ///mean temperature,metallicty,star formation rate\n    Double_t Temp_mean_gas, Z_mean_gas, SFR_mean_gas;\n    ///physical properties for dynamical state\n    Double_t Efrac_gas, Pot_gas, T_gas;\n    //@}\n\n    ///\\name gas aperture quantities/ radial profiles\n    //@{\n    vector<unsigned int> aperture_npart_gas;\n    vector<float> aperture_mass_gas;\n    vector<float> aperture_veldisp_gas;\n    vector<float> aperture_vrdisp_gas;\n    vector<float> aperture_SFR_gas;\n    vector<float> aperture_Z_gas;\n    vector<float> aperture_rhalfmass_gas;\n    vector<Coordinate> aperture_L_gas;\n    vector<Coordinate> aperture_mass_proj_gas;\n    vector<Coordinate> aperture_rhalfmass_proj_gas;\n    vector<Coordinate> aperture_SFR_proj_gas;\n    vector<Coordinate> aperture_Z_proj_gas;\n    vector<unsigned int> profile_npart_gas;\n    vector<unsigned int> profile_npart_inclusive_gas;\n    vector<float> profile_mass_gas;\n    vector<float> profile_mass_inclusive_gas;\n    vector<Coordinate> profile_L_gas;\n    //@}\n\n    vector<Double_t> SO_mass_gas;\n    vector<Coordinate> SO_angularmomentum_gas;\n#ifdef STARON\n    ///\\name star forming gas specific quantities\n    //@{\n    ///number of particles\n    int n_gas_sf;\n    ///mass\n    Double_t M_gas_sf, M_gas_sf_rvmax,M_gas_sf_30kpc,M_gas_sf_50kpc, M_gas_sf_500c;\n    ///mass in spherical overdensities\n    Double_t M_200crit_gas_sf, M_200mean_gas_sf, M_BN98_gas_sf;\n    ///mass in spherical overdensities inclusive of all masses\n    Double_t M_200crit_excl_gas_sf, M_200mean_excl_gas_sf, M_BN98_excl_gas_sf;\n    ///velocity/angular momentum info\n    Double_t Krot_gas_sf;\n    Coordinate L_gas_sf;\n    ///physical properties for angular momentum (can be inclusive or exclusive )\n    Coordinate L_200crit_gas_sf, L_200mean_gas_sf, L_BN98_gas_sf;\n    ///physical properties for angular momentum exclusiveto object\n    Coordinate L_200crit_excl_gas_sf, L_200mean_excl_gas_sf, L_BN98_excl_gas_sf;\n    //dispersion\n    Double_t sigV_gas_sf;\n    ///morphology\n    Double_t MassTwiceRhalfmass_gas_sf, Rhalfmass_gas_sf, q_gas_sf, s_gas_sf;\n    ///mass weighted sum of temperature, metallicty, star formation rate\n    Double_t Temp_gas_sf, Z_gas_sf, SFR_gas_sf;\n    ///mean temperature,metallicty,star formation rate\n    Double_t Temp_mean_gas_sf, Z_mean_gas_sf, SFR_mean_gas_sf;\n    //@}\n\n    ///\\name gas star forming aperture quantities/ radial profiles\n    //@{\n    vector<unsigned int> aperture_npart_gas_sf;\n    vector<float> aperture_mass_gas_sf;\n    vector<float> aperture_veldisp_gas_sf;\n    vector<float> aperture_vrdisp_gas_sf;\n    vector<float> aperture_rhalfmass_gas_sf;\n    vector<float> aperture_Z_gas_sf;\n    vector<Coordinate> aperture_L_gas_sf;\n    vector<Coordinate> aperture_mass_proj_gas_sf;\n    vector<Coordinate> aperture_rhalfmass_proj_gas_sf;\n    vector<Coordinate> aperture_Z_proj_gas_sf;\n    vector<unsigned int> profile_npart_gas_sf;\n    vector<unsigned int> profile_npart_inclusive_gas_sf;\n    vector<float> profile_mass_gas_sf;\n    vector<float> profile_mass_inclusive_gas_sf;\n    vector<Coordinate> profile_L_gas_sf;\n    //@}\n\n    vector<Double_t> SO_mass_gas_sf;\n    vector<Coordinate> SO_angularmomentum_gas_sf;\n\n    ///\\name star forming gas specific quantities\n    //@{\n    ///number of particles\n    int n_gas_nsf;\n    ///mass\n    Double_t M_gas_nsf, M_gas_nsf_rvmax,M_gas_nsf_30kpc,M_gas_nsf_50kpc, M_gas_nsf_500c;\n    ///mass in spherical overdensities\n    Double_t M_200crit_gas_nsf, M_200mean_gas_nsf, M_BN98_gas_nsf;\n    ///mass in spherical overdensities inclusive of all masses\n    Double_t M_200crit_excl_gas_nsf, M_200mean_excl_gas_nsf, M_BN98_excl_gas_nsf;\n    ///velocity/angular momentum info\n    Double_t Krot_gas_nsf;\n    Coordinate L_gas_nsf;\n    ///physical properties for angular momentum (can be inclusive or exclusive )\n    Coordinate L_200crit_gas_nsf, L_200mean_gas_nsf, L_BN98_gas_nsf;\n    ///physical properties for angular momentum exclusiveto object\n    Coordinate L_200crit_excl_gas_nsf, L_200mean_excl_gas_nsf, L_BN98_excl_gas_nsf;\n    //dispersion\n    Double_t sigV_gas_nsf;\n    ///morphology\n    Double_t MassTwiceRhalfmass_gas_nsf, Rhalfmass_gas_nsf, q_gas_nsf, s_gas_nsf;\n    ///mass weighted sum of temperature, metallicty, star formation rate\n    Double_t Temp_gas_nsf, Z_gas_nsf;\n    ///mean temperature,metallicty,star formation rate\n    Double_t Temp_mean_gas_nsf, Z_mean_gas_nsf;\n    //@}\n\n    ///\\name gas star forming/non-star forming aperture quantities/radial profiles\n    //@{\n    vector<unsigned int> aperture_npart_gas_nsf;\n    vector<float> aperture_mass_gas_nsf;\n    vector<float> aperture_veldisp_gas_nsf;\n    vector<float> aperture_vrdisp_gas_nsf;\n    vector<float> aperture_rhalfmass_gas_nsf;\n    vector<float> aperture_Z_gas_nsf;\n    vector<Coordinate> aperture_L_gas_nsf;\n    vector<Coordinate> aperture_mass_proj_gas_nsf;\n    vector<Coordinate> aperture_rhalfmass_proj_gas_nsf;\n    vector<Coordinate> aperture_Z_proj_gas_nsf;\n    vector<unsigned int> profile_npart_gas_nsf;\n    vector<unsigned int> profile_npart_inclusive_gas_nsf;\n    vector<float> profile_mass_gas_nsf;\n    vector<float> profile_mass_inclusive_gas_nsf;\n    vector<Coordinate> profile_L_gas_nsf;\n    //@}\n\n    vector<Double_t> SO_mass_gas_nsf;\n    vector<Coordinate> SO_angularmomentum_gas_nsf;\n#endif\n#endif\n\n#ifdef STARON\n    ///\\name star specific quantities\n    //@{\n    ///number of particles\n    int n_star;\n    ///mass\n    Double_t M_star, M_star_rvmax, M_star_30kpc, M_star_50kpc, M_star_500c;\n    ///mass in spherical overdensities\n    Double_t M_200crit_star, M_200mean_star, M_BN98_star;\n    ///mass in spherical overdensities inclusive of all masses\n    Double_t M_200crit_excl_star, M_200mean_excl_star, M_BN98_excl_star;\n    ///pos/vel info\n    Coordinate cm_star,cmvel_star;\n    ///velocity/angular momentum info\n    Double_t Krot_star;\n    Coordinate L_star;\n    ///physical properties for angular momentum (can be inclusive or exclusive )\n    Coordinate L_200crit_star, L_200mean_star, L_BN98_star;\n    ///physical properties for angular momentum exclusiveto object\n    Coordinate L_200crit_excl_star, L_200mean_excl_star, L_BN98_excl_star;\n    Matrix veldisp_star;\n    ///morphology\n    Double_t MassTwiceRhalfmass_star, Rhalfmass_star,q_star,s_star;\n    Matrix eigvec_star;\n    ///mean age,metallicty\n    Double_t t_star,Z_star;\n    ///mean age,metallicty\n    Double_t t_mean_star,Z_mean_star;\n    ///physical properties for dynamical state\n    Double_t Efrac_star,Pot_star,T_star;\n    //@}\n\n    ///\\name stellar aperture quantities/radial profiles\n    //@{\n    vector<unsigned int> aperture_npart_star;\n    vector<float> aperture_mass_star;\n    vector<float> aperture_veldisp_star;\n    vector<float> aperture_vrdisp_star;\n    vector<float> aperture_rhalfmass_star;\n    vector<float> aperture_Z_star;\n    vector<Coordinate> aperture_L_star;\n    vector<Coordinate> aperture_mass_proj_star;\n    vector<Coordinate> aperture_rhalfmass_proj_star;\n    vector<Coordinate> aperture_Z_proj_star;\n    vector<unsigned int> profile_npart_star;\n    vector<unsigned int> profile_npart_inclusive_star;\n    vector<float> profile_mass_star;\n    vector<float> profile_mass_inclusive_star;\n    vector<Coordinate> profile_L_star;\n    //@}\n\n    vector<Double_t> SO_mass_star;\n    vector<Coordinate> SO_angularmomentum_star;\n#endif\n\n#ifdef BHON\n    ///\\name black hole specific quantities\n    //@{\n    ///number of BH\n    int n_bh;\n    ///mass\n    Double_t M_bh, M_bh_mostmassive;\n    ///mean accretion rate, metallicty\n    Double_t acc_bh, acc_bh_mostmassive;\n\n    ///\\name blackhole aperture quantities/radial profiles\n    //@{\n    vector<int> aperture_npart_bh;\n    vector<float> aperture_mass_bh;\n    vector<Coordinate> aperture_mass_proj_bh;\n    vector<Coordinate> aperture_L_bh;\n    //@}\n\n    vector<Double_t> SO_mass_bh;\n    vector<Coordinate> SO_angularmomentum_bh;\n    //@}\n#endif\n\n#ifdef HIGHRES\n    ///\\name low resolution interloper particle specific quantities\n    //@{\n    ///number of interloper low res particles\n    int n_interloper;\n    ///mass\n    Double_t M_interloper;\n    ///mass in spherical overdensities\n    Double_t M_200crit_interloper, M_200mean_interloper, M_BN98_interloper;\n    ///mass in spherical overdensities inclusive of all masses\n    Double_t M_200crit_excl_interloper, M_200mean_excl_interloper, M_BN98_excl_interloper;\n\n    vector<unsigned int> aperture_npart_interloper;\n    vector<float> aperture_mass_interloper;\n    vector<Coordinate> aperture_mass_proj_interloper;\n    vector<unsigned int> profile_npart_interloper;\n    vector<unsigned int> profile_npart_inclusive_interloper;\n    vector<float> profile_mass_interloper;\n    vector<float> profile_mass_inclusive_interloper;\n\n    vector<Double_t> SO_mass_interloper;\n    //@}\n#endif\n\n    /// \\name extra hydro/star/bh properties such as chemistry/feedback/metal production\n\n    //@{\n#if defined(GASON)\n    HydroProperties hydroprop;\n    vector<HydroProperties> aperture_properties_gas;\n#if defined(STARON)\n    vector<HydroProperties> aperture_properties_gas_sf;\n    vector<HydroProperties> aperture_properties_gas_nsf;\n#endif\n#endif\n#if defined(STARON)\n    StarProperties starprop;\n    vector<StarProperties> aperture_properties_star;\n#endif\n#if defined(BHON)\n    BHProperties bhprop;\n    vector<BHProperties> aperture_properties_bh;\n#endif\n#if defined(EXTRADMON)\n    Int_t n_dm;\n    ExtraDMProperties extradmprop;\n    vector<ExtraDMProperties> aperture_properties_extra_dm;\n#endif\n    //@}\n\n    ///\\name standard units of physical properties\n    //@{\n    string massunit, velocityunit, lengthunit, energyunit;\n    //@}\n\n\n    PropData()\n    {\n        num=gNFOF=gN6DFOF=0;\n        gmass=gsize=gRmbp=gmaxvel=gRmaxvel=gRvir=gR200m=gR200c=gRhalfmass=gMassTwiceRhalfmass=Efrac=Pot=T=0.;\n        gMFOF=gM6DFOF=0;\n        gM500c=gR500c=0;\n        gMBN98=gRBN98=0;\n        gRhalf200c = gRhalf200m = gRhalfBN98 = 0.;\n        cNFW200c = cNFW200c = cNFWBN98 = 0;\n        gcm[0]=gcm[1]=gcm[2]=gcmvel[0]=gcmvel[1]=gcmvel[2]=0.;\n        gJ[0]=gJ[1]=gJ[2]=0;\n        gJ200m[0]=gJ200m[1]=gJ200m[2]=0;\n        gJ200c[0]=gJ200c[1]=gJ200c[2]=0;\n        gJBN98[0]=gJBN98[1]=gJBN98[2]=0;\n        gveldisp=Matrix(0.);\n        gq=gs=1.0;\n        Krot=0.;\n\n        gM200m_excl=gM200c_excl=gMBN98_excl=0;\n        gR200m_excl=gR200c_excl=gRBN98_excl=0;\n        gJ200m_excl[0]=gJ200m_excl[1]=gJ200m_excl[2]=0;\n        gJ200c_excl[0]=gJ200c_excl[1]=gJ200c_excl[2]=0;\n        gJBN98_excl[0]=gJBN98_excl[1]=gJBN98_excl[2]=0;\n\n        RV_sigma_v=0;\n        RV_q=RV_s=1.;\n        RV_J[0]=RV_J[1]=RV_J[2]=0;\n        RV_veldisp=Matrix(0.);\n        RV_eigvec=Matrix(0.);\n        RV_lambda_B=RV_lambda_P=RV_Krot=0;\n\n#ifdef GASON\n        M_gas_rvmax=M_gas_30kpc=M_gas_50kpc=0;\n        n_gas=M_gas=Efrac_gas=0;\n        cm_gas[0]=cm_gas[1]=cm_gas[2]=cmvel_gas[0]=cmvel_gas[1]=cmvel_gas[2]=0.;\n        L_gas[0]=L_gas[1]=L_gas[2]=0;\n        q_gas=s_gas=1.0;\n        MassTwiceRhalfmass_gas=Rhalfmass_gas=0;\n        eigvec_gas=Matrix(1,0,0,0,1,0,0,0,1);\n        Temp_gas=Z_gas=SFR_gas=0.0;\n        Temp_mean_gas=Z_mean_gas=SFR_mean_gas=0.0;\n        veldisp_gas=Matrix(0.);\n        Krot_gas=T_gas=Pot_gas=0;\n\n        M_200mean_gas=M_200crit_gas=M_BN98_gas=0;\n        M_200mean_excl_gas=M_200crit_excl_gas=M_BN98_excl_gas=0;\n        L_200crit_gas[0]=L_200crit_gas[1]=L_200crit_gas[2]=0;\n        L_200mean_gas[0]=L_200mean_gas[1]=L_200mean_gas[2]=0;\n        L_BN98_gas[0]=L_BN98_gas[1]=L_BN98_gas[2]=0;\n        L_200crit_excl_gas[0]=L_200crit_excl_gas[1]=L_200crit_excl_gas[2]=0;\n        L_200mean_excl_gas[0]=L_200mean_excl_gas[1]=L_200mean_excl_gas[2]=0;\n        L_BN98_excl_gas[0]=L_BN98_excl_gas[1]=L_BN98_excl_gas[2]=0;\n#ifdef STARON\n        n_gas_sf = n_gas_nsf = 0;\n        M_gas_sf=M_gas_sf_rvmax=M_gas_sf_30kpc=M_gas_sf_50kpc=0;\n        L_gas_sf[0]=L_gas_sf[1]=L_gas_sf[2]=0;\n        q_gas_sf=s_gas_sf=1.0;\n        MassTwiceRhalfmass_gas_sf=Rhalfmass_gas_sf=0;\n        Temp_gas_sf=Z_gas_sf=0.0;\n        Temp_mean_gas_sf=Z_mean_gas_sf=0.0;\n        sigV_gas_sf=0;\n\n        M_200mean_gas_sf=M_200crit_gas_sf=M_BN98_gas_sf=0;\n        M_200mean_excl_gas_sf=M_200crit_excl_gas_sf=M_BN98_excl_gas_sf=0;\n        L_200crit_gas_sf[0]=L_200crit_gas_sf[1]=L_200crit_gas_sf[2]=0;\n        L_200mean_gas_sf[0]=L_200mean_gas_sf[1]=L_200mean_gas_sf[2]=0;\n        L_BN98_gas_sf[0]=L_BN98_gas_sf[1]=L_BN98_gas_sf[2]=0;\n        L_200crit_excl_gas_sf[0]=L_200crit_excl_gas_sf[1]=L_200crit_excl_gas_sf[2]=0;\n        L_200mean_excl_gas_sf[0]=L_200mean_excl_gas_sf[1]=L_200mean_excl_gas_sf[2]=0;\n        L_BN98_excl_gas_sf[0]=L_BN98_excl_gas_sf[1]=L_BN98_excl_gas_sf[2]=0;\n\n        M_gas_nsf=M_gas_nsf_rvmax=M_gas_nsf_30kpc=M_gas_nsf_50kpc=0;\n        L_gas_nsf[0]=L_gas_nsf[1]=L_gas_nsf[2]=0;\n        q_gas_nsf=s_gas_nsf=1.0;\n        MassTwiceRhalfmass_gas_nsf=Rhalfmass_gas_nsf=0;\n        Temp_gas_nsf=Z_gas_nsf=0.0;\n        Temp_mean_gas_nsf=Z_mean_gas_nsf=0.0;\n        sigV_gas_nsf=0;\n        M_200mean_gas_nsf=M_200crit_gas_nsf=M_BN98_gas_nsf=0;\n        M_200mean_excl_gas_nsf=M_200crit_excl_gas_nsf=M_BN98_excl_gas_nsf=0;\n        L_200crit_gas_nsf[0]=L_200crit_gas_nsf[1]=L_200crit_gas_nsf[2]=0;\n        L_200mean_gas_nsf[0]=L_200mean_gas_nsf[1]=L_200mean_gas_nsf[2]=0;\n        L_BN98_gas_nsf[0]=L_BN98_gas_nsf[1]=L_BN98_gas_nsf[2]=0;\n        L_200crit_excl_gas_nsf[0]=L_200crit_excl_gas_nsf[1]=L_200crit_excl_gas_nsf[2]=0;\n        L_200mean_excl_gas_nsf[0]=L_200mean_excl_gas_nsf[1]=L_200mean_excl_gas_nsf[2]=0;\n        L_BN98_excl_gas_nsf[0]=L_BN98_excl_gas_nsf[1]=L_BN98_excl_gas_nsf[2]=0;\n#endif\n#endif\n#ifdef STARON\n        M_star_rvmax=M_star_30kpc=M_star_50kpc=0;\n        n_star=M_star=Efrac_star=0;\n        cm_star[0]=cm_star[1]=cm_star[2]=cmvel_star[0]=cmvel_star[1]=cmvel_star[2]=0.;\n        L_star[0]=L_star[1]=L_star[2]=0;\n        q_star=s_star=1.0;\n        MassTwiceRhalfmass_star=Rhalfmass_star=0;\n        eigvec_star=Matrix(1,0,0,0,1,0,0,0,1);\n        t_star=Z_star=0.;\n        t_mean_star=Z_mean_star=0.;\n        veldisp_star=Matrix(0.);\n        Krot_star=T_star=Pot_star=0;\n\n        M_200mean_star=M_200crit_star=M_BN98_star=0;\n        M_200mean_excl_star=M_200crit_excl_star=M_BN98_excl_star=0;\n        L_200crit_star[0]=L_200crit_star[1]=L_200crit_star[2]=0;\n        L_200mean_star[0]=L_200mean_star[1]=L_200mean_star[2]=0;\n        L_BN98_star[0]=L_BN98_star[1]=L_BN98_star[2]=0;\n        L_200crit_excl_star[0]=L_200crit_excl_star[1]=L_200crit_excl_star[2]=0;\n        L_200mean_excl_star[0]=L_200mean_excl_star[1]=L_200mean_excl_star[2]=0;\n        L_BN98_excl_star[0]=L_BN98_excl_star[1]=L_BN98_excl_star[2]=0;\n#endif\n#ifdef BHON\n        n_bh=M_bh=0;\n        M_bh_mostmassive=0;\n        acc_bh=0;\n        acc_bh_mostmassive=0;\n#endif\n#ifdef HIGHRES\n        n_interloper=M_interloper=0;\n#endif\n#ifdef EXTRADMON\n        n_dm = 0;\n#endif\n    }\n    ///equals operator, useful if want inclusive information before substructure search\n    PropData& operator=(const PropData &p) = default;\n    /*\n    PropData& operator=(const PropData &p) {\n        num=p.num;\n        gcm=p.gcm;gcmvel=p.gcmvel;\n        gposmbp=p.gposmbp;gvelmbp=p.gvelmbp;\n        gposminpot=p.gposminpot;gvelminpot=p.gvelminpot;\n        gmass=p.gmass;gsize=p.gsize;\n        gMvir=p.gMvir;gRvir=p.gRvir;gRmbp=p.gRmbp;\n        gmaxvel=gmaxvel=p.gmaxvel;gRmaxvel=p.gRmaxvel;gMmaxvel=p.gMmaxvel;\n        gM200c=p.gM200c;gR200c=p.gR200c;\n        gM200m=p.gM200m;gR200m=p.gR200m;\n        gM500c=p.gM500c;gR500c=p.gR500c;\n        gMBN98=p.gMBN98;gRBN98=p.gRBN98;\n        gNFOF=p.gNFOF;\n        gMFOF=p.gMFOF;\n\n        gM200c_excl=p.gM200c_excl;gR200c_excl=p.gR200c_excl;\n        gM200m_excl=p.gM200m_excl;gR200m_excl=p.gR200m_excl;\n        gMBN98_excl=p.gMBN98_excl;gRBN98_excl=p.gRBN98_excl;\n        gJ=p.gJ;\n        gJ200c=p.gJ200c;\n        gJ200m=p.gJ200m;\n        gJBN98=p.gJBN98;\n        gJ200c_excl=p.gJ200c_excl;\n        gJ200m_excl=p.gJ200m_excl;\n        gJBN98_excl=p.gJBN98_excl;\n\n        ///expand to copy all the gas, star, bh, stuff\n#ifdef GASON\n        M_200mean_gas=p.M_200mean_gas;\n        M_200crit_gas=p.M_200crit_gas;\n        M_BN98_gas=p.M_BN98_gas;\n        M_200mean_excl_gas=p.M_200mean_excl_gas;\n        M_200crit_excl_gas=p.M_200crit_excl_gas;\n        M_BN98_excl_gas=p.M_BN98_excl_gas;\n        L_200mean_gas=p.L_200mean_gas;\n        L_200crit_gas=p.L_200crit_gas;\n        L_BN98_gas=p.L_BN98_gas;\n        L_200mean_excl_gas=p.L_200mean_excl_gas;\n        L_200crit_excl_gas=p.L_200crit_excl_gas;\n        L_BN98_excl_gas=p.L_BN98_excl_gas;\n#ifdef STARON\n        M_200mean_gas_sf=p.M_200mean_gas_sf;\n        M_200crit_gas_sf=p.M_200crit_gas_sf;\n        M_BN98_gas_sf=p.M_BN98_gas_sf;\n        M_200mean_excl_gas_sf=p.M_200mean_excl_gas_sf;\n        M_200crit_excl_gas_sf=p.M_200crit_excl_gas_sf;\n        M_BN98_excl_gas_sf=p.M_BN98_excl_gas_sf;\n        L_200mean_gas_sf=p.L_200mean_gas_sf;\n        L_200crit_gas_sf=p.L_200crit_gas_sf;\n        L_BN98_gas_sf=p.L_BN98_gas_sf;\n        L_200mean_excl_gas_sf=p.L_200mean_excl_gas_sf;\n        L_200crit_excl_gas_sf=p.L_200crit_excl_gas_sf;\n        L_BN98_excl_gas_sf=p.L_BN98_excl_gas_sf;\n\n        M_200mean_gas_nsf=p.M_200mean_gas_nsf;\n        M_200crit_gas_nsf=p.M_200crit_gas_nsf;\n        M_BN98_gas_nsf=p.M_BN98_gas_nsf;\n        M_200mean_excl_gas_nsf=p.M_200mean_excl_gas_nsf;\n        M_200crit_excl_gas_nsf=p.M_200crit_excl_gas_nsf;\n        M_BN98_excl_gas_nsf=p.M_BN98_excl_gas_nsf;\n        L_200mean_gas_nsf=p.L_200mean_gas_nsf;\n        L_200crit_gas_nsf=p.L_200crit_gas_nsf;\n        L_BN98_gas_nsf=p.L_BN98_gas_nsf;\n        L_200mean_excl_gas_nsf=p.L_200mean_excl_gas_nsf;\n        L_200crit_excl_gas_nsf=p.L_200crit_excl_gas_nsf;\n        L_BN98_excl_gas_nsf=p.L_BN98_excl_gas_nsf;\n#endif\n#endif\n#ifdef STARON\n        M_200mean_star=p.M_200mean_star;\n        M_200crit_star=p.M_200crit_star;\n        M_BN98_star=p.M_BN98_star;\n        M_200mean_excl_star=p.M_200mean_excl_star;\n        M_200crit_excl_star=p.M_200crit_excl_star;\n        M_BN98_excl_star=p.M_BN98_excl_star;\n        L_200mean_star=p.L_200mean_star;\n        L_200crit_star=p.L_200crit_star;\n        L_BN98_star=p.L_BN98_star;\n        L_200mean_excl_star=p.L_200mean_excl_star;\n        L_200crit_excl_star=p.L_200crit_excl_star;\n        L_BN98_excl_star=p.L_BN98_excl_star;\n#endif\n        aperture_npart=p.aperture_npart;\n        aperture_mass=p.aperture_mass;\n        aperture_veldisp=p.aperture_veldisp;\n        aperture_vrdisp=p.aperture_vrdisp;\n        aperture_rhalfmass=p.aperture_rhalfmass;\n#if defined(GASON) || defined(STARON) || defined(BHON)\n        aperture_npart_dm=p.aperture_npart_dm;\n        aperture_mass_dm=p.aperture_mass_dm;\n        aperture_veldisp_dm=p.aperture_veldisp_dm;\n        aperture_vrdisp_dm=p.aperture_vrdisp_dm;\n        aperture_rhalfmass_dm=p.aperture_rhalfmass_dm;\n        #endif\n#ifdef GASON\n        aperture_npart_gas=p.aperture_npart_gas;\n        aperture_mass_gas=p.aperture_mass_gas;\n        aperture_veldisp_gas=p.aperture_veldisp_gas;\n        aperture_rhalfmass_gas=p.aperture_rhalfmass_gas;\n#ifdef STARON\n        aperture_SFR_gas=p.aperture_SFR_gas;\n        aperture_Z_gas=p.aperture_Z_gas;\n        aperture_npart_gas_sf=p.aperture_npart_gas_sf;\n        aperture_npart_gas_nsf=p.aperture_npart_gas_nsf;\n        aperture_mass_gas_sf=p.aperture_mass_gas_sf;\n        aperture_mass_gas_nsf=p.aperture_mass_gas_nsf;\n        aperture_veldisp_gas_sf=p.aperture_veldisp_gas_sf;\n        aperture_veldisp_gas_nsf=p.aperture_veldisp_gas_nsf;\n        aperture_vrdisp_gas_sf=p.aperture_vrdisp_gas_sf;\n        aperture_vrdisp_gas_nsf=p.aperture_vrdisp_gas_nsf;\n        aperture_rhalfmass_gas_sf=p.aperture_rhalfmass_gas_sf;\n        aperture_rhalfmass_gas_nsf=p.aperture_rhalfmass_gas_nsf;\n        aperture_Z_gas_sf=p.aperture_Z_gas_sf;\n        aperture_Z_gas_nsf=p.aperture_Z_gas_nsf;\n#endif\n#endif\n#ifdef STARON\n        aperture_npart_star=p.aperture_npart_star;\n        aperture_mass_star=p.aperture_mass_star;\n        aperture_veldisp_star=p.aperture_veldisp_star;\n        aperture_vrdisp_star=p.aperture_vrdisp_star;\n        aperture_rhalfmass_star=p.aperture_rhalfmass_star;\n        aperture_Z_star=p.aperture_Z_star;\n#endif\n        aperture_mass_proj=p.aperture_mass_proj;\n        aperture_rhalfmass_proj=p.aperture_rhalfmass_proj;\n#ifdef GASON\n        aperture_mass_proj_gas=p.aperture_mass_proj_gas;\n        aperture_rhalfmass_proj_gas=p.aperture_rhalfmass_proj_gas;\n#ifdef STARON\n        aperture_SFR_proj_gas=p.aperture_SFR_proj_gas;\n        aperture_Z_proj_gas=p.aperture_Z_proj_gas;\n        aperture_mass_proj_gas_sf=p.aperture_mass_proj_gas_sf;\n        aperture_mass_proj_gas_nsf=p.aperture_mass_proj_gas_nsf;\n        aperture_rhalfmass_proj_gas_sf=p.aperture_rhalfmass_proj_gas_sf;\n        aperture_rhalfmass_proj_gas_nsf=p.aperture_rhalfmass_proj_gas_nsf;\n        aperture_Z_proj_gas_sf=p.aperture_Z_proj_gas_sf;\n        aperture_Z_proj_gas_nsf=p.aperture_Z_proj_gas_nsf;\n#endif\n#endif\n#ifdef STARON\n        aperture_mass_proj_star=p.aperture_mass_proj_star;\n        aperture_rhalfmass_proj_star=p.aperture_rhalfmass_proj_star;\n        aperture_Z_proj_star=p.aperture_Z_proj_star;\n#endif\n        profile_npart=p.profile_npart;\n        profile_mass=p.profile_mass;\n        profile_npart_inclusive=p.profile_npart_inclusive;\n        profile_mass_inclusive=p.profile_mass_inclusive;\n#ifdef GASON\n        profile_npart_gas=p.profile_npart_gas;\n        profile_mass_gas=p.profile_mass_gas;\n        profile_npart_inclusive_gas=p.profile_npart_inclusive_gas;\n        profile_mass_inclusive_gas=p.profile_mass_inclusive_gas;\n#ifdef STARON\n        profile_npart_gas_sf=p.profile_npart_gas_sf;\n        profile_mass_gas_sf=p.profile_mass_gas_sf;\n        profile_npart_inclusive_gas_sf=p.profile_npart_inclusive_gas_sf;\n        profile_mass_inclusive_gas_sf=p.profile_mass_inclusive_gas_sf;\n        profile_npart_gas_nsf=p.profile_npart_gas_nsf;\n        profile_mass_gas_nsf=p.profile_mass_gas_nsf;\n        profile_npart_inclusive_gas_nsf=p.profile_npart_inclusive_gas_nsf;\n        profile_mass_inclusive_gas_nsf=p.profile_mass_inclusive_gas_nsf;\n#endif\n#endif\n#ifdef STARON\n        profile_npart_star=p.profile_npart_star;\n        profile_mass_star=p.profile_mass_star;\n        profile_npart_inclusive_star=p.profile_npart_inclusive_star;\n        profile_mass_inclusive_star=p.profile_mass_inclusive_star;\n#endif\n        return *this;\n    }\n    */\n\n    //allocate memory for profiles\n    void Allocate(Options &opt) {\n        AllocateApertures(opt);\n        AllocateProfiles(opt);\n        AllocateSOs(opt);\n    }\n    void AllocateApertures(Options &opt)\n    {\n        if (opt.iaperturecalc && opt.aperturenum>0) {\n            aperture_npart.resize(opt.aperturenum);\n            aperture_mass.resize(opt.aperturenum);\n            aperture_veldisp.resize(opt.aperturenum);\n            aperture_vrdisp.resize(opt.aperturenum);\n            aperture_rhalfmass.resize(opt.aperturenum);\n#ifdef GASON\n            aperture_npart_gas.resize(opt.aperturenum);\n            aperture_mass_gas.resize(opt.aperturenum);\n            aperture_veldisp_gas.resize(opt.aperturenum);\n            aperture_vrdisp_gas.resize(opt.aperturenum);\n            aperture_rhalfmass_gas.resize(opt.aperturenum);\n            if (opt.gas_extraprop_aperture_calc) aperture_properties_gas.resize(opt.aperturenum);\n#ifdef STARON\n            aperture_SFR_gas.resize(opt.aperturenum);\n            aperture_Z_gas.resize(opt.aperturenum);\n            aperture_npart_gas_sf.resize(opt.aperturenum);\n            aperture_npart_gas_nsf.resize(opt.aperturenum);\n            aperture_mass_gas_sf.resize(opt.aperturenum);\n            aperture_mass_gas_nsf.resize(opt.aperturenum);\n            aperture_veldisp_gas_sf.resize(opt.aperturenum);\n            aperture_veldisp_gas_nsf.resize(opt.aperturenum);\n            aperture_vrdisp_gas_sf.resize(opt.aperturenum);\n            aperture_vrdisp_gas_nsf.resize(opt.aperturenum);\n            aperture_rhalfmass_gas_sf.resize(opt.aperturenum);\n            aperture_rhalfmass_gas_nsf.resize(opt.aperturenum);\n            aperture_Z_gas_sf.resize(opt.aperturenum);\n            aperture_Z_gas_nsf.resize(opt.aperturenum);\n            if (opt.gas_extraprop_aperture_calc) aperture_properties_gas_sf.resize(opt.aperturenum);\n            if (opt.gas_extraprop_aperture_calc) aperture_properties_gas_nsf.resize(opt.aperturenum);\n#endif\n#endif\n#ifdef STARON\n            aperture_npart_star.resize(opt.aperturenum);\n            aperture_mass_star.resize(opt.aperturenum);\n            aperture_veldisp_star.resize(opt.aperturenum);\n            aperture_vrdisp_star.resize(opt.aperturenum);\n            aperture_rhalfmass_star.resize(opt.aperturenum);\n            aperture_Z_star.resize(opt.aperturenum);\n            if (opt.star_extraprop_aperture_calc) aperture_properties_star.resize(opt.aperturenum);\n#endif\n#ifdef BHON\n            aperture_npart_bh.resize(opt.aperturenum);\n            aperture_mass_bh.resize(opt.aperturenum);\n            if (opt.bh_extraprop_aperture_calc) aperture_properties_bh.resize(opt.aperturenum);\n#endif\n#ifdef HIGHRES\n            aperture_npart_interloper.resize(opt.aperturenum);\n            aperture_mass_interloper.resize(opt.aperturenum);\n#endif\n#ifdef EXTRADMON\n            if (opt.extra_dm_extraprop_aperture_calc) aperture_properties_extra_dm.resize(opt.aperturenum);\n#endif\n#if defined(GASON) || defined(STARON) || defined(BHON)\n            //if searching all types, also store dm only aperture quantities\n            if (opt.partsearchtype==PSTALL) {\n                aperture_npart_dm.resize(opt.aperturenum);\n                aperture_mass_dm.resize(opt.aperturenum);\n                aperture_veldisp_dm.resize(opt.aperturenum);\n                aperture_vrdisp_dm.resize(opt.aperturenum);\n                aperture_rhalfmass_dm.resize(opt.aperturenum);\n            }\n#endif\n            for (auto &x:aperture_npart) x=0;\n            for (auto &x:aperture_mass) x=-1;\n            for (auto &x:aperture_veldisp) x=0;\n            for (auto &x:aperture_rhalfmass) x=-1;\n#ifdef GASON\n            for (auto &x:aperture_npart_gas) x=0;\n            for (auto &x:aperture_mass_gas) x=-1;\n            for (auto &x:aperture_veldisp_gas) x=0;\n            for (auto &x:aperture_rhalfmass_gas) x=-1;\n#ifdef STARON\n            for (auto &x:aperture_SFR_gas) x=0;\n            for (auto &x:aperture_Z_gas) x=0;\n            for (auto &x:aperture_npart_gas_sf) x=0;\n            for (auto &x:aperture_mass_gas_sf) x=-1;\n            for (auto &x:aperture_npart_gas_nsf) x=0;\n            for (auto &x:aperture_mass_gas_nsf) x=-1;\n            for (auto &x:aperture_veldisp_gas_sf) x=0;\n            for (auto &x:aperture_veldisp_gas_nsf) x=0;\n            for (auto &x:aperture_rhalfmass_gas_sf) x=-1;\n            for (auto &x:aperture_rhalfmass_gas_nsf) x=-1;\n            for (auto &x:aperture_Z_gas_sf) x=0;\n            for (auto &x:aperture_Z_gas_nsf) x=0;\n#endif\n#endif\n#ifdef STARON\n            for (auto &x:aperture_npart_star) x=0;\n            for (auto &x:aperture_mass_star) x=-1;\n            for (auto &x:aperture_veldisp_star) x=0;\n            for (auto &x:aperture_rhalfmass_star) x=-1;\n            for (auto &x:aperture_Z_star) x=0;\n#endif\n#ifdef HIGHRES\n            for (auto &x:aperture_npart_interloper) x=0;\n            for (auto &x:aperture_mass_interloper) x=-1;\n#endif\n#if defined(GASON) || defined(STARON) || defined(BHON)\n            if (opt.partsearchtype==PSTALL) {\n                for (auto &x:aperture_npart_dm) x=0;\n                for (auto &x:aperture_mass_dm) x=-1;\n                for (auto &x:aperture_veldisp_dm) x=0;\n                for (auto &x:aperture_rhalfmass_dm) x=0;\n            }\n#endif\n        }\n\n        if (opt.iaperturecalc && opt.apertureprojnum>0) {\n            aperture_mass_proj.resize(opt.apertureprojnum);\n            aperture_rhalfmass_proj.resize(opt.apertureprojnum);\n#ifdef GASON\n            aperture_mass_proj_gas.resize(opt.apertureprojnum);\n            aperture_rhalfmass_proj_gas.resize(opt.apertureprojnum);\n#ifdef STARON\n            aperture_SFR_proj_gas.resize(opt.apertureprojnum);\n            aperture_Z_proj_gas.resize(opt.apertureprojnum);\n            aperture_mass_proj_gas_sf.resize(opt.apertureprojnum);\n            aperture_mass_proj_gas_nsf.resize(opt.apertureprojnum);\n            aperture_rhalfmass_proj_gas_sf.resize(opt.apertureprojnum);\n            aperture_rhalfmass_proj_gas_nsf.resize(opt.apertureprojnum);\n            aperture_Z_proj_gas_sf.resize(opt.apertureprojnum);\n            aperture_Z_proj_gas_nsf.resize(opt.apertureprojnum);\n#endif\n#endif\n#ifdef STARON\n            aperture_mass_proj_star.resize(opt.apertureprojnum);\n            aperture_rhalfmass_proj_star.resize(opt.apertureprojnum);\n            aperture_Z_proj_star.resize(opt.apertureprojnum);\n#endif\n#ifdef BHON\n            aperture_mass_proj_bh.resize(opt.apertureprojnum);\n#endif\n#ifdef HIGHRES\n            aperture_mass_proj_interloper.resize(opt.apertureprojnum);\n#endif\n            for (auto &x:aperture_mass_proj) x[0]=x[1]=x[2]=-1;\n            for (auto &x:aperture_rhalfmass_proj) x[0]=x[1]=x[2]=-1;\n#ifdef GASON\n            for (auto &x:aperture_mass_proj_gas) x[0]=x[1]=x[2]=-1;\n            for (auto &x:aperture_rhalfmass_proj_gas) x[0]=x[1]=x[2]=-1;\n#ifdef STARON\n            for (auto &x:aperture_SFR_proj_gas) x[0]=x[1]=x[2]=0;\n            for (auto &x:aperture_Z_proj_gas) x[0]=x[1]=x[2]=0;\n            for (auto &x:aperture_mass_proj_gas_sf) x[0]=x[1]=x[2]=-1;\n            for (auto &x:aperture_rhalfmass_proj_gas_sf) x[0]=x[1]=x[2]=-1;\n            for (auto &x:aperture_mass_proj_gas_nsf) x[0]=x[1]=x[2]=-1;\n            for (auto &x:aperture_rhalfmass_proj_gas_nsf) x[0]=x[1]=x[2]=-1;\n            for (auto &x:aperture_Z_proj_gas_sf) x[0]=x[1]=x[2]=-1;\n            for (auto &x:aperture_Z_proj_gas_nsf) x[0]=x[1]=x[2]=-1;\n#endif\n#endif\n#ifdef STARON\n            for (auto &x:aperture_mass_proj_star) x[0]=x[1]=x[2]=-1;\n            for (auto &x:aperture_rhalfmass_proj_star) x[0]=x[1]=x[2]=-1;\n            for (auto &x:aperture_Z_proj_star) x[0]=x[1]=x[2]=-1;\n#endif\n#ifdef BHON\n            for (auto &x:aperture_mass_proj_bh) x[0]=x[1]=x[2]=-1;\n#endif\n#ifdef HIGHRES\n            for (auto &x:aperture_mass_proj_interloper) x[0]=x[1]=x[2]=-1;\n#endif\n        }\n    }\n    void AllocateProfiles(Options &opt)\n    {\n        if (opt.iprofilecalc && gNFOF>=opt.profileminFOFsize && num>=opt.profileminsize) {\n            profile_npart.resize(opt.profilenbins);\n            profile_mass.resize(opt.profilenbins);\n            for (auto i=0;i<opt.profilenbins;i++) profile_npart[i]=profile_mass[i]=0;\n#ifdef GASON\n            profile_npart_gas.resize(opt.profilenbins);\n            profile_mass_gas.resize(opt.profilenbins);\n#ifdef STARON\n            profile_npart_gas_sf.resize(opt.profilenbins);\n            profile_mass_gas_sf.resize(opt.profilenbins);\n            profile_npart_gas_nsf.resize(opt.profilenbins);\n            profile_mass_gas_nsf.resize(opt.profilenbins);\n#endif\n            for (auto i=0;i<opt.profilenbins;i++) profile_npart_gas[i]=profile_mass_gas[i]=0;\n#ifdef STARON\n            for (auto i=0;i<opt.profilenbins;i++) profile_npart_gas_sf[i]=profile_mass_gas_sf[i]=profile_npart_gas_nsf[i]=profile_mass_gas_nsf[i]=0;\n#endif\n#endif\n#ifdef STARON\n            profile_npart_star.resize(opt.profilenbins);\n            profile_mass_star.resize(opt.profilenbins);\n            for (auto i=0;i<opt.profilenbins;i++) profile_npart_star[i]=profile_mass_star[i]=0;\n#endif\n            if (opt.iInclusiveHalo>0) {\n                profile_npart_inclusive.resize(opt.profilenbins);\n                profile_mass_inclusive.resize(opt.profilenbins);\n                for (auto i=0;i<opt.profilenbins;i++) profile_npart_inclusive[i]=profile_mass_inclusive[i]=0;\n#ifdef GASON\n                profile_npart_inclusive_gas.resize(opt.profilenbins);\n                profile_mass_inclusive_gas.resize(opt.profilenbins);\n#ifdef STARON\n                profile_npart_inclusive_gas_sf.resize(opt.profilenbins);\n                profile_mass_inclusive_gas_sf.resize(opt.profilenbins);\n                profile_npart_inclusive_gas_nsf.resize(opt.profilenbins);\n                profile_mass_inclusive_gas_nsf.resize(opt.profilenbins);\n#endif\n                for (auto i=0;i<opt.profilenbins;i++) profile_npart_inclusive_gas[i]=profile_mass_inclusive_gas[i]=0;\n#ifdef STARON\n                for (auto i=0;i<opt.profilenbins;i++) profile_npart_inclusive_gas_sf[i]=profile_mass_inclusive_gas_sf[i]=profile_npart_inclusive_gas_nsf[i]=profile_mass_inclusive_gas_nsf[i]=0;\n#endif\n#endif\n#ifdef STARON\n                profile_npart_inclusive_star.resize(opt.profilenbins);\n                profile_mass_inclusive_star.resize(opt.profilenbins);\n                for (auto i=0;i<opt.profilenbins;i++) profile_npart_inclusive_star[i]=profile_mass_inclusive_star[i]=0;\n#endif\n            }\n\n        }\n    }\n    void AllocateSOs(Options &opt)\n    {\n        if (opt.SOnum>0) {\n            SO_mass.resize(opt.SOnum);\n            SO_radius.resize(opt.SOnum);\n            for (auto &x:SO_mass) x=0;\n            for (auto &x:SO_radius) x=0;\n            if (opt.iextrahalooutput) {\n                SO_angularmomentum.resize(opt.SOnum);\n                for (auto &x:SO_angularmomentum) {x[0]=x[1]=x[2]=0;}\n#ifdef GASON\n                if (opt.iextragasoutput) {\n                    SO_mass_gas.resize(opt.SOnum);\n                    for (auto &x:SO_mass_gas) x=0;\n                    SO_angularmomentum_gas.resize(opt.SOnum);\n                    for (auto &x:SO_angularmomentum_gas) {x[0]=x[1]=x[2]=0;}\n#ifdef STARON\n#endif\n                }\n#endif\n#ifdef STARON\n                if (opt.iextrastaroutput) {\n                    SO_mass_star.resize(opt.SOnum);\n                    for (auto &x:SO_mass_star) x=0;\n                    SO_angularmomentum_star.resize(opt.SOnum);\n                    for (auto &x:SO_angularmomentum_star) {x[0]=x[1]=x[2]=0;}\n                }\n#endif\n#ifdef HIGHRES\n                if (opt.iextrainterloperoutput) {\n                    SO_mass_interloper.resize(opt.SOnum);\n                    for (auto &x:SO_mass_interloper) x=0;\n                }\n#endif\n            }\n        }\n    }\n    void CopyProfileToInclusive(Options &opt) {\n        for (auto i=0;i<opt.profilenbins;i++) {\n            profile_npart_inclusive[i]=profile_npart[i];\n            profile_mass_inclusive[i]=profile_mass[i];\n            profile_npart[i]=profile_mass[i]=0;\n#ifdef GASON\n            profile_npart_inclusive_gas[i]=profile_npart_gas[i];\n            profile_mass_inclusive_gas[i]=profile_mass_gas[i];\n            profile_npart_gas[i]=profile_mass_gas[i]=0;\n#ifdef STARON\n            profile_npart_inclusive_gas_sf[i]=profile_npart_gas_sf[i];\n            profile_mass_inclusive_gas_sf[i]=profile_mass_gas_sf[i];\n            profile_npart_gas_sf[i]=profile_mass_gas_sf[i]=0;\n            profile_npart_inclusive_gas_nsf[i]=profile_npart_gas_nsf[i];\n            profile_mass_inclusive_gas_nsf[i]=profile_mass_gas_nsf[i];\n            profile_npart_gas_nsf[i]=profile_mass_gas_nsf[i]=0;\n#endif\n#endif\n#ifdef STARON\n            profile_npart_inclusive_star[i]=profile_npart_star[i];\n            profile_mass_inclusive_star[i]=profile_mass_star[i];\n            profile_npart_star[i]=profile_mass_star[i]=0;\n#endif\n        }\n    }\n\n    ///converts the properties data into comoving little h values\n    ///so masses, positions have little h values and positions are comoving\n    void ConverttoComove(Options &opt){\n        gcm=gcm*opt.h/opt.a;\n        gposmbp=gposmbp*opt.h/opt.a;\n        gposminpot=gposminpot*opt.h/opt.a;\n        gmass*=opt.h;\n        gMvir*=opt.h;\n        gM200c*=opt.h;\n        gM200m*=opt.h;\n        gM500c*=opt.h;\n        gMBN98*=opt.h;\n        gMFOF*=opt.h;\n        gsize*=opt.h/opt.a;\n        gRmbp*=opt.h/opt.a;\n        gRmaxvel*=opt.h/opt.a;\n        gRvir*=opt.h/opt.a;\n        gR200c*=opt.h/opt.a;\n        gR200m*=opt.h/opt.a;\n        gR500c*=opt.h/opt.a;\n        gRBN98*=opt.h/opt.a;\n        gRhalf200m*=opt.h/opt.a;\n        gRhalf200c*=opt.h/opt.a;\n        gRhalfBN98*=opt.h/opt.a;\n        gMassTwiceRhalfmass*=opt.h;\n        gRhalfmass*=opt.h/opt.a;\n        gJ=gJ*opt.h*opt.h/opt.a;\n        gJ200m=gJ200m*opt.h*opt.h/opt.a;\n        gJ200c=gJ200c*opt.h*opt.h/opt.a;\n        gJBN98=gJBN98*opt.h*opt.h/opt.a;\n        RV_J=RV_J*opt.h*opt.h/opt.a;\n\n        if (opt.iextrahalooutput) {\n            gM200c_excl*=opt.h;\n            gM200m_excl*=opt.h;\n            gMBN98_excl*=opt.h;\n            gR200c_excl*=opt.h/opt.a;\n            gR200m_excl*=opt.h/opt.a;\n            gRBN98_excl*=opt.h/opt.a;\n            gJ200m_excl=gJ200m_excl*opt.h*opt.h/opt.a;\n            gJ200c_excl=gJ200c_excl*opt.h*opt.h/opt.a;\n            gJBN98_excl=gJBN98_excl*opt.h*opt.h/opt.a;\n        }\n\n#ifdef GASON\n        M_gas*=opt.h;\n        M_gas_rvmax*=opt.h;\n        M_gas_30kpc*=opt.h;\n        M_gas_50kpc*=opt.h;\n        M_gas_500c*=opt.h;\n\n        cm_gas=cm_gas*opt.h/opt.a;\n        L_gas=L_gas*opt.h*opt.h/opt.a;\n        MassTwiceRhalfmass_gas*=opt.h;\n        Rhalfmass_gas*=opt.h/opt.a;\n\n        if (opt.iextragasoutput) {\n            M_200mean_gas*=opt.h;\n            M_200crit_gas*=opt.h;\n            M_BN98_gas*=opt.h;\n            M_200mean_excl_gas*=opt.h;\n            M_200crit_excl_gas*=opt.h;\n            M_BN98_excl_gas*=opt.h;\n            L_200crit_gas=L_200crit_gas*opt.h*opt.h/opt.a;\n            L_200mean_gas=L_200mean_gas*opt.h*opt.h/opt.a;\n            L_BN98_gas=L_BN98_gas*opt.h*opt.h/opt.a;\n            L_200crit_excl_gas=L_200crit_excl_gas*opt.h*opt.h/opt.a;\n            L_200mean_excl_gas=L_200mean_excl_gas*opt.h*opt.h/opt.a;\n            L_BN98_excl_gas=L_BN98_excl_gas*opt.h*opt.h/opt.a;\n        }\n        #ifdef STARON\n        M_gas_sf*=opt.h;\n        L_gas_sf*=opt.h*opt.h/opt.a;\n        MassTwiceRhalfmass_gas_sf*=opt.h;\n        Rhalfmass_gas_sf*=opt.h/opt.a;\n\n        M_gas_nsf*=opt.h;\n        L_gas_nsf*=opt.h*opt.h/opt.a;\n        MassTwiceRhalfmass_gas_nsf*=opt.h;\n        Rhalfmass_gas_nsf*=opt.h/opt.a;\n\n        if (opt.iextragasoutput) {\n            M_200mean_gas_sf*=opt.h;\n            M_200crit_gas_sf*=opt.h;\n            M_BN98_gas_sf*=opt.h;\n            M_200mean_excl_gas_sf*=opt.h;\n            M_200crit_excl_gas_sf*=opt.h;\n            M_BN98_excl_gas_sf*=opt.h;\n            L_200crit_gas_sf*=opt.h*opt.h/opt.a;\n            L_200mean_gas_sf*=opt.h*opt.h/opt.a;\n            L_BN98_gas_sf*=opt.h*opt.h/opt.a;\n            L_200crit_excl_gas_sf*=opt.h*opt.h/opt.a;\n            L_200mean_excl_gas_sf*=opt.h*opt.h/opt.a;\n            L_BN98_excl_gas_sf*=opt.h*opt.h/opt.a;\n\n            M_200mean_gas_nsf*=opt.h;\n            M_200crit_gas_nsf*=opt.h;\n            M_BN98_gas_nsf*=opt.h;\n            M_200mean_excl_gas_nsf*=opt.h;\n            M_200crit_excl_gas_nsf*=opt.h;\n            M_BN98_excl_gas_nsf*=opt.h;\n            L_200crit_gas_nsf*=opt.h*opt.h/opt.a;\n            L_200mean_gas_nsf*=opt.h*opt.h/opt.a;\n            L_BN98_gas_nsf*=opt.h*opt.h/opt.a;\n            L_200crit_excl_gas_nsf*=opt.h*opt.h/opt.a;\n            L_200mean_excl_gas_nsf*=opt.h*opt.h/opt.a;\n            L_BN98_excl_gas_nsf*=opt.h*opt.h/opt.a;\n        }\n        #endif\n\n#endif\n#ifdef STARON\n        M_star*=opt.h;\n        M_star_rvmax*=opt.h;\n        M_star_30kpc*=opt.h;\n        M_star_50kpc*=opt.h;\n        M_star_500c*=opt.h;\n        cm_star=cm_star*opt.h/opt.a;\n        MassTwiceRhalfmass_star*=opt.h/opt.a;\n        Rhalfmass_star*=opt.h/opt.a;\n        L_star=L_star*opt.h*opt.h/opt.a;\n#endif\n#ifdef BHON\n        M_bh*=opt.h;\n#endif\n#ifdef HIGHRES\n        M_interloper*=opt.h;\n#endif\n        if (opt.iaperturecalc) {\n            for (auto i=0;i<opt.iaperturecalc;i++) {\n                aperture_mass[i]*=opt.h;\n#ifdef GASON\n                aperture_mass_gas[i]*=opt.h;\n#ifdef STARON\n                aperture_mass_gas_sf[i]*=opt.h;\n                aperture_mass_gas_nsf[i]*=opt.h;\n#endif\n#endif\n#ifdef STARON\n                aperture_mass_star[i]*=opt.h;\n#endif\n            }\n        }\n        if (opt.SOnum>0) {\n            for (auto i=0;i<opt.SOnum;i++) {\n                SO_mass[i] *= opt.h;\n                SO_radius[i] *= opt.h/opt.a;\n                if (opt.iextrahalooutput) {\n                    SO_angularmomentum[i]*=(opt.h*opt.h/opt.a);\n#ifdef GASON\n                    SO_mass_gas[i] *= opt.h;\n                    SO_angularmomentum_gas[i]*=(opt.h*opt.h/opt.a);\n#ifdef STARON\n#endif\n#endif\n#ifdef STARON\n                    SO_mass_star[i] *= opt.h;\n                    SO_angularmomentum_star[i]*=(opt.h*opt.h/opt.a);\n#endif\n                }\n            }\n        }\n    }\n\n    void ConvertProfilestoComove(Options &opt){\n        for (auto i=0;i<opt.profilenbins;i++) {\n            profile_mass[i]*=opt.h;\n#ifdef GASON\n            profile_mass_gas[i]*=opt.h;\n#ifdef STARON\n            profile_mass_gas_sf[i]*=opt.h;\n            profile_mass_gas_nsf[i]*=opt.h;\n#endif\n#endif\n#ifdef STARON\n            profile_mass_star[i]*=opt.h;\n#endif\n            }\n        if (opt.iInclusiveHalo) {\n            for (auto i=0;i<opt.profilenbins;i++) {\n                profile_mass_inclusive[i]*=opt.h;\n#ifdef GASON\n                profile_mass_inclusive_gas[i]*=opt.h;\n#ifdef STARON\n                profile_mass_inclusive_gas_sf[i]*=opt.h;\n                profile_mass_inclusive_gas_nsf[i]*=opt.h;\n#endif\n#endif\n#ifdef STARON\n                profile_mass_inclusive_star[i]*=opt.h;\n#endif\n            }\n        }\n    }\n\n    void WriteBinary(fstream &Fout, Options &opt);\n    void WriteAscii(fstream &Fout, Options &opt);\n    ///write (append) the properties data to an already open ascii file\n#ifdef USEHDF\n    ///write (append) the properties data to an already open hdf file\n    //void WriteHDF(H5File &Fhdf, DataSpace *&dataspaces, DataSet *&datasets, Options&opt){};\n#endif\n};\n\n\n//for storing the units of known fields\nstruct HeaderUnitInfo{\n    float massdim, lengthdim, velocitydim, timedim, energydim;\n    string extrainfo;\n    HeaderUnitInfo(float md = 0, float ld = 0, float vd = 0, float td = 0, string s = \"\"){\n        massdim = md;\n        lengthdim = ld;\n        velocitydim = vd;\n        timedim = td;\n        extrainfo = s;\n    };\n    //Parse the string in the format massdim:lengthdim:velocitydim:timedim:energydim if only a string is passed\n    //if format does not match this then just store string\n    HeaderUnitInfo(string s);\n};\n\n/*! Structures stores header info of the data writen by the \\ref PropData data structure,\n    specifically the \\ref PropData::WriteBinary, \\ref PropData::WriteAscii, \\ref PropData::WriteHDF routines\n    Must ensure that these routines are all altered together so that the io makes sense.\n*/\nstruct PropDataHeader{\n    //list the header info\n    vector<string> headerdatainfo;\n    vector<HeaderUnitInfo> unitdatainfo;\n\n#ifdef USEHDF\n    // vector<PredType> predtypeinfo;\n    vector<hid_t> hdfpredtypeinfo;\n#endif\n#ifdef USEADIOS\n    vector<ADIOS_DATATYPES> adiospredtypeinfo;\n#endif\n    PropDataHeader(Options&opt);\n};\n\n\n/*! Structures stores profile info of the data writen by the \\ref PropData profiles data structures,\n    specifically the \\ref PropData::WriteProfileBinary, \\ref PropData::WriteProfileAscii, \\ref PropData::WriteProfileHDF routines\n*/\n\nstruct ProfileDataHeader{\n    //list the header info\n    vector<string> headerdatainfo;\n#ifdef USEHDF\n    vector<hid_t> hdfpredtypeinfo;\n#endif\n#ifdef USEADIOS\n    vector<ADIOS_DATATYPES> adiospredtypeinfo;\n#endif\n    int numberscalarentries, numberarrayallgroupentries, numberarrayhaloentries;\n    int offsetscalarentries, offsetarrayallgroupentries, offsetarrayhaloentries;\n\n    ProfileDataHeader(Options&opt){\n        int sizeval;\n#ifdef USEHDF\n        vector<hid_t> hdfdesiredproprealtype;\n        if (sizeof(Double_t)==sizeof(double)) hdfdesiredproprealtype.push_back(H5T_NATIVE_DOUBLE);\n        else hdfdesiredproprealtype.push_back(H5T_NATIVE_FLOAT);\n#endif\n#ifdef USEADIOS\n        vector<ADIOS_DATATYPES> desiredadiosproprealtype;\n        if (sizeof(Double_t)==sizeof(double)) desiredadiosproprealtype.push_back(ADIOS_DATATYPES::adios_double);\n        else desiredadiosproprealtype.push_back(ADIOS_DATATYPES::adios_real);\n#endif\n\n        offsetscalarentries=0;\n        headerdatainfo.push_back(\"ID\");\n#ifdef USEHDF\n        hdfpredtypeinfo.push_back(H5T_NATIVE_ULONG);\n#endif\n#ifdef USEADIOS\n        adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n#endif\n        //if normalisation is phys then no need for writing normalisation block\n        if (opt.iprofilenorm != PROFILERNORMPHYS) {\n        headerdatainfo.push_back(opt.profileradnormstring);\n#ifdef USEHDF\n        hdfpredtypeinfo.push_back(hdfdesiredproprealtype[0]);\n#endif\n#ifdef USEADIOS\n        adiospredtypeinfo.push_back(desiredadiosproprealtype[0]);\n#endif\n        }\n        numberscalarentries=headerdatainfo.size();\n\n\t    offsetarrayallgroupentries=headerdatainfo.size();\n        headerdatainfo.push_back(\"Npart_profile\");\n#ifdef GASON\n        headerdatainfo.push_back(\"Npart_profile_gas\");\n#ifdef STARON\n        headerdatainfo.push_back(\"Npart_profile_gas_sf\");\n        headerdatainfo.push_back(\"Npart_profile_gas_nsf\");\n#endif\n#endif\n#ifdef STARON\n        headerdatainfo.push_back(\"Npart_profile_star\");\n#endif\n#ifdef USEHDF\n        sizeval=hdfpredtypeinfo.size();\n        // for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(PredType::STD_U32LE);\n        for (int i=sizeval;i<headerdatainfo.size();i++) hdfpredtypeinfo.push_back(H5T_NATIVE_UINT);\n#endif\n#ifdef USEADIOS\n        sizeval=adiospredtypeinfo.size();\n        for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_unsigned_integer);\n#endif\n\n        headerdatainfo.push_back(\"Mass_profile\");\n#ifdef GASON\n        headerdatainfo.push_back(\"Mass_profile_gas\");\n#ifdef STARON\n        headerdatainfo.push_back(\"Mass_profile_gas_sf\");\n        headerdatainfo.push_back(\"Mass_profile_gas_nsf\");\n#endif\n#endif\n#ifdef STARON\n        headerdatainfo.push_back(\"Mass_profile_star\");\n#endif\n\n#ifdef USEHDF\n        sizeval=hdfpredtypeinfo.size();\n        // for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(PredType::NATIVE_FLOAT);\n        for (int i=sizeval;i<headerdatainfo.size();i++) hdfpredtypeinfo.push_back(H5T_NATIVE_FLOAT);\n#endif\n#ifdef USEADIOS\n        sizeval=adiospredtypeinfo.size();\n        for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_real);\n#endif\n        numberarrayallgroupentries=headerdatainfo.size()-offsetarrayallgroupentries;\n\n        //stuff for inclusive halo/SO profiles\n        if (opt.iInclusiveHalo >0) {\n        offsetarrayhaloentries=headerdatainfo.size();\n        headerdatainfo.push_back(\"Npart_inclusive_profile\");\n#ifdef GASON\n        headerdatainfo.push_back(\"Npart_inclusive_profile_gas\");\n#ifdef STARON\n        headerdatainfo.push_back(\"Npart_inclusive_profile_gas_sf\");\n        headerdatainfo.push_back(\"Npart_inclusive_profile_gas_nsf\");\n#endif\n#endif\n#ifdef STARON\n        headerdatainfo.push_back(\"Npart_inclusive_profile_star\");\n#endif\n#ifdef USEHDF\n        sizeval=hdfpredtypeinfo.size();\n        // for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(PredType::STD_U32LE);\n        for (int i=sizeval;i<headerdatainfo.size();i++) hdfpredtypeinfo.push_back(H5T_NATIVE_UINT);\n#endif\n#ifdef USEADIOS\n        sizeval=adiospredtypeinfo.size();\n        for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_unsigned_integer);\n#endif\n\n        headerdatainfo.push_back(\"Mass_inclusive_profile\");\n#ifdef GASON\n        headerdatainfo.push_back(\"Mass_inclusive_profile_gas\");\n#ifdef STARON\n        headerdatainfo.push_back(\"Mass_inclusive_profile_gas_sf\");\n        headerdatainfo.push_back(\"Mass_inclusive_profile_gas_nsf\");\n#endif\n#endif\n#ifdef STARON\n        headerdatainfo.push_back(\"Mass_inclusive_profile_star\");\n#endif\n#ifdef USEHDF\n        sizeval=hdfpredtypeinfo.size();\n        // for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(PredType::NATIVE_FLOAT);\n        for (int i=sizeval;i<headerdatainfo.size();i++) hdfpredtypeinfo.push_back(H5T_NATIVE_FLOAT);\n#endif\n#ifdef USEADIOS\n        sizeval=adiospredtypeinfo.size();\n        for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_real);\n#endif\n        numberarrayhaloentries=headerdatainfo.size()-offsetarrayhaloentries;\n        }\n    }\n};\n\n/*! Structure used to keep track of a structure's parent structure\n    note that level could be sim->halo->subhalo->subsubhalo\n    or even sim->wall/void/filament->halo->substructure->subsubstructure\n    here sim is stype=0,gid=0, and the other structure types are to be defined.\n    The data structure is meant to be traversed from\n        - level 0 structures (\"field\" objects)\n        - level 0 pointer to nextlevel\n        - nextlevel containing nginlevel objects\n*/\nstruct StrucLevelData\n{\n    ///structure type and number in current level of hierarchy\n    Int_t stype,nsinlevel;\n    ///points to the the head pfof address of the group and parent\n    Particle **Phead;\n    Int_t **gidhead;\n    ///parent pointers point to the address of the parents gidhead and Phead\n    Particle **Pparenthead;\n    Int_t **gidparenthead;\n    ///add uber parent pointer (that is pointer to field halo)\n    Int_t **giduberparenthead;\n    ///allowing for multiple structure types at a given level in the hierarchy\n    Int_t *stypeinlevel;\n    StrucLevelData *nextlevel;\n    StrucLevelData(Int_t numgroups=-1){\n        if (numgroups<=0) {\n            Phead=NULL;\n            Pparenthead=NULL;\n            gidhead=NULL;\n            gidparenthead=NULL;\n            giduberparenthead=NULL;\n            nextlevel=NULL;\n            stypeinlevel=NULL;\n            nsinlevel=0;\n        }\n        else Allocate(numgroups);\n    }\n    ///just allocate memory\n    void Allocate(Int_t numgroups){\n        nsinlevel=numgroups;\n        Phead=new Particle*[numgroups+1];\n        Pparenthead=new Particle*[numgroups+1];\n        gidhead=new Int_t*[numgroups+1];\n        gidparenthead=new Int_t*[numgroups+1];\n        giduberparenthead=new Int_t*[numgroups+1];\n        stypeinlevel=new Int_t[numgroups+1];\n        nextlevel=NULL;\n    }\n    ///initialize\n    void Initialize(){\n        for (Int_t i=1;i<=nsinlevel;i++) {gidhead[i]=NULL;gidparenthead[i]=NULL;giduberparenthead[i]=NULL;}\n    }\n    ~StrucLevelData(){\n        if (nextlevel!=NULL) delete nextlevel;\n        nextlevel=NULL;\n        delete[] Phead;\n        delete[] Pparenthead;\n        delete[] gidhead;\n        delete[] gidparenthead;\n        delete[] giduberparenthead;\n        delete[] stypeinlevel;\n    }\n};\n\n#if defined(USEHDF)||defined(USEADIOS)\n///store the names of datasets in catalog output\nstruct DataGroupNames {\n    ///store names of catalog group files\n    vector<string> prop;\n#ifdef USEHDF\n    //store the data type\n    // vector<PredType> propdatatype;\n    vector<hid_t> hdfpropdatatype;\n#endif\n#ifdef USEADIOS\n    vector<ADIOS_DATATYPES> adiospropdatatype;\n#endif\n\n    ///store names of catalog group files\n    vector<string> group;\n#ifdef USEHDF\n    // vector<PredType> groupdatatype;\n    vector<hid_t> hdfgroupdatatype;\n#endif\n#ifdef USEADIOS\n    vector<ADIOS_DATATYPES> adiosgroupdatatype;\n#endif\n\n    ///store the names of catalog particle files\n    vector<string> part;\n#ifdef USEHDF\n    // vector<PredType> partdatatype;\n    vector<hid_t> hdfpartdatatype;\n#endif\n#ifdef USEADIOS\n    vector<ADIOS_DATATYPES> adiospartdatatype;\n#endif\n\n    ///store the names of catalog particle type files\n    vector<string> types;\n#ifdef USEHDF\n    // vector<PredType> typesdatatype;\n    vector<hid_t> hdftypesdatatype;\n#endif\n#ifdef USEADIOS\n    vector<ADIOS_DATATYPES> adiostypesdatatype;\n#endif\n\n    ///store the names of hierarchy files\n    vector<string> hierarchy;\n#ifdef USEHDF\n    // vector<PredType> hierarchydatatype;\n    vector<hid_t> hdfhierarchydatatype;\n#endif\n#ifdef USEADIOS\n    vector<ADIOS_DATATYPES> adioshierarchydatatype;\n#endif\n\n    ///store names of SO files\n    vector<string> SO;\n#ifdef USEHDF\n    // vector<PredType> SOdatatype;\n    vector<hid_t> hdfSOdatatype;\n#endif\n#ifdef USEADIOS\n    vector<ADIOS_DATATYPES> SOdatatype;\n#endif\n\n    //store names of profile files\n    vector<string> profile;\n#ifdef USEHDF\n    //store the data type\n    // vector<PredType> profiledatatype;\n    vector<hid_t> hdfprofiledatatype;\n#endif\n#ifdef USEADIOS\n    vector<ADIOS_DATATYPES> adiosprofiledatatype;\n#endif\n\n    DataGroupNames(){\n#ifdef USEHDF\n        vector<hid_t> hdfdesiredproprealtype;\n        if (sizeof(Double_t)==sizeof(double)) hdfdesiredproprealtype.push_back(H5T_NATIVE_DOUBLE);\n        else hdfdesiredproprealtype.push_back(H5T_NATIVE_FLOAT);\n#endif\n#ifdef USEADIOS\n        vector<ADIOS_DATATYPES> desiredadiosproprealtype;\n        if (sizeof(Double_t)==sizeof(double)) desiredadiosproprealtype.push_back(ADIOS_DATATYPES::adios_double);\n        else desiredadiosproprealtype.push_back(ADIOS_DATATYPES::adios_real);\n#endif\n        prop.push_back(\"File_id\");\n        prop.push_back(\"Num_of_files\");\n        prop.push_back(\"Num_of_groups\");\n        prop.push_back(\"Total_num_of_groups\");\n        prop.push_back(\"Cosmological_Sim\");\n        prop.push_back(\"Comoving_or_Physical\");\n        prop.push_back(\"Period\");\n        prop.push_back(\"Time\");\n        prop.push_back(\"Length_unit_to_kpc\");\n        prop.push_back(\"Velocity_to_kms\");\n        prop.push_back(\"Mass_unit_to_solarmass\");\n#if defined(GASON) || defined(STARON) || defined(BHON)\n        prop.push_back(\"Metallicity_unit_to_solar\");\n        prop.push_back(\"SFR_unit_to_solarmassperyear\");\n        prop.push_back(\"Stellar_age_unit_to_yr\");\n#endif\n#ifdef USEHDF\n        hdfpropdatatype.push_back(H5T_NATIVE_INT);\n        hdfpropdatatype.push_back(H5T_NATIVE_INT);\n        hdfpropdatatype.push_back(H5T_NATIVE_ULONG);\n        hdfpropdatatype.push_back(H5T_NATIVE_ULONG);\n        hdfpropdatatype.push_back(H5T_NATIVE_UINT);\n        hdfpropdatatype.push_back(H5T_NATIVE_UINT);\n        hdfpropdatatype.push_back(hdfdesiredproprealtype[0]);\n        hdfpropdatatype.push_back(hdfdesiredproprealtype[0]);\n        hdfpropdatatype.push_back(hdfdesiredproprealtype[0]);\n        hdfpropdatatype.push_back(hdfdesiredproprealtype[0]);\n        hdfpropdatatype.push_back(hdfdesiredproprealtype[0]);\n#if defined(GASON) || defined(STARON) || defined(BHON)\n        hdfpropdatatype.push_back(hdfdesiredproprealtype[0]);\n        hdfpropdatatype.push_back(hdfdesiredproprealtype[0]);\n        hdfpropdatatype.push_back(hdfdesiredproprealtype[0]);\n#endif\n\n#endif\n#ifdef USEADIOS\n        adiospropdatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adiospropdatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adiospropdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiospropdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiospropdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_integer);\n        adiospropdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_integer);\n        adiospropdatatype.push_back(desiredadiosproprealtype[0]);\n        adiospropdatatype.push_back(desiredadiosproprealtype[0]);\n        adiospropdatatype.push_back(desiredadiosproprealtype[0]);\n        adiospropdatatype.push_back(desiredadiosproprealtype[0]);\n        adiospropdatatype.push_back(desiredadiosproprealtype[0]);\n#if defined(GASON) || defined(STARON) || defined(BHON)\n        adiospropdatatype.push_back(desiredadiosproprealtype[0]);\n        adiospropdatatype.push_back(desiredadiosproprealtype[0]);\n        adiospropdatatype.push_back(desiredadiosproprealtype[0]);\n#endif\n#endif\n\n        group.push_back(\"File_id\");\n        group.push_back(\"Num_of_files\");\n        group.push_back(\"Num_of_groups\");\n        group.push_back(\"Total_num_of_groups\");\n        group.push_back(\"Group_Size\");\n        group.push_back(\"Offset\");\n        group.push_back(\"Offset_unbound\");\n#ifdef USEHDF\n        hdfgroupdatatype.push_back(H5T_NATIVE_INT);\n        hdfgroupdatatype.push_back(H5T_NATIVE_INT);\n        hdfgroupdatatype.push_back(H5T_NATIVE_ULONG);\n        hdfgroupdatatype.push_back(H5T_NATIVE_ULONG);\n        hdfgroupdatatype.push_back(H5T_NATIVE_ULONG);\n        hdfgroupdatatype.push_back(H5T_NATIVE_ULONG);\n        hdfgroupdatatype.push_back(H5T_NATIVE_ULONG);\n\n#endif\n#ifdef USEADIOS\n        adiosgroupdatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adiosgroupdatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adiosgroupdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiosgroupdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiosgroupdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_integer);\n        adiosgroupdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiosgroupdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n#endif\n\n        part.push_back(\"File_id\");\n        part.push_back(\"Num_of_files\");\n        part.push_back(\"Num_of_particles_in_groups\");\n        part.push_back(\"Total_num_of_particles_in_all_groups\");\n        part.push_back(\"Particle_IDs\");\n#ifdef USEHDF\n        hdfpartdatatype.push_back(H5T_NATIVE_INT);\n        hdfpartdatatype.push_back(H5T_NATIVE_INT);\n        hdfpartdatatype.push_back(H5T_NATIVE_ULONG);\n        hdfpartdatatype.push_back(H5T_NATIVE_ULONG);\n        hdfpartdatatype.push_back(H5T_NATIVE_LONG);\n\n#endif\n#ifdef USEADIOS\n        adiospartdatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adiospartdatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adiospartdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiospartdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiospartdatatype.push_back(ADIOS_DATATYPES::adios_long);\n#endif\n\n        types.push_back(\"File_id\");\n        types.push_back(\"Num_of_files\");\n        types.push_back(\"Num_of_particles_in_groups\");\n        types.push_back(\"Total_num_of_particles_in_all_groups\");\n        types.push_back(\"Particle_types\");\n#ifdef USEHDF\n\n        hdftypesdatatype.push_back(H5T_NATIVE_INT);\n        hdftypesdatatype.push_back(H5T_NATIVE_INT);\n        hdftypesdatatype.push_back(H5T_NATIVE_ULONG);\n        hdftypesdatatype.push_back(H5T_NATIVE_ULONG);\n        hdftypesdatatype.push_back(H5T_NATIVE_USHORT);\n#endif\n#ifdef USEADIOS\n        adiostypesdatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adiostypesdatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adiostypesdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiostypesdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiostypesdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_short);\n#endif\n\n        hierarchy.push_back(\"File_id\");\n        hierarchy.push_back(\"Num_of_files\");\n        hierarchy.push_back(\"Num_of_groups\");\n        hierarchy.push_back(\"Total_num_of_groups\");\n        hierarchy.push_back(\"Number_of_substructures_in_halo\");\n        hierarchy.push_back(\"Parent_halo_ID\");\n#ifdef USEHDF\n        hdfhierarchydatatype.push_back(H5T_NATIVE_INT);\n        hdfhierarchydatatype.push_back(H5T_NATIVE_INT);\n        hdfhierarchydatatype.push_back(H5T_NATIVE_ULONG);\n        hdfhierarchydatatype.push_back(H5T_NATIVE_ULONG);\n        hdfhierarchydatatype.push_back(H5T_NATIVE_UINT);\n        hdfhierarchydatatype.push_back(H5T_NATIVE_LONG);\n\n#endif\n#ifdef USEADIOS\n        adioshierarchydatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adioshierarchydatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adioshierarchydatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adioshierarchydatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adioshierarchydatatype.push_back(ADIOS_DATATYPES::adios_unsigned_integer);\n        adioshierarchydatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n#endif\n        SO.push_back(\"File_id\");\n        SO.push_back(\"Num_of_files\");\n        SO.push_back(\"Num_of_SO_regions\");\n        SO.push_back(\"Total_num_of_SO_regions\");\n        SO.push_back(\"Num_of_particles_in_SO_regions\");\n        SO.push_back(\"Total_num_of_particles_in_SO_regions\");\n        SO.push_back(\"SO_size\");\n        SO.push_back(\"Offset\");\n        SO.push_back(\"Particle_IDs\");\n#if defined(GASON) || defined(STARON) || defined(BHON)\n        SO.push_back(\"Particle_types\");\n#endif\n\n#ifdef USEHDF\n        hdfSOdatatype.push_back(H5T_NATIVE_INT);\n        hdfSOdatatype.push_back(H5T_NATIVE_INT);\n        hdfSOdatatype.push_back(H5T_NATIVE_ULONG);\n        hdfSOdatatype.push_back(H5T_NATIVE_ULONG);\n        hdfSOdatatype.push_back(H5T_NATIVE_ULONG);\n        hdfSOdatatype.push_back(H5T_NATIVE_ULONG);\n        hdfSOdatatype.push_back(H5T_NATIVE_UINT);\n        hdfSOdatatype.push_back(H5T_NATIVE_ULONG);\n        hdfSOdatatype.push_back(H5T_NATIVE_LONG);\n        #if defined(GASON) || defined(STARON) || defined(BHON)\n        hdfSOdatatype.push_back(H5T_NATIVE_INT);\n        #endif\n\n#endif\n#ifdef USEADIOS\n        adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_integer);\n        adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_long);\n#if defined(GASON) || defined(STARON) || defined(BHON)\n        adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_integer);\n#endif\n#endif\n\n        profile.push_back(\"File_id\");\n        profile.push_back(\"Num_of_files\");\n        profile.push_back(\"Num_of_groups\");\n        profile.push_back(\"Total_num_of_groups\");\n        profile.push_back(\"Num_of_halos\");\n        profile.push_back(\"Total_num_of_halos\");\n        profile.push_back(\"Radial_norm\");\n        profile.push_back(\"Inclusive_profiles_flag\");\n        profile.push_back(\"Num_of_bin_edges\");\n        profile.push_back(\"Radial_bin_edges\");\n#ifdef USEHDF\n        hdfprofiledatatype.push_back(H5T_NATIVE_INT);\n        hdfprofiledatatype.push_back(H5T_NATIVE_INT);\n        hdfprofiledatatype.push_back(H5T_NATIVE_ULONG);\n        hdfprofiledatatype.push_back(H5T_NATIVE_ULONG);\n        hdfprofiledatatype.push_back(H5T_NATIVE_ULONG);\n        hdfprofiledatatype.push_back(H5T_NATIVE_ULONG);\n        hdfprofiledatatype.push_back(H5T_C_S1);\n        hdfprofiledatatype.push_back(H5T_NATIVE_INT);\n        hdfprofiledatatype.push_back(H5T_NATIVE_INT);\n        hdfprofiledatatype.push_back(hdfdesiredproprealtype[0]);\n#endif\n#ifdef USEADIOS\n        adiosprofiledatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adiosprofiledatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adiosprofiledatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiosprofiledatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiosprofiledatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiosprofiledatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiosprofiledatatype.push_back(ADIOS_DATATYPES::adios_string);\n        adiosprofiledatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adiosprofiledatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adiosprofiledatatype.push_back(desiredadiosproprealtype[0]);\n#endif\n\n    }\n};\n#endif\n\n///Useful structore to store information of leaf nodes in the tree\nstruct leaf_node_info{\n    int num, numtot;\n    Int_t id, istart, iend;\n    Coordinate cm;\n    Double_t size;\n#ifdef USEMPI\n    Double_t searchdist;\n#endif\n};\n\n///if using MPI API\n#ifdef USEMPI\n#include <mpi.h>\n///Includes external global variables used for MPI version of code\n#include \"mpivar.h\"\n#endif\n\nextern StrucLevelData *psldata;\n\n#endif\n", "meta": {"hexsha": "4399334b85ceeafea581c9c3d64107d52b19391c", "size": 117926, "ext": "h", "lang": "C", "max_stars_repo_path": "src/allvars.h", "max_stars_repo_name": "EthTay/VELOCIraptor-STF", "max_stars_repo_head_hexsha": "deb674aedf0885ecfc82c0b6fe3b2ef45966907c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/allvars.h", "max_issues_repo_name": "EthTay/VELOCIraptor-STF", "max_issues_repo_head_hexsha": "deb674aedf0885ecfc82c0b6fe3b2ef45966907c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/allvars.h", "max_forks_repo_name": "EthTay/VELOCIraptor-STF", "max_forks_repo_head_hexsha": "deb674aedf0885ecfc82c0b6fe3b2ef45966907c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.259399684, "max_line_length": 224, "alphanum_fraction": 0.7077574072, "num_tokens": 31644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33807713748839185, "lm_q2_score": 0.028870905692919478, "lm_q1q2_score": 0.009760593153359533}}
{"text": "#pragma once\n#include \"BufferView.h\"\n#include \"Enum.h\"\n#include \"Error.h\"\n#include \"parsers/Parsing.h\"\n#include <boost/hana/define_struct.hpp>\n#include <gsl/span>\n\nnamespace gltfpp {\n\tinline namespace v1 {\n\t\tBETTER_ENUM(AccessorComponentType,\n\t\t            int,\n\t\t            BYTE = 5120,\n\t\t            UNSIGNED_BYTE = 5121,\n\t\t            SHORT = 5122,\n\t\t            UNSIGNED_SHORT = 5123,\n\t\t            UNSIGNED_INT = 5125,\n\t\t            FLOAT = 5126)\n\n\t\tBETTER_ENUM(AccessorType, int, SCALAR, VEC2, VEC3, VEC4, MAT2, MAT3, MAT4)\n\n\t\tconstexpr auto AccessorTypeComponentCount =\n\t\t    boost::hana::make_map(boost::hana::make_pair(boost::hana::int_c<(int)AccessorType::SCALAR>, 1),\n\t\t                          boost::hana::make_pair(boost::hana::int_c<(int)AccessorType::VEC2>, 2),\n\t\t                          boost::hana::make_pair(boost::hana::int_c<(int)AccessorType::VEC3>, 3),\n\t\t                          boost::hana::make_pair(boost::hana::int_c<(int)AccessorType::VEC4>, 4),\n\t\t                          boost::hana::make_pair(boost::hana::int_c<(int)AccessorType::MAT2>, 4),\n\t\t                          boost::hana::make_pair(boost::hana::int_c<(int)AccessorType::MAT3>, 9),\n\t\t                          boost::hana::make_pair(boost::hana::int_c<(int)AccessorType::MAT4>, 16));\n\n\t\tstruct Accessor {\n\t\t\tBOOST_HANA_DEFINE_STRUCT(Accessor,\n\t\t\t                         (bool, normalized),\n\t\t\t                         (std::vector<double>, min),\n\t\t\t                         (std::vector<double>, max),\n\t\t\t                         (option<std::string>, name),\n\t\t\t                         (option<nlohmann::json>, sparse),\n\t\t\t                         (option<nlohmann::json>, extensions),\n\t\t\t                         (option<nlohmann::json>, extras),\n\t\t\t                         (ptrdiff_t, byteOffset),\n\t\t\t                         (size_t, count),\n\t\t\t                         (AccessorComponentType, componentType));\n\t\t\tBufferView const *bufferView;\n\t\t};\n\n\t\tauto parse(Accessor &) noexcept;\n\t}    // namespace v1\n}    // namespace gltfpp\n", "meta": {"hexsha": "1b2166ea0bf1f460d6a157619d393fbc4b0a11f6", "size": 2036, "ext": "h", "lang": "C", "max_stars_repo_path": "gltfpp/include/Accessor.h", "max_stars_repo_name": "mmha/gltfpp", "max_stars_repo_head_hexsha": "9e9e2fe5f8da374838a5b6b03d97963bed87956d", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2017-05-03T04:09:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-06T04:23:54.000Z", "max_issues_repo_path": "gltfpp/include/Accessor.h", "max_issues_repo_name": "mmha/gltfpp", "max_issues_repo_head_hexsha": "9e9e2fe5f8da374838a5b6b03d97963bed87956d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2017-06-02T16:53:11.000Z", "max_issues_repo_issues_event_max_datetime": "2017-06-02T18:05:45.000Z", "max_forks_repo_path": "gltfpp/include/Accessor.h", "max_forks_repo_name": "mmha/gltfpp", "max_forks_repo_head_hexsha": "9e9e2fe5f8da374838a5b6b03d97963bed87956d", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2017-06-01T14:38:11.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-18T07:04:15.000Z", "avg_line_length": 41.5510204082, "max_line_length": 101, "alphanum_fraction": 0.5279960707, "num_tokens": 487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234991142019, "lm_q2_score": 0.02228618789322103, "lm_q1q2_score": 0.009757416765326595}}
{"text": "/* vector/gsl_vector_short.h\r\n * \r\n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\r\n * \r\n * This program is free software; you can redistribute it and/or modify\r\n * it under the terms of the GNU General Public License as published by\r\n * the Free Software Foundation; either version 3 of the License, or (at\r\n * your option) any later version.\r\n * \r\n * This program is distributed in the hope that it will be useful, but\r\n * WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n * General Public License for more details.\r\n * \r\n * You should have received a copy of the GNU General Public License\r\n * along with this program; if not, write to the Free Software\r\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r\n */\r\n\r\n#ifndef __GSL_VECTOR_SHORT_H__\r\n#define __GSL_VECTOR_SHORT_H__\r\n\r\n#if !defined( GSL_FUN )\r\n#  if !defined( GSL_DLL )\r\n#    define GSL_FUN extern\r\n#  elif defined( BUILD_GSL_DLL )\r\n#    define GSL_FUN extern __declspec(dllexport)\r\n#  else\r\n#    define GSL_FUN extern __declspec(dllimport)\r\n#  endif\r\n#endif\r\n\r\n#include <stdlib.h>\r\n#include <gsl/gsl_types.h>\r\n#include <gsl/gsl_errno.h>\r\n#include <gsl/gsl_inline.h>\r\n#include <gsl/gsl_check_range.h>\r\n#include <gsl/gsl_block_short.h>\r\n\r\n#undef __BEGIN_DECLS\r\n#undef __END_DECLS\r\n#ifdef __cplusplus\r\n# define __BEGIN_DECLS extern \"C\" {\r\n# define __END_DECLS }\r\n#else\r\n# define __BEGIN_DECLS /* empty */\r\n# define __END_DECLS /* empty */\r\n#endif\r\n\r\n__BEGIN_DECLS\r\n\r\ntypedef struct \r\n{\r\n  size_t size;\r\n  size_t stride;\r\n  short *data;\r\n  gsl_block_short *block;\r\n  int owner;\r\n} \r\ngsl_vector_short;\r\n\r\ntypedef struct\r\n{\r\n  gsl_vector_short vector;\r\n} _gsl_vector_short_view;\r\n\r\ntypedef _gsl_vector_short_view gsl_vector_short_view;\r\n\r\ntypedef struct\r\n{\r\n  gsl_vector_short vector;\r\n} _gsl_vector_short_const_view;\r\n\r\ntypedef const _gsl_vector_short_const_view gsl_vector_short_const_view;\r\n\r\n\r\n/* Allocation */\r\n\r\nGSL_FUN gsl_vector_short *gsl_vector_short_alloc (const size_t n);\r\nGSL_FUN gsl_vector_short *gsl_vector_short_calloc (const size_t n);\r\n\r\nGSL_FUN gsl_vector_short *gsl_vector_short_alloc_from_block (gsl_block_short * b,\r\n                                                     const size_t offset, \r\n                                                     const size_t n, \r\n                                                     const size_t stride);\r\n\r\nGSL_FUN gsl_vector_short *gsl_vector_short_alloc_from_vector (gsl_vector_short * v,\r\n                                                      const size_t offset, \r\n                                                      const size_t n, \r\n                                                      const size_t stride);\r\n\r\nGSL_FUN void gsl_vector_short_free (gsl_vector_short * v);\r\n\r\n/* Views */\r\n\r\nGSL_FUN _gsl_vector_short_view \r\ngsl_vector_short_view_array (short *v, size_t n);\r\n\r\nGSL_FUN _gsl_vector_short_view \r\ngsl_vector_short_view_array_with_stride (short *base,\r\n                                         size_t stride,\r\n                                         size_t n);\r\n\r\nGSL_FUN _gsl_vector_short_const_view \r\ngsl_vector_short_const_view_array (const short *v, size_t n);\r\n\r\nGSL_FUN _gsl_vector_short_const_view \r\ngsl_vector_short_const_view_array_with_stride (const short *base,\r\n                                               size_t stride,\r\n                                               size_t n);\r\n\r\nGSL_FUN _gsl_vector_short_view \r\ngsl_vector_short_subvector (gsl_vector_short *v, \r\n                            size_t i, \r\n                            size_t n);\r\n\r\nGSL_FUN _gsl_vector_short_view \r\ngsl_vector_short_subvector_with_stride (gsl_vector_short *v, \r\n                                        size_t i,\r\n                                        size_t stride,\r\n                                        size_t n);\r\n\r\nGSL_FUN _gsl_vector_short_const_view \r\ngsl_vector_short_const_subvector (const gsl_vector_short *v, \r\n                                  size_t i, \r\n                                  size_t n);\r\n\r\nGSL_FUN _gsl_vector_short_const_view \r\ngsl_vector_short_const_subvector_with_stride (const gsl_vector_short *v, \r\n                                              size_t i, \r\n                                              size_t stride,\r\n                                              size_t n);\r\n\r\n/* Operations */\r\n\r\nGSL_FUN void gsl_vector_short_set_zero (gsl_vector_short * v);\r\nGSL_FUN void gsl_vector_short_set_all (gsl_vector_short * v, short x);\r\nGSL_FUN int gsl_vector_short_set_basis (gsl_vector_short * v, size_t i);\r\n\r\nGSL_FUN int gsl_vector_short_fread (FILE * stream, gsl_vector_short * v);\r\nGSL_FUN int gsl_vector_short_fwrite (FILE * stream, const gsl_vector_short * v);\r\nGSL_FUN int gsl_vector_short_fscanf (FILE * stream, gsl_vector_short * v);\r\nGSL_FUN int gsl_vector_short_fprintf (FILE * stream, const gsl_vector_short * v,\r\n                              const char *format);\r\n\r\nGSL_FUN int gsl_vector_short_memcpy (gsl_vector_short * dest, const gsl_vector_short * src);\r\n\r\nGSL_FUN int gsl_vector_short_reverse (gsl_vector_short * v);\r\n\r\nGSL_FUN int gsl_vector_short_swap (gsl_vector_short * v, gsl_vector_short * w);\r\nGSL_FUN int gsl_vector_short_swap_elements (gsl_vector_short * v, const size_t i, const size_t j);\r\n\r\nGSL_FUN short gsl_vector_short_max (const gsl_vector_short * v);\r\nGSL_FUN short gsl_vector_short_min (const gsl_vector_short * v);\r\nGSL_FUN void gsl_vector_short_minmax (const gsl_vector_short * v, short * min_out, short * max_out);\r\n\r\nGSL_FUN size_t gsl_vector_short_max_index (const gsl_vector_short * v);\r\nGSL_FUN size_t gsl_vector_short_min_index (const gsl_vector_short * v);\r\nGSL_FUN void gsl_vector_short_minmax_index (const gsl_vector_short * v, size_t * imin, size_t * imax);\r\n\r\nGSL_FUN int gsl_vector_short_add (gsl_vector_short * a, const gsl_vector_short * b);\r\nGSL_FUN int gsl_vector_short_sub (gsl_vector_short * a, const gsl_vector_short * b);\r\nGSL_FUN int gsl_vector_short_mul (gsl_vector_short * a, const gsl_vector_short * b);\r\nGSL_FUN int gsl_vector_short_div (gsl_vector_short * a, const gsl_vector_short * b);\r\nGSL_FUN int gsl_vector_short_scale (gsl_vector_short * a, const double x);\r\nGSL_FUN int gsl_vector_short_add_constant (gsl_vector_short * a, const double x);\r\n\r\nGSL_FUN int gsl_vector_short_isnull (const gsl_vector_short * v);\r\nGSL_FUN int gsl_vector_short_ispos (const gsl_vector_short * v);\r\nGSL_FUN int gsl_vector_short_isneg (const gsl_vector_short * v);\r\nGSL_FUN int gsl_vector_short_isnonneg (const gsl_vector_short * v);\r\n\r\nGSL_FUN INLINE_DECL short gsl_vector_short_get (const gsl_vector_short * v, const size_t i);\r\nGSL_FUN INLINE_DECL void gsl_vector_short_set (gsl_vector_short * v, const size_t i, short x);\r\nGSL_FUN INLINE_DECL short * gsl_vector_short_ptr (gsl_vector_short * v, const size_t i);\r\nGSL_FUN INLINE_DECL const short * gsl_vector_short_const_ptr (const gsl_vector_short * v, const size_t i);\r\n\r\n#ifdef HAVE_INLINE\r\n\r\nINLINE_FUN\r\nshort\r\ngsl_vector_short_get (const gsl_vector_short * v, const size_t i)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(i >= v->size))\r\n    {\r\n      GSL_ERROR_VAL (\"index out of range\", GSL_EINVAL, 0);\r\n    }\r\n#endif\r\n  return v->data[i * v->stride];\r\n}\r\n\r\nINLINE_FUN\r\nvoid\r\ngsl_vector_short_set (gsl_vector_short * v, const size_t i, short x)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(i >= v->size))\r\n    {\r\n      GSL_ERROR_VOID (\"index out of range\", GSL_EINVAL);\r\n    }\r\n#endif\r\n  v->data[i * v->stride] = x;\r\n}\r\n\r\nINLINE_FUN\r\nshort *\r\ngsl_vector_short_ptr (gsl_vector_short * v, const size_t i)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(i >= v->size))\r\n    {\r\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\r\n    }\r\n#endif\r\n  return (short *) (v->data + i * v->stride);\r\n}\r\n\r\nINLINE_FUN\r\nconst short *\r\ngsl_vector_short_const_ptr (const gsl_vector_short * v, const size_t i)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(i >= v->size))\r\n    {\r\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\r\n    }\r\n#endif\r\n  return (const short *) (v->data + i * v->stride);\r\n}\r\n#endif /* HAVE_INLINE */\r\n\r\n__END_DECLS\r\n\r\n#endif /* __GSL_VECTOR_SHORT_H__ */\r\n\r\n\r\n", "meta": {"hexsha": "51218c5543da469d23cca218a90d3e32c5593f39", "size": 8199, "ext": "h", "lang": "C", "max_stars_repo_path": "deps/include/gsl/gsl_vector_short.h", "max_stars_repo_name": "berkus/music-cs", "max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "deps/include/gsl/gsl_vector_short.h", "max_issues_repo_name": "berkus/music-cs", "max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "deps/include/gsl/gsl_vector_short.h", "max_forks_repo_name": "berkus/music-cs", "max_forks_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4495798319, "max_line_length": 107, "alphanum_fraction": 0.6689840224, "num_tokens": 1931, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24220563966531902, "lm_q2_score": 0.040237943199081735, "lm_q1q2_score": 0.009745856771350364}}
{"text": "// Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved.\n\n// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"),\n// to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,\n// 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:\n\n// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#ifndef COMMON_H\n#define COMMON_H\n\n#include <cmath>\n#include <optional>\n#include <yato/array_view.h>\n\n//#define CHECK_ASSERT\n\n#include <training/system/Errors.h>\n#include <training/system/Name.h>\n#include <training/system/TypeHalf.h>\n#include <training/system/Types.h>\n\n#include <map>\n#include <utility>\n\n#if defined(_BLAS) && !defined(_BLAS_ENHANCE)\nextern \"C\"\n{\n#include <cblas.h>\n}\n#else\n#ifndef OPENBLAS_CONST\n#define OPENBLAS_CONST const\n#endif\n\ntypedef enum CBLAS_TRANSPOSE\n{\n    CblasNoTrans = 111,\n    CblasTrans = 112,\n    CblasConjTrans = 113,\n    CblasConjNoTrans = 114\n} CBLAS_TRANSPOSE;\n\ntypedef enum CBLAS_UPLO\n{\n    CblasUpper = 121,\n    CblasLower = 122\n} CBLAS_UPLO;\n#endif\n\n#ifdef CHECK_ASSERT\n#define CHECK_NEAR ASSERT_NEAR\n#else\n#define CHECK_NEAR EXPECT_NEAR\n#endif\n\n#define RAUL_E 2.71828182845904523536        // e\n#define RAUL_LOG2E 1.44269504088896340736    // log2(e)\n#define RAUL_LOG10E 0.434294481903251827651  // log10(e)\n#define RAUL_LN2 0.693147180559945309417     // ln(2)\n#define RAUL_LN10 2.30258509299404568402     // ln(10)\n#define RAUL_PI 3.14159265358979323846       // pi\n#define RAUL_PI_2 1.57079632679489661923     // pi/2\n#define RAUL_PI_4 0.785398163397448309616    // pi/4\n#define RAUL_1_PI 0.318309886183790671538    // 1/pi\n#define RAUL_2_PI 0.636619772367581343076    // 2/pi\n#define RAUL_2_SQRTPI 1.12837916709551257390 // 2/sqrt(pi)\n#define RAUL_SQRT2_PI 0.79788456080286535588 // sqrt(2/pi)\n#define RAUL_SQRT2 1.41421356237309504880    // sqrt(2)\n#define RAUL_SQRT1_2 0.707106781186547524401 // 1/sqrt(2)\n\n#define GELU_CONST 0.044715\n\nnamespace raul\n{\n\nenum class Limit : int\n{\n    Left = 0,\n    Middle = 1,\n    Right = 2\n};\n\nenum class Dimension : int\n{\n    Default = -1,\n    Batch = 0,\n    Depth = 1,\n    Height = 2,\n    Width = 3\n};\n\n#if defined(_MSC_VER)\n#define INLINE __forceinline\n#else\n#define INLINE __attribute__((always_inline))\n#endif\n\ntemplate<typename Type>\nclass TensorImpl;\ntypedef TensorImpl<dtype> Tensor;\ntypedef TensorImpl<half> TensorFP16;\n\n#if defined(ANDROID)\n#define TOMMTYPE(var) static_cast<typename MM::type>(var)\n#else\n#define TOMMTYPE(var) castHelper<typename MM::type>::cast(var)\n#endif\n\nusing shape = yato::dimensionality<4U, size_t>;\n} // raul namespace\n\nnamespace raul\n{\n\nenum class NetworkMode\n{\n    Train = 0,\n    Test = 1,\n    TrainCheckpointed = 2\n};\n\nenum class CompressionMode\n{\n    NONE = -1,\n    FP16 = 0,\n    INT8 = 1\n};\n\nenum class CalculationMode\n{\n    DETERMINISTIC = 0,\n#if defined(_OPENMP)\n    FAST = 1,\n#endif\n};\n\n/**\n * @brief Hardware target platform\n *\n */\nenum class ExecutionTarget\n{\n    CPU = 0,\n    CPUFP16 = 1\n};\n\n/**\n * @brief Hardware target platform per layer\n *\n * \\note Might override execution target for workflow, useful for mixed precision\n */\nenum class LayerExecutionTarget\n{\n    Default = -1, // use same as ExecutionTarget\n    CPU = 0,      // from this point enums should be aligned with ExecutionTarget (due to LayerExecutionTarget = static_cast<ExecutionTarget>(enum))\n    CPUFP16 = 1\n};\n\n/**\n * @brief Memory allocation mode\n */\nenum class AllocationMode\n{\n    STANDARD,\n    POOL\n};\n\nenum class DeclarationType\n{\n    Tensor = 0,\n    Shape = 1,\n    //    Alias = 2\n};\n\nclass OpenclInitializer;\n\nclass Common\n{\n  public:\n\n    // generate vector of random index permutation of [0..n-1]\n    static void generate_permutation(size_t n, std::vector<size_t>& ind_vector, unsigned int seed = 0);\n\n    /*\n     * [cols x rows]\n     * A[k x m]\n     * B[n x k]\n     * C[n x m]\n     * https://software.intel.com/en-us/mkl-developer-reference-c-cblas-gemm\n     * C = alpha * A * B + beta * C\n     * bOffset - in elements (not bytes)\n     */\n    static void gemm(OPENBLAS_CONST CBLAS_TRANSPOSE transA,\n                     OPENBLAS_CONST CBLAS_TRANSPOSE transB,\n                     size_t m,\n                     size_t n,\n                     size_t k,\n                     OPENBLAS_CONST dtype alpha,\n                     OPENBLAS_CONST dtype* a,\n                     OPENBLAS_CONST dtype* b,\n                     OPENBLAS_CONST dtype beta,\n                     dtype* c);\n\n    static void gemm(OPENBLAS_CONST CBLAS_TRANSPOSE transA,\n                     OPENBLAS_CONST CBLAS_TRANSPOSE transB,\n                     size_t m,\n                     size_t n,\n                     size_t k,\n                     OPENBLAS_CONST dtype alpha,\n                     OPENBLAS_CONST half* a,\n                     OPENBLAS_CONST half* b,\n                     OPENBLAS_CONST dtype beta,\n                     half* c);\n\n    /**\n     * @brief : Basic Linear Algebra Subroutine y = y + ax\n     *\n     *  \\f[\n     *      \\vec{y} = \\vec{y} + \\alpha * \\vec{x},\n     *  \\f]\n     *\n     * @param n The number of elements in vectors x and y.\n     * @param sa The scalar alpha.\n     * @param sx The vector x of length n. Specified as: a one-dimensional array of (at least) length \\f$ 1+(n-1)|incx| \\f$.\n     * @param incx The stride for vector x. Specified as: an integer. It can have any value.\n     * @param sy The vector y of length n. Specified as: a one-dimensional array of (at least) length \\f$ 1+(n-1)|incy| \\f$.\n     * @param incy The stride for vector y.\n     * @param xOffset The offset for vector x.\n     * @param yOffset The offset for vector y.\n     * @return The vector y, containing the results of the computation.\n     */\n    static void axpy(size_t n, OPENBLAS_CONST dtype sa, OPENBLAS_CONST dtype* sx, size_t incx, dtype* sy, size_t incy, size_t xOffset = 0, size_t yOffset = 0);\n    static void axpy(size_t n, OPENBLAS_CONST dtype sa, OPENBLAS_CONST half* sx, size_t incx, half* sy, size_t incy, size_t xOffset = 0, size_t yOffset = 0);\n\n    /**\n     * @brief : Basic Linear Algebra Subroutine y = ax + by\n     *\n     *  \\f[\n     *      \\vec{y} = \\alpha \\vec{x} + \\beta \\vec{y},\n     *  \\f]\n     *\n     * @param n The number of elements in vectors x and y.\n     * @param alpha The scalar alpha.\n     * @param x The vector x of length n. Specified as: a one-dimensional array of (at least) length \\f$ 1+(n-1)|incx| \\f$.\n     * @param incx The stride for vector x. Specified as: an integer. It can have any value.\n     * @param beta The scalar beta.\n     * @param y The vector y of length n. Specified as: a one-dimensional array of (at least) length \\f$ 1+(n-1)|incy| \\f$.\n     * @param incy The stride for vector y.\n     * @param xOffset The offset for vector x.\n     * @param yOffset The offset for vector y.\n     * @return The vector y, containing the results of the computation.\n     */\n    static int axpby(OPENBLAS_CONST size_t n,\n                     OPENBLAS_CONST dtype alpha,\n                     OPENBLAS_CONST dtype* x,\n                     OPENBLAS_CONST size_t incx,\n                     OPENBLAS_CONST dtype beta,\n                     dtype* y,\n                     OPENBLAS_CONST size_t incy,\n                     size_t xOffset,\n                     size_t yOffset);\n\n    static int axpby(OPENBLAS_CONST size_t n,\n                     OPENBLAS_CONST dtype alpha,\n                     OPENBLAS_CONST half* x,\n                     OPENBLAS_CONST size_t incx,\n                     OPENBLAS_CONST dtype beta,\n                     half* y,\n                     OPENBLAS_CONST size_t incy,\n                     size_t xOffset,\n                     size_t yOffset);\n    /**\n     * @brief : Basic Linear Algebra Subroutine y = alpha * a * x + beta * y\n     *\n     * Vector by vector element wise multiplication\n     *\n     *  \\f[\n     *      \\vec{y} = \\alpha \\vec{a} \\vec{x} + \\beta \\vec{y},\n     *  \\f]\n     *\n     * @param n The number of elements in vectors x and y.\n     * @param alpha The scalar alpha.\n     * @param a The vector of length n.\n     * @param x The vector x of length n. Specified as: a one-dimensional array of (at least) length \\f$ 1+(n-1)|incx| \\f$.\n     * @param incx The stride for vector x. Specified as: an integer. It can have any value.\n     * @param beta The scalar beta.\n     * @param y The vector y of length n. Specified as: a one-dimensional array of (at least) length \\f$ 1+(n-1)|incy| \\f$.\n     * @param incy The stride for vector y.\n     */\n\n    static void hadamard(OPENBLAS_CONST size_t n,\n                         OPENBLAS_CONST dtype alpha,\n                         OPENBLAS_CONST dtype* a,\n                         OPENBLAS_CONST dtype* x,\n                         OPENBLAS_CONST size_t incx,\n                         OPENBLAS_CONST dtype beta,\n                         dtype* y,\n                         OPENBLAS_CONST size_t incy);\n\n    static dtype dot(size_t n, OPENBLAS_CONST dtype* sx, size_t incx, OPENBLAS_CONST dtype* sy, size_t incy);\n\n    static void scal(size_t n, OPENBLAS_CONST dtype sa, dtype* sx, size_t incx);\n\n    static void transpose(Tensor& tensor, size_t cols);\n    static void transpose(TensorFP16& tensor, size_t cols);\n\n    /*\n     * memory for dst should be allocated externaly\n     */\n    static void addPadding1D(const dtype* src, dtype* dst, size_t srcChannels, size_t srcSize, size_t dstSize, bool reversedOrder = false);\n    template<typename T>\n    static void addPadding2D(const T* src, T* dst, size_t srcChannels, size_t srcWidth, size_t srcHeight, size_t dstWidth, size_t dstHeight)\n    {\n        if ((dstWidth >= srcWidth) && (dstHeight >= srcHeight))\n        {\n            size_t padWidth = dstWidth - srcWidth;\n            size_t padHeight = dstHeight - srcHeight;\n\n            size_t leftPad = padWidth / 2;\n            // size_t rightPad = padWidth - leftPad;\n            size_t topPad = padHeight / 2;\n            size_t bottomPad = padHeight - topPad;\n\n            for (size_t d = 0; d < srcChannels; ++d)\n            {\n                // top\n                for (size_t y = 0; y < topPad; ++y)\n                {\n                    for (size_t x = 0; x < dstWidth; ++x)\n                    {\n                        dst[d * dstWidth * dstHeight + dstWidth * y + x] = static_cast<T>(0.0_dt);\n                    }\n                }\n\n                for (size_t y = topPad; y < topPad + srcHeight; ++y)\n                {\n                    // left\n                    for (size_t x = 0; x < leftPad; ++x)\n                    {\n                        dst[d * dstWidth * dstHeight + dstWidth * y + x] = static_cast<T>(0.0_dt);\n                    }\n\n                    // src\n                    for (size_t x = leftPad; x < leftPad + srcWidth; ++x)\n                    {\n                        dst[d * dstWidth * dstHeight + dstWidth * y + x] = src[d * srcWidth * srcHeight + srcWidth * (y - topPad) + x - leftPad];\n                    }\n\n                    // right\n                    for (size_t x = leftPad + srcWidth; x < dstWidth; ++x)\n                    {\n                        dst[d * dstWidth * dstHeight + dstWidth * y + x] = static_cast<T>(0.0_dt);\n                    }\n                }\n\n                // bottom\n                for (size_t y = dstHeight - bottomPad; y < dstHeight; ++y)\n                {\n                    for (size_t x = 0; x < dstWidth; ++x)\n                    {\n                        dst[d * dstWidth * dstHeight + dstWidth * y + x] = static_cast<T>(0.0_dt);\n                    }\n                }\n            }\n        }\n    }\n\n    /*\n     * memory for dst should be allocated externaly\n     */\n    static void removePadding1D(const dtype* src, dtype* dst, size_t srcChannels, size_t srcSize, size_t dstSize, bool reversedOrder = false, bool overwrite = true);\n    template<typename T>\n    static void removePadding2D(const T* src, T* dst, size_t srcChannels, size_t srcWidth, size_t srcHeight, size_t dstWidth, size_t dstHeight, bool overwrite = true)\n    {\n        if ((dstWidth <= srcWidth) && (dstHeight <= srcHeight))\n        {\n            size_t padWidth = srcWidth - dstWidth;\n            size_t padHeight = srcHeight - dstHeight;\n\n            size_t leftPad = padWidth / 2;\n            // size_t rightPad = padWidth - leftPad;\n            size_t topPad = padHeight / 2;\n            // size_t bottomPad = padHeight - topPad;\n\n            if (overwrite)\n            {\n                for (size_t d = 0; d < srcChannels; ++d)\n                {\n                    for (size_t y = 0; y < dstHeight; ++y)\n                    {\n                        for (size_t x = 0; x < dstWidth; ++x)\n                        {\n                            dst[d * dstWidth * dstHeight + dstWidth * y + x] = src[d * srcWidth * srcHeight + srcWidth * (y + topPad) + x + leftPad];\n                        }\n                    }\n                }\n            }\n            else\n            {\n                for (size_t d = 0; d < srcChannels; ++d)\n                {\n                    for (size_t y = 0; y < dstHeight; ++y)\n                    {\n                        for (size_t x = 0; x < dstWidth; ++x)\n                        {\n                            dst[d * dstWidth * dstHeight + dstWidth * y + x] += src[d * srcWidth * srcHeight + srcWidth * (y + topPad) + x + leftPad];\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    /*\n     * paddingWidth, paddingHeight - zero padding added for both sides of the input\n     * memory for matrix should be allocated externaly\n     */\n    template<typename T>\n    static void im2col(const T* image,\n                       size_t imageWidth,\n                       size_t imageHeight,\n                       size_t imageChannels,\n                       size_t filterWidth,\n                       size_t filterHeight,\n                       size_t strideWidth,\n                       size_t strideHeight,\n                       size_t paddingWidth,\n                       size_t paddingHeight,\n                       T* matrix,\n                       bool reversedOrder = false);\n\n    static size_t im2colOutputSize(size_t imageWidth,\n                                   size_t imageHeight,\n                                   size_t imageChannels,\n                                   size_t filterWidth,\n                                   size_t filterHeight,\n                                   size_t strideWidth,\n                                   size_t strideHeight,\n                                   size_t paddingWidth,\n                                   size_t paddingHeight,\n                                   size_t dilationWidth,\n                                   size_t dilationHeight);\n\n    /*\n     * paddingWidth, paddingHeight - zero padding added for both sides of the input\n     * memory for image should be allocated externaly\n     */\n    template<typename T>\n    static void col2im(const T* matrix,\n                       size_t imageWidth,\n                       size_t imageHeight,\n                       size_t imageChannels,\n                       size_t filterWidth,\n                       size_t filterHeight,\n                       size_t strideWidth,\n                       size_t strideHeight,\n                       size_t paddingWidth,\n                       size_t paddingHeight,\n                       T* image,\n                       bool reversedOrder = false,\n                       bool zeroOutput = true);\n\n    /*\n     * Rectified Linear Unit\n     */\n    template<typename T>\n    static T ReLU(T x)\n    {\n        return std::max(static_cast<T>(0), x);\n    }\n    template<typename T>\n    static T ReLU6(T x)\n    {\n        return std::min(std::max(static_cast<T>(0), x), static_cast<T>(6.0_dt));\n    }\n\n    template<typename T>\n    static void ReLU(const T& in, T& out)\n    {\n        std::transform(in.begin(), in.end(), out.begin(), [&](typename T::type val) -> typename T::type { return ReLU(val); });\n    }\n\n    template<typename T>\n    static void ReLU6(const T& in, T& out)\n    {\n        std::transform(in.begin(), in.end(), out.begin(), [&](typename T::type val) -> typename T::type { return ReLU6(val); });\n    }\n\n    template<typename T>\n    static void ReLUBackward(const T& out, const T& delta, T& prevDelta)\n    {\n#if defined(_OPENMP)\n#pragma omp parallel for\n#endif\n        for (size_t q = 0; q < prevDelta.size(); ++q)\n        {\n            prevDelta[q] += (out[q] > static_cast<typename T::type>(0)) ? delta[q] : static_cast<typename T::type>(0);\n        }\n    }\n\n    template<typename T>\n    static void ReLU6Backward(const T& out, const T& delta, T& prevDelta)\n    {\n#if defined(_OPENMP)\n#pragma omp parallel for\n#endif\n        for (size_t q = 0; q < prevDelta.size(); ++q)\n        {\n            prevDelta[q] += (out[q] > static_cast<typename T::type>(0) && out[q] < static_cast<typename T::type>(6.0f)) ? delta[q] : static_cast<typename T::type>(0);\n        }\n    }\n\n    /*\n     * Gaussian error linear unit\n     * @see https://arxiv.org/abs/1606.08415\n     */\n    static dtype GeLU_Erf(dtype x);\n    static dtype GeLU_Tanh(dtype x);\n\n    /*\n     * Hard Sigmoid\n     */\n    template<typename T>\n    static T HSigmoid(T x)\n    {\n        return static_cast<T>(ReLU6(TODTYPE(x) + 3.0_dt) / 6.0_dt);\n    }\n\n    /*\n     * Hard Swish\n     */\n    template<typename T>\n    static T HSwish(T x)\n    {\n        return x * HSigmoid(x);\n    }\n    static dtype sign(dtype x) { return TODTYPE((0.0_dt < x) - (x < 0.0_dt)); }\n\n    template<typename T, typename U>\n    static void copyView(const T& view_from, U& view_to, const bool overwrite = false)\n    {\n        auto retLhs = [](typename T::value_type& lhs, [[maybe_unused]] typename T::value_type& rhs) { return lhs; };\n\n        auto copyViewImpl = [](const T& view_from, U& view_to, auto&& func)\n        {\n            for (size_t i1 = 0; i1 < view_from.size(0); ++i1)\n            {\n                for (size_t i2 = 0; i2 < view_from.size(1); ++i2)\n                {\n                    for (size_t i3 = 0; i3 < view_from.size(2); ++i3)\n                    {\n                        for (size_t i4 = 0; i4 < view_from.size(3); ++i4)\n                        {\n                            view_to[i1][i2][i3][i4] = func(view_from[i1][i2][i3][i4], view_to[i1][i2][i3][i4]);\n                        }\n                    }\n                }\n            }\n        };\n\n        if (overwrite)\n        {\n            copyViewImpl(view_from, view_to, retLhs);\n        }\n        else\n        {\n            copyViewImpl(view_from, view_to, std::plus<typename T::value_type>());\n        }\n    }\n\n    template<typename T>\n    static void unpack4D(const T& src, T& dst, Dimension dir, size_t index, const Name& layerType, const Name& layerName, bool overwrite)\n    {\n        auto input4d = src.get4DView();\n        auto inputDims = yato::dims(src.getDepth(), src.getHeight(), src.getWidth());\n\n        auto outputDims = dst.getShape();\n\n        const typename T::type* startEl = nullptr;\n        switch (dir)\n        {\n            case Dimension::Depth:\n                startEl = &input4d[0][index][0][0];\n                break;\n            case Dimension::Height:\n                startEl = &input4d[0][0][index][0];\n                break;\n            default:\n                throw std::runtime_error(layerType + \"[\" + layerName + \"]: unpack4D unknown dim\");\n        }\n\n        auto srcView = yato::array_view_4d<const typename T::type>(startEl, outputDims, inputDims);\n        auto outputView = dst.get4DView();\n        Common::copyView(srcView, outputView, overwrite);\n    }\n\n    template<typename T>\n    static void pack4D(const T& src, T& dst, Dimension dir, size_t index, const Name& layerType, const Name& layerName, bool overwrite)\n    {\n        auto output4d = dst.get4DView();\n\n        yato::dimensionality<3U, size_t> concatDims(dst.getDepth(), dst.getHeight(), dst.getWidth());\n\n        auto srcView = src.get4DView();\n        typename T::type* startEl = nullptr;\n        switch (dir)\n        {\n            case Dimension::Depth:\n                startEl = &output4d[0][index][0][0];\n                break;\n            case Dimension::Height:\n                startEl = &output4d[0][0][index][0];\n                break;\n            default:\n                throw std::runtime_error(layerType + \"[\" + layerName + \"]: pack4D unknown dim\");\n        }\n\n        auto dstView = yato::array_view_4d<typename T::type>(startEl, src.getShape(), concatDims);\n        Common::copyView(srcView, dstView, overwrite);\n    }\n\n    /*\n     * Upper triangle of a rectangular array\n     */\n    template<typename T>\n    static void triu(T* data, size_t nrows, size_t ncols, int diag = 0)\n    {\n        size_t i = 0;\n        int cols = (int)ncols;\n        int rows = (int)nrows;\n        for (int r = 0; r < rows; ++r)\n        {\n            for (int c = 0; c < cols; ++c, ++i)\n            {\n                if (c - r - diag < 0)\n                {\n                    data[i] = static_cast<T>(0);\n                }\n            }\n        }\n    }\n\n    /*\n     * Applies a 1D convolution over an input signal composed of several input planes.\n     * Supports 2 modes:\n     *  1. PyTorch style: Input[N, C, 1, L1] (or [N, 1, C, L1]) -> Output[N, FILTERS, 1, L2] (or [N, 1, FILTERS, L2])\n     *  2. TensorFlow style: Input[N, L1, 1, C] (or [N, 1, L1, C]) -> Output[N, L2, 1, FILTERS] (or [N, 1, L2, FILTERS])\n     * Output is not zeroed prior to convolution (operator += is used)\n     */\n    static void conv1d(const dtype* input,\n                       dtype* output,\n                       const dtype* kernel,\n                       const dtype* bias,\n                       size_t batchSize,\n                       size_t inputSize,\n                       size_t inputChannels,\n                       size_t outputSize,\n                       size_t outputChannels,\n                       size_t kernelSize,\n                       size_t padding,\n                       size_t stride,\n                       size_t dilation = 1U,\n                       size_t groups = 1U,\n                       bool tfStyle = false);\n\n    /*\n     * Applies 2D convolution over input tensor, all channels convolved\n     * Output is not zeroed prior to convolution (operator += is used)\n     */\n    template<typename T>\n    static void conv2d(const T* input,\n                       T* output,\n                       const T* kernel,\n                       const T* bias,\n                       size_t batchSize,\n                       size_t inputWidth,\n                       size_t inputHeight,\n                       size_t inputChannels,\n                       size_t outputWidth,\n                       size_t outputHeight,\n                       size_t outputChannels,\n                       size_t kernelWidth,\n                       size_t kernelHeight,\n                       size_t paddingW,\n                       size_t paddingH,\n                       size_t strideW,\n                       size_t strideH,\n                       size_t dilationW = 1U,\n                       size_t dilationH = 1U,\n                       size_t groups = 1U)\n    {\n        auto inputs3D = yato::array_view_3d<T>(const_cast<T*>(input), yato::dims(batchSize, inputChannels, inputHeight * inputWidth));\n        auto outputs3D = yato::array_view_3d<T>(output, yato::dims(batchSize, outputChannels, outputHeight * outputWidth));\n        auto kernelsWeights4D = yato::array_view_4d<T>(const_cast<T*>(kernel), yato::dims(outputChannels, inputChannels / groups, kernelHeight, kernelWidth));\n\n        for (size_t q = 0; q < batchSize; ++q)\n        {\n            for (size_t d = 0; d < outputChannels; ++d)\n            {\n                std::fill(outputs3D[q][d].begin(), outputs3D[q][d].end(), static_cast<T>(0.0_dt));\n            }\n\n            size_t inputWidthPadded = inputWidth + 2 * paddingW;\n            size_t inputHeightPadded = inputHeight + 2 * paddingH;\n\n            std::vector<T> inputPadded(inputChannels * inputHeightPadded * inputWidthPadded);\n\n            Common::addPadding2D(&inputs3D[q][0][0], inputPadded.data(), inputChannels, inputWidth, inputHeight, inputWidthPadded, inputHeightPadded);\n\n            auto inputPadded2D = yato::view(inputPadded).reshape(yato::dims(inputChannels, inputHeightPadded * inputWidthPadded));\n\n            for (size_t group = 0; group < groups; ++group)\n            {\n                for (size_t kernelIndex = 0; kernelIndex < outputChannels / groups; ++kernelIndex)\n                {\n                    for (size_t d = 0; d < inputChannels / groups; ++d)\n                    {\n                        for (size_t oy = 0; oy < outputHeight; ++oy)\n                        {\n                            for (size_t ox = 0; ox < outputWidth; ++ox)\n                            {\n                                for (size_t ky = 0; ky < kernelHeight; ++ky)\n                                {\n                                    for (size_t kx = 0; kx < kernelWidth; ++kx)\n                                    {\n                                        outputs3D[q][kernelIndex + group * outputChannels / groups][oy * outputWidth + ox] +=\n                                            kernelsWeights4D[kernelIndex + group * outputChannels / groups][d][ky][kx] *\n                                            inputPadded2D[d + group * inputChannels / groups][oy * inputWidthPadded * strideH + ky * dilationH * inputWidthPadded + ox * strideW + kx * dilationW];\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        if (bias)\n        {\n            for (size_t q = 0; q < batchSize; ++q)\n            {\n                for (size_t kernelIndex = 0; kernelIndex < outputChannels; ++kernelIndex)\n                {\n                    for (size_t oy = 0; oy < outputHeight; ++oy)\n                    {\n                        for (size_t ox = 0; ox < outputWidth; ++ox)\n                        {\n                            outputs3D[q][kernelIndex][oy * outputWidth + ox] += bias[kernelIndex];\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    template<typename T = dtype, typename Iterator>\n    static void arange(Iterator begin, Iterator end, T start = static_cast<T>(0), T step = static_cast<T>(1))\n    {\n        auto val = start;\n        for (auto p = begin; p != end; ++p)\n        {\n            *p = static_cast<std::remove_reference_t<decltype(*p)>>(val);\n            val += step;\n        }\n    }\n\n    template<typename T = dtype, typename Iterable>\n    static void arange(Iterable& i, T start = static_cast<T>(0), T step = static_cast<T>(1))\n    {\n        return arange(i.begin(), i.end(), start, step);\n    }\n\n    static void replaceAll(std::string& str, const std::string& srcSubstr, const std::string& tgtSubstr)\n    {\n        size_t start_pos = 0;\n        while ((start_pos = str.find(srcSubstr, start_pos)) != std::string::npos)\n        {\n            str.replace(start_pos, srcSubstr.length(), tgtSubstr);\n            start_pos += tgtSubstr.length(); // srcSubstr could be a substring of tgtSubstr\n        }\n    }\n\n    static bool startsWith(const std::string& str, const std::string& srcSubstr) { return (str.rfind(srcSubstr, 0) == 0); }\n\n    static std::vector<std::string> split(const std::string& string, char delimeter);\n\n    /*\n     * @see https://docs.scipy.org/doc/numpy-1.13.0/user/basics.broadcasting.html\n     */\n    template<typename T>\n    static bool shapeIsBroadcastable(const T& from, const T& to)\n    {\n        const auto n = to.dimensions_num();\n        for (size_t i = 0; i < n; ++i)\n        {\n            if (from[i] != to[i] && from[i] != 1U && to[i] != 1U)\n            {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    static bool endsWith(std::string const& value, std::string const& ending)\n    {\n        if (ending.size() > value.size())\n        {\n            return false;\n        }\n        return std::equal(ending.rbegin(), ending.rend(), value.rbegin());\n    }\n\n    static shape getStrides(const shape& tensor_shape);\n\n    static shape offsetToIndexes(size_t offset, const shape& strides);\n\n    static size_t indexesToOffset(const shape& indexes, const shape& strides);\n};\n\ntemplate<class T>\nbool if_equals(const std::string&& error, const T val1, const T val2)\n{\n    if (val1 != val2)\n    {\n        throw(std::runtime_error(error));\n    }\n    return val1 == val2;\n}\n\n} // raul namespace\n\n#endif // COMMON_H\n", "meta": {"hexsha": "7afdb9731074bcdc6461c9829d2e1a3060d1bee4", "size": 29303, "ext": "h", "lang": "C", "max_stars_repo_path": "training/src/compiler/training/base/common/Common.h", "max_stars_repo_name": "steelONIONknight/bolt", "max_stars_repo_head_hexsha": "9bd3d08f2abb14435ca3ad0179889e48fa7e9b47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "training/src/compiler/training/base/common/Common.h", "max_issues_repo_name": "steelONIONknight/bolt", "max_issues_repo_head_hexsha": "9bd3d08f2abb14435ca3ad0179889e48fa7e9b47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "training/src/compiler/training/base/common/Common.h", "max_forks_repo_name": "steelONIONknight/bolt", "max_forks_repo_head_hexsha": "9bd3d08f2abb14435ca3ad0179889e48fa7e9b47", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.926102503, "max_line_length": 195, "alphanum_fraction": 0.533324233, "num_tokens": 7228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24220562872535947, "lm_q2_score": 0.04023794219201673, "lm_q1q2_score": 0.00974585608723208}}
{"text": "// --------------------------------------------------------------------------\n//                   OpenMS -- Open-Source Mass Spectrometry\n// --------------------------------------------------------------------------\n// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,\n// ETH Zurich, and Freie Universitaet Berlin 2002-2013.\n//\n// This software is released under a three-clause BSD license:\n//  * Redistributions of source code must retain the above copyright\n//    notice, this list of conditions and the following disclaimer.\n//  * Redistributions in binary form must reproduce the above copyright\n//    notice, this list of conditions and the following disclaimer in the\n//    documentation and/or other materials provided with the distribution.\n//  * Neither the name of any author or any participating institution\n//    may be used to endorse or promote products derived from this software\n//    without specific prior written permission.\n// For a full list of authors, refer to the file AUTHORS.\n// --------------------------------------------------------------------------\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING\n// INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// --------------------------------------------------------------------------\n// $Maintainer: Stephan Aiche$\n// $Authors: Stephan Aiche, Marc Sturm $\n// --------------------------------------------------------------------------\n\n#ifndef OPENMS_TRANSFORMATIONS_FEATUREFINDER_TRACEFITTER_H\n#define OPENMS_TRANSFORMATIONS_FEATUREFINDER_TRACEFITTER_H\n\n#include <OpenMS/TRANSFORMATIONS/FEATUREFINDER/FeatureFinderAlgorithmPickedHelperStructs.h>\n\n#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>\n#include <OpenMS/DATASTRUCTURES/ListUtils.h>\n\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_multifit_nlin.h>\n#include <gsl/gsl_blas.h>\n\nnamespace OpenMS\n{\n\n  /**\n   * @brief Abstract fitter for RT profile fitting\n   *\n   * This class provides the basic interface and some functionality to fit multiple mass traces to\n   * a given RT shape model using the Levenberg-Marquardt algorithm.\n   *\n   * @todo docu needs update\n   *\n   */\n  template <class PeakType>\n  class TraceFitter :\n    public DefaultParamHandler\n  {\n\npublic:\n    /// default constructor.\n    TraceFitter() :\n      DefaultParamHandler(\"TraceFitter\")\n    {\n      defaults_.setValue(\"max_iteration\", 500, \"Maximum number of iterations used by the Levenberg-Marquardt algorithm.\", ListUtils::create<String>(\"advanced\"));\n      defaults_.setValue(\"epsilon_abs\", 0.0001, \"Absolute error used by the Levenberg-Marquardt algorithm.\", ListUtils::create<String>(\"advanced\"));\n      defaults_.setValue(\"epsilon_rel\", 0.0001, \"Relative error used by the Levenberg-Marquardt algorithm.\", ListUtils::create<String>(\"advanced\"));\n      defaults_.setValue(\"weighted\", \"false\", \"Weight mass traces according to their theoretical intensities.\", ListUtils::create<String>(\"advanced\"));\n      defaults_.setValidStrings(\"weighted\", ListUtils::create<String>(\"true,false\"));\n      defaultsToParam_();\n    }\n\n    /// copy constructor\n    TraceFitter(const TraceFitter& source) :\n      DefaultParamHandler(source),\n      epsilon_abs_(source.epsilon_abs_),\n      epsilon_rel_(source.epsilon_rel_),\n      max_iterations_(source.max_iterations_),\n      weighted_(source.weighted_)\n    {\n      updateMembers_();\n    }\n\n    /// assignment operator\n    virtual TraceFitter& operator=(const TraceFitter& source)\n    {\n      DefaultParamHandler::operator=(source);\n      max_iterations_ = source.max_iterations_;\n      epsilon_abs_  = source.epsilon_abs_;\n      epsilon_rel_ = source.epsilon_rel_;\n      weighted_ = source.weighted_;\n      updateMembers_();\n\n      return *this;\n    }\n\n    /// destructor\n    virtual ~TraceFitter()\n    {\n    }\n\n    /**\n     * Main method of the TraceFitter which triggers the actual fitting.\n     */\n    virtual void fit(FeatureFinderAlgorithmPickedHelperStructs::MassTraces<PeakType>& traces) = 0;\n\n    /**\n     * Returns the lower bound of the fitted RT model\n     */\n    virtual DoubleReal getLowerRTBound() const = 0;\n\n    /**\n     * Returns the upper bound of the fitted RT model\n     */\n    virtual DoubleReal getUpperRTBound() const = 0;\n\n    /**\n     * Returns the height of the fitted model\n     */\n    virtual DoubleReal getHeight() const = 0;\n\n    /**\n     * Returns the center position of the fitted model\n     */\n    virtual DoubleReal getCenter() const = 0;\n\n    /**\n     * Returns the mass trace width at half max (FWHM)\n     */\n    virtual DoubleReal getFWHM() const = 0;\n\n    /**\n     * Evaluate the fitted model at a time point\n     */\n    virtual DoubleReal getValue(DoubleReal rt) const = 0;\n\n    /**\n     * Returns the theoretical value of the fitted model at position k in the passed mass trace\n     *\n     * @param trace the mass trace for which the value should be computed\n     * @param k  use the position of the k-th peak to compute the value\n     */\n    DoubleReal computeTheoretical(const FeatureFinderAlgorithmPickedHelperStructs::MassTrace<PeakType>& trace, Size k)\n    {\n      double rt = trace.peaks[k].first;\n\n      return trace.theoretical_int * getValue(rt);\n    }\n\n    /**\n     * Checks if the fitted model fills out at least 'min_rt_span' of the RT span\n     *\n     * @param rt_bounds RT boundaries of the fitted model\n     * @param min_rt_span Minimum RT span in relation to extended area that has to remain after model fitting\n     */\n    virtual bool checkMinimalRTSpan(const std::pair<DoubleReal, DoubleReal>& rt_bounds, const DoubleReal min_rt_span) = 0;\n\n    /**\n     * Checks if the fitted model is not to big\n     *\n     * @param max_rt_span Maximum RT span in relation to extended area that the model is allowed to have\n     */\n    virtual bool checkMaximalRTSpan(const DoubleReal max_rt_span) = 0;\n\n    /**\n     * Returns the peak area of the fitted model\n     */\n    virtual DoubleReal getArea() = 0;\n\n    /**\n     * Returns a textual representation of the fitted model function, that can be plotted using Gnuplot\n     *\n     * @param trace The mass trace that should be plotted\n     * @param function_name The name of the function (e.g. f(x) -> function_name = f)\n     * @param baseline The intensity of the baseline\n     * @param rt_shift A shift value, that allows to plot all RT profiles side by side, even if they would overlap in reality.\n     *                 This should be 0 for the first mass trace and increase by a fixed value for each mass trace.\n     */\n    virtual String getGnuplotFormula(const FeatureFinderAlgorithmPickedHelperStructs::MassTrace<PeakType>& trace, const char function_name, const DoubleReal baseline, const DoubleReal rt_shift) = 0;\n\nprotected:\n\n    /// Structure for passing data to GSL functions\n    struct ModelData\n    {\n      FeatureFinderAlgorithmPickedHelperStructs::MassTraces<PeakType>* traces_ptr;\n      bool weighted;\n    };\n\n    /**\n     * Prints the state of the current iteration (e.g., values of the parameters)\n     *\n     * @param iter Number of current iteration.\n     * @param s The solver that also contains all the parameters.\n     */\n    virtual void printState_(SignedSize iter, gsl_multifit_fdfsolver* s) = 0;\n\n    virtual void updateMembers_()\n    {\n      max_iterations_ = this->param_.getValue(\"max_iteration\");\n      epsilon_abs_ = this->param_.getValue(\"epsilon_abs\");\n      epsilon_rel_ = this->param_.getValue(\"epsilon_rel\");\n      weighted_ = this->param_.getValue(\"weighted\") == \"true\";\n    }\n\n    /**\n     * Updates all member variables to the fitted values stored in the solver.\n     *\n     * @param s The solver containing the fitted parameter values.\n     */\n    virtual void getOptimizedParameters_(gsl_multifit_fdfsolver* s) = 0;\n\n    /**\n     * Optimize the given parameters using the Levenberg-Marquardt algorithm.\n     */\n    void optimize_(FeatureFinderAlgorithmPickedHelperStructs::MassTraces<PeakType> & traces, const Size num_params, double x_init[],\n                   Int (* residual)(const gsl_vector* x, void* params, gsl_vector* f),\n                   Int (* jacobian)(const gsl_vector* x, void* params, gsl_matrix* J),\n                   Int (* evaluate)(const gsl_vector* x, void* params, gsl_vector* f, gsl_matrix * J))\n    {\n      const gsl_multifit_fdfsolver_type* T;\n      gsl_multifit_fdfsolver* s;\n\n      const size_t data_count = traces.getPeakCount();\n\n      // gsl always expects N>=p or default gsl error handler invoked,\n      // cause Jacobian be rectangular M x N with M>=N\n      if (data_count < num_params) throw Exception::UnableToFit(__FILE__, __LINE__, __PRETTY_FUNCTION__, \"UnableToFit-FinalSet\", \"Skipping feature, gsl always expects N>=p\");\n\n      gsl_multifit_function_fdf func;\n      gsl_vector_view x = gsl_vector_view_array(x_init, num_params);\n      gsl_rng_env_setup();\n      func.f = (residual);\n      func.df = (jacobian);\n      func.fdf = (evaluate);\n      func.n = data_count;\n      func.p = num_params;\n      ModelData params = {&traces, weighted_};\n      func.params = &params;\n      T = gsl_multifit_fdfsolver_lmsder;\n      s = gsl_multifit_fdfsolver_alloc(T, data_count, num_params);\n      gsl_multifit_fdfsolver_set(s, &func, &x.vector);\n      SignedSize iter = 0;\n      Int gsl_status_;\n      do\n      {\n        iter++;\n        gsl_status_ = gsl_multifit_fdfsolver_iterate(s);\n        printState_(iter, s);\n        if (gsl_status_) break;\n        gsl_status_ = gsl_multifit_test_delta(s->dx, s->x, epsilon_abs_, epsilon_rel_);\n      }\n      while (gsl_status_ == GSL_CONTINUE && iter < max_iterations_);\n\n      // get the parameters out of the fdfsolver\n      getOptimizedParameters_(s);\n\n      gsl_multifit_fdfsolver_free(s);\n    }\n\n    /** Test for the convergence of the sequence by comparing the last iteration step dx with the absolute error epsabs and relative error epsrel to the current position x */\n    /// Absolute error\n    DoubleReal epsilon_abs_;\n    /// Relative error\n    DoubleReal epsilon_rel_;\n    /// Maximum number of iterations\n    SignedSize max_iterations_;\n    /// Whether to weight mass traces by theoretical intensity during the optimization\n    bool weighted_;\n\n  };\n\n}\n\n#endif // #ifndef OPENMS_TRANSFORMATIONS_FEATUREFINDER_FEATUREFINDERALGORITHMPICKED_RTFITTING_H\n", "meta": {"hexsha": "0c337f129259a259f7099fd852c0dfd7e6144a4d", "size": 10962, "ext": "h", "lang": "C", "max_stars_repo_path": "src/openms/include/OpenMS/TRANSFORMATIONS/FEATUREFINDER/TraceFitter.h", "max_stars_repo_name": "kreinert/OpenMS", "max_stars_repo_head_hexsha": "45455356482ce5ab35e32e445609b291ec78a6d6", "max_stars_repo_licenses": ["Zlib", "Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-12-09T01:45:03.000Z", "max_stars_repo_stars_event_max_datetime": "2016-12-09T01:45:03.000Z", "max_issues_repo_path": "src/openms/include/OpenMS/TRANSFORMATIONS/FEATUREFINDER/TraceFitter.h", "max_issues_repo_name": "kreinert/OpenMS", "max_issues_repo_head_hexsha": "45455356482ce5ab35e32e445609b291ec78a6d6", "max_issues_repo_licenses": ["Zlib", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/openms/include/OpenMS/TRANSFORMATIONS/FEATUREFINDER/TraceFitter.h", "max_forks_repo_name": "kreinert/OpenMS", "max_forks_repo_head_hexsha": "45455356482ce5ab35e32e445609b291ec78a6d6", "max_forks_repo_licenses": ["Zlib", "Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.0106761566, "max_line_length": 198, "alphanum_fraction": 0.6748768473, "num_tokens": 2475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.411110869232168, "lm_q2_score": 0.023689470093140645, "lm_q1q2_score": 0.009738998641640498}}
{"text": "/**\n * This file is part of yasimSBML (http://www.labri.fr/perso/ghozlane/metaboflux/about/yasimSBML.php)\n * Copyright (C) 2010 Amine Ghozlane from LaBRI and University of Bordeaux 1\n *\n * yasimSBML is free software: you can redistribute it and/or modify\n * it under the terms of the Lesser GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * yasimSBML is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the Lesser GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n/**\n * \\file yasimSBML.c\n * \\brief Main program\n * \\author {Amine Ghozlane}\n * \\version 1.0\n * \\date 27 octobre 2009\n */\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include <string.h>\n#include <assert.h>\n#include <unistd.h>\n#include <gsl/gsl_rng.h>\n#include <sbml/SBMLTypes.h>\n#include \"especes.h\"\n#include \"simulation.h\"\n\n/**\n * \\fn int main(int argc, char **argv)\n * \\author Amine Ghozlane\n * \\brief  Enter in the program for simulated annealing\n * \\param  argc Number of arguments\n * \\param  argv List of arguments\n * \\return EXIT_SUCCESS Normal stop of the program\n */\nint main(int argc, char **argv) {\n  SBMLDocument_t *file=NULL;\n  Model_t *mod=NULL;\n  unsigned int errors = 0;\n  /*unsigned int level;\n  unsigned int version;*/\n\n  /* File adress */\n  if (argc <= 2) {\n      fprintf(stderr, \"Usage ./yasimSBML.exe sbml_file.xml number_of_simulation\\n\");\n      return 1;\n  }\n\n  /* Load File  */\n  file = readSBML(argv[1]);\n  errors = SBMLDocument_getNumErrors(file);\n\n  /* Error File */\n  if (errors > 0) {\n      printf(\"Encountered the following SBML error(s):\\n\");\n      SBMLDocument_printErrors(file, stdout);\n      printf(\"Simulation skipped.  Please correct the problems above first.\\n\");\n      return errors;\n  }\n\n  /*level = SBMLDocument_getLevel(file);\n  version = SBMLDocument_getVersion(file);\n  printf(\"SBML Level : %d, version : %d\\n\", level, version);*/\n\n  /* Testing mod file */\n  mod = SBMLDocument_getModel(file);\n  if (mod == NULL)\n    fprintf(stderr, \"Error: file %s doesn't exist!\\n\", argv[1]);\n  /*compute_simulation(mod);*/\n  SBML_compute_simulation_mean(mod,atoi(argv[2]));\n\n  /* free memory */\n  Model_free(mod);\n  /*SBMLDocument_free(file);*/\n\n  return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "d94f83d1176a2a9adf6ad967243b997086b42093", "size": 2557, "ext": "c", "lang": "C", "max_stars_repo_path": "src/yasimSBML.c", "max_stars_repo_name": "aghozlane/yasimSBML", "max_stars_repo_head_hexsha": "bd2067127afaaeccf3292b288797ce90ec9cddc0", "max_stars_repo_licenses": ["DOC"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/yasimSBML.c", "max_issues_repo_name": "aghozlane/yasimSBML", "max_issues_repo_head_hexsha": "bd2067127afaaeccf3292b288797ce90ec9cddc0", "max_issues_repo_licenses": ["DOC"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/yasimSBML.c", "max_forks_repo_name": "aghozlane/yasimSBML", "max_forks_repo_head_hexsha": "bd2067127afaaeccf3292b288797ce90ec9cddc0", "max_forks_repo_licenses": ["DOC"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0568181818, "max_line_length": 101, "alphanum_fraction": 0.6926085256, "num_tokens": 693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30735800417608683, "lm_q2_score": 0.031618770462458395, "lm_q1q2_score": 0.009718282183843019}}
{"text": "/* matrix/gsl_matrix_long_double.h\r\n * \r\n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\r\n * \r\n * This program is free software; you can redistribute it and/or modify\r\n * it under the terms of the GNU General Public License as published by\r\n * the Free Software Foundation; either version 3 of the License, or (at\r\n * your option) any later version.\r\n * \r\n * This program is distributed in the hope that it will be useful, but\r\n * WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n * General Public License for more details.\r\n * \r\n * You should have received a copy of the GNU General Public License\r\n * along with this program; if not, write to the Free Software\r\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r\n */\r\n\r\n#ifndef __GSL_MATRIX_LONG_DOUBLE_H__\r\n#define __GSL_MATRIX_LONG_DOUBLE_H__\r\n\r\n#if !defined( GSL_FUN )\r\n#  if !defined( GSL_DLL )\r\n#    define GSL_FUN extern\r\n#  elif defined( BUILD_GSL_DLL )\r\n#    define GSL_FUN extern __declspec(dllexport)\r\n#  else\r\n#    define GSL_FUN extern __declspec(dllimport)\r\n#  endif\r\n#endif\r\n\r\n#include <stdlib.h>\r\n#include <gsl/gsl_types.h>\r\n#include <gsl/gsl_errno.h>\r\n#include <gsl/gsl_inline.h>\r\n#include <gsl/gsl_check_range.h>\r\n#include <gsl/gsl_vector_long_double.h>\r\n\r\n#undef __BEGIN_DECLS\r\n#undef __END_DECLS\r\n#ifdef __cplusplus\r\n# define __BEGIN_DECLS extern \"C\" {\r\n# define __END_DECLS }\r\n#else\r\n# define __BEGIN_DECLS /* empty */\r\n# define __END_DECLS /* empty */\r\n#endif\r\n\r\n__BEGIN_DECLS\r\n\r\ntypedef struct \r\n{\r\n  size_t size1;\r\n  size_t size2;\r\n  size_t tda;\r\n  long double * data;\r\n  gsl_block_long_double * block;\r\n  int owner;\r\n} gsl_matrix_long_double;\r\n\r\ntypedef struct\r\n{\r\n  gsl_matrix_long_double matrix;\r\n} _gsl_matrix_long_double_view;\r\n\r\ntypedef _gsl_matrix_long_double_view gsl_matrix_long_double_view;\r\n\r\ntypedef struct\r\n{\r\n  gsl_matrix_long_double matrix;\r\n} _gsl_matrix_long_double_const_view;\r\n\r\ntypedef const _gsl_matrix_long_double_const_view gsl_matrix_long_double_const_view;\r\n\r\n/* Allocation */\r\n\r\nGSL_FUN gsl_matrix_long_double * \r\ngsl_matrix_long_double_alloc (const size_t n1, const size_t n2);\r\n\r\nGSL_FUN gsl_matrix_long_double * \r\ngsl_matrix_long_double_calloc (const size_t n1, const size_t n2);\r\n\r\nGSL_FUN gsl_matrix_long_double * \r\ngsl_matrix_long_double_alloc_from_block (gsl_block_long_double * b, \r\n                                   const size_t offset, \r\n                                   const size_t n1, \r\n                                   const size_t n2, \r\n                                   const size_t d2);\r\n\r\nGSL_FUN gsl_matrix_long_double * \r\ngsl_matrix_long_double_alloc_from_matrix (gsl_matrix_long_double * m,\r\n                                    const size_t k1, \r\n                                    const size_t k2,\r\n                                    const size_t n1, \r\n                                    const size_t n2);\r\n\r\nGSL_FUN gsl_vector_long_double * \r\ngsl_vector_long_double_alloc_row_from_matrix (gsl_matrix_long_double * m,\r\n                                        const size_t i);\r\n\r\nGSL_FUN gsl_vector_long_double * \r\ngsl_vector_long_double_alloc_col_from_matrix (gsl_matrix_long_double * m,\r\n                                        const size_t j);\r\n\r\nGSL_FUN void gsl_matrix_long_double_free (gsl_matrix_long_double * m);\r\n\r\n/* Views */\r\n\r\nGSL_FUN _gsl_matrix_long_double_view \r\ngsl_matrix_long_double_submatrix (gsl_matrix_long_double * m, \r\n                            const size_t i, const size_t j, \r\n                            const size_t n1, const size_t n2);\r\n\r\nGSL_FUN _gsl_vector_long_double_view \r\ngsl_matrix_long_double_row (gsl_matrix_long_double * m, const size_t i);\r\n\r\nGSL_FUN _gsl_vector_long_double_view \r\ngsl_matrix_long_double_column (gsl_matrix_long_double * m, const size_t j);\r\n\r\nGSL_FUN _gsl_vector_long_double_view \r\ngsl_matrix_long_double_diagonal (gsl_matrix_long_double * m);\r\n\r\nGSL_FUN _gsl_vector_long_double_view \r\ngsl_matrix_long_double_subdiagonal (gsl_matrix_long_double * m, const size_t k);\r\n\r\nGSL_FUN _gsl_vector_long_double_view \r\ngsl_matrix_long_double_superdiagonal (gsl_matrix_long_double * m, const size_t k);\r\n\r\nGSL_FUN _gsl_vector_long_double_view\r\ngsl_matrix_long_double_subrow (gsl_matrix_long_double * m, const size_t i,\r\n                         const size_t offset, const size_t n);\r\n\r\nGSL_FUN _gsl_vector_long_double_view\r\ngsl_matrix_long_double_subcolumn (gsl_matrix_long_double * m, const size_t j,\r\n                            const size_t offset, const size_t n);\r\n\r\nGSL_FUN _gsl_matrix_long_double_view\r\ngsl_matrix_long_double_view_array (long double * base,\r\n                             const size_t n1, \r\n                             const size_t n2);\r\n\r\nGSL_FUN _gsl_matrix_long_double_view\r\ngsl_matrix_long_double_view_array_with_tda (long double * base, \r\n                                      const size_t n1, \r\n                                      const size_t n2,\r\n                                      const size_t tda);\r\n\r\n\r\nGSL_FUN _gsl_matrix_long_double_view\r\ngsl_matrix_long_double_view_vector (gsl_vector_long_double * v,\r\n                              const size_t n1, \r\n                              const size_t n2);\r\n\r\nGSL_FUN _gsl_matrix_long_double_view\r\ngsl_matrix_long_double_view_vector_with_tda (gsl_vector_long_double * v,\r\n                                       const size_t n1, \r\n                                       const size_t n2,\r\n                                       const size_t tda);\r\n\r\n\r\nGSL_FUN _gsl_matrix_long_double_const_view \r\ngsl_matrix_long_double_const_submatrix (const gsl_matrix_long_double * m, \r\n                                  const size_t i, const size_t j, \r\n                                  const size_t n1, const size_t n2);\r\n\r\nGSL_FUN _gsl_vector_long_double_const_view \r\ngsl_matrix_long_double_const_row (const gsl_matrix_long_double * m, \r\n                            const size_t i);\r\n\r\nGSL_FUN _gsl_vector_long_double_const_view \r\ngsl_matrix_long_double_const_column (const gsl_matrix_long_double * m, \r\n                               const size_t j);\r\n\r\nGSL_FUN _gsl_vector_long_double_const_view\r\ngsl_matrix_long_double_const_diagonal (const gsl_matrix_long_double * m);\r\n\r\nGSL_FUN _gsl_vector_long_double_const_view \r\ngsl_matrix_long_double_const_subdiagonal (const gsl_matrix_long_double * m, \r\n                                    const size_t k);\r\n\r\nGSL_FUN _gsl_vector_long_double_const_view \r\ngsl_matrix_long_double_const_superdiagonal (const gsl_matrix_long_double * m, \r\n                                      const size_t k);\r\n\r\nGSL_FUN _gsl_vector_long_double_const_view\r\ngsl_matrix_long_double_const_subrow (const gsl_matrix_long_double * m, const size_t i,\r\n                               const size_t offset, const size_t n);\r\n\r\nGSL_FUN _gsl_vector_long_double_const_view\r\ngsl_matrix_long_double_const_subcolumn (const gsl_matrix_long_double * m, const size_t j,\r\n                                  const size_t offset, const size_t n);\r\n\r\nGSL_FUN _gsl_matrix_long_double_const_view\r\ngsl_matrix_long_double_const_view_array (const long double * base,\r\n                                   const size_t n1, \r\n                                   const size_t n2);\r\n\r\nGSL_FUN _gsl_matrix_long_double_const_view\r\ngsl_matrix_long_double_const_view_array_with_tda (const long double * base, \r\n                                            const size_t n1, \r\n                                            const size_t n2,\r\n                                            const size_t tda);\r\n\r\nGSL_FUN _gsl_matrix_long_double_const_view\r\ngsl_matrix_long_double_const_view_vector (const gsl_vector_long_double * v,\r\n                                    const size_t n1, \r\n                                    const size_t n2);\r\n\r\nGSL_FUN _gsl_matrix_long_double_const_view\r\ngsl_matrix_long_double_const_view_vector_with_tda (const gsl_vector_long_double * v,\r\n                                             const size_t n1, \r\n                                             const size_t n2,\r\n                                             const size_t tda);\r\n\r\n/* Operations */\r\n\r\nGSL_FUN void gsl_matrix_long_double_set_zero (gsl_matrix_long_double * m);\r\nGSL_FUN void gsl_matrix_long_double_set_identity (gsl_matrix_long_double * m);\r\nGSL_FUN void gsl_matrix_long_double_set_all (gsl_matrix_long_double * m, long double x);\r\n\r\nGSL_FUN int gsl_matrix_long_double_fread (FILE * stream, gsl_matrix_long_double * m) ;\r\nGSL_FUN int gsl_matrix_long_double_fwrite (FILE * stream, const gsl_matrix_long_double * m) ;\r\nGSL_FUN int gsl_matrix_long_double_fscanf (FILE * stream, gsl_matrix_long_double * m);\r\nGSL_FUN int gsl_matrix_long_double_fprintf (FILE * stream, const gsl_matrix_long_double * m, const char * format);\r\n \r\nGSL_FUN int gsl_matrix_long_double_memcpy(gsl_matrix_long_double * dest, const gsl_matrix_long_double * src);\r\nGSL_FUN int gsl_matrix_long_double_swap(gsl_matrix_long_double * m1, gsl_matrix_long_double * m2);\r\n\r\nGSL_FUN int gsl_matrix_long_double_swap_rows(gsl_matrix_long_double * m, const size_t i, const size_t j);\r\nGSL_FUN int gsl_matrix_long_double_swap_columns(gsl_matrix_long_double * m, const size_t i, const size_t j);\r\nGSL_FUN int gsl_matrix_long_double_swap_rowcol(gsl_matrix_long_double * m, const size_t i, const size_t j);\r\nGSL_FUN int gsl_matrix_long_double_transpose (gsl_matrix_long_double * m);\r\nGSL_FUN int gsl_matrix_long_double_transpose_memcpy (gsl_matrix_long_double * dest, const gsl_matrix_long_double * src);\r\n\r\nGSL_FUN long double gsl_matrix_long_double_max (const gsl_matrix_long_double * m);\r\nGSL_FUN long double gsl_matrix_long_double_min (const gsl_matrix_long_double * m);\r\nGSL_FUN void gsl_matrix_long_double_minmax (const gsl_matrix_long_double * m, long double * min_out, long double * max_out);\r\n\r\nGSL_FUN void gsl_matrix_long_double_max_index (const gsl_matrix_long_double * m, size_t * imax, size_t *jmax);\r\nGSL_FUN void gsl_matrix_long_double_min_index (const gsl_matrix_long_double * m, size_t * imin, size_t *jmin);\r\nGSL_FUN void gsl_matrix_long_double_minmax_index (const gsl_matrix_long_double * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);\r\n\r\nGSL_FUN int gsl_matrix_long_double_isnull (const gsl_matrix_long_double * m);\r\nGSL_FUN int gsl_matrix_long_double_ispos (const gsl_matrix_long_double * m);\r\nGSL_FUN int gsl_matrix_long_double_isneg (const gsl_matrix_long_double * m);\r\nGSL_FUN int gsl_matrix_long_double_isnonneg (const gsl_matrix_long_double * m);\r\n\r\nGSL_FUN int gsl_matrix_long_double_add (gsl_matrix_long_double * a, const gsl_matrix_long_double * b);\r\nGSL_FUN int gsl_matrix_long_double_sub (gsl_matrix_long_double * a, const gsl_matrix_long_double * b);\r\nGSL_FUN int gsl_matrix_long_double_mul_elements (gsl_matrix_long_double * a, const gsl_matrix_long_double * b);\r\nGSL_FUN int gsl_matrix_long_double_div_elements (gsl_matrix_long_double * a, const gsl_matrix_long_double * b);\r\nGSL_FUN int gsl_matrix_long_double_scale (gsl_matrix_long_double * a, const double x);\r\nGSL_FUN int gsl_matrix_long_double_add_constant (gsl_matrix_long_double * a, const double x);\r\nGSL_FUN int gsl_matrix_long_double_add_diagonal (gsl_matrix_long_double * a, const double x);\r\n\r\n/***********************************************************************/\r\n/* The functions below are obsolete                                    */\r\n/***********************************************************************/\r\nGSL_FUN int gsl_matrix_long_double_get_row(gsl_vector_long_double * v, const gsl_matrix_long_double * m, const size_t i);\r\nGSL_FUN int gsl_matrix_long_double_get_col(gsl_vector_long_double * v, const gsl_matrix_long_double * m, const size_t j);\r\nGSL_FUN int gsl_matrix_long_double_set_row(gsl_matrix_long_double * m, const size_t i, const gsl_vector_long_double * v);\r\nGSL_FUN int gsl_matrix_long_double_set_col(gsl_matrix_long_double * m, const size_t j, const gsl_vector_long_double * v);\r\n/***********************************************************************/\r\n\r\n/* inline functions if you are using GCC */\r\n\r\nGSL_FUN INLINE_DECL long double   gsl_matrix_long_double_get(const gsl_matrix_long_double * m, const size_t i, const size_t j);\r\nGSL_FUN INLINE_DECL void    gsl_matrix_long_double_set(gsl_matrix_long_double * m, const size_t i, const size_t j, const long double x);\r\nGSL_FUN INLINE_DECL long double * gsl_matrix_long_double_ptr(gsl_matrix_long_double * m, const size_t i, const size_t j);\r\nGSL_FUN INLINE_DECL const long double * gsl_matrix_long_double_const_ptr(const gsl_matrix_long_double * m, const size_t i, const size_t j);\r\n\r\n#ifdef HAVE_INLINE\r\nINLINE_FUN \r\nlong double\r\ngsl_matrix_long_double_get(const gsl_matrix_long_double * m, const size_t i, const size_t j)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(1)) \r\n    {\r\n      if (i >= m->size1)\r\n        {\r\n          GSL_ERROR_VAL(\"first index out of range\", GSL_EINVAL, 0) ;\r\n        }\r\n      else if (j >= m->size2)\r\n        {\r\n          GSL_ERROR_VAL(\"second index out of range\", GSL_EINVAL, 0) ;\r\n        }\r\n    }\r\n#endif\r\n  return m->data[i * m->tda + j] ;\r\n} \r\n\r\nINLINE_FUN \r\nvoid\r\ngsl_matrix_long_double_set(gsl_matrix_long_double * m, const size_t i, const size_t j, const long double x)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(1)) \r\n    {\r\n      if (i >= m->size1)\r\n        {\r\n          GSL_ERROR_VOID(\"first index out of range\", GSL_EINVAL) ;\r\n        }\r\n      else if (j >= m->size2)\r\n        {\r\n          GSL_ERROR_VOID(\"second index out of range\", GSL_EINVAL) ;\r\n        }\r\n    }\r\n#endif\r\n  m->data[i * m->tda + j] = x ;\r\n}\r\n\r\nINLINE_FUN \r\nlong double *\r\ngsl_matrix_long_double_ptr(gsl_matrix_long_double * m, const size_t i, const size_t j)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(1)) \r\n    {\r\n      if (i >= m->size1)\r\n        {\r\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\r\n        }\r\n      else if (j >= m->size2)\r\n        {\r\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\r\n        }\r\n    }\r\n#endif\r\n  return (long double *) (m->data + (i * m->tda + j)) ;\r\n} \r\n\r\nINLINE_FUN \r\nconst long double *\r\ngsl_matrix_long_double_const_ptr(const gsl_matrix_long_double * m, const size_t i, const size_t j)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(1)) \r\n    {\r\n      if (i >= m->size1)\r\n        {\r\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\r\n        }\r\n      else if (j >= m->size2)\r\n        {\r\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\r\n        }\r\n    }\r\n#endif\r\n  return (const long double *) (m->data + (i * m->tda + j)) ;\r\n} \r\n\r\n#endif\r\n\r\n__END_DECLS\r\n\r\n#endif /* __GSL_MATRIX_LONG_DOUBLE_H__ */\r\n", "meta": {"hexsha": "1d06fe8b1e8a527538c884d15054b684ae236b21", "size": 14660, "ext": "h", "lang": "C", "max_stars_repo_path": "deps/include/gsl/gsl_matrix_long_double.h", "max_stars_repo_name": "berkus/music-cs", "max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "deps/include/gsl/gsl_matrix_long_double.h", "max_issues_repo_name": "berkus/music-cs", "max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "deps/include/gsl/gsl_matrix_long_double.h", "max_forks_repo_name": "berkus/music-cs", "max_forks_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.8356545961, "max_line_length": 145, "alphanum_fraction": 0.6762619372, "num_tokens": 3395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29746994260479465, "lm_q2_score": 0.03258974793716635, "lm_q1q2_score": 0.009694470448373597}}
{"text": "#include <gsl/gsl_errno.h>\n#include <gsl/matrix/gsl_matrix.h>\n#include <string.h>\n\n\n#define BASE_DOUBLE\n#include <gsl/templates_on.h>\n#include <gsl/matrix/copy_source.c>\n#include <gsl/templates_off.h>\n#undef BASE_DOUBLE\n", "meta": {"hexsha": "df30e8aa5f74b04ad9941c395a04bed50f8f737b", "size": 220, "ext": "c", "lang": "C", "max_stars_repo_path": "Cartwheel/cartwheel-3d/gsl/matrix/copy.c", "max_stars_repo_name": "MontyThibault/centre-of-mass-awareness", "max_stars_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Cartwheel/cartwheel-3d/gsl/matrix/copy.c", "max_issues_repo_name": "MontyThibault/centre-of-mass-awareness", "max_issues_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cartwheel/cartwheel-3d/gsl/matrix/copy.c", "max_forks_repo_name": "MontyThibault/centre-of-mass-awareness", "max_forks_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0, "max_line_length": 35, "alphanum_fraction": 0.7681818182, "num_tokens": 60, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3665897501624599, "lm_q2_score": 0.02635535169899494, "lm_q1q2_score": 0.009661601794778318}}
{"text": "#pragma once\n\n#include <gsl\\gsl>\n#include <winrt\\Windows.Foundation.h>\n#include <d3d11.h>\n#include \"DrawableGameComponent.h\"\n#include \"MatrixHelper.h\"\n#include \"SpotLight.h\"\n\nnamespace Library\n{\n\tclass ProxyModel;\n}\n\nnamespace Rendering\n{\n\tclass SpotLightMaterial;\n\n\tclass SpotLightDemo final : public Library::DrawableGameComponent\n\t{\n\tpublic:\n\t\tSpotLightDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera);\n\t\tSpotLightDemo(const SpotLightDemo&) = delete;\n\t\tSpotLightDemo(SpotLightDemo&&) = default;\n\t\tSpotLightDemo& operator=(const SpotLightDemo&) = default;\t\t\n\t\tSpotLightDemo& operator=(SpotLightDemo&&) = default;\n\t\t~SpotLightDemo();\n\n\t\tfloat AmbientLightIntensity() const;\n\t\tvoid SetAmbientLightIntensity(float intensity);\n\n\t\tfloat SpotLightIntensity() const;\n\t\tvoid SetSpotLightIntensity(float intensity);\n\n\t\tconst DirectX::XMFLOAT3& LightPosition() const;\n\t\tconst DirectX::XMVECTOR LightPositionVector() const;\n\t\tvoid SetLightPosition(const DirectX::XMFLOAT3& position);\n\t\tvoid SetLightPosition(DirectX::FXMVECTOR position);\n\n\t\tconst DirectX::XMFLOAT3& LightLookAt() const;\n\t\tvoid RotateSpotLight(const DirectX::XMFLOAT2& amount);\n\n\t\tfloat LightRadius() const;\n\t\tvoid SetLightRadius(float radius);\n\n\t\tfloat SpecularIntensity() const;\n\t\tvoid SetSpecularIntensity(float intensity);\n\n\t\tfloat SpecularPower() const;\n\t\tvoid SetSpecularPower(float power);\n\n\t\tfloat SpotLightInnerAngle() const;\n\t\tvoid SetSpotLightInnerAngle(float angle);\n\n\t\tfloat SpotLightOuterAngle() const;\n\t\tvoid SetSpotLightOuterAngle(float angle);\n\n\t\tvirtual void Initialize() override;\n\t\tvirtual void Update(const Library::GameTime& gameTime) override;\n\t\tvirtual void Draw(const Library::GameTime& gameTime) override;\n\n\tprivate:\n\t\tstd::shared_ptr<SpotLightMaterial> mMaterial;\n\t\tDirectX::XMFLOAT4X4 mWorldMatrix{ Library::MatrixHelper::Identity };\n\t\twinrt::com_ptr<ID3D11Buffer> mVertexBuffer;\n\t\tstd::uint32_t mVertexCount{ 0 };\n\t\tLibrary::SpotLight mSpotLight;\n\t\tstd::unique_ptr<Library::ProxyModel> mProxyModel;\n\t\tfloat mModelRotationAngle{ 0.0f };\n\t\tbool mUpdateMaterial{ true };\n\t};\n}", "meta": {"hexsha": "ac4d8856cca5f861baf765957eae6207ca8626a7", "size": 2084, "ext": "h", "lang": "C", "max_stars_repo_path": "source/4.2_Spot_Light/SpotLightDemo.h", "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/4.2_Spot_Light/SpotLightDemo.h", "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/4.2_Spot_Light/SpotLightDemo.h", "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9444444444, "max_line_length": 85, "alphanum_fraction": 0.7711132438, "num_tokens": 524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.02128735260839224, "lm_q1q2_score": 0.009648744782635015}}
{"text": "#pragma once\n\n#include <gsl/gsl>\n#include <memory>\n\nstruct SpeexResamplerState_;\ntypedef struct SpeexResamplerState_ SpeexResamplerState;\n\nnamespace Halley\n{\n\tstruct AudioResamplerResult\n\t{\n\t\tsize_t nRead;\n\t\tsize_t nWritten;\n\t};\n\n\tclass AudioResampler\n\t{\n\tpublic:\n\t\tAudioResampler(int from, int to, int nChannels, float quality = 1.0f);\n\t\t~AudioResampler();\n\n\t\tAudioResamplerResult resample(gsl::span<const float> src, gsl::span<float> dst, size_t channel);\n\t\tAudioResamplerResult resampleInterleaved(gsl::span<const float> src, gsl::span<float> dst);\n\t\tAudioResamplerResult resampleInterleaved(gsl::span<const short> src, gsl::span<short> dst);\n\t\tAudioResamplerResult resampleNoninterleaved(gsl::span<const float> src, gsl::span<float> dst, const size_t numChannels);\n\t\tsize_t numOutputSamples(size_t numInputSamples) const;\n\n\tprivate:\n\t\tstd::unique_ptr<SpeexResamplerState, void(*)(SpeexResamplerState*)> resampler;\n\t\tsize_t nChannels;\n\t\tint from;\n\t\tint to;\n\t};\n}", "meta": {"hexsha": "341b1cfdbb09eae11d584b2bf8f238c96f783c47", "size": 965, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engine/utils/include/halley/audio/resampler.h", "max_stars_repo_name": "sunhay/halley", "max_stars_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3262.0, "max_stars_repo_stars_event_min_datetime": "2016-04-10T15:24:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:47:08.000Z", "max_issues_repo_path": "src/engine/utils/include/halley/audio/resampler.h", "max_issues_repo_name": "sunhay/halley", "max_issues_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 53.0, "max_issues_repo_issues_event_min_datetime": "2016-10-09T16:25:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-10T13:52:37.000Z", "max_forks_repo_path": "src/engine/utils/include/halley/audio/resampler.h", "max_forks_repo_name": "sunhay/halley", "max_forks_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 193.0, "max_forks_repo_forks_event_min_datetime": "2017-10-23T06:08:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T12:59:58.000Z", "avg_line_length": 27.5714285714, "max_line_length": 122, "alphanum_fraction": 0.7678756477, "num_tokens": 276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39981165504266236, "lm_q2_score": 0.024053550664422888, "lm_q1q2_score": 0.009616889900795445}}
{"text": "/* TODO these are parts of the tests from msprime that haven't been ported\n * into the new test framework yet. Once these have all been moved across\n * into the appropriate location, delete.\n */\n#define _GNU_SOURCE\n/*\n * Unit tests for the low-level msprime API.\n */\n#include \"tsk_genotypes.h\"\n#include \"tsk_convert.h\"\n#include \"tsk_stats.h\"\n\n#include <float.h>\n#include <limits.h>\n#include <stdio.h>\n#include <unistd.h>\n\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_randist.h>\n#include <CUnit/Basic.h>\n\n/* Global variables used for test in state in the test suite */\n\nchar *_tmp_file_name;\nFILE *_devnull;\n\n#define SIMPLE_BOTTLENECK 0\n#define INSTANTANEOUS_BOTTLENECK 1\n\ntypedef struct {\n    int type;\n    double time;\n    uint32_t population_id;\n    double parameter;\n} bottleneck_desc_t;\n\n/* Example tree sequences used in some of the tests. */\n\n/* Simple single tree example. */\nconst char *single_tree_ex_nodes = /*          6          */\n    \"1  0   -1   -1\\n\"             /*         / \\         */\n    \"1  0   -1   -1\\n\"             /*        /   \\        */\n    \"1  0   -1   -1\\n\"             /*       /     \\       */\n    \"1  0   -1   -1\\n\"             /*      /       5      */\n    \"0  1   -1   -1\\n\"             /*     4       / \\     */\n    \"0  2   -1   -1\\n\"             /*    / \\     /   \\    */\n    \"0  3   -1   -1\\n\";            /*   0   1   2     3   */\nconst char *single_tree_ex_edges = \"0  1   4   0,1\\n\"\n                                   \"0  1   5   2,3\\n\"\n                                   \"0  1   6   4,5\\n\";\nconst char *single_tree_ex_sites = \"0.1  0\\n\"\n                                   \"0.2  0\\n\"\n                                   \"0.3  0\\n\";\nconst char *single_tree_ex_mutations\n    = \"0    2     1   -1\\n\"\n      \"1    4     1   -1\\n\"\n      \"1    0     0   1\\n\"  /* Back mutation over 0 */\n      \"2    0     1   -1\\n\" /* recurrent mutations over samples */\n      \"2    1     1   -1\\n\"\n      \"2    2     1   -1\\n\"\n      \"2    3     1   -1\\n\";\n\n/* Example from the PLOS paper */\nconst char *paper_ex_nodes = \"1  0       -1   0\\n\"\n                             \"1  0       -1   0\\n\"\n                             \"1  0       -1   1\\n\"\n                             \"1  0       -1   1\\n\"\n                             \"0  0.071   -1   -1\\n\"\n                             \"0  0.090   -1   -1\\n\"\n                             \"0  0.170   -1   -1\\n\"\n                             \"0  0.202   -1   -1\\n\"\n                             \"0  0.253   -1   -1\\n\";\nconst char *paper_ex_edges = \"2 10 4 2\\n\"\n                             \"2 10 4 3\\n\"\n                             \"0 10 5 1\\n\"\n                             \"0 2  5 3\\n\"\n                             \"2 10 5 4\\n\"\n                             \"0 7  6 0,5\\n\"\n                             \"7 10 7 0,5\\n\"\n                             \"0 2  8 2,6\\n\";\n/* We make one mutation for each tree */\nconst char *paper_ex_sites = \"1      0\\n\"\n                             \"4.5    0\\n\"\n                             \"8.5    0\\n\";\nconst char *paper_ex_mutations = \"0      2   1\\n\"\n                                 \"1      0   1\\n\"\n                                 \"2      5   1\\n\";\n/* Two (diploid) indivduals */\nconst char *paper_ex_individuals = \"0      0.2,1.5\\n\"\n                                   \"0      0.0,0.0\\n\";\n\n/* An example of a nonbinary tree sequence */\nconst char *nonbinary_ex_nodes = \"1  0       0   -1\\n\"\n                                 \"1  0       0   -1\\n\"\n                                 \"1  0       0   -1\\n\"\n                                 \"1  0       0   -1\\n\"\n                                 \"1  0       0   -1\\n\"\n                                 \"1  0       0   -1\\n\"\n                                 \"1  0       0   -1\\n\"\n                                 \"1  0       0   -1\\n\"\n                                 \"0  0.01    0   -1\\n\"\n                                 \"0  0.068   0   -1\\n\"\n                                 \"0  0.130   0   -1\\n\"\n                                 \"0  0.279   0   -1\\n\"\n                                 \"0  0.405   0   -1\\n\";\nconst char *nonbinary_ex_edges = \"0\t100\t8\t0,1,2,3\\n\"\n                                 \"0\t100\t9\t6,8\\n\"\n                                 \"0  100 10  4\\n\"\n                                 \"0  17  10  5\\n\"\n                                 \"0  100 10  7\\n\"\n                                 \"17\t100\t11\t5,9\\n\"\n                                 \"0\t17\t12\t9\\n\"\n                                 \"0  100 12  10\\n\"\n                                 \"17\t100\t12\t11\";\nconst char *nonbinary_ex_sites = \"1  0\\n\"\n                                 \"18 0\\n\";\nconst char *nonbinary_ex_mutations = \"0    2   1\\n\"\n                                     \"1    11  1\";\n\n/* An example of a tree sequence with unary nodes. */\n\nconst char *unary_ex_nodes = \"1  0       0  -1\\n\"\n                             \"1  0       0  -1\\n\"\n                             \"1  0       0  -1\\n\"\n                             \"1  0       0  -1\\n\"\n                             \"0  0.071   0  -1\\n\"\n                             \"0  0.090   0  -1\\n\"\n                             \"0  0.170   0  -1\\n\"\n                             \"0  0.202   0  -1\\n\"\n                             \"0  0.253   0  -1\\n\";\nconst char *unary_ex_edges = \"2 10 4 2,3\\n\"\n                             \"0 10 5 1\\n\"\n                             \"0 2  5 3\\n\"\n                             \"2 10 5 4\\n\"\n                             \"0 7  6 0,5\\n\"\n                             \"7 10 7 0\\n\"\n                             \"0 2  7 2\\n\"\n                             \"7 10 7 5\\n\"\n                             \"0 7  8 6\\n\"\n                             \"0 2  8 7\\n\";\n\n/* We make one mutation for each tree, over unary nodes if this exist */\nconst char *unary_ex_sites = \"1.0    0\\n\"\n                             \"4.5    0\\n\"\n                             \"8.5    0\\n\";\nconst char *unary_ex_mutations = \"0    2   1\\n\"\n                                 \"1    6   1\\n\"\n                                 \"2    5   1\\n\";\n\n/* An example of a tree sequence with internally sampled nodes. */\n\n/* TODO: find a way to draw these side-by-side */\n/*\n  7\n+-+-+\n|   5\n| +-++\n| |  4\n| | +++\n| | | 3\n| | |\n| 1 2\n|\n0\n\n  8\n+-+-+\n|   5\n| +-++\n| |  4\n| | +++\n3 | | |\n  | | |\n  1 2 |\n      |\n      0\n\n  6\n+-+-+\n|   5\n| +-++\n| |  4\n| | +++\n| | | 3\n| | |\n| 1 2\n|\n0\n*/\n\nconst char *internal_sample_ex_nodes = \"1  0.0   0   -1\\n\"\n                                       \"1  0.1   0   -1\\n\"\n                                       \"1  0.1   0   -1\\n\"\n                                       \"1  0.2   0   -1\\n\"\n                                       \"0  0.4   0   -1\\n\"\n                                       \"1  0.5   0   -1\\n\"\n                                       \"0  0.7   0   -1\\n\"\n                                       \"0  1.0   0   -1\\n\"\n                                       \"0  1.2   0   -1\\n\";\nconst char *internal_sample_ex_edges = \"2 8  4 0\\n\"\n                                       \"0 10 4 2\\n\"\n                                       \"0 2  4 3\\n\"\n                                       \"8 10 4 3\\n\"\n                                       \"0 10 5 1,4\\n\"\n                                       \"8 10 6 0,5\\n\"\n                                       \"0 2  7 0,5\\n\"\n                                       \"2 8  8 3,5\\n\";\n/* We make one mutation for each tree, some above the internal node */\nconst char *internal_sample_ex_sites = \"1.0    0\\n\"\n                                       \"4.5    0\\n\"\n                                       \"8.5    0\\n\";\nconst char *internal_sample_ex_mutations = \"0    2   1\\n\"\n                                           \"1    5   1\\n\"\n                                           \"2    5   1\\n\";\n\n/* Simple utilities to parse text so we can write declaritive\n * tests. This is not intended as a robust general input mechanism.\n */\n\nstatic void\nparse_nodes(const char *text, tsk_node_tbl_t *node_table)\n{\n    int ret;\n    size_t c, k;\n    size_t MAX_LINE = 1024;\n    char line[MAX_LINE];\n    const char *whitespace = \" \\t\";\n    char *p;\n    double time;\n    int flags, population, individual;\n    char *name;\n\n    c = 0;\n    while (text[c] != '\\0') {\n        /* Fill in the line */\n        k = 0;\n        while (text[c] != '\\n' && text[c] != '\\0') {\n            CU_ASSERT_FATAL(k < MAX_LINE - 1);\n            line[k] = text[c];\n            c++;\n            k++;\n        }\n        if (text[c] == '\\n') {\n            c++;\n        }\n        line[k] = '\\0';\n        p = strtok(line, whitespace);\n        CU_ASSERT_FATAL(p != NULL);\n        flags = atoi(p);\n        p = strtok(NULL, whitespace);\n        CU_ASSERT_FATAL(p != NULL);\n        time = atof(p);\n        p = strtok(NULL, whitespace);\n        CU_ASSERT_FATAL(p != NULL);\n        population = atoi(p);\n        p = strtok(NULL, whitespace);\n        if (p == NULL) {\n            individual = -1;\n        } else {\n            individual = atoi(p);\n            p = strtok(NULL, whitespace);\n        }\n        if (p == NULL) {\n            name = \"\";\n        } else {\n            name = p;\n        }\n        ret = tsk_node_tbl_add_row(\n            node_table, flags, time, population, individual, name, strlen(name));\n        CU_ASSERT_FATAL(ret >= 0);\n    }\n}\n\nstatic void\nparse_edges(const char *text, tsk_edge_tbl_t *edge_table)\n{\n    int ret;\n    size_t c, k;\n    size_t MAX_LINE = 1024;\n    char line[MAX_LINE], sub_line[MAX_LINE];\n    const char *whitespace = \" \\t\";\n    char *p, *q;\n    double left, right;\n    tsk_id_t parent, child;\n    uint32_t num_children;\n\n    c = 0;\n    while (text[c] != '\\0') {\n        /* Fill in the line */\n        k = 0;\n        while (text[c] != '\\n' && text[c] != '\\0') {\n            CU_ASSERT_FATAL(k < MAX_LINE - 1);\n            line[k] = text[c];\n            c++;\n            k++;\n        }\n        if (text[c] == '\\n') {\n            c++;\n        }\n        line[k] = '\\0';\n        p = strtok(line, whitespace);\n        CU_ASSERT_FATAL(p != NULL);\n        left = atof(p);\n        p = strtok(NULL, whitespace);\n        CU_ASSERT_FATAL(p != NULL);\n        right = atof(p);\n        p = strtok(NULL, whitespace);\n        CU_ASSERT_FATAL(p != NULL);\n        parent = atoi(p);\n        num_children = 0;\n        p = strtok(NULL, whitespace);\n        CU_ASSERT_FATAL(p != NULL);\n\n        num_children = 1;\n        q = p;\n        while (*q != '\\0') {\n            if (*q == ',') {\n                num_children++;\n            }\n            q++;\n        }\n        CU_ASSERT_FATAL(num_children >= 1);\n        strncpy(sub_line, p, MAX_LINE);\n        q = strtok(sub_line, \",\");\n        for (k = 0; k < num_children; k++) {\n            CU_ASSERT_FATAL(q != NULL);\n            child = atoi(q);\n            ret = tsk_edge_tbl_add_row(edge_table, left, right, parent, child);\n            CU_ASSERT_FATAL(ret >= 0);\n            q = strtok(NULL, \",\");\n        }\n        CU_ASSERT_FATAL(q == NULL);\n    }\n}\n\nstatic void\nparse_sites(const char *text, tsk_site_tbl_t *site_table)\n{\n    int ret;\n    size_t c, k;\n    size_t MAX_LINE = 1024;\n    char line[MAX_LINE];\n    double position;\n    char ancestral_state[MAX_LINE];\n    const char *whitespace = \" \\t\";\n    char *p;\n\n    c = 0;\n    while (text[c] != '\\0') {\n        /* Fill in the line */\n        k = 0;\n        while (text[c] != '\\n' && text[c] != '\\0') {\n            CU_ASSERT_FATAL(k < MAX_LINE - 1);\n            line[k] = text[c];\n            c++;\n            k++;\n        }\n        if (text[c] == '\\n') {\n            c++;\n        }\n        line[k] = '\\0';\n        p = strtok(line, whitespace);\n        CU_ASSERT_FATAL(p != NULL);\n        position = atof(p);\n        p = strtok(NULL, whitespace);\n        CU_ASSERT_FATAL(p != NULL);\n        strncpy(ancestral_state, p, MAX_LINE);\n        ret = tsk_site_tbl_add_row(\n            site_table, position, ancestral_state, strlen(ancestral_state), NULL, 0);\n        CU_ASSERT_FATAL(ret >= 0);\n    }\n}\n\nstatic void\nparse_mutations(const char *text, tsk_mutation_tbl_t *mutation_table)\n{\n    int ret;\n    size_t c, k;\n    size_t MAX_LINE = 1024;\n    char line[MAX_LINE];\n    const char *whitespace = \" \\t\";\n    char *p;\n    tsk_id_t node;\n    tsk_id_t site;\n    tsk_id_t parent;\n    char derived_state[MAX_LINE];\n\n    c = 0;\n    while (text[c] != '\\0') {\n        /* Fill in the line */\n        k = 0;\n        while (text[c] != '\\n' && text[c] != '\\0') {\n            CU_ASSERT_FATAL(k < MAX_LINE - 1);\n            line[k] = text[c];\n            c++;\n            k++;\n        }\n        if (text[c] == '\\n') {\n            c++;\n        }\n        line[k] = '\\0';\n        p = strtok(line, whitespace);\n        site = atoi(p);\n        CU_ASSERT_FATAL(p != NULL);\n        p = strtok(NULL, whitespace);\n        CU_ASSERT_FATAL(p != NULL);\n        node = atoi(p);\n        p = strtok(NULL, whitespace);\n        CU_ASSERT_FATAL(p != NULL);\n        strncpy(derived_state, p, MAX_LINE);\n        parent = TSK_NULL;\n        p = strtok(NULL, whitespace);\n        if (p != NULL) {\n            parent = atoi(p);\n        }\n        ret = tsk_mutation_tbl_add_row(mutation_table, site, node, parent, derived_state,\n            strlen(derived_state), NULL, 0);\n        CU_ASSERT_FATAL(ret >= 0);\n    }\n}\n\nstatic void\nparse_individuals(const char *text, tsk_individual_tbl_t *individual_table)\n{\n    int ret;\n    size_t c, k;\n    size_t MAX_LINE = 1024;\n    char line[MAX_LINE];\n    char sub_line[MAX_LINE];\n    const char *whitespace = \" \\t\";\n    char *p, *q;\n    double location[MAX_LINE];\n    int location_len;\n    int flags;\n    char *name;\n\n    c = 0;\n    while (text[c] != '\\0') {\n        /* Fill in the line */\n        k = 0;\n        while (text[c] != '\\n' && text[c] != '\\0') {\n            CU_ASSERT_FATAL(k < MAX_LINE - 1);\n            line[k] = text[c];\n            c++;\n            k++;\n        }\n        if (text[c] == '\\n') {\n            c++;\n        }\n        line[k] = '\\0';\n        p = strtok(line, whitespace);\n        CU_ASSERT_FATAL(p != NULL);\n        flags = atoi(p);\n\n        p = strtok(NULL, whitespace);\n        CU_ASSERT_FATAL(p != NULL);\n        // the locations are comma-separated\n        location_len = 1;\n        q = p;\n        while (*q != '\\0') {\n            if (*q == ',') {\n                location_len++;\n            }\n            q++;\n        }\n        CU_ASSERT_FATAL(location_len >= 1);\n        strncpy(sub_line, p, MAX_LINE);\n        q = strtok(sub_line, \",\");\n        for (k = 0; k < location_len; k++) {\n            CU_ASSERT_FATAL(q != NULL);\n            location[k] = atof(q);\n            q = strtok(NULL, \",\");\n        }\n        CU_ASSERT_FATAL(q == NULL);\n        p = strtok(NULL, whitespace);\n        if (p == NULL) {\n            name = \"\";\n        } else {\n            name = p;\n        }\n        ret = tsk_individual_tbl_add_row(\n            individual_table, flags, location, location_len, name, strlen(name));\n        CU_ASSERT_FATAL(ret >= 0);\n    }\n}\n\nstatic void\ntsk_treeseq_from_text(tsk_treeseq_t *ts, double sequence_length, const char *nodes,\n    const char *edges, const char *migrations, const char *sites, const char *mutations,\n    const char *individuals, const char *provenance)\n{\n    int ret;\n    tsk_tbl_collection_t tables;\n    tsk_id_t max_population_id;\n    tsk_tbl_size_t j;\n\n    CU_ASSERT_FATAL(ts != NULL);\n    CU_ASSERT_FATAL(nodes != NULL);\n    CU_ASSERT_FATAL(edges != NULL);\n    /* Not supporting provenance here for now */\n    CU_ASSERT_FATAL(provenance == NULL);\n\n    ret = tsk_tbl_collection_init(&tables, 0);\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n    tables.sequence_length = sequence_length;\n    parse_nodes(nodes, tables.nodes);\n    parse_edges(edges, tables.edges);\n    if (sites != NULL) {\n        parse_sites(sites, tables.sites);\n    }\n    if (mutations != NULL) {\n        parse_mutations(mutations, tables.mutations);\n    }\n    if (individuals != NULL) {\n        parse_individuals(individuals, tables.individuals);\n    }\n    /* We need to add in populations if they are referenced */\n    max_population_id = -1;\n    for (j = 0; j < tables.nodes->num_rows; j++) {\n        max_population_id = TSK_MAX(max_population_id, tables.nodes->population[j]);\n    }\n    if (max_population_id >= 0) {\n        for (j = 0; j <= (tsk_tbl_size_t) max_population_id; j++) {\n            ret = tsk_population_tbl_add_row(tables.populations, NULL, 0);\n            CU_ASSERT_EQUAL_FATAL(ret, j);\n        }\n    }\n\n    ret = tsk_treeseq_init(ts, &tables, TSK_BUILD_INDEXES);\n    /* tsk_treeseq_print_state(ts, stdout); */\n    /* printf(\"ret = %s\\n\", tsk_strerror(ret)); */\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n    tsk_tbl_collection_free(&tables);\n}\n\nstatic int\nget_max_site_mutations(tsk_treeseq_t *ts)\n{\n    int ret;\n    int max_mutations = 0;\n    size_t j;\n    tsk_site_t site;\n\n    for (j = 0; j < tsk_treeseq_get_num_sites(ts); j++) {\n        ret = tsk_treeseq_get_site(ts, j, &site);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        max_mutations = TSK_MAX(max_mutations, site.mutations_length);\n    }\n    return max_mutations;\n}\n\nstatic bool\nmulti_mutations_exist(tsk_treeseq_t *ts, size_t start, size_t end)\n{\n    int ret;\n    size_t j;\n    tsk_site_t site;\n\n    for (j = 0; j < TSK_MIN(tsk_treeseq_get_num_sites(ts), end); j++) {\n        ret = tsk_treeseq_get_site(ts, j, &site);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        if (site.mutations_length > 1) {\n            return true;\n        }\n    }\n    return false;\n}\n\nstatic void\nunsort_edges(tsk_edge_tbl_t *edges, size_t start)\n{\n    size_t j, k;\n    size_t n = edges->num_rows - start;\n    tsk_edge_t *buff = malloc(n * sizeof(tsk_edge_t));\n    gsl_rng *rng = gsl_rng_init(gsl_rng_default);\n\n    CU_ASSERT_FATAL(edges != NULL);\n    CU_ASSERT_FATAL(rng != NULL);\n    gsl_rng_set(rng, 1);\n\n    for (j = 0; j < n; j++) {\n        k = start + j;\n        buff[j].left = edges->left[k];\n        buff[j].right = edges->right[k];\n        buff[j].parent = edges->parent[k];\n        buff[j].child = edges->child[k];\n    }\n    gsl_ran_shuffle(rng, buff, n, sizeof(tsk_edge_t));\n    for (j = 0; j < n; j++) {\n        k = start + j;\n        edges->left[k] = buff[j].left;\n        edges->right[k] = buff[j].right;\n        edges->parent[k] = buff[j].parent;\n        edges->child[k] = buff[j].child;\n    }\n    free(buff);\n    gsl_rng_free(rng);\n}\n\nstatic void\nunsort_sites(tsk_site_tbl_t *sites, tsk_mutation_tbl_t *mutations)\n{\n    double position;\n    char *ancestral_state = NULL;\n    size_t j, k, length;\n\n    if (sites->num_rows > 1) {\n        /* Swap the first two sites */\n        CU_ASSERT_EQUAL_FATAL(sites->ancestral_state_offset[0], 0);\n\n        position = sites->position[0];\n        length = sites->ancestral_state_offset[1];\n        /* Save a copy of the first ancestral state */\n        ancestral_state = malloc(length);\n        CU_ASSERT_FATAL(ancestral_state != NULL);\n        memcpy(ancestral_state, sites->ancestral_state, length);\n        /* Now write the ancestral state for the site 1 here */\n        k = 0;\n        for (j = sites->ancestral_state_offset[1]; j < sites->ancestral_state_offset[2];\n             j++) {\n            sites->ancestral_state[k] = sites->ancestral_state[j];\n            k++;\n        }\n        sites->ancestral_state_offset[1] = k;\n        memcpy(sites->ancestral_state + k, ancestral_state, length);\n        sites->position[0] = sites->position[1];\n        sites->position[1] = position;\n\n        /* Update the mutations for these sites */\n        j = 0;\n        while (j < mutations->num_rows && mutations->site[j] == 0) {\n            mutations->site[j] = 1;\n            j++;\n        }\n        while (j < mutations->num_rows && mutations->site[j] == 1) {\n            mutations->site[j] = 0;\n\n            j++;\n        }\n    }\n    tsk_safe_free(ancestral_state);\n}\n\nstatic void\nadd_individuals(tsk_treeseq_t *ts)\n{\n    int ret;\n    int max_inds = 20;\n    tsk_id_t j;\n    int k = 0;\n    int ploidy = 2;\n    tsk_tbl_collection_t tables;\n    char *metadata = \"abc\";\n    size_t metadata_length = 3;\n    tsk_id_t *samples;\n    tsk_tbl_size_t num_samples = tsk_treeseq_get_num_samples(ts);\n\n    ret = tsk_treeseq_get_samples(ts, &samples);\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n\n    ret = tsk_treeseq_copy_tables(ts, &tables);\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n\n    tsk_individual_tbl_clear(tables.individuals);\n    memset(tables.nodes->individual, 0xff, tables.nodes->num_rows * sizeof(tsk_id_t));\n\n    k = 0;\n    for (j = 0; j < num_samples; j++) {\n        if ((k % ploidy) == 0) {\n            tsk_individual_tbl_add_row(\n                tables.individuals, (uint32_t) k, NULL, 0, metadata, metadata_length);\n            CU_ASSERT_TRUE(ret >= 0)\n        }\n        tables.nodes->individual[samples[j]] = k / ploidy;\n        k += 1;\n        if (k >= ploidy * max_inds) {\n            break;\n        }\n    }\n    ret = tsk_treeseq_free(ts);\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n    ret = tsk_treeseq_init(ts, &tables, TSK_BUILD_INDEXES);\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n    tsk_tbl_collection_free(&tables);\n}\n\nstatic void\nverify_nodes_equal(tsk_node_t *n1, tsk_node_t *n2)\n{\n    double eps = 1e-6;\n\n    CU_ASSERT_DOUBLE_EQUAL_FATAL(n1->time, n1->time, eps);\n    CU_ASSERT_EQUAL_FATAL(n1->population, n2->population);\n    CU_ASSERT_EQUAL_FATAL(n1->flags, n2->flags);\n    CU_ASSERT_FATAL(n1->metadata_length == n2->metadata_length);\n    CU_ASSERT_NSTRING_EQUAL_FATAL(n1->metadata, n2->metadata, n1->metadata_length);\n}\n\nstatic void\nverify_edges_equal(tsk_edge_t *r1, tsk_edge_t *r2, double scale)\n{\n    double eps = 1e-6;\n\n    CU_ASSERT_DOUBLE_EQUAL_FATAL(r1->left * scale, r2->left, eps);\n    CU_ASSERT_DOUBLE_EQUAL_FATAL(r1->right * scale, r2->right, eps);\n    CU_ASSERT_EQUAL_FATAL(r1->parent, r2->parent);\n    CU_ASSERT_EQUAL_FATAL(r1->child, r2->child);\n}\n\nstatic void\nverify_migrations_equal(tsk_migration_t *r1, tsk_migration_t *r2, double scale)\n{\n    double eps = 1e-6;\n\n    CU_ASSERT_DOUBLE_EQUAL_FATAL(r1->left * scale, r2->left, eps);\n    CU_ASSERT_DOUBLE_EQUAL_FATAL(r1->right * scale, r2->right, eps);\n    CU_ASSERT_DOUBLE_EQUAL_FATAL(r1->time, r2->time, eps);\n    CU_ASSERT_EQUAL_FATAL(r1->node, r2->node);\n    CU_ASSERT_EQUAL_FATAL(r1->source, r2->source);\n    CU_ASSERT_EQUAL_FATAL(r1->dest, r2->dest);\n}\n\nstatic void\nverify_provenances_equal(tsk_provenance_t *p1, tsk_provenance_t *p2)\n{\n    CU_ASSERT_FATAL(p1->timestamp_length == p2->timestamp_length);\n    CU_ASSERT_NSTRING_EQUAL_FATAL(p1->timestamp, p2->timestamp, p1->timestamp_length);\n    CU_ASSERT_FATAL(p1->record_length == p2->record_length);\n    CU_ASSERT_NSTRING_EQUAL_FATAL(p1->record, p2->record, p1->record_length);\n}\n\nstatic void\nverify_individuals_equal(tsk_individual_t *i1, tsk_individual_t *i2)\n{\n    tsk_tbl_size_t j;\n\n    CU_ASSERT_FATAL(i1->id == i2->id);\n    CU_ASSERT_FATAL(i1->flags == i2->flags);\n    CU_ASSERT_FATAL(i1->metadata_length == i2->metadata_length);\n    CU_ASSERT_NSTRING_EQUAL_FATAL(i1->metadata, i2->metadata, i1->metadata_length);\n    CU_ASSERT_FATAL(i1->location_length == i2->location_length);\n    for (j = 0; j < i1->location_length; j++) {\n        CU_ASSERT_EQUAL_FATAL(i1->location[j], i2->location[j]);\n    }\n}\n\nstatic void\nverify_populations_equal(tsk_population_t *p1, tsk_population_t *p2)\n{\n    CU_ASSERT_FATAL(p1->id == p2->id);\n    CU_ASSERT_FATAL(p1->metadata_length == p2->metadata_length);\n    CU_ASSERT_NSTRING_EQUAL_FATAL(p1->metadata, p2->metadata, p1->metadata_length);\n}\n\nstatic tsk_tree_t *\nget_tree_list(tsk_treeseq_t *ts)\n{\n    int ret;\n    tsk_tree_t t, *trees;\n    size_t num_trees;\n\n    num_trees = tsk_treeseq_get_num_trees(ts);\n    ret = tsk_tree_init(&t, ts, 0);\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n    trees = malloc(num_trees * sizeof(tsk_tree_t));\n    CU_ASSERT_FATAL(trees != NULL);\n    for (ret = tsk_tree_first(&t); ret == 1; ret = tsk_tree_next(&t)) {\n        CU_ASSERT_FATAL(t.index < num_trees);\n        ret = tsk_tree_init(&trees[t.index], ts, 0);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        ret = tsk_tree_copy(&trees[t.index], &t);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        ret = tsk_tree_equal(&trees[t.index], &t);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        /* Make sure the left and right coordinates are also OK */\n        CU_ASSERT_DOUBLE_EQUAL(trees[t.index].left, t.left, 1e-6);\n        CU_ASSERT_DOUBLE_EQUAL(trees[t.index].right, t.right, 1e-6);\n    }\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n    ret = tsk_tree_free(&t);\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n    return trees;\n}\n\nstatic void\nverify_tree_next_prev(tsk_treeseq_t *ts)\n{\n    int ret;\n    tsk_tree_t *trees, t;\n    size_t j;\n    size_t num_trees = tsk_treeseq_get_num_trees(ts);\n\n    trees = get_tree_list(ts);\n    ret = tsk_tree_init(&t, ts, 0);\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n\n    /* Single forward pass */\n    j = 0;\n    for (ret = tsk_tree_first(&t); ret == 1; ret = tsk_tree_next(&t)) {\n        CU_ASSERT_EQUAL_FATAL(j, t.index);\n        ret = tsk_tree_equal(&t, &trees[t.index]);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        j++;\n    }\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n    CU_ASSERT_EQUAL_FATAL(j, num_trees);\n\n    /* Single reverse pass */\n    j = num_trees;\n    for (ret = tsk_tree_last(&t); ret == 1; ret = tsk_tree_prev(&t)) {\n        CU_ASSERT_EQUAL_FATAL(j - 1, t.index);\n        ret = tsk_tree_equal(&t, &trees[t.index]);\n        if (ret != 0) {\n            printf(\"trees differ\\n\");\n            printf(\"REVERSE tree::\\n\");\n            tsk_tree_print_state(&t, stdout);\n            printf(\"FORWARD tree::\\n\");\n            tsk_tree_print_state(&trees[t.index], stdout);\n        }\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        j--;\n    }\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n    CU_ASSERT_EQUAL_FATAL(j, 0);\n\n    /* Full forward, then reverse */\n    j = 0;\n    for (ret = tsk_tree_first(&t); ret == 1; ret = tsk_tree_next(&t)) {\n        CU_ASSERT_EQUAL_FATAL(j, t.index);\n        ret = tsk_tree_equal(&t, &trees[t.index]);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        j++;\n    }\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n    CU_ASSERT_EQUAL_FATAL(j, num_trees);\n    j--;\n    while ((ret = tsk_tree_prev(&t)) == 1) {\n        CU_ASSERT_EQUAL_FATAL(j - 1, t.index);\n        ret = tsk_tree_equal(&t, &trees[t.index]);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        j--;\n    }\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n    CU_ASSERT_EQUAL_FATAL(j, 0);\n    CU_ASSERT_EQUAL_FATAL(t.index, 0);\n    /* Calling prev should return 0 and have no effect. */\n    for (j = 0; j < 10; j++) {\n        ret = tsk_tree_prev(&t);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        CU_ASSERT_EQUAL_FATAL(t.index, 0);\n        ret = tsk_tree_equal(&t, &trees[t.index]);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n    }\n\n    /* Full reverse then forward */\n    j = num_trees;\n    for (ret = tsk_tree_last(&t); ret == 1; ret = tsk_tree_prev(&t)) {\n        CU_ASSERT_EQUAL_FATAL(j - 1, t.index);\n        ret = tsk_tree_equal(&t, &trees[t.index]);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        j--;\n    }\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n    CU_ASSERT_EQUAL_FATAL(j, 0);\n    j++;\n    while ((ret = tsk_tree_next(&t)) == 1) {\n        CU_ASSERT_EQUAL_FATAL(j, t.index);\n        ret = tsk_tree_equal(&t, &trees[t.index]);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        j++;\n    }\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n    CU_ASSERT_EQUAL_FATAL(j, num_trees);\n    CU_ASSERT_EQUAL_FATAL(t.index, num_trees - 1);\n    /* Calling next should return 0 and have no effect. */\n    for (j = 0; j < 10; j++) {\n        ret = tsk_tree_next(&t);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        CU_ASSERT_EQUAL_FATAL(t.index, num_trees - 1);\n        ret = tsk_tree_equal(&t, &trees[t.index]);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n    }\n\n    /* Do a zigzagging traversal */\n    ret = tsk_tree_first(&t);\n    CU_ASSERT_EQUAL_FATAL(ret, 1);\n    for (j = 1; j < TSK_MIN(10, num_trees / 2); j++) {\n        while (t.index < num_trees - j) {\n            ret = tsk_tree_next(&t);\n            CU_ASSERT_EQUAL_FATAL(ret, 1);\n        }\n        CU_ASSERT_EQUAL_FATAL(t.index, num_trees - j);\n        ret = tsk_tree_equal(&t, &trees[t.index]);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        while (t.index > j) {\n            ret = tsk_tree_prev(&t);\n            CU_ASSERT_EQUAL_FATAL(ret, 1);\n        }\n        CU_ASSERT_EQUAL_FATAL(t.index, j);\n        ret = tsk_tree_equal(&t, &trees[t.index]);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n    }\n\n    /* Free the trees. */\n    ret = tsk_tree_free(&t);\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n    for (j = 0; j < tsk_treeseq_get_num_trees(ts); j++) {\n        ret = tsk_tree_free(&trees[j]);\n    }\n    free(trees);\n}\n\nstatic void\nverify_vargen(tsk_treeseq_t *ts)\n{\n    int ret;\n    tsk_vargen_t vargen;\n    size_t num_samples = tsk_treeseq_get_num_samples(ts);\n    size_t num_sites = tsk_treeseq_get_num_sites(ts);\n    tsk_variant_t *var;\n    size_t j, k, f, s;\n    int flags[] = { 0, TSK_16_BIT_GENOTYPES };\n    tsk_id_t *samples[] = { NULL, NULL };\n\n    ret = tsk_treeseq_get_samples(ts, samples);\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n\n    for (s = 0; s < 2; s++) {\n        for (f = 0; f < sizeof(flags) / sizeof(*flags); f++) {\n            ret = tsk_vargen_init(&vargen, ts, samples[s], num_samples, flags[f]);\n            CU_ASSERT_EQUAL_FATAL(ret, 0);\n            tsk_vargen_print_state(&vargen, _devnull);\n            j = 0;\n            while ((ret = tsk_vargen_next(&vargen, &var)) == 1) {\n                CU_ASSERT_EQUAL(var->site->id, j);\n                if (var->site->mutations_length == 0) {\n                    CU_ASSERT_EQUAL(var->num_alleles, 1);\n                } else {\n                    CU_ASSERT_TRUE(var->num_alleles > 1);\n                }\n                CU_ASSERT_EQUAL(\n                    var->allele_lengths[0], var->site->ancestral_state_length);\n                CU_ASSERT_NSTRING_EQUAL_FATAL(\n                    var->alleles[0], var->site->ancestral_state, var->allele_lengths[0]);\n                for (k = 0; k < var->num_alleles; k++) {\n                    CU_ASSERT_TRUE(var->allele_lengths[k] >= 0);\n                }\n                for (k = 0; k < num_samples; k++) {\n                    if (flags[f] == TSK_16_BIT_GENOTYPES) {\n                        CU_ASSERT(var->genotypes.u16[k] <= var->num_alleles);\n                    } else {\n                        CU_ASSERT(var->genotypes.u8[k] <= var->num_alleles);\n                    }\n                }\n                j++;\n            }\n            CU_ASSERT_EQUAL_FATAL(ret, 0);\n            CU_ASSERT_EQUAL(j, num_sites);\n            CU_ASSERT_EQUAL_FATAL(tsk_vargen_next(&vargen, &var), 0);\n            ret = tsk_vargen_free(&vargen);\n            CU_ASSERT_EQUAL_FATAL(ret, 0);\n        }\n    }\n}\n\nstatic void\nverify_stats(tsk_treeseq_t *ts)\n{\n    int ret;\n    uint32_t num_samples = tsk_treeseq_get_num_samples(ts);\n    tsk_id_t *samples;\n    uint32_t j;\n    double pi;\n    int max_site_mutations = get_max_site_mutations(ts);\n\n    ret = tsk_treeseq_get_pairwise_diversity(ts, NULL, 0, &pi);\n    CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_BAD_PARAM_VALUE);\n    ret = tsk_treeseq_get_pairwise_diversity(ts, NULL, 1, &pi);\n    CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_BAD_PARAM_VALUE);\n    ret = tsk_treeseq_get_pairwise_diversity(ts, NULL, num_samples + 1, &pi);\n    CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_BAD_PARAM_VALUE);\n\n    ret = tsk_treeseq_get_samples(ts, &samples);\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n\n    for (j = 2; j < num_samples; j++) {\n        ret = tsk_treeseq_get_pairwise_diversity(ts, samples, j, &pi);\n        if (max_site_mutations <= 1) {\n            CU_ASSERT_EQUAL_FATAL(ret, 0);\n            CU_ASSERT_TRUE_FATAL(pi >= 0);\n        } else {\n            CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_ONLY_INFINITE_SITES);\n        }\n    }\n}\n\n/* FIXME: this test is weak and should check the return value somehow.\n * We should also have simplest and single tree tests along with separate\n * tests for the error conditions. This should be done as part of the general\n * stats framework.\n */\nstatic void\nverify_genealogical_nearest_neighbours(tsk_treeseq_t *ts)\n{\n    int ret;\n    tsk_id_t *samples;\n    tsk_id_t *sample_sets[2];\n    size_t sample_set_size[2];\n    size_t num_samples = tsk_treeseq_get_num_samples(ts);\n    double *A = malloc(2 * num_samples * sizeof(double));\n    CU_ASSERT_FATAL(A != NULL);\n\n    ret = tsk_treeseq_get_samples(ts, &samples);\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n\n    sample_sets[0] = samples;\n    sample_set_size[0] = num_samples / 2;\n    sample_sets[1] = samples + sample_set_size[0];\n    sample_set_size[1] = num_samples - sample_set_size[0];\n\n    ret = tsk_treeseq_genealogical_nearest_neighbours(\n        ts, samples, num_samples, sample_sets, sample_set_size, 2, 0, A);\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n\n    free(A);\n}\n\n/* FIXME: this test is weak and should check the return value somehow.\n * We should also have simplest and single tree tests along with separate\n * tests for the error conditions. This should be done as part of the general\n * stats framework.\n */\nstatic void\nverify_mean_descendants(tsk_treeseq_t *ts)\n{\n    int ret;\n    tsk_id_t *samples;\n    tsk_id_t *sample_sets[2];\n    size_t sample_set_size[2];\n    size_t num_samples = tsk_treeseq_get_num_samples(ts);\n    double *C = malloc(2 * tsk_treeseq_get_num_nodes(ts) * sizeof(double));\n    CU_ASSERT_FATAL(C != NULL);\n\n    ret = tsk_treeseq_get_samples(ts, &samples);\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n\n    sample_sets[0] = samples;\n    sample_set_size[0] = num_samples / 2;\n    sample_sets[1] = samples + sample_set_size[0];\n    sample_set_size[1] = num_samples - sample_set_size[0];\n\n    ret = tsk_treeseq_mean_descendants(ts, sample_sets, sample_set_size, 2, 0, C);\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n\n    /* Check some error conditions */\n    ret = tsk_treeseq_mean_descendants(ts, sample_sets, sample_set_size, 0, 0, C);\n    CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_BAD_PARAM_VALUE);\n    samples[0] = -1;\n    ret = tsk_treeseq_mean_descendants(ts, sample_sets, sample_set_size, 2, 0, C);\n    CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_OUT_OF_BOUNDS);\n    samples[0] = tsk_treeseq_get_num_nodes(ts) + 1;\n    ret = tsk_treeseq_mean_descendants(ts, sample_sets, sample_set_size, 2, 0, C);\n    CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_OUT_OF_BOUNDS);\n\n    free(C);\n}\n\nstatic void\nverify_compute_mutation_parents(tsk_treeseq_t *ts)\n{\n    int ret;\n    size_t size = tsk_treeseq_get_num_mutations(ts) * sizeof(tsk_id_t);\n    tsk_id_t *parent = malloc(size);\n    tsk_tbl_collection_t tables;\n\n    CU_ASSERT_FATAL(parent != NULL);\n    ret = tsk_treeseq_copy_tables(ts, &tables);\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n    memcpy(parent, tables.mutations->parent, size);\n    /* tsk_tbl_collection_print_state(&tables, stdout); */\n    /* Make sure the tables are actually updated */\n    memset(tables.mutations->parent, 0xff, size);\n\n    ret = tsk_tbl_collection_compute_mutation_parents(&tables, 0);\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n    CU_ASSERT_EQUAL_FATAL(memcmp(parent, tables.mutations->parent, size), 0);\n    /* printf(\"after\\n\"); */\n    /* tsk_tbl_collection_print_state(&tables, stdout); */\n\n    free(parent);\n    tsk_tbl_collection_free(&tables);\n}\n\nstatic void\nverify_individual_nodes(tsk_treeseq_t *ts)\n{\n    int ret;\n    tsk_individual_t individual;\n    tsk_id_t k;\n    size_t num_nodes = tsk_treeseq_get_num_nodes(ts);\n    size_t num_individuals = tsk_treeseq_get_num_individuals(ts);\n    size_t j;\n\n    for (k = 0; k < (tsk_id_t) num_individuals; k++) {\n        ret = tsk_treeseq_get_individual(ts, k, &individual);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        CU_ASSERT_FATAL(individual.nodes_length >= 0);\n        for (j = 0; j < individual.nodes_length; j++) {\n            CU_ASSERT_FATAL(individual.nodes[j] < num_nodes);\n            CU_ASSERT_EQUAL_FATAL(k, ts->tables->nodes->individual[individual.nodes[j]]);\n        }\n    }\n}\n\n/* When we keep all sites in simplify, the genotypes for the subset of the\n * samples should be the same as the original */\nstatic void\nverify_simplify_genotypes(tsk_treeseq_t *ts, tsk_treeseq_t *subset, tsk_id_t *samples,\n    uint32_t num_samples, tsk_id_t *node_map)\n{\n    int ret;\n    size_t m = tsk_treeseq_get_num_sites(ts);\n    tsk_vargen_t vargen, subset_vargen;\n    tsk_variant_t *variant, *subset_variant;\n    size_t j, k;\n    tsk_id_t *all_samples;\n    uint8_t a1, a2;\n    tsk_id_t *sample_index_map;\n\n    tsk_treeseq_get_sample_index_map(ts, &sample_index_map);\n\n    /* tsk_treeseq_print_state(ts, stdout); */\n    /* tsk_treeseq_print_state(subset, stdout); */\n\n    ret = tsk_vargen_init(&vargen, ts, NULL, 0, 0);\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n    ret = tsk_vargen_init(&subset_vargen, subset, NULL, 0, 0);\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n    CU_ASSERT_EQUAL_FATAL(m, tsk_treeseq_get_num_sites(subset));\n    tsk_treeseq_get_samples(ts, &all_samples);\n\n    for (j = 0; j < m; j++) {\n        ret = tsk_vargen_next(&vargen, &variant);\n        CU_ASSERT_EQUAL_FATAL(ret, 1);\n        ret = tsk_vargen_next(&subset_vargen, &subset_variant);\n        CU_ASSERT_EQUAL_FATAL(ret, 1);\n        CU_ASSERT_EQUAL(variant->site->id, j)\n        CU_ASSERT_EQUAL(subset_variant->site->id, j)\n        CU_ASSERT_EQUAL(variant->site->position, subset_variant->site->position);\n        for (k = 0; k < num_samples; k++) {\n            CU_ASSERT_FATAL(sample_index_map[samples[k]] < ts->num_samples);\n            a1 = variant->genotypes.u8[sample_index_map[samples[k]]];\n            a2 = subset_variant->genotypes.u8[k];\n            /* printf(\"a1 = %d, a2 = %d\\n\", a1, a2); */\n            /* printf(\"k = %d original node = %d \" */\n            /*         \"original_index = %d a1=%.*s a2=%.*s\\n\", */\n            /*         (int) k, samples[k], sample_index_map[samples[k]], */\n            /*         variant->allele_lengths[a1], variant->alleles[a1], */\n            /*         subset_variant->allele_lengths[a2], subset_variant->alleles[a2]);\n             */\n            CU_ASSERT_FATAL(a1 < variant->num_alleles);\n            CU_ASSERT_FATAL(a2 < subset_variant->num_alleles);\n            CU_ASSERT_EQUAL_FATAL(\n                variant->allele_lengths[a1], subset_variant->allele_lengths[a2]);\n            CU_ASSERT_NSTRING_EQUAL_FATAL(variant->alleles[a1],\n                subset_variant->alleles[a2], variant->allele_lengths[a1]);\n        }\n    }\n    tsk_vargen_free(&vargen);\n    tsk_vargen_free(&subset_vargen);\n}\n\nstatic void\nverify_simplify_properties(tsk_treeseq_t *ts, tsk_treeseq_t *subset, tsk_id_t *samples,\n    uint32_t num_samples, tsk_id_t *node_map)\n{\n    int ret;\n    tsk_node_t n1, n2;\n    tsk_tree_t full_tree, subset_tree;\n    tsk_site_t *tree_sites;\n    tsk_tbl_size_t tree_sites_length;\n    uint32_t j, k;\n    tsk_id_t u, mrca1, mrca2;\n    size_t total_sites;\n\n    CU_ASSERT_EQUAL(\n        tsk_treeseq_get_sequence_length(ts), tsk_treeseq_get_sequence_length(subset));\n    CU_ASSERT_EQUAL(tsk_treeseq_get_num_samples(subset), num_samples);\n    CU_ASSERT(tsk_treeseq_get_num_nodes(ts) >= tsk_treeseq_get_num_nodes(subset));\n    CU_ASSERT_EQUAL(tsk_treeseq_get_num_samples(subset), num_samples);\n\n    /* Check the sample properties */\n    for (j = 0; j < num_samples; j++) {\n        ret = tsk_treeseq_get_node(ts, samples[j], &n1);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        CU_ASSERT_EQUAL(node_map[samples[j]], j);\n        ret = tsk_treeseq_get_node(subset, node_map[samples[j]], &n2);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        CU_ASSERT_EQUAL_FATAL(n1.population, n2.population);\n        CU_ASSERT_EQUAL_FATAL(n1.time, n2.time);\n        CU_ASSERT_EQUAL_FATAL(n1.flags, n2.flags);\n        CU_ASSERT_EQUAL_FATAL(n1.metadata_length, n2.metadata_length);\n        CU_ASSERT_NSTRING_EQUAL(n1.metadata, n2.metadata, n2.metadata_length);\n    }\n    /* Check that node mappings are correct */\n    for (j = 0; j < tsk_treeseq_get_num_nodes(ts); j++) {\n        ret = tsk_treeseq_get_node(ts, j, &n1);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        if (node_map[j] != TSK_NULL) {\n            ret = tsk_treeseq_get_node(subset, node_map[j], &n2);\n            CU_ASSERT_EQUAL_FATAL(ret, 0);\n            CU_ASSERT_EQUAL_FATAL(n1.population, n2.population);\n            CU_ASSERT_EQUAL_FATAL(n1.time, n2.time);\n            CU_ASSERT_EQUAL_FATAL(n1.flags, n2.flags);\n            CU_ASSERT_EQUAL_FATAL(n1.metadata_length, n2.metadata_length);\n            CU_ASSERT_NSTRING_EQUAL(n1.metadata, n2.metadata, n2.metadata_length);\n        }\n    }\n    if (num_samples == 0) {\n        CU_ASSERT_EQUAL(tsk_treeseq_get_num_edges(subset), 0);\n        CU_ASSERT_EQUAL(tsk_treeseq_get_num_nodes(subset), 0);\n    } else if (num_samples == 1) {\n        CU_ASSERT_EQUAL(tsk_treeseq_get_num_edges(subset), 0);\n        CU_ASSERT_EQUAL(tsk_treeseq_get_num_nodes(subset), 1);\n    }\n    /* Check the pairwise MRCAs */\n    ret = tsk_tree_init(&full_tree, ts, 0);\n    CU_ASSERT_EQUAL(ret, 0);\n    ret = tsk_tree_init(&subset_tree, subset, 0);\n    CU_ASSERT_EQUAL(ret, 0);\n    ret = tsk_tree_first(&full_tree);\n    CU_ASSERT_EQUAL(ret, 1);\n    ret = tsk_tree_first(&subset_tree);\n    CU_ASSERT_EQUAL(ret, 1);\n\n    total_sites = 0;\n    while (1) {\n        while (full_tree.right <= subset_tree.right) {\n            for (j = 0; j < num_samples; j++) {\n                for (k = j + 1; k < num_samples; k++) {\n                    ret = tsk_tree_get_mrca(&full_tree, samples[j], samples[k], &mrca1);\n                    CU_ASSERT_EQUAL_FATAL(ret, 0);\n                    ret = tsk_tree_get_mrca(&subset_tree, node_map[samples[j]],\n                        node_map[samples[k]], &mrca2);\n                    CU_ASSERT_EQUAL_FATAL(ret, 0);\n                    if (mrca1 == TSK_NULL) {\n                        CU_ASSERT_EQUAL_FATAL(mrca2, TSK_NULL);\n                    } else {\n                        CU_ASSERT_EQUAL(node_map[mrca1], mrca2);\n                    }\n                }\n            }\n            ret = tsk_tree_next(&full_tree);\n            CU_ASSERT_FATAL(ret >= 0);\n            if (ret != 1) {\n                break;\n            }\n        }\n        /* Check the sites in this tree */\n        ret = tsk_tree_get_sites(&subset_tree, &tree_sites, &tree_sites_length);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n\n        for (j = 0; j < tree_sites_length; j++) {\n            CU_ASSERT(subset_tree.left <= tree_sites[j].position);\n            CU_ASSERT(tree_sites[j].position < subset_tree.right);\n            for (k = 0; k < tree_sites[j].mutations_length; k++) {\n                ret = tsk_tree_get_parent(\n                    &subset_tree, tree_sites[j].mutations[k].node, &u);\n                CU_ASSERT_EQUAL(ret, 0);\n            }\n            total_sites++;\n        }\n        ret = tsk_tree_next(&subset_tree);\n        if (ret != 1) {\n            break;\n        }\n    }\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n    CU_ASSERT_EQUAL(tsk_treeseq_get_num_sites(subset), total_sites);\n\n    tsk_tree_free(&subset_tree);\n    tsk_tree_free(&full_tree);\n    verify_vargen(subset);\n}\n\nstatic void\nverify_simplify(tsk_treeseq_t *ts)\n{\n    int ret;\n    uint32_t n = tsk_treeseq_get_num_samples(ts);\n    uint32_t num_samples[] = { 0, 1, 2, 3, n / 2, n - 1, n };\n    size_t j;\n    tsk_id_t *sample;\n    tsk_id_t *node_map = malloc(tsk_treeseq_get_num_nodes(ts) * sizeof(tsk_id_t));\n    tsk_treeseq_t subset;\n    int flags = TSK_FILTER_SITES;\n\n    CU_ASSERT_FATAL(node_map != NULL);\n    ret = tsk_treeseq_get_samples(ts, &sample);\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n    if (tsk_treeseq_get_num_migrations(ts) > 0) {\n        ret = tsk_treeseq_simplify(ts, sample, 2, 0, &subset, NULL);\n        CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_SIMPLIFY_MIGRATIONS_NOT_SUPPORTED);\n        /* Exiting early here because simplify isn't supported with migrations. */\n        goto out;\n    }\n\n    for (j = 0; j < sizeof(num_samples) / sizeof(uint32_t); j++) {\n        if (num_samples[j] <= n) {\n            ret = tsk_treeseq_simplify(\n                ts, sample, num_samples[j], flags, &subset, node_map);\n            /* printf(\"ret = %s\\n\", tsk_strerror(ret)); */\n            CU_ASSERT_EQUAL_FATAL(ret, 0);\n            verify_simplify_properties(ts, &subset, sample, num_samples[j], node_map);\n            tsk_treeseq_free(&subset);\n\n            /* Keep all sites */\n            ret = tsk_treeseq_simplify(ts, sample, num_samples[j], 0, &subset, node_map);\n            CU_ASSERT_EQUAL_FATAL(ret, 0);\n            verify_simplify_properties(ts, &subset, sample, num_samples[j], node_map);\n            verify_simplify_genotypes(ts, &subset, sample, num_samples[j], node_map);\n            tsk_treeseq_free(&subset);\n        }\n    }\nout:\n    free(node_map);\n}\n\nstatic void\nverify_reduce_topology(tsk_treeseq_t *ts)\n{\n    int ret;\n    size_t j;\n    tsk_id_t *sample;\n    tsk_treeseq_t reduced;\n    tsk_edge_t edge;\n    double *X;\n    size_t num_sites;\n    size_t n = tsk_treeseq_get_num_samples(ts);\n    int flags = TSK_REDUCE_TO_SITE_TOPOLOGY;\n\n    ret = tsk_treeseq_get_samples(ts, &sample);\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n\n    if (tsk_treeseq_get_num_migrations(ts) > 0) {\n        ret = tsk_treeseq_simplify(ts, sample, 2, flags, &reduced, NULL);\n        CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_SIMPLIFY_MIGRATIONS_NOT_SUPPORTED);\n        return;\n    }\n\n    ret = tsk_treeseq_simplify(ts, sample, n, flags, &reduced, NULL);\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n    X = reduced.tables->sites->position;\n    num_sites = reduced.tables->sites->num_rows;\n    if (num_sites == 0) {\n        CU_ASSERT_EQUAL_FATAL(tsk_treeseq_get_num_edges(&reduced), 0);\n    }\n    for (j = 0; j < tsk_treeseq_get_num_edges(&reduced); j++) {\n        ret = tsk_treeseq_get_edge(&reduced, j, &edge);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        if (edge.left != 0) {\n            CU_ASSERT_EQUAL_FATAL(\n                edge.left, X[tsk_search_sorted(X, num_sites, edge.left)]);\n        }\n        if (edge.right != tsk_treeseq_get_sequence_length(&reduced)) {\n            CU_ASSERT_EQUAL_FATAL(\n                edge.right, X[tsk_search_sorted(X, num_sites, edge.right)]);\n        }\n    }\n    tsk_treeseq_free(&reduced);\n}\n\n/* Utility function to return a tree sequence for testing. It is the\n * callers responsilibility to free all memory.\n */\nstatic tsk_treeseq_t *\nget_example_tree_sequence(uint32_t num_samples, uint32_t num_historical_samples,\n    uint32_t num_loci, double sequence_length, double recombination_rate,\n    double mutation_rate, uint32_t num_bottlenecks, bottleneck_desc_t *bottlenecks,\n    int alphabet)\n{\n    return NULL;\n}\n\ntsk_treeseq_t **\nget_example_nonbinary_tree_sequences(void)\n{\n    return NULL;\n}\n\ntsk_treeseq_t *\nmake_recurrent_and_back_mutations_copy(tsk_treeseq_t *ts)\n{\n    return NULL;\n}\n\ntsk_treeseq_t *\nmake_permuted_nodes_copy(tsk_treeseq_t *ts)\n{\n    return NULL;\n}\n\n/* Insert some gaps into the specified tree sequence, i.e., positions\n * that no edge covers. */\ntsk_treeseq_t *\nmake_gappy_copy(tsk_treeseq_t *ts)\n{\n    return NULL;\n}\n\n/* Return a copy of the tree sequence after deleting half of its edges.\n */\ntsk_treeseq_t *\nmake_decapitated_copy(tsk_treeseq_t *ts)\n{\n    return NULL;\n}\n\ntsk_treeseq_t *\nmake_multichar_mutations_copy(tsk_treeseq_t *ts)\n{\n    return NULL;\n}\n\ntsk_treeseq_t **\nget_example_tree_sequences(int include_nonbinary)\n{\n    size_t max_examples = 1024;\n    tsk_treeseq_t **ret = malloc(max_examples * sizeof(tsk_treeseq_t *));\n    ret[0] = NULL;\n    return ret;\n}\n\nstatic void\nverify_vcf_converter(tsk_treeseq_t *ts, unsigned int ploidy)\n{\n    int ret;\n    char *str = NULL;\n    tsk_vcf_converter_t vc;\n    unsigned int num_variants;\n\n    ret = tsk_vcf_converter_init(&vc, ts, ploidy, \"chr1234\");\n    CU_ASSERT_FATAL(ret == 0);\n    tsk_vcf_converter_print_state(&vc, _devnull);\n    ret = tsk_vcf_converter_get_header(&vc, &str);\n    CU_ASSERT_EQUAL(ret, 0);\n    CU_ASSERT_NSTRING_EQUAL(\"##\", str, 2);\n    num_variants = 0;\n    while ((ret = tsk_vcf_converter_next(&vc, &str)) == 1) {\n        CU_ASSERT_NSTRING_EQUAL(\"chr1234\\t\", str, 2);\n        num_variants++;\n    }\n    CU_ASSERT_EQUAL(ret, 0);\n    CU_ASSERT_TRUE(num_variants == tsk_treeseq_get_num_mutations(ts));\n    tsk_vcf_converter_free(&vc);\n}\n\nstatic void\ntest_node_metadata(void)\n{\n    const char *nodes = \"1  0   0   -1   n1\\n\"\n                        \"1  0   0   -1   n2\\n\"\n                        \"0  1   0   -1   A_much_longer_name\\n\"\n                        \"0  1   0   -1\\n\"\n                        \"0  1   0   -1   n4\";\n    const char *edges = \"0  1   2   0,1\\n\";\n    tsk_treeseq_t ts;\n    int ret;\n    tsk_node_t node;\n\n    tsk_treeseq_from_text(&ts, 1, nodes, edges, NULL, NULL, NULL, NULL, NULL);\n    CU_ASSERT_EQUAL(tsk_treeseq_get_num_samples(&ts), 2);\n    CU_ASSERT_EQUAL(tsk_treeseq_get_num_nodes(&ts), 5);\n\n    ret = tsk_treeseq_get_node(&ts, 0, &node);\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n    CU_ASSERT_NSTRING_EQUAL(node.metadata, \"n1\", 2);\n\n    ret = tsk_treeseq_get_node(&ts, 1, &node);\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n    CU_ASSERT_NSTRING_EQUAL(node.metadata, \"n2\", 2);\n\n    ret = tsk_treeseq_get_node(&ts, 2, &node);\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n    CU_ASSERT_NSTRING_EQUAL(node.metadata, \"A_much_longer_name\", 18);\n\n    ret = tsk_treeseq_get_node(&ts, 3, &node);\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n    CU_ASSERT_NSTRING_EQUAL(node.metadata, \"\", 0);\n\n    ret = tsk_treeseq_get_node(&ts, 4, &node);\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n    CU_ASSERT_NSTRING_EQUAL(node.metadata, \"n4\", 2);\n\n    tsk_treeseq_free(&ts);\n}\n\nstatic void\nverify_trees_consistent(tsk_treeseq_t *ts)\n{\n    int ret;\n    size_t num_trees;\n    tsk_tree_t tree;\n\n    ret = tsk_tree_init(&tree, ts, 0);\n    CU_ASSERT_EQUAL(ret, 0);\n\n    num_trees = 0;\n    for (ret = tsk_tree_first(&tree); ret == 1; ret = tsk_tree_next(&tree)) {\n        tsk_tree_print_state(&tree, _devnull);\n        CU_ASSERT_EQUAL(tree.index, num_trees);\n        num_trees++;\n    }\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n    CU_ASSERT_EQUAL(tsk_treeseq_get_num_trees(ts), num_trees);\n\n    tsk_tree_free(&tree);\n}\n\nstatic void\nverify_ld(tsk_treeseq_t *ts)\n{\n    int ret;\n    size_t num_sites = tsk_treeseq_get_num_sites(ts);\n    tsk_site_t *sites = malloc(num_sites * sizeof(tsk_site_t));\n    int *num_site_mutations = malloc(num_sites * sizeof(int));\n    tsk_ld_calc_t ld_calc;\n    double *r2, *r2_prime, x;\n    size_t j, num_r2_values;\n    double eps = 1e-6;\n\n    r2 = calloc(num_sites, sizeof(double));\n    r2_prime = calloc(num_sites, sizeof(double));\n    CU_ASSERT_FATAL(r2 != NULL);\n    CU_ASSERT_FATAL(r2_prime != NULL);\n    CU_ASSERT_FATAL(sites != NULL);\n    CU_ASSERT_FATAL(num_site_mutations != NULL);\n\n    ret = tsk_ld_calc_init(&ld_calc, ts);\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n    tsk_ld_calc_print_state(&ld_calc, _devnull);\n\n    for (j = 0; j < num_sites; j++) {\n        ret = tsk_treeseq_get_site(ts, j, sites + j);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        num_site_mutations[j] = sites[j].mutations_length;\n        ret = tsk_ld_calc_get_r2(&ld_calc, j, j, &x);\n        if (num_site_mutations[j] <= 1) {\n            CU_ASSERT_EQUAL_FATAL(ret, 0);\n            CU_ASSERT_DOUBLE_EQUAL_FATAL(x, 1.0, eps);\n        } else {\n            CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_ONLY_INFINITE_SITES);\n        }\n    }\n\n    if (num_sites > 0) {\n        /* Some checks in the forward direction */\n        ret = tsk_ld_calc_get_r2_array(\n            &ld_calc, 0, TSK_DIR_FORWARD, num_sites, DBL_MAX, r2, &num_r2_values);\n        if (multi_mutations_exist(ts, 0, num_sites)) {\n            CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_ONLY_INFINITE_SITES);\n        } else {\n            CU_ASSERT_EQUAL_FATAL(ret, 0);\n            CU_ASSERT_EQUAL_FATAL(num_r2_values, num_sites - 1);\n        }\n        tsk_ld_calc_print_state(&ld_calc, _devnull);\n\n        ret = tsk_ld_calc_get_r2_array(&ld_calc, num_sites - 2, TSK_DIR_FORWARD,\n            num_sites, DBL_MAX, r2_prime, &num_r2_values);\n        if (multi_mutations_exist(ts, num_sites - 2, num_sites)) {\n            CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_ONLY_INFINITE_SITES);\n        } else {\n            CU_ASSERT_EQUAL_FATAL(ret, 0);\n            CU_ASSERT_EQUAL_FATAL(num_r2_values, 1);\n        }\n        tsk_ld_calc_print_state(&ld_calc, _devnull);\n\n        ret = tsk_ld_calc_get_r2_array(\n            &ld_calc, 0, TSK_DIR_FORWARD, num_sites, DBL_MAX, r2_prime, &num_r2_values);\n        if (multi_mutations_exist(ts, 0, num_sites)) {\n            CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_ONLY_INFINITE_SITES);\n        } else {\n            CU_ASSERT_EQUAL_FATAL(ret, 0);\n            CU_ASSERT_EQUAL_FATAL(num_r2_values, num_sites - 1);\n            tsk_ld_calc_print_state(&ld_calc, _devnull);\n            for (j = 0; j < num_r2_values; j++) {\n                CU_ASSERT_EQUAL_FATAL(r2[j], r2_prime[j]);\n                ret = tsk_ld_calc_get_r2(&ld_calc, 0, j + 1, &x);\n                CU_ASSERT_EQUAL_FATAL(ret, 0);\n                CU_ASSERT_DOUBLE_EQUAL_FATAL(r2[j], x, eps);\n            }\n        }\n\n        /* Some checks in the reverse direction */\n        ret = tsk_ld_calc_get_r2_array(&ld_calc, num_sites - 1, TSK_DIR_REVERSE,\n            num_sites, DBL_MAX, r2, &num_r2_values);\n        if (multi_mutations_exist(ts, 0, num_sites)) {\n            CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_ONLY_INFINITE_SITES);\n        } else {\n            CU_ASSERT_EQUAL_FATAL(ret, 0);\n            CU_ASSERT_EQUAL_FATAL(num_r2_values, num_sites - 1);\n        }\n        tsk_ld_calc_print_state(&ld_calc, _devnull);\n\n        ret = tsk_ld_calc_get_r2_array(\n            &ld_calc, 1, TSK_DIR_REVERSE, num_sites, DBL_MAX, r2_prime, &num_r2_values);\n        if (multi_mutations_exist(ts, 0, 1)) {\n            CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_ONLY_INFINITE_SITES);\n        } else {\n            CU_ASSERT_EQUAL_FATAL(ret, 0);\n            CU_ASSERT_EQUAL_FATAL(num_r2_values, 1);\n        }\n        tsk_ld_calc_print_state(&ld_calc, _devnull);\n\n        ret = tsk_ld_calc_get_r2_array(&ld_calc, num_sites - 1, TSK_DIR_REVERSE,\n            num_sites, DBL_MAX, r2_prime, &num_r2_values);\n        if (multi_mutations_exist(ts, 0, num_sites)) {\n            CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_ONLY_INFINITE_SITES);\n        } else {\n            CU_ASSERT_EQUAL_FATAL(ret, 0);\n            CU_ASSERT_EQUAL_FATAL(num_r2_values, num_sites - 1);\n            tsk_ld_calc_print_state(&ld_calc, _devnull);\n\n            for (j = 0; j < num_r2_values; j++) {\n                CU_ASSERT_EQUAL_FATAL(r2[j], r2_prime[j]);\n                ret = tsk_ld_calc_get_r2(&ld_calc, num_sites - 1, num_sites - j - 2, &x);\n                CU_ASSERT_EQUAL_FATAL(ret, 0);\n                CU_ASSERT_DOUBLE_EQUAL_FATAL(r2[j], x, eps);\n            }\n        }\n\n        /* Check some error conditions */\n        ret = tsk_ld_calc_get_r2_array(\n            &ld_calc, 0, 0, num_sites, DBL_MAX, r2, &num_r2_values);\n        CU_ASSERT_EQUAL(ret, TSK_ERR_BAD_PARAM_VALUE);\n    }\n\n    if (num_sites > 3) {\n        /* Check for some basic distance calculations */\n        j = num_sites / 2;\n        x = sites[j + 1].position - sites[j].position;\n        ret = tsk_ld_calc_get_r2_array(\n            &ld_calc, j, TSK_DIR_FORWARD, num_sites, x, r2, &num_r2_values);\n        if (multi_mutations_exist(ts, j, num_sites)) {\n            CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_ONLY_INFINITE_SITES);\n        } else {\n            CU_ASSERT_EQUAL_FATAL(ret, 0);\n            CU_ASSERT_EQUAL_FATAL(num_r2_values, 1);\n        }\n\n        x = sites[j].position - sites[j - 1].position;\n        ret = tsk_ld_calc_get_r2_array(\n            &ld_calc, j, TSK_DIR_REVERSE, num_sites, x, r2, &num_r2_values);\n        if (multi_mutations_exist(ts, 0, j + 1)) {\n            CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_ONLY_INFINITE_SITES);\n        } else {\n            CU_ASSERT_EQUAL_FATAL(ret, 0);\n            CU_ASSERT_EQUAL_FATAL(num_r2_values, 1);\n        }\n    }\n\n    /* Check some error conditions */\n    for (j = num_sites; j < num_sites + 2; j++) {\n        ret = tsk_ld_calc_get_r2_array(\n            &ld_calc, j, TSK_DIR_FORWARD, num_sites, DBL_MAX, r2, &num_r2_values);\n        CU_ASSERT_EQUAL(ret, TSK_ERR_OUT_OF_BOUNDS);\n        ret = tsk_ld_calc_get_r2(&ld_calc, j, 0, r2);\n        CU_ASSERT_EQUAL(ret, TSK_ERR_OUT_OF_BOUNDS);\n        ret = tsk_ld_calc_get_r2(&ld_calc, 0, j, r2);\n        CU_ASSERT_EQUAL(ret, TSK_ERR_OUT_OF_BOUNDS);\n    }\n\n    tsk_ld_calc_free(&ld_calc);\n    free(r2);\n    free(r2_prime);\n    free(sites);\n    free(num_site_mutations);\n}\n\nstatic void\nverify_empty_tree_sequence(tsk_treeseq_t *ts, double sequence_length)\n{\n    CU_ASSERT_EQUAL(tsk_treeseq_get_num_edges(ts), 0);\n    CU_ASSERT_EQUAL(tsk_treeseq_get_num_mutations(ts), 0);\n    CU_ASSERT_EQUAL(tsk_treeseq_get_num_mutations(ts), 0);\n    CU_ASSERT_EQUAL(tsk_treeseq_get_num_migrations(ts), 0);\n    CU_ASSERT_EQUAL(tsk_treeseq_get_num_samples(ts), 0);\n    CU_ASSERT_EQUAL(tsk_treeseq_get_sequence_length(ts), sequence_length);\n    CU_ASSERT_EQUAL(tsk_treeseq_get_num_trees(ts), 1);\n    verify_trees_consistent(ts);\n    verify_ld(ts);\n    verify_stats(ts);\n    verify_vargen(ts);\n    verify_vcf_converter(ts, 1);\n}\n\nstatic void\nverify_sample_sets_for_tree(tsk_tree_t *tree)\n{\n    int ret, stack_top, j;\n    tsk_id_t u, v, n, num_nodes, num_samples;\n    size_t tmp;\n    tsk_id_t *stack, *samples;\n    tsk_treeseq_t *ts = tree->tree_sequence;\n    tsk_id_t *sample_index_map = ts->sample_index_map;\n    const tsk_id_t *list_left = tree->left_sample;\n    const tsk_id_t *list_right = tree->right_sample;\n    const tsk_id_t *list_next = tree->next_sample;\n    tsk_id_t stop, sample_index;\n\n    n = tsk_treeseq_get_num_samples(ts);\n    num_nodes = tsk_treeseq_get_num_nodes(ts);\n    stack = malloc(n * sizeof(tsk_id_t));\n    samples = malloc(n * sizeof(tsk_id_t));\n    CU_ASSERT_FATAL(stack != NULL);\n    CU_ASSERT_FATAL(samples != NULL);\n    for (u = 0; u < num_nodes; u++) {\n        if (tree->left_child[u] == TSK_NULL && !tsk_treeseq_is_sample(ts, u)) {\n            CU_ASSERT_EQUAL(list_left[u], TSK_NULL);\n            CU_ASSERT_EQUAL(list_right[u], TSK_NULL);\n        } else {\n            stack_top = 0;\n            num_samples = 0;\n            stack[stack_top] = u;\n            while (stack_top >= 0) {\n                v = stack[stack_top];\n                stack_top--;\n                if (tsk_treeseq_is_sample(ts, v)) {\n                    samples[num_samples] = v;\n                    num_samples++;\n                }\n                for (v = tree->right_child[v]; v != TSK_NULL; v = tree->left_sib[v]) {\n                    stack_top++;\n                    stack[stack_top] = v;\n                }\n            }\n            ret = tsk_tree_get_num_samples(tree, u, &tmp);\n            CU_ASSERT_EQUAL(ret, 0);\n            CU_ASSERT_EQUAL_FATAL(num_samples, tmp);\n\n            j = 0;\n            sample_index = list_left[u];\n            if (sample_index != TSK_NULL) {\n                stop = list_right[u];\n                while (true) {\n                    CU_ASSERT_TRUE_FATAL(j < n);\n                    CU_ASSERT_EQUAL_FATAL(sample_index, sample_index_map[samples[j]]);\n                    j++;\n                    if (sample_index == stop) {\n                        break;\n                    }\n                    sample_index = list_next[sample_index];\n                }\n            }\n            CU_ASSERT_EQUAL_FATAL(j, num_samples);\n        }\n    }\n    free(stack);\n    free(samples);\n}\n\nstatic void\nverify_sample_sets(tsk_treeseq_t *ts)\n{\n    int ret;\n    tsk_tree_t t;\n\n    ret = tsk_tree_init(&t, ts, TSK_SAMPLE_COUNTS | TSK_SAMPLE_LISTS);\n    CU_ASSERT_EQUAL(ret, 0);\n\n    for (ret = tsk_tree_first(&t); ret == 1; ret = tsk_tree_next(&t)) {\n        verify_sample_sets_for_tree(&t);\n    }\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n    for (ret = tsk_tree_last(&t); ret == 1; ret = tsk_tree_prev(&t)) {\n        verify_sample_sets_for_tree(&t);\n    }\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n\n    tsk_tree_free(&t);\n}\n\nstatic void\nverify_tree_equals(tsk_treeseq_t *ts)\n{\n    int ret;\n    tsk_tree_t *trees, t;\n    size_t j, k;\n    tsk_treeseq_t *other_ts\n        = get_example_tree_sequence(10, 0, 100, 100.0, 1.0, 1.0, 0, NULL, 0);\n    int flags[] = { 0, TSK_SAMPLE_LISTS, TSK_SAMPLE_COUNTS,\n        TSK_SAMPLE_LISTS | TSK_SAMPLE_COUNTS };\n\n    trees = get_tree_list(ts);\n    ret = tsk_tree_init(&t, other_ts, 0);\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n    for (j = 0; j < tsk_treeseq_get_num_trees(ts); j++) {\n        ret = tsk_tree_equal(&t, &trees[j]);\n        CU_ASSERT_EQUAL(ret, TSK_ERR_BAD_PARAM_VALUE);\n        for (k = 0; k < tsk_treeseq_get_num_trees(ts); k++) {\n            ret = tsk_tree_equal(&trees[j], &trees[k]);\n            if (j == k) {\n                CU_ASSERT_EQUAL_FATAL(ret, 0);\n            } else {\n                CU_ASSERT_EQUAL_FATAL(ret, 1);\n            }\n        }\n    }\n    ret = tsk_tree_free(&t);\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n\n    for (j = 0; j < sizeof(flags) / sizeof(int); j++) {\n        ret = tsk_tree_init(&t, ts, flags[j]);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        for (ret = tsk_tree_first(&t); ret == 1; ret = tsk_tree_next(&t)) {\n            for (k = 0; k < tsk_treeseq_get_num_trees(ts); k++) {\n                ret = tsk_tree_equal(&t, &trees[k]);\n                if (t.index == k) {\n                    CU_ASSERT_EQUAL_FATAL(ret, 0);\n                } else {\n                    CU_ASSERT_EQUAL_FATAL(ret, 1);\n                }\n            }\n        }\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        ret = tsk_tree_free(&t);\n        CU_ASSERT_EQUAL(ret, 0);\n    }\n    for (j = 0; j < tsk_treeseq_get_num_trees(ts); j++) {\n        ret = tsk_tree_free(&trees[j]);\n    }\n    free(trees);\n    tsk_treeseq_free(other_ts);\n    free(other_ts);\n}\n\nstatic void\ntest_individual_nodes_from_examples(void)\n{\n    tsk_treeseq_t **examples = get_example_tree_sequences(1);\n    uint32_t j;\n\n    CU_ASSERT_FATAL(examples != NULL);\n    for (j = 0; examples[j] != NULL; j++) {\n        verify_individual_nodes(examples[j]);\n        add_individuals(examples[j]);\n        verify_individual_nodes(examples[j]);\n        tsk_treeseq_free(examples[j]);\n        free(examples[j]);\n    }\n    free(examples);\n}\n\nstatic void\ntest_diff_iter_from_examples(void)\n{\n    /* tsk_treeseq_t **examples = get_example_tree_sequences(1); */\n    /* uint32_t j; */\n\n    /* CU_ASSERT_FATAL(examples != NULL); */\n    /* for (j = 0; examples[j] != NULL; j++) { */\n    /*     verify_tree_diffs(examples[j]); */\n    /*     tsk_treeseq_free(examples[j]); */\n    /*     free(examples[j]); */\n    /* } */\n    /* free(examples); */\n}\n\nstatic void\ntest_tree_iter_from_examples(void)\n{\n\n    tsk_treeseq_t **examples = get_example_tree_sequences(1);\n    uint32_t j;\n\n    CU_ASSERT_FATAL(examples != NULL);\n    for (j = 0; examples[j] != NULL; j++) {\n        verify_trees_consistent(examples[j]);\n        tsk_treeseq_free(examples[j]);\n        free(examples[j]);\n    }\n    free(examples);\n}\n\nstatic void\ntest_sample_sets_from_examples(void)\n{\n    tsk_treeseq_t **examples = get_example_tree_sequences(1);\n    uint32_t j;\n\n    CU_ASSERT_FATAL(examples != NULL);\n    for (j = 0; examples[j] != NULL; j++) {\n        verify_sample_sets(examples[j]);\n        tsk_treeseq_free(examples[j]);\n        free(examples[j]);\n    }\n    free(examples);\n}\n\nstatic void\ntest_tree_equals_from_examples(void)\n{\n    tsk_treeseq_t **examples = get_example_tree_sequences(1);\n    uint32_t j;\n\n    CU_ASSERT_FATAL(examples != NULL);\n    for (j = 0; examples[j] != NULL; j++) {\n        verify_tree_equals(examples[j]);\n        tsk_treeseq_free(examples[j]);\n        free(examples[j]);\n    }\n    free(examples);\n}\n\nstatic void\ntest_next_prev_from_examples(void)\n{\n\n    tsk_treeseq_t **examples = get_example_tree_sequences(1);\n    uint32_t j;\n\n    CU_ASSERT_FATAL(examples != NULL);\n    for (j = 0; examples[j] != NULL; j++) {\n        verify_tree_next_prev(examples[j]);\n        tsk_treeseq_free(examples[j]);\n        free(examples[j]);\n    }\n    free(examples);\n}\n\nstatic void\ntest_ld_from_examples(void)\n{\n    tsk_treeseq_t **examples = get_example_tree_sequences(1);\n    uint32_t j;\n\n    CU_ASSERT_FATAL(examples != NULL);\n    for (j = 0; examples[j] != NULL; j++) {\n        verify_ld(examples[j]);\n        tsk_treeseq_free(examples[j]);\n        free(examples[j]);\n    }\n    free(examples);\n}\n\nstatic void\ntest_tsk_vargen_from_examples(void)\n{\n    tsk_treeseq_t **examples = get_example_tree_sequences(1);\n    uint32_t j;\n\n    CU_ASSERT_FATAL(examples != NULL);\n    for (j = 0; examples[j] != NULL; j++) {\n        verify_vargen(examples[j]);\n        tsk_treeseq_free(examples[j]);\n        free(examples[j]);\n    }\n    free(examples);\n}\n\nstatic void\ntest_stats_from_examples(void)\n{\n    tsk_treeseq_t **examples = get_example_tree_sequences(1);\n    uint32_t j;\n\n    CU_ASSERT_FATAL(examples != NULL);\n    for (j = 0; examples[j] != NULL; j++) {\n        verify_stats(examples[j]);\n        tsk_treeseq_free(examples[j]);\n        free(examples[j]);\n    }\n    free(examples);\n}\n\nstatic void\ntest_genealogical_nearest_neighbours_from_examples(void)\n{\n    tsk_treeseq_t **examples = get_example_tree_sequences(1);\n    uint32_t j;\n\n    CU_ASSERT_FATAL(examples != NULL);\n    for (j = 0; examples[j] != NULL; j++) {\n        verify_genealogical_nearest_neighbours(examples[j]);\n        tsk_treeseq_free(examples[j]);\n        free(examples[j]);\n    }\n    free(examples);\n}\n\nstatic void\ntest_mean_descendants_from_examples(void)\n{\n    tsk_treeseq_t **examples = get_example_tree_sequences(1);\n    uint32_t j;\n\n    CU_ASSERT_FATAL(examples != NULL);\n    for (j = 0; examples[j] != NULL; j++) {\n        verify_mean_descendants(examples[j]);\n        tsk_treeseq_free(examples[j]);\n        free(examples[j]);\n    }\n    free(examples);\n}\n\nstatic void\ntest_compute_mutation_parents_from_examples(void)\n{\n    tsk_treeseq_t **examples = get_example_tree_sequences(1);\n    uint32_t j;\n\n    CU_ASSERT_FATAL(examples != NULL);\n    for (j = 0; examples[j] != NULL; j++) {\n        verify_compute_mutation_parents(examples[j]);\n        tsk_treeseq_free(examples[j]);\n        free(examples[j]);\n    }\n    free(examples);\n}\n\nstatic void\nverify_simplify_errors(tsk_treeseq_t *ts)\n{\n    int ret;\n    tsk_id_t *s;\n    tsk_id_t u;\n    tsk_treeseq_t subset;\n    tsk_id_t sample[2];\n\n    ret = tsk_treeseq_get_samples(ts, &s);\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n    memcpy(sample, s, 2 * sizeof(tsk_id_t));\n\n    for (u = 0; u < (tsk_id_t) tsk_treeseq_get_num_nodes(ts); u++) {\n        if (!tsk_treeseq_is_sample(ts, u)) {\n            sample[1] = u;\n            ret = tsk_treeseq_simplify(ts, sample, 2, 0, &subset, NULL);\n            CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_BAD_SAMPLES);\n        }\n    }\n    sample[0] = -1;\n    ret = tsk_treeseq_simplify(ts, sample, 2, 0, &subset, NULL);\n    CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_NODE_OUT_OF_BOUNDS);\n    sample[0] = s[0];\n    sample[1] = s[0];\n    ret = tsk_treeseq_simplify(ts, sample, 2, 0, &subset, NULL);\n    CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_DUPLICATE_SAMPLE);\n}\n\nstatic void\ntest_simplify_from_examples(void)\n{\n    tsk_treeseq_t **examples = get_example_tree_sequences(1);\n    uint32_t j;\n\n    CU_ASSERT_FATAL(examples != NULL);\n    for (j = 0; examples[j] != NULL; j++) {\n        verify_simplify(examples[j]);\n        if (tsk_treeseq_get_num_migrations(examples[j]) == 0) {\n            /* Migrations are not supported at the moment, so skip these tests\n             * rather than complicate them */\n            verify_simplify_errors(examples[j]);\n        }\n        tsk_treeseq_free(examples[j]);\n        free(examples[j]);\n    }\n    free(examples);\n}\n\nstatic void\ntest_reduce_topology_from_examples(void)\n{\n    tsk_treeseq_t **examples = get_example_tree_sequences(1);\n    uint32_t j;\n\n    CU_ASSERT_FATAL(examples != NULL);\n    for (j = 0; examples[j] != NULL; j++) {\n        verify_reduce_topology(examples[j]);\n        tsk_treeseq_free(examples[j]);\n        free(examples[j]);\n    }\n    free(examples);\n}\n\nstatic void\nverify_newick(tsk_treeseq_t *ts)\n{\n    /* int ret, err; */\n    /* tsk_tree_t t; */\n    /* tsk_id_t root; */\n    /* size_t precision = 4; */\n    /* size_t buffer_size = 1024 * 1024; */\n    /* char *newick = malloc(buffer_size); */\n    /* size_t j, size; */\n\n    /* CU_ASSERT_FATAL(newick != NULL); */\n\n    /* ret = tsk_tree_init(&t, ts, 0); */\n    /* CU_ASSERT_EQUAL_FATAL(ret, 0); */\n    /* ret = tsk_tree_first(&t); */\n    /* CU_ASSERT_FATAL(ret == 1); */\n    /* for (root = t.left_root; root != TSK_NULL; root = t.right_sib[root]) { */\n    /*     err = tsk_tree_get_newick(&t, root, precision, 0, buffer_size, newick); */\n    /*     CU_ASSERT_EQUAL_FATAL(err, 0); */\n    /*     size = strlen(newick); */\n    /*     CU_ASSERT_TRUE(size > 0); */\n    /*     CU_ASSERT_TRUE(size < buffer_size); */\n    /*     for (j = 0; j <= size; j++) { */\n    /*         err = tsk_tree_get_newick(&t, root, precision, 0, j, newick); */\n    /*         CU_ASSERT_EQUAL_FATAL(err, TSK_ERR_BUFFER_OVERFLOW); */\n    /*     } */\n    /*     err = tsk_tree_get_newick(&t, root, precision, 0, size + 1, newick); */\n    /*     CU_ASSERT_EQUAL_FATAL(err, 0); */\n    /* } */\n\n    /* for (ret = tsk_tree_first(&t); ret == 1; ret = tsk_tree_next(&t)) { */\n    /*     for (root = t.left_root; root != TSK_NULL; root = t.right_sib[root]) { */\n    /*         err = tsk_tree_get_newick(&t, root, precision, 0, 0, NULL); */\n    /*         CU_ASSERT_EQUAL_FATAL(err, TSK_ERR_BAD_PARAM_VALUE); */\n    /*         err = tsk_tree_get_newick(&t, root, precision, 0, buffer_size, newick); */\n    /*         CU_ASSERT_EQUAL_FATAL(err, 0); */\n    /*         size = strlen(newick); */\n    /*         CU_ASSERT_EQUAL(newick[size - 1], ';'); */\n    /*     } */\n    /* } */\n    /* CU_ASSERT_EQUAL_FATAL(ret, 0); */\n\n    /* tsk_tree_free(&t); */\n    /* free(newick); */\n}\n\nstatic void\ntest_newick_from_examples(void)\n{\n    tsk_treeseq_t **examples = get_example_tree_sequences(1);\n    uint32_t j;\n\n    CU_ASSERT_FATAL(examples != NULL);\n    for (j = 0; examples[j] != NULL; j++) {\n        verify_newick(examples[j]);\n        tsk_treeseq_free(examples[j]);\n        free(examples[j]);\n    }\n    free(examples);\n}\n\nstatic void\nverify_tree_sequences_equal(tsk_treeseq_t *ts1, tsk_treeseq_t *ts2,\n    bool check_migrations, bool check_mutations, bool check_provenance)\n{\n    int ret, err1, err2;\n    size_t j;\n    tsk_edge_t r1, r2;\n    tsk_node_t n1, n2;\n    tsk_migration_t m1, m2;\n    tsk_provenance_t p1, p2;\n    tsk_individual_t i1, i2;\n    tsk_population_t pop1, pop2;\n    size_t num_mutations = tsk_treeseq_get_num_mutations(ts1);\n    tsk_site_t site_1, site_2;\n    tsk_mutation_t mutation_1, mutation_2;\n    tsk_tree_t t1, t2;\n\n    /* tsk_treeseq_print_state(ts1, stdout); */\n    /* tsk_treeseq_print_state(ts2, stdout); */\n\n    CU_ASSERT_EQUAL(tsk_treeseq_get_num_samples(ts1), tsk_treeseq_get_num_samples(ts2));\n    CU_ASSERT_EQUAL(\n        tsk_treeseq_get_sequence_length(ts1), tsk_treeseq_get_sequence_length(ts2));\n    CU_ASSERT_EQUAL(tsk_treeseq_get_num_edges(ts1), tsk_treeseq_get_num_edges(ts2));\n    CU_ASSERT_EQUAL(tsk_treeseq_get_num_nodes(ts1), tsk_treeseq_get_num_nodes(ts2));\n    CU_ASSERT_EQUAL(tsk_treeseq_get_num_trees(ts1), tsk_treeseq_get_num_trees(ts2));\n\n    for (j = 0; j < tsk_treeseq_get_num_nodes(ts1); j++) {\n        ret = tsk_treeseq_get_node(ts1, j, &n1);\n        CU_ASSERT_EQUAL(ret, 0);\n        ret = tsk_treeseq_get_node(ts2, j, &n2);\n        CU_ASSERT_EQUAL(ret, 0);\n        verify_nodes_equal(&n1, &n2);\n    }\n    for (j = 0; j < tsk_treeseq_get_num_edges(ts1); j++) {\n        ret = tsk_treeseq_get_edge(ts1, j, &r1);\n        CU_ASSERT_EQUAL(ret, 0);\n        ret = tsk_treeseq_get_edge(ts2, j, &r2);\n        CU_ASSERT_EQUAL(ret, 0);\n        verify_edges_equal(&r1, &r2, 1.0);\n    }\n    if (check_mutations) {\n        CU_ASSERT_EQUAL_FATAL(\n            tsk_treeseq_get_num_sites(ts1), tsk_treeseq_get_num_sites(ts2));\n        for (j = 0; j < tsk_treeseq_get_num_sites(ts1); j++) {\n            ret = tsk_treeseq_get_site(ts1, j, &site_1);\n            CU_ASSERT_EQUAL(ret, 0);\n            ret = tsk_treeseq_get_site(ts2, j, &site_2);\n            CU_ASSERT_EQUAL(ret, 0);\n            CU_ASSERT_EQUAL(site_1.position, site_2.position);\n            CU_ASSERT_EQUAL(\n                site_1.ancestral_state_length, site_2.ancestral_state_length);\n            CU_ASSERT_NSTRING_EQUAL(site_1.ancestral_state, site_2.ancestral_state,\n                site_1.ancestral_state_length);\n            CU_ASSERT_EQUAL(site_1.metadata_length, site_2.metadata_length);\n            CU_ASSERT_NSTRING_EQUAL(\n                site_1.metadata, site_2.metadata, site_1.metadata_length);\n        }\n        CU_ASSERT_EQUAL_FATAL(\n            tsk_treeseq_get_num_mutations(ts1), tsk_treeseq_get_num_mutations(ts2));\n        for (j = 0; j < num_mutations; j++) {\n            ret = tsk_treeseq_get_mutation(ts1, j, &mutation_1);\n            CU_ASSERT_EQUAL(ret, 0);\n            ret = tsk_treeseq_get_mutation(ts2, j, &mutation_2);\n            CU_ASSERT_EQUAL(ret, 0);\n            CU_ASSERT_EQUAL(mutation_1.id, j);\n            CU_ASSERT_EQUAL(mutation_1.id, mutation_2.id);\n            CU_ASSERT_EQUAL(mutation_1.site, mutation_2.site);\n            CU_ASSERT_EQUAL(mutation_1.node, mutation_2.node);\n            CU_ASSERT_EQUAL_FATAL(mutation_1.parent, mutation_2.parent);\n            CU_ASSERT_EQUAL_FATAL(\n                mutation_1.derived_state_length, mutation_2.derived_state_length);\n            CU_ASSERT_NSTRING_EQUAL(mutation_1.derived_state, mutation_2.derived_state,\n                mutation_1.derived_state_length);\n            CU_ASSERT_EQUAL_FATAL(\n                mutation_1.metadata_length, mutation_2.metadata_length);\n            CU_ASSERT_NSTRING_EQUAL(\n                mutation_1.metadata, mutation_2.metadata, mutation_1.metadata_length);\n        }\n    }\n    if (check_migrations) {\n        CU_ASSERT_EQUAL_FATAL(\n            tsk_treeseq_get_num_migrations(ts1), tsk_treeseq_get_num_migrations(ts2));\n        for (j = 0; j < tsk_treeseq_get_num_migrations(ts1); j++) {\n            ret = tsk_treeseq_get_migration(ts1, j, &m1);\n            CU_ASSERT_EQUAL(ret, 0);\n            ret = tsk_treeseq_get_migration(ts2, j, &m2);\n            CU_ASSERT_EQUAL(ret, 0);\n            verify_migrations_equal(&m1, &m2, 1.0);\n        }\n    }\n    if (check_provenance) {\n        CU_ASSERT_EQUAL_FATAL(\n            tsk_treeseq_get_num_provenances(ts1), tsk_treeseq_get_num_provenances(ts2));\n        for (j = 0; j < tsk_treeseq_get_num_provenances(ts1); j++) {\n            ret = tsk_treeseq_get_provenance(ts1, j, &p1);\n            CU_ASSERT_EQUAL(ret, 0);\n            ret = tsk_treeseq_get_provenance(ts2, j, &p2);\n            CU_ASSERT_EQUAL(ret, 0);\n            verify_provenances_equal(&p1, &p2);\n        }\n    }\n\n    CU_ASSERT_EQUAL_FATAL(\n        tsk_treeseq_get_num_individuals(ts1), tsk_treeseq_get_num_individuals(ts2));\n    for (j = 0; j < tsk_treeseq_get_num_individuals(ts1); j++) {\n        ret = tsk_treeseq_get_individual(ts1, j, &i1);\n        CU_ASSERT_EQUAL(ret, 0);\n        ret = tsk_treeseq_get_individual(ts2, j, &i2);\n        CU_ASSERT_EQUAL(ret, 0);\n        verify_individuals_equal(&i1, &i2);\n    }\n\n    CU_ASSERT_EQUAL_FATAL(\n        tsk_treeseq_get_num_populations(ts1), tsk_treeseq_get_num_populations(ts2));\n    for (j = 0; j < tsk_treeseq_get_num_populations(ts1); j++) {\n        ret = tsk_treeseq_get_population(ts1, j, &pop1);\n        CU_ASSERT_EQUAL(ret, 0);\n        ret = tsk_treeseq_get_population(ts2, j, &pop2);\n        CU_ASSERT_EQUAL(ret, 0);\n        verify_populations_equal(&pop1, &pop2);\n    }\n\n    ret = tsk_tree_init(&t1, ts1, 0);\n    CU_ASSERT_EQUAL(ret, 0);\n    ret = tsk_tree_init(&t2, ts2, 0);\n    CU_ASSERT_EQUAL(ret, 0);\n    ret = tsk_tree_first(&t1);\n    CU_ASSERT_EQUAL(ret, 1);\n    ret = tsk_tree_first(&t2);\n    CU_ASSERT_EQUAL(ret, 1);\n    while (1) {\n        err1 = tsk_tree_next(&t1);\n        err2 = tsk_tree_next(&t2);\n        CU_ASSERT_EQUAL_FATAL(err1, err2);\n        if (err1 != 1) {\n            break;\n        }\n    }\n    tsk_tree_free(&t1);\n    tsk_tree_free(&t2);\n}\n\nstatic void\ntest_save_empty_kas(void)\n{\n    int ret;\n    tsk_treeseq_t ts1, ts2;\n    double sequence_length = 1234.00;\n    tsk_tbl_collection_t tables;\n\n    ret = tsk_tbl_collection_init(&tables, 0);\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n    tables.sequence_length = sequence_length;\n\n    ret = tsk_treeseq_init(&ts1, &tables, TSK_BUILD_INDEXES);\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n\n    ret = tsk_treeseq_dump(&ts1, _tmp_file_name, 0);\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n    verify_empty_tree_sequence(&ts1, sequence_length);\n    ret = tsk_treeseq_load(&ts2, _tmp_file_name, 0);\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n    verify_empty_tree_sequence(&ts2, sequence_length);\n\n    tsk_treeseq_free(&ts1);\n    tsk_treeseq_free(&ts2);\n    tsk_tbl_collection_free(&tables);\n}\n\nstatic void\ntest_save_kas(void)\n{\n    int ret;\n    size_t j, k;\n    tsk_treeseq_t **examples = get_example_tree_sequences(1);\n    tsk_treeseq_t ts2;\n    tsk_treeseq_t *ts1;\n    char *file_uuid;\n    int dump_flags[] = { 0 };\n\n    CU_ASSERT_FATAL(examples != NULL);\n\n    for (j = 0; examples[j] != NULL; j++) {\n        ts1 = examples[j];\n        file_uuid = tsk_treeseq_get_file_uuid(ts1);\n        CU_ASSERT_EQUAL_FATAL(file_uuid, NULL);\n        for (k = 0; k < sizeof(dump_flags) / sizeof(int); k++) {\n            ret = tsk_treeseq_dump(ts1, _tmp_file_name, dump_flags[k]);\n            CU_ASSERT_EQUAL_FATAL(ret, 0);\n            ret = tsk_treeseq_load(&ts2, _tmp_file_name, TSK_LOAD_EXTENDED_CHECKS);\n            CU_ASSERT_EQUAL_FATAL(ret, 0);\n            verify_tree_sequences_equal(ts1, &ts2, true, true, true);\n            tsk_treeseq_print_state(&ts2, _devnull);\n            verify_vargen(&ts2);\n            file_uuid = tsk_treeseq_get_file_uuid(&ts2);\n            CU_ASSERT_NOT_EQUAL_FATAL(file_uuid, NULL);\n            CU_ASSERT_EQUAL(strlen(file_uuid), TSK_UUID_SIZE);\n            tsk_treeseq_free(&ts2);\n        }\n        tsk_treeseq_free(ts1);\n        free(ts1);\n    }\n    free(examples);\n}\n\nstatic void\ntest_save_kas_tables(void)\n{\n    int ret;\n    size_t j, k;\n    tsk_treeseq_t **examples = get_example_tree_sequences(1);\n    tsk_treeseq_t *ts1;\n    tsk_tbl_collection_t t1, t2;\n    int dump_flags[] = { 0 };\n\n    CU_ASSERT_FATAL(examples != NULL);\n\n    for (j = 0; examples[j] != NULL; j++) {\n        ts1 = examples[j];\n        ret = tsk_tbl_collection_init(&t1, 0);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        ret = tsk_treeseq_copy_tables(ts1, &t1);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        CU_ASSERT_EQUAL_FATAL(t1.file_uuid, NULL);\n        for (k = 0; k < sizeof(dump_flags) / sizeof(int); k++) {\n            ret = tsk_tbl_collection_dump(&t1, _tmp_file_name, dump_flags[k]);\n            CU_ASSERT_EQUAL_FATAL(ret, 0);\n            ret = tsk_tbl_collection_init(&t2, 0);\n            CU_ASSERT_EQUAL_FATAL(ret, 0);\n            ret = tsk_tbl_collection_load(&t2, _tmp_file_name, 0);\n            CU_ASSERT_EQUAL_FATAL(ret, 0);\n            CU_ASSERT_TRUE(tsk_tbl_collection_equals(&t1, &t2));\n            CU_ASSERT_EQUAL_FATAL(t1.file_uuid, NULL);\n            CU_ASSERT_NOT_EQUAL_FATAL(t2.file_uuid, NULL);\n            CU_ASSERT_EQUAL(strlen(t2.file_uuid), TSK_UUID_SIZE);\n            tsk_tbl_collection_free(&t2);\n        }\n        tsk_tbl_collection_free(&t1);\n        tsk_treeseq_free(ts1);\n        free(ts1);\n    }\n    free(examples);\n}\n\nstatic void\ntest_sort_tables(void)\n{\n    int ret;\n    tsk_treeseq_t **examples = get_example_tree_sequences(1);\n    tsk_treeseq_t ts2;\n    tsk_treeseq_t *ts1;\n    size_t j, k, start, starts[3];\n    tsk_tbl_collection_t tables;\n    int load_flags = TSK_BUILD_INDEXES;\n    tsk_id_t tmp_node;\n\n    ret = tsk_tbl_collection_init(&tables, 0);\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n    CU_ASSERT_FATAL(examples != NULL);\n\n    for (j = 0; examples[j] != NULL; j++) {\n        ts1 = examples[j];\n\n        ret = tsk_treeseq_copy_tables(ts1, &tables);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n\n        /* Check the input validation */\n        ret = tsk_tbl_collection_sort(NULL, 0, 0);\n        CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_BAD_PARAM_VALUE);\n        /* Check edge sorting */\n        if (tables.edges->num_rows == 2) {\n            starts[0] = 0;\n            starts[1] = 0;\n            starts[2] = 0;\n        } else {\n            starts[0] = 0;\n            starts[1] = tables.edges->num_rows / 2;\n            starts[2] = tables.edges->num_rows - 2;\n        }\n        for (k = 0; k < 3; k++) {\n            start = starts[k];\n            unsort_edges(tables.edges, start);\n            ret = tsk_treeseq_init(&ts2, &tables, load_flags);\n            CU_ASSERT_NOT_EQUAL_FATAL(ret, 0);\n            tsk_treeseq_free(&ts2);\n\n            ret = tsk_tbl_collection_sort(&tables, 0, 0);\n            CU_ASSERT_EQUAL_FATAL(ret, 0);\n\n            ret = tsk_treeseq_init(&ts2, &tables, load_flags);\n            CU_ASSERT_EQUAL_FATAL(ret, 0);\n            verify_tree_sequences_equal(ts1, &ts2, true, true, false);\n            tsk_treeseq_free(&ts2);\n        }\n\n        /* A start value of num_tables.edges should have no effect */\n        ret = tsk_tbl_collection_sort(&tables, tables.edges->num_rows, 0);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        ret = tsk_treeseq_init(&ts2, &tables, load_flags);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        verify_tree_sequences_equal(ts1, &ts2, true, true, false);\n        tsk_treeseq_free(&ts2);\n\n        if (tables.sites->num_rows > 1) {\n            /* Check site sorting */\n            unsort_sites(tables.sites, tables.mutations);\n            ret = tsk_treeseq_init(&ts2, &tables, load_flags);\n            CU_ASSERT_NOT_EQUAL(ret, 0);\n            tsk_treeseq_free(&ts2);\n\n            ret = tsk_tbl_collection_sort(&tables, 0, 0);\n            CU_ASSERT_EQUAL_FATAL(ret, 0);\n\n            ret = tsk_treeseq_init(&ts2, &tables, load_flags);\n            CU_ASSERT_EQUAL_FATAL(ret, 0);\n            verify_tree_sequences_equal(ts1, &ts2, true, true, false);\n            tsk_treeseq_free(&ts2);\n\n            /* Check for site bounds error */\n            tables.mutations->site[0] = tables.sites->num_rows;\n            ret = tsk_tbl_collection_sort(&tables, 0, 0);\n            CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_SITE_OUT_OF_BOUNDS);\n            tables.mutations->site[0] = 0;\n            ret = tsk_tbl_collection_sort(&tables, 0, 0);\n            CU_ASSERT_EQUAL_FATAL(ret, 0);\n\n            /* Check for edge node bounds error */\n            tmp_node = tables.edges->parent[0];\n            tables.edges->parent[0] = tables.nodes->num_rows;\n            ret = tsk_tbl_collection_sort(&tables, 0, 0);\n            CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_NODE_OUT_OF_BOUNDS);\n            tables.edges->parent[0] = tmp_node;\n            ret = tsk_tbl_collection_sort(&tables, 0, 0);\n            CU_ASSERT_EQUAL_FATAL(ret, 0);\n\n            /* Check for mutation node bounds error */\n            tmp_node = tables.mutations->node[0];\n            tables.mutations->node[0] = tables.nodes->num_rows;\n            ret = tsk_tbl_collection_sort(&tables, 0, 0);\n            CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_NODE_OUT_OF_BOUNDS);\n            tables.mutations->node[0] = tmp_node;\n\n            /* Check for mutation parent bounds error */\n            tables.mutations->parent[0] = tables.mutations->num_rows;\n            ret = tsk_tbl_collection_sort(&tables, 0, 0);\n            CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_MUTATION_OUT_OF_BOUNDS);\n            tables.mutations->parent[0] = TSK_NULL;\n            ret = tsk_tbl_collection_sort(&tables, 0, 0);\n            CU_ASSERT_EQUAL_FATAL(ret, 0);\n        }\n        tsk_treeseq_free(ts1);\n        free(ts1);\n    }\n    free(examples);\n    tsk_tbl_collection_free(&tables);\n}\nstatic void\ntest_dump_tables(void)\n{\n    int ret;\n    tsk_treeseq_t **examples = get_example_tree_sequences(1);\n    tsk_treeseq_t ts2;\n    tsk_treeseq_t *ts1;\n    tsk_tbl_collection_t tables;\n    size_t j;\n    int load_flags = TSK_BUILD_INDEXES;\n\n    ret = tsk_tbl_collection_init(&tables, 0);\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n    CU_ASSERT_FATAL(examples != NULL);\n\n    for (j = 0; examples[j] != NULL; j++) {\n        ts1 = examples[j];\n\n        ret = tsk_treeseq_copy_tables(ts1, NULL);\n        CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_BAD_PARAM_VALUE);\n\n        ret = tsk_treeseq_copy_tables(ts1, &tables);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        ret = tsk_treeseq_init(&ts2, &tables, load_flags);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        verify_tree_sequences_equal(ts1, &ts2, true, true, true);\n        tsk_treeseq_print_state(&ts2, _devnull);\n        tsk_treeseq_free(&ts2);\n        tsk_treeseq_free(ts1);\n        free(ts1);\n    }\n\n    free(examples);\n    tsk_tbl_collection_free(&tables);\n}\n\nstatic void\ntest_dump_tables_kas(void)\n{\n    int ret;\n    size_t k;\n    tsk_treeseq_t *ts1, ts2, ts3, **examples;\n    tsk_tbl_collection_t tables;\n    int load_flags = TSK_BUILD_INDEXES;\n\n    ret = tsk_tbl_collection_init(&tables, 0);\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n\n    examples = get_example_tree_sequences(1);\n    for (k = 0; examples[k] != NULL; k++) {\n        ts1 = examples[k];\n        CU_ASSERT_FATAL(ts1 != NULL);\n        ret = tsk_treeseq_copy_tables(ts1, &tables);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        ret = tsk_treeseq_init(&ts2, &tables, load_flags);\n        ret = tsk_treeseq_dump(&ts2, _tmp_file_name, 0);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        ret = tsk_treeseq_load(&ts3, _tmp_file_name, TSK_LOAD_EXTENDED_CHECKS);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        verify_tree_sequences_equal(ts1, &ts3, true, true, true);\n        tsk_treeseq_print_state(&ts2, _devnull);\n\n        tsk_treeseq_free(&ts2);\n        tsk_treeseq_free(&ts3);\n        tsk_treeseq_free(ts1);\n        free(ts1);\n    }\n    free(examples);\n    tsk_tbl_collection_free(&tables);\n}\n\nvoid\ntest_tsk_tbl_collection_simplify_errors(void)\n{\n    int ret;\n    tsk_tbl_collection_t tables;\n    tsk_id_t samples[] = { 0, 1 };\n\n    ret = tsk_tbl_collection_init(&tables, 0);\n    CU_ASSERT_EQUAL_FATAL(ret, 0);\n    tables.sequence_length = 1;\n\n    ret = tsk_site_tbl_add_row(tables.sites, 0, \"A\", 1, NULL, 0);\n    CU_ASSERT_FATAL(ret >= 0);\n    ret = tsk_site_tbl_add_row(tables.sites, 0, \"A\", 1, NULL, 0);\n    CU_ASSERT_FATAL(ret >= 0);\n    ret = tsk_tbl_collection_simplify(&tables, samples, 0, 0, NULL);\n    CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_DUPLICATE_SITE_POSITION);\n\n    /* Out of order positions */\n    tables.sites->position[0] = 0.5;\n    ret = tsk_tbl_collection_simplify(&tables, samples, 0, 0, NULL);\n    CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_UNSORTED_SITES);\n\n    /* Position out of bounds */\n    tables.sites->position[0] = 1.5;\n    ret = tsk_tbl_collection_simplify(&tables, samples, 0, 0, NULL);\n    CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_BAD_SITE_POSITION);\n\n    /* TODO More tests for this: see\n     * https://github.com/tskit-dev/msprime/issues/517 */\n\n    tsk_tbl_collection_free(&tables);\n}\nvoid\ntest_tsk_tbl_collection_position_errors(void)\n{\n    int ret;\n    int j;\n    tsk_tbl_collection_t t1, t2;\n    tsk_tbl_collection_position_t pos1, pos2;\n    tsk_treeseq_t **examples = get_example_tree_sequences(1);\n\n    CU_ASSERT_FATAL(examples != NULL);\n    for (j = 0; examples[j] != NULL; j++) {\n        // set-up\n        ret = tsk_tbl_collection_init(&t1, 0);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        ret = tsk_tbl_collection_init(&t2, 0);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        ret = tsk_treeseq_copy_tables(examples[j], &t1);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        ret = tsk_tbl_collection_copy(&t1, &t2);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        tsk_tbl_collection_record_position(&t1, &pos1);\n\n        // for each table, add a new row to t2, bookmark that location,\n        // then try to reset t1 to this illegal location\n\n        // individuals\n        tsk_individual_tbl_add_row(t2.individuals, 0, NULL, 0, NULL, 0);\n        tsk_tbl_collection_record_position(&t2, &pos2);\n        ret = tsk_tbl_collection_reset_position(&t1, &pos2);\n        CU_ASSERT_EQUAL(ret, TSK_ERR_BAD_TABLE_POSITION);\n        ret = tsk_tbl_collection_reset_position(&t2, &pos1);\n        CU_ASSERT_EQUAL(ret, 0);\n\n        // nodes\n        tsk_node_tbl_add_row(t2.nodes, 0, 1.2, 0, -1, NULL, 0);\n        tsk_tbl_collection_record_position(&t2, &pos2);\n        ret = tsk_tbl_collection_reset_position(&t1, &pos2);\n        CU_ASSERT_EQUAL(ret, TSK_ERR_BAD_TABLE_POSITION);\n        ret = tsk_tbl_collection_reset_position(&t2, &pos1);\n        CU_ASSERT_EQUAL(ret, 0);\n\n        // edges\n        tsk_edge_tbl_add_row(t2.edges, 0.1, 0.4, 0, 3);\n        tsk_tbl_collection_record_position(&t2, &pos2);\n        ret = tsk_tbl_collection_reset_position(&t1, &pos2);\n        CU_ASSERT_EQUAL(ret, TSK_ERR_BAD_TABLE_POSITION);\n        ret = tsk_tbl_collection_reset_position(&t2, &pos1);\n        CU_ASSERT_EQUAL(ret, 0);\n\n        // migrations\n        tsk_migration_tbl_add_row(t2.migrations, 0.1, 0.2, 2, 1, 2, 1.2);\n        tsk_tbl_collection_record_position(&t2, &pos2);\n        ret = tsk_tbl_collection_reset_position(&t1, &pos2);\n        CU_ASSERT_EQUAL(ret, TSK_ERR_BAD_TABLE_POSITION);\n        ret = tsk_tbl_collection_reset_position(&t2, &pos1);\n        CU_ASSERT_EQUAL(ret, 0);\n\n        // sites\n        tsk_site_tbl_add_row(t2.sites, 0.3, \"A\", 1, NULL, 0);\n        tsk_tbl_collection_record_position(&t2, &pos2);\n        ret = tsk_tbl_collection_reset_position(&t1, &pos2);\n        CU_ASSERT_EQUAL(ret, TSK_ERR_BAD_TABLE_POSITION);\n        ret = tsk_tbl_collection_reset_position(&t2, &pos1);\n        CU_ASSERT_EQUAL(ret, 0);\n\n        // mutations\n        tsk_mutation_tbl_add_row(t2.mutations, 0, 1, -1, \"X\", 1, NULL, 0);\n        tsk_tbl_collection_record_position(&t2, &pos2);\n        ret = tsk_tbl_collection_reset_position(&t1, &pos2);\n        CU_ASSERT_EQUAL(ret, TSK_ERR_BAD_TABLE_POSITION);\n        ret = tsk_tbl_collection_reset_position(&t2, &pos1);\n        CU_ASSERT_EQUAL(ret, 0);\n\n        // populations\n        tsk_population_tbl_add_row(t2.populations, NULL, 0);\n        tsk_tbl_collection_record_position(&t2, &pos2);\n        ret = tsk_tbl_collection_reset_position(&t1, &pos2);\n        CU_ASSERT_EQUAL(ret, TSK_ERR_BAD_TABLE_POSITION);\n        ret = tsk_tbl_collection_reset_position(&t2, &pos1);\n        CU_ASSERT_EQUAL(ret, 0);\n\n        // provenance\n        tsk_provenance_tbl_add_row(t2.provenances, \"abc\", 3, NULL, 0);\n        tsk_tbl_collection_record_position(&t2, &pos2);\n        ret = tsk_tbl_collection_reset_position(&t1, &pos2);\n        CU_ASSERT_EQUAL(ret, TSK_ERR_BAD_TABLE_POSITION);\n        ret = tsk_tbl_collection_reset_position(&t2, &pos1);\n        CU_ASSERT_EQUAL(ret, 0);\n\n        tsk_tbl_collection_free(&t1);\n        tsk_tbl_collection_free(&t2);\n        tsk_treeseq_free(examples[j]);\n        free(examples[j]);\n    }\n    free(examples);\n}\n\nvoid\ntest_tsk_tbl_collection_position(void)\n{\n    int ret;\n    int j, k;\n    tsk_treeseq_t **examples;\n    tsk_tbl_collection_t t1, t2, t3;\n    tsk_tbl_collection_position_t pos1, pos2;\n\n    examples = get_example_tree_sequences(1);\n    CU_ASSERT_FATAL(examples != NULL);\n\n    for (j = 0; examples[j] != NULL; j++) {\n        ret = tsk_tbl_collection_init(&t1, 0);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        ret = tsk_tbl_collection_init(&t2, 0);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        ret = tsk_tbl_collection_init(&t3, 0);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n\n        ret = tsk_treeseq_copy_tables(examples[j], &t1);\n\n        // bookmark at pos1\n        tsk_tbl_collection_record_position(&t1, &pos1);\n        // copy to t2\n        ret = tsk_tbl_collection_copy(&t1, &t2);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        // resetting position should do nothing\n        ret = tsk_tbl_collection_reset_position(&t2, &pos1);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        CU_ASSERT_TRUE(tsk_tbl_collection_equals(&t1, &t2));\n        // add more rows to t2\n        // (they don't have to make sense for this test)\n        for (k = 0; k < 3; k++) {\n            tsk_node_tbl_add_row(t2.nodes, 0, 1.2, 0, -1, NULL, 0);\n            tsk_node_tbl_add_row(t2.nodes, 0, 1.2, k, -1, NULL, 0);\n            tsk_edge_tbl_add_row(t2.edges, 0.1, 0.5, k, k + 1);\n            tsk_edge_tbl_add_row(t2.edges, 0.3, 0.8, k, k + 2);\n        }\n        // bookmark at pos2\n        tsk_tbl_collection_record_position(&t2, &pos2);\n        // copy to t3\n        ret = tsk_tbl_collection_copy(&t2, &t3);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        // add more rows to t3\n        for (k = 0; k < 3; k++) {\n            tsk_node_tbl_add_row(t3.nodes, 0, 1.2, k + 5, -1, NULL, 0);\n            tsk_site_tbl_add_row(t3.sites, 0.2, \"A\", 1, NULL, 0);\n            tsk_site_tbl_add_row(t3.sites, 0.2, \"C\", 1, NULL, 0);\n            tsk_mutation_tbl_add_row(t3.mutations, 0, k, -1, \"T\", 1, NULL, 0);\n            tsk_migration_tbl_add_row(t3.migrations, 0.0, 0.5, 1, 0, 1, 1.2);\n            tsk_individual_tbl_add_row(t3.individuals, k, NULL, 0, NULL, 0);\n            tsk_population_tbl_add_row(t3.populations, \"X\", 1);\n            tsk_provenance_tbl_add_row(t3.provenances, \"abc\", 3, NULL, 0);\n        }\n        // now resetting t3 to pos2 should equal t2\n        ret = tsk_tbl_collection_reset_position(&t3, &pos2);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        CU_ASSERT_TRUE(tsk_tbl_collection_equals(&t2, &t3));\n        // and resetting to pos1 should equal t1\n        ret = tsk_tbl_collection_reset_position(&t3, &pos1);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        CU_ASSERT_TRUE(tsk_tbl_collection_equals(&t1, &t3));\n\n        ret = tsk_tbl_collection_clear(&t1);\n        CU_ASSERT_EQUAL_FATAL(ret, 0);\n        CU_ASSERT_EQUAL(t1.individuals->num_rows, 0);\n        CU_ASSERT_EQUAL(t1.populations->num_rows, 0);\n        CU_ASSERT_EQUAL(t1.nodes->num_rows, 0);\n        CU_ASSERT_EQUAL(t1.edges->num_rows, 0);\n        CU_ASSERT_EQUAL(t1.migrations->num_rows, 0);\n        CU_ASSERT_EQUAL(t1.sites->num_rows, 0);\n        CU_ASSERT_EQUAL(t1.mutations->num_rows, 0);\n        CU_ASSERT_EQUAL(t1.provenances->num_rows, 0);\n\n        tsk_tbl_collection_free(&t1);\n        tsk_tbl_collection_free(&t2);\n        tsk_tbl_collection_free(&t3);\n        tsk_treeseq_free(examples[j]);\n        free(examples[j]);\n    }\n    free(examples);\n}\n\nstatic int\nmsprime_suite_init(void)\n{\n    int fd;\n    static char template[] = \"/tmp/tsk_c_test_XXXXXX\";\n\n    _tmp_file_name = NULL;\n    _devnull = NULL;\n\n    _tmp_file_name = malloc(sizeof(template));\n    if (_tmp_file_name == NULL) {\n        return CUE_NOMEMORY;\n    }\n    strcpy(_tmp_file_name, template);\n    fd = mkstemp(_tmp_file_name);\n    if (fd == -1) {\n        return CUE_SINIT_FAILED;\n    }\n    close(fd);\n    _devnull = fopen(\"/dev/null\", \"w\");\n    if (_devnull == NULL) {\n        return CUE_SINIT_FAILED;\n    }\n    return CUE_SUCCESS;\n}\n\nstatic int\nmsprime_suite_cleanup(void)\n{\n    if (_tmp_file_name != NULL) {\n        unlink(_tmp_file_name);\n        free(_tmp_file_name);\n    }\n    if (_devnull != NULL) {\n        fclose(_devnull);\n    }\n    return CUE_SUCCESS;\n}\n\nstatic void\nhandle_cunit_error()\n{\n    fprintf(stderr, \"CUnit error occured: %d: %s\\n\", CU_get_error(), CU_get_error_msg());\n    exit(EXIT_FAILURE);\n}\n\nint\nmain(int argc, char **argv)\n{\n    int ret;\n    CU_pTest test;\n    CU_pSuite suite;\n    CU_TestInfo tests[] = {\n        { \"test_node_metadata\", test_node_metadata },\n\n        { \"test_diff_iter_from_examples\", test_diff_iter_from_examples },\n        { \"test_tree_iter_from_examples\", test_tree_iter_from_examples },\n        { \"test_tree_equals_from_examples\", test_tree_equals_from_examples },\n        { \"test_next_prev_from_examples\", test_next_prev_from_examples },\n        { \"test_sample_sets_from_examples\", test_sample_sets_from_examples },\n        { \"test_tsk_vargen_from_examples\", test_tsk_vargen_from_examples },\n        { \"test_newick_from_examples\", test_newick_from_examples },\n        { \"test_stats_from_examples\", test_stats_from_examples },\n        { \"test_compute_mutation_parents_from_examples\",\n            test_compute_mutation_parents_from_examples },\n        { \"test_individual_nodes_from_examples\", test_individual_nodes_from_examples },\n        { \"test_ld_from_examples\", test_ld_from_examples },\n        { \"test_simplify_from_examples\", test_simplify_from_examples },\n        { \"test_reduce_topology_from_examples\", test_reduce_topology_from_examples },\n        { \"test_save_empty_kas\", test_save_empty_kas },\n        { \"test_save_kas\", test_save_kas },\n        { \"test_save_kas_tables\", test_save_kas_tables },\n        { \"test_dump_tables\", test_dump_tables },\n        { \"test_sort_tables\", test_sort_tables },\n        { \"test_dump_tables_kas\", test_dump_tables_kas },\n\n        { \"test_tsk_tbl_collection_position\", test_tsk_tbl_collection_position },\n        { \"test_tsk_tbl_collection_position_errors\",\n            test_tsk_tbl_collection_position_errors },\n\n        { \"test_genealogical_nearest_neighbours_from_examples\",\n            test_genealogical_nearest_neighbours_from_examples },\n        { \"test_mean_descendants_from_examples\", test_mean_descendants_from_examples },\n        CU_TEST_INFO_NULL,\n    };\n\n    /* We use initialisers here as the struct definitions change between\n     * versions of CUnit */\n    CU_SuiteInfo suites[] = {\n        { .pName = \"msprime\",\n            .pInitFunc = msprime_suite_init,\n            .pCleanupFunc = msprime_suite_cleanup,\n            .pTests = tests },\n        CU_SUITE_INFO_NULL,\n    };\n    if (CUE_SUCCESS != CU_initialize_registry()) {\n        handle_cunit_error();\n    }\n    if (CUE_SUCCESS != CU_register_suites(suites)) {\n        handle_cunit_error();\n    }\n    CU_basic_set_mode(CU_BRM_VERBOSE);\n\n    if (argc == 1) {\n        CU_basic_run_tests();\n    } else if (argc == 2) {\n        suite = CU_get_suite_by_name(\"msprime\", CU_get_registry());\n        if (suite == NULL) {\n            printf(\"Suite not found\\n\");\n            return EXIT_FAILURE;\n        }\n        test = CU_get_test_by_name(argv[1], suite);\n        if (test == NULL) {\n            printf(\"Test '%s' not found\\n\", argv[1]);\n            return EXIT_FAILURE;\n        }\n        CU_basic_run_test(suite, test);\n    } else {\n        printf(\"usage: ./tests <test_name>\\n\");\n        return EXIT_FAILURE;\n    }\n\n    ret = EXIT_SUCCESS;\n    if (CU_get_number_of_tests_failed() != 0) {\n        printf(\"Test failed!\\n\");\n        ret = EXIT_FAILURE;\n    }\n    CU_cleanup_registry();\n    return ret;\n}\n", "meta": {"hexsha": "4f61515a434f8b8da5f2a249049535cd7183611d", "size": 97770, "ext": "c", "lang": "C", "max_stars_repo_path": "c/tests/old_tests.c", "max_stars_repo_name": "grahamgower/tskit", "max_stars_repo_head_hexsha": "5fd0e3774283fa7e634c48f0f6314f6352c3ee8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c/tests/old_tests.c", "max_issues_repo_name": "grahamgower/tskit", "max_issues_repo_head_hexsha": "5fd0e3774283fa7e634c48f0f6314f6352c3ee8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c/tests/old_tests.c", "max_forks_repo_name": "grahamgower/tskit", "max_forks_repo_head_hexsha": "5fd0e3774283fa7e634c48f0f6314f6352c3ee8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-07T10:09:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-07T10:09:40.000Z", "avg_line_length": 33.4943473792, "max_line_length": 89, "alphanum_fraction": 0.591940268, "num_tokens": 27880, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.373875808818685, "lm_q2_score": 0.02556521206720831, "lm_q1q2_score": 0.009558214339248711}}
{"text": "#pragma once\n\n#include <gsl\\gsl>\n#include <winrt\\Windows.Foundation.h>\n#include <d3d11.h>\n#include \"DrawableGameComponent.h\"\n#include \"MatrixHelper.h\"\n#include \"DirectionalLight.h\"\n\nnamespace Library\n{\n\tclass ProxyModel;\n}\n\nnamespace Rendering\n{\n\tclass TransparencyMaterial;\n\n\tclass TransparencyDemo final : public Library::DrawableGameComponent\n\t{\n\tpublic:\n\t\tTransparencyDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera);\n\t\tTransparencyDemo(const TransparencyDemo&) = delete;\n\t\tTransparencyDemo(TransparencyDemo&&) = default;\n\t\tTransparencyDemo& operator=(const TransparencyDemo&) = default;\t\t\n\t\tTransparencyDemo& operator=(TransparencyDemo&&) = default;\n\t\t~TransparencyDemo();\n\n\t\tfloat AmbientLightIntensity() const;\n\t\tvoid SetAmbientLightIntensity(float intensity);\n\t\t\n\t\tfloat DirectionalLightIntensity() const;\n\t\tvoid SetDirectionalLightIntensity(float intensity);\n\n\t\tconst DirectX::XMFLOAT3& LightDirection() const;\n\t\tvoid RotateDirectionalLight(DirectX::XMFLOAT2 amount);\n\n\t\tfloat SpecularIntensity() const;\n\t\tvoid SetSpecularIntensity(float intensity);\n\n\t\tfloat SpecularPower() const;\n\t\tvoid SetSpecularPower(float power);\n\t\t\n\t\tfloat FogStart() const;\n\t\tvoid SetFogStart(float fogStart);\n\n\t\tfloat FogRange() const;\n\t\tvoid SetFogRange(float fogRange);\n\n\t\tvirtual void Initialize() override;\n\t\tvirtual void Update(const Library::GameTime& gameTime) override;\n\t\tvirtual void Draw(const Library::GameTime& gameTime) override;\n\n\tprivate:\n\t\tinline static const float RotationRate{ DirectX::XM_PI };\n\n\t\tstd::shared_ptr<TransparencyMaterial> mMaterial;\n\t\tDirectX::XMFLOAT4X4 mWorldMatrix{ Library::MatrixHelper::Identity };\n\t\twinrt::com_ptr<ID3D11Buffer> mVertexBuffer;\n\t\tstd::uint32_t mVertexCount{ 0 };\n\t\tLibrary::DirectionalLight mDirectionalLight;\n\t\tstd::unique_ptr<Library::ProxyModel> mProxyModel;\n\t\tbool mUpdateMaterial{ true };\n\t};\n}", "meta": {"hexsha": "2fd0cfcf2e15ee980324c5ad4c65910d6dbe95b4", "size": 1864, "ext": "h", "lang": "C", "max_stars_repo_path": "source/5.4_Transparency/TransparencyDemo.h", "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/5.4_Transparency/TransparencyDemo.h", "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/5.4_Transparency/TransparencyDemo.h", "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6769230769, "max_line_length": 88, "alphanum_fraction": 0.7741416309, "num_tokens": 455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.020023443007294046, "lm_q1q2_score": 0.009542765481509598}}
{"text": "#include \"../include/paralleltt.h\"\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <cblas.h>\n#include <lapacke.h>\n#include <time.h>\n\nflattening_info* flattening_info_init(const MPI_tensor* ten, int flattening, int iscol, int t_v_block)\n{\n    // Tensor info\n    flattening_info* fi = (flattening_info*) malloc(sizeof(flattening_info));\n    int t_d = ten->d;\n\n    int* t_nps = (int*) malloc(t_d*sizeof(int));\n    int t_Nblocks = 1;\n    for (int ii = 0; ii < t_d; ++ii){\n        t_nps[ii] = ten->nps[ii];\n        t_Nblocks = t_Nblocks * t_nps[ii];\n    }\n\n    int* t_t_block = (int*) malloc(t_d*sizeof(int));\n    to_tensor_ind(t_t_block, t_v_block, t_nps, t_d);\n\n    long t_N = 1;\n    int* t_t_sizes = (int*) malloc(t_d*sizeof(int));\n    int* t_t_index = (int*) malloc(t_d*sizeof(int));\n    for (int ii = 0; ii < t_d; ++ii){\n        int* partition_ii = ten->partitions[ii];\n        t_t_index[ii] = partition_ii[t_t_block[ii]];\n        t_t_sizes[ii] = partition_ii[t_t_block[ii]+1] - t_t_index[ii];\n        t_N = t_N * t_t_sizes[ii];\n    }\n\n    // Flattening info\n    int f_d = (iscol) ? flattening : t_d-flattening;\n\n    int offset = (iscol) ? 0 : flattening;\n    long f_N = 1;\n    int f_Nblocks = 1;\n    int* f_nps     = (int*) malloc(f_d * sizeof(int));\n    int* f_t_block = (int*) malloc(f_d * sizeof(int));\n    int* f_t_index = (int*) malloc(f_d * sizeof(int));\n    int* f_t_sizes = (int*) malloc(f_d * sizeof(int));\n    for (int ii = 0; ii < f_d; ++ii){\n        f_nps[ii]     = t_nps[ii+offset];\n        f_t_block[ii] = t_t_block[ii+offset];\n        f_t_index[ii] = t_t_index[ii+offset];\n        f_t_sizes[ii] = t_t_sizes[ii+offset];\n        f_N = f_N * f_t_sizes[ii];\n        f_Nblocks = f_Nblocks * f_nps[ii];\n    }\n    int f_v_block = to_vec_ind(f_t_block, f_nps, f_d);\n\n    // Sketching dimensions info\n    int s_d = t_d - f_d;\n    long s_N = 1;\n\n    offset = (iscol) ? flattening : 0;\n    int* s_nps     = (int*) malloc(s_d * sizeof(int));\n    int* s_t_index = (int*) malloc(s_d * sizeof(int));\n    int* s_t_sizes = (int*) malloc(s_d * sizeof(int));\n    for (int ii = 0; ii < s_d; ++ii){\n        s_nps[ii]     = t_nps[ii+offset];\n        s_t_index[ii] = t_t_index[ii+offset];\n        s_t_sizes[ii] = t_t_sizes[ii+offset];\n        s_N = s_N * s_t_sizes[ii];\n    }\n\n    // Assigning\n    fi->t_d       = t_d;\n    fi->t_N       = t_N;\n    fi->t_Nblocks = t_Nblocks;\n    fi->t_nps     = t_nps;\n    fi->t_v_block = t_v_block;\n    fi->t_t_block = t_t_block;\n    fi->t_t_index = t_t_index;\n    fi->t_t_sizes = t_t_sizes;\n\n    fi->flattening = flattening;\n    fi->iscol      = iscol;\n    fi->f_d        = f_d;\n    fi->f_N        = f_N;\n    fi->f_Nblocks  = f_Nblocks;\n    fi->f_nps      = f_nps;\n    fi->f_v_block  = f_v_block;\n    fi->f_t_block  = f_t_block;\n    fi->f_t_index  = f_t_index;\n    fi->f_t_sizes  = f_t_sizes;\n\n    fi->s_d       = s_d;\n    fi->s_N       = s_N;\n    fi->s_nps     = s_nps;\n    fi->s_t_index = s_t_index;\n    fi->s_t_sizes = s_t_sizes;\n\n    return fi;\n}\n\nvoid flattening_info_free(flattening_info* fi)\n{\n    free(fi->t_nps);     fi->t_nps = NULL;\n    free(fi->t_t_block); fi->t_t_block = NULL;\n    free(fi->t_t_index); fi->t_t_index = NULL;\n    free(fi->t_t_sizes); fi->t_t_sizes = NULL;\n    free(fi->f_nps);     fi->f_nps = NULL;\n    free(fi->f_t_block); fi->f_t_block = NULL;\n    free(fi->f_t_index); fi->f_t_index = NULL;\n    free(fi->f_t_sizes); fi->f_t_sizes = NULL;\n    free(fi->s_nps);     fi->s_nps = NULL;\n    free(fi->s_t_index); fi->s_t_index = NULL;\n    free(fi->s_t_sizes); fi->s_t_sizes = NULL;\n\n    free(fi);\n}\n\nvoid flattening_info_update(flattening_info* fi, const MPI_tensor* ten, int t_v_block)\n{\n    // Tensor info\n    int t_d = ten->d;\n    int* t_nps = fi->t_nps;\n    int* t_t_block = fi->t_t_block;\n    to_tensor_ind(t_t_block, t_v_block, t_nps, t_d);\n\n    long t_N = 1;\n    int* t_t_sizes = fi->t_t_sizes;\n    int* t_t_index = fi->t_t_index;\n    for (int ii = 0; ii < t_d; ++ii){\n        int* partition_ii = ten->partitions[ii];\n        t_t_index[ii] = partition_ii[t_t_block[ii]];\n        t_t_sizes[ii] = partition_ii[t_t_block[ii]+1] - t_t_index[ii];\n        t_N = t_N * t_t_sizes[ii];\n    }\n\n    // Flattening info\n    int flattening = fi->flattening;\n    int iscol = fi->iscol;\n    int f_d = fi->f_d;\n\n    int offset = (iscol) ? 0 : flattening;\n    long f_N = 1;\n    int* f_nps     = fi->f_nps;\n    int* f_t_block = fi->f_t_block;\n    int* f_t_index = fi->f_t_index;\n    int* f_t_sizes = fi->f_t_sizes;\n    for (int ii = 0; ii < f_d; ++ii){\n        f_nps[ii]     = t_nps[ii+offset];\n        f_t_block[ii] = t_t_block[ii+offset];\n        f_t_index[ii] = t_t_index[ii+offset];\n        f_t_sizes[ii] = t_t_sizes[ii+offset];\n        f_N = f_N * f_t_sizes[ii];\n    }\n    int f_v_block = to_vec_ind(f_t_block, f_nps, f_d);\n\n    // Sketching dimensions info\n    int s_d = fi->s_d;\n    long s_N = 1;\n\n    offset = (iscol) ? flattening : 0;\n    int* s_nps     = fi->s_nps;\n    int* s_t_index = fi->s_t_index;\n    int* s_t_sizes = fi->s_t_sizes;\n    for (int ii = 0; ii < s_d; ++ii){\n        s_nps[ii]     = t_nps[ii+offset];\n        s_t_index[ii] = t_t_index[ii+offset];\n        s_t_sizes[ii] = t_t_sizes[ii+offset];\n        s_N = s_N * s_t_sizes[ii];\n    }\n\n    // Assigning\n    fi->t_d = t_d;\n    fi->t_N = t_N;\n    fi->t_nps = t_nps;\n    fi->t_v_block = t_v_block;\n    fi->t_t_block = t_t_block;\n    fi->t_t_index = t_t_index;\n    fi->t_t_sizes = t_t_sizes;\n\n    fi->flattening = flattening;\n    fi->iscol = iscol;\n    fi->f_d = f_d;\n    fi->f_N       = f_N;\n    fi->f_nps     = f_nps;\n    fi->f_v_block = f_v_block;\n    fi->f_t_block = f_t_block;\n    fi->f_t_index = f_t_index;\n    fi->f_t_sizes = f_t_sizes;\n\n    fi->s_d = s_d;\n    fi->s_N = s_N;\n    fi->s_nps = s_nps;\n    fi->s_t_index = s_t_index;\n    fi->s_t_sizes = s_t_sizes;\n}\n\nvoid flattening_info_f_update(flattening_info* fi, const MPI_tensor* ten, int f_v_block)\n{\n    // tensor info\n    int t_d = fi->t_d;\n\n    long t_N = -1;\n    int t_v_block = -1;\n    int* t_t_block = fi->t_t_block;\n    int* t_t_index = fi->t_t_index;\n    int* t_t_sizes = fi->t_t_sizes;\n    for (int ii = 0; ii < t_d; ++ii){\n        t_t_block[ii] = -1;\n        t_t_index[ii] = 0;\n        t_t_sizes[ii] = 0;\n    }\n    fi->t_N = t_N;\n    fi->t_v_block = t_v_block;\n\n    // flattening info\n    int flattening = fi->flattening;\n    int iscol = fi->iscol;\n    int f_d = fi->f_d;\n    int f_Nblocks = fi->f_Nblocks;\n    int* f_nps = fi->f_nps;\n\n    int* f_t_block = fi->f_t_block;\n    to_tensor_ind(f_t_block, (long) f_v_block, f_nps, f_d);\n\n    long f_N = 1;\n    int* f_t_index = fi->f_t_index;\n    int* f_t_sizes = fi->f_t_sizes;\n    int offset = (iscol) ? 0 : flattening;\n    for (int ii = 0; ii < f_d; ++ii){\n        int* partition_ii = ten->partitions[ii + offset];\n        f_t_index[ii] = partition_ii[f_t_block[ii]];\n        f_t_sizes[ii] = partition_ii[f_t_block[ii]+1] - f_t_index[ii];\n        f_N = f_N * f_t_sizes[ii];\n    }\n    fi->f_N = f_N;\n    fi->f_v_block = f_v_block;\n\n    // Sketching dimensions info\n    int s_d = fi->s_d;\n    long s_N = 0;\n\n    int* s_t_index = fi->s_t_index;\n    int* s_t_sizes = fi->s_t_sizes;\n\n    for (int ii = 0; ii < s_d; ++ii){\n        s_t_index[ii] = 0;\n        s_t_sizes[ii] = 0;\n    }\n    fi->s_N = s_N;\n}\n\nvoid flattening_info_print(flattening_info* fi)\n{\n    printf(\"\\n~~~~~~~~~~~~~~~ Flattening Info ~~~~~~~~~~~~~~~\\n\");\n    int t_d = fi->t_d;\n    printf(\"t_d = %d\\n\", t_d);\n\n    printf(\"t_N = %ld\\n\", fi->t_N);\n\n    printf(\"t_Nblocks = %d\\n\", fi->t_Nblocks);\n\n    if (t_d>0){\n        printf(\"t_nps = [%d\", fi->t_nps[0]);\n        for (int ii = 1; ii < t_d; ++ii){printf(\", %d\", fi->t_nps[ii]); }\n        printf(\"]\\n\");\n    }\n    else{ printf(\"t_nps = []\\n\"); }\n\n    printf(\"t_v_block = %d\\n\", fi->t_v_block);\n\n    if (t_d>0){\n        printf(\"t_t_block = [%d\", fi->t_t_block[0]);\n        for (int ii = 1; ii < t_d; ++ii){printf(\", %d\", fi->t_t_block[ii]);}\n        printf(\"]\\n\");\n    }\n    else{ printf(\"t_t_block = []\\n\"); }\n\n    if (t_d>0){\n        printf(\"t_t_index = [%d\", fi->t_t_index[0]);\n        for (int ii = 1; ii < t_d; ++ii){printf(\", %d\", fi->t_t_index[ii]);}\n        printf(\"]\\n\");\n    }\n    else{ printf(\"t_t_index = []\\n\"); }\n\n    if (t_d>0){\n        printf(\"t_t_sizes = [%d\", fi->t_t_sizes[0]);\n        for (int ii = 1; ii < t_d; ++ii){printf(\", %d\", fi->t_t_sizes[ii]);}\n        printf(\"]\\n\");\n    }\n    else{ printf(\"t_t_sizes = []\\n\"); }\n\n    printf(\"flattening = %d\\n\", fi->flattening);\n\n    printf(\"iscol = %d\\n\", fi->iscol);\n\n    int f_d = fi->f_d;\n    printf(\"f_d = %d\\n\", f_d);\n\n    printf(\"f_N = %ld\\n\", fi->f_N);\n\n    printf(\"f_Nblocks = %d\\n\", fi->f_Nblocks);\n\n    if (f_d>0){\n        printf(\"f_nps = [%d\", fi->f_nps[0]);\n        for (int ii = 1; ii < f_d; ++ii){printf(\", %d\", fi->f_nps[ii]);}\n        printf(\"]\\n\");\n    }\n    else{ printf(\"f_nps = []\\n\"); }\n\n    printf(\"f_v_block = %d\\n\", fi->f_v_block);\n\n    if (f_d>0){\n        printf(\"f_t_block = [%d\", fi->f_t_block[0]);\n        for (int ii = 1; ii < f_d; ++ii){printf(\", %d\", fi->f_t_block[ii]);}\n        printf(\"]\\n\");\n    }\n    else{ printf(\"f_t_block = []\\n\"); }\n\n    if (f_d>0){\n        printf(\"f_t_index = [%d\", fi->f_t_index[0]);\n        for (int ii = 1; ii < f_d; ++ii){printf(\", %d\", fi->f_t_index[ii]);}\n        printf(\"]\\n\");\n    }\n    else{ printf(\"f_t_index = []\\n\"); }\n\n    if (f_d>0){\n        printf(\"f_t_sizes = [%d\", fi->f_t_sizes[0]);\n        for (int ii = 1; ii < f_d; ++ii){printf(\", %d\", fi->f_t_sizes[ii]);}\n        printf(\"]\\n\");\n    }\n    else{ printf(\"f_t_sizes = []\\n\"); }\n\n    int s_d = fi->s_d;\n    printf(\"s_d = %d\\n\", s_d);\n\n    printf(\"s_N = %ld\\n\", fi->s_N);\n\n    if (s_d>0){\n        printf(\"s_nps = [%d\", fi->s_nps[0]);\n        for (int ii = 1; ii < s_d; ++ii){printf(\", %d\", fi->s_nps[ii]);}\n        printf(\"]\\n\");\n    }\n    else{ printf(\"s_nps = []\\n\"); }\n\n    if (s_d>0){\n        printf(\"s_t_index = [%d\", fi->s_t_index[0]);\n        for (int ii = 1; ii < s_d; ++ii){printf(\", %d\", fi->s_t_index[ii]);}\n        printf(\"]\\n\");\n    }\n    else{ printf(\"s_t_index = []\\n\"); }\n\n\n    if (s_d>0){\n        printf(\"s_t_sizes = [%d\", fi->s_t_sizes[0]);\n        for (int ii = 1; ii < s_d; ++ii){printf(\", %d\", fi->s_t_sizes[ii]);}\n        printf(\"]\\n\");\n    }\n    else{ printf(\"s_t_sizes = []\\n\"); }\n    printf(\"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\\n\");\n}\n\n\nint* get_sketch_owners(MPI_tensor* ten, int flattening, int iscol)\n{\n    int np_flattening = 1;\n    int* nps = ten->nps;\n    int ii0 = (iscol) ? 0 : flattening;\n    int ii1 = (iscol) ? flattening : ten->d;\n\n    for (int ii = ii0; ii < ii1; ++ii){\n        np_flattening = np_flattening * nps[ii];\n    }\n\n    int* owners = get_partition(ten->comm_size, np_flattening);\n    return owners;\n}\n\nvoid get_sketch_height(MPI_tensor* ten, int* owners, int flattening, int iscol, long* X_height_ptr, long* buf_height_ptr)\n{\n    *X_height_ptr = 0;\n    *buf_height_ptr = 0;\n\n    flattening_info* fi = flattening_info_init(ten, flattening, iscol, 0);\n\n    for (int rank = 0; rank < ten->comm_size; ++rank){\n        long X_height_tmp = 0;\n        for (int jj = owners[rank]; jj < owners[rank + 1]; ++jj){\n            flattening_info_f_update(fi, ten, jj);\n            X_height_tmp = X_height_tmp + fi->f_N;\n            *buf_height_ptr = (fi->f_N > *buf_height_ptr) ? fi->f_N : *buf_height_ptr;\n        }\n\n        *X_height_ptr = (X_height_tmp > *X_height_ptr) ? X_height_tmp : *X_height_ptr;\n    }\n\n    flattening_info_free(fi);\n}\n\nmatrix_tt** get_sketch_Omega(const MPI_tensor* ten, int flattening, int r, int buf, int iscol)\n{\n    // Seed random numbers\n    double t = (double) time(NULL);\n    MPI_Bcast(&t, 1, MPI_DOUBLE, 0, ten->comm);\n    srand((unsigned long) t);\n\n    int ii0 = iscol ? flattening : 0;\n    int n_Omega = iscol ? (ten->d) - flattening : flattening;\n\n    matrix_tt** Omegas = (matrix_tt**) malloc(n_Omega * sizeof(matrix_tt*));\n    for (int ii = 0; ii < n_Omega; ++ii){\n        Omegas[ii] = matrix_tt_init(ten->n[ii+ii0], r+buf);\n        matrix_tt_dlarnv(Omegas[ii]);\n    }\n\n    return Omegas;\n}\n\nvoid get_KR_info(int *d_KR, int *stride_KR, matrix_tt** KRs, MPI_tensor* ten, int flattening, int r, int buf, int iscol)\n{\n    int max_m = 1000;\n\n\n    int assigned = 0;\n    *d_KR = 0;\n    int N_KR = 1;\n\n    int ii0 = iscol ? flattening : 0;\n    int n_Omega = iscol ? (ten->d) - flattening : flattening;\n\n    KRs[2] = matrix_tt_init(1, r+buf);\n\n    for (int ii = 0; ii < n_Omega; ++ii){\n        if (assigned == 0){\n            int* partition_ii = ten->partitions[ii + ii0];\n            int sz_ii = 0;\n            for (int jj = 0; jj < ten->nps[ii+ii0]; ++jj){\n                int candidate_n = partition_ii[jj+1] - partition_ii[jj];\n                sz_ii = (sz_ii > candidate_n) ? sz_ii : candidate_n;\n            }\n            if (N_KR * sz_ii < max_m){\n                *d_KR = ii+1;\n                N_KR = N_KR * sz_ii;\n            }\n            else{\n                *stride_KR = max_m / N_KR;\n                KRs[0] = matrix_tt_init(N_KR, r+buf);\n                KRs[1] = matrix_tt_init(*stride_KR, r+buf);\n                N_KR = N_KR * (*stride_KR);\n                KRs[3] = matrix_tt_init(N_KR, r+buf);\n                assigned = 1;\n            }\n        }\n    }\n    if (assigned == 0){\n        *stride_KR = 0;\n        KRs[0] = matrix_tt_init(N_KR, r+buf);\n        KRs[1] = matrix_tt_init(1, r+buf);\n        KRs[3] = matrix_tt_init(N_KR, r+buf);\n    }\n}\n\n\nsketch* sketch_init(MPI_tensor* ten, int flattening, int r, int buf, int iscol)\n{\n    sketch* s = (sketch*) malloc(sizeof(sketch));\n\n    s->ten = ten;\n    s->flattening = flattening;\n    s->r = r;\n    s->buf = buf;\n    s->iscol = iscol;\n    s->owner_partition = get_sketch_owners(ten, flattening, iscol);\n    long recv_buf_height = 0;\n    get_sketch_height(ten, s->owner_partition, flattening, iscol, &(s->lda), &recv_buf_height);\n    s->Omegas = get_sketch_Omega(ten, flattening, r, buf, iscol);\n    s->X_size = (s->lda)*(r+buf);\n    s->X = (double*) calloc(s->X_size, sizeof(double));\n    s->scratch = (double*) calloc(s->X_size, sizeof(double));\n    s->recv_buf = (double*) calloc(recv_buf_height * (r+buf), sizeof(double));\n    s->fi = flattening_info_init(ten, flattening, iscol, 0);\n    s->KRs = (matrix_tt**) calloc(4, sizeof(matrix_tt*));\n    get_KR_info(&(s->d_KR), &(s->stride_KR), s->KRs, ten, flattening, r, buf, iscol);\n\n    return s;\n}\n\nmatrix_tt** copy_sketch_Omega(matrix_tt** Omegas, MPI_tensor* ten, int flattening, int r, int buf, int iscol)\n{\n    int ii0 = iscol ? flattening : 0;\n    int n_Omega = iscol ? (ten->d) - flattening : flattening;\n\n    matrix_tt** Omegas_cp = (matrix_tt**) malloc(n_Omega * sizeof(matrix_tt*));\n    for (int ii = 0; ii < n_Omega; ++ii){\n        submatrix_update(Omegas[ii], 0, ten->n[ii+ii0], 0, r+buf);\n        Omegas_cp[ii] = matrix_tt_copy(Omegas[ii]);\n    }\n\n    return Omegas_cp;\n}\n\n\nsketch* sketch_init_with_Omega(MPI_tensor* ten, int flattening, int r, int buf, int iscol, matrix_tt** Omegas)\n{\n    sketch* s = (sketch*) malloc(sizeof(sketch));\n    s->ten = ten;\n    s->flattening = flattening;\n    s->r = r;\n    s->buf = buf;\n    s->iscol = iscol;\n    s->owner_partition = get_sketch_owners(ten, flattening, iscol);\n    long recv_buf_height;\n    get_sketch_height(ten, s->owner_partition, flattening, iscol, &(s->lda), &recv_buf_height);\n    s->Omegas = copy_sketch_Omega(Omegas, ten, flattening, r, buf, iscol);\n    s->X_size = (s->lda)*(r+buf);\n    s->X = (double*) calloc(s->X_size, sizeof(double));\n    s->scratch = (double*) calloc(s->X_size, sizeof(double));\n    s->recv_buf = (double*) calloc(recv_buf_height * (r+buf), sizeof(double));\n    s->fi = flattening_info_init(ten, flattening, iscol, 0);\n    s->KRs = (matrix_tt**) calloc(4, sizeof(matrix_tt*));\n    get_KR_info(&(s->d_KR), &(s->stride_KR), s->KRs, ten, flattening, r, buf, iscol);\n\n    return s;\n}\n\n\n// NOTE: does not free the MPI_tensor. We assume this is shared, and should not be freed this way.\nvoid sketch_free(sketch* s)\n{\n    MPI_tensor* ten = s->ten; s->ten = NULL;\n    int d = ten->d;\n    int n_Omega = s->iscol ? d - s->flattening : s->flattening;\n    for (int ii = 0; ii < n_Omega; ++ii){\n        matrix_tt_free(s->Omegas[ii]); s->Omegas[ii] = NULL;\n    }\n    for (int ii = 0; ii < 4; ++ii){\n        matrix_tt_free(s->KRs[ii]); s->KRs[ii] = NULL;\n    }\n    free(s->KRs); s->KRs = NULL;\n\n    free(s->owner_partition); s->owner_partition = NULL;\n    free(s->X);               s->X = NULL;\n    free(s->scratch);         s->scratch = NULL;\n    free(s->Omegas);          s->Omegas = NULL;\n    free(s->recv_buf);        s->recv_buf = NULL;\n    flattening_info_free(s->fi); s->fi = NULL;\n    free(s);\n}\n\nvoid sketch_print(sketch* s)\n{\n    printf(\"Printing sketch at %p\\n\", s);\n\n    printf(\"\\nten address: %p\\n\", s->ten);\n    printf(\"flattening = %d\\n\",s->flattening);\n    printf(\"r = %d\\n\", s->r);\n    printf(\"buf = %d\\n\", s->buf);\n    printf(\"iscol = %d\\n\", s->iscol);\n\n    int* op = s->owner_partition;\n    MPI_tensor* ten = s->ten;\n    printf(\"owner_partition = [%d\", op[0]);\n    for (int ii = 1; ii < (ten->comm_size) + 1; ++ii){\n        printf(\", %d\", op[ii]);\n    }\n    printf(\"]\\n\");\n\n    printf(\"lda = %ld\\n\", s->lda);\n    printf(\"X_size = %ld\\n\", s->X_size);\n\n    printf(\"\\nX = \\n\");\n    int r = s->r; int buf = s->buf; long X_size = s->X_size; long lda = s->lda;\n    matrix_tt* X_mat = matrix_tt_wrap(lda, r+buf, s->X);\n    matrix_tt_print(X_mat, 1);\n    free(X_mat); X_mat = NULL;\n\n    printf(\"\\nscratch = \\n\");\n    matrix_tt* scratch_mat = matrix_tt_wrap(lda, r+buf, s->scratch);\n    matrix_tt_print(scratch_mat, 1);\n    free(scratch_mat); scratch_mat = NULL;\n\n    int n_Omega = s->iscol ? (s->ten)->d-s->flattening : s->flattening;\n    for (int ii = 0; ii < n_Omega; ++ii){\n        printf(\"\\nOmegas[%d] = \\n\", ii);\n        matrix_tt_print(s->Omegas[ii], 1);\n    }\n}\n\n// Performs C[ii + n_ii * jj,kk] = A[ii, kk] * B[jj, kk]\nvoid submatrix_khatri_rao_outer_product(matrix_tt* A, matrix_tt* B, matrix_tt* C)\n{\n    for (int kk = 0; kk < A->n; ++kk){\n        int A_offset = A->offset + kk*(A->lda);\n        int B_offset = B->offset + kk*(B->lda);\n        int C_offset = C->offset + kk*(C->lda);\n\n\n        cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans,\n                A->m, B->m, 1,\n                1.0,\n                A->X + A_offset, A->m,\n                B->X + B_offset, 1,\n                0.0,\n                C->X + C_offset, A->m);\n    }\n}\n\n// General idea of the algorithm:\n// Split the Omegas into 3 parts: ii < d_KR, ii == d_KR, ii > d_KR\n// For ii <  d_KR, we will pre-multiply the sketch matrices Omega[ii] (Call this KR_1)\n// For ii == d_KR, we will loop through blocks of Omega[d_KR]\n// For ii > d_KR, we will loop and multiply to get a row vector       (Call this KR_3)\n\n// Then, at each point in the loop, we will perform\n//     KR_2 = Omegas[ii] * KR_3 and\n//     KR_4 = KR_1 * KR_2,\n// where * is the Khatri-Rao product. Finally, we multiply X_mat by KR_4 to update the sketch, and repeat.\nvoid subtensor_khatri_rao(sketch* s, matrix_tt* C, flattening_info* fi, double beta, matrix_tt* X_mat)\n{\n    int r = s->r + s->buf;\n    matrix_tt** Omegas = s->Omegas;\n\n    MPI_tensor* ten = s->ten;\n    int d_KR = s->d_KR;\n    matrix_tt* KR_1;\n    matrix_tt* KR_4;\n    if ((d_KR == 0) || (d_KR%2 == 1)){\n        KR_1 = s->KRs[0];\n        KR_4 = s->KRs[3];\n    }\n    else{\n        KR_1 = s->KRs[3];\n        KR_4 = s->KRs[0];\n    }\n    int s_d = fi->s_d;\n\n    int N_kk = 1;\n\n    int h = 0;\n\n    int Omega_offset_KR;\n\n//    printf(\"Starting loop to get KR_1\\n\");\n    for (int ii = 0; ii < s_d; ++ii){\n        int ii0 = fi->s_t_index[ii];\n        int ii1 = ii0 + fi->s_t_sizes[ii];\n\n        submatrix_update(Omegas[ii], ii0, ii1, 0, r);\n\n        if (ii > d_KR){\n            N_kk = N_kk * fi->s_t_sizes[ii]; // Number of elements in outer loop\n        }\n        else if (ii == d_KR){\n            Omega_offset_KR = ii0;\n        }\n\n\n        if ((ii == 0) && (d_KR > 0)){\n            matrix_tt_reshape(ii1-ii0, r, KR_1);\n            matrix_tt_copy_data(KR_1, Omegas[0]);\n            h = ii1 - ii0;\n        }\n        else if (ii < d_KR){ // Multiply inner matrices\n            matrix_tt* tmp = KR_1;\n            KR_1 = KR_4;\n            KR_4 = tmp;\n\n            h = h*(ii1-ii0);\n            matrix_tt_reshape(h, r, KR_1);\n            submatrix_khatri_rao_outer_product(KR_4, Omegas[ii], KR_1);\n        }\n    }\n//    printf(\"Finished loop to get KR_1\\n\");\n\n    if (fi->iscol){\n        matrix_tt_wrap_update(X_mat, fi->f_N, fi->s_N, get_X(ten));\n    }\n    else{\n        matrix_tt_wrap_update(X_mat, fi->s_N, fi->f_N, get_X(ten));\n    }\n    X_mat->transpose = (fi->iscol ? 0 : 1);\n\n    if (d_KR == s_d){ // If we have done everything, just multiply (the sketch is relatively small)\n        matrix_tt_dgemm(X_mat, KR_1, C, 1.0, beta);\n        return;\n    }\n\n    int stride_KR = s->stride_KR;\n    matrix_tt* KR_2 = s->KRs[1];\n    matrix_tt* KR_3 = s->KRs[2];\n\n    int* t_kk = ten->t_kk;\n    int size_KR = fi->s_t_sizes[d_KR];\n    int N_ll = 1 + (size_KR - 1) / stride_KR;\n\n    int tensor_offset = 0;\n\n    for (int kk = 0; kk < N_kk; ++kk) {\n        to_tensor_ind(t_kk, (long) kk, fi->s_t_sizes + d_KR + 1, s_d - 1 - d_KR);\n\n        for (int ii = d_KR + 1; ii < s_d; ++ii){\n            if (ii == d_KR + 1){\n                for (int jj = 0; jj < r; ++jj){\n                    KR_3->X[jj] = matrix_tt_element(Omegas[ii], t_kk[ii-d_KR-1], jj);\n                }\n            }\n            else{\n                for (int jj = 0; jj < r; ++jj){\n                    KR_3->X[jj] *= matrix_tt_element(Omegas[ii], t_kk[ii-d_KR-1], jj);\n                }\n            }\n        }\n\n        for (int ll = 0; ll < N_ll; ++ll){\n            double bb = ((kk==0) && (ll==0)) ? beta : 1.0;\n            int ii0 = Omega_offset_KR + ll * stride_KR;\n            int ii1 = ((ll+1)*stride_KR > size_KR) ? size_KR + Omega_offset_KR: (ll+1)*stride_KR + Omega_offset_KR;\n\n            submatrix_update(Omegas[d_KR], ii0, ii1, 0, r);\n            if (d_KR + 1 == s_d){ // If we only need KR_1 and Omegas[ii]\n                matrix_tt_reshape((KR_1->m) * (ii1-ii0), r, KR_4);\n                submatrix_khatri_rao_outer_product(KR_1, Omegas[d_KR], KR_4);\n            }\n            else if (d_KR == 0){ // If we only need Omegas[ii] and KR_3\n                matrix_tt_reshape(Omegas[d_KR]->m, r, KR_4);\n                submatrix_khatri_rao_outer_product(Omegas[d_KR], KR_3, KR_4);\n            }\n            else{ // We need everything...\n                matrix_tt_reshape(ii1-ii0, r, KR_2);\n                submatrix_khatri_rao_outer_product(Omegas[d_KR], KR_3, KR_2);\n                matrix_tt_reshape((ii1-ii0) * (KR_1->m), r, KR_4);\n                submatrix_khatri_rao_outer_product(KR_1, KR_2, KR_4);\n            }\n\n\n            if (fi->iscol) {\n                submatrix_update(X_mat, 0, fi->f_N, tensor_offset, tensor_offset + KR_4->m);\n            }\n            else {\n                submatrix_update(X_mat, tensor_offset, tensor_offset + KR_4->m, 0, fi->f_N);\n            }\n\n            matrix_tt_dgemm(X_mat, KR_4, C, 1.0, bb);\n            tensor_offset = tensor_offset + KR_4->m;\n        }\n    }\n}\n\nint get_owner(int block, int* owner_partition, int comm_size)\n{\n    int color = -1;\n    for (int ii = 0; ii < comm_size; ++ii){\n        if ((block >= owner_partition[ii]) && (block < owner_partition[ii+1])){\n            color = ii;\n        }\n    }\n\n    return color;\n}\n\nint s_get_owner(sketch* s, int f_v_block){\n    int* op = s->owner_partition;\n    MPI_tensor* ten = s->ten;\n    int size = ten->comm_size;\n\n    // Binary search (basically wikipedia)\n    int a = 0;\n    int b = size-1;\n    int c;\n\n    while (a <= b){\n        c = (a+b)/2;\n        if (f_v_block < op[c]){\n            b = c-1;\n        }\n        else if(f_v_block >= op[c+1]){\n            a = c+1;\n        }\n        else{\n            return c;\n        }\n    }\n\n    return -1;\n}\n\nvoid own_submatrix_update(matrix_tt* mat, sketch* s, int f_v_block, int with_buf){\n    if (f_v_block == -1){\n        return;\n    }\n\n    int sketch_offset = 0;\n    int sketch_lda = s->lda;\n    MPI_tensor* ten = s->ten;\n    int world_rank = ten->rank;\n    int* owner_partition = s->owner_partition;\n\n    flattening_info* fi = s->fi;\n    if ((f_v_block < owner_partition[world_rank]) || (f_v_block >= owner_partition[world_rank+1])){\n        printf(\"r%d own_submatrix: This core does not own f_v_block = %d\\n\", world_rank, f_v_block);\n    }\n\n    for (int block = s->owner_partition[world_rank]; block < f_v_block; ++block){\n        flattening_info_f_update(fi, ten, block);\n        sketch_offset = sketch_offset + fi->f_N;\n    }\n    flattening_info_f_update(fi, ten, f_v_block);\n\n\n    matrix_tt_wrap_update(mat, sketch_lda, s->r + s->buf, s->X);\n    int r = (with_buf) ? s->r + s->buf : s->r;\n    submatrix_update(mat, sketch_offset, sketch_offset + fi->f_N, 0, r);\n}\n\nmatrix_tt* own_submatrix(sketch* s, int f_v_block, int with_buf){\n    matrix_tt* mat = (matrix_tt*) malloc(sizeof(matrix_tt));\n    own_submatrix_update(mat, s, f_v_block, with_buf);\n    return mat;\n}\n\nvoid subtensor_sketch_multiply(sketch* s, flattening_info* fi, matrix_tt** holders)\n{\n    MPI_tensor* ten = s->ten;\n    int* owner_partition = s->owner_partition;\n    int world_size = ten->comm_size;\n    int world_rank = ten->rank;\n\n    // Actually sketch the thing\n    matrix_tt* sketch_mat = holders[0];\n    double beta = 0.0;\n    if (ten->current_part != -1){\n        int current_color = get_owner(fi->f_v_block, owner_partition, world_size);\n        if (current_color == world_rank){\n            own_submatrix_update(sketch_mat, s, fi->f_v_block, 1);\n            beta = 1.0;\n        }\n        else{\n            matrix_tt_wrap_update(sketch_mat, fi->f_N, s->r + s->buf, s->scratch);\n            beta = 0.0;\n        }\n\n        subtensor_khatri_rao(s, sketch_mat, fi, beta, holders[1]);\n    }\n}\n\nvoid subtensor_sketch_communicate(sketch* s, int stream_step, flattening_info* fi, matrix_tt** holders)\n{\n    MPI_tensor* ten = s->ten;\n    int* owner_partition = s->owner_partition;\n    int world_size = ten->comm_size;\n    int world_rank = ten->rank;\n    int* group_ranks = ten->group_ranks;\n\n    flattening_info* fi_tmp = s->fi;\n    matrix_tt* sketch_mat = holders[0];\n\n    // For each flattening block\n    for (int ii = 0; ii < fi->f_Nblocks; ++ii){\n        int kk = 0;\n        int owner_ii = get_owner(ii, owner_partition, world_size);\n        int group_owner;\n        // For each rank in the world\n        for (int jj = 0; jj < world_size; ++jj){\n            // If the rank owns the block\n            if (owner_ii == jj){\n                // Add it to the group\n                group_ranks[kk] = jj;\n                kk = kk+1;\n                group_owner = jj;\n            }\n            else{\n                int* schedule_jj = ten->schedule[jj];\n                int stream_jj = schedule_jj[stream_step];\n                if (stream_jj != -1){\n                    flattening_info_update(fi_tmp, ten, schedule_jj[stream_step]);\n                    // Else, if the rank just calculated something that adds to the block\n                    if (ii == fi_tmp->f_v_block){\n                        // Add it to the group\n                        group_ranks[kk] = jj;\n                        kk = kk+1;\n                    }\n                }\n            }\n        }\n\n\n        if (world_rank == owner_ii){\n            matrix_tt* comm_matrix = holders[1];\n            own_submatrix_update(comm_matrix, s, ii, 1);\n            matrix_tt* buf_mat = holders[2];\n            matrix_tt_wrap_update(buf_mat, comm_matrix->m, comm_matrix->n, s->recv_buf);\n\n            matrix_tt_group_reduce(ten->comm, world_rank, comm_matrix, buf_mat, owner_ii, group_ranks, kk);\n        }\n        else if (sketch_mat->X){\n            matrix_tt* buf_mat = holders[2];\n            matrix_tt_wrap_update(buf_mat, sketch_mat->m, sketch_mat->n, s->recv_buf);\n            matrix_tt_group_reduce(ten->comm, world_rank,sketch_mat, buf_mat, owner_ii, group_ranks, kk);\n        }\n\n    }\n}\n\n\nvoid multi_perform_sketch(sketch** sketches, int n_sketch)\n{\n    int n_holders = 3;\n    matrix_tt** holders = (matrix_tt**) malloc(n_holders*n_sketch*sizeof(matrix_tt*));\n    for (int ii = 0; ii < n_holders*n_sketch; ++ii){\n        holders[ii] = (matrix_tt*) calloc(1, sizeof(matrix_tt));\n    }\n\n    MPI_tensor* ten = sketches[0]->ten; // Tensor\n    int rank = ten->rank;\n    int* schedule_rank = ten->schedule[rank];\n\n    flattening_info** fis = (flattening_info**) calloc(n_sketch, sizeof(flattening_info*));\n    for (int ii = 0; ii < n_sketch; ++ii){\n        fis[ii] = flattening_info_init(ten, sketches[ii]->flattening, sketches[ii]->iscol, 0);\n    }\n\n\n\n    for (int ii = 0; ii < ten->n_schedule; ++ii){\n        stream(ten, schedule_rank[ii]);\n        for (int jj = 0; jj < n_sketch; ++jj){\n            matrix_tt** holders_jj = holders + jj*n_holders;\n            flattening_info_update(fis[jj], ten, ten->current_part);\n            holders_jj[0]->X = NULL;\n            subtensor_sketch_multiply(sketches[jj], fis[jj], holders_jj);\n        }\n\n        for (int jj = 0; jj < n_sketch; ++jj){\n            matrix_tt** holders_jj = holders + jj*n_holders;\n            subtensor_sketch_communicate(sketches[jj], ii, fis[jj], holders_jj);\n        }\n    }\n\n    for (int ii = 0; ii < n_holders*n_sketch; ++ii){\n        free(holders[ii]); holders[ii] = NULL;\n    }\n\n    for (int ii = 0; ii < n_sketch; ++ii){\n        flattening_info_free(fis[ii]); fis[ii] = NULL;\n    }\n    free(fis); fis = NULL;\n    free(holders); holders = NULL;\n}\n\nvoid sketch_qr(sketch* sketch)\n{\n\n    MPI_tensor* ten = sketch->ten;\n    int* owner_partition = sketch->owner_partition;\n    int flattening = sketch->flattening;\n    int iscol = sketch->iscol;\n    int r = sketch->r;\n    int buf = sketch->buf;\n\n    MPI_Comm comm = ten->comm;\n    int size = ten->comm_size;\n    int rank = ten->rank;\n\n    // A little pre-processing\n    int head = 0;\n    flattening_info* fi = flattening_info_init(ten, flattening, iscol, 0);\n    int* Ns = (int*) calloc(size, sizeof(int));\n\n    for (int ii = 0; ii < size; ++ii){\n        for (int jj = owner_partition[ii]; jj < owner_partition[ii+1]; ++jj){\n            flattening_info_f_update(fi, ten, jj);\n            Ns[ii] = Ns[ii] + fi->f_N;\n        }\n    }\n\n    int N_rank = Ns[rank];\n    int lda = sketch->lda;\n    matrix_tt* Q_big = matrix_tt_wrap(lda, r+buf, sketch->X);\n    matrix_tt* Q = submatrix(Q_big, 0, N_rank, 0, r+buf);\n    matrix_tt* Q_head = NULL;\n    matrix_tt* R = NULL;\n\n    if (rank == head){\n        Q_head = matrix_tt_init(size * (r+buf), r+buf);\n        R = submatrix(Q_head, 0, r+buf, 0, r+buf);\n    }\n    else{\n        R = matrix_tt_init(r+buf, r+buf);\n    }\n\n    matrix_tt_truncated_qr(Q, R, r+buf);\n\n\n\n    // Gather the Rs\n    for (int jj = 0; jj < r+buf; ++jj){\n//        printf(\"r%d jj%d\\n\", rank, jj);\n        if (rank == head){\n            double* col = Q_head->X + jj*(Q_head->lda);\n            MPI_Gather(col, r+buf, MPI_DOUBLE, col, r+buf, MPI_DOUBLE, head, comm);\n        }\n        else{\n            MPI_Gather(R->X + jj*(R->lda), r+buf, MPI_DOUBLE, NULL, r+buf, MPI_DOUBLE, head, comm);\n        }\n    }\n\n    // Take the QR of the Rs\n    if (rank == head){\n        matrix_tt_truncated_qr(Q_head, NULL, r+buf);\n    }\n\n    // Scatter the Q of the preceding step\n    for (int jj = 0; jj < r+buf; ++jj){\n        if (rank == head){\n            double* col = Q_head->X + jj*(Q_head->lda);\n            MPI_Scatter(col, r+buf, MPI_DOUBLE, col, r+buf, MPI_DOUBLE, head, comm);\n        }\n        else{\n            MPI_Scatter(NULL, r+buf, MPI_DOUBLE, R->X + jj*(R->lda), r+buf, MPI_DOUBLE, head, comm);\n        }\n    }\n\n    // Multiply to get the final Q\n    matrix_tt* X_big = matrix_tt_wrap(lda, r, sketch->scratch);\n    matrix_tt* new_X = submatrix(X_big, 0, N_rank, 0, r);\n    matrix_tt* Q_head_sub = submatrix(R, 0, r+buf, 0, r);\n    matrix_tt_dgemm(Q, Q_head_sub, new_X, 1.0, 0.0);\n\n    // Switch so the QR lives in X\n    double* tmp = sketch->scratch;\n    sketch->scratch = sketch->X;\n    sketch->X = tmp;\n\n    free(X_big);              X_big = NULL;\n    free(new_X);              new_X = NULL;\n    free(Q_head_sub);         Q_head_sub = NULL;\n    flattening_info_free(fi); fi = NULL;\n    free(Ns);                 Ns = NULL;\n    free(Q_big);              Q_big = NULL;\n    free(Q);                  Q = NULL;\n    if (rank == head){\n        matrix_tt_free(Q_head); Q_head = NULL;\n        free(R);             R = NULL;\n    }\n    else{\n        matrix_tt_free(R); R = NULL;\n    }\n}\n\nvoid perform_sketch(sketch* s)\n{\n    multi_perform_sketch(&s, 1);\n}\n\n// Gets the sketch block from the correct owner (stored in fi->f_v_block). Returns a matrix with the correct dimensions\nvoid sendrecv_sketch_block(matrix_tt* mat, sketch* s, flattening_info* fi, int recv_rank, int with_buf)\n{\n    int f_v_block = fi->f_v_block;\n\n\n    MPI_tensor* ten = s->ten;\n    int rank = ten->rank;\n    MPI_Comm comm = ten->comm;\n\n    int owner = s_get_owner(s, f_v_block);\n    int r = (with_buf) ? s->r + s->buf : s->r;\n\n    if (rank == recv_rank){\n        if (rank == owner){\n            own_submatrix_update(mat, s, f_v_block, with_buf);\n        }\n        else{\n            matrix_tt_wrap_update(mat, fi->f_N, r, s->scratch);\n            matrix_tt_recv(comm, mat, owner);\n        }\n    }\n    else{\n        if(rank == owner){\n            own_submatrix_update(mat, s, f_v_block, with_buf);\n            matrix_tt_send(comm, mat, recv_rank);\n        }\n        mat->X = NULL;\n    }\n}\n\n// Eats s, so be careful!\nMPI_tensor* sketch_to_tensor(sketch** s_ptr)\n{\n    sketch* s = *s_ptr;\n\n    MPI_tensor* sten = (MPI_tensor*) malloc(sizeof(MPI_tensor));\n    MPI_tensor* ten = s->ten;\n    int rank = ten->rank;\n    int size = ten->comm_size;\n\n    flattening_info* fi = flattening_info_init(ten, s->flattening, s->iscol, 0);\n\n    // Get the schedule from the owner_partition\n    int n_schedule = 0;\n    int* owners = s->owner_partition;\n    for (int ii = 0; ii < size; ++ii){\n        int sz = owners[ii+1] - owners[ii];\n        n_schedule = (n_schedule > sz) ? n_schedule : sz;\n    }\n\n    int** schedule = (int**) malloc(size * sizeof(int*));\n    int* inverse_schedule = (int*) malloc(fi->f_Nblocks * sizeof(int));\n    for (int ii = 0; ii < size; ++ii){\n        schedule[ii] = (int*) malloc(n_schedule * sizeof(int));\n\n        int* schedule_ii = schedule[ii];\n        int jj0 = owners[ii];\n        int sz = owners[ii+1] - jj0;\n        for (int jj = 0; jj < n_schedule; ++jj){\n            if (jj < sz){\n                schedule_ii[jj] = jj+jj0;\n                inverse_schedule[jj+jj0] = ii*n_schedule + jj;\n            }\n            else{\n                schedule_ii[jj] = -1;\n            }\n        }\n    }\n\n    int d = fi->f_d + 1;\n    int soffset = (s->iscol) ? 0 : 1;\n    int offset = (s->iscol) ? 0 : s->flattening;\n    int end_ind = (s->iscol) ? d-1 : 0;\n\n    // Inherit the properties of ten\n    int* n = (int*) malloc(d * sizeof(int));\n    int* nps = (int*) malloc(d * sizeof(int));\n    int** partitions = (int**) malloc(d * sizeof(int*));\n    for (int ii = 0; ii < d-1; ++ii){\n        n[ii + soffset] = ten->n[ii + offset];\n        nps[ii + soffset] = ten->nps[ii + offset];\n        partitions[ii + soffset] = (int*) malloc( (nps[ii+soffset] + 1) * sizeof(int));\n\n        int* spartition_ii = partitions[ii+soffset];\n        int* partition_ii = ten->partitions[ii+offset];\n        for (int jj = 0; jj < nps[ii+soffset] + 1; ++jj){\n            spartition_ii[jj] = partition_ii[jj];\n        }\n    }\n    // Set the special sketched dimension properties\n    n[end_ind] = s->r;\n    nps[end_ind] = 1;\n    partitions[end_ind] = (int*) malloc( (nps[end_ind] + 1) * sizeof(int));\n    int* spartition_end = partitions[end_ind];\n    spartition_end[0] = 0; spartition_end[1] = n[end_ind];\n\n\n    // Get the parameters giving the subtensor locations\n    double** subtensors = (double**) malloc(n_schedule * sizeof(double*));\n    int* schedule_rank = schedule[rank];\n    int with_buf = 0;\n    long scratch_offset = 0;\n    for (int ii = 0; ii < n_schedule; ++ii){\n        if (schedule_rank[ii] != -1){\n            matrix_tt* X_submat = own_submatrix(s, schedule_rank[ii], with_buf);\n            subtensors[ii] = s->scratch + scratch_offset;\n            matrix_tt* scratch_submat = matrix_tt_wrap(X_submat->m, X_submat->n, subtensors[ii]);\n            matrix_tt_copy_data(scratch_submat, X_submat);\n            scratch_offset = scratch_offset + X_submat->n * X_submat->m;\n            free(X_submat);\n            free(scratch_submat);\n        }\n    }\n    void* parameters = p_static_init(subtensors);\n\n    // Assigning fields\n    sten->d = d;\n    sten->n = n;\n\n    sten->comm = ten->comm;\n    sten->rank = ten->rank;\n    sten->comm_size = ten->comm_size;\n\n    sten->schedule = schedule;\n    sten->n_schedule = n_schedule;\n    sten->inverse_schedule = inverse_schedule;\n\n    sten->partitions = partitions;\n    sten->nps = nps;\n\n    sten->current_part = -1;\n\n    sten->f_ten = NULL;\n    sten->parameters = parameters;\n\n    sten->X_size = s->X_size;\n    sten->X = s->scratch;\n\n    sten->ind1 = (int*) malloc(d * sizeof(int));\n    sten->ind2 = (int*) malloc(d * sizeof(int));\n    sten->tensor_part = (int*) malloc(d * sizeof(int));\n    sten->group_ranks = (int*) malloc(ten->comm_size * sizeof(int));\n    sten->t_kk = (int*) malloc(d * sizeof(int));\n\n    // Freeing sketch things\n    int n_Omega = s->iscol ? ten->d - s->flattening : s->flattening;\n    for (int ii = 0; ii < n_Omega; ++ii){\n        matrix_tt_free(s->Omegas[ii]); s->Omegas[ii] = NULL;\n    }\n    for (int ii = 0; ii < 4; ++ii){\n        matrix_tt_free(s->KRs[ii]); s->KRs[ii] = NULL;\n    }\n    free(s->KRs); s->KRs = NULL;\n    s->ten = NULL;\n    free(s->owner_partition); s->owner_partition = NULL;\n    free(s->X);               s->X = NULL;\n    free(s->Omegas);          s->Omegas = NULL;\n    free(s->recv_buf);        s->recv_buf = NULL;\n    flattening_info_free(s->fi); s->fi = NULL;\n    free(s);                  *s_ptr = NULL;\n\n\n    flattening_info_free(fi);\n\n    return sten;\n}", "meta": {"hexsha": "f839fadf2b29677c37488abe76ddcb5c097db805", "size": 37971, "ext": "c", "lang": "C", "max_stars_repo_path": "src/sketch.c", "max_stars_repo_name": "SidShi/Parallel_TT_sketching", "max_stars_repo_head_hexsha": "e2c00c289d75d3ac1df32ed2b95af579a517fcbf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/sketch.c", "max_issues_repo_name": "SidShi/Parallel_TT_sketching", "max_issues_repo_head_hexsha": "e2c00c289d75d3ac1df32ed2b95af579a517fcbf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sketch.c", "max_forks_repo_name": "SidShi/Parallel_TT_sketching", "max_forks_repo_head_hexsha": "e2c00c289d75d3ac1df32ed2b95af579a517fcbf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1493027071, "max_line_length": 121, "alphanum_fraction": 0.554265097, "num_tokens": 12193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814648038985, "lm_q2_score": 0.021948251635672697, "lm_q1q2_score": 0.009525134394733799}}
{"text": "\n/*\n* -----------------------------------------------------------------\n*  isat_lib.c\n*  In Situ Adaptive Tabulation Library\n*  Version: 2.0\n*  Last Update: Nov 3, 2019\n*  \n*  Programmer: Americo Barbosa da Cunha Junior\n*              americo.cunhajr@gmail.com\n* -----------------------------------------------------------------\n*  Copyright (c) 2010-2019, Americo Barbosa da Cunha Junior\n*  All rights reserved.\n* -----------------------------------------------------------------\n*  This is the implementation file for ISAT_LIB module, a \n*  computational library with In Situ Adaptive Tabulation (ISAT) \n*  algorithm routines.\n* -----------------------------------------------------------------\n*/\n\n\n\n\n#include <stdlib.h>\n#include <math.h>\n#include <time.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_errno.h>\n\n#include \"../include/thrm_lib.h\"\n#include \"../include/ell_lib.h\"\n#include \"../include/ode_lib.h\"\n#include \"../include/isat_lib.h\"\n\n\n\n\n/*\n*------------------------------------------------------------\n*   isat_alloc\n*\n*   This function alocates memory for an ISAT workspace\n*   structure and initialize its elements.\n*\n*   Output:\n*   isat_mem - pointer to ISAT workspace\n*\n*   last update: Oct 9, 2019\n*------------------------------------------------------------\n*/\n\nisat_wrk *isat_alloc()\n{\n    /* create ISAT workspace */\n    isat_wrk *isat_mem = NULL;\n\n    /* memory allocation for ISAT workspace */\n    isat_mem = (isat_wrk *) malloc(sizeof(isat_wrk));\n    if ( isat_mem == NULL )\n        return NULL;\n    \n    /* initialize ISAT workspace elements */\n    isat_mem->root      = NULL;\n    isat_mem->lf        = 0;\n    isat_mem->nd        = 0;\n    isat_mem->add       = 0;\n    isat_mem->grw       = 0;\n    isat_mem->rtv       = 0;\n    isat_mem->dev       = 0;\n    isat_mem->hgt       = 0;\n    isat_mem->maxleaves = 0;\n    isat_mem->time_add  = 0.0;\n    isat_mem->time_grw  = 0.0;\n    isat_mem->time_rtv  = 0.0;\n    isat_mem->time_dev  = 0.0;\n    \n    return isat_mem;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*\n*------------------------------------------------------------\n*   isat_free\n*\n*   This function release the memory used by ISAT workspace.\n*\n*   Input:\n*   isat_bl - pointer to ISAT workspace\n*\n*   last update: Oct 9, 2019\n*------------------------------------------------------------\n*/\n\nvoid isat_free(void **isat_bl)\n{\n    /* create ISAT workspace */\n    isat_wrk *isat_mem = NULL;\n    \n    /* check if ISAT workspace memory block is NULL */\n    if ( *isat_bl == NULL )\n        return;\n    \n    isat_mem = (isat_wrk *) (*isat_bl);\n    \n    /* release the memory allocated for ISAT workspace elements */\n    if( isat_mem->root != NULL )\n    {\n        bst_node_free((void **)&(isat_mem->root));\n        isat_mem->root = NULL;\n    }\n    \n    /* release the memory allocated for ISAT workspace */\n    free(*isat_bl);\n    *isat_bl = NULL;\n    \n    return;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*\n*------------------------------------------------------------\n*   isat_bst_init\n*\n*   This function initiates ISAT binary search tree.\n*\n*   Input:\n*   isat_mem - pointer to ISAT workspace\n*\n*   last update: Oct 9, 2019\n*------------------------------------------------------------\n*/\n\nint isat_bst_init(isat_wrk *isat_mem)\n{\n    /* check if ISAT workspece is allocated */\n    if ( isat_mem == NULL )\n        return GSL_EINVAL;\n    \n    /* memory allocation for ISAT binary search tree root */\n    if ( isat_mem->root == NULL )\n    {\n        isat_mem->root = bst_node_alloc();\n        if ( isat_mem->root == NULL )\n        {\n            free(isat_mem);\n            isat_mem = NULL;\n            return GSL_EINVAL;\n        }\n    }\n    \n    return GSL_SUCCESS;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*\n*------------------------------------------------------------\n*   isat_statistics\n*\n*   This function prints on screen ISAT workspace\n*   statistics of usage.\n*\n*   Input:\n*   isat_mem - pointer to ISAT workspace\n*\n*   last update: Oct 1, 2019\n*------------------------------------------------------------\n*/\n\nvoid isat_statistics(isat_wrk *isat_mem)\n{\n    double time_add;\n    double time_grw;\n    double time_rtv;\n    double time_dev;\n    \n    time_add = (double) (isat_mem->time_add / CLOCKS_PER_SEC) / isat_mem->add;\n    time_grw = (double) (isat_mem->time_grw / CLOCKS_PER_SEC) / isat_mem->grw;\n    time_rtv = (double) (isat_mem->time_rtv / CLOCKS_PER_SEC) / isat_mem->rtv;\n    time_dev = (double) (isat_mem->time_dev / CLOCKS_PER_SEC) / isat_mem->dev;\n    \n    printf(\"\\n ISAT statistics:\");\n    printf(\"\\n # of adds         = %d\",   isat_mem->add);\n    printf(\"\\n # of grows        = %d\",   isat_mem->grw);\n    printf(\"\\n # of retrieves    = %d\",   isat_mem->rtv);\n    printf(\"\\n # of dir. eval.   = %d\",   isat_mem->dev);\n    printf(\"\\n # of leaves       = %d\",   isat_mem->lf);\n    printf(\"\\n # of nodes        = %d\",   isat_mem->nd);\n    printf(\"\\n tree height       = %d\\n\", isat_mem->hgt);\n    \n    printf(\"\\n average values for CPU time (s):\");\n    printf(\"\\n add: %+.6e\",time_add);\n    printf(\"\\n grw: %+.6e\",time_grw);\n    printf(\"\\n rtv: %+.6e\",time_rtv);\n    printf(\"\\n dev: %+.6e\",time_dev);\n    \n    return;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*\n* -----------------------------------------------------------------\n*   isat_input\n*\n*   This function receives ISAT input parameters from the user.\n*\n*   Input:\n*   maxleaves - maximum number of ISAT tree leaves\n*   etol      - ISAT error tolerance\n*\n*   Output:\n*   success or error\n*\n*   last update: Nov 3, 2019\n* -----------------------------------------------------------------\n*/\n\nint isat_input(unsigned int *maxleaves,double *etol)\n{\n    printf(\"\\n Input ISAT parameters:\\n\");\n    \n    printf(\"\\n maximum of tree leaves:\");\n    scanf(\"%d\", maxleaves);\n    printf(\"\\n %d\\n\", *maxleaves);\n    if( *maxleaves <= 0 )\n\tGSL_ERROR(\" maxleaves must be a positive integer\",GSL_EINVAL);\n\n    printf(\"\\n ISAT error tolerance:\");\n    scanf(\"%lf\", etol);\n    printf(\"\\n %+.1e\\n\", *etol);\n    if( *etol < 0.0 )\n\tGSL_ERROR(\" etol must be grather than zero\",GSL_EINVAL);\n    \n    return GSL_SUCCESS;\n}\n/*----------------------------------------------------------------*/\n\n\n\n\n/*\n*------------------------------------------------------------\n*   isat_eoa_matrix\n*\n*   This function computes the EOA matrix in Cholesky form.\n*   \n*   Input:\n*   A    - gradient matrix\n*   etol - error tolerance\n*\n*   Output:\n*   L    - EOA Cholesky matrix\n*\n*   last update: Oct 9, 2019\n*------------------------------------------------------------\n*/\n\nvoid isat_eoa_mtrx(gsl_matrix *A,\n                   double etol,\n                   gsl_matrix *L)\n{\n    unsigned int i;\n    double  eps_max   = 0.5;\n    gsl_matrix *Aetol = NULL;\n    gsl_matrix *V     = NULL;\n    gsl_vector *sigma = NULL;\n\n    /* memory allocation */\n    Aetol = gsl_matrix_calloc(A->size2,A->size2);\n    V     = gsl_matrix_calloc(A->size2,A->size2);\n    sigma = gsl_vector_calloc(A->size2);\n    \n    /* Aetol := A */\n    gsl_matrix_memcpy(Aetol,A);\n    \n    /* Aetol := (1/etol).A */\n    gsl_matrix_scale (Aetol,1.0/etol);\n\n    /* Aetol = U*sigma*V^T */\n    ell_psd2eig(Aetol,V,sigma);\n\n    /* eliminate small and large singular values */\n    for ( i = 0; i < sigma->size; i++ )\n        sigma->data[i] = GSL_MAX(sigma->data[i],eps_max);\n    \n    /* V*sigma^2*V^T = L*L^T */\n    ell_eig2chol(V,sigma,L);\n    \n    /* release allocated memory */\n    gsl_vector_free(sigma);\n    gsl_matrix_free(V);\n    gsl_matrix_free(Aetol);\n    sigma = NULL;\n    V     = NULL;\n    Aetol = NULL;\n    \n    return;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*\n*------------------------------------------------------------\n*   isat_lerror\n*\n*   This function computes the local error defined as\n*\n*   eps = ||Rl(phi)- R(phi)||_2 where\n*\n*   Rl(phi) = R(phi0) + A*(phi-phi0).\n*\n*   Input:\n*   Rphi  - reaction mapping of phi\n*   Rphi0 - reaction mapping of phi0\n*   A     - mapping gradient matrix\n*   phi   - query composition\n*   phi0  - initial composition\n*\n*   Output:\n*   eps   - local error\n*\n*   last update: Feb 19, 2010\n*------------------------------------------------------------\n*/\n\ndouble isat_lerror(gsl_vector *Rphi,\n                   gsl_vector *Rphi0,\n                   gsl_matrix *A,\n                   gsl_vector *phi,\n                   gsl_vector *phi0)\n{\n    double eps;\n    gsl_vector *Rlphi = NULL;\n    \n    /* memory allocation for Rlphi */\n    Rlphi = gsl_vector_calloc(phi->size);\n    \n    /* Rlphi := R(phi0) + A*(phi-phi0) */\n    linear_approx(phi,phi0,Rphi0,A,Rlphi);\n    \n    /* Rlphi := Rl(phi) - R(phi) */\n    gsl_vector_sub(Rlphi,Rphi);\n    \n    /* eps := 2-norm(Rl(phi) - R(phi)) */\n    eps = gsl_blas_dnrm2(Rlphi);\n    \n    /* releasing allocated memory */\n    gsl_vector_free(Rlphi);\n    Rlphi = NULL;\n    \n    return eps;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*\n*------------------------------------------------------------\n*   isat4\n*\n*   This function executes the 4-th version of the\n*   In Situ Adaptive Tabulation (ISAT) algorithm.\n*\n*   \n*   Input:\n*   isat_mem  - ISAT workspace\n*   cvode_mem - ODE solver workspace\n*   etol      - error tolerance\n*   t0        - initial time\n*   delta_t   - time step\n*   phi       - query composition\n*   A         - mapping gradient matrix\n*   L         - EOA Cholesky matrix\n*\n*   Output:\n*   Rphi      - reaction mapping\n*   success or error\n*\n*   last update: Nov 3, 2019\n*------------------------------------------------------------\n*/\n\nint isat4(isat_wrk *isat_mem,\n          void *cvode_mem,\n          double etol,\n          double t0,\n          double delta_t,\n          gsl_vector *phi,\n          gsl_matrix *A,\n          gsl_matrix *L,\n          gsl_vector *Rphi)\n{\n\n    /* CPU clock start counter */\n    clock_t cpu_start = clock();\n\n    int flag;\n    unsigned int bst_side;\n    bst_leaf *end_leaf     = NULL;\n    bst_node *end_node     = NULL;\n    \n    /****** First call for ISAT algorithm ******/\n\n    /* check if there is no leaf in the binary search tree */\n    if( isat_mem->lf == 0 )\n    {\n        int flag;\n        bst_leaf *first_leaf = NULL;\n\t\n\t/* memory allocation for BST first leaf */\n        first_leaf = bst_leaf_alloc();\n\tif ( first_leaf == NULL )\n                return GSL_ENOMEM;\n        \n        /* direct integration */\n        flag = odesolver_reinit(t0,phi,cvode_mem);\n        if ( flag != GSL_SUCCESS )\n            return flag;\n        \n        flag = odesolver(cvode_mem,\n                         delta_t,\n                         Rphi);\n        if ( flag != GSL_SUCCESS )\n            return flag;\n        \n        /* compute the mapping gradient matrix */\n        flag = gradient(cvode_mem,t0,delta_t,phi,Rphi,A);\n        if ( flag != GSL_SUCCESS )\n            return flag;\n        \n        /* compute EOA Cholesky matrix */\n        isat_eoa_mtrx(A,etol,L);\n        \n        /* define first leaf elements */\n        bst_leaf_set(phi,Rphi,A,L,first_leaf);\n        isat_mem->root->r_leaf = first_leaf;\n        \n        /* update ISAT workspace counters */\n        isat_mem->lf++;\n        isat_mem->hgt = bst_height(isat_mem->root);\n        \n        return GSL_SUCCESS;\n    }\n    \n    \n    /****** Further calls for ISAT algorithm ******/  \n    \n    /* search for the near composition in binary search tree */\n    if( isat_mem->lf > 1 )\n\tbst_side = bst_search(isat_mem->root,\n                              phi,\n                              &end_node,\n                              &end_leaf);\n    else\n    {\n        end_node = isat_mem->root;\n        end_leaf = isat_mem->root->r_leaf;\n        bst_side = BST_RIGHT;\n    }\n    \n    /* check if the near composition is inside the ellipsoid */\n    flag = ell_pt_in(phi,end_leaf->phi,end_leaf->L);\n    if( flag == ELL_TRUE )\n    {\n        /* compute the linear approximation */\n        linear_approx(phi,end_leaf->phi,end_leaf->Rphi,end_leaf->A,Rphi);\n        \n        /* update ISAT workspace counters */\n        isat_mem->rtv++;\n\t    isat_mem->time_rtv += clock() - cpu_start;\n        \n        return GSL_SUCCESS;\n    }\n    else\n    {\n        double lerror = 0.0;\n\t\n        /* performe direct integration */\n        flag = odesolver_reinit(t0,phi,cvode_mem);\n        if ( flag != GSL_SUCCESS )\n            return flag;\n        \n        flag = odesolver(cvode_mem,delta_t,Rphi);\n        if ( flag != GSL_SUCCESS )\n            return flag;\n        \n        /* compute ISAT local error */\n        lerror = isat_lerror(Rphi,end_leaf->Rphi,\n                             end_leaf->A,phi,end_leaf->phi);\n        \n        /* check if the local error is greater than etol */\n        if( lerror < etol )\n        {\n            /* grow the ellipsoid */\n            ell_pt_modify(phi,end_leaf->phi,end_leaf->L);\n            \n            /* update ISAT workspace counters */\n            isat_mem->grw++;\n\t        isat_mem->time_grw += clock() - cpu_start;\n            \n            return GSL_SUCCESS;\n        }\n        else\n        {\n\t    /* check if the maximum number of leaves is excced */\n\t    if( isat_mem->lf > isat_mem->maxleaves )\n\t    {\n\t        /*  update ISAT workspace counters */\n\t        isat_mem->dev++;\n\t\t    isat_mem->time_dev +=  clock() - cpu_start;\n\t\t    return GSL_SUCCESS;\n\t    }\n\t    \n            bst_leaf *new_leaf = NULL;\n            \n\t    /* memory allocation */\n            new_leaf = bst_leaf_alloc();\n            if ( new_leaf == NULL )\n                return GSL_ENOMEM;\n            \n            /* compute the mapping gradient matrix */\n            flag = gradient(cvode_mem,t0,delta_t,phi,Rphi,A);\n            if ( flag != GSL_SUCCESS )\n                return flag;\n            \n            /* compute ellipsoid matrix */\n            isat_eoa_mtrx(A,etol,L);\n            \n            /* define the new leaf elements */\n            bst_leaf_set(phi,Rphi,A,L,new_leaf);\n            \n            /* check if the binary search tree has more than one leaf */\n            if( isat_mem->lf > 1 )\n            {\n                bst_node *new_node = NULL;\n\t\t\n\t\t        /* memory allocation for the new node */\n                new_node = bst_node_alloc();\n                if ( new_node == NULL )\n                    return GSL_ENOMEM;\n                \n\t\t        /* define the new node leaves */\n                bst_node_set(end_leaf,new_leaf,new_node);\n\t\t\n\t\t        /* add the new node to the binary search tree */\n                bst_node_add(bst_side,end_node,new_node);\n            }\n\t        else\n                bst_node_set(end_leaf,new_leaf,end_node);\n            \n            /* update ISAT workspace counters */\n            isat_mem->add++;\n            isat_mem->lf++;\n            isat_mem->nd++;\n            isat_mem->hgt = bst_height(isat_mem->root);\n\t        isat_mem->time_add += clock() - cpu_start;\n            \n            return GSL_SUCCESS;\n        }\n    }\n}\n/*------------------------------------------------------------*/\n", "meta": {"hexsha": "7114e18da121f5a8e494e7c54eeadcb0df60f4e6", "size": 15022, "ext": "c", "lang": "C", "max_stars_repo_path": "CRFlowLib-2.0/src/isat_lib.c", "max_stars_repo_name": "americocunhajr/CRFlowLib", "max_stars_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-29T12:56:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-29T12:56:14.000Z", "max_issues_repo_path": "CRFlowLib-2.0/src/isat_lib.c", "max_issues_repo_name": "americocunhajr/CRFlowLib", "max_issues_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CRFlowLib-2.0/src/isat_lib.c", "max_forks_repo_name": "americocunhajr/CRFlowLib", "max_forks_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-15T03:57:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-30T01:44:13.000Z", "avg_line_length": 26.0346620451, "max_line_length": 78, "alphanum_fraction": 0.4840900013, "num_tokens": 3742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.27512972382317524, "lm_q2_score": 0.034618834979657495, "lm_q1q2_score": 0.009524670507033246}}
{"text": "#pragma once\n\n#include <algorithm>\n#include <array>\n#include <cstdint>\n#include <initializer_list>\n#include <iterator>\n#include <sstream>\n#include <string>\n#include <tuple>\n\n#include <gsl/gsl>\n\n#include \"chainerx/axes.h\"\n#include \"chainerx/constant.h\"\n#include \"chainerx/dtype.h\"\n#include \"chainerx/error.h\"\n#include \"chainerx/macro.h\"\n#include \"chainerx/shape.h\"\n\nnamespace chainerx {\n\nclass Strides : public Dims {\n    using BaseVector = Dims;\n\npublic:\n    using const_iterator = BaseVector::const_iterator;\n    using const_reverse_iterator = BaseVector::const_reverse_iterator;\n\n    Strides() = default;\n\n    ~Strides() = default;\n\n    // Creates strides for contiguous array.\n    Strides(const Shape& shape, Dtype dtype) : Strides{shape, GetItemSize(dtype)} {}\n    Strides(const Shape& shape, int64_t item_size);\n\n    // by iterators\n    template <typename InputIt>\n    Strides(InputIt first, InputIt last) {\n        if (std::distance(first, last) > kMaxNdim) {\n            throw DimensionError{\"too many dimensions: \", std::distance(first, last)};\n        }\n        insert(begin(), first, last);\n    }\n\n    // by gsl:span\n    explicit Strides(gsl::span<const int64_t> dims) : Strides{dims.begin(), dims.end()} {}\n\n    // by initializer list\n    Strides(std::initializer_list<int64_t> dims) : Strides{dims.begin(), dims.end()} {}\n\n    // copy\n    Strides(const Strides&) = default;\n    Strides& operator=(const Strides&) = default;\n\n    // move\n    Strides(Strides&&) = default;\n    Strides& operator=(Strides&&) = default;\n\n    std::string ToString() const;\n\n    int8_t ndim() const noexcept { return gsl::narrow_cast<int8_t>(size()); }\n\n    const int64_t& operator[](int8_t index) const {\n        if (!(0 <= index && static_cast<size_t>(index) < size())) {\n            throw DimensionError{\"Stride index \", index, \" out of bounds for strides with \", size(), \" size.\"};\n        }\n        return this->StackVector::operator[](index);\n    }\n\n    int64_t& operator[](int8_t index) {\n        if (!(0 <= index && static_cast<size_t>(index) < size())) {\n            throw DimensionError{\"Stride index \", index, \" out of bounds for strides with \", size(), \" size.\"};\n        }\n        return this->StackVector::operator[](index);\n    }\n\n    // span\n    gsl::span<const int64_t> span() const { return {*this}; }\n\n    // Rearranges strides in the order specified by the axes.\n    //\n    // The size of given axes may be fewer than the size of strides.\n    // In that case, new strides will be composed by only given axes.\n    //\n    // It is the caller's responsibility to ensure validity of permutation.\n    // If the permutation is invalid, the behavior is undefined.\n    Strides Permute(const Axes& axes) const {\n        CHAINERX_ASSERT(axes.size() <= size());\n        Strides new_strides{};\n        for (int8_t axe : axes) {\n            new_strides.emplace_back(operator[](axe));\n        }\n        return new_strides;\n    }\n};\n\nstd::ostream& operator<<(std::ostream& os, const Strides& strides);\n\nvoid CheckEqual(const Strides& lhs, const Strides& rhs);\n\n// Returns a pair of lower and upper byte offsets to store the data.\n// This forumula always holds: lower <= 0 < item_size <= upper\nstd::tuple<int64_t, int64_t> GetDataRange(const Shape& shape, const Strides& strides, size_t item_size);\n\n}  // namespace chainerx\n", "meta": {"hexsha": "04c4dc9f73f9002a70a18ab73d9da548cdb74449", "size": 3318, "ext": "h", "lang": "C", "max_stars_repo_path": "chainerx_cc/chainerx/strides.h", "max_stars_repo_name": "prabhatnagarajan/chainer", "max_stars_repo_head_hexsha": "3029bbaa587c15b3539b55ee1fd357a4149e5aed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chainerx_cc/chainerx/strides.h", "max_issues_repo_name": "prabhatnagarajan/chainer", "max_issues_repo_head_hexsha": "3029bbaa587c15b3539b55ee1fd357a4149e5aed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chainerx_cc/chainerx/strides.h", "max_forks_repo_name": "prabhatnagarajan/chainer", "max_forks_repo_head_hexsha": "3029bbaa587c15b3539b55ee1fd357a4149e5aed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7222222222, "max_line_length": 111, "alphanum_fraction": 0.6503918023, "num_tokens": 826, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23651624720889433, "lm_q2_score": 0.040237939602421106, "lm_q1q2_score": 0.00951692647018279}}
{"text": "#ifndef CIMPLE_CIMPLE_AUXILIARY_FUNCTIONS_H\n#define CIMPLE_CIMPLE_AUXILIARY_FUNCTIONS_H\n\n/**\n * @brief Macro computes number of an array.\n *\n * Remark: It is defined as a Macro so that it can be used independently of the type of the array\n * e.g. int a[2]; =>N_ELEMS(a)=2\n *      polytope b[3]; =>N_ELEMS(a)=2 (this is an array of 3 polytopes that's why it is not \"polytope*\")\n */\n#define N_ELEMS(x)  (sizeof(x) / sizeof((x)[0]))\n\n#include <stdio.h>\n#include <string.h>\n#include <pthread.h>\n#include <stddef.h>\n#include <math.h>\n#include <stdbool.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_blas.h>\n\n\n/**\n * @brief Generates random numbers with normal distribution\n * @param mu\n * @param sigma\n * @return\n */\ndouble randn (double mu,\n              double sigma);\n\n/**\n * @brief Timer simulating one time step in discrete control\n * @param arg\n * @return\n */\nvoid * timer(void * arg);\n\n/**\n * @brief Breaks infinte loop in a pthread\n * @param mtx\n * @return\n */\nint needQuit(pthread_mutex_t *mtx);\n#endif //CIMPLE_CIMPLE_AUXILIARY_FUNCTIONS_H\n", "meta": {"hexsha": "5709aa83f1dde0d888137b30e2e82fa7638b2b1a", "size": 1047, "ext": "h", "lang": "C", "max_stars_repo_path": "Interface/Cimple/cimple_auxiliary_functions.h", "max_stars_repo_name": "shaesaert/TuLiPXML", "max_stars_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-28T23:44:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-28T23:44:28.000Z", "max_issues_repo_path": "Interface/Cimple/cimple_auxiliary_functions.h", "max_issues_repo_name": "shaesaert/TuLiPXML", "max_issues_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-10-03T18:54:08.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-21T09:50:09.000Z", "max_forks_repo_path": "Interface/Cimple/cimple_auxiliary_functions.h", "max_forks_repo_name": "shaesaert/TuLiPXML", "max_forks_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-06T12:58:52.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-06T12:58:52.000Z", "avg_line_length": 22.7608695652, "max_line_length": 104, "alphanum_fraction": 0.6867239733, "num_tokens": 300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658973632215985, "lm_q2_score": 0.025957358893192575, "lm_q1q2_score": 0.009515701352275138}}
{"text": "/* matrix/gsl_matrix_long_double.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_MATRIX_LONG_DOUBLE_H__\n#define __GSL_MATRIX_LONG_DOUBLE_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_vector_long_double.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size1;\n  size_t size2;\n  size_t tda;\n  long double * data;\n  gsl_block_long_double * block;\n  int owner;\n} gsl_matrix_long_double;\n\ntypedef struct\n{\n  gsl_matrix_long_double matrix;\n} _gsl_matrix_long_double_view;\n\ntypedef _gsl_matrix_long_double_view gsl_matrix_long_double_view;\n\ntypedef struct\n{\n  gsl_matrix_long_double matrix;\n} _gsl_matrix_long_double_const_view;\n\ntypedef const _gsl_matrix_long_double_const_view gsl_matrix_long_double_const_view;\n\n/* Allocation */\n\nGSL_EXPORT\ngsl_matrix_long_double *\ngsl_matrix_long_double_alloc (const size_t n1, const size_t n2);\n\nGSL_EXPORT\ngsl_matrix_long_double *\ngsl_matrix_long_double_calloc (const size_t n1, const size_t n2);\n\nGSL_EXPORT\ngsl_matrix_long_double *\ngsl_matrix_long_double_alloc_from_block (gsl_block_long_double * b,\n                                   const size_t offset,\n                                   const size_t n1,\n                                   const size_t n2,\n                                   const size_t d2);\n\nGSL_EXPORT\ngsl_matrix_long_double *\ngsl_matrix_long_double_alloc_from_matrix (gsl_matrix_long_double * m,\n                                    const size_t k1,\n                                    const size_t k2,\n                                    const size_t n1,\n                                    const size_t n2);\n\nGSL_EXPORT\ngsl_vector_long_double *\ngsl_vector_long_double_alloc_row_from_matrix (gsl_matrix_long_double * m,\n                                        const size_t i);\n\nGSL_EXPORT\ngsl_vector_long_double *\ngsl_vector_long_double_alloc_col_from_matrix (gsl_matrix_long_double * m,\n                                        const size_t j);\n\nGSL_EXPORT void gsl_matrix_long_double_free (gsl_matrix_long_double * m);\n\n/* Views */\n\nGSL_EXPORT\n_gsl_matrix_long_double_view\ngsl_matrix_long_double_submatrix (gsl_matrix_long_double * m,\n                            const size_t i, const size_t j,\n                            const size_t n1, const size_t n2);\n\nGSL_EXPORT\n_gsl_vector_long_double_view\ngsl_matrix_long_double_row (gsl_matrix_long_double * m, const size_t i);\n\nGSL_EXPORT\n_gsl_vector_long_double_view\ngsl_matrix_long_double_column (gsl_matrix_long_double * m, const size_t j);\n\nGSL_EXPORT\n_gsl_vector_long_double_view\ngsl_matrix_long_double_diagonal (gsl_matrix_long_double * m);\n\nGSL_EXPORT\n_gsl_vector_long_double_view\ngsl_matrix_long_double_subdiagonal (gsl_matrix_long_double * m, const size_t k);\n\nGSL_EXPORT\n_gsl_vector_long_double_view\ngsl_matrix_long_double_superdiagonal (gsl_matrix_long_double * m, const size_t k);\n\nGSL_EXPORT\n_gsl_matrix_long_double_view\ngsl_matrix_long_double_view_array (long double * base,\n                             const size_t n1,\n                             const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_long_double_view\ngsl_matrix_long_double_view_array_with_tda (long double * base,\n                                      const size_t n1,\n                                      const size_t n2,\n                                      const size_t tda);\n\n\nGSL_EXPORT\n_gsl_matrix_long_double_view\ngsl_matrix_long_double_view_vector (gsl_vector_long_double * v,\n                              const size_t n1,\n                              const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_long_double_view\ngsl_matrix_long_double_view_vector_with_tda (gsl_vector_long_double * v,\n                                       const size_t n1,\n                                       const size_t n2,\n                                       const size_t tda);\n\n\nGSL_EXPORT\n_gsl_matrix_long_double_const_view\ngsl_matrix_long_double_const_submatrix (const gsl_matrix_long_double * m,\n                                  const size_t i, const size_t j,\n                                  const size_t n1, const size_t n2);\n\nGSL_EXPORT\n_gsl_vector_long_double_const_view\ngsl_matrix_long_double_const_row (const gsl_matrix_long_double * m,\n                            const size_t i);\n\nGSL_EXPORT\n_gsl_vector_long_double_const_view\ngsl_matrix_long_double_const_column (const gsl_matrix_long_double * m,\n                               const size_t j);\n\nGSL_EXPORT\n_gsl_vector_long_double_const_view\ngsl_matrix_long_double_const_diagonal (const gsl_matrix_long_double * m);\n\nGSL_EXPORT\n_gsl_vector_long_double_const_view\ngsl_matrix_long_double_const_subdiagonal (const gsl_matrix_long_double * m,\n                                    const size_t k);\n\nGSL_EXPORT\n_gsl_vector_long_double_const_view\ngsl_matrix_long_double_const_superdiagonal (const gsl_matrix_long_double * m,\n                                      const size_t k);\n\nGSL_EXPORT\n_gsl_matrix_long_double_const_view\ngsl_matrix_long_double_const_view_array (const long double * base,\n                                   const size_t n1,\n                                   const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_long_double_const_view\ngsl_matrix_long_double_const_view_array_with_tda (const long double * base,\n                                            const size_t n1,\n                                            const size_t n2,\n                                            const size_t tda);\n\nGSL_EXPORT\n_gsl_matrix_long_double_const_view\ngsl_matrix_long_double_const_view_vector (const gsl_vector_long_double * v,\n                                    const size_t n1,\n                                    const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_long_double_const_view\ngsl_matrix_long_double_const_view_vector_with_tda (const gsl_vector_long_double * v,\n                                             const size_t n1,\n                                             const size_t n2,\n                                             const size_t tda);\n\n/* Operations */\n\nGSL_EXPORT long double   gsl_matrix_long_double_get(const gsl_matrix_long_double * m, const size_t i, const size_t j);\nGSL_EXPORT void    gsl_matrix_long_double_set(gsl_matrix_long_double * m, const size_t i, const size_t j, const long double x);\n\nGSL_EXPORT long double * gsl_matrix_long_double_ptr(gsl_matrix_long_double * m, const size_t i, const size_t j);\nGSL_EXPORT const long double * gsl_matrix_long_double_const_ptr(const gsl_matrix_long_double * m, const size_t i, const size_t j);\n\nGSL_EXPORT void gsl_matrix_long_double_set_zero (gsl_matrix_long_double * m);\nGSL_EXPORT void gsl_matrix_long_double_set_identity (gsl_matrix_long_double * m);\nGSL_EXPORT void gsl_matrix_long_double_set_all (gsl_matrix_long_double * m, long double x);\n\nGSL_EXPORT int gsl_matrix_long_double_fread (FILE * stream, gsl_matrix_long_double * m) ;\nGSL_EXPORT int gsl_matrix_long_double_fwrite (FILE * stream, const gsl_matrix_long_double * m) ;\nGSL_EXPORT int gsl_matrix_long_double_fscanf (FILE * stream, gsl_matrix_long_double * m);\nGSL_EXPORT int gsl_matrix_long_double_fprintf (FILE * stream, const gsl_matrix_long_double * m, const char * format);\n\nGSL_EXPORT int gsl_matrix_long_double_memcpy(gsl_matrix_long_double * dest, const gsl_matrix_long_double * src);\nGSL_EXPORT int gsl_matrix_long_double_swap(gsl_matrix_long_double * m1, gsl_matrix_long_double * m2);\n\nGSL_EXPORT int gsl_matrix_long_double_swap_rows(gsl_matrix_long_double * m, const size_t i, const size_t j);\nGSL_EXPORT int gsl_matrix_long_double_swap_columns(gsl_matrix_long_double * m, const size_t i, const size_t j);\nGSL_EXPORT int gsl_matrix_long_double_swap_rowcol(gsl_matrix_long_double * m, const size_t i, const size_t j);\nGSL_EXPORT int gsl_matrix_long_double_transpose (gsl_matrix_long_double * m);\nGSL_EXPORT int gsl_matrix_long_double_transpose_memcpy (gsl_matrix_long_double * dest, const gsl_matrix_long_double * src);\n\nGSL_EXPORT long double gsl_matrix_long_double_max (const gsl_matrix_long_double * m);\nGSL_EXPORT long double gsl_matrix_long_double_min (const gsl_matrix_long_double * m);\nGSL_EXPORT void gsl_matrix_long_double_minmax (const gsl_matrix_long_double * m, long double * min_out, long double * max_out);\n\nGSL_EXPORT void gsl_matrix_long_double_max_index (const gsl_matrix_long_double * m, size_t * imax, size_t *jmax);\nGSL_EXPORT void gsl_matrix_long_double_min_index (const gsl_matrix_long_double * m, size_t * imin, size_t *jmin);\nGSL_EXPORT void gsl_matrix_long_double_minmax_index (const gsl_matrix_long_double * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);\n\nGSL_EXPORT int gsl_matrix_long_double_isnull (const gsl_matrix_long_double * m);\n\nGSL_EXPORT int gsl_matrix_long_double_add (gsl_matrix_long_double * a, const gsl_matrix_long_double * b);\nGSL_EXPORT int gsl_matrix_long_double_sub (gsl_matrix_long_double * a, const gsl_matrix_long_double * b);\nGSL_EXPORT int gsl_matrix_long_double_mul_elements (gsl_matrix_long_double * a, const gsl_matrix_long_double * b);\nGSL_EXPORT int gsl_matrix_long_double_div_elements (gsl_matrix_long_double * a, const gsl_matrix_long_double * b);\nGSL_EXPORT int gsl_matrix_long_double_scale (gsl_matrix_long_double * a, const double x);\nGSL_EXPORT int gsl_matrix_long_double_add_constant (gsl_matrix_long_double * a, const double x);\nGSL_EXPORT int gsl_matrix_long_double_add_diagonal (gsl_matrix_long_double * a, const double x);\n\n/***********************************************************************/\n/* The functions below are obsolete                                    */\n/***********************************************************************/\nGSL_EXPORT int gsl_matrix_long_double_get_row(gsl_vector_long_double * v, const gsl_matrix_long_double * m, const size_t i);\nGSL_EXPORT int gsl_matrix_long_double_get_col(gsl_vector_long_double * v, const gsl_matrix_long_double * m, const size_t j);\nGSL_EXPORT int gsl_matrix_long_double_set_row(gsl_matrix_long_double * m, const size_t i, const gsl_vector_long_double * v);\nGSL_EXPORT int gsl_matrix_long_double_set_col(gsl_matrix_long_double * m, const size_t j, const gsl_vector_long_double * v);\n\n/* inline functions if you are using GCC */\n\n#ifdef HAVE_INLINE\nextern inline\nlong double\ngsl_matrix_long_double_get(const gsl_matrix_long_double * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_VAL(\"first index out of range\", GSL_EINVAL, 0) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_VAL(\"second index out of range\", GSL_EINVAL, 0) ;\n    }\n#endif\n  return m->data[i * m->tda + j] ;\n}\n\nextern inline\nvoid\ngsl_matrix_long_double_set(gsl_matrix_long_double * m, const size_t i, const size_t j, const long double x)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_VOID(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_VOID(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  m->data[i * m->tda + j] = x ;\n}\n\nextern inline\nlong double *\ngsl_matrix_long_double_ptr(gsl_matrix_long_double * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  return (long double *) (m->data + (i * m->tda + j)) ;\n}\n\nextern inline\nconst long double *\ngsl_matrix_long_double_const_ptr(const gsl_matrix_long_double * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  return (const long double *) (m->data + (i * m->tda + j)) ;\n}\n\n#endif\n\n__END_DECLS\n\n#endif /* __GSL_MATRIX_LONG_DOUBLE_H__ */\n", "meta": {"hexsha": "f219ce76c61a8da15579df33d0e78297ece48cc7", "size": 12788, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/gsl/include/gsl/gsl_matrix_long_double.h", "max_stars_repo_name": "dynaryu/vaws", "max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/gsl/include/gsl/gsl_matrix_long_double.h", "max_issues_repo_name": "dynaryu/vaws", "max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/gsl/include/gsl/gsl_matrix_long_double.h", "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2827988338, "max_line_length": 147, "alphanum_fraction": 0.7081639037, "num_tokens": 2987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658975016245987, "lm_q2_score": 0.02595735625591038, "lm_q1q2_score": 0.009515700744732151}}
{"text": "/* adept_source.h - Source code for the Adept library\n\n  Copyright (C) 2012-2015 The University of Reading\n  Copyright (C) 2015-2017 European Centre for Medium-Range Weather Forecasts\n\n  Licensed under the Apache License, Version 2.0 (the \"License\"); you\n  may not use this file except in compliance with the License.  You\n  may obtain a copy of the License at\n\n      http://www.apache.org/licenses/LICENSE-2.0\n\n  Unless required by applicable law or agreed to in writing, software\n  distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n  implied.  See the License for the specific language governing\n  permissions and limitations under the License.\n\n\n  This file was created automatically by script ./create_adept_source_header \n  on Sun 28 Jan 21:05:14 GMT 2018\n\n  It contains a concatenation of the source files from the Adept\n  library. The idea is that a program may #include this file in one of\n  its source files (typically the one containing the main function),\n  and then the Adept library will be built into the executable without\n  the need to link to an external library. All other source files\n  should just #include <adept.h> or <adept_arrays.h>. The ability to\n  use Adept in this way makes it easier to distribute an Adept package\n  that is usable on non-Unix platforms that are unable to use the\n  autoconf configure script to build external libraries.\n\n  If HAVE_BLAS is defined below then matrix multiplication will be\n  enabled; the BLAS library should be provided at the link stage\n  although no header file is required.  If HAVE_LAPACK is defined\n  below then linear algebra routines will be enabled (matrix inverse\n  and solving linear systems of equations); again, the LAPACK library\n  should be provided at the link stage although no header file is\n  required.\n\n*/\n\n/* Feel free to delete this warning: */\n#ifdef _MSC_FULL_VER \n#pragma message(\"warning: the adept_source.h header file has not been edited so BLAS matrix multiplication and LAPACK linear-algebra support have been disabled\")\n#else\n#warning \"The adept_source.h header file has not been edited so BLAS matrix multiplication and LAPACK linear-algebra support have been disabled\"\n#endif\n\n/* Uncomment this if you are linking to the BLAS library (header file\n   not required) to enable matrix multiplication */\n#define HAVE_BLAS 1\n\n/* Uncomment this if you are linking to the LAPACK library (header\n   file not required) */\n//#define HAVE_LAPACK 1\n\n/* Uncomment this if you have the cblas.h header from OpenBLAS */\n//#define HAVE_OPENBLAS_CBLAS_HEADER\n\n/*\n\n  The individual source files now follow.\n\n*/\n\n#ifndef AdeptSource_H\n#define AdeptSource_H 1\n\n\n\n\n// =================================================================\n// Contents of config_platform_independent.h\n// =================================================================\n\n/* config_platform_independent.h.  Generated from config_platform_independent.h.in by configure.  */\n/* config_platform_independent.h.in. */\n\n/* Name of package */\n#define PACKAGE \"adept\"\n\n/* Define to the address where bug reports for this package should be sent. */\n#define PACKAGE_BUGREPORT \"r.j.hogan@ecmwf.int\"\n\n/* Define to the full name of this package. */\n#define PACKAGE_NAME \"adept\"\n\n/* Define to the full name and version of this package. */\n#define PACKAGE_STRING \"adept 2.0.5\"\n\n/* Define to the one symbol short name of this package. */\n#define PACKAGE_TARNAME \"adept\"\n\n/* Define to the home page for this package. */\n#define PACKAGE_URL \"http://www.met.reading.ac.uk/clouds/adept/\"\n\n/* Define to the version of this package. */\n#define PACKAGE_VERSION \"2.0.5\"\n\n/* Version number of package */\n#define VERSION \"2.0.5\"\n\n\n\n// =================================================================\n// Contents of cpplapack.h\n// =================================================================\n\n/* cpplapack.h -- C++ interface to LAPACK\n\n    Copyright (C) 2015-2016 European Centre for Medium-Range Weather Forecasts\n\n    Author: Robin Hogan <r.j.hogan@ecmwf.int>\n\n    This file is part of the Adept library.\n*/\n\n#ifndef AdeptCppLapack_H\n#define AdeptCppLapack_H 1                       \n\n#include <vector>\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#ifdef HAVE_LAPACK\n\nextern \"C\" {\n  // External LAPACK Fortran functions\n  void sgetrf_(const int* m, const int* n, float*  a, const int* lda, int* ipiv, int* info);\n  void dgetrf_(const int* m, const int* n, double* a, const int* lda, int* ipiv, int* info);\n  void sgetri_(const int* n, float* a, const int* lda, const int* ipiv, \n\t       float* work, const int* lwork, int* info);\n  void dgetri_(const int* n, double* a, const int* lda, const int* ipiv, \n\t       double* work, const int* lwork, int* info);\n  void ssytrf_(const char* uplo, const int* n, float* a, const int* lda, int* ipiv,\n\t       float* work, const int* lwork, int* info);\n  void dsytrf_(const char* uplo, const int* n, double* a, const int* lda, int* ipiv,\n\t       double* work, const int* lwork, int* info);\n  void ssytri_(const char* uplo, const int* n, float* a, const int* lda, \n\t       const int* ipiv, float* work, int* info);\n  void dsytri_(const char* uplo, const int* n, double* a, const int* lda, \n\t       const int* ipiv, double* work, int* info);\n  void ssysv_(const char* uplo, const int* n, const int* nrhs, float* a, const int* lda, \n\t      int* ipiv, float* b, const int* ldb, float* work, const int* lwork, int* info);\n  void dsysv_(const char* uplo, const int* n, const int* nrhs, double* a, const int* lda, \n\t      int* ipiv, double* b, const int* ldb, double* work, const int* lwork, int* info);\n  void sgesv_(const int* n, const int* nrhs, float* a, const int* lda, \n\t      int* ipiv, float* b, const int* ldb, int* info);\n  void dgesv_(const int* n, const int* nrhs, double* a, const int* lda, \n\t      int* ipiv, double* b, const int* ldb, int* info);\n}\n\nnamespace adept {\n\n  // Overloaded functions provide both single &\n  // double precision versions, and prevents the huge lapacke.h having\n  // to be included in all user code\n  namespace internal {\n    typedef int lapack_int;\n    // Factorize a general matrix\n    inline\n    int cpplapack_getrf(int n, float* a,  int lda, int* ipiv) {\n      int info;\n      sgetrf_(&n, &n, a, &lda, ipiv, &info);\n      return info;\n    }\n    inline\n    int cpplapack_getrf(int n, double* a, int lda, int* ipiv) {\n      int info;\n      dgetrf_(&n, &n, a, &lda, ipiv, &info);\n      return info;\n    }\n\n    // Invert a general matrix\n    inline\n    int cpplapack_getri(int n, float* a,  int lda, const int* ipiv) {\n      int info;\n      float work_query;\n      int lwork = -1;\n      // Find out how much work memory required\n      sgetri_(&n, a, &lda, ipiv, &work_query, &lwork, &info);\n      lwork = static_cast<int>(work_query);\n      std::vector<float> work(static_cast<size_t>(lwork));\n      // Do full calculation\n      sgetri_(&n, a, &lda, ipiv, &work[0], &lwork, &info);\n      return info;\n    }\n    inline\n    int cpplapack_getri(int n, double* a,  int lda, const int* ipiv) {\n      int info;\n      double work_query;\n      int lwork = -1;\n      // Find out how much work memory required\n      dgetri_(&n, a, &lda, ipiv, &work_query, &lwork, &info);\n      lwork = static_cast<int>(work_query);\n      std::vector<double> work(static_cast<size_t>(lwork));\n      // Do full calculation\n      dgetri_(&n, a, &lda, ipiv, &work[0], &lwork, &info);\n      return info;\n    }\n\n    // Factorize a symmetric matrix\n    inline\n    int cpplapack_sytrf(char uplo, int n, float* a, int lda, int* ipiv) {\n      int info;\n      float work_query;\n      int lwork = -1;\n      // Find out how much work memory required\n      ssytrf_(&uplo, &n, a, &lda, ipiv, &work_query, &lwork, &info);\n      lwork = static_cast<int>(work_query);\n      std::vector<float> work(static_cast<size_t>(lwork));\n      // Do full calculation\n      ssytrf_(&uplo, &n, a, &lda, ipiv, &work[0], &lwork, &info);\n      return info;\n    }\n    inline\n    int cpplapack_sytrf(char uplo, int n, double* a, int lda, int* ipiv) {\n      int info;\n      double work_query;\n      int lwork = -1;\n      // Find out how much work memory required\n      dsytrf_(&uplo, &n, a, &lda, ipiv, &work_query, &lwork, &info);\n      lwork = static_cast<int>(work_query);\n      std::vector<double> work(static_cast<size_t>(lwork));\n      // Do full calculation\n      dsytrf_(&uplo, &n, a, &lda, ipiv, &work[0], &lwork, &info);\n      return info;\n    }\n\n    // Invert a symmetric matrix\n    inline\n    int cpplapack_sytri(char uplo, int n, float* a, int lda, const int* ipiv) {\n      int info;\n      std::vector<float> work(n);\n      ssytri_(&uplo, &n, a, &lda, ipiv, &work[0], &info);\n      return info;\n    }\n    inline\n    int cpplapack_sytri(char uplo, int n, double* a, int lda, const int* ipiv) {\n      int info;\n      std::vector<double> work(n);\n      dsytri_(&uplo, &n, a, &lda, ipiv, &work[0], &info);\n      return info;\n    }\n\n    // Solve system of linear equations with general matrix\n    inline\n    int cpplapack_gesv(int n, int nrhs, float* a, int lda,\n\t\t       int* ipiv, float* b, int ldb) {\n      int info;\n      sgesv_(&n, &nrhs, a, &lda, ipiv, b, &lda, &info);\n      return info;\n    }\n    inline\n    int cpplapack_gesv(int n, int nrhs, double* a, int lda,\n\t\t       int* ipiv, double* b, int ldb) {\n      int info;\n      dgesv_(&n, &nrhs, a, &lda, ipiv, b, &lda, &info);\n      return info;\n    }\n\n    // Solve system of linear equations with symmetric matrix\n    inline\n    int cpplapack_sysv(char uplo, int n, int nrhs, float* a, int lda, int* ipiv,\n\t\t       float* b, int ldb) {\n      int info;\n      float work_query;\n      int lwork = -1;\n      // Find out how much work memory required\n      ssysv_(&uplo, &n, &nrhs, a, &lda, ipiv, b, &ldb, &work_query, &lwork, &info);\n      lwork = static_cast<int>(work_query);\n      std::vector<float> work(static_cast<size_t>(lwork));\n      // Do full calculation\n      ssysv_(&uplo, &n, &nrhs, a, &lda, ipiv, b, &ldb, &work[0], &lwork, &info);\n      return info;\n    }\n    inline\n    int cpplapack_sysv(char uplo, int n, int nrhs, double* a, int lda, int* ipiv,\n\t\t       double* b, int ldb) {\n      int info;\n      double work_query;\n      int lwork = -1;\n      // Find out how much work memory required\n      dsysv_(&uplo, &n, &nrhs, a, &lda, ipiv, b, &ldb, &work_query, &lwork, &info);\n      lwork = static_cast<int>(work_query);\n      std::vector<double> work(static_cast<size_t>(lwork));\n      // Do full calculation\n      dsysv_(&uplo, &n, &nrhs, a, &lda, ipiv, b, &ldb, &work[0], &lwork, &info);\n      return info;\n    }\n\n  }\n}\n\n#endif\n\n#endif\n\n\n// =================================================================\n// Contents of Array.cpp\n// =================================================================\n\n/* Array.cpp -- Functions and global variables controlling array behaviour\n\n    Copyright (C) 2015-2016 European Centre for Medium-Range Weather Forecasts\n\n    Robin Hogan <r.j.hogan@ecmwf.int>\n\n    This file is part of the Adept library.\n*/\n\n\n#include <adept/Array.h>\n\nnamespace adept {\n  namespace internal {\n    bool array_row_major_order = true;\n    //    bool array_print_curly_brackets = true;\n\n    // Variables describing how arrays are written to a stream\n    ArrayPrintStyle array_print_style = PRINT_STYLE_CURLY;\n    std::string vector_separator = \", \";\n    std::string vector_print_before = \"{\";\n    std::string vector_print_after = \"}\";\n    std::string array_opening_bracket = \"{\";\n    std::string array_closing_bracket = \"}\";\n    std::string array_contiguous_separator = \", \";\n    std::string array_non_contiguous_separator = \",\\n\";\n    std::string array_print_before = \"\\n{\";\n    std::string array_print_after = \"}\";\n    std::string array_print_empty_before = \"(empty rank-\";\n    std::string array_print_empty_after = \" array)\";\n    bool array_print_indent = true;\n    bool array_print_empty_rank = true;\n  }\n\n  void set_array_print_style(ArrayPrintStyle ps) {\n    using namespace internal;\n    switch (ps) {\n    case PRINT_STYLE_PLAIN:\n       vector_separator = \" \";\n       vector_print_before = \"\";\n       vector_print_after = \"\";\n       array_opening_bracket = \"\";\n       array_closing_bracket = \"\";\n       array_contiguous_separator = \" \";\n       array_non_contiguous_separator = \"\\n\";\n       array_print_before = \"\";\n       array_print_after = \"\";\n       array_print_empty_before = \"(empty rank-\";\n       array_print_empty_after = \" array)\";\n       array_print_indent = false;\n       array_print_empty_rank = true;\n       break;\n    case PRINT_STYLE_CSV:\n       vector_separator = \", \";\n       vector_print_before = \"\";\n       vector_print_after = \"\";\n       array_opening_bracket = \"\";\n       array_closing_bracket = \"\";\n       array_contiguous_separator = \", \";\n       array_non_contiguous_separator = \"\\n\";\n       array_print_before = \"\";\n       array_print_after = \"\";\n       array_print_empty_before = \"empty\";\n       array_print_empty_after = \"\";\n       array_print_indent = false;\n       array_print_empty_rank = false;\n       break;\n    case PRINT_STYLE_MATLAB:\n       vector_separator = \" \";\n       vector_print_before = \"[\";\n       vector_print_after = \"]\";\n       array_opening_bracket = \"\";\n       array_closing_bracket = \"\";\n       array_contiguous_separator = \" \";\n       array_non_contiguous_separator = \";\\n\";\n       array_print_before = \"[\";\n       array_print_after = \"]\";\n       array_print_empty_before = \"[\";\n       array_print_empty_after = \"]\";\n       array_print_indent = true;\n       array_print_empty_rank = false;\n       break;\n    case PRINT_STYLE_CURLY:\n       vector_separator = \", \";\n       vector_print_before = \"{\";\n       vector_print_after = \"}\";\n       array_opening_bracket = \"{\";\n       array_closing_bracket = \"}\";\n       array_contiguous_separator = \", \";\n       array_non_contiguous_separator = \",\\n\";\n       array_print_before = \"\\n{\";\n       array_print_after = \"}\";\n       array_print_empty_before = \"(empty rank-\";\n       array_print_empty_after = \" array)\";\n       array_print_indent = true;\n       array_print_empty_rank = true;\n       break;\n    default:\n      //throw invalid_operation(\"Array print style not understood\");\n      printf(\"invalid operation\\n\");\n      assert(false);\n    }\n    array_print_style = ps;\n  }\n\n}\n\n\n// =================================================================\n// Contents of Stack.cpp\n// =================================================================\n\n/* Stack.cpp -- Stack for storing automatic differentiation information\n\n     Copyright (C) 2012-2014 University of Reading\n    Copyright (C) 2015 European Centre for Medium-Range Weather Forecasts\n\n    Author: Robin Hogan <r.j.hogan@ecmwf.int>\n\n    This file is part of the Adept library.\n\n*/\n\n\n#include <iostream>\n#include <cstring> // For memcpy\n\n\n\n#ifdef _OPENMP\n#include <omp.h>\n#endif\n\n#include <adept/Stack.h>\n\n\nnamespace adept {\n\n  using namespace internal;\n\n  // Global pointers to the current thread, the second of which is\n  // thread safe. The first is only used if ADEPT_STACK_THREAD_UNSAFE\n  // is defined.\n  ADEPT_THREAD_LOCAL Stack* _stack_current_thread = 0;\n  Stack* _stack_current_thread_unsafe = 0;\n\n  // MEMBER FUNCTIONS OF THE STACK CLASS\n\n  // Destructor: frees dynamically allocated memory (if any)\n  Stack::~Stack() {\n    // If this is the currently active stack then set to NULL as\n    // \"this\" is shortly to become invalid\n    if (is_thread_unsafe_) {\n      if (_stack_current_thread_unsafe == this) {\n\t_stack_current_thread_unsafe = 0; \n      }\n    }\n    else if (_stack_current_thread == this) {\n      _stack_current_thread = 0; \n    }\n#ifndef ADEPT_STACK_STORAGE_STL\n    if (gradient_) {\n      delete[] gradient_;\n    }\n#endif\n  }\n  \n  // Make this stack \"active\" by copying its \"this\" pointer to a\n  // global variable; this makes it the stack that aReal objects\n  // subsequently interact with when being created and participating\n  // in mathematical expressions\n  void\n  Stack::activate()\n  {\n    // Check that we don't already have an active stack in this thread\n    if ((is_thread_unsafe_ && _stack_current_thread_unsafe \n\t && _stack_current_thread_unsafe != this)\n\t|| ((!is_thread_unsafe_) && _stack_current_thread\n\t    && _stack_current_thread != this)) {\n      //throw(stack_already_active());\n      printf(\"stack already active\\n\");\n      assert(false);\n    }\n    else {\n      if (!is_thread_unsafe_) {\n\t_stack_current_thread = this;\n      }\n      else {\n\t_stack_current_thread_unsafe = this;\n      }\n    }    \n  }\n\n  \n  // Set the maximum number of threads to be used in Jacobian\n  // calculations, if possible. A value of 1 indicates that OpenMP\n  // will not be used, while a value of 0 indicates that the number\n  // will match the number of available processors. Returns the\n  // maximum that will be used, which will be 1 if the Adept library\n  // was compiled without OpenMP support. Note that a value of 1 will\n  // disable the use of OpenMP with Adept, so Adept will then use no\n  // OpenMP directives or function calls. Note that if in your program\n  // you use OpenMP with each thread performing automatic\n  // differentiaion with its own independent Adept stack, then\n  // typically only one OpenMP thread is available for each Jacobian\n  // calculation, regardless of whether you call this function.\n  int\n  Stack::set_max_jacobian_threads(int n)\n  {\n#ifdef _OPENMP\n    if (have_openmp_) {\n      if (n == 1) {\n\topenmp_manually_disabled_ = true;\n\treturn 1;\n      }\n      else if (n < 1) {\n\topenmp_manually_disabled_ = false;\n\tomp_set_num_threads(omp_get_num_procs());\n\treturn omp_get_max_threads();\n      }\n      else {\n\topenmp_manually_disabled_ = false;\n\tomp_set_num_threads(n);\n\treturn omp_get_max_threads();\n      }\n    }\n#endif\n    return 1;\n  }\n\n\n  // Return maximum number of OpenMP threads to be used in Jacobian\n  // calculation\n  int \n  Stack::max_jacobian_threads() const\n  {\n#ifdef _OPENMP\n    if (have_openmp_) {\n      if (openmp_manually_disabled_) {\n\treturn 1;\n      }\n      else {\n\treturn omp_get_max_threads();\n      }\n    }\n#endif\n    return 1;\n  }\n\n\n  // Perform to adjoint computation (reverse mode). It is assumed that\n  // some gradients have been assigned already, otherwise the function\n  // returns with an error.\n  void\n  Stack::compute_adjoint()\n  {\n    if (gradients_are_initialized()) {\n      // Loop backwards through the derivative statements\n      for (uIndex ist = n_statements_-1; ist > 0; ist--) {\n\tconst Statement& statement = statement_[ist];\n\t// We copy the RHS gradient (LHS in the original derivative\n\t// statement but swapped in the adjoint equivalent) to \"a\" in\n\t// case it appears on the LHS in any of the following statements\n\tReal a = gradient_[statement.index];\n\tgradient_[statement.index] = 0.0;\n\t// By only looping if a is non-zero we gain a significant speed-up\n\tif (a != 0.0) {\n\t  // Loop over operations\n\t  for (uIndex i = statement_[ist-1].end_plus_one;\n\t       i < statement.end_plus_one; i++) {\n\t    gradient_[index_[i]] += multiplier_[i]*a;\n\t  }\n\t}\n      }\n    }  \n    else {\n      //throw(gradients_not_initialized());\n      printf(\"gradients not initialized\\n\");\n      assert(false);\n    }  \n  }\n\n\n  // Perform tangent linear computation (forward mode). It is assumed\n  // that some gradients have been assigned already, otherwise the\n  // function returns with an error.\n  void\n  Stack::compute_tangent_linear()\n  {\n    if (gradients_are_initialized()) {\n      // Loop forward through the statements\n      for (uIndex ist = 1; ist < n_statements_; ist++) {\n\tconst Statement& statement = statement_[ist];\n\t// We copy the LHS to \"a\" in case it appears on the RHS in any\n\t// of the following statements\n\tReal a = 0.0;\n\tfor (uIndex i = statement_[ist-1].end_plus_one;\n\t     i < statement.end_plus_one; i++) {\n\t  a += multiplier_[i]*gradient_[index_[i]];\n\t}\n\tgradient_[statement.index] = a;\n      }\n    }\n    else {\n      //throw(gradients_not_initialized());\n      printf(\"gradients not initialized\\n\");\n      assert(false);\n    }\n  }\n\n\n\n  // Register n gradients\n  uIndex\n  Stack::do_register_gradients(const uIndex& n) {\n    n_gradients_registered_ += n;\n    if (!gap_list_.empty()) {\n      uIndex return_val;\n      // Insert in a gap, if there is one big enough\n      for (GapListIterator it = gap_list_.begin();\n\t   it != gap_list_.end(); it++) {\n\tuIndex len = it->end + 1 - it->start;\n\tif (len > n) {\n\t  // Gap a bit larger than needed: reduce its size\n\t  return_val = it->start;\n\t  it->start += n;\n\t  return return_val;\n\t}\n\telse if (len == n) {\n\t  // Gap exactly the size needed: fill it and remove from list\n\t  return_val = it->start;\n\t  if (most_recent_gap_ == it) {\n\t    gap_list_.erase(it);\n\t    most_recent_gap_ = gap_list_.end();\n\t  }\n\t  else {\n\t    gap_list_.erase(it);\n\t  }\n\t  return return_val;\n\t}\n      }\n    }\n    // No suitable gap found; instead add to end of gradient vector\n    i_gradient_ += n;\n    if (i_gradient_ > max_gradient_) {\n      max_gradient_ = i_gradient_;\n    }\n    return i_gradient_ - n;\n  }\n  \n\n  // If an aReal object is deleted, its gradient_index is\n  // unregistered from the stack.  If this is at the top of the stack\n  // then this is easy and is done inline; this is the usual case\n  // since C++ trys to deallocate automatic objects in the reverse\n  // order to that in which they were allocated.  If it is not at the\n  // top of the stack then a non-inline function is called to ensure\n  // that the gap list is adjusted correctly.\n  void\n  Stack::unregister_gradient_not_top(const uIndex& gradient_index)\n  {\n    enum {\n      ADDED_AT_BASE,\n      ADDED_AT_TOP,\n      NEW_GAP,\n      NOT_FOUND\n    } status = NOT_FOUND;\n    // First try to find if the unregistered element is at the\n    // start or end of an existing gap\n    if (!gap_list_.empty() && most_recent_gap_ != gap_list_.end()) {\n      // We have a \"most recent\" gap - check whether the gradient\n      // to be unregistered is here\n      Gap& current_gap = *most_recent_gap_;\n      if (gradient_index == current_gap.start - 1) {\n\tcurrent_gap.start--;\n\tstatus = ADDED_AT_BASE;\n      }\n      else if (gradient_index == current_gap.end + 1) {\n\tcurrent_gap.end++;\n\tstatus = ADDED_AT_TOP;\n      }\n      // Should we check for erroneous removal from middle of gap?\n    }\n    if (status == NOT_FOUND) {\n      // Search other gaps\n      for (GapListIterator it = gap_list_.begin();\n\t   it != gap_list_.end(); it++) {\n\tif (gradient_index <= it->end + 1) {\n\t  // Gradient to unregister is either within the gap\n\t  // referenced by iterator \"it\", or it is between \"it\"\n\t  // and the previous gap in the list\n\t  if (gradient_index == it->start - 1) {\n\t    status = ADDED_AT_BASE;\n\t    it->start--;\n\t    most_recent_gap_ = it;\n\t  }\n\t  else if (gradient_index == it->end + 1) {\n\t    status = ADDED_AT_TOP;\n\t    it->end++;\n\t    most_recent_gap_ = it;\n\t  }\n\t  else {\n\t    // Insert a new gap of width 1; note that list::insert\n\t    // inserts *before* the specified location\n\t    most_recent_gap_\n\t      = gap_list_.insert(it, Gap(gradient_index));\n\t    status = NEW_GAP;\n\t  }\n\t  break;\n\t}\n      }\n      if (status == NOT_FOUND) {\n\tgap_list_.push_back(Gap(gradient_index));\n\tmost_recent_gap_ = gap_list_.end();\n\tmost_recent_gap_--;\n      }\n    }\n    // Finally check if gaps have merged\n    if (status == ADDED_AT_BASE\n\t&& most_recent_gap_ != gap_list_.begin()) {\n      // Check whether the gap has merged with the next one\n      GapListIterator it = most_recent_gap_;\n      it--;\n      if (it->end == most_recent_gap_->start - 1) {\n\t// Merge two gaps\n\tmost_recent_gap_->start = it->start;\n\tgap_list_.erase(it);\n      }\n    }\n    else if (status == ADDED_AT_TOP) {\n      GapListIterator it = most_recent_gap_;\n      it++;\n      if (it != gap_list_.end()\n\t  && it->start == most_recent_gap_->end + 1) {\n\t// Merge two gaps\n\tmost_recent_gap_->end = it->end;\n\tgap_list_.erase(it);\n      }\n    }\n  }\t\n\n\n  // Unregister n gradients starting at gradient_index\n  void\n  Stack::unregister_gradients(const uIndex& gradient_index,\n\t\t\t      const uIndex& n)\n  {\n    n_gradients_registered_ -= n;\n    if (gradient_index+n == i_gradient_) {\n      // Gradient to be unregistered is at the top of the stack\n      i_gradient_ -= n;\n      if (!gap_list_.empty()) {\n\tGap& last_gap = gap_list_.back();\n\tif (i_gradient_ == last_gap.end+1) {\n\t  // We have unregistered the elements between the \"gap\" of\n\t  // unregistered element and the top of the stack, so can set\n\t  // the variables indicating the presence of the gap to zero\n\t  i_gradient_ = last_gap.start;\n\t  GapListIterator it = gap_list_.end();\n\t  it--;\n\t  if (most_recent_gap_ == it) {\n\t    most_recent_gap_ = gap_list_.end();\n\t  }\n\t  gap_list_.pop_back();\n\t}\n      }\n    }\n    else { // Gradients to be unregistered not at top of stack.\n      enum {\n\tADDED_AT_BASE,\n\tADDED_AT_TOP,\n\tNEW_GAP,\n\tNOT_FOUND\n      } status = NOT_FOUND;\n      // First try to find if the unregistered element is at the start\n      // or end of an existing gap\n      if (!gap_list_.empty() && most_recent_gap_ != gap_list_.end()) {\n\t// We have a \"most recent\" gap - check whether the gradient\n\t// to be unregistered is here\n\tGap& current_gap = *most_recent_gap_;\n\tif (gradient_index == current_gap.start - n) {\n\t  current_gap.start -= n;\n\t  status = ADDED_AT_BASE;\n\t}\n\telse if (gradient_index == current_gap.end + 1) {\n\t  current_gap.end += n;\n\t  status = ADDED_AT_TOP;\n\t}\n\t/*\n\telse if (gradient_index > current_gap.start - n\n\t\t && gradient_index < current_gap.end + 1) {\n\t  std::cout << \"** Attempt to find \" << gradient_index << \" in gaps \";\n\t  print_gaps();\n\t  std::cout << \"\\n\";\n\t  throw invalid_operation(\"Gap list corruption\");\n\t}\n\t*/\n\t// Should we check for erroneous removal from middle of gap?\n      }\n      if (status == NOT_FOUND) {\n\t// Search other gaps\n\tfor (GapListIterator it = gap_list_.begin();\n\t     it != gap_list_.end(); it++) {\n\t  if (gradient_index <= it->end + 1) {\n\t    // Gradient to unregister is either within the gap\n\t    // referenced by iterator \"it\", or it is between \"it\" and\n\t    // the previous gap in the list\n\t    if (gradient_index == it->start - n) {\n\t      status = ADDED_AT_BASE;\n\t      it->start -= n;\n\t      most_recent_gap_ = it;\n\t    }\n\t    else if (gradient_index == it->end + 1) {\n\t      status = ADDED_AT_TOP;\n\t      it->end += n;\n\t      most_recent_gap_ = it;\n\t    }\n\t    /*\n\t    else if (gradient_index > it->start - n) {\n\t      std::cout << \"*** Attempt to find \" << gradient_index << \" in gaps \";\n\t      print_gaps();\n\t      std::cout << \"\\n\";\n\t      throw invalid_operation(\"Gap list corruption\");\n\t    }\n\t    */\n\t    else {\n\t      // Insert a new gap; note that list::insert inserts\n\t      // *before* the specified location\n\t      most_recent_gap_\n\t\t= gap_list_.insert(it, Gap(gradient_index,\n\t\t\t\t\t   gradient_index+n-1));\n\t      status = NEW_GAP;\n\t    }\n\t    break;\n\t  }\n\t}\n\tif (status == NOT_FOUND) {\n\t  gap_list_.push_back(Gap(gradient_index,\n\t\t\t\t  gradient_index+n-1));\n\t  most_recent_gap_ = gap_list_.end();\n\t  most_recent_gap_--;\n\t}\n      }\n      // Finally check if gaps have merged\n      if (status == ADDED_AT_BASE\n\t  && most_recent_gap_ != gap_list_.begin()) {\n\t// Check whether the gap has merged with the next one\n\tGapListIterator it = most_recent_gap_;\n\tit--;\n\tif (it->end == most_recent_gap_->start - 1) {\n\t  // Merge two gaps\n\t  most_recent_gap_->start = it->start;\n\t  gap_list_.erase(it);\n\t}\n      }\n      else if (status == ADDED_AT_TOP) {\n\tGapListIterator it = most_recent_gap_;\n\n\tit++;\n\tif (it != gap_list_.end()\n\t    && it->start == most_recent_gap_->end + 1) {\n\t  // Merge two gaps\n\t  most_recent_gap_->end = it->end;\n\t  gap_list_.erase(it);\n\t}\n      }\n    }\n  }\n  \n  \n  // Print each derivative statement to the specified stream (standard\n  // output if omitted)\n  void\n  Stack::print_statements(std::ostream& os) const\n  {\n    for (uIndex ist = 1; ist < n_statements_; ist++) {\n      const Statement& statement = statement_[ist];\n      os << ist\n\t\t<< \": d[\" << statement.index\n\t\t<< \"] = \";\n      \n      if (statement_[ist-1].end_plus_one == statement_[ist].end_plus_one) {\n\tos << \"0\\n\";\n      }\n      else {    \n\tfor (uIndex i = statement_[ist-1].end_plus_one;\n\t     i < statement.end_plus_one; i++) {\n\t  os << \" + \" << multiplier_[i] << \"*d[\" << index_[i] << \"]\";\n\t}\n\tos << \"\\n\";\n      }\n    }\n  }\n  \n  // Print the current gradient list to the specified stream (standard\n  // output if omitted)\n  bool\n  Stack::print_gradients(std::ostream& os) const\n  {\n    if (gradients_are_initialized()) {\n      for (uIndex i = 0; i < max_gradient_; i++) {\n\tif (i%10 == 0) {\n\t  if (i != 0) {\n\t    os << \"\\n\";\n\t  }\n\t  os << i << \":\";\n\t}\n\tos << \" \" << gradient_[i];\n      }\n      os << \"\\n\";\n      return true;\n    }\n    else {\n      os << \"No gradients initialized\\n\";\n      return false;\n    }\n  }\n\n  // Print the list of gaps in the gradient list to the specified\n  // stream (standard output if omitted)\n  void\n  Stack::print_gaps(std::ostream& os) const\n  {\n    for (std::list<Gap>::const_iterator it = gap_list_.begin();\n\t it != gap_list_.end(); it++) {\n      os << it->start << \"-\" << it->end << \" \";\n    }\n  }\n\n\n#ifndef ADEPT_STACK_STORAGE_STL\n  // Initialize the vector of gradients ready for the adjoint\n  // calculation\n  void\n  Stack::initialize_gradients()\n  {\n    if (max_gradient_ > 0) {\n      if (n_allocated_gradients_ < max_gradient_) {\n\tif (gradient_) {\n\t  delete[] gradient_;\n\t}\n\tgradient_ = new Real[max_gradient_];\n\tn_allocated_gradients_ = max_gradient_;\n      }\n      for (uIndex i = 0; i < max_gradient_; i++) {\n\tgradient_[i] = 0.0;\n      }\n    }\n    gradients_initialized_ = true;\n  }\n#else\n  void\n  Stack::initialize_gradients()\n  {\n    gradient_.resize(max_gradient_+10, 0.0);\n      gradients_initialized_ = true;\n  }\n#endif\n\n  // Report information about the stack to the specified stream, or\n  // standard output if omitted; note that this is synonymous with\n  // sending the Stack object to a stream using the \"<<\" operator.\n  void\n  Stack::print_status(std::ostream& os) const\n  {\n    os << \"Automatic Differentiation Stack (address \" << this << \"):\\n\";\n    if ((!is_thread_unsafe_) && _stack_current_thread == this) {\n      os << \"   Currently attached - thread safe\\n\";\n    }\n    else if (is_thread_unsafe_ && _stack_current_thread_unsafe == this) {\n      os << \"   Currently attached - thread unsafe\\n\";\n    }\n    else {\n      os << \"   Currently detached\\n\";\n    }\n    os << \"   Recording status:\\n\";\n    if (is_recording_) {\n      os << \"      Recording is ON\\n\";  \n    }\n    else {\n      os << \"      Recording is PAUSED\\n\";\n    }\n    // Account for the null statement at the start by subtracting one\n    os << \"      \" << n_statements()-1 << \" statements (\" \n       << n_allocated_statements() << \" allocated)\";\n    os << \" and \" << n_operations() << \" operations (\" \n       << n_allocated_operations() << \" allocated)\\n\";\n    os << \"      \" << n_gradients_registered() << \" gradients currently registered \";\n    os << \"and a total of \" << max_gradients() << \" needed (current index \"\n       << i_gradient() << \")\\n\";\n    if (gap_list_.empty()) {\n      os << \"      Gradient list has no gaps\\n\";\n    }\n    else {\n      os << \"      Gradient list has \" << gap_list_.size() << \" gaps (\";\n      print_gaps(os);\n      os << \")\\n\";\n    }\n    os << \"   Computation status:\\n\";\n    if (gradients_are_initialized()) {\n      os << \"      \" << max_gradients() << \" gradients assigned (\" \n\t << n_allocated_gradients() << \" allocated)\\n\";\n    }\n    else {\n      os << \"      0 gradients assigned (\" << n_allocated_gradients()\n\t << \" allocated)\\n\";\n    }\n    os << \"      Jacobian size: \" << n_dependents() << \"x\" << n_independents() << \"\\n\";\n    if (n_dependents() <= 10 && n_independents() <= 10) {\n      os << \"      Independent indices:\";\n      for (std::size_t i = 0; i < independent_index_.size(); ++i) {\n\tos << \" \" << independent_index_[i];\n      }\n      os << \"\\n      Dependent indices:  \";\n      for (std::size_t i = 0; i < dependent_index_.size(); ++i) {\n\tos << \" \" << dependent_index_[i];\n      }\n      os << \"\\n\";\n    }\n\n#ifdef _OPENMP\n    if (have_openmp_) {\n      if (openmp_manually_disabled_) {\n\tos << \"      Parallel Jacobian calculation manually disabled\\n\";\n      }\n      else {\n\tos << \"      Parallel Jacobian calculation can use up to \"\n\t   << omp_get_max_threads() << \" threads\\n\";\n\tos << \"      Each thread treats \" << ADEPT_MULTIPASS_SIZE \n\t   << \" (in)dependent variables\\n\";\n      }\n    }\n    else {\n#endif\n      os << \"      Parallel Jacobian calculation not available\\n\";\n#ifdef _OPENMP\n    }\n#endif\n  }\n} // End namespace adept\n\n\n\n// =================================================================\n// Contents of StackStorageOrig.cpp\n// =================================================================\n\n/* StackStorageOrig.cpp -- Original storage of stacks using STL containers\n\n    Copyright (C) 2014-2015 University of Reading\n\n    Author: Robin Hogan <r.j.hogan@ecmwf.int>\n\n    This file is part of the Adept library.\n\n   The Stack class inherits from a class providing the storage (and\n   interface to the storage) for the derivative statements that are\n   accumulated during the execution of an algorithm.  The derivative\n   statements are held in two stacks described by Hogan (2014): the\n   \"statement stack\" and the \"operation stack\".\n\n   This file provides one of the original storage engine, which used\n   std::vector to hold the two stacks. Note that these stacks are\n   contiguous in memory, which is not ideal for very large algorithms.\n\n*/\n\n#include <cstring>\n\n#include <adept/StackStorageOrig.h>\n\nnamespace adept {\n  namespace internal {\n\n    StackStorageOrig::~StackStorageOrig() {\n      if (statement_) {\n\tdelete[] statement_;\n      }\n      if (multiplier_) {\n\tdelete[] multiplier_;\n      }\n      if (index_) {\n\tdelete[] index_;\n      }\n    }\n\n\n    // Double the size of the operation stack, or grow it even more if\n    // the requested minimum number of extra entries (min) is greater\n    // than this would allow\n    void\n    StackStorageOrig::grow_operation_stack(uIndex min)\n    {\n      uIndex new_size = 2*n_allocated_operations_;\n      if (min > 0 && new_size < n_allocated_operations_+min) {\n\tnew_size += min;\n      }\n      Real* new_multiplier = new Real[new_size];\n      uIndex* new_index = new uIndex[new_size];\n      \n      std::memcpy(new_multiplier, multiplier_, n_operations_*sizeof(Real));\n      std::memcpy(new_index, index_, n_operations_*sizeof(uIndex));\n      \n      delete[] multiplier_;\n      delete[] index_;\n      \n      multiplier_ = new_multiplier;\n      index_ = new_index;\n      \n      n_allocated_operations_ = new_size;\n    }\n    \n    // ... likewise for the statement stack\n    void\n    StackStorageOrig::grow_statement_stack(uIndex min)\n    {\n      uIndex new_size = 2*n_allocated_statements_;\n      if (min > 0 && new_size < n_allocated_statements_+min) {\n\tnew_size += min;\n      }\n      Statement* new_statement = new Statement[new_size];\n      std::memcpy(new_statement, statement_,\n\t\t  n_statements_*sizeof(Statement));\n      delete[] statement_;\n      \n      statement_ = new_statement;\n      \n      n_allocated_statements_ = new_size;\n    }\n\n  }\n}\n\n\n// =================================================================\n// Contents of Storage.cpp\n// =================================================================\n\n/* Storage.cpp -- Global variables recording use of Storage objects\n\n    Copyright (C) 2015 European Centre for Medium-Range Weather Forecasts\n\n    Author: Robin Hogan <r.j.hogan@ecmwf.int>\n\n    This file is part of the Adept library.\n\n*/\n\n#include <adept/Storage.h>\n\nnamespace adept {\n  namespace internal {\n    Index n_storage_objects_created_;\n    Index n_storage_objects_deleted_;\n  }\n}\n\n\n// =================================================================\n// Contents of cppblas.cpp\n// =================================================================\n\n/* cppblas.cpp -- C++ interface to BLAS functions\n\n    Copyright (C) 2015-2016 European Centre for Medium-Range Weather Forecasts\n\n    Author: Robin Hogan <r.j.hogan@ecmwf.int>\n\n    This file is part of the Adept library.\n\n   This file provides a C++ interface to selected Level-2 and -3 BLAS\n   functions in which the precision of the arguments (float versus\n   double) is inferred via overloading\n\n*/\n\n#include <adept/exception.h>\n#include <adept/cppblas.h>\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#ifdef HAVE_BLAS\n\nextern \"C\" {\n  void sgemm_(const char* TransA, const char* TransB, const int* M,\n\t      const int* N, const int* K, const float* alpha,\n\t      const float* A, const int* lda, const float* B, const int* ldb,\n\t      const float* beta, const float* C, const int* ldc);\n  void dgemm_(const char* TransA, const char* TransB, const int* M,\n\t      const int* N, const int* K, const double* alpha,\n\t      const double* A, const int* lda, const double* B, const int* ldb,\n\t      const double* beta, const double* C, const int* ldc);\n  void sgemv_(const char* TransA, const int* M, const int* N, const float* alpha,\n\t      const float* A, const int* lda, const float* X, const int* incX,\n\t      const float* beta, const float* Y, const int* incY);\n  void dgemv_(const char* TransA, const int* M, const int* N, const double* alpha,\n\t      const double* A, const int* lda, const double* X, const int* incX,\n\t      const double* beta, const double* Y, const int* incY);\n  void ssymm_(const char* side, const char* uplo, const int* M, const int* N,\n\t      const float* alpha, const float* A, const int* lda, const float* B,\n\t      const int* ldb, const float* beta, float* C, const int* ldc);\n  void dsymm_(const char* side, const char* uplo, const int* M, const int* N,\n\t      const double* alpha, const double* A, const int* lda, const double* B,\n\t      const int* ldb, const double* beta, double* C, const int* ldc);\n  void ssymv_(const char* uplo, const int* N, const float* alpha, const float* A, \n\t      const int* lda, const float* X, const int* incX, const float* beta, \n\t      const float* Y, const int* incY);\n  void dsymv_(const char* uplo, const int* N, const double* alpha, const double* A, \n\t      const int* lda, const double* X, const int* incX, const double* beta, \n\t      const double* Y, const int* incY);\n  void sgbmv_(const char* TransA, const int* M, const int* N, const int* kl, \n\t      const int* ku, const float* alpha, const float* A, const int* lda,\n\t      const float* X, const int* incX, const float* beta, \n\t      const float* Y, const int* incY);\n  void dgbmv_(const char* TransA, const int* M, const int* N, const int* kl, \n\t      const int* ku, const double* alpha, const double* A, const int* lda,\n\t      const double* X, const int* incX, const double* beta, \n\t      const double* Y, const int* incY);\n};\n\nnamespace adept {\n\n  namespace internal {\n    \n    // Matrix-matrix multiplication for general dense matrices\n#define ADEPT_DEFINE_GEMM(T, FUNC, FUNC_COMPLEX)\t\t\\\n    void cppblas_gemm(BLAS_ORDER Order,\t\t\t\t\\\n\t\t      BLAS_TRANSPOSE TransA,\t\t\t\\\n\t\t      BLAS_TRANSPOSE TransB,\t\t\t\\\n\t\t      int M, int N,\t\t\t\t\\\n\t\t      int K, T alpha, const T *A,\t\t\\\n\t\t      int lda, const T *B, int ldb,\t\t\\\n\t\t      T beta, T *C, int ldc) {\t\t\t\\\n      if (Order == BlasColMajor) {\t\t\t\t\\\n        FUNC(&TransA, &TransB, &M, &N, &K, &alpha, A, &lda,\t\\\n\t     B, &ldb, &beta, C, &ldc);\t\t\t\t\\\n      }\t\t\t\t\t\t\t\t\\\n      else {\t\t\t\t\t\t\t\\\n        FUNC(&TransB, &TransA, &N, &M, &K, &alpha, B, &ldb,\t\\\n\t     A, &lda, &beta, C, &ldc);\t\t\t\t\\\n      }\t\t\t\t\t\t\t\t\\\n    }\n    ADEPT_DEFINE_GEMM(double, dgemm_, zgemm_);\n    ADEPT_DEFINE_GEMM(float,  sgemm_, cgemm_);\n#undef ADEPT_DEFINE_GEMM\n    \n    // Matrix-vector multiplication for a general dense matrix\n#define ADEPT_DEFINE_GEMV(T, FUNC, FUNC_COMPLEX)\t\t\\\n    void cppblas_gemv(const BLAS_ORDER Order,\t\t\t\\\n\t\t      const BLAS_TRANSPOSE TransA,\t\t\\\n\t\t      const int M, const int N,\t\t\t\\\n\t\t      const T alpha, const T *A, const int lda,\t\\\n\t\t      const T *X, const int incX, const T beta,\t\\\n\t\t      T *Y, const int incY) {\t\t\t\\\n      if (Order == BlasColMajor) {\t\t\t\t\\\n        FUNC(&TransA, &M, &N, &alpha, A, &lda, X, &incX, \t\\\n\t     &beta, Y, &incY);\t\t\t\t\t\\\n      }\t\t\t\t\t\t\t\t\\\n      else {\t\t\t\t\t\t\t\\\n        BLAS_TRANSPOSE TransNew\t\t\t\t\t\\\n\t  = TransA == BlasTrans ? BlasNoTrans : BlasTrans;\t\\\n        FUNC(&TransNew, &N, &M, &alpha, A, &lda, X, &incX, \t\\\n\t     &beta, Y, &incY);\t\t\t\t\t\\\n      }\t\t\t\t\t\t\t\t\\\n    }\n    ADEPT_DEFINE_GEMV(double, dgemv_, zgemv_);\n    ADEPT_DEFINE_GEMV(float,  sgemv_, cgemv_);\n#undef ADEPT_DEFINE_GEMV\n    \n    // Matrix-matrix multiplication where matrix A is symmetric\n    // FIX! CHECK ROW MAJOR VERSION IS RIGHT\t\t\t\n#define ADEPT_DEFINE_SYMM(T, FUNC, FUNC_COMPLEX)\t\t\t\\\n    void cppblas_symm(const BLAS_ORDER Order,\t\t\t\t\\\n\t\t      const BLAS_SIDE Side,\t\t\t\t\\\n\t\t      const BLAS_UPLO Uplo,\t\t\t\t\\\n\t\t      const int M, const int N,\t\t\t\t\\\n\t\t      const T alpha, const T *A, const int lda,\t\t\\\n\t\t      const T *B, const int ldb, const T beta,\t\t\\\n\t\t      T *C, const int ldc) {\t\t\t\t\\\n      if (Order == BlasColMajor) {\t\t\t\t\t\\\n        FUNC(&Side, &Uplo, &M, &N, &alpha, A, &lda,\t\t\t\\\n\t     B, &ldb, &beta, C, &ldc);\t\t\t\t\t\\\n      }\t\t\t\t\t\t\t\t\t\\\n      else {\t\t\t\t\t\t\t\t\\\n\tBLAS_SIDE SideNew = Side == BlasLeft  ? BlasRight : BlasLeft;\t\\\n\tBLAS_UPLO UploNew = Uplo == BlasUpper ? BlasLower : BlasUpper;  \\\n        FUNC(&SideNew, &UploNew, &N, &M, &alpha, A, &lda,\t\t\\\n\t     B, &ldb, &beta, C, &ldc);\t\t\t\t\t\\\n      }\t\t\t\t\t\t\t\t\t\\\n    }\n    ADEPT_DEFINE_SYMM(double, dsymm_, zsymm_);\n    ADEPT_DEFINE_SYMM(float,  ssymm_, csymm_);\n#undef ADEPT_DEFINE_SYMM\n    \n    // Matrix-vector multiplication where the matrix is symmetric\n#define ADEPT_DEFINE_SYMV(T, FUNC, FUNC_COMPLEX)\t\t\t\\\n    void cppblas_symv(const BLAS_ORDER Order,\t\t\t\t\\\n\t\t      const BLAS_UPLO Uplo,\t\t\t\t\\\n\t\t      const int N, const T alpha, const T *A,\t\t\\\n\t\t      const int lda, const T *X, const int incX,\t\\\n\t\t      const T beta, T *Y, const int incY) {\t\t\\\n      if (Order == BlasColMajor) {\t\t\t\t\t\\\n        FUNC(&Uplo, &N, &alpha, A, &lda, X, &incX, &beta, Y, &incY);\t\\\n      }\t\t\t\t\t\t\t\t\t\\\n      else {\t\t\t\t\t\t\t\t\\\n        BLAS_UPLO UploNew = Uplo == BlasUpper ? BlasLower : BlasUpper;  \\\n        FUNC(&UploNew, &N, &alpha, A, &lda, X, &incX, &beta, Y, &incY);\t\\\n      }\t\t\t\t\t\t\t\t\t\\\n    }\n    ADEPT_DEFINE_SYMV(double, dsymv_, zsymv_);\n    ADEPT_DEFINE_SYMV(float,  ssymv_, csymv_);\n#undef ADEPT_DEFINE_SYMV\n    \n    // Matrix-vector multiplication for a general band matrix\n#define ADEPT_DEFINE_GBMV(T, FUNC, FUNC_COMPLEX)\t\t\\\n    void cppblas_gbmv(const BLAS_ORDER Order,\t\t\t\\\n\t\t      const BLAS_TRANSPOSE TransA,\t\t\\\n\t\t      const int M, const int N,\t\t\t\\\n\t\t      const int KL, const int KU, const T alpha,\\\n\t\t      const T *A, const int lda, const T *X,\t\\\n\t\t      const int incX, const T beta, T *Y,\t\\\n\t\t      const int incY) {\t\t\t\t\\\n      if (Order == BlasColMajor) {\t\t\t\t\\\n        FUNC(&TransA, &M, &N, &KL, &KU, &alpha, A, &lda,\t\\\n\t     X, &incX, &beta, Y, &incY);\t\t\t\\\n      }\t\t\t\t\t\t\t\t\\\n      else {\t\t\t\t\t\t\t\\\n\tBLAS_TRANSPOSE TransNew\t\t\t\t\t\\\n\t  = TransA == BlasTrans ? BlasNoTrans : BlasTrans;\t\\\n\tFUNC(&TransNew, &N, &M, &KU, &KL, &alpha, A, &lda,\t\\\n\t     X, &incX, &beta, Y, &incY);\t\t\t\\\n      }\t\t\t\t\t\t\t\t\\\n    }\n    ADEPT_DEFINE_GBMV(double, dgbmv_, zgbmv_);\n    ADEPT_DEFINE_GBMV(float,  sgbmv_, cgbmv_);\n#undef ADEPT_DEFINE_GBMV\n  \n  } // End namespace internal\n  \n} // End namespace adept\n  \n\n#else // Don't have BLAS\n\n\nnamespace adept {\n\n  namespace internal {\n    \n    // Matrix-matrix multiplication for general dense matrices\n#define ADEPT_DEFINE_GEMM(T, FUNC, FUNC_COMPLEX)\t\t\\\n    void cppblas_gemm(BLAS_ORDER Order,\t\t\t\t\\\n\t\t      BLAS_TRANSPOSE TransA,\t\t\t\\\n\t\t      BLAS_TRANSPOSE TransB,\t\t\t\\\n\t\t      int M, int N,\t\t\t\t\\\n\t\t      int K, T alpha, const T *A,\t\t\\\n\t\t      int lda, const T *B, int ldb,\t\t\\\n\t\t      T beta, T *C, int ldc) {\t\t\t\\\n      throw feature_not_available(\"Cannot perform matrix-matrix multiplication because compiled without BLAS\"); \\\n    }\n    ADEPT_DEFINE_GEMM(double, dgemm_, zgemm_);\n    ADEPT_DEFINE_GEMM(float,  sgemm_, cgemm_);\n#undef ADEPT_DEFINE_GEMM\n    \n    // Matrix-vector multiplication for a general dense matrix\n#define ADEPT_DEFINE_GEMV(T, FUNC, FUNC_COMPLEX)\t\t\\\n    void cppblas_gemv(const BLAS_ORDER Order,\t\t\t\\\n\t\t      const BLAS_TRANSPOSE TransA,\t\t\\\n\t\t      const int M, const int N,\t\t\t\\\n\t\t      const T alpha, const T *A, const int lda,\t\\\n\t\t      const T *X, const int incX, const T beta,\t\\\n\t\t      T *Y, const int incY) {\t\t\t\\\n      throw feature_not_available(\"Cannot perform matrix-vector multiplication because compiled without BLAS\"); \\\n    }\n    ADEPT_DEFINE_GEMV(double, dgemv_, zgemv_);\n    ADEPT_DEFINE_GEMV(float,  sgemv_, cgemv_);\n#undef ADEPT_DEFINE_GEMV\n    \n    // Matrix-matrix multiplication where matrix A is symmetric\n    // FIX! CHECK ROW MAJOR VERSION IS RIGHT\t\t\t\n#define ADEPT_DEFINE_SYMM(T, FUNC, FUNC_COMPLEX)\t\t\t\\\n    void cppblas_symm(const BLAS_ORDER Order,\t\t\t\t\\\n\t\t      const BLAS_SIDE Side,\t\t\t\t\\\n\t\t      const BLAS_UPLO Uplo,\t\t\t\t\\\n\t\t      const int M, const int N,\t\t\t\t\\\n\t\t      const T alpha, const T *A, const int lda,\t\t\\\n\t\t      const T *B, const int ldb, const T beta,\t\t\\\n\t\t      T *C, const int ldc) {\t\t\t\t\\\n      throw feature_not_available(\"Cannot perform symmetric matrix-matrix multiplication because compiled without BLAS\"); \\\n    }\n    ADEPT_DEFINE_SYMM(double, dsymm_, zsymm_);\n    ADEPT_DEFINE_SYMM(float,  ssymm_, csymm_);\n#undef ADEPT_DEFINE_SYMM\n    \n    // Matrix-vector multiplication where the matrix is symmetric\n#define ADEPT_DEFINE_SYMV(T, FUNC, FUNC_COMPLEX)\t\t\t\\\n    void cppblas_symv(const BLAS_ORDER Order,\t\t\t\t\\\n\t\t      const BLAS_UPLO Uplo,\t\t\t\t\\\n\t\t      const int N, const T alpha, const T *A,\t\t\\\n\t\t      const int lda, const T *X, const int incX,\t\\\n\t\t      const T beta, T *Y, const int incY) {\t\t\\\n      throw feature_not_available(\"Cannot perform symmetric matrix-vector multiplication because compiled without BLAS\"); \\\n    }\n    ADEPT_DEFINE_SYMV(double, dsymv_, zsymv_);\n    ADEPT_DEFINE_SYMV(float,  ssymv_, csymv_);\n#undef ADEPT_DEFINE_SYMV\n    \n    // Matrix-vector multiplication for a general band matrix\n#define ADEPT_DEFINE_GBMV(T, FUNC, FUNC_COMPLEX)\t\t\\\n    void cppblas_gbmv(const BLAS_ORDER Order,\t\t\t\\\n\t\t      const BLAS_TRANSPOSE TransA,\t\t\\\n\t\t      const int M, const int N,\t\t\t\\\n\t\t      const int KL, const int KU, const T alpha,\\\n\t\t      const T *A, const int lda, const T *X,\t\\\n\t\t      const int incX, const T beta, T *Y,\t\\\n\t\t      const int incY) {\t\t\t\t\\\n      throw feature_not_available(\"Cannot perform band matrix-vector multiplication because compiled without BLAS\"); \\\n    }\n    ADEPT_DEFINE_GBMV(double, dgbmv_, zgbmv_);\n    ADEPT_DEFINE_GBMV(float,  sgbmv_, cgbmv_);\n#undef ADEPT_DEFINE_GBMV\n\n  }\n}\n\n#endif\n\n\n// =================================================================\n// Contents of index.cpp\n// =================================================================\n\n/* index.cpp -- Definitions of \"end\" and \"__\" for array indexing\n\n    Copyright (C) 2015 European Centre for Medium-Range Weather Forecasts\n\n    Robin Hogan <r.j.hogan@ecmwf.int>\n\n    This file is part of the Adept library.\n*/\n\n#include <adept/RangeIndex.h>\n\nnamespace adept {\n\n  ::adept::internal::EndIndex end;\n  ::adept::internal::AllIndex __;\n\n}\n\n\n// =================================================================\n// Contents of inv.cpp\n// =================================================================\n\n/* inv.cpp -- Invert matrices\n\n    Copyright (C) 2015-2016 European Centre for Medium-Range Weather Forecasts\n\n    Author: Robin Hogan <r.j.hogan@ecmwf.int>\n\n    This file is part of the Adept library.\n*/\n                             \n#include <vector>\n\n#include <adept/Array.h>\n#include <adept/SpecialMatrix.h>\n\n#ifndef AdeptSource_H\n#include \"cpplapack.h\"\n#endif\n\n#ifdef HAVE_LAPACK\n\nnamespace adept {\n\n  // -------------------------------------------------------------------\n  // Invert general square matrix A\n  // -------------------------------------------------------------------\n  template <typename Type>\n  Array<2,Type,false> \n  inv(const Array<2,Type,false>& A) {\n    using internal::cpplapack_getrf;\n    using internal::cpplapack_getri;\n\n    if (A.dimension(0) != A.dimension(1)) {\n      //throw invalid_operation(\"Only square matrices can be inverted\"\n\t//\t\t      ADEPT_EXCEPTION_LOCATION);\n      printf(\"invalid operation\\n\");\n      assert(false);\n    }\n\n    Array<2,Type,false> A_;\n\n    // LAPACKE is more efficient with column-major input\n    A_.resize_column_major(A.dimensions());\n    A_ = A;\n\n    std::vector<lapack_int> ipiv(A_.dimension(0));\n\n    //    lapack_int status = LAPACKE_dgetrf(LAPACK_COL_MAJOR, A_.dimension(0), A_.dimension(1),\n    //\t\t\t\t       A_.data(), A_.offset(1), &ipiv[0]);\n\n    lapack_int status = cpplapack_getrf(A_.dimension(0),\n\t\t\t\t\tA_.data(), A_.offset(1), &ipiv[0]);\n    if (status != 0) {\n      std::stringstream s;\n      s << \"Failed to factorize matrix: LAPACK ?getrf returned code \" << status;\n      //throw(matrix_ill_conditioned(s.str() ADEPT_EXCEPTION_LOCATION));\n      printf(\"matrix ill conditioned\\n\");\n      assert(false);\n    }\n\n    //    status = LAPACKE_dgetri(LAPACK_COL_MAJOR, A_.dimension(0),\n    //\t\t\t    A_.data(), A_.offset(1), &ipiv[0]);\n    status = cpplapack_getri(A_.dimension(0),\n\t\t\t     A_.data(), A_.offset(1), &ipiv[0]);\n\n    if (status != 0) {\n      std::stringstream s;\n      s << \"Failed to invert matrix: LAPACK ?getri returned code \" << status;\n      //throw(matrix_ill_conditioned(s.str() ADEPT_EXCEPTION_LOCATION));\n      printf(\"matrix ill conditioned\\n\");\n      assert(false);\n    }\n    return A_;\n  }\n\n\n\n  // -------------------------------------------------------------------\n  // Invert symmetric matrix A\n  // -------------------------------------------------------------------\n  template <typename Type, SymmMatrixOrientation Orient>\n  SpecialMatrix<Type,SymmEngine<Orient>,false> \n  inv(const SpecialMatrix<Type,SymmEngine<Orient>,false>& A) {\n    using internal::cpplapack_sytrf;\n    using internal::cpplapack_sytri;\n\n    SpecialMatrix<Type,SymmEngine<Orient>,false> A_;\n\n    A_.resize(A.dimension());\n    A_ = A;\n\n    // Treat symmetric matrix as column-major\n    char uplo;\n    if (Orient == ROW_LOWER_COL_UPPER) {\n      uplo = 'U';\n    }\n    else {\n      uplo = 'L';\n    }\n\n    std::vector<lapack_int> ipiv(A_.dimension(0));\n\n    //    lapack_int status = LAPACKE_dsytrf(LAPACK_COL_MAJOR, uplo, A_.dimension(),\n    //\t\t\t\t       A_.data(), A_.offset(), &ipiv[0]);\n    lapack_int status = cpplapack_sytrf(uplo, A_.dimension(),\n\t\t\t\t\tA_.data(), A_.offset(), &ipiv[0]);\n    if (status != 0) {\n      std::stringstream s;\n      s << \"Failed to factorize symmetric matrix: LAPACK ?sytrf returned code \" << status;\n      //throw(matrix_ill_conditioned(s.str() ADEPT_EXCEPTION_LOCATION));\n      printf(\"matrix ill conditioned\\n\");\n      assert(false);\n    }\n\n    //    status = LAPACKE_dsytri(LAPACK_COL_MAJOR, uplo, A_.dimension(),\n    //\t\t\t    A_.data(), A_.offset(), &ipiv[0]);\n    status = cpplapack_sytri(uplo, A_.dimension(),\n\t\t\t     A_.data(), A_.offset(), &ipiv[0]);\n    if (status != 0) {\n      std::stringstream s;\n      s << \"Failed to invert symmetric matrix: LAPACK ?sytri returned code \" << status;\n      //throw(matrix_ill_conditioned(s.str() ADEPT_EXCEPTION_LOCATION));\n      printf(\"matrix ill conditioned\\n\");\n      assert(false);\n    }\n    return A_;\n  }\n\n}\n\n#else // LAPACK not available\n    \nnamespace adept {\n\n  // -------------------------------------------------------------------\n  // Invert general square matrix A\n  // -------------------------------------------------------------------\n  template <typename Type>\n  Array<2,Type,false> \n  inv(const Array<2,Type,false>& A) {\n    //throw feature_not_available(\"Cannot invert matrix because compiled without LAPACK\");\n    printf(\"feature not available\\n\");\n    assert(false);\n  }\n\n  // -------------------------------------------------------------------\n  // Invert symmetric matrix A\n  // -------------------------------------------------------------------\n  template <typename Type, SymmMatrixOrientation Orient>\n  SpecialMatrix<Type,SymmEngine<Orient>,false> \n  inv(const SpecialMatrix<Type,SymmEngine<Orient>,false>& A) {\n    //throw feature_not_available(\"Cannot invert matrix because compiled without LAPACK\");\n    printf(\"feature not available\\n\");\n    assert(false);\n  }\n  \n}\n\n#endif\n\nnamespace adept {\n  // -------------------------------------------------------------------\n  // Explicit instantiations\n  // -------------------------------------------------------------------\n#define ADEPT_EXPLICIT_INV(TYPE)\t\t\t\t\t\\\n  template Array<2,TYPE,false>\t\t\t\t\t\t\\\n  inv(const Array<2,TYPE,false>& A);\t\t\t\t\t\\\n  template SpecialMatrix<TYPE,SymmEngine<ROW_LOWER_COL_UPPER>,false>\t\\\n  inv(const SpecialMatrix<TYPE,SymmEngine<ROW_LOWER_COL_UPPER>,false>&); \\\n  template SpecialMatrix<TYPE,SymmEngine<ROW_UPPER_COL_LOWER>,false>\t\\\n  inv(const SpecialMatrix<TYPE,SymmEngine<ROW_UPPER_COL_LOWER>,false>&)\n\n  ADEPT_EXPLICIT_INV(float);\n  ADEPT_EXPLICIT_INV(double);\n\n#undef ADEPT_EXPLICIT_INV\n  \n}\n\n\n\n\n// =================================================================\n// Contents of jacobian.cpp\n// =================================================================\n\n/* jacobian.cpp -- Computation of Jacobian matrix\n\n    Copyright (C) 2012-2014 University of Reading\n    Copyright (C) 2015-2016 European Centre for Medium-Range Weather Forecasts\n\n    Author: Robin Hogan <r.j.hogan@ecmwf.int>\n\n    This file is part of the Adept library.\n\n*/\n\n#ifdef _OPENMP\n#include <omp.h>\n#endif\n\n#include \"adept/Stack.h\"\n#include \"adept/Packet.h\"\n#include \"adept/traits.h\"\n\nnamespace adept {\n\n  namespace internal {\n    static const int MULTIPASS_SIZE = ADEPT_REAL_PACKET_SIZE == 1 ? ADEPT_MULTIPASS_SIZE : ADEPT_REAL_PACKET_SIZE;\n  }\n\n  using namespace internal;\n\n  template <typename T>\n  T _check_long_double() {\n    // The user may have requested Real to be of type \"long double\" by\n    // specifying ADEPT_REAL_TYPE_SIZE=16. If the present system can\n    // only support double then sizeof(long double) will be 8, but\n    // Adept will not be emitting the best code for this, so it is\n    // probably better to fail forcing the user to specify\n    // ADEPT_REAL_TYPE_SIZE=8.\n    ADEPT_STATIC_ASSERT(ADEPT_REAL_TYPE_SIZE != 16 || ADEPT_REAL_TYPE_SIZE == sizeof(Real),\n\t\t\tCOMPILER_DOES_NOT_SUPPORT_16_BYTE_LONG_DOUBLE);\n    return 1;\n  }\n\n  /*\n  void\n  Stack::jacobian_forward_kernel(Real* gradient_multipass_b) const\n  {\n    static const int MULTIPASS_SIZE = Packet<Real>::size;\n\n    // Loop forward through the derivative statements\n    for (uIndex ist = 1; ist < n_statements_; ist++) {\n      const Statement& statement = statement_[ist];\n      // We copy the LHS to \"a\" in case it appears on the RHS in any\n      // of the following statements\n      Block<MULTIPASS_SIZE,Real> a; // Initialized to zero automatically\n      \n      // Loop through operations\n      for (uIndex iop = statement_[ist-1].end_plus_one;\n\t   iop < statement.end_plus_one; iop++) {\n\tReal* __restrict grad = gradient_multipass_b+index_[iop]*MULTIPASS_SIZE;\n\t// Loop through columns within this block; we hope the\n\t// compiler can optimize this loop. Note that it is faster\n\t// to always use MULTIPASS_SIZE, always known at\n\t// compile time, than to use block_size, which is not, even\n\t// though in the last iteration this may involve redundant\n\t// computations.\n\tif (multiplier_[iop] == 1.0) {\n\t  //\t    if (__builtin_expect(multiplier_[iop] == 1.0,0)) {\n\t  for (uIndex i = 0; i < MULTIPASS_SIZE; i++) {\n\t    //\t      for (uIndex i = 0; i < block_size; i++) {\n\t    a[i] += grad[i];\n\t  }\n\t}\n\telse {\n\t  for (uIndex i = 0; i < MULTIPASS_SIZE; i++) {\n\t    //\t      for (uIndex i = 0; i < block_size; i++) {\n\t    a[i] += multiplier_[iop]*grad[i];\n\t  }\n\t}\n      }\n      // Copy the results\n      for (uIndex i = 0; i < MULTIPASS_SIZE; i++) {\n\tgradient_multipass_b[statement.index*MULTIPASS_SIZE+i] = a[i];\n      }\n    } // End of loop over statements\n  }    \n  */\n\n#if ADEPT_REAL_PACKET_SIZE > 1\n  void\n  Stack::jacobian_forward_kernel(Real* __restrict gradient_multipass_b) const\n  {\n\n    // Loop forward through the derivative statements\n    for (uIndex ist = 1; ist < n_statements_; ist++) {\n      const Statement& statement = statement_[ist];\n      // We copy the LHS to \"a\" in case it appears on the RHS in any\n      // of the following statements\n      Packet<Real> a; // Zeroed automatically\n      // Loop through operations\n      for (uIndex iop = statement_[ist-1].end_plus_one;\n\t   iop < statement.end_plus_one; iop++) {\n\tPacket<Real> g(gradient_multipass_b+index_[iop]*MULTIPASS_SIZE);\n\tPacket<Real> m(multiplier_[iop]);\n\ta += m * g;\n      }\n      // Copy the results\n      a.put(gradient_multipass_b+statement.index*MULTIPASS_SIZE);\n    } // End of loop over statements\n  }    \n#else\n  void\n  Stack::jacobian_forward_kernel(Real* __restrict gradient_multipass_b) const\n  {\n\n    // Loop forward through the derivative statements\n    for (uIndex ist = 1; ist < n_statements_; ist++) {\n      const Statement& statement = statement_[ist];\n      // We copy the LHS to \"a\" in case it appears on the RHS in any\n      // of the following statements\n      Block<MULTIPASS_SIZE,Real> a; // Zeroed automatically\n      // Loop through operations\n      for (uIndex iop = statement_[ist-1].end_plus_one;\n\t   iop < statement.end_plus_one; iop++) {\n\tfor (uIndex i = 0; i < MULTIPASS_SIZE; i++) {\n\t  a[i] += multiplier_[iop]*gradient_multipass_b[index_[iop]*MULTIPASS_SIZE+i];\n\t}\n      }\n      // Copy the results\n      for (uIndex i = 0; i < MULTIPASS_SIZE; i++) {\n\tgradient_multipass_b[statement.index*MULTIPASS_SIZE+i] = a[i];\n      }\n    } // End of loop over statements\n  }    \n#endif\n\n  void\n  Stack::jacobian_forward_kernel_extra(Real* __restrict gradient_multipass_b,\n\t\t\t\t       uIndex n_extra) const\n  {\n\n    // Loop forward through the derivative statements\n    for (uIndex ist = 1; ist < n_statements_; ist++) {\n      const Statement& statement = statement_[ist];\n      // We copy the LHS to \"a\" in case it appears on the RHS in any\n      // of the following statements\n      Block<MULTIPASS_SIZE,Real> a; // Zeroed automatically\n      // Loop through operations\n      for (uIndex iop = statement_[ist-1].end_plus_one;\n\t   iop < statement.end_plus_one; iop++) {\n\tfor (uIndex i = 0; i < n_extra; i++) {\n\t  a[i] += multiplier_[iop]*gradient_multipass_b[index_[iop]*MULTIPASS_SIZE+i];\n\t}\n      }\n      // Copy the results\n      for (uIndex i = 0; i < n_extra; i++) {\n\tgradient_multipass_b[statement.index*MULTIPASS_SIZE+i] = a[i];\n      }\n    } // End of loop over statements\n  }    \n\n\n\n  // Compute the Jacobian matrix, parallelized using OpenMP. Normally\n  // the user would call the jacobian or jacobian_forward functions,\n  // and the OpenMP version would only be called if OpenMP is\n  // available and the Jacobian matrix is large enough for\n  // parallelization to be worthwhile.  Note that jacobian_out must be\n  // allocated to be of size m*n, where m is the number of dependent\n  // variables and n is the number of independents. The independents\n  // and dependents must have already been identified with the\n  // functions \"independent\" and \"dependent\", otherwise this function\n  // will fail with FAILURE_XXDEPENDENT_NOT_IDENTIFIED. In the\n  // resulting matrix, the \"m\" dimension of the matrix varies\n  // fastest. This is implemented using a forward pass, appropriate\n  // for m>=n.\n  void\n  Stack::jacobian_forward_openmp(Real* jacobian_out) const\n  {\n\n    // Number of blocks to cycle through, including a possible last\n    // block containing fewer than MULTIPASS_SIZE variables\n    int n_block = (n_independent() + MULTIPASS_SIZE - 1)\n      / MULTIPASS_SIZE;\n    uIndex n_extra = n_independent() % MULTIPASS_SIZE;\n    \n    int iblock;\n    \n#pragma omp parallel\n    {\n      //      std::vector<Block<MULTIPASS_SIZE,Real> > \n      //\tgradient_multipass_b(max_gradient_);\n      uIndex gradient_multipass_size = max_gradient_*MULTIPASS_SIZE;\n      Real* __restrict gradient_multipass_b \n\t= alloc_aligned<Real>(gradient_multipass_size);\n      \n#pragma omp for schedule(static)\n      for (iblock = 0; iblock < n_block; iblock++) {\n\t// Set the index to the dependent variables for this block\n\tuIndex i_independent =  MULTIPASS_SIZE * iblock;\n\t\n\tuIndex block_size = MULTIPASS_SIZE;\n\t// If this is the last iteration and the number of extra\n\t// elements is non-zero, then set the block size to the number\n\t// of extra elements. If the number of extra elements is zero,\n\t// then the number of independent variables is exactly divisible\n\t// by MULTIPASS_SIZE, so the last iteration will be the\n\t// same as all the rest.\n\tif (iblock == n_block-1 && n_extra > 0) {\n\t  block_size = n_extra;\n\t}\n\t\n\t// Set the initial gradients all to zero\n\tfor (std::size_t i = 0; i < gradient_multipass_size; i++) {\n\t  gradient_multipass_b[i] = 0.0;\n\t}\n\t// Each seed vector has one non-zero entry of 1.0\n\tfor (uIndex i = 0; i < block_size; i++) {\n\t  gradient_multipass_b[independent_index_[i_independent+i]*MULTIPASS_SIZE+i] = 1.0;\n\t}\n\n\tjacobian_forward_kernel(gradient_multipass_b);\n\n\t// Copy the gradients corresponding to the dependent variables\n\t// into the Jacobian matrix\n\tfor (uIndex idep = 0; idep < n_dependent(); idep++) {\n\t  for (uIndex i = 0; i < block_size; i++) {\n\t    jacobian_out[(i_independent+i)*n_dependent()+idep]\n\t      = gradient_multipass_b[dependent_index_[idep]*MULTIPASS_SIZE+i];\n\t  }\n\t}\n      } // End of loop over blocks\n      free_aligned(gradient_multipass_b);\n    } // End of parallel section\n  } // End of jacobian function\n\n\n  // Compute the Jacobian matrix; note that jacobian_out must be\n  // allocated to be of size m*n, where m is the number of dependent\n  // variables and n is the number of independents. The independents\n  // and dependents must have already been identified with the\n  // functions \"independent\" and \"dependent\", otherwise this function\n  // will fail with FAILURE_XXDEPENDENT_NOT_IDENTIFIED. In the\n  // resulting matrix, the \"m\" dimension of the matrix varies\n  // fastest. This is implemented using a forward pass, appropriate\n  // for m>=n.\n  void\n  Stack::jacobian_forward(Real* jacobian_out)\n  {\n    if (independent_index_.empty() || dependent_index_.empty()) {\n      //throw(dependents_or_independents_not_identified());\n      printf(\"dependents or independents not identified\\n\");\n      assert(false);\n    }\n#ifdef _OPENMP\n    if (have_openmp_ \n\t&& !openmp_manually_disabled_\n\t&& n_independent() > MULTIPASS_SIZE\n\t&& omp_get_max_threads() > 1) {\n      // Call the parallel version\n      jacobian_forward_openmp(jacobian_out);\n      return;\n    }\n#endif\n\n    // For optimization reasons, we process a block of\n    // MULTIPASS_SIZE columns of the Jacobian at once; calculate\n    // how many blocks are needed and how many extras will remain\n    uIndex n_block = n_independent() / MULTIPASS_SIZE;\n    uIndex n_extra = n_independent() % MULTIPASS_SIZE;\n\n    ///gradient_multipass_.resize(max_gradient_);\n    uIndex gradient_multipass_size = max_gradient_*MULTIPASS_SIZE;\n    Real* __restrict gradient_multipass_b \n      = alloc_aligned<Real>(gradient_multipass_size);\n\n    // Loop over blocks of MULTIPASS_SIZE columns\n    for (uIndex iblock = 0; iblock < n_block; iblock++) {\n      // Set the index to the dependent variables for this block\n      uIndex i_independent =  MULTIPASS_SIZE * iblock;\n\n      // Set the initial gradients all to zero\n      ///zero_gradient_multipass();\n      for (std::size_t i = 0; i < gradient_multipass_size; i++) {\n\tgradient_multipass_b[i] = 0.0;\n      }\n\n      // Each seed vector has one non-zero entry of 1.0\n      for (uIndex i = 0; i < MULTIPASS_SIZE; i++) {\n\tgradient_multipass_b[independent_index_[i_independent+i]*MULTIPASS_SIZE+i] = 1.0;\n      }\n\n      jacobian_forward_kernel(gradient_multipass_b);\n\n      // Copy the gradients corresponding to the dependent variables\n      // into the Jacobian matrix\n      for (uIndex idep = 0; idep < n_dependent(); idep++) {\n\tfor (uIndex i = 0; i < MULTIPASS_SIZE; i++) {\n\t  jacobian_out[(i_independent+i)*n_dependent()+idep] \n\t    = gradient_multipass_b[dependent_index_[idep]*MULTIPASS_SIZE+i];\n\t}\n      }\n      i_independent += MULTIPASS_SIZE;\n    } // End of loop over blocks\n    \n    // Now do the same but for the remaining few columns in the matrix\n    if (n_extra > 0) {\n      uIndex i_independent =  MULTIPASS_SIZE * n_block;\n      ///zero_gradient_multipass();\n      for (std::size_t i = 0; i < gradient_multipass_size; i++) {\n\tgradient_multipass_b[i] = 0.0;\n      }\n\n      for (uIndex i = 0; i < n_extra; i++) {\n\tgradient_multipass_b[independent_index_[i_independent+i]*MULTIPASS_SIZE+i] = 1.0;\n      }\n\n      jacobian_forward_kernel_extra(gradient_multipass_b, n_extra);\n\n      for (uIndex idep = 0; idep < n_dependent(); idep++) {\n\tfor (uIndex i = 0; i < n_extra; i++) {\n\t  jacobian_out[(i_independent+i)*n_dependent()+idep] \n\t    = gradient_multipass_b[dependent_index_[idep]*MULTIPASS_SIZE+i];\n\t}\n      }\n    }\n\n    free_aligned(gradient_multipass_b);\n  }\n\n\n  // Compute the Jacobian matrix, parallelized using OpenMP.  Normally\n  // the user would call the jacobian or jacobian_reverse functions,\n  // and the OpenMP version would only be called if OpenMP is\n  // available and the Jacobian matrix is large enough for\n  // parallelization to be worthwhile.  Note that jacobian_out must be\n  // allocated to be of size m*n, where m is the number of dependent\n  // variables and n is the number of independents. The independents\n  // and dependents must have already been identified with the\n  // functions \"independent\" and \"dependent\", otherwise this function\n  // will fail with FAILURE_XXDEPENDENT_NOT_IDENTIFIED. In the\n  // resulting matrix, the \"m\" dimension of the matrix varies\n  // fastest. This is implemented using a reverse pass, appropriate\n  // for m<n.\n  void\n  Stack::jacobian_reverse_openmp(Real* jacobian_out) const\n  {\n\n    // Number of blocks to cycle through, including a possible last\n    // block containing fewer than MULTIPASS_SIZE variables\n    int n_block = (n_dependent() + MULTIPASS_SIZE - 1)\n      / MULTIPASS_SIZE;\n    uIndex n_extra = n_dependent() % MULTIPASS_SIZE;\n    \n    int iblock;\n\n    // Inside the OpenMP loop, the \"this\" pointer may be NULL if the\n    // adept::Stack pointer is declared as thread-local and if the\n    // OpenMP memory model uses thread-local storage for private\n    // data. If this is the case then local pointers to or copies of\n    // the following members of the adept::Stack object may need to be\n    // made: dependent_index_ n_statements_ statement_ multiplier_\n    // index_ independent_index_ n_dependent() n_independent().\n    // Limited testing implies this is OK though.\n\n#pragma omp parallel\n    {\n      std::vector<Block<MULTIPASS_SIZE,Real> > \n\tgradient_multipass_b(max_gradient_);\n      \n#pragma omp for schedule(static)\n      for (iblock = 0; iblock < n_block; iblock++) {\n\t// Set the index to the dependent variables for this block\n\tuIndex i_dependent =  MULTIPASS_SIZE * iblock;\n\t\n\tuIndex block_size = MULTIPASS_SIZE;\n\t// If this is the last iteration and the number of extra\n\t// elements is non-zero, then set the block size to the number\n\t// of extra elements. If the number of extra elements is zero,\n\t// then the number of independent variables is exactly divisible\n\t// by MULTIPASS_SIZE, so the last iteration will be the\n\t// same as all the rest.\n\tif (iblock == n_block-1 && n_extra > 0) {\n\t  block_size = n_extra;\n\t}\n\n\t// Set the initial gradients all to zero\n\tfor (std::size_t i = 0; i < gradient_multipass_b.size(); i++) {\n\t  gradient_multipass_b[i].zero();\n\t}\n\t// Each seed vector has one non-zero entry of 1.0\n\tfor (uIndex i = 0; i < block_size; i++) {\n\t  gradient_multipass_b[dependent_index_[i_dependent+i]][i] = 1.0;\n\t}\n\n\t// Loop backward through the derivative statements\n\tfor (uIndex ist = n_statements_-1; ist > 0; ist--) {\n\t  const Statement& statement = statement_[ist];\n\t  // We copy the RHS to \"a\" in case it appears on the LHS in any\n\t  // of the following statements\n\t  Real a[MULTIPASS_SIZE];\n#if MULTIPASS_SIZE > MULTIPASS_SIZE_ZERO_CHECK\n\t  // For large blocks, we only process the ones where a[i] is\n\t  // non-zero\n\t  uIndex i_non_zero[MULTIPASS_SIZE];\n#endif\n\t  uIndex n_non_zero = 0;\n\t  for (uIndex i = 0; i < block_size; i++) {\n\t    a[i] = gradient_multipass_b[statement.index][i];\n\t    gradient_multipass_b[statement.index][i] = 0.0;\n\t    if (a[i] != 0.0) {\n#if MULTIPASS_SIZE > MULTIPASS_SIZE_ZERO_CHECK\n\t      i_non_zero[n_non_zero++] = i;\n#else\n\t      n_non_zero = 1;\n#endif\n\t    }\n\t  }\n\n\t  // Only do anything for this statement if any of the a values\n\t  // are non-zero\n\t  if (n_non_zero) {\n\t    // Loop through the operations\n\t    for (uIndex iop = statement_[ist-1].end_plus_one;\n\t\t iop < statement.end_plus_one; iop++) {\n\t      // Try to minimize pointer dereferencing by making local\n\t      // copies\n\t      Real multiplier = multiplier_[iop];\n\t      Real* __restrict gradient_multipass \n\t\t= &(gradient_multipass_b[index_[iop]][0]);\n#if MULTIPASS_SIZE > MULTIPASS_SIZE_ZERO_CHECK\n\t      // For large blocks, loop over only the indices\n\t      // corresponding to non-zero a\n\t      for (uIndex i = 0; i < n_non_zero; i++) {\n\t\tgradient_multipass[i_non_zero[i]] += multiplier*a[i_non_zero[i]];\n\t      }\n#else\n\t      // For small blocks, do all indices\n\t      for (uIndex i = 0; i < block_size; i++) {\n\t      //\t      for (uIndex i = 0; i < MULTIPASS_SIZE; i++) {\n\t\tgradient_multipass[i] += multiplier*a[i];\n\t      }\n#endif\n\t    }\n\t  }\n\t} // End of loop over statement\n\t// Copy the gradients corresponding to the independent\n\t// variables into the Jacobian matrix\n\tfor (uIndex iindep = 0; iindep < n_independent(); iindep++) {\n\t  for (uIndex i = 0; i < block_size; i++) {\n\t    jacobian_out[iindep*n_dependent()+i_dependent+i] \n\t      = gradient_multipass_b[independent_index_[iindep]][i];\n\t  }\n\t}\n      } // End of loop over blocks\n    } // end #pragma omp parallel\n  } // end jacobian_reverse_openmp\n\n\n  // Compute the Jacobian matrix; note that jacobian_out must be\n  // allocated to be of size m*n, where m is the number of dependent\n  // variables and n is the number of independents. The independents\n  // and dependents must have already been identified with the\n  // functions \"independent\" and \"dependent\", otherwise this function\n  // will fail with FAILURE_XXDEPENDENT_NOT_IDENTIFIED. In the\n  // resulting matrix, the \"m\" dimension of the matrix varies\n  // fastest. This is implemented using a reverse pass, appropriate\n  // for m<n.\n  void\n  Stack::jacobian_reverse(Real* jacobian_out)\n  {\n    if (independent_index_.empty() || dependent_index_.empty()) {\n      //throw(dependents_or_independents_not_identified());\n      printf(\"dependents or independents not identified\\n\");\n      assert(false);\n    }\n#ifdef _OPENMP\n    if (have_openmp_ \n\t&& !openmp_manually_disabled_\n\t&& n_dependent() > MULTIPASS_SIZE\n\t&& omp_get_max_threads() > 1) {\n      // Call the parallel version\n      jacobian_reverse_openmp(jacobian_out);\n      return;\n    }\n#endif\n\n    //    gradient_multipass_.resize(max_gradient_);\n    std::vector<Block<MULTIPASS_SIZE,Real> > \n      gradient_multipass_b(max_gradient_);\n\n    // For optimization reasons, we process a block of\n    // MULTIPASS_SIZE rows of the Jacobian at once; calculate\n    // how many blocks are needed and how many extras will remain\n    uIndex n_block = n_dependent() / MULTIPASS_SIZE;\n    uIndex n_extra = n_dependent() % MULTIPASS_SIZE;\n    uIndex i_dependent = 0; // uIndex of first row in the block we are\n\t\t\t    // currently computing\n    // Loop over the of MULTIPASS_SIZE rows\n    for (uIndex iblock = 0; iblock < n_block; iblock++) {\n      // Set the initial gradients all to zero\n      //      zero_gradient_multipass();\n      for (std::size_t i = 0; i < gradient_multipass_b.size(); i++) {\n\tgradient_multipass_b[i].zero();\n      }\n\n      // Each seed vector has one non-zero entry of 1.0\n      for (uIndex i = 0; i < MULTIPASS_SIZE; i++) {\n\tgradient_multipass_b[dependent_index_[i_dependent+i]][i] = 1.0;\n      }\n      // Loop backward through the derivative statements\n      for (uIndex ist = n_statements_-1; ist > 0; ist--) {\n\tconst Statement& statement = statement_[ist];\n\t// We copy the RHS to \"a\" in case it appears on the LHS in any\n\t// of the following statements\n\tReal a[MULTIPASS_SIZE];\n#if MULTIPASS_SIZE > MULTIPASS_SIZE_ZERO_CHECK\n\t// For large blocks, we only process the ones where a[i] is\n\t// non-zero\n\tuIndex i_non_zero[MULTIPASS_SIZE];\n#endif\n\tuIndex n_non_zero = 0;\n\tfor (uIndex i = 0; i < MULTIPASS_SIZE; i++) {\n\t  a[i] = gradient_multipass_b[statement.index][i];\n\t  gradient_multipass_b[statement.index][i] = 0.0;\n\t  if (a[i] != 0.0) {\n#if MULTIPASS_SIZE > MULTIPASS_SIZE_ZERO_CHECK\n\t    i_non_zero[n_non_zero++] = i;\n#else\n\t    n_non_zero = 1;\n#endif\n\t  }\n\t}\n\t// Only do anything for this statement if any of the a values\n\t// are non-zero\n\tif (n_non_zero) {\n\t  // Loop through the operations\n\t  for (uIndex iop = statement_[ist-1].end_plus_one;\n\t       iop < statement.end_plus_one; iop++) {\n\t    // Try to minimize pointer dereferencing by making local\n\t    // copies\n\t    Real multiplier = multiplier_[iop];\n\t    Real* __restrict gradient_multipass \n\t      = &(gradient_multipass_b[index_[iop]][0]);\n#if MULTIPASS_SIZE > MULTIPASS_SIZE_ZERO_CHECK\n\t    // For large blocks, loop over only the indices\n\t    // corresponding to non-zero a\n\t    for (uIndex i = 0; i < n_non_zero; i++) {\n\t      gradient_multipass[i_non_zero[i]] += multiplier*a[i_non_zero[i]];\n\t    }\n#else\n\t    // For small blocks, do all indices\n\t    for (uIndex i = 0; i < MULTIPASS_SIZE; i++) {\n\t      gradient_multipass[i] += multiplier*a[i];\n\t    }\n#endif\n\t  }\n\t}\n      } // End of loop over statement\n      // Copy the gradients corresponding to the independent variables\n      // into the Jacobian matrix\n      for (uIndex iindep = 0; iindep < n_independent(); iindep++) {\n\tfor (uIndex i = 0; i < MULTIPASS_SIZE; i++) {\n\t  jacobian_out[iindep*n_dependent()+i_dependent+i] \n\t    = gradient_multipass_b[independent_index_[iindep]][i];\n\t}\n      }\n      i_dependent += MULTIPASS_SIZE;\n    } // End of loop over blocks\n    \n    // Now do the same but for the remaining few rows in the matrix\n    if (n_extra > 0) {\n      for (std::size_t i = 0; i < gradient_multipass_b.size(); i++) {\n\tgradient_multipass_b[i].zero();\n      }\n      //      zero_gradient_multipass();\n      for (uIndex i = 0; i < n_extra; i++) {\n\tgradient_multipass_b[dependent_index_[i_dependent+i]][i] = 1.0;\n      }\n      for (uIndex ist = n_statements_-1; ist > 0; ist--) {\n\tconst Statement& statement = statement_[ist];\n\tReal a[MULTIPASS_SIZE];\n#if MULTIPASS_SIZE > MULTIPASS_SIZE_ZERO_CHECK\n\tuIndex i_non_zero[MULTIPASS_SIZE];\n#endif\n\tuIndex n_non_zero = 0;\n\tfor (uIndex i = 0; i < n_extra; i++) {\n\t  a[i] = gradient_multipass_b[statement.index][i];\n\t  gradient_multipass_b[statement.index][i] = 0.0;\n\t  if (a[i] != 0.0) {\n#if MULTIPASS_SIZE > MULTIPASS_SIZE_ZERO_CHECK\n\t    i_non_zero[n_non_zero++] = i;\n#else\n\t    n_non_zero = 1;\n#endif\n\t  }\n\t}\n\tif (n_non_zero) {\n\t  for (uIndex iop = statement_[ist-1].end_plus_one;\n\t       iop < statement.end_plus_one; iop++) {\n\t    Real multiplier = multiplier_[iop];\n\t    Real* __restrict gradient_multipass \n\t      = &(gradient_multipass_b[index_[iop]][0]);\n\t    //\t    if (index_[iop] > max_gradient_-1\n\t    //\t\t|| index_[iop] < 0) {\n\t    //\t    std::cerr << \"AAAAAA: iop=\" << iop << \" index_[iop]=\" << index_[iop] << \" max_gradient_=\" << max_gradient_ << \" ist=\" << ist << \"\\n\";\n\t      //\t    }\n#if MULTIPASS_SIZE > MULTIPASS_SIZE_ZERO_CHECK\n\t    for (uIndex i = 0; i < n_non_zero; i++) {\n\t      gradient_multipass[i_non_zero[i]] += multiplier*a[i_non_zero[i]];\n\t    }\n#else\n\t    for (uIndex i = 0; i < n_extra; i++) {\n\t      //\t      std::cerr << \"BBBBB: i=\" << i << \" gradient_multipass[i]=\" << gradient_multipass[i] << \" multiplier=\" << multiplier << \" a[i]=\" << a[i] << \"\\n\";\n\t      gradient_multipass[i] += multiplier*a[i];\n\t    }\n#endif\n\t  }\n\t}\n      }\n      for (uIndex iindep = 0; iindep < n_independent(); iindep++) {\n\tfor (uIndex i = 0; i < n_extra; i++) {\n\t  jacobian_out[iindep*n_dependent()+i_dependent+i] \n\t    = gradient_multipass_b[independent_index_[iindep]][i];\n\t}\n      }\n    }\n  }\n\n  // Compute the Jacobian matrix; note that jacobian_out must be\n  // allocated to be of size m*n, where m is the number of dependent\n  // variables and n is the number of independents. In the resulting\n  // matrix, the \"m\" dimension of the matrix varies fastest. This is\n  // implemented by calling one of jacobian_forward and\n  // jacobian_reverse, whichever would be faster.\n  void\n  Stack::jacobian(Real* jacobian_out)\n  {\n    //    std::cout << \">>> Computing \" << n_dependent() << \"x\" << n_independent()\n    //\t      << \" Jacobian from \" << n_statements_ << \" statements, \"\n    //\t      << n_operations() << \" operations and \" << max_gradient_ << \" gradients\\n\";\n\n    if (n_independent() <= n_dependent()) {\n      jacobian_forward(jacobian_out);\n    }\n    else {\n      jacobian_reverse(jacobian_out);\n    }\n  }\n  \n} // End namespace adept\n\n\n// =================================================================\n// Contents of settings.cpp\n// =================================================================\n\n/* settings.cpp -- View/change the overall Adept settings\n\n    Copyright (C) 2016 European Centre for Medium-Range Weather Forecasts\n\n    Author: Robin Hogan <r.j.hogan@ecmwf.int>\n\n    This file is part of the Adept library.\n\n*/\n\n#include <sstream>\n#include <cstring>\n\n#include <adept/base.h>\n#include <adept/settings.h>\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#ifdef HAVE_OPENBLAS_CBLAS_HEADER\n#include <cblas.h>\n#endif\n\nnamespace adept {\n\n  // -------------------------------------------------------------------\n  // Get compile-time settings\n  // -------------------------------------------------------------------\n\n  // Return the version of Adept at compile time\n  std::string\n  version()\n  {\n    return ADEPT_VERSION_STR;\n  }\n\n  // Return the compiler used to compile the Adept library (e.g. \"g++\n  // [4.3.2]\" or \"Microsoft Visual C++ [1800]\")\n  std::string\n  compiler_version()\n  {\n#ifdef CXX\n    std::string cv = CXX; // Defined in config.h\n#elif defined(_MSC_VER)\n    std::string cv = \"Microsoft Visual C++\";\n#else\n    std::string cv = \"unknown\";\n#endif\n\n#ifdef __GNUC__\n\n#define STRINGIFY3(A,B,C) STRINGIFY(A) \".\" STRINGIFY(B) \".\" STRINGIFY(C)\n#define STRINGIFY(A) #A\n    cv += \" [\" STRINGIFY3(__GNUC__,__GNUC_MINOR__,__GNUC_PATCHLEVEL__) \"]\";\n#undef STRINGIFY\n#undef STRINGIFY3\n\n#elif defined(_MSC_VER)\n\n#define STRINGIFY1(A) STRINGIFY(A)\n#define STRINGIFY(A) #A\n    cv += \" [\" STRINGIFY1(_MSC_VER) \"]\";\n#undef STRINGIFY\n#undef STRINGIFY1\n\n#endif\n    return cv;\n  }\n\n  // Return the compiler flags used when compiling the Adept library\n  // (e.g. \"-Wall -g -O3\")\n  std::string\n  compiler_flags()\n  {\n#ifdef CXXFLAGS\n    return CXXFLAGS; // Defined in config.h\n#else\n    return \"unknown\";\n#endif\n  }\n\n  // Return a multi-line string listing numerous aspects of the way\n  // Adept has been configured.\n  std::string\n  configuration()\n  {\n    std::stringstream s;\n    s << \"Adept version \" << adept::version() << \":\\n\";\n    s << \"  Compiled with \" << adept::compiler_version() << \"\\n\";\n    s << \"  Compiler flags \\\"\" << adept::compiler_flags() << \"\\\"\\n\";\n#ifdef BLAS_LIBS\n    if (std::strlen(BLAS_LIBS) > 2) {\n      const char* blas_libs = BLAS_LIBS + 2;\n      s << \"  BLAS support from \" << blas_libs << \" library\\n\";\n    }\n    else {\n      s << \"  BLAS support from built-in library\\n\";\n    }\n#endif\n#ifdef HAVE_OPENBLAS_CBLAS_HEADER\n    s << \"  Number of BLAS threads may be specified up to maximum of \"\n      << max_blas_threads() << \"\\n\";\n#endif\n    s << \"  Jacobians processed in blocks of size \" \n      << ADEPT_MULTIPASS_SIZE << \"\\n\";\n    return s.str();\n  }\n\n\n  // -------------------------------------------------------------------\n  // Get/set number of threads for array operations\n  // -------------------------------------------------------------------\n\n  // Get the maximum number of threads available for BLAS operations\n  int\n  max_blas_threads()\n  {\n#ifdef HAVE_OPENBLAS_CBLAS_HEADER\n    return openblas_get_num_threads();\n#else\n    return 1;\n#endif\n  }\n\n  // Set the maximum number of threads available for BLAS operations\n  // (zero means use the maximum sensible number on the current\n  // system), and return the number actually set. Note that OpenBLAS\n  // uses pthreads and the Jacobian calculation uses OpenMP - this can\n  // lead to inefficient behaviour so if you are computing Jacobians\n  // then you may get better performance by setting the number of\n  // array threads to one.\n  int\n  set_max_blas_threads(int n)\n  {\n#ifdef HAVE_OPENBLAS_CBLAS_HEADER\n    openblas_set_num_threads(n);\n    return openblas_get_num_threads();\n#else\n    return 1;\n#endif\n  }\n\n  // Was the library compiled with matrix multiplication support (from\n  // BLAS)?\n  bool\n  have_matrix_multiplication() {\n#ifdef HAVE_BLAS\n    return true;\n#else\n    return false;\n#endif\n  }\n\n  // Was the library compiled with linear algebra support (e.g. inv\n  // and solve from LAPACK)\n  bool\n  have_linear_algebra() {\n#ifdef HAVE_LAPACK\n    return true;\n#else\n    return false;\n#endif\n  }\n\n} // End namespace adept\n\n\n// =================================================================\n// Contents of solve.cpp\n// =================================================================\n\n/* solve.cpp -- Solve systems of linear equations using LAPACK\n\n    Copyright (C) 2015-2016 European Centre for Medium-Range Weather Forecasts\n\n    Author: Robin Hogan <r.j.hogan@ecmwf.int>\n\n    This file is part of the Adept library.\n*/\n                             \n\n#include <vector>\n\n\n#include <adept/solve.h>\n#include <adept/Array.h>\n#include <adept/SpecialMatrix.h>\n\n// If ADEPT_SOURCE_H is defined then we are in a header file generated\n// from all the source files, so cpplapack.h will already have been\n// included\n#ifndef AdeptSource_H\n#include \"cpplapack.h\"\n#endif\n\n#ifdef HAVE_LAPACK\n\nnamespace adept {\n\n  // -------------------------------------------------------------------\n  // Solve Ax = b for general square matrix A\n  // -------------------------------------------------------------------\n  template <typename T>\n  Array<1,T,false> \n  solve(const Array<2,T,false>& A, const Array<1,T,false>& b) {\n    Array<2,T,false> A_;\n    Array<1,T,false> b_;\n\n    // LAPACKE is more efficient with column-major input\n    // if (A.is_row_contiguous()) {\n      A_.resize_column_major(A.dimensions());\n      A_ = A;\n    // }\n    // else {\n    //   A_.link(A);\n    // }\n\n    // if (b_.offset(0) != 0) {\n      b_ = b;\n    // }\n    // else {\n    //   b_.link(b);\n    // }\n\n    std::vector<lapack_int> ipiv(A_.dimension(0));\n\n    //    lapack_int status = LAPACKE_dgesv(LAPACK_COL_MAJOR, A_.dimension(0), 1,\n    //\t\t\t\t      A_.data(), A_.offset(1), &ipiv[0],\n    //\t\t\t\t      b_.data(), b_.dimension(0));\n    lapack_int status = cpplapack_gesv(A_.dimension(0), 1,\n\t\t\t\t       A_.data(), A_.offset(1), &ipiv[0],\n\t\t\t\t       b_.data(), b_.dimension(0));\n\n    if (status != 0) {\n      std::stringstream s;\n      s << \"Failed to solve general system of equations: LAPACK ?gesv returned code \" << status;\n      //throw(matrix_ill_conditioned(s.str() ADEPT_EXCEPTION_LOCATION));\n      printf(\"matrix ill conditioned\\n\");\n      assert(false);\n    }\n    return b_;    \n  }\n\n  // -------------------------------------------------------------------\n  // Solve AX = B for general square matrix A and rectangular matrix B\n  // -------------------------------------------------------------------\n  template <typename T>\n  Array<2,T,false> \n  solve(const Array<2,T,false>& A, const Array<2,T,false>& B) {\n    Array<2,T,false> A_;\n    Array<2,T,false> B_;\n    \n    // LAPACKE is more efficient with column-major input\n    // if (A.is_row_contiguous()) {\n      A_.resize_column_major(A.dimensions());\n      A_ = A;\n    // }\n    // else {\n    //   A_.link(A);\n    // }\n\n    // if (B.is_row_contiguous()) {\n      B_.resize_column_major(B.dimensions());\n      B_ = B;\n    // }\n    // else {\n    //   B_.link(B);\n    // }\n\n    std::vector<lapack_int> ipiv(A_.dimension(0));\n\n    //    lapack_int status = LAPACKE_dgesv(LAPACK_COL_MAJOR, A_.dimension(0), B.dimension(1),\n    //\t\t\t\t      A_.data(), A_.offset(1), &ipiv[0],\n    //\t\t\t\t      B_.data(), B_.offset(1));\n    lapack_int status = cpplapack_gesv(A_.dimension(0), B.dimension(1),\n\t\t\t\t       A_.data(), A_.offset(1), &ipiv[0],\n\t\t\t\t       B_.data(), B_.offset(1));\n    if (status != 0) {\n      std::stringstream s;\n      s << \"Failed to solve general system of equations for matrix RHS: LAPACK ?gesv returned code \" << status;\n      //throw(matrix_ill_conditioned(s.str() ADEPT_EXCEPTION_LOCATION));\n      printf(\"matrix ill conditioned\\n\");\n      assert(false);\n    }\n    return B_;    \n  }\n\n\n  // -------------------------------------------------------------------\n  // Solve Ax = b for symmetric square matrix A\n  // -------------------------------------------------------------------\n  template <typename T, SymmMatrixOrientation Orient>\n  Array<1,T,false>\n  solve(const SpecialMatrix<T,SymmEngine<Orient>,false>& A,\n\tconst Array<1,T,false>& b) {\n    SpecialMatrix<T,SymmEngine<Orient>,false> A_;\n    Array<1,T,false> b_;\n\n    // Not sure why the original code copies A...\n    A_.resize(A.dimension());\n    A_ = A;\n    // A_.link(A);\n\n    // if (b.offset(0) != 1) {\n      b_ = b;\n    // }\n    // else {\n    //   b_.link(b);\n    // }\n\n    // Treat symmetric matrix as column-major\n    char uplo;\n    if (Orient == ROW_LOWER_COL_UPPER) {\n      uplo = 'U';\n    }\n    else {\n      uplo = 'L';\n    }\n\n    std::vector<lapack_int> ipiv(A_.dimension());\n\n    //    lapack_int status = LAPACKE_dsysv(LAPACK_COL_MAJOR, uplo, A_.dimension(0), 1,\n    //\t\t\t\t      A_.data(), A_.offset(), &ipiv[0],\n    //\t\t\t\t      b_.data(), b_.dimension(0));\n    lapack_int status = cpplapack_sysv(uplo, A_.dimension(0), 1,\n\t\t\t\t       A_.data(), A_.offset(), &ipiv[0],\n\t\t\t\t       b_.data(), b_.dimension(0));\n\n    if (status != 0) {\n      //      std::stringstream s;\n      //      s << \"Failed to solve symmetric system of equations: LAPACK ?sysv returned code \" << status;\n      //      throw(matrix_ill_conditioned(s.str() ADEPT_EXCEPTION_LOCATION));\n      std::cerr << \"Warning: LAPACK solve symmetric system failed (?sysv): trying general (?gesv)\\n\";\n      return solve(Array<2,T,false>(A_),b_);\n    }\n    return b_;    \n  }\n\n\n  // -------------------------------------------------------------------\n  // Solve AX = B for symmetric square matrix A\n  // -------------------------------------------------------------------\n  template <typename T, SymmMatrixOrientation Orient>\n  Array<2,T,false>\n  solve(const SpecialMatrix<T,SymmEngine<Orient>,false>& A,\n\tconst Array<2,T,false>& B) {\n    SpecialMatrix<T,SymmEngine<Orient>,false> A_;\n    Array<2,T,false> B_;\n\n    A_.resize(A.dimension());\n    A_ = A;\n    // A_.link(A);\n\n    // if (B.is_row_contiguous()) {\n      B_.resize_column_major(B.dimensions());\n      B_ = B;\n    // }\n    // else {\n    //   B_.link(B);\n    // }\n\n    // Treat symmetric matrix as column-major\n    char uplo;\n    if (Orient == ROW_LOWER_COL_UPPER) {\n      uplo = 'U';\n    }\n    else {\n      uplo = 'L';\n    }\n\n    std::vector<lapack_int> ipiv(A_.dimension());\n\n    //    lapack_int status = LAPACKE_dsysv(LAPACK_COL_MAJOR, uplo, A_.dimension(0), B.dimension(1),\n    //\t\t\t\t      A_.data(), A_.offset(), &ipiv[0],\n    //\t\t\t\t      B_.data(), B_.offset(1));\n    lapack_int status = cpplapack_sysv(uplo, A_.dimension(0), B.dimension(1),\n\t\t\t\t       A_.data(), A_.offset(), &ipiv[0],\n\t\t\t\t       B_.data(), B_.offset(1));\n\n    if (status != 0) {\n      std::stringstream s;\n      s << \"Failed to solve symmetric system of equations with matrix RHS: LAPACK ?sysv returned code \" << status;\n      //throw(matrix_ill_conditioned(s.str() ADEPT_EXCEPTION_LOCATION));\n      printf(\"matrix ill conditioned\\n\");\n      assert(false);\n    }\n    return B_;\n  }\n\n}\n\n#else\n\nnamespace adept {\n  \n  // -------------------------------------------------------------------\n  // Solve Ax = b for general square matrix A\n  // -------------------------------------------------------------------\n  template <typename T>\n  Array<1,T,false> \n  solve(const Array<2,T,false>& A, const Array<1,T,false>& b) {\n    //throw feature_not_available(\"Cannot solve linear equations because compiled without LAPACK\");\n    printf(\"feature not available\\n\");\n    assert(false);\n  }\n\n  // -------------------------------------------------------------------\n  // Solve AX = B for general square matrix A and rectangular matrix B\n  // -------------------------------------------------------------------\n  template <typename T>\n  Array<2,T,false> \n  solve(const Array<2,T,false>& A, const Array<2,T,false>& B) {\n    //throw feature_not_available(\"Cannot solve linear equations because compiled without LAPACK\");\n    printf(\"feature not available\\n\");\n    assert(false);\n  }\n\n  // -------------------------------------------------------------------\n  // Solve Ax = b for symmetric square matrix A\n  // -------------------------------------------------------------------\n  template <typename T, SymmMatrixOrientation Orient>\n  Array<1,T,false>\n  solve(const SpecialMatrix<T,SymmEngine<Orient>,false>& A,\n\tconst Array<1,T,false>& b) {\n    //throw feature_not_available(\"Cannot solve linear equations because compiled without LAPACK\");\n    printf(\"feature not available\\n\");\n    assert(false);\n  }\n\n  // -------------------------------------------------------------------\n  // Solve AX = B for symmetric square matrix A\n  // -------------------------------------------------------------------\n  template <typename T, SymmMatrixOrientation Orient>\n  Array<2,T,false>\n  solve(const SpecialMatrix<T,SymmEngine<Orient>,false>& A,\n\tconst Array<2,T,false>& B) {\n    //throw feature_not_available(\"Cannot solve linear equations because compiled without LAPACK\");\n    printf(\"feature not available\\n\");\n    assert(false);\n  }\n\n}\n\n#endif\n\n\nnamespace adept {\n\n  // -------------------------------------------------------------------\n  // Explicit instantiations\n  // -------------------------------------------------------------------\n#define ADEPT_EXPLICIT_SOLVE(TYPE,RRANK)\t\t\t\t\\\n  template Array<RRANK,TYPE,false>\t\t\t\t\t\\\n  solve(const Array<2,TYPE,false>& A, const Array<RRANK,TYPE,false>& b); \\\n  template Array<RRANK,TYPE,false>\t\t\t\t\t\\\n  solve(const SpecialMatrix<TYPE,SymmEngine<ROW_LOWER_COL_UPPER>,false>& A, \\\n\tconst Array<RRANK,TYPE,false>& b);\t\t\t\t\t\\\n  template Array<RRANK,TYPE,false>\t\t\t\t\t\\\n  solve(const SpecialMatrix<TYPE,SymmEngine<ROW_UPPER_COL_LOWER>,false>& A, \\\n\tconst Array<RRANK,TYPE,false>& b);\n\n  ADEPT_EXPLICIT_SOLVE(float,1)\n  ADEPT_EXPLICIT_SOLVE(float,2)\n  ADEPT_EXPLICIT_SOLVE(double,1)\n  ADEPT_EXPLICIT_SOLVE(double,2)\n#undef ADEPT_EXPLICIT_SOLVE\n\n}\n\n\n\n// =================================================================\n// Contents of vector_utilities.cpp\n// =================================================================\n\n/* vector_utilities.cpp -- Vector utility functions\n\n    Copyright (C) 2016 European Centre for Medium-Range Weather Forecasts\n\n    Author: Robin Hogan <r.j.hogan@ecmwf.int>\n\n    This file is part of the Adept library.\n\n*/\n\n#include <adept/vector_utilities.h>\n\nnamespace adept {\n\n  Array<1,Real,false>\n  linspace(Real x1, Real x2, Index n) {\n    Array<1,Real,false> ans(n);\n    if (n > 1) {\n      for (Index i = 0; i < n; ++i) {\n\tans(i) = x1 + (x2-x1)*i / static_cast<Real>(n-1);\n      }\n    }\n    else if (n == 1 && x1 == x2) {\n      ans(0) = x1;\n      return ans;\n    }\n    else if (n == 1) {\n      //throw(invalid_operation(\"linspace(x1,x2,n) with n=1 only valid if x1=x2\"));\n      printf(\"invalid operation\\n\");\n      assert(false);\n    }\n    return ans;\n  }\n\n}\n\n\n\n#endif\n\n", "meta": {"hexsha": "e1abf1a0e86440a7c68f2f19aa860a19d1862d57", "size": 91668, "ext": "h", "lang": "C", "max_stars_repo_path": "apps_enzymetest/adept-serial/include/adept_source.h", "max_stars_repo_name": "timkaler/ligra-gcn", "max_stars_repo_head_hexsha": "f6c4312dfec9a014c9db2e8d1c875476880dc363", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "apps_enzymetest/adept-serial/include/adept_source.h", "max_issues_repo_name": "timkaler/ligra-gcn", "max_issues_repo_head_hexsha": "f6c4312dfec9a014c9db2e8d1c875476880dc363", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "apps_enzymetest/adept-serial/include/adept_source.h", "max_forks_repo_name": "timkaler/ligra-gcn", "max_forks_repo_head_hexsha": "f6c4312dfec9a014c9db2e8d1c875476880dc363", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5294535131, "max_line_length": 161, "alphanum_fraction": 0.6181001004, "num_tokens": 24474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33458942798284697, "lm_q2_score": 0.02843603253025177, "lm_q1q2_score": 0.009514395858398568}}
{"text": "#ifndef _PARRSB_H_\n#define _PARRSB_H_\n\n#include <gslib.h>\n\ntypedef struct {\n  /* General options */\n  int global_partitioner; // -1 - None, 0 - RSB, 1 - RCB, 2 - RIB (Default: 0)\n  int local_partitioner;  // -1 - None, 0 - RSB, 1 - RCB, 2 - RIB (Default: -1)\n  int debug_level;        // 0, 1, 2, .. etc (Default: 0)\n  int print_timing_info;  // 0 or 1 (Default: 0)\n\n  /* RSB specific */\n  int rsb_algo;         // 0 - Lanczos, 1 - MG (Default: 0)\n  int rsb_prepartition; // 0 - None, 1 - RCB , 2 - RIB (Default: 1)\n  int rsb_grammian;     // 0 or 1 (Default: 1)\n} parRSB_options;\n\nextern parRSB_options parrsb_default_options;\n\n#define fparRSB_partMesh FORTRAN_UNPREFIXED(fparrsb_partmesh, FPARRSB_PARTMESH)\nvoid fparRSB_partMesh(int *part, int *seq, long long *vtx, double *coord,\n                      int *nel, int *nve, int *options, int *comm, int *err);\n\nint parRSB_partMesh(int *part, int *seq, long long *vtx, double *coord, int nel,\n                    int nv, parRSB_options *options, MPI_Comm comm);\n\n#define fparRSB_findConnectivity                                               \\\n  FORTRAN_UNPREFIXED(fparrsb_findconnectivity, FPARRSB_FINDCONNECTIVITY)\nvoid fparRSB_findConnectivity(long long *vertexId, double *coord, int *nel,\n                              int *nDim, long long *periodicInfo,\n                              int *nPeriodicFaces, double *tol, MPI_Fint *fcomm,\n                              int *verbose, int *err);\n\nint parRSB_findConnectivity(long long *vertexid, double *coord, int nel,\n                            int nDim, long long *periodicInfo,\n                            int nPeriodicFaces, double tol, MPI_Comm comm,\n                            int verbose);\n\n#endif\n", "meta": {"hexsha": "412f69437c84f83ff31d8a84a5e13760ec97fe30", "size": 1707, "ext": "h", "lang": "C", "max_stars_repo_path": "3rd_party/nek5000_parRSB/src/parRSB.h", "max_stars_repo_name": "RonRahaman/nekRS", "max_stars_repo_head_hexsha": "ffc02bca33ece6ba3330c4ee24565b1c6b5f7242", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-06T16:16:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T16:16:08.000Z", "max_issues_repo_path": "3rd_party/nek5000_parRSB/src/parRSB.h", "max_issues_repo_name": "neams-th-coe/nekRS", "max_issues_repo_head_hexsha": "5d2c8ab3d14b3fb16db35682336a1f96000698bb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3rd_party/nek5000_parRSB/src/parRSB.h", "max_forks_repo_name": "neams-th-coe/nekRS", "max_forks_repo_head_hexsha": "5d2c8ab3d14b3fb16db35682336a1f96000698bb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-10T20:12:48.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-10T20:12:48.000Z", "avg_line_length": 41.6341463415, "max_line_length": 80, "alphanum_fraction": 0.5998828354, "num_tokens": 500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.334589441253186, "lm_q2_score": 0.028436031089369332, "lm_q1q2_score": 0.00951439575365031}}
{"text": "#pragma once\n\n#if SEAL_COMPILER == SEAL_COMPILER_GCC\n\n// We require GCC >= 6\n#if (__GNUC__ < 6) || not defined(__cplusplus)\n#error \"SEAL requires __GNUC__ >= 6\" \n#endif\n\n// Read in config.h\n#include \"config.h\"\n\n// Are we using MSGSL?\n#ifdef SEAL_USE_MSGSL\n#include <gsl/gsl>\n#endif\n\n// Are intrinsics enabled?\n#ifdef SEAL_USE_INTRIN\n#include <x86intrin.h>\n\n#ifdef SEAL_USE___BUILTIN_CLZLL\n#define SEAL_MSB_INDEX_UINT64(result, value) {                                      \\\n    *result = 63 - __builtin_clzll(value);                                          \\\n}\n#endif \n\n#ifdef SEAL_USE___INT128\n#define SEAL_MULTIPLY_UINT64_HW64(operand1, operand2, hw64) {                       \\\n    *hw64 = static_cast<uint64_t>((static_cast<unsigned __int128>(operand1)         \\\n            * static_cast<unsigned __int128>(operand2)) >> 64);                     \\\n}\n\n#define SEAL_MULTIPLY_UINT64(operand1, operand2, result128) {                       \\\n    unsigned __int128 product = static_cast<unsigned __int128>(operand1) * operand2;\\\n    result128[0] = static_cast<uint64_t>(product);                                  \\\n    result128[1] = product >> 64;                                                   \\\n}\n#endif \n\n#ifdef SEAL_USE__ADDCARRY_U64\n#define SEAL_ADD_CARRY_UINT64(operand1, operand2, carry, result) _addcarry_u64(     \\\n    carry,                                                                          \\\n    static_cast<unsigned long long>(operand1),                                      \\\n    static_cast<unsigned long long>(operand2),                                      \\\n    reinterpret_cast<unsigned long long*>(result))\n#endif\n\n#ifdef SEAL_USE__SUBBORROW_U64\n#if ((__GNUC__ == 7) && (__GNUC_MINOR__ >= 2)) || (__GNUC__  >= 8)\n// The inverted arguments problem was fixed in GCC-7.2 \n// (https://patchwork.ozlabs.org/patch/784309/)\n#define SEAL_SUB_BORROW_UINT64(operand1, operand2, borrow, result) _subborrow_u64(  \\\n    borrow,                                                                         \\\n    static_cast<unsigned long long>(operand1),                                      \\\n    static_cast<unsigned long long>(operand2),                                      \\\n    reinterpret_cast<unsigned long long*>(result))\n#else\n// Warning: Note the inverted order of operand1 and operand2\n#define SEAL_SUB_BORROW_UINT64(operand1, operand2, borrow, result) _subborrow_u64(  \\\n    borrow,                                                                         \\\n    static_cast<unsigned long long>(operand2),                                      \\\n    static_cast<unsigned long long>(operand1),                                      \\\n    reinterpret_cast<unsigned long long*>(result))\n#endif //(__GNUC__ == 7) && (__GNUC_MINOR__ >= 2)\n#endif \n\n#endif //SEAL_USE_INTRIN\n\n#endif", "meta": {"hexsha": "1b2d4390f306d35eb8480635069e3cc80ca828c2", "size": 2796, "ext": "h", "lang": "C", "max_stars_repo_path": "SEAL/seal2/gcc.h", "max_stars_repo_name": "MarbleHE/SEAL4Pyfhel", "max_stars_repo_head_hexsha": "dca915e0964f6ae1b891876e64101f09c1ecfe08", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-19T17:09:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-27T06:25:36.000Z", "max_issues_repo_path": "SEAL/seal2/gcc.h", "max_issues_repo_name": "MarbleHE/SEAL4Pyfhel", "max_issues_repo_head_hexsha": "dca915e0964f6ae1b891876e64101f09c1ecfe08", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SEAL/seal2/gcc.h", "max_forks_repo_name": "MarbleHE/SEAL4Pyfhel", "max_forks_repo_head_hexsha": "dca915e0964f6ae1b891876e64101f09c1ecfe08", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-05-29T10:15:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-26T02:31:56.000Z", "avg_line_length": 39.9428571429, "max_line_length": 85, "alphanum_fraction": 0.5468526466, "num_tokens": 605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3242354120407358, "lm_q2_score": 0.029312227995466327, "lm_q1q2_score": 0.009504062321942015}}
{"text": "#pragma once\n\n#include <algorithm>\n#include <array>\n#include <bitset>\n#include <cassert>\n#include <cctype>\n#include <cerrno>\n#include <chrono>\n#include <climits>\n#include <cmath>\n#include <csignal>\n#include <cstdarg>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <memory>\n#include <numeric>\n#include <sstream>\n#include <stdexcept>\n#include <string>\n#include <thread>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\n#ifdef __linux__\n#define LINUX\n#endif\n\n#ifdef _MSC_VER\n#pragma warning(disable : 4267)\n#endif\n\n#include \"Base64.h\"\n#include <GLTFAccessor.h>\n#include <GLTFAsset.h>\n#include <GLTFBuffer.h>\n#include <GLTFBufferView.h>\n#include <GLTFMesh.h>\n#include <GLTFPrimitive.h>\n#include <GLTFScene.h>\n#include <GLTFTargetNames.h>\n\n#ifdef _MSC_VER\n#pragma warning(push)\n#pragma warning(disable : 4996)\n#pragma warning(default : 4267)\n#endif\n#include \"rapidjson/document.h\"\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n#include \"rapidjson/prettywriter.h\"\n#include \"rapidjson/stringbuffer.h\"\n#include \"rapidjson/writer.h\"\n\n#include <gsl/span>\n\n#include <coveo/enumerable.h>\n#include <coveo/linq.h>\n\n#include <maya/M3dView.h>\n#include <maya/MAnimControl.h>\n#include <maya/MAnimUtil.h>\n#include <maya/MArgDatabase.h>\n#include <maya/MArgList.h>\n#include <maya/MDagModifier.h>\n#include <maya/MDagPath.h>\n#include <maya/MDagPathArray.h>\n#include <maya/MFileIO.h>\n#include <maya/MFileObject.h>\n#include <maya/MFloatMatrix.h>\n#include <maya/MFloatPointArray.h>\n#include <maya/MFloatVectorArray.h>\n#include <maya/MFnAttribute.h>\n#include <maya/MFnBlendShapeDeformer.h>\n#include <maya/MFnBlinnShader.h>\n#include <maya/MFnCamera.h>\n#include <maya/MFnComponentListData.h>\n#include <maya/MFnLambertShader.h>\n#include <maya/MFnMatrixData.h>\n#include <maya/MFnMesh.h>\n#include <maya/MFnMessageAttribute.h>\n#include <maya/MFnNumericAttribute.h>\n#include <maya/MFnPhongShader.h>\n#include <maya/MFnSet.h>\n#include <maya/MFnSingleIndexedComponent.h>\n#include <maya/MFnSkinCluster.h>\n#include <maya/MFnStringArrayData.h>\n#include <maya/MFnTransform.h>\n#include <maya/MFnTypedAttribute.h>\n#include <maya/MGlobal.h>\n#include <maya/MIOStream.h>\n#include <maya/MImage.h>\n#include <maya/MItDependencyGraph.h>\n#include <maya/MItDependencyNodes.h>\n#include <maya/MItGeometry.h>\n#include <maya/MItMeshFaceVertex.h>\n#include <maya/MItMeshPolygon.h>\n#include <maya/MMatrix.h>\n#include <maya/MPointArray.h>\n#include <maya/MPxCommand.h>\n#include <maya/MQuaternion.h>\n#include <maya/MRenderSetup.h>\n#include <maya/MSelectionList.h>\n#include <maya/MStreamUtils.h>\n#include <maya/MSyntax.h>\n#include <maya/MTime.h>\n#include <maya/MUuid.h>\n\n#ifdef isnan\n#   undef isnan\n#endif\n", "meta": {"hexsha": "b03c37cb6c34c51f598f8f18ed2c8fcc2c0a7913", "size": 2757, "ext": "h", "lang": "C", "max_stars_repo_path": "src/externals.h", "max_stars_repo_name": "infinitedescent/Maya2glTF", "max_stars_repo_head_hexsha": "3da15de118e98a10d2edc49b77ad9e61daee5ff1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 86.0, "max_stars_repo_stars_event_min_datetime": "2020-08-05T01:51:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T09:46:13.000Z", "max_issues_repo_path": "src/externals.h", "max_issues_repo_name": "yjcnbnbnb200/Maya2glTF", "max_issues_repo_head_hexsha": "3da15de118e98a10d2edc49b77ad9e61daee5ff1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 55.0, "max_issues_repo_issues_event_min_datetime": "2020-07-16T13:27:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T15:05:14.000Z", "max_forks_repo_path": "src/externals.h", "max_forks_repo_name": "yjcnbnbnb200/Maya2glTF", "max_forks_repo_head_hexsha": "3da15de118e98a10d2edc49b77ad9e61daee5ff1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2020-11-21T09:58:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T13:44:52.000Z", "avg_line_length": 23.1680672269, "max_line_length": 43, "alphanum_fraction": 0.7631483497, "num_tokens": 780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3140505578320071, "lm_q2_score": 0.03021458433846381, "lm_q1q2_score": 0.009488907066156784}}
{"text": "/* matrix/gsl_matrix_ushort.h\r\n * \r\n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\r\n * \r\n * This program is free software; you can redistribute it and/or modify\r\n * it under the terms of the GNU General Public License as published by\r\n * the Free Software Foundation; either version 3 of the License, or (at\r\n * your option) any later version.\r\n * \r\n * This program is distributed in the hope that it will be useful, but\r\n * WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n * General Public License for more details.\r\n * \r\n * You should have received a copy of the GNU General Public License\r\n * along with this program; if not, write to the Free Software\r\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r\n */\r\n\r\n#ifndef __GSL_MATRIX_USHORT_H__\r\n#define __GSL_MATRIX_USHORT_H__\r\n\r\n#if !defined( GSL_FUN )\r\n#  if !defined( GSL_DLL )\r\n#    define GSL_FUN extern\r\n#  elif defined( BUILD_GSL_DLL )\r\n#    define GSL_FUN extern __declspec(dllexport)\r\n#  else\r\n#    define GSL_FUN extern __declspec(dllimport)\r\n#  endif\r\n#endif\r\n\r\n#include <stdlib.h>\r\n#include <gsl/gsl_types.h>\r\n#include <gsl/gsl_errno.h>\r\n#include <gsl/gsl_inline.h>\r\n#include <gsl/gsl_check_range.h>\r\n#include <gsl/gsl_vector_ushort.h>\r\n\r\n#undef __BEGIN_DECLS\r\n#undef __END_DECLS\r\n#ifdef __cplusplus\r\n# define __BEGIN_DECLS extern \"C\" {\r\n# define __END_DECLS }\r\n#else\r\n# define __BEGIN_DECLS /* empty */\r\n# define __END_DECLS /* empty */\r\n#endif\r\n\r\n__BEGIN_DECLS\r\n\r\ntypedef struct \r\n{\r\n  size_t size1;\r\n  size_t size2;\r\n  size_t tda;\r\n  unsigned short * data;\r\n  gsl_block_ushort * block;\r\n  int owner;\r\n} gsl_matrix_ushort;\r\n\r\ntypedef struct\r\n{\r\n  gsl_matrix_ushort matrix;\r\n} _gsl_matrix_ushort_view;\r\n\r\ntypedef _gsl_matrix_ushort_view gsl_matrix_ushort_view;\r\n\r\ntypedef struct\r\n{\r\n  gsl_matrix_ushort matrix;\r\n} _gsl_matrix_ushort_const_view;\r\n\r\ntypedef const _gsl_matrix_ushort_const_view gsl_matrix_ushort_const_view;\r\n\r\n/* Allocation */\r\n\r\nGSL_FUN gsl_matrix_ushort * \r\ngsl_matrix_ushort_alloc (const size_t n1, const size_t n2);\r\n\r\nGSL_FUN gsl_matrix_ushort * \r\ngsl_matrix_ushort_calloc (const size_t n1, const size_t n2);\r\n\r\nGSL_FUN gsl_matrix_ushort * \r\ngsl_matrix_ushort_alloc_from_block (gsl_block_ushort * b, \r\n                                   const size_t offset, \r\n                                   const size_t n1, \r\n                                   const size_t n2, \r\n                                   const size_t d2);\r\n\r\nGSL_FUN gsl_matrix_ushort * \r\ngsl_matrix_ushort_alloc_from_matrix (gsl_matrix_ushort * m,\r\n                                    const size_t k1, \r\n                                    const size_t k2,\r\n                                    const size_t n1, \r\n                                    const size_t n2);\r\n\r\nGSL_FUN gsl_vector_ushort * \r\ngsl_vector_ushort_alloc_row_from_matrix (gsl_matrix_ushort * m,\r\n                                        const size_t i);\r\n\r\nGSL_FUN gsl_vector_ushort * \r\ngsl_vector_ushort_alloc_col_from_matrix (gsl_matrix_ushort * m,\r\n                                        const size_t j);\r\n\r\nGSL_FUN void gsl_matrix_ushort_free (gsl_matrix_ushort * m);\r\n\r\n/* Views */\r\n\r\nGSL_FUN _gsl_matrix_ushort_view \r\ngsl_matrix_ushort_submatrix (gsl_matrix_ushort * m, \r\n                            const size_t i, const size_t j, \r\n                            const size_t n1, const size_t n2);\r\n\r\nGSL_FUN _gsl_vector_ushort_view \r\ngsl_matrix_ushort_row (gsl_matrix_ushort * m, const size_t i);\r\n\r\nGSL_FUN _gsl_vector_ushort_view \r\ngsl_matrix_ushort_column (gsl_matrix_ushort * m, const size_t j);\r\n\r\nGSL_FUN _gsl_vector_ushort_view \r\ngsl_matrix_ushort_diagonal (gsl_matrix_ushort * m);\r\n\r\nGSL_FUN _gsl_vector_ushort_view \r\ngsl_matrix_ushort_subdiagonal (gsl_matrix_ushort * m, const size_t k);\r\n\r\nGSL_FUN _gsl_vector_ushort_view \r\ngsl_matrix_ushort_superdiagonal (gsl_matrix_ushort * m, const size_t k);\r\n\r\nGSL_FUN _gsl_vector_ushort_view\r\ngsl_matrix_ushort_subrow (gsl_matrix_ushort * m, const size_t i,\r\n                         const size_t offset, const size_t n);\r\n\r\nGSL_FUN _gsl_vector_ushort_view\r\ngsl_matrix_ushort_subcolumn (gsl_matrix_ushort * m, const size_t j,\r\n                            const size_t offset, const size_t n);\r\n\r\nGSL_FUN _gsl_matrix_ushort_view\r\ngsl_matrix_ushort_view_array (unsigned short * base,\r\n                             const size_t n1, \r\n                             const size_t n2);\r\n\r\nGSL_FUN _gsl_matrix_ushort_view\r\ngsl_matrix_ushort_view_array_with_tda (unsigned short * base, \r\n                                      const size_t n1, \r\n                                      const size_t n2,\r\n                                      const size_t tda);\r\n\r\n\r\nGSL_FUN _gsl_matrix_ushort_view\r\ngsl_matrix_ushort_view_vector (gsl_vector_ushort * v,\r\n                              const size_t n1, \r\n                              const size_t n2);\r\n\r\nGSL_FUN _gsl_matrix_ushort_view\r\ngsl_matrix_ushort_view_vector_with_tda (gsl_vector_ushort * v,\r\n                                       const size_t n1, \r\n                                       const size_t n2,\r\n                                       const size_t tda);\r\n\r\n\r\nGSL_FUN _gsl_matrix_ushort_const_view \r\ngsl_matrix_ushort_const_submatrix (const gsl_matrix_ushort * m, \r\n                                  const size_t i, const size_t j, \r\n                                  const size_t n1, const size_t n2);\r\n\r\nGSL_FUN _gsl_vector_ushort_const_view \r\ngsl_matrix_ushort_const_row (const gsl_matrix_ushort * m, \r\n                            const size_t i);\r\n\r\nGSL_FUN _gsl_vector_ushort_const_view \r\ngsl_matrix_ushort_const_column (const gsl_matrix_ushort * m, \r\n                               const size_t j);\r\n\r\nGSL_FUN _gsl_vector_ushort_const_view\r\ngsl_matrix_ushort_const_diagonal (const gsl_matrix_ushort * m);\r\n\r\nGSL_FUN _gsl_vector_ushort_const_view \r\ngsl_matrix_ushort_const_subdiagonal (const gsl_matrix_ushort * m, \r\n                                    const size_t k);\r\n\r\nGSL_FUN _gsl_vector_ushort_const_view \r\ngsl_matrix_ushort_const_superdiagonal (const gsl_matrix_ushort * m, \r\n                                      const size_t k);\r\n\r\nGSL_FUN _gsl_vector_ushort_const_view\r\ngsl_matrix_ushort_const_subrow (const gsl_matrix_ushort * m, const size_t i,\r\n                               const size_t offset, const size_t n);\r\n\r\nGSL_FUN _gsl_vector_ushort_const_view\r\ngsl_matrix_ushort_const_subcolumn (const gsl_matrix_ushort * m, const size_t j,\r\n                                  const size_t offset, const size_t n);\r\n\r\nGSL_FUN _gsl_matrix_ushort_const_view\r\ngsl_matrix_ushort_const_view_array (const unsigned short * base,\r\n                                   const size_t n1, \r\n                                   const size_t n2);\r\n\r\nGSL_FUN _gsl_matrix_ushort_const_view\r\ngsl_matrix_ushort_const_view_array_with_tda (const unsigned short * base, \r\n                                            const size_t n1, \r\n                                            const size_t n2,\r\n                                            const size_t tda);\r\n\r\nGSL_FUN _gsl_matrix_ushort_const_view\r\ngsl_matrix_ushort_const_view_vector (const gsl_vector_ushort * v,\r\n                                    const size_t n1, \r\n                                    const size_t n2);\r\n\r\nGSL_FUN _gsl_matrix_ushort_const_view\r\ngsl_matrix_ushort_const_view_vector_with_tda (const gsl_vector_ushort * v,\r\n                                             const size_t n1, \r\n                                             const size_t n2,\r\n                                             const size_t tda);\r\n\r\n/* Operations */\r\n\r\nGSL_FUN void gsl_matrix_ushort_set_zero (gsl_matrix_ushort * m);\r\nGSL_FUN void gsl_matrix_ushort_set_identity (gsl_matrix_ushort * m);\r\nGSL_FUN void gsl_matrix_ushort_set_all (gsl_matrix_ushort * m, unsigned short x);\r\n\r\nGSL_FUN int gsl_matrix_ushort_fread (FILE * stream, gsl_matrix_ushort * m) ;\r\nGSL_FUN int gsl_matrix_ushort_fwrite (FILE * stream, const gsl_matrix_ushort * m) ;\r\nGSL_FUN int gsl_matrix_ushort_fscanf (FILE * stream, gsl_matrix_ushort * m);\r\nGSL_FUN int gsl_matrix_ushort_fprintf (FILE * stream, const gsl_matrix_ushort * m, const char * format);\r\n \r\nGSL_FUN int gsl_matrix_ushort_memcpy(gsl_matrix_ushort * dest, const gsl_matrix_ushort * src);\r\nGSL_FUN int gsl_matrix_ushort_swap(gsl_matrix_ushort * m1, gsl_matrix_ushort * m2);\r\n\r\nGSL_FUN int gsl_matrix_ushort_swap_rows(gsl_matrix_ushort * m, const size_t i, const size_t j);\r\nGSL_FUN int gsl_matrix_ushort_swap_columns(gsl_matrix_ushort * m, const size_t i, const size_t j);\r\nGSL_FUN int gsl_matrix_ushort_swap_rowcol(gsl_matrix_ushort * m, const size_t i, const size_t j);\r\nGSL_FUN int gsl_matrix_ushort_transpose (gsl_matrix_ushort * m);\r\nGSL_FUN int gsl_matrix_ushort_transpose_memcpy (gsl_matrix_ushort * dest, const gsl_matrix_ushort * src);\r\n\r\nGSL_FUN unsigned short gsl_matrix_ushort_max (const gsl_matrix_ushort * m);\r\nGSL_FUN unsigned short gsl_matrix_ushort_min (const gsl_matrix_ushort * m);\r\nGSL_FUN void gsl_matrix_ushort_minmax (const gsl_matrix_ushort * m, unsigned short * min_out, unsigned short * max_out);\r\n\r\nGSL_FUN void gsl_matrix_ushort_max_index (const gsl_matrix_ushort * m, size_t * imax, size_t *jmax);\r\nGSL_FUN void gsl_matrix_ushort_min_index (const gsl_matrix_ushort * m, size_t * imin, size_t *jmin);\r\nGSL_FUN void gsl_matrix_ushort_minmax_index (const gsl_matrix_ushort * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);\r\n\r\nGSL_FUN int gsl_matrix_ushort_isnull (const gsl_matrix_ushort * m);\r\nGSL_FUN int gsl_matrix_ushort_ispos (const gsl_matrix_ushort * m);\r\nGSL_FUN int gsl_matrix_ushort_isneg (const gsl_matrix_ushort * m);\r\nGSL_FUN int gsl_matrix_ushort_isnonneg (const gsl_matrix_ushort * m);\r\n\r\nGSL_FUN int gsl_matrix_ushort_add (gsl_matrix_ushort * a, const gsl_matrix_ushort * b);\r\nGSL_FUN int gsl_matrix_ushort_sub (gsl_matrix_ushort * a, const gsl_matrix_ushort * b);\r\nGSL_FUN int gsl_matrix_ushort_mul_elements (gsl_matrix_ushort * a, const gsl_matrix_ushort * b);\r\nGSL_FUN int gsl_matrix_ushort_div_elements (gsl_matrix_ushort * a, const gsl_matrix_ushort * b);\r\nGSL_FUN int gsl_matrix_ushort_scale (gsl_matrix_ushort * a, const double x);\r\nGSL_FUN int gsl_matrix_ushort_add_constant (gsl_matrix_ushort * a, const double x);\r\nGSL_FUN int gsl_matrix_ushort_add_diagonal (gsl_matrix_ushort * a, const double x);\r\n\r\n/***********************************************************************/\r\n/* The functions below are obsolete                                    */\r\n/***********************************************************************/\r\nGSL_FUN int gsl_matrix_ushort_get_row(gsl_vector_ushort * v, const gsl_matrix_ushort * m, const size_t i);\r\nGSL_FUN int gsl_matrix_ushort_get_col(gsl_vector_ushort * v, const gsl_matrix_ushort * m, const size_t j);\r\nGSL_FUN int gsl_matrix_ushort_set_row(gsl_matrix_ushort * m, const size_t i, const gsl_vector_ushort * v);\r\nGSL_FUN int gsl_matrix_ushort_set_col(gsl_matrix_ushort * m, const size_t j, const gsl_vector_ushort * v);\r\n/***********************************************************************/\r\n\r\n/* inline functions if you are using GCC */\r\n\r\nGSL_FUN INLINE_DECL unsigned short   gsl_matrix_ushort_get(const gsl_matrix_ushort * m, const size_t i, const size_t j);\r\nGSL_FUN INLINE_DECL void    gsl_matrix_ushort_set(gsl_matrix_ushort * m, const size_t i, const size_t j, const unsigned short x);\r\nGSL_FUN INLINE_DECL unsigned short * gsl_matrix_ushort_ptr(gsl_matrix_ushort * m, const size_t i, const size_t j);\r\nGSL_FUN INLINE_DECL const unsigned short * gsl_matrix_ushort_const_ptr(const gsl_matrix_ushort * m, const size_t i, const size_t j);\r\n\r\n#ifdef HAVE_INLINE\r\nINLINE_FUN \r\nunsigned short\r\ngsl_matrix_ushort_get(const gsl_matrix_ushort * m, const size_t i, const size_t j)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(1)) \r\n    {\r\n      if (i >= m->size1)\r\n        {\r\n          GSL_ERROR_VAL(\"first index out of range\", GSL_EINVAL, 0) ;\r\n        }\r\n      else if (j >= m->size2)\r\n        {\r\n          GSL_ERROR_VAL(\"second index out of range\", GSL_EINVAL, 0) ;\r\n        }\r\n    }\r\n#endif\r\n  return m->data[i * m->tda + j] ;\r\n} \r\n\r\nINLINE_FUN \r\nvoid\r\ngsl_matrix_ushort_set(gsl_matrix_ushort * m, const size_t i, const size_t j, const unsigned short x)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(1)) \r\n    {\r\n      if (i >= m->size1)\r\n        {\r\n          GSL_ERROR_VOID(\"first index out of range\", GSL_EINVAL) ;\r\n        }\r\n      else if (j >= m->size2)\r\n        {\r\n          GSL_ERROR_VOID(\"second index out of range\", GSL_EINVAL) ;\r\n        }\r\n    }\r\n#endif\r\n  m->data[i * m->tda + j] = x ;\r\n}\r\n\r\nINLINE_FUN \r\nunsigned short *\r\ngsl_matrix_ushort_ptr(gsl_matrix_ushort * m, const size_t i, const size_t j)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(1)) \r\n    {\r\n      if (i >= m->size1)\r\n        {\r\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\r\n        }\r\n      else if (j >= m->size2)\r\n        {\r\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\r\n        }\r\n    }\r\n#endif\r\n  return (unsigned short *) (m->data + (i * m->tda + j)) ;\r\n} \r\n\r\nINLINE_FUN \r\nconst unsigned short *\r\ngsl_matrix_ushort_const_ptr(const gsl_matrix_ushort * m, const size_t i, const size_t j)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(1)) \r\n    {\r\n      if (i >= m->size1)\r\n        {\r\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\r\n        }\r\n      else if (j >= m->size2)\r\n        {\r\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\r\n        }\r\n    }\r\n#endif\r\n  return (const unsigned short *) (m->data + (i * m->tda + j)) ;\r\n} \r\n\r\n#endif\r\n\r\n__END_DECLS\r\n\r\n#endif /* __GSL_MATRIX_USHORT_H__ */\r\n", "meta": {"hexsha": "580e059e5db7b907fc6d545b58094df5e965435e", "size": 13730, "ext": "h", "lang": "C", "max_stars_repo_path": "deps/include/gsl/gsl_matrix_ushort.h", "max_stars_repo_name": "berkus/music-cs", "max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "deps/include/gsl/gsl_matrix_ushort.h", "max_issues_repo_name": "berkus/music-cs", "max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "deps/include/gsl/gsl_matrix_ushort.h", "max_forks_repo_name": "berkus/music-cs", "max_forks_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.2451253482, "max_line_length": 135, "alphanum_fraction": 0.6543335761, "num_tokens": 3395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23934934732271168, "lm_q2_score": 0.03963883711558994, "lm_q1q2_score": 0.00948752979224773}}
{"text": "/*\nCopyright (c) 2015, Patrick Weltevrede\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n#include <stdio.h>\n#include <string.h>\n#include <math.h>\n#include <gsl/gsl_sort.h>\n#include \"psrsalsa.h\"\ntypedef struct {\n  datafile_definition datafile;\n  double f2_min, f2_max;\n  double f3_min, f3_max;\n  double P3IntegrateLow, P3IntegrateHigh;\n  int SelectP3Integrate;\n  double oversaturize;\n}twodfs_def;\ntypedef struct {\n  char *textside;\n  double fl_min, fl_max;\n  double dl;\n  double LRegionLow, LRegionHigh;\n  int SelectLRegion;\n  int doFlip;\n  int ExtraVerticalMaximaSkip;\n  int noside;\n  int overlaypp;\n  int inside;\n  int noylabels;\n  int noxlabels;\n  int notop;\n  int autooversaturizel, autooversaturize2, autozoomP2;\n  float labelscale, titlescale;\n  double oversaturizel;\n  double Imin, Imax;\n  double scaleFig_x, scaleFig_y;\n  int plot_xlabel, plot_ylabel, plot_ylabeltop;\n  int nomain;\n  int showwedge;\n  int showwedge_max;\n  int normaliseSide;\n  int nointegrateNumbers;\n  int intflip;\n  int usephase;\n  int lineColour;\n  int normalise_spectra;\n  int SelectP3Region;\n}plotoptions_def;\nint loadLRFS(datafile_definition *lrfs, int extprefix, int longsnap, int argc, char **argv, plotoptions_def *plotoptions, verbose_definition verbose);\nint load2dfs(twodfs_def *twodfs_allinfo, datafile_definition AverageProfile, int file_number, int extprefix, int altname, int argc, char **argv, plotoptions_def plotoptions, verbose_definition verbose);\nvoid Plot2dfs(twodfs_def twodfs_allinfo, twodfs_def twodfs2_allinfo, datafile_definition AverageProfile, int twodfsonly, int Number, char *title, plotoptions_def plotoptions, verbose_definition verbose);\nvoid PlotLRFS(datafile_definition lrfs, datafile_definition AverageProfile, twodfs_def twodfs_allinfo, char *title, plotoptions_def plotoptions, verbose_definition verbose);\nint loadHeaderPulseStack(datafile_definition *AverageProfile, datafile_definition lrfs, double *period, int type_of_plots, int argc, char **argv, verbose_definition verbose);\nvoid autozoomP2(twodfs_def *twodfs_allinfo, datafile_definition AverageProfile, plotoptions_def plotoptions, verbose_definition verbose);\nint main(int argc, char **argv)\n{\n  int i, j, xi, SelectP2Region, LoadTwo, NrSelectedOverSaturize;\n  int file_number, ImaxSet, IminSet, type_of_plots, maxSubpulsePhaseSet, minSubpulsePhaseSet, do_phase_slope, extprefix;\n  char PlotDevice[100], filename[1000], txt[1000];\n  int title_index, Load2dfs, LoadLRFS, plotvariance, plotmodindex, ok_flag, altProf, lineStyle, ret, longsnap;\n  double P3RegionLow, P3RegionHigh, maxSubpulsePhase, minSubpulsePhase;\n  float I, x, profilescale;\n  float maxvalue_mod, maxvalue_stddev, maxsigma_stddev, maxsigma_mod, ImaxValue, IminValue, phase_slope_g, phase_slope_o;\n  FILE *fout_ascii;\n  long k;\n  datafile_definition subpulseTrackProfile, subpulseTrackProfileErr, subpulseAmpProfile;\n  datafile_definition AverageProfile, VarianceProfile, ModProfile, VarianceProfileErr, ModProfileErr, lrfs;\n  verbose_definition noverbose;\n  psrsalsaApplication application;\n  plotoptions_def plotoptions;\n  twodfs_def twodfs_allinfo, twodfs2_allinfo;\n  initApplication(&application, \"pspecFig\", \"\");\n  type_of_plots = 0;\n  file_number = 1;\n  plotoptions.scaleFig_x = 1;\n  plotoptions.scaleFig_y = 1;\n  do_phase_slope = 0;\n  plotoptions.autooversaturizel = 0;\n  plotoptions.autooversaturize2 = 0;\n  plotoptions.autozoomP2 = 0;\n  extprefix = 0;\n  longsnap = 0;\n  if(argc < 2) {\n    printf(\"Program to plot some of the pspec output\\n\\nUsage: pspecFig [options] stack_file (i.e. the name of the pulse stack that has been processed by pspec). By default the profile/modulation index/standard deviation profile/lrfs/2dfs are combined in a single plot (mode A). When -phaseplot is specified, a plot of the profile/subpulse amplitude and subpulse phase is produced (mode B).\\n\\n\");\n    printf(\"Where optional options are:\\n\\n\");\n    printf(\"General options:\\n\");\n    printf(\"-headerlist       Show options of the -header option.\\n\");\n    printf(\"-header           Change this header parameter.\\n\");\n    printf(\"                  Example -header 'name J0123+4567'\\n\");\n    printf(\"-v                Verbose mode (to get a better idea what is happening)\\n\");\n    printf(\"-debug            Enable more output (where implemented)\\n\");\n    printf(\"-nocounters       Don't show counters etc (useful when generating log files)\\n\");\n    printf(\"-phaseplot        Enable mode B operation, see above.\\n\");\n    printf(\"\\nGeneral file/panel options:\\n\");\n    printf(\"-altProf          Load this alternative .profile file (generated by pspec).\\n\");\n    printf(\"                  Useful if profile/modindex/stddev curves are calculated from\\n\");\n    printf(\"                  a different file than the spectra.\\n\");\n    printf(\"-notop            Don't show top plot\\n\");\n    printf(\"\\nMode A specific file/panel options:\\n\");\n    printf(\"-2                Load two 2dfs's corresponding to two pulse longitude ranges\\n\");\n    printf(\"-2dfsnr           Override 2dfs file number of first 2dfs. Default is %d.\\n\", file_number);\n    printf(\"-nolrfs           Do not load lrfs\\n\");\n    printf(\"-no2dfs           Do not load 2dfs's\\n\");\n    printf(\"-noside           Don't show side panels\\n\");\n    printf(\"-normspectra      Normalise the spectra (peak value=1)\\n\");\n    printf(\"-normside         Normalise the side panels (peak value=1)\\n\");\n    printf(\"\\nGeneral range options:\\n\");\n    printf(\"-Imax             Set maximum value of the y-range of the top plot\\n\");\n    printf(\"-Imin             Set minimum value of the y-range of the top plot\\n\");\n    printf(\"-long  \\\"low high\\\" Set horizontal range shown lrfs/profile.\\n\");\n    printf(\"-phase            Use pulse longitude in phase rather than degrees.\\n\");\n    printf(\"-dlong            Shift lrfs/profile by this amount of degrees or phase.\\n\");\n    printf(\"\\nMode A specific range options:\\n\");\n    printf(\"-p3 \\\"low high\\\"    Set vertical range shown in lrfs/2dfs in cpp.\\n\");\n    printf(\"-p2 \\\"low high\\\"    Set horizontal range as shown in 2dfs (can use this option\\n\");\n    printf(\"                  twice if -2 is used) in cpp.\\n\");\n    printf(\"-int  \\\"low high\\\"  Select vertical integration range in 2dfs in cpp\\n\");\n    printf(\"                  (affects the side panels, can be use twice if -2 is used).\\n\");\n    printf(\"-modsigma         Set minimum significance for the modulation index (def. is 3).\\n\");\n    printf(\"-stddevsigma      Same for the stddev values (default is 3).\\n\");\n    printf(\"-modmax           Set the max allowed value for the modulation index\\n\");\n    printf(\"                  (other values are ignored).\\n\");\n    printf(\"-stddevmax        Same for the stddev values\\n\");\n    printf(\"\\nMode B specific range options:\\n\");\n    printf(\"-spmax            Set maximum value of the y-range of the subpulse phase plot\\n\");\n    printf(\"-spmin            Set minimum value of the y-range of the subpulse phase plot\\n\");\n    printf(\"\\nOther graphics options:\\n\");\n    printf(\"-device  \\\"...\\\"    Plot device\\n\");\n    printf(\"-inside           Place tick marks inside\\n\");\n    printf(\"-labelscale       Set size of labels (default is 1)\\n\");\n    printf(\"-titlescale       Set size of title (default is 1), but -labalscale affects size as well.\\n\");\n    printf(\"-noylabels        Don't show ylabels\\n\");\n    printf(\"-linestyle        Set the PGPLOT line style of the pulse profile\\n\");\n    printf(\"-linecolor        Set the PGPLOT line color of the pulse profile\\n\");\n    printf(\"-scalefig \\\"x y\\\"   Scale size of panel with factors x and y\\n\");\n    printf(\"-title            Set the title\\n\");\n    printf(\"-ytop             Show y-label of top plot\\n\");\n    printf(\"\\nMode A specific graphics options:\\n\");\n    printf(\"-intflip          Add a flipped version of the vertical integration of the 2dfs\\n\");\n    printf(\"-intnrs           Show nrs along side panels axis, instead of just a tick\\n\");\n    printf(\"-scalel scale     The values in the lrfs are boosted by factor scale, resulting\\n\");\n    printf(\"                  in clipping, which can highlight weaker features.\\n\");\n    printf(\"-scale2 scale     As -scalel, but for 2dfs instead of lrfs.\\n\");\n    printf(\"                  When this option is used twice, the 2nd time the\\n\");\n    printf(\"                  option is used applies to the second 2dfs shown.\\n\");\n    printf(\"-scalep           Scale profile by this factor\\n\");\n    printf(\"-noflip           Do not flip 2DFS horizontally. If specified positive drift\\n\");\n    printf(\"                  corresponds to power in the negative side of the diagram.\\n\");\n    printf(\"-overlay          Overlay pulse profile over LRFS\\n\");\n    printf(\"-noxlabels        Don't show xlabels on 2dfs bottom integration panel.\\n\");\n    printf(\"-nomod            Do not plot a modulation index profile\\n\");\n    printf(\"-nostddev         Do not plot a standard deviation profile\\n\");\n    printf(\"-showwedge        Plot an annotated wedge to show color scale\\n\");\n    printf(\"-showwedge_showmax  Plot a label indicating the maximum value in the data.\\n\");\n    printf(\"                  With the -scalel or -scale2 option this is not necessarily\\n\");\n    printf(\"                  the maximum of the colour scale.\\n\");\n    printf(\"-textside         Set the text printed in top left corner of the graph\\n\");\n    printf(\"-xlabel           Show x-label of LRFS and 2DFS in cpp\\n\");\n    printf(\"-xlabel2          Show x-label of LRFS and 2DFS in P0/P2\\n\");\n    printf(\"-xlabel3          Show x-label of LRFS and 2DFS in P/P2\\n\");\n    printf(\"-ylabel           Show y-label of LRFS in cpp\\n\");\n    printf(\"-ylabel2          Show y-label of LRFS in P0/P3\\n\");\n    printf(\"-ylabel3          Show y-label of LRFS in P/P3\\n\");\n    printf(\"-s                Skip the specified number of P3 bins when determining\\n\");\n    printf(\"                  the range in left-hand side integrations panels. By default\\n\");\n    printf(\"                  the first bin is skipped.\\n\");\n    printf(\"\\nMode B specific graphics options:\\n\");\n    printf(\"-noflip           Do not change sign of subpulse phase. If specified positive\\n\");\n    printf(\"                  drift corresponds to a decrease subpulse phase as function of\\n\");\n    printf(\"                  pulse longitude.\\n\");\n    printf(\"-xlabel           Show x-label in pulse longitude\\n\");\n    printf(\"-ylabel           Show y-label in subpulse phase\\n\");\n    printf(\"-phaseslope \\\"g o\\\" In the subpulse phase plot, add a line with gradient g (in deg\\n\");\n    printf(\"                  per deg) and offset o in deg.\\n\");\n    printf(\"\\n\");\n    printf(\"Please use the appropriate citation when using results of this software in your publications:\\n\\n\");\n    printf(\"More information about the lrfs/2dfs/modulation index can be found in:\\n\");\n    printf(\" - Weltevrede et al. 2006, A&A, 445, 243\\n\");\n    printf(\" - Weltevrede et al. 2007, A&A, 469, 607\\n\");\n    printf(\"More information about bootstrap/subpulse phase track & amplitude can be found in:\\n\");\n    printf(\" - Weltevrede et al. 2012, MNRAS, 424, 843\\n\\n\");\n    printCitationInfo();\n    terminateApplication(&application);\n    return 0;\n  }\n  plotoptions.plot_ylabeltop = 0;\n  plotoptions.nomain = 0;\n  plotoptions.SelectP3Region = 0;\n  SelectP2Region = 0;\n  plotoptions.SelectLRegion = 0;\n  twodfs_allinfo.SelectP3Integrate = 0;\n  twodfs2_allinfo.SelectP3Integrate = 0;\n  LoadTwo = 0;\n  strcpy(PlotDevice, \"?\");\n  twodfs_allinfo.oversaturize = 1;\n  twodfs2_allinfo.oversaturize = 1;\n  plotoptions.oversaturizel = 1;\n  NrSelectedOverSaturize = 0;\n  maxvalue_mod = -1;\n  maxsigma_mod = 3;\n  maxvalue_stddev = -1;\n  maxsigma_stddev = 3;\n  title_index = -1;\n  plotoptions.textside = NULL;\n  plotoptions.doFlip = 1;\n  plotoptions.ExtraVerticalMaximaSkip = 1;\n  Load2dfs = 1;\n  LoadLRFS = 1;\n  plotvariance = 1;\n  plotmodindex = 1;\n  profilescale = 1;\n  plotoptions.plot_xlabel = 0;\n  plotoptions.plot_ylabel = 0;\n  plotoptions.notop = 0;\n  plotoptions.noside = 0;\n  plotoptions.overlaypp = 0;\n  plotoptions.inside = 0;\n  plotoptions.labelscale = 1.0;\n  plotoptions.titlescale = 1.0;\n  plotoptions.noylabels = 0;\n  plotoptions.noxlabels = 0;\n  altProf = 0;\n  plotoptions.dl = 0;\n  ImaxSet = 0;\n  IminSet = 0;\n  lineStyle = 1;\n  plotoptions.lineColour = 1;\n  maxSubpulsePhaseSet = 0;\n  minSubpulsePhaseSet = 0;\n  maxSubpulsePhase = 0;\n  minSubpulsePhase = 0;\n  plotoptions.showwedge = 0;\n  plotoptions.showwedge_max = 0;\n  plotoptions.normalise_spectra = 0;\n  plotoptions.normaliseSide = 0;\n  plotoptions.nointegrateNumbers = 1;\n  plotoptions.intflip = 0;\n  plotoptions.usephase = 0;\n  twodfs_allinfo.f2_min = 0.0;\n  twodfs_allinfo.f2_max = 0.0;\n  twodfs2_allinfo.f2_min = 0.0;\n  twodfs2_allinfo.f2_max = 0.0;\n  for(i = 1; i < argc; i++) {\n    if(strcmp(argv[i], \"-headerlist\") == 0) {\n      printHeaderCommandlineOptions(stdout);\n      terminateApplication(&application);\n      return 0;\n    }\n  }\n  int argclast;\n  argclast = argc-1;\n  if(argv[argc-1][0] == '-')\n    argclast += 1;\n  for(i = 1; i < argclast; i++) {\n    if(strcmp(argv[i], \"-d\") == 0 || strcmp(argv[i], \"-D\") == 0 || strcmp(argv[i], \"-device\") == 0 || strcmp(argv[i], \"-dev\") == 0) {\n      strcpy(PlotDevice, argv[i+1]);\n      i++;\n    }else if(strcmp(argv[i], \"-v\") == 0) {\n      application.verbose_state.verbose = 1;\n    }else if(strcmp(argv[i], \"-phaseplot\") == 0) {\n      type_of_plots = 1;\n    }else if(strcmp(argv[i], \"-debug\") == 0) {\n      application.verbose_state.debug = 1;\n    }else if(strcmp(argv[i], \"-nocounters\") == 0) {\n      application.verbose_state.nocounters = 1;\n    }else if(strcmp(argv[i], \"-xlabel\") == 0\n      ) {\n      plotoptions.plot_xlabel = 1;\n    }else if(strcmp(argv[i], \"-xlabel2\") == 0\n      ) {\n      plotoptions.plot_xlabel = 2;\n    }else if(strcmp(argv[i], \"-xlabel3\") == 0\n      ) {\n      plotoptions.plot_xlabel = 3;\n    }else if(strcmp(argv[i], \"-ylabel\") == 0\n      ) {\n      plotoptions.plot_ylabel = 1;\n    }else if(strcmp(argv[i], \"-ylabel2\") == 0\n      ) {\n      plotoptions.plot_ylabel = 2;\n    }else if(strcmp(argv[i], \"-ylabel3\") == 0\n      ) {\n      plotoptions.plot_ylabel = 3;\n    }else if(strcmp(argv[i], \"-nolrfs\") == 0\n      ) {\n      LoadLRFS = 0;\n    }else if(strcmp(argv[i], \"-2\") == 0) {\n      LoadTwo = 1;\n    }else if(strcmp(argv[i], \"-no2dfs\") == 0\n      ) {\n      Load2dfs = 0;\n    }else if(strcmp(argv[i], \"-inside\") == 0) {\n      plotoptions.inside = 1;\n    }else if(strcmp(argv[i], \"-nostddev\") == 0\n      ) {\n      plotvariance = 0;\n    }else if(strcmp(argv[i], \"-nomod\") == 0\n      ) {\n      plotmodindex = 0;\n    }else if(strcmp(argv[i], \"-f\") == 0 || strcmp(argv[i], \"-noflip\") == 0) {\n      plotoptions.doFlip = 0;\n    }else if(strcmp(argv[i], \"-notop\") == 0) {\n      plotoptions.notop = 1;\n    }else if(strcmp(argv[i], \"-noside\") == 0) {\n      plotoptions.noside = 1;\n    }else if(strcmp(argv[i], \"-nomain\") == 0) {\n      plotoptions.nomain = 1;\n    }else if(strcmp(argv[i], \"-overlay\") == 0) {\n      plotoptions.overlaypp = 1;\n    }else if(strcmp(argv[i], \"-noylabels\") == 0) {\n      plotoptions.noylabels = 1;\n    }else if(strcmp(argv[i], \"-noxlabels\") == 0) {\n      plotoptions.noxlabels = 1;\n    }else if(strcmp(argv[i], \"-showwedge\") == 0) {\n      plotoptions.showwedge = 1;\n    }else if(strcmp(argv[i], \"-showwedge_showmax\") == 0) {\n      plotoptions.showwedge_max = 1;\n    }else if(strcmp(argv[i], \"-normspectra\") == 0) {\n      plotoptions.normalise_spectra = 1;\n    }else if(strcmp(argv[i], \"-normside\") == 0) {\n      plotoptions.normaliseSide = 1;\n    }else if(strcmp(argv[i], \"-intnrs\") == 0) {\n      plotoptions.nointegrateNumbers = 0;\n    }else if(strcmp(argv[i], \"-intflip\") == 0) {\n      plotoptions.intflip = 1;\n    }else if(strcmp(argv[i], \"-phase\") == 0) {\n      plotoptions.usephase = 1;\n    }else if(strcmp(argv[i], \"-linestyle\") == 0) {\n      if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, \"%d\", &lineStyle, NULL) == 0) {\n printerror(application.verbose_state.debug, \"ERROR pspecFig: Cannot parse '%s' option.\", argv[i]);\n return 0;\n      }\n      i++;\n    }else if(strcmp(argv[i], \"-linecolor\") == 0 || strcmp(argv[i], \"-linecolour\") == 0) {\n      if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, \"%d\", &(plotoptions.lineColour), NULL) == 0) {\n printerror(application.verbose_state.debug, \"ERROR pspecFig: Cannot parse '%s' option.\", argv[i]);\n return 0;\n      }\n      i++;\n    }else if(strcmp(argv[i], \"-scalep\") == 0\n      ) {\n      if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, \"%f\", &profilescale, NULL) == 0) {\n printerror(application.verbose_state.debug, \"ERROR pspecFig: Cannot parse '%s' option.\", argv[i]);\n return 0;\n      }\n      i++;\n    }else if(strcmp(argv[i], \"-dlong\") == 0 || strcmp(argv[i], \"-dl\") == 0) {\n      if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, \"%lf\", &(plotoptions.dl), NULL) == 0) {\n printerror(application.verbose_state.debug, \"ERROR pspecFig: Cannot parse '%s' option.\", argv[i]);\n return 0;\n      }\n      i++;\n    }else if(strcmp(argv[i], \"-labelscale\") == 0) {\n      if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, \"%f\", &(plotoptions.labelscale), NULL) == 0) {\n printerror(application.verbose_state.debug, \"ERROR pspecFig: Cannot parse '%s' option.\", argv[i]);\n return 0;\n      }\n      i++;\n    }else if(strcmp(argv[i], \"-titlescale\") == 0) {\n      if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, \"%f\", &(plotoptions.titlescale), NULL) == 0) {\n printerror(application.verbose_state.debug, \"ERROR pspecFig: Cannot parse '%s' option.\", argv[i]);\n return 0;\n      }\n      i++;\n    }else if(strcmp(argv[i], \"-Imax\") == 0) {\n      if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, \"%f\", &ImaxValue, NULL) == 0) {\n printerror(application.verbose_state.debug, \"ERROR pspecFig: Cannot parse '%s' option.\", argv[i]);\n return 0;\n      }\n      ImaxSet = 1;\n      i++;\n    }else if(strcmp(argv[i], \"-Imin\") == 0) {\n      if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, \"%f\", &IminValue, NULL) == 0) {\n printerror(application.verbose_state.debug, \"ERROR pspecFig: Cannot parse '%s' option.\", argv[i]);\n return 0;\n      }\n      IminSet = 1;\n      i++;\n    }else if(strcmp(argv[i], \"-spmax\") == 0) {\n      if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, \"%lf\", &maxSubpulsePhase, NULL) == 0) {\n printerror(application.verbose_state.debug, \"ERROR pspecFig: Cannot parse '%s' option.\", argv[i]);\n return 0;\n      }\n      maxSubpulsePhaseSet = 1;\n      i++;\n    }else if(strcmp(argv[i], \"-spmin\") == 0) {\n      if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, \"%lf\", &minSubpulsePhase, NULL) == 0) {\n printerror(application.verbose_state.debug, \"ERROR pspecFig: Cannot parse '%s' option.\", argv[i]);\n return 0;\n      }\n      minSubpulsePhaseSet = 1;\n      i++;\n    }else if(strcmp(argv[i], \"-header\") == 0) {\n      i++;\n    }else if(strcmp(argv[i], \"-altProf\") == 0) {\n      altProf = i+1;\n      i++;\n    }else if(strcmp(argv[i], \"-p3\") == 0) {\n      plotoptions.SelectP3Region = 1;\n      if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, \"%lf %lf\", &P3RegionLow, &P3RegionHigh, NULL) == 0) {\n printerror(application.verbose_state.debug, \"ERROR pspecFig: Cannot parse '%s' option.\", argv[i]);\n return 0;\n      }\n      i++;\n    }else if(strcmp(argv[i], \"-p2\") == 0) {\n      if(SelectP2Region == 0) {\n SelectP2Region = 1;\n if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, \"%lf %lf\", &(twodfs_allinfo.f2_min), &(twodfs_allinfo.f2_max), NULL) == 0) {\n   printerror(application.verbose_state.debug, \"ERROR pspecFig: Cannot parse '%s' option.\", argv[i]);\n   return 0;\n }\n twodfs2_allinfo.f2_min = twodfs_allinfo.f2_min;\n twodfs2_allinfo.f2_max = twodfs_allinfo.f2_max;\n      }else {\n if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, \"%lf %lf\", &(twodfs2_allinfo.f2_min), &(twodfs2_allinfo.f2_max), NULL) == 0) {\n   printerror(application.verbose_state.debug, \"ERROR pspecFig: Cannot parse '%s' option.\", argv[i]);\n   return 0;\n }\n      }\n      i++;\n    }else if(strcmp(argv[i], \"-long\") == 0 || strcmp(argv[i], \"-l\") == 0) {\n      plotoptions.SelectLRegion = 1;\n      if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, \"%lf %lf\", &(plotoptions.LRegionLow), &(plotoptions.LRegionHigh), NULL) == 0) {\n printerror(application.verbose_state.debug, \"ERROR pspecFig: Cannot parse '%s' option.\", argv[i]);\n return 0;\n      }\n      i++;\n    }else if(strcmp(argv[i], \"-phaseslope\") == 0) {\n      if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, \"%f %f\", &phase_slope_g, &phase_slope_o, NULL) == 0) {\n printerror(application.verbose_state.debug, \"ERROR pspecFig: Cannot parse '%s' option.\", argv[i]);\n return 0;\n      }\n      do_phase_slope = 1;\n      i++;\n    }else if(strcmp(argv[i], \"-scalel\") == 0\n      ) {\n      if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, \"%lf\", &(plotoptions.oversaturizel), NULL) == 0) {\n printerror(application.verbose_state.debug, \"ERROR pspecFig: Cannot parse '%s' option.\", argv[i]);\n return 0;\n      }\n      i++;\n    }else if(strcmp(argv[i], \"-scale2\") == 0\n      ) {\n      if(NrSelectedOverSaturize == 0) {\n if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, \"%lf\", &(twodfs_allinfo.oversaturize), NULL) == 0) {\n   printerror(application.verbose_state.debug, \"ERROR pspecFig: Cannot parse '%s' option.\", argv[i]);\n   return 0;\n }\n twodfs2_allinfo.oversaturize = twodfs_allinfo.oversaturize;\n NrSelectedOverSaturize = 1;\n      }else {\n if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, \"%lf\", &(twodfs2_allinfo.oversaturize), NULL) == 0) {\n   printerror(application.verbose_state.debug, \"ERROR pspecFig: Cannot parse '%s' option.\", argv[i]);\n   return 0;\n }\n      }\n      i++;\n    }else if(strcmp(argv[i], \"-modsigma\") == 0\n      ) {\n      if(parse_command_string(application.verbose_state, argc, argv, i+1, 0,-1, \"%f\", &maxsigma_mod, NULL) == 0) {\n printerror(application.verbose_state.debug, \"ERROR pspecFig: Cannot parse '%s' option.\", argv[i]);\n return 0;\n      }\n      i++;\n    }else if(strcmp(argv[i], \"-stddevsigma\") == 0\n      ) {\n      if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, \"%f\", &maxsigma_stddev, NULL) == 0) {\n printerror(application.verbose_state.debug, \"ERROR pspecFig: Cannot parse '%s' option.\", argv[i]);\n return 0;\n      }\n      i++;\n    }else if(strcmp(argv[i], \"-modmax\") == 0\n      ) {\n      if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, \"%f\", &maxvalue_mod, NULL) == 0) {\n printerror(application.verbose_state.debug, \"ERROR pspecFig: Cannot parse '%s' option.\", argv[i]);\n return 0;\n      }\n      i++;\n    }else if(strcmp(argv[i], \"-stddevmax\") == 0\n      ) {\n      if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, \"%f\", &maxvalue_stddev, NULL) == 0) {\n printerror(application.verbose_state.debug, \"ERROR pspecFig: Cannot parse '%s' option.\", argv[i]);\n return 0;\n      }\n      i++;\n    }else if(strcmp(argv[i], \"-s\") == 0) {\n      if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, \"%d\", &(plotoptions.ExtraVerticalMaximaSkip), NULL) == 0) {\n printerror(application.verbose_state.debug, \"ERROR pspecFig: Cannot parse '%s' option.\", argv[i]);\n return 0;\n      }\n      i++;\n    }else if(strcmp(argv[i], \"-title\") == 0\n      ) {\n      title_index = i+1;\n      i++;\n    }else if(strcmp(argv[i], \"-textside\") == 0\n      ) {\n      plotoptions.textside = argv[i+1];\n      i++;\n    }else if(strcmp(argv[i], \"-2dfsnr\") == 0) {\n      if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, \"%d\", &file_number, NULL) == 0) {\n printerror(application.verbose_state.debug, \"ERROR pspecFig: Cannot parse '%s' option.\", argv[i]);\n return 0;\n      }\n      i++;\n    }else if(strcmp(argv[i], \"-int\") == 0\n      ) {\n      if(twodfs_allinfo.SelectP3Integrate == 0) {\n twodfs_allinfo.SelectP3Integrate = 1;\n if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, \"%lf %lf\", &(twodfs_allinfo.P3IntegrateLow), &(twodfs_allinfo.P3IntegrateHigh), NULL) == 0) {\n   printerror(application.verbose_state.debug, \"ERROR pspecFig: Cannot parse '%s' option.\", argv[i]);\n   return 0;\n }\n twodfs2_allinfo.SelectP3Integrate = 1;\n twodfs2_allinfo.P3IntegrateLow = twodfs_allinfo.P3IntegrateLow;\n twodfs2_allinfo.P3IntegrateHigh = twodfs_allinfo.P3IntegrateHigh;\n      }else {\n twodfs2_allinfo.SelectP3Integrate = 1;\n if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, \"%lf %lf\", &(twodfs2_allinfo.P3IntegrateLow), &(twodfs2_allinfo.P3IntegrateHigh), NULL) == 0) {\n   printerror(application.verbose_state.debug, \"ERROR pspecFig: Cannot parse '%s' option.\", argv[i]);\n   return 0;\n }\n      }\n      i++;\n    }else if(strcmp(argv[i], \"-ytop\") == 0\n      ) {\n      plotoptions.plot_ylabeltop = 1;\n    }else if(strcmp(argv[i], \"-scalefig\") == 0) {\n      if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, \"%lf %lf\", &(plotoptions.scaleFig_x), &(plotoptions.scaleFig_y), NULL) == 0) {\n printerror(application.verbose_state.debug, \"ERROR pspecFig: Cannot parse '%s' option.\", argv[i]);\n return 0;\n      }\n      i++;\n    }else {\n      printerror(application.verbose_state.debug, \"Unknown option: %s\\nRun pspecFig without command line options for a help\", argv[i]);\n      terminateApplication(&application);\n      return 0;\n    }\n  }\n  copyVerboseState(application.verbose_state, &noverbose);\n  noverbose.verbose = 0;\n  cleanPSRData(&(twodfs_allinfo.datafile), application.verbose_state);\n  cleanPSRData(&(twodfs2_allinfo.datafile), application.verbose_state);\n  cleanPSRData(&lrfs, application.verbose_state);\n  cleanPSRData(&AverageProfile, application.verbose_state);\n  cleanPSRData(&VarianceProfile, application.verbose_state);\n  cleanPSRData(&VarianceProfileErr, application.verbose_state);\n  cleanPSRData(&ModProfile, application.verbose_state);\n  cleanPSRData(&ModProfileErr, application.verbose_state);\n  cleanPSRData(&subpulseTrackProfile, application.verbose_state);\n  cleanPSRData(&subpulseTrackProfileErr, application.verbose_state);\n  cleanPSRData(&subpulseAmpProfile, application.verbose_state);\n  if(type_of_plots == 0) {\n    if(loadLRFS(&lrfs, extprefix, longsnap, argc, argv, &plotoptions, application.verbose_state) == 0) {\n      return 0;\n    }\n  }\n  double period;\n  if(loadHeaderPulseStack(&AverageProfile, lrfs, &period, type_of_plots, argc, argv, application.verbose_state) == 0) {\n    return 0;\n  }\n  if(extprefix == 0) {\n    sprintf(txt, \"profile\");\n  }\n  if(change_filename_extension(argv[argc-1], filename, txt, 1000, application.verbose_state) == 0)\n    return 0;\n  if(altProf > 0) {\n    strncpy(filename, argv[altProf], 1000);\n  }\n  if(set_filename_PSRData(&AverageProfile, filename, application.verbose_state) == 0) {\n    fflush(stdout);\n    printerror(application.verbose_state.debug, \"ERROR psecFig: Setting file name failed.\");\n    return 0;\n  }\n  if(type_of_plots == 0) {\n    copy_params_PSRData(AverageProfile, &VarianceProfile, application.verbose_state);\n    copy_params_PSRData(AverageProfile, &ModProfile, application.verbose_state);\n    copy_params_PSRData(AverageProfile, &VarianceProfileErr, application.verbose_state);\n    copy_params_PSRData(AverageProfile, &ModProfileErr, application.verbose_state);\n    VarianceProfile.data = malloc(AverageProfile.NrBins*sizeof(float));\n    ModProfile.data = malloc(AverageProfile.NrBins*sizeof(float));\n    VarianceProfileErr.data = malloc(AverageProfile.NrBins*sizeof(float));\n    ModProfileErr.data = malloc(AverageProfile.NrBins*sizeof(float));\n    if(VarianceProfile.data == NULL || ModProfile.data == NULL || VarianceProfileErr.data == NULL || ModProfileErr.data == NULL) {\n      printerror(application.verbose_state.debug, \"Memory allocation error\");\n      return 0;\n    }\n  }else {\n    copy_params_PSRData(AverageProfile, &subpulseTrackProfile, application.verbose_state);\n    copy_params_PSRData(AverageProfile, &subpulseTrackProfileErr, application.verbose_state);\n    copy_params_PSRData(AverageProfile, &subpulseAmpProfile, application.verbose_state);\n    subpulseTrackProfile.data = malloc(AverageProfile.NrBins*sizeof(float));\n    subpulseTrackProfileErr.data = malloc(AverageProfile.NrBins*sizeof(float));\n    subpulseAmpProfile.data = malloc(AverageProfile.NrBins*sizeof(float));\n    if(subpulseTrackProfile.data == NULL || subpulseTrackProfileErr.data == NULL || subpulseAmpProfile.data == NULL) {\n      printerror(application.verbose_state.debug, \"Memory allocation error\");\n      return 0;\n    }\n  }\n  if(application.verbose_state.verbose)\n    printf(\"Reading %s\\n\", filename);\n  fout_ascii = fopen(filename, \"r\");\n  if(fout_ascii == NULL) {\n    printerror(application.verbose_state.debug, \"ERROR pspecFig: Unable to open %s.\", filename);\n    return 0;\n  }\n  for(i = 0; i < AverageProfile.NrBins; i++) {\n    if(type_of_plots == 0) {\n      j = fscanf(fout_ascii, \"%ld %f %f %f %f %f\", &k, &AverageProfile.data[i], &VarianceProfile.data[i], &VarianceProfileErr.data[i], &ModProfile.data[i], &ModProfileErr.data[i]);\n    }else {\n      float junk;\n      j = fscanf(fout_ascii, \"%ld %f %f %f %f %f\", &k, &AverageProfile.data[i], &junk, &junk, &junk, &junk);\n    }\n    if(j != 6) {\n printwarning(application.verbose_state.debug, \"WARNING: It looks like profile data is rebinned? Check the units.\");\n AverageProfile.fixedtsamp *= AverageProfile.NrBins/(double)(i);\n AverageProfile.tsampMode = TSAMPMODE_FIXEDTSAMP;\n AverageProfile.NrBins = i;\n printwarning(application.verbose_state.debug, \"WARNING: Assuming the number of bins = %ld and the sampling time = %lf s.\", AverageProfile.NrBins, AverageProfile.fixedtsamp);\n if(type_of_plots == 0) {\n   copy_params_PSRData(AverageProfile, &VarianceProfile, application.verbose_state);\n   copy_params_PSRData(AverageProfile, &ModProfile, application.verbose_state);\n   copy_params_PSRData(AverageProfile, &VarianceProfileErr, application.verbose_state);\n   copy_params_PSRData(AverageProfile, &ModProfileErr, application.verbose_state);\n }else {\n   copy_params_PSRData(AverageProfile, &subpulseTrackProfile, application.verbose_state);\n   copy_params_PSRData(AverageProfile, &subpulseTrackProfileErr, application.verbose_state);\n   copy_params_PSRData(AverageProfile, &subpulseAmpProfile, application.verbose_state);\n }\n break;\n    }\n    if(k != i) {\n      printerror(application.verbose_state.debug, \"Unexpected bin number\");\n      return 0;\n    }\n  }\n  fclose(fout_ascii);\n  if(application.verbose_state.verbose)\n    printf(\"%ld points read from %s\\n\", AverageProfile.NrBins, filename);\n  ret = get_period(AverageProfile, 0, &period, application.verbose_state);\n  if(ret == 2) {\n    printerror(application.verbose_state.debug, \"ERROR pspecFig (%s): Cannot obtain period\", AverageProfile.filename);\n    return 0;\n  }\n  plotoptions.fl_min = 0 + plotoptions.dl;\n  plotoptions.fl_max = 360*(AverageProfile.NrBins-1)*get_tsamp(AverageProfile, 0, application.verbose_state)/period + plotoptions.dl;\n  if(plotoptions.usephase) {\n    plotoptions.fl_min /= 360.0;\n    plotoptions.fl_max /= 360.0;\n  }\n  if(type_of_plots == 1) {\n    if(extprefix == 0) {\n      sprintf(txt, \"amplitude\");\n    }\n    if(change_filename_extension(argv[argc-1], filename, txt, 1000, application.verbose_state) == 0)\n      return 0;\n    if(application.verbose_state.verbose)\n      printf(\"Reading %s\\n\", filename);\n    fout_ascii = fopen(filename, \"r\");\n    if(fout_ascii == NULL) {\n      printerror(application.verbose_state.debug, \"ERROR pspecFig: Unable to open %s.\", filename);\n      return 0;\n    }\n    for(i = 0; i < AverageProfile.NrBins; i++) {\n      j = fscanf(fout_ascii, \"%ld %f\", &k, &subpulseAmpProfile.data[i]);\n      if(j != 2) {\n printerror(application.verbose_state.debug, \"Unexpected end of file (bin %d). Resolution in subpulse phase track doesn't match resolution in profile file?\", i+1);\n return 0;\n      }\n      if(k != i) {\n printerror(application.verbose_state.debug, \"Unexpected bin number\");\n return 0;\n      }\n    }\n    fclose(fout_ascii);\n    if(application.verbose_state.verbose)\n      printf(\"%ld points read from %s\\n\", AverageProfile.NrBins, filename);\n  }\n  if(type_of_plots == 1) {\n    if(extprefix == 0) {\n      sprintf(txt, \"track\");\n    }\n    if(change_filename_extension(argv[argc-1], filename, txt, 1000, application.verbose_state) == 0)\n      return 0;\n    if(application.verbose_state.verbose)\n      printf(\"Reading %s\\n\", filename);\n    fout_ascii = fopen(filename, \"r\");\n    if(fout_ascii == NULL) {\n      printerror(application.verbose_state.debug, \"ERROR pspecFig: Unable to open %s.\", filename);\n      return 0;\n    }\n    for(i = 0; i < AverageProfile.NrBins; i++) {\n      j = fscanf(fout_ascii, \"%ld %f %f\", &k, &subpulseTrackProfile.data[i], &subpulseTrackProfileErr.data[i]);\n      if(j != 3) {\n printerror(application.verbose_state.debug, \"Unexpected end of file (bin %d). Resolution in subpulse phase track doesn't match resolution in profile file?\", i+1);\n return 0;\n      }\n      if(k != i) {\n printerror(application.verbose_state.debug, \"Unexpected bin number\");\n return 0;\n      }\n    }\n    fclose(fout_ascii);\n    if(application.verbose_state.verbose)\n      printf(\"%ld points read from %s\\n\", AverageProfile.NrBins, filename);\n  }\n  twodfs_allinfo.f3_min = 0;\n  twodfs_allinfo.f3_max = 0.5;\n  if(type_of_plots == 0 && Load2dfs != 0) {\n    if(load2dfs(&twodfs_allinfo, AverageProfile, file_number, extprefix, 0, argc, argv, plotoptions, application.verbose_state) == 0) {\n      return 0;\n    }\n    if(LoadTwo != 0) {\n      file_number++;\n      if(load2dfs(&twodfs2_allinfo, AverageProfile, file_number, extprefix, 0, argc, argv, plotoptions, application.verbose_state) == 0) {\n return 0;\n      }\n    }\n    if(plotoptions.SelectP3Region != 0) {\n      twodfs_allinfo.f3_min = P3RegionLow;\n      twodfs_allinfo.f3_max = P3RegionHigh;\n      twodfs2_allinfo.f3_min = P3RegionLow;\n      twodfs2_allinfo.f3_max = P3RegionHigh;\n    }\n    if(twodfs_allinfo.SelectP3Integrate == 0) {\n      twodfs_allinfo.P3IntegrateLow = twodfs_allinfo.f3_min;\n      twodfs_allinfo.P3IntegrateHigh = twodfs_allinfo.f3_max;\n      twodfs2_allinfo.P3IntegrateLow = twodfs_allinfo.f3_min;\n      twodfs2_allinfo.P3IntegrateHigh = twodfs_allinfo.f3_max;\n    }\n  }\n  ppgopen(PlotDevice);\n  ppgask(0);\n  ppgslw(1);\n  ppgpage();\n  ppgslw(1);\n  ppgscf(1);\n  ppgsch(0.38*plotoptions.labelscale);\n  if(plotoptions.notop == 0) {\n    ppgsch(0.55*plotoptions.labelscale*plotoptions.titlescale);\n    ppgscf(2);\n    ppgslw(2);\n    ppgsvp(0.2, 0.2+0.11*plotoptions.scaleFig_x, 0.95-0.15*plotoptions.scaleFig_y, 0.95);\n    if(title_index > 0) {\n      ppgmtxt(\"t\",1,0.5,0.5,argv[title_index]);\n    }\n    ppgslw(1);\n    ppgscf(1);\n    ppgsch(0.38*plotoptions.labelscale);\n    plotoptions.Imin = 0;\n    plotoptions.Imax = 0;\n    ret = get_period(AverageProfile, 0, &period, application.verbose_state);\n    if(ret == 2) {\n      printerror(application.verbose_state.debug, \"ERROR pspecFig (%s): Cannot obtain period\", AverageProfile.filename);\n      return 0;\n    }\n    for(xi=0; xi < AverageProfile.NrBins; xi++) {\n      double xpos;\n      xpos = xi*get_tsamp(AverageProfile, 0, application.verbose_state)*360.0/period;\n      if(plotoptions.usephase)\n xpos /= 360.0;\n      if(xpos >= plotoptions.fl_min && xpos <= plotoptions.fl_max) {\n I = AverageProfile.data[xi];\n if(I > plotoptions.Imax)\n   plotoptions.Imax = I;\n if(I < plotoptions.Imin)\n   plotoptions.Imin = I;\n      }\n    }\n    if(plotoptions.SelectLRegion != 0) {\n      plotoptions.fl_min = plotoptions.LRegionLow;\n      plotoptions.fl_max = plotoptions.LRegionHigh;\n    }\n    if(type_of_plots == 0) {\n      for(xi=0; xi < ModProfile.NrBins; xi++) {\n double xpos;\n xpos = xi*get_tsamp(AverageProfile, 0, application.verbose_state)*360.0/period;\n if(plotoptions.usephase)\n   xpos /= 360.0;\n if(xpos+plotoptions.dl >= plotoptions.fl_min && xpos+plotoptions.dl <= plotoptions.fl_max) {\n   ok_flag = 1;\n   if(maxsigma_mod > 0 && ModProfile.data[xi]/ModProfileErr.data[xi] < maxsigma_mod)\n     ok_flag = 0;\n   if(maxvalue_mod > 0 && ModProfile.data[xi] > maxvalue_mod)\n     ok_flag = 0;\n   if(ok_flag) {\n     I = ModProfile.data[xi];\n     if(I+ModProfileErr.data[xi] > plotoptions.Imax)\n       plotoptions.Imax = I+ModProfileErr.data[xi];\n     if(I-ModProfileErr.data[xi] < plotoptions.Imin)\n       plotoptions.Imin = I-ModProfileErr.data[xi];\n   }\n }\n      }\n      for(xi=0; xi < VarianceProfile.NrBins; xi++) {\n double xpos;\n xpos = xi*get_tsamp(AverageProfile, 0, application.verbose_state)*360.0/period;\n if(plotoptions.usephase)\n   xpos /= 360.0;\n if(xpos + plotoptions.dl >= plotoptions.fl_min && xpos + plotoptions.dl <= plotoptions.fl_max) {\n   I = VarianceProfile.data[xi];\n   if(I > plotoptions.Imax)\n     plotoptions.Imax = I;\n   if(I < plotoptions.Imin)\n     plotoptions.Imin = I;\n }\n      }\n    }else {\n      for(xi=0; xi < subpulseAmpProfile.NrBins; xi++) {\n double xpos;\n xpos = xi*get_tsamp(AverageProfile, 0, application.verbose_state)*360.0/period;\n if(plotoptions.usephase)\n   xpos /= 360.0;\n if(xpos + plotoptions.dl >= plotoptions.fl_min && xpos + plotoptions.dl <= plotoptions.fl_max) {\n   I = subpulseAmpProfile.data[xi];\n   if(I > plotoptions.Imax)\n     plotoptions.Imax = I;\n   if(I < plotoptions.Imin)\n     plotoptions.Imin = I;\n }\n      }\n    }\n    if(-0.05*plotoptions.Imax < plotoptions.Imin)\n      plotoptions.Imin = -0.05*plotoptions.Imax;\n    if(ImaxSet)\n      plotoptions.Imax = ImaxValue/1.05;\n    if(IminSet)\n      plotoptions.Imin = IminValue/1.05;\n    ppgswin(plotoptions.fl_min, plotoptions.fl_max, plotoptions.Imin, 1.05*plotoptions.Imax);\n    if(LoadLRFS == 0) {\n      if(plotoptions.inside) {\n if(plotoptions.noylabels) {\n   ppgbox(\"bcnst\",0.0,0,\"bcst\",0.0,0);\n }else {\n   ppgbox(\"bcnst\",0.0,0,\"bcnst\",0.0,0);\n }\n      }else {\n if(plotoptions.noylabels) {\n   ppgbox(\"bcnst\",0.0,0,\"bcsti\",0.0,0);\n }else {\n   ppgbox(\"bcnst\",0.0,0,\"bcnsti\",0.0,0);\n }\n      }\n    }else {\n      if(plotoptions.inside) {\n if(plotoptions.noylabels) {\n   ppgbox(\"cst\",0.0,0,\"bcst\",0.0,0);\n }else {\n   ppgbox(\"cst\",0.0,0,\"bcnst\",0.0,0);\n }\n      }else {\n if(plotoptions.noylabels) {\n   ppgbox(\"cst\",0.0,0,\"bcsti\",0.0,0);\n }else {\n   ppgbox(\"cst\",0.0,0,\"bcnsti\",0.0,0);\n }\n      }\n    }\n    if(plotoptions.plot_xlabel != 0 && LoadLRFS == 0) {\n      ppgsch(0.3*plotoptions.labelscale);\n      if(plotoptions.usephase)\n ppgmtxt(\"b\",3.0,0.5,0.5,\"Pulse longitude (phase)\");\n      else\n ppgmtxt(\"b\",3.0,0.5,0.5,\"Pulse longitude (deg)\");\n      ppgsch(0.38*plotoptions.labelscale);\n    }\n    ppgsls(lineStyle);\n    ppgslw(2);\n    ppgsci(plotoptions.lineColour);\n    i = 0;\n    double deg_per_sample;\n    deg_per_sample = get_tsamp(AverageProfile, 0, application.verbose_state)*360.0/period;\n    for(xi=0; xi < AverageProfile.NrBins; xi++) {\n      double xpos;\n      xpos = xi*deg_per_sample;\n      if(plotoptions.usephase)\n xpos /= 360.0;\n      if(xpos+plotoptions.dl >= plotoptions.fl_min-deg_per_sample && xpos+plotoptions.dl <= plotoptions.fl_max+deg_per_sample) {\n I = AverageProfile.data[xi]*profilescale;\n if(i == 0) {\n   ppgmove(xpos+plotoptions.dl,I);\n   i = 1;\n }else {\n   ppgdraw(xpos+plotoptions.dl,I);\n }\n      }\n    }\n    ppgsci(1);\n    if(type_of_plots == 0) {\n      if(plotvariance) {\n i = 0;\n ppgsls(1);\n ppgslw(1);\n ppgscr(20, 0.5, 0.5, 0.5);\n ppgsci(20);\n for(xi=0; xi < AverageProfile.NrBins; xi++) {\n   x = xi*get_tsamp(AverageProfile, 0, application.verbose_state)*360.0/period;\n   if(plotoptions.usephase)\n     x /= 360.0;\n   x += plotoptions.dl;\n   if(x >= plotoptions.fl_min-deg_per_sample && x <= plotoptions.fl_max+deg_per_sample) {\n     I = VarianceProfile.data[xi];\n     ok_flag = 1;\n     if(maxsigma_stddev > 0 && VarianceProfile.data[xi]/VarianceProfileErr.data[xi] < maxsigma_stddev)\n       ok_flag = 0;\n     if(maxvalue_stddev > 0 && VarianceProfile.data[xi] > maxvalue_stddev)\n       ok_flag = 0;\n     if(ok_flag == 0) {\n       I = 0;\n       i = 0;\n     }else {\n       if(i == 0) {\n  ppgmove(x,I);\n  i = 1;\n       }else {\n  ppgsci(20);\n  ppgdraw(x,I);\n       }\n       ppgsci(1);\n       ppgpt1(x, I, 4);\n     }\n   }\n }\n ppgsci(1);\n      }\n      if(plotmodindex) {\n i = 0;\n ppgsls(1);\n ppgslw(1);\n for(xi=0; xi < ModProfile.NrBins; xi++) {\n   x = xi*get_tsamp(AverageProfile, 0, application.verbose_state)*360.0/period;\n   if(plotoptions.usephase)\n     x /= 360.0;\n   x += plotoptions.dl;\n   if(x >= plotoptions.fl_min-deg_per_sample && x <= plotoptions.fl_max+deg_per_sample) {\n     I = ModProfile.data[xi];\n     ok_flag = 1;\n     if(maxsigma_mod > 0 && ModProfile.data[xi]/ModProfileErr.data[xi] < maxsigma_mod)\n       ok_flag = 0;\n     if(maxvalue_mod > 0 && ModProfile.data[xi] > maxvalue_mod)\n       ok_flag = 0;\n     if(ok_flag == 0) {\n       I = 0;\n       i = 0;\n     }else {\n       if(i == 0) {\n  ppgmove(x,I);\n  i = 1;\n       }else {\n  ppgdraw(x,I);\n       }\n     }\n   }\n }\n ppgsls(1);\n ppgslw(1);\n for(xi=0; xi < ModProfile.NrBins; xi++) {\n   x = xi*get_tsamp(AverageProfile, 0, application.verbose_state)*360.0/period;\n   if(plotoptions.usephase)\n     x /= 360.0;\n   x += plotoptions.dl;\n   if(x >= plotoptions.fl_min-deg_per_sample && x <= plotoptions.fl_max+deg_per_sample) {\n     I = ModProfile.data[xi];\n     ok_flag = 1;\n     if(maxsigma_mod > 0 && ModProfile.data[xi]/ModProfileErr.data[xi] < maxsigma_mod)\n       ok_flag = 0;\n     if(maxvalue_mod > 0 && ModProfile.data[xi] > maxvalue_mod)\n       ok_flag = 0;\n     if(ok_flag != 0) {\n       ppgpt1(x, I, -1);\n       ppgerr1(6,x,I,ModProfileErr.data[xi], 1);\n     }\n   }\n }\n      }\n    }else {\n      i = 0;\n      ppgsls(4);\n      ppgslw(1);\n      for(xi=0; xi < AverageProfile.NrBins; xi++) {\n x = xi*get_tsamp(AverageProfile, 0, application.verbose_state)*360.0/period;\n if(plotoptions.usephase)\n   x /= 360.0;\n x += plotoptions.dl;\n if(x >= plotoptions.fl_min-deg_per_sample && x <= plotoptions.fl_max+deg_per_sample) {\n   I = subpulseAmpProfile.data[xi];\n   if(i == 0) {\n     ppgmove(x, I);\n     i = 1;\n   }else {\n     ppgdraw(x, I);\n   }\n }\n      }\n      ppgsls(1);\n    }\n    if(plotoptions.plot_ylabel != 0) {\n      ppgsch(0.3*plotoptions.labelscale);\n      if(plotoptions.plot_ylabeltop) {\n if(type_of_plots == 0) {\n   ppgmtxt(\"l\",2.8,0.5,0.5,\"Intensity/Modulation index\");\n }else {\n   ppgmtxt(\"l\",2.8,0.5,0.5,\"Intensity\");\n }\n      }\n      ppgsch(0.38*plotoptions.labelscale);\n    }\n  }\n  if(type_of_plots == 0) {\n    if(Load2dfs != 0 && LoadLRFS == 0) {\n      char *title;\n      title = NULL;\n      if(title_index > 0 && plotoptions.notop && LoadLRFS == 0) {\n title = argv[title_index];\n      }\n      Plot2dfs(twodfs_allinfo, twodfs2_allinfo, AverageProfile, 1, 0, title, plotoptions, application.verbose_state);\n      if (LoadTwo != 0) {\n Plot2dfs(twodfs_allinfo, twodfs2_allinfo, AverageProfile, 1, 1, NULL, plotoptions, application.verbose_state);\n      }\n    }else {\n      if(LoadLRFS != 0) {\n char *title;\n title = NULL;\n if(title_index > 0 && plotoptions.notop) {\n   title = argv[title_index];\n }\n PlotLRFS(lrfs, AverageProfile, twodfs_allinfo, title, plotoptions, application.verbose_state);\n      }\n      if(Load2dfs != 0) {\n Plot2dfs(twodfs_allinfo, twodfs2_allinfo, AverageProfile, 0, 0, NULL, plotoptions, application.verbose_state);\n      }\n      if(LoadTwo != 0) {\n Plot2dfs(twodfs_allinfo, twodfs2_allinfo, AverageProfile, 0, 1, NULL, plotoptions, application.verbose_state);\n      }\n    }\n  }else {\n    ppgsvp(0.2, 0.2+0.11*plotoptions.scaleFig_x, 0.95-0.3*plotoptions.scaleFig_y, 0.95-0.15*plotoptions.scaleFig_y);\n    ppgslw(1);\n    ppgscf(1);\n    ppgsch(0.38*plotoptions.labelscale);\n    plotoptions.Imin = 0;\n    plotoptions.Imax = 0;\n    for(xi=0; xi < subpulseTrackProfile.NrBins; xi++) {\n      double xpos;\n      xpos = xi*get_tsamp(AverageProfile, 0, application.verbose_state)*360.0/period;\n      if(plotoptions.usephase)\n xpos /= 360.0;\n      if(xpos+plotoptions.dl >= plotoptions.fl_min && xpos+plotoptions.dl <= plotoptions.fl_max) {\n I = subpulseTrackProfile.data[xi];\n if(plotoptions.doFlip)\n   I *= -1;\n if(I+subpulseTrackProfileErr.data[xi] > plotoptions.Imax)\n   plotoptions.Imax = I+subpulseTrackProfileErr.data[xi];\n if(I-subpulseTrackProfileErr.data[xi] < plotoptions.Imin)\n   plotoptions.Imin = I-subpulseTrackProfileErr.data[xi];\n      }\n    }\n    if(plotoptions.SelectLRegion != 0) {\n      plotoptions.fl_min = plotoptions.LRegionLow;\n      plotoptions.fl_max = plotoptions.LRegionHigh;\n    }\n    if(maxSubpulsePhaseSet)\n      plotoptions.Imax = maxSubpulsePhase/1.05;\n    if(minSubpulsePhaseSet)\n      plotoptions.Imin = minSubpulsePhase/1.05;\n    ppgswin(plotoptions.fl_min, plotoptions.fl_max, plotoptions.Imin, 1.05*plotoptions.Imax);\n    if(plotoptions.inside) {\n      if(plotoptions.noylabels) {\n ppgbox(\"bcnst\",0.0,0,\"bcst\",0.0,0);\n      }else {\n ppgbox(\"bcnst\",0.0,0,\"bcnst\",0.0,0);\n      }\n    }else {\n      if(plotoptions.noylabels) {\n ppgbox(\"bcnst\",0.0,0,\"bcsti\",0.0,0);\n      }else {\n ppgbox(\"bcnst\",0.0,0,\"bcnsti\",0.0,0);\n      }\n    }\n    if(plotoptions.plot_xlabel != 0 && LoadLRFS == 0) {\n      ppgsch(0.3*plotoptions.labelscale);\n      if(plotoptions.usephase)\n ppgmtxt(\"b\",3.0,0.5,0.5,\"Pulse longitude (phase)\");\n      else\n ppgmtxt(\"b\",3.0,0.5,0.5,\"Pulse longitude (deg)\");\n      ppgsch(0.38*plotoptions.labelscale);\n    }\n    if(do_phase_slope) {\n      ppgsls(4);\n      if(plotoptions.usephase == 0) {\n x = plotoptions.dl;\n I = x*phase_slope_g + phase_slope_o;\n I = derotate_deg(I);\n ppgmove(x, I);\n ppgdraw(x+360, I+phase_slope_g*360);\n ppgmove(x, I-360);\n ppgdraw(x+360, I-360+phase_slope_g*360);\n ppgmove(x, I-2*360);\n ppgdraw(x+360, I-2*360+phase_slope_g*360);\n ppgmove(x, I+360);\n ppgdraw(x+360, I+360+phase_slope_g*360);\n ppgmove(x, I+2*360);\n ppgdraw(x+360, I+2*360+phase_slope_g*360);\n      }else {\n x = plotoptions.dl;\n I = x*360.0*phase_slope_g + phase_slope_o;\n I = derotate_deg(I);\n ppgmove(x, I);\n ppgdraw(x+1.0, I+phase_slope_g*360);\n ppgmove(x, I-360);\n ppgdraw(x+1.0, I-360+phase_slope_g*360);\n ppgmove(x, I-2*360);\n ppgdraw(x+1.0, I-2*360+phase_slope_g*360);\n ppgmove(x, I+360);\n ppgdraw(x+1.0, I+360+phase_slope_g*360);\n ppgmove(x, I+2*360);\n ppgdraw(x+1.0, I+2*360+phase_slope_g*360);\n      }\n      ppgsls(1);\n    }\n    ppgscr(20, 0.5, 0.5, 0.5);\n    ppgsci(20);\n    ppgsls(1);\n    ppgslw(1);\n    for(xi=0; xi < subpulseTrackProfile.NrBins; xi++) {\n      x = xi*get_tsamp(AverageProfile, 0, application.verbose_state)*360.0/period;\n      if(plotoptions.usephase)\n x /= 360.0;\n      x += plotoptions.dl;\n      if(x >= plotoptions.fl_min && x <= plotoptions.fl_max) {\n I = subpulseTrackProfile.data[xi];\n if(plotoptions.doFlip)\n   I *= -1;\n ppgerr1(6,x,I,subpulseTrackProfileErr.data[xi], 1);\n ppgerr1(6,x,I+360,subpulseTrackProfileErr.data[xi], 1);\n ppgerr1(6,x,I-360,subpulseTrackProfileErr.data[xi], 1);\n      }\n    }\n    ppgsci(1);\n    ppgslw(3);\n    for(xi=0; xi < subpulseTrackProfile.NrBins; xi++) {\n      x = xi*get_tsamp(AverageProfile, 0, application.verbose_state)*360.0/period;\n      if(plotoptions.usephase)\n x /= 360.0;\n      x += plotoptions.dl;\n      if(x >= plotoptions.fl_min && x <= plotoptions.fl_max) {\n I = subpulseTrackProfile.data[xi];\n if(plotoptions.doFlip)\n   I *= -1;\n ppgpt1(x, I, -1);\n ppgpt1(x, I+360, -1);\n ppgpt1(x, I-360, -1);\n      }\n    }\n    ppgslw(1);\n    if(plotoptions.plot_xlabel != 0) {\n      ppgsch(0.3*plotoptions.labelscale);\n      if(plotoptions.usephase)\n ppgmtxt(\"b\",3.0,0.5,0.5,\"Pulse longitude (phase)\");\n      else\n ppgmtxt(\"b\",3.0,0.5,0.5,\"Pulse longitude (deg)\");\n      ppgsch(0.38*plotoptions.labelscale);\n    }\n    if(plotoptions.plot_ylabel != 0) {\n      ppgsch(0.3*plotoptions.labelscale);\n      if(plotoptions.usephase)\n ppgmtxt(\"l\",2.8,0.5,0.5,\"Subpulse phase (phase)\");\n      else\n ppgmtxt(\"l\",2.8,0.5,0.5,\"Subpulse phase (deg)\");\n      ppgsch(0.38*plotoptions.labelscale);\n    }\n  }\n  if(preprocess_checknan(AverageProfile, 1, noverbose)) {\n    printwarning(application.verbose_state.debug, \"WARNING: The profile data appears to have NAN's in them. Artifacts can be expected in the plot.\");\n  }\n  if(preprocess_checkinf(AverageProfile, 1, noverbose)) {\n    printwarning(application.verbose_state.debug, \"WARNING: The profile data appears to have INF's in them. Artifacts can be expected in the plot.\");\n  }\n  if(type_of_plots == 0) {\n    if(preprocess_checknan(VarianceProfile, 1, noverbose)) {\n      printwarning(application.verbose_state.debug, \"WARNING: The profile data appears to have NAN's in them. Artifacts can be expected in the plot.\");\n    }\n    if(preprocess_checkinf(VarianceProfile, 1, noverbose)) {\n      printwarning(application.verbose_state.debug, \"WARNING: The profile data appears to have INF's in them. Artifacts can be expected in the plot.\");\n    }\n    if(preprocess_checknan(ModProfile, 1, noverbose)) {\n      printwarning(application.verbose_state.debug, \"WARNING: The profile data appears to have NAN's in them. Artifacts can be expected in the plot.\");\n    }\n    if(preprocess_checkinf(ModProfile, 1, noverbose)) {\n      printwarning(application.verbose_state.debug, \"WARNING: The profile data appears to have INF's in them. Artifacts can be expected in the plot.\");\n    }\n    if(preprocess_checknan(VarianceProfileErr, 1, noverbose)) {\n      printwarning(application.verbose_state.debug, \"WARNING: The profile data appears to have NAN's in them. Artifacts can be expected in the plot.\");\n    }\n    if(preprocess_checkinf(VarianceProfileErr, 1, noverbose)) {\n      printwarning(application.verbose_state.debug, \"WARNING: The profile data appears to have INF's in them. Artifacts can be expected in the plot.\");\n    }\n    if(preprocess_checknan(ModProfileErr, 1, noverbose)) {\n      printwarning(application.verbose_state.debug, \"WARNING: The profile data appears to have NAN's in them. Artifacts can be expected in the plot.\");\n    }\n    if(preprocess_checkinf(ModProfileErr, 1, noverbose)) {\n      printwarning(application.verbose_state.debug, \"WARNING: The profile data appears to have INF's in them. Artifacts can be expected in the plot.\");\n    }\n  }else {\n    if(preprocess_checknan(subpulseTrackProfile, 1, noverbose)) {\n      printwarning(application.verbose_state.debug, \"WARNING: The profile data appears to have NAN's in them. Artifacts can be expected in the plot.\");\n    }\n    if(preprocess_checkinf(subpulseTrackProfile, 1, noverbose)) {\n      printwarning(application.verbose_state.debug, \"WARNING: The profile data appears to have INF's in them. Artifacts can be expected in the plot.\");\n    }\n    if(preprocess_checknan(subpulseTrackProfileErr, 1, noverbose)) {\n      printwarning(application.verbose_state.debug, \"WARNING: The profile data appears to have NAN's in them. Artifacts can be expected in the plot.\");\n    }\n    if(preprocess_checkinf(subpulseTrackProfileErr, 1, noverbose)) {\n      printwarning(application.verbose_state.debug, \"WARNING: The profile data appears to have INF's in them. Artifacts can be expected in the plot.\");\n    }\n    if(preprocess_checknan(subpulseAmpProfile, 1, noverbose)) {\n      printwarning(application.verbose_state.debug, \"WARNING: The profile data appears to have NAN's in them. Artifacts can be expected in the plot.\");\n    }\n    if(preprocess_checkinf(subpulseAmpProfile, 1, noverbose)) {\n      printwarning(application.verbose_state.debug, \"WARNING: The profile data appears to have INF's in them. Artifacts can be expected in the plot.\");\n    }\n  }\n  ppgend();\n  closePSRData(&AverageProfile, 0, application.verbose_state);\n  closePSRData(&(twodfs_allinfo.datafile), 0, application.verbose_state);\n    closePSRData(&(twodfs2_allinfo.datafile), 0, application.verbose_state);\n  closePSRData(&lrfs, 0, application.verbose_state);\n  closePSRData(&VarianceProfile, 0, application.verbose_state);\n  closePSRData(&ModProfile, 0, application.verbose_state);\n  closePSRData(&VarianceProfileErr, 0, application.verbose_state);\n  closePSRData(&ModProfileErr, 0, application.verbose_state);\n  closePSRData(&subpulseTrackProfile, 0, application.verbose_state);\n  closePSRData(&subpulseTrackProfileErr, 0, application.verbose_state);\n  closePSRData(&subpulseAmpProfile, 0, application.verbose_state);\n  terminateApplication(&application);\n  return 0;\n}\nvoid GetExtremesSubsetVertical(twodfs_def twodfs_allinfo, float *Imin, float *Imax)\n{\n  float I, x, y;\n  int xi, yi;\n  *Imin = 0;\n  *Imax = 0;\n  for(xi = 0; xi < twodfs_allinfo.datafile.NrBins; xi++) {\n    I = 0;\n    for(yi = 0; yi < twodfs_allinfo.datafile.NrSubints; yi++) {\n      pgplotMapCoordinateInverse(&x, &y, xi, yi);\n      if(y >= twodfs_allinfo.P3IntegrateLow && y <= twodfs_allinfo.P3IntegrateHigh) {\n if(x >= twodfs_allinfo.f2_min && x <= twodfs_allinfo.f2_max) {\n   I += twodfs_allinfo.datafile.data[yi*twodfs_allinfo.datafile.NrBins+xi];\n }\n      }\n    }\n    if(I < *Imin)\n      *Imin = I;\n    if(I > *Imax)\n      *Imax = I;\n  }\n  *Imin *= 2.0;\n  *Imax *= 2.0;\n}\nvoid GetExtremesSubsetHorizontal(datafile_definition spectrum, int istwodfs, double f2_min, double f2_max, double f3_min, double f3_max, float *Imin, float *Imax, plotoptions_def plotoptions)\n{\n  float I, x, y;\n  int xi, yi, ok;\n  *Imin = 0;\n  *Imax = 0;\n  for(yi = plotoptions.ExtraVerticalMaximaSkip; yi < spectrum.NrSubints; yi++) {\n    I = 0;\n    for(xi = 0; xi < spectrum.NrBins; xi++) {\n      pgplotMapCoordinateInverse(&x, &y, xi, yi);\n      ok = 0;\n      if(istwodfs == 0) {\n if(x >= plotoptions.fl_min && x <= plotoptions.fl_max && y >= f3_min && y <= f3_max) {\n   ok = 1;\n }\n      }else {\n if(x >= f2_min && x <= f2_max && y >= f3_min && y <= f3_max) {\n   ok = 1;\n }\n      }\n      if(ok) {\n I += spectrum.data[yi*spectrum.NrBins+xi];\n      }\n    }\n    if(I < *Imin)\n      *Imin = I;\n    if(I > *Imax)\n      *Imax = I;\n  }\n  *Imin *= 2.0;\n  *Imax *= 2.0;\n}\nvoid IntegrateSubsetHorizontal(datafile_definition lrfs, twodfs_def twodfs_allinfo, twodfs_def twodfs2_allinfo, int twodfsonly, int Number, int normalise, plotoptions_def plotoptions)\n{\n  float I, Imin, Imax, x, y;\n  int xi, yi;\n  float offset;\n  offset = 0+0.03*(plotoptions.labelscale-1.0)*((float)Number+1.0);\n  if(Number == -1) {\n    ppgsvp(0.2-0.04*plotoptions.scaleFig_x, 0.2, 0.95-0.3*plotoptions.scaleFig_y, 0.95-0.15*plotoptions.scaleFig_y);\n  }else {\n    if(twodfsonly == 0) {\n      ppgsvp(0.2-0.04*plotoptions.scaleFig_x, 0.2, 0.95-0.48*plotoptions.scaleFig_y-0.22*Number*plotoptions.scaleFig_y-offset*plotoptions.scaleFig_y, 0.95-0.33*plotoptions.scaleFig_y-0.22*Number*plotoptions.scaleFig_y-offset*plotoptions.scaleFig_y);\n    }else {\n      ppgsvp(0.2-0.04*plotoptions.scaleFig_x, 0.2, 0.95-0.33*plotoptions.scaleFig_y-0.22*Number*plotoptions.scaleFig_y-offset*plotoptions.scaleFig_y, 0.95-0.18*plotoptions.scaleFig_y-0.22*Number*plotoptions.scaleFig_y-offset*plotoptions.scaleFig_y);\n    }\n  }\n  if(Number == -1) {\n    GetExtremesSubsetHorizontal(lrfs, 0, 0.0, 0.0, twodfs_allinfo.f3_min, twodfs_allinfo.f3_max, &Imin, &Imax, plotoptions);\n  }else if(Number == 0) {\n    GetExtremesSubsetHorizontal(twodfs_allinfo.datafile, 1, twodfs_allinfo.f2_min, twodfs_allinfo.f2_max, twodfs_allinfo.f3_min, twodfs_allinfo.f3_max, &Imin, &Imax, plotoptions);\n  }else {\n    GetExtremesSubsetHorizontal(twodfs2_allinfo.datafile, 1, twodfs2_allinfo.f2_min, twodfs2_allinfo.f2_max, twodfs2_allinfo.f3_min, twodfs2_allinfo.f3_max, &Imin, &Imax, plotoptions);\n  }\n  double scale;\n  scale = fabs(Imax);\n  if(fabs(Imin) > scale)\n    scale = fabs(Imin);\n  if(normalise == 0)\n    scale = 1.0;\n  ppgswin(Imin/scale,1.05*Imax/scale, twodfs_allinfo.f3_min,twodfs_allinfo.f3_max);\n  ppgbox(\"bcv\",0.0,0,\"bnsti\",0.0,0);\n  ppgbox(\"\",0.0,0,\"c\",0.0,0);\n  if(plotoptions.textside != NULL) {\n    if(twodfsonly == 0) {\n      if(Number == -1) {\n ppgsch(0.55*plotoptions.labelscale*plotoptions.titlescale);\n ppgscf(2);\n ppgslw(2);\n if (plotoptions.notop == 1) {\n   ppgtext(Imin, (twodfs_allinfo.f3_max-twodfs_allinfo.f3_min)*1.15, plotoptions.textside);\n } else {\n   ppgtext(Imin, (twodfs_allinfo.f3_max-twodfs_allinfo.f3_min)*2.095, plotoptions.textside);\n }\n ppgslw(1);\n ppgscf(1);\n ppgsch(0.38*plotoptions.labelscale);\n      }\n    }else {\n      if(strlen(plotoptions.textside) != 0 && plotoptions.notop == 0) {\n ppgsch(0.55*plotoptions.labelscale*plotoptions.titlescale);\n ppgscf(2);\n ppgslw(2);\n ppgtext(Imin, (twodfs_allinfo.f3_max-twodfs_allinfo.f3_min)+0.65, plotoptions.textside);\n ppgslw(1);\n ppgscf(1);\n ppgsch(0.38*plotoptions.labelscale);\n      }else if (strlen(plotoptions.textside) != 0 && plotoptions.notop == 1) {\n ppgsch(0.55*plotoptions.labelscale*plotoptions.titlescale);\n ppgscf(2);\n ppgslw(2);\n ppgtext(Imin, (twodfs_allinfo.f3_max-twodfs_allinfo.f3_min)+0.1, plotoptions.textside);\n ppgslw(1);\n ppgscf(1);\n ppgsch(0.38*plotoptions.labelscale);\n      }\n    }\n  }\n  y = floor(log10(Imax*0.33/scale));\n  x = floor(Imax*0.33/(pow(10,y)*scale));\n  x = x*pow(10,y);\n  char labelnumbers[3];\n  if(plotoptions.nointegrateNumbers == 0) {\n    strcpy(labelnumbers, \"n\");\n  }else {\n    strcpy(labelnumbers, \"\");\n  }\n  ppgsch(0.38*plotoptions.labelscale*0.66);\n  ppgaxis(labelnumbers,0,twodfs_allinfo.f3_max,Imax*0.33/scale,twodfs_allinfo.f3_max,0,Imax*0.33/scale,x,1,0.3,0,0,-0.5,90);\n  ppgsch(0.38*plotoptions.labelscale);\n  datafile_definition *spectrum;\n  double xmin, xmax, ymin, ymax;\n  if(Number == -1) {\n    spectrum = &lrfs;\n    xmin = plotoptions.fl_min;\n    xmax = plotoptions.fl_max;\n    ymin = twodfs_allinfo.f3_min;\n    ymax = twodfs_allinfo.f3_max;\n  }else if(Number == 0) {\n    spectrum = &(twodfs_allinfo.datafile);\n    xmin = twodfs_allinfo.f2_min;\n    xmax = twodfs_allinfo.f2_max;\n    ymin = twodfs_allinfo.f3_min;\n    ymax = twodfs_allinfo.f3_max;\n  }else if(Number == 1) {\n    spectrum = &(twodfs2_allinfo.datafile);\n    xmin = twodfs2_allinfo.f2_min;\n    xmax = twodfs2_allinfo.f2_max;\n    ymin = twodfs2_allinfo.f3_min;\n    ymax = twodfs2_allinfo.f3_max;\n  }\n  for(yi = 0; yi < spectrum->NrSubints; yi++) {\n    I = 0;\n    for(xi = 0; xi < spectrum->NrBins; xi++) {\n      pgplotMapCoordinateInverse(&x, &y, xi, yi);\n      if(x >= xmin && x <= xmax && y >= ymin && y <= ymax) {\n I += spectrum->data[yi*spectrum->NrBins+xi];\n      }\n    }\n    if(yi == 0) {\n      ppgmove(2.0*I/scale, y);\n    }else {\n      ppgdraw(2.0*I/scale, y);\n    }\n  }\n}\nvoid PlotLRFS(datafile_definition lrfs, datafile_definition AverageProfile, twodfs_def twodfs_allinfo, char *title, plotoptions_def plotoptions, verbose_definition verbose)\n{\n  float I;\n  int xi, i;\n  ppgsvp(0.2, 0.2+0.11*plotoptions.scaleFig_x, 0.95-0.3*plotoptions.scaleFig_y, 0.95-0.15*plotoptions.scaleFig_y);\n  if(title != NULL) {\n    ppgsch(0.55*plotoptions.labelscale*plotoptions.titlescale);\n    ppgscf(2);\n    ppgslw(2);\n    ppgmtxt(\"t\",1,0.5,0.5,title);\n    ppgslw(1);\n    ppgscf(1);\n    ppgsch(0.38*plotoptions.labelscale);\n  }\n  if(plotoptions.SelectLRegion != 0) {\n    plotoptions.fl_min = plotoptions.LRegionLow;\n    plotoptions.fl_max = plotoptions.LRegionHigh;\n  }\n  ppgswin(plotoptions.fl_min,plotoptions.fl_max,twodfs_allinfo.f3_min,twodfs_allinfo.f3_max);\n  if(plotoptions.plot_xlabel != 0) {\n    ppgsch(0.3*plotoptions.labelscale);\n    if(plotoptions.usephase)\n      ppgmtxt(\"b\",3.0,0.5,0.5,\"Pulse longitude (phase)\");\n    else\n      ppgmtxt(\"b\",3.0,0.5,0.5,\"Pulse longitude (deg)\");\n    ppgsch(0.38*plotoptions.labelscale);\n  }\n  if(plotoptions.plot_ylabel != 0) {\n    ppgsch(0.3*plotoptions.labelscale);\n    if(plotoptions.noside) {\n      if(plotoptions.plot_ylabel == 1)\n ppgmtxt(\"l\",2.8,0.5,0.5,\"Fluctuation frequency (cpp)\");\n      else if(plotoptions.plot_ylabel == 2)\n ppgmtxt(\"l\",2.8,0.5,0.5,\"Fluctuation frequency (P\\\\d0\\\\u/P\\\\d3\\\\u)\");\n      else if(plotoptions.plot_ylabel == 3)\n ppgmtxt(\"l\",2.8,0.5,0.5,\"Fluctuation frequency (P/P\\\\d3\\\\u)\");\n    }else {\n      float offset;\n      offset = 10 - (plotoptions.labelscale-1.0)*(7-2.8);\n      offset += 7*(plotoptions.scaleFig_x-1.0);\n      if(plotoptions.plot_ylabel == 1)\n ppgmtxt(\"l\",offset,0.5,0.5,\"Fluctuation frequency (cpp)\");\n      else if(plotoptions.plot_ylabel == 2)\n ppgmtxt(\"l\",offset,0.5,0.5,\"Fluctuation frequency (P\\\\d0\\\\u/P\\\\d3\\\\u)\");\n      else if(plotoptions.plot_ylabel == 3)\n ppgmtxt(\"l\",offset,0.5,0.5,\"Fluctuation frequency (P/P\\\\d3\\\\u)\");\n    }\n    ppgsch(0.38*plotoptions.labelscale);\n  }\n  pgplot_options_definition pgplot_options;\n  pgplot_clear_options(&pgplot_options);\n  pgplot_options.box.box_labelsize = 0.3*plotoptions.labelscale;\n  pgplot_options.viewport.dontopen = 1;\n  pgplot_options.viewport.dontclose = 1;\n  pgplot_options.viewport.noclear = 1;\n  double period;\n  int ret;\n  ret = get_period(lrfs, 0, &period, verbose);\n  if(ret == 2) {\n    printerror(verbose.debug, \"ERROR pspecFig (%s): Cannot obtain period\", lrfs.filename);\n    exit(0);\n  }\n  double xright;\n  xright = 360*(lrfs.NrBins-1)*get_tsamp(lrfs, 0, verbose)/period;\n  if(plotoptions.usephase)\n    xright /= 360.0;\n  pgplotMap(&pgplot_options, lrfs.data, lrfs.NrBins, lrfs.NrSubints, 0+plotoptions.dl, xright+plotoptions.dl, plotoptions.fl_min, plotoptions.fl_max, 0, 0.5, twodfs_allinfo.f3_min, twodfs_allinfo.f3_max, PPGPLOT_GRAYSCALE, 0, 0, 0, NULL, 0, 0, plotoptions.oversaturizel, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, plotoptions.showwedge, plotoptions.showwedge_max, 0, 0, verbose);\n  ret = get_period(AverageProfile, 0, &period, verbose);\n  if(ret == 2) {\n    printerror(verbose.debug, \"ERROR pspecFig (%s): Cannot obtain period\", AverageProfile.filename);\n    exit(0);\n  }\n  if(plotoptions.overlaypp) {\n    ppgsci(plotoptions.lineColour);\n    ppgsls(1);\n    ppgslw(1);\n    i = 0;\n    for(xi=0; xi < AverageProfile.NrBins; xi++) {\n      double xpos;\n      xpos = xi*get_tsamp(AverageProfile, 0, verbose)*360.0/period;\n      if(plotoptions.usephase)\n xpos /= 360.0;\n      if(xpos+plotoptions.dl >= plotoptions.fl_min && xpos+plotoptions.dl <= plotoptions.fl_max) {\n I = AverageProfile.data[xi]*0.5;\n if(i == 0) {\n   ppgmove(xpos+plotoptions.dl,I);\n   i = 1;\n }else {\n   ppgdraw(xpos+plotoptions.dl,I);\n }\n      }\n    }\n    ppgsci(1);\n  }\n  ppgswin(plotoptions.fl_min,plotoptions.fl_max,twodfs_allinfo.f3_min,twodfs_allinfo.f3_max);\n  ppgsch(0.38*plotoptions.labelscale);\n  if(plotoptions.noside) {\n    if(plotoptions.inside) {\n      if(plotoptions.noylabels)\n ppgbox(\"bcnst\",0.0,0,\"bcst\",0.0,0);\n      else\n ppgbox(\"bcnst\",0.0,0,\"bcnst\",0.0,0);\n    }else {\n      if(plotoptions.noylabels)\n ppgbox(\"bcnsti\",0.0,0,\"bcsti\",0.0,0);\n      else\n ppgbox(\"bcnsti\",0.0,0,\"bcnsti\",0.0,0);\n    }\n  }else {\n    if(plotoptions.inside) {\n      ppgbox(\"bcnst\",0.0,0,\"cst\",0.0,0);\n    }else {\n      ppgbox(\"bcnsti\",0.0,0,\"csti\",0.0,0);\n    }\n  }\n  if(plotoptions.noside == 0) {\n    IntegrateSubsetHorizontal(lrfs, twodfs_allinfo, twodfs_allinfo, 0, -1, plotoptions.normaliseSide, plotoptions);\n  }\n  ppgsch(0.38*plotoptions.labelscale);\n}\nvoid IntegrateSubsetVertical(twodfs_def twodfs_allinfo, int twodfsonly, int Number, int normalise, int nointegrateNumbers, plotoptions_def plotoptions)\n{\n  float I, Imin, Imax, x, y, offset;\n  int xi, yi;\n  offset = 0+0.03*(plotoptions.labelscale-1.0)*((float)Number+1.0);\n  if(twodfsonly == 0) {\n    ppgsvp(0.2, 0.2+0.11*plotoptions.scaleFig_x, 0.95-0.52*plotoptions.scaleFig_y-0.22*Number*plotoptions.scaleFig_y-offset*plotoptions.scaleFig_y, 0.95-0.48*plotoptions.scaleFig_y-0.22*Number*plotoptions.scaleFig_y-offset*plotoptions.scaleFig_y);\n  }else {\n    ppgsvp(0.2, 0.2+0.11*plotoptions.scaleFig_x, 0.95-0.37*plotoptions.scaleFig_y-0.22*Number*plotoptions.scaleFig_y-offset*plotoptions.scaleFig_y, 0.95-0.33*plotoptions.scaleFig_y-0.22*Number*plotoptions.scaleFig_y-offset*plotoptions.scaleFig_y);\n  }\n  GetExtremesSubsetVertical(twodfs_allinfo, &Imin, &Imax);\n  double scale;\n  scale = fabs(Imax);\n  if(fabs(Imin) > scale)\n    scale = fabs(Imin);\n  if(normalise == 0)\n    scale = 1.0;\n  ppgswin(twodfs_allinfo.f2_min,twodfs_allinfo.f2_max,Imin/scale,1.05*Imax/scale);\n  if(plotoptions.noxlabels == 0)\n    ppgbox(\"bnst\",0.0,0,\"bcvi\",0.0,0);\n  else\n    ppgbox(\"bst\",0.0,0,\"bcvi\",0.0,0);\n  ppgbox(\"c\",0.0,0,\"\",0.0,0);\n  y = floor(log10(Imax*0.7/scale));\n  x = floor(Imax*0.7/(pow(10,y)*scale));\n  x = x*pow(10,y);\n  char labelnumbers[3];\n  if(plotoptions.nointegrateNumbers == 0) {\n    strcpy(labelnumbers, \"n\");\n  }else {\n    strcpy(labelnumbers, \"\");\n  }\n  ppgsch(0.38*plotoptions.labelscale*0.66);\n  ppgaxis(labelnumbers,twodfs_allinfo.f2_min, 0,twodfs_allinfo.f2_min, Imax*.7/scale,0,Imax*.7/scale,x,1,0.3,0,0,-0.8,90);\n  ppgsch(0.38*plotoptions.labelscale);\n  int direction;\n  for(direction = 1-plotoptions.intflip; direction < 2; direction++) {\n    if(direction == 0) {\n      ppgsci(8);\n      ppgsls(2);\n    }else {\n      ppgsci(1);\n      ppgsls(1);\n    }\n    for(xi = 0; xi < twodfs_allinfo.datafile.NrBins; xi++) {\n      I = 0;\n      for(yi = 0; yi < twodfs_allinfo.datafile.NrSubints; yi++) {\n pgplotMapCoordinateInverse(&x, &y, xi, yi);\n if(y >= twodfs_allinfo.P3IntegrateLow && y <= twodfs_allinfo.P3IntegrateHigh)\n   I += twodfs_allinfo.datafile.data[yi*twodfs_allinfo.datafile.NrBins+xi];\n      }\n      if(direction == 0)\n x *= -1.0;\n      if(xi == 0) {\n ppgmove(x,2.0*I/scale);\n      }else {\n ppgdraw(x,2.0*I/scale);\n      }\n    }\n  }\n}\nvoid Plot2dfs(twodfs_def twodfs_allinfo, twodfs_def twodfs2_allinfo, datafile_definition AverageProfile, int twodfsonly, int Number, char *title, plotoptions_def plotoptions, verbose_definition verbose)\n{\n  float offset;\n  offset = 0+0.03*(plotoptions.labelscale-1.0)*((float)Number+1.0);\n  if(twodfsonly == 0) {\n    ppgsvp(0.2, 0.2+0.11*plotoptions.scaleFig_x, 0.95-0.48*plotoptions.scaleFig_y-0.22*Number*plotoptions.scaleFig_y-offset*plotoptions.scaleFig_y, 0.95-0.33*plotoptions.scaleFig_y-0.22*Number*plotoptions.scaleFig_y-offset*plotoptions.scaleFig_y);\n  }else {\n    ppgsvp(0.2, 0.2+0.11*plotoptions.scaleFig_x, 0.95-0.33*plotoptions.scaleFig_y-0.22*Number*plotoptions.scaleFig_y-offset*plotoptions.scaleFig_y, 0.95-0.18*plotoptions.scaleFig_y-0.22*Number*plotoptions.scaleFig_y-offset*plotoptions.scaleFig_y);\n  }\n  if(twodfsonly && title != NULL) {\n    ppgsch(0.55*plotoptions.labelscale*plotoptions.titlescale);\n    ppgscf(2);\n    ppgslw(2);\n    ppgmtxt(\"t\",1,0.5,0.5,title);\n    ppgslw(1);\n    ppgscf(1);\n    ppgsch(0.38*plotoptions.labelscale);\n  }\n  ppgswin(twodfs_allinfo.f2_min,twodfs_allinfo.f2_max,twodfs_allinfo.f3_min,twodfs_allinfo.f3_max);\n  if(plotoptions.plot_ylabel != 0) {\n    ppgsch(0.3*plotoptions.labelscale);\n    if(plotoptions.noside) {\n      if(plotoptions.plot_ylabel == 1)\n ppgmtxt(\"l\",2.8,0.5,0.5,\"Fluctuation frequency (cpp)\");\n      else if(plotoptions.plot_ylabel == 2)\n ppgmtxt(\"l\",2.8,0.5,0.5,\"Fluctuation frequency (P\\\\d0\\\\u/P\\\\d3\\\\u)\");\n      else if(plotoptions.plot_ylabel == 3)\n ppgmtxt(\"l\",2.8,0.5,0.5,\"Fluctuation frequency (P/P\\\\d3\\\\u)\");\n    }else {\n      float offset;\n      offset = 10 - (plotoptions.labelscale-1.0)*(7-2.8);\n      offset += 7*(plotoptions.scaleFig_x-1.0);\n      if(plotoptions.plot_ylabel == 1)\n ppgmtxt(\"l\",offset,0.5,0.5,\"Fluctuation frequency (cpp)\");\n      else if(plotoptions.plot_ylabel == 2)\n ppgmtxt(\"l\",offset,0.5,0.5,\"Fluctuation frequency (P\\\\d0\\\\u/P\\\\d3\\\\u)\");\n      else if(plotoptions.plot_ylabel == 3)\n ppgmtxt(\"l\",offset,0.5,0.5,\"Fluctuation frequency (P/P\\\\d3\\\\u)\");\n    }\n    ppgsch(0.38*plotoptions.labelscale);\n  }\n  pgplot_options_definition pgplot_options;\n  pgplot_clear_options(&pgplot_options);\n  pgplot_options.box.box_labelsize = 0.3*plotoptions.labelscale;\n  pgplot_options.viewport.noclear = 1;\n  pgplot_options.viewport.dontopen = 1;\n  pgplot_options.viewport.dontclose = 1;\n  if(!plotoptions.nomain) {\n    datafile_definition *curtwodfs;\n    float cur_f2_min, cur_f2_max;\n    float cur_f3_min, cur_f3_max;\n    float cur_oversaturize;\n    if(Number == 0) {\n      curtwodfs = &(twodfs_allinfo.datafile);\n      cur_f2_min = twodfs_allinfo.f2_min;\n      cur_f2_max = twodfs_allinfo.f2_max;\n      cur_f3_min = twodfs_allinfo.f3_min;\n      cur_f3_max = twodfs_allinfo.f3_max;\n      cur_oversaturize = twodfs_allinfo.oversaturize;\n    }else {\n      curtwodfs = &(twodfs2_allinfo.datafile);\n      cur_f2_min = twodfs2_allinfo.f2_min;\n      cur_f2_max = twodfs2_allinfo.f2_max;\n      cur_f3_min = twodfs2_allinfo.f3_min;\n      cur_f3_max = twodfs2_allinfo.f3_max;\n      cur_oversaturize = twodfs2_allinfo.oversaturize;\n    }\n    float cpp_min;\n    float cpp_max;\n    if(curtwodfs->xrangeset) {\n      cpp_min = curtwodfs->xrange[0];\n      cpp_max = curtwodfs->xrange[1];\n    }else {\n      cpp_min = -AverageProfile.NrBins/2.0-0.5*AverageProfile.NrBins/(float)curtwodfs->NrBins;\n      cpp_max = +AverageProfile.NrBins/2.0-0.5*AverageProfile.NrBins/(float)curtwodfs->NrBins;\n    }\n    if(plotoptions.doFlip) {\n      cpp_min *= -1.0;\n      cpp_max *= -1.0;\n    }\n    pgplotMap(&pgplot_options, curtwodfs->data, curtwodfs->NrBins, curtwodfs->NrSubints, cpp_min, cpp_max, cur_f2_min, cur_f2_max, 0, 0.5, cur_f3_min, cur_f3_max, PPGPLOT_GRAYSCALE, 0, 0, 0, NULL, 0, 0, cur_oversaturize, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, plotoptions.showwedge, plotoptions.showwedge_max, 0, 0, verbose);\n    ppgsch(0.38*plotoptions.labelscale);\n    if(plotoptions.noside) {\n      if(plotoptions.inside) {\n if(plotoptions.noylabels)\n   ppgbox(\"cst\",0.0,0,\"bcst\",0.0,0);\n else\n   ppgbox(\"cst\",0.0,0,\"bcnst\",0.0,0);\n      }else {\n if(plotoptions.noylabels)\n   ppgbox(\"csti\",0.0,0,\"bcsti\",0.0,0);\n else\n   ppgbox(\"csti\",0.0,0,\"bcnsti\",0.0,0);\n      }\n    }else {\n      if(plotoptions.inside) {\n ppgbox(\"cst\",0.0,0,\"cst\",0.0,0);\n      }else {\n ppgbox(\"csti\",0.0,0,\"csti\",0.0,0);\n      }\n    }\n    ppgbox(\"c\",0.0,0,\"c\",0.0,0);\n    if(twodfs_allinfo.SelectP3Integrate != 0) {\n      ppgsls(2);\n      ppgslw(1);\n      if(Number == 0) {\n ppgmove(twodfs_allinfo.f2_min, twodfs_allinfo.P3IntegrateLow);\n ppgdraw(twodfs_allinfo.f2_max, twodfs_allinfo.P3IntegrateLow);\n      }else {\n ppgmove(twodfs_allinfo.f2_min, twodfs2_allinfo.P3IntegrateLow);\n ppgdraw(twodfs_allinfo.f2_max, twodfs2_allinfo.P3IntegrateLow);\n      }\n      ppgsls(2);\n      if(Number == 0) {\n ppgmove(twodfs_allinfo.f2_min, twodfs_allinfo.P3IntegrateHigh);\n ppgdraw(twodfs_allinfo.f2_max, twodfs_allinfo.P3IntegrateHigh);\n      }else {\n ppgmove(twodfs_allinfo.f2_min, twodfs2_allinfo.P3IntegrateHigh);\n ppgdraw(twodfs_allinfo.f2_max, twodfs2_allinfo.P3IntegrateHigh);\n      }\n      ppgsls(1);\n      ppgslw(1);\n    }\n  }\n  if(Number == 0) {\n    IntegrateSubsetVertical(twodfs_allinfo, twodfsonly, Number, plotoptions.normaliseSide, plotoptions.nointegrateNumbers, plotoptions);\n  }else {\n    IntegrateSubsetVertical(twodfs2_allinfo, twodfsonly, Number, plotoptions.normaliseSide, plotoptions.nointegrateNumbers, plotoptions);\n  }\n  if(plotoptions.plot_xlabel == 1) {\n    ppgsch(0.3*plotoptions.labelscale);\n    ppgmtxt(\"b\",3.0,0.5,0.5,\"Fluctuation frequency (cpp)\");\n    ppgsch(0.38*plotoptions.labelscale);\n  }else if(plotoptions.plot_xlabel == 2) {\n    ppgsch(0.3*plotoptions.labelscale);\n    ppgmtxt(\"b\",3.0,0.5,0.5,\"Fluctuation frequency (P\\\\d0\\\\u/P\\\\d2\\\\u)\");\n    ppgsch(0.38*plotoptions.labelscale);\n  }else if(plotoptions.plot_xlabel == 3) {\n    ppgsch(0.3*plotoptions.labelscale);\n    ppgmtxt(\"b\",3.0,0.5,0.5,\"Fluctuation frequency (P/P\\\\d2\\\\u)\");\n    ppgsch(0.38*plotoptions.labelscale);\n  }\n  if(!(plotoptions.noside)) {\n    IntegrateSubsetHorizontal(twodfs_allinfo.datafile, twodfs_allinfo, twodfs2_allinfo, twodfsonly, Number, plotoptions.normaliseSide, plotoptions);\n  }\n}\nint loadLRFS(datafile_definition *lrfs, int extprefix, int longsnap, int argc, char **argv, plotoptions_def *plotoptions, verbose_definition verbose)\n{\n  char filename[MaxFilenameLength], txt[MaxFilenameLength];\n  datafile_definition clone;\n  if(extprefix == 0) {\n    sprintf(txt, \"lrfs\");\n  }\n  if(change_filename_extension(argv[argc-1], filename, txt, MaxFilenameLength, verbose) == 0) {\n    return 0;\n  }\n  if(verbose.verbose) {\n    printf(\"Reading %s\\n\", filename);\n  }\n  closePSRData(lrfs, 0, verbose);\n  if(!openPSRData(lrfs, filename, 0, 0, 1, 0, verbose)) {\n    return 0;\n  }\n  if(PSRDataHeader_parse_commandline(lrfs, argc, argv, verbose) == 0) {\n    return 0;\n  }\n  double period;\n  int ret;\n  ret = get_period(*lrfs, 0, &period, verbose);\n  if(ret == 2) {\n    printerror(verbose.debug, \"ERROR pspecFig (%s): Cannot obtain period\", lrfs->filename);\n    return 0;\n  }\n  if(period < 0.001) {\n    printerror(verbose.debug, \"ERROR pspecFig (%s): The period does not appear to be set in the header. Consider using the -header option.\", lrfs->filename);\n    return 0;\n  }\n  if(get_tsamp(*lrfs, 0, verbose) < 0.0000001) {\n    printerror(verbose.debug, \"ERROR pspecFig (%s): The sampling time does not appear to be set in the header. Consider using the -header option.\", lrfs->filename);\n    return 0;\n  }\n  if(verbose.verbose) {\n    printf(\"%ldx%ld points read from lrfs\\n\", lrfs->NrBins, lrfs->NrSubints);\n  }\n  if(lrfs->NrPols > 1) {\n    if(preprocess_polselect(*lrfs, &clone, 0, verbose) == 0) {\n      printerror(verbose.debug, \"ERROR pspecFig (%s): Error selecting polarization channel 0.\", lrfs->filename);\n      return 0;\n    }\n    swap_orig_clone(lrfs, &clone, verbose);\n  }\n  long i;\n  double max;\n  if(plotoptions->normalise_spectra) {\n    for(i = 0; i < lrfs->NrSubints * lrfs->NrBins; i++) {\n      if(i == 0 || fabs(lrfs->data[i]) > max) {\n max = fabs(lrfs->data[i]);\n      }\n    }\n    for(i = 0; i < lrfs->NrSubints * lrfs->NrBins; i++) {\n      lrfs->data[i] /= 0.999*max;\n    }\n  }\n  return 1;\n}\nint loadHeaderPulseStack(datafile_definition *AverageProfile, datafile_definition lrfs, double *period, int type_of_plots, int argc, char **argv, verbose_definition verbose)\n{\n  if(verbose.verbose)\n    printf(\"Reading %s\\n\", argv[argc-1]);\n  closePSRData(AverageProfile, 0, verbose);\n  if(!openPSRData(AverageProfile, argv[argc-1], 0, 0, 0, 0, verbose))\n    return 0;\n  if(!readHeaderPSRData(AverageProfile, 0, 0, verbose))\n    return 0;\n  if(PSRDataHeader_parse_commandline(AverageProfile, argc, argv, verbose) == 0)\n    return 0;\n  if(type_of_plots == 0) {\n    if(AverageProfile->NrBins != lrfs.NrBins) {\n      printwarning(verbose.debug, \"WARNING: Nr of bins in pulse stack and LRFS do not match. It looks like data is rebinned? Check the units.\");\n    }\n  }\n  int ret_prd;\n  ret_prd = get_period(*AverageProfile, 0, period, verbose);\n  if(ret_prd == 2) {\n    printerror(verbose.debug, \"ERROR pspecFig (%s): Cannot obtain period\", AverageProfile->filename);\n    return 0;\n  }\n  if(*period < 0.001) {\n    printerror(verbose.debug, \"ERROR pspecFig (%s): The period does not appear to be set in the header. Consider using the -header option.\", AverageProfile->filename);\n    return 0;\n  }\n  if(get_tsamp(*AverageProfile, 0, verbose) < 0.0000001) {\n    printerror(verbose.debug, \"ERROR pspecFig (%s): The sampling time does not appear to be set in the header. Consider using the -header option.\", AverageProfile->filename);\n    return 0;\n  }\n  closePSRData(AverageProfile, 1, verbose);\n  AverageProfile->format = MEMORY_format;\n  AverageProfile->NrSubints = 1;\n  AverageProfile->NrFreqChan = 1;\n  AverageProfile->NrPols = 1;\n  AverageProfile->data = malloc(AverageProfile->NrBins*sizeof(float));\n  if(AverageProfile->data == NULL) {\n    printerror(verbose.debug, \"ERROR pspecFig (%s): Memory allocation error\", AverageProfile->filename);\n    return 0;\n  }\n  return 1;\n}\nint load2dfs(twodfs_def *twodfs_allinfo, datafile_definition AverageProfile, int file_number, int extprefix, int altname, int argc, char **argv, plotoptions_def plotoptions, verbose_definition verbose)\n{\n  char filename[MaxFilenameLength], txt[MaxFilenameLength];\n  datafile_definition clone;\n  if(altname) {\n    strcpy(filename, argv[altname]);\n  }else {\n    if(extprefix == 0) {\n      sprintf(txt, \"%d.2dfs\", file_number);\n    }\n    if(change_filename_extension(argv[argc-1], filename, txt, MaxFilenameLength, verbose) == 0) {\n      return 0;\n    }\n  }\n  if(verbose.verbose) {\n    printf(\"Reading %s\\n\", filename);\n  }\n  closePSRData(&(twodfs_allinfo->datafile), 0, verbose);\n  if(!openPSRData(&(twodfs_allinfo->datafile), filename, 0, 0, 1, 0, verbose)) {\n    return 0;\n  }\n  if(PSRDataHeader_parse_commandline(&(twodfs_allinfo->datafile), argc, argv, verbose) == 0) {\n    return 0;\n  }\n  if(verbose.verbose) {\n    printf(\"%ldx%ld points read from 2dfs\\n\", twodfs_allinfo->datafile.NrBins, twodfs_allinfo->datafile.NrSubints);\n  }\n  if(twodfs_allinfo->datafile.NrPols > 1) {\n    if(preprocess_polselect(twodfs_allinfo->datafile, &clone, 0, verbose) == 0) {\n      printerror(verbose.debug, \"ERROR pspecFig: Error selecting polarization channel 0.\");\n      return 0;\n    }\n    swap_orig_clone(&(twodfs_allinfo->datafile), &clone, verbose);\n  }\n  long i;\n  double max;\n  if(plotoptions.normalise_spectra) {\n    for(i = 0; i < twodfs_allinfo->datafile.NrSubints * twodfs_allinfo->datafile.NrBins; i++) {\n      if(i == 0 || fabs(twodfs_allinfo->datafile.data[i]) > max) {\n max = fabs(twodfs_allinfo->datafile.data[i]);\n      }\n    }\n    for(i = 0; i < twodfs_allinfo->datafile.NrSubints * twodfs_allinfo->datafile.NrBins; i++) {\n      twodfs_allinfo->datafile.data[i] /= 0.999*max;\n    }\n  }\n  if(twodfs_allinfo->f2_min == 0.0 && twodfs_allinfo->f2_min == 0.0) {\n    if(twodfs_allinfo->datafile.xrangeset) {\n      twodfs_allinfo->f2_min = twodfs_allinfo->datafile.xrange[0];\n      twodfs_allinfo->f2_max = twodfs_allinfo->datafile.xrange[1];\n    }else {\n      twodfs_allinfo->f2_min = -AverageProfile.NrBins/2.0;\n      twodfs_allinfo->f2_max = -AverageProfile.NrBins/2.0 + AverageProfile.NrBins*(twodfs_allinfo->datafile.NrBins-1.0)/(float)twodfs_allinfo->datafile.NrBins;\n    }\n    float f2_resolution;\n    f2_resolution = (twodfs_allinfo->f2_max - twodfs_allinfo->f2_min)/(float)(twodfs_allinfo->datafile.NrBins-1);\n    twodfs_allinfo->f2_min -= 0.5*f2_resolution;\n    twodfs_allinfo->f2_max += 0.5*f2_resolution;\n    if(plotoptions.doFlip) {\n      float swap;\n      swap = twodfs_allinfo->f2_min;\n      twodfs_allinfo->f2_min = -twodfs_allinfo->f2_max;\n      twodfs_allinfo->f2_max = -swap;\n    }\n  }\n  twodfs_allinfo->f3_min = 0;\n  twodfs_allinfo->f3_max = 0.5;\n  if(twodfs_allinfo->SelectP3Integrate) {\n    if(twodfs_allinfo->P3IntegrateHigh > twodfs_allinfo->f3_max) {\n      twodfs_allinfo->P3IntegrateHigh = twodfs_allinfo->f3_max;\n    }\n  }\n  if(twodfs_allinfo->f3_min < 0) {\n    twodfs_allinfo->f3_min = 0;\n  }\n  return 1;\n}\n", "meta": {"hexsha": "29647052f566fb812a8a3ebaceb1f43850d33aa8", "size": 79665, "ext": "c", "lang": "C", "max_stars_repo_path": "src/prog/pspecFig.c", "max_stars_repo_name": "weltevrede/psrsalsa", "max_stars_repo_head_hexsha": "4c5b1b32513174ec1f6929905e67c8b9ca44e008", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-09-05T23:22:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-11T14:12:18.000Z", "max_issues_repo_path": "src/prog/pspecFig.c", "max_issues_repo_name": "weltevrede/psrsalsa", "max_issues_repo_head_hexsha": "4c5b1b32513174ec1f6929905e67c8b9ca44e008", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-04-26T13:35:30.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-20T08:49:57.000Z", "max_forks_repo_path": "src/prog/pspecFig.c", "max_forks_repo_name": "weltevrede/psrsalsa", "max_forks_repo_head_hexsha": "4c5b1b32513174ec1f6929905e67c8b9ca44e008", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-04-09T09:04:46.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-16T15:24:07.000Z", "avg_line_length": 41.3844155844, "max_line_length": 755, "alphanum_fraction": 0.6692399423, "num_tokens": 25425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.02262920254601444, "lm_q1q2_score": 0.009474777167200082}}
{"text": "#include <stdio.h>\n#include <gsl/gsl_block.h>\n\nint\nmain (void)\n{\n  gsl_block * b = gsl_block_alloc (100);\n  \n  printf (\"length of block = %zu\\n\", b->size);\n  printf (\"block data address = %p\\n\", b->data);\n\n  gsl_block_free (b);\n  return 0;\n}\n", "meta": {"hexsha": "ca6e80e3d733baf32b3090b7b78f1d66270204da", "size": 242, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/doc/examples/block.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/block.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/block.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 16.1333333333, "max_line_length": 48, "alphanum_fraction": 0.6198347107, "num_tokens": 77, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18242550602671442, "lm_q2_score": 0.0518454661004018, "lm_q1q2_score": 0.009457935388556667}}
{"text": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n#pragma once\n\n#include \"BaseFeatureMatcher.h\"\n#include \"OnlineBow.h\"\n\n#include <gsl\\gsl>\n#include <unordered_map>\n\nnamespace mage\n{\n    class Keyframe;\n\n    class OnlineBowFeatureMatcher : public BaseFeatureMatcher\n    {\n    public:\n        OnlineBowFeatureMatcher(const OnlineBow& onlineBow, const Id<Keyframe>& id, gsl::span<const ORBDescriptor> features);\n\n        virtual size_t QueryFeatures(const ORBDescriptor& descriptor, std::vector<ptrdiff_t>& matches) const override;\n\n        virtual const Id<Keyframe>& GetId() const override;\n\n    private:\n        // a Map of NodeId <==> the indexes of the features which are assigned to the Node.\n        std::unordered_map<ptrdiff_t, std::vector<ptrdiff_t>> m_featureMap;\n        const OnlineBow& m_onlineBow;\n        const Id<Keyframe> m_id;\n    };\n}", "meta": {"hexsha": "d6a53ab9a6cc761cddabe95557a3938c9088d405", "size": 877, "ext": "h", "lang": "C", "max_stars_repo_path": "Core/MAGESLAM/Source/BoW/OnlineBowFeatureMatcher.h", "max_stars_repo_name": "syntheticmagus/mageslam", "max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z", "max_issues_repo_path": "Core/MAGESLAM/Source/BoW/OnlineBowFeatureMatcher.h", "max_issues_repo_name": "syntheticmagus/mageslam", "max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z", "max_forks_repo_path": "Core/MAGESLAM/Source/BoW/OnlineBowFeatureMatcher.h", "max_forks_repo_name": "syntheticmagus/mageslam", "max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z", "avg_line_length": 28.2903225806, "max_line_length": 125, "alphanum_fraction": 0.7069555302, "num_tokens": 202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33111973962899144, "lm_q2_score": 0.02843603036892814, "lm_q1q2_score": 0.009415730971841578}}
{"text": "\ufeff#pragma once\n#include <cassert>\n#include <gsl/span>\n\n#include <iostream>\n\n#include <optixu/optixpp_namespace.h>\n\nnamespace DeepestScatter\n{\n    template<typename T>\n    class BufferBind\n    {\n    public:\n        explicit BufferBind(optix::Buffer buffer, unsigned int level = 0);\n        \n        ~BufferBind();\n\n        gsl::span<T>& getData();\n\n        const T& operator [](size_t pos) const;\n        T& operator [](size_t pos);\n\n    private:\n        optix::Buffer buffer;\n        unsigned int level;\n\n        gsl::span<T> optixOwned;\n    };\n\n    \n    template<typename T>\n    BufferBind<T>::BufferBind(optix::Buffer buffer, unsigned int level):\n        buffer(buffer),\n        level(level)\n    {\n        assert(sizeof(T) == buffer->getElementSize());\n        auto rawArray = static_cast<T*>(buffer->map(level));\n\n        RTsize totalSize = 1;\n        RTsize sizes[3];\n        buffer->getMipLevelSize(level, sizes[0], sizes[1], sizes[2]);\n        for (unsigned int i = 0; i < buffer->getDimensionality(); i++)\n        {\n            totalSize *= sizes[i];\n        }\n\n        optixOwned = gsl::make_span(rawArray, totalSize);\n    }\n\n    template <typename T>\n    BufferBind<T>::~BufferBind()\n    {\n        buffer->unmap(level);\n    }\n\n\n    template <typename T>\n    gsl::span<T>& BufferBind<T>::getData()\n    {\n        return optixOwned;\n    }\n\n    template <typename T>\n    inline const T& BufferBind<T>::operator[](size_t pos) const\n    {\n        return optixOwned[pos];\n    }\n\n    template <typename T>\n    inline T& BufferBind<T>::operator[](size_t pos)\n    {\n        return optixOwned[pos];\n    }\n}\n", "meta": {"hexsha": "0885fe821c7aabc032cfff29f4cbb698bb23bcd9", "size": 1604, "ext": "h", "lang": "C", "max_stars_repo_path": "DeepestScatter_DataGen/DeepestScatter_DataGen/src/Util/BufferBind.h", "max_stars_repo_name": "marsermd/DeepestScatter", "max_stars_repo_head_hexsha": "eeb490b5e6afd7f05049c8aca90a5c2e6f253726", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2018-09-02T05:39:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T13:15:14.000Z", "max_issues_repo_path": "DeepestScatter_DataGen/DeepestScatter_DataGen/src/Util/BufferBind.h", "max_issues_repo_name": "marsermd/DeepestScatter", "max_issues_repo_head_hexsha": "eeb490b5e6afd7f05049c8aca90a5c2e6f253726", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18.0, "max_issues_repo_issues_event_min_datetime": "2020-01-28T22:39:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T23:33:13.000Z", "max_forks_repo_path": "DeepestScatter_DataGen/DeepestScatter_DataGen/src/Util/BufferBind.h", "max_forks_repo_name": "marsermd/DeepestScatter", "max_forks_repo_head_hexsha": "eeb490b5e6afd7f05049c8aca90a5c2e6f253726", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-12-07T01:20:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-17T02:10:36.000Z", "avg_line_length": 21.1052631579, "max_line_length": 74, "alphanum_fraction": 0.5748129676, "num_tokens": 394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2068940488158881, "lm_q2_score": 0.045352577167234585, "lm_q1q2_score": 0.009383178314364164}}
{"text": "/*\nMPCOTool:\nThe Multi-Purposes Calibration and Optimization Tool. A software to perform\ncalibrations or optimizations of empirical parameters.\n\nAUTHORS: Javier Burguete and Borja Latorre.\n\nCopyright 2012-2019, AUTHORS.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n    1. Redistributions of source code must retain the above copyright notice,\n        this list of conditions and the following disclaimer.\n\n    2. Redistributions in binary form must reproduce the above copyright notice,\n        this list of conditions and the following disclaimer in the\n        documentation and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY AUTHORS ``AS IS'' AND ANY EXPRESS OR IMPLIED\nWARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT\nSHALL AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\nBUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING\nIN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY\nOF SUCH DAMAGE.\n*/\n\n/**\n * \\file main.c\n * \\brief Main source file.\n * \\authors Javier Burguete and Borja Latorre.\n * \\copyright Copyright 2012-2019, all rights reserved.\n */\n#define _GNU_SOURCE\n#include \"config.h\"\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <locale.h>\n#include <gsl/gsl_rng.h>\n#include <libxml/parser.h>\n#include <libintl.h>\n#include <glib.h>\n#include <json-glib/json-glib.h>\n#ifdef G_OS_WIN32\n#include <windows.h>\n#endif\n#if HAVE_MPI\n#include <mpi.h>\n#endif\n#if HAVE_GTK\n#include <gio/gio.h>\n#include <gtk/gtk.h>\n#endif\n#include \"genetic/genetic.h\"\n#include \"utils.h\"\n#include \"experiment.h\"\n#include \"variable.h\"\n#include \"input.h\"\n#include \"optimize.h\"\n#if HAVE_GTK\n#include \"interface.h\"\n#endif\n#include \"mpcotool.h\"\n\nint\nmain (int argn, char **argc)\n{\n#if HAVE_GTK\n  show_pending = process_pending;\n#endif\n  return mpcotool (argn, argc);\n}\n", "meta": {"hexsha": "4ea87389464f1fa053bb3288af6f2150d2b918e7", "size": 2336, "ext": "c", "lang": "C", "max_stars_repo_path": "4.0.5/main.c", "max_stars_repo_name": "jburguete/mpcotool", "max_stars_repo_head_hexsha": "e8a6a9713d4ef73b0aa8a0a552d91117ebd22610", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-17T14:59:29.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-17T14:59:29.000Z", "max_issues_repo_path": "4.0.5/main.c", "max_issues_repo_name": "jburguete/mpcotool", "max_issues_repo_head_hexsha": "e8a6a9713d4ef73b0aa8a0a552d91117ebd22610", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-03-08T17:02:14.000Z", "max_issues_repo_issues_event_max_datetime": "2016-03-08T17:02:14.000Z", "max_forks_repo_path": "4.0.5/main.c", "max_forks_repo_name": "jburguete/mpcotool", "max_forks_repo_head_hexsha": "e8a6a9713d4ef73b0aa8a0a552d91117ebd22610", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5696202532, "max_line_length": 80, "alphanum_fraction": 0.7636986301, "num_tokens": 547, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2877678157610531, "lm_q2_score": 0.03258974641032064, "lm_q1q2_score": 0.009378280140704591}}
{"text": "/*\nCopyright 2010-2011, D. E. Shaw Research.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n* Redistributions of source code must retain the above copyright\n  notice, this list of conditions, and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright\n  notice, this list of conditions, and the following disclaimer in the\n  documentation and/or other materials provided with the distribution.\n\n* Neither the name of D. E. Shaw Research nor the names of its\n  contributors may be used to endorse or promote products derived from\n  this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n#ifndef __r123_compat_gslrng_dot_h__\n#define __r123_compat_gslrng_dot_h__\n\n#include <gsl/gsl_rng.h>\n#include <string.h>\n\n/**\n   The macro:  GSL_CBRNG(NAME, CBRNGNAME)\n   declares the necessary structs and  constants that define a\n   gsl_rng_NAME type based on the counter-based RNG CBRNGNAME.  For example:\n\n   Usage:\n\n   @code\n   #include <Random123/threefry.h>\n   #include <Random123/conventional/gsl_cbrng.h>  // this file\n   GSL_CBRNG(cbrng, threefry4x32); // creates gsl_rng_cbrng\n\n   int main(int argc, char **argv){\n       gsl_rng *r = gsl_rng_alloc(gsl_rng_cbrng);\n       ... use r as you would use any other gsl_rng ...   \n    }\n    @endcode\n\n    It requires that NAME be the name of a CBRNG that follows the\n    naming and stylistic conventions of the Random123 library.\n\n    Note that wrapping a \\ref CBRNG \"counter-based PRNG\" with a traditional API in\n    this way obscures much of the power of the CBRNG API.\n    Nevertheless, it may be of value to applications that are already\n    coded to work with GSL random number generators, and that wish\n    to use the RNGs in the Random123 library.\n\n */ \n\n#define GSL_CBRNG(NAME, CBRNGNAME)                                      \\\nconst gsl_rng_type *gsl_rng_##NAME;                                     \\\n                                                                        \\\ntypedef struct{                                                         \\\n    CBRNGNAME##_ctr_t ctr;                                                   \\\n    CBRNGNAME##_ctr_t r;                                                     \\\n    CBRNGNAME##_key_t key;                                                   \\\n    int elem;                                                           \\\n} NAME##_state;                                                         \\\n                                                                        \\\nstatic unsigned long int NAME##_get(void *vstate){                      \\\n    NAME##_state *st = (NAME##_state *)vstate;                          \\\n    const int N=sizeof(st->ctr.v)/sizeof(st->ctr.v[0]);                 \\\n    if( st->elem == 0 ){                                                \\\n        ++st->ctr.v[0];                                                 \\\n        if( N>1 && st->ctr.v[0] == 0 ) ++st->ctr.v[1];                  \\\n        if( N>2 && st->ctr.v[1] == 0 ) ++st->ctr.v[2];                  \\\n        if( N>3 && st->ctr.v[2] == 0 ) ++st->ctr.v[3];                  \\\n        st->r = CBRNGNAME(st->ctr, st->key);                                 \\\n        st->elem = N;                                                   \\\n    }                                                                   \\\n    return st->r.v[--st->elem];                                         \\\n}                                                                       \\\n                                                                        \\\nstatic double NAME##_get_double (void * vstate);                        \\\n                                                                        \\\nstatic void NAME##_set(void *vstate, unsigned long int s){              \\\n    NAME##_state *st = (NAME##_state *)vstate;                          \\\n    st->elem = 0;                                                       \\\n    /* Assume that key and ctr have an array member, v,                 \\\n       as if they are r123arrayNxW.  If not, this will fail             \\\n       to compile.  In particular, this macro fails to compile          \\\n       when the underlying CBRNG requires use of keyinit */             \\\n    memset(&st->ctr.v[0], 0, sizeof(st->ctr.v));                        \\\n    memset(&st->key.v[0], 0, sizeof(st->key.v));                        \\\n    /* GSL 1.15 documentation says this about gsl_rng_set:              \\\n         Note that the most generators only accept 32-bit seeds, with higher \\\n         values being reduced modulo 2^32.  For generators with smaller \\\n         ranges the maximum seed value will typically be lower.         \\\n     so we won't jump through any hoops here to deal with               \\\n     high bits if sizeof(unsigned long) > sizeof(uint32_t). */          \\\n    st->key.v[0] = s;                                                   \\\n}                                                                       \\\n                                                                        \\\nstatic const gsl_rng_type NAME##_type = {                               \\\n    #NAME,                                                              \\\n    ~0UL>>((R123_W(CBRNGNAME##_ctr_t)>=8*sizeof(unsigned long))? 0 : (8*sizeof(unsigned long) - R123_W(CBRNGNAME##_ctr_t))),     \\\n    0,                                                                  \\\n    sizeof(NAME##_state),                                               \\\n    &NAME##_set,                                                        \\\n    &NAME##_get,                                                        \\\n    &NAME##_get_double                                                  \\\n};                                                                      \\\n                                                                        \\\nstatic double                                                           \\\nNAME##_get_double (void * vstate)                                       \\\n{                                                                       \\\n    return NAME##_get (vstate)/(double)NAME##_type.max;                 \\\n}                                                                       \\\n                                                                        \\\nconst gsl_rng_type *gsl_rng_##NAME = &NAME##_type\n\n#endif\n\n", "meta": {"hexsha": "82bc90475ff632ab6626dc607c25944a64befcce", "size": 7199, "ext": "h", "lang": "C", "max_stars_repo_path": "benchmark/askit_release/rkdtsrc/external/Random123/conventional/gsl_cbrng.h", "max_stars_repo_name": "maumueller/rehashing", "max_stars_repo_head_hexsha": "38fe7a1a71fcc5ecd10384fac01bfeb134ea5fad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2019-05-14T20:08:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-22T20:48:29.000Z", "max_issues_repo_path": "benchmark/askit_release/rkdtsrc/external/Random123/conventional/gsl_cbrng.h", "max_issues_repo_name": "maumueller/rehashing", "max_issues_repo_head_hexsha": "38fe7a1a71fcc5ecd10384fac01bfeb134ea5fad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-10-06T09:47:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-09T04:27:39.000Z", "max_forks_repo_path": "benchmark/askit_release/rkdtsrc/external/Random123/conventional/gsl_cbrng.h", "max_forks_repo_name": "maumueller/rehashing", "max_forks_repo_head_hexsha": "38fe7a1a71fcc5ecd10384fac01bfeb134ea5fad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-11T22:29:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-08T20:02:46.000Z", "avg_line_length": 54.9541984733, "max_line_length": 130, "alphanum_fraction": 0.4545075705, "num_tokens": 1345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2509127868852725, "lm_q2_score": 0.03732689055684297, "lm_q1q2_score": 0.009365794135379031}}
{"text": "/*\t$Id$ */\n/*\n * Copyright (c) 2014, 2015 Kristaps Dzonsons <kristaps@kcons.eu>\n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n */\n#include <assert.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <string.h>\n\n#ifdef MAC_INTEGRATION\n#include <gtkosxapplication.h>\n#endif\n#include <gtk/gtk.h>\n#include <gdk/gdk.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_multifit.h>\n#include <gsl/gsl_histogram.h>\n#include <kplot.h>\n\n#include \"extern.h\"\n\n/*\n * Brute-force scan all possible pi values (and Poisson means) by\n * scanning through the strategy space.\n */\nint\nrangefind(struct bmigrate *b)\n{\n\tsize_t\t\t mutants;\n\tdouble\t\t mstrat, istrat, v;\n\tgchar\t\t buf[22];\n\n\tg_assert(b->rangeid);\n\n\t/*\n\t * Set the number of mutants on a given island, then see what\n\t * the utility function would yield given that number of mutants\n\t * and incumbents, setting the current player to be one or the\n\t * other..\n\t */\n\tmstrat = istrat = 0.0;\n\tfor (mutants = 0; mutants <= b->range.n; mutants++) {\n\t\tmstrat = b->range.ymin + \n\t\t\t(b->range.slicey / (double)b->range.slices) * \n\t\t\t(b->range.ymax - b->range.ymin);\n\t\tistrat = b->range.xmin + \n\t\t\t(b->range.slicex / (double)b->range.slices) * \n\t\t\t(b->range.xmax - b->range.xmin);\n\t\t/*\n\t\t * Only check for a given mutant/incumbent individual's\n\t\t * strategy if the population is going to support the\n\t\t * existence of that individual.\n\t\t */\n\t\tif (mutants > 0) {\n\t\t\tv = hnode_exec\n\t\t\t\t((const struct hnode *const *) \n\t\t\t\t b->range.exp, \n\t\t\t\t istrat, mstrat * mutants + istrat * \n\t\t\t\t (b->range.n - mutants), b->range.n);\n\t\t\tif (0.0 != v && ! isnormal(v))\n\t\t\t\tbreak;\n\t\t\tif (v < b->range.pimin)\n\t\t\t\tb->range.pimin = v;\n\t\t\tif (v > b->range.pimax)\n\t\t\t\tb->range.pimax = v;\n\t\t\tb->range.piaggr += v;\n\t\t\tb->range.picount++;\n\t\t}\n\t\tif (mutants != b->range.n) {\n\t\t\tv = hnode_exec\n\t\t\t\t((const struct hnode *const *) \n\t\t\t\t b->range.exp, \n\t\t\t\t mstrat, mstrat * mutants + istrat * \n\t\t\t\t (b->range.n - mutants), b->range.n);\n\t\t\tif (0.0 != v && ! isnormal(v))\n\t\t\t\tbreak;\n\t\t\tif (v < b->range.pimin)\n\t\t\t\tb->range.pimin = v;\n\t\t\tif (v > b->range.pimax)\n\t\t\t\tb->range.pimax = v;\n\t\t\tb->range.piaggr += v;\n\t\t\tb->range.picount++;\n\t\t}\n\t}\n\n\t/*\n\t * We might have hit a discontinuous number.\n\t * If we did, then print out an error and don't continue.\n\t * If not, update to the next mutant and incumbent.\n\t */\n\tif (mutants <= b->range.n) {\n\t\tg_snprintf(buf, sizeof(buf), \n\t\t\t\"%zu mutants, mutant=%g, incumbent=%g\",\n\t\t\tmutants, mstrat, istrat);\n\t\tgtk_label_set_text(b->wins.rangeerror, buf);\n\t\tgtk_widget_show_all(GTK_WIDGET(b->wins.rangeerrorbox));\n\t\tg_debug(\"Range-finder idle event complete (error)\");\n\t\tb->rangeid = 0;\n\t} else {\n\t\tif (++b->range.slicey == b->range.slices) {\n\t\t\tb->range.slicey = 0;\n\t\t\tb->range.slicex++;\n\t\t}\n\t\tif (b->range.slicex == b->range.slices) {\n\t\t\tg_debug(\"Range-finder idle event complete\");\n\t\t\tb->rangeid = 0;\n\t\t}\n\t}\n\n\t/*\n\t * Set our current extrema.\n\t */\n\tg_snprintf(buf, sizeof(buf), \"%g\", b->range.pimin);\n\tgtk_label_set_text(b->wins.rangemin, buf);\n\tg_snprintf(buf, sizeof(buf), \"%g\", b->range.alpha * \n\t\t(1.0 + b->range.delta * b->range.pimin));\n\tgtk_label_set_text(b->wins.rangeminlambda, buf);\n\n\tg_snprintf(buf, sizeof(buf), \"%g\", b->range.pimax);\n\tgtk_label_set_text(b->wins.rangemax, buf);\n\tg_snprintf(buf, sizeof(buf), \"%g\", b->range.alpha * \n\t\t(1.0 + b->range.delta * b->range.pimax));\n\tgtk_label_set_text(b->wins.rangemaxlambda, buf);\n\n\tv = b->range.piaggr / (double)b->range.picount;\n\tg_snprintf(buf, sizeof(buf), \"%g\", v);\n\tgtk_label_set_text(b->wins.rangemean, buf);\n\tg_snprintf(buf, sizeof(buf), \"%g\", b->range.alpha * \n\t\t(1.0 + b->range.delta * v));\n\tgtk_label_set_text(b->wins.rangemeanlambda, buf);\n\n\tv = (b->range.slicex * b->range.slices + b->range.slicey) /\n\t\t(double)(b->range.slices * b->range.slices);\n\tg_snprintf(buf, sizeof(buf), \"%.1f%%\", v * 100.0);\n\tgtk_label_set_text(b->wins.rangestatus, buf);\n\n\treturn(0 != b->rangeid);\n}\n\n", "meta": {"hexsha": "216d845ef5261b6bdfb7f969287419991d72ff8e", "size": 4557, "ext": "c", "lang": "C", "max_stars_repo_path": "rangefind.c", "max_stars_repo_name": "kristapsdz/bmigrate", "max_stars_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-03-03T17:13:19.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-03T17:13:19.000Z", "max_issues_repo_path": "rangefind.c", "max_issues_repo_name": "kristapsdz/bmigrate", "max_issues_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rangefind.c", "max_forks_repo_name": "kristapsdz/bmigrate", "max_forks_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9802631579, "max_line_length": 75, "alphanum_fraction": 0.6530612245, "num_tokens": 1410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334000459302, "lm_q2_score": 0.022977370662700763, "lm_q1q2_score": 0.00935945051615351}}
{"text": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n#pragma once\n\n#include <algorithm>\n#include <boost/iostreams/categories.hpp>\n#include <gsl/gsl>\n#include <iosfwd>\n#include <vector>\n\nnamespace mira\n{\n    class memory_device\n    {\n    public:\n        using char_type = char;\n        using category = boost::iostreams::seekable_device_tag;\n\n        memory_device(std::vector<char>& memory, std::streamoff pos)\n            : m_pos{ pos }\n            , m_memory{ memory }\n        {}\n\n        std::streamoff position() const\n        {\n            return m_pos;\n        }\n\n        void reset()\n        {\n            m_pos = 0;\n        }\n\n        std::streamsize read(char* s, std::streamsize n)\n        {\n            // Read up to n characters from the underlying data source\n            // into the buffer s, returning the number of characters\n            // read; return -1 to indicate EOF\n            std::streamsize read = std::min<std::streamsize>(m_memory.size() - m_pos, n);\n            if (read == 0)\n                return -1;\n\n            std::copy(pointer(), pointer() + gsl::narrow_cast<ptrdiff_t>(read), s);\n            m_pos += read;\n\n            return read;\n        }\n\n        std::streamsize write(const char* s, std::streamsize n)\n        {\n            // Write up to n characters to the underlying\n            // data sink into the buffer s, returning the\n            // number of characters written\n            std::streamsize written = 0ll;\n            if (m_pos != gsl::narrow<std::streamoff>(m_memory.size()))\n            {\n                written = std::min<std::streamsize>(n, m_memory.size() - m_pos);\n                std::copy(s,\n                          s + gsl::narrow_cast<ptrdiff_t>(written),\n                          m_memory.begin() + gsl::narrow_cast<ptrdiff_t>(m_pos));\n                m_pos += written;\n            }\n\n            if (written < n)\n            {\n                m_memory.insert(m_memory.end(), s + written, s + n);\n                m_pos = gsl::narrow<std::streamoff>(m_memory.size());\n            }\n\n            return n;\n        }\n\n        std::streamoff seek(std::streamoff off, std::ios_base::seekdir way)\n        {\n            // Seek to position off and return the new stream\n            // position. The argument way indicates how off is\n            // interpretted:\n            //    - std::ios_base::beg indicates an offset from the\n            //      sequence beginning\n            //    - std::ios_base::cur indicates an offset from the\n            //      current character position\n            //    - std::ios_base::end indicates an offset from the\n            //      sequence end\n\n            std::streamoff next;\n            if (way == std::ios_base::beg)\n            {\n                next = off;\n            }\n            else if (way == std::ios_base::cur)\n            {\n                next = m_pos + off;\n            }\n            else if (way == std::ios_base::end)\n            {\n                next = m_memory.size() + off - 1;\n            }\n            else\n            {\n                throw std::ios_base::failure(\"bad seek direction\");\n            }\n\n            // Check for errors\n            if (next < 0 || next > gsl::narrow<std::streamoff>(m_memory.size()))\n            {\n                throw std::ios_base::failure(\"bad seek offset\");\n            }\n\n            m_pos = next;\n            return m_pos;\n        }\n\n    private:\n        char* pointer()\n        {\n            return &m_memory[gsl::narrow_cast<ptrdiff_t>(m_pos)];\n        }\n\n        std::streamoff m_pos{0};\n        std::vector<char>& m_memory;\n    };\n}\n", "meta": {"hexsha": "181ea343b60c7abe9dedb32b298a3c5a452517ac", "size": 3627, "ext": "h", "lang": "C", "max_stars_repo_path": "Dependencies/Arcana/Shared/arcana/streams/memory_device.h", "max_stars_repo_name": "syntheticmagus/mageslam", "max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z", "max_issues_repo_path": "Dependencies/Arcana/Shared/arcana/streams/memory_device.h", "max_issues_repo_name": "syntheticmagus/mageslam", "max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z", "max_forks_repo_path": "Dependencies/Arcana/Shared/arcana/streams/memory_device.h", "max_forks_repo_name": "syntheticmagus/mageslam", "max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z", "avg_line_length": 29.25, "max_line_length": 89, "alphanum_fraction": 0.488006617, "num_tokens": 808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2782567817320044, "lm_q2_score": 0.033589507464017766, "lm_q1q2_score": 0.009346508246900724}}
{"text": "#pragma once\n\n#include \"file_descriptor.h\"\n#include <filesystem>\n#include <gsl/span>\n#include <random>\n\nnamespace dogbox\n{\n    inline void create_randomness(gsl::span<std::byte> const into)\n    {\n        file_descriptor const random = open_file_for_reading(\"/dev/urandom\").value();\n        ptrdiff_t written = 0;\n        while (written < into.size())\n        {\n            size_t const reading = static_cast<size_t>(into.size() - written);\n            ssize_t const read_result = read(random.handle, into.data() + written, reading);\n            if (read_result < 0)\n            {\n                TO_DO();\n            }\n            written += reading;\n        }\n    }\n}\n", "meta": {"hexsha": "390f56cbcd58f53383594df9b05a544a1c68f043", "size": 669, "ext": "h", "lang": "C", "max_stars_repo_path": "common/create_randomness.h", "max_stars_repo_name": "TyRoXx/dogbox", "max_stars_repo_head_hexsha": "af9c7631f6f5a22a73fbd4a497a84ed75183c7d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "common/create_randomness.h", "max_issues_repo_name": "TyRoXx/dogbox", "max_issues_repo_head_hexsha": "af9c7631f6f5a22a73fbd4a497a84ed75183c7d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-09-02T20:36:02.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-02T20:36:02.000Z", "max_forks_repo_path": "common/create_randomness.h", "max_forks_repo_name": "TyRoXx/dogbox", "max_forks_repo_head_hexsha": "af9c7631f6f5a22a73fbd4a497a84ed75183c7d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-08-29T22:01:48.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-29T22:01:48.000Z", "avg_line_length": 25.7307692308, "max_line_length": 92, "alphanum_fraction": 0.5754857997, "num_tokens": 147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19930801692797973, "lm_q2_score": 0.04672496045133235, "lm_q1q2_score": 0.009312659208593331}}
{"text": "#pragma once\n\n#include \"PropertyType.h\"\n\n#include <CesiumUtility/SpanHelper.h>\n\n#include <gsl/span>\n\n#include <cassert>\n#include <cstddef>\n\nnamespace CesiumGltf {\ntemplate <typename ElementType> class MetadataArrayView {\npublic:\n  MetadataArrayView() : _valueBuffer{} {}\n\n  MetadataArrayView(const gsl::span<const std::byte>& buffer) noexcept\n      : _valueBuffer{\n            CesiumUtility::reintepretCastSpan<const ElementType>(buffer)} {}\n\n  const ElementType& operator[](int64_t index) const noexcept {\n    return _valueBuffer[index];\n  }\n\n  int64_t size() const noexcept {\n    return static_cast<int64_t>(_valueBuffer.size());\n  }\n\nprivate:\n  gsl::span<const ElementType> _valueBuffer;\n};\n\ntemplate <> class MetadataArrayView<bool> {\npublic:\n  MetadataArrayView() : _valueBuffer{}, _bitOffset{0}, _instanceCount{0} {}\n\n  MetadataArrayView(\n      const gsl::span<const std::byte>& buffer,\n      int64_t bitOffset,\n      int64_t instanceCount) noexcept\n      : _valueBuffer{buffer},\n        _bitOffset{bitOffset},\n        _instanceCount{instanceCount} {}\n\n  bool operator[](int64_t index) const noexcept {\n    index += _bitOffset;\n    const int64_t byteIndex = index / 8;\n    const int64_t bitIndex = index % 8;\n    const int bitValue =\n        static_cast<int>(_valueBuffer[byteIndex] >> bitIndex) & 1;\n    return bitValue == 1;\n  }\n\n  int64_t size() const noexcept { return _instanceCount; }\n\nprivate:\n  gsl::span<const std::byte> _valueBuffer;\n  int64_t _bitOffset;\n  int64_t _instanceCount;\n};\n\ntemplate <> class MetadataArrayView<std::string_view> {\npublic:\n  MetadataArrayView()\n      : _valueBuffer{}, _offsetBuffer{}, _offsetType{}, _size{0} {}\n\n  MetadataArrayView(\n      const gsl::span<const std::byte>& buffer,\n      const gsl::span<const std::byte>& offsetBuffer,\n      PropertyType offsetType,\n      int64_t size) noexcept\n      : _valueBuffer{buffer},\n        _offsetBuffer{offsetBuffer},\n        _offsetType{offsetType},\n        _size{size} {}\n\n  std::string_view operator[](int64_t index) const noexcept {\n    const size_t currentOffset =\n        getOffsetFromOffsetBuffer(index, _offsetBuffer, _offsetType);\n    const size_t nextOffset =\n        getOffsetFromOffsetBuffer(index + 1, _offsetBuffer, _offsetType);\n    return std::string_view(\n        reinterpret_cast<const char*>(_valueBuffer.data() + currentOffset),\n        (nextOffset - currentOffset));\n  }\n\n  int64_t size() const noexcept { return _size; }\n\nprivate:\n  static size_t getOffsetFromOffsetBuffer(\n      size_t instance,\n      const gsl::span<const std::byte>& offsetBuffer,\n      PropertyType offsetType) noexcept {\n    switch (offsetType) {\n    case PropertyType::Uint8: {\n      assert(instance < offsetBuffer.size() / sizeof(uint8_t));\n      const uint8_t offset = *reinterpret_cast<const uint8_t*>(\n          offsetBuffer.data() + instance * sizeof(uint8_t));\n      return static_cast<size_t>(offset);\n    }\n    case PropertyType::Uint16: {\n      assert(instance < offsetBuffer.size() / sizeof(uint16_t));\n      const uint16_t offset = *reinterpret_cast<const uint16_t*>(\n          offsetBuffer.data() + instance * sizeof(uint16_t));\n      return static_cast<size_t>(offset);\n    }\n    case PropertyType::Uint32: {\n      assert(instance < offsetBuffer.size() / sizeof(uint32_t));\n      const uint32_t offset = *reinterpret_cast<const uint32_t*>(\n          offsetBuffer.data() + instance * sizeof(uint32_t));\n      return static_cast<size_t>(offset);\n    }\n    case PropertyType::Uint64: {\n      assert(instance < offsetBuffer.size() / sizeof(uint64_t));\n      const uint64_t offset = *reinterpret_cast<const uint64_t*>(\n          offsetBuffer.data() + instance * sizeof(uint64_t));\n      return static_cast<size_t>(offset);\n    }\n    default:\n      assert(false && \"Offset type has unknown type\");\n      return 0;\n    }\n  }\n  gsl::span<const std::byte> _valueBuffer;\n  gsl::span<const std::byte> _offsetBuffer;\n  PropertyType _offsetType;\n  int64_t _size;\n};\n} // namespace CesiumGltf\n", "meta": {"hexsha": "153f9d1fd44c935734786ee4e1a678e725da8c79", "size": 3976, "ext": "h", "lang": "C", "max_stars_repo_path": "CesiumGltf/include/CesiumGltf/MetadataArrayView.h", "max_stars_repo_name": "JiangMuWen/cesium-native", "max_stars_repo_head_hexsha": "1d9912307336c833b74b7e9b7bc715d0a4e6c7ec", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CesiumGltf/include/CesiumGltf/MetadataArrayView.h", "max_issues_repo_name": "JiangMuWen/cesium-native", "max_issues_repo_head_hexsha": "1d9912307336c833b74b7e9b7bc715d0a4e6c7ec", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CesiumGltf/include/CesiumGltf/MetadataArrayView.h", "max_forks_repo_name": "JiangMuWen/cesium-native", "max_forks_repo_head_hexsha": "1d9912307336c833b74b7e9b7bc715d0a4e6c7ec", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5846153846, "max_line_length": 76, "alphanum_fraction": 0.6836016097, "num_tokens": 977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.28140560742914383, "lm_q2_score": 0.03308597958047282, "lm_q1q2_score": 0.009310580181231203}}
{"text": "#pragma once\n\n#include <type_traits>\n\n#include <cuda/define_specifiers.hpp>\n#include <cuda/runtime_api.hpp>\n\n#include <thrust/iterator/counting_iterator.h>\n#include <thrust/iterator/transform_iterator.h>\n#include <thrust/iterator/zip_iterator.h>\n\n#include <gsl-lite/gsl-lite.hpp>\n\n#include <cub/cub.cuh>\n\n#include <thrustshift/constant.h>\n#include <thrustshift/math.h>\n#include <thrustshift/not-a-vector.h>\n\nnamespace thrustshift {\n\nnamespace device_function {\n\nnamespace implicit_unroll {\n\n/*! \\brief Write the selected values to the result if select_op is true.\n *\n *  All threads check if their value should be selected. Afterwards, it is\n *  determined within the warp how many values were selected. Then, the first\n *  in the warp determines the range in the result, which is reserved for the\n *  warp via an atomic increment on `result_pos`. Subsequently, each thread with\n *  a selected value and `valid_write` writes the result into the reserved range.\n *  Only full warps are allowed to enter this function.\n *\n *  \\param x the value for each thread\n *  \\param selected_values result range.\n *  \\param selected_values_pos to an integer holding the ID of the first\n *      written result element by this function (usually initialized with\n *      zero). This counter is read and written atomically by the first lane of\n *      the warp. Usually this counter is shared among threads because it is\n *      incremented and read atomically.\n *  \\param lane_id ID of the thread within the warp.\n *  \\param valid_write some threads might be disabled with this flag (useful for\n *      handling range borders).\n *  \\param select_op lambda to select the values.\n */\ntemplate <typename T, typename It, typename Bool, class F>\nCUDA_FD void select_if_warp_aggregated(T x,\n                                       It selected_values,\n                                       int* selected_values_pos,\n                                       int lane_id,\n                                       Bool valid_write,\n                                       F select_op) {\n\n\tconst bool p = select_op(x) && valid_write;\n\n\tconst unsigned umask = __ballot_sync(0xffffffff, p);\n\tconst int num_selected_values = __popc(umask);\n\n\tconstexpr int source_lane = 0;\n\tint pos;\n\tif (lane_id == source_lane) {\n\t\tpos = atomicAdd(selected_values_pos, num_selected_values);\n\t}\n\tconst unsigned umask_before_me =\n\t    (~unsigned(0)) >> (sizeof(unsigned) * 8 - lane_id);\n\tconst int num_selected_values_before_me = __popc(umask & umask_before_me);\n\tpos = __shfl_sync(0xffffffff, pos, source_lane);\n\tpos += num_selected_values_before_me;\n\tif (p) {\n\t\tselected_values[pos] = x;\n\t}\n}\n\n/*! \\brief select_if as a block level primitive.\n *\n *  \\param values iterator to range of length N\n *  \\param N length of input values\n *  \\param selected_values iterator to range of length `*selected_values_pos + N`\n *  \\param selected_values_pos pointer to an integer holding the ID of the first\n *      written selected_values element by this function (usually initialized\n *      with zero). This counter must be shared among all threads, which\n *      enter this function because it is incremented and read atomically.\n *  \\param tid thread ID\n *  \\param num_threads number of threads which enter this function.\n *  \\param select_op lambda to select the values.\n */\ntemplate <typename It, typename ItResult, typename I0, typename I1, class F>\nCUDA_FD void select_if(It values,\n                       I0 N,\n                       ItResult selected_values,\n                       int* selected_values_pos,\n                       int tid,\n                       I1 num_threads,\n                       F select_op) {\n\n\tconst int num_tiles = thrustshift::ceil_divide(N, num_threads);\n\tfor (int tile_id = 0; tile_id < num_tiles - 1; ++tile_id) {\n\t\tconst int j = tile_id * num_threads + tid;\n\t\tauto x = values[j];\n\t\tselect_if_warp_aggregated(x,\n\t\t                          selected_values,\n\t\t                          selected_values_pos,\n\t\t                          tid % warp_size,\n\t\t                          std::bool_constant<true>(),\n\t\t                          select_op);\n\t}\n\tauto rest = N % num_threads;\n\tif (rest > 0) {\n\t\tconst int j = (num_tiles - 1) * num_threads + tid;\n\t\tconst bool valid_rw = tid < rest;\n\t\tusing T = typename std::remove_const<\n\t\t    typename std::iterator_traits<It>::value_type>::type;\n\t\tconst auto x = [&]() -> T {\n\t\t\tif (valid_rw) {\n\t\t\t\treturn values[j];\n\t\t\t}\n\t\t\treturn T{};\n\t\t}();\n\t\tselect_if_warp_aggregated(x,\n\t\t                          selected_values,\n\t\t                          selected_values_pos,\n\t\t                          tid % warp_size,\n\t\t                          valid_rw,\n\t\t                          select_op);\n\t}\n}\n\n} // namespace implicit_unroll\n\n} // namespace device_function\n\nnamespace async {\n\ntemplate <class ValuesRange,\n          class SelectedRange,\n          class NumSelectedPtr,\n          class SelectOp,\n          class MemoryResource>\nvoid select_if(cuda::stream_t& stream,\n               ValuesRange&& values,\n               SelectedRange&& selected,\n               NumSelectedPtr num_selected_ptr,\n               SelectOp select_op,\n               MemoryResource& delayed_memory_resource) {\n\n\tconst std::size_t N = values.size();\n\n\tgsl_Expects(selected.size() == N);\n\n\tsize_t tmp_bytes_size = 0;\n\tvoid* tmp_ptr = nullptr;\n\n\tusing T = typename std::remove_reference<ValuesRange>::type::value_type;\n\n\tauto exec = [&] {\n\t\tcuda::throw_if_error(cub::DeviceSelect::If(tmp_ptr,\n\t\t                                           tmp_bytes_size,\n\t\t                                           values.data(),\n\t\t                                           selected.data(),\n\t\t                                           num_selected_ptr,\n\t\t                                           N,\n\t\t                                           select_op,\n\t\t                                           stream.handle()));\n\t};\n\texec();\n\tauto tmp =\n\t    make_not_a_vector<uint8_t>(tmp_bytes_size, delayed_memory_resource);\n\ttmp_ptr = tmp.to_span().data();\n\texec();\n}\n\ntemplate <class ValuesIt,\n          class SelectedIt,\n          class NumSelectedPtr,\n          class SelectOp,\n          class MemoryResource>\nvoid select_if(cuda::stream_t& stream,\n               ValuesIt values,\n               SelectedIt selected,\n               NumSelectedPtr num_selected_ptr,\n               size_t N,\n               SelectOp select_op,\n               MemoryResource& delayed_memory_resource) {\n\n\tsize_t tmp_bytes_size = 0;\n\tvoid* tmp_ptr = nullptr;\n\n\tauto exec = [&] {\n\t\tcuda::throw_if_error(cub::DeviceSelect::If(tmp_ptr,\n\t\t                                           tmp_bytes_size,\n\t\t                                           values,\n\t\t                                           selected,\n\t\t                                           num_selected_ptr,\n\t\t                                           N,\n\t\t                                           select_op,\n\t\t                                           stream.handle()));\n\t};\n\texec();\n\tauto tmp =\n\t    make_not_a_vector<uint8_t>(tmp_bytes_size, delayed_memory_resource);\n\ttmp_ptr = tmp.to_span().data();\n\texec();\n}\n\n/*! \\brief Select values based on predicate with their index.\n *\n *  \\param values Range of length N with value_type `T`\n *  \\param selected Range of length N with a value type which is assignable\n *      by a thrust::tuple<T, int>.\n *  \\param select_op select predicate with signature\n *      ```\n *      select_op = [] __device__ (const thrust::tuple<T, int>& tup) { ... };\n *      ```\n */\ntemplate <class ValuesRange,\n          class SelectedRange,\n          class NumSelectedPtr,\n          class SelectOp,\n          class MemoryResource>\nvoid select_if_with_index(cuda::stream_t& stream,\n                          ValuesRange&& values,\n                          SelectedRange&& selected,\n                          NumSelectedPtr num_selected_ptr,\n                          SelectOp select_op,\n                          MemoryResource& delayed_memory_resource) {\n\n\tconst std::size_t N = values.size();\n\n\tgsl_Expects(selected.size() == N);\n\n\tsize_t tmp_bytes_size = 0;\n\tvoid* tmp_ptr = nullptr;\n\n\tusing T = typename std::remove_reference<ValuesRange>::type::value_type;\n\n\tauto cit = thrust::make_counting_iterator(0);\n\tauto it = thrust::make_zip_iterator(thrust::make_tuple(values.data(), cit));\n\n\tauto exec = [&] {\n\t\tcuda::throw_if_error(cub::DeviceSelect::If(tmp_ptr,\n\t\t                                           tmp_bytes_size,\n\t\t                                           it,\n\t\t                                           selected.data(),\n\t\t                                           num_selected_ptr,\n\t\t                                           N,\n\t\t                                           select_op,\n\t\t                                           stream.handle()));\n\t};\n\texec();\n\tauto tmp =\n\t    make_not_a_vector<uint8_t>(tmp_bytes_size, delayed_memory_resource);\n\ttmp_ptr = tmp.to_span().data();\n\texec();\n}\n\ntemplate <class ValuesRange,\n          class SelectedRange,\n          class SelectedIndexRange,\n          class NumSelectedPtr,\n          class SelectOp,\n          class MemoryResource>\nvoid select_if_with_index(cuda::stream_t& stream,\n                          ValuesRange&& values,\n                          SelectedRange&& selected,\n                          SelectedIndexRange&& selected_indices,\n                          NumSelectedPtr num_selected_ptr,\n                          SelectOp select_op,\n                          MemoryResource& delayed_memory_resource) {\n\n\tconst std::size_t N = values.size();\n\n\tgsl_Expects(selected.size() == N);\n\n\tsize_t tmp_bytes_size = 0;\n\tvoid* tmp_ptr = nullptr;\n\n\tusing T = typename std::remove_reference<ValuesRange>::type::value_type;\n\n\tauto cit = thrust::make_counting_iterator(0);\n\tauto it = thrust::make_zip_iterator(thrust::make_tuple(values.data(), cit));\n\tauto result_it = thrust::make_zip_iterator(\n\t    thrust::make_tuple(selected.data(), selected_indices.data()));\n\n\tauto exec = [&] {\n\t\tcuda::throw_if_error(cub::DeviceSelect::If(tmp_ptr,\n\t\t                                           tmp_bytes_size,\n\t\t                                           it,\n\t\t                                           result_it,\n\t\t                                           num_selected_ptr,\n\t\t                                           N,\n\t\t                                           select_op,\n\t\t                                           stream.handle()));\n\t};\n\texec();\n\tauto tmp =\n\t    make_not_a_vector<uint8_t>(tmp_bytes_size, delayed_memory_resource);\n\ttmp_ptr = tmp.to_span().data();\n\texec();\n}\n\n} // namespace async\n\n} // namespace thrustshift\n", "meta": {"hexsha": "979fb31c72865e21886693c5aeb8b7d937eaf467", "size": 10635, "ext": "h", "lang": "C", "max_stars_repo_path": "include/thrustshift/select-if.h", "max_stars_repo_name": "pauleonix/thrustshift", "max_stars_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/thrustshift/select-if.h", "max_issues_repo_name": "pauleonix/thrustshift", "max_issues_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/thrustshift/select-if.h", "max_forks_repo_name": "pauleonix/thrustshift", "max_forks_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.868852459, "max_line_length": 81, "alphanum_fraction": 0.5660554772, "num_tokens": 2109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3923368443773708, "lm_q2_score": 0.023689470437778862, "lm_q1q2_score": 0.009294252076529171}}
{"text": "#ifndef ARRUS_COMMON_FORMAT_H\n#define ARRUS_COMMON_FORMAT_H\n\n// String formatting and parsing utilities.\n// Currently wraps fmt library calls.\n#include <fmt/format.h>\n#include <stdexcept>\n#include <cctype>\n#include <vector>\n#include <set>\n#include <unordered_set>\n#include <optional>\n#include <sstream>\n#include <gsl/span>\n\n#include <boost/algorithm/string/join.hpp>\n\n#include \"arrus/core/api/common/Tuple.h\"\n#include \"arrus/core/api/common/Interval.h\"\n\nnamespace arrus {\n\ntemplate<typename... Args>\nauto format(Args &&... args) {\n    return fmt::format(std::forward<Args>(args)...);\n}\n\n/**\n * Returns true if the given string contains numeric characters only.\n *\n * @param num string to verify\n * @return true if the given string contains numeric characters only,\n *         false otherwise.\n */\ninline bool isDigitsOnly(const std::string &num) {\n    return std::all_of(num.begin(), num.end(), isdigit);\n}\n\n/**\n * General purpose 'toString' function basing on ostream << operator.\n */\ntemplate<typename T>\nstd::string toString(const T &t)  {\n    std::ostringstream ss;\n    ss << t;\n    return ss.str();\n}\n\ntemplate<typename T>\ninline std::string toString(const std::vector<T> &values) {\n    std::vector<std::string> vStr(values.size());\n    std::transform(std::begin(values), std::end(values), std::begin(vStr),\n                   [](auto v) { return std::to_string(v); });\n    return boost::algorithm::join(vStr, \", \");\n}\n\ntemplate<typename T>\ninline std::string toString(\n        const gsl::span<T> &values) {\n    std::vector<std::string> vStr(values.size());\n    std::transform(std::begin(values), std::end(values), std::begin(vStr),\n                   [](auto v) { return std::to_string(v); });\n    return boost::algorithm::join(vStr, \", \");\n}\n\ntemplate<typename T>\ninline std::string toStringTransform(\n        const std::vector<T> &values,\n        const std::function<std::string(const T&)> &func) {\n    std::vector<std::string> vStr(values.size());\n    std::transform(std::begin(values), std::end(values), std::begin(vStr),\n                   [&func](T v) { return func(v); });\n    return boost::algorithm::join(vStr, \", \");\n}\n\ntemplate<typename T>\ninline std::string toString(const ::std::set<T> &values) {\n    std::vector<std::string> vStr(values.size());\n    std::transform(std::begin(values), std::end(values), std::begin(vStr),\n                   [](auto v) { return std::to_string(v); });\n    return boost::algorithm::join(vStr, \", \");\n}\n\ntemplate<typename T>\ninline std::string toString(const ::std::unordered_set<T> &values) {\n    std::vector<std::string> vStr(values.size());\n    std::transform(std::begin(values), std::end(values), std::begin(vStr),\n                   [](auto v) { return std::to_string(v); });\n    return boost::algorithm::join(vStr, \", \");\n}\n\ntemplate<typename T>\ninline std::string toString(const std::optional<T> value) {\n    if(value.has_value()) {\n        return std::to_string(value.value());\n    } else return \"(no value)\";\n}\n\ntemplate<typename T>\ninline std::string toString(const Tuple<T> tuple) {\n    return ::arrus::format(\"Tuple({})\", toString(tuple.getValues()));\n}\n\ntemplate<typename T>\ninline std::string toString(const Interval<T> i) {\n    return ::arrus::format(\"Interval: start: {}, right: {}\",\n                           i.start(), i.end());\n}\n\n}\n\n#endif //ARRUS_COMMON_FORMAT_H\n", "meta": {"hexsha": "9984672e483b93cd4e5b24200494b8fec98f7622", "size": 3334, "ext": "h", "lang": "C", "max_stars_repo_path": "arrus/common/format.h", "max_stars_repo_name": "us4useu/arrus", "max_stars_repo_head_hexsha": "10487b09f556e327ddb1bec28fbaccf3b8b08064", "max_stars_repo_licenses": ["BSL-1.0", "MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2021-02-04T19:56:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T09:41:51.000Z", "max_issues_repo_path": "arrus/common/format.h", "max_issues_repo_name": "us4useu/arrus", "max_issues_repo_head_hexsha": "10487b09f556e327ddb1bec28fbaccf3b8b08064", "max_issues_repo_licenses": ["BSL-1.0", "MIT"], "max_issues_count": 60.0, "max_issues_repo_issues_event_min_datetime": "2020-11-06T04:59:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T17:39:06.000Z", "max_forks_repo_path": "arrus/common/format.h", "max_forks_repo_name": "us4useu/arrus", "max_forks_repo_head_hexsha": "10487b09f556e327ddb1bec28fbaccf3b8b08064", "max_forks_repo_licenses": ["BSL-1.0", "MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-07-22T16:13:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T08:53:31.000Z", "avg_line_length": 29.5044247788, "max_line_length": 74, "alphanum_fraction": 0.6433713257, "num_tokens": 796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21733753118592733, "lm_q2_score": 0.04272219785119705, "lm_q1q2_score": 0.009285137007815896}}
{"text": "\n// Copyright (C) 2021 Intel Corporation\n// SPDX-License-Identifier: Apache-2.0\n\n#ifndef _HEBench_ClearText_BE_DataPack_H_7e5fa8c2415240ea93eff148ed73539b\n#define _HEBench_ClearText_BE_DataPack_H_7e5fa8c2415240ea93eff148ed73539b\n\n#include <memory>\n#include <vector>\n\n#include <gsl/gsl>\n\n#include \"clear_error.h\"\n\n#include \"hebench/api_bridge/types.h\"\n\n#include \"hebench/api_bridge/cpp/hebench.hpp\"\n\ntemplate <class T>\n/**\n * @brief Encapsulates a HEBench DataPack.\n */\nclass ClearDataPack : public hebench::cpp::ITaggedObject\n{\nprivate:\n    HEBERROR_DECLARE_CLASS_NAME(ClearDataPack)\n\npublic:\n    explicit ClearDataPack(const hebench::APIBridge::DataPack &data_pack);\n    /**\n     * @brief Creates a new data pack with specified data sizes.\n     * @param sample_count[in] Number of data samples to be contained in this pack.\n     * @param p_sample_sizes[in] List of number of items per data sample.\n     * @param position[in] Parameter position corresponding to hebench::APIBridge::DataPack::param_position.\n     * @details This constructor initializes vector<vector<T>> data structure of the shape\n     * @code\n     * data = vector<vector<T>>(sample_count)\n     * @endcode\n     * and\n     * @code\n     * data[i] = vector<T>(p_sample_sizes[i])\n     * @endcode\n     */\n    explicit ClearDataPack(std::uint64_t sample_count,\n                           const std::uint64_t *p_sample_sizes,\n                           std::uint64_t position);\n    ~ClearDataPack() override {}\n\n    /**\n     * @brief Fills pre-allocated HEBench data pack with the data contained in this\n     * data pack.\n     * @param data_pack[out] HEBench data pack where to store the data.\n     * @param b_pad[in] If true, any extra space in \\p data_pack will be padded with\n     * zeroes. Otherwise, extra space will not be overwritten.\n     * @details This method is the inverse of the constructor. Thus, if the constructor\n     * performs some type of conversion, it must be reversible, and this method\n     * reverses the conversion.\n     *\n     * Default implementation is a simple copy of the data.\n     */\n    virtual void fillHEBenchDataPack(hebench::APIBridge::DataPack &data_pack, bool b_pad) const;\n\n    std::uint64_t getSamplesCount() const { return m_data.size(); }\n    gsl::span<T> getSample(std::uint64_t sample_index);\n    gsl::span<const T> getSample(std::uint64_t sample_index) const;\n    /**\n     * @brief Copies the data contained in \\p sample_data into this data pack's\n     * sample specified by \\p sample index.\n     * @param sample_index[in] Index of data sample in this data pack to overwrite.\n     * @param sample_data[in] Data to copy into this data pack sample.\n     * @details The size of this data pack sample will be resized to match the\n     * size of specified \\p sample-data.\n     */\n    void setSample(std::uint64_t sample_index, const gsl::span<T> &sample_data);\n    /**\n     * @brief Copies the data contained in \\p sample_data into this data pack's\n     * sample specified by \\p sample index.\n     * @param sample_index[in] Index of data sample in this data pack to overwrite.\n     * @param sample_data[in] Data to copy into this data pack sample.\n     * @param pad_value[in] Value to be used for padding if needed.\n     * @details The size of this data pack sample will remain constant. If not\n     * enough space, this method will copy as much data as it can from \\p sample_data\n     * into the specified sample. If this data pack's sample's size is more than\n     * the supplied data in \\p sample_data, the remaining space will be padded\n     * with the specified padding value \\p pad_value.\n     */\n    void setSample(std::uint64_t sample_index, const gsl::span<T> &sample_data, const T &pad_value);\n\n    std::uint64_t position() const { return m_position; }\n\nprotected:\n    std::vector<std::vector<T>> m_data;\n\n    ClearDataPack(std::uint64_t position = 0) :\n        m_position(position) {}\n    void allocateBuffers(std::uint64_t sample_count, const std::uint64_t *p_sample_sizes);\n    void allocateBuffers(const hebench::APIBridge::DataPack &data_pack);\n    /**\n     * @brief Performs a simple copy.\n     * @param data_pack\n     */\n    virtual void fillFromHEBenchDataPack(const hebench::APIBridge::DataPack &data_pack);\n\nprivate:\n    std::uint64_t m_position;\n};\n\n#include \"inl/data_container.inl\"\n\n#endif // defined _HEBench_ClearText_BE_DataPack_H_7e5fa8c2415240ea93eff148ed73539b\n", "meta": {"hexsha": "fccdf51c73f1c521ee6a89d79ba8a55df7ec15c4", "size": 4393, "ext": "h", "lang": "C", "max_stars_repo_path": "include/data_container.h", "max_stars_repo_name": "jlakness-intel/backend-cpu-helib", "max_stars_repo_head_hexsha": "ff74311abd749809b732f1f2f63fe78e245c726d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-28T17:57:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T17:57:32.000Z", "max_issues_repo_path": "include/data_container.h", "max_issues_repo_name": "jlakness-intel/backend-cpu-helib", "max_issues_repo_head_hexsha": "ff74311abd749809b732f1f2f63fe78e245c726d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-12-06T19:37:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-16T23:37:53.000Z", "max_forks_repo_path": "include/data_container.h", "max_forks_repo_name": "jlakness-intel/backend-cpu-helib", "max_forks_repo_head_hexsha": "ff74311abd749809b732f1f2f63fe78e245c726d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-05T18:01:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-05T18:01:48.000Z", "avg_line_length": 39.5765765766, "max_line_length": 108, "alphanum_fraction": 0.7054404735, "num_tokens": 1110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20689405370611846, "lm_q2_score": 0.04468087170375928, "lm_q1q2_score": 0.009244206669913761}}
{"text": "\ufeff#pragma once\n#include <Hypo/System/Exports.h>\n#include <Hypo/Config.h>\n#include <ostream>\n#include <gsl/span>\n#include <Hypo/System/Exports.h>\n\n#include <Hypo/System/Buffer/Buffer.h>\n#include <Hypo/System/Streams/MemoryStream.h>\n\nnamespace Hypo\n{\n\tclass HYPO_SYSTEM_API BinaryWriter\n\t{\n\tpublic:\n\t\tBinaryWriter(std::ostream& stream);\n\t\n\t\tBinaryWriter& operator <<(uInt8 value);\n\t\tBinaryWriter& operator <<(uInt16 value);\n\t\tBinaryWriter& operator <<(uInt32 value);\n\t\tBinaryWriter& operator <<(uInt64 value);\n\n\t\tBinaryWriter& operator <<(Int8 value);\n\t\tBinaryWriter& operator <<(Int16 value);\n\t\tBinaryWriter& operator <<(Int32 value);\n\t\tBinaryWriter& operator <<(Int64 value);\n\n\t\tBinaryWriter& operator <<(const std::string& value);\n\t\tBinaryWriter& operator <<(const char* value);\n\n\t\ttemplate<typename T>\n\t\tBinaryWriter& operator <<(const std::vector<T>& value)\n\t\t{\n\t\t\tconst uInt32 size(static_cast<uInt32>(value.size()));\n\t\t\t*this << size;\n\t\t\tfor (auto& element : value)\n\t\t\t{\n\t\t\t\t*this << element;\n\t\t\t}\n\t\t\treturn *this;\n\t\t}\n\n\t\tvoid WriteRaw(const std::string& data);\n\t\tvoid WriteRaw(const gsl::span<uInt8>& data);\n\t\tvoid WriteRaw(const void* data, int size);\n\t\t\n\t\tvoid WriteBOM();\n\t\n\t\tvoid Write7BitEncoded(uInt32 value);\n\t\tvoid Write7BitEncoded(uInt64 value);\n\n\t\tvoid Flush()const { m_Stream.flush(); }\n\t\tbool Good()const { return m_Stream.good(); }\n\t\tbool Bad()const { return m_Stream.bad(); }\n\t\tbool Fail() const { return m_Stream.fail(); }\n\n\t\tstd::ostream& GetStream() const {return m_Stream;}\t\n\tprivate:\n\t\tstd::ostream& m_Stream;\n\t};\n\n\n\ttemplate <typename T>\n\tclass BasicMemoryBinaryWriter : public BinaryWriter\n\t\t/// A convenient wrapper for using Buffer and MemoryStream with BinarWriter.\n\t{\n\tpublic:\n\t\tBasicMemoryBinaryWriter(Buffer<T>& data) :\n\t\t\tBinaryWriter(_ostr),\n\t\t\t_data(data),\n\t\t\t_ostr(data.begin(), data.Capacity())\n\t\t{\n\t\t}\n\n\t\t~BasicMemoryBinaryWriter()\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tFlush();\n\t\t\t}\n\t\t\tcatch (...)\n\t\t\t{\n\t\t\t}\n\t\t}\n\n\t\tBuffer<T>& data()\n\t\t{\n\t\t\treturn _data;\n\t\t}\n\n\t\tconst Buffer<T>& data() const\n\t\t{\n\t\t\treturn _data;\n\t\t}\n\n\t\tconst MemoryOutputStream& stream() const\n\t\t{\n\t\t\treturn _ostr;\n\t\t}\n\n\t\tMemoryOutputStream& stream()\n\t\t{\n\t\t\treturn _ostr;\n\t\t}\n\n\tprivate:\n\t\tBuffer<T>& _data;\n\t\tMemoryOutputStream _ostr;\n\t};\n\n\n\ttypedef BasicMemoryBinaryWriter<char> MemoryBinaryWriter;\n\n}\n", "meta": {"hexsha": "2b68a678e97bcd2da4ced438e369303d2382124f", "size": 2290, "ext": "h", "lang": "C", "max_stars_repo_path": "HypoSystem/src/Hypo/System/Streams/BinaryWriter.h", "max_stars_repo_name": "TheodorLindberg/Hypo", "max_stars_repo_head_hexsha": "67107bf14671711ab5979e2af8c7ead6ee043805", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HypoSystem/src/Hypo/System/Streams/BinaryWriter.h", "max_issues_repo_name": "TheodorLindberg/Hypo", "max_issues_repo_head_hexsha": "67107bf14671711ab5979e2af8c7ead6ee043805", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HypoSystem/src/Hypo/System/Streams/BinaryWriter.h", "max_forks_repo_name": "TheodorLindberg/Hypo", "max_forks_repo_head_hexsha": "67107bf14671711ab5979e2af8c7ead6ee043805", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.9130434783, "max_line_length": 78, "alphanum_fraction": 0.6742358079, "num_tokens": 656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.27512972382317524, "lm_q2_score": 0.03358950456175575, "lm_q1q2_score": 0.009241471113433146}}
{"text": "#pragma once\n#include <gsl/gsl_vector.h>\n#include \"BooleanNodes.h\"\n#include \"BooleanDAG.h\"\n#include <map>\n#include \"SymbolicEvaluator.h\"\n#include \"ConflictGenerator.h\"\n\n#include <iostream>\n#include \"Util.h\"\n\n\nclass SmartConflictGenerator: public ConflictGenerator {\n\tSymbolicEvaluator* eval;\n\tmap<int, int>& imap;\n\tBooleanDAG* dag;\n\tset<int>& ignoredBoolNodes;\n\tset<int>& ctrlNodes;\n\t\n\t\n\tvector<set<int>> dependentInputs;\n\tvector<set<int>> dependentCtrls;\n\npublic:\n\tConflictGenerator(SymbolicEvaluator* eval_, map<int, int>& imap_, BooleanDAG* dag_, set<int>& ignoredBoolNodes_, set<int>& ctrlNodes_): eval(eval_), imap(imap_), dag(dag_), ignoredBoolNodes(ignoredBoolNodes_), ctrlNodes(ctrlNodes_) {\n\t\t// process the dag and collect dependencies\n\t\tfor (BooleanDAG::iterator node_it = dag->begin(); node_it != dag->end(); ++node_it) {\n\t\t\tbool_node* n = *node_it;\n\t\t\tset<int> inputs; set<int> ctrls;\n\t\t\t\n\t\t\tconst vector<bool_node*>& parents = n->parents();\n\t\t\tfor (int i = 0; i < parents.size(); i++) {\n\t\t\t\tbool_node* parent = parents[i];\n\t\t\t\tset<int>& parentInputs = dependentInputs[parent->id];\n\t\t\t\tset<int>& parentCtrls = dependentCtrls[parent->id];\n\t\t\t\tif (parent->getOtype() == OutType::BOOL) {\n\t\t\t\t\tif (ignoredBoolNodes.find(parent->id) == ignoredBoolNodes.end()) {\n\t\t\t\t\t\tinputs.insert(parent->id);\n\t\t\t\t\t\t//inputs.insert(parentInputs.begin(), parentInputs.end());\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tinputs.insert(parentInputs.begin(), parentInputs.end());\n\t\t\t\t\tctrls.insert(parentCtrls.begin(), parentCtrls.end());\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (ctrlNodes.find(parent->id) != ctrlNodes.end()) {\n\t\t\t\t\tctrls.insert(parent->id);\n\t\t\t\t}\n\t\t\t}\n\t\t\tdependentInputs.push_back(inputs);\n\t\t\tdependentCtrls.push_back(ctrls);\n\t\t}\n\t\t\n\t}\n\t\n\tbool isConflict(set<int> influentialControls, set<int> myControls) {\n\t\tfor (int i : influentialControls) {\n\t\t\tif (myControls.find(i) != myControls.end()) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tvirtual vector<pair<int, int>> getConflicts(gsl_vector* state, vector<vector<int>>& allInputs, vector<int>& instanceIds, int rowid, int colid) {\n\t\tvector<pair<int, int>> conflicts;\n\t\tfor (int i = 0; i < allInputs.size(); i++) {\n\t\t\tconst map<int, int>& nodeValsMap = Util::getNodeToValMap(imap, allInputs[i]);\n\t\t\teval->run(state, nodeValsMap);\n\t\t\t\n\t\t\t// First, find a failing node\n\t\t\tbool_node* failedNode = NULL;\n\t\t\tfor (BooleanDAG::iterator node_it = dag->begin(); node_it != dag->end(); ++node_it) {\n\t\t\t\tbool_node* n = *node_it;\n\t\t\t\tif (n->type == bool_node::ASSERT) {\n\t\t\t\t\tif (!eval->check(n->mother, 1)) {\n\t\t\t\t\t\tfailedNode = n;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (n->getOtype() == OutType::BOOL) {\n\t\t\t\t\tauto it = nodeValsMap.find(n->id);\n\t\t\t\t\tif (it != nodeValsMap.end()) {\n\t\t\t\t\t\tint val = it->second;\n\t\t\t\t\t\tif (!eval->check(n, val)) {\n\t\t\t\t\t\t\tfailedNode = n;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tAssert(failedNode != NULL, \"No conflict?\");\n\t\t\tcout << failedNode->lprint() << endl;\n\t\t\tset<int> conflictNodes;\n\t\t\t// First, add all dependent inputs\n\t\t\tset<int>& depInputs = dependentInputs[failedNode->id];\n\t\t\tconflictNodes.insert(depInputs.begin(), depInputs.end());\n\t\t\tcout << \"Dep inputs:\" << endl;\n\t\t\tfor (auto it = depInputs.begin(); it != depInputs.end(); it++) {\n\t\t\t\tcout << (*dag)[(*it)]->lprint() << endl;\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\tset<int>& depCtrls = dependentCtrls[failedNode->id];\n\t\t\tcout << \"Dep ctrls:\" << endl;\n\t\t\tfor (auto it = depCtrls.begin(); it != depCtrls.end(); it++) {\n\t\t\t\tcout << (*dag)[(*it)]->lprint() << endl;\n\t\t\t}\n\t\t\t// Next, collect all boolean nodes that are influenced by the controls that affect the failed node\n\t\t\tfor (BooleanDAG::iterator node_it = dag->begin(); node_it != dag->end(); ++node_it) {\n\t\t\t\tbool_node* n = *node_it;\n\t\t\t\tif (n->type == bool_node::ASSERT) {\n\t\t\t\t\tif (isConflict(depCtrls, dependentCtrls[n->id])) {\n\t\t\t\t\t\tconflictNodes.insert(n->id);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (n->getOtype() == OutType::BOOL) {\n\t\t\t\t\tif (isConflict(depCtrls, dependentCtrls[n->id])) {\n\t\t\t\t\t\tconflictNodes.insert(n->id);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tcout << \"Final conflict nodes\" << endl;\n\t\t\n\t\t\t//conflictNodes.insert(colid);\n\t\t\t\n\t\t\t\n\t\t\t// Process the conflicts\n\t\t\tfor (int j = 0; j < imap.size(); j++) {\n\t\t\t\tif (allInputs[i][j] != EMPTY) {\n\t\t\t\t\tif (ignoredBoolNodes.find(imap[j]) == ignoredBoolNodes.end()) {\n\t\t\t\t\t\tif (imap[j] < 0 || conflictNodes.find(imap[j]) != conflictNodes.end()) {\n\t\t\t\t\t\t\tif (imap[j] >= 0) {\n\t\t\t\t\t\t\t\tcout << (*dag)[imap[j]]->lprint() << \" \" << allInputs[i][j] << endl;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconflicts.push_back(make_pair(instanceIds[i], j));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn conflicts;\n\t}\n\t\n};\n", "meta": {"hexsha": "026c62ead6c9da2ba25c134f5ddaea8af6ac1ae5", "size": 4543, "ext": "h", "lang": "C", "max_stars_repo_path": "src/SketchSolver/NumericalSynthesis/ConflictGenerators/SmartConflictGenerator.h", "max_stars_repo_name": "natebragg/sketch-backend", "max_stars_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_stars_repo_licenses": ["X11"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2020-08-20T14:54:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T00:28:40.000Z", "max_issues_repo_path": "src/SketchSolver/NumericalSynthesis/ConflictGenerators/SmartConflictGenerator.h", "max_issues_repo_name": "natebragg/sketch-backend", "max_issues_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_issues_repo_licenses": ["X11"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-01T16:53:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T04:02:09.000Z", "max_forks_repo_path": "src/SketchSolver/NumericalSynthesis/ConflictGenerators/SmartConflictGenerator.h", "max_forks_repo_name": "natebragg/sketch-backend", "max_forks_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_forks_repo_licenses": ["X11"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-04T20:47:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-06T01:45:04.000Z", "avg_line_length": 30.6959459459, "max_line_length": 234, "alphanum_fraction": 0.6156724631, "num_tokens": 1289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167941228964, "lm_q2_score": 0.02002344139910453, "lm_q1q2_score": 0.009231142761122853}}
{"text": "#pragma once\n\n#include <iostream>\n\n#include <gsl/gsl.h>\n\nnamespace util{\ntemplate<typename T>\nvoid print(T const&x){\n    std::cerr <<x << \" \";\n}\n\ntemplate<typename T, int64_t M>\nvoid print(gsl::span<T,M> const span){\n    for(auto x : span) print(x);\n    std::cerr << \" :1D\"<<std::endl;\n}\n\ntemplate<typename T, int64_t M,int64_t N>\nvoid print(gsl::span<T,M,N> const span){\n    ////ranged for iterates flattened span.\n    //for(auto x : span) print(x);\n    for(int64_t i=0; i<M; ++i) print(span[i]);\n    std::cerr << \" :2D static\"<<std::endl;\n}\n\ntemplate<typename T, int64_t M,int64_t N>\nvoid print(gsl::span<const T,gsl::dynamic_range,M,N> span){\n    for(int64_t i=0; i<M; ++i) print(span[i]);\n    //for(auto it=span.cbegin(); it<span.cend(); ++it) print_span(*it);\n    std::cerr << \" :2D dynamic_range\"<<std::endl;\n}\n// template<typename T>\n// void print(std::vector<T> const & vec){\n//     print(gsl::as_span(vec));\n// }\n// template<typename T, size_t M>\n// void print(std::array<T,M> arr){\n//     print(gsl::as_span(arr));\n// }\n\n}//namespcae util\n", "meta": {"hexsha": "2f1211c5a22ca1ecbb04ace5719e1b302255e1f8", "size": 1049, "ext": "h", "lang": "C", "max_stars_repo_path": "rnn++/utils/print.h", "max_stars_repo_name": "uphere-co/nlp-prototype", "max_stars_repo_head_hexsha": "c4623927e5c5c5f9c3e702eb36497ea1d9fd1ff3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rnn++/utils/print.h", "max_issues_repo_name": "uphere-co/nlp-prototype", "max_issues_repo_head_hexsha": "c4623927e5c5c5f9c3e702eb36497ea1d9fd1ff3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rnn++/utils/print.h", "max_forks_repo_name": "uphere-co/nlp-prototype", "max_forks_repo_head_hexsha": "c4623927e5c5c5f9c3e702eb36497ea1d9fd1ff3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3953488372, "max_line_length": 71, "alphanum_fraction": 0.6177311725, "num_tokens": 324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21206880435710532, "lm_q2_score": 0.04336580108207338, "lm_q1q2_score": 0.009196533585463365}}
{"text": "#include <stdio.h>\n#include <stdarg.h>\n#include <string.h>\n#include <math.h>\n#include <gbpLib.h>\n#include <gbpRNG.h>\n#include <gbpMCMC.h>\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_fit.h>\n#include <gsl/gsl_interp.h>\n\nvoid free_MCMC(MCMC_info *MCMC) {\n    int           i_P, i_DS;\n    int           i_array;\n    MCMC_DS_info *current_DS;\n    MCMC_DS_info *next_DS;\n\n    SID_log(\"Freeing MCMC structure...\", SID_LOG_OPEN);\n\n    // Parameter arrays\n    for(i_P = 0; i_P < MCMC->n_P; i_P++)\n        SID_free(SID_FARG MCMC->P_names[i_P]);\n    SID_free(SID_FARG MCMC->P_names);\n    SID_free(SID_FARG MCMC->P_init);\n    SID_free(SID_FARG MCMC->P_new);\n    SID_free(SID_FARG MCMC->P_last);\n    SID_free(SID_FARG MCMC->P_chain);\n    SID_free(SID_FARG MCMC->P_limit_min);\n    SID_free(SID_FARG MCMC->P_limit_max);\n    if(MCMC->n_arrays > 0) {\n        for(i_array = 0; i_array < MCMC->n_arrays; i_array++) {\n            SID_free(SID_FARG MCMC->array[i_array]);\n            SID_free(SID_FARG MCMC->array_name[i_array]);\n        }\n        SID_free(SID_FARG MCMC->array);\n        SID_free(SID_FARG MCMC->array_name);\n    }\n\n    // Covariance and displacement vector\n    free_MCMC_covariance(MCMC);\n\n    // Random number generator\n    if(MCMC->RNG != NULL)\n        free_RNG(MCMC->RNG);\n\n    // Dataset arrays\n    free_MCMC_arrays(MCMC);\n    free_MCMC_DS(MCMC);\n\n    // Communicators\n    SID_Comm_free(&(MCMC->comm));\n\n    SID_log(\"Done.\", SID_LOG_CLOSE);\n}\n", "meta": {"hexsha": "1bb02e7e83bc55ae1d5c16de8724b79023280c06", "size": 1445, "ext": "c", "lang": "C", "max_stars_repo_path": "src/gbpMath/gbpMCMC/free_MCMC.c", "max_stars_repo_name": "gbpoole/gbpCode", "max_stars_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-10-20T11:39:53.000Z", "max_stars_repo_stars_event_max_datetime": "2015-10-20T11:39:53.000Z", "max_issues_repo_path": "src/gbpMath/gbpMCMC/free_MCMC.c", "max_issues_repo_name": "gbpoole/gbpCode", "max_issues_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-07-30T11:10:49.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-18T00:40:46.000Z", "max_forks_repo_path": "src/gbpMath/gbpMCMC/free_MCMC.c", "max_forks_repo_name": "gbpoole/gbpCode", "max_forks_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-01-23T00:50:40.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-01T08:14:24.000Z", "avg_line_length": 26.2727272727, "max_line_length": 63, "alphanum_fraction": 0.6415224913, "num_tokens": 475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37022539259558657, "lm_q2_score": 0.024798158123527633, "lm_q1q2_score": 0.009180907826930452}}
{"text": "/* matrix/gsl_matrix_short.h\r\n * \r\n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\r\n * \r\n * This program is free software; you can redistribute it and/or modify\r\n * it under the terms of the GNU General Public License as published by\r\n * the Free Software Foundation; either version 3 of the License, or (at\r\n * your option) any later version.\r\n * \r\n * This program is distributed in the hope that it will be useful, but\r\n * WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n * General Public License for more details.\r\n * \r\n * You should have received a copy of the GNU General Public License\r\n * along with this program; if not, write to the Free Software\r\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r\n */\r\n\r\n#ifndef __GSL_MATRIX_SHORT_H__\r\n#define __GSL_MATRIX_SHORT_H__\r\n\r\n#if !defined( GSL_FUN )\r\n#  if !defined( GSL_DLL )\r\n#    define GSL_FUN extern\r\n#  elif defined( BUILD_GSL_DLL )\r\n#    define GSL_FUN extern __declspec(dllexport)\r\n#  else\r\n#    define GSL_FUN extern __declspec(dllimport)\r\n#  endif\r\n#endif\r\n\r\n#include <stdlib.h>\r\n#include <gsl/gsl_types.h>\r\n#include <gsl/gsl_errno.h>\r\n#include <gsl/gsl_inline.h>\r\n#include <gsl/gsl_check_range.h>\r\n#include <gsl/gsl_vector_short.h>\r\n\r\n#undef __BEGIN_DECLS\r\n#undef __END_DECLS\r\n#ifdef __cplusplus\r\n# define __BEGIN_DECLS extern \"C\" {\r\n# define __END_DECLS }\r\n#else\r\n# define __BEGIN_DECLS /* empty */\r\n# define __END_DECLS /* empty */\r\n#endif\r\n\r\n__BEGIN_DECLS\r\n\r\ntypedef struct \r\n{\r\n  size_t size1;\r\n  size_t size2;\r\n  size_t tda;\r\n  short * data;\r\n  gsl_block_short * block;\r\n  int owner;\r\n} gsl_matrix_short;\r\n\r\ntypedef struct\r\n{\r\n  gsl_matrix_short matrix;\r\n} _gsl_matrix_short_view;\r\n\r\ntypedef _gsl_matrix_short_view gsl_matrix_short_view;\r\n\r\ntypedef struct\r\n{\r\n  gsl_matrix_short matrix;\r\n} _gsl_matrix_short_const_view;\r\n\r\ntypedef const _gsl_matrix_short_const_view gsl_matrix_short_const_view;\r\n\r\n/* Allocation */\r\n\r\nGSL_FUN gsl_matrix_short * \r\ngsl_matrix_short_alloc (const size_t n1, const size_t n2);\r\n\r\nGSL_FUN gsl_matrix_short * \r\ngsl_matrix_short_calloc (const size_t n1, const size_t n2);\r\n\r\nGSL_FUN gsl_matrix_short * \r\ngsl_matrix_short_alloc_from_block (gsl_block_short * b, \r\n                                   const size_t offset, \r\n                                   const size_t n1, \r\n                                   const size_t n2, \r\n                                   const size_t d2);\r\n\r\nGSL_FUN gsl_matrix_short * \r\ngsl_matrix_short_alloc_from_matrix (gsl_matrix_short * m,\r\n                                    const size_t k1, \r\n                                    const size_t k2,\r\n                                    const size_t n1, \r\n                                    const size_t n2);\r\n\r\nGSL_FUN gsl_vector_short * \r\ngsl_vector_short_alloc_row_from_matrix (gsl_matrix_short * m,\r\n                                        const size_t i);\r\n\r\nGSL_FUN gsl_vector_short * \r\ngsl_vector_short_alloc_col_from_matrix (gsl_matrix_short * m,\r\n                                        const size_t j);\r\n\r\nGSL_FUN void gsl_matrix_short_free (gsl_matrix_short * m);\r\n\r\n/* Views */\r\n\r\nGSL_FUN _gsl_matrix_short_view \r\ngsl_matrix_short_submatrix (gsl_matrix_short * m, \r\n                            const size_t i, const size_t j, \r\n                            const size_t n1, const size_t n2);\r\n\r\nGSL_FUN _gsl_vector_short_view \r\ngsl_matrix_short_row (gsl_matrix_short * m, const size_t i);\r\n\r\nGSL_FUN _gsl_vector_short_view \r\ngsl_matrix_short_column (gsl_matrix_short * m, const size_t j);\r\n\r\nGSL_FUN _gsl_vector_short_view \r\ngsl_matrix_short_diagonal (gsl_matrix_short * m);\r\n\r\nGSL_FUN _gsl_vector_short_view \r\ngsl_matrix_short_subdiagonal (gsl_matrix_short * m, const size_t k);\r\n\r\nGSL_FUN _gsl_vector_short_view \r\ngsl_matrix_short_superdiagonal (gsl_matrix_short * m, const size_t k);\r\n\r\nGSL_FUN _gsl_vector_short_view\r\ngsl_matrix_short_subrow (gsl_matrix_short * m, const size_t i,\r\n                         const size_t offset, const size_t n);\r\n\r\nGSL_FUN _gsl_vector_short_view\r\ngsl_matrix_short_subcolumn (gsl_matrix_short * m, const size_t j,\r\n                            const size_t offset, const size_t n);\r\n\r\nGSL_FUN _gsl_matrix_short_view\r\ngsl_matrix_short_view_array (short * base,\r\n                             const size_t n1, \r\n                             const size_t n2);\r\n\r\nGSL_FUN _gsl_matrix_short_view\r\ngsl_matrix_short_view_array_with_tda (short * base, \r\n                                      const size_t n1, \r\n                                      const size_t n2,\r\n                                      const size_t tda);\r\n\r\n\r\nGSL_FUN _gsl_matrix_short_view\r\ngsl_matrix_short_view_vector (gsl_vector_short * v,\r\n                              const size_t n1, \r\n                              const size_t n2);\r\n\r\nGSL_FUN _gsl_matrix_short_view\r\ngsl_matrix_short_view_vector_with_tda (gsl_vector_short * v,\r\n                                       const size_t n1, \r\n                                       const size_t n2,\r\n                                       const size_t tda);\r\n\r\n\r\nGSL_FUN _gsl_matrix_short_const_view \r\ngsl_matrix_short_const_submatrix (const gsl_matrix_short * m, \r\n                                  const size_t i, const size_t j, \r\n                                  const size_t n1, const size_t n2);\r\n\r\nGSL_FUN _gsl_vector_short_const_view \r\ngsl_matrix_short_const_row (const gsl_matrix_short * m, \r\n                            const size_t i);\r\n\r\nGSL_FUN _gsl_vector_short_const_view \r\ngsl_matrix_short_const_column (const gsl_matrix_short * m, \r\n                               const size_t j);\r\n\r\nGSL_FUN _gsl_vector_short_const_view\r\ngsl_matrix_short_const_diagonal (const gsl_matrix_short * m);\r\n\r\nGSL_FUN _gsl_vector_short_const_view \r\ngsl_matrix_short_const_subdiagonal (const gsl_matrix_short * m, \r\n                                    const size_t k);\r\n\r\nGSL_FUN _gsl_vector_short_const_view \r\ngsl_matrix_short_const_superdiagonal (const gsl_matrix_short * m, \r\n                                      const size_t k);\r\n\r\nGSL_FUN _gsl_vector_short_const_view\r\ngsl_matrix_short_const_subrow (const gsl_matrix_short * m, const size_t i,\r\n                               const size_t offset, const size_t n);\r\n\r\nGSL_FUN _gsl_vector_short_const_view\r\ngsl_matrix_short_const_subcolumn (const gsl_matrix_short * m, const size_t j,\r\n                                  const size_t offset, const size_t n);\r\n\r\nGSL_FUN _gsl_matrix_short_const_view\r\ngsl_matrix_short_const_view_array (const short * base,\r\n                                   const size_t n1, \r\n                                   const size_t n2);\r\n\r\nGSL_FUN _gsl_matrix_short_const_view\r\ngsl_matrix_short_const_view_array_with_tda (const short * base, \r\n                                            const size_t n1, \r\n                                            const size_t n2,\r\n                                            const size_t tda);\r\n\r\nGSL_FUN _gsl_matrix_short_const_view\r\ngsl_matrix_short_const_view_vector (const gsl_vector_short * v,\r\n                                    const size_t n1, \r\n                                    const size_t n2);\r\n\r\nGSL_FUN _gsl_matrix_short_const_view\r\ngsl_matrix_short_const_view_vector_with_tda (const gsl_vector_short * v,\r\n                                             const size_t n1, \r\n                                             const size_t n2,\r\n                                             const size_t tda);\r\n\r\n/* Operations */\r\n\r\nGSL_FUN void gsl_matrix_short_set_zero (gsl_matrix_short * m);\r\nGSL_FUN void gsl_matrix_short_set_identity (gsl_matrix_short * m);\r\nGSL_FUN void gsl_matrix_short_set_all (gsl_matrix_short * m, short x);\r\n\r\nGSL_FUN int gsl_matrix_short_fread (FILE * stream, gsl_matrix_short * m) ;\r\nGSL_FUN int gsl_matrix_short_fwrite (FILE * stream, const gsl_matrix_short * m) ;\r\nGSL_FUN int gsl_matrix_short_fscanf (FILE * stream, gsl_matrix_short * m);\r\nGSL_FUN int gsl_matrix_short_fprintf (FILE * stream, const gsl_matrix_short * m, const char * format);\r\n \r\nGSL_FUN int gsl_matrix_short_memcpy(gsl_matrix_short * dest, const gsl_matrix_short * src);\r\nGSL_FUN int gsl_matrix_short_swap(gsl_matrix_short * m1, gsl_matrix_short * m2);\r\n\r\nGSL_FUN int gsl_matrix_short_swap_rows(gsl_matrix_short * m, const size_t i, const size_t j);\r\nGSL_FUN int gsl_matrix_short_swap_columns(gsl_matrix_short * m, const size_t i, const size_t j);\r\nGSL_FUN int gsl_matrix_short_swap_rowcol(gsl_matrix_short * m, const size_t i, const size_t j);\r\nGSL_FUN int gsl_matrix_short_transpose (gsl_matrix_short * m);\r\nGSL_FUN int gsl_matrix_short_transpose_memcpy (gsl_matrix_short * dest, const gsl_matrix_short * src);\r\n\r\nGSL_FUN short gsl_matrix_short_max (const gsl_matrix_short * m);\r\nGSL_FUN short gsl_matrix_short_min (const gsl_matrix_short * m);\r\nGSL_FUN void gsl_matrix_short_minmax (const gsl_matrix_short * m, short * min_out, short * max_out);\r\n\r\nGSL_FUN void gsl_matrix_short_max_index (const gsl_matrix_short * m, size_t * imax, size_t *jmax);\r\nGSL_FUN void gsl_matrix_short_min_index (const gsl_matrix_short * m, size_t * imin, size_t *jmin);\r\nGSL_FUN void gsl_matrix_short_minmax_index (const gsl_matrix_short * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);\r\n\r\nGSL_FUN int gsl_matrix_short_isnull (const gsl_matrix_short * m);\r\nGSL_FUN int gsl_matrix_short_ispos (const gsl_matrix_short * m);\r\nGSL_FUN int gsl_matrix_short_isneg (const gsl_matrix_short * m);\r\nGSL_FUN int gsl_matrix_short_isnonneg (const gsl_matrix_short * m);\r\n\r\nGSL_FUN int gsl_matrix_short_add (gsl_matrix_short * a, const gsl_matrix_short * b);\r\nGSL_FUN int gsl_matrix_short_sub (gsl_matrix_short * a, const gsl_matrix_short * b);\r\nGSL_FUN int gsl_matrix_short_mul_elements (gsl_matrix_short * a, const gsl_matrix_short * b);\r\nGSL_FUN int gsl_matrix_short_div_elements (gsl_matrix_short * a, const gsl_matrix_short * b);\r\nGSL_FUN int gsl_matrix_short_scale (gsl_matrix_short * a, const double x);\r\nGSL_FUN int gsl_matrix_short_add_constant (gsl_matrix_short * a, const double x);\r\nGSL_FUN int gsl_matrix_short_add_diagonal (gsl_matrix_short * a, const double x);\r\n\r\n/***********************************************************************/\r\n/* The functions below are obsolete                                    */\r\n/***********************************************************************/\r\nGSL_FUN int gsl_matrix_short_get_row(gsl_vector_short * v, const gsl_matrix_short * m, const size_t i);\r\nGSL_FUN int gsl_matrix_short_get_col(gsl_vector_short * v, const gsl_matrix_short * m, const size_t j);\r\nGSL_FUN int gsl_matrix_short_set_row(gsl_matrix_short * m, const size_t i, const gsl_vector_short * v);\r\nGSL_FUN int gsl_matrix_short_set_col(gsl_matrix_short * m, const size_t j, const gsl_vector_short * v);\r\n/***********************************************************************/\r\n\r\n/* inline functions if you are using GCC */\r\n\r\nGSL_FUN INLINE_DECL short   gsl_matrix_short_get(const gsl_matrix_short * m, const size_t i, const size_t j);\r\nGSL_FUN INLINE_DECL void    gsl_matrix_short_set(gsl_matrix_short * m, const size_t i, const size_t j, const short x);\r\nGSL_FUN INLINE_DECL short * gsl_matrix_short_ptr(gsl_matrix_short * m, const size_t i, const size_t j);\r\nGSL_FUN INLINE_DECL const short * gsl_matrix_short_const_ptr(const gsl_matrix_short * m, const size_t i, const size_t j);\r\n\r\n#ifdef HAVE_INLINE\r\nINLINE_FUN \r\nshort\r\ngsl_matrix_short_get(const gsl_matrix_short * m, const size_t i, const size_t j)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(1)) \r\n    {\r\n      if (i >= m->size1)\r\n        {\r\n          GSL_ERROR_VAL(\"first index out of range\", GSL_EINVAL, 0) ;\r\n        }\r\n      else if (j >= m->size2)\r\n        {\r\n          GSL_ERROR_VAL(\"second index out of range\", GSL_EINVAL, 0) ;\r\n        }\r\n    }\r\n#endif\r\n  return m->data[i * m->tda + j] ;\r\n} \r\n\r\nINLINE_FUN \r\nvoid\r\ngsl_matrix_short_set(gsl_matrix_short * m, const size_t i, const size_t j, const short x)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(1)) \r\n    {\r\n      if (i >= m->size1)\r\n        {\r\n          GSL_ERROR_VOID(\"first index out of range\", GSL_EINVAL) ;\r\n        }\r\n      else if (j >= m->size2)\r\n        {\r\n          GSL_ERROR_VOID(\"second index out of range\", GSL_EINVAL) ;\r\n        }\r\n    }\r\n#endif\r\n  m->data[i * m->tda + j] = x ;\r\n}\r\n\r\nINLINE_FUN \r\nshort *\r\ngsl_matrix_short_ptr(gsl_matrix_short * m, const size_t i, const size_t j)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(1)) \r\n    {\r\n      if (i >= m->size1)\r\n        {\r\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\r\n        }\r\n      else if (j >= m->size2)\r\n        {\r\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\r\n        }\r\n    }\r\n#endif\r\n  return (short *) (m->data + (i * m->tda + j)) ;\r\n} \r\n\r\nINLINE_FUN \r\nconst short *\r\ngsl_matrix_short_const_ptr(const gsl_matrix_short * m, const size_t i, const size_t j)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(1)) \r\n    {\r\n      if (i >= m->size1)\r\n        {\r\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\r\n        }\r\n      else if (j >= m->size2)\r\n        {\r\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\r\n        }\r\n    }\r\n#endif\r\n  return (const short *) (m->data + (i * m->tda + j)) ;\r\n} \r\n\r\n#endif\r\n\r\n__END_DECLS\r\n\r\n#endif /* __GSL_MATRIX_SHORT_H__ */\r\n", "meta": {"hexsha": "7aed526b1358ea69e34ce41fbced21744cdfff83", "size": 13352, "ext": "h", "lang": "C", "max_stars_repo_path": "deps/include/gsl/gsl_matrix_short.h", "max_stars_repo_name": "berkus/music-cs", "max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "deps/include/gsl/gsl_matrix_short.h", "max_issues_repo_name": "berkus/music-cs", "max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "deps/include/gsl/gsl_matrix_short.h", "max_forks_repo_name": "berkus/music-cs", "max_forks_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1922005571, "max_line_length": 133, "alphanum_fraction": 0.6460455362, "num_tokens": 3177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.214691419112242, "lm_q2_score": 0.042722200593555464, "lm_q1q2_score": 0.00917208987302829}}
{"text": "/* ****************************************************************** **\n**    OpenSees - Open System for Earthquake Engineering Simulation    **\n**          Pacific Earthquake Engineering Research Center            **\n**                                                                    **\n**                                                                    **\n** (C) Copyright 1999, The Regents of the University of California    **\n** All Rights Reserved.                                               **\n**                                                                    **\n** Commercial use of this program without express permission of the   **\n** University of California, Berkeley, is strictly prohibited.  See   **\n** file 'COPYRIGHT'  in main directory for information on usage and   **\n** redistribution,  and for a DISCLAIMER OF ALL WARRANTIES.           **\n**                                                                    **\n** Developed by:                                                      **\n**   Frank McKenna (fmckenna@ce.berkeley.edu)                         **\n**   Gregory L. Fenves (fenves@ce.berkeley.edu)                       **\n**   Filip C. Filippou (filippou@ce.berkeley.edu)                     **\n**                                                                    **\n** ****************************************************************** */\n                                                                        \n// $Revision: 1.2 $\n// $Date: 2007-02-14 20:12:32 $\n// $Source: /usr/local/cvs/OpenSees/SRC/system_of_eqn/linearSOE/petsc/ShadowPetscSOE.h,v $\n                                                                        \n                                                                        \n// File: ~/system_of_eqn/linearSOE/petsc/ShadowPetscSOE.h\n//\n// Written: fmk & om\n// Created: 7/98\n// Revision: A\n//\n// Description: This file contains the class definition for ShadowPetscSOE\n// ShadowPetscSOE is a subclass of LinearSOE. \n\n// What: \"@(#) ShadowPetscSOE.h, revA\"\n\n#ifndef ShadowPetscSOE_h\n#define ShadowPetscSOE_h\n\n#include <LinearSOE.h>\n#include <Vector.h>\n#include <PetscSOE.h>\n\nextern \"C\" {\n#include <petsc.h>\n}\n\nclass PetscSolver;\n\nclass ShadowPetscSOE : public LinearSOE\n{\n  public:\n    ShadowPetscSOE(PetscSolver &theSolver, int blockSize);    \n    \n    ~ShadowPetscSOE();\n\n    int solve(void);    \n\n    int getNumEqn(void) const;\n    int setSize(Graph &theGraph);\n    \n    int addA(const Matrix &, const ID &, double fact = 1.0);\n    int addB(const Vector &, const ID &, double fact = 1.0);    \n    int setB(const Vector &, double fact = 1.0);        \n\n    void zeroA(void);\n    void zeroB(void);\n\n    const Vector &getX(void);\n    const Vector &getB(void);\n    double normRHS(void);\n\n    void setX(int loc, double value);    \n\n    int setSolver(PetscSolver &newSolver);    \n\n    int sendSelf(int commitTag, Channel &theChannel);\n    int recvSelf(int commitTag, Channel &theChannel, \n\t\t FEM_ObjectBroker &theBroker);    \n    \n  protected:\n    \n  private:\n    MPI_Comm theComm; // a comm for communicating to the ActorPetscSOE's\n                      // without using PETSC_COMM_WORLD\n    PetscSOE theSOE;  // the local portion of the SOE\n    PetscSolver *theSolver; // created by the user\n    int myRank;\n    int numProcessors;\n    int sendData[3];\n    void *sendBuffer;\n    int blockSize;\n};\n\n\n#endif\n\n\n\n\n\n\n", "meta": {"hexsha": "c96490fc998cbb65ca307c19a34bb058e93053d0", "size": 3380, "ext": "h", "lang": "C", "max_stars_repo_path": "OpenSees/SRC/system_of_eqn/linearSOE/petsc/ShadowPetscSOE.h", "max_stars_repo_name": "kuanshi/ductile-fracture", "max_stars_repo_head_hexsha": "ccb350564df54f5c5ec3a079100effe261b46650", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-03-05T16:25:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-17T14:12:03.000Z", "max_issues_repo_path": "SRC/system_of_eqn/linearSOE/petsc/ShadowPetscSOE.h", "max_issues_repo_name": "steva44/OpenSees", "max_issues_repo_head_hexsha": "417c3be117992a108c6bbbcf5c9b63806b9362ab", "max_issues_repo_licenses": ["TCL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SRC/system_of_eqn/linearSOE/petsc/ShadowPetscSOE.h", "max_forks_repo_name": "steva44/OpenSees", "max_forks_repo_head_hexsha": "417c3be117992a108c6bbbcf5c9b63806b9362ab", "max_forks_repo_licenses": ["TCL"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-09-21T03:11:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-19T07:29:37.000Z", "avg_line_length": 32.8155339806, "max_line_length": 90, "alphanum_fraction": 0.4872781065, "num_tokens": 719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2689414096510109, "lm_q2_score": 0.03410042509880116, "lm_q1q2_score": 0.009171016395770296}}
{"text": "/*\nFRACTAL - A program growing fractals to benchmark parallelization and drawing\nlibraries.\n\nCopyright 2009-2021, Javier Burguete Tolosa.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\n  list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice,\n  this list of conditions and the following disclaimer in the documentation\n  and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``AS IS'' AND ANY EXPRESS\nOR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\nEVENT SHALL Javier Burguete Tolosa OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\nINDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\nBUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\nADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n/**\n * \\file graphic.c\n * \\brief Source file to define the graphic drawing data and functions.\n * \\author Javier Burguete Tolosa.\n * \\copyright Copyright 2009-2021, Javier Burguete Tolosa.\n */\n#define _GNU_SOURCE\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <gsl/gsl_rng.h>\n#include <glib.h>\n#include <png.h>\n#include <ft2build.h>\n#include FT_FREETYPE_H\n#include <gtk/gtk.h>\n#include <GL/glew.h>\n\n#include \"config.h\"\n#include \"fractal.h\"\n#include \"image.h\"\n#include \"text.h\"\n#include \"graphic.h\"\n\nunsigned int window_width = 480;        ///< Graphic window width.\nunsigned int window_height = 480;       ///< Graphic window height.\n\n/**\n * Function to init the graphic data.\n\n * \\return 1 on success, 0 on error.\n */\nint\ngraphic_init (Graphic * graphic,        ///< Draw struct.\n              char *logo_name)  ///< Logo PNG file name.\n{\n  const GLfloat projection_matrix[16] = {\n    1., 0., 0., 0.,\n    0, 1., 0., 0.,\n    0., 0, 0., 0.,\n    0., 0., 0., 1.\n  };\n  const char *vs_3D_source =\n    \"attribute highp vec3 position;\"\n    \"attribute lowp vec3 color;\"\n    \"varying lowp vec3 fcolor;\"\n    \"uniform highp mat4 matrix;\"\n    \"void main ()\"\n    \"{gl_Position = matrix * vec4 (position, 1.f); fcolor = color;}\";\n  const char *fs_source =\n    \"varying lowp vec3 fcolor;\"\n    \"void main () {gl_FragColor = vec4 (fcolor, 1.f);}\";\n  const char *vertex_name = \"position\";\n  const char *color_name = \"color\";\n  const char *matrix_name = \"matrix\";\n  // GLSL version\n  const char *version = \"#version 120\\n\";       // OpenGL 2.1\n  const char *vs_3D_sources[3] = { version, INIT_GL_GLES, vs_3D_source };\n  const char *fs_sources[3] = { version, INIT_GL_GLES, fs_source };\n  const char *error_message;\n  GLint k;\n  GLuint vs, fs;\n  GLenum glew_status;\n\n#if DEBUG\n  printf (\"graphic_init: start\\n\");\n  fflush (stdout);\n#endif\n\n  // Initing GLEW\n#if DEBUG\n  printf (\"Initing GLEW\\n\");\n  fflush (stdout);\n#endif\n  glew_status = glewInit ();\n  if (glew_status != GLEW_OK)\n    {\n      printf (\"ERROR! glewInit: %s\\n\", glewGetErrorString (glew_status));\n      return 0;\n    }\n\n#if DEBUG\n  printf (\"graphic_init: compiling fragment shader\\n\");\n  fflush (stdout);\n#endif\n  fs = glCreateShader (GL_FRAGMENT_SHADER);\n  glShaderSource (fs, 3, fs_sources, NULL);\n  glCompileShader (fs);\n  glGetShaderiv (fs, GL_COMPILE_STATUS, &k);\n  if (!k)\n    {\n      error_message = \"unable to compile the fragment shader\";\n      goto exit_on_error;\n    }\n\n#if DEBUG\n  printf (\"graphic_init: compiling 3D vertex shader\\n\");\n  fflush (stdout);\n#endif\n  vs = glCreateShader (GL_VERTEX_SHADER);\n  glShaderSource (vs, 3, vs_3D_sources, NULL);\n  glCompileShader (vs);\n  glGetShaderiv (vs, GL_COMPILE_STATUS, &k);\n  if (!k)\n    {\n      glDeleteShader (fs);\n      error_message = \"unable to compile the 3D vertex shader\";\n      goto exit_on_error;\n    }\n\n  graphic->program_3D = glCreateProgram ();\n  glAttachShader (graphic->program_3D, vs);\n  glAttachShader (graphic->program_3D, fs);\n  glLinkProgram (graphic->program_3D);\n  glDeleteShader (vs);\n  glDeleteShader (fs);\n  glGetProgramiv (graphic->program_3D, GL_LINK_STATUS, &k);\n  if (!k)\n    {\n      error_message = \"unable to link the program 3D\";\n      goto exit_on_error;\n    }\n\n  graphic->attribute_3D_position\n    = glGetAttribLocation (graphic->program_3D, vertex_name);\n  if (graphic->attribute_3D_position == -1)\n    {\n      error_message = \"could not bind attribute\";\n      goto exit_on_error;\n    }\n\n  graphic->attribute_3D_color\n    = glGetAttribLocation (graphic->program_3D, color_name);\n  if (graphic->attribute_3D_color == -1)\n    {\n      error_message = \"could not bind attribute\";\n      goto exit_on_error;\n    }\n\n  graphic->uniform_3D_matrix\n    = glGetUniformLocation (graphic->program_3D, matrix_name);\n  if (graphic->uniform_3D_matrix == -1)\n    {\n      error_message = \"could not bind uniform\";\n      goto exit_on_error;\n    }\n\n  memcpy (graphic->projection_matrix, projection_matrix, 16 * sizeof (GLfloat));\n\n#if DEBUG\n  printf (\"graphic_init: initing logo\\n\");\n  fflush (stdout);\n#endif\n  if (logo_name)\n    {\n      graphic->logo = image_new (logo_name);\n      if (!graphic->logo)\n        {\n          error_message = \"unable to open the logo\";\n          goto exit_on_error;\n        }\n      if (!image_init (graphic->logo))\n        {\n          error_message = \"unable to init the logo\";\n          goto exit_on_error;\n        }\n    }\n  else\n    graphic->logo = NULL;\n\n#if DEBUG\n  printf (\"graphic_init: initing text\\n\");\n  fflush (stdout);\n#endif\n  if (!text_init (graphic->text))\n    {\n      error_message = \"unable to init the text\";\n      goto exit_on_error;\n    }\n\n#if DEBUG\n  printf (\"graphic_init: end\\n\");\n  fflush (stdout);\n#endif\n  return 1;\n\nexit_on_error:\n  printf (\"ERROR! %s\\n\", error_message);\n#if DEBUG\n  printf (\"graphic_init: end\\n\");\n  fflush (stdout);\n#endif\n  return 0;\n}\n\n/**\n * Function to free the memory used by graphic drawing functions.\n */\nvoid\ngraphic_destroy (Graphic * graphic)     ///< Graphic struct.\n{\n#if DEBUG\n  printf (\"graphic_destroy: start\\n\");\n  fflush (stdout);\n#endif\n  text_destroy (graphic->text);\n  image_destroy (graphic->logo);\n#if DEBUG\n  printf (\"graphic_destroy: end\\n\");\n  fflush (stdout);\n#endif\n}\n\n/**\n * Function to draw the fractal.\n */\nvoid\ngraphic_render (Graphic * graphic)      ///< Graphic struct.\n{\n  // Rectangle matrix\n  const Point3D square_vertices[4] = {\n    {{0., 0., 0.}, {0., 0., 0.}},\n    {{length, 0., 0.}, {0., 0., 0.}},\n    {{length, width, 0.}, {0., 0., 0.}},\n    {{0., width, 0.}, {0., 0., 0.}}\n  };\n  const GLushort square_indices[4] = { 0, 1, 2, 3 };\n  const GLfloat black[4] = { 0., 0., 0., 1. };\n  const char *str_version = \"Fractal 3.4.15\";\n  float cp, sp, ct, st, w, h, sx, sy;\n  GLuint vbo_square, ibo_square, vbo_points;\n\n#if DEBUG\n  printf (\"graphic_render: start\\n\");\n  fflush (stdout);\n#endif\n\n  // Drawing a white background\n  glClearColor (1., 1., 1., 0.);\n  glClear (GL_COLOR_BUFFER_BIT);\n\n#if DEBUG\n  printf (\"graphic_render: ending if no fractal\\n\");\n  fflush (stdout);\n#endif\n\n  // Ending if no fractal\n  if (!medium)\n    goto end_draw;\n\n#if DEBUG\n  printf (\"graphic_render: checking the fractal type\\n\");\n  fflush (stdout);\n#endif\n\n  // Checking if 3D or 2D fractal\n  glUseProgram (graphic->program_3D);\n  if (fractal_3D)\n    {\n      // Projection matrix\n      sincosf (graphic->phi, &sp, &cp);\n      sincosf (graphic->theta, &st, &ct);\n      w = graphic->xmax - graphic->xmin;\n      h = graphic->ymax - graphic->ymin;\n      graphic->projection_matrix[0] = 2. * cp / w;\n      graphic->projection_matrix[1] = 2. * ct * sp / h;\n      graphic->projection_matrix[4] = -2. * sp / w;\n      graphic->projection_matrix[5] = 2. * ct * cp / h;\n      graphic->projection_matrix[9] = 2. * st / h;\n      graphic->projection_matrix[12] = -1.;\n      graphic->projection_matrix[13] = -1. - 2. * graphic->ymin / h;\n      glUniformMatrix4fv (graphic->uniform_3D_matrix, 1, GL_FALSE,\n                          graphic->projection_matrix);\n\n      // Drawing a black rectangle\n      glGenBuffers (1, &vbo_square);\n      glBindBuffer (GL_ARRAY_BUFFER, vbo_square);\n      glBufferData (GL_ARRAY_BUFFER, sizeof (square_vertices), square_vertices,\n                    GL_DYNAMIC_DRAW);\n      glGenBuffers (1, &ibo_square);\n      glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, ibo_square);\n      glBufferData (GL_ELEMENT_ARRAY_BUFFER, sizeof (square_indices),\n                    square_indices, GL_DYNAMIC_DRAW);\n      glBindBuffer (GL_ARRAY_BUFFER, vbo_square);\n      glEnableVertexAttribArray (graphic->attribute_3D_position);\n      glVertexAttribPointer (graphic->attribute_3D_position,\n                             3, GL_FLOAT, GL_FALSE, sizeof (Point3D), NULL);\n      glEnableVertexAttribArray (graphic->attribute_3D_color);\n      glVertexAttribPointer (graphic->attribute_3D_color,\n                             3,\n                             GL_FLOAT,\n                             GL_FALSE,\n                             sizeof (Point3D),\n                             (GLvoid *) offsetof (Point3D, c));\n      glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, ibo_square);\n      glDrawElements (GL_LINE_LOOP, 4, GL_UNSIGNED_SHORT, 0);\n      glDeleteBuffers (1, &ibo_square);\n      glDeleteBuffers (1, &vbo_square);\n      glDisableVertexAttribArray (graphic->attribute_3D_color);\n      glDisableVertexAttribArray (graphic->attribute_3D_position);\n    }\n  else\n    {\n      // Projection matrix\n      graphic->projection_matrix[0] = 2. / width;\n      graphic->projection_matrix[5] = 2. / height;\n      graphic->projection_matrix[12] = graphic->projection_matrix[13] = -1.;\n      graphic->projection_matrix[1] = graphic->projection_matrix[4]\n        = graphic->projection_matrix[9] = 0.;\n      glUniformMatrix4fv (graphic->uniform_3D_matrix, 1, GL_FALSE,\n                          graphic->projection_matrix);\n    }\n\n#if DEBUG\n  printf (\"graphic_render: drawing the fractal points\\n\");\n  fflush (stdout);\n#endif\n\n  // Drawing the fractal points\n  glGenBuffers (1, &vbo_points);\n  glBindBuffer (GL_ARRAY_BUFFER, vbo_points);\n  glBufferData (GL_ARRAY_BUFFER, npoints * sizeof (Point3D), point,\n                GL_DYNAMIC_DRAW);\n  glEnableVertexAttribArray (graphic->attribute_3D_position);\n  glVertexAttribPointer (graphic->attribute_3D_position,\n                         3, GL_FLOAT, GL_FALSE, sizeof (Point3D), NULL);\n  glEnableVertexAttribArray (graphic->attribute_3D_color);\n  glVertexAttribPointer (graphic->attribute_3D_color,\n                         3,\n                         GL_FLOAT,\n                         GL_FALSE,\n                         sizeof (Point3D), (GLvoid *) offsetof (Point3D, c));\n  glDrawArrays (GL_POINTS, 0, npoints);\n  glDeleteBuffers (1, &vbo_points);\n  glDisableVertexAttribArray (graphic->attribute_3D_color);\n  glDisableVertexAttribArray (graphic->attribute_3D_position);\n\nend_draw:\n\n  // OpenGL properties\n  glEnable (GL_BLEND);\n  glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n#if DEBUG\n  printf (\"graphic_render: drawing the logo\\n\");\n  fflush (stdout);\n#endif\n\n  // Drawing the logo\n  image_draw (graphic->logo, 0, 0, window_width, window_height);\n\n#if DEBUG\n  printf (\"graphic_render: displaying the program version\\n\");\n  fflush (stdout);\n#endif\n\n  // Displaying the program version\n  sx = 0.15 * 12. / window_width;\n  sy = 0.15 * 12. / window_height;\n  text_draw (graphic->text, (char *) str_version,\n             0.99 - 7. * strlen (str_version) * sx, -0.99, sx, sy, black);\n\n  // Disabling OpenGL properties\n  glDisable (GL_BLEND);\n\n#if DEBUG\n  printf (\"graphic_render: displaying the draw\\n\");\n  fflush (stdout);\n#endif\n\n#if DEBUG\n  printf (\"graphic_render: end\\n\");\n  fflush (stdout);\n#endif\n}\n\n/**\n * Function to save the draw in a PNG file.\n */\nvoid\ngraphic_save (char *file_name)  ///< File name.\n{\n  png_struct *png;\n  png_info *info;\n  png_byte **row_pointers;\n  GLubyte *pixels;\n  FILE *file;\n  unsigned int i, row_bytes, pointers_bytes, pixels_bytes;\n\n#if DEBUG\n  printf (\"graphic_save: start\\n\");\n  fflush (stdout);\n#endif\n\n  // Creating the PNG header\n  png = png_create_write_struct (PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);\n  if (!png)\n    return;\n  info = png_create_info_struct (png);\n  if (!info)\n    return;\n  file = fopen (file_name, \"wb\");\n  if (!file)\n    return;\n  if (setjmp (png_jmpbuf (png)))\n    {\n      printf (\"Error png_init_io\\n\");\n      exit (0);\n    }\n  png_init_io (png, file);\n  if (setjmp (png_jmpbuf (png)))\n    {\n      printf (\"Error png_set_IHDR\\n\");\n      exit (0);\n    }\n  png_set_IHDR (png,\n                info,\n                window_width,\n                window_height,\n                8,\n                PNG_COLOR_TYPE_RGBA,\n                PNG_INTERLACE_NONE,\n                PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);\n  if (setjmp (png_jmpbuf (png)))\n    {\n      printf (\"Error png_write_info\\n\");\n      exit (0);\n    }\n  png_write_info (png, info);\n\n  // Getting the OpenGL pixels\n  glViewport (0, 0, window_width, window_height);\n  row_bytes = 4 * window_width;\n  pixels_bytes = row_bytes * window_height;\n  pixels = (GLubyte *) g_slice_alloc (pixels_bytes);\n  glReadPixels (0, 0, window_width, window_height, GL_RGBA, GL_UNSIGNED_BYTE,\n                pixels);\n\n  // Saving the pixels in the PNG order\n  pointers_bytes = window_height * sizeof (png_byte *);\n  row_pointers = (png_byte **) g_slice_alloc (pointers_bytes);\n  for (i = 0; i < window_height; ++i)\n    {\n      row_pointers[i] = (png_byte *) g_slice_alloc (row_bytes);\n      memcpy (row_pointers[i], pixels + (window_height - 1 - i) * row_bytes,\n              row_bytes);\n    }\n  if (setjmp (png_jmpbuf (png)))\n    {\n      printf (\"Error png_write_image\\n\");\n      exit (0);\n    }\n  png_write_image (png, row_pointers);\n\n  // Freeing memory\n  for (i = 0; i < window_height; ++i)\n    g_slice_free1 (row_bytes, row_pointers[i]);\n  g_slice_free1 (pointers_bytes, row_pointers);\n  g_slice_free1 (pixels_bytes, pixels);\n\n  // Saving the file\n  if (setjmp (png_jmpbuf (png)))\n    {\n      printf (\"Error png_write_end\\n\");\n      exit (0);\n    }\n  png_write_end (png, NULL);\n  fclose (file);\n\n  // Freeing memory\n  png_destroy_write_struct (&png, &info);\n\n#if DEBUG\n  printf (\"graphic_save: end\\n\");\n  fflush (stdout);\n#endif\n}\n", "meta": {"hexsha": "93ddc66d6c2cd7fdfd389bdde47e3aaa3509693d", "size": 14594, "ext": "c", "lang": "C", "max_stars_repo_path": "3.4.15/graphic.c", "max_stars_repo_name": "jburguete/fractal", "max_stars_repo_head_hexsha": "95d711dcb7b385556fb77794bc01737b21e99774", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "3.4.15/graphic.c", "max_issues_repo_name": "jburguete/fractal", "max_issues_repo_head_hexsha": "95d711dcb7b385556fb77794bc01737b21e99774", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3.4.15/graphic.c", "max_forks_repo_name": "jburguete/fractal", "max_forks_repo_head_hexsha": "95d711dcb7b385556fb77794bc01737b21e99774", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7850098619, "max_line_length": 80, "alphanum_fraction": 0.6525284363, "num_tokens": 3886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29421497216298875, "lm_q2_score": 0.03114382738739638, "lm_q1q2_score": 0.009162980307831753}}
{"text": "/*! \\file allvars.h\n *  \\brief declares global variables.\n *\n *  This file declares all global variables and structures. Further variables should be added here, and declared as\n *  \\e \\b extern. The actual existence of these variables is provided by the file \\ref allvars.cxx. To produce\n *  \\ref allvars.cxx from \\ref allvars.h, do the following:\n *\n *     \\arg Erase all \\#define's, typedef's, and enum's\n *     \\arg add \\#include \"allvars.h\", delete the \\#ifndef ALLVARS_H conditional\n *     \\arg delete all keywords 'extern'\n *     \\arg delete all struct definitions enclosed in {...}, e.g.\n *        \"extern struct global_data_all_processes {....} All;\"\n *        becomes \"struct global_data_all_processes All;\"\n */\n\n#ifndef ALLVARS_H\n#define ALLVARS_H\n\n#include <cstdio>\n#include <cstdlib>\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <cmath>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <map>\n#include <getopt.h>\n#include <sys/stat.h>\n#include <sys/timeb.h>\n\n#include <gsl/gsl_heapsort.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_roots.h>\n\n\n///\\name Include for NBodyFramework library.\n//@{\n///nbody code\n#include <NBody.h>\n///Math code\n#include <NBodyMath.h>\n///Binary KD-Tree code\n#include <KDTree.h>\n///Extra routines that analyze a distribution of particles\n#include <Analysis.h>\n//@}\n\n// ///\\name for checking the endian of floats\n//#include <endianutils.h>\n\n///if using OpenMP API\n#ifdef USEOPENMP\n#include <omp.h>\n#include \"ompvar.h\"\n#endif\n\n///if using HDF API\n#ifdef USEHDF\n#include \"H5Cpp.h\"\n#ifndef H5_NO_NAMESPACE\nusing namespace H5;\n#endif\n#endif\n\n///if using ADIOS API\n#ifdef USEADIOS\n#include \"adios.h\"\n#endif\n\n//#include \"swiftinterface.h\"\n//\n//using namespace Swift;\nusing namespace std;\nusing namespace Math;\nusing namespace NBody;\n\n//-- Structures and external variables\n\n/// \\defgroup PARTTYPES Particle types\n//@{\n#define  GASTYPE 0\n#define  DARKTYPE 1\n#define  DARK2TYPE 2\n#define  DARK3TYPE 3\n#define  STARTYPE 4\n#define  BHTYPE 5\n#define  WINDTYPE 6\n#define  NPARTTYPES 7\n//number of baryon types +1, to store all baryons\n#define  NBARYONTYPES 5\n//@}\n\n/// \\defgroup SEARCHTYPES Specify particle type to be searched, all, dm only, separate\n//@{\n#define  PSTALL 1\n#define  PSTDARK 2\n#define  PSTSTAR 3\n#define  PSTGAS 4\n#define  PSTBH 5\n#define  PSTNOBH 6\n//@}\n\n/// \\defgroup STRUCTURETYPES Specific structure type, allow for other types beside HALO\n//@{\n/// \\todo note that here I have set background group type to a halo structure type but that can be changed\n#define HALOSTYPE 10\n#define HALOCORESTYPE 5\n#define WALLSTYPE 1\n#define VOIDSTYPE 2\n#define FILAMENTSTYPE 3\n#define BGTYPE 10\n#define GROUPNOPARENT -1\n#define FOF3DTYPE 7\n#define FOF3DGROUP -2\n//@}\n\n/// \\defgroup FOFTYPES FOF search types\n//@{\n//subsets made\n///call \\ref FOFStreamwithprob\n#define  FOFSTPROB 1\n///6D FOF search but only with outliers\n#define  FOF6DSUBSET 7\n///like \\ref FOFStreamwithprob search but search is limited to nearest physical neighbours\n#define  FOFSTPROBNN 9\n///like \\ref FOFStreamwithprob search but here linking length adjusted by velocity offset, smaller lengths for larger velocity offsets\n#define  FOFSTPROBLX 10\n///like \\ref FOFSTPROBLX but for NN search\n#define  FOFSTPROBNNLX 11\n///like \\ref FOFSTPROBNN but there is not linking length applied just use nearest neighbours\n#define  FOFSTPROBNNNODIST 12\n//for iterative method with FOFStreamwithprob\n//#define  FOFSTPROBIT 13\n#define  FOFSTPROBSCALEELL 13\n//#define  FOFSTPROBIT 13\n#define  FOFSTPROBSCALEELLNN 14\n//solely phase-space tensor core growth substructure search\n#define  FOF6DCORE 6\n\n///phase-space FOF but no subset produced\n#define  FOFSTNOSUBSET 2\n///no subsets made, just 6d (with each 6dfof search using 3d fof velocity dispersion,)\n#define  FOF6DADAPTIVE 3\n///6d fof but only use single velocity dispersion from largest 3d fof object\n#define  FOF6D 4\n///3d search\n#define  FOF3D 5\n///baryon 6D FOF search\n#define FOFBARYON6D 0\n///baryon phase tensor search\n#define FOFBARYONPHASETENSOR 1\n//@}\n\n/// \\defgroup INTERATIVESEARCHPARAMS for iterative subsubstructure search\n//@{\n/// this is minimum particle number size for a subsearch to proceed whereby substructure split up into CELLSPLITNUM new cells\n#define  MINCELLSIZE 100\n#define  CELLSPLITNUM 8\n#define  MINSUBSIZE MINCELLSIZE*CELLSPLITNUM\n#define  MAXSUBLEVEL 8\n/// maximum fraction a cell can take of a halo\n#define  MAXCELLFRACTION 0.1\n//@}\n\n///\\defgroup GRIDTYPES Type of Grid structures\n//@{\n#define  PHYSENGRID 1\n#define  PHASEENGRID 2\n#define  PHYSGRID 3\n//@}\n\n/// \\name Max number of neighbouring cells used in interpolation of background velocity field.\n//@{\n\n//if cells were cubes this would be all the neighbours that full enclose the cube, 6 faces+20 diagonals\n//using daganoals may not be ideal. Furthermore, code using adaptive grid that if effectively produces\n//cell that are rectangular prisms. Furthermore, not all cells will share a boundary with another cell.\n//So just consider \"faces\".\n#define MAXNGRID 6\n\n//@}\n\n///\\defgroup INPUTTYPES defining types of input\n//@{\n#define  NUMINPUTS 5\n#define  IOGADGET 1\n#define  IOHDF 2\n#define  IOTIPSY 3\n#define  IORAMSES 4\n#define  IONCHILADA 5\n//@}\n\n\n///\\defgroup OUTPUTTYPES defining format types of output\n//@{\n#define OUTASCII 0\n#define OUTBINARY 1\n#define OUTHDF 2\n#define OUTADIOS 3\n//@}\n\n/// \\name For Unbinding\n//@{\n\n///number below which just use PP calculation for potential, which occurs roughly at when n~2*log(n) (from scaling of n^2 vs n ln(n) for PP vs tree and factor of 2 is\n///for extra overhead in producing tree. For reasonable values of n (>100) this occurs at ~100. Here to account for extra memory need for tree, we use n=3*log(n) or 150\n#define UNBINDNUM 150\n///when unbinding check to see if system is bound and least bound particle is also bound\n#define USYSANDPART 0\n///when unbinding check to see if least bound particle is also bound\n#define UPART 1\n///use the bulk centre of mass velocity to define velocity reference frame when determining if particle bound\n#define CMVELREF 0\n///use the particle at potential minimum. Issues if too few particles used as particles will move in and out of deepest point of the potential well\n#define POTREF 1\n///use Centre-of-mass to caculate Properties\n#define PROPREFCM 0\n///use most bound particle to calculate properties\n#define PROPREFMBP 1\n///use minimum potential particle to calculat properties\n#define PROPREFMINPOT 2\n\n//@}\n\n/// \\name For Tree potential calculation\n//@{\n\n///leafflag indicating in tree-calculation of potential, reached a leaf node that does not satisfy mono-pole approx\n#define leafflag 1\n///split flag means node not used as subcells are searched\n#define splitflag -1\n///cellflag means a node that is not necessarily a leaf node can be approximated by mono-pole\n#define cellflag 0\n\n//@}\n\n/// \\defgroup OMPLIMS For determining whether loop contains enough for openm to be worthwhile.\n//@{\n#ifndef USEOPENMP\n#define ompsearchnum 50000\n#define ompunbindnum 1000\n#define ompperiodnum 50000\n#define omppropnum 50000\n#endif\n//@}\n\n/// \\defgroup PROPLIMS Particle limits for calculating properties\n//@{\n#define PROPNFWMINNUM 100\n#define PROPCMMINNUM 10\n#define PROPROTMINNUM 10\n#define PROPMORPHMINNUM 10\n//@}\n\n///\\name halo id modifers used with current snapshot value to make temporally unique halo identifiers\n#ifdef LONGINT\n#define HALOIDSNVAL 1000000000000L\n#else\n#define HALOIDSNVAL 1000000\n#endif\n\n///\\defgroup radial profile parameters\n//@{\n#define PROFILERNORMPHYS 0\n#define PROFILERNORMR200CRIT 1\n#define PROFILERBINTYPELOG 0\n//@}\n\n///\\defgroup GASPARAMS Useful constants for gas\n//@{\n///mass of helium relative to hydrogen\n#define M_HetoM_H 4.0026\n//@}\n\n\n/// Structure stores unbinding information\nstruct UnbindInfo\n{\n    ///\\name flag whether unbind groups, keep bg potential when unbinding, type of unbinding and reference frame\n    //@{\n    int unbindflag,bgpot,unbindtype,cmvelreftype;\n    //@}\n    ///boolean as to whether code calculate potentials or potentials are externally provided\n    bool icalculatepotential;\n    ///fraction of potential energy that kinetic energy is allowed to be and consider particle bound\n    Double_t Eratio;\n    ///minimum bound mass fraction\n    Double_t minEfrac;\n    ///when to recalculate kinetic energies if cmvel has changed enough\n    Double_t cmdelta;\n    ///maximum fraction of particles to remove when unbinding in one given unbinding step\n    Double_t maxunbindfrac;\n    ///Maximum fraction of particles that can be considered unbound before group removed entirely\n    Double_t maxunboundfracforiterativeunbind;\n    ///Max allowed unbound fraction to speed up unbinding\n    Double_t maxallowedunboundfrac;\n\n    ///minimum number of particles to use to calculate reference frame if using particles around deepest potential well as reference frame\n    Int_t Npotref;\n    ///fraction of number of particles to use to calculate reference frame if using particles around deepest potential well as reference frame\n    Double_t fracpotref;\n    ///\\name gravity and tree potential calculation;\n    //@{\n    int BucketSize;\n    Double_t TreeThetaOpen;\n    ///softening length\n    Double_t eps;\n    //@}\n    UnbindInfo(){\n        icalculatepotential=true;\n        unbindflag=0;\n        bgpot=1;\n        unbindtype=UPART;\n        cmvelreftype=CMVELREF;\n        cmdelta=0.02;\n        Eratio=1.0;\n        minEfrac=1.0;\n        BucketSize=8;\n        TreeThetaOpen=0.5;\n        eps=0.0;\n        Npotref=20;\n        fracpotref=1.0;\n        maxunbindfrac=0.5;\n        maxunboundfracforiterativeunbind=0.95;\n        maxallowedunboundfrac=0.025;\n    }\n};\n\n/// Structure stores information used when calculating bulk (sub)structure properties\n/// which is used in \\ref substructureproperties.cxx\nstruct PropInfo\n{\n    //interate till this much mass in contained in a spherical region to calculate cm quantities\n    Double_t cmfrac,cmadjustfac;\n\n    PropInfo(){\n        cmfrac=0.1;\n        cmadjustfac=0.7;\n    }\n};\n\n/* Structure to hold the location of a top-level cell. */\nstruct cell_loc {\n\n    /* Coordinates x,y,z */\n    double loc[3];\n\n};\n\n/// Options structure stores useful variables that have user determined values which are altered by \\ref GetArgs in \\ref ui.cxx\nstruct Options\n{\n    ///\\name filenames\n    //@{\n    char *fname,*outname,*smname,*pname,*gname;\n    char *ramsessnapname;\n    //@}\n    ///input format\n    int inputtype;\n    ///number of snapshots\n    int num_files,snum;\n    ///if parallel reading, number of files read in parallel\n    int nsnapread;\n    ///for output, specify the formats, ie. many separate files\n    int iseparatefiles;\n    ///for output specify the format HDF, binary or ascii \\ref OUTHDF, \\ref OUTBINARY, \\ref OUTASCII\n    int ibinaryout;\n    ///for extended output allowing extraction of particles\n    int iextendedoutput;\n    /// output extra fields in halo properties\n    int iextrahalooutput;\n    /// calculate and output extra gas fields\n    int iextragasoutput;\n    /// calculate and output extra star fields\n    int iextrastaroutput;\n    /// calculate and output extra bh fields\n    int iextrabhoutput;\n    /// calculate and output extra interloper fields\n    int iextrainterloperoutput;\n    /// calculate subind like properties\n    int isubfindproperties;\n    ///for output, produce subfind like format\n    int isubfindoutput;\n\n    ///disable particle id related output like fof.grp or catalog_group data. Useful if just want halo properties\n    ///and not interested in tracking. Code writes halo properties catalog and exits.\n    int inoidoutput;\n    ///return propery data in in comoving little h units instead of standard physical units\n    int icomoveunit;\n    /// input is a cosmological simulation so can use box sizes, cosmological parameters, etc to set scales\n    int icosmologicalin;\n    /// input buffer size when reading data\n    long int inputbufsize;\n    /// mpi paritcle buffer size when sending input particle information\n    long int mpiparticletotbufsize,mpiparticlebufsize;\n    /// mpi factor by which to multiple the memory allocated, ie: buffer region\n    /// to reduce likelihood of having to expand/allocate new memory\n    Double_t mpipartfac;\n\n    /// run FOF using OpenMP\n    int iopenmpfof;\n    /// size of openmp FOF region\n    int openmpfofsize;\n\n    ///\\name length,m,v,grav conversion units\n    //@{\n    Double_t lengthinputconversion, massinputconversion, energyinputconversion, velocityinputconversion;\n    Double_t SFRinputconversion, metallicityinputconversion, stellarageinputconversion;\n    int istellaragescalefactor, isfrisssfr;\n    Double_t G;\n    Double_t lengthtokpc, velocitytokms, masstosolarmass, energyperunitmass, timetoseconds;\n    Double_t SFRtosolarmassperyear, stellaragetoyrs, metallicitytosolar;\n    //@}\n    ///period (comove)\n    Double_t p;\n    ///\\name scale factor, Hubunit, h, cosmology, virial density. These are used if linking lengths are scaled or trying to define virlevel using the cosmology\n    //@{\n    Double_t a,H,h;\n    Double_t Omega_m, Omega_b, Omega_cdm, Omega_Lambda, Omega_k, Omega_r, Omega_nu, Omega_de, w_de;\n    Double_t rhocrit, rhobg, virlevel, virBN98;\n    int comove;\n    /// to store the internal code unit to kpc and the distance^2 of 30 kpc, and 50 kpc\n    Double_t lengthtokpc30pow2, lengthtokpc50pow2;\n    //@}\n\n    ///to store number of each particle types so that if only searching one particle type, assumes order of gas, dark (halo, disk,bulge), star, special or sink for pfof tipsy style output\n    Int_t numpart[NPARTTYPES];\n\n    ///\\name parameters that control the local and average volumes used to calculate the local velocity density and the mean field, also the size of the leafnode in the kd-tree used when searching the tree for fof neighbours\n    //@{\n    int iLocalVelDenApproxCalcFlag;\n    int Nvel, Nsearch, Bsize;\n    Int_t Ncell;\n    Double_t Ncellfac;\n    //@}\n    ///minimum group size\n    int MinSize;\n    ///allows for field halos to have a different minimum size\n    int HaloMinSize;\n    ///Significance parameter for groups\n    Double_t siglevel;\n\n    ///whether to search for substructures at all\n    int iSubSearch;\n    ///type of search\n    int foftype,fofbgtype;\n    ///grid type, physical, physical+entropy splitting criterion, phase+entropy splitting criterion. Note that this parameter should not be changed from the default value\n    int gridtype;\n    ///flag indicating search all particle types or just dark matter\n    int partsearchtype;\n    ///flag indicating a separate baryonic search is run, looking for all particles that are associated in phase-space\n    ///with dark matter particles that belong to a structure\n    int iBaryonSearch;\n    /// FOF search for baryons\n    int ifofbaryonsearch;\n    ///flag indicating if move to CM frame for substructure search\n    int icmrefadjust;\n    /// flag indicating if CM is interated shrinking spheres\n    int iIterateCM;\n    /// flag to sort output particle lists by binding energy (or potential if not on)\n    int iSortByBindingEnergy;\n    /// what reference position to use when calculating Properties\n    int iPropertyReferencePosition;\n    /// what particle type is used to define reference position\n    int ParticleTypeForRefenceFrame;\n\n\n    ///threshold on particle ELL value, normalized logarithmic distance from predicted maxwellian velocity density.\n    Double_t ellthreshold;\n    ///\\name fofstream search parameters\n    //@{\n    Double_t thetaopen,Vratio,ellphys;\n    //@}\n    ///fof6d search parameters\n    Double_t ellvel;\n    ///scaling for ellphs and ellvel\n    Double_t ellxscale,ellvscale;\n    ///flag to use iterative method\n    int iiterflag;\n    ///\\name factors used to multiply the input values to find initial candidate particles and for mergering groups in interative search\n    //@{\n    Double_t ellfac,ellxfac,vfac,thetafac,nminfac;\n    Double_t fmerge;\n    //@}\n    ///factors to alter halo linking length search (related to substructure search)\n    //@{\n    Double_t ellhalophysfac,ellhalovelfac;\n    //@}\n    ///\\name parameters related to 3DFOF search & subsequent 6DFOF search\n    //@{\n    Double_t ellhalo3dxfac;\n    Double_t ellhalo6dxfac;\n    Double_t ellhalo6dvfac;\n    int iKeepFOF;\n    Int_t num3dfof;\n    //@}\n    //@{\n    ///\\name factors used to check for halo mergers, large background substructures and store the velocity scale when searching for associated baryon substructures\n    //@{\n    Double_t HaloMergerSize,HaloMergerRatio,HaloSigmaV,HaloVelDispScale,HaloLocalSigmaV;\n    Double_t fmergebg;\n    //@}\n    ///flag indicating a single halo is passed or must run search for FOF haloes\n    Int_t iSingleHalo;\n    ///flag indicating haloes are to be check for self-boundness after being searched for substructure\n    Int_t iBoundHalos;\n    /// store denv ratio statistics\n    //@{\n    int idenvflag;\n    Double_t denvstat[3];\n    //@}\n    ///verbose output flag\n    int iverbose;\n    ///whether or not to write a fof.grp tipsy like array file\n    int iwritefof;\n    ///whether mass properties for field objects are inclusive\n    int iInclusiveHalo;\n\n    ///if no mass value stored then store global mass value\n    Double_t MassValue;\n\n    ///structure that contains variables for unbinding\n    UnbindInfo uinfo;\n    ///structure that contains variables for property calculation\n    PropInfo pinfo;\n\n    ///effective resolution for zoom simulations\n    Int_t Neff;\n\n    ///if during substructure search, want to also search for larger substructures\n    //using the more time consuming local velocity calculations (partly in lieu of using the faster core search)\n    int iLargerCellSearch;\n\n    ///\\name extra stuff for halo merger check and identification of multiple halo core and flag for fully adaptive linking length using number density of candidate objects\n    //@{\n    /// run halo core search for mergers\n    int iHaloCoreSearch;\n    ///maximum sublevel at which we search for phase-space cores\n    int maxnlevelcoresearch;\n    ///parameters associated with phase-space search for cores of mergers\n    Double_t halocorexfac, halocorevfac, halocorenfac, halocoresigmafac;\n    ///x and v space linking lengths calculated for each object\n    int iAdaptiveCoreLinking;\n    ///use phase-space tensor core assignment\n    int iPhaseCoreGrowth;\n    ///number of iterations\n    int halocorenumloops;\n    ///factor by which one multiples the configuration space dispersion when looping for cores\n    Double_t halocorexfaciter;\n    ///factor by which one multiples the velocity space dispersion when looping for cores\n    Double_t halocorevfaciter;\n    ///factor by which one multiples the min num when looping for cores\n    Double_t halocorenumfaciter;\n    ///factor by which a core must be seperated from main core in phase-space in sigma units\n    Double_t halocorephasedistsig;\n    ///factor by which a substructure s must be closer than in phase-space to merger with another substructure in sigma units\n    Double_t coresubmergemindist;\n    //@}\n    ///for storing a snapshot value to make halo ids unique across snapshots\n    long long snapshotvalue;\n\n    ///\\name for reading gadget info with lots of extra sph, star and bh blocks\n    //@{\n    int gnsphblocks,gnstarblocks,gnbhblocks;\n    //@}\n\n    /// \\name Extra HDF flags indicating the existence of extra baryonic/dm particle types\n    //@{\n    /// input naming convention\n    int ihdfnameconvention;\n    /// input contains dm particles\n    int iusedmparticles;\n    /// input contains hydro/gas particles\n    int iusegasparticles;\n    /// input contains star particles\n    int iusestarparticles;\n    /// input contains black hole/sink particles\n    int iusesinkparticles;\n    /// input contains wind particles\n    int iusewindparticles;\n    /// input contains tracer particles\n    int iusetracerparticles;\n    /// input contains extra dark type particles\n    int iuseextradarkparticles;\n    //@}\n\n    /// if want full spherical overdensity, factor by which size is multiplied to get\n    ///bucket of particles\n    Double_t SphericalOverdensitySeachFac;\n    ///minimum enclosed mass on which to base SO calculations, <1\n    Double_t SphericalOverdensityMinHaloFac;\n    ///if want to the particle IDs that are within the SO overdensity of a halo\n    int iSphericalOverdensityPartList;\n    /// \\name Extra variables to store information useful in zoom simluations\n    //@{\n    /// store the lowest dark matter particle mass\n    Double_t zoomlowmassdm;\n    //@}\n\n    ///\\name extra runtime flags\n    //@{\n    ///scale lengths. Useful if searching single halo system and which to automatically scale linking lengths\n    int iScaleLengths;\n\n    /// \\name Swift/Metis related quantitites\n    //@{\n    //Swift::siminfo swiftsiminfo;\n\n    double spacedimension[3];\n\n    /* Number of top-level cells. */\n    int numcells;\n\n    /* Number of top-level cells in each dimension. */\n    int numcellsperdim;\n\n    /* Locations of top-level cells. */\n    cell_loc *cellloc;\n\n    /*! Top-level cell width. */\n    double cellwidth[3];\n\n    /*! Inverse of the top-level cell width. */\n    double icellwidth[3];\n\n    /*! Holds the node ID of each top-level cell. */\n    const int *cellnodeids;\n    //@}\n\n    /// \\name options related to calculation of aperture/profile\n    //@{\n    int iaperturecalc;\n    int aperturenum,apertureprojnum;\n    vector<Double_t> aperture_values_kpc;\n    vector<string> aperture_names_kpc;\n    vector<Double_t> aperture_proj_values_kpc;\n    vector<string> aperture_proj_names_kpc;\n    int iprofilecalc, iprofilenorm, iprofilebintype;\n    int profilenbins;\n    int iprofilecumulative;\n    string profileradnormstring;\n    vector<Double_t> profile_bin_edges;\n    //@}\n\n    /// \\name options related to calculation of arbitrary overdensities masses, radii, angular momentum\n    //@{\n    int SOnum;\n    vector<Double_t> SOthresholds_values_crit;\n    vector<string> SOthresholds_names_crit;\n    //@}\n\n    /// \\name options related to calculating star forming gas quantities\n    //@{\n    Double_t gas_sfr_threshold;\n    //@}\n\n    Options()\n    {\n        lengthinputconversion = 1.0;\n        massinputconversion = 1.0;\n        velocityinputconversion = 1.0;\n        SFRinputconversion = 1.0;\n        metallicityinputconversion = 1.0;\n        energyinputconversion = 1.0;\n        stellarageinputconversion =1.0;\n        istellaragescalefactor = 1;\n        isfrisssfr = 0;\n\n        G = 1.0;\n        p = 0.0;\n\n        a = 1.0;\n        H = 0.;\n        h = 1.0;\n        Omega_m = 1.0;\n        Omega_Lambda = 0.0;\n        Omega_b = 0.0;\n        Omega_cdm = Omega_m;\n        Omega_k = 0;\n        Omega_r = 0.0;\n        Omega_nu = 0.0;\n        Omega_de = 0.0;\n        w_de = -1.0;\n        rhobg = 1.0;\n        virlevel = -1;\n        comove=0;\n        H=100.0;//value of Hubble flow in h 1 km/s/Mpc\n        MassValue=1.0;\n\n        inputtype=IOGADGET;\n\n        num_files=1;\n        nsnapread=1;\n\n        fname=outname=smname=pname=gname=outname=NULL;\n\n        Bsize=32;\n        Nvel=32;\n        Nsearch=256;\n        Ncellfac=0.01;\n\n        iSubSearch=1;\n        partsearchtype=PSTALL;\n        for (int i=0;i<NPARTTYPES;i++)numpart[i]=0;\n        foftype=FOFSTPROB;\n        gridtype=PHYSENGRID;\n        fofbgtype=FOF6D;\n        idenvflag=0;\n        iBaryonSearch=0;\n        icmrefadjust=1;\n        iIterateCM = 1;\n        iLocalVelDenApproxCalcFlag = 1 ;\n\n        Neff=-1;\n\n\n        ellthreshold=1.5;\n        thetaopen=0.05;\n        Vratio=1.25;\n        ellphys=0.2;\n        MinSize=20;\n        HaloMinSize=-1;\n        siglevel=2.0;\n        ellvel=0.5;\n        ellxscale=ellvscale=1.0;\n        ellhalophysfac=ellhalovelfac=1.0;\n        ellhalo6dxfac=1.0;\n        ellhalo6dvfac=1.25;\n        ellhalo3dxfac=-1.0;\n\n        iiterflag=0;\n        ellfac=2.5;\n        ellxfac=3.0;\n        vfac=1.0;\n        thetafac=1.0;\n        nminfac=0.5;\n        fmerge=0.25;\n\n        HaloMergerSize=10000;\n        HaloMergerRatio=0.2;\n        HaloVelDispScale=0;\n        fmergebg=0.5;\n        iSingleHalo=0;\n        iBoundHalos=0;\n        iInclusiveHalo=0;\n        iKeepFOF=0;\n        iSortByBindingEnergy=1;\n        iPropertyReferencePosition=PROPREFCM;\n        ParticleTypeForRefenceFrame=-1;\n\n        iLargerCellSearch=0;\n\n        iHaloCoreSearch=0;\n        iAdaptiveCoreLinking=0;\n        iPhaseCoreGrowth=1;\n        maxnlevelcoresearch=5;\n        halocorexfac=0.5;\n        halocorevfac=2.0;\n        halocorenfac=0.1;\n        halocoresigmafac=2.0;\n        halocorenumloops=3;\n        halocorexfaciter=0.75;\n        halocorevfaciter=0.75;\n        halocorenumfaciter=1.0;\n        halocorephasedistsig=2.0;\n        coresubmergemindist=0.0;\n\n        iverbose=0;\n        iwritefof=0;\n        iseparatefiles=0;\n        ibinaryout=0;\n        iextendedoutput=0;\n        isubfindoutput=0;\n        inoidoutput=0;\n        icomoveunit=0;\n        icosmologicalin=1;\n\n        iextrahalooutput=0;\n        iextragasoutput=0;\n        iextrastaroutput=0;\n        iextrainterloperoutput=0;\n        isubfindproperties=0;\n\n        iusedmparticles=1;\n        iusegasparticles=1;\n        iusestarparticles=1;\n        iusesinkparticles=1;\n        iusewindparticles=0;\n        iusetracerparticles=0;\n#ifdef HIGHRES\n        iuseextradarkparticles=1;\n#else\n        iuseextradarkparticles=0;\n#endif\n\n        snapshotvalue=0;\n\n        gnsphblocks=4;\n        gnstarblocks=2;\n        gnbhblocks=2;\n\n        iScaleLengths=0;\n\n        inputbufsize=100000;\n\n        mpiparticletotbufsize=-1;\n        mpiparticlebufsize=-1;\n\n        lengthtokpc=-1.0;\n        velocitytokms=-1.0;\n        masstosolarmass=-1.0;\n#if defined(GASON) || defined(STARON) || defined(BHON)\n        SFRtosolarmassperyear=-1.0;\n        stellaragetoyrs=-1.0;\n        metallicitytosolar=-1.0;\n#endif\n\n\n        lengthtokpc30pow2=30.0*30.0;\n        lengthtokpc50pow2=50.0*50.0;\n\n        SphericalOverdensitySeachFac=2.5;\n        SphericalOverdensityMinHaloFac=0.05;\n        iSphericalOverdensityPartList=0;\n\n        mpipartfac=0.1;\n#if USEHDF\n        ihdfnameconvention=-1;\n#endif\n        iaperturecalc=0;\n        aperturenum=0;\n        apertureprojnum=0;\n        SOnum=0;\n\n        iprofilecalc=0;\n        iprofilenorm=PROFILERNORMR200CRIT;\n        iprofilebintype=PROFILERBINTYPELOG;\n        iprofilecumulative=0;\n        profilenbins=0;\n#ifdef USEOPENMP\n        iopenmpfof = 1;\n        openmpfofsize = ompfofsearchnum;\n#endif\n    }\n};\n\nstruct ConfigInfo{\n    //list the name of the info\n    vector<string> nameinfo;\n    //vector<float> datainfo;\n    vector<string> datainfo;\n    //vector<int> datatype;\n    ConfigInfo(Options &opt){\n        //if compiler is super old and does not have at least std 11 implementation to_string does not exist\n#ifndef OLDCCOMPILER\n        //general search operations\n        nameinfo.push_back(\"Particle_search_type\");\n        datainfo.push_back(to_string(opt.partsearchtype));\n        nameinfo.push_back(\"FoF_search_type\");\n        datainfo.push_back(to_string(opt.foftype));\n        nameinfo.push_back(\"FoF_Field_search_type\");\n        datainfo.push_back(to_string(opt.fofbgtype));\n        nameinfo.push_back(\"Search_for_substructure\");\n        datainfo.push_back(to_string(opt.iSubSearch));\n        nameinfo.push_back(\"Keep_FOF\");\n        datainfo.push_back(to_string(opt.iKeepFOF));\n        nameinfo.push_back(\"Iterative_searchflag\");\n        datainfo.push_back(to_string(opt.iiterflag));\n        nameinfo.push_back(\"Unbind_flag\");\n        datainfo.push_back(to_string(opt.uinfo.unbindflag));\n        nameinfo.push_back(\"Baryon_searchflag\");\n        datainfo.push_back(to_string(opt.iBaryonSearch));\n        nameinfo.push_back(\"CMrefadjustsubsearch_flag\");\n        datainfo.push_back(to_string(opt.icmrefadjust));\n        nameinfo.push_back(\"Halo_core_search\");\n        datainfo.push_back(to_string(opt.iHaloCoreSearch));\n        nameinfo.push_back(\"Use_adaptive_core_search\");\n        datainfo.push_back(to_string(opt.iAdaptiveCoreLinking));\n        nameinfo.push_back(\"Use_phase_tensor_core_growth\");\n        datainfo.push_back(to_string(opt.iPhaseCoreGrowth));\n\n        //local field parameters\n        nameinfo.push_back(\"Cell_fraction\");\n        datainfo.push_back(to_string(opt.Ncellfac));\n        nameinfo.push_back(\"Grid_type\");\n        datainfo.push_back(to_string(opt.gridtype));\n        nameinfo.push_back(\"Nsearch_velocity\");\n        datainfo.push_back(to_string(opt.Nvel));\n        nameinfo.push_back(\"Nsearch_physical\");\n        datainfo.push_back(to_string(opt.Nsearch));\n\n        //substructure search parameters\n        nameinfo.push_back(\"Outlier_threshold\");\n        datainfo.push_back(to_string(opt.ellthreshold));\n        nameinfo.push_back(\"Significance_level\");\n        datainfo.push_back(to_string(opt.siglevel));\n        nameinfo.push_back(\"Velocity_ratio\");\n        datainfo.push_back(to_string(opt.Vratio));\n        nameinfo.push_back(\"Velocity_opening_angle\");\n        datainfo.push_back(to_string(opt.thetaopen));\n        ///\\todo this configuration option will be deprecated. Replaced by Substructure_physical_linking_length\n        //nameinfo.push_back(\"Physical_linking_length\");\n        //datainfo.push_back(to_string(opt.ellphys));\n        nameinfo.push_back(\"Substructure_physical_linking_length\");\n        datainfo.push_back(to_string(opt.ellphys));\n        nameinfo.push_back(\"Velocity_linking_length\");\n        datainfo.push_back(to_string(opt.ellvel));\n        nameinfo.push_back(\"Minimum_size\");\n        datainfo.push_back(to_string(opt.MinSize));\n\n        //field object specific searches\n        nameinfo.push_back(\"Minimum_halo_size\");\n        datainfo.push_back(to_string(opt.HaloMinSize));\n        ///\\todo this configuration option will be deprecated. Replaced by Halo_3D_physical_linking_length\n        //nameinfo.push_back(\"Halo_linking_length_factor\");\n        //datainfo.push_back(to_string(opt.ellhalophysfac));\n        nameinfo.push_back(\"Halo_3D_linking_length\");\n        datainfo.push_back(to_string(opt.ellhalo3dxfac));\n        nameinfo.push_back(\"Halo_velocity_linking_length_factor\");\n        datainfo.push_back(to_string(opt.ellhalovelfac));\n\n        //specific to 6DFOF field search\n        nameinfo.push_back(\"Halo_6D_linking_length_factor\");\n        datainfo.push_back(to_string(opt.ellhalo6dxfac));\n        nameinfo.push_back(\"Halo_6D_vel_linking_length_factor\");\n        datainfo.push_back(to_string(opt.ellhalo6dvfac));\n\n        //specific search for 6d fof core searches\n        nameinfo.push_back(\"Halo_core_ellx_fac\");\n        datainfo.push_back(to_string(opt.halocorexfac));\n        nameinfo.push_back(\"Halo_core_ellv_fac\");\n        datainfo.push_back(to_string(opt.halocorevfac));\n        nameinfo.push_back(\"Halo_core_ncellfac\");\n        datainfo.push_back(to_string(opt.halocorenfac));\n        nameinfo.push_back(\"Halo_core_adaptive_sigma_fac\");\n        datainfo.push_back(to_string(opt.halocoresigmafac));\n        nameinfo.push_back(\"Halo_core_num_loops\");\n        datainfo.push_back(to_string(opt.halocorenumloops));\n        nameinfo.push_back(\"Halo_core_loop_ellx_fac\");\n        datainfo.push_back(to_string(opt.halocorexfaciter));\n        nameinfo.push_back(\"Halo_core_loop_ellv_fac\");\n        datainfo.push_back(to_string(opt.halocorevfaciter));\n        nameinfo.push_back(\"Halo_core_loop_elln_fac\");\n        datainfo.push_back(to_string(opt.halocorenumfaciter));\n        nameinfo.push_back(\"Halo_core_phase_significance\");\n        datainfo.push_back(to_string(opt.halocorephasedistsig));\n\n\n        //for changing factors used in iterative search\n        nameinfo.push_back(\"Iterative_threshold_factor\");\n        datainfo.push_back(to_string(opt.ellfac));\n        nameinfo.push_back(\"Iterative_linking_length_factor\");\n        datainfo.push_back(to_string(opt.ellxfac));\n        nameinfo.push_back(\"Iterative_Vratio_factor\");\n        datainfo.push_back(to_string(opt.vfac));\n        nameinfo.push_back(\"Iterative_ThetaOp_factor\");\n        datainfo.push_back(to_string(opt.thetafac));\n\n        //for changing effective resolution when rescaling linking lengh\n        nameinfo.push_back(\"Effective_resolution\");\n        datainfo.push_back(to_string(opt.Neff));\n\n        //for changing effective resolution when rescaling linking lengh\n        nameinfo.push_back(\"Singlehalo_search\");\n        datainfo.push_back(to_string(opt.iSingleHalo));\n\n        //units, cosmology\n        nameinfo.push_back(\"Length_unit\");\n        datainfo.push_back(to_string(opt.lengthinputconversion));\n        nameinfo.push_back(\"Velocity_unit\");\n        datainfo.push_back(to_string(opt.velocityinputconversion));\n        nameinfo.push_back(\"Mass_unit\");\n        datainfo.push_back(to_string(opt.massinputconversion));\n        nameinfo.push_back(\"Length_input_unit_conversion_to_output_unit\");\n        datainfo.push_back(to_string(opt.lengthinputconversion));\n        nameinfo.push_back(\"Velocity_input_unit_conversion_to_output_unit\");\n        datainfo.push_back(to_string(opt.velocityinputconversion));\n        nameinfo.push_back(\"Mass_input_unit_conversion_to_output_unit\");\n        datainfo.push_back(to_string(opt.massinputconversion));\n        nameinfo.push_back(\"Star_formation_rate_input_unit_conversion_to_output_unit\");\n        datainfo.push_back(to_string(opt.SFRinputconversion));\n        nameinfo.push_back(\"Metallicity_input_unit_conversion_to_output_unit\");\n        datainfo.push_back(to_string(opt.metallicityinputconversion));\n        nameinfo.push_back(\"Stellar_age_input_is_cosmological_scalefactor\");\n        datainfo.push_back(to_string(opt.istellaragescalefactor));\n        nameinfo.push_back(\"Hubble_unit\");\n        datainfo.push_back(to_string(opt.H));\n        nameinfo.push_back(\"Gravity\");\n        datainfo.push_back(to_string(opt.G));\n        nameinfo.push_back(\"Mass_value\");\n        datainfo.push_back(to_string(opt.MassValue));\n        nameinfo.push_back(\"Length_unit_to_kpc\");\n        datainfo.push_back(to_string(opt.lengthtokpc));\n        nameinfo.push_back(\"Velocity_to_kms\");\n        datainfo.push_back(to_string(opt.velocitytokms));\n        nameinfo.push_back(\"Mass_to_solarmass\");\n        datainfo.push_back(to_string(opt.masstosolarmass));\n        nameinfo.push_back(\"Star_formation_rate_to_solarmassperyear\");\n        datainfo.push_back(to_string(opt.SFRtosolarmassperyear));\n        nameinfo.push_back(\"Metallicity_to_solarmetallicity\");\n        datainfo.push_back(to_string(opt.metallicitytosolar));\n        nameinfo.push_back(\"Stellar_age_to_yr\");\n        datainfo.push_back(to_string(opt.stellaragetoyrs));\n\n        nameinfo.push_back(\"Period\");\n        datainfo.push_back(to_string(opt.p));\n        nameinfo.push_back(\"Scale_factor\");\n        datainfo.push_back(to_string(opt.a));\n        nameinfo.push_back(\"h_val\");\n        datainfo.push_back(to_string(opt.h));\n        nameinfo.push_back(\"Omega_m\");\n        datainfo.push_back(to_string(opt.Omega_m));\n        nameinfo.push_back(\"Omega_Lambda\");\n        datainfo.push_back(to_string(opt.Omega_Lambda));\n        nameinfo.push_back(\"Critical_density\");\n        datainfo.push_back(to_string(opt.rhobg));\n        nameinfo.push_back(\"Virial_density\");\n        datainfo.push_back(to_string(opt.virlevel));\n        nameinfo.push_back(\"Omega_cdm\");\n        datainfo.push_back(to_string(opt.Omega_cdm));\n        nameinfo.push_back(\"Omega_b\");\n        datainfo.push_back(to_string(opt.Omega_b));\n        nameinfo.push_back(\"Omega_r\");\n        datainfo.push_back(to_string(opt.Omega_r));\n        nameinfo.push_back(\"Omega_nu\");\n        datainfo.push_back(to_string(opt.Omega_nu));\n        nameinfo.push_back(\"Omega_DE\");\n        datainfo.push_back(to_string(opt.Omega_de));\n        nameinfo.push_back(\"w_of_DE\");\n        datainfo.push_back(to_string(opt.w_de));\n\n        //unbinding\n        nameinfo.push_back(\"Softening_length\");\n        datainfo.push_back(to_string(opt.uinfo.eps));\n        nameinfo.push_back(\"Allowed_kinetic_potential_ratio\");\n        datainfo.push_back(to_string(opt.uinfo.Eratio));\n        nameinfo.push_back(\"Min_bound_mass_frac\");\n        datainfo.push_back(to_string(opt.uinfo.minEfrac));\n        nameinfo.push_back(\"Bound_halos\");\n        datainfo.push_back(to_string(opt.iBoundHalos));\n        nameinfo.push_back(\"Keep_background_potential\");\n        datainfo.push_back(to_string(opt.uinfo.bgpot));\n        nameinfo.push_back(\"Kinetic_reference_frame_type\");\n        datainfo.push_back(to_string(opt.uinfo.cmvelreftype));\n        nameinfo.push_back(\"Min_npot_ref\");\n        datainfo.push_back(to_string(opt.uinfo.Npotref));\n        nameinfo.push_back(\"Frac_pot_ref\");\n        datainfo.push_back(to_string(opt.uinfo.fracpotref));\n        nameinfo.push_back(\"Unbinding_type\");\n        datainfo.push_back(to_string(opt.uinfo.unbindtype));\n\n        //property related\n        nameinfo.push_back(\"Inclusive_halo_masses\");\n        datainfo.push_back(to_string(opt.iInclusiveHalo));\n        nameinfo.push_back(\"Extensive_halo_properties_output\");\n        datainfo.push_back(to_string(opt.iextrahalooutput));\n        nameinfo.push_back(\"Extensive_gas_properties_output\");\n        datainfo.push_back(to_string(opt.iextragasoutput));\n        nameinfo.push_back(\"Iterate_cm_flag\");\n        datainfo.push_back(to_string(opt.iIterateCM));\n        nameinfo.push_back(\"Sort_by_binding_energy\");\n        datainfo.push_back(to_string(opt.iSortByBindingEnergy));\n\n        //other options\n        nameinfo.push_back(\"Verbose\");\n        datainfo.push_back(to_string(opt.iverbose));\n        nameinfo.push_back(\"Write_group_array_file\");\n        datainfo.push_back(to_string(opt.iwritefof));\n        nameinfo.push_back(\"Snapshot_value\");\n        datainfo.push_back(to_string(opt.snapshotvalue));\n\n        //io related\n        nameinfo.push_back(\"Cosmological_input\");\n        datainfo.push_back(to_string(opt.icosmologicalin));\n        nameinfo.push_back(\"Input_chunk_size\");\n        datainfo.push_back(to_string(opt.inputbufsize));\n        nameinfo.push_back(\"MPI_particle_total_buf_size\");\n        datainfo.push_back(to_string(opt.mpiparticletotbufsize));\n        nameinfo.push_back(\"Separate_output_files\");\n        datainfo.push_back(to_string(opt.iseparatefiles));\n        nameinfo.push_back(\"Binary_output\");\n        datainfo.push_back(to_string(opt.ibinaryout));\n        nameinfo.push_back(\"Comoving_units\");\n        datainfo.push_back(to_string(opt.icomoveunit));\n        nameinfo.push_back(\"Extended_output\");\n        datainfo.push_back(to_string(opt.iextendedoutput));\n\n        //gadget io related to extra info for sph, stars, bhs,\n        nameinfo.push_back(\"NSPH_extra_blocks\");\n        datainfo.push_back(to_string(opt.gnsphblocks));\n        nameinfo.push_back(\"NStar_extra_blocks\");\n        datainfo.push_back(to_string(opt.gnstarblocks));\n        nameinfo.push_back(\"NBH_extra_blocks\");\n        datainfo.push_back(to_string(opt.gnbhblocks));\n\n        //mpi related configuration\n        nameinfo.push_back(\"MPI_part_allocation_fac\");\n        datainfo.push_back(to_string(opt.mpiparticletotbufsize));\n#endif\n    }\n};\n\nstruct SimInfo{\n    //list the name of the info\n    vector<string> nameinfo;\n    vector<string> datainfo;\n\n    SimInfo(Options &opt){\n        //if compiler is super old and does not have at least std 11 implementation to_string does not exist\n#ifndef OLDCCOMPILER\n        nameinfo.push_back(\"Cosmological_Sim\");\n        datainfo.push_back(to_string(opt.icosmologicalin));\n        if (opt.icosmologicalin) {\n            nameinfo.push_back(\"ScaleFactor\");\n            datainfo.push_back(to_string(opt.a));\n            nameinfo.push_back(\"h_val\");\n            datainfo.push_back(to_string(opt.h));\n            nameinfo.push_back(\"Omega_m\");\n            datainfo.push_back(to_string(opt.Omega_m));\n            nameinfo.push_back(\"Omega_Lambda\");\n            datainfo.push_back(to_string(opt.Omega_Lambda));\n            nameinfo.push_back(\"Omega_cdm\");\n            datainfo.push_back(to_string(opt.Omega_cdm));\n            nameinfo.push_back(\"Omega_b\");\n            datainfo.push_back(to_string(opt.Omega_b));\n            nameinfo.push_back(\"w_of_DE\");\n            datainfo.push_back(to_string(opt.w_de));\n            nameinfo.push_back(\"Period\");\n            datainfo.push_back(to_string(opt.p));\n            nameinfo.push_back(\"Hubble_unit\");\n            datainfo.push_back(to_string(opt.H));\n        }\n        else{\n            nameinfo.push_back(\"Time\");\n            datainfo.push_back(to_string(opt.a));\n            nameinfo.push_back(\"Period\");\n            datainfo.push_back(to_string(opt.p));\n        }\n\n        //units\n        nameinfo.push_back(\"Length_unit\");\n        datainfo.push_back(to_string(opt.lengthinputconversion));\n        nameinfo.push_back(\"Velocity_unit\");\n        datainfo.push_back(to_string(opt.velocityinputconversion));\n        nameinfo.push_back(\"Mass_unit\");\n        datainfo.push_back(to_string(opt.massinputconversion));\n        nameinfo.push_back(\"Gravity\");\n        datainfo.push_back(to_string(opt.G));\n#ifdef NOMASS\n        nameinfo.push_back(\"Mass_value\");\n        datainfo.push_back(to_string(opt.MassValue));\n#endif\n\n#endif\n    }\n};\n\n\nstruct UnitInfo{\n    //list the name of the info\n    vector<string> nameinfo;\n    vector<string> datainfo;\n\n    UnitInfo(Options &opt){\n        //if compiler is super old and does not have at least std 11 implementation to_string does not exist\n#ifndef OLDCCOMPILER\n        nameinfo.push_back(\"Cosmological_Sim\");\n        datainfo.push_back(to_string(opt.icosmologicalin));\n        nameinfo.push_back(\"Comoving_or_Physical\");\n        datainfo.push_back(to_string(opt.icomoveunit));\n        //units\n        nameinfo.push_back(\"Length_unit_to_kpc\");\n        datainfo.push_back(to_string(opt.lengthtokpc));\n        nameinfo.push_back(\"Velocity_unit_to_kms\");\n        datainfo.push_back(to_string(opt.velocitytokms));\n        nameinfo.push_back(\"Mass_unit_to_solarmass\");\n        datainfo.push_back(to_string(opt.masstosolarmass));\n#if defined(GASON) || defined(STARON) || defined(BHON)\n        nameinfo.push_back(\"Metallicity_unit_to_solar\");\n        datainfo.push_back(to_string(opt.metallicitytosolar));\n        nameinfo.push_back(\"SFR_unit_to_solarmassperyear\");\n        datainfo.push_back(to_string(opt.SFRtosolarmassperyear));\n        nameinfo.push_back(\"Stellar_age_unit_to_yr\");\n        datainfo.push_back(to_string(opt.stellaragetoyrs));\n#endif\n#endif\n    }\n};\n\n/// N-dim grid cell\nstruct GridCell\n{\n    int ndim;\n    Int_t gid;\n    //middle of cell, and boundaries of cell\n    Double_t xm[6], xbl[6],xbu[6];\n    //mass, radial size of in cell\n    Double_t mass, rsize;\n    //number of particles in cell\n    Int_t nparts,*nindex;\n    //neighbouring grid cells and distance from cell centers\n    Int_t nnidcells[MAXNGRID];\n    Double_t nndist[MAXNGRID];\n    Double_t den;\n    GridCell(int N=3){\n        ndim=N;\n        nparts=0;\n        den=0;\n    }\n    ~GridCell(){\n        if (nparts>0)delete nindex;\n    }\n};\n\n/*! structure stores bulk properties like\n    \\f$ m,\\ (x,y,z)_{\\rm cm},\\ (vx,vy,vz)_{\\rm cm},\\ V_{\\rm max},\\ R_{\\rm max}, \\f$\n    which is calculated in \\ref substructureproperties.cxx\n*/\nstruct PropData\n{\n    ///\\name order in structure hierarchy and number of subhaloes\n    //@{\n    long long haloid,hostid,directhostid, hostfofid;\n    Int_t numsubs;\n    //@}\n\n    ///\\name properties of total object including DM, gas, stars, bh, etc\n    //@{\n    ///number of particles\n    Int_t num;\n    ///number of particles in FOF envelop\n    Int_t gNFOF,gN6DFOF;\n    ///centre of mass\n    Coordinate gcm, gcmvel;\n    ///Position of most bound particle, and also of particle with min potential\n    Coordinate gposmbp, gvelmbp, gposminpot, gvelminpot;\n    ///\\name physical properties regarding mass, size\n    //@{\n    Double_t gmass,gsize,gMvir,gRvir,gRcm,gRmbp,gRminpot,gmaxvel,gRmaxvel,gMmaxvel,gRhalfmass,gMassTwiceRhalfmass;\n    Double_t gM200c,gR200c,gM200m,gR200m,gMFOF,gM6DFOF,gM500c,gR500c,gMBN98,gRBN98;\n    //to store exclusive masses of halo ignoring substructure\n    Double_t gMvir_excl,gRvir_excl,gM200c_excl,gR200c_excl,gM200m_excl,gR200m_excl,gMBN98_excl,gRBN98_excl;\n    //@}\n    ///\\name physical properties for shape/mass distribution\n    //@{\n    ///axis ratios\n    Double_t gq,gs;\n    ///eigenvector\n    Matrix geigvec;\n    //@}\n    ///\\name physical properties for velocity\n    //@{\n    ///velocity dispersion\n    Double_t gsigma_v;\n    ///dispersion tensor\n    Matrix gveldisp;\n    //@}\n    ///physical properties for dynamical state\n    Double_t Efrac,Pot,T;\n    ///physical properties for angular momentum\n    Coordinate gJ;\n    Coordinate gJ200m, gJ200c, gJBN98;\n    ///physical properties for angular momentum exclusive\n    Coordinate gJ200m_excl, gJ200c_excl, gJBN98_excl;\n    ///Keep track of position of least unbound particle and most bound particle pid and minimum potential\n    Int_t iunbound,ibound, iminpot;\n    ///Type of structure\n    int stype;\n    ///concentration (and related quantity used to calculate a concentration)\n    Double_t cNFW, VmaxVvir2;\n    ///Bullock & Peebles spin parameters\n    Double_t glambda_B,glambda_P;\n    ///measure of rotational support\n    Double_t Krot;\n    //@}\n\n    ///\\name halo properties within RVmax\n    //@{\n    Double_t RV_q,RV_s;\n    Matrix RV_eigvec;\n    Double_t RV_sigma_v;\n    Matrix RV_veldisp;\n    Coordinate RV_J;\n    Double_t RV_lambda_B,RV_lambda_P;\n    Double_t RV_Krot;\n    //@}\n\n    ///\\name radial profiles\n    //@{\n    vector<unsigned int> aperture_npart;\n    vector<float> aperture_mass;\n    vector<float> aperture_veldisp;\n    vector<float> aperture_vrdisp;\n    vector<float> aperture_rhalfmass;\n    vector<Coordinate> aperture_mass_proj;\n    vector<Coordinate> aperture_rhalfmass_proj;\n    vector<Coordinate> aperture_L;\n    vector<unsigned int> profile_npart;\n    vector<unsigned int> profile_npart_inclusive;\n    vector<float> profile_mass;\n    vector<float> profile_mass_inclusive;\n    vector<Coordinate> profile_L;\n    #if defined(GASON) || defined(STARON) || defined(BHON)\n    vector<unsigned int> aperture_npart_dm;\n    vector<float> aperture_mass_dm;\n    vector<float> aperture_veldisp_dm;\n    vector<float> aperture_vrdisp_dm;\n    vector<float> aperture_rhalfmass_dm;\n    #endif\n    //@}\n\n    vector<Double_t> SO_mass, SO_radius;\n    vector<Coordinate> SO_angularmomentum;\n\n#ifdef GASON\n    ///\\name gas specific quantities\n    //@{\n    ///number of particles\n    int n_gas;\n    ///mass\n    Double_t M_gas, M_gas_rvmax, M_gas_30kpc, M_gas_50kpc, M_gas_500c;\n    ///mass in spherical overdensities\n    Double_t M_200crit_gas, M_200mean_gas, M_BN98_gas;\n    ///mass in spherical overdensities inclusive of all masses\n    Double_t M_200crit_excl_gas, M_200mean_excl_gas, M_BN98_excl_gas;\n    ///pos/vel info\n    Coordinate cm_gas,cmvel_gas;\n    ///velocity/angular momentum info\n    Double_t Krot_gas;\n    Coordinate L_gas;\n    ///physical properties for angular momentum (can be inclusive or exclusive )\n    Coordinate L_200crit_gas, L_200mean_gas, L_BN98_gas;\n    ///physical properties for angular momentum exclusiveto object\n    Coordinate L_200crit_excl_gas, L_200mean_excl_gas, L_BN98_excl_gas;\n    //dispersion\n    Matrix veldisp_gas;\n    ///morphology\n    Double_t MassTwiceRhalfmass_gas, Rhalfmass_gas, q_gas, s_gas;\n    Matrix eigvec_gas;\n    ///mass weighted sum of temperature, metallicty, star formation rate\n    Double_t Temp_gas, Z_gas, SFR_gas;\n    ///mean temperature,metallicty,star formation rate\n    Double_t Temp_mean_gas, Z_mean_gas, SFR_mean_gas;\n    ///physical properties for dynamical state\n    Double_t Efrac_gas, Pot_gas, T_gas;\n    //@}\n\n    ///\\name gas radial profiles\n    //@{\n    vector<unsigned int> aperture_npart_gas;\n    vector<float> aperture_mass_gas;\n    vector<float> aperture_veldisp_gas;\n    vector<float> aperture_vrdisp_gas;\n    vector<float> aperture_SFR_gas;\n    vector<float> aperture_rhalfmass_gas;\n    vector<Coordinate> aperture_mass_proj_gas;\n    vector<Coordinate> aperture_rhalfmass_proj_gas;\n    vector<Coordinate> aperture_SFR_proj_gas;\n    vector<Coordinate> aperture_L_gas;\n    vector<unsigned int> profile_npart_gas;\n    vector<unsigned int> profile_npart_inclusive_gas;\n    vector<float> profile_mass_gas;\n    vector<float> profile_mass_inclusive_gas;\n    vector<Coordinate> profile_L_gas;\n    //@}\n\n    vector<Double_t> SO_mass_gas;\n    vector<Coordinate> SO_angularmomentum_gas;\n#ifdef STARON\n    ///\\name star forming gas specific quantities\n    //@{\n    ///number of particles\n    int n_gas_sf;\n    ///mass\n    Double_t M_gas_sf, M_gas_sf_rvmax,M_gas_sf_30kpc,M_gas_sf_50kpc, M_gas_sf_500c;\n    ///mass in spherical overdensities\n    Double_t M_200crit_gas_sf, M_200mean_gas_sf, M_BN98_gas_sf;\n    ///mass in spherical overdensities inclusive of all masses\n    Double_t M_200crit_excl_gas_sf, M_200mean_excl_gas_sf, M_BN98_excl_gas_sf;\n    ///velocity/angular momentum info\n    Double_t Krot_gas_sf;\n    Coordinate L_gas_sf;\n    ///physical properties for angular momentum (can be inclusive or exclusive )\n    Coordinate L_200crit_gas_sf, L_200mean_gas_sf, L_BN98_gas_sf;\n    ///physical properties for angular momentum exclusiveto object\n    Coordinate L_200crit_excl_gas_sf, L_200mean_excl_gas_sf, L_BN98_excl_gas_sf;\n    //dispersion\n    Double_t sigV_gas_sf;\n    ///morphology\n    Double_t MassTwiceRhalfmass_gas_sf, Rhalfmass_gas_sf, q_gas_sf, s_gas_sf;\n    ///mass weighted sum of temperature, metallicty, star formation rate\n    Double_t Temp_gas_sf, Z_gas_sf, SFR_gas_sf;\n    ///mean temperature,metallicty,star formation rate\n    Double_t Temp_mean_gas_sf, Z_mean_gas_sf, SFR_mean_gas_sf;\n    //@}\n\n    ///\\name gas star forming radial profiles\n    //@{\n    vector<unsigned int> aperture_npart_gas_sf;\n    vector<float> aperture_mass_gas_sf;\n    vector<float> aperture_veldisp_gas_sf;\n    vector<float> aperture_vrdisp_gas_sf;\n    vector<float> aperture_rhalfmass_gas_sf;\n    vector<Coordinate> aperture_mass_proj_gas_sf;\n    vector<Coordinate> aperture_rhalfmass_proj_gas_sf;\n    vector<Coordinate> aperture_L_gas_sf;\n    vector<unsigned int> profile_npart_gas_sf;\n    vector<unsigned int> profile_npart_inclusive_gas_sf;\n    vector<float> profile_mass_gas_sf;\n    vector<float> profile_mass_inclusive_gas_sf;\n    vector<Coordinate> profile_L_gas_sf;\n    //@}\n\n    vector<Double_t> SO_mass_gas_sf;\n    vector<Coordinate> SO_angularmomentum_gas_sf;\n\n    ///\\name star forming gas specific quantities\n    //@{\n    ///number of particles\n    int n_gas_nsf;\n    ///mass\n    Double_t M_gas_nsf, M_gas_nsf_rvmax,M_gas_nsf_30kpc,M_gas_nsf_50kpc, M_gas_nsf_500c;\n    ///mass in spherical overdensities\n    Double_t M_200crit_gas_nsf, M_200mean_gas_nsf, M_BN98_gas_nsf;\n    ///mass in spherical overdensities inclusive of all masses\n    Double_t M_200crit_excl_gas_nsf, M_200mean_excl_gas_nsf, M_BN98_excl_gas_nsf;\n    ///velocity/angular momentum info\n    Double_t Krot_gas_nsf;\n    Coordinate L_gas_nsf;\n    ///physical properties for angular momentum (can be inclusive or exclusive )\n    Coordinate L_200crit_gas_nsf, L_200mean_gas_nsf, L_BN98_gas_nsf;\n    ///physical properties for angular momentum exclusiveto object\n    Coordinate L_200crit_excl_gas_nsf, L_200mean_excl_gas_nsf, L_BN98_excl_gas_nsf;\n    //dispersion\n    Double_t sigV_gas_nsf;\n    ///morphology\n    Double_t MassTwiceRhalfmass_gas_nsf, Rhalfmass_gas_nsf, q_gas_nsf, s_gas_nsf;\n    ///mass weighted sum of temperature, metallicty, star formation rate\n    Double_t Temp_gas_nsf, Z_gas_nsf;\n    ///mean temperature,metallicty,star formation rate\n    Double_t Temp_mean_gas_nsf, Z_mean_gas_nsf;\n    //@}\n\n    ///\\name gas star forming radial profiles\n    //@{\n    vector<unsigned int> aperture_npart_gas_nsf;\n    vector<float> aperture_mass_gas_nsf;\n    vector<float> aperture_veldisp_gas_nsf;\n    vector<float> aperture_vrdisp_gas_nsf;\n    vector<float> aperture_rhalfmass_gas_nsf;\n    vector<Coordinate> aperture_mass_proj_gas_nsf;\n    vector<Coordinate> aperture_rhalfmass_proj_gas_nsf;\n    vector<Coordinate> aperture_L_gas_nsf;\n    vector<unsigned int> profile_npart_gas_nsf;\n    vector<unsigned int> profile_npart_inclusive_gas_nsf;\n    vector<float> profile_mass_gas_nsf;\n    vector<float> profile_mass_inclusive_gas_nsf;\n    vector<Coordinate> profile_L_gas_nsf;\n    //@}\n\n    vector<Double_t> SO_mass_gas_nsf;\n    vector<Coordinate> SO_angularmomentum_gas_nsf;\n#endif\n#endif\n\n#ifdef STARON\n    ///\\name star specific quantities\n    //@{\n    ///number of particles\n    int n_star;\n    ///mass\n    Double_t M_star, M_star_rvmax, M_star_30kpc, M_star_50kpc, M_star_500c;\n    ///mass in spherical overdensities\n    Double_t M_200crit_star, M_200mean_star, M_BN98_star;\n    ///mass in spherical overdensities inclusive of all masses\n    Double_t M_200crit_excl_star, M_200mean_excl_star, M_BN98_excl_star;\n    ///pos/vel info\n    Coordinate cm_star,cmvel_star;\n    ///velocity/angular momentum info\n    Double_t Krot_star;\n    Coordinate L_star;\n    ///physical properties for angular momentum (can be inclusive or exclusive )\n    Coordinate L_200crit_star, L_200mean_star, L_BN98_star;\n    ///physical properties for angular momentum exclusiveto object\n    Coordinate L_200crit_excl_star, L_200mean_excl_star, L_BN98_excl_star;\n    Matrix veldisp_star;\n    ///morphology\n    Double_t MassTwiceRhalfmass_star, Rhalfmass_star,q_star,s_star;\n    Matrix eigvec_star;\n    ///mean age,metallicty\n    Double_t t_star,Z_star;\n    ///mean age,metallicty\n    Double_t t_mean_star,Z_mean_star;\n    ///physical properties for dynamical state\n    Double_t Efrac_star,Pot_star,T_star;\n    //@}\n\n    ///\\name stellar radial profiles\n    //@{\n    vector<unsigned int> aperture_npart_star;\n    vector<float> aperture_mass_star;\n    vector<float> aperture_veldisp_star;\n    vector<float> aperture_vrdisp_star;\n    vector<float> aperture_rhalfmass_star;\n    vector<Coordinate> aperture_mass_proj_star;\n    vector<Coordinate> aperture_rhalfmass_proj_star;\n    vector<Coordinate> aperture_L_star;\n    vector<unsigned int> profile_npart_star;\n    vector<unsigned int> profile_npart_inclusive_star;\n    vector<float> profile_mass_star;\n    vector<float> profile_mass_inclusive_star;\n    vector<Coordinate> profile_L_star;\n    //@}\n\n    vector<Double_t> SO_mass_star;\n    vector<Coordinate> SO_angularmomentum_star;\n#endif\n\n#ifdef BHON\n    ///\\name black hole specific quantities\n    //@{\n    ///number of BH\n    int n_bh;\n    ///mass\n    Double_t M_bh, M_bh_mostmassive;\n    ///mean accretion rate, metallicty\n    Double_t acc_bh, acc_bh_mostmassive;\n\n    ///\\name blackhole aperture/radial profiles\n    //@{\n    vector<int> aperture_npart_bh;\n    vector<float> aperture_mass_bh;\n    vector<Coordinate> aperture_L_bh;\n    //@}\n\n    vector<Double_t> SO_mass_bh;\n    vector<Coordinate> SO_angularmomentum_bh;\n    //@}\n#endif\n\n#ifdef HIGHRES\n    ///\\name low resolution interloper particle specific quantities\n    //@{\n    ///number of interloper low res particles\n    int n_interloper;\n    ///mass\n    Double_t M_interloper;\n    ///mass in spherical overdensities\n    Double_t M_200crit_interloper, M_200mean_interloper, M_BN98_interloper;\n    ///mass in spherical overdensities inclusive of all masses\n    Double_t M_200crit_excl_interloper, M_200mean_excl_interloper, M_BN98_excl_interloper;\n\n    vector<unsigned int> aperture_npart_interloper;\n    vector<float> aperture_mass_interloper;\n    vector<unsigned int> profile_npart_interloper;\n    vector<unsigned int> profile_npart_inclusive_interloper;\n    vector<float> profile_mass_interloper;\n    vector<float> profile_mass_inclusive_interloper;\n\n    vector<Double_t> SO_mass_interloper;\n    //@}\n#endif\n\n    PropData()\n    {\n        num=gNFOF=gN6DFOF=0;\n        gmass=gsize=gRmbp=gmaxvel=gRmaxvel=gRvir=gR200m=gR200c=gRhalfmass=gMassTwiceRhalfmass=Efrac=Pot=T=0.;\n        gMFOF=gM6DFOF=0;\n        gM500c=gR500c=0;\n        gMBN98=gRBN98=0;\n        gcm[0]=gcm[1]=gcm[2]=gcmvel[0]=gcmvel[1]=gcmvel[2]=0.;\n        gJ[0]=gJ[1]=gJ[2]=0;\n        gJ200m[0]=gJ200m[1]=gJ200m[2]=0;\n        gJ200c[0]=gJ200c[1]=gJ200c[2]=0;\n        gJBN98[0]=gJBN98[1]=gJBN98[2]=0;\n        gveldisp=Matrix(0.);\n        gq=gs=1.0;\n        Krot=0.;\n\n        gM200m_excl=gM200c_excl=gMBN98_excl=0;\n        gR200m_excl=gR200c_excl=gRBN98_excl=0;\n        gJ200m_excl[0]=gJ200m_excl[1]=gJ200m_excl[2]=0;\n        gJ200c_excl[0]=gJ200c_excl[1]=gJ200c_excl[2]=0;\n        gJBN98_excl[0]=gJBN98_excl[1]=gJBN98_excl[2]=0;\n\n        RV_sigma_v=0;\n        RV_q=RV_s=1.;\n        RV_J[0]=RV_J[1]=RV_J[2]=0;\n        RV_veldisp=Matrix(0.);\n        RV_eigvec=Matrix(0.);\n        RV_lambda_B=RV_lambda_P=RV_Krot=0;\n\n#ifdef GASON\n        M_gas_rvmax=M_gas_30kpc=M_gas_50kpc=0;\n        n_gas=M_gas=Efrac_gas=0;\n        cm_gas[0]=cm_gas[1]=cm_gas[2]=cmvel_gas[0]=cmvel_gas[1]=cmvel_gas[2]=0.;\n        L_gas[0]=L_gas[1]=L_gas[2]=0;\n        q_gas=s_gas=1.0;\n        MassTwiceRhalfmass_gas=Rhalfmass_gas=0;\n        eigvec_gas=Matrix(1,0,0,0,1,0,0,0,1);\n        Temp_gas=Z_gas=SFR_gas=0.0;\n        Temp_mean_gas=Z_mean_gas=SFR_mean_gas=0.0;\n        veldisp_gas=Matrix(0.);\n        Krot_gas=T_gas=Pot_gas=0;\n\n        M_200mean_gas=M_200crit_gas=M_BN98_gas=0;\n        M_200mean_excl_gas=M_200crit_excl_gas=M_BN98_excl_gas=0;\n        L_200crit_gas[0]=L_200crit_gas[1]=L_200crit_gas[2]=0;\n        L_200mean_gas[0]=L_200mean_gas[1]=L_200mean_gas[2]=0;\n        L_BN98_gas[0]=L_BN98_gas[1]=L_BN98_gas[2]=0;\n        L_200crit_excl_gas[0]=L_200crit_excl_gas[1]=L_200crit_excl_gas[2]=0;\n        L_200mean_excl_gas[0]=L_200mean_excl_gas[1]=L_200mean_excl_gas[2]=0;\n        L_BN98_excl_gas[0]=L_BN98_excl_gas[1]=L_BN98_excl_gas[2]=0;\n#ifdef STARON\n        M_gas_sf=M_gas_sf_rvmax=M_gas_sf_30kpc=M_gas_sf_50kpc=0;\n        L_gas_sf[0]=L_gas_sf[1]=L_gas_sf[2]=0;\n        q_gas_sf=s_gas_sf=1.0;\n        MassTwiceRhalfmass_gas_sf=Rhalfmass_gas_sf=0;\n        Temp_gas_sf=Z_gas_sf=0.0;\n        Temp_mean_gas_sf=Z_mean_gas_sf=0.0;\n        sigV_gas_sf=0;\n\n        M_200mean_gas_sf=M_200crit_gas_sf=M_BN98_gas_sf=0;\n        M_200mean_excl_gas_sf=M_200crit_excl_gas_sf=M_BN98_excl_gas_sf=0;\n        L_200crit_gas_sf[0]=L_200crit_gas_sf[1]=L_200crit_gas_sf[2]=0;\n        L_200mean_gas_sf[0]=L_200mean_gas_sf[1]=L_200mean_gas_sf[2]=0;\n        L_BN98_gas_sf[0]=L_BN98_gas_sf[1]=L_BN98_gas_sf[2]=0;\n        L_200crit_excl_gas_sf[0]=L_200crit_excl_gas_sf[1]=L_200crit_excl_gas_sf[2]=0;\n        L_200mean_excl_gas_sf[0]=L_200mean_excl_gas_sf[1]=L_200mean_excl_gas_sf[2]=0;\n        L_BN98_excl_gas_sf[0]=L_BN98_excl_gas_sf[1]=L_BN98_excl_gas_sf[2]=0;\n\n        M_gas_nsf=M_gas_nsf_rvmax=M_gas_nsf_30kpc=M_gas_nsf_50kpc=0;\n        L_gas_nsf[0]=L_gas_nsf[1]=L_gas_nsf[2]=0;\n        q_gas_nsf=s_gas_nsf=1.0;\n        MassTwiceRhalfmass_gas_nsf=Rhalfmass_gas_nsf=0;\n        Temp_gas_nsf=Z_gas_nsf=0.0;\n        Temp_mean_gas_nsf=Z_mean_gas_nsf=0.0;\n        sigV_gas_nsf=0;\n        M_200mean_gas_nsf=M_200crit_gas_nsf=M_BN98_gas_nsf=0;\n        M_200mean_excl_gas_nsf=M_200crit_excl_gas_nsf=M_BN98_excl_gas_nsf=0;\n        L_200crit_gas_nsf[0]=L_200crit_gas_nsf[1]=L_200crit_gas_nsf[2]=0;\n        L_200mean_gas_nsf[0]=L_200mean_gas_nsf[1]=L_200mean_gas_nsf[2]=0;\n        L_BN98_gas_nsf[0]=L_BN98_gas_nsf[1]=L_BN98_gas_nsf[2]=0;\n        L_200crit_excl_gas_nsf[0]=L_200crit_excl_gas_nsf[1]=L_200crit_excl_gas_nsf[2]=0;\n        L_200mean_excl_gas_nsf[0]=L_200mean_excl_gas_nsf[1]=L_200mean_excl_gas_nsf[2]=0;\n        L_BN98_excl_gas_nsf[0]=L_BN98_excl_gas_nsf[1]=L_BN98_excl_gas_nsf[2]=0;\n#endif\n#endif\n#ifdef STARON\n        M_star_rvmax=M_star_30kpc=M_star_50kpc=0;\n        n_star=M_star=Efrac_star=0;\n        cm_star[0]=cm_star[1]=cm_star[2]=cmvel_star[0]=cmvel_star[1]=cmvel_star[2]=0.;\n        L_star[0]=L_star[1]=L_star[2]=0;\n        q_star=s_star=1.0;\n        MassTwiceRhalfmass_star=Rhalfmass_star=0;\n        eigvec_star=Matrix(1,0,0,0,1,0,0,0,1);\n        t_star=Z_star=0.;\n        t_mean_star=Z_mean_star=0.;\n        veldisp_star=Matrix(0.);\n        Krot_star=T_star=Pot_star=0;\n\n        M_200mean_star=M_200crit_star=M_BN98_star=0;\n        M_200mean_excl_star=M_200crit_excl_star=M_BN98_excl_star=0;\n        L_200crit_star[0]=L_200crit_star[1]=L_200crit_star[2]=0;\n        L_200mean_star[0]=L_200mean_star[1]=L_200mean_star[2]=0;\n        L_BN98_star[0]=L_BN98_star[1]=L_BN98_star[2]=0;\n        L_200crit_excl_star[0]=L_200crit_excl_star[1]=L_200crit_excl_star[2]=0;\n        L_200mean_excl_star[0]=L_200mean_excl_star[1]=L_200mean_excl_star[2]=0;\n        L_BN98_excl_star[0]=L_BN98_excl_star[1]=L_BN98_excl_star[2]=0;\n#endif\n#ifdef BHON\n        n_bh=M_bh=0;\n        M_bh_mostmassive=0;\n        acc_bh=0;\n        acc_bh_mostmassive=0;\n#endif\n#ifdef HIGHRES\n        n_interloper=M_interloper=0;\n#endif\n    }\n    ///equals operator, useful if want inclusive information before substructure search\n    PropData& operator=(const PropData &p){\n        num=p.num;\n        gcm=p.gcm;gcmvel=p.gcmvel;\n        gposmbp=p.gposmbp;gvelmbp=p.gvelmbp;\n        gposminpot=p.gposminpot;gvelminpot=p.gvelminpot;\n        gmass=p.gmass;gsize=p.gsize;\n        gMvir=p.gMvir;gRvir=p.gRvir;gRmbp=p.gRmbp;\n        gmaxvel=gmaxvel=p.gmaxvel;gRmaxvel=p.gRmaxvel;gMmaxvel=p.gMmaxvel;\n        gM200c=p.gM200c;gR200c=p.gR200c;\n        gM200m=p.gM200m;gR200m=p.gR200m;\n        gM500c=p.gM500c;gR500c=p.gR500c;\n        gMBN98=p.gMBN98;gRBN98=p.gRBN98;\n        gNFOF=p.gNFOF;\n        gMFOF=p.gMFOF;\n\n        gM200c_excl=p.gM200c_excl;gR200c_excl=p.gR200c_excl;\n        gM200m_excl=p.gM200m_excl;gR200m_excl=p.gR200m_excl;\n        gMBN98_excl=p.gMBN98_excl;gRBN98_excl=p.gRBN98_excl;\n        gJ=p.gJ;\n        gJ200c=p.gJ200c;\n        gJ200m=p.gJ200m;\n        gJBN98=p.gJBN98;\n        gJ200c_excl=p.gJ200c_excl;\n        gJ200m_excl=p.gJ200m_excl;\n        gJBN98_excl=p.gJBN98_excl;\n\n        ///expand to copy all the gas, star, bh, stuff\n#ifdef GASON\n        M_200mean_gas=p.M_200mean_gas;\n        M_200crit_gas=p.M_200crit_gas;\n        M_BN98_gas=p.M_BN98_gas;\n        M_200mean_excl_gas=p.M_200mean_excl_gas;\n        M_200crit_excl_gas=p.M_200crit_excl_gas;\n        M_BN98_excl_gas=p.M_BN98_excl_gas;\n        L_200mean_gas=p.L_200mean_gas;\n        L_200crit_gas=p.L_200crit_gas;\n        L_BN98_gas=p.L_BN98_gas;\n        L_200mean_excl_gas=p.L_200mean_excl_gas;\n        L_200crit_excl_gas=p.L_200crit_excl_gas;\n        L_BN98_excl_gas=p.L_BN98_excl_gas;\n#ifdef STARON\n        M_200mean_gas_sf=p.M_200mean_gas_sf;\n        M_200crit_gas_sf=p.M_200crit_gas_sf;\n        M_BN98_gas_sf=p.M_BN98_gas_sf;\n        M_200mean_excl_gas_sf=p.M_200mean_excl_gas_sf;\n        M_200crit_excl_gas_sf=p.M_200crit_excl_gas_sf;\n        M_BN98_excl_gas_sf=p.M_BN98_excl_gas_sf;\n        L_200mean_gas_sf=p.L_200mean_gas_sf;\n        L_200crit_gas_sf=p.L_200crit_gas_sf;\n        L_BN98_gas_sf=p.L_BN98_gas_sf;\n        L_200mean_excl_gas_sf=p.L_200mean_excl_gas_sf;\n        L_200crit_excl_gas_sf=p.L_200crit_excl_gas_sf;\n        L_BN98_excl_gas_sf=p.L_BN98_excl_gas_sf;\n\n        M_200mean_gas_nsf=p.M_200mean_gas_nsf;\n        M_200crit_gas_nsf=p.M_200crit_gas_nsf;\n        M_BN98_gas_nsf=p.M_BN98_gas_nsf;\n        M_200mean_excl_gas_nsf=p.M_200mean_excl_gas_nsf;\n        M_200crit_excl_gas_nsf=p.M_200crit_excl_gas_nsf;\n        M_BN98_excl_gas_nsf=p.M_BN98_excl_gas_nsf;\n        L_200mean_gas_nsf=p.L_200mean_gas_nsf;\n        L_200crit_gas_nsf=p.L_200crit_gas_nsf;\n        L_BN98_gas_nsf=p.L_BN98_gas_nsf;\n        L_200mean_excl_gas_nsf=p.L_200mean_excl_gas_nsf;\n        L_200crit_excl_gas_nsf=p.L_200crit_excl_gas_nsf;\n        L_BN98_excl_gas_nsf=p.L_BN98_excl_gas_nsf;\n#endif\n#endif\n#ifdef STARON\n        M_200mean_star=p.M_200mean_star;\n        M_200crit_star=p.M_200crit_star;\n        M_BN98_star=p.M_BN98_star;\n        M_200mean_excl_star=p.M_200mean_excl_star;\n        M_200crit_excl_star=p.M_200crit_excl_star;\n        M_BN98_excl_star=p.M_BN98_excl_star;\n        L_200mean_star=p.L_200mean_star;\n        L_200crit_star=p.L_200crit_star;\n        L_BN98_star=p.L_BN98_star;\n        L_200mean_excl_star=p.L_200mean_excl_star;\n        L_200crit_excl_star=p.L_200crit_excl_star;\n        L_BN98_excl_star=p.L_BN98_excl_star;\n#endif\n        aperture_npart=p.aperture_npart;\n        aperture_mass=p.aperture_mass;\n        aperture_veldisp=p.aperture_veldisp;\n        aperture_vrdisp=p.aperture_vrdisp;\n        aperture_rhalfmass=p.aperture_rhalfmass;\n        #if defined(GASON) || defined(STARON) || defined(BHON)\n        aperture_npart_dm=p.aperture_npart_dm;\n        aperture_mass_dm=p.aperture_mass_dm;\n        aperture_veldisp_dm=p.aperture_veldisp_dm;\n        aperture_vrdisp_dm=p.aperture_vrdisp_dm;\n        aperture_rhalfmass_dm=p.aperture_rhalfmass_dm;\n        #endif\n#ifdef GASON\n        aperture_npart_gas=p.aperture_npart_gas;\n        aperture_mass_gas=p.aperture_mass_gas;\n        aperture_veldisp_gas=p.aperture_veldisp_gas;\n        aperture_rhalfmass_gas=p.aperture_rhalfmass_gas;\n#ifdef STARON\n        aperture_SFR_gas=p.aperture_SFR_gas;\n        aperture_npart_gas_sf=p.aperture_npart_gas_sf;\n        aperture_npart_gas_nsf=p.aperture_npart_gas_nsf;\n        aperture_mass_gas_sf=p.aperture_mass_gas_sf;\n        aperture_mass_gas_nsf=p.aperture_mass_gas_nsf;\n        aperture_veldisp_gas_sf=p.aperture_veldisp_gas_sf;\n        aperture_veldisp_gas_nsf=p.aperture_veldisp_gas_nsf;\n        aperture_vrdisp_gas_sf=p.aperture_vrdisp_gas_sf;\n        aperture_vrdisp_gas_nsf=p.aperture_vrdisp_gas_nsf;\n        aperture_rhalfmass_gas_sf=p.aperture_rhalfmass_gas_sf;\n        aperture_rhalfmass_gas_nsf=p.aperture_rhalfmass_gas_nsf;\n#endif\n#endif\n#ifdef STARON\n        aperture_npart_star=p.aperture_npart_star;\n        aperture_mass_star=p.aperture_mass_star;\n        aperture_veldisp_star=p.aperture_veldisp_star;\n        aperture_vrdisp_star=p.aperture_vrdisp_star;\n        aperture_rhalfmass_star=p.aperture_rhalfmass_star;\n#endif\n        aperture_mass_proj=p.aperture_mass_proj;\n        aperture_rhalfmass_proj=p.aperture_rhalfmass_proj;\n#ifdef GASON\n        aperture_mass_proj_gas=p.aperture_mass_proj_gas;\n        aperture_rhalfmass_proj_gas=p.aperture_rhalfmass_proj_gas;\n#ifdef STARON\n        aperture_mass_proj_gas_sf=p.aperture_mass_proj_gas_sf;\n        aperture_rhalfmass_proj_gas_nsf=p.aperture_rhalfmass_proj_gas_nsf;\n#endif\n#endif\n#ifdef STARON\n        aperture_mass_proj_star=p.aperture_mass_proj_star;\n        aperture_rhalfmass_proj_star=p.aperture_rhalfmass_proj_star;\n#endif\n        profile_npart=p.profile_npart;\n        profile_mass=p.profile_mass;\n        profile_npart_inclusive=p.profile_npart_inclusive;\n        profile_mass_inclusive=p.profile_mass_inclusive;\n#ifdef GASON\n        profile_npart_gas=p.profile_npart_gas;\n        profile_mass_gas=p.profile_mass_gas;\n        profile_npart_inclusive_gas=p.profile_npart_inclusive_gas;\n        profile_mass_inclusive_gas=p.profile_mass_inclusive_gas;\n#ifdef STARON\n        profile_npart_gas_sf=p.profile_npart_gas_sf;\n        profile_mass_gas_sf=p.profile_mass_gas_sf;\n        profile_npart_inclusive_gas_sf=p.profile_npart_inclusive_gas_sf;\n        profile_mass_inclusive_gas_sf=p.profile_mass_inclusive_gas_sf;\n        profile_npart_gas_nsf=p.profile_npart_gas_nsf;\n        profile_mass_gas_nsf=p.profile_mass_gas_nsf;\n        profile_npart_inclusive_gas_nsf=p.profile_npart_inclusive_gas_nsf;\n        profile_mass_inclusive_gas_nsf=p.profile_mass_inclusive_gas_nsf;\n#endif\n#endif\n#ifdef STARON\n        profile_npart_star=p.profile_npart_star;\n        profile_mass_star=p.profile_mass_star;\n        profile_npart_inclusive_star=p.profile_npart_inclusive_star;\n        profile_mass_inclusive_star=p.profile_mass_inclusive_star;\n#endif\n        return *this;\n    }\n\n    //allocate memory for profiles\n    void Allocate(Options &opt) {\n        AllocateApertures(opt);\n        AllocateProfiles(opt);\n        AllocateSOs(opt);\n    }\n    void AllocateApertures(Options &opt)\n    {\n        if (opt.iaperturecalc && opt.aperturenum>0) {\n            aperture_npart.resize(opt.aperturenum);\n            aperture_mass.resize(opt.aperturenum);\n            aperture_veldisp.resize(opt.aperturenum);\n            aperture_vrdisp.resize(opt.aperturenum);\n            aperture_rhalfmass.resize(opt.aperturenum);\n#ifdef GASON\n            aperture_npart_gas.resize(opt.aperturenum);\n            aperture_mass_gas.resize(opt.aperturenum);\n            aperture_veldisp_gas.resize(opt.aperturenum);\n            aperture_vrdisp_gas.resize(opt.aperturenum);\n            aperture_rhalfmass_gas.resize(opt.aperturenum);\n#ifdef STARON\n            aperture_SFR_gas.resize(opt.aperturenum);\n            aperture_npart_gas_sf.resize(opt.aperturenum);\n            aperture_npart_gas_nsf.resize(opt.aperturenum);\n            aperture_mass_gas_sf.resize(opt.aperturenum);\n            aperture_mass_gas_nsf.resize(opt.aperturenum);\n            aperture_veldisp_gas_sf.resize(opt.aperturenum);\n            aperture_veldisp_gas_nsf.resize(opt.aperturenum);\n            aperture_vrdisp_gas_sf.resize(opt.aperturenum);\n            aperture_vrdisp_gas_nsf.resize(opt.aperturenum);\n            aperture_rhalfmass_gas_sf.resize(opt.aperturenum);\n            aperture_rhalfmass_gas_nsf.resize(opt.aperturenum);\n#endif\n#endif\n#ifdef STARON\n            aperture_npart_star.resize(opt.aperturenum);\n            aperture_mass_star.resize(opt.aperturenum);\n            aperture_veldisp_star.resize(opt.aperturenum);\n            aperture_vrdisp_star.resize(opt.aperturenum);\n            aperture_rhalfmass_star.resize(opt.aperturenum);\n#endif\n#ifdef HIGHRES\n            aperture_npart_interloper.resize(opt.aperturenum);\n            aperture_mass_interloper.resize(opt.aperturenum);\n#endif\n            #if defined(GASON) || defined(STARON) || defined(BHON)\n            //if searching all types, also store dm only aperture quantities\n            if (opt.partsearchtype==PSTALL) {\n            aperture_npart_dm.resize(opt.aperturenum);\n            aperture_mass_dm.resize(opt.aperturenum);\n            aperture_veldisp_dm.resize(opt.aperturenum);\n            aperture_vrdisp_dm.resize(opt.aperturenum);\n            aperture_rhalfmass_dm.resize(opt.aperturenum);\n            }\n            #endif\n            for (auto &x:aperture_npart) x=0;\n            for (auto &x:aperture_mass) x=-1;\n            for (auto &x:aperture_veldisp) x=0;\n            for (auto &x:aperture_rhalfmass) x=-1;\n#ifdef GASON\n            for (auto &x:aperture_npart_gas) x=0;\n            for (auto &x:aperture_mass_gas) x=-1;\n            for (auto &x:aperture_veldisp_gas) x=0;\n            for (auto &x:aperture_rhalfmass_gas) x=-1;\n#ifdef STARON\n            for (auto &x:aperture_SFR_gas) x=0;\n            for (auto &x:aperture_npart_gas_sf) x=0;\n            for (auto &x:aperture_mass_gas_sf) x=-1;\n            for (auto &x:aperture_npart_gas_nsf) x=0;\n            for (auto &x:aperture_mass_gas_nsf) x=-1;\n            for (auto &x:aperture_veldisp_gas_sf) x=0;\n            for (auto &x:aperture_veldisp_gas_nsf) x=0;\n            for (auto &x:aperture_rhalfmass_gas_sf) x=-1;\n            for (auto &x:aperture_rhalfmass_gas_nsf) x=-1;\n#endif\n#endif\n#ifdef STARON\n            for (auto &x:aperture_npart_star) x=0;\n            for (auto &x:aperture_mass_star) x=-1;\n            for (auto &x:aperture_veldisp_star) x=0;\n            for (auto &x:aperture_rhalfmass_star) x=-1;\n#endif\n#ifdef HIGHRES\n            for (auto &x:aperture_npart_interloper) x=0;\n            for (auto &x:aperture_mass_interloper) x=-1;\n#endif\n            #if defined(GASON) || defined(STARON) || defined(BHON)\n            if (opt.partsearchtype==PSTALL) {\n            for (auto &x:aperture_npart_dm) x=0;\n            for (auto &x:aperture_mass_dm) x=-1;\n            for (auto &x:aperture_veldisp_dm) x=0;\n            for (auto &x:aperture_rhalfmass_dm) x=0;\n            }\n            #endif\n\n        }\n\n        if (opt.iaperturecalc && opt.apertureprojnum>0) {\n            aperture_mass_proj.resize(opt.apertureprojnum);\n            aperture_rhalfmass_proj.resize(opt.apertureprojnum);\n#ifdef GASON\n            aperture_mass_proj_gas.resize(opt.apertureprojnum);\n            aperture_rhalfmass_proj_gas.resize(opt.apertureprojnum);\n#ifdef STARON\n            aperture_SFR_proj_gas.resize(opt.apertureprojnum);\n            aperture_mass_proj_gas_sf.resize(opt.apertureprojnum);\n            aperture_mass_proj_gas_nsf.resize(opt.apertureprojnum);\n            aperture_rhalfmass_proj_gas_sf.resize(opt.apertureprojnum);\n            aperture_rhalfmass_proj_gas_nsf.resize(opt.apertureprojnum);\n#endif\n#endif\n#ifdef STARON\n            aperture_mass_proj_star.resize(opt.apertureprojnum);\n            aperture_rhalfmass_proj_star.resize(opt.apertureprojnum);\n#endif\n\n            for (auto &x:aperture_mass_proj) x[0]=x[1]=x[2]=-1;\n            for (auto &x:aperture_rhalfmass_proj) x[0]=x[1]=x[2]=-1;\n#ifdef GASON\n            for (auto &x:aperture_mass_proj_gas) x[0]=x[1]=x[2]=-1;\n            for (auto &x:aperture_rhalfmass_proj_gas) x[0]=x[1]=x[2]=-1;\n#ifdef STARON\n            for (auto &x:aperture_SFR_proj_gas) x[0]=x[1]=x[2]=0;\n            for (auto &x:aperture_mass_proj_gas_sf) x[0]=x[1]=x[2]=-1;\n            for (auto &x:aperture_rhalfmass_proj_gas_sf) x[0]=x[1]=x[2]=-1;\n            for (auto &x:aperture_mass_proj_gas_nsf) x[0]=x[1]=x[2]=-1;\n            for (auto &x:aperture_rhalfmass_proj_gas_nsf) x[0]=x[1]=x[2]=-1;\n#endif\n#endif\n#ifdef STARON\n            for (auto &x:aperture_mass_proj_star) x[0]=x[1]=x[2]=-1;\n            for (auto &x:aperture_rhalfmass_proj_star) x[0]=x[1]=x[2]=-1;\n#endif\n        }\n    }\n    void AllocateProfiles(Options &opt)\n    {\n        if (opt.iprofilecalc) {\n            profile_npart.resize(opt.profilenbins);\n            profile_mass.resize(opt.profilenbins);\n            for (auto i=0;i<opt.profilenbins;i++) profile_npart[i]=profile_mass[i]=0;\n#ifdef GASON\n            profile_npart_gas.resize(opt.profilenbins);\n            profile_mass_gas.resize(opt.profilenbins);\n#ifdef STARON\n            profile_npart_gas_sf.resize(opt.profilenbins);\n            profile_mass_gas_sf.resize(opt.profilenbins);\n            profile_npart_gas_nsf.resize(opt.profilenbins);\n            profile_mass_gas_nsf.resize(opt.profilenbins);\n#endif\n            for (auto i=0;i<opt.profilenbins;i++) profile_npart_gas[i]=profile_mass_gas[i]=0;\n#ifdef STARON\n            for (auto i=0;i<opt.profilenbins;i++) profile_npart_gas_sf[i]=profile_mass_gas_sf[i]=profile_npart_gas_nsf[i]=profile_mass_gas_nsf[i]=0;\n#endif\n#endif\n#ifdef STARON\n            profile_npart_star.resize(opt.profilenbins);\n            profile_mass_star.resize(opt.profilenbins);\n            for (auto i=0;i<opt.profilenbins;i++) profile_npart_star[i]=profile_mass_star[i]=0;\n#endif\n            if (opt.iInclusiveHalo>0) {\n                profile_npart_inclusive.resize(opt.profilenbins);\n                profile_mass_inclusive.resize(opt.profilenbins);\n                for (auto i=0;i<opt.profilenbins;i++) profile_npart_inclusive[i]=profile_mass_inclusive[i]=0;\n#ifdef GASON\n                profile_npart_inclusive_gas.resize(opt.profilenbins);\n                profile_mass_inclusive_gas.resize(opt.profilenbins);\n#ifdef STARON\n                profile_npart_inclusive_gas_sf.resize(opt.profilenbins);\n                profile_mass_inclusive_gas_sf.resize(opt.profilenbins);\n                profile_npart_inclusive_gas_nsf.resize(opt.profilenbins);\n                profile_mass_inclusive_gas_nsf.resize(opt.profilenbins);\n#endif\n                for (auto i=0;i<opt.profilenbins;i++) profile_npart_inclusive_gas[i]=profile_mass_inclusive_gas[i]=0;\n#ifdef STARON\n                for (auto i=0;i<opt.profilenbins;i++) profile_npart_inclusive_gas_sf[i]=profile_mass_inclusive_gas_sf[i]=profile_npart_inclusive_gas_nsf[i]=profile_mass_inclusive_gas_nsf[i]=0;\n#endif\n#endif\n#ifdef STARON\n                profile_npart_inclusive_star.resize(opt.profilenbins);\n                profile_mass_inclusive_star.resize(opt.profilenbins);\n                for (auto i=0;i<opt.profilenbins;i++) profile_npart_inclusive_star[i]=profile_mass_inclusive_star[i]=0;\n#endif\n            }\n\n        }\n    }\n    void AllocateSOs(Options &opt)\n    {\n        if (opt.SOnum>0) {\n            SO_mass.resize(opt.SOnum);\n            SO_radius.resize(opt.SOnum);\n            for (auto &x:SO_mass) x=0;\n            for (auto &x:SO_radius) x=0;\n            if (opt.iextrahalooutput) {\n                SO_angularmomentum.resize(opt.SOnum);\n                for (auto &x:SO_angularmomentum) {x[0]=x[1]=x[2]=0;}\n#ifdef GASON\n                if (opt.iextragasoutput) {\n                    SO_mass_gas.resize(opt.SOnum);\n                    for (auto &x:SO_mass_gas) x=0;\n                    SO_angularmomentum_gas.resize(opt.SOnum);\n                    for (auto &x:SO_angularmomentum_gas) {x[0]=x[1]=x[2]=0;}\n#ifdef STARON\n#endif\n                }\n#endif\n#ifdef STARON\n                if (opt.iextrastaroutput) {\n                    SO_mass_star.resize(opt.SOnum);\n                    for (auto &x:SO_mass_star) x=0;\n                    SO_angularmomentum_star.resize(opt.SOnum);\n                    for (auto &x:SO_angularmomentum_star) {x[0]=x[1]=x[2]=0;}\n                }\n#endif\n#ifdef HIGHRES\n                if (opt.iextrainterloperoutput) {\n                    SO_mass_interloper.resize(opt.SOnum);\n                    for (auto &x:SO_mass_interloper) x=0;\n                }\n#endif\n            }\n        }\n    }\n    void CopyProfileToInclusive(Options &opt) {\n        for (auto i=0;i<opt.profilenbins;i++) {\n            profile_npart_inclusive[i]=profile_npart[i];\n            profile_mass_inclusive[i]=profile_mass[i];\n            profile_npart[i]=profile_mass[i]=0;\n#ifdef GASON\n            profile_npart_inclusive_gas[i]=profile_npart_gas[i];\n            profile_mass_inclusive_gas[i]=profile_mass_gas[i];\n            profile_npart_gas[i]=profile_mass_gas[i]=0;\n#ifdef STARON\n            profile_npart_inclusive_gas_sf[i]=profile_npart_gas_sf[i];\n            profile_mass_inclusive_gas_sf[i]=profile_mass_gas_sf[i];\n            profile_npart_gas_sf[i]=profile_mass_gas_sf[i]=0;\n            profile_npart_inclusive_gas_nsf[i]=profile_npart_gas_nsf[i];\n            profile_mass_inclusive_gas_nsf[i]=profile_mass_gas_nsf[i];\n            profile_npart_gas_nsf[i]=profile_mass_gas_nsf[i]=0;\n#endif\n#endif\n#ifdef STARON\n            profile_npart_inclusive_star[i]=profile_npart_star[i];\n            profile_mass_inclusive_star[i]=profile_mass_star[i];\n            profile_npart_star[i]=profile_mass_star[i]=0;\n#endif\n        }\n    }\n\n    ///converts the properties data into comoving little h values\n    ///so masses, positions have little h values and positions are comoving\n    void ConverttoComove(Options &opt){\n        gcm=gcm*opt.h/opt.a;\n        gposmbp=gposmbp*opt.h/opt.a;\n        gposminpot=gposminpot*opt.h/opt.a;\n        gmass*=opt.h;\n        gMvir*=opt.h;\n        gM200c*=opt.h;\n        gM200m*=opt.h;\n        gM500c*=opt.h;\n        gMBN98*=opt.h;\n        gMFOF*=opt.h;\n        gsize*=opt.h/opt.a;\n        gRmbp*=opt.h/opt.a;\n        gRmaxvel*=opt.h/opt.a;\n        gRvir*=opt.h/opt.a;\n        gR200c*=opt.h/opt.a;\n        gR200m*=opt.h/opt.a;\n        gR500c*=opt.h/opt.a;\n        gRBN98*=opt.h/opt.a;\n        gMassTwiceRhalfmass*=opt.h;\n        gRhalfmass*=opt.h/opt.a;\n        gJ=gJ*opt.h*opt.h/opt.a;\n        gJ200m=gJ200m*opt.h*opt.h/opt.a;\n        gJ200c=gJ200c*opt.h*opt.h/opt.a;\n        gJBN98=gJBN98*opt.h*opt.h/opt.a;\n        RV_J=RV_J*opt.h*opt.h/opt.a;\n\n        if (opt.iextrahalooutput) {\n            gM200c_excl*=opt.h;\n            gM200m_excl*=opt.h;\n            gMBN98_excl*=opt.h;\n            gR200c_excl*=opt.h/opt.a;\n            gR200m_excl*=opt.h/opt.a;\n            gRBN98_excl*=opt.h/opt.a;\n            gJ200m_excl=gJ200m_excl*opt.h*opt.h/opt.a;\n            gJ200c_excl=gJ200c_excl*opt.h*opt.h/opt.a;\n            gJBN98_excl=gJBN98_excl*opt.h*opt.h/opt.a;\n        }\n\n#ifdef GASON\n        M_gas*=opt.h;\n        M_gas_rvmax*=opt.h;\n        M_gas_30kpc*=opt.h;\n        M_gas_50kpc*=opt.h;\n        M_gas_500c*=opt.h;\n\n        cm_gas=cm_gas*opt.h/opt.a;\n        L_gas=L_gas*opt.h*opt.h/opt.a;\n        MassTwiceRhalfmass_gas*=opt.h;\n        Rhalfmass_gas*=opt.h/opt.a;\n\n        if (opt.iextragasoutput) {\n            M_200mean_gas*=opt.h;\n            M_200crit_gas*=opt.h;\n            M_BN98_gas*=opt.h;\n            M_200mean_excl_gas*=opt.h;\n            M_200crit_excl_gas*=opt.h;\n            M_BN98_excl_gas*=opt.h;\n            L_200crit_gas=L_200crit_gas*opt.h*opt.h/opt.a;\n            L_200mean_gas=L_200mean_gas*opt.h*opt.h/opt.a;\n            L_BN98_gas=L_BN98_gas*opt.h*opt.h/opt.a;\n            L_200crit_excl_gas=L_200crit_excl_gas*opt.h*opt.h/opt.a;\n            L_200mean_excl_gas=L_200mean_excl_gas*opt.h*opt.h/opt.a;\n            L_BN98_excl_gas=L_BN98_excl_gas*opt.h*opt.h/opt.a;\n        }\n        #ifdef STARON\n        M_gas_sf*=opt.h;\n        L_gas_sf*=opt.h*opt.h/opt.a;\n        MassTwiceRhalfmass_gas_sf*=opt.h;\n        Rhalfmass_gas_sf*=opt.h/opt.a;\n\n        M_gas_nsf*=opt.h;\n        L_gas_nsf*=opt.h*opt.h/opt.a;\n        MassTwiceRhalfmass_gas_nsf*=opt.h;\n        Rhalfmass_gas_nsf*=opt.h/opt.a;\n\n        if (opt.iextragasoutput) {\n            M_200mean_gas_sf*=opt.h;\n            M_200crit_gas_sf*=opt.h;\n            M_BN98_gas_sf*=opt.h;\n            M_200mean_excl_gas_sf*=opt.h;\n            M_200crit_excl_gas_sf*=opt.h;\n            M_BN98_excl_gas_sf*=opt.h;\n            L_200crit_gas_sf*=opt.h*opt.h/opt.a;\n            L_200mean_gas_sf*=opt.h*opt.h/opt.a;\n            L_BN98_gas_sf*=opt.h*opt.h/opt.a;\n            L_200crit_excl_gas_sf*=opt.h*opt.h/opt.a;\n            L_200mean_excl_gas_sf*=opt.h*opt.h/opt.a;\n            L_BN98_excl_gas_sf*=opt.h*opt.h/opt.a;\n\n            M_200mean_gas_nsf*=opt.h;\n            M_200crit_gas_nsf*=opt.h;\n            M_BN98_gas_nsf*=opt.h;\n            M_200mean_excl_gas_nsf*=opt.h;\n            M_200crit_excl_gas_nsf*=opt.h;\n            M_BN98_excl_gas_nsf*=opt.h;\n            L_200crit_gas_nsf*=opt.h*opt.h/opt.a;\n            L_200mean_gas_nsf*=opt.h*opt.h/opt.a;\n            L_BN98_gas_nsf*=opt.h*opt.h/opt.a;\n            L_200crit_excl_gas_nsf*=opt.h*opt.h/opt.a;\n            L_200mean_excl_gas_nsf*=opt.h*opt.h/opt.a;\n            L_BN98_excl_gas_nsf*=opt.h*opt.h/opt.a;\n        }\n        #endif\n\n#endif\n#ifdef STARON\n        M_star*=opt.h;\n        M_star_rvmax*=opt.h;\n        M_star_30kpc*=opt.h;\n        M_star_50kpc*=opt.h;\n        M_star_500c*=opt.h;\n        cm_star=cm_star*opt.h/opt.a;\n        MassTwiceRhalfmass_star*=opt.h/opt.a;\n        Rhalfmass_star*=opt.h/opt.a;\n        L_star=L_star*opt.h*opt.h/opt.a;\n#endif\n#ifdef BHON\n        M_bh*=opt.h;\n#endif\n#ifdef HIGHRES\n        M_interloper*=opt.h;\n#endif\n        if (opt.iaperturecalc) {\n            for (auto i=0;i<opt.iaperturecalc;i++) {\n                aperture_mass[i]*=opt.h;\n#ifdef GASON\n                aperture_mass_gas[i]*=opt.h;\n#ifdef STARON\n                aperture_mass_gas_sf[i]*=opt.h;\n                aperture_mass_gas_nsf[i]*=opt.h;\n#endif\n#endif\n#ifdef STARON\n                aperture_mass_star[i]*=opt.h;\n#endif\n            }\n        }\n        if (opt.SOnum>0) {\n            for (auto i=0;i<opt.SOnum;i++) {\n                SO_mass[i] *= opt.h;\n                SO_radius[i] *= opt.h/opt.a;\n                if (opt.iextrahalooutput) {\n                    SO_angularmomentum[i]*=(opt.h*opt.h/opt.a);\n#ifdef GASON\n                    SO_mass_gas[i] *= opt.h;\n                    SO_angularmomentum_gas[i]*=(opt.h*opt.h/opt.a);\n#ifdef STARON\n#endif\n#endif\n#ifdef STARON\n                    SO_mass_star[i] *= opt.h;\n                    SO_angularmomentum_star[i]*=(opt.h*opt.h/opt.a);\n#endif\n                }\n            }\n        }\n    }\n\n    void ConvertProfilestoComove(Options &opt){\n        for (auto i=0;i<opt.profilenbins;i++) {\n            profile_mass[i]*=opt.h;\n#ifdef GASON\n            profile_mass_gas[i]*=opt.h;\n#ifdef STARON\n            profile_mass_gas_sf[i]*=opt.h;\n            profile_mass_gas_nsf[i]*=opt.h;\n#endif\n#endif\n#ifdef STARON\n            profile_mass_star[i]*=opt.h;\n#endif\n            }\n        if (opt.iInclusiveHalo) {\n            for (auto i=0;i<opt.profilenbins;i++) {\n                profile_mass_inclusive[i]*=opt.h;\n#ifdef GASON\n                profile_mass_inclusive_gas[i]*=opt.h;\n#ifdef STARON\n                profile_mass_inclusive_gas_sf[i]*=opt.h;\n                profile_mass_inclusive_gas_nsf[i]*=opt.h;\n#endif\n#endif\n#ifdef STARON\n                profile_mass_inclusive_star[i]*=opt.h;\n#endif\n            }\n        }\n    }\n\n    ///write (append) the properties data to an already open binary file\n    void WriteBinary(fstream &Fout, Options&opt){\n        long long lval;\n        long unsigned idval;\n        unsigned int ival;\n        double val, val3[3],val9[9];\n        idval=haloid;\n        Fout.write((char*)&idval,sizeof(idval));\n        lval=ibound;\n        Fout.write((char*)&lval,sizeof(idval));\n        lval=iminpot;\n        Fout.write((char*)&lval,sizeof(idval));\n        lval=hostid;\n        Fout.write((char*)&lval,sizeof(idval));\n        idval=numsubs;\n        Fout.write((char*)&idval,sizeof(idval));\n        idval=num;\n        Fout.write((char*)&idval,sizeof(idval));\n        ival=stype;\n        Fout.write((char*)&ival,sizeof(ival));\n        if (opt.iKeepFOF==1) {\n            idval=directhostid;\n            Fout.write((char*)&idval,sizeof(idval));\n            idval=hostfofid;\n            Fout.write((char*)&idval,sizeof(idval));\n        }\n\n        val=gMvir;\n        Fout.write((char*)&val,sizeof(val));\n\n        for (int k=0;k<3;k++) val3[k]=gcm[k];\n        Fout.write((char*)val3,sizeof(val)*3);\n        for (int k=0;k<3;k++) val3[k]=gposmbp[k];\n        Fout.write((char*)val3,sizeof(val)*3);\n        for (int k=0;k<3;k++) val3[k]=gposminpot[k];\n        Fout.write((char*)val3,sizeof(val)*3);\n        for (int k=0;k<3;k++) val3[k]=gcmvel[k];\n        Fout.write((char*)val3,sizeof(val)*3);\n        for (int k=0;k<3;k++) val3[k]=gvelmbp[k];\n        Fout.write((char*)val3,sizeof(val)*3);\n        for (int k=0;k<3;k++) val3[k]=gvelminpot[k];\n        Fout.write((char*)val3,sizeof(val)*3);\n\n\n        val=gmass;\n        Fout.write((char*)&val,sizeof(val));\n        val=gMFOF;\n        Fout.write((char*)&val,sizeof(val));\n        val=gM200m;\n        Fout.write((char*)&val,sizeof(val));\n        val=gM200c;\n        Fout.write((char*)&val,sizeof(val));\n        val=gMBN98;\n        Fout.write((char*)&val,sizeof(val));\n\n        val=Efrac;\n        Fout.write((char*)&val,sizeof(val));\n\n        val=gRvir;\n        Fout.write((char*)&val,sizeof(val));\n        val=gsize;\n        Fout.write((char*)&val,sizeof(val));\n        val=gR200m;\n        Fout.write((char*)&val,sizeof(val));\n        val=gR200c;\n        Fout.write((char*)&val,sizeof(val));\n        val=gRBN98;\n        Fout.write((char*)&val,sizeof(val));\n        val=gRhalfmass;\n        Fout.write((char*)&val,sizeof(val));\n        val=gRmaxvel;\n        Fout.write((char*)&val,sizeof(val));\n\n        val=gmaxvel;\n        Fout.write((char*)&val,sizeof(val));\n        val=gsigma_v;\n        Fout.write((char*)&val,sizeof(val));\n        for (int k=0;k<3;k++) for (int n=0;n<3;n++) val9[k*3+n]=gveldisp(k,n);\n        Fout.write((char*)val9,sizeof(val)*9);\n\n        val=glambda_B;\n        Fout.write((char*)&val,sizeof(val));\n        for (int k=0;k<3;k++) val3[k]=gJ[k];\n        Fout.write((char*)val3,sizeof(val)*3);\n\n        val=gq;\n        Fout.write((char*)&val,sizeof(val));\n        val=gs;\n        Fout.write((char*)&val,sizeof(val));\n        for (int k=0;k<3;k++) for (int n=0;n<3;n++) val9[k*3+n]=geigvec(k,n);\n        Fout.write((char*)val9,sizeof(val)*9);\n\n        val=cNFW;\n        Fout.write((char*)&val,sizeof(val));\n        val=Krot;\n        Fout.write((char*)&val,sizeof(val));\n        val=T;\n        Fout.write((char*)&val,sizeof(val));\n        val=Pot;\n        Fout.write((char*)&val,sizeof(val));\n\n        val=RV_sigma_v;\n        Fout.write((char*)&val,sizeof(val));\n        for (int k=0;k<3;k++) for (int n=0;n<3;n++) val9[k*3+n]=RV_veldisp(k,n);\n        Fout.write((char*)val9,sizeof(val)*9);\n\n        val=RV_lambda_B;\n        Fout.write((char*)&val,sizeof(val));\n        for (int k=0;k<3;k++) val3[k]=RV_J[k];\n        Fout.write((char*)val3,sizeof(val)*3);\n\n        val=RV_q;\n        Fout.write((char*)&val,sizeof(val));\n        val=RV_s;\n        Fout.write((char*)&val,sizeof(val));\n        for (int k=0;k<3;k++) for (int n=0;n<3;n++) val9[k*3+n]=RV_eigvec(k,n);\n        Fout.write((char*)val9,sizeof(val)*9);\n\n        if (opt.iextrahalooutput) {\n            for (int k=0;k<3;k++) val3[k]=gJ200m[k];\n            Fout.write((char*)val3,sizeof(val)*3);\n            for (int k=0;k<3;k++) val3[k]=gJ200c[k];\n            Fout.write((char*)val3,sizeof(val)*3);\n            for (int k=0;k<3;k++) val3[k]=gJBN98[k];\n            Fout.write((char*)val3,sizeof(val)*3);\n            if (opt.iInclusiveHalo>0) {\n                val=gM200m_excl;\n                Fout.write((char*)&val,sizeof(val));\n                val=gM200c_excl;\n                Fout.write((char*)&val,sizeof(val));\n                val=gMBN98_excl;\n                Fout.write((char*)&val,sizeof(val));\n\n                val=gR200m_excl;\n                Fout.write((char*)&val,sizeof(val));\n                val=gR200c_excl;\n                Fout.write((char*)&val,sizeof(val));\n                val=gRBN98_excl;\n                Fout.write((char*)&val,sizeof(val));\n\n                for (int k=0;k<3;k++) val3[k]=gJ200m_excl[k];\n                Fout.write((char*)val3,sizeof(val)*3);\n                for (int k=0;k<3;k++) val3[k]=gJ200c_excl[k];\n                Fout.write((char*)val3,sizeof(val)*3);\n                for (int k=0;k<3;k++) val3[k]=gJBN98_excl[k];\n                Fout.write((char*)val3,sizeof(val)*3);\n            }\n        }\n#ifdef GASON\n        idval=n_gas;\n        Fout.write((char*)&idval,sizeof(idval));\n        val=M_gas;\n        Fout.write((char*)&val,sizeof(val));\n        val=M_gas_rvmax;\n        Fout.write((char*)&val,sizeof(val));\n        val=M_gas_30kpc;\n        Fout.write((char*)&val,sizeof(val));\n        val=M_gas_500c;\n        Fout.write((char*)&val,sizeof(val));\n\n        for (int k=0;k<3;k++) val3[k]=cm_gas[k];\n        Fout.write((char*)val3,sizeof(val)*3);\n        for (int k=0;k<3;k++) val3[k]=cmvel_gas[k];\n        Fout.write((char*)val3,sizeof(val)*3);\n\n        val=Efrac_gas;\n        Fout.write((char*)&val,sizeof(val));\n\n        val=Rhalfmass_gas;\n        Fout.write((char*)&val,sizeof(val));\n\n        for (int k=0;k<3;k++) for (int n=0;n<3;n++) val9[k*3+n]=veldisp_gas(k,n);\n        Fout.write((char*)val9,sizeof(val)*9);\n\n        for (int k=0;k<3;k++) val3[k]=L_gas[k];\n        Fout.write((char*)val3,sizeof(val)*3);\n\n        val=q_gas;\n        Fout.write((char*)&val,sizeof(val));\n        val=s_gas;\n        Fout.write((char*)&val,sizeof(val));\n        for (int k=0;k<3;k++) for (int n=0;n<3;n++) val9[k*3+n]=eigvec_gas(k,n);\n        Fout.write((char*)val9,sizeof(val)*9);\n\n        val=Krot_gas;\n        Fout.write((char*)&val,sizeof(val));\n        val=Temp_mean_gas;\n        Fout.write((char*)&val,sizeof(val));\n\n#ifdef STARON\n        val=Z_mean_gas;\n        Fout.write((char*)&val,sizeof(val));\n        val=SFR_gas;\n        Fout.write((char*)&val,sizeof(val));\n#endif\n\n    if (opt.iextragasoutput) {\n        val=M_200mean_gas;\n        Fout.write((char*)&val,sizeof(val));\n        val=M_200crit_gas;\n        Fout.write((char*)&val,sizeof(val));\n        val=M_BN98_gas;\n        Fout.write((char*)&val,sizeof(val));\n        for (int k=0;k<3;k++) val3[k]=L_200mean_gas[k];\n        Fout.write((char*)val3,sizeof(val)*3);\n        for (int k=0;k<3;k++) val3[k]=L_200crit_gas[k];\n        Fout.write((char*)val3,sizeof(val)*3);\n        for (int k=0;k<3;k++) val3[k]=L_BN98_gas[k];\n        Fout.write((char*)val3,sizeof(val)*3);\n        if (opt.iInclusiveHalo>0) {\n            val=M_200mean_excl_gas;\n            Fout.write((char*)&val,sizeof(val));\n            val=M_200crit_excl_gas;\n            Fout.write((char*)&val,sizeof(val));\n            val=M_BN98_excl_gas;\n            Fout.write((char*)&val,sizeof(val));\n            for (int k=0;k<3;k++) val3[k]=L_200mean_excl_gas[k];\n            Fout.write((char*)val3,sizeof(val)*3);\n            for (int k=0;k<3;k++) val3[k]=L_200crit_excl_gas[k];\n            Fout.write((char*)val3,sizeof(val)*3);\n            for (int k=0;k<3;k++) val3[k]=L_BN98_excl_gas[k];\n            Fout.write((char*)val3,sizeof(val)*3);\n        }\n    }\n#endif\n\n#ifdef STARON\n        idval=n_star;\n        Fout.write((char*)&idval,sizeof(idval));\n        val=M_star;\n        Fout.write((char*)&val,sizeof(val));\n        val=M_star_rvmax;\n        Fout.write((char*)&val,sizeof(val));\n        val=M_star_30kpc;\n        Fout.write((char*)&val,sizeof(val));\n        val=M_star_500c;\n        Fout.write((char*)&val,sizeof(val));\n\n        for (int k=0;k<3;k++) val3[k]=cm_star[k];\n        Fout.write((char*)val3,sizeof(val)*3);\n        for (int k=0;k<3;k++) val3[k]=cmvel_star[k];\n        Fout.write((char*)val3,sizeof(val)*3);\n\n        val=Efrac_star;\n        Fout.write((char*)&val,sizeof(val));\n\n        val=Rhalfmass_star;\n        Fout.write((char*)&val,sizeof(val));\n\n        for (int k=0;k<3;k++) for (int n=0;n<3;n++) val9[k*3+n]=veldisp_star(k,n);\n        Fout.write((char*)val9,sizeof(val)*9);\n\n        for (int k=0;k<3;k++) val3[k]=L_star[k];\n        Fout.write((char*)val3,sizeof(val)*3);\n\n        val=q_star;\n        Fout.write((char*)&val,sizeof(val));\n        val=s_star;\n        Fout.write((char*)&val,sizeof(val));\n        for (int k=0;k<3;k++) for (int n=0;n<3;n++) val9[k*3+n]=eigvec_star(k,n);\n        Fout.write((char*)val9,sizeof(val)*9);\n\n        val=Krot_star;\n        Fout.write((char*)&val,sizeof(val));\n        val=t_mean_star;\n        Fout.write((char*)&val,sizeof(val));\n        val=Z_mean_star;\n        Fout.write((char*)&val,sizeof(val));\n\n        if (opt.iextrastaroutput) {\n            val=M_200mean_star;\n            Fout.write((char*)&val,sizeof(val));\n            val=M_200crit_star;\n            Fout.write((char*)&val,sizeof(val));\n            val=M_BN98_star;\n            Fout.write((char*)&val,sizeof(val));\n            for (int k=0;k<3;k++) val3[k]=L_200mean_star[k];\n            Fout.write((char*)val3,sizeof(val)*3);\n            for (int k=0;k<3;k++) val3[k]=L_200crit_star[k];\n            Fout.write((char*)val3,sizeof(val)*3);\n            for (int k=0;k<3;k++) val3[k]=L_BN98_star[k];\n            Fout.write((char*)val3,sizeof(val)*3);\n            if (opt.iInclusiveHalo>0) {\n                val=M_200mean_excl_star;\n                Fout.write((char*)&val,sizeof(val));\n                val=M_200crit_excl_star;\n                Fout.write((char*)&val,sizeof(val));\n                val=M_BN98_excl_star;\n                Fout.write((char*)&val,sizeof(val));\n                for (int k=0;k<3;k++) val3[k]=L_200mean_excl_star[k];\n                Fout.write((char*)val3,sizeof(val)*3);\n                for (int k=0;k<3;k++) val3[k]=L_200crit_excl_star[k];\n                Fout.write((char*)val3,sizeof(val)*3);\n                for (int k=0;k<3;k++) val3[k]=L_BN98_excl_star[k];\n                Fout.write((char*)val3,sizeof(val)*3);\n            }\n        }\n#endif\n\n#ifdef BHON\n        idval=n_bh;\n        Fout.write((char*)&idval,sizeof(idval));\n        val=M_bh;\n        Fout.write((char*)&val,sizeof(val));\n#endif\n#ifdef HIGHRES\n        idval=n_interloper;\n        Fout.write((char*)&idval,sizeof(idval));\n        val=M_interloper;\n        Fout.write((char*)&val,sizeof(val));\n#endif\n\n#if defined(GASON) && defined(STARON)\n    val=M_gas_sf;\n    Fout.write((char*)&val,sizeof(val));\n    val=Rhalfmass_gas_sf;\n    Fout.write((char*)&val,sizeof(val));\n    val=sigV_gas_sf;\n    Fout.write((char*)&val,sizeof(val));\n    for (int k=0;k<3;k++) val3[k]=L_gas_sf[k];\n    Fout.write((char*)val3,sizeof(val)*3);\n    val=Krot_gas_sf;\n    Fout.write((char*)&val,sizeof(val));\n    val=Temp_mean_gas_sf;\n    Fout.write((char*)&val,sizeof(val));\n    val=Z_mean_gas_sf;\n    Fout.write((char*)&val,sizeof(val));\n\n    if (opt.iextragasoutput) {\n    val=M_200mean_gas_sf;\n    Fout.write((char*)&val,sizeof(val));\n    val=M_200crit_gas_sf;\n    Fout.write((char*)&val,sizeof(val));\n    val=M_BN98_gas_sf;\n    Fout.write((char*)&val,sizeof(val));\n    for (int k=0;k<3;k++) val3[k]=L_200mean_gas_sf[k];\n    Fout.write((char*)val3,sizeof(val)*3);\n    for (int k=0;k<3;k++) val3[k]=L_200crit_gas_sf[k];\n    Fout.write((char*)val3,sizeof(val)*3);\n    for (int k=0;k<3;k++) val3[k]=L_BN98_gas_sf[k];\n    Fout.write((char*)val3,sizeof(val)*3);\n    if (opt.iInclusiveHalo>0) {\n        val=M_200mean_excl_gas_sf;\n        Fout.write((char*)&val,sizeof(val));\n        val=M_200crit_excl_gas_sf;\n        Fout.write((char*)&val,sizeof(val));\n        val=M_BN98_excl_gas_sf;\n        Fout.write((char*)&val,sizeof(val));\n        for (int k=0;k<3;k++) val3[k]=L_200mean_excl_gas_sf[k];\n        Fout.write((char*)val3,sizeof(val)*3);\n        for (int k=0;k<3;k++) val3[k]=L_200crit_excl_gas_sf[k];\n        Fout.write((char*)val3,sizeof(val)*3);\n        for (int k=0;k<3;k++) val3[k]=L_BN98_excl_gas_sf[k];\n        Fout.write((char*)val3,sizeof(val)*3);\n    }\n    }\n\n    val=M_gas_nsf;\n    Fout.write((char*)&val,sizeof(val));\n    val=Rhalfmass_gas_nsf;\n    Fout.write((char*)&val,sizeof(val));\n    val=sigV_gas_nsf;\n    Fout.write((char*)&val,sizeof(val));\n    for (int k=0;k<3;k++) val3[k]=L_gas_nsf[k];\n    Fout.write((char*)val3,sizeof(val)*3);\n    val=Krot_gas_nsf;\n    Fout.write((char*)&val,sizeof(val));\n    val=Temp_mean_gas_nsf;\n    Fout.write((char*)&val,sizeof(val));\n    val=Z_mean_gas_nsf;\n    Fout.write((char*)&val,sizeof(val));\n\n    if (opt.iextragasoutput) {\n    val=M_200mean_gas_nsf;\n    Fout.write((char*)&val,sizeof(val));\n    val=M_200crit_gas_nsf;\n    Fout.write((char*)&val,sizeof(val));\n    val=M_BN98_gas_nsf;\n    Fout.write((char*)&val,sizeof(val));\n    for (int k=0;k<3;k++) val3[k]=L_200mean_gas_nsf[k];\n    Fout.write((char*)val3,sizeof(val)*3);\n    for (int k=0;k<3;k++) val3[k]=L_200crit_gas_nsf[k];\n    Fout.write((char*)val3,sizeof(val)*3);\n    for (int k=0;k<3;k++) val3[k]=L_BN98_gas_nsf[k];\n    Fout.write((char*)val3,sizeof(val)*3);\n    if (opt.iInclusiveHalo>0) {\n        val=M_200mean_excl_gas_nsf;\n        Fout.write((char*)&val,sizeof(val));\n        val=M_200crit_excl_gas_nsf;\n        Fout.write((char*)&val,sizeof(val));\n        val=M_BN98_excl_gas_nsf;\n        Fout.write((char*)&val,sizeof(val));\n        for (int k=0;k<3;k++) val3[k]=L_200mean_excl_gas_nsf[k];\n        Fout.write((char*)val3,sizeof(val)*3);\n        for (int k=0;k<3;k++) val3[k]=L_200crit_excl_gas_nsf[k];\n        Fout.write((char*)val3,sizeof(val)*3);\n        for (int k=0;k<3;k++) val3[k]=L_BN98_excl_gas_nsf[k];\n        Fout.write((char*)val3,sizeof(val)*3);\n    }\n    }\n#endif\n        if (opt.iaperturecalc && opt.aperturenum>0){\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout.write((char*)&aperture_npart[j],sizeof(int));\n            }\n#ifdef GASON\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout.write((char*)&aperture_npart_gas[j],sizeof(int));\n            }\n#ifdef STARON\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout.write((char*)&aperture_npart_gas_sf[j],sizeof(int));\n            }\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout.write((char*)&aperture_npart_gas_nsf[j],sizeof(int));\n            }\n#endif\n#endif\n#ifdef STARON\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout.write((char*)&aperture_npart_star[j],sizeof(int));\n            }\n#endif\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout.write((char*)&aperture_mass[j],sizeof(val));\n            }\n            #ifdef GASON\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout.write((char*)&aperture_mass_gas[j],sizeof(val));\n            }\n            #ifdef STARON\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout.write((char*)&aperture_mass_gas_sf[j],sizeof(val));\n            }\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout.write((char*)&aperture_mass_gas_nsf[j],sizeof(val));\n            }\n            #endif\n            #endif\n            #ifdef STARON\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout.write((char*)&aperture_mass_star[j],sizeof(val));\n            }\n            #endif\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout.write((char*)&aperture_rhalfmass[j],sizeof(val));\n            }\n#ifdef GASON\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout.write((char*)&aperture_rhalfmass_gas[j],sizeof(val));\n            }\n#ifdef STARON\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout.write((char*)&aperture_rhalfmass_gas_sf[j],sizeof(val));\n            }\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout.write((char*)&aperture_rhalfmass_gas_nsf[j],sizeof(val));\n            }\n#endif\n#endif\n#ifdef STARON\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout.write((char*)&aperture_rhalfmass_star[j],sizeof(val));\n            }\n#endif\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout.write((char*)&aperture_veldisp[j],sizeof(val));\n            }\n#ifdef GASON\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout.write((char*)&aperture_veldisp_gas[j],sizeof(val));\n            }\n#ifdef STARON\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout.write((char*)&aperture_veldisp_gas_sf[j],sizeof(val));\n            }\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout.write((char*)&aperture_veldisp_gas_nsf[j],sizeof(val));\n            }\n#endif\n#endif\n#ifdef STARON\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout.write((char*)&aperture_veldisp_star[j],sizeof(val));\n            }\n#endif\n#if defined(GASON) && defined(STARON)\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout.write((char*)&aperture_SFR_gas[j],sizeof(val));\n            }\n#endif\n        }\n        if (opt.iaperturecalc && opt.apertureprojnum>0){\n            for (auto k=0;k<3;k++) {\n            for (auto j=0;j<opt.apertureprojnum;j++) {\n                Fout.write((char*)&aperture_mass_proj[j][k],sizeof(val));\n            }\n            #ifdef GASON\n            for (auto j=0;j<opt.apertureprojnum;j++) {\n                Fout.write((char*)&aperture_mass_proj_gas[j][k],sizeof(val));\n            }\n            #ifdef STARON\n            for (auto j=0;j<opt.apertureprojnum;j++) {\n                Fout.write((char*)&aperture_mass_proj_gas_sf[j][k],sizeof(val));\n            }\n            for (auto j=0;j<opt.apertureprojnum;j++) {\n                Fout.write((char*)&aperture_mass_proj_gas_nsf[j][k],sizeof(val));\n            }\n            #endif\n            #endif\n            #ifdef STARON\n            for (auto j=0;j<opt.apertureprojnum;j++) {\n                Fout.write((char*)&aperture_mass_proj_star[j][k],sizeof(val));\n            }\n            #endif\n            for (auto j=0;j<opt.apertureprojnum;j++) {\n                Fout.write((char*)&aperture_rhalfmass_proj[j][k],sizeof(val));\n            }\n            #ifdef GASON\n            for (auto j=0;j<opt.apertureprojnum;j++) {\n                Fout.write((char*)&aperture_rhalfmass_proj_gas[j][k],sizeof(val));\n            }\n            #ifdef STARON\n            for (auto j=0;j<opt.apertureprojnum;j++) {\n                Fout.write((char*)&aperture_rhalfmass_proj_gas_sf[j][k],sizeof(val));\n            }\n            for (auto j=0;j<opt.apertureprojnum;j++) {\n                Fout.write((char*)&aperture_rhalfmass_proj_gas_nsf[j][k],sizeof(val));\n            }\n            #endif\n            #endif\n            #ifdef STARON\n            for (auto j=0;j<opt.apertureprojnum;j++) {\n                Fout.write((char*)&aperture_rhalfmass_proj_star[j][k],sizeof(val));\n            }\n            #endif\n#if defined(GASON) && defined(STARON)\n            for (auto j=0;j<opt.apertureprojnum;j++) {\n                Fout.write((char*)&aperture_SFR_proj_gas[j][k],sizeof(val));\n            }\n#endif\n            }\n        }\n        if (opt.SOnum>0){\n            for (auto j=0;j<opt.SOnum;j++) {\n                Fout.write((char*)&SO_mass[j],sizeof(int));\n            }\n            for (auto j=0;j<opt.SOnum;j++) {\n                Fout.write((char*)&SO_radius[j],sizeof(int));\n            }\n#ifdef GASON\n            if (opt.iextragasoutput && opt.iextrahalooutput)\n            for (auto j=0;j<opt.SOnum;j++) {\n                Fout.write((char*)&SO_mass_gas[j],sizeof(int));\n            }\n#ifdef STARON\n#endif\n#endif\n#ifdef STARON\n            if (opt.iextrastaroutput && opt.iextrahalooutput)\n            for (auto j=0;j<opt.SOnum;j++) {\n                Fout.write((char*)&SO_mass_star[j],sizeof(int));\n            }\n#endif\n        }\n        if (opt.SOnum>0 && opt.iextrahalooutput){\n            for (auto j=0;j<opt.SOnum;j++) {\n                for (auto k=0;k<3;k++) Fout.write((char*)&SO_angularmomentum[j][k],sizeof(int));\n\n            }\n#ifdef GASON\n            if (opt.iextragasoutput)\n            for (auto j=0;j<opt.SOnum;j++) {\n                for (auto k=0;k<3;k++) Fout.write((char*)&SO_angularmomentum_gas[j][k],sizeof(int));\n            }\n#ifdef STARON\n#endif\n#endif\n#ifdef STARON\n            if (opt.iextrastaroutput)\n            for (auto j=0;j<opt.SOnum;j++) {\n                for (auto k=0;k<3;k++) Fout.write((char*)&SO_angularmomentum_star[j][k],sizeof(int));\n            }\n#endif\n        }\n    }\n\n    ///write (append) the properties data to an already open ascii file\n    void WriteAscii(fstream &Fout, Options&opt){\n        Fout<<haloid<<\" \";\n        Fout<<ibound<<\" \";\n        Fout<<iminpot<<\" \";\n        Fout<<hostid<<\" \";\n        Fout<<numsubs<<\" \";\n        Fout<<num<<\" \";\n        Fout<<stype<<\" \";\n        if (opt.iKeepFOF==1) {\n            Fout<<directhostid<<\" \";\n            Fout<<hostfofid<<\" \";\n        }\n        Fout<<gMvir<<\" \";\n        for (int k=0;k<3;k++) Fout<<gcm[k]<<\" \";\n        for (int k=0;k<3;k++) Fout<<gposmbp[k]<<\" \";\n        for (int k=0;k<3;k++) Fout<<gposminpot[k]<<\" \";\n        for (int k=0;k<3;k++) Fout<<gcmvel[k]<<\" \";\n        for (int k=0;k<3;k++) Fout<<gvelmbp[k]<<\" \";\n        for (int k=0;k<3;k++) Fout<<gvelminpot[k]<<\" \";\n        Fout<<gmass<<\" \";\n        Fout<<gMFOF<<\" \";\n        Fout<<gM200m<<\" \";\n        Fout<<gM200c<<\" \";\n        Fout<<gMBN98<<\" \";\n        Fout<<Efrac<<\" \";\n        Fout<<gRvir<<\" \";\n        Fout<<gsize<<\" \";\n        Fout<<gR200m<<\" \";\n        Fout<<gR200c<<\" \";\n        Fout<<gRBN98<<\" \";\n        Fout<<gRhalfmass<<\" \";\n        Fout<<gRmaxvel<<\" \";\n        Fout<<gmaxvel<<\" \";\n        Fout<<gsigma_v<<\" \";\n        for (int k=0;k<3;k++) for (int n=0;n<3;n++) Fout<<gveldisp(k,n)<<\" \";\n        Fout<<glambda_B<<\" \";\n        for (int k=0;k<3;k++) Fout<<gJ[k]<<\" \";\n        Fout<<gq<<\" \";\n        Fout<<gs<<\" \";\n        for (int k=0;k<3;k++) for (int n=0;n<3;n++) Fout<<geigvec(k,n)<<\" \";\n        Fout<<cNFW<<\" \";\n        Fout<<Krot<<\" \";\n        Fout<<T<<\" \";\n        Fout<<Pot<<\" \";\n\n        Fout<<RV_sigma_v<<\" \";\n        for (int k=0;k<3;k++) for (int n=0;n<3;n++) Fout<<RV_veldisp(k,n)<<\" \";\n        Fout<<RV_lambda_B<<\" \";\n        for (int k=0;k<3;k++) Fout<<RV_J[k]<<\" \";\n        Fout<<RV_q<<\" \";\n        Fout<<RV_s<<\" \";\n        for (int k=0;k<3;k++) for (int n=0;n<3;n++) Fout<<RV_eigvec(k,n)<<\" \";\n\n        if (opt.iextrahalooutput) {\n            for (int k=0;k<3;k++) Fout<<gJ200m[k]<<\" \";\n            for (int k=0;k<3;k++) Fout<<gJ200c[k]<<\" \";\n            for (int k=0;k<3;k++) Fout<<gJBN98[k]<<\" \";\n            if (opt.iInclusiveHalo>0) {\n                Fout<<gM200m_excl<<\" \";\n                Fout<<gM200c_excl<<\" \";\n                Fout<<gMBN98_excl<<\" \";\n                Fout<<gR200m_excl<<\" \";\n                Fout<<gR200c_excl<<\" \";\n                Fout<<gRBN98_excl<<\" \";\n                for (int k=0;k<3;k++) Fout<<gJ200m_excl[k]<<\" \";\n                for (int k=0;k<3;k++) Fout<<gJ200c_excl[k]<<\" \";\n                for (int k=0;k<3;k++) Fout<<gJBN98_excl[k]<<\" \";\n            }\n        }\n\n#ifdef GASON\n        Fout<<n_gas<<\" \";\n        Fout<<M_gas<<\" \";\n        Fout<<M_gas_rvmax<<\" \";\n        Fout<<M_gas_30kpc<<\" \";\n        //Fout<<M_gas_50kpc<<\" \";\n        Fout<<M_gas_500c<<\" \";\n        for (int k=0;k<3;k++) Fout<<cm_gas[k]<<\" \";\n        for (int k=0;k<3;k++) Fout<<cmvel_gas[k]<<\" \";\n        Fout<<Efrac_gas<<\" \";\n        Fout<<Rhalfmass_gas<<\" \";\n        for (int k=0;k<3;k++) for (int n=0;n<3;n++) Fout<<veldisp_gas(k,n)<<\" \";\n        for (int k=0;k<3;k++) Fout<<L_gas[k]<<\" \";\n        Fout<<q_gas<<\" \";\n        Fout<<s_gas<<\" \";\n        for (int k=0;k<3;k++) for (int n=0;n<3;n++) Fout<<eigvec_gas(k,n)<<\" \";\n        Fout<<Krot_gas<<\" \";\n        Fout<<Temp_mean_gas<<\" \";\n#ifdef STARON\n        Fout<<Z_mean_gas<<\" \";\n        Fout<<SFR_gas<<\" \";\n#endif\n    if (opt.iextragasoutput) {\n        Fout<<M_200mean_gas<<\" \";\n        Fout<<M_200crit_gas<<\" \";\n        Fout<<M_BN98_gas<<\" \";\n        for (int k=0;k<3;k++) Fout<<L_200mean_gas[k]<<\" \";\n        for (int k=0;k<3;k++) Fout<<L_200crit_gas[k]<<\" \";\n        for (int k=0;k<3;k++) Fout<<L_BN98_gas[k]<<\" \";\n        if (opt.iInclusiveHalo>0) {\n            Fout<<M_200mean_excl_gas<<\" \";\n            Fout<<M_200crit_excl_gas<<\" \";\n            Fout<<M_BN98_excl_gas<<\" \";\n            for (int k=0;k<3;k++) Fout<<L_200mean_excl_gas[k]<<\" \";\n            for (int k=0;k<3;k++) Fout<<L_200crit_excl_gas[k]<<\" \";\n            for (int k=0;k<3;k++) Fout<<L_BN98_excl_gas[k]<<\" \";\n        }\n    }\n#endif\n\n#ifdef STARON\n        Fout<<n_star<<\" \";\n        Fout<<M_star<<\" \";\n        Fout<<M_star_rvmax<<\" \";\n        Fout<<M_star_30kpc<<\" \";\n        //Fout<<M_star_50kpc<<\" \";\n        Fout<<M_star_500c<<\" \";\n        for (int k=0;k<3;k++) Fout<<cm_star[k]<<\" \";\n        for (int k=0;k<3;k++) Fout<<cmvel_star[k]<<\" \";\n        Fout<<Efrac_star<<\" \";\n        Fout<<Rhalfmass_star<<\" \";\n        for (int k=0;k<3;k++) for (int n=0;n<3;n++) Fout<<veldisp_star(k,n)<<\" \";\n        for (int k=0;k<3;k++) Fout<<L_star[k]<<\" \";\n        Fout<<q_star<<\" \";\n        Fout<<s_star<<\" \";\n        for (int k=0;k<3;k++) for (int n=0;n<3;n++) Fout<<eigvec_star(k,n)<<\" \";\n        Fout<<Krot_star<<\" \";\n        Fout<<t_mean_star<<\" \";\n        Fout<<Z_mean_star<<\" \";\n        if (opt.iextrastaroutput) {\n            Fout<<M_200mean_star<<\" \";\n            Fout<<M_200crit_star<<\" \";\n            Fout<<M_BN98_star<<\" \";\n            for (int k=0;k<3;k++) Fout<<L_200mean_star[k]<<\" \";\n            for (int k=0;k<3;k++) Fout<<L_200crit_star[k]<<\" \";\n            for (int k=0;k<3;k++) Fout<<L_BN98_star[k]<<\" \";\n            if (opt.iInclusiveHalo>0) {\n                Fout<<M_200mean_excl_star<<\" \";\n                Fout<<M_200crit_excl_star<<\" \";\n                Fout<<M_BN98_excl_star<<\" \";\n                for (int k=0;k<3;k++) Fout<<L_200mean_excl_star[k]<<\" \";\n                for (int k=0;k<3;k++) Fout<<L_200crit_excl_star[k]<<\" \";\n                for (int k=0;k<3;k++) Fout<<L_BN98_excl_star[k]<<\" \";\n            }\n        }\n#endif\n\n#ifdef BHON\n        Fout<<n_bh<<\" \";\n        Fout<<M_bh<<\" \";\n#endif\n#ifdef HIGHRES\n        Fout<<n_interloper<<\" \";\n        Fout<<M_interloper<<\" \";\n        if (opt.iextrainterloperoutput) {\n            Fout<<M_200mean_interloper<<\" \";\n            Fout<<M_200crit_interloper<<\" \";\n            Fout<<M_BN98_interloper<<\" \";\n            if (opt.iInclusiveHalo>0) {\n                Fout<<M_200mean_excl_interloper<<\" \";\n                Fout<<M_200crit_excl_interloper<<\" \";\n                Fout<<M_BN98_excl_interloper<<\" \";\n            }\n        }\n#endif\n\n#if defined(GASON) && defined(STARON)\n        Fout<<M_gas_sf<<\" \";\n        Fout<<Rhalfmass_gas_sf<<\" \";\n        Fout<<sigV_gas_sf<<\" \";\n        for (int k=0;k<3;k++) Fout<<L_gas_sf[k]<<\" \";\n        Fout<<Krot_gas_sf<<\" \";\n        Fout<<Temp_mean_gas_sf<<\" \";\n        Fout<<Z_mean_gas_sf<<\" \";\n        if (opt.iextragasoutput) {\n            Fout<<M_200mean_gas_sf<<\" \";\n            Fout<<M_200crit_gas_sf<<\" \";\n            Fout<<M_BN98_gas_sf<<\" \";\n            for (int k=0;k<3;k++) Fout<<L_200mean_gas_sf[k]<<\" \";\n            for (int k=0;k<3;k++) Fout<<L_200crit_gas_sf[k]<<\" \";\n            for (int k=0;k<3;k++) Fout<<L_BN98_gas_sf[k]<<\" \";\n            if (opt.iInclusiveHalo>0) {\n                Fout<<M_200mean_excl_gas_sf<<\" \";\n                Fout<<M_200crit_excl_gas_sf<<\" \";\n                Fout<<M_BN98_excl_gas_sf<<\" \";\n                for (int k=0;k<3;k++) Fout<<L_200mean_excl_gas_sf[k]<<\" \";\n                for (int k=0;k<3;k++) Fout<<L_200crit_excl_gas_sf[k]<<\" \";\n                for (int k=0;k<3;k++) Fout<<L_BN98_excl_gas_sf[k]<<\" \";\n            }\n        }\n        Fout<<M_gas_nsf<<\" \";\n        Fout<<Rhalfmass_gas_nsf<<\" \";\n        Fout<<sigV_gas_nsf<<\" \";\n        for (int k=0;k<3;k++) Fout<<L_gas_nsf[k]<<\" \";\n        Fout<<Krot_gas_nsf<<\" \";\n        Fout<<Temp_mean_gas_nsf<<\" \";\n        Fout<<Z_mean_gas_nsf<<\" \";\n        if (opt.iextragasoutput) {\n            Fout<<M_200mean_gas_nsf<<\" \";\n            Fout<<M_200crit_gas_nsf<<\" \";\n            Fout<<M_BN98_gas_nsf<<\" \";\n            for (int k=0;k<3;k++) Fout<<L_200mean_gas_nsf[k]<<\" \";\n            for (int k=0;k<3;k++) Fout<<L_200crit_gas_nsf[k]<<\" \";\n            for (int k=0;k<3;k++) Fout<<L_BN98_gas_nsf[k]<<\" \";\n            if (opt.iInclusiveHalo>0) {\n                Fout<<M_200mean_excl_gas_nsf<<\" \";\n                Fout<<M_200crit_excl_gas_nsf<<\" \";\n                Fout<<M_BN98_excl_gas_nsf<<\" \";\n                for (int k=0;k<3;k++) Fout<<L_200mean_excl_gas_nsf[k]<<\" \";\n                for (int k=0;k<3;k++) Fout<<L_200crit_excl_gas_nsf[k]<<\" \";\n                for (int k=0;k<3;k++) Fout<<L_BN98_excl_gas_nsf[k]<<\" \";\n            }\n        }\n#endif\n\n        if (opt.iaperturecalc && opt.aperturenum>0){\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout<<aperture_npart[j]<<\" \";\n            }\n#ifdef GASON\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout<<aperture_npart_gas[j]<<\" \";\n            }\n#ifdef STARON\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout<<aperture_npart_gas_sf[j]<<\" \";\n            }\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout<<aperture_npart_gas_nsf[j]<<\" \";\n            }\n#endif\n#endif\n#ifdef STARON\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout<<aperture_npart_star[j]<<\" \";\n            }\n#endif\n#ifdef HIGHRES\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout<<aperture_npart_interloper[j]<<\" \";\n            }\n#endif\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout<<aperture_mass[j]<<\" \";\n            }\n            #ifdef GASON\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout<<aperture_mass_gas[j]<<\" \";\n            }\n            #ifdef STARON\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout<<aperture_mass_gas_sf[j]<<\" \";\n            }\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout<<aperture_mass_gas_nsf[j]<<\" \";\n            }\n#endif\n#endif\n#ifdef STARON\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout<<aperture_mass_star[j]<<\" \";\n            }\n#endif\n#ifdef HIGHRES\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout<<aperture_mass_interloper[j]<<\" \";\n            }\n#endif\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout<<aperture_rhalfmass[j]<<\" \";\n            }\n            #ifdef GASON\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout<<aperture_rhalfmass_gas[j]<<\" \";\n            }\n            #ifdef STARON\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout<<aperture_rhalfmass_gas_sf[j]<<\" \";\n            }\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout<<aperture_rhalfmass_gas_nsf[j]<<\" \";\n            }\n            #endif\n            #endif\n            #ifdef STARON\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout<<aperture_rhalfmass_star[j]<<\" \";\n            }\n            #endif\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout<<aperture_veldisp[j]<<\" \";\n            }\n#ifdef GASON\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout<<aperture_veldisp_gas[j]<<\" \";\n            }\n#ifdef STARON\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout<<aperture_veldisp_gas_sf[j]<<\" \";\n            }\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout<<aperture_veldisp_gas_nsf[j]<<\" \";\n            }\n#endif\n#endif\n#ifdef STARON\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout<<aperture_veldisp_star[j]<<\" \";\n            }\n#endif\n#if defined(GASON) && defined(STARON)\n            for (auto j=0;j<opt.aperturenum;j++) {\n                Fout<<aperture_SFR_gas[j]<<\" \";\n            }\n#endif\n        }\n        if (opt.iaperturecalc && opt.apertureprojnum>0) {\n            for (auto k=0;k<3;k++) {\n            for (auto j=0;j<opt.apertureprojnum;j++){\n                Fout<<aperture_mass_proj[j][k]<<\" \";\n            }\n            #ifdef GASON\n            for (auto j=0;j<opt.apertureprojnum;j++){\n                Fout<<aperture_mass_proj_gas[j][k]<<\" \";\n            }\n            #ifdef STARON\n            for (auto j=0;j<opt.apertureprojnum;j++){\n                Fout<<aperture_mass_proj_gas_sf[j][k]<<\" \";\n            }\n            for (auto j=0;j<opt.apertureprojnum;j++){\n                Fout<<aperture_mass_proj_gas_nsf[j][k]<<\" \";\n            }\n            #endif\n            #endif\n            #ifdef STARON\n            for (auto j=0;j<opt.apertureprojnum;j++){\n                Fout<<aperture_mass_proj_star[j][k]<<\" \";\n            }\n            #endif\n            for (auto j=0;j<opt.apertureprojnum;j++){\n                Fout<<aperture_rhalfmass_proj[j][k]<<\" \";\n            }\n            #ifdef GASON\n            for (auto j=0;j<opt.apertureprojnum;j++){\n                Fout<<aperture_rhalfmass_proj_gas[j][k]<<\" \";\n            }\n            #ifdef STARON\n            for (auto j=0;j<opt.apertureprojnum;j++){\n                Fout<<aperture_rhalfmass_proj_gas_sf[j][k]<<\" \";\n            }\n            for (auto j=0;j<opt.apertureprojnum;j++){\n                Fout<<aperture_rhalfmass_proj_gas_nsf[j][k]<<\" \";\n            }\n            #endif\n            #endif\n            #ifdef STARON\n            for (auto j=0;j<opt.apertureprojnum;j++){\n                Fout<<aperture_rhalfmass_proj_star[j][k]<<\" \";\n            }\n            #endif\n            #if defined(GASON) && defined(STARON)\n            for (auto j=0;j<opt.apertureprojnum;j++) {\n                Fout<<aperture_SFR_proj_gas[j][k]<<\" \";\n            }\n            #endif\n            }\n        }\n        if (opt.SOnum>0){\n            for (auto j=0;j<opt.SOnum;j++) {\n                Fout<<SO_mass[j]<<\" \";\n            }\n            for (auto j=0;j<opt.SOnum;j++) {\n                Fout<<SO_radius[j]<<\" \";\n            }\n#ifdef GASON\n            if (opt.iextragasoutput && opt.iextrahalooutput)\n            for (auto j=0;j<opt.SOnum;j++) {\n                Fout<<SO_mass_gas[j]<<\" \";\n            }\n#ifdef STARON\n#endif\n#endif\n#ifdef STARON\n            if (opt.iextrastaroutput && opt.iextrahalooutput)\n            for (auto j=0;j<opt.SOnum;j++) {\n                Fout<<SO_mass_star[j]<<\" \";\n            }\n#endif\n#ifdef HIGHRES\n            if (opt.iextrainterloperoutput && opt.iextrahalooutput)\n            for (auto j=0;j<opt.SOnum;j++) {\n                Fout<<SO_mass_interloper[j]<<\" \";\n            }\n#endif\n        }\n        if (opt.SOnum>0 && opt.iextrahalooutput){\n            for (auto j=0;j<opt.SOnum;j++) {\n                for (auto k=0;k<3;k++) Fout<<SO_angularmomentum[j][k]<<\" \";\n            }\n#ifdef GASON\n            if (opt.iextragasoutput)\n            for (auto j=0;j<opt.SOnum;j++) {\n                for (auto k=0;k<3;k++) Fout<<SO_angularmomentum_gas[j][k]<<\" \";\n            }\n#ifdef STARON\n#endif\n#endif\n#ifdef STARON\n            if (opt.iextrastaroutput)\n            for (auto j=0;j<opt.SOnum;j++) {\n                for (auto k=0;k<3;k++) Fout<<SO_angularmomentum_star[j][k]<<\" \";\n            }\n#endif\n        }\n        Fout<<endl;\n    }\n#ifdef USEHDF\n    ///write (append) the properties data to an already open hdf file\n    void WriteHDF(H5File &Fhdf, DataSpace *&dataspaces, DataSet *&datasets, Options&opt){\n    };\n#endif\n};\n\n/*! Structures stores header info of the data writen by the \\ref PropData data structure,\n    specifically the \\ref PropData::WriteBinary, \\ref PropData::WriteAscii, \\ref PropData::WriteHDF routines\n    Must ensure that these routines are all altered together so that the io makes sense.\n*/\nstruct PropDataHeader{\n    //list the header info\n    vector<string> headerdatainfo;\n#ifdef USEHDF\n    vector<PredType> predtypeinfo;\n#endif\n#ifdef USEADIOS\n    vector<ADIOS_DATATYPES> adiospredtypeinfo;\n#endif\n    PropDataHeader(Options&opt){\n        int sizeval;\n#ifdef USEHDF\n        vector<PredType> desiredproprealtype;\n        if (sizeof(Double_t)==sizeof(double)) desiredproprealtype.push_back(PredType::NATIVE_DOUBLE);\n        else desiredproprealtype.push_back(PredType::NATIVE_FLOAT);\n#endif\n#ifdef USEADIOS\n        vector<ADIOS_DATATYPES> desiredadiosproprealtype;\n        if (sizeof(Double_t)==sizeof(double)) desiredadiosproprealtype.push_back(ADIOS_DATATYPES::adios_double);\n        else desiredadiosproprealtype.push_back(ADIOS_DATATYPES::adios_real);\n#endif\n\n        headerdatainfo.push_back(\"ID\");\n        headerdatainfo.push_back(\"ID_mbp\");\n        headerdatainfo.push_back(\"ID_minpot\");\n        headerdatainfo.push_back(\"hostHaloID\");\n        headerdatainfo.push_back(\"numSubStruct\");\n        headerdatainfo.push_back(\"npart\");\n        headerdatainfo.push_back(\"Structuretype\");\n        if (opt.iKeepFOF==1){\n            headerdatainfo.push_back(\"hostDirectHaloID\");\n            headerdatainfo.push_back(\"hostFOFID\");\n        }\n\n        //if using hdf, store the type\n#ifdef USEHDF\n        predtypeinfo.push_back(PredType::STD_U64LE);\n        predtypeinfo.push_back(PredType::STD_I64LE);\n        predtypeinfo.push_back(PredType::STD_I64LE);\n        predtypeinfo.push_back(PredType::STD_I64LE);\n        predtypeinfo.push_back(PredType::STD_U64LE);\n        predtypeinfo.push_back(PredType::STD_U64LE);\n        predtypeinfo.push_back(PredType::STD_I32LE);\n        if (opt.iKeepFOF==1){\n            predtypeinfo.push_back(PredType::STD_I64LE);\n            predtypeinfo.push_back(PredType::STD_I64LE);\n        }\n#endif\n#ifdef USEADIOS\n        adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_long);\n        adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_long);\n        adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_long);\n        adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_integer);\n        if (opt.iKeepFOF==1){\n            adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_long);\n            adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_long);\n        }\n#endif\n\n        headerdatainfo.push_back(\"Mvir\");\n        headerdatainfo.push_back(\"Xc\");\n        headerdatainfo.push_back(\"Yc\");\n        headerdatainfo.push_back(\"Zc\");\n        headerdatainfo.push_back(\"Xcmbp\");\n        headerdatainfo.push_back(\"Ycmbp\");\n        headerdatainfo.push_back(\"Zcmbp\");\n        headerdatainfo.push_back(\"Xcminpot\");\n        headerdatainfo.push_back(\"Ycminpot\");\n        headerdatainfo.push_back(\"Zcminpot\");\n        headerdatainfo.push_back(\"VXc\");\n        headerdatainfo.push_back(\"VYc\");\n        headerdatainfo.push_back(\"VZc\");\n        headerdatainfo.push_back(\"VXcmbp\");\n        headerdatainfo.push_back(\"VYcmbp\");\n        headerdatainfo.push_back(\"VZcmbp\");\n        headerdatainfo.push_back(\"VXcminpot\");\n        headerdatainfo.push_back(\"VYcminpot\");\n        headerdatainfo.push_back(\"VZcminpot\");\n        headerdatainfo.push_back(\"Mass_tot\");\n        headerdatainfo.push_back(\"Mass_FOF\");\n        headerdatainfo.push_back(\"Mass_200mean\");\n        headerdatainfo.push_back(\"Mass_200crit\");\n        headerdatainfo.push_back(\"Mass_BN98\");\n        headerdatainfo.push_back(\"Efrac\");\n        headerdatainfo.push_back(\"Rvir\");\n        headerdatainfo.push_back(\"R_size\");\n        headerdatainfo.push_back(\"R_200mean\");\n        headerdatainfo.push_back(\"R_200crit\");\n        headerdatainfo.push_back(\"R_BN98\");\n        headerdatainfo.push_back(\"R_HalfMass\");\n        headerdatainfo.push_back(\"Rmax\");\n        headerdatainfo.push_back(\"Vmax\");\n        headerdatainfo.push_back(\"sigV\");\n        headerdatainfo.push_back(\"veldisp_xx\");\n        headerdatainfo.push_back(\"veldisp_xy\");\n        headerdatainfo.push_back(\"veldisp_xz\");\n        headerdatainfo.push_back(\"veldisp_yx\");\n        headerdatainfo.push_back(\"veldisp_yy\");\n        headerdatainfo.push_back(\"veldisp_yz\");\n        headerdatainfo.push_back(\"veldisp_zx\");\n        headerdatainfo.push_back(\"veldisp_zy\");\n        headerdatainfo.push_back(\"veldisp_zz\");\n        headerdatainfo.push_back(\"lambda_B\");\n        headerdatainfo.push_back(\"Lx\");\n        headerdatainfo.push_back(\"Ly\");\n        headerdatainfo.push_back(\"Lz\");\n        headerdatainfo.push_back(\"q\");\n        headerdatainfo.push_back(\"s\");\n        headerdatainfo.push_back(\"eig_xx\");\n        headerdatainfo.push_back(\"eig_xy\");\n        headerdatainfo.push_back(\"eig_xz\");\n        headerdatainfo.push_back(\"eig_yx\");\n        headerdatainfo.push_back(\"eig_yy\");\n        headerdatainfo.push_back(\"eig_yz\");\n        headerdatainfo.push_back(\"eig_zx\");\n        headerdatainfo.push_back(\"eig_zy\");\n        headerdatainfo.push_back(\"eig_zz\");\n        headerdatainfo.push_back(\"cNFW\");\n        headerdatainfo.push_back(\"Krot\");\n        headerdatainfo.push_back(\"Ekin\");\n        headerdatainfo.push_back(\"Epot\");\n\n        //some properties within RVmax\n        headerdatainfo.push_back(\"RVmax_sigV\");\n        headerdatainfo.push_back(\"RVmax_veldisp_xx\");\n        headerdatainfo.push_back(\"RVmax_veldisp_xy\");\n        headerdatainfo.push_back(\"RVmax_veldisp_xz\");\n        headerdatainfo.push_back(\"RVmax_veldisp_yx\");\n        headerdatainfo.push_back(\"RVmax_veldisp_yy\");\n        headerdatainfo.push_back(\"RVmax_veldisp_yz\");\n        headerdatainfo.push_back(\"RVmax_veldisp_zx\");\n        headerdatainfo.push_back(\"RVmax_veldisp_zy\");\n        headerdatainfo.push_back(\"RVmax_veldisp_zz\");\n        headerdatainfo.push_back(\"RVmax_lambda_B\");\n        headerdatainfo.push_back(\"RVmax_Lx\");\n        headerdatainfo.push_back(\"RVmax_Ly\");\n        headerdatainfo.push_back(\"RVmax_Lz\");\n        headerdatainfo.push_back(\"RVmax_q\");\n        headerdatainfo.push_back(\"RVmax_s\");\n        headerdatainfo.push_back(\"RVmax_eig_xx\");\n        headerdatainfo.push_back(\"RVmax_eig_xy\");\n        headerdatainfo.push_back(\"RVmax_eig_xz\");\n        headerdatainfo.push_back(\"RVmax_eig_yx\");\n        headerdatainfo.push_back(\"RVmax_eig_yy\");\n        headerdatainfo.push_back(\"RVmax_eig_yz\");\n        headerdatainfo.push_back(\"RVmax_eig_zx\");\n        headerdatainfo.push_back(\"RVmax_eig_zy\");\n        headerdatainfo.push_back(\"RVmax_eig_zz\");\n\n        if (opt.iextrahalooutput) {\n            headerdatainfo.push_back(\"Lx_200mean\");\n            headerdatainfo.push_back(\"Ly_200mean\");\n            headerdatainfo.push_back(\"Lz_200mean\");\n            headerdatainfo.push_back(\"Lx_200crit\");\n            headerdatainfo.push_back(\"Ly_200crit\");\n            headerdatainfo.push_back(\"Lz_200crit\");\n            headerdatainfo.push_back(\"Lx_BN98\");\n            headerdatainfo.push_back(\"Ly_BN98\");\n            headerdatainfo.push_back(\"Lz_BN98\");\n            if (opt.iInclusiveHalo>0) {\n                headerdatainfo.push_back(\"Mass_200mean_excl\");\n                headerdatainfo.push_back(\"Mass_200crit_excl\");\n                headerdatainfo.push_back(\"Mass_BN98_excl\");\n                headerdatainfo.push_back(\"R_200mean_excl\");\n                headerdatainfo.push_back(\"R_200crit_excl\");\n                headerdatainfo.push_back(\"R_BN98_excl\");\n                headerdatainfo.push_back(\"Lx_200mean_excl\");\n                headerdatainfo.push_back(\"Ly_200mean_excl\");\n                headerdatainfo.push_back(\"Lz_200mean_excl\");\n                headerdatainfo.push_back(\"Lx_200crit_excl\");\n                headerdatainfo.push_back(\"Ly_200crit_excl\");\n                headerdatainfo.push_back(\"Lz_200crit_excl\");\n                headerdatainfo.push_back(\"Lx_BN98_excl\");\n                headerdatainfo.push_back(\"Ly_BN98_excl\");\n                headerdatainfo.push_back(\"Lz_BN98_excl\");\n            }\n        }\n\n#ifdef USEHDF\n        sizeval=predtypeinfo.size();\n        for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(desiredproprealtype[0]);\n#endif\n#ifdef USEADIOS\n        sizeval=adiospredtypeinfo.size();\n        for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(desiredadiosproprealtype[0]);\n#endif\n\n#ifdef GASON\n        headerdatainfo.push_back(\"n_gas\");\n#ifdef USEHDF\n        predtypeinfo.push_back(PredType::STD_U64LE);\n#endif\n#ifdef USEADIOS\n        adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n#endif\n        headerdatainfo.push_back(\"M_gas\");\n        headerdatainfo.push_back(\"M_gas_Rvmax\");\n        headerdatainfo.push_back(\"M_gas_30kpc\");\n        //headerdatainfo.push_back(\"M_gas_50kpc\");\n        headerdatainfo.push_back(\"M_gas_500c\");\n        headerdatainfo.push_back(\"Xc_gas\");\n        headerdatainfo.push_back(\"Yc_gas\");\n        headerdatainfo.push_back(\"Zc_gas\");\n        headerdatainfo.push_back(\"VXc_gas\");\n        headerdatainfo.push_back(\"VYc_gas\");\n        headerdatainfo.push_back(\"VZc_gas\");\n        headerdatainfo.push_back(\"Efrac_gas\");\n        headerdatainfo.push_back(\"R_HalfMass_gas\");\n        headerdatainfo.push_back(\"veldisp_xx_gas\");\n        headerdatainfo.push_back(\"veldisp_xy_gas\");\n        headerdatainfo.push_back(\"veldisp_xz_gas\");\n        headerdatainfo.push_back(\"veldisp_yx_gas\");\n        headerdatainfo.push_back(\"veldisp_yy_gas\");\n        headerdatainfo.push_back(\"veldisp_yz_gas\");\n        headerdatainfo.push_back(\"veldisp_zx_gas\");\n        headerdatainfo.push_back(\"veldisp_zy_gas\");\n        headerdatainfo.push_back(\"veldisp_zz_gas\");\n        headerdatainfo.push_back(\"Lx_gas\");\n        headerdatainfo.push_back(\"Ly_gas\");\n        headerdatainfo.push_back(\"Lz_gas\");\n        headerdatainfo.push_back(\"q_gas\");\n        headerdatainfo.push_back(\"s_gas\");\n        headerdatainfo.push_back(\"eig_xx_gas\");\n        headerdatainfo.push_back(\"eig_xy_gas\");\n        headerdatainfo.push_back(\"eig_xz_gas\");\n        headerdatainfo.push_back(\"eig_yx_gas\");\n        headerdatainfo.push_back(\"eig_yy_gas\");\n        headerdatainfo.push_back(\"eig_yz_gas\");\n        headerdatainfo.push_back(\"eig_zx_gas\");\n        headerdatainfo.push_back(\"eig_zy_gas\");\n        headerdatainfo.push_back(\"eig_zz_gas\");\n        headerdatainfo.push_back(\"Krot_gas\");\n        headerdatainfo.push_back(\"T_gas\");\n#ifdef STARON\n        headerdatainfo.push_back(\"Zmet_gas\");\n        headerdatainfo.push_back(\"SFR_gas\");\n#endif\n    if (opt.iextragasoutput) {\n        headerdatainfo.push_back(\"Mass_200mean_gas\");\n        headerdatainfo.push_back(\"Mass_200crit_gas\");\n        headerdatainfo.push_back(\"Mass_BN98_gas\");\n        headerdatainfo.push_back(\"Lx_200c_gas\");\n        headerdatainfo.push_back(\"Ly_200c_gas\");\n        headerdatainfo.push_back(\"Lz_200c_gas\");\n        headerdatainfo.push_back(\"Lx_200m_gas\");\n        headerdatainfo.push_back(\"Ly_200m_gas\");\n        headerdatainfo.push_back(\"Lz_200m_gas\");\n        headerdatainfo.push_back(\"Lx_BN98_gas\");\n        headerdatainfo.push_back(\"Ly_BN98_gas\");\n        headerdatainfo.push_back(\"Lz_BN98_gas\");\n        if (opt.iInclusiveHalo>0) {\n            headerdatainfo.push_back(\"Mass_200mean_excl_gas\");\n            headerdatainfo.push_back(\"Mass_200crit_excl_gas\");\n            headerdatainfo.push_back(\"Mass_BN98_excl_gas\");\n            headerdatainfo.push_back(\"Lx_200c_excl_gas\");\n            headerdatainfo.push_back(\"Ly_200c_excl_gas\");\n            headerdatainfo.push_back(\"Lz_200c_excl_gas\");\n            headerdatainfo.push_back(\"Lx_200m_excl_gas\");\n            headerdatainfo.push_back(\"Ly_200m_excl_gas\");\n            headerdatainfo.push_back(\"Lz_200m_excl_gas\");\n            headerdatainfo.push_back(\"Lx_BN98_excl_gas\");\n            headerdatainfo.push_back(\"Ly_BN98_excl_gas\");\n            headerdatainfo.push_back(\"Lz_BN98_excl_gas\");\n        }\n    }\n#ifdef USEHDF\n        sizeval=predtypeinfo.size();\n        for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(desiredproprealtype[0]);\n#endif\n#ifdef USEADIOS\n        sizeval=adiospredtypeinfo.size();\n        for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(desiredadiosproprealtype[0]);\n#endif\n#endif\n\n#ifdef STARON\n        headerdatainfo.push_back(\"n_star\");\n#ifdef USEHDF\n        predtypeinfo.push_back(PredType::STD_U64LE);\n#endif\n#ifdef USEADIOS\n        adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n#endif\n        headerdatainfo.push_back(\"M_star\");\n        headerdatainfo.push_back(\"M_star_Rvmax\");\n        headerdatainfo.push_back(\"M_star_30kpc\");\n        //headerdatainfo.push_back(\"M_star_50kpc\");\n        headerdatainfo.push_back(\"M_star_500c\");\n        headerdatainfo.push_back(\"Xc_star\");\n        headerdatainfo.push_back(\"Yc_star\");\n        headerdatainfo.push_back(\"Zc_star\");\n        headerdatainfo.push_back(\"VXc_star\");\n        headerdatainfo.push_back(\"VYc_star\");\n        headerdatainfo.push_back(\"VZc_star\");\n        headerdatainfo.push_back(\"Efrac_star\");\n        headerdatainfo.push_back(\"R_HalfMass_star\");\n        headerdatainfo.push_back(\"veldisp_xx_star\");\n        headerdatainfo.push_back(\"veldisp_xy_star\");\n        headerdatainfo.push_back(\"veldisp_xz_star\");\n        headerdatainfo.push_back(\"veldisp_yx_star\");\n        headerdatainfo.push_back(\"veldisp_yy_star\");\n        headerdatainfo.push_back(\"veldisp_yz_star\");\n        headerdatainfo.push_back(\"veldisp_zx_star\");\n        headerdatainfo.push_back(\"veldisp_zy_star\");\n        headerdatainfo.push_back(\"veldisp_zz_star\");\n        headerdatainfo.push_back(\"Lx_star\");\n        headerdatainfo.push_back(\"Ly_star\");\n        headerdatainfo.push_back(\"Lz_star\");\n        headerdatainfo.push_back(\"q_star\");\n        headerdatainfo.push_back(\"s_star\");\n        headerdatainfo.push_back(\"eig_xx_star\");\n        headerdatainfo.push_back(\"eig_xy_star\");\n        headerdatainfo.push_back(\"eig_xz_star\");\n        headerdatainfo.push_back(\"eig_yx_star\");\n        headerdatainfo.push_back(\"eig_yy_star\");\n        headerdatainfo.push_back(\"eig_yz_star\");\n        headerdatainfo.push_back(\"eig_zx_star\");\n        headerdatainfo.push_back(\"eig_zy_star\");\n        headerdatainfo.push_back(\"eig_zz_star\");\n        headerdatainfo.push_back(\"Krot_star\");\n        headerdatainfo.push_back(\"tage_star\");\n        headerdatainfo.push_back(\"Zmet_star\");\n        if (opt.iextrastaroutput) {\n            headerdatainfo.push_back(\"Mass_200mean_star\");\n            headerdatainfo.push_back(\"Mass_200crit_star\");\n            headerdatainfo.push_back(\"Mass_BN98_star\");\n            headerdatainfo.push_back(\"Lx_200c_star\");\n            headerdatainfo.push_back(\"Ly_200c_star\");\n            headerdatainfo.push_back(\"Lz_200c_star\");\n            headerdatainfo.push_back(\"Lx_200m_star\");\n            headerdatainfo.push_back(\"Ly_200m_star\");\n            headerdatainfo.push_back(\"Lz_200m_star\");\n            headerdatainfo.push_back(\"Lx_BN98_star\");\n            headerdatainfo.push_back(\"Ly_BN98_star\");\n            headerdatainfo.push_back(\"Lz_BN98_star\");\n            if (opt.iInclusiveHalo>0) {\n                headerdatainfo.push_back(\"Mass_200mean_excl_star\");\n                headerdatainfo.push_back(\"Mass_200crit_excl_star\");\n                headerdatainfo.push_back(\"Mass_BN98_excl_star\");\n                headerdatainfo.push_back(\"Lx_200c_excl_star\");\n                headerdatainfo.push_back(\"Ly_200c_excl_star\");\n                headerdatainfo.push_back(\"Lz_200c_excl_star\");\n                headerdatainfo.push_back(\"Lx_200m_excl_star\");\n                headerdatainfo.push_back(\"Ly_200m_excl_star\");\n                headerdatainfo.push_back(\"Lz_200m_excl_star\");\n                headerdatainfo.push_back(\"Lx_BN98_excl_star\");\n                headerdatainfo.push_back(\"Ly_BN98_excl_star\");\n                headerdatainfo.push_back(\"Lz_BN98_excl_star\");\n            }\n        }\n#ifdef USEHDF\n        sizeval=predtypeinfo.size();\n        for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(desiredproprealtype[0]);\n#endif\n#ifdef USEADIOS\n        sizeval=adiospredtypeinfo.size();\n        for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(desiredadiosproprealtype[0]);\n#endif\n#endif\n\n#ifdef BHON\n        headerdatainfo.push_back(\"n_bh\");\n#ifdef USEHDF\n        predtypeinfo.push_back(PredType::STD_U64LE);\n#endif\n#ifdef USEADIOS\n        adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n#endif\n        headerdatainfo.push_back(\"M_bh\");\n#ifdef USEHDF\n        sizeval=predtypeinfo.size();\n        for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(desiredproprealtype[0]);\n#endif\n#ifdef USEADIOS\n        sizeval=adiospredtypeinfo.size();\n        for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(desiredadiosproprealtype[0]);\n#endif\n#endif\n\n\n#ifdef HIGHRES\n        headerdatainfo.push_back(\"n_interloper\");\n#ifdef USEHDF\n        predtypeinfo.push_back(PredType::STD_U64LE);\n#endif\n#ifdef USEADIOS\n        adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n#endif\n        headerdatainfo.push_back(\"M_interloper\");\n        if (opt.iextrainterloperoutput) {\n            headerdatainfo.push_back(\"Mass_200mean_interloper\");\n            headerdatainfo.push_back(\"Mass_200crit_interloper\");\n            headerdatainfo.push_back(\"Mass_BN98_interloper\");\n            if (opt.iInclusiveHalo>0) {\n                headerdatainfo.push_back(\"Mass_200mean_excl_interloper\");\n                headerdatainfo.push_back(\"Mass_200crit_excl_interloper\");\n                headerdatainfo.push_back(\"Mass_BN98_excl_interloper\");\n            }\n        }\n#ifdef USEHDF\n        sizeval=predtypeinfo.size();\n        for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(desiredproprealtype[0]);\n#endif\n#ifdef USEADIOS\n        sizeval=adiospredtypeinfo.size();\n        for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(desiredadiosproprealtype[0]);\n#endif\n#endif\n\n#if defined(GASON) && defined(STARON)\n        headerdatainfo.push_back(\"M_gas_sf\");\n        headerdatainfo.push_back(\"R_HalfMass_gas_sf\");\n        headerdatainfo.push_back(\"sigV_gas_sf\");\n        headerdatainfo.push_back(\"Lx_gas_sf\");\n        headerdatainfo.push_back(\"Ly_gas_sf\");\n        headerdatainfo.push_back(\"Lz_gas_sf\");\n        headerdatainfo.push_back(\"Krot_gas_sf\");\n        headerdatainfo.push_back(\"T_gas_sf\");\n        headerdatainfo.push_back(\"Zmet_gas_sf\");\n        if (opt.iextragasoutput) {\n            headerdatainfo.push_back(\"Mass_200mean_gas_sf\");\n            headerdatainfo.push_back(\"Mass_200crit_gas_sf\");\n            headerdatainfo.push_back(\"Mass_BN98_gas_sf\");\n            headerdatainfo.push_back(\"Lx_200c_gas_sf\");\n            headerdatainfo.push_back(\"Ly_200c_gas_sf\");\n            headerdatainfo.push_back(\"Lz_200c_gas_sf\");\n            headerdatainfo.push_back(\"Lx_200m_gas_sf\");\n            headerdatainfo.push_back(\"Ly_200m_gas_sf\");\n            headerdatainfo.push_back(\"Lz_200m_gas_sf\");\n            headerdatainfo.push_back(\"Lx_BN98_gas_sf\");\n            headerdatainfo.push_back(\"Ly_BN98_gas_sf\");\n            headerdatainfo.push_back(\"Lz_BN98_gas_sf\");\n            if (opt.iInclusiveHalo>0) {\n                headerdatainfo.push_back(\"Mass_200mean_excl_gas_sf\");\n                headerdatainfo.push_back(\"Mass_200crit_excl_gas_sf\");\n                headerdatainfo.push_back(\"Mass_BN98_excl_gas_sf\");\n                headerdatainfo.push_back(\"Lx_200c_excl_gas_sf\");\n                headerdatainfo.push_back(\"Ly_200c_excl_gas_sf\");\n                headerdatainfo.push_back(\"Lz_200c_excl_gas_sf\");\n                headerdatainfo.push_back(\"Lx_200m_excl_gas_sf\");\n                headerdatainfo.push_back(\"Ly_200m_excl_gas_sf\");\n                headerdatainfo.push_back(\"Lz_200m_excl_gas_sf\");\n                headerdatainfo.push_back(\"Lx_BN98_excl_gas_sf\");\n                headerdatainfo.push_back(\"Ly_BN98_excl_gas_sf\");\n                headerdatainfo.push_back(\"Lz_BN98_excl_gas_sf\");\n            }\n        }\n        headerdatainfo.push_back(\"M_gas_nsf\");\n        headerdatainfo.push_back(\"R_HalfMass_gas_nsf\");\n        headerdatainfo.push_back(\"sigV_gas_nsf\");\n        headerdatainfo.push_back(\"Lx_gas_nsf\");\n        headerdatainfo.push_back(\"Ly_gas_nsf\");\n        headerdatainfo.push_back(\"Lz_gas_nsf\");\n        headerdatainfo.push_back(\"Krot_gas_nsf\");\n        headerdatainfo.push_back(\"T_gas_nsf\");\n        headerdatainfo.push_back(\"Zmet_gas_nsf\");\n        if (opt.iextragasoutput) {\n            headerdatainfo.push_back(\"Mass_200mean_gas_nsf\");\n            headerdatainfo.push_back(\"Mass_200crit_gas_nsf\");\n            headerdatainfo.push_back(\"Mass_BN98_gas_nsf\");\n            headerdatainfo.push_back(\"Lx_200c_gas_nsf\");\n            headerdatainfo.push_back(\"Ly_200c_gas_nsf\");\n            headerdatainfo.push_back(\"Lz_200c_gas_nsf\");\n            headerdatainfo.push_back(\"Lx_200m_gas_nsf\");\n            headerdatainfo.push_back(\"Ly_200m_gas_nsf\");\n            headerdatainfo.push_back(\"Lz_200m_gas_nsf\");\n            headerdatainfo.push_back(\"Lx_BN98_gas_nsf\");\n            headerdatainfo.push_back(\"Ly_BN98_gas_nsf\");\n            headerdatainfo.push_back(\"Lz_BN98_gas_nsf\");\n            if (opt.iInclusiveHalo>0) {\n                headerdatainfo.push_back(\"Mass_200mean_excl_gas_nsf\");\n                headerdatainfo.push_back(\"Mass_200crit_excl_gas_nsf\");\n                headerdatainfo.push_back(\"Mass_BN98_excl_gas_nsf\");\n                headerdatainfo.push_back(\"Lx_200c_excl_gas_nsf\");\n                headerdatainfo.push_back(\"Ly_200c_excl_gas_nsf\");\n                headerdatainfo.push_back(\"Lz_200c_excl_gas_nsf\");\n                headerdatainfo.push_back(\"Lx_200m_excl_gas_nsf\");\n                headerdatainfo.push_back(\"Ly_200m_excl_gas_nsf\");\n                headerdatainfo.push_back(\"Lz_200m_excl_gas_nsf\");\n                headerdatainfo.push_back(\"Lx_BN98_excl_gas_nsf\");\n                headerdatainfo.push_back(\"Ly_BN98_excl_gas_nsf\");\n                headerdatainfo.push_back(\"Lz_BN98_excl_gas_nsf\");\n            }\n        }\n#ifdef USEHDF\n        sizeval=predtypeinfo.size();\n        for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(desiredproprealtype[0]);\n#endif\n#ifdef USEADIOS\n        sizeval=adiospredtypeinfo.size();\n        for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(desiredadiosproprealtype[0]);\n#endif\n#endif\n\n        //if aperture information calculated also include\n        if (opt.iaperturecalc>0 && opt.aperturenum>0) {\n            for (auto i=0; i<opt.aperturenum;i++)\n                headerdatainfo.push_back((string(\"Aperture_npart_\")+opt.aperture_names_kpc[i]+string(\"_kpc\")));\n#ifdef GASON\n            for (auto i=0; i<opt.aperturenum;i++)\n                headerdatainfo.push_back((string(\"Aperture_npart_gas_\")+opt.aperture_names_kpc[i]+string(\"_kpc\")));\n#ifdef STARON\n            for (auto i=0; i<opt.aperturenum;i++)\n                headerdatainfo.push_back((string(\"Aperture_npart_gas_sf_\")+opt.aperture_names_kpc[i]+string(\"_kpc\")));\n            for (auto i=0; i<opt.aperturenum;i++)\n                headerdatainfo.push_back((string(\"Aperture_npart_gas_nsf_\")+opt.aperture_names_kpc[i]+string(\"_kpc\")));\n#endif\n#endif\n#ifdef STARON\n            for (auto i=0; i<opt.aperturenum;i++)\n                headerdatainfo.push_back((string(\"Aperture_npart_star_\")+opt.aperture_names_kpc[i]+string(\"_kpc\")));\n#endif\n#ifdef HIGHRES\n            for (auto i=0; i<opt.aperturenum;i++)\n                headerdatainfo.push_back((string(\"Aperture_npart_interloper_\")+opt.aperture_names_kpc[i]+string(\"_kpc\")));\n#endif\n#ifdef USEHDF\n            sizeval=predtypeinfo.size();\n            for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(PredType::STD_U32LE);\n#endif\n#ifdef USEADIOS\n            sizeval=adiospredtypeinfo.size();\n            for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_unsigned_int);\n#endif\n            for (auto i=0; i<opt.aperturenum;i++)\n                headerdatainfo.push_back((string(\"Aperture_mass_\")+opt.aperture_names_kpc[i]+string(\"_kpc\")));\n#ifdef GASON\n            for (auto i=0; i<opt.aperturenum;i++)\n                headerdatainfo.push_back((string(\"Aperture_mass_gas_\")+opt.aperture_names_kpc[i]+string(\"_kpc\")));\n#ifdef STARON\n            for (auto i=0; i<opt.aperturenum;i++)\n                headerdatainfo.push_back((string(\"Aperture_mass_gas_sf_\")+opt.aperture_names_kpc[i]+string(\"_kpc\")));\n            for (auto i=0; i<opt.aperturenum;i++)\n                headerdatainfo.push_back((string(\"Aperture_mass_gas_nsf_\")+opt.aperture_names_kpc[i]+string(\"_kpc\")));\n#endif\n#endif\n#ifdef STARON\n            for (auto i=0; i<opt.aperturenum;i++)\n                headerdatainfo.push_back((string(\"Aperture_mass_star_\")+opt.aperture_names_kpc[i]+string(\"_kpc\")));\n#endif\n#ifdef HIGHRES\n            for (auto i=0; i<opt.aperturenum;i++)\n                headerdatainfo.push_back((string(\"Aperture_mass_interloper_\")+opt.aperture_names_kpc[i]+string(\"_kpc\")));\n#endif\n\n            for (auto i=0; i<opt.aperturenum;i++)\n                headerdatainfo.push_back((string(\"Aperture_rhalfmass_\")+opt.aperture_names_kpc[i]+string(\"_kpc\")));\n#ifdef GASON\n            for (auto i=0; i<opt.aperturenum;i++)\n                headerdatainfo.push_back((string(\"Aperture_rhalfmass_gas_\")+opt.aperture_names_kpc[i]+string(\"_kpc\")));\n#ifdef STARON\n            for (auto i=0; i<opt.aperturenum;i++)\n                headerdatainfo.push_back((string(\"Aperture_rhalfmass_gas_sf_\")+opt.aperture_names_kpc[i]+string(\"_kpc\")));\n            for (auto i=0; i<opt.aperturenum;i++)\n                headerdatainfo.push_back((string(\"Aperture_rhalfmass_gas_nsf_\")+opt.aperture_names_kpc[i]+string(\"_kpc\")));\n#endif\n#endif\n#ifdef STARON\n            for (auto i=0; i<opt.aperturenum;i++)\n                headerdatainfo.push_back((string(\"Aperture_rhalfmass_star_\")+opt.aperture_names_kpc[i]+string(\"_kpc\")));\n#endif\n\n            for (auto i=0; i<opt.aperturenum;i++)\n                headerdatainfo.push_back((string(\"Aperture_veldisp_\")+opt.aperture_names_kpc[i]+string(\"_kpc\")));\n#ifdef GASON\n            for (auto i=0; i<opt.aperturenum;i++)\n                headerdatainfo.push_back((string(\"Aperture_veldisp_gas_\")+opt.aperture_names_kpc[i]+string(\"_kpc\")));\n#ifdef STARON\n            for (auto i=0; i<opt.aperturenum;i++)\n                headerdatainfo.push_back((string(\"Aperture_veldips_gas_sf_\")+opt.aperture_names_kpc[i]+string(\"_kpc\")));\n            for (auto i=0; i<opt.aperturenum;i++)\n                headerdatainfo.push_back((string(\"Aperture_veldisp_gas_nsf_\")+opt.aperture_names_kpc[i]+string(\"_kpc\")));\n#endif\n#endif\n#ifdef STARON\n            for (auto i=0; i<opt.aperturenum;i++)\n                headerdatainfo.push_back((string(\"Aperture_veldisp_star_\")+opt.aperture_names_kpc[i]+string(\"_kpc\")));\n#endif\n#if defined(GASON) && defined(STARON)\n            for (auto i=0; i<opt.aperturenum;i++)\n                headerdatainfo.push_back((string(\"Aperture_SFR_gas_\")+opt.aperture_names_kpc[i]+string(\"_kpc\")));\n#endif\n\n#ifdef USEHDF\n            sizeval=predtypeinfo.size();\n            for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(desiredproprealtype[0]);\n#endif\n#ifdef USEADIOS\n            sizeval=adiospredtypeinfo.size();\n            for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(desiredadiosproprealtype[0]);\n#endif\n        }\n        if (opt.iaperturecalc>0 && opt.apertureprojnum>0) {\n            for (auto k=0;k<3;k++) {\n            string projname = \"Projected_aperture_\"+to_string(k+1)+\"_\";\n            for (auto i=0; i<opt.apertureprojnum;i++)\n                headerdatainfo.push_back(projname+string(\"mass_\")+opt.aperture_proj_names_kpc[i]+string(\"_kpc\"));\n#ifdef GASON\n            for (auto i=0; i<opt.apertureprojnum;i++)\n                headerdatainfo.push_back(projname+string(\"mass_gas_\")+opt.aperture_proj_names_kpc[i]+string(\"_kpc\"));\n#ifdef STARON\n            for (auto i=0; i<opt.apertureprojnum;i++)\n                headerdatainfo.push_back(projname+string(\"mass_gas_sf_\")+opt.aperture_proj_names_kpc[i]+string(\"_kpc\"));\n            for (auto i=0; i<opt.apertureprojnum;i++)\n                headerdatainfo.push_back(projname+string(\"mass_gas_nsf_\")+opt.aperture_proj_names_kpc[i]+string(\"_kpc\"));\n#endif\n#endif\n#ifdef STARON\n            for (auto i=0; i<opt.apertureprojnum;i++)\n                headerdatainfo.push_back(projname+string(\"mass_star_\")+opt.aperture_proj_names_kpc[i]+string(\"_kpc\"));\n#endif\n\n            for (auto i=0; i<opt.apertureprojnum;i++)\n                headerdatainfo.push_back(projname+string(\"rhalfmass_\")+opt.aperture_proj_names_kpc[i]+string(\"_kpc\"));\n#ifdef GASON\n            for (auto i=0; i<opt.apertureprojnum;i++)\n                headerdatainfo.push_back(projname+string(\"rhalfmass_gas_\")+opt.aperture_proj_names_kpc[i]+string(\"_kpc\"));\n#ifdef STARON\n            for (auto i=0; i<opt.apertureprojnum;i++)\n                headerdatainfo.push_back(projname+string(\"rhalfmass_gas_sf_\")+opt.aperture_proj_names_kpc[i]+string(\"_kpc\"));\n            for (auto i=0; i<opt.apertureprojnum;i++)\n                headerdatainfo.push_back(projname+string(\"rhalfmass_gas_nsf_\")+opt.aperture_proj_names_kpc[i]+string(\"_kpc\"));\n#endif\n#endif\n#ifdef STARON\n            for (auto i=0; i<opt.apertureprojnum;i++)\n                headerdatainfo.push_back(projname+string(\"rhalfmass_star_\")+opt.aperture_proj_names_kpc[i]+string(\"_kpc\"));\n#endif\n#if defined(GASON) && defined(STARON)\n            for (auto i=0; i<opt.apertureprojnum;i++)\n                headerdatainfo.push_back(projname+string(\"SFR_gas_\")+opt.aperture_proj_names_kpc[i]+string(\"_kpc\"));\n#endif\n            }\n#ifdef USEHDF\n            sizeval=predtypeinfo.size();\n            for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(desiredproprealtype[0]);\n#endif\n#ifdef USEADIOS\n            sizeval=adiospredtypeinfo.size();\n            for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(desiredadiosproprealtype[0]);\n#endif\n        }\n\n        //if aperture information calculated also include\n        if (opt.SOnum>0) {\n            for (auto i=0; i<opt.SOnum;i++) {\n                headerdatainfo.push_back((string(\"SO_Mass_\")+opt.SOthresholds_names_crit[i]+string(\"_rhocrit\")));\n#ifdef USEHDF\n                predtypeinfo.push_back(desiredproprealtype[0]);\n#endif\n#ifdef USEADIOS\n                adiospredtypeinfo.push_back(desiredadiosproprealtype[0]);\n#endif\n            }\n            for (auto i=0; i<opt.SOnum;i++) {\n                headerdatainfo.push_back((string(\"SO_R_\")+opt.SOthresholds_names_crit[i]+string(\"_rhocrit\")));\n#ifdef USEHDF\n                predtypeinfo.push_back(desiredproprealtype[0]);\n#endif\n#ifdef USEADIOS\n                adiospredtypeinfo.push_back(desiredadiosproprealtype[0]);\n#endif\n            }\n#ifdef GASON\n            if (opt.iextragasoutput && opt.iextrahalooutput) {\n                for (auto i=0; i<opt.SOnum;i++) {\n                    headerdatainfo.push_back((string(\"SO_Mass_gas_\")+opt.SOthresholds_names_crit[i]+string(\"_rhocrit\")));\n#ifdef USEHDF\n                    predtypeinfo.push_back(desiredproprealtype[0]);\n#endif\n#ifdef USEADIOS\n                    adiospredtypeinfo.push_back(desiredadiosproprealtype[0]);\n#endif\n                }\n#ifdef STARON\n#endif\n            }\n#endif\n\n#ifdef STARON\n            if (opt.iextrastaroutput && opt.iextrahalooutput) {\n                for (auto i=0; i<opt.SOnum;i++) {\n                    headerdatainfo.push_back((string(\"SO_Mass_star_\")+opt.SOthresholds_names_crit[i]+string(\"_rhocrit\")));\n#ifdef USEHDF\n                    predtypeinfo.push_back(desiredproprealtype[0]);\n#endif\n#ifdef USEADIOS\n                    adiospredtypeinfo.push_back(desiredadiosproprealtype[0]);\n#endif\n                }\n            }\n#endif\n#ifdef HIGHRES\n            if (opt.iextrainterloperoutput && opt.iextrahalooutput) {\n                for (auto i=0; i<opt.SOnum;i++) {\n                    headerdatainfo.push_back((string(\"SO_Mass_interloper_\")+opt.SOthresholds_names_crit[i]+string(\"_rhocrit\")));\n#ifdef USEHDF\n                    predtypeinfo.push_back(desiredproprealtype[0]);\n#endif\n#ifdef USEADIOS\n                    adiospredtypeinfo.push_back(desiredadiosproprealtype[0]);\n#endif\n                }\n            }\n#endif\n        }\n        if (opt.SOnum>0 && opt.iextrahalooutput) {\n            for (auto i=0; i<opt.SOnum;i++) {\n                headerdatainfo.push_back((string(\"SO_Lx_\")+opt.SOthresholds_names_crit[i]+string(\"_rhocrit\")));\n                headerdatainfo.push_back((string(\"SO_Ly_\")+opt.SOthresholds_names_crit[i]+string(\"_rhocrit\")));\n                headerdatainfo.push_back((string(\"SO_Lz_\")+opt.SOthresholds_names_crit[i]+string(\"_rhocrit\")));\n                for (auto k=0;k<3;k++) {\n#ifdef USEHDF\n                    predtypeinfo.push_back(desiredproprealtype[0]);\n#endif\n#ifdef USEADIOS\n                    adiospredtypeinfo.push_back(desiredadiosproprealtype[0]);\n#endif\n                }\n            }\n#ifdef GASON\n            if (opt.iextragasoutput) {\n                for (auto i=0; i<opt.SOnum;i++) {\n                    headerdatainfo.push_back((string(\"SO_Lx_gas_\")+opt.SOthresholds_names_crit[i]+string(\"_rhocrit\")));\n                    headerdatainfo.push_back((string(\"SO_Ly_gas_\")+opt.SOthresholds_names_crit[i]+string(\"_rhocrit\")));\n                    headerdatainfo.push_back((string(\"SO_Lz_gas_\")+opt.SOthresholds_names_crit[i]+string(\"_rhocrit\")));\n                    for (auto k=0;k<3;k++) {\n#ifdef USEHDF\n                        predtypeinfo.push_back(desiredproprealtype[0]);\n#endif\n#ifdef USEADIOS\n                        adiospredtypeinfo.push_back(desiredadiosproprealtype[0]);\n#endif\n                    }\n                }\n#ifdef STARON\n#endif\n            }\n#endif\n\n#ifdef STARON\n            if (opt.iextrastaroutput) {\n                for (auto i=0; i<opt.SOnum;i++) {\n                    headerdatainfo.push_back((string(\"SO_Lx_star_\")+opt.SOthresholds_names_crit[i]+string(\"_rhocrit\")));\n                    headerdatainfo.push_back((string(\"SO_Ly_star_\")+opt.SOthresholds_names_crit[i]+string(\"_rhocrit\")));\n                    headerdatainfo.push_back((string(\"SO_Lz_star_\")+opt.SOthresholds_names_crit[i]+string(\"_rhocrit\")));\n                    for (auto k=0;k<3;k++) {\n#ifdef USEHDF\n                        predtypeinfo.push_back(desiredproprealtype[0]);\n#endif\n#ifdef USEADIOS\n                        adiospredtypeinfo.push_back(desiredadiosproprealtype[0]);\n#endif\n                    }\n                }\n            }\n#endif\n        }\n    }\n};\n\n\n/*! Structures stores profile info of the data writen by the \\ref PropData profiles data structures,\n    specifically the \\ref PropData::WriteProfileBinary, \\ref PropData::WriteProfileAscii, \\ref PropData::WriteProfileHDF routines\n*/\n\nstruct ProfileDataHeader{\n    //list the header info\n    vector<string> headerdatainfo;\n#ifdef USEHDF\n    vector<PredType> predtypeinfo;\n#endif\n#ifdef USEADIOS\n    vector<ADIOS_DATATYPES> adiospredtypeinfo;\n#endif\n    int numberscalarentries, numberarrayallgroupentries, numberarrayhaloentries;\n    int offsetscalarentries, offsetarrayallgroupentries, offsetarrayhaloentries;\n\n    ProfileDataHeader(Options&opt){\n        int sizeval;\n#ifdef USEHDF\n        vector<PredType> desiredproprealtype;\n        if (sizeof(Double_t)==sizeof(double)) desiredproprealtype.push_back(PredType::NATIVE_DOUBLE);\n        else desiredproprealtype.push_back(PredType::NATIVE_FLOAT);\n#endif\n#ifdef USEADIOS\n        vector<ADIOS_DATATYPES> desiredadiosproprealtype;\n        if (sizeof(Double_t)==sizeof(double)) desiredadiosproprealtype.push_back(ADIOS_DATATYPES::adios_double);\n        else desiredadiosproprealtype.push_back(ADIOS_DATATYPES::adios_real);\n#endif\n\n        offsetscalarentries=0;\n        headerdatainfo.push_back(\"ID\");\n#ifdef USEHDF\n        predtypeinfo.push_back(PredType::STD_U64LE);\n#endif\n#ifdef USEADIOS\n        adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n#endif\n        //if normalisation is phys then no need for writing normalisation block\n        if (opt.iprofilenorm != PROFILERNORMPHYS) {\n        headerdatainfo.push_back(opt.profileradnormstring);\n#ifdef USEHDF\n        predtypeinfo.push_back(desiredproprealtype[0]);\n#endif\n#ifdef USEADIOS\n        adiospredtypeinfo.push_back(desiredadiosproprealtype[0]);\n#endif\n        }\n        numberscalarentries=headerdatainfo.size();\n\n\toffsetarrayallgroupentries=headerdatainfo.size();\n        headerdatainfo.push_back(\"Npart_profile\");\n#ifdef GASON\n        headerdatainfo.push_back(\"Npart_profile_gas\");\n#ifdef STARON\n        headerdatainfo.push_back(\"Npart_profile_gas_sf\");\n        headerdatainfo.push_back(\"Npart_profile_gas_nsf\");\n#endif\n#endif\n#ifdef STARON\n        headerdatainfo.push_back(\"Npart_profile_star\");\n#endif\n#ifdef USEHDF\n        sizeval=predtypeinfo.size();\n        for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(PredType::STD_U32LE);\n#endif\n#ifdef USEADIOS\n        sizeval=adiospredtypeinfo.size();\n        for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_unsigned_integer);\n#endif\n\n        headerdatainfo.push_back(\"Mass_profile\");\n#ifdef GASON\n        headerdatainfo.push_back(\"Mass_profile_gas\");\n#ifdef STARON\n        headerdatainfo.push_back(\"Mass_profile_gas_sf\");\n        headerdatainfo.push_back(\"Mass_profile_gas_nsf\");\n#endif\n#endif\n#ifdef STARON\n        headerdatainfo.push_back(\"Mass_profile_star\");\n#endif\n\n#ifdef USEHDF\n        sizeval=predtypeinfo.size();\n        for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(PredType::NATIVE_FLOAT);\n#endif\n#ifdef USEADIOS\n        sizeval=adiospredtypeinfo.size();\n        for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_real);\n#endif\n        numberarrayallgroupentries=headerdatainfo.size()-offsetarrayallgroupentries;\n\n        //stuff for inclusive halo/SO profiles\n        if (opt.iInclusiveHalo >0) {\n        offsetarrayhaloentries=headerdatainfo.size();\n        headerdatainfo.push_back(\"Npart_inclusive_profile\");\n#ifdef GASON\n        headerdatainfo.push_back(\"Npart_inclusive_profile_gas\");\n#ifdef STARON\n        headerdatainfo.push_back(\"Npart_inclusive_profile_gas_sf\");\n        headerdatainfo.push_back(\"Npart_inclusive_profile_gas_nsf\");\n#endif\n#endif\n#ifdef STARON\n        headerdatainfo.push_back(\"Npart_inclusive_profile_star\");\n#endif\n#ifdef USEHDF\n        sizeval=predtypeinfo.size();\n        for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(PredType::STD_U32LE);\n#endif\n#ifdef USEADIOS\n        sizeval=adiospredtypeinfo.size();\n        for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_unsigned_integer);\n#endif\n\n        headerdatainfo.push_back(\"Mass_inclusive_profile\");\n#ifdef GASON\n        headerdatainfo.push_back(\"Mass_inclusive_profile_gas\");\n#ifdef STARON\n        headerdatainfo.push_back(\"Mass_inclusive_profile_gas_sf\");\n        headerdatainfo.push_back(\"Mass_inclusive_profile_gas_nsf\");\n#endif\n#endif\n#ifdef STARON\n        headerdatainfo.push_back(\"Mass_inclusive_profile_star\");\n#endif\n#ifdef USEHDF\n        sizeval=predtypeinfo.size();\n        for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(PredType::NATIVE_FLOAT);\n#endif\n#ifdef USEADIOS\n        sizeval=adiospredtypeinfo.size();\n        for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_real);\n#endif\n        numberarrayhaloentries=headerdatainfo.size()-offsetarrayhaloentries;\n        }\n    }\n};\n\n/*! Structure used to keep track of a structure's parent structure\n    note that level could be sim->halo->subhalo->subsubhalo\n    or even sim->wall/void/filament->halo->substructure->subsubstructure\n    here sim is stype=0,gid=0, and the other structure types are to be defined.\n    The data structure is meant to be traversed from\n        - level 0 structures (\"field\" objects)\n        - level 0 pointer to nextlevel\n        - nextlevel containing nginlevel objects\n*/\nstruct StrucLevelData\n{\n    ///structure type and number in current level of hierarchy\n    Int_t stype,nsinlevel;\n    ///points to the the head pfof address of the group and parent\n    Particle **Phead;\n    Int_t **gidhead;\n    ///parent pointers point to the address of the parents gidhead and Phead\n    Particle **Pparenthead;\n    Int_t **gidparenthead;\n    ///add uber parent pointer (that is pointer to field halo)\n    Int_t **giduberparenthead;\n    ///allowing for multiple structure types at a given level in the hierarchy\n    Int_t *stypeinlevel;\n    StrucLevelData *nextlevel;\n    StrucLevelData(Int_t numgroups=-1){\n        if (numgroups<=0) {\n            Phead=NULL;\n            Pparenthead=NULL;\n            gidhead=NULL;\n            gidparenthead=NULL;\n            giduberparenthead=NULL;\n            nextlevel=NULL;\n            stypeinlevel=NULL;\n            nsinlevel=0;\n        }\n        else Allocate(numgroups);\n    }\n    ///just allocate memory\n    void Allocate(Int_t numgroups){\n        nsinlevel=numgroups;\n        Phead=new Particle*[numgroups+1];\n        gidhead=new Int_t*[numgroups+1];\n        stypeinlevel=new Int_t[numgroups+1];\n        gidparenthead=new Int_t*[numgroups+1];\n        giduberparenthead=new Int_t*[numgroups+1];\n        nextlevel=NULL;\n    }\n    ///initialize\n    void Initialize(){\n        for (Int_t i=1;i<=nsinlevel;i++) {gidhead[i]=NULL;gidparenthead[i]=NULL;giduberparenthead[i]=NULL;}\n    }\n    ~StrucLevelData(){\n        if (nextlevel!=NULL) delete nextlevel;\n        nextlevel=NULL;\n        if (nsinlevel>0) {\n            delete[] Phead;\n            delete[] gidhead;\n            delete[] stypeinlevel;\n            delete[] gidparenthead;\n            delete[] giduberparenthead;\n        }\n    }\n};\n\n#if defined(USEHDF)||defined(USEADIOS)\n///store the names of datasets in catalog output\nstruct DataGroupNames {\n    ///store names of catalog group files\n    vector<string> prop;\n#ifdef USEHDF\n    //store the data type\n    vector<PredType> propdatatype;\n#endif\n#ifdef USEADIOS\n    vector<ADIOS_DATATYPES> adiospropdatatype;\n#endif\n\n    ///store names of catalog group files\n    vector<string> group;\n#ifdef USEHDF\n    vector<PredType> groupdatatype;\n#endif\n#ifdef USEADIOS\n    vector<ADIOS_DATATYPES> adiosgroupdatatype;\n#endif\n\n    ///store the names of catalog particle files\n    vector<string> part;\n#ifdef USEHDF\n    vector<PredType> partdatatype;\n#endif\n#ifdef USEADIOS\n    vector<ADIOS_DATATYPES> adiospartdatatype;\n#endif\n\n    ///store the names of catalog particle type files\n    vector<string> types;\n#ifdef USEHDF\n    vector<PredType> typesdatatype;\n#endif\n#ifdef USEADIOS\n    vector<ADIOS_DATATYPES> adiostypesdatatype;\n#endif\n\n    ///store the names of hierarchy files\n    vector<string> hierarchy;\n#ifdef USEHDF\n    vector<PredType> hierarchydatatype;\n#endif\n#ifdef USEADIOS\n    vector<ADIOS_DATATYPES> adioshierarchydatatype;\n#endif\n\n    ///store names of SO files\n    vector<string> SO;\n#ifdef USEHDF\n    vector<PredType> SOdatatype;\n#endif\n#ifdef USEADIOS\n    vector<ADIOS_DATATYPES> SOdatatype;\n#endif\n\n    //store names of profile files\n    vector<string> profile;\n#ifdef USEHDF\n    //store the data type\n    vector<PredType> profiledatatype;\n#endif\n#ifdef USEADIOS\n    vector<ADIOS_DATATYPES> adiosprofiledatatype;\n#endif\n\n    DataGroupNames(){\n#ifdef USEHDF\n        vector<PredType> desiredproprealtype;\n        if (sizeof(Double_t)==sizeof(double)) desiredproprealtype.push_back(PredType::NATIVE_DOUBLE);\n        else desiredproprealtype.push_back(PredType::NATIVE_FLOAT);\n#endif\n#ifdef USEADIOS\n        vector<ADIOS_DATATYPES> desiredadiosproprealtype;\n        if (sizeof(Double_t)==sizeof(double)) desiredadiosproprealtype.push_back(ADIOS_DATATYPES::adios_double);\n        else desiredadiosproprealtype.push_back(ADIOS_DATATYPES::adios_real);\n#endif\n        prop.push_back(\"File_id\");\n        prop.push_back(\"Num_of_files\");\n        prop.push_back(\"Num_of_groups\");\n        prop.push_back(\"Total_num_of_groups\");\n        prop.push_back(\"Cosmological_Sim\");\n        prop.push_back(\"Comoving_or_Physical\");\n        prop.push_back(\"Period\");\n        prop.push_back(\"Time\");\n        prop.push_back(\"Length_unit_to_kpc\");\n        prop.push_back(\"Velocity_to_kms\");\n        prop.push_back(\"Mass_unit_to_solarmass\");\n#if defined(GASON) || defined(STARON) || defined(BHON)\n        prop.push_back(\"Metallicity_unit_to_solar\");\n        prop.push_back(\"SFR_unit_to_solarmassperyear\");\n        prop.push_back(\"Stellar_age_unit_to_yr\");\n#endif\n#ifdef USEHDF\n        propdatatype.push_back(PredType::STD_I32LE);\n        propdatatype.push_back(PredType::STD_I32LE);\n        propdatatype.push_back(PredType::STD_U64LE);\n        propdatatype.push_back(PredType::STD_U64LE);\n        propdatatype.push_back(PredType::STD_U32LE);\n        propdatatype.push_back(PredType::STD_U32LE);\n        propdatatype.push_back(desiredproprealtype[0]);\n        propdatatype.push_back(desiredproprealtype[0]);\n        propdatatype.push_back(desiredproprealtype[0]);\n        propdatatype.push_back(desiredproprealtype[0]);\n        propdatatype.push_back(desiredproprealtype[0]);\n#if defined(GASON) || defined(STARON) || defined(BHON)\n        propdatatype.push_back(desiredproprealtype[0]);\n        propdatatype.push_back(desiredproprealtype[0]);\n        propdatatype.push_back(desiredproprealtype[0]);\n#endif\n#endif\n#ifdef USEADIOS\n        adiospropdatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adiospropdatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adiospropdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiospropdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiospropdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_integer);\n        adiospropdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_integer);\n        adiospropdatatype.push_back(desiredadiosproprealtype[0]);\n        adiospropdatatype.push_back(desiredadiosproprealtype[0]);\n        adiospropdatatype.push_back(desiredadiosproprealtype[0]);\n        adiospropdatatype.push_back(desiredadiosproprealtype[0]);\n        adiospropdatatype.push_back(desiredadiosproprealtype[0]);\n#if defined(GASON) || defined(STARON) || defined(BHON)\n        adiospropdatatype.push_back(desiredadiosproprealtype[0]);\n        adiospropdatatype.push_back(desiredadiosproprealtype[0]);\n        adiospropdatatype.push_back(desiredadiosproprealtype[0]);\n#endif\n#endif\n\n        group.push_back(\"File_id\");\n        group.push_back(\"Num_of_files\");\n        group.push_back(\"Num_of_groups\");\n        group.push_back(\"Total_num_of_groups\");\n        group.push_back(\"Group_Size\");\n        group.push_back(\"Offset\");\n        group.push_back(\"Offset_unbound\");\n#ifdef USEHDF\n        groupdatatype.push_back(PredType::STD_I32LE);\n        groupdatatype.push_back(PredType::STD_I32LE);\n        groupdatatype.push_back(PredType::STD_U64LE);\n        groupdatatype.push_back(PredType::STD_U64LE);\n        groupdatatype.push_back(PredType::STD_U32LE);\n        groupdatatype.push_back(PredType::STD_U64LE);\n        groupdatatype.push_back(PredType::STD_U64LE);\n#endif\n#ifdef USEADIOS\n        adiosgroupdatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adiosgroupdatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adiosgroupdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiosgroupdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiosgroupdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_integer);\n        adiosgroupdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiosgroupdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n#endif\n\n        part.push_back(\"File_id\");\n        part.push_back(\"Num_of_files\");\n        part.push_back(\"Num_of_particles_in_groups\");\n        part.push_back(\"Total_num_of_particles_in_all_groups\");\n        part.push_back(\"Particle_IDs\");\n#ifdef USEHDF\n        partdatatype.push_back(PredType::STD_I32LE);\n        partdatatype.push_back(PredType::STD_I32LE);\n        partdatatype.push_back(PredType::STD_U64LE);\n        partdatatype.push_back(PredType::STD_U64LE);\n        partdatatype.push_back(PredType::STD_I64LE);\n#endif\n#ifdef USEADIOS\n        adiospartdatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adiospartdatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adiospartdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiospartdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiospartdatatype.push_back(ADIOS_DATATYPES::adios_long);\n#endif\n\n        types.push_back(\"File_id\");\n        types.push_back(\"Num_of_files\");\n        types.push_back(\"Num_of_particles_in_groups\");\n        types.push_back(\"Total_num_of_particles_in_all_groups\");\n        types.push_back(\"Particle_types\");\n#ifdef USEHDF\n        typesdatatype.push_back(PredType::STD_I32LE);\n        typesdatatype.push_back(PredType::STD_I32LE);\n        typesdatatype.push_back(PredType::STD_U64LE);\n        typesdatatype.push_back(PredType::STD_U64LE);\n        typesdatatype.push_back(PredType::STD_U16LE);\n#endif\n#ifdef USEADIOS\n        adiostypesdatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adiostypesdatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adiostypesdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiostypesdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiostypesdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_short);\n#endif\n\n        hierarchy.push_back(\"File_id\");\n        hierarchy.push_back(\"Num_of_files\");\n        hierarchy.push_back(\"Num_of_groups\");\n        hierarchy.push_back(\"Total_num_of_groups\");\n        hierarchy.push_back(\"Number_of_substructures_in_halo\");\n        hierarchy.push_back(\"Parent_halo_ID\");\n#ifdef USEHDF\n        hierarchydatatype.push_back(PredType::STD_I32LE);\n        hierarchydatatype.push_back(PredType::STD_I32LE);\n        hierarchydatatype.push_back(PredType::STD_U64LE);\n        hierarchydatatype.push_back(PredType::STD_U64LE);\n        hierarchydatatype.push_back(PredType::STD_U32LE);\n        hierarchydatatype.push_back(PredType::STD_I64LE);\n#endif\n#ifdef USEADIOS\n        adioshierarchydatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adioshierarchydatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adioshierarchydatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adioshierarchydatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adioshierarchydatatype.push_back(ADIOS_DATATYPES::adios_unsigned_integer);\n        adioshierarchydatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n#endif\n        SO.push_back(\"File_id\");\n        SO.push_back(\"Num_of_files\");\n        SO.push_back(\"Num_of_SO_regions\");\n        SO.push_back(\"Total_num_of_SO_regions\");\n        SO.push_back(\"Num_of_particles_in_SO_regions\");\n        SO.push_back(\"Total_num_of_particles_in_SO_regions\");\n        SO.push_back(\"SO_size\");\n        SO.push_back(\"Offset\");\n        SO.push_back(\"Particle_IDs\");\n#if defined(GASON) || defined(STARON) || defined(BHON)\n        SO.push_back(\"Particle_types\");\n#endif\n\n#ifdef USEHDF\n        SOdatatype.push_back(PredType::STD_I32LE);\n        SOdatatype.push_back(PredType::STD_I32LE);\n        SOdatatype.push_back(PredType::STD_U64LE);\n        SOdatatype.push_back(PredType::STD_U64LE);\n        SOdatatype.push_back(PredType::STD_U64LE);\n        SOdatatype.push_back(PredType::STD_U64LE);\n        SOdatatype.push_back(PredType::STD_U32LE);\n        SOdatatype.push_back(PredType::STD_U64LE);\n        SOdatatype.push_back(PredType::STD_I64LE);\n#if defined(GASON) || defined(STARON) || defined(BHON)\n        SOdatatype.push_back(PredType::STD_I32LE);\n#endif\n#endif\n#ifdef USEADIOS\n        adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_integer);\n        adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_long);\n#if defined(GASON) || defined(STARON) || defined(BHON)\n        adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_integer);\n#endif\n#endif\n\n        profile.push_back(\"File_id\");\n        profile.push_back(\"Num_of_files\");\n        profile.push_back(\"Num_of_groups\");\n        profile.push_back(\"Total_num_of_groups\");\n        profile.push_back(\"Num_of_halos\");\n        profile.push_back(\"Total_num_of_halos\");\n        profile.push_back(\"Radial_norm\");\n        profile.push_back(\"Inclusive_profiles_flag\");\n        profile.push_back(\"Num_of_bin_edges\");\n        profile.push_back(\"Radial_bin_edges\");\n#ifdef USEHDF\n        profiledatatype.push_back(PredType::STD_I32LE);\n        profiledatatype.push_back(PredType::STD_I32LE);\n        profiledatatype.push_back(PredType::STD_U64LE);\n        profiledatatype.push_back(PredType::STD_U64LE);\n        profiledatatype.push_back(PredType::STD_U64LE);\n        profiledatatype.push_back(PredType::STD_U64LE);\n        profiledatatype.push_back(PredType::C_S1);\n        profiledatatype.push_back(PredType::STD_I32LE);\n        profiledatatype.push_back(PredType::STD_I32LE);\n        profiledatatype.push_back(desiredproprealtype[0]);\n#endif\n#ifdef USEADIOS\n        adiosprofiledatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adiosprofiledatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adiosprofiledatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiosprofiledatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiosprofiledatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiosprofiledatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiosprofiledatatype.push_back(ADIOS_DATATYPES::adios_string);\n        adiosprofiledatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adiosprofiledatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adiosprofiledatatype.push_back(desiredadiosproprealtype[0]);\n#endif\n\n    }\n};\n#endif\n\n///Useful structore to store information of leaf nodes in the tree\nstruct leaf_node_info{\n    int num, numtot;\n    Int_t id, istart, iend;\n    Coordinate cm;\n    Double_t size;\n#ifdef USEMPI\n    Double_t searchdist;\n#endif\n};\n\n///if using MPI API\n#ifdef USEMPI\n#include <mpi.h>\n///Includes external global variables used for MPI version of code\n#include \"mpivar.h\"\n#endif\n\nextern StrucLevelData *psldata;\n\n#endif\n", "meta": {"hexsha": "9cf741ed875eafdfa85e2218878572fe2c55cd16", "size": 175486, "ext": "h", "lang": "C", "max_stars_repo_path": "src/allvars.h", "max_stars_repo_name": "mtrebitsch/VELOCIraptor-STF", "max_stars_repo_head_hexsha": "3d518101e870b943777155d585db2e458e74e13f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/allvars.h", "max_issues_repo_name": "mtrebitsch/VELOCIraptor-STF", "max_issues_repo_head_hexsha": "3d518101e870b943777155d585db2e458e74e13f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/allvars.h", "max_forks_repo_name": "mtrebitsch/VELOCIraptor-STF", "max_forks_repo_head_hexsha": "3d518101e870b943777155d585db2e458e74e13f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.1906420022, "max_line_length": 224, "alphanum_fraction": 0.6490147362, "num_tokens": 48274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3073580041760868, "lm_q2_score": 0.02976009523675189, "lm_q1q2_score": 0.009147003476058327}}
{"text": "////////////////////////////////////////////////////////////\n//\n// Copyright (c) 2018 Sir Ementaler\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n//\n////////////////////////////////////////////////////////////\n\n#ifndef PICTOLEV_BINARY_SERIALIZATION_H\n#define PICTOLEV_BINARY_SERIALIZATION_H\n\n#include <algorithm>\n#include <iterator>\n#include <limits>\n#include <ostream>\n#include <type_traits>\n#include <gsl/gsl_util>\n\nenum class endian {\n#ifdef _WIN32\n\tlittle = 0,\n\tbig = 1,\n\tnative = little\n#else\n\tlittle = __ORDER_LITTLE_ENDIAN__,\n\tbig = __ORDER_BIG_ENDIAN__,\n\tnative = __BYTE_ORDER__\n#endif\n};\n\ntemplate<std::size_t N>\nvoid write_buffer(std::ostream& stream, const char (&buffer)[N]) {\n\tstream.write(buffer, N);\n}\n\ntemplate<endian Endian = endian::native, typename T>\nstd::enable_if_t<std::is_integral_v<T> && (sizeof(T) == 1)>\nwrite_binary(std::ostream& stream, T value) {\n\tstream.put(value);\n}\n\ntemplate<endian Endian, typename T>\nstd::enable_if_t<std::is_integral_v<T> && (sizeof(T) > 1)>\nwrite_binary(std::ostream& stream, T value) {\n\tstatic_assert(Endian == endian::little || Endian == endian::big);\n\tstd::make_unsigned_t<T> u_value = value;\n\tconst auto generator = [&u_value]() {\n\t\tconst char result = gsl::narrow_cast<unsigned char>(u_value);\n\t\tu_value >>= std::numeric_limits<unsigned char>::digits;\n\t\treturn result;\n\t};\n\tchar buffer[sizeof(T)] {};\n\tif constexpr (Endian == endian::little)\n\t\tstd::generate(std::begin(buffer), std::end(buffer), generator);\n\telse\n\t\tstd::generate(std::rbegin(buffer), std::rend(buffer), generator);\n\twrite_buffer(stream, buffer);\n}\n\n#endif\n", "meta": {"hexsha": "0db140f09f7a69468db29c3bad1fb40619e18171", "size": 2611, "ext": "h", "lang": "C", "max_stars_repo_path": "PicToLev/include/binary_serialization.h", "max_stars_repo_name": "SirEmentaler/PicToLev", "max_stars_repo_head_hexsha": "2319122aef4827e0b81294f5177f6f6de08a506c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PicToLev/include/binary_serialization.h", "max_issues_repo_name": "SirEmentaler/PicToLev", "max_issues_repo_head_hexsha": "2319122aef4827e0b81294f5177f6f6de08a506c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PicToLev/include/binary_serialization.h", "max_forks_repo_name": "SirEmentaler/PicToLev", "max_forks_repo_head_hexsha": "2319122aef4827e0b81294f5177f6f6de08a506c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9090909091, "max_line_length": 81, "alphanum_fraction": 0.7050938338, "num_tokens": 602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2720245510940225, "lm_q2_score": 0.03358950274784212, "lm_q1q2_score": 0.00913716940645319}}
{"text": "/*\n * optimize_tnc.h\n *\n *  Created on: Feb 9, 2010\n *      Author: smitty\n */\n\n#ifndef _OPTIMIZE_STATE_RECONSTRUCTOR_PERIODS_NLOPT_H_\n#define _OPTIMIZE_STATE_RECONSTRUCTOR_PERIODS_NLOPT_H_\n\n#include <nlopt.h>\n\n#include \"state_reconstructor.h\"\n#include \"rate_model.h\"\n\n#include <armadillo>\nusing namespace arma;\n\nvoid optimize_sr_periods_nlopt(vector<RateModel> * _rm,StateReconstructor * _sr,\n    vector<mat> * _free_mask, int _nfree);\n\n#endif /* _OPTIMIZE_STATE_RECONSTRUCTOR_PERIODS_NLOPT_H_ */\n", "meta": {"hexsha": "11ebc551dc4983a2b60cde6a42cbafb29d52b764", "size": 498, "ext": "h", "lang": "C", "max_stars_repo_path": "src/phyx-1.01/src/optimize_state_reconstructor_periods_nlopt.h", "max_stars_repo_name": "jlanga/smsk_selection", "max_stars_repo_head_hexsha": "08070c6d4a6fbd9320265e1e698c95ba80f81123", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-07-18T05:20:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T10:22:33.000Z", "max_issues_repo_path": "src/phyx-1.01/src/optimize_state_reconstructor_periods_nlopt.h", "max_issues_repo_name": "jlanga/smsk_selection", "max_issues_repo_head_hexsha": "08070c6d4a6fbd9320265e1e698c95ba80f81123", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-08-21T07:26:13.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-08T13:59:48.000Z", "max_forks_repo_path": "src/phyx-1.01/src/optimize_state_reconstructor_periods_nlopt.h", "max_forks_repo_name": "jlanga/smsk_orthofinder", "max_forks_repo_head_hexsha": "08070c6d4a6fbd9320265e1e698c95ba80f81123", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-07-18T05:20:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:23:31.000Z", "avg_line_length": 21.652173913, "max_line_length": 80, "alphanum_fraction": 0.7730923695, "num_tokens": 141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.33111975283019596, "lm_q2_score": 0.027585281527290968, "lm_q1q2_score": 0.009134031601067955}}
{"text": "/*\n  *  This code is to merge all the files among different directories once the MCRaT simulation is complete\n  *  The input should be the main CMC directory and the sub directories of each angle range with the number of MPI processes used to start the simulation in each directory\n  *  eg call: mpiexec -np X /.merge /dir/to/CMC_dir/  \n  *  where X shuould be a multiple of the number of sub directories\n  *  SHOULD BE COMPILED WITH -O2 OPTIMIZATION\n*/ //TEST WITH PROCESSES INJECTING IN MULTIPLE FRAMES\n\n#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n#include <sys/types.h>\n#include <dirent.h>\n#include <sys/stat.h>\n#include <unistd.h>\n#include <errno.h>\n#include <math.h>\n#include <gsl/gsl_rng.h>\n#include \"hdf5.h\"\n#include \"mclib.h\"\n#include \"mpi.h\"\n\nint main(int argc, char **argv)\n{\n    double *p0=NULL, *p1=NULL, *p2=NULL, *p3=NULL, *comv_p0=NULL, *comv_p1=NULL, *comv_p2=NULL, *comv_p3=NULL, *r0=NULL, *r1=NULL, *r2=NULL, *s0=NULL, *s1=NULL, *s2=NULL, *s3=NULL, *num_scatt=NULL, *weight=NULL;\n    double *p0_p=NULL, *p1_p=NULL, *p2_p=NULL, *p3_p=NULL, *comv_p0_p=NULL, *comv_p1_p=NULL, *comv_p2_p=NULL, *comv_p3_p=NULL, *r0_p=NULL, *r1_p=NULL, *r2_p=NULL, *s0_p=NULL, *s1_p=NULL, *s2_p=NULL, *s3_p=NULL, *num_scatt_p=NULL, *weight_p=NULL;\n    int num_angle_dirs=0, i=0, j=0, k=0, l=0, num_types=12;\n    int *num_procs_per_dir=NULL, frm0_small, frm0_large, last_frm, frm2_small, frm2_large, small_frm, large_frm, frm=0, all_photons;\n    int *frm_array=NULL, *each_subdir_number=NULL, *displPtr=NULL;\n    int myid, numprocs, subdir_procs, subdir_id, frames_to_merge, start_count, end_count ;\n    int  count=0, index=0,  isNotCorrupted=0;\n    int file_count = 0, max_num_procs_per_dir=0;\n    int *photon_injection_count=NULL;\n    double garbage;\n    char mc_file[500]=\"\" ;\n    char dir[500]=\"\";\n    char group[500]=\"\";\n    char merged_filename[500]=\"\";\n    char filename_k[2000]=\"\", mcdata_type[20]=\"\";\n    char *str=\"mc_proc_\", *ph_type=NULL, *ph_type_p=NULL;\n    struct dirent* dent;\n    DIR * dirp;\n    struct dirent * entry;\n    DIR* srcdir = opendir(argv[1]);\n    \n    MPI_Datatype stype;\n    hid_t       file, file_id, group_id, dspace, fspace, mspace;         /* file and dataset identifiers */\n    hid_t\tplist_id_file, plist_id_data;        /* property list identifier( access template) */\n    hsize_t dims[1]={0},dims_old[1]={0};\n     hsize_t maxdims[1]={H5S_UNLIMITED};\n     hsize_t      size[1];\n    hsize_t      offset[1];\n    herr_t\tstatus, status_group;\n    hid_t dset_p0, dset_p1, dset_p2, dset_p3, dset_comv_p0, dset_comv_p1, dset_comv_p2, dset_comv_p3, dset_r0, dset_r1, dset_r2, dset_s0, dset_s1, dset_s2, dset_s3, dset_num_scatt, dset_weight, dset_ph_type;\n    \n    #if COMV_SWITCH == ON && STOKES_SWITCH == ON\n    {\n        num_types=17;//both switches on, want to save comv and stokes\n    }\n    #elif COMV_SWITCH == ON || STOKES_SWITCH == ON\n    {\n        num_types=13;//either switch acivated, just subtract 4 datasets\n    }\n    #else\n    {\n        num_types=9;//just save lab 4 momentum, position and num_scatt\n    }\n    #endif\n    \n    #if SAVE_TYPE == ON\n    {\n        num_types+=1;\n    }\n    #endif\n\n\n    while((dent = readdir(srcdir)) != NULL)\n    {\n        struct stat st;\n        //file_count=0;\n        \n        if(strcmp(dent->d_name, \".\") == 0 || strcmp(dent->d_name, \"..\") == 0)\n            continue;\n\n        if (fstatat(dirfd(srcdir), dent->d_name, &st, 0) < 0)\n        {\n            perror(dent->d_name);\n            continue;\n        }\n\n        if (S_ISDIR(st.st_mode)) \n        {\n            //snprintf(dir,sizeof(dir),\"%s\",dent->d_name );\n            if (strstr(dent->d_name, \"ALL_DATA\") == NULL)\n            {\n                num_angle_dirs++;\n                //printf(\"found directory %s\\n\", dent->d_name);\n            }\n        }\n        \n    }\n    \n    closedir(srcdir);\n    \n    num_procs_per_dir=malloc(num_angle_dirs*sizeof(int));\n    each_subdir_number=malloc(num_angle_dirs*sizeof(int));\n    displPtr=malloc(num_angle_dirs*sizeof(int));\n    *(displPtr+0)=0;\n     char *dirs[num_angle_dirs];\n    \n    count=0;\n    srcdir = opendir(argv[1]);\n    while((dent = readdir(srcdir)) != NULL)\n    {\n        struct stat st;\n        file_count=0;\n        \n        if(strcmp(dent->d_name, \".\") == 0 || strcmp(dent->d_name, \"..\") == 0)\n            continue;\n\n        if (fstatat(dirfd(srcdir), dent->d_name, &st, 0) < 0)\n        {\n            perror(dent->d_name);\n            continue;\n        }\n\n        if (S_ISDIR(st.st_mode)) \n        {\n            //printf(\"found directory %s\\n\", dent->d_name);\n             if (strstr(dent->d_name, \"ALL_DATA\") == NULL)\n            {\n                snprintf(dir,sizeof(dir),\"%s%s/\",argv[1],dent->d_name );\n                dirs[count] =  malloc((strlen(dir)+1));\n                strcpy(dirs[count],dir);\n                //printf(\"SECOND: found directory %s\\n\", dirs[count]);\n            \n                dirp = opendir(dir); //do into the directory to get each file\n                while ((entry = readdir(dirp)) != NULL) \n                {\n                    if ((entry->d_type == DT_REG) && (strstr(entry->d_name, str) != NULL))\n                    { /* If the entry is a regular file  */\n                        file_count++;\n                        //printf(\"%s\\n\", entry->d_name );\n                    }\n                }\n                *(num_procs_per_dir +count)=file_count;\n                if (max_num_procs_per_dir<file_count)\n                {\n                    max_num_procs_per_dir=file_count; //find the max number of processes in each directory\n                }\n                \n                count++;\n            }\n        }\n        \n    }\n    \n    closedir(srcdir);\n    \n    //find number of directories for each angle range\n    //printf(\"%s: %d\\n\", argv[1], num_angle_dirs);\n    \n    //for (i=0;i<num_angle_dirs;i++)\n    //{\n     //   printf(\"%d\\n\", *(num_procs_per_dir+i));\n     //   printf(\" %s\\n\",  dirs[i]);\n    //}\n    \n    //get the last and initial hydro file in sim\n    snprintf(mc_file,sizeof(mc_file),\"%s%s\",argv[1],MCPAR);\n    readMcPar(mc_file, &garbage, &garbage, &garbage,&garbage, &garbage, &garbage, &garbage,&garbage, &frm0_small,&frm0_large, &last_frm ,&frm2_small, &frm2_large, &garbage, &garbage, &i, &i, &i,&i); //thetas that comes out is in degrees\n        //printf(\"%s frm_0small: %d frm_0large: %d, last: %d\\n\", mc_file, frm0_small,frm0_large, last_frm);\n    \n    //with all the info make array of all the files that need to be created\n    small_frm= (frm0_small < frm0_large) ? frm0_small : frm0_large;\n    large_frm= (frm2_small > frm2_large) ? frm2_small : frm2_large;\n    frm_array=malloc(sizeof(int)*(last_frm-small_frm+1));\n    count=0;\n    for (i=small_frm;i<last_frm+1;i++)\n    {\n        //printf(\"Count: %d\\n\",count);\n        *(frm_array+count)=i;\n        count++;\n    }\n    \n    //set up the ALL_DATA directory name\n    snprintf(dir,sizeof(dir),\"%sALL_DATA/\",argv[1] );\n    \n    //set up MPI and break up the processes into groups of the number of sub directories\n    MPI_Init(NULL,NULL);\n    MPI_Comm_size(MPI_COMM_WORLD, &numprocs);\n    MPI_Comm_rank(MPI_COMM_WORLD, &myid);\n    \n    //break up into groups by subdir\n    index= myid/num_angle_dirs;\n    MPI_Comm frames_to_merge_comm;\n    MPI_Comm_split(MPI_COMM_WORLD, index , myid, &frames_to_merge_comm);\n    MPI_Comm_rank(frames_to_merge_comm, &subdir_id);\n    MPI_Comm_size(frames_to_merge_comm, &subdir_procs);\n    \n    frames_to_merge=(count-1)/(numprocs/num_angle_dirs); //count-1 b/c @ end of loop it added 1\n    start_count=*(frm_array+(index*frames_to_merge));\n    end_count=*(frm_array+((index+1)*frames_to_merge));\n    \n\n    if (index==(numprocs/num_angle_dirs)-1)\n    {\n        //printf(\"in If\\n\");\n        end_count=*(frm_array+(count-1))+1;\n    }\n    \n    \n    \n    \n    printf(\"subdir_id %d, subdir_procs %d subdir %s, num of frames to merge %d, index %d\\n\", subdir_id, subdir_procs, dirs[subdir_id], frames_to_merge, index );\n    printf(\"Start file %d end file %d\\n\", start_count, end_count);\n    \n    //exit(0);\n    \n    if (myid==0)\n    {\n        //have 1st process see if the folder ALL_DATA exists and if not create it\n        dirp = opendir(dir);\n        if (ENOENT == errno)\n        {\n            //if it doesnt exist create it\n            mkdir(dir, 0777); //make the directory with full permissions\n        }\n        else\n        {\n            closedir(dirp);\n        }\n    }\n    \n    //directory exists now, can create files in it with appropriate datasets, all processes in communicator participate in this\n    //Set up file access property list with parallel I/O access\n    MPI_Info info  = MPI_INFO_NULL;\n    \n    photon_injection_count=malloc((*(num_procs_per_dir+subdir_id))*sizeof(int)); //to incrememnt the number of photons already injected by a process\n    for (k=0;k<*(num_procs_per_dir+subdir_id);k++)\n    {\n        *(photon_injection_count+k)=0;\n    }\n    \n    //create files\n    //start_count=2474;\n    //end_count=143;\n    for (i= end_count-1; i>=start_count;i--)\n    {\n        //go through the mpi files to find the total number of photons needed for the final dataset  \n        //printf(\"\\n\\n%d\\n\", i);\n        dims[0]=0;\n         j=0;\n        for (k=0;k<*(num_procs_per_dir+subdir_id);k++)\n        {\n            //for each process' file, find out how many elements and add up to find total number of elements needed in the data set for the frame number\n            snprintf(filename_k,sizeof(filename_k),\"%s%s%d%s\",dirs[subdir_id],\"mc_proc_\", k, \".h5\" );\n            //printf(\"Dir: %s\\n\",filename_k );\n            \n            //open the file\n            file=H5Fopen(filename_k, H5F_ACC_RDONLY, H5P_DEFAULT);\n            \n            \n            //see if the frame exists\n            snprintf(group,sizeof(group),\"%d\",i );\n            status = H5Eset_auto(NULL, NULL, NULL);\n            status_group = H5Gget_objinfo (file, group, 0, NULL);\n            status = H5Eset_auto(H5E_DEFAULT, H5Eprint2, stderr);\n            \n            //if it does open it and read in the size\n            if (status_group == 0)\n            {\n                //open the datatset\n                group_id = H5Gopen2(file, group, H5P_DEFAULT);\n                dset_p0 = H5Dopen (group_id, \"P0\", H5P_DEFAULT); //open dataset\n                \n                //get the number of points\n                dspace = H5Dget_space (dset_p0);\n                status=H5Sget_simple_extent_dims(dspace, dims, NULL); //save dimesnions in dims\n                j+=dims[0];//calculate the total number of photons to save to new hdf5 file\n                \n                //printf(\"File %s num_ph %d\\n\", filename_k, j);\n                \n                status = H5Sclose (dspace);\n                status = H5Dclose (dset_p0);\n                status = H5Gclose(group_id);\n            }\n            status = H5Fclose(file);\n            \n        }\n        \n        //find total number of photons\n        MPI_Allreduce(&j, &all_photons, 1, MPI_INT, MPI_SUM, frames_to_merge_comm);\n        \n        //get the number for each subdir for later use\n        //MPI_Allgather(&j, 1, MPI_INT, each_subdir_number, 1, MPI_INT, frames_to_merge_comm);\n        \n        //set up the displacement of data\n        //for (j=1;j<num_angle_dirs;j++)\n        //{\n        //    *(displPtr+j)=(*(displPtr+j-1))+(*(each_subdir_number+j-1));\n        //}\n        \n        //if (subdir_id==0)\n        //{\n        //    printf(\"Frame: %d Total photons %d\\n\", i, all_photons);\n        //}\n        \n        \n        plist_id_file = H5Pcreate(H5P_FILE_ACCESS);\n        H5Pset_fapl_mpio(plist_id_file, frames_to_merge_comm, info);\n        \n        snprintf(merged_filename,sizeof(merged_filename),\"%smcdata_%d.h5\",dir, i );\n        status = H5Eset_auto(NULL, NULL, NULL); //turn off automatic error printing\n        file_id = H5Fcreate(merged_filename, H5F_ACC_EXCL, H5P_DEFAULT, plist_id_file);\n        status = H5Eset_auto(H5E_DEFAULT, H5Eprint2, stderr); //turn on auto error printing\n        \n        //if the file exists we have to check it to ensure its not corrupted\n        \n         if (file_id<0)\n        {\n            //printf( \"Checking File %s\\n\",merged_filename );\n            //the file exists, open it with read write \n            file_id=H5Fopen(merged_filename, H5F_ACC_RDWR, plist_id_file);\n            \n            for (k=0;k<num_types;k++)\n            {\n                #if COMV_SWITCH == ON && STOKES_SWITCH == ON\n                {\n                    switch (k)\n                    {\n                        case 0: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"P0\"); break;\n                        case 1: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"P1\");break;\n                        case 2: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"P2\"); break;\n                        case 3: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"P3\"); break;\n                        case 4: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"COMV_P0\"); break;\n                        case 5: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"COMV_P1\");break;\n                        case 6: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"COMV_P2\"); break;\n                        case 7: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"COMV_P3\"); break;\n                        case 8: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"R0\"); break;\n                        case 9: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"R1\"); break;\n                        case 10: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"R2\"); break;\n                        case 11: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"S0\"); break;\n                        case 12: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"S1\");break;\n                        case 13: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"S2\"); break;\n                        case 14: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"S3\"); break;\n                        case 15: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"NS\"); break;\n                        case 16: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"PW\"); break;\n                        #if SAVE_TYPES == ON\n                        {\n                            case 17: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"PT\"); break;\n                        }\n                        #endif\n\n                    }\n                }\n                #elif STOKES_SWITCH == ON && COMV_SWITCH == OFF\n                {\n                    switch (k)\n                    {\n                        case 0: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"P0\"); break;\n                        case 1: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"P1\");break;\n                        case 2: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"P2\"); break;\n                        case 3: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"P3\"); break;\n                        case 4: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"R0\"); break;\n                        case 5: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"R1\"); break;\n                        case 6: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"R2\"); break;\n                        case 7: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"S0\"); break;\n                        case 8: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"S1\");break;\n                        case 9: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"S2\"); break;\n                        case 10: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"S3\"); break;\n                        case 11: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"NS\"); break;\n                        case 12: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"PW\"); break;\n                        #if SAVE_TYPES == ON\n                        {\n                            case 13: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"PT\"); break;\n                        }\n                        #endif\n\n                    }\n                }\n                #elif STOKES_SWITCH == OFF && COMV_SWITCH == ON\n                {\n                    switch (k)\n                    {\n                        case 0: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"P0\"); break;\n                        case 1: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"P1\");break;\n                        case 2: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"P2\"); break;\n                        case 3: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"P3\"); break;\n                        case 4: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"COMV_P0\"); break;\n                        case 5: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"COMV_P1\");break;\n                        case 6: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"COMV_P2\"); break;\n                        case 7: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"COMV_P3\"); break;\n                        case 8: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"R0\"); break;\n                        case 9: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"R1\"); break;\n                        case 10: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"R2\"); break;\n                        case 11: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"NS\"); break;\n                        case 12: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"PW\"); break;\n                        #if SAVE_TYPES == ON\n                        {\n                            case 13: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"PT\"); break;\n                        }\n                        #endif\n                    }\n                }\n                #else\n                {\n                    switch (k)\n                    {\n                        case 0: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"P0\"); break;\n                        case 1: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"P1\");break;\n                        case 2: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"P2\"); break;\n                        case 3: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"P3\"); break;\n                        case 4: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"R0\"); break;\n                        case 5: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"R1\"); break;\n                        case 6: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"R2\"); break;\n                        case 7: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"NS\"); break;\n                        case 8: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"PW\"); break;\n                        #if SAVE_TYPES == ON\n                        {\n                            case 9: snprintf(mcdata_type,sizeof(mcdata_type), \"%s\", \"PT\"); break;\n                        }\n                        #endif\n                    }\n                }\n                #endif\n            \n                //open the datatset\n                dset_p0 = H5Dopen (file_id, mcdata_type, H5P_DEFAULT); //open dataset\n                \n                //get the number of points\n                dspace = H5Dget_space (dset_p0);\n                status=H5Sget_simple_extent_dims(dspace, dims, NULL); //save dimesnions in dims\n                \n                //fprintf(fPtr, \"j:%d, dim: %d\\n\",j, dims[0] );\n                //fflush(fPtr);\n                \n                isNotCorrupted += fmod(dims[0], all_photons); //if the dimension is the dame then the fmod ==0 (remainder of 0), if all datatsets are ==0 then you get a truth value of 0 meaning that it isnt corrupted\n                \n                status = H5Sclose (dspace);\n                status = H5Dclose (dset_p0);\n            }\n            \n            status = H5Fclose(file_id);\n            file_id=-1; //do this so if the file exists it doesnt go into the rewriting portion just based on that\n        }\n        \n        //printf(\"file %s has isNotCorrupted=%d\\n\", merged_filename, isNotCorrupted );\n        \n        \n        if ((file_id>=0) || (isNotCorrupted != 0 ))\n        {\n            if (isNotCorrupted != 0)\n            {\n                //if the data is corrupted overwrite the file\n                file_id = H5Fcreate(merged_filename, H5F_ACC_TRUNC, H5P_DEFAULT, plist_id_file);\n            }\n            \n            frm=(i <  large_frm) ? i  : large_frm;\n            \n            for (k=0;k<*(num_procs_per_dir+subdir_id);k++)\n            {\n                *(photon_injection_count+k)=0; //reset the count to 0\n            }\n            \n            //order data based on which processes injected photons 1st\n            #if SYNCHROTRON_SWITCH == ON\n            l=i;\n            #else\n            for (l=small_frm;l<frm+1;l++)\n            #endif\n            {\n                //printf(\"\\n\\n %d\\n\\n\",l);\n                //read the data in from each process in a given subdir, use max_num_procs_per_dir in case one directory used more processes than the others and deal with it in code\n                for (k=0;k<max_num_procs_per_dir;k++)\n                {                \n                \n                    dims[0]=0;\n                    j=0;\n                    //for each process' file, find out how many elements and add up to find total number of elements needed in the data set for the frame number\n                    snprintf(filename_k,sizeof(filename_k),\"%s%s%d%s\",dirs[subdir_id],\"mc_proc_\", k, \".h5\" );\n                    //printf(\"Dir: %s\\n\",filename_k );\n            \n                    if (k<*(num_procs_per_dir+subdir_id))\n                    {\n                        //we know that the process exists and the file should exist\n                        //open the file\n                        status = H5Eset_auto(NULL, NULL, NULL); //turn of error printing if the file doesnt exist, if the process number doesnt exist\n                        file=H5Fopen(filename_k, H5F_ACC_RDONLY, H5P_DEFAULT);\n                        status = H5Eset_auto(H5E_DEFAULT, H5Eprint2, stderr);\n                    }\n                    else\n                    {\n                        //know that the process doesnt exist within that subdirectory so dont rry to open a non-existant file\n                        file=-1;\n                    }\n                \n                    if (file>=0)\n                    {\n                        {\n\n                            //see if the frame exists\n                            /*\n                            snprintf(group,sizeof(group),\"%d\",i );\n                            status = H5Eset_auto(NULL, NULL, NULL);\n                            status_group = H5Gget_objinfo (file, group, 0, NULL);\n                            status = H5Eset_auto(H5E_DEFAULT, H5Eprint2, stderr);\n                            */\n                            snprintf(group,sizeof(group),\"%d/PW\",l );\n                            status = H5Eset_auto(NULL, NULL, NULL);\n                            status_group = H5Gget_objinfo (file, group, 0, NULL);\n                            status = H5Eset_auto(H5E_DEFAULT, H5Eprint2, stderr);\n                        }\n\n                    }\n                \n            \n                    //if it does open it and read in the size\n                    //#if SYNCHROTRON_SWITCH == ON\n                    //if (status_group >= 0 && file>=0 && l>=i)\n                    //#else\n                    if (status_group >= 0 && file>=0)\n                    //#endif\n                    {\n                        //read in the number of injected photons first\n                        #if SYNCHROTRON_SWITCH == ON\n                            snprintf(group,sizeof(group),\"%d\",i );\n                        #else\n                            snprintf(group,sizeof(group),\"%d\",l );\n                        #endif\n                        group_id = H5Gopen2(file, group, H5P_DEFAULT);\n                        dset_weight = H5Dopen (group_id, \"PW\", H5P_DEFAULT);\n                        dspace = H5Dget_space (dset_weight);\n                        status=H5Sget_simple_extent_dims(dspace, dims, NULL); //save dimesnions in dims\n                        j=dims[0];//calculate the total number of photons to save to new hdf5 file\n                        status = H5Sclose (dspace);\n                        status = H5Dclose (dset_weight);\n                        status = H5Gclose(group_id);\n                        //printf(\"Num of ph: %d\\n\", j);\n                        \n                        snprintf(group,sizeof(group),\"%d\",i ); \n                    \n                        //printf(\"Opening dataset\\n\");\n                            //open the datatset\n                        group_id = H5Gopen2(file, group, H5P_DEFAULT);\n                        dset_p0 = H5Dopen (group_id, \"P0\", H5P_DEFAULT); //open dataset\n                        dset_p1 = H5Dopen (group_id, \"P1\", H5P_DEFAULT);\n                        dset_p2 = H5Dopen (group_id, \"P2\", H5P_DEFAULT);\n                        dset_p3 = H5Dopen (group_id, \"P3\", H5P_DEFAULT);\n                        \n                        #if COMV_SWITCH == ON\n                        {\n                            dset_comv_p0 = H5Dopen (group_id, \"COMV_P0\", H5P_DEFAULT); //open dataset\n                            dset_comv_p1 = H5Dopen (group_id, \"COMV_P1\", H5P_DEFAULT);\n                            dset_comv_p2 = H5Dopen (group_id, \"COMV_P2\", H5P_DEFAULT);\n                            dset_comv_p3 = H5Dopen (group_id, \"COMV_P3\", H5P_DEFAULT);\n                        }\n                        #endif\n                        \n                        dset_r0 = H5Dopen (group_id, \"R0\", H5P_DEFAULT); \n                        dset_r1 = H5Dopen (group_id, \"R1\", H5P_DEFAULT);\n                        dset_r2 = H5Dopen (group_id, \"R2\", H5P_DEFAULT);\n                        \n                        #if STOKES_SWITCH == ON\n                        {\n                            dset_s0 = H5Dopen (group_id, \"S0\", H5P_DEFAULT);\n                            dset_s1 = H5Dopen (group_id, \"S1\", H5P_DEFAULT);\n                            dset_s2 = H5Dopen (group_id, \"S2\", H5P_DEFAULT);\n                            dset_s3 = H5Dopen (group_id, \"S3\", H5P_DEFAULT);\n                        }\n                        #endif\n                        \n                        dset_num_scatt = H5Dopen (group_id, \"NS\", H5P_DEFAULT);\n                        \n                        #if SYNCHROTRON_SWITCH == ON\n                        {\n                            dset_weight = H5Dopen (group_id, \"PW\", H5P_DEFAULT);\n                        }\n                        #else\n                        {\n                            dset_weight = H5Dopen (file, \"PW\", H5P_DEFAULT);//for non synch runs look at the global /PW dataset\n                        }\n                        #endif\n                        \n                        #if SAVE_TYPE == ON\n                        {\n                            dset_ph_type = H5Dopen (group_id, \"PT\", H5P_DEFAULT);\n                        }\n                        #endif\n\n                        \n                        //malloc memory\n                        p0_p=malloc(j*sizeof(double));  p1_p=malloc(j*sizeof(double));  p2_p=malloc(j*sizeof(double));  p3_p=malloc(j*sizeof(double));\n                        \n                        #if COMV_SWITCH == ON\n                        {\n                            comv_p0_p=malloc(j*sizeof(double));  comv_p1_p=malloc(j*sizeof(double));  comv_p2_p=malloc(j*sizeof(double));  comv_p3_p=malloc(j*sizeof(double));\n                        }\n                        #endif\n                        \n                        r0_p=malloc(j*sizeof(double));  r1_p=malloc(j*sizeof(double));  r2_p=malloc(j*sizeof(double));\n                        \n                        #if STOKES_SWITCH == ON\n                        {\n                            s0_p=malloc(j*sizeof(double));  s1_p=malloc(j*sizeof(double));  s2_p=malloc(j*sizeof(double));  s3_p=malloc(j*sizeof(double));\n                        }\n                        #endif\n                        \n                        #if SAVE_TYPE == ON\n                        {\n                            ph_type_p=malloc((j)*sizeof(char));\n                        }\n                        #endif\n                        \n                        num_scatt_p=malloc(j*sizeof(double));\n                        \n                        weight_p=malloc(j*sizeof(double));\n                        \n                        //printf(\"file %d frame: %d, process  %d start: %d, j: %d\\n\", i, l, k, *(photon_injection_count+k), dims[0]);\n                        \n                        #if SYNCHROTRON_SWITCH == ON\n                        {\n                            offset[0]=0;\n                        }\n                        #else\n                        {\n                            offset[0]=*(photon_injection_count+k);\n                        }\n                        #endif\n                        \n                        //have to read in the data from *(photon_injection_count+k) to *(photon_injection_count+k)+j\n                        mspace = H5Screate_simple (1, dims, NULL);\n                        dspace = H5Dget_space(dset_p0);\n                        status = H5Sselect_hyperslab (dspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                        \n                \n                        //read the data in\n                        status = H5Dread(dset_p0, H5T_NATIVE_DOUBLE, mspace, dspace, H5P_DEFAULT, (p0_p));\n                        status = H5Sclose (dspace);  status = H5Dclose (dset_p0);\n                        \n                        dspace = H5Dget_space(dset_p1);\n                        status = H5Sselect_hyperslab (dspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                        status = H5Dread(dset_p1, H5T_NATIVE_DOUBLE, mspace, dspace, H5P_DEFAULT, (p1_p));\n                        status = H5Sclose (dspace);  status = H5Dclose (dset_p1);\n                        \n                        dspace = H5Dget_space(dset_p2);\n                        status = H5Sselect_hyperslab (dspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                        status = H5Dread(dset_p2, H5T_NATIVE_DOUBLE, mspace, dspace, H5P_DEFAULT, (p2_p));\n                        status = H5Sclose (dspace); status = H5Dclose (dset_p2); \n                        \n                        dspace = H5Dget_space(dset_p3);\n                        status = H5Sselect_hyperslab (dspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                        status = H5Dread(dset_p3, H5T_NATIVE_DOUBLE, mspace, dspace, H5P_DEFAULT, (p3_p));\n                        status = H5Sclose (dspace); status = H5Dclose (dset_p3);\n                        \n                        #if COMV_SWITCH == ON\n                        {\n                            dspace = H5Dget_space(dset_comv_p0);\n                            status = H5Sselect_hyperslab (dspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                            status = H5Dread(dset_comv_p0, H5T_NATIVE_DOUBLE, mspace, dspace, H5P_DEFAULT, (comv_p0_p));\n                            status = H5Sclose (dspace);  status = H5Dclose (dset_comv_p0);\n                            \n                            dspace = H5Dget_space(dset_comv_p1);\n                            status = H5Sselect_hyperslab (dspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                            status = H5Dread(dset_comv_p1, H5T_NATIVE_DOUBLE, mspace, dspace, H5P_DEFAULT, (comv_p1_p));\n                            status = H5Sclose (dspace);  status = H5Dclose (dset_comv_p1);\n                            \n                            dspace = H5Dget_space(dset_comv_p2);\n                            status = H5Sselect_hyperslab (dspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                            status = H5Dread(dset_comv_p2, H5T_NATIVE_DOUBLE, mspace, dspace, H5P_DEFAULT, (comv_p2_p));\n                            status = H5Sclose (dspace);  status = H5Dclose (dset_comv_p2);\n                            \n                            dspace = H5Dget_space(dset_comv_p3);\n                            status = H5Sselect_hyperslab (dspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                            status = H5Dread(dset_comv_p3, H5T_NATIVE_DOUBLE, mspace, dspace, H5P_DEFAULT, (comv_p3_p));\n                            status = H5Sclose (dspace);  status = H5Dclose (dset_comv_p3);\n                        }\n                        #endif\n                        \n                        dspace = H5Dget_space(dset_r0);\n                        status = H5Sselect_hyperslab (dspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                        status = H5Dread(dset_r0, H5T_NATIVE_DOUBLE, mspace, dspace, H5P_DEFAULT, (r0_p));\n                        status = H5Sclose (dspace); status = H5Dclose (dset_r0); \n                        \n                        dspace = H5Dget_space(dset_r1);\n                        status = H5Sselect_hyperslab (dspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                        status = H5Dread(dset_r1, H5T_NATIVE_DOUBLE, mspace, dspace, H5P_DEFAULT, (r1_p));\n                        status = H5Sclose (dspace); status = H5Dclose (dset_r1); \n                        \n                        dspace = H5Dget_space(dset_r2);\n                        status = H5Sselect_hyperslab (dspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                        status = H5Dread(dset_r2, H5T_NATIVE_DOUBLE, mspace, dspace, H5P_DEFAULT, (r2_p));\n                        status = H5Sclose (dspace); status = H5Dclose (dset_r2);\n                        \n                        #if STOKES_SWITCH == ON\n                        {\n                            dspace = H5Dget_space(dset_s0);\n                            status = H5Sselect_hyperslab (dspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                            status = H5Dread(dset_s0, H5T_NATIVE_DOUBLE, mspace, dspace, H5P_DEFAULT, (s0_p));\n                            status = H5Sclose (dspace); status = H5Dclose (dset_s0);\n                            \n                            dspace = H5Dget_space(dset_s1);\n                            status = H5Sselect_hyperslab (dspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                            status = H5Dread(dset_s1, H5T_NATIVE_DOUBLE, mspace, dspace, H5P_DEFAULT, (s1_p));\n                            status = H5Sclose (dspace); status = H5Dclose (dset_s1);\n                            \n                            dspace = H5Dget_space(dset_s2);\n                            status = H5Sselect_hyperslab (dspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                            status = H5Dread(dset_s2, H5T_NATIVE_DOUBLE, mspace, dspace, H5P_DEFAULT, (s2_p));\n                            status = H5Sclose (dspace); status = H5Dclose (dset_s2);\n                            \n                            dspace = H5Dget_space(dset_s3);\n                            status = H5Sselect_hyperslab (dspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                            status = H5Dread(dset_s3, H5T_NATIVE_DOUBLE, mspace, dspace, H5P_DEFAULT, (s3_p));\n                            status = H5Sclose (dspace); status = H5Dclose (dset_s3);\n                        }\n                        #endif\n                        \n                        dspace = H5Dget_space(dset_num_scatt);\n                        status = H5Sselect_hyperslab (dspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                        status = H5Dread(dset_num_scatt, H5T_NATIVE_DOUBLE, mspace, dspace, H5P_DEFAULT, (num_scatt_p));\n                        status = H5Sclose (dspace); status = H5Dclose (dset_num_scatt);\n                        \n                        //printf(\"Before Weight read\\n\");\n                        dspace = H5Dget_space(dset_weight);\n                        status = H5Sselect_hyperslab (dspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                        status = H5Dread(dset_weight, H5T_NATIVE_DOUBLE, mspace, dspace, H5P_DEFAULT, (weight_p));\n                        status = H5Sclose (dspace); status = H5Dclose (dset_weight);\n                        //printf(\"After Weight read\\n\");\n                        \n                        #if SAVE_TYPE == ON\n                        {\n                            dspace = H5Dget_space(dset_ph_type);\n                            status = H5Sselect_hyperslab (dspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                            status = H5Dread(dset_ph_type, H5T_NATIVE_CHAR, mspace, dspace, H5P_DEFAULT, (ph_type_p));\n                            status = H5Sclose (dspace); status = H5Dclose (dset_ph_type);\n                        }\n                        #endif\n                        \n                        status = H5Sclose (mspace);\n                        status = H5Gclose(group_id);\n                        \n                        \n                        \n                        //#if SYNCHROTRON_SWITCH == ON\n                        //{\n                        //    *(photon_injection_count+k)+=0;\n                        //}\n                        //#else\n                        {\n                            *(photon_injection_count+k)+=j;\n                        }\n                        //#endif\n                    }\n                    else\n                    {\n                        //allocate memory so Allgather doesn't fail with NULL pointer\n                        j=1;\n                        p0_p=malloc(j*sizeof(double));  p1_p=malloc(j*sizeof(double));  p2_p=malloc(j*sizeof(double));  p3_p=malloc(j*sizeof(double));\n                        \n                        #if COMV_SWITCH == ON\n                        {\n                            comv_p0_p=malloc(j*sizeof(double));  comv_p1_p=malloc(j*sizeof(double));  comv_p2_p=malloc(j*sizeof(double));  comv_p3_p=malloc(j*sizeof(double));\n                        }\n                        #endif\n                        \n                        r0_p=malloc(j*sizeof(double));  r1_p=malloc(j*sizeof(double));  r2_p=malloc(j*sizeof(double));\n                        \n                        #if STOKES_SWITCH == ON\n                        {\n                            s0_p=malloc(j*sizeof(double));  s1_p=malloc(j*sizeof(double));  s2_p=malloc(j*sizeof(double));  s3_p=malloc(j*sizeof(double));\n                        }\n                        #endif\n                        \n                        #if SAVE_TYPE == ON\n                        {\n                            ph_type_p=malloc((j)*sizeof(char));\n                        }\n                        #endif\n                        \n                        num_scatt_p=malloc(j*sizeof(double));\n                        \n                        weight_p=malloc(j*sizeof(double));\n                    }\n                    \n                    //find total number of photons\n                    MPI_Allreduce(&dims[0], &all_photons, 1, MPI_INT, MPI_SUM,  frames_to_merge_comm);\n                    //dims[0]=all_photons;\n                    \n                    //printf(\"ID %d j: %d\\n\", subdir_id, dims[0]);\n                    \n                    //get the number for each subdir for later use\n                    MPI_Allgather(&dims[0], 1, MPI_INT, each_subdir_number, 1, MPI_INT,   frames_to_merge_comm);\n                    //for (j=0;j<num_angle_dirs;j++)\n                    //{\n                     //    printf(\"ID %d eachsubdir_num %d \\n\",  subdir_id, *(each_subdir_number+j));\n                    //}\n                    \n        \n                    //set up the displacement of data\n                    for (j=1;j<num_angle_dirs;j++)\n                    {\n                        *(displPtr+j)=(*(displPtr+j-1))+(*(each_subdir_number+j-1));\n                         //printf(\"Displ %d eachsubdir_num %d \\n\",  *(displPtr+j), *(each_subdir_number+j-1));\n                    }\n        \n                    //if (subdir_id==0)\n                    //{\n                    //    printf(\"Frame: %d Total photons %d\\n\", i, all_photons);\n                    //}\n                    \n                    //now allocate enough ememory for all_photons in the mpi files from proc 0 initially \n                    p0=malloc(all_photons*sizeof(double));  p1=malloc(all_photons*sizeof(double));  p2=malloc(all_photons*sizeof(double));  p3=malloc(all_photons*sizeof(double));\n                    \n                    #if COMV_SWITCH == ON\n                    {\n                        comv_p0=malloc(all_photons*sizeof(double));  comv_p1=malloc(all_photons*sizeof(double));  comv_p2=malloc(all_photons*sizeof(double));  comv_p3=malloc(all_photons*sizeof(double));\n                    }\n                    #endif\n                    \n                    r0=malloc(all_photons*sizeof(double));  r1=malloc(all_photons*sizeof(double));  r2=malloc(all_photons*sizeof(double));\n                    \n                    #if STOKES_SWITCH == ON\n                    {\n                        s0=malloc(all_photons*sizeof(double));  s1=malloc(all_photons*sizeof(double));  s2=malloc(all_photons*sizeof(double));  s3=malloc(all_photons*sizeof(double));\n                    }\n                    #endif\n                    \n                    #if SAVE_TYPE == ON\n                    {\n                        ph_type=malloc(all_photons*sizeof(char));\n                    }\n                    #endif\n                    \n                    num_scatt=malloc(all_photons*sizeof(double));\n                    \n                    weight=malloc(all_photons*sizeof(double));\n                    \n                    \n                    //save data in correct order to p0, s0, r0, etc. in order of angle \n                    \n                    //MPI_Type_commit( &stype ); \n                    MPI_Allgatherv(p0_p, dims[0], MPI_DOUBLE, p0, each_subdir_number, displPtr, MPI_DOUBLE, frames_to_merge_comm);\n                    MPI_Allgatherv(p1_p, dims[0], MPI_DOUBLE, p1, each_subdir_number, displPtr, MPI_DOUBLE, frames_to_merge_comm);\n                    MPI_Allgatherv(p2_p, dims[0], MPI_DOUBLE, p2, each_subdir_number, displPtr, MPI_DOUBLE, frames_to_merge_comm);\n                    MPI_Allgatherv(p3_p, dims[0], MPI_DOUBLE, p3, each_subdir_number, displPtr, MPI_DOUBLE, frames_to_merge_comm);\n                    \n                    #if COMV_SWITCH == ON\n                    {\n                        MPI_Allgatherv(comv_p0_p, dims[0], MPI_DOUBLE, comv_p0, each_subdir_number, displPtr, MPI_DOUBLE, frames_to_merge_comm);\n                        MPI_Allgatherv(comv_p1_p, dims[0], MPI_DOUBLE, comv_p1, each_subdir_number, displPtr, MPI_DOUBLE, frames_to_merge_comm);\n                        MPI_Allgatherv(comv_p2_p, dims[0], MPI_DOUBLE, comv_p2, each_subdir_number, displPtr, MPI_DOUBLE, frames_to_merge_comm);\n                        MPI_Allgatherv(comv_p3_p, dims[0], MPI_DOUBLE, comv_p3, each_subdir_number, displPtr, MPI_DOUBLE, frames_to_merge_comm);\n                    }\n                    #endif\n                    \n                    MPI_Allgatherv(r0_p, dims[0], MPI_DOUBLE, r0, each_subdir_number, displPtr, MPI_DOUBLE, frames_to_merge_comm);\n                    MPI_Allgatherv(r1_p, dims[0], MPI_DOUBLE, r1, each_subdir_number, displPtr, MPI_DOUBLE, frames_to_merge_comm);\n                    MPI_Allgatherv(r2_p, dims[0], MPI_DOUBLE, r2, each_subdir_number, displPtr, MPI_DOUBLE, frames_to_merge_comm);\n                    \n                    #if STOKES_SWITCH == ON\n                    {\n                        MPI_Allgatherv(s0_p, dims[0], MPI_DOUBLE, s0, each_subdir_number, displPtr, MPI_DOUBLE, frames_to_merge_comm);\n                        MPI_Allgatherv(s1_p, dims[0], MPI_DOUBLE, s1, each_subdir_number, displPtr, MPI_DOUBLE, frames_to_merge_comm);\n                        MPI_Allgatherv(s2_p, dims[0], MPI_DOUBLE, s2, each_subdir_number, displPtr, MPI_DOUBLE, frames_to_merge_comm);\n                        MPI_Allgatherv(s3_p, dims[0], MPI_DOUBLE, s3, each_subdir_number, displPtr, MPI_DOUBLE, frames_to_merge_comm);\n                    }\n                    #endif\n                    \n                    #if SAVE_TYPE == ON\n                    {\n                        MPI_Allgatherv(ph_type_p, dims[0], MPI_CHAR, ph_type, each_subdir_number, displPtr, MPI_CHAR, frames_to_merge_comm);\n                    }\n                    #endif\n\n                    \n                    MPI_Allgatherv(num_scatt_p, dims[0], MPI_DOUBLE, num_scatt, each_subdir_number, displPtr, MPI_DOUBLE, frames_to_merge_comm);\n                    \n                    MPI_Allgatherv(weight_p, dims[0], MPI_DOUBLE, weight, each_subdir_number, displPtr, MPI_DOUBLE, frames_to_merge_comm);\n                    \n                    /*\n                    if (subdir_id==0)\n                    {\n                        for (j=0;j<all_photons;j++)\n                        {\n                            printf(\"Read Data: %e Gathered data: %e\\n\", *(s0+j), *(s0_p+j));\n                        }\n                    }\n                     */\n                    //exit(0);\n                    \n                    dims[0]=all_photons;\n                    //if ((k==0)  && (all_photons>0))\n                    #if SYNCHROTRON_SWITCH == ON\n                    if ((l==i) && (k==0) && (all_photons>0))\n                    #else\n                    if ((l==small_frm)  && (all_photons>0))\n                    #endif\n                    {\n                        //printf(\"IN THE IF STATEMENT\\n\");\n                        //set up new dataset\n                        //create the datasets with the appropriate number of elements\n                        \n                        plist_id_data = H5Pcreate (H5P_DATASET_CREATE);\n                        status = H5Pset_chunk (plist_id_data, 1, dims);\n                        dspace = H5Screate_simple (1, dims, maxdims);\n                        \n                        \n                        \n                        dset_p0=H5Dcreate2(file_id, \"P0\", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, plist_id_data, H5P_DEFAULT);\n                        dset_p1=H5Dcreate2(file_id, \"P1\", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, plist_id_data, H5P_DEFAULT);\n                        dset_p2=H5Dcreate2(file_id, \"P2\", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, plist_id_data, H5P_DEFAULT);\n                        dset_p3=H5Dcreate2(file_id, \"P3\", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, plist_id_data, H5P_DEFAULT);\n                        \n                        #if COMV_SWITCH == ON\n                        {\n                            dset_comv_p0=H5Dcreate2(file_id, \"COMV_P0\", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, plist_id_data, H5P_DEFAULT);\n                            dset_comv_p1=H5Dcreate2(file_id, \"COMV_P1\", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, plist_id_data, H5P_DEFAULT);\n                            dset_comv_p2=H5Dcreate2(file_id, \"COMV_P2\", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, plist_id_data, H5P_DEFAULT);\n                            dset_comv_p3=H5Dcreate2(file_id, \"COMV_P3\", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, plist_id_data, H5P_DEFAULT);\n                        }\n                        #endif\n                        \n                        dset_r0=H5Dcreate2(file_id, \"R0\", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, plist_id_data, H5P_DEFAULT);\n                        dset_r1=H5Dcreate2(file_id, \"R1\", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, plist_id_data, H5P_DEFAULT);\n                        dset_r2=H5Dcreate2(file_id, \"R2\", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, plist_id_data, H5P_DEFAULT);\n                        \n                        #if STOKES_SWITCH == ON\n                        {\n                            dset_s0=H5Dcreate2(file_id, \"S0\", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, plist_id_data, H5P_DEFAULT);\n                            dset_s1=H5Dcreate2(file_id, \"S1\", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, plist_id_data, H5P_DEFAULT);\n                            dset_s2=H5Dcreate2(file_id, \"S2\", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, plist_id_data, H5P_DEFAULT);\n                            dset_s3=H5Dcreate2(file_id, \"S3\", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, plist_id_data, H5P_DEFAULT);\n                        }\n                        #endif\n                        \n                        #if SAVE_TYPE == ON\n                        {\n                            dset_ph_type=H5Dcreate2(file_id, \"PT\", H5T_NATIVE_CHAR, dspace, H5P_DEFAULT, plist_id_data, H5P_DEFAULT);\n                        }\n                        #endif\n\n                        \n                        dset_num_scatt=H5Dcreate2(file_id, \"NS\", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, plist_id_data, H5P_DEFAULT);\n                        \n                        dset_weight=H5Dcreate2(file_id, \"PW\", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, plist_id_data, H5P_DEFAULT);\n\n                                                 \n                        H5Pclose(plist_id_data);\n                        H5Sclose(dspace);\n                        \n                        plist_id_data = H5Pcreate (H5P_DATASET_XFER);\n                        H5Pset_dxpl_mpio (plist_id_data, H5FD_MPIO_COLLECTIVE);\n                        \n                        //write data\n                        offset[0]=0;\n                        dspace = H5Dget_space(dset_p0);\n                        status = H5Sselect_hyperslab(dspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                        status = H5Dwrite (dset_p0, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, plist_id_data, p0);\n                        H5Sclose(dspace);\n                        \n                        \n                         dspace = H5Dget_space(dset_p1);\n                        status = H5Sselect_hyperslab(dspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                        status = H5Dwrite (dset_p1, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, plist_id_data, p1);\n                        H5Sclose(dspace);\n                        \n                        dspace = H5Dget_space(dset_p2);\n                        status = H5Sselect_hyperslab(dspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                        status = H5Dwrite (dset_p2, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, plist_id_data, p2);\n                        H5Sclose(dspace);\n                        \n                        dspace = H5Dget_space(dset_p3);\n                        status = H5Sselect_hyperslab(dspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                        status = H5Dwrite (dset_p3, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, plist_id_data, p3);\n                        H5Sclose(dspace);\n                        \n                        #if COMV_SWITCH == ON\n                        {\n                            dspace = H5Dget_space(dset_comv_p0);\n                            status = H5Sselect_hyperslab(dspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                            status = H5Dwrite (dset_comv_p0, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, plist_id_data, comv_p0);\n                            H5Sclose(dspace);\n                            \n                            \n                            dspace = H5Dget_space(dset_comv_p1);\n                            status = H5Sselect_hyperslab(dspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                            status = H5Dwrite (dset_comv_p1, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, plist_id_data, comv_p1);\n                            H5Sclose(dspace);\n                            \n                            dspace = H5Dget_space(dset_comv_p2);\n                            status = H5Sselect_hyperslab(dspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                            status = H5Dwrite (dset_comv_p2, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, plist_id_data, comv_p2);\n                            H5Sclose(dspace);\n                            \n                            dspace = H5Dget_space(dset_comv_p3);\n                            status = H5Sselect_hyperslab(dspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                            status = H5Dwrite (dset_comv_p3, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, plist_id_data, comv_p3);\n                            H5Sclose(dspace);\n                        }\n                        #endif\n                        \n                        dspace = H5Dget_space(dset_r0);\n                        status = H5Sselect_hyperslab(dspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                        status = H5Dwrite (dset_r0, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, plist_id_data, r0);\n                        H5Sclose(dspace);\n        \n                        dspace = H5Dget_space(dset_r1);\n                        status = H5Sselect_hyperslab(dspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                        status = H5Dwrite (dset_r1, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, plist_id_data, r1);\n                        H5Sclose(dspace);\n                        \n                        dspace = H5Dget_space(dset_r2);\n                        status = H5Sselect_hyperslab(dspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                        status = H5Dwrite (dset_r2, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, plist_id_data, r2);\n                        H5Sclose(dspace);\n                        \n                        #if STOKES_SWITCH == ON\n                        {\n                            dspace = H5Dget_space(dset_s0);\n                            status = H5Sselect_hyperslab(dspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                            status = H5Dwrite (dset_s0, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, plist_id_data, s0);\n                            H5Sclose(dspace);\n                            \n                            dspace = H5Dget_space(dset_s1);\n                            status = H5Sselect_hyperslab(dspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                            status = H5Dwrite (dset_s1, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, plist_id_data, s1);\n                            H5Sclose(dspace);\n                            \n                            dspace = H5Dget_space(dset_s2);\n                            status = H5Sselect_hyperslab(dspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                            status = H5Dwrite (dset_s2, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, plist_id_data, s2);\n                            H5Sclose(dspace);\n                            \n                            dspace = H5Dget_space(dset_s3);\n                            status = H5Sselect_hyperslab(dspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                            status = H5Dwrite (dset_s3, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL,  plist_id_data, s3);\n                            H5Sclose(dspace);\n                        }\n                        #endif\n                        \n                        #if SAVE_TYPE == ON\n                        {\n                            dspace = H5Dget_space(dset_ph_type);\n                            status = H5Sselect_hyperslab(dspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                            status = H5Dwrite (dset_ph_type, H5T_NATIVE_CHAR, H5S_ALL, H5S_ALL, plist_id_data, ph_type);\n                            H5Sclose(dspace);\n\n                        }\n                        #endif\n\n                        \n                        dspace = H5Dget_space(dset_num_scatt);\n                        status = H5Sselect_hyperslab(dspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                        status = H5Dwrite (dset_num_scatt, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, plist_id_data, num_scatt);\n                        H5Sclose(dspace);\n                        \n                        dspace = H5Dget_space(dset_weight);\n                        status = H5Sselect_hyperslab(dspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                        status = H5Dwrite (dset_weight, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, plist_id_data, weight);\n                        H5Sclose(dspace);\n\n                        \n                        status = H5Dclose (dset_p0); \n                        status = H5Dclose (dset_p1); status = H5Dclose (dset_p2); status = H5Dclose (dset_p3);\n                        \n                        #if COMV_SWITCH == ON\n                        {\n                            status = H5Dclose (dset_comv_p0); status = H5Dclose (dset_comv_p1); status = H5Dclose (dset_comv_p2); status = H5Dclose (dset_comv_p3);\n                        }\n                        #endif\n                        \n                        status = H5Dclose (dset_r0); status = H5Dclose (dset_r1); status = H5Dclose (dset_r2);\n                        \n                        #if STOKES_SWITCH == ON\n                        {\n                            status = H5Dclose (dset_s0); status = H5Dclose (dset_s1); status = H5Dclose (dset_s2); status = H5Dclose (dset_s3);\n                        }\n                        #endif\n                        \n                        #if SAVE_TYPE == ON\n                        {\n                            status = H5Dclose (dset_ph_type);\n                        }\n                        #endif\n\n                        \n                        status = H5Dclose (dset_num_scatt);\n                        \n                        status = H5Dclose (dset_weight);\n                        \n                        H5Pclose(plist_id_data);\n                        \n                    }\n                    #if SYNCHROTRON_SWITCH == ON\n                    else\n                    #else\n                    else if ((l>small_frm) && (all_photons>0))\n                    #endif\n                    {\n                        //printf(\"IN THE ELSE IF STATEMENT\\n\"); if ((k>0)  && (all_photons>0))\n                        plist_id_data = H5Pcreate (H5P_DATASET_XFER);\n                        H5Pset_dxpl_mpio (plist_id_data, H5FD_MPIO_COLLECTIVE);\n                        \n                        dset_p0 = H5Dopen (file_id, \"P0\", H5P_DEFAULT); //open dataset\n                        dspace = H5Dget_space (dset_p0);\n                        status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims_old\n                        \n                        size[0] = dims[0]+ dims_old[0];\n                        status = H5Dset_extent (dset_p0, size);\n                        \n                        fspace = H5Dget_space (dset_p0);\n                        offset[0] = dims_old[0];\n                        \n                        status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                        mspace = H5Screate_simple (1, dims, NULL);\n                        status = H5Dwrite (dset_p0, H5T_NATIVE_DOUBLE, mspace, fspace, plist_id_data, p0);\n                        status = H5Sclose (dspace);\n                        status = H5Sclose (mspace);\n                        status = H5Sclose (fspace);\n                        status = H5Dclose (dset_p0);\n                        \n                        dset_p1 = H5Dopen (file_id, \"P1\", H5P_DEFAULT); //open dataset\n                        dspace = H5Dget_space (dset_p1);\n                        status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims_old\n                        size[0] = dims[0]+ dims_old[0];\n                        status = H5Dset_extent (dset_p1, size);\n                        fspace = H5Dget_space (dset_p1);\n                        offset[0] = dims_old[0];\n                        status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                        mspace = H5Screate_simple (1, dims, NULL);\n                        status = H5Dwrite (dset_p1, H5T_NATIVE_DOUBLE, mspace, fspace, plist_id_data, p1);\n                        status = H5Sclose (dspace);\n                        status = H5Sclose (mspace);\n                        status = H5Sclose (fspace);\n                        status = H5Dclose (dset_p1);\n                        \n                        dset_p2 = H5Dopen (file_id, \"P2\", H5P_DEFAULT); //open dataset\n                        dspace = H5Dget_space (dset_p2);\n                        status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims_old\n                        size[0] = dims[0]+ dims_old[0];\n                        status = H5Dset_extent (dset_p2, size);\n                        fspace = H5Dget_space (dset_p2);\n                        offset[0] = dims_old[0];\n                        status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                        mspace = H5Screate_simple (1, dims, NULL);\n                        status = H5Dwrite (dset_p2, H5T_NATIVE_DOUBLE, mspace, fspace, plist_id_data, p2);\n                        status = H5Sclose (dspace);\n                        status = H5Sclose (mspace);\n                        status = H5Sclose (fspace);\n                        status = H5Dclose (dset_p2);\n                        \n                        dset_p3 = H5Dopen (file_id, \"P3\", H5P_DEFAULT); //open dataset\n                        dspace = H5Dget_space (dset_p3);\n                        status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims_old\n                        size[0] = dims[0]+ dims_old[0];\n                        status = H5Dset_extent (dset_p3, size);\n                        fspace = H5Dget_space (dset_p3);\n                        offset[0] = dims_old[0];\n                        status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                        mspace = H5Screate_simple (1, dims, NULL);\n                        status = H5Dwrite (dset_p3, H5T_NATIVE_DOUBLE, mspace, fspace, plist_id_data, p3);\n                        status = H5Sclose (dspace);\n                        status = H5Sclose (mspace);\n                        status = H5Sclose (fspace);\n                        status = H5Dclose (dset_p3);\n                        \n                        #if COMV_SWITCH == ON\n                        {\n                            dset_comv_p0 = H5Dopen (file_id, \"COMV_P0\", H5P_DEFAULT); //open dataset\n                            dspace = H5Dget_space (dset_comv_p0);\n                            status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims_old\n                            size[0] = dims[0]+ dims_old[0];\n                            status = H5Dset_extent (dset_comv_p0, size);\n                            fspace = H5Dget_space (dset_comv_p0);\n                            offset[0] = dims_old[0];\n                            status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                            mspace = H5Screate_simple (1, dims, NULL);\n                            status = H5Dwrite (dset_comv_p0, H5T_NATIVE_DOUBLE, mspace, fspace, plist_id_data, comv_p0);\n                            status = H5Sclose (dspace);\n                            status = H5Sclose (mspace);\n                            status = H5Sclose (fspace);\n                            status = H5Dclose (dset_comv_p0);\n                            \n                            dset_comv_p1 = H5Dopen (file_id, \"COMV_P1\", H5P_DEFAULT); //open dataset\n                            dspace = H5Dget_space (dset_comv_p1);\n                            status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims_old\n                            size[0] = dims[0]+ dims_old[0];\n                            status = H5Dset_extent (dset_comv_p1, size);\n                            fspace = H5Dget_space (dset_comv_p1);\n                            offset[0] = dims_old[0];\n                            status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                            mspace = H5Screate_simple (1, dims, NULL);\n                            status = H5Dwrite (dset_comv_p1, H5T_NATIVE_DOUBLE, mspace, fspace, plist_id_data, comv_p1);\n                            status = H5Sclose (dspace);\n                            status = H5Sclose (mspace);\n                            status = H5Sclose (fspace);\n                            status = H5Dclose (dset_comv_p1);\n                            \n                            dset_comv_p2 = H5Dopen (file_id, \"COMV_P2\", H5P_DEFAULT); //open dataset\n                            dspace = H5Dget_space (dset_comv_p2);\n                            status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims_old\n                            size[0] = dims[0]+ dims_old[0];\n                            status = H5Dset_extent (dset_comv_p2, size);\n                            fspace = H5Dget_space (dset_comv_p2);\n                            offset[0] = dims_old[0];\n                            status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                            mspace = H5Screate_simple (1, dims, NULL);\n                            status = H5Dwrite (dset_comv_p2, H5T_NATIVE_DOUBLE, mspace, fspace, plist_id_data, comv_p2);\n                            status = H5Sclose (dspace);\n                            status = H5Sclose (mspace);\n                            status = H5Sclose (fspace);\n                            status = H5Dclose (dset_comv_p2);\n                            \n                            dset_comv_p3 = H5Dopen (file_id, \"COMV_P3\", H5P_DEFAULT); //open dataset\n                            dspace = H5Dget_space (dset_comv_p3);\n                            status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims_old\n                            size[0] = dims[0]+ dims_old[0];\n                            status = H5Dset_extent (dset_comv_p3, size);\n                            fspace = H5Dget_space (dset_comv_p3);\n                            offset[0] = dims_old[0];\n                            status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                            mspace = H5Screate_simple (1, dims, NULL);\n                            status = H5Dwrite (dset_comv_p3, H5T_NATIVE_DOUBLE, mspace, fspace, plist_id_data, comv_p3);\n                            status = H5Sclose (dspace);\n                            status = H5Sclose (mspace);\n                            status = H5Sclose (fspace);\n                            status = H5Dclose (dset_comv_p3);\n                        }\n                        #endif\n                        \n                        dset_r0 = H5Dopen (file_id, \"R0\", H5P_DEFAULT); //open dataset\n                        dspace = H5Dget_space (dset_r0);\n                        status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims_old\n                        size[0] = dims[0]+ dims_old[0];\n                        status = H5Dset_extent (dset_r0, size);\n                        fspace = H5Dget_space (dset_r0);\n                        offset[0] = dims_old[0];\n                        status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                        mspace = H5Screate_simple (1, dims, NULL);\n                        status = H5Dwrite (dset_r0, H5T_NATIVE_DOUBLE, mspace, fspace, plist_id_data, r0);\n                        status = H5Sclose (dspace);\n                        status = H5Sclose (mspace);\n                        status = H5Sclose (fspace);\n                        status = H5Dclose (dset_r0);\n                        \n                        dset_r1 = H5Dopen (file_id, \"R1\", H5P_DEFAULT); //open dataset\n                        dspace = H5Dget_space (dset_r1);\n                        status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims_old\n                        size[0] = dims[0]+ dims_old[0];\n                        status = H5Dset_extent (dset_r1, size);\n                        fspace = H5Dget_space (dset_r1);\n                        offset[0] = dims_old[0];\n                        status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                        mspace = H5Screate_simple (1, dims, NULL);\n                        status = H5Dwrite (dset_r1, H5T_NATIVE_DOUBLE, mspace, fspace, plist_id_data, r1);\n                        status = H5Sclose (dspace);\n                        status = H5Sclose (mspace);\n                        status = H5Sclose (fspace);\n                        status = H5Dclose (dset_r1);\n                        \n                        dset_r2 = H5Dopen (file_id, \"R2\", H5P_DEFAULT); //open dataset\n                        dspace = H5Dget_space (dset_r2);\n                        status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims_old\n                        size[0] = dims[0]+ dims_old[0];\n                        status = H5Dset_extent (dset_r2, size);\n                        fspace = H5Dget_space (dset_r2);\n                        offset[0] = dims_old[0];\n                        status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                        mspace = H5Screate_simple (1, dims, NULL);\n                        status = H5Dwrite (dset_r2, H5T_NATIVE_DOUBLE, mspace, fspace, plist_id_data, r2);\n                        status = H5Sclose (dspace);\n                        status = H5Sclose (mspace);\n                        status = H5Sclose (fspace);\n                        status = H5Dclose (dset_r2);\n                        \n                        #if STOKES_SWITCH == ON\n                        {\n                            dset_s0 = H5Dopen (file_id, \"S0\", H5P_DEFAULT); //open dataset\n                            dspace = H5Dget_space (dset_s0);\n                            status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims_old\n                            size[0] = dims[0]+ dims_old[0];\n                            status = H5Dset_extent (dset_s0, size);\n                            fspace = H5Dget_space (dset_s0);\n                            offset[0] = dims_old[0];\n                            status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                            mspace = H5Screate_simple (1, dims, NULL);\n                            status = H5Dwrite (dset_s0, H5T_NATIVE_DOUBLE, mspace, fspace, plist_id_data, s0);\n                            status = H5Sclose (dspace);\n                            status = H5Sclose (mspace);\n                            status = H5Sclose (fspace);\n                            status = H5Dclose (dset_s0);\n                            \n                            dset_s1 = H5Dopen (file_id, \"S1\", H5P_DEFAULT); //open dataset\n                            dspace = H5Dget_space (dset_s1);\n                            status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims_old\n                            size[0] = dims[0]+ dims_old[0];\n                            status = H5Dset_extent (dset_s1, size);\n                            fspace = H5Dget_space (dset_s1);\n                            offset[0] = dims_old[0];\n                            status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                            mspace = H5Screate_simple (1, dims, NULL);\n                            status = H5Dwrite (dset_s1, H5T_NATIVE_DOUBLE, mspace, fspace, plist_id_data, s1);\n                            status = H5Sclose (dspace);\n                            status = H5Sclose (mspace);\n                            status = H5Sclose (fspace);\n                            status = H5Dclose (dset_s1);\n                            \n                            dset_s2 = H5Dopen (file_id, \"S2\", H5P_DEFAULT); //open dataset\n                            dspace = H5Dget_space (dset_s2);\n                            status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims_old\n                            size[0] = dims[0]+ dims_old[0];\n                            status = H5Dset_extent (dset_s2, size);\n                            fspace = H5Dget_space (dset_s2);\n                            offset[0] = dims_old[0];\n                            status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                            mspace = H5Screate_simple (1, dims, NULL);\n                            status = H5Dwrite (dset_s2, H5T_NATIVE_DOUBLE, mspace, fspace, plist_id_data, s2);\n                            status = H5Sclose (dspace);\n                            status = H5Sclose (mspace);\n                            status = H5Sclose (fspace);\n                            status = H5Dclose (dset_s2);\n                            \n                            dset_s3 = H5Dopen (file_id, \"S3\", H5P_DEFAULT); //open dataset\n                            dspace = H5Dget_space (dset_s3);\n                            status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims_old\n                            size[0] = dims[0]+ dims_old[0];\n                            status = H5Dset_extent (dset_s3, size);\n                            fspace = H5Dget_space (dset_s3);\n                            offset[0] = dims_old[0];\n                            status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                            mspace = H5Screate_simple (1, dims, NULL);\n                            status = H5Dwrite (dset_s3, H5T_NATIVE_DOUBLE, mspace, fspace, plist_id_data, s3);\n                            status = H5Sclose (dspace);\n                            status = H5Sclose (mspace);\n                            status = H5Sclose (fspace);\n                            status = H5Dclose (dset_s3);\n                        }\n                        #endif\n                        \n                        #if SAVE_TYPE == ON\n                        {\n                            dset_ph_type = H5Dopen (file_id, \"PT\", H5P_DEFAULT); //open dataset\n                            dspace = H5Dget_space (dset_ph_type);\n                            status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims_old\n                            size[0] = dims[0]+ dims_old[0];\n                            status = H5Dset_extent (dset_ph_type, size);\n                            fspace = H5Dget_space (dset_ph_type);\n                            offset[0] = dims_old[0];\n                            status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                            mspace = H5Screate_simple (1, dims, NULL);\n                            status = H5Dwrite (dset_ph_type, H5T_NATIVE_CHAR, mspace, fspace, plist_id_data, ph_type);\n                            status = H5Sclose (dspace);\n                            status = H5Sclose (mspace);\n                            status = H5Sclose (fspace);\n                            status = H5Dclose (dset_ph_type);\n\n                        }\n                        #endif\n\n                        \n                        dset_num_scatt = H5Dopen (file_id, \"NS\", H5P_DEFAULT); //open dataset\n                        dspace = H5Dget_space (dset_num_scatt);\n                        status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims_old\n                        size[0] = dims[0]+ dims_old[0];\n                        status = H5Dset_extent (dset_num_scatt, size);\n                        fspace = H5Dget_space (dset_num_scatt);\n                        offset[0] = dims_old[0];\n                        status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                        mspace = H5Screate_simple (1, dims, NULL);\n                        status = H5Dwrite (dset_num_scatt, H5T_NATIVE_DOUBLE, mspace, fspace, plist_id_data, num_scatt);\n                        status = H5Sclose (dspace);\n                        status = H5Sclose (mspace);\n                        status = H5Sclose (fspace);\n                        status = H5Dclose (dset_num_scatt);\n                        \n                        //printf(\"Before weight write\\n\");\n                        dset_weight = H5Dopen (file_id, \"PW\", H5P_DEFAULT); //open dataset\n                        dspace = H5Dget_space (dset_weight);\n                        status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims_old\n                        size[0] = dims[0]+ dims_old[0];\n                        status = H5Dset_extent (dset_weight, size);\n                        fspace = H5Dget_space (dset_weight);\n                        offset[0] = dims_old[0];\n                        status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                        mspace = H5Screate_simple (1, dims, NULL);\n                        status = H5Dwrite (dset_weight, H5T_NATIVE_DOUBLE, mspace, fspace, plist_id_data, weight);\n                        status = H5Sclose (dspace);\n                        status = H5Sclose (mspace);\n                        status = H5Sclose (fspace);\n                        status = H5Dclose (dset_weight);\n                        //printf(\"After weight write\\n\");\n                        \n                        \n                        H5Pclose(plist_id_data);\n                        \n                    }\n                    \n                    \n                    \n                    if (file>=0)\n                    {\n                        status = H5Fclose(file);\n                    }\n                    \n                    free(p0_p);free(p1_p); free(p2_p);free(p3_p);\n                    \n                    #if COMV_SWITCH == ON\n                    {\n                        free(comv_p0_p);free(comv_p1_p); free(comv_p2_p);free(comv_p3_p);\n                    }\n                    #endif\n                    \n                    free(r0_p);free(r1_p); free(r2_p);\n                    \n                    #if STOKES_SWITCH == ON\n                    {\n                        free(s0_p);free(s1_p); free(s2_p);free(s3_p);\n                    }\n                    #endif\n                    \n                    free(num_scatt_p);\n                    \n                    free(weight_p);\n                    \n                    #if SAVE_TYPE == ON\n                    {\n                        free(ph_type_p);\n                    }\n                    #endif\n\n                    \n                    free(p0);free(p1); free(p2);free(p3);\n                    \n                    #if COMV_SWITCH == ON\n                    {\n                        free(comv_p0);free(comv_p1); free(comv_p2);free(comv_p3);\n                    }\n                    #endif\n                    \n                    free(r0);free(r1); free(r2);\n                    \n                    #if STOKES_SWITCH == ON\n                    {\n                        free(s0);free(s1); free(s2);free(s3);\n                    }\n                    #endif\n                    \n                    free(num_scatt);\n                    \n                    free(weight);\n                    \n                    #if SAVE_TYPE == ON\n                    {\n                        free(ph_type);\n                    }\n                    #endif\n                    //exit(0);\n                }\n            \n            \n            \n            }\n            H5Fclose(file_id);\n        }\n        \n        \n        \n        \n        H5Pclose(plist_id_file);\n        \n    }\n    \n    /*\n    if (index==0)\n    {\n        plist_id_file = H5Pcreate(H5P_FILE_ACCESS);\n        H5Pset_fapl_mpio(plist_id_file, frames_to_merge_comm, info);\n        //merge the weights in the same order\n        snprintf(merged_filename,sizeof(merged_filename),\"%smcdata_PW.h5\",dir );\n        \n        file_id = H5Fcreate(merged_filename, H5F_ACC_TRUNC, H5P_DEFAULT, plist_id_file);\n        \n         for (i= small_frm; i<large_frm+1;i++)\n         {\n        //last_frm\n            for (k=0;k<max_num_procs_per_dir;k++)\n            {\n                dims[0]=0;\n                j=0;\n                \n                snprintf(filename_k,sizeof(filename_k),\"%s%s%d%s\",dirs[subdir_id],\"mc_proc_\", k, \".h5\" );\n                //printf(\"Dir: %s\\n\",filename_k );\n            \n                //open the file and see if t exists\n                status = H5Eset_auto(NULL, NULL, NULL); //turn of error printing if the file doesnt exist, if the process number doesnt exist\n                file=H5Fopen(filename_k, H5F_ACC_RDONLY, H5P_DEFAULT);\n                status = H5Eset_auto(H5E_DEFAULT, H5Eprint2, stderr);\n                \n                if (file>=0)\n                {\n                    //if the file exists, see if the frame exists\n                    snprintf(group,sizeof(group),\"%d/PW\",i );\n                    status = H5Eset_auto(NULL, NULL, NULL);\n                    status_group = H5Gget_objinfo (file, group, 0, NULL);\n                    status = H5Eset_auto(H5E_DEFAULT, H5Eprint2, stderr);\n                }\n                \n                //printf(\"Proc %d has status_group %d\\n\", subdir_id, status_group);\n                \n                if ((status_group == 0) && (file>=0))\n                {\n            \n                    //read dataset and then \n                     snprintf(group,sizeof(group),\"%d\",i );\n                    group_id = H5Gopen2(file, group, H5P_DEFAULT);\n                    dset_weight = H5Dopen (group_id, \"PW\", H5P_DEFAULT); //open dataset\n                    \n                    //get the number of points\n                    dspace = H5Dget_space (dset_weight);\n                    status=H5Sget_simple_extent_dims(dspace, dims, NULL); //save dimesnions in dims\n                    j=dims[0];//calculate the total number of photons to save to new hdf5 file\n                    \n                    weight_p=malloc(j*sizeof(double));\n                    \n                    status = H5Dread(dset_weight, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, (weight_p));\n                    \n                    status = H5Sclose (dspace);\n                    status = H5Dclose (dset_weight);\n                    status = H5Gclose(group_id);\n                }\n                else\n                {\n                    //theres nothing to read\n                    j=1;\n                    weight_p=malloc(j*sizeof(double));\n                }\n                \n                //find total number of photons\n                MPI_Allreduce(&dims[0], &all_photons, 1, MPI_INT, MPI_SUM,  frames_to_merge_comm);\n                    \n                //printf(\"ID %d j: %d\\n\", subdir_id, dims[0]);\n                    \n                //get the number for each subdir for later use\n                MPI_Allgather(&dims[0], 1, MPI_INT, each_subdir_number, 1, MPI_INT,   frames_to_merge_comm);\n                //for (j=0;j<num_angle_dirs;j++)\n                //{\n                 //       printf(\"ID %d eachsubdir_num %d \\n\",  subdir_id, *(each_subdir_number+j));\n                //}\n                    \n        \n                //set up the displacement of data\n                for (j=1;j<num_angle_dirs;j++)\n                {\n                    *(displPtr+j)=(*(displPtr+j-1))+(*(each_subdir_number+j-1));\n                       // printf(\"Displ %d eachsubdir_num %d \\n\",  *(displPtr+j), *(each_subdir_number+j-1));\n                }\n                \n                weight=malloc(all_photons*sizeof(double)); \n                    \n                //MPI_Type_commit( &stype ); \n                MPI_Allgatherv(weight_p, dims[0], MPI_DOUBLE, weight, each_subdir_number, displPtr, MPI_DOUBLE, frames_to_merge_comm);\n                \n                dims[0]=all_photons;\n                \n                if ((i== small_frm) && (all_photons>0))\n                {\n                    //create new datatset\n                    plist_id_data = H5Pcreate (H5P_DATASET_CREATE);\n                    status = H5Pset_chunk (plist_id_data, 1, dims);\n                    dspace = H5Screate_simple (1, dims, maxdims);\n                        \n                    dset_weight=H5Dcreate(file_id, \"PW\", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, plist_id_data, H5P_DEFAULT);\n                    H5Pclose(plist_id_data);\n                    H5Sclose(dspace);\n                        \n                    plist_id_data = H5Pcreate (H5P_DATASET_XFER);\n                    H5Pset_dxpl_mpio (plist_id_data, H5FD_MPIO_COLLECTIVE);\n                        \n                    //write data\n                    offset[0]=0;\n                    dspace = H5Dget_space(dset_weight);\n                    status = H5Sselect_hyperslab(dspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                    status = H5Dwrite (dset_weight, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, plist_id_data, weight);\n                    H5Sclose(dspace);\n                    status = H5Dclose (dset_weight);\n                        \n                    H5Pclose(plist_id_data);\n                    \n                }\n                else if ((i != small_frm) && (all_photons>0))\n                {\n                    //extend the datatset\n                    plist_id_data = H5Pcreate (H5P_DATASET_XFER);\n                    H5Pset_dxpl_mpio (plist_id_data, H5FD_MPIO_COLLECTIVE);\n                        \n                    dset_weight = H5Dopen (file_id, \"PW\", H5P_DEFAULT); //open dataset\n                    dspace = H5Dget_space (dset_weight);\n                    status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims_old\n                        \n                    size[0] = dims[0]+ dims_old[0];\n                    status = H5Dset_extent (dset_weight, size);\n                        \n                    fspace = H5Dget_space (dset_weight);\n                    offset[0] = dims_old[0];\n                        \n                    status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL);\n                    mspace = H5Screate_simple (1, dims, NULL);\n                    status = H5Dwrite (dset_weight, H5T_NATIVE_DOUBLE, mspace, fspace, plist_id_data, weight);\n                    status = H5Sclose (dspace);\n                    status = H5Sclose (mspace);\n                    status = H5Sclose (fspace);\n                    status = H5Dclose (dset_weight);\n                }\n                \n                //exit(0);\n                 if (file>=0)\n                {\n                    status = H5Fclose(file);\n                }\n            \n            }\n            \n         }\n        \n        H5Pclose(plist_id_file);\n        free(weight_p); free(weight);\n        H5Fclose(file_id);\n    }\n    */\n    \n    MPI_Finalize();\n    \n    free(num_procs_per_dir);\n    free(each_subdir_number);\n    free(displPtr);\n    free(frm_array);\n}\n\n\n", "meta": {"hexsha": "274b0a5c880bae855ab279fa358ce1a9ead0bb98", "size": 86724, "ext": "c", "lang": "C", "max_stars_repo_path": "Src/merge.c", "max_stars_repo_name": "outflows/MCRaT", "max_stars_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Src/merge.c", "max_issues_repo_name": "outflows/MCRaT", "max_issues_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Src/merge.c", "max_forks_repo_name": "outflows/MCRaT", "max_forks_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-19T09:13:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T09:13:42.000Z", "avg_line_length": 52.8482632541, "max_line_length": 245, "alphanum_fraction": 0.4698353397, "num_tokens": 20588, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29746994260479465, "lm_q2_score": 0.03067579993834215, "lm_q1q2_score": 0.009125128447014803}}
{"text": "/* Internal header file for cminpack, by Frederic Devernay. */\n#ifndef __CMINPACKP_H__\n#define __CMINPACKP_H__\n\n#ifndef __CMINPACK_H__\n#error \"cminpackP.h in an internal cminpack header, and must be included after all other headers (including cminpack.h)\"\n#endif\n\n#if (defined (USE_CBLAS) || defined (USE_LAPACK)) && !defined (__cminpack_double__)\n#error \"cminpack can use cblas and lapack only in double precision mode\"\n#endif\n\n#ifdef USE_CBLAS\n#ifdef __APPLE__\n#include <Accelerate/Accelerate.h>\n#else\n#include <cblas.h>\n#endif\n#define __cminpack_enorm__(n,x) cblas_dnrm2(n,x,1)\n#else\n#define __cminpack_enorm__(n,x) __cminpack_func__(enorm)(n,x)\n#endif\n\n#ifdef USE_LAPACK\n#ifdef __APPLE__\n#include <Accelerate/Accelerate.h>\n#else\n#if defined(__LP64__) /* In LP64 match sizes with the 32 bit ABI */\ntypedef int \t\t__CLPK_integer;\ntypedef int \t\t__CLPK_logical;\ntypedef float \t\t__CLPK_real;\ntypedef double \t\t__CLPK_doublereal;\ntypedef __CLPK_logical \t(*__CLPK_L_fp)();\ntypedef int \t\t__CLPK_ftnlen;\n#else\ntypedef long int \t__CLPK_integer;\ntypedef long int \t__CLPK_logical;\ntypedef float \t\t__CLPK_real;\ntypedef double \t\t__CLPK_doublereal;\ntypedef __CLPK_logical \t(*__CLPK_L_fp)();\ntypedef long int \t__CLPK_ftnlen;\n#endif\n//extern void dlartg_(double *f, double *g, double *cs, double *sn, double *r__);\nint dlartg_(__CLPK_doublereal *f, __CLPK_doublereal *g, __CLPK_doublereal *cs,\n            __CLPK_doublereal *sn, __CLPK_doublereal *r__)\n//extern void dgeqp3_(int *m, int *n, double *a, int *lda, int *jpvt, double *tau, double *work, int *lwork, int *info);\nint dgeqp3_(__CLPK_integer *m, __CLPK_integer *n, __CLPK_doublereal *a, __CLPK_integer *\n            lda, __CLPK_integer *jpvt, __CLPK_doublereal *tau, __CLPK_doublereal *work, __CLPK_integer *lwork,\n            __CLPK_integer *info)\n//extern void dgeqrf_(int *m, int *n, double *a, int *lda, double *tau, double *work, int *lwork, int *info);\nint dgeqrf_(__CLPK_integer *m, __CLPK_integer *n, __CLPK_doublereal *a, __CLPK_integer *\n            lda, __CLPK_doublereal *tau, __CLPK_doublereal *work, __CLPK_integer *lwork, __CLPK_integer *info)\n#endif\n#endif\n\n#define real_mp __cminpack_real__\n#define minpack_min(a,b) ((a) <= (b) ? (a) : (b))\n#define minpack_max(a,b) ((a) >= (b) ? (a) : (b))\n#define TRUE_ (1)\n#define FALSE_ (0)\n\n#endif /* !__CMINPACKP_H__ */\n", "meta": {"hexsha": "d2aa28f962ac69056f4d31262b95a75d6a0895a0", "size": 2320, "ext": "h", "lang": "C", "max_stars_repo_path": "wisdem/pymap/src/cminpack/cminpackP.h", "max_stars_repo_name": "ptrbortolotti/WISDEM", "max_stars_repo_head_hexsha": "2b7e44716d022e2f62140073dd078c5deeb8bf0a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 384.0, "max_stars_repo_stars_event_min_datetime": "2017-08-13T18:41:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T22:33:55.000Z", "max_issues_repo_path": "wisdem/pymap/src/cminpack/cminpackP.h", "max_issues_repo_name": "ptrbortolotti/WISDEM", "max_issues_repo_head_hexsha": "2b7e44716d022e2f62140073dd078c5deeb8bf0a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 802.0, "max_issues_repo_issues_event_min_datetime": "2017-04-17T15:19:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:32:37.000Z", "max_forks_repo_path": "wisdem/pymap/src/cminpack/cminpackP.h", "max_forks_repo_name": "ptrbortolotti/WISDEM", "max_forks_repo_head_hexsha": "2b7e44716d022e2f62140073dd078c5deeb8bf0a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 291.0, "max_forks_repo_forks_event_min_datetime": "2017-04-27T21:52:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T17:51:36.000Z", "avg_line_length": 36.8253968254, "max_line_length": 120, "alphanum_fraction": 0.7409482759, "num_tokens": 777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416729909662417, "lm_q2_score": 0.02064593058857012, "lm_q1q2_score": 0.009118749914335183}}
{"text": "#pragma once\r\n// support functions for TString & c-string handling...\r\n// v1.17\r\n\r\n#include <tchar.h>\r\n#include <cstdlib>\r\n#include <codecvt>\r\n\r\n#ifdef max\r\n#undef max\r\n#endif\r\n#ifdef min\r\n#undef min\r\n#endif\r\n\r\n#include <concepts>\r\n\r\n#include <gsl/gsl>\r\n\r\n// determine whether _Ty is a Number type (excluding char / wchar)\r\ntemplate<class _Ty>\r\nstruct is_Numeric\r\n\t: std::integral_constant<bool,\r\n\t(std::is_arithmetic_v<_Ty> || std::is_same_v<_Ty, std::byte> || std::is_enum_v<_Ty>)\r\n\t&& !std::is_same_v<_Ty, wchar_t>\r\n\t&& !std::is_same_v<_Ty, char>\r\n\t&& !std::is_pointer_v<_Ty>\r\n\t>\r\n{\r\n};\r\n\r\n// determine whether T is a Number type (excluding char / wchar), same as is_Numeric<T>::value\r\ntemplate <typename T>\r\nconstexpr bool is_Numeric_v = is_Numeric<T>::value;\r\n\r\nnamespace std\r\n{\r\n\tinline string to_string(const wstring& wstr)\r\n\t{\r\n\t\t//string str;\r\n\t\t//str.assign(wstr.begin(), wstr.end());\r\n\t\t//return str;\r\n\r\n\t\tusing convert_type = std::codecvt_utf8<wchar_t>;\r\n\t\tstd::wstring_convert<convert_type, wchar_t> converter;\r\n\r\n\t\t//use converter (.to_bytes: wstr->str, .from_bytes: str->wstr)\r\n\t\treturn converter.to_bytes(wstr);\r\n\t}\r\n\r\n\tinline wstring to_wstring(const string& str)\r\n\t{\r\n\t\twstring wstr;\r\n\t\twstr.assign(str.begin(), str.end());\r\n\t\treturn wstr;\r\n\t}\r\n\r\n\tinline string to_string(const std::byte& num)\r\n\t{\r\n\t\treturn to_string(gsl::narrow_cast<uint8_t>(num));\r\n\t}\r\n\r\n\tinline wstring to_wstring(const std::byte& num)\r\n\t{\r\n\t\treturn to_wstring(gsl::narrow_cast<uint8_t>(num));\r\n\t}\r\n}\r\n\r\nstruct ci_char_traits\r\n\t: public std::char_traits<char>\r\n{\r\n\tstatic char to_upper(char ch) noexcept\r\n\t{\r\n\t\tif (ch >= 'a' && ch <= 'z') return _toupper(ch);\r\n\t\treturn ch;\r\n\t}\r\n\tstatic bool eq(char c1, char c2) noexcept\r\n\t{\r\n\t\treturn to_upper(c1) == to_upper(c2);\r\n\t}\r\n\tstatic bool lt(char c1, char c2) noexcept\r\n\t{\r\n\t\treturn to_upper(c1) < to_upper(c2);\r\n\t}\r\n\tstatic int compare(const char* s1, const char* s2, size_t n) noexcept\r\n\t{\r\n\t\twhile (n-- != 0)\r\n\t\t{\r\n\t\t\tif (to_upper(*s1) < to_upper(*s2)) return -1;\r\n\t\t\tif (to_upper(*s1) > to_upper(*s2)) return 1;\r\n\t\t\t++s1; ++s2;\r\n\t\t}\r\n\t\treturn 0;\r\n\t}\r\n\tstatic const char* find(const char* s, int n, char a) noexcept\r\n\t{\r\n\t\tif (s)\r\n\t\t\tfor (auto const ua(to_upper(a)); (n != 0); ++s, --n)\r\n\t\t\t{\r\n\t\t\t\tif (to_upper(*s) == ua)\r\n\t\t\t\t\treturn s;\r\n\t\t\t}\r\n\t\treturn nullptr;\r\n\t}\r\n};\r\nstruct ci_wchar_traits\r\n\t: public std::char_traits<wchar_t>\r\n{\r\n\tstatic wchar_t to_upper(wchar_t ch) noexcept\r\n\t{\r\n\t\tif (ch >= L'a' && ch <= L'z') return _toupper(ch);\r\n\t\treturn ch;\r\n\t}\r\n\tstatic bool eq(wchar_t c1, wchar_t c2) noexcept\r\n\t{\r\n\t\treturn to_upper(c1) == to_upper(c2);\r\n\t}\r\n\tstatic bool lt(wchar_t c1, wchar_t c2) noexcept\r\n\t{\r\n\t\treturn to_upper(c1) < to_upper(c2);\r\n\t}\r\n\tstatic int compare(const wchar_t* s1, const wchar_t* s2, size_t n) noexcept\r\n\t{\r\n\t\twhile (n-- != 0)\r\n\t\t{\r\n\t\t\tif (to_upper(*s1) < to_upper(*s2)) return -1;\r\n\t\t\tif (to_upper(*s1) > to_upper(*s2)) return 1;\r\n\t\t\t++s1; ++s2;\r\n\t\t}\r\n\t\treturn 0;\r\n\t}\r\n\tstatic const wchar_t* find(const wchar_t* s, int n, wchar_t a) noexcept\r\n\t{\r\n\t\tif (s)\r\n\t\t\tfor (auto const ua(to_upper(a)); (n-- != 0); ++s)\r\n\t\t\t{\r\n\t\t\t\tif (to_upper(*s) == ua)\r\n\t\t\t\t\treturn s;\r\n\t\t\t}\r\n\t\treturn nullptr;\r\n\t}\r\n};\r\nusing ci_stringview = std::basic_string_view<char, ci_char_traits>;\r\nusing ci_wstringview = std::basic_string_view<wchar_t, ci_wchar_traits>;\r\n\r\nnamespace details {\r\n\ttemplate<class _Ty>\r\n\tstruct is_pod\r\n\t\t: std::integral_constant<bool, std::is_standard_layout_v<_Ty>&& std::is_trivial_v<_Ty> >\r\n\t{\r\n\t};\r\n\r\n\ttemplate <typename T>\r\n\tconstexpr bool is_pod_v = is_pod<T>::value;\r\n\r\n\ttemplate<typename T>\r\n\tconcept IsPODText = std::is_same_v<std::remove_all_extents_t<std::remove_cv_t<std::remove_pointer_t<T>>>, char> || std::is_same_v<std::remove_all_extents_t<std::remove_cv_t<std::remove_pointer_t<T>>>, wchar_t>;\r\n\r\n\ttemplate <class T>\r\n\tconcept IsNumeric = is_Numeric_v<std::remove_cvref_t<T>>;\r\n\r\n\ttemplate <class T>\r\n\tconcept HasDataFunction = requires(T t)\r\n\t{\r\n\t\tt.data();\r\n\t};\r\n\r\n\ttemplate <class T>\r\n\tconcept HasChrFunction = requires(T t)\r\n\t{\r\n\t\tt.to_chr();\r\n\t};\r\n\r\n\ttemplate <class T>\r\n\tconcept HasSizeFunction = requires(T t)\r\n\t{\r\n\t\tstatic_cast<std::size_t>(t.size());\r\n\t};\r\n\r\n\ttemplate <class T>\r\n\tconcept HasDataSizeNoChr = HasDataFunction<T> && HasSizeFunction<T> && !HasChrFunction<T>;\r\n\r\n\ttemplate <class T>\r\n\tconcept HasDataSizeChr = HasDataFunction<T> && HasSizeFunction<T> && HasChrFunction<T>;\r\n\r\n\tconstexpr WCHAR make_upper(const WCHAR c) noexcept\r\n\t{\r\n\t\tif (c >= L'a' && c <= L'z') return _toupper(c);\r\n\t\treturn c;\r\n\t}\r\n\tconstexpr char make_upper(const char c) noexcept\r\n\t{\r\n\t\tif (c >= 'a' && c <= 'z') return _toupper(c);\r\n\t\treturn c;\r\n\t}\r\n\tconstexpr bool CompareChar(const WCHAR c, const WCHAR other, const bool bCase) noexcept\r\n\t{\r\n\t\treturn (bCase) ? c == other : make_upper(c) == make_upper(other);\r\n\t}\r\n\tconstexpr bool CompareChar(const char c, const char other, const bool bCase) noexcept\r\n\t{\r\n\t\treturn (bCase) ? c == other : make_upper(c) == make_upper(other);\r\n\t}\r\n\r\n\ttemplate <typename Result, typename Format>\r\n\tResult& _ts_printf_do(Result& res, const Format& fmt)\r\n\t{\r\n\t\tres += fmt;\r\n\t\treturn res;\r\n\t}\r\n\r\n\ttemplate <typename Result, typename Format, typename Value, typename... Arguments>\r\n\tResult& _ts_printf_do(Result& res, const Format& fmt, const Value& val, Arguments&&... args)\r\n\t{\r\n\t\tauto i = 0U;\r\n\t\tauto bSkip = false;\r\n\r\n\t\tfor (auto c = fmt[0]; c != decltype(c){'\\0'}; c = fmt[++i])\r\n\t\t{\r\n\t\t\tif (!bSkip)\r\n\t\t\t{\r\n\t\t\t\tif (c == decltype(c){'\\\\'})\r\n\t\t\t\t{\r\n\t\t\t\t\tbSkip = true;\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\t\t\t\telse if (c == decltype(c){'%'})\r\n\t\t\t\t{\r\n\t\t\t\t\tif constexpr (is_Numeric_v<Value>)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif constexpr (std::is_same_v<std::string, std::remove_cv_t<Result>>)\r\n\t\t\t\t\t\t\tres += std::to_string(val);\r\n\t\t\t\t\t\telse if constexpr (std::is_same_v<std::wstring, std::remove_cv_t<Result>>)\r\n\t\t\t\t\t\t\tres += std::to_wstring(val);\r\n\t\t\t\t\t\telse\r\n\t\t\t\t\t\t\tres += val;\t// assumes this type can handle adding numbers.\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse\r\n\t\t\t\t\t\tres += val;\r\n\r\n\t\t\t\t\tif constexpr (std::is_array_v<Format> && details::is_pod_v<Format>)\r\n\t\t\t\t\t\treturn _ts_printf_do(res, &fmt[0] + i + 1, args...);\r\n\t\t\t\t\telse\r\n\t\t\t\t\t\treturn _ts_printf_do(res, fmt + i + 1, args...);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t\tbSkip = false;\r\n\t\t\tres += c;\r\n\t\t}\r\n\r\n\t\t//// Ook: needs checked may need work\r\n\t\t//for (const auto &c: fmt)\r\n\t\t//{\r\n\t\t//\tif (!bSkip)\r\n\t\t//\t{\r\n\t\t//\t\tif (c == decltype(c){'\\\\'})\r\n\t\t//\t\t{\r\n\t\t//\t\t\tbSkip = true;\r\n\t\t//\t\t\tcontinue;\r\n\t\t//\t\t}\r\n\t\t//\t\telse if (c == decltype(c){'%'})\r\n\t\t//\t\t{\r\n\t\t//\t\t\tif constexpr (is_Numeric_v<Value>)\r\n\t\t//\t\t\t{\r\n\t\t//\t\t\t\tif constexpr (std::is_same_v<std::string, std::remove_cv_t<Result>>)\r\n\t\t//\t\t\t\t\tres += std::to_string(val);\r\n\t\t//\t\t\t\telse if constexpr (std::is_same_v<std::wstring, std::remove_cv_t<Result>>)\r\n\t\t//\t\t\t\t\tres += std::to_wstring(val);\r\n\t\t//\t\t\t\telse\r\n\t\t//\t\t\t\t\tres += val;\t// assumes this type can handle adding numbers.\r\n\t\t//\t\t\t}\r\n\t\t//\t\t\telse\r\n\t\t//\t\t\t\tres += val;\r\n\t\t//\t\t\tif constexpr (std::is_array_v<Format> && std::is_pod_v<Format>)\r\n\t\t//\t\t\t\treturn _ts_printf_do(res, &fmt[0] + i + 1, args...);\r\n\t\t//\t\t\telse\r\n\t\t//\t\t\t\treturn _ts_printf_do(res, fmt + i + 1, args...);\r\n\t\t//\t\t}\r\n\t\t//\t}\r\n\t\t//\telse\r\n\t\t//\t\tbSkip = false;\r\n\t\t//\tres += c;\r\n\t\t//}\r\n\t\treturn res;\r\n\t}\r\n\r\n\ttemplate<typename T, class TR = std::char_traits<T> >\r\n\tstruct impl_strstr {\r\n\t\tusing ptype = typename TR::char_type*;\r\n\t\tusing cptype = typename const ptype;\r\n\r\n\t\tptype operator()(ptype input, cptype find)\r\n\t\t{\r\n\t\t\tdo {\r\n\t\t\t\tptype p{}, q{};\r\n\t\t\t\tfor (p = input, q = find; !TR::eq(*q, 0) && TR::eq(*p, *q); p++, q++) {}\r\n\r\n\t\t\t\tif (TR::eq(*q, 0))\r\n\t\t\t\t\treturn input;\r\n\r\n\t\t\t} while (!TR::eq(*(input++), 0));\r\n\t\t\treturn nullptr;\r\n\t\t}\r\n\t};\r\n\r\n\t//// Test if a string is empty, works for std::basic_string & TString objects\r\n\t//template <typename T>\r\n\t//std::enable_if_t<!std::is_pointer_v<T> && !std::is_pod_v<T> && std::is_member_function_pointer_v<decltype(&T::empty)>, bool> _ts_isEmpty(const T &str) noexcept\r\n\t//{\r\n\t//\treturn str.empty();\r\n\t//}\r\n\t//\r\n\t//// Test if a string is empty, works for C String char * or wchar_t *\r\n\t//template <typename T>\r\n\t//std::enable_if_t<std::is_pointer_v<T>, bool> _ts_isEmpty(const T &str) noexcept\r\n\t//{\r\n\t//\tusing value_type = std::remove_cv_t<std::remove_pointer_t<T> >;\r\n\t//\r\n\t//\tstatic_assert(std::is_same_v<value_type, char> || std::is_same_v<value_type, wchar_t>, \"Invalid Type used\");\r\n\t//\treturn ((str == nullptr) || (str[0] == value_type()));\r\n\t//}\r\n\t//\r\n\t//// Test if a string is empty, works for C char or wchar_t\r\n\t//template <typename T>\r\n\t//std::enable_if_t<!std::is_pointer_v<T> && std::is_pod_v<T>, bool> _ts_isEmpty(const T &str) noexcept\r\n\t//{\r\n\t//\tusing value_type = std::remove_cv_t<T>;\r\n\t//\r\n\t//\tstatic_assert(std::is_same_v<value_type, char> || std::is_same_v<value_type, wchar_t>, \"Invalid Type used\");\r\n\t//\treturn (str == value_type());\r\n\t//}\r\n\r\n\ttemplate <typename T>\r\n\tbool _ts_isEmpty(const T& str) noexcept\r\n\t{\r\n\t\tif constexpr (std::is_pointer_v<T>)\r\n\t\t{\r\n\t\t\t// T is a pointer\r\n\t\t\t// Test if a string is empty, works for C String char * or wchar_t *\r\n\t\t\tusing value_type = std::remove_cv_t<std::remove_pointer_t<T> >;\r\n\r\n\t\t\tstatic_assert(IsPODText<value_type>, \"Invalid Type used\");\r\n\t\t\treturn ((str == nullptr) || (str[0] == value_type()));\r\n\t\t}\r\n\t\telse if constexpr (std::is_standard_layout_v<T> && std::is_trivial_v<T>) // same as old std::is_pod_v<T>\r\n\t\t{\r\n\t\t\tif constexpr (std::is_array_v<T>)\r\n\t\t\t{\r\n\t\t\t\t// T is NOT a pointer but IS POD and IS an array (char[3] ...)\r\n\t\t\t\t// Test if a string is empty, works for C char or wchar_t\r\n\t\t\t\tusing value_type = std::remove_all_extents_t<std::remove_cv_t<T>>;\r\n\r\n\t\t\t\tstatic_assert(IsPODText<value_type>, \"Invalid Type used\");\r\n\t\t\t\treturn (str[0] == value_type());\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\t// T is NOT a pointer but IS POD and is NOT an array (single char ...)\r\n\t\t\t\t// Test if a string is empty, works for C char or wchar_t\r\n\t\t\t\tusing value_type = std::remove_cv_t<T>;\r\n\r\n\t\t\t\tstatic_assert(IsPODText<value_type>, \"Invalid Type used\");\r\n\t\t\t\treturn (str == value_type());\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if constexpr (std::is_member_function_pointer_v<decltype(&T::empty)>)\r\n\t\t{\r\n\t\t\t// T is NOT a pointer and is NOT POD\r\n\t\t\t// Test if a container is empty, works for std::basic_string & TString objects or any container with an empty() member function.\r\n\t\t\treturn str.empty();\r\n\t\t}\r\n\t}\r\n\r\n\t//// Get String length\r\n\t//template <typename T, typename size_type = std::size_t>\r\n\t//std::enable_if_t<std::is_pointer_v<T>, size_type> _ts_strlen(const T &str) noexcept\r\n\t//{\r\n\t//\tusing value_type = std::remove_cv_t<std::remove_pointer_t<T> >;\r\n\t//\r\n\t//\tstatic_assert(std::is_same_v<value_type, char> || std::is_same_v<value_type, wchar_t>, \"Invalid Type used\");\r\n\t//\tauto iLen = size_type();\r\n\t//\tfor (auto p = str; p && *p; ++p)\r\n\t//\t\t++iLen;\r\n\t//\treturn iLen;\r\n\t//}\r\n\t//\r\n\t//template <typename T, typename size_type = std::size_t>\r\n\t//constexpr inline std::enable_if_t<!std::is_pointer_v<T> && std::is_same_v<std::remove_cv_t<T>, wchar_t>, size_type> _ts_strlen(const T &str) noexcept\r\n\t//{\r\n\t//\treturn (str == T() ? 0U : 1U);\r\n\t//}\r\n\t//\r\n\t//template <typename T, typename size_type = std::size_t>\r\n\t//constexpr inline std::enable_if_t<!std::is_pointer_v<T> && std::is_same_v<std::remove_cv_t<T>, char>, size_type> _ts_strlen(const T &str) noexcept\r\n\t//{\r\n\t//\treturn (str == T() ? 0U : 1U);\r\n\t//}\r\n\t//\r\n\t//template <typename T, typename size_type = std::size_t, std::size_t N>\r\n\t//constexpr inline size_type _ts_strlen(T const (&)[N]) noexcept\r\n\t//{\r\n\t//\treturn (N == 0U ? 0U : N - 1);\r\n\t//}\r\n\t//\r\n\t//template <typename T, typename size_type = T::size_type>\r\n\t//inline std::enable_if_t<!std::is_pointer_v<T> && std::is_member_function_pointer_v<decltype(&T::length)>, size_type> _ts_strlen(const T &str)\r\n\t//{\r\n\t//\treturn str.length();\r\n\t//}\r\n\r\n\t// Get String length\r\n\ttemplate <typename T, IsNumeric size_type = std::size_t>\r\n\tconstexpr size_type _ts_strlen(const T& str) noexcept\r\n\t{\r\n\t\tif constexpr (std::is_pointer_v<T>)\r\n\t\t{\r\n\t\t\t// T is a pointer\r\n\t\t\t//  return length of string...\r\n\r\n\t\t\tstatic_assert(IsPODText<T>, \"Invalid Type used\");\r\n\t\t\tauto iLen = size_type();\r\n\t\t\tfor (auto p = str; p && *p; ++p)\r\n\t\t\t\t++iLen;\r\n\t\t\treturn iLen;\r\n\t\t}\r\n\t\telse if constexpr (IsPODText<T>)\r\n\t\t{\r\n\t\t\t// T is POD, char or wchar_t\r\n\t\t\t// checks if char is zero or not\r\n\t\t\treturn (str == T() ? 0U : 1U);\r\n\t\t}\r\n\t\telse if constexpr (std::is_member_function_pointer_v<decltype(&T::length)>)\r\n\t\t{\r\n\t\t\t// T has a member function length()\r\n\t\t\treturn gsl::narrow_cast<size_type>(str.length());\r\n\t\t}\r\n\t}\r\n\r\n\t//template <typename T, typename size_type = std::size_t, std::size_t N>\r\n\t//constexpr inline size_type _ts_strlen(T const (&)[N]) noexcept\r\n\t//{\r\n\t//\t// T is a fixed array\r\n\t//\treturn (N == 0U ? 0U : N - 1);\r\n\t//}\r\n\r\n\ttemplate <IsPODText T, IsNumeric size_type = std::size_t, std::size_t N>\r\n\tconstexpr inline size_type _ts_strlen(T const (&)[N]) noexcept\r\n\t{\r\n\t\t// T is a fixed array\r\n\t\treturn (N == 0U ? 0U : N - 1);\r\n\t}\r\n\r\n\ttemplate <typename T>\r\n\tstruct _impl_strnlen {\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_strnlen<char*> {\r\n\t\tsize_t operator()(const char* const ptr, size_t length) noexcept\r\n\t\t{\r\n\t\t\treturn strnlen(ptr, length);\r\n\t\t}\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_strnlen<wchar_t*> {\r\n\t\tsize_t operator()(const wchar_t* const ptr, size_t length) noexcept\r\n\t\t{\r\n\t\t\treturn wcsnlen(ptr, length);\r\n\t\t}\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_strnlen<char> {\r\n\t\tsize_t operator()(const char& ptr, size_t length) noexcept\r\n\t\t{\r\n\t\t\treturn (ptr == 0 || length == 0 ? 0U : 1U);\r\n\t\t}\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_strnlen<wchar_t> {\r\n\t\tsize_t operator()(const wchar_t& ptr, size_t length) noexcept\r\n\t\t{\r\n\t\t\treturn (ptr == 0 || length == 0 ? 0U : 1U);\r\n\t\t}\r\n\t};\r\n\r\n\ttemplate <typename T>\r\n\tstruct _impl_strcpyn {\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_strcpyn<char> {\r\n\t\tchar* operator()(char* const pDest, const char* const pSrc, const size_t length) noexcept\r\n\t\t{\r\n\t\t\t//auto t = strncpy(pDest, pSrc, length);\t// doesn't guarantee NULL termination!\r\n\t\t\t//if (t)\r\n\t\t\t//\tt[length - 1] = 0;\t// make sure it ends in NULL\r\n\t\t\t//return t;\r\n\r\n\t\t\treturn lstrcpynA(pDest, pSrc, gsl::narrow_cast<int>(length));\r\n\t\t}\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_strcpyn<wchar_t> {\r\n\t\twchar_t* operator()(wchar_t* const pDest, const wchar_t* const pSrc, const size_t length) noexcept\r\n\t\t{\r\n\t\t\t//auto t = wcsncpy(pDest, pSrc, length); // doesn't guarantee NULL termination!\r\n\t\t\t//if (t)\r\n\t\t\t//\tt[length - 1] = 0;\t// make sure it ends in NULL\r\n\t\t\t//return t;\r\n\r\n\t\t\treturn lstrcpynW(pDest, pSrc, gsl::narrow_cast<int>(length));\r\n\t\t}\r\n\t};\r\n\r\n\ttemplate <typename T>\r\n\tstruct _impl_strcpy {\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_strcpy<char> {\r\n\t\tchar* operator()(char* const pDest, const char* const pSrc) noexcept\r\n\t\t{\r\n\t\t\treturn strcpy(pDest, pSrc);\r\n\t\t}\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_strcpy<wchar_t> {\r\n\t\twchar_t* operator()(wchar_t* const pDest, const wchar_t* const pSrc) noexcept\r\n\t\t{\r\n\t\t\treturn wcscpy(pDest, pSrc);\r\n\t\t}\r\n\t};\r\n\r\n\ttemplate <typename T>\r\n\tstruct _impl_strncat {\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_strncat<char> {\r\n\t\tchar* operator()(char* const pDest, const char* const pSrc, const size_t length) noexcept\r\n\t\t{\r\n\t\t\treturn strncat(pDest, pSrc, length);\r\n\t\t}\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_strncat<wchar_t> {\r\n\t\twchar_t* operator()(wchar_t* const pDest, const wchar_t* const pSrc, const size_t length) noexcept\r\n\t\t{\r\n\t\t\treturn wcsncat(pDest, pSrc, length);\r\n\t\t}\r\n\t};\r\n\r\n\ttemplate <typename T>\r\n\tstruct _impl_strcat {\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_strcat<char> {\r\n\t\tchar* operator()(char* const pDest, const char* const pSrc) noexcept\r\n\t\t{\r\n\t\t\treturn strcat(pDest, pSrc);\r\n\t\t}\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_strcat<wchar_t> {\r\n\t\twchar_t* operator()(wchar_t* const pDest, const wchar_t* const pSrc) noexcept\r\n\t\t{\r\n\t\t\treturn wcscat(pDest, pSrc);\r\n\t\t}\r\n\t};\r\n\r\n\ttemplate <typename T>\r\n\tstruct _impl_strchr {\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_strchr<char> {\r\n\t\tchar* operator()(char* const pString, const char ch)\r\n\t\t{\r\n\t\t\treturn strchr(pString, ch);\r\n\t\t}\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_strchr<wchar_t> {\r\n\t\twchar_t* operator()(wchar_t* const pString, const wchar_t ch)\r\n\t\t{\r\n\t\t\treturn wcschr(pString, ch);\r\n\t\t}\r\n\t};\r\n\r\n\ttemplate <typename T>\r\n\tstruct _impl_strncmp {\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_strncmp<char> {\r\n\t\tint operator()(const char* const pDest, const char* const pSrc, const size_t length) noexcept\r\n\t\t{\r\n\t\t\treturn strncmp(pDest, pSrc, length);\r\n\t\t}\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_strncmp<wchar_t> {\r\n\t\tint operator()(const wchar_t* const pDest, const wchar_t* const pSrc, const size_t length) noexcept\r\n\t\t{\r\n\t\t\treturn wcsncmp(pDest, pSrc, length);\r\n\t\t}\r\n\t};\r\n\r\n\ttemplate <typename T>\r\n\tstruct _impl_strnicmp {\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_strnicmp<char> {\r\n\t\tint operator()(const char* const pDest, const char* const pSrc, const size_t length) noexcept\r\n\t\t{\r\n\t\t\treturn _strnicmp(pDest, pSrc, length);\r\n\t\t}\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_strnicmp<wchar_t> {\r\n\t\tint operator()(const wchar_t* const pDest, const wchar_t* const pSrc, const size_t length) noexcept\r\n\t\t{\r\n\t\t\treturn _wcsnicmp(pDest, pSrc, length);\r\n\t\t}\r\n\t};\r\n\r\n\ttemplate <typename T>\r\n\tstruct _impl_strcmp {\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_strcmp<char> {\r\n\t\tint operator()(const char* const pDest, const char* const pSrc) noexcept\r\n\t\t{\r\n\t\t\treturn strcmp(pDest, pSrc);\r\n\t\t}\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_strcmp<wchar_t> {\r\n\t\tint operator()(const wchar_t* const pDest, const wchar_t* const pSrc) noexcept\r\n\t\t{\r\n\t\t\treturn wcscmp(pDest, pSrc);\r\n\t\t}\r\n\t};\r\n\r\n\ttemplate <typename T>\r\n\tstruct _impl_stricmp {\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_stricmp<char> {\r\n\t\tint operator()(const char* const pDest, const char* const pSrc) noexcept\r\n\t\t{\r\n\t\t\treturn _stricmp(pDest, pSrc);\r\n\t\t}\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_stricmp<wchar_t> {\r\n\t\tint operator()(const wchar_t* const pDest, const wchar_t* const pSrc) noexcept\r\n\t\t{\r\n\t\t\treturn _wcsicmp(pDest, pSrc);\r\n\t\t}\r\n\t};\r\n\r\n\ttemplate <typename T>\r\n\tstruct _impl_ts_find {\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_ts_find<char> {\r\n\t\tconst char* operator()(const char* const str, const char& srch) noexcept\r\n\t\t{\r\n\t\t\treturn strchr(str, srch);\r\n\t\t}\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_ts_find<const char> {\r\n\t\tconst char* operator()(const char* const str, const char& srch) noexcept\r\n\t\t{\r\n\t\t\treturn strchr(str, srch);\r\n\t\t}\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_ts_find<char*> {\r\n\t\tconst char* operator()(const char* const str, const char* srch) noexcept\r\n\t\t{\r\n\t\t\treturn strstr(str, srch);\r\n\t\t}\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_ts_find<const char*> {\r\n\t\tconst char* operator()(const char* const str, const char* srch) noexcept\r\n\t\t{\r\n\t\t\treturn strstr(str, srch);\r\n\t\t}\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_ts_find<wchar_t> {\r\n\t\tconst wchar_t* operator()(const wchar_t* const str, const wchar_t& srch) noexcept\r\n\t\t{\r\n\t\t\treturn wcschr(str, srch);\r\n\t\t}\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_ts_find<const wchar_t> {\r\n\t\tconst wchar_t* operator()(const wchar_t* const str, const wchar_t& srch) noexcept\r\n\t\t{\r\n\t\t\treturn wcschr(str, srch);\r\n\t\t}\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_ts_find<wchar_t*> {\r\n\t\tconst wchar_t* operator()(const wchar_t* const str, const wchar_t* srch) noexcept\r\n\t\t{\r\n\t\t\treturn wcsstr(str, srch);\r\n\t\t}\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_ts_find<const wchar_t*> {\r\n\t\tconst wchar_t* operator()(const wchar_t* const str, const wchar_t* srch) noexcept\r\n\t\t{\r\n\t\t\treturn wcsstr(str, srch);\r\n\t\t}\r\n\t};\r\n\r\n\ttemplate <typename T>\r\n\tstruct _impl_vscprintf {\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_vscprintf<char> {\r\n\t\tconst int operator()(const char* const fmt, const va_list args) noexcept\r\n\t\t{\r\n\t\t\treturn _vscprintf(fmt, args);\r\n\t\t}\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_vscprintf<wchar_t> {\r\n\t\tconst int operator()(const wchar_t* const fmt, const va_list args) noexcept\r\n\t\t{\r\n\t\t\treturn _vscwprintf(fmt, args);\r\n\t\t}\r\n\t};\r\n\r\n\ttemplate <typename T>\r\n\tstruct _impl_vsprintf {\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_vsprintf<char> {\r\n\t\tconst int operator()(char* const buf, size_t nCount, const char* const fmt, const va_list args) noexcept\r\n\t\t{\r\n\t\t\treturn vsnprintf(buf, nCount, fmt, args);\r\n\t\t}\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_vsprintf<wchar_t> {\r\n\t\tconst int operator()(wchar_t* const buf, size_t nCount, const wchar_t* const fmt, const va_list args) noexcept\r\n\t\t{\r\n\t\t\treturn vswprintf(buf, nCount, fmt, args);\r\n\t\t}\r\n\t};\r\n\r\n\ttemplate <typename T, typename Format, typename... Arguments>\r\n\tstruct _impl_snprintf {\r\n\t};\r\n\ttemplate <typename... Arguments>\r\n\tstruct _impl_snprintf<char, char, Arguments...> {\r\n\t\tconst int operator()(char* const buf, const size_t nCount, const char* const fmt, const Arguments&&... args) noexcept\r\n\t\t{\r\n\t\t\treturn snprintf(buf, nCount, fmt, args...);\r\n\t\t}\r\n\t};\r\n\ttemplate <typename... Arguments>\r\n\tstruct _impl_snprintf<wchar_t, wchar_t, Arguments...> {\r\n\t\tconst int operator()(wchar_t* const buf, const size_t nCount, const wchar_t* const fmt, const Arguments&&... args) noexcept\r\n\t\t{\r\n\t\t\treturn _snwprintf(buf, nCount, fmt, args...);\r\n\t\t}\r\n\t};\r\n\r\n\t//template <typename T, typename... Arguments>\r\n\t//struct _impl_snprintf<T, typename T::value_type, Arguments...> {\r\n\t//\tconst std::enable_if_t<std::is_member_function_pointer_v<decltype(&T::data)> && std::is_member_function_pointer_v<decltype(&T::size)>, int> operator()(T& buf, const typename T::value_type* const fmt, const Arguments&&... args) noexcept\r\n\t//\t{\r\n\t//\t\tif constexpr (std::is_same_v<char, T::value_type>)\r\n\t//\t\t\treturn snprintf(buf.data(), buf.size(), fmt, args...);\r\n\t//\t\telse\r\n\t//\t\t\treturn _snwprintf(buf.data(), buf.size(), fmt, args...);\r\n\t//\t}\r\n\t//};\r\n\r\n\ttemplate <HasDataSizeNoChr T, typename... Arguments>\r\n\tstruct _impl_snprintf<T, typename T::value_type, Arguments...> {\r\n\t\tconst int operator()(T& buf, const typename T::value_type* const fmt, const Arguments&&... args) noexcept\r\n\t\t{\r\n\t\t\tif constexpr (std::is_same_v<char, T::value_type>)\r\n\t\t\t\treturn snprintf(buf.data(), buf.size(), fmt, args...);\r\n\t\t\telse\r\n\t\t\t\treturn _snwprintf(buf.data(), buf.size(), fmt, args...);\r\n\t\t}\r\n\t};\r\n\ttemplate <HasDataSizeChr T, typename... Arguments>\r\n\tstruct _impl_snprintf<T, typename T::value_type, Arguments...> {\r\n\t\tconst int operator()(T& buf, const typename T::value_type* const fmt, const Arguments&&... args) noexcept\r\n\t\t{\r\n\t\t\tif constexpr (std::is_same_v<char, T::value_type>)\r\n\t\t\t\treturn snprintf(buf.to_chr(), buf.size(), fmt, args...);\r\n\t\t\telse\r\n\t\t\t\treturn _snwprintf(buf.to_chr(), buf.size(), fmt, args...);\r\n\t\t}\r\n\t};\r\n\r\n\ttemplate <typename T>\r\n\tstruct _impl_atoi {\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_atoi<char> {\r\n\t\tauto operator()(const char* const buf) noexcept\r\n\t\t{\r\n\t\t\treturn atoi(buf);\r\n\t\t}\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_atoi<wchar_t> {\r\n\t\tauto operator()(const wchar_t* const buf) noexcept\r\n\t\t{\r\n\t\t\treturn _wtoi(buf);\r\n\t\t}\r\n\t};\r\n\r\n\ttemplate <typename T>\r\n\tstruct _impl_atoi64 {\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_atoi64<char> {\r\n\t\tauto operator()(const char* const buf) noexcept\r\n\t\t{\r\n\t\t\treturn _atoi64(buf);\r\n\t\t}\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_atoi64<wchar_t> {\r\n\t\tauto operator()(const wchar_t* const buf) noexcept\r\n\t\t{\r\n\t\t\treturn _wtoi64(buf);\r\n\t\t}\r\n\t};\r\n\r\n\ttemplate <typename T>\r\n\tstruct _impl_atof {\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_atof<char> {\r\n\t\tauto operator()(const char* const buf) noexcept\r\n\t\t{\r\n\t\t\treturn atof(buf);\r\n\t\t}\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_atof<wchar_t> {\r\n\t\tauto operator()(const wchar_t* const buf) noexcept\r\n\t\t{\r\n\t\t\treturn _wtof(buf);\r\n\t\t}\r\n\t};\r\n\r\n\ttemplate <typename T>\r\n\tstruct _impl_itoa {\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_itoa<char> {\r\n\t\tauto operator()(const int val, char* const buf, const int radix) noexcept\r\n\t\t{\r\n\t\t\treturn _itoa(val, buf, radix);\r\n\t\t}\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_itoa<wchar_t> {\r\n\t\tauto operator()(const int val, wchar_t* const buf, const int radix) noexcept\r\n\t\t{\r\n\t\t\treturn _itow(val, buf, radix);\r\n\t\t}\r\n\t};\r\n\r\n\ttemplate <typename T>\r\n\tstruct _impl_strtoul {\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_strtoul<char> {\r\n\t\tauto operator()(const char* const buf, char** endptr, int radx) noexcept\r\n\t\t{\r\n\t\t\treturn strtoul(buf, endptr, radx);\r\n\t\t}\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_strtoul<wchar_t> {\r\n\t\tauto operator()(const wchar_t* const buf, wchar_t** endptr, int radx) noexcept\r\n\t\t{\r\n\t\t\treturn wcstoul(buf, endptr, radx);\r\n\t\t}\r\n\t};\r\n\r\n\t/// <summary>\r\n\t/// Convert a string representation of a binary number to an unsigned long\r\n\t/// </summary>\r\n\t/// <typeparam name=\"T\">- char or wchar_t</typeparam>\r\n\ttemplate <typename T>\r\n\tstruct _impl_bstrtoul {\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_bstrtoul<char> {\r\n\t\tauto operator()(const char* const buf) noexcept\r\n\t\t{\r\n\t\t\treturn strtoul(buf, nullptr, 2);\r\n\t\t}\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_bstrtoul<wchar_t> {\r\n\t\tauto operator()(const wchar_t* const buf) noexcept\r\n\t\t{\r\n\t\t\treturn wcstoul(buf, nullptr, 2);\r\n\t\t}\r\n\t};\r\n\ttemplate <typename T>\r\n\tstruct _impl_strtok {\r\n\t};\r\n\ttemplate <>\r\n\tstruct _impl_strtok<char> {\r\n\t\tauto operator()(char* const buf, const char* delim, char** contex) noexcept\r\n\t\t{\r\n\t\t\treturn strtok_s(buf, delim, contex);\r\n\t\t}\r\n\t};\r\n\r\n\ttemplate <>\r\n\tstruct _impl_strtok<wchar_t> {\r\n\t\tauto operator()(wchar_t* const buf, const wchar_t* delim, wchar_t** contex) noexcept\r\n\t\t{\r\n\t\t\treturn wcstok_s(buf, delim, contex);\r\n\t\t}\r\n\t};\r\n}\r\n\r\n// Check string bounds, make sure dest is not within the source string & vice versa (this could be a possible reason for some strcpyn() fails we see)\r\ntemplate <details::IsPODText T>\r\nconstexpr bool isInBounds(const T* const sDest, const T* const sSrc, const std::size_t iLen) noexcept\r\n{\r\n\treturn (sSrc >= sDest && sSrc <= (sDest + iLen)) || (sDest >= sSrc && sDest <= (sSrc + iLen));\r\n}\r\n\r\ntemplate <typename Result, typename Format, typename Value, typename... Arguments>\r\nResult& _ts_sprintf(Result& res, const Format& fmt, const Value& val, Arguments&&... args)\r\n{\r\n\tstatic_assert(details::IsPODText<Format>, \"Format string must be char or wchar_t\");\r\n\tres.clear();\r\n\treturn details::_ts_printf_do(res, fmt, val, args...);\r\n}\r\n\r\ntemplate <details::IsPODText T>\r\nT* _ts_strstr(T* input, const std::remove_const_t<T>* find)\r\n{\r\n\treturn details::impl_strstr<T>()(input, find);\r\n}\r\n\r\n// Get String length\r\ntemplate <typename T>\r\ninline auto _ts_strlen(const T& str) noexcept\r\n{\r\n\treturn details::_ts_strlen(str);\r\n}\r\n\r\n// Get String length (with buffer size limit)\r\ntemplate <details::IsPODText T>\r\ninline size_t _ts_strnlen(const T& str, const size_t& nBufSize) noexcept\r\n{\r\n\treturn details::_impl_strnlen<T>()(str, nBufSize);\r\n}\r\n\r\n// Test if a string is empty, works for any object that has an empty() member function as well as C strings.\r\ntemplate <typename T>\r\ninline bool _ts_isEmpty(const T& str) noexcept\r\n{\r\n\treturn details::_ts_isEmpty(str);\r\n}\r\n\r\n// Finds a string or character within a string & returns a pointer to it.\r\ntemplate <details::IsPODText HayStack, details::IsPODText Needle>\r\ninline HayStack* _ts_find(HayStack* const str, Needle srch) noexcept\r\n{\r\n\treturn const_cast<HayStack*>(details::_impl_ts_find<Needle>()(str, srch));\r\n}\r\ntemplate <details::IsPODText HayStack, details::IsPODText Needle>\r\ninline const HayStack* _ts_find(const HayStack* const str, Needle srch) noexcept\r\n{\r\n\treturn details::_impl_ts_find<Needle>()(str, srch);\r\n}\r\n\r\n// Finds a string literal within a string & returns a pointer to it.\r\ntemplate <typename T, size_t N>\r\ninline T* _ts_find(T* const str, const T(&srch)[N]) noexcept\r\n{\r\n\treturn const_cast<T*>(details::_impl_ts_find<std::add_pointer_t<T>>()(str, &srch[0]));\r\n}\r\n\r\n//// Finds a string or character within a string & returns a pointer to it.\r\n//template <typename T, typename TStr>\r\n//inline TStr *_ts_find(TStr *const str, T &srch)\r\n//{\r\n//\treturn const_cast<TStr *>(details::_impl_ts_find<std::remove_cv_t<T>>()(str, srch));\r\n//}\r\n//\r\n//// Finds a string literal within a string & returns a pointer to it.\r\n//template <typename T, typename TStr, size_t N>\r\n//inline TStr *_ts_find(TStr *const str, const T (&srch)[N])\r\n//{\r\n//\treturn const_cast<TStr *>(details::_impl_ts_find<std::add_pointer_t<T>>()(str, &srch[0]));\r\n//}\r\n\r\n//template <typename T, typename TStr>\r\n//inline const TStr *_ts_find(const TStr *const str, const T &srch)\r\n//{\r\n//\treturn details::_impl_ts_find<std::remove_cv_t<T>>()(str, srch);\r\n//}\r\n//\r\n//template <typename T, typename TStr>\r\n//inline TStr *_ts_find(TStr *const str, const T &srch)\r\n//{\r\n//\treturn const_cast<TStr *>(details::_impl_ts_find<std::remove_cv_t<T>>()(str, srch));\r\n//}\r\n\r\ntemplate <details::IsPODText T>\r\nT* _ts_strcpyn(T* const sDest, const T* const sSrc, const size_t iChars) noexcept\r\n{\r\n\tstatic_assert(details::IsPODText<T>, \"Only char & wchar_t supported...\");\r\n\r\n\t//#if DCX_DEBUG_OUTPUT\r\n\t//\tif ((sDest == nullptr) || (sSrc == nullptr) || isInBounds<std::remove_cv_t<T> >(sDest, sSrc, iChars))\r\n\t//\t\treturn nullptr;\r\n\t//#else\r\n\tif ((!sDest) || (!sSrc))\r\n\t\treturn nullptr;\r\n\t//#endif\r\n\r\n\treturn details::_impl_strcpyn<T>()(sDest, sSrc, iChars);\r\n}\r\n\r\ntemplate <details::IsPODText T>\r\nT* _ts_strcpy(T* const sDest, const T* const sSrc) noexcept\r\n{\r\n\tstatic_assert(details::IsPODText<T>, \"Only char & wchar_t supported...\");\r\n\r\n\tif ((!sDest) || (!sSrc))\r\n\t\treturn nullptr;\r\n\r\n\treturn details::_impl_strcpy<T>()(sDest, sSrc);\r\n}\r\n\r\ntemplate <details::IsPODText T>\r\nT* _ts_strncat(T* const sDest, const T* const sSrc, const size_t iChars) noexcept\r\n{\r\n\tstatic_assert(details::IsPODText<T>, \"Only char & wchar_t supported...\");\r\n\r\n\treturn details::_impl_strncat<T>()(sDest, sSrc, iChars);\r\n}\r\n\r\ntemplate <details::IsPODText T>\r\nT* _ts_strcat(T* const sDest, const T* const sSrc) noexcept\r\n{\r\n\tstatic_assert(details::IsPODText<T>, \"Only char & wchar_t supported...\");\r\n\r\n\treturn details::_impl_strcat<T>()(sDest, sSrc);\r\n}\r\n\r\ntemplate <details::IsPODText T>\r\nT* _ts_strchr(T* const sDest, const T ch)\r\n{\r\n\tstatic_assert(details::IsPODText<T>, \"Only char & wchar_t supported...\");\r\n\r\n\treturn details::_impl_strchr<T>()(sDest, ch);\r\n}\r\n\r\ntemplate <details::IsPODText T>\r\nint _ts_strncmp(const T* const sDest, const T* const sSrc, const size_t iChars) noexcept\r\n{\r\n\tstatic_assert(details::IsPODText<T>, \"Only char & wchar_t supported...\");\r\n\r\n\treturn details::_impl_strncmp<T>()(sDest, sSrc, iChars);\r\n}\r\n\r\ntemplate <details::IsPODText T>\r\nint _ts_strnicmp(const T* const sDest, const T* const sSrc, const size_t iChars) noexcept\r\n{\r\n\tstatic_assert(details::IsPODText<T>, \"Only char & wchar_t supported...\");\r\n\r\n\treturn details::_impl_strnicmp<T>()(sDest, sSrc, iChars);\r\n}\r\n\r\ntemplate <details::IsPODText T>\r\nint _ts_strcmp(const T* const sDest, const T* const sSrc) noexcept\r\n{\r\n\tstatic_assert(details::IsPODText<T>, \"Only char & wchar_t supported...\");\r\n\r\n\treturn details::_impl_strcmp<T>()(sDest, sSrc);\r\n}\r\n\r\ntemplate <details::IsPODText T>\r\nint _ts_stricmp(const T* const sDest, const T* const sSrc) noexcept\r\n{\r\n\tstatic_assert(details::IsPODText<T>, \"Only char & wchar_t supported...\");\r\n\r\n\treturn details::_impl_stricmp<T>()(sDest, sSrc);\r\n}\r\n\r\ntemplate <details::IsPODText T>\r\nint _ts_vscprintf(_Printf_format_string_ const T* const _Format, va_list _ArgList) noexcept\r\n{\r\n\tstatic_assert(details::IsPODText<T>, \"Only char & wchar_t supported...\");\r\n\r\n\treturn details::_impl_vscprintf<T>()(_Format, _ArgList);\r\n}\r\n\r\ntemplate <details::IsPODText T>\r\nint _ts_vsprintf(T* const buf, size_t nCount, _Printf_format_string_ const T* const fmt, const va_list args) noexcept\r\n{\r\n\tstatic_assert(details::IsPODText<T>, \"Only char & wchar_t supported...\");\r\n\r\n\treturn details::_impl_vsprintf<T>()(buf, nCount, fmt, args);\r\n}\r\n\r\ntemplate <details::IsPODText T, typename Format, typename... Arguments>\r\nint _ts_snprintf(T* const buf, const size_t nCount, _Printf_format_string_ const Format* const fmt, Arguments&&... args) noexcept\r\n{\r\n\tstatic_assert(details::IsPODText<T>, \"Only char & wchar_t supported...\");\r\n\tstatic_assert(std::is_same_v<std::remove_cv_t<T>, std::remove_cv_t<Format>>, \"Buffer & format must have same type.\");\r\n\r\n\treturn details::_impl_snprintf<T, Format, Arguments...>()(buf, nCount, fmt, std::forward<Arguments>(args)...);\r\n}\r\n\r\ntemplate <typename T, details::IsPODText Format, typename... Arguments>\r\nint _ts_snprintf(T& buf, _Printf_format_string_ const Format* const fmt, Arguments&&... args) noexcept\r\n{\r\n\tstatic_assert(details::IsPODText<Format>, \"Only char & wchar_t supported...\");\r\n\r\n\treturn details::_impl_snprintf<T, Format, Arguments...>()(buf, fmt, std::forward<Arguments>(args)...);\r\n}\r\n\r\ntemplate <details::IsPODText T>\r\nauto _ts_atoi(const T* const buf) noexcept\r\n{\r\n\tstatic_assert(details::IsPODText<T>, \"Only char & wchar_t supported...\");\r\n\r\n\treturn details::_impl_atoi<T>()(buf);\r\n}\r\n\r\ntemplate <details::IsPODText T>\r\nauto _ts_atoi64(const T* const buf) noexcept\r\n{\r\n\tstatic_assert(details::IsPODText<T>, \"Only char & wchar_t supported...\");\r\n\r\n\treturn details::_impl_atoi64<T>()(buf);\r\n}\r\n\r\ntemplate <details::IsPODText T>\r\nauto _ts_atof(const T* const buf) noexcept\r\n{\r\n\tstatic_assert(details::IsPODText<T>, \"Only char & wchar_t supported...\");\r\n\r\n\treturn details::_impl_atof<T>()(buf);\r\n}\r\n\r\ntemplate <details::IsPODText T>\r\nauto _ts_itoa(const int val, T* const buf, const int radix) noexcept\r\n{\r\n\tstatic_assert(details::IsPODText<T>, \"Only char & wchar_t supported...\");\r\n\r\n\treturn details::_impl_itoa<T>()(val, buf, radix);\r\n}\r\n\r\ntemplate <details::IsPODText T>\r\nauto _ts_strtoul(const T* const buf, T** endptr, int base) noexcept\r\n{\r\n\tstatic_assert(details::IsPODText<T>, \"Only char & wchar_t supported...\");\r\n\r\n\treturn details::_impl_strtoul<T>()(buf, endptr, base);\r\n}\r\n\r\n/// <summary>\r\n/// Convert a string representation of a binary number to an unsigned long\r\n/// </summary>\r\n/// <param name=\"buf\">- String representing a binary number.</param>\r\n/// <returns>Binary number</returns>\r\ntemplate <details::IsPODText T>\r\nauto _ts_bstrtoul(const T* const buf) noexcept\r\n{\r\n\tstatic_assert(details::IsPODText<T>, \"Only char & wchar_t supported...\");\r\n\r\n\treturn details::_impl_bstrtoul<T>()(buf);\r\n}\r\n\r\n/// <summary>\r\n/// same as strtok_s()\r\n/// </summary>\r\n/// <param name=\"buf\"></param>\r\n/// <param name=\"delim\"></param>\r\n/// <param name=\"contex\"></param>\r\n/// <returns></returns>\r\ntemplate <details::IsPODText T>\r\nauto _ts_strtok(T* const buf, const T* delim, T** contex) noexcept\r\n{\r\n\tstatic_assert(details::IsPODText<T>, \"Only char & wchar_t supported...\");\r\n\r\n\treturn details::_impl_strtok<T>()(buf, delim, contex);\r\n}\r\n\r\n/// <summary>\r\n/// Converts a number into a binary string representing that number (whole integers only)\r\n/// </summary>\r\n/// <typeparam name=\"Result\">A string type object</typeparam>\r\n/// <param name=\"a\">- The number to convert.</param>\r\n/// <returns>The string representation of the number.</returns>\r\ntemplate <details::IsNumeric T, class Result>\r\nResult DecimalToBinaryString(const T& a)\r\n{\r\n\tResult binary;\r\n\tconstexpr auto sz = sizeof(a) * 8;\r\n\tstd::remove_const_t<T> mask = 1;\r\n\tfor (std::remove_const_t<decltype(sz)> i = 0; i < sz; ++i)\r\n\t{\r\n\t\tif ((mask & a))\r\n\t\t\tbinary = '1' + binary;\r\n\t\telse\r\n\t\t\tbinary = '0' + binary;\r\n\t\tmask <<= 1;\r\n\t}\r\n\treturn binary;\r\n}\r\n\r\n/// <summary>\r\n/// Replace all instances of 'rep' in 'str' with 'with'\r\n/// </summary>\r\n/// <typeparam name=\"T\"></typeparam>\r\n/// <typeparam name=\"RepThis\"></typeparam>\r\n/// <typeparam name=\"WithThis\"></typeparam>\r\n/// <param name=\"str\">- string to search</param>\r\n/// <param name=\"rep\">- string to search for</param>\r\n/// <param name=\"with\">- replacement string</param>\r\n/// <returns>The string it was passed with the changes made.</returns>\r\ntemplate <class T, class RepThis, class WithThis>\r\nT& _ts_replace(T& str, RepThis rep, WithThis with)\r\n{\r\n\tfor (std::size_t wlen = _ts_strlen(with), rlen = _ts_strlen(rep), pos = 0U; ; pos += wlen)\r\n\t{\r\n\t\tpos = str.find(rep, pos);\r\n\t\tif (pos == T::npos)\r\n\t\t\tbreak;\r\n\r\n\t\tif constexpr (std::is_same_v<char, std::remove_cv_t<WithThis>> || std::is_same_v<wchar_t, std::remove_cv_t<WithThis>>)\r\n\t\t{\r\n\t\t\tstr.replace(pos, rlen, 1, with);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tstr.replace(pos, rlen, with);\r\n\t\t}\r\n\t}\r\n\treturn str;\r\n}\r\n\r\n//void ReplaceStringInPlace(std::string& subject, const std::string& search, const std::string& replace)\r\n//{\r\n//\tsize_t pos = 0;\r\n//\twhile ((pos = subject.find(search, pos)) != std::string::npos)\r\n//\t{\r\n//\t\tsubject.replace(pos, search.length(), replace);\r\n//\t\tpos += replace.length();\r\n//\t}\r\n//}\r\n\r\n/// <summary>\r\n/// Replace all instances of each character in 'rep' in 'str' with 'with'\r\n/// </summary>\r\n/// <typeparam name=\"T\"></typeparam>\r\n/// <typeparam name=\"RepThis\"></typeparam>\r\n/// <typeparam name=\"WithThis\"></typeparam>\r\n/// <param name=\"str\">- string to search</param>\r\n/// <param name=\"rep\">- string of characters to search for</param>\r\n/// <param name=\"with\">- replacement string</param>\r\n/// <returns>The string it was passed with the changes made.</returns>\r\ntemplate <class T, class RepThis, class WithThis>\r\nT& _ts_mreplace(T& str, RepThis rep, WithThis with)\r\n{\r\n\tfor (std::ptrdiff_t i = 0; rep[i] != 0; ++i)\r\n\t\t_ts_replace(str, rep[i], with);\r\n\treturn str;\r\n}\r\n\r\n/// <summary>\r\n/// Remove all instances of 'rep' within 'str'\r\n/// </summary>\r\n/// <typeparam name=\"T\"></typeparam>\r\n/// <typeparam name=\"RemThis\"></typeparam>\r\n/// <param name=\"str\">- string to search.</param>\r\n/// <param name=\"rep\">- string to remove.</param>\r\n/// <returns>The string it was passed with the changes made.</returns>\r\ntemplate <class T, class RemThis>\r\nT& _ts_remove(T& str, RemThis rep)\r\n{\r\n\tfor (auto itEnd = str.end(), itStart = str.begin(); str.erase(std::find(itStart, itEnd, rep)) != itEnd; ) {}\r\n\r\n\treturn str;\r\n}\r\n\r\n/// <summary>\r\n/// Remove spaces from the front and back of the string.\r\n/// </summary>\r\n/// <typeparam name=\"T\">A string type object</typeparam>\r\n/// <param name=\"str\">- The string to trim.</param>\r\n/// <returns>A reference to the same string object it was passed.</returns>\r\ntemplate <class T>\r\nT& _ts_trim(T& str)\r\n{\r\n\tif (str.empty())\r\n\t\treturn str;\r\n\r\n\twhile (str.front() == _T(' '))\r\n\t\tstr.erase(0, 1);\r\n\r\n\twhile (str.back() == _T(' '))\r\n\t\tstr.pop_back();\r\n\r\n\treturn str;\r\n}\r\n\r\n/// <summary>\r\n/// Copies the string then remove spaces from the front and back of the string.\r\n/// </summary>\r\n/// <typeparam name=\"T\">A string type object</typeparam>\r\n/// <param name=\"str\">- The string to trim.</param>\r\n/// <returns>A copy of the string object it was passed.</returns>\r\ntemplate <class T>\r\nT _ts_trim_and_copy(const T& str)\r\n{\r\n\tif (str.empty())\r\n\t\treturn str;\r\n\r\n\tT res(str);\r\n\twhile (res.front() == _T(' '))\r\n\t\tres.erase(0, 1);\r\n\r\n\twhile (res.back() == _T(' '))\r\n\t\tres.pop_back();\r\n\r\n\treturn res;\r\n}\r\n\r\n/// <summary>\r\n/// Trim the string and remove double spaces.\r\n/// </summary>\r\n/// <typeparam name=\"T\"></typeparam>\r\n/// <param name=\"str\">- string to modify.</param>\r\n/// <returns>The string it was passed with the changes made.</returns>\r\ntemplate <class T>\r\nT& _ts_strip(T& str)\r\n{\r\n\t//_ts_remove(str, _T('\\0x02'));\t//02\r\n\t//_ts_remove(str, _T('\\0x0F'));\t//15\r\n\t//_ts_remove(str, _T('\\0x16'));\t//22\r\n\t//_ts_remove(str, _T('\\0x1D'));\t//29\r\n\t_ts_replace(str, _T(\"  \"), _T(' '));\r\n\t// NB: TODO: add ctrl-k removal for colour codes.\r\n\treturn _ts_trim(str);\r\n}\r\n\r\n/// <summary>\r\n/// Change a string to uppercase.\r\n/// </summary>\r\n/// <typeparam name=\"T\"></typeparam>\r\n/// <param name=\"str\">- string to modify.</param>\r\n/// <returns>The string it was passed with the changes made.</returns>\r\ntemplate <class T>\r\nT& _ts_toupper(T& str)\r\n{\r\n\tfor (auto& a : str)\r\n\t\ta = details::make_upper(a);\r\n\treturn str;\r\n}\r\n\r\ntemplate <details::IsPODText T>\r\nT _ts_toupper_c(const T& c) noexcept\r\n{\r\n\treturn details::make_upper(c);\r\n}\r\n\r\ntemplate <details::IsPODText T>\r\nbool _ts_isupper(const T& c) noexcept\r\n{\r\n\tif constexpr (std::is_same_v<wchar_t, T>)\r\n\t\treturn (iswupper(c) != 0);\r\n\telse\r\n\t\treturn (isupper(c) != 0);\r\n}\r\n\r\n/// <summary>\r\n/// Convert a string to a number.\r\n/// </summary>\r\n/// <typeparam name=\"T\"></typeparam>\r\n/// <typeparam name=\"Input\"></typeparam>\r\n/// <param name=\"str\">- string to convert.</param>\r\n/// <returns>The number contained in the string.</returns>\r\ntemplate <class T, class Input>\r\nT _ts_to_(const Input& str)\r\n{\r\n\tstatic_assert(is_Numeric_v<T>, \"Type T must be (int, long, float, double, ....)\");\r\n\r\n\tstd::basic_istringstream<TCHAR> ss(str);\t// makes copy of string :(\r\n\tT result{};\r\n\treturn ss >> result ? result : T();\r\n}\r\n\r\n#define TSTRING_WILDT 0\r\n#define TSTRING_WILDA 0\r\n#define TSTRING_WILDE 0\r\n#define TSTRING_WILDW 0\r\n\r\n//template <class T>\r\n//constexpr auto getWildType(T s) noexcept\r\n//{\r\n//\tif constexpr (details::is_pod_v<T>)\r\n//\t\treturn typename std::remove_pointer_t<std::remove_cv_t<std::remove_all_extents_t<T>>>;\r\n//\telse\r\n//\t\treturn typename std::remove_pointer_t<std::remove_cv_t<std::remove_all_extents_t<T::value_type>>>;\r\n//}\r\n//\r\n//template <typename TameString, typename WildString>\r\n//[[gsl::suppress(bounds)]] bool _ts_WildcardMatch(const TameString& pszString, const WildString& pszMatch, const bool bCase = false)\r\n//{\r\n//\t//if ((!pszMatch) || (!pszString))\r\n//\t//\treturn false;\r\n//\r\n//\tif (_ts_isEmpty(pszMatch) || _ts_isEmpty(pszString))\r\n//\t\treturn false;\r\n//\r\n//\tptrdiff_t MatchPlaceholder = 0;\r\n//\tptrdiff_t StringPlaceholder = 0;\r\n//\tptrdiff_t iWildOffset = 0;\r\n//\tptrdiff_t iTameOffset = 0;\r\n//\r\n//\t//using _WildString = typename std::remove_pointer_t<std::remove_cv_t<std::remove_all_extents_t<WildString::value_type>>>;\r\n//\tusing _WildString = typename std::remove_pointer_t<std::remove_cv_t<std::remove_all_extents_t<WildString>>>;\r\n//\t//auto a = getWildType(pszMatch);\r\n//\r\n//\tconstexpr _WildString _zero{};\r\n//\tconstexpr _WildString _star = static_cast<_WildString>('*');\r\n//\tconstexpr _WildString _question = static_cast<_WildString>('?');\r\n//\tconstexpr _WildString _tilda = static_cast<_WildString>('~');\r\n//\tconstexpr _WildString _space = static_cast<_WildString>(' ');\r\n//\tconstexpr _WildString _power = static_cast<_WildString>('^');\r\n//\tconstexpr _WildString _hash = static_cast<_WildString>('#');\r\n//\tconstexpr _WildString _slash = static_cast<_WildString>('\\\\');\r\n//\tconstexpr _WildString _tab = static_cast<_WildString>('\\t');\r\n//\tconstexpr _WildString _n = static_cast<_WildString>('\\n');\r\n//\tconstexpr _WildString _r = static_cast<_WildString>('\\r');\r\n//\r\n//\twhile (pszString[iTameOffset])\r\n//\t{\r\n//\t\tif (pszMatch[iWildOffset] == _star)\r\n//\t\t{\r\n//\t\t\tif (pszMatch[++iWildOffset] == _zero)\r\n//\t\t\t\treturn true;\r\n//\t\t\tMatchPlaceholder = iWildOffset;\r\n//\t\t\tStringPlaceholder = iTameOffset + 1;\r\n//\t\t}\r\n//#if TSTRING_WILDT\r\n//\t\telse if (pszMatch[iWildOffset] == _tilda && pszString[iTameOffset] == _space)\r\n//\t\t{\r\n//\t\t\t++iWildOffset;\r\n//\t\t\twhile (pszString[iTameOffset] == _space)\r\n//\t\t\t\t++iTameOffset;\r\n//\t\t}\r\n//#endif\r\n//#if TSTRING_WILDA\r\n//\t\telse if (pszMatch[iWildOffset] == _power)\r\n//\t\t{\r\n//\t\t\t++iWildOffset;\r\n//\t\t\tif (details::CompareChar(pszMatch[iWildOffset], pszString[iTameOffset], bCase))\r\n//\t\t\t\t++iTameOffset;\r\n//\t\t\t++iWildOffset;\r\n//\t\t}\r\n//#endif\r\n//#if TSTRING_WILDE\r\n//\t\telse if (pszMatch[iWildOffset] == _slash)\r\n//\t\t{\r\n//\t\t\t// any character following a '\\' is taken as a literal character.\r\n//\t\t\t++iWildOffset;\r\n//\t\t\tif (!details::CompareChar(pszMatch[iWildOffset], pszString[iTameOffset], bCase))\r\n//\t\t\t\treturn false;\r\n//\t\t\t++iTameOffset;\r\n//\t\t}\r\n//#endif\r\n//#if TSTRING_WILDW\r\n//\t\telse if (pszMatch[iWildOffset] == _hash)\r\n//\t\t{\r\n//\t\t\t++iWildOffset;\r\n//\t\t\twhile (pszString[iTameOffset] && (pszString[iTameOffset] != _space || pszString[iTameOffset] != _tab || pszString[iTameOffset] != _n || pszString[iTameOffset] != _r))\r\n//\t\t\t\t++iTameOffset;\r\n//\t\t}\r\n//#endif\r\n//\t\t//else if (pszMatch[iWildOffset] == TEXT('?') || _toupper(pszMatch[iWildOffset]) == _toupper(pszString[iTameOffset]))\r\n//\t\telse if (pszMatch[iWildOffset] == _question || details::CompareChar(pszMatch[iWildOffset], pszString[iTameOffset], bCase))\r\n//\t\t{\r\n//\t\t\t++iWildOffset;\r\n//\t\t\t++iTameOffset;\r\n//\t\t}\r\n//\t\telse if (StringPlaceholder == 0)\r\n//\t\t\treturn false;\r\n//\t\telse\r\n//\t\t{\r\n//\t\t\tiWildOffset = MatchPlaceholder;\r\n//\t\t\tiTameOffset = StringPlaceholder++;\r\n//\t\t}\r\n//\t}\r\n//\r\n//\twhile (pszMatch[iWildOffset] == _star)\r\n//\t\t++iWildOffset;\r\n//\r\n//\treturn !pszMatch[iWildOffset];\r\n//}\r\n\r\n/// <summary>\r\n/// Internal wildcard match function.\r\n/// </summary>\r\n/// <typeparam name=\"_Wild\"></typeparam>\r\n/// <typeparam name=\"TameString\"></typeparam>\r\n/// <typeparam name=\"WildString\"></typeparam>\r\n/// <param name=\"pszString\"></param>\r\n/// <param name=\"pszMatch\"></param>\r\n/// <param name=\"bCase\"></param>\r\n/// <returns></returns>\r\ntemplate <class _Wild, typename TameString, typename WildString>\r\nGSL_SUPPRESS(bounds.4) bool _ts_InnerWildcardMatch(const TameString& pszString, const WildString& pszMatch, const bool bCase) noexcept(std::is_nothrow_move_assignable_v<WildString>)\r\n{\r\n\tptrdiff_t MatchPlaceholder = 0;\r\n\tptrdiff_t StringPlaceholder = 0;\r\n\tptrdiff_t iWildOffset = 0;\r\n\tptrdiff_t iTameOffset = 0;\r\n\r\n\tconstexpr _Wild _zero{};\r\n\tconstexpr _Wild _star = static_cast<_Wild>('*');\r\n\tconstexpr _Wild _question = static_cast<_Wild>('?');\r\n\tconstexpr _Wild _tilda = static_cast<_Wild>('~');\r\n\tconstexpr _Wild _space = static_cast<_Wild>(' ');\r\n\tconstexpr _Wild _power = static_cast<_Wild>('^');\r\n\tconstexpr _Wild _hash = static_cast<_Wild>('#');\r\n\tconstexpr _Wild _slash = static_cast<_Wild>('\\\\');\r\n\tconstexpr _Wild _tab = static_cast<_Wild>('\\t');\r\n\tconstexpr _Wild _n = static_cast<_Wild>('\\n');\r\n\tconstexpr _Wild _r = static_cast<_Wild>('\\r');\r\n\r\n\twhile (pszString[iTameOffset])\r\n\t{\r\n\t\tif (pszMatch[iWildOffset] == _star)\r\n\t\t{\r\n\t\t\tif (pszMatch[++iWildOffset] == _zero)\r\n\t\t\t\treturn true;\r\n\t\t\tMatchPlaceholder = iWildOffset;\r\n\t\t\tStringPlaceholder = iTameOffset + 1;\r\n\t\t}\r\n#if TSTRING_WILDT\r\n\t\telse if (pszMatch[iWildOffset] == _tilda && pszString[iTameOffset] == _space)\r\n\t\t{\r\n\t\t\t++iWildOffset;\r\n\t\t\twhile (pszString[iTameOffset] == _space)\r\n\t\t\t\t++iTameOffset;\r\n\t\t}\r\n#endif\r\n#if TSTRING_WILDA\r\n\t\telse if (pszMatch[iWildOffset] == _power)\r\n\t\t{\r\n\t\t\t++iWildOffset;\r\n\t\t\tif (details::CompareChar(pszMatch[iWildOffset], pszString[iTameOffset], bCase))\r\n\t\t\t\t++iTameOffset;\r\n\t\t\t++iWildOffset;\r\n\t\t}\r\n#endif\r\n#if TSTRING_WILDE\r\n\t\telse if (pszMatch[iWildOffset] == _slash)\r\n\t\t{\r\n\t\t\t// any character following a '\\' is taken as a literal character.\r\n\t\t\t++iWildOffset;\r\n\t\t\tif (!details::CompareChar(pszMatch[iWildOffset], pszString[iTameOffset], bCase))\r\n\t\t\t\treturn false;\r\n\t\t\t++iTameOffset;\r\n\t\t}\r\n#endif\r\n#if TSTRING_WILDW\r\n\t\telse if (pszMatch[iWildOffset] == _hash)\r\n\t\t{\r\n\t\t\t++iWildOffset;\r\n\t\t\twhile (pszString[iTameOffset] && (pszString[iTameOffset] != _space || pszString[iTameOffset] != _tab || pszString[iTameOffset] != _n || pszString[iTameOffset] != _r))\r\n\t\t\t\t++iTameOffset;\r\n\t\t}\r\n#endif\r\n\t\t//else if (pszMatch[iWildOffset] == _question || _toupper(pszMatch[iWildOffset]) == _toupper(pszString[iTameOffset]))\r\n\t\telse if (pszMatch[iWildOffset] == _question || details::CompareChar(pszMatch[iWildOffset], pszString[iTameOffset], bCase))\r\n\t\t{\r\n\t\t\t++iWildOffset;\r\n\t\t\t++iTameOffset;\r\n\t\t}\r\n\t\telse if (StringPlaceholder == 0)\r\n\t\t\treturn false;\r\n\t\telse\r\n\t\t{\r\n\t\t\tiWildOffset = MatchPlaceholder;\r\n\t\t\tiTameOffset = StringPlaceholder++;\r\n\t\t}\r\n\t}\r\n\r\n\twhile (pszMatch[iWildOffset] == _star)\r\n\t\t++iWildOffset;\r\n\r\n\treturn !pszMatch[iWildOffset];\r\n}\r\n\r\n/// <summary>\r\n/// Wildcard match\r\n/// </summary>\r\n/// <typeparam name=\"TameString\"></typeparam>\r\n/// <typeparam name=\"WildString\"></typeparam>\r\n/// <param name=\"pszString\">- string to search</param>\r\n/// <param name=\"pszMatch\">- the wildcard string to search for.</param>\r\n/// <param name=\"bCase\">- does case matter</param>\r\n/// <returns>did match succeed true/false</returns>\r\ntemplate <typename TameString, typename WildString>\r\nGSL_SUPPRESS(bounds) bool _ts_WildcardMatch(const TameString& pszString, const WildString& pszMatch, const bool bCase = false) noexcept(std::is_nothrow_move_assignable_v<WildString>)\r\n{\r\n\tif (_ts_isEmpty(pszMatch) || _ts_isEmpty(pszString))\r\n\t\treturn false;\r\n\r\n\tif constexpr (details::is_pod_v<std::remove_pointer_t<std::remove_cv_t<std::remove_all_extents_t<WildString>>>>)\r\n\t\treturn _ts_InnerWildcardMatch<std::remove_pointer_t<std::remove_cv_t<std::remove_all_extents_t<WildString>>>>(pszString, pszMatch, bCase);\r\n\telse\r\n\t\treturn _ts_InnerWildcardMatch<std::remove_pointer_t<std::remove_cv_t<std::remove_all_extents_t<WildString::value_type>>>>(pszString, pszMatch, bCase);\r\n}\r\n\r\ntemplate <typename T> T* _ts_AddMem(std::vector<std::shared_ptr<std::vector<char>>>& mem, std::size_t sz = sizeof(T))\r\n{\r\n\tstd::shared_ptr<std::vector<char>> x = std::make_shared<std::vector<char>>();\r\n\tx->resize(sz);\r\n\tmem.push_back(x);\r\n\tT* d = (T*)mem[mem.size() - 1].get()->data();\r\n\treturn d;\r\n}\r\n\r\n/// <summary>\r\n/// Sort a vector\r\n/// </summary>\r\n/// <typeparam name=\"T\"></typeparam>\r\n/// <param name=\"str\">- The vector to sort.</param>\r\n/// <returns>A sorted copy of the input.</returns>\r\ntemplate <class T>\r\nstd::vector<T> _ts_SortString(const std::vector<T>& str)\r\n{\r\n\tstd::vector<T> out(str);\r\n\r\n\tstd::sort(out.begin(), out.end(), std::less<T>);\r\n\r\n\treturn out;\r\n}\r\n", "meta": {"hexsha": "f214a8321168ab3ef5a3babd767986f99d63f565", "size": 48594, "ext": "h", "lang": "C", "max_stars_repo_path": "Classes/tstring/string_support.h", "max_stars_repo_name": "twig/dcxdll", "max_stars_repo_head_hexsha": "cd0cb308b76daf0be614025d71670580007a0d78", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2015-02-21T05:41:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-26T00:48:31.000Z", "max_issues_repo_path": "Classes/tstring/string_support.h", "max_issues_repo_name": "twig/dcxdll", "max_issues_repo_head_hexsha": "cd0cb308b76daf0be614025d71670580007a0d78", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 68.0, "max_issues_repo_issues_event_min_datetime": "2015-04-06T16:23:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T17:33:50.000Z", "max_forks_repo_path": "Classes/tstring/string_support.h", "max_forks_repo_name": "twig/dcxdll", "max_forks_repo_head_hexsha": "cd0cb308b76daf0be614025d71670580007a0d78", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-04-01T09:39:33.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-04T23:53:29.000Z", "avg_line_length": 29.2911392405, "max_line_length": 240, "alphanum_fraction": 0.6503683582, "num_tokens": 14064, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.173288223007179, "lm_q2_score": 0.05261895854749497, "lm_q1q2_score": 0.009118245823183817}}
{"text": "#ifndef _PYGSL_SOLVER_H_\n#define _PYGSL_SOLVER_H_ 1\n#include <pygsl/intern.h>\n#include <pygsl/block_helpers.h>\n/* Not directly needed here, but provides a lot of convienience functions */\n#include <pygsl/error_helpers.h>\n#include <gsl/gsl_math.h>\n#include <setjmp.h>\n/*\n * Many functions are \"just\" accessor methods. These different methods are\n * listed here.\n *\n * Convention: they all end with \"m_t\" short for method type. This emphasises\n * that this type is pointer to a method.\n */ \ntypedef int (*int_m_t)(void *);\ntypedef size_t (*size_t_m_t)(void *);\ntypedef void (*void_m_t)(void *);\ntypedef void *(*void_a_t)(const void *);\ntypedef void *(*void_an_t)(const void *, size_t n);\ntypedef void *(*void_anp_t)(const void *, size_t n, size_t p);\ntypedef const char * (*name_m_t)(void *);\ntypedef double  (*double_m_t)(void *);\ntypedef gsl_vector *(*ret_vec)(void *);\ntypedef int (*set_m_t)(void *, void *, const gsl_vector *);\ntypedef int (*set_m_d_t) (void *, gsl_function *, double);\ntypedef int (*set_m_ddd_t) (void *, gsl_function *, double, double, double);\ntypedef int (*int_f_vd_t)(const gsl_vector *, double);\ntypedef int (*int_f_vvdd_t)(const gsl_vector *, const gsl_vector *, double, double);\n\nstruct _PyGSLSolverObject;\n\n/*\n * GSL Methods which are implemented as C functions. The specifiy pointer to\n * the solver struct are passed as (void *) pointers.\n */\nstruct _GSLMethods{\n     /* Method to be called to free the GSL solver */\n     void_m_t free;\n     /*\n      * Some solvers provide a restart method. If not available set it to NULL.\n      */\n     void_m_t restart;\n     /* returns a string with the name of the solver */\n     name_m_t name;\n     /* takes one more step towards the solution */\n     int_m_t iterate;\n};\n\nstruct _SolverStatic{\n     struct _GSLMethods cmethods;\n     /* How many callbacks will be used? */\n     int n_cbs;\n     /* Additional methods not provided by the basis solver. */\n     PyMethodDef *pymethods;\n     /* Describes the type of the solver. e. g. F-Minimizer */\n     const char * type_name;\n};\n\nstruct pygsl_array_cache{\n     double * data;\n     PyArrayObject * ref;\n};\n#define PyGSL_SOLVER_NCBS_MAX 4\n#define PyGSL_SOLVER_PB_ND_MAX 2\n#define PyGSL_SOLVER_N_ARRAYS 10\n\nstruct _PyGSLSolverObject{\n     PyObject_HEAD\n     /* \n      *\tSome solvers do not propagate errors. Here I use longjmp if an error \n      * is raised by the evaluator.\n      */\n     jmp_buf buffer;\n     /*\n      * Array generation is a vital part of the callback process. To increase\n      * the calculation speed, I want to store them here, thus I can reuse them\n      * if not stored by the user for later evaluation.\n      */\n     struct pygsl_array_cache *cache;\n     /*\n      * The Python callback methods.\n      */\n     PyObject* cbs[PyGSL_SOLVER_NCBS_MAX];\n     /*\n      * Additional arguments passed to the callbacks\n      */\n     PyObject* args;\n     /*\n      * The solver itself.\n      */     \n     void * solver;\n     /*\n      * The space needed to store the variables for the C functions ....\n      */\n     void * c_sys;\n     /*\n      * The dimensionality of the problem. Typically one or two numbers ...\n      */\n     int problem_dimensions[PyGSL_SOLVER_PB_ND_MAX];\n     /*\n      * The methods of the solver.\n      */\n     const struct _SolverStatic* mstatic;\n     /* before one can iterate the solver the method set() must be called!*/\n     int set_called;\n     /* Used as a flag if the jmp_buf is set */\n     int isset; \n};\ntypedef struct _PyGSLSolverObject PyGSL_solver;\n\n\ntypedef struct{\n     const void * type;\n     void* alloc;\n     const struct _SolverStatic* mstatic;\n} solver_alloc_struct;\n\n\n\n#ifndef _PyGSL_SOLVER_API_MODULE\n#define PyGSL_SOLVER_API_EXTERN extern\n#else \n#define PyGSL_SOLVER_API_EXTERN static\n#endif \n\n/*\n *  Initalises a solver\n *\n *  The internal structure is set up and the \n *  nd: number of dimensions\n *     0 ... zero dimensional e.g. minimize, root\n *     1 ... one  dimensional e.g. multimin\n *     2 ... two  dimensional e.g. multifit_nlin\n *    \n *     3 ... only initalise the structure\n * \n */\nPyGSL_SOLVER_API_EXTERN  PyObject *\nPyGSL_solver_dn_init(PyObject *self, PyObject *args, const solver_alloc_struct * alloc, int nd);\n\n/*\n * Accessor methods.\n *\n * These methods allow to access parameters of the C structure using the access\n * methods _m_t func\n */\nPyGSL_SOLVER_API_EXTERN PyObject* \nPyGSL_solver_ret_double(PyGSL_solver *self, PyObject *args, double_m_t func);\n\nPyGSL_SOLVER_API_EXTERN PyObject* \nPyGSL_solver_ret_int(PyGSL_solver *self, PyObject *args, int_m_t func);\n\nPyGSL_SOLVER_API_EXTERN PyObject* \nPyGSL_solver_ret_size_t(PyGSL_solver *self, PyObject *args, size_t_m_t func);\n\nPyGSL_SOLVER_API_EXTERN PyObject* \nPyGSL_solver_ret_vec(PyGSL_solver *self, PyObject *args,  ret_vec func);\n\n/*\n * evaluates a C function taking an vector and a double as input and returning a status.\n */\n\n#define PyGSL_CALLABLE_CHECK(ob, name) \\\n(PyCallable_Check(ob) ? GSL_SUCCESS : PyGSL_Callable_Check(ob, name))\n\nPyGSL_SOLVER_API_EXTERN int\nPyGSL_Callable_Check(PyObject *f, const char * myname);\n\nPyGSL_SOLVER_API_EXTERN int\nPyGSL_function_wrap_On_O(const gsl_vector * x, PyObject *callback,\n\t\t\t PyObject *arguments, double *result1,\n\t\t\t gsl_vector *result2, int n, const char * c_func_name);\n\nPyGSL_SOLVER_API_EXTERN int\nPyGSL_function_wrap_OnOn_On(const gsl_vector *x, const gsl_vector *v, gsl_vector *hv, PyObject *callback,\n\t\t\t    PyObject *arguments, int n, const char *c_func_name);\n\nPyGSL_SOLVER_API_EXTERN int\nPyGSL_function_wrap_Op_On_Opn(const gsl_vector *x, gsl_vector *f1, gsl_matrix *f2, PyObject *callback,\n\t\t\t    PyObject *arguments, int n, int p, const char *c_func_name);\n\nPyGSL_SOLVER_API_EXTERN int\nPyGSL_function_wrap_Op_On(const gsl_vector * x, gsl_vector *f, PyObject *callback, \n\t\t\t  PyObject * arguments, int n, int p, const char *c_func_name);\n\nPyGSL_SOLVER_API_EXTERN int\nPyGSL_function_wrap_Op_Opn(const gsl_vector * x, gsl_matrix *f, PyObject *callback,\n\t\t\t   PyObject *arguments, int n, int p, const char * c_func_name);\n\n/*\n * evaluates a C function taking an vector and a double as input and returning a status.\n */\nPyGSL_SOLVER_API_EXTERN PyObject*\nPyGSL_solver_vd_i(PyObject * self, PyObject *args, int_f_vd_t func);\n\nPyGSL_SOLVER_API_EXTERN PyObject *\nPyGSL_solver_vvdd_i(PyObject * self, PyObject * args, int_f_vvdd_t func);\n\nstruct pygsl_solver_n_set{\n     int is_fdf;\n     void *c_sys;\n     set_m_t set;\n};\n\nPyGSL_SOLVER_API_EXTERN PyObject *\nPyGSL_solver_n_set(PyGSL_solver *self, PyObject *pyargs, PyObject *kw, \n\t\t   const struct pygsl_solver_n_set * info);\n\n\n/*\n *\n */\nPyGSL_SOLVER_API_EXTERN int\nPyGSL_solver_func_set(PyGSL_solver *self, PyObject *args, PyObject *f,\n\t\t       PyObject *df, PyObject *fdf);\n\nPyGSL_SOLVER_API_EXTERN PyObject* \nPyGSL_solver_set_f(PyGSL_solver *self, PyObject *pyargs, PyObject *kw, \n\t\t   void *fptr, int isfdf); \n\n\n#define _GET(name, cast, func) \\\nPyObject * PyGSL_ ## name(PyGSL_solver *self, PyObject *args) \\\n{ \\\n    return PyGSL_solver_ ## func(self, args, (cast) gsl_ ## name); \\\n} \n\n#define GETDOUBLE(name) _GET(name, double_m_t, ret_double)\n#define GETSIZET(name)  _GET(name, size_t_m_t, ret_size_t)\n#define GETINT(name)    _GET(name, int_m_t,    ret_int)\n#define GETVEC(name)    _GET(name, ret_vec,    ret_vec)\n\n\n/*\n * Get or set a double ....\n */\nenum PyGSL_GETSET_typemode {\n     PyGSL_MODE_DOUBLE = 0,\n     PyGSL_MODE_INT,\n     PyGSL_MODE_SIZE_T\n};\n\nPyGSL_SOLVER_API_EXTERN PyObject *\nPyGSL_solver_GetSet(PyObject *self, PyObject *args, void * address, enum PyGSL_GETSET_typemode mode);\n\n#ifndef _PyGSL_SOLVER_API_MODULE\n\n#define PyGSL_function_wrap_Op_On \\\n(* (int (*)(const gsl_vector *, gsl_vector *, PyObject *, PyObject *, int, int, const char *))\\\n PyGSL_API[PyGSL_function_wrap_Op_On_NUM])\n\n#define PyGSL_function_wrap_On_O \\\n(* (int (*)(const gsl_vector *, PyObject *, PyObject *, double *, gsl_vector *, int, const char *))\\\n PyGSL_API[PyGSL_function_wrap_On_O_NUM])\n\n#define PyGSL_function_wrap_OnOn_On \\\n(* (int (*)(const gsl_vector *, const gsl_vector *, gsl_vector *, PyObject *,  PyObject *,int, const char *))\\\n PyGSL_API[PyGSL_function_wrap_OnOn_On_NUM])\n\n#define PyGSL_function_wrap_Op_On_Opn \\\n(* (int (*)(const gsl_vector *, gsl_vector *, gsl_matrix *, PyObject *, PyObject *, int, int, const char *))\\\n PyGSL_API[PyGSL_function_wrap_Op_On_Opn_NUM])\n\n#define PyGSL_function_wrap_Op_Opn \\\n(* (int (*)(const gsl_vector *, gsl_matrix *, PyObject *, PyObject *, int, int, const char *))\\\n PyGSL_API[PyGSL_function_wrap_Op_Opn_NUM])\n\n\n#define PyGSL_solver_ret_int \\\n(*(PyObject *  (*) (PyGSL_solver *, PyObject *, int_m_t func))    PyGSL_API[PyGSL_solver_ret_int_NUM])\n\n#define PyGSL_solver_ret_double \\\n(*(PyObject *  (*) (PyGSL_solver *, PyObject *, double_m_t func)) PyGSL_API[PyGSL_solver_ret_double_NUM])\n\n#define PyGSL_solver_ret_size_t \\\n(*(PyObject *  (*) (PyGSL_solver *, PyObject *, size_t_m_t func)) PyGSL_API[PyGSL_solver_ret_size_t_NUM])\n\n#define PyGSL_solver_ret_vec \\\n(*(PyObject *  (*) (PyGSL_solver *, PyObject *, ret_vec func))    PyGSL_API[PyGSL_solver_ret_vec_NUM])    \n\n#define  PyGSL_solver_dn_init \\\n(*(PyObject * (*)(PyObject *, PyObject *, const solver_alloc_struct *, int))PyGSL_API[PyGSL_solver_dn_init_NUM])  \n\n#define PyGSL_Callable_Check \\\n(*(int (*)(PyObject *, const char *)) PyGSL_API[PyGSL_Callable_Check_NUM])\n\n#define PyGSL_solver_vd_i \\\n(*(PyObject * (*) (PyObject *, PyObject *, int_f_vd_t)) PyGSL_API[PyGSL_solver_vd_i_NUM])\n\n#define PyGSL_solver_vvdd_i \\\n(*(PyObject * (*) (PyObject *, PyObject *, int_f_vvdd_t)) PyGSL_API[PyGSL_solver_vvdd_i_NUM])\n\n#define PyGSL_solver_func_set \\\n(*(int (*)(PyGSL_solver *, PyObject *, PyObject *, PyObject *, PyObject *)) PyGSL_API[PyGSL_solver_func_set_NUM])\n\n#define PyGSL_solver_n_set \\\n(*(PyObject * (*)(PyGSL_solver *, PyObject *, PyObject *,  const struct pygsl_solver_n_set *)) PyGSL_API[PyGSL_solver_n_set_NUM])\n\n#define PyGSL_solver_set_f \\\n(* (PyObject * (*)(PyGSL_solver *, PyObject *, PyObject *, void *, int )) PyGSL_API[PyGSL_solver_set_f_NUM])\n\n#define PyGSL_solver_GetSet \\\n(* (PyObject * (*) (PyObject *, PyObject *, void *, enum PyGSL_GETSET_typemode mode)) PyGSL_API[PyGSL_solver_getset_NUM])\n\n#define PyGSL_solver_check(ob) (((ob)->ob_type) == (PyGSL_API[PyGSL_solver_type_NUM]))\n\n#define import_pygsl_solver() \\\n{ \\\n   init_pygsl(); \\\n   if (PyImport_ImportModule(\"pygsl.testing.solver\") != NULL) { \\\n          ;\\\n   } else { \\\n        fprintf(stderr, \"failed to import pygsl solver!!\\n\"); \\\n   } \\\n}\n\n#else  /* _PyGSL_API_MODULE */\n#define PyGSL_solver_check(ob) ((ob)->ob_type == &PyGSL_solver_pytype)\n#endif /* _PyGSL_API_MODULE */\n\n\n#endif /* _PYGSL_SOLVER_H_ */\n", "meta": {"hexsha": "edde8c05aa020f5da5b0001295a9df1bb11095a1", "size": 10638, "ext": "h", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/Include/pygsl/solver.h", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/Include/pygsl/solver.h", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/Include/pygsl/solver.h", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 32.8333333333, "max_line_length": 129, "alphanum_fraction": 0.7150780222, "num_tokens": 2909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2751297238231752, "lm_q2_score": 0.03308598053388779, "lm_q1q2_score": 0.009102936686707497}}
{"text": "#include <mpi.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <gsl/gsl_math.h>\n\n#include \"allvars.h\"\n#include \"proto.h\"\n\n\n#ifdef PEDANTIC_MEMORY_HANDLER\n\n#define MAXBLOCKS 5000\n\n#ifdef PEDANTIC_MEMORY_CEILING\nstatic size_t TotBytes;\nstatic void *Base;\n#endif\n\nstatic unsigned long Nblocks;\nstatic double Highmark;\n\n\nstatic void **Table;\nstatic size_t *BlockSize;\n\nvoid mymalloc_init(void)\n{\n#ifdef PEDANTIC_MEMORY_CEILING\n  size_t n;\n#endif\n\n  BlockSize = (size_t *) malloc(MAXBLOCKS * sizeof(size_t));\n  Table = (void **) malloc(MAXBLOCKS * sizeof(void *));\n\n#ifdef PEDANTIC_MEMORY_CEILING\n  n = PEDANTIC_MEMORY_CEILING * 1024.0 * 1024.0;\n\n  if(!(Base = malloc(n)))\n    {\n      printf(\"Failed to allocate memory for `Base' (%d Mbytes).\\n\", (int) PEDANTIC_MEMORY_CEILING);\n      endrun(122);\n    }\n\n  TotBytes = FreeBytes = n;\n#endif\n\n  AllocatedBytes = 0;\n  Nblocks = 0;\n  Highmark = 0;\n}\n\n\n\nvoid *mymalloc(size_t n)\n{\n  if((n % 8) > 0)\n    n = (n / 8 + 1) * 8;\n\n  if(n < 8)\n    n = 8;\n\n  if(Nblocks >= MAXBLOCKS)\n    {\n      printf(\"Task=%d: No blocks left in mymalloc().\\n\", ThisTask);\n      endrun(813);\n    }\n\n#ifdef PEDANTIC_MEMORY_CEILING\n  if(n > FreeBytes)\n    {\n      printf(\"Task=%d: Not enough memory in mymalloc(n=%g MB).  FreeBytes=%g MB\\n\",\n\t     ThisTask, n / (1024.0 * 1024.0), FreeBytes / (1024.0 * 1024.0));\n      endrun(812);\n    }\n  Table[Nblocks] = Base + (TotBytes - FreeBytes);\n  FreeBytes -= n;\n#else\n  Table[Nblocks] = malloc(n);\n  if(!(Table[Nblocks]))\n    {\n      printf(\"failed to allocate %g MB of memory. (presently allocated=%g MB)\\n\",\n\t     n / (1024.0 * 1024.0), AllocatedBytes / (1024.0 * 1024.0));\n      endrun(18);\n    }\n#endif\n\n  AllocatedBytes += n;\n  BlockSize[Nblocks] = n;\n\n  Nblocks += 1;\n\n  /*\n     if(AllocatedBytes / (1024.0 * 1024.0) > Highmark)\n     {\n     Highmark = AllocatedBytes / (1024.0 * 1024.0);\n     printf(\"Task=%d:   new highmark=%g MB\\n\",\n     ThisTask, Highmark);\n     fflush(stdout);\n     }\n   */\n\n  return Table[Nblocks - 1];\n}\n\n\nvoid *mymalloc_msg(size_t n, char *message)\n{\n  if((n % 8) > 0)\n    n = (n / 8 + 1) * 8;\n\n  if(n < 8)\n    n = 8;\n\n  if(Nblocks >= MAXBLOCKS)\n    {\n      printf(\"Task=%d: No blocks left in mymalloc().\\n\", ThisTask);\n      endrun(813);\n    }\n\n#ifdef PEDANTIC_MEMORY_CEILING\n  if(n > FreeBytes)\n    {\n      printf\n\t(\"Task=%d: Not enough memory in for allocating (n=%g MB) for block='%s'.  FreeBytes=%g MB  AllocatedBytes=%g MB.\\n\",\n\t ThisTask, n / (1024.0 * 1024.0), message, FreeBytes / (1024.0 * 1024.0),\n\t AllocatedBytes / (1024.0 * 1024.0));\n      endrun(812);\n    }\n  Table[Nblocks] = Base + (TotBytes - FreeBytes);\n  FreeBytes -= n;\n#else\n  Table[Nblocks] = malloc(n);\n  if(!(Table[Nblocks]))\n    {\n      printf(\"failed to allocate %g MB of memory for block='%s'. (presently allocated=%g MB)\\n\",\n\t     n / (1024.0 * 1024.0), message, AllocatedBytes / (1024.0 * 1024.0));\n      endrun(18);\n    }\n#endif\n\n  AllocatedBytes += n;\n  BlockSize[Nblocks] = n;\n\n  Nblocks += 1;\n\n  return Table[Nblocks - 1];\n}\n\n\n\n\nvoid myfree(void *p)\n{\n  if(Nblocks == 0)\n    endrun(76878);\n\n  if(p != Table[Nblocks - 1])\n    {\n      printf(\"Task=%d: Wrong call of myfree() - not the last allocated block!\\n\", ThisTask);\n      fflush(stdout);\n      endrun(814);\n    }\n\n  Nblocks -= 1;\n  AllocatedBytes -= BlockSize[Nblocks];\n#ifdef PEDANTIC_MEMORY_CEILING\n  FreeBytes += BlockSize[Nblocks];\n#else\n  free(p);\n#endif\n}\n\nvoid myfree_msg(void *p, char *msg)\n{\n  if(Nblocks == 0)\n    endrun(76878);\n\n  if(p != Table[Nblocks - 1])\n    {\n      printf(\"Task=%d: Wrong call of myfree() - '%s' not the last allocated block!\\n\", ThisTask, msg);\n      fflush(stdout);\n      endrun(8141);\n    }\n\n  Nblocks -= 1;\n  AllocatedBytes -= BlockSize[Nblocks];\n#ifdef PEDANTIC_MEMORY_CEILING\n  FreeBytes += BlockSize[Nblocks];\n#else\n  free(p);\n#endif\n}\n\n\n\nvoid *myrealloc(void *p, size_t n)\n{\n  if((n % 8) > 0)\n    n = (n / 8 + 1) * 8;\n\n  if(n < 8)\n    n = 8;\n\n  if(Nblocks == 0)\n    endrun(76879);\n\n  if(p != Table[Nblocks - 1])\n    {\n      printf(\"Task=%d: Wrong call of myrealloc() - not the last allocated block!\\n\", ThisTask);\n      fflush(stdout);\n      endrun(815);\n    }\n\n  AllocatedBytes -= BlockSize[Nblocks - 1];\n#ifdef PEDANTIC_MEMORY_CEILING\n  FreeBytes += BlockSize[Nblocks - 1];\n#endif\n\n\n#ifdef PEDANTIC_MEMORY_CEILING\n  if(n > FreeBytes)\n    {\n      printf(\"Task=%d: Not enough memory in myremalloc(n=%g MB). previous=%g FreeBytes=%g MB\\n\",\n\t     ThisTask, n / (1024.0 * 1024.0), BlockSize[Nblocks - 1] / (1024.0 * 1024.0),\n\t     FreeBytes / (1024.0 * 1024.0));\n      endrun(812);\n    }\n  Table[Nblocks - 1] = Base + (TotBytes - FreeBytes);\n  FreeBytes -= n;\n#else\n  Table[Nblocks - 1] = realloc(Table[Nblocks - 1], n);\n  if(!(Table[Nblocks - 1]))\n    {\n      printf(\"failed to reallocate %g MB of memory. previous=%g FreeBytes=%g MB\\n\",\n\t     n / (1024.0 * 1024.0), BlockSize[Nblocks - 1] / (1024.0 * 1024.0),\n\t     FreeBytes / (1024.0 * 1024.0));\n      endrun(18123);\n    }\n#endif\n\n  AllocatedBytes += n;\n  BlockSize[Nblocks - 1] = n;\n\n  return Table[Nblocks - 1];\n}\n\n\n\n#else\n\nvoid mymalloc_init(void)\n{\n  AllocatedBytes = 0;\n}\n\nvoid *mymalloc(size_t n)\n{\n  void *ptr;\n\n  if(n < 8)\n    n = 8;\n\n  ptr = malloc(n);\n\n  if(!(ptr))\n    {\n      printf(\"failed to allocate %g MB of memory.\\n\", n / (1024.0 * 1024.0));\n      endrun(14);\n    }\n\n  return ptr;\n}\n\n\nvoid *mymalloc_msg(size_t n, char *message)\n{\n  void *ptr;\n\n  if(n < 8)\n    n = 8;\n\n  ptr = malloc(n);\n\n  if(!(ptr))\n    {\n      printf(\"failed to allocate %g MB of memory when trying to allocate '%s'.\\n\",\n\t     n / (1024.0 * 1024.0), message);\n      endrun(14);\n    }\n\n  return ptr;\n}\n\n\n\nvoid *myrealloc(void *p, size_t n)\n{\n  void *ptr;\n\n  ptr = realloc(p, n);\n\n  if(!(ptr))\n    {\n      printf(\"failed to re-allocate %g MB of memory.\\n\", n / (1024.0 * 1024.0));\n      endrun(15);\n    }\n\n  return ptr;\n}\n\nvoid myfree(void *p)\n{\n  free(p);\n}\n\nvoid myfree_msg(void *p, char *msg)\n{\n  free(p);\n}\n\n\n\n#endif\n", "meta": {"hexsha": "ece3f4f38ac49cf7e2deb79d2467b40b99003983", "size": 5966, "ext": "c", "lang": "C", "max_stars_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/mymalloc.c", "max_stars_repo_name": "egpbos/egp", "max_stars_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/mymalloc.c", "max_issues_repo_name": "egpbos/egp", "max_issues_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/mymalloc.c", "max_forks_repo_name": "egpbos/egp", "max_forks_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.3006134969, "max_line_length": 117, "alphanum_fraction": 0.5883338921, "num_tokens": 1997, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2877678157610531, "lm_q2_score": 0.03161877012026414, "lm_q1q2_score": 0.009098864414559262}}
{"text": "#pragma once\n\n#include <functional>\n#include <gsl/gsl>\n#include <memory>\n#include <vector>\n#include \"halley/text/halleystring.h\"\n#include \"halley/maths/vector2.h\"\n#include \"halley/maths/vector3.h\"\n#include <memory>\n\nnamespace Halley\n{\n\tclass AudioPosition;\n\tclass AudioClip;\n\tclass AudioEvent;\n\tclass IAudioClip;\n\tclass AudioEmitterBehaviour;\n\n    namespace AudioConfig {\n        constexpr int sampleRate = 48000;\n\t\tconstexpr int maxChannels = 8;\n        using SampleFormat = float;\n    }\n\n\tclass AudioDevice\n\t{\n\tpublic:\n\t\tvirtual ~AudioDevice() {}\n\t\tvirtual String getName() const = 0;\n\t};\n\n\tstruct alignas(64) AudioSamplePack\n\t{\n\t\tconstexpr static int NumSamples = 16;\n\t\tstd::array<AudioConfig::SampleFormat, NumSamples> samples; // AVX-512 friendly\n\t};\n\n\tenum class AudioSampleFormat\n\t{\n\t\tUndefined,\n\t\tInt16,\n\t\tInt32,\n\t\tFloat\n\t};\n\n\ttemplate <>\n\tstruct EnumNames<AudioSampleFormat> {\n\t\tconstexpr std::array<const char*, 4> operator()() const {\n\t\t\treturn{{\n\t\t\t\t\"undefined\",\n\t\t\t\t\"int16\",\n\t\t\t\t\"int32\",\n\t\t\t\t\"float\"\n\t\t\t}};\n\t\t}\n\t};\n\n\tclass AudioSpec\n\t{\n\tpublic:\n\t\tint sampleRate;\n\t\tint numChannels;\n\t\tint bufferSize;\n\t\tAudioSampleFormat format;\n\n\t\tAudioSpec() {}\n\t\tAudioSpec(int sampleRate, int numChannels, int bufferSize, AudioSampleFormat format)\n\t\t\t: sampleRate(sampleRate)\n\t\t\t, numChannels(numChannels)\n\t\t\t, bufferSize(bufferSize)\n\t\t\t, format(format)\n\t\t{}\n\t};\n\n\tclass AudioListenerData\n\t{\n\tpublic:\n\t\tVector3f position;\n\n\t\tAudioListenerData() {}\n\t\tAudioListenerData(Vector3f position)\n\t\t\t: position(position)\n\t\t{}\n\t};\n\n\tusing AudioCallback = std::function<void()>;\n\n\tclass AudioOutputAPI\n\t{\n\tpublic:\n\t\tvirtual ~AudioOutputAPI() {}\n\n\t\tvirtual Vector<std::unique_ptr<const AudioDevice>> getAudioDevices() = 0;\n\t\tvirtual AudioSpec openAudioDevice(const AudioSpec& requestedFormat, const AudioDevice* device = nullptr, AudioCallback prepareAudioCallback = AudioCallback()) = 0;\n\t\tvirtual void closeAudioDevice() = 0;\n\n\t\tvirtual void startPlayback() = 0;\n\t\tvirtual void stopPlayback() = 0;\n\n\t\tvirtual void queueAudio(gsl::span<const float> data) = 0;\n\t\tvirtual bool needsMoreAudio() = 0;\n\n\t\tvirtual bool needsAudioThread() const = 0;\n\t};\n\n\tclass IAudioHandle\n\t{\n\tpublic:\n\t\tvirtual ~IAudioHandle() {}\n\n\t\tvirtual void setGain(float gain) = 0;\n\t\tvirtual void setVolume(float volume) = 0;\n\t\tvirtual void setPosition(Vector2f pos) = 0;\n\t\tvirtual void setPan(float pan) = 0;\n\n\t\tvirtual void stop(float fadeTime = 0.0f) = 0;\n\t\tvirtual bool isPlaying() const = 0;\n\t\tvirtual void setBehaviour(std::unique_ptr<AudioEmitterBehaviour> behaviour) = 0;\n\t};\n\tusing AudioHandle = std::shared_ptr<IAudioHandle>;\n\n\tclass AudioAPI\n\t{\n\tpublic:\n\t\tvirtual ~AudioAPI() {}\n\n\t\tvirtual Vector<std::unique_ptr<const AudioDevice>> getAudioDevices() = 0;\n\t\tvirtual void startPlayback(int deviceNumber = 0) = 0;\n\t\tvirtual void stopPlayback() = 0;\n\t\tvirtual void pausePlayback() = 0;\n\t\tvirtual void resumePlayback() = 0;\n\n\t\tvirtual AudioHandle postEvent(const String& name, AudioPosition position) = 0;\n\n\t\tvirtual AudioHandle play(std::shared_ptr<const IAudioClip> clip, AudioPosition position, float volume = 1.0f, bool loop = false) = 0;\n\t\tvirtual AudioHandle playMusic(const String& eventName, int track = 0) = 0;\n\t\tvirtual AudioHandle getMusic(int track = 0) = 0;\n\t\tvirtual void stopMusic(int track = 0, float fadeOutTime = 0.0f) = 0;\n\t\tvirtual void stopAllMusic(float fadeOutTime = 0.0f) = 0;\n\n\t\tvirtual void setMasterVolume(float gain = 1.0f) = 0;\n\t\tvirtual void setGroupVolume(const String& groupName, float gain = 1.0f) = 0;\n\n\t\tvirtual void setListener(AudioListenerData listener) = 0;\n\t};\n}\n", "meta": {"hexsha": "037edc93256e83fd836e2f9c010580db656ca854", "size": 3564, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engine/core/include/halley/core/api/audio_api.h", "max_stars_repo_name": "Healthire/halley", "max_stars_repo_head_hexsha": "aa58e1abe22cda9e80637922721c03574779cd81", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/engine/core/include/halley/core/api/audio_api.h", "max_issues_repo_name": "Healthire/halley", "max_issues_repo_head_hexsha": "aa58e1abe22cda9e80637922721c03574779cd81", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engine/core/include/halley/core/api/audio_api.h", "max_forks_repo_name": "Healthire/halley", "max_forks_repo_head_hexsha": "aa58e1abe22cda9e80637922721c03574779cd81", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0810810811, "max_line_length": 165, "alphanum_fraction": 0.7121212121, "num_tokens": 972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35577487985229844, "lm_q2_score": 0.025565214804898748, "lm_q1q2_score": 0.009095461225611053}}
{"text": "#pragma once\n#include <gsl/span>\n#include \"halley/core/api/audio_api.h\"\n#include \"audio_buffer.h\"\n\nnamespace Halley\n{\n\tclass AudioMixer\n\t{\n\tpublic:\n\t\tstatic void mixAudio(AudioSamplesConst src, AudioSamples dst, float gainStart, float gainEnd);\n\t\tstatic void mixAudio(AudioMultiChannelSamplesConst src, AudioMultiChannelSamples dst, float gainStart, float gainEnd);\n\t\tstatic void mixAudio(AudioMultiChannelSamples src, AudioMultiChannelSamples dst, float gainStart, float gainEnd);\n\n\t\tstatic void interleaveChannels(AudioSamples dst, gsl::span<AudioBuffer*> srcs);\n\t\tstatic void concatenateChannels(AudioSamples dst, gsl::span<AudioBuffer*> srcs);\n\t\tstatic void compressRange(AudioSamples buffer);\n\n\t\tstatic void zero(AudioSamples dst);\n\t\tstatic void zero(AudioMultiChannelSamples dst, size_t nChannels = 8);\n\t\tstatic void zeroRange(AudioMultiChannelSamples dst, size_t nChannels, size_t start, size_t len = std::numeric_limits<size_t>::max());\n\t\tstatic void copy(AudioMultiChannelSamples dst, AudioMultiChannelSamples src, size_t nChannels = 8);\n\t\tstatic void copy(AudioSamples dst, AudioSamples src);\n\t\tstatic void copy(AudioSamples dst, AudioSamples src, float gainStart, float gainEnd);\n\t};\n}\n", "meta": {"hexsha": "d655e55ba5629a929f03d5c8065f05286ef274dd", "size": 1197, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engine/audio/src/audio_mixer.h", "max_stars_repo_name": "amrezzd/halley", "max_stars_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/engine/audio/src/audio_mixer.h", "max_issues_repo_name": "amrezzd/halley", "max_issues_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engine/audio/src/audio_mixer.h", "max_forks_repo_name": "amrezzd/halley", "max_forks_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.3333333333, "max_line_length": 135, "alphanum_fraction": 0.7961570593, "num_tokens": 276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33458944125318596, "lm_q2_score": 0.02716923380033906, "lm_q1q2_score": 0.00909053875653262}}
{"text": "/*\n *  read_parameters.h\n *  Spike\n *\tparse simple name/value pairs\n *\n *  Created by Ben Evans on 28/11/2008.\n *  Copyright 2008 University of Oxford. All rights reserved.\n *\n */\n\n#ifndef _READ_PARAMETERS_H\n#define _READ_PARAMETERS_H\n\n#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n#include <math.h>\n#include <ctype.h>\n#include <assert.h>\n\n#include \"globals.h\"\n#include \"parameters.h\"\n#include \"utils.h\"\n#include <gsl/gsl_sf_gamma.h> // N choose M funcion\n\n\n#define MAXLEN 256\n#define BUFFER 512 // Make larger for comments or break up comments\n#define VECBUFF 4\n\nchar * trim(char * string);\nint parse_string(PARAMS * params, char * string);\nint read_parameters(PARAMS * params, char * paramfile);\nint parseIntVector(char * string, int ** array);\nint parseFloatVector(char * string, float ** array);\nint printParameters(PARAMS * mp, char * paramfile);\nvoid printIntArray(FILE * fp, char * name, int * array, int len);\nvoid printFloatArray(FILE * fp, char * name, float * array, int len);\n\n#endif\n", "meta": {"hexsha": "ab17ba2a5bfacca0803f048a14379fd99afa9274", "size": 1009, "ext": "h", "lang": "C", "max_stars_repo_path": "source/read_parameters.h", "max_stars_repo_name": "wincle626/SpikingNeuralNetworkSimulatorXOS", "max_stars_repo_head_hexsha": "23f537bfa3605a5d1100b51eea7160d92d43be58", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/read_parameters.h", "max_issues_repo_name": "wincle626/SpikingNeuralNetworkSimulatorXOS", "max_issues_repo_head_hexsha": "23f537bfa3605a5d1100b51eea7160d92d43be58", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/read_parameters.h", "max_forks_repo_name": "wincle626/SpikingNeuralNetworkSimulatorXOS", "max_forks_repo_head_hexsha": "23f537bfa3605a5d1100b51eea7160d92d43be58", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6097560976, "max_line_length": 69, "alphanum_fraction": 0.7185332012, "num_tokens": 256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.25091279808829703, "lm_q2_score": 0.036220056645233006, "lm_q1q2_score": 0.009088075759772031}}
{"text": "\n#include <petsc.h>\n#include <bpetsc_impl.h>\n#include <assert.h>\n\n#define LEFT_SUBSPACE Full\n  #define RIGHT_SUBSPACE Full\n    #include <buildmat_template.h>\n  #undef RIGHT_SUBSPACE\n#undef LEFT_SUBSPACE\n\nint main(int argc, char const *argv[]) {\n\n  PetscErrorCode ierr;\n  PetscScalar* x_array;\n  PetscScalar* b_array;\n  shell_context ctx;\n  data_Full subspace_data;\n\n  /* test identity */\n  ctx.nmasks = 1;\n  ierr = PetscMalloc1(1, &(ctx.masks));CHKERRQ(ierr);\n  ierr = PetscMalloc1(2, &(ctx.mask_offsets));CHKERRQ(ierr);\n  ierr = PetscMalloc1(1, &(ctx.signs));CHKERRQ(ierr);\n  ierr = PetscMalloc1(1, &(ctx.real_coeffs));CHKERRQ(ierr);\n\n  ctx.masks[0] = 0;\n  ctx.mask_offsets[0] = 0;\n  ctx.mask_offsets[1] = 1;\n  ctx.signs[0] = 0;\n  ctx.real_coeffs[0] = 1.;\n\n  subspace_data.L = -1;\n  ctx.left_subspace_data = &subspace_data;\n  ctx.right_subspace_data = &subspace_data;\n\n  #define DIM 100\n\n  ierr = PetscMalloc1(DIM, &x_array);CHKERRQ(ierr);\n  ierr = PetscMalloc1(DIM, &b_array);CHKERRQ(ierr);\n\n  for (PetscInt i = 0; i < DIM; ++i) {\n    x_array[i] = i;\n    b_array[i] = 0;\n  }\n\n  MatMult_CPU_kernel_Full_Full(x_array, b_array, &ctx, 0, DIM, 0, DIM);\n\n  for (PetscInt i = 0; i < DIM; ++i) {\n    assert(b_array[i] == i);\n  }\n\n  ierr = PetscFree(x_array);CHKERRQ(ierr);\n  ierr = PetscFree(b_array);CHKERRQ(ierr);\n\n  #undef DIM\n\n  ierr = PetscFree(ctx.masks);CHKERRQ(ierr);\n  ierr = PetscFree(ctx.mask_offsets);CHKERRQ(ierr);\n  ierr = PetscFree(ctx.signs);CHKERRQ(ierr);\n  ierr = PetscFree(ctx.real_coeffs);CHKERRQ(ierr);\n\n  return 0;\n}\n", "meta": {"hexsha": "a7a7f42ea5a668be900138ffe697fa1a3134ba09", "size": 1533, "ext": "c", "lang": "C", "max_stars_repo_path": "dynamite/_backend/tests/test_shell_kernel.c", "max_stars_repo_name": "GregDMeyer/dynamite", "max_stars_repo_head_hexsha": "440f0c3674bf12a835b8ad4b3c10c303c2d28265", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2017-10-11T22:53:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-23T01:17:07.000Z", "max_issues_repo_path": "dynamite/_backend/tests/test_shell_kernel.c", "max_issues_repo_name": "GregDMeyer/dynamite", "max_issues_repo_head_hexsha": "440f0c3674bf12a835b8ad4b3c10c303c2d28265", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2017-10-11T22:57:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-03T20:35:44.000Z", "max_forks_repo_path": "dynamite/_backend/tests/test_shell_kernel.c", "max_forks_repo_name": "GregDMeyer/dynamite", "max_forks_repo_head_hexsha": "440f0c3674bf12a835b8ad4b3c10c303c2d28265", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T19:36:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T21:38:18.000Z", "avg_line_length": 23.5846153846, "max_line_length": 71, "alphanum_fraction": 0.6738421396, "num_tokens": 482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334000459302, "lm_q2_score": 0.022286185945086776, "lm_q1q2_score": 0.00907790789506802}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdbool.h>\n#include <limits.h>\n#include <getopt.h>\n#include <mpi.h>\n#include \"compearth.h\"\n#include \"parmt_utils.h\"\n#ifdef PARMT_USE_INTEL\n#include <mkl_cblas.h>\n#else\n#include <cblas.h>\n#endif\n#include \"parmt_polarity.h\"\n#include \"parmt_postProcess.h\"\n#include \"parmt_mtsearch.h\"\n#include \"iscl/array/array.h\"\n#include \"iscl/memory/memory.h\"\n#include \"iscl/os/os.h\"\n\n#define PROGRAM_NAME \"postmt\"\n#define OUTDIR \"postprocess\"\n#define WAVOUT_DIR \"obsest\"\n\nstatic int parseArguments(int argc, char *argv[], char iniFile[PATH_MAX]);\nstatic void printUsage(void);\nint parmt_freeData(struct parmtData_struct *data);\n\nint main(int argc, char *argv[])\n{\n    struct parmtGeneralParms_struct parms;\n    struct parmtData_struct data;\n    struct parmtPolarityParms_struct polarityParms;\n    struct polarityData_struct polarityData;\n    FILE *ofl;\n    char fname[PATH_MAX];\n    char iniFile[PATH_MAX];\n    char programNameIn[256];\n    bool lpol;\n    double U[9], Muse[6], Mned[6], lam[3], *betas, *deps, *depMPDF, *depMagMPDF,\n           *G, *gammas, *kappas,\n           *sigmas, *thetas, *M0s, *phi, *var, dip, epoch,\n           lagTime, Mw, phiLoc, xnorm, xsum;\n    int ierr, iobs, imtopt, jb, jg, jk, jloc, jm, joptLoc, \n        js, jt, k, lag, myid, nb, ng, nk, nlags, nlocs,\n        nm, nmt, npmax, npts, nprocs, ns, nt,\n        provided;\n    bool ldefault;\n    // Start MPI\n    MPI_Init_thread(&argc, &argv, MPI_THREAD_FUNNELED, &provided);\n    MPI_Comm_rank(MPI_COMM_WORLD, &myid);\n    MPI_Comm_size(MPI_COMM_WORLD, &nprocs);\n    // Initialize\n    depMPDF = NULL; \n    depMagMPDF = NULL;\n    betas = NULL;\n    deps = NULL;\n    gammas = NULL;\n    kappas = NULL;\n    sigmas = NULL;\n    thetas = NULL;\n    M0s = NULL;\n    phi = NULL;\n    memset(&parms, 0, sizeof(struct parmtGeneralParms_struct));\n    memset(&data, 0, sizeof(struct parmtData_struct));\n    memset(&polarityParms, 0, sizeof(struct parmtPolarityParms_struct));\n    memset(&polarityData, 0, sizeof(struct polarityData_struct));\n    // Parse the input arguments \n    ierr = parseArguments(argc, argv, iniFile);\n    if (ierr != 0)\n    {\n        if (ierr ==-2){return 0;}\n        printf(\"%s: Error parsing arguments\\n\", PROGRAM_NAME);\n        return EXIT_FAILURE;\n    }\n    // Load the ini file - from this we should be able to deduce the archive\n    ierr = parmt_utils_readGeneralParms(iniFile, &parms);\n    if (ierr != 0)\n    {\n        printf(\"%s: Error reading general parameters\\n\", PROGRAM_NAME);\n        return EXIT_FAILURE;\n    }\n    if (!os_path_isfile(parms.postmtFile))\n    {\n        printf(\"%s: Archive file %s doesn't exist\\n\",\n               PROGRAM_NAME, parms.postmtFile);\n        return EXIT_FAILURE;\n    }\n    ierr += parmt_utils_readPolarityParms(iniFile, &polarityParms);\n\n    // TODO make this a config\n    if (!os_path_isdir(OUTDIR))\n    {\n        os_makedirs(OUTDIR);\n    }\n    if (!os_path_isdir(WAVOUT_DIR))\n    {\n        os_makedirs(WAVOUT_DIR);\n    }\n    // Load the data\n    printf(\"%s: Reading data...\\n\", PROGRAM_NAME);\n    ierr = utils_dataArchive_readAllWaveforms(parms.dataFile, &data);\n    if (ierr != 0)\n    {\n        printf(\"%s: Error reading data\\n\", PROGRAM_NAME);\n        goto ERROR;\n    }\n    data.est = (struct sacData_struct *)\n               calloc((size_t) data.nobs, sizeof(struct sacData_struct));\n    // Read the archive\n    printf(\"%s: Reading archive %s...\\n\", PROGRAM_NAME, parms.postmtFile); \nprintf(\"%s %s %s\\n\", parms.resultsDir, parms.projnm, parms.resultsFileSuffix);\n    ierr = parmt_io_readObjfnArchive64f(\n                   //parms.resultsDir, parms.projnm, parms.resultsFileSuffix,\n                   parms.postmtFile, //parms.parmtArchive,\n                   programNameIn,\n                   &nlocs, &deps,\n                   &nm, &M0s,\n                   &nb, &betas,\n                   &ng, &gammas,\n                   &nk, &kappas,\n                   &ns, &sigmas,\n                   &nt, &thetas,\n                   &nmt, &phi);\n    if (ierr != 0)\n    {\n        printf(\"%s: Error loading archive\\n\", PROGRAM_NAME);\n        goto ERROR;\n    }\n/*\ndouble *phi1; \n    ierr = parmt_io_readObjfnArchive64f(\n                   \"bw\", parms.projnm, \"bodyWaves\",\n                   &nlocs, &deps,\n                   &nm, &M0s,\n                   &nb, &betas,\n                   &ng, &gammas,\n                   &nk, &kappas,\n                   &ns, &sigmas,\n                   &nt, &thetas,\n                   &nmt, &phi1);\nfor (int imt=0; imt<nmt; imt++)\n{\n  phi[imt] = (12.0*phi1[imt] + 11*phi[imt]);\n}\n        ierr = parmt_io_createObjfnArchive64f(\"joint\", parms.projnm,\n                                              \"joint\",\n                                              25, //data.nobs,\n                                              nlocs, deps,\n                                              nm, M0s,\n                                              nb, betas,\n                                              ng, gammas,\n                                              nk, kappas,\n                                              ns, sigmas,\n                                              nt, thetas);\n        ierr = parmt_io_writeObjectiveFunction64f(\n                   \"joint\", parms.projnm, \"joint\",\n                   nmt, phi);\nreturn 0;\n*/\n    // Get the optimum moment tensor for the waveforms\n    ierr = marginal_getOptimum(nlocs, nm, nb,\n                               ng, nk, ns, nt,\n                               phi,\n                               &jloc, &jm, &jb, &jg,\n                               &jk, &js, &jt);\n    if (ierr != 0)\n    {\n        printf(\"%s: Failed to get optimum\\n\", PROGRAM_NAME);\n        goto ERROR;\n    }\n    imtopt = jloc*nm*nb*ng*nk*ns*nt\n           +      jm*nb*ng*nk*ns*nt\n           +         jb*ng*nk*ns*nt\n           +            jg*nk*ns*nt\n           +               jk*ns*nt\n           +                  js*nt\n           +                     jt;\n//printf(\"%d %e\\n\", jm, M0s[jm]);\n//getchar();\n    compearth_m02mw(1, CE_KANAMORI_1978, &M0s[jm], &Mw);\n    joptLoc = jloc;\n//printf(\"%d %d %d %d %d %d %d\\n\", jloc, jm, jg, jb, jk, js, jt);\n//jloc =4; jm = 5; jg =1; jb=0; jk=11; js=2; jt=4;\n\n    printf(\"%s: Optimum information:\\n\", PROGRAM_NAME);\n    printf(\"        Value: %f\\n\", phi[imtopt]);\n    printf(\"        Depth: %f (km)\\n\", deps[jloc]);\n    printf(\"        Magnitude: %f\\n\", Mw);\n    printf(\"        Lune longitude: %f (deg)\\n\", gammas[jg]*180.0/M_PI);\n    printf(\"        Lune latitude: %f (deg)\\n\", (M_PI_2 - betas[jb])*180.0/M_PI);\n    printf(\"        Strike: %f (deg)\\n\", kappas[jk]*180.0/M_PI);\n    printf(\"        Slip: %f (deg)\\n\", sigmas[js]*180.0/M_PI); \n    printf(\"        Dip: %f (deg)\\n\", thetas[jt]*180.0/M_PI);\n    // Display the moment tensor in USE format which is useful for obspy and gmt\n        double gammaOpt = gammas[jg]*180.0/M_PI;\n        double deltaOpt = 90.0-betas[jb]*180.0/M_PI;\n        double kappaOpt = kappas[jk]*180.0/M_PI;\n        double thetaOpt = thetas[jt]*180.0/M_PI;\n        double sigmaOpt = sigmas[js]*180.0/M_PI; \n        compearth_TT2CMT(1, &gammaOpt,\n                         &deltaOpt,\n                         &M0s[jm],\n                         &kappaOpt,\n                         &thetaOpt,\n                         &sigmaOpt,\n                         Muse, lam, U);\n\n/*\n    compearth_tt2cmt(gammas[jg]*180.0/M_PI,\n                     (M_PI/2.0 - betas[jb])*180.0/M_PI,\n                     M0s[jm],\n                     kappas[jk]*180.0/M_PI,\n                     thetas[jt]*180.0/M_PI,\n                     sigmas[js]*180.0/M_PI,\n                     Muse, lam, U);\n*/\n/*\nMuse[0] = 28200000000000000.;  // mrr\nMuse[1] = 283100000000000000.; // mtt\nMuse[2] =-311300000000000000.; // mpp\nMuse[3] =-243300000000000000.; // mrt\nMuse[4] =-149900000000000000.; // mrp\nMuse[5] = 467500000000000000.; // mtp\ncompearth_convertMT(1, CE_USE,  CE_NED, Muse, Mned);\n*/\n    ierr = parmt_discretizeMT64f(1, &gammas[jg],\n                                 1, &betas[jb],\n                                 1, &M0s[jm],\n                                 1, &kappas[jk],\n                                 1, &thetas[jt],\n                                 1, &sigmas[js],\n                                 6, 1, Mned);\n\n    printf(\"mtUSE =[%.6e,%.6e,%.6e,%.6e,%.6e,%.6e]\\n\",\n           Muse[0], Muse[1], Muse[2], Muse[3], Muse[4], Muse[5]);\n    printf(\"mtNED =[%.6e,%.6e,%.6e,%.6e,%.6e,%.6e]\\n\",\n           Mned[0], Mned[1], Mned[2], Mned[3], Mned[4], Mned[5]);\n//printf(\"%e\\n\", M0s[jm]);\n//compearth_CMT2m0(1, 1, Mned, &M0s[jm]);\n//printf(\"%e\\n\", M0s[jm]);\n//getchar();\n    // Compute the polarities\n    lpol = true;\n    ierr = parmt_polarity_computeTTimesGreens(MPI_COMM_WORLD, polarityParms,\n                                              data, &polarityData);\n    if (ierr != 0)\n    {   \n        printf(\"%s: Error computing polarity Green's functions\\n\",\n               PROGRAM_NAME);\n        ierr = 1;\n        lpol = false;\n    }\n    if (lpol && polarityData.nPolarity > 0)\n    {\n        double *Gpol = memory_calloc64f(6*polarityData.nPolarity);\n        double *est = memory_calloc64f(polarityData.nPolarity);\n        double phiPol;\n        int ipol, kt;\n        kt = jloc*polarityData.nPolarity;\nprintf(\"G\\n\");\n        for (ipol=0; ipol<polarityData.nPolarity; ipol++)\n        {\n            Gpol[6*ipol+0] = polarityData.Gxx[kt+ipol];\n            Gpol[6*ipol+1] = polarityData.Gyy[kt+ipol];\n            Gpol[6*ipol+2] = polarityData.Gzz[kt+ipol];\n            Gpol[6*ipol+3] = polarityData.Gxy[kt+ipol];\n            Gpol[6*ipol+4] = polarityData.Gxz[kt+ipol];\n            Gpol[6*ipol+5] = polarityData.Gyz[kt+ipol];\nprintf(\"%f %f %f %f %f %f\\n\", Gpol[6*ipol+0], Gpol[6*ipol+1], Gpol[6*ipol+2],\n                     Gpol[6*ipol+3], Gpol[6*ipol+4], Gpol[6*ipol+5]);\n        }\n        cblas_dgemv(CblasRowMajor, CblasNoTrans,\n                    polarityData.nPolarity, 6, 1.0, Gpol, 6,\n                    Mned, 1, 0.0, est, 1);\n        for (ipol=0; ipol<polarityData.nPolarity; ipol++)\n        {\n            est[ipol] = copysign(1.0, est[ipol]);\n            printf(\"Polarity: obs %f; est %f\\n\",\n                   polarityData.polarity[ipol], est[ipol]);\n        }\n        \n    }\n    // Write the output file\n\n    struct globalMapOpts_struct globalMap;\n    memset(&globalMap, 0, sizeof(struct globalMapOpts_struct));\n    strcpy(globalMap.outputScript, \"gmtScripts/globalMap.sh\");\n    strcpy(globalMap.psFile, \"globalMap.ps\");\n    array_copy64f_work(6, Muse, globalMap.mts);\n    globalMap.basis = CE_USE;\n    globalMap.evla = data.data[0].header.evla;\n    globalMap.evlo = data.data[0].header.evlo;\n    globalMap.evdp = deps[jloc]; \n    globalMap.lwantMT = true;\n    globalMap.lwantPolarity = true;\nprintf(\"%f %f\\n\", globalMap.mts[0], globalMap.mts[1]);\n    ierr = postmt_gmtHelper_writeGlobalMap(globalMap, data.nobs, data.data);\n/*\nprintf(\"overriding ned and joptloc\\n\");\njoptLoc=5;\nMned[0] = 8.526325e+15;\nMned[1] =-8.707938e+16;\nMned[2] = 2.226786e+17;\nMned[3] =-5.768950e+17;\nMned[4] =-3.469420e+17;\nMned[5] =-2.756277e+17;\n*/\n    // Compute the scaling factor\n    xnorm = marginal_computeNormalization(nlocs, deps,\n                                          nm, M0s,\n                                          nb, betas,\n                                          ng, gammas,\n                                          nk, kappas,\n                                          ns, sigmas,\n                                          nt, thetas,\n                                          phi, &ierr);\n    if (xnorm <= 0.0 || ierr != 0)\n    {\n        printf(\"%s: Failed to compute normalization factor - setting to 1\\n\",\n               PROGRAM_NAME);\n        ierr = 0;\n        xnorm = 1.0;\n    }\n    printf(\"%s: Scaling factor: %e\\n\", PROGRAM_NAME, xnorm);\n    cblas_dscal(nmt, 1.0/xnorm, phi, 1);\n    printf(\"%s: Computing pure histograms\\n\", PROGRAM_NAME);\n\n    double *locHist, *magHist, *betaHist, *gammaHist, *kappaHist, *sigmaHist, *thetaHist;\n    ierr = postmt_gmtHelper_makeRegularHistograms(nlocs, nm,\n                                                  nb, ng, nk, ns, nt, \n                                                  nmt, phi,\n                                                  &locHist, &magHist, &betaHist,\n                                                  &gammaHist, &kappaHist, &sigmaHist,\n                                                  &thetaHist);\n    int i;\n/*\n    printf(\"Depths\\n\");\n    for (i=0; i<nlocs; i++)\n    {\n        printf(\"%f %f\\n\", deps[i], locHist[i]);\n    }\n    printf(\"Magnitudes\\n\");\n    for (i=0; i<nm; i++)\n    {\n        compearth_m02mw(1, CE_KANAMORI_1978, &M0s[i], &Mw);\n        printf(\"%f %f\\n\", Mw, magHist[i]);\n    }\n    printf(\"Gammas\\n\");\n    for (i=0; i<ng; i++)\n    {\n        printf(\"%f %f\\n\", gammas[i]*180.0/M_PI, gammaHist[i]);\n    }\n*/\n    printf(\"Betas\\n\");\n    for (i=0; i<nb; i++)\n    {\n        printf(\"%f %f\\n\", 90.0 - betas[i]*180.0/M_PI, betaHist[i]);\n    }\n/*\n    printf(\"Kappas\\n\");\n    for (i=0; i<nk; i++)\n    {\n        printf(\"%f %f\\n\", kappas[i]*180.0/M_PI, kappaHist[i]);\n    }\n    printf(\"Sigmas\\n\");\n    for (i=0; i<ns; i++)\n    {\n        printf(\"%f %f\\n\", sigmas[i]*180.0/M_PI, sigmaHist[i]);\n    }\n    printf(\"Thetas\\n\");\n    for (i=0; i<nt; i++)\n    {\n        printf(\"%f %f\\n\", thetas[i]*180.0/M_PI, thetaHist[i]);\n    }\n*/\nconst char *scriptFile = \"gmtScripts/boxes.sh\";\nconst char *psFile = \"boxes.ps\";\nierr = postmt_gmtHelper_writeBetaBoxes(false, false, scriptFile, psFile,\n                                       nb, jb, betas, betaHist);\nierr = postmt_gmtHelper_writeGammaBoxes(true, false, scriptFile, psFile,\n                                        ng, jg, gammas, gammaHist);\nierr = postmt_gmtHelper_writeKappaBoxes(true, false, scriptFile, psFile,\n                                        nk, jk, kappas, kappaHist);\nierr = postmt_gmtHelper_writeSigmaBoxes(true, false, scriptFile, psFile,\n                                        ns, js, sigmas, sigmaHist);\nierr = postmt_gmtHelper_writeThetaBoxes(true, false, scriptFile, psFile,\n                                        nt, jt, thetas, thetaHist);\nierr = postmt_gmtHelper_writeMagnitudeBoxes(true, false, scriptFile, psFile,\n                                            nm, jm, M0s, magHist);\nierr = postmt_gmtHelper_writeDepthBoxes(true, true, scriptFile, psFile,\n                                        nlocs, joptLoc, deps, locHist);\n\n    // Start the post-processing - compute the depgh magnitude mPDFs\n    printf(\"%s: Computing the depth MPDF's\\n\", PROGRAM_NAME);\n    depMagMPDF = memory_calloc64f(nm*nlocs);\n    depMPDF = memory_calloc64f(nlocs);\n    ierr = marginal_computeDepthMPDF(nlocs,\n                                     nm, M0s,\n                                     nb, betas,\n                                     ng, gammas,\n                                     nk, kappas,\n                                     ns, sigmas,\n                                     nt, thetas,\n                                     phi, depMagMPDF, depMPDF);\n    if (ierr != 0)\n    {\n        printf(\"%s: Error computing depthMPDF\\n\", PROGRAM_NAME);\n        goto ERROR;\n    }\n    // Print the station list for my edification\n    for (k=0; k<data.nobs; k++)\n    {\n        printf(\"%8.3f %8.3f %6s\\n\", data.data[k].header.stlo,\n                                    data.data[k].header.stla,\n                                    data.data[k].header.kstnm);\n    }\nint im, iloc;\n    for (im=0; im<nm; im++)\n    {\n        compearth_m02mw(1, CE_KANAMORI_1978, &M0s[im], &Mw);\n        printf(\"Writing magnitude: %f\\n\", Mw);\n        memset(fname, 0, PATH_MAX*sizeof(char));\n        sprintf(fname, \"%s/%s_dep.%d.txt\", OUTDIR, parms.projnm, im+1);\n        ofl = fopen(fname, \"w\");\n        for (iloc=0; iloc<nlocs; iloc++)\n        {\n            jloc = im*nlocs + iloc;\n            fprintf(ofl, \"%e %e\\n\", deps[iloc], depMagMPDF[jloc]);\n        }\n        fclose(ofl);\n    }\n    memset(fname, 0, PATH_MAX*sizeof(char));\n    sprintf(fname, \"%s/%s_dep.txt\", OUTDIR, parms.projnm);\n    ofl = fopen(fname, \"w\");\n    for (iloc=0; iloc<nlocs; iloc++)\n    {\n        fprintf(ofl, \"%e %e\\n\", deps[iloc], depMPDF[iloc]);\n    }\n    fclose(ofl);\n    // Compute the optimal synthetics\n    xsum = 0.0;\n    for (iobs=0; iobs<data.nobs; iobs++)\n    {\n        // Extract the depth waveform\n        npts = data.data[iobs].npts;\n        npmax = npts;\n        G = memory_calloc64f(6*npmax);\n        var = memory_calloc64f(npmax);\n        ierr = parmt_utils_setDataOnG(iobs, joptLoc, npmax, data, G);\n        if (ierr != 0)\n        {\n            printf(\"%s: Failed to set data on G\\n\", PROGRAM_NAME);\n            goto ERROR;\n        }\n        // Compute the lag time\n        nlags = 0;\n        lag = 0;\n        if (parms.lwantLags)\n        {\n            //lagTime = data.data[iobs].header.user0;\n            //if (lagTime < 0.0){lagTime = parms.defaultMaxLagTime;}\n            lagTime = parmt_utils_getLagTime(data.data[iobs], \n                                             parms.defaultMaxLagTime,\n                                             &ldefault);\n            nlags = (int) (lagTime/data.data[iobs].header.delta + 0.5);\n        }\n        ierr = parmt_mtSearchL164f(6, 1,\n                                   npts, 1,\n                                   nlags, parms.lwantLags,\n                                   parms.lrescale,\n                                   &G[0*npmax], &G[1*npmax], &G[2*npmax],\n                                   &G[3*npmax], &G[4*npmax], &G[5*npmax],\n                                   NULL, Mned, data.data[iobs].data,\n                                   &phiLoc, var, &lag);\n        if (ierr != 0)\n        {\n            printf(\"%s: Error computing lags for waveform %d\\n\",\n                   PROGRAM_NAME, iobs);\n            goto ERROR;\n        }\n        // Compute the synthetic\n        k = iobs*data.nlocs + joptLoc;\n        parmt_utils_sacGrnsToEst(data.data[iobs],\n                                 data.sacGxx[k], data.sacGyy[k],\n                                 data.sacGzz[k], data.sacGxy[k],\n                                 data.sacGxz[k], data.sacGyz[k],\n                                 Mned,\n                                 parms.lrescale,\n                                 &data.est[iobs]);\n        // Fix the timing\n        ierr = sacio_getEpochalStartTime(data.est[iobs].header, &epoch);\n        epoch = epoch + (double) lag*data.data[iobs].header.delta;\n        sacio_setEpochalStartTime(epoch, &data.est[iobs].header);\n        // Write the file\n        memset(fname, 0, PATH_MAX*sizeof(char));\n        sprintf(fname, \"%s/%s.%s.%s.%s.SAC\",\n                WAVOUT_DIR,\n                data.data[iobs].header.knetwk,\n                data.data[iobs].header.kstnm,\n                data.data[iobs].header.kcmpnm,\n                data.data[iobs].header.khole);\n        sacio_writeTimeSeriesFile(fname, data.data[iobs]);\n        memset(fname, 0, PATH_MAX*sizeof(char));\n        sprintf(fname, \"%s/%s.%s.%s.%s.EST.SAC\",\n                WAVOUT_DIR,\n                data.data[iobs].header.knetwk,\n                data.data[iobs].header.kstnm,\n                data.data[iobs].header.kcmpnm,\n                data.data[iobs].header.khole);\n        sacio_writeTimeSeriesFile(fname, data.est[iobs]);\n        printf(\"Waveform %6s has lag %+4d=%+8.3e (s) and a fit of %f\\n\",\n               data.data[iobs].header.kstnm,\n               lag, lag*data.data[iobs].header.delta, phiLoc);\n        memory_free64f(&G); \n        memory_free64f(&var);\n        xsum = xsum + phiLoc;\n    } \n    printf(\"Average %f\\n\", xsum/(double) data.nobs );\n/*\ndouble *db = memory_calloc64f(nb);\ndouble *dg = memory_calloc64f(ng);\ndouble *dt = memory_calloc64f(nt);\npostprocess_computeBetaCellSpacing(nb, betas, db); \n printf(\"\\n\");\npostprocess_computeGammaCellSpacing(ng, gammas, dg);\nprintf(\"\\n\");\npostprocess_computeThetaCellSpacing(nt, thetas, dt);\n*/\n    // Free memory\nERROR:;\n    parmt_freeData(&data);\n    memory_free64f(&depMagMPDF);\n    memory_free64f(&depMPDF);\n    memory_free64f(&deps);\n    memory_free64f(&M0s); \n    memory_free64f(&betas);\n    memory_free64f(&gammas);\n    memory_free64f(&kappas);\n    memory_free64f(&sigmas);\n    memory_free64f(&thetas);\n    memory_free64f(&phi);\n    iscl_finalize();\n    MPI_Finalize();\n    return ierr;\n}\n//============================================================================//\n/*!\n * @brief Parses the input arguments to get the ini file anme\n */\nstatic int parseArguments(int argc, char *argv[], char iniFile[PATH_MAX])\n{\n    bool linFile;\n    memset(iniFile, 0, PATH_MAX*sizeof(char));\n    while (true)\n    {\n        static struct option longOptions[] =\n        {\n            {\"help\", no_argument, 0, '?'},\n            {\"help\", no_argument, 0, 'h'},\n            {\"ini_file\", required_argument, 0, 'i'},\n            {0, 0, 0, 0}\n        };  \n        int c, optionIndex;\n        c = getopt_long(argc, argv, \"?hi:\",\n                        longOptions, &optionIndex);\n        if (c ==-1){break;}\n        if (c == 'i')\n        {   \n            strcpy(iniFile, (const char *) optarg);\n            linFile = true; \n        }\n        else if (c == 'h' || c == '?')\n        {\n            printUsage();\n            return -2;\n        }   \n        else\n        {\n            printf(\"%s: Unknown options: %s\\n\",\n                   PROGRAM_NAME, argv[optionIndex]);\n        }\n    }\n    if (!linFile)\n    {\n        printf(\"%s: Error must specify ini file\\n\\n\", PROGRAM_NAME);\n        printUsage();\n        return -1;\n    }\n    return 0;\n}\n\nstatic void printUsage(void)\n{\n    printf(\"Usage:\\n   postmt -i input_file\\n\\n\");\n    printf(\"Required arguments:\\n\");\n    printf(\"   -i input_file specifies the initialization file\\n\");\n    printf(\"\\n\");\n    printf(\"Optional arguments:\\n\");\n    printf(\"   -h displays this message\\n\");\n    return;\n}\n\n\nint parmt_freeData(struct parmtData_struct *data)\n{\n    int i;\n    if (data->nobs > 0 && data->nlocs > 0 &&\n        data->sacGxx != NULL && data->sacGyy != NULL && data->sacGzz != NULL &&\n        data->sacGxy != NULL && data->sacGxz != NULL && data->sacGyz != NULL)\n    {\n        for (i=0; i<data->nobs*data->nlocs; i++)\n        {\n            sacio_freeData(&data->sacGxx[i]);\n            sacio_freeData(&data->sacGyy[i]);\n            sacio_freeData(&data->sacGzz[i]);\n            sacio_freeData(&data->sacGxy[i]);\n            sacio_freeData(&data->sacGxz[i]);\n            sacio_freeData(&data->sacGyz[i]);\n        }\n        free(data->sacGxx);\n        free(data->sacGyy);\n        free(data->sacGzz);\n        free(data->sacGxy);\n        free(data->sacGxz);\n        free(data->sacGyz);\n    }\n    if (data->nobs > 0 && data->data != NULL)\n    {\n        for (i=0; i<data->nobs; i++)\n        {\n            sacio_freeData(&data->data[i]);\n        }\n        free(data->data);\n    }\n    if (data->nobs > 0 && data->est != NULL)\n    {\n        free(data->est);\n    }\n    memset(data, 0, sizeof(struct parmtData_struct));\n    return 0;\n}\n", "meta": {"hexsha": "acf976e353614f8f9e920165766ccfb3a8a3b170", "size": 22959, "ext": "c", "lang": "C", "max_stars_repo_path": "postprocess/postmt.c", "max_stars_repo_name": "bakerb845/parmt", "max_stars_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_stars_repo_licenses": ["Intel"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "postprocess/postmt.c", "max_issues_repo_name": "bakerb845/parmt", "max_issues_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_issues_repo_licenses": ["Intel"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "postprocess/postmt.c", "max_forks_repo_name": "bakerb845/parmt", "max_forks_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_forks_repo_licenses": ["Intel"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.650621118, "max_line_length": 89, "alphanum_fraction": 0.5020253495, "num_tokens": 6514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215925474903, "lm_q2_score": 0.021287350900896458, "lm_q1q2_score": 0.00907525733718743}}
{"text": "#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_vector.h>\n#include \"cimple_polytope_library.h\"\n\n/**\n * \"Constructor\" Dynamically allocates the space a polytope needs\n */\nstruct polytope *polytope_alloc(size_t k,\n                                size_t n)\n{\n\n    struct polytope *return_polytope = malloc (sizeof (struct polytope));\n\n    return_polytope->H = gsl_matrix_alloc(k, n);\n    if (return_polytope->H == NULL) {\n        free (return_polytope);\n        return NULL;\n    }\n\n    return_polytope->G = gsl_vector_alloc(k);\n    if (return_polytope->H == NULL) {\n        free (return_polytope);\n        return NULL;\n    }\n\n    return_polytope->chebyshev_center = malloc(n* sizeof (double));\n    if (return_polytope->chebyshev_center == NULL) {\n        free (return_polytope);\n        return NULL;\n    }\n\n    return return_polytope;\n};\n\n/**\n * \"Destructor\" Deallocates the dynamically allocated memory of the polytope\n */\nvoid polytope_free(polytope *polytope)\n{\n    gsl_matrix_free(polytope->H);\n    gsl_vector_free(polytope->G);\n    free(polytope->chebyshev_center);\n    free(polytope);\n};\n\n/**\n * \"Constructor\" Dynamically allocates the space a polytope needs\n */\nstruct cell *cell_alloc(size_t k,\n                        size_t n,\n                        int time_horizon)\n{\n\n    struct cell *return_cell = malloc (sizeof (struct cell));\n\n    return_cell->safe_mode = malloc(sizeof(polytope)*time_horizon);\n    if (return_cell->safe_mode == NULL) {\n        free (return_cell);\n        return NULL;\n    }\n\n    return_cell->polytope_description = polytope_alloc(k,n);\n    if (return_cell->polytope_description == NULL) {\n        free (return_cell);\n        return NULL;\n    }\n    return return_cell;\n};\n\n/**\n * \"Destructor\" Deallocates the dynamically allocated memory of the region of polytopes\n */\nvoid cell_free(cell *cell)\n{\n    polytope_free(cell->polytope_description);\n    free(cell->safe_mode);\n    free(cell);\n\n};\n\n/**\n * \"Constructor\" Dynamically allocates the space a region of polytope needs\n */\nstruct abstract_state *abstract_state_alloc(size_t *k,\n                                            size_t k_hull,\n                                            size_t n,\n                                            int transitions_in_count,\n                                            int transitions_out_count,\n                                            int cells_count,\n                                            int time_horizon)\n{\n\n    struct abstract_state *return_abstract_state = malloc (sizeof (struct abstract_state));\n\n    /*\n     * Default values: at initialization safe mode is not yet computed.\n     * Thus it is assumed that the state does not contain an invariant set => invariant_set = NULL\n     * next_state (next state the system has to transition to reach an invariant set) is unknown at initialization.\n     */\n\n    return_abstract_state->next_state = NULL;\n    return_abstract_state->invariant_set = NULL;\n//    return_abstract_state->distance_invariant_set = INFINITY;\n\n    return_abstract_state->cells = malloc(sizeof(cell)*cells_count);\n    if (return_abstract_state->cells == NULL) {\n        free (return_abstract_state);\n        return NULL;\n    }\n\n    for(int i = 0; i < cells_count; i++){\n        return_abstract_state->cells[i] = cell_alloc(*(k+i), n, time_horizon);\n        if (return_abstract_state->cells[i] == NULL) {\n            free (return_abstract_state);\n            return NULL;\n        }\n    }\n\n    return_abstract_state->cells_count = cells_count;\n\n    return_abstract_state->transitions_in = malloc(sizeof(struct abstract_state) * transitions_in_count);\n    if (return_abstract_state->transitions_in == NULL) {\n        free (return_abstract_state);\n        return NULL;\n    }\n\n    return_abstract_state->transitions_in_count = transitions_in_count;\n\n    return_abstract_state->transitions_out = malloc(sizeof(struct abstract_state) * transitions_out_count);\n    if (return_abstract_state->transitions_out == NULL) {\n        free (return_abstract_state);\n        return NULL;\n    }\n\n    return_abstract_state->transitions_out_count = transitions_out_count;\n\n    return_abstract_state->convex_hull = polytope_alloc(k_hull, n);\n    if (return_abstract_state->convex_hull == NULL) {\n        free (return_abstract_state);\n        return NULL;\n    }\n\n    return return_abstract_state;\n};\n\n/**\n * \"Destructor\" Deallocates the dynamically allocated memory of the region of polytopes\n */\nvoid abstract_state_free(abstract_state * abstract_state){\n    polytope_free(abstract_state->convex_hull);\n    for(int i = 0; i< abstract_state->cells_count; i++){\n        cell_free(abstract_state->cells[i]);\n    }\n    free(abstract_state->transitions_out);\n    free(abstract_state->transitions_in);\n    free(abstract_state->cells);\n    free(abstract_state);\n\n};\n\n/**\n * Converts two C arrays to a polytope consistent of a left side matrix (i.e. H) and right side vector (i.e. G)\n */\nvoid polytope_from_arrays(polytope *polytope,\n                          double *left_side,\n                          double *right_side,\n                          double *cheby,\n                          char*name)\n{\n\n    gsl_matrix_from_array(polytope->H, left_side, name);\n    gsl_vector_from_array(polytope->G, right_side, name);\n    for(int i = 0; i < polytope->H->size2; i++){\n        polytope->chebyshev_center[i] = cheby[i];\n    }\n};\n\n/**\n * Converts a polytope in gsl form to cdd constraint form\n */\ndd_PolyhedraPtr polytope_to_cdd(polytope *original,\n                                dd_ErrorType *err)\n{\n    dd_PolyhedraPtr new;\n    dd_MatrixPtr constraints;\n    constraints = dd_CreateMatrix(original->H->size1, (original->H->size2+1));\n    for (size_t k = 0; k < (original->H->size1); k++) {\n        double value = gsl_vector_get(original->G, k);\n        dd_set_d(constraints->matrix[k][0],value);\n    }\n    for(size_t i = 0; i<original->H->size1; i++){\n        for (size_t j = 1; j < (original->H->size2+1); j++) {\n            double value = gsl_matrix_get(original->H, i, j-1);\n            dd_set_d(constraints->matrix[i][j],-1*value);\n        }\n    }\n    constraints->representation=dd_Inequality;\n    new = dd_DDMatrix2Poly(constraints, err);\n    dd_FreeMatrix(constraints);\n    return new;\n};\n\n/**\n * Converts a polytope in cdd constraint form to gsl form\n */\npolytope * cdd_to_polytope(dd_PolyhedraPtr *original)\n{\n\n    dd_MatrixPtr constraints;\n    constraints = dd_CopyInequalities(*original);\n    polytope *new = polytope_alloc(constraints->rowsize, constraints->colsize-1);\n    for (size_t k = 0; k < (constraints->rowsize); k++) {\n        double value = dd_get_d(constraints->matrix[k][0]);\n        gsl_vector_set(new->G, k, value);\n    }\n    for(size_t i = 0; i<constraints->rowsize; i++){\n        for (size_t j = 0; j < (constraints->colsize-1); j++) {\n            double value = dd_get_d(constraints->matrix[i][j+1]);\n            gsl_matrix_set(new->H,i,j,-value);\n        }\n    }\n    dd_FreeMatrix(constraints);\n    return new;\n\n};\n\n/**\n * Generate a polytope representing a scaled unit cube\n */\npolytope * polytope_scaled_unit_cube(double scale,\n                                     int dimensions)\n{\n\n    dd_PolyhedraPtr cube = cdd_scaled_unit_cube(scale, dimensions);\n    polytope * return_cube = cdd_to_polytope(&cube);\n    dd_FreePolyhedra(cube);\n\n    return return_cube;\n};\n\n/**\n * Checks whether a state is in a certain polytope\n */\nbool polytope_check_state(polytope *polytope,\n                         gsl_vector *x)\n{\n    gsl_vector * result = gsl_vector_alloc(polytope->G->size);\n    gsl_blas_dgemv(CblasNoTrans, 1.0, polytope->H, x, 0.0, result);\n    for(size_t i = 0; i< polytope->G->size; i++){\n        if(gsl_vector_get(result, i) > gsl_vector_get(polytope->G, i)){\n            gsl_vector_free(result);\n            return false;\n        }\n    }\n    gsl_vector_free(result);\n    return true;\n};\n\n/**\n * Checks whether polytope P1 \\ issubset P2\n */\nbool polytope_is_subset(polytope *P1,\n                        polytope *P2)\n{\n    dd_ErrorType err = dd_NoError;\n    dd_PolyhedraPtr first = polytope_to_cdd(P1, &err);\n    dd_MatrixPtr verticesFirst = dd_CopyGenerators(first);\n    gsl_vector *vertex = gsl_vector_alloc(P1->H->size2);\n    gsl_vector_set_zero(vertex);\n    int is_included;\n    bool is_subset = true;\n    for(int i = 0; i<verticesFirst->rowsize;i++){\n        double valueFirst0 = dd_get_d(verticesFirst->matrix[i][0]);\n        if(valueFirst0 == 1){\n            for(int j = 0; j<vertex->size; j++){\n                double valueFirstj = dd_get_d(verticesFirst->matrix[i][j+1]);\n                gsl_vector_set(vertex,(size_t)j, valueFirstj);\n            }\n            is_included = polytope_check_state(P2,vertex);\n            if(!is_included){\n                is_subset = false;\n                break;\n            }\n        }\n    }\n    gsl_vector_free(vertex);\n    dd_FreePolyhedra(first);\n    dd_FreeMatrix(verticesFirst);\n    return is_subset;\n};\n\n/**\n * Unite inequalities of P1 and P2 in new polytope and remove redundancies\n */\npolytope * polytope_unite_inequalities(polytope *P1,\n                                       polytope *P2)\n{\n    polytope *united = polytope_alloc(P1->H->size1+P2->H->size1,P1->H->size2);\n    //Unite H\n    gsl_matrix_set_zero(united->H);\n    gsl_matrix_view H_P1 = gsl_matrix_submatrix(united->H, 0, 0, P1->H->size1, P1->H->size2);\n    gsl_matrix_memcpy(&H_P1.matrix, P1->H);\n    gsl_matrix_view H_P2 = gsl_matrix_submatrix(united->H, P1->H->size1, 0, P2->H->size1, P2->H->size2);\n    gsl_matrix_memcpy(&H_P2.matrix, P2->H);\n\n    //Unite G\n    gsl_vector_set_zero(united->G);\n    gsl_vector_view G_P1 = gsl_vector_subvector(united->G, 0, P1->G->size);\n    gsl_vector_memcpy(&G_P1.vector, P1->G);\n    gsl_vector_view G_P2 = gsl_vector_subvector(united->G, P1->G->size,P2->G->size);\n    gsl_vector_memcpy(&G_P2.vector, P2->G);\n    polytope * return_polytope = polytope_minimize(united);\n\n    polytope_free(united);\n\n    return return_polytope;\n\n};\n\n/**\n * Project original polytope (in cdd format) to the first n dimensions\n */\npolytope * polytope_projection(polytope * original,\n                               size_t n)\n{\n\n    dd_ErrorType err;\n    dd_PolyhedraPtr orig_cdd = polytope_to_cdd(original, &err);\n    dd_PolyhedraPtr new_cdd = NULL;\n\n    cdd_projection(&orig_cdd, &new_cdd, n, &err);\n    polytope * new = cdd_to_polytope(&new_cdd);\n    dd_FreePolyhedra(orig_cdd);\n    dd_FreePolyhedra(new_cdd);\n\n    return new;\n\n};\n\npolytope * polytope_linear_transform(polytope *original,\n                                     gsl_matrix *scale){\n\n    dd_ErrorType err = dd_NoError;\n    dd_PolyhedraPtr orig_cdd = polytope_to_cdd(original, &err);\n\n    dd_MatrixPtr vertices = dd_CopyGenerators(orig_cdd);\n\n    dd_MatrixPtr transformed_vertices = dd_CreateMatrix(1, scale->size1+1);\n    dd_MatrixPtr transformed_vertex = dd_CreateMatrix(1, scale->size1+1);\n    bool new_matrix_started = false;\n    gsl_vector *vertex = gsl_vector_alloc((vertices->colsize - 1));\n    gsl_vector *scaled_vertex = gsl_vector_alloc(scale->size1);\n    gsl_vector_set_zero(vertex);\n    gsl_vector_set_zero(scaled_vertex);\n\n    for(int i = 0; i<vertices->rowsize; i++) {\n        //Check whether row represents ray or vertex\n        double is_vertex = dd_get_d(vertices->matrix[i][0]);\n        if (is_vertex == 1) {\n            for (size_t j = 1; j < vertices->colsize; j++) {\n                double value = dd_get_d(vertices->matrix[i][j]);\n                gsl_vector_set(vertex, j-1, value);\n            }\n            gsl_blas_dgemv(CblasNoTrans, 1.0, scale, vertex, 0.0, scaled_vertex);\n\n            if (new_matrix_started) {\n                dd_set_d(transformed_vertex->matrix[0][0], 1);\n                for (size_t j = 0; j < scaled_vertex->size; j++) {\n                    dd_set_d(transformed_vertex->matrix[0][j + 1], gsl_vector_get(scaled_vertex, j));\n                }\n                dd_MatrixAppendTo(&transformed_vertices, transformed_vertex);\n            } else {\n                dd_set_d(transformed_vertices->matrix[0][0], 1);\n                for (size_t j = 0; j < scaled_vertex->size; j++) {\n                    dd_set_d(transformed_vertices->matrix[0][j + 1], gsl_vector_get(scaled_vertex, j));\n                }\n                new_matrix_started = true;\n            }\n\n        }\n    }\n\n    transformed_vertices->representation = dd_Generator;\n    dd_PolyhedraPtr transformed_cdd = dd_DDMatrix2Poly(transformed_vertices, &err);\n    polytope *transformed = cdd_to_polytope(&transformed_cdd);\n\n    //Clean up\n    dd_FreeMatrix(transformed_vertex);\n    dd_FreeMatrix(transformed_vertices);\n    dd_FreePolyhedra(orig_cdd);\n    dd_FreePolyhedra(transformed_cdd);\n    dd_FreeMatrix(vertices);\n    gsl_vector_free(vertex);\n    gsl_vector_free(scaled_vertex);\n\n    return transformed;\n\n};\n/**\n * Remove redundancies from gsl polytope inequalities\n */\npolytope * polytope_minimize(polytope *original)\n{\n\n\n    dd_ErrorType err = dd_NoError;\n    dd_MatrixPtr min_matrix;\n\n    dd_PolyhedraPtr cdd_original = polytope_to_cdd(original, &err);\n\n    dd_PolyhedraPtr cdd_minimized = cdd_minimize(&cdd_original, &err);\n    min_matrix = dd_CopyInequalities(cdd_minimized);\n\n    polytope * minimized = cdd_to_polytope(&cdd_minimized);\n    dd_FreeMatrix(min_matrix);\n    dd_FreePolyhedra(cdd_original);\n    dd_FreePolyhedra(cdd_minimized);\n\n    return minimized;\n\n};\n\n/**\n * Compute Minkowski sum of two polytopes\n */\npolytope * polytope_minkowski(polytope *P1,\n                              polytope *P2)\n{\n    dd_ErrorType err = dd_NoError;\n    dd_PolyhedraPtr A = polytope_to_cdd(P1, &err);\n    dd_PolyhedraPtr B = polytope_to_cdd(P2, &err);\n    dd_PolyhedraPtr C = cdd_minkowski(A,B);\n    polytope * returnPolytope = cdd_to_polytope(&C);\n    dd_FreePolyhedra(A);\n    dd_FreePolyhedra(B);\n    dd_FreePolyhedra(C);\n    return returnPolytope;\n};\n\n/**\n * Compute Pontryagin difference C = A-B s.t.:\n * A-B = {c \\in A-B| c+b \\in A, \\forall b \\in B}\n */\npolytope * polytope_pontryagin(polytope* A,\n                               polytope* B)\n{\n\n    dd_ErrorType err;\n    dd_MatrixPtr verticesA, verticesB;\n    //create cddPoly A,B\n    dd_PolyhedraPtr cddA = polytope_to_cdd(A, &err);\n\n    dd_PolyhedraPtr cddB = polytope_to_cdd(B, &err);\n\n    polytope *C = NULL;\n\n    verticesA = dd_CopyGenerators(cddA);\n    verticesB = dd_CopyGenerators(cddB);\n    for(int i = 0; i<verticesB->rowsize; i++){\n        //Check whether row represents ray or vertex\n        double value_B0 = dd_get_d(verticesB->matrix[i][0]);\n        if(value_B0 == 1){\n            dd_MatrixPtr tempA;\n            //A-b (where b is the vertex)\n            tempA = dd_CreateMatrix(verticesA->rowsize,verticesA->colsize);\n            //each vertex of A displaced by b\n            for(int j = 0; j<verticesA->rowsize; j++){\n                double value_A0 = dd_get_d(verticesA->matrix[j][0]);\n                if(value_A0 == 1){\n                    dd_set_d(tempA->matrix[j][0], 1);\n                    for(int k = 1; k<verticesA->colsize; k++){\n                        double value_Ak = dd_get_d(verticesA->matrix[j][k]);\n                        double value_Bk = dd_get_d(verticesB->matrix[i][k]);\n                        dd_set_d(tempA->matrix[j][k],(value_Ak-value_Bk));\n                    }\n                }else{\n                    dd_set_d(tempA->matrix[j][0], 0);\n                    for(int k = 1; k<verticesA->colsize; k++){\n                        double value_Ak = dd_get_d(verticesA->matrix[j][k]);\n                        dd_set_d(tempA->matrix[j][k],(value_Ak));\n                    }\n                }\n            }\n            dd_PolyhedraPtr cdd_temp;\n            tempA->representation = dd_Generator;\n            cdd_temp = dd_DDMatrix2Poly(tempA, &err);\n            polytope *tempC = cdd_to_polytope(&cdd_temp);\n            dd_FreePolyhedra(cdd_temp);\n            if(C == NULL){\n                C = polytope_alloc(tempC->H->size1,tempC->H->size2);\n                gsl_matrix_memcpy(C->H,tempC->H);\n                gsl_vector_memcpy(C->G,tempC->G);\n                polytope_free(tempC);\n            }else{\n                polytope *copyC = C;\n                C = polytope_unite_inequalities(copyC, tempC);\n                polytope_free(tempC);\n                polytope_free(copyC);\n            }\n            dd_FreeMatrix(tempA);\n        }\n    }\n\n    dd_FreeMatrix(verticesA);\n    dd_FreeMatrix(verticesB);\n    dd_FreePolyhedra(cddA);\n    dd_FreePolyhedra(cddB);\n    return C;\n};\n\n/**\n * Set up constraints in quadratic problem for GUROBI\n */\nint polytope_to_constraints_gurobi(polytope *constraints,\n                                   GRBmodel *model,\n                                   size_t N)\n{\n\n    int error = 0;\n    double constraint_val[N];\n    int ind[N];\n    for(size_t i = 0; i < constraints->H->size1;i++){\n        char constraint_name[5];\n        sprintf(constraint_name, \"c_%d\", (int)i);\n        for(size_t j = 0; j < N;j++){\n            ind[j] = (int)j;\n            constraint_val[j] = gsl_matrix_get(constraints->H,i,j);\n        }\n\n        error = GRBaddconstr(model, (int)N, ind, constraint_val, GRB_LESS_EQUAL, gsl_vector_get(constraints->G,i), constraint_name);\n\n        if(error){\n            return error;\n        }\n    }\n    return error;\n};\n\n/**\n * Generate a polytope representing a scaled unit cube\n */\ndd_PolyhedraPtr cdd_scaled_unit_cube(double scale,\n                                     int dimensions)\n{\n\n    dd_MatrixPtr constraints;\n    dd_PolyhedraPtr cube = NULL;\n    dd_ErrorType err = dd_NoError;\n    constraints = dd_CreateMatrix(dimensions*2,dimensions+1);\n    for(int i = 0; i<(dimensions); i++){\n\n            dd_set_d(constraints->matrix[2*i][0],(scale*0.5));\n            dd_set_d(constraints->matrix[2*i][i+1],-1);\n            dd_set_d(constraints->matrix[2*i+1][0],(scale*0.5));\n            dd_set_d(constraints->matrix[2*i+1][i+1],1);\n    }\n    constraints->representation=dd_Inequality;\n    cube = dd_DDMatrix2Poly(constraints, &err);\n    dd_FreeMatrix(constraints);\n\n    return cube;\n};\n\n\n/**\n * Project original polytope (in cdd format) to the first n dimensions\n */\nvoid cdd_projection(dd_PolyhedraPtr *original,\n                    dd_PolyhedraPtr *new,\n                    size_t n,\n                    dd_ErrorType *err)\n{\n    dd_MatrixPtr full=NULL,projected=NULL;\n    full = dd_CopyInequalities(*original);\n    dd_colrange j,d;\n    dd_rowset redset,impl_linset;\n    dd_colset delset;\n    dd_rowindex newpos;\n\n    d=full->colsize;\n    set_initialize(&delset, d);\n    for (j=n+1; j<d; j++){\n        set_addelem(delset, j+1);\n    }\n\n    projected=dd_BlockElimination(full, delset, err);\n\n    dd_MatrixCanonicalize(&projected,&impl_linset,&redset,&newpos,err);\n\n    dd_FreeMatrix(full);\n    projected->representation = dd_Inequality;\n    *new = dd_DDMatrix2Poly(projected, err);\n    dd_FreeMatrix(projected);\n    set_free(delset);\n    set_free(redset);\n    set_free(impl_linset);\n    free(newpos);\n\n};\n\n/**\n * Remove redundancies from cdd polytope inequalities\n */\ndd_PolyhedraPtr cdd_minimize(dd_PolyhedraPtr *original,\n                             dd_ErrorType *err)\n{\n\n    dd_rowset redset,impl_linset;\n    dd_rowindex newpos;\n    dd_MatrixPtr full=NULL;\n    full = dd_CopyInequalities(*original);\n    dd_MatrixCanonicalize(&full,&impl_linset,&redset,&newpos,err);\n\n    full->representation = dd_Inequality;\n    dd_PolyhedraPtr new = dd_DDMatrix2Poly(full, err);\n    dd_FreeMatrix(full);\n    set_free(redset);\n    set_free(impl_linset);\n    free(newpos);\n    return new;\n\n};", "meta": {"hexsha": "28c77a4f009be1dd20d8f75b66d48391e6b08504", "size": 19466, "ext": "c", "lang": "C", "max_stars_repo_path": "Interface/Cimple/cimple_polytope_library.c", "max_stars_repo_name": "shaesaert/TuLiPXML", "max_stars_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-28T23:44:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-28T23:44:28.000Z", "max_issues_repo_path": "Interface/Cimple/cimple_polytope_library.c", "max_issues_repo_name": "shaesaert/TuLiPXML", "max_issues_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-10-03T18:54:08.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-21T09:50:09.000Z", "max_forks_repo_path": "Interface/Cimple/cimple_polytope_library.c", "max_forks_repo_name": "shaesaert/TuLiPXML", "max_forks_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-06T12:58:52.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-06T12:58:52.000Z", "avg_line_length": 31.2958199357, "max_line_length": 132, "alphanum_fraction": 0.6184629611, "num_tokens": 5106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3886180408675583, "lm_q2_score": 0.023330769572455574, "lm_q1q2_score": 0.009066757963180126}}
{"text": "/* spmatrix/gsl_spmatrix_float.h\n * \n * Copyright (C) 2012, 2013, 2014, 2015, 2016, 2017, 2018 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_SPMATRIX_COMPLEX_FLOAT_H__\n#define __GSL_SPMATRIX_COMPLEX_FLOAT_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_bst.h>\n#include <gsl/gsl_vector_complex_float.h>\n#include <gsl/gsl_matrix_complex_float.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\n/*\n * COO format:\n *\n * If data[n] = A_{ij}, then:\n *   i = A->i[n]\n *   j = A->p[n]\n *\n * Compressed column format (CSC):\n *\n * If data[n] = A_{ij}, then:\n *   i = A->i[n]\n *   A->p[j] <= n < A->p[j+1]\n * so that column j is stored in\n * [ data[p[j]], data[p[j] + 1], ..., data[p[j+1] - 1] ]\n *\n * Compressed row format (CSR):\n *\n * If data[n] = A_{ij}, then:\n *   j = A->i[n]\n *   A->p[i] <= n < A->p[i+1]\n * so that row i is stored in\n * [ data[p[i]], data[p[i] + 1], ..., data[p[i+1] - 1] ]\n */\n\ntypedef struct\n{\n  size_t size1;              /* number of rows */\n  size_t size2;              /* number of columns */\n\n  /* i (size nzmax) contains:\n   *\n   * COO/CSC: row indices\n   * CSR: column indices\n   */\n  int *i;\n\n  float *data;               /* matrix elements of size nzmax */\n\n  /*\n   * COO: p[n] = column number of element data[n]\n   * CSC: p[j] = index in data of first non-zero element in column j\n   * CSR: p[i] = index in data of first non-zero element in row i\n   */\n  int *p;\n\n  size_t nzmax;              /* maximum number of matrix elements */\n  size_t nz;                 /* number of non-zero values in matrix */\n\n  gsl_bst_workspace *tree;   /* binary tree structure */\n  gsl_spmatrix_pool *pool;   /* memory pool for binary tree nodes */\n  size_t node_size;          /* size of individual tree node in bytes */\n\n  /*\n   * workspace of size 2*MAX(size1,size2)*MAX(sizeof(float),sizeof(int))\n   * used in various routines\n   */\n  union\n    {\n      void *work_void;\n      int *work_int;\n      float *work_atomic;\n    } work;\n\n  int sptype;                /* sparse storage type */\n  size_t spflags;            /* GSL_SPMATRIX_FLG_xxx */\n} gsl_spmatrix_complex_float;\n\n/*\n * Prototypes\n */\n\n/* allocation / initialization */\n\ngsl_spmatrix_complex_float * gsl_spmatrix_complex_float_alloc (const size_t n1, const size_t n2);\ngsl_spmatrix_complex_float * gsl_spmatrix_complex_float_alloc_nzmax (const size_t n1, const size_t n2,\n                                                                     const size_t nzmax, const int sptype);\nvoid gsl_spmatrix_complex_float_free (gsl_spmatrix_complex_float * m);\nint gsl_spmatrix_complex_float_realloc (const size_t nzmax, gsl_spmatrix_complex_float * m);\nsize_t gsl_spmatrix_complex_float_nnz (const gsl_spmatrix_complex_float * m);\nconst char * gsl_spmatrix_complex_float_type (const gsl_spmatrix_complex_float * m);\nint gsl_spmatrix_complex_float_set_zero (gsl_spmatrix_complex_float * m);\nint gsl_spmatrix_complex_float_tree_rebuild (gsl_spmatrix_complex_float * m);\n\n/* compress */\n\nint gsl_spmatrix_complex_float_csc (gsl_spmatrix_complex_float * dest, const gsl_spmatrix_complex_float * src);\nint gsl_spmatrix_complex_float_csr (gsl_spmatrix_complex_float * dest, const gsl_spmatrix_complex_float * src);\ngsl_spmatrix_complex_float * gsl_spmatrix_complex_float_compress (const gsl_spmatrix_complex_float * src, const int sptype);\ngsl_spmatrix_complex_float * gsl_spmatrix_complex_float_compcol (const gsl_spmatrix_complex_float * src);\ngsl_spmatrix_complex_float * gsl_spmatrix_complex_float_ccs (const gsl_spmatrix_complex_float * src);\ngsl_spmatrix_complex_float * gsl_spmatrix_complex_float_crs (const gsl_spmatrix_complex_float * src);\n\n/* copy */\n\nint gsl_spmatrix_complex_float_memcpy (gsl_spmatrix_complex_float * dest, const gsl_spmatrix_complex_float * src);\n\n/* file I/O */\n\nint gsl_spmatrix_complex_float_fprintf (FILE * stream, const gsl_spmatrix_complex_float * m, const char * format);\ngsl_spmatrix_complex_float * gsl_spmatrix_complex_float_fscanf (FILE * stream);\nint gsl_spmatrix_complex_float_fwrite (FILE * stream, const gsl_spmatrix_complex_float * m);\nint gsl_spmatrix_complex_float_fread (FILE * stream, gsl_spmatrix_complex_float * m);\n\n/* get/set */\n\ngsl_complex_float gsl_spmatrix_complex_float_get (const gsl_spmatrix_complex_float * m, const size_t i, const size_t j);\nint gsl_spmatrix_complex_float_set (gsl_spmatrix_complex_float * m, const size_t i, const size_t j, const gsl_complex_float x);\ngsl_complex_float * gsl_spmatrix_complex_float_ptr (const gsl_spmatrix_complex_float * m, const size_t i, const size_t j);\n\n/* operations */\n\nint gsl_spmatrix_complex_float_scale (gsl_spmatrix_complex_float * m, const gsl_complex_float x);\nint gsl_spmatrix_complex_float_scale_columns (gsl_spmatrix_complex_float * m, const gsl_vector_complex_float * x);\nint gsl_spmatrix_complex_float_scale_rows (gsl_spmatrix_complex_float * m, const gsl_vector_complex_float * x);\nint gsl_spmatrix_complex_float_add (gsl_spmatrix_complex_float * c, const gsl_spmatrix_complex_float * a, const gsl_spmatrix_complex_float * b);\nint gsl_spmatrix_complex_float_d2sp (gsl_spmatrix_complex_float * T, const gsl_matrix_complex_float * A);\nint gsl_spmatrix_complex_float_sp2d (gsl_matrix_complex_float * A, const gsl_spmatrix_complex_float * S);\n\n/* properties */\n\nint gsl_spmatrix_complex_float_equal (const gsl_spmatrix_complex_float * a, const gsl_spmatrix_complex_float * b);\n\n/* swap */\n\nint gsl_spmatrix_complex_float_transpose (gsl_spmatrix_complex_float * m);\nint gsl_spmatrix_complex_float_transpose2 (gsl_spmatrix_complex_float * m);\nint gsl_spmatrix_complex_float_transpose_memcpy (gsl_spmatrix_complex_float * dest, const gsl_spmatrix_complex_float * src);\n\n__END_DECLS\n\n#endif /* __GSL_SPMATRIX_COMPLEX_FLOAT_H__ */\n", "meta": {"hexsha": "fa216c7ab328eac3bf9a4c66f3e8c04142ace1ac", "size": 6595, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gsl/gsl_spmatrix_complex_float.h", "max_stars_repo_name": "vinej/sml", "max_stars_repo_head_hexsha": "115c007926ca80d51a37cdf887b5252338d8bc8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/gsl/gsl_spmatrix_complex_float.h", "max_issues_repo_name": "vinej/sml", "max_issues_repo_head_hexsha": "115c007926ca80d51a37cdf887b5252338d8bc8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gsl/gsl_spmatrix_complex_float.h", "max_forks_repo_name": "vinej/sml", "max_forks_repo_head_hexsha": "115c007926ca80d51a37cdf887b5252338d8bc8d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.3430232558, "max_line_length": 144, "alphanum_fraction": 0.7387414708, "num_tokens": 1785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29098086621490676, "lm_q2_score": 0.03114383267050219, "lm_q1q2_score": 0.00906225940771484}}
{"text": "\n/* Copyright (c) 2016, 2017 Bradley Worley <geekysuavo@gmail.com>\n * Released under the MIT License\n */\n\n/* ensure once-only inclusion. */\n#ifndef __MATTE_OBJECT_H__\n#define __MATTE_OBJECT_H__\n\n/* include required standard c library headers. */\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdarg.h>\n#include <stddef.h>\n#include <string.h>\n#include <stdbool.h>\n\n/* include required c math library headers. */\n#include <math.h>\n#include <complex.h>\n\n/* include the blas/lapack headers. */\n#include <cblas.h>\n#include <clapack.h>\n\n/* include the required matte headers. */\n#include <matte/zone.h>\n\n/* type definitions of blas/lapack enumerations:\n *  MatteTranspose: transpose options.\n *  MatteTriangle: triangle options.\n *  MatteDiagonal: diagonal options.\n */\ntypedef enum CBLAS_TRANSPOSE MatteTranspose;\ntypedef enum CBLAS_UPLO MatteTriangle;\ntypedef enum CBLAS_DIAG MatteDiagonal;\n\n/* MATTE_TYPE: macro to obtain the type structure pointer of an object.\n */\n#define MATTE_TYPE(obj) \\\n  (((Object) obj)->type)\n\n/* MATTE_TYPE_CHECK: macro to check that a matte object has a specific type.\n */\n#define MATTE_TYPE_CHECK(obj,typ) \\\n  ((obj) && MATTE_TYPE(obj) == typ)\n\n/* OBJECT_BASE: macro to place at the beginning of every matte object.\n * this allows all objects to be directly cast into the base object\n * type for memory management, dynamic dispatch, etc.\n */\n#define OBJECT_BASE \\\n  Object base;\n\n/* ObjectType: pointer to a struct _ObjectType. */\ntypedef struct _ObjectType *ObjectType;\n\n/* Object: pointer to a struct _Object. */\ntypedef struct _Object *Object;\n\n/* ObjectMethods: pointer to a struct _ObjectMethod. */\ntypedef struct _ObjectMethod *ObjectMethods;\n\n/* general-purpose function pointer type definition:\n */\ntypedef Object (*matte_func) (Zone, Object);\n\n/* function pointer type definitions for matte objects:\n */\ntypedef Object (*obj_constructor) (Zone, Object);\ntypedef void   (*obj_destructor)  (Zone, Object);\ntypedef int    (*obj_display)     (Zone, Object);\ntypedef int    (*obj_assert)      (Object);\ntypedef Object (*obj_unary)       (Zone, Object);\ntypedef Object (*obj_binary)      (Zone, Object, Object);\ntypedef Object (*obj_ternary)     (Zone, Object, Object, Object);\ntypedef Object (*obj_variadic)    (Zone, int, va_list);\ntypedef Object (*obj_method)      (Zone, Object, Object);\n\n/* _ObjectMethod: structure that holds information about a matte object\n * method.\n */\nstruct _ObjectMethod {\n  /* @name: string name of the method.\n   * @fn: method function pointer.\n   */\n  const char *name;\n  obj_method fn;\n};\n\n/* _ObjectType: structure that holds the core set of information required\n * by the matte object system.\n */\nstruct _ObjectType {\n  /* core object information:\n   *  @name: string name of the matte type.\n   *  @size: base size of the type struct.\n   *  @precedence: object precedence for dynamic dispatch.\n   */\n  const char *name;\n  unsigned int size;\n  unsigned int precedence;\n\n  /* core object method table:\n   */\n  obj_constructor fn_new;\n  obj_constructor fn_copy;\n  obj_destructor  fn_delete;\n  obj_display     fn_disp;\n  obj_assert      fn_true;\n\n  /* numeric method table:\n   */\n  obj_binary   fn_plus;        /* a+b      binary addition.             */\n  obj_binary   fn_minus;       /* a-b      binary subtraction.          */\n  obj_unary    fn_uminus;      /* -a       unary minus.                 */\n  obj_binary   fn_times;       /* a.*b     element-wise multiplication. */\n  obj_binary   fn_mtimes;      /* a*b      matrix multiplication.       */\n  obj_binary   fn_rdivide;     /* a./b     element-wise right division. */\n  obj_binary   fn_ldivide;     /* a.\\b     element-wise left division.  */\n  obj_binary   fn_mrdivide;    /* a/b      matrix right division.       */\n  obj_binary   fn_mldivide;    /* a\\b      matrix left division.        */\n  obj_binary   fn_power;       /* a.^b     element-wise power.          */\n  obj_binary   fn_mpower;      /* a^b      matrix power.                */\n  obj_binary   fn_lt;          /* a<b      less than.                   */\n  obj_binary   fn_gt;          /* a>b      greater than.                */\n  obj_binary   fn_le;          /* a<=b     less than or equal to.       */\n  obj_binary   fn_ge;          /* a>=b     greater than or equal to.    */\n  obj_binary   fn_ne;          /* a!=b     inequality.                  */\n  obj_binary   fn_eq;          /* a==b     equality.                    */\n  obj_binary   fn_and;         /* a&b      logical and.                 */\n  obj_binary   fn_or;          /* a|b      logical or.                  */\n  obj_binary   fn_mand;        /* a&&b     matrix logical and.          */\n  obj_binary   fn_mor;         /* a||b     matrix logical or.           */\n  obj_unary    fn_not;         /* !a       logical negation.            */\n  obj_ternary  fn_colon;       /* a:d:b    colon operator.              */\n  obj_unary    fn_ctranspose;  /* a'       conjugate transpose.         */\n  obj_unary    fn_transpose;   /* a.'      matrix transpose.            */\n  obj_variadic fn_horzcat;     /* [a,b]    horizontal concatenation.    */\n  obj_variadic fn_vertcat;     /* [a;b]    vertical concatenation.      */\n  obj_binary   fn_subsref;     /* a(s)     subscripted reference.       */\n  obj_ternary  fn_subsasgn;    /* a(s)=b   subscripted assignment.      */\n  obj_unary    fn_subsindex;   /* b(a)     subscript index.             */\n\n  /* general-purpose method table:\n   */\n  ObjectMethods methods;\n};\n\n/* _Object: structure for type-casting between any number of matte objects.\n * holds a pointer to the object type structure as its first element.\n */\nstruct _Object {\n  /* @type: the type of matte object that is located\n   * at the current address in memory.\n   */\n  ObjectType type;\n\n  /* in all other matte objects, object instance variables go here. */\n};\n\n/* function declarations (object.c): */\n\nObject object_alloc (Zone z, ObjectType type);\n\nObject object_copy (Zone z, Object obj);\n\nvoid object_free (Zone z, void *ptr);\n\nvoid object_free_all (Zone z);\n\nint object_disp (Zone z, Object obj);\n\nint object_display (Zone z, Object obj, const char *var);\n\nint object_true (Object obj);\n\n/* object method declarations (object.c): */\n\nObject object_plus       (Zone z, Object a, Object b);\nObject object_minus      (Zone z, Object a, Object b);\nObject object_uminus     (Zone z, Object a);\nObject object_times      (Zone z, Object a, Object b);\nObject object_mtimes     (Zone z, Object a, Object b);\nObject object_rdivide    (Zone z, Object a, Object b);\nObject object_ldivide    (Zone z, Object a, Object b);\nObject object_mrdivide   (Zone z, Object a, Object b);\nObject object_mldivide   (Zone z, Object a, Object b);\nObject object_power      (Zone z, Object a, Object b);\nObject object_mpower     (Zone z, Object a, Object b);\nObject object_lt         (Zone z, Object a, Object b);\nObject object_gt         (Zone z, Object a, Object b);\nObject object_le         (Zone z, Object a, Object b);\nObject object_ge         (Zone z, Object a, Object b);\nObject object_ne         (Zone z, Object a, Object b);\nObject object_eq         (Zone z, Object a, Object b);\nObject object_and        (Zone z, Object a, Object b);\nObject object_or         (Zone z, Object a, Object b);\nObject object_mand       (Zone z, Object a, Object b);\nObject object_mor        (Zone z, Object a, Object b);\nObject object_not        (Zone z, Object a);\nObject object_colon      (Zone z, Object a, Object b, Object c);\nObject object_ctranspose (Zone z, Object a);\nObject object_transpose  (Zone z, Object a);\nObject object_horzcat    (Zone z, int n, ...);\nObject object_vertcat    (Zone z, int n, ...);\nObject object_subsref    (Zone z, Object a, Object b);\nObject object_subsasgn   (Zone z, Object a, Object b, Object c);\nObject object_subsindex  (Zone z, Object a);\n\n/* utility function declarations: */\n\nchar *strdup (const char *s);\n\n#endif /* !__MATTE_OBJECT_H__ */\n\n", "meta": {"hexsha": "a64a60ff816e0b1e12f87ca83fe2a32932bc745d", "size": 7909, "ext": "h", "lang": "C", "max_stars_repo_path": "matte/object.h", "max_stars_repo_name": "geekysuavo/matte", "max_stars_repo_head_hexsha": "5bfbddb5aa3c9ff7451b47cbf6561b7f000a7cff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-03T07:58:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-03T23:47:43.000Z", "max_issues_repo_path": "matte/object.h", "max_issues_repo_name": "geekysuavo/matte", "max_issues_repo_head_hexsha": "5bfbddb5aa3c9ff7451b47cbf6561b7f000a7cff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "matte/object.h", "max_forks_repo_name": "geekysuavo/matte", "max_forks_repo_head_hexsha": "5bfbddb5aa3c9ff7451b47cbf6561b7f000a7cff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.4470046083, "max_line_length": 76, "alphanum_fraction": 0.6392717158, "num_tokens": 1978, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29098086621490676, "lm_q2_score": 0.03114383053477846, "lm_q1q2_score": 0.009062258786260099}}
{"text": "/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*\n**                                                                                  **\n** This file forms part of the Underworld geophysics modelling application.         **\n**                                                                                  **\n** For full license and copyright information, please refer to the LICENSE.md file  **\n** located at the project root, or contact the authors.                             **\n**                                                                                  **\n**~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/\n\n\n#ifndef __StgFEM_Discretisation_Discretisation_h__\n#define __StgFEM_Discretisation_Discretisation_h__\n\t\n\t\n\t#include \"types.h\"\n\n\t#include <petsc.h>\n\t#include <petscvec.h>\n\t#include <petscmat.h>\n\t#include <petscksp.h>\n#if( (PETSC_VERSION_MAJOR==3 && PETSC_VERSION_MINOR==0) || (PETSC_VERSION_MAJOR<3) )\n\t#include <petscmg.h>\n#endif\t\n\t#include <petscsnes.h>\n\t#include \"PETScErrorChecking.h\"\n\n\t#include \"FeMesh_Algorithms.h\"\n\t#include \"FeMesh_ElementType.h\"\n\t#include \"ElementType.h\"\n\t#include \"ElementType_Register.h\"\n\t#include \"ConstantElementType.h\"\n\t#include \"LinearElementType.h\"\n\t#include \"BilinearElementType.h\"\n\t#include \"TrilinearElementType.h\"\n\t#include \"Biquadratic.h\"\n\t#include \"Triquadratic.h\"\n\t#include \"LinearTriangleElementType.h\"\n\t#include \"BilinearInnerElType.h\"\n\t#include \"TrilinearInnerElType.h\"\n    #include \"dQ13DElementType.h\"\n    #include \"dQ12DElementType.h\"\n\t#include \"dQ1Generator.h\"\n\n    #include \"Element.h\"\n\t#include \"FeMesh.h\"\n\t#include \"C0Generator.h\"\n\t#include \"C2Generator.h\"\n\t#include \"Inner2DGenerator.h\"\n\t#include \"LinkedDofInfo.h\"\n\t#include \"FeEquationNumber.h\"\n\t#include \"FeVariable.h\"\n\n    #include \"IrregularMeshGaussLayout.h\"\n\n\t#include \"Init.h\"\n\t#include \"Finalise.h\"\n\n#endif /* __StgFEM_Discretisation_Discretisation_h__ */\n", "meta": {"hexsha": "63a9a010a5bdf5a005dc78b6273ad7e31b03703b", "size": 1963, "ext": "h", "lang": "C", "max_stars_repo_path": "underworld/libUnderworld/StgFEM/Discretisation/src/Discretisation.h", "max_stars_repo_name": "longgangfan/underworld2", "max_stars_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 116.0, "max_stars_repo_stars_event_min_datetime": "2015-09-28T10:30:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T04:12:38.000Z", "max_issues_repo_path": "underworld/libUnderworld/StgFEM/Discretisation/src/Discretisation.h", "max_issues_repo_name": "longgangfan/underworld2", "max_issues_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 561.0, "max_issues_repo_issues_event_min_datetime": "2015-09-29T06:05:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T23:37:29.000Z", "max_forks_repo_path": "underworld/libUnderworld/StgFEM/Discretisation/src/Discretisation.h", "max_forks_repo_name": "longgangfan/underworld2", "max_forks_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 68.0, "max_forks_repo_forks_event_min_datetime": "2015-12-14T21:57:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-25T04:54:26.000Z", "avg_line_length": 33.2711864407, "max_line_length": 87, "alphanum_fraction": 0.5736118186, "num_tokens": 590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33807712415000585, "lm_q2_score": 0.026759283670536, "lm_q1q2_score": 0.009046701667649024}}
{"text": "/* vector/gsl_vector_complex_double.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_VECTOR_COMPLEX_DOUBLE_H__\n#define __GSL_VECTOR_COMPLEX_DOUBLE_H__\n\n#if !defined( GSL_FUN )\n#  if !defined( GSL_DLL )\n#    define GSL_FUN extern\n#  elif defined( BUILD_GSL_DLL )\n#    define GSL_FUN extern __declspec(dllexport)\n#  else\n#    define GSL_FUN extern __declspec(dllimport)\n#  endif\n#endif\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_complex.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_vector_double.h>\n#include <gsl/gsl_vector_complex.h>\n#include <gsl/gsl_block_complex_double.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size;\n  size_t stride;\n  double *data;\n  gsl_block_complex *block;\n  int owner;\n} gsl_vector_complex;\n\ntypedef struct\n{\n  gsl_vector_complex vector;\n} _gsl_vector_complex_view;\n\ntypedef _gsl_vector_complex_view gsl_vector_complex_view;\n\ntypedef struct\n{\n  gsl_vector_complex vector;\n} _gsl_vector_complex_const_view;\n\ntypedef const _gsl_vector_complex_const_view gsl_vector_complex_const_view;\n\n/* Allocation */\n\nGSL_FUN gsl_vector_complex *gsl_vector_complex_alloc (const size_t n);\nGSL_FUN gsl_vector_complex *gsl_vector_complex_calloc (const size_t n);\n\nGSL_FUN gsl_vector_complex *\ngsl_vector_complex_alloc_from_block (gsl_block_complex * b, \n                                           const size_t offset, \n                                           const size_t n, \n                                           const size_t stride);\n\nGSL_FUN gsl_vector_complex *\ngsl_vector_complex_alloc_from_vector (gsl_vector_complex * v, \n                                             const size_t offset, \n                                             const size_t n, \n                                             const size_t stride);\n\nGSL_FUN void gsl_vector_complex_free (gsl_vector_complex * v);\n\n/* Views */\n\nGSL_FUN _gsl_vector_complex_view\ngsl_vector_complex_view_array (double *base,\n                                     size_t n);\n\nGSL_FUN _gsl_vector_complex_view\ngsl_vector_complex_view_array_with_stride (double *base,\n                                                 size_t stride,\n                                                 size_t n);\n\nGSL_FUN _gsl_vector_complex_const_view\ngsl_vector_complex_const_view_array (const double *base,\n                                           size_t n);\n\nGSL_FUN _gsl_vector_complex_const_view\ngsl_vector_complex_const_view_array_with_stride (const double *base,\n                                                       size_t stride,\n                                                       size_t n);\n\nGSL_FUN _gsl_vector_complex_view\ngsl_vector_complex_subvector (gsl_vector_complex *base,\n                                         size_t i, \n                                         size_t n);\n\n\nGSL_FUN _gsl_vector_complex_view \ngsl_vector_complex_subvector_with_stride (gsl_vector_complex *v, \n                                                size_t i, \n                                                size_t stride, \n                                                size_t n);\n\nGSL_FUN _gsl_vector_complex_const_view\ngsl_vector_complex_const_subvector (const gsl_vector_complex *base,\n                                               size_t i, \n                                               size_t n);\n\n\nGSL_FUN _gsl_vector_complex_const_view \ngsl_vector_complex_const_subvector_with_stride (const gsl_vector_complex *v, \n                                                      size_t i, \n                                                      size_t stride, \n                                                      size_t n);\n\nGSL_FUN _gsl_vector_view\ngsl_vector_complex_real (gsl_vector_complex *v);\n\nGSL_FUN _gsl_vector_view \ngsl_vector_complex_imag (gsl_vector_complex *v);\n\nGSL_FUN _gsl_vector_const_view\ngsl_vector_complex_const_real (const gsl_vector_complex *v);\n\nGSL_FUN _gsl_vector_const_view \ngsl_vector_complex_const_imag (const gsl_vector_complex *v);\n\n\n/* Operations */\n\nGSL_FUN void gsl_vector_complex_set_zero (gsl_vector_complex * v);\nGSL_FUN void gsl_vector_complex_set_all (gsl_vector_complex * v,\n                                       gsl_complex z);\nGSL_FUN int gsl_vector_complex_set_basis (gsl_vector_complex * v, size_t i);\n\nGSL_FUN int gsl_vector_complex_fread (FILE * stream,\n                                    gsl_vector_complex * v);\nGSL_FUN int gsl_vector_complex_fwrite (FILE * stream,\n                                     const gsl_vector_complex * v);\nGSL_FUN int gsl_vector_complex_fscanf (FILE * stream,\n                                     gsl_vector_complex * v);\nGSL_FUN int gsl_vector_complex_fprintf (FILE * stream,\n                                      const gsl_vector_complex * v,\n                                      const char *format);\n\nGSL_FUN int gsl_vector_complex_memcpy (gsl_vector_complex * dest, const gsl_vector_complex * src);\n\nGSL_FUN int gsl_vector_complex_reverse (gsl_vector_complex * v);\n\nGSL_FUN int gsl_vector_complex_swap (gsl_vector_complex * v, gsl_vector_complex * w);\nGSL_FUN int gsl_vector_complex_swap_elements (gsl_vector_complex * v, const size_t i, const size_t j);\n\nGSL_FUN int gsl_vector_complex_equal (const gsl_vector_complex * u, \n                                    const gsl_vector_complex * v);\n\nGSL_FUN int gsl_vector_complex_isnull (const gsl_vector_complex * v);\nGSL_FUN int gsl_vector_complex_ispos (const gsl_vector_complex * v);\nGSL_FUN int gsl_vector_complex_isneg (const gsl_vector_complex * v);\nGSL_FUN int gsl_vector_complex_isnonneg (const gsl_vector_complex * v);\n\nGSL_FUN int gsl_vector_complex_add (gsl_vector_complex * a, const gsl_vector_complex * b);\nGSL_FUN int gsl_vector_complex_sub (gsl_vector_complex * a, const gsl_vector_complex * b);\nGSL_FUN int gsl_vector_complex_mul (gsl_vector_complex * a, const gsl_vector_complex * b);\nGSL_FUN int gsl_vector_complex_div (gsl_vector_complex * a, const gsl_vector_complex * b);\nGSL_FUN int gsl_vector_complex_scale (gsl_vector_complex * a, const gsl_complex x);\nGSL_FUN int gsl_vector_complex_add_constant (gsl_vector_complex * a, const gsl_complex x);\n\nGSL_FUN INLINE_DECL gsl_complex gsl_vector_complex_get (const gsl_vector_complex * v, const size_t i);\nGSL_FUN INLINE_DECL void gsl_vector_complex_set (gsl_vector_complex * v, const size_t i, gsl_complex z);\nGSL_FUN INLINE_DECL gsl_complex *gsl_vector_complex_ptr (gsl_vector_complex * v, const size_t i);\nGSL_FUN INLINE_DECL const gsl_complex *gsl_vector_complex_const_ptr (const gsl_vector_complex * v, const size_t i);\n\n#ifdef HAVE_INLINE\n\nINLINE_FUN\ngsl_complex\ngsl_vector_complex_get (const gsl_vector_complex * v,\n                              const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= v->size))\n    {\n      gsl_complex zero = {{0, 0}};\n      GSL_ERROR_VAL (\"index out of range\", GSL_EINVAL, zero);\n    }\n#endif\n  return *GSL_COMPLEX_AT (v, i);\n}\n\nINLINE_FUN\nvoid\ngsl_vector_complex_set (gsl_vector_complex * v,\n                              const size_t i, gsl_complex z)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= v->size))\n    {\n      GSL_ERROR_VOID (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  *GSL_COMPLEX_AT (v, i) = z;\n}\n\nINLINE_FUN\ngsl_complex *\ngsl_vector_complex_ptr (gsl_vector_complex * v,\n                              const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= v->size))\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return GSL_COMPLEX_AT (v, i);\n}\n\nINLINE_FUN\nconst gsl_complex *\ngsl_vector_complex_const_ptr (const gsl_vector_complex * v,\n                                    const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= v->size))\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return GSL_COMPLEX_AT (v, i);\n}\n\n\n#endif /* HAVE_INLINE */\n\n__END_DECLS\n\n#endif /* __GSL_VECTOR_COMPLEX_DOUBLE_H__ */\n", "meta": {"hexsha": "4b84c426598cd20834348fcf906ee884ad86e5b5", "size": 8845, "ext": "h", "lang": "C", "max_stars_repo_path": "mbsysCopy/win64_include_lib/include/gsl/gsl_vector_complex_double.h", "max_stars_repo_name": "mharding01/augmented-neuromuscular-RT-running", "max_stars_repo_head_hexsha": "7e1ef00d3fdf9cfa9d59fc4f3a6a0e6dd792a834", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mbsysCopy/win64_include_lib/include/gsl/gsl_vector_complex_double.h", "max_issues_repo_name": "mharding01/augmented-neuromuscular-RT-running", "max_issues_repo_head_hexsha": "7e1ef00d3fdf9cfa9d59fc4f3a6a0e6dd792a834", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mbsysCopy/win64_include_lib/include/gsl/gsl_vector_complex_double.h", "max_forks_repo_name": "mharding01/augmented-neuromuscular-RT-running", "max_forks_repo_head_hexsha": "7e1ef00d3fdf9cfa9d59fc4f3a6a0e6dd792a834", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7595419847, "max_line_length": 115, "alphanum_fraction": 0.6650084794, "num_tokens": 1973, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33807711081162, "lm_q2_score": 0.02675928202122034, "lm_q1q2_score": 0.0090467007531275}}
{"text": "/*\n  Copyright [2021] [IBM Corporation]\n  Licensed under the Apache License, Version 2.0 (the \"License\");\n  you may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n  http://www.apache.org/licenses/LICENSE-2.0\n  Unless required by applicable law or agreed to in writing, software\n  distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions and\n  limitations under the License.\n*/\n\n#ifndef _MCAS_NUMA_NODE_MASK__H_\n#define _MCAS_NUMA_NODE_MASK__H_\n\n#include <numa.h> /* bitmask */\n#include <common/string_view.h>\n#include <gsl/pointers> /* not_null */\n#include <memory> /* unique_ptr */\n\nstruct numa_node_mask_dtor\n{\n\tvoid operator()(bitmask *b) { numa_free_nodemask(b); }\n};\n\nstruct numa_node_mask\n{\n\tnuma_node_mask(common::string_view mask_)\n\t\t: _mask(std::unique_ptr<bitmask, numa_node_mask_dtor>(mask_not_null(std::string(mask_))))\n\t{\n\t}\n\tnuma_node_mask(const bitmask *b)\n\t\t: _mask(std::unique_ptr<bitmask, numa_node_mask_dtor>(numa_allocate_nodemask()))\n\t{\n\t\tcopy_bitmask_to_bitmask(const_cast<bitmask *>(b), get());\n\t}\n\tconst bitmask *get() const { return _mask.get().get(); }\n\tbitmask *get() { return _mask.get().get(); }\n\t/* get first 64 bits in mask */\n\tuint64_t get64()\n\t{\n\t\tuint64_t r = 0;\n\t\tfor ( unsigned i = 0; i != 64; ++i )\n\t\t{\n\t\t\tif ( numa_bitmask_isbitset(get(), i) )\n\t\t\t{\n\t\t\t\tr |= ( 1U << i );\n\t\t\t}\n\t\t}\n\t\treturn r;\n\t}\nprivate:\n\tstatic bitmask *mask_not_null(common::string_view mask_)\n\t{\n\t\tauto m = numa_parse_nodestring(std::string(mask_).c_str());\n\t\treturn m ? m : numa_allocate_nodemask();\n\t}\n\tgsl::not_null<std::unique_ptr<bitmask, numa_node_mask_dtor>> _mask;\n};\n\n#endif\n", "meta": {"hexsha": "92e04091f76543998f6cb50d9967beb385c719db", "size": 1793, "ext": "h", "lang": "C", "max_stars_repo_path": "src/components/store/mapstore/src/numa_node_mask.h", "max_stars_repo_name": "IBM/artemis", "max_stars_repo_head_hexsha": "f655d6e952577de11b52e2f4ab6f48c73ce5dba1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/components/store/mapstore/src/numa_node_mask.h", "max_issues_repo_name": "IBM/artemis", "max_issues_repo_head_hexsha": "f655d6e952577de11b52e2f4ab6f48c73ce5dba1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/components/store/mapstore/src/numa_node_mask.h", "max_forks_repo_name": "IBM/artemis", "max_forks_repo_head_hexsha": "f655d6e952577de11b52e2f4ab6f48c73ce5dba1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4603174603, "max_line_length": 91, "alphanum_fraction": 0.7116564417, "num_tokens": 503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32766830082071396, "lm_q2_score": 0.02758528272643216, "lm_q1q2_score": 0.009038822718629018}}
{"text": "#pragma once\n\n#include <gsl/span>\n\n#include <cstddef>\n\nnamespace imageview {\n\n// Implementation of the PixelFormat concept for the 8-bit grayscale pixel\n// format.\nclass PixelFormatGrayscale8 {\n public:\n  using color_type = unsigned char;\n  static constexpr int kBytesPerPixel = 1;\n\n  constexpr color_type read(gsl::span<const std::byte, kBytesPerPixel> data) const;\n\n  constexpr void write(const color_type& color, gsl::span<std::byte, kBytesPerPixel> data) const;\n};\n\nconstexpr PixelFormatGrayscale8::color_type PixelFormatGrayscale8::read(\n    gsl::span<const std::byte, kBytesPerPixel> data) const {\n  return static_cast<color_type>(data[0]);\n}\n\nconstexpr void PixelFormatGrayscale8::write(const color_type& color, gsl::span<std::byte, kBytesPerPixel> data) const {\n  data[0] = static_cast<std::byte>(color);\n}\n\n}  // namespace imageview\n", "meta": {"hexsha": "c7fa95940211594cfbe2cc3a94e7f4ac46a8f389", "size": 842, "ext": "h", "lang": "C", "max_stars_repo_path": "include/imageview/pixel_formats/PixelFormatGrayscale8.h", "max_stars_repo_name": "alexanderbelous/imageview", "max_stars_repo_head_hexsha": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/imageview/pixel_formats/PixelFormatGrayscale8.h", "max_issues_repo_name": "alexanderbelous/imageview", "max_issues_repo_head_hexsha": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/imageview/pixel_formats/PixelFormatGrayscale8.h", "max_forks_repo_name": "alexanderbelous/imageview", "max_forks_repo_head_hexsha": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1612903226, "max_line_length": 119, "alphanum_fraction": 0.7553444181, "num_tokens": 211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21733753118592733, "lm_q2_score": 0.04146226812171166, "lm_q1q2_score": 0.009011306990941789}}
{"text": "/* histogram/file.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#include <config.h>\n#include <stdio.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_block.h>\n#include <gsl/gsl_histogram.h>\n\nint\ngsl_histogram_fread (FILE * stream, gsl_histogram * h)\n{\n  int status = gsl_block_raw_fread (stream, h->range, h->n + 1, 1);\n\n  if (status)\n    return status;\n\n  status = gsl_block_raw_fread (stream, h->bin, h->n, 1);\n  return status;\n}\n\nint\ngsl_histogram_fwrite (FILE * stream, const gsl_histogram * h)\n{\n  int status = gsl_block_raw_fwrite (stream, h->range, h->n + 1, 1);\n\n  if (status)\n    return status;\n\n  status = gsl_block_raw_fwrite (stream, h->bin, h->n, 1);\n  return status;\n}\n\nint\ngsl_histogram_fprintf (FILE * stream, const gsl_histogram * h,\n\t\t       const char *range_format, const char *bin_format)\n{\n  size_t i;\n  const size_t n = h->n;\n\n  for (i = 0; i < n; i++)\n    {\n      int status = fprintf (stream, range_format, h->range[i]);\n\n      if (status < 0)\n\t{\n\t  GSL_ERROR (\"fprintf failed\", GSL_EFAILED);\n\t}\n\n      status = putc (' ', stream);\n\n      if (status == EOF)\n\t{\n\t  GSL_ERROR (\"putc failed\", GSL_EFAILED);\n\t}\n\n      status = fprintf (stream, range_format, h->range[i + 1]);\n\n      if (status < 0)\n\t{\n\t  GSL_ERROR (\"fprintf failed\", GSL_EFAILED);\n\t}\n\n      status = putc (' ', stream);\n\n      if (status == EOF)\n\t{\n\t  GSL_ERROR (\"putc failed\", GSL_EFAILED);\n\t}\n\n      status = fprintf (stream, bin_format, h->bin[i]);\n\n      if (status < 0)\n\t{\n\t  GSL_ERROR (\"fprintf failed\", GSL_EFAILED);\n\t}\n\n      status = putc ('\\n', stream);\n\n      if (status == EOF)\n\t{\n\t  GSL_ERROR (\"putc failed\", GSL_EFAILED);\n\t}\n    }\n\n  return GSL_SUCCESS;\n}\n\nint\ngsl_histogram_fscanf (FILE * stream, gsl_histogram * h)\n{\n  size_t i;\n  const size_t n = h->n;\n  double upper;\n\n  for (i = 0; i < n; i++)\n    {\n      int status = fscanf (stream,\n\t\t\t   \"%lg %lg %lg\", h->range + i, &upper,\n\t\t\t   h->bin + i);\n\n      if (status != 3)\n\t{\n\t  GSL_ERROR (\"fscanf failed\", GSL_EFAILED);\n\t}\n    }\n\n  h->range[n] = upper;\n\n  return GSL_SUCCESS;\n}\n", "meta": {"hexsha": "031d81f4ba5d5cde5dd1b6699f5e04a090fb65de", "size": 2758, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/histogram/file.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/histogram/file.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/histogram/file.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 21.546875, "max_line_length": 72, "alphanum_fraction": 0.6348803481, "num_tokens": 803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33111975283019596, "lm_q2_score": 0.02716923025565704, "lm_q1q2_score": 0.008996268806839841}}
{"text": "#pragma once\n\n#include <string>\n#include <gsl/span>\n\nnamespace crypto {\n\n\t/*\n\t\tUse the Windows CNG API to compute a MD5 hash of the\n\t\tprovided data view and return it as a lowercase hex\n\t\tstring.\n\t*/\n\tstd::string MD5AsString(gsl::span<uint8_t> data);\n\n}\n", "meta": {"hexsha": "9113310ed79d4bcc62f167a80174a9f497f9436f", "size": 254, "ext": "h", "lang": "C", "max_stars_repo_path": "Infrastructure/include/infrastructure/crypto.h", "max_stars_repo_name": "edoipi/TemplePlus", "max_stars_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 69.0, "max_stars_repo_stars_event_min_datetime": "2015-05-05T14:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T06:13:04.000Z", "max_issues_repo_path": "Infrastructure/include/infrastructure/crypto.h", "max_issues_repo_name": "edoipi/TemplePlus", "max_issues_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 457.0, "max_issues_repo_issues_event_min_datetime": "2015-05-01T22:07:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T02:19:10.000Z", "max_forks_repo_path": "Infrastructure/include/infrastructure/crypto.h", "max_forks_repo_name": "edoipi/TemplePlus", "max_forks_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2016-02-04T21:19:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T23:14:51.000Z", "avg_line_length": 15.875, "max_line_length": 54, "alphanum_fraction": 0.7047244094, "num_tokens": 69, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3738758367247085, "lm_q2_score": 0.024053552019915058, "lm_q1q2_score": 0.008993041887647045}}
{"text": "#pragma once\n\n#include <gsl/span>\n#include <array>\n#include \"halley/core/api/audio_api.h\"\n\nnamespace Halley\n{\n\tusing AudioSourceData = std::array<gsl::span<AudioConfig::SampleFormat>, AudioConfig::maxChannels>;\n\n\tclass AudioSource {\n\tpublic:\n\t\tvirtual ~AudioSource() {}\n\n\t\tvirtual size_t getNumberOfChannels() const = 0;\n\t\tvirtual bool isReady() const { return true; }\n\t\tvirtual bool getAudioData(size_t numSamples, AudioSourceData& dst) = 0;\n\t};\n}\n", "meta": {"hexsha": "22aa245b14a782a7ee9246444d2e029dfdbdc461", "size": 449, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engine/audio/src/audio_source.h", "max_stars_repo_name": "lye/halley", "max_stars_repo_head_hexsha": "16b6c9783e4b21377f902a9d02366c1f19450a21", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T20:23:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T20:23:45.000Z", "max_issues_repo_path": "src/engine/audio/src/audio_source.h", "max_issues_repo_name": "lye/halley", "max_issues_repo_head_hexsha": "16b6c9783e4b21377f902a9d02366c1f19450a21", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engine/audio/src/audio_source.h", "max_forks_repo_name": "lye/halley", "max_forks_repo_head_hexsha": "16b6c9783e4b21377f902a9d02366c1f19450a21", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.45, "max_line_length": 100, "alphanum_fraction": 0.7349665924, "num_tokens": 111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2751297119360208, "lm_q2_score": 0.03258974464857568, "lm_q1q2_score": 0.008966407057231104}}
{"text": "#include <stdio.h>\n#include <stdarg.h>\n#include <string.h>\n#include <math.h>\n#include <gbpLib.h>\n#include <gbpRNG.h>\n#include <gbpMCMC.h>\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_fit.h>\n#include <gsl/gsl_interp.h>\n\nvoid restart_MCMC(MCMC_info *MCMC) {\n    SID_log(\"Resetting MCMC structure for a fresh run...\", SID_LOG_OPEN);\n\n    MCMC->flag_integrate_on     = GBP_FALSE;\n    MCMC->flag_analysis_on      = GBP_TRUE;\n    MCMC->first_map_call        = GBP_TRUE;\n    MCMC->first_link_call       = GBP_TRUE;\n    MCMC->flag_init_chain       = GBP_TRUE;\n    MCMC->first_chain_call      = GBP_TRUE;\n    MCMC->first_parameter_call  = GBP_TRUE;\n    MCMC->first_likelihood_call = GBP_TRUE;\n    MCMC->ln_likelihood_last    = 0.;\n    MCMC->ln_likelihood_new     = 0.;\n    MCMC->ln_likelihood_chain   = 0.;\n    MCMC->n_success             = 0;\n    MCMC->n_propositions        = 0;\n    MCMC->n_map_calls           = 0;\n\n    free_MCMC_covariance(MCMC);\n    free_MCMC_arrays(MCMC);\n\n    SID_log(\"Done.\", SID_LOG_CLOSE);\n}\n", "meta": {"hexsha": "b8c6260790b3f1df569d62b1dd9773ee8cc01ac1", "size": 1011, "ext": "c", "lang": "C", "max_stars_repo_path": "src/gbpMath/gbpMCMC/restart_MCMC.c", "max_stars_repo_name": "gbpoole/gbpCode", "max_stars_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-10-20T11:39:53.000Z", "max_stars_repo_stars_event_max_datetime": "2015-10-20T11:39:53.000Z", "max_issues_repo_path": "src/gbpMath/gbpMCMC/restart_MCMC.c", "max_issues_repo_name": "gbpoole/gbpCode", "max_issues_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-07-30T11:10:49.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-18T00:40:46.000Z", "max_forks_repo_path": "src/gbpMath/gbpMCMC/restart_MCMC.c", "max_forks_repo_name": "gbpoole/gbpCode", "max_forks_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-01-23T00:50:40.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-01T08:14:24.000Z", "avg_line_length": 28.8857142857, "max_line_length": 73, "alphanum_fraction": 0.6478733927, "num_tokens": 320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2751297238231752, "lm_q2_score": 0.032589743004280476, "lm_q1q2_score": 0.008966406992235942}}
{"text": "/* matrix/gsl_matrix_complex_float.h\r\n * \r\n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\r\n * \r\n * This program is free software; you can redistribute it and/or modify\r\n * it under the terms of the GNU General Public License as published by\r\n * the Free Software Foundation; either version 3 of the License, or (at\r\n * your option) any later version.\r\n * \r\n * This program is distributed in the hope that it will be useful, but\r\n * WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n * General Public License for more details.\r\n * \r\n * You should have received a copy of the GNU General Public License\r\n * along with this program; if not, write to the Free Software\r\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r\n */\r\n\r\n#ifndef __GSL_MATRIX_COMPLEX_FLOAT_H__\r\n#define __GSL_MATRIX_COMPLEX_FLOAT_H__\r\n\r\n#if !defined( GSL_FUN )\r\n#  if !defined( GSL_DLL )\r\n#    define GSL_FUN extern\r\n#  elif defined( BUILD_GSL_DLL )\r\n#    define GSL_FUN extern __declspec(dllexport)\r\n#  else\r\n#    define GSL_FUN extern __declspec(dllimport)\r\n#  endif\r\n#endif\r\n\r\n#include <stdlib.h>\r\n#include <gsl/gsl_types.h>\r\n#include <gsl/gsl_errno.h>\r\n#include <gsl/gsl_complex.h>\r\n#include <gsl/gsl_check_range.h>\r\n#include <gsl/gsl_vector_complex_float.h>\r\n\r\n#undef __BEGIN_DECLS\r\n#undef __END_DECLS\r\n#ifdef __cplusplus\r\n# define __BEGIN_DECLS extern \"C\" {\r\n# define __END_DECLS }\r\n#else\r\n# define __BEGIN_DECLS /* empty */\r\n# define __END_DECLS /* empty */\r\n#endif\r\n\r\n__BEGIN_DECLS\r\n\r\ntypedef struct \r\n{\r\n  size_t size1;\r\n  size_t size2;\r\n  size_t tda;\r\n  float * data;\r\n  gsl_block_complex_float * block;\r\n  int owner;\r\n} gsl_matrix_complex_float ;\r\n\r\ntypedef struct\r\n{\r\n  gsl_matrix_complex_float matrix;\r\n} _gsl_matrix_complex_float_view;\r\n\r\ntypedef _gsl_matrix_complex_float_view gsl_matrix_complex_float_view;\r\n\r\ntypedef struct\r\n{\r\n  gsl_matrix_complex_float matrix;\r\n} _gsl_matrix_complex_float_const_view;\r\n\r\ntypedef const _gsl_matrix_complex_float_const_view gsl_matrix_complex_float_const_view;\r\n\r\n\r\n/* Allocation */\r\n\r\nGSL_FUN gsl_matrix_complex_float * \r\ngsl_matrix_complex_float_alloc (const size_t n1, const size_t n2);\r\n\r\nGSL_FUN gsl_matrix_complex_float * \r\ngsl_matrix_complex_float_calloc (const size_t n1, const size_t n2);\r\n\r\nGSL_FUN gsl_matrix_complex_float * \r\ngsl_matrix_complex_float_alloc_from_block (gsl_block_complex_float * b, \r\n                                           const size_t offset, \r\n                                           const size_t n1, const size_t n2, const size_t d2);\r\n\r\nGSL_FUN gsl_matrix_complex_float * \r\ngsl_matrix_complex_float_alloc_from_matrix (gsl_matrix_complex_float * b,\r\n                                            const size_t k1, const size_t k2,\r\n                                            const size_t n1, const size_t n2);\r\n\r\nGSL_FUN gsl_vector_complex_float * \r\ngsl_vector_complex_float_alloc_row_from_matrix (gsl_matrix_complex_float * m,\r\n                                                const size_t i);\r\n\r\nGSL_FUN gsl_vector_complex_float * \r\ngsl_vector_complex_float_alloc_col_from_matrix (gsl_matrix_complex_float * m,\r\n                                                const size_t j);\r\n\r\nGSL_FUN void gsl_matrix_complex_float_free (gsl_matrix_complex_float * m);\r\n\r\n/* Views */\r\n\r\nGSL_FUN _gsl_matrix_complex_float_view \r\ngsl_matrix_complex_float_submatrix (gsl_matrix_complex_float * m, \r\n                            const size_t i, const size_t j, \r\n                            const size_t n1, const size_t n2);\r\n\r\nGSL_FUN _gsl_vector_complex_float_view \r\ngsl_matrix_complex_float_row (gsl_matrix_complex_float * m, const size_t i);\r\n\r\nGSL_FUN _gsl_vector_complex_float_view \r\ngsl_matrix_complex_float_column (gsl_matrix_complex_float * m, const size_t j);\r\n\r\nGSL_FUN _gsl_vector_complex_float_view \r\ngsl_matrix_complex_float_diagonal (gsl_matrix_complex_float * m);\r\n\r\nGSL_FUN _gsl_vector_complex_float_view \r\ngsl_matrix_complex_float_subdiagonal (gsl_matrix_complex_float * m, const size_t k);\r\n\r\nGSL_FUN _gsl_vector_complex_float_view \r\ngsl_matrix_complex_float_superdiagonal (gsl_matrix_complex_float * m, const size_t k);\r\n\r\nGSL_FUN _gsl_vector_complex_float_view\r\ngsl_matrix_complex_float_subrow (gsl_matrix_complex_float * m,\r\n                                 const size_t i, const size_t offset,\r\n                                 const size_t n);\r\n\r\nGSL_FUN _gsl_vector_complex_float_view\r\ngsl_matrix_complex_float_subcolumn (gsl_matrix_complex_float * m,\r\n                                    const size_t j, const size_t offset,\r\n                                    const size_t n);\r\n\r\nGSL_FUN _gsl_matrix_complex_float_view\r\ngsl_matrix_complex_float_view_array (float * base,\r\n                             const size_t n1, \r\n                             const size_t n2);\r\n\r\nGSL_FUN _gsl_matrix_complex_float_view\r\ngsl_matrix_complex_float_view_array_with_tda (float * base, \r\n                                      const size_t n1, \r\n                                      const size_t n2,\r\n                                      const size_t tda);\r\n\r\nGSL_FUN _gsl_matrix_complex_float_view\r\ngsl_matrix_complex_float_view_vector (gsl_vector_complex_float * v,\r\n                              const size_t n1, \r\n                              const size_t n2);\r\n\r\nGSL_FUN _gsl_matrix_complex_float_view\r\ngsl_matrix_complex_float_view_vector_with_tda (gsl_vector_complex_float * v,\r\n                                       const size_t n1, \r\n                                       const size_t n2,\r\n                                       const size_t tda);\r\n\r\n\r\nGSL_FUN _gsl_matrix_complex_float_const_view \r\ngsl_matrix_complex_float_const_submatrix (const gsl_matrix_complex_float * m, \r\n                                  const size_t i, const size_t j, \r\n                                  const size_t n1, const size_t n2);\r\n\r\nGSL_FUN _gsl_vector_complex_float_const_view \r\ngsl_matrix_complex_float_const_row (const gsl_matrix_complex_float * m, \r\n                            const size_t i);\r\n\r\nGSL_FUN _gsl_vector_complex_float_const_view \r\ngsl_matrix_complex_float_const_column (const gsl_matrix_complex_float * m, \r\n                               const size_t j);\r\n\r\nGSL_FUN _gsl_vector_complex_float_const_view\r\ngsl_matrix_complex_float_const_diagonal (const gsl_matrix_complex_float * m);\r\n\r\nGSL_FUN _gsl_vector_complex_float_const_view \r\ngsl_matrix_complex_float_const_subdiagonal (const gsl_matrix_complex_float * m, \r\n                                    const size_t k);\r\n\r\nGSL_FUN _gsl_vector_complex_float_const_view \r\ngsl_matrix_complex_float_const_superdiagonal (const gsl_matrix_complex_float * m, \r\n                                      const size_t k);\r\n\r\nGSL_FUN _gsl_vector_complex_float_const_view\r\ngsl_matrix_complex_float_const_subrow (const gsl_matrix_complex_float * m,\r\n                                       const size_t i, const size_t offset,\r\n                                       const size_t n);\r\n\r\nGSL_FUN _gsl_vector_complex_float_const_view\r\ngsl_matrix_complex_float_const_subcolumn (const gsl_matrix_complex_float * m,\r\n                                          const size_t j, const size_t offset,\r\n                                          const size_t n);\r\n\r\nGSL_FUN _gsl_matrix_complex_float_const_view\r\ngsl_matrix_complex_float_const_view_array (const float * base,\r\n                                   const size_t n1, \r\n                                   const size_t n2);\r\n\r\nGSL_FUN _gsl_matrix_complex_float_const_view\r\ngsl_matrix_complex_float_const_view_array_with_tda (const float * base, \r\n                                            const size_t n1, \r\n                                            const size_t n2,\r\n                                            const size_t tda);\r\n\r\nGSL_FUN _gsl_matrix_complex_float_const_view\r\ngsl_matrix_complex_float_const_view_vector (const gsl_vector_complex_float * v,\r\n                                    const size_t n1, \r\n                                    const size_t n2);\r\n\r\nGSL_FUN _gsl_matrix_complex_float_const_view\r\ngsl_matrix_complex_float_const_view_vector_with_tda (const gsl_vector_complex_float * v,\r\n                                             const size_t n1, \r\n                                             const size_t n2,\r\n                                             const size_t tda);\r\n\r\n/* Operations */\r\n\r\nGSL_FUN void gsl_matrix_complex_float_set_zero (gsl_matrix_complex_float * m);\r\nGSL_FUN void gsl_matrix_complex_float_set_identity (gsl_matrix_complex_float * m);\r\nGSL_FUN void gsl_matrix_complex_float_set_all (gsl_matrix_complex_float * m, gsl_complex_float x);\r\n\r\nGSL_FUN int gsl_matrix_complex_float_fread (FILE * stream, gsl_matrix_complex_float * m) ;\r\nGSL_FUN int gsl_matrix_complex_float_fwrite (FILE * stream, const gsl_matrix_complex_float * m) ;\r\nGSL_FUN int gsl_matrix_complex_float_fscanf (FILE * stream, gsl_matrix_complex_float * m);\r\nGSL_FUN int gsl_matrix_complex_float_fprintf (FILE * stream, const gsl_matrix_complex_float * m, const char * format);\r\n\r\nGSL_FUN int gsl_matrix_complex_float_memcpy(gsl_matrix_complex_float * dest, const gsl_matrix_complex_float * src);\r\nGSL_FUN int gsl_matrix_complex_float_swap(gsl_matrix_complex_float * m1, gsl_matrix_complex_float * m2);\r\n\r\nGSL_FUN int gsl_matrix_complex_float_swap_rows(gsl_matrix_complex_float * m, const size_t i, const size_t j);\r\nGSL_FUN int gsl_matrix_complex_float_swap_columns(gsl_matrix_complex_float * m, const size_t i, const size_t j);\r\nGSL_FUN int gsl_matrix_complex_float_swap_rowcol(gsl_matrix_complex_float * m, const size_t i, const size_t j);\r\n\r\nGSL_FUN int gsl_matrix_complex_float_transpose (gsl_matrix_complex_float * m);\r\nGSL_FUN int gsl_matrix_complex_float_transpose_memcpy (gsl_matrix_complex_float * dest, const gsl_matrix_complex_float * src);\r\n\r\nGSL_FUN int gsl_matrix_complex_float_isnull (const gsl_matrix_complex_float * m);\r\nGSL_FUN int gsl_matrix_complex_float_ispos (const gsl_matrix_complex_float * m);\r\nGSL_FUN int gsl_matrix_complex_float_isneg (const gsl_matrix_complex_float * m);\r\nGSL_FUN int gsl_matrix_complex_float_isnonneg (const gsl_matrix_complex_float * m);\r\n\r\nGSL_FUN int gsl_matrix_complex_float_add (gsl_matrix_complex_float * a, const gsl_matrix_complex_float * b);\r\nGSL_FUN int gsl_matrix_complex_float_sub (gsl_matrix_complex_float * a, const gsl_matrix_complex_float * b);\r\nGSL_FUN int gsl_matrix_complex_float_mul_elements (gsl_matrix_complex_float * a, const gsl_matrix_complex_float * b);\r\nGSL_FUN int gsl_matrix_complex_float_div_elements (gsl_matrix_complex_float * a, const gsl_matrix_complex_float * b);\r\nGSL_FUN int gsl_matrix_complex_float_scale (gsl_matrix_complex_float * a, const gsl_complex_float x);\r\nGSL_FUN int gsl_matrix_complex_float_add_constant (gsl_matrix_complex_float * a, const gsl_complex_float x);\r\nGSL_FUN int gsl_matrix_complex_float_add_diagonal (gsl_matrix_complex_float * a, const gsl_complex_float x);\r\n\r\n/***********************************************************************/\r\n/* The functions below are obsolete                                    */\r\n/***********************************************************************/\r\nGSL_FUN int gsl_matrix_complex_float_get_row(gsl_vector_complex_float * v, const gsl_matrix_complex_float * m, const size_t i);\r\nGSL_FUN int gsl_matrix_complex_float_get_col(gsl_vector_complex_float * v, const gsl_matrix_complex_float * m, const size_t j);\r\nGSL_FUN int gsl_matrix_complex_float_set_row(gsl_matrix_complex_float * m, const size_t i, const gsl_vector_complex_float * v);\r\nGSL_FUN int gsl_matrix_complex_float_set_col(gsl_matrix_complex_float * m, const size_t j, const gsl_vector_complex_float * v);\r\n/***********************************************************************/\r\n\r\n/* inline functions if you are using GCC */\r\n\r\nGSL_FUN INLINE_DECL gsl_complex_float gsl_matrix_complex_float_get(const gsl_matrix_complex_float * m, const size_t i, const size_t j);\r\nGSL_FUN INLINE_DECL void gsl_matrix_complex_float_set(gsl_matrix_complex_float * m, const size_t i, const size_t j, const gsl_complex_float x);\r\n\r\nGSL_FUN INLINE_DECL gsl_complex_float * gsl_matrix_complex_float_ptr(gsl_matrix_complex_float * m, const size_t i, const size_t j);\r\nGSL_FUN INLINE_DECL const gsl_complex_float * gsl_matrix_complex_float_const_ptr(const gsl_matrix_complex_float * m, const size_t i, const size_t j);\r\n\r\n#ifdef HAVE_INLINE\r\n\r\nINLINE_FUN \r\ngsl_complex_float\r\ngsl_matrix_complex_float_get(const gsl_matrix_complex_float * m, \r\n                     const size_t i, const size_t j)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(1)) \r\n    {\r\n      gsl_complex_float zero = {{0,0}};\r\n\r\n      if (i >= m->size1)\r\n        {\r\n          GSL_ERROR_VAL(\"first index out of range\", GSL_EINVAL, zero) ;\r\n        }\r\n      else if (j >= m->size2)\r\n        {\r\n          GSL_ERROR_VAL(\"second index out of range\", GSL_EINVAL, zero) ;\r\n        }\r\n    }\r\n#endif\r\n  return *(gsl_complex_float *)(m->data + 2*(i * m->tda + j)) ;\r\n} \r\n\r\nINLINE_FUN \r\nvoid\r\ngsl_matrix_complex_float_set(gsl_matrix_complex_float * m, \r\n                     const size_t i, const size_t j, const gsl_complex_float x)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(1)) \r\n    {\r\n      if (i >= m->size1)\r\n        {\r\n          GSL_ERROR_VOID(\"first index out of range\", GSL_EINVAL) ;\r\n        }\r\n      else if (j >= m->size2)\r\n        {\r\n          GSL_ERROR_VOID(\"second index out of range\", GSL_EINVAL) ;\r\n        }\r\n    }\r\n#endif\r\n  *(gsl_complex_float *)(m->data + 2*(i * m->tda + j)) = x ;\r\n}\r\n\r\nINLINE_FUN \r\ngsl_complex_float *\r\ngsl_matrix_complex_float_ptr(gsl_matrix_complex_float * m, \r\n                             const size_t i, const size_t j)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(1)) \r\n    {\r\n      if (i >= m->size1)\r\n        {\r\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\r\n        }\r\n      else if (j >= m->size2)\r\n        {\r\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\r\n        }\r\n    }\r\n#endif\r\n  return (gsl_complex_float *)(m->data + 2*(i * m->tda + j)) ;\r\n} \r\n\r\nINLINE_FUN \r\nconst gsl_complex_float *\r\ngsl_matrix_complex_float_const_ptr(const gsl_matrix_complex_float * m, \r\n                                   const size_t i, const size_t j)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(1)) \r\n    {\r\n      if (i >= m->size1)\r\n        {\r\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\r\n        }\r\n      else if (j >= m->size2)\r\n        {\r\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\r\n        }\r\n    }\r\n#endif\r\n  return (const gsl_complex_float *)(m->data + 2*(i * m->tda + j)) ;\r\n} \r\n\r\n#endif /* HAVE_INLINE */\r\n\r\n__END_DECLS\r\n\r\n#endif /* __GSL_MATRIX_COMPLEX_FLOAT_H__ */\r\n", "meta": {"hexsha": "61e19e1411621c7f8af7339aa0ce6cd207710ddb", "size": 14760, "ext": "h", "lang": "C", "max_stars_repo_path": "deps/include/gsl/gsl_matrix_complex_float.h", "max_stars_repo_name": "berkus/music-cs", "max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "deps/include/gsl/gsl_matrix_complex_float.h", "max_issues_repo_name": "berkus/music-cs", "max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "deps/include/gsl/gsl_matrix_complex_float.h", "max_forks_repo_name": "berkus/music-cs", "max_forks_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.0, "max_line_length": 150, "alphanum_fraction": 0.6714092141, "num_tokens": 3271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2751297119360208, "lm_q2_score": 0.03258974335662944, "lm_q1q2_score": 0.008966406701778305}}
{"text": "#ifndef __SAMPLER_H__\n#define __SAMPLER_H__\n\n#include <dSFMT.h>\n#include <gsl/gsl_randist.h>\n#include <gsl/gsl_rng.h>\n\nclass Sampler {\n\n  dsfmt_t dsfmt;\n\n  void init_random(unsigned params_random_seed) {\n#ifdef USE_MT_RANDOM\n  dsfmt_init_gen_rand(&dsfmt, params_random_seed);\n#else\n  srand(params_random_seed);\n#endif\n  };\n\n protected:\n  \n  /* gsl random number generator */\n  gsl_rng* _gsl_rng;\n\n  /* default constructor */\n  Sampler(unsigned int random_seed) {\n    /* do i still need this ? */\n    init_random(random_seed);\n    /* init gsl random number generator */\n    _gsl_rng = gsl_rng_alloc( gsl_rng_taus );\n  };\n\n  double sample_uniform();\n  unsigned long int sample_integer_uniform(unsigned int from, unsigned int to);\n  \n};\n\n#endif\n", "meta": {"hexsha": "0215c4ef2aab5f47f6c1bc86d280a3384a60fba3", "size": 742, "ext": "h", "lang": "C", "max_stars_repo_path": "models/topic-models/template-modeling/src/sampler.h", "max_stars_repo_name": "ypetinot/web-summarization", "max_stars_repo_head_hexsha": "2f7caf51b1e8bf5e510ce91070d622c8119e9865", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/topic-models/template-modeling/src/sampler.h", "max_issues_repo_name": "ypetinot/web-summarization", "max_issues_repo_head_hexsha": "2f7caf51b1e8bf5e510ce91070d622c8119e9865", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/topic-models/template-modeling/src/sampler.h", "max_forks_repo_name": "ypetinot/web-summarization", "max_forks_repo_head_hexsha": "2f7caf51b1e8bf5e510ce91070d622c8119e9865", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-03-03T04:58:44.000Z", "max_forks_repo_forks_event_max_datetime": "2016-03-03T04:58:44.000Z", "avg_line_length": 19.0256410256, "max_line_length": 79, "alphanum_fraction": 0.7169811321, "num_tokens": 187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.2877678157610531, "lm_q2_score": 0.031143834131786938, "lm_q1q2_score": 0.00896219312252886}}
{"text": "#pragma once\n\n#include \"schedule.h\"\n#include <gsl/gsl-lite.hpp>\n#include <range/v3/view/span.hpp>\n#include <vector>\n\nnamespace angonoka::stun {\nusing ranges::span;\nstruct ScheduleParams;\n\n/**\n    Makespan estimator.\n\n    Further reading:\n    https://en.wikipedia.org/wiki/Makespan\n*/\nclass Makespan {\npublic:\n    /**\n        Constructor.\n\n        @param params       An instance of ScheduleParams\n        @param tasks_count  Total number of tasks\n        @param agents_count Total number of agents\n    */\n    Makespan(const ScheduleParams& params);\n\n    Makespan(const Makespan& other);\n    Makespan& operator=(const Makespan& other) noexcept;\n    Makespan(Makespan&& other) noexcept;\n    Makespan& operator=(Makespan&& other) noexcept;\n    ~Makespan() noexcept;\n\n    /**\n        Calculate the makespan of a given scheduling configuration.\n\n        @param schedule Scheduling configuration\n\n        @return Makespan in seconds\n    */\n    float operator()(Schedule schedule) noexcept;\n\n    /**\n        Get the current ScheduleParams object.\n\n        @return Schedule parameters.\n    */\n    [[nodiscard]] const ScheduleParams& params() const;\n\n    /**\n        Set the ScheduleParams object.\n\n        @param params ScheduleParams object\n    */\n    void params(const ScheduleParams& params);\n\nprivate:\n    struct Impl;\n    gsl::not_null<const ScheduleParams*> params_;\n    std::vector<float> sum_buffer;\n    span<float> task_done;\n    span<float> work_done;\n};\n\nclass RandomUtils;\n\n/**\n    Shuffle tasks and agents in-place.\n\n    Randomly swaps two adjacent tasks within the schedule and\n    reassigns an agent of a random task.\n*/\nclass Mutator {\npublic:\n    /**\n        Mutator options.\n\n        @var params Schedule parameters\n        @var random Random utils.\n    */\n    struct Options {\n        gsl::not_null<const ScheduleParams*> params;\n        gsl::not_null<RandomUtils*> random;\n    };\n\n    /**\n        Constructor.\n\n        @param params An instance of ScheduleParams\n        @param random An instance of RandomUtils\n    */\n    Mutator(const ScheduleParams& params, RandomUtils& random);\n    Mutator(const Options& options);\n\n    /**\n        Mutates the scheduling configuration in-place.\n\n        @param schedule Scheduling configuration\n    */\n    void operator()(MutSchedule schedule) const noexcept;\n\n    /**\n        Get current options.\n\n        @return Options.\n    */\n    [[nodiscard]] Options options() const;\n\n    /**\n        Set options.\n\n        @param options Options.\n    */\n    void options(const Options& options);\n\nprivate:\n    struct Impl;\n    gsl::not_null<const ScheduleParams*> params;\n    gsl::not_null<RandomUtils*> random;\n};\n} // namespace angonoka::stun\n", "meta": {"hexsha": "77ee1df083bde3ac502efa51c706bc211f50517a", "size": 2686, "ext": "h", "lang": "C", "max_stars_repo_path": "src/stun/utils.h", "max_stars_repo_name": "coffee-lord/angonoka", "max_stars_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-10-23T18:05:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T21:53:24.000Z", "max_issues_repo_path": "src/stun/utils.h", "max_issues_repo_name": "coffee-lord/angonoka", "max_issues_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2022-02-12T19:52:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-12T19:55:52.000Z", "max_forks_repo_path": "src/stun/utils.h", "max_forks_repo_name": "coffee-lord/angonoka", "max_forks_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.837398374, "max_line_length": 67, "alphanum_fraction": 0.6496649293, "num_tokens": 575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3451052574867685, "lm_q2_score": 0.025957359552513166, "lm_q1q2_score": 0.008958021252046687}}
{"text": "/*\n * Implement Heap sort -- direct and indirect sorting\n * Based on descriptions in Sedgewick \"Algorithms in C\"\n *\n * Copyright (C) 1999  Thomas Walter\n *\n * 18 February 2000: Modified for GSL by Brian Gough\n *\n * This is free software; you can redistribute it and/or modify it\n * under the terms of the GNU General Public License as published by the\n * Free Software Foundation; either version 3, or (at your option) any\n * later version.\n *\n * This source is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n * for more details.\n */\n\n#include <config.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_sort.h>\n#include <gsl/gsl_sort_vector.h>\n\n#define BASE_LONG_DOUBLE\n#include \"templates_on.h\"\n#include \"sortvecind_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_LONG_DOUBLE\n\n#define BASE_DOUBLE\n#include \"templates_on.h\"\n#include \"sortvecind_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_DOUBLE\n\n#define BASE_FLOAT\n#include \"templates_on.h\"\n#include \"sortvecind_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_FLOAT\n\n#define BASE_ULONG\n#include \"templates_on.h\"\n#include \"sortvecind_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_ULONG\n\n#define BASE_LONG\n#include \"templates_on.h\"\n#include \"sortvecind_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_LONG\n\n#define BASE_UINT\n#include \"templates_on.h\"\n#include \"sortvecind_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_UINT\n\n#define BASE_INT\n#include \"templates_on.h\"\n#include \"sortvecind_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_INT\n\n#define BASE_USHORT\n#include \"templates_on.h\"\n#include \"sortvecind_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_USHORT\n\n#define BASE_SHORT\n#include \"templates_on.h\"\n#include \"sortvecind_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_SHORT\n\n#define BASE_UCHAR\n#include \"templates_on.h\"\n#include \"sortvecind_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_UCHAR\n\n#define BASE_CHAR\n#include \"templates_on.h\"\n#include \"sortvecind_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_CHAR\n", "meta": {"hexsha": "aa1aa8a7de9c893da540952dab155bb67468720c", "size": 2187, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/sort/sortvecind.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/sort/sortvecind.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/sort/sortvecind.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 24.032967033, "max_line_length": 77, "alphanum_fraction": 0.7709190672, "num_tokens": 529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33458942798284697, "lm_q2_score": 0.026759285901963227, "lm_q1q2_score": 0.008953374163167337}}
{"text": "#pragma once\n\n#include <type_traits>\n\n#include <cuda/define_specifiers.hpp>\n#include <cuda/runtime_api.hpp>\n\n#include <gsl-lite/gsl-lite.hpp>\n\n#include <thrustshift/fill.h>\n\nnamespace thrustshift {\n\nnamespace kernel {\n\ntemplate <typename SrcT, typename DstT>\n__global__ void copy(gsl_lite::span<const SrcT> src, gsl_lite::span<DstT> dst) {\n\n\tconst auto gtid = threadIdx.x + blockIdx.x * blockDim.x;\n\tif (gtid < src.size()) {\n\t\tdst[gtid] = src[gtid];\n\t}\n}\n\ntemplate <typename SrcT, typename DstT, typename T, typename I>\n__global__ void copy_find(gsl_lite::span<const SrcT> src,\n                          gsl_lite::span<DstT> dst,\n                          T value,\n                          I* pos) {\n\n\tconst auto gtid = threadIdx.x + blockIdx.x * blockDim.x;\n\tif (gtid < src.size()) {\n\t\tconst auto src_value = src[gtid];\n\t\tdst[gtid] = src_value;\n\t\tif (src_value == value) {\n\t\t\t*pos = gtid;\n\t\t}\n\t}\n}\n\n} // namespace kernel\n\nnamespace async {\n\n//! thrust uses sometimes a cudaMemcpyAsync instead of a copy kernel\ntemplate <class SrcRange, class DstRange>\nvoid copy(cuda::stream_t& stream, SrcRange&& src, DstRange&& dst) {\n\tgsl_Expects(src.size() == dst.size());\n\n\tif (src.empty()) {\n\t\treturn;\n\t}\n\n\tusing src_value_type =\n\t    typename std::remove_reference<SrcRange>::type::value_type;\n\tusing dst_value_type =\n\t    typename std::remove_reference<DstRange>::type::value_type;\n\n\tconstexpr cuda::grid::block_dimension_t block_dim = 128;\n\tconst cuda::grid::dimension_t grid_dim =\n\t    (src.size() + block_dim - 1) / block_dim;\n\tauto c = cuda::make_launch_config(grid_dim, block_dim);\n\tauto k = kernel::copy<src_value_type, dst_value_type>;\n\tcuda::enqueue_launch(k, stream, c, src, dst);\n}\n\n//! Copy and search for an element. If the element occurs more than once, it\n//! is undefined which of the valid positions is returned. If the element does\n//! not occur `pos` is unchanged.\ntemplate <class SrcRange, class DstRange, typename T, typename I>\nvoid copy_find(cuda::stream_t& stream,\n               SrcRange&& src,\n               DstRange&& dst,\n               const T& value,\n               I* pos) {\n\tgsl_Expects(src.size() == dst.size());\n\tgsl_Expects(pos != nullptr);\n\n\tif (src.empty()) {\n\t\treturn;\n\t}\n\n\tusing src_value_type =\n\t    typename std::remove_reference<SrcRange>::type::value_type;\n\tusing dst_value_type =\n\t    typename std::remove_reference<DstRange>::type::value_type;\n\n\tconstexpr cuda::grid::block_dimension_t block_dim = 128;\n\tconst cuda::grid::dimension_t grid_dim =\n\t    (src.size() + block_dim - 1) / block_dim;\n\tauto c = cuda::make_launch_config(grid_dim, block_dim);\n\tauto k = kernel::copy_find<src_value_type, dst_value_type, T, I>;\n\tcuda::enqueue_launch(k, stream, c, src, dst, value, pos);\n}\n\n} // namespace async\n\nnamespace detail {\n\ntemplate <int BLOCK_DIM,\n          int NUM_ELEMENTS,\n          int LD_FIRST = NUM_ELEMENTS,\n          int LD_RESULT = NUM_ELEMENTS,\n          int NUM_PER_ROW_FIRST = NUM_ELEMENTS,\n          int NUM_PER_ROW_RESULT = NUM_ELEMENTS>\nstruct helper_t {\n\ttemplate <class iteratorA_t, class iteratorB_t, class F>\n\tCUDA_FHD static void block_copy_even(iteratorA_t first,\n\t                                     iteratorB_t result,\n\t                                     int tid,\n\t                                     F f) {\n\t\tif (BLOCK_DIM < NUM_ELEMENTS) {\n// pragma unroll is device code specific\n#ifdef __CUDA_ARCH__\n#pragma unroll\n#endif\n\t\t\tfor (int i = 0; i < NUM_ELEMENTS - BLOCK_DIM; i += BLOCK_DIM) {\n\t\t\t\tf(first,\n\t\t\t\t  result,\n\t\t\t\t  i + ((i + tid) / NUM_PER_ROW_FIRST) *\n\t\t\t\t          (LD_FIRST - NUM_PER_ROW_FIRST) + tid,\n\t\t\t\t  i + ((i + tid) / NUM_PER_ROW_RESULT) *\n\t\t\t\t          (LD_RESULT - NUM_PER_ROW_RESULT) + tid);\n\t\t\t}\n\t\t}\n\t}\n\n\ttemplate <class iteratorA_t, class iteratorB_t, class F>\n\tCUDA_FHD static void block_copy_tail(iteratorA_t first,\n\t                                     iteratorB_t result,\n\t                                     int tid,\n\t                                     F f) {\n\t\tif (NUM_ELEMENTS % BLOCK_DIM == 0) {\n\t\t\tf(first,\n\t\t\t  result,\n\t\t\t  (NUM_ELEMENTS - BLOCK_DIM) +\n\t\t\t      (((NUM_ELEMENTS - BLOCK_DIM) + tid) / NUM_PER_ROW_FIRST) *\n\t\t\t          (LD_FIRST - NUM_PER_ROW_FIRST) + tid,\n\t\t\t  (NUM_ELEMENTS - BLOCK_DIM) +\n\t\t\t      (((NUM_ELEMENTS - BLOCK_DIM) + tid) / NUM_PER_ROW_RESULT) *\n\t\t\t          (LD_RESULT - NUM_PER_ROW_RESULT) + tid);\n\t\t}\n\t\telse if (tid + (NUM_ELEMENTS / BLOCK_DIM) * BLOCK_DIM < NUM_ELEMENTS) {\n\t\t\tconstexpr int j = (NUM_ELEMENTS / BLOCK_DIM) * BLOCK_DIM;\n\t\t\tf(first,\n\t\t\t  result,\n\t\t\t  j + ((j + tid) / NUM_PER_ROW_FIRST) *\n\t\t\t          (LD_FIRST - NUM_PER_ROW_FIRST) + tid,\n\t\t\t  j + ((j + tid) / NUM_PER_ROW_RESULT) *\n\t\t\t          (LD_RESULT - NUM_PER_ROW_RESULT) + tid);\n\t\t}\n\t}\n}; // helper\n\ntemplate <int BLOCK_DIM, int NUM_ELEMENTS>\nstruct helper_t<BLOCK_DIM,\n                NUM_ELEMENTS,\n                NUM_ELEMENTS,\n                NUM_ELEMENTS,\n                NUM_ELEMENTS,\n                NUM_ELEMENTS> {\n\ttemplate <class iteratorA_t, class iteratorB_t, class F>\n\tCUDA_FHD static void block_copy_even(iteratorA_t first,\n\t                                     iteratorB_t result,\n\t                                     int tid,\n\t                                     F f) {\n\t\tif (BLOCK_DIM < NUM_ELEMENTS) {\n// pragma unroll is device code specific\n#ifdef __CUDA_ARCH__\n#pragma unroll\n#endif\n\t\t\tfor (int i = 0; i < NUM_ELEMENTS - BLOCK_DIM; i += BLOCK_DIM) {\n\t\t\t\tconst int j = i + tid;\n\t\t\t\tf(first, result, j, j);\n\t\t\t}\n\t\t}\n\t}\n\n\ttemplate <class iteratorA_t, class iteratorB_t, class F>\n\tCUDA_FHD static void block_copy_tail(iteratorA_t first,\n\t                                     iteratorB_t result,\n\t                                     int tid,\n\t                                     F f) {\n\t\tif (NUM_ELEMENTS % BLOCK_DIM == 0) {\n\t\t\tconst int j = NUM_ELEMENTS - BLOCK_DIM + tid;\n\t\t\tf(first,\n\t\t\t  result,\n\t\t\t  j,\n\t\t\t  j);\n\t\t}\n\t\telse if (tid + (NUM_ELEMENTS / BLOCK_DIM) * BLOCK_DIM < NUM_ELEMENTS) {\n\t\t\tconst int j = (NUM_ELEMENTS / BLOCK_DIM) * BLOCK_DIM + tid;\n\t\t\tf(first, result, j, j);\n\t\t}\n\t}\n}; // struct helper_t\n\n//! Specialization for equal block dimension and number of elements\ntemplate <int BD_AND_NE>\nstruct helper_t<BD_AND_NE,\n                BD_AND_NE,\n                BD_AND_NE,\n                BD_AND_NE,\n                BD_AND_NE,\n                BD_AND_NE> {\n\ttemplate <class iteratorA_t, class iteratorB_t, class F>\n\tCUDA_FHD static void block_copy_even(iteratorA_t first,\n\t                                     iteratorB_t result,\n\t                                     int tid,\n\t                                     F f) {\n\t}\n\n\ttemplate <class iteratorA_t, class iteratorB_t, class F>\n\tCUDA_FHD static void block_copy_tail(iteratorA_t first,\n\t                                     iteratorB_t result,\n\t                                     int tid,\n\t                                     F f) {\n\t\tf(first, result, tid, tid);\n\t}\n\n}; // struct helper_t\n\n}; // namespace detail\n\n/* \\brief Copy data blockwise with efficient loop unrolling.\n *\n * This function implements an efficient memory copy. This is in particular\n * useful if you use only a few threads to copy data, since this is limited\n * by register dependencies if trivially implemented. The algorithm is\n * implemented in two steps. First we copy elements subsequently and\n * block wise with the whole thread block:\n *\n *     N = 11, bdim = 4: x x x x | x x x x | o o o\n *     N = 12, bdim = 4: x x x x | x x x x | o o o o\n *     N = 13, bdim = 4: x x x x | x x x x | x x x x | o\n *\n * Thus the last elements are not copied (denoted by `o`).\n * Afterwards we must copy the remaining elements, which is\n * trivial if N % bdim == 0.\n *\n * \\param BLOCK_DIM Current thread block dimension\n * \\param NUM_ELEMENTS total amount of elements to copy\n * \\param LD_RESULT Leading dimension on result. Only used in case of two dimensional\n *        arranged data. This is equal to the number of elements, which\n *        must be skipped to get an element in the next row. This is\n *        useful if you want to skip some of the columns of the 2D data:\n *\n *           |    ld     |\n *            x x x x o o\n *            x x x x o o\n *            x x x x o o\n *            x x x x o o\n *           |  nepr |\n *\n *        `nepr` = num elements per row\n *        `ld` = leading dimension\n *        If you want to copy only the `x` elements.\n *\n * \\param NUM_PER_ROW Only used in case of two dimensional data copies\n * \\param first iterator to first read element\n * \\param result iterator to first result element\n * \\param f A functor to write the data, e.g.\n *      ```\n *      auto default_f = [](iteratorA_t first,\n *                          iteratorB_t result,\n *                          int i_first,\n *                          int i_result) {\n *          result[i_result] = first[i_first];\n *      };\n *      ```\n *     `i_first` and `i_result` are the global indices on iterator `first` and `result`. With such\n *     a functor it is possible to modify the read and write process. E.g. you can read\n *     the data in a permuted way.\n *\n */\ntemplate <int BLOCK_DIM,\n          int NUM_ELEMENTS,\n          class iteratorA_t,\n          class iteratorB_t,\n          int LD_FIRST = NUM_ELEMENTS,\n          int LD_RESULT = NUM_ELEMENTS,\n          int NUM_PER_ROW_FIRST = NUM_ELEMENTS,\n          int NUM_PER_ROW_RESULT = NUM_ELEMENTS,\n          class F>\nCUDA_FHD void block_copy(iteratorA_t first,\n                         iteratorB_t result,\n                         int tid,\n                         F f) {\n\n\tdetail::helper_t<BLOCK_DIM,\n\t                 NUM_ELEMENTS,\n\t                 LD_FIRST,\n\t                 LD_RESULT,\n\t                 NUM_PER_ROW_FIRST,\n\t                 NUM_PER_ROW_RESULT>::block_copy_even(first,\n\t                                                      result,\n\t                                                      tid,\n\t                                                      f);\n\tdetail::helper_t<BLOCK_DIM,\n\t                 NUM_ELEMENTS,\n\t                 LD_FIRST,\n\t                 LD_RESULT,\n\t                 NUM_PER_ROW_FIRST,\n\t                 NUM_PER_ROW_RESULT>::block_copy_tail(first,\n\t                                                      result,\n\t                                                      tid,\n\t                                                      f);\n}\n\ntemplate <int BLOCK_DIM,\n          int NUM_ELEMENTS,\n          int LD_FIRST = NUM_ELEMENTS,\n          int LD_RESULT = NUM_ELEMENTS,\n          int NUM_PER_ROW_FIRST = NUM_ELEMENTS,\n          int NUM_PER_ROW_RESULT = NUM_ELEMENTS,\n          class iteratorA_t,\n          class iteratorB_t>\nCUDA_FHD void block_copy(iteratorA_t first,\n                         iteratorB_t result,\n                         int tid = threadIdx.x) {\n\n\tauto default_f = [](iteratorA_t first,\n\t                    iteratorB_t result,\n\t                    int i_first,\n\t                    int i_result) {\n\t\tresult[i_result] = first[i_first];\n\t};\n\n\tblock_copy<BLOCK_DIM,\n\t           NUM_ELEMENTS,\n\t           iteratorA_t,\n\t           iteratorB_t,\n\t           LD_FIRST,\n\t           LD_RESULT,\n\t           NUM_PER_ROW_FIRST,\n\t           NUM_PER_ROW_RESULT>(first, result, tid, default_f);\n}\n\n//! copy data without loops unrolled\ntemplate <class iteratorA_t, class iteratorB_t>\nCUDA_FHD void block_copy(iteratorA_t first,\n                        int num_elements,\n                        iteratorB_t result,\n                        int group_dim,\n                        int ld_first,\n                        int ld_result,\n                        int num_per_row_first,\n                        int num_per_row_result,\n                        int tid) {\n\tauto f = [](iteratorA_t first,\n\t            iteratorB_t result,\n\t            int i_first,\n\t            int i_result) { result[i_result] = first[i_first]; };\n\t//////////\n\t// HEAD //\n\t//////////\n\tif (group_dim < num_elements) {\n\t\tfor (int i = 0; i < num_elements - group_dim; i += group_dim) {\n\t\t\tf(first,\n\t\t\t  result,\n\t\t\t  i + ((i + tid) / num_per_row_first) *\n\t\t\t          (ld_first - num_per_row_first) + tid,\n\t\t\t  i + ((i + tid) / num_per_row_result) *\n\t\t\t          (ld_result - num_per_row_result) + tid);\n\t\t}\n\t}\n\t//////////\n\t// TAIL //\n\t//////////\n\tif (num_elements % group_dim == 0) {\n\t\tf(first,\n\t\t  result,\n\t\t  (num_elements - group_dim) +\n\t\t      (((num_elements - group_dim) + tid) / num_per_row_first) *\n\t\t          (ld_first - num_per_row_first) + tid,\n\t\t  (num_elements - group_dim) +\n\t\t      (((num_elements - group_dim) + tid) / num_per_row_result) *\n\t\t          (ld_result - num_per_row_result) + tid);\n\t}\n\telse if (tid + (num_elements / group_dim) * group_dim < num_elements) {\n\t\tconst int j = (num_elements / group_dim) * group_dim;\n\t\tf(first,\n\t\t  result,\n\t\t  j + ((j + tid) / num_per_row_first) * (ld_first - num_per_row_first) + tid,\n\t\t  j + ((j + tid) / num_per_row_result) *\n\t\t          (ld_result - num_per_row_result) + tid);\n\t}\n}\n\n} // namespace thrustshift\n", "meta": {"hexsha": "844663e3f8b7a21b27248c516b7ba6dee4e1ac8c", "size": 12901, "ext": "h", "lang": "C", "max_stars_repo_path": "include/thrustshift/copy.h", "max_stars_repo_name": "pauleonix/thrustshift", "max_stars_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-16T13:01:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T13:01:46.000Z", "max_issues_repo_path": "include/thrustshift/copy.h", "max_issues_repo_name": "pauleonix/thrustshift", "max_issues_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-23T14:12:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-17T11:40:04.000Z", "max_forks_repo_path": "include/thrustshift/copy.h", "max_forks_repo_name": "pauleonix/thrustshift", "max_forks_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9948849105, "max_line_length": 98, "alphanum_fraction": 0.5613518332, "num_tokens": 3041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25091279808829703, "lm_q2_score": 0.03567855023687644, "lm_q1q2_score": 0.00895220487166854}}
{"text": "#ifndef DEINOS_ALGORITHM_H\n#define DEINOS_ALGORITHM_H\n#include \"chess.h\"\n#include <vector>\n#include <array>\n#include <gsl/pointers>\n#include <mutex>\n#include <variant>\n#include <functional>\n#include <string>\n#include <thread>\n#include <future>\n#include <condition_variable>\n\n//memory consmption ideas:\n//can halve Move size by removing piece type tracking and putting boold inside promotion piece\n//can reduce AnalysedPosition size by doubling up control inside one byte\n//perhaps dynamically delete parts of the tree e.g. only positions and regenerate if necessary\n//deletion thread?\n\n//Other\n//use gsl::index in for loops?\n\nnamespace algorithm {\n\tclass AnalysedPosition{\n\tpublic:\n\t\tconstexpr AnalysedPosition() = default;\n\t\texplicit AnalysedPosition(const chess::Position&); //generate from scratch\n\n\t\tvoid advance_by(chess::MoveRecord);\n\t\tstruct occlusion_info {\n\t\t\tstd::array<std::array<chess::Square, 16>, 2> squares;\n\t\t\tstd::array<int, 2> counts = {0};\n\t\t};\n\t\tAnalysedPosition::occlusion_info get_occlusion(chess::MoveRecord);\n\n\t\tinline const chess::Position& pos() const {return m_position;}\n\t\tinline uint8_t ctrl(chess::Almnt a, chess::Square s) const {return m_control[chess::as_index(a)].get(s.file(), s.rank());}\n\t\tinline const std::vector<chess::MoveRecord>& moves(chess::Almnt a) const {return m_moves[chess::as_index(a)];}\n\t\tinline const std::vector<chess::MoveRecord>& moves() const {return moves(pos().to_move());}\n\t\tinline chess::Move get_move(int index) const {return chess::Move(pos(), moves().at(index));}\n\t\tinline const chess::Square king_sq(chess::Almnt a) const {return m_king_sq[chess::as_index(a)];}\n\t\tinline bool in_check(chess::Almnt a) const {return ctrl(!a, king_sq(a)) > 0;}\n\t\tinline bool legal_check() const {return in_check(pos().to_move());}\n\t\tinline bool illegal_check() const {return in_check(!pos().to_move());}\n\t\tstd::optional<chess::Move> find_record(const std::string& name) const;\n\t\tfriend std::ostream& operator<<(std::ostream& os, const AnalysedPosition& ap);\n\t\t\n\tprivate:\n\t\tvoid append_calculation(chess::Square start); //calculate data associated with this square and append to state (for initialisation)\n\t\tvoid append_castling();\n\t\tstd::array<chess::Square, 2> m_king_sq;\n\t\tchess::Position m_position;\n\t\tstd::array<chess::HalfByteBoard, 2> m_control;\n\t\tstd::array<std::vector<chess::MoveRecord>, 2> m_moves = {};\n\t};\n\tstd::ostream& operator<<(std::ostream& os, const AnalysedPosition& ap);\n\n\tclass Node;\n\t\n\tstruct Edge {\n\t\t//std::mutex ptr_mutex;\n\t\tfloat total_value;\n\t\tint visits = 0;\n\t\t//bool legal = true;\n\t\tinline bool legal() const {return visits != -1;}\n\t\tstd::unique_ptr<Node> node = nullptr;\n\t};\n\n\tstruct EdgeDatum {\n\t\tfloat total_value = 0.0;\n\t\tint visits = 0;\n\t\tbool legal = true;\n\t};\n\n\tstruct EdgeData {\n\t\tEdgeData(int moves_num) : edges(std::vector<EdgeDatum>(moves_num)) {}\n\t\tint total_n = 1;\n\t\tstd::vector<EdgeDatum> edges;\n\t};\n\n\tclass Node { //TODO\n\tpublic:\n\t\texplicit Node(std::unique_ptr<const AnalysedPosition> t_apos);\n\t\texplicit Node(const AnalysedPosition& t_apos);\n\t\tint preferred_index();\n\t\tstd::unique_ptr<Node>* find_child(const std::string& fen);\n\t\tstd::unique_ptr<Node>* find_child(const chess::Move& mv);\n\t\tinline Node* child(int index) const {return edges[index].node.get();}\n\t\tconst chess::Move best_move() {return chess::Move(apos->pos(), apos->moves()[preferred_index()]);}\n\t\tinline std::optional<chess::GameResult> result() const {return m_result;}\n\t\t//inline int res_dist() const {return m_res_dist;} //TODO\n\t\tstd::string display() const;\n\n\t\tinline int total_n() const {return m_total_n;} //synchronise?\n\t\t\n\t\tconst std::unique_ptr<const AnalysedPosition> apos;\n\t\tconst bool white_to_play;\n\t\t\n\tprivate:\n\t\tvoid update(int index, float t_value);\n\t\tvoid increment_n();\n\t\tvoid set_illegal(int index);\n\t\n\t\tstd::optional<chess::GameResult> m_result = std::nullopt;\n\t\t//int m_res_dist = 0; //TODO\n\t\t//std::mutex data_mutex2;\n\t\t//EdgeData data;\n\t\tint m_total_n = 1;\n\t\tstd::vector<Edge> edges;\n\t\t//std::vector<Edge> edges2;\n\t\tstd::mutex data_mutex; //40B\n\n\t\tstd::array<uint8_t, 3> node_prefetch = {0};\n\t\t\n\t\tfriend class Tree;\n\t};\n\n\tclass Tree {\n\tpublic:\n\t\tTree(const AnalysedPosition& base_apos, std::function<float(const AnalysedPosition&)> t_value_fn,\n\t\t\tstd::function<float(const AnalysedPosition&, const chess::Move&)> t_prior_fn, float t_expl_c = 0.2)\t\t\t\n\t\t\t: base(std::make_unique<Node>(base_apos)), value_fn(t_value_fn), prior_fn(t_prior_fn), expl_c(t_expl_c) {}\n\t\tvoid search(bool update_prefetch = false);\n\t\tstd::unique_ptr<Node> base;\n\t\tstd::function<float(const AnalysedPosition&)> value_fn;\n\t\tstd::function<float(const AnalysedPosition&, const chess::Move&)> prior_fn;\n\t\tfloat expl_c = 0.2; //exploration coefficient\n\n\tprivate:\n\t\tfloat evaluate_node(Node& node); //used in search() for recursion\n\t\tvoid update_node(int index, float t_value);\n\t\tstd::optional<int> edge_to_search(Node& node);\n\t\tvoid update_prefetch(Node& node);\n\t};\n\n\tclass TreeEngine {\n\tpublic:\n\t\tTreeEngine(\n\t\t\tconst AnalysedPosition& initial_position,\n\t\t\tstd::function<float(const AnalysedPosition&)> t_value_fn,\n\t\t\tstd::function<float(const AnalysedPosition&, const chess::Move&)> t_prior_fn,\n\t\t\tfloat exploration_coefficient);\n\n\t\t~TreeEngine() {\n\t\t\thalt_promise.set_value();\n\t\t\tfor (auto& t : m_threads) t.join();\n\t\t}\n\n\t\tTreeEngine(const TreeEngine&) = delete;\n\t\tTreeEngine& operator=(const TreeEngine&) = delete;\n\t\tTreeEngine(TreeEngine&&) = delete;\n\t\tTreeEngine& operator=(TreeEngine&&) = delete;\n\n\t\t//void start();\n\t\tconst chess::Move choose_move(); //maybe add exploration?\n\t\tbool advance_to(const std::string& fen);\n\t\tbool advance_by(const chess::Move& mv); //TODO\n\t\tstd::string display() const; //TODO\n\n\t\tinline int total_n() const {return m_tree.base->total_n();};\n\t\t\n\tprivate:\n\t\tbool should_pause();\n\t\tvoid pause(); //blocks until all threads are paused\n\t\tvoid resume(); //blocks until all threads are resumed\n\t\n\t\tTree m_tree;\n\t\tstd::promise<void> halt_promise;\n\t\tstd::mutex pause_mx;\n\t\tstd::condition_variable pause_cv;\n\t\tbool pause_bool = false;\n\t\tint pause_count = 0;\n\t\tstd::vector<std::thread> m_threads;\n\t};\n}\n#endif", "meta": {"hexsha": "39b310a3cd8acf6cbfaaa560661fc6366e2a1e36", "size": 6080, "ext": "h", "lang": "C", "max_stars_repo_path": "deinos/algorithm.h", "max_stars_repo_name": "Ayals4/deinos", "max_stars_repo_head_hexsha": "940f60f4c4907c3484217c082db6b66b3c39a373", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-05T00:44:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-05T00:44:30.000Z", "max_issues_repo_path": "deinos/algorithm.h", "max_issues_repo_name": "Ayals4/deinos", "max_issues_repo_head_hexsha": "940f60f4c4907c3484217c082db6b66b3c39a373", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "deinos/algorithm.h", "max_forks_repo_name": "Ayals4/deinos", "max_forks_repo_head_hexsha": "940f60f4c4907c3484217c082db6b66b3c39a373", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3502824859, "max_line_length": 133, "alphanum_fraction": 0.7180921053, "num_tokens": 1665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3775406687981454, "lm_q2_score": 0.023689474013400658, "lm_q1q2_score": 0.00894373986249557}}
{"text": "/*\n * Copyright (c) 1997-1999 Massachusetts Institute of Technology\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n *\n */\n\n/* fftw.h -- system-wide definitions */\n/* $Id: fftw-int.h,v 1.39 1999/02/19 17:22:00 athena Exp $ */\n\n#ifndef FFTW_INT_H\n#define FFTW_INT_H\n#include <config.h>\n#include <fftw.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#else\n#endif\t\t\t\t/* __cplusplus */\n\n/****************************************************************************/\n/*                            Private Functions                             */\n/****************************************************************************/\n\nextern fftw_twiddle *fftw_create_twiddle(int n, const fftw_codelet_desc *d);\nextern void fftw_destroy_twiddle(fftw_twiddle *tw);\n\nextern void fftw_strided_copy(int, fftw_complex *, int, fftw_complex *);\nextern void fftw_executor_simple(int, const fftw_complex *, fftw_complex *,\n\t\t\t\t fftw_plan_node *, int, int);\n\nextern fftwnd_plan fftwnd_create_plan_aux(int rank, const int *n,\n\t\t\t\t\t  fftw_direction dir, int flags);\nextern fftw_plan *fftwnd_new_plan_array(int rank);\nextern fftw_plan *fftwnd_create_plans_generic(fftw_plan *plans,\n\t\t\t\t\t      int rank, const int *n,\n\t\t\t\t\t      fftw_direction dir, int flags);\nextern fftw_plan *fftwnd_create_plans_specific(fftw_plan *plans,\n\t\t\t\t\t       int rank, const int *n,\n\t\t\t\t\t       const int *n_after,\n\t\t\t\t\t       fftw_direction dir, int flags,\n\t\t\t\t\t       fftw_complex *in, int istride,\n\t\t\t\t\t       fftw_complex *out, int ostride);\nextern int fftwnd_work_size(int rank, const int *n, int flags, int ncopies);\n\nextern void fftwnd_aux(fftwnd_plan p, int cur_dim,\n\t\t       fftw_complex *in, int istride,\n\t\t       fftw_complex *out, int ostride,\n\t\t       fftw_complex *work);\nextern void fftwnd_aux_howmany(fftwnd_plan p, int cur_dim,\n\t\t\t       int howmany,\n\t\t\t       fftw_complex *in, int istride, int idist,\n\t\t\t       fftw_complex *out, int ostride, int odist,\n\t\t\t       fftw_complex *work);\n\n/* wisdom prototypes */\nenum fftw_wisdom_category {\n     FFTW_WISDOM, RFFTW_WISDOM\n};\n\nextern int fftw_wisdom_lookup(int n, int flags, fftw_direction dir,\n\t\t\t      enum fftw_wisdom_category category,\n\t\t\t      int istride, int ostride,\n\t\t\t      enum fftw_node_type *type,\n\t\t\t      int *signature, int replace_p);\nextern void fftw_wisdom_add(int n, int flags, fftw_direction dir,\n\t\t\t    enum fftw_wisdom_category cat,\n\t\t\t    int istride, int ostride,\n\t\t\t    enum fftw_node_type type,\n\t\t\t    int signature);\n\n/* Private planner functions: */\nextern double fftw_estimate_node(fftw_plan_node *p);\nextern fftw_plan_node *fftw_make_node_notw(int size,\n\t\t\t\t\tconst fftw_codelet_desc *config);\nextern fftw_plan_node *fftw_make_node_real2hc(int size,\n\t\t\t\t\tconst fftw_codelet_desc *config);\nextern fftw_plan_node *fftw_make_node_hc2real(int size,\n\t\t\t\t\tconst fftw_codelet_desc *config);\nextern fftw_plan_node *fftw_make_node_twiddle(int n,\n\t\t\t\t\t const fftw_codelet_desc *config,\n\t\t\t\t\t      fftw_plan_node *recurse,\n\t\t\t\t\t      int flags);\nextern fftw_plan_node *fftw_make_node_hc2hc(int n,\n\t\t\t\t\t    fftw_direction dir,\n\t\t\t\t\t const fftw_codelet_desc *config,\n\t\t\t\t\t    fftw_plan_node *recurse,\n\t\t\t\t\t    int flags);\nextern fftw_plan_node *fftw_make_node_generic(int n, int size,\n\t\t\t\t\t      fftw_generic_codelet *codelet,\n\t\t\t\t\t      fftw_plan_node *recurse,\n\t\t\t\t\t      int flags);\nextern fftw_plan_node *fftw_make_node_rgeneric(int n, int size,\n\t\t\t\t\t       fftw_direction dir,\n\t\t\t\t\t       fftw_rgeneric_codelet * codelet,\n\t\t\t\t\t       fftw_plan_node *recurse,\n\t\t\t\t\t       int flags);\nextern int fftw_factor(int n);\nextern fftw_plan_node *fftw_make_node(void);\nextern fftw_plan fftw_make_plan(int n, fftw_direction dir,\n\t\t\t\tfftw_plan_node *root, int flags,\n\t\t\t\tenum fftw_node_type wisdom_type,\n\t\t\t\tint wisdom_signature);\nextern void fftw_use_plan(fftw_plan p);\nextern void fftw_use_node(fftw_plan_node *p);\nextern void fftw_destroy_plan_internal(fftw_plan p);\nextern fftw_plan fftw_pick_better(fftw_plan p1, fftw_plan p2);\nextern fftw_plan fftw_lookup(fftw_plan *table, int n, int flags);\nextern void fftw_insert(fftw_plan *table, fftw_plan this_plan, int n);\nextern void fftw_make_empty_table(fftw_plan *table);\nextern void fftw_destroy_table(fftw_plan *table);\nextern void fftw_complete_twiddle(fftw_plan_node *p, int n);\n\nextern fftw_plan_node *fftw_make_node_rader(int n, int size,\n\t\t\t\t\t    fftw_direction dir,\n\t\t\t\t\t    fftw_plan_node *recurse,\n\t\t\t\t\t    int flags);\nextern fftw_rader_data *fftw_rader_top;\n\n/****************************************************************************/\n/*                           Floating Point Types                           */\n/****************************************************************************/\n\n/*\n * We use these definitions to make it easier for people to change\n * FFTW to use long double and similar types. You shouldn't have to\n * change this just to use float or double. \n */\n\n/*\n * Change this if your floating-point constants need to be expressed\n * in a special way.  For example, if fftw_real is long double, you\n * will need to append L to your fp constants to make them of the\n * same precision.  Do this by changing \"x\" below to \"x##L\". \n */\n#define FFTW_KONST(x) ((fftw_real) x)\n\n#define FFTW_TRIG_SIN sin\n#define FFTW_TRIG_COS cos\ntypedef double FFTW_TRIG_REAL;\t/* the argument type for sin and cos */\n\n#define FFTW_K2PI FFTW_KONST(6.2831853071795864769252867665590057683943388)\n\n/****************************************************************************/\n/*                               gcc/x86 hacks                              */\n/****************************************************************************/\n\n/*\n * gcc 2.[78].x and x86 specific hacks.  These macros align the stack\n * pointer so that the double precision temporary variables in the\n * codelets will be aligned to a multiple of 8 bytes (*way* faster on\n * pentium and pentiumpro)\n */\n#ifdef __GNUC__\n#ifdef __i386__\n#ifdef FFTW_ENABLE_I386_HACKS\n#ifndef FFTW_ENABLE_FLOAT\n#define FFTW_USING_I386_HACKS\n#define HACK_ALIGN_STACK_EVEN() {                        \\\n     if ((((long) (__builtin_alloca(0))) & 0x7)) __builtin_alloca(4);    \\\n}\n\n#define HACK_ALIGN_STACK_ODD() {                         \\\n     if (!(((long) (__builtin_alloca(0))) & 0x7)) __builtin_alloca(4);   \\\n}\n\n#ifdef FFTW_DEBUG_ALIGNMENT\n#define ASSERT_ALIGNED_DOUBLE() {                        \\\n     double __foo;                                       \\\n     if ((((long) &__foo) & 0x7)) abort();                \\\n}\n#endif\n\n#endif\n#endif\n#endif\n#endif\n\n#ifndef HACK_ALIGN_STACK_EVEN\n#define HACK_ALIGN_STACK_EVEN()\n#endif\n#ifndef HACK_ALIGN_STACK_ODD\n#define HACK_ALIGN_STACK_ODD()\n#endif\n#ifndef ASSERT_ALIGNED_DOUBLE\n#define ASSERT_ALIGNED_DOUBLE()\n#endif\n\n/****************************************************************************/\n/*                                  Timers                                  */\n/****************************************************************************/\n\n/*\n * Here, you can use all the nice timers available in your machine.\n */\n\n/*\n *\n Things you should define to include your own clock:\n \n fftw_time -- the data type used to store a time\n \n extern fftw_time fftw_get_time(void); \n -- a function returning the current time.  (We have\n implemented this as a macro in most cases.)\n \n extern fftw_time fftw_time_diff(fftw_time t1, fftw_time t2);\n -- returns the time difference (t1 - t2).\n If t1 < t2, it may simply return zero (although this\n is not required).  (We have implemented this as a macro\n in most cases.)\n \n extern double fftw_time_to_sec(fftw_time t);\n -- returns the time t expressed in seconds, as a double.\n (Implemented as a macro in most cases.)\n \n FFTW_TIME_MIN -- a double-precision macro holding the minimum\n time interval (in seconds) for accurate time measurements.\n This should probably be at least 100 times the precision of\n your clock (we use even longer intervals, to be conservative).\n This will determine how long the planner takes to measure\n the speeds of different possible plans.\n \n Bracket all of your definitions with an appropriate #ifdef so that\n they will be enabled on your machine.  If you do add your own\n high-precision timer code, let us know (at fftw@theory.lcs.mit.edu).\n \n Only declarations should go in this file.  Any function definitions\n that you need should go into timer.c.\n */\n\n/*\n * define a symbol so that we know that we have the fftw_time_diff\n * function/macro (it did not exist prior to FFTW 1.2) \n */\n#define FFTW_HAS_TIME_DIFF\n\n/**********************************************\n *              SOLARIS\n **********************************************/\n#if defined(HAVE_GETHRTIME)\n\n/* we use the nanosecond virtual timer */\n#ifdef HAVE_SYS_TIME_H\n#include <sys/time.h>\n#endif\n\ntypedef hrtime_t fftw_time;\n\n#define fftw_get_time() gethrtime()\n#define fftw_time_diff(t1,t2) ((t1) - (t2))\n#define fftw_time_to_sec(t) ((double) t / 1.0e9)\n\n/*\n * a measurement is valid if it runs for at least\n * FFTW_TIME_MIN seconds.\n */\n#define FFTW_TIME_MIN (1.0e-4)\t/* for Solaris nanosecond timer */\n#define FFTW_TIME_REPEAT 8\n\n/**********************************************\n *        Pentium time stamp counter\n **********************************************/\n#elif defined(__GNUC__) && defined(__i386__) && defined(FFTW_ENABLE_PENTIUM_TIMER)\n\n/*\n * Use internal Pentium register (time stamp counter). Resolution\n * is 1/FFTW_CYCLES_PER_SEC seconds (e.g. 5 ns for Pentium 200 MHz).\n * (This code was contributed by Wolfgang Reimer)\n */\n\n#ifndef FFTW_CYCLES_PER_SEC\n#error \"Must define FFTW_CYCLES_PER_SEC in fftw/config.h to use the Pentium cycle counter\"\n#endif\n\ntypedef unsigned long long fftw_time;\n\nstatic __inline__ fftw_time read_tsc()\n{\n     struct {\n\t  long unsigned lo, hi;\n     } counter;\n     long unsigned sav_eax, sav_edx;\n   __asm__(\"movl %%eax,%0\":\"=m\"(sav_eax));\n   __asm__(\"movl %%edx,%0\":\"=m\"(sav_edx));\n     __asm__(\"rdtsc\");\n   __asm__(\"movl %%eax,%0\":\"=m\"(counter.lo));\n   __asm__(\"movl %%edx,%0\":\"=m\"(counter.hi));\n   __asm__(\"movl %0,%%eax\": : \"m\"(sav_eax):\"eax\");\n   __asm__(\"movl %0,%%edx\": : \"m\"(sav_edx):\"edx\");\n     return *(fftw_time *) & counter;\n}\n\n#define fftw_get_time()  read_tsc()\n#define fftw_time_diff(t1,t2) ((t1) - (t2))\n#define fftw_time_to_sec(t) (((double) (t)) / FFTW_CYCLES_PER_SEC)\n#define FFTW_TIME_MIN (1.0e-4)\t/* for Pentium TSC register */\n\n/************* generic systems having gettimeofday ************/\n#elif defined(HAVE_GETTIMEOFDAY) || defined(HAVE_BSDGETTIMEOFDAY)\n#ifdef HAVE_SYS_TIME_H\n#include <sys/time.h>\n#endif\n#ifdef HAVE_UNISTD_H\n#include <unistd.h>\n#endif\n#define FFTW_USE_GETTIMEOFDAY\n\ntypedef struct timeval fftw_time;\n\nextern fftw_time fftw_gettimeofday_get_time(void);\nextern fftw_time fftw_gettimeofday_time_diff(fftw_time t1, fftw_time t2);\n#define fftw_get_time() fftw_gettimeofday_get_time()\n#define fftw_time_diff(t1, t2) fftw_gettimeofday_time_diff(t1, t2)\n#define fftw_time_to_sec(t) ((double)(t).tv_sec + (double)(t).tv_usec * 1.0E-6)\n\n#ifndef FFTW_TIME_MIN\n/* this should be fine on any system claiming a microsecond timer */\n#define FFTW_TIME_MIN (1.0e-2)\n#endif\n\n/**********************************************\n *              MACINTOSH\n **********************************************/\n#elif defined(HAVE_MAC_TIMER)\n\n/*\n * By default, use the microsecond-timer in the Mac Time Manager.\n * Alternatively, by changing the following #if 1 to #if 0, you\n * can use the nanosecond timer available *only* on PCI PowerMacs. \n */\n#ifndef HAVE_MAC_PCI_TIMER\t/* use time manager */\n\n/*\n * Use Macintosh Time Manager routines (maximum resolution is about 20\n * microseconds). \n */\ntypedef struct fftw_time_struct {\n     unsigned long hi, lo;\n} fftw_time;\n\nextern fftw_time get_Mac_microseconds(void);\n\n#define fftw_get_time() get_Mac_microseconds()\n\n/* define as a function instead of a macro: */\nextern fftw_time fftw_time_diff(fftw_time t1, fftw_time t2);\n\n#define fftw_time_to_sec(t) ((t).lo * 1.0e-6 + 4294967295.0e-6 * (t).hi)\n\n/* very conservative, since timer should be accurate to 20e-6: */\n/* (although this seems not to be the case in practice) */\n#define FFTW_TIME_MIN (5.0e-2)\t/* for MacOS Time Manager timer */\n\n#else\t\t\t\t/* use nanosecond timer */\n\n/* Use the nanosecond timer available on PCI PowerMacs. */\n\n#include <DriverServices.h>\n\ntypedef AbsoluteTime fftw_time;\n#define fftw_get_time() UpTime()\n#define fftw_time_diff(t1,t2) SubAbsoluteFromAbsolute(t1,t2)\n#define fftw_time_to_sec(t) (AbsoluteToNanoseconds(t).lo * 1.0e-9)\n\n/* Extremely conservative minimum time: */\n/* for MacOS PCI PowerMac nanosecond timer */\n#define FFTW_TIME_MIN (5.0e-3)\t\n\n#endif\t\t\t\t/* use nanosecond timer */\n\n/**********************************************\n *              WINDOWS\n **********************************************/\n#elif defined(HAVE_WIN32_TIMER)\n\n#include <time.h>\n\ntypedef unsigned long fftw_time;\nextern unsigned long GetPerfTime(void);\nextern double GetPerfSec(double ticks);\n\n#define fftw_get_time() GetPerfTime()\n#define fftw_time_diff(t1,t2) ((t1) - (t2))\n#define fftw_time_to_sec(t) GetPerfSec(t)\n\n#define FFTW_TIME_MIN (5.0e-2)\t/* for Win32 timer */\n\n/**********************************************\n *              CRAY\n **********************************************/\n#elif defined(_CRAYMPP)\t\t/* Cray MPP system */\n\ndouble SECONDR(void);\t\t/* \n\t\t\t\t * I think you have to link with -lsci to\n\t\t\t\t * get this \n\t\t\t\t */\n\ntypedef double fftw_time;\n#define fftw_get_time() SECONDR()\n#define fftw_time_diff(t1,t2) ((t1) - (t2))\n#define fftw_time_to_sec(t) (t)\n\n#define FFTW_TIME_MIN (1.0e-1)\t/* for Cray MPP SECONDR timer */\n\n/**********************************************\n *          VANILLA UNIX/ISO C SYSTEMS\n **********************************************/\n/* last resort: use good old Unix clock() */\n#else\n\n#include <time.h>\n\ntypedef clock_t fftw_time;\n\n#ifndef CLOCKS_PER_SEC\n#ifdef sun\n/* stupid sunos4 prototypes */\n#define CLOCKS_PER_SEC 1000000\nextern long clock(void);\n#else\t\t\t\t/* not sun, we don't know CLOCKS_PER_SEC */\n#error Please define CLOCKS_PER_SEC\n#endif\n#endif\n\n#define fftw_get_time() clock()\n#define fftw_time_diff(t1,t2) ((t1) - (t2))\n#define fftw_time_to_sec(t) (((double) (t)) / CLOCKS_PER_SEC)\n\n/*\n * ***VERY*** conservative constant: this says that a\n * measurement must run for 200ms in order to be valid.\n * You had better check the manual of your machine\n * to discover if it can do better than this\n */\n#define FFTW_TIME_MIN (2.0e-1)\t/* for default clock() timer */\n\n#endif\t\t\t\t/* UNIX clock() */\n\n/* take FFTW_TIME_REPEAT measurements... */\n#ifndef FFTW_TIME_REPEAT\n#define FFTW_TIME_REPEAT 4\n#endif\n\n/* but do not run for more than TIME_LIMIT seconds while measuring one FFT */\n#ifndef FFTW_TIME_LIMIT\n#define FFTW_TIME_LIMIT 2.0\n#endif\n\n#ifdef __cplusplus\n}\t\t\t\t/* extern \"C\" */\n\n#endif\t\t\t\t/* __cplusplus */\n\n#endif\t\t\t\t/* FFTW_INT_H */\n", "meta": {"hexsha": "637f537b06040647f03460adb5ee966bc9aca320", "size": 15443, "ext": "h", "lang": "C", "max_stars_repo_path": "jlp_numeric/old/fftw2_src/fftw-int.h", "max_stars_repo_name": "jlprieur/jlplib", "max_stars_repo_head_hexsha": "6073d7a7eb76d916662b1f8a4eb54f345cf7c772", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "jlp_numeric/old/fftw2_src/fftw-int.h", "max_issues_repo_name": "jlprieur/jlplib", "max_issues_repo_head_hexsha": "6073d7a7eb76d916662b1f8a4eb54f345cf7c772", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jlp_numeric/old/fftw2_src/fftw-int.h", "max_forks_repo_name": "jlprieur/jlplib", "max_forks_repo_head_hexsha": "6073d7a7eb76d916662b1f8a4eb54f345cf7c772", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-09T00:20:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-09T00:20:49.000Z", "avg_line_length": 32.9978632479, "max_line_length": 90, "alphanum_fraction": 0.6478663472, "num_tokens": 3840, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3140505321516081, "lm_q2_score": 0.028436034485735198, "lm_q1q2_score": 0.008930351762526618}}
{"text": "#pragma once\n\n#include \"types/type_util.h\"\n\n#include <expected.hpp>\n#include <gsl/gsl>\n#include <sstream>\n#include <variant>\n\nnamespace util {\n\ntemplate<typename... Args>\nstd::string\nconcat(const Args&... args)\n{\n  std::stringstream ss;\n  (ss << ... << args);\n  return ss.str();\n}\n\nnamespace detail {\ntemplate<typename T>\nT\nstr_to(const std::string& str, std::size_t* pos, int base)\n{\n  static_assert(AlwaysFalse<T>::value, \"try_parse_number not defined for type T!\");\n}\n\n#define GEN_STR_TO_SPECIALIZATION(type, func)                                                      \\\n  template<>                                                                                       \\\n  inline type str_to(const std::string& str, std::size_t* pos, int base)                           \\\n  {                                                                                                \\\n    const auto parsed = func(str, pos, base);                                                      \\\n    if (parsed > std::numeric_limits<type>::max()) {                                               \\\n      throw std::out_of_range{ \"Value is out of range for type \" #type };                          \\\n    }                                                                                              \\\n    return gsl::narrow_cast<type>(parsed);                                                         \\\n  }\n\nGEN_STR_TO_SPECIALIZATION(uint8_t, std::stoul)\nGEN_STR_TO_SPECIALIZATION(int8_t, std::stol)\nGEN_STR_TO_SPECIALIZATION(uint16_t, std::stoul)\nGEN_STR_TO_SPECIALIZATION(int16_t, std::stol)\nGEN_STR_TO_SPECIALIZATION(uint32_t, std::stoul)\nGEN_STR_TO_SPECIALIZATION(int32_t, std::stol)\nGEN_STR_TO_SPECIALIZATION(uint64_t, std::stoull)\nGEN_STR_TO_SPECIALIZATION(int64_t, std::stoll)\n\ntemplate<>\ninline float\nstr_to(const std::string& str, std::size_t* pos, int)\n{\n  return std::stof(str, pos);\n}\n\ntemplate<>\ninline double\nstr_to(const std::string& str, std::size_t* pos, int)\n{\n  return std::stod(str, pos);\n}\n\ntemplate<>\ninline long double\nstr_to(const std::string& str, std::size_t* pos, int)\n{\n  return std::stold(str, pos);\n}\n\n}\n\n/**\n * Wrapper around the std::stoX functions. Tries to parse the given string as a number\n * of the given type and returns a tl::expected with the resulting number of the reason\n * for failure. The arguments are the same as for the std functions, with the exception that\n * base is only valid if T is an integer type\n */\ntemplate<typename T>\ntl::expected<T, std::variant<std::invalid_argument, std::out_of_range>>\ntry_parse_number(const std::string& str, std::size_t* pos = nullptr, int base = 10)\n{\n  try {\n    const auto number = detail::str_to<T>(str, pos, base);\n    return { number };\n  } catch (const std::invalid_argument& ex) {\n    return tl::make_unexpected(std::variant<std::invalid_argument, std::out_of_range>{ ex });\n  } catch (const std::out_of_range& ex) {\n    return tl::make_unexpected(std::variant<std::invalid_argument, std::out_of_range>{ ex });\n  }\n}\n\n} // namespace util", "meta": {"hexsha": "44263c55abcae12744170bf2fb2e4a358987bf7c", "size": 3006, "ext": "h", "lang": "C", "max_stars_repo_path": "schwarzwald/util/algorithms/Strings.h", "max_stars_repo_name": "igd-geo/schwarzwald", "max_stars_repo_head_hexsha": "e3e041f87c93985394444ee056ce8ba7ae62194b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2021-01-06T14:16:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T00:15:17.000Z", "max_issues_repo_path": "schwarzwald/util/algorithms/Strings.h", "max_issues_repo_name": "igd-geo/schwarzwald", "max_issues_repo_head_hexsha": "e3e041f87c93985394444ee056ce8ba7ae62194b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-25T08:37:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T06:28:06.000Z", "max_forks_repo_path": "schwarzwald/util/algorithms/Strings.h", "max_forks_repo_name": "igd-geo/schwarzwald", "max_forks_repo_head_hexsha": "e3e041f87c93985394444ee056ce8ba7ae62194b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T13:50:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T11:45:45.000Z", "avg_line_length": 32.6739130435, "max_line_length": 100, "alphanum_fraction": 0.5831669993, "num_tokens": 688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.26894142136999516, "lm_q2_score": 0.03308598220236406, "lm_q1q2_score": 0.008898191080926154}}
{"text": "#ifndef IAIF_H\n#define IAIF_H\n\n#include <utility>\n#include <tuple>\n\n#include <gsl/gsl_vector.h>\n\n#include \"constants.h\"\n#include \"lpc.h\"\n#include \"filter.h\"\n\nvoid computeIAIF(gsl_vector *g, gsl_vector *dg, gsl_vector *x);\n\n\n#endif // IAIF_H\n", "meta": {"hexsha": "dc65fd75ab1434aa53b8c1310c90298d766465c0", "size": 241, "ext": "h", "lang": "C", "max_stars_repo_path": "inc/iaif.h", "max_stars_repo_name": "ichi-rika/glottal-inverse", "max_stars_repo_head_hexsha": "c922ed540278e3c8eec528c2cf66b89e6d310575", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-01-24T17:01:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-26T16:22:08.000Z", "max_issues_repo_path": "inc/iaif.h", "max_issues_repo_name": "ichi-rika/glottal-inverse", "max_issues_repo_head_hexsha": "c922ed540278e3c8eec528c2cf66b89e6d310575", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inc/iaif.h", "max_forks_repo_name": "ichi-rika/glottal-inverse", "max_forks_repo_head_hexsha": "c922ed540278e3c8eec528c2cf66b89e6d310575", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-04-27T00:23:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-27T14:41:25.000Z", "avg_line_length": 14.1764705882, "max_line_length": 63, "alphanum_fraction": 0.7178423237, "num_tokens": 69, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.2942149721629888, "lm_q2_score": 0.030214584447621016, "lm_q1q2_score": 0.008889583122173092}}
{"text": "/******************************************************************************\n* Copyright 2018 The Apollo Authors. All Rights Reserved.\n*\n* Licensed under the Apache License, Version 2.0 (the License);\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an AS IS BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*****************************************************************************/\n#pragma once\n\n#include <cblas.h>\n\n#include \"modules/perception/camera/common/camera_frame.h\"\n\nnamespace apollo {\nnamespace perception {\nnamespace camera {\n\nclass BaseSimilar {\n public:\n  virtual bool Calc(CameraFrame *frame1,\n                    CameraFrame *frame2,\n                    base::Blob<float> *sim) = 0;\n};\n\nclass CosineSimilar : public BaseSimilar {\n public:\n  CosineSimilar() = default;\n\n  bool Calc(CameraFrame *frame1,\n            CameraFrame *frame2,\n            base::Blob<float> *sim) override;\n};\n\nclass GPUSimilar : public BaseSimilar {\n public:\n  bool Calc(CameraFrame *frame1,\n            CameraFrame *frame2,\n            base::Blob<float> *sim) override;\n};\n}  // namespace camera\n}  // namespace perception\n}  // namespace apollo\n", "meta": {"hexsha": "c57916c5ece081b7cfe3a12dc4e20aaf8004aef2", "size": 1510, "ext": "h", "lang": "C", "max_stars_repo_path": "modules/perception/camera/lib/obstacle/tracker/common/similar.h", "max_stars_repo_name": "ghdawn/apollo", "max_stars_repo_head_hexsha": "002eba4a1635d6af7f1ebd2118464bca6f86b106", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-01-15T08:34:59.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-15T08:35:00.000Z", "max_issues_repo_path": "modules/perception/camera/lib/obstacle/tracker/common/similar.h", "max_issues_repo_name": "thomasgui76/apollo", "max_issues_repo_head_hexsha": "808f1d20a08efea23b718b4e423d6619c9d4b412", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/perception/camera/lib/obstacle/tracker/common/similar.h", "max_forks_repo_name": "thomasgui76/apollo", "max_forks_repo_head_hexsha": "808f1d20a08efea23b718b4e423d6619c9d4b412", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-02-24T06:20:29.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-24T06:20:29.000Z", "avg_line_length": 29.6078431373, "max_line_length": 79, "alphanum_fraction": 0.6298013245, "num_tokens": 306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356685373537454, "lm_q2_score": 0.021948253554929756, "lm_q1q2_score": 0.008857587632149251}}
{"text": "/**\n * Original Author:\n * * author: Jochen K\"upper\n * * created: April 2002\n * \n * author: Pierre Schnizer\n * created: December 2003\n * file: pygsl/src/simanmodule.c\n * $Id: simanmodule.c,v 1.9 2008/10/25 20:45:04 schnizer Exp $\n *\n * Jochen K\"upper wrote the original version of this module. In December 2003 I\n * rewrote it. Now I only support the variable type as it is more pythonic.\n *\n */\n\n#include <Python.h>\n#include <math.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <setjmp.h>\n#include <gsl/gsl_siman.h>\n#include <gsl/gsl_nan.h>\n#include <pygsl/error_helpers.h>\n#include <pygsl/general_helpers.h>\n#include <pygsl/rng.h>\n#include <pygsl/rng_helpers.h>\n\n/*\n * Common to all objects of one problem\n * Currently the individual method pointers are not used. Instead the method \n * is resolved every time. Do you know which method is faster? Is it advicable\n * to resolve it once and store it here? Pierre\n */\ntypedef struct{\n\t/*\n\t  PyObject * efunc;\n\t  PyObject * step;\n\t  PyObject * metric;\n\t  PyObject * print;\n\t*/\n\tPyObject * rng;\n\tjmp_buf  buffer;\n}pygsl_siman_func_t;\n\n/*\n * The Linked list keeping the reference to the individual objects.\n *\n * Necessary as I have to use longjmp as the current implementation does \n * not allow error propagation yet!\n */\nstruct _pygsl_siman_t{\n\tpygsl_siman_func_t *func;\n\tPyObject * x;\n\tstruct _pygsl_siman_t * prev;\n\tstruct _pygsl_siman_t * next;\n};\ntypedef struct _pygsl_siman_t pygsl_siman_t;\n\n\n\nstatic const char module_doc[] = \"C Implementation needed for the siman module.\";\nstatic PyObject *module = NULL;\nstatic const char filename[] = __FILE__;\n\n/*\n * Naming of the various methods the object has provide as callbacks.\n */\nstatic const char EFunc_name[]  = \"EFunc\";\nstatic const char Metric_name[] = \"Metric\";\nstatic const char Step_name[]   = \"Step\";\nstatic const char Clone_name[]  = \"Clone\";\nstatic const char Print_name[]  = \"Print\";\n\n\n/*\n * Get a callable method from a object.\n *\n * Basically it is a flat wrapper around PyObject_GetAttrString but \n * checks if the method is callable and adds a Traceback frame\n *\n * Flag usage: \n *           flag == 1 Must exist and must be callable\n *           flag == 2 If it exists it must be callable \n *\n * For the traceback frame all arguments following the module are needed.\n * If you do not know the module, you can pass a NULL pointer.\n */\nstatic PyObject *\nPyGSL_get_callable_method(PyObject *o, const char * attr, int flag, PyObject *module,\n\t\t\t  const char * filename, const char * func_name,\n\t\t\t  int lineno)\n{\n\tPyObject * method = NULL;\n\n\tFUNC_MESS_BEGIN();\n\tmethod = PyObject_GetAttrString(o, (char *) attr);\n\tif(method == NULL){\n\t\tif(flag == 1){\n\t\t\tPyGSL_add_traceback(module, filename, func_name, lineno);\n\t\t}else if(flag == 2){\n\t\t\t/* Clear the error otherwise it will show up later on! */\n\t\t\tPyErr_Clear();\n\t\t}\t\t\n\t\treturn NULL;\n\t}\n\tif(!(PyCallable_Check(method))) {\n\t\t/* I must add the method name! I must change it to an more descriptive exception! */\n\t\tPyGSL_add_traceback(module, (const char *) filename, func_name, lineno);\n\t\tPyErr_SetString(PyExc_TypeError, \"Found a attribute which was not callable!\" \n\t\t\t\t\"XXX must add the method name!\");\n\t\treturn NULL;\n\t}\n\tDEBUG_MESS(2, \"Found a method at %p\", (void *) method);\n\tFUNC_MESS_END();\n\treturn method;\n}\n\n/* This function type should return the energy of a configuration XP. */\nstatic double \nPyGSL_siman_efunc(void *xp)\n{\n\n\t\n\tPyObject *result = NULL, *callback = NULL, *arglist = NULL;\n\tPyGSL_error_info info;\n\tpygsl_siman_t *x;\n\tint flag=GSL_EFAILED;\n\tdouble value;\n\t/* static char *functionname  = __FUNCTION__; */\n\n\tFUNC_MESS_BEGIN();\n\n\tassert(xp);\t\n\tx = (pygsl_siman_t *) xp;\n\n\tDEBUG_MESS(2, \"Found a pygsl_siman_t at %p and a pygsl_siman_func_t at %p and x at %p\", \n\t\t   (void *)x, (void *) x->func, (void *) x->x);\n\n\tassert(x);\n\tassert(x->func);\n\n\tcallback = PyGSL_get_callable_method(x->x, EFunc_name, 1, module, filename, __FUNCTION__, __LINE__);\n\tif(callback == NULL)\n\t\tgoto fail;\n\n\tinfo.callback = callback;\n\tinfo.message  = __FUNCTION__;\n\tinfo.error_description = \"and the description ???\";\n\tinfo.argnum = 1;\n\n\targlist = PyTuple_New(0);\n\tresult = PyEval_CallObject(callback, arglist);\n\tPy_DECREF(arglist);\n\tif((flag = PyGSL_CHECK_PYTHON_RETURN(result, 1, &info)) != GSL_SUCCESS){\n\t\tPyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__);\n\t\tgoto fail;\n\t}\n\tif((flag = PyGSL_PYFLOAT_TO_DOUBLE(result, &value, &info)) != GSL_SUCCESS){\n\t\tPyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__);\n\t\tgoto fail;\n\t}\n\tPy_DECREF(result);\n\tFUNC_MESS_END();\n\treturn value;\n\n  fail:\n\tFUNC_MESS(\"In Fail\");\n\tPy_XDECREF(result);\n\tlongjmp(x->func->buffer, flag);\n\treturn GSL_NAN;\n}\n\n\n\n/* \n *  This function type should modify the configuration XP using a random step\n *  taken from the generator R, up to a maximum distance of STEP_SIZE. \n */\nstatic void \nPyGSL_siman_step(const gsl_rng *r, void *xp, double step_size)\n{\n\n\n\tPyObject *result = NULL, *arglist = NULL, *callback = NULL;\n\tPyGSL_error_info info;\n\tpygsl_siman_t *x;\n\tint flag=GSL_EFAILED;\n\n\t/* static const char * functionname  = __FUNCTION__; */\n\n\tFUNC_MESS_BEGIN();\n\tx = (pygsl_siman_t *) xp;\n\tDEBUG_MESS(2, \"Found x at %p\", xp);\n\n\tcallback = PyGSL_get_callable_method(x->x, Step_name, 1, module, filename, __FUNCTION__, __LINE__);\n\tif(callback == NULL)\n\t\tgoto fail;\n\n\tinfo.callback = callback;\n\tinfo.message  = __FUNCTION__;\n\tinfo.error_description = \"???\";\n\tinfo.argnum = 1;\n\n\tassert(PyGSL_RNG_Check(x->func->rng));\n\tassert(((PyGSL_rng *) x->func->rng)->rng == r);\n\n\t/* create argument list */\n\targlist = PyTuple_New(2);\n\tPyTuple_SET_ITEM(arglist, 0, x->func->rng); \n\tPy_INCREF(x->func->rng); /* Don't forget tuple is owner! */\n\tPyTuple_SET_ITEM(arglist, 1, PyFloat_FromDouble(step_size));\n\n\tresult = PyEval_CallObject(callback, arglist);\n\tPy_DECREF(arglist);\n\tif((flag = PyGSL_CHECK_PYTHON_RETURN(result, 0, &info)) != GSL_SUCCESS){\n\t\tPyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__);\n\t\tgoto fail;\n\t}\n\tPy_DECREF(result);\n\tFUNC_MESS_END();\n\treturn;\n\n  fail:\n\tFUNC_MESS(\"In Fail\");\n\tPy_XDECREF(result);\n\tlongjmp(x->func->buffer, flag);\n\treturn;\n}\n\n\n\n/* This function type should return the distance between two configurations XP\n   and YP. */\nstatic double \nPyGSL_siman_metric(void *xp, void *yp)\n{\n\n\tPyObject *result = NULL, *arglist = NULL, *callback = NULL;\n\tPyGSL_error_info info;\n\tpygsl_siman_t *x, *y;\n\tint flag=GSL_EFAILED;\n\tdouble value;\n\t/* static const char * functionname = __FUNCTION__; */\n\n\tFUNC_MESS_BEGIN();\n\tx = (pygsl_siman_t *) xp;\n\ty = (pygsl_siman_t *) yp;\n\n\tDEBUG_MESS(2, \"Found x at (%p,%p) and y at (%p %p)\", \n\t\t   (void *) x, (void *)x->x, (void *) y, (void *) y->x);\n\n\tassert(x);\n\tassert(y);\n\tassert(x->x);\n\tassert(y->x);\n\n\tcallback = PyGSL_get_callable_method(x->x, Metric_name, 1, module, filename, __FUNCTION__, __LINE__);\n\tif(callback == NULL)\n\t\tgoto fail;\n\n\tinfo.callback = callback;\n\tinfo.message  = __FUNCTION__;\n\tinfo.error_description = \"???\";\n\tinfo.argnum = 1;\n\t\t\n\targlist = PyTuple_New(1);\n\tPyTuple_SET_ITEM(arglist, 0, y->x); \n\tPy_INCREF(y->x); /* Tuple is owner! */\n\n\tresult = PyEval_CallObject(callback, arglist);\n\tPy_XDECREF(arglist);\n\n\tif((flag = PyGSL_CHECK_PYTHON_RETURN(result, 0, &info)) != GSL_SUCCESS){\n\t\tPyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__);\n\t\tgoto fail;\n\t}\n\tif((flag = PyGSL_PYFLOAT_TO_DOUBLE(result, &value, &info)) != GSL_SUCCESS){\n\t\tPyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__);\n\t\tgoto fail;\n\t}\n\tPy_DECREF(result);\n\tFUNC_MESS_END();\n\treturn value;\n\n  fail:\n\tFUNC_MESS(\"In Fail\");\n\tPy_XDECREF(result);\n\tlongjmp(x->func->buffer, flag);\n\treturn GSL_NAN;\n}\n\n\n\n/* This function type should print the contents of the configuration XP. */\nstatic void \nPyGSL_siman_print(void *xp)\n{\n\tPyObject *result = NULL, *callback=NULL, *arglist=NULL;\n\tPyGSL_error_info info;\n\tpygsl_siman_t *x;\n\tint flag=GSL_EFAILED;\n\t/* static const char * functionname  = __FUNCTION__; */\n\n\tFUNC_MESS_BEGIN();\n\tx = (pygsl_siman_t *) xp;\n\n\tcallback = PyGSL_get_callable_method(x->x, Print_name, 1, module, filename, __FUNCTION__, __LINE__);\n\tif(callback == NULL)\n\t\tgoto fail;\n\n\tinfo.callback = callback;\n\tinfo.message  = __FUNCTION__;\n\tinfo.error_description = \"what goes here ???\";\n\tinfo.argnum = 1;\n\t\t\n\targlist = PyTuple_New(0);\n\tresult = PyEval_CallObject(callback, arglist);\n\tPy_DECREF(arglist);\n\n\tif((flag = PyGSL_CHECK_PYTHON_RETURN(result, 0, &info)) != GSL_SUCCESS){\n\t\tPyGSL_add_traceback(module, (const char*)filename, __FUNCTION__, __LINE__);\n\t\tgoto fail;\n\t}\n\tPy_DECREF(result);\n\tFUNC_MESS_END();\n\treturn;\n\n  fail:\n\tFUNC_MESS(\"In Fail\");\n\tPy_XDECREF(result);\n\tlongjmp(x->func->buffer, flag);\n\treturn;\n\n}\n\n/*\n * As Python is generating the new objects I can not skip the reference \n * counting, but must add a reference for each object in construct and \n * depose it here and in the siman_destroy function.\n *\n * siman_solve will call siman_release_x anyway at the end to clear up\n * all objects. Necessary to non existing error propagation in the siman\n * module.\n */\nstatic void \nPyGSL_siman_copy(void *src, void *dst)\n{\n\tPyObject *callback=NULL, *new = NULL, *arglist = NULL;\n\tPyGSL_error_info info;\n\tpygsl_siman_t *x, *y;\n\tint flag=GSL_EFAILED;\n\t/* static const char * functionname = __FUNCTION__; */\n\n\tFUNC_MESS_BEGIN();\n\tx = (pygsl_siman_t *) src;\n\ty = (pygsl_siman_t *) dst;\n\t\n\tDEBUG_MESS(2, \"Got source at %p, Destination at %p\", (void *) x, (void *) y);\n\tassert(x->x);\n\tcallback = PyGSL_get_callable_method(x->x, Clone_name, 1, module, filename, __FUNCTION__, __LINE__);\n\tif(callback == NULL)\n\t\tgoto fail;\n\n\targlist = PyTuple_New(0);\n\tnew = PyEval_CallObject(callback, arglist);\n\tPy_DECREF(arglist);\n\n\tinfo.callback = callback;\n\tinfo.message  = __FUNCTION__;\n\tinfo.error_description = \"???\";\n\tinfo.argnum = 1;\n\n\tif((flag = PyGSL_CHECK_PYTHON_RETURN(new, 1, &info)) != GSL_SUCCESS){\n\t\tPyGSL_add_traceback(module, (const char*)filename, __FUNCTION__, __LINE__);\n\t\tgoto fail;\n\t}\n\tPy_XDECREF(y->x);\n\t/* Py_INCREF(new);  Necessary? I don't think so. */\n\ty->x = new;\n\tFUNC_MESS_END();\n\treturn;\n\n  fail:\n\tFUNC_MESS(\"Fail\");\n\tPy_XDECREF(new);\n\tlongjmp(x->func->buffer, flag);\n\t\n}\n\nstatic void *\nPyGSL_siman_copy_construct(void *new)\n{\n\tpygsl_siman_t * ret, * n, *p;\n\tint flag = GSL_ENOMEM;\n\t\n\tFUNC_MESS_BEGIN();\n\tn   = (pygsl_siman_t *) new;\n\n\t/* The pointers next and prev are checked against NULL */\n\tret = (pygsl_siman_t *) calloc(1, sizeof(pygsl_siman_t));\n\tDEBUG_MESS(2, \"New was %p, Constructed a new object at %p\", new, (void *) ret);\n\tif(ret == NULL){\n\t\tpygsl_error(\"Could not allocate the object for the linked list\", \n\t\t\t  filename, __LINE__ - 3, GSL_ENOMEM);\n\t\tgoto fail;\t\n\t}\n\t/* Put the Link to the old object so that I can clone when I need to copy */\n\tret->x    = n->x;\n\t/* Eventually I will dispose the object */\n\tPy_INCREF(ret->x);\n\t/* Pointer to the func struct. This information is the same for all objects */\n\tret->func = n->func;\n\n\n\t/* Find the first open object in the linked list ... */\n\tp = n;\n\twhile(p->next != NULL){\n\t\tp = p->next;\n\t}\n\tDEBUG_MESS(2, \"I found a open object at %p\", (void *) p);\n\t/* and connect the links */\n\tp->next = ret;\n\tret->prev = p;\n\n\tFUNC_MESS_END();\n\treturn ret;\n\n  fail:\n\tFUNC_MESS(\"Fail\");\n\tlongjmp(n->func->buffer, flag);\n\treturn NULL;\n\n}\n\nstatic void\nPyGSL_siman_destroy(void * old)\n{\n\tpygsl_siman_t * o;\n\n\tFUNC_MESS_BEGIN();\n\to = (pygsl_siman_t *) old;\t\n\tassert(o);\n\n\n\t/* fprintf(stderr, \"Destroying: Previous object = %p, Next Object = %p\\n\", \n\t   (void *)o->prev, (void *)o->next); */\n\n\t/* Reconnect the linked list */\n\tif (o->prev && o->next){\n\t\t/* Connect the both */\n\t\to->prev->next = o->next;\n\t\to->next->prev = o->prev;\n\t}\n\telse if (o->prev && o->next == NULL){\n\t\t/* Prev last element. Terminate the list */\n\t\to->prev->next = NULL;\n\t}\n\telse if (o->prev == NULL && o->next == NULL){\n\t\t/* Last Element, better to leave it */\n\t\tDEBUG_MESS(2, \"I do not dispose the last element %p!\", (void *) o);\n\t\treturn;\n\t}\n\t\n\t/* Dispose the object */\n\tPy_XDECREF(o->x);\n\tfree(o);\n\tFUNC_MESS_END();\n}\n\n/* Clean up of the linked list of objects */\nint \nPyGSL_siman_release_x(pygsl_siman_t * myargs, pygsl_siman_t * x)\n{\n\tpygsl_siman_t *p=NULL;\n\tFUNC_MESS_BEGIN();\n\n\tp = myargs;\n\t/* fprintf(stderr, \"Releasing list!\\n\"); */\n\twhile(1){\t\t\n\t\t/* fprintf(stderr, \"Previous object = %p, Next Object = %p\\n\", \n\t\t   (void *)p->prev, (void *)p->next); */\n\t\t/* Don't delete the object containing the result! */\n\t\tif(p != x){\n\t\t\t/* fprintf(stderr, \"Deleting object at %p\\n\", (void *) p); */\n\t\t\tPyGSL_siman_destroy((void *) p);\n\t\t}\n\t\tif(p->next == NULL)\n\t\t\tbreak;\n\t\tp = p->next;\n\t}\n\tFUNC_MESS_END();\n\treturn GSL_SUCCESS;\n}\n\nstatic const char pygsl_siman_solve_doc[] = \n\"Simulated annealing driver.\\n\\\n\\n\\\nUsage:\\n\\\nresult = solve(r, x0, ...)\\n\\\n\\n\\\nInput:\\n\\\n    r   ... a random generator from pygsl.rng\\n\\\n    x0  ... a configuration. It must be an object providing the following\\n\\\n            methods:\\n\\\n            EFunc()\\n\\\n            Metric()\\n\\\n            Step()\\n\\\n            Clone()\\n\\\n               If you want to use the print functionality you must provide\\n\\\n               the following method:\\n\\\n            Print()\\n\\\n\\n\\\nOutput:\\n\\\n    result ... a object of type x0 with the final value.\\n\\\n\\n\\\nKeywords:\\n\\\n    n_tries       = 200  ... how many points to try for each step\\n\\\n    iters_fixed_T = 10   ... how many iterations at each temperature?\\n\\\n    step_size     = 10   ... max step size in the random walk\\n\\\n\\n\\\n                      parameters for the Boltzmann distribution\\n\\\n    k             = 1.0    ... Boltzmann constant\\n\\\n    t_initial     = 0.002  ... initial temperature\\n\\\n    mu_t          = 1.005  ... damping factor for the temperature\\n\\\n    t_min         = 2.0e-6\\n\\\n\\n\\\n    do_print      = 0      ... print the status of the annealing process\\n\\\n                               (== 0: do not print)\\n\\\n                               ( > 0: print)\\n\\\n\";\n\n\n/* wrapper functions */\nstatic PyObject *\nPyGSL_siman_solve(PyObject *self, PyObject *args, PyObject *kw)\n{\n\tPyObject *result = NULL;\n\tPyObject *efunc = NULL, *step = NULL, *metric = NULL, *clone = NULL,\n\t\t *print = NULL, *r_o = NULL, *x_o=NULL;\n\n\tgsl_rng *rng = NULL;\n\n\tgsl_siman_print_t    a_print= PyGSL_siman_print;\n\tgsl_siman_params_t   params = {200, 10, 10.0, 1.0, 0.002, 1.005, 2.0e-6};\n\n\n\tpygsl_siman_func_t   myargs_func = {NULL};\n\tpygsl_siman_t        myargs = {NULL, NULL, NULL, NULL}; \n\t\n\n\t/* static const char  * functionname = __FUNCTION__; */\n\n\tint flag=GSL_EFAILED, do_print=0;\n\tvoid * x0 = NULL;\n\n\tstatic const char * kwlist[] = {\"rng\", \"x0\", \"n_tries\", \"iters_fixed_T\", \"step_size\", \"k\",\n\t\t\t\t\t\"t_initial\", \"mu_t\",  \"t_min\", \"do_print\", NULL};\n\n\tFUNC_MESS_BEGIN();\n\t/* python arguments are (rng, x0, settings) */\n\tif(! PyArg_ParseTupleAndKeywords(args, kw, \"OO|iidddddi\",  (char **) kwlist, &r_o, &x_o,\n\t\t\t      &params.n_tries, &params.iters_fixed_T, &params.step_size,\n\t\t\t      &params.k, &params.t_initial, &params.mu_t, &params.t_min, &do_print))\n\t\treturn NULL;\n\n\t/* The following methods must exist */\n\tefunc  = PyGSL_get_callable_method(x_o, EFunc_name,  1, module, filename, __FUNCTION__, __LINE__);\n\tstep   = PyGSL_get_callable_method(x_o, Step_name,   1, module, filename, __FUNCTION__, __LINE__);\n\tmetric = PyGSL_get_callable_method(x_o, Metric_name, 1, module, filename, __FUNCTION__, __LINE__);\n\tclone  = PyGSL_get_callable_method(x_o, Clone_name,  1, module, filename, __FUNCTION__, __LINE__);\n\tif( efunc == NULL || step == NULL || metric == NULL || clone == NULL){\n\t\treturn NULL;\n\t}\n\t\n\t/* optional print */\n\tif(do_print == 0){\n\t\ta_print = NULL;\t\t\n\t} else {\n\t\tprint  = PyGSL_get_callable_method(x_o, Print_name,  1, module, filename, __FUNCTION__, __LINE__);\n\t\tif(print == NULL){\n\t\t\tDEBUG_MESS(2, \"Did not get a print method! print = %p\", print);\n\t\t\ta_print = NULL;\n\t\t\treturn NULL;\n\t\t}\n\t}\n\n\trng = PyGSL_gsl_rng_from_pyobject(r_o);\n\tif(rng == NULL){\n\t\treturn NULL;\n\t}\n\n\n\t/* initialize/assign functions */\n\tPy_INCREF(x_o);\n\t/*\n\t  myargs_func.efunc  = efunc;\n\t  myargs_func.step   = step;\n\t  myargs_func.metric = metric;\n\t  myargs_func.print  = print;\n\t*/\n\tmyargs_func.rng    = r_o;\n\n\tmyargs.func = &myargs_func;\n\tmyargs.x   = x_o;\n\tmyargs.prev = NULL;\n\tmyargs.next = NULL;\n\n\tx0 = (void *) &myargs;\n\tDEBUG_MESS(2, \"x0 @ %p; myargs at %p; myargs_func at %p\", x0, (void *) &myargs, (void *) &myargs_func);\n\tDEBUG_MESS(2, \"Found a pygsl_siman_t at %p and a pygsl_siman_func_t at %p\", \n\t\t   (void *) x0, \n\t\t   (void *) (((pygsl_siman_t *) x0)->func));\n\n\tif((flag = setjmp(myargs_func.buffer)) == 0){\n\t\tFUNC_MESS(\"Starting siman\");\n\t\tgsl_siman_solve(rng, x0, PyGSL_siman_efunc, PyGSL_siman_step,\n\t\t\t\tPyGSL_siman_metric, a_print, PyGSL_siman_copy,\n\t\t\t\tPyGSL_siman_copy_construct, PyGSL_siman_destroy,\n\t\t\t\t0, /* Only variable mode supported by this wrapper. */\n\t\t\t\tparams);\n\t\tFUNC_MESS(\"End siman\");\n\t}else{\n\t\tPyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__);\n\t\tgoto fail;\n\t}\n\tPy_DECREF(x_o);\n\tDEBUG_MESS(2, \"I found x0 at %p\", x0);\n\tresult = ((pygsl_siman_t *) x0)->x;\n\n\tPyGSL_siman_release_x(&myargs, x0);\n\tFUNC_MESS_END();\n\treturn result;\n\n  fail:\n\tFUNC_MESS(\"In Fail\");\n\tPyGSL_siman_release_x(&myargs, x0);\n\tPy_XDECREF(x_o);\n\tPyGSL_error_flag(flag);\n\treturn NULL;\n}\n\n\n/* module initialization */\nstatic PyMethodDef simanMethods[] = {\n\t{\"solve\", (PyCFunction) PyGSL_siman_solve, \n\t METH_VARARGS | METH_KEYWORDS, (char *) pygsl_siman_solve_doc},\n\t{NULL, NULL} /* Sentinel */\n};\n\n\n\nDL_EXPORT(void) init_siman(void)\n{\n\tPyObject *m = NULL;\n\tFUNC_MESS_BEGIN();\n\tm = Py_InitModule(\"_siman\", simanMethods);\n\tmodule = m;\n\tinit_pygsl();\n\timport_pygsl_rng();\n\tFUNC_MESS_END();\n\treturn;\n}\n\n\n\n/*\n * Local Variables:\n * mode: C\n * c-file-style: \"python\"\n * End:\n */\n\n", "meta": {"hexsha": "7accc521496ed465f6bc464e936132f262e97494", "size": 17655, "ext": "c", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/src/simanmodule.c", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/src/simanmodule.c", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/src/simanmodule.c", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 26.2332838039, "max_line_length": 104, "alphanum_fraction": 0.6714811668, "num_tokens": 5165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23370634623958197, "lm_q2_score": 0.03789242771609848, "lm_q1q2_score": 0.008855700831676843}}
{"text": "#pragma once\n\n#include \"Common.h\"\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/depth_first_search.hpp>\n#include <boost/graph/edge_list.hpp>\n#include <boost/graph/graph_selectors.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/graph/visitors.hpp>\n#include <any>\n#include <forward_list>\n#include <functional>\n#include <gsl/span>\n#include <set>\n#include <string_view>\n#include <variant>\n\nnamespace bcos::scheduler\n{\nclass GraphKeyLocks\n{\npublic:\n    using Ptr = std::shared_ptr<GraphKeyLocks>;\n    using KeyLock = std::tuple<std::string, std::string>;\n    using KeyLockView = std::tuple<std::string_view, std::string_view>;\n\n    using ContractView = std::string_view;\n    using KeyView = std::string_view;\n\n    GraphKeyLocks() = default;\n    GraphKeyLocks(const GraphKeyLocks&) = delete;\n    GraphKeyLocks(GraphKeyLocks&&) = delete;\n    GraphKeyLocks& operator=(const GraphKeyLocks&) = delete;\n    GraphKeyLocks& operator=(GraphKeyLocks&&) = delete;\n\n    bool batchAcquireKeyLock(std::string_view contract, gsl::span<std::string const> keyLocks,\n        ContextID contextID, Seq seq);\n\n    bool acquireKeyLock(\n        std::string_view contract, std::string_view key, ContextID contextID, Seq seq);\n\n    std::vector<std::string> getKeyLocksNotHoldingByContext(\n        std::string_view contract, ContextID excludeContextID) const;\n\n    void releaseKeyLocks(ContextID contextID, Seq seq);\n\n    bool detectDeadLock(ContextID contextID);\n\n    struct Vertex : public std::variant<ContextID, KeyLock>\n    {\n        using std::variant<ContextID, KeyLock>::variant;\n\n        bool operator==(const KeyLockView& rhs) const\n        {\n            if (index() != 1)\n            {\n                return false;\n            }\n\n            auto view = std::make_tuple(std::string_view(std::get<0>(std::get<1>(*this))),\n                std::string_view(std::get<1>(std::get<1>(*this))));\n            return view == rhs;\n        }\n    };\n\nprivate:\n    struct VertexIterator\n    {\n        using kind = boost::vertex_property_tag;\n    };\n    using VertexProperty = boost::property<VertexIterator, const Vertex*>;\n    struct EdgeSeq\n    {\n        using kind = boost::edge_property_tag;\n    };\n    using EdgeProperty = boost::property<EdgeSeq, int64_t>;\n\n    using Graph = boost::adjacency_list<boost::multisetS, boost::multisetS, boost::bidirectionalS,\n        VertexProperty, EdgeProperty>;\n    using VertexPropertyTag = boost::property_map<Graph, VertexIterator>::const_type;\n    using EdgePropertyTag = boost::property_map<Graph, EdgeSeq>::const_type;\n    using VertexID = Graph::vertex_descriptor;\n    using EdgeID = Graph::edge_descriptor;\n\n    Graph m_graph;\n    std::map<Vertex, VertexID, std::less<>> m_vertexes;\n\n    VertexID touchContext(ContextID contextID);\n    VertexID touchKeyLock(KeyLockView keylockView);\n\n    void addEdge(VertexID source, VertexID target, Seq seq);\n    void removeEdge(VertexID source, VertexID target, Seq seq);\n};\n\n}  // namespace bcos::scheduler\n\nnamespace std\n{\ninline bool operator<(const bcos::scheduler::GraphKeyLocks::Vertex& lhs,\n    const bcos::scheduler::GraphKeyLocks::KeyLockView& rhs)\n{\n    if (lhs.index() != 1)\n    {\n        return true;\n    }\n\n    auto view = std::make_tuple(std::string_view(std::get<0>(std::get<1>(lhs))),\n        std::string_view(std::get<1>(std::get<1>(lhs))));\n    return view < rhs;\n}\n\ninline bool operator<(const bcos::scheduler::GraphKeyLocks::KeyLockView& lhs,\n    const bcos::scheduler::GraphKeyLocks::Vertex& rhs)\n{\n    if (rhs.index() != 1)\n    {\n        return false;\n    }\n\n    auto view = std::make_tuple(std::string_view(std::get<0>(std::get<1>(rhs))),\n        std::string_view(std::get<1>(std::get<1>(rhs))));\n    return lhs < view;\n}\n}  // namespace std", "meta": {"hexsha": "bd436ed17a54cb7d20444311a2ad1fc32a205dc0", "size": 3747, "ext": "h", "lang": "C", "max_stars_repo_path": "bcos-scheduler/src/GraphKeyLocks.h", "max_stars_repo_name": "xueying4402/FISCO-BCOS", "max_stars_repo_head_hexsha": "737e08752e8904c7c24e3737f8f46bf5327ef792", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-06T10:46:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T10:46:12.000Z", "max_issues_repo_path": "bcos-scheduler/src/GraphKeyLocks.h", "max_issues_repo_name": "xueying4402/FISCO-BCOS", "max_issues_repo_head_hexsha": "737e08752e8904c7c24e3737f8f46bf5327ef792", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2021-06-21T10:15:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-06T14:42:46.000Z", "max_forks_repo_path": "bcos-scheduler/src/GraphKeyLocks.h", "max_forks_repo_name": "xueying4402/FISCO-BCOS", "max_forks_repo_head_hexsha": "737e08752e8904c7c24e3737f8f46bf5327ef792", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-06-10T02:44:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-04T02:51:38.000Z", "avg_line_length": 30.2177419355, "max_line_length": 98, "alphanum_fraction": 0.6733386709, "num_tokens": 959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658973632215985, "lm_q2_score": 0.02405355311305396, "lm_q1q2_score": 0.008817785693325518}}
{"text": "/* This file is necessary otherwise clang instantiate the bindgen tools\n * multiple time concurrently which produce non-deterministic results. */\n\n#include <cblas.h>\n#include <lapacke.h>\n", "meta": {"hexsha": "ba490e1a69bd0d0d9e804a7e076a8adafeddf8cc", "size": 187, "ext": "h", "lang": "C", "max_stars_repo_path": "lapack-jni/src/include.h", "max_stars_repo_name": "florv/scala-offheap", "max_stars_repo_head_hexsha": "2fec4031f085ccb4f32a020c9f817e3f919bfa65", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lapack-jni/src/include.h", "max_issues_repo_name": "florv/scala-offheap", "max_issues_repo_head_hexsha": "2fec4031f085ccb4f32a020c9f817e3f919bfa65", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lapack-jni/src/include.h", "max_forks_repo_name": "florv/scala-offheap", "max_forks_repo_head_hexsha": "2fec4031f085ccb4f32a020c9f817e3f919bfa65", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1666666667, "max_line_length": 73, "alphanum_fraction": 0.7807486631, "num_tokens": 39, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3140505578320071, "lm_q2_score": 0.028007522938509034, "lm_q1q2_score": 0.008795778202331496}}
{"text": "#include <assert.h>\n#include <stdlib.h>\n#include <ctype.h>\n#include <string.h>\n\n#include <asf.h>\n#include \"asf_tiff.h\"\n\n#include <gsl/gsl_math.h>\n#include <proj_api.h>\n\n#include \"asf_jpeg.h\"\n#include <png.h>\n#include \"envi.h\"\n\n#include \"dateUtil.h\"\n#include <time.h>\n#include \"matrix.h\"\n#include <asf_nan.h>\n#include <asf_endian.h>\n#include <asf_meta.h>\n#include <asf_export.h>\n#include <asf_raster.h>\n#include <float_image.h>\n#include <spheroids.h>\n#include <typlim.h>\n#include <hdf5.h>\n#include <netcdf.h>\n\n#define RES 16\n#define MAX_PTS 256\n\nvoid nc_meta_double(int group_id, char *name, char *desc, char *units,\n\t\t    double *value)\n{\n  int var_id;\n  char *str = (char *) MALLOC(sizeof(char)*1024);\n  nc_def_var(group_id, name, NC_DOUBLE, 0, 0, &var_id);\n  nc_put_att_text(group_id, var_id, \"long_name\", strlen(desc), desc);\n  if (units && strlen(units) > 0) {\n    strcpy(str, units);\n    nc_put_att_text(group_id, var_id, \"units\", strlen(str), str);\n  }\n  nc_put_var_double(group_id, var_id, value);\n}\n\nvoid nc_meta_float(int group_id, char *name, char *desc, char *units, \n\t\t   float *value)\n{\n  int var_id;\n  char *str = (char *) MALLOC(sizeof(char)*1024);\n  nc_def_var(group_id, name, NC_FLOAT, 0, 0, &var_id);\n  nc_put_att_text(group_id, var_id, \"long_name\", strlen(desc), desc);\n  if (units && strlen(units) > 0) {\n    strcpy(str, units);\n    nc_put_att_text(group_id, var_id, \"units\", strlen(str), str);\n  }\n  nc_put_var_float(group_id, var_id, value);\n}\n\nvoid nc_meta_int(int group_id, char *name, char *desc, char *units,\n\t\t int *value)\n{\n  int var_id;\n  char *str = (char *) MALLOC(sizeof(char)*1024);\n  nc_def_var(group_id, name, NC_INT, 0, 0, &var_id);\n  nc_put_att_text(group_id, var_id, \"long_name\", strlen(desc), desc);\n  if (units && strlen(units) > 0) {\n    strcpy(str, units);\n    nc_put_att_text(group_id, var_id, \"units\", strlen(str), str);\n  }\n  nc_put_var_int(group_id, var_id, value);\n}\n\nvoid nc_meta_str(int group_id, char *name, char *desc, char *units,\n\t\t char *value)\n{\n  int var_id;\n  const char *str_value = (char *) MALLOC(sizeof(char)*strlen(value));\n  strcpy(str_value, value);\n  char *str = (char *) MALLOC(sizeof(char)*1024);\n  nc_def_var(group_id, name, NC_STRING, 0, 0, &var_id);\n  nc_put_att_text(group_id, var_id, \"long_name\", strlen(desc), desc);\n  if (units && strlen(units) > 0) {\n    strcpy(str, units);\n    nc_put_att_text(group_id, var_id, \"units\", strlen(str), str);\n  }\n  nc_put_var_string(group_id, var_id, &str_value);\n}\n\nnetcdf_t *initialize_netcdf_file(const char *output_file, \n\t\t\t\t meta_parameters *meta)\n{\n  int ii, status, ncid, var_id;\n  int dim_xgrid_id, dim_ygrid_id, dim_lat_id, dim_lon_id, dim_time_id;\n  char *spatial_ref=NULL, *datum=NULL, *spheroid=NULL;\n\n  // Convenience variables\n  meta_general *mg = meta->general;\n  meta_sar *ms = meta->sar;\n  meta_state_vectors *mo = meta->state_vectors;\n  meta_projection *mp = meta->projection;\n\n  // Assign parameters\n  int projected = FALSE;\n  int band_count = mg->band_count;\n  int variable_count = band_count + 3;\n  if (mp && mp->type != SCANSAR_PROJECTION) {\n    projected = TRUE;\n    variable_count += 2;\n  }\n  size_t line_count = mg->line_count;\n  size_t sample_count = mg->sample_count;\n\n  // Assign data type\n  nc_type datatype;\n  if (mg->data_type == BYTE)\n    datatype = NC_CHAR;\n  else if (mg->data_type == REAL32)\n    datatype = NC_FLOAT;\n\n  // Initialize the netCDF pointer structure\n  netcdf_t *netcdf = (netcdf_t *) MALLOC(sizeof(netcdf_t));\n  netcdf->var_count = variable_count;\n  netcdf->var_id = (int *) MALLOC(sizeof(int)*variable_count);\n\n  // Create the actual file\n  status = nc_create(output_file, NC_CLOBBER|NC_NETCDF4, &ncid);\n  netcdf->ncid = ncid;\n  if (status != NC_NOERR)\n    asfPrintError(\"Could not open netCDF file (%s).\\n\", nc_strerror(status));\n\n  // Define dimensions\n  if (projected) {\n    nc_def_dim(ncid, \"xgrid\", sample_count, &dim_xgrid_id);\n    nc_def_dim(ncid, \"ygrid\", line_count, &dim_ygrid_id);\n  }\n  else {\n    status = nc_def_dim(ncid, \"longitude\", sample_count, &dim_lon_id);\n    if (status != NC_NOERR)\n      asfPrintError(\"Problem with longitude definition\\n\");\n    status = nc_def_dim(ncid, \"latitude\", line_count, &dim_lat_id);\n    if (status != NC_NOERR)\n      asfPrintError(\"Problem with latitude definition\\n\");\n  }\n  status = nc_def_dim(ncid, \"time\", 1, &dim_time_id);\n  if (status != NC_NOERR)\n    asfPrintError(\"Problem with time definition\\n\");\n\n  // Define projection\n  char *str = (char *) MALLOC(sizeof(char)*1024);\n  double lfValue;\n  if (projected) {\n    nc_def_var(ncid, \"projection\", NC_CHAR, 0, 0, &var_id);\n    if (mp->type == UNIVERSAL_TRANSVERSE_MERCATOR) {\n\n      strcpy(str, \"transverse_mercator\");\n      nc_put_att_text(ncid, var_id, \"grid_mapping_name\", strlen(str), str);\n      nc_put_att_double(ncid, var_id, \"scale_factor_at_central_meridian\", \n\t\t\tNC_DOUBLE, 1, &mp->param.utm.scale_factor);\n      nc_put_att_double(ncid, var_id, \"longitude_of_central_meridian\",\n\t\t\tNC_DOUBLE, 1, &mp->param.utm.lon0);\n      nc_put_att_double(ncid, var_id, \"latitude_of_projection_origin\",\n\t\t\tNC_DOUBLE, 1, &mp->param.utm.lat0);\n      nc_put_att_double(ncid, var_id, \"false_easting\", NC_DOUBLE, 1, \n\t\t\t&mp->param.utm.false_easting);\n      nc_put_att_double(ncid, var_id, \"false_northing\", NC_DOUBLE, 1, \n\t\t\t&mp->param.utm.false_northing);\n      strcpy(str, \"xgrid\");\n      nc_put_att_text(ncid, var_id, \"projection_x_coordinate\", strlen(str), \n\t\t      str);\n      strcpy(str, \"ygrid\");\n      nc_put_att_text(ncid, var_id, \"projection_y_coordinate\", strlen(str), \n\t\t      str);\n      strcpy(str, \"m\");\n      nc_put_att_text(ncid, var_id, \"units\", strlen(str), str); \n      nc_put_att_double(ncid, var_id, \"grid_boundary_top_projected_y\",\n\t\t\tNC_DOUBLE, 1, &mp->startY);\n      lfValue = mp->startY + mg->line_count * mp->perY;\n      nc_put_att_double(ncid, var_id, \"grid_boundary_bottom_projected_y\",\n\t\t\tNC_DOUBLE, 1, &lfValue);\n      lfValue = mp->startX + mg->sample_count * mp->perX;\n      nc_put_att_double(ncid, var_id, \"grid_boundary_right_projected_x\",\n\t\t\tNC_DOUBLE, 1, &lfValue);\n      nc_put_att_double(ncid, var_id, \"grid_boundary_left_projected_x\",\n\t\t\tNC_DOUBLE, 1, &mp->startX);\n      spatial_ref = (char *) MALLOC(sizeof(char)*1024);\n      datum = (char *) datum_toString(mp->datum);\n      spheroid = (char *) spheroid_toString(mp->spheroid);\n      double flat = mp->re_major/(mp->re_major - mp->re_minor);\n      sprintf(spatial_ref, \"PROJCS[\\\"%s_UTM_Zone_%d%c\\\",GEOGCS[\\\"GCS_%s\\\",DATUM[\\\"D_%s\\\",SPHEROID[\\\"%s\\\",%.1lf,%-16.11g]],PRIMEM[\\\"Greenwich\\\",0],UNIT[\\\"Degree\\\",0.017453292519943295]],PROJECTION[\\\"Transverse_Mercator\\\"],PARAMETER[\\\"False_Easting\\\",%.1lf],PARAMETER[\\\"False_Northing\\\",%.1lf],PARAMETER[\\\"Central_Meridian\\\",%.1lf],PARAMETER[\\\"Scale_Factor\\\",%.4lf],PARAMETER[\\\"Latitude_Of_Origin\\\",%.1lf],UNIT[\\\"Meter\\\",1]]\",\n\t      spheroid, mp->param.utm.zone, mp->hem, spheroid, datum, \n\t      spheroid, mp->re_major, flat, mp->param.utm.false_easting, \n\t      mp->param.utm.false_northing, mp->param.utm.lon0, \n\t      mp->param.utm.scale_factor, mp->param.utm.lat0);\n      nc_put_att_text(ncid, var_id, \"spatial_ref\", strlen(spatial_ref), \n\t\t      spatial_ref);\n      sprintf(str, \"+proj=utm +zone=%d\", mp->param.utm.zone);\n      if (meta->general->center_latitude < 0)\n\tstrcat(str, \" +south\");\n      nc_put_att_text(ncid, var_id, \"proj4text\", strlen(str), str);\n      nc_put_att_int(ncid, var_id, \"zone\", NC_INT, 1, &mp->param.utm.zone);\n      nc_put_att_double(ncid, var_id, \"semimajor_radius\", NC_DOUBLE, 1, \n\t\t\t&mp->re_major);\n      nc_put_att_double(ncid, var_id, \"semiminor_radius\", NC_DOUBLE, 1, \n\t\t\t&mp->re_minor);\n      sprintf(str, \"%.6lf %.6lf 0 %.6lf 0 %.6lf\", mp->startX, mp->perX, \n\t      mp->startY, mp->perY); \n      nc_put_att_text(ncid, var_id, \"GeoTransform\", strlen(str), str);\n    }\n    else if (mp->type == POLAR_STEREOGRAPHIC) {\n\n      strcpy(str, \"polar_stereographic\");\n      nc_put_att_text(ncid, var_id, \"grid_mapping_name\", strlen(str), str);\n      lfValue = 90.0;\n      nc_put_att_double(ncid, var_id, \"straight_vertical_longitude_from_pole\", \n\t\t\tNC_DOUBLE, 1, &mp->param.ps.slon);\n      nc_put_att_double(ncid, var_id, \"longitude_of_central_meridian\",\n\t\t\tNC_DOUBLE, 1, &lfValue);\n      nc_put_att_double(ncid, var_id, \"standard_parallel\",\n\t\t\tNC_DOUBLE, 1, &mp->param.ps.slat);\n      nc_put_att_double(ncid, var_id, \"false_easting\", NC_DOUBLE, 1, \n\t\t\t&mp->param.ps.false_easting);\n      nc_put_att_double(ncid, var_id, \"false_northing\", NC_DOUBLE, 1, \n\t\t\t&mp->param.ps.false_northing);\n      strcpy(str, \"xgrid\");\n      nc_put_att_text(ncid, var_id, \"projection_x_coordinate\", strlen(str), \n\t\t      str);\n      strcpy(str, \"ygrid\");\n      nc_put_att_text(ncid, var_id, \"projection_y_coordinate\", strlen(str), \n\t\t      str);\n      strcpy(str, \"m\");\n      nc_put_att_text(ncid, var_id, \"units\", strlen(str), str); \n      nc_put_att_double(ncid, var_id, \"grid_boundary_top_projected_y\",\n\t\t\tNC_DOUBLE, 1, &mp->startY);\n      lfValue = mp->startY + mg->line_count * mp->perY;\n      nc_put_att_double(ncid, var_id, \"grid_boundary_bottom_projected_y\",\n\t\t\tNC_DOUBLE, 1, &lfValue);\n      lfValue = mp->startX + mg->sample_count * mp->perX;\n      nc_put_att_double(ncid, var_id, \"grid_boundary_right_projected_x\",\n\t\t\tNC_DOUBLE, 1, &lfValue);\n      nc_put_att_double(ncid, var_id, \"grid_boundary_left_projected_x\",\n\t\t\tNC_DOUBLE, 1, &mp->startX);\n      spatial_ref = (char *) MALLOC(sizeof(char)*1024);\n      datum = (char *) datum_toString(mp->datum);\n      spheroid = (char *) spheroid_toString(mp->spheroid);\n      double flat = mp->re_major/(mp->re_major - mp->re_minor);\n      sprintf(spatial_ref, \"PROJCS[\\\"Stereographic_North_Pole\\\",GEOGCS[\\\"unnamed ellipse\\\",DATUM[\\\"D_unknown\\\",SPHEROID[\\\"Unknown\\\",%.3lf,%-16.11g]],PRIMEM[\\\"Greenwich\\\",0],UNIT[\\\"Degree\\\",0.0002247191011236]],PROJECTION[\\\"Stereographic_North_Pole\\\"],PARAMETER[\\\"standard_parallel_1\\\",%.4lf],PARAMETER[\\\"central_meridian\\\",%.4lf],PARAMETER[\\\"scale_factor\\\",1],PARAMETER[\\\"false_easting\\\",%.3lf],PARAMETER[\\\"false_northing\\\",%.3lf],UNIT[\\\"Meter\\\",1,AUTHORITY[\\\"EPSG\\\",\\\"9122\\\"]],AUTHORITY[\\\"EPSG\\\",\\\"3411\\\"]]\",\n\t      mp->re_major, flat, mp->param.ps.slat, mp->param.ps.slon,\n\t      mp->param.ps.false_easting, mp->param.ps.false_northing);\n      nc_put_att_text(ncid, var_id, \"spatial_ref\", strlen(spatial_ref), \n\t\t      spatial_ref);\n      if (mp->param.ps.is_north_pole)\n\tsprintf(str, \"+proj=stere +lat_0=90.0000 +lat_ts=%.4lf \"\n\t\t\"+lon_0=%.4lf +k=1 +x_0=%.3lf +y_0=%.3lf +a=%.3lf +b=%.3lf \"\n\t\t\"+units=m +no_defs\", mp->param.ps.slat, mp->param.ps.slon,\n\t\tmp->param.ps.false_easting, mp->param.ps.false_northing,\n\t\tmp->re_major, mp->re_minor);\n      else\n\tsprintf(str, \"+proj=stere +lat_0=-90.0000 +lat_ts=%.4lf \"\n\t\t\"+lon_0=%.4lf +k=1 +x_0=%.3lf +y_0=%.3lf +a=%.3lf +b=%.3lf \"\n\t\t\"+units=m +no_defs\", mp->param.ps.slat, mp->param.ps.slon,\n\t\tmp->param.ps.false_easting, mp->param.ps.false_northing,\n\t\tmp->re_major, mp->re_minor);\n      nc_put_att_text(ncid, var_id, \"proj4text\", strlen(str), str);\n      nc_put_att_double(ncid, var_id, \"latitude_of_true_scale\", NC_DOUBLE, 1,\n\t\t\t&mp->param.ps.slat);\n      nc_put_att_double(ncid, var_id, \"longitude_of_projection_origin\", \n\t\t\tNC_DOUBLE, 1, &mp->param.ps.slon);\n      nc_put_att_double(ncid, var_id, \"semimajor_radius\", NC_DOUBLE, 1, \n\t\t\t&mp->re_major);\n      nc_put_att_double(ncid, var_id, \"semiminor_radius\", NC_DOUBLE, 1, \n\t\t\t&mp->re_minor);\n      sprintf(str, \"%.6lf %.6lf 0 %.6lf 0 %.6lf\", mp->startX, mp->perX, \n\t      mp->startY, mp->perY); \n      nc_put_att_text(ncid, var_id, \"GeoTransform\", strlen(str), str);\n    }\n    else if (mp->type == ALBERS_EQUAL_AREA) {\n\n      strcpy(str, \"albers_conical_equal_area\");\n      nc_put_att_text(ncid, var_id, \"grid_mapping_name\", strlen(str), str);\n      lfValue = 90.0;\n      nc_put_att_double(ncid, var_id, \"standard_parallel_1\", \n\t\t\tNC_DOUBLE, 1, &mp->param.albers.std_parallel1);\n      nc_put_att_double(ncid, var_id, \"standard_parallel_2\",\n\t\t\tNC_DOUBLE, 1, &mp->param.albers.std_parallel2);\n      nc_put_att_double(ncid, var_id, \"longitude_of_central_meridian\",\n\t\t\tNC_DOUBLE, 1, &mp->param.albers.center_meridian);\n      nc_put_att_double(ncid, var_id, \"latitude_of_projection_origin\",\n\t\t\tNC_DOUBLE, 1, &mp->param.albers.orig_latitude);\n      nc_put_att_double(ncid, var_id, \"false_easting\", NC_DOUBLE, 1, \n\t\t\t&mp->param.albers.false_easting);\n      nc_put_att_double(ncid, var_id, \"false_northing\", NC_DOUBLE, 1, \n\t\t\t&mp->param.albers.false_northing);\n      strcpy(str, \"xgrid\");\n      nc_put_att_text(ncid, var_id, \"projection_x_coordinate\", strlen(str), \n\t\t      str);\n      strcpy(str, \"ygrid\");\n      nc_put_att_text(ncid, var_id, \"projection_y_coordinate\", strlen(str), \n\t\t      str);\n      strcpy(str, \"m\");\n      nc_put_att_text(ncid, var_id, \"units\", strlen(str), str); \n      nc_put_att_double(ncid, var_id, \"grid_boundary_top_projected_y\",\n\t\t\tNC_DOUBLE, 1, &mp->startY);\n      lfValue = mp->startY + mg->line_count * mp->perY;\n      nc_put_att_double(ncid, var_id, \"grid_boundary_bottom_projected_y\",\n\t\t\tNC_DOUBLE, 1, &lfValue);\n      lfValue = mp->startX + mg->sample_count * mp->perX;\n      nc_put_att_double(ncid, var_id, \"grid_boundary_right_projected_x\",\n\t\t\tNC_DOUBLE, 1, &lfValue);\n      nc_put_att_double(ncid, var_id, \"grid_boundary_left_projected_x\",\n\t\t\tNC_DOUBLE, 1, &mp->startX);\n      spatial_ref = (char *) MALLOC(sizeof(char)*1024);\n      datum = (char *) datum_toString(mp->datum);\n      spheroid = (char *) spheroid_toString(mp->spheroid);\n      double flat = mp->re_major/(mp->re_major - mp->re_minor);\n      sprintf(spatial_ref, \"PROJCS[\\\"Albers_Equal_Area_Conic\\\",GEOGCS[\\\"GCS_%s\\\",DATUM[\\\"D_%s\\\",SPHEROID[\\\"%s\\\",%.3lf,%-16.11g]],PRIMEM[\\\"Greenwich\\\",0],UNIT[\\\"Degree\\\",0.0174532925199432955]],PROJECTION[\\\"Albers\\\"],PARAMETER[\\\"False_Easting\\\",%.3lf],PARAMETER[\\\"False_Northing\\\",%.3lf],PARAMETER[\\\"Central_Meridian\\\",%.4lf],PARAMETER[\\\"Standard_Parallel_1\\\",%.4lf],PARAMETER[\\\"Standard_Parallel_2\\\",%.4lf],PARAMETER[\\\"Latitude_Of_Origin\\\",%.4lf],UNIT[\\\"Meter\\\",1]]\",\n\t      datum, datum, spheroid, mp->re_major, flat, \n\t      mp->param.albers.false_easting, mp->param.albers.false_northing,\n\t      mp->param.albers.center_meridian, mp->param.albers.std_parallel1,\n\t      mp->param.albers.std_parallel2, mp->param.albers.orig_latitude);\n      nc_put_att_text(ncid, var_id, \"spatial_ref\", strlen(spatial_ref), \n\t\t      spatial_ref);\n      sprintf(str, \"+proj=aea +lat_1=%.4lf +lat_2=%.4lf +lat_0=%.4lf \"\n\t      \"+lon_0=%.4lf +x_0=%.3lf +y_0=%.3lf\", \n\t      mp->param.albers.std_parallel1, mp->param.albers.std_parallel2, \n\t      mp->param.albers.orig_latitude, mp->param.albers.center_meridian,\n\t      mp->param.albers.false_easting, mp->param.albers.false_northing);\n      nc_put_att_text(ncid, var_id, \"proj4text\", strlen(str), str);\n      nc_put_att_double(ncid, var_id, \"latitude_of_true_scale\", NC_DOUBLE, 1,\n\t\t\t&mp->param.ps.slat);\n      nc_put_att_double(ncid, var_id, \"longitude_of_projection_origin\", \n\t\t\tNC_DOUBLE, 1, &mp->param.ps.slon);\n      nc_put_att_double(ncid, var_id, \"semimajor_radius\", NC_DOUBLE, 1, \n\t\t\t&mp->re_major);\n      nc_put_att_double(ncid, var_id, \"semiminor_radius\", NC_DOUBLE, 1, \n\t\t\t&mp->re_minor);\n      sprintf(str, \"%.6lf %.6lf 0 %.6lf 0 %.6lf\", mp->startX, mp->perX, \n\t      mp->startY, mp->perY); \n      nc_put_att_text(ncid, var_id, \"GeoTransform\", strlen(str), str);\n    }\n    else if (mp->type == LAMBERT_CONFORMAL_CONIC) {\n\n      strcpy(str, \"lambert_conformal_conic\");\n      nc_put_att_text(ncid, var_id, \"grid_mapping_name\", strlen(str), str);\n      lfValue = 90.0;\n      nc_put_att_double(ncid, var_id, \"standard_parallel_1\", \n\t\t\tNC_DOUBLE, 1, &mp->param.lamcc.plat1);\n      nc_put_att_double(ncid, var_id, \"standard_parallel_2\",\n\t\t\tNC_DOUBLE, 1, &mp->param.lamcc.plat2);\n      nc_put_att_double(ncid, var_id, \"longitude_of_central_meridian\",\n\t\t\tNC_DOUBLE, 1, &mp->param.lamcc.lon0);\n      nc_put_att_double(ncid, var_id, \"latitude_of_projection_origin\",\n\t\t\tNC_DOUBLE, 1, &mp->param.lamcc.lat0);\n      nc_put_att_double(ncid, var_id, \"false_easting\", NC_DOUBLE, 1, \n\t\t\t&mp->param.lamcc.false_easting);\n      nc_put_att_double(ncid, var_id, \"false_northing\", NC_DOUBLE, 1, \n\t\t\t&mp->param.lamcc.false_northing);\n      strcpy(str, \"xgrid\");\n      nc_put_att_text(ncid, var_id, \"projection_x_coordinate\", strlen(str), \n\t\t      str);\n      strcpy(str, \"ygrid\");\n      nc_put_att_text(ncid, var_id, \"projection_y_coordinate\", strlen(str), \n\t\t      str);\n      strcpy(str, \"m\");\n      nc_put_att_text(ncid, var_id, \"units\", strlen(str), str); \n      nc_put_att_double(ncid, var_id, \"grid_boundary_top_projected_y\",\n\t\t\tNC_DOUBLE, 1, &mp->startY);\n      lfValue = mp->startY + mg->line_count * mp->perY;\n      nc_put_att_double(ncid, var_id, \"grid_boundary_bottom_projected_y\",\n\t\t\tNC_DOUBLE, 1, &lfValue);\n      lfValue = mp->startX + mg->sample_count * mp->perX;\n      nc_put_att_double(ncid, var_id, \"grid_boundary_right_projected_x\",\n\t\t\tNC_DOUBLE, 1, &lfValue);\n      nc_put_att_double(ncid, var_id, \"grid_boundary_left_projected_x\",\n\t\t\tNC_DOUBLE, 1, &mp->startX);\n      spatial_ref = (char *) MALLOC(sizeof(char)*1024);\n      datum = (char *) datum_toString(mp->datum);\n      spheroid = (char *) spheroid_toString(mp->spheroid);\n      double flat = mp->re_major/(mp->re_major - mp->re_minor);\n      sprintf(spatial_ref, \"PROJCS[\\\"Lambert_Conformal_Conic\\\",GEOGCS[\\\"GCS_%s\\\",DATUM[\\\"D_%s\\\",SPHEROID[\\\"%s\\\",%.3lf,%-16.11g]],PRIMEM[\\\"Greenwich\\\",0],UNIT[\\\"Degree\\\",0.0174532925199432955]],PROJECTION[\\\"Lambert_Conformal_Conic\\\"],PARAMETER[\\\"False_Easting\\\",%.3lf],PARAMETER[\\\"False_Northing\\\",%.3lf],PARAMETER[\\\"Central_Meridian\\\",%.4lf],PARAMETER[\\\"Standard_Parallel_1\\\",%.4lf],PARAMETER[\\\"Standard_Parallel_2\\\",%.4lf],PARAMETER[\\\"Latitude_Of_Origin\\\",%.4lf],UNIT[\\\"Meter\\\",1]]\",\n\t      datum, datum, spheroid, mp->re_major, flat, \n\t      mp->param.lamcc.false_easting, mp->param.lamcc.false_northing,\n\t      mp->param.lamcc.lon0, mp->param.lamcc.plat1,\n\t      mp->param.lamcc.plat2, mp->param.lamcc.lat0);\n      nc_put_att_text(ncid, var_id, \"spatial_ref\", strlen(spatial_ref), \n\t\t      spatial_ref);\n      sprintf(str, \"+proj=lcc +lat_1=%.4lf +lat_2=%.4lf +lat_0=%.4lf \"\n\t      \"+lon_0=%.4lf +x_0=%.3lf +y_0=%.3lf\", \n\t      mp->param.lamcc.plat1, mp->param.lamcc.plat2,\n\t      mp->param.lamcc.lat0, mp->param.lamcc.lon0,\n\t      mp->param.lamcc.false_easting, mp->param.lamcc.false_northing);\n      nc_put_att_text(ncid, var_id, \"proj4text\", strlen(str), str);\n      nc_put_att_double(ncid, var_id, \"semimajor_radius\", NC_DOUBLE, 1, \n\t\t\t&mp->re_major);\n      nc_put_att_double(ncid, var_id, \"semiminor_radius\", NC_DOUBLE, 1, \n\t\t\t&mp->re_minor);\n      sprintf(str, \"%.6lf %.6lf 0 %.6lf 0 %.6lf\", mp->startX, mp->perX, \n\t      mp->startY, mp->perY); \n      nc_put_att_text(ncid, var_id, \"GeoTransform\", strlen(str), str);\n    }\n    else if (mp->type == LAMBERT_AZIMUTHAL_EQUAL_AREA) {\n\n      strcpy(str, \"lambert_azimuthal_equal_area\");\n      nc_put_att_text(ncid, var_id, \"grid_mapping_name\", strlen(str), str);\n      nc_put_att_double(ncid, var_id, \"longitude_of_projection_origin\",\n\t\t\tNC_DOUBLE, 1, &mp->param.lamaz.center_lon);\n      nc_put_att_double(ncid, var_id, \"latitude_of_projection_origin\",\n\t\t\tNC_DOUBLE, 1, &mp->param.lamaz.center_lat);\n      nc_put_att_double(ncid, var_id, \"false_easting\", NC_DOUBLE, 1, \n\t\t\t&mp->param.lamaz.false_easting);\n      nc_put_att_double(ncid, var_id, \"false_northing\", NC_DOUBLE, 1, \n\t\t\t&mp->param.lamaz.false_northing);\n      strcpy(str, \"xgrid\");\n      nc_put_att_text(ncid, var_id, \"projection_x_coordinate\", strlen(str), \n\t\t      str);\n      strcpy(str, \"ygrid\");\n      nc_put_att_text(ncid, var_id, \"projection_y_coordinate\", strlen(str), \n\t\t      str);\n      strcpy(str, \"m\");\n      nc_put_att_text(ncid, var_id, \"units\", strlen(str), str); \n      nc_put_att_double(ncid, var_id, \"grid_boundary_top_projected_y\",\n\t\t\tNC_DOUBLE, 1, &mp->startY);\n      lfValue = mp->startY + mg->line_count * mp->perY;\n      nc_put_att_double(ncid, var_id, \"grid_boundary_bottom_projected_y\",\n\t\t\tNC_DOUBLE, 1, &lfValue);\n      lfValue = mp->startX + mg->sample_count * mp->perX;\n      nc_put_att_double(ncid, var_id, \"grid_boundary_right_projected_x\",\n\t\t\tNC_DOUBLE, 1, &lfValue);\n      nc_put_att_double(ncid, var_id, \"grid_boundary_left_projected_x\",\n\t\t\tNC_DOUBLE, 1, &mp->startX);\n      spatial_ref = (char *) MALLOC(sizeof(char)*1024);\n      datum = (char *) datum_toString(mp->datum);\n      spheroid = (char *) spheroid_toString(mp->spheroid);\n      double flat = mp->re_major/(mp->re_major - mp->re_minor);\n      sprintf(spatial_ref, \"PROJCS[\\\"Lambert_Azimuthal_Equal_Area\\\",GEOGCS[\\\"GCS_%s\\\",DATUM[\\\"D_%s\\\",SPHEROID[\\\"%s\\\",%.3lf,%-16.11g]],PRIMEM[\\\"Greenwich\\\",0],UNIT[\\\"Degree\\\",0.0174532925199432955]],PROJECTION[\\\"Lambert_Conformal_Conic\\\"],PARAMETER[\\\"False_Easting\\\",%.3lf],PARAMETER[\\\"False_Northing\\\",%.3lf],PARAMETER[\\\"Central_Meridian\\\",%.4lf],PARAMETER[\\\"Latitude_Of_Origin\\\",%.4lf],UNIT[\\\"Meter\\\",1]]\",\n\t      datum, datum, spheroid, mp->re_major, flat, \n\t      mp->param.lamaz.false_easting, mp->param.lamaz.false_northing,\n\t      mp->param.lamaz.center_lon, mp->param.lamaz.center_lat);\n      nc_put_att_text(ncid, var_id, \"spatial_ref\", strlen(spatial_ref), \n\t\t      spatial_ref);\n      sprintf(str, \"+proj=laea +lat_0=%.4lf +lon_0=%.4lf +x_0=%.3lf \"\n\t      \"+y_0=%.3lf\", \n\t      mp->param.lamaz.center_lat, mp->param.lamaz.center_lon,\n\t      mp->param.lamaz.false_easting, mp->param.lamaz.false_northing);\n      nc_put_att_text(ncid, var_id, \"proj4text\", strlen(str), str);\n      nc_put_att_double(ncid, var_id, \"semimajor_radius\", NC_DOUBLE, 1, \n\t\t\t&mp->re_major);\n      nc_put_att_double(ncid, var_id, \"semiminor_radius\", NC_DOUBLE, 1, \n\t\t\t&mp->re_minor);\n      sprintf(str, \"%.6lf %.6lf 0 %.6lf 0 %.6lf\", mp->startX, mp->perX, \n\t      mp->startY, mp->perY); \n      nc_put_att_text(ncid, var_id, \"GeoTransform\", strlen(str), str);\n    }\n  }\n  \n  // Define variables and data attributes\n  char **band_name = extract_band_names(meta->general->bands, band_count);\n  int dims_bands[3];\n  dims_bands[0] = dim_time_id;\n  if (projected) {\n    dims_bands[1] = dim_ygrid_id;\n    dims_bands[2] = dim_xgrid_id;\n  }\n  else {\n    dims_bands[1] = dim_lon_id;\n    dims_bands[2] = dim_lat_id;\n  }\n\n  for (ii=0; ii<band_count; ii++) {\n    \n    sprintf(str, \"%s_AMPLITUDE_IMAGE\", band_name[ii]);\n    nc_def_var(ncid, str, datatype, 3, dims_bands, &var_id);\n    netcdf->var_id[ii] = var_id;\n    nc_def_var_deflate(ncid, var_id, 0, 1, 6);    \n    lfValue = -999.0;\n    nc_put_att_double(ncid, var_id, \"FillValue\", NC_DOUBLE, 1, &lfValue);\n    sprintf(str, \"%s\", mg->sensor);\n    if (mg->image_data_type < 9)\n      strcat(str, \" radar backscatter\");\n    if (mg->radiometry >= r_SIGMA_DB && mg->radiometry <= r_GAMMA_DB)\n      strcat(str, \" in dB\");\n    nc_put_att_text(ncid, var_id, \"long_name\", strlen(str), str);\n    strcpy(str, \"area: backcatter value\");\n    nc_put_att_text(ncid, var_id, \"cell_methods\", strlen(str), str);\n    strcpy(str, \"1\");\n    nc_put_att_text(ncid, var_id, \"units\", strlen(str), str);\n    strcpy(str, \"unitless normalized radar cross-section\");\n    if (mg->radiometry >= r_SIGMA && mg->radiometry <= r_GAMMA)\n      strcat(str, \" stored as powerscale\");\n    else if (mg->radiometry >= r_SIGMA_DB && mg->radiometry <= r_GAMMA_DB)\n      strcat(str, \" stored as dB=10*log10(*)\");\n    nc_put_att_text(ncid, var_id, \"units_description\", strlen(str), str);\n    strcpy(str, \"longitude latitude\");\n    nc_put_att_text(ncid, var_id, \"coordinates\", strlen(str), str);\n    if (projected) {\n      strcpy(str, \"projection\");\n      nc_put_att_text(ncid, var_id, \"grid_mapping\", strlen(str), str);\n    } \n  }\n\n  // Define other attributes\n  ymd_date ymd;\n  hms_time hms;\n  parse_date(mg->acquisition_date, &ymd, &hms);\n\n  // Time\n  ii = band_count;\n  int dims_time[1] = { dim_time_id };\n  nc_def_var(ncid, \"time\", NC_FLOAT, 1, dims_time, &var_id);\n  netcdf->var_id[ii] = var_id;\n  strcpy(str, \"seconds since 1900-01-01T00:00:00Z\");\n  nc_put_att_text(ncid, var_id, \"units\", strlen(str), str);\n  strcpy(str, \"scene center time\");\n  nc_put_att_text(ncid, var_id, \"references\", strlen(str), str);\n  strcpy(str, \"time\");\n  nc_put_att_text(ncid, var_id, \"standard_name\", strlen(str), str);\n  strcpy(str, \"T\");\n  nc_put_att_text(ncid, var_id, \"axis\", strlen(str), str);\n  strcpy(str, \"serial date\");\n  nc_put_att_text(ncid, var_id, \"long_name\", strlen(str), str);\n\n  // Longitude\n  ii++;\n  if (projected) {\n    int dims_lon[2] = { dim_ygrid_id, dim_xgrid_id };\n    nc_def_var(ncid, \"longitude\", NC_FLOAT, 2, dims_lon, &var_id);\n  }\n  else {\n    int dims_lon[2] = { dim_lon_id, dim_lat_id };\n    nc_def_var(ncid, \"longitude\", NC_FLOAT, 2, dims_lon, &var_id);\n  }\n  netcdf->var_id[ii] = var_id;\n  nc_def_var_deflate(ncid, var_id, 0, 1, 6);    \n  strcpy(str, \"longitude\");\n  nc_put_att_text(ncid, var_id, \"standard_name\", strlen(str), str);\n  strcpy(str, \"longitude\");\n  nc_put_att_text(ncid, var_id, \"long_name\", strlen(str), str);\n  strcpy(str, \"degrees_east\");\n  nc_put_att_text(ncid, var_id, \"units\", strlen(str), str);\n  double *valid_range = (double *) MALLOC(sizeof(double)*2);\n  valid_range[0] = -180.0;\n  valid_range[1] = 180.0;\n  nc_put_att_double(ncid, var_id, \"valid_range\", NC_DOUBLE, 2, valid_range);\n  FREE(valid_range);\n  lfValue = -999.0;\n  nc_put_att_double(ncid, var_id, \"FillValue\", NC_DOUBLE, 1, &lfValue);\n\n  // Latitude\n  ii++;\n  if (projected) {\n    int dims_lat[2] = { dim_ygrid_id, dim_xgrid_id };\n    nc_def_var(ncid, \"latitude\", NC_FLOAT, 2, dims_lat, &var_id);\n  }\n  else {\n    int dims_lat[2] = { dim_lat_id, dim_lon_id };\n    nc_def_var(ncid, \"latitude\", NC_FLOAT, 2, dims_lat, &var_id);\n  }\n  netcdf->var_id[ii] = var_id;\n  nc_def_var_deflate(ncid, var_id, 0, 1, 6);    \n  strcpy(str, \"latitude\");\n  nc_put_att_text(ncid, var_id, \"standard_name\", strlen(str), str);\n  strcpy(str, \"latitude\");\n  nc_put_att_text(ncid, var_id, \"long_name\", strlen(str), str);\n  strcpy(str, \"degrees_north\");\n  nc_put_att_text(ncid, var_id, \"units\", strlen(str), str);\n  valid_range = (double *) MALLOC(sizeof(double)*2);\n  valid_range[0] = -90.0;\n  valid_range[1] = 90.0;\n  nc_put_att_double(ncid, var_id, \"valid_range\", NC_DOUBLE, 2, valid_range);\n  FREE(valid_range);\n  lfValue = -999.0;\n  nc_put_att_double(ncid, var_id, \"FillValue\", NC_DOUBLE, 1, &lfValue);\n\n  if (projected) {\n\n    // ygrid\n    ii++;\n    int dims_ygrid[1] = { dim_ygrid_id };\n    nc_def_var(ncid, \"ygrid\", NC_FLOAT, 1, dims_ygrid, &var_id);\n    netcdf->var_id[ii] = var_id;\n    nc_def_var_deflate(ncid, var_id, 0, 1, 6);    \n    strcpy(str, \"projection_y_coordinates\");\n    nc_put_att_text(ncid, var_id, \"standard_name\", strlen(str), str);\n    strcpy(str, \"projection_grid_y_centers\");\n    nc_put_att_text(ncid, var_id, \"long_name\", strlen(str), str);\n    strcpy(str, \"meters\");\n    nc_put_att_text(ncid, var_id, \"units\", strlen(str), str);\n    strcpy(str, \"Y\");\n    nc_put_att_text(ncid, var_id, \"axis\", strlen(str), str);\n\n    // xgrid\n    ii++;\n    int dims_xgrid[1] = { dim_xgrid_id };\n    nc_def_var(ncid, \"xgrid\", NC_FLOAT, 1, dims_xgrid, &var_id);\n    netcdf->var_id[ii] = var_id;\n    nc_def_var_deflate(ncid, var_id, 0, 1, 6);    \n    strcpy(str, \"projection_x_coordinates\");\n    nc_put_att_text(ncid, var_id, \"standard_name\", strlen(str), str);\n    strcpy(str, \"projection_grid_x_centers\");\n    nc_put_att_text(ncid, var_id, \"long_name\", strlen(str), str);\n    strcpy(str, \"meters\");\n    nc_put_att_text(ncid, var_id, \"units\", strlen(str), str);\n    strcpy(str, \"X\");\n    nc_put_att_text(ncid, var_id, \"axis\", strlen(str), str);\n  }\n  \n  // Define global attributes\n  strcpy(str, \"CF-1.4\");\n  nc_put_att_text(ncid, NC_GLOBAL, \"Conventions\", strlen(str), str);\n  strcpy(str, \"Alaska Satellite Facility\");\n  nc_put_att_text(ncid, NC_GLOBAL, \"institution\", strlen(str), str);\n  sprintf(str, \"%s %s %s image\", mg->sensor, mg->sensor_name, mg->mode);\n  nc_put_att_text(ncid, NC_GLOBAL, \"title\", strlen(str), str);\n  if (mg->image_data_type == AMPLITUDE_IMAGE)\n    strcpy(str, \"SAR backcatter image\");\n  nc_put_att_text(ncid, NC_GLOBAL, \"source\", strlen(str), str);\n  sprintf(str, \"%s\", mg->basename);\n  nc_put_att_text(ncid, NC_GLOBAL, \"original_file\", strlen(str), str);\n  if (strcmp_case(mg->sensor, \"RSAT-1\") == 0)\n    sprintf(str, \"Copyright Canadian Space Agency, %d\", ymd.year);\n  else if (strncmp_case(mg->sensor, \"ERS\", 3) == 0)\n    sprintf(str, \"Copyright European Space Agency, %d\", ymd.year);\n  else if (strcmp_case(mg->sensor, \"JERS-1\") == 0 ||\n\t   strcmp_case(mg->sensor, \"ALOS\") == 0)\n    sprintf(str, \"Copyright Japan Aerospace Exploration Agency , %d\", \n\t    ymd.year);\n  nc_put_att_text(ncid, NC_GLOBAL, \"comment\", strlen(str), str);\n  strcpy(str, \"Documentation available at: www.asf.alaska.edu\");\n  nc_put_att_text(ncid, NC_GLOBAL, \"references\", strlen(str), str);\n  time_t t;\n  struct tm *timeinfo;\n  time(&t);\n  timeinfo = gmtime(&t);\n  sprintf(str, \"%s\", asctime(timeinfo));\n  chomp(str);\n  strcat(str, \", UTC: netCDF File created.\");\n  nc_put_att_text(ncid, NC_GLOBAL, \"history\", strlen(str), str);\n\n  // Metadata  \n  int meta_id;\n  nc_def_grp(ncid, \"metadata\", &meta_id);\n\n  // Metadata - general block\n  nc_meta_str(meta_id, \"general_name\", \"file name\", NULL, mg->basename);\n  nc_meta_str(meta_id, \"general_sensor\", \"imaging satellite\", NULL, mg->sensor);\n  nc_meta_str(meta_id, \"general_sensor_name\", \"imaging sensor\", NULL, \n\t      mg->sensor_name);\n  nc_meta_str(meta_id, \"general_mode\", \"imaging mode\", NULL, mg->mode);\n  nc_meta_str(meta_id, \"general_processor\", \"name and version of processor\", \n\t      NULL, mg->processor);\n  nc_meta_str(meta_id, \"general_data_type\", \"type of samples (e.g. REAL64)\", \n\t      NULL, data_type2str(mg->data_type));\n  nc_meta_str(meta_id, \"general_image_data_type\", \n\t      \"image data type (e.g. AMPLITUDE_IMAGE)\", NULL, \n\t      image_data_type2str(mg->image_data_type));\n  nc_meta_str(meta_id, \"general_radiometry\", \"radiometry (e.g. SIGMA)\", NULL, \n\t      radiometry2str(mg->radiometry));\n  nc_meta_str(meta_id, \"general_acquisition_date\", \n\t      \"acquisition date of the image\", NULL, mg->acquisition_date);\n  nc_meta_int(meta_id, \"general_orbit\", \"orbit number of image\", NULL, \n\t      &mg->orbit);\n  if (mg->orbit_direction == 'A')\n    strcpy(str, \"Ascending\");\n  else\n    strcpy(str, \"Descending\");\n  nc_meta_str(meta_id, \"general_orbit_direction\", \"orbit direction\", NULL, str);\n  nc_meta_int(meta_id, \"general_frame\", \"frame number of image\", NULL, \n\t      &mg->frame);\n  nc_meta_int(meta_id, \"general_band_count\", \"number of bands in image\", NULL, \n\t      &mg->band_count);\n  nc_meta_str(meta_id, \"general_bands\", \"bands of the sensor\", NULL, \n\t      &mg->bands);\n  nc_meta_int(meta_id, \"general_line_count\", \"number of lines in image\", NULL, \n\t      &mg->line_count);\n  nc_meta_int(meta_id, \"general_sample_count\", \"number of samples in image\", \n\t      NULL, &mg->sample_count);\n  nc_meta_int(meta_id, \"general_start_line\", \n\t      \"first line relative to original image\", NULL, &mg->start_line);\n  nc_meta_int(meta_id, \"general_start_sample\", \n\t      \"first sample relative to original image\", NULL, \n\t      &mg->start_sample);\n  nc_meta_double(meta_id, \"general_x_pixel_size\", \"range pixel size\", \"m\", \n\t\t &mg->x_pixel_size);\n  nc_meta_double(meta_id, \"general_y_pixel_size\", \"azimuth pixel size\", \"m\", \n\t\t &mg->y_pixel_size);\n  nc_meta_double(meta_id, \"general_center_latitude\", \n\t\t \"approximate image center latitude\", \"degrees_north\", \n\t\t &mg->center_latitude);\n  nc_meta_double(meta_id, \"general_center_longitude\",\n\t\t \"approximate image center longitude\", \"degrees_east\", \n\t\t &mg->center_longitude);\n  nc_meta_double(meta_id,  \"general_re_major\", \"major (equator) axis of earth\",\n\t\t \"m\", &mg->re_major);\n  nc_meta_double(meta_id, \"general_re_minor\", \"minor (polar) axis of earth\", \n\t\t \"m\", &mg->re_minor);\n  nc_meta_double(meta_id, \"general_bit_error_rate\", \n\t\t \"fraction of bits which are in error\", NULL, \n\t\t &mg->bit_error_rate);\n  nc_meta_int(meta_id, \"general_missing_lines\", \n\t      \"number of missing lines in data take\", NULL, &mg->missing_lines);\n  nc_meta_float(meta_id, \"general_no_data\", \n\t\t\"value indicating no data for a pixel\",\tNULL, &mg->no_data);\n\n  if (ms) {\n    // Metadata - SAR block\n    if (ms->image_type == 'S')\n      sprintf(str, \"slant range\");\n    else if (ms->image_type == 'G')\n      sprintf(str, \"ground range\");\n    else if (ms->image_type == 'P')\n      sprintf(str, \"projected\");\n    else if (ms->image_type == 'R')\n      sprintf(str, \"georeferenced\");    \n    nc_meta_str(meta_id, \"sar_image_type\", \"image type\", NULL, str);\n    if (ms->look_direction == 'R')\n      sprintf(str, \"right\");\n    else if (ms->look_direction == 'L')\n      sprintf(str, \"left\");\n    nc_meta_str(meta_id, \"sar_look_direction\", \"SAR satellite look direction\", \n\t\tNULL, str);\n    nc_meta_int(meta_id, \"sar_look_count\", \"number of looks to take from SLC\", \n\t\tNULL, &ms->look_count);\n    nc_meta_int(meta_id, \"sar_multilook\", \"multilooking flag\", NULL, \n\t\t&ms->multilook);\n    nc_meta_int(meta_id, \"sar_deskewed\", \"zero doppler deskew flag\", NULL, \n\t\t&ms->deskewed);\n    nc_meta_int(meta_id, \"sar_original_line_count\", \n\t\t\"number of lines in original image\", NULL, \n\t\t&ms->original_line_count);\n    nc_meta_int(meta_id, \"sar_original_sample_count\", \n\t\t\"number of samples in original image\", NULL, \n\t\t&ms->original_sample_count);\n    nc_meta_double(meta_id, \"sar_line_increment\", \n\t\t   \"line increment for sampling\", NULL, &ms->line_increment);\n    nc_meta_double(meta_id, \"sar_sample_increment\", \n\t\t   \"sample increment for sampling\", NULL, \n\t\t   &ms->sample_increment);\n    nc_meta_double(meta_id, \"sar_range_time_per_pixel\", \n\t\t   \"time per pixel in range\", \"s\", \n\t\t   &ms->range_time_per_pixel);\n    nc_meta_double(meta_id, \"sar_azimuth_time_per_pixel\", \n\t\t   \"time per pixel in azimuth\", \"s\", \n\t\t   &ms->azimuth_time_per_pixel);\n    nc_meta_double(meta_id, \"sar_slant_range_first_pixel\", \n\t\t   \"slant range to first pixel\", \"m\", \n\t\t   &ms->slant_range_first_pixel);\n    nc_meta_double(meta_id, \"sar_slant_shift\", \n\t\t   \"error correction factor in slant range\", \"m\", \n\t\t   &ms->slant_shift);\n    nc_meta_double(meta_id, \"sar_time_shift\", \"error correction factor in time\",\n\t\t   \"s\", &ms->time_shift);\n    nc_meta_double(meta_id, \"sar_wavelength\", \"SAR carrier wavelength\", \"m\", \n\t\t   &ms->wavelength);\n    nc_meta_double(meta_id, \"sar_pulse_repetition_frequency\", \n\t\t   \"pulse repetition frequency\", \"Hz\", &ms->prf);\n    nc_meta_double(meta_id, \"sar_earth_radius\", \"earth radius at scene center\", \n\t\t   \"m\", &ms->earth_radius);\n    nc_meta_double(meta_id, \"sar_satellite_height\", \n\t\t   \"satellite height from earth's center\", \"m\", \n\t\t   &ms->satellite_height);\n    nc_meta_double(meta_id, \"sar_range_doppler_centroid\", \n\t\t   \"range doppler centroid\", \"Hz\", \n\t\t   &ms->range_doppler_coefficients[0]);\n    nc_meta_double(meta_id, \"sar_range_doppler_linear\", \n\t\t   \"range doppler per range pixel\", \"Hz/pixel\", \n\t\t   &ms->range_doppler_coefficients[1]);\n    nc_meta_double(meta_id, \"sar_range_doppler_quadratic\", \n\t\t   \"range doppler per range pixel square\", \"Hz/pixel^2\", \n\t\t   &ms->range_doppler_coefficients[2]);\n    nc_meta_double(meta_id, \"sar_azimuth_doppler_centroid\", \n\t\t   \"azimuth doppler centroid\", \"Hz\", \n\t\t   &ms->azimuth_doppler_coefficients[0]);\n    nc_meta_double(meta_id, \"sar_azimuth_doppler_linear\", \n\t\t   \"azimuth doppler per azimuth pixel\", \"Hz/pixel\", \n\t\t   &ms->azimuth_doppler_coefficients[1]);\n    nc_meta_double(meta_id, \"sar_azimuth_doppler_quadratic\", \n\t\t   \"azimuth doppler per azimuth per azimuth pixel square\", \n\t\t   \"Hz/pixel^2\", &ms->azimuth_doppler_coefficients[2]);\n  }\n\n  char tmp[50];\n  if (mo) {\n    // Metadata - state vector block\n    nc_meta_int(meta_id, \"orbit_year\", \"year of image start\", NULL, &mo->year);\n    nc_meta_int(meta_id, \"orbit_day_of_year\", \"day of the year at image start\",\n\t\tNULL, &mo->julDay);\n    nc_meta_double(meta_id, \"orbit_second_of_day\", \n\t\t   \"second of the day at image start\", \"seconds\", &mo->second);\n    int vector_count = mo->vector_count;\n    nc_meta_int(meta_id, \"orbit_vector_count\", \"number of state vectors\", NULL,\n\t\t&vector_count);\n    for (ii=0; ii<vector_count; ii++) {\n      sprintf(tmp, \"orbit_vector[%d]_time\", ii+1);\n      nc_meta_double(meta_id, tmp, \"time relative to image start\", \"s\",\n\t\t     &mo->vecs[ii].time);\n      sprintf(tmp, \"orbit_vector[%d]_position_x\", ii+1);\n      nc_meta_double(meta_id, tmp, \"x coordinate, earth-fixed\", \"m\",\n\t\t     &mo->vecs[ii].vec.pos.x);\n      sprintf(tmp, \"orbit_vector[%d]_position_y\", ii+1);\n      nc_meta_double(meta_id, tmp, \"y coordinate, earth-fixed\", \"m\",\n\t\t     &mo->vecs[ii].vec.pos.y);\n      sprintf(tmp, \"orbit_vector[%d]_position_z\", ii+1);\n      nc_meta_double(meta_id, tmp, \"z coordinate, earth-fixed\", \"m\",\n\t\t     &mo->vecs[ii].vec.pos.z);\n      sprintf(tmp, \"orbit_vector[%d]_velocity_x\", ii+1);\n      nc_meta_double(meta_id, tmp, \"x velocity, earth-fixed\", \"m/s\",\n\t\t     &mo->vecs[ii].vec.vel.x);\n      sprintf(tmp, \"orbit_vector[%d]_velocity_y\", ii+1);\n      nc_meta_double(meta_id, tmp, \"y velocity, earth-fixed\", \"m/s\",\n\t\t     &mo->vecs[ii].vec.vel.y);\n      sprintf(tmp, \"orbit_vector[%d]_velocity_z\", ii+1);\n      nc_meta_double(meta_id, tmp, \"z velocity, earth-fixed\", \"m/s\",\n\t\t     &mo->vecs[ii].vec.vel.z);\n    }    \n  }\n\n  // Finish off definition block\n  nc_enddef(ncid); \n    \n  // Write ASF metadata to XML file\n  char *output_file_name = \n    (char *) MALLOC(sizeof(char)*(strlen(output_file)+5));\n  sprintf(output_file_name, \"%s.xml\", output_file);\n  meta_write_xml(meta, output_file_name);\n  FREE(output_file_name);\n\n  // Clean up\n  FREE(str);\n  if (spatial_ref)\n    FREE(spatial_ref);\n  \n  return netcdf;\n}\n\nvoid finalize_netcdf_file(netcdf_t *netcdf, meta_parameters *md)\n{\n  int ncid = netcdf->ncid;\n  int n = md->general->band_count;\n  int nl = md->general->line_count;\n  int ns = md->general->sample_count;\n  long pixel_count = md->general->line_count * md->general->sample_count;\n  int projected = FALSE;\n  if (md->projection && md->projection->type != SCANSAR_PROJECTION)\n    projected = TRUE;\n\n  // Extra bands - Time\n  float time = (float) seconds_from_str(md->general->acquisition_date);\n  asfPrintStatus(\"Storing band 'time' ...\\n\");\n  nc_put_var_float(ncid, netcdf->var_id[n], &time);\n\n  // Extra bands - longitude\n  n++;\n  int ii, kk;\n  double *value = (double *) MALLOC(sizeof(double)*MAX_PTS);\n  double *l = (double *) MALLOC(sizeof(double)*MAX_PTS);\n  double *s = (double *) MALLOC(sizeof(double)*MAX_PTS);\n  double line, sample, lat, lon, first_value;\n  float *lons = (float *) MALLOC(sizeof(float)*pixel_count);\n  asfPrintStatus(\"Generating band 'longitude' ...\\n\");\n  meta_get_latLon(md, 0, 0, 0.0, &lat, &lon);\n  if (lon < 0.0)\n    first_value = lon + 360.0;\n  else\n    first_value = lon;\n  asfPrintStatus(\"Calculating grid for quadratic fit ...\\n\");\n  for (ii=0; ii<RES; ii++) {\n    for (kk=0; kk<RES; kk++) {\n      line = ii * nl / RES;\n      sample = kk * ns / RES;\n      meta_get_latLon(md, line, sample, 0.0, &lat, &lon);\n      l[ii*RES+kk] = line;\n      s[ii*RES+kk] = sample;\n      if (lon < 0.0)\n\tvalue[ii*RES+kk] = lon + 360.0;\n      else\n\tvalue[ii*RES+kk] = lon;\n    }\n    asfLineMeter(ii, nl);\n  }\n  quadratic_2d q = find_quadratic(value, l, s, MAX_PTS);\n  q.A = first_value;\n  for (ii=0; ii<nl; ii++) {\n    for (kk=0; kk<ns; kk++) {\n      lons[ii*ns+kk] = (float)\n\t(q.A + q.B*ii + q.C*kk + q.D*ii*ii + q.E*ii*kk + q.F*kk*kk +\n\t q.G*ii*ii*kk + q.H*ii*kk*kk + q.I*ii*ii*kk*kk + q.J*ii*ii*ii +\n\t q.K*kk*kk*kk) - 360.0;\n      if (lons[ii*ns+kk] < -180.0)\n\tlons[ii*ns+kk] += 360.0;\n    }\n    asfLineMeter(ii, nl);\n  }\n  asfPrintStatus(\"Storing band 'longitude' ...\\n\");\n  nc_put_var_float(ncid, netcdf->var_id[n], &lons[0]);\n  FREE(lons);\n\n  // Extra bands - Latitude\n  n++;\n  float *lats = (float *) MALLOC(sizeof(float)*pixel_count);\n  asfPrintStatus(\"Generating band 'latitude' ...\\n\");\n  meta_get_latLon(md, 0, 0, 0.0, &lat, &lon);\n  first_value = lat + 180.0;\n  asfPrintStatus(\"Calculating grid for quadratic fit ...\\n\");\n  for (ii=0; ii<RES; ii++) {\n    for (kk=0; kk<RES; kk++) {\n      line = ii * nl / RES;\n      sample = kk * ns / RES;\n      meta_get_latLon(md, line, sample, 0.0, &lat, &lon);\n      l[ii*RES+kk] = line;\n      s[ii*RES+kk] = sample;\n      value[ii*RES+kk] = lat + 180.0;\n    }\n    asfLineMeter(ii, nl);\n  }\n  q = find_quadratic(value, l, s, MAX_PTS);\n  q.A = first_value;\n  for (ii=0; ii<nl; ii++) {\n    for (kk=0; kk<ns; kk++) {\n      if (md->general->orbit_direction == 'A')\n\tlats[(nl-ii-1)*ns+kk] = (float)\n\t  (q.A + q.B*ii + q.C*kk + q.D*ii*ii + q.E*ii*kk + q.F*kk*kk +\n\t   q.G*ii*ii*kk + q.H*ii*kk*kk + q.I*ii*ii*kk*kk + q.J*ii*ii*ii +\n\t   q.K*kk*kk*kk) - 180.0;\n      else\n\tlats[ii*ns+kk] = (float)\n\t  (q.A + q.B*ii + q.C*kk + q.D*ii*ii + q.E*ii*kk + q.F*kk*kk +\n\t   q.G*ii*ii*kk + q.H*ii*kk*kk + q.I*ii*ii*kk*kk + q.J*ii*ii*ii +\n\t   q.K*kk*kk*kk) - 180.0;\n    }\n    asfLineMeter(ii, nl);\n  }\n  asfPrintStatus(\"Storing band 'latitude' ...\\n\");\n  nc_put_var_float(ncid, netcdf->var_id[n], &lats[0]);\n  FREE(lats);\n\n  if (projected) {\n    // Extra bands - ygrid\n    n++;\n    float *ygrids = (float *) MALLOC(sizeof(float)*pixel_count);\n    for (ii=0; ii<nl; ii++) {\n      for (kk=0; kk<ns; kk++)\n\tygrids[ii*ns+kk] = \n\t  md->projection->startY + kk*md->projection->perY;\n      asfLineMeter(ii, nl);\n    }\n    asfPrintStatus(\"Storing band 'ygrid' ...\\n\");\n    nc_put_var_float(ncid, netcdf->var_id[n], &ygrids[0]);\n    FREE(ygrids);\n    \n    // Extra bands - xgrid\n    n++;\n    float *xgrids = (float *) MALLOC(sizeof(float)*pixel_count);\n    for (ii=0; ii<nl; ii++) {\n      for (kk=0; kk<ns; kk++) \n\txgrids[ii*ns+kk] = \n\t  md->projection->startX + kk*md->projection->perX;\n      asfLineMeter(ii, nl);\n    }\n    asfPrintStatus(\"Storing band 'xgrid' ...\\n\");\n    nc_put_var_float(ncid, netcdf->var_id[n], &xgrids[0]);\n    FREE(xgrids);\n  }\n\n  // Close file and clean up\n  int status = nc_close(ncid);\n  if (status != NC_NOERR)\n    asfPrintError(\"Could not close netCDF file (%s).\\n\", nc_strerror(status));\n  FREE(netcdf->var_id);\n  FREE(netcdf);\n}\n", "meta": {"hexsha": "f0927900e9cc060be2827853717828c79f438c3e", "size": 42015, "ext": "c", "lang": "C", "max_stars_repo_path": "src/libasf_export/export_netcdf.c", "max_stars_repo_name": "glshort/MapReady", "max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z", "max_issues_repo_path": "src/libasf_export/export_netcdf.c", "max_issues_repo_name": "glshort/MapReady", "max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libasf_export/export_netcdf.c", "max_forks_repo_name": "glshort/MapReady", "max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z", "avg_line_length": 43.225308642, "max_line_length": 509, "alphanum_fraction": 0.6636677377, "num_tokens": 13406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2909808785120009, "lm_q2_score": 0.030214586849079555, "lm_q1q2_score": 0.008791867025222317}}
{"text": "/* $Id$  */\n/*--------------------------------------------------------------------*/\n/*;  Copyright (C) 2013                                               */\n/*;  Associated Universities, Inc. Washington DC, USA.                */\n/*;                                                                   */\n/*;  This program is free software; you can redistribute it and/or    */\n/*;  modify it under the terms of the GNU General Public License as   */\n/*;  published by the Free Software Foundation; either version 2 of   */\n/*;  the License, or (at your option) any later version.              */\n/*;                                                                   */\n/*;  This program is distributed in the hope that it will be useful,  */\n/*;  but WITHOUT ANY WARRANTY; without even the implied warranty of   */\n/*;  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the    */\n/*;  GNU General Public License for more details.                     */\n/*;                                                                   */\n/*;  You should have received a copy of the GNU General Public        */\n/*;  License along with this program; if not, write to the Free       */\n/*;  Software Foundation, Inc., 675 Massachusetts Ave, Cambridge,     */\n/*;  MA 02139, USA.                                                   */\n/*;                                                                   */\n/*;Correspondence about this software should be addressed as follows: */\n/*;         Internet email: bcotton@nrao.edu.                         */\n/*;         Postal address: William Cotton                            */\n/*;                         National Radio Astronomy Observatory      */\n/*;                         520 Edgemont Road                         */\n/*;                         Charlottesville, VA 22903-2475 USA        */\n/*--------------------------------------------------------------------*/\n\n#include <time.h>\n#include <gsl/gsl_randist.h>\n#include \"ObitThread.h\"\n#include \"ObitOTFUtil.h\"\n\n/*----------------Obit: Merx mollis mortibus nuper ------------------*/\n/**\n * \\file ObitVEGASUtil.c\n * ObitOTF class utility function definitions.\n */\n\n/*---------------Private structures----------------*/\n\n/*---------------Private function prototypes----------------*/\n/*----------------------Public functions---------------------------*/\n/**\n * Average the frequencies in a GBT/VEGAS OTF\n * \\param inVEGAS  Input VEGAS, any calibration and flagging should be applied.\n * \\param outVEGAS Output VEGAS, must already be defined\n * \\param chAvg  Number of channels to average, -1 => all\n * \\param err    Error stack\n */\nvoid ObitVEGASUtilAverage(ObitOTF *inOTF, ObitOTF *outOTF, olong chAvg,\n\t\t\t  ObitErr *err) \n{\n  const ObitClassInfo *ParentClass;\n  ObitIOCode retCode;\n  gboolean doCalSelect, done;\n  olong firstRec, navg, nchanIn, nchanOut;\n  olong ichan, ochan, ochn, ifeed, nfeed, istok, nstok, indx, ondx;\n  ObitInfoType type;\n  ObitIOAccess access;\n  gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};\n  ofloat sum, sumWt, *iData, *oData;\n  olong NPIO, iran, irec;\n  ObitOTFDesc *iDesc, *oDesc;\n  ObitHistory *inHist=NULL, *outHist=NULL;\n  /* Don't copy Cal and Soln or data or flag tables */\n  gchar *exclude[]={\"OTFSoln\", \"OTFCal\", \"OTFScanData\", \"OTFFlag\", NULL};\n  gchar *routine = \"ObitVEGASUtilAverage\";\n\n    /* error checks */\n  g_assert (ObitErrIsA(err));\n  if (err->error) return;\n  g_assert (ObitOTFIsA(inOTF));\n  g_assert (ObitOTFIsA(outOTF));\n  /* Input and output must be different */\n  Obit_return_if_fail ((!ObitOTFSame (inOTF, outOTF, err)), err,\n\t\t       \"%s: Output cannot be the same as the input\", routine);\n\n  /* deep copy any base class members */\n  ParentClass = ((ObitClassInfo*)inOTF->ClassInfo)->ParentClass;\n  g_assert ((ParentClass!=NULL) && (ParentClass->ObitCopy!=NULL));\n  ParentClass->ObitCopy (inOTF, outOTF, err);\n  outOTF->mySel     = newObitOTFSel (outOTF->name);\n  outOTF->tableList = newObitTableList(outOTF->name);\n  outOTF->geom      = newObitOTFArrayGeom(outOTF->name);\n\n  /* Calibration wanted? */ \n  doCalSelect = FALSE;\n  ObitInfoListGetTest(inOTF->info, \"doCalSelect\", &type, (gint32*)dim, \n\t\t      &doCalSelect);\n  if (doCalSelect) access = OBIT_IO_ReadCal;\n  else access = OBIT_IO_ReadWrite;\n\n  /* Make sure NPIO the same */\n  NPIO = 1000;\n  dim[0] = 1;\n  ObitInfoListGetTest (inOTF->info, \"nRecPIO\", &type, dim,  &NPIO);\n  ObitInfoListAlwaysPut (inOTF->info, \"nRecPIO\", OBIT_long, dim,  &NPIO);\n  ObitInfoListAlwaysPut (outOTF->info, \"nRecPIO\", OBIT_long, dim,  &NPIO);\n\n  /* Open Input Data */\n  retCode = ObitOTFOpen (inOTF, access, err);\n  if ((retCode != OBIT_IO_OK) || (err->error>0)) goto cleanup;\n\n  /* How many channels to average? Defaults to all. */\n  iDesc = inOTF->myDesc;\n  nchanIn = iDesc->inaxes[iDesc->jlocf];\n  if (chAvg>0) navg = chAvg;\n  else         navg = nchanIn;\n  navg     = MAX (1, MIN (navg, nchanIn));\n  nchanOut = MAX (1, (olong)(((ofloat)(nchanIn)/navg)+0.9999));\n\n  /* Number of feeds */\n  nfeed = iDesc->inaxes[iDesc->jlocfeed];\n  /* NUmber of Stokes */\n  nstok = iDesc->inaxes[iDesc->jlocs];\n\n  /* Copy descriptor */\n  outOTF->myDesc = (gpointer)ObitOTFDescCopy(iDesc, outOTF->myDesc, err); \n  outOTF->myDesc->nrecord = 0;     /* may not copy all */\n  oDesc = outOTF->myDesc;\n \n  /* Averaging in frequency */\n  oDesc->inaxes[oDesc->jlocf]      = nchanOut;\n  oDesc->colRepeat[oDesc->ncol-1] /= navg;\n  oDesc->cdelt[oDesc->jlocf]      *= navg;\n  oDesc->crpix[oDesc->jlocf]      /= navg;\n  ObitOTFDescIndex (oDesc);\n\n  /* copy/average Array Geometry - this time with full information\n     NO, VEGAS doesn't have one \"detector\" per frequency \n  outOTF->geom = ObitOTFArrayGeomAver(inOTF->geom, iDesc, outOTF->geom, oDesc, err);\n  if (err->error) goto cleanup; */\n\n  /* Open Output Data */\n  retCode = ObitOTFOpen (outOTF, OBIT_IO_WriteOnly, err) ;\n  if ((retCode != OBIT_IO_OK) || (err->error>0)) goto cleanup;\n\n  /* Copy any history */\n  inHist  = newObitHistoryValue(\"in history\", inOTF->info, err);\n  outHist = newObitHistoryValue(\"out history\", outOTF->info, err);\n  outHist = ObitHistoryCopy (inHist, outHist, err);\n  if (err->error)  goto cleanup;\n  inHist  = ObitHistoryUnref(inHist);\n  outHist = ObitHistoryUnref(outHist);\n\n   /* Copy tables before data  */\n  retCode = ObitOTFCopyTables (inOTF, outOTF, exclude, NULL, err);\n  if (err->error) goto cleanup;\n\n  /* Close and reopen input to init calibration which will have \n     been disturbed by the table copy */\n  retCode = ObitOTFClose (inOTF, err);\n  if (err->error) goto cleanup;\n\n  retCode = ObitOTFOpen (inOTF, access, err);\n  if ((retCode != OBIT_IO_OK) || (err->error>0)) goto cleanup;\n\n  /* Loop over data */\n  done = (retCode != OBIT_IO_OK);\n  while (!done) {\n\n    /* read buffer */#\n    retCode = ObitOTFRead (inOTF, NULL, err);\n    if (err->error) goto cleanup;\n    done = (retCode == OBIT_IO_EOF); /* done? */\n    if (done) break;\n    firstRec = inOTF->myDesc->firstRec;\n\n    iData = inOTF->buffer;   /* Input data pointer */\n    oData = outOTF->buffer;  /* Output data pointer */\n    \n    /* How many? */\n    outOTF->myDesc->numRecBuff = inOTF->myDesc->numRecBuff;\n    \n    /* Loop over buffer */\n    for (irec=0; irec<iDesc->numRecBuff; irec++) {\n\n      /* Copy random (descriptive parameters */\n      for (iran=0; iran<iDesc->numDesc; iran++) oData[iran] = iData[iran];\n\n      /* Average input to output */\n      /* Loop over Stokes */\n      for (istok=0; istok<nstok; istok++) {\n\t/* Loop over Feed */\n\tfor (ifeed=0; ifeed<nfeed; ifeed++) {\n\t  /* Outer loop over channel */\n\t  ochn = 0;  /* output channel 0-rel index */\n\t  for (ochan=0; ochan<nchanIn; ochan+=navg) {\n\t    /* Inner frequency loop summing */\n\t    sum = sumWt = 0.0;\n\t    indx = iDesc->ilocdata + istok*iDesc->incs + ifeed*iDesc->incfeed;\n\t    ondx = oDesc->ilocdata + istok*oDesc->incs + ifeed*oDesc->incfeed;\n\t    for (ichan=ochan; ichan<ochan+navg; ichan++) {\n\t      sum   += iData[indx+ichan*iDesc->incf] * iData[indx+ichan*iDesc->incf+1];\n\t      sumWt += iData[indx+ichan*iDesc->incf+1];\n\t    } /* end inner loop */\n\t    /* Save average to outout */\n\t    if (sumWt>0.0) {\n\t      oData[ondx+ochn*oDesc->incf]   = sum/sumWt;\n\t      oData[ondx+ochn*oDesc->incf+1] = sumWt;\n\t    } else { /* bad */\n\t      oData[ondx+ochn*oDesc->incf]   = 0.0;\n\t      oData[ondx+ochn*oDesc->incf+1] = 0.0;\n\t    }\n\t    ochn++;\n\t  } /* end outer channel loop */\n\t} /* end feed loop */\n      } /* end Stokes loop */\n      iData += iDesc->lrec;  /* Update buffer pointers */\n      oData += oDesc->lrec;\n    } /* end loop over buffer */\n    \n    /* Write buffer */\n    if (outOTF->myDesc->numRecBuff>0) retCode = ObitOTFWrite (outOTF, NULL, err);\n    if (err->error) goto cleanup;\n  } /* end loop over file */\n  \n cleanup:\n  /* unset output buffer  */\n  outOTF->buffer = NULL;\n  outOTF->bufferSize = 0;\n  retCode = ObitOTFClose (outOTF, err); /* Close output */\n\n  /* Close input */\n  retCode = ObitOTFClose (inOTF, err);\n\n  /* cleanup */\n  if (err->error) Obit_traceback_msg (err, routine, inOTF->name);\n\n} /* end ObitOTFUtilAverage */\n", "meta": {"hexsha": "32ef3157d19be3c00749f6adf71cace65aa2cc2e", "size": 9037, "ext": "c", "lang": "C", "max_stars_repo_path": "ObitSystem/ObitSD/src/ObitVEGASUtil.c", "max_stars_repo_name": "sarrvesh/Obit", "max_stars_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-08-26T06:53:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-20T01:08:59.000Z", "max_issues_repo_path": "ObitSystem/ObitSD/src/ObitVEGASUtil.c", "max_issues_repo_name": "sarrvesh/Obit", "max_issues_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ObitSystem/ObitSD/src/ObitVEGASUtil.c", "max_forks_repo_name": "sarrvesh/Obit", "max_forks_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-08-29T15:12:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:16:08.000Z", "avg_line_length": 38.9525862069, "max_line_length": 84, "alphanum_fraction": 0.5841540334, "num_tokens": 2728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22815649166448124, "lm_q2_score": 0.038466191880538673, "lm_q1q2_score": 0.008776311387156458}}
{"text": "/* histogram/file2d.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <stdio.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_block.h>\n#include <gsl/gsl_histogram2d.h>\n\nint\ngsl_histogram2d_fread (FILE * stream, gsl_histogram2d * h)\n{\n  int status = gsl_block_raw_fread (stream, h->xrange, h->nx + 1, 1);\n\n  if (status)\n    return status;\n\n  status = gsl_block_raw_fread (stream, h->yrange, h->ny + 1, 1);\n\n  if (status)\n    return status;\n\n  status = gsl_block_raw_fread (stream, h->bin, h->nx * h->ny, 1);\n\n  return status;\n}\n\nint\ngsl_histogram2d_fwrite (FILE * stream, const gsl_histogram2d * h)\n{\n  int status = gsl_block_raw_fwrite (stream, h->xrange, h->nx + 1, 1);\n\n  if (status)\n    return status;\n\n  status = gsl_block_raw_fwrite (stream, h->yrange, h->ny + 1, 1);\n\n  if (status)\n    return status;\n\n  status = gsl_block_raw_fwrite (stream, h->bin, h->nx * h->ny, 1);\n  return status;\n}\n\nint\ngsl_histogram2d_fprintf (FILE * stream, const gsl_histogram2d * h,\n                         const char *range_format, const char *bin_format)\n{\n  size_t i, j;\n  const size_t nx = h->nx;\n  const size_t ny = h->ny;\n  int status;\n\n  for (i = 0; i < nx; i++)\n    {\n      for (j = 0; j < ny; j++)\n        {\n          status = fprintf (stream, range_format, h->xrange[i]);\n\n          if (status < 0)\n            {\n              GSL_ERROR (\"fprintf failed\", GSL_EFAILED);\n            }\n\n          status = putc (' ', stream);\n\n          if (status == EOF)\n            {\n              GSL_ERROR (\"putc failed\", GSL_EFAILED);\n            }\n\n          status = fprintf (stream, range_format, h->xrange[i + 1]);\n\n          if (status < 0)\n            {\n              GSL_ERROR (\"fprintf failed\", GSL_EFAILED);\n            }\n\n          status = putc (' ', stream);\n\n          if (status == EOF)\n            {\n              GSL_ERROR (\"putc failed\", GSL_EFAILED);\n            }\n\n          status = fprintf (stream, range_format, h->yrange[j]);\n\n          if (status < 0)\n            {\n              GSL_ERROR (\"fprintf failed\", GSL_EFAILED);\n            }\n\n          status = putc (' ', stream);\n\n          if (status == EOF)\n            {\n              GSL_ERROR (\"putc failed\", GSL_EFAILED);\n            }\n\n          status = fprintf (stream, range_format, h->yrange[j + 1]);\n\n          if (status < 0)\n            {\n              GSL_ERROR (\"fprintf failed\", GSL_EFAILED);\n            }\n\n          status = putc (' ', stream);\n\n          if (status == EOF)\n            {\n              GSL_ERROR (\"putc failed\", GSL_EFAILED);\n            }\n\n          status = fprintf (stream, bin_format, h->bin[i * ny + j]);\n\n          if (status < 0)\n            {\n              GSL_ERROR (\"fprintf failed\", GSL_EFAILED);\n            }\n\n          status = putc ('\\n', stream);\n\n          if (status == EOF)\n            {\n              GSL_ERROR (\"putc failed\", GSL_EFAILED);\n            }\n        }\n      status = putc ('\\n', stream);\n\n      if (status == EOF)\n        {\n          GSL_ERROR (\"putc failed\", GSL_EFAILED);\n        }\n    }\n\n  return GSL_SUCCESS;\n}\n\nint\ngsl_histogram2d_fscanf (FILE * stream, gsl_histogram2d * h)\n{\n  size_t i, j;\n  const size_t nx = h->nx;\n  const size_t ny = h->ny;\n  double xupper, yupper;\n\n  for (i = 0; i < nx; i++)\n    {\n      for (j = 0; j < ny; j++)\n        {\n          int status = fscanf (stream,\n                               \"%lg %lg %lg %lg %lg\",\n                               h->xrange + i, &xupper,\n                               h->yrange + j, &yupper,\n                               h->bin + i * ny + j);\n\n          if (status != 5)\n            {\n              GSL_ERROR (\"fscanf failed\", GSL_EFAILED);\n            }\n        }\n      h->yrange[ny] = yupper;\n    }\n\n  h->xrange[nx] = xupper;\n\n  return GSL_SUCCESS;\n}\n", "meta": {"hexsha": "26877840a3a3ee6e8d33010064c0721ca846e0d6", "size": 4516, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/histogram/file2d.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/histogram/file2d.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/histogram/file2d.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 24.4108108108, "max_line_length": 81, "alphanum_fraction": 0.5276793623, "num_tokens": 1199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3380771241500058, "lm_q2_score": 0.025957359929267794, "lm_q1q2_score": 0.008775589595413453}}
{"text": "/* vector/gsl_vector_complex_long_double.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_VECTOR_COMPLEX_LONG_DOUBLE_H__\n#define __GSL_VECTOR_COMPLEX_LONG_DOUBLE_H__\n\n#if !defined( GSL_FUN )\n#  if !defined( GSL_DLL )\n#    define GSL_FUN extern\n#  elif defined( BUILD_GSL_DLL )\n#    define GSL_FUN extern __declspec(dllexport)\n#  else\n#    define GSL_FUN extern __declspec(dllimport)\n#  endif\n#endif\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_complex.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_vector_long_double.h>\n#include <gsl/gsl_vector_complex.h>\n#include <gsl/gsl_block_complex_long_double.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size;\n  size_t stride;\n  long double *data;\n  gsl_block_complex_long_double *block;\n  int owner;\n} gsl_vector_complex_long_double;\n\ntypedef struct\n{\n  gsl_vector_complex_long_double vector;\n} _gsl_vector_complex_long_double_view;\n\ntypedef _gsl_vector_complex_long_double_view gsl_vector_complex_long_double_view;\n\ntypedef struct\n{\n  gsl_vector_complex_long_double vector;\n} _gsl_vector_complex_long_double_const_view;\n\ntypedef const _gsl_vector_complex_long_double_const_view gsl_vector_complex_long_double_const_view;\n\n/* Allocation */\n\nGSL_FUN gsl_vector_complex_long_double *gsl_vector_complex_long_double_alloc (const size_t n);\nGSL_FUN gsl_vector_complex_long_double *gsl_vector_complex_long_double_calloc (const size_t n);\n\nGSL_FUN gsl_vector_complex_long_double *\ngsl_vector_complex_long_double_alloc_from_block (gsl_block_complex_long_double * b, \n                                           const size_t offset, \n                                           const size_t n, \n                                           const size_t stride);\n\nGSL_FUN gsl_vector_complex_long_double *\ngsl_vector_complex_long_double_alloc_from_vector (gsl_vector_complex_long_double * v, \n                                             const size_t offset, \n                                             const size_t n, \n                                             const size_t stride);\n\nGSL_FUN void gsl_vector_complex_long_double_free (gsl_vector_complex_long_double * v);\n\n/* Views */\n\nGSL_FUN _gsl_vector_complex_long_double_view\ngsl_vector_complex_long_double_view_array (long double *base,\n                                     size_t n);\n\nGSL_FUN _gsl_vector_complex_long_double_view\ngsl_vector_complex_long_double_view_array_with_stride (long double *base,\n                                                 size_t stride,\n                                                 size_t n);\n\nGSL_FUN _gsl_vector_complex_long_double_const_view\ngsl_vector_complex_long_double_const_view_array (const long double *base,\n                                           size_t n);\n\nGSL_FUN _gsl_vector_complex_long_double_const_view\ngsl_vector_complex_long_double_const_view_array_with_stride (const long double *base,\n                                                       size_t stride,\n                                                       size_t n);\n\nGSL_FUN _gsl_vector_complex_long_double_view\ngsl_vector_complex_long_double_subvector (gsl_vector_complex_long_double *base,\n                                         size_t i, \n                                         size_t n);\n\n\nGSL_FUN _gsl_vector_complex_long_double_view \ngsl_vector_complex_long_double_subvector_with_stride (gsl_vector_complex_long_double *v, \n                                                size_t i, \n                                                size_t stride, \n                                                size_t n);\n\nGSL_FUN _gsl_vector_complex_long_double_const_view\ngsl_vector_complex_long_double_const_subvector (const gsl_vector_complex_long_double *base,\n                                               size_t i, \n                                               size_t n);\n\n\nGSL_FUN _gsl_vector_complex_long_double_const_view \ngsl_vector_complex_long_double_const_subvector_with_stride (const gsl_vector_complex_long_double *v, \n                                                      size_t i, \n                                                      size_t stride, \n                                                      size_t n);\n\nGSL_FUN _gsl_vector_long_double_view\ngsl_vector_complex_long_double_real (gsl_vector_complex_long_double *v);\n\nGSL_FUN _gsl_vector_long_double_view \ngsl_vector_complex_long_double_imag (gsl_vector_complex_long_double *v);\n\nGSL_FUN _gsl_vector_long_double_const_view\ngsl_vector_complex_long_double_const_real (const gsl_vector_complex_long_double *v);\n\nGSL_FUN _gsl_vector_long_double_const_view \ngsl_vector_complex_long_double_const_imag (const gsl_vector_complex_long_double *v);\n\n\n/* Operations */\n\nGSL_FUN void gsl_vector_complex_long_double_set_zero (gsl_vector_complex_long_double * v);\nGSL_FUN void gsl_vector_complex_long_double_set_all (gsl_vector_complex_long_double * v,\n                                       gsl_complex_long_double z);\nGSL_FUN int gsl_vector_complex_long_double_set_basis (gsl_vector_complex_long_double * v, size_t i);\n\nGSL_FUN int gsl_vector_complex_long_double_fread (FILE * stream,\n                                    gsl_vector_complex_long_double * v);\nGSL_FUN int gsl_vector_complex_long_double_fwrite (FILE * stream,\n                                     const gsl_vector_complex_long_double * v);\nGSL_FUN int gsl_vector_complex_long_double_fscanf (FILE * stream,\n                                     gsl_vector_complex_long_double * v);\nGSL_FUN int gsl_vector_complex_long_double_fprintf (FILE * stream,\n                                      const gsl_vector_complex_long_double * v,\n                                      const char *format);\n\nGSL_FUN int gsl_vector_complex_long_double_memcpy (gsl_vector_complex_long_double * dest, const gsl_vector_complex_long_double * src);\n\nGSL_FUN int gsl_vector_complex_long_double_reverse (gsl_vector_complex_long_double * v);\n\nGSL_FUN int gsl_vector_complex_long_double_swap (gsl_vector_complex_long_double * v, gsl_vector_complex_long_double * w);\nGSL_FUN int gsl_vector_complex_long_double_swap_elements (gsl_vector_complex_long_double * v, const size_t i, const size_t j);\n\nGSL_FUN int gsl_vector_complex_long_double_equal (const gsl_vector_complex_long_double * u, \n                                    const gsl_vector_complex_long_double * v);\n\nGSL_FUN int gsl_vector_complex_long_double_isnull (const gsl_vector_complex_long_double * v);\nGSL_FUN int gsl_vector_complex_long_double_ispos (const gsl_vector_complex_long_double * v);\nGSL_FUN int gsl_vector_complex_long_double_isneg (const gsl_vector_complex_long_double * v);\nGSL_FUN int gsl_vector_complex_long_double_isnonneg (const gsl_vector_complex_long_double * v);\n\nGSL_FUN int gsl_vector_complex_long_double_add (gsl_vector_complex_long_double * a, const gsl_vector_complex_long_double * b);\nGSL_FUN int gsl_vector_complex_long_double_sub (gsl_vector_complex_long_double * a, const gsl_vector_complex_long_double * b);\nGSL_FUN int gsl_vector_complex_long_double_mul (gsl_vector_complex_long_double * a, const gsl_vector_complex_long_double * b);\nGSL_FUN int gsl_vector_complex_long_double_div (gsl_vector_complex_long_double * a, const gsl_vector_complex_long_double * b);\nGSL_FUN int gsl_vector_complex_long_double_scale (gsl_vector_complex_long_double * a, const gsl_complex_long_double x);\nGSL_FUN int gsl_vector_complex_long_double_add_constant (gsl_vector_complex_long_double * a, const gsl_complex_long_double x);\nGSL_FUN int gsl_vector_complex_long_double_axpby (const gsl_complex_long_double alpha, const gsl_vector_complex_long_double * x, const gsl_complex_long_double beta, gsl_vector_complex_long_double * y);\n\nGSL_FUN INLINE_DECL gsl_complex_long_double gsl_vector_complex_long_double_get (const gsl_vector_complex_long_double * v, const size_t i);\nGSL_FUN INLINE_DECL void gsl_vector_complex_long_double_set (gsl_vector_complex_long_double * v, const size_t i, gsl_complex_long_double z);\nGSL_FUN INLINE_DECL gsl_complex_long_double *gsl_vector_complex_long_double_ptr (gsl_vector_complex_long_double * v, const size_t i);\nGSL_FUN INLINE_DECL const gsl_complex_long_double *gsl_vector_complex_long_double_const_ptr (const gsl_vector_complex_long_double * v, const size_t i);\n\n#ifdef HAVE_INLINE\n\nINLINE_FUN\ngsl_complex_long_double\ngsl_vector_complex_long_double_get (const gsl_vector_complex_long_double * v,\n                              const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= v->size))\n    {\n      gsl_complex_long_double zero = {{0, 0}};\n      GSL_ERROR_VAL (\"index out of range\", GSL_EINVAL, zero);\n    }\n#endif\n  return *GSL_COMPLEX_LONG_DOUBLE_AT (v, i);\n}\n\nINLINE_FUN\nvoid\ngsl_vector_complex_long_double_set (gsl_vector_complex_long_double * v,\n                              const size_t i, gsl_complex_long_double z)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= v->size))\n    {\n      GSL_ERROR_VOID (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  *GSL_COMPLEX_LONG_DOUBLE_AT (v, i) = z;\n}\n\nINLINE_FUN\ngsl_complex_long_double *\ngsl_vector_complex_long_double_ptr (gsl_vector_complex_long_double * v,\n                              const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= v->size))\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return GSL_COMPLEX_LONG_DOUBLE_AT (v, i);\n}\n\nINLINE_FUN\nconst gsl_complex_long_double *\ngsl_vector_complex_long_double_const_ptr (const gsl_vector_complex_long_double * v,\n                                    const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= v->size))\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return GSL_COMPLEX_LONG_DOUBLE_AT (v, i);\n}\n\n\n#endif /* HAVE_INLINE */\n\n__END_DECLS\n\n#endif /* __GSL_VECTOR_COMPLEX_LONG_DOUBLE_H__ */\n", "meta": {"hexsha": "8ad85a3b8cb26e893f8709fa2ecf6aee54c276fb", "size": 10746, "ext": "h", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_vector_complex_long_double.h", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-28T08:20:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-28T08:20:20.000Z", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_vector_complex_long_double.h", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_vector_complex_long_double.h", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-14T12:45:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-14T12:45:35.000Z", "avg_line_length": 40.8593155894, "max_line_length": 201, "alphanum_fraction": 0.721570817, "num_tokens": 2302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37022540649291935, "lm_q2_score": 0.023689471687092442, "lm_q1q2_score": 0.008770444284956304}}
{"text": "/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*\n**                                                                                  **\n** This file forms part of the Underworld geophysics modelling application.         **\n**                                                                                  **\n** For full license and copyright information, please refer to the LICENSE.md file  **\n** located at the project root, or contact the authors.                             **\n**                                                                                  **\n**~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/\n#include <petsc.h>\n#include <petscvec.h>\n#include <petscmat.h>\n#include <petscksp.h>\n#include <petscsnes.h>\n\n#include <petscversion.h>\n#if ( (PETSC_VERSION_MAJOR >= 3) && (PETSC_VERSION_MINOR >=3) )\n  #if (PETSC_VERSION_MINOR >=6)\n     #include \"petsc/private/vecimpl.h\"\n     #include \"petsc/private/matimpl.h\"\n     #include \"petsc/private/pcimpl.h\"\n     #include \"petsc/private/kspimpl.h\"\n     #include \"petsc/private/snesimpl.h\"\n  #else\n     #include \"petsc-private/vecimpl.h\"\n     #include \"petsc-private/matimpl.h\"\n     #include \"petsc-private/pcimpl.h\"\n     #include \"petsc-private/kspimpl.h\"\n     #include \"petsc-private/snesimpl.h\"\n  #endif\n#else\n  #include \"private/vecimpl.h\"\n  #include \"private/matimpl.h\"\n  #include \"private/pcimpl.h\"\n  #include \"private/kspimpl.h\"\n  #include \"private/snesimpl.h\"\n#endif\n\n\n\n#include \"common-driver-utils.h\"\n\n\n#define BSSCR_report_op(op,v,i,func_name) \\\n  if((op)) { PetscViewerASCIIPrintf((v), \"[%.2d] %s: valid operation \\n\", i, func_name ); } \\\n  else { PetscViewerASCIIPrintf((v),     \"[%.2d] %s: OPERATION NOT DEFINED \\n\", i, func_name ); } \\\n\n\nPetscErrorCode BSSCR_MatListOperations( Mat A, PetscViewer v )\n{\n\tMatOps ops = A->ops;\n\tMatType type;\n\tPetscInt i;\n\t\n\tMatGetType( A, &type );\n\tPetscViewerASCIIPrintf(v, \"Operations available for MatType: %s \\n\", type );\n\t\n\tPetscViewerASCIIPushTab( v );\n\t\n\ti=0;\n\tPetscViewerASCIIPrintf(v, \"------------------------------------------------\\n\");\n\tBSSCR_report_op( ops->setvalues, v,  i++, \"MatSetValues\" );\n\tBSSCR_report_op( ops->getrow, v,     i++, \"MatSetValues\" );\n\tBSSCR_report_op( ops->restorerow, v, i++, \"MatRestoreRow\" );\n\tBSSCR_report_op( ops->mult, v,       i++, \"MatMult\" );\n\tBSSCR_report_op( ops->multadd, v,    i++, \"MatMultAdd\" );\n\t\n\tBSSCR_report_op( ops->multtranspose, v,    i++, \"MatMultTranspose\" );\n\tBSSCR_report_op( ops->multtransposeadd, v, i++, \"MatMultTransposeAdd\" );\n\tBSSCR_report_op( ops->solve, v,            i++, \"MatSolve\" );\n\tBSSCR_report_op( ops->solveadd, v,         i++, \"MatSolveAdd\" );\n\tBSSCR_report_op( ops->solvetranspose, v,   i++, \"MatSolveTranspose\" );\n\t\n\tPetscViewerASCIIPrintf(v, \"------------------------------------------------\\n\");\n\tBSSCR_report_op( ops->solvetransposeadd, v,  i++, \"MatSolveTransposeAdd\" );\n\tBSSCR_report_op( ops->lufactor, v,           i++, \"MatLUFactor\" );\n\tBSSCR_report_op( ops->choleskyfactor, v,     i++, \"MatCholeskyFactor\" );\n#if( ( PETSC_VERSION_MAJOR >= 3 ) && ( PETSC_VERSION_MINOR > 0 ) )\n\tBSSCR_report_op( ops->sor, v,                i++, \"MatSor\" );\n#else\n\tBSSCR_report_op( ops->relax, v,              i++, \"MatRelax\" );\n#endif\n\tBSSCR_report_op( ops->transpose, v,          i++, \"MatTranspose\" );\n\t\n\tBSSCR_report_op( ops->getinfo, v,       i++, \"MatGetInfo\" );\n\tBSSCR_report_op( ops->equal, v,         i++, \"MatEqual\" );\n\tBSSCR_report_op( ops->getdiagonal, v,   i++, \"MatGetDiagonal\" );\n\tBSSCR_report_op( ops->diagonalscale, v, i++, \"MatDiagonalScale\" );\n\tBSSCR_report_op( ops->norm, v,          i++, \"MatNorm\" );\n\t\n\tPetscViewerASCIIPrintf(v, \"------------------------------------------------\\n\");\n\tBSSCR_report_op( ops->assemblybegin, v, i++, \"MatAssemblyBegin\" );\n\tBSSCR_report_op( ops->assemblyend, v,   i++, \"MatAssemblyEnd\" );\n#if( ( ( PETSC_VERSION_MAJOR == 3 ) && ( PETSC_VERSION_MINOR < 1 ) ) || ( PETSC_VERSION_MAJOR <= 2 ) )\n\tBSSCR_report_op( ops->compress, v,      i++, \"MatCompress\" );\n#endif\n\tBSSCR_report_op( ops->setoption, v,     i++, \"MatSetOption\" );\n\tBSSCR_report_op( ops->zeroentries, v,   i++, \"MatZeroEntries\" );\n\t\n\tBSSCR_report_op( ops->zerorows, v,               i++, \"Stg_MatZeroRows\" );\n\tBSSCR_report_op( ops->lufactorsymbolic, v,       i++, \"MatLUFactorSymbolic\" );\n\tBSSCR_report_op( ops->lufactornumeric, v,        i++, \"MatLUFactorNumeric\" );\n\tBSSCR_report_op( ops->choleskyfactorsymbolic, v, i++, \"MatCholeskyFactorSymbolic\" );\n\tBSSCR_report_op( ops->choleskyfactornumeric, v,  i++, \"MatCholeskyFactorNumeric\" );\n\t\n\tPetscViewerASCIIPrintf(v, \"------------------------------------------------\\n\");\n\n\tBSSCR_report_op( ops->ilufactorsymbolic, v,  i++, \"MatILUFactorSymbolic\" );\n\tBSSCR_report_op( ops->iccfactorsymbolic, v,  i++, \"MatICCFactorSymbolic\" );\n\n\n\t\n\tBSSCR_report_op( ops->duplicate, v,     i++, \"MatDuplicate\" );\n\tBSSCR_report_op( ops->forwardsolve, v,  i++, \"MatForwardSolve\" );\n\tBSSCR_report_op( ops->backwardsolve, v, i++, \"MatBackwardSolve\" );\n\tBSSCR_report_op( ops->ilufactor, v,     i++, \"MatILUFactor\" );\n\tBSSCR_report_op( ops->iccfactor, v,     i++, \"MatICCFactor\" );\n\t\n\tPetscViewerASCIIPrintf(v, \"------------------------------------------------\\n\");\n\tBSSCR_report_op( ops->axpy, v,            i++, \"MatAXPY\" );\n\n#if( (PETSC_VERSION_MAJOR == 3) &&  (PETSC_VERSION_MINOR > 7) )\n    BSSCR_report_op( ops->createsubmatrices, v,  i++, \"MatCreateSubMatrices\" );\n#else\n    BSSCR_report_op( ops->getsubmatrices, v,  i++, \"MatGetSubMatrices\" );\n#endif\n\n    BSSCR_report_op( ops->increaseoverlap, v, i++, \"MatIncreaseOverlap\" );\n\tBSSCR_report_op( ops->getvalues, v,       i++, \"MatGetValues\" );\n\tBSSCR_report_op( ops->copy, v,            i++, \"MatCopy\" );\n\t\n\tBSSCR_report_op( ops->getrowmax, v,   i++, \"MatGetRowMax\" );\n\tBSSCR_report_op( ops->scale, v,       i++, \"MatScale\" );\n\tBSSCR_report_op( ops->shift, v,       i++, \"MatShift\" );\n\tBSSCR_report_op( ops->diagonalset, v, i++, \"MatDiagonalSet\" );\n#if( ( ( PETSC_VERSION_MAJOR == 3 ) && ( PETSC_VERSION_MINOR < 1 ) ) || ( PETSC_VERSION_MAJOR <= 2 ) )\n\tBSSCR_report_op( ops->iludtfactor, v, i++, \"MatILUDTFactor\" );\n#endif\n\t\n\tPetscViewerASCIIPrintf(v, \"------------------------------------------------\\n\");\n\n\tBSSCR_report_op( ops->getrowij, v,        i++, \"MatGetRowIJ\" );\n\tBSSCR_report_op( ops->restorerowij, v,    i++, \"MatRestoreRowIJ\" );\n\tBSSCR_report_op( ops->getcolumnij, v,     i++, \"MatGetColumnIJ\" );\n\tBSSCR_report_op( ops->restorecolumnij, v, i++, \"MatRestoreColumnIJ\" );\n\t\n\tBSSCR_report_op( ops->fdcoloringcreate, v, i++, \"MatFDColoringCreate\" );\n\tBSSCR_report_op( ops->coloringpatch, v,    i++, \"MatColoringPatch\" );\n\tBSSCR_report_op( ops->setunfactored, v,    i++, \"MatSetUnFactored\" );\n\tBSSCR_report_op( ops->permute, v,          i++, \"MatPermute\" );\n\tBSSCR_report_op( ops->setvaluesblocked, v, i++, \"MatSetValuesBlocked\" );\n\t\n\tPetscViewerASCIIPrintf(v, \"------------------------------------------------\\n\");\n\n#if( (PETSC_VERSION_MAJOR == 3) &&  (PETSC_VERSION_MINOR > 7) )\n    BSSCR_report_op( ops->createsubmatrix, v,  i++, \"MatCreateSubMatrix\" );\n#else\n    BSSCR_report_op( ops->getsubmatrix, v,  i++, \"MatGetSubMatrix\" );\n#endif\n\n\tBSSCR_report_op( ops->destroy, v,       i++, \"MatDestroy\" );\n\tBSSCR_report_op( ops->view, v,          i++, \"MatView\" );\n\tBSSCR_report_op( ops->convertfrom, v,   i++, \"MatConvertFrom\" );\n\n\t\n\n\n\tBSSCR_report_op( ops->setlocaltoglobalmapping, v, i++, \"MatSetLocalToGlobalMapping\" );\n\tBSSCR_report_op( ops->setvalueslocal, v,          i++, \"MatSetValuesLocal\" );\n\tBSSCR_report_op( ops->zerorowslocal, v,           i++, \"Stg_MatZeroRowsLocal\" );\n\t\n\tPetscViewerASCIIPrintf(v, \"------------------------------------------------\\n\");\n\tBSSCR_report_op( ops->getrowmaxabs, v,    i++, \"MatGetRowMaxAbs\" );\n\tBSSCR_report_op( ops->convert, v,         i++, \"MatConvert\" );\n//    BSSCR_report_op( ops->setcoloring, v,     i++, \"MatSetColoring\" );  NOT SURE IF THIS IS AVAIL IN 3.8\n\n\tBSSCR_report_op( ops->setvaluesadifor, v, i++, \"MatSetValuesAdicfor\" );\n\t\n\tBSSCR_report_op( ops->fdcoloringapply, v,              i++, \"MatFDCloringApply\" );\n\tBSSCR_report_op( ops->setfromoptions, v,               i++, \"MatSetFromOptions\" );\n\tBSSCR_report_op( ops->multconstrained, v,              i++, \"MatMultConstrained\" );\n\tBSSCR_report_op( ops->multtransposeconstrained, v,     i++, \"MatMultTransposeConstrained\" );\n\t/* data member depreciated from PETSc v. 3.0.0 */\n#if( PETSC_VERSION_MAJOR <= 2 )\n\tBSSCR_report_op( ops->ilufactorsymbolicconstrained, v, i++, \"MatILUFactorSymbolicConstrained\" );\n#endif\t\n\tPetscViewerASCIIPrintf(v, \"------------------------------------------------\\n\");\n#if( ( ( PETSC_VERSION_MAJOR == 3 ) && ( PETSC_VERSION_MINOR < 2 ) ) )\n\tBSSCR_report_op( ops->permutesparsify, v, i++, \"MatPermuteSparsify\" );\n#endif\n\tBSSCR_report_op( ops->mults, v,           i++, \"MatMults\" );\n\tBSSCR_report_op( ops->solves, v,          i++, \"MatSolves\" );\n\tBSSCR_report_op( ops->getinertia, v,      i++, \"MatGetInertia\" );\n\tBSSCR_report_op( ops->load, v,            i++, \"MatLoad\" );\n\t\n\tBSSCR_report_op( ops->issymmetric, v,             i++, \"MatIsSymmetric\" );\n\tBSSCR_report_op( ops->ishermitian, v,             i++, \"MatIsHermitian\" );\n\tBSSCR_report_op( ops->isstructurallysymmetric, v, i++, \"MatIsStructurallySymmetric\" );\n#if( ( ( PETSC_VERSION_MAJOR == 3 ) && ( PETSC_VERSION_MINOR < 1 ) ) || ( PETSC_VERSION_MAJOR <= 2 ) )\n\tBSSCR_report_op( ops->pbrelax, v,                 i++, \"MatPBRelax\" );\n#endif\n\tBSSCR_report_op( ops->getvecs, v,                 i++, \"MatGetVec\" );\n\t\n\tPetscViewerASCIIPrintf(v, \"------------------------------------------------\\n\");\n\tBSSCR_report_op( ops->matmult, v,         i++, \"MatMatMult\" );\n\tBSSCR_report_op( ops->matmultsymbolic, v, i++, \"MatMatMultSymbolic\" );\n\tBSSCR_report_op( ops->matmultnumeric, v,  i++, \"MatMatMultNumeric\" );\n\tBSSCR_report_op( ops->ptap, v,            i++, \"MatPtAP\" );\n\tBSSCR_report_op( ops->ptapsymbolic, v,    i++, \"MatPtAPSymbolic\" );\n\t\n\tBSSCR_report_op( ops->ptapnumeric, v,              i++, \"MatPtAPNumeric\" );\n\n\n\n\n\t\n\tPetscViewerASCIIPrintf(v, \"------------------------------------------------\\n\");\n\n\n\n\tBSSCR_report_op( ops->conjugate, v,           i++, \"MatConjugate\" );\n\t//BSSCR_report_op( ops->setsizes, v,            i++, \"MatSetSizes\" );\n\t\n\tBSSCR_report_op( ops->setvaluesrow, v,              i++, \"MatSetValuesRow\" );\n\tBSSCR_report_op( ops->realpart, v,                  i++, \"MatRealPart\" );\n\tBSSCR_report_op( ops->imaginarypart, v,             i++, \"MatImaginaryPart\" );\n\tBSSCR_report_op( ops->getrowuppertriangular, v,     i++, \"MatGetRowUpperTriangular\" );\n\tBSSCR_report_op( ops->restorerowuppertriangular, v, i++, \"MatRestoreRowUpperTriangular\" );\n\t\n\tPetscViewerASCIIPrintf(v, \"------------------------------------------------\\n\");\n\tBSSCR_report_op( ops->matsolve, v,           i++, \"MatMatSolve\" );\n#if ( (PETSC_VERSION_MAJOR >= 3) && (PETSC_VERSION_MINOR <6) )\n\tBSSCR_report_op( ops->getredundantmatrix, v, i++, \"MatGetRedundantMatrix\" );\n#endif\n\tBSSCR_report_op( ops->getrowmin, v,          i++, \"MatGetRowMin\" );\n\tBSSCR_report_op( ops->getcolumnvector, v,    i++, \"MatGetColumnVector\" );\n\t\n\t\n\tPetscViewerASCIIPopTab( v );\n\t\n\tPetscFunctionReturn(0);\n}\n\n\nPetscErrorCode BSSCR_VecListOperations( Vec x, PetscViewer v )\n{\n\tVecOps ops = x->ops;\n\tVecType type;\n\tPetscInt i;\n\t\n\tVecGetType( x, &type );\n\tPetscViewerASCIIPrintf(v, \"Operations available for VecType: %s \\n\", type );\n\t\n\tPetscViewerASCIIPushTab( v );\n\t\n\t\n\t\n\tPetscViewerASCIIPopTab( v );\n\t\n\tPetscFunctionReturn(0);\n}\n\nPetscErrorCode BSSCR_KSPListOperations( KSP ksp, PetscViewer v )\n{\n\tKSPOps ops = ksp->ops;\n\tKSPType type;\n\tPetscInt i;\n\t\n\tKSPGetType( ksp, &type );\n\tPetscViewerASCIIPrintf(v, \"Operations available for KSPType: %s \\n\", type );\n\t\n\tPetscViewerASCIIPushTab( v );\n\t\n\ti=0;\n\tPetscViewerASCIIPrintf(v, \"------------------------------------------------\\n\");\n\tBSSCR_report_op( ops->buildsolution, v,  i++, \"KSPBuildSolution\" );\n\tBSSCR_report_op( ops->buildresidual, v,  i++, \"KSPBuildResidual\" );\n\tBSSCR_report_op( ops->solve, v,          i++, \"KSPSolve\" );\n\tBSSCR_report_op( ops->setup, v,          i++, \"KSPSetUp\" );\n\tBSSCR_report_op( ops->setfromoptions, v, i++, \"KSPSetFromOptions\" );\n\t\n\tBSSCR_report_op( ops->publishoptions, v,               i++, \"KSPPublishOptions\" );\n\tBSSCR_report_op( ops->computeextremesingularvalues, v, i++, \"KSPComputeExtremeSingularValues\" );\n\tBSSCR_report_op( ops->computeeigenvalues, v,           i++, \"KSPComputeEigenvalues\" );\n\tBSSCR_report_op( ops->destroy, v, i++, \"BSSCR_KSPDestroy\" );\n\tBSSCR_report_op( ops->view, v,    i++, \"KSPView\" );\n\t\n\tPetscViewerASCIIPopTab( v );\n\t\n\tPetscFunctionReturn(0);\n}\n\nPetscErrorCode BSSCR_PCListOperations( PC pc, PetscViewer v )\n{\n\tPCOps ops = pc->ops;\n\tPCType type;\n\tPetscInt i;\n\t\n\tPCGetType( pc, &type );\n\tPetscViewerASCIIPrintf(v, \"Operations available for PCType: %s \\n\", type );\n\t\n\tPetscViewerASCIIPushTab( v );\n\t\n\ti=0;\n\tPetscViewerASCIIPrintf(v, \"------------------------------------------------\\n\");\n\tBSSCR_report_op( ops->setup, v,           i++, \"PCSetUp\" );\n\tBSSCR_report_op( ops->apply, v,           i++, \"PCApply\" );\n\tBSSCR_report_op( ops->applyrichardson, v, i++, \"PCApplyRichardson\" );\n\tBSSCR_report_op( ops->applyBA, v,         i++, \"PCApplyBA\" );\n\tBSSCR_report_op( ops->applytranspose, v,  i++, \"PCApplyTranspose\" );\n\t\n\tBSSCR_report_op( ops->applyBAtranspose, v,  i++, \"PCApplyBATranspose\" );\n\tBSSCR_report_op( ops->setfromoptions, v,    i++, \"PCSetFromOptions\" );\n\tBSSCR_report_op( ops->presolve, v,          i++, \"PCPreSolve\" );\n\tBSSCR_report_op( ops->postsolve, v,         i++, \"PCPostSolve\" );\n\tBSSCR_report_op( ops->getfactoredmatrix, v, i++, \"PCGetFactoredMatrix\" );\n\t\n\t\n\tPetscViewerASCIIPrintf(v, \"------------------------------------------------\\n\");\n\tBSSCR_report_op( ops->applysymmetricleft, v,  i++, \"PCApplySymmetricLeft\" );\n\tBSSCR_report_op( ops->applysymmetricright, v, i++, \"PCApplySymmetricRight\" );\n\tBSSCR_report_op( ops->setuponblocks, v,       i++, \"PCSetupOnBlocks\" );\n\tBSSCR_report_op( ops->destroy, v,             i++, \"PCDestroy\" );\n\tBSSCR_report_op( ops->view, v,                i++, \"PCView\" );\n\t\n\t\n\tPetscViewerASCIIPopTab( v );\n\t\n\tPetscFunctionReturn(0);\n}\n\nPetscErrorCode BSSCR_SNESListOperations( SNES snes, PetscViewer v )\n{\n\tSNESOps ops = snes->ops;\n\tSNESType type;\n\tPetscInt i;\n\t\n\tSNESGetType( snes, &type );\n\tPetscViewerASCIIPrintf(v, \"Operations available for SNESType: %s \\n\", type );\n\t\n\tPetscViewerASCIIPushTab( v );\n\t\n\ti=0;\n\tPetscViewerASCIIPrintf(v, \"------------------------------------------------\\n\");\n\n\n\tBSSCR_report_op( ops->computescaling, v,  i++, \"SNESComputeScaling\" );\n\tBSSCR_report_op( ops->update, v,          i++, \"SNESUpdate\" );\n\tBSSCR_report_op( ops->converged, v,       i++, \"SNESConverged\" );\n\t\n\tBSSCR_report_op( ops->setup, v,           i++, \"SNESSetUp\" );\n\tBSSCR_report_op( ops->solve, v,           i++, \"SNESSolve\" );\n\tBSSCR_report_op( ops->view, v,            i++, \"SNESView\" );\n\tBSSCR_report_op( ops->setfromoptions, v,  i++, \"SNESSetFromOptions\" );\n\tBSSCR_report_op( ops->destroy, v,         i++, \"SNESDestroy\" );\n\t\n\tPetscViewerASCIIPopTab( v );\n\t\n\tPetscFunctionReturn(0);\n}\n", "meta": {"hexsha": "2632ac1401ba59fa5a4879cccf87f05a4556875d", "size": 15145, "ext": "c", "lang": "C", "max_stars_repo_path": "libUnderworld/Solvers/KSPSolvers/src/BSSCR/list_operations.c", "max_stars_repo_name": "jmansour/underworld2", "max_stars_repo_head_hexsha": "6da9f52268d366ae08533374afebb6f278c04576", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-28T20:00:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-28T20:00:12.000Z", "max_issues_repo_path": "libUnderworld/Solvers/KSPSolvers/src/BSSCR/list_operations.c", "max_issues_repo_name": "jmansour/underworld2", "max_issues_repo_head_hexsha": "6da9f52268d366ae08533374afebb6f278c04576", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libUnderworld/Solvers/KSPSolvers/src/BSSCR/list_operations.c", "max_forks_repo_name": "jmansour/underworld2", "max_forks_repo_head_hexsha": "6da9f52268d366ae08533374afebb6f278c04576", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.0694444444, "max_line_length": 106, "alphanum_fraction": 0.6038296467, "num_tokens": 4908, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1943678016853152, "lm_q2_score": 0.044680868364504835, "lm_q1q2_score": 0.00868452216139975}}
{"text": "#ifndef QUAC_P_H_\n#define QUAC_P_H_\n#include <petsc.h>\nextern int  petsc_initialized;\nPetscLogEvent add_lin_event,add_to_ham_event,add_lin_recovery_event,add_encoded_gate_to_circuit_event;\nPetscLogEvent _qc_event_function_event,_qc_postevent_function_event,_apply_gate_event;\nPetscClassId quac_class_id;\nPetscLogStage pre_solve_stage,solve_stage,post_solve_stage;\n#endif\n", "meta": {"hexsha": "a678252d48f1656044a75d86ac7cba3c0ab5fd83", "size": 371, "ext": "h", "lang": "C", "max_stars_repo_path": "src/quac_p.h", "max_stars_repo_name": "sgulania/QuaC", "max_stars_repo_head_hexsha": "2b47b378c6b5b823a094e9af79f7cb8eb39dd337", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2017-06-18T02:11:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-28T10:27:57.000Z", "max_issues_repo_path": "src/quac_p.h", "max_issues_repo_name": "sgulania/QuaC", "max_issues_repo_head_hexsha": "2b47b378c6b5b823a094e9af79f7cb8eb39dd337", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-07-17T15:16:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-03T14:21:56.000Z", "max_forks_repo_path": "src/quac_p.h", "max_forks_repo_name": "sgulania/QuaC", "max_forks_repo_head_hexsha": "2b47b378c6b5b823a094e9af79f7cb8eb39dd337", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2017-03-13T15:03:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T20:07:22.000Z", "avg_line_length": 37.1, "max_line_length": 102, "alphanum_fraction": 0.897574124, "num_tokens": 98, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.32423539898095244, "lm_q2_score": 0.026759285901963227, "lm_q1q2_score": 0.008676307740868423}}
{"text": "// -*- c++ -*-\n\n#if 1\n#include <string>\n#include <vector>\n#include <utility> // for std::pair\n#include <stdint.h>\n\n#include <iostream>\nclass Foo \n{\npublic:\n  static std::string GetName() { return \"Foo\"; }\n\n  Foo();\n  ~Foo();\n\n  void setDouble(double d) { m_d = d;}\n  void setDouble(double d, float x) { m_d = d+x;}\n  //void setFoo(const std::string &s) {std::cout << s << std::endl;}\n  void setFoo(const std::string &s=\"f\", double x=1) {std::cout << s << x << std::endl;}\n  void setInt(int i) { std::cout << i << std::endl;}\n  void setInt(long i, float x=2) {std::cout << i+x << std::endl;}\n  double getDouble() { return m_d; }\n\n  void setUint64(uint64_t v) { m_uint64 = v; }\n  uint64_t getUint64() { return m_uint64; }\n\n  std::vector<Foo> getCollection() { return std::vector<Foo>(1, *this); }\n  std::vector<std::vector<std::pair<int, int> > > getMatrix() { return std::vector<std::vector<std::pair<int,int> > >(); }\n\n  std::vector< int>::iterator getIterator() { return std::vector<int>().begin(); }\n\n  static void frobnicate() { std::cout << \"frobnicate\"; }\n  //void frobnicate() { std::cout << \"frobnicate -- non static\"; }\n\n  Foo operator+(const Foo& a) { return Foo(); }\n  Foo& operator+=(const Foo& a) { \n    this->m_d += a.m_d; \n    this->m_uint64 += a.m_uint64;\n    return *this;\n  }\n\n  Foo& operator=(const Foo& rhs) {\n    this->m_d = rhs.m_d;\n    this->m_uint64 = rhs.m_uint64;\n    return *this;\n  }\n\n  void save(std::ostream &out) { out << m_d << m_uint64; }\n  \n  double getme(double d) { return d; }\n  int    getme(int i) { return i; }\n  void   getme() const { return ; }\n  void   getme()       { return ; }\n\nprivate:\n  double m_d;\n  uint64_t m_uint64;\n};\n\nFoo::Foo()\n{}\n\nFoo::~Foo()\n{}\n\nclass IFoo \n{\npublic:\n\n  virtual\n  void virtual_meth() const {}\n\n  virtual\n  void pure_virtual_meth() const = 0;\n\n};\n\n//template class std::vector<Foo>;\nnamespace Math {\n  void do_hello() {\n    std::cout << \"helllo\" << std::endl;\n  }\n  double do_add(double i, double j=2) { return i+j; }\n  double do_add(int i, int j=2, int k=3, int l=4) { return i+j+k+l; }\n  double do_add() { return 42; }\n\n  const std::string& say_hello() { static std::string hi=\"hi\"; return hi;}\n\n  double adder(double i, double j) { return i+j; }\n}\n\nnamespace Math2 {\n  // std::string do_hello() {\n  //   return \"hi\";\n  // }\n  std::string do_hello(const std::string& name = \"you\") {\n    return std::string(\"hello \") + name;\n  }\n  std::string do_hello(const char* name) {\n    return std::string(\"hello -- \") + std::string(name);\n  }\n\n  std::string do_hello_c(const char* name) {\n    return std::string(\"hello -- \") + std::string(name);\n  }\n}\n\nnamespace NS {\n  class Bar {\n  public:\n    Bar() {}\n    void syHello() {\n      std::cout << \"hello\" << std::endl;\n    }\n  };\n\n  template<class F> F tmpl_fct() { return F(); }\n\n  template<> int tmpl_fct<int>() { return 42; }\n\n  template<int N> int tmpl_fct_n() { return N; }\n  template<> int tmpl_fct_n<42>() { return 42; }\n  template<> int tmpl_fct_n<-1>() { return -1; }\n}\n\nnamespace TT {\n  typedef int    foo_t;\n  typedef foo_t* bar_t;\n  typedef const bar_t baz_t;\n  //'int *'    'foo *'    'bar'\n}\n\n#endif\n\n#define BIT(n)       (1ULL << (n))\nenum MyEnum {\n  kValue = BIT(2)\n};\n\ntypedef int            Ssiz_t;      //String size (int)\nstruct LongStr_t\n{\n  Ssiz_t    fCap;    // Max string length (including null)\n  Ssiz_t    fSize;   // String length (excluding null)\n  char     *fData;   // Long string data\n};\n\nenum Enum0 { \n  kMinCap = (sizeof(LongStr_t) - 1)/sizeof(char) <= 2 ?\n            2 : (sizeof(LongStr_t) - 1)/sizeof(char),\n  kMin1 = 1 >= 2 ? 1 : 2\n};\n\ntypedef void (*Func_t)();\n\nclass TVersionCheck {\npublic:\n   TVersionCheck(int versionCode);  // implemented in TSystem.cxx\n};\n\n//static TVersionCheck gVersionCheck(335360);\n//#define ROOT_VERSION_CODE 335360\n//static TVersionCheck gVersionCheck = ROOT_VERSION_CODE;\n\nclass EnumNs\n{\npublic:\n   enum ESTLtype { kSTL       = 300 /* TVirtualStreamerInfo::kSTL */, \n                   kSTLbitset =  8\n   };\n   // TStreamerElement status bits\n   enum {\n      kHasRange     = BIT(6),\n      kCache        = BIT(9),\n      kRepeat       = BIT(10),\n      kRead         = BIT(11),\n      kWrite        = BIT(12),\n      kDoNotDelete  = BIT(13)\n   };\n  \n};\n\n\nclass Base\n{\npublic:\n  virtual void initialize() = 0;\n};\n\nclass Base2\n{\npublic:\n  virtual void execute() = 0;\n};\n\nclass Alg : public Base, virtual public Base2\n{\npublic:\n  virtual void initialize() { std::cout << \"::initialize();\\n\"; }\n  virtual void execute() { std::cout << \"::execute();\\n\"; }\n};\n\n\nclass WithPrivateBase: public Base, private Base2\n{\npublic:\n  virtual void initialize() { std::cout << \"::initialize();\\n\"; }\n  virtual void execute() { std::cout << \"::execute();\\n\"; }\n\n  WithPrivateBase() {}\n  WithPrivateBase(int /*i*/) {}\n\n  Enum0 myenum;\n\n  operator double() { return myenum; }\n\n  enum Enum1 { \n    kMinCap = (sizeof(LongStr_t) - 1)/sizeof(char) <= 2 ?\n              2 : (sizeof(LongStr_t) - 1)/sizeof(char),\n    kMin1 = 1 >= 2 ? 1 : 2\n  };\n\nprivate:\n  void some_private_method() { std::cout << \"::private()\\n\"; }\n};\n\n// #include <cblas.h>\n", "meta": {"hexsha": "9b76fd61a39811d85ba17e06b0c9a59af2675040", "size": 5089, "ext": "h", "lang": "C", "max_stars_repo_path": "example/mylib.h", "max_stars_repo_name": "sbinet/go-cxxdict", "max_stars_repo_head_hexsha": "538632c38965335a9043e4b8dc7ca56533f54a5b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-07-25T12:07:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-22T10:09:38.000Z", "max_issues_repo_path": "example/mylib.h", "max_issues_repo_name": "sbinet/go-cxxdict", "max_issues_repo_head_hexsha": "538632c38965335a9043e4b8dc7ca56533f54a5b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/mylib.h", "max_forks_repo_name": "sbinet/go-cxxdict", "max_forks_repo_head_hexsha": "538632c38965335a9043e4b8dc7ca56533f54a5b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-07-22T05:52:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-21T22:54:06.000Z", "avg_line_length": 22.1260869565, "max_line_length": 122, "alphanum_fraction": 0.5893102771, "num_tokens": 1576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24508501313237174, "lm_q2_score": 0.03514484614814642, "lm_q1q2_score": 0.008613475079753649}}
{"text": "#ifndef _SPC_DRIZ_H\n#define _SPC_DRIZ_H\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <gsl/gsl_vector.h>\n\ndouble sgarea(double x1, double y1, double x2, double y2, int is, int js);\ndouble boxer(int is,int js,double *x,double *y);\n\n\n#endif\n", "meta": {"hexsha": "661bf04bc41dfe17bd8b994dd0721691781f3895", "size": 280, "ext": "h", "lang": "C", "max_stars_repo_path": "cextern/src/spc_driz.h", "max_stars_repo_name": "sosey/pyaxe", "max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cextern/src/spc_driz.h", "max_issues_repo_name": "sosey/pyaxe", "max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cextern/src/spc_driz.h", "max_forks_repo_name": "sosey/pyaxe", "max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.6666666667, "max_line_length": 74, "alphanum_fraction": 0.7214285714, "num_tokens": 85, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3522017684487511, "lm_q2_score": 0.024423090142868222, "lm_q1q2_score": 0.00860185553930145}}
{"text": "#ifndef OPENMC_TALLIES_FILTER_H\n#define OPENMC_TALLIES_FILTER_H\n\n#include <cstdint>\n#include <string>\n#include <unordered_map>\n\n#include \"pugixml.hpp\"\n#include <gsl/gsl>\n\n#include \"openmc/constants.h\"\n#include \"openmc/hdf5_interface.h\"\n#include \"openmc/memory.h\"\n#include \"openmc/particle.h\"\n#include \"openmc/tallies/filter_match.h\"\n#include \"openmc/vector.h\"\n\nnamespace openmc {\n\n//==============================================================================\n//! Modifies tally score events.\n//==============================================================================\n\nclass Filter\n{\npublic:\n  //----------------------------------------------------------------------------\n  // Constructors, destructors, factory functions\n\n  Filter();\n  virtual ~Filter();\n\n  //! Create a new tally filter\n  //\n  //! \\tparam T Type of the filter\n  //! \\param[in] id  Unique ID for the filter. If none is passed, an ID is\n  //!    automatically assigned\n  //! \\return Pointer to the new filter object\n  template<typename T>\n  static T* create(int32_t id = -1);\n\n  //! Create a new tally filter\n  //\n  //! \\param[in] type  Type of the filter\n  //! \\param[in] id  Unique ID for the filter. If none is passed, an ID is\n  //!    automatically assigned\n  //! \\return Pointer to the new filter object\n  static Filter* create(const std::string& type, int32_t id = -1);\n\n  //! Create a new tally filter from an XML node\n  //\n  //! \\param[in] node XML node\n  //! \\return Pointer to the new filter object\n  static Filter* create(pugi::xml_node node);\n\n  //! Uses an XML input to fill the filter's data fields.\n  virtual void from_xml(pugi::xml_node node) = 0;\n\n  //----------------------------------------------------------------------------\n  // Methods\n\n  virtual std::string type() const = 0;\n\n  //! Matches a tally event to a set of filter bins and weights.\n  //!\n  //! \\param[in] p Particle being tracked\n  //! \\param[in] estimator Tally estimator being used\n  //! \\param[out] match will contain the matching bins and corresponding\n  //!   weights; note that there may be zero matching bins\n  virtual void\n  get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match) const = 0;\n\n  //! Writes data describing this filter to an HDF5 statepoint group.\n  virtual void\n  to_statepoint(hid_t filter_group) const\n  {\n    write_dataset(filter_group, \"type\", type());\n    write_dataset(filter_group, \"n_bins\", n_bins_);\n  }\n\n  //! Return a string describing a filter bin for the tallies.out file.\n  //\n  //! For example, an `EnergyFilter` might return the string\n  //! \"Incoming Energy [0.625E-6, 20.0)\".\n  virtual std::string text_label(int bin) const = 0;\n\n  //----------------------------------------------------------------------------\n  // Accessors\n\n  //! Get unique ID of filter\n  //! \\return Unique ID\n  int32_t id() const { return id_; }\n\n  //! Assign a unique ID to the filter\n  //! \\param[in]  Unique ID to assign. A value of -1 indicates that an ID should\n  //!   be automatically assigned\n  void set_id(int32_t id);\n\n  //! Get number of bins\n  //! \\return Number of bins\n  int n_bins() const { return n_bins_; }\n\n  gsl::index index() const { return index_; }\n\n  //----------------------------------------------------------------------------\n  // Data members\n\nprotected:\n  int n_bins_;\nprivate:\n  int32_t id_ {C_NONE};\n  gsl::index index_;\n};\n\n//==============================================================================\n// Global variables\n//==============================================================================\n\nnamespace model {\n  extern \"C\" int32_t n_filters;\n  extern std::unordered_map<int, int> filter_map;\n  extern vector<unique_ptr<Filter>> tally_filters;\n}\n\n//==============================================================================\n// Non-member functions\n//==============================================================================\n\n//! Make sure index corresponds to a valid filter\nint verify_filter(int32_t index);\n\n} // namespace openmc\n#endif // OPENMC_TALLIES_FILTER_H\n", "meta": {"hexsha": "9620632a340dfe7869b01b85a6afeb14be45eece", "size": 4018, "ext": "h", "lang": "C", "max_stars_repo_path": "include/openmc/tallies/filter.h", "max_stars_repo_name": "cjwyett/openmc", "max_stars_repo_head_hexsha": "a9e85f4d5b59d133c17caccf4704a032184841d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-02-07T20:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-07T20:23:33.000Z", "max_issues_repo_path": "include/openmc/tallies/filter.h", "max_issues_repo_name": "cjwyett/openmc", "max_issues_repo_head_hexsha": "a9e85f4d5b59d133c17caccf4704a032184841d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-05-22T07:57:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-21T17:34:35.000Z", "max_forks_repo_path": "include/openmc/tallies/filter.h", "max_forks_repo_name": "cjwyett/openmc", "max_forks_repo_head_hexsha": "a9e85f4d5b59d133c17caccf4704a032184841d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9850746269, "max_line_length": 90, "alphanum_fraction": 0.5542558487, "num_tokens": 875, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18952109132967757, "lm_q2_score": 0.04535258023172813, "lm_q1q2_score": 0.008595270500133877}}
{"text": "/* Xrecon.h */\n/*---------------------------------------------------------------------------*/\n/*                                                                           */\n/* Xrecon.h: Global includes and defines                                     */\n/*                                                                           */\n/* Copyright (C) 2012 Paul Kinchesh                                          */\n/*               2012 Martyn Klassen                                         */\n/*               2012 Margaret Kritzer                                       */\n/*                                                                           */\n/* This file is part of Xrecon.                                              */\n/*                                                                           */\n/* Xrecon is free software: you can redistribute it and/or modify            */\n/* it under the terms of the GNU General Public License as published by      */\n/* the Free Software Foundation, either version 3 of the License, or         */\n/* (at your option) any later version.                                       */\n/*                                                                           */\n/* Xrecon is distributed in the hope that it will be useful,                 */\n/* but WITHOUT ANY WARRANTY; without even the implied warranty of            */\n/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the              */\n/* GNU General Public License for more details.                              */\n/*                                                                           */\n/* You should have received a copy of the GNU General Public License         */\n/* along with Xrecon. If not, see <http://www.gnu.org/licenses/>.            */\n/*                                                                           */\n/*---------------------------------------------------------------------------*/\n/*\f*/\n\n\n/*--------------------------------------------------------*/\n/*---- Wrap the header to prevent multiple inclusions ----*/\n/*--------------------------------------------------------*/\n#ifndef _H_Xrecon_H\n#define _H_Xrecon_H\n\n\n/*------------------------------------------------------------*/\n/*---- If C++ compiler is used it needs to know this is C ----*/\n/*------------------------------------------------------------*/\n//#ifdef __cplusplus\n//extern \"C\" {\n//#endif\n\n/*----------------------------------*/\n/*---- Include standard headers ----*/\n/*----------------------------------*/\n#include <stdio.h>\n#include <math.h>\n#include <string.h>\n#include <stdlib.h>\n#include <sys/param.h>\n#include <sys/stat.h>\n#include <stddef.h>\n#include <sys/time.h>\n#include <sys/types.h>\n#include <unistd.h>\n#include <signal.h>\n\n\n/*-----------------------------*/\n/*---- Include GSL Headers ----*/\n/*-----------------------------*/\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_complex_math.h>\n#include <gsl/gsl_sf_bessel.h>\n\n\n/*-----------------------------*/\n/*---- Include fftw header ----*/\n/*-----------------------------*/\n#include <fftw3.h>\n\n\n/*--------------------------------*/\n/*---- Include complex header ----*/\n/*--------------------------------*/\n/* NB If you have a C compiler, such as gcc, that supports the recent C99 standard,\n   and you #include <complex.h> before <fftw3.h>, then fftw_complex is the native\n   double-precision complex type and you can manipulate it with ordinary arithmetic.\n   Otherwise, FFTW defines its own complex type, which is bit-compatible with the\n   C99 complex type. */\n/* We will wait for C99 standard to become a bit more standard */\n//#include <complex.h>\n\n#ifdef DOTIFF\n/*---------------------------------*/\n/*---- Include tiff I/O header ----*/\n/*---------------------------------*/\n#include <tiffio.h>\n#endif\n\n\n/*------------------------------------------*/\n/*---- Include Varian data file handler ----*/\n/*------------------------------------------*/\n#include \"data.h\"\n\n\n/*-------------------------------------------*/\n/*---- Make sure __FUNCTION__ is defined ----*/\n/*-------------------------------------------*/\n#ifndef __FUNCTION__\n#define __FUNCTION__ __func__\n#endif\n\n\n/*------------------------------*/\n/*---- Include bool headers ----*/\n/*------------------------------*/\n#ifdef _STDC_C99\n#include <stdbool.h>\n#else\n#ifndef bool\n#define bool int\n#endif\n#ifndef true\n#define true 1\n#endif\n#ifndef false\n#define false 0\n#endif\n#endif\n\n\n/*----------------------------*/\n/*---- Some basic defines ----*/\n/*----------------------------*/\n#define TRUE       1\n#define FALSE      0\n#define ACTIVE     1\n#define NACTIVE    0\n#define NACQ       2\n\n/* image scaling */\n#define FFT_SCALE 0.5e-6\n\n\n/*-------------------------*/\n/*---- Some data types ----*/\n/*-------------------------*/\n#define INT16      1  /* 16 bit integer */\n#define INT32      2  /* 32 bit integer */\n#define FLT32      3  /* 32 bit float */\n#define DBL64      4  /* 64 bit double */\n\n\n/*-------------------------*/\n/*---- Some data modes ----*/\n/*-------------------------*/\n#define NONE       0  /* No data */\n#define FID        1  /* Raw */\n#define IMAGE      2  /* Image */\n#define RE         3  /* Real */\n#define IM         4  /* Imaginary */\n#define MG         5  /* Magnitude */\n#define PH         6  /* Phase */\n#define CX         7  /* Complex */\n#define STD        8  /* Standard */\n#define READ       9  /* Read */\n#define PHASE     10  /* Phase */\n#define PHASE2    11  /* 2nd Phase */\n#define REF       12  /* Reference */\n#define REFREAD   13  /* Reference Read */\n#define REFPHASE  14  /* Reference Phase */\n#define REFPHASE2 15  /* Reference Phase 2 */\n#define MK        16  /* Mask */\n#define MKREAD    17  /* Mask Read */\n#define MKPHASE   18  /* Mask Phase */\n#define MKPHASE2  19  /* Mask Phase 2 */\n#define RMK       20  /* Reverse Mask of magnitude */\n#define MKROI     21  /* Mask ROI */\n#define SM        22  /* Sensitivity map */\n#define SMREAD    23  /* Sensitivity Map Read */\n#define SMPHASE   24  /* Sensitivity Map Phase */\n#define SMPHASE2  25  /* Sensitivity Map Phase 2 */\n#define GF        26  /* Geometry Factor */\n#define RS        27  /* Relative SNR */\n#define EPIREF    28  /* EPI reference */\n#define VJ        29  /* Defined by VnmrJ parameters */\n#define SPATIAL   30  /* for csi */\n#define SPECTRAL  31  /* for csi */\n#define SPATSPECT 32  /* for csi */\n#define PHASE3    33  /* for 3D CSI */\n\n\n/*---------------------------------------------------------*/\n/*---- Some data status bits (0-15) for each dimension ----*/\n/*---------------------------------------------------------*/\n#define DATA     0x1  /* 0 = no data, 1= data */\n#define SHIFT    0x2  /* 0 = no shift, 1 = shift */\n#define ZEROFILL 0x4  /* 0 = no zerofill, 1 = zerofill */\n#define FFT      0x8  /* 0 = no FFT, 1 = FFT */\n/* Bits 4-15 are currently unused */\n\n\n/*-----------------------------*/\n/*---- Some sequence modes ----*/\n/*-----------------------------*/\n/* For 1D */\n#define IM1D      100\n#define IM0DCSI   101  /* single voxel csi */\n\n/* For 2D multislice 200 < seqmode < 300 */\n#define IM2D      200\n#define IM2DCC    201  /* seqcon = \"*ccnn\" */\n#define IM2DCS    202  /* seqcon = \"*csnn\" */\n#define IM2DSC    203  /* seqcon = \"*scnn\" */\n#define IM2DSS    204  /* seqcon = \"*ssnn\" */\n#define IM2DCCFSE 205  /* apptype = \"im2Dfse\", seqcon = \"nccnn\" */\n#define IM2DCSFSE 206  /* apptype = \"im2Dfse\", seqcon = \"ncsnn\" */\n#define IM2DSCFSE 207  /* apptype = \"im2Dfse\", seqcon = \"nscnn\" */\n#define IM2DSSFSE 208  /* apptype = \"im2Dfse\", seqcon = \"nssnn\" */\n#define IM2DEPI   209  /* apptype = \"im2Depi\" */\n#define IM1DCSI   210  /* csi has one extra dimension */\n\n#define IM2DCCLL  211  /* looklocker seqcon = \"*ccnn\" */\n#define IM2DCSLL  212  /* looklocker seqcon = \"*csnn\" */\n#define IM2DSCLL  213  /* looklocker seqcon = \"*scnn\" */\n#define IM2DSSLL  214  /* looklocker seqcon = \"*ssnn\" */\n\n\n/* For 3D 300 < seqmode < 400 */\n#define IM3D      300\n#define IM3DCC    301  /* seqcon = \"**ccn\" */\n#define IM3DCS    302  /* seqcon = \"**csn\" */\n#define IM3DSC    303  /* seqcon = \"**scn\" */\n#define IM3DSS    304  /* seqcon = \"**ssn\" */\n#define IM3DCFSE  305  /* apptype = \"im3Dfse\", seqcon = \"ncccn\" */\n#define IM3DSFSE  306  /* apptype = \"im3Dfse\", seqcon = \"nccsn\" */\n#define IM2DCSCSI   307  /* apptype = \"im2DCSI\", seqcon = \"nncsn\" */\n#define IM2DSCCSI   308  /* apptype = \"im2DCSI\", seqcon = \"nnscn\" */\n#define IM2DSSCSI   309  /* apptype = \"im2DCSI\", seqcon = \"ncssn\" */\n#define IM2DCCCSI   310  /* apptype = \"im2DCSI\", seqcon = \"nnccn\" */\n\n/* For 4D */\n#define IM4D      400\n#define IM3DCCCCSI   401  /* csi has one extra dimension */\n#define IM3DCCSCSI   402\n#define IM3DCSCCSI   403\n#define IM3DCSSCSI   404\n#define IM3DSCCCSI   405\n#define IM3DSCSCSI   406\n#define IM3DSSCCSI   407\n#define IM3DSSSCSI   408\n\n /* max dimensions */\n#define MAXDIM    500\n\n/*-------------------------*/\n/*---- For TIF scaling ----*/\n/*-------------------------*/\n#define NSCALE     0  /* Don't scale data */\n#define SCALE     -1  /* Scale to maximum of data in each volume */\n#define NOISE     -2  /* Scale to see noise */\n\n\n/*--------------------------------*/\n/*---- For NIFTI-1/Analyze7.5 ----*/\n/*--------------------------------*/\n#define NIFTI      1  /* NIFTI-1 format */\n#define ANALYZE    2  /* Analyze7.5 format */\n\n\n/*---------------------------------------------------------------------------*/\n/* Modes for DC correction using dbh.lvl and dbh.tlt in getvol(d,index,mode) */\n/*---------------------------------------------------------------------------*/\n#define NDCC       0  /* No DC correction using dbh.lvl and dbh.tlt */\n#define DCC        1  /* DC correction using dbh.lvl and dbh.tlt */\n\n\n/*-----------------------------------------------------------------------------------------*/\n/* Modes for writing raw data in wrawbin3D(struct data *d,int mode,int type,int precision) */\n/*-----------------------------------------------------------------------------------------*/\n#define D1         1  /* 1D data mode, data[nr][dim3][dim1] */\n#define D12        2  /* 2D/3D data mode, data[nr][dim3][dim2*dim1] */\n#define D3         3  /* 3D block processing mode, data[nr][dim2*dim1][dim3] */\n\n\n/*-------------------*/\n/*---- Constants ----*/\n/*-------------------*/\n#ifndef M_PI\n#define M_PI 3.14159265358979323846 /* pi */\n#endif\n#define DEG2RAD 0.017453292         /* convert degrees to radians */\n#define MAXRCVRS 2048               /* maximum number of receivers */\n\n\n/*------------------------------------------------------*/\n/*---- Floating point comparison macros (as in SGL) ----*/\n/*------------------------------------------------------*/\n/* EPSILON is the largest allowable deviation due to floating point storage */\n#define EPSILON 1e-9\n#define FP_LT(A,B)  (((A)<(B)) && (fabs((A)-(B))>EPSILON))  /* A less than B */\n#define FP_GT(A,B)  (((A)>(B)) && (fabs((A)-(B))>EPSILON))  /* A greater than B */\n#define FP_EQ(A,B)  (fabs((A)-(B))<=EPSILON)                /* A equal to B */\n#define FP_NEQ(A,B) (!FP_EQ(A,B))                           /* A not equal to B */\n#define FP_GTE(A,B) (FP_GT(A,B) || FP_EQ(A,B))              /* A greater than or equal to B */\n#define FP_LTE(A,B) (FP_LT(A,B) || FP_EQ(A,B))              /* A less than or equal to B */\n\n\n/*-------------------------------------------------------*/\n/*---- So we can simply include Xrecon.h in Xrecon.c ----*/\n/*-------------------------------------------------------*/\n#ifdef LOCAL\n#define EXTERN\n#else\n#define EXTERN extern\n#endif\n\n\nint interupt;  // for killing the process\n\n/*-------------------------------------------*/\n/*---- Structure to hold input filenames ----*/\n/*-------------------------------------------*/\nstruct file\n{\n  int      nfiles;    /* number of files */\n  char     **fid;     /* fid files */\n  char     **procpar; /* procpar files */\n};\n\n\n/*------------------------------------------------*/\n/*---- Structure to hold 'procpar' parameters ----*/\n/*------------------------------------------------*/\nstruct pars\n{\n  int      npars;   /* number of parameters in structure */\n  char     **name;  /* parameter name */\n  int      *type;   /* parameter type */\n  int      *active; /* parameter state */\n  int      *nvals;  /* number of values of parameters */\n  int      **i;     /* integer values */\n  double   **d;     /* real values */\n  char     ***s;    /* strings */\n};\n\n\n/*---------------------------------------------------------*/\n/*---- Structure to hold maximum value and coordinates ----*/\n/*---------------------------------------------------------*/\nstruct max\n{\n  int      data;    /* Data flag 0/FALSE=no data, or 1/TRUE=data */\n  double   Mval;    /* Maximum magnitude value */\n  double   Rval;    /* Maximum real value */\n  double   Ival;    /* Maximum imaginary value */\n  int      np;      /* position of maximum along np */\n  int      nv;      /* position of maximum along nv */\n  int      nv2;     /* position of maximum along nv2 */\n  int      nv3;     /* position of maximum along nv3 */\n};\n\n\n/*----------------------------------------------*/\n/*---- Structure to hold noise measurements ----*/\n/*----------------------------------------------*/\nstruct noise\n{\n  int      data;    /* Data flag 0/FALSE=no data, or 1/TRUE=data */\n  int      zero;    /* Zero data flag 0/FALSE=noise data not zero, or 1/TRUE=noise data is zero */\n  int      equal;   /* Equalize flag 0/FALSE=not equal, or 1/TRUE=equal */\n  int      samples; /* Number of noise samples */\n  double   *M;      /* Mean magnitude */\n  double   *M2;     /* Mean magnitude^2 */\n  double   *Re;     /* Mean real */\n  double   *Im;     /* Mean imaginary */\n  double   avM;     /* Averaged over all receivers */\n  double   avM2;    /* Averaged over all receivers */\n  double   avRe;    /* Averaged over all receivers */\n  double   avIm;    /* Averaged over all receivers */\n  gsl_matrix_complex   **mat;    /* Noise matrix */\n};\n\n\n/*--------------------------------*/\n/*---- Structure to hold data ----*/\n/*--------------------------------*/\nstruct data\n{\n  FILE                    *fp;         /* fid file pointer */\n  FILE                    *datafp;     /* data file pointer */\n  FILE                    *phasfp;     /* phasefile file pointer */\n  FILE                    *fidfp;      /* for writing in fid format */\n  char                    *file;       /* fid file */\n  char                    *procpar;    /* procpar file */\n  struct datafilehead     fh;          /* data file header */\n  struct datablockhead    bh;          /* data block header */\n  struct hypercmplxbhead  hcbh;        /* hypercomplex block header */\n  struct stat             buf;         /* data file info */\n\n  int                     nvols;       /* number of volumes at end of expt */\n  int                     startvol;    /* start volume for processing */\n  int                     endvol;      /* end volume for processing */\n  int                     vol;         /* current volume counter */\n  int                     outvol;      /* output volume (not counting reference volumes) */\n\n  int                     nblocks;     /* number of blocks */\n  int                     startpos;    /* start position of block for processing */\n  int                     endpos;      /* end position of block for processing */\n  int                     block;       /* current block counter */\n\n  int                     np,nv,nv2,nv3; /* number of points and views including nv3 for CSI */\n  int                     nseg,etl;    /* number of segments and echo train length */\n  int                     ne;          /* number of echoes */\n  int                     fn,fn1,fn2,fn3;  /* zerofilling */\n  int                     nr,ns;       /* number of receivers and slices */\n  int                     korder;       /* for csi, indicates elliptical or otherwise acquired */\n  int                     synclist[3];  /* indicates which dimensions are part of sync'ed lists such as pelist, pe2list, etc. */\n  int                     startd1, startd2, startd3;  // for csi cropping\n  int                     cropd1, cropd2, cropd3;     // for csi cropping\n\n  int                     profile;     /* profile flag, 0/FALSE=not profile, 1/TRUE=profile */\n  int                     proj2D;      /* 2D projection flag, 0/FALSE=not 2D projection, 1/TRUE=2D projection */\n\n  int                     nav;         /* navigator flag, 0/FALSE=none, 1/TRUE=navigators */\n  int                     nnav;        /* number of navigators */\n  int                     *navpos;     /* position(s) of navigator data amongst actual data */\n\n  int                     seqmode;     /* sequence mode depends on seqcon and apptype */\n\n  int                     *dim2order;  /* dim2 order in fid file */\n  int                     *dim3order;  /* dim3 order in fid file */\n  int                     *dim4order;  /* dim4 order in fid file */\n  int                     *pssorder;   /* slice order in fid file */\n\n  int                     *dim2orderR; /* Table for reduced dim2 order */\n  int                     *dim3orderR; /* Table for reduced dim3 order */\n  int                     *dim4orderR; /* Table for reduced dim4 order */\n  int                     dim2R,dim3R, dim4R; /* Size of dim2 and dim3 and dim4 BEFORE reduction */\n  int\t\t\t\t\t  d1rev, d2rev, d3rev; /* flag for csi dimension reversal */\n\n  fftw_complex            ***data;     /* actual data */\n  fftw_complex\t          **csi_data; /* different organization */\n  int                     **mask;      /* data mask */\n\n  int                     ndim;        /* number of data dimensions */\n  int                     *dimstatus;  /* status of each dimension */\n\n  int                     datamode;    /* data mode to flag different types of data, eg. see default EPI recon */\n\n  struct max              max;         /* maximum value and coordinates */\n  struct noise            noise;       /* noise measurement data */\n\n  struct pars             p;           /* 'procpar' parameters */\n  struct pars             a;           /* 'array' parameters */\n  struct pars             s;           /* 'sviblist' parameters */\n\n  char                    *fdfhdr;     /* fdf header */\n};\n\n\n/*-------------------------------------*/\n/*---- Structure to hold dimstatus ----*/\n/*-------------------------------------*/\nstruct dimstatus\n{\n  int ndim;        /* number of data dimensions */\n  int *dimstatus;  /* status of each dimension */\n};\n\n\n/*-------------------------------------------------*/\n/*---- Structure to hold segment scaling (EPI) ----*/\n/*-------------------------------------------------*/\nstruct segscale\n{\n  int data;\n  double ***value;\n};\n\n\n/*------------------------------*/\n/*---- Main recon functions ----*/\n/*------------------------------*/\nvoid recon1D(struct data *d);    /* recon1D.c */\nvoid recon2D(struct data *d);    /* recon2D.c */\nvoid reconEPI(struct data *d);   /* reconEPI.c */\nvoid recon3D(struct data *d);    /* recon3D.c */\nvoid recon2DCSI(struct data *d);\n\n\n/*---------------------------------*/\n/*---- Default recon functions ----*/\n/*---------------------------------*/\nvoid default1D(struct data *d);     /* default1D.c */\nvoid default2D(struct data *d);     /* default2D.c */\nvoid defaultEPI(struct data *d);    /* defaultEPI.c */\nvoid default3D(struct data *d);     /* default3D.c */\n\n\n/*-------------------------------*/\n/*---- default1D.c functions ----*/\n/*-------------------------------*/\nvoid refcorr1D(struct data *d,struct data *ref);\nvoid combine1D(struct data *d);\n\n\n/*-------------------------------*/\n/*---- profile1D.c functions ----*/\n/*-------------------------------*/\nvoid profile1D(struct data *d);\n\n\n/*----------------------------*/\n/*---- proj2D.c functions ----*/\n/*----------------------------*/\nvoid proj2D(struct data *d);\n\n\n/*------------------------*/\n/*---- CSI  functions ----*/\n/*------------------------*/\nvoid reconCSI(struct data *d);\nvoid reconCSI2D(struct data *d);\nvoid reconCSI3D(struct data *d);\nvoid dimorderCSI2D(struct data *d);\nvoid dimorderCSI3D(struct data *d);\nvoid getblockCSI2D(struct data *d,int volindex,int DCCflag);\nvoid getblockCSI3D(struct data *d,int volindex,int DCCflag);\nvoid w2DCSI(struct data *d,int receiver,int d4, int d3, int d2,int fileid);\nvoid wdfhCSI(struct data *d,int fileid);\nvoid zerofill2DCSI(struct data *d, int mode);\nvoid phaseramp2DCSI(struct data *d, int d4index, int mode);\nvoid shiftdim3dataCSI(struct data *d,int shft);\nvoid phaserampdim3CSI(struct data *d, int mode);\nvoid regridEPSI(struct data *d);\n\n\n/*----------------------------*/\n/*---- mask2D.c functions ----*/\n/*----------------------------*/\nvoid mask2D(struct data *d);\nvoid add2mask2D(struct data *d);\nint read2Dmask(struct data *d,int mode);\nvoid mask2Ddata(struct data *d1,struct data *d2);\n\n\n/*-----------------------------*/\n/*---- sense2D.c functions ----*/\n/*-----------------------------*/\nvoid sense2D(struct data *d);\nvoid sense2Dunfold(struct data *d,struct data *ref);\nvoid svd2Dinmem(struct data *ref);\nvoid setref2Dmatrix(struct data *ref,struct data *d);\nint checksenseref(struct data *d,struct data *ref);\n\n\n/*-----------------------------*/\n/*---- sensi2D.c functions ----*/\n/*-----------------------------*/\nvoid sensibility2D(struct data *d);\nvoid gmap2D(struct data *d);\n\n\n/*----------------------------*/\n/*---- smap2D.c functions ----*/\n/*----------------------------*/\nvoid smap2D(struct data *d,int mode);\nint smap2Dvcoil(struct data *d,struct data *ref,int mode);\nint smap2Dacoil(struct data *d,int mode);\nint setvcoil2D(struct data *d,struct data *ref,struct file *fref);\nvoid gen2Dsmapsos(struct data *d);\nvoid gen2Dsmapsuper(struct data *d);\nvoid gen2Dsmapvcoil(struct data *d,struct data *ref);\n\n\n/*-------------------------------*/\n/*---- asltest2D.c functions ----*/\n/*-------------------------------*/\nvoid asltest2D(struct data *d);\n\n\n/*-----------------------------------*/\n/*---- multiblock3D.c  functions ----*/\n/*-----------------------------------*/\nvoid multiblock3D(struct data *d);\n\n\n/*------------------------------*/\n/*---- dprocEPI.c functions ----*/\n/*------------------------------*/\nvoid addscaledEPIref(struct data *d,struct data *ref1,struct data *ref2);\nvoid addEPIref(struct data *d,struct data *ref);\nvoid ftnvEPI(struct data *d);\nvoid nvfillEPI(struct data *d);\nvoid ftnpEPI(struct data *d);\nvoid zoomEPI(struct data *d);\nvoid revreadEPI(struct data *d);\nvoid prepEPIref(struct data *ref1,struct data *ref2);\nvoid phaseEPIref(struct data *ref1,struct data *ref2,struct data *ref3);\nvoid phaseEPI(struct data *d,struct data *ref);\nvoid phaserampEPI(struct data *d,int mode);\nvoid navcorrEPI(struct data *d);\nvoid stripEPInav(struct data *d);\nvoid weightnavs(struct data *d,double gf);\nvoid setsegscale(struct data *d,struct segscale *scale);\nvoid segscale(struct data *d,struct segscale *scale);\nvoid analyseEPInav(struct data *d);\nvoid getblockEPI(struct data *d,int volindex,int DCCflag);\nvoid setblockEPI(struct data *d);\nvoid setoutvolEPI(struct data *d);\nint outvolEPI(struct data *d);\nvoid setnvolsEPI(struct data *d);\nvoid setblockSGE(struct data *d);\n\n\n/*---------------------------------*/\n/*---- prescanEPI.c functions -----*/\n/*---------------------------------*/\nvoid prescanEPI(struct data *d);\nvoid settep(struct data *d, int mode);\n\n\n/*---------------------------*/\n/*---- dproc.c functions ----*/\n/*---------------------------*/\nint *sliceorder(struct data *d,int dim,char *par);\nint *phaseorder(struct data *d,int views,int dim,char *par);\nint *phaselist(struct data *d,char *par);\nvoid getmax(struct data *d);\nvoid getnoise(struct data *d,int mode);\nvoid equalizenoise(struct data *d,int mode);\nvoid dccorrect(struct data *d);\nvoid scaledata(struct data *d,double factor);\nvoid combine_channels(struct data *d);\nvoid opti_comb(struct data *d, int offset);\ndouble *unwrap1D(double *angles, int nangles);\n\n\n/*-----------------------------*/\n/*---- dproc1D.c functions ----*/\n/*-----------------------------*/\nvoid fft1D(struct data *d,int dataorder);\nvoid shiftdata1D(struct data *d,int mode,int dataorder);\nvoid shift1Ddata(struct data *d,int shft,int dataorder);\nvoid weightdata1D(struct data *d,int mode,int dataorder);\nvoid zerofill1D(struct data *d,int mode,int dataorder);\nvoid phaseramp1D(struct data *d,int mode);\nvoid phasedata1D(struct data *d,int mode,int dataorder);\nvoid getmaxtrace1D(struct data *d,int trace);\n\n\n/*-----------------------------*/\n/*---- dproc2D.c functions ----*/\n/*-----------------------------*/\nvoid dimorder2D(struct data *d);\nvoid fft2D(struct data *d,int mode);\nvoid ifft2D(struct data *d,int mode);\nvoid shiftdata2D(struct data *d,int mode);\nvoid shift2Ddata(struct data *d,int npshft,int nvshft);\nvoid shift2DCSIdata(struct data *d,int nvshft,int nv2shft);\nvoid weightdata2D(struct data *d,int mode);\nvoid zerofill2D(struct data *d,int mode);\nvoid phaseramp2D(struct data *d,int mode);\nvoid phasedata2D(struct data *d,int mode);\nvoid zoomdata2D(struct data *d,int startdim1, int widthdim1, int startdim2, int widthdim2);\nvoid revread(struct data *d);\nvoid navcorr(struct data *d,struct data *nav);\n\n\n/*-----------------------------*/\n/*---- dproc3D.c functions ----*/\n/*-----------------------------*/\nvoid dimorder3D(struct data *d);\nvoid getblock3D(struct data *d,int volindex,int DCCflag);\nvoid getnavblock3D(struct data *d,int volindex,int DCCflag);\nvoid shiftdatadim3(struct data *d,int dataorder,int mode);\nvoid shiftdim3data(struct data *d,int dim3shft);\nvoid shiftD3data(struct data *d,int dim3shft);\nvoid weightdatadim3(struct data *d,int mode);\nvoid zerofilldim3(struct data *d,int mode);\nvoid fftdim3(struct data *d);\nvoid phaserampdim3(struct data *d,int mode);\nvoid phasedatadim3(struct data *d,int mode);\n\n\n/*-----------------------------*/\n/*---- noise2D.c functions ----*/\n/*-----------------------------*/\nvoid get2Dnoisematrix(struct data *d,int mode);\nvoid zero2Dnoisematrix(struct data *d);\nvoid print2Dnoisematrix(struct data *d);\n\n\n/*-----------------------------*/\n/*---- dmask2D.c functions ----*/\n/*-----------------------------*/\nvoid get2Dmask(struct data *d,int mode);\nvoid fill2Dmask(struct data *d,int mode);\n\n\n/*---------------------------*/\n/*---- dread.c functions ----*/\n/*---------------------------*/\nvoid setblock(struct data *d,int dim);\nvoid getblock(struct data *d,int volindex,int DCCflag);\nint readfblock(struct data *d,int volindex,int DCCflag);\nint readlblock(struct data *d,int volindex,int DCCflag);\nint readsblock(struct data *d,int volindex,int DCCflag);\nint setoffset(struct data *d,int volindex,int receiver,int dim3index,int dim2index);\nvoid getnavblock(struct data *d,int volindex,int DCCflag);\nint readnavfblock(struct data *d,int volindex,int DCCflag);\nint readnavlblock(struct data *d,int volindex,int DCCflag);\nint readnavsblock(struct data *d,int volindex,int DCCflag);\nint setnavoffset(struct data *d,int volindex,int receiver,int dim3index,int seg,int nav);\nint sliceindex(struct data *d,int slice);\nint segindex(struct data *d,int phase);\nint phaseindex(struct data *d,int phase);\nint phase2index(struct data *d,int phase2);\nint phase3index(struct data *d,int phase3);\nvoid synctablesort2D(struct data *d, int d2, int d3, int *p2, int *p3);\nint synctablesort3D(struct data *d, int d2, int d3, int d4, int *p2, int *p3, int *p4);\n\n\n/*-----------------------------*/\n/*---- dread1D.c functions ----*/\n/*-----------------------------*/\nvoid getblock1D(struct data *d,int volindex,int DCCflag);\n\n\n/*-----------------------------*/\n/*---- dread2D.c functions ----*/\n/*-----------------------------*/\nvoid getblock2D(struct data *d,int volindex,int DCCflag);\nvoid getnavblock2D(struct data *d,int volindex,int DCCflag);\nint process2Dblock(struct data *d,char *startpar,char *endpar);\n\n\n/*---------------------------*/\n/*---- dhead.c functions ----*/\n/*---------------------------*/\nvoid getdfh(struct data *d);\nvoid getdbh(struct data *d,int blockindex);\nvoid gethcbh(struct data *d,int blockindex);\nvoid reversedfh(struct datafilehead *dfh);\nvoid reversedbh(struct datablockhead *dbh);\nvoid reversehcbh(struct hypercmplxbhead *hcbh);\nvoid printfileheader(struct datafilehead *dfh);\nvoid printfilestatus(struct datafilehead *dfh);\nvoid printblockheader(struct datablockhead *dbh,int blockindex);\nvoid printhcblockheader(struct hypercmplxbhead *hcbh,int blockindex);\n\n\n/*----------------------------*/\n/*---- dutils.c functions ----*/\n/*----------------------------*/\nvoid opendata(char *datafile,struct data *d);\nvoid setnvols(struct data *d);\nvoid setstartendvol(struct data *d);\nvoid setdatapars(struct data *d);\nvoid setseqmode(struct data *d);\nvoid setdim(struct data *d);\nint spar(struct data *d,char *par,char *str);\nint im1D(struct data *d);\nint im2D(struct data *d);\nint im2DLL(struct data *d);\nint im3D(struct data *d);\nint im4D(struct data *d);\nint imCSI(struct data *d);\ndouble getelem(struct data *d,char *par,int image);\nint wprocpar(struct data *d,char *filename);\nvoid copydbh(struct datablockhead *dbh1,struct datablockhead *dbh2);\nvoid setfile(struct file *datafile,char *datadir);\nvoid setreffile(struct file *datafile,struct data *d,char *refpar);\nvoid setfn(struct data *d1,struct data *d2,double multiplier);\nvoid setfn1(struct data *d1,struct data *d2,double multiplier);\nvoid setdimstatus(struct data *d,struct dimstatus *status,int block);\nvoid copynblocks(struct data *d1,struct data *d2);\nvoid copymaskpars(struct data *d1,struct data *d2);\nvoid copysmappars(struct data *d1,struct data *d2);\nvoid copysensepars(struct data *d1,struct data *d2);\nint checkequal(struct data *d1,struct data *d2,char *par,char *comment);\nvoid initdatafrom(struct data *d1, struct data *d2);\nvoid initdata(struct data *d);\nvoid nulldata(struct data *d);\nvoid cleardimorder(struct data *d);\nvoid clearstatus(struct data *d);\nvoid zeromax(struct data *d);\nvoid zeronoise(struct data *d);\nvoid initnoise(struct data *d);\nvoid nullnoise(struct data *d);\nvoid closedata(struct data *d);\n\n\n/*------------------------------*/\n/*---- dutils1D.c functions ----*/\n/*------------------------------*/\nvoid clear1Dall(struct data *d);\nvoid clear1Ddata(struct data *d);\nvoid clearnoise1D(struct data *d);\nvoid clear1Dmask(struct data *d);\n\n\n/*------------------------------*/\n/*---- dutils2D.c functions ----*/\n/*------------------------------*/\nint check2Dref(struct data *d,struct data *ref);\nvoid copy2Ddata(struct data *d1,struct data *d2);\nvoid clear2Dall(struct data *d);\nvoid clear2Ddata(struct data *d);\nvoid clearCSIdata(struct data *d);\nvoid clearnoise2D(struct data *d);\nvoid clear2Dmask(struct data *d);\nvoid checkCrop(struct data *d);\nvoid checkCrop3D(struct data *d);\n\n\n/*------------------------------------*/\n/*---- pars.c 'procpar' functions ----*/\n/*------------------------------------*/\nvoid getpars(char *procpar,struct data *d);\nvoid getprocparpars(char *procpar,struct pars *p);\nvoid skipprocparvals(FILE *fp,struct pars *p,int type,int nvals);\nvoid procparerror(const char *function,char *par,char *str);\nvoid setarray(struct pars *p,struct pars *a);\nint list2array(char *par,struct pars *p1,struct pars *p2);\nvoid setval(struct pars *p,char *par,double value);\nvoid setsval(struct pars *p,char *par,char *svalue);\nvoid cppar(char *par1,struct pars *p1,char *par2,struct pars *p2);\nvoid copypar(char *par,struct pars *p1,struct pars *p2);\nvoid copypars(struct pars *p1, struct pars *p2);\nvoid copyvalues(struct pars *p1,int ix1,struct pars *p2,int ix2);\nvoid mallocnpars(struct pars *p);\nvoid freenpars(struct pars *p);\nvoid printarray(struct pars *a,char *array);\nvoid printprocpar(struct pars *p);\nint ptype(char *par,struct pars *p);\nint nvals(char *par,struct pars *p);\nint *ival(char *par,struct pars *p);\ndouble *val(char *par,struct pars *p);\nchar **sval(char *par,struct pars *p);\nint parindex(char *par,struct pars *p);\nint arraycheck(char *par,struct pars *a);\nint getcycle(char *par,struct pars *a);\nint cyclefaster(char *par1,char *par2,struct pars *a);\nvoid clearpars(struct pars *p);\nvoid cleararray(struct pars *a);\nvoid nullpars(struct pars *p);\n\n\n/*-------------------------------------*/\n/*---- utils.c utilities functions ----*/\n/*-------------------------------------*/\nint check_CPU_type();\nvoid complexmatrixmultiply(gsl_matrix_complex *A,gsl_matrix_complex *B,gsl_matrix_complex *C);\nvoid complexmatrixconjugate(gsl_matrix_complex *A);\nint round2int(double dval);\nvoid reverse2ByteOrder(int nele,char *ptr);\nvoid reverse4ByteOrder(int nele,char *ptr);\nvoid reverse8ByteOrder(int nele,char *ptr);\nint doublecmp(const void *double1,const void *double2);\nint nomem(char *file,const char *function,int line);\nint createdir(char *dirname);\nint checkdir(char *dirname);\nint checkfile(char *filename);\n\n\n/*-----------------------------*/\n/*---- write1D.c functions ----*/\n/*-----------------------------*/\nvoid w1Dtrace(struct data *d,int receiver,int trace,int fileid);\nvoid w1Dblock(struct data *d,int receiver,int fileid);\nvoid wdfh(struct data *d,int fileid);\nvoid wdbh(struct data *d,int fileid);\nvoid openfpw(struct data *d,int fileid);\nvoid closefp(struct data *d,int fileid);\n\n\n/*--------------------------------*/\n/*---- fdfwrite2D.c functions ----*/\n/*--------------------------------*/\nvoid w2Dfdfs(struct data *d,int type,int scalevalue,int volindex);\nint magnitude2Dfdfs(struct data *d,char *par,char *parIR,char *outdir,int type,int precision,int volindex);\nvoid other2Dfdfs(struct data *d,char *par,char *outdir,int type,int precision,int volindex);\nvoid gen2Dfdfs(struct data *d,int mode,char *outdir,int type,int precision,int volindex);\nvoid w2Dfdf(char *filename,struct data *d,int image,int slice,int sliceindex,int echo,int receiver,int type,int precision);\nvoid wcomb2Dfdf(char *filename,struct data *d,int image,int slice,int sliceindex,int echo,int type,int precision);\nvoid gen2Dfdfhdr(struct data *d,int image,int slice,int echo,int receiver,int type,int precision);\nint validtype(int type);\nint addpar2hdr(struct pars *p,int ix);\ndouble sliceposition(struct data *d,int slice);\n\n\n/*--------------------------------*/\n/*---- fdfwrite3D.c functions ----*/\n/*--------------------------------*/\nvoid w3Dfdfs(struct data *d,int type,int scalevalue,int volindex);\nint magnitude3Dfdfs(struct data *d,char *par,char *parIR,char *outdir,int type,int precision,int volindex);\nvoid other3Dfdfs(struct data *d,char *par,char *outdir,int type,int precision,int volindex);\nvoid gen3Dfdfs(struct data *d,int mode,char *outdir,int type,int precision,int volindex);\nvoid w3Dfdf(char *filename,struct data *d,int image,int slab,int echo,int receiver,int type,int precision);\nvoid wcomb3Dfdf(char *filename,struct data *d,int image,int slab,int echo,int type,int precision);\nvoid gen3Dfdfhdr(struct data *d,int image,int slice,int echo,int receiver,int type,int precision);\n\n\n/*-----------------------------*/\n/*---- rawIO3D.c functions ----*/\n/*-----------------------------*/\nvoid wrawbin3D(struct data *d,int dataorder,int type,int precision);\nvoid gen3Draw(struct data *d,int output,char *outdir,int dataorder,int type,int precision);\nvoid w3Draw(char *filename,struct data *d,int receiver,int type,int precision);\nvoid w3DrawD3(char *filename,struct data *d,int receiver);\nvoid wcomb3Draw(char *filename,struct data *d,int type,int precision);\nvoid cleardim3data(struct data *d);\nvoid rrawbin3D(struct data *d,int dataorder,int type,int precision);\nvoid get3Draw(struct data *d,int mode,char *indir,int dataorder);\nvoid r3Draw(char *filename,struct data *d,int receiver);\nvoid r3DrawD3(char *filename,struct data *d,int receiver);\nvoid delrawbin3D(struct data *d,int dataorder,int type);\nvoid del3Draw(struct data *d,char *dir);\n\n\n/*--------------------------------*/\n/*---- niftiwrite.c functions ----*/\n/*--------------------------------*/\nvoid wnifti(struct data *d,int type,int precision,int volindex);\nvoid writenifti(struct data *d,int type,int precision,int format,int volindex);\nint magnifti(struct data *d,char *par,char *parIR,char *outdir,int type,int precision,int format,int volindex);\nvoid othernifti(struct data *d,char *par,char *outdir,int type,int precision,int format,int volindex);\nvoid gennifti(struct data *d,int mode,char *outdir,int type,int precision,int format,int volindex);\nvoid wniftihdr(char *filebase,struct data *d,int precision,int format,int image);\nvoid wniftidata(char *filebase,struct data *d,int receiver,int type,int precision,int format,int newfile);\nvoid wcombniftidata(char *filebase,struct data *d,int type,int precision,int format,int newfile);\n\n\n/*--------------------------------*/\n/*---- tifwrite2D.c functions ----*/\n/*--------------------------------*/\nint wtifs2D(struct data *d,int type,int scalevalue,int volindex);\nint wtif2D(char *filename,struct data *d,int receiver,int slice,int type,double scale);\n\n\n/*--------------------------------*/\n/*---- rawwrite2D.c functions ----*/\n/*--------------------------------*/\nint wrawbin2D(struct data *d,int type,int precision,int volindex);\nint wraw2D(char *filename,struct data *d,int receiver,int slice,int type,int precision);\n\n\n/*-----------------------------*/\n/*---- options.c functions ----*/\n/*-----------------------------*/\nvoid getoptions(struct file *f,int argc,char *argv[]);\n\n\n/*---------------------------*/\n/*---- For byte swapping ----*/\n/*---------------------------*/\nEXTERN int reverse_byte_order;\n\n\n/*-------------------------*/\n/*---- For VnmrJ recon ----*/\n/*-------------------------*/\nEXTERN int vnmrj_recon;\nEXTERN char vnmrj_path[MAXPATHLEN];\n\n\n/*-------------------------------------------------------------*/\n/*---- If C++ compiler is used it needs to know above is C ----*/\n/*-------------------------------------------------------------*/\n//#ifdef __cplusplus\n//}\n//#endif\n\n/*----------------------------*/\n/*---- End of header wrap ----*/\n/*----------------------------*/\n#endif\n", "meta": {"hexsha": "ad1dded940eb9186d1fbdb0977200cad38f4721f", "size": 37725, "ext": "h", "lang": "C", "max_stars_repo_path": "src/xrecon/Xrecon.h", "max_stars_repo_name": "DanIverson/OpenVnmrJ", "max_stars_repo_head_hexsha": "0db324603dbd8f618a6a9526b9477a999c5a4cc3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2016-06-17T05:04:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T17:54:44.000Z", "max_issues_repo_path": "src/xrecon/Xrecon.h", "max_issues_repo_name": "DanIverson/OpenVnmrJ", "max_issues_repo_head_hexsha": "0db324603dbd8f618a6a9526b9477a999c5a4cc3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 128.0, "max_issues_repo_issues_event_min_datetime": "2016-07-13T17:09:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T17:53:52.000Z", "max_forks_repo_path": "src/xrecon/Xrecon.h", "max_forks_repo_name": "DanIverson/OpenVnmrJ", "max_forks_repo_head_hexsha": "0db324603dbd8f618a6a9526b9477a999c5a4cc3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 102.0, "max_forks_repo_forks_event_min_datetime": "2016-01-23T15:27:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T05:41:54.000Z", "avg_line_length": 38.8117283951, "max_line_length": 128, "alphanum_fraction": 0.5423989397, "num_tokens": 9166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.331119752830196, "lm_q2_score": 0.02595735606753309, "lm_q1q2_score": 0.008594993325206945}}
{"text": "#pragma once\n\n#include <gsl/span>\n#include <utility>\n\nnamespace hz::range {\n    template<typename T>\n    using contiguous_view = gsl::span<T>;\n\n    template<typename Container>\n    auto make_contiguous_view(Container && c) noexcept -> contiguous_view<std::remove_reference_t<decltype(std::data(*std::forward<Container>(c)))>> {\n        return gsl::make_span(std::forward<Container>(c));\n    }\n}", "meta": {"hexsha": "b1c806b997652870deef2b8da9c0bf75730eba69", "size": 394, "ext": "h", "lang": "C", "max_stars_repo_path": "include/common/range/view.h", "max_stars_repo_name": "KABoissonneault/AGEA", "max_stars_repo_head_hexsha": "8ca42d30da06084a00a46830e5bff45409c23bf4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-12-07T02:00:32.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-07T02:00:32.000Z", "max_issues_repo_path": "include/common/range/view.h", "max_issues_repo_name": "KABoissonneault/AGEA", "max_issues_repo_head_hexsha": "8ca42d30da06084a00a46830e5bff45409c23bf4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/common/range/view.h", "max_forks_repo_name": "KABoissonneault/AGEA", "max_forks_repo_head_hexsha": "8ca42d30da06084a00a46830e5bff45409c23bf4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1428571429, "max_line_length": 150, "alphanum_fraction": 0.6979695431, "num_tokens": 90, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.15817433687509236, "lm_q2_score": 0.05419873249666699, "lm_q1q2_score": 0.008572848572130821}}
{"text": "#include <mpi.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <time.h>\n#include <sys/time.h>\n#include <sys/resource.h>\n#include <unistd.h>\n#include <signal.h>\n#include <gsl/gsl_rng.h>\n\n\n#include \"allvars.h\"\n#include \"proto.h\"\n\n\n\n#ifdef DEBUG\n#include <fenv.h>\nvoid enable_core_dumps_and_fpu_exceptions(void)\n{\n  struct rlimit rlim;\n  extern int feenableexcept(int __excepts);\n\n  /* enable floating point exceptions */\n\n  /*\n     feenableexcept(FE_DIVBYZERO | FE_INVALID);\n   */\n\n  /* Note: FPU exceptions appear not to work properly \n   * when the Intel C-Compiler for Linux is used\n   */\n\n  /* set core-dump size to infinity */\n  getrlimit(RLIMIT_CORE, &rlim);\n  rlim.rlim_cur = RLIM_INFINITY;\n  setrlimit(RLIMIT_CORE, &rlim);\n\n  /* MPICH catches the signales SIGSEGV, SIGBUS, and SIGFPE....\n   * The following statements reset things to the default handlers,\n   * which will generate a core file.  \n   */\n  /*\n     signal(SIGSEGV, catch_fatal);\n     signal(SIGBUS, catch_fatal);\n     signal(SIGFPE, catch_fatal);\n     signal(SIGINT, catch_fatal);\n   */\n\n  signal(SIGSEGV, SIG_DFL);\n  signal(SIGBUS, SIG_DFL);\n  signal(SIGFPE, SIG_DFL);\n  signal(SIGINT, SIG_DFL);\n\n  /* Establish a handler for SIGABRT signals. */\n  signal(SIGABRT, catch_abort);\n}\n\n\nvoid catch_abort(int sig)\n{\n  MPI_Finalize();\n  exit(0);\n}\n\nvoid catch_fatal(int sig)\n{\n  terminate_processes();\n  MPI_Finalize();\n\n  signal(sig, SIG_DFL);\n  raise(sig);\n}\n\n\nvoid terminate_processes(void)\n{\n  pid_t my_pid;\n  char buf[500], hostname[500], *cp;\n  char commandbuf[500];\n  FILE *fd;\n  int i, pid;\n\n  sprintf(buf, \"%s%s\", All.OutputDir, \"PIDs.txt\");\n\n  my_pid = getpid();\n\n  if((fd = fopen(buf, \"r\")))\n    {\n      for(i = 0; i < NTask; i++)\n\t{\n\t  int ret;\n\n\t  ret = fscanf(fd, \"%s %d\", hostname, &pid);\n\n\t  cp = hostname;\n\t  while(*cp)\n\t    {\n\t      if(*cp == '.')\n\t\t*cp = 0;\n\t      else\n\t\tcp++;\n\t    }\n\n\t  if(my_pid != pid)\n\t    {\n\t      sprintf(commandbuf, \"ssh %s kill -ABRT %d\", hostname, pid);\n\t      printf(\"--> %s\\n\", commandbuf);\n\t      fflush(stdout);\n#ifndef NOCALLSOFSYSTEM\n\t      ret = system(commandbuf);\n#endif\n\t    }\n\t}\n\n      fclose(fd);\n    }\n}\n\nvoid write_pid_file(void)\n{\n  pid_t my_pid;\n  char mode[8], buf[500];\n  FILE *fd;\n  int i;\n\n  my_pid = getpid();\n\n  sprintf(buf, \"%s%s\", All.OutputDir, \"PIDs.txt\");\n\n  if(RestartFlag == 0)\n    strcpy(mode, \"w\");\n  else\n    strcpy(mode, \"a\");\n\n  for(i = 0; i < NTask; i++)\n    {\n      if(ThisTask == i)\n\t{\n\t  if(ThisTask == 0)\n\t    sprintf(mode, \"w\");\n\t  else\n\t    sprintf(mode, \"a\");\n\n\t  if((fd = fopen(buf, mode)))\n\t    {\n\t      fprintf(fd, \"%s %d\\n\", getenv(\"HOST\"), (int) my_pid);\n\t      fclose(fd);\n\t    }\n\t}\n\n      MPI_Barrier(MPI_COMM_WORLD);\n    }\n}\n#endif\n\n\n\ndouble get_random_number(unsigned int id)\n{\n  return RndTable[(id % RNDTABLE)];\n}\n\nvoid set_random_numbers(void)\n{\n  int i;\n\n  for(i = 0; i < RNDTABLE; i++)\n    RndTable[i] = gsl_rng_uniform(random_generator);\n}\n\n\n/* returns the number of cpu-ticks in seconds that\n * have elapsed. (or the wall-clock time)\n */\ndouble second(void)\n{\n#ifdef WALLCLOCK\n  return MPI_Wtime();\n#else\n  return ((double) clock()) / CLOCKS_PER_SEC;\n#endif\n\n  /* note: on AIX and presumably many other 32bit systems, \n   * clock() has only a resolution of 10ms=0.01sec \n   */\n}\n\ndouble measure_time(void)\t/* strategy: call this at end of functions to account for time in this function, and before another (nontrivial) function is called */\n{\n  double t, dt;\n\n  t = second();\n  dt = t - WallclockTime;\n  WallclockTime = t;\n\n  return dt;\n}\n\n/* returns the time difference between two measurements \n * obtained with second(). The routine takes care of the \n * possible overflow of the tick counter on 32bit systems.\n */\ndouble timediff(double t0, double t1)\n{\n  double dt;\n\n  dt = t1 - t0;\n\n  if(dt < 0)\t\t\t/* overflow has occured (for systems with 32bit tick counter) */\n    {\n#ifdef WALLCLOCK\n      dt = 0;\n#else\n      dt = t1 + pow(2, 32) / CLOCKS_PER_SEC - t0;\n#endif\n    }\n\n  return dt;\n}\n\n\n\n\n#ifdef X86FIX\n\n#define _FPU_SETCW(x) asm volatile (\"fldcw %0\": :\"m\" (x));\n#define _FPU_GETCW(x) asm volatile (\"fnstcw %0\":\"=m\" (x));\n#define _FPU_EXTENDED 0x0300\n#define _FPU_DOUBLE   0x0200\n\nvoid x86_fix(void)\n{\n  unsigned short dummy, new_cw;\n  unsigned short *old_cw;\n\n  old_cw = &dummy;\n\n  _FPU_GETCW(*old_cw);\n  new_cw = (*old_cw & ~_FPU_EXTENDED) | _FPU_DOUBLE;\n  _FPU_SETCW(new_cw);\n}\n\n#endif\n\n\nvoid sumup_large_ints(int n, int *src, long long *res)\n{\n  int i, j, *numlist;\n\n  numlist = (int *) mymalloc(NTask * n * sizeof(int));\n  MPI_Allgather(src, n, MPI_INT, numlist, n, MPI_INT, MPI_COMM_WORLD);\n\n  for(j = 0; j < n; j++)\n    res[j] = 0;\n\n  for(i = 0; i < NTask; i++)\n    for(j = 0; j < n; j++)\n      res[j] += numlist[i * n + j];\n\n  myfree(numlist);\n}\n\nvoid sumup_longs(int n, long long *src, long long *res)\n{\n  int i, j;\n  long long *numlist;\n\n  numlist = (long long *) mymalloc(NTask * n * sizeof(long long));\n  MPI_Allgather(src, n * sizeof(long long), MPI_BYTE, numlist, n * sizeof(long long), MPI_BYTE,\n\t\tMPI_COMM_WORLD);\n\n  for(j = 0; j < n; j++)\n    res[j] = 0;\n\n  for(i = 0; i < NTask; i++)\n    for(j = 0; j < n; j++)\n      res[j] += numlist[i * n + j];\n\n  myfree(numlist);\n}\n\nsize_t sizemax(size_t a, size_t b)\n{\n  if(a < b)\n    return b;\n  else\n    return a;\n}\n\n\nvoid report_VmRSS(void)\n{\n  pid_t my_pid;\n  FILE *fd;\n  char buf[1024];\n\n  my_pid = getpid();\n\n  sprintf(buf, \"/proc/%d/status\", my_pid);\n\n  if((fd = fopen(buf, \"r\")))\n    {\n      while(1)\n\t{\n\t  if(fgets(buf, 500, fd) != buf)\n\t    break;\n\n\t  if(strncmp(buf, \"VmRSS\", 5) == 0)\n\t    {\n\t      printf(\"ThisTask=%d: %s\", ThisTask, buf);\n\t    }\n\t  if(strncmp(buf, \"VmSize\", 6) == 0)\n\t    {\n\t      printf(\"ThisTask=%d: %s\", ThisTask, buf);\n\t    }\n\t}\n      fclose(fd);\n    }\n}\n", "meta": {"hexsha": "ddd7966596c2c1c40fa3dfbdb74531ac7ffc42f0", "size": 5758, "ext": "c", "lang": "C", "max_stars_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/system.c", "max_stars_repo_name": "egpbos/egp", "max_stars_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/system.c", "max_issues_repo_name": "egpbos/egp", "max_issues_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/system.c", "max_forks_repo_name": "egpbos/egp", "max_forks_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.826625387, "max_line_length": 160, "alphanum_fraction": 0.606634248, "num_tokens": 1795, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3106943959796865, "lm_q2_score": 0.02758528212686156, "lm_q1q2_score": 0.008570592568334494}}
{"text": "#pragma once\n\n#include <gsl/span>\n\n#include \"halley/text/halleystring.h\"\n#include \"halley/resources/resource.h\"\n#include \"halley/maths/range.h\"\n#include \"halley/maths/vector4.h\"\n#include \"halley/data_structures/maybe.h\"\n#include <map>\n#include <vector>\n\n#include \"halley/utils/type_traits.h\"\n\n#if defined(DEV_BUILD)\n#define STORE_CONFIG_NODE_PARENTING\n#endif\n\nnamespace Halley {\n\tclass Serializer;\n\tclass Deserializer;\n\tclass ConfigNode;\n\n\ttemplate<typename T>\n\tstruct HasToConfigNode\n\t{\n\tprivate:\n\t\ttypedef std::true_type yes;\n\t\ttypedef std::false_type no;\n\t\ttemplate<typename U> static auto test(int) -> decltype(std::declval<U>().toConfigNode(), yes());\n\t\ttemplate<typename> static no test(...);\n\t \n\tpublic:\n\t\tstatic constexpr bool value = std::is_same<decltype(test<T>(0)),yes>::value;\n\t};\n\n\ttemplate<typename T>\n\tstruct HasConfigNodeConstructor\n\t{\n\tprivate:\n\t\ttypedef std::true_type yes;\n\t\ttypedef std::false_type no;\n\t\ttemplate<typename U> static auto test(int) -> decltype(U(std::declval<ConfigNode>()), yes());\n\t\ttemplate<typename> static no test(...);\n\t \n\tpublic:\n\t\tstatic constexpr bool value = std::is_same<decltype(test<T>(0)),yes>::value;\n\t};\n\n    enum class ConfigNodeType\n    {\n        Undefined,\n        String,\n        Sequence,\n        Map,\n        Int,\n        Float,\n        Int2,\n        Float2,\n        Int3,\n        Float3,\n        Int4,\n        Float4,\n        Bytes,\n        DeltaSequence, // For delta coding\n        DeltaMap,      // For delta coding\n        Noop,          // For delta coding\n        Idx,           // For delta coding\n        Del            // For delta coding\n    };\n\n    template <>\n    struct EnumNames< ConfigNodeType >\n    {\n        constexpr std::array< const char*, 17 > operator()() const\n        {\n            return { { \"undefined\",\n                \"string\",\n                \"sequence\",\n                \"map\",\n                \"int\",\n                \"float\",\n                \"int2\",\n                \"float2\",\n                \"int3\",\n                \"float3\",\n                \"int4\",\n                \"float4\",\n                \"bytes\",\n                \"deltaSequence\",\n                \"deltaMap\",\n                \"noop\",\n                \"idx\"\n                \"del\" } };\n        }\n    };\n\n    class ConfigFile;\n\n    class ConfigNode\n    {\n        friend class ConfigFile;\n\n    public:\n        using MapType = std::map< String, ConfigNode >;\n        using SequenceType = std::vector< ConfigNode >;\n\n        struct NoopType\n        {\n        };\n        struct DelType\n        {\n        };\n        struct IdxType\n        {\n            int start;\n            int len;\n            IdxType() = default;\n            IdxType( int start, int len ) :\n                start( start ), len( len ) { }\n        };\n\n        ConfigNode();\n        explicit ConfigNode( const ConfigNode& other );\n        ConfigNode( ConfigNode&& other ) noexcept;\n        ConfigNode( MapType entryMap );\n        ConfigNode( SequenceType entryList );\n        explicit ConfigNode( String value );\n        explicit ConfigNode( const char* value );\n        explicit ConfigNode( bool value );\n        explicit ConfigNode( int value );\n        explicit ConfigNode( float value );\n        explicit ConfigNode( Angle1f value );\n        explicit ConfigNode( Vector2i value );\n        explicit ConfigNode( Vector2f value );\n        explicit ConfigNode( Vector3i value );\n        explicit ConfigNode( Vector3f value );\n        explicit ConfigNode( Vector4i value );\n        explicit ConfigNode( Vector4f value );\n        explicit ConfigNode( Bytes value );\n        explicit ConfigNode( NoopType value );\n        explicit ConfigNode( DelType value );\n        explicit ConfigNode( IdxType value );\n\n\t\ttemplate <typename T>\n\t\texplicit ConfigNode(const std::vector<T>& sequence)\n\t\t{\n\t\t\tSequenceType seq;\n\t\t\tseq.reserve(sequence.size());\n\t\t\tfor (auto& e: sequence) {\n\t\t\t\tif constexpr (HasToConfigNode<T>::value) {\n\t\t\t\t\tseq.push_back(e.toConfigNode());\n\t\t\t\t} else {\n\t\t\t\t\tseq.push_back(ConfigNode(e));\n\t\t\t\t}\n\t\t\t}\n\t\t\t*this = seq;\n\t\t}\n\n        ~ConfigNode();\n\n        ConfigNode& operator=( const ConfigNode& other );\n        ConfigNode& operator=( ConfigNode&& other ) noexcept;\n        ConfigNode& operator=( bool value );\n        ConfigNode& operator=( int value );\n        ConfigNode& operator=( float value );\n        ConfigNode& operator=( Angle1f value );\n        ConfigNode& operator=( Vector2i value );\n        ConfigNode& operator=( Vector2f value );\n        ConfigNode& operator=( Vector3i value );\n        ConfigNode& operator=( Vector3f value );\n        ConfigNode& operator=( Vector4i value );\n        ConfigNode& operator=( Vector4f value );\n\n        ConfigNode& operator=( MapType entryMap );\n        ConfigNode& operator=( SequenceType entryList );\n        ConfigNode& operator=( String value );\n        ConfigNode& operator=( Bytes value );\n        ConfigNode& operator=( gsl::span< const gsl::byte > bytes );\n\n        ConfigNode& operator=( const char* value );\n\n        ConfigNode& operator=( NoopType value );\n        ConfigNode& operator=( DelType value );\n        ConfigNode& operator=( IdxType value );\n\n\t\ttemplate <typename T>\n\t\tConfigNode& operator=(const std::vector<T>& sequence)\n\t\t{\n\t\t\tSequenceType seq;\n\t\t\tseq.reserve(sequence.size());\n\t\t\tfor (auto& e: sequence) {\n\t\t\t\tif constexpr (HasToConfigNode<T>::value) {\n\t\t\t\t\tseq.push_back(e.toConfigNode());\n\t\t\t\t} else {\n\t\t\t\t\tseq.push_back(ConfigNode(e));\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn *this = seq;\n\t\t}\n\n        bool operator==( const ConfigNode& other ) const;\n        bool operator!=( const ConfigNode& other ) const;\n\n        ConfigNodeType getType() const;\n\n        void serialize( Serializer& s ) const;\n        void deserialize( Deserializer& s );\n\n        int asInt() const;\n        float asFloat() const;\n        bool asBool() const;\n        Angle1f asAngle1f() const;\n        Vector2i asVector2i() const;\n        Vector2f asVector2f() const;\n        Vector3i asVector3i() const;\n        Vector3f asVector3f() const;\n        Vector4i asVector4i() const;\n        Vector4f asVector4f() const;\n        Range< float > asFloatRange() const;\n        String asString() const;\n        const Bytes& asBytes() const;\n\n        int asInt( int defaultValue ) const;\n        float asFloat( float defaultValue ) const;\n        bool asBool( bool defaultValue ) const;\n        String asString( const String& defaultValue ) const;\n        Angle1f asAngle1f( Angle1f defaultValue ) const;\n        Vector2i asVector2i( Vector2i defaultValue ) const;\n        Vector2f asVector2f( Vector2f defaultValue ) const;\n        Vector3i asVector3i( Vector3i defaultValue ) const;\n        Vector3f asVector3f( Vector3f defaultValue ) const;\n        Vector4i asVector4i( Vector4i defaultValue ) const;\n        Vector4f asVector4f( Vector4f defaultValue ) const;\n\n\t\ttemplate <typename T>\n\t\tstd::vector<T> asVector() const\n\t\t{\n\t\t\tif (type == ConfigNodeType::Sequence) {\n\t\t\t\tstd::vector<T> result;\n\t\t\t\tresult.reserve(asSequence().size());\n\t\t\t\tfor (const auto& e : asSequence()) {\n\t\t\t\t\tif constexpr (HasConfigNodeConstructor<T>::value) {\n\t\t\t\t\t\tresult.emplace_back(T(e));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresult.emplace_back(e.convertTo(Tag<T>()));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t} else {\n\t\t\t\tthrow Exception(\"Can't convert \" + getNodeDebugId() + \" from \" + toString(getType()) + \" to std::vector<T>.\", HalleyExceptions::Resources);\n\t\t\t}\n\t\t}\n\n\t\ttemplate <typename T>\n\t\tstd::vector<T> asVector(const std::vector<T>& defaultValue) const\n\t\t{\n\t\t\tif (type == ConfigNodeType::Sequence) {\n\t\t\t\treturn asVector<T>();\n\t\t\t} else {\n\t\t\t\treturn defaultValue;\n\t\t\t}\n\t\t}\n\n        const SequenceType& asSequence() const;\n        const MapType& asMap() const;\n        SequenceType& asSequence();\n        MapType& asMap();\n\n        void ensureType( ConfigNodeType type );\n\n        bool hasKey( const String& key ) const;\n        void removeKey( const String& key );\n\n        ConfigNode& operator[]( const String& key );\n        ConfigNode& operator[]( size_t idx );\n\n        const ConfigNode& operator[]( const String& key ) const;\n        const ConfigNode& operator[]( size_t idx ) const;\n\n        SequenceType::iterator begin();\n        SequenceType::iterator end();\n\n        SequenceType::const_iterator begin() const;\n        SequenceType::const_iterator end() const;\n\n        void reset();\n        void setOriginalPosition( int line, int column );\n        void setParent( const ConfigNode* parent, int idx );\n        void propagateParentingInformation( const ConfigFile* parentFile );\n\n        inline void assertValid() const\n        {\n            Expects( intData != 0xCDCDCDCD );\n            Expects( intData != 0xDDDDDDDD );\n        }\n\n        struct BreadCrumb\n        {\n            const BreadCrumb* prev = nullptr;\n            String key;\n            OptionalLite< int > idx;\n            int depth = 0;\n\n            BreadCrumb() = default;\n            BreadCrumb( const BreadCrumb& prev, String key ) :\n                prev( &prev ), key( std::move( key ) ), depth( prev.depth + 1 ) { }\n            BreadCrumb( const BreadCrumb& prev, int index ) :\n                prev( &prev ), idx( index ), depth( prev.depth + 1 ) { }\n\n            bool hasKeyAt( const String& key, int depth ) const;\n            bool hasIndexAt( int idx, int depth ) const;\n        };\n\n        class IDeltaCodeHints\n        {\n        public:\n            virtual ~IDeltaCodeHints() = default;\n\n            virtual std::optional< size_t > getSequenceMatch( const SequenceType& seq, const ConfigNode& newValue, size_t curIdx, const BreadCrumb& breadCrumb ) const = 0;\n            virtual bool doesSequenceOrderMatter( const BreadCrumb& breadCrumb ) const { return true; }\n            virtual bool canDeleteKey( const String& key, const BreadCrumb& breadCrumb ) const { return true; }\n            virtual bool canDeleteAnyKey() const { return true; }\n            virtual bool shouldBypass( const BreadCrumb& breadCrumb ) const { return false; }\n            virtual bool areNullAndEmptyEquivalent( const BreadCrumb& breadCrumb ) const { return false; }\n        };\n\n        static ConfigNode createDelta( const ConfigNode& from, const ConfigNode& to, const IDeltaCodeHints* hints = nullptr );\n        static ConfigNode applyDelta( const ConfigNode& from, const ConfigNode& delta );\n        void applyDelta( const ConfigNode& delta );\n        void decayDeltaArtifacts();\n\n    private:\n        template < typename T >\n        class Tag\n        {\n        };\n\n        union {\n            String* strData;\n            MapType* mapData;\n            SequenceType* sequenceData;\n            Bytes* bytesData;\n            void* rawPtrData;\n            int intData;\n            float floatData;\n            Angle1f ang1fData;\n            Vector2i vec2iData;\n            Vector2f vec2fData;\n            Vector3i vec3iData;\n            Vector3f vec3fData;\n            Vector4i vec4iData;\n            Vector4f vec4fData;\n        };\n        ConfigNodeType type = ConfigNodeType::Undefined;\n        int auxData = 0; // Used by delta coding\n\n#if defined(STORE_CONFIG_NODE_PARENTING)\n        struct ParentingInfo\n        {\n            int line = 0;\n            int column = 0;\n            int idx = 0;\n            const ConfigNode* node = nullptr;\n            const ConfigFile* file = nullptr;\n        };\n        std::unique_ptr< ParentingInfo > parent;\n#endif\n        static ConfigNode undefinedConfigNode;\n        static String undefinedConfigNodeName;\n\n        template < typename T >\n        void deserializeContents( Deserializer& s )\n        {\n            T v;\n            s >> v;\n            *this = std::move( v );\n        }\n\n        String getNodeDebugId() const;\n        String backTrackFullNodeName() const;\n\n        int convertTo( Tag< int > tag ) const;\n        float convertTo( Tag< float > tag ) const;\n        bool convertTo( Tag< bool > tag ) const;\n        Angle1f convertTo( Tag< Angle1f > tag ) const;\n        Vector2i convertTo( Tag< Vector2i > tag ) const;\n        Vector2f convertTo( Tag< Vector2f > tag ) const;\n        Vector3i convertTo( Tag< Vector3i > tag ) const;\n        Vector3f convertTo( Tag< Vector3f > tag ) const;\n        Vector4i convertTo( Tag< Vector4i > tag ) const;\n        Vector4f convertTo( Tag< Vector4f > tag ) const;\n        Range< float > convertTo( Tag< Range< float > > tag ) const;\n        String convertTo( Tag< String > tag ) const;\n        const Bytes& convertTo( Tag< Bytes& > tag ) const;\n\n        bool isNullOrEmpty() const;\n\n        static ConfigNode doCreateDelta( const ConfigNode& from, const ConfigNode& to, const BreadCrumb& breadCrumb, const IDeltaCodeHints* hints );\n        static ConfigNode createMapDelta( const ConfigNode& from, const ConfigNode& to, const BreadCrumb& breadCrumb, const IDeltaCodeHints* hints );\n        static ConfigNode createSequenceDelta( const ConfigNode& from, const ConfigNode& to, const BreadCrumb& breadCrumb, const IDeltaCodeHints* hints );\n        void applyMapDelta( const ConfigNode& delta );\n        void applySequenceDelta( const ConfigNode& delta );\n\n        bool isEquivalent( const ConfigNode& other ) const;\n        bool isEquivalentStrictOrder( const ConfigNode& other ) const;\n    };\n} // namespace Halley\n", "meta": {"hexsha": "e0f9f1701ff2bc594cbeac6fe1590c5dcafa4faf", "size": 13174, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engine/utils/include/halley/data_structures/config_node.h", "max_stars_repo_name": "chidddy/halley", "max_stars_repo_head_hexsha": "f828b74a6bbe7f172a7dba84e72429d3163bd61c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/engine/utils/include/halley/data_structures/config_node.h", "max_issues_repo_name": "chidddy/halley", "max_issues_repo_head_hexsha": "f828b74a6bbe7f172a7dba84e72429d3163bd61c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engine/utils/include/halley/data_structures/config_node.h", "max_forks_repo_name": "chidddy/halley", "max_forks_repo_head_hexsha": "f828b74a6bbe7f172a7dba84e72429d3163bd61c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2102689487, "max_line_length": 171, "alphanum_fraction": 0.5978442387, "num_tokens": 3091, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2751297238231752, "lm_q2_score": 0.03114383109681101, "lm_q1q2_score": 0.008568593648461229}}
{"text": "/*  Copyright 2017 International Business Machines Corporation\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.  */\n\n#pragma once\n\n#include <kernelpp/types.h>\n#include <kernelpp/kernel.h>\n\n#include <gsl.h>\n\nnamespace mwe {\nnamespace kernels\n{\n    using kernelpp::compute_mode;\n    using kernelpp::error_code;\n\n    /*  Declare a kernel 'add' which is overloaded to operate\n     *  on single or array-like inputs.\n     *\n     *  Also, declare the compute modes (CPU,GPU) which\n     *  this kernel will support.\n     */\n    KERNEL_DECL(add,\n        compute_mode::CPU, compute_mode::CUDA)\n    {\n        template <compute_mode> static kernelpp::variant<int, error_code> op(\n            int a, int b\n            );\n\n        template <compute_mode> static error_code op(\n            const gsl::span<int> a, const gsl::span<int> b, gsl::span<int> result\n            );\n    };\n}\n}", "meta": {"hexsha": "502e7c7612d85078b27a949ca7b484ab11e0560e", "size": 1347, "ext": "h", "lang": "C", "max_stars_repo_path": "src/kernels/add.h", "max_stars_repo_name": "rayglover-ibm/cuda-bindings", "max_stars_repo_head_hexsha": "7d9f2f1f2f15cec7ec7b1d5882dc2a2cbfb646cd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2017-04-18T02:56:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-25T10:01:56.000Z", "max_issues_repo_path": "src/kernels/add.h", "max_issues_repo_name": "rayglover-ibm/cuda-bindings", "max_issues_repo_head_hexsha": "7d9f2f1f2f15cec7ec7b1d5882dc2a2cbfb646cd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernels/add.h", "max_forks_repo_name": "rayglover-ibm/cuda-bindings", "max_forks_repo_head_hexsha": "7d9f2f1f2f15cec7ec7b1d5882dc2a2cbfb646cd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2826086957, "max_line_length": 81, "alphanum_fraction": 0.6904231626, "num_tokens": 307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23651622568252115, "lm_q2_score": 0.03622005950618011, "lm_q1q2_score": 0.008566631768398041}}
{"text": "//\n// Created by Huy Vo on 2019-06-29.\n//\n\n#ifndef PACMENSL_SRC_PETSCWRAP_PETSCWRAP_H_\n#define PACMENSL_SRC_PETSCWRAP_PETSCWRAP_H_\n#include <petsc.h>\n#include <iostream>\n#include \"Sys.h\"\nnamespace pacmensl {\n\ntemplate<typename PetscT>\nclass Petsc {\n protected:\n  PetscT dat = nullptr;\n\n  int Destroy(PetscT *obj);\n\n public:\n\n  Petsc() {\n    static_assert(std::is_convertible<PetscT, Vec>::value || std::is_convertible<PetscT, Mat>::value\n                      || std::is_convertible<PetscT, IS>::value || std::is_convertible<PetscT, VecScatter>::value\n                      || std::is_convertible<PetscT, KSP>::value || std::is_convertible<PetscT, TS>::value,\n                  \"pacmensl::Petsc can only wrap PETSc objects.\");\n  }\n\n  PetscT *mem() { return &dat; }\n\n  const PetscT *mem() const { return &dat; }\n\n  bool IsEmpty() { return (dat == nullptr); }\n\n  operator PetscT() { return dat; }\n\n  ~Petsc() {\n    Destroy(&dat);\n  }\n};\n\ntemplate<>\nint Petsc<Vec>::Destroy(Vec *obj);\n\ntemplate<>\nint Petsc<Mat>::Destroy(Mat *obj);\n\ntemplate<>\nint Petsc<IS>::Destroy(IS *obj);\n\ntemplate<>\nint Petsc<VecScatter>::Destroy(VecScatter *obj);\n\ntemplate<>\nint Petsc<KSP>::Destroy(KSP *obj);\n\ntemplate<>\nint Petsc<TS>::Destroy(TS *obj);\n\nPacmenslErrorCode ExpandVec(Petsc<Vec> &p, const std::vector<PetscInt> &new_indices, const PetscInt new_local_size);\nPacmenslErrorCode ExpandVec(Vec &p, const std::vector<PetscInt> &new_indices, const PetscInt new_local_size);\n}\n#endif //PACMENSL_SRC_PETSCWRAP_PETSCWRAP_H_\n", "meta": {"hexsha": "7299fc51d38e1e470d968ae1df82f346357e1e77", "size": 1502, "ext": "h", "lang": "C", "max_stars_repo_path": "src/PetscWrap/PetscWrap.h", "max_stars_repo_name": "voduchuy/pacmensl", "max_stars_repo_head_hexsha": "d35adb165caef5c8fa992be6fda16e1bfb1dfd4a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/PetscWrap/PetscWrap.h", "max_issues_repo_name": "voduchuy/pacmensl", "max_issues_repo_head_hexsha": "d35adb165caef5c8fa992be6fda16e1bfb1dfd4a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/PetscWrap/PetscWrap.h", "max_forks_repo_name": "voduchuy/pacmensl", "max_forks_repo_head_hexsha": "d35adb165caef5c8fa992be6fda16e1bfb1dfd4a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8412698413, "max_line_length": 116, "alphanum_fraction": 0.6837549933, "num_tokens": 443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25091278688527247, "lm_q2_score": 0.03410042264475985, "lm_q1q2_score": 0.008556232079762346}}
{"text": "/*\n * author: Pierre Schnizer\n * created: March 2004\n * file: pygsl/src/initmodule.c\n * $Id: initmodule.c,v 1.14 2008/10/25 20:45:04 schnizer Exp $\n *\n * Changes: \n *     7. October 2003:\n *     Removed the error handler from this file. It is now in \n *     Lib/error_helpers.c Each module must call init_pygsl()\n *     in its init routine. This is necessary to support platforms\n *     where the gsl library is statically linked to the various \n *     modules.    \n */\n#define  _PyGSL_API_MODULE 1\n#include <pygsl/intern.h>\n#include <pygsl/utils.h>\n#include <pygsl/error_helpers.h>\n\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_ieee_utils.h>\n#include <gsl/gsl_version.h>\n\n\n/* Taken from Modules/getbuildinfo */\n#ifndef DATE\n#ifdef __DATE__\n#define DATE __DATE__\n#else\n#define DATE \"xx/xx/xx\"\n#endif\n#endif\n\n#ifndef TIME\n#ifdef __TIME__\n#define TIME __TIME__\n#else\n#define TIME \"xx:xx:xx\"\n#endif\n#endif\n/* End */\n\n/*\n * Used as a buffer to generate error messages.\n */\nstatic char pygsl_error_str[512];\n#include \"profile.c\"\n#include \"error_helpers.c\"\n#include \"general_helpers.c\"\n#include \"complex_helpers.c\"\n#include \"block_helpers.c\"\n#include \"function_helpers.c\"\n#include \"rng_helpers.c\"\n\nstatic PyObject * debuglist = NULL;\n\n\nstatic int \nPyGSL_register_debug_flag(int * ptr, const char * module_name)\n{\n#if DEBUG == 1\n     PyObject * cobj;\n     FUNC_MESS_BEGIN();\n     if ((cobj = PyCObject_FromVoidPtr((void *) ptr, NULL)) == NULL){\n\t  fprintf(stderr, \"Could not create PyCObject for ptr %p to debug flag for module %s\\n\",\n\t\t  (void * ) ptr, module_name);\n\t  return GSL_EFAILED;\n     }\n     DEBUG_MESS(2, \"Registering ptr %p for module %s\", (void *) ptr,  module_name);\n     if(PyList_Append(debuglist, cobj) != 0){\n\t  return GSL_EFAILED;\n     }\n     *ptr = pygsl_debug_level;\n     FUNC_MESS_END();\n     return GSL_SUCCESS;\n#endif\n     PyGSL_ERROR(\"Why does it try to register the debug level callback? Should\"\n\t       \" use the compile time value DEBUG!\", GSL_ESANITY);\n}\n\nstatic PyObject *\nPyGSL_set_debug_level(PyObject *self, PyObject *args)\n{\n\n     FUNC_MESS_BEGIN();\n#if DEBUG == 1\n     PyObject *o;\n     int tmp, i, max, *ptr;\n     if(!PyArg_ParseTuple(args, \"i\", &tmp))\n\t  return NULL;\n     if(tmp >= 0 && tmp <PyGSL_DEBUG_MAX)\n\t  ;\n     else\n\t  PyGSL_ERROR_VAL(\"Only accept debug levels between 0 and PyGSL_DEBUG_MAX\", GSL_EINVAL, NULL);\n\n     pygsl_debug_level = tmp;\n     max = PySequence_Size(debuglist);\n     DEBUG_MESS(3, \"Setting debug level to %d for %d modules\", pygsl_debug_level, max);\n     for(i = 0; i < max; ++i){\n\t  if((o = PySequence_GetItem(debuglist, i)) == NULL){\n\t       fprintf(stderr, \"In file %s at line %d; Could not get element %d\\n\", \n\t\t       __FILE__, __LINE__, i);\n\t       continue;\n\t  }\n\t  ptr = (int *)PyCObject_AsVoidPtr(o);\n\t  DEBUG_MESS(2, \"Setting info ptr %p\", (void *) ptr);\n\t  *ptr = tmp;\n     }\n     Py_INCREF(Py_None);\n     FUNC_MESS_END();\n     return Py_None;\n#else \n     PyGSL_ERROR_NULL(\"PyGSL was not compiled with DEBUG = 1; Can not set DEBUG level!\", GSL_EUNIMPL);\n#endif \n}\n\nstatic PyObject *\nPyGSL_get_debug_level(PyObject *self, PyObject *args)\n{\n     int tmp;\n#if DEBUG == 1\n     tmp = (int) pygsl_debug_level;\n#else \n     tmp = DEBUG;\n#endif \n     return PyInt_FromLong(tmp);\n}\n\nstatic void * _PyGSL_API[PyGSL_NENTRIES_NUM];\n\nstatic PyMethodDef initMethods[] = {\n     {\"get_debug_level\", PyGSL_get_debug_level, METH_NOARGS, NULL},\n     {\"set_debug_level\", PyGSL_set_debug_level, METH_VARARGS, NULL},\n     {\"vector_transform_counter\",  PyGSL_get_vector_transform_counter ,METH_NOARGS, NULL},\n     {\"matrix_transform_counter\",  PyGSL_get_matrix_transform_counter ,METH_NOARGS, NULL},\n     {\"complex_transform_counter\", PyGSL_get_complex_transform_counter,METH_NOARGS, NULL},\n     {\"float_transform_counter\",   PyGSL_get_float_transform_counter  ,METH_NOARGS, NULL},\n     {\"register_exceptions\",       PyGSL_register_exceptions,          METH_VARARGS,NULL},\n     {\"register_warnings\",         PyGSL_register_warnings,            METH_VARARGS,NULL},\n     {NULL,     NULL, 0, NULL}        /* Sentinel */\n};\n\n\nstatic void\nPyGSL_init_api(void)\n{\n     int i;\n     \n     for(i=0;i<PyGSL_NENTRIES_NUM; ++i){\n\t  _PyGSL_API[i] = NULL;\n     }\n     _PyGSL_API[PyGSL_api_version_NUM                          ] = (void *) PyGSL_API_VERSION;\n     _PyGSL_API[PyGSL_RNG_ObjectType_NUM                       ] = NULL;\n     _PyGSL_API[PyGSL_error_flag_NUM                           ] = (void *) &PyGSL_error_flag;\n     _PyGSL_API[PyGSL_error_flag_to_pyint_NUM                  ] = (void *) &PyGSL_error_flag_to_pyint;\n     _PyGSL_API[PyGSL_add_traceback_NUM                        ] = (void *) &PyGSL_add_traceback;    \n     _PyGSL_API[PyGSL_module_error_handler_NUM                 ] = (void *) &PyGSL_module_error_handler;\n\n     _PyGSL_API[PyGSL_error_string_for_callback_NUM            ] = (void *) & PyGSL_set_error_string_for_callback        ;\n     _PyGSL_API[PyGSL_pyfloat_to_double_NUM                    ] = (void *) & PyGSL_pyfloat_to_double                    ;\n     _PyGSL_API[PyGSL_pylong_to_ulong_NUM                      ] = (void *) & PyGSL_pylong_to_ulong                      ;\n     _PyGSL_API[PyGSL_pylong_to_uint_NUM                       ] = (void *) & PyGSL_pylong_to_uint                       ;\n     _PyGSL_API[PyGSL_check_python_return_NUM                  ] = (void *) & PyGSL_check_python_return                  ;\n     _PyGSL_API[PyGSL_clear_name_NUM                           ] = (void *) & PyGSL_clear_name                           ;\n\n\n     _PyGSL_API[PyGSL_PyComplex_to_gsl_complex_NUM             ] = (void *) & PyGSL_PyComplex_to_gsl_complex             ;\n     _PyGSL_API[PyGSL_PyComplex_to_gsl_complex_float_NUM       ] = (void *) & PyGSL_PyComplex_to_gsl_complex_float       ;\n     _PyGSL_API[PyGSL_PyComplex_to_gsl_complex_long_double_NUM ] = (void *) & PyGSL_PyComplex_to_gsl_complex_long_double ;\n\n     _PyGSL_API[PyGSL_stride_recalc_NUM                        ] = (void *) & PyGSL_stride_recalc                        ;\n     _PyGSL_API[PyGSL_PyArray_new_NUM                          ] = (void *) & PyGSL_New_Array                            ;\n     _PyGSL_API[PyGSL_PyArray_copy_NUM                         ] = (void *) & PyGSL_Copy_Array                           ;\n/*\n     _PyGSL_API[PyGSL_PyArray_prepare_gsl_vector_view_NUM      ] = (void *) & PyGSL_PyArray_prepare_gsl_vector_view      ;\n     _PyGSL_API[PyGSL_PyArray_prepare_gsl_matrix_view_NUM      ] = (void *) & PyGSL_PyArray_prepare_gsl_matrix_view      ;\n*/\n     _PyGSL_API[PyGSL_PyArray_generate_gsl_vector_view_NUM     ] = (void *) & PyGSL_PyArray_generate_gsl_vector_view     ;\n     _PyGSL_API[PyGSL_PyArray_generate_gsl_matrix_view_NUM     ] = (void *) & PyGSL_PyArray_generate_gsl_matrix_view     ;\n     _PyGSL_API[PyGSL_copy_pyarray_to_gslvector_NUM            ] = (void *) & PyGSL_copy_pyarray_to_gslvector            ;\n     _PyGSL_API[PyGSL_copy_pyarray_to_gslmatrix_NUM            ] = (void *) & PyGSL_copy_pyarray_to_gslmatrix            ;\n     _PyGSL_API[PyGSL_copy_gslvector_to_pyarray_NUM            ] = (void *) & PyGSL_copy_gslvector_to_pyarray            ;\n     _PyGSL_API[PyGSL_copy_gslmatrix_to_pyarray_NUM            ] = (void *) & PyGSL_copy_gslmatrix_to_pyarray            ;\n\n     _PyGSL_API[PyGSL_gsl_rng_from_pyobject_NUM                ] = (void *) & PyGSL_gsl_rng_from_pyobject                ;\n     _PyGSL_API[PyGSL_function_wrap_helper_NUM                 ] = (void *) & PyGSL_function_wrap_helper                 ;\n     _PyGSL_API[PyGSL_register_debug_flag_NUM                  ] = (void *) & PyGSL_register_debug_flag                  ;\n     _PyGSL_API[PyGSL_vector_or_double_NUM                     ] = (void *) & PyGSL_vector_or_double                     ;\n     _PyGSL_API[PyGSL_warning_NUM                              ] = (void *) & PyGSL_warning                              ;\n     _PyGSL_API[PyGSL_pyint_to_int_NUM                         ] = (void *) & PyGSL_pyint_to_int                         ;\n     _PyGSL_API[PyGSL_vector_check_NUM                         ] = (void *) & PyGSL_vector_check                         ;\n     _PyGSL_API[PyGSL_matrix_check_NUM                         ] = (void *) & PyGSL_matrix_check                         ;\n     _PyGSL_API[PyGSL_array_check_NUM                          ] = (void *) & PyGSL_array_check                          ;\n\n}\n\nDL_EXPORT(void) initinit(void)\n{\n  PyObject *m = NULL, *d = NULL, *version=NULL, *date=NULL, *api = NULL;\n\n  m = Py_InitModule(\"pygsl.init\", initMethods);\n  import_array();\n  \n  \n  if(m == NULL){\n       fprintf(stderr, \"I could not init pygsl.init!\");\n       return;\n  }\n\n  d = PyModule_GetDict(m);\n  if(d == NULL){\n       fprintf(stderr, \"I could not get the module dict for  pygsl.init!\");\n       return;\n  }\n\n  PyGSL_init_api();\n  \n  if(PyGSL_init_errno() != 0){ \n       PyErr_SetString(PyExc_ImportError, \"Failed to init errno handling!\");\n  }\n  PyGSL_API = _PyGSL_API;\n  PyGSL_SET_ERROR_HANDLER();\n\n  api = PyCObject_FromVoidPtr((void *) PyGSL_API, NULL);\n  assert(api);\n  if (PyDict_SetItemString(d, \"_PYGSL_API\", api) != 0){\n       PyErr_SetString(PyExc_ImportError, \n\t\t       \"I could not add  _PYGSL_API!\");\n       return;\n  }\n\n  version = PyString_FromString(GSL_VERSION);\n  if(version == NULL){\n       fprintf(stderr, \"I could not create the version string for pygsl.init!\");\n       return;\n  }\n  if(PyDict_SetItemString(d, \"compiled_gsl_version\", version) != 0){\n       fprintf(stderr, \"I could not add the compile version string to the module dict of pygsl.init!\");\n       return;\n  }\n\n  version = PyString_FromString(gsl_version);\n  if(version == NULL){\n       fprintf(stderr, \"I could not create the version string for pygsl.init!\");\n       return;\n  }\n  if(PyDict_SetItemString(d, \"run_gsl_version\", version) != 0){\n       fprintf(stderr, \"I could not add the run version string to the module dict of pygsl.init!\");\n       return;\n  }\n\n  date = PyString_FromString(DATE \" \" TIME);\n  if(version == NULL){\n       fprintf(stderr, \"I could not create the date string for pygsl.init!\");\n       return;\n  }\n  if(PyDict_SetItemString(d, \"compile_date\", date) != 0){\n       fprintf(stderr, \"I could not add the date version string to the module dict of pygsl.init!\");\n       return;\n  }\n\n  if((debuglist = PyList_New(0)) == NULL){\n       fprintf(stderr, \"Failed to init Debug list!\\n\");\n  }\n  /*\n   * These functions will be moved to the approbriate modules and the user will\n   * have to call them explicitly when needed.\n   */\n  \n  return;\n}\n", "meta": {"hexsha": "d8106275cd753188cab47de5b5b6b20cbdd0d349", "size": 10501, "ext": "c", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/src/init/initmodule.c", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/src/init/initmodule.c", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/src/init/initmodule.c", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 38.6066176471, "max_line_length": 122, "alphanum_fraction": 0.6267974479, "num_tokens": 2874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20946969120038575, "lm_q2_score": 0.04084571941267692, "lm_q1q2_score": 0.008555940232231036}}
{"text": "/*\n  Copyright (c) 2016-2017 Hong Xu\n\n  This file is part of WCSPLift.\n\n  WCSPLift is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  WCSPLift is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with WCSPLift.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n/** \\file WCSPInstance.h\n *\n * Define the definition of WCSP instances and the constraints in it. Algorithms that can be applied\n * directly on WCSP instances, i.e., the min-sum message passing algorithm \\cite xkk17 and integer\n * linear programming \\cite xkk17a, are also included in this file.\n */\n\n#ifndef WCSPINSTANCE_H_\n#define WCSPINSTANCE_H_\n\n#include <array>\n#include <cstdint>\n#include <istream>\n#include <map>\n#include <numeric>\n#include <set>\n#include <stdexcept>\n#include <utility>\n#include <vector>\n\n#include <boost/dynamic_bitset.hpp>\n#include <boost/property_tree/json_parser.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <cblas.h>\n\n#include \"global.h\"\n#include \"RunningTime.h\"\n#include \"LinearProgramSolver.h\"\n\n/** \\brief Weighted constraint.\n *\n * This class describes a weighted constraint. It consists of the IDs of the variables as well as\n * how the weight corresponding to each assignment.\n *\n * \\tparam VarIdType The type of variable IDs. It must be an integer type and defaults to \\p\n * intmax_t.\n *\n * \\tparam WeightType The type of weights. It must be a numeric type and defaults to \\p double.\n *\n * \\tparam ValueType The type of values of all variables in the constraint. It should usually be a\n * bitset type and defaults to \\p boost::dynamic_bitset<>.\n */\ntemplate < class VarIdType = intmax_t,\n           class WeightType = double,\n           class ValueType = boost::dynamic_bitset<>,  // The type of the values to represent each constraint\n           class NonBooleanValueType = size_t>\nclass Constraint\n{\npublic:\n    /** Alias of \\p VarIDType. */\n    typedef VarIdType variable_id_t;\n\n    /** Alias of \\p ValueType. */\n    typedef ValueType value_t;\n\n    /** Alias of \\p WeightType. */\n    typedef WeightType weight_t;\n\n    /** Alias of \\p NonBooleanValueType. */\n    typedef NonBooleanValueType non_boolean_value_t;\n\nprivate:\n    // This class is only used for Polynomial key comparison. This function ensures keys with\n    // a smaller number of variables must precede larger number of variables.\n    class PolynomialKeyComparison\n    {\n    public:\n        bool operator () (const std::set<variable_id_t>& a, const std::set<variable_id_t>& b) const\n        {\n            if (a.size() > b.size())\n                return true;\n\n            if (a.size() < b.size())\n                return false;\n\n            return a < b;\n        }\n    };\npublic:\n    /** The polynomial form of constraints consisting of the coefficient of each term (each term is\n     * represented by an assignment of values to variables). */\n    typedef std::map<std::set<variable_id_t>, weight_t, PolynomialKeyComparison> Polynomial;\n\nprivate:\n    std::vector<variable_id_t> nonBooleanVariables;\n    std::vector<variable_id_t> variables;\n    std::map<value_t, weight_t> weights;\n    std::map<std::vector<non_boolean_value_t>, weight_t> nonBooleanWeights;\n\npublic:\n    /** Alias of \\p Constraint<VarIdType, WeightType, ValueType, NonBooleanValueType>, i.e., the\n     * class type itself. */\n    typedef Constraint<VarIdType, WeightType, ValueType, NonBooleanValueType> self_t;\n\n    /** \\brief Get the list of the IDs of non-Boolean variables in the constraint.\n     *\n     * \\return A list of variable IDs.\n     */\n    inline const std::vector<variable_id_t>& getNonBooleanVariables() const noexcept\n    {\n        return nonBooleanVariables;\n    }\n\n    /** \\brief Get the list of the IDs of variables in the constraint.\n     *\n     * \\return A list of variable IDs.\n     */\n    inline const std::vector<variable_id_t>& getVariables() const noexcept\n    {\n        return variables;\n    }\n\n    /** \\brief Get the ID of the <tt>i</tt>'th variable.\n     *\n     * \\param[in] i The index of the variable of which to get the ID.\n     *\n     * \\return The ID of the <tt>i</tt>'th variable.\n     */\n    inline variable_id_t getVariable(size_t i) const noexcept\n    {\n        return variables.at(i);\n    }\n\n    /** \\brief Set the IDs of the variables in the constraint from a \\p std::vector<variable_id_t>\n     * object.\n     *\n     * \\param[in] variables: A list of variable IDs to set.\n     */\n    inline void setVariables(const std::vector<variable_id_t>& variables) noexcept\n    {\n        this->variables = variables;\n        this->weights.clear();\n    }\n\n    /** \\brief Set the IDs of the non-Boolean variables in the constraint from a \\p\n     * std::vector<variable_id_t> object.\n     *\n     * \\param[in] variables: A list of variable IDs to set.\n     */\n    inline void setNonBooleanVariables(const std::vector<variable_id_t>& variables) noexcept\n    {\n        this->nonBooleanVariables = variables;\n        this->weights.clear();\n    }\n\n    /** \\brief Set the IDs of the variables in the constraint from a range of iterators.\n     *\n     * \\param[in] b the beginning iterator.\n     *\n     * \\param[in] e the ending iterator.\n     */\n    template<class Iter>\n    inline void setVariables(Iter b, Iter e) noexcept\n    {\n        variables.clear();\n        std::copy(b, e, std::back_inserter(variables));\n    }\n\n    /** \\brief Set the weight of a given assignment of values to variables specified by \\p v to \\p\n     * w.\n     *\n     * \\param[in] v An assignment of values to variables.\n     *\n     * \\param[in] w A weight.\n     *\n     * \\return A reference to the class object itself.\n     */\n    inline self_t& setWeight(const value_t& v, weight_t w)\n    {\n        weights[v] = w;\n        return *this;\n    }\n\n    /** \\brief Set the weight of a given assignment of values to non-Boolean variables specified by\n     * \\p v to \\p w.\n     *\n     * \\param[in] v An assignment of values to variables.\n     *\n     * \\param[in] w A weight.\n     *\n     * \\return A reference to the class object itself.\n     */\n    inline self_t& setWeight(const std::vector<non_boolean_value_t>& v, weight_t w)\n    {\n        nonBooleanWeights[v] = w;\n        return *this;\n    }\n\n    /** \\brief Get the weight of a given assignment of values to variables specified by \\p v.\n     *\n     * \\param[in] v The assignment of values to variables.\n     *\n     * \\return The weight of a given assignment of values to variables specified by \\p v.\n     */\n    inline weight_t getWeight(const value_t& v) const noexcept\n    {\n        auto it = weights.find(v);\n        if (it == weights.end()) // not found, return 0\n            return weight_t();\n\n        return it->second;\n    }\n\n    /** \\brief Get the weight of a given assignment of values to non-Boolean variables specified by\n     * \\p v.\n     *\n     * \\param[in] v The assignment of values to variables.\n     *\n     * \\return The weight of a given assignment of values to variables specified by \\p v.\n     */\n    inline weight_t getWeight(const std::vector<non_boolean_value_t>& v) const noexcept\n    {\n        auto it = nonBooleanWeights.find(v);\n        if (it == nonBooleanWeights.end()) // not found, return 0\n            return weight_t();\n\n        return it->second;\n    }\n\n    /** \\brief Get a map object that maps assignments of values to variables to weights.\n     *\n     * \\return A map object that maps assignments of values to variables to weights.\n     */\n    inline const std::map<value_t, weight_t> getWeights() const noexcept\n    {\n        return weights;\n    }\n\n    /** \\brief Represent the constraint using a \\p boost::property_tree::ptree object.\n     *\n     * \\param[out] t A \\p boost::property_tree::ptree object that represents the constraint.\n     */\n    void toPropertyTree(boost::property_tree::ptree& t) const\n    {\n        using namespace boost::property_tree;\n\n        t.clear();\n\n        // put the variables\n        ptree vs;\n        for (auto& v : variables)\n            vs.push_back(\n                std::make_pair(\"\", ptree(std::to_string(v))));\n\n        t.put_child(\"variables\", vs);\n\n        // put the weights\n        ptree ws;\n        for (auto& w : weights)\n        {\n            ptree we;\n\n            for (size_t i = 0; i < getVariables().size(); ++ i)\n            {\n                if (w.first[i])\n                    we.push_back(std::make_pair(\"\", ptree(\"1\")));\n                else\n                    we.push_back(std::make_pair(\"\", ptree(\"0\")));\n            }\n\n            we.push_back(std::make_pair(\"\", ptree(std::to_string(w.second))));\n\n            ws.push_back(std::make_pair(\"\", we));\n        }\n\n        t.put_child(\"weights\", ws);\n    }\n\n    /** \\brief Compute the coefficients of the polynomial converted from a constraint according to\n     * \\cite k08.\n     *\n     * \\param[out] p A Constraint::Polynomial object corresponding to the polynomial representation\n     * of the constraint.\n     */\n    void toPolynomial(Polynomial& p) const noexcept\n    {\n        size_t s = getVariables().size();\n\n        // we basically solve A * x = b\n\n        size_t max_int = ((size_t) 1) << s;\n\n        // matrix a\n        double * a = new double[max_int * max_int];\n        memset(a, 0, max_int * max_int * sizeof(double));\n\n/// \\cond\n#define ENTRY(a, x, y) a[(y) * max_int + (x)]\n/// \\endcond\n        // set the first column to 1\n        for (size_t i = 0; i < max_int; ++ i)\n            ENTRY(a, i, 0) = 1.0;\n        // Set the lower triangle. The row number corresponds to the assignments of variables, and\n        // the col number corresponds to terms of the polynomial in the following order:\n        // X_1, X_2, X_1 X_2, X_3, X_1 X_3, X_2 X_3, X_1 X_2 X_3...\n        for (size_t i = 1; i < max_int; ++ i)\n            for (size_t j = 1; j <= i; ++ j)\n                // (i|j)==i : the 1-bits integer i includes all the 1-bits of j\n                ENTRY(a, i, j) = ((i | j) == i) ? 1.0 : 0.0;\n#undef ENTRY\n\n        // assign the vector b\n        double * x = new double[max_int];\n        for (size_t i = 0; i < max_int; ++ i)\n            x[i] = getWeight(value_t(s, i));\n\n        cblas_dtrsv(CblasColMajor, CblasLower, CblasNoTrans, CblasUnit, max_int, a, max_int, x, 1);\n        delete[] a;\n\n        // Insert all the coefficients into the polynomial.\n        for (size_t i = 0; i < max_int; ++ i)\n        {\n            typename Polynomial::key_type k;\n\n            for (size_t j = 0; j < s; ++ j)\n                if ((((size_t) 1u) << j) & i)\n                    k.insert(getVariable(j));\n\n            p[k] += x[i];\n        }\n\n        delete[] x;\n    }\n};\n\n/** \\brief A WCSP instance.\n *\n * This class describes a WCSP instance. It consists a set of constraints.\n *\n * \\tparam VarIdType The type of variable IDs. It must be an integer type and defaults to \\p\n * intmax_t.\n *\n * \\tparam WeightType The type of weights. It must be a numeric type and defaults to \\p double.\n *\n * \\tparam ConstraintValueType The type of values of all variables in the constraints in the WCSP\n * instance. It should usually be a bitset type and defaults to \\p boost::dynamic_bitset<>.\n */\ntemplate <class VarIdType = intmax_t, class WeightType = double,\n          class ConstraintValueType = boost::dynamic_bitset<>,\n          class NonBooleanValueType = size_t>\nclass WCSPInstance\n{\npublic:\n    /** Alias of \\p VarIdType. */\n    typedef VarIdType variable_id_t;\n    /** Alias of \\p WeightType. */\n    typedef WeightType weight_t;\n    /** Alias of \\p ConstraintValueType. */\n    typedef ConstraintValueType constraint_value_t;\n    /** Alias of \\p NonBooleanValueType. */\n    typedef NonBooleanValueType non_boolean_value_t;\n\npublic:\n    /** Alias of the Constraint type in the WCSP instance, i.e., \\p\n     * Constraint<variable_id_t,weight_t,constraint_value_t>.\n     */\n    typedef Constraint<variable_id_t, weight_t, constraint_value_t> constraint_t;\n\nprivate:\n    std::vector<constraint_t> constraints;\n\n    // map from non-Boolean variables to their Boolean variable representations\n    std::vector<std::vector<variable_id_t> > nonBooleanVariables;\n\npublic:\n\n    /** \\brief Get the mapping from original variables to Boolean variables.\n     *\n     * \\return The mapping.\n     */\n    inline const std::vector<std::vector<variable_id_t> >& getNonBooleanVariables()\n        const noexcept\n    {\n        return nonBooleanVariables;\n    }\n\n    /** \\brief Display the mapping from original variables to Boolean variables.\n     */\n    inline void displayNonBooleanVariableMapping() const noexcept\n    {\n        std:: cout << \"--- Non-Boolean Variable Mapping BEGINS ---\" << std::endl;\n        for (auto i = 0; i < nonBooleanVariables.size(); ++ i)\n        {\n            std::cout << i << '\\t';\n            for (auto j : nonBooleanVariables[i])\n            {\n                std::cout << j << ' ';\n            }\n            std::cout << std::endl;\n        }\n        std:: cout << \"--- Non-Boolean Variable Mapping ENDS ---\" << std::endl;\n    }\n\n    /** \\brief Get the list of constraints.\n     *\n     * \\return A list of \\p constraint_t objects.\n     */\n    inline const std::vector<constraint_t>& getConstraints() const noexcept\n    {\n        return constraints;\n    }\n\n    /** \\brief Get the <tt>i</tt>'th constraint.\n     *\n     * \\param[in] i The index of the Constraint object to get.\n     *\n     * \\return The <tt>i</tt>'th constraint.\n     */\n    inline const constraint_t& getConstraint(size_t i) const noexcept\n    {\n        return constraints.at(i);\n    }\n\n    /** \\brief Compute the total weight corresponding to an assignment of values to all variables.\n     *\n     * \\param[in] assignments The assignment of values to all variables.\n     *\n     * \\return The computed total weight.\n     */\n    inline weight_t computeTotalWeight(\n        const std::map<variable_id_t, non_boolean_value_t>& assignments) const noexcept\n    {\n        weight_t tw = 0;\n\n        for (const auto& c : constraints)\n        {\n            std::vector<non_boolean_value_t> val(c.getNonBooleanVariables().size());\n            for (size_t i = 0; i < c.getNonBooleanVariables().size(); ++ i)\n            {\n                try\n                {\n                    val[i] = assignments.at(c.getNonBooleanVariables().at(i));\n                } catch (std::out_of_range& e)\n                {\n                    // Here, it means the variable assignments does not hold\n                    // c.getNonBooleanVariables().at(i) -- the CCG does not contain that variable.\n                    // This may well be that the variable itself is a \"dummy\" variable -- the value\n                    // of it does not affect the total weight. In this case, we always assign zero\n                    // (or anything else) to it.\n                    val[i] = 0;\n                }\n            }\n\n            tw += c.getWeight(val);\n        }\n\n        return tw;\n    }\n\npublic:\n    /** \\brief Load a problem instance from a stream.\n     *\n     * \\param[in] f The input stream.\n     */\n    void load(std::istream& f);\n\n    /** \\brief Load the problem in DIMACS format. The format specification is at\n     * http://graphmod.ics.uci.edu/group/WCSP_file_format\n     *\n     * \\param[in] f The input stream.\n     */\n    void loadDimacs(std::istream& f);\n\n    /** \\brief Load the problem in UAI format. The format specification is at\n     * http://www.hlt.utdallas.edu/~vgogate/uai14-competition/modelformat.html\n     *\n     * \\param[in] f The input stream.\n     */\n    void loadUAI(std::istream& f);\n\n    /** List of supported input file formats.\n     */\n    enum class Format\n    {\n        DIMACS,\n        UAI\n    };\n\n    /** \\brief Construct a WCSP instance from an input stream in a given format.\n     *\n     * \\param[in] f The input stream.\n     *\n     * \\param[in] format The format of \\p f.\n     */\n    WCSPInstance(std::istream& f, Format format)\n    {\n        switch (format)\n        {\n        case Format::DIMACS:\n            loadDimacs(f);\n            break;\n        case Format::UAI:\n            loadUAI(f);\n            break;\n        }\n    }\n\n    /** \\brief Convert this WCSP instance to a human-readable string.\n     *\n     * \\return The human-readable string.\n     */\n    std::string toString() const noexcept\n    {\n        std::stringstream ss;\n\n        ss << '{' << std::endl;\n        for (auto& c : constraints)\n        {\n            ss << c;\n        }\n\n        return ss.str();\n    }\n\n    /** \\brief Solve the WCSP instance using the min-sum message passing algorithm.\n     *\n     * \\param[in] delta The threshold for convergence determination. That is, the algorithm\n     * terminates iff all messages change within \\p delta compared with the previous iteration.\n     *\n     * \\return A solution to the WCSP instance.\n     */\n    std::map<variable_id_t, bool> solveUsingMessagePassing(weight_t delta) const noexcept\n    {\n        std::map<variable_id_t, std::set<const constraint_t*> > constraint_list_for_v;\n\n        // Initialize all messages.\n        std::map<std::pair<variable_id_t, const constraint_t*>, std::array<weight_t, 2> > msgs_v_to_c;\n        std::map<std::pair<const constraint_t*, variable_id_t>, std::array<weight_t, 2> > msgs_c_to_v;\n        for (const auto& c : constraints)\n        {\n            for (auto v : c.getVariables())\n            {\n                constraint_list_for_v[v].insert(&c);\n                msgs_v_to_c[std::make_pair(v, &c)] = {0, 0};\n                msgs_c_to_v[std::make_pair(&c, v)] = {0, 0};\n            }\n        }\n\n        bool converged = false;\n        uintmax_t num_iterations = 0;\n        do\n        {\n            if (RunningTime::GetInstance().isTimeOut())  // time's up\n                break;\n\n            ++ num_iterations;\n\n            converged = true;\n\n            auto msgs_v_to_c0 = msgs_v_to_c;\n            auto msgs_c_to_v0 = msgs_c_to_v;\n\n            // Update all the messages from variables to constraints.\n            for (auto& it : msgs_v_to_c)\n            {\n                auto v = it.first.first;\n                auto c = it.first.second;\n\n                std::array<weight_t, 2> m = {0, 0};\n\n                for (auto nc : constraint_list_for_v.at(v))\n                {\n                    if (nc != c)\n                    {\n                        const auto m_to_v = msgs_c_to_v0.find(std::make_pair(nc, v))->second;\n\n                        m[0] += m_to_v.at(0);\n                        m[1] += m_to_v.at(1);\n                    }\n                }\n\n                it.second = m;\n\n                // is it now convergent?\n                if (converged)\n                {\n                    auto old_m = msgs_v_to_c0.at(it.first);\n\n                    if (std::abs(old_m.at(0) - m.at(0)) > delta ||\n                        std::abs(old_m.at(1) - m.at(1)) > delta)\n                        converged = false;\n                }\n            }\n\n            // Update all the messages from constraints to variables.\n            for (auto& it : msgs_c_to_v)\n            {\n                auto c = it.first.first;\n                auto v = it.first.second;\n\n                std::vector<std::array<weight_t, 2> > m_to_c;\n                m_to_c.reserve(c->getVariables().size());\n                std::vector<variable_id_t> v_ids;\n                v_ids.reserve(c->getVariables().size());\n                size_t self_index;   // index of the variable itself\n                for (size_t i = 0; i < c->getVariables().size(); ++ i)\n                {\n                    auto nv = c->getVariable(i);\n\n                    m_to_c.push_back(msgs_v_to_c0.at(std::make_pair(nv, c)));\n                    v_ids.push_back(nv);\n\n                    if (nv == v)\n                        self_index = i;\n                }\n\n                std::array<weight_t, 2> m = {\n                    std::numeric_limits<weight_t>::max(), std::numeric_limits<weight_t>::max()\n                };\n\n                // TODO: Change the iteration which does not have an upper limit of number of bits.\n                for (unsigned long i = 0; i < (1ul << c->getVariables().size()); ++ i)\n                {\n                    constraint_value_t values(c->getVariables().size(), i);\n\n                    weight_t sum = c->getWeight(values);\n\n                    for (size_t j = 0; j < c->getVariables().size(); ++ j)\n                        if (c->getVariable(j) != v)\n                            sum += msgs_v_to_c0.at(\n                                std::make_pair(c->getVariable(j), c))[values[j] ? 1 : 0];\n\n                    size_t index_update = values[self_index] ? 1 : 0;\n\n                    if (m[index_update] > sum)\n                        m[index_update] = sum;\n                }\n\n                auto m_min = m[0] < m[1] ? m[0] : m[1];\n                m[0] -= m_min;\n                m[1] -= m_min;\n\n                it.second = m;\n\n                // is it now convergent?\n                if (converged)\n                {\n                    auto old_m = msgs_c_to_v0.at(it.first);\n\n                    if (std::abs(old_m.at(0) - m.at(0)) > delta ||\n                        std::abs(old_m.at(1) - m.at(1)) > delta)\n                        converged = false;\n                }\n            }\n        } while (!converged);\n\n        std::cout << \"Number of iterations: \" << num_iterations << std::endl;\n\n        // compute the variable values\n        std::map<variable_id_t, std::array<weight_t, 2> > assignments_w;\n\n        converged = true;\n        for (const auto& c : constraints)\n            for (auto v : c.getVariables())\n            {\n                assignments_w[v][0] += msgs_c_to_v[std::make_pair(&c, v)][0];\n                assignments_w[v][1] += msgs_c_to_v[std::make_pair(&c, v)][1];\n                if (isinf(assignments_w[v][0]) || isinf(assignments_w[v][1]))\n                    converged = false;\n            }\n\n        std::map<variable_id_t, bool> assignments;\n        for (const auto& a : assignments_w)\n            assignments[a.first] = a.second[0] > a.second[1] ? a.second[1] : a.second[0];\n\n        if (!converged)\n            std::cout << \"*** Message passing not converged! ***\" << std::endl;\n\n        return assignments;\n    }\n\n    /** \\brief Solve the WCSP instance using linear programming.\n     *\n     * \\param[in] lps The linear program solver to be used.\n     *\n     * \\return A solution to the WCSP instance.\n     */\n    std::map<variable_id_t, non_boolean_value_t> solveUsingLinearProgramming(\n        LinearProgramSolver& lps) const noexcept\n    {\n        lps.reset();\n        lps.setTimeLimit(RunningTime::GetInstance().getTimeLimit().count());\n\n        lps.setObjectiveType(LinearProgramSolver::ObjectiveType::MIN);\n\n        auto constraints = this->getConstraints();\n\n        // Every variable needs a unary constraint. This is the indices of all unary constraints.\n        std::vector<size_t> unary_indices(this->getNonBooleanVariables().size(),\n                                                 std::numeric_limits<size_t>::max());\n        size_t num_unary = 0;\n        for (size_t i = 0; i < constraints.size(); ++ i)\n        {\n            auto& vs = constraints.at(i).getVariables();\n            if (vs.size() == 1)  // unary constraint\n            {\n                unary_indices[vs.at(0)] = i;\n                ++ num_unary;\n            }\n        }\n        constraints.reserve(constraints.size() + unary_indices.size() - num_unary);\n        for (variable_id_t i = 0; i < unary_indices.size(); ++ i)\n        {\n            // no unary constraint for this var\n            if (unary_indices.at(i) == std::numeric_limits<size_t>::max())\n            {\n                constraint_t cons;\n                cons.setNonBooleanVariables(std::vector<variable_id_t>{i});\n                constraints.push_back(std::move(cons));\n                unary_indices[i] = constraints.size() - 1;\n            }\n        }\n\n        std::vector<std::vector<LinearProgramSolver::variable_id_t> > lp_variables(\n            constraints.size());\n\n        // add LP variables and constraints\n        for (size_t i = 0; i < constraints.size(); ++ i)\n        {\n            size_t num_values = 1;\n            // Cartesian product of all values\n            for (const auto& nbv : constraints.at(i).getNonBooleanVariables())\n                num_values *= nonBooleanVariables[nbv].size() + 1;\n            lp_variables[i].reserve(num_values);\n            for (size_t j = 0; j < num_values; ++ j)  // add all variables\n            {\n                std::vector<non_boolean_value_t> val;\n                val.reserve(constraints.at(i).getNonBooleanVariables().size());\n\n                size_t j0 = j;\n                for (const auto& nbv : constraints.at(i).getNonBooleanVariables())\n                {\n                    size_t d = nonBooleanVariables[nbv].size() + 1;\n                    val.push_back(j0 % d);\n                    j0 /= d;\n                }\n\n                lp_variables[i].push_back(lps.addVariable(constraints.at(i).getWeight(val)));\n            }\n\n            // Only one value in a WCSP constraint can take effect.\n            lps.addConstraint(lp_variables[i], std::vector<double>(num_values, 1.0), 1.0,\n                              LinearProgramSolver::ConstraintType::EQUAL);\n        }\n\n        // Add constraints that make sure LP variables that represent overlapped WCSP variables are\n        // consistent.\n        for (size_t i = 0; i < lp_variables.size(); ++ i)\n        {\n            for (size_t j : unary_indices)\n            {\n                if (j <= i)  // Don't do a pair twice.\n                    continue;\n\n                // Get the overlap map.\n                std::vector<std::pair<size_t, size_t> > overlapped_variables;\n\n                // Whether a variable is overlapping?\n                std::vector<bool> vs_overlap_p[2];\n                vs_overlap_p[0].resize(constraints.at(i).getNonBooleanVariables().size());\n                vs_overlap_p[1].resize(constraints.at(j).getNonBooleanVariables().size());\n                std::array<std::vector<size_t>, 2> domain_sizes;\n                domain_sizes[0].reserve(constraints.at(i).getNonBooleanVariables().size());\n                domain_sizes[1].reserve(constraints.at(j).getNonBooleanVariables().size());\n                std::vector<size_t> overlapped_domain_sizes;\n\n                for (size_t z = 0; z < 2; ++ z)\n                {\n                    size_t c = z ? j : i;\n                    for (size_t k = 0; k < constraints.at(c).getNonBooleanVariables().size();\n                         ++ k)\n                        domain_sizes[z].push_back(\n                            nonBooleanVariables[\n                                constraints.at(c).getNonBooleanVariables()[k]].size() + 1);\n                }\n\n                for (size_t k0 = 0; k0 < constraints.at(i).getNonBooleanVariables().size(); ++ k0)\n                    for (size_t k1 = 0; k1 < constraints.at(j).getNonBooleanVariables().size(); ++ k1)\n                    {\n                        if (constraints.at(i).getNonBooleanVariables()[k0] ==\n                            constraints.at(j).getNonBooleanVariables()[k1])\n                        {\n                            overlapped_variables.push_back(std::make_pair(k0, k1));\n                            overlapped_domain_sizes.push_back(\n                                nonBooleanVariables[\n                                    constraints.at(i).getNonBooleanVariables()[k0]].size() + 1\n                                );\n                            vs_overlap_p[0][k0] = true;\n                            vs_overlap_p[1][k1] = true;\n                            break;\n                        }\n                    }\n\n                std::vector<non_boolean_value_t> vs[2];\n                vs[0].resize(constraints.at(i).getNonBooleanVariables().size());\n                vs[1].resize(constraints.at(j).getNonBooleanVariables().size());\n\n                if (overlapped_domain_sizes.empty())  // no overlapping\n                    continue;\n                // Cartesian product of all values of overlapped variables\n                size_t num_values = std::accumulate(overlapped_domain_sizes.begin(),\n                                                    overlapped_domain_sizes.end(),\n                                                    1, std::multiplies<size_t>());\n\n                for (size_t k = 0; k < num_values; ++ k)\n                {\n                    size_t k0 = k;\n                    for (const auto& ov : overlapped_variables)\n                    {\n                        size_t d = nonBooleanVariables[\n                            constraints.at(i).getNonBooleanVariables()[ov.first]].size() + 1;\n                        non_boolean_value_t val = k0 % d;\n                        k0 /= d;\n                        vs[0][ov.first] = val;\n                        vs[1][ov.second] = val;\n                    }\n\n                    // non-overlapped variables\n                    std::array<std::vector<non_boolean_value_t>, 2> vs_non_overlapped;\n                    vs_non_overlapped[0].resize((vs[0].size() - overlapped_variables.size()));\n                    vs_non_overlapped[1].resize((vs[1].size() - overlapped_variables.size()));\n\n                    std::vector<LinearProgramSolver::variable_id_t> lp_vs;  // LP variables\n                    std::vector<double> coefs;\n\n                    for (size_t z = 0; z < 2; ++ z)\n                    {\n                        size_t l;\n                        do {\n                            for (l = 0; l < vs[z].size(); ++ l)\n                            {\n                                if (vs_overlap_p[z][l])\n                                    continue;\n\n                                ++ vs[z][l];\n                                if (vs[z][l] >= domain_sizes[z][l])\n                                    vs[z][l] = 0;\n                                else\n                                    break;\n                            }\n\n                            size_t index = 0;  // index corresponding to the variable values vs[z]\n                            size_t cur_base = 1;\n                            for (size_t m = 0; m < vs[z].size(); ++ m)\n                            {\n                                index += cur_base * vs[z][m];\n                                cur_base *= domain_sizes[z][m];\n                            }\n\n                            if (z == 0)\n                            {\n                                lp_vs.push_back(lp_variables[i][index]);\n                                coefs.push_back(1.0);\n                            }\n                            else\n                            {\n                                lp_vs.push_back(lp_variables[j][index]);\n                                coefs.push_back(-1.0);\n                            }\n                        } while (l != vs[z].size());\n                    }\n\n                    lps.addConstraint(lp_vs, coefs, 0.0,\n                                      LinearProgramSolver::ConstraintType::EQUAL);\n                }\n            }\n        }\n\n        std::vector<double> assignments;\n        lps.solve(assignments);\n\n        // Compute the solutions from assignments\n        std::map<variable_id_t, non_boolean_value_t> solution;\n        for (size_t i : unary_indices)\n            for (size_t j = 0; j < lp_variables[i].size(); ++ j)\n            {\n                if (assignments[lp_variables[i][j]] > 0.99)\n                {\n                    solution[constraints.at(i).getNonBooleanVariables().at(0)] = j;\n                    break;\n                }\n            }\n\n        return solution;\n    }\n};\n\ntemplate <class VarIdType, class WeightType, class ConstraintValueType, class NonBooleanValueType>\nvoid WCSPInstance<VarIdType, WeightType, ConstraintValueType, NonBooleanValueType>::loadDimacs(\n    std::istream& f)\n{\n    std::string line;\n    std::string tmp;\n    size_t max_domain_size;\n    size_t nv, nc; // number of variables, number of constraints\n\n    // first line: problem_name number_of_variables max_domain_size number_of_constraints\n    // global_upper_bound\n    std::getline(f, line);\n    std::istringstream ss(line);\n    ss >> tmp; // name\n    ss >> nv;\n    ss >> max_domain_size; // max domain size\n    ss >> nc;\n    ss >> tmp; // ignore global upper bound\n\n    // domain size of all variables\n    std::getline(f, line);\n    ss.clear();\n    ss.str(line);\n    variable_id_t cur_var_id = 0;\n    nonBooleanVariables.clear();\n    nonBooleanVariables.reserve(nv);\n    for (size_t i = 0; i < nv; ++ i)\n    {\n        size_t domain_size;\n        ss >> domain_size;\n        // Boolean variables corresponding to the current variable\n        std::vector<variable_id_t> vs(domain_size-1);\n        std::iota(vs.begin(), vs.end(), cur_var_id);\n        cur_var_id += vs.size();\n        nonBooleanVariables.push_back(std::move(vs));\n    }\n\n    constraints.clear();\n    constraints.resize(nc);\n\n    // iterate over constraints\n    for (size_t i = 0; i < nc; ++ i)\n    {\n        size_t arity;\n        weight_t default_cost;\n        size_t ntuples; // number of tuples not having the default cost\n        std::getline(f, line);\n        ss.clear();\n        ss.str(line);\n\n        ss >> arity;\n\n        // load the variables in the constraint\n        std::vector<variable_id_t> non_bool_variables;\n        non_bool_variables.reserve(arity);\n        // load the corresponding Boolean variables in the constraint\n        std::vector<variable_id_t> variables;\n        variables.reserve(arity*max_domain_size);\n        for (size_t j = 0; j < arity; ++ j)\n        {\n            variable_id_t vid;\n            ss >> vid;\n            non_bool_variables.push_back(vid);\n            const auto& nbv = nonBooleanVariables[vid];\n            variables.insert(variables.end(), nbv.begin(), nbv.end());\n        }\n        constraints[i].setVariables(std::move(variables));\n        constraints[i].setNonBooleanVariables(std::move(non_bool_variables));\n        ss >> default_cost;\n        // TODO: More efficient handling\n        if (default_cost > std::abs(1e-6))   // non-zero default cost\n        {\n            constraint_value_t values;\n            values.resize(constraints[i].getVariables().size());\n            unsigned long te = (1u << constraints[i].getVariables().size());\n            for (unsigned long l = 0; l < te; ++ l)\n            {\n                for (unsigned long k = 0; k < values.size(); ++ k)\n                    values.set(k, (l & (1u << k)) ? 1 : 0);\n                constraints[i].setWeight(values, default_cost);\n            }\n        }\n        ss >> ntuples;\n\n        // load the entries in the constraints\n        for (size_t j = 0; j < ntuples; ++ j)\n        {\n            weight_t cost;\n            constraint_value_t values;\n            values.resize(constraints[i].getVariables().size());\n            values.set();\n            std::vector<non_boolean_value_t> non_boolean_values(arity);\n            std::getline(f, line);\n            ss.clear();\n            ss.str(line);\n            for (size_t k = 0, cur_bit = 0; k < arity; ++ k)\n            {\n                int val;\n                ss >> val;\n                non_boolean_values[k] = val;\n                size_t bvs = nonBooleanVariables[constraints[i].getNonBooleanVariables()[k]].size();\n                if (bvs == 1)\n                    values.set(cur_bit ++, val ? true : false);\n                else\n                {\n                    if (val != 0)\n                        values.set(cur_bit + val - 1, false);\n                    cur_bit += bvs;\n                }\n            }\n            ss >> cost;\n            constraints[i].setWeight(std::move(non_boolean_values), cost);\n            constraints[i].setWeight(std::move(values), cost);\n        }\n    }\n}\n\ntemplate <class VarIdType, class WeightType, class ConstraintValueType, class NonBooleanValueType>\nvoid WCSPInstance<VarIdType, WeightType, ConstraintValueType, NonBooleanValueType>::loadUAI(\n    std::istream& f)\n{\n    std::string line;\n    std::string tmp;\n    size_t nv, nc; // number of variables, number of constraints\n\n    // first line: MARKOV, just ignore it\n    std::getline(f, tmp);\n\n    // second line: number of variables\n    {\n        std::getline(f, line);\n        std::istringstream ss(line);\n        ss >> nv; // number of variables\n    }\n\n    // third line: arity\n    {\n        std::getline(f, line);\n        std::istringstream ss(line);\n        variable_id_t cur_var_id = 0;\n        nonBooleanVariables.clear();\n        nonBooleanVariables.reserve(nv);\n        for (size_t i = 0; i < nv; ++ i)\n        {\n            size_t domain_size;\n            ss >> domain_size;\n            // Boolean varaibles corresponding to the current variable\n            std::vector<variable_id_t> vs(domain_size-1);\n            std::iota(vs.begin(), vs.end(), cur_var_id);\n            cur_var_id += vs.size();\n            nonBooleanVariables.push_back(std::move(vs));\n        }\n    }\n\n    // fourth line: number of constraints\n    {\n        std::getline(f, line);\n        std::istringstream ss(line);\n        ss >> nc;\n        constraints.clear();\n        constraints.resize(nc);\n    }\n\n    // iterate over constraints\n    for (size_t i = 0; i < nc; ++ i)\n    {\n        size_t arity;\n        std::getline(f, line);\n        std::istringstream ss(line);\n\n        ss >> arity;\n\n        // Load the variables in the constraint. We load it reversely because UAI format arrange\n        // their constraint value reversely as we do.\n        std::vector<variable_id_t> variables;\n        std::vector<variable_id_t> non_bool_variables(arity);\n\n        for (size_t j = 0; j < arity; ++ j)\n        {\n            variable_id_t vid;\n            ss >> vid;\n            non_bool_variables[arity-j-1] = vid;\n            variables.insert(variables.end(),\n                             nonBooleanVariables[vid].rbegin(),\n                             nonBooleanVariables[vid].rend());\n        }\n        std::reverse(variables.begin(), variables.end());\n\n        constraints[i].setVariables(std::move(variables));\n        constraints[i].setNonBooleanVariables(std::move(non_bool_variables));\n    }\n\n    // iterate over constraints\n    for (size_t i = 0; i < nc; ++ i)\n    {\n        size_t ntuples;\n        f >> ntuples;  // number of entries\n\n        // load the entries in the constraints\n        std::vector<weight_t> costs(ntuples);\n        for (size_t j = 0; j < ntuples; ++ j)\n            f >> costs[j];\n\n        // normalization constant\n        weight_t sum(std::accumulate(costs.begin(), costs.end(), weight_t()));\n\n        // set the value of each tuple\n        for (size_t j = 0; j < ntuples; ++ j)\n        {\n            costs[j] = -std::log(costs[j] / sum);\n            if (!std::isfinite(costs[j]))\n                costs[j] = 1e6;\n            constraint_value_t values;\n            std::vector<non_boolean_value_t> non_boolean_values;\n            non_boolean_values.reserve(constraints[i].getNonBooleanVariables().size());\n            size_t j0 = j;\n            for (const auto& nbv : constraints[i].getNonBooleanVariables())\n            {\n                auto d = nonBooleanVariables[nbv].size() + 1;\n                size_t cur_val = j0 % d;\n                non_boolean_values.push_back(cur_val);\n\n                if (d == 2)\n                    values.push_back(cur_val ? true : false);\n                else\n                {\n                    for (size_t k = 1; k < d; ++ k)\n                    {\n                        if (cur_val == k)\n                            values.push_back(false);\n                        else\n                            values.push_back(true);\n                    }\n                }\n                j0 /= d;\n            }\n            constraints[i].setWeight(std::move(values), costs[j]);\n            constraints[i].setWeight(std::move(non_boolean_values), costs[j]);\n        }\n    }\n}\n\n/** \\brief Write a Constraint object to a stream in a human-readable form.\n *\n * \\param[in] o The stream to write to.\n *\n * \\param[in] c The constraint object to be write to \\p o.\n *\n * \\return The stream \\p o.\n */\ntemplate <class ...T>\nstd::ostream& operator << (std::ostream& o, const Constraint<T...>& c)\n{\n    boost::property_tree::ptree t;\n    c.toPropertyTree(t);\n    boost::property_tree::write_json(o, t, true);\n    return o;\n}\n\n#endif /* WCSPINSTANCE_H_ */\n", "meta": {"hexsha": "d5f22849f5c4556ecdbaab8d1b1f49bce22842c0", "size": 40569, "ext": "h", "lang": "C", "max_stars_repo_path": "third_parties/wcsp/src/WCSPInstance.h", "max_stars_repo_name": "nandofioretto/py_dcop", "max_stars_repo_head_hexsha": "fb2dbc97b69360f5d1fb67d84749e44afcdf48c3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-08-06T08:55:36.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-28T12:54:21.000Z", "max_issues_repo_path": "third_parties/wcsp/src/WCSPInstance.h", "max_issues_repo_name": "nandofioretto/py_dcop", "max_issues_repo_head_hexsha": "fb2dbc97b69360f5d1fb67d84749e44afcdf48c3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_parties/wcsp/src/WCSPInstance.h", "max_forks_repo_name": "nandofioretto/py_dcop", "max_forks_repo_head_hexsha": "fb2dbc97b69360f5d1fb67d84749e44afcdf48c3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.763496144, "max_line_length": 109, "alphanum_fraction": 0.5389583179, "num_tokens": 9309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658973632215985, "lm_q2_score": 0.02333076974222782, "lm_q1q2_score": 0.008552820727996322}}
{"text": "/**\n */\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <gsl/gsl_spline.h>\n#include \"aXe_grism.h\"\n#include \"aXe_utils.h\"\n#include \"spce_PET.h\"\n#include \"inout_aper.h\"\n//#include \"trace_conf.h\"\n//#include \"aper_conf.h\"\n//#include \"spc_sex.h\"\n//#include \"disp_conf.h\"\n//#include \"spc_wl_calib.h\"\n//#include \"spce_binning.h\"\n//#include \"spc_spc.h\"\n//#include \"spce_pgp.h\"\n//#include \"spce_output.h\"\n//#include \"spc_FITScards.h\"\n//#include \"spc_flatfield.h\"\n#include \"fringe_conf.h\"\n#include \"fringe_utils.h\"\n\n#define AXE_IMAGE_PATH \"AXE_IMAGE_PATH\"\n#define AXE_OUTPUT_PATH \"AXE_OUTPUT_PATH\"\n#define AXE_CONFIG_PATH \"AXE_CONFIG_PATH\"\n\n\nint\nmain (int argc, char *argv[])\n{\n  char *opt;\n  char aper_file[MAXCHAR];\n  char aper_file_path[MAXCHAR];\n\n  char conf_file[MAXCHAR];\n  char conf_file_path[MAXCHAR];\n\n  char fconf_file[MAXCHAR];\n  char fconf_file_path[MAXCHAR];\n\n  char grism_file[MAXCHAR];\n  char grism_file_path[MAXCHAR];\n\n  char FF_file[MAXCHAR];\n  //char FF_file_path[MAXCHAR];\n\n  char OPET_file[MAXCHAR];\n  char OPET_file_path[MAXCHAR];\n\n  char BPET_file[MAXCHAR];\n  char BPET_file_path[MAXCHAR];\n\n  aperture_conf *conf=NULL;\n  fringe_conf   *fconf=NULL;\n\n  object **oblist;\n  observation *obs=NULL;\n\n  ap_pixel *OPET=NULL;\n  ap_pixel *BPET=NULL;\n\n  fitsfile *OPET_ptr=NULL;\n  fitsfile *BPET_ptr=NULL;\n\n  beam act_beam;\n\n  int index;\n  int i;\n  int f_status = 0;\n  int bckmode = 0;\n  int oaperID, obeamID;\n  int baperID, bbeamID;\n\n  if ((argc < 4) || (opt = get_online_option (\"help\", argc, argv)))\n    {\n      fprintf (stdout,\n\t       \"aXe_FRINGECORR Version %s:\\n\",RELEASE);\n      exit (1);\n    }\n\n  fprintf (stdout, \"aXe_FRINGECORR: Starting...\\n\\n\");\n\n  // copy the first parameter to the grism filename\n  index = 0;\n  strcpy (grism_file, argv[++index]);\n  build_path (AXE_IMAGE_PATH, grism_file, grism_file_path);\n\n  // copy the next parameter to the aXe configuration file\n  strcpy (conf_file, argv[++index]);\n  build_path (AXE_CONFIG_PATH, conf_file, conf_file_path);\n\n  // copy the next parameter to the fringe configuration file\n  strcpy (fconf_file, argv[++index]);\n  build_path (AXE_CONFIG_PATH, fconf_file, fconf_file_path);\n\n  // Determine if we are using the special bck mode\n  // In this mode, file names are handled diferently\n  if ((opt = get_online_option(\"bck\", argc, argv)))\n    bckmode = 1;\n\n  // load the aXe configuration file\n  conf = get_aperture_descriptor (conf_file_path);\n\n  // load the fringe configuration file\n  fconf = load_fringe_conf(fconf_file_path);\n\n  // Determine where the various extensions are in the FITS file\n  get_extension_numbers(grism_file_path, conf,conf->optkey1,conf->optval1);\n\n  // Build aperture file name\n  replace_file_extension (grism_file, aper_file, \".fits\",\n\t\t\t  \".OAF\", conf->science_numext);\n  build_path (AXE_OUTPUT_PATH, aper_file, aper_file_path);\n\n  // Build object PET file name\n  replace_file_extension (grism_file, OPET_file, \".fits\",\n\t\t\t  \".PET.fits\", conf->science_numext);\n  build_path (AXE_OUTPUT_PATH, OPET_file, OPET_file_path);\n\n  // build the background PET file name\n  // if necessary\n  if (bckmode)\n    {\n      replace_file_extension (grism_file, BPET_file, \".fits\",\n\t\t\t      \".BCK.PET.fits\", conf->science_numext);\n      build_path (AXE_OUTPUT_PATH, BPET_file, BPET_file_path);\n  }\n\n\n  // Give a short feedback on the filenames\n  // of the various input\n  fprintf (stdout, \"aXe_FRINGECORR: Grism image file name:          %s\\n\",\n\t   grism_file_path);\n  fprintf (stdout, \"aXe_FRINGECORR: Aperture file name:             %s\\n\",\n\t   aper_file_path);\n  fprintf (stdout, \"aXe_FRINGECORR: aXe configuration file name:    %s\\n\",\n\t   conf_file_path);\n  fprintf (stdout, \"aXe_FRINGECORR: Fringe configuration file name: %s\\n\",\n\t   fconf_file_path);\n  fprintf (stdout, \"aXe_FRINGECORR: Object PET file name:           %s\\n\",\n\t   OPET_file_path);\n  if (bckmode)\n    fprintf (stdout, \"aXe_FRINGECORR: Background PET file name:       %s\\n\",\n\t     BPET_file_path);\n\n  // check whether all necessary information\n  // is in place, provide defaults\n  check_fringe_conf(fconf);\n\n\n  fprintf (stdout, \"aXe_FRINGECORR: Loading object aperture list...\");\n  fflush(stdout);\n  oblist = file_to_object_list_seq (aper_file_path, obs);\n  fprintf (stdout,\"%d objects loaded.\\n\",object_list_size(oblist));\n\n  // Open the OPET file for reading/writing\n  fits_open_file (&OPET_ptr, OPET_file_path, READWRITE, &f_status);\n  if (f_status)\n    {\n      ffrprt (stdout, f_status);\n      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t   \"aXe_FRINGECORR: Could not open file: %s\\n\",\n\t\t   OPET_file_path);\n    }\n\n  // if necessary, open the background PET\n  if (bckmode)\n    {\n      fits_open_file (&BPET_ptr, BPET_file_path, READWRITE, &f_status);\n      if (f_status)\n\t{\n\t  ffrprt (stdout, f_status);\n\t  aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t       \"aXe_FRINGECORR: Could not open file: %s\\n\",\n\t\t       BPET_file_path);\n\t}\n    }\n\n  i = 0;\n  if ((oblist!=NULL) && (strcmp(FF_file,\"None\")))\n    {\n      while (1)\n\t{\n\t  // Get the PET for this object\n\t  OPET = get_ALL_from_next_in_PET(OPET_ptr, &oaperID, &obeamID);\n\t  if ((oaperID==-1) && (obeamID==-1))\n\t    break;\n\n\t  // Get the PET for this object\n\t  if (bckmode)\n\t    {\n\t      BPET = get_ALL_from_next_in_PET(BPET_ptr, &baperID, &bbeamID);\n\t      if ((baperID != oaperID) ||  (bbeamID != obeamID))\n\t\t{\n\t\t  fprintf(stderr, \"%i, %i, %i, %i\\n\", oaperID, baperID, obeamID, bbeamID);\n\t\t  aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t\t       \"aXe_FRINGECORR: The beam order in the\\n\"\n\t\t\t       \"object PET %s and the background PET\\n\"\n\t\t\t       \"%s does not coincide!\\n\",\n\t\t\t       OPET_file_path, BPET_file_path);\n\t\t}\n\t    }\n\n\t  // check whether there is content in the PET;\n\t  // skip it if empty\n\t  if (OPET==NULL)\n\t    continue;\n\n\t  // refer about the actual beam in process\n\t  fprintf (stdout, \"aXe_FRINGECORR: BEAM %d%c\",oaperID, BEAM(obeamID));\n\n\t  // get the beam information from the OAF\n\t  act_beam = find_beam_in_object_list(oblist, oaperID, obeamID);\n\t  fprintf (stdout, \" Done. \\n\");\n\n\t  fringe_correct_PET(fconf, act_beam, OPET, BPET);\n\n\t  // update PET table with the new FF info\n\t  {\n\t    char ID[60];\n\t    sprintf (ID, \"%d%c\", oaperID, BEAM (act_beam.ID));\n\t    add_ALL_to_PET (OPET, ID, OPET_ptr,1);\n\n\t    if (bckmode)\n\t      add_ALL_to_PET (BPET, ID, BPET_ptr,1);\n            }\n\n\t  // free the memory of the object pixels\n\t  if (OPET!=NULL)\n\t    {\n\t      free(OPET);\n\t      OPET=NULL;\n\t    }\n\n\t  // free the memory of the background pixels\n\t  if (BPET!=NULL)\n\t    {\n\t      free(BPET);\n\t      BPET=NULL;\n\t    }\n\t}\n    }\n\n  // free the object list\n  if (oblist!=NULL)\n    free_oblist (oblist);\n\n  // close the object PET fits-file\n  fits_close_file (OPET_ptr, &f_status);\n  if (f_status)\n    {\n      ffrprt (stderr, f_status);\n      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t   \"aXe_PETFF: \" \"Error closing PET: %s\\n\",\n\t\t   OPET_file_path);\n    }\n\n  // if necessary, close the object PET fits-file\n  if (bckmode)\n    {\n      fits_close_file (BPET_ptr, &f_status);\n      if (f_status)\n\t{\n\t  ffrprt (stderr, f_status);\n\t  aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t       \"aXe_PETFF: \" \"Error closing PET: %s\\n\",\n\t\t       BPET_file_path);\n\t}\n    }\n\n  fprintf (stdout, \"aXe_FRINGECORR: Done...\\n\\n\");\n  exit (0);\n}\n", "meta": {"hexsha": "14dc9dde0be6e086fbb474f09890b06311254308", "size": 7287, "ext": "c", "lang": "C", "max_stars_repo_path": "cextern/src/aXe_FRINGECORR.c", "max_stars_repo_name": "sosey/pyaxe", "max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cextern/src/aXe_FRINGECORR.c", "max_issues_repo_name": "sosey/pyaxe", "max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cextern/src/aXe_FRINGECORR.c", "max_forks_repo_name": "sosey/pyaxe", "max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3068592058, "max_line_length": 76, "alphanum_fraction": 0.664333745, "num_tokens": 2233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3242353859211693, "lm_q2_score": 0.026355352463744812, "lm_q1q2_score": 0.008545337877170739}}
{"text": "#pragma once\n\n#include <gsl\\gsl>\n#include <winrt\\Windows.Foundation.h>\n#include <d3d11.h>\n#include \"DrawableGameComponent.h\"\n#include \"MatrixHelper.h\"\n#include \"PointLight.h\"\n\nnamespace Library\n{\n\tclass ProxyModel;\n}\n\nnamespace Rendering\n{\n\tclass PointLightMaterial;\n\n\tclass PointLightDemo final : public Library::DrawableGameComponent\n\t{\n\tpublic:\n\t\tPointLightDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera);\n\t\tPointLightDemo(const PointLightDemo&) = delete;\n\t\tPointLightDemo(PointLightDemo&&) = default;\n\t\tPointLightDemo& operator=(const PointLightDemo&) = default;\t\t\n\t\tPointLightDemo& operator=(PointLightDemo&&) = default;\n\t\t~PointLightDemo();\n\n\t\tbool AnimationEnabled() const;\n\t\tvoid SetAnimationEnabled(bool enabled);\n\t\tvoid ToggleAnimation();\n\n\t\tfloat AmbientLightIntensity() const;\n\t\tvoid SetAmbientLightIntensity(float intensity);\n\n\t\tfloat PointLightIntensity() const;\n\t\tvoid SetPointLightIntensity(float intensity);\n\n\t\tconst DirectX::XMFLOAT3& LightPosition() const;\n\t\tconst DirectX::XMVECTOR LightPositionVector() const;\n\t\tvoid SetLightPosition(const DirectX::XMFLOAT3& position);\n\t\tvoid SetLightPosition(DirectX::FXMVECTOR position);\n\n\t\tfloat LightRadius() const;\n\t\tvoid SetLightRadius(float radius);\n\n\t\tfloat SpecularIntensity() const;\n\t\tvoid SetSpecularIntensity(float intensity);\n\n\t\tfloat SpecularPower() const;\n\t\tvoid SetSpecularPower(float power);\n\n\t\tvirtual void Initialize() override;\n\t\tvirtual void Update(const Library::GameTime& gameTime) override;\n\t\tvirtual void Draw(const Library::GameTime& gameTime) override;\n\n\tprivate:\n\t\tinline static const float RotationRate{ DirectX::XM_PI };\n\n\t\tstd::shared_ptr<PointLightMaterial> mMaterial;\n\t\tDirectX::XMFLOAT4X4 mWorldMatrix{ Library::MatrixHelper::Identity };\n\t\twinrt::com_ptr<ID3D11Buffer> mVertexBuffer;\n\t\twinrt::com_ptr<ID3D11Buffer> mIndexBuffer;\n\t\tstd::uint32_t mIndexCount{ 0 };\n\t\tLibrary::PointLight mPointLight;\n\t\tstd::unique_ptr<Library::ProxyModel> mProxyModel;\n\t\tfloat mModelRotationAngle{ 0.0f };\n\t\tbool mAnimationEnabled{ true };\n\t\tbool mUpdateMaterial{ true };\n\t};\n}", "meta": {"hexsha": "c8fcd269d5d9b11afa656905216b2cf99c3033bb", "size": 2073, "ext": "h", "lang": "C", "max_stars_repo_path": "source/4.1_Point_Light/PointLightDemo.h", "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/4.1_Point_Light/PointLightDemo.h", "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/4.1_Point_Light/PointLightDemo.h", "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1971830986, "max_line_length": 86, "alphanum_fraction": 0.7708634829, "num_tokens": 508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40733340004593027, "lm_q2_score": 0.020964241697424654, "lm_q1q2_score": 0.00853943584999665}}
{"text": "/** \\file\n * This file contains an implementation of a MPMC queue by Dmitry Vyukov. It is\n * largely the same as the original source except for: minor formatting\n * changes, movement to a namespace, use of alignas(X) instead of pad variables,\n * and use of dyn_array from the guideline support library instead of\n * `new char[size]`.\n */\n\n/*  Multi-producer/multi-consumer bounded queue.\n *  http://www.1024cores.net/home/lock-free-algorithms/queues/bounded-mpmc-queue\n *\n *  Copyright (c) 2010-2011, Dmitry Vyukov. All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions are met:\n *\n *     1. Redistributions of source code must retain the above copyright notice,\n *        this list of conditions and the following disclaimer.\n *     2. Redistributions in binary form must reproduce the above copyright\n *        notice, this list of conditions and the following disclaimer in the\n *        documentation and/or other materials provided with the distribution.\n *\n *  THIS SOFTWARE IS PROVIDED BY DMITRY VYUKOV \"AS IS\" AND ANY EXPRESS OR\n *  IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n *  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\n *  EVENT SHALL DMITRY VYUKOV OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n *  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n *  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n *  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n *  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *  The views and conclusions contained in the software and documentation are\n *  those of the authors and should not be interpreted as representing official\n *  policies, either expressed or implied, of Dmitry Vyukov.\n */\n\n#include <cassert>\n#include <atomic>\n\n#include <gsl_p/dyn_array.h>\n\nnamespace dvyukov {\n\n    /**\n     * A 'lockless' bounded multi-producer, multi-consumer queue\n     *\n     * Has the caveat that the queue can *appear* empty even if there are\n     * returned items within it as a single thread can block progression\n     * of the queue.\n     */\n    template<typename T>\n    class mpmc_bounded_queue {\n    public:\n        /**\n         * Constructs a bounded multi-producer, multi-consumer queue\n         *\n         * Note: Due to the algorithm used, buffer_size must be a power\n         *       of two and must be greater than or equal to two.\n         *\n         * @param buffer_size Number of spaces available in the queue.\n         */\n        mpmc_bounded_queue(size_t buffer_size)\n                : buffer_(buffer_size),\n                  buffer_mask_(buffer_size - 1) {\n\n            assert((buffer_size >= 2) &&\n                   ((buffer_size & (buffer_size - 1)) == 0));\n            for (size_t i = 0; i != buffer_size; i += 1) {\n                buffer_[i].sequence_.store(i, std::memory_order_relaxed);\n            }\n            enqueue_pos_.store(0, std::memory_order_relaxed);\n            dequeue_pos_.store(0, std::memory_order_relaxed);\n        }\n\n        /**\n         * Enqueues an item into the queue\n         *\n         * @param data Argument to place into the array\n         * @return false if the queue was full (and enqueing failed),\n         *         true otherwise\n         */\n        bool enqueue(const T& data) {\n            cell_t *cell;\n            size_t pos = enqueue_pos_.load(std::memory_order_relaxed);\n            for (; ;) {\n                cell = &buffer_[pos & buffer_mask_];\n                size_t seq = cell->sequence_.load(std::memory_order_acquire);\n                intptr_t dif = (intptr_t) seq - (intptr_t) pos;\n                if (dif == 0) {\n                    if (enqueue_pos_.compare_exchange_weak(pos, pos + 1,\n                                                           std::memory_order_relaxed)) {\n                        break;\n                    }\n                } else if (dif < 0) {\n                    return false;\n                } else {\n                    pos = enqueue_pos_.load(std::memory_order_relaxed);\n                }\n            }\n\n            cell->data_ = data;\n            cell->sequence_.store(pos + 1, std::memory_order_release);\n\n            return true;\n        }\n\n        /**\n         * Dequeues an item from the queue\n         *\n         * @param[out] data Reference to place item into\n         * @return false if the queue was empty (and dequeuing failed),\n         *         true if successful\n         */\n        bool dequeue(T& data) {\n            cell_t *cell;\n            size_t pos = dequeue_pos_.load(std::memory_order_relaxed);\n            for (; ;) {\n                cell = &buffer_[pos & buffer_mask_];\n                size_t seq = cell->sequence_.load(std::memory_order_acquire);\n                intptr_t dif = (intptr_t) seq - (intptr_t) (pos + 1);\n                if (dif == 0) {\n                    if (dequeue_pos_.compare_exchange_weak(pos, pos + 1,\n                                                           std::memory_order_relaxed)) {\n                        break;\n                    }\n                } else if (dif < 0) {\n                    return false;\n                } else {\n                    pos = dequeue_pos_.load(std::memory_order_relaxed);\n                }\n            }\n\n            data = cell->data_;\n            cell->sequence_.store(pos + buffer_mask_ + 1,\n                                  std::memory_order_release);\n\n            return true;\n        }\n\n    private:\n        struct cell_t {\n            std::atomic<size_t> sequence_;\n            T data_;\n        };\n\n        static const size_t cacheline_size = 64;\n        typedef char cacheline_pad_t [cacheline_size];\n\n        cacheline_pad_t pad0_;\n        gsl_p::dyn_array<cell_t> buffer_;\n        const size_t buffer_mask_;\n        cacheline_pad_t pad1_;\n        std::atomic<size_t> enqueue_pos_;\n        cacheline_pad_t pad2_;\n        std::atomic<size_t> dequeue_pos_;\n        cacheline_pad_t pad3_;\n\n        mpmc_bounded_queue(mpmc_bounded_queue const &);\n\n        void operator=(mpmc_bounded_queue const &);\n    };\n}\n", "meta": {"hexsha": "cf0a861f8db935b48c204804753e31e8793e99cb", "size": 6366, "ext": "h", "lang": "C", "max_stars_repo_path": "thirdparty/dvyukov/include/dvyukov/mpmc_bounded_queue.h", "max_stars_repo_name": "Chippiewill/Phosphor", "max_stars_repo_head_hexsha": "ef090fa5b331dd94301cd8562b24c78c0c2030f1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thirdparty/dvyukov/include/dvyukov/mpmc_bounded_queue.h", "max_issues_repo_name": "Chippiewill/Phosphor", "max_issues_repo_head_hexsha": "ef090fa5b331dd94301cd8562b24c78c0c2030f1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thirdparty/dvyukov/include/dvyukov/mpmc_bounded_queue.h", "max_forks_repo_name": "Chippiewill/Phosphor", "max_forks_repo_head_hexsha": "ef090fa5b331dd94301cd8562b24c78c0c2030f1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.5818181818, "max_line_length": 88, "alphanum_fraction": 0.5848256362, "num_tokens": 1396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25386100696924885, "lm_q2_score": 0.033589503231552416, "lm_q1q2_score": 0.008527065113958735}}
{"text": "/*\nCopyright 2010-2011, D. E. Shaw Research.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n* Redistributions of source code must retain the above copyright\n  notice, this list of conditions, and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright\n  notice, this list of conditions, and the following disclaimer in the\n  documentation and/or other materials provided with the distribution.\n\n* Neither the name of D. E. Shaw Research nor the names of its\n  contributors may be used to endorse or promote products derived from\n  this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n#include <gsl/gsl_randist.h>\n#include <stdio.h>\n#include \"Random123/philox.h\"\n#include \"Random123/threefry.h\"\n#include \"Random123/conventional/gsl_cbrng.h\"\n#include <assert.h>\n\n/* Exercise the GSL_CBRNG macro */\n\nGSL_CBRNG(cbrng, threefry4x64); /* creates gsl_rng_cbrng */\n\nint main(int argc, char **argv){\n    int i;\n    gsl_rng *r;\n    gsl_rng *rcopy;\n    unsigned long save, x;\n    unsigned long saved[5];\n    double sum = 0.;\n    (void)argc; (void)argv; /* unused */\n\n    r = gsl_rng_alloc(gsl_rng_cbrng);\n    assert (gsl_rng_min(r) == 0);\n    assert (gsl_rng_max(r) == 0xffffffffUL); // Not necessarily ~0UL\n    assert (gsl_rng_size(r) > 0);\n\n    printf(\"%s\\nulongs from %s in initial state\\n\", argv[0], gsl_rng_name(r));\n    for (i = 0; i < 5; i++) {\n\tx = gsl_rng_get(r);\n        saved[i] = x;\n\tprintf(\"%d: 0x%lx\\n\", i, x);\n\tassert(x != 0);\n    }\n    printf(\"uniforms from %s\\n\", gsl_rng_name(r));\n    for (i = 0; i < 5; i++) {\n        double z = gsl_rng_uniform(r);\n        sum += z;\n        printf(\"%d: %.4g\\n\", i, z);\n    }\n    assert( sum < 0.9*5 && sum > 0.1*5 && (long)\"sum must be reasonably close  to 0.5*number of trials\");\n    save = gsl_rng_get(r);\n\n    gsl_rng_set(r, 0xdeadbeef); /* set a non-zero seed */\n    printf(\"ulongs from %s after seed\\n\", gsl_rng_name(r));\n    for (i = 0; i < 5; i++) {\n\tx = gsl_rng_get(r);\n\tprintf(\"%d: 0x%lx\\n\", i, x);\n\tassert(x != 0);\n    }\n    /* make a copy of the total state */\n    rcopy = gsl_rng_alloc(gsl_rng_cbrng);\n    gsl_rng_memcpy(rcopy, r);\n    printf(\"uniforms from %s\\n\", gsl_rng_name(r));\n    sum = 0.;\n    for (i = 0; i < 5; i++) {\n        double x = gsl_rng_uniform(r);\n        double y = gsl_rng_uniform(rcopy);\n\tprintf(\"%d: %.4g\\n\", i, x);\n        sum += x;\n        assert(x == y);\n    }\n    assert(gsl_rng_get(r) != save);\n    assert( sum < 0.9*5 && sum > 0.1*5 && (long)\"sum must be reasonably close  to 0.5*number of trials\");\n\n    /* gsl_rng_set(*, 0) is supposed to recover the default seed */\n    gsl_rng_set(r, 0);\n    printf(\"ulongs from %s after restore to initial\\n\", gsl_rng_name(r));\n    for (i = 0; i < 5; i++) {\n\tx = gsl_rng_get(r);\n        assert( x == saved[i] );\n\tprintf(\"%d: 0x%lx\\n\", i, x);\n\tassert(x != 0);\n    }\n    printf(\"uniforms from %s\\n\", gsl_rng_name(r));\n    for (i = 0; i < 5; i++) {\n\tprintf(\"%d: %.4g\\n\", i, gsl_rng_uniform(r));\n    }\n    assert(gsl_rng_get(r) == save);\n    \n    gsl_rng_free (r);\n    return 0;\n}\n", "meta": {"hexsha": "986de7ce2b65c6fe21d920bf007950793f2d9adf", "size": 3918, "ext": "c", "lang": "C", "max_stars_repo_path": "Random123/examples/ut_gsl.c", "max_stars_repo_name": "Yeahhhh/module", "max_stars_repo_head_hexsha": "ea486690d2c7958b5bcdda9102ca14591952bc6f", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 44.0, "max_stars_repo_stars_event_min_datetime": "2015-03-28T06:48:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-09T11:29:00.000Z", "max_issues_repo_path": "Random123/examples/ut_gsl.c", "max_issues_repo_name": "Yeahhhh/module", "max_issues_repo_head_hexsha": "ea486690d2c7958b5bcdda9102ca14591952bc6f", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 68.0, "max_issues_repo_issues_event_min_datetime": "2015-08-21T11:28:54.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T22:14:13.000Z", "max_forks_repo_path": "Random123/examples/ut_gsl.c", "max_forks_repo_name": "Yeahhhh/module", "max_forks_repo_head_hexsha": "ea486690d2c7958b5bcdda9102ca14591952bc6f", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-06-22T19:25:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-15T18:20:06.000Z", "avg_line_length": 34.6725663717, "max_line_length": 105, "alphanum_fraction": 0.6584992343, "num_tokens": 1119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2538610069692489, "lm_q2_score": 0.03358950190134913, "lm_q1q2_score": 0.00852706477627199}}
{"text": "#ifndef KEXPR_H\n#define KEXPR_H\n#pragma warning( disable : 991)\n\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_complex.h>\n#include <plplot/plplot.h>\n#include <stdint.h>\n#include <stdio.h>\n#include \"stack.h\"\n#include \"utf8.h\"\n#include \"gdate.h\"\n#include <setjmp.h>\n\n#if defined(_MSC_VER) || defined(_WIN32)\n#include <Windows.h>\n#endif\n\n#include \"api.h\"\n\n\n#ifdef _DEBUG\nvoid ke_validate_parameter_qte(sml_t* sml, token_t *p, int nb_param, char * function_name);\nvoid ke_validate_parameter_vtype(sml_t* sml, token_t * p, int vtype, char * param_name, char * function_name);\nvoid ke_validate_parameter_ttype(sml_t* sml, token_t * p, int ttype, char * function_name);\nvoid ke_validate_parameter_not_null(sml_t* sml, token_t * p, void * ptr, char * param_name, char * function_name);\nvoid ke_validate_parameter_int_gt_zero(sml_t* sml, token_t * p, char * param_name, char * function_name);\n#endif // _DEBUG\n\n\nvoid ke_set_jump(sml_t *sml, int info);\nsml_t * ke_create_sml();\nvoid ke_free_sml(sml_t *sml);\nvoid ke_init_memory_count(sml_t *sml);\nchar *ke_mystrndup(sml_t *sml, char *src, size_t n);\nutf8 *ke_mystr(sml_t *sml, utf8 *src, size_t n);\ntoken_t * ke_get_tok(sml_t *sml);\ntoken_t * ke_get_tokidx(sml_t *sml, int idx);\nfncp ke_function(sml_t *sml, char * name);\ntypedef int(*DLLPROC)();\nvoid ke_import(sml_t *sml, char * s);\nvoid ke_load_dll(sml_t *sml, char * p);\nvoid ke_free_val(sml_t *sml);\nvoid ke_free_tokens(sml_t *sml);\nint ke_fill_list(sml_t *sml, kexpr_t *ke);\nvoid ke_set_int(sml_t* sml, token_t *tokp, int64_t y);\nvoid ke_set_real(sml_t* sml, token_t *tokp, double x);\nvoid ke_set_vector(sml_t * sml, token_t *tokp, gsl_vector * vecp);\nvoid ke_set_vector_int(sml_t * sml, token_t *tokp, gsl_vector_int * vecp);\nvoid ke_set_date(sml_t * sml, token_t *tokp, GDate_t * datep);\nvoid ke_set_matrix(sml_t *sml, token_t *tokp, gsl_matrix * matp);\nvoid ke_set_complex(sml_t *sml, token_t *tokp, gsl_complex complex);\nstatic void ke_set_str_internal(sml_t* sml, token_t *tokp, char * tmp);\nvoid ke_set_str(sml_t* sml, token_t *tokp, char *x);\nvoid ke_set_str_direct(sml_t *sml, token_t * e, char *x);\nvoid ke_set_record(sml_t *sml, token_t *source, token_t *dest);\nvoid ke_set_image(sml_t *sml, token_t *source, token_t *dest);\nvoid ke_set_file(sml_t *sml, token_t *source, token_t *dest);\nvoid ke_set_buffer(sml_t *sml, token_t *source, token_t *dest);\nvoid ke_print_one_stack(token_t * tokp);\nvoid ke_print_one(sml_t *sml, token_t * tokp);\nvoid ke_print_stack(sml_t* sml, token_t *tokp, int top);\nvoid ke_print_range(kexpr_t *kexpr, int starti, int endi);\nvoid ke_print_error_one(sml_t * sml, kexpr_t *kexpr, char * name, token_t * e, int itok);\nvoid ke_print(sml_t* sml, kexpr_t *kexpr);\nvoid ke_fill_hash(sml_t *sml);\ntoken_t* ke_get_val_index(sml_t *sml, int i);\nvoid ke_set_val_index(sml_t *sml, int i, token_t *tokp);\nvoid ke_set_val(sml_t* sml, token_t* e, token_t *q);\nvoid ke_push_stack(sml_t * sml, token_t * tokp, int *top);\nvoid ke_free_dll(sml_t * sml);\nvoid ke_destroy(sml_t *sml, kexpr_t *kexpr);\nvoid ke_free_hash(sml_t *sml);\nvoid ke_free(sml_t* sml, kexpr_t *kexpr);\nint peekfor(sml_t* sml);\nint popfor(sml_t* sml);\nvoid pushfor(sml_t* sml, int val);\n\n#endif\n\n", "meta": {"hexsha": "b1ff9c0f7b89b5dc8efff07808f601183630ed5c", "size": 3210, "ext": "h", "lang": "C", "max_stars_repo_path": "kexpr.h", "max_stars_repo_name": "vinej/sml", "max_stars_repo_head_hexsha": "115c007926ca80d51a37cdf887b5252338d8bc8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kexpr.h", "max_issues_repo_name": "vinej/sml", "max_issues_repo_head_hexsha": "115c007926ca80d51a37cdf887b5252338d8bc8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kexpr.h", "max_forks_repo_name": "vinej/sml", "max_forks_repo_head_hexsha": "115c007926ca80d51a37cdf887b5252338d8bc8d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.1463414634, "max_line_length": 114, "alphanum_fraction": 0.746728972, "num_tokens": 1082, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32766831395172374, "lm_q2_score": 0.025957355219835304, "lm_q1q2_score": 0.00850540281952941}}
{"text": "#ifndef OPENMC_TALLIES_FILTER_CELL_INSTANCE_H\n#define OPENMC_TALLIES_FILTER_CELL_INSTANCE_H\n\n#include <cstdint>\n#include <unordered_map>\n#include <vector>\n\n#include <gsl/gsl>\n\n#include \"openmc/cell.h\"\n#include \"openmc/tallies/filter.h\"\n\n\nnamespace openmc {\n\n//==============================================================================\n//! Specifies cell instances that tally events reside in.\n//==============================================================================\n\nclass CellInstanceFilter : public Filter {\npublic:\n  //----------------------------------------------------------------------------\n  // Constructors, destructors\n\n  CellInstanceFilter() = default;\n  CellInstanceFilter(gsl::span<CellInstance> instances);\n  ~CellInstanceFilter() = default;\n\n  //----------------------------------------------------------------------------\n  // Methods\n\n  std::string type() const override {return \"cellinstance\";}\n\n  void from_xml(pugi::xml_node node) override;\n\n  void get_all_bins(const Particle* p, int estimator, FilterMatch& match)\n  const override;\n\n  void to_statepoint(hid_t filter_group) const override;\n\n  std::string text_label(int bin) const override;\n\n  //----------------------------------------------------------------------------\n  // Accessors\n\n  const std::vector<CellInstance>& cell_instances() const { return cell_instances_; }\n\n  void set_cell_instances(gsl::span<CellInstance> instances);\n\nprivate:\n  //----------------------------------------------------------------------------\n  // Data members\n\n  //! The indices of the cells binned by this filter.\n  std::vector<CellInstance> cell_instances_;\n\n  //! A map from cell/instance indices to filter bin indices.\n  std::unordered_map<CellInstance, gsl::index, CellInstanceHash> map_;\n};\n\n} // namespace openmc\n\n#endif // OPENMC_TALLIES_FILTER_CELL_INSTANCE_H\n", "meta": {"hexsha": "1b2cdd425e356cadc682b83e74e755fb0910b232", "size": 1841, "ext": "h", "lang": "C", "max_stars_repo_path": "include/openmc/tallies/filter_cell_instance.h", "max_stars_repo_name": "PullRequest-Agent/openmc", "max_stars_repo_head_hexsha": "de99faefc93fe46a48fb4c5abcb4b88fe0eec174", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-05T00:08:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-05T00:08:39.000Z", "max_issues_repo_path": "include/openmc/tallies/filter_cell_instance.h", "max_issues_repo_name": "norberto-schmidt/openmc-surftrack", "max_issues_repo_head_hexsha": "8a1b9d0350dcfc036a08023f22daf7c4a508221b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/openmc/tallies/filter_cell_instance.h", "max_forks_repo_name": "norberto-schmidt/openmc-surftrack", "max_forks_repo_head_hexsha": "8a1b9d0350dcfc036a08023f22daf7c4a508221b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.765625, "max_line_length": 85, "alphanum_fraction": 0.5589353612, "num_tokens": 340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21733752104706247, "lm_q2_score": 0.03904829552194686, "lm_q1q2_score": 0.00848665974985304}}
{"text": "//\n// Created by Tobias on 10/2/2020.\n//\n\n#ifndef SD3D_ORBITCAMERACONTROLLER_H\n#define SD3D_ORBITCAMERACONTROLLER_H\n\n#include <GLFW/glfw3.h>\n#include <gsl-lite/gsl-lite.hpp>\n\n#pragma warning(push, 0)\n\n#include <glm/glm.hpp>\n#include <glm/gtc/matrix_transform.hpp>\n\n#pragma warning(pop)\n\n#include \"../graphics/Camera.h\"\n\nclass OrbitCameraController {\npublic:\n\tstruct OrbitCamSettings {\n\t\tglm::vec3 target{};\n\n\t\tfloat dist{};\n\t\tfloat minDist{};\n\t\tfloat maxDist{};\n\t\tfloat scrollSpeed{};\n\n\t\tfloat speed{};\n\t\tfloat deceleration{};\n\n\t\tOrbitCamSettings(const glm::vec3 &target, float dist, float speed,\n\t\t\t\t\t\t float deceleration = 0.05f) :\n\t\t\tOrbitCamSettings{target, dist,  dist,        dist,\n\t\t\t\t\t\t\t 0.0f,   speed, deceleration} {}\n\n\t\tOrbitCamSettings(const glm::vec3 &target, float dist, float minDist,\n\t\t\t\t\t\t float maxDist, float scrollSpeed, float speed,\n\t\t\t\t\t\t float deceleration = 0.05f) :\n\t\t\ttarget{target},\n\t\t\tdist{dist},\n\t\t\tminDist{minDist},\n\t\t\tmaxDist{maxDist},\n\t\t\tscrollSpeed{scrollSpeed},\n\t\t\tspeed{speed},\n\t\t\tdeceleration{deceleration} {}\n\t};\n\nprivate:\n\t// split mouse vector in 2 directions\n\t// x -> theta\n\t// y -> phi\n\n\tglm::vec3 m_target{};\n\n\tfloat m_dist{};\n\tfloat m_minDist{};\n\tfloat m_maxDist{};\n\tfloat m_scrollSpeed{};\n\n\tfloat m_yaw{-90.0f};\n\tfloat m_pitch{};\n\n\tglm::vec2 m_moveVec{};\n\n\tfloat m_deceleration{0.05f};\n\tfloat m_speed{};\n\n\tCamera m_cam;\n\n\t// for settings window\nprivate:\n\tfloat m_fovTemp;\n\n\tfloat m_fovSaved;\n\tOrbitCamSettings m_settingsSaved;\n\npublic:\n\tOrbitCameraController(Camera &&cam, const OrbitCamSettings &settings) :\n\t\tm_target{settings.target},\n\t\tm_dist{settings.dist},\n\t\tm_minDist{settings.minDist},\n\t\tm_maxDist{settings.maxDist},\n\t\tm_scrollSpeed{settings.scrollSpeed},\n\t\tm_deceleration{settings.deceleration},\n\t\tm_speed{settings.speed},\n\t\tm_cam{cam},\n\t\tm_fovTemp{gsl::narrow_cast<float>(m_cam.fov())},\n\t\tm_fovSaved{m_fovTemp},\n\t\tm_settingsSaved{settings} {}\n\n\tvoid update(float deltaTime);\n\n\t[[nodiscard]] const Camera &ccam() const { return m_cam; }\n\t[[nodiscard]] Camera &cam() { return m_cam; };\n\n\tvoid rotate(double dX, double dY);\n\n\tvoid zoom(double dScroll);\n\n\t[[nodiscard]] float min_dist() const { return m_minDist; }\n\n\t[[nodiscard]] float max_dist() const { return m_maxDist; }\n\n\tvoid set_min_dist(float val) { m_minDist = val; }\n\n\tvoid set_max_dist(float val) { m_maxDist = val; }\n\n\tvoid settings_gui(bool &show, glm::vec3 &clearCol);\n\n\tvoid reset_settings() {\n\t\tm_target = m_settingsSaved.target;\n\t\tm_dist = m_settingsSaved.dist;\n\t\tm_minDist = m_settingsSaved.minDist;\n\t\tm_maxDist = m_settingsSaved.maxDist;\n\t\tm_scrollSpeed = m_settingsSaved.scrollSpeed;\n\t\tm_deceleration = m_settingsSaved.deceleration;\n\t\tm_speed = m_settingsSaved.speed;\n\n\t\tm_fovTemp = m_fovSaved;\n\t\tm_cam.set_fov(m_fovTemp);\n\t}\n};\n\n#endif // SD3D_ORBITCAMERACONTROLLER_H\n", "meta": {"hexsha": "1bc9ee3705e00e09cfaabbb779549fb614d35f07", "size": 2790, "ext": "h", "lang": "C", "max_stars_repo_path": "src/controls/OrbitCameraController.h", "max_stars_repo_name": "TNGraphics/SD3D", "max_stars_repo_head_hexsha": "380bbc233c1099f76b73d8145a4518d2ba53a7a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/controls/OrbitCameraController.h", "max_issues_repo_name": "TNGraphics/SD3D", "max_issues_repo_head_hexsha": "380bbc233c1099f76b73d8145a4518d2ba53a7a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/controls/OrbitCameraController.h", "max_forks_repo_name": "TNGraphics/SD3D", "max_forks_repo_head_hexsha": "380bbc233c1099f76b73d8145a4518d2ba53a7a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.968503937, "max_line_length": 72, "alphanum_fraction": 0.7132616487, "num_tokens": 798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2720245392906821, "lm_q2_score": 0.03114382794942887, "lm_q1q2_score": 0.008471885449691657}}
{"text": "/* vector/gsl_vector_ulong.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#ifndef __GSL_VECTOR_ULONG_H__\n#define __GSL_VECTOR_ULONG_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_block_ulong.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size;\n  size_t stride;\n  unsigned long *data;\n  gsl_block_ulong *block;\n  int owner;\n} \ngsl_vector_ulong;\n\ntypedef struct\n{\n  gsl_vector_ulong vector;\n} _gsl_vector_ulong_view;\n\ntypedef _gsl_vector_ulong_view gsl_vector_ulong_view;\n\ntypedef struct\n{\n  gsl_vector_ulong vector;\n} _gsl_vector_ulong_const_view;\n\ntypedef const _gsl_vector_ulong_const_view gsl_vector_ulong_const_view;\n\n\n/* Allocation */\n\ngsl_vector_ulong *gsl_vector_ulong_alloc (const size_t n);\ngsl_vector_ulong *gsl_vector_ulong_calloc (const size_t n);\n\ngsl_vector_ulong *gsl_vector_ulong_alloc_from_block (gsl_block_ulong * b,\n                                                     const size_t offset, \n                                                     const size_t n, \n                                                     const size_t stride);\n\ngsl_vector_ulong *gsl_vector_ulong_alloc_from_vector (gsl_vector_ulong * v,\n                                                      const size_t offset, \n                                                      const size_t n, \n                                                      const size_t stride);\n\nvoid gsl_vector_ulong_free (gsl_vector_ulong * v);\n\n/* Views */\n\n_gsl_vector_ulong_view \ngsl_vector_ulong_view_array (unsigned long *v, size_t n);\n\n_gsl_vector_ulong_view \ngsl_vector_ulong_view_array_with_stride (unsigned long *base,\n                                         size_t stride,\n                                         size_t n);\n\n_gsl_vector_ulong_const_view \ngsl_vector_ulong_const_view_array (const unsigned long *v, size_t n);\n\n_gsl_vector_ulong_const_view \ngsl_vector_ulong_const_view_array_with_stride (const unsigned long *base,\n                                               size_t stride,\n                                               size_t n);\n\n_gsl_vector_ulong_view \ngsl_vector_ulong_subvector (gsl_vector_ulong *v, \n                            size_t i, \n                            size_t n);\n\n_gsl_vector_ulong_view \ngsl_vector_ulong_subvector_with_stride (gsl_vector_ulong *v, \n                                        size_t i,\n                                        size_t stride,\n                                        size_t n);\n\n_gsl_vector_ulong_const_view \ngsl_vector_ulong_const_subvector (const gsl_vector_ulong *v, \n                                  size_t i, \n                                  size_t n);\n\n_gsl_vector_ulong_const_view \ngsl_vector_ulong_const_subvector_with_stride (const gsl_vector_ulong *v, \n                                              size_t i, \n                                              size_t stride,\n                                              size_t n);\n\n/* Operations */\n\nunsigned long gsl_vector_ulong_get (const gsl_vector_ulong * v, const size_t i);\nvoid gsl_vector_ulong_set (gsl_vector_ulong * v, const size_t i, unsigned long x);\n\nunsigned long *gsl_vector_ulong_ptr (gsl_vector_ulong * v, const size_t i);\nconst unsigned long *gsl_vector_ulong_const_ptr (const gsl_vector_ulong * v, const size_t i);\n\nvoid gsl_vector_ulong_set_zero (gsl_vector_ulong * v);\nvoid gsl_vector_ulong_set_all (gsl_vector_ulong * v, unsigned long x);\nint gsl_vector_ulong_set_basis (gsl_vector_ulong * v, size_t i);\n\nint gsl_vector_ulong_fread (FILE * stream, gsl_vector_ulong * v);\nint gsl_vector_ulong_fwrite (FILE * stream, const gsl_vector_ulong * v);\nint gsl_vector_ulong_fscanf (FILE * stream, gsl_vector_ulong * v);\nint gsl_vector_ulong_fprintf (FILE * stream, const gsl_vector_ulong * v,\n\t\t\t      const char *format);\n\nint gsl_vector_ulong_memcpy (gsl_vector_ulong * dest, const gsl_vector_ulong * src);\n\nint gsl_vector_ulong_reverse (gsl_vector_ulong * v);\n\nint gsl_vector_ulong_swap (gsl_vector_ulong * v, gsl_vector_ulong * w);\nint gsl_vector_ulong_swap_elements (gsl_vector_ulong * v, const size_t i, const size_t j);\n\nunsigned long gsl_vector_ulong_max (const gsl_vector_ulong * v);\nunsigned long gsl_vector_ulong_min (const gsl_vector_ulong * v);\nvoid gsl_vector_ulong_minmax (const gsl_vector_ulong * v, unsigned long * min_out, unsigned long * max_out);\n\nsize_t gsl_vector_ulong_max_index (const gsl_vector_ulong * v);\nsize_t gsl_vector_ulong_min_index (const gsl_vector_ulong * v);\nvoid gsl_vector_ulong_minmax_index (const gsl_vector_ulong * v, size_t * imin, size_t * imax);\n\nint gsl_vector_ulong_add (gsl_vector_ulong * a, const gsl_vector_ulong * b);\nint gsl_vector_ulong_sub (gsl_vector_ulong * a, const gsl_vector_ulong * b);\nint gsl_vector_ulong_mul (gsl_vector_ulong * a, const gsl_vector_ulong * b);\nint gsl_vector_ulong_div (gsl_vector_ulong * a, const gsl_vector_ulong * b);\nint gsl_vector_ulong_scale (gsl_vector_ulong * a, const double x);\nint gsl_vector_ulong_add_constant (gsl_vector_ulong * a, const double x);\n\nint gsl_vector_ulong_isnull (const gsl_vector_ulong * v);\n\nextern int gsl_check_range;\n\n#ifdef HAVE_INLINE\n\nextern inline\nunsigned long\ngsl_vector_ulong_get (const gsl_vector_ulong * v, const size_t i)\n{\n#ifndef GSL_RANGE_CHECK_OFF\n  if (i >= v->size)\n    {\n      GSL_ERROR_VAL (\"index out of range\", GSL_EINVAL, 0);\n    }\n#endif\n  return v->data[i * v->stride];\n}\n\nextern inline\nvoid\ngsl_vector_ulong_set (gsl_vector_ulong * v, const size_t i, unsigned long x)\n{\n#ifndef GSL_RANGE_CHECK_OFF\n  if (i >= v->size)\n    {\n      GSL_ERROR_VOID (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  v->data[i * v->stride] = x;\n}\n\nextern inline\nunsigned long *\ngsl_vector_ulong_ptr (gsl_vector_ulong * v, const size_t i)\n{\n#ifndef GSL_RANGE_CHECK_OFF\n  if (i >= v->size)\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return (unsigned long *) (v->data + i * v->stride);\n}\n\nextern inline\nconst unsigned long *\ngsl_vector_ulong_const_ptr (const gsl_vector_ulong * v, const size_t i)\n{\n#ifndef GSL_RANGE_CHECK_OFF\n  if (i >= v->size)\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return (const unsigned long *) (v->data + i * v->stride);\n}\n\n\n#endif /* HAVE_INLINE */\n\n__END_DECLS\n\n#endif /* __GSL_VECTOR_ULONG_H__ */\n\n\n", "meta": {"hexsha": "3269205933ae0315d30f963782ef42c13b0e7e6b", "size": 7189, "ext": "h", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/vector/gsl_vector_ulong.h", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/vector/gsl_vector_ulong.h", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/vector/gsl_vector_ulong.h", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 31.6696035242, "max_line_length": 108, "alphanum_fraction": 0.6793712616, "num_tokens": 1659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.334589441253186, "lm_q2_score": 0.025178843986520892, "lm_q1q2_score": 0.008424575340851169}}
{"text": "#ifndef PRK_PETSC_H_\n#define PRK_PETSC_H_\n\n#define PRK_PETSC_USE_MPI 1\n\n#ifdef PRK_PETSC_USE_MPI\n#include <mpi.h>\n#endif\n\n#include <petsc.h>\n#include <petscsys.h>\n#include <petscvec.h>\n#include <petscmat.h>\n\n#endif // PRK_PETSC_H_\n", "meta": {"hexsha": "3478c765e9d09095ab7efade4cef43eb101a8393", "size": 231, "ext": "h", "lang": "C", "max_stars_repo_path": "C1z/prk_petsc.h", "max_stars_repo_name": "hattom/Kernels", "max_stars_repo_head_hexsha": "dae34b73235ccbf150d9b0ed5fb480b924789383", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 346.0, "max_stars_repo_stars_event_min_datetime": "2015-06-07T19:55:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T07:55:10.000Z", "max_issues_repo_path": "C1z/prk_petsc.h", "max_issues_repo_name": "hattom/Kernels", "max_issues_repo_head_hexsha": "dae34b73235ccbf150d9b0ed5fb480b924789383", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 202.0, "max_issues_repo_issues_event_min_datetime": "2015-06-16T15:28:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-06T18:26:13.000Z", "max_forks_repo_path": "C1z/prk_petsc.h", "max_forks_repo_name": "hattom/Kernels", "max_forks_repo_head_hexsha": "dae34b73235ccbf150d9b0ed5fb480b924789383", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 101.0, "max_forks_repo_forks_event_min_datetime": "2015-06-15T22:06:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-13T02:56:02.000Z", "avg_line_length": 14.4375, "max_line_length": 27, "alphanum_fraction": 0.7619047619, "num_tokens": 79, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14223188046612723, "lm_q2_score": 0.05921024700601515, "lm_q1q2_score": 0.008421584774529414}}
{"text": "#pragma once\n#include \"nkg_point.h\"\n#include \"nkg_rect.h\"\n#include \"nk_essential.h\"\n#include \"utility/types.h\"\n#include \"utility/c++std/string_view.h\"\n#include <nuklear.h>\n#include <gsl/gsl>\n\nnamespace cws80 {\n\n// drawing\nvoid im_draw_point(nk_command_buffer *out, f32 x, f32 y, nk_color color);\nvoid im_fill_polygon(nk_command_buffer *out, gsl::span<const im_pointf> points, nk_color color);\nvoid im_draw_image(nk_command_buffer *out, im_rectf rect, const im_texture &tex,\n                   nk_color color);\nvoid im_draw_tiled_image(nk_command_buffer *out, im_rectf rect,\n                         const im_texture &tex, nk_color color);\nvoid im_draw_title_box(nk_context *ctx, im_rectf bounds, cxx::string_view title,\n                       im_rectf *content_bounds = nullptr);\nvoid im_draw_title_box_alt(nk_context *ctx, im_rectf bounds, cxx::string_view title);\nvoid im_draw_led_screen(nk_context *ctx, im_rectf bounds, cxx::string_view text,\n                        im_pointf textoff);\n\n// drawing in screen coordinates\nvoid ims_stroke_line(nk_context *ctx, f32 x0, f32 y0, f32 x1, f32 y1,\n                     f32 line_thickness, nk_color color);\nvoid ims_stroke_rect(nk_context *ctx, im_rectf rect, f32 rounding,\n                     f32 line_thickness, nk_color color);\nvoid ims_fill_rect(nk_context *ctx, im_rectf rect, f32 rounding, nk_color color);\nvoid ims_fill_polygon(nk_context *ctx, gsl::span<const im_pointf> points, nk_color color);\nvoid ims_draw_image(nk_context *ctx, im_rectf rect, const im_texture &tex, nk_color color);\nvoid ims_draw_tiled_image(nk_context *ctx, im_rectf rect, const im_texture &tex,\n                          nk_color color);\nvoid ims_draw_text(nk_context *ctx, im_rectf rect, const char *text, int len,\n                   const nk_user_font *fnt, nk_color bg, nk_color fg);\nvoid ims_push_scissor(nk_context *ctx, im_rectf rect);\n//\nvoid ims_draw_title_box(nk_context *ctx, im_rectf bounds, cxx::string_view title,\n                        im_rectf *content_bounds = nullptr);\nvoid ims_draw_title_box_alt(nk_context *ctx, im_rectf bounds, cxx::string_view title);\nvoid ims_draw_led_screen(nk_context *ctx, im_rectf bounds,\n                         cxx::string_view text, im_pointf textoff);\n\n// text\nf32 im_text_width(const nk_user_font *fnt, cxx::string_view text);\n\n}  // namespace cws80\n", "meta": {"hexsha": "2ec8cfcc17b37c699962f0082b656758d5fff1d2", "size": 2330, "ext": "h", "lang": "C", "max_stars_repo_path": "sources/ui/detail/nk_draw.h", "max_stars_repo_name": "jpcima/cws80", "max_stars_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-05-20T19:27:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-03T04:21:53.000Z", "max_issues_repo_path": "sources/ui/detail/nk_draw.h", "max_issues_repo_name": "jpcima/cws80", "max_issues_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-05-21T12:56:22.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-23T21:33:33.000Z", "max_forks_repo_path": "sources/ui/detail/nk_draw.h", "max_forks_repo_name": "jpcima/cws80", "max_forks_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.5510204082, "max_line_length": 96, "alphanum_fraction": 0.7175965665, "num_tokens": 605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32423539898095244, "lm_q2_score": 0.02595735418376027, "lm_q1q2_score": 0.008416293090261406}}
{"text": "#pragma once\n\n#include <thrust/iterator/counting_iterator.h>\n#include <thrust/iterator/transform_iterator.h>\n\n#include <cuda/runtime_api.hpp>\n\n#include <gsl-lite/gsl-lite.hpp>\n\n#include <cub/cub.cuh>\n\n#include <thrustshift/math.h>\n#include <thrustshift/not-a-vector.h>\n\nnamespace cub {\n\ntemplate <typename _UnsignedBits, typename T>\nstruct BaseTraits<SIGNED_INTEGER,\n                  false,\n                  false,\n                  _UnsignedBits,\n                  thrustshift::AbsView<T>> {\n\ttypedef _UnsignedBits UnsignedBits;\n\n\tstatic const Category CATEGORY = SIGNED_INTEGER;\n\tstatic const UnsignedBits HIGH_BIT = UnsignedBits(1)\n\t                                     << ((sizeof(UnsignedBits) * 8) - 1);\n\tstatic const UnsignedBits LOWEST_KEY = HIGH_BIT;\n\tstatic const UnsignedBits MAX_KEY = UnsignedBits(-1) ^ HIGH_BIT;\n\n\tenum {\n\t\tPRIMITIVE = true,\n\t\tNULL_TYPE = false,\n\t};\n\n\tstatic __device__ __forceinline__ UnsignedBits TwiddleIn(UnsignedBits key) {\n\t\tT val = key;\n\t\tif (val >= 0) {\n\t\t\treturn val;\n\t\t}\n\t\tUnsignedBits new_val = std::abs(val);\n\t\treturn new_val | HIGH_BIT;\n\t};\n\n\tstatic __device__ __forceinline__ UnsignedBits\n\tTwiddleOut(UnsignedBits key) {\n\t\tif (key & HIGH_BIT) {\n\t\t\tauto del_high_bit = key ^ HIGH_BIT;\n\t\t\tT x = -T(del_high_bit);\n\t\t\treturn x;\n\t\t}\n\t\treturn key;\n\t};\n\n\tstatic __host__ __device__ __forceinline__ T Max() {\n\t\treturn std::numeric_limits<T>::max();\n\t}\n\n\tstatic __host__ __device__ __forceinline__ T Lowest() {\n\t\treturn std::numeric_limits<T>::lowest();\n\t}\n};\n\ntemplate <typename _UnsignedBits, typename T>\nstruct BaseTraits<FLOATING_POINT,\n                  false,\n                  false,\n                  _UnsignedBits,\n                  thrustshift::AbsView<T>> {\n\ttypedef _UnsignedBits UnsignedBits;\n\n\tstatic const Category CATEGORY = FLOATING_POINT;\n\tstatic const UnsignedBits HIGH_BIT = UnsignedBits(1)\n\t                                     << ((sizeof(UnsignedBits) * 8) - 1);\n\tstatic const UnsignedBits LOWEST_KEY = UnsignedBits(-1);\n\tstatic const UnsignedBits MAX_KEY = UnsignedBits(-1) ^ HIGH_BIT;\n\n\tenum {\n\t\tPRIMITIVE = true,\n\t\tNULL_TYPE = false,\n\t};\n\n\tstatic __device__ __forceinline__ UnsignedBits TwiddleIn(UnsignedBits key) {\n\t\treturn key;\n\t};\n\n\tstatic __device__ __forceinline__ UnsignedBits\n\tTwiddleOut(UnsignedBits key) {\n\t\treturn key;\n\t};\n\n\tstatic __host__ __device__ __forceinline__ T Max() {\n\t\treturn FpLimits<T>::Max();\n\t}\n\n\tstatic __host__ __device__ __forceinline__ T Lowest() {\n\t\treturn FpLimits<T>::Lowest();\n\t}\n};\n\ntemplate <>\nstruct NumericTraits<thrustshift::AbsView<int>>\n    : BaseTraits<SIGNED_INTEGER,\n                 false,\n                 false,\n                 unsigned int,\n                 thrustshift::AbsView<int>> {};\ntemplate <>\nstruct NumericTraits<thrustshift::AbsView<long int>>\n    : BaseTraits<SIGNED_INTEGER,\n                 false,\n                 false,\n                 long unsigned int,\n                 thrustshift::AbsView<long int>> {};\ntemplate <>\nstruct NumericTraits<thrustshift::AbsView<long long int>>\n    : BaseTraits<SIGNED_INTEGER,\n                 false,\n                 false,\n                 long long unsigned int,\n                 thrustshift::AbsView<long long int>> {};\ntemplate <>\nstruct NumericTraits<thrustshift::AbsView<float>>\n    : BaseTraits<FLOATING_POINT,\n                 false,\n                 false,\n                 unsigned int,\n                 thrustshift::AbsView<float>> {};\ntemplate <>\nstruct NumericTraits<thrustshift::AbsView<double>>\n    : BaseTraits<FLOATING_POINT,\n                 false,\n                 false,\n                 long long unsigned int,\n                 thrustshift::AbsView<double>> {};\n\n} // namespace cub\n\nnamespace thrustshift {\n\nnamespace async {\n\n/*! \\brief Batched sort of keys with values.\n *\n *  Uses CUB's radix sort.\n */\ntemplate <class KeyInRange,\n          class KeyOutRange,\n          class ValueInRange,\n          class ValueOutRange,\n          class MemoryResource>\nvoid sort_batched_descending(cuda::stream_t& stream,\n                             KeyInRange&& keys_in,\n                             KeyOutRange&& keys_out,\n                             ValueInRange&& values_in,\n                             ValueOutRange&& values_out,\n                             std::size_t batch_len,\n                             MemoryResource& delayed_memory_resource) {\n\n\tconst std::size_t N = keys_in.size();\n\n\tgsl_Expects(N % batch_len == 0);\n\tgsl_Expects(batch_len > 0);\n\tgsl_Expects(keys_out.size() == N);\n\tgsl_Expects(values_in.size() == N);\n\tgsl_Expects(values_out.size() == N);\n\n\tauto cit = thrust::make_counting_iterator(0);\n\tauto tit = thrust::make_transform_iterator(\n\t    cit, [batch_len] __device__(int i) { return i * batch_len; });\n\n\tconst std::size_t num_batches = N / batch_len;\n\n\tsize_t tmp_bytes_size = 0;\n\tvoid* tmp_ptr = nullptr;\n\n\tusing KeyT = typename std::remove_reference<KeyOutRange>::type::value_type;\n\n\tauto exec = [&] {\n\t\tcuda::throw_if_error(cub::DeviceSegmentedRadixSort::SortPairsDescending(\n\t\t    tmp_ptr,\n\t\t    tmp_bytes_size,\n\t\t    keys_in.data(),\n\t\t    keys_out.data(),\n\t\t    values_in.data(),\n\t\t    values_out.data(),\n\t\t    gsl_lite::narrow<int>(N),\n\t\t    gsl_lite::narrow<int>(num_batches),\n\t\t    tit,\n\t\t    tit + 1,\n\t\t    0, // default value by CUB\n\t\t    sizeof(KeyT) * 8, // default value by CUB\n\t\t    stream.handle()));\n\t};\n\texec();\n\tauto tmp =\n\t    make_not_a_vector<uint8_t>(tmp_bytes_size, delayed_memory_resource);\n\ttmp_ptr = tmp.to_span().data();\n\texec();\n}\n\n/*! \\brief Batched sort of keys with respect to their absolute values.\n *\n *  Example:\n *\n *  ```\n *  batch_len = 5\n *  keys_in = {-8, 7, 10, -6, 5}\n *  // sort_batched_abs\n *  keys_out = {5, -6, 7, -8, 10}\n *  ```\n *\n *  ```\n *  batch_len = 3\n *  keys_in = {-8, 7, 10,   -6, 5, 4}\n *  // sort_batched_abs\n *  keys_out = {7, -8, 10,   4, 5, -6}\n *  ```\n */\ntemplate <class KeyInRange,\n          class KeyOutRange,\n          class ValueInRange,\n          class ValueOutRange,\n          class MemoryResource>\nvoid sort_batched_abs(cuda::stream_t& stream,\n                      KeyInRange&& keys_in,\n                      KeyOutRange&& keys_out,\n                      ValueInRange&& values_in,\n                      ValueOutRange&& values_out,\n                      std::size_t batch_len,\n                      MemoryResource& delayed_memory_resource) {\n\n\tconst std::size_t N = keys_in.size();\n\n\tgsl_Expects(N % batch_len == 0);\n\tgsl_Expects(batch_len > 0);\n\tgsl_Expects(keys_out.size() == N);\n\tgsl_Expects(values_in.size() == N);\n\tgsl_Expects(values_out.size() == N);\n\n\tusing KeyT = typename std::remove_reference<KeyOutRange>::type::value_type;\n\tusing AbsT = AbsView<KeyT>;\n\n\tauto cit = thrust::make_counting_iterator(0);\n\tauto tit = thrust::make_transform_iterator(\n\t    cit, [batch_len] __device__(int i) { return i * batch_len; });\n\n\tconst std::size_t num_batches = N / batch_len;\n\n\tsize_t tmp_bytes_size = 0;\n\tvoid* tmp_ptr = nullptr;\n\n\tauto exec = [&] {\n\t\tcuda::throw_if_error(cub::DeviceSegmentedRadixSort::SortPairs(\n\t\t    tmp_ptr,\n\t\t    tmp_bytes_size,\n\t\t    reinterpret_cast<const AbsT*>(keys_in.data()),\n\t\t    reinterpret_cast<AbsT*>(keys_out.data()),\n\t\t    values_in.data(),\n\t\t    values_out.data(),\n\t\t    gsl_lite::narrow<int>(N),\n\t\t    gsl_lite::narrow<int>(num_batches),\n\t\t    tit,\n\t\t    tit + 1,\n\t\t    0, // first key bit for comparison\n\t\t    sizeof(KeyT) * 8 - 1, // highest bit is used to save sign\n\t\t    stream.handle()));\n\t};\n\texec();\n\tauto tmp =\n\t    make_not_a_vector<uint8_t>(tmp_bytes_size, delayed_memory_resource);\n\ttmp_ptr = tmp.to_span().data();\n\texec();\n}\n\n} // namespace async\n\n} // namespace thrustshift\n", "meta": {"hexsha": "d9200d391f263dade3085d64dfd30f127c6d22d2", "size": 7600, "ext": "h", "lang": "C", "max_stars_repo_path": "include/thrustshift/sort.h", "max_stars_repo_name": "pauleonix/thrustshift", "max_stars_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/thrustshift/sort.h", "max_issues_repo_name": "pauleonix/thrustshift", "max_issues_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/thrustshift/sort.h", "max_forks_repo_name": "pauleonix/thrustshift", "max_forks_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2401433692, "max_line_length": 77, "alphanum_fraction": 0.6168421053, "num_tokens": 1842, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632159254749036, "lm_q2_score": 0.019719128971477647, "lm_q1q2_score": 0.008406690466769706}}
{"text": "#include <gsl/gsl_math.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_complex.h>\n#include <gsl/gsl_complex_math.h>\n\n#include \"oct.h\"\n\nvoid\nprint_octave(const gsl_matrix *m, const char *str)\n{\n  FILE *fp;\n  size_t i, j;\n  const size_t N = m->size1;\n  const size_t M = m->size2;\n\n  if (str == NULL)\n    fp = stdout;\n  else\n    fp = fopen(str, \"w\");\n\n  if (!fp)\n    return;\n\n  fprintf(fp, \"%% Created by Octave 2.1.73, Tue Aug 01 15:00:27 2006 MDT <blah@blah>\\n\");\n  fprintf(fp, \"%% name: %s\\n\", str);\n  fprintf(fp, \"%% type: matrix\\n\");\n  fprintf(fp, \"%% rows: %zu\\n\", N);\n  fprintf(fp, \"%% columns: %zu\\n\", M);\n\n  for (i = 0; i < N; ++i)\n    {\n      for (j = 0; j < M; ++j)\n        {\n          fprintf(fp,\n                  \"%10.12e%s\",\n                  gsl_matrix_get(m, i, j),\n                  (j < M - 1) ? \" \" : \"\\n\");\n        }\n    }\n\n  if (str != NULL)\n    fclose(fp);\n}\n\nvoid\nprintv_octave(const gsl_vector *v, const char *str)\n{\n  FILE *fp;\n  size_t i;\n  const size_t N = v->size;\n\n  fp = fopen(str, \"w\");\n\n  if (!fp)\n    return;\n\n  fprintf(fp, \"%% Created by Octave 2.1.73, Tue Aug 01 15:00:27 2006 MDT <blah@blah>\\n\");\n  fprintf(fp, \"%% name: %s\\n\", str);\n  fprintf(fp, \"%% type: matrix\\n\");\n  fprintf(fp, \"%% rows: %zu\\n\", N);\n  fprintf(fp, \"%% columns: %u\\n\", 1);\n\n  for (i = 0; i < N; ++i)\n    {\n      fprintf(fp, \"%10.12e\\n\", gsl_vector_get(v, i));\n    }\n\n  fclose(fp);\n}\n\nvoid\nprintc_octave(const gsl_matrix_complex *m, const char *str)\n{\n  FILE *fp;\n  size_t i, j;\n  const size_t N = m->size1;\n  const size_t M = m->size2;\n\n  fp = fopen(str, \"w\");\n\n  if (!fp)\n    return;\n\n  fprintf(fp, \"%% Created by Octave 2.1.73, Tue Aug 01 15:00:27 2006 MDT <blah@blah>\\n\");\n  fprintf(fp, \"%% name: %s\\n\", str);\n  fprintf(fp, \"%% type: complex matrix\\n\");\n  fprintf(fp, \"%% rows: %zu\\n\", N);\n  fprintf(fp, \"%% columns: %zu\\n\", M);\n\n  for (i = 0; i < N; ++i)\n    {\n      for (j = 0; j < M; ++j)\n        {\n          gsl_complex z = gsl_matrix_complex_get(m, i, j);\n          fprintf(fp,\n                  \"(%.12e,%.12e)%s\",\n                  GSL_REAL(z),\n                  GSL_IMAG(z),\n                  (j < M - 1) ? \" \" : \"\\n\");\n        }\n    }\n\n  fclose(fp);\n}\n\n/* print symmetric matrix, using upper triangle */\nvoid\nprintsym_octave(const gsl_matrix *m, const char *str)\n{\n  FILE *fp;\n  size_t i, j;\n  const size_t N = m->size1;\n  const size_t M = m->size2;\n\n  fp = fopen(str, \"w\");\n\n  if (!fp)\n    return;\n\n  fprintf(fp, \"%% Created by Octave 2.1.73, Tue Aug 01 15:00:27 2006 MDT <blah@blah>\\n\");\n  fprintf(fp, \"%% name: %s\\n\", str);\n  fprintf(fp, \"%% type: matrix\\n\");\n  fprintf(fp, \"%% rows: %zu\\n\", N);\n  fprintf(fp, \"%% columns: %zu\\n\", M);\n\n  for (i = 0; i < N; ++i)\n    {\n      for (j = 0; j < M; ++j)\n        {\n          double z;\n\n          if (j >= i)\n            z = gsl_matrix_get(m, i, j);\n          else\n            z = gsl_matrix_get(m, j, i);\n\n          fprintf(fp,\n                  \"%.12e%s\",\n                  z,\n                  (j < M - 1) ? \" \" : \"\\n\");\n        }\n    }\n\n  fclose(fp);\n}\n\n/* print Hermitian matrix, using upper triangle */\nvoid\nprintherm_octave(const gsl_matrix_complex *m, const char *str)\n{\n  FILE *fp;\n  size_t i, j;\n  const size_t N = m->size1;\n  const size_t M = m->size2;\n\n  fp = fopen(str, \"w\");\n\n  if (!fp)\n    return;\n\n  fprintf(fp, \"%% Created by Octave 2.1.73, Tue Aug 01 15:00:27 2006 MDT <blah@blah>\\n\");\n  fprintf(fp, \"%% name: %s\\n\", str);\n  fprintf(fp, \"%% type: complex matrix\\n\");\n  fprintf(fp, \"%% rows: %zu\\n\", N);\n  fprintf(fp, \"%% columns: %zu\\n\", M);\n\n  for (i = 0; i < N; ++i)\n    {\n      for (j = 0; j < M; ++j)\n        {\n          gsl_complex z;\n\n          if (j >= i)\n            z = gsl_matrix_complex_get(m, i, j);\n          else\n            z = gsl_complex_conjugate(gsl_matrix_complex_get(m, j, i));\n\n          fprintf(fp,\n                  \"(%.12e,%.12e)%s\",\n                  GSL_REAL(z),\n                  GSL_IMAG(z),\n                  (j < M - 1) ? \" \" : \"\\n\");\n        }\n    }\n\n  fclose(fp);\n}\n\nvoid\nprintcv_octave(const gsl_vector_complex *v, const char *str)\n{\n  FILE *fp;\n  size_t i;\n  const size_t N = v->size;\n\n  fp = fopen(str, \"w\");\n\n  if (!fp)\n    return;\n\n  fprintf(fp, \"%% Created by Octave 2.1.73, Tue Aug 01 15:00:27 2006 MDT <blah@blah>\\n\");\n  fprintf(fp, \"%% name: %s\\n\", str);\n  fprintf(fp, \"%% type: complex matrix\\n\");\n  fprintf(fp, \"%% rows: %zu\\n\", N);\n  fprintf(fp, \"%% columns: %u\\n\", 1);\n\n  for (i = 0; i < N; ++i)\n    {\n      gsl_complex z = gsl_vector_complex_get(v, i);\n      fprintf(fp, \"(%.12e,%.12e)\\n\", GSL_REAL(z), GSL_IMAG(z));\n    }\n\n  fclose(fp);\n}\n\n/* print triangular matrix, using upper triangle */\nvoid\nprinttri_octave(const gsl_matrix *m, const char *str)\n{\n  FILE *fp;\n  size_t i, j;\n  const size_t N = m->size1;\n  const size_t M = m->size2;\n\n  if (str == NULL)\n    fp = stdout;\n  else\n    fp = fopen(str, \"w\");\n\n  if (!fp)\n    return;\n\n  fprintf(fp, \"%% Created by Octave 2.1.73, Tue Aug 01 15:00:27 2006 MDT <blah@blah>\\n\");\n  fprintf(fp, \"%% name: %s\\n\", str);\n  fprintf(fp, \"%% type: matrix\\n\");\n  fprintf(fp, \"%% rows: %zu\\n\", N);\n  fprintf(fp, \"%% columns: %zu\\n\", M);\n\n  for (i = 0; i < N; ++i)\n    {\n      for (j = 0; j < M; ++j)\n        {\n          double mij;\n\n          if (j >= i)\n            mij = gsl_matrix_get(m, i, j);\n          else\n            mij = 0.0;\n\n          fprintf(fp,\n                  \"%10.12e%s\",\n                  mij,\n                  (j < M - 1) ? \" \" : \"\\n\");\n        }\n    }\n\n  if (str != NULL)\n    fclose(fp);\n}\n", "meta": {"hexsha": "8ccdc32c283a3d49d7e47154f40e2931b163d8e1", "size": 5502, "ext": "c", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/doc/examples/oct.c", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/doc/examples/oct.c", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/doc/examples/oct.c", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 21.0804597701, "max_line_length": 89, "alphanum_fraction": 0.4865503453, "num_tokens": 1868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31405054499180746, "lm_q2_score": 0.026759285513888915, "lm_q1q2_score": 0.008403768199228192}}
{"text": "#pragma once\n\n#include <gsl/span>\n\n#include \"halley/text/halleystring.h\"\n#include \"halley/resources/resource.h\"\n#include \"halley/maths/range.h\"\n#include \"halley/maths/vector4.h\"\n#include \"halley/data_structures/maybe.h\"\n#include <map>\n#include <vector>\n\n#include \"halley/utils/type_traits.h\"\n\n#if defined(DEV_BUILD)\n#define STORE_CONFIG_NODE_PARENTING\n#endif\n\nnamespace Halley {\n\tclass Serializer;\n\tclass Deserializer;\n\tclass ConfigNode;\n\n\ttemplate<typename T>\n\tstruct HasToConfigNode\n\t{\n\tprivate:\n\t\ttypedef std::true_type yes;\n\t\ttypedef std::false_type no;\n\t\ttemplate<typename U> static auto test(int) -> decltype(std::declval<U>().toConfigNode(), yes());\n\t\ttemplate<typename> static no test(...);\n\t \n\tpublic:\n\t\tstatic constexpr bool value = std::is_same<decltype(test<T>(0)),yes>::value;\n\t};\n\n\ttemplate<typename T>\n\tstruct HasConfigNodeConstructor\n\t{\n\tprivate:\n\t\ttypedef std::true_type yes;\n\t\ttypedef std::false_type no;\n\t\ttemplate<typename U> static auto test(int) -> decltype(U(std::declval<ConfigNode>()), yes());\n\t\ttemplate<typename> static no test(...);\n\t \n\tpublic:\n\t\tstatic constexpr bool value = std::is_same<decltype(test<T>(0)),yes>::value;\n\t};\n\n\tenum class ConfigNodeType\n\t{\n\t\tUndefined,\n\t\tString,\n\t\tSequence,\n\t\tMap,\n\t\tInt,\n\t\tFloat,\n\t\tInt2,\n\t\tFloat2,\n\t\tBytes,\n\t\tDeltaSequence, // For delta coding\n\t\tDeltaMap, // For delta coding\n\t\tNoop, // For delta coding\n\t\tIdx, // For delta coding\n\t\tDel // For delta coding\n\t};\n\n\ttemplate <>\n\tstruct EnumNames<ConfigNodeType> {\n\t\tconstexpr std::array<const char*, 13> operator()() const {\n\t\t\treturn{{\n\t\t\t\t\"undefined\",\n\t\t\t\t\"string\",\n\t\t\t\t\"sequence\",\n\t\t\t\t\"map\",\n\t\t\t\t\"int\",\n\t\t\t\t\"float\",\n\t\t\t\t\"int2\",\n\t\t\t\t\"float2\",\n\t\t\t\t\"bytes\",\n\t\t\t\t\"deltaSequence\",\n\t\t\t\t\"deltaMap\",\n\t\t\t\t\"noop\",\n\t\t\t\t\"idx\"\n\t\t\t\t\"del\"\n\t\t\t}};\n\t\t}\n\t};\n\n\tclass ConfigFile;\n\t\n\tclass ConfigNode\n\t{\n\t\tfriend class ConfigFile;\n\n\tpublic:\n\t\tusing MapType = std::map<String, ConfigNode, std::less<>>;\n\t\tusing SequenceType = std::vector<ConfigNode>;\n\n\t\tstruct NoopType {};\n\t\tstruct DelType {};\n\t\tstruct IdxType {\n\t\t\tint start;\n\t\t\tint len;\n\t\t\tIdxType() = default;\n\t\t\tIdxType(int start, int len) : start(start), len(len) {}\n\t\t};\n\t\t\n\t\tConfigNode();\n\t\texplicit ConfigNode(const ConfigNode& other);\n\t\tConfigNode(ConfigNode&& other) noexcept;\n\t\tConfigNode(MapType entryMap);\n\t\tConfigNode(SequenceType entryList);\n\t\texplicit ConfigNode(String value);\n\t\texplicit ConfigNode(const std::string_view& value);\n\t\texplicit ConfigNode(bool value);\n\t\texplicit ConfigNode(int value);\n\t\texplicit ConfigNode(float value);\n\t\texplicit ConfigNode(Vector2i value);\n\t\texplicit ConfigNode(Vector2f value);\n\t\texplicit ConfigNode(Bytes value);\n\t\texplicit ConfigNode(NoopType value);\n\t\texplicit ConfigNode(DelType value);\n\t\texplicit ConfigNode(IdxType value);\n\n\t\ttemplate <typename T>\n\t\texplicit ConfigNode(const std::vector<T>& sequence)\n\t\t{\n\t\t\t*this = sequence;\n\t\t}\n\n\t\ttemplate <typename K, typename V>\n\t\texplicit ConfigNode(const std::map<K, V>& values)\n\t\t{\n\t\t\t*this = values;\n\t\t}\n\n\t\t~ConfigNode();\n\t\t\n\t\tConfigNode& operator=(const ConfigNode& other);\n\t\tConfigNode& operator=(ConfigNode&& other) noexcept;\n\t\tConfigNode& operator=(bool value);\n\t\tConfigNode& operator=(int value);\n\t\tConfigNode& operator=(float value);\n\t\tConfigNode& operator=(Vector2i value);\n\t\tConfigNode& operator=(Vector2f value);\n\n\t\tConfigNode& operator=(MapType entryMap);\n\t\tConfigNode& operator=(SequenceType entryList);\n\t\tConfigNode& operator=(String value);\n\t\tConfigNode& operator=(Bytes value);\n\t\tConfigNode& operator=(gsl::span<const gsl::byte> bytes);\n\n\t\tConfigNode& operator=(const char* value);\n\t\tConfigNode& operator=(const std::string_view& value);\n\t\t\n\t\tConfigNode& operator=(NoopType value);\n\t\tConfigNode& operator=(DelType value);\n\t\tConfigNode& operator=(IdxType value);\n\n\t\ttemplate <typename T>\n\t\tConfigNode& operator=(const std::vector<T>& sequence)\n\t\t{\n\t\t\tSequenceType seq;\n\t\t\tseq.reserve(sequence.size());\n\t\t\tfor (const auto& e: sequence) {\n\t\t\t\tif constexpr (HasToConfigNode<T>::value) {\n\t\t\t\t\tseq.push_back(e.toConfigNode());\n\t\t\t\t} else {\n\t\t\t\t\tseq.push_back(ConfigNode(e));\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn *this = seq;\n\t\t}\n\n\t\ttemplate <typename K, typename V>\n\t\tConfigNode& operator=(const std::map<K, V>& values)\n\t\t{\n\t\t\tMapType map;\n\t\t\tfor (const auto& [k, v]: values) {\n\t\t\t\tString key = toString(k);\n\n\t\t\t\tif constexpr (HasToConfigNode<V>::value) {\n\t\t\t\t\tmap[std::move(key)] = v.toConfigNode();\n\t\t\t\t} else {\n\t\t\t\t\tmap[std::move(key)] = ConfigNode(v);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn *this = map;\n\t\t}\n\n\t\tbool operator==(const ConfigNode& other) const;\n\t\tbool operator!=(const ConfigNode& other) const;\n\n\t\tConfigNodeType getType() const;\n\n\t\tvoid serialize(Serializer& s) const;\n\t\tvoid deserialize(Deserializer& s);\n\n\t\tint asInt() const;\n\t\tfloat asFloat() const;\n\t\tbool asBool() const;\n\t\tVector2i asVector2i() const;\n\t\tVector2f asVector2f() const;\n\t\tVector3i asVector3i() const;\n\t\tVector3f asVector3f() const;\n\t\tVector4i asVector4i() const;\n\t\tVector4f asVector4f() const;\n\t\tRange<float> asFloatRange() const;\n\t\tString asString() const;\n\t\tconst Bytes& asBytes() const;\n\n\t\tint asInt(int defaultValue) const;\n\t\tfloat asFloat(float defaultValue) const;\n\t\tbool asBool(bool defaultValue) const;\n\t\tString asString(const std::string_view& defaultValue) const;\n\t\tVector2i asVector2i(Vector2i defaultValue) const;\n\t\tVector2f asVector2f(Vector2f defaultValue) const;\n\t\tVector3i asVector3i(Vector3i defaultValue) const;\n\t\tVector3f asVector3f(Vector3f defaultValue) const;\n\t\tVector4i asVector4i(Vector4i defaultValue) const;\n\t\tVector4f asVector4f(Vector4f defaultValue) const;\n\n\t\ttemplate <typename T>\n\t\tstd::vector<T> asVector() const\n\t\t{\n\t\t\tif (type == ConfigNodeType::Sequence) {\n\t\t\t\tstd::vector<T> result;\n\t\t\t\tresult.reserve(asSequence().size());\n\t\t\t\tfor (const auto& e : asSequence()) {\n\t\t\t\t\tif constexpr (HasConfigNodeConstructor<T>::value) {\n\t\t\t\t\t\tresult.emplace_back(T(e));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresult.emplace_back(e.convertTo(Tag<T>()));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t} else if (type == ConfigNodeType::Undefined) {\n\t\t\t\treturn {};\n\t\t\t} else {\n\t\t\t\tthrow Exception(\"Can't convert \" + getNodeDebugId() + \" from \" + toString(getType()) + \" to std::vector<T>.\", HalleyExceptions::Resources);\n\t\t\t}\n\t\t}\n\n\t\ttemplate <typename T>\n\t\tstd::vector<T> asVector(const std::vector<T>& defaultValue) const\n\t\t{\n\t\t\tif (type == ConfigNodeType::Sequence) {\n\t\t\t\treturn asVector<T>();\n\t\t\t} else {\n\t\t\t\treturn defaultValue;\n\t\t\t}\n\t\t}\n\n\t\ttemplate <typename K, typename V>\n\t\tstd::map<K, V> asMap() const\n\t\t{\n\t\t\tif (type == ConfigNodeType::Map) {\n\t\t\t\tstd::map<K, V> result;\n\t\t\t\tfor (const auto& [k, v] : asMap()) {\n\t\t\t\t\tconst K key = fromString<K>(k);\n\t\t\t\t\t\n\t\t\t\t\tif constexpr (HasConfigNodeConstructor<V>::value) {\n\t\t\t\t\t\tresult[std::move(key)] = V(v);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresult[std::move(key)] = v.convertTo(Tag<V>());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t} else if (type == ConfigNodeType::Undefined) {\n\t\t\t\treturn {};\n\t\t\t} else {\n\t\t\t\tthrow Exception(\"Can't convert \" + getNodeDebugId() + \" from \" + toString(getType()) + \" to std::map<K, V>.\", HalleyExceptions::Resources);\n\t\t\t}\n\t\t}\n\t\t\n\t\tconst SequenceType& asSequence() const;\n\t\tconst MapType& asMap() const;\n\t\tSequenceType& asSequence();\n\t\tMapType& asMap();\n\n\t\tvoid ensureType(ConfigNodeType type);\n\n\t\tbool hasKey(const String& key) const;\n\t\tvoid removeKey(const String& key);\n\n\t\tConfigNode& operator[](const std::string_view& key);\n\t\tConfigNode& operator[](size_t idx);\n\n\t\tconst ConfigNode& operator[](const std::string_view& key) const;\n\t\tconst ConfigNode& operator[](size_t idx) const;\n\n\t\tSequenceType::iterator begin();\n\t\tSequenceType::iterator end();\n\n\t\tSequenceType::const_iterator begin() const;\n\t\tSequenceType::const_iterator end() const;\n\n\t\tvoid reset();\n\t\tvoid setOriginalPosition(int line, int column);\n\t\tvoid setParent(const ConfigNode* parent, int idx);\n\t\tvoid propagateParentingInformation(const ConfigFile* parentFile);\n\n\t\tinline void assertValid() const\n\t\t{\n\t\t\tExpects(intData != 0xCDCDCDCD);\n\t\t\tExpects(intData != 0xDDDDDDDD);\n\t\t}\n\n\t\tstruct BreadCrumb {\n\t\t\tconst BreadCrumb* prev = nullptr;\n\t\t\tString key;\n\t\t\tOptionalLite<int> idx;\n\t\t\tint depth = 0;\n\n\t\t\tBreadCrumb() = default;\n\t\t\tBreadCrumb(const BreadCrumb& prev, String key) : prev(&prev), key(std::move(key)), depth(prev.depth + 1) {}\n\t\t\tBreadCrumb(const BreadCrumb& prev, int index) : prev(&prev), idx(index), depth(prev.depth + 1) {}\n\n\t\t\tbool hasKeyAt(const String& key, int depth) const;\n\t\t\tbool hasIndexAt(int idx, int depth) const;\n\t\t};\n\n\t\tclass IDeltaCodeHints {\n\t\tpublic:\n\t\t\tvirtual ~IDeltaCodeHints() = default;\n\n\t\t\tvirtual std::optional<size_t> getSequenceMatch(const SequenceType& seq, const ConfigNode& newValue, size_t curIdx, const BreadCrumb& breadCrumb) const = 0;\n\t\t\tvirtual bool doesSequenceOrderMatter(const BreadCrumb& breadCrumb) const { return true; }\n\t\t\tvirtual bool canDeleteKey(const String& key, const BreadCrumb& breadCrumb) const { return true; }\n\t\t\tvirtual bool canDeleteAnyKey() const { return true; }\n\t\t\tvirtual bool shouldBypass(const BreadCrumb& breadCrumb) const { return false; }\n\t\t\tvirtual bool areNullAndEmptyEquivalent(const BreadCrumb& breadCrumb) const { return false; }\n\t\t};\n\n\t\tstatic ConfigNode createDelta(const ConfigNode& from, const ConfigNode& to, const IDeltaCodeHints* hints = nullptr);\n\t\tstatic ConfigNode applyDelta(const ConfigNode& from, const ConfigNode& delta);\n\t\tvoid applyDelta(const ConfigNode& delta);\n\t\tvoid decayDeltaArtifacts();\n\n\tprivate:\n\t\ttemplate <typename T>\n\t\tclass Tag {};\n\n\t\tunion {\n\t\t\tString* strData;\n\t\t\tMapType* mapData;\n\t\t\tSequenceType* sequenceData;\n\t\t\tBytes* bytesData;\n\t\t\tvoid* rawPtrData;\n\t\t\tint intData;\n\t\t\tfloat floatData;\n\t\t\tVector2i vec2iData;\n\t\t\tVector2f vec2fData;\n\t\t};\n\t\tConfigNodeType type = ConfigNodeType::Undefined;\n\t\tint auxData = 0; // Used by delta coding\n\n#if defined(STORE_CONFIG_NODE_PARENTING)\n\t\tstruct ParentingInfo {\n\t\t\tint line = 0;\n\t\t\tint column = 0;\n\t\t\tint idx = 0;\n\t\t\tconst ConfigNode* node = nullptr;\n\t\t\tconst ConfigFile* file = nullptr;\n\t\t};\n\t\tstd::unique_ptr<ParentingInfo> parent;\n#endif\n\n\t\tstatic ConfigNode undefinedConfigNode;\n\t\tstatic String undefinedConfigNodeName;\n\n\t\ttemplate <typename T> void deserializeContents(Deserializer& s)\n\t\t{\n\t\t\tT v;\n\t\t\ts >> v;\n\t\t\t*this = std::move(v);\n\t\t}\n\n\t\tString getNodeDebugId() const;\n\t\tString backTrackFullNodeName() const;\n\n\t\tint convertTo(Tag<int> tag) const;\n\t\tfloat convertTo(Tag<float> tag) const;\n\t\tbool convertTo(Tag<bool> tag) const;\n\t\tVector2i convertTo(Tag<Vector2i> tag) const;\n\t\tVector2f convertTo(Tag<Vector2f> tag) const;\n\t\tVector3i convertTo(Tag<Vector3i> tag) const;\n\t\tVector3f convertTo(Tag<Vector3f> tag) const;\n\t\tVector4i convertTo(Tag<Vector4i> tag) const;\n\t\tVector4f convertTo(Tag<Vector4f> tag) const;\n\t\tRange<float> convertTo(Tag<Range<float>> tag) const;\n\t\tString convertTo(Tag<String> tag) const;\n\t\tconst Bytes& convertTo(Tag<Bytes&> tag) const;\n\n\t\tbool isNullOrEmpty() const;\n\n\t\tstatic ConfigNode doCreateDelta(const ConfigNode& from, const ConfigNode& to, const BreadCrumb& breadCrumb, const IDeltaCodeHints* hints);\n\t\tstatic ConfigNode createMapDelta(const ConfigNode& from, const ConfigNode& to, const BreadCrumb& breadCrumb, const IDeltaCodeHints* hints);\n\t\tstatic ConfigNode createSequenceDelta(const ConfigNode& from, const ConfigNode& to, const BreadCrumb& breadCrumb, const IDeltaCodeHints* hints);\n\t\tvoid applyMapDelta(const ConfigNode& delta);\n\t\tvoid applySequenceDelta(const ConfigNode& delta);\n\n\t\tbool isEquivalent(const ConfigNode& other) const;\n\t\tbool isEquivalentStrictOrder(const ConfigNode& other) const;\n\t};\n}\n", "meta": {"hexsha": "a5404eed9d2202f30bf77cd81d40312816c7fc62", "size": 11421, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engine/utils/include/halley/data_structures/config_node.h", "max_stars_repo_name": "moonantonio/halley", "max_stars_repo_head_hexsha": "c4dfc476ab58539ebb503a5fcdb929413674254d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/engine/utils/include/halley/data_structures/config_node.h", "max_issues_repo_name": "moonantonio/halley", "max_issues_repo_head_hexsha": "c4dfc476ab58539ebb503a5fcdb929413674254d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engine/utils/include/halley/data_structures/config_node.h", "max_forks_repo_name": "moonantonio/halley", "max_forks_repo_head_hexsha": "c4dfc476ab58539ebb503a5fcdb929413674254d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9926470588, "max_line_length": 158, "alphanum_fraction": 0.6981875493, "num_tokens": 3106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29098086621490676, "lm_q2_score": 0.02887090736407739, "lm_q1q2_score": 0.00840088163320957}}
{"text": "#ifndef SmtkMatcher_h\n#define SmtkMatcher_h\n\n/**\n * @file\n * $Revision: 1.1 $\n * $Date: 2009/09/09 23:42:41 $\n *\n *   Unless noted otherwise, the portions of Isis written by the USGS are\n *   public domain. See individual third-party library and package descriptions\n *   for intellectual property information, user agreements, and related\n *   information.\n *\n *   Although Isis has been used by the USGS, no warranty, expressed or\n *   implied, is made by the USGS as to the accuracy and functioning of such\n *   software and related material nor shall the fact of distribution\n *   constitute any such warranty, and no responsibility is assumed by the\n *   USGS in connection therewith.\n *\n *   For additional information, launch\n *   $ISISROOT/doc//documents/Disclaimers/Disclaimers.html\n *   in a browser or see the Privacy &amp; Disclaimers page on the Isis website,\n *   http://isis.astrogeology.usgs.gov, and the USGS privacy and disclaimers on\n *   http://www.usgs.gov/privacy.html.\n */\n\n#include <memory>\n\n\n#include <QSharedPointer>\n#include \"SmtkStack.h\"\n#include \"Gruen.h\"\n#include \"SmtkPoint.h\"\n\n#include \"GSLUtility.h\"\n#include <gsl/gsl_rng.h>\n\n\nnamespace Isis {\n\n/**\n * @brief Workhorse of stereo matcher\n *\n * This class provides stereo matching functionality to the SMTK toolkit.  It\n * registers points, clones them by adjusting parameters to nearby point\n * locations and manages point selection processes.\n *\n * The Gruen algorithm is initialized here and maintained for use in the\n * stereo matching process.\n *\n * @author 2011-05-28 Kris Becker\n *\n * @internal\n *   @history 2012-12-20 Debbie A. Cook - Removed unused Projection.h\n *                           References #775.\n *   @history 2017-08-18 Summer Stapleton, Ian Humphrey, Tyler Wilson - \n *                           Changed auto_ptr reference to QSharedPointer\n *                           so this class compiles under C++14.  \n *                           References #4809.\n */\nclass SmtkMatcher {\n  public:\n    SmtkMatcher();\n    SmtkMatcher(const QString &regdef);\n    SmtkMatcher(const QString &regdef, Cube *lhImage, Cube *rhImage);\n    SmtkMatcher(Cube *lhImage, Cube *rhImage);\n    ~SmtkMatcher();\n\n    void setImages(Cube *lhImage, Cube *rhImage);\n    void setGruenDef(const QString &regdef);\n\n    bool isValid(const Coordinate &pnt);\n    bool isValid(const SmtkPoint &spnt);\n\n    /** Return pattern chip */\n    Chip *PatternChip() const {\n      validate();\n      return (m_gruen->PatternChip());\n    }\n\n    /** Return search chip */\n    Chip *SearchChip() const {\n      validate();\n      return (m_gruen->SearchChip());\n    }\n\n    /** Returns the fit chip */\n    Chip *FitChip() const {\n      validate();\n      return (m_gruen->FitChip());\n    }\n\n    void setWriteSubsearchChipPattern(const QString &fileptrn = \"SmtkMatcher\");\n\n    SmtkQStackIter FindSmallestEV(SmtkQStack &stack);\n    SmtkQStackIter FindExpDistEV(SmtkQStack &stack, const double &seedsample,\n                                 const double &minEV, const double &maxEV);\n\n    SmtkPoint Register(const Coordinate &lpnt,\n                       const AffineRadio &affrad = AffineRadio());\n    SmtkPoint Register(const PointPair &pnts,\n                       const AffineRadio &affrad = AffineRadio());\n    SmtkPoint Register(const SmtkPoint &spnt,\n                       const AffineRadio &affrad = AffineRadio());\n    SmtkPoint Register(const PointGeometry &lpg, const PointGeometry &rpg,\n                       const AffineRadio &affrad  = AffineRadio());\n\n    SmtkPoint Create(const Coordinate &left, const Coordinate &right);\n    SmtkPoint Clone(const SmtkPoint &point, const Coordinate &left);\n\n    inline BigInt OffImageErrorCount() const { return (m_offImage);  }\n    inline BigInt SpiceErrorCount() const { return (m_spiceErr);  }\n\n    /** Return Gruen template parameters */\n    PvlGroup RegTemplate() { return (m_gruen->RegTemplate());  }\n    /** Return Gruen registration statistics */\n    Pvl RegistrationStatistics() { return (m_gruen->RegistrationStatistics()); }\n\n  private:\n    SmtkMatcher &operator=(const SmtkMatcher &matcher); // Assignment disabled\n    SmtkMatcher(const SmtkMatcher &matcher);            // Copy const disabled\n\n    Cube     *m_lhCube;                // Left image cube (not owned)\n    Cube     *m_rhCube;                // Right image cube (not owned)\n    QSharedPointer<Gruen> m_gruen;     // Gruen matcher\n    BigInt  m_offImage;                // Offimage counter\n    BigInt  m_spiceErr;                // SPICE distance error\n    bool    m_useAutoReg;              // Select AutoReg features\n    const gsl_rng_type * T;            // GSL random number type\n    gsl_rng * r;                       // GSL random number generator\n\n    void randomNumberSetup();\n    bool validate(const bool &throwError = true) const;\n\n    inline Camera &lhCamera() { return (*m_lhCube->camera());   }\n    inline Camera &rhCamera() { return (*m_rhCube->camera());   }\n\n    Coordinate getLineSample(Camera &camera, const Coordinate &geom);\n    Coordinate getLatLon(Camera &camera, const Coordinate &pnt);\n\n    bool inCube(const Camera &camera, const Coordinate &point) const;\n\n    SmtkPoint makeRegisteredPoint(const PointGeometry &left,\n                                  const PointGeometry &right, Gruen *gruen);\n};\n} // namespace Isis\n\n#endif\n", "meta": {"hexsha": "2ced22b4869ac2f165d895935f2b775b93a96cbf", "size": 5322, "ext": "h", "lang": "C", "max_stars_repo_path": "isis/src/base/objs/SmtkMatcher/SmtkMatcher.h", "max_stars_repo_name": "ihumphrey-usgs/ISIS3_old", "max_stars_repo_head_hexsha": "284cc442b773f8369d44379ee29a9b46961d8108", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-13T15:31:33.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-13T15:31:33.000Z", "max_issues_repo_path": "isis/src/base/objs/SmtkMatcher/SmtkMatcher.h", "max_issues_repo_name": "ihumphrey-usgs/ISIS3_old", "max_issues_repo_head_hexsha": "284cc442b773f8369d44379ee29a9b46961d8108", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "isis/src/base/objs/SmtkMatcher/SmtkMatcher.h", "max_forks_repo_name": "ihumphrey-usgs/ISIS3_old", "max_forks_repo_head_hexsha": "284cc442b773f8369d44379ee29a9b46961d8108", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-12T06:05:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-12T06:05:03.000Z", "avg_line_length": 35.7181208054, "max_line_length": 80, "alphanum_fraction": 0.6565201052, "num_tokens": 1305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31742625267332647, "lm_q2_score": 0.026355351890182406, "lm_q1q2_score": 0.008365880588387473}}
{"text": "/*\n * fvector.h\n *\n *  Created on: Feb 4, 2014\n *      Author: vbonnici\n */\n\n#ifndef FVECTOR_H_\n#define FVECTOR_H_\n\n\n#include <limits>\n#include <vector>\n#include \"data_ts.h\"\n\n#include <gsl/gsl_rng.h>\n\n\n\nusing namespace dolierlib;\n\nnamespace dolierlib{\n\n\n\n/*\n * shuffle sequences... remember to swap also their lengths\n */\nvoid shuffle(\n\t\tstd::vector<dna5_t*> &f_sequences,\n\t\tstd::vector<usize_t> &f_lengths,\n\t\tint ntimes)\n{\n\tsrand( (unsigned)time(NULL) );\n\tsize_t f,s;\n\t//dna5_t *tmp_s; usize_t tmp_l;\n\tfor(int i=0; i<ntimes; i++){\n\t\tf = static_cast<size_t>(ceil((rand()/(RAND_MAX +1.0))*(static_cast<double>(f_sequences.size() -1))));\n\t\ts = static_cast<size_t>(ceil((rand()/(RAND_MAX +1.0))*(static_cast<double>(f_sequences.size() -1))));\n//\t\tstd::cout<<f<<\"\\t\"<<s<<\"\\n\";\n\t\tstd::swap(f_sequences[f], f_sequences[s]);\n\t\tstd::swap(f_lengths[f], f_lengths[s]);\n\t}\n}\n\n\n\n/*\n * swap randomly the first leading_possequences with a forward position\n */\nvoid leading_shuffle(\n\t\tstd::vector<dna5_t*> &f_sequences,\n\t\tstd::vector<usize_t> &f_lengths,\n\t\tsize_t leading_pos)\n{\n\tsrand( (unsigned)time(NULL) );\n\n\n\tsize_t f;\n\tfor(size_t i=0; i<leading_pos; i++){\n\t\tf = static_cast<size_t>(ceil((rand()/(RAND_MAX))*(static_cast<double>(f_sequences.size()- leading_pos -1)))) + leading_pos;\n\t\t//f = static_cast<size_t>((gsl_rng_uniform (r) * static_cast<double>(f_sequences.size() - leading_pos))) + leading_pos\n//\t\tstd::cout<<i<<\"\\t\"<<f<<\"\\n\";\n\n//\t\tprint_dna5(f_sequences[i], f_lengths[i]);std::cout<<\"\\t\";print_dna5(f_sequences[f], f_lengths[f]);std::cout<<\"\\n\";\n\n\t\tstd::swap(f_sequences[i], f_sequences[f]);\n\t\tstd::swap(f_lengths[i], f_lengths[f]);\n\n//\t\tprint_dna5(f_sequences[i], f_lengths[i]);std::cout<<\"\\t\";print_dna5(f_sequences[f], f_lengths[f]);std::cout<<\"\\n\";\n\t}\n\n}\n\n\n/*\n * Get kmers spectra.\n * Only non-zero columns are reported.\n * Let X to be the length of the longest input sequences, then theoretically we have sum_{i=1}^{i<=X}(4^i) features (possible kmers)\n * but some of these theoretical kmers do not appear in the input sequences, so they are excluded from the output spectra.\n * Moreover, if sequences are all of the same length, the working X is X-1.\n *\n */\nvoid fvector(\n\t\tstd::vector<dna5_t*> &f_sequences,\n\t\tstd::vector<usize_t> &f_lengths,\n\t\tdouble ***vectors,  //output spectra, it's pointer\n\t\tsize_t *vector_length, //length of spectra, it's a pointer\n\t\tdouble **weights\n\t\t)\n{\n\n\tDNA5MS_t f_ms(true);\n\tconcat(f_ms, f_sequences, f_lengths, false);\n\tf_ms.areUndefTeminated = true;\n\n\tCsFullyContainer f_ds(true);\n\t\tbuild_fully_ds(f_ms, f_ds);\n\t\t//build_strict_ds(f_ms, f_ds);\n\tCs5DLIndex f_dlindex(f_ms.seq, f_ms.seq_length, f_ds.SA, f_ms.lengths, f_ms.nof_seqs);\n\tSASearcher sas(f_ms.seq, f_ds.SA, f_ms.seq_length);\n\n\n\tsize_t max_length = 0;\n\tfor(size_t i=0; i<f_lengths.size(); i++){\n\t\tif(f_lengths[i] > max_length)\n\t\t\tmax_length = f_lengths[i];\n\t}\n\n\n\n\tsize_t nof_features = 0;\n\tsize_t *nof_kfeatures = new size_t[max_length+1];\n\tfor(size_t i=1; i<=max_length; i++){\n\t\tNSAIterator it = NSAIterator::begin(f_ms, f_ds, i);\n\t\tnof_kfeatures[i] = nof(it);\n\t\tnof_features += nof_kfeatures[i];\n\n\t\tstd::cout<<i<<\"\\t\"<<nof_kfeatures[i]<<\"\\t\"<<f_sequences.size()<<\"\\n\";\n\n\t\t//if sequences are all of the same length, the working X is X-1.\n\t\tif(nof_kfeatures[i] == f_sequences.size()  &&  i<=max_length){\n\t\t\tif(i>1){\n\t\t\t\tstd::cout<<\"#\\n\";\n\t\t\t\tmax_length = i-1;\n\t\t\t\tnof_features -= nof_kfeatures[i];\n\t\t\t}\n\t\t\telse{\n\t\t\t\tmax_length = i;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\n\n\t//double **table = new double*[f_sequences.size()];\n\t(*vectors) =  new double*[f_sequences.size()];\n\tfor(size_t i=0; i<f_sequences.size(); i++){\n\t\t(*vectors)[i] =  new double[nof_features];\n\t\tfor(size_t j=0; j<nof_features; j++)\n\t\t\t(*vectors)[i][j] = 0;\n\t}\n\t(*weights) =  new double[nof_features];\n\n\tsize_t c_nf = 0;\n\tsize_t ii;\n\tfor(size_t k=1; k<=max_length; k++){\n\t\tNSAIterator it = NSAIterator::begin(f_ms, f_ds, k);\n\t\tdna5_t *kmer  = new dna5_t[k];\n\t\twhile(it.next()){\n\t\t\tit.get_kmer(kmer);\n//\t\t\tstd::cout<<c_nf<<\"\\t\";print_dna5(kmer,k); std::cout<<\"\\n\";\n\n\t\t\tfor(ii=it.i_start; ii<it.i_end; ii++){\n\t\t\t\t(*vectors)[f_dlindex.ss_ids[ii]][c_nf]++;\n\t\t\t\t(*weights)[c_nf] = k;\n\t\t\t}\n\t\t\tc_nf++;\n\t\t}\n\t}\n\n\t*vector_length = nof_features;\n}\n\n\n\n/*\n * normalize vectors by column, from [0,max] to [min,max]/(max-min)\n */\nvoid normalize(double **matrix, size_t size1, size_t size2)\n{\n\tfor(size_t i=0; i<size2; i++){\n\t\tdouble min = std::numeric_limits<double>::max();\n\t\tdouble max = std::numeric_limits<double>::min();\n\n\t\tfor(size_t j=0; j<size1; j++){\n\t\t\tif(matrix[j][i]< min)\n\t\t\t\tmin = matrix[j][i];\n\t\t\tif(matrix[j][i] > max)\n\t\t\t\tmax = matrix[j][i];\n\t\t}\n\n\t\tdouble f = max - min;\n\t\tfor(size_t j=0; j<size1; j++){\n\t\t\tmatrix[j][i] = (matrix[j][i] - min) / f;\n\t\t}\n\t}\n}\n\n\n/*\n * normalize vectors by column, from [0,max] to [0,max]/(max)\n */\nvoid normalize_by_sum(double **matrix, size_t size1, size_t size2)\n{\n\tfor(size_t i=0; i<size2; i++){\n\t\tdouble sum = 0;\n\t\tfor(size_t j=0; j<size1; j++){\n\t\t\tsum += matrix[j][i];\n\t\t}\n\t\tfor(size_t j=0; j<size1; j++){\n\t\t\tmatrix[j][i] /= sum;\n\t\t}\n\t}\n}\n\n\n\n/*\n * Keep only those columns having at least one element >= min_value.\n * Unselected columns are putted at the end of the matrix.\n */\nvoid keep_only(\n\t\tdouble **matrix, //input matrix\n\t\tsize_t size1, //number of rows\n\t\tsize_t size2, //number of columns\n\t\tdouble min_value, //min value for selection\n\t\tsize_t *new_size2 //result number of columns\n\t\t)\n{\n\tsize_t to_size = size2;\n\tsize_t to_pos = 0;\n\tfor(size_t j=0; j<size2; j++){\n\t\tbool keep = false;\n\t\tfor(size_t i=0; i<size1; i++){\n\t\t\tif(matrix[i][j] >= min_value){\n\t\t\t\tkeep = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif(keep){\n\t\t\tif(j != to_pos){\n\t\t\t\tfor(size_t i=0; i<size1; i++){\n\t\t\t\t\tmatrix[i][to_pos] = matrix[i][j];\n\t\t\t\t}\n\t\t\t}\n\t\t\tto_pos++;\n\t\t}\n\t\telse{\n\t\t\tto_size--;\n\t\t}\n\t}\n\t*new_size2 = to_size;\n}\n\n\n/*\n * Same behaviour of keep_only, but it swap the weights matrix, too.\n */\nvoid keep_only(double **matrix, size_t size1, size_t size2, double min_value, size_t *new_size2, double *weights)\n{\n\tsize_t to_size = size2;\n\tsize_t to_pos = 0;\n\tfor(size_t j=0; j<size2; j++){\n\t\tbool keep = false;\n\t\tfor(size_t i=0; i<size1; i++){\n\t\t\tif(matrix[i][j] >= min_value){\n\t\t\t\tkeep = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif(keep){\n\t\t\tif(j != to_pos){\n\t\t\t\tfor(size_t i=0; i<size1; i++){\n\t\t\t\t\tmatrix[i][to_pos] = matrix[i][j];\n\t\t\t\t}\n\t\t\t\tweights[to_pos] = weights[j];\n\t\t\t}\n\t\t\tto_pos++;\n\t\t}\n\t\telse{\n\t\t\tto_size--;\n\t\t}\n\t}\n\t*new_size2 = to_size;\n}\n\n\n\n\n/*\n * Theoretical spectra are vectors if length sum_{i=1}^{i<=X}(4^i).\n * Thus, weights[i] correspond to the specific length i of the releated theoretical kmer.\n *\n */\nvoid get_fvectors_weights(double *weights, size_t length, std::vector<dna5_t*> &f_sequences, std::vector<usize_t> &f_lengths){\n//\tsize_t base = 0;\n//\tsize_t ebase = 0;\n//\tsize_t cbase = 0;\n//\tfor(size_t i=0;i<length; i++){\n//\t\tif(cbase == ebase){\n//\t\t\tbase++;\n//\t\t\tebase = static_cast<size_t>(pow(4, base));\n//\t\t\tcbase = 0;\n//\t\t}\n//\t\tweights[i] = base;\n//\t\tcbase++;\n//\t}\n\n\tDNA5MS_t f_ms(true);\n\tconcat(f_ms, f_sequences, f_lengths, false);\n\tf_ms.areUndefTeminated = true;\n\n\tCsFullyContainer f_ds(true);\n\t\tbuild_fully_ds(f_ms, f_ds);\n\t\t//build_strict_ds(f_ms, f_ds);\n\tCs5DLIndex f_dlindex(f_ms.seq, f_ms.seq_length, f_ds.SA, f_ms.lengths, f_ms.nof_seqs);\n\tSASearcher sas(f_ms.seq, f_ds.SA, f_ms.seq_length);\n\n\n\tsize_t max_length = 0;\n\tfor(size_t i=0; i<f_lengths.size(); i++){\n\t\tif(f_lengths[i] > max_length)\n\t\t\tmax_length = f_lengths[i];\n\t}\n\n\n\n\tsize_t nof_features = 0;\n\tsize_t *nof_kfeatures = new size_t[max_length+1];\n\tfor(size_t i=1; i<=max_length; i++){\n\t\tNSAIterator it = NSAIterator::begin(f_ms, f_ds, i);\n\t\tnof_kfeatures[i] = nof(it);\n\t\tnof_features += nof_kfeatures[i];\n\n\t\tstd::cout<<i<<\"\\t\"<<nof_kfeatures[i]<<\"\\t\"<<f_sequences.size()<<\"\\n\";\n\n\t\t//if sequences are all of the same length, the working X is X-1.\n\t\tif(nof_kfeatures[i] == f_sequences.size()  &&  i<=max_length){\n\t\t\tif(i>1){\n\t\t\t\tstd::cout<<\"#\\n\";\n\t\t\t\tmax_length = i-1;\n\t\t\t\tnof_features -= nof_kfeatures[i];\n\t\t\t}\n\t\t\telse{\n\t\t\t\tmax_length = i;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\n\n\tsize_t c_nf = 0;\n\tsize_t ii;\n\tfor(size_t k=1; k<=max_length; k++){\n\t\tNSAIterator it = NSAIterator::begin(f_ms, f_ds, k);\n\t\tdna5_t *kmer  = new dna5_t[k];\n\t\twhile(it.next()){\n\t\t\tit.get_kmer(kmer);\n//\t\t\tstd::cout<<c_nf<<\"\\t\";print_dna5(kmer,k); std::cout<<\"\\n\";\n\t\t\tfor(ii=it.i_start; ii<it.i_end; ii++){\n\t\t\t\tweights[c_nf] = k;\n\t\t\t}\n\t\t\tc_nf++;\n\t\t}\n\t}\n}\n\n\n\nvoid print_matrix(double **matrix, size_t size1, size_t size2){\n\tfor(size_t i=0; i<size1; i++){\n\t\tfor(size_t j=0; j<size2; j++){\n\t\t\tstd::cout<<matrix[i][j]<<\" \";\n\t\t}\n\t\tstd::cout<<\"\\n\";\n\t}\n}\n\n\n\n}\n\n\n#endif /* FVECTOR_H_ */\n", "meta": {"hexsha": "5ca0d5d3cd394da48110648b2d5e66029a484c2f", "size": 8579, "ext": "h", "lang": "C", "max_stars_repo_path": "dolierlib/clustering/fvector.h", "max_stars_repo_name": "vbonnici/DoLiER", "max_stars_repo_head_hexsha": "6f628b4ac5ddcbe941196813cb5faba551bd2a26", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dolierlib/clustering/fvector.h", "max_issues_repo_name": "vbonnici/DoLiER", "max_issues_repo_head_hexsha": "6f628b4ac5ddcbe941196813cb5faba551bd2a26", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dolierlib/clustering/fvector.h", "max_forks_repo_name": "vbonnici/DoLiER", "max_forks_repo_head_hexsha": "6f628b4ac5ddcbe941196813cb5faba551bd2a26", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.6957671958, "max_line_length": 132, "alphanum_fraction": 0.6315421378, "num_tokens": 2812, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30735801686526387, "lm_q2_score": 0.027169229763340123, "lm_q1q2_score": 0.008350680579816923}}
{"text": "// MIT License Copyright (c) 2020 Jarrett Wendt\n\n#pragma once\n\n#include \"Macros.h\"\n#include \"Memory.h\"\n#include \"Util.h\"\n\n#include <algorithm>\t\t\t// std::min/max\n#include <compare>\t\t\t\t// std::strong_ordering\n#include <functional>\n#include <initializer_list>\t\t// std::initializer/list\n#include <iterator>\t\t\t\t// std::random_access_iterator\n\n#include <gsl/gsl>\t\t\t\t// gsl::owner\n\n// Some macros to save on typing.\n// These get #undef-ed at the end of the .inl file.\n// Also pretty convenient in case I ever decide I want to change/rename the template args.\n// The only downside is that intellisense thinks my methods are unimplemented.\n#define TEMPLATE template<typename T, Concept::ReserveStrategy ReserveStrategy>\n#define ARRAY Array<T, ReserveStrategy>\n\nnamespace Library\n{\n\t// TODO: Array<bool> can be specialized as a bit-array to save memory.\n\t\n\t/**\n\t * A contiguous-memory dynamically resizing array.\n\t * Internally uses std::vector and provides more convenience methods to it.\n\t * Name chosen to disambiguate between vector the data container and vector the mathematical concept.\n\t *\n\t * @param <T>\t\t\t\t\tThe type for this container to store.\n\t * @param <ReserveStrategy>\t\tA callable type for determining a new capacity given the current memory usage.\n\t */\n\ttemplate<typename T, Concept::ReserveStrategy ReserveStrategy = Util::DefaultReserveStrategy>\n\tclass Array final\n\t{\n\tpublic:\n\t\tusing value_type = T;\n\t\tusing reference = T&;\n\t\tusing const_reference = const T&;\n\t\tusing pointer = T*;\n\t\tusing const_pointer = const T*;\n\t\tusing size_type = size_t;\n\t\tusing difference_type = ptrdiff_t;\n\t\tusing reserve_strategy = ReserveStrategy;\n\t\t\n\tprivate:\n\t\tusing internal_size_type = uint32_t;\n\t\t\n\t\tT* array{ nullptr };\n\t\tinternal_size_type size{ 0 };\n\t\tinternal_size_type capacity{ 0 };\n\n\tpublic:\n#pragma region Special Members\n\t\t/**\n\t\t * default ctor\n\t\t * creates an empty container owning no memory\n\t\t */\n\t\tArray() = default;\n\n\t\t/**\n\t\t * explicit ctor\n\t\t * \n\t\t * @param capacity\t\thow many elements worth of space to reserve\n\t\t */\n\t\texplicit Array(size_type capacity);\n\n\t\t/**\n\t\t * explicit ctor\n\t\t * \n\t\t * @param count\t\t\thow many elements of space to reserve and construct\n\t\t * @param prototype\t\tprototypical value to be copy-constructed into each element\n\t\t */\n\t\tArray(size_type count, const T& prototype);\n\n\t\t/**\n\t\t * explicit ctor\n\t\t * Fills the container with values read through the iterators.\n\t\t *\n\t\t * @param <It>\t\t\tthe iterator type\n\t\t * @param first\t\t\tthe beginning iterator, inclusive\n\t\t * @param last\t\t\tthe last iterator, exclusive\n\t\t */\n\t\ttemplate<std::forward_iterator It>\n\t\tArray(It first, It last);\n\n\t\t/**\n\t\t * explicit ctor\n\t\t * Fills the container with values read through the iterators.\n\t\t *\n\t\t * @param <It>\t\t\tthe iterator type\n\t\t * @param first\t\t\tthe beginning iterator, inclusive\n\t\t * @param last\t\t\tthe last iterator, exclusive\n\t\t */\n\t\ttemplate<std::random_access_iterator It>\n\t\tArray(It first, It last);\n\n\t\t/**\n\t\t * typecast ctor which accepts any range\n\t\t * will at most resize once\n\t\t *\n\t\t * @param range\t\t\tthe range to construct from\n\t\t */\n\t\ttemplate<Concept::RangeOf<T> Range>\n\t\tArray(const Range& range);\n\n\t\t/**\n\t\t * typecast ctor which accepts any range\n\t\t * will at most resize once\n\t\t *\n\t\t * @param range\t\t\tthe range to construct from\n\t\t */\n\t\ttemplate<Concept::RangeOf<T> Range>\n\t\tArray& operator=(const Range& range);\n\n\t\t/**\n\t\t * initializer_list ctor\n\t\t * \n\t\t * @param list\t\tthe initializer_list to construct this container from\n\t\t */\n\t\tArray(std::initializer_list<T> list);\n\n\t\t/**\n\t\t * initializer_list operator=\n\t\t * \n\t\t * @param list\t\tthe initializer_list to assign this container to\n\t\t * @return\t\t\tthis container after assignment\n\t\t */\n\t\tArray& operator=(std::initializer_list<T> list);\n\n\t\t/**\n\t\t * copy ctor\n\t\t * \n\t\t * @param other\t\tthe container to copy\n\t\t */\n\t\tArray(const Array& other);\n\n\t\t/**\n\t\t * move ctor\n\t\t *\n\t\t * @param other\t\tthe container to move, will be made empty after this operation\n\t\t */\n\t\tArray(Array&& other) noexcept;\n\n\t\t/**\n\t\t * copy operator=\n\t\t *\n\t\t * @param other\t\tthe container to move, will be made empty after this operation\n\t\t * @returns\t\t\tthis container after assignment\n\t\t */\n\t\tArray& operator=(const Array& other);\n\n\t\t/**\n\t\t * move operator=\n\t\t *\n\t\t * @param other\t\tthe container to move, will be made empty after this operation\n\t\t * @returns\t\t\tthis container after assignment\n\t\t */\n\t\tArray& operator=(Array&& other) noexcept;\n\n\t\t/**\n\t\t * templated copy ctor accepting containers with other ReserveStrategies\n\t\t * this container will keep its original reserve strategy\n\t\t *\n\t\t * @param other\t\tthe container to move, will be made empty after this operation\n\t\t * @returns\t\t\tthis container after assignment\n\t\t */\n\t\ttemplate<Concept::ReserveStrategy OtherReserveStrategy>\n\t\tArray(const Array<T, OtherReserveStrategy>& other);\n\n\t\t/**\n\t\t * templated move ctor accepting containers with other ReserveStrategies\n\t\t * this container will keep its original reserve strategy\n\t\t *\n\t\t * @param other\t\tthe container to move, will be made empty after this operation\n\t\t * @returns\t\t\tthis container after assignment\n\t\t */\n\t\ttemplate<Concept::ReserveStrategy OtherReserveStrategy>\n\t\tArray(Array<T, OtherReserveStrategy>&& other) noexcept;\n\n\t\t/**\n\t\t * templated copy operator= accepting containers with other ReserveStrategies\n\t\t * this container will keep its original reserve strategy\n\t\t *\n\t\t * @param other\t\tthe container to move, will be made empty after this operation\n\t\t * @returns\t\t\tthis container after assignment\n\t\t */\n\t\ttemplate<Concept::ReserveStrategy OtherReserveStrategy>\n\t\tArray& operator=(const Array<T, OtherReserveStrategy>& other);\n\n\t\t/**\n\t\t * templated move operator= accepting containers with other ReserveStrategies\n\t\t * this container will keep its original reserve strategy\n\t\t *\n\t\t * @param other\t\tthe container to move, will be made empty after this operation\n\t\t * @returns\t\t\tthis container after assignment\n\t\t */\n\t\ttemplate<Concept::ReserveStrategy OtherReserveStrategy>\n\t\tArray& operator=(Array<T, OtherReserveStrategy>&& other) noexcept;\n\n\t\t/**\n\t\t * dtor\n\t\t * frees all associated memory\n\t\t */\n\t\t~Array();\n#pragma endregion\n\n#pragma region iterator\t\t\n\t\tclass iterator final\n\t\t{\n\t\t\tfriend class Array;\n\t\t\tfriend class const_iterator;\n\n\t\tprivate:\n\t\t\tT* data{ nullptr };\n#ifdef _DEBUG\n\t\t\tArray* owner{ nullptr };\n#endif\n\t\t\t\n\t\tpublic:\n\t\t\tusing iterator_category = std::random_access_iterator_tag;\n\t\t\tusing value_type = T;\n\t\t\tusing difference_type = ptrdiff_t;\n\t\t\tusing pointer = T*;\n\t\t\tusing reference = T&;\n\n\t\tprivate:\n\t\t\titerator(T* data, [[maybe_unused]] Array* owner) noexcept :\n\t\t\t\tdata(data)\n#ifdef _DEBUG\n\t\t\t\t,owner(owner)\n#endif\n\t\t\t{}\n\t\t\t\n\t\tpublic:\n\t\t\t/**\n\t\t\t * explicit constructor\n\t\t\t *\n\t\t\t * @param index\t\tindex for this iterator to start at\n\t\t\t * @param owner\t\tthe container this iterator references\n\t\t\t */\n\t\t\titerator(const size_type index, Array& owner) noexcept :\n\t\t\t\titerator(owner.array + index, &owner) {}\n\n\t\t\tSPECIAL_MEMBERS(iterator, default)\n\n\t\t\t/**\n\t\t\t * Difference of two iterators.\n\t\t\t *\n\t\t\t * @param left\t\tlhs of the operator\n\t\t\t * @param right\t\trhs of the operator\n\t\t\t * @returns\t\t\tThe difference between the indices of the two iterators.\n\t\t\t *\n\t\t\t * @asserts\t\t\tThe iterators are initialized and they belong to the same container.\n\t\t\t */\n\t\t\t[[nodiscard]] friend difference_type operator-(const iterator left, const iterator right) noexcept\n\t\t\t{\n\t\t\t\t// No need to AssertInitialize anything because it will be called by operator +=\n\t\t\t\t// AssertInitialize is therefore implicitly called on right since we're comparing it to left's owner\n\t\t\t\tassertm(left.owner == right.owner, \"iterators must belong to the same container\");\n\t\t\t\treturn left.data - right.data;\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * Will not go beyond end().\n\t\t\t *\n\t\t\t * @param i\t\tHow much to increment the iterator by.\n\t\t\t * @returns\t\tA new iterator at that index.\n\t\t\t *\n\t\t\t * @asserts\t\tthis iterator is initialized\n\t\t\t */\n\t\t\t[[nodiscard]] iterator operator+(difference_type i) const noexcept;\n\t\t\t\n\t\t\t/**\n\t\t\t * @returns\t\tThe value of the index the iterator is at.\n\t\t\t *\n\t\t\t * @asserts\t\tthis iterator is initialized and not at end().\n\t\t\t */\n\t\t\t[[nodiscard]] reference operator*() const;\n\n\t\t\tRANDOM_ITER_OPS(iterator)\n\n\t\tprivate:\n\t\t\t/**\n\t\t\t * @asserts\t\tthis iterator is initialized.\n\t\t\t */\n\t\t\tconstexpr void AssertInitialized() const noexcept;\n\t\t};\n\n\t\tclass const_iterator final\n\t\t{\n\t\t\tfriend class Array;\n\t\t\tCONST_RANDOM_ACCESS_ITERATOR(const_iterator, iterator)\n\n\t\t\t/**\n\t\t\t * explicit constructor\n\t\t\t *\n\t\t\t * @param index\t\tindex for this iterator to start at\n\t\t\t * @param owner\t\tthe container this iterator references\n\t\t\t */\n\t\t\tconst_iterator(const size_t index, const Array& owner) noexcept :\n\t\t\t\tit{ index, const_cast<Array&>(owner) } {};\n\t\t};\n\n\t\tBEGIN_END(iterator, const_iterator, Array)\n\t\tMAKE_REVERSE_BEGIN_END\n#pragma endregion\n\n#pragma region Properties\n\t\t/**\n\t\t * @returns\t\ttrue if the container is empty, false otherwise\n\t\t */\n\t\t[[nodiscard]] constexpr bool IsEmpty() const noexcept;\n\n\t\t/**\n\t\t * @returns\t\ttrue if the container is full, false otherwise\n\t\t */\n\t\t[[nodiscard]] constexpr bool IsFull() const noexcept;\n\n\t\t/**\n\t\t * @returns\t\tHow many elements are in the container.\n\t\t */\n\t\t[[nodiscard]] constexpr size_type Size() const noexcept;\n\n\t\t/**\n\t\t * @returns\t\tThe number of elements this container can hold without resizing.\n\t\t */\n\t\t[[nodiscard]] constexpr size_type Capacity() const noexcept;\n\n\t\t/**\n\t\t * @param it\tan iterator\n\t\t * @returns\t\tthe index represented by the iterator\n\t\t */\n\t\t[[nodiscard]] constexpr size_type IndexOf(const_iterator it) const noexcept;\n#pragma endregion\n\n#pragma region Element Access\n\t\t/**\n\t\t * Returns a reference to the given index with bounds checking.\n\t\t * \n\t\t * @param index\t\tposition of the element to return\n\t\t * @returns\t\t\treference to the requested element\n\t\t *\n\t\t * @throws std::out_of_range\tif index >= Size()\n\t\t */\n\t\t[[nodiscard]] T& At(size_type index);\n\t\t\n\t\t/**\n\t\t * Returns a reference to the given index with bounds checking.\n\t\t *\n\t\t * @param index\t\tposition of the element to return\n\t\t * @returns\t\t\treference to the requested element\n\t\t *\n\t\t * @throws std::out_of_range\tif index >= Size()\n\t\t */\n\t\t[[nodiscard]] const T& At(size_type index) const;\n\n\t\t/**\n\t\t * Returns a reference to the given index with bounds checking.\n\t\t *\n\t\t * @param index\t\tposition of the element to return\n\t\t * @returns\t\t\treference to the requested element\n\t\t *\n\t\t * @throws std::out_of_range\tif index >= Size()\n\t\t */\n\t\t[[nodiscard]] T& operator[](size_type index);\n\n\t\t/**\n\t\t * Returns a reference to the given index with bounds checking.\n\t\t *\n\t\t * @param index\t\tposition of the element to return\n\t\t * @returns\t\t\treference to the requested element\n\t\t *\n\t\t * @throws std::out_of_range\tif index >= Size()\n\t\t */\n\t\t[[nodiscard]] const T& operator[](size_type index) const;\n\n\t\t/**\n\t\t * @returns\t\treference to the first element.\n\t\t *\n\t\t * @throws std::out_of_range\tif the container is empty\n\t\t */\n\t\t[[nodiscard]] T& Front();\n\n\t\t/**\n\t\t * @returns\t\treference to the first element.\n\t\t *\n\t\t * @throws std::out_of_range\tif the container is empty\n\t\t */\n\t\t[[nodiscard]] const T& Front() const;\n\n\t\t/**\n\t\t * @returns\t\treference to the last element.\n\t\t *\n\t\t * @throws std::out_of_range\tif the container is empty\n\t\t */\n\t\t[[nodiscard]] T& Back();\n\n\t\t/**\n\t\t * @returns\t\treference to the last element.\n\t\t *\n\t\t * @throws std::out_of_range\tif the container is empty\n\t\t */\n\t\t[[nodiscard]] const T& Back() const;\n#pragma endregion\n\t\t\n#pragma region Insert\n\t\t/**\n\t\t * @param index\t\twhere the new element will be constructed\n\t\t * @param t\t\t\tvalue to insert\n\t\t */\n\t\tvoid Insert(size_t index, const T& t);\n\t\t\n\t\t/**\n\t\t * @param index\t\twhere the new element will be constructed\n\t\t * @param t\t\t\tvalue to insert\n\t\t */\n\t\tvoid Insert(size_t index, T&& t);\n\n\t\t/**\n\t\t * @param index\t\twhere the new element will be constructed\n\t\t * @param count\t\thow many copies of the value to insert\n\t\t * @param t\t\t\tvalue to insert\n\t\t * @returns\t\t\titerator at the position of the last element inserted\n\t\t */\n\t\titerator Insert(size_t index, size_t count, const T& t);\n\n\t\t/**\n\t\t * @param index\t\twhere the new element will be constructed\n\t\t * @param list\t\tinitializer_list of values to insert\n\t\t * @returns\t\t\titerator at the position of the last element inserted\n\t\t */\n\t\titerator Insert(size_t index, std::initializer_list<T> list);\n\n\t\t/**\n\t\t * Insert elements through the values read from the iterators in the range [first, last).\n\t\t *\n\t\t * @param index\t\twhere the first new element will be constructed\n\t\t * @param first\t\tbeginning iterator, inclusive\n\t\t * @param last\t\tending iterator, exclusive\n\t\t * @returns\t\t\titerator at the position of the last element inserted\n\t\t *\n\t\t * @throws\t\t\tstd::invalid_argument if the iterators belong to this container\n\t\t */\n\t\ttemplate<std::forward_iterator It>\n\t\titerator Insert(size_t index, It first, It last);\n\n\t\t/**\n\t\t * @param it\t\tposition of where to insert\n\t\t * @param t\t\t\tprototypical value to insert\n\t\t *\n\t\t * @throws std::invalid_argument\tif the iterator does not belong to this container\n\t\t */\n\t\tvoid Insert(const_iterator it, const T& t);\n\t\t\n\t\t/**\n\t\t * @param it\t\tposition of where to insert\n\t\t * @param t\t\t\tprototypical value to insert\n\t\t *\n\t\t * @throws std::invalid_argument\tif the iterator does not belong to this container\n\t\t */\n\t\tvoid Insert(const_iterator it, T&& t);\n\n\t\t/**\n\t\t * @param it\t\tinitial position of where to insert\n\t\t * @param count\t\thow many copies of the prototype to insert\n\t\t * @param t\t\t\tprototypical value to insert\n\t\t * @returns\t\t\titerator at the last element inserted\n\t\t *\n\t\t * @throws std::invalid_argument\tif the iterator does not belong to this container\n\t\t */\n\t\titerator Insert(const_iterator it, size_t count, const T& t);\n\n\n\t\t/**\n\t\t * @param it\t\tinitial position of where to insert\n\t\t * @param list\t\tinitializer_list of values to insert\n\t\t * @returns\t\t\titerator at the last element inserted\n\t\t *\n\t\t * @throws std::invalid_argument\tif the iterator does not belong to this container\n\t\t */\n\t\titerator Insert(const_iterator it, std::initializer_list<T> list);\n\n\t\t/**\n\t\t * Insert elements through the values read from the iterators in the range [first, last).\n\t\t *\n\t\t * @param it\t\tinitial position of where to insert\n\t\t * @param first\t\tbeginning iterator, inclusive\n\t\t * @param last\t\tending iterator, exclusive\n\t\t * @returns\t\t\titerator at the position of the last element inserted\n\t\t *\n\t\t * @throws\t\t\tstd::invalid_argument if the iterators do not belong to this container\n\t\t */\n\t\ttemplate<std::forward_iterator It>\n\t\titerator Insert(const_iterator it, It first, It last);\n\n\t\t/**\n\t\t * Inserts a new element into the container directly at index.\n\t\t *\n\t\t * @param index\t\tPosition in the container to put this element.\n\t\t * @param args\t\tArguments to forward to the constructor of the element.\n\t\t *\n\t\t * @throws std::out_of_range\tif index > Size().\n\t\t */\n\t\ttemplate<typename... Args>\n\t\treference Emplace(size_t index, Args&&... args);\n\n\t\t/**\n\t\t * Inserts a new element into the container directly at index.\n\t\t * The passed iterator is guaranteed to be valid and pointing at the position of the newly emplaced element after the operation.\n\t\t *\n\t\t * @param it\t\tPosition in the container to put this element.\n\t\t * @param args\t\tArguments to forward to the constructor of the element.\n\t\t *\n\t\t * @throws std::out_of_range\tif index > Size().\n\t\t */\n\t\ttemplate<typename... Args>\n\t\treference Emplace(const_iterator it, Args&&... args);\n\n\t\t/**\n\t\t * Appends a new element to the end of the container.\n\t\t * O(1) most cases.\n\t\t * O(n) if the operation requires a Resize().\n\t\t * \n\t\t * @param args\t\tArguments to forward to the constructor of the element.\n\t\t */\n\t\ttemplate<typename... Args>\n\t\treference EmplaceBack(Args&&... args);\n\n\t\t/**\n\t\t * Appends a new element to the front of the container.\n\t\t * O(1) most cases.\n\t\t * O(n) if the operation requires a Resize().\n\t\t *\n\t\t * @param args\t\tArguments to forward to the constructor of the element.\n\t\t */\n\t\ttemplate<typename... Args>\n\t\treference EmplaceFront(Args&&... args);\n\t\t\n\t\t/**\n\t\t * Appends the element to the end of the container.\n\t\t * O(1) most cases.\n\t\t * O(n) if the operation requires a Resize().\n\t\t * \n\t\t * @param t\t\tThe value of the element to append.\n\t\t */\n\t\tvoid PushBack(const T& t);\n\t\t\n\t\t/**\n\t\t * Appends the element to the end of the container.\n\t\t * O(n) where n is Size().\n\t\t * \n\t\t * @param t\t\tThe value of the element to append.\n\t\t */\n\t\tvoid PushBack(T&& t);\n\n\t\t/**\n\t\t * Appends the element to the front of the container.\n\t\t * O(n) where n is Size().\n\t\t * \n\t\t * @param t\t\tThe value of the element to prepend.\n\t\t */\n\t\tvoid PushFront(const T& t);\n\n\t\t/**\n\t\t * Appends the element to the front of the container.\n\t\t * O(n) where n is Size().\n\t\t * \n\t\t * @param t\t\tThe value of the element to prepend.\n\t\t */\n\t\tvoid PushFront(T&& t);\n\n\t\t/**\n\t\t * Insert elements through the values read from the iterators in the range [first, last).\n\t\t * Only resizes once (this is most efficient if It is a random access iterator).\n\t\t *\n\t\t * @param it\t\tinitial position of where to insert\n\t\t * @param first\t\tbeginning iterator, inclusive\n\t\t * @param last\t\tending iterator, exclusive\n\t\t * @returns\t\t\titerator at the position of the last element inserted\n\t\t */\n\t\ttemplate<std::forward_iterator It>\n\t\tvoid PushBack(It first, It last);\n\n\t\t/**\n\t\t * Insert elements through the values read from the iterators in the range [first, last).\n\t\t * Only resizes once (this is most efficient if It is a random access iterator).\n\t\t *\n\t\t * @param it\t\tinitial position of where to insert\n\t\t * @param first\t\tbeginning iterator, inclusive\n\t\t * @param last\t\tending iterator, exclusive\n\t\t * @returns\t\t\titerator at the position of the last element inserted\n\t\t */\n\t\ttemplate<std::forward_iterator It>\n\t\tvoid PushFront(It first, It last);\n\n\t\t/**\n\t\t * Copies the passed prototypical value into the remaining empty slots.\n\t\t * O(n) where n is Capacity() - Size().\n\t\t *\n\t\t * @param prototype\t\tThe prottype to fill the container with.\n\t\t */\n\t\tvoid Fill(const T& prototype);\n#pragma endregion\n\n#pragma region Remove\n\t\t/**\n\t\t * Removes the first instance of the passed value from the container.\n\t\t * Will only return false if the value did not exist in the container.\n\t\t * A return value of true does not imply that no duplicate values do not still exist in the container.\n\t\t * All elements after the removed one get shifted to the left in memory.\n\t\t * O(n)\n\t\t * \n\t\t * @param t\t\tThe value to remove.\n\t\t * @returns\t\tWhether or not a removal operation was performed.\n\t\t */\n\t\tbool Remove(const T& t);\n\n\t\t/**\n\t\t * Removes the first element matching the passed predicate.\n\t\t * Will only return false if the value did not exist in the container.\n\t\t * A return value of true does not imply that no duplicate values do not still exist in the container.\n\t\t * All elements after the removed one get shifted to the left in memory.\n\t\t * O(n)\n\t\t * \n\t\t * @param predicate\t\tThe predicate to query with.\n\t\t * @returns\t\t\t\tWhether or not a removal was performed.\n\t\t */\n\t\ttemplate<std::predicate<T> Predicate>\n\t\tbool Remove(Predicate predicate);\n\n\t\t/**\n\t\t * Removes the index specified and shift values to the left over.\n\t\t * O(n) where n is Size() - index;\n\t\t * \n\t\t * @param index\t\tThe index to remove.\n\t\t */\n\t\tvoid RemoveAt(size_t index);\n\n\t\t/**\n\t\t * Removes all elements matching the specified value.\n\t\t * O(n)\n\t\t * \n\t\t * @param t\t\tThe value to remove all instances of.\n\t\t * @returns\t\tHow many removals were performed.\n\t\t */\n\t\tsize_t RemoveAll(const T& t);\n\n\t\t/**\n\t\t * Removes all elements matching the passed predicate.\n\t\t * O(n)\n\t\t * \n\t\t * @param predicate\t\tThe predicate to query with.\n\t\t * @returns\t\t\t\tHow many elements were removed.\n\t\t */\n\t\ttemplate<std::predicate<T> Predicate>\n\t\tsize_t RemoveAll(Predicate predicate);\n\n\t\ttemplate<std::predicate<T> Predicate>\n\t\tfriend size_t erase_if(Array& arr, const Predicate predicate)\n\t\t{\n\t\t\treturn arr.RemoveAll(predicate);\n\t\t}\n\n\t\t/**\n\t\t * Removes the range [first, last) elements between the two passed indices.\n\t\t * If last is beyond Size() then all elements from first to the end will be removed safely.\n\t\t * Does nothing if the indices are both beyond Size().\n\t\t * \n\t\t * @param first\t\tindex of the first value to remove, inclusive.\n\t\t * @param last\t\tindex of the last value to remove, exclusive.\n\t\t * @returns\t\t\tThe number of elements removed, equal to first - last unless last > Size().\n\t\t *\n\t\t * @throws std::invalid_argument\tif first > last.\n\t\t */\n\t\tsize_t Remove(size_t first, size_t last);\n\n\t\t/**\n\t\t * Removes the range [first, last) elements between the two passed iterators.\n\t\t * O(n) where n = Size() - first\n\t\t *\n\t\t * @param first\t\titerator at the first element to remove, inclusive\n\t\t * @param last\t\titerator at the last element to remove, exclusive\n\t\t * @returns\t\t\tThe number of elements removed.\n\t\t */\n\t\tsize_t Remove(const_iterator first, const_iterator last);\n\t\t\n\t\t/**\n\t\t * O(1)\n\t\t * Removes the last element of the container.\n\t\t * Does nothing if the container is empty.\n\t\t */\n\t\tvoid PopBack();\n\t\t\n\t\t/**\n\t\t * O(n) where n = Size() - 1 before the operation.\n\t\t * Removes the first element of the container.\n\t\t * Does nothing if the container is empty.\n\t\t */\n\t\tvoid PopFront();\n\t\t\n\t\t/**\n\t\t * Erases all elements from the container by calling the destructors on each of them.\n\t\t * Afterwards Size() == 0.\n\t\t */\n\t\tvoid Clear() noexcept;\n\n\t\t/**\n\t\t * Erases all memory held by this container. \n\t\t */\n\t\tvoid Empty() noexcept;\n#pragma endregion\n\n#pragma region Query\n\t\t/**\n\t\t * Does an O(n) search for the first occurrence of the passed element.\n\t\t * \n\t\t * @param t\t\t\t\tthe element to query for.\n\t\t * @returns\t\t\t\tthe index of the first element found, or Size() if it was not found.\n\t\t */\n\t\tsize_type IndexOf(const T& t) const;\n\n\t\t/**\n\t\t * Does an O(n) search for the first element matching the passed predicate.\n\t\t *\n\t\t * @param predicate\t\tthe predicate to query with.\n\t\t * @returns\t\t\t\tthe index of the first element found, or Size() if it was not found.\n\t\t */\n\t\ttemplate<std::predicate<T> Predicate>\n\t\tsize_type IndexOf(Predicate predicate) const;\n#pragma endregion\n\t\t\n#pragma region Memory\t\t\n\t\t/**\n\t\t * Warning! Use at your own risk! Manipulating this memory can invalidate the state of the Array.\n\t\t *\n\t\t * @returns\t\tpointer to the underlying data. nullptr if the container is empty.\n\t\t */\n\t\t[[nodiscard]] T* Data() noexcept;\n\n\t\t/**\n\t\t * Warning! Use at your own risk! Manipulating this memory can invalidate the state of the Array.\n\t\t *\n\t\t * @returns\t\tpointer to the underlying data. nullptr if the container is empty.\n\t\t */\n\t\t[[nodiscard]] const T* Data() const noexcept;\n\n\t\t/**\n\t\t * Gets the underlying data and empties this container without deallocating any memory.\n\t\t * Guaranteed to cause a memory leak if the caller discards this return value.\n\t\t * Caller assumes all responsibility for managing this data.\n\t\t * \n\t\t * @returns\t\tpointer, size, capacity\n\t\t */\n\t\t[[nodiscard]]\n\t\tstd::tuple<gsl::owner<T*>, size_t, size_t> TakeData() noexcept;\n\n\t\t/**\n\t\t * Force this container to take on the given memory.\n\t\t * Will free all currently associated memory and destruct all objects.\n\t\t * The container will manage the given data as if it had allocated it itself,\n\t\t * possibly reallocating it in the event of an operation that would do such a thing.\n\t\t * \n\t\t * @param data\tpointer, size, capacity\n\t\t */\n\t\tvoid SetData(std::tuple<T*, size_t, size_t> data) noexcept;\n\n\t\t/**\n\t\t * Force this container to take on the given memory.\n\t\t * Will free all currently associated memory and destruct all objects.\n\t\t * The container will manage the given data as if it had allocated it itself,\n\t\t * possibly reallocating it in the event of an operation that would do such a thing.\n\t\t * \n\t\t * @param array\t\tpointer to array of T\n\t\t * @param size\t\thow many elements array contains\n\t\t * @param capacity\thow many elements array can store \n\t\t */\n\t\tvoid SetData(T* array, size_t size, size_t capacity) noexcept;\n\t\t\n\t\t/**\n\t\t * O(n) where n is the current size of the container.\n\t\t * Does nothing if newCapacity <= Capacity().\n\t\t * \n\t\t * @param newCapacity\tThe new capacity for the container.\n\t\t *\n\t\t * @throws std::length_error\tif newCapacity > MaxSize()\n\t\t * @throws std::bad_alloc\t\tif memory allocation fails.\t\n\t\t */\n\t\tvoid Reserve(size_t newCapacity);\n\n\t\t/**\n\t\t * O(n) where n = newSize - Size(), or n = newSize if the operation requires a Reserve().\n\t\t * If the current Size() is greater than newSize, the container is reduced to its first newSize elements.\n\t\t *\n\t\t * @param newSize\t\tThe new size for the container.\n\t\t * @param prototype\t\tThe value to initialize each new element with.\n\t\t */\n\t\tvoid Resize(size_t newSize, const T& prototype = T());\n\n\t\t/**\n\t\t * Reduces memory usage such that Size() == Capacity().\n\t\t * O(n) where n = Size().\n\t\t * Does nothing if IsFull()\n\t\t */\n\t\tvoid ShrinkToFit();\n\n\t\t/**\n\t\t * Reduces memory usage such that Capacity() == std::max(count, Size()).\n\t\t * O(n) where n = Size().\n\t\t * Does nothing if Capacity() already == std::max(count, Size()).\n\t\t */\n\t\tvoid ShrinkToFit(size_t count);\n\n\t\t/**\n\t\t * TODO: It might be that the STL expects swap to be lowercase and a non-member function (so a friend function will do).\n\t\t * O(1)\n\t\t * \n\t\t * @param <OtherReserveStrategy>\ttemplate parameter allowing swapping Arrays with different ReserveStrategies.\n\t\t * @param other\t\t\t\t\t\tcontainer to exchange contents with.\n\t\t */\n\t\ttemplate<Concept::ReserveStrategy OtherReserveStrategy>\n\t\tvoid Swap(Array<T, OtherReserveStrategy>& other) noexcept;\n\n\t\t/**\n\t\t * Reverses the order of the elements in the container.\n\t\t * O(n)\n\t\t */\n\t\tvoid Reverse() noexcept;\n#pragma endregion\n\n#pragma region Operators\n\t\t/**\n\t\t * templated operator== to allow for comparing containers with different reserve strategies\n\t\t *\n\t\t * @param <OtherReserveStrategy>\treserve strategy for the other container\n\t\t * @param left\t\t\t\t\t\tlhs container\n\t\t * @param right\t\t\t\t\t\trhs container\n\t\t * @returns\t\t\t\t\t\t\twhether or not the two containers are equal.\n\t\t */\n\t\ttemplate<Concept::ReserveStrategy OtherReserveStrategy>\n\t\t[[nodiscard]] friend bool operator==(const Array& left, const Array<T, OtherReserveStrategy>& right)\n\t\t{\n\t\t\treturn &left == reinterpret_cast<const Array*>(&right) || left.Size() == right.Size() && std::equal(left.begin(), left.end(), right.begin(), right.end());\n\t\t}\n\n\t\t/**\n\t\t * templated operator== to allow for comparing containers with different reserve strategies\n\t\t *\n\t\t * @param <OtherReserveStrategy>\treserve strategy for the other container\n\t\t * @param left\t\t\t\t\t\tlhs container\n\t\t * @param right\t\t\t\t\t\trhs container\n\t\t * @returns\t\t\t\t\t\t\twhether or not the two containers are equal.\n\t\t */\n\t\ttemplate<Concept::ReserveStrategy OtherReserveStrategy>\n\t\t[[nodiscard]] friend bool operator!=(const Array& left, const Array<T, OtherReserveStrategy>& right)\n\t\t{\n\t\t\treturn !operator==(left, right);\n\t\t}\n\t\t\n\t\tfriend std::ostream& operator<<(std::ostream& stream, const ARRAY& array) noexcept\n\t\t{\n\t\t\tUtil::StreamTo(stream, array.begin(), array.end());\n\t\t\treturn stream;\n\t\t}\n#pragma endregion\n\n#pragma region Helpers\n\tprivate:\n\t\t/**\n\t\t * assumes Capacity() is sufficient\n\t\t *\n\t\t * @param first\t\tthe beginning iterator to read from (inclusive)\n\t\t * @param last\t\tthe ending iterator to read from (exclusive)\n\t\t */\n\t\ttemplate<std::forward_iterator It>\n\t\tvoid PushBackNoResize(It first, It last);\n\t\t\n\t\t/**\n\t\t * Helper for methods that accept iterators.\n\t\t *\n\t\t * @param it\t\tThe iterator who's owner to compare against this.\n\t\t *\n\t\t * @asserts\t\t\towner == this\n\t\t */\n\t\tvoid AssertOwner(iterator it) const;\n\t\t\n\t\t/**\n\t\t * @param it\t\tThe iterator who's owner to compare against this.\n\t\t *\n\t\t * @asserts\t\t\towner == this\n\t\t */\n\t\tvoid AssertOwner(const_iterator it) const;\n\t\t\n\t\t/**\n\t\t * Calls the ReserveStrategy template argument and sanity checks its return value.\n\t\t * @returns\t\tA safe new Capacity() for this container.\n\t\t */\n\t\t[[nodiscard]] size_type InvokeReserveStrategy() const noexcept;\n\t\t\n\t\t/**\n\t\t * Calls destructor on all elements.\n\t\t */\n\t\tvoid DestructAll() noexcept;\n\n\t\t/**\n\t\t * Calls the destructor on all elements in range [first, last).\n\t\t * \n\t\t * @param first\t\tIndex of first element to be deconstructed, inclusive.\n\t\t * @param last\t\tIndex of last element to be decondstructed, exclusive.\n\t\t */\n\t\tvoid DestructAll(const size_type first, const size_type last) noexcept;\n\n\t\t/**\n\t\t * Shifts the internal array to the right starting at the passed index.\n\t\t * Moves memory as if calling the destructor on elements before they're overwritten and after they're moved.\n\t\t * \n\t\t * @param startIndex\tThe index to start the shifts at.\n\t\t * @param shiftAmount\tHow much to shift by.\n\t\t */\n\t\tvoid ShiftRight(size_type startIndex = 0, size_type shiftAmount = 1) noexcept;\n\n\t\t/**\n\t\t * Shifts the internal array to the left starting at the passed index.\n\t\t * Moves memory as if calling the destructor on elements before they're overwritten and after they're moved.\n\t\t * \n\t\t * @param startIndex\tThe index to start the shifts at.\n\t\t * @param shiftAmount\tHow much to shift by.\n\t\t */\n\t\tvoid ShiftLeft(size_type startIndex = 0, size_type shiftAmount = 1) noexcept;\n\t\t\n\t\t/**\n\t\t * Helper called from constructors.\n\t\t * Assumes size is 0 and capacity is sufficient.\n\t\t * \n\t\t * @param list\t\tlist to copy elements from.\n\t\t */\n\t\tvoid Copy(std::initializer_list<T> list);\n\n\t\t/**\n\t\t * Helper called from constructors.\n\t\t * Assumes size is 0 and capacity is sufficient.\n\t\t *\n\t\t * @param list\t\tlist to copy elements from.\n\t\t */\n\t\ttemplate<typename OtherReserveStrategy>\n\t\tvoid Copy(const Array<T, OtherReserveStrategy>& other);\n\n\t\t/**\n\t\t * Helper called from copy assignment operators.\n\t\t *\n\t\t * @param other\t\tThe array being copied.\n\t\t * @returns\t\t\tthis after the copy.\n\t\t */\n\t\ttemplate<typename OtherReserveStrategy>\n\t\t[[nodiscard]] Array& CopyAssign(const Array<T, OtherReserveStrategy>& other);\n\n\t\t/**\n\t\t * Helper called from move assignment operators.\n\t\t *\n\t\t * @param other\t\tThe array being moved.\n\t\t * @returns\t\t\tthis after the move.\n\t\t */\n\t\ttemplate<typename OtherReserveStrategy>\n\t\t[[nodiscard]] Array& MoveAssign(Array<T, OtherReserveStrategy>&& other);\n\n\t\t/**\n\t\t * Helper called from constructors.\n\t\t * Sets this Array's state after std::move.\n\t\t */\n\t\tvoid SetPostMoveState();\n#pragma endregion\n\t};\n}\n\n#include \"Array.inl\"\n", "meta": {"hexsha": "5522575a94c00d99d14483f7b7578740f6251769", "size": 30005, "ext": "h", "lang": "C", "max_stars_repo_path": "source/Library/containers/Array.h", "max_stars_repo_name": "JarrettWendt/FIEAEngine", "max_stars_repo_head_hexsha": "0bf7e89cd66fec29550f7d7a1a11f5cf398c27e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-05-27T14:01:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T09:11:58.000Z", "max_issues_repo_path": "source/Library/containers/Array.h", "max_issues_repo_name": "JarrettWendt/FIEAEngine", "max_issues_repo_head_hexsha": "0bf7e89cd66fec29550f7d7a1a11f5cf398c27e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/Library/containers/Array.h", "max_forks_repo_name": "JarrettWendt/FIEAEngine", "max_forks_repo_head_hexsha": "0bf7e89cd66fec29550f7d7a1a11f5cf398c27e5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6486210419, "max_line_length": 157, "alphanum_fraction": 0.6806198967, "num_tokens": 7422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1602660483710466, "lm_q2_score": 0.05184546756540989, "lm_q1q2_score": 0.008309068212657509}}
{"text": "#ifdef __GNUC__\n\t#define LIBKLR_API\t\n#else\n\t#ifdef LIBKLR_EXPORTS\n\t#define LIBKLR_API __declspec(dllexport)\n\t#else\n\t#define LIBKLR_API __declspec(dllimport)\n\t#endif\n#endif\n\n#pragma once\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <time.h>\n\n#ifdef __APPLE__\n#include <Accelerate/Accelerate.h>\n#else\n#include <cblas.h>\n#endif\n\n/* Matrix manipulation */\n#define MAT(X, row, i, j) ((X)[(i)+(j)*row])\n\n\nclass LIBKLR_API Clibklr {\n  int class_num;        /* Number of classes */\n  int sample_num;       /* Number of tatal MFCC's */\n  int itrKLR0;          /* KLR0 iteration*/\n  int itrCG;            /* Conjugate Gradient iteration */\n  int itrNewton;        /* Newton method iteration*/\n  double tparam;        /* if the error of gradient is less than tparam, stop CG*/\n  double *weight;       /* Importance Weight*/\n  double delta;         /* Generalization parameter for KLR*/\n  double *Vparam;       /* KLR parameter*/\npublic:\n\tClibklr(int c, int n);\n\n\tvoid set_class_num(int temp){class_num = temp;}\n\tvoid set_sample_num(int temp){sample_num = temp;}\n\tvoid set_itrKLR0(int temp){itrKLR0 = temp;}\n\tvoid set_itrCG(int temp){itrCG = temp;}\n\tvoid set_itrNewton(int temp){itrNewton = temp;}\n\tvoid set_tparam(double temp){tparam = temp;}\n\tvoid set_delta(double temp){delta = temp;}\n\t\n\tint get_class_num(void){return class_num;}\n\tint get_sample_num(void){return sample_num;}\n\tint get_itrKLR0(void){return itrKLR0;}\n\tint get_itrCG(void){return itrCG;}\n\tint get_itrNewton(void){return itrNewton;}\n\tdouble get_tparam(void){return tparam;}\n\tdouble get_delta(void){return delta;}\n\n\tvoid set_weight(double *inweight){ \n\t  for(int i = 0; i < sample_num; i++){\n\t    weight[i] = inweight[i];\n\t  }\n\t}\n\n\tvoid get_V(double* Vexp){\n\t  for(int i = 0; i < class_num; i++){\n\t    for(int j = 0; j < sample_num; j++){\n\t      Vexp[(i)+(j)*class_num] = Vparam[(i)+(j)*class_num];\n\t\t\t}\n\t\t}\n\t}\n\n\t/*  Train Kernel Logistic Regression */\n\tvoid train(double *Ktrain, int *label);\n\t/* Test KLR (vector kernel)*/\n\tdouble* test(double *Ktest, int n_test, double* V, int c, int n_train);\n\t/* Conjugate Gradient Method*/\n\tvoid CG(double*,double*, double*,double*,int,int,double*,int);\n\t/* Label matrix generation*/\n\tvoid yconst(int*, double*, int, int);\n\t/* Logistic Transform*/\n\tvoid mlogistic(double*, int, int);\n\t/* Norm computation */\n\tdouble norm(double *input, int c, int n);\n\tint* malloc_int(int n);\n\tdouble* malloc_double(int n);\n\tint display_array(double*, const int, const int);\n};\n\nextern LIBKLR_API int nlibklr;\n\nLIBKLR_API int fnlibklr(void);\n", "meta": {"hexsha": "1c28c254a2d5333a1a999578d1d1b51d11429d28", "size": 2541, "ext": "h", "lang": "C", "max_stars_repo_path": "contrib/libklr-2010_05_07/src/libklr.h", "max_stars_repo_name": "chungying/nuklei", "max_stars_repo_head_hexsha": "23db2a55a1b3260cf913d0ac10b3b27c000ae1a6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "contrib/libklr-2010_05_07/src/libklr.h", "max_issues_repo_name": "chungying/nuklei", "max_issues_repo_head_hexsha": "23db2a55a1b3260cf913d0ac10b3b27c000ae1a6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "contrib/libklr-2010_05_07/src/libklr.h", "max_forks_repo_name": "chungying/nuklei", "max_forks_repo_head_hexsha": "23db2a55a1b3260cf913d0ac10b3b27c000ae1a6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9230769231, "max_line_length": 82, "alphanum_fraction": 0.6753246753, "num_tokens": 699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.414898860266261, "lm_q2_score": 0.020023440668109332, "lm_q1q2_score": 0.008307702711807662}}
{"text": "#pragma once\n\n#include \"halley/text/halleystring.h\"\n#include <thread>\n#include <gsl/span>\n#include <atomic>\n\n#include \"halley/data_structures/hash_map.h\"\n#include \"halley/time/halleytime.h\"\n\nnamespace Halley {\n\tenum class ProfilerEventType {\n\t    CorePumpEvents,\n\t\tCoreDevConClient,\n\t\tCorePumpAudio,\n\t\tCoreFixedUpdate,\n\t\tCoreVariableUpdate,\n\t\tCoreUpdateSystem,\n\t\tCoreUpdatePlatform,\n\t\tCoreUpdate,\n\t\tCoreStartRender,\n\t\tCoreRender,\n\t\tCoreVSync,\n\n\t\tPainterDrawCall,\n\t\tPainterEndRender,\n\t\tPainterUpdateProjection,\n\n\t\tWorldVariableUpdate,\n\t\tWorldFixedUpdate,\n\t\tWorldRender,\n\t\tWorldSystemUpdate,\n\t\tWorldSystemRender,\n\n\t\tAudioGenerateBuffer,\n\n\t\tDiskIO,\n\n\t\tStatsView,\n\n\t\tGame\n    };\t\n\n    class ProfilerData {\n    public:\n        using TimePoint = std::chrono::steady_clock::time_point;\n    \tusing Duration = std::chrono::duration<int64_t, std::nano>;\n    \t\n\t\tclass Event {\n        public:\n\t        String name;\n        \tstd::thread::id threadId;\n\t\t\tProfilerEventType type;\n\t\t\tint depth;\n        \tuint64_t id;\n        \tTimePoint startTime;\n        \tTimePoint endTime;\n        };\n\n    \tclass ThreadInfo {\n    \tpublic:\n    \t\tstd::thread::id id;\n    \t\tint maxDepth = 0;\n    \t\tString name;\n    \t\tTimePoint startTime;\n    \t\tTimePoint endTime;\n    \t\tDuration totalTime;\n\n    \t\tbool operator< (const ThreadInfo& other) const;\n    \t};\n\n    \tProfilerData() = default;\n    \tProfilerData(TimePoint frameStartTime, TimePoint frameEndTime, std::vector<Event> events);\n\n    \tTimePoint getStartTime() const;\n    \tTimePoint getEndTime() const;\n    \tconst std::vector<Event>& getEvents() const;\n    \tDuration getTotalElapsedTime() const;\n\t\tDuration getElapsedTime(ProfilerEventType eventType) const;\n\n    \tgsl::span<const ThreadInfo> getThreads() const;\n\n    private:\n    \tTimePoint frameStartTime;\n    \tTimePoint frameEndTime;\n    \tstd::vector<Event> events;\n\n    \tstd::vector<ThreadInfo> threads;\n\n    \tvoid processEvents();\n    };\n\t\n    class ProfilerCapture {\n    public:\n        using EventId = uint64_t;\n    \t\n        ProfilerCapture(size_t maxEvents = 16384);\n    \t\n    \t[[nodiscard]] static ProfilerCapture& get();\n\n    \t[[nodiscard]] EventId recordEventStart(ProfilerEventType type, std::string_view name);\n    \tvoid recordEventEnd(EventId id);\n\n    \t[[nodiscard]] bool isRecording() const;\n\n    \tvoid startFrame(bool record);\n    \tvoid endFrame();\n\t\tProfilerData getCapture();\n\n    \tTime getFrameTime() const;\n\n    private:\n    \tenum class State {\n    \t\tIdle,\n    \t\tFrameStarted,\n    \t\tFrameEnded\n    \t};\n\n    \tstd::atomic<bool> recording;\n    \tstd::atomic<uint64_t> curId;\n    \tuint64_t startId;\n    \tstd::atomic<uint64_t> endId;\n        State state = State::Idle;\n    \t\n    \tstd::chrono::steady_clock::time_point frameStartTime;\n    \tstd::chrono::steady_clock::time_point frameEndTime;\n\n    \tstd::vector<ProfilerData::Event> events;\n    };\n\n\tclass ProfilerEvent {\n\tpublic:\n\t\tProfilerEvent(ProfilerEventType type, std::string_view name = \"\");\n\t\t~ProfilerEvent() noexcept;\n\n\t\tProfilerEvent(const ProfilerEvent& other) = delete;\n\t\tProfilerEvent(ProfilerEvent&& other) = delete;\n\t\tProfilerEvent& operator=(const ProfilerEvent& other) = delete;\n\t\tProfilerEvent& operator=(ProfilerEvent&& other) = delete;\n\n\tprivate:\n\t\tProfilerCapture::EventId id;\n\t};\n}\n", "meta": {"hexsha": "f4f230547265d3c42da67e5849aa48fac8f9f3d6", "size": 3235, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engine/utils/include/halley/support/profiler.h", "max_stars_repo_name": "pinguin999/halley", "max_stars_repo_head_hexsha": "895e5ae482787eb09185928625e1ee9be3845fbc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/engine/utils/include/halley/support/profiler.h", "max_issues_repo_name": "pinguin999/halley", "max_issues_repo_head_hexsha": "895e5ae482787eb09185928625e1ee9be3845fbc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engine/utils/include/halley/support/profiler.h", "max_forks_repo_name": "pinguin999/halley", "max_forks_repo_head_hexsha": "895e5ae482787eb09185928625e1ee9be3845fbc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.3103448276, "max_line_length": 95, "alphanum_fraction": 0.6766615147, "num_tokens": 802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23934933647101644, "lm_q2_score": 0.03461884020868244, "lm_q1q2_score": 0.008285996433344286}}
{"text": "#include \"jfftw_Wisdom.h\"\n#include <fftw.h>\n\n/*\n * Class:     jfftw_Wisdom\n * Method:    get\n * Signature: ()Ljava/lang/String;\n */\nJNIEXPORT jstring JNICALL Java_jfftw_Wisdom_get( JNIEnv * env, jclass clazz )\n{\n\tchar* cwisdom = fftw_export_wisdom_to_string();\n\n\tjstring wisdom = (*env)->NewStringUTF( env, cwisdom );\n\tfftw_free( cwisdom );\n\n\treturn wisdom;\n}\n/*\n * Class:     jfftw_Wisdom\n * Method:    add\n * Signature: (Ljava/lang/String;)V\n */\nJNIEXPORT void JNICALL Java_jfftw_Wisdom_add( JNIEnv * env, jclass clazz, jstring wisdom )\n{\n\tconst char* cwisdom = (*env)->GetStringUTFChars( env, wisdom, NULL );\n\n\tfftw_status s = fftw_import_wisdom_from_string( cwisdom );\n\n\t(*env)->ReleaseStringUTFChars( env, wisdom, cwisdom );\n\n\tif( s == FFTW_FAILURE )\n\t{\n\t\t(*env)->ThrowNew( env, (*env)->FindClass( env, \"java/lang/IllegalArgumentException\" ), \"unable to parse wisdom\" );\n\t}\n}\n/*\n * Class:     jfftw_Wisdom\n * Method:    clear\n * Signature: ()V\n */\nJNIEXPORT void JNICALL Java_jfftw_Wisdom_clear( JNIEnv * env, jclass clazz )\n{\n\tfftw_forget_wisdom();\n}\n", "meta": {"hexsha": "66a5ccca4d41e75a1820790f6a22c05d39eaa824", "size": 1057, "ext": "c", "lang": "C", "max_stars_repo_path": "triana-toolboxes/signalproc/src/main/java/signalproc/algorithms/c/jfftw_Wisdom.c", "max_stars_repo_name": "CSCSI/Triana", "max_stars_repo_head_hexsha": "da48ffaa0183f59e3fe7c6dc59d9f91234e65809", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2015-11-02T10:12:13.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-15T21:45:38.000Z", "max_issues_repo_path": "triana-toolboxes/signalproc/src/main/java/signalproc/algorithms/c/jfftw_Wisdom.c", "max_issues_repo_name": "CSCSI/Triana", "max_issues_repo_head_hexsha": "da48ffaa0183f59e3fe7c6dc59d9f91234e65809", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-08-28T13:52:42.000Z", "max_issues_repo_issues_event_max_datetime": "2016-01-22T13:06:00.000Z", "max_forks_repo_path": "triana-toolboxes/signalproc/src/main/java/signalproc/algorithms/c/jfftw_Wisdom.c", "max_forks_repo_name": "CSCSI/Triana", "max_forks_repo_head_hexsha": "da48ffaa0183f59e3fe7c6dc59d9f91234e65809", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-03-08T14:04:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T05:30:21.000Z", "avg_line_length": 23.4888888889, "max_line_length": 116, "alphanum_fraction": 0.6887417219, "num_tokens": 315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632159254749036, "lm_q2_score": 0.01941934665728465, "lm_q1q2_score": 0.008278886793165376}}
{"text": "#pragma once\n\n#include \"BoundingVolume.h\"\n#include \"Library.h\"\n#include \"TileContentLoadResult.h\"\n#include \"TileContentLoader.h\"\n#include \"TileID.h\"\n#include \"TileRefine.h\"\n\n#include <CesiumGltf/GltfReader.h>\n\n#include <glm/mat4x4.hpp>\n#include <gsl/span>\n#include <spdlog/fwd.h>\n\n#include <cstddef>\n\nnamespace Cesium3DTilesSelection {\n\nclass Tileset;\n\n/**\n * @brief Creates {@link TileContentLoadResult} from glTF data.\n */\nclass CESIUM3DTILESSELECTION_API GltfContent final : public TileContentLoader {\npublic:\n  /**\n   * @copydoc TileContentLoader::load\n   *\n   * The result will only contain the `model`. Other fields will be\n   * empty or have default values.\n   */\n  CesiumAsync::Future<std::unique_ptr<TileContentLoadResult>>\n  load(const TileContentLoadInput& input) override;\n\n  /**\n   * @brief Create a {@link TileContentLoadResult} from the given data.\n   *\n   * (Only public to be called from `Batched3DModelContent`)\n   *\n   * @param pLogger Only used for logging\n   * @param url The URL, only used for logging\n   * @param data The actual glTF data\n   * @return The {@link TileContentLoadResult}\n   */\n  static std::unique_ptr<TileContentLoadResult> load(\n      const std::shared_ptr<spdlog::logger>& pLogger,\n      const std::string& url,\n      const gsl::span<const std::byte>& data);\n\n  /**\n   * @brief Creates texture coordinates for mapping {@link RasterOverlay} tiles\n   * to {@link Tileset} tiles.\n   *\n   * Generates new texture coordinates for the `gltf` using the given\n   * `projection`. The first new texture coordinate (`u` or `s`) will be 0.0 at\n   * the `minimumX` of the given `rectangle` and 1.0 at the `maximumX`. The\n   * second texture coordinate (`v` or `t`) will be 0.0 at the `minimumY` of\n   * the given `rectangle` and 1.0 at the `maximumY`.\n   *\n   * Coordinate values for vertices in between these extremes are determined by\n   * projecting the vertex position with the `projection` and then computing the\n   * fractional distance of that projected position between the minimum and\n   * maximum.\n   *\n   * Projected positions that fall outside the `rectangle` will be clamped to\n   * the edges, so the coordinate values will never be less then 0.0 or greater\n   * than 1.0.\n   *\n   * These texture coordinates are stored in the provided glTF, and a new\n   * primitive attribute named `_CESIUMOVERLAY_n`, where `n` is the\n   * `textureCoordinateID` passed to this function, is added to each primitive.\n   *\n   * @param gltf The glTF model.\n   * @param transform The transformation of this glTF to ECEF coordinates.\n   * @param textureCoordinateID The texture coordinate ID.\n   * @param projection The projection. There is a linear relationship between\n   * the coordinates of this projection and the generated texture coordinates.\n   * @param rectangle The rectangle that all projected vertex positions are\n   * expected to lie within.\n   * @return The bounding region.\n   */\n  static CesiumGeospatial::BoundingRegion createRasterOverlayTextureCoordinates(\n      CesiumGltf::Model& gltf,\n      const glm::dmat4& transform,\n      int32_t textureCoordinateID,\n      const CesiumGeospatial::Projection& projection,\n      const CesiumGeometry::Rectangle& rectangle);\n\nprivate:\n  static CesiumGltf::GltfReader _gltfReader;\n};\n\n} // namespace Cesium3DTilesSelection\n", "meta": {"hexsha": "74724e19dbc6c5167c721558d23ab2f7db64dead", "size": 3299, "ext": "h", "lang": "C", "max_stars_repo_path": "Cesium3DTilesSelection/include/Cesium3DTilesSelection/GltfContent.h", "max_stars_repo_name": "JiangMuWen/cesium-native", "max_stars_repo_head_hexsha": "1d9912307336c833b74b7e9b7bc715d0a4e6c7ec", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-10-02T17:45:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-02T17:45:15.000Z", "max_issues_repo_path": "Cesium3DTilesSelection/include/Cesium3DTilesSelection/GltfContent.h", "max_issues_repo_name": "JiangMuWen/cesium-native", "max_issues_repo_head_hexsha": "1d9912307336c833b74b7e9b7bc715d0a4e6c7ec", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cesium3DTilesSelection/include/Cesium3DTilesSelection/GltfContent.h", "max_forks_repo_name": "JiangMuWen/cesium-native", "max_forks_repo_head_hexsha": "1d9912307336c833b74b7e9b7bc715d0a4e6c7ec", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7263157895, "max_line_length": 80, "alphanum_fraction": 0.7229463474, "num_tokens": 841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29421497216298875, "lm_q2_score": 0.028007523242750902, "lm_q1q2_score": 0.008240232671220217}}
{"text": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n#pragma once\n#include \"Data\\Intrinsics.h\"\n#include \"Data\\Pose.h\"\n#include \"Device/CameraCalibration.h\"\n#include \"MageSettings.h\"\n#include \"Device\\IMUCharacterization.h\"\n\n#include \"Map\\Map.h\"\n#include \"Map\\ThreadSafeMap.h\"\n#include \"Bow\\BaseBow.h\"\n\n#include \"Image\\AnalyzedImage.h\"\n\n#include \"Proxies\\MapPointProxy.h\"\n\n#include <opencv2\\core\\core.hpp>\n#include <opencv2\\features2d\\features2d.hpp>\n#include <memory>\n#include <gsl\\gsl>\n\nnamespace UnitTests\n{\n    class MapInitializationUnitTest;\n}\n\nnamespace mage\n{\n    class KeyframeBuilder;\n\n    class MapInitialization\n    {\n    public:\n\n        enum InitializationAttemptState\n        {\n            NoPose,\n            ResetInit,\n            FinishInit,\n            Skipped\n        };\n\n        MapInitialization(const MonoMapInitializationSettings& settings, const PerCameraSettings& cameraSettings, const device::IMUCharacterization& imuCharacterization, mira::determinator& determinator);\n\n        InitializationAttemptState TryInitializeMap(const std::shared_ptr<const AnalyzedImage>& frame,\n            thread_memory memory,\n            InitializationData& initializationData,\n            BaseBow& bagOfWords);\n\n        bool InitializeWithFrames(gsl::span<const cv::DMatch> matches,\n            const std::shared_ptr<const AnalyzedImage>& frame0,\n            const std::shared_ptr<const AnalyzedImage>& frame1,\n            InitializationData& initializationData,\n            thread_memory memory);\n\n        struct BundlerSettings\n        {\n            float HuberWidth;\n            float MaxOutlierError;\n            float MaxOutlierErrorScaleFactor;\n            float MinMeanSquareError;\n            bool FixMapPoints;\n            uint32_t NumStepsPerRun;\n            uint32_t NumSteps;\n            uint32_t MinSteps;\n        };\n        \n        static void BundleAdjustInitializationData(InitializationData& initializationData, mira::determinator& determinator, bool cullOutliers, const BundlerSettings& bundlerSettings, thread_memory memory);\n        static bool ValidateInitializationData(const InitializationData& initializationData, float maxZContribution, float amountBACanChangePose, size_t minFeatureCount);\n\n        // Frame1Points and Frame2Points are indexed to match each other\n        static void CollectMatchPoints(const std::shared_ptr<const AnalyzedImage>& referenceFrame,\n                const std::shared_ptr<const AnalyzedImage>& currentFrame,\n                gsl::span<const cv::DMatch> matches,\n                std::vector<cv::Point2f>& frame1Points,\n                std::vector<cv::Point2f>& frame2Points);\n\n        static void TriangulatePoints(const std::shared_ptr<const AnalyzedImage>& referenceFrame, const std::shared_ptr<const AnalyzedImage>& currentFrame,\n            const Pose & referencePose, const Pose & currentPose,\n            gsl::span<const cv::DMatch> matches,\n            gsl::span<const cv::Point2f> frame1_points, gsl::span<const cv::Point2f> frame2_points,\n            float pixelMaxEpipolarDistance, float minAcceptanceDistanceRatio,\n            std::vector<std::pair<cv::DMatch, cv::Point3f>>& initial3DPoints);\n\n    private:\n\n        struct MatchedImage\n        {\n            std::shared_ptr<const AnalyzedImage>    Image;\n            std::vector<cv::DMatch>                 Matches;\n\n            MatchedImage(std::shared_ptr<const AnalyzedImage> image, std::vector<cv::DMatch> matches)\n                : Image{ image },\n                Matches( std::move(matches) )\n            {};\n\n            MatchedImage(std::shared_ptr<const AnalyzedImage> image)\n                : Image{ image }\n            {};\n        };\n\n        struct PointAssociation\n        {\n            size_t      PointIndex2d;\n            size_t      PointIndex3d;\n\n            PointAssociation(size_t twoD, size_t threeD)\n                : PointIndex2d { twoD },\n                PointIndex3d { threeD }\n            {};\n        };\n\n        struct InitializationPose\n        {\n            std::shared_ptr<const AnalyzedImage>    Image;\n            mage::Pose                              Pose;\n            std::vector<PointAssociation>           Associations;\n\n            InitializationPose(std::shared_ptr<const AnalyzedImage> image, mage::Pose pose, std::vector<PointAssociation> associations)\n                : Image( image ),\n                Pose( pose ),\n                Associations(std::move(associations))\n            {};\n        };\n\n        void ResetMapInitialization();\n\n        bool TryIntializeMapWithProvidedFrames(\n            const MatchedImage& referenceFrame,\n            MatchedImage& currentFrame,\n            thread_memory memory,\n            InitializationData& initializationData,\n            BaseBow& bagOfWords);\n\n        std::vector<Pose> FindEssentialPotientialPoses(\n            const cv::Matx33f& essentialMat);\n        \n        //Frame1Points and Frame2Points are indexed to match each other\n        float ScoreFundamentalMatrix(gsl::span<const cv::Point2f> frame1Points,\n            gsl::span<const cv::Point2f> frame2Points,\n            const cv::Matx33f& fundamentalMat1To2,\n            const cv::Matx33f& fundamentalMat2To1);\n\n        //Frame1Points and Frame2Points are indexed to match each other\n        std::vector<Pose> FindPossiblePoses(gsl::span<const cv::Point2f> frame1Points,\n            gsl::span<const cv::Point2f> frame2Points,\n            const CameraCalibration& frame1Calibration,\n            const CameraCalibration& frame2Calibration);\n\n        //Frame1Points and Frame2Points are indexed to match each other\n        bool FindCorrectPose(gsl::span<const cv::Point2f> frame1Points,\n            gsl::span<const cv::Point2f> frame2Points,\n            gsl::span<const cv::DMatch> matches,\n            const CameraCalibration& frame1Calibration,\n            const CameraCalibration& frame2Calibration,\n            const Pose& referencePose,\n            const std::vector<Pose>& poses,\n            Pose& correctPose,\n            std::vector<std::pair<cv::DMatch, cv::Point3f>>& correct3DPoints);\n\n        const MonoMapInitializationSettings m_settings;\n        const PerCameraSettings m_cameraSettings;\n        const device::IMUCharacterization& m_imuCharacterization;\n        mira::determinator& m_determinator;\n\n        std::vector<MatchedImage> m_initializationFrames;\n        std::vector<uint8_t> m_initializationDescriptorsCounters;\n\n        //For Test\n        friend class ::UnitTests::MapInitializationUnitTest;\n     };\n}\n", "meta": {"hexsha": "90df93cd20b2367256fc21eb591f9d5c2fa9ace0", "size": 6521, "ext": "h", "lang": "C", "max_stars_repo_path": "Core/MAGESLAM/Source/Tracking/MapInitialization.h", "max_stars_repo_name": "syntheticmagus/mageslam", "max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z", "max_issues_repo_path": "Core/MAGESLAM/Source/Tracking/MapInitialization.h", "max_issues_repo_name": "syntheticmagus/mageslam", "max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z", "max_forks_repo_path": "Core/MAGESLAM/Source/Tracking/MapInitialization.h", "max_forks_repo_name": "syntheticmagus/mageslam", "max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z", "avg_line_length": 37.2628571429, "max_line_length": 206, "alphanum_fraction": 0.6440729949, "num_tokens": 1406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.021287353112879655, "lm_q1q2_score": 0.008193760737065245}}
{"text": "#if !defined(_MUSIC_GSL_)\n#define _MUSIC_GSL_\n\n#define WIN32\n\n#include <gsl/gsl_combination.h>\n#include <gsl/gsl_sf.h>\n\n#endif", "meta": {"hexsha": "4d9ed9b22b7aa354d5037add788b9446b0d4cf15", "size": 126, "ext": "h", "lang": "C", "max_stars_repo_path": "src/Extensions/Classifiers/Barbedo/gsl.h", "max_stars_repo_name": "berkus/music-cs", "max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Extensions/Classifiers/Barbedo/gsl.h", "max_issues_repo_name": "berkus/music-cs", "max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Extensions/Classifiers/Barbedo/gsl.h", "max_forks_repo_name": "berkus/music-cs", "max_forks_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.0, "max_line_length": 32, "alphanum_fraction": 0.7619047619, "num_tokens": 40, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3140505449918074, "lm_q2_score": 0.025957359552513166, "lm_q1q2_score": 0.008151922914015057}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef graph_46d3170b_a19a_4663_bbf9_c7372932671b_h\r\n#define graph_46d3170b_a19a_4663_bbf9_c7372932671b_h\r\n\r\n#include <assert.h>\r\n#include <gslib/std.h>\r\n\r\n__gslib_begin__\r\n\r\ntemplate<class _meta>\r\nstruct _mono_rel\r\n{\r\n    _meta*          _next;\r\n\r\n    _mono_rel() { _next = nullptr; }\r\n    _meta* next() const { return _next; }\r\n    void set_next(_meta* ptr) { _next = ptr; }\r\n    _meta* operator+(int d) const\r\n    {\r\n        assert(d >= 0);\r\n        _meta* p = static_cast<_meta*>(this);\r\n        for( ; d > 0; d --)\r\n            p = p->_next;\r\n        return p;\r\n    }\r\n    int operator-(const _meta& that) const\r\n    {\r\n        int c = 0;\r\n        _meta* p = static_cast<_meta*>(this);\r\n        for( ; p->_next; p = p->_next, c ++) {\r\n            if(p == &that)\r\n                return c;\r\n        }\r\n        assert(!\"unexpected.\");\r\n        return -1;\r\n    }\r\n    int count_to_tail() const\r\n    {\r\n        int c = 0;\r\n        for(_meta* p = static_cast<_meta*>(this); p->_next; p = p->_next, c ++);\r\n        return c;\r\n    }\r\n    static void shake(_meta* p1, _meta* p2) { p1->_next = p2; }\r\n};\r\n\r\ntemplate<class _meta>\r\nstruct _dual_rel\r\n{\r\n    _meta           *_prev, *_next;\r\n\r\n    _dual_rel() { _prev = _next = nullptr; }\r\n    _meta* prev() const { return _prev; }\r\n    _meta* next() const { return _next; }\r\n    void set_prev(_meta* ptr) { _prev = ptr; }\r\n    void set_next(_meta* ptr) { _next = ptr; }\r\n    _meta* operator+(int d) const\r\n    {\r\n        if(d < 0)\r\n            return operator-(-d);\r\n        _meta* p = static_cast<_meta*>(this);\r\n        for( ; d > 0; d --)\r\n            p = p->_next;\r\n        return p;\r\n    }\r\n    _meta* operator-(int d) const\r\n    {\r\n        if(d < 0)\r\n            return operator+(-d);\r\n        _meta* p = static_cast<_meta*>(this);\r\n        for( ; d > 0; d --)\r\n            p = p->_prev;\r\n        return p;\r\n    }\r\n    int operator-(const _meta& that) const\r\n    {\r\n        int c = 0;\r\n        _meta* p = static_cast<_meta*>(this);\r\n        for( ; p->_next; p = p->_next, c ++) {\r\n            if(p == &that)\r\n                return c;\r\n        }\r\n        assert(!\"unexpected.\");\r\n        return -1;\r\n    }\r\n    int count_to_head() const\r\n    {\r\n        int c = 0;\r\n        for(_meta* p = static_cast<_meta*>(this); p->_next; p = p->_prev, c ++);\r\n        return c;\r\n    }\r\n    int count_to_tail() const\r\n    {\r\n        int c = 0;\r\n        for(_meta* p = static_cast<_meta*>(this); p->_next; p = p->_next, c ++);\r\n        return c;\r\n    }\r\n    static void shake(_meta* p1, _meta* p2) { p1->_next = p2, p2->_prev = p1; }\r\n};\r\n\r\ntemplate<class _meta>\r\nstruct _pack_rel\r\n{\r\n    _meta       *_from, *_to;\r\n    int         _size;\r\n\r\n    _pack_rel() { _from = _to = nullptr, _size = 0; }\r\n    _pack_rel(_meta* from, _meta* to) { _from = from, _to = to, _size = 0; }\r\n    _meta* from() const { return _from; }\r\n    _meta* to() const { return _to; }\r\n    bool empty() const { return !_from; }\r\n    int size() const { return _size; }\r\n    void set_from(_meta* ptr) { _from = ptr; }\r\n    void set_to(_meta* ptr) { _to = ptr; }\r\n    void increase_size() { _size ++; }\r\n    void decrease_size() { _size --; }\r\n    void set_size(int s) { _size = s; }\r\n    bool check_mono() const\r\n    {\r\n        if(!_from)\r\n            return false;\r\n        _meta* p = static_cast<_meta*>(_from);\r\n        for( ; p->_next; p = p->_next);\r\n        return p == _to;\r\n    }\r\n    bool check_dual() const\r\n    {\r\n        if(!_from || _from->_prev)\r\n            return false;\r\n        _meta* p = static_cast<_meta*>(_from);\r\n        for( ; p->_next; p = p->_next) {\r\n            if(p->_prev && p != p->_prev->_next)\r\n                return false;\r\n        }\r\n        return p == _to;\r\n    }\r\n    bool is_belong_to(const _meta* ptr) const\r\n    {\r\n        _meta* p = static_cast<_meta*>(_from);\r\n        for( ; p; p = p->_next) {\r\n            if(ptr == p)\r\n                return true;\r\n        }\r\n        return false;\r\n    }\r\n};\r\n\r\nclass _graph_ortho_rel:\r\n    public _dual_rel<_graph_ortho_rel>\r\n{\r\npublic:\r\n    typedef _pack_rel<_graph_ortho_rel> hierarchic_rel;\r\n    typedef _dual_rel<_graph_ortho_rel> peer_rel;\r\n    typedef hierarchic_rel upper_rel;\r\n    typedef hierarchic_rel lower_rel;\r\n\r\nprotected:\r\n    hierarchic_rel  _parents, _children;\r\n\r\npublic:\r\n    hierarchic_rel& parents() { return _parents; }\r\n    hierarchic_rel& children() { return _children; }\r\n    peer_rel& siblings() { return static_cast<peer_rel&>(*this); }\r\n    const hierarchic_rel& const_parents() const { return _parents; }\r\n    const hierarchic_rel& const_children() const { return _children; }\r\n    const peer_rel& const_siblings() const { return static_cast<const peer_rel&>(*this); }\r\n    int parents_count() const { return _parents.size(); }\r\n    int children_count() const { return _children.size(); }\r\n};\r\n\r\nstruct _graph_trait_copy {};\r\nstruct _graph_trait_detach {};\r\n\r\ntemplate<class _ty, \r\n    class _rel = _graph_ortho_rel\r\n    >\r\nstruct _graph_ortho_cpy_wrapper:\r\n    public _ty,\r\n    public _rel\r\n{\r\n    typedef _ty value;\r\n    typedef _rel relation;\r\n    typedef _graph_ortho_cpy_wrapper<_ty, _rel> wrapper;\r\n    typedef _graph_trait_copy tsf_behavior;\r\n    \r\n    value* get_ptr() { return static_cast<value*>(this); }\r\n    const value* const_ptr() const { return static_cast<const value*>(this); }\r\n    value& get_ref() { return static_cast<value&>(*this); }\r\n    const value& const_ref() const { return static_cast<const value&>(*this); }\r\n    template<class _cst>\r\n    void born() {}  /* maybe a problem. */\r\n    void born() {}\r\n    void kill() {}\r\n    void copy(const wrapper* a) { assign<value>(a); }\r\n    void attach(wrapper* a) { !!error!! }\r\n    int get_parents_count() const { return parents_count(); }\r\n    int get_children_count() const { return children_count(); }\r\n    template<class c>\r\n    void assign(const wrapper* a) { static_cast<c&>(*this) = static_cast<c&>(*a); }\r\n};\r\n\r\ntemplate<class _ty, \r\n    class _rel = _graph_ortho_rel\r\n    >\r\nstruct _graph_ortho_wrapper:\r\n    public _rel\r\n{\r\n    typedef _ty value;\r\n    typedef _rel relation;\r\n    typedef _graph_ortho_wrapper<_ty, _rel> wrapper;\r\n    typedef _graph_trait_detach tsf_behavior;\r\n\r\n    value*          _value;\r\n\r\n    wrapper() { _value = nullptr; }\r\n    value* get_ptr() { return _value; }\r\n    const value* const_ptr() const { return _value; }\r\n    value& get_ref() { return *_value; }\r\n    const value& const_ref() const { return *_value; }\r\n    relation& get_relation() { return static_cast<relation&>(*this); }\r\n    const relation& const_relation() const { return static_cast<const relation&>(*this); }\r\n    template<class _cst>\r\n    void born() { _value = new _cst; }\r\n    void born() { _value = new value; }\r\n    void kill() { delete _value; }\r\n    void copy(const wrapper* a) { assert(!\"prevent.\"); }\r\n    void attach(wrapper* a)\r\n    {\r\n        assert(a && a->_value);\r\n        kill();\r\n        _value = a->_value;\r\n        a->_value = nullptr;\r\n    }\r\n    int get_parents_count() const { return parents_count(); }\r\n    int get_children_count() const { return children_count(); }\r\n};\r\n\r\ntemplate<class _wrapper>\r\nstruct _graph_allocator\r\n{\r\n    typedef _wrapper wrapper;\r\n    static wrapper* born() { return new wrapper; }\r\n    static void kill(wrapper* w) { delete w; }\r\n};\r\n\r\ntemplate<class _val>\r\nstruct _graph_ortho_val\r\n{\r\n    typedef _val value;\r\n    typedef const _val const_value;\r\n    union\r\n    {\r\n        value*          _vptr;\r\n        const_value*    _cvptr;\r\n    };\r\n    value* get_wrapper() const { return _vptr; }\r\n    value* trace_front(int d) const { return _vptr->siblings() + d; }\r\n    value* trace_back(int d) const { return _vptr->siblings() - d; }\r\n    value* trace_up(int d) const\r\n    {\r\n        if(d < 0)\r\n            return trace_down(-d);\r\n        value* p = _vptr;\r\n        for( ; d > 0; d --) {\r\n            assert(!p->parents().empty());\r\n            p = p->parents().from();\r\n        }\r\n        return p;\r\n    }\r\n    value* trace_down(int d) const\r\n    {\r\n        if(d < 0)\r\n            return trace_up(-d);\r\n        value* p = _vptr;\r\n        for( ; d > 0; d --) {\r\n            assert(!p->children().empty());\r\n            p = p->children().from();\r\n        }\r\n        return p;\r\n    }\r\n    value* trace_front() const\r\n    {\r\n        assert(_vptr);\r\n        return _vptr->next();\r\n    }\r\n    value* trace_back() const\r\n    {\r\n        assert(_vptr);\r\n        return _vptr->prev();\r\n    }\r\n};\r\n\r\ntemplate<class _ty,\r\n    class _wrapper = _graph_ortho_cpy_wrapper<_ty>\r\n    >\r\nclass _graph_ortho_const_iterator:\r\n    public _graph_ortho_val<_wrapper>\r\n{\r\npublic:\r\n    typedef _ty value;\r\n    typedef _wrapper wrapper;\r\n    typedef _graph_ortho_const_iterator<_ty, _wrapper> iterator;\r\n\r\npublic:\r\n    iterator(const wrapper* w = nullptr) { _cvptr = w; }\r\n    bool is_valid() const { return _cvptr != nullptr; }\r\n    const value* get_ptr() const { return _cvptr->const_ptr(); }\r\n    const value* operator->() const { return _cvptr->const_ptr(); }\r\n    const value& operator*() const { return _cvptr->const_ref(); }\r\n    iterator operator+(int d) const { return iterator(trace_front(d)); }\r\n    iterator operator-(int d) const { return iterator(trace_back(d)); }\r\n    iterator operator<<(int d) const { return iterator(trace_up(d)); }\r\n    iterator operator>>(int d) const { return iterator(trace_down(d)); }\r\n    int operator-(iterator i) const { return _cvptr->peer_rel::operator-(*(i._cvptr)); }\r\n};\r\n\r\ntemplate<class _ty,\r\n    class _wrapper = _graph_ortho_cpy_wrapper<_ty>\r\n    >\r\nclass _graph_ortho_iterator:\r\n    public _graph_ortho_const_iterator<_ty, _wrapper>\r\n{\r\npublic:\r\n    typedef _ty value;\r\n    typedef _wrapper wrapper;\r\n    typedef _graph_ortho_const_iterator<_ty, _wrapper> superref;\r\n    typedef _graph_ortho_const_iterator<_ty, _wrapper> const_iterator;\r\n    typedef _graph_ortho_iterator<_ty, _wrapper> iterator;\r\n\r\npublic:\r\n    iterator(wrapper* w = nullptr) { _vptr = w; }\r\n    value* get_ptr() const { return _vptr->get_ptr(); }\r\n    value* operator->() const { return _vptr->get_ptr(); }\r\n    value& operator*() const { return _vptr->get_ref(); }\r\n    bool operator==(const iterator& that) const { return _vptr == that._vptr; }\r\n    bool operator!=(const iterator& that) const { return _vptr != that._vptr; }\r\n    bool operator==(const const_iterator& that) const { return _vptr == that._vptr; }\r\n    bool operator!=(const const_iterator& that) const { return _vptr != that._vptr; }\r\n    void operator++() { _vptr = trace_front(); }\r\n    void operator--() { _vptr = trace_back(); }\r\n    void operator+=(int d) { _vptr = trace_front(d); }\r\n    void operator-=(int d) { _vptr = trace_back(d); }\r\n    void operator<<=(int d) { _vptr = trace_up(d); }\r\n    void operator>>=(int d) { _vptr = trace_down(d); }\r\n    operator const_iterator() { return const_iterator(_cvptr); }\r\n};\r\n\r\ntemplate<class _ty,\r\n    class _wrapper = _graph_ortho_wrapper<_ty>,\r\n    class _alloc = _graph_allocator<_wrapper>\r\n    >\r\nclass ortho_graph:\r\n    public _graph_ortho_val<_wrapper>\r\n{\r\npublic:\r\n    typedef _ty value;\r\n    typedef _wrapper wrapper;\r\n    typedef _alloc alloc;\r\n    typedef ortho_graph<_ty, _wrapper, _alloc> myref;\r\n    typedef _graph_ortho_const_iterator const_iterator;\r\n    typedef _graph_ortho_iterator iterator;\r\n\r\npublic:\r\n    ortho_graph() { _vptr = nullptr; }\r\n    ~ortho_graph() { destroy(); }\r\n    void destroy()\r\n    {\r\n        for(wrapper* i = _vptr; i; ) {\r\n            wrapper* n = i->next();\r\n            _erase(i);\r\n            i = n;\r\n        }\r\n    }\r\n    void clear() { destroy(); }\r\n    iterator get_root() { return iterator(_vptr); }\r\n    const_iterator const_root() const { return const_iterator(_cvptr); }\r\n    bool is_valid() const { return !_cvptr; }\r\n    iterator insert_before(iterator i) { return insert_before<value>(i); }\r\n    iterator insert_after(iterator i) { return insert_after<value>(i); }\r\n    iterator create_child(iterator from, iterator to = from) { return create_child<value>(from, to); }\r\n    iterator erase(iterator i)\r\n    {\r\n        iterator r(i->next());\r\n        _erase(i.get_wrapper());\r\n        return r;\r\n    }\r\n    \r\npublic:\r\n    template<class _cst>\r\n    iterator insert_before(iterator i)\r\n    {\r\n        if(!i.is_valid())\r\n            return _cvptr ? get_root() : _init<_cst>();\r\n        wrapper* n = alloc::born();\r\n        n->born<_cst>();\r\n        _fix_peer_rel(i->prev(), n, *i);\r\n        _fix_upper_rel(n, *i);\r\n        _fix_lower_rel(n, *i);\r\n        /* fix root, keep the root always be the top left corner. */\r\n        if(i.get_wrapper() == _vptr)\r\n            _vptr = n;\r\n        return iterator(n);\r\n    }\r\n    template<class _cst>\r\n    iterator insert_after(iterator i)\r\n    {\r\n        if(!i.is_valid())\r\n            return _cvptr ? get_root() : _init<_cst>();\r\n        wrapper* n = alloc::born();\r\n        n->born<_cst>();\r\n        _fix_peer_rel(*i, n, i->next());\r\n        _fix_upper_rel(n, *i);\r\n        _fix_lower_rel(n, *i);\r\n        return iterator(n);\r\n    }\r\n    template<class _cst>\r\n    iterator create_child(iterator from, iterator to = from)\r\n    {\r\n        assert(from.is_valid() && from->children().empty());\r\n        wrapper* n = alloc::born();\r\n        n->born<_cst>();\r\n        _fix_upper_rel(n, *from, *to);\r\n        return iterator(n);\r\n    }\r\n    template<class _lambda>\r\n    void _for_range(iterator from, iterator to, _lambda lam)\r\n    {\r\n        for(iterator i = from; ; i ++) {\r\n            lam(i->get_wrapper());\r\n            if(i == to)\r\n                break;\r\n        }\r\n    }\r\n    template<class _lambda>\r\n    void for_range(iterator from, iterator to, _lambda lam)\r\n    {\r\n        for(iterator i = from; ; i ++) {\r\n            lam(*i);\r\n            if(i == to)\r\n                break;\r\n        }\r\n    }\r\n\r\nprotected:\r\n    template<class _cst>\r\n    iterator _init()\r\n    {\r\n        _vptr = alloc::born();\r\n        _vptr->born<_cst>();\r\n        return iterator(_vptr);\r\n    }\r\n    void _erase(wrapper* w)\r\n    {\r\n        assert(w);\r\n        _fix_upper_rel(w);\r\n        _fix_lower_rel(w);\r\n        peer_rel::shake(w->prev(), w->next());\r\n        lower_rel& rel = w->children();\r\n        if(!rel.empty())\r\n            _for_range(rel.from(), rel.to(), [](wrapper* w) { _erase(w); });\r\n        if(w == _vptr)\r\n            _vptr = w->next();\r\n        w->kill();\r\n        alloc::kill(w);\r\n    }\r\n    void _set_range_upper(wrapper* from, wrapper* to, wrapper* r1, wrapper* r2, int size)\r\n    {\r\n        _for_range(iterator(from), iterator(to), [&r1, &r2, &size](wrapper* w) {\r\n            upper_rel& rel = w->parents();\r\n            rel.set_from(r1);\r\n            rel.set_to(r2);\r\n            rel.set_size(size);\r\n        });\r\n    }\r\n    void _set_range_lower(wrapper* from, wrapper* to, wrapper* r1, wrapper* r2, int size)\r\n    {\r\n        _for_range(iterator(from), iterator(to), [&r1, &r2, &size](wrapper* w) {\r\n            lower_rel& rel = w->children();\r\n            rel.set_from(r1);\r\n            rel.set_to(r2);\r\n            rel.set_size(size);\r\n        });\r\n    }\r\n    void _fix_peer_rel(wrapper* w1, wrapper* w2, wrapper* w3)\r\n    {\r\n        assert(w2 && (w1 || w3));\r\n        if(w1 != nullptr)\r\n            peer_rel::shake(w1, w2);\r\n        if(w3 != nullptr)\r\n            peer_rel::shake(w2, w3);\r\n    }\r\n    void _fix_upper_rel(wrapper* n, wrapper* w)\r\n    {\r\n        assert(n && w);\r\n        upper_rel& urel = w->parents();\r\n        wrapper* u1 = urel.from();\r\n        if(u1 == nullptr)\r\n            return;\r\n        wrapper* u2 = urel.to();\r\n        lower_rel& lrel = u1->children();\r\n        wrapper* l1 = lrel.from();\r\n        wrapper* l2 = lrel.to();\r\n        assert(l1 && l2);\r\n        wrapper *from = l1, *to = l2;\r\n        if(l1 == w && n == w->prev())\r\n            from = n;\r\n        else if(l2 == w && n == w->next())\r\n            to = n;\r\n        _set_range_lower(u1, u2, from, to, lrel.size() + 1);\r\n        upper_rel& u = n->parents();\r\n        u.set_from(u1);\r\n        u.set_to(u2);\r\n    }\r\n    void _fix_lower_rel(wrapper* n, wrapper* w)\r\n    {\r\n        assert(n && w);\r\n        lower_rel& lrel = w->children();\r\n        wrapper* l1 = lrel.from();\r\n        if(l1 == nullptr)\r\n            return;\r\n        wrapper* l2 = lrel.to();\r\n        upper_rel& urel = l1->parents();\r\n        wrapper* u1 = urel.from();\r\n        wrapper* u2 = urel.to();\r\n        assert(u1 && u2);\r\n        wrapper *from = u1, *to = u2;\r\n        if(u1 == w && n == w->prev())\r\n            from = n;\r\n        else if(u2 == w && n == w->next())\r\n            to = n;\r\n        _set_range_upper(l1, l2, from, to, urel.size() + 1);\r\n        lower_rel& l = n->children();\r\n        l.set_from(l1);\r\n        l.set_to(l2);\r\n    }\r\n    void _fix_upper_rel(wrapper* w)\r\n    {\r\n        assert(w);\r\n        upper_rel& urel = w->parents();\r\n        wrapper* u1 = urel.from();\r\n        if(u1 == nullptr)\r\n            return;\r\n        wrapper* u2 = urel.to();\r\n        assert(u2);\r\n        lower_rel& lrel = u1->children();\r\n        wrapper* l1 = lrel.from();\r\n        wrapper* l2 = lrel.to();\r\n        assert(l1 && l2);\r\n        wrapper *from = l1, *to = l2;\r\n        if(l1 == w && l2 == w)\r\n            from = to = nullptr;\r\n        else if(l1 == w)\r\n            from = w->next();\r\n        else if(l2 == w)\r\n            to = w->prev();\r\n        _set_range_lower(u1, u2, from, to, lrel.size() - 1);\r\n        urel.set_from(nullptr);\r\n        urel.set_to(nullptr);\r\n        urel.set_size(0);\r\n    }\r\n    void _fix_lower_rel(wrapper* w)\r\n    {\r\n        assert(w);\r\n        lower_rel& lrel = w->children();\r\n        wrapper* l1 = lrel.from();\r\n        if(l1 == nullptr)\r\n            return;\r\n        wrapper* l2 = lrel.to();\r\n        assert(l2);\r\n        upper_rel& urel = l1->parents();\r\n        wrapper* u1 = urel.from();\r\n        wrapper* u2 = urel.to();\r\n        assert(u1 && u2);\r\n        wrapper *from = u1, *to = u2;\r\n        if(u1 == w && u2 == w);\r\n        else if(u1 == w || u2 == w) {\r\n            u1 == w ? from = w->next() : to = w->prev();\r\n            lrel.set_from(nullptr);\r\n            lrel.set_to(nullptr);\r\n            lrel.set_size(0);\r\n        }\r\n        _set_range_upper(l1, l2, from, to, urel.size() - 1);\r\n    }\r\n    void _fix_upper_rel(wrapper* w, wrapper* u1, wrapper* u2)\r\n    {\r\n        assert(w && u1 && u2);\r\n        upper_rel& urel = w->parents();\r\n        urel.set_from(u1);\r\n        urel.set_to(u2);\r\n        urel.set_size(u1->count_to_tail(u2) + 1);\r\n        _set_range_lower(u1, u2, w, w, 1);\r\n    }\r\n};\r\n\r\n__gslib_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "99ec552b92ac06d24669695938f13031ddcda79c", "size": 19737, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gslib/graph.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/gslib/graph.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gslib/graph.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 31.6805778491, "max_line_length": 103, "alphanum_fraction": 0.550995592, "num_tokens": 5263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1993080074160125, "lm_q2_score": 0.040845712407222005, "lm_q1q2_score": 0.008140877551370917}}
{"text": "/*\n * Copyright (c) 2011-2013  University of Texas at Austin. All rights reserved.\n *\n * $COPYRIGHT$\n *\n * Additional copyrights may follow\n *\n * This file is part of PerfExpert.\n *\n * PerfExpert is free software: you can redistribute it and/or modify it under\n * the terms of the The University of Texas at Austin Research License\n * \n * PerfExpert is distributed in the hope that it will be useful, but WITHOUT ANY\n * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR\n * A PARTICULAR PURPOSE.\n * \n * Authors: Leonardo Fialho and Ashay Rane\n *\n * $HEADER$\n */\n\n#ifndef ANALYSIS_DEFS_H_\n#define ANALYSIS_DEFS_H_\n\n#include <vector>\n#include <gsl/gsl_histogram.h>\n\n#include \"tools/macpo/common/avl_tree.h\"\n#include \"tools/macpo/common/generic_defs.h\"\n#include \"tools/macpo/common/macpo_record.h\"\n#include \"tools/macpo/common/macpo_record_cxx.h\"\n\ntypedef gsl_histogram histogram_t;\n\ntypedef std::vector<mem_info_list_t> mem_info_bucket_t;\ntypedef std::vector<trace_info_list_t> trace_info_bucket_t;\ntypedef std::vector<vector_stride_info_list_t> vector_stride_info_bucket_t;\n\ntypedef std::vector<histogram_t*> histogram_list_t;\ntypedef std::vector<histogram_list_t> histogram_matrix_t;\n\ntypedef std::vector<avl_tree*> avl_tree_list_t;\n\ntypedef std::pair<size_t, size_t> pair_t;\ntypedef std::vector<pair_t> pair_list_t;\n\ntypedef std::vector<double> double_list_t;\ntypedef std::vector<int> int_list_t;\n\ntypedef struct {\n    size_t size, line_size, associativity, count;\n} cache_data_t;\n\ntypedef struct {\n    cache_data_t l1_data, l2_data, l3_data;\n    name_list_t stream_list;\n    mem_info_bucket_t mem_info_bucket;\n    trace_info_bucket_t trace_info_bucket;\n    vector_stride_info_bucket_t vector_stride_info_bucket;\n} global_data_t;\n\ntypedef struct {\n    size_t count, l1_conflicts, l2_conflicts;\n} stream_list_t;\n\n/* Different kinds of analyses options. */\n#define ANALYSIS_REUSE_DISTANCE     (1 << 0)\n#define ANALYSIS_CACHE_CONFLICTS    (1 << 1)\n#define ANALYSIS_PREFETCH_STREAMS   (1 << 2)\n#define ANALYSIS_STRIDES            (1 << 3)\n#define ANALYSIS_VECTOR_STRIDES     (1 << 4)\n\n#define ANALYSIS_ALL                (~0)\n\n/* Number of reuse distance entries to display for each stream. */\n#define REUSE_DISTANCE_COUNT        3\n\n#define ADDR_TO_CACHE_LINE(x)   (x >> 6)\n\n#endif /* ANALYSIS_DEFS_H_ */\n", "meta": {"hexsha": "989ba4a7447da620313ecb753ca3f01e474bc8d8", "size": 2329, "ext": "h", "lang": "C", "max_stars_repo_path": "tools/macpo/analyze/include/analysis_defs.h", "max_stars_repo_name": "roystgnr/perfexpert", "max_stars_repo_head_hexsha": "a03b13db9ac83e992e1c5cc3b6e45e52c266fe30", "max_stars_repo_licenses": ["BSD-4-Clause-UC"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2015-05-05T15:54:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-27T16:23:36.000Z", "max_issues_repo_path": "tools/macpo/analyze/include/analysis_defs.h", "max_issues_repo_name": "roystgnr/perfexpert", "max_issues_repo_head_hexsha": "a03b13db9ac83e992e1c5cc3b6e45e52c266fe30", "max_issues_repo_licenses": ["BSD-4-Clause-UC"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2015-10-07T20:52:05.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-18T16:08:41.000Z", "max_forks_repo_path": "tools/macpo/analyze/include/analysis_defs.h", "max_forks_repo_name": "roystgnr/perfexpert", "max_forks_repo_head_hexsha": "a03b13db9ac83e992e1c5cc3b6e45e52c266fe30", "max_forks_repo_licenses": ["BSD-4-Clause-UC"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2015-01-23T15:41:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-18T03:53:19.000Z", "avg_line_length": 28.7530864198, "max_line_length": 80, "alphanum_fraction": 0.7569772435, "num_tokens": 576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30404167496654744, "lm_q2_score": 0.026759284931777455, "lm_q1q2_score": 0.008135937811564712}}
{"text": "#include \"als.h\"\n#include \"mpi.h\"\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_matrix.h>\n\n#define MAX_NAME_LEN 10\n\n/* Define global variables */\nglobal_info info;\n\nfeature_t *movieMatrix; // feature matrix of movies\nfeature_t *userMatrix;  // feature matrix of users \n\n// store rating matrix in a compressed way\nint userNum;\nint movieNum;\nint ratingNum;\n\nint* userStartIdx;\nint* movieId;\ndouble* movieRating;\n\nint* movieStartIdx;\nint* userId; \ndouble* userRating;\n\nstruct movie* movie_hashtable; // to record the number of rating for each movie \nstruct user* user_hashtable;   // to record the number of rating for each user\n\nvoid computePredictionRMSE(gsl_matrix * M, gsl_matrix * U, gsl_matrix * R);\n\n//---------------------------------------------\n//------- helper function for hashtable--------\n//--------------------------------------------- \nvoid add_movie(int id, double rating) {\n    struct movie* res;\n    HASH_FIND_INT(movie_hashtable, &id, res);\n    if (res == NULL) {\n        struct movie* new_movie = (struct movie*)malloc(sizeof(struct movie));\n        new_movie -> id = id;\n        new_movie -> rating_num = 1;\n        new_movie -> num = 1;\n        new_movie -> total_rating = rating;\n        HASH_ADD_INT(movie_hashtable, id, new_movie);\n    } else {\n        res -> rating_num ++;\n        res -> num ++;\n        res -> total_rating += rating;\n    }\n}\n\nvoid delete_movie(int id) {\n    struct movie* res;\n    HASH_FIND_INT(movie_hashtable, &id, res);\n    res -> rating_num --;\n}\n\nint find_movie(int id) {\n    struct movie *result;\n    HASH_FIND_INT(movie_hashtable, &id, result);\n    if (result == NULL) {\n        return 0;\n    } else {\n        return result -> rating_num;\n    }\n}\n\ndouble get_movie_average(int id) {\n    struct movie *result;\n    HASH_FIND_INT(movie_hashtable, &id, result);\n    if (result == NULL) {\n        return 0;\n    } else {\n        return result -> total_rating / ((double)result -> num);\n    }\n}\n\nvoid add_user(int id) {\n    struct user* res;\n    HASH_FIND_INT(user_hashtable, &id, res);\n    if (res == NULL) {\n        struct user* new_user = (struct user*)malloc(sizeof(struct user));\n        new_user -> id = id;\n        new_user -> rating_num = 1;\n        HASH_ADD_INT(user_hashtable, id, new_user);\n    } else {\n        res -> rating_num ++;\n    }\n}\n\nvoid delete_user(int id) {\n    struct user* res;\n    HASH_FIND_INT(user_hashtable, &id, res);\n    res -> rating_num --;\n}\n\nint find_user(int id) {\n    struct user *result;\n    HASH_FIND_INT(user_hashtable, &id, result);\n    if (result == NULL) {\n        return 0;\n    } else {\n        return result -> rating_num;\n    }\n}\n\n//------------------------------------------------\n//-----------process input data-------------------\n//------------------------------------------------\n\n/*\n * get the input relevant stat\n */\nvoid getInputStat(char* inputFilename) {\n    userNum = 0;\n    movieNum = 0;\n    ratingNum = 0;\n\n    FILE* fp = fopen(inputFilename, \"r\");\n    if (fp == NULL) {\n        fprintf(stderr, \"Failed to read input file %s\\n\", inputFilename);\n        exit(-1);\n    }\n\n    ssize_t read;\n    size_t len = 0;\n    char* line = NULL;\n    int uid = 0;\n    int mid = 0;\n    double rating = 0;\n    if ((read = getline(&line, &len, fp)) != -1) {\n        printf(\"Start reading file, get input stat\\n\");\n    }\n\n    while ((read = getline(&line, &len, fp)) != -1) {\n        ratingNum++;\n\n        // split the data line with comma\n        char* tmp = line;\n        char* last_pos = line;\n        int word_len = 0;\n        int comma_cnt = 0;\n\n        while (comma_cnt < 3) {\n            if (*tmp == ',') {\n                word_len = tmp - last_pos;\n                char tmpbuf[MAX_NAME_LEN] = \"\";\n                strncpy(tmpbuf, last_pos, word_len);\n                if (comma_cnt == 0) {\n                    uid = atoi(tmpbuf);\n                } else if (comma_cnt == 1) {\n                    mid = atoi(tmpbuf);\n                } else {\n                    rating = atof(tmpbuf);\n                }\n                comma_cnt++;\n                last_pos = tmp + 1;\n            }\n            tmp++;\n        }\n        add_movie(mid, rating);  // keep record of rating number for each movie\n        add_user(uid);           // keep record of rating number of each user\n        userNum = max(userNum, uid);\n        movieNum = max(movieNum, mid);\n    }\n    printf(\"There are %d ratings, %d users, %d movies\\n\", ratingNum, userNum, movieNum);\n}\n\nvoid initUserStartIndex() {\n    int i;\n    int sum = 0;\n    for (i = 1; i <= userNum; ++i) {\n        int user_rating = find_user(i);\n        userStartIdx[i - 1] = sum;\n        sum += user_rating;\n    }\n    userStartIdx[userNum] = ratingNum;\n}\n\nvoid initMovieStartIndex() {\n    int i;\n    int sum = 0;\n    for (i = 1; i <= movieNum; ++i) {\n        int movie_rating = find_movie(i);\n        movieStartIdx[i - 1] = sum;\n        sum += movie_rating;\n    }\n    movieStartIdx[movieNum] = ratingNum;\n}\n\nvoid initRatingMatrix(int uid, int mid, double rating) {\n    int movieIdx = movieStartIdx[mid] - find_movie(mid);\n    int userIdx = userStartIdx[uid] - find_user(uid);\n    userId[movieIdx] = uid;\n    userRating[movieIdx] = rating;\n    movieId[userIdx] = mid;\n    movieRating[userIdx] = rating;\n    delete_movie(mid);\n    delete_user(uid);\n}\n\nvoid initMatrix() {\n    printf(\"Init movie matrix\\n\");\n    int i, j;\n    for (i = 0; i < movieNum; ++i) {\n        int start_idx = i * info.numFeatures;\n        movieMatrix[start_idx] = get_movie_average(i + 1);\n        // initialize the random small value\n        for (j = 1; j < info.numFeatures; ++j) {\n            movieMatrix[start_idx + j] = (rand() % 1000) / 1000.0;\n        }\n    }\n}\n\n// read input file \n// initializa the rating matrix & movie matrix \nvoid readInput(char* inputFilename) {\n    FILE* fp = fopen(inputFilename, \"r\");\n    if (fp == NULL) {\n        fprintf(stderr, \"Failed to read input file %s\\n\", inputFilename);\n        exit(-1);\n    }\n\n    ssize_t read;\n    size_t len = 0;\n    char* line = NULL;\n    int uid = 0;\n    int mid = 0;\n    double rating = 0;\n    if ((read = getline(&line, &len, fp)) != -1) {\n        printf(\"Start reading file, get rating details\\n\");\n    }\n\n    while ((read = getline(&line, &len, fp)) != -1) {\n        // split the data line with comma\n        char* tmp = line;\n        char* last_pos = line;\n        int word_len = 0;\n        int comma_cnt = 0;\n        \n        while (comma_cnt < 3) {\n            if (*tmp == ',') {\n                word_len = tmp - last_pos;\n                char tmpbuf[MAX_NAME_LEN] = \"\";\n                strncpy(tmpbuf, last_pos, word_len);\n                if (comma_cnt == 0) {\n                    uid = atoi(tmpbuf);\n                } else if (comma_cnt == 1) {\n                    mid = atoi(tmpbuf);\n                } else {\n                    rating = atof(tmpbuf);\n                }\n                comma_cnt++;\n                last_pos = tmp + 1;\n            }\n            tmp++;\n        }\n        // initialize the rating matrix (use compression)\n        initRatingMatrix(uid, mid, rating);\n    }\n}\n\n// init basic arg\nvoid init(int numFeatures, int numIter, double lambda) {\n    info.numIter = numIter;\n    info.numFeatures = numFeatures;\n    info.lambda = lambda;\n}\n\n/*\n * allocate data structure memory \n */\nvoid init_data(int userNum, int movieNum, int ratingNum, int nproc) {\n    printf(\"allocating data memory\\n\");\n\n    int movieSpan = (movieNum + nproc - 1) / nproc;\n    int userSpan = (userNum + nproc - 1) / nproc;\n\n    userStartIdx = (int*)calloc(userNum + 1, sizeof(int));\n    movieId =      (int*)calloc(ratingNum + 1, sizeof(int));\n    movieRating =  (double*)calloc(ratingNum + 1, sizeof(double));\n\n    movieStartIdx = (int*)calloc(movieNum + 1, sizeof(int));\n    userId =        (int*)calloc(ratingNum + 1, sizeof(int));\n    userRating =    (double*)calloc(ratingNum + 1, sizeof(double));\n\n    movieMatrix = (feature_t *)calloc(info.numFeatures * movieSpan * nproc, sizeof(feature_t));\n    userMatrix =  (feature_t *)calloc(info.numFeatures * userSpan * nproc, sizeof(feature_t));\n}\n\n//-----------------------------------------------------------------\n//---------------------real computation----------------------------\n//-----------------------------------------------------------------\nvoid compute(int procID, int nproc, char* inputFilename, \n             int numFeatures, int numIterations, double lambda) \n{\n    const int root = 0; // set the rank 0 processor as the root \n    int span;\n\n    // initialize\n    init(numFeatures, numIterations, lambda);\n\n    /* Read the input file and initialization */\n    if (procID == root) {\n        getInputStat(inputFilename);\n    }\n\n    /* broadcast the information of basic stat*/\n    MPI_Bcast(&userNum, 1, MPI_INT, root, MPI_COMM_WORLD);\n    MPI_Bcast(&movieNum, 1, MPI_INT, root, MPI_COMM_WORLD);\n    MPI_Bcast(&ratingNum, 1, MPI_INT, root, MPI_COMM_WORLD);\n\n    // initialize the data structure\n    init_data(userNum, movieNum, ratingNum, nproc);\n    \n    if (procID == root) {\n        initUserStartIndex();\n        initMovieStartIndex();\n    }\n    \n    /* broadcast the information about start index */\n    MPI_Bcast(userStartIdx, userNum + 1, MPI_INT, root, MPI_COMM_WORLD);\n    MPI_Bcast(movieStartIdx, movieNum + 1, MPI_INT, root, MPI_COMM_WORLD);\n   \n    /* Read the input file and get detailed rating */\n    if (procID == root) {\n        readInput(inputFilename);\n    }\n\n    MPI_Bcast(movieId, ratingNum + 1, MPI_INT, root, MPI_COMM_WORLD);\n    MPI_Bcast(movieRating, ratingNum + 1, MPI_DOUBLE, root, MPI_COMM_WORLD);\n    MPI_Bcast(userId, ratingNum + 1, MPI_INT, root, MPI_COMM_WORLD);\n    MPI_Bcast(userRating, ratingNum + 1, MPI_DOUBLE, root, MPI_COMM_WORLD);\n\n    // initialize movie/ user matrix\n    if (procID == root) {\n        initMatrix();\n    }\n\n    MPI_Bcast(movieMatrix, numFeatures * movieNum, MPI_DOUBLE, root, MPI_COMM_WORLD);\n\n    // initialize n_user and n_movie\n    int* n_user =  (int *)malloc(sizeof(int) * userNum);\n    int* n_movie = (int *)malloc(sizeof(int) * movieNum);\n    int i, j;\n    for (i = 0; i < userNum; ++i) {\n        n_user[i] = userStartIdx[i+1] - userStartIdx[i];\n    }\n    for (i = 0; i < movieNum; ++i) {\n        n_movie[i] = movieStartIdx[i+1] - movieStartIdx[i];\n    }\n\n    // create gsl objects\n    gsl_matrix * M = gsl_matrix_alloc (numFeatures, movieNum);\n    gsl_matrix * U = gsl_matrix_alloc (numFeatures, userNum);\n    gsl_matrix * R = gsl_matrix_alloc (userNum, movieNum);\n\n    gsl_matrix * A = gsl_matrix_alloc (numFeatures, numFeatures);\n    gsl_matrix * Ainv = gsl_matrix_alloc (numFeatures, numFeatures);\n\n    gsl_matrix * E = gsl_matrix_alloc (numFeatures, numFeatures);\n    for (i = 0; i < numFeatures; ++i)\n        gsl_matrix_set(E, i, i, 1);\n    gsl_matrix * F = gsl_matrix_alloc (numFeatures, numFeatures);\n\n    gsl_vector * V = gsl_vector_alloc (numFeatures);\n\n    gsl_vector * Rm = gsl_vector_alloc (movieNum);\n    gsl_vector * Ru = gsl_vector_alloc (userNum);\n\n    gsl_permutation *p = gsl_permutation_alloc(numFeatures);\n    gsl_vector * O = gsl_vector_alloc (numFeatures);\n\n    /* Start */\n    // start iteration\n    if (procID == root) {\n        printf(\"Start iteration\\n\");\n        computePredictionRMSE(M, U, R);\n    }\n\n    int iter = 0;\n    for (iter = 0; iter < numIterations; ++iter) {\n\n        // Each processor solve user feature\n        if (procID == root) {\n            printf(\"Updating user (iter = %d)\\n\", iter);\n        }\n\n        int user_idx;\n        int user_num = 0;\n\n        // check span\n        // NOTE THE NUMBER SHOULD BE DIVISIBLE\n        span = (userNum + nproc - 1) / nproc;\n        int user_start_idx = min(procID * span, userNum);\n        int user_end_idx = min(user_start_idx + span, userNum);\n\n        for (user_idx = user_start_idx; user_idx < user_end_idx; ++user_idx) {\n            user_num++;\n\n            gsl_matrix_set_zero (M);\n            for (i = userStartIdx[user_idx]; i < userStartIdx[user_idx+1]; ++i)\n                for (j = 0; j < numFeatures; ++j)\n                    gsl_matrix_set(M, j, i - userStartIdx[user_idx], movieMatrix[(movieId[i]-1) * numFeatures + j]);\n\n            gsl_blas_dgemm(CblasNoTrans, CblasTrans, 1, M, M, 0, A);\n            gsl_matrix_memcpy(F, E);\n            gsl_matrix_scale(F, lambda * n_user[user_idx]);\n            gsl_matrix_add(A, F); // A = M M^T + lambda * n * E\n\n            gsl_vector_set_zero (Rm);\n            for (i = userStartIdx[user_idx]; i < userStartIdx[user_idx+1]; ++i)\n                gsl_vector_set(Rm, i - userStartIdx[user_idx], movieRating[i]);\n\n            gsl_blas_dgemv(CblasNoTrans, 1, M, Rm, 0, V); // V = M R^T\n\n            int s;\n            gsl_linalg_LU_decomp(A, p, &s);\n            gsl_linalg_LU_invert(A, p, Ainv);\n\n            gsl_blas_dgemv(CblasNoTrans, 1, Ainv, V, 0, O); // O = A^-1 V\n\n            for (j = 0; j < numFeatures; ++j)\n                userMatrix[user_idx * numFeatures + j] = gsl_vector_get(O, j);\n        }\n\n        // allgather (everyone gets a local copy of U)\n        MPI_Allgather(&userMatrix[user_start_idx * numFeatures], \n                      span * numFeatures, MPI_DOUBLE, \n                      userMatrix, span * numFeatures, \n                      MPI_DOUBLE, MPI_COMM_WORLD);\n\n        // solver movie feature matrix\n        if (procID == root) {\n            printf(\"Updating movie (iter = %d)\\n\", iter);\n        }\n\n        int movie_idx;\n        int movie_num = 0;\n\n        span = (movieNum + nproc - 1) / nproc;\n        int movie_start_idx = min(procID * span, movieNum);\n        int movie_end_idx = min(movie_start_idx + span, movieNum);\n\n        for (movie_idx = movie_start_idx; movie_idx < movie_end_idx; ++movie_idx) {\n            if (movieStartIdx[movie_idx] == movieStartIdx[movie_idx+1])\n                continue;\n\n            movie_num++;\n            gsl_matrix_set_zero (U);\n            for (i = movieStartIdx[movie_idx]; i < movieStartIdx[movie_idx+1]; ++i)\n                for (j = 0; j < numFeatures; ++j)\n                    gsl_matrix_set(U, j, i - movieStartIdx[movie_idx], userMatrix[(userId[i]-1) * numFeatures + j]);\n\n            gsl_blas_dgemm(CblasNoTrans, CblasTrans, 1, U, U, 0, A);\n            gsl_matrix_memcpy(F, E);\n            gsl_matrix_scale(F, lambda * n_movie[movie_idx]);\n            gsl_matrix_add(A, F); // A = U U^T + lambda * n * E\n\n            gsl_vector_set_zero (Ru);\n            for (i = movieStartIdx[movie_idx]; i < movieStartIdx[movie_idx+1]; ++i)\n                gsl_vector_set(Ru, i - movieStartIdx[movie_idx], userRating[i]);\n\n            gsl_blas_dgemv(CblasNoTrans, 1, U, Ru, 0, V); // V = U R^T\n\n            int s;\n            gsl_linalg_LU_decomp(A, p, &s);\n            gsl_linalg_LU_invert(A, p, Ainv);\n\n            gsl_blas_dgemv(CblasNoTrans, 1, Ainv, V, 0, O); // O = A^-1 V\n\n            for (j = 0; j < numFeatures; ++j)\n                movieMatrix[movie_idx * numFeatures + j] = gsl_vector_get(O, j);\n        }\n\n        // allgather (everyone gets a local copy of M)\n        MPI_Allgather(&movieMatrix[movie_start_idx * numFeatures], \n                      span * numFeatures, MPI_DOUBLE, \n                      movieMatrix, span * numFeatures, \n                      MPI_DOUBLE, MPI_COMM_WORLD);\n\n        // compute prediction and rmse \n        if (procID == root) {\n            computePredictionRMSE(M, U, R);\n        }\n\n    }\n\n    gsl_matrix_free (M);\n    gsl_matrix_free (U);\n    gsl_matrix_free (R);\n    gsl_matrix_free (A);\n    gsl_matrix_free (Ainv);\n    gsl_matrix_free (E);\n    gsl_matrix_free (F);\n\n    gsl_vector_free (V);\n    gsl_vector_free (Rm);\n    gsl_vector_free (Ru);\n    gsl_vector_free (O);\n\n    gsl_permutation_free (p);\n\n    free(n_user);\n    free(n_movie);\n\n    free(userStartIdx);\n    free(movieId);\n    free(movieRating);\n    free(movieStartIdx);\n    free(userId);\n    free(userRating);\n    free(movieMatrix);\n    free(userMatrix);\n}\n\nvoid computePredictionRMSE(gsl_matrix * M, gsl_matrix * U, gsl_matrix * R) {\n    int i, j, user_idx;\n\n    for (i = 0; i < movieNum; ++i)\n        for (j = 0; j < info.numFeatures; ++j)\n            gsl_matrix_set(M, j, i, movieMatrix[i * info.numFeatures + j]);\n\n    for (i = 0; i < userNum; ++i)\n        for (j = 0; j < info.numFeatures; ++j)\n            gsl_matrix_set(U, j, i, userMatrix[i * info.numFeatures + j]);\n\n    gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1, U, M, 0, R);\n\n    double rmse = 0;\n\n    for (user_idx = 0; user_idx < userNum; ++user_idx)\n        for (i = userStartIdx[user_idx]; i < userStartIdx[user_idx+1]; ++i) {\n            double diff = movieRating[i] - gsl_matrix_get(R, user_idx, movieId[i] - 1);\n            rmse += diff * diff;\n        }\n\n    printf(\"RMSE = %f\\n\", rmse / ratingNum);\n}\n", "meta": {"hexsha": "5df898862d244c0700b19b9b40eec0683012cd2c", "size": 16743, "ext": "c", "lang": "C", "max_stars_repo_path": "als/als.c", "max_stars_repo_name": "zheweis/15618-Project", "max_stars_repo_head_hexsha": "64bf98fcdfc8cc1fed510f3c0d62c0204093f603", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-06T17:12:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-06T17:12:01.000Z", "max_issues_repo_path": "als/als.c", "max_issues_repo_name": "zheweis/15618-Project", "max_issues_repo_head_hexsha": "64bf98fcdfc8cc1fed510f3c0d62c0204093f603", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "als/als.c", "max_forks_repo_name": "zheweis/15618-Project", "max_forks_repo_head_hexsha": "64bf98fcdfc8cc1fed510f3c0d62c0204093f603", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7211009174, "max_line_length": 116, "alphanum_fraction": 0.5623245535, "num_tokens": 4441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30404167496654744, "lm_q2_score": 0.026759281924201777, "lm_q1q2_score": 0.008135936897136365}}
{"text": "#include <gsl/gsl_combination.h>\n#include <gsl/gsl_errno.h>\n#include <stdio.h>\n\nint mgsl_combination_fwrite(const char *filename, const gsl_combination *p)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_combination_fwrite(fp, p) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_combination_fread(const char *filename, gsl_combination *p)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_combination_fread(fp, p) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_combination_fprintf(const char *filename, const gsl_combination *p, const char *format)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_combination_fprintf(fp, p, format) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_combination_fscanf(const char *filename, gsl_combination *p)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_combination_fscanf(fp, p) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n", "meta": {"hexsha": "2e54e30c238c19d64b576665364f12b108024d8a", "size": 1143, "ext": "c", "lang": "C", "max_stars_repo_path": "src/combination.c", "max_stars_repo_name": "frithnanth/raku-Math-Libgsl-Combination", "max_stars_repo_head_hexsha": "3e14b5a2265f762e62e24dde3127faac2c69e4f6", "max_stars_repo_licenses": ["Artistic-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/combination.c", "max_issues_repo_name": "frithnanth/raku-Math-Libgsl-Combination", "max_issues_repo_head_hexsha": "3e14b5a2265f762e62e24dde3127faac2c69e4f6", "max_issues_repo_licenses": ["Artistic-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/combination.c", "max_forks_repo_name": "frithnanth/raku-Math-Libgsl-Combination", "max_forks_repo_head_hexsha": "3e14b5a2265f762e62e24dde3127faac2c69e4f6", "max_forks_repo_licenses": ["Artistic-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.575, "max_line_length": 96, "alphanum_fraction": 0.7226596675, "num_tokens": 329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34864513533394575, "lm_q2_score": 0.023330770803304368, "lm_q1q2_score": 0.008134159744163321}}
{"text": "#ifndef BANDED_FLOAT_IMAGE_H\n#define BANDED_FLOAT_IMAGE_H\n\n#include <stdio.h>\n#include <sys/types.h>\n\n#include <glib.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_histogram.h>\n\n#include \"float_image.h\"\n\ntypedef struct\n{\n        int nbands;\n        FloatImage **images;\n} BandedFloatImage;\n\nBandedFloatImage *\nbanded_float_image_new(int nbands, size_t size_x, size_t size_y);\n\nBandedFloatImage *\nbanded_float_image_new_with_value(int nBands, ssize_t size_x, ssize_t size_y, \n\t\t\t\t  float value);\n\nint\nbanded_float_image_store (BandedFloatImage *self, const char *file,\n\t\t\t  float_image_byte_order_t byte_order);\n\nvoid\nbanded_float_image_free(BandedFloatImage *self);\n\nfloat\nbanded_float_image_get_pixel(BandedFloatImage *self, int nband, \n                             ssize_t x, ssize_t y);\n\nvoid\nbanded_float_image_set_pixel(BandedFloatImage *self, int nband, \n                             ssize_t x, ssize_t y, float value);\n\nFloatImage *\nbanded_float_image_get_band(BandedFloatImage *self, int nband);\n\nBandedFloatImage *\nbanded_float_image_new_from_model_scaled (BandedFloatImage *model,\n                                          ssize_t scale_factor);\n\nvoid\nbanded_float_image_export_as_jpeg(BandedFloatImage *self,\n                                  const char *output_name);\n\n\n#endif\n", "meta": {"hexsha": "609b0d084c35c75ae41b5333f8edb4fa0d5ec4c3", "size": 1291, "ext": "h", "lang": "C", "max_stars_repo_path": "src/libasf_raster/banded_float_image.h", "max_stars_repo_name": "glshort/MapReady", "max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z", "max_issues_repo_path": "src/libasf_raster/banded_float_image.h", "max_issues_repo_name": "glshort/MapReady", "max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libasf_raster/banded_float_image.h", "max_forks_repo_name": "glshort/MapReady", "max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z", "avg_line_length": 23.9074074074, "max_line_length": 78, "alphanum_fraction": 0.7149496514, "num_tokens": 311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.399811640739795, "lm_q2_score": 0.020332352229600788, "lm_q1q2_score": 0.00812911110501612}}
{"text": "#pragma once\n\n#include <gsl\\gsl>\n#include <winrt\\Windows.Foundation.h>\n#include <d3d11.h>\n#include \"DrawableGameComponent.h\"\n#include \"MatrixHelper.h\"\n#include \"DirectionalLight.h\"\n\nnamespace Library\n{\n\tclass Texture2D;\n\tclass ProxyModel;\n}\n\nnamespace Rendering\n{\n\tclass NormalMappingMaterial;\n\n\tclass NormalMappingDemo final : public Library::DrawableGameComponent\n\t{\n\tpublic:\n\t\tNormalMappingDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera);\n\t\tNormalMappingDemo(const NormalMappingDemo&) = delete;\n\t\tNormalMappingDemo(NormalMappingDemo&&) = default;\n\t\tNormalMappingDemo& operator=(const NormalMappingDemo&) = default;\t\t\n\t\tNormalMappingDemo& operator=(NormalMappingDemo&&) = default;\n\t\t~NormalMappingDemo();\n\n\t\tbool RealNormalMapEnabled() const;\n\t\tvoid SetRealNormalMapEnabled(bool enabled);\n\t\tvoid ToggleRealNormalMap();\n\n\t\tfloat AmbientLightIntensity() const;\n\t\tvoid SetAmbientLightIntensity(float intensity);\n\n\t\tfloat DirectionalLightIntensity() const;\n\t\tvoid SetDirectionalLightIntensity(float intensity);\n\n\t\tconst DirectX::XMFLOAT3& LightDirection() const;\n\t\tvoid RotateDirectionalLight(DirectX::XMFLOAT2 amount);\n\n\t\tvirtual void Initialize() override;\n\t\tvirtual void Update(const Library::GameTime& gameTime) override;\n\t\tvirtual void Draw(const Library::GameTime& gameTime) override;\n\n\tprivate:\n\t\tstd::shared_ptr<NormalMappingMaterial> mMaterial;\n\t\tDirectX::XMFLOAT4X4 mWorldMatrix{ Library::MatrixHelper::Identity };\n\t\twinrt::com_ptr<ID3D11Buffer> mVertexBuffer;\n\t\tstd::uint32_t mVertexCount{ 0 };\n\t\tLibrary::DirectionalLight mDirectionalLight;\n\t\tstd::unique_ptr<Library::ProxyModel> mProxyModel;\n\t\tstd::shared_ptr<Library::Texture2D> mRealNormalMap;\n\t\tstd::shared_ptr<Library::Texture2D> mDefaultNormalMap;\n\t\tbool mUpdateMaterial{ true };\n\t\tbool mRealNormalMapEnabled{ true };\n\t};\n}", "meta": {"hexsha": "52f288eb006991c9f185f89e96c9e3a2d246179b", "size": 1815, "ext": "h", "lang": "C", "max_stars_repo_path": "source/6.1_Normal_Mapping/NormalMappingDemo.h", "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/6.1_Normal_Mapping/NormalMappingDemo.h", "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/6.1_Normal_Mapping/NormalMappingDemo.h", "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7627118644, "max_line_length": 89, "alphanum_fraction": 0.7834710744, "num_tokens": 451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.016914911439287056, "lm_q1q2_score": 0.008127254287646065}}
{"text": "#pragma once\n\n#include <gsl\\gsl>\n#include <winrt\\Windows.Foundation.h>\n#include <d3d11.h>\n#include \"DrawableGameComponent.h\"\n#include \"MatrixHelper.h\"\n#include \"DirectionalLight.h\"\n\nnamespace Library\n{\n\tclass ProxyModel;\n}\n\nnamespace Rendering\n{\n\tclass DiffuseLightingMaterial;\n\n\tclass DiffuseLightingDemo final : public Library::DrawableGameComponent\n\t{\n\tpublic:\n\t\tDiffuseLightingDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera);\n\t\tDiffuseLightingDemo(const DiffuseLightingDemo&) = delete;\n\t\tDiffuseLightingDemo(DiffuseLightingDemo&&) = default;\n\t\tDiffuseLightingDemo& operator=(const DiffuseLightingDemo&) = default;\t\t\n\t\tDiffuseLightingDemo& operator=(DiffuseLightingDemo&&) = default;\n\t\t~DiffuseLightingDemo();\n\n\t\tbool AnimationEnabled() const;\n\t\tvoid SetAnimationEnabled(bool enabled);\n\t\tvoid ToggleAnimation();\n\n\t\tfloat AmbientLightIntensity() const;\n\t\tvoid SetAmbientLightIntensity(float intensity);\n\n\t\tfloat DirectionalLightIntensity() const;\n\t\tvoid SetDirectionalLightIntensity(float intensity);\n\n\t\tconst DirectX::XMFLOAT3& LightDirection() const;\n\t\tvoid RotateDirectionalLight(DirectX::XMFLOAT2 amount);\n\n\t\tvirtual void Initialize() override;\n\t\tvirtual void Update(const Library::GameTime& gameTime) override;\n\t\tvirtual void Draw(const Library::GameTime& gameTime) override;\n\n\tprivate:\n\t\tinline static const float RotationRate{ DirectX::XM_PI };\n\n\t\tstd::shared_ptr<DiffuseLightingMaterial> mMaterial;\n\t\tDirectX::XMFLOAT4X4 mWorldMatrix{ Library::MatrixHelper::Identity };\n\t\twinrt::com_ptr<ID3D11Buffer> mVertexBuffer;\n\t\twinrt::com_ptr<ID3D11Buffer> mIndexBuffer;\n\t\tstd::uint32_t mIndexCount{ 0 };\n\t\tLibrary::DirectionalLight mDirectionalLight;\n\t\tstd::unique_ptr<Library::ProxyModel> mProxyModel;\n\t\tfloat mModelRotationAngle{ 0.0f };\n\t\tbool mAnimationEnabled{ false };\n\t\tbool mUpdateMaterial{ true };\n\t};\n}", "meta": {"hexsha": "88dc06f1c53a9bf100911b31a670792aaf12fa86", "size": 1839, "ext": "h", "lang": "C", "max_stars_repo_path": "source/7.4_Distortion_Mapping/DiffuseLightingDemo.h", "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/7.4_Distortion_Mapping/DiffuseLightingDemo.h", "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/7.4_Distortion_Mapping/DiffuseLightingDemo.h", "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.65, "max_line_length": 91, "alphanum_fraction": 0.7819467102, "num_tokens": 472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37022537869825406, "lm_q2_score": 0.021948252475347638, "lm_q1q2_score": 0.008125800084450472}}
{"text": "#include <stdlib.h>\n#include <stdio.h>\n#include <stdint.h>\n#include <dc1394/dc1394.h>\n#include <math.h>\n#include <fitsio.h>\n#include <gsl/gsl_statistics.h>\n#include <time.h>\n#include <sys/time.h>\n#include <string.h>\n#include <inttypes.h>\n\n#define REG_CAMERA_ABS_MIN                  0x000U\n#define REG_CAMERA_ABS_MAX                  0x004U\n#define REG_CAMERA_ABS_VALUE                0x008U\n\nint grab_frame(dc1394camera_t *c, unsigned char *buf, int nbytes) {\n  dc1394video_frame_t *frame=NULL;\n  dc1394error_t err;\n  \n  err = dc1394_capture_dequeue(c, DC1394_CAPTURE_POLICY_WAIT, &frame);\n  if (err != DC1394_SUCCESS) {\n    dc1394_log_error(\"Unable to capture.\");\n    dc1394_capture_stop(c);\n    dc1394_camera_free(c);\n    exit(1);\n  }\n  \n  memcpy(buf, frame->image, nbytes);\n  dc1394_capture_enqueue(c, frame);\n  return 1;\n}\n\nint main(int argc, char *argv[]) {\n  \n  long nelements, naxes[2];\n  dc1394_t * dc;\n  dc1394camera_t * camera;\n  dc1394camera_list_t * list;\n  dc1394error_t err;\n  dc1394video_mode_t mode;\n  unsigned int max_height, max_width, winleft, wintop;\n  \n  unsigned char *buffer, *buffer2;\n  double *average, *diff;\n  int j, f, status, nimages, xsize, ysize;\n  double mean, var, exp;\n  struct timeval start_time, end_time;\n  time_t start_sec, end_sec;\n  suseconds_t start_usec, end_usec;\n  float elapsed_time, fps;\n  \n  stderr = freopen(\"noise_test.log\", \"w\", stderr);\n  \n  srand48((unsigned)time(NULL));\n  \n  nimages = 0;\n  status = 0;\n  xsize = 320;\n  ysize = 240;\n  naxes[0] = xsize;\n  naxes[1] = ysize;\n  \n  nelements = naxes[0]*naxes[1];\n  \n  mode = DC1394_VIDEO_MODE_FORMAT7_1;\n  dc = dc1394_new();\n  if (!dc)\n    return -1;\n  err = dc1394_camera_enumerate(dc, &list);\n  DC1394_ERR_RTN(err, \"Failed to enumerate cameras.\");\n  \n  if (list->num == 0) {\n    dc1394_log_error(\"No cameras found.\");\n    return -1;\n  }\n  \n  camera = dc1394_camera_new(dc, list->ids[0].guid);\n  if (!camera) {\n    dc1394_log_error(\"Failed to initialize camera with guid %\"PRIx64\".\", \n                     list->ids[0].guid);\n    return -1;\n  }\n  dc1394_camera_free_list(list);\n  \n  printf(\"Using camera with GUID %\"PRIx64\"\\n\", camera->guid);\n  \n  // need to use legacy firewire400 mode for now.  800 not quite reliable.\n  dc1394_video_set_iso_speed(camera, DC1394_ISO_SPEED_400);\n  \n  // configure camera for format7\n  err = dc1394_video_set_mode(camera, mode);\n  DC1394_ERR_CLN_RTN(err, dc1394_camera_free(camera), \"Can't choose video mode.\");\n  \n  err = dc1394_format7_get_max_image_size(camera, mode, &max_width, &max_height);\n  DC1394_ERR_CLN_RTN(err,dc1394_camera_free (camera),\"cannot get max image size.\");\n  \n  winleft = 0;\n  wintop = 0;\n  \n  err = dc1394_format7_set_roi(camera,\n                               mode,\n                               DC1394_COLOR_CODING_MONO8,\n                               DC1394_USE_MAX_AVAIL,\n                               //\t\t\t\t packet,\n                               winleft, wintop, // left, top\n                               xsize, ysize);\n  DC1394_ERR_CLN_RTN(err, dc1394_camera_free(camera), \"Can't set ROI.\");\n  \n  err=dc1394_video_set_framerate(camera, DC1394_FRAMERATE_MAX);\n  DC1394_ERR_CLN_RTN(err,dc1394_camera_free (camera),\"cannot set framerate\");\n    \n  err = dc1394_feature_set_mode (camera, DC1394_FEATURE_SHUTTER, DC1394_FEATURE_MODE_MANUAL);\n  DC1394_ERR_CLN_RTN(err,dc1394_camera_free (camera),\"cannot set shutter to manual\");\n  \n  err = dc1394_feature_set_value (camera, DC1394_FEATURE_SHUTTER, 61);\n  DC1394_ERR_CLN_RTN(err,dc1394_camera_free (camera),\"cannot set shutter\");\n  \n  err = dc1394_feature_set_mode (camera, DC1394_FEATURE_GAIN, DC1394_FEATURE_MODE_MANUAL);\n  DC1394_ERR_CLN_RTN(err,dc1394_camera_free (camera),\"cannot set gain to manual\");\n  \n  err = dc1394_feature_set_value (camera, DC1394_FEATURE_GAIN, 48);\n  DC1394_ERR_CLN_RTN(err,dc1394_camera_free (camera),\"cannot set gain\");\n  \n  // set brightness manually.  use relative value in range 0 to 1023.\n  err = dc1394_feature_set_mode(camera, DC1394_FEATURE_BRIGHTNESS, DC1394_FEATURE_MODE_MANUAL);\n  DC1394_ERR_CLN_RTN(err,dc1394_camera_free (camera),\"cannot set brightness to manual\");\n  err = dc1394_feature_set_value(camera, DC1394_FEATURE_BRIGHTNESS, 500);\n  DC1394_ERR_CLN_RTN(err,dc1394_camera_free (camera),\"cannot set brightness\");\n  printf (\"I: brightness is %d\\n\", 500);\n  \n  err = dc1394_capture_setup(camera, 16, DC1394_CAPTURE_FLAGS_DEFAULT);\n  DC1394_ERR_CLN_RTN(err, dc1394_camera_free(camera), \"Error capturing.\");\n  \n  // start the camera up\n  err = dc1394_video_set_transmission(camera, DC1394_ON);\n  if (err != DC1394_SUCCESS) {\n    dc1394_log_error(\"Unable to start camera iso transmission.\");\n    dc1394_capture_stop(camera);\n    dc1394_camera_free(camera);\n    return -1;\n  }\n  \n  printf(\"Camera successfully initialized.\\n\");\n  \n  if (!(buffer = malloc(nelements*sizeof(char)))) {\n    printf(\"Couldn't Allocate Image Buffer\\n\");\n    exit(-1);\n  }\n  \n  if (!(buffer2 = malloc(nelements*sizeof(char)))) {\n    printf(\"Couldn't Allocate Image2 Buffer\\n\");\n    exit(-1);\n  }\n  \n  if (!(average = calloc(nelements, sizeof(double)))) {\n    printf(\"Couldn't Allocate Average Image Buffer\\n\");\n    exit(-1);\n  }\n  \n  if (!(diff = calloc(nelements, sizeof(double)))) {\n    printf(\"Couldn't Allocate Diff Image Buffer\\n\");\n    exit(-1);\n  }\n  \n  gettimeofday(&start_time, NULL);\n  \n  f = 0;\n  \n  err = dc1394_feature_set_absolute_control(camera, DC1394_FEATURE_SHUTTER, DC1394_TRUE);\n  DC1394_ERR_CLN_RTN(err,dc1394_camera_free (camera),\"cannot set shutter to absolute mode\");\n  exp = 8.0*1.0e-5;\n  err = dc1394_feature_set_absolute_value(camera, DC1394_FEATURE_SHUTTER, exp);\n  grab_frame(camera, buffer, nelements*sizeof(char));\n  grab_frame(camera, buffer, nelements*sizeof(char));\n  \n  for (f=8; f<320; f++) {\n    exp = f*1.0e-5;\n    err = dc1394_feature_set_absolute_value(camera, DC1394_FEATURE_SHUTTER, exp);\n    DC1394_ERR_CLN_RTN(err,dc1394_camera_free (camera),\"cannot set shutter\");\n    \n    grab_frame(camera, buffer, nelements*sizeof(char));\n    grab_frame(camera, buffer2, nelements*sizeof(char));\n    for (j=0; j<nelements; j++) {\n      average[j] = (buffer[j]+buffer2[j])/2.0;\n    }\n    for (j=0; j<nelements; j++) {\n      diff[j] = buffer[j] - buffer2[j];\n    }\n    \n    var = gsl_stats_variance(diff, 1, nelements);\n    mean = gsl_stats_mean(average, 1, nelements);\n    \n    var = var/2.0;\n    \n    printf(\"%e %10.2f %10.3f\\n\", exp, mean, var);\n    \n  }\n\n  gettimeofday(&end_time, NULL);\n  printf(\"End capture.\\n\");\n  \n  start_sec = start_time.tv_sec;\n  start_usec = start_time.tv_usec;\n  end_sec = end_time.tv_sec;\n  end_usec = end_time.tv_usec;\n  \n  elapsed_time = (float)((end_sec + 1.0e-6*end_usec) - (start_sec + 1.0e-6*start_usec));\n  fps = nimages/elapsed_time;\n  printf(\"Elapsed time = %g seconds.\\n\", elapsed_time);\n  printf(\"Framerate = %g fps.\\n\", fps);\n  \n  /*-----------------------------------------------------------------------\n   *  stop data transmission\n   *-----------------------------------------------------------------------*/\n  err=dc1394_video_set_transmission(camera,DC1394_OFF);\n  DC1394_ERR_RTN(err,\"couldn't stop the camera?\");\n  \n  return (status);\n}\n", "meta": {"hexsha": "ce3d2765027155a9b770a9cf5887969be6603faf", "size": 7148, "ext": "c", "lang": "C", "max_stars_repo_path": "src/noise_test.c", "max_stars_repo_name": "marissakotze/timDIMM", "max_stars_repo_head_hexsha": "dde00a3bb6ca7c3d9b71e24f9363350a0e2a323f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-06T15:26:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-06T15:26:36.000Z", "max_issues_repo_path": "src/noise_test.c", "max_issues_repo_name": "marissakotze/timDIMM", "max_issues_repo_head_hexsha": "dde00a3bb6ca7c3d9b71e24f9363350a0e2a323f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/noise_test.c", "max_forks_repo_name": "marissakotze/timDIMM", "max_forks_repo_head_hexsha": "dde00a3bb6ca7c3d9b71e24f9363350a0e2a323f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-07-29T15:16:35.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-01T13:02:36.000Z", "avg_line_length": 32.3438914027, "max_line_length": 95, "alphanum_fraction": 0.6645215445, "num_tokens": 2071, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32766830082071396, "lm_q2_score": 0.024798158619019753, "lm_q1q2_score": 0.008125570498176745}}
{"text": "#include <api/components.h>\n#include <api/kvstore_itf.h>\n#include <common/string_view.h>\n#include <common/utils.h> /* MiB */\n#include <gsl/pointers> /* not_null */\n\n#include <cstddef> /* size_t */ \n#include <memory> /* unique_ptr */ \n#include <stdexcept> /* runtime_error */\n#include <string>\n\nnamespace\n{\n\t/* things which differ depending on the type of store used */\n\tstruct custom_store\n\t{\n\t\tvirtual ~custom_store() {}\n\t\tvirtual std::size_t minimum_size(std::size_t s) const { return s; }\n\t\tvirtual component::uuid_t factory() const = 0;\n\t\tvirtual std::size_t presumed_allocation() const = 0;\n\t\tvirtual bool uses_numa_nodes() const { return false; }\n\t\tvirtual status_t rc_unknown_attribute() const { return E_NOT_SUPPORTED; }\n\t\tvirtual status_t rc_percent_used() const { return S_OK; }\n\t\tvirtual status_t rc_resize_locked() const { return E_LOCKED; }\n\t\tvirtual status_t rc_attribute_key_null_ptr() const { return E_BAD_PARAM; }\n\t\tvirtual status_t rc_attribute_key_not_found() const { return component::IKVStore::E_KEY_NOT_FOUND; }\n\t\tvirtual status_t rc_attribute_hashtable_expansion() const { return S_OK; }\n\t\tvirtual status_t rc_out_of_memory() const { return component::IKVStore::E_TOO_LARGE; }\n\t\tvirtual status_t rc_atomic_update() const { return S_OK; }\n\t\tvirtual status_t rc_allocate_pool_memory_size_0() const { return S_OK; }\n\t\tvirtual bool swap_updates_timestamp() const { return false; }\n\t};\n\n\tstruct custom_mapstore\n\t\t: public custom_store\n\t{\n\t\tvirtual component::uuid_t factory() const override { return component::mapstore_factory; }\n\t\tstd::size_t minimum_size(std::size_t s) const override { return std::max(std::size_t(8), s); }\n\t\tstd::size_t presumed_allocation() const override { return 1ULL << DM_REGION_LOG_GRAIN_SIZE; }\n\t\tbool uses_numa_nodes() const override { return true; }\n\t\tstatus_t rc_unknown_attribute() const override { return E_INVALID_ARG; }\n\t\tstatus_t rc_percent_used() const override { return rc_unknown_attribute(); }\n\t\tstatus_t rc_resize_locked() const override { return E_INVAL; }\n\t\tstatus_t rc_attribute_key_null_ptr() const override { return E_INVALID_ARG; }\n\t\tstatus_t rc_attribute_key_not_found() const override { return rc_unknown_attribute(); }\n\t\tstatus_t rc_attribute_hashtable_expansion() const override { return rc_unknown_attribute(); }\n\t\tstatus_t rc_out_of_memory() const override { return E_INVAL; }\n\t\tstatus_t rc_atomic_update() const override { return E_NOT_SUPPORTED; }\n\t\tstatus_t rc_allocate_pool_memory_size_0() const override { return E_INVAL; }\n\t};\n\n\tstruct custom_hstore\n\t\t: public custom_store\n\t{\n\t\tvirtual component::uuid_t factory() const override { return component::hstore_factory; }\n\t\tstd::size_t presumed_allocation() const override { return MiB(32); }\n\t\tbool swap_updates_timestamp() const override { return true; }\n\t};\n\n\tstruct custom_hstore_cc\n\t\t: public custom_hstore\n\t{\n\t\tstd::size_t presumed_allocation() const override { return MiB(32); }\n\t};\n\n\tcustom_mapstore custom_mapstore_i{};\n\tcustom_hstore custom_hstore_i{};\n\tcustom_hstore_cc custom_hstore_cc_i{};\n\n\tconst std::map<std::string, gsl::not_null<custom_store *>, std::less<>> custom_map =\n\t{\n\t\t{ \"mapstore\", &custom_mapstore_i },\n\t\t{ \"hstore\", &custom_hstore_i },\n\t\t{ \"hstore-cc\", &custom_hstore_cc_i },\n\t\t{ \"hstore-mc\", &custom_hstore_i },\n\t\t{ \"hstore-mr\", &custom_hstore_i },\n\t\t{ \"hstore-mm\", &custom_hstore_i },\n\t};\n}\n\ngsl::not_null<custom_store *> locate_custom_store(common::string_view store)\n{\n\tconst auto c_it = custom_map.find(store);\n\tif ( c_it == custom_map.end() )\n    {\n\t\tthrow std::runtime_error(common::format(\"store {} not recognized\", store));\n    }\n\treturn c_it->second;\n}\n\nauto make_kvstore(\n\tcommon::string_view store\n\t, gsl::not_null<custom_store *> c\n\t, const component::IKVStore_factory::map_create & mc\n) -> std::unique_ptr<component::IKVStore>\n{\n\tusing IKVStore_factory = component::IKVStore_factory;\n\tconst std::string store_lib = \"libcomponent-\" + std::string(store) + \".so\";\n\tauto *comp = component::load_component(store_lib.c_str(), c->factory());\n\tif ( ! comp )\n    {\n\t\tthrow std::runtime_error(common::format(\"failed to load component {}\", store_lib));\n    }\n\n\tconst auto fact = make_itf_ref(static_cast<IKVStore_factory*>(comp->query_interface(IKVStore_factory::iid())));\n\tconst auto kvstore = fact->create(0, mc);\n\n\treturn std::unique_ptr<component::IKVStore>(kvstore);\n}\n", "meta": {"hexsha": "7458b5315dbfd4895abcad64914a59bbc007585d", "size": 4330, "ext": "h", "lang": "C", "max_stars_repo_path": "src/components/store/test/src/make_kvstore.h", "max_stars_repo_name": "IBM/artemis", "max_stars_repo_head_hexsha": "f655d6e952577de11b52e2f4ab6f48c73ce5dba1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/components/store/test/src/make_kvstore.h", "max_issues_repo_name": "IBM/artemis", "max_issues_repo_head_hexsha": "f655d6e952577de11b52e2f4ab6f48c73ce5dba1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/components/store/test/src/make_kvstore.h", "max_forks_repo_name": "IBM/artemis", "max_forks_repo_head_hexsha": "f655d6e952577de11b52e2f4ab6f48c73ce5dba1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.3636363636, "max_line_length": 112, "alphanum_fraction": 0.7404157044, "num_tokens": 1105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34158248603300034, "lm_q2_score": 0.023689472204049804, "lm_q1q2_score": 0.008091908808268992}}
{"text": "#pragma once\n#include <array>\n#include <variant>\n#include <gsl/gsl-lite.hpp>\n\n#include <clrie/method_info.h>\n#include <clrie/instruction_factory.h>\n\n#include <corhdr.h>\n\n#include \"cil.h\"\n#include \"signature.h\"\n\nnamespace appmap {\n    template <typename T>\n    constexpr COR_SIGNATURE type_signature() {\n        if constexpr (std::is_same_v<T, void>) {\n            return ELEMENT_TYPE_VOID;\n        } else if constexpr (std::is_same_v<T, int32_t>) {\n            return ELEMENT_TYPE_I4;\n        } else if constexpr (std::is_same_v<T, int64_t>) {\n            return ELEMENT_TYPE_I8;\n        } else if constexpr (std::is_same_v<T, uint32_t>) {\n            return ELEMENT_TYPE_U4;\n        } else if constexpr (std::is_same_v<T, uint64_t>) {\n            return ELEMENT_TYPE_U8;\n        } else if constexpr (std::is_same_v<T, char *> || std::is_same_v<T, const char *>) {\n            return ELEMENT_TYPE_STRING;\n        } else if constexpr (std::is_pointer_v<T>) {\n            static_assert(sizeof(void *) == 8);\n            return ELEMENT_TYPE_I8;\n        } else if constexpr (std::is_same_v<T, bool>) {\n            return ELEMENT_TYPE_BOOLEAN;\n        } else {\n            static_assert(std::is_same_v<T, void>, \"unhandled native type\");\n        }\n    }\n\n    template <typename F>\n    struct func_traits;\n\n    template <typename Ret, typename... Args>\n    struct func_traits<Ret(*)(Args...)>\n    {\n        static constexpr std::size_t arity = sizeof...(Args);\n        static constexpr std::array<COR_SIGNATURE, 3 + arity> signature = {\n            IMAGE_CEE_UNMANAGED_CALLCONV_STDCALL,\n            arity,\n            type_signature<Ret>(),\n            type_signature<Args>()...\n        };\n    };\n\n    template <typename C, typename Ret, typename... Args>\n    struct func_traits<Ret(C::*)(Args...)>\n    {\n        using instance_type = C;\n        static constexpr std::size_t arity = sizeof...(Args);\n        static constexpr std::array<COR_SIGNATURE, 4 + arity> signature = {\n            IMAGE_CEE_UNMANAGED_CALLCONV_STDCALL,\n            arity + 1,\n            type_signature<Ret>,\n            type_signature<C*>,\n            type_signature<Args>...\n        };\n    };\n\n    struct instrumentation : public clrie::instruction_factory {\n        instrumentation(clrie::method_info method_info) :\n            clrie::instruction_factory(method_info.instruction_factory()),\n            method(method_info),\n            module(method.module_info()),\n            module_id(module.module_id()),\n            metadata(module.meta_data_emit()),\n            type_factory(module.create_type_factory()),\n            locals(method.get(&IMethodInfo::GetLocalVariables))\n        {}\n\n        clrie::method_info method;\n        clrie::module_info module;\n        const ModuleID module_id;\n        com::ptr<IMetaDataEmit> metadata;\n        com::ptr<ITypeCreator> type_factory;\n        com::ptr<ILocalVariableCollection> locals;\n\n        static com::ptr<ISignatureBuilder> signature_builder;\n\n        template <class F>\n        instruction_sequence make_call(F f) const {\n            return make_call_sig(reinterpret_cast<void *>(f), gsl::make_span(func_traits<F>::signature));\n        }\n\n        instruction_sequence create_call_to_string(const clrie::type &type) const noexcept;\n\n        // Note capture_value takes a reference; in case of a composite type, it dereferences\n        // it to a primitive that can be then passed onto the correct native function.\n        // The argument is updated to reflect the resulting simple type.\n        instruction_sequence capture_value(clrie::type &type) const noexcept;\n\n        template <typename T>\n        uint64_t add_local()\n        {\n            auto t = type_factory.get(&ITypeCreator::FromCorElement, static_cast<CorElementType>(type_signature<T>()));\n            return locals.get(&ILocalVariableCollection::AddLocal, t);\n        }\n\n        // emit metadata and return reference tokens\n\n        mdAssemblyRef assembly_reference(const char16_t *assembly);\n\n        mdTypeRef type_reference(mdAssemblyRef assembly, const char16_t *type);\n        mdTypeRef type_reference(const char16_t *assembly, const char16_t *type) {\n            return type_reference(assembly_reference(assembly), type);\n        }\n\n        mdMemberRef member_reference(mdTypeRef type, const char16_t *member,\n            gsl::span<const COR_SIGNATURE> signature);\n\n        mdMemberRef member_reference(mdAssemblyRef assembly, const char16_t *type,\n            const char16_t *member, gsl::span<const COR_SIGNATURE> signature) {\n            return member_reference(type_reference(assembly, type), member, signature);\n        }\n\n        mdMemberRef member_reference(const char16_t *assembly, const char16_t *type,\n            const char16_t *member, gsl::span<const COR_SIGNATURE> signature) {\n            return member_reference(type_reference(assembly, type), member, signature);\n        }\n\n        mdTypeDef define_type(const char16_t *name);\n        mdFieldDef define_field(mdTypeDef type, const char16_t *name, gsl::span<const COR_SIGNATURE> signature);\n\n        mdMethodDef define_method(\n            mdTypeDef type,\n            const char16_t *name,\n            gsl::span<const COR_SIGNATURE> signature,\n            std::initializer_list<appmap::signature::type> locals,\n            std::vector<cil::instruction> code\n        );\n\n        mdMethodDef define_method(mdTypeDef type, const char16_t *name, gsl::span<const COR_SIGNATURE> signature, std::vector<cil::instruction> code) {\n            return define_method(type, name, signature, {}, std::move(code));\n        }\n\n        template <class Ret, class... Args>\n        mdTypeSpec native_type(Ret (*)(Args...)) {\n            constexpr auto sig = func_traits<Ret(*)(Args...)>::signature;\n            return metadata.get(&IMetaDataEmit::GetTokenFromSig, sig.data(), sig.size());\n        }\n\n        mdTypeSpec type_token(gsl::span<const COR_SIGNATURE> sig) {\n            return metadata.get(&IMetaDataEmit::GetTokenFromTypeSpec, sig.data(), sig.size());\n        }\n\n    protected:\n        instruction_sequence make_call_sig(void *fn, gsl::span<const COR_SIGNATURE> signature) const;\n    };\n}\n", "meta": {"hexsha": "e39ac320525788df14d3974f401af822a44a7f16", "size": 6139, "ext": "h", "lang": "C", "max_stars_repo_path": "source/instrumentation.h", "max_stars_repo_name": "applandinc/appmap-dotnet", "max_stars_repo_head_hexsha": "f62bf237493472a61701c82ddf8d6f3491707307", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-03-11T04:59:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-24T02:04:49.000Z", "max_issues_repo_path": "source/instrumentation.h", "max_issues_repo_name": "applandinc/appmap-dotnet", "max_issues_repo_head_hexsha": "f62bf237493472a61701c82ddf8d6f3491707307", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18.0, "max_issues_repo_issues_event_min_datetime": "2021-03-28T22:32:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-22T16:45:26.000Z", "max_forks_repo_path": "source/instrumentation.h", "max_forks_repo_name": "applandinc/appmap-dotnet", "max_forks_repo_head_hexsha": "f62bf237493472a61701c82ddf8d6f3491707307", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-24T02:05:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-24T02:05:16.000Z", "avg_line_length": 38.8544303797, "max_line_length": 151, "alphanum_fraction": 0.6393549438, "num_tokens": 1336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2974699426047947, "lm_q2_score": 0.02716923419419264, "lm_q1q2_score": 0.00808203053636271}}
{"text": "/*\n* Copyright 2019 Virtru Corporation\n*\n* SPDX - License Identifier: BSD-3-Clause-Clear\n*\n*/\n//\n//  TDF SDK\n//\n//  Created by Sujan Reddy on 2019/04/07.\n//\n\n#ifndef VIRTRU_BYTES_H\n#define VIRTRU_BYTES_H\n\n#include <gsl/span>\n#include <array>\n\n/// This provides a simple wrapper around gsl to work with bytes.\nnamespace virtru::crypto {\n\n    /// Constants\n    constexpr auto kKeyLength = 32;\n    constexpr auto kIVLength = 16;\n\n   ///\n   /// Define the bytes(Read only).\n   ///\n   template <std::ptrdiff_t Extent = gsl :: dynamic_extent>\n   using BytesT = gsl::span <const gsl::byte, Extent>;\n   using Bytes = BytesT<>;\n\n   ///\n   /// Wrapper around std::array\n   ///\n   template <std::size_t N>\n   using ByteArray = std::array <gsl :: byte, N>;\n   using WrappedKey = ByteArray<kKeyLength>;\n   using IV = ByteArray<kIVLength>;\n\n    ///\n    /// Define writeable bytes\n    ///\n    template <std::ptrdiff_t Extent = gsl::dynamic_extent>\n    using WriteableBytesT = gsl::span <gsl::byte, Extent>;\n    using WriteableBytes = WriteableBytesT<>;\n\n    template <std :: ptrdiff_t Extent >\n    constexpr auto toBytes(BytesT < Extent > data) noexcept {\n        return data;\n    }\n    \n    template <std::ptrdiff_t Extent>\n    constexpr auto toWriteableBytes(WriteableBytesT <Extent> data) noexcept {\n        return data;\n    }\n\n    /// Adding constness\n    template <std::ptrdiff_t Extent>\n    constexpr auto toBytes (gsl::span <gsl::byte, Extent> data) noexcept {\n        return BytesT <Extent> {data};\n    }\n\n    /// Any containers inherited from basic_string<ElementType> to bytes(Read only).\n    template <typename ElementType,\n              std::ptrdiff_t Extent,\n              typename = std::enable_if_t <std::has_unique_object_representations_v <ElementType>> >\n    auto toBytes (gsl::span <ElementType, Extent> data) noexcept {\n        return as_bytes(data);\n    }\n\n    /// Any containers inherited from basic_string<ElementType> to writable bytes.\n    template <typename ElementType,\n              std::ptrdiff_t Extent,\n              typename = std::enable_if_t <std::has_unique_object_representations_v <ElementType>> >\n    auto toWriteableBytes(gsl::span <ElementType, Extent> data) noexcept {\n        return as_writeable_bytes(data);\n    }\n\n    /// Form std::array to bytes(Read only).\n    template <typename ElementType,\n              std::size_t N,\n              typename = std::enable_if_t <std::has_unique_object_representations_v <ElementType>> >\n    constexpr auto toBytes(const std::array <ElementType, N> & data) noexcept {\n        return toBytes(gsl::span <const ElementType, N > { data });\n    }\n\n    /// Form std::array to writable bytes.\n    template <typename ElementType,\n              std::size_t N,\n              typename = std::enable_if_t <std::has_unique_object_representations_v <ElementType>> >\n    constexpr auto toWriteableBytes(std::array <ElementType, N> & data) noexcept {\n        return toWriteableBytes(gsl::span <ElementType, N> { data });\n    }\n\n    // Form Plain old C array to bytes(Read only).\n    template <typename ElementType, \n              std::size_t N,\n              typename = std::enable_if_t <std::has_unique_object_representations_v <ElementType>> >\n    constexpr auto toBytes(ElementType (& arr)[N]) noexcept {\n        return toBytes(gsl::make_span(arr));\n    }\n\n    // Form Plain old C array to writable bytes.\n    template <typename ElementType,\n              std::size_t N,\n              typename = std::enable_if_t <std::has_unique_object_representations_v <ElementType>> >\n    constexpr auto toWriteableBytes(ElementType(&arr)[N]) noexcept {\n        return toWriteableBytes(gsl::make_span(arr));\n    }\n\n    // From container(std::string/std::vector<char>) to bytes(Read only).\n    template <class Cont,\n              typename = std::enable_if_t <std::has_unique_object_representations_v <std::remove_reference_t <\n                                           decltype(* std::declval <const Cont&> ().data ())>> > >\n    constexpr auto toBytes(const Cont & cont) noexcept {\n        return toBytes(gsl::make_span(cont));\n    }\n\n    // From container(std::string/std::vector<char>) to to writable bytes.\n    template <class Cont,\n              typename = std::enable_if_t <std::has_unique_object_representations_v <std::remove_reference_t <\n                                           decltype(* std::declval <Cont &> ().data ())>> > >\n    constexpr auto toWriteableBytes(Cont & cont) noexcept {\n        return toWriteableBytes(gsl::make_span(cont));\n    }\n\n    ///\n    /// Simple conversions.\n    ///\n    template <typename T>\n    using ConvertibleToBytes = decltype(toBytes(std::declval <const T&> ()));\n\n    template <typename T, std::ptrdiff_t Extent = gsl::dynamic_extent>\n    inline constexpr bool isBytes = std::is_convertible_v <const T&, BytesT <Extent>>;\n\n    template <typename T>\n    using ExplicitlyConvertibleToBytes = std::enable_if_t <! isBytes <T>, ConvertibleToBytes <T>>;\n\n    template <typename T, typename = ConvertibleToBytes <T>>\n    auto toDynamicBytes (const T& t) {\n        return Bytes { toBytes(t) };\n    }\n\n    template <typename T, typename = ExplicitlyConvertibleToBytes <T>>\n    auto toDynamicBytesExplicitly (const T& t) {\n        return toDynamicBytes(t);\n    }\n\n    inline unsigned char* toUchar(gsl::byte* p) {\n        return reinterpret_cast <unsigned char *> (p);\n    }\n\n    inline const unsigned char *toUchar (const gsl::byte *p) {\n        return reinterpret_cast <const unsigned char *> (p);\n    }\n\n    template <std::ptrdiff_t Extent>\n    auto toUchar(BytesT<Extent> src) {\n        return gsl::span <const unsigned char, Extent> {reinterpret_cast <const unsigned char *> (src.data ()), src.size()};\n    }\n\n    inline char* toChar(gsl::byte *p) {\n        return reinterpret_cast <char*> (p);\n    }\n\n    inline const char* toChar(const gsl::byte* p) {\n        return reinterpret_cast <const char *> (p);\n    }\n\n    template <std::ptrdiff_t Extent>\n    auto toChar(BytesT <Extent> src) {\n        return gsl :: span <const char, Extent> { reinterpret_cast <const char*> (src.data()), src.size ()};\n    }\n\n    template <std::ptrdiff_t Extent>\n    auto toChar(WriteableBytesT <Extent> src) {\n        return gsl::span <const char, Extent> { reinterpret_cast <const char *> (src.data()), src.size ()};\n    }\n\n    inline auto finalizeSize(WriteableBytes& buffer, const int& size) {\n        return gsl::finally( [&buffer, &size ] { buffer = buffer.first(size); });\n    }\n} // namespace virtru::crypto\n\n#endif //VIRTRU_BYTES_H\n\n", "meta": {"hexsha": "6de72185fec91d21997ee77adc40a801a2c26f8b", "size": 6504, "ext": "h", "lang": "C", "max_stars_repo_path": "src/lib/include/crypto/bytes.h", "max_stars_repo_name": "opentdf/client-cpp", "max_stars_repo_head_hexsha": "9c6dbc73a989733e30371555aa7a24ff496a62f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lib/include/crypto/bytes.h", "max_issues_repo_name": "opentdf/client-cpp", "max_issues_repo_head_hexsha": "9c6dbc73a989733e30371555aa7a24ff496a62f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2022-01-31T14:42:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T22:44:54.000Z", "max_forks_repo_path": "src/lib/include/crypto/bytes.h", "max_forks_repo_name": "opentdf/client-cpp", "max_forks_repo_head_hexsha": "9c6dbc73a989733e30371555aa7a24ff496a62f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-09T18:40:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T18:40:47.000Z", "avg_line_length": 34.5957446809, "max_line_length": 124, "alphanum_fraction": 0.6434501845, "num_tokens": 1592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2068940390354276, "lm_q2_score": 0.039048296220876993, "lm_q1q2_score": 0.008078859722589066}}
{"text": "#include \"ccv_nnc.h\"\n#include \"ccv_nnc_easy.h\"\n#include \"ccv_nnc_internal.h\"\n#include \"ccv_internal.h\"\n#include \"3rdparty/khash/khash.h\"\n#ifdef HAVE_GSL\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n#else\n#include \"3rdparty/sfmt/SFMT.h\"\n#endif\n\nKHASH_MAP_INIT_INT64(ctx, ccv_array_t*)\n\nstruct ccv_cnnp_dataframe_s {\n\tint row_count;\n\tint column_size;\n\tint* shuffled_idx;\n#ifdef HAVE_GSL\n\tgsl_rng* rng;\n#else\n\tsfmt_t sfmt;\n#endif\n\tkhash_t(ctx)* data_ctx; // The stream context based cache for data entity of columns. This helps us to avoid allocations when iterate through data.\n\tccv_array_t* derived_column_data;\n\tccv_cnnp_column_data_t column_data[1];\n};\n\ntypedef struct {\n\tint stream_type;\n\tint column_idx_size;\n\tint* column_idxs;\n\tccv_cnnp_column_data_enum_f data_enum;\n\tccv_cnnp_column_data_deinit_f data_deinit;\n\tvoid* context;\n\tccv_cnnp_column_data_context_deinit_f context_deinit;\n\tccv_cnnp_column_data_map_f map;\n} ccv_cnnp_derived_column_data_t;\n\nccv_cnnp_dataframe_t* ccv_cnnp_dataframe_new(const ccv_cnnp_column_data_t* const column_data, const int column_size, const int row_count)\n{\n\tassert(column_size >= 0);\n\tccv_cnnp_dataframe_t* const dataframe = (ccv_cnnp_dataframe_t*)cccalloc(1, sizeof(ccv_cnnp_dataframe_t) + sizeof(ccv_cnnp_column_data_t) * (column_size - 1));\n\tdataframe->row_count = row_count;\n\tdataframe->column_size = column_size;\n\tdataframe->data_ctx = kh_init(ctx);\n\tif (column_size > 0)\n\t\tmemcpy(dataframe->column_data, column_data, sizeof(ccv_cnnp_column_data_t) * column_size);\n\treturn dataframe;\n}\n\nvoid ccv_cnnp_dataframe_shuffle(ccv_cnnp_dataframe_t* const dataframe)\n{\n\tassert(dataframe->row_count);\n\tint i;\n\tif (!dataframe->shuffled_idx)\n\t{\n\t\tdataframe->shuffled_idx = (int*)ccmalloc(sizeof(int) * dataframe->row_count);\n\t\tfor (i = 0; i < dataframe->row_count; i++)\n\t\t\tdataframe->shuffled_idx[i] = i;\n#ifdef HAVE_GSL\n\t\tassert(!dataframe->rng);\n\t\tgsl_rng_env_setup();\n\t\tdataframe->rng = gsl_rng_alloc(gsl_rng_default);\n\t\tgsl_rng_set(dataframe->rng, (unsigned long int)dataframe);\n#else\n\t\tsfmt_init_gen_rand(&dataframe->sfmt, (uint32_t)dataframe);\n#endif\n\t}\n#ifdef HAVE_GSL\n\tgsl_ran_shuffle(dataframe->rng, dataframe->shuffled_idx, dataframe->row_count, sizeof(int));\n#else\n\tsfmt_genrand_shuffle(&dataframe->sfmt, dataframe->shuffled_idx, dataframe->row_count, sizeof(int));\n#endif\n}\n\nint ccv_cnnp_dataframe_row_count(ccv_cnnp_dataframe_t* const dataframe)\n{\n\treturn dataframe->row_count;\n}\n\nint ccv_cnnp_dataframe_add(ccv_cnnp_dataframe_t* const dataframe, ccv_cnnp_column_data_enum_f data_enum, const int stream_type, ccv_cnnp_column_data_deinit_f data_deinit, void* const context, ccv_cnnp_column_data_context_deinit_f context_deinit)\n{\n\tif (!dataframe->derived_column_data)\n\t\tdataframe->derived_column_data = ccv_array_new(sizeof(ccv_cnnp_derived_column_data_t), 1, 0);\n\tccv_cnnp_derived_column_data_t column_data = {\n\t\t.stream_type = stream_type,\n\t\t.data_enum = data_enum,\n\t\t.data_deinit = data_deinit,\n\t\t.context = context,\n\t\t.context_deinit = context_deinit,\n\t};\n\tccv_array_push(dataframe->derived_column_data, &column_data);\n\treturn dataframe->column_size + dataframe->derived_column_data->rnum - 1;\n}\n\nint ccv_cnnp_dataframe_map(ccv_cnnp_dataframe_t* const dataframe, ccv_cnnp_column_data_map_f map, const int stream_type, ccv_cnnp_column_data_deinit_f data_deinit, const int* const column_idxs, const int column_idx_size, void* const context, ccv_cnnp_column_data_context_deinit_f context_deinit)\n{\n\tassert(column_idx_size > 0);\n\tif (!dataframe->derived_column_data)\n\t\tdataframe->derived_column_data = ccv_array_new(sizeof(ccv_cnnp_derived_column_data_t), 1, 0);\n\tconst int column_size = dataframe->column_size + dataframe->derived_column_data->rnum;\n\tint i;\n\tfor (i = 0; i < column_idx_size; i++)\n\t\t{ assert(column_idxs[i] < column_size); }\n\tccv_cnnp_derived_column_data_t column_data = {\n\t\t.stream_type = stream_type,\n\t\t.column_idx_size = column_idx_size,\n\t\t.column_idxs = (int*)ccmalloc(sizeof(int) * column_idx_size),\n\t\t.map = map,\n\t\t.data_deinit = data_deinit,\n\t\t.context = context,\n\t\t.context_deinit = context_deinit,\n\t};\n\tmemcpy(column_data.column_idxs, column_idxs, sizeof(int) * column_idx_size);\n\tccv_array_push(dataframe->derived_column_data, &column_data);\n\treturn dataframe->column_size + dataframe->derived_column_data->rnum - 1;\n}\n\nvoid* ccv_cnnp_dataframe_column_context(const ccv_cnnp_dataframe_t* const dataframe, const int column_idx)\n{\n\tassert(column_idx >= 0);\n\tconst int column_size = dataframe->column_size + (dataframe->derived_column_data ? dataframe->derived_column_data->rnum : 0);\n\tassert(column_idx < column_size);\n\tif (column_idx < dataframe->column_size)\n\t\treturn dataframe->column_data[column_idx].context;\n\tassert(dataframe->derived_column_data);\n\tccv_cnnp_derived_column_data_t* const derived_column_data = (ccv_cnnp_derived_column_data_t*)ccv_array_get(dataframe->derived_column_data, column_idx - dataframe->column_size);\n\treturn derived_column_data->context;\n}\n\ntypedef struct {\n\tint flag; // Mark this as cached or not.\n\tuint64_t ctx; // The stream context.\n\tvoid* data;\n} ccv_cnnp_dataframe_data_item_t;\n\ntypedef struct {\n\tccv_nnc_stream_context_t* stream_context;\n\tccv_nnc_stream_signal_t* signal;\n} ccv_cnnp_dataframe_column_ctx_t;\n\nKHASH_MAP_INIT_INT64(iter_ctx, ccv_cnnp_dataframe_column_ctx_t*)\n\nstruct ccv_cnnp_dataframe_iter_s {\n\tint idx;\n\tint prefetch_head;\n\tint prefetch_tail;\n\tint column_idx_size;\n\tint fetched_size; // The size of fetched data.\n\tccv_cnnp_dataframe_t* dataframe;\n\tvoid**** derived_data; // This is ridiculous, but it is true.\n\tvoid** fetched_data; // The cache to store fetched data.\n\tkhash_t(iter_ctx)* column_ctx; // Column context specific to a stream context. The key will be a parent stream context and value will be child stream context + signal.\n\tccv_array_t* prefetches; // The prefetch contents.\n\tint* column_idxs;\n\tccv_cnnp_dataframe_data_item_t cached_data[1]; // The data cached when deriving data.\n};\n\n#define INDEX_DATA(iter) ((int*)((iter)->fetched_data))\n#define FETCHED_DATA(iter, idx) ((iter)->fetched_data + ((idx) + 1) * (iter)->fetched_size)\n\nccv_cnnp_dataframe_iter_t* ccv_cnnp_dataframe_iter_new(ccv_cnnp_dataframe_t* const dataframe, const int* const column_idxs, const int column_idx_size)\n{\n\tassert(column_idx_size > 0);\n\tconst int column_size = dataframe->column_size + (dataframe->derived_column_data ? dataframe->derived_column_data->rnum : 0);\n\tint i;\n\tfor (i = 0; i < column_idx_size; i++)\n\t\t{ assert(column_idxs[i] < column_size); }\n\tccv_cnnp_dataframe_iter_t* const iter = (ccv_cnnp_dataframe_iter_t*)cccalloc(1, sizeof(ccv_cnnp_dataframe_iter_t) + sizeof(ccv_cnnp_dataframe_data_item_t) * column_size + sizeof(void*) * (column_idx_size - 1) + sizeof(int) * column_idx_size);\n\titer->dataframe = dataframe;\n\titer->prefetch_tail = -1;\n\titer->column_idx_size = column_idx_size;\n\titer->column_idxs = (int*)(iter->cached_data + column_size);\n\tmemcpy(iter->column_idxs, column_idxs, sizeof(int) * column_idx_size);\n\t// Preallocate fetched data.\n\titer->fetched_size = 1;\n\titer->fetched_data = (void**)ccmalloc(sizeof(void*) * (column_size + 1));\n\treturn iter;\n}\n\nstatic void _ccv_cnnp_dataframe_enqueue_data(ccv_cnnp_dataframe_t* const dataframe, void* const data, const int column_idx, const uint64_t ctx)\n{\n\tif (!data)\n\t\treturn;\n\tkhash_t(ctx)* const data_ctx = dataframe->data_ctx;\n\tint ret = 0;\n\tkhiter_t k = kh_put(ctx, data_ctx, ctx, &ret);\n\tassert(ret >= 0);\n\tconst int column_size = dataframe->column_size + (dataframe->derived_column_data ? dataframe->derived_column_data->rnum : 0);\n\tassert(column_idx < column_size);\n\t// If ret == 0, the key already exist, we can get the columns directly, otherwise, create and assign back.\n\tccv_array_t* const columns = (ret == 0) ? kh_val(data_ctx, k) : ccv_array_new(sizeof(ccv_array_t*), column_size, 0);\n\tif (ret != 0)\n\t\tkh_val(data_ctx, k) = columns;\n\tif (columns->rnum < column_size)\n\t\tccv_array_resize(columns, column_size);\n\tccv_array_t* column = *(ccv_array_t**)ccv_array_get(columns, column_idx);\n\tif (!column)\n\t{\n\t\tcolumn = ccv_array_new(sizeof(void*), 1, 0);\n\t\t*(ccv_array_t**)ccv_array_get(columns, column_idx) = column;\n\t}\n\tccv_array_push(column, &data);\n}\n\nstatic void* _ccv_cnnp_dataframe_dequeue_data(ccv_cnnp_dataframe_t* const dataframe, const int column_idx, ccv_nnc_stream_context_t* const stream_context)\n{\n\tconst uint64_t ctx = (uint64_t)(uintptr_t)stream_context;\n\tkhash_t(ctx)* const data_ctx = dataframe->data_ctx;\n\tkhiter_t k = kh_get(ctx, data_ctx, ctx);\n\tif (k == kh_end(data_ctx))\n\t\treturn 0;\n\tccv_array_t* const columns = kh_val(data_ctx, k);\n\tif (column_idx >= columns->rnum)\n\t\treturn 0;\n\tccv_array_t* const column = *(ccv_array_t**)ccv_array_get(columns, column_idx);\n\tif (!column || column->rnum == 0)\n\t\treturn 0;\n\tvoid* const data = *(void**)ccv_array_get(column, column->rnum - 1);\n\t--column->rnum;\n\treturn data;\n}\n\nstatic ccv_cnnp_dataframe_column_ctx_t _ccv_cnnp_child_column_ctx_for_stream_type(ccv_cnnp_dataframe_t* const dataframe, ccv_cnnp_dataframe_iter_t* const iter, const int column_idx, ccv_nnc_stream_context_t* const stream_context, const int stream_type)\n{\n\tccv_cnnp_dataframe_column_ctx_t child_ctx = {\n\t\t.stream_context = stream_context,\n\t};\n\tif (stream_context && ccv_nnc_stream_context_type(stream_context) != stream_type && stream_type != 0)\n\t{\n\t\tif (!iter->column_ctx)\n\t\t\titer->column_ctx = kh_init(iter_ctx);\n\t\tkhash_t(iter_ctx)* const column_ctx = iter->column_ctx;\n\t\tint ret = 0;\n\t\tkhiter_t k = kh_put(iter_ctx, column_ctx, (uint64_t)(uintptr_t)stream_context, &ret);\n\t\tassert(ret >= 0);\n\t\tconst int column_size = dataframe->column_size + (dataframe->derived_column_data ? dataframe->derived_column_data->rnum : 0);\n\t\tccv_cnnp_dataframe_column_ctx_t* const ctx = (ret == 0) ? kh_val(column_ctx, k) : cccalloc(column_size, sizeof(ccv_cnnp_dataframe_column_ctx_t));\n\t\tif (ret != 0)\n\t\t\tkh_val(column_ctx, k) = ctx;\n\t\tif (!ctx[column_idx].stream_context)\n\t\t\tctx[column_idx].stream_context = ccv_nnc_stream_context_new(stream_type);\n\t\tif (!ctx[column_idx].signal)\n\t\t\tctx[column_idx].signal = ccv_nnc_stream_signal_new(stream_type);\n\t\tchild_ctx = ctx[column_idx];\n\t}\n\treturn child_ctx;\n}\n\nstatic void _ccv_cnnp_dataframe_column_data(ccv_cnnp_dataframe_t* const dataframe, ccv_cnnp_dataframe_iter_t* const iter, ccv_cnnp_dataframe_data_item_t* const cached_data, void** const fetched_data, const int* const row_idxs, const int row_size, const int column_idx, const int cached_step, ccv_nnc_stream_context_t* const stream_context)\n{\n\tint i;\n\tif (cached_data[column_idx * cached_step].flag)\n\t{\n\t\tfor (i = 1; i < row_size; i++)\n\t\t\t{ assert(cached_data[i + column_idx * cached_step].flag); }\n\t\tfor (i = 0; i < row_size; i++)\n\t\t\tfetched_data[i] = cached_data[i + column_idx * cached_step].data;\n\t\treturn;\n\t} else {\n\t\tfor (i = 1; i < row_size; i++)\n\t\t\t{ assert(!cached_data[i + column_idx * cached_step].flag); }\n\t\tfor (i = 0; i < row_size; i++)\n\t\t\tfetched_data[i] = _ccv_cnnp_dataframe_dequeue_data(dataframe, column_idx, stream_context);\n\t}\n\tif (column_idx >= dataframe->column_size)\n\t{\n\t\tassert(dataframe->derived_column_data);\n\t\tconst int derived_column_idx = column_idx - dataframe->column_size;\n\t\tconst ccv_cnnp_derived_column_data_t* const derived_column_data = (ccv_cnnp_derived_column_data_t*)ccv_array_get(dataframe->derived_column_data, derived_column_idx);\n\t\tccv_cnnp_dataframe_column_ctx_t child_ctx = _ccv_cnnp_child_column_ctx_for_stream_type(dataframe, iter, column_idx, stream_context, derived_column_data->stream_type);\n\t\tconst int column_idx_size = derived_column_data->column_idx_size;\n\t\tif (derived_column_data->map)\n\t\t{\n\t\t\tint i;\n\t\t\tif (!iter->derived_data)\n\t\t\t\titer->derived_data = (void****)cccalloc(dataframe->derived_column_data->rnum, sizeof(void***));\n\t\t\tif (!iter->derived_data[derived_column_idx])\n\t\t\t\titer->derived_data[derived_column_idx] = (void***)cccalloc(derived_column_data->column_idx_size, sizeof(void**));\n\t\t\tvoid*** const derived_data = iter->derived_data[derived_column_idx];\n\t\t\tfor (i = 0; i < column_idx_size; i++)\n\t\t\t{\n\t\t\t\tderived_data[i] = FETCHED_DATA(iter, derived_column_data->column_idxs[i]);\n\t\t\t\t_ccv_cnnp_dataframe_column_data(dataframe, iter, cached_data, derived_data[i], row_idxs, row_size, derived_column_data->column_idxs[i], cached_step, stream_context);\n\t\t\t}\n\t\t\tderived_column_data->map(derived_data, derived_column_data->column_idx_size, row_size, fetched_data, derived_column_data->context, child_ctx.stream_context);\n\t\t} else\n\t\t\tderived_column_data->data_enum(column_idx, row_idxs, row_size, fetched_data, derived_column_data->context, child_ctx.stream_context);\n\t\tif (child_ctx.stream_context != stream_context)\n\t\t{\n\t\t\tccv_nnc_stream_context_emit_signal(child_ctx.stream_context, child_ctx.signal);\n\t\t\tccv_nnc_stream_context_wait_signal(stream_context, child_ctx.signal);\n\t\t}\n\t} else {\n\t\tconst ccv_cnnp_column_data_t* const column_data = dataframe->column_data + column_idx;\n\t\tccv_cnnp_dataframe_column_ctx_t child_ctx = _ccv_cnnp_child_column_ctx_for_stream_type(dataframe, iter, column_idx, stream_context, column_data->stream_type);\n\t\tcolumn_data->data_enum(column_idx, row_idxs, row_size, fetched_data, column_data->context, child_ctx.stream_context);\n\t\tif (child_ctx.stream_context != stream_context)\n\t\t{\n\t\t\tccv_nnc_stream_context_emit_signal(child_ctx.stream_context, child_ctx.signal);\n\t\t\tccv_nnc_stream_context_wait_signal(stream_context, child_ctx.signal);\n\t\t}\n\t}\n\tfor (i = 0; i < row_size; i++)\n\t{\n\t\tcached_data[i + column_idx * cached_step].flag = 1;\n\t\tcached_data[i + column_idx * cached_step].ctx = (uint64_t)(uintptr_t)stream_context;\n\t\tcached_data[i + column_idx * cached_step].data = fetched_data[i];\n\t}\n}\n\nint ccv_cnnp_dataframe_iter_next(ccv_cnnp_dataframe_iter_t* const iter, void** const data_ref, const int column_idx_size, ccv_nnc_stream_context_t* const stream_context)\n{\n\tccv_cnnp_dataframe_t* const dataframe = iter->dataframe;\n\tassert(column_idx_size <= iter->column_idx_size);\n\tconst int column_size = dataframe->column_size + (dataframe->derived_column_data ? dataframe->derived_column_data->rnum : 0);\n\tint i;\n\t// Push existing data back to reusable state (note, these may not be reused immediately because they may be on a different stream context).\n\tfor (i = 0; i < column_size; i++)\n\t\tif (iter->cached_data[i].flag)\n\t\t{\n\t\t\t_ccv_cnnp_dataframe_enqueue_data(dataframe, iter->cached_data[i].data, i, iter->cached_data[i].ctx);\n\t\t\titer->cached_data[i].flag = 0;\n\t\t\titer->cached_data[i].data = 0;\n\t\t\titer->cached_data[i].ctx = 0;\n\t\t}\n\tconst int idx = iter->idx;\n\tif (idx == dataframe->row_count)\n\t\treturn -1;\n\tif (iter->prefetch_tail != -1) // If there is something in prefetch log.\n\t{\n\t\tccv_array_t* const prefetches = iter->prefetches;\n\t\tassert(prefetches);\n\t\tconst int lines = prefetches->rnum / column_size;\n\t\tif (iter->prefetch_head == iter->prefetch_tail) // Only one item.\n\t\t\titer->prefetch_tail = -1;\n\t\tccv_cnnp_dataframe_data_item_t* const cached_data = (ccv_cnnp_dataframe_data_item_t*)ccv_array_get(iter->prefetches, iter->prefetch_head);\n\t\tfor (i = 0; i < column_size; i++)\n\t\t{\n\t\t\tif (!cached_data[i * lines].flag)\n\t\t\t\tcontinue;\n\t\t\tif (cached_data[i * lines].ctx == (uint64_t)(uintptr_t)stream_context) // If match existing stream context.\n\t\t\t\titer->cached_data[i] = cached_data[i * lines];\n\t\t\telse // Recycle\n\t\t\t\t_ccv_cnnp_dataframe_enqueue_data(dataframe, cached_data[i * lines].data, i, cached_data[i * lines].ctx);\n\t\t}\n\t\t++iter->prefetch_head;\n\t\tassert(prefetches->rnum % column_size == 0);\n\t\tif (iter->prefetch_head >= lines)\n\t\t\titer->prefetch_head = 0;\n\t}\n\tfor (i = 0; i < column_idx_size; i++)\n\t\t_ccv_cnnp_dataframe_column_data(dataframe, iter, iter->cached_data, data_ref + i, dataframe->shuffled_idx ? dataframe->shuffled_idx + idx : &idx, 1, iter->column_idxs[i], 1, stream_context);\n\t++iter->idx;\n\treturn 0;\n}\n\nstatic void _ccv_cnnp_null_prefetches(ccv_cnnp_dataframe_iter_t* const iter)\n{\n\tccv_cnnp_dataframe_t* const dataframe = iter->dataframe;\n\tassert(dataframe);\n\tint i, j;\n\tconst int column_size = dataframe->column_size + (dataframe->derived_column_data ? dataframe->derived_column_data->rnum : 0);\n\tif (iter->prefetch_head <= iter->prefetch_tail)\n\t{\n\t\tassert(iter->prefetches);\n\t\tconst int lines = iter->prefetches->rnum / column_size;\n\t\tfor (i = iter->prefetch_head; i <= iter->prefetch_tail; i++)\n\t\t{\n\t\t\tccv_cnnp_dataframe_data_item_t* const cached_data = ccv_array_get(iter->prefetches, i);\n\t\t\tfor (j = 0; j < column_size; j++)\n\t\t\t\tif (cached_data[j * lines].flag)\n\t\t\t\t\t_ccv_cnnp_dataframe_enqueue_data(dataframe, cached_data[j * lines].data, j, cached_data[j * lines].ctx);\n\t\t}\n\t} else if (iter->prefetch_tail >= 0) { // -1 means no item.\n\t\tassert(iter->prefetches);\n\t\tconst int lines = iter->prefetches->rnum / column_size;\n\t\tfor (i = iter->prefetch_head; i < lines; i++)\n\t\t{\n\t\t\tccv_cnnp_dataframe_data_item_t* const cached_data = ccv_array_get(iter->prefetches, i);\n\t\t\tfor (j = 0; j < column_size; j++)\n\t\t\t\tif (cached_data[j * lines].flag)\n\t\t\t\t\t_ccv_cnnp_dataframe_enqueue_data(dataframe, cached_data[j * lines].data, j, cached_data[j * lines].ctx);\n\t\t}\n\t\tfor (i = 0; i <= iter->prefetch_tail; i++)\n\t\t{\n\t\t\tccv_cnnp_dataframe_data_item_t* const cached_data = ccv_array_get(iter->prefetches, i);\n\t\t\tfor (j = 0; j < column_size; j++)\n\t\t\t\tif (cached_data[j * lines].flag)\n\t\t\t\t\t_ccv_cnnp_dataframe_enqueue_data(dataframe, cached_data[j * lines].data, j, cached_data[j * lines].ctx);\n\t\t}\n\t}\n\titer->prefetch_head = 0;\n\titer->prefetch_tail = -1;\n}\n\nstatic void _ccv_cnnp_prefetch_cached_data(ccv_cnnp_dataframe_iter_t* const iter, ccv_cnnp_dataframe_data_item_t* const cached_data, const int idx, const int max_to_prefetch, ccv_nnc_stream_context_t* const stream_context)\n{\n\tccv_cnnp_dataframe_t* const dataframe = iter->dataframe;\n\tassert(dataframe);\n\tconst int column_size = dataframe->column_size + (dataframe->derived_column_data ? dataframe->derived_column_data->rnum : 0);\n\tassert(iter->prefetches);\n\tconst int lines = iter->prefetches->rnum / column_size;\n\tint i, j;\n\t// Reset\n\tfor (i = 0; i < column_size; i++)\n\t\tfor (j = 0; j < max_to_prefetch; j++)\n\t\t{\n\t\t\tcached_data[j + i * lines].flag = 0;\n\t\t\tcached_data[j + i * lines].data = 0;\n\t\t\tcached_data[j + i * lines].ctx = 0;\n\t\t}\n\tif (iter->fetched_size < max_to_prefetch)\n\t{\n\t\titer->fetched_data = ccrealloc(iter->fetched_data, sizeof(void*) * max_to_prefetch * (column_size + 1));\n\t\titer->fetched_size = max_to_prefetch;\n\t}\n\tif (dataframe->shuffled_idx)\n\t\tfor (i = 0; i < iter->column_idx_size; i++)\n\t\t\t_ccv_cnnp_dataframe_column_data(dataframe, iter, cached_data, FETCHED_DATA(iter, iter->column_idxs[i]), dataframe->shuffled_idx + idx, max_to_prefetch, iter->column_idxs[i], lines, stream_context);\n\telse {\n\t\tfor (i = 0; i < max_to_prefetch; i++)\n\t\t\tINDEX_DATA(iter)[i] = idx + i;\n\t\tfor (i = 0; i < iter->column_idx_size; i++)\n\t\t\t_ccv_cnnp_dataframe_column_data(dataframe, iter, cached_data, FETCHED_DATA(iter, iter->column_idxs[i]), INDEX_DATA(iter), max_to_prefetch, iter->column_idxs[i], lines, stream_context);\n\t}\n}\n\nint ccv_cnnp_dataframe_iter_prefetch(ccv_cnnp_dataframe_iter_t* const iter, const int prefetch_count, ccv_nnc_stream_context_t* const stream_context)\n{\n\tccv_cnnp_dataframe_t* const dataframe = iter->dataframe;\n\tassert(dataframe);\n\tconst int column_size = dataframe->column_size + (dataframe->derived_column_data ? dataframe->derived_column_data->rnum : 0);\n\tint i, j;\n\tassert(iter->idx <= dataframe->row_count);\n\tint lines, next, max_to_prefetch;\n\tif (iter->prefetch_tail == -1)\n\t{\n\t\tif (iter->idx == dataframe->row_count)\n\t\t\treturn -1; // Cannot be done.\n\t\tmax_to_prefetch = ccv_min(dataframe->row_count - iter->idx, prefetch_count);\n\t\tif (!iter->prefetches)\n\t\t{\n\t\t\titer->prefetches = ccv_array_new(sizeof(ccv_cnnp_dataframe_data_item_t), max_to_prefetch * column_size, 0);\n\t\t\tccv_array_resize(iter->prefetches, max_to_prefetch * column_size);\n\t\t}\n\t\titer->prefetch_tail = iter->prefetch_head = 0; // Advance!\n\t\tnext = iter->idx;\n\t\tlines = iter->prefetches->rnum / column_size;\n\t\t// Reset to enough space.\n\t\tif (lines < max_to_prefetch)\n\t\t{\n\t\t\tccv_array_resize(iter->prefetches, max_to_prefetch * column_size);\n\t\t\tlines = max_to_prefetch;\n\t\t}\n\t} else {\n\t\tassert(iter->prefetches);\n\t\tccv_array_t* const prefetches = iter->prefetches;\n\t\tassert(prefetches->rnum % column_size == 0);\n\t\tlines = prefetches->rnum / column_size;\n\t\tconst int prefetched = iter->prefetch_tail >= iter->prefetch_head ? iter->prefetch_tail - iter->prefetch_head + 1: lines - iter->prefetch_head + iter->prefetch_tail + 1;\n\t\tif (iter->idx + prefetched == dataframe->row_count) // Nothing to prefetch.\n\t\t\treturn -1;\n\t\tmax_to_prefetch = ccv_min(dataframe->row_count - (iter->idx + prefetched), prefetch_count);\n\t\t// Not enough space, need to resize.\n\t\tif (prefetched + max_to_prefetch > lines)\n\t\t{\n\t\t\tconst int new_lines = prefetched + max_to_prefetch;\n\t\t\tccv_array_resize(prefetches, new_lines * column_size);\n\t\t\t// These are overlap moves, have to make sure start from the end and move it up to the beginning.\n\t\t\tif (iter->prefetch_head > iter->prefetch_tail)\n\t\t\t{\n\t\t\t\tconst int offset = new_lines - lines;\n\t\t\t\tfor (i = column_size - 1; i >= 0; i--)\n\t\t\t\t{\n\t\t\t\t\tfor (j = lines - 1; j >= iter->prefetch_head; j--)\n\t\t\t\t\t\t*(ccv_cnnp_dataframe_data_item_t*)ccv_array_get(prefetches, j + offset + i * new_lines) = *(ccv_cnnp_dataframe_data_item_t*)ccv_array_get(prefetches, j + i * lines);\n\t\t\t\t\tfor (j = iter->prefetch_tail; j >= 0; j--)\n\t\t\t\t\t\t*(ccv_cnnp_dataframe_data_item_t*)ccv_array_get(prefetches, j + i * new_lines) = *(ccv_cnnp_dataframe_data_item_t*)ccv_array_get(prefetches, j + i * lines);\n\t\t\t\t}\n\t\t\t\titer->prefetch_head += offset;\n\t\t\t} else {\n\t\t\t\tfor (i = column_size - 1; i >= 0; i--)\n\t\t\t\t\tfor (j = iter->prefetch_tail; j >= iter->prefetch_head; j--)\n\t\t\t\t\t\t*(ccv_cnnp_dataframe_data_item_t*)ccv_array_get(prefetches, j + i * new_lines) = *(ccv_cnnp_dataframe_data_item_t*)ccv_array_get(prefetches, j + i * lines);\n\t\t\t}\n\t\t\tlines = new_lines;\n\t\t}\n\t\t++iter->prefetch_tail; // Move to the next ready tail.\n\t\tif (iter->prefetch_tail >= lines)\n\t\t\titer->prefetch_tail = 0;\n\t\tnext = iter->idx + prefetched;\n\t}\n\tccv_array_t* const prefetches = iter->prefetches;\n\tccv_cnnp_dataframe_data_item_t* const cached_data = (ccv_cnnp_dataframe_data_item_t*)ccv_array_get(prefetches, iter->prefetch_tail);\n\t// If the tail is before the head, we must have enough space for the max_to_prefetch\n\tif (iter->prefetch_tail < iter->prefetch_head)\n\t{\n\t\tassert(iter->prefetch_tail + max_to_prefetch - 1 < iter->prefetch_head);\n\t\t_ccv_cnnp_prefetch_cached_data(iter, cached_data, next, max_to_prefetch, stream_context);\n\t\titer->prefetch_tail += max_to_prefetch - 1;\n\t} else {\n\t\t// First, fetch to the end.\n\t\tconst int fetch_to_end = ccv_min(max_to_prefetch, lines - iter->prefetch_tail);\n\t\t_ccv_cnnp_prefetch_cached_data(iter, cached_data, next, fetch_to_end, stream_context);\n\t\tif (fetch_to_end == max_to_prefetch)\n\t\t\titer->prefetch_tail += fetch_to_end - 1;\n\t\telse {\n\t\t\t// Need to fetch more.\n\t\t\tccv_cnnp_dataframe_data_item_t* const more_data = (ccv_cnnp_dataframe_data_item_t*)ccv_array_get(prefetches, 0);\n\t\t\tassert(max_to_prefetch > fetch_to_end);\n\t\t\t_ccv_cnnp_prefetch_cached_data(iter, more_data, next + fetch_to_end, max_to_prefetch - fetch_to_end, stream_context);\n\t\t\titer->prefetch_tail = max_to_prefetch - fetch_to_end - 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\nint ccv_cnnp_dataframe_iter_set_cursor(ccv_cnnp_dataframe_iter_t* const iter, const int idx)\n{\n\tccv_cnnp_dataframe_t* const dataframe = iter->dataframe;\n\tassert(dataframe);\n\tif (idx >= dataframe->row_count)\n\t\treturn -1;\n\tif (idx == iter->idx)\n\t\treturn 0;\n\titer->idx = idx;\n\t_ccv_cnnp_null_prefetches(iter);\n\treturn 0;\n}\n\nvoid ccv_cnnp_dataframe_iter_free(ccv_cnnp_dataframe_iter_t* const iter)\n{\n\tccv_cnnp_dataframe_t* const dataframe = iter->dataframe;\n\tconst int column_size = dataframe->column_size + (dataframe->derived_column_data ? dataframe->derived_column_data->rnum : 0);\n\tint i;\n\t// Push existing data back to reusable state (note, these may not be reused immediately because they may be on a different stream context).\n\tfor (i = 0; i < column_size; i++)\n\t\tif (iter->cached_data[i].flag)\n\t\t\t_ccv_cnnp_dataframe_enqueue_data(dataframe, iter->cached_data[i].data, i, iter->cached_data[i].ctx);\n\t// Push prefetches back to reusable state.\n\t_ccv_cnnp_null_prefetches(iter);\n\tif (iter->prefetches)\n\t\tccv_array_free(iter->prefetches);\n\tif (iter->derived_data)\n\t{\n\t\tassert(dataframe->derived_column_data);\n\t\tfor (i = 0; i < dataframe->derived_column_data->rnum; i++)\n\t\t\tif (iter->derived_data[i])\n\t\t\t\tccfree(iter->derived_data[i]);\n\t\tccfree(iter->derived_data);\n\t}\n\tccfree(iter->fetched_data);\n\tif (iter->column_ctx)\n\t{\n\t\tkhash_t(iter_ctx)* const column_ctx = iter->column_ctx;\n\t\tkhiter_t k;\n\t\tfor (k = kh_begin(column_ctx); k != kh_end(column_ctx); ++k)\n\t\t{\n\t\t\tif (!kh_exist(column_ctx, k))\n\t\t\t\tcontinue;\n\t\t\tccv_cnnp_dataframe_column_ctx_t* const ctx = kh_val(column_ctx, k);\n\t\t\tfor (i = 0; i < column_size; i++)\n\t\t\t{\n\t\t\t\tif (ctx[i].stream_context)\n\t\t\t\t\tccv_nnc_stream_context_free(ctx[i].stream_context);\n\t\t\t\tif (ctx[i].signal)\n\t\t\t\t\tccv_nnc_stream_signal_free(ctx[i].signal);\n\t\t\t}\n\t\t}\n\t\tkh_destroy(iter_ctx, column_ctx);\n\t}\n\tccfree(iter);\n}\n\nvoid ccv_cnnp_dataframe_free(ccv_cnnp_dataframe_t* const dataframe)\n{\n\tint i, j;\n\tkhash_t(ctx)* const data_ctx = dataframe->data_ctx;\n\tkhiter_t k;\n\tconst int column_size = dataframe->column_size + (dataframe->derived_column_data ? dataframe->derived_column_data->rnum : 0);\n\tfor (k = kh_begin(data_ctx); k != kh_end(data_ctx); ++k)\n\t{\n\t\tif (!kh_exist(data_ctx, k))\n\t\t\tcontinue;\n\t\tccv_array_t* const columns = kh_val(data_ctx, k);\n\t\tassert(columns->rnum <= column_size);\n\t\tfor (i = 0; i < columns->rnum; i++)\n\t\t{\n\t\t\tccv_array_t* const column = *(ccv_array_t**)ccv_array_get(columns, i);\n\t\t\tvoid* context;\n\t\t\tccv_cnnp_column_data_deinit_f data_deinit;\n\t\t\tif (i < dataframe->column_size)\n\t\t\t{\n\t\t\t\tdata_deinit = dataframe->column_data[i].data_deinit;\n\t\t\t\tcontext = dataframe->column_data[i].context;\n\t\t\t} else {\n\t\t\t\tassert(dataframe->derived_column_data);\n\t\t\t\tccv_cnnp_derived_column_data_t* const derived_column_data = (ccv_cnnp_derived_column_data_t*)ccv_array_get(dataframe->derived_column_data, i - dataframe->column_size);\n\t\t\t\tdata_deinit = derived_column_data->data_deinit;\n\t\t\t\tcontext = derived_column_data->context;\n\t\t\t}\n\t\t\tif (data_deinit)\n\t\t\t\tfor (j = 0; j < column->rnum; j++)\n\t\t\t\t\tdata_deinit(*(void**)ccv_array_get(column, j), context);\n\t\t\tccv_array_free(column);\n\t\t}\n\t\tccv_array_free(columns);\n\t}\n\tkh_destroy(ctx, data_ctx);\n\tif (dataframe->derived_column_data)\n\t{\n\t\tfor (i = 0; i < dataframe->derived_column_data->rnum; i++)\n\t\t{\n\t\t\tccv_cnnp_derived_column_data_t* const derived_column_data = (ccv_cnnp_derived_column_data_t*)ccv_array_get(dataframe->derived_column_data, i);\n\t\t\tif (derived_column_data->context_deinit)\n\t\t\t\tderived_column_data->context_deinit(derived_column_data->context);\n\t\t\tccfree(derived_column_data->column_idxs);\n\t\t}\n\t\tccv_array_free(dataframe->derived_column_data);\n\t}\n\tfor (i = 0; i < dataframe->column_size; i++)\n\t\tif (dataframe->column_data[i].context_deinit)\n\t\t\tdataframe->column_data[i].context_deinit(dataframe->column_data[i].context);\n\tif (dataframe->shuffled_idx)\n\t\tccfree(dataframe->shuffled_idx);\n#ifdef HAVE_GSL\n\tif (dataframe->rng)\n\t\tgsl_rng_free(dataframe->rng);\n#endif\n\tccfree(dataframe);\n}\n", "meta": {"hexsha": "124e8d44eab6b54337b7ee813d7f479b876d5e5a", "size": 27226, "ext": "c", "lang": "C", "max_stars_repo_path": "lib/nnc/ccv_cnnp_dataframe.c", "max_stars_repo_name": "xiaoye77/ccv", "max_stars_repo_head_hexsha": "655cb2c4a95694a69b81eab5ccb823dbcaa805e4", "max_stars_repo_licenses": ["CC0-1.0", "CC-BY-4.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-26T11:40:31.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-26T11:40:31.000Z", "max_issues_repo_path": "lib/nnc/ccv_cnnp_dataframe.c", "max_issues_repo_name": "lyp365859350/ccv", "max_issues_repo_head_hexsha": "cf86aacc6a59fcc4f3e203eb3889a89c5e8f5c66", "max_issues_repo_licenses": ["CC0-1.0", "CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/nnc/ccv_cnnp_dataframe.c", "max_forks_repo_name": "lyp365859350/ccv", "max_forks_repo_head_hexsha": "cf86aacc6a59fcc4f3e203eb3889a89c5e8f5c66", "max_forks_repo_licenses": ["CC0-1.0", "CC-BY-4.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-18T15:50:49.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-18T15:50:49.000Z", "avg_line_length": 42.9432176656, "max_line_length": 339, "alphanum_fraction": 0.7487695585, "num_tokens": 7680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121585956185, "lm_q2_score": 0.020964242614952146, "lm_q1q2_score": 0.008069391878243484}}
{"text": "/* matrix/gsl_matrix_double.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_MATRIX_DOUBLE_H__\n#define __GSL_MATRIX_DOUBLE_H__\n\n#if !defined( GSL_FUN )\n#  if !defined( GSL_DLL )\n#    define GSL_FUN extern\n#  elif defined( BUILD_GSL_DLL )\n#    define GSL_FUN extern __declspec(dllexport)\n#  else\n#    define GSL_FUN extern __declspec(dllimport)\n#  endif\n#endif\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_inline.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_vector_double.h>\n#include <gsl/gsl_blas_types.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size1;\n  size_t size2;\n  size_t tda;\n  double * data;\n  gsl_block * block;\n  int owner;\n} gsl_matrix;\n\ntypedef struct\n{\n  gsl_matrix matrix;\n} _gsl_matrix_view;\n\ntypedef _gsl_matrix_view gsl_matrix_view;\n\ntypedef struct\n{\n  gsl_matrix matrix;\n} _gsl_matrix_const_view;\n\ntypedef const _gsl_matrix_const_view gsl_matrix_const_view;\n\n/* Allocation */\n\nGSL_FUN gsl_matrix * \ngsl_matrix_alloc (const size_t n1, const size_t n2);\n\nGSL_FUN gsl_matrix * \ngsl_matrix_calloc (const size_t n1, const size_t n2);\n\nGSL_FUN gsl_matrix * \ngsl_matrix_alloc_from_block (gsl_block * b, \n                                   const size_t offset, \n                                   const size_t n1, \n                                   const size_t n2, \n                                   const size_t d2);\n\nGSL_FUN gsl_matrix * \ngsl_matrix_alloc_from_matrix (gsl_matrix * m,\n                                    const size_t k1, \n                                    const size_t k2,\n                                    const size_t n1, \n                                    const size_t n2);\n\nGSL_FUN gsl_vector * \ngsl_vector_alloc_row_from_matrix (gsl_matrix * m,\n                                        const size_t i);\n\nGSL_FUN gsl_vector * \ngsl_vector_alloc_col_from_matrix (gsl_matrix * m,\n                                        const size_t j);\n\nGSL_FUN void gsl_matrix_free (gsl_matrix * m);\n\n/* Views */\n\nGSL_FUN _gsl_matrix_view \ngsl_matrix_submatrix (gsl_matrix * m, \n                            const size_t i, const size_t j, \n                            const size_t n1, const size_t n2);\n\nGSL_FUN _gsl_vector_view \ngsl_matrix_row (gsl_matrix * m, const size_t i);\n\nGSL_FUN _gsl_vector_view \ngsl_matrix_column (gsl_matrix * m, const size_t j);\n\nGSL_FUN _gsl_vector_view \ngsl_matrix_diagonal (gsl_matrix * m);\n\nGSL_FUN _gsl_vector_view \ngsl_matrix_subdiagonal (gsl_matrix * m, const size_t k);\n\nGSL_FUN _gsl_vector_view \ngsl_matrix_superdiagonal (gsl_matrix * m, const size_t k);\n\nGSL_FUN _gsl_vector_view\ngsl_matrix_subrow (gsl_matrix * m, const size_t i,\n                         const size_t offset, const size_t n);\n\nGSL_FUN _gsl_vector_view\ngsl_matrix_subcolumn (gsl_matrix * m, const size_t j,\n                            const size_t offset, const size_t n);\n\nGSL_FUN _gsl_matrix_view\ngsl_matrix_view_array (double * base,\n                             const size_t n1, \n                             const size_t n2);\n\nGSL_FUN _gsl_matrix_view\ngsl_matrix_view_array_with_tda (double * base, \n                                      const size_t n1, \n                                      const size_t n2,\n                                      const size_t tda);\n\n\nGSL_FUN _gsl_matrix_view\ngsl_matrix_view_vector (gsl_vector * v,\n                              const size_t n1, \n                              const size_t n2);\n\nGSL_FUN _gsl_matrix_view\ngsl_matrix_view_vector_with_tda (gsl_vector * v,\n                                       const size_t n1, \n                                       const size_t n2,\n                                       const size_t tda);\n\n\nGSL_FUN _gsl_matrix_const_view \ngsl_matrix_const_submatrix (const gsl_matrix * m, \n                                  const size_t i, const size_t j, \n                                  const size_t n1, const size_t n2);\n\nGSL_FUN _gsl_vector_const_view \ngsl_matrix_const_row (const gsl_matrix * m, \n                            const size_t i);\n\nGSL_FUN _gsl_vector_const_view \ngsl_matrix_const_column (const gsl_matrix * m, \n                               const size_t j);\n\nGSL_FUN _gsl_vector_const_view\ngsl_matrix_const_diagonal (const gsl_matrix * m);\n\nGSL_FUN _gsl_vector_const_view \ngsl_matrix_const_subdiagonal (const gsl_matrix * m, \n                                    const size_t k);\n\nGSL_FUN _gsl_vector_const_view \ngsl_matrix_const_superdiagonal (const gsl_matrix * m, \n                                      const size_t k);\n\nGSL_FUN _gsl_vector_const_view\ngsl_matrix_const_subrow (const gsl_matrix * m, const size_t i,\n                               const size_t offset, const size_t n);\n\nGSL_FUN _gsl_vector_const_view\ngsl_matrix_const_subcolumn (const gsl_matrix * m, const size_t j,\n                                  const size_t offset, const size_t n);\n\nGSL_FUN _gsl_matrix_const_view\ngsl_matrix_const_view_array (const double * base,\n                                   const size_t n1, \n                                   const size_t n2);\n\nGSL_FUN _gsl_matrix_const_view\ngsl_matrix_const_view_array_with_tda (const double * base, \n                                            const size_t n1, \n                                            const size_t n2,\n                                            const size_t tda);\n\nGSL_FUN _gsl_matrix_const_view\ngsl_matrix_const_view_vector (const gsl_vector * v,\n                                    const size_t n1, \n                                    const size_t n2);\n\nGSL_FUN _gsl_matrix_const_view\ngsl_matrix_const_view_vector_with_tda (const gsl_vector * v,\n                                             const size_t n1, \n                                             const size_t n2,\n                                             const size_t tda);\n\n/* Operations */\n\nGSL_FUN void gsl_matrix_set_zero (gsl_matrix * m);\nGSL_FUN void gsl_matrix_set_identity (gsl_matrix * m);\nGSL_FUN void gsl_matrix_set_all (gsl_matrix * m, double x);\n\nGSL_FUN int gsl_matrix_fread (FILE * stream, gsl_matrix * m) ;\nGSL_FUN int gsl_matrix_fwrite (FILE * stream, const gsl_matrix * m) ;\nGSL_FUN int gsl_matrix_fscanf (FILE * stream, gsl_matrix * m);\nGSL_FUN int gsl_matrix_fprintf (FILE * stream, const gsl_matrix * m, const char * format);\n \nGSL_FUN int gsl_matrix_memcpy(gsl_matrix * dest, const gsl_matrix * src);\nGSL_FUN int gsl_matrix_swap(gsl_matrix * m1, gsl_matrix * m2);\nGSL_FUN int gsl_matrix_tricpy(CBLAS_UPLO_t Uplo, CBLAS_DIAG_t Diag, gsl_matrix * dest, const gsl_matrix * src);\n\nGSL_FUN int gsl_matrix_swap_rows(gsl_matrix * m, const size_t i, const size_t j);\nGSL_FUN int gsl_matrix_swap_columns(gsl_matrix * m, const size_t i, const size_t j);\nGSL_FUN int gsl_matrix_swap_rowcol(gsl_matrix * m, const size_t i, const size_t j);\nGSL_FUN int gsl_matrix_transpose (gsl_matrix * m);\nGSL_FUN int gsl_matrix_transpose_memcpy (gsl_matrix * dest, const gsl_matrix * src);\nGSL_FUN int gsl_matrix_transpose_tricpy (CBLAS_UPLO_t Uplo_src, CBLAS_DIAG_t Diag, gsl_matrix * dest, const gsl_matrix * src);\n\nGSL_FUN double gsl_matrix_max (const gsl_matrix * m);\nGSL_FUN double gsl_matrix_min (const gsl_matrix * m);\nGSL_FUN void gsl_matrix_minmax (const gsl_matrix * m, double * min_out, double * max_out);\n\nGSL_FUN void gsl_matrix_max_index (const gsl_matrix * m, size_t * imax, size_t *jmax);\nGSL_FUN void gsl_matrix_min_index (const gsl_matrix * m, size_t * imin, size_t *jmin);\nGSL_FUN void gsl_matrix_minmax_index (const gsl_matrix * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);\n\nGSL_FUN int gsl_matrix_equal (const gsl_matrix * a, const gsl_matrix * b);\n\nGSL_FUN int gsl_matrix_isnull (const gsl_matrix * m);\nGSL_FUN int gsl_matrix_ispos (const gsl_matrix * m);\nGSL_FUN int gsl_matrix_isneg (const gsl_matrix * m);\nGSL_FUN int gsl_matrix_isnonneg (const gsl_matrix * m);\n\nGSL_FUN int gsl_matrix_add (gsl_matrix * a, const gsl_matrix * b);\nGSL_FUN int gsl_matrix_sub (gsl_matrix * a, const gsl_matrix * b);\nGSL_FUN int gsl_matrix_mul_elements (gsl_matrix * a, const gsl_matrix * b);\nGSL_FUN int gsl_matrix_div_elements (gsl_matrix * a, const gsl_matrix * b);\nGSL_FUN int gsl_matrix_scale (gsl_matrix * a, const double x);\nGSL_FUN int gsl_matrix_scale_rows (gsl_matrix * a, const gsl_vector * x);\nGSL_FUN int gsl_matrix_scale_columns (gsl_matrix * a, const gsl_vector * x);\nGSL_FUN int gsl_matrix_add_constant (gsl_matrix * a, const double x);\nGSL_FUN int gsl_matrix_add_diagonal (gsl_matrix * a, const double x);\n\n/***********************************************************************/\n/* The functions below are obsolete                                    */\n/***********************************************************************/\nGSL_FUN int gsl_matrix_get_row(gsl_vector * v, const gsl_matrix * m, const size_t i);\nGSL_FUN int gsl_matrix_get_col(gsl_vector * v, const gsl_matrix * m, const size_t j);\nGSL_FUN int gsl_matrix_set_row(gsl_matrix * m, const size_t i, const gsl_vector * v);\nGSL_FUN int gsl_matrix_set_col(gsl_matrix * m, const size_t j, const gsl_vector * v);\n/***********************************************************************/\n\n/* inline functions if you are using GCC */\n\nGSL_FUN INLINE_DECL double   gsl_matrix_get(const gsl_matrix * m, const size_t i, const size_t j);\nGSL_FUN INLINE_DECL void    gsl_matrix_set(gsl_matrix * m, const size_t i, const size_t j, const double x);\nGSL_FUN INLINE_DECL double * gsl_matrix_ptr(gsl_matrix * m, const size_t i, const size_t j);\nGSL_FUN INLINE_DECL const double * gsl_matrix_const_ptr(const gsl_matrix * m, const size_t i, const size_t j);\n\n#ifdef HAVE_INLINE\nINLINE_FUN \ndouble\ngsl_matrix_get(const gsl_matrix * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_VAL(\"first index out of range\", GSL_EINVAL, 0) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_VAL(\"second index out of range\", GSL_EINVAL, 0) ;\n        }\n    }\n#endif\n  return m->data[i * m->tda + j] ;\n} \n\nINLINE_FUN \nvoid\ngsl_matrix_set(gsl_matrix * m, const size_t i, const size_t j, const double x)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_VOID(\"first index out of range\", GSL_EINVAL) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_VOID(\"second index out of range\", GSL_EINVAL) ;\n        }\n    }\n#endif\n  m->data[i * m->tda + j] = x ;\n}\n\nINLINE_FUN \ndouble *\ngsl_matrix_ptr(gsl_matrix * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n        }\n    }\n#endif\n  return (double *) (m->data + (i * m->tda + j)) ;\n} \n\nINLINE_FUN \nconst double *\ngsl_matrix_const_ptr(const gsl_matrix * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n        }\n    }\n#endif\n  return (const double *) (m->data + (i * m->tda + j)) ;\n} \n\n#endif\n\n__END_DECLS\n\n#endif /* __GSL_MATRIX_DOUBLE_H__ */\n", "meta": {"hexsha": "7205c9e19d888958d1438d530cfd42a327811045", "size": 12359, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gsl/gsl_matrix_double.h", "max_stars_repo_name": "zhanghe9704/jspec2", "max_stars_repo_head_hexsha": "0073e0515b87610b7f88ad2b07fc7d23618c159a", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-28T08:20:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-28T08:20:20.000Z", "max_issues_repo_path": "include/gsl/gsl_matrix_double.h", "max_issues_repo_name": "zhanghe9704/jspec2", "max_issues_repo_head_hexsha": "0073e0515b87610b7f88ad2b07fc7d23618c159a", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gsl/gsl_matrix_double.h", "max_forks_repo_name": "zhanghe9704/jspec2", "max_forks_repo_head_hexsha": "0073e0515b87610b7f88ad2b07fc7d23618c159a", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-14T12:45:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-14T12:45:35.000Z", "avg_line_length": 33.7677595628, "max_line_length": 126, "alphanum_fraction": 0.6384820778, "num_tokens": 3131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2877678157610531, "lm_q2_score": 0.028007523546992777, "lm_q1q2_score": 0.008059663875994374}}
{"text": "/**\n */\n#ifndef _DRZ2PET_UTILS_H\n#define _DRZ2PET_UTILS_H\n\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include \"aXe_grism.h\"\n#include <math.h>\n#include <string.h>\n\nap_pixel *\nmake_spc_drztable(observation * const obs, observation * const wobs,\n                  const object *ob, const double lambda0,\n                  const double dlambda);\n\nextern char *\nget_ID_num(char *grism_image,char *extname);\n\nextern void\nnormalize_weight(observation * wobs, object *ob,\n                 const int opt_extr);\n\nextern gsl_matrix *\ncomp_equ_weight(gsl_matrix *exp_map, const object *ob);\n\ngsl_matrix *\ncomp_exp_weight(gsl_matrix *exp_map, const object *ob);\n\ngsl_matrix *\ncomp_opt_weight(gsl_matrix *mod_map,\n                gsl_matrix *var_map, const object *ob);\n#endif /* !_DRZ2PET_UTILS_H */\n", "meta": {"hexsha": "6d5f6d417eb99a3b4d4c9ccd5cb7278842b0e6b8", "size": 801, "ext": "h", "lang": "C", "max_stars_repo_path": "cextern/src/drz2pet_utils.h", "max_stars_repo_name": "sosey/pyaxe", "max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cextern/src/drz2pet_utils.h", "max_issues_repo_name": "sosey/pyaxe", "max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cextern/src/drz2pet_utils.h", "max_forks_repo_name": "sosey/pyaxe", "max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5588235294, "max_line_length": 68, "alphanum_fraction": 0.7016229713, "num_tokens": 207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4339814648038986, "lm_q2_score": 0.0185465635627783, "lm_q1q2_score": 0.00804886482205314}}
{"text": "#pragma once\n\n#include <algorithm>\n#include <cstddef>\n#include <cstdint>\n#include <tuple>\n#include <type_traits>\n\n#include <gsl/gsl>\n\n#include \"chainerx/array.h\"\n#include \"chainerx/axes.h\"\n#include \"chainerx/backend_util.h\"\n#include \"chainerx/constant.h\"\n#include \"chainerx/dtype.h\"\n#include \"chainerx/indexer.h\"\n#include \"chainerx/macro.h\"\n#include \"chainerx/shape.h\"\n#include \"chainerx/strides.h\"\n\nnamespace chainerx {\nnamespace indexable_array_detail {\n\ntemplate <typename To, typename From>\nusing WithConstnessOf = dtype_detail::WithConstnessOf<To, From>;\n\nstatic inline std::tuple<const uint8_t*, const uint8_t*> GetDataRange(const Array& a) {\n    std::tuple<int64_t, int64_t> range = chainerx::GetDataRange(a.shape(), a.strides(), a.GetItemSize());\n    int64_t lower = std::get<0>(range);\n    int64_t upper = std::get<1>(range);\n    const uint8_t* base = static_cast<const uint8_t*>(internal::GetRawOffsetData(a));\n    return std::tuple<const uint8_t*, const uint8_t*>{base + lower, base + upper};\n}\n\n}  // namespace indexable_array_detail\n\ntemplate <typename T, int8_t kNdim = kDynamicNdim>\nclass IndexableArray {\npublic:\n    using ElementType = T;\n\nprivate:\n    template <typename U>\n    using WithConstnessOfT = indexable_array_detail::WithConstnessOf<U, T>;\n    using VoidType = WithConstnessOfT<void>;\n    using DeviceStorageType = TypeToDeviceStorageType<T>;\n\npublic:\n    IndexableArray(VoidType* data, const Strides& strides) : data_{data} { std::copy(strides.begin(), strides.end(), strides_); }\n\n    IndexableArray(const Array& array, const Strides& strides) : IndexableArray{internal::GetRawOffsetData(array), strides} {\n        CHAINERX_ASSERT(TypeToDtype<T> == array.dtype());\n\n#if CHAINERX_DEBUG\n        std::tie(first_, last_) = indexable_array_detail::GetDataRange(array);\n#endif  // CHAINERX_DEBUG\n    }\n\n    explicit IndexableArray(const Array& array) : IndexableArray{array, array.strides()} {}\n\n    CHAINERX_HOST_DEVICE int8_t ndim() const { return kNdim; }\n\n    CHAINERX_HOST_DEVICE const int64_t* strides() const { return strides_; }\n\n    CHAINERX_HOST_DEVICE VoidType* data() const { return data_; }\n\n    CHAINERX_HOST_DEVICE DeviceStorageType& operator[](const int64_t* index) const {\n        auto data_ptr = static_cast<WithConstnessOfT<uint8_t>*>(data_);\n        for (int8_t dim = 0; dim < kNdim; ++dim) {\n            data_ptr += strides_[dim] * index[dim];\n        }\n#if CHAINERX_DEBUG\n        CHAINERX_ASSERT(first_ == nullptr || first_ <= data_ptr);\n        CHAINERX_ASSERT(last_ == nullptr || data_ptr <= last_ - sizeof(T));\n#endif  // CHAINERX_DEBUG\n        return *static_cast<DeviceStorageType*>(static_cast<VoidType*>(data_ptr));\n    }\n\n    CHAINERX_HOST_DEVICE WithConstnessOfT<DeviceStorageType>& operator[](const IndexIterator<kNdim>& it) const {\n        return operator[](it.index());\n    }\n\n    // Permutes the axes.\n    //\n    // It is the caller's responsibility to ensure validity of permutation.\n    // If the permutation is invalid, the behavior is undefined.\n    IndexableArray<T, kNdim>& Permute(const Axes& axes) {\n        CHAINERX_ASSERT(axes.size() == static_cast<size_t>(kNdim));\n        int64_t c[kNdim]{};\n        std::copy(std::begin(strides_), std::end(strides_), c);\n        for (size_t i = 0; i < kNdim; ++i) {\n            strides_[i] = c[axes[i]];\n        }\n        return *this;\n    }\n\nprivate:\n    WithConstnessOfT<void>* data_;\n#if CHAINERX_DEBUG\n    const uint8_t* first_{nullptr};\n    const uint8_t* last_{nullptr};\n#endif  // CHAINERX_DEBUG\n    int64_t strides_[kNdim];\n};\n\n// Static 0-dimensional specialization.\ntemplate <typename T>\nclass IndexableArray<T, 0> {\npublic:\n    using ElementType = T;\n\nprivate:\n    template <typename U>\n    using WithConstnessOfT = indexable_array_detail::WithConstnessOf<U, T>;\n    using VoidType = WithConstnessOfT<void>;\n    using DeviceStorageType = TypeToDeviceStorageType<T>;\n\npublic:\n    IndexableArray(VoidType* data, const Strides& strides) : data_{data} { CHAINERX_ASSERT(0 == strides.ndim()); }\n\n    IndexableArray(const Array& array, const Strides& strides) : IndexableArray{internal::GetRawOffsetData(array), strides} {\n        CHAINERX_ASSERT(TypeToDtype<T> == array.dtype());\n    }\n\n    explicit IndexableArray(const Array& array) : IndexableArray{array, array.strides()} {}\n\n    CHAINERX_HOST_DEVICE constexpr int8_t ndim() const { return 0; }\n\n    CHAINERX_HOST_DEVICE constexpr const int64_t* strides() const { return nullptr; }\n\n    CHAINERX_HOST_DEVICE VoidType* data() const { return data_; }\n\n    CHAINERX_HOST_DEVICE DeviceStorageType& operator[](const int64_t* index) const {\n        CHAINERX_ASSERT(index == nullptr || index[0] == 0);\n        return *static_cast<WithConstnessOfT<DeviceStorageType>*>(data_);\n    }\n\n    CHAINERX_HOST_DEVICE DeviceStorageType& operator[](const IndexIterator<0>& it) const { return operator[](it.index()); }\n\n    IndexableArray<T, 0>& Permute(const Axes& /*axes*/) {\n        // NOOP for 1-dimensional array.\n        return *this;\n    }\n\nprivate:\n    WithConstnessOfT<void>* data_;\n};\n\n// Static 1-dimensional specialization.\ntemplate <typename T>\nclass IndexableArray<T, 1> {\npublic:\n    using ElementType = T;\n\nprivate:\n    template <typename U>\n    using WithConstnessOfT = indexable_array_detail::WithConstnessOf<U, T>;\n    using VoidType = WithConstnessOfT<void>;\n    using DeviceStorageType = TypeToDeviceStorageType<T>;\n\npublic:\n    IndexableArray(VoidType* data, const Strides& strides) : data_{data}, stride_{strides[0]} { CHAINERX_ASSERT(1 == strides.ndim()); }\n\n    IndexableArray(const Array& array, const Strides& strides) : IndexableArray{internal::GetRawOffsetData(array), strides} {\n        CHAINERX_ASSERT(TypeToDtype<T> == array.dtype());\n\n#if CHAINERX_DEBUG\n        std::tie(first_, last_) = indexable_array_detail::GetDataRange(array);\n#endif  // CHAINERX_DEBUG\n    }\n\n    explicit IndexableArray(const Array& array) : IndexableArray{array, array.strides()} {}\n\n    CHAINERX_HOST_DEVICE constexpr int8_t ndim() const { return 1; }\n\n    CHAINERX_HOST_DEVICE const int64_t* strides() const { return &stride_; }\n\n    CHAINERX_HOST_DEVICE VoidType* data() const { return data_; }\n\n    CHAINERX_HOST_DEVICE DeviceStorageType& operator[](const int64_t* index) const {\n        auto data_ptr = reinterpret_cast<WithConstnessOfT<uint8_t>*>(data_) +\n                        stride_ * index[0];  // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast)\n#if CHAINERX_DEBUG\n        CHAINERX_ASSERT(first_ == nullptr || first_ <= data_ptr);\n        CHAINERX_ASSERT(last_ == nullptr || data_ptr <= last_ - sizeof(T));\n#endif  // CHAINERX_DEBUG\n        return *static_cast<DeviceStorageType*>(static_cast<VoidType*>(data_ptr));\n    }\n\n    CHAINERX_HOST_DEVICE DeviceStorageType& operator[](const IndexIterator<1>& it) const { return operator[](it.index()); }\n\n    IndexableArray<T, 1>& Permute(const Axes& /*axes*/) {\n        // NOOP for 1-dimensional array.\n        return *this;\n    }\n\nprivate:\n    WithConstnessOfT<void>* data_;\n#if CHAINERX_DEBUG\n    const uint8_t* first_{nullptr};\n    const uint8_t* last_{nullptr};\n#endif  // CHAINERX_DEBUG\n    int64_t stride_{};\n};\n\n// Runtime determined dynamic dimension specialization.\ntemplate <typename T>\nclass IndexableArray<T, kDynamicNdim> {\npublic:\n    using ElementType = T;\n\nprivate:\n    template <typename U>\n    using WithConstnessOfT = indexable_array_detail::WithConstnessOf<U, T>;\n    using VoidType = WithConstnessOfT<void>;\n    using DeviceStorageType = TypeToDeviceStorageType<T>;\n\npublic:\n    IndexableArray(WithConstnessOfT<void>* data, const Strides& strides) : data_{data}, ndim_{strides.ndim()} {\n        std::copy(strides.begin(), strides.end(), strides_);\n    }\n\n    IndexableArray(const Array& array, const Strides& strides) : IndexableArray{internal::GetRawOffsetData(array), strides} {\n        CHAINERX_ASSERT(TypeToDtype<T> == array.dtype());\n\n#if CHAINERX_DEBUG\n        std::tie(first_, last_) = indexable_array_detail::GetDataRange(array);\n#endif  // CHAINERX_DEBUG\n    }\n\n    explicit IndexableArray(const Array& array) : IndexableArray{array, array.strides()} {}\n\n    CHAINERX_HOST_DEVICE int8_t ndim() const { return ndim_; }\n\n    CHAINERX_HOST_DEVICE const int64_t* strides() const { return strides_; }\n\n    CHAINERX_HOST_DEVICE VoidType* data() const { return data_; }\n\n    CHAINERX_HOST_DEVICE DeviceStorageType& operator[](const int64_t* index) const {\n        auto data_ptr = static_cast<WithConstnessOfT<uint8_t>*>(data_);\n        for (int8_t dim = 0; dim < ndim_; ++dim) {\n            data_ptr += strides_[dim] * index[dim];\n        }\n#if CHAINERX_DEBUG\n        CHAINERX_ASSERT(first_ == nullptr || first_ <= data_ptr);\n        CHAINERX_ASSERT(last_ == nullptr || data_ptr <= last_ - sizeof(T));\n#endif  // CHAINERX_DEBUG\n        return *static_cast<DeviceStorageType*>(static_cast<VoidType*>(data_ptr));\n    }\n\n    CHAINERX_HOST_DEVICE DeviceStorageType& operator[](const IndexIterator<kDynamicNdim>& it) const { return operator[](it.index()); }\n\n    // Permutes the axes.\n    //\n    // Given axes may be fewer than that held by the array.\n    // In that case, the axes in the array will be reduced.\n    //\n    // It is the caller's responsibility to ensure validity of permutation.\n    // If the permutation is invalid, the behavior is undefined.\n    IndexableArray<T, kDynamicNdim>& Permute(const Axes& axes) {\n        CHAINERX_ASSERT(axes.size() <= static_cast<size_t>(ndim_));\n        int64_t c[kMaxNdim]{};\n        std::copy(std::begin(strides_), std::end(strides_), c);\n        for (size_t i = 0; i < axes.size(); ++i) {\n            strides_[i] = c[axes[i]];\n        }\n        ndim_ = static_cast<int8_t>(axes.size());\n        return *this;\n    }\n\nprivate:\n    WithConstnessOfT<void>* data_;\n#if CHAINERX_DEBUG\n    const uint8_t* first_{nullptr};\n    const uint8_t* last_{nullptr};\n#endif  // CHAINERX_DEBUG\n    int64_t strides_[kMaxNdim];\n    int8_t ndim_;\n};\n\n}  // namespace chainerx\n", "meta": {"hexsha": "0ae8d6d7a0ede574363436fda0101a69dffc14a1", "size": 9938, "ext": "h", "lang": "C", "max_stars_repo_path": "chainerx_cc/chainerx/indexable_array.h", "max_stars_repo_name": "hikjik/chainer", "max_stars_repo_head_hexsha": "324a1bc1ea3edd63d225e4a87ed0a36af7fd712f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-02-14T09:18:32.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-14T09:18:32.000Z", "max_issues_repo_path": "chainerx_cc/chainerx/indexable_array.h", "max_issues_repo_name": "nolfwin/chainer", "max_issues_repo_head_hexsha": "8d776fcc1e848cb9d3800a6aab356eb91ae9d088", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-06-26T08:16:09.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-26T08:16:09.000Z", "max_forks_repo_path": "chainerx_cc/chainerx/indexable_array.h", "max_forks_repo_name": "nolfwin/chainer", "max_forks_repo_head_hexsha": "8d776fcc1e848cb9d3800a6aab356eb91ae9d088", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-05-28T22:43:34.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-28T22:43:34.000Z", "avg_line_length": 35.2411347518, "max_line_length": 135, "alphanum_fraction": 0.6925940833, "num_tokens": 2591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22541661583507672, "lm_q2_score": 0.03567854908333912, "lm_q1q2_score": 0.008042537792271983}}
{"text": "\ufeff#pragma once\n#include <Hypo/Config.h>\n#include <Hypo/System/Exports.h>\n#include <gsl/span>\n#include <Hypo/System/Streams/MemoryStream.h>\n#include <Hypo/System/Buffer/Buffer.h>\n\nnamespace Hypo\n{\n\tclass HYPO_SYSTEM_API BinaryReader\n\t{\n\tpublic:\n\t\tBinaryReader(std::istream& stream);\n\n\t\tBinaryReader& operator >>(uInt8& value);\n\t\tBinaryReader& operator >>(uInt16& value);\n\t\tBinaryReader& operator >>(uInt32& value);\n\t\tBinaryReader& operator >>(uInt64& value);\n\t\tBinaryReader& operator >>(Int8& value );\n\t\tBinaryReader& operator >>(Int16& value);\n\t\tBinaryReader& operator >>(Int32& value);\n\t\tBinaryReader& operator >>(Int64& value);\n\t\t\n\t\tBinaryReader& operator >>(std::string& value);\n\n\t\ttemplate<typename T>\n\t\tBinaryReader& operator >>(std::vector<T>& value)\n\t\t{\n\t\t\tuInt32 size = 0;\n\t\t\t*this >> size;\n\t\t\t\n\t\t\tfor (int i = 0; i < size; i++)\n\t\t\t{\n\t\t\t\tT elem;\n\t\t\t\t*this >> elem;\n\t\t\t\tvalue.push_back(elem);\n\t\t\t}\n\t\t\treturn *this;\n\t\t}\n\n\t\tstd::vector<unsigned char> ReadRaw(int size);\n\t\tvoid ReadRaw(void* buffer, int size);\n\n\t\tvoid ReadBOM();\n\n\t\tvoid Read7BitEncoded(uInt32& value);\n\t\tvoid Read7BitEncoded(uInt64& value);\n\n\t\tbool Good()const { return m_Stream.good(); }\n\t\tbool Bad()const { return m_Stream.bad(); }\n\t\tbool Fail() const { return m_Stream.fail(); }\n\t\tbool Eof() const { return m_Stream.eof(); }\n\n\t\tstd::istream& GetStream() const { return m_Stream; }\n\n\tprivate:\n\t\tstd::istream& m_Stream;\n\t};\n\n\ttemplate <typename T>\n\tclass BasicMemoryBinaryReader : public BinaryReader\n\t\t/// A convenient wrapper for using Buffer and MemoryStream with BinaryReader.\n\t{\n\tpublic:\n\t\tBasicMemoryBinaryReader(const Buffer<T>& data) :\n\t\t\tBinaryReader(_istr),\n\t\t\t_data(data),\n\t\t\t_istr(data.begin(), data.Capacity())\n\t\t{\n\t\t}\n\n\n\t\t~BasicMemoryBinaryReader()\n\t\t{\n\t\t}\n\n\t\tconst Buffer<T>& data() const\n\t\t{\n\t\t\treturn _data;\n\t\t}\n\n\t\tconst MemoryInputStream& stream() const\n\t\t{\n\t\t\treturn _istr;\n\t\t}\n\n\t\tMemoryInputStream& stream()\n\t\t{\n\t\t\treturn _istr;\n\t\t}\n\n\tprivate:\n\t\tconst Buffer<T>& _data;\n\t\tMemoryInputStream _istr;\n\t};\n\n\n\ttypedef BasicMemoryBinaryReader<char> MemoryBinaryReader;\n\n\n\n}\n\n", "meta": {"hexsha": "7d1c3a8adf687f2550618655d56d05c960174f8c", "size": 2060, "ext": "h", "lang": "C", "max_stars_repo_path": "HypoSystem/src/Hypo/System/Streams/BinaryReader.h", "max_stars_repo_name": "TheodorLindberg/Hypo", "max_stars_repo_head_hexsha": "67107bf14671711ab5979e2af8c7ead6ee043805", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HypoSystem/src/Hypo/System/Streams/BinaryReader.h", "max_issues_repo_name": "TheodorLindberg/Hypo", "max_issues_repo_head_hexsha": "67107bf14671711ab5979e2af8c7ead6ee043805", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HypoSystem/src/Hypo/System/Streams/BinaryReader.h", "max_forks_repo_name": "TheodorLindberg/Hypo", "max_forks_repo_head_hexsha": "67107bf14671711ab5979e2af8c7ead6ee043805", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.8076923077, "max_line_length": 79, "alphanum_fraction": 0.672815534, "num_tokens": 592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21206880435710534, "lm_q2_score": 0.03789242934583515, "lm_q1q2_score": 0.008035802185557352}}
{"text": "#pragma once\n\n#define EXPORT __declspec(dllexport)\n\n#define WIN32_LEAN_AND_MEAN\n\n// STL\n#include <array>\n#include <cassert>\n#include <cstdint>\n#include <deque>\n#include <exception>\n#include <fstream>\n#include <iomanip>\n#include <sstream>\n#include <stack>\n#include <stdexcept>\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\n// Windows\n#include <Windows.h>\n#include <VersionHelpers.h>\n#include <WTypes.h>\n\n// DirectX 11\n#include <d3d11_1.h>\n#include \"d3d8types.h\"\n#include <d3dcompiler.h>\n#include <DirectXMath.h>\n\n// GSL\n#include <gsl/span>\n\n// DirectXTK\n#include <wrl/client.h>\n#include <SimpleMath.h>\n\n// Local\n#include \"cbuffers.h\"\n#include \"CBufferWriter.h\"\n#include \"d3d8to11.hpp\"\n#include \"d3d8to11_base.h\"\n#include \"d3d8to11_device.h\"\n#include \"d3d8to11_index_buffer.h\"\n#include \"d3d8to11_resource.h\"\n#include \"d3d8to11_surface.h\"\n#include \"d3d8to11_texture.h\"\n#include \"d3d8to11_vertex_buffer.h\"\n#include \"d3d8types.hpp\"\n#include \"defs.h\"\n#include <dirty_t.h>\n#include \"hash_combine.h\"\n#include \"int_multiple.h\"\n#include \"Light.h\"\n#include \"Material.h\"\n#include \"Shader.h\"\n#include \"simple_math.h\"\n#include \"SimpleMath.h\"\n#include \"typedefs.h\"\n#include \"Unknown.h\"\n#include \"dynarray.h\"\n", "meta": {"hexsha": "45bf20948ad3455872f478c06c69389d1054b8b4", "size": 1228, "ext": "h", "lang": "C", "max_stars_repo_path": "d3d8to11/stdafx.h", "max_stars_repo_name": "basecq/d3d8to11", "max_stars_repo_head_hexsha": "f830e567e020305d30fc2ad3751e2b367382a09f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "d3d8to11/stdafx.h", "max_issues_repo_name": "basecq/d3d8to11", "max_issues_repo_head_hexsha": "f830e567e020305d30fc2ad3751e2b367382a09f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "d3d8to11/stdafx.h", "max_forks_repo_name": "basecq/d3d8to11", "max_forks_repo_head_hexsha": "f830e567e020305d30fc2ad3751e2b367382a09f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.8923076923, "max_line_length": 36, "alphanum_fraction": 0.7442996743, "num_tokens": 345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2782567937024021, "lm_q2_score": 0.028870906319603686, "lm_q1q2_score": 0.00803352582377534}}
{"text": "//\n//  rope.hpp\n//  Fans\n//\n//  Created by tqtifnypmb on 06/12/2017.\n//  Copyright \u00a9 2017 tqtifnypmb. All rights reserved.\n//\n\n#pragma once\n\n#include <memory>\n#include <functional>\n#include <vector>\n#include <string>\n\n#include <gsl/gsl>\n#include \"RopeNode.h\"\n#include \"Range.h\"\n#include \"RopeIter.h\"\n#include \"../types.h\"\n\nnamespace brick\n{\n\t\nclass Rope {\npublic:\n    static constexpr size_t max_leaf_length = 1;\n    \n\tRope(Rope&& l, Rope&& r);\n\t\n\tRope();\n    Rope(const Rope&);\n    \n\tRope(Rope&& r) = default;\n\tRope& operator=(Rope&&) = default;\n\tRope& operator=(const Rope&) = delete;\n\t\n\ttemplate <class Converter>\n    void insert(gsl::span<const char> bytes, size_t pos);\n    void insert(const detail::CodePointList& cp, size_t pos);\n    \n    void erase(const Range& range);\n    \n    size_t size() const {\n        return size_;\n    }\n    \n    RopeIter begin() const;\n    RopeIter end() const;\n    \n    std::reverse_iterator<RopeIter> rbegin() const {\n        return std::reverse_iterator<RopeIter>(end());\n    }\n    \n    std::reverse_iterator<RopeIter> rend() const {\n        return std::reverse_iterator<RopeIter>(begin());\n    }\n    \n    RopeIter iterator(size_t index) const;\n    \n    bool empty() const {\n        return size_ == 0;\n    }\n    \n    void swap(Rope& other) noexcept {\n        std::swap(size_, other.size_);\n        root_.swap(other.root_);\n    }\n    \n    std::string string() const;\n    \n    detail::RopeNode* root_test() {\n        return root_.get();\n    }\n    \n    detail::RopeNodePtr nextLeaf_test(detail::RopeNode* current) {\n        return nextLeaf(current);\n    }\n    \n    detail::RopeNodePtr prevLeaf_test(detail::RopeNode* current) {\n        return prevLeaf(current);\n    }\n    \n    void rebalance_test() {\n        rebalance();\n    }\n    \n    std::tuple<detail::RopeNodePtr, size_t> get_test(detail::RopeNode* root, size_t index) {\n        return getLeaf(root, index);\n    }\n    \n    size_t lengthOfWholeRope_test(gsl::not_null<detail::RopeNode*> root) {\n        return lengthOfWholeRope(root);\n    }\n    \n    bool checkHeight();\n    bool checkLength();\n    \nprivate:\n    friend class RopeIter;\n    \n    static const size_t npos = -1;\n    \n    Rope(std::vector<std::unique_ptr<detail::RopeNode>>& cplist);\n    \n    detail::RopeNodePtr nextLeaf(gsl::not_null<detail::RopeNode*> current) const;\n    detail::RopeNodePtr prevLeaf(gsl::not_null<detail::RopeNode*> current) const;\n    void removeLeaf(detail::RopeNodePtr node);\n    \n    size_t lengthOfWholeRope(gsl::not_null<detail::RopeNode*> root);\n    \n    std::vector<std::unique_ptr<detail::RopeNode>> collectLeaves(bool move) const;\n\tbool needBalance();\n\tvoid rebalance();\n    \n    std::tuple<detail::RopeNodePtr /* leaf */, size_t /* pos */>\n    getLeaf(gsl::not_null<detail::RopeNode*> root, size_t index, detail::RopeNode** lastVisitedNode = nullptr) const;\n    \n    void insertSubRope(detail::RopeNodePtr leaf, size_t pos, std::unique_ptr<detail::RopeNode> subRope, size_t len);\n    \n    size_t size_ = 0;\n\tstd::unique_ptr<detail::RopeNode> root_;\n};\n\t\ntemplate <class Converter>\nvoid Rope::insert(gsl::span<const char> bytes, size_t pos) {\n    insert(Converter::encode(bytes), pos);\n}\n\n\n}   // namespace brick\n", "meta": {"hexsha": "638df980d5fa71f4a6f3bf0a48e5ae4e88bc04be", "size": 3194, "ext": "h", "lang": "C", "max_stars_repo_path": "src/rope/Rope.h", "max_stars_repo_name": "tqtifnypmb/brick", "max_stars_repo_head_hexsha": "49398f77113c57d4e256e838a5ad6b9a6381de6a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/rope/Rope.h", "max_issues_repo_name": "tqtifnypmb/brick", "max_issues_repo_head_hexsha": "49398f77113c57d4e256e838a5ad6b9a6381de6a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/rope/Rope.h", "max_forks_repo_name": "tqtifnypmb/brick", "max_forks_repo_head_hexsha": "49398f77113c57d4e256e838a5ad6b9a6381de6a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.196969697, "max_line_length": 117, "alphanum_fraction": 0.6383844709, "num_tokens": 871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3140505449918074, "lm_q2_score": 0.025565216475354074, "lm_q1q2_score": 0.00802877016691848}}
{"text": "#pragma once\n\n#include <winrt\\Windows.Foundation.h>\n#include <d3d11.h>\n#include <DirectXMath.h>\n#include <gsl\\gsl>\n#include \"DrawableGameComponent.h\"\n#include \"MatrixHelper.h\"\n\nnamespace Library\n{\n\tclass SkyboxMaterial;\n\n\tclass Skybox final : public DrawableGameComponent\n\t{\n\t\tRTTI_DECLARATIONS(Skybox, DrawableGameComponent)\n\n\tpublic:\n\t\tSkybox(Game& game, const std::shared_ptr<Camera>& camera, const std::wstring& cubeMapFileName, float scale);\n\t\tSkybox(const Skybox&) = delete;\n\t\tSkybox(Skybox&&) = default;\n\t\tSkybox& operator=(const Skybox&) = delete;\t\t\n\t\tSkybox& operator=(Skybox&&) = default;\n\t\t~Skybox() = default;\n\n\t\tvirtual void Initialize() override;\n\t\tvirtual void Draw(const GameTime& gameTime) override;\n\n\tprivate:\n\t\tstd::wstring mCubeMapFileName;\n\t\tDirectX::XMFLOAT4X4 mWorldMatrix{ MatrixHelper::Identity };\n\t\tfloat mScale;\n\t\tstd::shared_ptr<SkyboxMaterial> mMaterial;\n\t\twinrt::com_ptr<ID3D11Buffer> mVertexBuffer;\n\t\twinrt::com_ptr<ID3D11Buffer> mIndexBuffer;\n\t\tstd::uint32_t mIndexCount{ 0 };\n\t\tbool mUpdateMaterial{ true };\n\t};\n}", "meta": {"hexsha": "57884b60fef9a418a099ac30261f0d90d399cf9e", "size": 1046, "ext": "h", "lang": "C", "max_stars_repo_path": "source/Library.Shared/Skybox.h", "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/Library.Shared/Skybox.h", "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/Library.Shared/Skybox.h", "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8205128205, "max_line_length": 110, "alphanum_fraction": 0.7456978967, "num_tokens": 298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3886180267058489, "lm_q2_score": 0.02064593303660557, "lm_q1q2_score": 0.008023381756186752}}
{"text": "/*\nCopyright (c) 2015, Patrick Weltevrede\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n#define _FILE_OFFSET_BITS 64\n#define _USE_LARGEFILE 1\n#define _LARGEFILE_SOURCE 1\n#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n#include <string.h>\n#include <stdlib.h>\n#include <gsl/gsl_sort.h>\n#include \"psrsalsa.h\"\n#define MaxNrOnpulseRegions 10\nint NrOnpulseRegions, OnPulseRegion[MaxNrOnpulseRegions][2];\nvoid PlotProfile(int NrBins, float *Ipulse, char *xlabel, char *ylabel, char *title, int Highlight, int color, int clearPage);\nvoid ShiftProfile(int shift, int NrBins, float *Iprofile, float *outputProfile);\nint main(int argc, char **argv)\n{\n  char output_fname[1000], PlotDevice[100], singlechar, *inputname;\n  int circularShift, noinput, onlyI, memsave, currentfilenumber, dummy_int;\n  int shift, bin1, bin2, subintWritten, poladd, freqadd;\n  long i, j, pol, fchan, nsub, binnr, nrinputfiles, subintslost, currentOutputSubint, sumNsub, curNrInsubint;\n  float *Iprofile, *Iprofile_firstfile, *shiftedProfile, *subint, x, y, *float_ptr, *float_ptr2;\n  datafile_definition **fin;\n  datafile_definition fout, clone;\n  psrsalsaApplication application;\n  initApplication(&application, \"padd\", \"[options] inputfiles\");\n  application.switch_blocksize = 1;\n  application.switch_verbose = 1;\n  application.switch_debug = 1;\n  application.switch_filelist = 1;\n  application.switch_iformat = 1;\n  application.switch_oformat = 1;\n  application.switch_formatlist = 1;\n  application.switch_fscr = 1;\n  application.switch_FSCR = 1;\n  application.switch_nocounters = 1;\n  application.switch_changeRefFreq = 1;\n  application.oformat = FITS_format;\n  strcpy(PlotDevice, \"?\");\n  onlyI = 0;\n  strcpy(output_fname, \"addedfile.gg\");\n  NrOnpulseRegions = 0;\n  circularShift = 0;\n  noinput = 0;\n  shift = 0;\n  memsave = 0;\n  sumNsub = 1;\n  poladd = 0;\n  freqadd = 0;\n  x = y = singlechar = 0;\n  if(argc < 2) {\n    printf(\"Program to add data files together. Usage:\\n\\n\");\n    printApplicationHelp(&application);\n    printf(\"Optional options:\\n\");\n    printf(\"-w                      Output name. Default is \\\"%s\\\"\\n\", output_fname);\n    printf(\"-I                      Only process the first polarization channel\\n\");\n    printf(\"-c                      Turn on circular shifting (so that no subint is lost).\\n\");\n    printf(\"                        The first and last subintegrations are spilling over\\n\");\n    printf(\"                        into each other.\\n\");\n    printf(\"-n                      No graphical input, circular shifting by this number of\\n\");\n    printf(\"                        bins, so this option implies -c. So -n 0 results in a\\n\");\n    printf(\"                        simple concatenation of the input files.\\n\");\n    printf(\"-nsub                   This number of subintegrations are summed before being\\n\");\n    printf(\"                        written out\\n\");\n    printf(\"-poladd                 The input files are to be interpretted as separate\\n\");\n    printf(\"                        polarization channels (option implies -n 0).\\n\");\n    printf(\"-freqadd                The input files are to be interpretted as separate\\n\");\n    printf(\"                        frequency bands (option implies -n 0).\\n\");\n    printf(\"-memsave                Only one full input data-set exists in memory at a time,\\n\");\n    printf(\"                        but every input file will be opened twice.\\n\");\n    printf(\"\\n\");\n    printCitationInfo();\n    terminateApplication(&application);\n    return 0;\n  }else {\n    for(i = 1; i < argc; i++) {\n      dummy_int = i;\n      if(processCommandLine(&application, argc, argv, &dummy_int)) {\n i = dummy_int;\n      }else if(strcmp(argv[i], \"-w\") == 0 || strcmp(argv[i], \"-W\") == 0) {\n strcpy(output_fname,argv[i+1]);\n        i++;\n      }else if(strcmp(argv[i], \"-memsave\") == 0) {\n memsave = 1;\n      }else if(strcmp(argv[i], \"-c\") == 0 || strcmp(argv[i], \"-C\") == 0) {\n circularShift = 1;\n      }else if(strcmp(argv[i], \"-I\") == 0) {\n onlyI = 1;\n      }else if(strcmp(argv[i], \"-poladd\") == 0) {\n poladd = 1;\n circularShift = 1;\n noinput = 1;\n shift = 0;\n      }else if(strcmp(argv[i], \"-freqadd\") == 0) {\n freqadd = 1;\n circularShift = 1;\n noinput = 1;\n shift = 0;\n      }else if(strcmp(argv[i], \"-n\") == 0) {\n circularShift = 1;\n noinput = 1;\n if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, \"%d\", &shift, NULL) == 0) {\n   printerror(application.verbose_state.debug, \"ERROR padd: Cannot parse '%s' option.\", argv[i]);\n   return 0;\n }\n i++;\n      }else if(strcmp(argv[i], \"-nsub\") == 0) {\n if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, \"%ld\", &sumNsub, NULL) == 0) {\n   printerror(application.verbose_state.debug, \"ERROR padd: Cannot parse '%s' option.\", argv[i]);\n   return 0;\n }\n if(sumNsub < 1) {\n   fflush(stdout);\n   printerror(application.verbose_state.debug, \"ERROR padd: Cannot parse option %s, expected one integer number > 1\", argv[i]);\n   return 0;\n }\n i++;\n      }else {\n if(argv[i][0] == '-') {\n   printerror(application.verbose_state.debug, \"ERROR padd: Unknown option %s. Run padd without command-line options to get help.\", argv[i]);\n   terminateApplication(&application);\n   return 0;\n }else {\n   if(applicationAddFilename(i, application.verbose_state) == 0)\n     return 0;\n }\n      }\n    }\n  }\n  if(applicationFilenameList_checkConsecutive(argv, application.verbose_state) == 0) {\n    return 0;\n  }\n  nrinputfiles = numberInApplicationFilenameList(&application, argv, application.verbose_state);\n  if(nrinputfiles < 2) {\n    printerror(application.verbose_state.debug, \"ERROR padd: Need at least two input files\");\n    return 0;\n  }\n  if(freqadd && poladd) {\n    printerror(application.verbose_state.debug, \"ERROR padd: Cannot use the -freqadd and -poladd flag simultaneously.\");\n    return 0;\n  }\n  if(sumNsub != 1 && poladd) {\n    printerror(application.verbose_state.debug, \"ERROR padd: Cannot use the -nsub and -poladd flag simultaneously.\");\n    return 0;\n  }\n  if(sumNsub != 1 && freqadd) {\n    printerror(application.verbose_state.debug, \"ERROR padd: Cannot use the -nsub and -freqadd flag simultaneously.\");\n    return 0;\n  }\n  if(circularShift != 1 && poladd) {\n    printerror(application.verbose_state.debug, \"ERROR padd: You must use the -c option together with -poladd.\");\n    return 0;\n  }\n  if(circularShift != 1 && freqadd) {\n    printerror(application.verbose_state.debug, \"ERROR padd: You must use the -c option together with -freqadd.\");\n    return 0;\n  }\n  if((noinput != 1 || shift != 0) && poladd) {\n    printerror(application.verbose_state.debug, \"ERROR padd: You must use the -n 0 option together with -poladd.\");\n    return 0;\n  }\n  if((noinput != 1 || shift != 0) && freqadd) {\n    printerror(application.verbose_state.debug, \"ERROR padd: You must use the -n 0 option together with -poladd.\");\n    return 0;\n  }\n  fin = malloc(nrinputfiles*sizeof(datafile_definition *));\n  if(fin == NULL) {\n    printerror(application.verbose_state.debug, \"ERROR padd: Memory allocation error\");\n    return 0;\n  }\n  for(i = 0; i < nrinputfiles; i++) {\n    fin[i] = malloc(sizeof(datafile_definition));\n    if(fin[i] == NULL) {\n      printerror(application.verbose_state.debug, \"ERROR padd: Memory allocation error\");\n      return 0;\n    }\n  }\n  currentfilenumber = 0;\n  while((inputname = getNextFilenameFromList(&application, argv, application.verbose_state)) != NULL) {\n    verbose_definition verbose2;\n    copyVerboseState(application.verbose_state, &verbose2);\n    verbose2.indent = application.verbose_state.indent + 2;\n    if(memsave == 0 || (currentfilenumber == 0 && noinput == 0)) {\n      if(currentfilenumber == 0) {\n printf(\"Read in input files:\\n\");\n      }\n      if(openPSRData(fin[currentfilenumber], inputname, application.iformat, 0, 1, 0, verbose2) == 0) {\n printerror(application.verbose_state.debug, \"ERROR padd: Cannot open %s\\n\", inputname);\n return 0;\n      }\n      if(currentfilenumber == 0) {\n for(i = 1; i < argc; i++) {\n   if(strcmp(argv[i], \"-header\") == 0) {\n     fflush(stdout);\n     printwarning(application.verbose_state.debug, \"WARNING: If using the -header option, be aware it applied BEFORE the preprocessing.\");\n   }\n }\n      }\n      if(preprocessApplication(&application, fin[currentfilenumber]) == 0) {\n printerror(application.verbose_state.debug, \"ERROR padd: preprocess option failed on file %s\\n\", inputname);\n return 0;\n      }\n    }else {\n      if(currentfilenumber == 0)\n printf(\"Read in headers of input files:\\n\");\n      if(openPSRData(fin[currentfilenumber], inputname, application.iformat, 0, 0, 0, verbose2) == 0) {\n printerror(application.verbose_state.debug, \"ERROR padd: Cannot open %s\\n\", inputname);\n return 0;\n      }\n      if(readHeaderPSRData(fin[currentfilenumber], 1, 0, verbose2) == 0) {\n printerror(application.verbose_state.debug, \"ERROR padd: Cannot read header of file %s\\n\", inputname);\n return 0;\n      }\n    }\n    if(currentfilenumber == 0 && noinput == 0) {\n      Iprofile_firstfile = (float *)malloc(fin[0]->NrPols*fin[0]->NrBins*sizeof(float));\n      shiftedProfile = (float *)malloc(fin[0]->NrPols*fin[0]->NrBins*sizeof(float));\n      if(Iprofile_firstfile == NULL || shiftedProfile == NULL) {\n printerror(application.verbose_state.debug, \"ERROR padd: Cannot allocate memory.\");\n return 0;\n      }\n      if(read_profilePSRData(*fin[0], Iprofile_firstfile, NULL, 0, application.verbose_state) != 1) {\n printerror(application.verbose_state.debug, \"ERROR padd: Reading pulse profile of first input file failed.\");\n return 0;\n      }\n    }\n    if(memsave) {\n      if(closePSRData(fin[currentfilenumber], 1, application.verbose_state) != 0) {\n printerror(application.verbose_state.debug, \"ERROR padd: Closing file %s failed\\n\", inputname);\n return 0;\n      }\n    }\n    if(fin[currentfilenumber]->NrBins != fin[0]->NrBins) {\n      printerror(application.verbose_state.debug, \"ERROR padd: Number of pulse longitude bins not equal in input files.\");\n      return 0;\n    }\n    if(fin[0]->NrPols != fin[currentfilenumber]->NrPols && onlyI == 0) {\n      printerror(application.verbose_state.debug, \"ERROR padd: Number of polarization channels are different. Maybe you want to use the -I option?\");\n      return 0;\n    }\n    if(freqadd == 0) {\n      if(fin[currentfilenumber]->NrFreqChan != fin[0]->NrFreqChan) {\n printerror(application.verbose_state.debug, \"ERROR padd: Number of frequency channels not equal in input files.\");\n return 0;\n      }\n    }\n    if(poladd || freqadd) {\n      if(fin[0]->NrSubints != fin[currentfilenumber]->NrSubints) {\n printerror(application.verbose_state.debug, \"ERROR padd: Number of subints are different. This is not allowed with the -poladd or -freqadd options.\");\n return 0;\n      }\n    }\n    if(poladd) {\n      if(fin[currentfilenumber]->NrPols != 1) {\n printerror(application.verbose_state.debug, \"ERROR padd: Number of polarization channels in input files should be 1 if using the -poladd option.\");\n return 0;\n      }\n    }\n    if(fin[currentfilenumber]->isDeDisp != fin[0]->isDeDisp) {\n      printerror(application.verbose_state.debug, \"ERROR padd: Dedispersion state is not equal in input files.\");\n      return 0;\n    }\n    if(fin[currentfilenumber]->isDeFarad != fin[0]->isDeFarad) {\n      printerror(application.verbose_state.debug, \"ERROR padd: De-Faraday rotation state is not equal in input files.\");\n      return 0;\n    }\n    if(fin[currentfilenumber]->isDePar != fin[0]->isDePar) {\n      printerror(application.verbose_state.debug, \"ERROR padd: Parallactic angle state is not equal in input files.\");\n      return 0;\n    }\n    currentfilenumber++;\n  }\n  printf(\"Reading of input files done\\n\");\n  unsigned long *sort_indx;\n  sort_indx = (unsigned long *)malloc(nrinputfiles*sizeof(unsigned long));\n  if(sort_indx == NULL) {\n    printerror(application.verbose_state.debug, \"ERROR padd: Memory allocation error\\n\");\n    return 0;\n  }\n    for(currentfilenumber = 0; currentfilenumber < nrinputfiles; currentfilenumber++) {\n      sort_indx[currentfilenumber] = currentfilenumber;\n    }\n  cleanPSRData(&fout, application.verbose_state);\n  copy_params_PSRData(*(fin[0]), &fout, application.verbose_state);\n  if(onlyI) {\n    fout.NrPols = 1;\n  }\n  fout.format = application.oformat;\n  fout.NrSubints = 0;\n  subintslost = 0;\n  if(poladd) {\n    fout.NrPols = nrinputfiles;\n    fout.NrSubints = fin[0]->NrSubints;\n  }else if(freqadd) {\n    fout.NrSubints = fin[0]->NrSubints;\n    fout.NrFreqChan = 0;\n    for(currentfilenumber = 0; currentfilenumber < nrinputfiles; currentfilenumber++) {\n      fout.NrFreqChan += fin[currentfilenumber]->NrFreqChan;\n    }\n    fout.freqMode = FREQMODE_FREQTABLE;\n    if(fout.freqlabel_list != NULL) {\n      free(fout.freqlabel_list);\n    }\n    fout.freqlabel_list = (double *)malloc(fout.NrFreqChan*fout.NrSubints*sizeof(double));\n    if(fout.freqlabel_list == NULL) {\n      printerror(application.verbose_state.debug, \"ERROR padd: Memory allocation error\");\n      return 0;\n    }\n    long currentOutputChan = 0;\n    for(i = 0; i < nrinputfiles; i++) {\n      currentfilenumber = sort_indx[i];\n      for(fchan = 0; fchan < fin[currentfilenumber]->NrFreqChan; fchan++) {\n for(nsub = 0; nsub < fin[currentfilenumber]->NrSubints; nsub++) {\n   double freq;\n   freq = get_weighted_channel_freq(*(fin[currentfilenumber]), nsub, fchan, application.verbose_state);\n   if(set_weighted_channel_freq(&fout, nsub, currentOutputChan, freq, application.verbose_state) == 0) {\n     printerror(application.verbose_state.debug, \"ERROR padd: Constructing frequency table failed\");\n     return 0;\n   }\n }\n currentOutputChan++;\n      }\n    }\n  }else {\n    for(i = 0; i < nrinputfiles; i++) {\n      fout.NrSubints += fin[i]->NrSubints;\n      if(circularShift == 0) {\n fout.NrSubints -= 1;\n subintslost += 1;\n      }\n    }\n  }\n  if(freqadd || poladd) {\n    printf(\"\\nOutput data will be %ld subints, %ld phase bins %ld frequency channels and %ld polarizations.\\n\", fout.NrSubints, fout.NrBins, fout.NrFreqChan, fout.NrPols);\n  }else {\n    printf(\"\\nInput data contains %ld subints, %ld phase bins %ld frequency channels and %ld polarizations.\\n\", fout.NrSubints+subintslost, fout.NrBins, fout.NrFreqChan, fout.NrPols);\n    printf(\"%ld subints are lost because of the alignment of input data\", subintslost);\n    if(subintslost > 0)\n      printf(\" (consider using -c option)\");\n  }\n  fout.tsubMode = TSUBMODE_TSUBLIST;\n  if(fout.tsub_list != NULL) {\n    free(fout.tsub_list);\n  }\n  fout.tsub_list = (double *)malloc(fout.NrSubints*sizeof(double));\n  if(fout.tsub_list == NULL) {\n    printerror(application.verbose_state.debug, \"ERROR padd: Memory allocation error\");\n    return 0;\n  }\n  currentOutputSubint = 0;\n  fout.tsub_list[0] = 0;\n  subintWritten = 0;\n  curNrInsubint = 0;\n  if(poladd || freqadd) {\n    for(nsub = 0; nsub < fin[0]->NrSubints; nsub++) {\n      fout.tsub_list[nsub] = get_tsub(*(fin[0]), nsub, application.verbose_state);\n    }\n  }else {\n    for(i = 0; i < nrinputfiles; i++) {\n      currentfilenumber = sort_indx[i];\n      for(nsub = 0; nsub < fin[currentfilenumber]->NrSubints; nsub++) {\n if(currentOutputSubint < fout.NrSubints)\n   fout.tsub_list[currentOutputSubint] += get_tsub(*(fin[currentfilenumber]), nsub, application.verbose_state);\n if(sumNsub == 1) {\n   subintWritten = 1;\n }else if(curNrInsubint == sumNsub - 1) {\n   subintWritten = 1;\n }\n curNrInsubint++;\n if(subintWritten) {\n   subintWritten = 0;\n   curNrInsubint = 0;\n   currentOutputSubint++;\n   if(currentOutputSubint < fout.NrSubints)\n     fout.tsub_list[currentOutputSubint] = 0;\n }\n      }\n    }\n  }\n  if(freqadd == 0 && poladd == 0) {\n    dummy_int = fout.NrSubints % sumNsub;\n    fout.NrSubints = fout.NrSubints/sumNsub;\n    printf(\"\\nOutput data will contain %ld subints\", fout.NrSubints);\n    if(sumNsub > 1)\n      printf(\" after summing every %ld input subints\", sumNsub);\n    if(dummy_int)\n      printf(\" (%d input subints lost because of incomplete last subint)\", dummy_int);\n    printf(\"\\n\\n\");\n  }\n  if(fout.gentype == GENTYPE_PULSESTACK && sumNsub != 1) {\n    if(fout.NrSubints != 1) {\n      fout.gentype = GENTYPE_SUBINTEGRATIONS;\n    }else {\n      fout.gentype = GENTYPE_PROFILE;\n    }\n  }\n  if(openPSRData(&fout, output_fname, fout.format, 1, 0, 0, application.verbose_state) == 0) {\n    printerror(application.verbose_state.debug, \"ERROR padd: Cannot open %s\", output_fname);\n    return 0;\n  }\n  if(writeHeaderPSRData(&fout, argc, argv, application.history_cmd_only, application.verbose_state) != 1) {\n    printerror(application.verbose_state.debug, \"ERROR padd: Cannot write header to %s\", output_fname);\n    return 0;\n  }\n  Iprofile = (float *)malloc(fout.NrPols*fout.NrBins*sizeof(float));\n  if(Iprofile == NULL) {\n    printerror(application.verbose_state.debug, \"ERROR padd: Cannot allocate memory.\");\n    return 0;\n  }\n  if(sumNsub > 1) {\n    subint = (float *)malloc(fout.NrPols*fout.NrBins*fout.NrFreqChan*sizeof(float));\n    if(subint == NULL) {\n      printerror(application.verbose_state.debug, \"ERROR padd: Cannot allocate memory.\");\n      return 0;\n    }\n  }\n  if(noinput == 0) {\n    ppgopen(PlotDevice);\n    ppgask(0);\n    ppgslw(1);\n  }\n  currentfilenumber = 0;\n  currentOutputSubint = 0;\n  curNrInsubint = 0;\n  subintWritten = 0;\n  rewindFilenameList(&application);\n  long currentfilenumber_index;\n  long fchan_offset = 0;\n  while((inputname = getNextFilenameFromList(&application, argv, application.verbose_state)) != NULL) {\n    currentfilenumber_index = sort_indx[currentfilenumber];\n    if(memsave) {\n      closePSRData(fin[currentfilenumber_index], 0, application.verbose_state);\n      if(openPSRData(fin[currentfilenumber_index], inputname, application.iformat, 0, 1, 0, application.verbose_state) == 0) {\n printerror(application.verbose_state.debug, \"ERROR padd: Cannot open %s\\n\", inputname);\n return 0;\n      }\n      if(currentfilenumber == 0) {\n for(i = 1; i < argc; i++) {\n   if(strcmp(argv[i], \"-header\") == 0) {\n     fflush(stdout);\n     printwarning(application.verbose_state.debug, \"WARNING: If using the -header option, be aware it applied BEFORE the preprocessing.\");\n   }\n }\n      }\n      if(preprocessApplication(&application, fin[currentfilenumber_index]) == 0) {\n printerror(application.verbose_state.debug, \"ERROR padd: preprocess option failed on file %s\\n\", inputname);\n return 0;\n      }\n    }\n    if(shift >= fout.NrBins)\n      shift -= fout.NrBins;\n    if(shift < 0)\n      shift += fout.NrBins;\n    if(noinput == 0 && currentfilenumber != 0) {\n      if(read_profilePSRData(*fin[currentfilenumber_index], Iprofile, NULL, 0, application.verbose_state) != 1) {\n printerror(application.verbose_state.debug, \"ERROR padd: Reading pulse profile failed.\");\n return 0;\n      }\n      do {\n ShiftProfile(shift, fout.NrBins, Iprofile, shiftedProfile);\n PlotProfile(fout.NrBins, Iprofile_firstfile, \"Bin number\", \"Intensity\", \"Click to shift profile, press s to stop\", 0, 1, 1);\n PlotProfile(fout.NrBins, shiftedProfile, \"\", \"\", \"\", 0, 2, 0);\n j = 0;\n do {\n   if(j == 0)\n     ppgband(0, 0, 0.0, 0.0, &x, &y, &singlechar);\n   else\n     ppgband(4, 0, bin1, 0.0, &x, &y, &singlechar);\n   if(singlechar == 65) {\n     if(j == 0)\n       bin1 = x;\n     else\n       bin2 = x;\n     j++;\n   }else if(singlechar == 115 || singlechar ==83 ) {\n     j = 10;\n   }\n }while(j < 2);\n if(j < 10) {\n   shift += bin2 - bin1;\n   if(shift >= fout.NrBins)\n     shift -= fout.NrBins;\n   if(shift < 0)\n     shift += fout.NrBins;\n }\n      }while(j < 10);\n    }\n    if(shift != 0) {\n      if(continuous_shift(*fin[currentfilenumber_index], &clone, shift, circularShift, \"padd\", MEMORY_format, 0, NULL, application.verbose_state, application.verbose_state.debug) != 1) {\n printerror(application.verbose_state.debug, \"ERROR padd: circular shift failed.\");\n      }\n      swap_orig_clone(fin[currentfilenumber_index], &clone, application.verbose_state);\n    }\n    long nrPulsesInCurFile;\n    nrPulsesInCurFile = fin[currentfilenumber_index]->NrSubints;\n    if(shift == 0 && circularShift == 0)\n      nrPulsesInCurFile -= 1;\n    for(nsub = 0; nsub < nrPulsesInCurFile; nsub++) {\n      int nrpolsinloop;\n      nrpolsinloop = fout.NrPols;\n      if(poladd) {\n nrpolsinloop = 1;\n      }\n      for(pol = 0; pol < nrpolsinloop; pol++) {\n for(fchan = 0; fchan < fin[currentfilenumber_index]->NrFreqChan; fchan++) {\n   if(readPulsePSRData(fin[currentfilenumber_index], nsub, pol, fchan, 0, fin[currentfilenumber_index]->NrBins, Iprofile, application.verbose_state) != 1) {\n     printerror(application.verbose_state.debug, \"ERROR padd: Read error\");\n     return 0;\n   }\n   if(sumNsub == 1) {\n     if(poladd == 0 && freqadd == 0) {\n  if(writePulsePSRData(&fout, currentOutputSubint, pol, fchan, 0, fout.NrBins, Iprofile, application.verbose_state) != 1) {\n    printerror(application.verbose_state.debug, \"ERROR padd: Write error\");\n    return 0;\n  }\n     }else {\n       if(poladd) {\n  if(writePulsePSRData(&fout, nsub, currentfilenumber, fchan, 0, fout.NrBins, Iprofile, application.verbose_state) != 1) {\n    printerror(application.verbose_state.debug, \"ERROR padd: Write error\");\n    return 0;\n  }\n       }else if(freqadd) {\n  if(writePulsePSRData(&fout, nsub, pol, fchan+fchan_offset, 0, fout.NrBins, Iprofile, application.verbose_state) != 1) {\n    printerror(application.verbose_state.debug, \"ERROR padd: Write error\");\n    return 0;\n  }\n       }\n     }\n     subintWritten = 1;\n   }else {\n     float_ptr = &subint[fout.NrBins*(pol+fout.NrPols*fchan)];\n     float_ptr2 = Iprofile;\n     if(curNrInsubint == 0) {\n       for(binnr = 0; binnr < fout.NrBins; binnr++) {\n  *float_ptr = *float_ptr2;\n  float_ptr++;\n  float_ptr2++;\n       }\n     }else {\n       for(binnr = 0; binnr < fout.NrBins; binnr++) {\n  *float_ptr += *float_ptr2;\n  float_ptr++;\n  float_ptr2++;\n       }\n     }\n     if(curNrInsubint == sumNsub - 1) {\n       if(writePulsePSRData(&fout, currentOutputSubint, pol, fchan, 0, fout.NrBins, float_ptr-fout.NrBins, application.verbose_state) != 1) {\n  printerror(application.verbose_state.debug, \"ERROR padd: Write error\");\n  return 0;\n       }\n       subintWritten = 1;\n     }\n   }\n }\n      }\n      curNrInsubint++;\n      if(subintWritten) {\n subintWritten = 0;\n curNrInsubint = 0;\n currentOutputSubint++;\n      }\n      if(application.verbose_state.nocounters == 0) {\n printf(\"Processing input file %d: %.1f%%     \\r\", currentfilenumber+1, (100.0*(nsub+1))/(float)(fin[currentfilenumber_index]->NrSubints));\n fflush(stdout);\n      }\n    }\n    if(freqadd) {\n      fchan_offset += fin[currentfilenumber_index]->NrFreqChan;\n    }\n    if(application.verbose_state.nocounters == 0) {\n      printf(\"Processing file %d is done (%s).                                \\n\", currentfilenumber+1, fin[currentfilenumber_index]->filename);\n    }\n    closePSRData(fin[currentfilenumber_index], 0, application.verbose_state);\n    currentfilenumber++;\n  }\n  closePSRData(&fout, 0, application.verbose_state);\n  if(noinput == 0)\n    ppgend();\n  free(Iprofile);\n  if(noinput == 0) {\n    free(shiftedProfile);\n    free(Iprofile_firstfile);\n  }\n  if(sumNsub > 1)\n    free(subint);\n  for(i = 0; i < nrinputfiles; i++) {\n    free(fin[i]);\n  }\n  free(fin);\n  free(sort_indx);\n  terminateApplication(&application);\n  return 0;\n}\nint CheckOnPulse(int bin, int NrRegions, int Regions[MaxNrOnpulseRegions][2])\n{\n  int i;\n  for(i = 0; i < NrRegions; i++) {\n    if(bin >= Regions[i][0] && bin <= Regions[i][1])\n      return i+1;\n  }\n  return 0;\n}\nvoid PlotProfile(int NrBins, float *Ipulse, char *xlabel, char *ylabel, char *title, int Highlight, int color, int clearPage)\n{\n  long j;\n  float ymin, ymax;\n  ymin = ymax = Ipulse[0];\n  for(j = 1; j < NrBins; j++) {\n    if(Ipulse[j] > ymax)\n      ymax = Ipulse[j];\n    if(Ipulse[j] < ymin)\n      ymin = Ipulse[j];\n  }\n  if(clearPage) {\n    ppgpage();\n    ppgsci(1);\n    ppgsvp(0.1, 0.9, 0.1, 0.9);\n    ppgswin(0,NrBins-1,-0.1,1.1);\n    ppgbox(\"bcnsti\",0.0,0,\"bcnti\",0.0,0);\n    ppglab(xlabel, ylabel, title);\n  }\n  ppgsci(color);\n  ppgmove(0, Ipulse[0]/ymax);\n  for(j = 1; j < NrBins; j++) {\n    if(Highlight != 0)\n      ppgsci(color+CheckOnPulse(j,NrOnpulseRegions,OnPulseRegion));\n    else\n      ppgsci(color);\n    ppgdraw(j, Ipulse[j]/ymax);\n  }\n  ppgsci(1);\n}\nvoid ShiftProfile(int shift, int NrBins, float *Iprofile, float *outputProfile)\n{\n  int b, b2;\n  for(b = 0; b < NrBins; b++) {\n    b2 = b+shift;\n    if(b2 < 0)\n      b2 += NrBins;\n    if(b2 >= NrBins)\n      b2 -= NrBins;\n    outputProfile[b2] = Iprofile[b];\n  }\n}\n", "meta": {"hexsha": "3366c74756779708a5b0a05270297840533ab659", "size": 25790, "ext": "c", "lang": "C", "max_stars_repo_path": "src/prog/padd.c", "max_stars_repo_name": "weltevrede/psrsalsa", "max_stars_repo_head_hexsha": "4c5b1b32513174ec1f6929905e67c8b9ca44e008", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-09-05T23:22:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-11T14:12:18.000Z", "max_issues_repo_path": "src/prog/padd.c", "max_issues_repo_name": "weltevrede/psrsalsa", "max_issues_repo_head_hexsha": "4c5b1b32513174ec1f6929905e67c8b9ca44e008", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-04-26T13:35:30.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-20T08:49:57.000Z", "max_forks_repo_path": "src/prog/padd.c", "max_forks_repo_name": "weltevrede/psrsalsa", "max_forks_repo_head_hexsha": "4c5b1b32513174ec1f6929905e67c8b9ca44e008", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-04-09T09:04:46.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-16T15:24:07.000Z", "avg_line_length": 39.1350531108, "max_line_length": 755, "alphanum_fraction": 0.6622334238, "num_tokens": 7244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936414516010196, "lm_q2_score": 0.022286186675637105, "lm_q1q2_score": 0.008008856423568782}}
{"text": "/* matrix/gsl_matrix_ulong.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_MATRIX_ULONG_H__\n#define __GSL_MATRIX_ULONG_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_vector_ulong.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size1;\n  size_t size2;\n  size_t tda;\n  unsigned long * data;\n  gsl_block_ulong * block;\n  int owner;\n} gsl_matrix_ulong;\n\ntypedef struct\n{\n  gsl_matrix_ulong matrix;\n} _gsl_matrix_ulong_view;\n\ntypedef _gsl_matrix_ulong_view gsl_matrix_ulong_view;\n\ntypedef struct\n{\n  gsl_matrix_ulong matrix;\n} _gsl_matrix_ulong_const_view;\n\ntypedef const _gsl_matrix_ulong_const_view gsl_matrix_ulong_const_view;\n\n/* Allocation */\n\nGSL_EXPORT\ngsl_matrix_ulong *\ngsl_matrix_ulong_alloc (const size_t n1, const size_t n2);\n\nGSL_EXPORT\ngsl_matrix_ulong *\ngsl_matrix_ulong_calloc (const size_t n1, const size_t n2);\n\nGSL_EXPORT\ngsl_matrix_ulong *\ngsl_matrix_ulong_alloc_from_block (gsl_block_ulong * b,\n                                   const size_t offset,\n                                   const size_t n1,\n                                   const size_t n2,\n                                   const size_t d2);\n\nGSL_EXPORT\ngsl_matrix_ulong *\ngsl_matrix_ulong_alloc_from_matrix (gsl_matrix_ulong * m,\n                                    const size_t k1,\n                                    const size_t k2,\n                                    const size_t n1,\n                                    const size_t n2);\n\nGSL_EXPORT\ngsl_vector_ulong *\ngsl_vector_ulong_alloc_row_from_matrix (gsl_matrix_ulong * m,\n                                        const size_t i);\n\nGSL_EXPORT\ngsl_vector_ulong *\ngsl_vector_ulong_alloc_col_from_matrix (gsl_matrix_ulong * m,\n                                        const size_t j);\n\nGSL_EXPORT void gsl_matrix_ulong_free (gsl_matrix_ulong * m);\n\n/* Views */\n\nGSL_EXPORT\n_gsl_matrix_ulong_view\ngsl_matrix_ulong_submatrix (gsl_matrix_ulong * m,\n                            const size_t i, const size_t j,\n                            const size_t n1, const size_t n2);\n\nGSL_EXPORT\n_gsl_vector_ulong_view\ngsl_matrix_ulong_row (gsl_matrix_ulong * m, const size_t i);\n\nGSL_EXPORT\n_gsl_vector_ulong_view\ngsl_matrix_ulong_column (gsl_matrix_ulong * m, const size_t j);\n\nGSL_EXPORT\n_gsl_vector_ulong_view\ngsl_matrix_ulong_diagonal (gsl_matrix_ulong * m);\n\nGSL_EXPORT\n_gsl_vector_ulong_view\ngsl_matrix_ulong_subdiagonal (gsl_matrix_ulong * m, const size_t k);\n\nGSL_EXPORT\n_gsl_vector_ulong_view\ngsl_matrix_ulong_superdiagonal (gsl_matrix_ulong * m, const size_t k);\n\nGSL_EXPORT\n_gsl_matrix_ulong_view\ngsl_matrix_ulong_view_array (unsigned long * base,\n                             const size_t n1,\n                             const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_ulong_view\ngsl_matrix_ulong_view_array_with_tda (unsigned long * base,\n                                      const size_t n1,\n                                      const size_t n2,\n                                      const size_t tda);\n\n\nGSL_EXPORT\n_gsl_matrix_ulong_view\ngsl_matrix_ulong_view_vector (gsl_vector_ulong * v,\n                              const size_t n1,\n                              const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_ulong_view\ngsl_matrix_ulong_view_vector_with_tda (gsl_vector_ulong * v,\n                                       const size_t n1,\n                                       const size_t n2,\n                                       const size_t tda);\n\n\nGSL_EXPORT\n_gsl_matrix_ulong_const_view\ngsl_matrix_ulong_const_submatrix (const gsl_matrix_ulong * m,\n                                  const size_t i, const size_t j,\n                                  const size_t n1, const size_t n2);\n\nGSL_EXPORT\n_gsl_vector_ulong_const_view\ngsl_matrix_ulong_const_row (const gsl_matrix_ulong * m,\n                            const size_t i);\n\nGSL_EXPORT\n_gsl_vector_ulong_const_view\ngsl_matrix_ulong_const_column (const gsl_matrix_ulong * m,\n                               const size_t j);\n\nGSL_EXPORT\n_gsl_vector_ulong_const_view\ngsl_matrix_ulong_const_diagonal (const gsl_matrix_ulong * m);\n\nGSL_EXPORT\n_gsl_vector_ulong_const_view\ngsl_matrix_ulong_const_subdiagonal (const gsl_matrix_ulong * m,\n                                    const size_t k);\n\nGSL_EXPORT\n_gsl_vector_ulong_const_view\ngsl_matrix_ulong_const_superdiagonal (const gsl_matrix_ulong * m,\n                                      const size_t k);\n\nGSL_EXPORT\n_gsl_matrix_ulong_const_view\ngsl_matrix_ulong_const_view_array (const unsigned long * base,\n                                   const size_t n1,\n                                   const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_ulong_const_view\ngsl_matrix_ulong_const_view_array_with_tda (const unsigned long * base,\n                                            const size_t n1,\n                                            const size_t n2,\n                                            const size_t tda);\n\nGSL_EXPORT\n_gsl_matrix_ulong_const_view\ngsl_matrix_ulong_const_view_vector (const gsl_vector_ulong * v,\n                                    const size_t n1,\n                                    const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_ulong_const_view\ngsl_matrix_ulong_const_view_vector_with_tda (const gsl_vector_ulong * v,\n                                             const size_t n1,\n                                             const size_t n2,\n                                             const size_t tda);\n\n/* Operations */\n\nGSL_EXPORT unsigned long   gsl_matrix_ulong_get(const gsl_matrix_ulong * m, const size_t i, const size_t j);\nGSL_EXPORT void    gsl_matrix_ulong_set(gsl_matrix_ulong * m, const size_t i, const size_t j, const unsigned long x);\n\nGSL_EXPORT unsigned long * gsl_matrix_ulong_ptr(gsl_matrix_ulong * m, const size_t i, const size_t j);\nGSL_EXPORT const unsigned long * gsl_matrix_ulong_const_ptr(const gsl_matrix_ulong * m, const size_t i, const size_t j);\n\nGSL_EXPORT void gsl_matrix_ulong_set_zero (gsl_matrix_ulong * m);\nGSL_EXPORT void gsl_matrix_ulong_set_identity (gsl_matrix_ulong * m);\nGSL_EXPORT void gsl_matrix_ulong_set_all (gsl_matrix_ulong * m, unsigned long x);\n\nGSL_EXPORT int gsl_matrix_ulong_fread (FILE * stream, gsl_matrix_ulong * m) ;\nGSL_EXPORT int gsl_matrix_ulong_fwrite (FILE * stream, const gsl_matrix_ulong * m) ;\nGSL_EXPORT int gsl_matrix_ulong_fscanf (FILE * stream, gsl_matrix_ulong * m);\nGSL_EXPORT int gsl_matrix_ulong_fprintf (FILE * stream, const gsl_matrix_ulong * m, const char * format);\n\nGSL_EXPORT int gsl_matrix_ulong_memcpy(gsl_matrix_ulong * dest, const gsl_matrix_ulong * src);\nGSL_EXPORT int gsl_matrix_ulong_swap(gsl_matrix_ulong * m1, gsl_matrix_ulong * m2);\n\nGSL_EXPORT int gsl_matrix_ulong_swap_rows(gsl_matrix_ulong * m, const size_t i, const size_t j);\nGSL_EXPORT int gsl_matrix_ulong_swap_columns(gsl_matrix_ulong * m, const size_t i, const size_t j);\nGSL_EXPORT int gsl_matrix_ulong_swap_rowcol(gsl_matrix_ulong * m, const size_t i, const size_t j);\nGSL_EXPORT int gsl_matrix_ulong_transpose (gsl_matrix_ulong * m);\nGSL_EXPORT int gsl_matrix_ulong_transpose_memcpy (gsl_matrix_ulong * dest, const gsl_matrix_ulong * src);\n\nGSL_EXPORT unsigned long gsl_matrix_ulong_max (const gsl_matrix_ulong * m);\nGSL_EXPORT unsigned long gsl_matrix_ulong_min (const gsl_matrix_ulong * m);\nGSL_EXPORT void gsl_matrix_ulong_minmax (const gsl_matrix_ulong * m, unsigned long * min_out, unsigned long * max_out);\n\nGSL_EXPORT void gsl_matrix_ulong_max_index (const gsl_matrix_ulong * m, size_t * imax, size_t *jmax);\nGSL_EXPORT void gsl_matrix_ulong_min_index (const gsl_matrix_ulong * m, size_t * imin, size_t *jmin);\nGSL_EXPORT void gsl_matrix_ulong_minmax_index (const gsl_matrix_ulong * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);\n\nGSL_EXPORT int gsl_matrix_ulong_isnull (const gsl_matrix_ulong * m);\n\nGSL_EXPORT int gsl_matrix_ulong_add (gsl_matrix_ulong * a, const gsl_matrix_ulong * b);\nGSL_EXPORT int gsl_matrix_ulong_sub (gsl_matrix_ulong * a, const gsl_matrix_ulong * b);\nGSL_EXPORT int gsl_matrix_ulong_mul_elements (gsl_matrix_ulong * a, const gsl_matrix_ulong * b);\nGSL_EXPORT int gsl_matrix_ulong_div_elements (gsl_matrix_ulong * a, const gsl_matrix_ulong * b);\nGSL_EXPORT int gsl_matrix_ulong_scale (gsl_matrix_ulong * a, const double x);\nGSL_EXPORT int gsl_matrix_ulong_add_constant (gsl_matrix_ulong * a, const double x);\nGSL_EXPORT int gsl_matrix_ulong_add_diagonal (gsl_matrix_ulong * a, const double x);\n\n/***********************************************************************/\n/* The functions below are obsolete                                    */\n/***********************************************************************/\nGSL_EXPORT int gsl_matrix_ulong_get_row(gsl_vector_ulong * v, const gsl_matrix_ulong * m, const size_t i);\nGSL_EXPORT int gsl_matrix_ulong_get_col(gsl_vector_ulong * v, const gsl_matrix_ulong * m, const size_t j);\nGSL_EXPORT int gsl_matrix_ulong_set_row(gsl_matrix_ulong * m, const size_t i, const gsl_vector_ulong * v);\nGSL_EXPORT int gsl_matrix_ulong_set_col(gsl_matrix_ulong * m, const size_t j, const gsl_vector_ulong * v);\n\n/* inline functions if you are using GCC */\n\n#ifdef HAVE_INLINE\nextern inline\nunsigned long\ngsl_matrix_ulong_get(const gsl_matrix_ulong * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_VAL(\"first index out of range\", GSL_EINVAL, 0) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_VAL(\"second index out of range\", GSL_EINVAL, 0) ;\n    }\n#endif\n  return m->data[i * m->tda + j] ;\n}\n\nextern inline\nvoid\ngsl_matrix_ulong_set(gsl_matrix_ulong * m, const size_t i, const size_t j, const unsigned long x)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_VOID(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_VOID(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  m->data[i * m->tda + j] = x ;\n}\n\nextern inline\nunsigned long *\ngsl_matrix_ulong_ptr(gsl_matrix_ulong * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  return (unsigned long *) (m->data + (i * m->tda + j)) ;\n}\n\nextern inline\nconst unsigned long *\ngsl_matrix_ulong_const_ptr(const gsl_matrix_ulong * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  return (const unsigned long *) (m->data + (i * m->tda + j)) ;\n}\n\n#endif\n\n__END_DECLS\n\n#endif /* __GSL_MATRIX_ULONG_H__ */\n", "meta": {"hexsha": "00d51818981ce88ea3b2b3b7e2150358a7c22770", "size": 11748, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/gsl/include/gsl/gsl_matrix_ulong.h", "max_stars_repo_name": "dynaryu/vaws", "max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/gsl/include/gsl/gsl_matrix_ulong.h", "max_issues_repo_name": "dynaryu/vaws", "max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/gsl/include/gsl/gsl_matrix_ulong.h", "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.250728863, "max_line_length": 135, "alphanum_fraction": 0.682328907, "num_tokens": 2810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3702253786982541, "lm_q2_score": 0.02161533508674184, "lm_q1q2_score": 0.008002545618178657}}
{"text": "//! \\file openmc_driver.h\n//! Driver to initialize and run OpenMC in stages\n#ifndef ENRICO_OPENMC_DRIVER_H\n#define ENRICO_OPENMC_DRIVER_H\n\n#include \"cell_instance.h\"\n#include \"geom.h\"\n#include \"neutronics_driver.h\"\n\n#include \"openmc/tallies/tally.h\"\n#include <gsl/gsl>\n#include <mpi.h>\n\n#include <vector>\n\nnamespace enrico {\n\n//! Driver to initialize and run OpenMC in stages\nclass OpenmcDriver : public NeutronicsDriver {\npublic:\n  //! One-time initalization of OpenMC and member variables\n  //! \\param comm An existing MPI communicator used to inialize OpenMC\n  explicit OpenmcDriver(MPI_Comm comm);\n\n  //! One-time finalization of OpenMC\n  ~OpenmcDriver();\n\n  //! Create energy production tallies for a list of materials\n  //! \\param[in] materials  Indices into OpenMC's materials array\n  void create_tallies(gsl::span<int32_t> materials);\n\n  xt::xtensor<double, 1> heat_source(double power) const final;\n\n  //! Initialization required in each Picard iteration\n  void init_step() final;\n\n  //! Runs OpenMC for one Picard iteration\n  void solve_step() final;\n\n  //! Writes OpenMC output for given timestep and iteration\n  //! \\param timestep timestep index\n  //! \\param iteration iteration index\n  void write_step(int timestep, int iteration) final;\n\n  //! Finalization required in each Picard iteration\n  void finalize_step() final;\n\n  // Data\n  openmc::Tally* tally_;            //!< Fission energy deposition tally\n  int32_t index_filter_;            //!< Index in filters arrays for material filter\n  std::vector<CellInstance> cells_; //!< Array of cell instances\n};\n\n} // namespace enrico\n\n#endif // ENRICO_OPENMC_DRIVER_H\n", "meta": {"hexsha": "98e26d2d80ad91e8427c5cb46669e09487d1f000", "size": 1630, "ext": "h", "lang": "C", "max_stars_repo_path": "include/enrico/openmc_driver.h", "max_stars_repo_name": "sphamil/enrico", "max_stars_repo_head_hexsha": "7a346c14d113c0068382fdd5ae82f6c7d253c9eb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/enrico/openmc_driver.h", "max_issues_repo_name": "sphamil/enrico", "max_issues_repo_head_hexsha": "7a346c14d113c0068382fdd5ae82f6c7d253c9eb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/enrico/openmc_driver.h", "max_forks_repo_name": "sphamil/enrico", "max_forks_repo_head_hexsha": "7a346c14d113c0068382fdd5ae82f6c7d253c9eb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5964912281, "max_line_length": 84, "alphanum_fraction": 0.7349693252, "num_tokens": 393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20181322226037884, "lm_q2_score": 0.039638838108279964, "lm_q1q2_score": 0.00799964164528948}}
{"text": "#ifndef VM_CODE_CODE_VIEW_H\n#define VM_CODE_CODE_VIEW_H\n\n#include <cstddef>\n#include <cstring>\n#include <cstdint>\n#include <type_traits>\n#include <array>\n#include <bitset>\n#include <optional>\n#include <variant>\n#include <algorithm>\n#include <iosfwd>\n#include <ostream>\n#include <iomanip>\n#include <gsl/span>\n#include <gsl/gsl>\n#include \"wasm_base.h\"\n\n\nnamespace wasm::opc {\n\nnamespace detail {\n\ntemplate <class It>\n[[gnu::pure]]\nstd::tuple<wasm_uint32_t, wasm_uint32_t, It> read_memory_immediate(It first, It last)\n{\n\talignas(wasm_uint32_t) char buff1[sizeof(wasm_uint32_t)];\n\talignas(wasm_uint32_t) char buff2[sizeof(wasm_uint32_t)];\n\twasm_uint32_t flags;\n\twasm_uint32_t offset;\n\tfor(auto& chr: buff1)\n\t{\n\t\tassert(first != last);\n\t\tchr = *first++;\n\t}\n\tfor(auto& chr: buff2)\n\t{\n\t\tassert(first != last);\n\t\tchr = *first++;\n\t}\n\tstd::memcpy(&flags, buff1, sizeof(flags));\n\tstd::memcpy(&offset, buff1, sizeof(offset));\n\treturn std::make_tuple(flags, offset, first);\n}\n\ntemplate <class T, class It>\n[[gnu::pure]]\nstd::pair<T, It> read_serialized_immediate(It first, It last)\n{\n\tstatic_assert(std::is_trivially_copyable_v<T>);\n\tT value;\n\talignas(T) char buff[sizeof(T)];\n\tfor(auto& chr: buff)\n\t{\n\t\tassert(first != last);\n\t\tchr = *first++;\n\t}\n\tstd::memcpy(&value, buff, sizeof(value));\n\treturn std::make_pair(value, first);\n}\n\n} /* namespace detail */\n\nstruct BadOpcodeError:\n\tpublic std::logic_error\n{\n\tBadOpcodeError(OpCode op, const char* msg):\n\t\tstd::logic_error(msg),\n\t\topcode(op)\n\t{\n\n\t}\n\t\n\tconst OpCode opcode;\n};\n\ntemplate <class It, class Visitor>\ndecltype(auto) visit_opcode(Visitor visitor, It first, It last)\n{\n\tassert(first != last);\n\tOpCode op;\n\tauto pos = first;\n\tusing value_type = typename std::iterator_traits<It>::value_type;\n\tusing underlying_type = std::underlying_type_t<OpCode>;\n\tif constexpr(not std::is_same_v<value_type, OpCode>)\n\t{\n\t\tvalue_type opcode = *pos++;\n\t\top = static_cast<OpCode>(opcode);\n\t\tassert(static_cast<value_type>(op) == opcode);\n\t}\n\telse\n\t{\n\t\top = *pos++;\n\t}\n\n\t// Handling the invalid opcode case is optional.\n\tif constexpr(std::is_invocable_v<Visitor, OpCode, std::nullopt_t>)\n\t{\n\t\tif(not opcode_exists(static_cast<underlying_type>(op)))\n\t\t{\n\t\t\treturn visitor(\n\t\t\t\tfirst, \n\t\t\t\tlast,\n\t\t\t\tpos,\n\t\t\t\top,\n\t\t\t\tBadOpcodeError(op, \"Given op is not a valid WASM opcode.\")\n\t\t\t);\n\t\t}\n\t}\n\telse\n\t{\n\t\tif(not opcode_exists(static_cast<underlying_type>(op)))\n\t\t\tassert(false);\n\t}\n\t\n\tif(op >= OpCode::I32_LOAD and op <= OpCode::I64_STORE32)\n\t{\n\t\twasm_uint32_t flags, offset;\n\t\tstd::tie(flags, offset, pos) = detail::read_memory_immediate(pos, last);\n\t\treturn visitor(first, last, pos, op, flags, offset);\n\t}\n\telse if(\n\t\t(op >= OpCode::GET_LOCAL and op <= OpCode::SET_GLOBAL)\n\t\tor (op == OpCode::CALL or op == OpCode::CALL_INDIRECT)\n\t\tor (op == OpCode::BR or op == OpCode::BR_IF)\n\t\tor (op == OpCode::ELSE)\n\t)\n\t{\n\t\twasm_uint32_t value;\n\t\tstd::tie(value, pos) = detail::read_serialized_immediate<wasm_uint32_t>(pos, last);\n\t\treturn visitor(first, last, pos, op, value);\n\t}\n\telse if(op == OpCode::BLOCK or op == OpCode::IF)\n\t{\n\t\tassert(first != last);\n\t\tLanguageType tp = static_cast<LanguageType>(*first++);\n\t\twasm_uint32_t label;\n\t\tstd::tie(label, pos) = detail::read_serialized_immediate<wasm_uint32_t>(pos, last);\n\t\treturn visitor(first, last, pos, op, tp, label);\n\t}\n\telse if(op == OpCode::LOOP)\n\t{\n\t\tassert(first != last);\n\t\tLanguageType tp = static_cast<LanguageType>(*first++);\n\t\treturn visitor(first, last, pos, op, tp);\n\t}\n\telse if(op == OpCode::BR_TABLE)\n\t{\n\t\twasm_uint32_t len;\n\t\tstd::tie(len, pos) = detail::read_serialized_immediate<wasm_uint32_t>(pos, last);\n\t\tauto base = pos;\n\t\tstd::advance(pos, (1 + len) * sizeof(wasm_uint32_t));\n\t\treturn visitor(first, last, pos, op, base, len);\n\t}\n\t\n\tswitch(op)\n\t{\n\tcase OpCode::I32_CONST: {\n\t\twasm_sint32_t v;\n\t\tstd::tie(v, pos) = detail::read_serialized_immediate<wasm_sint32_t>(pos, last);\n\t\treturn visitor(first, last, pos, op, v);\n\t\tbreak;\n\t}\n\tcase OpCode::I64_CONST: {\n\t\twasm_sint64_t v;\n\t\tstd::tie(v, pos) = detail::read_serialized_immediate<wasm_sint64_t>(pos, last);\n\t\treturn visitor(first, last, pos, op, v);\n\t\tbreak;\n\t}\n\tcase OpCode::F32_CONST: {\n\t\twasm_float32_t v;\n\t\tstd::tie(v, pos) = detail::read_serialized_immediate<wasm_float32_t>(pos, last);\n\t\treturn visitor(first, last, pos, op, v);\n\t\tbreak;\n\t}\n\tcase OpCode::F64_CONST: {\t\n\t\twasm_float64_t v;\n\t\tstd::tie(v, pos) = detail::read_serialized_immediate<wasm_float64_t>(pos, last);\n\t\treturn visitor(first, last, pos, op, v);\n\t\tbreak;\n\t}\n\tdefault:\n\t\treturn visitor(op, first, pos, last);\n\t}\n\tassert(false and \"Internal Error: All cases should have been handled by this point.\");\n}\n\nstruct MemoryImmediate:\n\tpublic std::pair<const wasm_uint32_t, const wasm_uint32_t>\n{\n\tusing std::pair<const wasm_uint32_t, const wasm_uint32_t>::pair;\n};\n\nwasm_uint32_t flags(const MemoryImmediate& immed)\n{ return immed.first; }\n\nwasm_uint32_t offset(const MemoryImmediate& immed)\n{ return immed.second; }\n\nstruct BlockImmediate:\n\tpublic std::pair<const LanguageType, const wasm_uint32_t>\n{\n\tusing std::pair<const LanguageType, const wasm_uint32_t>::pair;\n};\n\ngsl::span<const LanguageType> signature(const BlockImmediate& immed)\n{ return gsl::span<const LanguageType>(&(immed.first), 1u); }\n\nstd::size_t arity(const BlockImmediate& immed)\n{ return signature(immed).size(); }\n\nwasm_uint32_t offset(const BlockImmediate& immed)\n{ return immed.second; }\n\nstruct BranchTableImmediate\n{\n\ttemplate <class ... T>\n\tBranchTableImmediate(T&& ... args):\n\t\ttable_(std::forward<T>(args)...)\n\t{\n\t\t\n\t}\n\n\twasm_uint32_t at(wasm_uint32_t idx) const\n\t{\n\t\tidx = std::min(std::size_t(table_.size() - 1u), std::size_t(idx));\n\t\twasm_uint32_t depth;\n\t\tstd::memcpy(&depth, table_.data() + idx, sizeof(depth));\n\t\treturn depth;\n\t}\n\nprivate:\n\tconst gsl::span<const char[sizeof(wasm_uint32_t)]> table_;\n};\n\nstruct CodeView\n{\n\tstruct Iterator;\n\tusing value_type = WasmInstruction;\n\tusing pointer = WasmInstruction*;\n\tusing const_pointer = const WasmInstruction*;\n\tusing reference = WasmInstruction&;\n\tusing const_reference = WasmInstruction&;\n\tusing size_type = std::string_view::size_type;\n\tusing difference_type = std::string_view::difference_type;\n\tusing iterator = Iterator;\n\tusing const_iterator = iterator;\n\nprivate:\n\n\tstruct InstructionVisitor {\n\n\t\ttemplate <class ... T>\n\t\tWasmInstruction operator()(\n\t\t\tconst char* first,\n\t\t\tconst char* last,\n\t\t\tconst char* pos,\n\t\t\tOpCode op,\n\t\t\tT&& ... args\n\t\t)\n\t\t{\n\t\t\tassert(first < pos);\n\t\t\tassert(pos <= last);\n\t\t\treturn make_instr(\n\t\t\t\tstd::string_view(first, pos - first),\n\t\t\t\top,\n\t\t\t\tlast,\n\t\t\t\tstd::forward<T>(args)...\n\t\t\t);\n\t\t}\n\n\tprivate:\n\t\t// Overload for instructions with immediate operands\n\t\tWasmInstruction make_instr(std::string_view view, OpCode op, const char* last)\n\t\t{ return WasmInstruction(view, op, last, std::monostate()); }\n\n\t\ttemplate <\n\t\t\tclass T,\n\t\t\t/* enable overloads for the simple alternatives. */\n\t\t\tclass = std::enable_if_t<\n\t\t\t\tstd::disjunction_v<\n\t\t\t\t\tstd::is_same_v<std::decay_t<T>, wasm_uint32_t>,\n\t\t\t\t\tstd::is_same_v<std::decay_t<T>, wasm_sint32_t>,\n\t\t\t\t\tstd::is_same_v<std::decay_t<T>, wasm_sint64_t>,\n\t\t\t\t\tstd::is_same_v<std::decay_t<T>, wasm_float32_t>,\n\t\t\t\t\tstd::is_same_v<std::decay_t<T>, wasm_float64_t>\n\t\t\t\t>\n\t\t\t>\n\t\t>\n\t\tWasmInstruction make_instr(std::string_view view, OpCode op, const char* last, T&& arg)\n\t\t{ return WasmInstruction(view, op, last, std::forward<T>(arg)); }\n\n\t\t/// Loop overload\n\t\tWasmInstruction make_instr(std::string_view view, OpCode op, const char* last, LanguageType tp)\n\t\t{ return WasmInstruction(view, op, last, tp); }\n\n\t\t/// Branch table overload\n\t\tWasmInstruction make_instr(std::string_view view, OpCode op, const char* last, const char* base, wasm_uint32_t len)\n\t\t{\n\t\t\tassert(last > base);\n\t\t\tstd::size_t byte_count = base - last;\n\t\t\tstd::size_t bytes_needed = sizeof(wasm_uint32_t) * (len + 1u);\n\t\t\tassert(byte_count >= bytes_needed);\n\t\t\t// the table and 'view' should end at the same byte address\n\t\t\tassert(view.data() + view.size() == (base + (len + 1u) * sizeof(wasm_uint32_t)));\n\t\t\tusing buffer_type = const char[sizeof(wasm_uint32_t)];\n\t\t\tauto table = gsl::span<buffer_type>(reinterpret_cast<buffer_type*>(base), len + 1u);\n\t\t\treturn WasmInstruction(view, op, last, table);\n\t\t}\n\n\t\t/// Block overload\n\t\tWasmInstruction make_instr(std::string_view view, OpCode op, const char* last, LanguageType tp, wasm_uint32_t label)\n\t\t{ return WasmInstruction(view, op, last, BlockImmediate(tp, label)); }\n\n\t\t/// Memory overload\n\t\tWasmInstruction make_instr(std::string_view view, OpCode op, const char* last, wasm_uint32_t flags, wasm_uint32_t offset)\n\t\t{ return WasmInstruction(view, op, last, MemoryImmediate(flags, offset)); }\n\n\t\t/// Invalid opcode overload\n\t\t[[noreturn]]\n\t\tWasmInstruction make_instr(std::string_view, OpCode, const char*, const BadOpCodeError& err)\n\t\t{ throw err; }\n\n\t};\n\npublic:\n\t\n\tstruct Iterator {\n\t\tusing value_type = CodeView::value_type;\n\t\tusing difference_type = CodeView::difference_type;\n\t\tusing pointer = CodeView::pointer;\n\t\tusing reference = CodeView::value_type;\n\t\tusing iterator_category = std::input_iterator_tag;\n\t\t\n\t\tfriend bool operator==(const Iterator& left, const Iterator& right)\n\t\t{ return left.code_ == right.code_; }\n\t\t\n\t\tfriend bool operator!=(const Iterator& left, const Iterator& right)\n\t\t{ return not (left == right); }\n\tprivate:\n\t\tgsl::not_null<CodeView*> code_;\n\t};\n\n\tCodeView(const WasmFunction& func):\n\t\tfunction_(&func),\n\t\tcode_(code(func))\n\t{\n\t\t\n\t}\n\n\tconst WasmFunction* function() const\n\t{ return function_; }\n\n\tOpCode current_op() const\n\t{\n\t\tassert(ready());\n\t\treturn static_cast<WasmInstruction>(code_.front());\n\t}\n\n\tbool done() const\n\t{ return not code_.empty(); }\n\n\tstd::optional<WasmInstruction> next_instruction() const\n\t{\n\t\tassert(ready());\n\t\tif(code_.size() == 0)\n\t\t\treturn std::nullopt;\n\t\treturn visit_opcode(InstructionVisitor{}, code_.data(), code_.data() + code_.size());\n\t}\n\n\tconst char* pos() const\n\t{ return code_.data(); }\n\n\tvoid advance(const CodeView& other)\n\t{\n\t\tassert(function() == other.function());\n\t\tassert(ready());\n\t\tassert(code_.data() + code_.size() == other.code_.data() + other.code_.size());\n\t\tassert(code_.data() < other.code_.data());\n\t\tcode_ = other.code_;\n\t}\n\nprivate:\n\n\tbool ready() const\n\t{\n\t\tif(done())\n\t\t\treturn false;\n\t\tassert(opcode_exists(code_.front()));\n\t\treturn true;\n\t}\n\tconst WasmFunction* function_;\n\tstd::string_view code_;\n};\n\n\n} /* namespace opc */\n} /* namespace wasm */\n\n\n\n\n\n#endif /* VM_CODE_CODE_VIEW_H */\n", "meta": {"hexsha": "36136a29384c3830decc21768fbf5d5191b9ea91", "size": 10417, "ext": "h", "lang": "C", "max_stars_repo_path": "include/vm/code/CodeView.h", "max_stars_repo_name": "tvanslyke/wasm-cpp", "max_stars_repo_head_hexsha": "8a56c1706e2723ece36e3642bae9e36792dbd7b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/vm/code/CodeView.h", "max_issues_repo_name": "tvanslyke/wasm-cpp", "max_issues_repo_head_hexsha": "8a56c1706e2723ece36e3642bae9e36792dbd7b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/vm/code/CodeView.h", "max_forks_repo_name": "tvanslyke/wasm-cpp", "max_forks_repo_head_hexsha": "8a56c1706e2723ece36e3642bae9e36792dbd7b2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5945945946, "max_line_length": 123, "alphanum_fraction": 0.6959777287, "num_tokens": 2910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2942149845400438, "lm_q2_score": 0.027169232618778332, "lm_q1q2_score": 0.00799359535489872}}
{"text": "//\n// Created by robin on 2018/9/1.\n// Copyright (c) 2018 Robin. All rights reserved.\n//\n\n#pragma once\n\n#include <type_traits>\n#include <vector>\n#include <algorithm>\n#include <gsl/gsl>\n\nnamespace satz::bytes {\n\n/**\n * @brief Generate n random bytes.\n */\nstd::vector<uint8_t> make_random_bytes (int n);\n\n\n\n/**\n * @brief Given a byte sequence, return the indices of non-zero bits, regarding\n *    the bytes as a little-endian bit array with index starting at 0.\n * @param bytes\n * @post The resultant vector should be in increasing order.\n */\ntemplate <typename T>\nstd::vector<T> make_indices (gsl::span<const uint8_t> bytes) {\n  std::vector<T> d;\n  d.reserve(bytes.size() * 8);\n\n  for (int i = 0; i < bytes.size(); ++i) {\n    for (int j = 0; j < 8; ++j) {\n      if ((bytes[i] >> j) & 0x1) d.push_back(8 * i + j);\n    }\n  }\n\n  return d;\n}\n\n/**\n * @brief Given a byte sequence, join the bytes into a single object.\n *    If the number of bytes is greater than the size of T, discard extra\n *    bytes. If the number of bytes is less than the size of T, pad with\n *    leading zeros.\n * @param bytes\n * @example\n *    [0xef, 0xbe, 0xed, 0xfe] ==> 0xfeedbeef\n *    [0xed, 0xfe] ==> 0x0000feed\n *    [0xef, 0xbe, 0xed, 0xfe, 0xee] => 0xfeedbeef\n * @post The relative byte order of the result should be the same as the argument.\n */\ntemplate <typename T>\nT from_bytes (gsl::span<const uint8_t> bytes) {\n\n  static_assert(std::is_trivially_copyable_v<T>);\n  using U = std::make_unsigned_t<T>;\n  static_assert(sizeof(U) == sizeof(T));\n\n  U             ret = 0;\n  const ssize_t m   = bytes.size();\n  const ssize_t n   = sizeof(U);\n\n  std::for_each(bytes.rbegin() + std::max(m - n, ssize_t(0)),\n                bytes.rend(),\n                [&ret] (uint8_t b) {\n                  ret = (ret << 8) | b;\n                });\n\n  return static_cast<T>(ret);\n}\n\n}\n", "meta": {"hexsha": "9ab5bd6d541d1961b64c55ff5ab39920d2a7f96e", "size": 1846, "ext": "h", "lang": "C", "max_stars_repo_path": "src/bytes.h", "max_stars_repo_name": "lie-yan/rabin-fingerprint", "max_stars_repo_head_hexsha": "834d2d52e4c5967fe4b7aa6026742cc82c6bc031", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/bytes.h", "max_issues_repo_name": "lie-yan/rabin-fingerprint", "max_issues_repo_head_hexsha": "834d2d52e4c5967fe4b7aa6026742cc82c6bc031", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/bytes.h", "max_forks_repo_name": "lie-yan/rabin-fingerprint", "max_forks_repo_head_hexsha": "834d2d52e4c5967fe4b7aa6026742cc82c6bc031", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-26T11:41:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-26T11:41:15.000Z", "avg_line_length": 24.6133333333, "max_line_length": 82, "alphanum_fraction": 0.6121343445, "num_tokens": 558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24508501313237172, "lm_q2_score": 0.03258974652777031, "lm_q1q2_score": 0.007987258455739252}}
{"text": "/* vector/gsl_vector_ulong.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_VECTOR_ULONG_H__\n#define __GSL_VECTOR_ULONG_H__\n\n#if !defined( GSL_FUN )\n#  if !defined( GSL_DLL )\n#    define GSL_FUN extern\n#  elif defined( BUILD_GSL_DLL )\n#    define GSL_FUN extern __declspec(dllexport)\n#  else\n#    define GSL_FUN extern __declspec(dllimport)\n#  endif\n#endif\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_inline.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_block_ulong.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size;\n  size_t stride;\n  unsigned long *data;\n  gsl_block_ulong *block;\n  int owner;\n} \ngsl_vector_ulong;\n\ntypedef struct\n{\n  gsl_vector_ulong vector;\n} _gsl_vector_ulong_view;\n\ntypedef _gsl_vector_ulong_view gsl_vector_ulong_view;\n\ntypedef struct\n{\n  gsl_vector_ulong vector;\n} _gsl_vector_ulong_const_view;\n\ntypedef const _gsl_vector_ulong_const_view gsl_vector_ulong_const_view;\n\n\n/* Allocation */\n\nGSL_FUN gsl_vector_ulong *gsl_vector_ulong_alloc (const size_t n);\nGSL_FUN gsl_vector_ulong *gsl_vector_ulong_calloc (const size_t n);\n\nGSL_FUN gsl_vector_ulong *gsl_vector_ulong_alloc_from_block (gsl_block_ulong * b,\n                                                     const size_t offset, \n                                                     const size_t n, \n                                                     const size_t stride);\n\nGSL_FUN gsl_vector_ulong *gsl_vector_ulong_alloc_from_vector (gsl_vector_ulong * v,\n                                                      const size_t offset, \n                                                      const size_t n, \n                                                      const size_t stride);\n\nGSL_FUN void gsl_vector_ulong_free (gsl_vector_ulong * v);\n\n/* Views */\n\nGSL_FUN _gsl_vector_ulong_view \ngsl_vector_ulong_view_array (unsigned long *v, size_t n);\n\nGSL_FUN _gsl_vector_ulong_view \ngsl_vector_ulong_view_array_with_stride (unsigned long *base,\n                                         size_t stride,\n                                         size_t n);\n\nGSL_FUN _gsl_vector_ulong_const_view \ngsl_vector_ulong_const_view_array (const unsigned long *v, size_t n);\n\nGSL_FUN _gsl_vector_ulong_const_view \ngsl_vector_ulong_const_view_array_with_stride (const unsigned long *base,\n                                               size_t stride,\n                                               size_t n);\n\nGSL_FUN _gsl_vector_ulong_view \ngsl_vector_ulong_subvector (gsl_vector_ulong *v, \n                            size_t i, \n                            size_t n);\n\nGSL_FUN _gsl_vector_ulong_view \ngsl_vector_ulong_subvector_with_stride (gsl_vector_ulong *v, \n                                        size_t i,\n                                        size_t stride,\n                                        size_t n);\n\nGSL_FUN _gsl_vector_ulong_const_view \ngsl_vector_ulong_const_subvector (const gsl_vector_ulong *v, \n                                  size_t i, \n                                  size_t n);\n\nGSL_FUN _gsl_vector_ulong_const_view \ngsl_vector_ulong_const_subvector_with_stride (const gsl_vector_ulong *v, \n                                              size_t i, \n                                              size_t stride,\n                                              size_t n);\n\n/* Operations */\n\nGSL_FUN void gsl_vector_ulong_set_zero (gsl_vector_ulong * v);\nGSL_FUN void gsl_vector_ulong_set_all (gsl_vector_ulong * v, unsigned long x);\nGSL_FUN int gsl_vector_ulong_set_basis (gsl_vector_ulong * v, size_t i);\n\nGSL_FUN int gsl_vector_ulong_fread (FILE * stream, gsl_vector_ulong * v);\nGSL_FUN int gsl_vector_ulong_fwrite (FILE * stream, const gsl_vector_ulong * v);\nGSL_FUN int gsl_vector_ulong_fscanf (FILE * stream, gsl_vector_ulong * v);\nGSL_FUN int gsl_vector_ulong_fprintf (FILE * stream, const gsl_vector_ulong * v,\n                              const char *format);\n\nGSL_FUN int gsl_vector_ulong_memcpy (gsl_vector_ulong * dest, const gsl_vector_ulong * src);\n\nGSL_FUN int gsl_vector_ulong_reverse (gsl_vector_ulong * v);\n\nGSL_FUN int gsl_vector_ulong_swap (gsl_vector_ulong * v, gsl_vector_ulong * w);\nGSL_FUN int gsl_vector_ulong_swap_elements (gsl_vector_ulong * v, const size_t i, const size_t j);\n\nGSL_FUN unsigned long gsl_vector_ulong_max (const gsl_vector_ulong * v);\nGSL_FUN unsigned long gsl_vector_ulong_min (const gsl_vector_ulong * v);\nGSL_FUN void gsl_vector_ulong_minmax (const gsl_vector_ulong * v, unsigned long * min_out, unsigned long * max_out);\n\nGSL_FUN size_t gsl_vector_ulong_max_index (const gsl_vector_ulong * v);\nGSL_FUN size_t gsl_vector_ulong_min_index (const gsl_vector_ulong * v);\nGSL_FUN void gsl_vector_ulong_minmax_index (const gsl_vector_ulong * v, size_t * imin, size_t * imax);\n\nGSL_FUN int gsl_vector_ulong_add (gsl_vector_ulong * a, const gsl_vector_ulong * b);\nGSL_FUN int gsl_vector_ulong_sub (gsl_vector_ulong * a, const gsl_vector_ulong * b);\nGSL_FUN int gsl_vector_ulong_mul (gsl_vector_ulong * a, const gsl_vector_ulong * b);\nGSL_FUN int gsl_vector_ulong_div (gsl_vector_ulong * a, const gsl_vector_ulong * b);\nGSL_FUN int gsl_vector_ulong_scale (gsl_vector_ulong * a, const unsigned long x);\nGSL_FUN int gsl_vector_ulong_add_constant (gsl_vector_ulong * a, const double x);\nGSL_FUN int gsl_vector_ulong_axpby (const unsigned long alpha, const gsl_vector_ulong * x, const unsigned long beta, gsl_vector_ulong * y);\nGSL_FUN unsigned long gsl_vector_ulong_sum (const gsl_vector_ulong * a);\n\nGSL_FUN int gsl_vector_ulong_equal (const gsl_vector_ulong * u, \n                            const gsl_vector_ulong * v);\n\nGSL_FUN int gsl_vector_ulong_isnull (const gsl_vector_ulong * v);\nGSL_FUN int gsl_vector_ulong_ispos (const gsl_vector_ulong * v);\nGSL_FUN int gsl_vector_ulong_isneg (const gsl_vector_ulong * v);\nGSL_FUN int gsl_vector_ulong_isnonneg (const gsl_vector_ulong * v);\n\nGSL_FUN INLINE_DECL unsigned long gsl_vector_ulong_get (const gsl_vector_ulong * v, const size_t i);\nGSL_FUN INLINE_DECL void gsl_vector_ulong_set (gsl_vector_ulong * v, const size_t i, unsigned long x);\nGSL_FUN INLINE_DECL unsigned long * gsl_vector_ulong_ptr (gsl_vector_ulong * v, const size_t i);\nGSL_FUN INLINE_DECL const unsigned long * gsl_vector_ulong_const_ptr (const gsl_vector_ulong * v, const size_t i);\n\n#ifdef HAVE_INLINE\n\nINLINE_FUN\nunsigned long\ngsl_vector_ulong_get (const gsl_vector_ulong * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= v->size))\n    {\n      GSL_ERROR_VAL (\"index out of range\", GSL_EINVAL, 0);\n    }\n#endif\n  return v->data[i * v->stride];\n}\n\nINLINE_FUN\nvoid\ngsl_vector_ulong_set (gsl_vector_ulong * v, const size_t i, unsigned long x)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= v->size))\n    {\n      GSL_ERROR_VOID (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  v->data[i * v->stride] = x;\n}\n\nINLINE_FUN\nunsigned long *\ngsl_vector_ulong_ptr (gsl_vector_ulong * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= v->size))\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return (unsigned long *) (v->data + i * v->stride);\n}\n\nINLINE_FUN\nconst unsigned long *\ngsl_vector_ulong_const_ptr (const gsl_vector_ulong * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= v->size))\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return (const unsigned long *) (v->data + i * v->stride);\n}\n#endif /* HAVE_INLINE */\n\n__END_DECLS\n\n#endif /* __GSL_VECTOR_ULONG_H__ */\n\n\n", "meta": {"hexsha": "216b46f9e1c94481f3c1220c4b3cd00dcfce0361", "size": 8465, "ext": "h", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_vector_ulong.h", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-28T08:20:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-28T08:20:20.000Z", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_vector_ulong.h", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_vector_ulong.h", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-14T12:45:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-14T12:45:35.000Z", "avg_line_length": 34.8353909465, "max_line_length": 139, "alphanum_fraction": 0.6948611931, "num_tokens": 2030, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33111975283019596, "lm_q2_score": 0.024053555430508595, "lm_q1q2_score": 0.007964607328837423}}
{"text": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n#pragma once\n\n#include \"Data/Data.h\"\n#include <gsl/gsl>\n\n// forward declare cv::KeyPoint\nnamespace cv\n{\n    class KeyPoint;\n}\n\nnamespace mage\n{\n    struct InitializationData;\n    struct FrameData;\n    class AnalyzedImage;\n\n    class Introspector\n    {\n    public:\n        virtual ~Introspector() = default;\n\n        virtual void Introspect(const InitializationData& /*data*/) {}\n\n        virtual void IntrospectEstimatedPose(const mage::FrameId& /*frameId*/, const mage::Matrix& /*viewMatrix*/) {}\n\n        virtual void IntrospectAnalyzedImage(const mage::FrameData& /*frame*/, const mage::AnalyzedImage& /* image */) {}\n    };\n}\n", "meta": {"hexsha": "d58fbb642c8c9ba2c9e6dd3c83b10726751094f4", "size": 706, "ext": "h", "lang": "C", "max_stars_repo_path": "Core/MAGESLAM/Source/Debugging/Introspector.h", "max_stars_repo_name": "syntheticmagus/mageslam", "max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z", "max_issues_repo_path": "Core/MAGESLAM/Source/Debugging/Introspector.h", "max_issues_repo_name": "syntheticmagus/mageslam", "max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z", "max_forks_repo_path": "Core/MAGESLAM/Source/Debugging/Introspector.h", "max_forks_repo_name": "syntheticmagus/mageslam", "max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z", "avg_line_length": 21.3939393939, "max_line_length": 121, "alphanum_fraction": 0.6742209632, "num_tokens": 164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.2974699550610674, "lm_q2_score": 0.026759283573517426, "lm_q1q2_score": 0.007960082882080588}}
{"text": "#include <pygsl/utils.h>\n#include <pygsl/block_helpers.h>\n#include <pygsl/error_helpers.h>\n#include <gsl/gsl_qrng.h>\n#include <pygsl/error_helpers.h>\n#include \"qrng_module_defines.h\"\nstatic PyObject *module = NULL;\n\nstatic void\t\t\t/* generic instance destruction */\ngeneric_dealloc (PyObject *self)\n{\n  DEBUG_MESS(1, \" *** generic_dealloc %p\\n\", (void *) self);\n  PyObject_Del(self);\n}\n\n\n/*---------------------------------------------------------------------------*/\n/* encapsulation for the PyGSL_qrng_type */\ntypedef struct {\n     PyObject_HEAD\n     gsl_qrng_type * qrng_type;\n     const char * py_name; /* can not use the name here... niederreiter-*/\n} PyGSL_qrng_type;\n\n/*\nPyObject*\nqrng_type_getattr(PyGSL_qrng_type *self, char *name)\n{\n     if(strcmp(name, \"__doc__\") == 0){\n\t  return PyGSL_get_docobject_for_object(self->py_name);\n     }else{\n\t  Py_INCREF(Py_None);\n\t  return Py_None;\n     }\t  \n}\n*/\nstatic PyTypeObject PyGSL_qrng_type_pytype = {\n  PyObject_HEAD_INIT(NULL)\t/* fix up the type slot in initcrng */\n  0,\t\t\t\t/* ob_size */\n  \"PyGSL_qrng_type\",     \t/* tp_name */\n  sizeof(PyGSL_qrng_type),       /* tp_basicsize */\n  0,\t\t\t\t/* tp_itemsize */\n\n  /* standard methods */\n  (destructor)  generic_dealloc,   /* tp_dealloc  ref-count==0  */\n  (printfunc)   0,\t\t   /* tp_print    \"print x\"     */\n  (getattrfunc) 0/*qrng_type_getattr*/, /* tp_getattr  \"x.attr\"      */\n  (setattrfunc) 0,\t\t   /* tp_setattr  \"x.attr=v\"    */\n  (cmpfunc)     0,\t\t   /* tp_compare  \"x > y\"       */\n  (reprfunc)    0,                 /* tp_repr     `x`, print x  */\n\n  /* type categories */\n  0,\t\t\t\t/* tp_as_number   +,-,*,/,%,&,>>,pow...*/\n  0,\t\t\t\t/* tp_as_sequence +,[i],[i:j],len, ...*/\n  0,\t\t\t\t/* tp_as_mapping  [key], len, ...*/\n\n  /* more methods */\n  (hashfunc)     0,\t\t/* tp_hash    \"dict[x]\" */\n  (ternaryfunc)  0,             /* tp_call    \"x()\"     */\n  (reprfunc)     0,             /* tp_str     \"str(x)\"  */\n  (getattrofunc) 0,\t\t/* tp_getattro */\n  (setattrofunc) 0,\t\t/* tp_setattro */\n  0,\t\t\t\t/* tp_as_buffer */\n  0L,\t\t\t\t/* tp_flags */\n  NULL/* PyGSL_qrng_type_pytype_doc*/       /* tp_doc */\n};\n\nvoid\ncreate_qrng_types(PyObject *module)\n{\n     PyGSL_qrng_type *a_rng = NULL;\n     const gsl_qrng_type* thisRNGType, \n\t  *types[3] = {gsl_qrng_niederreiter_2, gsl_qrng_sobol, NULL};\n     const char* gsl_qrng_names[3] = {\"_qrng.niederreiter_2\", \"_qrng.sobol\", NULL};\n\t  \n     PyObject* module_dict=PyModule_GetDict(module);\n     PyObject* item = NULL;\n     int i;\n     \n     assert(module_dict);     \n     FUNC_MESS_BEGIN();\n     /* provide other rng types as subclasses of rng  */\n     for(i=0; types[i]!=NULL; i++){\n\t  thisRNGType = types[i];\n\t  a_rng =  PyObject_NEW(PyGSL_qrng_type, &PyGSL_qrng_type_pytype);\n\t  a_rng->qrng_type = (gsl_qrng_type *) thisRNGType;\n\t  item = PyString_FromString((thisRNGType)->name);\n\t  assert(item);\n\t  PyGSL_clear_name(PyString_AsString(item), PyString_Size(item));\n\t  assert(gsl_qrng_names[i]);\n\t  a_rng->py_name = gsl_qrng_names[i];\n\t  PyDict_SetItem(module_dict, item, (PyObject *) a_rng);\n\t  Py_DECREF(item);\n\t  item = NULL;\t\n\t  thisRNGType++;       \n     }\n     FUNC_MESS_END();\n}\n#define PyGSL_QRngType_Check(v) ((v)->ob_type == &PyGSL_qrng_type_pytype)\n\n/*---------------------------------------------------------------------------*/\n/* qrng */\n\nstaticforward PyTypeObject PyGSL_qrng_pytype;\n#if 1\ntypedef struct {\n  PyObject_HEAD\n  gsl_qrng * qrng;\n} PyGSL_qrng;\n#endif \nstatic void qrng_delete(PyGSL_qrng *self);\n\n\nstatic PyObject *\t\t/* on \"instance.attr\" */\nqrng_getattr (PyGSL_qrng *self, char *name);\n\nstatic PyObject *\nqrng_get(PyGSL_qrng *self, PyObject *args);\n\nstatic PyTypeObject PyGSL_qrng_pytype = {\n  PyObject_HEAD_INIT(NULL)\t/* fix up the type slot in initcrng */\n  0,\t\t\t\t/* ob_size */\n  \"PyGSL_qrng\",\t\t\t/* tp_name */\n  sizeof(PyGSL_qrng),\t        /* tp_basicsize */\n  0,\t\t\t\t/* tp_itemsize */\n\n  /* standard methods */\n  (destructor)  qrng_delete,       /* tp_dealloc  ref-count==0  */\n  (printfunc)   0,\t\t   /* tp_print    \"print x\"     */\n  (getattrfunc) qrng_getattr,       /* tp_getattr  \"x.attr\"      */\n  (setattrfunc) 0,\t\t   /* tp_setattr  \"x.attr=v\"    */\n  (cmpfunc)     0,\t\t   /* tp_compare  \"x > y\"       */\n  (reprfunc)    0,                 /* tp_repr     `x`, print x  */\n\n  /* type categories */\n  0,\t\t\t\t/* tp_as_number   +,-,*,/,%,&,>>,pow...*/\n  0,\t\t\t\t/* tp_as_sequence +,[i],[i:j],len, ...*/\n  0,\t\t\t\t/* tp_as_mapping  [key], len, ...*/\n\n  /* more methods */\n  (hashfunc)     0,\t\t/* tp_hash    \"dict[x]\" */\n  (ternaryfunc)  qrng_get,      /* tp_call    \"x()\"     */\n  (reprfunc)     0,             /* tp_str     \"str(x)\"  */\n  (getattrofunc) 0,\t\t/* tp_getattro */\n  (setattrofunc) 0,\t\t/* tp_setattro */\n  0,\t\t\t\t/* tp_as_buffer */\n  0L,\t\t\t\t/* tp_flags */\n  0\t\t/* tp_doc */\n};\n\n\n#define PyGSLQRng_Check(v) ((v)->ob_type == &PyGSL_qrng_pytype)\n\n\nPyObject *\nqrng_init(PyObject *self, PyObject *args)\n{\n     PyObject *type = NULL;\n     PyGSL_qrng *qrng = NULL;\n     int dimension;\n     assert(args);\n     if (0 == PyArg_ParseTuple(args, \"O!i:rng.__init__\", &PyGSL_qrng_type_pytype, \n\t\t\t       &type, &dimension)){\n\t  PyGSL_add_traceback(module, __FILE__, \"rng.__init__\", __LINE__ - 2);\n\t  return NULL;\n     }\n     if (dimension <= 0){\n\t  PyErr_SetString(PyExc_ValueError, \"The sample number must be positive!\");\n\t  PyGSL_add_traceback(module, __FILE__, \"qrng.__init__\", __LINE__ - 2);\n\t  return NULL;\n     }\n     qrng =  (PyGSL_qrng *) PyObject_NEW(PyGSL_qrng, &PyGSL_qrng_pytype);\n     qrng->qrng = gsl_qrng_alloc(((PyGSL_qrng_type *)type)->qrng_type, dimension);\n     return (PyObject *) qrng;\n}\n\nstatic void\nqrng_delete(PyGSL_qrng *self)\n{\n     assert(PyGSLQRng_Check(self));\n     gsl_qrng_free(self->qrng);\n     DEBUG_MESS(1, \" self %p\\n\",(void *) self);\n}\n\nstatic PyObject *\nqrng_reinit(PyGSL_qrng *self, PyObject *args)\n{\n     assert(PyGSLQRng_Check(self));\n     gsl_qrng_init(self->qrng);\n     Py_INCREF(Py_None);\n     return Py_None;\n}\n\nstatic PyObject *\nqrng_get(PyGSL_qrng *self, PyObject *args)\n{\n     int dimension = 1, lineno=0;\n     PyArrayObject *a_array;\n     PyGSL_array_index_t dims[2];\n     double *data;\n     int i;\n\n     FUNC_MESS_BEGIN();\n     assert(PyGSLQRng_Check(self));\n     if(0 == PyArg_ParseTuple(args, \"|i\", &dimension)){\n\t  goto fail;\n     }\n     if(dimension <= 0){\n\t  lineno = __LINE__ - 1;\n\t  PyErr_SetString(PyExc_ValueError, \n\t\t\t  \"The sample number must be positive!\");\n\t  goto fail;\n     }\n     dims[0] = dimension;\n     dims[1] = self->qrng->dimension;\n     DEBUG_MESS(5, \"Building return array with dimensions (%ld,%ld)\", (long)dims[0], (long)dims[1]);\n     a_array = (PyArrayObject *) PyGSL_New_Array(2, dims, PyArray_DOUBLE);\n     if(a_array == NULL){lineno = __LINE__ - 1; goto fail;}\n     DEBUG_MESS(5, \"Its strides are (%d,%d)\", a_array->strides[0], a_array->strides[1]);\n     assert((a_array->strides[1] / sizeof(double)) == 1);\n\n     for(i=0; i<dimension; i++){\n\t  DEBUG_MESS(6, \"Setting slice %d\", i);\n\t  data = (double *) (a_array->data + a_array->strides[0] * i);\n\t  DEBUG_MESS(6, \"Data at %p\", (void *) data);\n\t  gsl_qrng_get(self->qrng, data);\n     }\n\n     FUNC_MESS_END();\n     return (PyObject *) a_array;\n\n fail:\n     FUNC_MESS(\"In Fail!\");\n     PyGSL_add_traceback(module, __FILE__, \"_qrng.__attr__\",  lineno);\n     return NULL;\n}\n\nstatic PyObject *\nqrng_name(PyGSL_qrng *self, PyObject *args)\n{\n     assert(PyGSLQRng_Check(self));\n     if(0 == PyArg_ParseTuple(args, \":name\"))\n\t  return NULL;\n     return PyString_FromString(gsl_qrng_name(self->qrng));\n}\n\nstatic PyObject *\nqrng_clone(PyGSL_qrng *self, PyObject *args)\n{\n     PyGSL_qrng * qrng;\n     assert(PyGSLQRng_Check(self));\n     if(0 == PyArg_ParseTuple(args, \":clone\"))\n\t  return NULL;\n     qrng =  (PyGSL_qrng *) PyObject_NEW(PyGSL_qrng, &PyGSL_qrng_pytype);\n     qrng->qrng = gsl_qrng_clone(self->qrng);\n     return (PyObject *) qrng;\n}\n\n\nstatic struct PyMethodDef qrng_methods[] = {\n     {\"init\", (PyCFunction) qrng_reinit, METH_VARARGS, QRNG_INIT},\n     {\"get\", (PyCFunction) qrng_get, METH_VARARGS, QRNG_GET},\n     {\"name\", (PyCFunction) qrng_name, METH_VARARGS, QRNG_NAME},\n     {\"clone\", (PyCFunction) qrng_clone, METH_VARARGS, QRNG_CLONE},\n     {\"__copy__\", (PyCFunction) qrng_clone, METH_VARARGS, QRNG_CLONE},\n     {NULL, NULL}\n};\n\n\nstatic PyObject *\t\t/* on \"instance.attr\" */\nqrng_getattr (PyGSL_qrng *self, char *name){\n     PyObject *tmp = NULL;\n     assert(PyGSLQRng_Check(self));\n\n     /*\n     if(strcmp(name, \"__doc__\") == 0)\n\t  return PyGSL_get_docobject_for_object(\"qrng.qrng\");\n     */\n     tmp = Py_FindMethod(qrng_methods, (PyObject *) self, name);\n     if(NULL == tmp){\t  \n\t  PyGSL_add_traceback(module, __FILE__, \"qrng.__attr__\", __LINE__ - 1);\n\t  return NULL;\n     }\n     return tmp;\n\n}\n\nstatic PyMethodDef PyGSL_qrng_module_functions[] = {\n     {\"qrng\", qrng_init, METH_VARARGS},\n     {0, 0}\n}; \n\n\nvoid \ninit_qrng(void)\n{\n     PyObject *m;\n\n     m = Py_InitModule(\"_qrng\", PyGSL_qrng_module_functions);\n     init_pygsl();\n\n\n     assert(m);\n     create_qrng_types(m);\n     module = m;\n\n     PyGSL_qrng_type_pytype.ob_type = &PyType_Type;\n     PyGSL_qrng_pytype.ob_type = &PyType_Type;   \n\n     /*\n       {\n       PyObject *o, *s, *d;\n       d = PyModule_GetDict(m);\n\n       s = PyGSL_get_docobject_for_object(\"_qrng\");\n       if(s)\n          PyDict_SetItemString(d, \"__doc__\", s);\n\n\n     o = PyGSL_get_docobject_for_object(\"_qrng.PyGSL_qrng_type\");\n     if(o){\n\t  Py_INCREF(o);\n\t  PyGSL_qrng_type_pytype.tp_doc = PyString_AsString(o);\n     }\n     o = PyGSL_get_docobject_for_object(\"_qrng.PyGSL_qrng\");\n     if(o){\n\t  Py_INCREF(o);\n\t  PyGSL_qrng_type_pytype.tp_doc = PyString_AsString(o);\n     }\n     }\n     */\n     \n}\n", "meta": {"hexsha": "a5ce913c2b5ab2199cbf657811a7b60656cf8f07", "size": 9630, "ext": "c", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/src/qrng_module.c", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/src/qrng_module.c", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/src/qrng_module.c", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 28.8323353293, "max_line_length": 100, "alphanum_fraction": 0.6092419522, "num_tokens": 3029, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23651622568252115, "lm_q2_score": 0.0335895083105109, "lm_q1q2_score": 0.007944463728133715}}
{"text": "/* matrix/gsl_matrix_double.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_MATRIX_DOUBLE_H__\n#define __GSL_MATRIX_DOUBLE_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_inline.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_vector_double.h>\n#include <gsl/gsl_blas_types.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size1;\n  size_t size2;\n  size_t tda;\n  double * data;\n  gsl_block * block;\n  int owner;\n} gsl_matrix;\n\ntypedef struct\n{\n  gsl_matrix matrix;\n} _gsl_matrix_view;\n\ntypedef _gsl_matrix_view gsl_matrix_view;\n\ntypedef struct\n{\n  gsl_matrix matrix;\n} _gsl_matrix_const_view;\n\ntypedef const _gsl_matrix_const_view gsl_matrix_const_view;\n\n/* Allocation */\n\ngsl_matrix * \ngsl_matrix_alloc (const size_t n1, const size_t n2);\n\ngsl_matrix * \ngsl_matrix_calloc (const size_t n1, const size_t n2);\n\ngsl_matrix * \ngsl_matrix_alloc_from_block (gsl_block * b, \n                                   const size_t offset, \n                                   const size_t n1, \n                                   const size_t n2, \n                                   const size_t d2);\n\ngsl_matrix * \ngsl_matrix_alloc_from_matrix (gsl_matrix * m,\n                                    const size_t k1, \n                                    const size_t k2,\n                                    const size_t n1, \n                                    const size_t n2);\n\ngsl_vector * \ngsl_vector_alloc_row_from_matrix (gsl_matrix * m,\n                                        const size_t i);\n\ngsl_vector * \ngsl_vector_alloc_col_from_matrix (gsl_matrix * m,\n                                        const size_t j);\n\nvoid gsl_matrix_free (gsl_matrix * m);\n\n/* Views */\n\n_gsl_matrix_view \ngsl_matrix_submatrix (gsl_matrix * m, \n                            const size_t i, const size_t j, \n                            const size_t n1, const size_t n2);\n\n_gsl_vector_view \ngsl_matrix_row (gsl_matrix * m, const size_t i);\n\n_gsl_vector_view \ngsl_matrix_column (gsl_matrix * m, const size_t j);\n\n_gsl_vector_view \ngsl_matrix_diagonal (gsl_matrix * m);\n\n_gsl_vector_view \ngsl_matrix_subdiagonal (gsl_matrix * m, const size_t k);\n\n_gsl_vector_view \ngsl_matrix_superdiagonal (gsl_matrix * m, const size_t k);\n\n_gsl_vector_view\ngsl_matrix_subrow (gsl_matrix * m, const size_t i,\n                         const size_t offset, const size_t n);\n\n_gsl_vector_view\ngsl_matrix_subcolumn (gsl_matrix * m, const size_t j,\n                            const size_t offset, const size_t n);\n\n_gsl_matrix_view\ngsl_matrix_view_array (double * base,\n                             const size_t n1, \n                             const size_t n2);\n\n_gsl_matrix_view\ngsl_matrix_view_array_with_tda (double * base, \n                                      const size_t n1, \n                                      const size_t n2,\n                                      const size_t tda);\n\n\n_gsl_matrix_view\ngsl_matrix_view_vector (gsl_vector * v,\n                              const size_t n1, \n                              const size_t n2);\n\n_gsl_matrix_view\ngsl_matrix_view_vector_with_tda (gsl_vector * v,\n                                       const size_t n1, \n                                       const size_t n2,\n                                       const size_t tda);\n\n\n_gsl_matrix_const_view \ngsl_matrix_const_submatrix (const gsl_matrix * m, \n                                  const size_t i, const size_t j, \n                                  const size_t n1, const size_t n2);\n\n_gsl_vector_const_view \ngsl_matrix_const_row (const gsl_matrix * m, \n                            const size_t i);\n\n_gsl_vector_const_view \ngsl_matrix_const_column (const gsl_matrix * m, \n                               const size_t j);\n\n_gsl_vector_const_view\ngsl_matrix_const_diagonal (const gsl_matrix * m);\n\n_gsl_vector_const_view \ngsl_matrix_const_subdiagonal (const gsl_matrix * m, \n                                    const size_t k);\n\n_gsl_vector_const_view \ngsl_matrix_const_superdiagonal (const gsl_matrix * m, \n                                      const size_t k);\n\n_gsl_vector_const_view\ngsl_matrix_const_subrow (const gsl_matrix * m, const size_t i,\n                               const size_t offset, const size_t n);\n\n_gsl_vector_const_view\ngsl_matrix_const_subcolumn (const gsl_matrix * m, const size_t j,\n                                  const size_t offset, const size_t n);\n\n_gsl_matrix_const_view\ngsl_matrix_const_view_array (const double * base,\n                                   const size_t n1, \n                                   const size_t n2);\n\n_gsl_matrix_const_view\ngsl_matrix_const_view_array_with_tda (const double * base, \n                                            const size_t n1, \n                                            const size_t n2,\n                                            const size_t tda);\n\n_gsl_matrix_const_view\ngsl_matrix_const_view_vector (const gsl_vector * v,\n                                    const size_t n1, \n                                    const size_t n2);\n\n_gsl_matrix_const_view\ngsl_matrix_const_view_vector_with_tda (const gsl_vector * v,\n                                             const size_t n1, \n                                             const size_t n2,\n                                             const size_t tda);\n\n/* Operations */\n\nvoid gsl_matrix_set_zero (gsl_matrix * m);\nvoid gsl_matrix_set_identity (gsl_matrix * m);\nvoid gsl_matrix_set_all (gsl_matrix * m, double x);\n\nint gsl_matrix_fread (FILE * stream, gsl_matrix * m) ;\nint gsl_matrix_fwrite (FILE * stream, const gsl_matrix * m) ;\nint gsl_matrix_fscanf (FILE * stream, gsl_matrix * m);\nint gsl_matrix_fprintf (FILE * stream, const gsl_matrix * m, const char * format);\n \nint gsl_matrix_memcpy(gsl_matrix * dest, const gsl_matrix * src);\nint gsl_matrix_swap(gsl_matrix * m1, gsl_matrix * m2);\nint gsl_matrix_tricpy(CBLAS_UPLO_t Uplo, CBLAS_DIAG_t Diag, gsl_matrix * dest, const gsl_matrix * src);\n\nint gsl_matrix_swap_rows(gsl_matrix * m, const size_t i, const size_t j);\nint gsl_matrix_swap_columns(gsl_matrix * m, const size_t i, const size_t j);\nint gsl_matrix_swap_rowcol(gsl_matrix * m, const size_t i, const size_t j);\nint gsl_matrix_transpose (gsl_matrix * m);\nint gsl_matrix_transpose_memcpy (gsl_matrix * dest, const gsl_matrix * src);\nint gsl_matrix_transpose_tricpy (CBLAS_UPLO_t Uplo_src, CBLAS_DIAG_t Diag, gsl_matrix * dest, const gsl_matrix * src);\n\ndouble gsl_matrix_max (const gsl_matrix * m);\ndouble gsl_matrix_min (const gsl_matrix * m);\nvoid gsl_matrix_minmax (const gsl_matrix * m, double * min_out, double * max_out);\n\nvoid gsl_matrix_max_index (const gsl_matrix * m, size_t * imax, size_t *jmax);\nvoid gsl_matrix_min_index (const gsl_matrix * m, size_t * imin, size_t *jmin);\nvoid gsl_matrix_minmax_index (const gsl_matrix * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);\n\nint gsl_matrix_equal (const gsl_matrix * a, const gsl_matrix * b);\n\nint gsl_matrix_isnull (const gsl_matrix * m);\nint gsl_matrix_ispos (const gsl_matrix * m);\nint gsl_matrix_isneg (const gsl_matrix * m);\nint gsl_matrix_isnonneg (const gsl_matrix * m);\n\ndouble gsl_matrix_norm1 (const gsl_matrix * m);\n\nint gsl_matrix_add (gsl_matrix * a, const gsl_matrix * b);\nint gsl_matrix_sub (gsl_matrix * a, const gsl_matrix * b);\nint gsl_matrix_mul_elements (gsl_matrix * a, const gsl_matrix * b);\nint gsl_matrix_div_elements (gsl_matrix * a, const gsl_matrix * b);\nint gsl_matrix_scale (gsl_matrix * a, const double x);\nint gsl_matrix_scale_rows (gsl_matrix * a, const gsl_vector * x);\nint gsl_matrix_scale_columns (gsl_matrix * a, const gsl_vector * x);\nint gsl_matrix_add_constant (gsl_matrix * a, const double x);\nint gsl_matrix_add_diagonal (gsl_matrix * a, const double x);\n\n/***********************************************************************/\n/* The functions below are obsolete                                    */\n/***********************************************************************/\nint gsl_matrix_get_row(gsl_vector * v, const gsl_matrix * m, const size_t i);\nint gsl_matrix_get_col(gsl_vector * v, const gsl_matrix * m, const size_t j);\nint gsl_matrix_set_row(gsl_matrix * m, const size_t i, const gsl_vector * v);\nint gsl_matrix_set_col(gsl_matrix * m, const size_t j, const gsl_vector * v);\n/***********************************************************************/\n\n/* inline functions if you are using GCC */\n\nINLINE_DECL double   gsl_matrix_get(const gsl_matrix * m, const size_t i, const size_t j);\nINLINE_DECL void    gsl_matrix_set(gsl_matrix * m, const size_t i, const size_t j, const double x);\nINLINE_DECL double * gsl_matrix_ptr(gsl_matrix * m, const size_t i, const size_t j);\nINLINE_DECL const double * gsl_matrix_const_ptr(const gsl_matrix * m, const size_t i, const size_t j);\n\n#ifdef HAVE_INLINE\nINLINE_FUN \ndouble\ngsl_matrix_get(const gsl_matrix * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_VAL(\"first index out of range\", GSL_EINVAL, 0) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_VAL(\"second index out of range\", GSL_EINVAL, 0) ;\n        }\n    }\n#endif\n  return m->data[i * m->tda + j] ;\n} \n\nINLINE_FUN \nvoid\ngsl_matrix_set(gsl_matrix * m, const size_t i, const size_t j, const double x)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_VOID(\"first index out of range\", GSL_EINVAL) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_VOID(\"second index out of range\", GSL_EINVAL) ;\n        }\n    }\n#endif\n  m->data[i * m->tda + j] = x ;\n}\n\nINLINE_FUN \ndouble *\ngsl_matrix_ptr(gsl_matrix * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n        }\n    }\n#endif\n  return (double *) (m->data + (i * m->tda + j)) ;\n} \n\nINLINE_FUN \nconst double *\ngsl_matrix_const_ptr(const gsl_matrix * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n        }\n    }\n#endif\n  return (const double *) (m->data + (i * m->tda + j)) ;\n} \n\n#endif\n\n__END_DECLS\n\n#endif /* __GSL_MATRIX_DOUBLE_H__ */\n", "meta": {"hexsha": "c54fa59f11e354878d16cb3d30298a9ae5adedb7", "size": 11575, "ext": "h", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/matrix/gsl_matrix_double.h", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/matrix/gsl_matrix_double.h", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/matrix/gsl_matrix_double.h", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 32.3324022346, "max_line_length": 118, "alphanum_fraction": 0.625399568, "num_tokens": 2835, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.26284183737131667, "lm_q2_score": 0.03021459034211049, "lm_q1q2_score": 0.00794165844094196}}
{"text": "#ifndef DEGNOME\r\n#define DEGNOME\r\n\r\n#include <stdlib.h>\r\n#include <gsl/gsl_rng.h>\r\n#include <gsl/gsl_randist.h>\r\n\r\n//Degnomedia Rogerus\r\ntypedef struct Degnome Degnome;\r\nstruct Degnome {\r\n\tdouble* dna_array;\r\n\tdouble hat_size;\r\n\r\n};\r\n\r\nDegnome* Degnome_new(void);\r\nvoid Degnome_mate(Degnome* location, Degnome* p1, Degnome* p2, gsl_rng* rng,\r\n\tint mutation_rate, int mutation_effect, int crossover_rate);\r\nvoid Degnome_free(Degnome* q);\r\n\r\nint chrom_size;\r\n\r\n#endif", "meta": {"hexsha": "4e53e2a7e21ead866a8be37683f675daf73e8294", "size": 465, "ext": "h", "lang": "C", "max_stars_repo_path": "src/degnome.h", "max_stars_repo_name": "Darokrithia/PolygenSim", "max_stars_repo_head_hexsha": "4ef91b1d3cf00d9caca6c4fa2fb5c401a0f8d191", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-08-14T20:45:40.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-01T18:53:36.000Z", "max_issues_repo_path": "src/degnome.h", "max_issues_repo_name": "Darokrithia/PopGenSim", "max_issues_repo_head_hexsha": "4ef91b1d3cf00d9caca6c4fa2fb5c401a0f8d191", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2019-09-17T20:12:17.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T23:56:03.000Z", "max_forks_repo_path": "src/degnome.h", "max_forks_repo_name": "Darokrithia/PolygenSim", "max_forks_repo_head_hexsha": "4ef91b1d3cf00d9caca6c4fa2fb5c401a0f8d191", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-27T23:28:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-27T23:28:50.000Z", "avg_line_length": 20.2173913043, "max_line_length": 77, "alphanum_fraction": 0.7311827957, "num_tokens": 125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.28776781576105315, "lm_q2_score": 0.02758527932886559, "lm_q1q2_score": 0.007938155579626181}}
{"text": "/*\n *  A rng module implementation which can return a sample as an array.\n *  Author : Pierre Schnizer <schnizer@users.sourceforge.net>\n *  Date   : 1. July. 2003\n *\n */\n\n#include <pygsl/error_helpers.h>\n#include <pygsl/block_helpers.h>\n#include <pygsl/utils.h>\n\n#ifdef PyGSL_NO_IMPORT_API\n#undef PyGSL_NO_IMPORT_API\n#endif\n#include <pygsl/rng_helpers.h>\n#include <pygsl/rng.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n\n/*\n * All doc strings\n */\nstatic PyObject *module = NULL;\n\n#include \"rng_helpers.c\"\n#include \"rngmodule_docs.h\"\n\n\nstatic void rng_delete(PyGSL_rng *self);\nstatic PyObject * rng_call(PyGSL_rng *self, PyObject *args);\n\n#undef PyGSL_RNG_Check\n\n#define PyGSL_RNG_Check(op) ((op)->ob_type == &PyGSL_rng_pytype)\n\nstatic PyObject *\t\t/* on \"instance.attr\" */\nrng_getattr (PyGSL_rng *self, char *name);\n\n\nPyTypeObject PyGSL_rng_pytype = {\n  PyObject_HEAD_INIT(NULL)\t/* fix up the type slot in initcrng */\n  0,\t\t\t\t/* ob_size */\n  \"PyGSL_rng\",\t\t\t/* tp_name */\n  sizeof(PyGSL_rng),\t        /* tp_basicsize */\n  0,\t\t\t\t/* tp_itemsize */\n\n  /* standard methods */\n  (destructor)  rng_delete,       /* tp_dealloc  ref-count==0  */\n  (printfunc)   0,\t\t   /* tp_print    \"print x\"     */\n  (getattrfunc) rng_getattr,       /* tp_getattr  \"x.attr\"      */\n  (setattrfunc) 0,\t\t   /* tp_setattr  \"x.attr=v\"    */\n  (cmpfunc)     0,\t\t   /* tp_compare  \"x > y\"       */\n  (reprfunc)    0,                 /* tp_repr     `x`, print x  */\n\n  /* type categories */\n  0,\t\t\t\t/* tp_as_number   +,-,*,/,%,&,>>,pow...*/\n  0,\t\t\t\t/* tp_as_sequence +,[i],[i:j],len, ...*/\n  0,\t\t\t\t/* tp_as_mapping  [key], len, ...*/\n\n  /* more methods */\n  (hashfunc)     0,\t\t/* tp_hash    \"dict[x]\" */\n  (ternaryfunc)  rng_call,      /* tp_call    \"x()\"     */\n  (reprfunc)     0,             /* tp_str     \"str(x)\"  */\n  (getattrofunc) 0,\t\t/* tp_getattro */\n  (setattrofunc) 0,\t\t/* tp_setattro */\n  0,\t\t\t\t/* tp_as_buffer */\n  0L,\t\t\t\t/* tp_flags */\n  rng_type_doc\t\t/* tp_doc */\n};\n\n\n\n\n\nstatic PyObject *\nPyGSL_rng_init(PyObject *self, PyObject *args, const gsl_rng_type * rng_type)\n{\n\n     PyGSL_rng *rng = NULL;\n\n     FUNC_MESS_BEGIN();\n     rng =  (PyGSL_rng *) PyObject_NEW(PyGSL_rng, &PyGSL_rng_pytype);\n     if(rng == NULL){\n\t  return NULL;\n     }\n     if(rng_type == NULL){\n\t  rng->rng = gsl_rng_alloc(gsl_rng_default);\n\t  gsl_rng_set(rng->rng, gsl_rng_default_seed);\n     }else{\n\t  rng->rng = gsl_rng_alloc(rng_type);\n     }\n     FUNC_MESS_END();\n     return (PyObject *) rng;\n}\n\n#define RNG_ARNG(name)                                                       \\\nstatic PyObject* PyGSL_rng_init_ ## name (PyObject *self, PyObject *args)    \\\n{                                                                            \\\n     PyObject *tmp = NULL;                                                   \\\n     FUNC_MESS_BEGIN();                                                      \\\n     tmp = PyGSL_rng_init(self, args,  gsl_rng_ ## name);                    \\\n     if (tmp == NULL){                                                       \\\n\t  PyGSL_add_traceback(module, __FILE__, __FUNCTION__, __LINE__);     \\\n     }                                                                       \\\n     FUNC_MESS_END();                                                        \\\n     return tmp;                                                             \\\n}\n\n#include \"rng_list.h\"\n\nstatic PyObject *\nPyGSL_rng_init_default(PyObject *self, PyObject *args)              \n{                                                                    \n     PyObject *tmp = NULL;                                           \n     FUNC_MESS_BEGIN();                                              \n     tmp = PyGSL_rng_init(self, args,  NULL);            \n     if (tmp == NULL){                                               \n\t  PyGSL_add_traceback(module, __FILE__, __FUNCTION__, __LINE__ - 1);\n     }                                                               \n     FUNC_MESS_END();                                                \n     return tmp;                                                     \n}\n\n\nstatic void\nrng_delete(PyGSL_rng *self)\n{\n     FUNC_MESS_BEGIN();\n     assert(PyGSL_RNG_Check(self));\n     if(self->rng != NULL){\n\t  DEBUG_MESS(5, \"Freeing gsl_rng @ %p\", self->rng);\n\t  gsl_rng_free(self->rng);\n\t  self->rng = NULL;\n     }\n     DEBUG_MESS(1, \" self %p\\n\",(void *) self);\n     PyObject_Del(self);\n     self = NULL;\n     FUNC_MESS_END();\n}\n\nstatic PyObject *\t\t/* on \"instance.uniform()\" and \"instance()\" */\nrng_call (PyGSL_rng *self, PyObject *args)\n{\n     PyObject *tmp;\n\n     FUNC_MESS_BEGIN();\n     assert(PyGSL_RNG_Check(self));\n     tmp = PyGSL_rng_to_double(self, args, gsl_rng_uniform);\n     if(!tmp)\n\t  PyGSL_add_traceback(module, __FILE__, \"rng.__call__\", __LINE__ - 2);\n     FUNC_MESS_END();\n     return tmp;\n}\n\nstatic PyObject *\nrng_uniform_pos (PyGSL_rng *self, PyObject *args)\n{\n     PyObject *tmp;\n\n     FUNC_MESS_BEGIN();\n     assert(PyGSL_RNG_Check(self));\n     tmp = PyGSL_rng_to_double(self, args, gsl_rng_uniform_pos);\n     if(!tmp)\n\t  PyGSL_add_traceback(module, __FILE__, \"rng.uniform_pos\", __LINE__-2);\n     FUNC_MESS_END();\n     return tmp;\n}\n\nstatic PyObject *\nrng_uniform_int (PyGSL_rng *self, PyObject *args)\n{\n     PyObject *tmp = NULL;\n\n     FUNC_MESS_BEGIN();\n     assert(PyGSL_RNG_Check(self));\n     tmp = PyGSL_rng_ul_to_ulong(self, args, gsl_rng_uniform_int);\n     if(!tmp)\n\t  PyGSL_add_traceback(module, __FILE__, \"rng.uniform_int\", __LINE__-2);\n     FUNC_MESS_END();\n     return tmp;\n}\n\n\n\nstatic PyObject *\nrng_get(PyGSL_rng *self, PyObject *args)\n{\n     PyObject  *tmp = NULL;\n\n     FUNC_MESS_BEGIN();\n     assert(PyGSL_RNG_Check(self));\n     tmp = PyGSL_rng_to_ulong(self, args, gsl_rng_get);\n     if(!tmp)\n\t  PyGSL_add_traceback(module, __FILE__, \"rng.get\", __LINE__ - 2);\n     FUNC_MESS_END();\n     return tmp;\n}\n\nstatic PyObject *\nrng_set(PyGSL_rng *self, PyObject *args)\n{\n     PyObject *tmp = NULL, *seed = NULL;\n     unsigned long int useed;\n     int lineno;\n\n     FUNC_MESS_BEGIN();\n     assert(PyGSL_RNG_Check(self));\n     if(0 == PyArg_ParseTuple(args, \"O\", &tmp)){\n\t  lineno = __LINE__; goto fail;\n     }\n     assert(tmp != NULL);\n     seed = PyNumber_Long(tmp);\n     if(!seed){lineno = __LINE__ - 1; goto fail;}\n     useed =  PyLong_AsUnsignedLong(seed);\n     gsl_rng_set(self->rng, useed);\n     \n     Py_INCREF(Py_None);\n     FUNC_MESS_END();\n     return Py_None;\n\n fail:\n     FUNC_MESS(\"FAIL\");\n     PyGSL_add_traceback(module, __FILE__, \"rng.set\", lineno);\n     return NULL;\n}\n\nstatic PyObject *\nrng_name(PyGSL_rng *self, PyObject *args)\n{\n     PyObject *tmp = NULL;\n     FUNC_MESS_BEGIN();\n     assert(PyGSL_RNG_Check(self));\n     if(0 == PyArg_ParseTuple(args, \":name\"))\n\t  return NULL;\n     tmp = PyString_FromString(gsl_rng_name(self->rng));\n     FUNC_MESS_END();\n     return tmp;\n}\n\nstatic PyObject *\nrng_max(PyGSL_rng *self, PyObject *args)\n{\n     PyObject *tmp = NULL;\n     FUNC_MESS_BEGIN();\n     assert(PyGSL_RNG_Check(self));\n     if(0 == PyArg_ParseTuple(args, \":max\"))\n\t  return NULL;\n     tmp = PyLong_FromUnsignedLong(gsl_rng_max(self->rng));\n     FUNC_MESS_END();\n     return tmp;\n}\n\nstatic PyObject *\nrng_min(PyGSL_rng *self, PyObject *args)\n{\n     PyObject *tmp = NULL;\n     FUNC_MESS_BEGIN();\n     assert(PyGSL_RNG_Check(self));\n     if(0 == PyArg_ParseTuple(args, \":min\"))\n\t  return NULL;\n     tmp = PyLong_FromUnsignedLong(gsl_rng_min(self->rng));\n     FUNC_MESS_END();\n     return tmp;\n}\n\nstatic PyObject *\nrng_clone(PyGSL_rng *self, PyObject *args)\n{\n     PyGSL_rng * rng = NULL;\n\n     FUNC_MESS_BEGIN();\n     assert(PyGSL_RNG_Check(self));\n     if(0 == PyArg_ParseTuple(args, \":clone\"))\n\t  return NULL;\n     rng =  (PyGSL_rng *) PyObject_NEW(PyGSL_rng, &PyGSL_rng_pytype);\n     rng->rng = gsl_rng_clone(self->rng);\n     FUNC_MESS_END();\n     return (PyObject *) rng;\n}\n\n/*\n * Is #name a standard macro definition?\n */\n#define RNG_DISTRIBUTION(name, function)                                     \\\nstatic PyObject* rng_ ## name (PyGSL_rng *self, PyObject *args)              \\\n{                                                                            \\\n     PyObject *tmp = NULL;                                                   \\\n     FUNC_MESS_BEGIN();                                                      \\\n     tmp = PyGSL_rng_ ## function (self, args,  gsl_ran_ ## name);           \\\n     if (tmp == NULL){                                                       \\\n       /* PyGSL_add_traceback(module, __FILE__, \"rng.\" #name, __LINE__); */  \\\n\t  PyGSL_add_traceback(module, __FILE__, __FUNCTION__, __LINE__);     \\\n     }                                                                       \\\n     FUNC_MESS_END();                                                        \\\n     return tmp;                                                             \\\n}\n\n#include \"rng_distributions.h\"\n\n/* Redefine to trigger emacs into correct coloring */\n/*\n * This list is not optimized. I guess... Do you know how to optimize it?\n */\nstatic struct PyMethodDef rng_methods[] = {\n  {\"get\", (PyCFunction) rng_get, METH_VARARGS, rng_get_doc},\n  {\"set\", (PyCFunction) rng_set, METH_VARARGS, rng_set_doc},\n  {\"uniform\", (PyCFunction) rng_call, METH_VARARGS, rng_uniform_doc},\n  {\"uniform_pos\", (PyCFunction) rng_uniform_pos, METH_VARARGS, rng_uniform_pos_doc},\n  {\"uniform_int\", (PyCFunction) rng_uniform_int, METH_VARARGS, rng_uniform_int_doc},\n  {\"name\", (PyCFunction) rng_name, METH_VARARGS, NULL},\n  {\"max\", (PyCFunction) rng_max, METH_VARARGS, rng_max_doc},\n  {\"min\", (PyCFunction) rng_min, METH_VARARGS, rng_min_doc},\n  {\"clone\", (PyCFunction) rng_clone, METH_VARARGS, rng_clone_doc},\n#if  (PY_MAJOR_VERSION == 2) && (PY_MINOR_VERSION == 3)\n  /* RNG clone can not be used to copy a rng type in python 2.3 No idea how to do that correctly */\n#else\n  {\"__copy__\", (PyCFunction) rng_clone, METH_VARARGS, rng_clone_doc},\n#endif\n  /* distributions */\n  {\"gaussian\", (PyCFunction) rng_gaussian,METH_VARARGS, rng_gaussian_doc},\n  {\"gaussian_ratio_method\", (PyCFunction) rng_gaussian_ratio_method,METH_VARARGS, rng_gaussian_ratio_doc},\n  {\"ugaussian\", (PyCFunction) rng_ugaussian,METH_VARARGS, rng_ugaussian_doc},\n  {\"ugaussian_ratio_method\",(PyCFunction) rng_ugaussian_ratio_method,METH_VARARGS, rng_ugaussian_ratio_doc},\n  {\"gaussian_tail\", (PyCFunction) rng_gaussian_tail,METH_VARARGS, rng_gaussian_tail_doc},\n  {\"ugaussian_tail\",(PyCFunction) rng_ugaussian_tail,METH_VARARGS, rng_ugaussian_tail_doc},\n  {\"bivariate_gaussian\", (PyCFunction) rng_bivariate_gaussian,METH_VARARGS, rng_bivariate_gaussian_doc},\n  {\"exponential\",(PyCFunction)rng_exponential,METH_VARARGS, rng_exponential_doc},\n  {\"laplace\",(PyCFunction)rng_laplace,METH_VARARGS, rng_laplace_doc},\n  {\"exppow\",(PyCFunction)rng_exppow,METH_VARARGS, rng_exppow_doc},\n  {\"cauchy\",(PyCFunction)rng_cauchy,METH_VARARGS, rng_cauchy_doc},\n  {\"rayleigh\",(PyCFunction)rng_rayleigh,METH_VARARGS, rng_rayleigh_doc},\n  {\"rayleigh_tail\",(PyCFunction)rng_rayleigh_tail,METH_VARARGS, rng_rayleigh_tail_doc},\n  {\"levy\",(PyCFunction)rng_levy,METH_VARARGS, rng_levy_doc},\n  {\"levy_skew\",(PyCFunction)rng_levy_skew,METH_VARARGS, rng_levy_skew_doc},\n  {\"gamma\",(PyCFunction)rng_gamma,METH_VARARGS, rng_gamma_doc},\n  {\"gamma_int\",(PyCFunction)rng_gamma_int,METH_VARARGS, NULL},\n  {\"flat\",(PyCFunction)rng_flat,METH_VARARGS, rng_flat_doc},\n  {\"lognormal\",(PyCFunction)rng_lognormal,METH_VARARGS, rng_lognormal_doc},\n  {\"chisq\",(PyCFunction)rng_chisq,METH_VARARGS, rng_chisq_doc},\n  {\"fdist\",(PyCFunction)rng_fdist,METH_VARARGS, rng_fdist_doc},\n  {\"tdist\",(PyCFunction)rng_tdist,METH_VARARGS, rng_tdist_doc},\n  {\"beta\",(PyCFunction)rng_beta,METH_VARARGS, rng_beta_doc},\n  {\"logistic\",(PyCFunction)rng_logistic,METH_VARARGS, rng_logistic_doc},\n  {\"pareto\",(PyCFunction)rng_pareto,METH_VARARGS, rng_pareto_doc},\n  {\"dir_2d\",(PyCFunction)rng_dir_2d,METH_VARARGS, rng_dir_2d_doc},\n  {\"dir_2d_trig_method\",(PyCFunction)rng_dir_2d_trig_method,METH_VARARGS, rng_dir_2d_trig_method_doc},\n  {\"dir_3d\",(PyCFunction)rng_dir_3d,METH_VARARGS, rng_dir_3d_doc},\n  {\"dir_nd\",(PyCFunction)rng_dir_nd,METH_VARARGS, rng_dir_nd_doc},\n  {\"weibull\",(PyCFunction)rng_weibull,METH_VARARGS, rng_weibull_doc},\n  {\"gumbel1\",(PyCFunction)rng_gumbel1,METH_VARARGS, rng_gumbel1_doc},\n  {\"gumbel2\",(PyCFunction)rng_gumbel2,METH_VARARGS, rng_gumbel2_doc},\n  {\"poisson\",(PyCFunction)rng_poisson,METH_VARARGS, rng_poisson_doc},\n  {\"bernoulli\",(PyCFunction)rng_bernoulli,METH_VARARGS, rng_bernoulli_doc},\n  {\"binomial\",(PyCFunction)rng_binomial,METH_VARARGS, rng_binomial_doc},\n  {\"negative_binomial\",(PyCFunction)rng_negative_binomial,METH_VARARGS, rng_negative_binomial_doc},\n  {\"pascal\",(PyCFunction)rng_pascal,METH_VARARGS, rng_pascal_doc},\n  {\"geometric\",(PyCFunction)rng_geometric,METH_VARARGS, rng_geometric_doc},\n  {\"hypergeometric\",(PyCFunction)rng_hypergeometric,METH_VARARGS, rng_hypergeometric_doc},\n  {\"logarithmic\",(PyCFunction)rng_logarithmic,METH_VARARGS, rng_logarithmic_doc},\n  {\"landau\",(PyCFunction)rng_landau,METH_VARARGS, rng_landau_doc},\n  {\"erlang\",(PyCFunction)rng_erlang,METH_VARARGS, NULL},  \n  {\"multinomial\",(PyCFunction)rng_multinomial,METH_VARARGS, multinomial_doc},\n  {\"dirichlet\",(PyCFunction)rng_dirichlet,METH_VARARGS, rng_dirichlet_doc},\n  {NULL, NULL,}\n};\n\nstatic PyObject *\nrng_getattr(PyGSL_rng *self, char *name)\n{\n     PyObject *tmp = NULL;\n\n     FUNC_MESS_BEGIN();\n     assert(PyGSL_RNG_Check(self));\n \n     tmp = Py_FindMethod(rng_methods, (PyObject *) self, name);\n     if(NULL == tmp){\t  \n\t  PyGSL_add_traceback(module, __FILE__, \"rng.__attr__\", __LINE__ - 1);\n\t  return NULL;\n     }\n     return tmp;\n}\n\n\nstatic PyObject *\nrng_create_list(PyObject *self, PyObject *args)\n{\n     const gsl_rng_type** thisRNGType=gsl_rng_types_setup();\n     PyObject* list = NULL, *item=NULL;\n     \n     FUNC_MESS_BEGIN();\n     /* provide other rng types as subclasses of rng */\n\n     list = PyList_New(0);\n     while ((*thisRNGType)!=NULL) {\n\t  item = PyString_FromString((*thisRNGType)->name);\n\t  Py_INCREF(item);\n\t  assert(item);\n\t  PyGSL_clear_name(PyString_AsString(item), PyString_Size(item));\n\t  if(PyList_Append(list, item) != 0)\n\t       goto fail;\n\t  thisRNGType++;\n     }\n     FUNC_MESS_END();\n     return list;\n fail:\n     Py_XDECREF(list);\n     Py_XDECREF(item);\n     return NULL;\n}\n\n/*---------------------------------------------------------------------------*/\n/* Module set up */\n#define RNG_GENERATE_PDF\n#undef RNG_DISTRIBUTION\n#define RNG_DISTRIBUTION(name, function)                                   \\\nstatic PyObject* rng_ ## name ## _pdf (PyObject *self, PyObject *args)     \\\n{                                                                          \\\n     PyObject * tmp;                                                       \\\n     FUNC_MESS_BEGIN();                                                    \\\n     tmp =  PyGSL_pdf_ ## function (self, args, gsl_ran_ ## name ## _pdf); \\\n     if (tmp == NULL){                                                     \\\n\t  PyGSL_add_traceback(module, __FILE__, #name  \"_pdf\", __LINE__);  \\\n     }                                                                     \\\n     FUNC_MESS_END();                                                      \\\n     return tmp;                                                           \\\n}\n\n#include \"rng_distributions.h\"\n\n\nstatic PyObject* rng_dirichlet_lnpdf (PyObject *self, PyObject *args)         \n{ \n     PyObject *tmp;\n     FUNC_MESS_BEGIN();\n     tmp = PyGSL_pdf_dA_to_dA(self, args, gsl_ran_dirichlet_lnpdf); \n     FUNC_MESS_END();\n     return tmp;\n}\n\nstatic PyObject* rng_multinomial_lnpdf (PyObject *self, PyObject *args)\n{ \n     PyObject *tmp;\n     FUNC_MESS_BEGIN();\n     tmp = PyGSL_pdf_uidA_to_uiA(self, args, gsl_ran_multinomial_lnpdf);\n     FUNC_MESS_END();\n     return tmp;\n}\n\n\nstatic const char rng_env_setup_doc[] = \n\"This function reads the environment variables `GSL_RNG_TYPE' and\\n\\\n`GSL_RNG_SEED'.\\n\\\nThe environment variable `GSL_RNG_TYPE' should be the name of a\\n\\\ngenerator, such as `taus' or `mt19937'. The environment variable\\n\\\n`GSL_RNG_SEED' should contain the desired seed value. It is\\n\\\nconverted to an `unsigned long int' using the C library function\\n\\\n`strtoul'.\\n\";\n\nstatic PyObject *\nPyGSL_rng_env_setup(PyObject *self, PyObject *args)\n{\n     gsl_rng_env_setup();\n     Py_INCREF(Py_None);\n     return Py_None;\n}\n\nstatic PyMethodDef PyGSL_rng_module_functions[] = {\n     {\"borosh13\"        , PyGSL_rng_init_borosh13        , METH_NOARGS, NULL},\n     {\"cmrg\"            , PyGSL_rng_init_cmrg            , METH_NOARGS, NULL},\n     {\"coveyou\"         , PyGSL_rng_init_coveyou         , METH_NOARGS, NULL},\n     {\"fishman18\"       , PyGSL_rng_init_fishman18       , METH_NOARGS, NULL},\n     {\"fishman20\"       , PyGSL_rng_init_fishman20       , METH_NOARGS, NULL},\n     {\"fishman2x\"       , PyGSL_rng_init_fishman2x       , METH_NOARGS, NULL},\n     {\"gfsr4\"           , PyGSL_rng_init_gfsr4           , METH_NOARGS, NULL},\n     {\"knuthran\"        , PyGSL_rng_init_knuthran        , METH_NOARGS, NULL},\n     {\"knuthran2\"       , PyGSL_rng_init_knuthran2       , METH_NOARGS, NULL},\n#ifdef  _PYGSL_GSL_HAS_RNG_KNUTHRAN2002\n     {\"knuthran2002\"    , PyGSL_rng_init_knuthran2002    , METH_NOARGS, NULL},\n#endif\n     {\"lecuyer21\"       , PyGSL_rng_init_lecuyer21       , METH_NOARGS, NULL},\n     {\"minstd\"          , PyGSL_rng_init_minstd          , METH_NOARGS, NULL},\n     {\"mrg\"             , PyGSL_rng_init_mrg             , METH_NOARGS, NULL},\n     {\"mt19937\"         , PyGSL_rng_init_mt19937         , METH_NOARGS, NULL},\n     {\"mt19937_1999\"    , PyGSL_rng_init_mt19937_1999    , METH_NOARGS, NULL},\n     {\"mt19937_1998\"    , PyGSL_rng_init_mt19937_1998    , METH_NOARGS, NULL},\n     {\"r250\"\t        , PyGSL_rng_init_r250            , METH_NOARGS, NULL},\n     {\"ran0\"\t        , PyGSL_rng_init_ran0            , METH_NOARGS, NULL},\n     {\"ran1\"\t        , PyGSL_rng_init_ran1            , METH_NOARGS, NULL},\n     {\"ran2\"\t        , PyGSL_rng_init_ran2            , METH_NOARGS, NULL},\n     {\"ran3\"\t        , PyGSL_rng_init_ran3            , METH_NOARGS, NULL},\n     {\"rand\"\t        , PyGSL_rng_init_rand            , METH_NOARGS, NULL},\n     {\"rand48\"          , PyGSL_rng_init_rand48          , METH_NOARGS, NULL},\n     {\"random128_bsd\"   , PyGSL_rng_init_random128_bsd   , METH_NOARGS, NULL},\n     {\"random128_glibc2\", PyGSL_rng_init_random128_glibc2, METH_NOARGS, NULL},\n     {\"random128_libc5\" , PyGSL_rng_init_random128_libc5 , METH_NOARGS, NULL},\n     {\"random256_bsd\"   , PyGSL_rng_init_random256_bsd   , METH_NOARGS, NULL},\n     {\"random256_glibc2\", PyGSL_rng_init_random256_glibc2, METH_NOARGS, NULL},\n     {\"random256_libc5\" , PyGSL_rng_init_random256_libc5 , METH_NOARGS, NULL},\n     {\"random32_bsd\"    , PyGSL_rng_init_random32_bsd    , METH_NOARGS, NULL},\n     {\"random32_glibc2\" , PyGSL_rng_init_random32_glibc2 , METH_NOARGS, NULL},\n     {\"random32_libc5\"  , PyGSL_rng_init_random32_libc5  , METH_NOARGS, NULL},\n     {\"random64_bsd\"    , PyGSL_rng_init_random64_bsd    , METH_NOARGS, NULL},\n     {\"random64_glibc2\" , PyGSL_rng_init_random64_glibc2 , METH_NOARGS, NULL},\n     {\"random64_libc5\"  , PyGSL_rng_init_random64_libc5  , METH_NOARGS, NULL},\n     {\"random8_bsd\"     , PyGSL_rng_init_random8_bsd     , METH_NOARGS, NULL},\n     {\"random8_glibc2\"  , PyGSL_rng_init_random8_glibc2  , METH_NOARGS, NULL},\n     {\"random8_libc5\"   , PyGSL_rng_init_random8_libc5   , METH_NOARGS, NULL},\n     {\"random_bsd\"      , PyGSL_rng_init_random_bsd      , METH_NOARGS, NULL},\n     {\"random_glibc2\"   , PyGSL_rng_init_random_glibc2   , METH_NOARGS, NULL},\n     {\"random_libc5\"    , PyGSL_rng_init_random_libc5    , METH_NOARGS, NULL},\n     {\"randu\"           , PyGSL_rng_init_randu           , METH_NOARGS, NULL},\n     {\"ranf\"            , PyGSL_rng_init_ranf            , METH_NOARGS, NULL},\n     {\"ranlux\"          , PyGSL_rng_init_ranlux          , METH_NOARGS, NULL},\n     {\"ranlux389\"       , PyGSL_rng_init_ranlux389       , METH_NOARGS, NULL},\n     {\"ranlxd1\"         , PyGSL_rng_init_ranlxd1         , METH_NOARGS, NULL},\n     {\"ranlxd2\"         , PyGSL_rng_init_ranlxd2         , METH_NOARGS, NULL},\n     {\"ranlxs0\"         , PyGSL_rng_init_ranlxs0         , METH_NOARGS, NULL},\n     {\"ranlxs1\"         , PyGSL_rng_init_ranlxs1         , METH_NOARGS, NULL},\n     {\"ranlxs2\"         , PyGSL_rng_init_ranlxs2         , METH_NOARGS, NULL},\n     {\"ranmar\"          , PyGSL_rng_init_ranmar          , METH_NOARGS, NULL},\n     {\"slatec\"          , PyGSL_rng_init_slatec          , METH_NOARGS, NULL},\n     {\"taus\"            , PyGSL_rng_init_taus            , METH_NOARGS, NULL},\n     {\"taus2\"           , PyGSL_rng_init_taus2           , METH_NOARGS, NULL},\n     {\"taus113\"         , PyGSL_rng_init_taus113         , METH_NOARGS, NULL},\n     {\"transputer\"      , PyGSL_rng_init_transputer      , METH_NOARGS, NULL},\n     {\"tt800\"           , PyGSL_rng_init_tt800           , METH_NOARGS, NULL},\n     {\"uni\"             , PyGSL_rng_init_uni             , METH_NOARGS, NULL},\n     {\"uni32\"           , PyGSL_rng_init_uni32           , METH_NOARGS, NULL},\n     {\"vax\"             , PyGSL_rng_init_vax             , METH_NOARGS, NULL},\n     {\"waterman14\"      , PyGSL_rng_init_waterman14      , METH_NOARGS, NULL},\n     {\"zuf\"             , PyGSL_rng_init_zuf             , METH_NOARGS, NULL},\n     {\"rng\", PyGSL_rng_init_default, METH_NOARGS, rng_doc},\n     {\"list_available_rngs\", rng_create_list, METH_VARARGS},\n     /*densities*/\n     {\"gaussian_pdf\",rng_gaussian_pdf,METH_VARARGS, rng_gaussian_pdf_doc},\n     {\"ugaussian_pdf\",rng_ugaussian_pdf,METH_VARARGS, rng_ugaussian_pdf_doc},\n     {\"gaussian_tail_pdf\",rng_gaussian_tail_pdf,METH_VARARGS, rng_gaussian_tail_pdf_doc},\n     {\"ugaussian_tail_pdf\",rng_ugaussian_tail_pdf,METH_VARARGS, rng_ugaussian_tail_pdf_doc},\n     {\"bivariate_gaussian_pdf\",rng_bivariate_gaussian_pdf,METH_VARARGS, rng_bivariate_gaussian_pdf_doc},\n     {\"exponential_pdf\",rng_exponential_pdf,METH_VARARGS, rng_exponential_pdf_doc},\n     {\"laplace_pdf\",rng_laplace_pdf,METH_VARARGS, rng_laplace_pdf_doc},\n     {\"exppow_pdf\",rng_exppow_pdf,METH_VARARGS, rng_exppow_pdf_doc},\n     {\"cauchy_pdf\",rng_cauchy_pdf,METH_VARARGS, rng_cauchy_pdf_doc},\n     {\"rayleigh_pdf\",rng_rayleigh_pdf,METH_VARARGS, rng_rayleigh_pdf_doc},\n     {\"rayleigh_tail_pdf\",rng_rayleigh_tail_pdf,METH_VARARGS, rng_rayleigh_tail_pdf_doc},\n     {\"gamma_pdf\",rng_gamma_pdf,METH_VARARGS, rng_gamma_pdf_doc},\n     {\"flat_pdf\",rng_flat_pdf,METH_VARARGS, rng_flat_pdf_doc},\n     {\"lognormal_pdf\",rng_lognormal_pdf,METH_VARARGS, rng_lognormal_pdf_doc},\n     {\"chisq_pdf\",rng_chisq_pdf,METH_VARARGS, rng_chisq_pdf_doc},\n     {\"fdist_pdf\",rng_fdist_pdf,METH_VARARGS, rng_fdist_pdf_doc},\n     {\"tdist_pdf\",rng_tdist_pdf,METH_VARARGS, rng_tdist_pdf_doc},\n     {\"beta_pdf\",rng_beta_pdf,METH_VARARGS, rng_beta_pdf_doc},\n     {\"logistic_pdf\",rng_logistic_pdf,METH_VARARGS, rng_logistic_pdf_doc},\n     {\"pareto_pdf\",rng_pareto_pdf,METH_VARARGS, rng_pareto_pdf_doc},\n     {\"weibull_pdf\",rng_weibull_pdf,METH_VARARGS, rng_weibull_pdf_doc},\n     {\"gumbel1_pdf\",rng_gumbel1_pdf,METH_VARARGS, rng_gumbel1_pdf_doc},\n     {\"gumbel2_pdf\",rng_gumbel2_pdf,METH_VARARGS, rng_gumbel2_pdf_doc},\n     {\"poisson_pdf\",rng_poisson_pdf,METH_VARARGS, rng_poisson_pdf_doc},\n     {\"bernoulli_pdf\",rng_bernoulli_pdf,METH_VARARGS, rng_bernoulli_pdf_doc},\n     {\"binomial_pdf\",rng_binomial_pdf,METH_VARARGS,  rng_binomial_pdf_doc},\n     {\"negative_binomial_pdf\",rng_negative_binomial_pdf,METH_VARARGS, rng_negative_binomial_pdf_doc},\n     {\"pascal_pdf\",rng_pascal_pdf,METH_VARARGS, rng_pascal_pdf_doc},\n     {\"geometric_pdf\",rng_geometric_pdf,METH_VARARGS, rng_geometric_pdf_doc},\n     {\"hypergeometric_pdf\",rng_hypergeometric_pdf,METH_VARARGS, rng_hypergeometric_pdf_doc},\n     {\"logarithmic_pdf\",rng_logarithmic_pdf,METH_VARARGS, rng_logarithmic_pdf_doc},  \n     {\"landau_pdf\",rng_landau_pdf,METH_VARARGS, rng_landau_pdf_doc},  \n     {\"erlang_pdf\",rng_erlang_pdf,METH_VARARGS, NULL},\n     {\"multinomial_pdf\",rng_multinomial_pdf,METH_VARARGS,multinomial_pdf_doc},  \n     {\"dirichlet_pdf\",rng_dirichlet_pdf,METH_VARARGS, rng_dirichlet_pdf_doc},\n     {\"multinomial_lnpdf\",rng_multinomial_lnpdf,METH_VARARGS, NULL},  \n     {\"dirichlet_lnpdf\",rng_dirichlet_lnpdf,METH_VARARGS, rng_dirichlet_lnpdf_doc},\n     {\"env_setup\",PyGSL_rng_env_setup,METH_NOARGS, (char*) rng_env_setup_doc},\n     {NULL, NULL, 0}        /* Sentinel */\n};\n\nstatic void \nset_api_pointer(void)\n{\n\n     FUNC_MESS_BEGIN();\n     PyGSL_API[PyGSL_RNG_ObjectType_NUM] = (void *) &PyGSL_rng_pytype;\n     DEBUG_MESS(2, \"__PyGSL_RNG_API   @ %p,  \", (void *) PyGSL_API);\n     DEBUG_MESS(2, \"PyGSL_rng_pytype  @ %p,  \", (void *) &PyGSL_rng_pytype);\n     /* fprintf(stderr, \"__PyGSL_RNG_API @ %p\\n\", (void *) __PyGSL_RNG_API); */\n     FUNC_MESS_END();\n}\n\nvoid \ninitrng(void)\n{\n     PyObject *m=NULL, *item=NULL, *dict=NULL;\n     PyObject *api=NULL;\n\n     m = Py_InitModule(\"rng\", PyGSL_rng_module_functions);\n     assert(m);\n     /* import_array(); */\n     init_pygsl();\n\n     /* create_rng_types(m); */\n     module = m;\n\n     dict = PyModule_GetDict(m);\n     if(!dict)\n\t  goto fail;\n     \n     if (!(item = PyString_FromString(rng_module_doc))){\n\t  PyErr_SetString(PyExc_ImportError, \n\t\t\t  \"I could not generate module doc string!\");\n\t  goto fail;\n     }\n     if (PyDict_SetItemString(dict, \"__doc__\", item) != 0){\n\t  PyErr_SetString(PyExc_ImportError, \n\t\t\t  \"I could not init doc string!\");\n\t  goto fail;\n     }\n\n     PyGSL_rng_pytype.ob_type = &PyType_Type;\n\n\n     set_api_pointer();\n     api = PyCObject_FromVoidPtr((void *) PyGSL_API, NULL);\n     assert(api);\n     if (PyDict_SetItemString(dict, \"_PYGSL_RNG_API\", api) != 0){\n\t  PyErr_SetString(PyExc_ImportError, \n\t\t\t  \"I could not add  _PYGSL_RNG_API!\");\n\t  goto fail;\n     }\n     \n     return;\n     \n fail:\n     if(!PyErr_Occurred()){\n\t  PyErr_SetString(PyExc_ImportError, \"I could not init rng module!\");\n     }\n\n}\n", "meta": {"hexsha": "80bbc24c799fb146544aa4fd510b56fa5075ac1a", "size": 25894, "ext": "c", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/src/rng/rngmodule.c", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/src/rng/rngmodule.c", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/src/rng/rngmodule.c", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 40.6499215071, "max_line_length": 108, "alphanum_fraction": 0.6275971267, "num_tokens": 7305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20946968626535542, "lm_q2_score": 0.03789242921002377, "lm_q1q2_score": 0.007937315258455868}}
{"text": "#pragma once\n\n#include <gsl\\gsl>\n#include <winrt\\Windows.Foundation.h>\n#include <d3d11.h>\n#include <map>\n#include \"DrawableGameComponent.h\"\n#include \"FullScreenRenderTarget.h\"\n#include \"FullScreenQuad.h\"\n#include \"MatrixHelper.h\"\n\nnamespace Library\n{\n\tclass Texture2D;\n\tclass TexturedModelMaterial;\n}\n\nnamespace Rendering\n{\n\tclass DistortionMaskingDemo final : public Library::DrawableGameComponent\n\t{\n\tpublic:\n\t\tDistortionMaskingDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera);\n\t\tDistortionMaskingDemo(const DistortionMaskingDemo&) = delete;\n\t\tDistortionMaskingDemo(DistortionMaskingDemo&&) = default;\n\t\tDistortionMaskingDemo& operator=(const DistortionMaskingDemo&) = default;\t\t\n\t\tDistortionMaskingDemo& operator=(DistortionMaskingDemo&&) = default;\n\t\t~DistortionMaskingDemo();\n\n\t\tbool DrawCutoutModeEnabled() const;\n\t\tvoid SetDrawCutoutModeEnabled(bool enabled);\n\t\tvoid ToggledDrawCutoutModeEnabled();\n\n\t\tfloat DisplacementScale() const;\n\t\tvoid SetDisplacementScale(float displacementScale);\n\n\t\tvirtual void Initialize() override;\n\t\tvirtual void Draw(const Library::GameTime& gameTime) override;\n\n\tprivate:\n\t\tstruct PixelCBufferPerObject\n\t\t{\n\t\t\tfloat DisplacementScale{ 1.0f };\n\t\t\tDirectX::XMFLOAT3 Padding;\n\t\t};\n\n\t\tenum class DistortionShaderClass\n\t\t{\n\t\t\tCutout = 0,\n\t\t\tComposite,\n\t\t\tNoDistortion\n\t\t};\n\n\t\tinline static const DirectX::XMVECTORF32 CutoutZeroColor{ DirectX::Colors::Black };\n\n\t\tDirectX::XMFLOAT4X4 mWorldMatrix{ Library::MatrixHelper::Identity };\n\t\tstd::shared_ptr<Library::TexturedModelMaterial> mTexturedModelMaterial;\n\t\tLibrary::FullScreenRenderTarget mSceneRenderTarget;\n\t\tLibrary::FullScreenRenderTarget mCutoutRenderTarget;\n\t\tLibrary::FullScreenQuad mFullScreenQuad;\t\t\n\t\twinrt::com_ptr<ID3D11Buffer> mPixelCBufferPerObject;\n\t\tPixelCBufferPerObject mPixelCBufferPerObjectData;\n\t\tstd::shared_ptr<Library::Texture2D> mDistortionMap;\n\t\tstd::map<DistortionShaderClass, winrt::com_ptr<ID3D11ClassInstance>> mShaderClassInstances;\n\t\twinrt::com_ptr<ID3D11Buffer> mVertexBuffer;\n\t\twinrt::com_ptr<ID3D11Buffer> mIndexBuffer;\n\t\tstd::uint32_t mIndexCount{ 0 };\n\t\tbool mDrawCutoutModeEnabled{ false };\t\t\n\t\tbool mUpdateMaterial{ true };\n\t};\n}", "meta": {"hexsha": "0a0707f7e5b5ea75ade69a1fbc5584922d8413f0", "size": 2178, "ext": "h", "lang": "C", "max_stars_repo_path": "source/7.5_Distortion_Masking/DistortionMaskingDemo.h", "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/7.5_Distortion_Masking/DistortionMaskingDemo.h", "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/7.5_Distortion_Masking/DistortionMaskingDemo.h", "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.676056338, "max_line_length": 93, "alphanum_fraction": 0.7865013774, "num_tokens": 585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35577489351363034, "lm_q2_score": 0.022286186675637105, "lm_q1q2_score": 0.007928865691349679}}
{"text": "#include <stdio.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/block/gsl_block.h>\n\n#define BASE_DOUBLE\n#include <gsl/templates_on.h>\n#include <gsl/block/fwrite_source.c>\n#include <gsl/block/fprintf_source.c>\n#include <gsl/templates_off.h>\n#undef BASE_DOUBLE", "meta": {"hexsha": "38aee3fc0085763ec0a4632e2d1b3a04aa402f26", "size": 254, "ext": "c", "lang": "C", "max_stars_repo_path": "Cartwheel/cartwheel-3d/gsl/block/file.c", "max_stars_repo_name": "MontyThibault/centre-of-mass-awareness", "max_stars_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Cartwheel/cartwheel-3d/gsl/block/file.c", "max_issues_repo_name": "MontyThibault/centre-of-mass-awareness", "max_issues_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cartwheel/cartwheel-3d/gsl/block/file.c", "max_forks_repo_name": "MontyThibault/centre-of-mass-awareness", "max_forks_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4, "max_line_length": 37, "alphanum_fraction": 0.7755905512, "num_tokens": 67, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2658804730998169, "lm_q2_score": 0.02976009093412654, "lm_q1q2_score": 0.007912627057059135}}
{"text": "/*\nCopyright (c) 2003-2008 Rudi Cilibrasi, Rulers of the RHouse\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n1. Redistributions of source code must retain the above copyright\n   notice, this list of conditions and the following disclaimer.\n2. Redistributions in binary form must reproduce the above copyright\n   notice, this list of conditions and the following disclaimer in the\n   documentation and/or other materials provided with the distribution.\n3. Neither the name of the University nor the names of its contributors\n   may be used to endorse or promote products derived from this software\n   without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE RULERS AND CONTRIBUTORS ``AS IS'' AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED.  IN NO EVENT SHALL THE RULERS OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\nOR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\nHOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\nLIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\nOUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGE.\n*/\n#include <glib.h>\n#include <libintl.h>\n#include <locale.h>\n#include \"complearn/newcomplearn.h\"\n#include \"complearn/clconfig.h\"\n\n#define _(O) gettext(O)\n\n#define clStringstackPush(a,v) {void*_u=(void*)v;g_array_append(a,_u);}while(0)\n\nGString *complearn_matrix_prettyprint_text(LabeledMatrix *result) {\n  int i, j;\n  int html = complearn_ncd_get_html_output(complearn_ncd_top());\n  char *rowstart = \"\", *rowend = \"\\n\", *numstart = \"\", *numend = \"\", *labstart = \"\", *labend = \" \", *lastcellstart=\"\", *lastcellend =\"\";\n  GString *toWrite = g_string_new(\"\");\n  CompLearnNcd *top = complearn_ncd_top();\n  gsl_matrix *goodmat =gsl_matrix_alloc(result->mat->size1, result->mat->size2);\n  gsl_matrix_memcpy(goodmat, result->mat);\n  if (html) {\n    g_string_append(toWrite, \"<table cellpadding='0' cellspacing='0'>\\n\");\n      rowstart = \"<tr>\\n\"; rowend = \"</tr>\\n\";\n      lastcellstart = \"<td style='font-family: sans-serif; padding: 7px; border: 0px gray solid; border-bottom-width: 1px; border-right-style: dashed; border-right-width:1px; border-left-style: dashed; border-left-width:1px;'>\"; lastcellend = \"</td>\";\n      numstart = \"<td style='font-family: sans-serif; padding: 7px; border: 0px gray solid; border-bottom-width: 1px; border-left-style: dashed; border-left-width:1px;'>\"; numend = \"</td>\";\n      labstart = \"<td style='color: green; font-weight: bold; padding: 7px; border: 0px gray solid; border-bottom-width: 1px;'>\"; labend = \"</td>\";\n    }\n    for (j = 0; j < goodmat->size2; j += 1) {\n      g_string_append(toWrite, rowstart);\n      if (complearn_ncd_get_show_labels(top)) {\n        g_string_append(toWrite, labstart);\n        if (result->labels2[j] == NULL)\n          g_error(\"bad labels2 %d with mat size2 %d\", j, goodmat->size2);\n        g_string_append(toWrite, result->labels2[j]);\n        g_string_append(toWrite, labend);\n      }\n      for (i = 0; i < goodmat->size1; i += 1) {\n        char buf[256];\n        sprintf(buf, \"%f \", gsl_matrix_get(goodmat, i, j));\n        g_string_append(toWrite, i == goodmat->size1-1 ? lastcellstart : numstart);\n        g_string_append(toWrite, buf);\n        g_string_append(toWrite, i == goodmat->size1-1 ? lastcellend : numend);\n      }\n      g_string_append(toWrite, rowend);\n    }\n  if (html)\n    g_string_append(toWrite, \"</table>\\n\");\n  gsl_matrix_free(goodmat);\n  return toWrite;\n}\n\n#include <complearn/complearn.h>\n#include <sys/types.h>\n#include <unistd.h>\n#include <assert.h>\n#include <string.h>\n\n#include <libxml/parser.h>\n#include <libxml/tree.h>\n#include <libxml/xmlwriter.h>\n#include <libxml/encoding.h>\n\n#define MY_ENCODING \"ISO-8859-1\"\n\n#include <gsl/gsl_linalg.h>\n\n#define PWD_RDY 1\n#define UTS_RDY 1\n\n#ifndef __MINGW32__\n\n#if PWD_RDY\n#include <pwd.h>\n#endif\n\n#if UTS_RDY\n#include <sys/utsname.h>\n#endif\n\n#endif\n\n\nGArray *clDefaultLabels(int i);\n\nstatic void complearn_handle_string_list(xmlDocPtr doc, xmlNodePtr node, GArray *ss,\n                             const char *tagname) {\n  node = node->xmlChildrenNode;\n  while (node != NULL) {\n    if (strcmp(tagname, (char *) node->name) == 0) {\n      guchar *v = xmlNodeListGetString(doc, node->xmlChildrenNode,1);\n      g_array_append_val(ss, v);\n    }\n    node = node->next;\n  }\n}\n\nstatic void handleDM(xmlDocPtr doc, xmlNodePtr node, GArray *ss,\nstruct CLDistMatrix *result) {\n  result->title = (char *) xmlGetProp(node, (unsigned char *) \"title\");\n  result->creationTime = (char *) xmlGetProp(node, (unsigned char *) \"creationtime\");\n  node = node->xmlChildrenNode;\n  GArray *numa, *lab1a, *lab2a;\n  numa = result->numa;\n  lab1a = result->labels1a;\n  lab2a = result->labels2a;\n  while (node != NULL) {\n    do {\n        if (strcmp(\"entries\", (char *) node->name) == 0) {\n          complearn_handle_string_list(doc, node, numa, \"number\");\n          continue;\n        }\n        if (strcmp((char *) node->name, \"axis1\") == 0) {\n          complearn_handle_string_list(doc, node, lab1a, \"name\");\n          continue;\n        }\n        if (strcmp((char *) node->name, \"axis2\") == 0) {\n          complearn_handle_string_list(doc, node, lab2a, \"name\");\n          continue;\n        }\n      } while(0);\n    node = node->next;\n  }\n}\n\nstatic void complearn_write_string_list(xmlTextWriterPtr tw, char **ss, const char *topname, const char *itemname) {\n  int rc;\n  int i;\n  rc = xmlTextWriterStartElement(tw, (unsigned char *) topname);\n  for (i = 0; i < complearn_count_strings((const char * const * )ss); i += 1)\n    rc = xmlTextWriterWriteElement(tw, (unsigned char *) itemname, (unsigned char *) ss[i]);\n  rc = xmlTextWriterEndElement(tw);\n}\n\nstatic char *getTimestrNow(void)\n{\n  static char buf[32];\n  sprintf(buf, \"%lu\", (unsigned long) time(NULL));\n  return buf;\n}\n\nstatic struct CLDistMatrix *fill_in_blanks(struct CLDistMatrix *clb)\n{\n  if (clb->m == NULL) {\n    g_error(_(\"Cannot write NULL gsl_matrix, exitting.\"));\n  }\n  if (clb->m->mat->size1 < 1 || clb->m->mat->size2 < 1) {\n    g_error(_(\"Invalid gsl_matrix size, cannot write.  Exitting.\"));\n  }\n  if (clb->fileverstr == NULL)\n    clb->fileverstr = g_strdup(\"1.0\");\n  if (clb->cllibver == NULL)\n    clb->cllibver = g_strdup(complearn_package_version);\n  if (clb->username == NULL)\n    clb->username = g_strdup(g_get_user_name());\n  if (clb->hostname == NULL)\n    clb->hostname = g_strdup(complearn_get_hostname());\n  if (clb->title == NULL)\n    clb->title = g_strdup(_(\"untitled\"));\n  if (clb->compressor == NULL)\n    clb->compressor = g_strdup(_(\"unknown\"));\n  if (clb->creationTime == NULL)\n    clb->creationTime = g_strdup(getTimestrNow());\n  return clb;\n}\n\nstruct CLDistMatrix *complearn_clone_cldm(struct CLDistMatrix *clb)\n{\n  struct CLDistMatrix *r = calloc(sizeof(*r), 1);\n  if (clb->m == NULL) {\n    g_error(_(\"Cannot write NULL gsl_matrix, exitting.\"));\n  }\n#define DUPSTR(s) if (clb->s) r->s = g_strdup(clb->s)\n  DUPSTR(cllibver);\n  DUPSTR(username);\n  DUPSTR(hostname);\n  DUPSTR(title);\n  DUPSTR(compressor);\n  DUPSTR(creationTime);\n  r->m = calloc(sizeof(*(r->m)), 1);\n  r->m->mat = gsl_matrix_alloc(clb->m->mat->size1, clb->m->mat->size2);\n  gsl_matrix_memcpy(r->m->mat, clb->m->mat);\n  r->m->labels1 = complearn_dupe_strings((const char * const *)clb->m->labels1);\n  r->m->labels2 = complearn_dupe_strings((const char * const *)clb->m->labels2);\n  r->cmds = complearn_dupe_strings((const char * const *)clb->cmds);\n  r->cmdtimes = complearn_dupe_strings((const char * const *)clb->cmdtimes);\n  return r;\n}\n\nvoid complearn_free_cldm(struct CLDistMatrix *clb)\n{\n  if (clb->cllibver) g_free(clb->cllibver);\n  if (clb->username) g_free(clb->username);\n  if (clb->hostname) g_free(clb->hostname);\n  if (clb->title) g_free(clb->title);\n  if (clb->compressor) g_free(clb->compressor);\n  if (clb->creationTime) g_free(clb->creationTime);\n  if (clb->m->mat) gsl_matrix_free(clb->m->mat);\n  g_strfreev(clb->m->labels1);\n  g_strfreev(clb->m->labels2);\n  g_strfreev(clb->cmdtimes);\n  g_strfreev(clb->cmds);\n  g_free(clb->m);\n  memset(clb, 0, sizeof(*clb));\n  g_free(clb);\n}\n\nstatic char *clXMLQuoteStr(char *inp)\n{\n  int i, c, j;\n  static char *outstr;\n  if (outstr != NULL)\n    g_free(outstr);\n  outstr = calloc(strlen(inp) * 10, 1);\n  j = 0;\n  for (i = 0; inp[i]; i += 1) {\n    c = inp[i];\n    switch(c) {\n      case '&':\n        outstr[j++] = '&'; outstr[j++] = 'a'; outstr[j++] = 'm';\n        outstr[j++] = 'p'; outstr[j++] = ';'; break;\n      case '>':\n        outstr[j++] = '&'; outstr[j++] = 'g'; outstr[j++] = 't';\n        outstr[j++] = ';'; break;\n      case '<':\n        outstr[j++] = '&'; outstr[j++] = 'l'; outstr[j++] = 't';\n        outstr[j++] = ';'; break;\n      case '\"':\n        outstr[j++] = '&'; outstr[j++] = 'q'; outstr[j++] = 'o';\n        outstr[j++] = 'o'; outstr[j++] = 't'; outstr[j++] = ';'; break;\n      case '\\'':\n        outstr[j++] = '&'; outstr[j++] = 'a'; outstr[j++] = 'p';\n        outstr[j++] = 'o'; outstr[j++] = 's'; outstr[j++] = ';'; break;\n//      case '\\\\':\n //     case '#':\n//        outstr[j++] = '\\\\'; outstr[j++] = c; break;\n      default:\n        outstr[j++] = c;\n    }\n  }\n  outstr[j++] = 0;\n  return outstr;\n}\n\nstatic GString *clRealWriteCLBDistMatrix(struct CLDistMatrix *clb)\n{\n  int rc;\n  GString *result, *cres;\n  int dim1, dim2, i, j;\n  gsl_matrix *m = clb->m->mat;\n  xmlBufferPtr b;\n  xmlTextWriterPtr tw;\n  clb = fill_in_blanks(complearn_clone_cldm(clb));\n  b = xmlBufferCreate();\n  tw =xmlNewTextWriterMemory(b, 0);\n  rc = xmlTextWriterStartDocument(tw, NULL, MY_ENCODING, NULL);\n  rc = xmlTextWriterStartElement(tw, (unsigned char *) \"clb\");\n  rc = xmlTextWriterWriteAttribute(tw, (unsigned char *) \"version\", (unsigned char *) clb->fileverstr);\n\n    rc = xmlTextWriterWriteElement(tw, (unsigned char *) \"cllibver\", (unsigned char *) clb->cllibver);\n    rc = xmlTextWriterWriteElement(tw, (unsigned char *) \"username\", (unsigned char *) clb->username);\n    rc = xmlTextWriterWriteElement(tw, (unsigned char *) \"hostname\", (unsigned char *) clb->hostname);\n    rc = xmlTextWriterWriteElement(tw, (unsigned char *) \"compressor\", (unsigned char *) clb->compressor);\n    rc = xmlTextWriterStartElement(tw,(unsigned char *)  \"distmatrix\");\n    rc = xmlTextWriterWriteAttribute(tw,(unsigned char *)  \"creationtime\", (unsigned char *) clb->creationTime);\n    rc = xmlTextWriterWriteAttribute(tw, (unsigned char *) \"title\",(unsigned char *)  clb->title);\n    complearn_write_string_list(tw, clb->m->labels1,  \"axis1\",  \"name\");\n    complearn_write_string_list(tw, clb->m->labels2,  \"axis2\",  \"name\");\n    dim1 = complearn_count_strings((const char * const *) clb->m->labels1);\n    dim2 = complearn_count_strings((const char * const *) clb->m->labels2);\n      rc = xmlTextWriterStartElement(tw,(unsigned char *)  \"entries\");\n      for (i = 0; i < dim1; i += 1) {\n        for (j = 0; j < dim2; j += 1) {\n          double g = gsl_matrix_get(m, i, j);\n            xmlTextWriterWriteFormatElement(tw, (unsigned char *) \"number\", (char *) \"%f\", g);\n        }\n      }\n      rc = xmlTextWriterEndElement(tw);\n    rc = xmlTextWriterEndElement(tw);\n    if (clb->cmds) {\n      char *str;\n      rc = xmlTextWriterStartElement(tw,(unsigned char *)  \"commands\");\n      for (i = 0; i < complearn_count_strings((const char * const *) clb->cmds); i += 1) {\n        char *t = clb->cmdtimes ? (clb->cmdtimes[i]) : NULL;\n        rc = xmlTextWriterStartElement(tw,(unsigned char *)  \"cmdstring\");\n        if (t)\n          rc = xmlTextWriterWriteAttribute(tw,(unsigned char *)  \"creationtime\", (unsigned char *) t);\n        str = clb->cmds[i];\n        xmlTextWriterWriteRaw(tw, (unsigned char *)  clXMLQuoteStr(str));\n        rc = xmlTextWriterEndElement(tw);\n      }\n      rc = xmlTextWriterEndElement(tw);\n    }\n  rc = xmlTextWriterEndElement(tw);\n  rc = xmlTextWriterEndDocument(tw);\n  xmlFreeTextWriter(tw);\n  result = g_string_new((char *) b->content);\n  xmlBufferFree(b);\n  /* TODO: remove more mem leaks from above func */\n  complearn_free_cldm(clb);\n  CompLearnRealCompressor *bz = COMPLEARN_REAL_COMPRESSOR(complearn_environment_get_nameable(\"bzlib\"));\n  if (bz == NULL)\n    g_error(_(\"Cannot load bzlib\"));\n  cres = real_compressor_compress(bz, result);\n  g_string_free(result, TRUE);\n  return cres;\n}\n\ngsl_matrix *complearn_clb_dist_matrix(const GString *db)\n{\n  return complearn_read_clb_dist_matrix(db)->m->mat;\n}\n\nstruct CLDistMatrix *complearn_read_clb_dist_matrix(const GString *udb)\n{\n  struct CLDistMatrix *result = calloc(sizeof(struct CLDistMatrix), 1);\n  GArray *ents = g_array_new(FALSE, TRUE, sizeof(gpointer));\n  GString *db;\n  int dim1, dim2;\n  xmlDocPtr doc;\n  xmlNodePtr node;\n  CompLearnRealCompressor *bz = COMPLEARN_REAL_COMPRESSOR(complearn_environment_get_nameable(\"bzlib\"));\n  if (bz == NULL)\n    g_error(_(\"Cannot load bzlib compressor.\"));\n  if (real_compressor_is_decompressible(bz, udb))\n    db = real_compressor_decompress(bz, udb);\n  else\n    db = g_string_new_len(udb->str, udb->len);\n  if (db == NULL || db->len < 1)\n    return NULL;\n  if (db->str[0] != '<')\n    return NULL;\n  result->fileverstr = \"\";\n  result->username = \"\";\n  result->title = \"\";\n  result->creationTime = \"\";\n  result->cmdsa = g_array_new(FALSE, TRUE, sizeof(gpointer));\n  result->cmdtimesa = g_array_new(FALSE, TRUE, sizeof(gpointer));\n  result->labels1a = g_array_new(FALSE, TRUE, sizeof(gpointer));\n  result->labels2a = g_array_new(FALSE, TRUE, sizeof(gpointer));\n  result->numa = g_array_new(FALSE, TRUE, sizeof(gpointer));\n  result->m = calloc(sizeof(*result->m), 1);\n  doc = xmlReadMemory((char *)db->str, db->len, \"noname.xml\",\n                      NULL, 0);\n  if (doc == NULL) {\n    g_error(_(\"Failed to parse document.\"));\n    g_string_free(db, TRUE);\n    free(result);\n    return NULL;\n  }\n  node = doc->children;\n  if (strcmp((char *) node->name, \"clb\") != 0) {\n    free(result);\n    g_string_free(db, TRUE);\n    return NULL;\n  }\n  result->fileverstr = (char *) xmlGetProp(node, (unsigned char *) \"version\");\n  node = node->xmlChildrenNode;\n while (node != NULL) {\n    do {\n      if (strcmp((char *) node->name, \"commands\") == 0) {\n        complearn_handle_string_list(doc, node, result->cmdsa, \"cmdstring\");\n        continue;\n      }\n      if (strcmp((char *) node->name, \"distmatrix\") == 0) {\n        handleDM(doc, node, ents, result);\n  result->m->mat = gsl_matrix_alloc(result->labels1a->len, result->labels2a->len);\n  int i, x=0, y=0;\n  for (i = 0; i < result->numa->len; i += 1) {\n    gsl_matrix_set(result->m->mat,x,y,atof(g_array_index(result->numa, char *, i)));\n    g_assert(y < result->m->mat->size2);\n    x += 1;\n    if (x == result->m->mat->size1) {\n      x = 0; y += 1;\n    }\n  }\n        continue;\n      }\n      if (strcmp((char *) node->name, \"cllibver\") == 0) {\n        result->cllibver = (char *) g_strdup((char *) xmlNodeListGetString(doc, node->xmlChildrenNode, 1));\n        continue;\n      }\n      if (strcmp((char *) node->name, \"compressor\") == 0) {\n        result->compressor = (char *) g_strdup((char *) xmlNodeListGetString(doc, node->xmlChildrenNode, 1));\n        continue;\n      }\n      if (strcmp((char *) node->name, \"username\") == 0) {\n        result->username = (char *) g_strdup((char *) xmlNodeListGetString(doc, node->xmlChildrenNode, 1));\n        continue;\n      }\n    } while (0);\n    node = node->next;\n    }\n\n  dim1 = result->labels1a->len;\n  if (dim1 <= 0) {\n    g_error(_(\"Error, no labels for dimension 1.\"));\n    exit(1);\n  }\n  dim2 = result->labels2a->len;\n  if (dim2 <= 0) {\n    g_error(_(\"Error, no labels for dimension 2.\"));\n    exit(1);\n  }\n  g_array_free(ents, TRUE);\n  g_string_free(db, TRUE);\n  result->m->labels1 = calloc(result->labels1a->len+1, sizeof(gpointer));\n  result->m->labels2 = calloc(result->labels2a->len+1, sizeof(gpointer));\n  memcpy(result->m->labels1, result->labels1a->data, sizeof(gpointer)*(result->labels1a->len));\n  memcpy(result->m->labels2, result->labels2a->data, sizeof(gpointer)*(result->labels2a->len));\n  return result;\n}\n\nconst char *complearn_complearn_get_hostname(void)\n{\n  static char hostname[1024];\n#ifdef __MINGW32__\n\tstrcpy(hostname, \"localhost\");\n#else\n  gethostname(hostname, 1024);\n#endif\n  return hostname;\n}\n\nconst char *complearn_get_uts_name(void)\n{\n  static char utsname[1024];\n#if UTS_RDY\n#ifdef __MINGW32__\n\tstrcpy(utsname, \"mingw32\");\n#else\n  struct utsname uts;\n  uname(&uts);\n  sprintf(utsname, \"[%s (%s), %s]\", uts.sysname, uts.release, uts.machine);\n#endif\n#else\n  strcpy(utsname, \"[unknown]\");\n#endif\n  return utsname;\n}\n\nGString *complearn_matrix_prettyprint_clb(LabeledMatrix *dm) {\n  struct CLDistMatrix inp;\n  memset(&inp, 0, sizeof(inp));\n  inp.m = dm;\n  char *old_locale = setlocale(LC_NUMERIC, NULL);\n  setlocale(LC_NUMERIC, \"C\");\n  GString *result = clRealWriteCLBDistMatrix(&inp);\n  setlocale(LC_NUMERIC, old_locale);\n  return result;\n}\n\nLabeledMatrix *complearn_load_any_matrix(const GString *inp)\n{\n  complearn_environment_top();\n  if (complearn_is_nexus_file(inp))\n    return complearn_load_nexus_matrix(inp);\n  struct CLDistMatrix *cld;\n  cld = complearn_read_clb_dist_matrix(inp);\n  if (cld) {\n    return cld->m;\n  }\n  if (complearn_is_text_matrix(inp)) {\n    return complearn_load_text_matrix(inp);\n  }\n  return NULL;\n}\n\n", "meta": {"hexsha": "9bb8ea6eec65b4a576173a9b59646fb1e752eef7", "size": 17576, "ext": "c", "lang": "C", "max_stars_repo_path": "src/cloutput.c", "max_stars_repo_name": "rudi-cilibrasi/classic-complearn", "max_stars_repo_head_hexsha": "c70ac5ad7bcfe3af80a2a8f087ee6f5904820a66", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-03-14T13:52:31.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-08T11:13:03.000Z", "max_issues_repo_path": "src/cloutput.c", "max_issues_repo_name": "rudi-cilibrasi/classic-complearn", "max_issues_repo_head_hexsha": "c70ac5ad7bcfe3af80a2a8f087ee6f5904820a66", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2016-05-10T12:56:52.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-15T18:30:04.000Z", "max_forks_repo_path": "src/cloutput.c", "max_forks_repo_name": "rudi-cilibrasi/classic-complearn", "max_forks_repo_head_hexsha": "c70ac5ad7bcfe3af80a2a8f087ee6f5904820a66", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5789473684, "max_line_length": 251, "alphanum_fraction": 0.6504893036, "num_tokens": 5210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29421497216298875, "lm_q2_score": 0.02675928502879603, "lm_q1q2_score": 0.007872982299848705}}
{"text": "/****************************************************************************\n *                                                                          *\n *  Author : lukasz.iwaszkiewicz@gmail.com                                  *\n *  ~~~~~~~~                                                                *\n *  License : see COPYING file for details.                                 *\n *  ~~~~~~~~~                                                               *\n ****************************************************************************/\n\n#pragma once\n\n/**\n * This file is for maintaining compatibility with systems where C++ standard library is\n * not available i.e. for Arduino. I was totally unaware, that there is no C++ standard\n * library implemented for this toy platform.\n */\n\n#if defined(__GNUC__) && (defined(AVR) || defined(ARDUINO) || defined (ARDUINO_ARCH_AVR))\n#include <assert.h>\n#include <stddef.h>\n#include <stdint.h>\n\n#include <etl/array.h>\n#include <etl/map.h>\n#include <etl/optional.h>\n\n#if !defined Expects\n#define Expects(x) assert (x)\n#endif\n\nnamespace gsl {\n\ntemplate <class T, std::size_t N> constexpr T &at (T (&arr)[N], const int i)\n{\n        Expects (i >= 0 && i < static_cast<int> (N));\n        return arr[static_cast<size_t> (i)];\n}\n\ntemplate <class Cont> constexpr auto at (Cont &cont, const int i) -> decltype (cont[cont.size ()])\n{\n        Expects (i >= 0 && i < static_cast<int> (cont.size ()));\n        using size_type = decltype (cont.size ());\n        return cont[static_cast<size_type> (i)];\n}\n} // namespace gsl\n\nnamespace std {\ntemplate <typename _Tp, typename _Up = _Tp &&> _Up __declval (int);\n\ntemplate <typename _Tp> _Tp __declval (long);\n\ntemplate <typename _Tp> auto declval () noexcept -> decltype (__declval<_Tp> (0));\n\ntemplate <typename _Tp> struct __declval_protector {\n        static const bool __stop = false;\n};\n\ntemplate <typename _Tp> auto declval () noexcept -> decltype (__declval<_Tp> (0))\n{\n        static_assert (__declval_protector<_Tp>::__stop, \"declval() must not be used!\");\n        return __declval<_Tp> (0);\n}\n} // namespace std\n#else\n#include <cstdint>\n#include <gsl/gsl>\n#endif\n\n#include <etl/map.h>\n#include <etl/optional.h>\n", "meta": {"hexsha": "a28faf8aec0e65f5599060e20614d723319b3e52", "size": 2204, "ext": "h", "lang": "C", "max_stars_repo_path": "src/CppCompat.h", "max_stars_repo_name": "semasquare/cpp-can-isotp", "max_stars_repo_head_hexsha": "8f6b487de162e4c7e871d33ce9cdb4329eff9d5d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-09-17T15:01:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-09T20:32:58.000Z", "max_issues_repo_path": "src/CppCompat.h", "max_issues_repo_name": "semasquare/cpp-can-isotp", "max_issues_repo_head_hexsha": "8f6b487de162e4c7e871d33ce9cdb4329eff9d5d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-02T19:05:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-26T15:32:11.000Z", "max_forks_repo_path": "src/CppCompat.h", "max_forks_repo_name": "semasquare/cpp-can-isotp", "max_forks_repo_head_hexsha": "8f6b487de162e4c7e871d33ce9cdb4329eff9d5d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-09-15T06:14:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-31T07:40:34.000Z", "avg_line_length": 31.4857142857, "max_line_length": 98, "alphanum_fraction": 0.5322141561, "num_tokens": 493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.17553808224967946, "lm_q2_score": 0.04468087361190477, "lm_q1q2_score": 0.007843194867074072}}
{"text": "/* matrix/gsl_matrix_complex_long_double.h\r\n * \r\n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\r\n * \r\n * This program is free software; you can redistribute it and/or modify\r\n * it under the terms of the GNU General Public License as published by\r\n * the Free Software Foundation; either version 3 of the License, or (at\r\n * your option) any later version.\r\n * \r\n * This program is distributed in the hope that it will be useful, but\r\n * WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n * General Public License for more details.\r\n * \r\n * You should have received a copy of the GNU General Public License\r\n * along with this program; if not, write to the Free Software\r\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r\n */\r\n\r\n#ifndef __GSL_MATRIX_COMPLEX_LONG_DOUBLE_H__\r\n#define __GSL_MATRIX_COMPLEX_LONG_DOUBLE_H__\r\n\r\n#if !defined( GSL_FUN )\r\n#  if !defined( GSL_DLL )\r\n#    define GSL_FUN extern\r\n#  elif defined( BUILD_GSL_DLL )\r\n#    define GSL_FUN extern __declspec(dllexport)\r\n#  else\r\n#    define GSL_FUN extern __declspec(dllimport)\r\n#  endif\r\n#endif\r\n\r\n#include <stdlib.h>\r\n#include <gsl/gsl_types.h>\r\n#include <gsl/gsl_errno.h>\r\n#include <gsl/gsl_complex.h>\r\n#include <gsl/gsl_check_range.h>\r\n#include <gsl/gsl_vector_complex_long_double.h>\r\n\r\n#undef __BEGIN_DECLS\r\n#undef __END_DECLS\r\n#ifdef __cplusplus\r\n# define __BEGIN_DECLS extern \"C\" {\r\n# define __END_DECLS }\r\n#else\r\n# define __BEGIN_DECLS /* empty */\r\n# define __END_DECLS /* empty */\r\n#endif\r\n\r\n__BEGIN_DECLS\r\n\r\ntypedef struct \r\n{\r\n  size_t size1;\r\n  size_t size2;\r\n  size_t tda;\r\n  long double * data;\r\n  gsl_block_complex_long_double * block;\r\n  int owner;\r\n} gsl_matrix_complex_long_double ;\r\n\r\ntypedef struct\r\n{\r\n  gsl_matrix_complex_long_double matrix;\r\n} _gsl_matrix_complex_long_double_view;\r\n\r\ntypedef _gsl_matrix_complex_long_double_view gsl_matrix_complex_long_double_view;\r\n\r\ntypedef struct\r\n{\r\n  gsl_matrix_complex_long_double matrix;\r\n} _gsl_matrix_complex_long_double_const_view;\r\n\r\ntypedef const _gsl_matrix_complex_long_double_const_view gsl_matrix_complex_long_double_const_view;\r\n\r\n\r\n/* Allocation */\r\n\r\nGSL_FUN gsl_matrix_complex_long_double * \r\ngsl_matrix_complex_long_double_alloc (const size_t n1, const size_t n2);\r\n\r\nGSL_FUN gsl_matrix_complex_long_double * \r\ngsl_matrix_complex_long_double_calloc (const size_t n1, const size_t n2);\r\n\r\nGSL_FUN gsl_matrix_complex_long_double * \r\ngsl_matrix_complex_long_double_alloc_from_block (gsl_block_complex_long_double * b, \r\n                                           const size_t offset, \r\n                                           const size_t n1, const size_t n2, const size_t d2);\r\n\r\nGSL_FUN gsl_matrix_complex_long_double * \r\ngsl_matrix_complex_long_double_alloc_from_matrix (gsl_matrix_complex_long_double * b,\r\n                                            const size_t k1, const size_t k2,\r\n                                            const size_t n1, const size_t n2);\r\n\r\nGSL_FUN gsl_vector_complex_long_double * \r\ngsl_vector_complex_long_double_alloc_row_from_matrix (gsl_matrix_complex_long_double * m,\r\n                                                const size_t i);\r\n\r\nGSL_FUN gsl_vector_complex_long_double * \r\ngsl_vector_complex_long_double_alloc_col_from_matrix (gsl_matrix_complex_long_double * m,\r\n                                                const size_t j);\r\n\r\nGSL_FUN void gsl_matrix_complex_long_double_free (gsl_matrix_complex_long_double * m);\r\n\r\n/* Views */\r\n\r\nGSL_FUN _gsl_matrix_complex_long_double_view \r\ngsl_matrix_complex_long_double_submatrix (gsl_matrix_complex_long_double * m, \r\n                            const size_t i, const size_t j, \r\n                            const size_t n1, const size_t n2);\r\n\r\nGSL_FUN _gsl_vector_complex_long_double_view \r\ngsl_matrix_complex_long_double_row (gsl_matrix_complex_long_double * m, const size_t i);\r\n\r\nGSL_FUN _gsl_vector_complex_long_double_view \r\ngsl_matrix_complex_long_double_column (gsl_matrix_complex_long_double * m, const size_t j);\r\n\r\nGSL_FUN _gsl_vector_complex_long_double_view \r\ngsl_matrix_complex_long_double_diagonal (gsl_matrix_complex_long_double * m);\r\n\r\nGSL_FUN _gsl_vector_complex_long_double_view \r\ngsl_matrix_complex_long_double_subdiagonal (gsl_matrix_complex_long_double * m, const size_t k);\r\n\r\nGSL_FUN _gsl_vector_complex_long_double_view \r\ngsl_matrix_complex_long_double_superdiagonal (gsl_matrix_complex_long_double * m, const size_t k);\r\n\r\nGSL_FUN _gsl_vector_complex_long_double_view\r\ngsl_matrix_complex_long_double_subrow (gsl_matrix_complex_long_double * m,\r\n                                 const size_t i, const size_t offset,\r\n                                 const size_t n);\r\n\r\nGSL_FUN _gsl_vector_complex_long_double_view\r\ngsl_matrix_complex_long_double_subcolumn (gsl_matrix_complex_long_double * m,\r\n                                    const size_t j, const size_t offset,\r\n                                    const size_t n);\r\n\r\nGSL_FUN _gsl_matrix_complex_long_double_view\r\ngsl_matrix_complex_long_double_view_array (long double * base,\r\n                             const size_t n1, \r\n                             const size_t n2);\r\n\r\nGSL_FUN _gsl_matrix_complex_long_double_view\r\ngsl_matrix_complex_long_double_view_array_with_tda (long double * base, \r\n                                      const size_t n1, \r\n                                      const size_t n2,\r\n                                      const size_t tda);\r\n\r\nGSL_FUN _gsl_matrix_complex_long_double_view\r\ngsl_matrix_complex_long_double_view_vector (gsl_vector_complex_long_double * v,\r\n                              const size_t n1, \r\n                              const size_t n2);\r\n\r\nGSL_FUN _gsl_matrix_complex_long_double_view\r\ngsl_matrix_complex_long_double_view_vector_with_tda (gsl_vector_complex_long_double * v,\r\n                                       const size_t n1, \r\n                                       const size_t n2,\r\n                                       const size_t tda);\r\n\r\n\r\nGSL_FUN _gsl_matrix_complex_long_double_const_view \r\ngsl_matrix_complex_long_double_const_submatrix (const gsl_matrix_complex_long_double * m, \r\n                                  const size_t i, const size_t j, \r\n                                  const size_t n1, const size_t n2);\r\n\r\nGSL_FUN _gsl_vector_complex_long_double_const_view \r\ngsl_matrix_complex_long_double_const_row (const gsl_matrix_complex_long_double * m, \r\n                            const size_t i);\r\n\r\nGSL_FUN _gsl_vector_complex_long_double_const_view \r\ngsl_matrix_complex_long_double_const_column (const gsl_matrix_complex_long_double * m, \r\n                               const size_t j);\r\n\r\nGSL_FUN _gsl_vector_complex_long_double_const_view\r\ngsl_matrix_complex_long_double_const_diagonal (const gsl_matrix_complex_long_double * m);\r\n\r\nGSL_FUN _gsl_vector_complex_long_double_const_view \r\ngsl_matrix_complex_long_double_const_subdiagonal (const gsl_matrix_complex_long_double * m, \r\n                                    const size_t k);\r\n\r\nGSL_FUN _gsl_vector_complex_long_double_const_view \r\ngsl_matrix_complex_long_double_const_superdiagonal (const gsl_matrix_complex_long_double * m, \r\n                                      const size_t k);\r\n\r\nGSL_FUN _gsl_vector_complex_long_double_const_view\r\ngsl_matrix_complex_long_double_const_subrow (const gsl_matrix_complex_long_double * m,\r\n                                       const size_t i, const size_t offset,\r\n                                       const size_t n);\r\n\r\nGSL_FUN _gsl_vector_complex_long_double_const_view\r\ngsl_matrix_complex_long_double_const_subcolumn (const gsl_matrix_complex_long_double * m,\r\n                                          const size_t j, const size_t offset,\r\n                                          const size_t n);\r\n\r\nGSL_FUN _gsl_matrix_complex_long_double_const_view\r\ngsl_matrix_complex_long_double_const_view_array (const long double * base,\r\n                                   const size_t n1, \r\n                                   const size_t n2);\r\n\r\nGSL_FUN _gsl_matrix_complex_long_double_const_view\r\ngsl_matrix_complex_long_double_const_view_array_with_tda (const long double * base, \r\n                                            const size_t n1, \r\n                                            const size_t n2,\r\n                                            const size_t tda);\r\n\r\nGSL_FUN _gsl_matrix_complex_long_double_const_view\r\ngsl_matrix_complex_long_double_const_view_vector (const gsl_vector_complex_long_double * v,\r\n                                    const size_t n1, \r\n                                    const size_t n2);\r\n\r\nGSL_FUN _gsl_matrix_complex_long_double_const_view\r\ngsl_matrix_complex_long_double_const_view_vector_with_tda (const gsl_vector_complex_long_double * v,\r\n                                             const size_t n1, \r\n                                             const size_t n2,\r\n                                             const size_t tda);\r\n\r\n/* Operations */\r\n\r\nGSL_FUN void gsl_matrix_complex_long_double_set_zero (gsl_matrix_complex_long_double * m);\r\nGSL_FUN void gsl_matrix_complex_long_double_set_identity (gsl_matrix_complex_long_double * m);\r\nGSL_FUN void gsl_matrix_complex_long_double_set_all (gsl_matrix_complex_long_double * m, gsl_complex_long_double x);\r\n\r\nGSL_FUN int gsl_matrix_complex_long_double_fread (FILE * stream, gsl_matrix_complex_long_double * m) ;\r\nGSL_FUN int gsl_matrix_complex_long_double_fwrite (FILE * stream, const gsl_matrix_complex_long_double * m) ;\r\nGSL_FUN int gsl_matrix_complex_long_double_fscanf (FILE * stream, gsl_matrix_complex_long_double * m);\r\nGSL_FUN int gsl_matrix_complex_long_double_fprintf (FILE * stream, const gsl_matrix_complex_long_double * m, const char * format);\r\n\r\nGSL_FUN int gsl_matrix_complex_long_double_memcpy(gsl_matrix_complex_long_double * dest, const gsl_matrix_complex_long_double * src);\r\nGSL_FUN int gsl_matrix_complex_long_double_swap(gsl_matrix_complex_long_double * m1, gsl_matrix_complex_long_double * m2);\r\n\r\nGSL_FUN int gsl_matrix_complex_long_double_swap_rows(gsl_matrix_complex_long_double * m, const size_t i, const size_t j);\r\nGSL_FUN int gsl_matrix_complex_long_double_swap_columns(gsl_matrix_complex_long_double * m, const size_t i, const size_t j);\r\nGSL_FUN int gsl_matrix_complex_long_double_swap_rowcol(gsl_matrix_complex_long_double * m, const size_t i, const size_t j);\r\n\r\nGSL_FUN int gsl_matrix_complex_long_double_transpose (gsl_matrix_complex_long_double * m);\r\nGSL_FUN int gsl_matrix_complex_long_double_transpose_memcpy (gsl_matrix_complex_long_double * dest, const gsl_matrix_complex_long_double * src);\r\n\r\nGSL_FUN int gsl_matrix_complex_long_double_isnull (const gsl_matrix_complex_long_double * m);\r\nGSL_FUN int gsl_matrix_complex_long_double_ispos (const gsl_matrix_complex_long_double * m);\r\nGSL_FUN int gsl_matrix_complex_long_double_isneg (const gsl_matrix_complex_long_double * m);\r\nGSL_FUN int gsl_matrix_complex_long_double_isnonneg (const gsl_matrix_complex_long_double * m);\r\n\r\nGSL_FUN int gsl_matrix_complex_long_double_add (gsl_matrix_complex_long_double * a, const gsl_matrix_complex_long_double * b);\r\nGSL_FUN int gsl_matrix_complex_long_double_sub (gsl_matrix_complex_long_double * a, const gsl_matrix_complex_long_double * b);\r\nGSL_FUN int gsl_matrix_complex_long_double_mul_elements (gsl_matrix_complex_long_double * a, const gsl_matrix_complex_long_double * b);\r\nGSL_FUN int gsl_matrix_complex_long_double_div_elements (gsl_matrix_complex_long_double * a, const gsl_matrix_complex_long_double * b);\r\nGSL_FUN int gsl_matrix_complex_long_double_scale (gsl_matrix_complex_long_double * a, const gsl_complex_long_double x);\r\nGSL_FUN int gsl_matrix_complex_long_double_add_constant (gsl_matrix_complex_long_double * a, const gsl_complex_long_double x);\r\nGSL_FUN int gsl_matrix_complex_long_double_add_diagonal (gsl_matrix_complex_long_double * a, const gsl_complex_long_double x);\r\n\r\n/***********************************************************************/\r\n/* The functions below are obsolete                                    */\r\n/***********************************************************************/\r\nGSL_FUN int gsl_matrix_complex_long_double_get_row(gsl_vector_complex_long_double * v, const gsl_matrix_complex_long_double * m, const size_t i);\r\nGSL_FUN int gsl_matrix_complex_long_double_get_col(gsl_vector_complex_long_double * v, const gsl_matrix_complex_long_double * m, const size_t j);\r\nGSL_FUN int gsl_matrix_complex_long_double_set_row(gsl_matrix_complex_long_double * m, const size_t i, const gsl_vector_complex_long_double * v);\r\nGSL_FUN int gsl_matrix_complex_long_double_set_col(gsl_matrix_complex_long_double * m, const size_t j, const gsl_vector_complex_long_double * v);\r\n/***********************************************************************/\r\n\r\n/* inline functions if you are using GCC */\r\n\r\nGSL_FUN INLINE_DECL gsl_complex_long_double gsl_matrix_complex_long_double_get(const gsl_matrix_complex_long_double * m, const size_t i, const size_t j);\r\nGSL_FUN INLINE_DECL void gsl_matrix_complex_long_double_set(gsl_matrix_complex_long_double * m, const size_t i, const size_t j, const gsl_complex_long_double x);\r\n\r\nGSL_FUN INLINE_DECL gsl_complex_long_double * gsl_matrix_complex_long_double_ptr(gsl_matrix_complex_long_double * m, const size_t i, const size_t j);\r\nGSL_FUN INLINE_DECL const gsl_complex_long_double * gsl_matrix_complex_long_double_const_ptr(const gsl_matrix_complex_long_double * m, const size_t i, const size_t j);\r\n\r\n#ifdef HAVE_INLINE\r\n\r\nINLINE_FUN \r\ngsl_complex_long_double\r\ngsl_matrix_complex_long_double_get(const gsl_matrix_complex_long_double * m, \r\n                     const size_t i, const size_t j)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(1)) \r\n    {\r\n      gsl_complex_long_double zero = {{0,0}};\r\n\r\n      if (i >= m->size1)\r\n        {\r\n          GSL_ERROR_VAL(\"first index out of range\", GSL_EINVAL, zero) ;\r\n        }\r\n      else if (j >= m->size2)\r\n        {\r\n          GSL_ERROR_VAL(\"second index out of range\", GSL_EINVAL, zero) ;\r\n        }\r\n    }\r\n#endif\r\n  return *(gsl_complex_long_double *)(m->data + 2*(i * m->tda + j)) ;\r\n} \r\n\r\nINLINE_FUN \r\nvoid\r\ngsl_matrix_complex_long_double_set(gsl_matrix_complex_long_double * m, \r\n                     const size_t i, const size_t j, const gsl_complex_long_double x)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(1)) \r\n    {\r\n      if (i >= m->size1)\r\n        {\r\n          GSL_ERROR_VOID(\"first index out of range\", GSL_EINVAL) ;\r\n        }\r\n      else if (j >= m->size2)\r\n        {\r\n          GSL_ERROR_VOID(\"second index out of range\", GSL_EINVAL) ;\r\n        }\r\n    }\r\n#endif\r\n  *(gsl_complex_long_double *)(m->data + 2*(i * m->tda + j)) = x ;\r\n}\r\n\r\nINLINE_FUN \r\ngsl_complex_long_double *\r\ngsl_matrix_complex_long_double_ptr(gsl_matrix_complex_long_double * m, \r\n                             const size_t i, const size_t j)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(1)) \r\n    {\r\n      if (i >= m->size1)\r\n        {\r\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\r\n        }\r\n      else if (j >= m->size2)\r\n        {\r\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\r\n        }\r\n    }\r\n#endif\r\n  return (gsl_complex_long_double *)(m->data + 2*(i * m->tda + j)) ;\r\n} \r\n\r\nINLINE_FUN \r\nconst gsl_complex_long_double *\r\ngsl_matrix_complex_long_double_const_ptr(const gsl_matrix_complex_long_double * m, \r\n                                   const size_t i, const size_t j)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(1)) \r\n    {\r\n      if (i >= m->size1)\r\n        {\r\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\r\n        }\r\n      else if (j >= m->size2)\r\n        {\r\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\r\n        }\r\n    }\r\n#endif\r\n  return (const gsl_complex_long_double *)(m->data + 2*(i * m->tda + j)) ;\r\n} \r\n\r\n#endif /* HAVE_INLINE */\r\n\r\n__END_DECLS\r\n\r\n#endif /* __GSL_MATRIX_COMPLEX_LONG_DOUBLE_H__ */\r\n", "meta": {"hexsha": "d22636e2c5d73108a4442aafc4b60f66542ae9a5", "size": 16008, "ext": "h", "lang": "C", "max_stars_repo_path": "deps/include/gsl/gsl_matrix_complex_long_double.h", "max_stars_repo_name": "berkus/music-cs", "max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "deps/include/gsl/gsl_matrix_complex_long_double.h", "max_issues_repo_name": "berkus/music-cs", "max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "deps/include/gsl/gsl_matrix_complex_long_double.h", "max_forks_repo_name": "berkus/music-cs", "max_forks_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.4666666667, "max_line_length": 168, "alphanum_fraction": 0.6967141429, "num_tokens": 3479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2782568056728001, "lm_q2_score": 0.02800751888195107, "lm_q1q2_score": 0.007793282738912338}}
{"text": "#include <config.h>\n#include <stddef.h>\n#include <stdlib.h>\n#include <math.h>\n#include <float.h>\n#include <stdio.h>\n\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_complex.h>\n\n#include <gsl/gsl_fft_complex.h>\n\n#define BASE_DOUBLE\n#include \"templates_on.h\"\n#include \"compare_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_DOUBLE\n\n#define BASE_FLOAT\n#include \"templates_on.h\"\n#include \"compare_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_FLOAT\n", "meta": {"hexsha": "9a636511d5f98d23822792d46bfed9a5c0e7e55e", "size": 449, "ext": "c", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/fft/compare.c", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/fft/compare.c", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/fft/compare.c", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 18.7083333333, "max_line_length": 32, "alphanum_fraction": 0.7527839644, "num_tokens": 112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40733341443526055, "lm_q2_score": 0.019124035562926515, "lm_q1q2_score": 0.007789858703628208}}
{"text": "/* rng/types.c\n * \n * Copyright (C) 2001, 2007 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <stdlib.h>\n#include <gsl/gsl_rng.h>\n\n#define N 100\n\nconst gsl_rng_type * gsl_rng_generator_types[N];\n\n#define ADD(t) {if (i==N) abort(); gsl_rng_generator_types[i] = (t); i++; };\n\nconst gsl_rng_type **\ngsl_rng_types_setup (void)\n{\n  int i = 0;\n\n  ADD(gsl_rng_borosh13);\n  ADD(gsl_rng_cmrg);\n  ADD(gsl_rng_coveyou);\n  ADD(gsl_rng_fishman18);\n  ADD(gsl_rng_fishman20);\n  ADD(gsl_rng_fishman2x);\n  ADD(gsl_rng_gfsr4);\n  ADD(gsl_rng_knuthran);\n  ADD(gsl_rng_knuthran2);\n  ADD(gsl_rng_knuthran2002);\n  ADD(gsl_rng_lecuyer21);\n  ADD(gsl_rng_minstd);\n  ADD(gsl_rng_mrg);\n  ADD(gsl_rng_mt19937);\n  ADD(gsl_rng_mt19937_1999);\n  ADD(gsl_rng_mt19937_1998);\n  ADD(gsl_rng_r250);\n  ADD(gsl_rng_ran0);\n  ADD(gsl_rng_ran1);\n  ADD(gsl_rng_ran2);\n  ADD(gsl_rng_ran3);\n  ADD(gsl_rng_rand);\n  ADD(gsl_rng_rand48);\n  ADD(gsl_rng_random128_bsd);\n  ADD(gsl_rng_random128_glibc2);\n  ADD(gsl_rng_random128_libc5);\n  ADD(gsl_rng_random256_bsd);\n  ADD(gsl_rng_random256_glibc2);\n  ADD(gsl_rng_random256_libc5);\n  ADD(gsl_rng_random32_bsd);\n  ADD(gsl_rng_random32_glibc2);\n  ADD(gsl_rng_random32_libc5);\n  ADD(gsl_rng_random64_bsd);\n  ADD(gsl_rng_random64_glibc2);\n  ADD(gsl_rng_random64_libc5);\n  ADD(gsl_rng_random8_bsd);\n  ADD(gsl_rng_random8_glibc2);\n  ADD(gsl_rng_random8_libc5);\n  ADD(gsl_rng_random_bsd);\n  ADD(gsl_rng_random_glibc2);\n  ADD(gsl_rng_random_libc5);\n  ADD(gsl_rng_randu);\n  ADD(gsl_rng_ranf);\n  ADD(gsl_rng_ranlux);\n  ADD(gsl_rng_ranlux389);\n  ADD(gsl_rng_ranlxd1);\n  ADD(gsl_rng_ranlxd2);\n  ADD(gsl_rng_ranlxs0);\n  ADD(gsl_rng_ranlxs1);\n  ADD(gsl_rng_ranlxs2);\n  ADD(gsl_rng_ranmar);\n  ADD(gsl_rng_slatec);\n  ADD(gsl_rng_taus);\n  ADD(gsl_rng_taus2);\n  ADD(gsl_rng_taus113);\n  ADD(gsl_rng_transputer);\n  ADD(gsl_rng_tt800);\n  ADD(gsl_rng_uni);\n  ADD(gsl_rng_uni32);\n  ADD(gsl_rng_vax);\n  ADD(gsl_rng_waterman14);\n  ADD(gsl_rng_zuf);\n  ADD(0);\n\n  return gsl_rng_generator_types;\n}\n\n", "meta": {"hexsha": "071edcf635a9937597742111c219973e4fcd7ac2", "size": 2692, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/rng/types.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/rng/types.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/rng/types.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 26.3921568627, "max_line_length": 81, "alphanum_fraction": 0.7466567608, "num_tokens": 886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3040416749665474, "lm_q2_score": 0.02556521364486039, "lm_q1q2_score": 0.007772890377460985}}
{"text": "#pragma once\n\n#include <iosfwd>\n#include <map>\n#include <memory>\n#include <vector>\n\n#include <gsl/gsl>\n\nnamespace sframe {\n\nstruct openssl_error : std::runtime_error\n{\n  openssl_error();\n};\n\nstruct unsupported_ciphersuite_error : std::runtime_error\n{\n  unsupported_ciphersuite_error();\n};\n\nstruct authentication_error : std::runtime_error\n{\n  authentication_error();\n};\n\nstruct buffer_too_small_error : std::runtime_error\n{\n  using parent = std::runtime_error;\n  using parent::parent;\n};\n\nstruct invalid_parameter_error : std::runtime_error\n{\n  using parent = std::runtime_error;\n  using parent::parent;\n};\n\nenum class CipherSuite : uint16_t\n{\n  AES_CM_128_HMAC_SHA256_4 = 1,\n  AES_CM_128_HMAC_SHA256_8 = 2,\n  AES_GCM_128_SHA256 = 3,\n  AES_GCM_256_SHA512 = 4,\n};\n\nconstexpr size_t max_overhead = 17 + 16;\n\nusing bytes = std::vector<uint8_t>;\nusing input_bytes = gsl::span<const uint8_t>;\nusing output_bytes = gsl::span<uint8_t>;\n\nstd::ostream&\noperator<<(std::ostream& str, const input_bytes data);\n\nusing KeyID = uint64_t;\nusing Counter = uint64_t;\n\nclass SFrame\n{\nprotected:\n  CipherSuite suite;\n\n  SFrame(CipherSuite suite_in);\n  virtual ~SFrame();\n\n  struct KeyState\n  {\n    static KeyState from_base_key(CipherSuite suite, const bytes& base_key);\n\n    bytes key;\n    bytes salt;\n    Counter counter;\n  };\n\n  output_bytes _protect(KeyID key_id,\n                        output_bytes ciphertext,\n                        input_bytes plaintext);\n  output_bytes _unprotect(output_bytes ciphertext, input_bytes plaintext);\n\n  virtual KeyState& get_state(KeyID key_id) = 0;\n};\n\nclass Context : public SFrame\n{\npublic:\n  Context(CipherSuite suite);\n\n  void add_key(KeyID kid, const bytes& key);\n\n  output_bytes protect(KeyID key_id,\n                       output_bytes ciphertext,\n                       input_bytes plaintext);\n  output_bytes unprotect(output_bytes plaintext, input_bytes ciphertext);\n\nprivate:\n  std::map<KeyID, KeyState> state;\n\n  KeyState& get_state(KeyID key_id) override;\n};\n\nclass MLSContext : public SFrame\n{\npublic:\n  using EpochID = uint64_t;\n  using SenderID = uint32_t;\n\n  MLSContext(CipherSuite suite_in, size_t epoch_bits_in);\n\n  void add_epoch(EpochID epoch_id, const bytes& sframe_epoch_secret);\n  void purge_before(EpochID keeper);\n\n  output_bytes protect(EpochID epoch_id,\n                       SenderID sender_id,\n                       output_bytes ciphertext,\n                       input_bytes plaintext);\n  output_bytes unprotect(output_bytes plaintext, input_bytes ciphertext);\n\nprivate:\n  const size_t epoch_bits;\n  const size_t epoch_mask;\n\n  struct EpochKeys\n  {\n    const EpochID full_epoch;\n    const bytes sframe_epoch_secret;\n    std::map<SenderID, KeyState> sender_keys;\n\n    EpochKeys(EpochID full_epoch_in, bytes sframe_epoch_secret_in);\n    KeyState& get(CipherSuite suite, SenderID sender_id);\n  };\n\n  std::vector<std::unique_ptr<EpochKeys>> epoch_cache;\n  KeyState& get_state(KeyID key_id) override;\n};\n\n} // namespace sframe\n", "meta": {"hexsha": "c5bf936bef1c16f133c61c26c90671298c91b363", "size": 2976, "ext": "h", "lang": "C", "max_stars_repo_path": "include/sframe/sframe.h", "max_stars_repo_name": "fanglinliu/sframe", "max_stars_repo_head_hexsha": "360dcc6546448c933f1974463aef257a61a6a25a", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/sframe/sframe.h", "max_issues_repo_name": "fanglinliu/sframe", "max_issues_repo_head_hexsha": "360dcc6546448c933f1974463aef257a61a6a25a", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/sframe/sframe.h", "max_forks_repo_name": "fanglinliu/sframe", "max_forks_repo_head_hexsha": "360dcc6546448c933f1974463aef257a61a6a25a", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5652173913, "max_line_length": 76, "alphanum_fraction": 0.7147177419, "num_tokens": 724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3276683008207139, "lm_q2_score": 0.023689472936406088, "lm_q1q2_score": 0.007762289344410471}}
{"text": "/* Author: G. Jungman\n */\n#include <config.h>\n#include <stdlib.h>\n#include <string.h>\n#include <gsl/gsl_errno.h>\n#include \"gsl_qrng.h\"\n\n\ngsl_qrng *\ngsl_qrng_alloc (const gsl_qrng_type * T, unsigned int dimension)\n{\n\n  gsl_qrng * r = (gsl_qrng *) malloc (sizeof (gsl_qrng));\n\n  if (r == 0)\n    {\n      GSL_ERROR_VAL (\"allocation failed for qrng struct\",\n\t\t\tGSL_ENOMEM, 0);\n    };\n\n  r->dimension = dimension;\n  r->state_size = T->state_size(dimension);\n  r->state = malloc (r->state_size);\n\n  if (r->state == 0)\n    {\n      free (r);\n      GSL_ERROR_VAL (\"allocation failed for qrng state\",\n\t\t\tGSL_ENOMEM, 0);\n    };\n\n  r->type = T;\n\n  T->init_state(r->state, r->dimension);\n\n  return r;\n}\n\n\nint\ngsl_qrng_memcpy (gsl_qrng * dest, const gsl_qrng * src)\n{\n  if (dest->type != src->type)\n    {\n      GSL_ERROR (\"generators must be of the same type\", GSL_EINVAL);\n    }\n\n  dest->dimension = src->dimension;\n  dest->state_size = src->state_size;\n  memcpy (dest->state, src->state, src->state_size);\n\n  return GSL_SUCCESS;\n}\n\n\ngsl_qrng *\ngsl_qrng_clone (const gsl_qrng * q)\n{\n  gsl_qrng * r = (gsl_qrng *) malloc (sizeof (gsl_qrng));\n\n  if (r == 0)\n    {\n      GSL_ERROR_VAL (\"failed to allocate space for rng struct\",\n\t\t\tGSL_ENOMEM, 0);\n    };\n\n  r->dimension = q->dimension;\n  r->state_size = q->state_size;\n  r->state = malloc (r->state_size);\n\n  if (r->state == 0)\n    {\n      free (r);\n      GSL_ERROR_VAL (\"failed to allocate space for rng state\",\n\t\t\tGSL_ENOMEM, 0);\n    };\n\n  r->type = q->type;\n\n  memcpy (r->state, q->state, q->state_size);\n\n  return r;\n}\n\n#ifndef HIDE_INLINE_STATIC\nint\ngsl_qrng_get (const gsl_qrng * r, double x[])\n{\n  return (r->type->get) (r->state, r->dimension, x);\n}\n#endif\n\nconst char *\ngsl_qrng_name (const gsl_qrng * r)\n{\n  return r->type->name;\n}\n\n\nsize_t\ngsl_qrng_size (const gsl_qrng * r)\n{\n  return r->state_size;\n}\n\n\nvoid *\ngsl_qrng_state (const gsl_qrng * r)\n{\n  return r->state;\n}\n\n\nvoid\ngsl_qrng_free (gsl_qrng * r)\n{\n  if(r != 0) {\n    if(r->state != 0) free (r->state);\n    free (r);\n  }\n}\n", "meta": {"hexsha": "45e4e7ee17edcd87bd72a175a576f13a08f7d0ea", "size": 2028, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/qrng/qrng.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/qrng/qrng.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/qrng/qrng.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 16.487804878, "max_line_length": 68, "alphanum_fraction": 0.617357002, "num_tokens": 661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.256831980010821, "lm_q2_score": 0.030214585320878645, "lm_q1q2_score": 0.00776007177316715}}
{"text": "//Include guard\n#ifndef SEQUENCE_H\n#define SEQUENCE_H\n\n\n//Forward declared dependencies\n\n//Included dependencies\n#include <vector>\n#include <string>\n#include <gsl/gsl_rng.h>\n\nclass Sequence{\nprivate:\n    //Internal variables\n    std::vector<char> seq;\n    \npublic:\n    Sequence();\n    Sequence(int length);\n    Sequence(std::vector<char>& s);\n    Sequence(std::string s);\n    ~Sequence();\n    \n    void setSeq(std::vector<char>& s);\n\tstd::string getSeqAsString();\n    void setBase(int index, char b);\n    void addBase(char b);\n\tvoid removeBase(int index);\n    char getBase(int index);\n    int getLength();\n    void print();\n    std::string printToString();\n    std::string printToStringNoHyphens();\n    Sequence subset(int start, int finish);\n    void addBaseFront(char b);\n};\n\n#endif \n", "meta": {"hexsha": "80700d79ad4a1268dbb3ea5def779bca9b02236b", "size": 786, "ext": "h", "lang": "C", "max_stars_repo_path": "Codes/Codes_for_xStar/sequence.h", "max_stars_repo_name": "CasperLumby/Bottleneck_Size_Estimation", "max_stars_repo_head_hexsha": "9f9d81e35c1ac9dc74541401e8da70d428be1ad1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Codes/Codes_for_xStar/sequence.h", "max_issues_repo_name": "CasperLumby/Bottleneck_Size_Estimation", "max_issues_repo_head_hexsha": "9f9d81e35c1ac9dc74541401e8da70d428be1ad1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Codes/Codes_for_xStar/sequence.h", "max_forks_repo_name": "CasperLumby/Bottleneck_Size_Estimation", "max_forks_repo_head_hexsha": "9f9d81e35c1ac9dc74541401e8da70d428be1ad1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-06-12T13:25:36.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-12T13:25:36.000Z", "avg_line_length": 19.65, "max_line_length": 43, "alphanum_fraction": 0.6692111959, "num_tokens": 185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16026604837104663, "lm_q2_score": 0.048136775213228455, "lm_q1q2_score": 0.00771469074474947}}
{"text": "/* Copyright (C) 2021 Barcelona Supercomputing Center and University of\n * Illinois at Urbana-Champaign\n * SPDX-License-Identifier: MIT\n *\n * This is the c ODE solver for the chemistry module\n * It is currently set up to use the SUNDIALS BDF method, Newton\n * iteration with the KLU sparse linear solver.\n *\n * It uses a scalar relative tolerance and a vector absolute tolerance.\n *\n */\n/** \\file\n * \\brief Interface to c solvers for chemistry\n */\n#include \"camp_solver.h\"\n#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include \"aero_rep_solver.h\"\n#include \"rxn_solver.h\"\n#include \"sub_model_solver.h\"\n#ifdef CAMP_USE_GPU\n#include \"cuda/camp_gpu_solver.h\"\n#endif\n#ifdef CAMP_USE_GSL\n#include <gsl/gsl_deriv.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_roots.h>\n#endif\n#include \"camp_debug.h\"\n\n// Default solver initial time step relative to total integration time\n#define DEFAULT_TIME_STEP 1.0\n// State advancement factor for Jacobian element evaluation\n#define JAC_CHECK_ADV_MAX 1.0E-00\n#define JAC_CHECK_ADV_MIN 1.0E-12\n// Relative tolerance for Jacobian element evaluation against GSL absolute\n// errors\n#define JAC_CHECK_GSL_REL_TOL 1.0e-4\n// Absolute Jacobian error tolerance\n#define JAC_CHECK_GSL_ABS_TOL 1.0e-9\n// Set MAX_TIMESTEP_WARNINGS to a negative number to prevent output\n#define MAX_TIMESTEP_WARNINGS -1\n// Maximum number of steps in discreet addition guess helper\n#define GUESS_MAX_ITER 5\n\n// Status codes for calls to camp_solver functions\n#define CAMP_SOLVER_SUCCESS 0\n#define CAMP_SOLVER_FAIL 1\n\n/** \\brief Get a new solver object\n *\n * Return a pointer to a new SolverData object\n *\n * \\param n_state_var Number of variables on the state array per grid cell\n * \\param n_cells Number of grid cells to solve simultaneously\n * \\param var_type Pointer to array of state variable types (solver, constant,\n *                 PSSA)\n * \\param n_rxn Number of reactions to include\n * \\param n_rxn_int_param Total number of integer reaction parameters\n * \\param n_rxn_float_param Total number of floating-point reaction parameters\n * \\param n_rxn_env_param Total number of environment-dependent reaction\n * parameters \\param n_aero_phase Number of aerosol phases \\param\n * n_aero_phase_int_param Total number of integer aerosol phase parameters\n * \\param n_aero_phase_float_param Total number of floating-point aerosol phase\n *                                 parameters\n * \\param n_aero_rep Number of aerosol representations\n * \\param n_aero_rep_int_param Total number of integer aerosol representation\n *                             parameters\n * \\param n_aero_rep_float_param Total number of floating-point aerosol\n *                               representation parameters\n * \\param n_aero_rep_env_param Total number of environment-dependent aerosol\n *                             representation parameters\n * \\param n_sub_model Number of sub models\n * \\param n_sub_model_int_param Total number of integer sub model parameters\n * \\param n_sub_model_float_param Total number of floating-point sub model\n *                                parameters\n * \\param n_sub_model_env_param Total number of environment-dependent sub model\n *                              parameters\n * \\return Pointer to the new SolverData object\n */\nvoid *solver_new(int n_state_var, int n_cells, int *var_type, int n_rxn,\n                 int n_rxn_int_param, int n_rxn_float_param,\n                 int n_rxn_env_param, int n_aero_phase,\n                 int n_aero_phase_int_param, int n_aero_phase_float_param,\n                 int n_aero_rep, int n_aero_rep_int_param,\n                 int n_aero_rep_float_param, int n_aero_rep_env_param,\n                 int n_sub_model, int n_sub_model_int_param,\n                 int n_sub_model_float_param, int n_sub_model_env_param) {\n  // Create the SolverData object\n  SolverData *sd = (SolverData *)malloc(sizeof(SolverData));\n  if (sd == NULL) {\n    printf(\"\\n\\nERROR allocating space for SolverData\\n\\n\");\n    exit(EXIT_FAILURE);\n  }\n\n#ifdef CAMP_USE_SUNDIALS\n#ifdef CAMP_DEBUG\n  // Default to no debugging output\n  sd->debug_out = SUNFALSE;\n\n  // Initialize the Jac solver flag\n  sd->eval_Jac = SUNFALSE;\n#endif\n#endif\n\n  // Do not output precision loss by default\n  sd->output_precision = 0;\n\n  // Use the Jacobian estimated derivative in f() by default\n  sd->use_deriv_est = 1;\n\n  // Save the number of state variables per grid cell\n  sd->model_data.n_per_cell_state_var = n_state_var;\n\n  // Set number of cells to compute simultaneously\n  sd->model_data.n_cells = n_cells;\n\n  // Add the variable types to the solver data\n  sd->model_data.var_type = (int *)malloc(n_state_var * sizeof(int));\n  if (sd->model_data.var_type == NULL) {\n    printf(\"\\n\\nERROR allocating space for variable types\\n\\n\");\n    exit(EXIT_FAILURE);\n  }\n  for (int i = 0; i < n_state_var; i++)\n    sd->model_data.var_type[i] = var_type[i];\n\n  // Get the number of solver variables per grid cell\n  int n_dep_var = 0;\n  for (int i = 0; i < n_state_var; i++)\n    if (var_type[i] == CHEM_SPEC_VARIABLE) n_dep_var++;\n\n  // Save the number of solver variables per grid cell\n  sd->model_data.n_per_cell_dep_var = n_dep_var;\n\n#ifdef CAMP_USE_SUNDIALS\n  // Set up a TimeDerivative object to use during solving\n  if (time_derivative_initialize(&(sd->time_deriv), n_dep_var) != 1) {\n    printf(\"\\n\\nERROR initializing the TimeDerivative\\n\\n\");\n    exit(EXIT_FAILURE);\n  }\n\n  // Set up the solver variable array and helper derivative array\n  sd->y = N_VNew_Serial(n_dep_var * n_cells);\n  sd->deriv = N_VNew_Serial(n_dep_var * n_cells);\n#endif\n\n  // Allocate space for the reaction data and set the number\n  // of reactions (including one int for the number of reactions\n  // and one int per reaction to store the reaction type)\n  sd->model_data.rxn_int_data =\n      (int *)malloc((n_rxn_int_param + n_rxn) * sizeof(int));\n  if (sd->model_data.rxn_int_data == NULL) {\n    printf(\"\\n\\nERROR allocating space for reaction integer data\\n\\n\");\n    exit(EXIT_FAILURE);\n  }\n  sd->model_data.rxn_float_data =\n      (double *)malloc(n_rxn_float_param * sizeof(double));\n  if (sd->model_data.rxn_float_data == NULL) {\n    printf(\"\\n\\nERROR allocating space for reaction float data\\n\\n\");\n    exit(EXIT_FAILURE);\n  }\n  sd->model_data.rxn_env_data =\n      (double *)calloc(n_cells * n_rxn_env_param, sizeof(double));\n  if (sd->model_data.rxn_env_data == NULL) {\n    printf(\n        \"\\n\\nERROR allocating space for environment-dependent \"\n        \"data\\n\\n\");\n    exit(EXIT_FAILURE);\n  }\n\n  // Allocate space for the reaction data pointers\n  sd->model_data.rxn_int_indices = (int *)malloc((n_rxn + 1) * sizeof(int *));\n  if (sd->model_data.rxn_int_indices == NULL) {\n    printf(\"\\n\\nERROR allocating space for reaction integer indices\\n\\n\");\n    exit(EXIT_FAILURE);\n  }\n  sd->model_data.rxn_float_indices = (int *)malloc((n_rxn + 1) * sizeof(int *));\n  if (sd->model_data.rxn_float_indices == NULL) {\n    printf(\"\\n\\nERROR allocating space for reaction float indices\\n\\n\");\n    exit(EXIT_FAILURE);\n  }\n  sd->model_data.rxn_env_idx = (int *)malloc((n_rxn + 1) * sizeof(int));\n  if (sd->model_data.rxn_env_idx == NULL) {\n    printf(\n        \"\\n\\nERROR allocating space for reaction environment-dependent \"\n        \"data pointers\\n\\n\");\n    exit(EXIT_FAILURE);\n  }\n\n  sd->model_data.n_rxn = n_rxn;\n  sd->model_data.n_added_rxns = 0;\n  sd->model_data.n_rxn_env_data = 0;\n  sd->model_data.rxn_int_indices[0] = 0;\n  sd->model_data.rxn_float_indices[0] = 0;\n  sd->model_data.rxn_env_idx[0] = 0;\n\n  // If there are no reactions, flag the solver not to run\n  sd->no_solve = (n_rxn == 0);\n\n  // Allocate space for the aerosol phase data and st the number\n  // of aerosol phases (including one int for the number of\n  // phases)\n  sd->model_data.aero_phase_int_data =\n      (int *)malloc(n_aero_phase_int_param * sizeof(int));\n  if (sd->model_data.aero_phase_int_data == NULL) {\n    printf(\"\\n\\nERROR allocating space for aerosol phase integer data\\n\\n\");\n    exit(EXIT_FAILURE);\n  }\n  sd->model_data.aero_phase_float_data =\n      (double *)malloc(n_aero_phase_float_param * sizeof(double));\n  if (sd->model_data.aero_phase_float_data == NULL) {\n    printf(\n        \"\\n\\nERROR allocating space for aerosol phase floating-point \"\n        \"data\\n\\n\");\n    exit(EXIT_FAILURE);\n  }\n\n  // Allocate space for the aerosol phase data pointers\n  sd->model_data.aero_phase_int_indices =\n      (int *)malloc((n_aero_phase + 1) * sizeof(int *));\n  if (sd->model_data.aero_phase_int_indices == NULL) {\n    printf(\"\\n\\nERROR allocating space for reaction integer indices\\n\\n\");\n    exit(EXIT_FAILURE);\n  }\n  sd->model_data.aero_phase_float_indices =\n      (int *)malloc((n_aero_phase + 1) * sizeof(int *));\n  if (sd->model_data.aero_phase_float_indices == NULL) {\n    printf(\"\\n\\nERROR allocating space for reaction float indices\\n\\n\");\n    exit(EXIT_FAILURE);\n  }\n\n  sd->model_data.n_aero_phase = n_aero_phase;\n  sd->model_data.n_added_aero_phases = 0;\n  sd->model_data.aero_phase_int_indices[0] = 0;\n  sd->model_data.aero_phase_float_indices[0] = 0;\n\n  // Allocate space for the aerosol representation data and set\n  // the number of aerosol representations (including one int\n  // for the number of aerosol representations and one int per\n  // aerosol representation to store the aerosol representation\n  // type)\n  sd->model_data.aero_rep_int_data =\n      (int *)malloc((n_aero_rep_int_param + n_aero_rep) * sizeof(int));\n  if (sd->model_data.aero_rep_int_data == NULL) {\n    printf(\n        \"\\n\\nERROR allocating space for aerosol representation integer \"\n        \"data\\n\\n\");\n    exit(EXIT_FAILURE);\n  }\n  sd->model_data.aero_rep_float_data =\n      (double *)malloc(n_aero_rep_float_param * sizeof(double));\n  if (sd->model_data.aero_rep_float_data == NULL) {\n    printf(\n        \"\\n\\nERROR allocating space for aerosol representation \"\n        \"floating-point data\\n\\n\");\n    exit(EXIT_FAILURE);\n  }\n  sd->model_data.aero_rep_env_data =\n      (double *)calloc(n_cells * n_aero_rep_env_param, sizeof(double));\n  if (sd->model_data.aero_rep_env_data == NULL) {\n    printf(\n        \"\\n\\nERROR allocating space for aerosol representation \"\n        \"environmental parameters\\n\\n\");\n    exit(EXIT_FAILURE);\n  }\n\n  // Allocate space for the aerosol representation data pointers\n  sd->model_data.aero_rep_int_indices =\n      (int *)malloc((n_aero_rep + 1) * sizeof(int *));\n  if (sd->model_data.aero_rep_int_indices == NULL) {\n    printf(\"\\n\\nERROR allocating space for reaction integer indices\\n\\n\");\n    exit(EXIT_FAILURE);\n  }\n  sd->model_data.aero_rep_float_indices =\n      (int *)malloc((n_aero_rep + 1) * sizeof(int *));\n  if (sd->model_data.aero_rep_float_indices == NULL) {\n    printf(\"\\n\\nERROR allocating space for reaction float indices\\n\\n\");\n    exit(EXIT_FAILURE);\n  }\n  sd->model_data.aero_rep_env_idx =\n      (int *)malloc((n_aero_rep + 1) * sizeof(int));\n  if (sd->model_data.aero_rep_env_idx == NULL) {\n    printf(\n        \"\\n\\nERROR allocating space for aerosol representation \"\n        \"environment-dependent data pointers\\n\\n\");\n    exit(EXIT_FAILURE);\n  }\n\n  sd->model_data.n_aero_rep = n_aero_rep;\n  sd->model_data.n_added_aero_reps = 0;\n  sd->model_data.n_aero_rep_env_data = 0;\n  sd->model_data.aero_rep_int_indices[0] = 0;\n  sd->model_data.aero_rep_float_indices[0] = 0;\n  sd->model_data.aero_rep_env_idx[0] = 0;\n\n  // Allocate space for the sub model data and set the number of sub models\n  // (including one int for the number of sub models and one int per sub\n  // model to store the sub model type)\n  sd->model_data.sub_model_int_data =\n      (int *)malloc((n_sub_model_int_param + n_sub_model) * sizeof(int));\n  if (sd->model_data.sub_model_int_data == NULL) {\n    printf(\"\\n\\nERROR allocating space for sub model integer data\\n\\n\");\n    exit(EXIT_FAILURE);\n  }\n  sd->model_data.sub_model_float_data =\n      (double *)malloc(n_sub_model_float_param * sizeof(double));\n  if (sd->model_data.sub_model_float_data == NULL) {\n    printf(\"\\n\\nERROR allocating space for sub model floating-point data\\n\\n\");\n    exit(EXIT_FAILURE);\n  }\n  sd->model_data.sub_model_env_data =\n      (double *)calloc(n_cells * n_sub_model_env_param, sizeof(double));\n  if (sd->model_data.sub_model_env_data == NULL) {\n    printf(\n        \"\\n\\nERROR allocating space for sub model environment-dependent \"\n        \"data\\n\\n\");\n    exit(EXIT_FAILURE);\n  }\n\n  // Allocate space for the sub-model data pointers\n  sd->model_data.sub_model_int_indices =\n      (int *)malloc((n_sub_model + 1) * sizeof(int *));\n  if (sd->model_data.sub_model_int_indices == NULL) {\n    printf(\"\\n\\nERROR allocating space for reaction integer indices\\n\\n\");\n    exit(EXIT_FAILURE);\n  }\n  sd->model_data.sub_model_float_indices =\n      (int *)malloc((n_sub_model + 1) * sizeof(int *));\n  if (sd->model_data.sub_model_float_indices == NULL) {\n    printf(\"\\n\\nERROR allocating space for reaction float indices\\n\\n\");\n    exit(EXIT_FAILURE);\n  }\n  sd->model_data.sub_model_env_idx =\n      (int *)malloc((n_sub_model + 1) * sizeof(int));\n  if (sd->model_data.sub_model_env_idx == NULL) {\n    printf(\n        \"\\n\\nERROR allocating space for sub model environment-dependent \"\n        \"data pointers\\n\\n\");\n    exit(EXIT_FAILURE);\n  }\n\n  sd->model_data.n_sub_model = n_sub_model;\n  sd->model_data.n_added_sub_models = 0;\n  sd->model_data.n_sub_model_env_data = 0;\n  sd->model_data.sub_model_int_indices[0] = 0;\n  sd->model_data.sub_model_float_indices[0] = 0;\n  sd->model_data.sub_model_env_idx[0] = 0;\n\n#ifdef CAMP_USE_GPU\n  solver_new_gpu_cu(n_dep_var, n_state_var, n_rxn, n_rxn_int_param,\n                    n_rxn_float_param, n_rxn_env_param, n_cells);\n#endif\n\n#ifdef CAMP_DEBUG\n  if (sd->debug_out) print_data_sizes(&(sd->model_data));\n#endif\n\n  // Return a pointer to the new SolverData object\n  return (void *)sd;\n}\n\n/** \\brief Solver initialization\n *\n * Allocate and initialize solver objects\n *\n * \\param solver_data Pointer to a SolverData object\n * \\param abs_tol Pointer to array of absolute tolerances\n * \\param rel_tol Relative integration tolerance\n * \\param max_steps Maximum number of internal integration steps\n * \\param max_conv_fails Maximum number of convergence failures\n */\nvoid solver_initialize(void *solver_data, double *abs_tol, double rel_tol,\n                       int max_steps, int max_conv_fails) {\n#ifdef CAMP_USE_SUNDIALS\n  SolverData *sd;   // SolverData object\n  int flag;         // return code from SUNDIALS functions\n  int n_dep_var;    // number of dependent variables per grid cell\n  int i_dep_var;    // index of dependent variables in loops\n  int n_state_var;  // number of variables on the state array per\n                    // grid cell\n  int n_cells;      // number of cells to solve simultaneously\n  int *var_type;    // state variable types\n\n  // Seed the random number generator\n  srand((unsigned int)100);\n\n  // Get a pointer to the SolverData\n  sd = (SolverData *)solver_data;\n\n  // Create a new solver object\n  sd->cvode_mem = CVodeCreate(CV_BDF, CV_NEWTON);\n  check_flag_fail((void *)sd->cvode_mem, \"CVodeCreate\", 0);\n\n  // Get the number of total and dependent variables on the state array,\n  // and the type of each state variable. All values are per-grid-cell.\n  n_state_var = sd->model_data.n_per_cell_state_var;\n  n_dep_var = sd->model_data.n_per_cell_dep_var;\n  var_type = sd->model_data.var_type;\n  n_cells = sd->model_data.n_cells;\n\n  // Set the solver data\n  flag = CVodeSetUserData(sd->cvode_mem, sd);\n  check_flag_fail(&flag, \"CVodeSetUserData\", 1);\n\n  /* Call CVodeInit to initialize the integrator memory and specify the\n   * right-hand side function in y'=f(t,y), the initial time t0, and\n   * the initial dependent variable vector y. */\n  flag = CVodeInit(sd->cvode_mem, f, (realtype)0.0, sd->y);\n  check_flag_fail(&flag, \"CVodeInit\", 1);\n\n  // Set the relative and absolute tolerances\n  sd->abs_tol_nv = N_VNew_Serial(n_dep_var * n_cells);\n  i_dep_var = 0;\n  for (int i_cell = 0; i_cell < n_cells; ++i_cell)\n    for (int i_spec = 0; i_spec < n_state_var; ++i_spec)\n      if (var_type[i_spec] == CHEM_SPEC_VARIABLE)\n        NV_Ith_S(sd->abs_tol_nv, i_dep_var++) = (realtype)abs_tol[i_spec];\n  flag = CVodeSVtolerances(sd->cvode_mem, (realtype)rel_tol, sd->abs_tol_nv);\n  check_flag_fail(&flag, \"CVodeSVtolerances\", 1);\n\n  // Add a pointer in the model data to the absolute tolerances for use during\n  // solving. TODO find a better way to do this\n  sd->model_data.abs_tol = abs_tol;\n\n  // Set the maximum number of iterations\n  flag = CVodeSetMaxNumSteps(sd->cvode_mem, max_steps);\n  check_flag_fail(&flag, \"CVodeSetMaxNumSteps\", 1);\n\n  // Set the maximum number of convergence failures\n  flag = CVodeSetMaxConvFails(sd->cvode_mem, max_conv_fails);\n  check_flag_fail(&flag, \"CVodeSetMaxConvFails\", 1);\n\n  // Set the maximum number of error test failures (TODO make separate input?)\n  flag = CVodeSetMaxErrTestFails(sd->cvode_mem, max_conv_fails);\n  check_flag_fail(&flag, \"CVodeSetMaxErrTestFails\", 1);\n\n  // Set the maximum number of warnings about a too-small time step\n  flag = CVodeSetMaxHnilWarns(sd->cvode_mem, MAX_TIMESTEP_WARNINGS);\n  check_flag_fail(&flag, \"CVodeSetMaxHnilWarns\", 1);\n\n  // Get the structure of the Jacobian matrix\n  sd->J = get_jac_init(sd);\n  sd->model_data.J_init = SUNMatClone(sd->J);\n  SUNMatCopy(sd->J, sd->model_data.J_init);\n\n  // Create a Jacobian matrix for correcting negative predicted concentrations\n  // during solving\n  sd->J_guess = SUNMatClone(sd->J);\n  SUNMatCopy(sd->J, sd->J_guess);\n\n  // Create a KLU SUNLinearSolver\n  sd->ls = SUNKLU(sd->y, sd->J);\n  check_flag_fail((void *)sd->ls, \"SUNKLU\", 0);\n\n  // Attach the linear solver and Jacobian to the CVodeMem object\n  flag = CVDlsSetLinearSolver(sd->cvode_mem, sd->ls, sd->J);\n  check_flag_fail(&flag, \"CVDlsSetLinearSolver\", 1);\n\n  // Set the Jacobian function to Jac\n  flag = CVDlsSetJacFn(sd->cvode_mem, Jac);\n  check_flag_fail(&flag, \"CVDlsSetJacFn\", 1);\n\n  // Set a function to improve guesses for y sent to the linear solver\n  flag = CVodeSetDlsGuessHelper(sd->cvode_mem, guess_helper);\n  check_flag_fail(&flag, \"CVodeSetDlsGuessHelper\", 1);\n\n// Allocate Jacobian on GPU\n#ifdef CAMP_USE_GPU\n  allocate_jac_gpu(sd->model_data.n_per_cell_solver_jac_elem, n_cells);\n#endif\n\n// Set gpu rxn values\n#ifdef CAMP_USE_GPU\n  solver_set_rxn_data_gpu(&(sd->model_data));\n#endif\n\n#ifndef FAILURE_DETAIL\n  // Set a custom error handling function\n  flag = CVodeSetErrHandlerFn(sd->cvode_mem, error_handler, (void *)sd);\n  check_flag_fail(&flag, \"CVodeSetErrHandlerFn\", 0);\n#endif\n\n#endif\n}\n\n#ifdef CAMP_DEBUG\n/** \\brief Set the flag indicating whether to output debugging information\n *\n * \\param solver_data A pointer to the solver data\n * \\param do_output Whether to output debugging information during solving\n */\nint solver_set_debug_out(void *solver_data, bool do_output) {\n#ifdef CAMP_USE_SUNDIALS\n  SolverData *sd = (SolverData *)solver_data;\n\n  sd->debug_out = do_output == true ? SUNTRUE : SUNFALSE;\n  return CAMP_SOLVER_SUCCESS;\n#else\n  return 0;\n#endif\n}\n#endif\n\n#ifdef CAMP_DEBUG\n/** \\brief Set the flag indicating whether to evalute the Jacobian during\n **        solving\n *\n * \\param solver_data A pointer to the solver data\n * \\param eval_Jac Flag indicating whether to evaluate the Jacobian during\n *                 solving\n */\nint solver_set_eval_jac(void *solver_data, bool eval_Jac) {\n#ifdef CAMP_USE_SUNDIALS\n  SolverData *sd = (SolverData *)solver_data;\n\n  sd->eval_Jac = eval_Jac == true ? SUNTRUE : SUNFALSE;\n  return CAMP_SOLVER_SUCCESS;\n#else\n  return 0;\n#endif\n}\n#endif\n\n/** \\brief Solve for a given timestep\n *\n * \\param solver_data A pointer to the initialized solver data\n * \\param state A pointer to the full state array (all grid cells)\n * \\param env A pointer to the full array of environmental conditions\n *            (all grid cells)\n * \\param t_initial Initial time (s)\n * \\param t_final (s)\n * \\return Flag indicating CAMP_SOLVER_SUCCESS or CAMP_SOLVER_FAIL\n */\nint solver_run(void *solver_data, double *state, double *env, double t_initial,\n               double t_final) {\n#ifdef CAMP_USE_SUNDIALS\n  SolverData *sd = (SolverData *)solver_data;\n  ModelData *md = &(sd->model_data);\n  int n_state_var = sd->model_data.n_per_cell_state_var;\n  int n_cells = sd->model_data.n_cells;\n  int flag;\n\n  // Update the dependent variables\n  int i_dep_var = 0;\n  for (int i_cell = 0; i_cell < n_cells; i_cell++)\n    for (int i_spec = 0; i_spec < n_state_var; i_spec++)\n      if (sd->model_data.var_type[i_spec] == CHEM_SPEC_VARIABLE) {\n        NV_Ith_S(sd->y, i_dep_var++) =\n            state[i_spec + i_cell * n_state_var] > TINY\n                ? (realtype)state[i_spec + i_cell * n_state_var]\n                : TINY;\n      } else if (md->var_type[i_spec] == CHEM_SPEC_CONSTANT) {\n        state[i_spec + i_cell * n_state_var] =\n            state[i_spec + i_cell * n_state_var] > TINY\n                ? state[i_spec + i_cell * n_state_var]\n                : TINY;\n      }\n\n  // Update model data pointers\n  sd->model_data.total_state = state;\n  sd->model_data.total_env = env;\n\n#ifdef CAMP_DEBUG\n  // Update the debug output flag in CVODES and the linear solver\n  flag = CVodeSetDebugOut(sd->cvode_mem, sd->debug_out);\n  check_flag_fail(&flag, \"CVodeSetDebugOut\", 1);\n  flag = SUNKLUSetDebugOut(sd->ls, sd->debug_out);\n  check_flag_fail(&flag, \"SUNKLUSetDebugOut\", 1);\n#endif\n\n  // Reset the counter of Jacobian evaluation failures\n  sd->Jac_eval_fails = 0;\n\n  // Update data for new environmental state\n  // (This is set up to assume the environmental variables do not change during\n  //  solving. This can be changed in the future if necessary.)\n  for (int i_cell = 0; i_cell < md->n_cells; ++i_cell) {\n    // Set the grid cell state pointers\n    md->grid_cell_id = i_cell;\n    md->grid_cell_state = &(md->total_state[i_cell * md->n_per_cell_state_var]);\n    md->grid_cell_env = &(md->total_env[i_cell * CAMP_NUM_ENV_PARAM_]);\n    md->grid_cell_rxn_env_data =\n        &(md->rxn_env_data[i_cell * md->n_rxn_env_data]);\n    md->grid_cell_aero_rep_env_data =\n        &(md->aero_rep_env_data[i_cell * md->n_aero_rep_env_data]);\n    md->grid_cell_sub_model_env_data =\n        &(md->sub_model_env_data[i_cell * md->n_sub_model_env_data]);\n\n    // Update the model for the current environmental state\n    aero_rep_update_env_state(md);\n    sub_model_update_env_state(md);\n    rxn_update_env_state(md);\n  }\n\n  CAMP_DEBUG_JAC_STRUCT(sd->model_data.J_init, \"Begin solving\");\n\n  // Reset the flag indicating a current J_guess\n  sd->curr_J_guess = false;\n\n  // Set the initial time step\n  sd->init_time_step = (t_final - t_initial) * DEFAULT_TIME_STEP;\n\n  // Check whether there is anything to solve (filters empty air masses with no\n  // emissions)\n  if (is_anything_going_on_here(sd, t_initial, t_final) == false)\n    return CAMP_SOLVER_SUCCESS;\n\n  // Reinitialize the solver\n  flag = CVodeReInit(sd->cvode_mem, t_initial, sd->y);\n  check_flag_fail(&flag, \"CVodeReInit\", 1);\n\n  // Reinitialize the linear solver\n  flag = SUNKLUReInit(sd->ls, sd->J, SM_NNZ_S(sd->J), SUNKLU_REINIT_PARTIAL);\n  check_flag_fail(&flag, \"SUNKLUReInit\", 1);\n\n  // Set the inital time step\n  flag = CVodeSetInitStep(sd->cvode_mem, sd->init_time_step);\n  check_flag_fail(&flag, \"CVodeSetInitStep\", 1);\n\n  // Run the solver\n  realtype t_rt = (realtype)t_initial;\n  if (!sd->no_solve) {\n    flag = CVode(sd->cvode_mem, (realtype)t_final, sd->y, &t_rt, CV_NORMAL);\n    sd->solver_flag = flag;\n#ifndef FAILURE_DETAIL\n    if (flag < 0) {\n#else\n    if (check_flag(&flag, \"CVode\", 1) == CAMP_SOLVER_FAIL) {\n      if (flag == -6) {\n        long int lsflag;\n        int lastflag = CVDlsGetLastFlag(sd->cvode_mem, &lsflag);\n        printf(\"\\nLinear Solver Setup Fail: %d %ld\", lastflag, lsflag);\n      }\n      N_Vector deriv = N_VClone(sd->y);\n      flag = f(t_initial, sd->y, deriv, sd);\n      if (flag != 0)\n        printf(\"\\nCall to f() at failed state failed with flag %d\\n\", flag);\n      for (int i_cell = 0; i_cell < md->n_cells; ++i_cell) {\n        printf(\"\\n Cell: %d \", i_cell);\n        printf(\"temp = %le pressure = %le\\n\", env[i_cell * CAMP_NUM_ENV_PARAM_],\n               env[i_cell * CAMP_NUM_ENV_PARAM_ + 1]);\n        for (int i_spec = 0, i_dep_var = 0; i_spec < md->n_per_cell_state_var;\n             i_spec++)\n          if (md->var_type[i_spec] == CHEM_SPEC_VARIABLE) {\n            printf(\n                \"spec %d = %le deriv = %le\\n\", i_spec,\n                NV_Ith_S(sd->y, i_cell * md->n_per_cell_dep_var + i_dep_var),\n                NV_Ith_S(deriv, i_cell * md->n_per_cell_dep_var + i_dep_var));\n            i_dep_var++;\n          } else {\n            printf(\"spec %d = %le\\n\", i_spec,\n                   state[i_cell * md->n_per_cell_state_var + i_spec]);\n          }\n      }\n      solver_print_stats(sd->cvode_mem);\n#endif\n      return CAMP_SOLVER_FAIL;\n    }\n  }\n\n  // Update the species concentrations on the state array\n  i_dep_var = 0;\n  for (int i_cell = 0; i_cell < n_cells; i_cell++) {\n    for (int i_spec = 0; i_spec < n_state_var; i_spec++) {\n      if (md->var_type[i_spec] == CHEM_SPEC_VARIABLE) {\n        state[i_spec + i_cell * n_state_var] =\n            (double)(NV_Ith_S(sd->y, i_dep_var) > 0.0\n                         ? NV_Ith_S(sd->y, i_dep_var)\n                         : 0.0);\n        i_dep_var++;\n      }\n    }\n  }\n\n  // Re-run the pre-derivative calculations to update equilibrium species\n  // and apply adjustments to final state\n  sub_model_calculate(md);\n\n  return CAMP_SOLVER_SUCCESS;\n#else\n  return CAMP_SOLVER_FAIL;\n#endif\n}\n\n/** \\brief Get solver statistics after an integration attempt\n *\n * \\param solver_data           Pointer to the solver data\n * \\param solver_flag           Last flag returned by the solver\n * \\param num_steps             Pointer to set to the number of integration\n *                              steps\n * \\param RHS_evals             Pointer to set to the number of right-hand side\n *                              evaluations\n * \\param LS_setups             Pointer to set to the number of linear solver\n *                              setups\n * \\param error_test_fails      Pointer to set to the number of error test\n *                              failures\n * \\param NLS_iters             Pointer to set to the non-linear solver\n *                              iterations\n * \\param NLS_convergence_fails Pointer to set to the non-linear solver\n *                              convergence failures\n * \\param DLS_Jac_evals         Pointer to set to the direct linear solver\n *                              Jacobian evaluations\n * \\param DLS_RHS_evals         Pointer to set to the direct linear solver\n *                              right-hand side evaluations\n * \\param last_time_step__s     Pointer to set to the last time step size [s]\n * \\param next_time_step__s     Pointer to set to the next time step size [s]\n * \\param Jac_eval_fails        Number of Jacobian evaluation failures\n * \\param RHS_evals_total       Total calls to `f()`\n * \\param Jac_evals_total       Total calls to `Jac()`\n * \\param RHS_time__s           Compute time for calls to f() [s]\n * \\param Jac_time__s           Compute time for calls to Jac() [s]\n * \\param max_loss_precision    Indicators of loss of precision in derivative\n *                              calculation for each species\n */\nvoid solver_get_statistics(void *solver_data, int *solver_flag, int *num_steps,\n                           int *RHS_evals, int *LS_setups,\n                           int *error_test_fails, int *NLS_iters,\n                           int *NLS_convergence_fails, int *DLS_Jac_evals,\n                           int *DLS_RHS_evals, double *last_time_step__s,\n                           double *next_time_step__s, int *Jac_eval_fails,\n                           int *RHS_evals_total, int *Jac_evals_total,\n                           double *RHS_time__s, double *Jac_time__s,\n                           double *max_loss_precision) {\n#ifdef CAMP_USE_SUNDIALS\n  SolverData *sd = (SolverData *)solver_data;\n  long int nst, nfe, nsetups, nje, nfeLS, nni, ncfn, netf, nge;\n  realtype last_h, curr_h;\n  int flag;\n\n  *solver_flag = sd->solver_flag;\n  flag = CVodeGetNumSteps(sd->cvode_mem, &nst);\n  if (check_flag(&flag, \"CVodeGetNumSteps\", 1) == CAMP_SOLVER_FAIL) return;\n  *num_steps = (int)nst;\n  flag = CVodeGetNumRhsEvals(sd->cvode_mem, &nfe);\n  if (check_flag(&flag, \"CVodeGetNumRhsEvals\", 1) == CAMP_SOLVER_FAIL) return;\n  *RHS_evals = (int)nfe;\n  flag = CVodeGetNumLinSolvSetups(sd->cvode_mem, &nsetups);\n  if (check_flag(&flag, \"CVodeGetNumLinSolveSetups\", 1) == CAMP_SOLVER_FAIL)\n    return;\n  *LS_setups = (int)nsetups;\n  flag = CVodeGetNumErrTestFails(sd->cvode_mem, &netf);\n  if (check_flag(&flag, \"CVodeGetNumErrTestFails\", 1) == CAMP_SOLVER_FAIL)\n    return;\n  *error_test_fails = (int)netf;\n  flag = CVodeGetNumNonlinSolvIters(sd->cvode_mem, &nni);\n  if (check_flag(&flag, \"CVodeGetNonlinSolvIters\", 1) == CAMP_SOLVER_FAIL)\n    return;\n  *NLS_iters = (int)nni;\n  flag = CVodeGetNumNonlinSolvConvFails(sd->cvode_mem, &ncfn);\n  if (check_flag(&flag, \"CVodeGetNumNonlinSolvConvFails\", 1) ==\n      CAMP_SOLVER_FAIL)\n    return;\n  *NLS_convergence_fails = ncfn;\n  flag = CVDlsGetNumJacEvals(sd->cvode_mem, &nje);\n  if (check_flag(&flag, \"CVDlsGetNumJacEvals\", 1) == CAMP_SOLVER_FAIL) return;\n  *DLS_Jac_evals = (int)nje;\n  flag = CVDlsGetNumRhsEvals(sd->cvode_mem, &nfeLS);\n  if (check_flag(&flag, \"CVDlsGetNumRhsEvals\", 1) == CAMP_SOLVER_FAIL) return;\n  *DLS_RHS_evals = (int)nfeLS;\n  flag = CVodeGetLastStep(sd->cvode_mem, &last_h);\n  if (check_flag(&flag, \"CVodeGetLastStep\", 1) == CAMP_SOLVER_FAIL) return;\n  *last_time_step__s = (double)last_h;\n  flag = CVodeGetCurrentStep(sd->cvode_mem, &curr_h);\n  if (check_flag(&flag, \"CVodeGetCurrentStep\", 1) == CAMP_SOLVER_FAIL) return;\n  *next_time_step__s = (double)curr_h;\n  *Jac_eval_fails = sd->Jac_eval_fails;\n#ifdef CAMP_DEBUG\n  *RHS_evals_total = sd->counterDeriv;\n  *Jac_evals_total = sd->counterJac;\n  *RHS_time__s = ((double)sd->timeDeriv) / CLOCKS_PER_SEC;\n  *Jac_time__s = ((double)sd->timeJac) / CLOCKS_PER_SEC;\n  *max_loss_precision = sd->max_loss_precision;\n#else\n  *RHS_evals_total = -1;\n  *Jac_evals_total = -1;\n  *RHS_time__s = 0.0;\n  *Jac_time__s = 0.0;\n  *max_loss_precision = 0.0;\n#endif\n#endif\n}\n\n#ifdef CAMP_USE_SUNDIALS\n\n/** \\brief Update the model state from the current solver state\n *\n * \\param solver_state Solver state vector\n * \\param model_data Pointer to the model data (including the state array)\n * \\param threshhold A lower limit for model concentrations below which the\n *                   solver value is replaced with a replacement value\n * \\param replacement_value Replacement value for low concentrations\n * \\return CAMP_SOLVER_SUCCESS for successful update or\n *         CAMP_SOLVER_FAIL for negative concentration\n */\nint camp_solver_update_model_state(N_Vector solver_state, ModelData *model_data,\n                                   realtype threshhold,\n                                   realtype replacement_value) {\n  int n_state_var = model_data->n_per_cell_state_var;\n  int n_dep_var = model_data->n_per_cell_dep_var;\n  int n_cells = model_data->n_cells;\n\n  int i_dep_var = 0;\n  for (int i_cell = 0; i_cell < n_cells; i_cell++) {\n    for (int i_spec = 0; i_spec < n_state_var; ++i_spec) {\n      if (model_data->var_type[i_spec] == CHEM_SPEC_VARIABLE) {\n        if (NV_DATA_S(solver_state)[i_dep_var] < -SMALL) {\n#ifdef FAILURE_DETAIL\n          printf(\"\\nFailed model state update: [spec %d] = %le\", i_spec,\n                 NV_DATA_S(solver_state)[i_dep_var]);\n#endif\n          return CAMP_SOLVER_FAIL;\n        }\n        // Assign model state to solver_state\n        model_data->total_state[i_spec + i_cell * n_state_var] =\n            NV_DATA_S(solver_state)[i_dep_var] > threshhold\n                ? NV_DATA_S(solver_state)[i_dep_var]\n                : replacement_value;\n        i_dep_var++;\n      }\n    }\n  }\n  return CAMP_SOLVER_SUCCESS;\n}\n\n/** \\brief Compute the time derivative f(t,y)\n *\n * \\param t Current model time (s)\n * \\param y Dependent variable array\n * \\param deriv Time derivative vector f(t,y) to calculate\n * \\param solver_data Pointer to the solver data\n * \\return Status code\n */\nint f(realtype t, N_Vector y, N_Vector deriv, void *solver_data) {\n  SolverData *sd = (SolverData *)solver_data;\n  ModelData *md = &(sd->model_data);\n  realtype time_step;\n\n#ifdef CAMP_DEBUG\n  sd->counterDeriv++;\n#endif\n\n  // Get a pointer to the derivative data\n  double *deriv_data = N_VGetArrayPointer(deriv);\n\n  // Get a pointer to the Jacobian estimated derivative data\n  double *jac_deriv_data = N_VGetArrayPointer(md->J_tmp);\n\n  // Get the grid cell dimensions\n  int n_cells = md->n_cells;\n  int n_state_var = md->n_per_cell_state_var;\n  int n_dep_var = md->n_per_cell_dep_var;\n\n  // Get the current integrator time step (s)\n  CVodeGetCurrentStep(sd->cvode_mem, &time_step);\n\n  // On the first call to f(), the time step hasn't been set yet, so use the\n  // default value\n  time_step = time_step > ZERO ? time_step : sd->init_time_step;\n\n  // Update the state array with the current dependent variable values.\n  // Signal a recoverable error (positive return value) for negative\n  // concentrations.\n  if (camp_solver_update_model_state(y, md, -SMALL, TINY) != CAMP_SOLVER_SUCCESS)\n    return 1;\n\n  // Get the Jacobian-estimated derivative\n  N_VLinearSum(1.0, y, -1.0, md->J_state, md->J_tmp);\n  SUNMatMatvec(md->J_solver, md->J_tmp, md->J_tmp2);\n  N_VLinearSum(1.0, md->J_deriv, 1.0, md->J_tmp2, md->J_tmp);\n\n#ifdef CAMP_DEBUG\n  // Measure calc_deriv time execution\n  clock_t start = clock();\n#endif\n\n#ifdef CAMP_USE_GPU\n  // Reset the derivative vector\n  N_VConst(ZERO, deriv);\n\n  // Calculate the time derivative f(t,y)\n  // (this is for all grid cells at once)\n  rxn_calc_deriv_gpu(md, deriv, (double)time_step);\n#endif\n\n#ifdef CAMP_DEBUG\n  clock_t end = clock();\n  sd->timeDeriv += (end - start);\n#endif\n\n  // Loop through the grid cells and update the derivative array\n  for (int i_cell = 0; i_cell < n_cells; ++i_cell) {\n    // Set the grid cell state pointers\n    md->grid_cell_id = i_cell;\n    md->grid_cell_state = &(md->total_state[i_cell * n_state_var]);\n    md->grid_cell_env = &(md->total_env[i_cell * CAMP_NUM_ENV_PARAM_]);\n    md->grid_cell_rxn_env_data =\n        &(md->rxn_env_data[i_cell * md->n_rxn_env_data]);\n    md->grid_cell_aero_rep_env_data =\n        &(md->aero_rep_env_data[i_cell * md->n_aero_rep_env_data]);\n    md->grid_cell_sub_model_env_data =\n        &(md->sub_model_env_data[i_cell * md->n_sub_model_env_data]);\n\n    // Update the aerosol representations\n    aero_rep_update_state(md);\n\n    // Run the sub models\n    sub_model_calculate(md);\n\n#ifdef CAMP_DEBUG\n    // Measure calc_deriv time execution\n    clock_t start2 = clock();\n#endif\n\n#ifndef CAMP_USE_GPU\n    // Reset the TimeDerivative\n    time_derivative_reset(sd->time_deriv);\n\n    // Calculate the time derivative f(t,y)\n    rxn_calc_deriv(md, sd->time_deriv, (double)time_step);\n\n    // Update the deriv array\n    if (sd->use_deriv_est == 1) {\n      time_derivative_output(sd->time_deriv, deriv_data, jac_deriv_data,\n                             sd->output_precision);\n    } else {\n      time_derivative_output(sd->time_deriv, deriv_data, NULL,\n                             sd->output_precision);\n    }\n#else\n    // Add contributions from reactions not implemented on GPU\n    // FIXME need to fix this to use TimeDerivative\n    rxn_calc_deriv_specific_types(md, sd->time_deriv, (double)time_step);\n#endif\n\n#ifdef CAMP_DEBUG\n    clock_t end2 = clock();\n    sd->timeDeriv += (end2 - start2);\n    sd->max_loss_precision = time_derivative_max_loss_precision(sd->time_deriv);\n#endif\n\n    // Advance the derivative for the next cell\n    deriv_data += n_dep_var;\n    jac_deriv_data += n_dep_var;\n  }\n\n  // Return 0 if success\n  return (0);\n}\n\n/** \\brief Compute the Jacobian\n *\n * \\param t Current model time (s)\n * \\param y Dependent variable array\n * \\param deriv Time derivative vector f(t,y)\n * \\param J Jacobian to calculate\n * \\param solver_data Pointer to the solver data\n * \\param tmp1 Unused vector\n * \\param tmp2 Unused vector\n * \\param tmp3 Unused vector\n * \\return Status code\n */\nint Jac(realtype t, N_Vector y, N_Vector deriv, SUNMatrix J, void *solver_data,\n        N_Vector tmp1, N_Vector tmp2, N_Vector tmp3) {\n  SolverData *sd = (SolverData *)solver_data;\n  ModelData *md = &(sd->model_data);\n  realtype time_step;\n\n#ifdef CAMP_DEBUG\n  sd->counterJac++;\n#endif\n\n  // Get the grid cell dimensions\n  int n_state_var = md->n_per_cell_state_var;\n  int n_dep_var = md->n_per_cell_dep_var;\n  int n_cells = md->n_cells;\n\n  // Get pointers to the rxn and parameter Jacobian arrays\n  double *J_param_data = SM_DATA_S(md->J_params);\n  double *J_rxn_data = SM_DATA_S(md->J_rxn);\n  // Initialize the sparse matrix (sized for one grid cell)\n  // solver_data->model_data.J_rxn =\n  //    SUNSparseMatrix(n_state_var, n_state_var, n_jac_elem_rxn, CSC_MAT);\n\n  // TODO: use this instead of saving all this jacs\n  // double J_rxn_data[md->n_per_cell_dep_var];\n  // memset(J_rxn_data, 0, md->n_per_cell_dep_var * sizeof(double));\n\n  // double *J_rxn_data = (double*)calloc(md->n_per_cell_state_var,\n  // sizeof(double));\n\n  // !!!! Do not use tmp2 - it is the same as y !!!! //\n  // FIXME Find out why cvode is sending tmp2 as y\n\n  // Calculate the the derivative for the current state y without\n  // the estimated derivative from the last Jacobian calculation\n  sd->use_deriv_est = 0;\n  if (f(t, y, deriv, solver_data) != 0) {\n    printf(\"\\n Derivative calculation failed.\\n\");\n    sd->use_deriv_est = 1;\n    return 1;\n  }\n  sd->use_deriv_est = 1;\n\n  // Update the state array with the current dependent variable values\n  // Signal a recoverable error (positive return value) for negative\n  // concentrations.\n  if (camp_solver_update_model_state(y, md, -SMALL, TINY) != CAMP_SOLVER_SUCCESS)\n    return 1;\n\n  // Get the current integrator time step (s)\n  CVodeGetCurrentStep(sd->cvode_mem, &time_step);\n\n  // Reset the primary Jacobian\n  /// \\todo #83 Figure out how to stop CVODE from resizing the Jacobian\n  ///       during solving\n  SM_NNZ_S(J) = SM_NNZ_S(md->J_init);\n  for (int i = 0; i <= SM_NP_S(J); i++) {\n    (SM_INDEXPTRS_S(J))[i] = (SM_INDEXPTRS_S(md->J_init))[i];\n  }\n  for (int i = 0; i < SM_NNZ_S(J); i++) {\n    (SM_INDEXVALS_S(J))[i] = (SM_INDEXVALS_S(md->J_init))[i];\n    (SM_DATA_S(J))[i] = (realtype)0.0;\n  }\n\n#ifdef CAMP_DEBUG\n  clock_t start2 = clock();\n#endif\n\n#ifdef CAMP_USE_GPU\n  // Calculate the Jacobian\n  rxn_calc_jac_gpu(md, J, time_step);\n#endif\n\n#ifdef CAMP_DEBUG\n  clock_t end2 = clock();\n  sd->timeJac += (end2 - start2);\n#endif\n\n  // Solving on CPU only\n\n  // Loop over the grid cells to calculate sub-model and rxn Jacobians\n  for (int i_cell = 0; i_cell < n_cells; ++i_cell) {\n    // Set the grid cell state pointers\n    md->grid_cell_id = i_cell;\n    md->grid_cell_state = &(md->total_state[i_cell * n_state_var]);\n    md->grid_cell_env = &(md->total_env[i_cell * CAMP_NUM_ENV_PARAM_]);\n    md->grid_cell_rxn_env_data =\n        &(md->rxn_env_data[i_cell * md->n_rxn_env_data]);\n    md->grid_cell_aero_rep_env_data =\n        &(md->aero_rep_env_data[i_cell * md->n_aero_rep_env_data]);\n    md->grid_cell_sub_model_env_data =\n        &(md->sub_model_env_data[i_cell * md->n_sub_model_env_data]);\n\n    // Reset the sub-model and reaction Jacobians\n    for (int i = 0; i < SM_NNZ_S(md->J_params); ++i)\n      SM_DATA_S(md->J_params)[i] = 0.0;\n    jacobian_reset(sd->jac);\n\n    // Update the aerosol representations\n    aero_rep_update_state(md);\n\n    // Run the sub models and get the sub-model Jacobian\n    sub_model_calculate(md);\n    sub_model_get_jac_contrib(md, J_param_data, time_step);\n    CAMP_DEBUG_JAC(md->J_params, \"sub-model Jacobian\");\n\n#ifdef CAMP_DEBUG\n    clock_t start = clock();\n#endif\n\n#ifndef CAMP_USE_GPU\n    // Calculate the reaction Jacobian\n    rxn_calc_jac(md, sd->jac, time_step);\n#else\n    // Add contributions from reactions not implemented on GPU\n    rxn_calc_jac_specific_types(md, sd->jac, time_step);\n#endif\n\n// rxn_calc_jac_specific_types(md, J_rxn_data, time_step);\n#ifdef CAMP_DEBUG\n    clock_t end = clock();\n    sd->timeJac += (end - start);\n#endif\n\n    // Output the Jacobian to the SUNDIALS J_rxn\n    jacobian_output(sd->jac, SM_DATA_S(md->J_rxn));\n    CAMP_DEBUG_JAC(md->J_rxn, \"reaction Jacobian\");\n\n    // Set the solver Jacobian using the reaction and sub-model Jacobians\n    JacMap *jac_map = md->jac_map;\n    SM_DATA_S(md->J_params)[0] = 1.0;  // dummy value for non-sub model calcs\n    for (int i_map = 0; i_map < md->n_mapped_values; ++i_map)\n      SM_DATA_S(J)\n      [i_cell * md->n_per_cell_solver_jac_elem + jac_map[i_map].solver_id] +=\n          SM_DATA_S(md->J_rxn)[jac_map[i_map].rxn_id] *\n          SM_DATA_S(md->J_params)[jac_map[i_map].param_id];\n    CAMP_DEBUG_JAC(J, \"solver Jacobian\");\n  }\n\n  // Save the Jacobian for use with derivative calculations\n  for (int i_elem = 0; i_elem < SM_NNZ_S(J); ++i_elem)\n    SM_DATA_S(md->J_solver)[i_elem] = SM_DATA_S(J)[i_elem];\n  N_VScale(1.0, y, md->J_state);\n  N_VScale(1.0, deriv, md->J_deriv);\n\n#ifdef CAMP_DEBUG\n  // Evaluate the Jacobian if flagged to do so\n  if (sd->eval_Jac == SUNTRUE) {\n    if (!check_Jac(t, y, J, deriv, tmp1, tmp3, solver_data)) {\n      ++(sd->Jac_eval_fails);\n    }\n  }\n#endif\n\n  return (0);\n}\n\n/** \\brief Check a Jacobian for accuracy\n *\n * This function compares Jacobian elements against differences in derivative\n * calculations for small changes to the state array:\n * \\f[\n *   J_{ij}(x) = \\frac{f_i(x+\\sum_j e_j) - f_i(x)}{\\epsilon}\n * \\f]\n * where \\f$\\epsilon_j = 10^{-8} \\left|x_j\\right|\\f$\n *\n * \\param t Current time [s]\n * \\param y Current state array\n * \\param J Jacobian matrix to evaluate\n * \\param deriv Current derivative \\f$f(y)\\f$\n * \\param tmp Working array the size of \\f$y\\f$\n * \\param tmp1 Working array the size of \\f$y\\f$\n * \\param solver_data Solver data\n * \\return True if Jacobian values are accurate, false otherwise\n */\nbool check_Jac(realtype t, N_Vector y, SUNMatrix J, N_Vector deriv,\n               N_Vector tmp, N_Vector tmp1, void *solver_data) {\n  realtype *d_state = NV_DATA_S(y);\n  realtype *d_deriv = NV_DATA_S(deriv);\n  bool retval = true;\n\n#ifdef CAMP_USE_GSL\n  GSLParam gsl_param;\n  gsl_function gsl_func;\n\n  // Set up gsl parameters needed during numerical differentiation\n  gsl_param.t = t;\n  gsl_param.y = tmp;\n  gsl_param.deriv = tmp1;\n  gsl_param.solver_data = (SolverData *)solver_data;\n\n  // Set up the gsl function\n  gsl_func.function = &gsl_f;\n  gsl_func.params = &gsl_param;\n#endif\n\n  // Calculate the the derivative for the current state y\n  if (f(t, y, deriv, solver_data) != 0) {\n    printf(\"\\n Derivative calculation failed.\\n\");\n    return false;\n  }\n\n  // Loop through the independent variables, numerically calculating\n  // the partial derivatives d_fy/d_x\n  for (int i_ind = 0; i_ind < NV_LENGTH_S(y); ++i_ind) {\n    // If GSL is available, use their numerical differentiation to\n    // calculate the partial derivatives. Otherwise, estimate them by\n    // advancing the state.\n#ifdef CAMP_USE_GSL\n\n    // Reset tmp to the initial state\n    N_VScale(ONE, y, tmp);\n\n    // Save the independent species concentration and index\n    double x = d_state[i_ind];\n    gsl_param.ind_var = i_ind;\n\n    // Skip small concentrations\n    if (x < SMALL) continue;\n\n    // Do the numerical differentiation for each potentially non-zero\n    // Jacobian element\n    for (int i_elem = SM_INDEXPTRS_S(J)[i_ind];\n         i_elem < SM_INDEXPTRS_S(J)[i_ind + 1]; ++i_elem) {\n      int i_dep = SM_INDEXVALS_S(J)[i_elem];\n\n      double abs_err;\n      double partial_deriv;\n\n      gsl_param.dep_var = i_dep;\n\n      bool test_pass = false;\n      double h, abs_tol, rel_diff, scaling;\n\n      // Evaluate the Jacobian element over a range of initial step sizes\n      for (scaling = JAC_CHECK_ADV_MIN;\n           scaling <= JAC_CHECK_ADV_MAX && test_pass == false;\n           scaling *= 10.0) {\n        // Get the current initial step size\n        h = x * scaling;\n\n        // Get the partial derivative d_fy/dx\n        if (gsl_deriv_forward(&gsl_func, x, h, &partial_deriv, &abs_err) == 1) {\n          printf(\"\\nERROR in numerical differentiation for J[%d][%d]\", i_ind,\n                 i_dep);\n        }\n\n        // Evaluate the results\n        abs_tol = 1.2 * fabs(abs_err);\n        abs_tol =\n            abs_tol > JAC_CHECK_GSL_ABS_TOL ? abs_tol : JAC_CHECK_GSL_ABS_TOL;\n        rel_diff = 1.0;\n        if (partial_deriv != 0.0)\n          rel_diff =\n              fabs((SM_DATA_S(J)[i_elem] - partial_deriv) / partial_deriv);\n        if (fabs(SM_DATA_S(J)[i_elem] - partial_deriv) < abs_tol ||\n            rel_diff < JAC_CHECK_GSL_REL_TOL)\n          test_pass = true;\n      }\n\n      // If the test does not pass with any initial step size, print out the\n      // failure, output the local derivative state and return false\n      if (test_pass == false) {\n        printf(\n            \"\\nError in Jacobian[%d][%d]: Got %le; expected %le\"\n            \"\\n  difference %le is greater than error %le\",\n            i_ind, i_dep, SM_DATA_S(J)[i_elem], partial_deriv,\n            fabs(SM_DATA_S(J)[i_elem] - partial_deriv), abs_tol);\n        printf(\"\\n  relative error %le intial step size %le\", rel_diff, h);\n        printf(\"\\n  initial rate %le initial state %le\", d_deriv[i_dep],\n               d_state[i_ind]);\n        printf(\" scaling %le\", scaling);\n        ModelData *md = &(((SolverData *)solver_data)->model_data);\n        for (int i_cell = 0; i_cell < md->n_cells; ++i_cell)\n          for (int i_spec = 0; i_spec < md->n_per_cell_state_var; ++i_spec)\n            printf(\"\\n cell: %d species %d state_id %d conc: %le\", i_cell,\n                   i_spec, i_cell * md->n_per_cell_state_var + i_spec,\n                   md->total_state[i_cell * md->n_per_cell_state_var + i_spec]);\n        retval = false;\n        output_deriv_local_state(t, y, deriv, solver_data, &f, i_dep, i_ind,\n                                 SM_DATA_S(J)[i_elem], h / 10.0);\n      }\n    }\n#endif\n  }\n  return retval;\n}\n\n#ifdef CAMP_USE_GSL\n/** \\brief Wrapper function for derivative calculations for numerical solving\n *\n * Wraps the f(t,y) function for use by the GSL numerical differentiation\n * functions.\n *\n * \\param x Independent variable \\f$x\\f$ for calculations of \\f$df_y/dx\\f$\n * \\param param Differentiation parameters\n * \\return Partial derivative \\f$df_y/dx\\f$\n */\ndouble gsl_f(double x, void *param) {\n  GSLParam *gsl_param = (GSLParam *)param;\n  N_Vector y = gsl_param->y;\n  N_Vector deriv = gsl_param->deriv;\n\n  // Set the independent variable\n  NV_DATA_S(y)[gsl_param->ind_var] = x;\n\n  // Calculate the derivative\n  if (f(gsl_param->t, y, deriv, (void *)gsl_param->solver_data) != 0) {\n    printf(\"\\nDerivative calculation failed!\");\n    for (int i_spec = 0; i_spec < NV_LENGTH_S(y); ++i_spec)\n      printf(\"\\n species %d conc: %le\", i_spec, NV_DATA_S(y)[i_spec]);\n    return 0.0 / 0.0;\n  }\n\n  // Return the calculated derivative for the dependent variable\n  return NV_DATA_S(deriv)[gsl_param->dep_var];\n}\n#endif\n\n/** \\brief Try to improve guesses of y sent to the linear solver\n *\n * This function checks if there are any negative guessed concentrations,\n * and if there are it calculates a set of initial corrections to the\n * guessed state using the state at time \\f$t_{n-1}\\f$ and the derivative\n * \\f$f_{n-1}\\f$ and advancing the state according to:\n * \\f[\n *   y_n = y_{n-1} + \\sum_{j=1}^m h_j * f_j\n * \\f]\n * where \\f$h_j\\f$ is the largest timestep possible where\n * \\f[\n *   y_{j-1} + h_j * f_j > 0\n * \\f]\n * and\n * \\f[\n *   t_n = t_{n-1} + \\sum_{j=1}^m h_j\n * \\f]\n *\n * \\param t_n Current time [s]\n * \\param h_n Current time step size [s] If this is set to zero, the change hf\n *            is assumed to be an adjustment where y_n = y_n1 + hf\n * \\param y_n Current guess for \\f$y(t_n)\\f$\n * \\param y_n1 \\f$y(t_{n-1})\\f$\n * \\param hf Current guess for change in \\f$y\\f$ from \\f$t_{n-1}\\f$ to\n *            \\f$t_n\\f$ [input/output]\n * \\param solver_data Solver data\n * \\param tmp1 Temporary vector for calculations\n * \\param corr Vector of calculated adjustments to \\f$y(t_n)\\f$ [output]\n * \\return 1 if corrections were calculated, 0 if not\n */\nint guess_helper(const realtype t_n, const realtype h_n, N_Vector y_n,\n                 N_Vector y_n1, N_Vector hf, void *solver_data, N_Vector tmp1,\n                 N_Vector corr) {\n  SolverData *sd = (SolverData *)solver_data;\n  realtype *ay_n = NV_DATA_S(y_n);\n  realtype *ay_n1 = NV_DATA_S(y_n1);\n  realtype *atmp1 = NV_DATA_S(tmp1);\n  realtype *acorr = NV_DATA_S(corr);\n  realtype *ahf = NV_DATA_S(hf);\n  int n_elem = NV_LENGTH_S(y_n);\n\n  // Only try improvements when negative concentrations are predicted\n  if (N_VMin(y_n) > -SMALL) return 0;\n\n  CAMP_DEBUG_PRINT_FULL(\"Trying to improve guess\");\n\n  // Copy \\f$y(t_{n-1})\\f$ to working array\n  N_VScale(ONE, y_n1, tmp1);\n\n  // Get  \\f$f(t_{n-1})\\f$\n  if (h_n > ZERO) {\n    N_VScale(ONE / h_n, hf, corr);\n  } else {\n    N_VScale(ONE, hf, corr);\n  }\n  CAMP_DEBUG_PRINT(\"Got f0\");\n\n  // Advance state interatively\n  realtype t_0 = h_n > ZERO ? t_n - h_n : t_n - ONE;\n  realtype t_j = ZERO;\n  int iter = 0;\n  for (; iter < GUESS_MAX_ITER && t_0 + t_j < t_n; iter++) {\n    // Calculate \\f$h_j\\f$\n    realtype h_j = t_n - (t_0 + t_j);\n    int i_fast = -1;\n    for (int i = 0; i < n_elem; i++) {\n      realtype t_star = -atmp1[i] / acorr[i];\n      if ((t_star > ZERO || (t_star == ZERO && acorr[i] < ZERO)) &&\n          t_star < h_j) {\n        h_j = t_star;\n        i_fast = i;\n      }\n    }\n\n    // Scale incomplete jumps\n    if (i_fast >= 0 && h_n > ZERO)\n      h_j *= 0.95 + 0.1 * rand() / (double)RAND_MAX;\n    h_j = t_n < t_0 + t_j + h_j ? t_n - (t_0 + t_j) : h_j;\n\n    // Only make small changes to adjustment vectors used in Newton iteration\n    if (h_n == ZERO &&\n        t_n - (h_j + t_j + t_0) > ((CVodeMem)sd->cvode_mem)->cv_reltol)\n      return -1;\n\n    // Advance the state\n    N_VLinearSum(ONE, tmp1, h_j, corr, tmp1);\n    CAMP_DEBUG_PRINT_FULL(\"Advanced state\");\n\n    // Advance t_j\n    t_j += h_j;\n\n    // Recalculate the time derivative \\f$f(t_j)\\f$\n    if (f(t_0 + t_j, tmp1, corr, solver_data) != 0) {\n      CAMP_DEBUG_PRINT(\"Unexpected failure in guess helper!\");\n      N_VConst(ZERO, corr);\n      return -1;\n    }\n    ((CVodeMem)sd->cvode_mem)->cv_nfe++;\n\n    if (iter == GUESS_MAX_ITER - 1 && t_0 + t_j < t_n) {\n      CAMP_DEBUG_PRINT(\"Max guess iterations reached!\");\n      if (h_n == ZERO) return -1;\n    }\n  }\n\n  CAMP_DEBUG_PRINT_INT(\"Guessed y_h in steps:\", iter);\n\n  // Set the correction vector\n  N_VLinearSum(ONE, tmp1, -ONE, y_n, corr);\n\n  // Scale the initial corrections\n  if (h_n > ZERO) N_VScale(0.999, corr, corr);\n\n  // Update the hf vector\n  N_VLinearSum(ONE, tmp1, -ONE, y_n1, hf);\n\n  return 1;\n}\n\n/** \\brief Create a sparse Jacobian matrix based on model data\n *\n * \\param solver_data A pointer to the SolverData\n * \\return Sparse Jacobian matrix with all possible non-zero elements intialize\n *         to 1.0\n */\nSUNMatrix get_jac_init(SolverData *solver_data) {\n  int n_rxn;                      /* number of reactions in the mechanism\n                                   * (stored in first position in *rxn_data) */\n  sunindextype n_jac_elem_rxn;    /* number of potentially non-zero Jacobian\n                                     elements in the reaction matrix*/\n  sunindextype n_jac_elem_param;  /* number of potentially non-zero Jacobian\n                                     elements in the reaction matrix*/\n  sunindextype n_jac_elem_solver; /* number of potentially non-zero Jacobian\n                                     elements in the reaction matrix*/\n  // Number of grid cells\n  int n_cells = solver_data->model_data.n_cells;\n\n  // Number of variables on the state array per grid cell\n  // (these are the ids the reactions are initialized with)\n  int n_state_var = solver_data->model_data.n_per_cell_state_var;\n\n  // Number of total state variables\n  int n_state_var_total = n_state_var * n_cells;\n\n  // Number of solver variables per grid cell (excludes constants, parameters,\n  // etc.)\n  int n_dep_var = solver_data->model_data.n_per_cell_dep_var;\n\n  // Number of total solver variables\n  int n_dep_var_total = n_dep_var * n_cells;\n\n  // Initialize the Jacobian for reactions\n  if (jacobian_initialize_empty(&(solver_data->jac),\n                                (unsigned int)n_state_var) != 1) {\n    printf(\"\\n\\nERROR allocating Jacobian structure\\n\\n\");\n    exit(EXIT_FAILURE);\n  }\n\n  // Add diagonal elements by default\n  for (unsigned int i_spec = 0; i_spec < n_state_var; ++i_spec) {\n    jacobian_register_element(&(solver_data->jac), i_spec, i_spec);\n  }\n\n  // Fill in the 2D array of flags with Jacobian elements used by the\n  // mechanism reactions for a single grid cell\n  rxn_get_used_jac_elem(&(solver_data->model_data), &(solver_data->jac));\n\n  // Build the sparse Jacobian\n  if (jacobian_build_matrix(&(solver_data->jac)) != 1) {\n    printf(\"\\n\\nERROR building sparse full-state Jacobian\\n\\n\");\n    exit(EXIT_FAILURE);\n  }\n\n  // Determine the number of non-zero Jacobian elements per grid cell\n  n_jac_elem_rxn = jacobian_number_of_elements(solver_data->jac);\n\n  // Save number of reaction jacobian elements per grid cell\n  solver_data->model_data.n_per_cell_rxn_jac_elem = (int)n_jac_elem_rxn;\n\n  // Initialize the sparse matrix (sized for one grid cell)\n  solver_data->model_data.J_rxn =\n      SUNSparseMatrix(n_state_var, n_state_var, n_jac_elem_rxn, CSC_MAT);\n\n  // Set the column and row indices\n  for (unsigned int i_col = 0; i_col <= n_state_var; ++i_col) {\n    (SM_INDEXPTRS_S(solver_data->model_data.J_rxn))[i_col] =\n        jacobian_column_pointer_value(solver_data->jac, i_col);\n  }\n  for (unsigned int i_elem = 0; i_elem < n_jac_elem_rxn; ++i_elem) {\n    (SM_DATA_S(solver_data->model_data.J_rxn))[i_elem] = (realtype)0.0;\n    (SM_INDEXVALS_S(solver_data->model_data.J_rxn))[i_elem] =\n        jacobian_row_index(solver_data->jac, i_elem);\n  }\n\n  // Build the set of time derivative ids\n  int *deriv_ids = (int *)malloc(sizeof(int) * n_state_var);\n\n  if (deriv_ids == NULL) {\n    printf(\"\\n\\nERROR allocating space for derivative ids\\n\\n\");\n    exit(EXIT_FAILURE);\n  }\n  int i_dep_var = 0;\n  for (int i_spec = 0; i_spec < n_state_var; i_spec++) {\n    if (solver_data->model_data.var_type[i_spec] == CHEM_SPEC_VARIABLE) {\n      deriv_ids[i_spec] = i_dep_var++;\n    } else {\n      deriv_ids[i_spec] = -1;\n    }\n  }\n\n  // Update the ids in the reaction data\n  rxn_update_ids(&(solver_data->model_data), deriv_ids, solver_data->jac);\n\n  ////////////////////////////////////////////////////////////////////////\n  // Get the Jacobian elements used in sub model parameter calculations //\n  ////////////////////////////////////////////////////////////////////////\n\n  // Initialize the Jacobian for sub-model parameters\n  Jacobian param_jac;\n  if (jacobian_initialize_empty(&param_jac, (unsigned int)n_state_var) != 1) {\n    printf(\"\\n\\nERROR allocating sub-model Jacobian structure\\n\\n\");\n    exit(EXIT_FAILURE);\n  }\n\n  // Set up a dummy element at the first position\n  jacobian_register_element(&param_jac, 0, 0);\n\n  // Fill in the 2D array of flags with Jacobian elements used by the\n  // mechanism sub models\n  sub_model_get_used_jac_elem(&(solver_data->model_data), &param_jac);\n\n  // Build the sparse Jacobian for sub-model parameters\n  if (jacobian_build_matrix(&param_jac) != 1) {\n    printf(\"\\n\\nERROR building sparse Jacobian for sub-model parameters\\n\\n\");\n    exit(EXIT_FAILURE);\n  }\n\n  // Save the number of sub model Jacobian elements per grid cell\n  n_jac_elem_param = jacobian_number_of_elements(param_jac);\n  solver_data->model_data.n_per_cell_param_jac_elem = (int)n_jac_elem_param;\n\n  // Set up the parameter Jacobian (sized for one grid cell)\n  // Initialize the sparse matrix with one extra element (at the first position)\n  // for use in mapping that is set to 1.0. (This is safe because there can be\n  // no elements on the diagonal in the sub model Jacobian.)\n  solver_data->model_data.J_params =\n      SUNSparseMatrix(n_state_var, n_state_var, n_jac_elem_param, CSC_MAT);\n\n  // Set the column and row indices\n  for (unsigned int i_col = 0; i_col <= n_state_var; ++i_col) {\n    (SM_INDEXPTRS_S(solver_data->model_data.J_params))[i_col] =\n        jacobian_column_pointer_value(param_jac, i_col);\n  }\n  for (unsigned int i_elem = 0; i_elem < n_jac_elem_param; ++i_elem) {\n    (SM_DATA_S(solver_data->model_data.J_params))[i_elem] = (realtype)0.0;\n    (SM_INDEXVALS_S(solver_data->model_data.J_params))[i_elem] =\n        jacobian_row_index(param_jac, i_elem);\n  }\n\n  // Update the ids in the sub model data\n  sub_model_update_ids(&(solver_data->model_data), deriv_ids, param_jac);\n\n  ////////////////////////////////\n  // Set up the solver Jacobian //\n  ////////////////////////////////\n\n  // Initialize the Jacobian for sub-model parameters\n  Jacobian solver_jac;\n  if (jacobian_initialize_empty(&solver_jac, (unsigned int)n_state_var) != 1) {\n    printf(\"\\n\\nERROR allocating solver Jacobian structure\\n\\n\");\n    exit(EXIT_FAILURE);\n  }\n\n  // Determine the structure of the solver Jacobian and number of mapped values\n  int n_mapped_values = 0;\n  for (int i_ind = 0; i_ind < n_state_var; ++i_ind) {\n    for (int i_dep = 0; i_dep < n_state_var; ++i_dep) {\n      // skip dependent species that are not solver variables and\n      // depenedent species that aren't used by any reaction\n      if (solver_data->model_data.var_type[i_dep] != CHEM_SPEC_VARIABLE ||\n          jacobian_get_element_id(solver_data->jac, i_dep, i_ind) == -1)\n        continue;\n      // If both elements are variable, use the rxn Jacobian only\n      if (solver_data->model_data.var_type[i_ind] == CHEM_SPEC_VARIABLE &&\n          solver_data->model_data.var_type[i_dep] == CHEM_SPEC_VARIABLE) {\n        jacobian_register_element(&solver_jac, i_dep, i_ind);\n        ++n_mapped_values;\n        continue;\n      }\n      // Check the sub model Jacobian for remaining conditions\n      /// \\todo Make the Jacobian mapping recursive for sub model parameters\n      ///       that depend on other sub model parameters\n      for (int j_ind = 0; j_ind < n_state_var; ++j_ind) {\n        if (jacobian_get_element_id(param_jac, i_ind, j_ind) != -1 &&\n            solver_data->model_data.var_type[j_ind] == CHEM_SPEC_VARIABLE) {\n          jacobian_register_element(&solver_jac, i_dep, j_ind);\n          ++n_mapped_values;\n        }\n      }\n    }\n  }\n\n  // Build the sparse solver Jacobian\n  if (jacobian_build_matrix(&solver_jac) != 1) {\n    printf(\"\\n\\nERROR building sparse Jacobian for the solver\\n\\n\");\n    exit(EXIT_FAILURE);\n  }\n\n  // Save the number of non-zero Jacobian elements\n  n_jac_elem_solver = jacobian_number_of_elements(solver_jac);\n  solver_data->model_data.n_per_cell_solver_jac_elem = (int)n_jac_elem_solver;\n\n  // Initialize the sparse matrix (for solver state array including all cells)\n  SUNMatrix M = SUNSparseMatrix(n_dep_var_total, n_dep_var_total,\n                                n_jac_elem_solver * n_cells, CSC_MAT);\n  solver_data->model_data.J_solver = SUNSparseMatrix(\n      n_dep_var_total, n_dep_var_total, n_jac_elem_solver * n_cells, CSC_MAT);\n\n  // Set the column and row indices\n  for (unsigned int i_cell = 0; i_cell < n_cells; ++i_cell) {\n    for (unsigned int cell_col = 0; cell_col < n_state_var; ++cell_col) {\n      if (deriv_ids[cell_col] == -1) continue;\n      unsigned int i_col = deriv_ids[cell_col] + i_cell * n_dep_var;\n      (SM_INDEXPTRS_S(M))[i_col] =\n          (SM_INDEXPTRS_S(solver_data->model_data.J_solver))[i_col] =\n              jacobian_column_pointer_value(solver_jac, cell_col) +\n              i_cell * n_jac_elem_solver;\n    }\n    for (unsigned int cell_elem = 0; cell_elem < n_jac_elem_solver;\n         ++cell_elem) {\n      unsigned int i_elem = cell_elem + i_cell * n_jac_elem_solver;\n      (SM_DATA_S(M))[i_elem] =\n          (SM_DATA_S(solver_data->model_data.J_solver))[i_elem] = (realtype)0.0;\n      (SM_INDEXVALS_S(M))[i_elem] =\n          (SM_INDEXVALS_S(solver_data->model_data.J_solver))[i_elem] =\n              deriv_ids[jacobian_row_index(solver_jac, cell_elem)] +\n              i_cell * n_dep_var;\n    }\n  }\n  (SM_INDEXPTRS_S(M))[n_cells * n_dep_var] =\n      (SM_INDEXPTRS_S(solver_data->model_data.J_solver))[n_cells * n_dep_var] =\n          n_cells * n_jac_elem_solver;\n\n  // Allocate space for the map\n  solver_data->model_data.n_mapped_values = n_mapped_values;\n  solver_data->model_data.jac_map =\n      (JacMap *)malloc(sizeof(JacMap) * n_mapped_values);\n  if (solver_data->model_data.jac_map == NULL) {\n    printf(\"\\n\\nERROR allocating space for jacobian map\\n\\n\");\n    exit(EXIT_FAILURE);\n  }\n  JacMap *map = solver_data->model_data.jac_map;\n\n  // Set map indices (when no sub-model value is used, the param_id is\n  // set to 0 which maps to a fixed value of 1.0\n  int i_mapped_value = 0;\n  for (unsigned int i_ind = 0; i_ind < n_state_var; ++i_ind) {\n    for (unsigned int i_elem =\n             jacobian_column_pointer_value(solver_data->jac, i_ind);\n         i_elem < jacobian_column_pointer_value(solver_data->jac, i_ind + 1);\n         ++i_elem) {\n      unsigned int i_dep = jacobian_row_index(solver_data->jac, i_elem);\n      // skip dependent species that are not solver variables and\n      // depenedent species that aren't used by any reaction\n      if (solver_data->model_data.var_type[i_dep] != CHEM_SPEC_VARIABLE ||\n          jacobian_get_element_id(solver_data->jac, i_dep, i_ind) == -1)\n        continue;\n      // If both elements are variable, use the rxn Jacobian only\n      if (solver_data->model_data.var_type[i_ind] == CHEM_SPEC_VARIABLE &&\n          solver_data->model_data.var_type[i_dep] == CHEM_SPEC_VARIABLE) {\n        map[i_mapped_value].solver_id =\n            jacobian_get_element_id(solver_jac, i_dep, i_ind);\n        map[i_mapped_value].rxn_id = i_elem;\n        map[i_mapped_value].param_id = 0;\n        ++i_mapped_value;\n        continue;\n      }\n      // Check the sub model Jacobian for remaining conditions\n      // (variable dependent species; independent parameter from sub model)\n      for (int j_ind = 0; j_ind < n_state_var; ++j_ind) {\n        if (jacobian_get_element_id(param_jac, i_ind, j_ind) != -1 &&\n            solver_data->model_data.var_type[j_ind] == CHEM_SPEC_VARIABLE) {\n          map[i_mapped_value].solver_id =\n              jacobian_get_element_id(solver_jac, i_dep, j_ind);\n          map[i_mapped_value].rxn_id = i_elem;\n          map[i_mapped_value].param_id =\n              jacobian_get_element_id(param_jac, i_ind, j_ind);\n          ++i_mapped_value;\n        }\n      }\n    }\n  }\n\n  SolverData *sd = solver_data;\n  CAMP_DEBUG_JAC_STRUCT(sd->model_data.J_params, \"Param struct\");\n  CAMP_DEBUG_JAC_STRUCT(sd->model_data.J_rxn, \"Reaction struct\");\n  CAMP_DEBUG_JAC_STRUCT(M, \"Solver struct\");\n\n  if (i_mapped_value != n_mapped_values) {\n    printf(\"[ERROR-340355266] Internal error\");\n    exit(EXIT_FAILURE);\n  }\n\n  // Create vectors to store Jacobian state and derivative data\n  solver_data->model_data.J_state = N_VClone(solver_data->y);\n  solver_data->model_data.J_deriv = N_VClone(solver_data->y);\n  solver_data->model_data.J_tmp = N_VClone(solver_data->y);\n  solver_data->model_data.J_tmp2 = N_VClone(solver_data->y);\n\n  // Initialize the Jacobian state and derivative arrays to zero\n  // for use before the first call to Jac()\n  N_VConst(0.0, solver_data->model_data.J_state);\n  N_VConst(0.0, solver_data->model_data.J_deriv);\n\n  // Free the memory used\n  jacobian_free(&param_jac);\n  jacobian_free(&solver_jac);\n  free(deriv_ids);\n\n  return M;\n}\n\n/** \\brief Check the return value of a SUNDIALS function\n *\n * \\param flag_value A pointer to check (either for NULL, or as an int pointer\n *                   giving the flag value\n * \\param func_name A string giving the function name returning this result code\n * \\param opt A flag indicating the type of check to perform (0 for NULL\n *            pointer check; 1 for integer flag check)\n * \\return Flag indicating CAMP_SOLVER_SUCCESS or CAMP_SOLVER_FAIL\n */\nint check_flag(void *flag_value, char *func_name, int opt) {\n  int *err_flag;\n\n  /* Check for a NULL pointer */\n  if (opt == 0 && flag_value == NULL) {\n    fprintf(stderr, \"\\nSUNDIALS_ERROR: %s() failed - returned NULL pointer\\n\\n\",\n            func_name);\n    return CAMP_SOLVER_FAIL;\n  }\n\n  /* Check if flag < 0 */\n  else if (opt == 1) {\n    err_flag = (int *)flag_value;\n    if (*err_flag < 0) {\n      fprintf(stderr, \"\\nSUNDIALS_ERROR: %s() failed with flag = %d\\n\\n\",\n              func_name, *err_flag);\n      return CAMP_SOLVER_FAIL;\n    }\n  }\n  return CAMP_SOLVER_SUCCESS;\n}\n\n/** \\brief Check the return value of a SUNDIALS function and exit on failure\n *\n * \\param flag_value A pointer to check (either for NULL, or as an int pointer\n *                   giving the flag value\n * \\param func_name A string giving the function name returning this result code\n * \\param opt A flag indicating the type of check to perform (0 for NULL\n *            pointer check; 1 for integer flag check)\n */\nvoid check_flag_fail(void *flag_value, char *func_name, int opt) {\n  if (check_flag(flag_value, func_name, opt) == CAMP_SOLVER_FAIL) {\n    exit(EXIT_FAILURE);\n  }\n}\n\n/** \\brief Reset the timers for solver functions\n *\n * \\param solver_data Pointer to the SolverData object with timers to reset\n */\n#ifdef CAMP_USE_SUNDIALS\nvoid solver_reset_timers(void *solver_data) {\n  SolverData *sd = (SolverData *)solver_data;\n\n#ifdef CAMP_DEBUG\n  sd->counterDeriv = 0;\n  sd->counterJac = 0;\n  sd->timeDeriv = 0;\n  sd->timeJac = 0;\n#endif\n}\n#endif\n\n/** \\brief Print solver statistics\n *\n * \\param cvode_mem Solver object\n */\nstatic void solver_print_stats(void *cvode_mem) {\n  long int nst, nfe, nsetups, nje, nfeLS, nni, ncfn, netf, nge;\n  realtype last_h, curr_h;\n  int flag;\n\n  flag = CVodeGetNumSteps(cvode_mem, &nst);\n  if (check_flag(&flag, \"CVodeGetNumSteps\", 1) == CAMP_SOLVER_FAIL) return;\n  flag = CVodeGetNumRhsEvals(cvode_mem, &nfe);\n  if (check_flag(&flag, \"CVodeGetNumRhsEvals\", 1) == CAMP_SOLVER_FAIL) return;\n  flag = CVodeGetNumLinSolvSetups(cvode_mem, &nsetups);\n  if (check_flag(&flag, \"CVodeGetNumLinSolveSetups\", 1) == CAMP_SOLVER_FAIL)\n    return;\n  flag = CVodeGetNumErrTestFails(cvode_mem, &netf);\n  if (check_flag(&flag, \"CVodeGetNumErrTestFails\", 1) == CAMP_SOLVER_FAIL)\n    return;\n  flag = CVodeGetNumNonlinSolvIters(cvode_mem, &nni);\n  if (check_flag(&flag, \"CVodeGetNonlinSolvIters\", 1) == CAMP_SOLVER_FAIL)\n    return;\n  flag = CVodeGetNumNonlinSolvConvFails(cvode_mem, &ncfn);\n  if (check_flag(&flag, \"CVodeGetNumNonlinSolvConvFails\", 1) ==\n      CAMP_SOLVER_FAIL)\n    return;\n  flag = CVDlsGetNumJacEvals(cvode_mem, &nje);\n  if (check_flag(&flag, \"CVDlsGetNumJacEvals\", 1) == CAMP_SOLVER_FAIL) return;\n  flag = CVDlsGetNumRhsEvals(cvode_mem, &nfeLS);\n  if (check_flag(&flag, \"CVDlsGetNumRhsEvals\", 1) == CAMP_SOLVER_FAIL) return;\n  flag = CVodeGetNumGEvals(cvode_mem, &nge);\n  if (check_flag(&flag, \"CVodeGetNumGEvals\", 1) == CAMP_SOLVER_FAIL) return;\n  flag = CVodeGetLastStep(cvode_mem, &last_h);\n  if (check_flag(&flag, \"CVodeGetLastStep\", 1) == CAMP_SOLVER_FAIL) return;\n  flag = CVodeGetCurrentStep(cvode_mem, &curr_h);\n  if (check_flag(&flag, \"CVodeGetCurrentStep\", 1) == CAMP_SOLVER_FAIL) return;\n\n  printf(\"\\nSUNDIALS Solver Statistics:\\n\");\n  printf(\"number of steps = %-6ld RHS evals = %-6ld LS setups = %-6ld\\n\", nst,\n         nfe, nsetups);\n  printf(\"error test fails = %-6ld LS iters = %-6ld NLS iters = %-6ld\\n\", netf,\n         nni, ncfn);\n  printf(\n      \"NL conv fails = %-6ld Dls Jac evals = %-6ld Dls RHS evals = %-6ld G \"\n      \"evals =\"\n      \" %-6ld\\n\",\n      ncfn, nje, nfeLS, nge);\n  printf(\"Last time step = %le Next time step = %le\\n\", last_h, curr_h);\n}\n\n#endif  // CAMP_USE_SUNDIALS\n\n/** \\brief Free a SolverData object\n *\n * \\param solver_data Pointer to the SolverData object to free\n */\nvoid solver_free(void *solver_data) {\n  SolverData *sd = (SolverData *)solver_data;\n\n#ifdef CAMP_USE_SUNDIALS\n  // free the SUNDIALS solver\n  CVodeFree(&(sd->cvode_mem));\n\n  // free the absolute tolerance vector\n  N_VDestroy(sd->abs_tol_nv);\n\n  // free the TimeDerivative\n  time_derivative_free(sd->time_deriv);\n\n  // free the Jacobian\n  jacobian_free(&(sd->jac));\n\n  // free the derivative vectors\n  N_VDestroy(sd->y);\n  N_VDestroy(sd->deriv);\n\n  // destroy the Jacobian marix\n  SUNMatDestroy(sd->J);\n\n  // destroy Jacobian matrix for guessing state\n  SUNMatDestroy(sd->J_guess);\n\n  // free the linear solver\n  SUNLinSolFree(sd->ls);\n#endif\n\n  // Free the allocated ModelData\n  model_free(sd->model_data);\n\n  // free the SolverData object\n  free(sd);\n}\n\n#ifdef CAMP_USE_SUNDIALS\n/** \\brief Determine if there is anything to solve\n *\n * If the solver state concentrations and the derivative vector are very small,\n * there is no point running the solver\n */\nbool is_anything_going_on_here(SolverData *sd, realtype t_initial,\n                               realtype t_final) {\n  ModelData *md = &(sd->model_data);\n\n  if (f(t_initial, sd->y, sd->deriv, sd)) {\n    int i_dep_var = 0;\n    for (int i_cell = 0; i_cell < md->n_cells; ++i_cell) {\n      for (int i_spec = 0; i_spec < md->n_per_cell_state_var; ++i_spec) {\n        if (md->var_type[i_spec] == CHEM_SPEC_VARIABLE) {\n          if (NV_Ith_S(sd->y, i_dep_var) >\n              NV_Ith_S(sd->abs_tol_nv, i_dep_var) * 1.0e-10)\n            return true;\n          if (NV_Ith_S(sd->deriv, i_dep_var) * (t_final - t_initial) >\n              NV_Ith_S(sd->abs_tol_nv, i_dep_var) * 1.0e-10)\n            return true;\n          i_dep_var++;\n        }\n      }\n    }\n    return false;\n  }\n\n  return true;\n}\n#endif\n\n/** \\brief Custom error handling function\n *\n * This is used for quiet operation. Solver failures are returned with a flag\n * from the solver_run() function.\n */\nvoid error_handler(int error_code, const char *module, const char *function,\n                   char *msg, void *sd) {\n  // Do nothing\n}\n\n/** \\brief Free a ModelData object\n *\n * \\param model_data Pointer to the ModelData object to free\n */\nvoid model_free(ModelData model_data) {\n#ifdef CAMP_USE_GPU\n  // free_gpu_cu();\n#endif\n\n#ifdef CAMP_USE_SUNDIALS\n  // Destroy the initialized Jacbobian matrix\n  SUNMatDestroy(model_data.J_init);\n  SUNMatDestroy(model_data.J_rxn);\n  SUNMatDestroy(model_data.J_params);\n  SUNMatDestroy(model_data.J_solver);\n  N_VDestroy(model_data.J_state);\n  N_VDestroy(model_data.J_deriv);\n  N_VDestroy(model_data.J_tmp);\n  N_VDestroy(model_data.J_tmp2);\n#endif\n  free(model_data.jac_map);\n  free(model_data.jac_map_params);\n  free(model_data.var_type);\n  free(model_data.rxn_int_data);\n  free(model_data.rxn_float_data);\n  free(model_data.rxn_env_data);\n  free(model_data.rxn_int_indices);\n  free(model_data.rxn_float_indices);\n  free(model_data.rxn_env_idx);\n  free(model_data.aero_phase_int_data);\n  free(model_data.aero_phase_float_data);\n  free(model_data.aero_phase_int_indices);\n  free(model_data.aero_phase_float_indices);\n  free(model_data.aero_rep_int_data);\n  free(model_data.aero_rep_float_data);\n  free(model_data.aero_rep_env_data);\n  free(model_data.aero_rep_int_indices);\n  free(model_data.aero_rep_float_indices);\n  free(model_data.aero_rep_env_idx);\n  free(model_data.sub_model_int_data);\n  free(model_data.sub_model_float_data);\n  free(model_data.sub_model_env_data);\n  free(model_data.sub_model_int_indices);\n  free(model_data.sub_model_float_indices);\n  free(model_data.sub_model_env_idx);\n}\n\n/** \\brief Free update data\n *\n * \\param update_data Object to free\n */\nvoid solver_free_update_data(void *update_data) { free(update_data); }\n", "meta": {"hexsha": "1b7454e894ace9fabcabec04735eda92f961f28d", "size": 71557, "ext": "c", "lang": "C", "max_stars_repo_path": "src/camp_solver.c", "max_stars_repo_name": "open-atmos/camp", "max_stars_repo_head_hexsha": "4c77145ac43ae3dcfce71f49a9709bb62f80b8c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-08-05T21:35:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T05:32:29.000Z", "max_issues_repo_path": "src/camp_solver.c", "max_issues_repo_name": "open-atmos/camp", "max_issues_repo_head_hexsha": "4c77145ac43ae3dcfce71f49a9709bb62f80b8c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2021-10-06T18:14:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-22T11:42:07.000Z", "max_forks_repo_path": "src/camp_solver.c", "max_forks_repo_name": "open-atmos/camp", "max_forks_repo_head_hexsha": "4c77145ac43ae3dcfce71f49a9709bb62f80b8c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6395289299, "max_line_length": 81, "alphanum_fraction": 0.67878754, "num_tokens": 19821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35577489351363034, "lm_q2_score": 0.02161533035977087, "lm_q1q2_score": 0.0076901918570094225}}
{"text": "/*\n * Copyright 2008-2016 Jan Gasthaus\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#ifndef UTILS_H_\n#define UTILS_H_\n\n#include <string>\n#include <cmath>\n#include <map>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <cassert>\n#include <algorithm>\n#include <gsl/gsl_sf_gamma.h>\n\n////////////////////////////////////////////////////////////////////////////////\n/////////////////   SOME USEFUL MACROS   ///////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n#ifdef DEBUG\n#define tracer if (0) ; else std::cerr\n#define DBG if (1)\n#else\n#define tracer if (1) ; else std::cerr\n#define DBG if (1) ; else\n#endif\n\n  // some syntactic sugar for implementing interfaces using (multiple) inheritance\n#define interface class\n#define implements public\n\n  // A macro to disallow the copy constructor and operator= functions\n  // This should be used in the private: declarations for a class\n#define DISALLOW_COPY_AND_ASSIGN(TypeName) \\\n  TypeName(const TypeName&);               \\\n  void operator=(const TypeName&)\n\n\nnamespace gatsby { namespace libplump {\n\n/**\n * Alias: std::vector<double>\n */\ntypedef std::vector<double> d_vec;\n\n/**\n * Alias: std::vector<std::vector<double> >\n */\ntypedef std::vector<d_vec> d_vec_vec;\n\n/**\n * Alias: std::vector<unsigned int>\n */\ntypedef std::vector<unsigned int> ui_vec;\n\n/**\n * Alias: std::vector<std::vector<unsigned int> >\n */\ntypedef std::vector<ui_vec> ui_vec_vec;\n\n\n\n/**\n * Compute log2(x) -- the log2 provided by GCC is somewhat weird.\n */\ninline double log2(double x){\n  static const double LOG2 = std::log(2.);\n  return std::log(x)/LOG2;\n}\n\n\n/**\n * Read items of type E from a file and push them into a sequence of type\n * S (that has to support push_back(E item). \n *\n * Items are read from the file sizeof(E) bytes at a time. No error checking\n * is performed.\n *\n * @tparam E Type of element to read from file, elements will be read sizeof(E)\n *           bytes at a time.\n * @tparam S Type of sequence to push items into; \n *           must support push_back(E item)\n * @param fileName Name of the file to read from \n * @param seq Sequence to push items into\n * @param limit Maximum number of items to push (default: 0, no limit)\n */\ntemplate<typename E, class S>\n  inline void pushFileToVec(const std::string& fileName, S& seq, int limit = 0){\n    std::ifstream in;\n    in.open(fileName.c_str(),std::ios::binary | std::ios_base::in);\n    char buffer[sizeof(E)];\n    in.read(buffer,sizeof(E));\n    int j = 0;\n    if (limit==0)\n      limit = -1;\n    while (!in.eof() && j!=limit){\n      seq.push_back(*((E*)buffer));\n      in.read(buffer,sizeof(E));\n      j++;\n    }\n    in.close();\n  }\n\n/**\n * Push each character of string s individually into container seq of type S, \n * which has to support push_back(char c);\n *\n * @tparam S type of container to push into\n * @param s input string to push\n * @param seq output container to push into\n */\ntemplate<class S>\n  inline void pushStringToVec(const std::string& s, S& seq){\n    for (size_t i=0;i<s.length();i++) {\n      seq.push_back(s[i]);\n    }\n  }\n\n/**\n * Convert a map<T,T> where T is an integer type with \n * range 0...MAX to a vector v of length MAX+1 so that \n * v[x] = m[x] for x=1,...,MAX. v[x] = 0 if m.count(x) = 0.\n *\n * @tparam T integer type\n * @param m input map\n * @param v output vector\n * @returns pointer to histogram vector on the heap\n */\ntemplate<typename T>\n  inline void mapHistogramToVectorHistogram(const std::map<T,T>& m, std::vector<T>& v) {\n    T max = (*max_element(m.begin(), m.end())).first;\n    v.clear();\n    v.assign(max + 1,0);\n    for (typename std::map<T,T>::iterator i = m.begin(); i != m.end(); ++i) {\n      v[(*i).first] = (*i).second; \n    }\n    return v;\n  }\n\n/** \n * Count the number of times the elements k=0...max-1 occur in vec and \n * return the result in ret[k].\n */\ntemplate<typename T>\n  inline std::vector<T> vec2hist(std::vector<T>& vec, T max) {\n    std::vector<T> ret(max,0);\n    for (unsigned int i = 0; i < vec.size(); ++i) {\n      ++ret[vec[i]];\n    }\n    return ret;\n  }\n\n/**\n * Compute the mean of the elements in a sequence.\n *\n * @tparam T iteratable sequence type; must have a const_iterator member\n *           as well as begin() and end() methods.\n * @param in sequence to compute the mean of\n * @returns the mean of the elements in the sequence\n */\ntemplate<typename T>\n  inline double mean(const T& in) {\n    double mean = 0.0;\n    size_t j = 0;\n    for (typename T::const_iterator i = in.begin(); i != in.end(); ++i) {\n      mean += (((double)*i)-mean)/(++j);\n    }\n    return mean;\n  }\n\n\n/**\n * Sum the elements in a sequence.\n *\n * @tparam T iteratable sequence type; must have a const_iterator member\n *           as well as begin() and end() methods.\n * @param in sequence to compute the sum of\n * @returns the sum of the elements in the sequence\n */\ntemplate<typename T>\n  inline typename T::value_type sum(const T& in) {\n    typename T::value_type sum = 0;\n    for (typename T::const_iterator i = in.begin(); i != in.end(); ++i) {\n      sum += *i;\n    }\n    return sum;\n  }\n\ninline void log2_vec(d_vec& in) {\n  for (size_t i=0;i<in.size();i++){\n    in[i] = log2(in[i]);\n  }\n}\n\ninline void exp_vec(d_vec& in) {\n  for (size_t i=0;i<in.size();i++){\n    in[i] = exp(in[i]);\n  }\n}\n\n/**\n * Multiply all elements of a vector by a constant.\n */\ntemplate<typename elem_t>\n  inline void mult_vec(std::vector<elem_t>& in, elem_t mult) {\n    for (size_t i=0;i<in.size();i++){\n      in[i] = in[i] * mult;\n    }\n  }\n\n/**\n * Add a constant to all elements of a vector.\n */\ntemplate<typename elem_t>\n  inline void add_vec(std::vector<elem_t>& in, elem_t add) {\n    for (size_t i=0;i<in.size();i++){\n      in[i] = in[i] + add;\n    }\n  }\n\n/**\n * Subtract max element fromall elements of a vector.\n */\ntemplate<typename elem_t>\n  inline void subMax_vec(std::vector<elem_t>& in) {\n    elem_t max = *std::max_element(in.begin(), in.end());\n    // if (max == -INFINITY) {\n    //   for (size_t i=0;i<in.size();i++){\n    //     in[i] = 0;\n    //   }\n    // }\n    for (size_t i=0;i<in.size();i++){ \n      in[i] = in[i] - max;\n    }\n  }\n\n\n/**\n * Add two vectors elementwise.\n */\ntemplate<typename elem_t>\n  inline void add_vec(std::vector<elem_t>& inout, const std::vector<elem_t>& add) {\n    std::transform(inout.begin(), inout.end(), add.begin(), inout.begin(),\n                  std::plus<elem_t>());\n  }\n\n/**\n * Elementwise multiplication. Results is returned in the first argument.\n */\ntemplate<typename elem_t>\n  inline void mult_vec(std::vector<elem_t>& inout, std::vector<elem_t> in) {\n    assert(inout.size() == in.size());\n    for (size_t i=0;i<inout.size();i++){\n      inout[i] *= in[i];\n    }\n  }\n\n\n/**\n * Average the values in multiple vectors of the same length.\n **/\ninline d_vec average(const d_vec_vec& ins) {\n  d_vec out(ins[0].size(), 0);\n  for (int j = 0; j < ins.size(); j++) {\n    add_vec(out, ins[j]);\n  }\n  mult_vec(out, 1./ins.size());\n  return out;\n}\n\n\ntemplate<typename elem_t>\n  inline double prob2loss(std::vector<elem_t> in) {\n    double out = 0.0;\n    for (size_t i=0;i<in.size();i++){\n      out -= log2(in[i]);\n    }\n    return out/in.size();\n  }\n\ninline bool closeTo(double value, double target, double tol=10e-4) {\n  return std::abs(value-target) < tol;\n}\n\ntemplate<typename Iterable>\n  inline std::string iterableToString(const Iterable input) {\n    std::ostringstream output;\n    for(typename Iterable::const_iterator it = input.begin(); it!=input.end();it++) {\n      output << *it << \", \";\n    }\n    return output.str();\n  }\n\ntemplate<typename Iterable>\n  void iterableToCSVFile(const Iterable input, std::string fn) {\n    std::ofstream output(fn.c_str());\n    output.precision(10);\n    for(typename Iterable::const_iterator it = input.begin(); it!=input.end();it++) {\n      output << *it << \", \";\n    }\n  }\n\n/**\n * computes log(exp(a) + exp(b)) while avoiding numerical\n * instabilities.\n */\ninline double logsumexp(double a, double b) {\n  // choose c to be the one that is largest in abs value\n  double c = (a>b)?a:b;\n  return (log(exp(a-c) + exp(b-c))) + c;\n}\n\n\ninline double sigmoid(double x) {\n  return 1.0/(1.0 + exp(-x));\n}\n\n// logit = inverse sigmoid\ninline double logit(double x) {\n  return log(x) - log(1-x);\n}\n\n\ninline double logKramp(double base, double inc, double lim) {\n  if (inc == 0)\n      return lim*log(base);\n  if (lim <= 0) {\n    return 0;\n  } else {\n    return lim*log(inc) + gsl_sf_lnpoch(base/inc, lim);\n  }\n}\n\n\ninline double kramp(double base, double inc, double lim) {\n  return exp(logKramp(base, inc, lim));\n}\n\n\n\nstatic clock_t global_clock;\n\n/*\n * Start timing\n */\ninline void tic() {\n  global_clock = clock();\n}\n\n/**\n * Return number of seconds since last tic()\n */\ninline double toc() {\n  return (clock() - global_clock)/(double)CLOCKS_PER_SEC; \n\n}\n\n\ninline std::string makeProgressBarString(double percentDone, int total=10) {\n  std::ostringstream out;\n\n  int numDone = (int)floor(total * percentDone);\n\n  out << \"[\";\n  for (int i=0; i<numDone; i++) {\n    out << \"=\";\n  }\n  out << \">\";\n  for (int i=numDone; i<total; i++) {\n    out << \" \";\n  }\n  out << \"]\";\n  return out.str();\n}\n\n\n}} // namespace gatsby::libplump\n\n#endif /* UTILS_H_ */\n", "meta": {"hexsha": "b0f6717b5546c8e258596fb070b78a6eba5f95df", "size": 9739, "ext": "h", "lang": "C", "max_stars_repo_path": "src/libplump/utils.h", "max_stars_repo_name": "jgasthaus/libPLUMP", "max_stars_repo_head_hexsha": "18e5911575e3c9a054482b08d637dc91b0cd05b9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2015-02-02T21:46:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-16T03:50:37.000Z", "max_issues_repo_path": "src/libplump/utils.h", "max_issues_repo_name": "jgasthaus/libPLUMP", "max_issues_repo_head_hexsha": "18e5911575e3c9a054482b08d637dc91b0cd05b9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libplump/utils.h", "max_forks_repo_name": "jgasthaus/libPLUMP", "max_forks_repo_head_hexsha": "18e5911575e3c9a054482b08d637dc91b0cd05b9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-11-17T19:19:37.000Z", "max_forks_repo_forks_event_max_datetime": "2016-11-20T00:56:17.000Z", "avg_line_length": 24.7811704835, "max_line_length": 88, "alphanum_fraction": 0.6144368005, "num_tokens": 2614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22815650216092534, "lm_q2_score": 0.03358950298969727, "lm_q1q2_score": 0.007663663511453273}}
{"text": "\ufeff/*! \\file deleter.h\n    \\brief gsl_interp_accel\u3068gsl_spline\u306e\u30c7\u30ea\u30fc\u30bf\u3092\u5ba3\u8a00\u30fb\u5b9a\u7fa9\u3057\u305f\u30d8\u30c3\u30c0\u30d5\u30a1\u30a4\u30eb\n\n    Copyright \u00a9 2015 @dc1394 All Rights Reserved.\n    This software is released under the BSD 2-Clause License.\n*/\n\n#ifndef _DELETER_H_\n#define _DELETER_H_\n\n#pragma once\n\n#include <gsl/gsl_spline.h>     // for gsl_interp_accel, gsl_interp_accel_free, gsl_spline, gsl_spline_free\n\nnamespace freefallsolveeom {\n    //! A lambda expression.\n    /*!\n        gsl_interp_accel\u3078\u306e\u30dd\u30a4\u30f3\u30bf\u3092\u89e3\u653e\u3059\u308b\u30e9\u30e0\u30c0\u5f0f\n        \\param acc gsl_interp_accel\u3078\u306e\u30dd\u30a4\u30f3\u30bf\n    */\n    static auto const gsl_interp_accel_deleter = [](auto acc) {\n        gsl_interp_accel_free(acc);\n    };\n\n    //! A lambda expression.\n    /*!\n        gsl_spline\u3078\u306e\u30dd\u30a4\u30f3\u30bf\u3092\u89e3\u653e\u3059\u308b\u30e9\u30e0\u30c0\u5f0f\n        \\param spline gsl_spline\u3078\u306e\u30dd\u30a4\u30f3\u30bf\n    */\n    static auto const gsl_spline_deleter = [](auto spline) {\n        gsl_spline_free(spline);\n    };\n}\n\n#endif  // _DELETER_H_\n", "meta": {"hexsha": "d399c0127c4710f9e669438748a12fc35f01fa51", "size": 868, "ext": "h", "lang": "C", "max_stars_repo_path": "Freefall/freefallsolveeom/utility/deleter.h", "max_stars_repo_name": "dc1394/Freefall", "max_stars_repo_head_hexsha": "a44993c1f2c08bedac84af158c75933e89cc6318", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Freefall/freefallsolveeom/utility/deleter.h", "max_issues_repo_name": "dc1394/Freefall", "max_issues_repo_head_hexsha": "a44993c1f2c08bedac84af158c75933e89cc6318", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Freefall/freefallsolveeom/utility/deleter.h", "max_forks_repo_name": "dc1394/Freefall", "max_forks_repo_head_hexsha": "a44993c1f2c08bedac84af158c75933e89cc6318", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1111111111, "max_line_length": 107, "alphanum_fraction": 0.6889400922, "num_tokens": 272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15203224162217424, "lm_q2_score": 0.05033062761181351, "lm_q1q2_score": 0.0076518781380749065}}
{"text": "/*\n* Copyright (c) 2006 Rudi Cilibrasi, Rulers of the RHouse\n* All rights reserved.     cilibrar@cilibrar.com\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following conditions are met:\n*\n*     * Redistributions of source code must retain the above copyright\n*       notice, this list of conditions and the following disclaimer.\n*     * Redistributions in binary form must reproduce the above copyright\n*       notice, this list of conditions and the following disclaimer in the\n*       documentation and/or other materials provided with the distribution.\n*     * Neither the name of the RHouse nor the\n*       names of its contributors may be used to endorse or promote products\n*       derived from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE RULERS AND CONTRIBUTORS \"AS IS\" AND ANY\n* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n* DISCLAIMED. IN NO EVENT SHALL THE RULERS AND CONTRIBUTORS BE LIABLE FOR ANY\n* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n#ifndef __CLOUTPUT_H\n#define __CLOUTPUT_H\n\n\n#include <math.h>\n\n#include <gsl/gsl_blas.h>\n\n/*! \\file cloutput.h */\n\ngsl_matrix *complearn_svd_project(gsl_matrix *a);\nGString *complearn_matrix_prettyprint_text(LabeledMatrix *inp);\nGString *complearn_matrix_prettyprint_nex(LabeledMatrix *inp, GString *treeblock);\n\nstruct CLDistMatrix {\n  char *fileverstr;\n  char *cllibver;\n  char *username;\n  char *hostname;\n  char *title;\n  char *compressor;\n  char *creationTime; // Seconds since the epoch\n  char * *cmds;\n  char * *cmdtimes; // Seconds since the epoch\n  LabeledMatrix *m;\n  GArray *cmdsa;\n  GArray *cmdtimesa;\n  GArray *numa;\n  GArray *labels1a;\n  GArray *labels2a;\n};\n\nstruct CLDistMatrix *complearn_read_clb_dist_matrix(const GString *db);\nGArray *complearn_get_nexus_labels(const GString *db);\ngsl_matrix *complearn_get_nexus_distance_matrix(const GString *db);\nGString *complearn_matrix_prettyprint_clb(LabeledMatrix *result);\nLabeledMatrix *complearn_load_nexus_matrix(const GString *inp);\nLabeledMatrix *complearn_load_any_matrix(const GString *inp);\ngboolean complearn_is_nexus_file(const GString *db);\nGString *complearn_get_nexus_tree_block(const GString *db);\ngboolean complearn_is_text_matrix(const GString *db);\nLabeledMatrix *complearn_load_text_matrix(const GString *inp);\n\n#endif\n\n", "meta": {"hexsha": "ea8ec45cfc490faaeb0fa480d425cba2064d0316", "size": 2890, "ext": "h", "lang": "C", "max_stars_repo_path": "src/complearn/cloutput.h", "max_stars_repo_name": "rudi-cilibrasi/classic-complearn", "max_stars_repo_head_hexsha": "c70ac5ad7bcfe3af80a2a8f087ee6f5904820a66", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-03-14T13:52:31.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-08T11:13:03.000Z", "max_issues_repo_path": "src/complearn/cloutput.h", "max_issues_repo_name": "rudi-cilibrasi/classic-complearn", "max_issues_repo_head_hexsha": "c70ac5ad7bcfe3af80a2a8f087ee6f5904820a66", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2016-05-10T12:56:52.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-15T18:30:04.000Z", "max_forks_repo_path": "src/complearn/cloutput.h", "max_forks_repo_name": "rudi-cilibrasi/classic-complearn", "max_forks_repo_head_hexsha": "c70ac5ad7bcfe3af80a2a8f087ee6f5904820a66", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.1388888889, "max_line_length": 82, "alphanum_fraction": 0.7778546713, "num_tokens": 712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.399811640739795, "lm_q2_score": 0.019124035772566928, "lm_q1q2_score": 0.007646012119796517}}
{"text": "/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*\n**                                                                                  **\n** This file forms part of the Underworld geophysics modelling application.         **\n**                                                                                  **\n** For full license and copyright information, please refer to the LICENSE.md file  **\n** located at the project root, or contact the authors.                             **\n**                                                                                  **\n**~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/\n#include <stdlib.h>\n#include <string.h>\n#include <assert.h>\n#include <mpi.h>\n#include <petsc.h>\n#include <petscvec.h>\n#include <petscmat.h>\n#include <petscksp.h>\n#include <petscpc.h>\n#include <petscsnes.h>\n\n#include <petscversion.h>\n#if ( (PETSC_VERSION_MAJOR >= 3) && (PETSC_VERSION_MINOR >=3) )\n  #if (PETSC_VERSION_MINOR >=6)\n     #include \"petsc/private/kspimpl.h\"\n  #else\n     #include \"petsc-private/kspimpl.h\"   /*I \"petscksp.h\" I*/\n  #endif\n#else\n  #include \"private/kspimpl.h\"   /*I \"petscksp.h\" I*/\n#endif\n\n#include <StGermain/libStGermain/src/StGermain.h>\n#include <StgDomain/libStgDomain/src/StgDomain.h>\n#include <StgFEM/libStgFEM/src/StgFEM.h>\n#include <PICellerator/libPICellerator/src/PICellerator.h>\n#include <Underworld/libUnderworld/src/Underworld.h>\n\n#include \"Solvers/KSPSolvers/src/KSPSolvers.h\"\n#include \"BSSCR/petsccompat.h\"\n\n#include \"Test/TestKSP.h\"\n#include \"BSSCR/BSSCR.h\"\n\n/************************************************************************/\n/*** This function is called from _StokesBlockKSPInterface_Initialise **************/\n/************************************************************************/\n#undef __FUNCT__  \n#define __FUNCT__ \"KSPRegisterAllKSP\"\nPetscErrorCode KSPRegisterAllKSP(const char path[])\n{\n\n    PetscFunctionBegin;\n    KSPRegisterTEST(path);/* not sure if the path matters much here. everything still worked even though I had it wrong */\n    KSPRegisterBSSCR (path);\n    PetscFunctionReturn(0);\n}\n\n", "meta": {"hexsha": "556a6ac4e467dc1e0ba6fada70735e7a4e9f0733", "size": 2154, "ext": "c", "lang": "C", "max_stars_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/ksp-register.c", "max_stars_repo_name": "rbeucher/underworld2", "max_stars_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/ksp-register.c", "max_issues_repo_name": "rbeucher/underworld2", "max_issues_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/ksp-register.c", "max_forks_repo_name": "rbeucher/underworld2", "max_forks_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.7894736842, "max_line_length": 122, "alphanum_fraction": 0.5208913649, "num_tokens": 622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.25683199138751883, "lm_q2_score": 0.029760095451883174, "lm_q1q2_score": 0.007643344578789797}}
{"text": "/*\t$Id$ */\r\n/*\r\n * Copyright (c) 2014, 2015 Kristaps Dzonsons <kristaps@kcons.eu>\r\n *\r\n * Permission to use, copy, modify, and distribute this software for any\r\n * purpose with or without fee is hereby granted, provided that the above\r\n * copyright notice and this permission notice appear in all copies.\r\n *\r\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\r\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\r\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\r\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\r\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\r\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\r\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\r\n */\r\n#include <assert.h>\r\n#include <math.h>\r\n#include <stdint.h>\r\n#include <stdlib.h>\r\n#ifdef __linux__\r\n#include <bsd/stdlib.h> /* arc4random() */\r\n#endif\r\n#include <string.h>\r\n\r\n#include <glib.h>\r\n#include <gtk/gtk.h>\r\n#include <gsl/gsl_rng.h>\r\n#include <gsl/gsl_multifit.h>\r\n#include <gsl/gsl_histogram.h>\r\n#include <kplot.h>\r\n\r\n#include \"extern.h\"\r\n\r\nenum\tkmltype {\r\n\tKML_INIT = 0,\r\n\tKML_KML,\r\n\tKML_DOCUMENT,\r\n\tKML_FOLDER,\r\n\tKML_PLACEMARK,\r\n\tKML_POINT,\r\n\tKML_COORDINATES,\r\n\tKML_DESCRIPTION,\r\n\tKML__MAX\r\n};\r\n\r\nenum\tkmlkey {\r\n\tKMLKEY_MEAN,\r\n\tKMLKEY_MEAN_PERCENT,\r\n\tKMLKEY_STDDEV,\r\n\tKMLKEY_POPULATION,\r\n\tKMLKEY__MAX\r\n};\r\n\r\nstruct\tkmlsave {\r\n\tFILE\t\t*f;\r\n\tstruct sim\t*cursim;\r\n\tsize_t\t\t curisland;\r\n\tgchar\t\t*buf;\r\n\tgsize\t\t bufsz;\r\n\tgsize\t\t bufmax;\r\n\tint\t\t buffering;\r\n};\r\n\r\nstruct\tkmlparse {\r\n\tenum kmltype\t elem; /* current element */\r\n\tstruct kmlplace\t*cur; /* currently-parsed kmlplace */\r\n\tgchar\t\t*buf; /* current parse text buffer */\r\n\tgsize\t \t bufsz; /* size in parse buffer */\r\n\tgsize\t \t bufmax; /* maximum sized buffer */\r\n\tgchar\t\t*altbuf; \r\n\tgsize\t \t altbufsz; \r\n\tgsize\t \t altbufmax; \r\n\tGList\t\t*places; /* parsed places */\r\n\tgchar\t\t*ign; /* element we're currently ignoring */\r\n\tsize_t\t\t ignstack; /* stack of \"ign\" while ignoring */\r\n#define\tKML_STACKSZ\t 128\r\n\tenum kmltype\t stack[128];\r\n\tsize_t\t\t stackpos;\r\n};\r\n\r\nstatic\tconst char *const kmlkeys[KMLKEY__MAX] = {\r\n\t\"mean\", /* KMLKEY_MEAN */\r\n\t\"meanpct\", /* KMLKEY_MEAN_PERCENT */\r\n\t\"stddev\", /* KMLKEY_STDDEV */\r\n\t\"population\", /* KMLKEY_POPULATION */\r\n};\r\n\r\nstatic\tconst char *const kmltypes[KML__MAX] = {\r\n\tNULL, /* KML_INIT */\r\n\t\"kml\", /* KML_KML */\r\n\t\"Document\", /* KML_DOCUMENT */\r\n\t\"Folder\", /* KML_FOLDER */\r\n\t\"Placemark\", /* KML_PLACEMARK */\r\n\t\"Point\", /* KML_POINT */\r\n\t\"coordinates\", /* KML_COORDINATES */\r\n\t\"description\", /* KML_DESCRIPTION */\r\n};\r\n\r\nstatic\tconst double DEG_TO_RAD = 0.017453292519943295769236907684886;\r\nstatic\tconst double EARTH_RADIUS_IN_METERS = 6372797.560856;\r\n\r\nstatic double\r\nkml_dist(const struct kmlplace *from, const struct kmlplace *to)\r\n{\r\n\tdouble\t latitudeArc, longitudeArc, \r\n\t\t latitudeH, lontitudeH, tmp;\r\n\r\n\tlatitudeArc = (from->lat - to->lat) * DEG_TO_RAD;\r\n\tlongitudeArc = (from->lng - to->lng) * DEG_TO_RAD;\r\n\tlatitudeH = sin(latitudeArc * 0.5);\r\n\tlatitudeH *= latitudeH;\r\n\tlontitudeH = sin(longitudeArc * 0.5);\r\n\tlontitudeH *= lontitudeH;\r\n\ttmp = cos(from->lat * DEG_TO_RAD) * \r\n\t\tcos(to->lat * DEG_TO_RAD);\r\n\r\n\treturn(EARTH_RADIUS_IN_METERS * 2.0 * \r\n\t\tasin(sqrt(latitudeH + tmp * lontitudeH)));\r\n}\r\n\r\nstatic void\r\nkml_append(gchar **buf, gsize *bufsz, \r\n\tgsize *bufmax, const char *text, gsize sz)\r\n{\r\n\r\n\t/* XXX: no check for overflow... */\r\n\tif (*bufsz + sz + 1 > *bufmax) {\r\n\t\t*bufmax = *bufsz + sz + 1024;\r\n\t\t*buf = g_realloc(*buf, *bufmax);\r\n\t}\r\n\r\n\tmemcpy(*buf + *bufsz, text, sz);\r\n\t*bufsz += sz;\r\n\t(*buf)[*bufsz] = '\\0';\r\n\tg_assert(*bufsz <= *bufmax);\r\n}\r\n\r\nstatic enum kmltype\r\nkml_lookup(const gchar *name)\r\n{\r\n\tenum kmltype\ti;\r\n\r\n\tfor (i = 0; i < KML__MAX; i++) {\r\n\t\tif (NULL == kmltypes[i])\r\n\t\t\tcontinue;\r\n\t\tif (0 == g_strcmp0(kmltypes[i], name))\r\n\t\t\tbreak;\r\n\t}\r\n\r\n\treturn(i);\r\n}\r\n\r\nstatic void\r\nkmlparse_free(gpointer dat)\r\n{\r\n\tstruct kmlplace\t*place = dat;\r\n\r\n\tif (NULL == place)\r\n\t\treturn;\r\n\tfree(place);\r\n}\r\n\r\nvoid\r\nkml_free(struct kml *kml)\r\n{\r\n\r\n\tif (NULL == kml)\r\n\t\treturn;\r\n\r\n\tg_list_free_full(kml->kmls, kmlparse_free);\r\n\r\n\tif (NULL != kml->file)\r\n\t\tg_mapped_file_unref(kml->file);\r\n}\r\n\r\n/*\r\n * Try to find the string \"@@population=NN@@\", which stipulates the\r\n * population for this particular island.\r\n * If we don't find it, just return--we'll use the default.\r\n * If we find a bad population, raise an error.\r\n */\r\nstatic int\r\nkml_placemark(const gchar *buf, struct kmlplace *place)\r\n{\r\n\tconst gchar\t*cp;\r\n\tgchar\t\t*ep;\r\n\tgsize\t\t keysz;\r\n\tgchar\t\t nbuf[22];\r\n\r\n\tkeysz = strlen(\"@@population=\");\r\n\twhile (NULL != (cp = strstr(buf, \"@@population=\"))) {\r\n\t\tbuf = cp + keysz;\r\n\t\tif (NULL == (cp = strstr(buf, \"@@\")))\r\n\t\t\tbreak;\r\n\t\tif ((gsize)(cp - buf) >= sizeof(nbuf) - 1)\r\n\t\t\treturn(0);\r\n\t\tmemcpy(nbuf, buf, cp - buf);\r\n\t\tnbuf[cp - buf] = '\\0';\r\n\t\tplace->pop = g_ascii_strtoull(buf, &ep, 10);\r\n\t\tif (ERANGE == errno || EINVAL == errno || ep == buf)\r\n\t\t\treturn(0);\r\n\t\tbreak;\r\n\t}\r\n\r\n\treturn(1);\r\n}\r\n\r\nstatic void\t\r\nkml_elem_end(GMarkupParseContext *ctx, \r\n\tconst gchar *name, gpointer dat, GError **er)\r\n{\r\n\tstruct kmlparse\t *p = dat;\r\n\tenum kmltype\t  t;\r\n\tgchar\t\t**set;\r\n\r\n\tif (NULL != p->ign) {\r\n\t\tg_assert(p->ignstack > 0);\r\n\t\tif (0 == g_strcmp0(p->ign, name))\r\n\t\t\tp->ignstack--;\r\n\t\tif (p->ignstack > 0)\r\n\t\t\treturn;\r\n\t\tg_free(p->ign);\r\n\t\tp->ign = NULL;\r\n\t\treturn;\r\n\t} \r\n\r\n\tt = kml_lookup(name);\r\n\tg_assert(p->stackpos > 0);\r\n\tg_assert(t == p->stack[p->stackpos - 1]);\r\n\tp->stackpos--;\r\n\r\n\tswitch (p->stack[p->stackpos]) {\r\n\tcase (KML_PLACEMARK):\r\n\t\t/*\r\n\t\t * if we're ending a Placemark, first check whether\r\n\t\t * we've listed a population somewhere in any of the\r\n\t\t * nested text segments.\r\n\t\t * Also make sure that we have some coordinates (the\r\n\t\t * default value was 360 for both, which of course isn't\r\n\t\t * a valid coordinate).\r\n\t\t */\r\n\t\tg_assert(NULL != p->cur);\r\n\t\tif ( ! kml_placemark(p->altbuf, p->cur)) {\r\n\t\t\t*er = g_error_new_literal\r\n\t\t\t\t(G_MARKUP_ERROR, \r\n\t\t\t\t G_MARKUP_ERROR_INVALID_CONTENT, \r\n\t\t\t\t \"Cannot parse population\");\r\n\t\t\tbreak;\r\n\t\t} else if (p->cur->lat > 180 || p->cur->lng > 180) {\r\n\t\t\t*er = g_error_new_literal\r\n\t\t\t\t(G_MARKUP_ERROR, \r\n\t\t\t\t G_MARKUP_ERROR_INVALID_CONTENT, \r\n\t\t\t\t \"No coordinates for placemark\");\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tp->places = g_list_append(p->places, p->cur);\r\n\t\tp->cur = NULL;\r\n\t\tbreak;\r\n\tcase (KML_COORDINATES):\r\n\t\t/*\r\n\t\t * Parse coordinates from the mix.\r\n\t\t * Coordinates are longitude,latitude,altitude.\r\n\t\t * Parse quickly and just make sure they're valid.\r\n\t\t */\r\n\t\tset = g_strsplit(p->buf, \",\", 3);\r\n\t\tp->cur->lng = g_ascii_strtod(set[0], NULL);\r\n\t\tif (ERANGE == errno)\r\n\t\t\t*er = g_error_new_literal\r\n\t\t\t\t(G_MARKUP_ERROR, \r\n\t\t\t\t G_MARKUP_ERROR_INVALID_CONTENT, \r\n\t\t\t\t \"Cannot parse longitude\");\r\n\t\telse if (p->cur->lng > 180.0 || p->cur->lng < -180.0)\r\n\t\t\t*er = g_error_new_literal\r\n\t\t\t\t(G_MARKUP_ERROR, \r\n\t\t\t\t G_MARKUP_ERROR_INVALID_CONTENT, \r\n\t\t\t\t \"Invalid longitude\");\r\n\t\tp->cur->lat = g_ascii_strtod(set[1], NULL);\r\n\t\tif (ERANGE == errno)\r\n\t\t\t*er = g_error_new_literal\r\n\t\t\t\t(G_MARKUP_ERROR, \r\n\t\t\t\t G_MARKUP_ERROR_INVALID_CONTENT, \r\n\t\t\t\t \"Cannot parse latitude\");\r\n\t\telse if (p->cur->lat > 90.0 || p->cur->lat < -90.0)\r\n\t\t\t*er = g_error_new_literal\r\n\t\t\t\t(G_MARKUP_ERROR, \r\n\t\t\t\t G_MARKUP_ERROR_INVALID_CONTENT, \r\n\t\t\t\t \"Invalid latitude\");\r\n\t\tg_strfreev(set);\r\n\t\tbreak;\r\n\tdefault:\r\n\t\tbreak;\r\n\t}\r\n}\r\n\r\nstatic void\r\nkml_elem_start(GMarkupParseContext *ctx, \r\n\tconst gchar *name, const gchar **attrn, \r\n\tconst gchar **attrv, gpointer dat, GError **er)\r\n{\r\n\tenum kmltype\t t;\r\n\tstruct kmlparse\t*p = dat;\r\n\r\n\tif (NULL != p->ign) {\r\n\t\tg_assert(p->ignstack > 0);\r\n\t\tif (0 == g_strcmp0(p->ign, name))\r\n\t\t\tp->ignstack++;\r\n\t\treturn;\r\n\t}\r\n\t\r\n\tif (KML__MAX == (t = kml_lookup(name))) {\r\n\t\tassert(0 == p->ignstack);\r\n\t\tp->ign = g_strdup(name);\r\n\t\tp->ignstack = 1;\r\n\t\treturn;\r\n\t}\r\n\r\n\tp->stack[p->stackpos++] = t;\r\n\tp->bufsz = 0;\r\n\t\r\n\tswitch (p->stack[p->stackpos - 1]) {\r\n\tcase (KML_PLACEMARK):\r\n\t\t/*\r\n\t\t * If we're starting a Placemark, initialise ourselves\r\n\t\t * with bad coorindates and a default population.\r\n\t\t */\r\n\t\tif (NULL == p->cur) {\r\n\t\t\tp->cur = g_malloc0(sizeof(struct kmlplace));\r\n\t\t\tp->cur->lat = p->cur->lng = 360;\r\n\t\t\tp->cur->pop = 2;\r\n\t\t\tp->altbufsz = 0;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\t*er = g_error_new_literal\r\n\t\t\t(G_MARKUP_ERROR, \r\n\t\t\t G_MARKUP_ERROR_INVALID_CONTENT, \r\n\t\t\t \"Nested placemarks not allowed.\");\r\n\t\tbreak;\r\n\tdefault:\r\n\t\tbreak;\r\n\t}\r\n}\r\n\r\nstatic void\r\nkml_text(GMarkupParseContext *ctx, \r\n\tconst gchar *txt, gsize sz, gpointer dat, GError **er)\r\n{\r\n\tstruct kmlparse\t*p = dat;\r\n\r\n\tif (NULL != p->cur)\r\n\t\tkml_append(&p->altbuf, &p->altbufsz, \r\n\t\t\t&p->altbufmax, txt, sz);\r\n\r\n\t/* No collection w/o element or while ignoring. */\r\n\tif (NULL != p->ign || 0 == p->stackpos)\r\n\t\treturn;\r\n\r\n\t/* Each element for which we're going to collect text. */\r\n\tswitch (p->stack[p->stackpos - 1]) {\r\n\tcase (KML_COORDINATES):\r\n\t\tbreak;\r\n\tdefault:\r\n\t\treturn;\r\n\t}\r\n\r\n\tkml_append(&p->buf, &p->bufsz, &p->bufmax, txt, sz);\r\n}\r\n\r\nstatic void\r\nkml_error(GMarkupParseContext *ctx, GError *er, gpointer dat)\r\n{\r\n\r\n\tg_warning(\"%s\", er->message);\r\n}\r\n\r\nstruct kml *\r\nkml_torus(size_t islands, size_t islanders)\r\n{\r\n\tstruct kml\t*kml;\r\n\tstruct kmlplace\t*p;\r\n\tsize_t\t\t i;\r\n\r\n\tkml = g_malloc0(sizeof(struct kml));\r\n\r\n\tfor (i = 0; i < islands; i++) {\r\n\t\tp = g_malloc0(sizeof(struct kmlplace));\r\n\t\tp->pop = islanders;\r\n\t\tp->lng = 360 * i / (double)islands - 180.0;\r\n\t\tp->lat = 0.0;\r\n\t\tkml->kmls = g_list_append(kml->kmls, p);\r\n\t}\r\n\r\n\treturn(kml);\r\n}\r\n\r\nstruct kml *\r\nkml_rand(size_t islands, size_t islanders)\r\n{\r\n\tstruct kml\t*kml;\r\n\tstruct kmlplace\t*p;\r\n\tsize_t\t\t i;\r\n\r\n\tkml = g_malloc0(sizeof(struct kml));\r\n\r\n\tfor (i = 0; i < islands; i++) {\r\n\t\tp = g_malloc0(sizeof(struct kmlplace));\r\n\t\tp->pop = islanders;\r\n\t\tp->lng = 360 * arc4random() / (double)UINT32_MAX - 180.0;\r\n\t\tp->lat = 180 * arc4random() / (double)UINT32_MAX - 90.0;\r\n\t\tkml->kmls = g_list_append(kml->kmls, p);\r\n\t}\r\n\r\n\treturn(kml);\r\n}\r\n\r\nstruct kml *\r\nkml_parse(const gchar *file, GError **er)\r\n{\r\n\tGMarkupParseContext\t*ctx;\r\n\tGMarkupParser\t  \t parse;\r\n\tGMappedFile\t\t*f;\r\n\tint\t\t\t rc;\r\n\tstruct kmlparse\t\t data;\r\n\tstruct kml\t\t*kml;\r\n\r\n\tif (NULL != er)\r\n\t\t*er = NULL;\r\n\r\n\tmemset(&parse, 0, sizeof(GMarkupParser));\r\n\tmemset(&data, 0, sizeof(struct kmlparse));\r\n\r\n\tdata.elem = KML_INIT;\r\n\r\n\tparse.start_element = kml_elem_start;\r\n\tparse.end_element = kml_elem_end;\r\n\tparse.text = kml_text;\r\n\tparse.error = kml_error;\r\n\r\n\tif (NULL == (f = g_mapped_file_new(file, FALSE, er)))\r\n\t\treturn(NULL);\r\n\r\n\tctx = g_markup_parse_context_new\r\n\t\t(&parse, 0, &data, NULL);\r\n\tg_assert(NULL != ctx);\r\n\trc = g_markup_parse_context_parse\r\n\t\t(ctx, g_mapped_file_get_contents(f),\r\n\t\t g_mapped_file_get_length(f), er);\r\n\r\n\tg_markup_parse_context_free(ctx);\r\n\tg_free(data.buf);\r\n\tg_free(data.altbuf);\r\n\tg_free(data.ign);\r\n\tkmlparse_free(data.cur);\r\n\r\n\tif (0 == rc) {\r\n\t\tg_list_free_full(data.places, kmlparse_free);\r\n\t\tg_mapped_file_unref(f);\r\n\t\treturn(NULL);\r\n\t} else if (NULL == data.places) {\r\n\t\tg_mapped_file_unref(f);\r\n\t\treturn(NULL);\r\n\t}\r\n\r\n\tg_assert(NULL != data.places);\r\n\tkml = g_malloc0(sizeof(struct kml));\r\n\tkml->file = f;\r\n\tkml->kmls = data.places;\r\n\treturn(kml);\r\n}\r\n\r\ndouble **\r\nkml_migration_twonearest(GList *list, enum maptop map)\r\n{\r\n\tdouble\t\t**p;\r\n\tdouble\t\t  dist, min;\r\n\tsize_t\t\t  i, j, len, minj, min2j;\r\n\tstruct kmlplace\t *pl1, *pl2;\r\n\r\n\tlen = (size_t)g_list_length(list);\r\n\tg_assert(len > 0);\r\n\tif (1 == len) {\r\n\t\tg_debug(\"Request for two nearest falling \"\r\n\t\t\t\"back to nearest\");\r\n\t\treturn(kml_migration_nearest(list, map));\r\n\t}\r\n\r\n\tp = g_malloc0_n(len, sizeof(double *));\r\n\r\n\t/* \r\n\t * Special case the torus, which has a well-defined layout\r\n\t * between nodes, such that the next (\"right\") and previous\r\n\t * (\"left\") islands, wrapping around, get the migrants.\r\n\t */\r\n\tif (MAPTOP_TORUS == map) {\r\n\t\tfor (i = 0; i < len; i++) {\r\n\t\t\tp[i] = g_malloc0_n(len, sizeof(double));\r\n\t\t\tif (i < len - 1)\r\n\t\t\t\tp[i][i + 1] = 0.5;\r\n\t\t\telse\r\n\t\t\t\tp[i][0] = 0.5;\r\n\t\t\tif (i > 0)\r\n\t\t\t\tp[i][i - 1] = 0.5;\r\n\t\t\telse\r\n\t\t\t\tp[i][len - 1] = 0.5;\r\n\t\t}\r\n\t\treturn(p);\r\n\t}\r\n\r\n\tfor (i = 0; i < len; i++) {\r\n\t\tpl1 = g_list_nth_data(list, i);\r\n\t\tp[i] = g_malloc0_n(len, sizeof(double));\r\n\t\tfor (minj = j = 0, min = DBL_MAX; j < len; j++) {\r\n\t\t\tif (i == j)\r\n\t\t\t\tcontinue;\r\n\t\t\tpl2 = g_list_nth_data(list, j);\r\n\t\t\tif ((dist = kml_dist(pl1, pl2)) < min) {\r\n\t\t\t\tmin = dist;\r\n\t\t\t\tminj = j;\r\n\t\t\t}\r\n\t\t}\r\n\t\tp[i][minj] = 0.5;\r\n\t\tfor (min2j = j = 0, min = DBL_MAX; j < len; j++) {\r\n\t\t\tif (i == j || j == minj)\r\n\t\t\t\tcontinue;\r\n\t\t\tpl2 = g_list_nth_data(list, j);\r\n\t\t\tif ((dist = kml_dist(pl1, pl2)) < min) {\r\n\t\t\t\tmin = dist;\r\n\t\t\t\tmin2j = j;\r\n\t\t\t}\r\n\t\t}\r\n\t\tp[i][min2j] = 0.5;\r\n\t\tg_assert(min2j != minj);\r\n\t\tg_assert(i != min2j);\r\n\t}\r\n\r\n\treturn(p);\r\n}\r\n\r\ndouble **\r\nkml_migration_nearest(GList *list, enum maptop map)\r\n{\r\n\tdouble\t\t**p;\r\n\tdouble\t\t  dist, min;\r\n\tsize_t\t\t  i, j, len, minj;\r\n\tstruct kmlplace\t *pl1, *pl2;\r\n\r\n\tlen = (size_t)g_list_length(list);\r\n\tg_assert(len > 0);\r\n\tp = g_malloc0_n(len, sizeof(double *));\r\n\r\n\t/* \r\n\t * Special case the torus, which has a well-defined layout\r\n\t * between nodes, such that the next (\"right\") island, wrapping\r\n\t * around, gets the migrant.\r\n\t */\r\n\tif (MAPTOP_TORUS == map) {\r\n\t\tfor (i = 0; i < len; i++) {\r\n\t\t\tp[i] = g_malloc0_n(len, sizeof(double));\r\n\t\t\tp[i][(i + 1) % len] = 1.0;\r\n\t\t}\r\n\t\treturn(p);\r\n\t}\r\n\r\n\tfor (i = 0; i < len; i++) {\r\n\t\tpl1 = g_list_nth_data(list, i);\r\n\t\tp[i] = g_malloc0_n(len, sizeof(double));\r\n\t\tfor (minj = j = 0, min = DBL_MAX; j < len; j++) {\r\n\t\t\tif (i == j)\r\n\t\t\t\tcontinue;\r\n\t\t\tpl2 = g_list_nth_data(list, j);\r\n\t\t\tif ((dist = kml_dist(pl1, pl2)) < min) {\r\n\t\t\t\tmin = dist;\r\n\t\t\t\tminj = j;\r\n\t\t\t}\r\n\t\t}\r\n\t\tp[i][minj] = 1.0;\r\n\t}\r\n\r\n\treturn(p);\r\n}\r\n\r\ndouble **\r\nkml_migration_distance(GList *list, enum maptop map)\r\n{\r\n\tdouble\t\t**p;\r\n\tdouble\t\t  dist, sum;\r\n\tsize_t\t\t  i, j, len;\r\n\tstruct kmlplace\t *pl1, *pl2;\r\n\r\n\tlen = (size_t)g_list_length(list);\r\n\tg_assert(len > 0);\r\n\tp = g_malloc0_n(len, sizeof(double *));\r\n\tfor (i = 0; i < len; i++) {\r\n\t\tpl1 = g_list_nth_data(list, i);\r\n\t\tp[i] = g_malloc0_n(len, sizeof(double));\r\n\t\tfor (sum = 0.0, j = 0; j < len; j++) {\r\n\t\t\tif (i == j) {\r\n\t\t\t\tp[i][j] = 0.0;\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tpl2 = g_list_nth_data(list, j);\r\n\t\t\tdist = kml_dist(pl1, pl2);\r\n\t\t\tp[i][j] = 1.0 / (dist * dist);\r\n\t\t\tsum += p[i][j];\r\n\t\t}\r\n\t\tfor (j = 0; j < len; j++) \r\n\t\t\tif (i != j)\r\n\t\t\t\tp[i][j] = p[i][j] / sum;\r\n\t}\r\n\r\n\treturn(p);\r\n}\r\n", "meta": {"hexsha": "adf305b5dcacb45a315a9348aa38727ed51b654f", "size": 14406, "ext": "c", "lang": "C", "max_stars_repo_path": "kml.c", "max_stars_repo_name": "kristapsdz/bmigrate", "max_stars_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-03-03T17:13:19.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-03T17:13:19.000Z", "max_issues_repo_path": "kml.c", "max_issues_repo_name": "kristapsdz/bmigrate", "max_issues_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kml.c", "max_forks_repo_name": "kristapsdz/bmigrate", "max_forks_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5008156607, "max_line_length": 76, "alphanum_fraction": 0.6065528252, "num_tokens": 4589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2720245392906821, "lm_q2_score": 0.028007521721541584, "lm_q1q2_score": 0.007618733192976121}}
{"text": "#pragma once\n\n#include \"Periodic.h\"\n\n#include <gsl/gsl>\n\n#include <algorithm>\n#include <vector>\n\n\nnamespace ad {\n\n\nclass Rythm\n{\npublic:\n    explicit Rythm(duration_t aPeriod, int aDuration) :\n        mMetronom(aPeriod),\n        mDuration(aDuration)\n    {}\n\n    Rythm & note(int aTime);\n\n    template <class T_functor, class... VT_args>\n    void forEachEvent(duration_t aDelta, const T_functor & aFunctor, VT_args &&... aArgs);\n\nprivate:\n    Periodic mMetronom;\n    int mDuration;\n    std::vector<int> mScore{};\n    int mCurrentNote{0};\n};\n\n\ninline Rythm & Rythm::note(int aTime)\n{\n    Expects( (aTime >= 0) && (aTime < mDuration) );\n    mScore.push_back(aTime);\n    return *this;\n}\n\n\ntemplate <class T_functor, class... VT_args>\nvoid Rythm::forEachEvent(duration_t aDelta, const T_functor & aFunctor, VT_args &&... aArgs)\n{\n    mMetronom.forEachEvent(aDelta, [&aFunctor, this](duration_t aRemainingTime, VT_args &&... aArgs)\n    {\n        if (std::find(mScore.begin(), mScore.end(), mCurrentNote) != mScore.end())\n        {\n            aFunctor(aRemainingTime, std::forward<VT_args>(aArgs)...);\n        }\n        if (++mCurrentNote == mDuration)\n        {\n            mCurrentNote = 0;\n        };\n    }, std::forward<VT_args>(aArgs)...);\n}\n\n\n} // namespace ad\n", "meta": {"hexsha": "6d76da887b53447cebef75d03e41445dd3471ea6", "size": 1261, "ext": "h", "lang": "C", "max_stars_repo_path": "src/app/shmurp/Utils/Rythm.h", "max_stars_repo_name": "FranzPoize/shmurp", "max_stars_repo_head_hexsha": "354a70fd89d0cdd9b4336961ad01d1567ac22474", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-06T08:48:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-06T08:48:31.000Z", "max_issues_repo_path": "src/app/shmurp/Utils/Rythm.h", "max_issues_repo_name": "FranzPoize/shmurp", "max_issues_repo_head_hexsha": "354a70fd89d0cdd9b4336961ad01d1567ac22474", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/app/shmurp/Utils/Rythm.h", "max_forks_repo_name": "FranzPoize/shmurp", "max_forks_repo_head_hexsha": "354a70fd89d0cdd9b4336961ad01d1567ac22474", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-31T13:17:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-31T13:17:54.000Z", "avg_line_length": 20.6721311475, "max_line_length": 100, "alphanum_fraction": 0.6233148295, "num_tokens": 353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33111973962899144, "lm_q2_score": 0.022977371499006513, "lm_q1q2_score": 0.0076082612681096454}}
{"text": "#include <assert.h>\n#include <stdlib.h>\n#include <ctype.h>\n#include <string.h>\n\n#include <asf.h>\n#include \"asf_tiff.h\"\n\n#include <gsl/gsl_math.h>\n#include <proj_api.h>\n\n#include \"asf_jpeg.h\"\n#include <png.h>\n#include \"envi.h\"\n\n#include \"dateUtil.h\"\n#include <time.h>\n#include \"matrix.h\"\n#include <asf_nan.h>\n#include <asf_endian.h>\n#include <asf_meta.h>\n#include <asf_export.h>\n#include <asf_raster.h>\n#include <float_image.h>\n#include <spheroids.h>\n#include <typlim.h>\n#include <netcdf.h>\n\n#define PGM_MAGIC_NUMBER    \"P5\"\n#ifdef  MAX_RGB\n#undef  MAX_RGB\n#endif\n#define MAX_RGB             255\n#define USHORT_MAX          65535\n#ifdef  OPT_STRIP_BYTES\n#undef  OPT_STRIP_BYTES\n#endif\n#define OPT_STRIP_BYTES     8192\n\n// If you change the BAND_ID_STRING here, make sure you make an identical\n// change in the import library ...the defs must match\n#define BAND_ID_STRING \"Color Channel (Band) Contents in RGBA+ order\"\n\n/* This constant is from the GeoTIFF spec.  It basically means that\n   the system which would normally be specified by the field\n   (projected coordinate system, datum, ellipsoid, whatever), in\n   instead going to be specified by more detailed low level tags.  */\nstatic const int user_defined_value_code = 32767;\n\nstatic char *t3_matrix[9] = {\"T11.bin\",\"T12_real.bin\",\"T12_imag.bin\",\n\t\t\t     \"T13_real.bin\",\"T13_imag.bin\",\"T22.bin\",\n\t\t\t     \"T23_real.bin\",\"T23_imag.bin\",\"T33.bin\"};\nstatic char *t4_matrix[16] = {\"T11.bin\",\"T12_real.bin\",\"T12_imag.bin\",\n\t\t\t      \"T13_real.bin\",\"T13_imag.bin\",\"T14_real.bin\",\n\t\t\t      \"T14_imag.bin\",\"T22.bin\",\"T23_real.bin\",\n\t\t\t      \"T23_imag.bin\",\"T24_real.bin\",\"T24_imag.bin\",\n\t\t\t      \"T33.bin\",\"T34_real.bin\",\"T34_imag.bin\",\n\t\t\t      \"T44.bin\"};\nstatic char *c2_matrix[4] = {\"C11.bin\",\"C12_real.bin\",\"C12_imag.bin\",\n\t\t\t     \"C22.bin\"};\nstatic char *c3_matrix[9] = {\"C11.bin\",\"C12_real.bin\",\"C12_imag.bin\",\n\t\t\t     \"C13_real.bin\",\"C13_imag.bin\",\"C22.bin\",\n\t\t\t     \"C23_real.bin\",\"C23_imag.bin\",\"C33.bin\"};\nstatic char *c4_matrix[16] = {\"C11.bin\",\"C12_real.bin\",\"C12_imag.bin\",\n\t\t\t      \"C13_real.bin\",\"C13_imag.bin\",\"C14_real.bin\",\n\t\t\t      \"C14_imag.bin\",\"C22.bin\",\"C23_real.bin\",\n\t\t\t      \"C23_imag.bin\",\"C24_real.bin\",\"C24_imag.bin\",\n\t\t\t      \"C33.bin\",\"C34_real.bin\",\"C34_imag.bin\",\n\t\t\t      \"C44.bin\"};\nstatic char *freeman2_decomposition[2] = \n  {\"Freeman2_Ground.bin\",\"Freeman2_Vol.bin\"};\nstatic char *freeman3_decomposition[3] = \n  {\"Freeman_Dbl.bin\",\"Freeman_Odd.bin\",\"Freeman_Vol.bin\"};\nstatic char *vanZyl3_decomposition[3] = \n  {\"VanZyl3_Dbl.bin\",\"VanZyl3_Odd.bin\",\"VanZyl3_Vol.bin\"};\nstatic char *yamaguchi3_decomposition[3] = \n  {\"Yamaguchi3_Dbl.bin\",\"Yamaguchi3_Odd.bin\",\"Yamaguchi3_Vol.bin\"};\nstatic char *yamaguchi4_decomposition[4] = \n  {\"Yamaguchi4_Dbl.bin\",\"Yamaguchi4_Hlx.bin\",\"Yamaguchi4_Odd.bin\",\n   \"Yamaguchi4_Vol.bin\"};\nstatic char *krogager_decomposition[3] = \n  {\"Krogager_Kd.bin\",\"Krogager_Kh.bin\",\"Krogager_Ks.bin\"};\nstatic char *touzi1_decomposition[3] = \n  {\"TSVM_alpha_s1.bin\",\"TSVM_alpha_s2.bin\",\"TSVM_alpha_s3.bin\"};\nstatic char *touzi2_decomposition[3] = \n  {\"TSVM_phi_s1.bin\",\"TSVM_phi_s2.bin\",\"TSVM_phi_s3.bin\"};\nstatic char *touzi3_decomposition[3] = \n  {\"TSVM_tau_m1.bin\",\"TSVM_tau_m2.bin\",\"TSVM_tau_m3.bin\"};\nstatic char *touzi4_decomposition[3] = \n  {\"TSVM_psi1.bin\",\"TSVM_psi2.bin\",\"TSVM_psi3.bin\"};\nstatic char *touzi5_decomposition[4] = \n  {\"TSVM_alpha_s.bin\",\"TSVM_phi_s.bin\",\"TSVM_tau_m.bin\",\"TSVM_psi.bin\"};\n\nint is_slant_range(meta_parameters *md);\nvoid initialize_tiff_file (TIFF **otif, GTIF **ogtif,\n                           const char *output_file_name,\n                           const char *metadata_file_name,\n                           int is_geotiff, scale_t sample_mapping,\n                           int rgb, int *palette_color_tiff, char **band_names,\n                           char *look_up_table_name, int is_colormapped);\nGTIF* write_tags_for_geotiff (TIFF *otif, const char *metadata_file_name,\n                              int rgb, char **band_names, int palette_color_tiff);\nvoid finalize_tiff_file(TIFF *otif, GTIF *ogtif, int is_geotiff);\nvoid append_band_names(char **band_names, int rgb, char *citation, int have_look_up_table);\nint lut_to_tiff_palette(unsigned short **colors, int size, char *look_up_table_name);\nvoid dump_palette_tiff_color_map(unsigned short *colors, int map_size);\nint meta_colormap_to_tiff_palette(unsigned short **colors, int *byte_image, meta_colormap *colormap);\nchar *sample_mapping2string(scale_t sample_mapping);\nvoid colormap_to_lut_file(meta_colormap *cm, const char *lut_file);\n\nstatic char *format2str(output_format_t format)\n{\n  char *str = (char *) MALLOC(sizeof(char)*256);\n\n  if (format == ENVI)\n    strcpy(str, \"ENVI\");\n  else if (format == ESRI)\n    strcpy(str, \"ESRI\");\n  else if (format == GEOTIFF)\n    strcpy(str, \"GEOTIFF\");\n  else if (format == TIF)\n    strcpy(str, \"TIFF\");\n  else if (format == JPEG)\n    strcpy(str, \"JPEG\");\n  else if (format == PGM)\n    strcpy(str, \"PGM\");\n  else if (format == PNG)\n    strcpy(str, \"PNG\");\n  else if (format == PNG_ALPHA)\n    strcpy(str, \"PNG ALPHA\");\n  else if (format == PNG_GE)\n    strcpy(str, \"PNG GOOGLE EARTH\");\n  else if (format == KML)\n    strcpy(str, \"KML\");\n  else if (format == POLSARPRO_HDR)\n    strcpy(str, \"POLSARPRO with ENVI header\");\n  else if (format == HDF)\n    strcpy(str, \"HDF5\");\n  else if (format == NC)\n    strcpy(str, \"netCDF\");\n  else\n    strcpy(str, MAGIC_UNSET_STRING);\n  \n  return str;\n}\n\n\nvoid initialize_tiff_file (TIFF **otif, GTIF **ogtif,\n                           const char *output_file_name,\n                           const char *metadata_file_name,\n                           int is_geotiff, scale_t sample_mapping,\n                           int rgb, int *palette_color_tiff, char **band_names,\n                           char *look_up_table_name, int is_colormapped)\n{\n  unsigned short sample_size;\n  int max_dn, map_size = 0, palette_color = 0;\n  unsigned short rows_per_strip;\n  unsigned short *colors = NULL;\n  int have_look_up_table = look_up_table_name && strlen(look_up_table_name) > 0;\n    \n  _XTIFFInitialize();\n\n  // Open output tiff file\n  *otif = XTIFFOpen (output_file_name, \"w\");\n  asfRequire(otif != NULL, \"Error opening output TIFF file.\\n\");\n\n  /* Get the image metadata.  */\n  meta_parameters *md = meta_read (metadata_file_name);\n\n  int byte_image = (md->general->data_type == BYTE) ||\n    !(sample_mapping == NONE && !md->optical && !have_look_up_table);\n  int int_image = (md->general->data_type == INTEGER16 &&\n    !md->optical && !have_look_up_table);\n\n  if (!byte_image && !int_image) {\n      // Float image\n      asfRequire(sizeof (float) == 4,\n                 \"Size of the unsigned char data type on this machine is \"\n                 \"different than expected.\\n\");\n      sample_size = 4;\n      TIFFSetField(*otif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_IEEEFP);\n  }\n  else if (int_image) {\n    sample_size = 2;\n    TIFFSetField(*otif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);\n  }\n  else {\n      // Byte image\n      asfRequire(sizeof(unsigned char) == 1,\n                 \"Size of the unsigned char data type on this machine is \"\n                 \"different than expected.\\n\");\n      if (have_look_up_table) {\n          // Get max DN from lut file and if it's greater than 255, then\n          // the TIFF standard will not allow indexed color.\n          if (sizeof(unsigned short) != 2) {\n              // The TIFF standard requires an unsigned short to be 16 bits long\n              asfPrintError(\"Size of the unsigned short integer data type on this machine (%d bytes) is \"\n                      \"different than expected (2 bytes).\\n\", sizeof(unsigned short));\n          }\n          // Try #1 ...Try 2 bytes just to get past lut_to_tiff_palette() with no errors\n          // ...More accurately, we are using lut_to_tiff_palette() to determine max_dn, the\n          // minimum number of entries that the color table must have\n          sample_size = 2; // Unsigned short ...2 bytes allows a color map 65535 elements long or smaller\n          map_size = 1 << (sample_size * 8); // 2^bits_per_sample;\n          max_dn = lut_to_tiff_palette(&colors, map_size, look_up_table_name);\n          sample_size = 1;\n          palette_color = 0;\n          if (max_dn <= MAX_RGB) {\n              sample_size = 1;\n              map_size = 1 << (sample_size * 8); // 2^bits_per_sample;\n              max_dn = lut_to_tiff_palette(&colors, map_size, look_up_table_name);\n              palette_color = 1;\n          }\n      }\n      else {\n          // No look-up table, so the data is already 0-255 or will be resampled down to\n          // the 0-255 range.  Only need a 1-byte pixel...\n          sample_size = 1;\n      }\n      // The sample format is 'unsigned integer', but the number of bytes per\n      // sample, i.e. short, int, or long, is set by TIFFTAG_BITSPERSAMPLE below\n      // which in turn is determined by the sample_size (in bytes) set above ;-)\n      // Note that for color images, \"bits per sample\" refers to one color component,\n      // not the group of 3 components.\n      TIFFSetField(*otif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);\n  }\n  // use the metadata's colormap if we have one.  a -lut specified on the command\n  // line will override, though (and in that case we should have already set\n  // up the colormap via lut_to_tiff_palette())\n  if (is_colormapped && md->colormap && !have_look_up_table)\n  {\n      asfPrintStatus(\"\\nFound single-band image with RGB color map ...storing as a Palette\\n\"\n          \"Color TIFF\\n\\n\");\n      palette_color = 1;\n      max_dn = map_size = meta_colormap_to_tiff_palette(&colors, &byte_image, md->colormap);\n  }\n\n  /* Set the normal TIFF image tags.  */\n  TIFFSetField(*otif, TIFFTAG_SUBFILETYPE, 0);\n  TIFFSetField(*otif, TIFFTAG_IMAGEWIDTH, md->general->sample_count);\n  TIFFSetField(*otif, TIFFTAG_IMAGELENGTH, md->general->line_count);\n  TIFFSetField(*otif, TIFFTAG_BITSPERSAMPLE, sample_size * 8);\n  TIFFSetField(*otif, TIFFTAG_COMPRESSION, COMPRESSION_LZW);\n  if  (\n       (!have_look_up_table && rgb           )  ||\n       ( have_look_up_table && !palette_color)\n      )\n  {\n      // Color RGB (no palette) image\n      TIFFSetField(*otif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);\n      TIFFSetField(*otif, TIFFTAG_SAMPLESPERPIXEL, 3);\n  }\n  else if (byte_image && palette_color) {\n      // Color Palette image\n      TIFFSetField(*otif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_PALETTE);\n      TIFFSetField(*otif, TIFFTAG_SAMPLESPERPIXEL, 1);\n\n      unsigned short *red, *green, *blue;\n      asfRequire(colors != NULL, \"Color map not allocated.\\n\");\n      asfRequire(map_size > 0,   \"Color map not initialized.\\n\");\n      red   = colors;\n      green = colors +   map_size;\n      blue  = colors + 2*map_size;\n      TIFFSetField(*otif, TIFFTAG_COLORMAP, red, green, blue);\n  }\n  else {\n    // Else assume grayscale with minimum value (usually zero) means 'black'\n    TIFFSetField(*otif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);\n    TIFFSetField(*otif, TIFFTAG_SAMPLESPERPIXEL, 1);\n  }\n\n  // Set rows per strip to 1, 4, 8, or 16 ...trying to set a near optimal 8k strip size\n  // FIXME: Implement the creation of TIFFS with optimized number of rows per strip ...someday\n  rows_per_strip = 1;//((OPT_STRIP_BYTES / (sample_size * md->general->sample_count)) < 4)  ? 1  :\n                   //((OPT_STRIP_BYTES / (sample_size * md->general->sample_count)) < 8)  ? 4  :\n                   //((OPT_STRIP_BYTES / (sample_size * md->general->sample_count)) < 16) ? 8  :\n                   //((OPT_STRIP_BYTES / (sample_size * md->general->sample_count)) < 32) ? 16 :\n                     //                                             (unsigned short) USHORT_MAX;\n  TIFFSetField(*otif, TIFFTAG_ROWSPERSTRIP, rows_per_strip);\n\n  TIFFSetField(*otif, TIFFTAG_XRESOLUTION, 1.0);\n  TIFFSetField(*otif, TIFFTAG_YRESOLUTION, 1.0);\n  TIFFSetField(*otif, TIFFTAG_RESOLUTIONUNIT, RESUNIT_NONE);\n  TIFFSetField(*otif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);\n\n  if (is_geotiff) {\n      *ogtif = write_tags_for_geotiff (*otif, metadata_file_name, rgb, band_names, palette_color);\n  }\n\n  if (should_write_insar_xml_meta(md)) {\n    char *xml_meta = get_insar_xml_string(md, TRUE);\n      TIFFSetField(*otif, TIFFTAG_ASF_INSAR_METADATA, xml_meta);\n      FREE(xml_meta);\n  }\n  else if (should_write_dem_xml_meta(md)) {\n    char *xml_meta = get_dem_xml_string(md, TRUE);\n    TIFFSetField(*otif, TIFFTAG_ASF_DEM_METADATA, xml_meta);\n    FREE(xml_meta);\n  }\n\n  *palette_color_tiff = palette_color;\n\n  meta_free(md);\n}\n\n\nvoid initialize_png_file(const char *output_file_name,\n\t\t\t meta_parameters *meta, FILE **opng,\n\t\t\t png_structp *png_ptr, png_infop *info_ptr,\n\t\t\t int rgb)\n{\n  return initialize_png_file_ext(output_file_name, meta, opng, png_ptr, \n\t\t\t\t info_ptr, rgb, FALSE);\n}\nvoid initialize_png_file_ext(const char *output_file_name,\n\t\t\t     meta_parameters *meta, FILE **opng,\n\t\t\t     png_structp *png_ptr, png_infop *info_ptr,\n\t\t\t     int rgb, int alpha)\n{\n    *opng = FOPEN(output_file_name, \"wb\");\n    *png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,\n        NULL, NULL, NULL);\n    if (!(*png_ptr))\n        asfPrintError(\"Error creating PNG write structure!\\n\");\n\n    *info_ptr = png_create_info_struct(*png_ptr);\n    if (!(*info_ptr))\n        asfPrintError(\"Error creating PNG info structure!\\n\");\n\n    png_init_io(*png_ptr, *opng);\n\n    int width = meta->general->sample_count;\n    int height = meta->general->line_count;\n    png_byte color_type;\n    if (alpha == 0)\n      color_type = rgb ? PNG_COLOR_TYPE_RGB : PNG_COLOR_TYPE_GRAY;\n    else if (alpha == 1) {\n      color_type = rgb ? PNG_COLOR_TYPE_RGB : PNG_COLOR_TYPE_GRAY;\n      int ii;\n      if (rgb) {\n\tpng_color_16 trans_rgb_value[256];\n\tfor (ii=0; ii<256; ii++) {\n\t  trans_rgb_value[ii].red = 255;\n\t  trans_rgb_value[ii].green = 255;\n\t  trans_rgb_value[ii].blue = 255;\n\t}\n\t// setting black to transparent\n\ttrans_rgb_value[0].red = 0;\n\ttrans_rgb_value[0].green = 0;\n\ttrans_rgb_value[0].blue = 0;\n\tpng_set_tRNS(*png_ptr, *info_ptr, trans_rgb_value, 256, NULL);\n      }\n      else {\n\tpng_byte trans_values[256];\n\tfor (ii=0; ii<256; ii++)\n\t  trans_values[ii] = 255;\n\ttrans_values[0] = 0; // setting black to transparent\n\tpng_set_tRNS(*png_ptr, *info_ptr, trans_values, 256, NULL);\n      }\n    }\n    else if (alpha == 2)\n      color_type = PNG_COLOR_TYPE_RGB_ALPHA;\n\n    png_set_IHDR(*png_ptr, *info_ptr, width, height, 8, color_type,\n            PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT,\n            PNG_FILTER_TYPE_DEFAULT);\n\n    png_write_info(*png_ptr, *info_ptr);\n}\n\nvoid initialize_jpeg_file(const char *output_file_name,\n        meta_parameters *meta, FILE **ojpeg,\n        struct jpeg_compress_struct *cinfo, int rgb)\n{\n  struct jpeg_error_mgr *jerr = MALLOC(sizeof(struct jpeg_error_mgr));\n\n  /* We need a version of the data in JSAMPLE form, so we have to map\n     floats into JSAMPLEs.  We do this by defining a region 2 sigma on\n     either side of the mean to be mapped in the range of JSAMPLE\n     linearly, and clamping everything outside this range at the\n     limits o the JSAMPLE range.  */\n  /* Here are some very funky checks to try to ensure that the JSAMPLE\n     really is the type we expect, so we can scale properly.  */\n  asfRequire(sizeof(unsigned char) == 1,\n             \"Size of the unsigned char data type on this machine is \"\n             \"different than expected.\\n\");\n  asfRequire(sizeof(unsigned char) == sizeof (JSAMPLE),\n             \"Size of unsigned char data type on this machine is different \"\n             \"than JPEG byte size.\\n\");\n  JSAMPLE test_jsample = 0;\n  test_jsample--;\n  asfRequire(test_jsample == UCHAR_MAX,\n             \"Something wacky happened, like data overflow.\\n\");\n\n  // Initializae libjpg structures.\n  cinfo->err = jpeg_std_error (jerr);\n  jpeg_create_compress (cinfo);\n\n  // Open the output file to be used.\n  *ojpeg = FOPEN(output_file_name, \"wb\");\n\n  // Connect jpeg output to the output file to be used.\n  jpeg_stdio_dest (cinfo, *ojpeg);\n\n  // Set image parameters that libjpeg needs to know about.\n  cinfo->image_width = meta->general->sample_count;\n  cinfo->image_height = meta->general->line_count;\n  if (rgb) {\n    cinfo->in_color_space = JCS_RGB;\n    cinfo->input_components = 3;\n  }\n  else {\n    cinfo->in_color_space = JCS_GRAYSCALE;\n    cinfo->input_components = 1;\n  }\n  jpeg_set_defaults (cinfo);   // Use default compression parameters.\n  jpeg_set_quality(cinfo, 100, 1);\n\n\n  // Reassure libjpeg that we will be writing a complete JPEG file.\n  jpeg_start_compress (cinfo, TRUE);\n\n  return;\n}\n\nvoid initialize_pgm_file(const char *output_file_name,\n       meta_parameters *meta, FILE **opgm)\n{\n  const int max_color_value = 255;\n\n  *opgm = FOPEN (output_file_name, \"w\");\n\n  fprintf (*opgm, \"%s\\n\", PGM_MAGIC_NUMBER);\n  fprintf (*opgm, \"%ld\\n\", (long int) meta->general->sample_count);\n  fprintf (*opgm, \"%ld\\n\", (long int) meta->general->line_count);\n  fprintf (*opgm, \"%d\\n\", max_color_value);\n\n  return;\n}\n\nvoid initialize_polsarpro_file(const char *output_file_name,\n\t\t\t       meta_parameters *meta, FILE **ofp)\n{\n  *ofp = FOPEN(output_file_name, \"wb\");\n  \n  char *output_header_file_name = \n    (char *) MALLOC(sizeof(char) * strlen(output_file_name) + 5);\n  sprintf(output_header_file_name, \"%s.hdr\", output_file_name);\n  char *band_name = get_filename(output_file_name);\n  envi_header *envi = meta2envi(meta);\n  envi->bands = 1;\n  char *band = stripExt(band_name);\n  strcpy(envi->band_name, band_name);\n  envi->byte_order = 0; // PolSARPro data is little endian by default\n  write_envi_header(output_header_file_name, output_file_name, meta, envi);\n  FREE(output_header_file_name);\n  FREE(band_name);\n  FREE(band);\n  FREE(envi);\n  \n  return;\n}\n\nGTIF* write_tags_for_geotiff (TIFF *otif, const char *metadata_file_name,\n                             int rgb, char **band_names, int palette_color_tiff)\n{\n  /* Get the image metadata.  */\n  meta_parameters *md = meta_read (metadata_file_name);\n  int map_projected = is_map_projected(md);\n  int is_slant_range_image = is_slant_range(md);\n  GTIF *ogtif;\n\n  /* Semi-major and -minor ellipse axis lengths.  This shows up in two\n  different places in our metadata, we want the projected one if\n  its available, otherwise the one from general.  */\n  double re_major, re_minor;\n\n  asfRequire (sizeof (unsigned short) == 2,\n              \"Unsigned short integer data type size is different than \"\n                  \"expected.\\n\");\n  asfRequire (sizeof (unsigned int) == 4,\n              \"Unsigned integer data type size is different than expected.\\n\");\n\n  if (!map_projected) {\n    asfPrintWarning(\"Image is not map-projected or the projection type is\\n\"\n        \"unrecognized or unsupported.\\n\\n\"\n        \"Exporting a non-geocoded, standard TIFF file instead...\\n\");\n  }\n\n  if (is_slant_range_image) {\n    asfPrintWarning(\"Image is either a SAR slant-range image or a ScanSAR\\n\"\n        \"along-track/cross-track projection.  Exporting as a GeoTIFF is not\\n\"\n        \"supported for these types.\\n\\n\"\n        \"Exporting a standard non-georeferenced/non-geocoded TIFF file instead...\\n\");\n  }\n\n  /******************************************/\n  /* Set the GeoTIFF extension image tags.  */\n  ogtif = GTIFNew (otif);\n  asfRequire (ogtif != NULL, \"Error opening output GeoKey file descriptor.\\n\");\n\n  // Common tags\n  if (map_projected)\n  {\n    // Write common tags for map-projected GeoTIFFs\n    GTIFKeySet (ogtif, GTRasterTypeGeoKey, TYPE_SHORT, 1, RasterPixelIsArea);\n    if (md->projection->type != LAT_LONG_PSEUDO_PROJECTION)\n      GTIFKeySet (ogtif, GTModelTypeGeoKey, TYPE_SHORT, 1, ModelTypeProjected);\n    else\n      GTIFKeySet (ogtif, GTModelTypeGeoKey, TYPE_SHORT, 1, ModelTypeGeographic);\n    GTIFKeySet (ogtif, GeogLinearUnitsGeoKey, TYPE_SHORT, 1, Linear_Meter);\n    GTIFKeySet (ogtif, GeogAngularUnitsGeoKey, TYPE_SHORT, 1, Angular_Degree);\n    GTIFKeySet (ogtif, ProjLinearUnitsGeoKey, TYPE_SHORT, 1, Linear_Meter);\n    GTIFKeySet (ogtif, GeogPrimeMeridianGeoKey, TYPE_SHORT, 1, PM_Greenwich);\n    re_major = md->projection->re_major;\n    re_minor = md->projection->re_minor;\n  }\n  else {\n    // If not map-projected, then common tags are not written.  If the file\n    // is georeferenced however, then pixel scale and tie point will be\n    // written below\n\n    re_major = md->general->re_major;\n    re_minor = md->general->re_minor;\n  }\n\n  // Pixel scale and tie points\n  if (md->projection) {\n    if (!(meta_is_valid_double(md->projection->startX) &&\n          meta_is_valid_double(md->projection->startY))\n       )\n    {\n      asfPrintWarning(\"Metadata projection block contains invalid startX \"\n          \"or startY values\\n\");\n    }\n    // Write georeferencing data\n    if (!is_slant_range_image) {\n      double tie_point[6];\n      double pixel_scale[3];\n      // FIXME: Note that the following tie points are in meters, but that's\n      // because we assume linear meters and a map-projected image.  If we ever\n      // export a geographic (lat/long) geotiff, then this code will need to\n      // smarten-up and write the tie points in lat/long or meters depending on the\n      // type of image data.  Same thing applies to perX and perY etc etc.\n      tie_point[0] = 0.0;\n      tie_point[1] = 0.0;\n      tie_point[2] = 0.0;\n\n      // these are both meters\n      tie_point[3] = md->projection->startX +\n                     md->general->start_sample * md->projection->perX;\n      tie_point[4] = md->projection->startY +\n                     md->general->start_line * md->projection->perY;\n\n      tie_point[5] = 0.0;\n      TIFFSetField(otif, TIFFTAG_GEOTIEPOINTS, 6, tie_point);\n\n      /* Set the scale of the pixels, in projection coordinates.  */\n      if (md->projection->perX < 0.0) {\n        asfPrintWarning(\"Unexpected non-positive perX in the \"\n            \"projection block.\\n\");\n      }\n      else {\n        pixel_scale[0] = fabs(md->projection->perX);\n      }\n\n      if (md->projection->perY > 0.0) {\n        asfPrintWarning(\"Unexpected non-negative perY in the \"\n            \"projection block.\\n\");\n      }\n      else {\n        pixel_scale[1] = fabs(md->projection->perY);\n        pixel_scale[2] = 0;\n      }\n      TIFFSetField (otif, TIFFTAG_GEOPIXELSCALE, 3, pixel_scale);\n    }\n  }\n\n  // Write geocode (map projection) parameters\n  if (map_projected) {\n    int max_citation_length = 2048;\n    char *citation;\n    int citation_length;\n\n    // For now, only support the Hughes ellipsoid for polar stereo\n    if (md->projection->datum == HUGHES_DATUM &&\n        md->projection->type != POLAR_STEREOGRAPHIC)\n    {\n      asfPrintError(\"Hughes Ellipsoid is only supported for Polar Stereographic projections.\\n\");\n    }\n\n    /* Write the appropriate geotiff keys for the projection type.  */\n    switch (md->projection->type) {\n      case UNIVERSAL_TRANSVERSE_MERCATOR:\n      {\n        short pcs;\n        if ( UTM_2_PCS(&pcs, md->projection->datum,\n             md->projection->param.utm.zone, md->projection->hem) ) {\n          GTIFKeySet (ogtif, ProjectedCSTypeGeoKey, TYPE_SHORT, 1, pcs);\n        GTIFKeySet (ogtif, ProjectionGeoKey, TYPE_SHORT, 1,\n                    user_defined_value_code);\n        GTIFKeySet (ogtif, ProjCoordTransGeoKey, TYPE_SHORT, 1,\n                    CT_TransverseMercator);\n\t  \n\t  if (meta_is_valid_double(md->projection->param.utm.false_easting)) {\n\t    GTIFKeySet (ogtif, ProjFalseEastingGeoKey, TYPE_DOUBLE, 1,\n\t\t\tmd->projection->param.utm.false_easting);\n\t  }\n\t  else {\n\t    GTIFKeySet (ogtif, ProjFalseEastingGeoKey, TYPE_DOUBLE, 1, 0.0);\n\t  }\n\t  if (meta_is_valid_double(md->projection->param.utm.false_northing)) {\n\t    GTIFKeySet (ogtif, ProjFalseNorthingGeoKey, TYPE_DOUBLE, 1,\n\t\t\tmd->projection->param.utm.false_northing);\n\t  }\n\t  else {\n\t    GTIFKeySet (ogtif, ProjFalseNorthingGeoKey, TYPE_DOUBLE, 1, 0.0);\n\t  }\n\t  if (meta_is_valid_double(md->projection->param.utm.lat0)) {\n\t    GTIFKeySet (ogtif, ProjNatOriginLatGeoKey, TYPE_DOUBLE, 1,\n\t\t\tmd->projection->param.utm.lat0);\n\t  }\n\t  if (meta_is_valid_double(md->projection->param.utm.lon0)) {\n\t    GTIFKeySet (ogtif, ProjNatOriginLongGeoKey, TYPE_DOUBLE, 1,\n\t\t\tmd->projection->param.utm.lon0);\n\t  }\n\t  GTIFKeySet (ogtif, ProjScaleAtNatOriginGeoKey, TYPE_DOUBLE, 1,\n\t\t      md->projection->param.utm.scale_factor);\n\n\t  write_datum_key(ogtif, md->projection->datum);\n\t  write_spheroid_key(ogtif, md->projection->spheroid, re_major, \n\t\t\t     re_minor);\n\n          // Write the citation\n          char datum_str[256];\n          if (md->projection->datum == ITRF97_DATUM) {\n            strcpy(datum_str, \"ITRF97 (WGS 84)\");\n          }\n          else {\n            pcs_2_string (datum_str, pcs);\n          }\n          citation = MALLOC ((max_citation_length + 1) * sizeof (char));\n          snprintf (citation, max_citation_length + 1,\n                    \"UTM zone %d %c projected GeoTIFF on %s \"\n                    \"%s written by Alaska Satellite Facility tools.\",\n                    md->projection->param.utm.zone, md->projection->hem,\n                    datum_str,\n                    md->projection->datum == HUGHES_DATUM ? \"ellipsoid\" : \"datum\");\n          append_band_names(band_names, rgb, citation, palette_color_tiff);\n          citation_length = strlen(citation);\n          asfRequire((citation_length >= 0) && (citation_length <= max_citation_length),\n                     \"GeoTIFF citation too long\" );\n          GTIFKeySet (ogtif, PCSCitationGeoKey, TYPE_ASCII, 1, citation);\n          GTIFKeySet (ogtif, GTCitationGeoKey, TYPE_ASCII, 1, citation);\n          FREE(citation);\n        }\n        else {\n          asfPrintWarning(\"Unsupported combination of datum and hemisphere for a UTM\\n\"\n              \"map projection occurred.\\n\"\n              \"...GeoTIFF will be written but will not contain projection information\\n\"\n              \"other than tiepoints and pixel scales.\\n\");\n        }\n      }\n        break;\n      case ALBERS_EQUAL_AREA:\n      {\n        GTIFKeySet (ogtif, ProjectedCSTypeGeoKey, TYPE_SHORT, 1,\n                    user_defined_value_code);\n        GTIFKeySet (ogtif, ProjectionGeoKey, TYPE_SHORT, 1,\n                    user_defined_value_code);\n        GTIFKeySet (ogtif, ProjCoordTransGeoKey, TYPE_SHORT, 1,\n                    CT_AlbersEqualArea);\n        if (meta_is_valid_double(md->projection->param.albers.std_parallel1)) {\n          GTIFKeySet (ogtif, ProjStdParallel1GeoKey, TYPE_DOUBLE, 1,\n                      md->projection->param.albers.std_parallel1);\n        }\n        if (meta_is_valid_double(md->projection->param.albers.std_parallel2)) {\n          GTIFKeySet (ogtif, ProjStdParallel2GeoKey, TYPE_DOUBLE, 1,\n                      md->projection->param.albers.std_parallel2);\n        }\n        if (meta_is_valid_double(md->projection->param.albers.false_easting)) {\n          GTIFKeySet (ogtif, ProjFalseEastingGeoKey, TYPE_DOUBLE, 1,\n                      md->projection->param.albers.false_easting);\n        }\n        else {\n          GTIFKeySet (ogtif, ProjFalseEastingGeoKey, TYPE_DOUBLE, 1, 0.0);\n        }\n        if (meta_is_valid_double(md->projection->param.albers.false_northing)) {\n          GTIFKeySet (ogtif, ProjFalseNorthingGeoKey, TYPE_DOUBLE, 1,\n                      md->projection->param.albers.false_northing);\n        }\n        else {\n          GTIFKeySet (ogtif, ProjFalseNorthingGeoKey, TYPE_DOUBLE, 1, 0.0);\n        }\n        if (meta_is_valid_double(md->projection->param.albers.orig_latitude)) {\n          GTIFKeySet (ogtif, ProjNatOriginLatGeoKey, TYPE_DOUBLE, 1,\n                      md->projection->param.albers.orig_latitude);\n        }\n        if (meta_is_valid_double(md->projection->param.albers.center_meridian)) {\n          // The following is where ArcGIS looks for the center meridian\n          GTIFKeySet (ogtif, ProjCenterLongGeoKey, TYPE_DOUBLE, 1,\n                      md->projection->param.albers.center_meridian);\n          // The following is where the center meridian _should_ be stored\n          GTIFKeySet (ogtif, ProjNatOriginLongGeoKey, TYPE_DOUBLE, 1,\n                      md->projection->param.albers.center_meridian);\n        }\n        write_datum_key(ogtif, md->projection->datum);\n        write_spheroid_key(ogtif, md->projection->spheroid, re_major, re_minor);\n\n        /* Set the citation key.  */\n        char datum_str[256];\n        datum_2_string (datum_str, md->projection->datum);\n        citation = MALLOC ((max_citation_length + 1) * sizeof (char));\n        snprintf (citation, max_citation_length + 1,\n                  \"Albers equal-area conic projected GeoTIFF using %s \"\n                  \"%s written by Alaska Satellite Facility \"\n                  \"tools.\", datum_str,\n                      md->projection->datum == HUGHES_DATUM ? \"ellipsoid\" : \"datum\");\n        append_band_names(band_names, rgb, citation, palette_color_tiff);\n        citation_length = strlen(citation);\n        asfRequire (citation_length >= 0 && citation_length <= max_citation_length,\n                    \"bad citation length\");\n        // The following is not needed for any but UTM (according to the standard)\n        // but it appears that everybody uses it anyway... so we'll write it\n        GTIFKeySet (ogtif, PCSCitationGeoKey, TYPE_ASCII, 1, citation);\n        // The following is recommended by the standard\n        GTIFKeySet (ogtif, GTCitationGeoKey, TYPE_ASCII, 1, citation);\n        free (citation);\n      }\n        break;\n      case LAMBERT_CONFORMAL_CONIC:\n      {\n        GTIFKeySet (ogtif, ProjectedCSTypeGeoKey, TYPE_SHORT, 1,\n                    user_defined_value_code);\n        GTIFKeySet (ogtif, ProjectionGeoKey, TYPE_SHORT, 1,\n                    user_defined_value_code);\n        GTIFKeySet (ogtif, ProjCoordTransGeoKey, TYPE_SHORT, 1,\n                    CT_LambertConfConic_2SP);\n        if (meta_is_valid_double(md->projection->param.lamcc.plat1)) {\n          GTIFKeySet (ogtif, ProjStdParallel1GeoKey, TYPE_DOUBLE, 1,\n                      md->projection->param.lamcc.plat1);\n        }\n        if (meta_is_valid_double(md->projection->param.lamcc.plat2)) {\n          GTIFKeySet (ogtif, ProjStdParallel2GeoKey, TYPE_DOUBLE, 1,\n                      md->projection->param.lamcc.plat2);\n        }\n        if (meta_is_valid_double(md->projection->param.lamcc.false_easting)) {\n          GTIFKeySet (ogtif, ProjFalseOriginEastingGeoKey, TYPE_DOUBLE, 1,\n                      md->projection->param.lamcc.false_easting);\n        }\n        else {\n          GTIFKeySet (ogtif, ProjFalseOriginEastingGeoKey, TYPE_DOUBLE, 1, 0.0);\n        }\n        if (meta_is_valid_double(md->projection->param.lamcc.false_northing)) {\n          GTIFKeySet (ogtif, ProjFalseOriginNorthingGeoKey, TYPE_DOUBLE, 1,\n                      md->projection->param.lamcc.false_northing);\n        }\n        else {\n          GTIFKeySet(ogtif, ProjFalseOriginNorthingGeoKey, TYPE_DOUBLE, 1, 0.0);\n        }\n        if (meta_is_valid_double(md->projection->param.lamcc.lon0)) {\n          GTIFKeySet (ogtif, ProjFalseOriginLongGeoKey, TYPE_DOUBLE, 1,\n                      md->projection->param.lamcc.lon0);\n        }\n        if (meta_is_valid_double(md->projection->param.lamcc.lat0)) {\n          GTIFKeySet (ogtif, ProjFalseOriginLatGeoKey, TYPE_DOUBLE, 1,\n                      md->projection->param.lamcc.lat0);\n        }\n        write_datum_key(ogtif, md->projection->datum);\n        write_spheroid_key(ogtif, md->projection->spheroid, re_major, re_minor);\n\n        /* Set the citation key.  */\n        char datum_str[256];\n        datum_2_string (datum_str, md->projection->datum);\n        citation = MALLOC ((max_citation_length + 1) * sizeof (char));\n        snprintf (citation, max_citation_length + 1,\n                  \"Lambert conformal conic projected GeoTIFF using %s \"\n                  \"%s written by Alaska Satellite Facility \"\n                  \"tools.\", datum_str,\n                  md->projection->datum == HUGHES_DATUM ? \"ellipsoid\" : \"datum\");\n        append_band_names(band_names, rgb, citation, palette_color_tiff);\n        citation_length = strlen(citation);\n        asfRequire (citation_length >= 0 && citation_length <= max_citation_length,\n                    \"bad citation length\");\n        // The following is not needed for any but UTM (according to the standard)\n        // but it appears that everybody uses it anyway... so we'll write it\n        GTIFKeySet (ogtif, PCSCitationGeoKey, TYPE_ASCII, 1, citation);\n        // The following is recommended by the standard\n        GTIFKeySet (ogtif, GTCitationGeoKey, TYPE_ASCII, 1, citation);\n        free (citation);\n      }\n      break;\n      case POLAR_STEREOGRAPHIC:\n      {\n        GTIFKeySet (ogtif, ProjectedCSTypeGeoKey, TYPE_SHORT, 1,\n                    user_defined_value_code);\n        GTIFKeySet (ogtif, ProjectionGeoKey, TYPE_SHORT, 1,\n                    user_defined_value_code);\n        GTIFKeySet (ogtif, ProjCoordTransGeoKey, TYPE_SHORT, 1,\n                    CT_PolarStereographic);\n        if (meta_is_valid_double(md->projection->param.ps.slon)) {\n          GTIFKeySet (ogtif, ProjStraightVertPoleLongGeoKey, TYPE_DOUBLE, 1,\n                      md->projection->param.ps.slon);\n        }\n        if (meta_is_valid_double(md->projection->param.ps.slat)) {\n          GTIFKeySet (ogtif, ProjNatOriginLatGeoKey, TYPE_DOUBLE, 1,\n                      md->projection->param.ps.slat);\n        }\n        if (meta_is_valid_double(md->projection->param.ps.false_easting)) {\n          GTIFKeySet (ogtif, ProjFalseEastingGeoKey, TYPE_DOUBLE, 1,\n                      md->projection->param.ps.false_easting);\n        }\n        else {\n          GTIFKeySet (ogtif, ProjFalseEastingGeoKey, TYPE_DOUBLE, 1, 0.0);\n        }\n        if (meta_is_valid_double(md->projection->param.ps.false_northing)) {\n          GTIFKeySet (ogtif, ProjFalseNorthingGeoKey, TYPE_DOUBLE, 1,\n                      md->projection->param.ps.false_northing);\n        }\n        else {\n          GTIFKeySet (ogtif, ProjFalseNorthingGeoKey, TYPE_DOUBLE, 1, 0.0);\n        }\n\tGTIFKeySet(ogtif, ProjScaleAtNatOriginGeoKey, TYPE_DOUBLE, 1, 1.0);\n        write_datum_key(ogtif, md->projection->datum);\n        write_spheroid_key(ogtif, md->projection->spheroid, re_major, re_minor);\n\n        /* Set the citation key.  */\n        char datum_str[256];\n        datum_2_string (datum_str, md->projection->datum);\n        citation = MALLOC ((max_citation_length + 1) * sizeof (char));\n        if (md->projection->datum != HUGHES_DATUM) {\n          snprintf (citation, max_citation_length + 1,\n                    \"Polar stereographic projected GeoTIFF using %s \"\n                    \"datum written by Alaska Satellite Facility \"\n                    \"tools\", datum_str);\n          append_band_names(band_names, rgb, citation, palette_color_tiff);\n          citation_length = strlen(citation);\n          asfRequire (citation_length >= 0 &&\n                      citation_length <= max_citation_length,\n                      \"bad citation length\");\n        }\n        else {\n          // Hughes Datum\n          // ...Since the datum is user-defined and the GeoTIFF is now delving outside the\n          // realm of 'normal' GeoTIFFs, we put all the pertinent projection parameters\n          // into the citation strings to help users if their s/w doesn't 'like' user-defined\n          // datums.\n\t  /*\n          snprintf (citation, max_citation_length + 1,\n                    \"Polar stereographic projected GeoTIFF using Hughes \"\n                    \"ellipsoid written by Alaska Satellite Facility \"\n                    \"tools, Natural Origin Latitude %lf, Straight Vertical \"\n                    \"Pole %lf.\", md->projection->param.ps.slat,\n                    md->projection->param.ps.slon);\n          append_band_names(band_names, rgb, citation, palette_color_tiff);\n          citation_length = strlen(citation);\n          asfRequire (citation_length >= 0 &&\n              citation_length <= max_citation_length,\n          \"bad citation length\");\n\t  */\n\t  GTIFKeySet(ogtif, GeographicTypeGeoKey, TYPE_SHORT, 1, 4054);\n\t  sprintf(citation, \"NSIDC Sea Ice Polar Stereographic North\");\n        }\n        GTIFKeySet (ogtif, PCSCitationGeoKey, TYPE_ASCII, 1, citation);\n        GTIFKeySet (ogtif, GTCitationGeoKey, TYPE_ASCII, 1, citation);\n        free (citation);\n      }\n      break;\n      case LAMBERT_AZIMUTHAL_EQUAL_AREA:\n      {\n        GTIFKeySet (ogtif, ProjectedCSTypeGeoKey, TYPE_SHORT, 1,\n                    user_defined_value_code);\n        GTIFKeySet (ogtif, ProjectionGeoKey, TYPE_SHORT, 1,\n                    user_defined_value_code);\n        GTIFKeySet (ogtif, ProjCoordTransGeoKey, TYPE_SHORT, 1,\n                    CT_LambertAzimEqualArea);\n        if (meta_is_valid_double(md->projection->param.lamaz.center_lon)) {\n          GTIFKeySet (ogtif, ProjCenterLongGeoKey, TYPE_DOUBLE, 1,\n                      md->projection->param.lamaz.center_lon);\n        }\n        if (meta_is_valid_double(md->projection->param.lamaz.center_lat)) {\n          GTIFKeySet (ogtif, ProjCenterLatGeoKey, TYPE_DOUBLE, 1,\n                      md->projection->param.lamaz.center_lat);\n        }\n        if (meta_is_valid_double(md->projection->param.lamaz.false_easting)) {\n          GTIFKeySet (ogtif, ProjFalseEastingGeoKey, TYPE_DOUBLE, 1,\n                      md->projection->param.lamaz.false_easting);\n        }\n        else {\n          GTIFKeySet (ogtif, ProjFalseEastingGeoKey, TYPE_DOUBLE, 1, 0.0);\n        }\n        if (meta_is_valid_double(md->projection->param.lamaz.false_northing)) {\n          GTIFKeySet (ogtif, ProjFalseNorthingGeoKey, TYPE_DOUBLE, 1,\n                      md->projection->param.lamaz.false_northing);\n        }\n        else {\n          GTIFKeySet (ogtif, ProjFalseNorthingGeoKey, TYPE_DOUBLE, 1, 0.0);\n        }\n        write_datum_key(ogtif, md->projection->datum);\n        write_spheroid_key(ogtif, md->projection->spheroid, re_major, re_minor);\n\n        /* Set the citation key.  */\n        char datum_str[256];\n        datum_2_string (datum_str, md->projection->datum);\n        citation = MALLOC ((max_citation_length + 1) * sizeof (char));\n        snprintf (citation, max_citation_length + 1,\n                  \"Lambert azimuthal equal area projected GeoTIFF using \"\n                  \"%s %s written by Alaska Satellite \"\n                      \"Facility tools.\", datum_str,\n                  md->projection->datum == HUGHES_DATUM ? \"ellipsoid\" : \"datum\");\n        append_band_names(band_names, rgb, citation, palette_color_tiff);\n        citation_length = strlen(citation);\n        asfRequire (citation_length >= 0 &&\n            citation_length <= max_citation_length,\n                \"bad citation length\");\n        // The following is not needed for any but UTM (according to the standard)\n        // but it appears that everybody uses it anyway... so we'll write it\n        GTIFKeySet (ogtif, PCSCitationGeoKey, TYPE_ASCII, 1, citation);\n        // The following is recommended by the standard\n        GTIFKeySet (ogtif, GTCitationGeoKey, TYPE_ASCII, 1, citation);\n        free (citation);\n      }\n        break;\n      case EQUI_RECTANGULAR:\n      {\n        GTIFKeySet (ogtif, ProjectedCSTypeGeoKey, TYPE_SHORT, 1,\n                    user_defined_value_code);\n        GTIFKeySet (ogtif, ProjectionGeoKey, TYPE_SHORT, 1,\n                    user_defined_value_code);\n        GTIFKeySet (ogtif, ProjCoordTransGeoKey, TYPE_SHORT, 1,\n                    CT_Equirectangular);\n\tGTIFKeySet (ogtif, ProjStdParallel1GeoKey, TYPE_DOUBLE, 1, 0.0);\n        if (meta_is_valid_double(md->projection->param.eqr.central_meridian)) {\n          GTIFKeySet (ogtif, ProjCenterLongGeoKey, TYPE_DOUBLE, 1,\n                      md->projection->param.eqr.central_meridian);\n        }\n        if (meta_is_valid_double(md->projection->param.eqr.orig_latitude)) {\n          GTIFKeySet (ogtif, ProjCenterLatGeoKey, TYPE_DOUBLE, 1,\n                      md->projection->param.eqr.orig_latitude);\n        }\n        if (meta_is_valid_double(md->projection->param.eqr.false_easting)) {\n          GTIFKeySet (ogtif, ProjFalseEastingGeoKey, TYPE_DOUBLE, 1,\n                      md->projection->param.eqr.false_easting);\n        }\n        else {\n          GTIFKeySet (ogtif, ProjFalseEastingGeoKey, TYPE_DOUBLE, 1, 0.0);\n        }\n        if (meta_is_valid_double(md->projection->param.eqr.false_northing)) {\n          GTIFKeySet (ogtif, ProjFalseNorthingGeoKey, TYPE_DOUBLE, 1,\n                      md->projection->param.eqr.false_northing);\n        }\n        else {\n          GTIFKeySet (ogtif, ProjFalseNorthingGeoKey, TYPE_DOUBLE, 1, 0.0);\n        }\n        write_datum_key(ogtif, md->projection->datum);\n        write_spheroid_key(ogtif, md->projection->spheroid, re_major, re_minor);\n\n        /* Set the citation key.  */\n        char datum_str[256];\n        datum_2_string (datum_str, md->projection->datum);\n        citation = MALLOC ((max_citation_length + 1) * sizeof (char));\n        snprintf (citation, max_citation_length + 1,\n                  \"Equi-rectangular projected GeoTIFF using \"\n                  \"%s %s written by Alaska Satellite \"\n                      \"Facility tools.\", datum_str,\n                  md->projection->datum == HUGHES_DATUM ? \"ellipsoid\" : \"datum\");\n        append_band_names(band_names, rgb, citation, palette_color_tiff);\n        citation_length = strlen(citation);\n        asfRequire (citation_length >= 0 &&\n            citation_length <= max_citation_length,\n                \"bad citation length\");\n        // The following is not needed for any but UTM (according to the standard)\n        // but it appears that everybody uses it anyway... so we'll write it\n        GTIFKeySet (ogtif, PCSCitationGeoKey, TYPE_ASCII, 1, citation);\n        // The following is recommended by the standard\n        GTIFKeySet (ogtif, GTCitationGeoKey, TYPE_ASCII, 1, citation);\n        free (citation);\n      }\n        break;\n      case EQUIDISTANT:\n      {\n\tGTIFKeySet (ogtif, GeogEllipsoidGeoKey, TYPE_SHORT, 1,\n\t\t    md->projection->spheroid);\n        GTIFKeySet (ogtif, ProjectedCSTypeGeoKey, TYPE_SHORT, 1,\n                    user_defined_value_code);\n        GTIFKeySet (ogtif, ProjectionGeoKey, TYPE_SHORT, 1,\n                    user_defined_value_code);\n        GTIFKeySet (ogtif, ProjCoordTransGeoKey, TYPE_SHORT, 1,\n                    32663);\n        if (meta_is_valid_double(md->projection->param.eqc.central_meridian)) {\n          GTIFKeySet (ogtif, ProjCenterLongGeoKey, TYPE_DOUBLE, 1,\n                      md->projection->param.eqc.central_meridian);\n        }\n        if (meta_is_valid_double(md->projection->param.eqc.orig_latitude)) {\n          GTIFKeySet (ogtif, ProjCenterLatGeoKey, TYPE_DOUBLE, 1,\n                      md->projection->param.eqc.orig_latitude);\n\t}\n        write_datum_key(ogtif, md->projection->datum);\n        write_spheroid_key(ogtif, md->projection->spheroid, re_major, re_minor);\n\n        /* Set the citation key.  */\n        char datum_str[256];\n        datum_2_string (datum_str, md->projection->datum);\n        citation = MALLOC ((max_citation_length + 1) * sizeof (char));\n        snprintf (citation, max_citation_length + 1,\n                  \"WGS 84 / World Equidistant Cylindrical\");\n        citation_length = strlen(citation);\n        asfRequire (citation_length >= 0 &&\n            citation_length <= max_citation_length,\n                \"bad citation length\");\n        // The following is not needed for any but UTM (according to the standard)\n        // but it appears that everybody uses it anyway... so we'll write it\n        GTIFKeySet (ogtif, PCSCitationGeoKey, TYPE_ASCII, 1, citation);\n        // The following is recommended by the standard\n        GTIFKeySet (ogtif, GTCitationGeoKey, TYPE_ASCII, 1, citation);\n        free (citation);\n      }\n        break;\n      case MERCATOR:\n      {\n        GTIFKeySet (ogtif, ProjectedCSTypeGeoKey, TYPE_SHORT, 1,\n                    user_defined_value_code);\n        GTIFKeySet (ogtif, ProjectionGeoKey, TYPE_SHORT, 1,\n                    user_defined_value_code);\n        GTIFKeySet (ogtif, ProjCoordTransGeoKey, TYPE_SHORT, 1,\n                    CT_Mercator);\n        if (meta_is_valid_double(md->projection->param.mer.central_meridian)) {\n          GTIFKeySet (ogtif, ProjNatOriginLongGeoKey, TYPE_DOUBLE, 1,\n                      md->projection->param.mer.central_meridian);\n        }\n        if (meta_is_valid_double(md->projection->param.mer.orig_latitude)) {\n          GTIFKeySet (ogtif, ProjNatOriginLatGeoKey, TYPE_DOUBLE, 1,\n                      md->projection->param.mer.orig_latitude);\n        }\n        if (meta_is_valid_double(md->projection->param.mer.standard_parallel)) {\n\t  // GeoTIFF only supports the scale factor version.\n\t  // Hence some fancy calculation\n\t  double lat = md->projection->param.mer.orig_latitude;\n\t  double lat1 = md->projection->param.mer.standard_parallel;\n\t  double re = md->projection->re_major;\n\t  double rp = md->projection->re_minor;\n\t  double e2 = sqrt(1.0 - rp*rp/(re*re));\n\t  double scale = (sqrt(1.0 - e2*sin(lat)*sin(lat))/cos(lat)) * \n\t    (cos(lat1)/sqrt(1.0 - e2*sin(lat1)*sin(lat1)));\n\n          GTIFKeySet (ogtif, ProjScaleAtNatOriginGeoKey, TYPE_DOUBLE, 1, scale);\n        }\n        if (meta_is_valid_double(md->projection->param.mer.false_easting)) {\n          GTIFKeySet (ogtif, ProjFalseEastingGeoKey, TYPE_DOUBLE, 1,\n                      md->projection->param.mer.false_easting);\n        }\n        else {\n          GTIFKeySet (ogtif, ProjFalseEastingGeoKey, TYPE_DOUBLE, 1, 0.0);\n        }\n        if (meta_is_valid_double(md->projection->param.mer.false_northing)) {\n          GTIFKeySet (ogtif, ProjFalseNorthingGeoKey, TYPE_DOUBLE, 1,\n                      md->projection->param.mer.false_northing);\n        }\n        else {\n          GTIFKeySet (ogtif, ProjFalseNorthingGeoKey, TYPE_DOUBLE, 1, 0.0);\n        }\n        write_datum_key(ogtif, md->projection->datum);\n        write_spheroid_key(ogtif, md->projection->spheroid, re_major, re_minor);\n\n        /* Set the citation key.  */\n        char datum_str[256];\n        datum_2_string (datum_str, md->projection->datum);\n        citation = MALLOC ((max_citation_length + 1) * sizeof (char));\n        snprintf (citation, max_citation_length + 1,\n                  \"Mercator projected GeoTIFF using \"\n                  \"%s %s written by Alaska Satellite \"\n                      \"Facility tools.\", datum_str,\n                  md->projection->datum == HUGHES_DATUM ? \"ellipsoid\" : \"datum\");\n        append_band_names(band_names, rgb, citation, palette_color_tiff);\n        citation_length = strlen(citation);\n        asfRequire (citation_length >= 0 &&\n            citation_length <= max_citation_length,\n                \"bad citation length\");\n        // The following is not needed for any but UTM (according to the standard)\n        // but it appears that everybody uses it anyway... so we'll write it\n        GTIFKeySet (ogtif, PCSCitationGeoKey, TYPE_ASCII, 1, citation);\n        // The following is recommended by the standard\n        GTIFKeySet (ogtif, GTCitationGeoKey, TYPE_ASCII, 1, citation);\n        free (citation);\n      }\n        break;\n      case SINUSOIDAL:\n\t{\n\t  GTIFKeySet (ogtif, ProjectedCSTypeGeoKey, TYPE_SHORT, 1,\n\t\t      user_defined_value_code);\n\t  GTIFKeySet (ogtif, ProjectionGeoKey, TYPE_SHORT, 1,\n\t\t      user_defined_value_code);\n\t  GTIFKeySet (ogtif, ProjCoordTransGeoKey, TYPE_SHORT, 1,\n\t\t      CT_Sinusoidal);\n\t  if (meta_is_valid_double(md->projection->param.sin.longitude_center))\n\t    GTIFKeySet (ogtif, ProjCenterLongGeoKey, TYPE_DOUBLE, 1,\n\t\t\tmd->projection->param.sin.longitude_center);\n\t  if (meta_is_valid_double(md->projection->param.sin.false_easting))\n\t    GTIFKeySet (ogtif, ProjFalseEastingGeoKey, TYPE_DOUBLE, 1,\n\t\t\tmd->projection->param.sin.false_easting);\n\t  else\n\t    GTIFKeySet (ogtif, ProjFalseEastingGeoKey, TYPE_DOUBLE, 1, 0.0);\n\t  if (meta_is_valid_double(md->projection->param.sin.false_northing)) \n\t    GTIFKeySet (ogtif, ProjFalseNorthingGeoKey, TYPE_DOUBLE, 1,\n\t\t\tmd->projection->param.sin.false_northing);\n\t  else\n\t    GTIFKeySet (ogtif, ProjFalseNorthingGeoKey, TYPE_DOUBLE, 1, 0.0);\n\n\t  // Write spherical paramters\n\t  GTIFKeySet (ogtif, GeogEllipsoidGeoKey, TYPE_SHORT, 1, \n\t\t      user_defined_value_code);\n\t  GTIFKeySet (ogtif, GeogSemiMajorAxisGeoKey, TYPE_DOUBLE, 1,\n\t\t      md->projection->re_major);\n\t  GTIFKeySet (ogtif, GeogInvFlatteningGeoKey, TYPE_DOUBLE, 1, 0.0);\n\t  \n\t  /* Set the citation key.  */\n\t  //char datum_str[256];\n\t  //datum_2_string (datum_str, md->projection->datum);\n\t  citation = MALLOC ((max_citation_length + 1) * sizeof (char));\n\t  snprintf (citation, max_citation_length + 1,\n\t\t    \"Sinusoidal projected GeoTIFF using \"\n\t\t    \"sphere written by Alaska Satellite \"\n\t\t    \"Facility tools.\");\n\t  append_band_names(band_names, rgb, citation, palette_color_tiff);\n\t  citation_length = strlen(citation);\n\t  asfRequire (citation_length >= 0 &&\n\t\t      citation_length <= max_citation_length,\n\t\t      \"bad citation length\");\n\t  GTIFKeySet (ogtif, PCSCitationGeoKey, TYPE_ASCII, 1, citation);\n\t  GTIFKeySet (ogtif, GTCitationGeoKey, TYPE_ASCII, 1, citation);\n\t  free (citation);\n\t}\n\tbreak;\n      case LAT_LONG_PSEUDO_PROJECTION:\n        {\n\t  write_datum_key(ogtif, md->projection->datum);\n\t  write_spheroid_key(ogtif, md->projection->spheroid, re_major, re_minor);\n\t}\n\tbreak;\n      default:\n        asfPrintWarning (\"Unsupported map projection found.  TIFF file will not\\n\"\n            \"contain projection information.\\n\");\n\tfree(citation);\n        break;\n    }\n  }\n\n  // NOTE: GTIFWriteKeys() must be called to finalize the writing of geokeys\n  // to the GeoTIFF file ...see finalize_tiff_file() ...do not insert a call\n  // to GTIFWriteKeys() here plz.\n\n  meta_free (md);\n\n  return ogtif;\n}\n\nvoid finalize_tiff_file(TIFF *otif, GTIF *ogtif, int is_geotiff)\n{\n  // Finalize the GeoTIFF\n  if (is_geotiff && ogtif != NULL) {\n    int ret;\n\n    ret = GTIFWriteKeys (ogtif);\n    asfRequire (ret, \"Error writing GeoTIFF keys.\\n\");\n    GTIFFree (ogtif);\n  }\n\n  // Finalize the TIFF file\n  if (otif != NULL) {\n    XTIFFClose (otif);\n  }\n}\n\nvoid finalize_jpeg_file(FILE *ojpeg, struct jpeg_compress_struct *cinfo)\n{\n  jpeg_finish_compress (cinfo);\n  FCLOSE (ojpeg);\n  jpeg_destroy_compress (cinfo);\n}\n\nvoid finalize_png_file(FILE *opng, png_structp png_ptr, png_infop info_ptr)\n{\n    png_write_end(png_ptr, NULL);\n    png_destroy_write_struct(&png_ptr, &info_ptr);\n    FCLOSE(opng);\n}\n\nvoid finalize_ppm_file(FILE *oppm)\n{\n  FCLOSE(oppm);\n}\n\n// Function to determine whether the output image will be a multiband but not RGB image\nint multiband(char *format, char **band_name, int band_count)\n{\n  int ii, nBands=0;\n\n  if (strcmp_case(format, \"HDF5\") != 0 && \n      strcmp_case(format, \"netCDF\") != 0)\n    return FALSE;\n\n  for (ii=0; ii<band_count; ii++) {\n    if (band_name[ii] && strlen(band_name[ii]) > 0)\n      nBands++;\n    else\n      break;\n  }\n  if (nBands > 1) \n    return TRUE;\n  else\n    return FALSE;\n}\n\nvoid\nexport_band_image (const char *metadata_file_name,\n                   const char *image_data_file_name,\n                   char *output_file_name,\n                   scale_t sample_mapping,\n                   char **band_name, int rgb,\n                   int true_color, int false_color,\n                   char *look_up_table_name,\n                   output_format_t format,\n                   int *noutputs,\n                   char ***output_names)\n{\n  int map_projected;\n  int is_geotiff = 1;\n  TIFF *otif = NULL; // FILE* pointer for TIFF files\n  GTIF *ogtif = NULL;\n  FILE *ojpeg = NULL, *opgm=NULL, *opng=NULL, *ofp=NULL;\n  struct jpeg_compress_struct cinfo;\n  png_structp png_ptr;\n  png_infop png_info_ptr;\n  h5_t *h5=NULL;\n  netcdf_t *netcdf=NULL;\n  float *nc = NULL;\n  float *hdf = NULL;\n  int ii,jj;\n  int palette_color_tiff = 0;\n  int have_look_up_table = look_up_table_name && strlen(look_up_table_name)>0;\n  char *lut_file = NULL;\n\n  meta_parameters *md = meta_read (metadata_file_name);\n  map_projected = is_map_projected(md);\n\n  if (format == PNG_GE)\n    meta_write(md, output_file_name);\n\n  if (format == HDF && rgb)\n    asfPrintError(\"Export to a color HDF format is not supported!\\n\");\n  else if (format == NC && rgb)\n    asfPrintError(\"Export to a color netCDF format is not supported!\\n\");\n\n  if (md->general->image_data_type >= POLARIMETRIC_C2_MATRIX &&\n      md->general->image_data_type <= POLARIMETRIC_T4_MATRIX &&\n      md->general->image_data_type != POLARIMETRIC_DECOMPOSITION &&\n      format == POLSARPRO_HDR)\n    append_ext_if_needed(output_file_name, \".bin\", NULL);\n\n  asfRequire( !(look_up_table_name == NULL &&\n                sample_mapping == TRUNCATE &&\n                (md->general->radiometry == r_SIGMA ||\n                 md->general->radiometry == r_BETA  ||\n                 md->general->radiometry == r_GAMMA)\n               ),\n              \"Downsampling a Sigma, Beta, or Gamma type image (power or dB)\\n\"\n              \"from floating point to byte using truncation is not supported.\\n\"\n              \"All values would map to black.\\n\");\n  if (md->general->data_type == BYTE &&\n      sample_mapping != TRUNCATE && sample_mapping != NONE &&\n      md->general->image_data_type != BROWSE_IMAGE)\n  {\n      asfPrintWarning(\"Using %s sample remapping on BYTE data will result in\\n\"\n                      \"contrast expansion.  If you do not want contrast expansion in\\n\"\n                      \"your exported file, then you need to select either TRUNCATE or\\n\"\n                      \"NONE for your sample remapping type.\\n\",\n                      sample_mapping2string(sample_mapping));\n  }\n\n  if (md->general->band_count < 1 || md->general->band_count > MAX_BANDS) {\n    asfPrintError (\"Unsupported number of channels found (%d).  Only 1 through\\n\"\n        \"%d channels are supported.\\n\", md->general->band_count, MAX_BANDS);\n  }\n\n  if (format == PGM && look_up_table_name != NULL && strlen(look_up_table_name) > 0) {\n    asfPrintWarning(\"Cannot apply look up table to PGM format output files since\\n\"\n        \"color is not supported ...Ignoring the look up table and continuing.\\n\");\n    have_look_up_table = 0;\n  }\n\n  // NOTE: if the truecolorFlag or falsecolorFlag was set, then 'rgb' is true\n  // and the band assignments are in the band_name[] array already.  The true_color\n  // and false_color parameters are provided separately just in case we decide\n  // to do anything different, e.g. normal rgb processing plus something specific\n  // to true_color or false_color (like contrast expansion)\n  if (strstr(uc(md->general->bands), \"POLSARPRO\") != NULL && format == PGM) {\n    asfPrintWarning(\n        \"Using PGM output for an image containing a PolSARpro classification\\n\"\n        \"band will result in separate greyscale images, and the PolSARpro classification\\n\"\n        \"will appear very DARK since all values in the image are small integers.  It is\\n\"\n        \"best to use a viewer that can apply the appropriate classification look-up table\\n\"\n        \"to the image, i.e. asf_view, a part of the ASF tool set.\\n\");\n  }\n\n  if (have_look_up_table) {\n    lut_file = STRDUP(look_up_table_name);\n  }\n  else {\n    // No look-up table\n    lut_file = (char*)CALLOC(256, sizeof(char)); // Empty string\n    if (format != PGM) {\n      if (md->colormap) {\n        // No look up table was provided for colormapped output ...Use the embedded\n        // colormap that is in the metadata\n        strcpy(lut_file, \"tmp_lut_file.lut\");\n        colormap_to_lut_file(md->colormap, lut_file);\n        have_look_up_table = TRUE;\n        asfPrintStatus(\"\\nUsing the colormap embedded in the ASF metadata (%s).\\n\"\n            \"for applicable bands.\\n\\n\",\n            md->colormap->look_up_table);\n      }\n    }\n  }\n\n  if (rgb && !have_look_up_table) {\n    // Initialize the selected format\n    if (format == TIF) {\n      is_geotiff = 0;\n      initialize_tiff_file(&otif, &ogtif, output_file_name,\n         metadata_file_name, is_geotiff,\n         sample_mapping, rgb, &palette_color_tiff, band_name, lut_file, 0);\n    }\n    else if (format == GEOTIFF) {\n      initialize_tiff_file(&otif, &ogtif, output_file_name,\n         metadata_file_name, is_geotiff,\n         sample_mapping, rgb, &palette_color_tiff, band_name, lut_file, 0);\n    }\n    else if (format == JPEG) {\n      initialize_jpeg_file(output_file_name, md, &ojpeg, &cinfo, rgb);\n    }\n    else if (format == PNG) {\n      initialize_png_file(output_file_name, md, &opng, &png_ptr,\n          &png_info_ptr, rgb);\n    }\n    else if (format == PNG_ALPHA) {\n      initialize_png_file_ext(output_file_name, md, &opng, &png_ptr,\n\t\t\t      &png_info_ptr, rgb, TRUE);\n    }\n    else if (format == PNG_GE) {\n      initialize_png_file_ext(output_file_name, md, &opng, &png_ptr,\n\t\t\t      &png_info_ptr, rgb, 2);\n    }\n    int ignored[4] = {0, 0, 0, 0};\n    int red_channel=-1, green_channel=-1, blue_channel=-1;\n    for (ii = 0; ii < 4; ii++) {\n        if (ii < md->general->band_count) {\n            ignored[ii] = strncmp(\"IGNORE\", uc(band_name[ii]), 6) == 0 ? 1 : 0;\n        }\n        else {\n            // Ignore bands that exceed band count\n            ignored[ii] = 1;\n        }\n    }\n    red_channel = get_band_number(md->general->bands,\n                                  md->general->band_count,\n                                  band_name[0]);\n    if (!ignored[0] && !(red_channel >= 0 && red_channel < MAX_BANDS)) {\n      asfPrintError(\"Band number (%d) out of range for %s channel.\\n\",\n                    red_channel, \"red\");\n    }\n    green_channel = get_band_number(md->general->bands,\n                                    md->general->band_count,\n                                    band_name[1]);\n    if (!ignored[1] && !(green_channel >= 0 && green_channel < MAX_BANDS)) {\n      asfPrintError(\"Band number (%d) out of range for %s channel.\\n\",\n                    green_channel, \"green\");\n    }\n    blue_channel = get_band_number(md->general->bands,\n                                   md->general->band_count,\n                                   band_name[2]);\n    if (!ignored[2] && !(blue_channel >= 0 && blue_channel < MAX_BANDS)) {\n      asfPrintError(\"Band number (%d) out of range for %s channel.\\n\",\n                    blue_channel, \"blue\");\n    }\n\n    channel_stats_t red_stats, blue_stats, green_stats;\n    red_stats.hist = NULL; red_stats.hist_pdf = NULL;\n    green_stats.hist = NULL; green_stats.hist_pdf = NULL;\n    blue_stats.hist = NULL; blue_stats.hist_pdf = NULL;\n\n    if (!md->optical) {\n      asfRequire (sizeof(unsigned char) == 1,\n                  \"Size of the unsigned char data type on this machine is \"\n                  \"different than expected.\\n\");\n\n        /*** Normal straight per-channel stats (no combined-band stats) */\n\n        // Red channel statistics\n        if (!ignored[red_channel]                           &&  // Non-blank band\n            sample_mapping != NONE                          &&  // Float-to-byte resampling needed\n            sample_mapping != HISTOGRAM_EQUALIZE            &&  // A histogram is not needed\n            md->stats      != NULL                          &&  // Stats exist and are valid\n            md->stats       > 0                             &&\n            meta_is_valid_string(band_name[0])              &&  // Band name exists and is valid\n            strlen(band_name[0]) > 0)\n        {\n          // If the stats already exist, then use them\n          int band_no = get_band_number(md->general->bands,\n                                        md->general->band_count,\n                                        band_name[0]);\n          red_stats.min  = md->stats->band_stats[band_no].min;\n          red_stats.max  = md->stats->band_stats[band_no].max;\n          red_stats.mean = md->stats->band_stats[band_no].mean;\n          red_stats.standard_deviation = md->stats->band_stats[band_no].std_deviation;\n          red_stats.hist     = NULL;\n          red_stats.hist_pdf = NULL;\n          if (sample_mapping == SIGMA) {\n            double omin = red_stats.mean - 2*red_stats.standard_deviation;\n            double omax = red_stats.mean + 2*red_stats.standard_deviation;\n            if (omin > red_stats.min) red_stats.min = omin;\n            if (omax < red_stats.max) red_stats.max = omax;\n          }\n\t  else if (sample_mapping == MINMAX_MEDIAN)\n\t    calc_minmax_median(image_data_file_name, band_name[0], \n\t\t\t       md->general->no_data, \n\t\t\t       &red_stats.min, &red_stats.max);\n        }\n        else {\n          // Calculate the stats if you have to...\n          if (sample_mapping != NONE && !ignored[red_channel]) { // byte image\n            asfPrintStatus(\"\\nGathering red channel statistics ...\\n\");\n            calc_stats_from_file(image_data_file_name, band_name[0],\n                                md->general->no_data,\n                                &red_stats.min, &red_stats.max, &red_stats.mean,\n                                &red_stats.standard_deviation, &red_stats.hist);\n            if (sample_mapping == SIGMA) {\n              double omin = red_stats.mean - 2*red_stats.standard_deviation;\n              double omax = red_stats.mean + 2*red_stats.standard_deviation;\n              if (omin > red_stats.min) red_stats.min = omin;\n              if (omax < red_stats.max) red_stats.max = omax;\n            }\n            else if ( sample_mapping == HISTOGRAM_EQUALIZE ) {\n              red_stats.hist_pdf = gsl_histogram_pdf_alloc (256);\n              gsl_histogram_pdf_init (red_stats.hist_pdf, red_stats.hist);\n            }\n\t    else if (sample_mapping == MINMAX_MEDIAN)\n\t      calc_minmax_median(image_data_file_name, band_name[0], \n\t\t\t\t md->general->no_data, \n\t\t\t\t &red_stats.min, &red_stats.max);\n          }\n        }\n\n        // Green channel statistics\n        if (!ignored[green_channel]                          &&  // Non-blank band\n             sample_mapping != NONE                          &&  // Float-to-byte resampling needed\n             sample_mapping != HISTOGRAM_EQUALIZE            &&  // A histogram is not needed\n             md->stats      != NULL                          &&  // Stats exist and are valid\n             md->stats       > 0                             &&\n             meta_is_valid_string(band_name[1])              &&  // Band name exists and is valid\n             strlen(band_name[1]) > 0)\n        {\n          // If the stats already exist, then use them\n          int band_no = get_band_number(md->general->bands,\n                                        md->general->band_count,\n                                        band_name[1]);\n          green_stats.min  = md->stats->band_stats[band_no].min;\n          green_stats.max  = md->stats->band_stats[band_no].max;\n          green_stats.mean = md->stats->band_stats[band_no].mean;\n          green_stats.standard_deviation = md->stats->band_stats[band_no].std_deviation;\n          green_stats.hist     = NULL;\n          green_stats.hist_pdf = NULL;\n          if (sample_mapping == SIGMA) {\n            double omin = green_stats.mean - 2*green_stats.standard_deviation;\n            double omax = green_stats.mean + 2*green_stats.standard_deviation;\n            if (omin > green_stats.min) green_stats.min = omin;\n            if (omax < green_stats.max) green_stats.max = omax;\n          }\n\t  else if (sample_mapping == MINMAX_MEDIAN)\n\t    calc_minmax_median(image_data_file_name, band_name[1], \n\t\t\t       md->general->no_data, \n\t\t\t       &green_stats.min, &green_stats.max);\n        }\n        else {\n          // Calculate the stats if you have to...\n          if (sample_mapping != NONE && !ignored[green_channel]) { // byte image\n            asfPrintStatus(\"\\nGathering green channel statistics ...\\n\");\n            calc_stats_from_file(image_data_file_name, band_name[1],\n                                md->general->no_data,\n                                &green_stats.min, &green_stats.max,\n                                &green_stats.mean,\n                                &green_stats.standard_deviation,\n                                &green_stats.hist);\n            if (sample_mapping == SIGMA) {\n              double omin = green_stats.mean - 2*green_stats.standard_deviation;\n              double omax = green_stats.mean + 2*green_stats.standard_deviation;\n              if (omin > green_stats.min) green_stats.min = omin;\n              if (omax < green_stats.max) green_stats.max = omax;\n            }\n            else if ( sample_mapping == HISTOGRAM_EQUALIZE ) {\n              green_stats.hist_pdf = gsl_histogram_pdf_alloc(256);\n              gsl_histogram_pdf_init (green_stats.hist_pdf, green_stats.hist);\n            }\n\t    else if (sample_mapping == MINMAX_MEDIAN)\n\t      calc_minmax_median(image_data_file_name, band_name[1], \n\t\t\t\t md->general->no_data, \n\t\t\t\t &green_stats.min, &green_stats.max);\n          }\n        }\n\n        // Blue channel statistics\n        if (!ignored[blue_channel]                          &&  // Non-blank band\n             sample_mapping != NONE                         &&  // Float-to-byte resampling needed\n             sample_mapping != HISTOGRAM_EQUALIZE           &&  // A histogram is not needed\n             md->stats      != NULL                         &&  // Stats exist and are valid\n             md->stats       > 0                            &&\n             meta_is_valid_string(band_name[2])             &&  // Band name exists and is valid\n             strlen(band_name[2]) > 0)\n        {\n          // If the stats already exist, then use them\n          int band_no = get_band_number(md->general->bands,\n                                        md->general->band_count,\n                                        band_name[2]);\n          blue_stats.min  = md->stats->band_stats[band_no].min;\n          blue_stats.max  = md->stats->band_stats[band_no].max;\n          blue_stats.mean = md->stats->band_stats[band_no].mean;\n          blue_stats.standard_deviation = md->stats->band_stats[band_no].std_deviation;\n          blue_stats.hist     = NULL;\n          blue_stats.hist_pdf = NULL;\n          if (sample_mapping == SIGMA) {\n            double omin = blue_stats.mean - 2*blue_stats.standard_deviation;\n            double omax = blue_stats.mean + 2*blue_stats.standard_deviation;\n            if (omin > blue_stats.min) blue_stats.min = omin;\n            if (omax < blue_stats.max) blue_stats.max = omax;\n          }\n\t  else if (sample_mapping == MINMAX_MEDIAN)\n\t    calc_minmax_median(image_data_file_name, band_name[2], \n\t\t\t       md->general->no_data, \n\t\t\t       &blue_stats.min, &blue_stats.max);\n        }\n        else {\n          // Calculate the stats if you have to...\n          if (sample_mapping != NONE && !ignored[blue_channel]) { // byte image\n            asfPrintStatus(\"\\nGathering blue channel statistics ...\\n\");\n            calc_stats_from_file(image_data_file_name, band_name[2],\n                                md->general->no_data,\n                                &blue_stats.min, &blue_stats.max,\n                                &blue_stats.mean,\n                                &blue_stats.standard_deviation,\n                                &blue_stats.hist);\n            if (sample_mapping == SIGMA) {\n              double omin = blue_stats.mean - 2*blue_stats.standard_deviation;\n              double omax = blue_stats.mean + 2*blue_stats.standard_deviation;\n              if (omin > blue_stats.min) blue_stats.min = omin;\n              if (omax < blue_stats.max) blue_stats.max = omax;\n            }\n            else if ( sample_mapping == HISTOGRAM_EQUALIZE ) {\n              blue_stats.hist_pdf = gsl_histogram_pdf_alloc (256);\n              gsl_histogram_pdf_init (blue_stats.hist_pdf, blue_stats.hist);\n            }\n\t    else if (sample_mapping == MINMAX_MEDIAN)\n\t      calc_minmax_median(image_data_file_name, band_name[2], \n\t\t\t\t md->general->no_data, \n\t\t\t\t &blue_stats.min, &blue_stats.max);\n          }\n        }\n    }\n\n    float *red_float_line = NULL;\n    float *green_float_line = NULL;\n    float *blue_float_line = NULL;\n\n    unsigned char *red_byte_line = NULL;\n    unsigned char *green_byte_line = NULL;\n    unsigned char *blue_byte_line = NULL;\n\n    // Write the data to the file\n    FILE *fp = FOPEN(image_data_file_name, \"rb\");\n\n    int sample_count = md->general->sample_count;\n    int offset = md->general->line_count;\n\n    // Allocate some memory\n    if (md->optical || md->general->data_type == BYTE) {\n      if (ignored[red_channel])\n        red_byte_line = (unsigned char *) CALLOC(sample_count, sizeof(char));\n      else\n        red_byte_line = (unsigned char *) MALLOC(sample_count * sizeof(char));\n\n      if (ignored[green_channel])\n        green_byte_line = (unsigned char *) CALLOC(sample_count, sizeof(char));\n      else\n        green_byte_line = (unsigned char *) MALLOC(sample_count * sizeof(char));\n\n      if (ignored[blue_channel])\n        blue_byte_line = (unsigned char *) CALLOC(sample_count, sizeof(char));\n      else\n        blue_byte_line = (unsigned char *) MALLOC(sample_count * sizeof(char));\n    }\n    else {\n      // Not optical data\n      red_float_line = (float *) MALLOC(sample_count * sizeof(float));\n      if (ignored[red_channel]){\n        for (ii=0; ii<sample_count; ++ii) {\n          red_float_line[ii] = md->general->no_data;\n        }\n      }\n\n      green_float_line = (float *) MALLOC(sample_count * sizeof(float));\n      if (ignored[green_channel]) {\n        for (ii=0; ii<sample_count; ++ii) {\n          green_float_line[ii] = md->general->no_data;\n        }\n      }\n\n      blue_float_line = (float *) MALLOC(sample_count * sizeof(float));\n      if (ignored[blue_channel]) {\n        for (ii=0; ii<sample_count; ++ii) {\n          blue_float_line[ii] = md->general->no_data;\n        }\n      }\n    }\n\n    double r_omin=0, r_omax=0;\n    double g_omin=0, g_omax=0;\n    double b_omin=0, b_omax=0;\n\n    if (md->optical && (true_color || false_color)) {\n      // NOTE: Using the stats from the metadata, if available, is only valid\n      // if no histogram is necessary, else one must be generated via the\n      // stats functions.  If true_color or false_color are selected, then sample_mapping\n      // should NOT be HISTOGRAM_EQUALIZE in particular and should always be set\n      // to SIGMA\n      if (sample_mapping == NONE && (true_color || false_color)) {\n          sample_mapping = SIGMA;\n      }\n      if (sample_mapping != SIGMA) {\n        asfPrintWarning(\"Cannot combine true or false color options with sample mappings\\n\"\n            \"other than 2-sigma.  You selected %s.  Defaulting to 2-sigma...\\n\",\n            sample_mapping == TRUNCATE ? \"TRUNCATE\" :\n            sample_mapping == MINMAX ? \"MINMAX\" :\n            sample_mapping == HISTOGRAM_EQUALIZE ? \"HISTOGRAM_EQUALIZE\" :\n            \"UNKNOWN or INVALID\");\n      }\n\n      asfPrintStatus(\"\\nSampling color channels for 2-sigma contrast-expanded %s output...\\n\",\n                     true_color ? \"True Color\" : false_color ? \"False Color\" : \"Unknown\");\n\n      // Set up red resampling\n      if (md->stats                                     &&\n          md->stats->band_count >= 3                    &&\n          meta_is_valid_string(band_name[0])            &&\n          strlen(band_name[0]) > 0                      &&\n          sample_mapping != HISTOGRAM_EQUALIZE)\n      {\n          // If the stats already exist, then use them\n        int band_no = get_band_number(md->general->bands,\n                                      md->general->band_count,\n                                      band_name[0]);\n        red_stats.min  = md->stats->band_stats[band_no].min;\n        red_stats.max  = md->stats->band_stats[band_no].max;\n        red_stats.mean = md->stats->band_stats[band_no].mean;\n        red_stats.standard_deviation = md->stats->band_stats[band_no].std_deviation;\n        red_stats.hist     = NULL;\n        red_stats.hist_pdf = NULL;\n      }\n      else {\n        asfPrintStatus(\"\\nGathering red channel statistics...\\n\");\n        calc_stats_from_file(image_data_file_name, band_name[0],\n                             md->general->no_data,\n                             &red_stats.min, &red_stats.max, &red_stats.mean,\n                             &red_stats.standard_deviation, &red_stats.hist);\n      }\n      r_omin = red_stats.mean - 2*red_stats.standard_deviation;\n      r_omax = red_stats.mean + 2*red_stats.standard_deviation;\n      if (r_omin < red_stats.min) r_omin = red_stats.min;\n      if (r_omax > red_stats.max) r_omax = red_stats.max;\n\n      // Set up green resampling\n      if (md->stats                                       &&\n          md->stats->band_count >= 3                      &&\n          meta_is_valid_string(band_name[1])              &&\n          strlen(band_name[1]) > 0                        &&\n          sample_mapping != HISTOGRAM_EQUALIZE)\n      {\n        // If the stats already exist, then use them\n        int band_no = get_band_number(md->general->bands,\n                                      md->general->band_count,\n                                      band_name[1]);\n        green_stats.min  = md->stats->band_stats[band_no].min;\n        green_stats.max  = md->stats->band_stats[band_no].max;\n        green_stats.mean = md->stats->band_stats[band_no].mean;\n        green_stats.standard_deviation = md->stats->band_stats[band_no].std_deviation;\n        green_stats.hist     = NULL;\n        green_stats.hist_pdf = NULL;\n      }\n      else {\n        asfPrintStatus(\"\\nGathering green channel statistics...\\n\");\n        calc_stats_from_file(image_data_file_name, band_name[1],\n                              md->general->no_data,\n                              &green_stats.min, &green_stats.max, &green_stats.mean,\n                              &green_stats.standard_deviation, &green_stats.hist);\n      }\n      g_omin = green_stats.mean - 2*green_stats.standard_deviation;\n      g_omax = green_stats.mean + 2*green_stats.standard_deviation;\n      if (g_omin < green_stats.min) g_omin = green_stats.min;\n      if (g_omax > green_stats.max) g_omax = green_stats.max;\n\n      // Set up blue resampling\n      if (md->stats                                      &&\n          md->stats->band_count >= 3                     &&\n          meta_is_valid_string(band_name[2])             &&\n          strlen(band_name[2]) > 0                       &&\n          sample_mapping != HISTOGRAM_EQUALIZE)\n      {\n        // If the stats already exist, then use them\n        int band_no = get_band_number(md->general->bands,\n                                      md->general->band_count,\n                                      band_name[2]);\n        blue_stats.min  = md->stats->band_stats[band_no].min;\n        blue_stats.max  = md->stats->band_stats[band_no].max;\n        blue_stats.mean = md->stats->band_stats[band_no].mean;\n        blue_stats.standard_deviation = md->stats->band_stats[band_no].std_deviation;\n        blue_stats.hist     = NULL;\n        blue_stats.hist_pdf = NULL;\n      }\n      else {\n        asfPrintStatus(\"\\nGathering blue channel statistics...\\n\\n\");\n        calc_stats_from_file(image_data_file_name, band_name[2],\n                             md->general->no_data,\n                             &blue_stats.min, &blue_stats.max, &blue_stats.mean,\n                             &blue_stats.standard_deviation, &blue_stats.hist);\n      }\n      b_omin = blue_stats.mean - 2*blue_stats.standard_deviation;\n      b_omax = blue_stats.mean + 2*blue_stats.standard_deviation;\n      if (b_omin < blue_stats.min) b_omin = blue_stats.min;\n      if (b_omax > blue_stats.max) b_omax = blue_stats.max;\n\n      asfPrintStatus(\"Applying 2-sigma contrast expansion to color bands...\\n\\n\");\n    }\n\n    for (ii=0; ii<md->general->line_count; ii++) {\n      if (md->optical || md->general->data_type == BYTE) {\n        // Optical images come as byte in the first place\n        if (!ignored[red_channel])\n          get_byte_line(fp, md, ii+red_channel*offset, red_byte_line);\n        if (!ignored[green_channel])\n          get_byte_line(fp, md, ii+green_channel*offset, green_byte_line);\n        if (!ignored[blue_channel])\n          get_byte_line(fp, md, ii+blue_channel*offset, blue_byte_line);\n        // If true or false color flag was set, then (re)sample with 2-sigma\n        // contrast expansion\n        if (true_color || false_color) {\n          for (jj=0; jj<sample_count; jj++) {\n            red_byte_line[jj] =\n                pixel_float2byte((float)red_byte_line[jj], SIGMA,\n                                  r_omin, r_omax,\n                                  red_stats.hist, red_stats.hist_pdf, NAN);\n            green_byte_line[jj] =\n                pixel_float2byte((float)green_byte_line[jj], SIGMA,\n                                  g_omin, g_omax,\n                                  green_stats.hist, green_stats.hist_pdf, NAN);\n            blue_byte_line[jj] =\n                pixel_float2byte((float)blue_byte_line[jj], SIGMA,\n                                  b_omin, b_omax,\n                                  blue_stats.hist, blue_stats.hist_pdf, NAN);\n          }\n        }\n        if (format == TIF || format == GEOTIFF)\n          write_rgb_tiff_byte2byte(otif, red_byte_line, green_byte_line,\n                                   blue_byte_line, ii, sample_count);\n        else if (format == JPEG)\n          write_rgb_jpeg_byte2byte(ojpeg, red_byte_line, green_byte_line,\n                                   blue_byte_line, &cinfo, sample_count);\n        else if (format == PNG || format == PNG_ALPHA || format == PNG_GE)\n          write_rgb_png_byte2byte(opng, red_byte_line, green_byte_line,\n                                  blue_byte_line, png_ptr, png_info_ptr,\n                                  sample_count);\n        else\n          asfPrintError(\"Impossible: unexpected format %s\\n\", format2str(format));\n      }\n      else if (sample_mapping == NONE) {\n        // Write float->float lines if float image\n        if (!ignored[red_channel])\n          get_float_line(fp, md, ii+red_channel*offset, red_float_line);\n        if (!ignored[green_channel])\n          get_float_line(fp, md, ii+green_channel*offset, green_float_line);\n        if (!ignored[blue_channel])\n          get_float_line(fp, md, ii+blue_channel*offset, blue_float_line);\n        if (format == GEOTIFF || format == TIF)\n          write_rgb_tiff_float2float(otif, red_float_line, green_float_line,\n                                     blue_float_line, ii, sample_count);\n        else\n          asfPrintError(\"Impossible: unexpected format %s\\n\", format2str(format));\n      }\n      else {\n        // Write float->byte lines if byte image\n        if (!ignored[red_channel])\n          get_float_line(fp, md, ii+red_channel*offset, red_float_line);\n        if (!ignored[green_channel])\n          get_float_line(fp, md, ii+green_channel*offset, green_float_line);\n        if (!ignored[blue_channel])\n          get_float_line(fp, md, ii+blue_channel*offset, blue_float_line);\n        if (format == TIF || format == GEOTIFF)\n          write_rgb_tiff_float2byte(otif, red_float_line, green_float_line,\n                                    blue_float_line, red_stats, green_stats,\n                                    blue_stats, sample_mapping,\n                                    md->general->no_data, ii, sample_count);\n        else if (format == JPEG)\n          write_rgb_jpeg_float2byte(ojpeg, red_float_line, green_float_line,\n                                    blue_float_line, &cinfo, red_stats,\n                                    green_stats, blue_stats, sample_mapping,\n                                    md->general->no_data, sample_count);\n        else if (format == PNG || format == PNG_ALPHA || format == PNG_GE)\n          write_rgb_png_float2byte(opng, red_float_line, green_float_line,\n                                   blue_float_line, png_ptr, png_info_ptr,\n                                   red_stats, green_stats, blue_stats,\n                                   sample_mapping, md->general->no_data,\n                                   sample_count);\n        else\n          asfPrintError(\"Impossible: unexpected format %s\\n\", format2str(format));\n      }\n\n      asfLineMeter(ii, md->general->line_count);\n    }\n\n    // Free memory\n    FREE(red_byte_line);\n    FREE(green_byte_line);\n    FREE(blue_byte_line);\n    FREE(red_float_line);\n    FREE(green_float_line);\n    FREE(blue_float_line);\n\n    // Finalize the chosen format\n    if (format == TIF || format == GEOTIFF)\n      finalize_tiff_file(otif, ogtif, is_geotiff);\n    else if (format == JPEG)\n      finalize_jpeg_file(ojpeg, &cinfo);\n    else if (format == PNG || format == PNG_ALPHA || format == PNG_GE)\n      finalize_png_file(opng, png_ptr, png_info_ptr);\n    else\n      asfPrintError(\"Impossible: unexpected format %s\\n\", format2str(format));\n\n    if (red_stats.hist) gsl_histogram_free(red_stats.hist);\n    if (red_stats.hist_pdf) gsl_histogram_pdf_free(red_stats.hist_pdf);\n    if (green_stats.hist) gsl_histogram_free(green_stats.hist);\n    if (green_stats.hist_pdf) gsl_histogram_pdf_free(green_stats.hist_pdf);\n    if (blue_stats.hist) gsl_histogram_free(blue_stats.hist);\n    if (blue_stats.hist_pdf) gsl_histogram_pdf_free(blue_stats.hist_pdf);\n\n    FCLOSE(fp);\n\n    // set the output filename\n    *noutputs = 1;\n    char **outs = MALLOC(sizeof(char*));\n    outs[0] = STRDUP(output_file_name);\n    *output_names = outs;\n  }\n  else if (multiband(format2str(format), band_name, md->general->band_count)) {\n    // Multi-band image output (but no RGB)\n    // This can currently only be the case for HDF5 and netCDF data\n    hid_t h5_data;\n\n    if (format == HDF) {\n      append_ext_if_needed(output_file_name, \".h5\", NULL);\n      h5 = initialize_h5_file(output_file_name, md);\n      hdf = (float *) \n\tMALLOC(sizeof(float)*md->general->line_count*md->general->sample_count);\n    }\n    else if (format == NC) {\n      append_ext_if_needed(output_file_name, \".nc\", NULL);\n      netcdf = initialize_netcdf_file(output_file_name, md);\n      nc = (float *)\n\tMALLOC(sizeof(float)*md->general->line_count*md->general->sample_count);    }\n\n    int kk, channel;\n    int band_count = md->general->band_count;\n    int sample_count = md->general->sample_count;\n    int offset = md->general->line_count;\n    FILE *fp = FOPEN(image_data_file_name, \"rb\");\n    float *float_line = (float *) MALLOC(sizeof(float) * sample_count);\n    for (kk=0; kk<band_count; kk++) {\n      for (ii=0; ii<md->general->line_count; ii++ ) {\n\tchannel = get_band_number(md->general->bands, band_count, band_name[kk]);\n\tget_float_line(fp, md, ii+channel*offset, float_line);\n\tif (format == HDF) {\n\t  int sample;\n\t  for (sample=0; sample<sample_count; sample++)\n\t    hdf[ii*sample_count+sample] = float_line[sample];\n\t}\n\telse if (format == NC) {\n\t  int sample;\n\t  for (sample=0; sample<sample_count; sample++) {\n\t    nc[ii*sample_count+sample] = float_line[sample];\n\t  }\n\t}\n\tasfLineMeter(ii, md->general->line_count);\n      }\n      if (format == HDF) {\n\tasfPrintStatus(\"Storing band '%s' ...\\n\", band_name[kk]);\n\tchar dataset[50];\n\tsprintf(dataset, \"/data/%s_AMPLITUDE_IMAGE\", band_name[kk]);\n\th5_data = H5Dopen(h5->file, dataset, H5P_DEFAULT);\n\tH5Dwrite(h5_data, H5T_NATIVE_FLOAT, H5S_ALL, H5S_ALL, \n\t\t H5P_DEFAULT, hdf);\n\tH5Dclose(h5_data);\n      }\n      else if (format == NC) {\n\tasfPrintStatus(\"Storing band '%s' ...\\n\", band_name[kk]);\n\tnc_put_var_float(netcdf->ncid, netcdf->var_id[kk], &nc[0]);\n      }\n    }\n\n    if (format == HDF) {\n      finalize_h5_file(h5);\n      FREE(hdf);\n    }\n    else if (format == NC) {\n      finalize_netcdf_file(netcdf, md);\n      FREE(nc);\n    }\n    else\n      asfPrintError(\"Impossible: unexpected format %s\\n\", format2str(format));\n\n    FCLOSE(fp);\n  }\n  else {\n    // Single-band image output (one grayscale file for each available band)\n    int free_band_names=FALSE;\n    int band_count = md->general->band_count;\n    char base_name[255];\n    char *bands = (char *) MALLOC(sizeof(char)*1024);\n    strcpy(bands, md->general->bands);\n    strcpy(base_name, output_file_name);\n    char *matrix = (char *) MALLOC(sizeof(char)*5);\n    char *decomposition = (char *) MALLOC(sizeof(char)*25);\n    char *path_name = (char *) MALLOC(sizeof(char)*1024);\n    char *out_file = NULL;\n\n    if (!band_name)\n    {\n      // caller did not pass in the band names -- we will have\n      // to come up with some band names ourselves\n      if (band_count == 1) {\n        // only one band, just call it \"01\"\n        band_name = (char **) CALLOC(MAX_BANDS, sizeof(char*));\n        band_name[0] = (char*) MALLOC(sizeof(char)*100);\n        strcpy(band_name[0], \"01\");\n      }\n      else if (have_look_up_table) {\n        // when exporting a look up table, number the bands\n        band_name = (char **) CALLOC(MAX_BANDS, sizeof(char*));\n        int i;\n        for (i=0; i<3; i++) {\n          band_name[i] = (char*) MALLOC(sizeof(char)*100);\n          sprintf(band_name[i], \"%02d\", i + 1);\n        }\n      }\n      else {\n        // get what is in the metadata\n        int n;\n        char *b = stripExt(image_data_file_name);\n        band_name = find_single_band(b, \"all\", &n);\n        asfRequire (n == band_count, \"Band count inconsistent: %d != %d\\n\",\n                    n, band_count);\n        FREE(b);\n      }\n\n      // in all three cases, we must free \"band_name\"\n      // (normally not freed, it the caller's)\n      free_band_names = TRUE;\n    }\n\n    if (md->general->image_data_type >= POLARIMETRIC_C2_MATRIX &&\n\tmd->general->image_data_type <= POLARIMETRIC_T4_MATRIX) {\n      if (strstr(md->general->bands, \"C44\"))\n\tsprintf(matrix, \"C4\");\n      else if (strstr(md->general->bands, \"C33\"))\n\tsprintf(matrix, \"C3\");\n      else if (strstr(md->general->bands, \"C22\"))\n\tsprintf(matrix, \"C2\");\n      else if (strstr(md->general->bands, \"T44\"))\n\tsprintf(matrix, \"T4\");\n      else if (strstr(md->general->bands, \"T33\"))\n\tsprintf(matrix, \"T3\");\n      else if (strstr(md->general->bands, \"T22\"))\n\tsprintf(matrix, \"T2\");\n      else\n\tasfPrintError(\"The bands do not correspond to matrix type (%s)\\n\",\n\t\t      image_data_type2str(md->general->image_data_type));\n    }\n\n    // If we are dealing with polarimetric matrices, the output file name\n    // becomes the name of an output directory. We need to figure out from\n    // the bands string, what kind of matrix we have, because we need to\n    // create the appropriate subdirectory. Otherwise, PolSARPro can't handle\n    // the files out of the box.\n    if (md->general->image_data_type >= POLARIMETRIC_C2_MATRIX &&\n\tmd->general->image_data_type <= POLARIMETRIC_T4_MATRIX &&\n\tmd->general->band_count != 1 && format == POLSARPRO_HDR) {\n      char *dirName = (char *) MALLOC(sizeof(char)*1024);\n      char *fileName = (char *) MALLOC(sizeof(char)*1024);\n      split_dir_and_file(output_file_name, dirName, fileName);\n      char *path = get_dirname(output_file_name);\n      if (strlen(dirName) <= 0) {\n\tpath = g_get_current_dir();\n\tsprintf(path_name, \"%s%c%s%c%s\", \n\t\tpath, DIR_SEPARATOR, output_file_name, DIR_SEPARATOR, matrix);\n      }\n      else\n\tsprintf(path_name, \"%s%c%s%c%s\", \n\t\tdirName, DIR_SEPARATOR, fileName, DIR_SEPARATOR, matrix);\n      if (is_dir(path_name))\n\tasfPrintError(\"Output directory (%s) already exists.\\n\", path_name);\n      else if(create_dir(path_name) == -1)\n\tasfPrintError(\"Can't generate output directory (%s).\\n\", path_name);\n      char *configFile = \n\t(char *) MALLOC(sizeof(char)*(strlen(path_name)+15));\n      sprintf(configFile, \"%s%cconfig.txt\", path_name, DIR_SEPARATOR);\n      FILE *fpConfig = FOPEN(configFile, \"w\");\n      fprintf(fpConfig, \"Nrow\\n%d\\n\", md->general->line_count);\n      fprintf(fpConfig, \"---------\\nNcol\\n%d\\n\", md->general->sample_count);\n      fprintf(fpConfig, \"---------\\nPolarCase\\nmonostatic\\n\");\n      fprintf(fpConfig, \"---------\\nPolarType\\nfull\\n\");\n      FCLOSE(fpConfig);\n      FREE(configFile);\n      FREE(path);\n      FREE(dirName);\n      FREE(fileName);\n    }\n\n    if (md->general->image_data_type == POLARIMETRIC_DECOMPOSITION)\n      strcpy(decomposition, band_name[band_count-1]);\n\n    // We treat polarimetric decompositions in a similar way. The output file\n    // name becomes the name of an output directory again. The actual file\n    // names can be extracted from the bands string.\n    if (md->general->image_data_type == POLARIMETRIC_DECOMPOSITION &&\n\tmd->general->band_count != 1 && format == POLSARPRO_HDR) {\n      char *dirName = (char *) MALLOC(sizeof(char)*1024);\n      char *fileName = (char *) MALLOC(sizeof(char)*1024);\n      split_dir_and_file(output_file_name, dirName, fileName);\n      char *path = get_dirname(output_file_name);\n      if (strlen(dirName) <= 0) {\n\tpath = g_get_current_dir();\n\tsprintf(path_name, \"%s%c%s\", \n\t\tpath, DIR_SEPARATOR, output_file_name);\n      }\n      else\n\tsprintf(path_name, \"%s%c%s\", \n\t\tdirName, DIR_SEPARATOR, fileName);\n      if (is_dir(path_name))\n\tasfPrintError(\"Output directory (%s) already exists.\\n\", path_name);\n      else if(create_dir(path_name) == -1)\n\tasfPrintError(\"Can't generate output directory (%s).\\n\", path_name);\n      char *configFile = \n\t(char *) MALLOC(sizeof(char)*(strlen(path_name)+15));\n      sprintf(configFile, \"%s%cconfig.txt\", path_name, DIR_SEPARATOR);\n      FILE *fpConfig = FOPEN(configFile, \"w\");\n      fprintf(fpConfig, \"Nrow\\n%d\\n\", md->general->line_count);\n      fprintf(fpConfig, \"---------\\nNcol\\n%d\\n\", md->general->sample_count);\n      fprintf(fpConfig, \"---------\\nPolarCase\\nmonostatic\\n\");\n      fprintf(fpConfig, \"---------\\nPolarType\\nfull\\n\");\n      FCLOSE(fpConfig);\n      FREE(configFile);\n      FREE(path);\n      FREE(dirName);\n      FREE(fileName);      \n    }\n\n    // store the names of the generated files here\n    *noutputs = 0;\n    *output_names = MALLOC(sizeof(char*) * band_count);\n\n    int kk;\n    int is_colormap_band;\n\n    for (kk=0; kk<band_count; kk++) {\n      if (band_name[kk]) {\n        is_colormap_band = FALSE;\n        // two ways we can be applying a colormap to this band:\n        //  (1) the metadata has an embedded colormap, and it's band_id\n        //      is this band.\n        //  (2) user used the \"-lut\" option -- we have the !md->colormap\n        //      here to avoid thinking we've got -lut when it was really\n        //      just the md->colormap (which sets have_look_up_table, above)\n        int is_polsarpro = \n          (md->general->image_data_type == POLARIMETRIC_IMAGE || \n\t   md->general->image_data_type == POLARIMETRIC_SEGMENTATION || \n\t   md->general->image_data_type == POLARIMETRIC_DECOMPOSITION || \n\t   md->general->image_data_type == POLARIMETRIC_PARAMETER ||\n\t   (md->general->image_data_type >= POLARIMETRIC_C2_MATRIX &&\n\t    md->general->image_data_type <= POLARIMETRIC_T4_MATRIX)) ? 1 : 0;\n        if (md->general->image_data_type == POLARIMETRIC_PARAMETER &&\n\t    md->colormap)\n\t  is_colormap_band = TRUE;\n\telse if ((md->colormap && \n\t\t  strcmp_case(band_name[kk], md->colormap->band_id)==0) ||\n\t\t (!md->colormap && have_look_up_table && \n\t\t  md->general->data_type == BYTE) ||\n\t\t (!md->colormap && have_look_up_table &&\n\t\t  md->general->data_type != BYTE && sample_mapping != NONE)) {\n\t  is_colormap_band = TRUE;\n\t  sample_mapping = is_polsarpro ? TRUNCATE : sample_mapping;\n\t}\n\t// skip the 'AMP' band if we have POlSARPro data and the user wants\n\t// to apply a LUT\n\tif (strcmp_case(band_name[kk], \"AMP\") == 0 && is_polsarpro  &&\n\t    band_count > 1)\n\t  continue;\n\n        if (format == POLSARPRO_HDR) {\n          is_colormap_band = FALSE;\n          sample_mapping = NONE;\n        }\n\n        if (have_look_up_table && is_colormap_band) {\n          asfPrintStatus(\"\\nApplying %s color look up table...\\n\\n\", look_up_table_name);\n        }\n\n        out_file = (char *) MALLOC(sizeof(char)*1024);\n        strcpy(out_file, output_file_name);\n\n\t// We enforce a byte conversion using truncate for polarimetric segmentation, regardless of\n\t// applying a look up table\n\tif (md->general->image_data_type == POLARIMETRIC_SEGMENTATION &&\n\t    md->colormap)\n\t  sample_mapping = TRUNCATE;\n\n        // Initialize the selected format\n        // NOTE: For PolSARpro, the first band is amplitude and should be\n        // written out as a single-band greyscale image while the second\n        // band is a classification and should be written out as color ...\n        // and for TIFF formats, as a palette color tiff.\n        // The only exception to this rule are polarimetric matrices\n        if (md->general->image_data_type >= POLARIMETRIC_C2_MATRIX &&\n\t    md->general->image_data_type <= POLARIMETRIC_T4_MATRIX &&\n\t    md->general->band_count != 1) {\n            int ll, found_band = FALSE;\n            int band_count;\n            if (strcmp(matrix, \"T3\") == 0)\n              band_count = 9;\n            if (strcmp(matrix, \"T4\") == 0)\n              band_count = 16;\n            if (strcmp(matrix, \"C2\") == 0)\n              band_count = 4;\n            if (strcmp(matrix, \"C3\") == 0)\n              band_count = 9;\n            if (strcmp(matrix, \"C4\") == 0)\n              band_count = 16;\n            for (ll=0; ll<band_count; ll++) {\n              if (strcmp(matrix, \"T3\") == 0 && \n                strncmp(band_name[kk], t3_matrix[ll], \n                strlen(band_name[kk])) == 0)\n                found_band = TRUE;\n              else if (strcmp(matrix, \"T4\") == 0 && \n                strncmp(band_name[kk], t4_matrix[ll], \n                strlen(band_name[kk])) == 0)\n                found_band = TRUE;\n              else if (strcmp(matrix, \"C2\") == 0 && \n                strncmp(band_name[kk], c2_matrix[ll], \n                strlen(band_name[kk])) == 0)\n                found_band = TRUE;\n              else if (strcmp(matrix, \"C3\") == 0 && \n                strncmp(band_name[kk], c3_matrix[ll], \n                strlen(band_name[kk])) == 0)\n                found_band = TRUE;\n              else if (strcmp(matrix, \"C4\") == 0 && \n                strncmp(band_name[kk], c4_matrix[ll], \n                strlen(band_name[kk])) == 0)\n                found_band = TRUE;\n            }\n            if (!found_band)\n              continue;\n\t    if (format == POLSARPRO_HDR) { // output goes to directory\n\t      sprintf(out_file, \"%s%c%s\", \n\t\t      path_name, DIR_SEPARATOR, band_name[kk]);\n\t    }\n\t    else { // individual file names\n\t      if (strcmp_case(md->general->sensor, \"UAVSAR\") == 0 &&\n\t\t  strcmp_case(md->general->sensor_name, \"POLSAR\") == 0) {\n\n\t\tchar mode[5];\n\t\tif (strcmp_case(md->general->mode, \"GRD\") == 0)\n\t\t  strcpy(mode, \"grd\");\n\t\telse if (strcmp_case(md->general->mode, \"MLC\") == 0)\n\t\t  strcpy(mode, \"mlc\");\n\n\t\tif (strcmp(mode, \"grd\") == 0 || strcmp(mode, \"mlc\") == 0) { \n\t\t  if (strcmp_case(band_name[kk], \"C11\") == 0)\n\t\t    sprintf(out_file, \"%s_%sHHHH\", output_file_name, mode);\n\t\t  else if (strcmp_case(band_name[kk], \"C22\") == 0)\n\t\t    sprintf(out_file, \"%s_%sHVHV\", output_file_name, mode);\n\t\t  else if (strcmp_case(band_name[kk], \"C33\") == 0)\n\t\t    sprintf(out_file, \"%s_%sVVVV\", output_file_name, mode);\n\t\t  else if (strcmp_case(band_name[kk], \"C12_real\") == 0)\n\t\t    sprintf(out_file, \"%s_%sHHHV_real\", output_file_name, mode);\n\t\t  else if (strcmp_case(band_name[kk], \"C12_imag\") == 0)\n\t\t    sprintf(out_file, \"%s_%sHHHV_imag\", output_file_name, mode);\n\t\t  else if (strcmp_case(band_name[kk], \"C13_real\") == 0)\n\t\t    sprintf(out_file, \"%s_%sHHVV_real\", output_file_name, mode);\n\t\t  else if (strcmp_case(band_name[kk], \"C13_imag\") == 0)\n\t\t    sprintf(out_file, \"%s_%sHHVV_imag\", output_file_name, mode);\n\t\t  else if (strcmp_case(band_name[kk], \"C23_real\") == 0)\n\t\t    sprintf(out_file, \"%s_%sHVVV_real\", output_file_name, mode);\n\t\t  else if (strcmp_case(band_name[kk], \"C23_imag\") == 0)\n\t\t    sprintf(out_file, \"%s_%sHVVV_imag\", output_file_name, mode);\n\t\t}\n\t\telse if (strcmp(mode, \"hgt\") == 0)\n\t\t  sprintf(out_file, \"%s_hgt\", output_file_name);\n\t      }\n\t    }\n\t    \n\t}\n        else if (md->general->image_data_type == POLARIMETRIC_STOKES_MATRIX) {\n\t  if (strcmp_case(md->general->sensor, \"UAVSAR\") == 0 &&\n\t      strcmp_case(md->general->sensor_name, \"POLSAR\") == 0 &&\n\t      strcmp_case(md->general->mode, \"DAT\") == 0)\n\t    sprintf(out_file, \"%s_dat%s\", output_file_name, band_name[kk]);\n\t}\n\telse if (md->general->image_data_type == DEM) {\n\t  if (strcmp_case(md->general->sensor, \"UAVSAR\") == 0 &&\n\t      strcmp_case(md->general->sensor_name, \"POLSAR\") == 0 &&\n\t      strcmp_case(md->general->mode, \"HGT\") == 0) {\n\t    char *tmp = stripExt(output_file_name);\n            sprintf(out_file, \"%s_hgt.tif\", tmp);\n            FREE(tmp);\n\t  }\n\t}\n        else if (md->general->image_data_type == POLARIMETRIC_DECOMPOSITION &&\n          md->general->band_count != 1) {\n            int ll, found_band = FALSE;\n            int band_count;\n            if (strcmp(decomposition, \"Freeman2_Vol\") == 0)\n              band_count = 2;\n            else if (strcmp(decomposition, \"Freeman_Vol\") == 0)\n              band_count = 3;\n            else if (strcmp(decomposition, \"VanZyl3_Vol\") == 0)\n              band_count = 3;\n            else if (strcmp(decomposition, \"Yamaguchi3_Vol\") == 0)\n              band_count = 3;\n            else if (strcmp(decomposition, \"Yamaguchi4_Vol\") == 0)\n              band_count = 4;\n            else if (strcmp(decomposition, \"Krogager_Ks\") == 0)\n              band_count = 3;\n            else if (strcmp(decomposition, \"TSVM_alpha_s3\") == 0)\n              band_count = 3;\n            else if (strcmp(decomposition, \"TSVM_phi_s3\") == 0)\n              band_count = 3;\n            else if (strcmp(decomposition, \"TSVM_tau_m3\") == 0)\n              band_count = 3;\n            else if (strcmp(decomposition, \"TSVM_psi3\") == 0)\n              band_count = 3;\n            else if (strcmp(decomposition, \"TSVM_psi\") == 0)\n              band_count = 4;\n            for (ll=0; ll<band_count; ll++) {\n              if (strcmp(decomposition, \"Freeman2_Vol\") == 0 && \n                strncmp(band_name[kk], freeman2_decomposition[ll], \n                strlen(band_name[kk])) == 0)\n                found_band = TRUE;\n              else if (strcmp(decomposition, \"Freeman_Vol\") == 0 && \n                strncmp(band_name[kk], freeman3_decomposition[ll], \n                strlen(band_name[kk])) == 0)\n                found_band = TRUE;\n              else if (strcmp(decomposition, \"VanZyl3_Vol\") == 0 && \n                strncmp(band_name[kk], vanZyl3_decomposition[ll], \n                strlen(band_name[kk])) == 0)\n                found_band = TRUE;\n              else if (strcmp(decomposition, \"Yamaguchi3_Vol\") == 0 && \n                strncmp(band_name[kk], yamaguchi3_decomposition[ll], \n                strlen(band_name[kk])) == 0)\n                found_band = TRUE;\n              else if (strcmp(decomposition, \"Yamaguchi4_Vol\") == 0 && \n                strncmp(band_name[kk], yamaguchi4_decomposition[ll], \n                strlen(band_name[kk])) == 0)\n                found_band = TRUE;\n              else if (strcmp(decomposition, \"Krogager_Ks\") == 0 && \n                strncmp(band_name[kk], krogager_decomposition[ll], \n                strlen(band_name[kk])) == 0)\n                found_band = TRUE;\n              else if (strcmp(decomposition, \"TSVM_alpha_s3\") == 0 && \n                strncmp(band_name[kk], touzi1_decomposition[ll], \n                strlen(band_name[kk])) == 0)\n                found_band = TRUE;\n              else if (strcmp(decomposition, \"TSVM_phi_s3\") == 0 && \n                strncmp(band_name[kk], touzi2_decomposition[ll], \n                strlen(band_name[kk])) == 0)\n                found_band = TRUE;\n              else if (strcmp(decomposition, \"TSVM_tau_m3\") == 0 && \n                strncmp(band_name[kk], touzi3_decomposition[ll], \n                strlen(band_name[kk])) == 0)\n                found_band = TRUE;\n              else if (strcmp(decomposition, \"TSVM_psi3\") == 0 && \n                strncmp(band_name[kk], touzi4_decomposition[ll], \n                strlen(band_name[kk])) == 0)\n                found_band = TRUE;\n              else if (strcmp(decomposition, \"TSVM_psi\") == 0 && \n                strncmp(band_name[kk], touzi5_decomposition[ll], \n                strlen(band_name[kk])) == 0)\n                found_band = TRUE;\n            }\n            if (!found_band)\n              continue;\n            sprintf(out_file, \"%s%c%s\", \n              path_name, DIR_SEPARATOR, band_name[kk]);\n\n          }\n        else if (md->general->image_data_type == POLARIMETRIC_SEGMENTATION ||\n          md->general->image_data_type == POLARIMETRIC_PARAMETER)\n          append_band_ext(base_name, out_file, NULL);\n        else {\n          if (band_count > 1) {\n\t    if (strstr(band_name[kk], \"INTERFEROGRAM_PHASE\") &&\n\t\tis_colormap_band)\n\t      append_band_ext(base_name, out_file, \"INTERFEROGRAM_RGB\");\n\t    else\n\t      append_band_ext(base_name, out_file, band_name[kk]);\n\t  }\n          else\n            append_band_ext(base_name, out_file, NULL);\n        }\n\n        if (strcmp(band_name[0], MAGIC_UNSET_STRING) != 0)\n          asfPrintStatus(\"\\nWriting band '%s' ...\\n\", band_name[kk]);\n\n        if (format == TIF || format == GEOTIFF) {\n          is_geotiff = (format == GEOTIFF) ? 1 : 0;\n          append_ext_if_needed (out_file, \".tif\", \".tiff\");\n          if (is_colormap_band && strlen(lut_file) > 0) {\n            //sample_mapping = TRUNCATE;\n            rgb = FALSE;\n            initialize_tiff_file(&otif, &ogtif, out_file,\n              metadata_file_name, is_geotiff,\n              sample_mapping, rgb,\n              &palette_color_tiff, band_name,\n              lut_file, TRUE);\n          }\n          else {\n            initialize_tiff_file(&otif, &ogtif, out_file,\n              metadata_file_name, is_geotiff,\n              sample_mapping, rgb,\n              &palette_color_tiff, band_name,\n              NULL, FALSE);\n          }\n        }\n        else if (format == JPEG) {\n          append_ext_if_needed (out_file, \".jpg\", \".jpeg\");\n          if (is_colormap_band) {\n            initialize_jpeg_file(out_file, md,\n              &ojpeg, &cinfo, TRUE);\n          }\n          else {\n            initialize_jpeg_file(out_file, md,\n              &ojpeg, &cinfo, rgb);\n          }\n        }\n        else if (format == PNG) {\n          append_ext_if_needed (out_file, \".png\", NULL);\n          if (is_colormap_band) {\n            initialize_png_file(out_file, md,\n              &opng, &png_ptr, &png_info_ptr, TRUE);\n          }\n          else {\n            initialize_png_file(out_file, md,\n              &opng, &png_ptr, &png_info_ptr, rgb);\n          }\n        }\n        else if (format == PNG_ALPHA) {\n          append_ext_if_needed (out_file, \".png\", NULL);\n          initialize_png_file_ext(out_file, md,\n            &opng, &png_ptr, &png_info_ptr, FALSE, TRUE);\n        }\n        else if (format == PNG_GE) {\n          append_ext_if_needed (out_file, \".png\", NULL);\n          initialize_png_file_ext(out_file, md,\n            &opng, &png_ptr, &png_info_ptr, 1, 2);\n        }\n        else if (format == PGM) {\n          append_ext_if_needed (out_file, \".pgm\", \".pgm\");\n          initialize_pgm_file(out_file, md, &opgm);\n        }\n        else if (format == POLSARPRO_HDR) {\n          append_ext_if_needed (out_file, \".bin\", NULL);\n          initialize_polsarpro_file(out_file, md, &ofp);\n        }\n\telse if (format == HDF) {\n\t  append_ext_if_needed (out_file, \".h5\", NULL);\n\t  h5 = initialize_h5_file(out_file, md);\n\t  hdf = (float *) \n\t    MALLOC(sizeof(float)*md->general->line_count*\n\t\t   md->general->sample_count);\n\t}\n        else if (format == NC) {\n          append_ext_if_needed (out_file, \".nc\", NULL);\n\t  netcdf = initialize_netcdf_file(out_file, md);\n\t  nc = (float *)\n\t    MALLOC(sizeof(float)*md->general->line_count*\n\t\t   md->general->sample_count);        \n\t}\n        else {\n          asfPrintError(\"Impossible: unexpected format %s\\n\", format2str(format));\n        }\n\n        (*output_names)[*noutputs] = STRDUP(out_file);\n        *noutputs += 1;\n\n        // Determine which channel to read\n        int channel;\n        if (md->general->image_data_type >  POLARIMETRIC_IMAGE &&\n\t    md->general->image_data_type <= POLARIMETRIC_T4_MATRIX)\n          channel = kk;\n        else {\n          if (md->general->band_count == 1)\n            channel = 0;\n          else\n            channel = get_band_number(bands, band_count, band_name[kk]);\n          asfRequire(channel >= 0 && channel <= MAX_BANDS,\n            \"Band number out of range\\n\");\n        }\n\n        int sample_count = md->general->sample_count;\n        int offset = md->general->line_count;\n\n        // Get the statistics if necessary\n        channel_stats_t stats;\n        stats.hist = NULL; stats.hist_pdf = NULL;\n\n        if (sample_mapping != NONE && sample_mapping != TRUNCATE)\n        {\n          asfRequire (sizeof(unsigned char) == 1,\n            \"Size of the unsigned char data type on this machine is \"\n            \"different than expected.\\n\");\n          if (md->stats                  &&\n            md->stats->band_count > 0  &&\n            meta_is_valid_double(md->stats->band_stats[channel].mean) &&\n            meta_is_valid_double(md->stats->band_stats[channel].min) &&\n            meta_is_valid_double(md->stats->band_stats[channel].max) &&\n            meta_is_valid_double(md->stats->band_stats[channel].std_deviation) &&\n            sample_mapping != HISTOGRAM_EQUALIZE)\n          {\n            asfPrintStatus(\"Using metadata statistics - skipping stats computations.\\n\");\n            stats.min  = md->stats->band_stats[channel].min;\n            stats.max  = md->stats->band_stats[channel].max;\n            stats.mean = md->stats->band_stats[channel].mean;\n            stats.standard_deviation = md->stats->band_stats[channel].std_deviation;\n            stats.hist = NULL;\n          }\n          else {\n            asfPrintStatus(\"Gathering statistics ...\\n\");\n            calc_stats_from_file(image_data_file_name, band_name[kk],\n              md->general->no_data,\n              &stats.min, &stats.max, &stats.mean,\n              &stats.standard_deviation, &stats.hist);\n          }\n          if (sample_mapping == TRUNCATE && !have_look_up_table) {\n            if (stats.mean >= 255)\n              asfPrintWarning(\"The image contains HIGH values and will turn out very\\n\"\n              \"bright or all-white.\\n  Min : %f\\n  Max : %f\\n  Mean: %f\\n\"\n              \"=> Consider using a sample mapping method other than TRUNCATE\\n\",\n              stats.min, stats.max, stats.mean);\n            if (stats.mean < 10)\n              asfPrintWarning(\"The image contains LOW values and will turn out very\\n\"\n              \"dark or all-black.\\n  Min : %f\\n  Max : %f\\n  Mean: %f\\n\"\n              \"=> Consider using a sample mapping method other than TRUNCATE\\n\",\n              stats.min, stats.max, stats.mean);\n          }\n          if (sample_mapping == SIGMA)\n          {\n            double omin = stats.mean - 2*stats.standard_deviation;\n            double omax = stats.mean + 2*stats.standard_deviation;\n            if (omin > stats.min) stats.min = omin;\n            if (omax < stats.max) stats.max = omax;\n          }\n          if ( sample_mapping == HISTOGRAM_EQUALIZE ) {\n            stats.hist_pdf = gsl_histogram_pdf_alloc (256); //NUM_HIST_BINS);\n            gsl_histogram_pdf_init (stats.hist_pdf, stats.hist);\n          }\n        }\n\n        // Write the output image\n        FILE *fp = FOPEN(image_data_file_name, \"rb\");\n        float *float_line = (float *) MALLOC(sizeof(float) * sample_count);\n        unsigned char *byte_line = MALLOC(sizeof(unsigned char) * sample_count);\n\n        asfPrintStatus(\"Writing output file...\\n\");\n        if (is_colormap_band)\n        { // Apply look up table\n          for (ii=0; ii<md->general->line_count; ii++ ) {\n            if ((md->optical || md->general->data_type == BYTE) &&\n\t\tmd->general->image_data_type != POLARIMETRIC_PARAMETER) {\n              get_byte_line(fp, md, ii+channel*offset, byte_line);\n              if (format == TIF || format == GEOTIFF)\n                write_tiff_byte2lut(otif, byte_line, ii, sample_count,\n                lut_file);\n              else if (format == JPEG)\n                write_jpeg_byte2lut(ojpeg, byte_line, &cinfo, sample_count,\n                lut_file);\n              else if (format == PNG || format == PNG_ALPHA || format == PNG_GE)\n                write_png_byte2lut(opng, byte_line, png_ptr, png_info_ptr,\n                sample_count, lut_file);\n              else\n                asfPrintError(\"Impossible: unexpected format %s\\n\", format2str(format));\n            }\n            else {\n              // Force a sample mapping of TRUNCATE for PolSARpro classifications\n              // (They contain low integer values stored in floats ...contrast\n              //  expansion will break the look up in the look up table.)\n              get_float_line(fp, md, ii+channel*offset, float_line);\n              if (format == TIF || format == GEOTIFF)\n                // Unlike the other graphics file formats, the TIFF file uses an embedded\n                // colormap (palette) and therefore each pixel should be a single byte value\n                // where each byte value is an index into the colormap.  The other graphics\n                // file formats use interlaced RGB lines and no index or colormap instead.\n                write_tiff_float2byte(otif, float_line, stats,\n                //is_colormap_band ? TRUNCATE : sample_mapping,\n                sample_mapping,\n                md->general->no_data, ii, sample_count);\n              else if (format == JPEG)\n                // Use lut to write an RGB line to the file\n                write_jpeg_float2lut(ojpeg, float_line, &cinfo, stats,\n                //is_colormap_band ? TRUNCATE : sample_mapping,\n                sample_mapping,\n                md->general->no_data,\n                sample_count, lut_file);\n              else if (format == PNG || format == PNG_ALPHA || format == PNG_GE)\n                // Use lut to write an RGB line to the file\n                write_png_float2lut(opng, float_line, png_ptr, png_info_ptr,\n                stats,\n                //is_colormap_band ? TRUNCATE : sample_mapping,\n                sample_mapping,\n                md->general->no_data,\n                sample_count, lut_file);\n              else if (format == PGM) {\n                // Can't put color in a PGM file, so map it to greyscale and write that\n                write_pgm_float2byte(opgm, float_line, stats,\n                  //is_colormap_band ? TRUNCATE : sample_mapping,\n                  sample_mapping,\n                  md->general->no_data, sample_count);\n              }\n              else\n                asfPrintError(\"Impossible: unexpected format %s\\n\", format2str(format));\n            }\n            asfLineMeter(ii, md->general->line_count);\n          }\n        }\n        else {\n          // Regular old single band image (no look up table applied)\n          for (ii=0; ii<md->general->line_count; ii++ ) {\n            if (md->optical || md->general->data_type == BYTE) {\n              get_byte_line(fp, md, ii+channel*offset, byte_line);\n              if (format == TIF || format == GEOTIFF)\n                write_tiff_byte2byte(otif, byte_line, stats, sample_mapping,\n                sample_count, ii);\n              else if (format == JPEG)\n                write_jpeg_byte2byte(ojpeg, byte_line, stats, sample_mapping,\n                &cinfo, sample_count);\n              else if (format == PNG)\n                write_png_byte2byte(opng, byte_line, stats, sample_mapping,\n                png_ptr, png_info_ptr, sample_count);\n              else if (format == PNG_ALPHA) {\n                asfPrintError(\"PNG_ALPHA not supported.\\n\");\n              }\n              else if (format == PNG_GE)\n                write_png_byte2rgbalpha(opng, byte_line, stats, sample_mapping,\n                                        png_ptr, png_info_ptr, sample_count);\n              else if (format == PGM)\n                write_pgm_byte2byte(opgm, byte_line, stats, sample_mapping,\n                sample_count);\n              else\n                asfPrintError(\"Impossible: unexpected format %s\\n\", format2str(format));\n            }\n            else if (sample_mapping == NONE && !is_colormap_band) {\n              get_float_line(fp, md, ii+channel*offset, float_line);\n              if (format == GEOTIFF || format == TIF) {\n\t\tif (md->general->data_type == REAL32)\n\t\t  write_tiff_float2float(otif, float_line, ii);\n\t\telse if (md->general->data_type == INTEGER16)\n\t\t  write_tiff_float2int(otif, float_line, ii,\n\t\t\t\t       md->general->sample_count);\n\t      }\n              else if (format == POLSARPRO_HDR) {\n                int sample;\n                for (sample=0; sample<sample_count; sample++)\n                  ieee_lil32(float_line[sample]);\n                fwrite(float_line,4,sample_count,ofp);\n              }\n\t      else if (format == HDF) {\n\t\tint sample;\n\t\tfor (sample=0; sample<sample_count; sample++)\n\t\t  hdf[ii*sample_count+sample] = float_line[sample];\n\t      }\n\t      else if (format == NC) {\n\t\tint sample;\n\t\tfor (sample=0; sample<sample_count; sample++) {\n\t\t  nc[ii*sample_count+sample] = float_line[sample];\n\t\t}\n\t      }\n              else\n                asfPrintError(\"Impossible: unexpected format %s\\n\", format2str(format));\n            }\n            else {\n              get_float_line(fp, md, ii+channel*offset, float_line);\n              if (format == TIF || format == GEOTIFF)\n                write_tiff_float2byte(otif, float_line, stats,\n                //is_colormap_band ? TRUNCATE : sample_mapping,\n                sample_mapping,\n                md->general->no_data, ii, sample_count);\n              else if (format == JPEG)\n                write_jpeg_float2byte(ojpeg, float_line, &cinfo, stats,\n                //is_colormap_band ? TRUNCATE : sample_mapping,\n                sample_mapping,\n                md->general->no_data,\n                sample_count);\n              else if (format == PNG || format == PNG_ALPHA || format == PNG_GE)\n                write_png_float2byte(opng, float_line, png_ptr, png_info_ptr,\n                stats,\n                //is_colormap_band ? TRUNCATE : sample_mapping,\n                sample_mapping,\n                md->general->no_data,\n                sample_count);\n              else if (format == PGM)\n                write_pgm_float2byte(opgm, float_line, stats,\n                //is_colormap_band ? TRUNCATE : sample_mapping,\n                sample_mapping,\n                md->general->no_data, sample_count);\n              else if (format == POLSARPRO_HDR) {\n                int sample;\n                for (sample=0; sample<sample_count; sample++)\n                  ieee_lil32(float_line[sample]);\n                fwrite(float_line,4,sample_count,ofp);\n              }\n              else\n                asfPrintError(\"Impossible: unexpected format %s\\n\", format2str(format));\n            }\n            asfLineMeter(ii, md->general->line_count);\n          } // End for each line\n        } // End if multi or single band\n        // Free memory\n        FREE(float_line);\n        FREE(byte_line);\n        if (stats.hist) gsl_histogram_free(stats.hist);\n        if (stats.hist_pdf) gsl_histogram_pdf_free(stats.hist_pdf);\n\n        // Finalize the chosen format\n        if (format == TIF || format == GEOTIFF)\n          finalize_tiff_file(otif, ogtif, is_geotiff);\n        else if (format == JPEG)\n          finalize_jpeg_file(ojpeg, &cinfo);\n        else if (format == PNG || format == PNG_ALPHA || format == PNG_GE)\n          finalize_png_file(opng, png_ptr, png_info_ptr);\n        else if (format == PGM)\n          finalize_ppm_file(opgm);\n        else if (format == POLSARPRO_HDR)\n          FCLOSE(ofp);\n\telse if (format == HDF) {\n\t  asfPrintStatus(\"Storing band '%s' ...\\n\", band_name[kk]);\n\t  char dataset[50];\n\t  sprintf(dataset, \"/data/%s_AMPLITUDE_IMAGE\", band_name[kk]);\n\t  hid_t h5_data = H5Dopen(h5->file, dataset, H5P_DEFAULT);\n\t  H5Dwrite(h5_data, H5T_NATIVE_FLOAT, H5S_ALL, H5S_ALL, \n\t\t   H5P_DEFAULT, hdf);\n\t  H5Dclose(h5_data);\n\t}\n\telse if (format == NC) {\n\t  asfPrintStatus(\"Storing band '%s' ...\\n\", band_name[kk]);\n\t  nc_put_var_float(netcdf->ncid, netcdf->var_id[kk], &nc[0]);\n\t}\n\n        FCLOSE(fp);\n      }\n    } // End for each band (kk is band number)\n\n    if (hdf) {\n      finalize_h5_file(h5);\n      FREE(hdf);\n    }\n\n    if (nc) {\n      finalize_netcdf_file(netcdf, md);\n      FREE(nc);\n    }\n    if (free_band_names) {\n      for (ii=0; ii<band_count; ++ii)\n        FREE(band_name[ii]);\n      FREE(band_name);\n    }\n    FREE(path_name);\n    FREE(matrix);\n    FREE(decomposition);\n    FREE(out_file);\n  }\n\n  if (lut_file && strstr(lut_file, \"tmp_lut_file.lut\") && fileExists(lut_file)) {\n    // If a temporary look-up table was generated (from an embedded colormap in the\n    // metadata) then remove it now.\n    remove(lut_file);\n  }\n  FREE(lut_file);\n  meta_free (md);\n}\n\nvoid append_band_names(char **band_names, int rgb, char *citation, int palette_color_tiff)\n{\n  char band_name[256];\n  int i=0;\n  sprintf(citation, \"%s, %s: \", citation, BAND_ID_STRING);\n  if (band_names) {\n    if (rgb && !palette_color_tiff) {\n      // RGB tiffs that do not use a color index (palette) have 3 bands, but\n      // palette color tiffs have a single band and an RGB look-up table (TIFFTAG_COLORMAP)\n      //\n      // When the image uses a look-up table, then meta->general->bands lists the look-up table\n      // name rather than a list of individual band names.  band_names[] will therefore only have\n      // a single entry.\n      //\n      // When a color image does not use a look-up table, then meta->general->bands contains\n      // the list of band names, one for each band, separated by commas.  It's safe to expect\n      // the band_names[] array to contain 3 bands in this case.\n      for (i=0; i<2; i++) {\n        // First 2 bands have a comma after the band name\n        if (band_names[i] != NULL && strlen(band_names[i]) > 0 &&\n            strncmp(band_names[i], MAGIC_UNSET_STRING, strlen(MAGIC_UNSET_STRING)) != 0)\n        {\n          sprintf(band_name, \"%s,\", strncmp(\"IGNORE\", uc(band_names[i]), 6) == 0 ? \"Empty\" : band_names[i]);\n          strcat(citation, band_name);\n        }\n        else {\n          sprintf(band_name, \"%02d,\", i + 1);\n          strcat(citation, band_name);\n        }\n      }\n      if (band_names[i] != NULL && strlen(band_names[i]) > 0 &&\n          strncmp(band_names[i], MAGIC_UNSET_STRING, strlen(MAGIC_UNSET_STRING)) != 0)\n      {\n        strcat(citation, strncmp(\"IGNORE\", uc(band_names[i]), 6) == 0 ? \"Empty\" : band_names[i]);\n      }\n      else {\n        sprintf(band_name, \"%02d\", i + 1);\n        strcat(citation, band_name);\n      }\n    }\n    else {\n        // Single band image or a palette color image\n        if (palette_color_tiff) {\n            strcat(citation, band_names[0]);\n        }\n        else {\n            if (band_names[0] != NULL && strlen(band_names[0]) > 0 &&\n                strncmp(band_names[i], MAGIC_UNSET_STRING, strlen(MAGIC_UNSET_STRING)) != 0)\n            {\n                strcat(citation, strncmp(\"IGNORE\", uc(band_names[0]), 6) == 0 ? \"Empty\" : band_names[0]);\n            }\n            else {\n                strcat(citation, \"01\");\n            }\n        }\n    }\n  }\n  else {\n    if (rgb && !palette_color_tiff)\n      strcat(citation, \"01,02,03\");\n    else\n      strcat(citation, \"01\");\n  }\n}\n\n// lut_to_tiff_palette() converts an ASF-style look-up table (text file) into\n// a TIFF standard RGB palette (indexed color map for TIFFTAG_COLORMAP)\nint lut_to_tiff_palette(unsigned short **colors, int map_size, char *look_up_table_name)\n{\n    int i, max_lut_dn;\n    unsigned char *lut = NULL;\n    float r, g, b;\n\n    asfRequire(map_size >= 1, \"TIFF palette color map size less than 1 element\\n\");\n    asfRequire(look_up_table_name != NULL && strlen(look_up_table_name) > 0,\n               \"Invalid look up table name\\n\");\n\n    // Use CALLOC so the entire look up table is initialized to zero\n    lut = (unsigned char *)CALLOC(MAX_LUT_DN * 3, sizeof(unsigned char));\n\n    // Read the look up table from the file.  It will be 3-color and have MAX_LUT_DN*3 elements\n    // in the array, in packed format <rgbrgbrgb...rgb>, and values range from 0 to 255\n    max_lut_dn = read_lut(look_up_table_name, lut);\n    if (max_lut_dn > map_size) {\n        FREE(lut);\n        asfPrintError(\"Look-up table too large (%d) for TIFF.  Maximum TIFF\\n\"\n                \"look-up table size for the data type is %d elements long.\\n\", max_lut_dn, map_size);\n    }\n    *colors = (unsigned short *)_TIFFmalloc(sizeof(unsigned short) * 3 * map_size);\n    asfRequire(*colors != NULL, \"Could not allocate TIFF palette.\\n\");\n    for (i = 0; i < 3 * map_size; i++) (*colors)[i] = (unsigned short)0; // Init to all zeros\n\n    // Normalize the look-up table values into the range specified by the TIFF standard\n    // (0 through 65535 ...the maximum unsigned short value)\n    for (i=0; i<max_lut_dn; i++) {\n        // TIFF color map structure is a one-row array, all the reds, then all the\n        // greens, then all the blues, i.e. <all reds><all greens><all blues>, each\n        // section 'map_size' elements long\n        //\n        // Grab rgb values from the lut\n        r = (float)lut[i*3  ];\n        g = (float)lut[i*3+1];\n        b = (float)lut[i*3+2];\n\n        // Normalize the lut values to the 0-65535 range as specified by the TIFF standard for\n        // color maps / palettes\n        (*colors)[i             ] = (unsigned short) ((r/(float)MAX_RGB)*(float)USHORT_MAX + 0.5);\n        (*colors)[i +   map_size] = (unsigned short) ((g/(float)MAX_RGB)*(float)USHORT_MAX + 0.5);\n        (*colors)[i + 2*map_size] = (unsigned short) ((b/(float)MAX_RGB)*(float)USHORT_MAX + 0.5);\n    }\n\n    return max_lut_dn;\n}\n\n// Assumes the color map is made from unsigned shorts (uint16 or equiv).  a) This is mandated\n// by v6 of the TIFF standard regardless of data type in the tiff, b) The only valid\n// data types for a colormap TIFF is i) 4-bit unsigned integer, or ii) 8-bit unsigned integer,\n// and c) the values in a TIFF colormap range from 0 to 65535 (max uint16) and must be normalized\n// to 0-255 as for display (the range 0-255 is normalize to 0-65535 when creating the colormap\n// in the first place.)\nvoid dump_palette_tiff_color_map(unsigned short *colors, int map_size)\n{\n    int i;\n    asfRequire(map_size <= 256, \"Map size too large.\\n\");\n\n    fprintf(stderr, \"\\n\\nColor Map (DN: red  green  blue):\\n\");\n    for (i=0; i<map_size; i++){\n        fprintf(stderr, \"%d:\\t%d\\t%d\\t%d\\n\", i,\n                (int)((float)colors[i +          0]*((float)MAX_RGB/(float)USHORT_MAX) + 0.5),\n                (int)((float)colors[i +   map_size]*((float)MAX_RGB/(float)USHORT_MAX) + 0.5),\n                (int)((float)colors[i + 2*map_size]*((float)MAX_RGB/(float)USHORT_MAX) + 0.5));\n    }\n}\n\nint meta_colormap_to_tiff_palette(unsigned short **tiff_palette, int *byte_image, meta_colormap *colormap)\n{\n    int i, size;\n    unsigned short r, g, b;\n    meta_colormap *cm = colormap; // Convenience ptr\n\n    asfRequire(colormap != NULL, \"Unallocated colormap.\\n\");\n    size = cm->num_elements;\n    *tiff_palette = (unsigned short *)CALLOC(3*size, sizeof(unsigned short));\n\n    // A TIFF palette is a one dimensional array ...all the reds, then all the greens, then all the blues\n    // Create TIFF palette by normalizing 0-255 range into 0-65535 and storing in the band sequential\n    // array.\n    for (i=0; i<size; i++) {\n        r = cm->rgb[i].red;\n        g = cm->rgb[i].green;\n        b = cm->rgb[i].blue;\n        (*tiff_palette)[i +      0] = (unsigned short) (((float)r/(float)MAX_RGB)*(float)USHORT_MAX + 0.5);\n        (*tiff_palette)[i +   size] = (unsigned short) (((float)g/(float)MAX_RGB)*(float)USHORT_MAX + 0.5);\n        (*tiff_palette)[i + 2*size] = (unsigned short) (((float)b/(float)MAX_RGB)*(float)USHORT_MAX + 0.5);\n    }\n\n    return size;\n}\n\nchar *sample_mapping2string(scale_t sample_mapping)\n{\n    switch(sample_mapping) {\n        case TRUNCATE:\n            return \"TRUNCATE\";\n            break;\n        case MINMAX:\n            return \"MIN-MAX\";\n            break;\n        case SIGMA:\n            return \"2-SIGMA\";\n            break;\n        case HISTOGRAM_EQUALIZE:\n            return \"HISTOGRAM EQUALIZE\";\n            break;\n        case NONE:\n            return \"NONE\";\n            break;\n        default:\n            return \"UNKNOWN or UNRECOGNIZED\";\n            break;\n    }\n}\n\nvoid colormap_to_lut_file(meta_colormap *cm, const char *lut_file)\n{\n  int i;\n  char line[256];\n\n  FILE *fp = FOPEN(lut_file, \"wt\");\n  fprintf(fp, \"# Temporary look-up table file for asf_export\\n\");\n  fprintf(fp, \"# Look-up table     : %s\\n\", cm->look_up_table);\n  fprintf(fp, \"# Number of elements: %d\\n\", cm->num_elements);\n  fprintf(fp, \"# Index   Red   Green   Blue\\n\");\n  for (i=0; i<cm->num_elements; i++) {\n    sprintf(line, \"%d %d %d %d\\n\",\n            i, cm->rgb[i].red, cm->rgb[i].green, cm->rgb[i].blue);\n    fprintf(fp, line);\n  }\n  FCLOSE(fp);\n}\n", "meta": {"hexsha": "7faebdfad2f292b32a9bb2e9d4a061631e8dfbb7", "size": 124750, "ext": "c", "lang": "C", "max_stars_repo_path": "src/libasf_export/export_band.c", "max_stars_repo_name": "glshort/MapReady", "max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z", "max_issues_repo_path": "src/libasf_export/export_band.c", "max_issues_repo_name": "glshort/MapReady", "max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libasf_export/export_band.c", "max_forks_repo_name": "glshort/MapReady", "max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z", "avg_line_length": 42.9875947622, "max_line_length": 108, "alphanum_fraction": 0.6051783567, "num_tokens": 32121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3311197264277872, "lm_q2_score": 0.022977367861076722, "lm_q1q2_score": 0.007608259760190354}}
{"text": "#pragma once\n/*\n * (C) Copyright 2020-2021 UCAR\n *\n * This software is licensed under the terms of the Apache Licence Version 2.0\n * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.\n */\n/*! \\addtogroup ioda_cxx_attribute\n *\n * @{\n * \\file Attribute_Creator.h\n * \\brief Flywheel creation of ioda::Attribute. Used by ioda::Has_Attributes and\n * ioda::VariableCreationParameters.\n */\n\n#include <gsl/gsl-lite.hpp>\n#include <iostream>\n#include <memory>\n#include <string>\n#include <vector>\n\n#include \"ioda/Attributes/Attribute.h\"\n#include \"ioda/Attributes/Has_Attributes.h\"\n#include \"ioda/Misc/Dimensions.h\"\n#include \"ioda/Types/Type.h\"\n#include \"ioda/defs.h\"\n\nnamespace ioda {\nnamespace detail {\n/// \\brief Flywheel creation of ioda::Attribute.\n/// \\ingroup ioda_cxx_attribute\nclass IODA_DL Attribute_Creator_Base {\nprotected:\n  std::string name_;\n\npublic:\n  virtual ~Attribute_Creator_Base();\n  virtual void apply(Has_Attributes& obj) const = 0;\n  Attribute_Creator_Base(const std::string& name);\n};\n}  // namespace detail\n\n/// \\brief Flywheel creation of ioda::Attribute.\n/// \\ingroup ioda_cxx_attribute\ntemplate <class DataType>\nclass Attribute_Creator : public detail::Attribute_Creator_Base {\nprivate:\n  ::std::vector<Dimensions_t> dimensions_;\n  ::std::vector<DataType> data_;\n\npublic:\n  virtual ~Attribute_Creator() {}\n  void apply(Has_Attributes& obj) const override { obj.add<DataType>(name_, data_, dimensions_); }\n\n  /// \\details Totally taking advantage of vector constructors.\n  template <class DataInput, class DimensionInput>\n  Attribute_Creator(const std::string& name, DataInput data, DimensionInput dimensions)\n      : Attribute_Creator_Base(name), data_(data.begin(), data.end()), dimensions_(dimensions) {}\n\n  template <class DimensionInput>\n  Attribute_Creator(const std::string& name, DimensionInput dimensions)\n      : Attribute_Creator_Base(name), dimensions_(dimensions) {}\n\n  template <class DataInput_junk_param = DataType>\n  void write(const ::gsl::span<const DataType>& data) {\n    data_ = ::std::vector<DataType>(data.begin(), data.end());\n  }\n};\n\n/// \\brief Flywheel creation of ioda::Attribute objects.\n/// \\ingroup ioda_cxx_attribute\n/// This is needed because you might want to make the same Attribute in multiple places.\nclass IODA_DL Attribute_Creator_Store : public detail::CanAddAttributes<Attribute_Creator_Store> {\n  std::vector<std::shared_ptr<detail::Attribute_Creator_Base>> atts_;\n\npublic:\n  Attribute_Creator_Store();\n  virtual ~Attribute_Creator_Store();\n\n  void apply(Has_Attributes& obj) const;\n\n  /// @name Convenience functions for adding attributes\n  /// @{\n  /// \\see CanAddAttributes\n  /// \\see CanAddAttributes::add\n\n  template <class DataType>\n  Attribute_Creator_Store& create(const std::string& attrname, ::gsl::span<const DataType> data,\n                                  ::std::initializer_list<Dimensions_t> dimensions) {\n    atts_.push_back(std::make_shared<Attribute_Creator<DataType>>(attrname, data, dimensions));\n    return *this;\n  }\n\n  template <class DataType>\n  Attribute_Creator_Store& create(const std::string& attrname,\n                                  ::std::initializer_list<DataType> data,\n                                  ::std::initializer_list<Dimensions_t> dimensions) {\n    atts_.push_back(std::make_shared<Attribute_Creator<DataType>>(attrname, data, dimensions));\n    return *this;\n  }\n\n  template <class DataType2>\n  struct AttWrapper {\n    std::shared_ptr<Attribute_Creator<DataType2>> inner;\n    AttWrapper(std::shared_ptr<Attribute_Creator<DataType2>> d) : inner(d) {}\n    template <class DataInput_junk_param = DataType2>\n    void write(const ::gsl::span<const DataType2>& data) {\n      inner->write(data);\n    }\n  };\n\n  template <class DataType>\n  AttWrapper<DataType> create(const std::string& attrname, ::std::vector<Dimensions_t> dimensions) {\n    auto res = std::make_shared<Attribute_Creator<DataType>>(attrname, dimensions);\n    atts_.push_back(res);\n    return AttWrapper<DataType>{res};\n  }\n\n  /// @}\n};\n\n}  // namespace ioda\n\n/// @} // End Doxygen block\n", "meta": {"hexsha": "55837f4e921183d96ac100248750581946b5a5e5", "size": 4068, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engines/ioda/include/ioda/Attributes/Attribute_Creator.h", "max_stars_repo_name": "NOAA-EMC/ioda", "max_stars_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-09T16:11:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-09T16:11:50.000Z", "max_issues_repo_path": "src/engines/ioda/include/ioda/Attributes/Attribute_Creator.h", "max_issues_repo_name": "NOAA-EMC/ioda", "max_issues_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engines/ioda/include/ioda/Attributes/Attribute_Creator.h", "max_forks_repo_name": "NOAA-EMC/ioda", "max_forks_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-06-09T16:12:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-14T09:19:25.000Z", "avg_line_length": 32.544, "max_line_length": 100, "alphanum_fraction": 0.7182890855, "num_tokens": 985, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11596070908851643, "lm_q2_score": 0.06560484430997267, "lm_q1q2_score": 0.0076075842658261525}}
{"text": "#pragma once\n\n#include <imageview/ContinuousImageView.h>\n#include <imageview/ImageView.h>\n\n#include <gsl/assert>\n\nnamespace imageview {\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr ImageView<PixelFormat, Mutable> crop(ImageView<PixelFormat, Mutable> image, unsigned int first_row,\n                                               unsigned int first_column, unsigned int num_rows,\n                                               unsigned int num_columns) {\n  Expects(first_row <= image.height());\n  Expects(first_column <= image.width());\n  Expects(first_row + num_rows <= image.height());\n  Expects(first_column + num_columns <= image.width());\n  const std::size_t data_offset = (first_row * image.stride() + first_column) * PixelFormat::kBytesPerPixel;\n  const std::size_t new_data_size =\n      (num_rows == 0) ? 0 : ((num_rows - 1) * image.stride() + num_columns) * PixelFormat::kBytesPerPixel;\n  const auto data_new = image.data().subspan(data_offset, new_data_size);\n  return ImageView<PixelFormat>(num_rows, num_columns, image.stride(), data_new, image.pixelFormat());\n}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr ImageView<PixelFormat, Mutable> crop(ContinuousImageView<PixelFormat, Mutable> image, unsigned int first_row,\n                                               unsigned int first_column, unsigned int num_rows,\n                                               unsigned int num_columns) {\n  return crop(ImageView<PixelFormat, Mutable>(image), first_column, first_column, num_rows, num_columns);\n}\n\n}  // namespace imageview\n", "meta": {"hexsha": "b1d85aff4478ae03ed08f559259cc9e954eef256", "size": 1553, "ext": "h", "lang": "C", "max_stars_repo_path": "include/imageview/ImageViewUtils.h", "max_stars_repo_name": "alexanderbelous/imageview", "max_stars_repo_head_hexsha": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/imageview/ImageViewUtils.h", "max_issues_repo_name": "alexanderbelous/imageview", "max_issues_repo_head_hexsha": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/imageview/ImageViewUtils.h", "max_forks_repo_name": "alexanderbelous/imageview", "max_forks_repo_head_hexsha": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.0606060606, "max_line_length": 119, "alphanum_fraction": 0.6722472634, "num_tokens": 317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20689403903542755, "lm_q2_score": 0.036769462249328304, "lm_q1q2_score": 0.00760738255792421}}
{"text": "#pragma once\n\n#include <cstdint>\n#include <array>\n#include <gsl/gsl>\n\n#include \"halley/data_structures/maybe.h\"\n#include \"halley/maths/vector2.h\"\n#include \"halley/maths/colour.h\"\n#include \"halley/file_formats/image.h\"\n\nnamespace Halley {\n\tenum class AsepriteBlendMode;\n\n\tenum class AsepriteDepth\n\t{\n\t\tRGBA32,\n\t\tGreyscale16,\n\t\tIndexed8\n\t};\n\n\tstruct AsepriteCel\n\t{\n\tpublic:\n\t\tVector2i pos;\n\t\tVector2i size;\n\t\tuint16_t layer = 0;\n\t\tuint16_t linkedFrame = 0;\n\t\tuint8_t opacity = 255;\n\t\tbool linked = false;\n\n\t\tBytes rawData;\n\t\tstd::unique_ptr<Image> imgData;\n\n\t\tvoid loadImage(AsepriteDepth depth, const Vector<uint32_t>& palette);\n\t\tvoid drawAt(Image& image, uint8_t opacity, AsepriteBlendMode blendMode) const;\n\t};\n\n\tstruct AsepriteFrame\n\t{\n\tpublic:\n\t\tAsepriteFrame(uint16_t duration);\n\n\t\tuint16_t duration;\n\t\tVector<AsepriteCel> cels;\n\t};\n\n\tenum class AsepriteLayerType\n\t{\n\t\tNormal,\n\t\tGroup\n\t};\n\n\tenum class AsepriteBlendMode\n\t{\n\t\tNormal,\n\t\tMultiply,\n\t\tScreen,\n\t\tOverlay,\n\t\tDarken,\n\t\tLighten,\n\t\tColorDodge,\n\t\tColorBurn,\n\t\tHardLight,\n\t\tSoftLight,\n\t\tDifference,\n\t\tExclusion,\n\t\tHue,\n\t\tSaturation,\n\t\tColor,\n\t\tLuminosity,\n\t\tAddition,\n\t\tSubtract,\n\t\tDivide\n\t};\n\n\tstruct AsepriteLayer\n\t{\n\t\tAsepriteLayerType type = AsepriteLayerType::Normal;\n\t\tAsepriteBlendMode blendMode = AsepriteBlendMode::Normal;\n\t\tint childLevel = 0;\n\t\tbool visible = true;\n\t\tbool editable = true;\n\t\tbool lockMovement = false;\n\t\tbool background = false;\n\t\tbool preferLinkedCels = false;\n\t\tbool layerGroupDisplaysCollapsed = false;\n\t\tbool referenceLayer = false;\n\t\tuint8_t opacity = 255;\n\t\tString layerName;\n\n\t\tOptionalLite<uint32_t> parentIdx;\n\t\tbool visibleInHierarchy = true;\n\t};\n\n\tenum class AsepriteAnimationDirection\n\t{\n\t\tForward,\n\t\tReverse,\n\t\tPingPong\n\t};\n\n\tstruct AsepriteTag\n\t{\n\t\tint fromFrame = -1;\n\t\tint toFrame = -1;\n\t\tAsepriteAnimationDirection animDirection = AsepriteAnimationDirection::Forward;\n\t\t\n\t\tString name;\n\t};\n        \n    class AsepriteFile {\n    public:\n\t\tAsepriteFile();\n\n\t\tvoid load(gsl::span<const gsl::byte> data);\n\n\t\tconst Vector<AsepriteTag>& getTags() const;\n\t\tstd::map<String, std::unique_ptr<Image>> makeGroupFrameImages(int frameNumber, bool groupSeparated);\n\t    const AsepriteFrame& getFrame(int n) const;\n\t    size_t getNumberOfFrames() const;\n\n    private:\n\t    void addFrame(uint16_t duration);\n\t    void addChunk(uint16_t chunkType, gsl::span<const gsl::byte> data);\n\n\t    void addLayerChunk(gsl::span<const gsl::byte> span);\n\t\tvoid addCelChunk(gsl::span<const gsl::byte> span);\n\t\tvoid addCelExtraChunk(gsl::span<const gsl::byte> span);\n\t\tvoid addPaletteChunk(gsl::span<const gsl::byte> span);\n\t\tvoid addTagsChunk(gsl::span<const gsl::byte> span);\n    \tvoid postProcessLayers();\n\n\t\ttemplate <typename T>\n\t\tvoid readData(T& dst, gsl::span<const gsl::byte>& data) const\n\t\t{\n\t\t\tif (data.size() < T::size) {\n\t\t\t\tthrow Exception(\"Insufficient data to decode Aseprite entry\", HalleyExceptions::Tools);\n\t\t\t}\n\t\t\tmemcpy(&dst, data.data(), T::size);\n\t\t\tdata = data.subspan(T::size);\n\t\t}\n\n\t\tString readString(gsl::span<const gsl::byte>& data) const\n\t\t{\n\t\t\tif (data.size() < 2) {\n\t\t\t\tthrow Exception(\"Insufficient data to decode Aseprite entry\", HalleyExceptions::Tools);\n\t\t\t}\n\t\t\tuint16_t size;\n\t\t\tmemcpy(&size, data.data(), 2);\n\t\t\tdata = data.subspan(2);\n\t\t\tif (data.size() < size) {\n\t\t\t\tthrow Exception(\"Insufficient data to decode Aseprite entry\", HalleyExceptions::Tools);\n\t\t\t}\n\t\t\tString result = String(reinterpret_cast<const char*>(data.data()), size);\n\t\t\tdata = data.subspan(size);\n\t\t\treturn result;\n\t\t}\n\n\t    AsepriteCel* getCelAt(int frameNumber, int layerNumber);\n\t    size_t getBPP() const;\n\n\t\tVector2i size;\n\t\tuint32_t flags;\n\t\tAsepriteDepth colourDepth;\n\t\tuint8_t transparentEntry;\n\t\tuint16_t numOfColours;\n\n\t\tVector<AsepriteFrame> frames;\n\t\tVector<AsepriteLayer> layers;\n\t\tVector<AsepriteTag> tags;\n\t\tVector<uint32_t> paletteBg;\n\t\tVector<uint32_t> paletteTransparent;\n    };\n}\n", "meta": {"hexsha": "ecafbd28aa2d680db7e63122915a3750eb04933b", "size": 3882, "ext": "h", "lang": "C", "max_stars_repo_path": "src/tools/tools/src/sprites/aseprite_file.h", "max_stars_repo_name": "amrezzd/halley", "max_stars_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tools/tools/src/sprites/aseprite_file.h", "max_issues_repo_name": "amrezzd/halley", "max_issues_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tools/tools/src/sprites/aseprite_file.h", "max_forks_repo_name": "amrezzd/halley", "max_forks_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0568181818, "max_line_length": 102, "alphanum_fraction": 0.7071097372, "num_tokens": 1124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29746995506106744, "lm_q2_score": 0.025565213598458862, "lm_q1q2_score": 0.007604882940260148}}
{"text": "#ifndef __GSL_MATRIX_H__\n#define __GSL_MATRIX_H__\n\n\n#include <gsl/matrix/gsl_matrix_double.h>\n\n\n#endif /* __GSL_MATRIX_H__ */\n", "meta": {"hexsha": "c138aef7f486c014f6d7997aa12930225f33cfc1", "size": 126, "ext": "h", "lang": "C", "max_stars_repo_path": "Cartwheel/cartwheel-3d/gsl/matrix/gsl_matrix.h", "max_stars_repo_name": "MontyThibault/centre-of-mass-awareness", "max_stars_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Cartwheel/cartwheel-3d/gsl/matrix/gsl_matrix.h", "max_issues_repo_name": "MontyThibault/centre-of-mass-awareness", "max_issues_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cartwheel/cartwheel-3d/gsl/matrix/gsl_matrix.h", "max_forks_repo_name": "MontyThibault/centre-of-mass-awareness", "max_forks_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.0, "max_line_length": 41, "alphanum_fraction": 0.7857142857, "num_tokens": 36, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22270013882530887, "lm_q2_score": 0.03410042583501359, "lm_q1q2_score": 0.007594169567459675}}
{"text": "#ifndef CONTROLLERS_FEATURE_DETECTOR_CONTROLLER_H\n#define CONTROLLERS_FEATURE_DETECTOR_CONTROLLER_H\n\n#include <QObject>\n\n#include <QAction>\n\n#include <s3d/cv/features/match_finder_cv.h>\n#include <s3d/cv/disparity/disparity_analyzer_stan.h>\n\n#include <gsl/gsl>\n\nclass FeatureDetectorControllerBase : QObject {\n  Q_OBJECT\n\npublic:\n  FeatureDetectorControllerBase(gsl::not_null<QAction*> action,\n                                gsl::not_null<s3d::DisparityAnalyzerSTAN*> disparityAnalyzer);\n\n  virtual std::unique_ptr<s3d::MatchFinderCV> createMatchFinder() = 0;\n\nprivate:\n  QAction* m_action;\n  s3d::DisparityAnalyzerSTAN* m_disparityAnalyzer;\n};\n\ntemplate <class T>\nclass FeatureDetectorController : public FeatureDetectorControllerBase {\n  FeatureDetectorController(gsl::not_null<QAction*> action,\n                            gsl::not_null<s3d::DisparityAnalyzerSTAN*> disparityAnalyzer)\n    : FeatureDetectorControllerBase(action, disparityAnalyzer) {}\n\n  std::unique_ptr<s3d::MatchFinderCV> createMatchFinder() override {\n    return std::make_unique<T>();\n  }\n};\n\n\n#endif //CONTROLLERS_FEATURE_DETECTOR_CONTROLLER_H\n", "meta": {"hexsha": "8ddcf142e539f731153a3f815775d2db7e5ebdb0", "size": 1118, "ext": "h", "lang": "C", "max_stars_repo_path": "src/apps/S3DAnalyzer/controllers/feature_detector_controller.h", "max_stars_repo_name": "hugbed/OpenS3D", "max_stars_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-16T16:38:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-20T03:23:15.000Z", "max_issues_repo_path": "src/apps/S3DAnalyzer/controllers/feature_detector_controller.h", "max_issues_repo_name": "hugbed/OpenS3D", "max_issues_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 40.0, "max_issues_repo_issues_event_min_datetime": "2017-04-12T17:24:44.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-21T18:41:23.000Z", "max_forks_repo_path": "src/apps/S3DAnalyzer/controllers/feature_detector_controller.h", "max_forks_repo_name": "hugbed/OpenS3D", "max_forks_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-07-13T21:51:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-18T16:22:03.000Z", "avg_line_length": 27.95, "max_line_length": 94, "alphanum_fraction": 0.7584973166, "num_tokens": 265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22270014914315836, "lm_q2_score": 0.034100424239886684, "lm_q1q2_score": 0.007594169564067737}}
{"text": "#pragma once\n\n#include <gsl\\gsl>\n#include <winrt\\Windows.Foundation.h>\n#include <d3d11.h>\n#include \"DrawableGameComponent.h\"\n#include \"MatrixHelper.h\"\n#include \"DirectionalLight.h\"\n\nnamespace Library\n{\n\tclass ProxyModel;\n}\n\nnamespace Rendering\n{\n\tclass BlinnPhongMaterial;\n\n\tclass BlinnPhongDemo final : public Library::DrawableGameComponent\n\t{\n\tpublic:\n\t\tBlinnPhongDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera);\n\t\tBlinnPhongDemo(const BlinnPhongDemo&) = delete;\n\t\tBlinnPhongDemo(BlinnPhongDemo&&) = default;\n\t\tBlinnPhongDemo& operator=(const BlinnPhongDemo&) = default;\t\t\n\t\tBlinnPhongDemo& operator=(BlinnPhongDemo&&) = default;\n\t\t~BlinnPhongDemo();\n\n\t\tbool AnimationEnabled() const;\n\t\tvoid SetAnimationEnabled(bool enabled);\n\t\tvoid ToggleAnimation();\n\n\t\tfloat AmbientLightIntensity() const;\n\t\tvoid SetAmbientLightIntensity(float intensity);\n\n\t\tfloat DirectionalLightIntensity() const;\n\t\tvoid SetDirectionalLightIntensity(float intensity);\n\n\t\tconst DirectX::XMFLOAT3& LightDirection() const;\n\t\tvoid RotateDirectionalLight(const DirectX::XMFLOAT2& amount);\n\n\t\tfloat SpecularIntensity() const;\n\t\tvoid SetSpecularIntensity(float intensity);\n\n\t\tfloat SpecularPower() const;\n\t\tvoid SetSpecularPower(float power);\n\n\t\tvirtual void Initialize() override;\n\t\tvirtual void Update(const Library::GameTime& gameTime) override;\n\t\tvirtual void Draw(const Library::GameTime& gameTime) override;\n\n\tprivate:\n\t\tinline static const float RotationRate{ DirectX::XM_PI };\n\n\t\tstd::shared_ptr<BlinnPhongMaterial> mMaterial;\n\t\tDirectX::XMFLOAT4X4 mWorldMatrix{ Library::MatrixHelper::Identity };\n\t\twinrt::com_ptr<ID3D11Buffer> mVertexBuffer;\n\t\twinrt::com_ptr<ID3D11Buffer> mIndexBuffer;\n\t\tstd::uint32_t mIndexCount{ 0 };\n\t\tLibrary::DirectionalLight mDirectionalLight;\n\t\tstd::unique_ptr<Library::ProxyModel> mProxyModel;\n\t\tfloat mModelRotationAngle{ 0.0f };\n\t\tbool mAnimationEnabled{ true };\n\t\tbool mUpdateMaterial{ true };\n\t};\n}", "meta": {"hexsha": "356e99c1cbef0bfbc3b0bb53312dc5115f741af1", "size": 1932, "ext": "h", "lang": "C", "max_stars_repo_path": "source/3.3_Specular_Highlights/BlinnPhongDemo.h", "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/3.3_Specular_Highlights/BlinnPhongDemo.h", "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/3.3_Specular_Highlights/BlinnPhongDemo.h", "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2727272727, "max_line_length": 86, "alphanum_fraction": 0.7738095238, "num_tokens": 508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658972248186006, "lm_q2_score": 0.02064592900676275, "lm_q1q2_score": 0.007568585384969341}}
{"text": "#if !defined(PETIGAGRID_H)\n#define PETIGAGRID_H\n\n#include <petsc.h>\n\n#if !defined(LGMap)\n#define LGMap ISLocalToGlobalMapping\n#endif\n\ntypedef struct _n_IGA_Grid *IGA_Grid;\n\nstruct _n_IGA_Grid {\n  MPI_Comm    comm;\n  PetscInt    dim,dof;\n  PetscInt    sizes[3];\n  PetscInt    local_start[3];\n  PetscInt    local_width[3];\n  PetscInt    ghost_start[3];\n  PetscInt    ghost_width[3];\n  AO          ao;\n  LGMap       lgmap;\n  PetscLayout map;\n  Vec         lvec,gvec,nvec;\n  VecScatter  g2l,l2g,g2n;\n};\n\nPETSC_EXTERN PetscErrorCode IGA_Grid_Create(MPI_Comm,IGA_Grid*);\nPETSC_EXTERN PetscErrorCode IGA_Grid_Init(IGA_Grid,\n                                          PetscInt,PetscInt,\n                                          const PetscInt[],\n                                          const PetscInt[],\n                                          const PetscInt[],\n                                          const PetscInt[],\n                                          const PetscInt[]);\nPETSC_EXTERN PetscErrorCode IGA_Grid_Reset(IGA_Grid);\nPETSC_EXTERN PetscErrorCode IGA_Grid_Destroy(IGA_Grid*);\nPETSC_EXTERN PetscErrorCode IGA_Grid_LocalIndices(IGA_Grid,PetscInt,PetscInt*,PetscInt*[]);\nPETSC_EXTERN PetscErrorCode IGA_Grid_GhostIndices(IGA_Grid,PetscInt,PetscInt*,PetscInt*[]);\nPETSC_EXTERN PetscErrorCode IGA_Grid_SetAO(IGA_Grid,AO);\nPETSC_EXTERN PetscErrorCode IGA_Grid_GetAO(IGA_Grid,AO*);\nPETSC_EXTERN PetscErrorCode IGA_Grid_SetLGMap(IGA_Grid,LGMap);\nPETSC_EXTERN PetscErrorCode IGA_Grid_GetLGMap(IGA_Grid,LGMap*);\nPETSC_EXTERN PetscErrorCode IGA_Grid_GetLayout(IGA_Grid,PetscLayout*);\nPETSC_EXTERN PetscErrorCode IGA_Grid_GetVecLocal  (IGA_Grid,const VecType,Vec*);\nPETSC_EXTERN PetscErrorCode IGA_Grid_GetVecGlobal (IGA_Grid,const VecType,Vec*);\nPETSC_EXTERN PetscErrorCode IGA_Grid_GetVecNatural(IGA_Grid,const VecType,Vec*);\nPETSC_EXTERN PetscErrorCode IGA_Grid_GetScatterG2L(IGA_Grid,VecScatter*);\nPETSC_EXTERN PetscErrorCode IGA_Grid_GetScatterL2G(IGA_Grid,VecScatter*);\nPETSC_EXTERN PetscErrorCode IGA_Grid_GetScatterG2N(IGA_Grid,VecScatter*);\n\nPETSC_EXTERN PetscErrorCode IGA_Grid_GlobalToLocal(IGA_Grid,Vec,Vec);\nPETSC_EXTERN PetscErrorCode IGA_Grid_LocalToGlobal(IGA_Grid,Vec,Vec,InsertMode);\nPETSC_EXTERN PetscErrorCode IGA_Grid_NaturalToGlobal(IGA_Grid,Vec,Vec);\nPETSC_EXTERN PetscErrorCode IGA_Grid_GlobalToNatural(IGA_Grid,Vec,Vec);\n\nPETSC_EXTERN PetscErrorCode IGA_Grid_NewScatterApp(IGA_Grid g,\n                                                   const PetscInt[],\n                                                   const PetscInt[],\n                                                   const PetscInt[],\n                                                   const PetscInt[],\n                                                   Vec*,VecScatter*,VecScatter*);\n\n#endif/*PETIGAGRID_H*/\n", "meta": {"hexsha": "9ed4e980da268cc276ed790cda48dbe9b093ba84", "size": 2794, "ext": "h", "lang": "C", "max_stars_repo_path": "src/petigagrid.h", "max_stars_repo_name": "dalcinl/PetIGA", "max_stars_repo_head_hexsha": "a1ffe3be8710dbc0ee43e7b9adff99d4059784d8", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T17:19:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T19:56:49.000Z", "max_issues_repo_path": "src/petigagrid.h", "max_issues_repo_name": "dalcinl/PetIGA", "max_issues_repo_head_hexsha": "a1ffe3be8710dbc0ee43e7b9adff99d4059784d8", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/petigagrid.h", "max_forks_repo_name": "dalcinl/PetIGA", "max_forks_repo_head_hexsha": "a1ffe3be8710dbc0ee43e7b9adff99d4059784d8", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.65625, "max_line_length": 91, "alphanum_fraction": 0.6692913386, "num_tokens": 675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23934934732271165, "lm_q2_score": 0.03161876761083971, "lm_q1q2_score": 0.007567931390802979}}
{"text": "#ifndef OPENMC_TALLIES_FILTER_CELL_INSTANCE_H\n#define OPENMC_TALLIES_FILTER_CELL_INSTANCE_H\n\n#include <cstdint>\n#include <unordered_map>\n\n#include <gsl/gsl>\n\n#include \"openmc/cell.h\"\n#include \"openmc/tallies/filter.h\"\n#include \"openmc/vector.h\"\n\nnamespace openmc {\n\n//==============================================================================\n//! Specifies cell instances that tally events reside in.\n//==============================================================================\n\nclass CellInstanceFilter : public Filter {\npublic:\n  //----------------------------------------------------------------------------\n  // Constructors, destructors\n\n  CellInstanceFilter() = default;\n  CellInstanceFilter(gsl::span<CellInstance> instances);\n  ~CellInstanceFilter() = default;\n\n  //----------------------------------------------------------------------------\n  // Methods\n\n  std::string type() const override { return \"cellinstance\"; }\n\n  void from_xml(pugi::xml_node node) override;\n\n  void get_all_bins(const Particle& p, TallyEstimator estimator,\n    FilterMatch& match) const override;\n\n  void to_statepoint(hid_t filter_group) const override;\n\n  std::string text_label(int bin) const override;\n\n  //----------------------------------------------------------------------------\n  // Accessors\n\n  const vector<CellInstance>& cell_instances() const { return cell_instances_; }\n\n  const std::unordered_set<int32_t>& cells() const { return cells_; }\n\n  void set_cell_instances(gsl::span<CellInstance> instances);\n\nprivate:\n  //----------------------------------------------------------------------------\n  // Data members\n\n  //! The indices of the cells binned by this filter.\n  vector<CellInstance> cell_instances_;\n\n  //! The set of cells used in this filter\n  std::unordered_set<int32_t> cells_;\n\n  //! A map from cell/instance indices to filter bin indices.\n  std::unordered_map<CellInstance, gsl::index, CellInstanceHash> map_;\n\n  //! Indicates if filter uses only material-filled cells\n  bool material_cells_only_;\n};\n\n} // namespace openmc\n\n#endif // OPENMC_TALLIES_FILTER_CELL_INSTANCE_H\n", "meta": {"hexsha": "d74850df757f86b713592394121a7772615d5e7b", "size": 2095, "ext": "h", "lang": "C", "max_stars_repo_path": "include/openmc/tallies/filter_cell_instance.h", "max_stars_repo_name": "stu314159/openmc", "max_stars_repo_head_hexsha": "2efe223404680099f9a77214e743ab78e37cd08c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-09T17:55:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-09T17:55:14.000Z", "max_issues_repo_path": "include/openmc/tallies/filter_cell_instance.h", "max_issues_repo_name": "huak95/openmc", "max_issues_repo_head_hexsha": "922f688978693761f82c4a3764ab05dd96cc8cff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/openmc/tallies/filter_cell_instance.h", "max_forks_repo_name": "huak95/openmc", "max_forks_repo_head_hexsha": "922f688978693761f82c4a3764ab05dd96cc8cff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5070422535, "max_line_length": 80, "alphanum_fraction": 0.5809069212, "num_tokens": 399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18713268216242654, "lm_q2_score": 0.040237943199081735, "lm_q1q2_score": 0.007529834235543535}}
{"text": "/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*\n**                                                                                  **\n** This file forms part of the Underworld geophysics modelling application.         **\n**                                                                                  **\n** For full license and copyright information, please refer to the LICENSE.md file  **\n** located at the project root, or contact the authors.                             **\n**                                                                                  **\n**~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/\n#ifndef __BSSCR_SUM_h__\n#define __BSSCR_SUM_h__\n\n#include <petsc.h>\n#include <petscmat.h>\n#include <petscvec.h>\n#include <petscksp.h>\n#include <petscpc.h>\n#include <StGermain/libStGermain/src/StGermain.h>\n#include <StgDomain/libStgDomain/src/StgDomain.h>\n#include <StgFEM/libStgFEM/src/StgFEM.h>\n#include <PICellerator/libPICellerator/src/PICellerator.h>\n#include <Underworld/libUnderworld/src/Underworld.h>\n#include \"Solvers/KSPSolvers/src/KSPSolvers.h\"\n\n#include \"common-driver-utils.h\"\n#include \"BSSCR.h\" /* includes StokesBlockKSPInterface.h */\n\n//void bsscr_summary(KSP_BSSCR * bsscrp_self, KSP ksp_S, KSP ksp_inner, Mat K,Mat Korig,Mat K2,Mat D,Mat G,Mat C,Vec u,Vec p,Vec f,Vec h,Vec t,\n\nvoid bsscr_summary(KSP_BSSCR * bsscrp_self, KSP ksp_S, KSP ksp_inner, Mat K,Mat K2,Mat D,Mat G,Mat C,Vec u,Vec p,Vec f,Vec h,Vec t,\n\t\t   double penaltyNumber,PetscTruth KisJustK,double mgSetupTime, double RHSSolveTime, double scrSolveTime,double a11SingleSolveTime);\n\n#endif\n", "meta": {"hexsha": "62eacfea83a534d0032ed24d84d8aac16711fc90", "size": 1667, "ext": "h", "lang": "C", "max_stars_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/summary.h", "max_stars_repo_name": "rbeucher/underworld2", "max_stars_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/summary.h", "max_issues_repo_name": "rbeucher/underworld2", "max_issues_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/summary.h", "max_forks_repo_name": "rbeucher/underworld2", "max_forks_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.5151515152, "max_line_length": 143, "alphanum_fraction": 0.5560887822, "num_tokens": 554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.39981165504266236, "lm_q2_score": 0.018833131955561747, "lm_q1q2_score": 0.007529705656789994}}
{"text": "#include \"scripts.h\"\n#include \"utility/fileutils.h\"\n#include \"lua.h\"\n#include \"lauxlib.h\"\n#include \"subsystems.h\"\n#include \"rendering/rendering.h\"\n#include <gsl/gsl_math.h>\n\n/**\n * Retrieve the integer value in the table at the top of the stack\n * associated with the specified key.\n */\nsd_result get_int_field(lua_State *L, const char *key, int *out) {\n  lua_getfield(L, -1, key);\n  if (!lua_isnumber(L, -1)) {\n    return SD_SCRIPT_TYPE_ERROR;\n  }\n  *out = (int)lua_tonumber(L, -1);\n  lua_pop(L, 1);\n  return SD_OK;\n}\n\n/**\n * Retrieve the double value in the table at the top of the stack\n * associated with the specified key.\n */\nsd_result get_double_field(lua_State *L, const char *key, double *out) {\n  lua_getfield(L, -1, key);\n  if (!lua_isnumber(L, -1)) {\n    return SD_SCRIPT_TYPE_ERROR;\n  }\n  *out = lua_tonumber(L, -1);\n  lua_pop(L, 1);\n  return SD_OK;\n}\n\n/**\n * Retrieve the string value in the table at the top of the stack\n * associated with the specified key.\n */\nsd_result get_string_field(lua_State *L, const char *key, char *out, size_t out_size) {\n  lua_getfield(L, -1, key);\n  if (!lua_isstring(L, -1)) {\n    return SD_SCRIPT_TYPE_ERROR;\n  }\n  size_t max = GSL_MIN(lua_rawlen(L, -1), out_size);\n  strncpy(out, lua_tostring(L, -1), max);\n  lua_pop(L, 1);\n  return SD_OK;\n}\n\n/**\n * Retrieve the boolean value in the table at the top of the stack\n * associated with the specified key.\n */\nsd_result get_bool_field(lua_State *L, const char *key, char *out) {\n  lua_getfield(L, -1, key);\n  if (!lua_isboolean(L, -1)) {\n    return SD_SCRIPT_TYPE_ERROR;\n  }\n  *out = lua_toboolean(L, -1);\n  lua_pop(L, 1);\n  return SD_OK;\n}\n\nsd_result read_init_info(const char *resource_path, initialization_params *out) {\n  lua_State *L = luaL_newstate();\n  bzero(out, sizeof(initialization_params));\n  window_creation_info *winfo = calloc(1, sizeof(window_creation_info));\n  out->window_info = winfo;\n\n  char *file_path = NULL;\n  fileutils.get_full_path(resource_path, &file_path);\n  if (luaL_loadfile(L, file_path) || lua_pcall(L, 0, 0, 0)) {\n    printf(\"Problem loading file %s\\n\", file_path);\n    return SD_GEN_ERROR;\n  }\n  lua_getglobal(L, \"timer\");\n  if (!lua_isstring(L, -1)) {\n    printf(\"Timer type is not a string\\n\");\n    return SD_SCRIPT_TYPE_ERROR;\n  }\n  const char *timer_type = lua_tostring(L,-1);\n  if (strncasecmp(\"glfw\", timer_type, lua_rawlen(L, -1))) {\n    printf(\"glfw timer specified\\n\");\n  };\n  out->timer_function = glfwGetTime;\n  lua_pop(L, 1);\n\n  lua_getglobal(L, \"window\");\n  if (!lua_istable(L, -1)) {\n    printf(\"Window description is not a table\\n\");\n    return SD_SCRIPT_TYPE_ERROR;\n  }\n\n  get_int_field(L, \"w\", &winfo->width);\n  get_int_field(L, \"h\", &winfo->height);\n  get_bool_field(L, \"full_screen\", &winfo->full_screen);\n  get_string_field(L, \"title\", winfo->window_title, \n                  sizeof(winfo->window_title));\n\n  // Sub table\n  lua_getfield(L, -1, \"clear_color\");\n  double dbuffer;\n  get_double_field(L, \"R\", &dbuffer);\n  winfo->clear_color[0] = (GLfloat)dbuffer;\n  get_double_field(L, \"G\", &dbuffer);\n  winfo->clear_color[1] = (GLfloat)dbuffer;\n  get_double_field(L, \"B\", &dbuffer);\n  winfo->clear_color[2] = (GLfloat)dbuffer;\n  get_double_field(L, \"A\", &dbuffer);\n  winfo->clear_color[3] = (GLfloat)dbuffer;\n  lua_pop(L, 1);\n\n  return SD_OK;\n}\n\nscripts_struct const scripts = {\n  .read_init_info=read_init_info\n};\n", "meta": {"hexsha": "49851c8a168b64c2f731b6c8efe1a28df45b64d9", "size": 3361, "ext": "c", "lang": "C", "max_stars_repo_path": "src/scripts/scripts.c", "max_stars_repo_name": "influenza/c8", "max_stars_repo_head_hexsha": "2cc34f384cedce9626e76be8ea22e5967db1b69b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/scripts/scripts.c", "max_issues_repo_name": "influenza/c8", "max_issues_repo_head_hexsha": "2cc34f384cedce9626e76be8ea22e5967db1b69b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/scripts/scripts.c", "max_forks_repo_name": "influenza/c8", "max_forks_repo_head_hexsha": "2cc34f384cedce9626e76be8ea22e5967db1b69b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7768595041, "max_line_length": 87, "alphanum_fraction": 0.6786670634, "num_tokens": 1006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20434189024594807, "lm_q2_score": 0.036769468582465784, "lm_q1q2_score": 0.007513542713480059}}
{"text": "/**\n* Copyright 2016 BitTorrent Inc.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n*    http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*/\n#pragma once\n\n#include <scraps/config.h>\n\n#include <scraps/base64.h>\n#include <scraps/Byte.h>\n#include <scraps/hex.h>\n#include <scraps/Temp.h>\n#include <scraps/random.h>\n#include <scraps/hash.h>\n#include <stdts/optional.h>\n\n#include <gsl.h>\n\n#include <cerrno>\n#include <vector>\n#include <iterator>\n#include <random>\n#include <chrono>\n\nnamespace scraps {\n\nconstexpr double kPi = 3.1415926535897932385;\n\n/**\n* Returns a string escaped according to RFC 4627.\n*\n* @param the string to be escaped\n* @return the string escaped according to RFC 4627\n*/\nstd::string JSONEscape(const char* str);\n\n/**\n* Returns a string in which all non-alphanumeric characters except dashes, underscores,\n* spaces, and periods are replaced with a percent sign followed by their hexadecimal\n* value. Spaces are replaced with plus signs.\n*\n* @return the url-encoded string\n*/\nstd::string URLEncode(const char* str);\n\ninline std::string URLEncode(const std::string& str) { return URLEncode(str.c_str()); }\n\n/**\n* Returns a string in which the effects of URLEncode have been reversed.\n*\n* @return the url-decoded string\n*/\nstd::string URLDecode(const char* str);\n\ninline std::string URLDecode(const std::string& str) { return URLDecode(str.c_str()); }\n\n/**\n * Clamp a value between min and max, inclusive.\n */\ntemplate <typename T, typename MinT, typename MaxT>\nconstexpr auto Clamp(const T& value, const MinT& min, const MaxT& max) {\n    return std::max<std::common_type_t<T, MinT, MaxT>>(min, std::min<std::common_type_t<T, MinT, MaxT>>(value, max));\n}\n\n/**\n* Parse out an address and port from the given host string. If a port is not found, the\n* defaultPort is returned.\n*/\nstd::tuple<std::string, uint16_t> ParseAddressAndPort(const std::string& host, uint16_t defaultPort);\n\n/**\n* @return the amount of physical memory that the system has, or 0 on error\n*/\nsize_t PhysicalMemory();\n\n/**\n* Iterates over a container, allowing for safe modification of the container at any point.\n*/\ntemplate <typename T, typename F>\nvoid NonatomicIteration(T&& iterable, F&& function) {\n    auto copy = iterable;\n    for (auto& element : copy) {\n        auto it = std::find(iterable.begin(), iterable.end(), element);\n        if (it == iterable.end()) {\n            continue;\n        }\n        function(element);\n    }\n}\n\ntemplate <typename T, std::ptrdiff_t N>\ngsl::basic_string_span<T> TrimLeft(gsl::basic_string_span<T, N> str) {\n    decltype(str.size()) i = 0;\n    while(i < str.size() && isspace(str[i])) { ++i; };\n    return {str.data() + i, static_cast<std::ptrdiff_t>(str.size() - i)};\n}\n\ntemplate <typename T, std::ptrdiff_t N>\ngsl::basic_string_span<T> TrimRight(gsl::basic_string_span<T, N> str) {\n    decltype(str.size()) i = str.size();\n    while(i > 0 && isspace(str[i - 1])) { --i; };\n    return {str.data(), static_cast<std::ptrdiff_t>(i)};\n}\n\ntemplate <typename T, std::ptrdiff_t N>\nauto Trim(gsl::basic_string_span<T, N> str) {\n    return TrimLeft(TrimRight(str));\n}\n\nstdts::optional<std::vector<Byte>> BytesFromFile(const std::string& path);\n\n/**\n* Sets the given file descriptor to blocking or non-blocking.\n*\n* @param fd the file descriptor\n* @param blocking true if the file descriptor should be set to blocking. false if it should be set to non-blocking\n* @return true on success\n*/\nbool SetBlocking(int fd, bool blocking = true);\n\n/**\n* Returns a demangled symbol name. If demangling is not supported, returns original mangled name.\n*/\nstd::string Demangle(const char* name);\n\n/**\n* Returns whether two strings are equal disregarding case\n*/\ninline bool CaseInsensitiveEquals(stdts::string_view l, stdts::string_view r) {\n    return l.size() == r.size() && std::equal(l.begin(), l.end(), r.begin(), [](char a, char b){ return tolower(a) == tolower(b); });\n}\n\n/**\n* Split a sequence on a delimiter. The SequenceType template argument should be\n* specified to the type of container OutputIt should accept. By default, it is\n* set OutputIt::container_type::value_type.\n*\n* @param begin beginning of input sequence\n* @param end end of input sequence\n* @param out output iterator to a container of Sequence types\n* @param delimiter a single element element in the sequence\n*/\ntemplate <typename InputIt, typename OutputIt, typename Delimiter, typename SequenceType = typename OutputIt::container_type::value_type>\nvoid Split(InputIt&& begin, InputIt&& end, OutputIt&& out, Delimiter&& delimiter) {\n    SequenceType current;\n    auto inserter = std::back_inserter(current);\n    for (auto it = begin; it != end; ++it) {\n        if (*it == delimiter) {\n            *(out++) = std::move(current);\n            current = {};\n            inserter = std::back_inserter(current);\n        } else {\n            inserter = *it;\n        }\n    }\n    *out = std::move(current);\n}\n\n} // namespace scraps\n", "meta": {"hexsha": "304cf324257501f2322ec7f57eadfb325a65a1d6", "size": 5351, "ext": "h", "lang": "C", "max_stars_repo_path": "include/scraps/utility.h", "max_stars_repo_name": "carlbrown/scraps", "max_stars_repo_head_hexsha": "78925a738540415ec04b9cbe23cb319421f44978", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/scraps/utility.h", "max_issues_repo_name": "carlbrown/scraps", "max_issues_repo_head_hexsha": "78925a738540415ec04b9cbe23cb319421f44978", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/scraps/utility.h", "max_forks_repo_name": "carlbrown/scraps", "max_forks_repo_head_hexsha": "78925a738540415ec04b9cbe23cb319421f44978", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2923976608, "max_line_length": 137, "alphanum_fraction": 0.696879088, "num_tokens": 1337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18952109132967757, "lm_q2_score": 0.039638841369975954, "lm_q1q2_score": 0.007512396475481814}}
{"text": "#include <ceed.h>\n#include <petsc.h>\n#include \"../problems/problems.h\"\n\nPetscErrorCode RegisterProblems(ProblemFunctions problem_functions) {\n  PetscErrorCode ierr;\n\n  PetscFunctionBegin;\n\n  SOLIDS_PROBLEM_REGISTER(problem_functions, \"Linear\", ElasLinear, NH);\n  SOLIDS_PROBLEM_REGISTER(problem_functions, \"SS-NH\", ElasSSNH, NH);\n  SOLIDS_PROBLEM_REGISTER(problem_functions, \"FSCurrent-NH1\", ElasFSCurrentNH1,\n                          NH);\n  SOLIDS_PROBLEM_REGISTER(problem_functions, \"FSCurrent-NH2\", ElasFSCurrentNH2,\n                          NH);\n  SOLIDS_PROBLEM_REGISTER(problem_functions, \"FSInitial-NH1\", ElasFSInitialNH1,\n                          NH);\n  SOLIDS_PROBLEM_REGISTER(problem_functions, \"FSInitial-NH2\", ElasFSInitialNH2,\n                          NH);\n  SOLIDS_PROBLEM_REGISTER(problem_functions, \"FSInitial-MR1\", ElasFSInitialMR1,\n                          MR);\n\n  PetscFunctionReturn(0);\n};\n", "meta": {"hexsha": "01531b6e9423d18d646778c289abff77f8adf86f", "size": 915, "ext": "c", "lang": "C", "max_stars_repo_path": "examples/solids/problems/problems.c", "max_stars_repo_name": "AdelekeBankole/libCEED", "max_stars_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 123.0, "max_stars_repo_stars_event_min_datetime": "2018-01-29T02:04:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T18:13:48.000Z", "max_issues_repo_path": "examples/solids/problems/problems.c", "max_issues_repo_name": "AdelekeBankole/libCEED", "max_issues_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 781.0, "max_issues_repo_issues_event_min_datetime": "2017-12-22T17:20:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T21:34:34.000Z", "max_forks_repo_path": "examples/solids/problems/problems.c", "max_forks_repo_name": "AdelekeBankole/libCEED", "max_forks_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2017-12-27T22:35:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:02:07.000Z", "avg_line_length": 36.6, "max_line_length": 79, "alphanum_fraction": 0.6885245902, "num_tokens": 221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.341582499438317, "lm_q2_score": 0.021948255434202448, "lm_q1q2_score": 0.0074971399495254954}}
{"text": "#pragma once\n\n#include \"CesiumUtility/Library.h\"\n#include <cmath>\n#include <cstdint>\n#include <gsl/narrow>\n#include <initializer_list>\n#include <map>\n#include <optional>\n#include <stdexcept>\n#include <string>\n#include <string_view>\n#include <type_traits>\n#include <variant>\n#include <vector>\n\nnamespace CesiumUtility {\n\nstruct JsonValueMissingKey : public std::runtime_error {\n  JsonValueMissingKey(const std::string& key)\n      : std::runtime_error(key + \" is not present in Object\") {}\n};\n\nstruct JsonValueNotRealValue : public std::runtime_error {\n  JsonValueNotRealValue()\n      : std::runtime_error(\"this->value was not double, uint64_t or int64_t\") {}\n};\n\ntemplate <typename T, typename U>\nconstexpr T losslessNarrowOrDefault(U u, T defaultValue) noexcept {\n  constexpr const bool is_different_signedness =\n      (std::is_signed<T>::value != std::is_signed<U>::value);\n\n  const T t = gsl::narrow_cast<T>(u);\n\n  if (static_cast<U>(t) != u ||\n      (is_different_signedness && ((t < T{}) != (u < U{})))) {\n    return defaultValue;\n  }\n\n  return t;\n}\n\n/**\n * @brief A generic implementation of a value in a JSON structure.\n *\n * Instances of this class are used to represent the common `extras` field\n * of glTF elements that extend the the {@link ExtensibleObject} class.\n */\nclass CESIUMUTILITY_API JsonValue final {\npublic:\n  /**\n   * @brief The type to represent a `null` JSON value.\n   */\n  using Null = std::nullptr_t;\n\n  /**\n   * @brief The type to represent a `Bool` JSON value.\n   */\n  using Bool = bool;\n\n  /**\n   * @brief The type to represent a `String` JSON value.\n   */\n  using String = std::string;\n\n  /**\n   * @brief The type to represent an `Object` JSON value.\n   */\n  using Object = std::map<std::string, JsonValue>;\n\n  /**\n   * @brief The type to represent an `Array` JSON value.\n   */\n  using Array = std::vector<JsonValue>;\n\n  /**\n   * @brief Default constructor.\n   */\n  JsonValue() : value() {}\n\n  /**\n   * @brief Creates a `null` JSON value.\n   */\n  JsonValue(std::nullptr_t) : value(nullptr) {}\n\n  /**\n   * @brief Creates a `Number` JSON value.\n   *\n   * NaN and \u00b1Infinity are represented as {@link JsonValue::Null}.\n   */\n  JsonValue(double v) {\n    if (std::isnan(v) || std::isinf(v)) {\n      value = nullptr;\n    } else {\n      value = v;\n    }\n  }\n\n  /**\n   * @brief Creates a `std::int64_t` JSON value (Widening conversion from\n   * std::int8_t).\n   */\n  JsonValue(std::int8_t v) : value(static_cast<std::int64_t>(v)) {}\n\n  /**\n   * @brief Creates a `std::uint64_t` JSON value (Widening conversion from\n   * std::uint8_t).\n   */\n  JsonValue(std::uint8_t v) : value(static_cast<std::uint64_t>(v)) {}\n\n  /**\n   * @brief Creates a `std::int64_t` JSON value (Widening conversion from\n   * std::int16_t).\n   */\n  JsonValue(std::int16_t v) : value(static_cast<std::int64_t>(v)) {}\n\n  /**\n   * @brief Creates a `std::uint64_t` JSON value (Widening conversion from\n   * std::uint16_t).\n   */\n  JsonValue(std::uint16_t v) : value(static_cast<std::uint64_t>(v)) {}\n\n  /**\n   * @brief Creates a `std::int64_t` JSON value (Widening conversion from\n   * std::int32_t).\n   */\n  JsonValue(std::int32_t v) : value(static_cast<std::int64_t>(v)) {}\n\n  /**\n   * @brief Creates a `std::uint64_t` JSON value (Widening conversion from\n   * std::uint32_t).\n   */\n  JsonValue(std::uint32_t v) : value(static_cast<std::uint64_t>(v)) {}\n\n  /**\n   * @brief Creates a `std::int64_t` JSON value.\n   */\n  JsonValue(std::int64_t v) : value(v) {}\n\n  /**\n   * @brief Creates a `std::uint64_t` JSON value.\n   */\n  JsonValue(std::uint64_t v) : value(v) {}\n\n  /**\n   * @brief Creates a `Bool` JSON value.\n   */\n  JsonValue(bool v) : value(v) {}\n\n  /**\n   * @brief Creates a `String` JSON value.\n   */\n  JsonValue(const std::string& v) : value(v) {}\n\n  /**\n   * @brief Creates a `String` JSON value.\n   */\n  JsonValue(std::string&& v) : value(std::move(v)) {}\n\n  /**\n   * @brief Creates a `String` JSON value.\n   */\n  JsonValue(const char* v) : value(std::string(v)) {}\n\n  /**\n   * @brief Creates an `Object` JSON value with the given properties.\n   */\n  JsonValue(const std::map<std::string, JsonValue>& v) : value(v) {}\n\n  /**\n   * @brief Creates an `Object` JSON value with the given properties.\n   */\n  JsonValue(std::map<std::string, JsonValue>&& v) : value(std::move(v)) {}\n\n  /**\n   * @brief Creates an `Array` JSON value with the given elements.\n   */\n  JsonValue(const std::vector<JsonValue>& v) : value(v) {}\n\n  /**\n   * @brief Creates an `Array` JSON value with the given elements.\n   */\n  JsonValue(std::vector<JsonValue>&& v) : value(std::move(v)) {}\n\n  /**\n   * @brief Creates an JSON value from the given initializer list.\n   */\n  JsonValue(std::initializer_list<JsonValue> v)\n      : value(std::vector<JsonValue>(v)) {}\n\n  /**\n   * @brief Creates an JSON value from the given initializer list.\n   */\n  JsonValue(std::initializer_list<std::pair<const std::string, JsonValue>> v)\n      : value(std::map<std::string, JsonValue>(v)) {}\n\n  [[nodiscard]] const JsonValue*\n  getValuePtrForKey(const std::string& key) const;\n  [[nodiscard]] JsonValue* getValuePtrForKey(const std::string& key);\n\n  /**\n   * @brief Gets a typed value corresponding to the given key in the\n   * object represented by this instance.\n   *\n   * If this instance is not a {@link JsonValue::Object}, returns\n   * `nullptr`. If the key does not exist in this object, returns\n   * `nullptr`. If the named value does not have the type T, returns\n   * nullptr.\n   *\n   * @tparam T The expected type of the value.\n   * @param key The key for which to retrieve the value from this object.\n   * @return A pointer to the requested value, or nullptr if the value\n   * cannot be obtained as requested.\n   */\n  template <typename T>\n  const T* getValuePtrForKey(const std::string& key) const {\n    const JsonValue* pValue = this->getValuePtrForKey(key);\n    if (!pValue) {\n      return nullptr;\n    }\n\n    return std::get_if<T>(&pValue->value);\n  }\n\n  /**\n   * @brief Gets a typed value corresponding to the given key in the\n   * object represented by this instance.\n   *\n   * If this instance is not a {@link JsonValue::Object}, returns\n   * `nullptr`. If the key does not exist in this object, returns\n   * `nullptr`. If the named value does not have the type T, returns\n   * nullptr.\n   *\n   * @tparam T The expected type of the value.\n   * @param key The key for which to retrieve the value from this object.\n   * @return A pointer to the requested value, or nullptr if the value\n   * cannot be obtained as requested.\n   */\n  template <typename T> T* getValuePtrForKey(const std::string& key) {\n    JsonValue* pValue = this->getValuePtrForKey(key);\n    return std::get_if<T>(&pValue->value);\n  }\n\n  /**\n   * @brief Converts the numerical value corresponding to the given key\n   * to the provided numerical template type.\n\n   * If this instance is not a {@link JsonValue::Object}, throws\n   * `std::bad_variant_access`. If the key does not exist in this object, throws\n   * `JsonValueMissingKey`. If the named value does not have a numerical type T,\n   *  throws `JsonValueNotRealValue`, if the named value cannot be converted\n   from\n   * `double` / `std::uint64_t` / `std::int64_t` without precision loss, throws\n   * `gsl::narrowing_error`\n   * @tparam To The expected type of the value.\n   * @param key The key for which to retrieve the value from this object.\n   * @return The converted value.\n   * @throws If unable to convert the converted value for one of the\n   aforementioned reasons.\n   * @remarks Compilation will fail if type 'To' is not an integral / float /\n   double type.\n   */\n  template <\n      typename To,\n      typename std::enable_if<\n          std::is_integral<To>::value ||\n          std::is_floating_point<To>::value>::type* = nullptr>\n  [[nodiscard]] To getSafeNumericalValueForKey(const std::string& key) const {\n    const Object& pObject = std::get<Object>(this->value);\n    const auto it = pObject.find(key);\n    if (it == pObject.end()) {\n      throw JsonValueMissingKey(key);\n    }\n    return it->second.getSafeNumber<To>();\n  }\n\n  /**\n   * @brief Converts the numerical value corresponding to the given key\n   * to the provided numerical template type.\n   *\n   * If this instance is not a {@link JsonValue::Object}, the key does not exist\n   * in this object, or the named value does not have a numerical type that can\n   * be represented as T without precision loss, then the default value is\n   * returned.\n   *\n   * @tparam To The expected type of the value.\n   * @param key The key for which to retrieve the value from this object.\n   * @return The converted value.\n   * @throws If unable to convert the converted value for one of the\n   * aforementioned reasons.\n   * @remarks Compilation will fail if type 'To' is not an integral / float /\n   * double type.\n   */\n  template <\n      typename To,\n      typename std::enable_if<\n          std::is_integral<To>::value ||\n          std::is_floating_point<To>::value>::type* = nullptr>\n  [[nodiscard]] To getSafeNumericalValueOrDefaultForKey(\n      const std::string& key,\n      To defaultValue) const {\n    const Object& pObject = std::get<Object>(this->value);\n    const auto it = pObject.find(key);\n    if (it == pObject.end()) {\n      return defaultValue;\n    }\n    return it->second.getSafeNumberOrDefault<To>(defaultValue);\n  }\n\n  /**\n   * @brief Determines if this value is an Object and has the given key.\n   *\n   * @param key The key.\n   * @return true if this value contains the key. false if it is not an object\n   * or does not contain the given key.\n   */\n  [[nodiscard]] inline bool hasKey(const std::string& key) const {\n    const Object* pObject = std::get_if<Object>(&this->value);\n    if (!pObject) {\n      return false;\n    }\n\n    return pObject->find(key) != pObject->end();\n  }\n\n  /**\n   * @brief Gets the numerical quantity from the value casted to the `To`\n   * type. This function should be used over `getDouble()` / `getUint64()` /\n   * `getInt64()` if you plan on casting that type into another smaller type or\n   * different type.\n   * @returns The converted type if it can be cast without precision loss.\n   * @throws If the underlying value is not a numerical type or it cannot be\n   *         converted without precision loss.\n   */\n  template <\n      typename To,\n      typename std::enable_if<\n          std::is_integral<To>::value ||\n          std::is_floating_point<To>::value>::type* = nullptr>\n  [[nodiscard]] To getSafeNumber() const {\n    const std::uint64_t* uInt = std::get_if<std::uint64_t>(&this->value);\n    if (uInt) {\n      return gsl::narrow<To>(*uInt);\n    }\n\n    const std::int64_t* sInt = std::get_if<std::int64_t>(&this->value);\n    if (sInt) {\n      return gsl::narrow<To>(*sInt);\n    }\n\n    const double* real = std::get_if<double>(&this->value);\n    if (real) {\n      return gsl::narrow<To>(*real);\n    }\n\n    throw JsonValueNotRealValue();\n  }\n\n  /**\n   * @brief Gets the numerical quantity from the value casted to the `To`\n   * type or returns defaultValue if unable to do so.\n\n   * @returns The converted type if it can be cast without precision loss\n   * or `defaultValue` if it cannot be converted safely.\n   */\n  template <\n      typename To,\n      typename std::enable_if<\n          std::is_integral<To>::value ||\n          std::is_floating_point<To>::value>::type* = nullptr>\n  [[nodiscard]] To getSafeNumberOrDefault(To defaultValue) const noexcept {\n    const std::uint64_t* uInt = std::get_if<std::uint64_t>(&this->value);\n    if (uInt) {\n      return losslessNarrowOrDefault<To>(*uInt, defaultValue);\n    }\n\n    const std::int64_t* sInt = std::get_if<std::int64_t>(&this->value);\n    if (sInt) {\n      return losslessNarrowOrDefault<To>(*sInt, defaultValue);\n    }\n\n    const double* real = std::get_if<double>(&this->value);\n    if (real) {\n      return losslessNarrowOrDefault<To>(*real, defaultValue);\n    }\n\n    return defaultValue;\n  }\n\n  /**\n   * @brief Gets the object from the value.\n   * @return The object.\n   * @throws std::bad_variant_access if the underlying type is not a\n   * JsonValue::Object\n   */\n\n  [[nodiscard]] inline const JsonValue::Object& getObject() const {\n    return std::get<JsonValue::Object>(this->value);\n  }\n\n  /**\n   * @brief Gets the string from the value.\n   * @return The string.\n   * @throws std::bad_variant_access if the underlying type is not a\n   * JsonValue::String\n   */\n  [[nodiscard]] inline const JsonValue::String& getString() const {\n    return std::get<String>(this->value);\n  }\n\n  /**\n   * @brief Gets the array from the value.\n   * @return The arrayj.\n   * @throws std::bad_variant_access if the underlying type is not a\n   * JsonValue::Array\n   */\n  [[nodiscard]] inline const JsonValue::Array& getArray() const {\n    return std::get<JsonValue::Array>(this->value);\n  }\n\n  /**\n   * @brief Gets the bool from the value.\n   * @return The bool.\n   * @throws std::bad_variant_access if the underlying type is not a\n   * JsonValue::Bool\n   */\n  [[nodiscard]] inline bool getBool() const {\n    return std::get<bool>(this->value);\n  }\n\n  /**\n   * @brief Gets the double from the value.\n   * @return The double.\n   * @throws std::bad_variant_access if the underlying type is not a double\n   */\n  [[nodiscard]] inline double getDouble() const {\n    return std::get<double>(this->value);\n  }\n\n  /**\n   * @brief Gets the std::uint64_t from the value.\n   * @return The std::uint64_t.\n   * @throws std::bad_variant_access if the underlying type is not a\n   * std::uint64_t\n   */\n  [[nodiscard]] std::uint64_t getUint64() const {\n    return std::get<std::uint64_t>(this->value);\n  }\n\n  /**\n   * @brief Gets the std::int64_t from the value.\n   * @return The std::int64_t.\n   * @throws std::bad_variant_access if the underlying type is not a\n   * std::int64_t\n   */\n  [[nodiscard]] std::int64_t getInt64() const {\n    return std::get<std::int64_t>(this->value);\n  }\n\n  /**\n   * @brief Gets the bool from the value or returns defaultValue\n   * @return The bool or defaultValue if this->value is not a bool.\n   */\n  [[nodiscard]] inline bool getBoolOrDefault(bool defaultValue) const {\n    const auto* v = std::get_if<bool>(&this->value);\n    if (v) {\n      return *v;\n    }\n\n    return defaultValue;\n  }\n\n  /**\n   * @brief Gets the string from the value or returns defaultValue\n   * @return The string or defaultValue if this->value is not a string.\n   */\n  [[nodiscard]] inline const JsonValue::String\n  getStringOrDefault(String defaultValue) const {\n    const auto* v = std::get_if<JsonValue::String>(&this->value);\n    if (v) {\n      return *v;\n    }\n\n    return defaultValue;\n  }\n\n  /**\n   * @brief Gets the double from the value or returns defaultValue\n   * @return The double or defaultValue if this->value is not a double.\n   */\n  [[nodiscard]] inline double getDoubleOrDefault(double defaultValue) const {\n    const auto* v = std::get_if<double>(&this->value);\n    if (v) {\n      return *v;\n    }\n\n    return defaultValue;\n  }\n\n  /**\n   * @brief Gets the uint64_t from the value or returns defaultValue\n   * @return The uint64_t or defaultValue if this->value is not a uint64_t.\n   */\n  [[nodiscard]] inline std::uint64_t\n  getUint64OrDefault(std::uint64_t defaultValue) const {\n    const auto* v = std::get_if<std::uint64_t>(&this->value);\n    if (v) {\n      return *v;\n    }\n\n    return defaultValue;\n  }\n\n  /**\n   * @brief Gets the int64_t from the value or returns defaultValue\n   * @return The int64_t or defaultValue if this->value is not a int64_t.\n   */\n  [[nodiscard]] inline std::int64_t\n  getInt64OrDefault(std::int64_t defaultValue) const {\n    const auto* v = std::get_if<std::int64_t>(&this->value);\n    if (v) {\n      return *v;\n    }\n\n    return defaultValue;\n  }\n\n  /**\n   * @brief Returns whether this value is a `null` value.\n   */\n  [[nodiscard]] inline bool isNull() const noexcept {\n    return std::holds_alternative<Null>(this->value);\n  }\n\n  /**\n   * @brief Returns whether this value is a `double`, `std::uint64_t` or\n   * `std::int64_t`. Use this function in conjunction with `getNumber` for\n   *  safely casting to arbitrary types\n   */\n  [[nodiscard]] inline bool isNumber() const noexcept {\n    return isDouble() || isUint64() || isInt64();\n  }\n\n  /**\n   * @brief Returns whether this value is a `Bool` value.\n   */\n  [[nodiscard]] inline bool isBool() const noexcept {\n    return std::holds_alternative<Bool>(this->value);\n  }\n\n  /**\n   * @brief Returns whether this value is a `String` value.\n   */\n  [[nodiscard]] inline bool isString() const noexcept {\n    return std::holds_alternative<String>(this->value);\n  }\n\n  /**\n   * @brief Returns whether this value is an `Object` value.\n   */\n  [[nodiscard]] inline bool isObject() const noexcept {\n    return std::holds_alternative<Object>(this->value);\n  }\n\n  /**\n   * @brief Returns whether this value is an `Array` value.\n   */\n  [[nodiscard]] inline bool isArray() const noexcept {\n    return std::holds_alternative<Array>(this->value);\n  }\n\n  /**\n   * @brief Returns whether this value is a `double` value.\n   */\n  [[nodiscard]] inline bool isDouble() const noexcept {\n    return std::holds_alternative<double>(this->value);\n  }\n\n  /**\n   * @brief Returns whether this value is a `std::uint64_t` value.\n   */\n  [[nodiscard]] inline bool isUint64() const noexcept {\n    return std::holds_alternative<std::uint64_t>(this->value);\n  }\n\n  /**\n   * @brief Returns whether this value is a `std::int64_t` value.\n   */\n  [[nodiscard]] inline bool isInt64() const noexcept {\n    return std::holds_alternative<std::int64_t>(this->value);\n  }\n\n  /**\n   * @brief The actual value.\n   *\n   * The type of the value may be queried with the `isNull`, `isDouble`,\n   * `isBool`, `isString`, `isObject`, `isUint64`, `isInt64`, `isNumber`, and\n   * `isArray` functions.\n   *\n   * The actual value may be obtained with the `getNumber`, `getBool`,\n   * and `getString` functions for the respective types. For\n   * `Object` values, the properties may be accessed with the\n   * `getValueForKey` functions.\n   */\n  std::variant<\n      Null,\n      double,\n      std::uint64_t,\n      std::int64_t,\n      Bool,\n      String,\n      Object,\n      Array>\n      value;\n};\n} // namespace CesiumUtility\n", "meta": {"hexsha": "52748dc5ff07cb94be61faebed67ca507446647f", "size": 18121, "ext": "h", "lang": "C", "max_stars_repo_path": "CesiumUtility/include/CesiumUtility/JsonValue.h", "max_stars_repo_name": "zrkcode/cesium-native", "max_stars_repo_head_hexsha": "5265a65053542fe02928c272762c6b89fa2b29bb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CesiumUtility/include/CesiumUtility/JsonValue.h", "max_issues_repo_name": "zrkcode/cesium-native", "max_issues_repo_head_hexsha": "5265a65053542fe02928c272762c6b89fa2b29bb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CesiumUtility/include/CesiumUtility/JsonValue.h", "max_forks_repo_name": "zrkcode/cesium-native", "max_forks_repo_head_hexsha": "5265a65053542fe02928c272762c6b89fa2b29bb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3220064725, "max_line_length": 80, "alphanum_fraction": 0.6465978699, "num_tokens": 4795, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24798742624020273, "lm_q2_score": 0.030214588268123323, "lm_q1q2_score": 0.007492837979519327}}
{"text": "#pragma once\n/*\n * (C) Copyright 2020-2021 UCAR\n *\n * This software is licensed under the terms of the Apache Licence Version 2.0\n * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.\n */\n/*! \\defgroup ioda_cxx_types Type System\n * \\brief The data type system\n * \\ingroup ioda_cxx_api\n *\n * @{\n * \\file Type.h\n * \\brief Interfaces for ioda::Type and related classes. Implements the type system.\n */\n#include <array>\n#include <cstring>\n#include <functional>\n#include <gsl/gsl-lite.hpp>\n#include <memory>\n#include <string>\n#include <typeindex>\n#include <typeinfo>\n#include <vector>\n\n#include \"ioda/Exception.h\"\n#include \"ioda/Types/Type_Provider.h\"\n#include \"ioda/defs.h\"\n\nnamespace ioda {\nclass Group;\nclass Type;\n\n/// Basic pre-defined types (Python convenience wrappers)\n/// \\see py_ioda.cpp\n/// \\note Names here do not match the Python equivalents. The\n///   Python names match numpy's definitions.\nenum class BasicTypes {\n  undefined_,  ///< Internal use only\n  float_,\n  double_,\n  ldouble_,\n  char_,\n  short_,\n  ushort_,\n  int_,\n  uint_,\n  lint_,\n  ulint_,\n  llint_,\n  ullint_,\n  int32_,\n  uint32_,\n  int16_,\n  uint16_,\n  int64_,\n  uint64_,\n  bool_,\n  str_\n};\n\n/// \\brief Data Types can be grouped into a few categories. These are the categories.\n/// \\note  Not all backends implement all types.\nenum class TypeClass {\n  Unknown,    ///< Unsupported / unhandled type\n  Integer,    ///< All integer types\n  Float,      ///< All floating-point types\n  String,     ///< All string types (fixed-length, variable, ASCII, UTF-8)\n  Bitfield,   ///< All bit fields\n  Opaque,     ///< All binary blobs\n  Compound,   ///< All compound types (types with member elements)\n  Reference,  ///< All object references\n  Enum,       ///< All enumerated types\n  VlenArray,  ///< All variable-length array types (not strings)\n  FixedArray  ///< All fixed-length array types\n};\n\nnamespace detail {\n/// \\brief Convenience function to safely copy a string.\nIODA_DL size_t COMPAT_strncpy_s(char* dest, size_t destSz, const char* src, size_t srcSz);\n\nclass Type_Backend;\n\ntemplate <class Type_Implementation = Type>\nclass Type_Base {\n  friend class ::ioda::Type;\n  std::shared_ptr<Type_Backend> backend_;\n\nprotected:\n  ::ioda::detail::Type_Provider* provider_;\n\n  /// @name General Functions\n  /// @{\n\n  Type_Base(std::shared_ptr<Type_Backend> b, ::ioda::detail::Type_Provider* p)\n      : backend_(b), provider_(p) {}\n\n  /// Get the type provider.\n  inline detail::Type_Provider* getTypeProvider() const { return provider_; }\n\npublic:\n  virtual ~Type_Base() {}\n  std::shared_ptr<Type_Backend> getBackend() const { return backend_; }\n  bool isValid() const { return (backend_.use_count() > 0); }\n\n  /// @}\n  /// @name General functions\n  /// @{\n\n  /// \\brief Get the size of a type, in bytes.\n  /// \\details This function is paired with the read and write functions to allow you to\n  /// read and write data in a type-agnostic manner.\n  /// This size report is a bit complicated when variable-length strings are encountered.\n  /// In these cases, the size of the string pointer is returned.\n  virtual size_t getSize() const;\n\n  /// \\brief Does this type represent a string, an integer, a float, an array, an\n  ///   enumeration, a bitset, or any other type?\n  virtual TypeClass getClass() const;\n\n  /// \\brief Save (commit) the type to a backend\n  /// \\details From the HDF5 docs:\n  ///   Committed datatypes can be used to save space in a file where many\n  ///   datasets or attributes use the same datatype or to avoid defining a complex\n  ///   compound datatype more than once. Committed datatypes can also be used to ensure\n  ///   that multiple instances of the same datatype are truly identical.\n  ///\n  ///   This is used extensively for enumerated types.\n  virtual void commitToBackend(Group& d, const std::string& name) const;\n\n  /// @}\n  /// @name Numeric type functions\n  /// @{\n\n  /// \\brief Is this type signed or unsigned?\n  /// \\returns true if signed, false if unsigned.\n  /// \\throws if the type is not a numeric type (i.e. not a simple integer or float).\n  virtual bool isTypeSigned() const;\n\n  /// @}\n  /// @name String type functions\n  /// @{\n\n  /// \\brief Is this a variable-length string type?\n  /// \\returns true if a variable-length string type, false if not.\n  ///   False can imply either that the type is a fixed-length string type (if getClass() == TypeClass::String),\n  ///   or that the type is not a string type at all.\n  virtual bool isVariableLengthStringType() const;\n\n  /// \\brief Get the character set of this string type.\n  /// \\returns Ascii or Unicode.\n  /// \\throws ioda::Exception on error, or if the type is not a string type.\n  /// \\note Currently, there is no way to set the character set. Everything is\n  ///   assumed to be a UTF-8 string in IODA.\n  virtual StringCSet getStringCSet() const;\n\n  /// @}\n  /// @name Array type functions\n  /// @{\n\n  /// \\brief Get the \"base\" type of an object. For an array, this is the type of\n  ///   the array's elements. I.e. an array of int32_t has a base type of int32_t.\n  ///   For an enumerated type, this is the type used for the enumeration.\n  virtual Type_Implementation getBaseType() const;\n\n  /// \\brief Get the dimensions of an array type.\n  /// \\returns A vector of the dimensions. vector::size() is the rank (dimensionality).\n  virtual std::vector<Dimensions_t> getDimensions() const;\n\n  /// @}\n};\n}  // namespace detail\n\n/// \\brief Represents the \"type\" (i.e. integer, string, float) of a piece of data.\n/// \\ingroup ioda_cxx_types\n///\n/// Generally, you do not have to use this class directly. Attributes and Variables have\n/// templated functions that convert your type into the type used internally by ioda.\n/// \\see Types::GetType and Types::GetType_Wrapper for functions that produce these types.\nclass IODA_DL Type : public detail::Type_Base<> {\npublic:\n  Type();\n  Type(std::shared_ptr<detail::Type_Backend> b, std::type_index t);\n  Type(BasicTypes, gsl::not_null<::ioda::detail::Type_Provider*> t);\n\n  virtual ~Type();\n\n  /// @name Type-querying functions\n  /// @{\n\n  /// @deprecated This function is problematic since we cannot query a type properly\n  /// when loading from a file.\n  std::type_index getType() const { return as_type_index_; }\n  inline std::type_index operator()() const { return getType(); }\n  inline std::type_index get() const { return getType(); }\n\n  /// @}\nprivate:\n  std::type_index as_type_index_;\n};\n\nnamespace detail {\n\n/// Backends inherit from this and they provide their own functions.\n/// Lots of std::dynamic_cast, unfortunately.\nclass IODA_DL Type_Backend : public Type_Base<> {\npublic:\n  virtual ~Type_Backend();\n  StringCSet getStringCSet() const override;\n\nprotected:\n  Type_Backend();\n};\n\n}  // namespace detail\n\n/// \\brief Defines the type system used for manipulating IODA objects.\nnamespace Types {\n\n// using namespace ioda::Handles;\n\n/// \\brief Convenience struct to determine if a type can represent a string.\n/// \\ingroup ioda_cxx_types\n/// \\todo extend to UTF-8 strings, as HDF5 supports these. No support for UTF-16, but conversion\n/// functions may be applied.\n/// \\todo Fix for \"const std::string\".\ntemplate <typename T>\nstruct is_string : public std::integral_constant<\n                     bool, std::is_same<char*, typename std::decay<T>::type>::value\n                             || std::is_same<const char*, typename std::decay<T>::type>::value> {};\n/// \\brief Convenience struct to determine if a type can represent a string.\n/// \\ingroup ioda_cxx_types\ntemplate <>\nstruct is_string<std::string> : std::true_type {};\n\n/// Useful compile-time definitions.\nnamespace constants {\n/// \\note Different than ObsSpace variable-length dimension. This is for a Type.\nconstexpr size_t _Variable_Length = 0;\n// constexpr int _Not_An_Array_type = -3;\n}  // namespace constants\n\n/// \\brief For fundamental, non-string types.\n/// \\ingroup ioda_cxx_types\ntemplate <class DataType, int Array_Type_Dimensionality = 0>\nType GetType(gsl::not_null<const ::ioda::detail::Type_Provider*> t,\n             std::initializer_list<Dimensions_t> Adims                   = {},\n             typename std::enable_if<!is_string<DataType>::value>::type* = 0) {\n  if (Array_Type_Dimensionality <= 0)\n    throw Exception(\n      \"Bad assertion / unsupported type at the frontend side \"\n      \"of the ioda type system.\",\n      ioda_Here());\n  else\n    return t->makeArrayType(Adims, typeid(DataType[]), typeid(DataType));\n}\n/// \\brief For fundamental string types. These are either constant or variable length arrays.\n/// Separate handling elsewhere.\n/// \\ingroup ioda_cxx_types\n/// \\todo Once C++20 support is added, make a distinction between std::string and std::u8string.\ntemplate <class DataType, int String_Type_Length = constants::_Variable_Length>\nType GetType(gsl::not_null<const ::ioda::detail::Type_Provider*> t,\n             std::initializer_list<Dimensions_t>                        = {},\n             typename std::enable_if<is_string<DataType>::value>::type* = 0) {\n  return t->makeStringType(typeid(DataType), String_Type_Length);\n}\n\n// This macro just repeats a long definition\n\n/// @def IODA_ADD_FUNDAMENTAL_TYPE\n/// Macro that defines a \"fundamental type\" that needs to be supported\n/// by the backend. These match C++11.\n/// \\ingroup ioda_cxx_types\n/// \\see https://en.cppreference.com/w/cpp/language/types\n/// \\since C++11: we use bool, short int, unsigned short int,\n///   int, unsigned int, long int, unsigned long int,\n///   long long int, unsigned long long int,\n///   signed char, unsigned char, char,\n///   wchar_t, char16_t, char32_t,\n///   float, double, long double.\n/// \\since C++20: we also add char8_t.\n#define IODA_ADD_FUNDAMENTAL_TYPE(x)                                                               \\\n  template <>                                                                                      \\\n  inline Type GetType<x, 0>(gsl::not_null<const ::ioda::detail::Type_Provider*> t,                 \\\n                            std::initializer_list<Dimensions_t>, void*) {                          \\\n    return t->makeFundamentalType(typeid(x));                                                      \\\n  }\n\nIODA_ADD_FUNDAMENTAL_TYPE(bool);\nIODA_ADD_FUNDAMENTAL_TYPE(short int);\nIODA_ADD_FUNDAMENTAL_TYPE(unsigned short int);\nIODA_ADD_FUNDAMENTAL_TYPE(int);\nIODA_ADD_FUNDAMENTAL_TYPE(unsigned int);\nIODA_ADD_FUNDAMENTAL_TYPE(long int);\nIODA_ADD_FUNDAMENTAL_TYPE(unsigned long int);\nIODA_ADD_FUNDAMENTAL_TYPE(long long int);\nIODA_ADD_FUNDAMENTAL_TYPE(unsigned long long int);\nIODA_ADD_FUNDAMENTAL_TYPE(signed char);\nIODA_ADD_FUNDAMENTAL_TYPE(unsigned char);\nIODA_ADD_FUNDAMENTAL_TYPE(char);\nIODA_ADD_FUNDAMENTAL_TYPE(wchar_t);\nIODA_ADD_FUNDAMENTAL_TYPE(char16_t);\nIODA_ADD_FUNDAMENTAL_TYPE(char32_t);\n// IODA_ADD_FUNDAMENTAL_TYPE(char8_t); // C++20\nIODA_ADD_FUNDAMENTAL_TYPE(float);\nIODA_ADD_FUNDAMENTAL_TYPE(double);\nIODA_ADD_FUNDAMENTAL_TYPE(long double);\n\n#undef IODA_ADD_FUNDAMENTAL_TYPE\n\n/*\n/// Used in an example. Incomplete.\n/// \\todo Pop off std::array as a 1-D object\ntemplate<> inline Type GetType<std::array<int,2>, 0>\n        (gsl::not_null<const ::ioda::detail::Type_Provider*> t,\n        std::initializer_list<Dimensions_t>, void*) {\n        return t->makeArrayType({2}, typeid(std::array<int,2>), typeid(int)); }\n\n*/\n\n/*\ntemplate <class DataType, int Array_Type_Dimensionality = 0>\nType GetType(\n        gsl::not_null<const ::ioda::detail::Type_Provider*> t,\n        std::initializer_list<Dimensions_t> Adims = {},\n        typename std::enable_if<!is_string<DataType>::value>::type* = 0);\ntemplate <class DataType, int String_Type_Length = constants::_Variable_Length>\nType GetType(\n        gsl::not_null<const ::ioda::detail::Type_Provider*> t,\n        typename std::enable_if<is_string<DataType>::value>::type* = 0);\n        */\n\n/// \\brief Wrapper struct to call GetType. Needed because of C++ template rules.\n/// \\ingroup ioda_cxx_types\n/// \\see ioda::Attribute, ioda::Has_Attributes, ioda::Variable, ioda::Has_Variables\ntemplate <class DataType,\n          int Length = 0>  //, typename = std::enable_if_t<!is_string<DataType>::value>>\nstruct GetType_Wrapper {\n  static Type GetType(gsl::not_null<const ::ioda::detail::Type_Provider*> t) {\n    /// \\note Currently breaks array types, but these are not yet used.\n    return ::ioda::Types::GetType<DataType, Length>(t, {Length});\n  }\n};\n/// \\ingroup ioda_cxx_types\ntypedef std::function<Type(gsl::not_null<const ::ioda::detail::Type_Provider*>)>\n  TypeWrapper_function;\n/*\ntemplate <class DataType, int Length = 0, typename = std::enable_if_t<is_string<DataType>::value>>\nstruct GetType_Wrapper {\n        Type GetType(gsl::not_null<const ::ioda::detail::Type_Provider*> t) const {\n                // string split\n                return ::ioda::Types::GetType<DataType, Length>(t);\n        }\n};\n*/\n\n// inline Encapsulated_Handle GetTypeFixedString(Dimensions_t sz);\n}  // namespace Types\n}  // namespace ioda\n\n/// @}\n", "meta": {"hexsha": "4794c7d7bd6d70d03a3e5d2cfdea9f03b43955d4", "size": 12935, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engines/ioda/include/ioda/Types/Type.h", "max_stars_repo_name": "NOAA-EMC/ioda", "max_stars_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/engines/ioda/include/ioda/Types/Type.h", "max_issues_repo_name": "NOAA-EMC/ioda", "max_issues_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engines/ioda/include/ioda/Types/Type.h", "max_forks_repo_name": "NOAA-EMC/ioda", "max_forks_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.7320441989, "max_line_length": 112, "alphanum_fraction": 0.6860456127, "num_tokens": 3226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12085324198975818, "lm_q2_score": 0.0618759813987784, "lm_q1q2_score": 0.007477912953340342}}
{"text": "#pragma once\n\n#include <gsl\\gsl>\n#include <winrt\\Windows.Foundation.h>\n#include <d3d11.h>\n#include \"DrawableGameComponent.h\"\n#include \"MatrixHelper.h\"\n#include \"DirectionalLight.h\"\n\nnamespace Library\n{\n\tclass Texture2D;\n\tclass ProxyModel;\n}\n\nnamespace Rendering\n{\n\tclass DisplacementMappingMaterial;\n\n\tclass DisplacementMappingDemo final : public Library::DrawableGameComponent\n\t{\n\tpublic:\n\t\tDisplacementMappingDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera);\n\t\tDisplacementMappingDemo(const DisplacementMappingDemo&) = delete;\n\t\tDisplacementMappingDemo(DisplacementMappingDemo&&) = default;\n\t\tDisplacementMappingDemo& operator=(const DisplacementMappingDemo&) = default;\t\t\n\t\tDisplacementMappingDemo& operator=(DisplacementMappingDemo&&) = default;\n\t\t~DisplacementMappingDemo();\n\n\t\tbool RealDisplacementMapEnabled() const;\n\t\tvoid SetRealDisplacementMapEnabled(bool enabled);\n\t\tvoid ToggleRealDisplacementMap();\n\n\t\tfloat AmbientLightIntensity() const;\n\t\tvoid SetAmbientLightIntensity(float intensity);\n\n\t\tfloat DirectionalLightIntensity() const;\n\t\tvoid SetDirectionalLightIntensity(float intensity);\n\n\t\tconst DirectX::XMFLOAT3& LightDirection() const;\n\t\tvoid RotateDirectionalLight(DirectX::XMFLOAT2 amount);\n\n\t\tconst float DisplacementScale() const;\n\t\tvoid SetDisplacementScale(float displacementScale);\n\n\t\tvirtual void Initialize() override;\n\t\tvirtual void Update(const Library::GameTime& gameTime) override;\n\t\tvirtual void Draw(const Library::GameTime& gameTime) override;\n\n\tprivate:\n\t\tstd::shared_ptr<DisplacementMappingMaterial> mMaterial;\n\t\tDirectX::XMFLOAT4X4 mWorldMatrix{ Library::MatrixHelper::Identity };\n\t\twinrt::com_ptr<ID3D11Buffer> mVertexBuffer;\n\t\twinrt::com_ptr<ID3D11Buffer> mIndexBuffer;\n\t\tstd::uint32_t mIndexCount{ 0 };\n\t\tLibrary::DirectionalLight mDirectionalLight;\n\t\tstd::unique_ptr<Library::ProxyModel> mProxyModel;\n\t\tstd::shared_ptr<Library::Texture2D> mRealDisplacementMap;\n\t\tstd::shared_ptr<Library::Texture2D> mDefaultDisplacementMap;\n\t\tbool mUpdateMaterial{ true };\n\t\tbool mRealDisplacementMapEnabled{ true };\n\t};\n}", "meta": {"hexsha": "8b19fd573e8a1f1b18b371f251931d225ccd3dd4", "size": 2069, "ext": "h", "lang": "C", "max_stars_repo_path": "source/6.2_Displacement_Mapping/DisplacementMappingDemo.h", "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/6.2_Displacement_Mapping/DisplacementMappingDemo.h", "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/6.2_Displacement_Mapping/DisplacementMappingDemo.h", "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8412698413, "max_line_length": 95, "alphanum_fraction": 0.7970033833, "num_tokens": 505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.019419349104640823, "lm_q1q2_score": 0.0074747433083494534}}
{"text": "//#include <gsl/gsl>\n\n#include \"../Problem15/ipv4Base.h\"\n\nclass ipv4Extend : public ipv4Base\n{\npublic:\n    ipv4Extend() : ipv4Base()\n    {\n    };\n\n    ipv4Extend( std::string   aInput ) : ipv4Base( aInput )\n    {\n    };\n\n    ~ipv4Extend()\n    {\n    };\n\n    ipv4Extend& operator= ( const ipv4Extend & aOther )\n    {\n        if ( this != & aOther )\n        {\n            mIPAddress = aOther.mIPAddress;\n        }\n\n        return *this;\n    }\n\n    //ipv4Extend& operator= ( ipv4Extend && aOther )\n    //{\n    //    if ( this != &aOther )\n    //    {\n    //    }\n\n    //    return *this;\n    //}\n\n    ipv4Extend& operator++()\n    {\n        increase();\n\n        return *this;\n    }\n\n    ipv4Extend operator++( int )\n    {\n        ipv4Extend sTemp( *this );\n        operator++();\n        return sTemp;\n    }\n\n    friend bool operator== ( const ipv4Extend   & aLhs,\n                             const ipv4Extend   & aRhs )\n    {\n        return (aLhs.mIPAddress == aRhs.mIPAddress);\n    }\n\n    friend bool operator!= ( const ipv4Extend   & aLhs,\n                             const ipv4Extend   & aRhs )\n    {\n        return !( aLhs == aRhs );\n    }\n\n    friend bool operator < ( const ipv4Extend   & aLhs,\n                             const ipv4Extend   & aRhs )\n    {\n        bool    sIsRigthBigger = false;\n        \n        for ( int i = 0; i < 4; i++ )\n        {\n            if ( aLhs.mIPAddress[i] < aRhs.mIPAddress[i] )\n            {\n                sIsRigthBigger = true;\n                break;\n            }\n        }\n\n        return sIsRigthBigger;\n    }\n\n    friend bool operator > ( const ipv4Extend   & aLhs,\n                             const ipv4Extend   & aRhs )\n    {\n        return aRhs < aLhs;\n    }\n\n    friend bool operator <= ( const ipv4Extend   & aLhs,\n                              const ipv4Extend   & aRhs )\n    {\n        return !( aLhs > aRhs );\n    }\n    \n    friend bool operator >= ( const ipv4Extend   & aLhs,\n                              const ipv4Extend   & aRhs )\n    {\n        return !( aLhs < aRhs );\n    }\n\nprivate:\n\n    void increase()\n    {\n        bool    sIsRoundUp = false;\n\n        mIPAddress[3]++;\n\n        for ( auto sIt = mIPAddress.rbegin();\n              sIt != mIPAddress.rend();\n              sIt++ )\n        {\n            //std::cout << *sIt << \"\\n\";\n            if ( sIsRoundUp == true )\n            {\n                *sIt = *sIt + 1;\n                //*sIt++;\n            }\n\n            //std::cout << *sIt << \"\\n\";\n            if ( (*sIt) > 255 )\n            {\n                sIsRoundUp = true;\n                *sIt = 0;\n            }\n            else\n            {\n                sIsRoundUp = false;\n            }\n        }\n\n        if ( sIsRoundUp == true )\n        {\n            mIPAddress[3]++;\n        }\n    }\n\n    void decrease()\n    {\n        bool sIsRoundDown = false;\n    }\n};\n", "meta": {"hexsha": "1a6b157a33259693675e44a060c6198a376a6ea4", "size": 2834, "ext": "h", "lang": "C", "max_stars_repo_path": "Language/Problem16/ipv4Extend.h", "max_stars_repo_name": "akaseon/ModernCppChallengeStudy", "max_stars_repo_head_hexsha": "1630f8cf5b3656171ee656738a908619cee6e718", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Language/Problem16/ipv4Extend.h", "max_issues_repo_name": "akaseon/ModernCppChallengeStudy", "max_issues_repo_head_hexsha": "1630f8cf5b3656171ee656738a908619cee6e718", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Language/Problem16/ipv4Extend.h", "max_forks_repo_name": "akaseon/ModernCppChallengeStudy", "max_forks_repo_head_hexsha": "1630f8cf5b3656171ee656738a908619cee6e718", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.9577464789, "max_line_length": 59, "alphanum_fraction": 0.4096683133, "num_tokens": 746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2628418489200747, "lm_q2_score": 0.028436032427331594, "lm_q1q2_score": 0.007474179339151036}}
{"text": "//  \u00a9 Shahram Talei @ 2020 The University of Alabama\n//you can redistribute it and/or modify\n//it under the terms of the GNU General Public License as published by\n//the Free Software Foundation; either version 3 of the License, or\n//(at your option) any later version.\n//You should have received a copy of the GNU General Public License\n//along with this program.  If not, see <http://www.gnu.org/licenses/>.\n// This code is distributed as is and there is no warranty or technical support\n// Reading stored data in a sage file\n// How to run:\n//first run:\n//$make\n//Then you can run\"\n// $./ExportForTracking > AllGals838.ascii\n// If you have an error you may need to give permission\n// $ chmod +x ExportForTracking\n//\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <unistd.h>\n//#include <gsl/gsl_rng.h>\n//#include <ctype.h>\n\n////////////////////////////////////////////////////////////\n//// Definitions and variables\nchar SageDir[500];\nstruct Path_Names\n{\n    char paths[100];\n}*SageFilesPath;\n\nint SageFilesCount;\nint NumGalaxies;\n\n// This structune holds all of the information from the Sage files\nstruct SageGalaxies\n{\n  int   Type;\n  int   FileNr;\n  long long   GalaxyIndex;\n  int   HaloIndex;\n  int   FOFHaloIndex; //SubhaloIndex;\n  int   TreeIndex;\n\n  int   SnapNum;\n  int   CentralGal; //GalIndex;\n  float CentralMvir;\n\n   //properties of subhalo at the last time this galaxy was a central galaaxy\n  float Pos[3];\n  float Vel[3];\n  float Spin[3];\n  int   Len;\n  float Mvir;\n  float Rvir;\n  float Vvir;\n  float Vmax;\n  float VelDisp;\n\n   //baryonic reservoirs\n  float ColdGas;\n  float StellarMass;\n  float BulgeMass;\n  float HotGas;\n  float EjectedMass;\n  float BlackHoleMass;\n  float ICS;\n  //metals\n float MetalsColdGas;\n float MetalsStellarMass;\n float MetalsBulgeMass;\n float MetalsHotGas;\n float MetalsEjectedMass;\n float MetalsICS;\n\n  //misc\n float Sfr;\n float SfrBulge;\n float SfrICS;\n float DiskScaleRadius;\n float Cooling;\n float Heating;\n float LastMajorMerger;\n float OutflowRate;\n\n float infallMvir;  //infall properties\n float infallVvir;\n float infallVmax;\n float r_heat;\n float Stars;\n\n}*SageOutput;\n//typedef struct SageGalaxies\n\n////////////////////////////////////////////////////////////\n//// Functions\n\n\nint CountSageFiles(int snap)\n{\n         //int i=0;\n         int n=0;\n         char line[10000];\n         char file1[10000];\n         FILE *fd;\n         sprintf(file1, \"%s/sagefile_%03d.txt\",SageDir, snap);\n         fd = fopen(file1, \"r\");\n         while(fgets(line, sizeof(line), fd)!=NULL)\n         {\n            n++;// 1;\n         }\n         fclose(fd);\n         return n;\n}\nvoid ReadSageFNames(int snap,struct Path_Names *SageFile)\n{\n        //printf(\"Reading sage file-name(s) for snap:%d\\n\",snap);\n    int i=0;\n    char line[10000];\n    char file1[10000];\n    char ABSpath[10000];//2\n    char model[500];\n    FILE *fd;\n    sprintf(file1, \"%s/sagefile_%03d.txt\", SageDir, snap);\n    fd = fopen(file1, \"r\");\n    while(EOF != fscanf(fd, \"%s%*[^\\n]\", line))\n    {\n       strcpy(ABSpath,line);//2\n       strcpy(model,strrchr(ABSpath,'/'));\n       //strcpy(SageFilesPath[i].paths, line);//1\n       if (model[0] == '/')\n         memmove(model, model+1, strlen(model));\n       sprintf(SageFile[i].paths,\"%s/%s\",SageDir,model);\n       i++;\n    }\n   fclose(fd);\n   return;\n }\n\n int ReadSageHeader(int FileCount,struct Path_Names *SageFile)\n {\n      int Ntrees;\n          int NtotGal;\n          int totmal;\n          int i;\n          FILE *fd;\n          char file1[1000];\n          totmal = 0;\n          for(i=0; i<FileCount; i++)\n             {\n                  sprintf(file1, \"%s\", SageFile[i].paths);\n                  fd = fopen(file1, \"rb\");\n                  if(NULL == fd)\n                  {\n                     printf(\"Cannot open sage file\");\n                     return(-1);\n                  }\n                  fread(&Ntrees, sizeof(int), 1, fd);\n                  fread(&NtotGal, sizeof(int), 1, fd);\n                  totmal = totmal + NtotGal;\n                  fclose(fd);\n             }\n return totmal;\n }\n\nvoid LoadSageFiles(int snap)\n{\n        SageFilesCount = CountSageFiles(snap);\n        SageFilesPath = (struct Path_Names*)malloc(SageFilesCount * sizeof(struct Path_Names));\n        ReadSageFNames(snap,SageFilesPath);\n        return;\n    }\n\n    void ReadSageModel(int FileCount,struct Path_Names *SageFile,struct SageGalaxies *Output)\n    {\n    int Ntrees;\n               int NtotGal;\n               int *galpertree;\n               char file1[1000];\n               int offset;\n               int i;\n               FILE *fd;\n               offset = 0;\n               for(i=0; i<FileCount; i++)\n               {\n                  sprintf(file1, \"%s\", SageFile[i].paths);\n                  fd = fopen(file1, \"rb\");\n                        if(NULL == fd)\n                        {\n                           printf(\"Cannot open sage for reading\");\n                           return;\n                        }\n                        fread(&Ntrees, sizeof(int), 1, fd);\n                        fread(&NtotGal, sizeof(int), 1, fd);\n                        galpertree = (int*)malloc(Ntrees*sizeof(int));\n                        fread(&galpertree[0], sizeof(int), Ntrees, fd);\n                        fread(&Output[offset], sizeof(struct SageGalaxies), NtotGal, fd);\n                        fclose(fd);\n                        offset = offset + NtotGal;\n                }\n                        free(galpertree);\n                        return;\n    }\n\nvoid ReadSage(int snap)\n{\n\n//printf(\"Extracting information from the sage file.\\n\");\nLoadSageFiles(snap);\nfflush(stdout);\nNumGalaxies = ReadSageHeader(SageFilesCount,SageFilesPath);\n\nif(( SageOutput = (struct SageGalaxies*)malloc(NumGalaxies * sizeof(struct SageGalaxies))) == NULL)\n    {\n        printf(\"Failed to allocate for target sage...\");\n        return;\n    }\nReadSageModel(SageFilesCount, SageFilesPath, SageOutput);\nreturn;\n}\n\n\nvoid PrintGalaxyInfo(struct SageGalaxies *Output,int index)\n{\n  int i;\n  i=index;\nprintf(\"~~~~~~~~~~~~~~~~~~~~~~\u222e\u222e\u222e\u222e\u222e\u222e\u222e\u222e\u222e\u222e\u222e\u222e~~~~~~~~~~~~~~~~~~~~~~\\n\");\nprintf(\"Galaxy Information- galaxy:%d, Type:%d, FileNr:%d\\n\",i,Output[i].Type,Output[i].FileNr);\nprintf(\"GalIndex:%lld,HaloIndex:%d,TreeIndex:%d,CentralGal:%d,CentralMvir:%f\\n\",Output[i].GalaxyIndex,Output[i].HaloIndex,\nOutput[i].TreeIndex,Output[i].CentralGal,Output[i].CentralMvir);\nprintf(\"Pos(x,y,z):(%f,%f,%f)\\nVel(vx,vy,vz):(%f,%f,%f)\\nSpin:(%f,%f,%f),Len:%d\\n\",Output[i].Pos[0],Output[i].Pos[1],\nOutput[i].Pos[2],Output[i].Vel[0],Output[i].Vel[1],Output[i].Vel[2],Output[i].Spin[0],Output[i].Spin[1],Output[i].Spin[2],Output[i].Len);\n\nprintf(\"Mvir:%f,Rvir:%f,Vvir:%f,Vmax:%f,VelDisp:%f\\n\",Output[i].Mvir,Output[i].Rvir,Output[i].Vvir,Output[i].Vmax,Output[i].VelDisp);\n\nprintf(\"ColdGas:%f,StellarMass:%f,BulgeMass:%f,HotGas:%f\\nEjectedMass:%f,BHMass:%f,ICS:%f\\n\",Output[i].ColdGas,Output[i].StellarMass,\nOutput[i].BulgeMass,Output[i].HotGas,Output[i].EjectedMass,Output[i].BlackHoleMass,Output[i].ICS);\n\nprintf(\"\\nMetals:\\nColdGas:%f,StellarMass:%f,BulgeMass:%f,HotGas:%f\\nEjectedMass:%f,ICS:%f\\n\\n\",Output[i].MetalsColdGas,\nOutput[i].MetalsStellarMass,Output[i].MetalsBulgeMass,Output[i].MetalsHotGas,Output[i].MetalsEjectedMass,Output[i].MetalsICS);\nprintf(\"Sfr:%f,SfrBulge:%f,SfrICS:%f\\nRd:%f,Cooling:%f,Heating:%f\\nLastMajorMerger:%f,OutflowRate:%f\\n\",Output[i].Sfr,\nOutput[i].SfrBulge,Output[i].SfrICS,Output[i].DiskScaleRadius,Output[i].Cooling,Output[i].Heating,Output[i].LastMajorMerger,Output[i].OutflowRate);\n\nprintf(\"infallMvir:%f,infallVvir:%f,infallVmax:%f,r_heat:%f\\n\",Output[i].infallMvir,Output[i].infallVvir,Output[i].infallVmax,Output[i].r_heat);\n//printf(\"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\");\n//printf(\"\u222e\u222e\u222e\u222e\u222e\u222e \u222e \u222e \u222e \u222e \u222e \u222e \u222e \u222e \u222e \u222e \u222e \u222e \u222e \u222e \u222e \u222e \u222e \u222e \u222e \u222e \u222e \u222e \u222e \u222e \u222e \u222e \u222e \u222e \u222e\u222e\u222e\u222e\u222e\u222e\\n\");\nprintf(\"~~~~~~~~~~~~~~~~~~~~~~\u222e\u222e\u222e\u222e\u222e\u222e\u222e\u222e\u222e\u222e\u222e\u222e~~~~~~~~~~~~~~~~~~~~~~\\n\");\n\nreturn;\n\n}\nvoid ExportGalaxy(int snap,struct SageGalaxies *Output, int id)\n{\n  //snap=161;\n  printf(\"%g,%g,%g,%g,%g,%d,%g,%d,%d,%d,%g\\n\",Output[id].Pos[0], Output[id].Pos[1],Output[id].Pos[2],Output[id].Mvir*(1.0e10),Output[id].Rvir,snap,Output[id].StellarMass*1.0e10,Output[id].GalaxyIndex,Output[id].HaloIndex,Output[id].CentralGal, Output[id].MetalsStellarMass*(1.0e10));//,Output[id].Stars, Output[id].DiskScaleRadius); //should remove stars for current tagging\n\n}\n\nint main(int argc, char * argv[])\n{\n//sprintf(SageDir,\"/home/shahram/Desktop/Research/3_Tagging/ReadSage/sage_out\");\n//838: 49-264\n//717: 36-264 -> new run error on 149\n//16406:40-264\n//19880: 41-264\n//32251: 46-264\n//High5M:\n//  /media/shahram/SD/Sample100Mpc/32251/High5M/r2/sage_out\n//  /media/shahram/SD/Sample100Mpc/m12f/sage_out\n\nsprintf(SageDir,\"/media/shahram/SD/Sample100Mpc/m12i/sage_out\"); //49-264\nint i,s, LastSnap,FirstSnap;\nLastSnap= atoi(argv[2]);\nFirstSnap=atoi(argv[1]);\nfor(s=FirstSnap;s<=LastSnap;s++)\n{\n  ReadSage(s);\n  //printf(\"snap:%d\\n\",s);\nfor(i=0;i<NumGalaxies;i++)\n  ExportGalaxy(s,SageOutput,i);\n}\n  return 0;\n}\n", "meta": {"hexsha": "b7bef0b387be9cc99aa4bafba87915bcf35c61a0", "size": 9087, "ext": "c", "lang": "C", "max_stars_repo_path": "ExportForTagging.c", "max_stars_repo_name": "stalei/TagMix", "max_stars_repo_head_hexsha": "36b7b6619c835b981c6f769cffbc34677d561346", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ExportForTagging.c", "max_issues_repo_name": "stalei/TagMix", "max_issues_repo_head_hexsha": "36b7b6619c835b981c6f769cffbc34677d561346", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ExportForTagging.c", "max_forks_repo_name": "stalei/TagMix", "max_forks_repo_head_hexsha": "36b7b6619c835b981c6f769cffbc34677d561346", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5520833333, "max_line_length": 374, "alphanum_fraction": 0.592934962, "num_tokens": 2710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.28776782797747225, "lm_q2_score": 0.025957358516437965, "lm_q1q2_score": 0.007469692680307894}}
{"text": "/*\nProgram to trace back a refined halo through a set of snapshots\n(contains code overhead, since it is based on a copy of trhalomult.c)\n\nicc -lm -lgsl -lgslcblas -o ../bin/altix/trace trace.c lmfit-2.2-icc/lmmin.o lmfit-2.2-icc/lm_eval.o libgad-icc.o KdTree-icc.o -I/usr/local/gsl-1.6\n\nicc -lm -lgsl -lgslcblas -o ../bin/altix/trace trace.c -lgad-altix-icc KdTree-icc.o -I/usr/local/gsl-1.6\nicc -lm -lgsl -lgslcblas -o ../bin/altix/trace_nopot trace.c -lgad-altix-icc-nopot KdTree-icc.o -I/usr/local/gsl-1.6 -DNOPOT\n\nadhara:\nicc -g -O2 -lm -lgsl -lgslcblas -o ../bin/other64/trace trace.c -lgad-adhara-icc adhara/KdTree-icc.o\n\nstan:\ngcc -lm -lgsl -lgslcblas -o ~/bin/trace trace.c -lgad-stan stan/KdTree.o -L/home/albireo/oser/libraries/stan/GSL/lib -L./lib/\n\ngcc -lm -lgsl -lgslcblas -o ~/bin/trace-winds trace.c -lgad-stan-winds stan/KdTree-winds.o -L/home/albireo/oser/libraries/stan/GSL/lib -L./lib/ -DWINDS\n\ngcc -fopenmp -lm -lgsl -lgslcblas -o ~/bin/trace trace.c -lgad-stan stan/KdTree.o -L/home/albireo/oser/libraries/stan/GSL/lib -L./lib/ stan/ompfuncs.o\n\n*/\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n#include <time.h>\n#include <string.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_eigen.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_permutation.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_linalg.h>\n//#include \"./lmfit-2.2/lmmin.h\"\n//#include \"./lmfit-2.2/lm_eval.h\"\n#include \"./lmmin.h\"\n#include \"./lm_eval.h\"\n#include \"libgad.h\"\n#include \"KdTree.h\"\n\n#define\tPI 3.14159265358979323846\n#define GAP2BORDER 10000                                     //min distance to boarders to ignore periodic boundaries\n#define INCLUDE 0                                    //(friends + INCLUDE*kpc/h) are used to determine CM\n#define NBOX 4 \n#define TRACE_FACTOR 2.0                             //TRACE_FACTOR times virial radius will be traced back to IC\n#define h0 0.72\n#define DIM 512\n#define ENVDENSRAD (4000 * h0)\n#define INERTIA_START_RAD 0.4\n#define INERTIA_USE_PART_TYPE 16\n#define CM_USE_PART_TYPE 16\n#define VA_USE_PART_TYPE 16\n#define MIN_PARTICLE_COUNT 30\n#define MAX_STAR_DIST (30*h0)\n#define GRIDSIZE 1000\n#define WORKSPACE 0.25                               //workspace for WORKSPACE*numpart particles is allocated, if glibc or segmentation fault occur, try to compile with a larger fraction\n#define LARGE_WS 8\n#define ADDSTAR_BUF 1000000\n#define ADDGAS_BUF 1000000\n#define kNN 50\n#define\tMIN(a, b)   ((a)<(b)?(a):(b))\n#define\tMAX(a, b)   ((a)>(b)?(a):(b))\n#define ABS(a) ((a) >= 0 ? (a) : -(a))\n#define CMP(a,b) ((a)>(b)?(1):(-1))\n#define PB(a,b) ((a)>(b)?((a)-(b)):(a))\n#define MOVE(a,b) PB((a)+((b)/2),(b))\n#define MOVEB(a) MOVE((a),boxsz)\n#define MV(a,b) ((a)+(b)/2)%(b)\n\n#define SOFTENING 0.40\n#define G 6.6742e-11\n#define Msun 1.989e30\n#define kpc 3.08567758128e19\n#define MAXNHALOES 30000\n#define MAXINT 10000000\n#define NUMTIMESTEPS 94\n#define NUMTRACE 50\n#define ACC_FRAC 0.1\n#define DENS_THRESH 1e-3                //Threshold for maxtemp of gas particles to be set\n\ndouble cdens;\n\nstruct particle {int ind;float dist;};\nclock_t t[2];\n\nstruct star{\n  int id;\n  float dist;\n  float gasdist;\n  float frac;\n  float idist;\n  float ifrac;\n  float ifrac_rhalf;\n  int isnap;\n  int snap;\n  float a;\n  int fnd;\n  float a_acc;\n#ifdef POTENTIAL\n  float pot;\n#endif\n};\n\nstruct gaspart{\n  int id;\n  float maxtemp;\n  float Tvir;\n  float Tvir_acc;\n  float a_maxtemp;\n  float frac_maxtemp;\n  float a_acc;\n  float T_acc;\n  float a_star;\n};\n\nint cmp_star_id(const void *a, const void *b)\n{\n  struct star *x= (struct star*)a;\n  struct star *y= (struct star*)b;\n  if (x->id > y->id) return 1;\n  if (x->id < y->id) return -1;\n  return 0;\n}\n\nint cmp_gas_id(const void *a, const void *b)\n{\n  struct gaspart *x= (struct gaspart*)a;\n  struct gaspart *y= (struct gaspart*)b;\n  if (x->id > y->id) return 1;\n  if (x->id < y->id) return -1;\n  return 0;\n}\n\ndouble fitfct(double t, double *p)\n{\n  return log10((p[0]) / ((t/p[1]) * SQR(1+t/p[1])));\n}\n\nvoid dumprintout ( int n_par, double* par, int m_dat, double* fvec, \n                       void *data, int iflag, int iter, int nfev )\n         {\n           // dummy function to catch fitting output\n\n         }\n\n\nvoid usage()\n{\n  fprintf(stderr,\"Trace v0.02\\n\");\n  fprintf(stderr,\"-f <snapshot basefilename>\\n\");\n  fprintf(stderr,\"-i <startindex> <endindex>\\n\");\n  fprintf(stderr,\"if you want to search for CM in an area around the given coordinates\\n\");\n  fprintf(stderr,\"add -sr <radius> to include particles for the search with distance to cm < radius\\n\");\n  fprintf(stderr,\"-n  <name of the halo>\\n\");\n  fprintf(stderr,\"-cm  <center of mass X Y Z>\\n\");\n  fprintf(stderr,\"-ui <bitcode for particle types to use for computation of Inertia Tensor>\\n\");\n  fprintf(stderr,\"-uva <bitcode for particle types to use for computation of Velocity Anisotropy>\\n\");\n  fprintf(stderr,\"-ucm <bitcode for particle types to use for computation of Center of Mass>\\n\");\n  fprintf(stderr,\"-cut <create Gadget-file for every halo>\\n\");\n  fprintf(stderr,\"-tf <trace factor>\\n\");\n  fprintf(stderr,\"-mincnt <minimum number of particles for CM-Search>\\n\");\n  fprintf(stderr,\"-ntr <Number of particles to trace back>\\n\");\n  fprintf(stderr,\"-cont <do not owerwrite existing files>\\n\");\n  exit(1);\n}\n\nfloat step()\n{\n  float tm;\n  t[1]=clock();\n  tm=(float)(t[1]-t[0])/CLOCKS_PER_SEC;\n  t[0]=clock();\n  return tm;\n}\n\n/*\nint cmp (struct particle *a, struct particle *b)\n{\n  if (a[0].dist > b[0].dist) return 1; else return -1;\n}\n*/\nint cmp (struct particle *a, struct particle *b)\n{\n  return CMP(a[0].dist,b[0].dist);\n}\n\nint cmpind (struct particle *a, struct particle *b)\n{\n  return CMP(a[0].ind,b[0].ind);\n}\n\nint compare (float *a, float *b)\n{\n  if (*a > *b) return 1; else return -1;\n}\n\nint coord512 (int *result, long index)\n{\n  int c[3];\n  int i;\n  result[0]=floor(index%262144/512.0);\n  result[1]=(index%512);\n  result[2]=floor(index/262144.0);\n  for (i=0; i<3; i++)\n    if ((result[i]<0) || (result[i]>512)) return 1;\n  return 0;\n}\n\n\nint main  (int argc, char *argv[])\n{\n  typedef float fltarr[3];\n  struct particle *part, *vpart;\n  gadpart *part_ev;\n  struct star *stars;\n  struct gaspart *gas;\n  struct header ic, evolved, out;\n  FILE *fp, *outf;\n  char cmfile[80],icfile[80],snapfile[256], basename[256],snfile[80],friendsfile[80],idlfile[80],asciifile[80],gridfile[80],jrfile[80], outfile[80], gadfile[80], starfile[80], prefix[20];\n  unsigned int numpart=0, nummass=0;\n  int blocksize,i,j,k,l,m,n,h,dum,tr_halo=0,tr_halo_cnt = 0,id,halo,checknpart,mindum,nhalo,count,notrace=0;\n  int *tr_halo_id,*tr_halo_i, ca[3], size[3];\n  fltarr *pos_ev,*pos_ic,*vel, *outpos, *outvel;\n  float *mass_ev, *mass_dum,*mass_ic,dist,maxdist,*distance,halomass,halorad, halolmd, *outmass;\n  double posdum,max[3],min[3],srad=25, icmin[3], icmax[3], envdens, bgdens;\n  float lmd,vcm[3]={0,0,0},jcm[3]={0,0,0},J[3]={0,0,0}, torq[3],rdum[3], vdum[3], massdum;\n  int *id_ev,*id_ic,*iclus, halonpart, *outid;\n  float tm,linkle,od, tr_factor, maxstardist=0;\n  double boxsz,cm[3]={0,0,0}, masstot, gridsize, rlog[50], p[50], err[50], d, rad_ratio;\n  double cvel[3];\n  short pb[3]={0,0,0};\n  int minbox[3], maxbox[3], szbox[3], ****grid, ***gridsz, boxind[3], alignf;\n  int nfun, npar, dojr=0, vcnt=0, use_inertia, use_va, use_cm;\n  double par[2],ddum, dx512, ddum1, totj, rotvel, peakrotvel, peakr, vmass, sqrenvdensrad, sfl=SOFTENING;\n  int  cutgad=0, idum, donotoverwrite=0, test=0, *cid, numalloc, numtrace;\n  fltarr *hcm;\n  int debug=0, maxhaloes, minpartcnt;\n  int startind, endind, snapind, starcnt=0, gascnt=0, totalstarcnt=0, totalgascnt=0,  dostars=1;\n  int addstar[ADDSTAR_BUF];\n  int addgas[ADDGAS_BUF];\n  double meff, effrad;\n  double ll = 0.8;\n  int doFOF = 1;\n  int doascii = 0;\n  int singlefile=0;\n  double GAP=GAP2BORDER;\n  double conv_dist=1.0;\n  double conv_mass=1.0;\n \n  //  float timestep[NUMTIMESTEPS];\n \n  t[0]=clock();\n  dx512=72000.0/512.0;\n  \n  rad_ratio=INERTIA_START_RAD;\n  use_inertia=INERTIA_USE_PART_TYPE;\n  use_va=VA_USE_PART_TYPE;\n  use_cm=CM_USE_PART_TYPE;\n  gridsize=GRIDSIZE;\n  maxhaloes=MAXNHALOES;\n  minpartcnt=MIN_PARTICLE_COUNT;\n  numtrace=NUMTRACE;\n  maxstardist=MAX_STAR_DIST;\n  sprintf(prefix,\"m\");\n\n  //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n  //filenames are ignored if given as command line parameters \n\n  strcpy(gridfile,\"<none>\");\n  strcpy(cmfile,\"<none>\");\n  strcpy(basename,\"\");\n  strcpy(icfile,\"\");\n  strcpy(idlfile,\"idlinp.dat\");\n  strcpy(asciifile,\"ascii.dat\");\n  tr_factor=TRACE_FACTOR;\n  //  tr_halo=123;\n  //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n  i=1;\n  if (argc==1) usage();\n  while (i<argc)\n    {\n      \n      if (!strcmp(argv[i],\"-f\"))\n\t{\n\t  i++;\n\t  strcpy(basename,argv[i]);\n\t  i++;\n\t}\n      else if (*argv[i]!='-')\n        {\n          startind=endind=1;\n          singlefile=1;\n          strcpy(basename,argv[i]);\n          i++;\n        }\n      else if (!strcmp(argv[i],\"-i\"))\n\t{\n\t  i++;\n\t  startind=atoi(argv[i]);\n\t  i++;\n\t  endind=atoi(argv[i]);\n\t  i++;\n\t  if (startind>endind)\n\t    {\n\t      int intdum=startind;\n\t      startind=endind;\n\t      endind=intdum;\n\t    }\n\t}\n      else if (!strcmp(argv[i],\"-n\"))\n\t{\n\t  i++;\n\t  strcpy(prefix,argv[i]);\n\t  i++;\n\t}\n      else if (!strcmp(argv[i],\"-debug\"))\n\t{\n\t  i++;\n\t  debug=1;\n\t}\n      else if (!strcmp(argv[i],\"-test\"))\n\t{\n\t  i++;\n\t  test=1;\n\t}\n      else if (!strcmp(argv[i],\"-cont\"))\n\t{\n\t  i++;\n\t  donotoverwrite=1;\n\t}\n      else if (!strcmp(argv[i],\"-gap\"))\n\t{\n\t  i++;\n\t  GAP=atof(argv[i]);\n\t  i++;\n\t}\n      else if (!strcmp(argv[i],\"-dc\"))\n\t{\n\t  i++;\n\t  conv_dist=atof(argv[i]);\n\t  i++;\n\t}\n      else if (!strcmp(argv[i],\"-mc\"))\n\t{\n\t  i++;\n\t  conv_mass=atof(argv[i]);\n\t  i++;\n\t}\n      else if (!strcmp(argv[i],\"-nofof\"))\n\t{\n\t  i++;\n\t  doFOF=0;\n\t}\n      else if (!strcmp(argv[i],\"-pfof\"))\n\t{\n\t  i++;\n\t  doFOF= doFOF | 2;\n\t}\n      else if (!strcmp(argv[i],\"-cutfof\"))\n\t{\n\t  i++;\n\t  doFOF= doFOF | 4;   //not yet implemented\n\t}\n      else if (!strcmp(argv[i],\"-idl\"))\n\t{\n\t  i++;\n\t  strcpy(idlfile,argv[i]);\n\t  i++;\n\t}\n      else if (!strcmp(argv[i],\"-ascii\"))\n\t{\n\t  i++;\n\t  doascii = 1;\n\t  strcpy(asciifile,argv[i]);\n\t  i++;\n\t}\n      else if (!strcmp(argv[i],\"-da\"))\n\t{\n\t  i++;\n\t  doascii = 1;\n\t}\n      else if (!strcmp(argv[i],\"-gr\"))\n\t{\n\t  i++;\n\t  strcpy(gridfile,argv[i]);\n\t  i++;\n\t}\n      else if (!strcmp(argv[i],\"-mincnt\"))\n\t{\n\t  i++;\n\t  minpartcnt=atoi(argv[i]);\n\t  i++;\n\t}\n      else if (!strcmp(argv[i],\"-ntr\"))\n\t{\n\t  i++;\n\t  numtrace=atoi(argv[i]);\n\t  i++;\n\t}\n      else if (!strcmp(argv[i],\"-sr\"))\n\t{\n\t  i++;\n\t  srad=atof(argv[i]);\n\t  i++;\n\t}\n      else if (!strcmp(argv[i],\"-gs\"))\n\t{\n\t  i++;\n\t  gridsize=atof(argv[i]);\n\t  i++;\n\t}\n       else if (!strcmp(argv[i],\"-r\"))\n\t{\n\t  i++;\n\t  rad_ratio=atof(argv[i]);\n\t  i++;\n\t}\n      else if (!strcmp(argv[i],\"-soft\"))\n\t{\n\t  i++;\n\t  sfl=atof(argv[i]);\n\t  i++;\n\t}\n      else if (!strcmp(argv[i],\"-ll\"))\n\t{\n\t  i++;\n\t  ll=atof(argv[i]);\n\t  i++;\n\t}\n      else if (!strcmp(argv[i],\"-ui\"))\n\t{\n\t  i++;\n\t  use_inertia=atoi(argv[i]);\n\t  i++;\n\t}\n      else if (!strcmp(argv[i],\"-uva\"))\n\t{\n\t  i++;\n\t  use_va=atoi(argv[i]);\n\t  i++;\n\t}\n      else if (!strcmp(argv[i],\"-ucm\"))\n\t{\n\t  i++;\n\t  use_cm=atoi(argv[i]);\n\t  i++;\n\t}\n      else if (!strcmp(argv[i],\"-use\"))\n\t{\n\t  i++;\n\t  use_cm=atoi(argv[i]);\n\t  use_va=use_cm;\n\t  use_inertia=use_cm;\n\t  i++;\n\t}\n      else if (!strcmp(argv[i],\"-jr\"))\n\t{\n\t  i++;\n\t  dojr=1;\n\t  strcpy(jrfile,argv[i]);\n\t  i++;\n\t}\n      else if (!strcmp(argv[i],\"-cut\"))\n\t{\n\t  i++;\n\t  cutgad=1;\n\t}\n      else if (!strcmp(argv[i],\"-tr\"))\n\t{\n\t  i++;\n          notrace=1;\n\t}\n      else if (!strcmp(argv[i],\"-ds\"))\n\t{\n\t  i++;\n          dostars=0;\n\t}\n      else if (!strcmp(argv[i],\"-msd\"))\n\t{\n\t  i++;\n\t  maxstardist=atof(argv[i]);\n\t  i++;\n\t}\n      else if (!strcmp(argv[i],\"-tf\"))\n\t{\n\t  i++;\n\t  tr_factor=atof(argv[i]);\n\t  i++;\n\t}\n       else if (!strcmp(argv[i],\"-cm\"))\n\t{\n\t  i++;\n\t  cm[0]=atof(argv[i++]);\n\t  cm[1]=atof(argv[i++]);\n\t  cm[2]=atof(argv[i++]);\n\t  //\t  cmset=1;\n\t}\n       else {\n\t  usage();\n\t}\n\n    }\n\n  cid=(int *) calloc(numtrace, sizeof(int));\n\n\n  /*\n  fp=fopen(\"times.dat\", \"r\");\n  if (fp!=NULL)\n    {\n      for (i=0; i<NUMTIMESTEPS; i++) fscanf(fp,\"%f\", &timestep[i]);\n      fclose(fp);\n    } else printf(\"times.dat not found\\n\");\n  */\n\n  dum=0;\n    \n\n  sqrenvdensrad=SQR(ENVDENSRAD); \n\n  if (debug) printf(\"comencing main loop...\\n\");fflush(stdout);\n\n/************************************************************************************/\n/* Start of main loop                                                               */\n/************************************************************************************/\n\n\n\n  for (snapind=endind; snapind>=startind; snapind--)\n    { \n      if (debug) {printf(\"Ind: %d %d %d\\n\", snapind, endind, startind);fflush(stdout);}\n      sprintf(snapfile,\"%s%03d\", basename, snapind);\n      if (singlefile) strcpy(snapfile, basename);\n      /*\n      if (access(outfile, 0)!=0) {\n\tprintf(\"File %s does not exits!\\n\", snapfile);\n\tcontinue;\n      }\n      */\n\n      //      numpart=readgadget(snapfile, &evolved, &pos_ev, &vel, &id_ev, &mass_ev);\n      numpart=readgadget_part(snapfile, &evolved, &part_ev);   \n      if (numpart==0) \n\t{\n\t  extern int libgaderr;\n\t  fprintf(stderr,\"LibGad Error Code: %d\\n\", libgaderr);\n\t  continue;\n\t}\n      convertunits(&evolved, part_ev, conv_mass, conv_dist);\n\n      if (evolved.npart[0]==0) {dostars=0;}\n      if (debug) {printf(\"numpart %d\\n\", numpart);fflush(stdout);}\n#ifndef NOGAS\n      if ((debug) && (evolved.npart[0]) ) {printf(\"sph:  %g %g\\n\", part_ev[0].sph->u, part_ev[0].sph->rho);fflush(stdout);}\n#endif\n      printf(\"SnapInd: %d\\nStart CM search at %f %f %f\\n\",snapind, cm[0], cm[1], cm[2]);\n      if (cid[0]) \n\t{\n\t  k=0;\n\t  for (j=0; j<3; j++) cm[j]=0;\n\t  masstot=0;\n\t  qsort(cid, numtrace, sizeof(int), cmp_int);\n\n\t  for (i=evolved.npart[0]; i< numpart; i++)\n\t    {\n\t      int *fnd=bsearch(&part_ev[i].id,cid, numtrace, sizeof(int), cmp_int);\n\t      if (fnd!=NULL)\n\t\t{\n\t\t  for (j=0; j<3; j++) \n\t\t    {\n\t\t      if (pb[j]) cm[j]+=MOVE(part_ev[i].pos[j], boxsz)*part_ev[i].mass;\n\t\t      else cm[j]+=part_ev[i].pos[j]*part_ev[i].mass;\n\t\t    }\n\t\t  masstot+=part_ev[i].mass;\n\t\t  k++;\n\t\t}\n\t      if (k==numtrace) break;\n\t    }\n\n\t  //\t  if (debug) printf(\"CID %d\\n\", cid);\n\t  //set start CM\n\t  for (j=0; j<3; j++) \n\t    {\n\t      cm[j]=cm[j]/masstot;\n\t      if (pb[j]) cm[j]==MOVE(cm[j],boxsz);\n\t    }\n\t}\n      cdens=(5.36e-8) * evolved.hubparam * evolved.hubparam;\n      cdens=cdens*(evolved.omegal+evolved.omega0*pow(evolved.time,-3));\n      bgdens=cdens*evolved.omega0;\n      if (debug) {printf(\"...\\n\");fflush(stdout);}\n      \n      tr_halo_cnt=0;\n      /*\n      for (k=0; k<3; k++) {\n\tcm[k]=hcm[trhalo][k];\n\tx=floor(cm[0]/gridsize);\n\ty=floor(cm[1]/gridsize);\n\tz=floor(cm[2]/gridsize);\n      }\n      */\n  sprintf(idlfile ,\"%s_%03d.idl\",prefix, snapind);\n  sprintf(asciifile ,\"%s_%03d.ascii\",prefix, snapind);\n  sprintf( jrfile ,\"%s_%03d.jr\", prefix, snapind);\n  sprintf(outfile ,\"%s_%03d.tr\", prefix, snapind);\n  sprintf(gadfile ,\"%s_%03d.gad\",prefix, snapind);\n   if ((access(outfile, 0)==0) && (donotoverwrite)) \n    {\n      continue;\n    }\n \n   if (singlefile)\n    {\n        sprintf(idlfile ,\"%s.idl\",prefix);\n        sprintf(asciifile ,\"%s.ascii\",prefix);\n\tsprintf( jrfile ,\"%s.jr\", prefix);\n\tsprintf(outfile ,\"%s.tr\", prefix);\n\tsprintf(gadfile ,\"%s.gad\",prefix);\n\toutf=stdout;\n    }\n   else\n     outf=fopen(outfile, \"w\");\n  fprintf(outf, \"ucm %d ui %d uva %d\\n\", use_cm, use_inertia, use_va);\n  pb[0]=0;\n  pb[1]=0;\n  pb[2]=0;\n  masstot=0;\n  double icm[3];\n  for (k=0; k<3; k++)                                                         //check whether periodic boundaries are needed\n    {\n      if ((cm[k]<GAP) || (cm[k]>(evolved.boxsize-GAP))) \n\t{\n\t  pb[k]=1;\n\t  cm[k]=MOVE(cm[k],boxsz);\n\t}\n      icm[k]=cm[k];\n    }\n\n\n\n  /*\n  index=(int *) malloc((int)(numpart*(WORKSPACE*LARGE_WS))*sizeof(int));\n  if (index==NULL)\n    {\n      fprintf(stderr, \"memory allocation failed (index)\\n\");\n      exit(1);\n    }\n  icnt=0;\n  for (i=(x-NBOX); i <= (x+NBOX); i++)\n  for (j=(y-NBOX); j <= (y+NBOX); j++)\n  for (k=(z-NBOX); k <= (z+NBOX); k++)\n    {\n      if (icnt>=(WORKSPACE*LARGE_WS*numpart-1))\n\t{\n\t  fprintf(stderr, \"out of memory (index), increase WORKSPACE and recompile\\n\");\n\t  exit(1);\n\t}\n      dist=sqrt(pow(x-i,2)+pow(y-j,2)+pow(z-k,2));\n      if (dist<(NBOX+1))\n      {\n      for (l=1; l <= grid[(i+n)%n][(j+n)%n][(k+n)%n][0]; l++)\n      {\n\tindex[icnt++]=grid[(i+n)%n][(j+n)%n][(k+n)%n][l];\n      }\n      }\n    }\n  //printf(\"halo %d %d x %d y %d z %d\\n\", tr_halo , icnt, x[tr_halo], y[tr_halo], z[tr_halo]);\n  index=realloc(index, sizeof(int)*icnt);\n  */\n\nif (debug) {printf(\"search Center\\n\");fflush(stdout);}\n  int iteration=0;\n  double searchrad=srad/1.5;\n  float allocsize=WORKSPACE/8;\n  if (srad>0) do\n    {\n      tr_halo_cnt=0;\n      for (k=0; k<3; k++) cm[k]=icm[k];\n      searchrad*=1.5;\n      allocsize=MIN(8*allocsize, WORKSPACE* LARGE_WS);\n      if (srad>0)\n\t{\n\t  tr_halo_id=(int *)malloc((int)(numpart*allocsize)*sizeof(int));\n\t  tr_halo_i =(int *)malloc((int)(numpart*allocsize)*sizeof(int));\n\t  if ((tr_halo_id==NULL) || (tr_halo_i==NULL))\n\t    {\n\t      fprintf(stderr, \"memory allocation failed\\n\");\n\t      exit(2);\n\t    }\n\t  maxdist=searchrad*searchrad;\n\t  if (debug) {printf(\"!\\n\");fflush(stdout);}\n\t  for (i=0; i < numpart; i++)\n\t    {\n\t      //\t      i=index[l];\n\t      dist=0;\n\t      for (j=0; j<3; j++) \n\t\tif (pb[j]) dist+=pow(MOVE(part_ev[i].pos[j],boxsz)-cm[j],2);\n\t\telse dist+=pow(part_ev[i].pos[j]-cm[j],2);\n\n\t      //\t      if (debug) {printf(\"%%\");fflush(stdout);}\n\t      int type= part_ev[i].type;\n      \n\t      if ((dist<maxdist) && ( (1<<type) & use_cm) )\n\t\t{\n\t\t  tr_halo_id[tr_halo_cnt]=part_ev[i].id;\n\t\t  tr_halo_i[tr_halo_cnt++]=i;\n\t\t}\n\t      if (tr_halo_cnt>=(allocsize*numpart-1))\n\t\t{\n\t\t  fprintf(stderr, \"out of memory (<srad), increase WORKSPACE and recompile!\\n\");\n\t\t  exit(1);\n\t\t}\n\t    }\n\n\t  //\t  tr_halo_id=realloc(tr_halo_id,sizeof(int)*tr_halo_cnt);\n\t  //\t  tr_halo_i =realloc(tr_halo_i ,sizeof(int)*tr_halo_cnt);\n  \n\t}\n\n      if (++iteration>3)\n\t{\n\t  tr_halo_cnt=0;\n\t}\n      if (debug) {printf(\"iteration %d\\n\", iteration);fflush(stdout);}\n      if (tr_halo_cnt < minpartcnt) \n\t{\n\n\t  break;\n\t}\n      if (srad>0)\n\t{\n\t  maxdist=searchrad;\n\t  count=tr_halo_cnt;\n\t  do\n\t    {\n\t      masstot=0;\n\t      maxdist*=0.92;\n\t      for (j=0; j<3; j++){rdum[j]=cm[j];}\n\t      cm[0]=0;\n\t      cm[1]=0;\n\t      cm[2]=0;\n\t      for (i=0; i < count; i++)\n\t\t{\n\t\t  for (j=0; j<3; j++) \n\t\t    {\n\t\t      if (pb[j]) cm[j]+=MOVEB(part_ev[tr_halo_i[i]].pos[j]) * part_ev[tr_halo_i[i]].mass;\n\t\t      else cm[j]+=part_ev[tr_halo_i[i]].pos[j]*part_ev[tr_halo_i[i]].mass;\n\t\t    }\n\t\t  masstot+=part_ev[tr_halo_i[i]].mass;\n\t\t}\n\n\n\t      for (j=0; j<3; j++) cm[j]=cm[j]/(masstot);\n  \n\t      dum=0;\n\t      for (i=0; i < count; i++)                                                //\n\t\t{\n\t\t  dist=0;\n\t\t  for (j=0; j<3; j++) \n\t\t    {\t\t      \n\t\t      if (pb[j]) dist += pow((MOVE(part_ev[tr_halo_i[i]].pos[j],boxsz)-cm[j]),2);\n\t\t      else dist += pow((part_ev[tr_halo_i[i]].pos[j]-cm[j]),2);\n\t\t    }\n      \n\t\t  dist=sqrt(dist);\n\t\t  if (dist < maxdist) \n\t\t    {\n\t\t      tr_halo_i[dum]=tr_halo_i[i];\n\t\t      dum++;\n\t\t    }\n\t\t}\n\t      count=dum;\n\t      if ((count<50) && (cvel[0]==0))\n\t\t{\n\t\t  masstot=0;\n\t\t  for (i=0; i< count; i++)\n\t\t    {\n\t\t      for (j=0; j<3; j++) \n\t\t\t{\n\t\t\t  cvel[j] += part_ev[tr_halo_i[i]].vel[j] * part_ev[tr_halo_i[i]].mass;\n\t\t\t}\n\t\t      masstot+= part_ev[tr_halo_i[i]].mass;\n\t\t    }\n\t\t  for (j=0; j<3; j++) cvel[j]=cvel[j]/(masstot);\n\t\t}\n\t    } while (count>5);\n\t  free(tr_halo_id);\n\t  free(tr_halo_i);\n\t}\n    } while  ((ABS(cm[0]-icm[0])>(searchrad/2)) ||\n\t      (ABS(cm[1]-icm[1])>(searchrad/2)) ||\n\t      (ABS(cm[2]-icm[2])>(searchrad/2)) );\n  if (debug) {printf(\"Center Found\\n\");fflush(stdout);}\n\n  if ((tr_halo_cnt < minpartcnt) && (srad>0))\n    {\n\n      fprintf(outf, \"%g %g %g <No Halo found>\\n\" ,cm[0], cm[1], cm[2]);\n      //      free(index);\n      free(tr_halo_id);\n      free(tr_halo_i);\n      fclose(outf);\n      continue;\n    }\n\n\n     maxdist=GAP*GAP;\n     numalloc=(int)(numpart);\n     part= (struct particle *)malloc(sizeof(struct particle)*numalloc);\n     vpart=(struct particle *)malloc(sizeof(struct particle)*numalloc);\n     if ((part==NULL) || (vpart==NULL))\n       {\n\t fprintf(stderr,\"memory allocation failed!\\n\");\n\t exit(1);\n       }\n     if (debug) {printf(\"memmory allocated\\n\");fflush(stdout);}\n\n     count=0;\n     envdens=0;\n\n     for (i=0; i< numpart; i++) \n       {\n\t //\t i=index[l];\n\t dist=0;\n\t for (j=0; j<3; j++) \n\t   {\n\t     if (pb[j]) dist += pow((MOVE(part_ev[i].pos[j],boxsz)-cm[j]),2);\n\t     else dist += pow((part_ev[i].pos[j]-cm[j]),2);\n\t     if (dist>maxdist) break;\n\t   }\n\n\t if (dist < sqrenvdensrad)\n\t   {\n\t     envdens+=part_ev[i].mass;\n\t   } \n\n\t if (dist < maxdist) \n\t   {\n\t     dist=sqrt(dist);\n\t     part[count].dist=dist;\n\t     part[count++].ind=i;\n\t   }\n\t \n\t if (count>=numalloc) \n\t   {\n\t     fprintf(stderr, \"increase Workspace!\\n\");\n\t     exit(1);\n\t   }\n\n       }\n\n     if (debug) {printf(\"Close particles chosen\\n\");fflush(stdout);}\n \n\n     //     qsort(&part[0],count,sizeof(struct particle), (__compar_fn_t)cmp);                  //sort particles by distance to CM of halo\n     qsort(&part[0],count,sizeof(struct particle), cmp);                  //sort particles by distance to CM of halo\n     //     part=realloc(part,sizeof(struct particle)*count);\n     masstot=0;\n     i=0;\n     od=201;\n     effrad=30*evolved.hubparam;\n     meff=0;\n     peakrotvel=0;\n     double b_mass=0;\n     double dm_mass=0;\n     while ((od > 200) || (i<5))                                                    //Add mass until overdensity drops below 200\n       {\n\t int ind= part[i].ind;\n\t masstot+=part_ev[ind].mass;\n\t if ((part_ev[ind].type == 0) ||(part_ev[ind].type == 4)) \n\t   {\n\t     b_mass += part_ev[ind].mass;\n\t   } else \n\t   {\n\t     dm_mass+= part_ev[ind].mass;\n\t   }\n\t if ((part[i].dist < effrad) && ( (1<<part_ev[ind].type) & use_cm ) )\n\t   {\n\t     meff +=part_ev[ind].mass;\n\t   }\n\n\t od=masstot/(pow(part[i].dist*evolved.time,3)*(4.0/3.0)*PI*cdens);\n\t //printf(\"i %d od %f\\n\",i,od);\n\t rotvel=sqrt((masstot/(part[i].dist*evolved.time))*(G*Msun*1e10/kpc))*1e-3;\n\t if (rotvel > peakrotvel) \n\t   {\n\t     peakrotvel= rotvel;\n\t     peakr=part[i].dist;\n\t   }\n\t vpart[i].dist=part[i].dist;\n         vpart[i].ind=part[i].ind;\n\t i++;\n\t if (i > count)\n\t   {\n\t     fp=fopen(\"error_trhalo.dat\",\"a\");\n\t     fprintf(fp,\"Halo %d is making trouble\\n\",snapind);\n\t     fclose(fp);\n\t     printf(\"halo %d is making trouble\\n\",snapind);\n\t     break;\n\t   }\n       }\n\n     if (debug) {fprintf(outf,\"Virial radius calculated\\n\");fflush(stdout);}\n     if (use_cm==1) fprintf(outf,\"Gas mass inside 30 kpc %f\\n\", meff);\n     if (use_cm==16) fprintf(outf,\"Stellar mass inside 30 kpc %f\\n\", meff);\n     if (use_cm==17) fprintf(outf,\"Baryonic mass inside 30 kpc %f\\n\", meff);\n \n     masstot-=part_ev[part[i-1].ind].mass;\n     if ((part_ev[part[i-1].ind].type == 0) ||(part_ev[part[i-1].ind].type == 4)) \n\t   {\n\t     b_mass -= part_ev[part[i-1].ind].mass;\n\t   } else \n\t   {\n\t     dm_mass-= part_ev[part[i-1].ind].mass;\n\t   }\n     dum=i-1;  \n     vcnt=i;\n     halorad=part[vcnt-1].dist;\n     vpart=realloc(vpart,sizeof(struct particle)*vcnt);\n     //     qsort(&vpart[0],vcnt,sizeof(struct particle),(__compar_fn_t)cmpind);\n     qsort(&vpart[0],vcnt,sizeof(struct particle),cmpind);\n\n     j=0;\n     k=0;\n     while (k<numtrace)\n       {\n\t if (part[j].ind>evolved.npart[0])\n\t   {\n\t     cid[k++]=part_ev[part[j].ind].id;\n\t   }\n\t if ((++j) > vcnt) \n\t   {\n\t     fprintf(stderr, \"not enough DM particles inside the virial radius (%d).\\n\", k);\n\t     numtrace=k;\n\t   }\n       }\n     if (debug) {printf(\"Innermost DM particles determined\\n\");fflush(stdout);}\n\n     envdens=envdens/((4.0/3.0)*PI*pow(ENVDENSRAD*evolved.time,3));\n\n\n for (j=0; j<3; j++) \n   {\n     if (pb[j])\n       {\n\t cm[j]=MOVE(cm[j],boxsz);\n\t fprintf(outf,\"!!!periodic boundaries used in Dimension %d !!!\\n\",j);\n       }\n   }\n vmass=masstot;\n fprintf(outf,\"redshift: %f\\naexp: %f\\n\", 1./evolved.time - 1,evolved.time);\n fprintf(outf,\"\\n halo in snapshot %5d consists of %5d particles, virial Mass/h %5.2f\\n rad %5.2f         od %4.2f\\n\",snapind,vcnt,masstot,halorad,od);\n fprintf(outf,\" Baryonic Mass/h %5.2f\\n DM Mass/h %5.2f \\n\\n\",b_mass, dm_mass);\n \n fprintf(outf,\"Center of Mass  : %12.2f %12.2f %12.2f\\n\",cm[0],cm[1],cm[2]);\n fprintf(outf,\"shift to cm-file: %+12.2f %+12.2f %+12.2f\\n\",cm[0]-icm[0],cm[1]-icm[1],cm[2]-icm[2]);\n fprintf(outf,\"CM Vel          : %12.2f %12.2f %12.2f\\n\",cvel[0],cvel[1],cvel[2]);\n fprintf(outf,\"particles in box: %d\\n\",count);\n fprintf(outf,\"Environmental Radius: %f \\n\", ENVDENSRAD);\n fprintf(outf,\"Environmental OD: %f %f\\n\", envdens/cdens, envdens/bgdens);\n fprintf(outf,\"Peakrotvel: %f at %f kpc\\n\",peakrotvel, peakr);\n fprintf(outf,\"    Rotvel: %f at Rvir\\n\",rotvel);\n\n\n tr_halo_id=(int *)malloc(count*sizeof(int));\n tr_halo_i =(int *)malloc(count*sizeof(int));\n if ((tr_halo_id==NULL) || (tr_halo_i==NULL))\n\t    {\n\t      fprintf(stderr, \"memory allocation failed (tr_halo_?)\\n\");\n\t      exit(2);\n\t    }\n tr_halo_cnt=0;\n\n\n if (cutgad)\n   {\n     gadpart *outpart= (gadpart *) malloc (sizeof(gadpart)* vcnt);\n     if ((outpart==NULL) )\n\t    {\n\t      fprintf(stderr, \"memory allocation failed (outpart)\\n\");\n\t      exit(2);\n\t    }\n//     outpos =(fltarr *)malloc(sizeof(fltarr)*i);\n//     outvel =(fltarr *)malloc(sizeof(fltarr)*i);\n//     outid =(int *)malloc(sizeof(int)*i);\n//     outmass =(float *)malloc(sizeof(float)*i);\n     out=evolved;\n     for (i=0; i<6; i++)\n       {\n\t out.npart[i]=0;\n\t out.nall[i]=0;\n       }\n     i=0;\n     while (i<vcnt)\n       {\n\t dist=vpart[i].dist;\n\t k=vpart[i].ind;\n\t outpart[i]=part_ev[k];\n\t for (j=0; j<3; j++)\n\t   {\n\n\t     if (pb[j]) outpart[i].pos[j]=MOVEB(outpart[i].pos[j]) - MOVEB(cm[j]);\n\t     else outpart[i].pos[j]=(outpart[i].pos[j]) - (cm[j]);\n\t     outpart[i].vel[j] -= cvel[j];\n\t   }\n//\t dum=0;\n//\t for (l=0; l<6; l++)\n//\t   {\n// \t     dum+=evolved.npart[l];\n//\t     if (k<dum) break;\n//\t   }\n\t out.npart[outpart[i].type]++;\n\t out.nall[outpart[i].type]++;\n\t i++;\n       }\n     if (debug) {printf(\"...writing output file %d %d\\n\", vcnt, i);fflush(stdout);}\n     //     if (debug) {printf(\"...data-test %g %g %g\\n\", outpart[0].sph->rho, outpart[0].sph->u, outpart[0].pot);fflush(stdout);}\n     writegadget_part(gadfile, out, outpart);\n     if (debug) {printf(\"Gadget File written\\n\");fflush(stdout);}\n     free(outpart);\n//     free(outpos);\n//     free(outvel);\n//     free(outid);\n//     free(outmass);\n\n   }\n\n\n maxdist=halorad*tr_factor;\n double hmeff=0;\n double galmass=0;\n double gasmass=0;\n double DMmass=0;\n double innertotm=0;\n double galrad=0;\n double gsfr=0;\n double meanage=0;\n int nstars_gal=0;\n dist=0;\n i=0;\n// for (j=0; j<50; j++)\n//   {\n//     p[j]=0;\n//     err[j]=0;\n//     rlog[j]=0;\n//   }\n while (dist<maxdist) \n   { \n     dist=part[i].dist;\n     m=part_ev[part[i].ind].type;\n     if ((m==4) && (dostars) && (dist < halorad) && (snapind==endind)) totalstarcnt++;\n     else if ((m==0) && (dostars) && (dist < (halorad * ACC_FRAC)) && (snapind==endind)) totalgascnt++;\n\n//     if ((dist<halorad) && (m>0) && (m<4) && (dist>sfl))\n//       {\n//\t d=log10(dist);\n//\t j=floor(d/(log10(halorad)/50));\n//\t err[j]++;\n//\t p[j]+=part_ev[part[i].ind].mass;\n//       }\n     if  ( ((1<<m) & use_cm) && (hmeff < (meff/2.0)) )\n       {\n\t hmeff+=part_ev[part[i].ind].mass;\n\t effrad=dist;\n       }\n     if ((dist < (halorad * 0.1) ) )\n       {\n\t innertotm+=part_ev[part[i].ind].mass;\n\t if ((m==4)) \n\t   {\n\t     galmass+= part_ev[part[i].ind].mass;\n\t     double redsh = (1/part_ev[part[i].ind].stellarage) - 1;\n\t     double sage = TIMEDIFF(redsh, (1/evolved.time)-1 );\n\t     meanage += sage;\n\t     nstars_gal++;\n\t   }\n\t else if ((m==0)) \n\t   {\n\t     gasmass+= part_ev[part[i].ind].mass;\n\t     gsfr+= part_ev[part[i].ind].sph->sfr;\n\t   }\n\t else if ((m==1)) DMmass+= part_ev[part[i].ind].mass;\n       }\n     i++;\n   }\n meanage /= nstars_gal;\n if (debug) {printf(\"totalstarcnt %d\\ntotalgascnt %d\\n\", totalstarcnt,totalgascnt);fflush(stdout);}\n if (use_cm&16)\n   {\n     i=0;\n     double mdum=0;\n     double total_mass=0;\n     double dm_mass=0;\n     dist=0;\n     while (dist<maxdist) \n       { \n\t total_mass += part_ev[part[i].ind].mass;\n\t dist=part[i].dist;\n\t m=part_ev[part[i].ind].type;\t \n\t if  (m==4) \n\t   {\n\t     if (mdum < (galmass/2.0)) \n\t       {\n\t\t mdum+=part_ev[part[i].ind].mass;\n\t\t galrad=dist;\n\t       } else break;\n\t   } else if ((m>0) && (m<4))\n\t   {\n\t     dm_mass += part_ev[part[i].ind].mass;\n\t   }\n\n\t i++;\n       }\n      fprintf(outf,\"3D half-mass-galaxy radius: %g\\n\", galrad);\n      fprintf(outf,\"total mass inside 3D half-mass-galaxy radius: %6g\\n\", total_mass);\n      fprintf(outf,\"stellar mass inside 3D half-mass-galaxy radius: %6g\\n\", mdum);\n      fprintf(outf,\"dark matter mass inside 3D half-mass-galaxy radius: %6g\\n\", dm_mass);\n   }\n fprintf(outf,\"hmeff: %f \\neffrad: %f\\n\", hmeff, effrad);\n fprintf(outf,\"Galaxy mass (M_star < 10 %% Rvir): %f \\n\", galmass);\n fprintf(outf,\"mean age: %g \\n\", meanage);\n fprintf(outf,\"SFR (< 10 %% Rvir): %g \\n\", gsfr);\n fprintf(outf,\"specific SFR (< 10 %% Rvir): %g \\n\", gsfr / galmass);\n fprintf(outf,\"Gas mass (M_gas < 10 %% Rvir): %f \\n\", gasmass);\n fprintf(outf,\"darkmatter mass (M_dm < 10 %% Rvir): %f \\n\", DMmass);\n fprintf(outf,\"Total mass < 10 %% Rvir: %f \\n\", innertotm);\n if (debug) {printf(\"Stars: %d\\ni %d\\n\",totalstarcnt, i);fflush(stdout);}\n /****************************************************************************************/\n /*Find Star Particles inside Rvir********************************************************/\n if (dostars)\n   {\n     if (debug) {printf(\"%d %d %d\\n\", snapind, endind, (snapind==endind));fflush(stdout);}\n     if (snapind==endind)\n       {\n\t starcnt=totalstarcnt;\n\t gascnt =totalgascnt;\n\t stars = (struct star*) calloc(starcnt, sizeof(struct star));\n\t gas   = (struct gaspart*) calloc(gascnt, sizeof(struct gaspart));\n\t if (debug) {printf(\"Memory for Stars allocated\\n\");fflush(stdout);}\n\t j=0;\n\t l=0;\n\t k=0;\n\t while ( (j<starcnt) || (k<gascnt) )\n\t   {\n\t     //\t     idum=0;\n//\t     for (m=0; m<6; m++)\n//\t       {\n//\t\t idum+=evolved.npart[m];\n//\t\t if (idum>part[l].ind) break;\n//\t       }\n\t     if (j>starcnt) exit(1);\n\t     m = part_ev[part[l].ind].type;\n\t     if ((m==4) && (part[l].dist < halorad))\n\t       {\n\t\t stars[j].id   =part_ev[part[l].ind].id;\n\t\t stars[j].idist=part[l].dist;\n\t\t stars[j].ifrac=part[l].dist/halorad;\n\t\t stars[j].ifrac_rhalf=part[l].dist/galrad;\n\t\t stars[j].isnap=snapind;\n\t\t stars[j].dist=part[l].dist;\n\t\t stars[j].frac=part[l].dist/halorad;\n\t\t if (stars[j].frac < ACC_FRAC) stars[j].a_acc=evolved.time;\n\t\t else stars[j].a_acc=0;\n\t\t stars[j].snap=snapind;\n\t\t stars[j].a=evolved.time;\n#ifdef POTENTIAL\n\t\t stars[j].pot=part_ev[part[l].ind].pot;\n#endif\n\t\t j++;\n\t       }\n\t     else if ((m==0) && (part[l].dist < halorad * ACC_FRAC))\n\t       {\n\n\t\t gas[k].id = part_ev[part[l].ind].id;\n\t\t double temp = temperature(part_ev[part[l].ind]);\n\t\t float vcirc = sqrt((vmass/(halorad * evolved.time))*(G*Msun*1e10/kpc))*1e-3;\n\t\t gas[k].Tvir_acc = SQR(vcirc / 167.) * 1e6;\n\t\t double rho = part_ev[part[l].ind].sph->rho * SQR(HUB) * pow(evolved.time, -3);\n\t\t if (rho < DENS_THRESH)\n\t\t   {\n\t\t     gas[k].maxtemp = temp;\n\t\t     gas[k].a_maxtemp = evolved.time;\n\t\t     gas[k].frac_maxtemp = part[l].dist / halorad;\n\t\t     gas[k].Tvir = SQR(vcirc / 167.) * 1e6;\n\t\t   }\n\t\t else \n\t\t   {\n\t\t     gas[k].maxtemp = 0;\n\t\t     gas[k].a_maxtemp = 0;\n\t\t     gas[k].frac_maxtemp = 0;\n\t\t     gas[k].Tvir = 0;\n\t\t   }\n\t\t gas[k].a_acc = evolved.time;\n\t\t gas[k].T_acc = temp;\n\t\t gas[k].a_star = 0;\n\t\t k++;\n\t       }\n\t     l++;\n\t   }\n\t if (debug) {printf(\"sorting initial stars and gas...\\n\");fflush(stdout);}\n\t //\t qsort(stars, starcnt, sizeof(struct star), (__compar_fn_t)cmp_star_id);\n\t qsort(stars, starcnt, sizeof(struct star)   , cmp_star_id);\n\t qsort(gas  , gascnt , sizeof(struct gaspart), cmp_gas_id);\n\t if (debug) {printf(\"Stars sorted\\n\");fflush(stdout);}\n       }\n     else\n       {\n\t j=0;\n\t l=0;\n\t k=0;\n\t n=0;\n\t h=0;\n\t struct star stardum;\n\t struct gaspart gasdum;\n\t if (debug) {printf(\"Search Stars..%d\\n\", starcnt);fflush(stdout);}\n\t while ( ( (j<starcnt) || (k<gascnt) )  && (l < count))\n\t   {\n//\t     idum=0;\n//\t     for (m=0; m<6; m++)\n//\t       {\n//\t\t idum+=evolved.npart[m];\n//\t\t if (idum>part[l].ind) break;\n//\t       }\n\t     m= part_ev[part[l].ind].type;\n\t     //\t     if (debug) {printf(\"#\");fflush(stdout);}\n\t     if ((m==0) || (m==4))\n\t       {\n\t\t stardum.id=part_ev[part[l].ind].id;\n\t\t struct star *fnd=bsearch(&stardum, stars, starcnt, sizeof(struct star), cmp_star_id);\n\t\t if (fnd!=NULL)\n\t\t   {\n\t\t     j++;\n\t\t     //\t\t     if (debug) {printf(\"Found one!...\\n\");fflush(stdout);}\n\t\t     if (m==4)\n\t\t       {\n\t\t\t fnd->dist=part[l].dist;\n\t\t\t fnd->frac=part[l].dist/halorad;\n\t\t\t if (fnd->frac < ACC_FRAC) fnd->a_acc=evolved.time;\n\t\t\t fnd->a=evolved.time;\n\t\t\t fnd->snap=snapind;\n#ifdef POTENTIAL\n\t\t\t fnd->pot=part_ev[part[l].ind].pot;\n#endif\t\t\t \n\t\t       } else \n\t\t       {\n\t\t\t fnd->fnd=1; \n\t\t\t fnd->gasdist=part[l].dist;\n\t\t\t if ( (fnd->ifrac <= ACC_FRAC)  )\n\t\t\t   {\n\t\t\t     addgas[h++]=l;\n\t\t\t     if (h>=ADDGAS_BUF) {fprintf(stderr, \"Increase ADDGAS_BUF\\n\");exit(1);}\n\t\t\t   }\n\t\t       }\n\t\t   } else\n\t\t   {\n\t\t     if (m==4)\n\t\t       {\n\t\t\t addstar[n++]=l;\n\t\t\t if (n>=ADDSTAR_BUF) {fprintf(stderr, \"Increase ADDSTAR_BUF\\n\");exit(1);}\n\t\t       }\n\t\t     else\n\t\t       {\n\t\t\t gasdum.id=part_ev[part[l].ind].id;\n\t\t\t struct gaspart *fndgas=bsearch(&gasdum, gas, gascnt, sizeof(struct gaspart), cmp_gas_id);\n\t\t\t if (fndgas != NULL)\n\t\t\t   {\n\t\t\t     double temp = temperature(part_ev[part[l].ind]);\n\t\t\t     double rho = part_ev[part[l].ind].sph->rho * SQR(HUB) * pow(evolved.time, -3);\n\t\t\t     if ((fndgas->maxtemp < temp) && (rho < DENS_THRESH))\n\t\t\t       {\n\t\t\t\t fndgas->maxtemp = temp;\n\t\t\t\t float vcirc = sqrt((vmass/(halorad * evolved.time))*(G*Msun*1e10/kpc))*1e-3;\n\t\t\t\t fndgas->Tvir = SQR(vcirc / 167.) * 1e6;\n\t\t\t\t fndgas->a_maxtemp = evolved.time;\n\t\t\t\t fndgas->frac_maxtemp = part[l].dist/halorad;\n\t\t\t       }\n\t\t\t     if (part[l].dist < (halorad * ACC_FRAC))\n\t\t\t       {\n\t\t\t\t fndgas->a_acc = evolved.time;\n\t\t\t\t fndgas->T_acc = temp;\n\t\t\t\t float vcirc = sqrt((vmass/(halorad * evolved.time))*(G*Msun*1e10/kpc))*1e-3;\n\t\t\t\t fndgas->Tvir_acc = SQR(vcirc / 167.) * 1e6;\n\t\t\t       }\n\t\t\t     k++;\n\t\t\t   }\n\n\t\t       }\n\t\t   }\n\t\t //\t\t j++;\n\t       }\n\t     l++;\n\t   }\n\t if (debug) {printf(\"Write Stars to list %d..\\n\",n);fflush(stdout);}\n\t if (n)\n\t   {\n\t     totalstarcnt+=n;\n\t     stars=realloc(stars, totalstarcnt* sizeof(struct star));\n\t     k=totalstarcnt-1;\n\t     while (k>=n)\n\t       {\n\t\t stars[k]=stars[k-n];\n\t\t k--;\n\t       }\n\t     for (k=0; k<n; k++)\n\t       {\n\t\t stars[k].id   =part_ev[part[addstar[k]].ind].id;\n\t\t stars[k].idist=part[addstar[k]].dist;\n\t\t stars[k].ifrac=part[addstar[k]].dist / halorad;\n\t\t stars[k].ifrac_rhalf=part[addstar[k]].dist / galrad;\n\t\t stars[k].isnap=snapind;\n\t\t stars[k].dist=part[addstar[k]].dist;\n\t\t stars[k].frac=part[addstar[k]].dist/halorad;\n\t\t if (stars[k].frac < ACC_FRAC) stars[k].a_acc=evolved.time;\n\t\t else stars[k].a_acc=0;\n\t\t stars[k].snap=snapind;\n\t\t stars[k].a=evolved.time;\n#ifdef POTENTIAL\n\t\t stars[k].pot=part_ev[part[addstar[k]].ind].pot;\n#endif\n\t       }\n\t     starcnt+=n;\n\t   }\n\t if (h)\n\t   {\n\t     totalgascnt+=h;\n\t     gas= realloc(gas, totalgascnt * sizeof(struct gaspart));\n\t     k=totalgascnt-1;\n\t     while (k>=h)\n\t       {\n\t\t gas[k] = gas[k-h];\n\t\t k--;\n\t       }\n\t     for ( k = 0; k < h; k++ )\n\t       {\n\t\t idum = addgas[k];\n\t\t gas[k].id = part_ev[part[idum].ind].id;\n\t\t double temp = temperature(part_ev[part[idum].ind]);\n\t\t float vcirc = sqrt((vmass/(halorad * evolved.time ))*(G*Msun*1e10/kpc))*1e-3;\n\t\t double rho = part_ev[part[idum].ind].sph->rho * SQR(HUB) * pow(evolved.time, -3);\n\t\t if (rho < DENS_THRESH)\n\t\t   {\n\t\t     gas[k].maxtemp = temp;\n\t\t     gas[k].Tvir = SQR(vcirc / 167.) * 1e6;\n\t\t     gas[k].a_maxtemp = evolved.time;\n\t\t     gas[k].frac_maxtemp = part[idum].dist / halorad;\n\t\t   }\n\t\t else\n\t\t   {\n\t\t     gas[k].maxtemp = 0;\n\t\t     gas[k].Tvir = 0;\n\t\t     gas[k].a_maxtemp = 0;\n\t\t     gas[k].frac_maxtemp = 0;\n\t\t   }\n\t\t if (part[idum].dist < (halorad * ACC_FRAC))\n\t\t   {\n\t\t     gas[k].a_acc = evolved.time;\n\t\t     gas[k].T_acc = temp;\n\t\t     gas[k].Tvir_acc = SQR(vcirc / 167.) * 1e6;\n\t\t   } \n\t\t else \n\t\t   {\n\t\t     gas[k].a_acc=0;\n\t\t     gas[k].T_acc=0;\n\t\t     gas[k].Tvir_acc=0;\n\t\t   }\n\t\t gas[k].a_star = evolved.time;\n\t       }\n\t     gascnt+=h;\n\t   }\n\t \n\t j=0;\n\t k=starcnt-1;\n\t while ((stars[k].fnd) && (k)) {k--;}\n\t l=0;\n\t if (debug) {printf(\"resorting Stars \\n\");fflush(stdout);}\n\t while (j<k)\n\t   {\n\t     if (stars[j].fnd)\n\t       {\n\t\t stardum=stars[j];\n\t\t stars[j]=stars[k];\n\t\t stars[k]=stardum;\n\t\t while ((stars[k].fnd) && (k)) {k--;}\n\t       }\n\t     j++;\n\t   }\n\t if (!stars[j].fnd) j++;\n\t starcnt=j;\n\t //\t qsort(stars, starcnt, sizeof(struct star), (__compar_fn_t)cmp_star_id);\n\t qsort(stars, starcnt, sizeof(struct star), cmp_star_id);\n\t qsort(gas, gascnt, sizeof(struct gaspart), cmp_gas_id);\n       }\n   }\n /****************************************************************************************/\n if (debug) printf(\"fitting...\\n\");fflush(stdout);\n// nfun=0;\n// k=0;\n// d=log10(halorad)/50;\n// for (j=0; j<50; j++)\n//   {\n//     if (err[j]!=0)\n//       {\n//     err[nfun]=1/sqrt(sqrt(err[j]));\n//     if (k==0) {\n//       rlog[nfun]=(pow(10, ((j+1)*d )))/2;\n//       p[nfun]=p[j]/((4.0/3.0)* PI * (pow(10, ((j+1)*d*3))));\n//       //       printf(\"j %d\\n\", j);\n//\n//     }\n//       else {\n//\t ddum=p[j];\n//\t rlog[nfun]=(pow(10, ((j+1)*d )) + pow(10, (k*d)))/2;\n//\t p[nfun]=p[j]/((4.0/3.0)* PI * (pow(10, ((j+1)*d*3)) - pow(10, (k*d*3))));\n//\t if (p[nfun]<0) fprintf(outf,\"%f %e %e \\n\", ddum, pow(10, ((j+1)*d*3)), pow(10, (k*d*3)) );\n//       }\n//     /*\n//     if (rlog[nfun] < SOFTENING) \n//       {\n//\t err[nfun]*=10;\n//\t printf(\"S %d\\n\", nfun);\n//       }\n//     */\n//     k=j+1;\n//     nfun++;\n//       } else {\n//\t //\t p[j]=0;\n//\t //\t err[j]=1e10;\n//       }\n//\n//\n//   }\n// \n// for (j=0; j<nfun; j++)\n//   {\n//          p[j]=log10(p[j]);\n//   }\n// \n// // auxiliary settings for fitting:\n//\n//    lm_control_type control;\n//    lm_data_type data;\n//    lm_initialize_control(&control);\n//\n//    data.user_func = fitfct;\n//    data.user_t = rlog;\n//    data.user_y = p;\n//---------------------------------------------------\n//\n// par[0]=1;\n// par[1]=10;\n// lm_minimize(nfun, 2, par, err, lm_evaluate_default, dumprintout, &data, &control);\n\n // printf(\"%f %f\\n\", d,  pow(10,d*50));\n i--;\n FILE *fp2;\n if (doascii)\n   {\n     fp2=fopen(asciifile,\"w\");\n     \n   }\n fp=fopen(idlfile,\"w\");\n fprintf(fp,\" %d %f %f %f %f %f\\n\",i,masstot,halorad,cm[0],cm[1],cm[2]);\n dist=0;\n i=0;\n while (dist < maxdist)\n   {\n     tr_halo_id[tr_halo_cnt]=part_ev[part[i].ind].id;\n     tr_halo_i[tr_halo_cnt++]=part[i].ind;\n     dist=part[i].dist;\n     double temp;\n     if (part_ev[part[i].ind].type == 0)\n       {\n\t temp = temperature(part_ev[part[i].ind]);\n       }\n     else\n       {\n\t temp=0;\n       }\n     fltarr veldum, raddum;\n     for ( j = 0; j < 3; j++ )\n       {\n\t veldum[j] = part_ev[part[i].ind].vel[j] - cvel[j];\n\t raddum[j] = part_ev[part[i].ind].pos[j] - cm[j];\n       }\n     double vrad = radvel(veldum, raddum);\n     fprintf(fp,\"%f %f %6d %3d %9.7g %8.2f\\n\",dist, part_ev[part[i].ind].mass, part_ev[part[i].ind].id, part_ev[part[i].ind].type, temp, vrad);\n     if (doascii)\n       {\n\t for (j=0; j<3; j++) fprintf(fp2, \"%12g \", part_ev[part[i].ind].pos[j]-cm[j]);\n\t for (j=0; j<3; j++) fprintf(fp2, \"%12g \", part_ev[part[i].ind].vel[j]-cvel[j]);\n\t fprintf(fp2, \" %6d \", part_ev[part[i].ind].id);\n\t fprintf(fp2, \" %6g \", part_ev[part[i].ind].mass);\n\t fprintf(fp2, \"\\n\");\n       }\n     i++;\n   }\n fprintf(outf,\"number of particles within %f times virial radius %d\\n\", tr_factor ,i);\n if (doascii)\n   {\n     fclose(fp2);\n   }\n fclose(fp);\n if (debug) printf(\"realloc...\\n\");fflush(stdout);\n tr_halo_id=realloc(tr_halo_id,sizeof(int)*tr_halo_cnt);\n tr_halo_i =realloc(tr_halo_i ,sizeof(int)*tr_halo_cnt);\n\n\n /**********************************************************************************************************************************************/\n if (debug) printf(\"lambda...\\n\");fflush(stdout);\n // for (l=-5; l<=5; l++)\n   {\n     count=vcnt; //+l*300;\n for (k=0; k<3; k++)\n   {\n     jcm[k]=0;\n     vcm[k]=0;\n     J[k]=0;\n   }\n totj=0;\n massdum=0;\n\n for (j=0; j < count; j++)\n   {\n     for (k=0; k<3; k++)\n       {\n\t vcm[k]+=(part_ev[part[j].ind].vel[k] * sqrt(evolved.time)*part_ev[part[j].ind].mass);\n\t if (pb[k]) jcm[k]+=(MOVE(part_ev[part[j].ind].pos[k],boxsz)*part_ev[part[j].ind].mass);\n\t else  jcm[k]+=(part_ev[part[j].ind].pos[k]*part_ev[part[j].ind].mass);\n       }\n      massdum+=part_ev[part[j].ind].mass;\n   }\n for (k=0; k<3; k++)\n   {\n     vcm[k]=vcm[k]/massdum;\n     jcm[k]=jcm[k]/massdum;\n     jcm[k]=jcm[k];\n     //test\n     //jcm[k]=cm[k];\n   }\n if (dojr) fp=fopen(jrfile,\"w\");\n for (j=0; j < count; j++)\n   {\n     for (k=0; k<3; k++) \n       {\n\t if (pb[k]) rdum[k]=MOVE(part_ev[part[j].ind].pos[k],boxsz)-jcm[k];\n\t else rdum[k]=part_ev[part[j].ind].pos[k]-jcm[k];\n\t vdum[k]=part_ev[part[j].ind].vel[k]-vcm[k];\n\t vdum[k] *= sqrt(evolved.time);\n       }\n     torq[0]=(rdum[1]*vdum[2]-rdum[2]*vdum[1]);\n     torq[1]=(rdum[2]*vdum[0]-rdum[0]*vdum[2]);\n     torq[2]=(rdum[0]*vdum[1]-rdum[1]*vdum[0]);\n\n     ddum=0;\n     for (k=0; k<3; k++) \n       {\n\t J[k]+=torq[k]*part_ev[part[j].ind].mass;\n\t ddum+=torq[k]*torq[k];\n       }\n     totj+=sqrt(ddum)*part_ev[part[j].ind].mass;\n     \n     ddum=0;\n     ddum1=0;\n     for (k=0; k<3; k++) {ddum+=SQR(rdum[k]); ddum1+=SQR(torq[k]);}\n     if (dojr) fprintf(fp,\"%g %g\\n\", sqrt(ddum), sqrt(ddum1)*part_ev[part[j].ind].mass);\n    }\n if (dojr) fclose(fp);\n\n\n lmd=0;\n  for (k=0; k<3; k++) {lmd+=J[k]*J[k];}\n  lmd=(sqrt(lmd)*1e10*(Msun/evolved.hubparam)*1e3*(kpc/evolved.hubparam))/(sqrt(2)*part[count-1].dist*(kpc/evolved.hubparam)*massdum*1e10*(Msun/evolved.hubparam));\n // lmd=(totj*1e10*(Msun/evolved.hubparam)*1e3*(kpc/evolved.hubparam))/(sqrt(2)*part[count-1].dist*(kpc/evolved.hubparam)*massdum*1e10*(Msun/evolved.hubparam));\n lmd=lmd/sqrt(G*massdum*1e10*(Msun/evolved.hubparam)/(part[count-1].dist*(kpc/evolved.hubparam)));\n\n fprintf(outf,\"Spin: lamda %e  r %g\\n\",lmd, part[count-1].dist);\n\n\n if (debug) printf(\"ui...\\n\");fflush(stdout);\n /*************************************************************************************************************************************************************/\n double q=1, s=1;\n double Pi[3]={0.0, 0.0, 0.0};\n double Pi_PHI=0;\n double Pi_RR=0;\n double delta;\n if (use_inertia)\n   {\n     maxdist=rad_ratio*halorad;\n     if ((use_inertia&16)) \n       {\n\t maxdist=galrad;\n\t //\t maxdist=10 * HUB; //think about it (used in feldmann 2010)\n       }\n     double s_old;\n     gsl_matrix *I = gsl_matrix_alloc (3, 3);\n     gsl_vector *eval = gsl_vector_alloc (3);\n     gsl_matrix *evec = gsl_matrix_alloc (3, 3);\n     gsl_matrix *LU = gsl_matrix_alloc (3, 3);\n     gsl_matrix *inv  = gsl_matrix_alloc (3, 3);     \n     gsl_eigen_symmv_workspace * w =  gsl_eigen_symmv_alloc (3);\n     gsl_matrix *rotation = gsl_matrix_alloc (3, 3);\n     gsl_matrix_set_identity(rotation);\n     gsl_matrix *resultmatrix = gsl_matrix_alloc (3, 3);\n     gsl_matrix_set_zero(I);\n     struct gadpart *wpart;\n      \n     wpart= (struct gadpart *)malloc(sizeof(struct gadpart)*vcnt);\n     m=0;\n     for (k=0; k < vcnt; k++)\n       {\n\t l=part[k].ind;\n\t wpart[k]=part_ev[l];\n\t for (j=0; j < 3; j++)\n\t   {\n\t     if (pb[j]) wpart[k].pos[j]=MOVEB(part_ev[l].pos[j])-MOVEB(cm[j]);\n\t       else wpart[k].pos[j]=part_ev[l].pos[j]-cm[j];\n\t     wpart[k].vel[j] -= cvel[j];\n\t   }\n\n       }\n     \n     do\n     {\n     s_old=s;\n     gsl_matrix_set_zero(I);\n     for (k=0; k < vcnt; k++)\n       {     \n\t l=part[k].ind;\n\t for (i=0; i < 3; i++)\n\t   for (j=i; j < 3; j++)\n\t     {\n\t       ddum =wpart[k].pos[i] * wpart[k].pos[j];\n\t       dist =SQR(wpart[k].pos[0])+SQR(wpart[k].pos[1]/q)+SQR(wpart[k].pos[2]/s);\n\t       ddum/= dist;\n\t       if ((sqrt(dist)<maxdist) && ((1<<wpart[k].type)&use_inertia)) \n\t\t {\n\t\t   gsl_matrix_set(I,i,j, gsl_matrix_get(I,i,j)+ddum);\n\t\t   if (i!=j) gsl_matrix_set(I,j,i, gsl_matrix_get(I,j,i)+ddum);\n\t\t }\n\t     }\n\n       }\n\n     gsl_eigen_symmv (I, eval, evec, w);\n     gsl_eigen_symmv_sort (eval, evec, GSL_EIGEN_SORT_ABS_DESC);\n     gsl_matrix_memcpy(LU, evec);\n     /*\n       for (i=0; i < 3; i++)\n       {\n       for (j=0; j < 3; j++)\n       printf(\"%15.4g\", gsl_matrix_get(I,i,j));\n       printf(\"\\n\");\n       }\n     */\n   \n     \n   for (i=0; i < 3; i++)\n     {\n       double eval_i  = gsl_vector_get (eval, i);\n       //             gsl_vector_view evec_i  = gsl_matrix_column (evec, i);\n       if (i==0) ddum = sqrt(eval_i);\n       else if (i==1) q=sqrt(eval_i)/ddum;\n       else           s=sqrt(eval_i)/ddum;\n       //printf (\"Ratio = %g\\n\", sqrt(eval_i)/ddum);\n\t     //             printf (\"eigenvector = \\n\");\n\t     //         gsl_vector_fprintf (stdout, &evec_i.vector, \"%g\");\n     }\n    \n   gsl_permutation *perm = gsl_permutation_alloc (3);\n   int sign;\n\n   gsl_linalg_LU_decomp (LU, perm, &sign);\n   gsl_linalg_LU_invert (LU, perm, inv);\n  \n\n   gsl_blas_dgemm (CblasNoTrans, CblasNoTrans,\n\t\t   1.0, inv, rotation,\n\t\t   0.0, resultmatrix);\n   gsl_matrix_memcpy (rotation, resultmatrix);\n\n   //Rotate Particles \n  gsl_vector *oldpos = gsl_vector_alloc (3);\n  gsl_vector *newpos = gsl_vector_alloc (3);  \n  gsl_vector *oldvel = gsl_vector_alloc (3);\n  gsl_vector *newvel = gsl_vector_alloc (3);\n  ddum=0;\n  for (k=0; k < vcnt; k++)\n    {\n      for (i=0; i<3; i++)\n\t{\n\t  gsl_vector_set(oldpos, i, wpart[k].pos[i]);\n\t  gsl_vector_set(oldvel, i, wpart[k].vel[i]);\n\t}\n      gsl_blas_dgemv( CblasNoTrans, 1.0, inv, oldpos, 0.0, newpos);\n      gsl_blas_dgemv( CblasNoTrans, 1.0, inv, oldvel, 0.0, newvel);\n      //ddum += gsl_blas_dnrm2 (oldvel) - gsl_blas_dnrm2 (newvel);\n      for (i=0; i<3; i++)\n\t{\n\t  wpart[k].pos[i]=gsl_vector_get(newpos, i);\n\t  wpart[k].vel[i]=gsl_vector_get(newvel, i);\n\t}\n    }\n  //printf(\"%g\\n\", ddum);\n  gsl_vector_free(oldpos);\n  gsl_vector_free(newpos);\n  gsl_vector_free(oldvel);\n  gsl_vector_free(newvel);\n  gsl_permutation_free(perm);\n     } while ((ABS(s_old-s)/s) > 1e-2);\n     \n     char rotgadfile[128];\n     if (singlefile)\n       {\n\t sprintf(rotgadfile ,\"%s.rot\",prefix);\n       } else\n       sprintf( rotgadfile, \"%s_%03d.rot\", prefix, snapind);\n\n     FILE *matrixf=fopen(rotgadfile,\"w\");\n     gsl_matrix_fwrite (matrixf, rotation);\n     fclose(matrixf);\n\n     fprintf(outf,\"longest axis = %g * R_vir\\nq = %g\\ns = %g\\n\", rad_ratio, q, s);\n\n\n     /***********************************************************************************************************************************/\n     /*Density Profile Fit      *********************************************************************************************************/\n     gadpart_dist * gpart =malloc(vcnt* sizeof(gadpart_dist));\n     for (i=0; i< vcnt; i++) \n       {\n\t gpart[i].part=wpart[i];\n\t for (j=0; j<3; j++) \n\t   {\n\t     gpart[i].part.vel[j] *= sqrt(evolved.time);\n\t   }\n\t gpart[i].dist = sqrt(SQR(gpart[i].part.pos[0]) + SQR(gpart[i].part.pos[1]) + SQR(gpart[i].part.pos[2])) * evolved.time;\n       }\n     qsort(gpart, vcnt, sizeof(gadpart_dist), cmp_dist);\n\n     double rcs;\n     double concentration = nfwfit(par, gpart, vcnt, halorad * evolved.time, sfl*evolved.time, &rcs);\n\n     fprintf(outf,\"Delta_c %f   Scale Radius %f   Concentration factor c %f\\n\", par[0], par[1], halorad/par[1]);\n     fprintf(outf,\"Error NFW: %6g\\n\", rcs);\n\n     double gamma = densproffit(par, gpart, vcnt, galrad*evolved.time, sfl*evolved.time, &rcs, 63);\n     fprintf(outf,\"logarithmic slope of density profile: %6g\\n\", gamma);\n     fprintf(outf,\"rho0 of fit: %6g\\n\", par[0]);\n     fprintf(outf,\"Error profile-fit: %6g\\n\", rcs);\n     /***********************************************************************************************************************************/\n\n     \n     //***********************************************\n     //Calculate projected half-mass-radii and VA\n     if (use_cm == 16)\n       {\n\t \n\t for (j=0; j<3; j++)\n\t   {\n\t     int dim[3];\n\t     dim[0]=j;\n\t     dim[1]=(j+1)%3;\n\t     dim[2]=(j+2)%3;\n\t     for (i=0; i< vcnt; i++) gpart[i].dist=sqrt(SQR(gpart[i].part.pos[dim[1]]) + SQR(gpart[i].part.pos[dim[2]]));\n\t     //\t     fprintf(outf,\"%g\\n\", gpart[10].dist);\n\t     //\t     qsort(gpart, vcnt, sizeof(gadpart_dist),(__compar_fn_t)  cmp_dist);\n\t     qsort(gpart, vcnt, sizeof(gadpart_dist), cmp_dist);\n\n\t     /*\n\t       r_e apperture\n\t      */\n\n\t     int count=0;\n\t     double prad=0;\n\t     double mdum=0;\n\t     double veltot=0;\n\t     double sqrveltot=0;\n\t     k=0;\n\t     while (mdum < (galmass/2.0))\n\t       {\n\t\t if (gpart[k].part.type == 4)\n\t\t   {\n\t\t     mdum+=gpart[k].part.mass;\n\t\t     prad =gpart[k].dist;\n\t\t     veltot   +=     gpart[k].part.vel[dim[0]] * gpart[k].part.mass;\n\t\t     sqrveltot+= SQR(gpart[k].part.vel[dim[0]]) *gpart[k].part.mass;\n\t\t     count++;\n\t\t   }\n\t\t k++;\n\t       }\n\t     double halfmassrad = gpart[k-1].dist;\n\t     double velmean   =    veltot / mdum;\n\t     double sqrvelmean= sqrveltot / mdum;\n\t     double sigm = sqrvelmean - SQR(velmean);\n\t     fprintf(outf,\"DIM %d (%d)| projected hm-radius: %6g | mean velocity variance %6g\\n\", j, count, prad, sqrt(sigm));\n\n\t     /*\n\t       1/2 * r_e aperture\n\t      */\n\n\t     count = 0;\n\t     prad  = 0;\n\t     mdum  = 0;\n\t     veltot= 0;\n\t     double total_mass= 0;\n\t     sqrveltot = 0;\n\t     k = 0;\n\t     while (gpart[k].dist <= (halfmassrad / 2.))\n\t       {\n\t\t if (gpart[k].part.type == 4)\n\t\t   {\n\t\t     mdum+=gpart[k].part.mass;\n\t\t     prad =gpart[k].dist;\n\t\t     veltot   +=     gpart[k].part.vel[dim[0]] * gpart[k].part.mass;\n\t\t     sqrveltot+= SQR(gpart[k].part.vel[dim[0]]) *gpart[k].part.mass;\n\t\t     count++;\n\t\t   }\n\t\t total_mass += gpart[k].part.mass;\n\t\t k++;\n\t       }\n\t     velmean = veltot / mdum;\n\t     sqrvelmean = sqrveltot / mdum;\n\t     sigm = sqrvelmean - SQR(velmean);\n\t     fprintf(outf,\"0.5 * R_1/2 aperture: DIM %d (%d)| projected hm-radius: %6g | mean velocity variance %6g | proj. stellar mass %6g | total proj. mass %6g\\n\", j, count, prad, sqrt(sigm), mdum, total_mass);\n\n\n\t     /*\n\t       1 kpc fixed radius\n\t      */\n\n\t     count = 0;\n\t     prad  = 0;\n\t     mdum  = 0;\n\t     veltot= 0;\n\t     sqrveltot = 0;\n\t     k = 0;\n\t     while (gpart[k].dist <= ( 1. * evolved.time ))\n\t       {\n\t\t if (gpart[k].part.type == 4)\n\t\t   {\n\t\t     mdum+=gpart[k].part.mass;\n\t\t     prad =gpart[k].dist;\n\t\t     veltot   +=     gpart[k].part.vel[dim[0]] * gpart[k].part.mass;\n\t\t     sqrveltot+= SQR(gpart[k].part.vel[dim[0]]) *gpart[k].part.mass;\n\t\t     count++;\n\t\t   }\n\t\t k++;\n\t       }\n\t     velmean = veltot / mdum;\n\t     sqrvelmean = sqrveltot / mdum;\n\t     sigm = sqrvelmean - SQR(velmean);\n\t     fprintf(outf,\"1 kpc fixed: DIM %d (%d)| projected hm-radius: %6g | mean velocity variance %6g | proj. stellar mass %6g\\n\", j, count, prad, sqrt(sigm), mdum);\n\n\n\t     \n\t   }\n\t\n\n       }\n     free(gpart);\n\n\n if (debug) printf(\"uva...\\n\");fflush(stdout);\n/*************************************************************************************/     \n/*Calculate Velocity anisotropy                                                      */\n\n     gadpart      * vapart=malloc(vcnt* sizeof(gadpart));\n     gadpart_dist * dpart =malloc(vcnt* sizeof(gadpart_dist));\n     int num_va=0;\n     for (i=0; i< vcnt; i++)\n       {\n\t if ((1<<(wpart[i].type))&use_va)\n\t   {\n\t     //\t     cpygadpart(&vapart[num_va]    , &wpart[i]);\n\t     //\t     cpygadpart(&dpart[num_va].part, &wpart[i]);\n\t     vapart[num_va]=wpart[i];\n\t     dpart[num_va].part=wpart[i];\n\t     dpart[num_va].dist=sqrt(SQR(wpart[i].pos[0])+SQR(wpart[i].pos[1]/q)+SQR(wpart[i].pos[2]/s));\n\t     num_va++;\n\t   }\n       }\n     if (debug) printf(\"particles copied for VA-calculation...\\n\");fflush(stdout);\n     if (num_va > 50)\n       {\n\n\t \n\t //\t qsort(&dpart[0], num_va, sizeof(gadpart_dist), (__compar_fn_t) cmp_dist);\n\t qsort(&dpart[0], num_va, sizeof(gadpart_dist),  cmp_dist);\n\n\t int distnum= gadsearch(dpart, maxdist, 0, num_va);\n\t //\t dpart= realloc(dpart, distnum*sizeof(gadpart_dist));\n\n\t if ((test) && (distnum==-1) )\n\t   printf(\"!num_va: %d %f %f %d\\n\", num_va, q, s, snapind);\n\t \n\n\n\t if (debug) printf(\"Build Tree...\\n\");fflush(stdout);\n\t KdNode * root;\n\t initKdNode(&root, NULL);\n\t buildKdTree(root, vapart, num_va, 0);\n\t if (debug) printf(\"Tree built...\\n\");fflush(stdout);\n\t if (debug) {\n\t   printf(\"check Tree...%d ?= %d\\n\", checkKdTree(root), num_va);\n\t   printf(\"min: %f %f %f %f %f\\n\", root->min, root->down->min, root->up->min, root->down->down->min, root->up->up->min);\n\t   printf(\"max: %f %f %f %f %f\\n\", root->max, root->down->max, root->up->max, root->down->down->max, root->up->up->max);\n\t   printf(\"dim: %d %d %d %d %d\\n\", root->dim, root->down->dim, root->up->dim, root->down->down->dim, root->up->up->dim);\n\t   fflush(stdout);\n\t }\n\t for (i=0; i<3; i++) Pi[j]=0;\n\t int incstep;\n\t if (distnum<120) incstep=1;\n\t else if (distnum<300) incstep=5;\n\t else if (distnum<500) incstep=10;\n\t else if (distnum<5000) incstep=30;\n\t else if (distnum<100000) incstep=50;\n\t else incstep=250;\n\n\n\n\t for (i=0; i<distnum; i+=incstep)\n\t   {\n\t     masstot=0;\n\t     gadpart_dist * knn;\n\t     double knndist=findkNN(root, &dpart[i].part, 0.5, &knn, kNN);\n\t     double meanv[3]={0.0, 0.0, 0.0};\n\t     double sqrmv[3]={0.0, 0.0, 0.0};\n\t     double R   = sqrt(SQR(dpart[i].part.pos[0])+SQR(dpart[i].part.pos[1]));\n\t     double ang;\n\t     double vR,vR2, vRsum;\n\t     double vPHI, vPHI2, vPHIsum;\n\t     for (j=0; j<3; j++)\n\t       {\n\t\t meanv[j]=dpart[i].part.vel[j]*dpart[i].part.mass;\n\t\t sqrmv[j]=SQR(dpart[i].part.vel[j])*dpart[i].part.mass;\n\t       }\n\t     ang    = atan2(dpart[i].part.pos[1], dpart[i].part.pos[0]);\n\t     vR     = dpart[i].part.vel[0]* cos(ang)+ dpart[i].part.vel[1]* sin(ang);\n\t     vR2    = SQR(vR)*dpart[i].part.mass;\n\t     vRsum  = vR*dpart[i].part.mass;\n\t     vPHI   = -dpart[i].part.vel[0]*sin(ang)+dpart[i].part.vel[1]*cos(ang);\n\t     vPHI2  = SQR(vPHI)*dpart[i].part.mass;\n\t     vPHIsum= vPHI*dpart[i].part.mass;\n\t     masstot=dpart[i].part.mass;\n\t     for (k=0; k<kNN; k++)\n\t       {\n\t\t for (j=0; j<3; j++)\n\t\t   {\n\t\t     meanv[j]+=knn[k].part.vel[j]*knn[k].part.mass;\n\t\t     sqrmv[j]+=SQR(knn[k].part.vel[j])*knn[k].part.mass;\n\t\t   }\n\t\t ang     = atan2(knn[k].part.pos[1], knn[k].part.pos[1]);\n\t\t vR      = knn[k].part.vel[0]* cos(ang)+ knn[k].part.vel[1]* sin(ang);\n\t\t vR2    += SQR(vR)*knn[k].part.mass;\n\t\t vRsum  += vR*knn[k].part.mass;\n\t\t vPHI    = -knn[k].part.vel[0]*sin(ang)+ knn[k].part.vel[1]* cos(ang);\n\t\t vPHI2  += SQR(vPHI)*knn[k].part.mass;\n\t\t vPHIsum+= vPHI*knn[k].part.mass;\n\t\t masstot+=knn[k].part.mass;\n\t       }\n\t     for (j=0; j<3; j++)\n\t       {\n\t\t meanv[j]=meanv[j]/masstot;\n\t\t sqrmv[j]=sqrmv[j]/masstot;\n\t\t double sigma=(sqrmv[j]-SQR(meanv[j]));\n\t\t Pi[j]+=(sqrmv[j]-SQR(meanv[j]));\n\t\t if (sigma < 0) printf(\"!sigmaerror!%g %g %g %g %g\\n\",sqrmv[j], meanv[j], SQR(meanv[j]), sigma, masstot);\n\t       }\n\t     vR2    = vR2/masstot;\n\t     vRsum  = vRsum/masstot;\n\t     vPHI2  = vPHI2/masstot;\n\t     vPHIsum= vPHIsum/masstot;\n\t     Pi_RR += vR2-SQR(vRsum);\n\t     Pi_PHI+= vPHI2-SQR(vPHIsum);\n\t   \n\t     //      printf(\"%5d %10.4g %10.4g %10.4g %10.4g %10.4g %10.4g %10.4g %10.4g\\n\", i, dpart[i].dist, knndist, dpart[i].part.pos[0], dpart[i].part.pos[1], dpart[i].part.pos[2], Pi[i][0], Pi[i][1], Pi[i][2]);\n\t     free(knn);\n\t   }\n\t \n\t fprintf(outf, \"PI %g %g %g\\n\", Pi[0], Pi[1], Pi[2]);\n\t double mPi=(Pi[0]+Pi[1])/2;\n\t delta= (mPi-Pi[2])/mPi;\n\t fprintf(outf, \"delta %g\\n\", delta);\n\n\t if (doFOF)\n\t {\n\t   if (debug) printf(\"look for central FOF-group...\\n\");fflush(stdout);\n\t   gadpart **FOF;\n\t   int nFOF = 0;      \n\t   int *done = NULL;\n\t   unsigned int buffer = 0;\n\t   fltarr center ={0.0, 0.0, 0.0};\n\t   \n//\t   findGadparts(root, center, 3 *  ll, &FOF, &nFOF, &buffer);\n//\t   //\t   \t   findGadparts(root, center,   ll, &FOF, &nFOF, &buffer);\n//\t   qsort(FOF, nFOF, sizeof(gadpart *), cmp_pointer_id );\n//\t   if (debug) printf(\"innermost particles determined and sorted...%d\\n\", nFOF);fflush(stdout);\n//\t   //testing\n//\t   \n//\t   if (debug) printf(\"sorted...\\n\");fflush(stdout);\n\n\t   findFOF(root, center, ll, &FOF, &nFOF, &buffer);\n\n   \t   if (debug) printf(\"central FOF-group determined...%d\\n\", nFOF);fflush(stdout);\n//\t   FILE* tmp;\n//\t   tmp = fopen(\"ids.tmp\",\"w\");\n//\t   for ( i = 0; i < nFOF; i++ )\n//\t     {\n//\t       int *fnd;\n//\t       fnd = bsearch( &(FOF[i] -> id), done, ndone, sizeof(int), cmp_int );\n//\t       if (fnd == NULL) fprintf(tmp,\"%d\\n\", FOF[i] -> id);\n//\t     }\n//\t   fclose(tmp);\n\t \n\t   double FOFmass = 0;\n\t   double FOFcenter[3] = { 0., 0., 0.};\n\t   for ( i = 0; i < nFOF; i++ )\n\t     {\n\t       FOFmass += FOF[i] -> mass;\n\t       for ( j = 0; j < 3; j++) FOFcenter[j] += FOF[i] -> pos[j] * FOF[i] -> mass;\n\t     }\n\t   double FOFdist = 0;\n\t   for ( j = 0; j < 3; j++) \n\t     {\n\t       FOFcenter[j] /= FOFmass;\n\t       FOFdist += SQR(FOFcenter[j]);\n\t     }\n\t   FOFdist = sqrt(FOFdist);\n\t   fprintf(outf, \"FOF-Mass: %f\\n\", FOFmass);\n\t   fprintf(outf, \"FOF-center: %f %f %f\\n\", FOFcenter[0], FOFcenter[1], FOFcenter[2]);\n\t   fprintf(outf, \"FOF-offset: %f\\n\", FOFdist);\n\t   \n\t   \n\n\t   if (use_cm&16)\n\t     {\n\t       i=0;\n\t       double mdum=0;\n\t       double fofrad=0;\n\t       dist=0;\n\t       while (dist<halorad) \n\t\t { \n\t\t   dist=part[i].dist;\n\t\t   m=part_ev[part[i].ind].type;\t \n\t\t   if  (m==4) \n\t\t     {\n\t\t       if (mdum < (FOFmass/2.0)) \n\t\t\t {\n\t\t\t   mdum+=part_ev[part[i].ind].mass;\n\t\t\t   fofrad=dist;\n\t\t\t } else break;\n\t\t     }\n\t\t   i++;\n\t\t }\n\t       fprintf(outf,\"3D-half-mass-FOF radius: %g\\n\", fofrad);\n\t     }\n\n\t   if (doFOF & 2)\n\t     {\n\t       char FOFfile[128];\n\t       if (singlefile)\n\t\t {\n\t\t   sprintf(FOFfile ,\"%s.fof\",prefix);\n\t\t } else\n\t\t {\n\t\t   sprintf(FOFfile ,\"%s_%03d.fof\",prefix, snapind);\n\t\t }\n\t       FILE *FOFfp = fopen(FOFfile, \"w\");\n\t       for ( i = 0; i < nFOF; i++ )\n\t\t {\n\t\t   fprintf(FOFfp, \"%d\\n\", FOF[i] -> id);\n\t\t }\n\t       fclose(FOFfp);\n\t     }\n\n\t   free(FOF);\n\t }\n\n\t free(root);\n       }\n     free(vapart);\n     free(dpart);\n\n\n/*************************************************************************************/     \n     /*\n  if (cutgad)\n   {\n     out=evolved;\n     qsort(&wpart[0],vcnt,sizeof(struct gadpart),cmp_type);\n     for (i=0; i<6; i++)\n       {\n\t out.npart[i]=0;\n\t out.nall[i]=0;\n       }\n     i=0;\n     while (i<vcnt)\n       {\n\t l=wpart[i].type;\n\t out.npart[l]++;\n\t out.nall[l]++;\n\t i++;\n       }\n     char rotgadfile[128];\n     sprintf( rotgadfile, \"%s_%03d_rot.gad\", prefix, snapind);\n     writegadget_part(rotgadfile, out, wpart);\n   }\n  */\n  gsl_matrix_free(I);\n  gsl_matrix_free(evec);\n  gsl_matrix_free(LU);\n  gsl_matrix_free(inv);\n  gsl_matrix_free(resultmatrix);\n  gsl_matrix_free(rotation);\n  gsl_vector_free(eval);\n  gsl_eigen_symmv_free(w);\n  free(wpart);\n   }\n\n /*************************************************************************************************************************************************************/\n //   endloop:\n fprintf(outf,\"\\n\\n%g %g %g %g %g %g %d %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g\\n\",cm[0],cm[1],cm[2],cm[0]-icm[0],cm[1]-icm[1],cm[2]-icm[2],vcnt,halorad, vmass ,par[0], par[1], halorad/par[1],(envdens/bgdens)-1,peakrotvel,peakr,rotvel,lmd, rad_ratio, q, s, Pi[0], Pi[1], Pi[2], Pi_RR, Pi_PHI);\n\n   }\n\n   fclose(outf);\n   free(part);\n   free(vpart);\n   free(tr_halo_i);\n   free(tr_halo_id);\n   //   free(index);\n#ifndef NOGAS\n   free(part_ev[0].sph);\n#endif\n   free(part_ev);\n//   free(pos_ev);\n//   free(id_ev);\n//   free(mass_ev);\n//   free(vel);\n\n }\n /**********************************************************************************************************************************************/\n\n  qsort(stars, totalstarcnt, sizeof(struct star), cmp_star_id);\n  if (dostars)\n    {\n  sprintf(starfile ,\"%s.stars.insitu\",prefix);\n  outf=fopen(starfile, \"w\");\n\n  for (i = 0; i < totalstarcnt; i++)\n    {\n      fprintf(outf,\"%8d %4d %8.2f %8.2f %8.7f %8.2f %4d %8.7f %1d %8.7f %8.7f %8.7f %8.7f\\n\", stars[i].id, stars[i].isnap, stars[i].idist, stars[i].dist, stars[i].frac, stars[i].gasdist, stars[i].snap, stars[i].a,  stars[i].fnd, stars[i].a_acc\n#ifdef POTENTIAL\n\t      ,stars[i].pot\n#else \n\t      , 0.\n#endif\n\t      , stars[i].ifrac, stars[i].ifrac_rhalf);\n    }\n\n  fclose(outf);\n\n  sprintf(starfile ,\"%s.gas.data\",prefix);\n  outf=fopen(starfile, \"w\");\n  for (i = 0; i < totalgascnt; i++)\n    {\n      fprintf(outf,\"%8d %8.4g %8.4g %8.4g %8.7f %8.7f %8.7f %8.4g %8.7f\\n\", gas[i].id, gas[i].maxtemp, gas[i].Tvir, gas[i].Tvir_acc, gas[i].a_maxtemp, gas[i].frac_maxtemp, gas[i].a_acc, gas[i].T_acc, gas[i].a_star);\n    }\n  fclose(outf);\n\n    }\n  printf(\"Time needed: %.2f sec\\n\",((float)clock())/CLOCKS_PER_SEC);\n  return 0;\n}\n", "meta": {"hexsha": "fac1d1cf6d3081ae7767a101a29d014982d824d3", "size": 60799, "ext": "c", "lang": "C", "max_stars_repo_path": "trace.c", "max_stars_repo_name": "Fette3lke/GadTools", "max_stars_repo_head_hexsha": "164263b8084e32e15022df81e35448cfa02f1ab1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "trace.c", "max_issues_repo_name": "Fette3lke/GadTools", "max_issues_repo_head_hexsha": "164263b8084e32e15022df81e35448cfa02f1ab1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-01-12T14:40:32.000Z", "max_issues_repo_issues_event_max_datetime": "2017-01-12T14:40:32.000Z", "max_forks_repo_path": "trace.c", "max_forks_repo_name": "lgo33/GadTools", "max_forks_repo_head_hexsha": "164263b8084e32e15022df81e35448cfa02f1ab1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9664213431, "max_line_length": 307, "alphanum_fraction": 0.5354693334, "num_tokens": 21252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.468790611783139, "lm_q2_score": 0.015906388300482414, "lm_q1q2_score": 0.007456765502643316}}
{"text": "// Copyright (c) 2013-2016 Anton Kozhevnikov, Thomas Schulthess\n// All rights reserved.\n// \n// Redistribution and use in source and binary forms, with or without modification, are permitted provided that \n// the following conditions are met:\n// \n// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the \n//    following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions \n//    and the following disclaimer in the documentation and/or other materials provided with the distribution.\n// \n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED \n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A \n// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR \n// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, \n// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER \n// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR \n// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n/** \\file sirius_internal.h\n *   \n *  \\brief Contains basic definitions and declarations.\n */\n\n#ifndef __SIRIUS_INTERNAL_H__\n#define __SIRIUS_INTERNAL_H__\n\n#include <omp.h>\n#include <signal.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <gsl/gsl_sf_bessel.h>\n#include <fftw3.h>\n#include <vector>\n#include <complex>\n#include <iostream>\n#include <algorithm>\n#include \"config.h\"\n#include \"communicator.hpp\"\n#include \"gpu.h\"\n#include \"runtime.h\"\n\n#ifdef __PLASMA\nextern \"C\" void plasma_init(int num_cores);\n#endif\n\n#ifdef __LIBSCI_ACC\nextern \"C\" void libsci_acc_init();\nextern \"C\" void libsci_acc_finalize();\n#endif\n\n/// Namespace of the SIRIUS library.\nnamespace sirius {\n\n    inline void initialize(bool call_mpi_init__)\n    {\n        if (call_mpi_init__) Communicator::initialize();\n\n        #ifdef __GPU\n        cuda_create_streams(omp_get_max_threads() + 1);\n        cublas_create_handles(omp_get_max_threads() + 1);\n        #endif\n        #ifdef __MAGMA\n        magma_init_wrapper();\n        #endif\n        #ifdef __PLASMA\n        plasma_init(omp_get_max_threads());\n        #endif\n        #ifdef __LIBSCI_ACC\n        libsci_acc_init();\n        #endif\n\n        assert(sizeof(int) == 4);\n        assert(sizeof(double) == 8);\n    }\n\n    inline void finalize()\n    {\n        Communicator::finalize();\n        #ifdef __MAGMA\n        magma_finalize_wrapper();\n        #endif\n        #ifdef __LIBSCI_ACC\n        libsci_acc_finalize();\n        #endif\n        #ifdef __GPU\n        cublas_destroy_handles(omp_get_max_threads() + 1);\n        cuda_destroy_streams();\n        cuda_device_reset();\n        #endif\n        fftw_cleanup();\n    }\n};\n\n#define TERMINATE_NO_GPU TERMINATE(\"not compiled with GPU support\");\n\n#define TERMINATE_NO_SCALAPACK TERMINATE(\"not compiled with ScaLAPACK support\");\n\n#define TERMINATE_NOT_IMPLEMENTED TERMINATE(\"feature is not implemented\");\n\n#endif // __SIRIUS_INTERNAL_H__\n\n/** \\mainpage Welcome to SIRIUS\n *  \\section intro Introduction\n *  SIRIUS is a domain-specific library for electronic structure calculations. It supports full-potential linearized\n *  augmented plane wave (FP-LAPW) and pseudopotential plane wave (PP-PW) methods and is designed to work with codes\n *  such as Exciting, Elk, Quantum ESPRESSO, etc.\n *  \\section install Installation\n *   ...\n */\n\n/** \\page stdvarname Standard variable names\n *   \n *  Below is the list of standard names for some of the loop variables:\n *  \n *  l - index of orbital quantum number \\n\n *  m - index of azimutal quantum nuber \\n\n *  lm - combined index of (l,m) quantum numbers \\n\n *  ia - index of atom \\n\n *  ic - index of atom class \\n\n *  iat - index of atom type \\n\n *  ir - index of r-point \\n\n *  ig - index of G-vector \\n\n *  idxlo - index of local orbital \\n\n *  idxrf - index of radial function \\n\n *  xi - compbined index of lm and idxrf (product of angular and radial functions) \\n\n *  ik - index of k-point \\n\n *  itp - index of (theta, phi) spherical angles \\n\n *\n *  The _loc suffix is often added to the variables to indicate that they represent the local fraction of the elements\n *  assigned to the given MPI rank.\n */\n\n//! \\page coding Coding style\n//!     \n//! Below are some basic style rules that we follow:\n//!     - Page width is approximately 120 characters. Screens are wide nowdays and 80 characters is an \n//!       obsolete restriction. Going slightly over 120 characters is allowed if it is requird for the line continuity.\n//!     - Identation: 4 spaces (no tabs)\n//!     - Coments are inserted before the code with slash-star style starting with the lower case:\n//!       \\code{.cpp}\n//!           /* call a very important function */\n//!           do_something();\n//!       \\endcode\n//!     - Spaces between most operators:\n//!       \\code{.cpp}\n//!           if (i < 5) {\n//!               j = 5;\n//!           }\n//!\n//!           for (int k = 0; k < 3; k++)\n//!\n//!           int lm = l * l + l + m;\n//!\n//!           double d = std::abs(e);\n//!\n//!           int k = idx[3];\n//!       \\endcode\n//!     - Spaces between function arguments:\n//!       \\code{.cpp}\n//!           double d = some_func(a, b, c);\n//!       \\endcode\n//!       but not\n//!       \\code{.cpp}\n//!           double d=some_func(a,b,c);\n//!       \\endcode\n//!       or\n//!       \\code{.cpp}\n//!           double d = some_func( a, b, c );\n//!       \\endcode\n//!     - Spaces between template arguments, but not between <> brackets:\n//!       \\code{.cpp}\n//!           std::vector<std::array<int, 2>> vec;\n//!       \\endcode\n//!       but not\n//!       \\code{.cpp}\n//!           std::vector< std::array< int, 2 > > vec;\n//!       \\endcode\n//!     - Curly braces for classes and functions start form the new line:\n//!       \\code{.cpp}\n//!           class A\n//!           {\n//!               ....\n//!           };\n//!\n//!           inline int num_points()\n//!           {\n//!               return num_points_;\n//!           }\n//!       \\endcode\n//!     - Curly braces for if-statements, for-loops, switch-case statements, etc. start at the end of the line:\n//!       \\code{.cpp}\n//!           for (int i: {0, 1, 2}) {\n//!               some_func(i);\n//!           }\n//!\n//!           if (a == 0) {\n//!               printf(\"a is zero\");\n//!           } else {\n//!               printf(\"a is not zero\");\n//!           }\n//!\n//!           switch (i) {\n//!               case 1: {\n//!                   do_something();\n//!                   break;\n//!               case 2: {\n//!                   do_something_else();\n//!                   break;\n//!               }\n//!           }\n//!       \\endcode\n//!     - Even single line 'if' statements and 'for' loops must have the curly brackes:\n//!       \\code{.cpp}  \n//!           if (i == 4) {\n//!               some_variable = 5;\n//!           }\n//!\n//!           for (int k = 0; k < 10; k++) {\n//!               do_something(k);\n//!           }\n//!       \\endcode\n//!     - Reference and pointer symbols are part of type:\n//!       \\code{.cpp}\n//!           std::vector<double>& vec = make_vector();\n//!\n//!           double* ptr = &vec[0];\n//!\n//!           auto& atom = unit_cell().atom(ia);\n//!       \\endcode\n//!     - Const modifier follows the type declaration:\n//!       \\code{.cpp}\n//!           std::vector<int> const& idx() const\n//!           {\n//!               return idx_;\n//!           }\n//!       \\endcode\n//!     - Names of class members end with underscore:\n//!       \\code{.cpp}\n//!           class A\n//!           {\n//!               private:\n//!                   int lmax_;\n//!           };\n//!       \\endcode\n//!     - Setter method starts from set_, getter method is a variable name itself:\n//!       \\code{.cpp}\n//!           class A\n//!           {\n//!               private:\n//!                   int lmax_;\n//!               public:\n//!                   int lmax() const\n//!                   {\n//!                       return lmax_;\n//!                   }\n//!                   void set_lmax(int lmax__)\n//!                   {\n//!                       lmax_ = lmax__;\n//!                   }\n//!           };\n//!       \\endcode\n//!     - Single-line functions should not be flattened:\n//!       \\code{.cpp}\n//!           struct A\n//!           {\n//!               int lmax() const\n//!               {\n//!                   return lmax_;\n//!               }\n//!           };\n//!       \\endcode\n//!       but not\n//!       \\code{.cpp}\n//!           struct A\n//!           {\n//!               int lmax() const { return lmax_; }\n//!           };\n//!       \\endcode\n//!     - Header guards have a standard name: double underscore + file name in capital letters + double underscore\n//!       \\code{.cpp}\n//!           #ifndef __SIRIUS_INTERNAL_H__\n//!           #define __SIRIUS_INTERNAL_H__\n//!           ...\n//!           #endif // __SIRIUS_INTERNAL_H__\n//!       \\endcode\n//! We use clang-format utility to enforce the basic formatting style. Please have a look at .clang-format config file \n//! in the source root folder for the definitions.\n//!        \n//! Class naming convention.\n//!      \n//! Problem: all 'standard' naming conventions are not satisfactory. For example, we have a class \n//! which does a DFT ground state. Following the common naming conventions it could be named like this:\n//! DFTGroundState, DftGroundState, dft_ground_state. Last two are bad, because DFT (and not Dft or dft)\n//! is a well recognized abbreviation. First one is band because capital G adds to DFT and we automaticaly\n//! read DFTG round state.\n//! \n//! Solution: we can propose the following: DFTgroundState or DFT_ground_state. The first variant still \n//! doens't look very good because one of the words is captalized (State) and one (ground) - is not. So we pick \n//! the second variant: DFT_ground_state (by the way, this is close to the Bjarne Stroustrup's naiming convention,\n//! where he uses first capital letter and underscores, for example class Io_obj).\n//!\n//! Some other examples:\n//!     - class Ground_state (composed of two words) \n//!     - class FFT_interface (composed of an abbreviation and a word)\n//!     - class Interface_XC (composed of a word and abbreviation)\n//!     - class Spline (single word)\n//!     \n//! Exceptions are allowed if it makes sense. For example, low level utility classes like 'mdarray' (multi-dimentional\n//! array) or 'pstdout' (parallel standard output) are named with small letters. \n//!\n", "meta": {"hexsha": "15b58c021921db73a70b6904ca815bef9f371a68", "size": 10800, "ext": "h", "lang": "C", "max_stars_repo_path": "src/sirius_internal.h", "max_stars_repo_name": "cocteautwins/SIRIUS-develop", "max_stars_repo_head_hexsha": "8ab09ca7cc69e9a7dc76475b7b562b20d56deea3", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/sirius_internal.h", "max_issues_repo_name": "cocteautwins/SIRIUS-develop", "max_issues_repo_head_hexsha": "8ab09ca7cc69e9a7dc76475b7b562b20d56deea3", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sirius_internal.h", "max_forks_repo_name": "cocteautwins/SIRIUS-develop", "max_forks_repo_head_hexsha": "8ab09ca7cc69e9a7dc76475b7b562b20d56deea3", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5047923323, "max_line_length": 119, "alphanum_fraction": 0.5780555556, "num_tokens": 2576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16667541296674693, "lm_q2_score": 0.044680869636601735, "lm_q1q2_score": 0.0074472023983939775}}
{"text": "/* err/env.c\n * \n * Copyright (C) 2001, 2007 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <stdlib.h>\n#include <gsl/gsl_errno.h>\n\n#define STR_EQ(x,y) (strcmp((x),(y)) == 0)\n\nvoid\ngsl_err_env_setup (void)\n{\n  const char * p = getenv(\"GSL_ERROR_MODE\") ;\n\n  if (p == 0)  /* GSL_ERROR_MODE environment variable is not set */\n    return ;\n\n  if (*p == '\\0') /* GSL_ERROR_MODE environment variable is empty */\n    return ;\n\n  printf(\"GSL_ERROR_MODE=\\\"\") ;\n  \n  if (STR_EQ(p, \"abort\"))\n    {\n      gsl_set_error_handler (NULL);\n      printf(\"abort\") ;\n    }\n\n  printf(\"\\\"\\n\") ;\n}\n\n\n\n\n\n", "meta": {"hexsha": "f1b4203e8e0a8d066f15decf939f822cf871f62f", "size": 1302, "ext": "c", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/err/env.c", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/err/env.c", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/err/env.c", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 25.0384615385, "max_line_length": 81, "alphanum_fraction": 0.6774193548, "num_tokens": 340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20181322226037884, "lm_q2_score": 0.036769462513209006, "lm_q1q2_score": 0.007420563710572917}}
{"text": "#ifndef PYGSL_STATMODULE_H\n#define PYGSL_STATMODULE_H 1\n\n#include <pygsl/error_helpers.h>\n#include <pygsl/block_helpers.h>\n#include <gsl/gsl_statistics.h>\n#include <Python.h>\n\n/*\n * This api will be only exported to the various  statistics\n * modules.\n */\nstatic void **PyGSL_STATISTICS_API = NULL;\n\n\n\n#define PyGSL_STATISTICS_d_A_NUM    0\n#define PyGSL_STATISTICS_l_A_NUM    1 \n#define PyGSL_STATISTICS_d_Ad_NUM   2\n#define PyGSL_STATISTICS_d_AA_NUM   3 \n#define PyGSL_STATISTICS_d_AAd_NUM  4\n#define PyGSL_STATISTICS_d_AAdd_NUM 5\n#define PyGSL_STATISTICS_d_Add_NUM  6\n#define PyGSL_STATISTICS_ll_A_NUM   7\n\n\n\n\n\n#define PyGSL_STATISTICS_d_A_PROTO  (PyObject *self, PyObject *args, \\\n\t\t     double (*pointer)(const void *, size_t, size_t),\\\n\t\t     int array_type, int basis_type_size) \n\n#define PyGSL_STATISTICS_l_A_PROTO   (PyObject *self, PyObject *args, \\\n\t\t      size_t (*pointer)(const void *, size_t, size_t), \\\n\t\t      int array_type, int basis_type_size)\n\n#define PyGSL_STATISTICS_d_Ad_PROTO  (PyObject *self, PyObject *args, \\\n\t\t       double (*pointer)(const void *, size_t, size_t, double), \\\n\t\t       int array_type, int basis_type_size)\n\n#define PyGSL_STATISTICS_d_AA_PROTO  (PyObject *self, PyObject *args, \\\n\t\t      double (*pointer)(const void  *, size_t,const void *, size_t, size_t), \\\n\t\t      int array_type, int basis_type_size)\n\n#define PyGSL_STATISTICS_d_AAd_PROTO (PyObject *self, PyObject *args, \\\n\t\t       double (*pointer)(const void *, size_t,const void *, size_t, size_t, double), \\\n\t\t       int array_type, int basis_type_size)\n\n\n#define PyGSL_STATISTICS_d_AAdd_PROTO (PyObject *self, PyObject *args, \\\n\t\t\tdouble (*pointer)(const void *, size_t,const void *, size_t, size_t, double, double), \\\n\t\t\tint array_type, int basis_type_size)\n\n#define PyGSL_STATISTICS_d_Add_PROTO (PyObject *self, PyObject *args, \\\n\t\t       double (*pointer)(const void *, size_t, size_t, double, double), \\\n\t\t       int array_type, int basis_type_size)\n\n#define PyGSL_STATISTICS_ll_A_PROTO  (PyObject *self, PyObject *args, \\\n\t\t      void (*pointer)(size_t *, size_t *, const void *, size_t, size_t), \\\n\t\t      int array_type, int basis_type_size)\n\n\n#if defined(PyGSL_STATISTICS_IMPORT_API)                   \nextern PyObject *  PyGSL_statistics_d_A    PyGSL_STATISTICS_d_A_PROTO;\nextern PyObject *  PyGSL_statistics_l_A    PyGSL_STATISTICS_l_A_PROTO;\nextern PyObject *  PyGSL_statistics_d_Ad   PyGSL_STATISTICS_d_Ad_PROTO;  \nextern PyObject *  PyGSL_statistics_d_AA   PyGSL_STATISTICS_d_AA_PROTO;  \nextern PyObject *  PyGSL_statistics_d_AAd  PyGSL_STATISTICS_d_AAd_PROTO; \nextern PyObject *  PyGSL_statistics_d_AAdd PyGSL_STATISTICS_d_AAdd_PROTO;\nextern PyObject *  PyGSL_statistics_d_Add  PyGSL_STATISTICS_d_Add_PROTO; \nextern PyObject *  PyGSL_statistics_ll_A   PyGSL_STATISTICS_ll_A_PROTO;  \n\n#define PyGSL_statistics_d_A    (*(PyObject* (*) PyGSL_STATISTICS_d_A_PROTO)    PyGSL_STATISTICS_API[PyGSL_STATISTICS_d_A_NUM])\n#define PyGSL_statistics_l_A    (*(PyObject* (*) PyGSL_STATISTICS_l_A_PROTO)    PyGSL_STATISTICS_API[PyGSL_STATISTICS_l_A_NUM])\n#define PyGSL_statistics_d_Ad   (*(PyObject* (*) PyGSL_STATISTICS_d_Ad_PROTO)   PyGSL_STATISTICS_API[PyGSL_STATISTICS_d_Ad_NUM])\n#define PyGSL_statistics_d_AA   (*(PyObject* (*) PyGSL_STATISTICS_d_AA_PROTO)   PyGSL_STATISTICS_API[PyGSL_STATISTICS_d_AA_NUM])\n#define PyGSL_statistics_d_AAd  (*(PyObject* (*) PyGSL_STATISTICS_d_AAd_PROTO)  PyGSL_STATISTICS_API[PyGSL_STATISTICS_d_AAd_NUM])\n#define PyGSL_statistics_d_AAdd (*(PyObject* (*) PyGSL_STATISTICS_d_AAdd_PROTO) PyGSL_STATISTICS_API[PyGSL_STATISTICS_d_AAdd_NUM])\n#define PyGSL_statistics_d_Add  (*(PyObject* (*) PyGSL_STATISTICS_d_Add_PROTO)  PyGSL_STATISTICS_API[PyGSL_STATISTICS_d_Add_NUM])\n#define PyGSL_statistics_ll_A   (*(PyObject* (*) PyGSL_STATISTICS_ll_A_PROTO)   PyGSL_STATISTICS_API[PyGSL_STATISTICS_ll_A_NUM])\n\n#else \nstatic PyObject *  PyGSL_statistics_d_A    PyGSL_STATISTICS_d_A_PROTO;\nstatic PyObject *  PyGSL_statistics_l_A    PyGSL_STATISTICS_l_A_PROTO;\nstatic PyObject *  PyGSL_statistics_d_Ad   PyGSL_STATISTICS_d_Ad_PROTO;  \nstatic PyObject *  PyGSL_statistics_d_AA   PyGSL_STATISTICS_d_AA_PROTO;  \nstatic PyObject *  PyGSL_statistics_d_AAd  PyGSL_STATISTICS_d_AAd_PROTO; \nstatic PyObject *  PyGSL_statistics_d_AAdd PyGSL_STATISTICS_d_AAdd_PROTO;\nstatic PyObject *  PyGSL_statistics_d_Add  PyGSL_STATISTICS_d_Add_PROTO; \nstatic PyObject *  PyGSL_statistics_ll_A   PyGSL_STATISTICS_ll_A_PROTO;  \n\n#endif \n#define import_pygsl_stats() \\\n{ \\\n   PyObject *pygsl = NULL, *c_api = NULL, *md = NULL; \\\n   if ( \\\n      (pygsl = PyImport_ImportModule(\"pygsl.statistics._stat\"))   != NULL && \\\n      (md = PyModule_GetDict(pygsl))                              != NULL && \\\n      (c_api = PyDict_GetItemString(md, \"_PYGSL_STATISTICS_API\")) != NULL && \\\n      (PyCObject_Check(c_api))                                        \\\n     ) { \\\n\t PyGSL_STATISTICS_API = (void **)PyCObject_AsVoidPtr(c_api); \\\n   } else { \\\n        fprintf(stderr, \"Could not init pygsl.statistics._stat!\\n\"); \\\n        PyGSL_STATISTICS_API = NULL; \\\n   } \\\n   DEBUG_MESS(2, \"PyGSL_API points to %p and PyGSL_STATISTICS_API points to %p\\n\", (void *) PyGSL_API, (void *) PyGSL_STATISTICS_API);  \\\n}\n\n#endif /* PYGSL_STATMODULE_H */\n", "meta": {"hexsha": "627ada69a3466cc5d4b5ef6ef1a2e00dc1df897e", "size": 5228, "ext": "h", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/src/statistics/statmodule.h", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/src/statistics/statmodule.h", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/src/statistics/statmodule.h", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 46.6785714286, "max_line_length": 137, "alphanum_fraction": 0.7484697781, "num_tokens": 1471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3593641588823762, "lm_q2_score": 0.020645930852204692, "lm_q1q2_score": 0.00741940757504624}}
{"text": "/* matrix/gsl_matrix_char.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_MATRIX_CHAR_H__\n#define __GSL_MATRIX_CHAR_H__\n\n#if !defined( GSL_FUN )\n#  if !defined( GSL_DLL )\n#    define GSL_FUN extern\n#  elif defined( BUILD_GSL_DLL )\n#    define GSL_FUN extern __declspec(dllexport)\n#  else\n#    define GSL_FUN extern __declspec(dllimport)\n#  endif\n#endif\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_inline.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_vector_char.h>\n#include <gsl/gsl_blas_types.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size1;\n  size_t size2;\n  size_t tda;\n  char * data;\n  gsl_block_char * block;\n  int owner;\n} gsl_matrix_char;\n\ntypedef struct\n{\n  gsl_matrix_char matrix;\n} _gsl_matrix_char_view;\n\ntypedef _gsl_matrix_char_view gsl_matrix_char_view;\n\ntypedef struct\n{\n  gsl_matrix_char matrix;\n} _gsl_matrix_char_const_view;\n\ntypedef const _gsl_matrix_char_const_view gsl_matrix_char_const_view;\n\n/* Allocation */\n\nGSL_FUN gsl_matrix_char * \ngsl_matrix_char_alloc (const size_t n1, const size_t n2);\n\nGSL_FUN gsl_matrix_char * \ngsl_matrix_char_calloc (const size_t n1, const size_t n2);\n\nGSL_FUN gsl_matrix_char * \ngsl_matrix_char_alloc_from_block (gsl_block_char * b, \n                                   const size_t offset, \n                                   const size_t n1, \n                                   const size_t n2, \n                                   const size_t d2);\n\nGSL_FUN gsl_matrix_char * \ngsl_matrix_char_alloc_from_matrix (gsl_matrix_char * m,\n                                    const size_t k1, \n                                    const size_t k2,\n                                    const size_t n1, \n                                    const size_t n2);\n\nGSL_FUN gsl_vector_char * \ngsl_vector_char_alloc_row_from_matrix (gsl_matrix_char * m,\n                                        const size_t i);\n\nGSL_FUN gsl_vector_char * \ngsl_vector_char_alloc_col_from_matrix (gsl_matrix_char * m,\n                                        const size_t j);\n\nGSL_FUN void gsl_matrix_char_free (gsl_matrix_char * m);\n\n/* Views */\n\nGSL_FUN _gsl_matrix_char_view \ngsl_matrix_char_submatrix (gsl_matrix_char * m, \n                            const size_t i, const size_t j, \n                            const size_t n1, const size_t n2);\n\nGSL_FUN _gsl_vector_char_view \ngsl_matrix_char_row (gsl_matrix_char * m, const size_t i);\n\nGSL_FUN _gsl_vector_char_view \ngsl_matrix_char_column (gsl_matrix_char * m, const size_t j);\n\nGSL_FUN _gsl_vector_char_view \ngsl_matrix_char_diagonal (gsl_matrix_char * m);\n\nGSL_FUN _gsl_vector_char_view \ngsl_matrix_char_subdiagonal (gsl_matrix_char * m, const size_t k);\n\nGSL_FUN _gsl_vector_char_view \ngsl_matrix_char_superdiagonal (gsl_matrix_char * m, const size_t k);\n\nGSL_FUN _gsl_vector_char_view\ngsl_matrix_char_subrow (gsl_matrix_char * m, const size_t i,\n                         const size_t offset, const size_t n);\n\nGSL_FUN _gsl_vector_char_view\ngsl_matrix_char_subcolumn (gsl_matrix_char * m, const size_t j,\n                            const size_t offset, const size_t n);\n\nGSL_FUN _gsl_matrix_char_view\ngsl_matrix_char_view_array (char * base,\n                             const size_t n1, \n                             const size_t n2);\n\nGSL_FUN _gsl_matrix_char_view\ngsl_matrix_char_view_array_with_tda (char * base, \n                                      const size_t n1, \n                                      const size_t n2,\n                                      const size_t tda);\n\n\nGSL_FUN _gsl_matrix_char_view\ngsl_matrix_char_view_vector (gsl_vector_char * v,\n                              const size_t n1, \n                              const size_t n2);\n\nGSL_FUN _gsl_matrix_char_view\ngsl_matrix_char_view_vector_with_tda (gsl_vector_char * v,\n                                       const size_t n1, \n                                       const size_t n2,\n                                       const size_t tda);\n\n\nGSL_FUN _gsl_matrix_char_const_view \ngsl_matrix_char_const_submatrix (const gsl_matrix_char * m, \n                                  const size_t i, const size_t j, \n                                  const size_t n1, const size_t n2);\n\nGSL_FUN _gsl_vector_char_const_view \ngsl_matrix_char_const_row (const gsl_matrix_char * m, \n                            const size_t i);\n\nGSL_FUN _gsl_vector_char_const_view \ngsl_matrix_char_const_column (const gsl_matrix_char * m, \n                               const size_t j);\n\nGSL_FUN _gsl_vector_char_const_view\ngsl_matrix_char_const_diagonal (const gsl_matrix_char * m);\n\nGSL_FUN _gsl_vector_char_const_view \ngsl_matrix_char_const_subdiagonal (const gsl_matrix_char * m, \n                                    const size_t k);\n\nGSL_FUN _gsl_vector_char_const_view \ngsl_matrix_char_const_superdiagonal (const gsl_matrix_char * m, \n                                      const size_t k);\n\nGSL_FUN _gsl_vector_char_const_view\ngsl_matrix_char_const_subrow (const gsl_matrix_char * m, const size_t i,\n                               const size_t offset, const size_t n);\n\nGSL_FUN _gsl_vector_char_const_view\ngsl_matrix_char_const_subcolumn (const gsl_matrix_char * m, const size_t j,\n                                  const size_t offset, const size_t n);\n\nGSL_FUN _gsl_matrix_char_const_view\ngsl_matrix_char_const_view_array (const char * base,\n                                   const size_t n1, \n                                   const size_t n2);\n\nGSL_FUN _gsl_matrix_char_const_view\ngsl_matrix_char_const_view_array_with_tda (const char * base, \n                                            const size_t n1, \n                                            const size_t n2,\n                                            const size_t tda);\n\nGSL_FUN _gsl_matrix_char_const_view\ngsl_matrix_char_const_view_vector (const gsl_vector_char * v,\n                                    const size_t n1, \n                                    const size_t n2);\n\nGSL_FUN _gsl_matrix_char_const_view\ngsl_matrix_char_const_view_vector_with_tda (const gsl_vector_char * v,\n                                             const size_t n1, \n                                             const size_t n2,\n                                             const size_t tda);\n\n/* Operations */\n\nGSL_FUN void gsl_matrix_char_set_zero (gsl_matrix_char * m);\nGSL_FUN void gsl_matrix_char_set_identity (gsl_matrix_char * m);\nGSL_FUN void gsl_matrix_char_set_all (gsl_matrix_char * m, char x);\n\nGSL_FUN int gsl_matrix_char_fread (FILE * stream, gsl_matrix_char * m) ;\nGSL_FUN int gsl_matrix_char_fwrite (FILE * stream, const gsl_matrix_char * m) ;\nGSL_FUN int gsl_matrix_char_fscanf (FILE * stream, gsl_matrix_char * m);\nGSL_FUN int gsl_matrix_char_fprintf (FILE * stream, const gsl_matrix_char * m, const char * format);\n \nGSL_FUN int gsl_matrix_char_memcpy(gsl_matrix_char * dest, const gsl_matrix_char * src);\nGSL_FUN int gsl_matrix_char_swap(gsl_matrix_char * m1, gsl_matrix_char * m2);\nGSL_FUN int gsl_matrix_char_tricpy(CBLAS_UPLO_t Uplo, CBLAS_DIAG_t Diag, gsl_matrix_char * dest, const gsl_matrix_char * src);\n\nGSL_FUN int gsl_matrix_char_swap_rows(gsl_matrix_char * m, const size_t i, const size_t j);\nGSL_FUN int gsl_matrix_char_swap_columns(gsl_matrix_char * m, const size_t i, const size_t j);\nGSL_FUN int gsl_matrix_char_swap_rowcol(gsl_matrix_char * m, const size_t i, const size_t j);\nGSL_FUN int gsl_matrix_char_transpose (gsl_matrix_char * m);\nGSL_FUN int gsl_matrix_char_transpose_memcpy (gsl_matrix_char * dest, const gsl_matrix_char * src);\nGSL_FUN int gsl_matrix_char_transpose_tricpy (CBLAS_UPLO_t Uplo_src, CBLAS_DIAG_t Diag, gsl_matrix_char * dest, const gsl_matrix_char * src);\n\nGSL_FUN char gsl_matrix_char_max (const gsl_matrix_char * m);\nGSL_FUN char gsl_matrix_char_min (const gsl_matrix_char * m);\nGSL_FUN void gsl_matrix_char_minmax (const gsl_matrix_char * m, char * min_out, char * max_out);\n\nGSL_FUN void gsl_matrix_char_max_index (const gsl_matrix_char * m, size_t * imax, size_t *jmax);\nGSL_FUN void gsl_matrix_char_min_index (const gsl_matrix_char * m, size_t * imin, size_t *jmin);\nGSL_FUN void gsl_matrix_char_minmax_index (const gsl_matrix_char * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);\n\nGSL_FUN int gsl_matrix_char_equal (const gsl_matrix_char * a, const gsl_matrix_char * b);\n\nGSL_FUN int gsl_matrix_char_isnull (const gsl_matrix_char * m);\nGSL_FUN int gsl_matrix_char_ispos (const gsl_matrix_char * m);\nGSL_FUN int gsl_matrix_char_isneg (const gsl_matrix_char * m);\nGSL_FUN int gsl_matrix_char_isnonneg (const gsl_matrix_char * m);\n\nGSL_FUN int gsl_matrix_char_add (gsl_matrix_char * a, const gsl_matrix_char * b);\nGSL_FUN int gsl_matrix_char_sub (gsl_matrix_char * a, const gsl_matrix_char * b);\nGSL_FUN int gsl_matrix_char_mul_elements (gsl_matrix_char * a, const gsl_matrix_char * b);\nGSL_FUN int gsl_matrix_char_div_elements (gsl_matrix_char * a, const gsl_matrix_char * b);\nGSL_FUN int gsl_matrix_char_scale (gsl_matrix_char * a, const double x);\nGSL_FUN int gsl_matrix_char_scale_rows (gsl_matrix_char * a, const gsl_vector_char * x);\nGSL_FUN int gsl_matrix_char_scale_columns (gsl_matrix_char * a, const gsl_vector_char * x);\nGSL_FUN int gsl_matrix_char_add_constant (gsl_matrix_char * a, const double x);\nGSL_FUN int gsl_matrix_char_add_diagonal (gsl_matrix_char * a, const double x);\n\n/***********************************************************************/\n/* The functions below are obsolete                                    */\n/***********************************************************************/\nGSL_FUN int gsl_matrix_char_get_row(gsl_vector_char * v, const gsl_matrix_char * m, const size_t i);\nGSL_FUN int gsl_matrix_char_get_col(gsl_vector_char * v, const gsl_matrix_char * m, const size_t j);\nGSL_FUN int gsl_matrix_char_set_row(gsl_matrix_char * m, const size_t i, const gsl_vector_char * v);\nGSL_FUN int gsl_matrix_char_set_col(gsl_matrix_char * m, const size_t j, const gsl_vector_char * v);\n/***********************************************************************/\n\n/* inline functions if you are using GCC */\n\nGSL_FUN INLINE_DECL char   gsl_matrix_char_get(const gsl_matrix_char * m, const size_t i, const size_t j);\nGSL_FUN INLINE_DECL void    gsl_matrix_char_set(gsl_matrix_char * m, const size_t i, const size_t j, const char x);\nGSL_FUN INLINE_DECL char * gsl_matrix_char_ptr(gsl_matrix_char * m, const size_t i, const size_t j);\nGSL_FUN INLINE_DECL const char * gsl_matrix_char_const_ptr(const gsl_matrix_char * m, const size_t i, const size_t j);\n\n#ifdef HAVE_INLINE\nINLINE_FUN \nchar\ngsl_matrix_char_get(const gsl_matrix_char * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_VAL(\"first index out of range\", GSL_EINVAL, 0) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_VAL(\"second index out of range\", GSL_EINVAL, 0) ;\n        }\n    }\n#endif\n  return m->data[i * m->tda + j] ;\n} \n\nINLINE_FUN \nvoid\ngsl_matrix_char_set(gsl_matrix_char * m, const size_t i, const size_t j, const char x)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_VOID(\"first index out of range\", GSL_EINVAL) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_VOID(\"second index out of range\", GSL_EINVAL) ;\n        }\n    }\n#endif\n  m->data[i * m->tda + j] = x ;\n}\n\nINLINE_FUN \nchar *\ngsl_matrix_char_ptr(gsl_matrix_char * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n        }\n    }\n#endif\n  return (char *) (m->data + (i * m->tda + j)) ;\n} \n\nINLINE_FUN \nconst char *\ngsl_matrix_char_const_ptr(const gsl_matrix_char * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n        }\n    }\n#endif\n  return (const char *) (m->data + (i * m->tda + j)) ;\n} \n\n#endif\n\n__END_DECLS\n\n#endif /* __GSL_MATRIX_CHAR_H__ */\n", "meta": {"hexsha": "9a691829abc335d744efd1658b4dc00cb1e36461", "size": 13349, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gsl/gsl_matrix_char.h", "max_stars_repo_name": "zhanghe9704/jspec2", "max_stars_repo_head_hexsha": "0073e0515b87610b7f88ad2b07fc7d23618c159a", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-28T08:20:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-28T08:20:20.000Z", "max_issues_repo_path": "include/gsl/gsl_matrix_char.h", "max_issues_repo_name": "zhanghe9704/jspec2", "max_issues_repo_head_hexsha": "0073e0515b87610b7f88ad2b07fc7d23618c159a", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gsl/gsl_matrix_char.h", "max_forks_repo_name": "zhanghe9704/jspec2", "max_forks_repo_head_hexsha": "0073e0515b87610b7f88ad2b07fc7d23618c159a", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-14T12:45:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-14T12:45:35.000Z", "avg_line_length": 36.4726775956, "max_line_length": 141, "alphanum_fraction": 0.6652932804, "num_tokens": 3339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.256832002764217, "lm_q2_score": 0.028870909139682776, "lm_q1q2_score": 0.0074149734159684655}}
{"text": "/*\nFRACTAL - A program growing fractals to benchmark parallelization and drawing\nlibraries.\n\nCopyright 2009-2021, Javier Burguete Tolosa.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\n  list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice,\n  this list of conditions and the following disclaimer in the documentation\n  and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``AS IS'' AND ANY EXPRESS\nOR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\nEVENT SHALL Javier Burguete Tolosa OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\nINDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\nBUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\nADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n/**\n * \\file draw.c\n * \\brief Source file to define the drawing data and functions.\n * \\author Javier Burguete Tolosa.\n * \\copyright Copyright 2009-2021, Javier Burguete Tolosa.\n */\n#define _GNU_SOURCE\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <time.h>\n#include <gsl/gsl_rng.h>\n#include <glib.h>\n#include <png.h>\n#include <ft2build.h>\n#include FT_FREETYPE_H\n#include <gtk/gtk.h>\n#include <GL/glew.h>\n#if HAVE_FREEGLUT\n#include <GL/freeglut.h>\n#elif HAVE_SDL\n#include <SDL.h>\n#elif HAVE_GLFW\n#include <GLFW/glfw3.h>\n#endif\n\n#include \"config.h\"\n#include \"fractal.h\"\n#include \"image.h\"\n#include \"text.h\"\n#include \"graphic.h\"\n#include \"draw.h\"\n#include \"simulator.h\"\n\nGraphic graphic[1];             ///< Graphic data.\n\n/**\n * Function to resize the draw.\n */\nvoid\ndraw_resize (int w,             ///< Graphic window width.\n             int h)             ///< Graphic window height.\n{\n#if DEBUG\n  printf (\"draw_resize: start\\n\");\n  fflush (stdout);\n#endif\n  if ((unsigned int) w < width)\n    w = width;\n  if ((unsigned int) h < height)\n    h = height;\n#if HAVE_FREEGLUT\n  glutReshapeWindow (w, h);\n#endif\n  window_width = w;\n  window_height = h;\n  glViewport (0, 0, w, h);\n#if DEBUG\n  printf (\"draw_resize: end\\n\");\n  fflush (stdout);\n#endif\n}\n\n#if HAVE_GTKGLAREA\nvoid\nresize (GtkGLArea * gl_area __attribute__((unused)), int w, int h)\n{\n  draw_resize (w, h);\n}\n#endif\n\n/**\n * Function to render graphics.\n */\nvoid\ndraw ()\n{\n#if HAVE_GLFW\n  int graphic_width, graphic_height;\n#endif\n\n#if DEBUG\n  printf (\"draw: start\\n\");\n  fflush (stdout);\n#endif\n\n#if HAVE_GLFW\n  glfwGetFramebufferSize (window, &graphic_width, &graphic_height);\n  draw_resize (graphic_width, graphic_height);\n#endif\n\n  graphic_render (graphic);\n\n  // Displaying the draw\n#if HAVE_GTKGLAREA\n  gtk_widget_queue_draw (GTK_WIDGET (dialog_simulator->gl_area));\n#elif HAVE_FREEGLUT\n  glutSwapBuffers ();\n#elif HAVE_SDL\n  SDL_GL_SwapWindow (window);\n#elif HAVE_GLFW\n  glfwSwapBuffers (window);\n#endif\n\n#if DEBUG\n  printf (\"draw: end\\n\");\n  fflush (stdout);\n#endif\n}\n", "meta": {"hexsha": "9e34df5e5503891a0786ae058c697a9365783940", "size": 3422, "ext": "c", "lang": "C", "max_stars_repo_path": "3.4.15/draw.c", "max_stars_repo_name": "jburguete/fractal", "max_stars_repo_head_hexsha": "95d711dcb7b385556fb77794bc01737b21e99774", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "3.4.15/draw.c", "max_issues_repo_name": "jburguete/fractal", "max_issues_repo_head_hexsha": "95d711dcb7b385556fb77794bc01737b21e99774", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3.4.15/draw.c", "max_forks_repo_name": "jburguete/fractal", "max_forks_repo_head_hexsha": "95d711dcb7b385556fb77794bc01737b21e99774", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7971014493, "max_line_length": 79, "alphanum_fraction": 0.7314436002, "num_tokens": 846, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3276683139517237, "lm_q2_score": 0.022629202546014436, "lm_q1q2_score": 0.0074148726443246035}}
{"text": "#ifndef __CROSSBOW_BLAS_H_\n#define __CROSSBOW_BLAS_H_\n\n#include <cblas.h>\n\n#include <jni.h>\n\nvoid blas_init (int size, int bufferSize);\n\nvoid blas_free ();\n\nenum CBLAS_TRANSPOSE getCblasTrans (const char *);\n\nvoid *getObjectBufferAddress (JNIEnv *, jobject, int);\n\n#endif /* __CROSSBOW_BLAS_H_ */\n", "meta": {"hexsha": "f294f1d044d46a548328aeb545586f768858983e", "size": 297, "ext": "h", "lang": "C", "max_stars_repo_path": "clib-multigpu/BLAS.h", "max_stars_repo_name": "lsds/Crossbow", "max_stars_repo_head_hexsha": "d4441b35315f9f7d48293fe81faaf21e1ca48002", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 50.0, "max_stars_repo_stars_event_min_datetime": "2019-01-09T14:30:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T11:42:51.000Z", "max_issues_repo_path": "clib-multigpu/BLAS.h", "max_issues_repo_name": "lsds/Crossbow", "max_issues_repo_head_hexsha": "d4441b35315f9f7d48293fe81faaf21e1ca48002", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-01-18T07:31:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-14T21:16:53.000Z", "max_forks_repo_path": "clib-multigpu/BLAS.h", "max_forks_repo_name": "lsds/Crossbow", "max_forks_repo_head_hexsha": "d4441b35315f9f7d48293fe81faaf21e1ca48002", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-03-20T14:56:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T06:13:09.000Z", "avg_line_length": 17.4705882353, "max_line_length": 54, "alphanum_fraction": 0.7542087542, "num_tokens": 82, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.17328821446825263, "lm_q2_score": 0.04272219556589849, "lm_q1q2_score": 0.007403252987778049}}
{"text": "/*\n * Copyright (c) 2020 Microsoft. All rights reserved.\n */\n\n#pragma once\n\n#include <array>\n\n#include <algorithm>\n#include <gsl/span>\n\n#include \"common/common.h\"\n#include \"common/logger.h\"\n\n// A wrapper around std::array that is specialized to uint8_t and enforces\n// initialization\ntemplate <size_t TLength> class Blob : public CanBeSerialsed {\n  using CArrayType = uint8_t[TLength];\n  using CppArrayType = std::array<uint8_t, TLength>;\n\n  CppArrayType _data;\n\npublic:\n  static constexpr size_t array_size = TLength;\n  using array_type = CppArrayType;\n\n  constexpr Blob(const CArrayType &data) {\n    std::copy(std::begin(data), std::end(data), _data.begin());\n  }\n\n  constexpr Blob(const gsl::span<const uint8_t> &data) {\n    const size_t size = std::min(_data.size(), data.size());\n    std::copy_n(data.begin(), size, _data.begin());\n  }\n\n  constexpr Blob() noexcept : _data() {\n    for (auto &b : _data) {\n      b = 0;\n    }\n  }\n\n  CppArrayType &array() { return _data; }\n\n  const CppArrayType &array() const { return _data; }\n\n  MemRef span() { return MakeMemRef(&_data); }\n\n  CMemRef span() const { return MakeCMemRef(&_data); }\n\n  uint8_t *data() noexcept { return _data.data(); }\n\n  const uint8_t *data() const noexcept { return _data.data(); }\n\n  uint8_t *end() {\n    const MemRef span = gsl::make_span(data(), TLength + 1);\n    const MemRef sub = span.subspan(TLength, 1);\n    return sub.data();\n  }\n\n  size_t length() const { return TLength; }\n\n  bool operator==(const Blob<TLength> &d) const { return d.array() == array(); }\n\n  bool operator!=(const Blob<TLength> &d) const { return d.array() != array(); }\n\n  // we cannot check the whole object, but we can check the array.\n  static_assert(OkAsParam<CppArrayType, TLength>::value);\n};\n\n// A wrapper around std::array that is specialized to char and enforces\n// initialization\ntemplate <size_t TLength> class CharBlob : public CannotBeSerialsed {\n  using CArrayType = char[TLength];\n  using CppArrayType = std::array<char, TLength>;\n\nprivate:\n  CppArrayType _data;\n  size_t _length; // Danger!\n\npublic:\n  constexpr CharBlob(const gsl::span<const char> &data) {\n    const size_t size = data.size();\n\n    if (size > TLength) {\n      HW_LOG_FAIL(\"Blob not long enough\");\n      while (1)\n        ;\n    }\n\n    _data.fill(0);\n    std::copy_n(data.begin(), size, _data.begin());\n    _length = size;\n  }\n\n  constexpr CharBlob(const char *data, size_t length) {\n    if (length > TLength) {\n      HW_LOG_FAIL(\"Blob not long enough\");\n      while (1)\n        ;\n    }\n\n    const CSignedMemRef aspan = MakeCSignedMemRef(data, length);\n    _data.fill(0);\n    std::copy_n(aspan.begin(), length, _data.begin());\n    _length = length;\n  }\n\n  constexpr CharBlob() noexcept : _data() {\n    _data.fill(0);\n    _length = 0;\n  }\n\n  CppArrayType &array() { return _data; }\n\n  const CppArrayType &array() const { return _data; }\n\n  SignedMemRef span() { return MakeSignedMemRef(&_data); }\n\n  CSignedMemRef span() const { return MakeCSignedMemRef(&_data); }\n\n  char *data() { return _data.data(); }\n\n  const char *data() const { return _data.data(); }\n\n  size_t maxlength() const { return TLength; }\n\n  size_t length() const { return _length; }\n\n  bool operator==(const CharBlob<TLength> &d) {\n    if (d.length() != length()) {\n      return false;\n    }\n\n    // not using the strcmp as these buffers may not have null-terminating\n    // character\n    const size_t len = length();\n    const CSignedMemRef _dspan = MakeCSignedMemRef(data(), len);\n    const CSignedMemRef dspan = MakeCSignedMemRef(d.data(), len);\n\n    return (_dspan == dspan);\n  }\n\n  bool operator!=(const CharBlob<TLength> &d) {\n    if (d.length() != length()) {\n      return true;\n    }\n\n    // not using the strcmp as these buffers may not have null-terminating\n    // character\n    const size_t len = length();\n    const CSignedMemRef _dspan = MakeCSignedMemRef(data(), len);\n    const CSignedMemRef dspan = MakeCSignedMemRef(d.data(), len);\n\n    return (_dspan != dspan);\n  }\n};\n", "meta": {"hexsha": "73070feb5701d634d710294488eeabbffef7a826", "size": 3986, "ext": "h", "lang": "C", "max_stars_repo_path": "src/common/Blob.h", "max_stars_repo_name": "verified-HRoT/Verified-DICE-for-STM32H7", "max_stars_repo_head_hexsha": "703299f9ae5422cfd7161f80c32b5f3ad1bb6af6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/common/Blob.h", "max_issues_repo_name": "verified-HRoT/Verified-DICE-for-STM32H7", "max_issues_repo_head_hexsha": "703299f9ae5422cfd7161f80c32b5f3ad1bb6af6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/common/Blob.h", "max_forks_repo_name": "verified-HRoT/Verified-DICE-for-STM32H7", "max_forks_repo_head_hexsha": "703299f9ae5422cfd7161f80c32b5f3ad1bb6af6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3885350318, "max_line_length": 80, "alphanum_fraction": 0.6545408931, "num_tokens": 1082, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20434189993684582, "lm_q2_score": 0.03622005859587873, "lm_q1q2_score": 0.007401275589305743}}
{"text": "\n// Copyright Twitch Interactive, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: MIT\n\n#pragma once\n\n#include <gsl/span>\n#include <vector>\n\nnamespace Twitch::Utility {\nclass OutputByteStream {\npublic:\n    void reserve(size_t size)\n    {\n        _data.reserve(size);\n    }\n\n    template<typename ValueType, typename ArgType>\n    void write(const ArgType &arg)\n    {\n        size_t startSize = _data.size();\n        size_t valueSize = sizeof(ValueType);\n        ValueType value = static_cast<ValueType>(arg);\n        _data.resize(startSize + valueSize);\n        memcpy_s(_data.data() + startSize, _data.size() - startSize, &value, valueSize);\n    }\n\n    void writeBytes(gsl::span<const uint8_t> bytes)\n    {\n        size_t startSize = _data.size();\n        _data.resize(startSize + bytes.size());\n        memcpy_s(_data.data() + startSize, _data.size() - startSize, bytes.data(), bytes.size());\n    }\n\n    std::vector<uint8_t> consume()\n    {\n        return std::move(_data);\n    }\n\nprivate:\n    std::vector<uint8_t> _data;\n};\n\nclass InputByteStream {\npublic:\n    InputByteStream(gsl::span<const uint8_t> data)\n        : _data(std::move(data))\n    {\n    }\n\n    template<typename ValueType>\n    ValueType read()\n    {\n        ValueType value;\n        size_t valueSize = sizeof(ValueType);\n        memcpy_s(&value, sizeof(value), _data.data() + _currentPosition, valueSize);\n        _currentPosition += valueSize;\n        return value;\n    }\n\n    void readBytes(gsl::span<uint8_t> bytes)\n    {\n        memcpy_s(bytes.data(), bytes.size(), _data.data() + _currentPosition, bytes.size());\n        _currentPosition += bytes.size();\n    }\n\n    gsl::span<const uint8_t> readBytesView(size_t size)\n    {\n        gsl::span<const uint8_t> bytesView = _data.subspan(_currentPosition, size);\n        _currentPosition += size;\n        return bytesView;\n    }\n\n    size_t remainingSize() const\n    {\n        return _data.size() - _currentPosition;\n    }\n\nprivate:\n    gsl::span<const uint8_t> _data;\n    size_t _currentPosition = 0;\n};\n} // namespace Twitch::Utility\n", "meta": {"hexsha": "b13fd9a049b94a8422ccd78d95de5feb8b1fbdb8", "size": 2076, "ext": "h", "lang": "C", "max_stars_repo_path": "libsoundtrackutil/include/libsoundtrackutil/ByteStream.h", "max_stars_repo_name": "LaudateCorpus1/libsoundtrackutil", "max_stars_repo_head_hexsha": "a0e0e022669afbf2f4fdb3914817a67606b4c320", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-10-14T00:51:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-11T01:10:56.000Z", "max_issues_repo_path": "libsoundtrackutil/include/libsoundtrackutil/ByteStream.h", "max_issues_repo_name": "twitchtv/libsoundtrackutil", "max_issues_repo_head_hexsha": "a0e0e022669afbf2f4fdb3914817a67606b4c320", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-08-10T21:56:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-10T21:56:07.000Z", "max_forks_repo_path": "libsoundtrackutil/include/libsoundtrackutil/ByteStream.h", "max_forks_repo_name": "LaudateCorpus1/libsoundtrackutil", "max_forks_repo_head_hexsha": "a0e0e022669afbf2f4fdb3914817a67606b4c320", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-10-02T17:34:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-10T21:55:56.000Z", "avg_line_length": 24.7142857143, "max_line_length": 97, "alphanum_fraction": 0.6324662813, "num_tokens": 504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18952107301879195, "lm_q2_score": 0.039048295661732874, "lm_q1q2_score": 0.007400474893366653}}
{"text": "#ifndef MAINH\n#define MAINH\n\n#include <stdlib.h>\n#include <string.h>\n#include \"data.h\"\n#include \"lda-seq.h\"\n#include \"lda.h\"\n#include <gsl/gsl_matrix.h>\n\ntypedef struct dtm_fit_params\n{\n    char* datafile;\n    char* outname;\n    char* heldout;\n    int start;\n    int end;\n    int ntopics;\n    int lda_max_em_iter;\n    double top_obs_var;\n    double top_chain_var;\n    double alpha;\n} dtm_fit_params;\n\n#endif\n", "meta": {"hexsha": "cb843c0b343f15df0dc11dcf821ee3594c8674c5", "size": 408, "ext": "h", "lang": "C", "max_stars_repo_path": "scripts/lib/DTM/dtm/main.h", "max_stars_repo_name": "iwangjian/dtm-lab", "max_stars_repo_head_hexsha": "07c936c07d268208dcc2f19e07fb8d2a18e39ba8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2018-07-12T11:05:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-22T08:34:34.000Z", "max_issues_repo_path": "scripts/lib/DTM/dtm/main.h", "max_issues_repo_name": "iwangjian/topic-extractor", "max_issues_repo_head_hexsha": "07c936c07d268208dcc2f19e07fb8d2a18e39ba8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/lib/DTM/dtm/main.h", "max_forks_repo_name": "iwangjian/topic-extractor", "max_forks_repo_head_hexsha": "07c936c07d268208dcc2f19e07fb8d2a18e39ba8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-03-15T04:11:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-10T09:29:17.000Z", "avg_line_length": 15.6923076923, "max_line_length": 29, "alphanum_fraction": 0.6789215686, "num_tokens": 114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3208213138121609, "lm_q2_score": 0.022977367233847502, "lm_q1q2_score": 0.007371629143907453}}
{"text": "#pragma once\n\n// Standard\n#include <exception>\n#include <cassert>\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <fstream>\n#include <memory>\n#include <vector>\n#include <map>\n#include <stack>\n#include <cstdint>\n#include <iomanip>\n#include <codecvt>\n#include <algorithm>\n#include <functional>\n#include <limits>\n#include <filesystem>\n#include <tuple>\n#include <iterator>\n#include <random>\n#include <cmath>\n\n#if defined(DEBUG) || defined(_DEBUG)\n#define _CRTDBG_MAP_ALLOC\n#include <stdlib.h>\n#include <crtdbg.h>\n#endif\n\n// Guidelines Support Library\n#include <gsl\\gsl>\n\n// Windows\n#include <windows.h>\n#include <winrt\\Windows.Foundation.h>\n\n// DirectX\n#include <d3d11_3.h>\n#include <dxgi1_2.h>\n#include <DirectXMath.h>\n#include <DirectXPackedVector.h>\n#include <DirectXColors.h>\n#include <DirectXTK\\DDSTextureLoader.h>\n#include <DirectXTK\\WICTextureLoader.h>\n#include <DirectXTK\\SpriteBatch.h>\n#include <DirectXTK\\SpriteFont.h>\n#include <DirectXTK\\GamePad.h>\n#include <DirectXTK\\Keyboard.h>\n#include <DirectXTK\\Mouse.h>", "meta": {"hexsha": "5ccc7ea757f858affad947ddc1b6345e3995640e", "size": 1034, "ext": "h", "lang": "C", "max_stars_repo_path": "source/Library.Shared/pch.h", "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/Library.Shared/pch.h", "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/Library.Shared/pch.h", "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.2745098039, "max_line_length": 39, "alphanum_fraction": 0.751450677, "num_tokens": 269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31069438321455395, "lm_q2_score": 0.023689471471693545, "lm_q1q2_score": 0.007360185727576598}}
{"text": "#ifndef H_GPM_STRIPPED_DOWN\n#define H_GPM_STRIPPED_DOWN\n\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_histogram.h>\n#include \"../csm_all.h\"\n\nvoid ght_find_theta_range(LDP laser_ref, LDP laser_sens,\n                const double*x0, double max_linear_correction,\n        double max_angular_correction_deg, int interval, gsl_histogram*hist, int*num_correspondences);\n\nvoid ght_one_shot(LDP laser_ref, LDP laser_sens,\n                const double*x0, double max_linear_correction,\n                double max_angular_correction_deg, int interval, double*x, int*num_correspondences) ;\n\n#endif\n\n", "meta": {"hexsha": "b8d6a29aab707e786e813c8e02b6bf36fcdb9415", "size": 588, "ext": "h", "lang": "C", "max_stars_repo_path": "src/csm/sm/csm/gpm/gpm.h", "max_stars_repo_name": "alecone/ROS_project", "max_stars_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/csm/sm/csm/gpm/gpm.h", "max_issues_repo_name": "alecone/ROS_project", "max_issues_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/csm/sm/csm/gpm/gpm.h", "max_forks_repo_name": "alecone/ROS_project", "max_forks_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6666666667, "max_line_length": 102, "alphanum_fraction": 0.7465986395, "num_tokens": 143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.2658804730998169, "lm_q2_score": 0.02758528372571652, "lm_q1q2_score": 0.007334388287586187}}
{"text": "/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*\n**                                                                                  **\n** This file forms part of the Underworld geophysics modelling application.         **\n**                                                                                  **\n** For full license and copyright information, please refer to the LICENSE.md file  **\n** located at the project root, or contact the authors.                             **\n**                                                                                  **\n**~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/\n\n#include <mpi.h>\n#include <StGermain/libStGermain/src/StGermain.h>\n#include <StgDomain/libStgDomain/src/StgDomain.h>\n#include \"StgFEM/Discretisation/src/types.h\"\n\n#include \"ElementType.h\"\n#include \"ElementType_Register.h\"\n#include \"Element.h\"\n#include \"FeMesh.h\"\n#include \"FeEquationNumber.h\"\n#include \"FeVariable.h\"\n#include \"LinkedDofInfo.h\"\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <assert.h>\n#include <mpi.h>\n#include <petsc.h>\n#include <petscvec.h>\n\n\n// Private prototype\nint GenerateEquationNumbering(\n\t\tint NX, int NY, int NZ,\n\t\tint nlocal, int g_node_id[],\n\t\tint dof, int nglobal,\n\t\tPetscTruth periodic_x, PetscTruth periodic_y, PetscTruth periodic_z,\n\t\tint npx, int npy, int npz,\n\t\tint periodic_x_gnode_id[], int periodic_y_gnode_id[], int periodic_z_gnode_id[],\n\t\tint eqnums[], int *neqnums );\n\n\nint stgCmpInt( const void *l, const void *r ) {\n   return *(int*)l - *(int*)r;\n}\n\n/*###### Typedefs and Structs ######*/\n\n/** Textual name of this class */\nconst Type FeEquationNumber_Type = \"FeEquationNumber\";\n\n/** struct to store sub-totals: what is the equation number up to at a given\n    node? These can then be exchanged between processors */\ntypedef struct CritPointInfo {\n      Node_GlobalIndex\tindex;\n      Dof_EquationNumber\teqNum;\n} CritPointInfo;\n\n\n/** An element of linked list of critical point info. Several of the functions\n    use this to keep track of key points */\ntypedef struct AddListEntry {\n      CritPointInfo*\t\tcritPointInfo;\n      struct AddListEntry*\tnext;\n} AddListEntry;\n\n/** Enum to say whetehr values at crit. nodes should be printed */\ntypedef enum PrintValuesFlag {\n   DONT_PRINT_VALUES,\n   PRINT_VALUES\n} PrintValuesFlag;\n\n/** MPI datatype handle for efficiently exchanging CritPointInfo structures.\n\tsee FeEquationNumber_Create_CritPointInfo_MPI_Datatype() for where this\n\thandle is defined. */\nMPI_Datatype MPI_critPointInfoType;\n\n/*###### Private Function Declarations ######*/\n\n\n/*###### Function Definitions ######*/\n\n/** Public constructor */\n\nFeEquationNumber* FeEquationNumber_New(\n\tName\t\t\t\t\t\tname,\n\tDomainContext*\t\t\tcontext,\n\tvoid*\t\t\t\t\t\tmesh,\n\tDofLayout*\t\t\t\tdofLayout,\n\tVariableCondition*\tbcs,\n\tLinkedDofInfo*\t\t\tlinkedDofInfo )\n{\n   FeEquationNumber* self = FeEquationNumber_DefaultNew( name );\n\n\tself->isConstructed = True;\n\t_FeEquationNumber_Init( self, context, mesh, dofLayout, bcs, linkedDofInfo );\n\n\treturn self;\n}\n\nvoid* FeEquationNumber_DefaultNew( Name name ) {\n\t/* Variables set in this function */\n\tSizeT                                              _sizeOfSelf = sizeof(FeEquationNumber);\n\tType                                                      type = FeEquationNumber_Type;\n\tStg_Class_DeleteFunction*                              _delete = _FeEquationNumber_Delete;\n\tStg_Class_PrintFunction*                                _print = _FeEquationNumber_Print;\n\tStg_Class_CopyFunction*                                  _copy = _FeEquationNumber_Copy;\n\tStg_Component_DefaultConstructorFunction*  _defaultConstructor = (Stg_Component_DefaultConstructorFunction*)FeEquationNumber_DefaultNew;\n\tStg_Component_ConstructFunction*                    _construct = _FeEquationNumber_AssignFromXML;\n\tStg_Component_BuildFunction*                            _build = _FeEquationNumber_Build;\n\tStg_Component_InitialiseFunction*                  _initialise = _FeEquationNumber_Initialise;\n\tStg_Component_ExecuteFunction*                        _execute = _FeEquationNumber_Execute;\n\tStg_Component_DestroyFunction*                        _destroy = _FeEquationNumber_Destroy;\n\tAllocationType                              nameAllocationType = NON_GLOBAL;\n\n   return _FeEquationNumber_New(  FEEQUATIONNUMBER_PASSARGS  );\n}\n/** Constructor implementation. */\nFeEquationNumber* _FeEquationNumber_New(  FEEQUATIONNUMBER_DEFARGS  ){\n   FeEquationNumber* self;\n\n   /* Allocate memory */\n   assert( _sizeOfSelf >= sizeof(FeEquationNumber) );\n   self = (FeEquationNumber*)_Stg_Component_New(  STG_COMPONENT_PASSARGS  );\n\n   /* General info */\n\n   /* Virtual info */\n   self->_build = _build;\n   self->_initialise = _initialise;\n\n   /* Mesh info */\n\n   return self;\n}\n\n\n/** Constructor variables initialisation. Doesn't allocate any\n    memory, just saves arguments and sets counters to 0. */\nvoid _FeEquationNumber_Init(\n   FeEquationNumber*\t\tself,\n\tDomainContext*\t\t\tcontext,\n   void*\t\t\t\t\t\tfeMesh,\n   DofLayout*\t\t\t\tdofLayout,\n   VariableCondition*\tbcs,\n   LinkedDofInfo*\t\t\tlinkedDofInfo )\n{\n   /* General and Virtual info should already be set */\n\n   /* FinteElementMesh info */\n\tself->context = context;\n   self->feMesh = (FeMesh*)feMesh;\n   self->globalSumUnconstrainedDofs = 0;\n   self->isBuilt = False;\n   self->locationMatrixBuilt = False;\n   self->_lowestLocalEqNum = -1;\n   self->_lowestGlobalEqNums = NULL;\n   self->_highestLocalEqNum = -1;\n   self->dofLayout = dofLayout;\n   self->bcs = bcs;\n   self->linkedDofInfo = linkedDofInfo;\n   self->remappingActivated = False;\n   /* register streams */\n   self->debug = Stream_RegisterChild( StgFEM_Discretisation_Debug, FeEquationNumber_Type );\n   self->debugLM = Stream_RegisterChild( self->debug, \"LM\" );\n   self->warning = Stream_RegisterChild( StgFEM_Warning, FeEquationNumber_Type );\n   self->removeBCs = True;\n   self->bcEqNums = STree_New();\n   STree_SetIntCallbacks( self->bcEqNums );\n   STree_SetItemSize( self->bcEqNums, sizeof(int) );\n   self->ownedMap = STreeMap_New();\n   STreeMap_SetItemSize( self->ownedMap, sizeof(int), sizeof(int) );\n   STree_SetIntCallbacks( self->ownedMap );\n\n   Stream_SetPrintingRank( self->debug, 0 );\n}\n\nvoid _FeEquationNumber_AssignFromXML( void* feEquationNumber, Stg_ComponentFactory *cf, void* data ) {\n}\n\nvoid _FeEquationNumber_Execute( void* feEquationNumber, void *data ){\n\n}\n\nvoid _FeEquationNumber_Destroy( void* feEquationNumber, void *data ){\n   FeEquationNumber* self = (FeEquationNumber*) feEquationNumber;\n   Index ii;\n\n   /* free destination array memory */\n   Journal_DPrintfL( self->debug, 2, \"Freeing I.D. Array\\n\" );\n   FreeArray( self->mapNodeDof2Eq );\n\n   if (self->locationMatrix) {\n      Journal_DPrintfL( self->debug, 2, \"Freeing Full L.M. Array\\n\" );\n      for( ii = 0; ii < self->nDomainEls; ii++ )\n         FreeArray( self->locationMatrix[ii] );\n\n      FreeArray( self->locationMatrix );\n   }\n\n   if( self->bcEqNums )\n      Stg_Class_Delete( self->bcEqNums );\n\n   if( self->ownedMap )\n      Stg_Class_Delete( self->ownedMap );\n}\n\n/* Copy */\n\n/** Stg_Class_Delete implementation. */\nvoid _FeEquationNumber_Delete( void* feEquationNumber ) {\n   FeEquationNumber* self = (FeEquationNumber*) feEquationNumber;\n\n   // This calls the Destroy() function\n   _Stg_Component_Delete( self );\n}\n\n\n/** Print implementation */\nvoid _FeEquationNumber_Print( void* mesh, Stream* stream ) {\n   FeEquationNumber* self = (FeEquationNumber*)mesh;\n\n   /* General info */\n   Journal_Printf( stream, \"FeEquationNumber (ptr): %p\\n\", self );\n\n   /* Print parent */\n   _Stg_Class_Print( self, stream );\n\n   /* Virtual info */\n   Journal_Printf( stream,  \"\\t_build (func ptr): %p\\n\", self->_build );\n   Journal_Printf( stream,  \"\\t_intialise (func ptr): %p\\n\", self->_initialise );\n\n   /* FeEquationNumber info */\n   /* Don't print dofs or bcs as these will be printed by FeVariable */\n\n   if ( self->mapNodeDof2Eq ) {\n      FeEquationNumber_PrintmapNodeDof2Eq( self, stream );\n      FeEquationNumber_PrintLocationMatrix( self, stream );\n   }\n   else {\n      Journal_Printf( stream, \"\\tmapNodeDof2Eq: (null)... not built yet\\n\" );\n      Journal_Printf( stream, \"\\tlocationMatrix: (null)... not built yet\\n\" );\n   }\n}\n\n\nvoid* _FeEquationNumber_Copy( void* feEquationNumber, void* dest, Bool deep, Name nameExt, PtrMap* ptrMap ) {\n\n   abort();\n}\n\nvoid _FeEquationNumber_Build( void* feEquationNumber, void* data ) {\n   FeEquationNumber* self = (FeEquationNumber*) feEquationNumber;\n\n   assert(self);\n\n   Journal_DPrintf( self->debug, \"In %s:\\n\",  __func__ );\n   Stream_IndentBranch( StgFEM_Debug );\n\n   Stg_Component_Build( self->feMesh   , data, False );\n   Stg_Component_Build( self->dofLayout, data, False );\n   if ( self->linkedDofInfo ) Stg_Component_Build( self->dofLayout, data, False );\n   if ( self->bcs )           Stg_Component_Build( self->bcs      , data, False );\n\t/* If we have new mesh topology information, do this differently. */\n   /* if( self->feMesh->topo->domains && self->feMesh->topo->domains[MT_VERTEX] ) { */\n\n   if( Mesh_HasExtension( self->feMesh, \"vertexGrid\" ) )\n      FeEquationNumber_BuildWithDave( self );\n   else\n      FeEquationNumber_BuildWithTopology( self );\n\n   /* If not removing BCs, construct a table of which equation numbers are actually BCs. */\n   if( !self->removeBCs ) {\n      FeMesh* mesh = self->feMesh;\n      DofLayout* dofLayout = self->dofLayout;\n      VariableCondition* bcs = self->bcs;\n      int nDofs, varInd;\n      int ii, jj;\n\n      for( ii = 0; ii < FeMesh_GetNodeLocalSize( mesh ); ii++ ) {\n         nDofs = dofLayout->dofCounts[ii];\n         for( jj = 0; jj < nDofs; jj++ ) {\n            varInd = dofLayout->varIndices[ii][jj];\n            if( bcs && VariableCondition_IsCondition( bcs, ii, varInd ) ) {\n               if( !STree_Has( self->bcEqNums, self->mapNodeDof2Eq[ii] + jj ) )\n                  STree_Insert( self->bcEqNums, self->mapNodeDof2Eq[ii] + jj );\n            }\n         }\n      }\n   }\n\n   if ( Stream_IsPrintableLevel( self->debug, 3 ) ) {\n      FeEquationNumber_PrintmapNodeDof2Eq( self, self->debug );\n   }\n\n   Stream_UnIndentBranch( StgFEM_Debug );\n}\n\n/** Initialise implementation. Currently does nothing. */\nvoid _FeEquationNumber_Initialise( void* feEquationNumber, void* data ) {\n   FeEquationNumber* self = (FeEquationNumber*) feEquationNumber;\n\n   Stg_Component_Initialise( self->feMesh   , data, False );\n   Stg_Component_Initialise( self->dofLayout, data, False );\n   if ( self->linkedDofInfo ) Stg_Component_Initialise( self->dofLayout, data, False );\n   if ( self->bcs )           Stg_Component_Initialise( self->bcs      , data, False );\n}\n\n\nIndex FeEquationNumber_CalculateActiveEqCountAtNode(\n   void*\t\t\tfeEquationNumber,\n   Node_DomainIndex\tdNode_I,\n   Dof_EquationNumber*\tlowestActiveEqNumAtNodePtr )\n{\n   FeEquationNumber*\tself = (FeEquationNumber*) feEquationNumber;\n   Dof_Index\t\tnodalDof_I = 0;\n   Index\t\t\tactiveEqsAtCurrRowNode = 0;\n   Dof_EquationNumber\tcurrEqNum;\n   Bool\t\t\tfoundLowest = False;\n\n   for ( nodalDof_I = 0; nodalDof_I < self->dofLayout->dofCounts[dNode_I]; nodalDof_I++ ) {\n      currEqNum = self->mapNodeDof2Eq[dNode_I][nodalDof_I];\n      if ( currEqNum != -1 ) {\n         activeEqsAtCurrRowNode++;\n         if ( False == foundLowest ) {\n            (*lowestActiveEqNumAtNodePtr) = currEqNum;\n            foundLowest = True;\n         }\n      }\n   }\n\n   return activeEqsAtCurrRowNode;\n}\n\n\nvoid FeEquationNumber_BuildLocationMatrix( void* feEquationNumber ) {\n   FeEquationNumber*\tself = (FeEquationNumber*)feEquationNumber;\n   FeMesh*\t\t\tfeMesh;\n   unsigned\t\tnDomainEls;\n   unsigned*\t\tnNodalDofs;\n   unsigned\t\tnElNodes;\n   int*       elNodes;\n   int**\t\t\tdstArray;\n   int***\t\t\tlocMat;\n   IArray*\t\t\tinc;\n   unsigned\t\te_i, n_i, dof_i;\n\n   assert( self );\n\n   /* Don't build if already done. */\n   if( self->locationMatrixBuilt ) {\n      Journal_DPrintf( self->debugLM, \"In %s: LM already built, so just returning.\\n\",  __func__ );\n      Stream_UnIndentBranch( StgFEM_Debug );\n      return;\n   }\n\n   inc = IArray_New();\n\n   /* Shortcuts. */\n   feMesh = self->feMesh;\n   nDomainEls = FeMesh_GetElementDomainSize( feMesh );\n   nNodalDofs = self->dofLayout->dofCounts;\n   dstArray = self->mapNodeDof2Eq;\n\n   /* Allocate for the location matrix. */\n   locMat = AllocArray( int**, nDomainEls );\n   for( e_i = 0; e_i < nDomainEls; e_i++ ) {\n      FeMesh_GetElementNodes( feMesh, e_i, inc );\n      nElNodes = IArray_GetSize( inc );\n      elNodes = IArray_GetPtr( inc );\n      locMat[e_i] = AllocArray( int*, nElNodes );\n      for( n_i = 0; n_i < nElNodes; n_i++ )\n         locMat[e_i][n_i] = AllocArray( int, nNodalDofs[elNodes[n_i]] );\n   }\n\n   /* Build location matrix. */\n   for( e_i = 0; e_i < nDomainEls; e_i++ ) {\n      FeMesh_GetElementNodes( feMesh, e_i, inc );\n      nElNodes = IArray_GetSize( inc );\n      elNodes = IArray_GetPtr( inc );\n      for( n_i = 0; n_i < nElNodes; n_i++ ) {\n         for( dof_i = 0; dof_i < nNodalDofs[elNodes[n_i]]; dof_i++ )\n            locMat[e_i][n_i][dof_i] = dstArray[elNodes[n_i]][dof_i];\n      }\n   }\n\n   Stg_Class_Delete( inc );\n\n   /* Store result. */\n   self->locationMatrix = locMat;\n}\n\nFeEquationNumber* _FeEquationNumber_Create( void* _self, Bool removeBCs ) {\n  /* Build a n equation number for a given feVariable */\n  FeVariable* feVar = Stg_CheckType( (FeVariable*)_self, FeVariable) ;\n  FeEquationNumber* eqNum=NULL;\n  Stg_Component_Build( feVar, NULL, False );\n  Stg_Component_Initialise( feVar, NULL, False );\n  eqNum = FeEquationNumber_New( \"\",\n                                  feVar->context,\n                                  feVar->feMesh,\n                                  feVar->dofLayout,\n                                  feVar->bcs,\n                                  NULL );\n\n  eqNum->removeBCs = removeBCs;\n  memcpy( eqNum->periodic, feVar->periodic, 3*sizeof(Bool) );\n  Stg_Component_Build( eqNum, NULL, False );\n  Stg_Component_Initialise( eqNum, NULL, False );\n  // feVar->eqNum = self->eqNum; // We do it for now\n  return eqNum;\n}\n\nvoid FeEquationNumber_PrintmapNodeDof2Eq( void* feFeEquationNumber, Stream* stream ) {\n   FeEquationNumber* self = (FeEquationNumber*) feFeEquationNumber;\n   FeMesh*\t\tfeMesh = self->feMesh;\n   MPI_Comm comm = Comm_GetMPIComm( Mesh_GetCommTopology( feMesh, MT_VERTEX ) );\n   unsigned rank;\n   Node_GlobalIndex gNode_I;\n   Node_GlobalIndex nodeGlobalCount = FeMesh_GetNodeGlobalSize( feMesh );\n\n   MPI_Comm_rank( comm, (int*)&rank );\n   Journal_Printf( stream, \"%d: *** Printing destination array ***\\n\", rank );\n\n   for (gNode_I =0; gNode_I < nodeGlobalCount; gNode_I++) {\n      Node_DomainIndex dNode_I;\n\n      if ( !Mesh_GlobalToDomain( feMesh, MT_VERTEX, gNode_I, &dNode_I ) ) {\n         Journal_Printf( stream, \"\\tmapNodeDof2Eq[(gnode)%2d]: on another proc\\n\", gNode_I);\n      }\n      else {\n         Dof_Index currNodeNumDofs = self->dofLayout->dofCounts[ dNode_I ];\n         Dof_Index nodeLocalDof_I;\n\n         Journal_Printf( stream, \"\\tmapNodeDof2Eq[(gnode)%2d][(dof)0-%d]:\",gNode_I, currNodeNumDofs );\n         for( nodeLocalDof_I = 0; nodeLocalDof_I < currNodeNumDofs; nodeLocalDof_I++ ) {\n            Journal_Printf( stream, \"%3d, \", self->mapNodeDof2Eq[dNode_I][nodeLocalDof_I] );\n         }\n         Journal_Printf( stream, \"\\n\" );\n      }\n   }\n}\n\nvoid FeEquationNumber_PrintmapNodeDof2EqBox( void* feFeEquationNumber, Stream* stream ) {\n\tFeEquationNumber*   self = (FeEquationNumber*) feFeEquationNumber;\n\tFeMesh*             feMesh = self->feMesh;\n\tMPI_Comm            comm = Comm_GetMPIComm( Mesh_GetCommTopology( feMesh, MT_VERTEX ) );\n\tunsigned            rank;\n\tGrid*               vGrid;\n\tint                 ijk[3];\n\tElement_LocalIndex  lNode_I;\n\tNode_GlobalIndex    gNode_I;\n\tNode_Index          sizeI, sizeJ, sizeK;\n\tDof_Index           nDofs;\n\tDof_Index           dof_I;\n\n\tMPI_Comm_rank( comm, (int*)&rank );\n\tJournal_Printf( stream, \"%d: *** Printing destination array ***\\n\", rank );\n\n\tvGrid = *Mesh_GetExtension( feMesh, Grid**,  feMesh->vertGridId );\n\tnDofs = self->dofLayout->dofCounts[0];\n\tsizeI = vGrid->sizes[ I_AXIS ];\n\tsizeJ = vGrid->sizes[ J_AXIS ];\n\tsizeK = vGrid->sizes[ K_AXIS ] ? vGrid->sizes[ K_AXIS ] : 1;\n\n\tfor ( ijk[2] = 0 ; ijk[2] < sizeK ; ijk[2]++ ) {\n\t\tif ( sizeK != 1 )\n\t\t\tJournal_Printf( stream, \"\\nk = %d\\n\", ijk[2] );\n\t\tfor ( ijk[1] = sizeJ - 1 ; ijk[1] >= 0 ; ijk[1]-- ) {\n\t\t\tJournal_Printf( stream, \"%2d - \", ijk[1] );\n\t\t\tfor ( ijk[0] = 0 ; ijk[0] < sizeI ; ijk[0]++ ) {\n\t\t\t\tgNode_I = Grid_Project( vGrid, ijk );\n\t\t\t\tJournal_Printf( stream, \"{ \" );\n\t\t\t\tif ( Mesh_GlobalToDomain( feMesh, MT_VERTEX, gNode_I, &lNode_I ) ) {\n\t\t\t\t\tfor ( dof_I = 0 ; dof_I < nDofs ; dof_I++ )\n\t\t\t\t\t\tJournal_Printf( stream, \"%3d \", self->mapNodeDof2Eq[lNode_I][dof_I] );\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tfor ( dof_I = 0 ; dof_I < nDofs ; dof_I++ )\n\t\t\t\t\t\tJournal_Printf( stream, \" XX \" );\n\t\t\t\t}\n\t\t\t\tJournal_Printf( stream, \"}\" );\n\t\t\t}\n\t\t\tJournal_Printf( stream, \"\\n\" );\n\t\t}\n\t\t/* Bottom row */\n\t\tJournal_Printf( stream, \"    \" );\n\t\tfor ( ijk[0] = 0 ; ijk[0] < sizeI ; ijk[0]++ ) {\n\t\t\tJournal_Printf( stream, \"    %3d    \", ijk[0] );\n\t\t\tif ( nDofs == 3 )\n\t\t\t\tJournal_Printf( stream, \"    \" );\n\t\t}\n\t\tJournal_Printf( stream, \"\\n\" );\n\t}\n}\n\nvoid FeEquationNumber_PrintLocationMatrix( void* feFeEquationNumber, Stream* stream ) {\n   FeEquationNumber* self = (FeEquationNumber*) feFeEquationNumber;\n   FeMesh*\t\tfeMesh = self->feMesh;\n   MPI_Comm comm = Comm_GetMPIComm( Mesh_GetCommTopology( feMesh, MT_VERTEX ) );\n   unsigned rank;\n   Element_GlobalIndex gEl_I;\n   unsigned nDims = Mesh_GetDimSize( feMesh );\n   Element_GlobalIndex elementGlobalCount = FeMesh_GetElementGlobalSize( feMesh );\n   unsigned nLocalEls = FeMesh_GetElementLocalSize( feMesh );\n\n   Journal_Printf( stream, \"%d: *** Printing location matrix ***\\n\", rank  );\n\n   MPI_Comm_rank( comm, (int*)&rank );\n\n   for (gEl_I =0; gEl_I < elementGlobalCount; gEl_I++ ) {\n      Element_LocalIndex lEl_I;\n\n      if ( !Mesh_GlobalToDomain( feMesh, nDims, gEl_I, &lEl_I ) || lEl_I >= nLocalEls ) {\n         Journal_Printf( stream, \"\\tLM[(g/l el)%2d/XXX]: on another proc\\n\", gEl_I);\n      }\n      else {\n         Node_LocalIndex numNodesAtElement;\n         Node_LocalIndex elLocalNode_I;\n         unsigned*\tincNodes;\n         IArray*\t\tinc;\n\n         inc = IArray_New();\n         FeMesh_GetElementNodes( self->feMesh, lEl_I, inc );\n         numNodesAtElement = IArray_GetSize( inc );\n         incNodes = IArray_GetPtr( inc );\n\n         Journal_Printf( stream, \"\\tLM[(g/l el)%2d/%2d][(enodes)0-%d]\", gEl_I, lEl_I, numNodesAtElement);\n         /* print the nodes and dofs */\n         for ( elLocalNode_I = 0; elLocalNode_I < numNodesAtElement; elLocalNode_I++ ) {\n            /* look up processor local node number. */\n            Element_LocalIndex currNode = incNodes[elLocalNode_I == 2 ? 3 :\n                                                   elLocalNode_I == 3 ? 2 :\n                                                   elLocalNode_I == 6 ? 7 :\n                                                   elLocalNode_I == 7 ? 6 :\n                                                   elLocalNode_I];\n            /* get the number of dofs at current node */\n            Dof_Index currNodeNumDofs = self->dofLayout->dofCounts[ currNode ];\n            Dof_Index nodeLocalDof_I;\n\n            Journal_Printf( stream, \"({%2d}\", currNode );\n            for( nodeLocalDof_I = 0; nodeLocalDof_I < currNodeNumDofs; nodeLocalDof_I++ ) {\n               Journal_Printf( stream, \"%3d,\", self->mapNodeDof2Eq[currNode][nodeLocalDof_I] );\n            }\n            Journal_Printf( stream, \"), \" );\n         }\n\n         Journal_Printf( stream, \"\\n\" );\n\n         Stg_Class_Delete( inc );\n      }\n\n   }\n}\n\nPartition_Index FeEquationNumber_CalculateOwningProcessorOfEqNum( void* feEquationNumber, Dof_EquationNumber eqNum ) {\n   FeEquationNumber* self = (FeEquationNumber*)feEquationNumber;\n   /* Partition_Index ownerProc = (unsigned int)-1; */\n   Comm*\tcomm = Mesh_GetCommTopology( self->feMesh, MT_VERTEX );\n   MPI_Comm\tmpiComm = Comm_GetMPIComm( comm );\n   unsigned\tnProcs;\n   unsigned\tp_i;\n\n   MPI_Comm_size( mpiComm, (int*)&nProcs );\n   for( p_i = 1; p_i < nProcs; p_i++ ) {\n      if( eqNum < self->_lowestGlobalEqNums[p_i] )\n         break;\n   }\n\n   return p_i - 1;\n\n}\n\nvoid FeEquationNumber_BuildWithTopology( FeEquationNumber* self ) {\n   Stream*\t\tstream;\n   double\t\tstartTime, endTime, time, tmin, tmax;\n   FeMesh*\t\tfeMesh;\n   Sync*\t\tsync;\n   Comm*\t\tcomm;\n   MPI_Comm\t\tmpiComm;\n   unsigned\t\trank, nProcs;\n   unsigned\t\tnDims;\n   unsigned\t\tnDomainNodes;\n   unsigned\t\tnLocalNodes;\n   unsigned*\t\tnNodalDofs;\n   unsigned\t\tnElNodes, *elNodes;\n   int**\t\tdstArray;\n   int\t\t\t*nLocMatDofs, ***locMat;\n   unsigned\t\tvarInd;\n   unsigned\t\tcurEqNum;\n   unsigned\t\tbase;\n   unsigned\t\tsubTotal;\n   MPI_Status\t\tstatus;\n   unsigned\t\tmaxDofs;\n   unsigned*\t\ttuples;\n   LinkedDofInfo*\tlinks;\n   unsigned\t\thighest;\n   IArray*\t\tinc;\n   unsigned             e_i, n_i, dof_i, s_i;\n   int\t\t\tii;\n\n   assert( self );\n\n   inc = IArray_New();\n\n//   stream = Journal_Register( Info_Type, (Name)self->type  );\n//   Stream_SetPrintingRank( stream, 0 );\n//\n//   Journal_RPrintf( stream, \"FeEquationNumber: '%s'\\n\", self->name );\n//   Stream_Indent( stream );\n//   Journal_RPrintf( stream, \"Generating equation numbers...\\n\" );\n//   Stream_Indent( stream );\n//   if( self->removeBCs )\n//      Journal_RPrintf( stream, \"BCs set to be removed.\\n\" );\n//   else\n//      Journal_RPrintf( stream, \"BCs will not be removed.\\n\" );\n\n   startTime = MPI_Wtime();\n\n   /* Shortcuts. */\n   feMesh = self->feMesh;\n   comm = Mesh_GetCommTopology( feMesh, MT_VERTEX );\n   mpiComm = Comm_GetMPIComm( comm );\n   MPI_Comm_size( mpiComm, (int*)&nProcs );\n   MPI_Comm_rank( mpiComm, (int*)&rank );\n   nDims = Mesh_GetDimSize( feMesh );\n   nDomainNodes = FeMesh_GetNodeDomainSize( feMesh );\n   self->nDomainEls = FeMesh_GetElementDomainSize( feMesh );\n   nLocalNodes = FeMesh_GetNodeLocalSize( feMesh );\n   nNodalDofs = self->dofLayout->dofCounts;\n   links = self->linkedDofInfo;\n\n   /* Allocate for destination array. */\n   dstArray = Memory_Alloc_2DComplex( int, nDomainNodes, nNodalDofs,\n                                      \"FeEquationNumber::mapNodeDof2Eq\" );\n\n   /* If needed, allocate for linked equation numbers. */\n   if( links ) {\n      unsigned\ts_i;\n\n      links->eqNumsOfLinkedDofs = ReallocArray( links->eqNumsOfLinkedDofs, int, links->linkedDofSetsCount );\n      for( s_i = 0; s_i < links->linkedDofSetsCount; s_i++ )\n         links->eqNumsOfLinkedDofs[s_i] = -1;\n   }\n\n   /* Allocate for the location matrix. */\n   nLocMatDofs = NULL;\n   locMat = AllocArray( int**, self->nDomainEls );\n   for( e_i = 0; e_i < self->nDomainEls; e_i++ ) {\n      FeMesh_GetElementNodes( feMesh, e_i, inc );\n      nElNodes = IArray_GetSize( inc );\n      elNodes = IArray_GetPtr( inc );\n      nLocMatDofs = ReallocArray( nLocMatDofs, int, nElNodes );\n      for( n_i = 0; n_i < nElNodes; n_i++ )\n         nLocMatDofs[n_i] = nNodalDofs[elNodes[n_i]];\n      locMat[e_i] = AllocComplex2D( int, nElNodes, nLocMatDofs );\n   }\n   FreeArray( nLocMatDofs );\n\n   /* Build initial destination array and store max dofs. */\n   curEqNum = 0;\n   maxDofs = 0;\n   for( n_i = 0; n_i < nLocalNodes; n_i++ ) {\n      if( nNodalDofs[n_i] > maxDofs )\n         maxDofs = nNodalDofs[n_i];\n\n      for( dof_i = 0; dof_i < nNodalDofs[n_i]; dof_i++ ) {\n         varInd = self->dofLayout->varIndices[n_i][dof_i];\n         if( !self->bcs || !VariableCondition_IsCondition( self->bcs, n_i, varInd ) ||\n             !self->removeBCs )\n         {\n            if( links && links->linkedDofTbl[n_i][dof_i] != -1 ) {\n               if( rank > 0 ) {\n                  dstArray[n_i][dof_i] = -2;\n                  continue;\n               }\n               if( links->eqNumsOfLinkedDofs[links->linkedDofTbl[n_i][dof_i]] == -1 )\n                  links->eqNumsOfLinkedDofs[links->linkedDofTbl[n_i][dof_i]] = curEqNum++;\n               dstArray[n_i][dof_i] = links->eqNumsOfLinkedDofs[links->linkedDofTbl[n_i][dof_i]];\n            }\n            else\n               dstArray[n_i][dof_i] = curEqNum++;\n         }\n         else\n            dstArray[n_i][dof_i] = -1;\n      }\n   }\n\n   /* Order the equation numbers based on processor rank; cascade counts forward. */\n   base = 0;\n   if( rank > 0 )\n      (void)MPI_Recv( &base, 1, MPI_UNSIGNED, rank - 1, 6669, mpiComm, &status );\n   subTotal = base + curEqNum;\n   if( rank < nProcs - 1 )\n      (void)MPI_Send( &subTotal, 1, MPI_UNSIGNED, rank + 1, 6669, mpiComm );\n\n   if( links ) {\n      /* Reduce to find lowest linked DOFs. */\n      for( s_i = 0; s_i < links->linkedDofSetsCount; s_i++ ) {\n         if( links->eqNumsOfLinkedDofs[s_i] != -1 )\n            links->eqNumsOfLinkedDofs[s_i] += base;\n/*\n  MPI_Allreduce( links->eqNumsOfLinkedDofs + s_i, &lowest, 1, MPI_UNSIGNED, MPI_MAX, mpiComm );\n*/\n         MPI_Allreduce( links->eqNumsOfLinkedDofs + s_i, &highest, 1, MPI_INT, MPI_MAX, mpiComm );\n/*\n  assert( (lowest == (unsigned)-1) ? lowest == highest : 1 );\n*/\n         links->eqNumsOfLinkedDofs[s_i] = highest;\n      }\n   }\n\n   /* Modify existing destination array and dump to a tuple array. */\n   tuples = AllocArray( unsigned, nDomainNodes * maxDofs );\n   for( n_i = 0; n_i < nLocalNodes; n_i++ ) {\n      for( dof_i = 0; dof_i < nNodalDofs[n_i]; dof_i++ ) {\n         varInd = self->dofLayout->varIndices[n_i][dof_i];\n         if( !self->bcs || !VariableCondition_IsCondition( self->bcs, n_i, varInd ) ||\n             !self->removeBCs )\n         {\n            if( links && links->linkedDofTbl[n_i][dof_i] != -1 ) {\n               highest = links->eqNumsOfLinkedDofs[links->linkedDofTbl[n_i][dof_i]];\n               dstArray[n_i][dof_i] = highest;\n            }\n            else\n               dstArray[n_i][dof_i] += base;\n         }\n         tuples[n_i * maxDofs + dof_i] = dstArray[n_i][dof_i];\n      }\n   }\n\n   /* Update all other procs. */\n   sync = Mesh_GetSync( feMesh, MT_VERTEX );\n   Sync_SyncArray( sync, tuples, maxDofs * sizeof(unsigned),\n                   tuples + nLocalNodes * maxDofs, maxDofs * sizeof(unsigned),\n                   maxDofs * sizeof(unsigned) );\n\n   /* Update destination array's domain indices. */\n   for( n_i = nLocalNodes; n_i < nDomainNodes; n_i++ ) {\n      for( dof_i = 0; dof_i < nNodalDofs[n_i]; dof_i++ ) {\n         varInd = self->dofLayout->varIndices[n_i][dof_i];\n         if( !self->bcs || !VariableCondition_IsCondition( self->bcs, n_i, varInd ) ||\n             !self->removeBCs )\n         {\n            dstArray[n_i][dof_i] = tuples[n_i * maxDofs + dof_i];\n         }\n         else\n            dstArray[n_i][dof_i] = -1;\n      }\n   }\n\n   /* Destroy tuple array. */\n   FreeArray( tuples );\n\n   /* Build location matrix. */\n   for( e_i = 0; e_i < self->nDomainEls; e_i++ ) {\n      FeMesh_GetElementNodes( feMesh, e_i, inc );\n      nElNodes = IArray_GetSize( inc );\n      elNodes = IArray_GetPtr( inc );\n      for( n_i = 0; n_i < nElNodes; n_i++ ) {\n         for( dof_i = 0; dof_i < nNodalDofs[elNodes[n_i]]; dof_i++ )\n            locMat[e_i][n_i][dof_i] = dstArray[elNodes[n_i]][dof_i];\n      }\n   }\n\n   /* Store stuff on class. */\n   self->mapNodeDof2Eq = dstArray;\n   self->locationMatrix = locMat;\n   self->locationMatrixBuilt = True;\n   self->remappingActivated = False;\n   self->localEqNumsOwnedCount = curEqNum;\n   self->firstOwnedEqNum = base;\n   self->lastOwnedEqNum = subTotal - 1;\n   self->_lowestLocalEqNum = self->firstOwnedEqNum;\n\n   /* Setup owned mapping. */\n   STree_Clear( self->ownedMap );\n   for( ii = self->firstOwnedEqNum; ii <= self->lastOwnedEqNum; ii++ ) {\n      int val = ii - self->firstOwnedEqNum;\n      STreeMap_Insert( self->ownedMap, &ii, &val );\n   }\n\n   /* Bcast global sum from highest rank. */\n   if( rank == nProcs - 1 )\n      self->globalSumUnconstrainedDofs = self->lastOwnedEqNum + 1;\n   (void)MPI_Bcast( &self->globalSumUnconstrainedDofs, 1, MPI_UNSIGNED, nProcs - 1, mpiComm );\n\n   /* Construct lowest global equation number list. */\n   self->_lowestGlobalEqNums = AllocArray( int, nProcs );\n   (void)MPI_Allgather( &self->firstOwnedEqNum, 1, MPI_UNSIGNED, self->_lowestGlobalEqNums, 1, MPI_UNSIGNED, mpiComm );\n\n//   endTime = MPI_Wtime();\n\n//   Journal_RPrintf( stream, \"Assigned %d global equation numbers.\\n\", self->globalSumUnconstrainedDofs );\n//   Journal_Printf( stream, \"[%u] Assigned %d local equation numbers, within range %d to %d.\\n\",\n//                   rank, self->lastOwnedEqNum - self->firstOwnedEqNum + 1, self->firstOwnedEqNum, self->lastOwnedEqNum + 1 );\n//   Stream_UnIndent( stream );\n\n//   time = endTime - startTime;\n//   (void)MPI_Reduce( &time, &tmin, 1, MPI_DOUBLE, MPI_MIN, 0, mpiComm );\n//   (void)MPI_Reduce( &time, &tmax, 1, MPI_DOUBLE, MPI_MAX, 0, mpiComm );\n//   Journal_RPrintf( stream, \"... Completed in %g [min] / %g [max] seconds.\\n\", tmin, tmax );\n//   Stream_UnIndent( stream );\n\n   Stg_Class_Delete( inc );\n}\n\nvoid FeEquationNumber_BuildWithDave( FeEquationNumber* self ) {\n   int nLocals, *locals;\n   Grid *vGrid;\n   int varInd;\n   int nEqNums, **dstArray;\n   IArray *inc;\n   int nDofs;\n   int *periodic;\n   int ***locMat;\n   int nDims;\n   int *elNodes;\n   Comm *comm;\n   MPI_Comm mpiComm;\n   int nRanks, rank;\n   Sync *sync;\n   Bool isCond;\n   int nPeriodicInds[3];\n   int *periodicInds[3];\n   int inds[3];\n   Bool usePeriodic;\n   int *tmpArray, nLocalEqNums;\n   int lastOwnedEqNum, ind;\n   STree *doneSet;\n   int ii, jj, kk;\n\n   comm = Mesh_GetCommTopology( self->feMesh, 0 );\n   mpiComm = Comm_GetMPIComm( comm );\n   MPI_Comm_size( mpiComm, &nRanks );\n   MPI_Comm_rank( mpiComm, &rank );\n\n   /* Setup an array containing global indices of all locally owned nodes. */\n   nLocals = Mesh_GetLocalSize( self->feMesh, 0 );\n   locals = AllocArray( int, nLocals );\n   for( ii = 0; ii < nLocals; ii++ )\n      locals[ii] = Mesh_DomainToGlobal( self->feMesh, 0, ii );\n\n   /* Allocate for destination array. */\n   nDofs = self->dofLayout->dofCounts[0];\n   dstArray = AllocArray2D( int, Mesh_GetDomainSize( self->feMesh, 0 ), nDofs );\n\n   /* Get the vertex grid extension and any periodicity. */\n   nDims = Mesh_GetDimSize( self->feMesh );\n   vGrid = *Mesh_GetExtension( self->feMesh, Grid**,  self->feMesh->vertGridId );\n   periodic = Mesh_GetExtension( self->feMesh, int*, self->feMesh->periodicId );\n\n   /* Fill destination array with initial values, setting dirichlet BCs as we go. */\n   for( ii = 0; ii < nLocals; ii++ )\n   {\n/*\n      Grid_Lift( vGrid, locals[ii], inds );\n      usePeriodic = False;\n      for( jj = 0; jj < nDims; jj++ )\n      {\n         if( (periodic[jj] || self->periodic[jj]) && (inds[jj] == 0 || inds[jj] == vGrid->sizes[jj] - 1) )\n         {\n            usePeriodic = True;\n            break;\n         }\n      }\n*/\n      for( jj = 0; jj < nDofs; jj++ )\n      {\n         varInd = self->dofLayout->varIndices[ii][jj];\n         if( self->bcs )\n            isCond = VariableCondition_IsCondition( self->bcs, ii, varInd );\n         else\n            isCond = False;\n\n         if( isCond && self->removeBCs )\n            dstArray[ii][jj] = -1;\n         else\n            dstArray[ii][jj] = 0;\n      }\n   }\n\n   /* Generate opposing indices for periodicity. */\n   for( ii = 0; ii < nDims; ii++ )\n   {\n      nPeriodicInds[ii] = 0;\n      periodicInds[ii] = NULL;\n      if( periodic[ii] || self->periodic[ii] )\n      {\n         periodicInds[ii] = AllocArray( int, nLocals );\n         for( jj = 0; jj < nLocals; jj++ )\n         {\n            Grid_Lift( vGrid, locals[jj], inds );\n            if( inds[ii] != vGrid->sizes[ii] - 1 )\n               continue;\n            /*\n            for( kk = 0; kk < nDofs; kk++ )\n               if( dstArray[jj][kk] == -1 )\n                  break;\n               if( kk < nDofs )\n                  continue;\n            */\n            periodicInds[ii][nPeriodicInds[ii]++] = locals[jj];\n         }\n      }\n   }\n\n   /* Call Dave's equation number generation routine. */\n   if( nDims == 2 ) {\n      GenerateEquationNumbering( vGrid->sizes[0], vGrid->sizes[1], 1,\n\t\t\t\t nLocals, locals,\n\t\t\t\t nDofs, Mesh_GetGlobalSize( self->feMesh, 0 ),\n\t\t\t\t periodic[0] || self->periodic[0], periodic[1] || self->periodic[1], False,\n\t\t\t\t nPeriodicInds[0], nPeriodicInds[1], 0,\n\t\t\t\t periodicInds[0], periodicInds[1], NULL,\n\t\t\t\t dstArray[0], &nEqNums );\n   }\n   else if( nDims == 3 ) {\n      GenerateEquationNumbering( vGrid->sizes[0], vGrid->sizes[1], vGrid->sizes[2],\n\t\t\t\t nLocals, locals,\n\t\t\t\t nDofs, Mesh_GetGlobalSize( self->feMesh, 0 ),\n\t\t\t\t periodic[0] || self->periodic[0], periodic[1] || self->periodic[1], periodic[2] || self->periodic[2],\n\t\t\t\t nPeriodicInds[0], nPeriodicInds[1], nPeriodicInds[2],\n\t\t\t\t periodicInds[0], periodicInds[1], periodicInds[2],\n\t\t\t\t dstArray[0], &nEqNums );\n   }\n   else if( nDims == 1 ) {\n      GenerateEquationNumbering( vGrid->sizes[0], 1, 1,\n\t\t\t\t nLocals, locals,\n\t\t\t\t nDofs, Mesh_GetGlobalSize( self->feMesh, 0 ),\n\t\t\t\t periodic[0], False, False,\n\t\t\t\t nPeriodicInds[0], 0, 0,\n\t\t\t\t periodicInds[0], NULL, NULL,\n\t\t\t\t dstArray[0], &nEqNums );\n   }\n   else\n      abort();\n\n   /* Free periodic arrays. */\n   for( ii = 0; ii < nDims; ii++ )\n   {\n      if( periodicInds[ii] )\n         FreeArray( periodicInds[ii] );\n   }\n\n   /* Setup owned mapping part 1. */\n   STree_Clear( self->ownedMap );\n   for( ii = 0; ii < nLocals; ii++ )\n   {\n      Grid_Lift( vGrid, locals[ii], inds );\n      for( jj = 0; jj < nDims; jj++ )\n      {\n         if( (periodic[jj] || self->periodic[jj]) && inds[jj] == vGrid->sizes[jj] - 1 )\n         {\n            inds[jj] = 0;\n            ind = Grid_Project( vGrid, inds );\n            if( !FeMesh_NodeGlobalToDomain( self->feMesh, ind, &ind ) )\n               break;\n         }\n      }\n      if( jj < nDims )\n         continue;\n      for( jj = 0; jj < nDofs; jj++ )\n      {\n         if( dstArray[ii][jj] == -1 || STreeMap_HasKey( self->ownedMap, dstArray[ii] + jj ) )\n            continue;\n         STreeMap_Insert( self->ownedMap, dstArray[ii] + jj, &ii );\n      }\n   }\n\n   /* Setup owned mapping. */\n   tmpArray = AllocArray( int, nLocals * nDofs );\n   memcpy( tmpArray, dstArray[0], nLocals * nDofs * sizeof(int) );\n   qsort( tmpArray, nLocals * nDofs, sizeof(int), stgCmpInt );\n   doneSet = STree_New();\n   STree_SetItemSize( doneSet, sizeof(int) );\n   STree_SetIntCallbacks( doneSet );\n   for( nLocalEqNums = 0, ii = 0; ii < nLocals * nDofs; ii++ )\n   {\n      if( tmpArray[ii] != -1 && STreeMap_HasKey( self->ownedMap, tmpArray + ii ) && !STree_Has( doneSet, tmpArray + ii ) )\n      {\n         if( !nLocalEqNums )\n            self->_lowestLocalEqNum = tmpArray[ii];\n         *(int*)STreeMap_Map( self->ownedMap, tmpArray + ii ) = nLocalEqNums;\n         STree_Insert( doneSet, tmpArray + ii );\n         nLocalEqNums++;\n      }\n   }\n   lastOwnedEqNum = -1; /* Don't need this anymore. */\n   FreeArray( tmpArray );\n   Stg_Class_Delete( doneSet );\n\n   /* Transfer remote equation numbers. */\n   sync = Mesh_GetSync( self->feMesh, 0 );\n   Sync_SyncArray( sync, dstArray[0], nDofs * sizeof(int),\n                   dstArray[0] + nLocals * nDofs, nDofs * sizeof(int),\n                   nDofs * sizeof(int) );\n\n   /* Allocate for location matrix. */\n   /* first store nDomainEls for usage during destroy */\n   self->nDomainEls = Mesh_GetDomainSize( self->feMesh, nDims );\n   locMat = AllocArray( int**, self->nDomainEls );\n   for( ii = 0; ii < self->nDomainEls; ii++ )\n      locMat[ii] = AllocArray2D( int, FeMesh_GetElementNodeSize( self->feMesh, 0 ), nDofs );\n\n   /* Fill in location matrix. */\n   inc = IArray_New();\n   for( ii = 0; ii < Mesh_GetDomainSize( self->feMesh, nDims ); ii++ )\n   {\n      FeMesh_GetElementNodes( self->feMesh, ii, inc );\n      elNodes = IArray_GetPtr( inc );\n      for( jj = 0; jj < FeMesh_GetElementNodeSize( self->feMesh, 0 ); jj++ )\n      {\n         for( kk = 0; kk < nDofs; kk++ )\n         locMat[ii][jj][kk] = dstArray[elNodes[jj]][kk];\n      }\n   }\n   Stg_Class_Delete( inc );\n\n   /* Fill in our other weird values. */\n   self->mapNodeDof2Eq = dstArray;\n   self->locationMatrix = locMat;\n   self->locationMatrixBuilt = True;\n   self->remappingActivated = False;\n   self->localEqNumsOwnedCount = nLocalEqNums;\n\n   /* Bcast global sum from highest rank. */\n   self->globalSumUnconstrainedDofs = nEqNums;\n\n   /* Construct lowest global equation number list. */\n   self->_lowestGlobalEqNums = AllocArray( int, nRanks );\n   (void)MPI_Allgather( &self->_lowestLocalEqNum, 1, MPI_UNSIGNED,\n                        self->_lowestGlobalEqNums, 1, MPI_UNSIGNED,\n                        mpiComm );\n\n   FreeArray( locals );\n\n   /*\n   printf( \"%d: localEqNumsOwned = %d\\n\", rank, self->localEqNumsOwnedCount );\n   printf( \"%d: globalSumUnconstrainedDofs = %d\\n\", rank, self->globalSumUnconstrainedDofs );\n   */\n}\n\n\n\n\n/*\n\nInput:\n  nlocal - number of locally ownded nodes\n  g_node_id - global indices of nodes owned locally. Size nlocal\n  dof - degrees of freedom per node\n  nglobal - number of global nodes\n  npx - number of consider to be periodic in x (local to this proc)\n  npy - number of consider to be periodic in y (local to this proc)\n  periodic_x_gnode_id - global indices of nodes (on this proc) which are on right hand side boundary\n  periodic_y_gnode_id - global indices of nodes (on this proc) whipch are on top boundary\n  eqnums - contains any dirichlet boundary conditions. Size nlocal*dof\n\nOutput;\n  eqnums - contains full list of eqnums\n\nAssumptions:\n- Ordering eqnums[] = { (node_0,[dof_0,dof_1,..,dof_x]), (node_1,[dof_0,dof_1,..,dof_x]), ... }\n- Any dirichlet set along a boundary deemed to be periodic will be clobbered.\n- Processors may have duplicate nodes in the g_node_id[] list.\n- A number in the corner is considered part of both boundaries (horiz and vert)\n- If npx is not 0, then periodicity is assumed in x\n- If npy is not 0, then periodicity is assumed in y\n- Dofs constrained to be dirichlet must be marked with a negative number.\n- Dofs are NOT split across processors.\n- We can define a logical i,j,k ordering to uniquely identify nodes.\n\n*/\n\nPetscErrorCode _VecScatterBeginEnd( VecScatter vscat, Vec FROM, Vec TO, InsertMode addv,ScatterMode mode )\n{\n#if( (PETSC_VERSION_MAJOR==2) && (PETSC_VERSION_MINOR==3) && (PETSC_VERSION_SUBMINOR==2) )\n\t// 2.3.2 ordering of args\n\tVecScatterBegin( FROM, TO, addv, mode, vscat );\n\tVecScatterEnd( FROM, TO, addv, mode, vscat );\n#else\n\t// 2.3.3 or 3.0.0\n\tVecScatterBegin( vscat, FROM, TO, addv, mode );\n\tVecScatterEnd( vscat, FROM, TO, addv, mode );\n#endif\n\n\tPetscFunctionReturn(0);\n}\n\nint GenerateEquationNumbering(\n\t\tint NX, int NY, int NZ,\n\t\tint nlocal, int g_node_id[],\n\t\tint dof, int nglobal,\n\t\tPetscTruth periodic_x, PetscTruth periodic_y, PetscTruth periodic_z,\n\t\tint npx, int npy, int npz,\n\t\tint periodic_x_gnode_id[], int periodic_y_gnode_id[], int periodic_z_gnode_id[],\n\t\tint eqnums[], int *neqnums )\n{\n\tPetscErrorCode ierr;\n\tPetscInt periodic_mask;\n\tVec global_eqnum, g_ownership;\n\tPetscInt i;\n\tPetscMPIInt rank;        /* processor rank */\n\tPetscMPIInt size;        /* size of communicator */\n\tVec local_ownership, local_eqnum;\n\tPetscInt *_g_node_id;\n\tIS is_gnode, is_eqnum;\n\tVecScatter vscat_ownership, vscat_eqnum;\n\tPetscScalar *_local_ownership, *_local_eqnum;\n\tPetscInt local_eqnum_count,global_eqnum_count;\n\tPetscScalar val[10];\n\tPetscInt d,idx[10];\n\tPetscInt *to_fetch,cnt,number_to_fetch;\n\tPetscInt eq_cnt;\n\tVec offset_list;\n\tVecScatter vscat_offset;\n\tVec seq_offset_list;\n\tPetscInt offset, inc;\n\n\tPetscInt spanx,spany,spanz,total;\n\tPetscInt loc;\n\tPetscReal max;\n\tPetscInt n_inserts;\n\n\n\tierr = MPI_Comm_rank(PETSC_COMM_WORLD,&rank);CHKERRQ(ierr);\n\tierr = MPI_Comm_size(PETSC_COMM_WORLD,&size);CHKERRQ(ierr);\n\n\tif( dof>=10 ) {\n\t\tStg_SETERRQ(PETSC_ERR_SUP, \"Max allowable degrees of freedom per node = 10. Change static size\" );\n\t}\n\n\n\t/*\n\tClaim locally owned nodes. Duplicate nodes on the interior will be resolved by the processor\n\twhich inserts last.\n\t*/\n\tVecCreate( PETSC_COMM_WORLD, &g_ownership );\n\tVecSetSizes( g_ownership, PETSC_DECIDE, nglobal );\n\tVecSetFromOptions( g_ownership );\n\n\tfor( i=0; i<nlocal; i++ ) {\n\t\tVecSetValue( g_ownership, g_node_id[i], rank, INSERT_VALUES );\n\t}\n\tVecAssemblyBegin(g_ownership);\n\tVecAssemblyEnd(g_ownership);\n\n\n\t/* Mask out the periodic boundaries. */\n\tperiodic_mask = -6699.0;\n\tif (periodic_x_gnode_id!=NULL) {\n\t\tfor( i=0; i<npx; i++ ) {\n\t\t\tVecSetValue( g_ownership, periodic_x_gnode_id[i], periodic_mask, INSERT_VALUES );\n\t\t}\n\t}\n\tif (periodic_y_gnode_id!=NULL) {\n\t\tfor( i=0; i<npy; i++ ) {\n\t\t\tVecSetValue( g_ownership, periodic_y_gnode_id[i], periodic_mask, INSERT_VALUES );\n\t\t}\n\t}\n\tif (periodic_z_gnode_id!=NULL) {\n\t\tfor( i=0; i<npz; i++ ) {\n\t\t\tVecSetValue( g_ownership, periodic_z_gnode_id[i], periodic_mask, INSERT_VALUES );\n\t\t}\n\t}\n\tVecAssemblyBegin(g_ownership);\n\tVecAssemblyEnd(g_ownership);\n\n\t/*\n\tPetscPrintf(PETSC_COMM_WORLD, \"g_ownership \\n\");\n\tVecView( g_ownership, PETSC_VIEWER_STDOUT_WORLD );\n\t*/\n\n\t/* Get all locally owned nodes */\n\tVecCreate( PETSC_COMM_SELF, &local_ownership );\n\tVecSetSizes( local_ownership, PETSC_DECIDE, nlocal );\n\tVecSetFromOptions( local_ownership );\n\n\tPetscMalloc( sizeof(PetscInt)*nlocal, &_g_node_id);\n\tfor( i=0; i<nlocal; i++ ) {\n\t\t_g_node_id[i] = g_node_id[i];\n\t}\n\tISCreateGeneralWithArray( PETSC_COMM_WORLD, nlocal, _g_node_id, &is_gnode );\n\tVecScatterCreate( g_ownership, is_gnode, local_ownership, PETSC_NULL, &vscat_ownership );\n\n\n\t/* assign unique equation numbers */\n\tVecSet( local_ownership, -6699 );\n\t_VecScatterBeginEnd( vscat_ownership, g_ownership, local_ownership, INSERT_VALUES, SCATTER_FORWARD );\n\n\n\t/* Count instances of rank in the local_ownership vector */\n\tVecGetArray( local_ownership, &_local_ownership );\n\tlocal_eqnum_count = 0;\n\tfor( i=0; i<nlocal; i++ ) {\n\t\tif( ((PetscInt)_local_ownership[i]) == rank ) {\n\t\t\tlocal_eqnum_count++;\n\t\t}\n\t}\n\n\t(void)MPI_Allreduce( &local_eqnum_count, &global_eqnum_count, 1, MPI_INT, MPI_SUM, PETSC_COMM_WORLD );\n\t/* PetscPrintf( PETSC_COMM_SELF,\n\t    \"[%d] number of local,global equations (without dofs) %d,%d \\n\", rank, local_eqnum_count, global_eqnum_count ); */\n\t/* check */\n\tspanx = NX;\n\tspany = NY;\n\tspanz = NZ;\n\tif( periodic_x==PETSC_TRUE ) {\n\t\tspanx--;\n\t}\n\tif( periodic_y==PETSC_TRUE ) {\n\t\tspany--;\n\t}\n\tif( periodic_z==PETSC_TRUE ) {\n\t\tspanz--;\n\t}\n\ttotal = spanx*spany*spanz;\n\tif( total!=global_eqnum_count ) {\n\t\tStg_SETERRQ(PETSC_ERR_SUP, \"Something stinks. Computed global size for nodes does not match expected\" );\n\t}\n\n\n\n\tVecCreate( PETSC_COMM_WORLD, &global_eqnum );\n\tVecSetSizes( global_eqnum, PETSC_DECIDE, nglobal*dof );\n\tVecSetFromOptions( global_eqnum );\n\tVecSet( global_eqnum, 0.0 );\n\n\t/* Load existing eqnums in */\n\tfor( i=0; i<nlocal; i++ ) {\n\t\tn_inserts = 0;\n\t\tfor( d=0; d<dof; d++ ) {\n/*\n\t\t\tidx[d] = -(g_node_id[i]*dof + d);\n\t\t\tval[d] = 0.0;\n*/\n\t\t\tif( eqnums[ i*dof + d ] < 0.0 ) {\n\t\t\t\tidx[n_inserts] = g_node_id[i]*dof + d;\n\t\t\t\tval[n_inserts] = eqnums[ i*dof + d ];\n\t\t\t\tn_inserts++;\n\t\t\t}\n\t\t}\n\t\t/* only insert dirichlet bc's */\n\t\tVecSetValues( global_eqnum, n_inserts, idx, val, INSERT_VALUES );\n\t}\n\tVecAssemblyBegin(global_eqnum);\n\tVecAssemblyEnd(global_eqnum);\n\n\n\n\n\n\t/* Generate list of eqnums to get */\n\tPetscMalloc( sizeof(PetscInt)*nlocal*dof, &to_fetch );\n\tcnt = 0;\n\tfor( i=0; i<nlocal; i++ ) {\n\t\tif( _local_ownership[i]==rank ) {\n\t\t\tfor( d=0; d<dof; d++ ) {\n\t\t\t\tto_fetch[cnt] = g_node_id[i]*dof + d;\n\t\t\t\tcnt++;\n\t\t\t}\n\t\t}\n\t}\n\tnumber_to_fetch = cnt;\n\n\n\tVecCreate( PETSC_COMM_SELF, &local_eqnum );\n\tVecSetSizes( local_eqnum, PETSC_DECIDE, number_to_fetch);\n\tVecSetFromOptions( local_eqnum );\n\n\tISCreateGeneralWithArray( PETSC_COMM_SELF, number_to_fetch, to_fetch, &is_eqnum );\n\tVecScatterCreate( global_eqnum, is_eqnum, local_eqnum, PETSC_NULL, &vscat_eqnum );\n\n\tVecSet( local_eqnum, -6699 );\n\t_VecScatterBeginEnd( vscat_eqnum, global_eqnum, local_eqnum, INSERT_VALUES, SCATTER_FORWARD );\n\n\n\t/* compute offset */\n\t/* count how many entries there are */\n\tVecGetArray( local_eqnum, &_local_eqnum );\n\teq_cnt = 0;\n\tfor( i=0; i<number_to_fetch; i++ ) {\n\t\tif( (PetscInt)_local_eqnum[i]==0 ) {\n\t\t\teq_cnt++;\n\t\t}\n\t}\n\tVecRestoreArray( local_eqnum, &_local_eqnum );\n\n    VecCreate( PETSC_COMM_WORLD, &offset_list );\n    VecSetSizes( offset_list, PETSC_DECIDE, size );\n    VecSetFromOptions( offset_list );\n    VecSetValue( offset_list, rank, eq_cnt, INSERT_VALUES );\n    VecAssemblyBegin(offset_list);\n    VecAssemblyEnd(offset_list);\n    /*\n    PetscPrintf(PETSC_COMM_WORLD, \"offset_list \\n\");\n    VecView( offset_list, PETSC_VIEWER_STDOUT_WORLD );\n    */\n\n    VecScatterCreateToAll(offset_list,&vscat_offset,&seq_offset_list);\n    _VecScatterBeginEnd( vscat_offset, offset_list, seq_offset_list, INSERT_VALUES, SCATTER_FORWARD );\n\n    {\n        PetscScalar *_seq_offset_list;\n\n        VecGetArray( seq_offset_list, &_seq_offset_list );\n        offset = 0;\n        for (i=0; i<rank; i++) {\n            offset+=_seq_offset_list[ i ];\n        }\n        VecRestoreArray( seq_offset_list, &_seq_offset_list );\n    }\n    Stg_VecScatterDestroy(&vscat_offset);\n    Stg_VecDestroy(&offset_list);\n    Stg_VecDestroy(&seq_offset_list);\n\n//    PetscPrintf( PETSC_COMM_SELF, \"[%d]: offset = %d \\n\", rank, offset ); \n\n\tVecGetArray( local_eqnum, &_local_eqnum );\n\tinc = 0;\n\tfor( i=0; i<number_to_fetch; i++ ) {\n\t\tif( (PetscInt)_local_eqnum[i]==0 ) {\n\t\t\t_local_eqnum[i] = offset+inc;\n\t\t\tinc++;\n\t\t}\n\t}\n\tVecRestoreArray( local_eqnum, &_local_eqnum );\n\n\t_VecScatterBeginEnd( vscat_eqnum, local_eqnum, global_eqnum, INSERT_VALUES, SCATTER_REVERSE );\n\t/*\n\tPetscPrintf(PETSC_COMM_WORLD, \"global_eqnum \\n\");\n\tVecView( global_eqnum, PETSC_VIEWER_STDOUT_WORLD );\n\t*/\n\n\t/* For each periodic boundary, get the mapped nodes */\n\n\tif( periodic_x==PETSC_TRUE ) {\n\t\tVecScatter vscat_p;\n\t\tIS is_from;\n\t\tPetscInt *from, *to;\n\t\tVec mapped;\n\t\tPetscScalar *_mapped;\n\t\tPetscInt c;\n\n\t\tPetscMalloc( sizeof(PetscInt)*npx*dof, &from );\n\t\tPetscMalloc( sizeof(PetscInt)*npx*dof, &to );\n\n\t\tc = 0;\n\t\tfor( i=0; i<npx; i++ ) {\n\t\t\tPetscInt I,J,K,gid,from_gid;\n\n\t\t\tgid = periodic_x_gnode_id[i];\n\t\t\tK = gid/(NX*NY);\n\t\t\tJ = (gid - K*(NX*NY))/NX;\n\t\t\tI = gid - K*(NX*NY) - J*NX;\n\t\t\tfrom_gid = (I-(NX-1)) + J*NX + K*(NX*NY);\n\n\t\t\tfor( d=0; d<dof; d++ ) {\n\t\t\t\tto[c] = gid * dof + d;\n\t\t\t\tfrom[c] = from_gid * dof + d;\n\t\t\t\tc++;\n\t\t\t}\n\t\t}\n\n\n\t\tVecCreate( PETSC_COMM_SELF, &mapped );\n\t\tVecSetSizes( mapped, PETSC_DECIDE, npx*dof );\n\t\tVecSetFromOptions( mapped );\n\n\t\tISCreateGeneralWithArray( PETSC_COMM_SELF, npx*dof, from, &is_from );\n\t\tVecScatterCreate( global_eqnum, is_from, mapped, PETSC_NULL, &vscat_p );\n\n\t\t_VecScatterBeginEnd( vscat_p, global_eqnum, mapped, INSERT_VALUES, SCATTER_FORWARD );\n\t\tif( npx>0 ) {\n\t\t\tVecGetArray( mapped, &_mapped );\n\t\t\tVecSetValues( global_eqnum, npx*dof, to, _mapped,  INSERT_VALUES );\n\t\t\tVecRestoreArray( mapped, &_mapped );\n\t\t}\n\n\t\tVecAssemblyBegin(global_eqnum);\n\t\tVecAssemblyEnd(global_eqnum);\n\n\t\tStg_VecScatterDestroy(&vscat_p );\n\t\tStg_ISDestroy(&is_from );\n\t\tStg_VecDestroy(&mapped );\n\t\tPetscFree( from );\n\t\tPetscFree( to );\n\t}\n\n\n\tif( periodic_y==PETSC_TRUE ) {\n\t\tVecScatter vscat_p;\n\t\tIS is_from;\n\t\tPetscInt *from, *to;\n\t\tVec mapped;\n\t\tPetscScalar *_mapped;\n\t\tPetscInt c;\n\n\t\tPetscMalloc( sizeof(PetscInt)*npy*dof, &from );\n\t\tPetscMalloc( sizeof(PetscInt)*npy*dof, &to );\n\n\t\tc = 0;\n\t\tfor( i=0; i<npy; i++ ) {\n\t\t\tPetscInt I,J,K,gid,from_gid;\n\n\t\t\tgid = periodic_y_gnode_id[i];\n\t\t\tK = gid/(NX*NY);\n\t\t\tJ = (gid - K*(NX*NY))/NX;\n\t\t\tI = gid - K*(NX*NY) - J*NX;\n\t\t\tfrom_gid = I + (J - (NY - 1))*NX + K*(NX*NY);\n\n\t\t\tfor( d=0; d<dof; d++ ) {\n\t\t\t\tto[c] = gid * dof + d;\n\t\t\t\tfrom[c] = from_gid * dof + d;\n\t\t\t\tc++;\n\t\t\t}\n\t\t}\n\n\n\t\tVecCreate( PETSC_COMM_SELF, &mapped );\n\t\tVecSetSizes( mapped, PETSC_DECIDE, npy*dof );\n\t\tVecSetFromOptions( mapped );\n\n\t\tISCreateGeneralWithArray( PETSC_COMM_SELF, npy*dof, from, &is_from );\n\t\tVecScatterCreate( global_eqnum, is_from, mapped, PETSC_NULL, &vscat_p );\n\n\t\t_VecScatterBeginEnd( vscat_p, global_eqnum, mapped, INSERT_VALUES, SCATTER_FORWARD );\n\t\tif( npy>0 ) {\n\t\t\tVecGetArray( mapped, &_mapped );\n\t\t\tVecSetValues( global_eqnum, npy*dof, to, _mapped,  INSERT_VALUES );\n\t\t\tVecRestoreArray( mapped, &_mapped );\n\t\t}\n\n\t\tVecAssemblyBegin(global_eqnum);\n\t\tVecAssemblyEnd(global_eqnum);\n\n\t\tStg_VecScatterDestroy(&vscat_p );\n\t\tStg_ISDestroy(&is_from );\n\t\tStg_VecDestroy(&mapped );\n\t\tPetscFree( from );\n\t\tPetscFree( to );\n\t}\n\n\tif( periodic_z==PETSC_TRUE ) {\n\t\tVecScatter vscat_p;\n\t\tIS is_from;\n\t\tPetscInt *from, *to;\n\t\tVec mapped;\n\t\tPetscScalar *_mapped;\n\t\tPetscInt c;\n\n\t\tPetscMalloc( sizeof(PetscInt)*npz*dof, &from );\n\t\tPetscMalloc( sizeof(PetscInt)*npz*dof, &to );\n\n\t\tc = 0;\n\t\tfor( i=0; i<npz; i++ ) {\n\t\t\tPetscInt I,J,K,gid,from_gid;\n\n\t\t\tgid = periodic_z_gnode_id[i];\n\t\t\tK = gid/(NX*NY);\n\t\t\tJ = (gid - K*(NX*NY))/NX;\n\t\t\tI = gid - K*(NX*NY) - J*NX;\n\t\t\tfrom_gid = I + J*NX + (K - (NZ-1))*(NX*NY);\n\n\t\t\tfor( d=0; d<dof; d++ ) {\n\t\t\t\tto[c] = gid * dof + d;\n\t\t\t\tfrom[c] = from_gid * dof + d;\n\t\t\t\tc++;\n\t\t\t}\n\t\t}\n\n\n\t\tVecCreate( PETSC_COMM_SELF, &mapped );\n\t\tVecSetSizes( mapped, PETSC_DECIDE, npz*dof );\n\t\tVecSetFromOptions( mapped );\n\n\t\tISCreateGeneralWithArray( PETSC_COMM_SELF, npz*dof, from, &is_from );\n\t\tVecScatterCreate( global_eqnum, is_from, mapped, PETSC_NULL, &vscat_p );\n\n\t\t_VecScatterBeginEnd( vscat_p, global_eqnum, mapped, INSERT_VALUES, SCATTER_FORWARD );\n\t\tif( npz>0 ) {\n\t\t\tVecGetArray( mapped, &_mapped );\n\t\t\tVecSetValues( global_eqnum, npz*dof, to, _mapped,  INSERT_VALUES );\n\t\t\tVecRestoreArray( mapped, &_mapped );\n\t\t}\n\n\t\tVecAssemblyBegin(global_eqnum);\n\t\tVecAssemblyEnd(global_eqnum);\n\n\t\tStg_VecScatterDestroy(&vscat_p );\n\t\tStg_ISDestroy(&is_from );\n\t\tStg_VecDestroy(&mapped );\n\t\tPetscFree( from );\n\t\tPetscFree( to );\n\t}\n\n\n\t/*\n\tPetscPrintf(PETSC_COMM_WORLD, \"global_eqnum following periodic \\n\");\n\tVecView( global_eqnum, PETSC_VIEWER_STDOUT_WORLD );\n\t*/\n\n\n\t/* Finally, scatter stuff from global_eqnums into MY array */\n\t{\n\t\tIS is_all_my_eqnums;\n\t\tPetscInt *all_my_eqnum_index;\n\t\tPetscInt _I,_D,CNT;\n\t\tVec all_my_eqnums;\n\t\tPetscScalar *_all_my_eqnums;\n\t\tVecScatter vscat_p;\n\n\t\tPetscMalloc( sizeof(PetscInt)*dof*nlocal, &all_my_eqnum_index );\n\n\t\tCNT = 0;\n\t\tfor( _I=0; _I<nlocal; _I++ ) {\n\t\t\tfor( _D=0; _D<dof; _D++ ) {\n\t\t\t\tall_my_eqnum_index[CNT] = g_node_id[_I]*dof + _D;\n\t\t\t\tCNT++;\n\t\t\t}\n\t\t}\n\n\t\tISCreateGeneralWithArray( PETSC_COMM_SELF, nlocal*dof, all_my_eqnum_index, &is_all_my_eqnums );\n\t\tVecCreate( PETSC_COMM_SELF, &all_my_eqnums );\n\t\tVecSetSizes( all_my_eqnums, PETSC_DECIDE, nlocal*dof );\n\t\tVecSetFromOptions( all_my_eqnums );\n\t\tVecScatterCreate( global_eqnum, is_all_my_eqnums, all_my_eqnums, PETSC_NULL, &vscat_p );\n\t\t_VecScatterBeginEnd( vscat_p, global_eqnum, all_my_eqnums, INSERT_VALUES, SCATTER_FORWARD );\n\t\tVecGetArray( all_my_eqnums, &_all_my_eqnums );\n\n\t\tfor( i=0; i<nlocal*dof; i++ ) {\n\t\t\teqnums[i] = (int)_all_my_eqnums[i];\n\t\t}\n\t\tVecRestoreArray( all_my_eqnums, &_all_my_eqnums );\n\n\t\tStg_VecScatterDestroy(&vscat_p );\n\t\tStg_VecDestroy(&all_my_eqnums );\n\t\tStg_ISDestroy(&is_all_my_eqnums );\n\t\tPetscFree( all_my_eqnum_index );\n\t}\n\n\tVecMax( global_eqnum, &loc, &max );\n\t*neqnums = (int)max;\n\t(*neqnums)++;\n\n\t/* tidy up */\n\tVecRestoreArray( local_ownership, &_local_ownership );\n\n\n\tStg_VecDestroy(&g_ownership );\n\tStg_VecDestroy(&local_ownership );\n\tPetscFree( _g_node_id );\n\tStg_ISDestroy(&is_gnode );\n\tStg_VecScatterDestroy(&vscat_ownership );\n\n\tStg_VecDestroy(&global_eqnum );\n\tStg_VecDestroy(&local_eqnum );\n\tPetscFree( to_fetch );\n\tStg_ISDestroy(&is_eqnum );\n\tStg_VecScatterDestroy(&vscat_eqnum );\n\n\treturn 0;\n}\n", "meta": {"hexsha": "8f8b5cf72a34e3e0d5f3aee2225b85b7e30f577b", "size": 51252, "ext": "c", "lang": "C", "max_stars_repo_path": "underworld/libUnderworld/StgFEM/Discretisation/src/FeEquationNumber.c", "max_stars_repo_name": "rbeucher/underworld2", "max_stars_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "underworld/libUnderworld/StgFEM/Discretisation/src/FeEquationNumber.c", "max_issues_repo_name": "rbeucher/underworld2", "max_issues_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "underworld/libUnderworld/StgFEM/Discretisation/src/FeEquationNumber.c", "max_forks_repo_name": "rbeucher/underworld2", "max_forks_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7698209719, "max_line_length": 137, "alphanum_fraction": 0.6381409506, "num_tokens": 15825, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.26894142136999516, "lm_q2_score": 0.027169232717241726, "lm_q1q2_score": 0.007306932064507166}}
{"text": "\ufeff// Created by BlurringShadow at 2021-02-27-\u4e0b\u5348 10:24\n\n#pragma once\n\n#include <algorithm>\n#include <chrono>\n\n#ifdef __cpp_lib_concepts\n#include <concepts>\n#include <ranges>\n#endif\n\n#include <execution>\n#include <optional>\n#include <string>\n#include <type_traits>\n#include <utility>\n\n#include <nameof.hpp>\n#include <boost/type_traits.hpp>\n#include <entt/entt.hpp>\n#include <fmt/ostream.h>\n#include <glm/ext.hpp>\n#include <gsl/gsl>\n#include <range/v3/all.hpp>\n#include <rxcpp/rx.hpp>\n#include <tl/expected.hpp>\n\nusing namespace std::literals;\n\nnamespace polycumic::utility\n{\n#ifndef __cpp_lib_concepts\n#define SFINAE(...) std::enable_if_t<__VA_ARGS__>* = nullptr\n#endif\n    using tl::expected;\n\n    template<typename T>\n    struct auto_cast\n    {\n        T&& t;\n\n        template<typename U>\n#ifdef __cpp_lib_concepts\n        requires requires { static_cast<std::decay_t<U>>(std::forward<T>(t)); }\n#endif\n        [[nodiscard]] constexpr operator\n        U() noexcept(std::is_nothrow_constructible_v<T, std::decay_t<U>>)\n        {\n            return static_cast<std::decay_t<U>>(std::forward<T>(t));\n        }\n    };\n\n    template<typename T>\n    auto_cast(T&& t) -> auto_cast<T>;\n\n    template<typename T, typename U, typename Comp>\n    constexpr T& set_if(T& left, U&& right, Comp comp)\n    {\n        if(comp(right, left)) left = std::forward<U>(right);\n        return left;\n    }\n\n    template<typename T, typename U>\n    constexpr T& set_if_greater(T& left, U&& right)\n    {\n        return set_if(left, std::forward<U>(right), std::greater<>{});\n    }\n\n    template<typename T, typename U>\n    constexpr T& set_if_lesser(T& left, U&& right)\n    {\n        return set_if(left, std::forward<U>(right), std::less<>{});\n    }\n\n    template<typename T, typename Compare>\n    [[nodiscard]] constexpr bool is_between(\n        const T& v,\n        const boost::type_identity_t<T>& min,\n        const boost::type_identity_t<T>& max,\n        Compare cmp\n    ) { return std::addressof(std::clamp(v, min, max, cmp)) == std::addressof(v); }\n\n    template<typename T>\n    [[nodiscard]] constexpr bool is_between(\n        const T& v,\n        const boost::type_identity_t<T>& min,\n        const boost::type_identity_t<T>& max\n    ) { return is_between(v, min, max, std::less<>{}); }\n\n#define AUTO_MEMBER(name, ini) decltype(ini) name = ini\n\n#define CONST_AUTO_MEMBER(name, ini) const decltype(ini) name = ini\n\n#define CONST_AUTO_REF_MEMBER(name, ini) const decltype(ini)& name = ini\n\n    namespace details\n    {\n        inline static std::random_device random_device;\n\n        inline static std::mt19937 random_engine{std::random_device{}()};\n    }\n\n    constexpr auto& get_random_device() { return details::random_device; }\n\n    constexpr auto& get_random_engine() { return details::random_engine; }\n\n    CPP_template(typename T)(requires std::is_enum_v<T>)\n    constexpr auto to_underlying(const T v) { return static_cast<std::underlying_type_t<T>>(v); }\n}\n", "meta": {"hexsha": "a5ff54db34b182b6b87ebae4fc570172a876ed1e", "size": 2941, "ext": "h", "lang": "C", "max_stars_repo_path": "polycumic/utility/include/utility_core.h", "max_stars_repo_name": "BlurringShadow/Polycumic", "max_stars_repo_head_hexsha": "616eac5d99775a9c130bfea7bf856d21d2528002", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "polycumic/utility/include/utility_core.h", "max_issues_repo_name": "BlurringShadow/Polycumic", "max_issues_repo_head_hexsha": "616eac5d99775a9c130bfea7bf856d21d2528002", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "polycumic/utility/include/utility_core.h", "max_forks_repo_name": "BlurringShadow/Polycumic", "max_forks_repo_head_hexsha": "616eac5d99775a9c130bfea7bf856d21d2528002", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4954954955, "max_line_length": 97, "alphanum_fraction": 0.6572594356, "num_tokens": 747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.26894142136999516, "lm_q2_score": 0.027169231929534604, "lm_q1q2_score": 0.007306931852660093}}
{"text": "/* matrix/gsl_matrix_int.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_MATRIX_INT_H__\n#define __GSL_MATRIX_INT_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_vector_int.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size1;\n  size_t size2;\n  size_t tda;\n  int * data;\n  gsl_block_int * block;\n  int owner;\n} gsl_matrix_int;\n\ntypedef struct\n{\n  gsl_matrix_int matrix;\n} _gsl_matrix_int_view;\n\ntypedef _gsl_matrix_int_view gsl_matrix_int_view;\n\ntypedef struct\n{\n  gsl_matrix_int matrix;\n} _gsl_matrix_int_const_view;\n\ntypedef const _gsl_matrix_int_const_view gsl_matrix_int_const_view;\n\n/* Allocation */\n\nGSL_EXPORT\ngsl_matrix_int *\ngsl_matrix_int_alloc (const size_t n1, const size_t n2);\n\nGSL_EXPORT\ngsl_matrix_int *\ngsl_matrix_int_calloc (const size_t n1, const size_t n2);\n\nGSL_EXPORT\ngsl_matrix_int *\ngsl_matrix_int_alloc_from_block (gsl_block_int * b,\n                                   const size_t offset,\n                                   const size_t n1,\n                                   const size_t n2,\n                                   const size_t d2);\n\nGSL_EXPORT\ngsl_matrix_int *\ngsl_matrix_int_alloc_from_matrix (gsl_matrix_int * m,\n                                    const size_t k1,\n                                    const size_t k2,\n                                    const size_t n1,\n                                    const size_t n2);\n\nGSL_EXPORT\ngsl_vector_int *\ngsl_vector_int_alloc_row_from_matrix (gsl_matrix_int * m,\n                                        const size_t i);\n\nGSL_EXPORT\ngsl_vector_int *\ngsl_vector_int_alloc_col_from_matrix (gsl_matrix_int * m,\n                                        const size_t j);\n\nGSL_EXPORT void gsl_matrix_int_free (gsl_matrix_int * m);\n\n/* Views */\n\nGSL_EXPORT\n_gsl_matrix_int_view\ngsl_matrix_int_submatrix (gsl_matrix_int * m,\n                            const size_t i, const size_t j,\n                            const size_t n1, const size_t n2);\n\nGSL_EXPORT\n_gsl_vector_int_view\ngsl_matrix_int_row (gsl_matrix_int * m, const size_t i);\n\nGSL_EXPORT\n_gsl_vector_int_view\ngsl_matrix_int_column (gsl_matrix_int * m, const size_t j);\n\nGSL_EXPORT\n_gsl_vector_int_view\ngsl_matrix_int_diagonal (gsl_matrix_int * m);\n\nGSL_EXPORT\n_gsl_vector_int_view\ngsl_matrix_int_subdiagonal (gsl_matrix_int * m, const size_t k);\n\nGSL_EXPORT\n_gsl_vector_int_view\ngsl_matrix_int_superdiagonal (gsl_matrix_int * m, const size_t k);\n\nGSL_EXPORT\n_gsl_matrix_int_view\ngsl_matrix_int_view_array (int * base,\n                             const size_t n1,\n                             const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_int_view\ngsl_matrix_int_view_array_with_tda (int * base,\n                                      const size_t n1,\n                                      const size_t n2,\n                                      const size_t tda);\n\n\nGSL_EXPORT\n_gsl_matrix_int_view\ngsl_matrix_int_view_vector (gsl_vector_int * v,\n                              const size_t n1,\n                              const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_int_view\ngsl_matrix_int_view_vector_with_tda (gsl_vector_int * v,\n                                       const size_t n1,\n                                       const size_t n2,\n                                       const size_t tda);\n\n\nGSL_EXPORT\n_gsl_matrix_int_const_view\ngsl_matrix_int_const_submatrix (const gsl_matrix_int * m,\n                                  const size_t i, const size_t j,\n                                  const size_t n1, const size_t n2);\n\nGSL_EXPORT\n_gsl_vector_int_const_view\ngsl_matrix_int_const_row (const gsl_matrix_int * m,\n                            const size_t i);\n\nGSL_EXPORT\n_gsl_vector_int_const_view\ngsl_matrix_int_const_column (const gsl_matrix_int * m,\n                               const size_t j);\n\nGSL_EXPORT\n_gsl_vector_int_const_view\ngsl_matrix_int_const_diagonal (const gsl_matrix_int * m);\n\nGSL_EXPORT\n_gsl_vector_int_const_view\ngsl_matrix_int_const_subdiagonal (const gsl_matrix_int * m,\n                                    const size_t k);\n\nGSL_EXPORT\n_gsl_vector_int_const_view\ngsl_matrix_int_const_superdiagonal (const gsl_matrix_int * m,\n                                      const size_t k);\n\nGSL_EXPORT\n_gsl_matrix_int_const_view\ngsl_matrix_int_const_view_array (const int * base,\n                                   const size_t n1,\n                                   const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_int_const_view\ngsl_matrix_int_const_view_array_with_tda (const int * base,\n                                            const size_t n1,\n                                            const size_t n2,\n                                            const size_t tda);\n\nGSL_EXPORT\n_gsl_matrix_int_const_view\ngsl_matrix_int_const_view_vector (const gsl_vector_int * v,\n                                    const size_t n1,\n                                    const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_int_const_view\ngsl_matrix_int_const_view_vector_with_tda (const gsl_vector_int * v,\n                                             const size_t n1,\n                                             const size_t n2,\n                                             const size_t tda);\n\n/* Operations */\n\nGSL_EXPORT int   gsl_matrix_int_get(const gsl_matrix_int * m, const size_t i, const size_t j);\nGSL_EXPORT void    gsl_matrix_int_set(gsl_matrix_int * m, const size_t i, const size_t j, const int x);\n\nGSL_EXPORT int * gsl_matrix_int_ptr(gsl_matrix_int * m, const size_t i, const size_t j);\nGSL_EXPORT const int * gsl_matrix_int_const_ptr(const gsl_matrix_int * m, const size_t i, const size_t j);\n\nGSL_EXPORT void gsl_matrix_int_set_zero (gsl_matrix_int * m);\nGSL_EXPORT void gsl_matrix_int_set_identity (gsl_matrix_int * m);\nGSL_EXPORT void gsl_matrix_int_set_all (gsl_matrix_int * m, int x);\n\nGSL_EXPORT int gsl_matrix_int_fread (FILE * stream, gsl_matrix_int * m) ;\nGSL_EXPORT int gsl_matrix_int_fwrite (FILE * stream, const gsl_matrix_int * m) ;\nGSL_EXPORT int gsl_matrix_int_fscanf (FILE * stream, gsl_matrix_int * m);\nGSL_EXPORT int gsl_matrix_int_fprintf (FILE * stream, const gsl_matrix_int * m, const char * format);\n\nGSL_EXPORT int gsl_matrix_int_memcpy(gsl_matrix_int * dest, const gsl_matrix_int * src);\nGSL_EXPORT int gsl_matrix_int_swap(gsl_matrix_int * m1, gsl_matrix_int * m2);\n\nGSL_EXPORT int gsl_matrix_int_swap_rows(gsl_matrix_int * m, const size_t i, const size_t j);\nGSL_EXPORT int gsl_matrix_int_swap_columns(gsl_matrix_int * m, const size_t i, const size_t j);\nGSL_EXPORT int gsl_matrix_int_swap_rowcol(gsl_matrix_int * m, const size_t i, const size_t j);\nGSL_EXPORT int gsl_matrix_int_transpose (gsl_matrix_int * m);\nGSL_EXPORT int gsl_matrix_int_transpose_memcpy (gsl_matrix_int * dest, const gsl_matrix_int * src);\n\nGSL_EXPORT int gsl_matrix_int_max (const gsl_matrix_int * m);\nGSL_EXPORT int gsl_matrix_int_min (const gsl_matrix_int * m);\nGSL_EXPORT void gsl_matrix_int_minmax (const gsl_matrix_int * m, int * min_out, int * max_out);\n\nGSL_EXPORT void gsl_matrix_int_max_index (const gsl_matrix_int * m, size_t * imax, size_t *jmax);\nGSL_EXPORT void gsl_matrix_int_min_index (const gsl_matrix_int * m, size_t * imin, size_t *jmin);\nGSL_EXPORT void gsl_matrix_int_minmax_index (const gsl_matrix_int * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);\n\nGSL_EXPORT int gsl_matrix_int_isnull (const gsl_matrix_int * m);\n\nGSL_EXPORT int gsl_matrix_int_add (gsl_matrix_int * a, const gsl_matrix_int * b);\nGSL_EXPORT int gsl_matrix_int_sub (gsl_matrix_int * a, const gsl_matrix_int * b);\nGSL_EXPORT int gsl_matrix_int_mul_elements (gsl_matrix_int * a, const gsl_matrix_int * b);\nGSL_EXPORT int gsl_matrix_int_div_elements (gsl_matrix_int * a, const gsl_matrix_int * b);\nGSL_EXPORT int gsl_matrix_int_scale (gsl_matrix_int * a, const double x);\nGSL_EXPORT int gsl_matrix_int_add_constant (gsl_matrix_int * a, const double x);\nGSL_EXPORT int gsl_matrix_int_add_diagonal (gsl_matrix_int * a, const double x);\n\n/***********************************************************************/\n/* The functions below are obsolete                                    */\n/***********************************************************************/\nGSL_EXPORT int gsl_matrix_int_get_row(gsl_vector_int * v, const gsl_matrix_int * m, const size_t i);\nGSL_EXPORT int gsl_matrix_int_get_col(gsl_vector_int * v, const gsl_matrix_int * m, const size_t j);\nGSL_EXPORT int gsl_matrix_int_set_row(gsl_matrix_int * m, const size_t i, const gsl_vector_int * v);\nGSL_EXPORT int gsl_matrix_int_set_col(gsl_matrix_int * m, const size_t j, const gsl_vector_int * v);\n \n/* inline functions if you are using GCC */\n\n#ifdef HAVE_INLINE\nextern inline \nint\ngsl_matrix_int_get(const gsl_matrix_int * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_VAL(\"first index out of range\", GSL_EINVAL, 0) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_VAL(\"second index out of range\", GSL_EINVAL, 0) ;\n    }\n#endif\n  return m->data[i * m->tda + j] ;\n} \n\nextern inline \nvoid\ngsl_matrix_int_set(gsl_matrix_int * m, const size_t i, const size_t j, const int x)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_VOID(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_VOID(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  m->data[i * m->tda + j] = x ;\n}\n\nextern inline \nint *\ngsl_matrix_int_ptr(gsl_matrix_int * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  return (int *) (m->data + (i * m->tda + j)) ;\n} \n\nextern inline \nconst int *\ngsl_matrix_int_const_ptr(const gsl_matrix_int * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  return (const int *) (m->data + (i * m->tda + j)) ;\n} \n\n#endif\n\n__END_DECLS\n\n#endif /* __GSL_MATRIX_INT_H__ */\n", "meta": {"hexsha": "1a732f95fe9f2c4177681b3196111b133dfd34f4", "size": 11196, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/gsl/include/gsl/gsl_matrix_int.h", "max_stars_repo_name": "dynaryu/vaws", "max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/gsl/include/gsl/gsl_matrix_int.h", "max_issues_repo_name": "dynaryu/vaws", "max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/gsl/include/gsl/gsl_matrix_int.h", "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6413994169, "max_line_length": 131, "alphanum_fraction": 0.667738478, "num_tokens": 2791, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29421497216298875, "lm_q2_score": 0.02479815942982506, "lm_q1q2_score": 0.0072959897863393375}}
{"text": "#pragma once\n#include \"typetraits.h\"\n\n#if defined(__has_include) && __has_include(<version>)\n#include <version>\n#if defined(__cpp_lib_span) && __cpp_lib_span >= 202002L\n#include <span>\n#else\n#include <gsl/span>\n#endif    // __cpp_lib_span >= 202002L\n#else\n#include <gsl/span>\n#endif    //__has_include(<version>)\n\n#include \"uuid.h\"\n\n#include <array>\n#include <chrono>\n#include <compare>\n\ntemplate <typename T> struct UuidObjectT;\n\ntemplate <typename T> struct UuidBasedId\n{\n    static UuidBasedId<T> Create()\n    {\n        UuidBasedId<T>     uuid;\n        std::random_device rd;\n        auto               seed_data = std::array<unsigned, std::mt19937::state_size>{};\n        std::generate(std::begin(seed_data), std::end(seed_data), std::ref(rd));\n        std::seed_seq                seq(std::begin(seed_data), std::end(seed_data));\n        std::mt19937                 generator(seq);\n        uuids::uuid_random_generator gen{generator};\n        uuid.uuid = gen();\n        return uuid;\n    }\n\n    template <typename TStr> static constexpr UuidBasedId<T> FromString(TStr const& str)\n    {\n        UuidBasedId<T> uuid;\n        uuid.guid = uuids::uuid(str);\n    }\n\n    public:\n    UuidBasedId() = default;\n\n    uuids::uuid uuid;\n\n    constexpr bool                  Empty() const { return uuid == Invalid().uuid; }\n    static constexpr UuidBasedId<T> Invalid() { return UuidBasedId<T>(); }\n    friend UuidObjectT<T>;\n\n    friend std::hash<UuidBasedId<T>>;\n};\n\ntemplate <typename T> struct UuidObjectT\n{\n    using Id = UuidBasedId<T>;\n    UuidObjectT() {}\n    Id id = Id::Create();\n};\n\ntemplate <> struct Stencil::TypeTraits<uuids::uuid>\n{\n    using Categories = std::tuple<Stencil::Category::Primitive>;\n};\n\ntemplate <typename T> struct Stencil::TypeTraits<UuidBasedId<T>>\n{\n    using Categories = std::tuple<Stencil::Category::Primitive>;\n};\n", "meta": {"hexsha": "0a1a4b5668a79ae3ca12ce730a1c10cfc41c2400", "size": 1843, "ext": "h", "lang": "C", "max_stars_repo_path": "include/stencil/uuidobject.h", "max_stars_repo_name": "ankurvdev/stencil", "max_stars_repo_head_hexsha": "b6429f8b92947273a5e66d5f10210b960616a89d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/stencil/uuidobject.h", "max_issues_repo_name": "ankurvdev/stencil", "max_issues_repo_head_hexsha": "b6429f8b92947273a5e66d5f10210b960616a89d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/stencil/uuidobject.h", "max_forks_repo_name": "ankurvdev/stencil", "max_forks_repo_head_hexsha": "b6429f8b92947273a5e66d5f10210b960616a89d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5972222222, "max_line_length": 88, "alphanum_fraction": 0.6364622897, "num_tokens": 473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2942149597859341, "lm_q2_score": 0.02479816028567514, "lm_q1q2_score": 0.007295989731215059}}
{"text": "/* matrix/gsl_matrix_long_double.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_MATRIX_LONG_DOUBLE_H__\n#define __GSL_MATRIX_LONG_DOUBLE_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_vector_long_double.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size1;\n  size_t size2;\n  size_t tda;\n  long double * data;\n  gsl_block_long_double * block;\n  int owner;\n} gsl_matrix_long_double;\n\ntypedef struct\n{\n  gsl_matrix_long_double matrix;\n} _gsl_matrix_long_double_view;\n\ntypedef _gsl_matrix_long_double_view gsl_matrix_long_double_view;\n\ntypedef struct\n{\n  gsl_matrix_long_double matrix;\n} _gsl_matrix_long_double_const_view;\n\ntypedef const _gsl_matrix_long_double_const_view gsl_matrix_long_double_const_view;\n\n/* Allocation */\n\ngsl_matrix_long_double * \ngsl_matrix_long_double_alloc (const size_t n1, const size_t n2);\n\ngsl_matrix_long_double * \ngsl_matrix_long_double_calloc (const size_t n1, const size_t n2);\n\ngsl_matrix_long_double * \ngsl_matrix_long_double_alloc_from_block (gsl_block_long_double * b, \n                                   const size_t offset, \n                                   const size_t n1, \n                                   const size_t n2, \n                                   const size_t d2);\n\ngsl_matrix_long_double * \ngsl_matrix_long_double_alloc_from_matrix (gsl_matrix_long_double * m,\n                                    const size_t k1, \n                                    const size_t k2,\n                                    const size_t n1, \n                                    const size_t n2);\n\ngsl_vector_long_double * \ngsl_vector_long_double_alloc_row_from_matrix (gsl_matrix_long_double * m,\n                                        const size_t i);\n\ngsl_vector_long_double * \ngsl_vector_long_double_alloc_col_from_matrix (gsl_matrix_long_double * m,\n                                        const size_t j);\n\nvoid gsl_matrix_long_double_free (gsl_matrix_long_double * m);\n\n/* Views */\n\n_gsl_matrix_long_double_view \ngsl_matrix_long_double_submatrix (gsl_matrix_long_double * m, \n                            const size_t i, const size_t j, \n                            const size_t n1, const size_t n2);\n\n_gsl_vector_long_double_view \ngsl_matrix_long_double_row (gsl_matrix_long_double * m, const size_t i);\n\n_gsl_vector_long_double_view \ngsl_matrix_long_double_column (gsl_matrix_long_double * m, const size_t j);\n\n_gsl_vector_long_double_view \ngsl_matrix_long_double_diagonal (gsl_matrix_long_double * m);\n\n_gsl_vector_long_double_view \ngsl_matrix_long_double_subdiagonal (gsl_matrix_long_double * m, const size_t k);\n\n_gsl_vector_long_double_view \ngsl_matrix_long_double_superdiagonal (gsl_matrix_long_double * m, const size_t k);\n\n_gsl_matrix_long_double_view\ngsl_matrix_long_double_view_array (long double * base,\n                             const size_t n1, \n                             const size_t n2);\n\n_gsl_matrix_long_double_view\ngsl_matrix_long_double_view_array_with_tda (long double * base, \n                                      const size_t n1, \n                                      const size_t n2,\n                                      const size_t tda);\n\n\n_gsl_matrix_long_double_view\ngsl_matrix_long_double_view_vector (gsl_vector_long_double * v,\n                              const size_t n1, \n                              const size_t n2);\n\n_gsl_matrix_long_double_view\ngsl_matrix_long_double_view_vector_with_tda (gsl_vector_long_double * v,\n                                       const size_t n1, \n                                       const size_t n2,\n                                       const size_t tda);\n\n\n_gsl_matrix_long_double_const_view \ngsl_matrix_long_double_const_submatrix (const gsl_matrix_long_double * m, \n                                  const size_t i, const size_t j, \n                                  const size_t n1, const size_t n2);\n\n_gsl_vector_long_double_const_view \ngsl_matrix_long_double_const_row (const gsl_matrix_long_double * m, \n                            const size_t i);\n\n_gsl_vector_long_double_const_view \ngsl_matrix_long_double_const_column (const gsl_matrix_long_double * m, \n                               const size_t j);\n\n_gsl_vector_long_double_const_view\ngsl_matrix_long_double_const_diagonal (const gsl_matrix_long_double * m);\n\n_gsl_vector_long_double_const_view \ngsl_matrix_long_double_const_subdiagonal (const gsl_matrix_long_double * m, \n                                    const size_t k);\n\n_gsl_vector_long_double_const_view \ngsl_matrix_long_double_const_superdiagonal (const gsl_matrix_long_double * m, \n                                      const size_t k);\n\n_gsl_matrix_long_double_const_view\ngsl_matrix_long_double_const_view_array (const long double * base,\n                                   const size_t n1, \n                                   const size_t n2);\n\n_gsl_matrix_long_double_const_view\ngsl_matrix_long_double_const_view_array_with_tda (const long double * base, \n                                            const size_t n1, \n                                            const size_t n2,\n                                            const size_t tda);\n\n_gsl_matrix_long_double_const_view\ngsl_matrix_long_double_const_view_vector (const gsl_vector_long_double * v,\n                                    const size_t n1, \n                                    const size_t n2);\n\n_gsl_matrix_long_double_const_view\ngsl_matrix_long_double_const_view_vector_with_tda (const gsl_vector_long_double * v,\n                                             const size_t n1, \n                                             const size_t n2,\n                                             const size_t tda);\n\n/* Operations */\n\nlong double   gsl_matrix_long_double_get(const gsl_matrix_long_double * m, const size_t i, const size_t j);\nvoid    gsl_matrix_long_double_set(gsl_matrix_long_double * m, const size_t i, const size_t j, const long double x);\n\nlong double * gsl_matrix_long_double_ptr(gsl_matrix_long_double * m, const size_t i, const size_t j);\nconst long double * gsl_matrix_long_double_const_ptr(const gsl_matrix_long_double * m, const size_t i, const size_t j);\n\nvoid gsl_matrix_long_double_set_zero (gsl_matrix_long_double * m);\nvoid gsl_matrix_long_double_set_identity (gsl_matrix_long_double * m);\nvoid gsl_matrix_long_double_set_all (gsl_matrix_long_double * m, long double x);\n\nint gsl_matrix_long_double_fread (FILE * stream, gsl_matrix_long_double * m) ;\nint gsl_matrix_long_double_fwrite (FILE * stream, const gsl_matrix_long_double * m) ;\nint gsl_matrix_long_double_fscanf (FILE * stream, gsl_matrix_long_double * m);\nint gsl_matrix_long_double_fprintf (FILE * stream, const gsl_matrix_long_double * m, const char * format);\n \nint gsl_matrix_long_double_memcpy(gsl_matrix_long_double * dest, const gsl_matrix_long_double * src);\nint gsl_matrix_long_double_swap(gsl_matrix_long_double * m1, gsl_matrix_long_double * m2);\n\nint gsl_matrix_long_double_swap_rows(gsl_matrix_long_double * m, const size_t i, const size_t j);\nint gsl_matrix_long_double_swap_columns(gsl_matrix_long_double * m, const size_t i, const size_t j);\nint gsl_matrix_long_double_swap_rowcol(gsl_matrix_long_double * m, const size_t i, const size_t j);\nint gsl_matrix_long_double_transpose (gsl_matrix_long_double * m);\nint gsl_matrix_long_double_transpose_memcpy (gsl_matrix_long_double * dest, const gsl_matrix_long_double * src);\n\nlong double gsl_matrix_long_double_max (const gsl_matrix_long_double * m);\nlong double gsl_matrix_long_double_min (const gsl_matrix_long_double * m);\nvoid gsl_matrix_long_double_minmax (const gsl_matrix_long_double * m, long double * min_out, long double * max_out);\n\nvoid gsl_matrix_long_double_max_index (const gsl_matrix_long_double * m, size_t * imax, size_t *jmax);\nvoid gsl_matrix_long_double_min_index (const gsl_matrix_long_double * m, size_t * imin, size_t *jmin);\nvoid gsl_matrix_long_double_minmax_index (const gsl_matrix_long_double * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);\n\nint gsl_matrix_long_double_isnull (const gsl_matrix_long_double * m);\nint gsl_matrix_long_double_ispos (const gsl_matrix_long_double * m);\nint gsl_matrix_long_double_isneg (const gsl_matrix_long_double * m);\n\nint gsl_matrix_long_double_add (gsl_matrix_long_double * a, const gsl_matrix_long_double * b);\nint gsl_matrix_long_double_sub (gsl_matrix_long_double * a, const gsl_matrix_long_double * b);\nint gsl_matrix_long_double_mul_elements (gsl_matrix_long_double * a, const gsl_matrix_long_double * b);\nint gsl_matrix_long_double_div_elements (gsl_matrix_long_double * a, const gsl_matrix_long_double * b);\nint gsl_matrix_long_double_scale (gsl_matrix_long_double * a, const double x);\nint gsl_matrix_long_double_add_constant (gsl_matrix_long_double * a, const double x);\nint gsl_matrix_long_double_add_diagonal (gsl_matrix_long_double * a, const double x);\n\n/***********************************************************************/\n/* The functions below are obsolete                                    */\n/***********************************************************************/\nint gsl_matrix_long_double_get_row(gsl_vector_long_double * v, const gsl_matrix_long_double * m, const size_t i);\nint gsl_matrix_long_double_get_col(gsl_vector_long_double * v, const gsl_matrix_long_double * m, const size_t j);\nint gsl_matrix_long_double_set_row(gsl_matrix_long_double * m, const size_t i, const gsl_vector_long_double * v);\nint gsl_matrix_long_double_set_col(gsl_matrix_long_double * m, const size_t j, const gsl_vector_long_double * v);\n\n/* inline functions if you are using GCC */\n\n#ifdef HAVE_INLINE\nextern inline \nlong double\ngsl_matrix_long_double_get(const gsl_matrix_long_double * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_VAL(\"first index out of range\", GSL_EINVAL, 0) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_VAL(\"second index out of range\", GSL_EINVAL, 0) ;\n    }\n#endif\n  return m->data[i * m->tda + j] ;\n} \n\nextern inline \nvoid\ngsl_matrix_long_double_set(gsl_matrix_long_double * m, const size_t i, const size_t j, const long double x)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_VOID(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_VOID(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  m->data[i * m->tda + j] = x ;\n}\n\nextern inline \nlong double *\ngsl_matrix_long_double_ptr(gsl_matrix_long_double * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  return (long double *) (m->data + (i * m->tda + j)) ;\n} \n\nextern inline \nconst long double *\ngsl_matrix_long_double_const_ptr(const gsl_matrix_long_double * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  return (const long double *) (m->data + (i * m->tda + j)) ;\n} \n\n#endif\n\n__END_DECLS\n\n#endif /* __GSL_MATRIX_LONG_DOUBLE_H__ */\n", "meta": {"hexsha": "3670105da898015bbf3d05d8fea9bde689672457", "size": 12282, "ext": "h", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/matrix/gsl_matrix_long_double.h", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/matrix/gsl_matrix_long_double.h", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/matrix/gsl_matrix_long_double.h", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 38.5015673981, "max_line_length": 136, "alphanum_fraction": 0.6956521739, "num_tokens": 2838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30735800417608683, "lm_q2_score": 0.023689473841081523, "lm_q1q2_score": 0.007281149399776435}}
{"text": "/**\n * File: spce_pgp.h\n * Interface to PGplot routines.\n *\n */\n\n#ifndef _SPCE_PGP_H\n\n#define _SPCE_PGP_H\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <gsl/gsl_roots.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_statistics.h>\n#include <gsl/gsl_vector.h>\n#include \"aXe_grism.h\"\n#include \"aXe_utils.h\"\n#include \"spce_pathlength.h\"\n#include \"spce_output.h\"\n\nextern void\npgp_stamp_image (const ap_pixel * const ap_p, const int n_sub,\n\t\t const object * ob, int beamnum, char filename[],\n\t\t const int negative);\n#endif /* !_SPCE_PGP_H */\n", "meta": {"hexsha": "83470ab2765df933e20ac983b067597465d68831", "size": 577, "ext": "h", "lang": "C", "max_stars_repo_path": "cextern/src/spce_pgp.h", "max_stars_repo_name": "sosey/pyaxe", "max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cextern/src/spce_pgp.h", "max_issues_repo_name": "sosey/pyaxe", "max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cextern/src/spce_pgp.h", "max_forks_repo_name": "sosey/pyaxe", "max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.8965517241, "max_line_length": 62, "alphanum_fraction": 0.719237435, "num_tokens": 172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.2720245392906821, "lm_q2_score": 0.026759280274886214, "lm_q1q2_score": 0.0072791808885261594}}
{"text": "#pragma once\r\n\r\n#include <cstddef>\r\n#include <gsl/gsl>\r\n#include <iterator>\r\n#include <limits>\r\n\r\n#include \"../math/General.h\"\r\n#include \"Concepts.h\"\r\n\r\nnamespace utils {\r\n\tusing concepts::DefaultConstructible, concepts::Integral, concepts::Copyable, concepts::Movable,\r\n\t\tconcepts::NotMovable, concepts::ConstructibleFrom;\r\n\t/// @brief A simple Ring Buffer implementation.\r\n\t/// Supports resizing, writing, reading, erasing, and provides mutable and immutable\r\n\t/// random access iterators.\r\n\t///\r\n\t/// # Iterator Invalidation\r\n\t/// * Iterators are lazily evaluated, so will only ever be invalidated at their current state.\r\n\t/// Performing any mutating operation (mutating the iterator, not the underlying data) on them\r\n\t/// will re-sync them with their associated `RingBuffer`.\r\n\t/// The following operations will invalidate an iterator's current state:\r\n\t/// - Read-only operations: never\r\n\t/// - clear: always\r\n\t/// - reserve: only if the `RingBuffer` changed capacity\r\n\t/// - erase: Erased elements and all following elements\r\n\t/// - push_back, emplace_back: only `end()`\r\n\t/// - insert, emplace: only the element at the position inserted/emplaced\r\n\t/// - pop_back: the element removed and `end()`\r\n\t///\r\n\t/// @tparam T - The type to store in the `RingBuffer`; Must be Default Constructible\r\n\ttemplate<DefaultConstructible T>\r\n\tclass RingBuffer {\r\n\t  public:\r\n\t\t/// Default capacity of `RingBuffer`\r\n\t\tstatic const constexpr size_t DEFAULT_CAPACITY = 16;\r\n\r\n\t\t/// @brief Random-Access Bidirectional iterator for `RingBuffer`\r\n\t\t/// @note All navigation operators are checked such that any movement past `begin()` or\r\n\t\t/// `end()` is ignored.\r\n\t\tclass Iterator {\r\n\t\t  public:\r\n\t\t\tusing iterator_category = std::random_access_iterator_tag;\r\n\t\t\tusing difference_type = std::ptrdiff_t;\r\n\t\t\tusing value_type = T;\r\n\t\t\tusing pointer = value_type*;\r\n\t\t\tusing reference = value_type&;\r\n\r\n\t\t\tconstexpr explicit Iterator(pointer ptr,\r\n\t\t\t\t\t\t\t\t\t\tRingBuffer* containerPtr,\r\n\t\t\t\t\t\t\t\t\t\tsize_t currentIndex) noexcept\r\n\t\t\t\t: mPtr(ptr), mContainerPtr(containerPtr), mCurrentIndex(currentIndex) {\r\n\t\t\t}\r\n\t\t\tconstexpr Iterator(const Iterator& iter) noexcept = default;\r\n\t\t\tconstexpr Iterator(Iterator&& iter) noexcept = default;\r\n\t\t\t~Iterator() noexcept = default;\r\n\r\n\t\t\t/// @brief Returns the index in the `RingBuffer` that corresponds\r\n\t\t\t/// to the element this iterator points to\r\n\t\t\t///\r\n\t\t\t/// @return The index corresponding with the element this points to\r\n\t\t\t[[nodiscard]] constexpr inline auto getIndex() const noexcept -> size_t {\r\n\t\t\t\treturn mCurrentIndex;\r\n\t\t\t}\r\n\r\n\t\t\tconstexpr auto operator=(const Iterator& iter) noexcept -> Iterator& = default;\r\n\t\t\tconstexpr auto operator=(Iterator&& iter) noexcept -> Iterator& = default;\r\n\r\n\t\t\tconstexpr inline auto operator==(const Iterator& rhs) const noexcept -> bool {\r\n\t\t\t\treturn mPtr == rhs.mPtr;\r\n\t\t\t}\r\n\r\n\t\t\tconstexpr inline auto operator!=(const Iterator& rhs) const noexcept -> bool {\r\n\t\t\t\treturn mPtr != rhs.mPtr;\r\n\t\t\t}\r\n\r\n\t\t\tconstexpr inline auto operator*() const noexcept -> reference {\r\n\t\t\t\treturn *mPtr;\r\n\t\t\t}\r\n\r\n\t\t\tconstexpr inline auto operator->() noexcept -> pointer {\r\n\t\t\t\treturn mPtr;\r\n\t\t\t}\r\n\r\n\t\t\tconstexpr inline auto operator++() noexcept -> Iterator& {\r\n\t\t\t\tmCurrentIndex++;\r\n\t\t\t\tif(mCurrentIndex >= mContainerPtr->capacity()) {\r\n\t\t\t\t\tmCurrentIndex = mContainerPtr->capacity();\r\n\t\t\t\t\tmPtr = mContainerPtr->end().mPtr;\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tmPtr = &(*mContainerPtr)[mCurrentIndex];\r\n\t\t\t\t}\r\n\t\t\t\treturn *this;\r\n\t\t\t}\r\n\r\n\t\t\tconstexpr inline auto operator++(int) noexcept -> Iterator {\r\n\t\t\t\tIterator temp = *this;\r\n\t\t\t\t++(*this);\r\n\t\t\t\treturn temp;\r\n\t\t\t}\r\n\r\n\t\t\tconstexpr inline auto operator--() noexcept -> Iterator& {\r\n\t\t\t\tif(mCurrentIndex == 0) {\r\n\t\t\t\t\treturn *this;\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tmCurrentIndex--;\r\n\t\t\t\t\tmPtr = &(*mContainerPtr)[mCurrentIndex];\r\n\t\t\t\t}\r\n\t\t\t\treturn *this;\r\n\t\t\t}\r\n\r\n\t\t\tconstexpr inline auto operator--(int) noexcept -> Iterator {\r\n\t\t\t\tIterator temp = *this;\r\n\t\t\t\t--(*this);\r\n\t\t\t\treturn temp;\r\n\t\t\t}\r\n\r\n\t\t\tconstexpr inline auto operator+(Integral auto rhs) const noexcept -> Iterator {\r\n\t\t\t\tconst auto diff = static_cast<size_t>(rhs);\r\n\t\t\t\tif(rhs < 0) {\r\n\t\t\t\t\treturn std::move(*this - -rhs);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tauto temp = *this;\r\n\t\t\t\ttemp.mCurrentIndex += diff;\r\n\t\t\t\tif(temp.mCurrentIndex > temp.mContainerPtr->capacity()) {\r\n\t\t\t\t\ttemp.mCurrentIndex = temp.mContainerPtr->capacity();\r\n\t\t\t\t\ttemp.mPtr = temp.mContainerPtr->end().mPtr;\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\ttemp.mPtr = &(*temp.mContainerPtr)[temp.mCurrentIndex];\r\n\t\t\t\t}\r\n\t\t\t\treturn temp;\r\n\t\t\t}\r\n\r\n\t\t\tconstexpr inline auto operator+=(Integral auto rhs) noexcept -> Iterator& {\r\n\t\t\t\t*this = std::move(*this + rhs);\r\n\t\t\t\treturn *this;\r\n\t\t\t}\r\n\r\n\t\t\tconstexpr inline auto operator-(Integral auto rhs) const noexcept -> Iterator {\r\n\t\t\t\tconst auto diff = static_cast<size_t>(rhs);\r\n\t\t\t\tif(rhs < 0) {\r\n\t\t\t\t\treturn std::move(*this + -rhs);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tauto temp = *this;\r\n\t\t\t\tif(diff > temp.mCurrentIndex) {\r\n\t\t\t\t\ttemp.mPtr = temp.mContainerPtr->begin().mPtr;\r\n\t\t\t\t\ttemp.mCurrentIndex = 0;\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\ttemp.mCurrentIndex -= diff;\r\n\t\t\t\t\ttemp.mPtr = &(*temp.mContainerPtr)[temp.mCurrentIndex];\r\n\t\t\t\t}\r\n\t\t\t\treturn temp;\r\n\t\t\t}\r\n\r\n\t\t\tconstexpr inline auto operator-=(Integral auto rhs) noexcept -> Iterator& {\r\n\t\t\t\t*this = std::move(*this - rhs);\r\n\t\t\t\treturn *this;\r\n\t\t\t}\r\n\r\n\t\t\tconstexpr inline auto operator-(const Iterator& rhs) const noexcept -> difference_type {\r\n\t\t\t\treturn mPtr - rhs.mPtr;\r\n\t\t\t}\r\n\r\n\t\t\tconstexpr inline auto operator[](Integral auto index) noexcept -> Iterator {\r\n\t\t\t\treturn std::move(*this + index);\r\n\t\t\t}\r\n\r\n\t\t\tconstexpr inline auto operator>(const Iterator& rhs) const noexcept -> bool {\r\n\t\t\t\treturn mCurrentIndex > rhs.mCurrentIndex;\r\n\t\t\t}\r\n\r\n\t\t\tconstexpr inline auto operator<(const Iterator& rhs) const noexcept -> bool {\r\n\t\t\t\treturn mCurrentIndex < rhs.mCurrentIndex;\r\n\t\t\t}\r\n\r\n\t\t\tconstexpr inline auto operator>=(const Iterator& rhs) const noexcept -> bool {\r\n\t\t\t\treturn mCurrentIndex >= rhs.mCurrentIndex;\r\n\t\t\t}\r\n\r\n\t\t\tconstexpr inline auto operator<=(const Iterator& rhs) const noexcept -> bool {\r\n\t\t\t\treturn mCurrentIndex <= rhs.mCurrentIndex;\r\n\t\t\t}\r\n\r\n\t\t  private:\r\n\t\t\tpointer mPtr;\r\n\t\t\tRingBuffer* mContainerPtr = nullptr;\r\n\t\t\tsize_t mCurrentIndex = 0;\r\n\t\t};\r\n\r\n\t\t/// @brief Read-only Random-Access Bidirectional iterator for `RingBuffer`\r\n\t\t/// @note All navigation operators are checked such that any movement past `begin()` or\r\n\t\t/// `end()` is ignored.\r\n\t\tclass ConstIterator {\r\n\t\t  public:\r\n\t\t\tusing iterator_category = std::random_access_iterator_tag;\r\n\t\t\tusing difference_type = std::ptrdiff_t;\r\n\t\t\tusing value_type = T;\r\n\t\t\tusing pointer = const value_type*;\r\n\t\t\tusing reference = const value_type&;\r\n\r\n\t\t\tconstexpr explicit ConstIterator(pointer ptr,\r\n\t\t\t\t\t\t\t\t\t\t\t RingBuffer* containerPtr,\r\n\t\t\t\t\t\t\t\t\t\t\t size_t currentIndex) noexcept\r\n\t\t\t\t: mPtr(ptr), mContainerPtr(containerPtr), mCurrentIndex(currentIndex) {\r\n\t\t\t}\r\n\t\t\tconstexpr ConstIterator(const ConstIterator& iter) noexcept = default;\r\n\t\t\tconstexpr ConstIterator(ConstIterator&& iter) noexcept = default;\r\n\t\t\t~ConstIterator() noexcept = default;\r\n\r\n\t\t\t/// @brief Returns the index in the `RingBuffer` that corresponds\r\n\t\t\t/// to the element this iterator points to\r\n\t\t\t///\r\n\t\t\t/// @return The index corresponding with the element this points to\r\n\t\t\t[[nodiscard]] constexpr inline auto getIndex() const noexcept -> size_t {\r\n\t\t\t\treturn mCurrentIndex;\r\n\t\t\t}\r\n\r\n\t\t\tconstexpr auto\r\n\t\t\toperator=(const ConstIterator& iter) noexcept -> ConstIterator& = default;\r\n\t\t\tconstexpr auto operator=(ConstIterator&& iter) noexcept -> ConstIterator& = default;\r\n\r\n\t\t\tconstexpr inline auto operator==(const ConstIterator& rhs) const noexcept -> bool {\r\n\t\t\t\treturn mPtr == rhs.mPtr;\r\n\t\t\t}\r\n\r\n\t\t\tconstexpr inline auto operator!=(const ConstIterator& rhs) const noexcept -> bool {\r\n\t\t\t\treturn mPtr != rhs.mPtr;\r\n\t\t\t}\r\n\r\n\t\t\tconstexpr inline auto operator*() const noexcept -> reference {\r\n\t\t\t\treturn *mPtr;\r\n\t\t\t}\r\n\r\n\t\t\tconstexpr inline auto operator->() const noexcept -> pointer {\r\n\t\t\t\treturn mPtr;\r\n\t\t\t}\r\n\r\n\t\t\tconstexpr inline auto operator++() noexcept -> ConstIterator& {\r\n\t\t\t\tmCurrentIndex++;\r\n\t\t\t\tif(mCurrentIndex >= mContainerPtr->capacity()) {\r\n\t\t\t\t\tmCurrentIndex = mContainerPtr->capacity();\r\n\t\t\t\t\tmPtr = mContainerPtr->end().mPtr;\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tmPtr = &(*mContainerPtr)[mCurrentIndex];\r\n\t\t\t\t}\r\n\t\t\t\treturn *this;\r\n\t\t\t}\r\n\r\n\t\t\tconstexpr inline auto operator++(int) noexcept -> ConstIterator {\r\n\t\t\t\tConstIterator temp = *this;\r\n\t\t\t\t++(*this);\r\n\t\t\t\treturn temp;\r\n\t\t\t}\r\n\r\n\t\t\tconstexpr inline auto operator--() noexcept -> ConstIterator& {\r\n\t\t\t\tif(mCurrentIndex == 0) {\r\n\t\t\t\t\treturn *this;\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tmCurrentIndex--;\r\n\t\t\t\t\tmPtr = &(*mContainerPtr)[mCurrentIndex];\r\n\t\t\t\t}\r\n\t\t\t\treturn *this;\r\n\t\t\t}\r\n\r\n\t\t\tconstexpr inline auto operator--(int) noexcept -> ConstIterator {\r\n\t\t\t\tConstIterator temp = *this;\r\n\t\t\t\t--(*this);\r\n\t\t\t\treturn temp;\r\n\t\t\t}\r\n\r\n\t\t\tconstexpr inline auto operator+(Integral auto rhs) const noexcept -> ConstIterator {\r\n\t\t\t\tconst auto diff = static_cast<size_t>(rhs);\r\n\t\t\t\tif(rhs < 0) {\r\n\t\t\t\t\treturn std::move(*this - -rhs);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tauto temp = *this;\r\n\t\t\t\ttemp.mCurrentIndex += diff;\r\n\t\t\t\tif(temp.mCurrentIndex > temp.mContainerPtr->capacity()) {\r\n\t\t\t\t\ttemp.mCurrentIndex = temp.mContainerPtr->capacity();\r\n\t\t\t\t\ttemp.mPtr = temp.mContainerPtr->end().mPtr;\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\ttemp.mPtr = &(*temp.mContainerPtr)[temp.mCurrentIndex];\r\n\t\t\t\t}\r\n\t\t\t\treturn temp;\r\n\t\t\t}\r\n\r\n\t\t\tconstexpr inline auto operator+=(Integral auto rhs) noexcept -> ConstIterator& {\r\n\t\t\t\t*this = std::move(*this + rhs);\r\n\t\t\t\treturn *this;\r\n\t\t\t}\r\n\r\n\t\t\tconstexpr inline auto operator-(Integral auto rhs) const noexcept -> ConstIterator {\r\n\t\t\t\tconst auto diff = static_cast<size_t>(rhs);\r\n\t\t\t\tif(rhs < 0) {\r\n\t\t\t\t\treturn std::move(*this + -rhs);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tauto temp = *this;\r\n\t\t\t\tif(diff > temp.mCurrentIndex) {\r\n\t\t\t\t\ttemp.mPtr = temp.mContainerPtr->begin().mPtr;\r\n\t\t\t\t\ttemp.mCurrentIndex = 0;\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\ttemp.mCurrentIndex -= diff;\r\n\t\t\t\t\ttemp.mPtr = &(*temp.mContainerPtr)[temp.mCurrentIndex];\r\n\t\t\t\t}\r\n\t\t\t\treturn temp;\r\n\t\t\t}\r\n\r\n\t\t\tconstexpr inline auto operator-=(Integral auto rhs) noexcept -> ConstIterator& {\r\n\t\t\t\t*this = std::move(*this - rhs);\r\n\t\t\t\treturn *this;\r\n\t\t\t}\r\n\r\n\t\t\tconstexpr inline auto\r\n\t\t\toperator-(const ConstIterator& rhs) const noexcept -> difference_type {\r\n\t\t\t\treturn mPtr - rhs.mPtr;\r\n\t\t\t}\r\n\r\n\t\t\tconstexpr inline auto operator[](Integral auto index) const noexcept -> ConstIterator {\r\n\t\t\t\treturn std::move(*this + index);\r\n\t\t\t}\r\n\r\n\t\t\tconstexpr inline auto operator>(const ConstIterator& rhs) const noexcept -> bool {\r\n\t\t\t\treturn mCurrentIndex > rhs.mCurrentIndex;\r\n\t\t\t}\r\n\r\n\t\t\tconstexpr inline auto operator<(const ConstIterator& rhs) const noexcept -> bool {\r\n\t\t\t\treturn mCurrentIndex < rhs.mCurrentIndex;\r\n\t\t\t}\r\n\r\n\t\t\tconstexpr inline auto operator>=(const ConstIterator& rhs) const noexcept -> bool {\r\n\t\t\t\treturn mCurrentIndex >= rhs.mCurrentIndex;\r\n\t\t\t}\r\n\r\n\t\t\tconstexpr inline auto operator<=(const ConstIterator& rhs) const noexcept -> bool {\r\n\t\t\t\treturn mCurrentIndex <= rhs.mCurrentIndex;\r\n\t\t\t}\r\n\r\n\t\t  private:\r\n\t\t\tpointer mPtr;\r\n\t\t\tRingBuffer* mContainerPtr = nullptr;\r\n\t\t\tsize_t mCurrentIndex = 0;\r\n\t\t};\r\n\r\n\t\t/// @brief Creates a `RingBuffer` with default capacity\r\n\t\tRingBuffer() noexcept : mBuffer(new T[DEFAULT_CAPACITY_INTERNAL]) {\r\n\t\t}\r\n\r\n\t\t/// @brief Creates a `RingBuffer` with (at least) the given initial capacity\r\n\t\t///\r\n\t\t/// @param initialCapacity - The initial capacity of the `RingBuffer`\r\n\t\tconstexpr explicit RingBuffer(size_t initialCapacity) noexcept\r\n\t\t\t: mBuffer(new T[initialCapacity + 1]), mLoopIndex(initialCapacity),\r\n\t\t\t  mCapacity(initialCapacity) {\r\n\t\t}\r\n\r\n\t\t/// @brief Constructs a new `RingBuffer` with the given initial capacity and\r\n\t\t/// fills it with `defaultValue`\r\n\t\t///\r\n\t\t/// @param initialCapacity - The initial capacity of the `RingBuffer`\r\n\t\t/// @param defaultValue - The value to fill the `RingBuffer` with\r\n\t\tconstexpr RingBuffer(size_t initialCapacity,\r\n\t\t\t\t\t\t\t const T& defaultValue) noexcept requires Copyable<T>\r\n\t\t\t: mBuffer(new T[initialCapacity + 1]),\r\n\t\t\t  mLoopIndex(initialCapacity),\r\n\t\t\t  mCapacity(initialCapacity) {\r\n\t\t\tfor(auto i = 0ULL; i < mCapacity; ++i) {\r\n\t\t\t\tpush_back(defaultValue);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tconstexpr RingBuffer(const RingBuffer& buffer) noexcept requires Copyable<T>\r\n\t\t\t: mBuffer(new T[buffer.mCapacity + 1]),\r\n\t\t\t  mWriteIndex(0ULL), // NOLINT\r\n\t\t\t  mStartIndex(0ULL), // NOLINT\r\n\t\t\t  mLoopIndex(buffer.mLoopIndex),\r\n\t\t\t  mCapacity(buffer.mCapacity) {\r\n\t\t\tfor(auto i = 0ULL; i < mCapacity; ++i) {\r\n\t\t\t\tpush_back(buffer.mBuffer[i]);\r\n\t\t\t}\r\n\t\t\tmStartIndex = buffer.mStartIndex; // NOLINT(cppcoreguidelines-prefer-member-initializer)\r\n\t\t\tmWriteIndex = buffer.mWriteIndex; // NOLINT(cppcoreguidelines-prefer-member-initializer)\r\n\t\t\tmSize = buffer.mSize;\t\t\t  // NOLINT(cppcoreguidelines-prefer-member-initializer)\r\n\t\t}\r\n\r\n\t\tconstexpr RingBuffer(RingBuffer&& buffer) noexcept\r\n\t\t\t: mBuffer(std::move(buffer.mBuffer)), mStartIndex(buffer.mStartIndex),\r\n\t\t\t  mLoopIndex(buffer.mLoopIndex), mCapacity(buffer.mCapacity), mSize(buffer.mSize) {\r\n\t\t\tbuffer.mCapacity = 0ULL;\r\n\t\t\tbuffer.mLoopIndex = 0ULL;\r\n\t\t\tbuffer.mSize = 0ULL;\r\n\t\t\tbuffer.mWriteIndex = 0ULL;\r\n\t\t\tbuffer.mStartIndex = 0ULL;\r\n\t\t\tbuffer.mBuffer = nullptr;\r\n\t\t}\r\n\r\n\t\t~RingBuffer() noexcept = default;\r\n\r\n\t\t/// @brief Returns the element at the given index.\r\n\t\t/// @note This is not checked in the same manner as STL containers:\r\n\t\t/// if index >= capacity, the element at capacity - 1 is returned.\r\n\t\t///\r\n\t\t/// @param index - The index of the desired element\r\n\t\t///\r\n\t\t/// @return The element at the given index, or at capacity - 1 if index >= capacity\r\n\t\t[[nodiscard]] constexpr inline auto at(Integral auto index) noexcept -> T& {\r\n\t\t\tauto i = getAdjustedInternalIndex(index);\r\n\r\n\t\t\tif(i > mLoopIndex) {\r\n\t\t\t\ti = mLoopIndex;\r\n\t\t\t}\r\n\r\n\t\t\treturn mBuffer[i]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\r\n\t\t}\r\n\r\n\t\t/// @brief Returns the first element in the `RingBuffer`\r\n\t\t///\r\n\t\t/// @return The first element\r\n\t\t[[nodiscard]] constexpr inline auto front() noexcept -> T& {\r\n\t\t\treturn mBuffer[mStartIndex]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\r\n\t\t}\r\n\r\n\t\t/// @brief Returns the last element in the `RingBuffer`\r\n\t\t/// @note If <= 1 elements are in the `RingBuffer`, this will be the same as `front`\r\n\t\t///\r\n\t\t/// @return The last element\r\n\t\t[[nodiscard]] constexpr inline auto back() noexcept -> T& {\r\n\t\t\tauto index = mWriteIndex - 1;\r\n\t\t\tif(mWriteIndex == 0) {\r\n\t\t\t\tif(mStartIndex == 0) {\r\n\t\t\t\t\tindex = 0;\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tindex = mLoopIndex;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn mBuffer[index]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\r\n\t\t}\r\n\r\n\t\t/// @brief Returns a pointer to the underlying data in the `RingBuffer`.\r\n\t\t/// @note This is not sorted in any way to match the representation used by the `RingBuffer`\r\n\t\t///\r\n\t\t/// @return A pointer to the underlying data\r\n\t\t[[nodiscard]] constexpr inline auto data() noexcept -> T* {\r\n\t\t\treturn mBuffer;\r\n\t\t}\r\n\r\n\t\t/// @brief Returns whether the `RingBuffer` is empty\r\n\t\t///\r\n\t\t/// @return `true` if the `RingBuffer` is empty, `false` otherwise\r\n\t\t[[nodiscard]] constexpr inline auto empty() noexcept -> bool {\r\n\t\t\treturn mSize == 0;\r\n\t\t}\r\n\r\n\t\t/// @brief Returns the current number of elements in the `RingBuffer`\r\n\t\t///\r\n\t\t/// @return The current number of elements\r\n\t\t[[nodiscard]] constexpr inline auto size() noexcept -> size_t {\r\n\t\t\treturn mSize;\r\n\t\t}\r\n\r\n\t\t/// @brief Returns the maximum possible number of elements this `RingBuffer` could store\r\n\t\t/// if grown to maximum possible capacity\r\n\t\t///\r\n\t\t/// @return The maximum possible number of storable elements\r\n\t\t[[nodiscard]] constexpr inline auto max_size() noexcept -> size_t {\r\n\t\t\treturn std::numeric_limits<size_t>::max();\r\n\t\t}\r\n\r\n\t\t/// @brief Returns the current capacity of the `RingBuffer`;\r\n\t\t/// the number of elements it can currently store\r\n\t\t///\r\n\t\t/// @return The current capacity\r\n\t\t[[nodiscard]] constexpr inline auto capacity() noexcept -> size_t {\r\n\t\t\treturn mCapacity;\r\n\t\t}\r\n\r\n\t\t/// @brief Reserves more storage for the `RingBuffer`. If `newCapacity` is > capacity,\r\n\t\t/// then the capacity of the `RingBuffer` will be extended until at least `newCapacity`\r\n\t\t/// elements can be stored.\r\n\t\t/// @note Memory contiguity is maintained, so no **elements** will be lost or invalidated.\r\n\t\t/// However, all iterators and references to elements will be invalidated.\r\n\t\t///\r\n\t\t/// @param newCapacity - The new capacity of the `RingBuffer`\r\n\t\tconstexpr inline auto reserve(size_t newCapacity) noexcept -> void {\r\n\t\t\t// we only need to do anything if `newCapacity` is actually larger than `mCapacity`\r\n\t\t\tif(newCapacity > mCapacity) {\r\n\t\t\t\tgsl::owner<T*> temp = new T[newCapacity]; // NOLINT\r\n\t\t\t\tauto span = gsl::make_span(temp, newCapacity);\r\n\t\t\t\tstd::copy(begin(), end(), span.begin());\r\n\t\t\t\tmBuffer.reset(temp);\r\n\t\t\t\tmStartIndex = 0;\r\n\t\t\t\tmWriteIndex = mLoopIndex + 1;\r\n\t\t\t\tmLoopIndex = newCapacity;\r\n\t\t\t\tmCapacity = newCapacity;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// @brief Erases all elements from the `RingBuffer`\r\n\t\tconstexpr inline auto clear() noexcept -> void {\r\n\t\t\tmStartIndex = 0;\r\n\t\t\tmWriteIndex = 0;\r\n\t\t\tmSize = 0;\r\n\t\t}\r\n\r\n\t\t/// @brief Inserts the given element at the end of the `RingBuffer`\r\n\t\t/// @note if `size() == capacity()` then this loops and overwrites `front()`\r\n\t\t///\r\n\t\t/// @param value - the element to insert\r\n\t\tconstexpr inline auto push_back(const T& value) noexcept -> void requires Copyable<T> {\r\n\t\t\t// clang-format off\r\n\t\tmBuffer[mWriteIndex] = value; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\r\n\t\t\t// clang-format on\r\n\r\n\t\t\tincrementIndices();\r\n\t\t}\r\n\r\n\t\t/// @brief Inserts the given element at the end of the `RingBuffer`\r\n\t\t/// @note if `size() == capacity()` then this loops and overwrites `front()`\r\n\t\t///\r\n\t\t/// @param value - the element to insert\r\n\t\tconstexpr inline auto push_back(T&& value) noexcept -> void {\r\n\t\t\t// clang-format off\r\n\t\t\tmBuffer[mWriteIndex] = std::forward<T>(value); // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\r\n\t\t\t// clang-format on\r\n\r\n\t\t\tincrementIndices();\r\n\t\t}\r\n\r\n\t\t/// @brief Constructs the given element in place at the end of the `RingBuffer`\r\n\t\t/// @note if `size() == capacity()` then this loops and overwrites `front()`\r\n\t\t///\r\n\t\t/// @tparam Args - The types of the element's constructor arguments\r\n\t\t/// @param args - The constructor arguments for the element\r\n\t\t///\r\n\t\t/// @return A reference to the element constructed at the end of the `RingBuffer`\r\n\t\ttemplate<typename... Args>\r\n\t\trequires ConstructibleFrom<T, Args...>\r\n\t\tconstexpr inline auto emplace_back(Args&&... args) noexcept -> T& requires Movable<T> {\r\n\t\t\t// clang-format off\r\n\t\t\tnew (&mBuffer[mWriteIndex]) T(args...); // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\r\n\t\t\t// clang-format on\r\n\r\n\t\t\tincrementIndices();\r\n\r\n\t\t\tauto index = mWriteIndex == 0 ? mLoopIndex : mWriteIndex - 1;\r\n\t\t\treturn mBuffer[index]; // NOLINT\r\n\t\t}\r\n\r\n\t\t/// @brief Constructs the given element in place at the location\r\n\t\t/// indicated by the `Iterator` `position`\r\n\t\t///\r\n\t\t/// @tparam Args - The types of the element's constructor arguments\r\n\t\t/// @param position - `Iterator` indicating where in the `RingBuffer` to construct the\r\n\t\t/// element\r\n\t\t/// @param args - The constructor arguments for the element\r\n\t\t///\r\n\t\t/// @return A reference to the element constructed at the location indicated by `position`\r\n\t\ttemplate<typename... Args>\r\n\t\trequires ConstructibleFrom<T, Args...>\r\n\t\tconstexpr inline auto emplace(const Iterator& position, Args&&... args) noexcept -> T& {\r\n\t\t\tauto index = getAdjustedInternalIndex(position.getIndex());\r\n\r\n\t\t\t// clang-format off\r\n\t\t\tnew (&mBuffer[index]) T(args...); // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\r\n\t\t\t// clang-format on\r\n\r\n\t\t\treturn mBuffer[index]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\r\n\t\t}\r\n\r\n\t\t/// @brief Constructs the given element in place at the location\r\n\t\t/// indicated by the `ConstIterator` `position`\r\n\t\t///\r\n\t\t/// @tparam Args - The types of the element's constructor arguments\r\n\t\t/// @param position - `ConstIterator` indicating where in the `RingBuffer` to construct the\r\n\t\t/// element\r\n\t\t/// @param args - The constructor arguments for the element\r\n\t\t///\r\n\t\t/// @return A reference to the element constructed at the location indicated by `position`\r\n\t\ttemplate<typename... Args>\r\n\t\tconstexpr inline auto\r\n\t\templace(const ConstIterator& position, Args&&... args) noexcept -> T& {\r\n\t\t\tauto index = getAdjustedInternalIndex(position.getIndex());\r\n\r\n\t\t\t// clang-format off\r\n\t\t\tnew (&mBuffer[index]) T(args...); // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\r\n\t\t\t// clang-format on\r\n\r\n\t\t\treturn mBuffer[index]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\r\n\t\t}\r\n\r\n\t\t/// @brief Assigns the given element to the position indicated\r\n\t\t/// by the `Iterator` `position`\r\n\t\t/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`\r\n\t\t///\r\n\t\t/// @param position - `Iterator` indicating where in the `RingBuffer` to place the element\r\n\t\t/// @param element - The element to store in the `RingBuffer`\r\n\t\tconstexpr inline auto\r\n\t\tinsert(const Iterator& position, const T& element) noexcept -> void requires Copyable<T> {\r\n\t\t\tinsert_internal(position.getIndex(), element);\r\n\t\t}\r\n\r\n\t\t/// @brief Assigns the given element to the position indicated\r\n\t\t/// by the `Iterator` `position`\r\n\t\t/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`\r\n\t\t///\r\n\t\t/// @param position - `Iterator` indicating where in the `RingBuffer` to place the element\r\n\t\t/// @param element - The element to store in the `RingBuffer`\r\n\t\tconstexpr inline auto insert(const Iterator& position, T&& element) noexcept -> void {\r\n\t\t\tinsert_internal(position.getIndex(), std::forward<T>(element));\r\n\t\t}\r\n\r\n\t\t/// @brief Assigns the given element to the position indicated\r\n\t\t/// by the `ConstIterator` `position`\r\n\t\t/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`\r\n\t\t///\r\n\t\t/// @param position - `ConstIterator` indicating where in the `RingBuffer` to place the\r\n\t\t/// element\r\n\t\t/// @param element - The element to store in the `RingBuffer`\r\n\t\tconstexpr inline auto insert(const ConstIterator& position, const T& element) noexcept\r\n\t\t\t-> void requires Copyable<T> {\r\n\t\t\tinsert_internal(position.getIndex(), element);\r\n\t\t}\r\n\r\n\t\t/// @brief Assigns the given element to the position indicated\r\n\t\t/// by the `ConstIterator` `position`\r\n\t\t/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`\r\n\t\t///\r\n\t\t/// @param position - `ConstIterator` indicating where in the `RingBuffer` to place the\r\n\t\t/// element\r\n\t\t/// @param element - The element to store in the `RingBuffer`\r\n\t\tconstexpr inline auto insert(const ConstIterator& position, T&& element) noexcept -> void {\r\n\t\t\tinsert_internal(position.getIndex(), std::forward<T>(element));\r\n\t\t}\r\n\r\n\t\t/// @brief Constructs the given element at the insertion position indicated\r\n\t\t/// by the `ConstIterator` `position`\r\n\t\t/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`\r\n\t\t///\r\n\t\t/// @param position - `ConstIterator` indicating where in the `RingBuffer` to place the\r\n\t\t/// element\r\n\t\t/// @param args - The arguments to the constructor for\r\n\t\t/// the element to store in the `RingBuffer`\r\n\t\ttemplate<typename... Args>\r\n\t\trequires ConstructibleFrom<T, Args...>\r\n\t\tconstexpr inline auto\r\n\t\tinsert_emplace(const Iterator& position, Args&&... args) noexcept -> T& {\r\n\t\t\treturn insert_emplace_internal(position.getIndex(), args...);\r\n\t\t}\r\n\r\n\t\t/// @brief Constructs the given element at the insertion position indicated\r\n\t\t/// by the `ConstIterator` `position`\r\n\t\t/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`\r\n\t\t///\r\n\t\t/// @param position - `ConstIterator` indicating where in the `RingBuffer` to place the\r\n\t\t/// element\r\n\t\t/// @param args - The arguments to the constructor for\r\n\t\t/// the element to store in the `RingBuffer`\r\n\t\ttemplate<typename... Args>\r\n\t\trequires ConstructibleFrom<T, Args...>\r\n\t\tconstexpr inline auto\r\n\t\tinsert_emplace(const ConstIterator& position, Args&&... args) noexcept -> T& {\r\n\t\t\treturn insert_emplace_internal(position.getIndex(), args...);\r\n\t\t}\r\n\r\n\t\t/// @brief Erases the element at the given `position`, moving other elements backward\r\n\t\t/// in the buffer to maintain contiguity\r\n\t\t///\r\n\t\t/// @param position - The element to erase\r\n\t\t///\r\n\t\t/// @return `Iterator` pointing to the element after the one erased\r\n\t\tconstexpr inline auto erase(const Iterator& position) noexcept -> Iterator {\r\n\t\t\treturn erase_internal(position.getIndex());\r\n\t\t}\r\n\r\n\t\t/// @brief Erases the element at the given `position`, moving other elements backward\r\n\t\t/// in the buffer to maintain contiguity\r\n\t\t///\r\n\t\t/// @param position - The element to erase\r\n\t\t///\r\n\t\t/// @return `Iterator` pointing to the element after the one erased\r\n\t\tconstexpr inline auto erase(const ConstIterator& position) noexcept -> Iterator {\r\n\t\t\treturn erase_internal(position.getIndex());\r\n\t\t}\r\n\r\n\t\t/// @brief Erases the range of elements in [`first`, `last`)\r\n\t\t/// Returns an `Iterator` to the element after the last one erased\r\n\t\t/// @note In the case `first` >= `last`, no elements are erased and `last` is returned;\r\n\t\t///\r\n\t\t/// @param first - The first element in the range to erase\r\n\t\t/// @param last - The last element in the range\r\n\t\t///\r\n\t\t/// @return `Iterator` pointing to the element after the last one erased\r\n\t\tconstexpr inline auto\r\n\t\terase(const Iterator& first, const Iterator& last) noexcept -> Iterator {\r\n\t\t\tif(first >= last) {\r\n\t\t\t\treturn last;\r\n\t\t\t}\r\n\r\n\t\t\treturn erase_internal(first.getIndex(), last.getIndex());\r\n\t\t}\r\n\r\n\t\t/// @brief Erases the range of elements in [`first`, `last`)\r\n\t\t/// Returns an `Iterator` to the element after the last one erased\r\n\t\t/// @note In the case `first` >= `last`, no elements are erased and `last` is returned;\r\n\t\t///\r\n\t\t/// @param first - The first element in the range to erase\r\n\t\t/// @param last - The last element in the range\r\n\t\t///\r\n\t\t/// @return `Iterator` pointing to the element after the last one erased\r\n\t\tconstexpr inline auto\r\n\t\terase(const ConstIterator& first, const ConstIterator& last) noexcept -> Iterator {\r\n\t\t\tif(first >= last) {\r\n\t\t\t\treturn last;\r\n\t\t\t}\r\n\r\n\t\t\treturn erase_internal(first.getIndex(), last.getIndex());\r\n\t\t}\r\n\r\n\t\t/// @brief Removes the last element in the `RingBuffer` and returns it\r\n\t\t///\r\n\t\t/// @return The last element in the `RingBuffer`\r\n\t\t[[nodiscard]] constexpr inline auto pop_back() noexcept -> T requires Copyable<T> {\r\n\t\t\tT _back = back();\r\n\t\t\terase(--end());\r\n\t\t\treturn _back;\r\n\t\t}\r\n\r\n\t\t/// @brief Returns a Random Access Bidirectional iterator over the `RingBuffer`,\r\n\t\t/// at the beginning\r\n\t\t///\r\n\t\t/// @return The iterator, at the beginning\r\n\t\t[[nodiscard]] constexpr inline auto begin() -> Iterator {\r\n\t\t\tT* p = &mBuffer[mStartIndex]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\r\n\r\n\t\t\treturn Iterator(p, this, 0ULL);\r\n\t\t}\r\n\r\n\t\t/// @brief Returns a Random Access Bidirectional iterator over the `RingBuffer`,\r\n\t\t/// at the end\r\n\t\t///\r\n\t\t/// @return The iterator, at the end\r\n\t\t[[nodiscard]] constexpr inline auto end() -> Iterator {\r\n\t\t\tT* p = &mBuffer[mWriteIndex]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\r\n\r\n\t\t\treturn Iterator(p, this, mSize);\r\n\t\t}\r\n\r\n\t\t/// @brief Returns a Random Access Bidirectional read-only iterator over the `RingBuffer`,\r\n\t\t/// at the beginning\r\n\t\t///\r\n\t\t/// @return The iterator, at the beginning\r\n\t\t[[nodiscard]] constexpr inline auto cbegin() -> ConstIterator {\r\n\t\t\tT* p = &mBuffer[mStartIndex]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\r\n\r\n\t\t\treturn ConstIterator(p, this, 0ULL);\r\n\t\t}\r\n\r\n\t\t/// @brief Returns a Random Access Bidirectional read-only iterator over the `RingBuffer`,\r\n\t\t/// at the end\r\n\t\t///\r\n\t\t/// @return The iterator, at the end\r\n\t\t[[nodiscard]] constexpr inline auto cend() -> ConstIterator {\r\n\t\t\tT* p = &mBuffer[mWriteIndex]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\r\n\t\t\treturn ConstIterator(p, this, mSize);\r\n\t\t}\r\n\r\n\t\t/// @brief Unchecked access-by-index operator\r\n\t\t///\r\n\t\t/// @param index - The index to get the corresponding element for\r\n\t\t///\r\n\t\t/// @return - The element at index\r\n\t\t[[nodiscard]] constexpr inline auto operator[](Integral auto index) noexcept -> T& {\r\n\t\t\tauto i = getAdjustedInternalIndex(index);\r\n\r\n\t\t\treturn mBuffer[i]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\r\n\t\t}\r\n\r\n\t\tconstexpr auto\r\n\t\toperator=(const RingBuffer& buffer) noexcept -> RingBuffer& requires Copyable<T> {\r\n\t\t\tif(this == &buffer) {\r\n\t\t\t\treturn *this;\r\n\t\t\t}\r\n\t\t\tmBuffer.reset(new T[buffer.mCapacity + 1]); // NOLINT\r\n\t\t\tmStartIndex = 0ULL;\r\n\t\t\tmWriteIndex = 0ULL;\r\n\t\t\tmCapacity = buffer.mCapacity;\r\n\t\t\tfor(auto i = 0ULL; i < mCapacity; ++i) {\r\n\t\t\t\tpush_back(buffer.mBuffer[i]);\r\n\t\t\t}\r\n\t\t\tmStartIndex = buffer.mStartIndex;\r\n\t\t\tmWriteIndex = buffer.mWriteIndex;\r\n\t\t\tmLoopIndex = buffer.mLoopIndex;\r\n\t\t\tmSize = buffer.mSize;\r\n\t\t\treturn *this;\r\n\t\t}\r\n\t\tconstexpr auto operator=(RingBuffer&& buffer) noexcept -> RingBuffer& {\r\n\t\t\tmBuffer = std::move(buffer.mBuffer);\r\n\t\t\tmWriteIndex = buffer.mWriteIndex;\r\n\t\t\tmStartIndex = buffer.mStartIndex;\r\n\t\t\tmLoopIndex = buffer.mLoopIndex;\r\n\t\t\tmCapacity = buffer.mCapacity;\r\n\t\t\tmSize = buffer.mSize;\r\n\t\t\tbuffer.mBuffer = nullptr;\r\n\t\t\tbuffer.mWriteIndex = 0ULL;\r\n\t\t\tbuffer.mStartIndex = 0ULL;\r\n\t\t\tbuffer.mCapacity = 0ULL;\r\n\t\t\tbuffer.mSize = 0ULL;\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t  private:\r\n\t\tstatic const constexpr size_t DEFAULT_CAPACITY_INTERNAL = DEFAULT_CAPACITY + 1;\r\n\t\tstd::unique_ptr<T[]> mBuffer = new T[DEFAULT_CAPACITY_INTERNAL]; // NOLINT\r\n\t\tsize_t mWriteIndex = 0;\r\n\t\tsize_t mStartIndex = 0;\r\n\t\tsize_t mLoopIndex = DEFAULT_CAPACITY;\r\n\t\tsize_t mCapacity = DEFAULT_CAPACITY;\r\n\t\tsize_t mSize = 0;\r\n\r\n\t\t/// @brief Converts the given `RingBuffer` index into the corresponding index into then\r\n\t\t/// underlying `T` array\r\n\t\t///\r\n\t\t/// @param index - The `RingBuffer` index to convert\r\n\t\t///\r\n\t\t/// @return The corresponding index into the underlying `T` array\r\n\t\t[[nodiscard]] constexpr inline auto\r\n\t\tgetAdjustedInternalIndex(Integral auto index) const noexcept -> size_t {\r\n\t\t\tauto i = static_cast<size_t>(index);\r\n\t\t\tif(mStartIndex + i > mLoopIndex) {\r\n\t\t\t\ti = (mStartIndex + i) - (mLoopIndex + 1);\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\ti += mStartIndex;\r\n\t\t\t}\r\n\r\n\t\t\treturn i;\r\n\t\t}\r\n\r\n\t\t/// @brief Converts the given index into the underlying `T` array into\r\n\t\t/// a using facing index into the `RingBuffer`\r\n\t\t///\r\n\t\t/// @param index - The internal index\r\n\t\t///\r\n\t\t/// @return The corresponding user-facing index\r\n\t\t[[nodiscard]] constexpr inline auto\r\n\t\tgetExternalIndexFromInternal(Integral auto index) const noexcept -> size_t {\r\n\t\t\tauto i = static_cast<size_t>(index);\r\n\t\t\tif(i > mStartIndex && i <= mLoopIndex) {\r\n\t\t\t\treturn i - mStartIndex;\r\n\t\t\t}\r\n\t\t\telse if(i < mStartIndex) {\r\n\t\t\t\treturn (mLoopIndex - mStartIndex) + i + 1;\r\n\t\t\t}\r\n\t\t\telse if(i == mStartIndex) {\r\n\t\t\t\treturn 0;\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\treturn mSize;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// @brief Increments the start and write indices into the underlying `T` array,\r\n\t\t/// and the size property, maintaining the logical `RingBuffer` structure\r\n\t\tconstexpr inline auto incrementIndices() noexcept -> void {\r\n\t\t\tmWriteIndex++;\r\n\t\t\tmSize = math::General::min(mSize + 1, mCapacity);\r\n\r\n\t\t\t// if write index is at start - 1, we need to push start forward to maintain\r\n\t\t\t// the \"invalid\" spacer element for this.end()\r\n\t\t\tif(mWriteIndex > mLoopIndex && mStartIndex == 0) {\r\n\t\t\t\tmWriteIndex = 0;\r\n\t\t\t\tmStartIndex = 1;\r\n\t\t\t}\r\n\t\t\telse if(mWriteIndex == mStartIndex) {\r\n\t\t\t\tmStartIndex++;\r\n\t\t\t\tif(mStartIndex > mLoopIndex) {\r\n\t\t\t\t\tmStartIndex = 0;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// @brief Inserts the given element at the position indicated\r\n\t\t/// by the `externalIndex`\r\n\t\t/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`\r\n\t\t///\r\n\t\t/// @param externalIndex - The user-facing index into the `RingBuffer` to insert the element\r\n\t\t/// at\r\n\t\t/// @param elem - The element to store in the `RingBuffer`\r\n\t\tconstexpr inline auto\r\n\t\tinsert_internal(size_t externalIndex, const T& elem) noexcept -> void requires Movable<T> {\r\n\t\t\tconst auto index = getAdjustedInternalIndex(externalIndex);\r\n\r\n\t\t\tif(index == mWriteIndex) {\r\n\t\t\t\templace_back(elem);\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tauto numToMove = mSize - externalIndex;\r\n\t\t\t\tauto iter = begin() + externalIndex;\r\n\t\t\t\tif(mSize == mCapacity) [[likely]] { // NOLINT\r\n\t\t\t\t\tfor(size_t i = 1ULL, j = numToMove - 2; i < numToMove; ++i, --j) {\r\n\t\t\t\t\t\t*((end() - i) + 1) = std::move(*(iter + j));\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tfor(size_t i = 0ULL, j = numToMove - 1; i < numToMove; ++i, --j) {\r\n\t\t\t\t\t\t*(end() - i) = std::move(*(iter + j));\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tincrementIndices();\r\n\t\t\t\tif(externalIndex == 0) {\r\n\t\t\t\t\t// clang-format off\r\n\t\t\t\t\tmBuffer[mStartIndex] = elem; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\r\n\t\t\t\t\t// clang-format on\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\t// clang-format off\r\n\t\t\t\t\tmBuffer[index] = elem; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\r\n\t\t\t\t\t// clang-format on\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// @brief Inserts the given element at the position indicated\r\n\t\t/// by the `externalIndex`\r\n\t\t/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`\r\n\t\t///\r\n\t\t/// @param externalIndex - The user-facing index into the `RingBuffer` to insert the element\r\n\t\t/// at\r\n\t\t/// @param elem - The element to store in the `RingBuffer`\r\n\t\tconstexpr inline auto insert_internal(size_t externalIndex, const T& elem) noexcept\r\n\t\t\t-> void requires NotMovable<T> {\r\n\t\t\tconst auto index = getAdjustedInternalIndex(externalIndex);\r\n\r\n\t\t\tif(index == mWriteIndex) {\r\n\t\t\t\templace_back(elem);\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tauto numToMove = mSize - externalIndex;\r\n\t\t\t\tauto iter = begin() + externalIndex;\r\n\t\t\t\tif(mSize == mCapacity) [[likely]] { // NOLINT\r\n\t\t\t\t\tfor(size_t i = 1ULL, j = numToMove - 2; i < numToMove; ++i, --j) {\r\n\t\t\t\t\t\t*((end() - i) + 1) = *(iter + j);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tfor(size_t i = 0ULL, j = numToMove - 1; i < numToMove; ++i, --j) {\r\n\t\t\t\t\t\t*(end() - i) = *(iter + j);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tincrementIndices();\r\n\t\t\t\tif(externalIndex == 0) {\r\n\t\t\t\t\t// clang-format off\r\n\t\t\t\t\tmBuffer[mStartIndex] = elem; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\r\n\t\t\t\t\t// clang-format on\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\t// clang-format off\r\n\t\t\t\t\tmBuffer[index] = elem; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\r\n\t\t\t\t\t// clang-format on\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// @brief Inserts the given element at the position indicated\r\n\t\t/// by the `externalIndex`\r\n\t\t/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`\r\n\t\t///\r\n\t\t/// @param externalIndex - The user-facing index into the `RingBuffer` to insert the element\r\n\t\t/// at\r\n\t\t/// @param elem - The element to store in the `RingBuffer`\r\n\t\tconstexpr inline auto\r\n\t\tinsert_internal(size_t externalIndex, T&& elem) noexcept -> void requires Movable<T> {\r\n\t\t\tconst auto index = getAdjustedInternalIndex(externalIndex);\r\n\r\n\t\t\tif(index == mWriteIndex) {\r\n\t\t\t\templace_back(elem);\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tauto numToMove = mSize - externalIndex;\r\n\t\t\t\tauto iter = begin() + externalIndex;\r\n\t\t\t\tif(mSize == mCapacity) [[likely]] { // NOLINT\r\n\t\t\t\t\tfor(size_t i = 1ULL, j = numToMove - 2; i < numToMove; ++i, --j) {\r\n\t\t\t\t\t\t*((end() - i) + 1) = std::move(*(iter + j));\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tfor(size_t i = 0ULL, j = numToMove - 1; i < numToMove; ++i, --j) {\r\n\t\t\t\t\t\t*(end() - i) = std::move(*(iter + j));\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tincrementIndices();\r\n\t\t\t\tif(externalIndex == 0) {\r\n\t\t\t\t\t// clang-format off\r\n\t\t\t\t\tmBuffer[mStartIndex] = std::move(elem); // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\r\n\t\t\t\t\t// clang-format on\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\t// clang-format off\r\n\t\t\t\t\tmBuffer[index] = std::move(elem); // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\r\n\t\t\t\t\t// clang-format on\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// @brief Inserts the given element at the position indicated\r\n\t\t/// by the `externalIndex`\r\n\t\t/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`\r\n\t\t///\r\n\t\t/// @param externalIndex - The user-facing index into the `RingBuffer` to insert the element\r\n\t\t/// at\r\n\t\t/// @param elem - The element to store in the `RingBuffer`\r\n\t\tconstexpr inline auto\r\n\t\tinsert_internal(size_t externalIndex, T&& elem) noexcept -> void requires NotMovable<T> {\r\n\t\t\tconst auto index = getAdjustedInternalIndex(externalIndex);\r\n\r\n\t\t\tif(index == mWriteIndex) {\r\n\t\t\t\templace_back(elem);\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tauto numToMove = mSize - externalIndex;\r\n\t\t\t\tauto iter = begin() + externalIndex;\r\n\t\t\t\tif(mSize == mCapacity) [[likely]] { // NOLINT\r\n\t\t\t\t\tfor(size_t i = 1ULL, j = numToMove - 2; i < numToMove; ++i, --j) {\r\n\t\t\t\t\t\t*((end() - i) + 1) = *(iter + j);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tfor(size_t i = 0ULL, j = numToMove - 1; i < numToMove; ++i, --j) {\r\n\t\t\t\t\t\t*(end() - i) = *(iter + j);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tincrementIndices();\r\n\t\t\t\tif(externalIndex == 0) {\r\n\t\t\t\t\t// clang-format off\r\n\t\t\t\t\tmBuffer[mStartIndex] = elem; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\r\n\t\t\t\t\t// clang-format on\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\t// clang-format off\r\n\t\t\t\t\tmBuffer[index] = elem; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\r\n\t\t\t\t\t// clang-format on\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// @brief Constructs the given element at the insertion position indicated\r\n\t\t/// by the `externalIndex`\r\n\t\t/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`\r\n\t\t///\r\n\t\t/// @param externalIndex - The user-facing index into the `RingBuffer` to insert the element\r\n\t\t/// at\r\n\t\t/// @param args - The arguments to the constructor for\r\n\t\t/// the element to store in the `RingBuffer`\r\n\t\ttemplate<typename... Args>\r\n\t\trequires ConstructibleFrom<T, Args...>\r\n\t\tconstexpr inline auto insert_emplace_internal(size_t externalIndex, Args&&... args) noexcept\r\n\t\t\t-> T& requires Movable<T> {\r\n\t\t\tconst auto index = getAdjustedInternalIndex(externalIndex);\r\n\r\n\t\t\tif(index == mWriteIndex) {\r\n\t\t\t\treturn emplace_back(args...);\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tauto numToMove = mSize - externalIndex;\r\n\t\t\t\tauto iter = begin() + externalIndex;\r\n\t\t\t\tif(mSize == mCapacity) [[likely]] { // NOLINT\r\n\t\t\t\t\tfor(size_t i = 1ULL, j = numToMove - 2; i < numToMove; ++i, --j) {\r\n\t\t\t\t\t\t*((end() - i) + 1) = std::move(*(iter + j));\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tfor(size_t i = 0ULL, j = numToMove - 1; i < numToMove; ++i, --j) {\r\n\t\t\t\t\t\t*(end() - i) = std::move(*(iter + j));\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tincrementIndices();\r\n\t\t\t\tif(externalIndex == 0) {\r\n\t\t\t\t\t// clang-format off\r\n\t\t\t\t\tnew (&mBuffer[mStartIndex]) T(args...); // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\r\n\t\t\t\t\treturn mBuffer[mStartIndex];// NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\r\n\t\t\t\t\t// clang-format on\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\t// clang-format off\r\n\t\t\t\t\tnew(&mBuffer[index]) T(args...); // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\r\n\t\t\t\t\treturn mBuffer[index];// NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\r\n\t\t\t\t\t// clang-format on\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// @brief Constructs the given element at the insertion position indicated\r\n\t\t/// by the `externalIndex`\r\n\t\t/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`\r\n\t\t///\r\n\t\t/// @param externalIndex - The user-facing index into the `RingBuffer` to insert the element\r\n\t\t/// at\r\n\t\t/// @param args - The arguments to the constructor for\r\n\t\t/// the element to store in the `RingBuffer`\r\n\t\ttemplate<typename... Args>\r\n\t\trequires ConstructibleFrom<T, Args...>\r\n\t\tconstexpr inline auto insert_emplace_internal(size_t externalIndex, Args&&... args) noexcept\r\n\t\t\t-> T& requires NotMovable<T> {\r\n\t\t\tconst auto index = getAdjustedInternalIndex(externalIndex);\r\n\r\n\t\t\tif(index == mWriteIndex) {\r\n\t\t\t\treturn emplace_back(args...);\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tauto numToMove = mSize - externalIndex;\r\n\t\t\t\tauto iter = begin() + externalIndex;\r\n\t\t\t\tif(mSize == mCapacity) [[likely]] { // NOLINT\r\n\t\t\t\t\tfor(size_t i = 1ULL, j = numToMove - 2; i < numToMove; ++i, --j) {\r\n\t\t\t\t\t\t*((end() - i) + 1) = *(iter + j);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tfor(size_t i = 0ULL, j = numToMove - 1; i < numToMove; ++i, --j) {\r\n\t\t\t\t\t\t*(end() - i) = *(iter + j);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tincrementIndices();\r\n\t\t\t\tif(externalIndex == 0) {\r\n\t\t\t\t\t// clang-format off\r\n\t\t\t\t\tnew (&mBuffer[mStartIndex]) T(args...); // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\r\n\t\t\t\t\treturn mBuffer[mStartIndex];// NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\r\n\t\t\t\t\t// clang-format on\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\t// clang-format off\r\n\t\t\t\t\tnew(&mBuffer[index]) T(args...); // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\r\n\t\t\t\t\treturn mBuffer[index];// NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\r\n\t\t\t\t\t// clang-format on\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// @brief Erases the element at the given index, returning an `Iterator` to the element\r\n\t\t/// after the removed one\r\n\t\t///\r\n\t\t/// @param index - The index to the element to remove. This should be a `RingBuffer` index:\r\n\t\t/// IE, not an interal one into the `T` array\r\n\t\t///\r\n\t\t/// @return `Iterator` pointing to the element after the one removed\r\n\t\t[[nodiscard]] constexpr inline auto erase_internal(size_t index) noexcept -> Iterator {\r\n\t\t\tauto indexInternal = getAdjustedInternalIndex(index);\r\n\t\t\tif(indexInternal == mWriteIndex) [[unlikely]] { // NOLINT\r\n\t\t\t\treturn end();\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tauto numToMove = (mSize - 1) - index;\r\n\t\t\t\tmWriteIndex = indexInternal;\r\n\t\t\t\tmSize -= numToMove + 1;\r\n\t\t\t\tauto posToMove = index + 1;\r\n\t\t\t\tfor(auto i = 0ULL; i < numToMove; ++i) {\r\n\t\t\t\t\t// clang-format off\r\n\t\t\t\t\templace_back(mBuffer[getAdjustedInternalIndex(posToMove + i)]); // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\r\n\t\t\t\t\t// clang-format on\r\n\t\t\t\t}\r\n\r\n\t\t\t\tauto iter = begin() + getExternalIndexFromInternal(mWriteIndex);\r\n\t\t\t\treturn iter;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// @brief Erases the range of elements in [`first`, `last`)\r\n\t\t/// Returns an `Iterator` to the element after the last one erased\r\n\t\t///\r\n\t\t/// @param first - The first index in the range to erase. This should be a `RingBuffer`\r\n\t\t/// index: IE, not an internal one into the `T` array\r\n\t\t/// @param last - The last index` in the range to erase. This should be a `RingBuffer`\r\n\t\t/// index: IE, not an internal one into the `T` array\r\n\t\t///\r\n\t\t/// @return `Iterator` pointing to the element after the last one erased\r\n\t\t[[nodiscard]] constexpr inline auto\r\n\t\terase_internal(size_t first, size_t last) noexcept -> Iterator {\r\n\t\t\tauto firstInternal = getAdjustedInternalIndex(first);\r\n\t\t\tauto lastInternal = getAdjustedInternalIndex(last);\r\n\t\t\tif(lastInternal == mWriteIndex) {\r\n\t\t\t\tif(mWriteIndex == mLoopIndex) {\r\n\t\t\t\t\tmStartIndex--;\r\n\t\t\t\t\tmWriteIndex -= last - first;\r\n\t\t\t\t}\r\n\t\t\t\telse if(mWriteIndex < mStartIndex) {\r\n\t\t\t\t\tauto numToRemove = (last - first);\r\n\t\t\t\t\tauto numBeforeZero = numToRemove - mWriteIndex;\r\n\t\t\t\t\tauto numAfterZero = numToRemove - numBeforeZero;\r\n\t\t\t\t\tmStartIndex -= numBeforeZero;\r\n\t\t\t\t\tif(numAfterZero > 0) {\r\n\t\t\t\t\t\tmWriteIndex = mLoopIndex;\r\n\t\t\t\t\t\tnumAfterZero--;\r\n\t\t\t\t\t\tmWriteIndex -= numAfterZero;\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse {\r\n\t\t\t\t\t\tmWriteIndex -= numBeforeZero;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse if(mWriteIndex > mStartIndex) {\r\n\t\t\t\t\tauto numToRemove = (last - first);\r\n\t\t\t\t\tmWriteIndex -= numToRemove;\r\n\t\t\t\t}\r\n\t\t\t\tmSize -= last - first;\r\n\t\t\t\treturn end();\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tauto numToMove = mSize - last;\r\n\t\t\t\tmWriteIndex = firstInternal;\r\n\t\t\t\tmSize -= numToMove + (last - first);\r\n\t\t\t\tauto posToMove = last;\r\n\t\t\t\tfor(auto i = 0ULL; i < numToMove; ++i) {\r\n\t\t\t\t\t// clang-format off\r\n\t\t\t\t\templace_back(mBuffer[getAdjustedInternalIndex(posToMove + i)]); // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\r\n\t\t\t\t\t// clang-format on\r\n\t\t\t\t}\r\n\r\n\t\t\t\tauto iter = begin() + first;\r\n\t\t\t\treturn iter;\r\n\t\t\t}\r\n\t\t}\r\n\t};\r\n\r\n} // namespace utils\r\n", "meta": {"hexsha": "560a2808bb6e3d23458e2c7d3d7fc3059b13d041", "size": 44013, "ext": "h", "lang": "C", "max_stars_repo_path": "src/utils/RingBuffer.h", "max_stars_repo_name": "braxtons12/ray_tracer", "max_stars_repo_head_hexsha": "274cadb7db4d434b5143503109d6cf58986fac9b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils/RingBuffer.h", "max_issues_repo_name": "braxtons12/ray_tracer", "max_issues_repo_head_hexsha": "274cadb7db4d434b5143503109d6cf58986fac9b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils/RingBuffer.h", "max_forks_repo_name": "braxtons12/ray_tracer", "max_forks_repo_head_hexsha": "274cadb7db4d434b5143503109d6cf58986fac9b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.6380566802, "max_line_length": 128, "alphanum_fraction": 0.6466952946, "num_tokens": 11488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2200070792891058, "lm_q2_score": 0.033085977316112354, "lm_q1q2_score": 0.007279149234743486}}
{"text": "/* $Id$  */\n/*--------------------------------------------------------------------*/\n/*;  Copyright (C) 2003-2009                                          */\n/*;  Associated Universities, Inc. Washington DC, USA.                */\n/*;                                                                   */\n/*;  This program is free software; you can redistribute it and/or    */\n/*;  modify it under the terms of the GNU General Public License as   */\n/*;  published by the Free Software Foundation; either version 2 of   */\n/*;  the License, or (at your option) any later version.              */\n/*;                                                                   */\n/*;  This program is distributed in the hope that it will be useful,  */\n/*;  but WITHOUT ANY WARRANTY; without even the implied warranty of   */\n/*;  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the    */\n/*;  GNU General Public License for more details.                     */\n/*;                                                                   */\n/*;  You should have received a copy of the GNU General Public        */\n/*;  License along with this program; if not, write to the Free       */\n/*;  Software Foundation, Inc., 675 Massachusetts Ave, Cambridge,     */\n/*;  MA 02139, USA.                                                   */\n/*;                                                                   */\n/*;Correspondence about this software should be addressed as follows: */\n/*;         Internet email: bcotton@nrao.edu.                         */\n/*;         Postal address: William Cotton                            */\n/*;                         National Radio Astronomy Observatory      */\n/*;                         520 Edgemont Road                         */\n/*;                         Charlottesville, VA 22903-2475 USA        */\n/*--------------------------------------------------------------------*/\n\n#include <time.h>\n#include <gsl/gsl_randist.h>\n#include \"ObitThread.h\"\n#include \"ObitOTFUtil.h\"\n#include \"ObitOTFGetSoln.h\"\n#include \"ObitTableOTFIndex.h\"\n#include \"ObitTableOTFTargetUtil.h\"\n#include \"ObitImageUtil.h\"\n\n/*----------------Obit: Merx mollis mortibus nuper ------------------*/\n/**\n * \\file ObitOTFUtil.c\n * ObitOTF class utility function definitions.\n */\n\n/*---------------Private structures----------------*/\n/* SubImage threaded function argument */\ntypedef struct {\n  /* OTF data set to model and subtract from current buffer */\n  ObitOTF       *otfdata;\n  /* First (1-rel) record in otfdata buffer to process this thread */\n  olong        first;\n  /* Highest (1-rel) record in otfdata buffer to process this thread  */\n  olong        last;\n  /* thread number, <0 -> no threading  */\n  olong        ithread;\n  /* Obit error stack object */\n  ObitErr      *err;\n  /* Image Interpolator */\n  ObitFInterpolate *Interp;\n  /* Scaling factor for model */\n  ofloat factor;\n  /* Work arrays the size of ndetect */\n  ofloat *xpos, *ypos;\n} SubImageFuncArg;\n\n/*---------------Private function prototypes----------------*/\n/** Private: Subtract an image interpolator from a buffer of data. */\nvoid ObitOTFUtilSubImageBuff (ObitOTF *in, ObitFInterpolate *image, ofloat factor, \n\t\t\t      olong nThread, SubImageFuncArg **args, ObitErr *err);\n\n/** Private: Convert an ObitOTFDesc to an ObitImageDesc */\nstatic void \nObitOTFUtilOTF2ImageDesc(ObitOTFDesc *OTFDesc, ObitImageDesc *imageDesc, \n\t\t\t gchar *Proj);\n\n/** Private: Get Date string for current date */\nstatic void ObitOTFUtilCurDate (gchar *date, olong len);\n\n/** Private: Threaded OTFUtilSubImageBuff */\nstatic gpointer ThreadOTFUtilSubImageBuff (gpointer arg);\n\n/** Private: Make arguments for Threaded OTFUtilSubImageBuff */\nstatic olong MakeOTFUtilSubImageArgs (ObitOTF *in, ObitErr *err, \n\t\t\t\t      SubImageFuncArg ***args);\n\n/** Private: Delete arguments for Threaded OTFUtilSubImageBuff */\nstatic void KillOTFUtilSubImageArgs (olong nargs, SubImageFuncArg **args);\n\n#define MAXSAMPLE 10000   /* Maximum number of samples in a scan */\n\n/*----------------------Public functions---------------------------*/\n/**\n * Subtract a 2D ObitFArray from an OTF\n * \\param inOTF  Input OTF \n * \\param outOTF Output OTF, must already be defined\n * \\param image  Image plane to subtract\n * \\param desc   Image descriptor for image\n * \\param err    Error stack\n */\nvoid ObitOTFUtilSubImage(ObitOTF *inOTF, ObitOTF *outOTF, ObitFArray *image, \n\t\t\t ObitImageDesc *desc, ObitErr *err) \n{\n  ObitFInterpolate *imageInt=NULL;\n  ObitIOCode retCode;\n  gboolean doCalSelect, done, same, doScale;\n  olong firstRec;\n  ObitInfoType type;\n  ObitIOAccess access;\n  gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};\n  ofloat scale = 1.0;\n  olong NPIO, nThreads=1;\n  SubImageFuncArg **targs=NULL;\n  /* Don't copy Cal and Soln or data or flag tables */\n  gchar *exclude[]={\"OTFSoln\", \"OTFCal\", \"OTFScanData\", \"OTFFlag\", NULL};\n  gchar *routine = \"ObitOTFUtilSubImage\";\n\n    /* error checks */\n  g_assert (ObitErrIsA(err));\n  if (err->error) return;\n  g_assert (ObitFArrayIsA(image));\n  g_assert (ObitImageDescIsA(desc));\n  g_assert (ObitOTFIsA(inOTF));\n  g_assert (ObitOTFIsA(outOTF));\n\n  /* An interpolator for the image */\n  imageInt = newObitFInterpolateCreate (image->name, image, desc, 2);\n\n  /* are input and utput the same? */\n  same = ObitOTFSame (inOTF, outOTF, err);\n  \n  /* Calibration wanted? */ \n  doCalSelect = FALSE;\n  ObitInfoListGetTest(inOTF->info, \"doCalSelect\", &type, (gint32*)dim, \n\t\t      &doCalSelect);\n  if (doCalSelect) access = OBIT_IO_ReadCal;\n  else access = OBIT_IO_ReadWrite;\n\n  /* Make sure NPIO the same */\n  NPIO = 1000;\n  dim[0] = 1;\n  ObitInfoListGetTest (inOTF->info, \"nRecPIO\", &type, dim,  &NPIO);\n  ObitInfoListAlwaysPut (inOTF->info, \"nRecPIO\", OBIT_long, dim,  &NPIO);\n  ObitInfoListAlwaysPut (outOTF->info, \"nRecPIO\", OBIT_long, dim,  &NPIO);\n\n /* Open Input Data */\n  retCode = ObitOTFOpen (inOTF, access, err);\n  if ((retCode != OBIT_IO_OK) || (err->error>0)) goto cleanup;\n\n  if (!same) {\n  /* use same data buffer on input and output \n     so don't assign buffer for output */\n    if (outOTF->buffer) ObitIOFreeBuffer(outOTF->buffer); /* free existing */\n    outOTF->buffer     = inOTF->buffer;\n    outOTF->bufferSize = inOTF->bufferSize;\n\n   /* Open Output Data */\n    retCode = ObitOTFOpen (outOTF, OBIT_IO_WriteOnly, err) ;\n    if ((retCode != OBIT_IO_OK) || (err->error>0)) goto cleanup;\n  }\n\n  /* Copy tables before data if they are different */\n  if (!same) {\n    retCode = ObitOTFCopyTables (inOTF, outOTF, exclude, NULL, err);\n    if (err->error) goto cleanup;\n  }\n\n  /* Close and reopen input to init calibration which will have \n     been disturbed by the table copy */\n  retCode = ObitOTFClose (inOTF, err);\n  if (err->error) goto cleanup;\n\n  retCode = ObitOTFOpen (inOTF, access, err);\n  if ((retCode != OBIT_IO_OK) || (err->error>0)) goto cleanup;\n\n  /* Scaling if needed to convert from image brightness to data \n     square of ratio of beam areas */\n  doScale = TRUE;\n  ObitInfoListGetTest(inOTF->info, \"doScale\", &type, dim, &doScale);\n  if (doScale) {\n    scale = inOTF->myDesc->beamSize / desc->beamMaj;\n    scale = scale * scale;\n  } else {\n    scale = 1.0;\n  }\n  /*fprintf (stderr,\"Scaling image to data by %f\\n\",scale); *//*debug */\n\n  /* Setup Threading */\n  nThreads = MakeOTFUtilSubImageArgs (inOTF, err, &targs);\n\n  /* Loop over data */\n  done = (retCode != OBIT_IO_OK);\n  while (!done) {\n\n    /* read buffer */#\n    retCode = ObitOTFRead (inOTF, NULL, err);\n    if (err->error) goto cleanup;\n    done = (retCode == OBIT_IO_EOF); /* done? */\n    if (done) break;\n    firstRec = inOTF->myDesc->firstRec;\n\n     /* How many? */\n     outOTF->myDesc->numRecBuff = inOTF->myDesc->numRecBuff;\n\n     if (outOTF->myDesc->numRecBuff>0) {\n       /* Subtract image from this buffer */\n       ObitOTFUtilSubImageBuff (outOTF, imageInt, scale, nThreads, targs, err);\n       \n       /* Write buffer */\n       retCode = ObitOTFWrite (outOTF, NULL, err);\n     }\n     if (err->error) goto cleanup;\n\n     /* suppress vis number update if rewriting the same file */\n     if (same) {\n       outOTF->myDesc->firstRec = firstRec;\n       ((ObitOTFDesc*)(outOTF->myIO->myDesc))->firstRec = firstRec;\n     }\n\n  } /* end scan loop */\n  \n cleanup:\n  /* unset output buffer (may be multiply deallocated ;'{ ) */\n  if (!same) {\n    outOTF->buffer = NULL;\n    outOTF->bufferSize = 0;\n    retCode = ObitOTFClose (outOTF, err); /* Close output */\n  } \n\n  /* Close input */\n  retCode = ObitOTFClose (inOTF, err);\n\n  /* cleanup */\n  imageInt = ObitFInterpolateUnref(imageInt);\n  if (err->error) Obit_traceback_msg (err, routine, inOTF->name);\n  /* Shutdown Threading */\n  KillOTFUtilSubImageArgs (nThreads, targs);\n\n} /* end ObitOTFUtilSubImage */\n\n/**\n * Replace the data in an OTF with the model values from FArray image\n * \\param inOTF  Input OTF \n * \\param outOTF Output OTF, must already be defined\n * \\param image  Image plane to subtract\n * \\param desc   Image descriptor for image\n * \\param err    Error stack\n */\nvoid ObitOTFUtilModelImage(ObitOTF *inOTF, ObitOTF *outOTF, ObitFArray *image, \n\t\t\t   ObitImageDesc *desc, ObitErr *err) \n{\n  ObitFInterpolate *imageInt=NULL;\n  ObitIOCode retCode;\n  gboolean doCalSelect, done, same, doScale;\n  olong firstRec;\n  ObitInfoType type;\n  ObitIOAccess access;\n  gint32 dim[MAXINFOELEMDIM];\n  ofloat scale = 1.0;\n  olong NPIO;\n  /* Don't copy Cal and Soln or data or flag tables */\n  gchar *exclude[]={\"OTFSoln\", \"OTFCal\", \"OTFScanData\", \"OTFFlag\", NULL};\n  gchar *routine = \"ObitOTFUtilModelImage\";\n\n    /* error checks */\n  g_assert (ObitErrIsA(err));\n  if (err->error) return;\n  g_assert (ObitFArrayIsA(image));\n  g_assert (ObitImageDescIsA(desc));\n  g_assert (ObitOTFIsA(inOTF));\n  g_assert (ObitOTFIsA(outOTF));\n\n  /* An interpolator for the image */\n  imageInt = newObitFInterpolateCreate (image->name, image, desc, 2);\n\n  /* are input and utput the same? */\n  same = ObitOTFSame (inOTF, outOTF, err);\n  \n  /* Calibration wanted? */ \n  doCalSelect = FALSE;\n  ObitInfoListGetTest(inOTF->info, \"doCalSelect\", &type, dim, &doCalSelect);\n  if (doCalSelect) access = OBIT_IO_ReadCal;\n  else access = OBIT_IO_ReadWrite;\n\n  /* Make sure NPIO the same */\n  NPIO = 1000;\n  dim[0] = 1;\n  ObitInfoListGetTest (inOTF->info, \"nRecPIO\", &type, dim,  &NPIO);\n  ObitInfoListAlwaysPut (inOTF->info, \"nRecPIO\", OBIT_long, dim,  &NPIO);\n  ObitInfoListAlwaysPut (outOTF->info, \"nRecPIO\", OBIT_long, dim,  &NPIO);\n\n /* Open Input Data */\n  retCode = ObitOTFOpen (inOTF, access, err);\n  if ((retCode != OBIT_IO_OK) || (err->error>0)) goto cleanup;\n\n  if (!same) {\n  /* use same data buffer on input and output \n     so don't assign buffer for output */\n    if (outOTF->buffer) ObitIOFreeBuffer(outOTF->buffer); /* free existing */\n    outOTF->buffer     = inOTF->buffer;\n    outOTF->bufferSize = inOTF->bufferSize;\n\n   /* Open Output Data */\n    retCode = ObitOTFOpen (outOTF, OBIT_IO_WriteOnly, err) ;\n    if ((retCode != OBIT_IO_OK) || (err->error>0)) goto cleanup;\n  }\n\n  /* Copy tables before data if they are different */\n  if (!same) {\n    retCode = ObitOTFCopyTables (inOTF, outOTF, exclude, NULL, err);\n    if (err->error) goto cleanup;\n  }\n\n  /* Close and reopen input to init calibration which will have \n     been disturbed by the table copy */\n  retCode = ObitOTFClose (inOTF, err);\n  if (err->error) goto cleanup;\n\n  retCode = ObitOTFOpen (inOTF, access, err);\n  if ((retCode != OBIT_IO_OK) || (err->error>0)) goto cleanup;\n\n  /* Scaling if needed to convert from image brightness to data \n     square of ratio of beam areas */\n  doScale = TRUE;\n  ObitInfoListGetTest(inOTF->info, \"doScale\", &type, dim, &doScale);\n  if (doScale) {\n    scale = inOTF->myDesc->beamSize / desc->beamMaj;\n    scale = scale * scale;\n  }\n  /*fprintf (stderr,\"Scaling image to data by %f\\n\",scale); *//*debug */\n\n  /* Loop over data */\n  done = (retCode != OBIT_IO_OK);\n  while (!done) {\n\n    /* read buffer */#\n    retCode = ObitOTFRead (inOTF, NULL, err);\n    if (err->error) goto cleanup;\n    done = (retCode == OBIT_IO_EOF); /* done? */\n    if (done) break;\n    firstRec = inOTF->myDesc->firstRec;\n\n     /* How many? */\n     outOTF->myDesc->numRecBuff = inOTF->myDesc->numRecBuff;\n\n     if (outOTF->myDesc->numRecBuff>0) {\n       /* Replace data with model in this buffer */\n       ObitOTFUtilModelImageBuff (outOTF, imageInt, scale, err);\n       \n       /* Write buffer */\n       retCode = ObitOTFWrite (outOTF, NULL, err);\n     }\n     if (err->error) goto cleanup;\n\n     /* suppress vis number update if rewriting the same file */\n     if (same) {\n       outOTF->myDesc->firstRec = firstRec;\n       ((ObitOTFDesc*)(outOTF->myIO->myDesc))->firstRec = firstRec;\n     }\n\n  } /* end scan loop */\n  \n cleanup:\n  /* unset output buffer (may be multiply deallocated ;'{ ) */\n  if (!same) {\n    outOTF->buffer = NULL;\n    outOTF->bufferSize = 0;\n    retCode = ObitOTFClose (outOTF, err); /* Close output */\n  } \n\n  /* Close input */\n  retCode = ObitOTFClose (inOTF, err);\n\n  /* cleanup */\n  imageInt = ObitFInterpolateUnref(imageInt);\n  if (err->error) Obit_traceback_msg (err, routine, inOTF->name);\n\n} /* end ObitOTFUtilModelImage */\n\n/**\n * Multiply all data in an OTF by a scale factor and add an offset\n * out = in*scale + offset\n * \\param inOTF  Input OTF \n * \\param outOTF Output OTF, must already be defined\n * \\param scale  scaling factor for data\n * \\param offset additive term to be applied to all data.\n * \\param err    Error stack\n */\nvoid ObitOTFUtilScale(ObitOTF *inOTF, ObitOTF *outOTF, ofloat scale, ofloat offset,\n\t\t      ObitErr *err)\n{\n  ObitIOCode retCode;\n  gboolean doCalSelect, done;\n  ObitInfoType type;\n  ObitIOAccess access;\n  gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};\n  ofloat *data, fblank = ObitMagicF();\n  olong i, j, ndetect, ndata;\n  olong incdatawt;\n  ObitOTFDesc* desc;\n /* Don't copy Cal and Soln or data or flag tables */\n  gchar *exclude[]={\"OTFSoln\", \"OTFCal\", \"OTFScanData\", \"OTFFlag\", NULL};\n  gchar *routine = \"ObitOTFUtilScale\";\n\n  /* error checks */\n  g_assert (ObitErrIsA(err));\n  if (err->error) return;\n  g_assert (ObitOTFIsA(inOTF));\n  g_assert (ObitOTFIsA(outOTF));\n\n  /* Local pointers */\n  desc = inOTF->myDesc;\n  incdatawt = desc->incdatawt; /* increment in data-wt axis */\n\n  /* Calibration wanted? */ \n  doCalSelect = FALSE;\n  ObitInfoListGetTest(inOTF->info, \"doCalSelect\", &type, (gint32*)dim, &doCalSelect);\n  if (doCalSelect) access = OBIT_IO_ReadCal;\n  else access = OBIT_IO_ReadWrite;\n\n /* Open Input Data */\n  retCode = ObitOTFOpen (inOTF, access, err);\n  if ((retCode != OBIT_IO_OK) || (err->error>0)) \n    Obit_traceback_msg (err, routine, inOTF->name);\n\n  /* use same data buffer on input and output \n     so don't assign buffer for output */\n  if (outOTF->buffer) ObitIOFreeBuffer(outOTF->buffer); /* free existing */\n  outOTF->buffer     = inOTF->buffer;\n  outOTF->bufferSize = inOTF->bufferSize;\n\n /* Open Output Data */\n  retCode = ObitOTFOpen (outOTF, OBIT_IO_WriteOnly, err) ;\n  if ((retCode != OBIT_IO_OK) || (err->error>0)) {\n    outOTF->buffer = NULL; /* remove pointer to inOTF buffer */\n    outOTF->bufferSize = 0;\n    Obit_traceback_msg (err, routine, outOTF->name);\n  }\n\n /* Copy tables before data */\n  retCode = ObitOTFCopyTables (inOTF, outOTF, exclude, NULL, err);\n  if (err->error) {/* add traceback,return */\n    outOTF->buffer = NULL;\n    outOTF->bufferSize = 0;\n    Obit_traceback_msg (err, routine, inOTF->name);\n  }\n\n  /* Close and reopen input to init calibration which will have been disturbed \n     by the table copy */\n  retCode = ObitOTFClose (inOTF, err);\n  if (err->error) {\n    outOTF->buffer = NULL; outOTF->bufferSize = 0;\n    Obit_traceback_msg (err, routine, inOTF->name);\n  }\n\n  retCode = ObitOTFOpen (inOTF, access, err);\n  if ((retCode != OBIT_IO_OK) || (err->error>0)) {\n    outOTF->buffer = NULL; outOTF->bufferSize = 0;\n    Obit_traceback_msg (err, routine, inOTF->name);\n  }\n\n  ndetect = inOTF->geom->numberDetect;    /* How many detectors */\n\n  /* Loop over data */\n  done = (retCode != OBIT_IO_OK);\n  while (!done) {\n\n    /* read buffer */\n    retCode = ObitOTFRead (inOTF, NULL, err);\n    if (err->error) {\n      outOTF->buffer = NULL; outOTF->bufferSize = 0;\n      Obit_traceback_msg (err, routine, inOTF->name);\n    }\n    done = (retCode == OBIT_IO_EOF); /* done? */\n    if (done) break;\n\n     /* How many? */\n     ndata   = inOTF->myDesc->numRecBuff;\n     outOTF->myDesc->numRecBuff = ndata;\n\n     if (ndata>0) {\n       /* Modify data from this buffer */\n       \n       data = inOTF->buffer;  /* data pointer */\n\n       /* Loop over buffer */\n       for (i=0; i<ndata; i++) {\n\t /* Loop over detectors */\n\t for (j=0; j<ndetect; j++) {\n\t   /* Modify */\n\t   if (data[desc->ilocdata+j*incdatawt]!=fblank) {\n\t     data[desc->ilocdata+j*incdatawt] *= scale;\n\t     data[desc->ilocdata+j*incdatawt] += offset;\n\t   }\t   \n\t } /* end loop over detectors */\n\t data += desc->lrec; /* update buffer pointer */\n       } /* end  Loop over buffer */  \n \n       /* Write buffer */\n       retCode = ObitOTFWrite (outOTF, NULL, err);\n     }\n     if (err->error) {\n       outOTF->buffer = NULL; outOTF->bufferSize = 0;\n       Obit_traceback_msg (err, routine, outOTF->name);\n     }\n\n  } /* end data loop */\n  \n  /* unset output buffer (may be multiply deallocated ;'{ ) */\n  outOTF->buffer = NULL;\n  outOTF->bufferSize = 0;\n\n  /* Close input */\n  retCode = ObitOTFClose (inOTF, err);\n  if (err->error) Obit_traceback_msg (err, routine, inOTF->name);\n\n  /* Close output */\n  retCode = ObitOTFClose (outOTF, err);\n  if (err->error) Obit_traceback_msg (err, routine, outOTF->name);\n\n} /* end ObitOTFUtilScale */\n\n/**\n * Add Gaussian noise to an OTF\n * out = in*scale +offset +  noise (sigma)\n * \\param inOTF  Input OTF \n * \\param outOTF Output OTF, must already be defined\n * \\param scale  scaling factor for data\n * \\param offset additive term to be applied to all data.\n * \\param sigma  Standard deviation of Gaussian noise .\n * \\param err    Error stack\n */\nvoid ObitOTFUtilNoise(ObitOTF *inOTF, ObitOTF *outOTF, ofloat scale, ofloat offset,\n\t\t      ofloat sigma, ObitErr *err)\n{\n  ObitIOCode retCode;\n  gboolean doCalSelect, done;\n  ObitInfoType type;\n  ObitIOAccess access;\n  gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};\n  ofloat *data, fblank = ObitMagicF();\n  odouble dsigma = sigma;\n  olong i, j, ndetect, ndata;\n  olong incdatawt;\n  ObitOTFDesc* desc;\n  /* Don't copy Cal and Soln or data or flag tables */\n  gchar *exclude[]={\"OTFSoln\", \"OTFCal\", \"OTFScanData\", \"OTFFlag\", NULL};\n  gsl_rng *ran=NULL;\n  gchar *routine = \"ObitOTFUtilNoise\";\n\n  /* error checks */\n  g_assert (ObitErrIsA(err));\n  if (err->error) return;\n  g_assert (ObitOTFIsA(inOTF));\n  g_assert (ObitOTFIsA(outOTF));\n\n  /* Local pointers */\n  desc = inOTF->myDesc;\n  incdatawt = desc->incdatawt; /* increment in data-wt axis */\n\n  /* Calibration wanted? */ \n  doCalSelect = FALSE;\n  ObitInfoListGetTest(inOTF->info, \"doCalSelect\", &type, (gint32*)dim, &doCalSelect);\n  if (doCalSelect) access = OBIT_IO_ReadCal;\n  else access = OBIT_IO_ReadWrite;\n\n /* Open Input Data */\n  retCode = ObitOTFOpen (inOTF, access, err);\n  if ((retCode != OBIT_IO_OK) || (err->error>0)) \n    Obit_traceback_msg (err, routine, inOTF->name);\n\n  /* use same data buffer on input and output \n     so don't assign buffer for output */\n  if (outOTF->buffer) ObitIOFreeBuffer(outOTF->buffer); /* free existing */\n  outOTF->buffer     = inOTF->buffer;\n  outOTF->bufferSize = inOTF->bufferSize;\n\n  /* Open Output Data */\n  retCode = ObitOTFOpen (outOTF, OBIT_IO_WriteOnly, err) ;\n  if ((retCode != OBIT_IO_OK) || (err->error>0)) {\n    outOTF->buffer = NULL; /* remove pointer to inOTF buffer */\n    outOTF->bufferSize = 0;\n    Obit_traceback_msg (err, routine, outOTF->name);\n  }\n\n  /* Copy tables before data */\n  retCode = ObitOTFCopyTables (inOTF, outOTF, exclude, NULL, err);\n  if (err->error) {/* add traceback,return */\n    outOTF->buffer = NULL;\n    outOTF->bufferSize = 0;\n    Obit_traceback_msg (err, routine, inOTF->name);\n  }\n\n  /* Close and reopen input to init calibration which will have been disturbed \n     by the table copy */\n  retCode = ObitOTFClose (inOTF, err);\n  if (err->error) {\n    outOTF->buffer = NULL; outOTF->bufferSize = 0;\n    Obit_traceback_msg (err, routine, inOTF->name);\n  }\n  \n  retCode = ObitOTFOpen (inOTF, access, err);\n  if ((retCode != OBIT_IO_OK) || (err->error>0)) {\n    outOTF->buffer = NULL; outOTF->bufferSize = 0;\n    Obit_traceback_msg (err, routine, inOTF->name);\n  }\n\n  ndetect = inOTF->geom->numberDetect;    /* How many detectors */\n\n  /* Init random number generator */\n  ran = gsl_rng_alloc(gsl_rng_taus);\n  \n  /* Loop over data */\n  done = (retCode != OBIT_IO_OK);\n  while (!done) {\n    \n    /* read buffer */\n    retCode = ObitOTFRead (inOTF, NULL, err);\n    if (err->error) {\n      outOTF->buffer = NULL; outOTF->bufferSize = 0;\n      Obit_traceback_msg (err, routine, inOTF->name);\n    }\n    done = (retCode == OBIT_IO_EOF); /* done? */\n    if (done) break;\n\n     /* How many? */\n     ndata   = inOTF->myDesc->numRecBuff;\n     outOTF->myDesc->numRecBuff = ndata;\n\n     if (ndata>0) {\n       /* Modify data from this buffer */\n       \n       data = inOTF->buffer;  /* data pointer */\n\n       /* Loop over buffer */\n       for (i=0; i<ndata; i++) {\n\t /* Loop over detectors */\n\t for (j=0; j<ndetect; j++) {\n\t   /* Modify */\n\t   if (data[desc->ilocdata+j*incdatawt]!=fblank) {\n\t     data[desc->ilocdata+j*incdatawt] *= scale;\n\t     data[desc->ilocdata+j*incdatawt] += offset + \n\t       (ofloat)gsl_ran_gaussian (ran, dsigma);\n\t   }\t   \n\t } /* end loop over detectors */\n\t data += desc->lrec; /* update buffer pointer */\n       } /* end  Loop over buffer */  \n \n       /* Write buffer */\n       retCode = ObitOTFWrite (outOTF, NULL, err);\n     }\n     if (err->error) {\n       outOTF->buffer = NULL; outOTF->bufferSize = 0;\n       Obit_traceback_msg (err, routine, outOTF->name);\n     }\n\n  } /* end data loop */\n  \n  /* unset output buffer (may be multiply deallocated ;'{ ) */\n  outOTF->buffer = NULL;\n  outOTF->bufferSize = 0;\n\n  /* Free random number generator */\n  gsl_rng_free(ran);\n  \n  /* Close input */\n  retCode = ObitOTFClose (inOTF, err);\n  if (err->error) Obit_traceback_msg (err, routine, inOTF->name);\n\n  /* Close output */\n  retCode = ObitOTFClose (outOTF, err);\n  if (err->error) Obit_traceback_msg (err, routine, outOTF->name);\n\n} /* end ObitOTFUtilNoise */\n\n/**\n * Subtract a sky model from a buffer full of OTF data.\n * \\param in         OTF with internal buffer to be modified.\n * \\param sky        OTFSkyModel to subtract.\n * \\param factor     Scaling factor for sky model.\n */\nvoid ObitOTFUtilSubSkyModelBuff (ObitOTF *in, ObitOTFSkyModel *sky, ofloat factor)\n{\n  ofloat *xpos, *ypos, *data, dist, maxdist, arg, gf1, gf2, sigma;\n  olong incdatawt;\n  olong  ndetect, ndata, ncomp, i, j, k;\n  ObitOTFDesc* desc;\n  ObitOTFArrayGeom* geom;\n\n  /* Error checks */\n  g_assert (ObitOTFIsA(in));\n  g_assert (ObitOTFSkyModelIsA(sky));\n\n  /* Local pointers */\n  desc = in->myDesc;\n  geom = in->geom;\n  data = in->buffer;\n  ndetect = geom->numberDetect;    /* How many detectors */\n  ndata   = desc->numRecBuff;      /* How many data records */\n  ncomp   = sky->numberComp;        /* How many components */\n  incdatawt = desc->incdatawt; /* increment in data-wt axis */\n\n  /* Allocate temporary arrays */\n  /* Projected data locations */\n  xpos = g_malloc0(ndetect*sizeof(float));\n  ypos = g_malloc0(ndetect*sizeof(float));\n\n  /* How close (deg^2) to consider 3 * beam size */\n  maxdist = (desc->beamSize * 3.0) * (desc->beamSize * 3.0);\n\n  /* Gaussian factors */\n  sigma = desc->beamSize/2.35;\n  gf1 = 1.0 / (2.0 * sigma * sigma);\n  /* Normalize the flux integral rather than the peak */\n  gf2 = factor / sqrt(2.0 * G_PI);\n  /* debug - normalize peak */\n  gf2 = -1.0;\n\n  /* Loop over data records */\n  for (i=0; i<ndata; i++) {\n\n    /* Get Sky locations of the data */\n    ObitOTFArrayGeomProj (geom, data[desc->ilocra], data[desc->ilocdec], \n\t\t\t  data[desc->ilocrot], sky->RACenter, sky->DecCenter, \n\t\t\t  sky->proj, xpos, ypos);\n    \n    /* Loop over the array */\n    for (j=0; j<ndetect; j++) {\n\n      /* loop over components in Sky model */\n      for (k=0; k<ncomp; k++) {\n\t/* how far is the measurement from the component (distance^2) */\n\tdist = (xpos[j]-sky->RAOffset[k]) * (xpos[j]-sky->RAOffset[k]) + \n\t  (ypos[j]-sky->DecOffset[k]) * (ypos[j]-sky->DecOffset[k]);\n\n\t/* Is this one close enough? */\n\tif (dist<maxdist) {\n\t  arg = -dist * gf1;\n\t  data[desc->ilocdata+j*incdatawt] -= gf2 * exp (arg) * sky->flux[k];  /* subtract */\n\t}\n      } /* end loop over components */\n    } /* end loop over array */\n    data += desc->lrec; /* update buffer pointer */\n  } /* end loop over buffer */\n\n  /* cleanup */\n  if (xpos) g_free(xpos);\n  if (ypos) g_free(ypos);\n} /* end ObitOTFUtilSubSkyModelBuff */\n\n/**\n * Subtract the values in an image from a buffer full of OTF data.\n * For CCB beamswitched data (OTFType=OBIT_GBTOTF_CCB, no. States=1)\n * If threading has been enabled by a call to ObitThreadAllowThreads \n * this routine will divide the buffer up amount the number of processors\n * returned by ObitThreadNumProc.\n * \\param in         OTF with internal buffer to be modified.\n * \\param image      Image interpolator\n * \\param factor     Scaling factor for model.\n * \\param nThreads   Number of elements in args\n * \\param args       Threaded function argument structs\n * \\param err        Error stack\n */\nvoid ObitOTFUtilSubImageBuff (ObitOTF *in, ObitFInterpolate *image, \n\t\t\t      ofloat factor, olong nThreads, SubImageFuncArg **args, \n\t\t\t      ObitErr *err)\n{\n  olong i, nrec, lorec, hirec, nTh, nrecPerThread;\n  gboolean OK = TRUE;\n  gchar *routine = \"ObitOTFUtilSubImageBuff\";\n\n  /* error checks - assume most done at higher level */\n  if (err->error) return;\n\n  /* Divide up work */\n  nrec = in->myDesc->numRecBuff;\n  nrecPerThread = nrec/nThreads;\n  nTh = nThreads;\n  if (nrec<100) {nrecPerThread = nrec; nTh = 1;}\n  lorec = 1;\n  hirec = nrecPerThread;\n  hirec = MIN (hirec, nrec);\n\n  /* Set up thread arguments */\n  for (i=0; i<nTh; i++) {\n    if (i==(nTh-1)) hirec = nrec;  /* Make sure do all */\n    args[i]->otfdata = in;\n    args[i]->first  = lorec;\n    args[i]->last   = hirec;\n    if (i==0) args[i]->Interp = ObitFInterpolateRef(image);\n    else args[i]->Interp = ObitFInterpolateClone(image, NULL);\n    args[i]->factor = factor;\n    if (nTh>1) args[i]->ithread = i;\n    else args[i]->ithread = -1;\n    /* Update which rec */\n    lorec += nrecPerThread;\n    hirec += nrecPerThread;\n    hirec = MIN (hirec, nrec);\n  }\n\n  /* Do operation */\n  OK = ObitThreadIterator (in->thread, nTh, \n\t\t\t   (ObitThreadFunc)ThreadOTFUtilSubImageBuff, \n\t\t\t   (gpointer**)args);\n\n  /* Check for problems */\n  if (!OK) Obit_log_error(err, OBIT_Error,\"%s: Problem in threading\", routine);\n} /* end ObitOTFUtilSubImageBuff */\n\n/**\n * Replace data with the values in an image in a buffer full of OTF data.\n * For CCB beamswitched data (OTFType=OBIT_GBTOTF_CCB, no. States=1)\n * \\param in         OTF with internal buffer to be modified.\n * \\param image      Image interpolator\n * \\param factor     Scaling factor for model.\n * \\param err        Error stack\n */\nvoid ObitOTFUtilModelImageBuff (ObitOTF *in, ObitFInterpolate *image, \n\t\t\t\tofloat factor, ObitErr *err)\n{\n  ofloat *xpos, *ypos, *data, ffact, value, RACenter, DecCenter;\n  ObitOTFProj proj;\n  odouble coord[IM_MAXDIM];\n  olong  ndetect, ndata, i, j;\n  olong incfeed, itemp,incdatawt ;\n  gboolean CCBBS, isRef;\n  ObitOTFDesc* desc;\n  ObitOTFArrayGeom* geom;\n  ofloat fblank = ObitMagicF();\n  gchar Proj[5];\n\n  /* Error checks */\n  g_assert (ObitOTFIsA(in));\n  g_assert (ObitFInterpolateIsA(image));\n\n  /* Local pointers */\n  desc = in->myDesc;\n  geom = in->geom;\n  data = in->buffer;\n  ndetect = geom->numberDetect;    /* How many detectors */\n  ndata   = desc->numRecBuff;      /* How many data records */\n  if (in->myDesc->jlocfeed>=0) \n    incfeed = in->myDesc->incfeed / in->myDesc->incdatawt;\n  else incfeed = 1;  /* This is probably a bad sign */\n\n  /* Get Model center */\n  RACenter  = image->myDesc->crval[0];\n  DecCenter = image->myDesc->crval[1];\n  strncpy (Proj, &image->myDesc->ctype[0][4], 5);\n  proj      = ObitOTFSkyModelProj (Proj);\n  incdatawt = desc->incdatawt; /* increment in data-wt axis */\n\n  /* Is this CCB beamswitched data? */\n  CCBBS = (in->myDesc->OTFType==OBIT_GBTOTF_CCB) &&\n    (in->myDesc->jlocstate>=0) &&\n    (in->myDesc->inaxes[in->myDesc->jlocstate]==1);\n\n  /* Allocate temporary arrays */\n  /* Projected data locations */\n  xpos = g_malloc0(ndetect*sizeof(float));\n  ypos = g_malloc0(ndetect*sizeof(float));\n  ffact = factor;\n\n  /* Loop over data records */\n  for (i=0; i<ndata; i++) {\n\n    /* Get Sky locations of the data projected onto the image */\n    ObitOTFArrayGeomProj(geom, data[desc->ilocra], data[desc->ilocdec], \n\t\t\t data[desc->ilocrot], RACenter, DecCenter, proj, \n\t\t\t xpos, ypos);\n\n    /* Loop over the array */\n    for (j=0; j<ndetect; j++) {\n      \n     /* Interpolate - use coordinates on a flat plane at the tangent point of the image \n\t xpos and ypos are offsets from the image center projected onto the plane \n\t of the image, ObitFInterpolateOffset does a linear approximation. */\n       coord[0] = xpos[j];  /* + RACenter; */\n       coord[1] = ypos[j];  /* + DecCenter; */\n       value = ObitFInterpolateOffset (image, coord, err); \n\n      /* Replace */\n      if ((value!=fblank) && (data[desc->ilocdata+j*incdatawt]!=fblank))\n\tdata[desc->ilocdata+j*incdatawt] = value * ffact;\n      else {\n\tdata[desc->ilocdata+j*incdatawt] = fblank;\n      }\n\n      /* For CCB beamswitched data add value corresponding to this feeds\n       reference beam */\n      if (CCBBS) {\n\t/* is this the reference or signal beam? */\n\titemp = j / incfeed;\n\t/* itemp odd means reference beam */\n\tisRef = itemp != 2*(itemp/2);\n\t/* Use feed offset for feed 1 if this is reference, else feed 2 */\n\tif (isRef) itemp = 0;\n\telse itemp = incfeed;\n\t/* interpolate */\n\tcoord[0] = xpos[itemp]; /* + RACenter; */\n\tcoord[1] = ypos[itemp]; /* + DecCenter; */\n\tvalue = ObitFInterpolateOffset (image, coord, err);\n       /* Replace */\n       if ((value!=fblank) && (data[desc->ilocdata+j*incdatawt]!=fblank))\n\t data[desc->ilocdata+j*incdatawt] = value * ffact;\n       else {\n\t data[desc->ilocdata+j*incdatawt] = fblank;\n       }\n      }  /* end adding to reference beam position */\n      \n    } /* end loop over array */\n    data += desc->lrec; /* update buffer pointer */\n  } /* end loop over buffer */\n  \n  /* cleanup */\n  if (xpos) g_free(xpos);\n  if (ypos) g_free(ypos);\n} /* end ObitOTFUtilModelImageBuff */\n\n/**\n * Create basic ObitImage structure and fill out descriptor.\n * Imaging parameters are on the inOTF info member.\n * \\li \"nx\"     OBIT_int (1,1,1) Dimension of image in RA [no default].\n * \\li \"ny\"     OBIT_int (1,1,1) Dimension of image in declination[no default]\n * \\li \"RA\"     OBIT_float (1,1,1) Right Ascension of center of image\n *                                 Default is observed position center in inOTF \n * \\li \"Dec\"    OBIT_float (1,1,1) Declination of center of image\n *                                 Default is observed position center in inOTF \n * \\li \"xCells\" OBIT_float (1,1,1) X (=RA) cell spacing in asec [no default]\n * \\li \"yCells\" OBIT_float (1,1,1) Y (=dec) cell spacing in asec [no default]\n * \\li \"Proj\"   OBIT_string (4,1,1) Projection string \"-SIN\", \"-ARC\", \"-TAN\"\n *                         [Default \"-SIN\"]\n * \\param inOTF     Input OTF data. \n * \\param err      Error stack, returns if not empty.\n * \\return Pointer to the newly created ObitImage.\n */\nObitImage* ObitOTFUtilCreateImage (ObitOTF *inOTF, ObitErr *err)\n{\n  ObitImage *outImage=NULL;\n  gchar outName[121], Proj[8];\n  gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};\n  ObitInfoType type;\n  olong itemp[10], nx, ny;\n  ofloat ftemp[10], xCells, yCells, RA, Dec;\n  gchar *routine = \"ObitOTFUtilCreateImage\";\n \n   /* error checks */\n  g_assert (ObitErrIsA(err));\n  if (err->error) return outImage;\n  g_assert (ObitOTFIsA(inOTF));\n\n  /* open/close OTF data to fully instantiate if not already open */\n  if (inOTF->myStatus==OBIT_Inactive) {\n    ObitOTFFullInstantiate (inOTF, TRUE, err);\n    if (err->error) Obit_traceback_val (err, routine, inOTF->name, outImage);\n  }\n\n  /* Create output */\n  g_snprintf (outName, 120, \"%s\",inOTF->name);\n  outImage = newObitImage(outName);\n\n  /* Get parameters for image */\n  /* Image size */\n  itemp[0] = -1;\n  if (!ObitInfoListGetTest(inOTF->info, \"nx\", &type, dim, itemp))\n    Obit_log_error(err, OBIT_Error, \"%s: %s MUST define nx\", routine, inOTF->name);\n  nx = itemp[0];\n \n  if (!ObitInfoListGetTest(inOTF->info, \"ny\", &type, dim, itemp))\n    Obit_log_error(err, OBIT_Error, \"%s: %s MUST define ny\", routine, inOTF->name);\n  ny = itemp[0];\n\n  /* Cell Spacing */\n  ftemp[0] = 0.0;\n  if (!ObitInfoListGetTest(inOTF->info, \"xCells\", &type, dim, ftemp))\n    Obit_log_error(err, OBIT_Error, \"%s: %s MUST define xCells\", routine, inOTF->name);\n  xCells = ftemp[0];\n\n  if (!ObitInfoListGetTest(inOTF->info, \"yCells\", &type, dim, ftemp)) \n    Obit_log_error(err, OBIT_Error, \"%s: %s MUST define yCells\", routine, inOTF->name);\n  yCells = ftemp[0];\n\n  /* Center Default is observed position center in inOTF */\n  ftemp[0] = inOTF->myDesc->obsra;\n  ObitInfoListGetTest(inOTF->info, \"RA\", &type, dim, ftemp);\n  RA = ftemp[0];\n\n  ftemp[0] = inOTF->myDesc->obsdec;\n  ObitInfoListGetTest(inOTF->info, \"Dec\", &type, dim, ftemp);\n  Dec = ftemp[0];\n \n  /* Default projection is -SIN */\n  Proj[0] = '-'; Proj[1] = 'S'; Proj[2] = 'I'; Proj[3] = 'N'; Proj[4] = 0; \n  ObitInfoListGetTest(inOTF->info, \"Proj\", &type, dim, (gpointer*)&Proj);\n  Proj[4] = 0;\n  \n  /* bail out if an error so far */\n  if (err->error) return outImage;\n\n  /* Set values on descriptor(s) */\n  outImage->myDesc->xshift = 0.0;\n  outImage->myDesc->yshift = 0.0;\n  outImage->myDesc->crota[0] = 0.0;\n  outImage->myDesc->crota[1] = 0.0;\n  outImage->myDesc->cdelt[0] = xCells / 3600.0;\n  outImage->myDesc->cdelt[1] = yCells / 3600.0;\n  outImage->myDesc->inaxes[0] = nx;\n  outImage->myDesc->inaxes[1] = ny;\n  outImage->myDesc->crval[0] = RA;\n  outImage->myDesc->crval[1] = Dec;\n\n  /* Fill in descriptor */\n  ObitOTFUtilOTF2ImageDesc (inOTF->myDesc, outImage->myDesc, Proj);\n\n  return outImage;\n} /* end ObitOTFUtilCreateImage */\n\n/**\n * Convolves data onto a grid, accumulated and normalizes.\n * Imaging parameters are on the inOTF info member.\n * \\li \"ConvType\"   OBIT_long scalar = Convolving function type: [def=3]\n *                  0 = pillbox, 3 = Gaussian, 4 = Exp*Sinc, 5 = Spherodial wave\n * \\li \"ConvParm\"  OBIT_float[10] = Convolving function parameters\n * \\li \"deBias\"    OBIT_bool scalar = Subtract calibration bias from image? [def False]\n *                 Note, this doesn't really work the way you would like\n * \\li \"deMode\"    OBIT_bool scalar = Subtract image mode from image? [def False]\n * \\li \"minWt\"     OBIT_float (1,1,1) Minimum summed gridding convolution weight \n *                 as a fraction of the maximum [def 0.01]\n * \\li \"doScale\"   OBIT_bool scalar If true, convolve/scale beam [def TRUE]\n * \\li \"doConvBeam\"  OBIT_bool scalar If true, convolve beam [def FALSE]\n * \\li \"doFilter\"  OBIT_bool scalar If true, filter out of band noise[def TRUE]\n * \\param inOTF    Input OTF data. \n * \\param outImage Image to be written.  Must be previously instantiated.\n * \\param doBeam   If TRUE also make convolved beam.  \n *                 Will make the myBeam member of outImage.\n * \\param Beam     If non NULL use as instrumental response beam \n * \\param Wt       If non NULL write weight array to.\n * \\param err      Error stack, returns if not empty.\n */\nvoid ObitOTFUtilMakeImage (ObitOTF *inOTF, ObitImage *outImage, gboolean doBeam, \n\t\t\t   ObitImage *Beam, ObitImage *Wt, ObitErr *err)\n{\n  ObitIOSize IOBy;\n  gchar *outName=NULL;\n  ObitOTFGrid *myGrid=NULL;\n  ObitFArray *biasArray=NULL;  \n  ObitInfoType type;\n  gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};\n  olong blc[IM_MAXDIM] = {1,1,1,1,1};\n  olong trc[IM_MAXDIM] = {0,0,0,0,0};\n  ofloat parms[10], xparms[10], mode, radius;\n  olong i, nparms, cType, tcType;\n  gboolean deBias, replCal, tbool, deMode, doFilter;\n  gchar *parmList[] = {\"minWt\",\"Clip\",\"beamNx\",\"beamNy\",\"doScale\",\"doConvBeam\", \n\t\t       NULL};\n  gchar *routine = \"ObitOTFUtilMakeImage\";\n\n   /* error checks */\n  g_assert (ObitErrIsA(err));\n  if (err->error) return;\n  g_assert (ObitOTFIsA(inOTF));\n  g_assert (ObitImageIsA(outImage));\n\n /* Make Gridding object */\n  outName = g_strconcat (\"OTFGrid for: \", inOTF->name, NULL);\n  myGrid = newObitOTFGrid(outName);\n  g_free(outName);\n\n  /* Copy control parameters to grid object */\n  ObitInfoListCopyList (inOTF->info, myGrid->info, parmList);\n\n  /* Now make image */\n  /* Set blc, trc */\n  blc[0] = 1;\n  blc[1] = 1;\n  blc[2] = 1;\n  trc[0] = outImage->myDesc->inaxes[0];\n  trc[1] = outImage->myDesc->inaxes[0];\n  trc[2] = 1;\n      \n  IOBy = OBIT_IO_byPlane;\n  dim[0] = 1;\n  ObitInfoListPut (outImage->info, \"IOBy\", OBIT_long, dim, (gpointer)&IOBy, err);\n  dim[0] = 7;\n  ObitInfoListPut (outImage->info, \"BLC\", OBIT_long, dim, (gpointer)blc, err); \n  ObitInfoListPut (outImage->info, \"TRC\", OBIT_long, dim, (gpointer)trc, err);\n  \n  /*  Open image to get descriptor */\n  if ((ObitImageOpen (outImage, OBIT_IO_WriteOnly, err) \n       != OBIT_IO_OK) || (err->error>0))\n    Obit_log_error(err, OBIT_Error, \"ERROR opening image %s\", outImage->name);\n  if (err->error) return;\n  \n  /* reset max, min */\n  outImage->myDesc->minval =  1.0e20;\n  outImage->myDesc->maxval = -1.0e20;\n  ((ObitImageDesc*)outImage->myIO->myDesc)->minval =  1.0e20;\n  ((ObitImageDesc*)outImage->myIO->myDesc)->maxval = -1.0e20;\n  \n  /* Gaussian beam */\n  outImage->myDesc->beamMaj = inOTF->myDesc->beamSize;\n  outImage->myDesc->beamMin = inOTF->myDesc->beamSize;\n  outImage->myDesc->beamPA  = 0.0;\n  \n  /* Gridding setup */\n  ObitOTFGridSetup (myGrid, inOTF, outImage->myDesc, err);\n  if (err->error) Obit_traceback_msg (err, routine, outImage->name);\n\n  /* Beam if requested */\n  if (doBeam) ObitOTFGridMakeBeam (myGrid, outImage, Beam, err);\n  if (err->error) Obit_traceback_msg (err, routine, outImage->name);\n  \n  /* Grid */\n  ObitOTFGridReadOTF (myGrid, inOTF, err);\n  if (err->error) Obit_traceback_msg (err, routine, outImage->name);\n  \n  /* Normalize */\n  ObitOTFGridNorm(myGrid, outImage->image, outImage->myDesc, err);\n  if (err->error) Obit_traceback_msg (err, routine, outImage->name);\n\n   /* reset beam size on IO descriptor for the effects of convolution */\n  ((ObitImageDesc*)outImage->myIO->myDesc)->beamMaj = outImage->myDesc->beamMaj;\n  ((ObitImageDesc*)outImage->myIO->myDesc)->beamMin = outImage->myDesc->beamMin;\n  \n  /* Remove image Mode */\n  deMode = FALSE;\n  ObitInfoListGetTest(inOTF->info, \"deMode\", &type, dim, &deMode);\n  if (deMode) {\n     /* remove mode of image */\n    mode = ObitFArrayMode(outImage->image);\n    ObitFArraySAdd(outImage->image, -mode);\n    /* Message */\n    Obit_log_error(err, OBIT_InfoErr, \"Subtract image Mode %g\",mode);\n  }\n\n  /* Debias? */\n  deBias = FALSE;\n  ObitInfoListGetTest(inOTF->info, \"deBias\", &type, dim, &deBias);\n  if (deBias) {\n    /* Save image array */\n    biasArray = ObitFArrayCopy (outImage->image, biasArray, err);\n    if (err->error) Obit_traceback_msg (err, routine, outImage->name);\n\n    /* This time replace data with cal value */\n    replCal = FALSE;\n    ObitInfoListGetTest(inOTF->info, \"replCal\", &type, dim, &replCal);\n    tbool = TRUE;\n    ObitInfoListAlwaysPut(inOTF->info, \"replCal\", OBIT_bool, dim, &tbool);\n\n    /* Use large Gaussian convolving fn twice beam size*/\n    cType = 3;\n    ObitInfoListGetTest(inOTF->info, \"ConvType\", &type, dim, &cType);\n    tcType = 3;\n    ObitInfoListAlwaysPut(inOTF->info, \"ConvType\", OBIT_long, dim, &tcType);\n    for (i=0; i<10; i++) parms[i] = 0.0;  /* Default 0.0 */\n    dim[0] = 1;\n    ObitInfoListGetTest(inOTF->info, \"ConvParm\", &type, dim, parms);\n    nparms = dim[0];\n    for (i=0; i<10; i++) xparms[i] = parms[i]; \n    xparms[0] = 7.0; xparms[1] = 2.0;\n    ObitInfoListAlwaysPut(inOTF->info, \"ConvParm\", OBIT_float, dim, xparms);\n  \n    /* Gridding setup */\n    ObitOTFGridSetup (myGrid, inOTF, outImage->myDesc, err);\n    if (err->error) Obit_traceback_msg (err, routine, outImage->name);\n\n    /* reGrid */\n    ObitOTFGridReadOTF (myGrid, inOTF, err);\n    if (err->error) Obit_traceback_msg (err, routine, outImage->name);\n    \n    /* Normalize  bias image */\n    ObitOTFGridNorm(myGrid, outImage->image, outImage->myDesc, err);\n    if (err->error) Obit_traceback_msg (err, routine, outImage->name);\n\n    /* Subtract bias image array */\n    ObitFArraySub(biasArray, outImage->image, outImage->image);\n\n    /* remove mode of image */\n    mode = ObitFArrayMode(outImage->image);\n    ObitFArraySAdd(outImage->image, -mode);\n\n    /* Restore the state of things */\n    dim[0] = 1;\n    ObitInfoListAlwaysPut(inOTF->info, \"replCal\", OBIT_bool, dim, &replCal);\n    ObitInfoListAlwaysPut(inOTF->info, \"ConvType\", OBIT_long, dim, &cType);\n    dim[0] = nparms;\n    ObitInfoListAlwaysPut(inOTF->info, \"ConvParm\", OBIT_float, dim, parms);\n    if (biasArray) ObitFArrayUnref(biasArray);\n  } /* end debias */\n\n /* Write image */\n  ObitImageWrite (outImage, NULL, err);\n  if (err->error) Obit_traceback_msg (err, routine, outImage->name);\n  \n  /* tell Max/Min */\n  Obit_log_error(err, OBIT_InfoErr, \n\t\t \"Image max %g, min %g for %s\", \n\t\t outImage->myDesc->maxval, outImage->myDesc->minval, \n\t\t outImage->name);\n  \n  /* Close Image */\n  ObitImageClose (outImage, err);\n  if (err->error) Obit_traceback_msg (err, routine, outImage->name);\n\n  /* Filter if requested */\n  doFilter = TRUE;\n  ObitInfoListGetTest(inOTF->info, \"doFilter\", &type, dim, &doFilter);\n  radius = 0.5 * inOTF->myDesc->diameter;\n  if (radius<=0.0) radius = 50.0;  /* Default = GBT */\n   /* radius *= 0.25;Factor of two squared somewhere? */\n   radius *= 0.5;/* Factor of two somewhere? */\n  if (doFilter) {\n    Obit_log_error(err, OBIT_InfoErr, \n\t\t   \"Filtering out of band noise for for %s\", outImage->name);\n    ObitImageUtilUVFilter(outImage, outImage, radius, err);\n    if (err->error) Obit_traceback_msg (err, routine, outImage->name);\n  }\n  /* Save Weight image? */\n  if (Wt!=NULL) {\n    ObitImageClone (outImage, Wt, err);   /* Looks like outImage */\n    ObitImageOpen (Wt, OBIT_IO_WriteOnly, err);\n    /* reset max, min */\n    Wt->myDesc->minval =  1.0e20;\n    Wt->myDesc->maxval = -1.0e20;\n    ((ObitImageDesc*)Wt->myIO->myDesc)->minval =  1.0e20;\n    ((ObitImageDesc*)Wt->myIO->myDesc)->maxval = -1.0e20;\n    ObitImageWrite (Wt, myGrid->gridWt->array, err);\n    ObitImageClose (Wt, err);\n    if (err->error) Obit_traceback_msg (err, routine, Wt->name);\n  }\n\n  /* Free myGrid */\n  myGrid = ObitOTFGridUnref(myGrid);\n  \n}  /* end ObitOTFUtilMakeImage */\n\n/**\n * Reads the OTF and rewrites its OTFIndex table\n * \\param inOTF    Input OTF data. \n * \\param err      Error stack, returns if not empty.\n */\nvoid ObitOTFUtilIndex (ObitOTF *inOTF, ObitErr *err)\n{ \n  ObitIOCode retCode;\n  ObitTableOTFIndex* table;\n  ObitTableOTFIndexRow* row;\n  olong num, i, lrec, iRow, ver, lastscan, iscan, target, lastTarget=0, startRec=1, curRec;\n  ofloat *rec;\n  odouble startTime=0.0, endTime=0.0; \n  gchar *routine = \"ObitOTFUtilIndex\";\n\n  /* error checks */\n  g_assert (ObitErrIsA(err));\n  if (err->error) return;\n  g_assert (ObitOTFIsA(inOTF));\n\n  /* Open OTF */\n  retCode = ObitOTFOpen (inOTF, OBIT_IO_ReadWrite, err);\n  if ((retCode != OBIT_IO_OK) || (err->error>0)) \n    Obit_traceback_msg (err, routine, inOTF->name);\n  lrec = inOTF->myDesc->lrec;  /* Size of record */\n  lastscan = -1000; /* initialize scan number */\n  curRec = 0;       /* record counter */\n\n  /* create Index table object */\n  ver = 1;\n  table = newObitTableOTFIndexValue (\"Index table\", (ObitData*)inOTF, &ver, \n\t\t\t\t     OBIT_IO_ReadWrite, err);\n  if (err->error) Obit_traceback_msg (err, routine, inOTF->name);\n\n  /* Open Index table */\n  if ((ObitTableOTFIndexOpen (table, OBIT_IO_ReadWrite, err) \n       != OBIT_IO_OK) || (err->error))  { /* error test */\n    Obit_log_error(err, OBIT_Error, \"ERROR opening output OTFIndex table\");\n    return;\n  }\n\n  /* Create Index Row */\n  row = newObitTableOTFIndexRow (table);\n\n  /* initialize row */\n  row->ScanID = 0;\n  row->TargetID = 0;\n  row->Time = 0.0;\n  row->TimeI = 0.0;\n  row->StartRec = -1;\n  row->EndRec = -1;\n\n  /* attach to table buffer */\n  ObitTableOTFIndexSetRow (table, row, err);\n  if (err->error) Obit_traceback_msg (err, routine, inOTF->name);\n\n  /* Write at beginning of OTFIndex Table */\n  iRow = 0;\n  table->myDesc->nrow = 0; /* ignore any previous entries */\n\n  /* Loop over OTF */\n  while (retCode==OBIT_IO_OK) {\n    retCode = ObitOTFRead (inOTF, inOTF->buffer, err);\n    if (retCode!=OBIT_IO_OK) break;\n\n    /* How many */\n    num = inOTF->myDesc->numRecBuff;\n    \n    /* Record pointer */\n    rec = inOTF->buffer;\n\n    /* initialize on first record */\n    if (curRec<=0) {\n      startRec   = 1;\n      startTime  = rec[inOTF->myDesc->iloct];\n    }\n    \n    /* Loop over buffer */\n    for (i=0; i<num; i++) {\n      \n      iscan  = rec[inOTF->myDesc->ilocscan] + 0.5; /* Which scan number */\n      target = rec[inOTF->myDesc->iloctar] + 0.5;  /* Target number */\n      curRec++; /* Current OTF record number */\n      /* Initialize? */\n      if (lastscan<=0)   lastscan = iscan;\n      if (lastTarget<=0) lastTarget = target;\n      \n      \n      /* New scan? */\n      if ((iscan!=lastscan) && (lastscan>0)) {  /* Write index */\n\n\t/* Record values */\n\trow->ScanID   = lastscan;\n\trow->TargetID = lastTarget;\n\trow->Time     = 0.5 * (startTime + endTime);\n\trow->TimeI    = (endTime - startTime);\n\trow->StartRec = startRec;\n\trow->EndRec   = curRec-1;\n\t\n\t/* Write OTFIndex table */\n\tiRow++;\n\tif ((ObitTableOTFIndexWriteRow (table, iRow, row, err)\n\t     != OBIT_IO_OK) || (err->error>0)) { \n\t  Obit_log_error(err, OBIT_Error, \"ERROR writing OTFIndex Table file\");\n\t  return;\n\t}\n\n\t/* Initialize next scan */\n\tlastscan   = iscan;\n\tlastTarget = target;\n\tstartRec   = curRec;\n\tstartTime  = rec[inOTF->myDesc->iloct];\n\tendTime    = rec[inOTF->myDesc->iloct];\n\t\n      } /* end of if new scan */\n\n      endTime    = rec[inOTF->myDesc->iloct]; /* potential end time */\n      rec += inOTF->myDesc->lrec;     /* Update data record pointer */\n    } /* end loop over buffer */\n\n  } /* End loop over OTF */\n\n  /* Last Scan */\n  /* Record values */\n  row->ScanID   = lastscan;\n  row->TargetID = lastTarget;\n  row->Time     = 0.5 * (startTime + endTime);\n  row->TimeI    = (endTime - startTime);\n  row->StartRec = startRec;\n  row->EndRec   = curRec-1;\n  \n  /* Write OTFIndex table */\n  iRow++;\n  if ((ObitTableOTFIndexWriteRow (table, iRow, row, err)\n       != OBIT_IO_OK) || (err->error>0)) { \n    Obit_log_error(err, OBIT_Error, \"ERROR writing OTFIndex Table file\");\n    return;\n  }\n\n /* Close OTFIndex table */\n  if ((ObitTableOTFIndexClose (table, err) \n       != OBIT_IO_OK) || (err->error>0)) { /* error test */\n    Obit_log_error(err, OBIT_Error, \"ERROR closing output OTFIndex Table file\");\n    return;\n  }\n\n  /* Cleanup */\n  row = ObitTableOTFIndexRowUnref(row);\n  table = ObitTableOTFIndexUnref(table);\n\n  /* Close OTF */\n  retCode = ObitOTFClose (inOTF, err);\n  if ((retCode != OBIT_IO_OK) || (err->error>0)) \n    Obit_traceback_msg (err, routine, inOTF->name);\n} /* end ObitOTFUtilIndex */\n\n/**\n * Differences the Ons and Offs in a beamswitched nodding scan\n * Output values on inOTF\n * \\li \"OnOff\"    OBIT_float (*,1,1) Differences of On-Off for each detector\n *                in the same order as defined in the data.  For beamswitched\n *                data this will be twice the source strength.\n * \\param inOTF    Input OTF data. Applies any calibration specified\n *                 Target position must be in OTFTarget table.\n * \\param scan     Scan number\n * \\param err      Error stack, returns if not empty.\n */\nvoid ObitOTFUtilDiffNod (ObitOTF *inOTF, olong scan, ObitErr *err)\n{\n  ObitIOCode retCode;\n  gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};\n  ObitTableOTFTarget* targetTable=NULL;\n  ofloat *avgOff=NULL, *avgOn=NULL, *feedRA=NULL, *feedDec=NULL;\n  olong   *cntOn=NULL, *cntOff=NULL;\n  olong i, state, ndetect, incfeed, itemp, iDet;\n  olong scans[2], doCal, incdatawt, targID=0;\n  olong ver;\n  gboolean doCalSelect, isCal, isRef, gotTarinfo=FALSE;\n  odouble RACal, DecCal, dra, ddec, val;\n  ofloat *rec, FluxCal, fblank = ObitMagicF();\n  gchar *routine = \"ObitOTFUtilDiffNod\";\n\n   /* error checks */\n  g_assert (ObitErrIsA(err));\n  if (err->error) return;\n  g_assert (ObitOTFIsA(inOTF));\n\n  /* How many detectors? */\n  ndetect = inOTF->geom->numberDetect;\n\n  /* Create arrays */\n  avgOff  = g_malloc0(ndetect*sizeof(ofloat));\n  avgOn   = g_malloc0(ndetect*sizeof(ofloat));\n  cntOff  = g_malloc0(ndetect*sizeof(olong));\n  cntOn   = g_malloc0(ndetect*sizeof(olong));\n  feedRA  = g_malloc(ndetect*sizeof(ofloat));\n  feedDec = g_malloc(ndetect*sizeof(ofloat));\n  for (i=0; i<ndetect; i++) avgOff[i] = avgOn[i] = 0.0;\n  for (i=0; i<ndetect; i++) cntOff[i] = cntOn[i] = 0;\n\n  /* Select scan on input */\n  doCalSelect = TRUE;\n  dim[0] = 1;\n  ObitInfoListAlwaysPut(inOTF->info, \"doCalSelect\", OBIT_bool, dim, &doCalSelect);\n  doCal = 1;\n  ObitInfoListAlwaysPut(inOTF->info, \"doCalib\", OBIT_bool, dim, &doCal);\n  scans[0] = scan; scans[1] = scan;\n  dim[0] = 2;\n  ObitInfoListAlwaysPut(inOTF->info, \"Scans\", OBIT_long, dim, scans);\n  incdatawt = inOTF->myDesc->incdatawt; /* increment in data-wt axis */\n\n   /* open OTF data to fully instantiate  */\n  retCode = ObitOTFOpen (inOTF, OBIT_IO_ReadCal, err);\n  if (err->error) goto cleanup;\n\n  /* loop reading data */\n  retCode = OBIT_IO_OK;\n  while (retCode == OBIT_IO_OK) {\n\n    /* read buffer */\n    retCode = ObitOTFReadSelect (inOTF, NULL, err);\n    if (err->error) goto cleanup;\n    if (retCode==OBIT_IO_EOF) break; /* done? */\n\n    /* Record pointer */\n    rec = inOTF->buffer;\n  \n    /* Feed increment in data */\n    if (inOTF->myDesc->jlocfeed>=0) \n      incfeed = inOTF->myDesc->incfeed / inOTF->myDesc->incdatawt;\n    else incfeed = 1;  /* This is probably a bad sign */\n\n    /* Loop over buffer */\n       for (i=0; i<inOTF->myDesc->numRecBuff; i++) {\n\n\t /* Get source info on first record */\n\t if (!gotTarinfo) {\n\t   gotTarinfo = TRUE;\n\t   /* Get position from table */\n\t   ver = 1;\n\t   targID     = (olong)rec[inOTF->myDesc->iloctar];\n\t   targetTable = \n\t     newObitTableOTFTargetValue (\"TargetTable\", (ObitData*)inOTF, &ver, OBIT_IO_ReadWrite, \n\t\t\t\t\t err);\n\t   ObitTableOTFTargetGetSource (targetTable, targID, &RACal, &DecCal, &FluxCal, err);\n\t   targetTable = ObitTableOTFTargetUnref(targetTable);\n\t   if (err->error) goto cleanup;\n\t   \n\t   /* Make sure there is something */\n\t   if ((RACal==0.0) || (DecCal==0.0)) {\n\t     Obit_log_error(err, OBIT_Error, \"%s: MISSING Calibrator info for %d %lf %lf in %s\", \n\t\t\t    routine, targID, RACal, DecCal, inOTF->name);\n\t     goto cleanup;\n\t   }\n\n\t } /* End of get target info & create arrays */\n\n\t /* Get feed positions */\n\t ObitOTFArrayGeomCoord (inOTF->geom,  rec[inOTF->myDesc->ilocra], \n\t\t\t\trec[inOTF->myDesc->ilocdec], rec[inOTF->myDesc->ilocrot], \n\t\t\t\tfeedRA, feedDec);\n\t /* Three states here, sig beam on source (state=1), ref beam on source (state=-1) \n\t    or neither (state=0) */\n\t state = 0;\n\t /* Close to sig beam?  */\n\t itemp = 0;\n\t dra  = feedRA[itemp]  - RACal;\n\t ddec = feedDec[itemp] - DecCal;\n\t if (sqrt(dra*dra+ddec*ddec) < 0.3*inOTF->myDesc->beamSize) state = 1;\n\n\t if (!state) {\n\t   /* Close to reference beam? */\n\t   itemp = inOTF->myDesc->incfeed;\n\t   dra  = feedRA[itemp]  - RACal;\n\t   ddec = feedDec[itemp] - DecCal;\n\t   if (sqrt(dra*dra+ddec*ddec) < 0.3*inOTF->myDesc->beamSize) state = -1;\n\t }\n\n\t /* sum values if on sig or ref position and cal off */\n\t isCal = rec[inOTF->myDesc->iloccal]!=0.0; /* Cal on? */\n\t if ((!isCal) && (state!=0)) {\n\t   for (iDet=0; iDet<=ndetect; iDet++) {\n\t     val = rec[inOTF->myDesc->ilocdata+iDet*incdatawt];\n\t     if (val==fblank) continue;\n\n\t     /* Is this a sig or ref beam */\n\t     itemp = iDet / incfeed;\n\t     /* itemp odd is reference beam */\n\t     isRef = itemp != 2*(itemp/2);\n\n\t     if (isRef) { /* reference beam */\n\t       if (state<0)      {avgOn[iDet]  += val; cntOn[iDet]++;}\n\t       else if (state>0) {avgOff[iDet] += val; cntOff[iDet]++;}\n\t     } else { /* signal beam */\n\t       if (state>0)      {avgOn[iDet]  += val; cntOn[iDet]++;}\n\t       else if (state<0) {avgOff[iDet] += val; cntOff[iDet]++;}\n\t     }\n\t   }\n\t }\n\n\t rec += inOTF->myDesc->lrec; /* Data record pointer */\t \n       } /* end loop over buffer load */\n  } /* end loop reading data */ \n  \n  /* Close data */\n  retCode = ObitOTFClose (inOTF, err);\n  if (err->error) goto cleanup;\n\n  /* Get On-Off */\n  for (i=0; i<ndetect; i++) {\n    /* Average */\n    if (cntOn[i]>0) avgOn[i] /= cntOn[i];\n    else avgOn[i] = fblank;\n    if (cntOff[i]>0) avgOff[i] /= cntOff[i];\n    else avgOff[i] = fblank;\n\n    if ((avgOff[i]!=fblank) && (avgOn[i]!=fblank)) {\n       avgOn[i] = (avgOn[i] - avgOff[i]);\n    } else {\n       avgOn[i] = fblank;\n    }\n  } /* end loop over detectors */\n\n  /* Save values on inOTF */\n  dim[0] = ndetect; dim[1] = 1;\n  ObitInfoListPut (inOTF->info, \"OnOff\",  OBIT_float, dim,  avgOn, err);\n\n  /* Cleanup */\n cleanup:\n  if (avgOn)   g_free(avgOn);\n  if (avgOff)  g_free(avgOff);\n  if (cntOn)   g_free(cntOn);\n  if (cntOff)  g_free(cntOff);\n  if (feedRA)  g_free(feedRA);\n  if (feedDec) g_free(feedDec);\n \n}  /* end ObitOTFUtilDiffNod */\n\n/**\n * Create an image and fill the descriptor values for an image cube\n * based on  the descriptor for a single plane and for the uv data \n * creating the image.\n * This should be called before the image is Opened or instantiated.\n * \\param inDesc    Input Image Descriptor.\n * \\param UVDesc    Input UV Descriptor.\n * \\param outDesc   Output Image Descriptor \n * \\param Stokes    Stokes parameter of image ' '=>'I', (I, Q, U, V, R, L)\n * \\param bchan     first (1-rel) channel in UVDesc\n * \\param echan     highest (1-rel) channel in UVDesc\n * \\param incr      channel increment in input\n * \\param nchavg    How many uv channels to average per image channel.\n *                  Ignored if uv data has multiple IFs.\n */\nvoid \nObitOTFUtilMakeCube (ObitImageDesc *inDesc, ObitOTFDesc *OTFDesc, \n\t\t       ObitImageDesc *outDesc, \n\t\t       gchar *Stokes, olong bchan, olong echan, olong incr, ObitErr *err)\n{\n  olong numberChann;\n  gchar *name;\n  gchar *routine = \"ObitOTFUtilMakeCube\";\n\n  /* error checks */\n  g_assert(ObitErrIsA(err));\n  if (err->error) return;\n  g_assert (ObitImageDescIsA(inDesc));\n  g_assert (ObitOTFDescIsA(OTFDesc));\n\n  /* Save output name */\n  if (outDesc->name) name = g_strdup (outDesc->name);\n  else  name = g_strdup (\"Descriptor\");\n\n  /* Most info from inDesc */\n  outDesc = ObitImageDescCopy (inDesc, outDesc, err);\n  if (err->error) Obit_traceback_msg (err, routine, inDesc->name);\n\n  /* restore name */\n  if (outDesc->name) g_free(outDesc->name);\n  outDesc->name = name;\n\n  /* Set number of channels */\n  numberChann = MIN (echan, OTFDesc->inaxes[OTFDesc->jlocf]) - MAX (1, bchan) + 1;\n  outDesc->inaxes[outDesc->jlocf] = MAX (1, numberChann / MAX (1, incr));\n\n  /* Stokes parameter */\n  if ((Stokes[0]=='I') || (Stokes[0]==' ')) outDesc->crval[outDesc->jlocs] = 1.0;\n  else if (Stokes[0]=='Q') outDesc->crval[outDesc->jlocs] =  2.0;\n  else if (Stokes[0]=='U') outDesc->crval[outDesc->jlocs] =  3.0;\n  else if (Stokes[0]=='V') outDesc->crval[outDesc->jlocs] =  4.0;\n  else if (Stokes[0]=='R') outDesc->crval[outDesc->jlocs] = -1.0;\n  else if (Stokes[0]=='L') outDesc->crval[outDesc->jlocs] = -1.0;\n\n  /* reset image max/min */\n  outDesc->maxval    = -1.0e20;\n  outDesc->minval    =  1.0e20;\n\n  return;\n} /* end ObitOTFUtilMakeCube */\n\n/**\n * Convolve a set of Clean components with a beam image\n * \\param CCTab      CC Table, following parameters on infoList\n * \\li  \"BComp\" OBIT_int (1,1,1) Start CC to use, 1-rel [def 1 ]\n * \\li  \"EComp\" OBIT_int (1,1,1) Highest CC to use, 1-rel [def to end ]\n * \\param Beam       Beam image to convolve with CCs\n * \\param Template   Template for output array\n * \\param err        Obit Error stack\n * \\return An ObitFArray whose size is that of Template, spacing is that of Beam\n *         with the CCs in CCTab convolved with Beam and the (0,0) position is\n *         (nx/2,ny/2) (0-rel)\n */\nObitFArray* ObitOTFUtilConvBeam (ObitTableCC *CCTab, ObitImage *Beam, \n\t\t\t\t ObitFArray *Template, ObitErr *err)\n{\n  ObitFArray *out = NULL;\n  ObitFArray *beamArray = NULL;\n  olong iRow;\n  ObitIOSize IOsize = OBIT_IO_byPlane;\n  ObitInfoType type;\n  gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};\n  olong  *iptr, bcomp, ecomp;\n  olong blc[IM_MAXDIM] = {1,1,1,1,1,1,1};\n  olong trc[IM_MAXDIM] = {0,0,0,0,0,0,0};\n  olong  pos[2], loop, beamCen[2], nrow, nx, ny, xcen, ycen;\n  ofloat xdelt, ydelt;\n  ObitTableCCRow *row=NULL;\n  gchar *routine = \"ObitOTFUtilConvBeam\";\n\n /* error checks */\n  if (err->error) return out;\n  g_assert (ObitTableCCIsA(CCTab));\n  g_assert (ObitImageIsA(Beam));\n  g_assert (ObitFArrayIsA(Template));\n\n  /* Make output array */\n  out = ObitFArrayCreate(routine, Template->ndim, Template->naxis);\n  /* Size and center */\n  nx = (olong)Template->naxis[0];\n  xcen = nx/2;\n  ny = (olong)Template->naxis[1];\n  ycen = ny/2;\n\n  /* Range of CCs - start CC number */\n  if (ObitInfoListGetP(CCTab->info, \"BComp\",  &type, dim, (gpointer)&iptr)) {\n    bcomp = iptr[0];\n  } else bcomp = 1;\n\n  /* End CC number */\n  if (ObitInfoListGetP(CCTab->info, \"EComp\",  &type, dim, (gpointer)&iptr)) {\n    ecomp = iptr[0];\n  } else ecomp = 0;\n\n  /* Read beam image - Full field */\n  dim[0] = IM_MAXDIM;\n  ObitInfoListPut (Beam->info, \"BLC\", OBIT_long, dim, blc, err); \n  ObitInfoListPut (Beam->info, \"TRC\", OBIT_long, dim, trc, err); \n  dim[0] = 1;\n  ObitInfoListPut (Beam->info, \"IOBy\", OBIT_long, dim, &IOsize, err);\n  Beam->extBuffer = FALSE;\n  ObitImageOpen  (Beam, OBIT_IO_ReadOnly, err); \n  ObitImageRead  (Beam, NULL, err);\n  ObitImageClose (Beam, err); \n  if (err->error) Obit_traceback_val (err, routine, Beam->name, out);\n  beamArray = Beam->image;  /* FArray with beam */\n  beamCen[0] = (olong)(Beam->myDesc->crpix[0] + 0.5);\n  beamCen[1] = (olong)(Beam->myDesc->crpix[1] + 0.5);\n  xdelt = 1.0 /  Beam->myDesc->cdelt[0];\n  ydelt = 1.0 /  Beam->myDesc->cdelt[1];\n\n  /* Open CC table */\n  ObitTableCCOpen (CCTab, OBIT_IO_ReadOnly, err); \n  if (err->error) Obit_traceback_val (err, routine, Beam->name, out);\n  row = newObitTableCCRow(CCTab);\n\n  /* Restoration loop */\n  nrow = CCTab->myDesc->nrow;\n  if (ecomp<1) ecomp = nrow;\n  Obit_log_error(err, OBIT_InfoErr, \"%s: Using %d components\", \n\t\t routine, ecomp-bcomp+1); \n  for (loop=bcomp; loop<=ecomp; loop++) {\n\n    /* Read CC table */\n    iRow = loop;\n    ObitTableCCReadRow (CCTab, iRow, row, err);\n    if (err->error) Obit_traceback_val (err, routine, CCTab->name, out);\n\n    /* Restore to residual */\n    pos[0] = (olong)(xcen + (row->DeltaX * xdelt) + 1.5);\n    pos[1] = (olong)(ycen + (row->DeltaY * ydelt) + 1.5);\n    ObitFArrayShiftAdd (out, pos, beamArray, beamCen, row->Flux, out);\n  } /* End Restoration loop */\n\n\n  /* Close CC table */\n  ObitTableCCClose (CCTab, err);\n  if (err->error) Obit_traceback_val (err, routine, CCTab->name, out);\n  Beam->image = ObitFArrayUnref(Beam->image);\n\n  /* Cleanup */\n  row        = ObitTableCCRowUnref(row);\n  return out;\n} /* end ObitOTFUtilConvBeam */\n\n/**\n * Determine an OTFSoln residual calibration table\n * If a model is given, a residual timestream data set is generated\n * by subtracting the model from the input data to a scratch file.\n * The scratch file (or input if no model given) is low pass filtered to \n * generate the solution table.\n * Calibration parameters are on the inOTF info member.\n * \\li \"calType\"   OBIT_string (*,1,1) Calibration type desired\n *                 \"Both\" => Detector offsets (per scan/maxInt) and common mode poly\n *                 \"Common\" => common mode poly\n *                 \"Offset\" Detector offsets \n *                 \"Gain\" => Gain (multiplicative, cal) solution only\n *                 \"Offset\" => Offset (additive) solution only\n *                 \"GainOffset\" both gain and offset calibration (probably bad idea).\n *                 \"Filter\" detector offsets from FFT low pass filter\n * \\li \"minResFlx\" OBIT_float (1,1,1) Min. model value, [ def -1.0e20]\n * \\li \"maxResFlx\" OBIT_float (1,1,1) Max. model value [def 1.0e20]\n * \\li \"solInt\"    OBIT_float (1,1,1) Solution interval in days [def 1 sec].\n * \\li \"maxInt\"    OBIT_float (1,1,1) max. Interval in days [def 10 min].\n *                 Scans longer than this will be broken into pieces,\n *                 for offset determination in calType \"Both\" only.\n * \\li \"minEl\"     OBIT_float (1,1,1) Minimum elevation allowed (deg)\n * \\li \"Clip\"      OBIT_float (1,1,1) data outside of range +/- Clip are replaced by\n *                 + or - Clip. [Def 1.0e20]\n * \\li \"doScale\"   OBIT_bool scalar If true, convolve/scale beam [def TRUE]\n * \\param inOTF    Input OTF data. \n * \\param outOTF   OTF with which the output  OTFSoln is to be associated\n * \\param model    If given the image to use as a model\n * \\param doCC     If true use CC model, else pixels  [def FALSE]\n * \\param PSF      PSF of instrument to use in generating model from CC table\n * \\param err      Error stack, returns if not empty.\n * \\return Pointer to the newly created OTFSoln object which is \n * associated with outOTF.\n */\nObitTableOTFSoln* ObitOTFUtilResidCal (ObitOTF *inOTF, ObitOTF *outOTF, \n\t\t\t\t       ObitImage *model, gboolean doModel,\n\t\t\t\t       ObitImage *PSF, ObitErr *err)\n{\n  ObitTableOTFSoln *outSoln=NULL;\n  ObitOTF          *residOTF=NULL;  \n  ObitTableCC      *CCTab=NULL;\n  ObitFArray *modPix;\n  gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};\n  ObitInfoType type;\n  ObitIOAccess access;\n  gboolean doCalSelect;\n  gchar calType[50];\n  olong  i, ver, noParms;\n  ofloat maxResFlx, minResFlx;\n  gchar *SolnParms[] = {  /* Solution parameters */\n    \"calType\", \"solInt\", \"maxInt\", \"minEl\", \"clipSig\", \"doScale\",\n    NULL\n  };\n  gchar *routine = \"ObitOTFUtilResidCal\";\n \n   /* error checks */\n  if (err->error) return outSoln;\n  g_assert (ObitOTFIsA(inOTF));\n\n  /* Calibration wanted? */ \n  doCalSelect = FALSE;\n  ObitInfoListGetTest(inOTF->info, \"doCalSelect\", &type, dim, &doCalSelect);\n  if (doCalSelect) access = OBIT_IO_ReadCal;\n  else access = OBIT_IO_ReadWrite;\n\n  /* Control parameters */\n  minResFlx = -1.0e20;\n  ObitInfoListGetTest(inOTF->info, \"minResFlx\",  &type, dim, &minResFlx);\n  maxResFlx = 1.0e20;\n  ObitInfoListGetTest(inOTF->info, \"maxResFlx\",  &type, dim, &maxResFlx);\n\n  /* calibration type */\n  for (i=0; i<50; i++) calType[i] = 0;\n  strcpy (calType, \"Both\");\n  ObitInfoListGetTest(inOTF->info, \"calType\", &type, dim, calType);\n\n  /* Using model? */\n  if (model) { /* Have model */\n    residOTF = newObitOTFScratch(inOTF, err); /* Scratch file for residual */\n\n    /* Read model Image */\n    ObitImageOpen (model, OBIT_IO_ReadOnly, err);\n    ObitImageRead (model, NULL, err);\n    modPix = model->image;\n    ObitImageClose (model, err);\n    if (err->error) Obit_traceback_val (err, routine, model->name, outSoln);\n\n    /* Replace pixels with CC model? */\n    if (doModel) {\n      /* Get CC table */\n      noParms = 0;\n      ver = 1;\n      CCTab = newObitTableCCValue (\"Temp CC\", (ObitData*)model,\n\t\t\t\t   &ver, OBIT_IO_ReadOnly, noParms, err);\n      if (err->error) Obit_traceback_val (err, routine, model->name, outSoln);\n     \n      modPix = ObitOTFUtilConvBeam (CCTab, PSF, model->image, err);\n      if (err->error) Obit_traceback_val (err, routine, model->name, outSoln);\n      CCTab = ObitTableCCUnref(CCTab); \n    } else {\n      modPix = ObitFArrayRef(model->image);\n    }\n\n    /* Clip model */\n    if ((minResFlx>-1.0e19) || (minResFlx<1.0e19)) {\n      ObitFArrayClip (modPix, -1.0e20, maxResFlx, maxResFlx);\n      ObitFArrayClip (modPix, minResFlx, 1.0e20, minResFlx);\n      Obit_log_error(err, OBIT_InfoErr, \"Clip model to range %12.4g %12.4g\", \n\t\t     minResFlx, maxResFlx);\n    }\n\n\n    /* Subtract to form residuals */\n    ObitOTFUtilSubImage (inOTF, residOTF, modPix, model->myDesc, err);\n    if (err->error) Obit_traceback_val (err, routine, model->name, outSoln);\n\n    /* Copy soln parameters to residOTF */\n    ObitInfoListCopyList (inOTF->info, residOTF->info, SolnParms);\n\n    /* DEBUG write as FITS \n    ObitImageUtilFArray2FITS(modPix, \"ModelImage.fits\", 0, model->myDesc, err);*/\n\n    /* Cleanup */\n    modPix       = ObitUnref(modPix); \n    model->image = ObitUnref(model->image);\n  } else { /* no model */\n    residOTF = ObitOTFRef(inOTF);\n  }\n\n  /* Do solutions */\n  if (!strncmp(calType, \"Common\",4)) \n    outSoln = ObitOTFGetSolnMBBase (residOTF, outOTF, err);\n  else if (!strncmp(calType, \"Offset\",6)) \n    outSoln = ObitOTFGetSolnMBBase (residOTF, outOTF, err);\n  else if (!strncmp(calType, \"Both\",10)) \n    outSoln = ObitOTFGetSolnMBBase (residOTF, outOTF, err);\n  else if (!strncmp(calType, \"Gain\",10)) \n    outSoln = ObitOTFGetSolnGain (residOTF, outOTF, err);\n  else if (!strncmp(calType, \"Offset\",10)) \n    outSoln = ObitOTFGetSolnGain (residOTF, outOTF, err);\n  else if (!strncmp(calType, \"GainOffset\",10)) \n    outSoln = ObitOTFGetSolnGain (residOTF, outOTF, err);\n  else if (!strncmp(calType, \"Filter\",10)) \n    outSoln = ObitOTFGetSolnCal (residOTF, outOTF, err);\n  if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);\n\n  /* Cleanup */\n  residOTF = ObitOTFUnref(residOTF);\n  \n  return outSoln;\n\n } /* end  ObitOTFUtilResidCal */\n\n/*----------------------Private functions---------------------------*/\n\n/**\n * Fill in an image Descriptor from a OTF Descriptor.\n * Needs size, cell spacing and center filled in\n * Information about the first two axes other than the type an \n * coordinate value need to be set separately.\n * to get the final position correct.\n * \\param OTFDesc    Input OTF Descriptor.\n * \\param imageDesc  Output image Descriptor\n * \\param Proj       Projection code.\n */\nstatic void \nObitOTFUtilOTF2ImageDesc(ObitOTFDesc *OTFDesc, ObitImageDesc *imageDesc,\n\t\t\t gchar *Proj)\n{\n  olong i, iaxis;\n  gchar *st1;\n\n  /* error checks */\n  g_assert (ObitOTFDescIsA(OTFDesc));\n  g_assert (ObitImageDescIsA(imageDesc));\n  \n  /* Be sure OTF descriptor is indexed */\n  ObitOTFDescIndex(OTFDesc);\n\n  /* loop over axes */\n\n  iaxis = 0;\n  /* RA axis, pos, inaxes, cdelt, crota, xshift set else where */\n  /* Form label string */\n  st1 = imageDesc->ctype[iaxis];\n  st1[0] = 'R'; st1[1] = 'A'; st1[2] = '-'; st1[3] = '-'; \n  for (i=0; i<4; i++)  st1[i+4]=Proj[i];\n  st1[9] = 0;\n\n  /* Reference pixel */\n  imageDesc->crpix[iaxis] = 1.0 + imageDesc->inaxes[iaxis] / 2.0;\n\n  /* Dec axis, pos, inaxes, cdelt, crota, xshift set else where */\n  iaxis++;\n  /* Form label string */\n  st1 = imageDesc->ctype[iaxis];\n  st1[0] = 'D'; st1[1] = 'E'; st1[2] = 'C'; st1[3] = '-'; \n  for (i=0; i<4; i++)  st1[i+4]=Proj[i];\n  st1[9] = 0;\n\n  /* Reference pixel */\n  imageDesc->crpix[iaxis] = 1.0 + imageDesc->inaxes[iaxis] / 2.0;\n\n  /* Frequency Axis */\n  iaxis++;\n  /* Initially set for continuum */\n  strncpy (imageDesc->ctype[iaxis], \"FREQ    \", IMLEN_KEYWORD-1);\n  imageDesc->inaxes[iaxis] = 1;  /* Only one for continuum */\n  imageDesc->crpix[iaxis] = 1.0; /* reference pixel */\n  imageDesc->crota[iaxis] = 0.0; /* no possible meaning */\n  imageDesc->cdelt[iaxis] = OTFDesc->cdelt[OTFDesc->jlocf];\n  if (OTFDesc->jlocf>=0)\n    imageDesc->crval[iaxis] = OTFDesc->crval[OTFDesc->jlocf];\n  else\n    imageDesc->crval[iaxis] = 1.0e9; /* unknown frequency */\n\n  /* Stokes Axis */\n  iaxis++;\n  imageDesc->inaxes[iaxis] = 1;  /* Only one */\n  strncpy (imageDesc->ctype[iaxis], \"STOKES  \", IMLEN_KEYWORD-1);\n  imageDesc->crval[iaxis] = 1.0;\n  imageDesc->crpix[iaxis] = 1.0; /* reference pixel */\n  imageDesc->cdelt[iaxis] = 1.0; /* coordinate increment */\n  imageDesc->crota[iaxis] = 0.0; /* no possible meaning */\n\n  /* Total number of axes */\n  imageDesc->naxis = iaxis+1;\n\n  /* Copy information not directly related to an axis */\n  /* Strings */\n  strncpy (imageDesc->object, OTFDesc->object, IMLEN_VALUE-1);\n  strncpy (imageDesc->teles,  OTFDesc->teles,  IMLEN_VALUE-1);\n  strncpy (imageDesc->origin, OTFDesc->origin, IMLEN_VALUE-1);\n  strncpy (imageDesc->bunit,  \"JY/BEAM \",     IMLEN_VALUE-1);\n  /* Set current date */\n  ObitOTFUtilCurDate (imageDesc->date, IMLEN_VALUE-1);\n\n  /* Observing date */\n  if (OTFDesc->JDObs>1.0) ObitOTFDescJD2Date (OTFDesc->JDObs, imageDesc->obsdat);\n\n  imageDesc->epoch        = OTFDesc->epoch;\n  imageDesc->obsra        = OTFDesc->obsra;\n  imageDesc->obsdec       = OTFDesc->obsdec;\n\n  /* initialize some values */\n  imageDesc->areBlanks = FALSE;\n  imageDesc->niter     = 0;\n  imageDesc->maxval    = -1.0e20;\n  imageDesc->minval    =  1.0e20;\n  imageDesc->bitpix    = -32;\n  imageDesc->beamMaj   = OTFDesc->beamSize;\n  imageDesc->beamMin   = OTFDesc->beamSize;\n  imageDesc->beamPA    = 0.0;\n\n  /* Index Image descriptor */\n  ObitImageDescIndex(imageDesc);\n\n} /* end ObitOTFUtilOTF2ImageDesc */\n\n/**\n * Fills an existing character array with the string for the current date.\n * \\param date Character string to accept the string (10 char+null)\n * \\param len  Actual length of date (should be at least 11)\n */\nstatic void ObitOTFUtilCurDate (gchar *date, olong len)\n{\n  struct tm *lp;\n  time_t clock;\n  \n  /* Get time since 00:00:00 GMT, Jan. 1, 1970 in seconds. */\n  time (&clock);\n  \n  /* Convert to  broken-down time. */\n  lp = localtime (&clock);\n  \n  /* Full year */\n  if (lp->tm_year<1000)  lp->tm_year += 1900; \n  lp->tm_mon++; /* Month 0-rel rest 1-rel */\n\n  /* to output */\n  g_snprintf (date, len, \"%4.4d-%2.2d-%2.2d\",\n\t      lp->tm_year, lp->tm_mon, lp->tm_mday);\n} /* end ObitOTFUtilCurDate */\n\n/**\n * Subtract the values in an image from a portion of a buffer of OTF data.\n * For CCB beamswitched data (OTFType=OBIT_GBTOTF_CCB, no. States=1)\n * Callable as thread\n * Arguments are given in the structure passed as arg\n * \\param arg Pointer to SubImageFuncArg argument with elements:\n * \\li sky     OTFSkyModel \n * \\li otfdata OTF data set to model and subtract from current buffer\n * \\li first  First (1-rel) rec in otfdata buffer to process this thread\n * \\li last   Highest (1-rel) rec inotfdata buffer to process this thread\n * \\li ithread thread number, >0 -> no threading\n * \\li err Obit error stack object.\n * \\li factor  Scaling factor for sky model\n * \\li Interp  Image Interpolator\n * \\li xpos, ypos, float arrays the size of ndetect\n * \\return NULL\n */\ngpointer ThreadOTFUtilSubImageBuff (gpointer args)\n{\n  SubImageFuncArg *largs  = (SubImageFuncArg*)args;\n  ObitOTF *in             = largs->otfdata;\n  olong loRec             = largs->first-1;\n  olong hiRec             = largs->last;\n  ofloat factor           = largs->factor;\n  ObitFInterpolate *image = largs->Interp;\n  ofloat *xpos            = largs->xpos;\n  ofloat *ypos            = largs->ypos;\n  ObitErr *err            = largs->err;\n\n  ofloat *data, ffact, value, RACenter, DecCenter;\n  ObitOTFProj proj;\n  odouble coord[IM_MAXDIM];\n  olong  ndetect, ndata, i, j;\n  olong incfeed, itemp,incdatawt ;\n  gboolean CCBBS, isRef;\n  ObitOTFDesc* desc;\n  ObitOTFArrayGeom* geom;\n  ofloat fblank = ObitMagicF();\n  gchar Proj[5];\n\n  /* Error checks */\n  if (err->error) goto finish;\n\n  /* Local pointers */\n  desc = in->myDesc;\n  geom = in->geom;\n  data = in->buffer+loRec*desc->lrec;  /* Appropriate offset in buffer */\n  ndetect = geom->numberDetect;        /* How many detectors */\n  ndata   = desc->numRecBuff;          /* How many data records */\n  if (in->myDesc->jlocfeed>=0) \n    incfeed = in->myDesc->incfeed / in->myDesc->incdatawt;\n  else incfeed = 1;  /* This is probably a bad sign */\n\n  /* Get Model center */\n  RACenter  = image->myDesc->crval[0];\n  DecCenter = image->myDesc->crval[1];\n  strncpy (Proj, &image->myDesc->ctype[0][4], 5);\n  proj      = ObitOTFSkyModelProj (Proj);\n  incdatawt = desc->incdatawt; /* increment in data-wt axis */\n\n  /* Is this CCB beamswitched data? */\n  CCBBS = (in->myDesc->OTFType==OBIT_GBTOTF_CCB) &&\n    (in->myDesc->jlocstate>=0) &&\n    (in->myDesc->inaxes[in->myDesc->jlocstate]==1);\n\n  ffact = factor;\n\n  /* Loop over data records */\n  for (i=loRec; i<hiRec; i++) {\n\n    /* Get Sky locations of the data projected onto the image */\n    ObitOTFArrayGeomProj(geom, data[desc->ilocra], data[desc->ilocdec], \n\t\t\t data[desc->ilocrot], RACenter, DecCenter, proj, \n\t\t\t xpos, ypos);\n\n    /* Loop over the array */\n    for (j=0; j<ndetect; j++) {\n      \n     /* Interpolate - use coordinates on a flat plane at the tangent point of the image \n\t xpos and ypos are offsets from the image center projected onto the plane \n\t of the image, ObitFInterpolateOffset does a linear approximation. */\n       coord[0] = xpos[j];  /* + RACenter; */\n       coord[1] = ypos[j];  /* + DecCenter; */\n       value = ObitFInterpolateOffset (image, coord, err); \n\n       /* debug \n       if ((fabs(data[desc->ilocdata+j]-value*ffact)>1.0)  && (j<=3)) {\n\t fprintf (stderr,\"debugSig: val %g pos %lf %lf in data %f %f pos %f %f\\n\", \n\t\t value, coord[0]*3600.0, coord[1]*3600.0, \n\t\t data[desc->ilocdata+j*incdatawt], (data[desc->ilocdata+j*incdatawt]-value*ffact),\n\t\t data[desc->ilocra], data[desc->ilocdec]);\n       } */\n       /* debug  \n       if ((fabs(coord[0])<0.0014) && (fabs(coord[1])<0.0014) && (j<=3)) {\n\t fprintf (stderr,\"debugSig: val %g pos %lf %lf in data %f %f pos %f %f\\n\", \n\t\t value, coord[0]*3600.0, coord[1]*3600.0, \n\t\t data[desc->ilocdata+j*incdatawt], (data[desc->ilocdata+j*incdatawt]-value*ffact),\n\t\t data[desc->ilocra], data[desc->ilocdec]);\n      }*/\n      /* debug  \n      if (value>0.2) {\n\tfprintf (stderr,\"debug: val %g pos %lf %lf in data %f %f pos %f %f\\n\", \n\t\t value, coord[0]*3600.0, coord[1]*3600.0, \n\t\t data[desc->ilocdata], factor*(data[desc->ilocdata]-value),\n\t\t data[desc->ilocra], data[desc->ilocdec]);\n      }*/\n\n      /* Subtract */\n      if ((value!=fblank) && (data[desc->ilocdata+j*incdatawt]!=fblank))\n\tdata[desc->ilocdata+j*incdatawt] -= value * ffact;\n      else {\n\tdata[desc->ilocdata+j*incdatawt] = fblank;\n      }\n\n      /* For CCB beamswitched data add value corresponding to this feeds\n       reference beam */\n      if (CCBBS) {\n\t/* is this the reference or signal beam? */\n\titemp = j / incfeed;\n\t/* itemp odd means reference beam */\n\tisRef = itemp != 2*(itemp/2);\n\t/* Use feed offset for feed 1 if this is reference, else feed 2 */\n\tif (isRef) itemp = 0;\n\telse itemp = incfeed;\n\t/* interpolate */\n\tcoord[0] = xpos[itemp]; /* + RACenter; */\n\tcoord[1] = ypos[itemp]; /* + DecCenter; */\n\tvalue = ObitFInterpolateOffset (image, coord, err);\n       /* debug \n       if ((fabs(data[desc->ilocdata+j*incdatawt]+value*ffact)>1.0)  && (j<=3)) {\n\t fprintf (stderr,\"debugRef: val %g pos %lf %lf in data %f %f pos %f %f\\n\", \n\t\t value, coord[0]*3600.0, coord[1]*3600.0, \n\t\t data[desc->ilocdata+j*incdatawt], (data[desc->ilocdata+j*incdatawt]+value*ffact),\n\t\t data[desc->ilocra], data[desc->ilocdec]);\n       } */\n       /* debug \n       if ((fabs(coord[0])<0.0014) && (fabs(coord[1])<0.0014) && (j<=3)) {\n\t fprintf (stderr,\"debugRef: val %g pos %lf %lf in data %f %f pos %f %f\\n\", \n\t\t value, coord[0]*3600.0, coord[1]*3600.0, \n\t\t data[desc->ilocdata+j*incdatawt], (data[desc->ilocdata+j*incdatawt]+value*ffact),\n\t\t data[desc->ilocra], data[desc->ilocdec]);\n       } */\n       /* Add */\n       if ((value!=fblank) && (data[desc->ilocdata+j*incdatawt]!=fblank))\n\t data[desc->ilocdata+j*incdatawt] += value * ffact;\n       else {\n\t data[desc->ilocdata+j*incdatawt] = fblank;\n       }\n      }  /* end adding to reference beam position */\n      \n    } /* end loop over array */\n    data += desc->lrec; /* update buffer pointer */\n  } /* end loop over buffer */\n  \n  /* Indicate completion */\n finish: \n  if (largs->ithread>=0)\n    ObitThreadPoolDone (in->thread, (gpointer)&largs->ithread);\n\n  return NULL;\n} /* end ThreadOTFUtilSubImageBuff */\n\n/**\n * Make arguments for Threaded OTFUtilSubImageBuff\n * \\param in         OTF with internal buffer to be modified.\n * \\param sky        OTFSkyModel to subtract.\n * \\param factor     Scaling factor for sky model.\n * \\param err        Obit error stack object.\n * \\param args       Created array of SubImageFuncArg, \n *                   delete with KillOTFUtilSubImageArgs\n * \\return number of elements in args.\n */\nstatic olong MakeOTFUtilSubImageArgs (ObitOTF *in, ObitErr *err, \n\t\t\t\t      SubImageFuncArg ***args)\n{\n  olong i, nThreads, ndetect;\n\n  /* Setup for threading */\n  /* How many threads? */\n  nThreads = MAX (1, ObitThreadNumProc(in->thread));\n\n  /* Initialize threadArg array */\n  *args = g_malloc0(nThreads*sizeof(SubImageFuncArg*));\n  for (i=0; i<nThreads; i++) \n    (*args)[i] = g_malloc0(sizeof(SubImageFuncArg)); \n  \n  ndetect = in->geom->numberDetect;    /* How many detectors */\n\n  for (i=0; i<nThreads; i++) {\n    (*args)[i]->otfdata = in;\n    (*args)[i]->ithread = i;\n    (*args)[i]->err     = err;\n    (*args)[i]->Interp  = NULL;\n    (*args)[i]->factor  = 1.0;\n    (*args)[i]->xpos    = g_malloc0(ndetect*sizeof(ofloat));\n    (*args)[i]->ypos    = g_malloc0(ndetect*sizeof(ofloat));\n  }\n\n  return nThreads;\n} /*  end MakeOTFUtilSubImageArgs */\n\n/**\n * Delete arguments for Threaded OTFUtilSubImageBuff\n * \\param nargs      number of elements in args.\n * \\param args       Array of SubImageFuncArg, type SubImageFuncArg\n */\nstatic void KillOTFUtilSubImageArgs (olong nargs, SubImageFuncArg **args)\n{\n  olong i;\n\n  if (args==NULL) return;\n  for (i=0; i<nargs; i++) {\n    if (args[i]) {\n      if (args[i]->Interp) ObitFInterpolateUnref(args[i]->Interp);\n      if (args[i]->xpos) g_free (args[i]->xpos);\n      if (args[i]->ypos) g_free (args[i]->ypos);\n      g_free(args[i]);\n    }\n  }\n  g_free(args);\n} /*  end KillOTFUtilSubImageArgs */\n", "meta": {"hexsha": "99393b58e907e70d5fe8eb6930f951604109a402", "size": 77681, "ext": "c", "lang": "C", "max_stars_repo_path": "ObitSystem/ObitSD/src/ObitOTFUtil.c", "max_stars_repo_name": "sarrvesh/Obit", "max_stars_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-08-26T06:53:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-20T01:08:59.000Z", "max_issues_repo_path": "ObitSystem/ObitSD/src/ObitOTFUtil.c", "max_issues_repo_name": "sarrvesh/Obit", "max_issues_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ObitSystem/ObitSD/src/ObitOTFUtil.c", "max_forks_repo_name": "sarrvesh/Obit", "max_forks_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-08-29T15:12:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:16:08.000Z", "avg_line_length": 34.632634864, "max_line_length": 92, "alphanum_fraction": 0.6332693966, "num_tokens": 25323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2598256264980406, "lm_q2_score": 0.02800751979467656, "lm_q1q2_score": 0.00727707137730811}}
{"text": "/*\nFRACTAL - A program growing fractals to benchmark parallelization and drawing\nlibraries.\n\nCopyright 2009-2021, Javier Burguete Tolosa.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\n  list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice,\n  this list of conditions and the following disclaimer in the documentation\n  and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``AS IS'' AND ANY EXPRESS\nOR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\nEVENT SHALL Javier Burguete Tolosa OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\nINDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\nBUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\nADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n/**\n * \\file main.c\n * \\brief Source file to define the main function.\n * \\author Javier Burguete Tolosa.\n * \\copyright Copyright 2009-2021, Javier Burguete Tolosa.\n */\n#define _GNU_SOURCE\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <time.h>\n#include <unistd.h>\n#include <libintl.h>\n#include <gsl/gsl_rng.h>\n#include <glib.h>\n#include <png.h>\n#include <ft2build.h>\n#include FT_FREETYPE_H\n#include <gtk/gtk.h>\n#include <GL/glew.h>\n#if HAVE_FREEGLUT\n#include <GL/freeglut.h>\n#elif HAVE_SDL\n#include <SDL.h>\n#elif HAVE_GLFW\n#include <GLFW/glfw3.h>\n#endif\n\n#include \"config.h\"\n#include \"fractal.h\"\n#include \"image.h\"\n#include \"text.h\"\n#include \"graphic.h\"\n#include \"draw.h\"\n#include \"simulator.h\"\n\n#if HAVE_SDL\nSDL_Window *window;             ///< SDL window.\n#elif HAVE_GLFW\nGLFWwindow *window;             ///< GLFW window.\n#endif\n\n/**\n * Function to do one main loop iteration.\n */\nvoid\nmain_iteration ()\n{\n  GMainContext *context;\n  context = g_main_context_default ();\n  while (g_main_context_pending (context))\n    g_main_context_iteration (context, 0);\n}\n\n/**\n * Function to do the main loop.\n */\nvoid\nmain_loop ()\n{\n\n#if HAVE_FREEGLUT\n\n  // Passing the GTK+ signals to the FreeGLUT main loop\n  glutIdleFunc (main_iteration);\n  // Setting our draw resize function as the FreeGLUT reshape function\n  glutReshapeFunc (draw_resize);\n  // Setting our draw function as the FreeGLUT display function\n  glutDisplayFunc (draw);\n  // FreeGLUT main loop\n  glutMainLoop ();\n\n#elif HAVE_SDL\n\n  SDL_Event event[1];\n  while (1)\n    {\n      main_iteration ();\n      while (SDL_PollEvent (event))\n        {\n          if (event->type == SDL_QUIT)\n            return;\n          if (event->type == SDL_WINDOWEVENT\n              && event->window.event == SDL_WINDOWEVENT_SIZE_CHANGED)\n            draw_resize (event->window.data1, event->window.data2);\n        }\n      draw ();\n    }\n\n#elif HAVE_GLFW\n\n  while (!glfwWindowShouldClose (window))\n    {\n      main_iteration ();\n      glfwPollEvents ();\n      draw ();\n    }\n\n#else\n\n  g_main_loop_run (dialog_simulator->loop);\n  g_main_loop_unref (dialog_simulator->loop);\n\n#endif\n}\n\n/**\n * Main function.\n *\n * \\return 0 on success.\n */\nint\nmain (int argn,                 ///< Arguments number.\n      char **argc)              ///< Array of arguments.\n{\n  if (argn > 2)\n    {\n      printf (\"Bad arguments number\\n\");\n      return 1;\n    }\n\n// PARALELLIZING INIT\n  nthreads = threads_number ();\n// END\n\n  // Initing locales\n#if DEBUG\n  printf (\"Initing locales\\n\");\n  fflush (stdout);\n#endif\n  bindtextdomain (\"fractal\", \"./po\");\n  bind_textdomain_codeset (\"fractal\", \"UTF-8\");\n  textdomain (\"fractal\");\n\n  // Initing graphic window\n#if HAVE_FREEGLUT\n\n#if DEBUG\n  printf (\"Initing FreeGLUT window\\n\");\n  fflush (stdout);\n#endif\n  glutInit (&argn, argc);\n  glutInitDisplayMode (GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);\n  glutInitWindowSize (window_width, window_height);\n  glutCreateWindow (\"fractal\");\n\n#elif HAVE_SDL\n\n#if DEBUG\n  printf (\"Initing SDL window\\n\");\n  fflush (stdout);\n#endif\n  SDL_Init (SDL_INIT_VIDEO);\n  window = SDL_CreateWindow (\"fractal\",\n                             SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,\n                             window_width, window_height,\n                             SDL_WINDOW_RESIZABLE | SDL_WINDOW_OPENGL);\n  if (!window)\n    {\n      printf (\"ERROR! unable to create the window: %s\\n\", SDL_GetError ());\n      return 1;\n    }\n  SDL_GL_SetAttribute (SDL_GL_CONTEXT_MAJOR_VERSION, 2);\n  if (!SDL_GL_CreateContext (window))\n    {\n      printf (\"ERROR! SDL_GL_CreateContext: %s\\n\", SDL_GetError ());\n      return 1;\n    }\n\n#elif HAVE_GLFW\n\n#if DEBUG\n  printf (\"Initing GLFW window\\n\");\n  fflush (stdout);\n#endif\n  if (!glfwInit ())\n    {\n      printf (\"ERROR! unable to init GLFW\\n\");\n      return 1;\n    }\n  window\n    = glfwCreateWindow (window_width, window_height, \"fractal\", NULL, NULL);\n  if (!window)\n    {\n      printf (\"ERROR! unable to open the window\\n\");\n      glfwTerminate ();\n      return 1;\n    }\n  glfwMakeContextCurrent (window);\n\n#endif\n\n  // Initing GTK+\n#if DEBUG\n  printf (\"Initing GTK+\\n\");\n  fflush (stdout);\n#endif\n#if !GTK4\n  gtk_init (&argn, &argc);\n#else\n  gtk_init ();\n#endif\n\n  // Creating the main GTK+ window\n#if DEBUG\n  printf (\"Creating simulator dialog\\n\");\n  fflush (stdout);\n#endif\n  dialog_simulator_create ();\n\n#if !HAVE_GTKGLAREA\n  // Initing drawing data\n#if DEBUG\n  printf (\"Initing drawing data\\n\");\n  fflush (stdout);\n#endif\n  if (!graphic_init (graphic, \"logo.png\"))\n    return 1;\n#endif\n\n  // Opening input file\n  if (argn == 2 && !fractal_input (argc[1]))\n    return 1;\n\n  // Updating view\n  if (argn == 2)\n    fractal ();\n  dialog_simulator_update ();\n\n  // Main loop\n#if DEBUG\n  printf (\"Main loop\\n\");\n  fflush (stdout);\n#endif\n  main_loop ();\n\n  // Freeing memory\n#if HAVE_GLFW\n  glfwDestroyWindow (window);\n  glfwTerminate ();\n#endif\n  graphic_destroy (graphic);\n\n  return 0;\n}\n", "meta": {"hexsha": "0bd54742e6280c7d7799d360aa5ced7bf6310349", "size": 6308, "ext": "c", "lang": "C", "max_stars_repo_path": "3.4.15/main.c", "max_stars_repo_name": "jburguete/fractal", "max_stars_repo_head_hexsha": "95d711dcb7b385556fb77794bc01737b21e99774", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "3.4.15/main.c", "max_issues_repo_name": "jburguete/fractal", "max_issues_repo_head_hexsha": "95d711dcb7b385556fb77794bc01737b21e99774", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3.4.15/main.c", "max_forks_repo_name": "jburguete/fractal", "max_forks_repo_head_hexsha": "95d711dcb7b385556fb77794bc01737b21e99774", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0218978102, "max_line_length": 79, "alphanum_fraction": 0.6777108434, "num_tokens": 1571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24798743735585305, "lm_q2_score": 0.02931223287127187, "lm_q1q2_score": 0.0072690655129247096}}
{"text": "/*\nMIT License\n\nCopyright (c) 2020 Huy Vo\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n#ifndef PACMENSL_UTIL_H\n#define PACMENSL_UTIL_H\n\n#define ARMA_DONT_PRINT_ERRORS\n#define ARMA_DONT_USE_WRAPPER\n#include <armadillo>\n#include <petscmat.h>\n#include <petscvec.h>\n#include <petscao.h>\n#include <petscis.h>\n#include <petscistypes.h>\n#include <petscoptions.h>\n#include <petsc.h>\n#include <petscsys.h>\n#include <petscconf.h>\n#include <cassert>\n#include <memory>\n#include <mpi.h>\n#include <zoltan.h>\n#include <parmetis.h>\n#include <string>\n#include <sstream>\n#include \"ErrorHandling.h\"\n\n#define NOT_COPYABLE_NOT_MOVABLE(object)\\\n            object( const object & ) = delete;\\\n            object &operator=( const object & ) = delete;\\\n\nnamespace pacmensl {\n#define SQR1 sqrt(0.1e0)\n\n/*! Round to 2 significant digits\n */\ndouble round2digit(double x);\n\n/*! Initialize and finalize Parallel context\n *\n */\nint PACMENSLInit(int *argc, char ***argv, const char *help);\n\nint PACMENSLFinalize();\n\nvoid sequential_action(MPI_Comm comm, std::function<void(void *)> action, void *data);\n\nclass Environment {\n public:\n  Environment();\n\n  Environment(int *argc, char ***argv, const char *help);\n\n  ~Environment();\n\n private:\n  bool initialized = false;\n  bool init_petsc = false; // If PETSc or MPI were already set, we do not meddle with them\n  bool init_mpi = false;\n};\n}\n\n#endif", "meta": {"hexsha": "cee8004f1d47891a82f68449491ad8059afab254", "size": 2347, "ext": "h", "lang": "C", "max_stars_repo_path": "src/Sys/Sys.h", "max_stars_repo_name": "voduchuy/pacmensl", "max_stars_repo_head_hexsha": "d35adb165caef5c8fa992be6fda16e1bfb1dfd4a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Sys/Sys.h", "max_issues_repo_name": "voduchuy/pacmensl", "max_issues_repo_head_hexsha": "d35adb165caef5c8fa992be6fda16e1bfb1dfd4a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Sys/Sys.h", "max_forks_repo_name": "voduchuy/pacmensl", "max_forks_repo_head_hexsha": "d35adb165caef5c8fa992be6fda16e1bfb1dfd4a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2771084337, "max_line_length": 90, "alphanum_fraction": 0.7533020878, "num_tokens": 554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20946968133032526, "lm_q2_score": 0.03461884207619153, "lm_q1q2_score": 0.0072515978177246955}}
{"text": "#ifndef QDM_CONFIG_H\n#define QDM_CONFIG_H 1\n\n#include <gsl/gsl_vector.h>\n\ntypedef struct {\n  unsigned long int rng_seed;\n\n  int acc_check;\n\n  int burn_discovery;\n  int iter_discovery;\n\n  int burn_analysis;\n  int iter_analysis;\n\n  int knot_try;\n  int spline_df;\n  int thin;\n\n  gsl_vector *months;\n  gsl_vector *knots;\n\n  gsl_vector *tau_highs;\n  gsl_vector *tau_lows;\n\n  double theta_min;\n  double theta_tune_sd;\n\n  double xi_high;\n  double xi_low;\n  double xi_prior_mean;\n  double xi_prior_var;\n  double xi_tune_sd;\n\n  double bound;\n\n  int debug;\n  int tau_table;\n} qdm_config;\n\nint\nqdm_config_read(\n    qdm_config **config,\n    const char *file_path,\n    const char *group_path\n);\n\nvoid\nqdm_config_fwrite(\n    FILE *f,\n    const qdm_config *cfg\n);\n\n#endif /* QDM_CONFIG_H */\n", "meta": {"hexsha": "ac87f7457db956153ad35d6baf6ad5d4e55c9386", "size": 776, "ext": "h", "lang": "C", "max_stars_repo_path": "include/qdm/config.h", "max_stars_repo_name": "calebcase/qdm", "max_stars_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/qdm/config.h", "max_issues_repo_name": "calebcase/qdm", "max_issues_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-03-06T18:09:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-22T20:22:53.000Z", "max_forks_repo_path": "include/qdm/config.h", "max_forks_repo_name": "calebcase/qdm", "max_forks_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.8571428571, "max_line_length": 29, "alphanum_fraction": 0.7152061856, "num_tokens": 221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.2538610069692489, "lm_q2_score": 0.028436034074054463, "lm_q1q2_score": 0.00721880024425134}}
{"text": "#include <stdio.h>\n#include <stdarg.h>\n#include <string.h>\n#include <math.h>\n#include <gbpLib.h>\n#include <gbpRNG.h>\n#include <gbpMCMC.h>\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_fit.h>\n#include <gsl/gsl_interp.h>\n\nvoid free_MCMC_arrays(MCMC_info *MCMC) {\n    int           i_DS;\n    MCMC_DS_info *current_DS;\n    MCMC_DS_info *next_DS;\n\n    if(MCMC->n_M != NULL) {\n        SID_log(\"Freeing MCMC target arrays for %d dataset(s)...\", SID_LOG_OPEN, MCMC->n_DS);\n\n        // Free chain arrays\n        i_DS       = 0;\n        current_DS = MCMC->DS;\n        while(current_DS != NULL) {\n            next_DS = current_DS->next;\n            SID_free(SID_FARG MCMC->M_new[i_DS]);\n            SID_free(SID_FARG MCMC->M_last[i_DS]);\n            current_DS = next_DS;\n            i_DS++;\n        }\n        SID_free(SID_FARG MCMC->n_M);\n        SID_free(SID_FARG MCMC->M_new);\n        SID_free(SID_FARG MCMC->M_last);\n        MCMC->n_M_total = 0;\n\n        // Free results arrays\n        SID_free(SID_FARG MCMC->P_min);\n        SID_free(SID_FARG MCMC->P_max);\n        SID_free(SID_FARG MCMC->P_avg);\n        SID_free(SID_FARG MCMC->dP_avg);\n        SID_free(SID_FARG MCMC->P_best);\n        SID_free(SID_FARG MCMC->P_peak);\n        SID_free(SID_FARG MCMC->P_lo_68);\n        SID_free(SID_FARG MCMC->P_hi_68);\n        SID_free(SID_FARG MCMC->P_lo_95);\n        SID_free(SID_FARG MCMC->P_hi_95);\n\n        SID_free(SID_FARG MCMC->ln_likelihood_DS);\n        SID_free(SID_FARG MCMC->ln_likelihood_DS_best);\n        SID_free(SID_FARG MCMC->ln_likelihood_DS_peak);\n        SID_free(SID_FARG MCMC->n_DoF_DS);\n        SID_free(SID_FARG MCMC->n_DoF_DS_best);\n        SID_free(SID_FARG MCMC->n_DoF_DS_peak);\n\n        // These only need to be deallocated if we are using MCMC_MODE_MINIMIZE_IO\n        if(SID_CHECK_BITFIELD_SWITCH(MCMC->mode, MCMC_MODE_MINIMIZE_IO)) {\n            SID_free(SID_FARG MCMC->flag_success_buffer);\n            SID_free(SID_FARG MCMC->ln_likelihood_new_buffer);\n            SID_free(SID_FARG MCMC->P_new_buffer);\n            SID_free(SID_FARG MCMC->M_new_buffer);\n        }\n\n        SID_log(\"Done.\", SID_LOG_CLOSE);\n    }\n}\n", "meta": {"hexsha": "852e847540704dd0cf0bdcd38208c6a471a01caf", "size": 2127, "ext": "c", "lang": "C", "max_stars_repo_path": "src/gbpMath/gbpMCMC/free_MCMC_arrays.c", "max_stars_repo_name": "gbpoole/gbpCode", "max_stars_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-10-20T11:39:53.000Z", "max_stars_repo_stars_event_max_datetime": "2015-10-20T11:39:53.000Z", "max_issues_repo_path": "src/gbpMath/gbpMCMC/free_MCMC_arrays.c", "max_issues_repo_name": "gbpoole/gbpCode", "max_issues_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-07-30T11:10:49.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-18T00:40:46.000Z", "max_forks_repo_path": "src/gbpMath/gbpMCMC/free_MCMC_arrays.c", "max_forks_repo_name": "gbpoole/gbpCode", "max_forks_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-01-23T00:50:40.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-01T08:14:24.000Z", "avg_line_length": 32.7230769231, "max_line_length": 93, "alphanum_fraction": 0.6271744241, "num_tokens": 667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2942149845400438, "lm_q2_score": 0.024423090320390247, "lm_q1q2_score": 0.00718563914103371}}
{"text": "/* matrix/gsl_matrix_short.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_MATRIX_SHORT_H__\n#define __GSL_MATRIX_SHORT_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_vector_short.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size1;\n  size_t size2;\n  size_t tda;\n  short * data;\n  gsl_block_short * block;\n  int owner;\n} gsl_matrix_short;\n\ntypedef struct\n{\n  gsl_matrix_short matrix;\n} _gsl_matrix_short_view;\n\ntypedef _gsl_matrix_short_view gsl_matrix_short_view;\n\ntypedef struct\n{\n  gsl_matrix_short matrix;\n} _gsl_matrix_short_const_view;\n\ntypedef const _gsl_matrix_short_const_view gsl_matrix_short_const_view;\n\n/* Allocation */\n\nGSL_EXPORT\ngsl_matrix_short *\ngsl_matrix_short_alloc (const size_t n1, const size_t n2);\n\nGSL_EXPORT\ngsl_matrix_short *\ngsl_matrix_short_calloc (const size_t n1, const size_t n2);\n\nGSL_EXPORT\ngsl_matrix_short *\ngsl_matrix_short_alloc_from_block (gsl_block_short * b,\n                                   const size_t offset,\n                                   const size_t n1,\n                                   const size_t n2,\n                                   const size_t d2);\n\nGSL_EXPORT\ngsl_matrix_short *\ngsl_matrix_short_alloc_from_matrix (gsl_matrix_short * m,\n                                    const size_t k1,\n                                    const size_t k2,\n                                    const size_t n1,\n                                    const size_t n2);\n\nGSL_EXPORT\ngsl_vector_short *\ngsl_vector_short_alloc_row_from_matrix (gsl_matrix_short * m,\n                                        const size_t i);\n\nGSL_EXPORT\ngsl_vector_short *\ngsl_vector_short_alloc_col_from_matrix (gsl_matrix_short * m,\n                                        const size_t j);\n\nGSL_EXPORT void gsl_matrix_short_free (gsl_matrix_short * m);\n\n/* Views */\n\nGSL_EXPORT\n_gsl_matrix_short_view\ngsl_matrix_short_submatrix (gsl_matrix_short * m,\n                            const size_t i, const size_t j,\n                            const size_t n1, const size_t n2);\n\nGSL_EXPORT\n_gsl_vector_short_view\ngsl_matrix_short_row (gsl_matrix_short * m, const size_t i);\n\nGSL_EXPORT\n_gsl_vector_short_view\ngsl_matrix_short_column (gsl_matrix_short * m, const size_t j);\n\nGSL_EXPORT\n_gsl_vector_short_view\ngsl_matrix_short_diagonal (gsl_matrix_short * m);\n\nGSL_EXPORT\n_gsl_vector_short_view\ngsl_matrix_short_subdiagonal (gsl_matrix_short * m, const size_t k);\n\nGSL_EXPORT\n_gsl_vector_short_view\ngsl_matrix_short_superdiagonal (gsl_matrix_short * m, const size_t k);\n\nGSL_EXPORT\n_gsl_matrix_short_view\ngsl_matrix_short_view_array (short * base,\n                             const size_t n1,\n                             const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_short_view\ngsl_matrix_short_view_array_with_tda (short * base,\n                                      const size_t n1,\n                                      const size_t n2,\n                                      const size_t tda);\n\n\nGSL_EXPORT\n_gsl_matrix_short_view\ngsl_matrix_short_view_vector (gsl_vector_short * v,\n                              const size_t n1,\n                              const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_short_view\ngsl_matrix_short_view_vector_with_tda (gsl_vector_short * v,\n                                       const size_t n1,\n                                       const size_t n2,\n                                       const size_t tda);\n\n\nGSL_EXPORT\n_gsl_matrix_short_const_view\ngsl_matrix_short_const_submatrix (const gsl_matrix_short * m,\n                                  const size_t i, const size_t j,\n                                  const size_t n1, const size_t n2);\n\nGSL_EXPORT\n_gsl_vector_short_const_view\ngsl_matrix_short_const_row (const gsl_matrix_short * m,\n                            const size_t i);\n\nGSL_EXPORT\n_gsl_vector_short_const_view\ngsl_matrix_short_const_column (const gsl_matrix_short * m,\n                               const size_t j);\n\nGSL_EXPORT\n_gsl_vector_short_const_view\ngsl_matrix_short_const_diagonal (const gsl_matrix_short * m);\n\nGSL_EXPORT\n_gsl_vector_short_const_view\ngsl_matrix_short_const_subdiagonal (const gsl_matrix_short * m,\n                                    const size_t k);\n\nGSL_EXPORT\n_gsl_vector_short_const_view\ngsl_matrix_short_const_superdiagonal (const gsl_matrix_short * m,\n                                      const size_t k);\n\nGSL_EXPORT\n_gsl_matrix_short_const_view\ngsl_matrix_short_const_view_array (const short * base,\n                                   const size_t n1,\n                                   const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_short_const_view\ngsl_matrix_short_const_view_array_with_tda (const short * base,\n                                            const size_t n1,\n                                            const size_t n2,\n                                            const size_t tda);\n\nGSL_EXPORT\n_gsl_matrix_short_const_view\ngsl_matrix_short_const_view_vector (const gsl_vector_short * v,\n                                    const size_t n1,\n                                    const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_short_const_view\ngsl_matrix_short_const_view_vector_with_tda (const gsl_vector_short * v,\n                                             const size_t n1,\n                                             const size_t n2,\n                                             const size_t tda);\n\n/* Operations */\n\nGSL_EXPORT short   gsl_matrix_short_get(const gsl_matrix_short * m, const size_t i, const size_t j);\nGSL_EXPORT void    gsl_matrix_short_set(gsl_matrix_short * m, const size_t i, const size_t j, const short x);\n\nGSL_EXPORT short * gsl_matrix_short_ptr(gsl_matrix_short * m, const size_t i, const size_t j);\nGSL_EXPORT const short * gsl_matrix_short_const_ptr(const gsl_matrix_short * m, const size_t i, const size_t j);\n\nGSL_EXPORT void gsl_matrix_short_set_zero (gsl_matrix_short * m);\nGSL_EXPORT void gsl_matrix_short_set_identity (gsl_matrix_short * m);\nGSL_EXPORT void gsl_matrix_short_set_all (gsl_matrix_short * m, short x);\n\nGSL_EXPORT int gsl_matrix_short_fread (FILE * stream, gsl_matrix_short * m) ;\nGSL_EXPORT int gsl_matrix_short_fwrite (FILE * stream, const gsl_matrix_short * m) ;\nGSL_EXPORT int gsl_matrix_short_fscanf (FILE * stream, gsl_matrix_short * m);\nGSL_EXPORT int gsl_matrix_short_fprintf (FILE * stream, const gsl_matrix_short * m, const char * format);\n\nGSL_EXPORT int gsl_matrix_short_memcpy(gsl_matrix_short * dest, const gsl_matrix_short * src);\nGSL_EXPORT int gsl_matrix_short_swap(gsl_matrix_short * m1, gsl_matrix_short * m2);\n\nGSL_EXPORT int gsl_matrix_short_swap_rows(gsl_matrix_short * m, const size_t i, const size_t j);\nGSL_EXPORT int gsl_matrix_short_swap_columns(gsl_matrix_short * m, const size_t i, const size_t j);\nGSL_EXPORT int gsl_matrix_short_swap_rowcol(gsl_matrix_short * m, const size_t i, const size_t j);\nGSL_EXPORT int gsl_matrix_short_transpose (gsl_matrix_short * m);\nGSL_EXPORT int gsl_matrix_short_transpose_memcpy (gsl_matrix_short * dest, const gsl_matrix_short * src);\n\nGSL_EXPORT short gsl_matrix_short_max (const gsl_matrix_short * m);\nGSL_EXPORT short gsl_matrix_short_min (const gsl_matrix_short * m);\nGSL_EXPORT void gsl_matrix_short_minmax (const gsl_matrix_short * m, short * min_out, short * max_out);\n\nGSL_EXPORT void gsl_matrix_short_max_index (const gsl_matrix_short * m, size_t * imax, size_t *jmax);\nGSL_EXPORT void gsl_matrix_short_min_index (const gsl_matrix_short * m, size_t * imin, size_t *jmin);\nGSL_EXPORT void gsl_matrix_short_minmax_index (const gsl_matrix_short * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);\n\nGSL_EXPORT int gsl_matrix_short_isnull (const gsl_matrix_short * m);\n\nGSL_EXPORT int gsl_matrix_short_add (gsl_matrix_short * a, const gsl_matrix_short * b);\nGSL_EXPORT int gsl_matrix_short_sub (gsl_matrix_short * a, const gsl_matrix_short * b);\nGSL_EXPORT int gsl_matrix_short_mul_elements (gsl_matrix_short * a, const gsl_matrix_short * b);\nGSL_EXPORT int gsl_matrix_short_div_elements (gsl_matrix_short * a, const gsl_matrix_short * b);\nGSL_EXPORT int gsl_matrix_short_scale (gsl_matrix_short * a, const double x);\nGSL_EXPORT int gsl_matrix_short_add_constant (gsl_matrix_short * a, const double x);\nGSL_EXPORT int gsl_matrix_short_add_diagonal (gsl_matrix_short * a, const double x);\n\n/***********************************************************************/\n/* The functions below are obsolete                                    */\n/***********************************************************************/\nGSL_EXPORT int gsl_matrix_short_get_row(gsl_vector_short * v, const gsl_matrix_short * m, const size_t i);\nGSL_EXPORT int gsl_matrix_short_get_col(gsl_vector_short * v, const gsl_matrix_short * m, const size_t j);\nGSL_EXPORT int gsl_matrix_short_set_row(gsl_matrix_short * m, const size_t i, const gsl_vector_short * v);\nGSL_EXPORT int gsl_matrix_short_set_col(gsl_matrix_short * m, const size_t j, const gsl_vector_short * v);\n\n/* inline functions if you are using GCC */\n\n#ifdef HAVE_INLINE\nextern inline\nshort\ngsl_matrix_short_get(const gsl_matrix_short * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_VAL(\"first index out of range\", GSL_EINVAL, 0) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_VAL(\"second index out of range\", GSL_EINVAL, 0) ;\n    }\n#endif\n  return m->data[i * m->tda + j] ;\n}\n\nextern inline\nvoid\ngsl_matrix_short_set(gsl_matrix_short * m, const size_t i, const size_t j, const short x)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_VOID(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_VOID(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  m->data[i * m->tda + j] = x ;\n}\n\nextern inline\nshort *\ngsl_matrix_short_ptr(gsl_matrix_short * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  return (short *) (m->data + (i * m->tda + j)) ;\n}\n\nextern inline\nconst short *\ngsl_matrix_short_const_ptr(const gsl_matrix_short * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  return (const short *) (m->data + (i * m->tda + j)) ;\n}\n\n#endif\n\n__END_DECLS\n\n#endif /* __GSL_MATRIX_SHORT_H__ */\n", "meta": {"hexsha": "ab72bd196f23b47dc0ee1b64bd2d9a39432fadba", "size": 11588, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/gsl/include/gsl/gsl_matrix_short.h", "max_stars_repo_name": "dynaryu/vaws", "max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/gsl/include/gsl/gsl_matrix_short.h", "max_issues_repo_name": "dynaryu/vaws", "max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/gsl/include/gsl/gsl_matrix_short.h", "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7842565598, "max_line_length": 135, "alphanum_fraction": 0.6796686227, "num_tokens": 2787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2974699426047947, "lm_q2_score": 0.024053550489520677, "lm_q1q2_score": 0.007155208283559247}}
{"text": "#ifndef __GSL_VECTOR_H__\n#define __GSL_VECTOR_H__\n\n#include <gsl/gsl_vector_complex_long_double.h>\n#include <gsl/gsl_vector_complex_double.h>\n#include <gsl/gsl_vector_complex_float.h>\n\n#include <gsl/gsl_vector_long_double.h>\n#include <gsl/gsl_vector_double.h>\n#include <gsl/gsl_vector_float.h>\n\n#include <gsl/gsl_vector_ulong.h>\n#include <gsl/gsl_vector_long.h>\n\n#include <gsl/gsl_vector_uint.h>\n#include <gsl/gsl_vector_int.h>\n\n#include <gsl/gsl_vector_ushort.h>\n#include <gsl/gsl_vector_short.h>\n\n#include <gsl/gsl_vector_uchar.h>\n#include <gsl/gsl_vector_char.h>\n\n\n#endif /* __GSL_VECTOR_H__ */\n", "meta": {"hexsha": "cf762e42fa949be09907f99b62ef90e9e2fede31", "size": 598, "ext": "h", "lang": "C", "max_stars_repo_path": "gsl-an/gsl/gsl_vector.h", "max_stars_repo_name": "juandesant/astrometry.net", "max_stars_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_stars_repo_licenses": ["Net-SNMP", "Xnet"], "max_stars_count": 460.0, "max_stars_repo_stars_event_min_datetime": "2015-01-06T13:20:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T00:37:55.000Z", "max_issues_repo_path": "gsl-an/gsl/gsl_vector.h", "max_issues_repo_name": "juandesant/astrometry.net", "max_issues_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_issues_repo_licenses": ["Net-SNMP", "Xnet"], "max_issues_count": 208.0, "max_issues_repo_issues_event_min_datetime": "2015-01-08T20:26:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T15:21:34.000Z", "max_forks_repo_path": "gsl-an/gsl/gsl_vector.h", "max_forks_repo_name": "juandesant/astrometry.net", "max_forks_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_forks_repo_licenses": ["Net-SNMP", "Xnet"], "max_forks_count": 173.0, "max_forks_repo_forks_event_min_datetime": "2015-01-08T18:01:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T07:27:04.000Z", "avg_line_length": 23.0, "max_line_length": 47, "alphanum_fraction": 0.7976588629, "num_tokens": 170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3208213138121609, "lm_q2_score": 0.022286186472706453, "lm_q1q2_score": 0.007149883624036492}}
{"text": "#pragma once\n\n#include <cstddef> // std::byte\n#include <map>\n#include <memory> // std::align\n#include <memory_resource>\n#include <vector>\n\n#include <gsl-lite/gsl-lite.hpp>\n\n#include <cuda/runtime_api.hpp>\n\nnamespace thrustshift {\n\nnamespace pmr {\n\n//! Unified CUDA Memory Resource. Buffers cannet be deallocated partially. Alignment is ignored.\nclass managed_resource_type : public std::pmr::memory_resource {\n\tvoid* do_allocate(std::size_t bytes,\n\t                  [[maybe_unused]] std::size_t alignment) override {\n\t\tauto region = cuda::memory::managed::detail::allocate(bytes);\n\t\treturn region.get();\n\t}\n\n\tvoid do_deallocate(void* p,\n\t                   [[maybe_unused]] std::size_t bytes,\n\t                   [[maybe_unused]] std::size_t alignment) override {\n\t\tcuda::memory::managed::detail::free(p);\n\t}\n\n\tbool do_is_equal(\n\t    const std::pmr::memory_resource& other) const noexcept override {\n\t\treturn this == &other;\n\t}\n};\n\n//! Device CUDA Memory Resource. Buffers cannot be deallocated partially. Alignment is ignored.\nclass device_resource_type : public std::pmr::memory_resource {\n\tvoid* do_allocate(std::size_t bytes,\n\t                  [[maybe_unused]] std::size_t alignment) override {\n\t\tauto region = cuda::memory::device::detail::allocate(bytes);\n\t\treturn region.get();\n\t}\n\n\tvoid do_deallocate(void* p,\n\t                   [[maybe_unused]] std::size_t bytes,\n\t                   [[maybe_unused]] std::size_t alignment) override {\n\t\tcuda::memory::device::free(p);\n\t}\n\n\tbool do_is_equal(\n\t    const std::pmr::memory_resource& other) const noexcept override {\n\t\treturn this == &other;\n\t}\n};\n\nclass host_resource_type : public std::pmr::memory_resource {\n\tvoid* do_allocate(std::size_t bytes,\n\t                  [[maybe_unused]] std::size_t alignment) override {\n\t\treturn malloc(bytes);\n\t}\n\n\tvoid do_deallocate(void* p,\n\t                   [[maybe_unused]] std::size_t bytes,\n\t                   [[maybe_unused]] std::size_t alignment) override {\n\t\tfree(p);\n\t}\n\n\tbool do_is_equal(\n\t    const std::pmr::memory_resource& other) const noexcept override {\n\t\treturn this == &other;\n\t}\n};\n\nnamespace detail {\n\nstruct page_id_type {\n\tsize_t bytes;\n\tsize_t alignment;\n};\n\ninline bool operator<(const page_id_type& a, const page_id_type& b) {\n\tif (a.bytes == b.bytes) {\n\t\treturn a.alignment < b.alignment;\n\t}\n\treturn a.bytes < b.bytes;\n}\n\n} // namespace detail\n\n/*! \\brief Allocates only if requested buffer size is currently not in the free pool.\n *\n *  This pool is useful for functions, which require temporary GPU memory. The\n *  host can allocate memory via this pool, launch the kernel with the corresponding\n *  pointer and exit the function without deallocating the memory because the\n *  host is not aware about the runtime of the GPU kernel and when the kernel\n *  may read the temporary required memory. This pool should not be used if the\n *  byte size of the allocations differ often becaues every time an allocation\n *  is called it actually results into a new allocation if not the exact same\n *  size was allocated previously.\n *\n *  This class is useful if functions delegate the memory resource to other functions, which\n *  are maybe called iteratively and if the function requires different buffers of\n *  the same size.\n *\n *  \\note std::pmr compatible\n */\ntemplate <class Upstream>\nclass delayed_pool_type : public std::pmr::memory_resource {\n   private:\n\tstruct page_item_type {\n\t\tvoid* ptr;\n\t\tbool allocated;\n\t};\n\n   public:\n\tdelayed_pool_type() = default;\n\n\t~delayed_pool_type() noexcept {\n\t\tfor (auto& [page_id, book_page] : book_) {\n\t\t\tfor (auto& page_item : book_page) {\n\t\t\t\tres_.deallocate(\n\t\t\t\t    page_item.ptr, page_id.bytes, page_id.alignment);\n\t\t\t}\n\t\t}\n\t}\n\n\tauto& get_book() const {\n\t\treturn book_;\n\t}\n\n   private:\n\tvoid* do_allocate(size_t bytes, size_t alignment) override {\n\t\tif (bytes == 0) {\n\t\t\treturn nullptr;\n\t\t}\n\t\tconst detail::page_id_type page_id({bytes, alignment});\n\t\tif (auto it = book_.find(page_id); it != book_.end()) {\n\t\t\tfor (auto& page_item : it->second) {\n\t\t\t\tif (!page_item.allocated) {\n\t\t\t\t\tpage_item.allocated = true;\n\t\t\t\t\treturn page_item.ptr;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// no page item was free\n\t\t\tvoid* ptr = res_.allocate(bytes, alignment);\n\t\t\tit->second.push_back({ptr, true});\n\t\t\treturn ptr;\n\t\t}\n\t\t// the required size was never allocated before\n\t\tvoid* ptr = res_.allocate(bytes, alignment);\n\t\tbook_[page_id] = {{ptr, true}};\n\t\treturn ptr;\n\t}\n\n\tvoid do_deallocate(void* ptr,\n\t                   size_t bytes,\n\t                   size_t alignment) noexcept override {\n\t\tconst detail::page_id_type page_id({bytes, alignment});\n\t\tif (ptr == nullptr || bytes == 0) {\n\t\t\treturn;\n\t\t}\n\t\tfor (auto& page_item : book_[page_id]) {\n\t\t\tif (page_item.ptr == ptr && page_item.allocated) {\n\t\t\t\tpage_item.allocated = false;\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\t// The pointer which should be deallocated was never allocated before\n\t\tstd::terminate();\n\t}\n\n\tbool do_is_equal(\n\t    const std::pmr::memory_resource& other) const noexcept override {\n\t\treturn this == &other;\n\t}\n\n\tUpstream res_;\n\t// size in bytes -> (ptr, alignment)\n\tstd::map<detail::page_id_type, std::vector<page_item_type>> book_;\n};\n\n/*! \\brief Allocates only if there is no buffer in the free pool which is of the required size or larger.\n *\n *  This pool searches for the smallest buffer in the pool which has the required alignment and is\n *  of equal or larger byte size than the required buffer and returns that buffer if do_allocate is called.\n *  Morevover, this pool has the same 'delayed' properties than the `delayed_pool_type`.\n *\n *  \\sa delayed_pool_type\n *  \\note std::pmr compatible\n */\ntemplate <class Upstream>\nclass delayed_fragmenting_pool_type : public std::pmr::memory_resource {\n   private:\n\tstruct page_item_type {\n\t\tvoid* ptr;\n\t\tbool allocated;\n\t};\n\n   public:\n\tdelayed_fragmenting_pool_type() = default;\n\n\t~delayed_fragmenting_pool_type() noexcept {\n\t\tfor (auto& [page_id, book_page] : book_) {\n\t\t\tfor (auto& page_item : book_page) {\n\t\t\t\tres_.deallocate(\n\t\t\t\t    page_item.ptr, page_id.bytes, page_id.alignment);\n\t\t\t}\n\t\t}\n\t}\n\n\tauto& get_book() const {\n\t\treturn book_;\n\t}\n\n   private:\n\tvoid* do_allocate(size_t bytes, size_t alignment) override {\n\t\tif (bytes == 0) {\n\t\t\treturn nullptr;\n\t\t}\n\t\tconst detail::page_id_type page_id({bytes, alignment});\n\t\tfor (auto& [k, v] : book_) {\n\t\t\tif (k.alignment == alignment && k.bytes >= bytes) {\n\t\t\t\tfor (auto& p : v) {\n\t\t\t\t\tif (!p.allocated) {\n\t\t\t\t\t\tp.allocated = true;\n\t\t\t\t\t\treturn p.ptr;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// no page item was free\n\t\tif (auto it = book_.find(page_id); it != book_.end()) {\n\t\t\tvoid* ptr = res_.allocate(bytes, alignment);\n\t\t\tit->second.push_back({ptr, true});\n\t\t\treturn ptr;\n\t\t}\n\t\t// the required size was never allocated before\n\t\tvoid* ptr = res_.allocate(bytes, alignment);\n\t\tbook_[page_id] = {{ptr, true}};\n\t\treturn ptr;\n\t}\n\n\tvoid do_deallocate(void* ptr,\n\t                   size_t bytes,\n\t                   size_t alignment) noexcept override {\n\t\tconst detail::page_id_type page_id({bytes, alignment});\n\n\t\tif (ptr == nullptr || bytes == 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tfor (auto& [k, v] : book_) {\n\t\t\tif (k.alignment == alignment && k.bytes >= bytes) {\n\t\t\t\tfor (auto& p : v) {\n\t\t\t\t\t// no comparison based on the bytes because the buffer can be larger\n\t\t\t\t\t// than the amount of requested bytes.\n\t\t\t\t\tif (p.ptr == ptr && p.allocated) {\n\t\t\t\t\t\tp.allocated = false;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// The pointer which should be deallocated was never allocated before\n\t\tstd::terminate();\n\t}\n\n\tbool do_is_equal(\n\t    const std::pmr::memory_resource& other) const noexcept override {\n\t\treturn this == &other;\n\t}\n\n\tUpstream res_;\n\t// size in bytes -> (ptr, alignment)\n\tstd::map<detail::page_id_type, std::vector<page_item_type>> book_;\n};\n\n/*! \\brief Wraps a memory resource around an existing buffer of fixed size.\n *\n *  This class takes a pointer and a size of an existing buffer and wraps a memory\n *  resource around that buffer. The resource can provide parts of that buffer by\n *  calling `do_allocate` and simply returns subsequently aligned parts of the buffer.\n *  If the buffer size is exceeded `gsl_FailFast()` is called.\n *\n *  \\note std::pmr compatible\n */\nclass wrapping_resource_type : public std::pmr::memory_resource {\n\n   public:\n\twrapping_resource_type(void* ptr, size_t size_in_bytes)\n\t    : size_in_bytes_(size_in_bytes), ptr_(ptr) {\n\t\tstatic_assert(sizeof(std::byte) == 1);\n\t}\n\n   private:\n\tvoid* do_allocate(size_t bytes, size_t alignment) noexcept override {\n\t\tif (bytes == 0) {\n\t\t\treturn nullptr;\n\t\t}\n\t\tvoid* ptr = std::align(alignment, bytes, ptr_, size_in_bytes_);\n\t\tgsl_Expects(ptr); // not nullptr\n\t\tgsl_Expects(\n\t\t    ptr ==\n\t\t    ptr_); // this is how I understand the function documentation of std::align\n\t\tgsl_Expects(size_in_bytes_ >= bytes);\n\t\tsize_in_bytes_ -= bytes;\n\t\tptr_ = reinterpret_cast<std::byte*>(ptr_) + bytes;\n\t\treturn ptr;\n\t}\n\n\tvoid do_deallocate([[maybe_unused]] void* ptr,\n\t                   [[maybe_unused]] size_t bytes,\n\t                   [[maybe_unused]] size_t alignment) noexcept override {\n\t}\n\n\tbool do_is_equal(\n\t    const std::pmr::memory_resource& other) const noexcept override {\n\t\treturn this == &other;\n\t}\n\n\tsize_t size_in_bytes_;\n\tvoid* ptr_;\n};\n\nstatic managed_resource_type default_resource;\n\n} // namespace pmr\n\n} // namespace thrustshift\n", "meta": {"hexsha": "96dcce2c2459f61109d4eb01a27efb8e622e56c4", "size": 9283, "ext": "h", "lang": "C", "max_stars_repo_path": "include/thrustshift/memory-resource.h", "max_stars_repo_name": "codecircuit/thrustshift", "max_stars_repo_head_hexsha": "533ed68f6aa201f54b9622dcaa203fdf6844b466", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-16T13:01:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T13:01:46.000Z", "max_issues_repo_path": "include/thrustshift/memory-resource.h", "max_issues_repo_name": "codecircuit/thrustshift", "max_issues_repo_head_hexsha": "533ed68f6aa201f54b9622dcaa203fdf6844b466", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-23T14:12:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-17T11:40:04.000Z", "max_forks_repo_path": "include/thrustshift/memory-resource.h", "max_forks_repo_name": "codecircuit/thrustshift", "max_forks_repo_head_hexsha": "533ed68f6aa201f54b9622dcaa203fdf6844b466", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9608433735, "max_line_length": 107, "alphanum_fraction": 0.6710115264, "num_tokens": 2354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21206880435710534, "lm_q2_score": 0.033589504078045444, "lm_q1q2_score": 0.007123285968779211}}
{"text": "// Copyright (c) Microsoft Corporation.\r\n// Licensed under the MIT license.\r\n\r\n#pragma once\r\n\r\n#define NOMINMAX\r\n#define WIN32_LEAN_AND_MEAN\r\n\r\n#include <array>\r\n#include <iomanip>\r\n#include <optional>\r\n#include <sstream>\r\n#include <string_view>\r\n#include <thread>\r\n#include <unordered_map>\r\n#include <unordered_set>\r\n#include <vector>\r\n\r\n#include <d2d1.h>\r\n#include <d3d11_1.h>\r\n#include <d3dcompiler.h>\r\n#include <dwrite_3.h>\r\n#include <dcomp.h>\r\n#include <dxgi1_3.h>\r\n#include <dxgidebug.h>\r\n#include <VersionHelpers.h>\r\n\r\n#include <gsl/gsl_util>\r\n#include <gsl/pointers>\r\n#include <gsl/span>\r\n#include <wil/com.h>\r\n#include <wil/filesystem.h>\r\n#include <wil/result_macros.h>\r\n#include <wil/stl.h>\r\n#include <wil/win32_helpers.h>\r\n\r\n// Dynamic Bitset (optional dependency on LibPopCnt for perf at bit counting)\r\n// Variable-size compressed-storage header-only bit flag storage library.\r\n#pragma warning(push)\r\n#pragma warning(disable : 4702) // unreachable code\r\n#include <dynamic_bitset.hpp>\r\n#pragma warning(pop)\r\n\r\n// Chromium Numerics (safe math)\r\n#pragma warning(push)\r\n#pragma warning(disable : 4100) // '...': unreferenced formal parameter\r\n#pragma warning(disable : 26812) // The enum type '...' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).\r\n#include <base/numerics/safe_math.h>\r\n#pragma warning(pop)\r\n\r\n#include <til.h>\r\n#include <til/bit.h>\r\n", "meta": {"hexsha": "e6ede9efed74c365c9bc5fc1a87d5e398a40319f", "size": 1365, "ext": "h", "lang": "C", "max_stars_repo_path": "src/renderer/atlas/pch.h", "max_stars_repo_name": "by-memory/terminal", "max_stars_repo_head_hexsha": "62c95b5017e92a780cdc43008e30b4e43d2edc9b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2020-04-21T02:08:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T09:58:23.000Z", "max_issues_repo_path": "src/renderer/atlas/pch.h", "max_issues_repo_name": "by-memory/terminal", "max_issues_repo_head_hexsha": "62c95b5017e92a780cdc43008e30b4e43d2edc9b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2020-05-22T17:33:36.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-20T16:23:04.000Z", "max_forks_repo_path": "src/renderer/atlas/pch.h", "max_forks_repo_name": "by-memory/terminal", "max_forks_repo_head_hexsha": "62c95b5017e92a780cdc43008e30b4e43d2edc9b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-31T06:35:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-31T06:35:07.000Z", "avg_line_length": 25.7547169811, "max_line_length": 111, "alphanum_fraction": 0.7135531136, "num_tokens": 338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23934934732271168, "lm_q2_score": 0.029760093515701677, "lm_q1q2_score": 0.007123058959246061}}
{"text": "/* matrix/gsl_matrix_short.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_MATRIX_SHORT_H__\n#define __GSL_MATRIX_SHORT_H__\n\n#if !defined( GSL_FUN )\n#  if !defined( GSL_DLL )\n#    define GSL_FUN extern\n#  elif defined( BUILD_GSL_DLL )\n#    define GSL_FUN extern __declspec(dllexport)\n#  else\n#    define GSL_FUN extern __declspec(dllimport)\n#  endif\n#endif\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_inline.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_vector_short.h>\n#include <gsl/gsl_blas_types.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size1;\n  size_t size2;\n  size_t tda;\n  short * data;\n  gsl_block_short * block;\n  int owner;\n} gsl_matrix_short;\n\ntypedef struct\n{\n  gsl_matrix_short matrix;\n} _gsl_matrix_short_view;\n\ntypedef _gsl_matrix_short_view gsl_matrix_short_view;\n\ntypedef struct\n{\n  gsl_matrix_short matrix;\n} _gsl_matrix_short_const_view;\n\ntypedef const _gsl_matrix_short_const_view gsl_matrix_short_const_view;\n\n/* Allocation */\n\nGSL_FUN gsl_matrix_short * \ngsl_matrix_short_alloc (const size_t n1, const size_t n2);\n\nGSL_FUN gsl_matrix_short * \ngsl_matrix_short_calloc (const size_t n1, const size_t n2);\n\nGSL_FUN gsl_matrix_short * \ngsl_matrix_short_alloc_from_block (gsl_block_short * b, \n                                   const size_t offset, \n                                   const size_t n1, \n                                   const size_t n2, \n                                   const size_t d2);\n\nGSL_FUN gsl_matrix_short * \ngsl_matrix_short_alloc_from_matrix (gsl_matrix_short * m,\n                                    const size_t k1, \n                                    const size_t k2,\n                                    const size_t n1, \n                                    const size_t n2);\n\nGSL_FUN gsl_vector_short * \ngsl_vector_short_alloc_row_from_matrix (gsl_matrix_short * m,\n                                        const size_t i);\n\nGSL_FUN gsl_vector_short * \ngsl_vector_short_alloc_col_from_matrix (gsl_matrix_short * m,\n                                        const size_t j);\n\nGSL_FUN void gsl_matrix_short_free (gsl_matrix_short * m);\n\n/* Views */\n\nGSL_FUN _gsl_matrix_short_view \ngsl_matrix_short_submatrix (gsl_matrix_short * m, \n                            const size_t i, const size_t j, \n                            const size_t n1, const size_t n2);\n\nGSL_FUN _gsl_vector_short_view \ngsl_matrix_short_row (gsl_matrix_short * m, const size_t i);\n\nGSL_FUN _gsl_vector_short_view \ngsl_matrix_short_column (gsl_matrix_short * m, const size_t j);\n\nGSL_FUN _gsl_vector_short_view \ngsl_matrix_short_diagonal (gsl_matrix_short * m);\n\nGSL_FUN _gsl_vector_short_view \ngsl_matrix_short_subdiagonal (gsl_matrix_short * m, const size_t k);\n\nGSL_FUN _gsl_vector_short_view \ngsl_matrix_short_superdiagonal (gsl_matrix_short * m, const size_t k);\n\nGSL_FUN _gsl_vector_short_view\ngsl_matrix_short_subrow (gsl_matrix_short * m, const size_t i,\n                         const size_t offset, const size_t n);\n\nGSL_FUN _gsl_vector_short_view\ngsl_matrix_short_subcolumn (gsl_matrix_short * m, const size_t j,\n                            const size_t offset, const size_t n);\n\nGSL_FUN _gsl_matrix_short_view\ngsl_matrix_short_view_array (short * base,\n                             const size_t n1, \n                             const size_t n2);\n\nGSL_FUN _gsl_matrix_short_view\ngsl_matrix_short_view_array_with_tda (short * base, \n                                      const size_t n1, \n                                      const size_t n2,\n                                      const size_t tda);\n\n\nGSL_FUN _gsl_matrix_short_view\ngsl_matrix_short_view_vector (gsl_vector_short * v,\n                              const size_t n1, \n                              const size_t n2);\n\nGSL_FUN _gsl_matrix_short_view\ngsl_matrix_short_view_vector_with_tda (gsl_vector_short * v,\n                                       const size_t n1, \n                                       const size_t n2,\n                                       const size_t tda);\n\n\nGSL_FUN _gsl_matrix_short_const_view \ngsl_matrix_short_const_submatrix (const gsl_matrix_short * m, \n                                  const size_t i, const size_t j, \n                                  const size_t n1, const size_t n2);\n\nGSL_FUN _gsl_vector_short_const_view \ngsl_matrix_short_const_row (const gsl_matrix_short * m, \n                            const size_t i);\n\nGSL_FUN _gsl_vector_short_const_view \ngsl_matrix_short_const_column (const gsl_matrix_short * m, \n                               const size_t j);\n\nGSL_FUN _gsl_vector_short_const_view\ngsl_matrix_short_const_diagonal (const gsl_matrix_short * m);\n\nGSL_FUN _gsl_vector_short_const_view \ngsl_matrix_short_const_subdiagonal (const gsl_matrix_short * m, \n                                    const size_t k);\n\nGSL_FUN _gsl_vector_short_const_view \ngsl_matrix_short_const_superdiagonal (const gsl_matrix_short * m, \n                                      const size_t k);\n\nGSL_FUN _gsl_vector_short_const_view\ngsl_matrix_short_const_subrow (const gsl_matrix_short * m, const size_t i,\n                               const size_t offset, const size_t n);\n\nGSL_FUN _gsl_vector_short_const_view\ngsl_matrix_short_const_subcolumn (const gsl_matrix_short * m, const size_t j,\n                                  const size_t offset, const size_t n);\n\nGSL_FUN _gsl_matrix_short_const_view\ngsl_matrix_short_const_view_array (const short * base,\n                                   const size_t n1, \n                                   const size_t n2);\n\nGSL_FUN _gsl_matrix_short_const_view\ngsl_matrix_short_const_view_array_with_tda (const short * base, \n                                            const size_t n1, \n                                            const size_t n2,\n                                            const size_t tda);\n\nGSL_FUN _gsl_matrix_short_const_view\ngsl_matrix_short_const_view_vector (const gsl_vector_short * v,\n                                    const size_t n1, \n                                    const size_t n2);\n\nGSL_FUN _gsl_matrix_short_const_view\ngsl_matrix_short_const_view_vector_with_tda (const gsl_vector_short * v,\n                                             const size_t n1, \n                                             const size_t n2,\n                                             const size_t tda);\n\n/* Operations */\n\nGSL_FUN void gsl_matrix_short_set_zero (gsl_matrix_short * m);\nGSL_FUN void gsl_matrix_short_set_identity (gsl_matrix_short * m);\nGSL_FUN void gsl_matrix_short_set_all (gsl_matrix_short * m, short x);\n\nGSL_FUN int gsl_matrix_short_fread (FILE * stream, gsl_matrix_short * m) ;\nGSL_FUN int gsl_matrix_short_fwrite (FILE * stream, const gsl_matrix_short * m) ;\nGSL_FUN int gsl_matrix_short_fscanf (FILE * stream, gsl_matrix_short * m);\nGSL_FUN int gsl_matrix_short_fprintf (FILE * stream, const gsl_matrix_short * m, const char * format);\n \nGSL_FUN int gsl_matrix_short_memcpy(gsl_matrix_short * dest, const gsl_matrix_short * src);\nGSL_FUN int gsl_matrix_short_swap(gsl_matrix_short * m1, gsl_matrix_short * m2);\nGSL_FUN int gsl_matrix_short_tricpy(CBLAS_UPLO_t Uplo, CBLAS_DIAG_t Diag, gsl_matrix_short * dest, const gsl_matrix_short * src);\n\nGSL_FUN int gsl_matrix_short_swap_rows(gsl_matrix_short * m, const size_t i, const size_t j);\nGSL_FUN int gsl_matrix_short_swap_columns(gsl_matrix_short * m, const size_t i, const size_t j);\nGSL_FUN int gsl_matrix_short_swap_rowcol(gsl_matrix_short * m, const size_t i, const size_t j);\nGSL_FUN int gsl_matrix_short_transpose (gsl_matrix_short * m);\nGSL_FUN int gsl_matrix_short_transpose_memcpy (gsl_matrix_short * dest, const gsl_matrix_short * src);\nGSL_FUN int gsl_matrix_short_transpose_tricpy (CBLAS_UPLO_t Uplo_src, CBLAS_DIAG_t Diag, gsl_matrix_short * dest, const gsl_matrix_short * src);\n\nGSL_FUN short gsl_matrix_short_max (const gsl_matrix_short * m);\nGSL_FUN short gsl_matrix_short_min (const gsl_matrix_short * m);\nGSL_FUN void gsl_matrix_short_minmax (const gsl_matrix_short * m, short * min_out, short * max_out);\n\nGSL_FUN void gsl_matrix_short_max_index (const gsl_matrix_short * m, size_t * imax, size_t *jmax);\nGSL_FUN void gsl_matrix_short_min_index (const gsl_matrix_short * m, size_t * imin, size_t *jmin);\nGSL_FUN void gsl_matrix_short_minmax_index (const gsl_matrix_short * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);\n\nGSL_FUN int gsl_matrix_short_equal (const gsl_matrix_short * a, const gsl_matrix_short * b);\n\nGSL_FUN int gsl_matrix_short_isnull (const gsl_matrix_short * m);\nGSL_FUN int gsl_matrix_short_ispos (const gsl_matrix_short * m);\nGSL_FUN int gsl_matrix_short_isneg (const gsl_matrix_short * m);\nGSL_FUN int gsl_matrix_short_isnonneg (const gsl_matrix_short * m);\n\nGSL_FUN int gsl_matrix_short_add (gsl_matrix_short * a, const gsl_matrix_short * b);\nGSL_FUN int gsl_matrix_short_sub (gsl_matrix_short * a, const gsl_matrix_short * b);\nGSL_FUN int gsl_matrix_short_mul_elements (gsl_matrix_short * a, const gsl_matrix_short * b);\nGSL_FUN int gsl_matrix_short_div_elements (gsl_matrix_short * a, const gsl_matrix_short * b);\nGSL_FUN int gsl_matrix_short_scale (gsl_matrix_short * a, const double x);\nGSL_FUN int gsl_matrix_short_scale_rows (gsl_matrix_short * a, const gsl_vector_short * x);\nGSL_FUN int gsl_matrix_short_scale_columns (gsl_matrix_short * a, const gsl_vector_short * x);\nGSL_FUN int gsl_matrix_short_add_constant (gsl_matrix_short * a, const double x);\nGSL_FUN int gsl_matrix_short_add_diagonal (gsl_matrix_short * a, const double x);\n\n/***********************************************************************/\n/* The functions below are obsolete                                    */\n/***********************************************************************/\nGSL_FUN int gsl_matrix_short_get_row(gsl_vector_short * v, const gsl_matrix_short * m, const size_t i);\nGSL_FUN int gsl_matrix_short_get_col(gsl_vector_short * v, const gsl_matrix_short * m, const size_t j);\nGSL_FUN int gsl_matrix_short_set_row(gsl_matrix_short * m, const size_t i, const gsl_vector_short * v);\nGSL_FUN int gsl_matrix_short_set_col(gsl_matrix_short * m, const size_t j, const gsl_vector_short * v);\n/***********************************************************************/\n\n/* inline functions if you are using GCC */\n\nGSL_FUN INLINE_DECL short   gsl_matrix_short_get(const gsl_matrix_short * m, const size_t i, const size_t j);\nGSL_FUN INLINE_DECL void    gsl_matrix_short_set(gsl_matrix_short * m, const size_t i, const size_t j, const short x);\nGSL_FUN INLINE_DECL short * gsl_matrix_short_ptr(gsl_matrix_short * m, const size_t i, const size_t j);\nGSL_FUN INLINE_DECL const short * gsl_matrix_short_const_ptr(const gsl_matrix_short * m, const size_t i, const size_t j);\n\n#ifdef HAVE_INLINE\nINLINE_FUN \nshort\ngsl_matrix_short_get(const gsl_matrix_short * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_VAL(\"first index out of range\", GSL_EINVAL, 0) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_VAL(\"second index out of range\", GSL_EINVAL, 0) ;\n        }\n    }\n#endif\n  return m->data[i * m->tda + j] ;\n} \n\nINLINE_FUN \nvoid\ngsl_matrix_short_set(gsl_matrix_short * m, const size_t i, const size_t j, const short x)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_VOID(\"first index out of range\", GSL_EINVAL) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_VOID(\"second index out of range\", GSL_EINVAL) ;\n        }\n    }\n#endif\n  m->data[i * m->tda + j] = x ;\n}\n\nINLINE_FUN \nshort *\ngsl_matrix_short_ptr(gsl_matrix_short * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n        }\n    }\n#endif\n  return (short *) (m->data + (i * m->tda + j)) ;\n} \n\nINLINE_FUN \nconst short *\ngsl_matrix_short_const_ptr(const gsl_matrix_short * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n        }\n    }\n#endif\n  return (const short *) (m->data + (i * m->tda + j)) ;\n} \n\n#endif\n\n__END_DECLS\n\n#endif /* __GSL_MATRIX_SHORT_H__ */\n", "meta": {"hexsha": "d6ae90b6c0f2be0917d29d042abfbe2fca9aea60", "size": 13582, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gsl/gsl_matrix_short.h", "max_stars_repo_name": "zhanghe9704/jspec2", "max_stars_repo_head_hexsha": "0073e0515b87610b7f88ad2b07fc7d23618c159a", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-28T08:20:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-28T08:20:20.000Z", "max_issues_repo_path": "include/gsl/gsl_matrix_short.h", "max_issues_repo_name": "zhanghe9704/jspec2", "max_issues_repo_head_hexsha": "0073e0515b87610b7f88ad2b07fc7d23618c159a", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gsl/gsl_matrix_short.h", "max_forks_repo_name": "zhanghe9704/jspec2", "max_forks_repo_head_hexsha": "0073e0515b87610b7f88ad2b07fc7d23618c159a", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-14T12:45:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-14T12:45:35.000Z", "avg_line_length": 37.1092896175, "max_line_length": 144, "alphanum_fraction": 0.6710351936, "num_tokens": 3339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24508500210441886, "lm_q2_score": 0.028870909244130154, "lm_q1q2_score": 0.0070758268528541245}}
{"text": "#pragma once\n#include <array>\n#include <gsl/span>\n#include <sam.h>\n\nnamespace mcu {\n\n#define EEPROM [[gnu::section(\".eeprom\")]]\n\nclass FlashEEPROM\n{\npublic:\n\tFlashEEPROM() = delete;\n\n\ttemplate <typename T>\n\tstatic void write(const T* flashAddress, const T& src) noexcept\n\t{\n\t\twrite(flashAddress, gsl::span(&src, 1));\n\t}\n\ttemplate <typename T>\n\tstatic T read(const T* flashAddress) noexcept\n\t{\n\t\tT result;\n\t\tread(flashAddress, gsl::span(&result, 1));\n\t\treturn result;\n\t}\n\n\ttemplate <typename T>\n\tstatic void write(const T* flashAddress, gsl::span<const T> src) noexcept\n\t{\n\t\twrite(reinterpret_cast<const std::byte*>(flashAddress), gsl::as_bytes(src));\n\t}\n\ttemplate <typename T>\n\tstatic void read(const T* flashAddress, gsl::span<T> dst) noexcept\n\t{\n\t\tread(reinterpret_cast<const std::byte*>(flashAddress), gsl::as_writable_bytes(dst));\n\t}\n\n\tstatic void write(const std::byte* flashAddress, gsl::span<const std::byte> src) noexcept;\n\tstatic void read(const std::byte* flashAddress, gsl::span<std::byte> dst) noexcept;\n\t\n\tstatic void commit() noexcept;\n\tstatic bool needsCommit() noexcept { return cacheDirty; }\n\t\nprivate:\n\tusing Page = std::array<unsigned, FLASH_PAGE_SIZE / sizeof(unsigned)>;\n\tusing Row = std::array<Page, 4>;\n\n\tstatic constexpr size_t RowSize = sizeof(Row);\n\tstatic constexpr uintptr_t RowOffsetMask = sizeof(Row) - 1;\n\n\tunion Cache {\n\t\tstd::array<std::byte, sizeof(Row)> bytes;\n\t\tRow pages;\n\t};\n\tstatic Cache cache;\n\tstatic Row* cacheTag;\n\tstatic bool cacheDirty;\n\t\n\tstatic void cacheRow(Row* row) noexcept;\n\tstatic void copyPage(const Page& src, Page& dst) noexcept;\n};\n\n} // namespace mcu\n", "meta": {"hexsha": "df76f5232c4201504f94ac9746c8d90259e36055", "size": 1609, "ext": "h", "lang": "C", "max_stars_repo_path": "include/flash_eeprom.h", "max_stars_repo_name": "dachsei/platform-samd20", "max_stars_repo_head_hexsha": "520ecaefb0a0c1b92be281d5834f44e927995190", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/flash_eeprom.h", "max_issues_repo_name": "dachsei/platform-samd20", "max_issues_repo_head_hexsha": "520ecaefb0a0c1b92be281d5834f44e927995190", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/flash_eeprom.h", "max_forks_repo_name": "dachsei/platform-samd20", "max_forks_repo_head_hexsha": "520ecaefb0a0c1b92be281d5834f44e927995190", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7538461538, "max_line_length": 91, "alphanum_fraction": 0.7134866377, "num_tokens": 420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18952110964056454, "lm_q2_score": 0.037326890021390696, "lm_q1q2_score": 0.007074233616285281}}
{"text": "// Copyright \u00a9 Matt Jones and Contributors. Licensed under the MIT Licence (MIT). See LICENCE.md in the repository root\n// for more information.\n\n#ifndef NOVELRT_GRAPHICS_H\n#define NOVELRT_GRAPHICS_H\n\n// Graphics dependencies\n#include \"NovelRT/EngineConfig.h\"\n#include \"NovelRT/Maths/Maths.h\"\n#include \"NovelRT/ResourceManagement/ResourceManagement.h\"\n#include \"NovelRT/SceneGraph/SceneGraph.h\"\n#include \"NovelRT/Threading/Threading.h\"\n#include \"NovelRT/Utilities/Event.h\"\n#include \"NovelRT/Utilities/Lazy.h\"\n#include \"NovelRT/Utilities/Misc.h\"\n#include \"RGBAColour.h\"\n#include <chrono>\n#include <cstdint>\n#include <filesystem>\n#include <gsl/span>\n#include <list>\n#include <memory>\n#include <mutex>\n#include <optional>\n#include <string>\n#include <typeindex>\n#include <utility>\n#include <vector>\n\n/**\n * @brief The experimental Graphics plugin API. Comes with built-in support for the ECS.\n */\nnamespace NovelRT::Graphics\n{\n    enum class ShaderProgramKind : uint32_t;\n    enum class GraphicsResourceAccess : uint32_t;\n    enum class GraphicsSurfaceKind : uint32_t;\n    enum class GraphicsTextureAddressMode : uint32_t;\n    enum class GraphicsPipelineBlendFactor : uint32_t;\n    enum class GraphicsPipelineInputElementKind : uint32_t;\n    enum class GraphicsPipelineResourceKind : uint32_t;\n    enum class ShaderProgramVisibility : uint32_t;\n    enum class GraphicsTextureKind : uint32_t;\n    enum class GraphicsMemoryRegionAllocationFlags : uint32_t;\n    enum class GraphicsMemoryRegionAllocationFlags : uint32_t;\n    enum class GraphicsBufferKind : uint32_t;\n    enum class TexelFormat : uint32_t;\n    struct GraphicsMemoryAllocatorSettings;\n    class GraphicsDeviceObject;\n    class IGraphicsSurface;\n    class GraphicsAdapter;\n    class GraphicsDevice;\n    class GraphicsResource;\n    class GraphicsBuffer;\n    class GraphicsTexture;\n    class ShaderProgram;\n    class GraphicsPipeline;\n    class GraphicsPipelineSignature;\n    class GraphicsPipelineInput;\n    class GraphicsPipelineResource;\n    class GraphicsPipelineInputElement;\n    class GraphicsContext;\n    class GraphicsFence;\n    class GraphicsPrimitive;\n    class GraphicsProvider;\n    class GraphicsMemoryAllocator;\n    class IGraphicsAdapterSelector;\n    class GraphicsMemoryBlockCollection;\n    class GraphicsMemoryBlock;\n    class GraphicsMemoryBudget;\n    class GraphicsSurfaceContext;\n    class GraphicsResourceManager;\n}\n\n// Graphics types\n// clang-format off\n\n#include \"ShaderProgramKind.h\"\n#include \"GraphicsAdapter.h\"\n#include \"GraphicsDeviceObject.h\"\n#include \"GraphicsContext.h\"\n#include \"GraphicsFence.h\"\n#include \"GraphicsMemoryAllocatorSettings.h\"\n#include \"GraphicsMemoryRegion.h\"\n#include \"IGraphicsMemoryRegionCollection.h\"\n#include \"GraphicsMemoryRegionAllocationFlags.h\"\n#include \"TexelFormat.h\"\n#include \"GraphicsMemoryAllocator.h\"\n#include \"GraphicsMemoryBlockCollection.h\"\n#include \"GraphicsMemoryBudget.h\"\n#include \"GraphicsMemoryBlock.h\"\n#include \"GraphicsResourceAccess.h\"\n#include \"GraphicsSurfaceKind.h\"\n#include \"GraphicsTextureKind.h\"\n#include \"IGraphicsSurface.h\"\n#include \"GraphicsSurfaceContext.h\"\n#include \"GraphicsDevice.h\"\n#include \"GraphicsResource.h\"\n#include \"GraphicsBufferKind.h\"\n#include \"GraphicsBuffer.h\"\n#include \"GraphicsTextureAddressMode.h\"\n#include \"GraphicsTexture.h\"\n#include \"IGraphicsAdapterSelector.h\"\n#include \"ShaderProgram.h\"\n#include \"GraphicsPipelineBlendFactor.h\"\n#include \"GraphicsPipeline.h\"\n#include \"GraphicsPipelineSignature.h\"\n#include \"GraphicsPrimitive.h\"\n#include \"GraphicsProvider.h\"\n#include \"GraphicsPipelineInput.h\"\n#include \"GraphicsPipelineInputElement.h\"\n#include \"GraphicsPipelineInputElementKind.h\"\n#include \"GraphicsPipelineResource.h\"\n#include \"GraphicsPipelineResourceKind.h\"\n#include \"ShaderProgramVisibility.h\"\n#include \"GraphicsResourceManager.h\"\n\n// clang-format on\n\n#endif // !NOVELRT_GRAPHICS_H\n", "meta": {"hexsha": "e913241987e384d172a96a0750e8d021f70d624e", "size": 3845, "ext": "h", "lang": "C", "max_stars_repo_path": "include/NovelRT/Graphics/Graphics.h", "max_stars_repo_name": "Shidesu/NovelRT", "max_stars_repo_head_hexsha": "53e341a79db9e84b47f80e12e1d7049a6874811d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/NovelRT/Graphics/Graphics.h", "max_issues_repo_name": "Shidesu/NovelRT", "max_issues_repo_head_hexsha": "53e341a79db9e84b47f80e12e1d7049a6874811d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/NovelRT/Graphics/Graphics.h", "max_forks_repo_name": "Shidesu/NovelRT", "max_forks_repo_head_hexsha": "53e341a79db9e84b47f80e12e1d7049a6874811d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7768595041, "max_line_length": 119, "alphanum_fraction": 0.7934980494, "num_tokens": 820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3073580295544412, "lm_q2_score": 0.022977371248114786, "lm_q1q2_score": 0.007062279551161432}}
{"text": "#ifndef GNUPLOT_H\n#define GNUPLOT_H\n\n\n#include <fstream>\n#include <gsl/gsl_vector.h>\n\n#include \"constants.h\"\n\n\nvoid writePlotData(gsl_vector *f, const std::string& filename);\n\n\n#endif // GNUPLOT_H\n", "meta": {"hexsha": "886c77362f2285385fbc2b82f3474bb7451d3537", "size": 197, "ext": "h", "lang": "C", "max_stars_repo_path": "inc/gnuplot.h", "max_stars_repo_name": "ichi-rika/glottal-inverse", "max_stars_repo_head_hexsha": "c922ed540278e3c8eec528c2cf66b89e6d310575", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-01-24T17:01:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-26T16:22:08.000Z", "max_issues_repo_path": "inc/gnuplot.h", "max_issues_repo_name": "ichi-rika/glottal-inverse", "max_issues_repo_head_hexsha": "c922ed540278e3c8eec528c2cf66b89e6d310575", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inc/gnuplot.h", "max_forks_repo_name": "ichi-rika/glottal-inverse", "max_forks_repo_head_hexsha": "c922ed540278e3c8eec528c2cf66b89e6d310575", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-04-27T00:23:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-27T14:41:25.000Z", "avg_line_length": 13.1333333333, "max_line_length": 63, "alphanum_fraction": 0.7411167513, "num_tokens": 54, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.2068940488158881, "lm_q2_score": 0.03410042681663018, "lm_q1q2_score": 0.007055175370442505}}
{"text": "#include <stdio.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_odeiv.h>\n#include <gsl/gsl_odeiv2.h>\n\n#include <stdlib.h>\n#include <string.h>\n#include <stdbool.h>\n\n#include <time.h>\n#include <math.h>\n\n#include <GL/glut.h>\n#include <GL/gl.h>\n\n#include <unistd.h>\n#include <signal.h>\n#include <sys/wait.h>\n#include <sys/types.h>\n\n#define SLICE\t360\n\ntypedef struct _line_vertex line_vertex;\nstruct _line_vertex\n{\n\tfloat x1;\n\tfloat y1;\n\n\tfloat x2;\n\tfloat y2;\n};\n\nfloat text_x = 64.0f, text_y = 58.0f;\nconst float TRANS_VAL = 100.0f;\n\nuint32_t mouse_loc;\nint x, y;\n\nbool clicked = false;\nint pos_x, pos_y;\nint mov_x, mov_y;\nint click_x, click_y;\nint special_key;\n\nbool run = false;\n\nline_vertex vertices[9] = {\n\t{ 50.0f, 50.0f, 50.0f, 30.0f },\n\t{ 50.0f, 50.0f, 55.0f, 50.0f },\n\t{ 75.0f, 50.0f, 80.0f, 50.0f },\n\t{ 80.0f, 50.0f, 80.0f, 30.0f },\n\t{ 55.0f, 55.0f, 55.0f, 45.0f },\n\t{ 55.0f, 55.0f, 75.0f, 55.0f },\n\t{ 75.0f, 55.0f, 75.0f, 45.0f },\n\t{ 55.0f, 45.0f, 75.0f, 45.0f }\n};\n\nline_vertex pick_vertices[9] = {\n\t{ 45.0f, 25.0f, 45.0f, 65.0f },\n\t{ 45.0f, 25.0f, 85.0f, 25.0f },\n\t{ 45.0f, 65.0f, 85.0f, 65.0f },\n\t{ 85.0f, 25.0f, 85.0f, 65.0f }\n};\n\nline_vertex power_vertices[5] = {\n\t{ 40.0f, 50.0f, 40.0f, 60.0f },\n\t{ 50.0f, 50.0f, 30.0f, 50.0f },\n\t{ 45.0f, 45.0f, 35.0f, 45.0f },\n\t{ 40.0f, 45.0f, 40.0f, 35.0f }\n};\n\nline_vertex ground_vertices[5] = {\n\t{ 40.0f, 50.0f, 40.0f, 60.0f },\n\t{ 50.0f, 50.0f, 30.0f, 50.0f },\n\t{ 47.5f, 47.5f, 32.5f, 47.5f },\n\t{ 45.0f, 45.0f, 35.0f, 45.0f }\n};\n\nint *jac;\n\nint rhs (double t, const double y[], double f[], void *params_ptr);\n//int jacobian (double t, const double y[], double *dfdy, double dfdt[], void *params_ptr);\n\nvoid calc_differential_eq(void);\nvoid draw_differential_eq_plot(void);\nvoid draw_lattice(void);\nvoid draw_lattice2(void);\nvoid draw_volt_plot(void);\n\nvoid reshape(int w, int h);\n\ntypedef struct _xy_plot xy_plot;\nstruct _xy_plot\n{\n\tdouble x;\n\tdouble y;\n};\n\n//xy_plot plot_res[1001];\nxy_plot plot_res[100000001];\n//double volt_res[100000001];\n\nfloat resistance;\nfloat inductance;\nfloat voltage;\n\nint sub_window;\nint sub_window2;\n\nvoid sim_reshape(int w, int h)\n{\n    GLfloat n_range = 100.0f;\n\n    if(h == 0)\n        h = 1;\n\n    glViewport(0, 0, w, h);\n    glMatrixMode(GL_PROJECTION);\n    glLoadIdentity();\n\n\t// glOrtho(\ud45c\uae30\ud558\uace0\uc790 \ud558\ub294 \ucd5c\uc18c x\uac12, \ucd5c\ub300 x\uac12, \ud654\uba74\uc0c1 \ub098\ud0c0\ub294 \ucd5c\uc18c y, \ucd5c\ub300 y, z\ub294 \uad00\uacc4\uc5c6\uc74c)\n\t// \uc989 \ub0b4\uac00 \ubcf4\uace0\uc790 \ud558\ub294 x, y, z\uc758 \ubc94\uc704\ub97c \uc9c0\uc815\ud560 \uc218 \uc788\uc74c\n\tglOrtho(-0.000005, 0.000005, -0.7, 0.7, -1, 1);\n\n    glMatrixMode(GL_MODELVIEW);\n    glLoadIdentity();\n}\n\nvoid simulate(void)\n{\n    glClearColor(0.0, 0.0, 0.0, 1.0);\n    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n    glLoadIdentity();\n\n    glColor3f(1, 0, 0);\n\n    glBegin(GL_LINE_LOOP);\n    \tglVertex3f(100.0, 0.0, 0.0);\n        glVertex3f(-100.0, 0.0, 0.0);\n    glEnd();\n\n    glColor3f(0.0, 1.0, 0.0);\n\n    glBegin(GL_LINE_LOOP);\n        glVertex3f(0.0, 100.0, 0.0);\n        glVertex3f(0.0, -100.0, 0.0);\n    glEnd();\n\n    draw_differential_eq_plot();\n    draw_lattice();\n\n    glutSwapBuffers();\n}\n\nvoid sim_reshape2(int w, int h)\n{\n    GLfloat n_range = 100.0f;\n\n    if(h == 0)\n        h = 1;\n\n    glViewport(0, 0, w, h);\n    glMatrixMode(GL_PROJECTION);\n    glLoadIdentity();\n\n\tglOrtho(-0.000005, 0.000005, -2000000, 500000, -1, 1);\n\n    glMatrixMode(GL_MODELVIEW);\n    glLoadIdentity();\n}\n\nvoid simulate2(void)\n{\n    glClearColor(0.0, 0.0, 0.0, 1.0);\n    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n    glLoadIdentity();\n\n    glColor3f(1, 0, 0);\n\n    glBegin(GL_LINE_LOOP);\n    \tglVertex3f(100.0, 0.0, 0.0);\n        glVertex3f(-100.0, 0.0, 0.0);\n    glEnd();\n\n    glColor3f(0.0, 1.0, 0.0);\n\n    glBegin(GL_LINE_LOOP);\n        glVertex3f(0.0, 500000.0, 0.0);\n        glVertex3f(0.0, -2000000.0, 0.0);\n    glEnd();\n\n    draw_volt_plot();\n    draw_lattice2();\n\n    glutSwapBuffers();\n}\n\nvoid keyboard_handler(unsigned char key, int x, int y)\n{\n\tint pid;\n\tint i, status;\n\n\t// fork -> execve\n\t// OpenGL -> GPU\n#if 0\n\tchar *argv[5] = {\"print_simulation\"};\n\tchar *envp[] = {0};\n\tchar volt[64] = {0};\n\tchar coil[64] = {0};\n\tchar resist[64] = {0};\n#endif\n\n\tswitch(key)\n\t{\n\t\tcase 's':\n\t\t\tprintf(\"Simulation Preparation\\n\");\n\t\t\tprintf(\"\uc800\ud56d\uac12 \uc785\ub825: \");\n\t\t\tscanf(\"%f\", &resistance);\n\t\t\tprintf(\"\uc778\ub355\ud134\uc2a4\uac12 \uc785\ub825: \");\n\t\t\tscanf(\"%f\", &inductance);\n\t\t\tprintf(\"\uc785\ub825 \uc804\uc6d0\uac12 \uc785\ub825: \");\n\t\t\tscanf(\"%f\", &voltage);\n\n\t\t\tprintf(\"R = %f, L = %f, V = %f\\n\", resistance, inductance, voltage);\n\n\t\t\tcalc_differential_eq();\n\t\t\trun = true;\n\t\t\tbreak;\n\t\tcase 'r':\n\t\t\tprintf(\"Run Simulation\\n\");\n\n#if 0\n\t\t\tpid = fork();\n\n\t\t\tif (pid > 0)\n\t\t\t{\n\t\t\t\tprintf(\"wait for simulation finished\\n\");\n\t\t\t\twait(&status);\n\t\t\t}\n\t\t\telse if (pid == 0)\n\t\t\t{\n\t\t\t\texecve(\"./print_simulation\", argv, envp);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tperror(\"fork() \");\n\t\t\t\texit(-1);\n\t\t\t}\n#endif\n\n\t\t\tsub_window = glutCreateWindow(\"Current i(t)\");\n\n\t\t\tglutDisplayFunc(simulate);\n\t\t\tglutReshapeFunc(sim_reshape);\n\n\t\t\tsub_window2 = glutCreateWindow(\"Voltage V(t)\");\n\n\t\t\tglutDisplayFunc(simulate2);\n\t\t\tglutReshapeFunc(sim_reshape2);\n\t\t\tbreak;\n\t\tcase 't':\n\t\t\tprintf(\"Termination\\n\");\n\t\t\tglutDestroyWindow(sub_window);\n\t\t\tglutDestroyWindow(sub_window2);\n\t\t\tbreak;\n\t\tcase 27:\n\t\t\texit(1);\n\t\t\tbreak;\n\t}\n}\n\nvoid on_mouse(int button, int state, int x, int y)\n{\n\tspecial_key = glutGetModifiers();\n\n\tif (button == GLUT_LEFT_BUTTON & state == GLUT_DOWN)\n\t{\n\t\tif (clicked == false)\n\t\t{\n\t\t\tprintf(\"Click - Down\\n\");\n\t\t\tclick_x = x;\n\t\t\tclick_y = y;\n\t\t\tclicked = true;\n\n\t\t\tprintf(\"click_x = %d, click_y = %d\\n\", click_x, click_y);\n\t\t}\n\t}\n\n\tif (button == GLUT_LEFT_BUTTON & state == GLUT_UP)\n\t{\n\t\tprintf(\"Click - Up\\n\");\n\t\tclicked = false;\n\t}\n\n\tint window_width = glutGet(GLUT_WINDOW_WIDTH);\n\tint window_height = glutGet(GLUT_WINDOW_HEIGHT);\n\n\tGLbyte color[4];\n\tGLfloat depth;\n\tGLuint index;\n\n\tglReadPixels(x, window_height - y - 1, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, color);\n\tglReadPixels(x, window_height - y - 1, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth);\n\tglReadPixels(x, window_height - y - 1, 1, 1, GL_STENCIL_INDEX, GL_UNSIGNED_INT, &index);\n\n\tprintf(\"Clicked on pixel %d, %d, color %02hhx%02hhx%02hhx%02hhx, depth %f, stencil index %u\\n\",\n\t\t\tx, y, color[0], color[1], color[2], color[3], depth, index);\n\n}\n\nvoid drag_mouse(int x, int y)\n{\n\tpos_x = x;\n\tpos_y = y;\n\n\tspecial_key = glutGetModifiers();\n\n\tif (clicked == true)\n\t{\n\t\tprintf(\"clicked!\\n\");\n\n\t\tmov_x = (click_x - pos_x) / 3;\n\t\tmov_y = (click_y - pos_y) / 2.5;\n\n\t\tclick_x = pos_x;\n\t\tclick_y = pos_y;\n\n\t\tprintf(\"mov_x = %d, mov_y = %d\\n\", mov_x, mov_y);\n\n\t\tint i;\n\n\t\tfor (i = 0; i < 8; i++)\n\t\t{ \n\t\t\tvertices[i].x1 -= mov_x;\n\t\t\tvertices[i].x2 -= mov_x;\n\t\t\tvertices[i].y1 += mov_y;\n\t\t\tvertices[i].y2 += mov_y;\n\t\t}\n\n\t\tfor (i = 0; i < 4; i++)\n\t\t{ \n\t\t\tpick_vertices[i].x1 -= mov_x;\n\t\t\tpick_vertices[i].x2 -= mov_x;\n\t\t\tpick_vertices[i].y1 += mov_y;\n\t\t\tpick_vertices[i].y2 += mov_y;\n\t\t}\n\n\t\tfor (i = 0; i < 4; i++)\n\t\t{\n\t\t\tpower_vertices[i].x1 -= mov_x;\n\t\t\tpower_vertices[i].x2 -= mov_x;\n\t\t\tpower_vertices[i].y1 += mov_y;\n\t\t\tpower_vertices[i].y2 += mov_y;\n\t\t}\n\n\t\tfor (i = 0; i < 4; i++)\n\t\t{\n\t\t\tground_vertices[i].x1 -= mov_x;\n\t\t\tground_vertices[i].x2 -= mov_x;\n\t\t\tground_vertices[i].y1 += mov_y;\n\t\t\tground_vertices[i].y2 += mov_y;\n\t\t}\n\n\t\ttext_x -= mov_x;\n\t\ttext_y += mov_y;\n\n\t\tglutPostRedisplay();\n\t}\n}\n\nvoid drawString (char *s)\n{\n\tunsigned int i;\n\n\tfor (i = 0; i < strlen (s); i++)\n\t\tglutBitmapCharacter (GLUT_BITMAP_HELVETICA_10, s[i]);\n}\n\nvoid drawStringBig (char *s)\n{\n\tunsigned int i;\n\n\tfor (i = 0; i < strlen (s); i++)\n\t\tglutBitmapCharacter (GLUT_BITMAP_HELVETICA_18, s[i]);\n}\n\nvoid draw_outline(void)\n{\n\tint i;\n\n\tglColor3f(0, 1, 0);\n\n\tglBegin(GL_LINES);\n\t\tfor (i = 0; i < 8; i++)\n\t\t{\n\t\t\tglVertex2f(pick_vertices[i].x1, pick_vertices[i].y1);\n\t\t\tglVertex2f(pick_vertices[i].x2, pick_vertices[i].y2);\n\t\t}\n\tglEnd();\n}\n\nvoid draw_inductance_outline(void)\n{\n\tint i;\n\n\tglColor3f(0, 1, 0);\n\n\tglBegin(GL_LINES);\n\t\tfor (i = 0; i < 4; i++)\n\t\t{\n\t\t\tglVertex2f(pick_vertices[i].x1 + 50.0f, pick_vertices[i].y1);\n\t\t\tglVertex2f(pick_vertices[i].x2 + 50.0f, pick_vertices[i].y2);\n\t\t}\n\tglEnd();\n}\n\nvoid draw_resistance(void)\n{\n\tint i;\n\tstatic char label[100];\n\n\tglColor3f(1, 0, 1);\n\n\tglBegin(GL_LINES);\n\t\tfor (i = 0; i < 8; i++)\n\t\t{\n\t\t\tglVertex2f(vertices[i].x1, vertices[i].y1);\n\t\t\tglVertex2f(vertices[i].x2, vertices[i].y2);\n\t\t}\n\tglEnd();\n\n\tsprintf (label, \"R\");\n\tglRasterPos2f (text_x, text_y);\n\tdrawStringBig (label);\n}\n\nvoid draw_inductance(void)\n{\n\tint i;\n\tstatic char label[100];\n\n\tglColor3f(1, 0, 1);\n\n\tglBegin(GL_LINES);\n\t\tfor (i = 0; i < 8; i++)\n\t\t{\n\t\t\tglVertex2f(vertices[i].x1 + 50.0f, vertices[i].y1);\n\t\t\tglVertex2f(vertices[i].x2 + 50.0f, vertices[i].y2);\n\t\t}\n\tglEnd();\n\n\tsprintf (label, \"L\");\n\tglRasterPos2f (text_x + 50.0f, text_y);\n\tdrawStringBig (label);\n}\n\nvoid draw_power_outline(void)\n{\n\tint i;\n\n\tglColor3f(0, 1, 0);\n\n\tglBegin(GL_LINES);\n\t\tfor (i = 0; i < 4; i++)\n\t\t{\n\t\t\tglVertex2f(pick_vertices[i].x1 - 75.0f, pick_vertices[i].y1 + 20.0f);\n\t\t\tglVertex2f(pick_vertices[i].x2 - 75.0f, pick_vertices[i].y2 + 20.0f);\n\t\t}\n\tglEnd();\n}\n\nvoid draw_power(void)\n{\n\tint i;\n\tstatic char label[100];\n\n\tglColor3f(1, 0, 1);\n\n\tglBegin(GL_LINES);\n\t\tfor (i = 0; i < 4; i++)\n\t\t{\n\t\t\tglVertex2f(power_vertices[i].x1 - 50.0f, power_vertices[i].y1 + 15.0f);\n\t\t\tglVertex2f(power_vertices[i].x2 - 50.0f, power_vertices[i].y2 + 15.0f);\n\t\t}\n\tglEnd();\n\n\tsprintf (label, \"V\");\n\tglRasterPos2f (text_x - 70.0f, text_y + 20.0f);\n\tdrawStringBig (label);\n}\n\nvoid draw_ground_outline(void)\n{\n\tint i;\n\n\tglColor3f(0, 1, 0);\n\n\tglBegin(GL_LINES);\n\t\tfor (i = 0; i < 4; i++)\n\t\t{\n\t\t\tglVertex2f(pick_vertices[i].x1 - 75.0f, pick_vertices[i].y1 - 20.0f);\n\t\t\tglVertex2f(pick_vertices[i].x2 - 75.0f, pick_vertices[i].y2 - 20.0f);\n\t\t}\n\tglEnd();\n}\n\nvoid draw_ground(void)\n{\n\tint i;\n\tstatic char label[100];\n\n\tglColor3f(1, 0, 1);\n\n\tglBegin(GL_LINES);\n\t\tfor (i = 0; i < 4; i++)\n\t\t{\n\t\t\tglVertex2f(ground_vertices[i].x1 - 50.0f, ground_vertices[i].y1 - 30.0f);\n\t\t\tglVertex2f(ground_vertices[i].x2 - 50.0f, ground_vertices[i].y2 - 30.0f);\n\t\t}\n\tglEnd();\n\n\tsprintf (label, \"GND\");\n\tglRasterPos2f (text_x - 70.0f, text_y - 30.0f);\n\tdrawStringBig (label);\n}\n\n\n\nvoid display(void)\n{\n\tglClearColor(0.0, 0.0, 0.0, 1.0);\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\tglLoadIdentity();\n\n\tglColor3f(1, 0, 0);\n\n\tglBegin(GL_LINE_LOOP);\n\tglVertex3f(100.0, 0.0, 0.0);\n        glVertex3f(-100.0, 0.0, 0.0);\n        glEnd();\n\n        glColor3f(0.0, 1.0, 0.0);\n\n        glBegin(GL_LINE_LOOP);\n        glVertex3f(0.0, 100.0, 0.0);\n        glVertex3f(0.0, -100.0, 0.0);\n    glEnd();\n\n\tdraw_resistance();\n\tdraw_outline();\n\n\tdraw_inductance();\n\tdraw_inductance_outline();\n\n\tdraw_power();\n\tdraw_power_outline();\n\n\tdraw_ground();\n\tdraw_ground_outline();\n\n#if 0\n\tif (run)\n\t{\n\t\tdraw_differential_eq_plot();\n\t}\n\n\tdraw_lattice();\n#endif\n\n\tglutSwapBuffers();\n}\n\nvoid reshape(int w, int h)\n{\n    GLfloat n_range = 100.0f;\n\n    if(h == 0)\n        h = 1;\n\n    glViewport(0, 0, w, h);\n    glMatrixMode(GL_PROJECTION);\n    glLoadIdentity();\n\n#if 0\n    if(w <= h)\n        glOrtho(-n_range, n_range, -n_range * h / w, n_range * h / w, -n_range, n_range);\n    else\n        glOrtho(-n_range * w / h, n_range * w / h, -n_range, n_range, -n_range, n_range);\n#endif\n\n\t//glOrtho(-10, 10, -0.5, 0.5, -1, 1);\n\tglOrtho(-100, 100, -100, 100, 1.0, -1.0);\n\n    glMatrixMode(GL_MODELVIEW);\n    glLoadIdentity();\n}\n\nint calc_vertices_num(void)\n{\n\tdouble tmin = 0.0, tmax = 10.0, delta_t = 0.01;\n\treturn (tmax - tmin) / delta_t;\n}\n\nvoid calc_differential_eq(void)\n{\n    int dim = 1;\n\n\tgsl_odeiv2_system sys = {rhs, NULL, dim, NULL};  \n\tgsl_odeiv2_driver * d = gsl_odeiv2_driver_alloc_y_new (&sys, gsl_odeiv2_step_rkf45, 1e-6, 1e-6, 0.0);\n\n\tint cnt = 0;\n\n\tdouble i;\n    double x0 = 0.0,  xf = 10.0;\n    double x = x0;\n    //double y[1] = { 0.5 };\n    double y[1] = { 0.0 };\n\tdouble delta = 0.0000001;\n\n\tfor (i = 0; i <= xf; i += delta)\n    {\n        double xi = x0 + i * (xf-x0) / xf;\n        int status = gsl_odeiv2_driver_apply (d, &x, xi, y);\n\n        if (status != GSL_SUCCESS)\n        {\n            printf (\"error, return value=%d\\n\", status);\n            break;\n        }\n\n\t\tplot_res[cnt].x = x;\n\t\tplot_res[cnt].y = y[0];\n\n\t\t//volt_res[cnt] = y[0] * (resistance / inductance);\n\n\t\tif (cnt < 1001)\n\t\t{\n       \t\tprintf (\"%.8e %.8e\\n\", plot_res[cnt].x, plot_res[cnt].y);\n\t\t}\n\n\t\tcnt++;\n    }\n\n\tprintf(\"Finish Calc\\n\");\n\n    gsl_odeiv2_driver_free (d);\n\n#if 0\n    const gsl_odeiv_step_type *type_ptr = gsl_odeiv_step_rkf45;\n\n    gsl_odeiv_step *step_ptr = gsl_odeiv_step_alloc (type_ptr, dimension);\n    gsl_odeiv_control *control_ptr = gsl_odeiv_control_y_new (eps_abs, eps_rel);\n    gsl_odeiv_evolve *evolve_ptr = gsl_odeiv_evolve_alloc (dimension);\n\n    gsl_odeiv_system my_system;\t/* structure with the rhs function, etc. */\n\n    double mu = 10;\t\t/* parameter for the diffeq */\n    double y[2];\t\t\t/* current solution vector */\n\n    double t, t_next;\t\t/* current and next independent variable */\n    double tmin, tmax, delta_t;\t/* range of t and step size for output */\n\n    double h = 1e-6;\t\t/* starting step size for ode solver */\n\n\tint cnt = 0;\n\tint vertex_num = calc_vertices_num();\n\n    my_system.function = rhs;\t/* the right-hand-side functions dy[i]/dt */\n    my_system.jacobian = NULL;\n    my_system.dimension = dimension;\t/* number of diffeq's */\n    my_system.params = NULL;\n\n    tmin = 0.;\t\t\t/* starting t value */\n    tmax = 10.;\t\t\t/* final t value */\n    delta_t = 0.01;\n\n    y[1] = 0.5;\t\t\t/* initial x value */\n\n    t = tmin;             /* initialize t */\n\n    for (t_next = tmin + delta_t; t_next <= tmax; t_next += delta_t)\n    {\n        while (t < t_next)\t/* evolve from t to t_next */\n        {\n            gsl_odeiv_evolve_apply (evolve_ptr, control_ptr, step_ptr,\n                                    &my_system, &t, t_next, &h, y);\n        }\n\n\t\tplot_res[cnt].x = t;\n\t\tplot_res[cnt].y = y[0];\n        printf (\"%.5e %.5e %.5e\\n\", t, plot_res[cnt].x, plot_res[cnt].y); /* print at t=t_next */\n\n\t\tcnt++;\n    }\n\n    gsl_odeiv_evolve_free (evolve_ptr);\n    gsl_odeiv_control_free (control_ptr);\n    gsl_odeiv_step_free (step_ptr);\n#endif\n}\n\nvoid draw_lattice(void)\n{\n\tint i;\n\tfloat lattice = 0.000001;\n\tchar buf[64] = {0};\n\n\tglColor3f(1, 1, 0);\n\tglBegin(GL_LINES);\n\t\tfor (i = 1; i <= 10; i++)\n\t\t{\n\t\t\tglVertex2f(i * 0.000001, -0.01);\n\t\t\tglVertex2f(i * 0.000001, 0.01);\n\t\t}\n\tglEnd();\n\n\tfor (i = 1; i <= 10; i++)\n\t{\n\t\tsprintf(buf, \"%f\", lattice * i);\n\t    glRasterPos2f (lattice * i - 0.0000005, -0.05);\n\t    drawStringBig (buf);\n\t}\n\n\tglBegin(GL_LINES);\n\t\tfor (i = 1; i <= 10; i++)\n\t\t{\n\t\t\tglVertex2f(-0.0000002, 0.1 * i);\n\t\t\tglVertex2f(0.0000002, 0.1 * i);\n\t\t}\n\tglEnd();\n\n\tfor (i = 1; i <= 10; i++)\n\t{\n\t\tsprintf(buf, \"%.1f\", 0.1 * i);\n\t    glRasterPos2f (-0.0000004, 0.1 * i - 0.05);\n\t    drawStringBig (buf);\n\t}\n}\n\nvoid draw_differential_eq_plot(void)\n{\n\tstatic char label[100];\n\n\tfloat x = 0, x2 = 0, y2, cx, cy;\n\tfloat tmp;\n\tint cache = 0;\n\tint i;\n\n\tglColor3f(0, 1, 1);\n\tglBegin(GL_LINES);\n\t//for(; ; t += step)\n\tfor (i = 0; i < 100000000; i++)\n\t{\n\t\tx2 = plot_res[i].x;\n\t\ty2 = plot_res[i].y;\n\n\t\tif(cache)\n\t\t{\n\t\t\tglVertex2f(cx, cy);\t// \uc774\uc804\uac12\n\t\t\tglVertex2f(x2, y2);\t// \ud604\uc7ac\uac12\n\t\t}\n\n\t\tcache = 1;\n\t\tcx = x2;\n\t\tcy = y2;\n\t\t//printf(\"t = %f, y2 = %f\\n\", x2, y2);\n\t}\n\tglEnd();\n\n\tsprintf (label, \"i(t)\");\n\t// -0.000005\n    glRasterPos2f (-0.0000045, 0.0000045);\n    drawStringBig (label);\n}\n\nvoid draw_lattice2(void)\n{\n\tint i;\n\tfloat lattice = 0.000001;\n\tchar buf[64] = {0};\n\n\tglColor3f(1, 0, 0);\n\tglBegin(GL_LINES);\n\t\tfor (i = 1; i <= 10; i++)\n\t\t{\n\t\t\tglVertex2f(i * 0.000001, -20000);\n\t\t\tglVertex2f(i * 0.000001, 20000);\n\t\t}\n\tglEnd();\n\n\tfor (i = 1; i <= 10; i++)\n\t{\n\t\tsprintf(buf, \"%f\", lattice * i);\n\t    glRasterPos2f (lattice * i - 0.0000005, 50000);\n\t    drawStringBig (buf);\n\t}\n\n\tglBegin(GL_LINES);\n\t\tfor (i = 1; i <= 10; i++)\n\t\t{\n\t\t\tglVertex2f(-0.0000002, -200000 * i);\n\t\t\tglVertex2f(0.0000002, -200000 * i);\n\t\t}\n\tglEnd();\n\n\tfor (i = 1; i <= 10; i++)\n\t{\n\t\tsprintf(buf, \"%d\", -200000 * i);\n\t    glRasterPos2f (-0.0000015, -200000 * i);\n\t    drawStringBig (buf);\n\t}\n\n}\n\nvoid draw_volt_plot(void)\n{\n\tstatic char label[100];\n\n\tfloat x = 0, x2 = 0, y2, cx, cy;\n\tfloat tmp;\n\tint cache = 0;\n\tint i;\n\n\tglColor3f(1, 1, 0);\n\tglBegin(GL_LINES);\n\t//for(; ; t += step)\n\tfor (i = 0; i < 100000000; i++)\n\t{\n\t\tx2 = plot_res[i].x;\n\t\ty2 = plot_res[i].y * (-resistance / inductance);\n\n\t\tif(cache)\n\t\t{\n\t\t\tglVertex2f(cx, cy);\t// \uc774\uc804\uac12\n\t\t\tglVertex2f(x2, y2);\t// \ud604\uc7ac\uac12\n\t\t}\n\n\t\tcache = 1;\n\t\tcx = x2;\n\t\tcy = y2;\n\t\t//printf(\"t = %f, y2 = %f\\n\", x2, y2);\n\t}\n\tglEnd();\n\n\tsprintf (label, \"V(t)\");\n\t// -0.000005\n    glRasterPos2f (-0.0000045, 0.000004);\n    drawStringBig (label);\n}\n\nint main (int argc, char **argv)\n{\n\tglutInit(&argc, argv);\n\tglutInitDisplayMode(GLUT_DOUBLE);\n\tglutInitWindowSize(800, 800);\n\tglutInitWindowPosition(0, 0);\n\tglutCreateWindow(\"Digital Signal Processing\");\n\n\tprintf(\"\uc800\ud56d 1000, \uc778\ub355\ud130: 0.0003, \uc804\uc555: 5V\\n\");\n\n\tglutDisplayFunc(display);\n\tglutReshapeFunc(reshape);\n\tglutMouseFunc(on_mouse);\n\tglutMotionFunc(drag_mouse);\n\t// \uc0c8\ub86d\uac8c \ucd94\uac00\ub41c \uc694\uac83\uc740 \ud0a4\ubcf4\ub4dc \uc785\ub825\uc744 \ucc98\ub9ac\ud558\ub294 \ucf5c\ubc31 \ub4f1\ub85d \ud568\uc218\n\tglutKeyboardFunc(keyboard_handler);\n\tglutMainLoop();\n\n    return 0;\n}\n\n/*************************** rhs ****************************/\n/* \n   x' = v                  ==>  dy[0]/dt = f[0] = y[1]\n   v' = -x + \\mu v (1-x^2) ==>  dy[1]/dt = f[1] = -y[0] + mu*y[1]*(1-y[0]*y[0])\n  \n   x''(t) + x'(t) + x(t) = 0\n   x''(t) = -x'(t) - x(t)\n\n   x' = v            ===> dy[0]/dt = f[0] = y[1]\n   v' = -v - x       ===> dy[1]/dt = f[1] = -y[1] - y[0]\n*/\n\n// https://www.wolframalpha.com/input/?i=y%27%27+%2B+y%27+%2B+y+%3D+0%2C+y%280%29+%3D+1%2C+y%27%280%29+%3D+0, y(0) = 1\n// https://www.wolframalpha.com/input/?i=%28sqrt%283%29+*+sin%28sqrt%283%29+%2F+2%29+%2B+3+*+cos%28sqrt%283%29+%2F+2%29%29+%2F+%283+*+sqrt%28e%29%29, y(1)\n// (sqrt(3) * sin(sqrt(3) / 2) + 3 * cos(sqrt(3) / 2)) / (3 * sqrt(e)), y(1) = 0.6597001...\nint\nrhs (double t, const double y[], double f[], void *params_ptr)\n{\n#if 0\n\tf[0] = y[1];\n\tf[1] = -y[1] - 9 * y[0];\n#endif\n\n\tf[0] =  -(resistance / inductance) * y[0] + voltage / inductance;\n\n    return GSL_SUCCESS;\t\t/* GSL_SUCCESS defined in gsl/errno.h as 0 */\n}\n\n#if 0\n\n\uc8fc\uc11d: \ud604\uc7ac \uc544\ub798 \uc0c1\ud669\uc740 \ubc29\uc804 \uc0c1\ud669\uc785\ub2c8\ub2e4.\n      \ub610\ud55c \ud604\uc7ac \ucf54\ub4dc\ub294 \ucda9\uc804 \uc0c1\ud669\uc785\ub2c8\ub2e4.\n\t  \ub450 \uac00\uc9c0 \ubc84\uc804\uc73c\ub85c \uc791\uc131\uc774 \ud544\uc694\ud568.\n\nV = iR + L * di /dt\n\ucd08\uae30\uc870\uac74 V_L(t) | (t=0) ===> V_L(0) = 0V\n\nV * (1 / L) = i(t) * (R / L) + i`(t)\n\nP(x) = R / L\n\nmu = C * exp^(int P(x)dx)\n\nmu = C * exp^(R/L)t\n\nd (mu * i(t)) / dt = (R/L) exp^(R/L)t * i(t) + exp^(R/L)t * i`(t)\n\nint d(mu * i(t)) / dt = mu * i(t) = c\n\nexp^(R/L)t * i(t) = C\n\ni(t) = C * exp^(-R/L)t\n\ni(t) | (t=0) = 0.5A ===> C = 0.5\n\ni(t) = 0.5 * exp^(-R/L)t\nV(t) = L di / dt\n     = L * 0.5 * (-R/L) * exp^(-R/L)t\n\t-(resistance / inductance)\n#endif\n", "meta": {"hexsha": "8ce56dd8b6025328afb533606f2c63516f376c74", "size": 18434, "ext": "c", "lang": "C", "max_stars_repo_path": "ch6/src/main/rl_circuit_simulation.c", "max_stars_repo_name": "EDDI-RobotAcademy/E4DS-DSP-Basic-Mathematics", "max_stars_repo_head_hexsha": "245385b79807c25081dfe2014c72843226716f92", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-22T00:39:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-22T00:39:04.000Z", "max_issues_repo_path": "ch6/src/main/rl_circuit_simulation.c", "max_issues_repo_name": "EDDI-RobotAcademy/E4DS-DSP-Basic-Mathematics", "max_issues_repo_head_hexsha": "245385b79807c25081dfe2014c72843226716f92", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch6/src/main/rl_circuit_simulation.c", "max_forks_repo_name": "EDDI-RobotAcademy/E4DS-DSP-Basic-Mathematics", "max_forks_repo_head_hexsha": "245385b79807c25081dfe2014c72843226716f92", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-19T01:22:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T01:22:06.000Z", "avg_line_length": 19.7577706324, "max_line_length": 154, "alphanum_fraction": 0.588043832, "num_tokens": 7142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.015663645351566797, "lm_q1q2_score": 0.007039126849862289}}
{"text": "#pragma once\n\n#include <imageview/ImageRowView.h>\n#include <imageview/IsPixelFormat.h>\n#include <imageview/internal/ImageViewIterator.h>\n#include <imageview/internal/ImageViewStorage.h>\n#include <imageview/internal/PixelRef.h>\n\n#include <gsl/assert>\n#include <gsl/span>\n\n#include <cstddef>\n#include <type_traits>\n\nnamespace imageview {\n\n// Non-owning view into a bitmap image with the specified pixel format.\n//\n// \\param PixelFormat - specifies how colors are stored in the bitmap.\n//        ContinuousImageView only supports images with fixed color depth (bits\n//        per pixel). PixelFormat should satisfy IsPixelFormat trait, i.e. be\n//        like\n//          class MyPixelFormat {\n//           public:\n//            using color_type = MyColor;\n//            static constexpr int kBytesPerPixel = N;\n//            color_type read(gsl::span<const std::byte, kBytesPerPixel> pixel_data) const;\n//            void write(const color_type& color, gsl::span<std::byte, kBytesPerPixel> pixel_data) const;\n//          };\n// \\param Mutable - if true, ContinuousImageView provides write access to the\n//        bitmap (naturally, this requires that ContinuousImageView is\n//        constructed from a non-const pointer to the data). Otherwise, only\n//        read-only access is provided.\ntemplate <class PixelFormat, bool Mutable = false>\nclass ContinuousImageView {\n public:\n  static_assert(IsPixelFormat<PixelFormat>::value, \"Not a PixelFormat.\");\n\n  using byte_type = std::conditional_t<Mutable, std::byte, const std::byte>;\n  using value_type = typename PixelFormat::color_type;\n  // If `Mutable == false`, then `reference` is an alias to `value_type`.\n  // Otherwise, it is a proxy class, which mimics `value_type&`:\n  // * is implicitly convertible to `value_type`.\n  // * you can assign a value_type to it, changing the color of the referenced pixel.\n  using reference = std::conditional_t<Mutable, detail::PixelRef<PixelFormat>, value_type>;\n  // Constant LegacyInputIterator whose value_type is @value_type.\n  // It is not, however, a LegacyForwardIterator, because\n  //   std::iterator_traits<iterator>::reference\n  // is not const value_type&.\n  // Nevertheless, this iterator supports all arithmetic operations of LegacyRandomAccessIterator, e.g.,\n  //   `it += n`, ` --it`, `it[n]`.\n  using const_iterator = detail::ImageViewIterator<PixelFormat, false>;\n  // LegacyInputIterator whose value_type is @value_type. If Mutable == true, then it also\n  // models LegacyOutputIterator. It is not, however, a LegacyForwardIterator, because\n  //   std::iterator_traits<iterator>::reference\n  // is neither value_type& nor const value_type&.\n  // Nevertheless, this iterator supports all arithmetic operations of LegacyRandomAccessIterator, e.g.,\n  //   `it += n`, ` --it`, `it[n]`.\n  using iterator = detail::ImageViewIterator<PixelFormat, Mutable>;\n\n  // Construct an empty view.\n  // This constructor is only available if PixelFormat is default-constructible.\n  template <class Enable = std::enable_if_t<std::is_default_constructible_v<PixelFormat>>>\n  constexpr ContinuousImageView() noexcept(noexcept(std::is_nothrow_default_constructible_v<PixelFormat>)) {}\n\n  // Construct a view into an image.\n  // This constructor is only available if PixelFormat is default-constructible\n  // \\param height - height of the image.\n  // \\param width - width of the image.\n  // \\param data - pointer to the uncompressed RGB24 bitmap data. The size of\n  //        the array should be exactly\n  //          height * width * PixelFormat::kBytesPerPixel.\n  //        Pixels are assumed to be stored contiguously, with each pixel\n  //        occupying exactly PixelFormat::kBytesPerPixel.\n  template <class Enable = std::enable_if_t<std::is_default_constructible_v<PixelFormat>>>\n  constexpr ContinuousImageView(unsigned int height, unsigned int width, gsl::span<byte_type> data) noexcept(\n      std::is_nothrow_default_constructible_v<PixelFormat>);\n\n  // Construct a view into an image.\n  // \\param height - height of the image.\n  // \\param width - width of the image.\n  // \\param data - pointer to the uncompressed RGB24 bitmap data. The size of\n  //        the array should be exactly\n  //          height * width * PixelFormat::kBytesPerPixel.\n  //        Pixels are assumed to be stored contiguously, with each pixel\n  //        occupying exactly PixelFormat::kBytesPerPixel.\n  // \\param pixel_format - PixelFormat instance to use.\n  constexpr ContinuousImageView(unsigned int height, unsigned int width, gsl::span<byte_type> data,\n                                const PixelFormat& pixel_format);\n\n  // Construct a view into an image.\n  // \\param height - height of the image.\n  // \\param width - width of the image.\n  // \\param data - pointer to the uncompressed RGB24 bitmap data. The size of\n  //        the array should be exactly\n  //          height * width * PixelFormat::kBytesPerPixel.\n  //        Pixels are assumed to be stored contiguously, with each pixel\n  //        occupying exactly PixelFormat::kBytesPerPixel.\n  // \\param pixel_format - PixelFormat instance to use.\n  constexpr ContinuousImageView(unsigned int height, unsigned int width, gsl::span<byte_type> data,\n                                PixelFormat&& pixel_format);\n\n  // Construct a read-only view from a mutable view.\n  template <class Enable = std::enable_if_t<!Mutable>>\n  constexpr ContinuousImageView(ContinuousImageView<PixelFormat, !Mutable> image);\n\n  // Returns the height of the image.\n  constexpr unsigned int height() const noexcept;\n\n  // Returns the width of the image.\n  constexpr unsigned int width() const noexcept;\n\n  // Returns the total number of pixels.\n  constexpr std::size_t area() const noexcept;\n\n  // Returns true if the image has zero area, false otherwise.\n  constexpr bool empty() const noexcept;\n\n  // Returns the pixel format used by this image.\n  constexpr const PixelFormat& pixelFormat() const noexcept;\n\n  // Returns the pointer to the bitmap data.\n  constexpr gsl::span<byte_type> data() const noexcept;\n\n  // Returns the total size of the bitmap in bytes.\n  constexpr std::size_t size_bytes() const noexcept;\n\n  // Returns an iterator to the first pixel.\n  constexpr iterator begin() const;\n\n  // Returns a const iterator to the first pixel.\n  constexpr const_iterator cbegin() const;\n\n  // Returns an iterator past the last pixel.\n  constexpr iterator end() const;\n\n  // Returns a const iterator past the last pixel.\n  constexpr const_iterator cend() const;\n\n  // Access the specified pixel.\n  // \\param y - Y coordinate of the pixel. Should be within [0; height()).\n  // \\param x - X coordinate of the pixel. Should be within [0; width()).\n  // \\return the color of the specified pixel.\n  constexpr reference operator()(unsigned int y, unsigned int x) const;\n\n  // Returns a non-owning view into the specified row of the image.\n  // \\param y - 0-based index of the row. Should be within [0; height()).\n  // \\return a non-owning view into the row @y.\n  constexpr ImageRowView<PixelFormat, Mutable> row(unsigned int y) const;\n\n private:\n  constexpr gsl::span<byte_type, PixelFormat::kBytesPerPixel> getPixelData(unsigned int y, unsigned int x) const;\n\n  detail::ImageViewStorage<PixelFormat, Mutable> storage_;\n  unsigned int height_ = 0;\n  unsigned int width_ = 0;\n};\n\n// Convert a ContinuousImageView into an ImageRowView.\n// \\param image - input image.\n// \\return an ImageRowView referring to the same data as image; the number of\n//         elements in the returned view equals image.area().\ntemplate <class PixelFormat, bool Mutable>\nconstexpr ImageRowView<PixelFormat, Mutable> flatten(ContinuousImageView<PixelFormat, Mutable> image) {\n  return ImageRowView<PixelFormat, Mutable>(image.data(), image.area(), image.pixelFormat());\n}\n\ntemplate <class PixelFormat, bool Mutable>\ntemplate <class Enable>\nconstexpr ContinuousImageView<PixelFormat, Mutable>::ContinuousImageView(\n    unsigned int height, unsigned int width,\n    gsl::span<byte_type> data) noexcept(std::is_nothrow_default_constructible_v<PixelFormat>)\n    : storage_(data.data()), height_(height), width_(width) {\n  Expects(data.size() == height * width * PixelFormat::kBytesPerPixel);\n}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr ContinuousImageView<PixelFormat, Mutable>::ContinuousImageView(unsigned int height, unsigned int width,\n                                                                         gsl::span<byte_type> data,\n                                                                         const PixelFormat& pixel_format)\n    : storage_(data.data(), pixel_format), height_(height), width_(width) {\n  Expects(data.size() == height * width * PixelFormat::kBytesPerPixel);\n}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr ContinuousImageView<PixelFormat, Mutable>::ContinuousImageView(unsigned int height, unsigned int width,\n                                                                         gsl::span<byte_type> data,\n                                                                         PixelFormat&& pixel_format)\n    : storage_(data.data(), std::move(pixel_format)), height_(height), width_(width) {\n  Expects(data.size() == height * width * PixelFormat::kBytesPerPixel);\n}\n\ntemplate <class PixelFormat, bool Mutable>\ntemplate <class Enable>\nconstexpr ContinuousImageView<PixelFormat, Mutable>::ContinuousImageView(\n    ContinuousImageView<PixelFormat, !Mutable> image)\n    : ContinuousImageView(image.height(), image.width(), image.data(), image.pixelFormat()) {}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr unsigned int ContinuousImageView<PixelFormat, Mutable>::height() const noexcept {\n  return height_;\n}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr unsigned int ContinuousImageView<PixelFormat, Mutable>::width() const noexcept {\n  return width_;\n}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr std::size_t ContinuousImageView<PixelFormat, Mutable>::area() const noexcept {\n  return static_cast<std::size_t>(height_) * width_;\n}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr bool ContinuousImageView<PixelFormat, Mutable>::empty() const noexcept {\n  return height_ == 0 || width_ == 0;\n}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr const PixelFormat& ContinuousImageView<PixelFormat, Mutable>::pixelFormat() const noexcept {\n  return storage_.pixelFormat();\n}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr auto ContinuousImageView<PixelFormat, Mutable>::data() const noexcept -> gsl::span<byte_type> {\n  return gsl::span<byte_type>(storage_.data(), size_bytes());\n}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr std::size_t ContinuousImageView<PixelFormat, Mutable>::size_bytes() const noexcept {\n  return area() * PixelFormat::kBytesPerPixel;\n}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr auto ContinuousImageView<PixelFormat, Mutable>::begin() const -> iterator {\n  return iterator(storage_.data(), pixelFormat());\n}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr auto ContinuousImageView<PixelFormat, Mutable>::cbegin() const -> const_iterator {\n  return const_iterator(storage_.data(), pixelFormat());\n}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr auto ContinuousImageView<PixelFormat, Mutable>::end() const -> iterator {\n  return iterator(storage_.data() + size_bytes(), pixelFormat());\n}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr auto ContinuousImageView<PixelFormat, Mutable>::cend() const -> const_iterator {\n  return const_iterator(storage_.data() + size_bytes(), pixelFormat());\n}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr auto ContinuousImageView<PixelFormat, Mutable>::getPixelData(unsigned int y, unsigned int x) const\n    -> gsl::span<byte_type, PixelFormat::kBytesPerPixel> {\n  Expects(y < height_);\n  Expects(x < width_);\n  const std::size_t offset = (y * width_ + x) * PixelFormat::kBytesPerPixel;\n  return gsl::span<byte_type, PixelFormat::kBytesPerPixel>(storage_.data() + offset, PixelFormat::kBytesPerPixel);\n}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr auto ContinuousImageView<PixelFormat, Mutable>::operator()(unsigned int y, unsigned int x) const\n    -> reference {\n  const gsl::span<byte_type, PixelFormat::kBytesPerPixel> pixel_data = getPixelData(y, x);\n  if constexpr (Mutable) {\n    return detail::PixelRef<PixelFormat>(pixel_data, storage_.pixelFormat());\n  } else {\n    return storage_.pixelFormat().read(pixel_data);\n  }\n}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr ImageRowView<PixelFormat, Mutable> ContinuousImageView<PixelFormat, Mutable>::row(unsigned int y) const {\n  Expects(y < height_);\n  const std::size_t bytes_per_row = static_cast<std::size_t>(width_) * PixelFormat::kBytesPerPixel;\n  const gsl::span<byte_type> row_data(storage_.data() + y * bytes_per_row, bytes_per_row);\n  return ImageRowView<PixelFormat, Mutable>(row_data, width_, pixelFormat());\n}\n\n}  // namespace imageview\n", "meta": {"hexsha": "bb8432b865371bd2fcb368739beff863303110fa", "size": 12898, "ext": "h", "lang": "C", "max_stars_repo_path": "include/imageview/ContinuousImageView.h", "max_stars_repo_name": "alexanderbelous/imageview", "max_stars_repo_head_hexsha": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/imageview/ContinuousImageView.h", "max_issues_repo_name": "alexanderbelous/imageview", "max_issues_repo_head_hexsha": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/imageview/ContinuousImageView.h", "max_forks_repo_name": "alexanderbelous/imageview", "max_forks_repo_head_hexsha": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.5759717314, "max_line_length": 115, "alphanum_fraction": 0.719879051, "num_tokens": 2811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2365162364457076, "lm_q2_score": 0.029760092440045342, "lm_q1q2_score": 0.007038745060195879}}
{"text": "// --------------------------------------------------------------------------\n//                   OpenMS -- Open-Source Mass Spectrometry\n// --------------------------------------------------------------------------\n// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,\n// ETH Zurich, and Freie Universitaet Berlin 2002-2013.\n//\n// This software is released under a three-clause BSD license:\n//  * Redistributions of source code must retain the above copyright\n//    notice, this list of conditions and the following disclaimer.\n//  * Redistributions in binary form must reproduce the above copyright\n//    notice, this list of conditions and the following disclaimer in the\n//    documentation and/or other materials provided with the distribution.\n//  * Neither the name of any author or any participating institution\n//    may be used to endorse or promote products derived from this software\n//    without specific prior written permission.\n// For a full list of authors, refer to the file AUTHORS.\n// --------------------------------------------------------------------------\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING\n// INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// --------------------------------------------------------------------------\n// $Maintainer: Erhan Kenar $\n// $Authors: $\n// --------------------------------------------------------------------------\n\n#ifndef OPENMS_DATASTRUCTURES_MATRIX_H\n#define OPENMS_DATASTRUCTURES_MATRIX_H\n\n#include <OpenMS/CONCEPT/Macros.h>\n\n#include <cmath> // pow()\n#include <iomanip>\n#include <vector>\n\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_linalg.h>\n\nnamespace OpenMS\n{\n\n  /**\n    @brief A two-dimensional matrix.  Similar to std::vector, but uses a binary\n    operator(,) for element access.\n\n    Think of it as a random access container.  You can also generate gray\n    scale images.  This data structure is not designed to be used for linear algebra,\n    but rather a simple two-dimensional array.\n\n    The following member functions of the base class std::vector<ValueType>\n    can also be used:\n\n    <ul>\n      <li>begin</li>\n      <li>end</li>\n      <li>rbegin</li>\n      <li>rend</li>\n      <li>front</li>\n      <li>back</li>\n      <li>assign</li>\n      <li>empty</li>\n      <li>size</li>\n      <li>capacity</li>\n      <li>max_size</li>\n    </ul>\n\n         @ingroup Datastructures\n  */\n  template <typename Value>\n  class Matrix :\n    protected std::vector<Value>\n  {\nprotected:\n    typedef std::vector<Value> Base;\n\npublic:\n\n    ///@name STL compliance type definitions\n    //@{\n    typedef Base container_type;\n\n    typedef typename Base::difference_type difference_type;\n    typedef typename Base::size_type size_type;\n\n    typedef typename Base::const_iterator const_iterator;\n    typedef typename Base::const_reverse_iterator const_reverse_iterator;\n    typedef typename Base::iterator iterator;\n    typedef typename Base::reverse_iterator reverse_iterator;\n\n    typedef typename Base::const_reference const_reference;\n    typedef typename Base::pointer pointer;\n    typedef typename Base::reference reference;\n    typedef typename Base::value_type value_type;\n\n    typedef typename Base::allocator_type allocator_type;\n    //@}\n\n    ///@name OpenMS compliance type definitions\n    //@{\n    typedef Base ContainerType;\n    typedef difference_type DifferenceType;\n    typedef size_type SizeType;\n\n    typedef const_iterator ConstIterator;\n    typedef const_reverse_iterator ConstReverseIterator;\n    typedef iterator Iterator;\n    typedef reverse_iterator ReverseIterator;\n\n    typedef const_reference ConstReference;\n    typedef pointer Pointer;\n    typedef reference Reference;\n    typedef value_type ValueType;\n\n    typedef allocator_type AllocatorType;\n    //@}\n\n    ///@name Constructors, assignment, and destructor\n    //@{\n    Matrix() :\n      Base(),\n      rows_(0),\n      cols_(0)\n    {}\n\n    Matrix(const SizeType rows, const SizeType cols, ValueType value = ValueType()) :\n      Base(rows * cols, value),\n      rows_(rows),\n      cols_(cols)\n    {}\n\n    Matrix(const Matrix& source) :\n      Base(source),\n      rows_(source.rows_),\n      cols_(source.cols_)\n    {}\n\n    Matrix& operator=(const Matrix& rhs)\n    {\n      Base::operator=(rhs);\n      rows_ = rhs.rows_;\n      cols_ = rhs.cols_;\n      return *this;\n    }\n\n    ~Matrix() {}\n    //@}\n\n    ///@name Accessors\n    //@{\n    const_reference operator()(size_type const i, size_type const j) const\n    {\n      return getValue(i, j);\n    }\n\n    reference operator()(size_type const i, size_type const j)\n    {\n      return getValue(i, j);\n    }\n\n    const_reference getValue(size_type const i, size_type const j) const\n    {\n      return Base::operator[](index(i, j));\n    }\n\n    reference getValue(size_type const i, size_type const j)\n    {\n      return Base::operator[](index(i, j));\n    }\n\n    void setValue(size_type const i, size_type const j, value_type value)\n    {\n      Base::operator[](index(i, j)) = value;\n    }\n\n    /// Return the i-th row of the matrix as a vector.\n    container_type row(size_type const i) const\n    {\n#ifdef OPENMS_DEBUG\n      if (i >= rows_) throw Exception::IndexOverflow(__FILE__, __LINE__, __PRETTY_FUNCTION__, i, rows_);\n#endif\n      container_type values(cols_);\n      for (size_type j = 0; j < cols_; j++)\n      {\n        values[j] = Base::operator[](index(i, j));\n      }\n      return values;\n    }\n\n    /// Return the i-th column of the matrix as a vector.\n    container_type col(size_type const i) const\n    {\n#ifdef OPENMS_DEBUG\n      if (i >= cols_) throw Exception::IndexOverflow(__FILE__, __LINE__, __PRETTY_FUNCTION__, i, cols_);\n#endif\n      container_type values(rows_);\n      for (size_type j = 0; j < rows_; j++)\n      {\n        values[j] = Base::operator[](index(j, i));\n      }\n      return values;\n    }\n\n    //@}\n\n\n    /**\n      @name Pure access declarations\n\n      These make begin(), end() etc. from container_type accessible.\n    */\n    //@{\npublic:\n\n    using Base::begin;\n    using Base::end;\n    using Base::rbegin;\n    using Base::rend;\n\n    using Base::front;\n    using Base::back;\n    using Base::assign;\n\n    using Base::empty;\n    using Base::size;\n\n    using Base::capacity;\n    using Base::max_size;\n\n    //@}\n\n    void clear()\n    {\n      Base::clear();\n      rows_ = 0;\n      cols_ = 0;\n    }\n\n    void resize(size_type i, size_type j, value_type value = value_type())\n    {\n      rows_ = i;\n      cols_ = j;\n      Base::resize(rows_ * cols_, value);\n    }\n\n    void resize(std::pair<Size, Size> const& size_pair, value_type value = value_type())\n    {\n      rows_ = size_pair.first;\n      cols_ = size_pair.second;\n      Base::resize(rows_ * cols_, value);\n    }\n\n    /// Number of rows\n    SizeType rows() const\n    {\n      return rows_;\n    }\n\n    /// Number of columns\n    SizeType cols() const\n    {\n      return cols_;\n    }\n\n    std::pair<Size, Size> sizePair() const\n    {\n      return std::pair<Size, Size>(rows_, cols_);\n    }\n\n    /**\n      @brief Calculate the index into the underlying vector from row and column.\n      Note that Matrix uses the (row,column) lexicographic ordering for indexing.\n    */\n    SizeType const index(SizeType row, SizeType col) const\n    {\n#ifdef OPENMS_DEBUG\n      if (row >= rows_) throw Exception::IndexOverflow(__FILE__, __LINE__, __PRETTY_FUNCTION__, row, rows_);\n      if (col >= cols_) throw Exception::IndexOverflow(__FILE__, __LINE__, __PRETTY_FUNCTION__, col, cols_);\n#endif\n      return row * cols_ + col;\n    }\n\n    /**\n      @brief Calculate the row and column from an index into the underlying vector.\n      Note that Matrix uses the (row,column) lexicographic ordering for indexing.\n    */\n    std::pair<Size, Size> const indexPair(Size index) const\n    {\n#ifdef OPENMS_DEBUG\n      if (index >= size()) throw Exception::IndexOverflow(__FILE__, __LINE__, __PRETTY_FUNCTION__, index, size() - 1);\n#endif\n      return std::pair<SizeType, SizeType>(index / cols_, index % cols_);\n    }\n\n    /**\n      @brief Calculate the column from an index into the underlying vector.\n      Note that Matrix uses the (row,column) lexicographic ordering for indexing.\n    */\n    SizeType colIndex(SizeType index) const\n    {\n#ifdef OPENMS_DEBUG\n      if (index >= size()) throw Exception::IndexOverflow(__FILE__, __LINE__, __PRETTY_FUNCTION__, index, size() - 1);\n#endif\n      return index % cols_;\n    }\n\n    /**\n      @brief Calculate the row from an index into the underlying vector.\n      Note that Matrix uses the (row,column) lexicographic ordering for indexing.\n    */\n    SizeType rowIndex(SizeType index) const\n    {\n#ifdef OPENMS_DEBUG\n      if (index >= size()) throw Exception::IndexOverflow(__FILE__, __LINE__, __PRETTY_FUNCTION__, index, size() - 1);\n#endif\n\n      return index / cols_;\n    }\n\n    /**\n      @brief Equality comparator.\n\n      If matrices have different row or column numbers, throws a precondition exception.\n    */\n    bool operator==(Matrix const& rhs) const\n    {\n      OPENMS_PRECONDITION(cols_ == rhs.cols_,\n                          \"Matrices have different row sizes.\");\n      OPENMS_PRECONDITION(rows_ == rhs.rows_,\n                          \"Matrices have different column sizes.\");\n      return static_cast<typename Matrix<Value>::Base const&>(*this) == static_cast<typename Matrix<Value>::Base const&>(rhs);\n    }\n\n    /**\n      @brief Less-than comparator.  Comparison is done lexicographically: first by row, then by column.\n\n      If matrices have different row or column numbers, throws a precondition exception.\n    */\n    bool operator<(Matrix const& rhs) const\n    {\n      OPENMS_PRECONDITION(cols_ == rhs.cols_,\n                          \"Matrices have different row sizes.\");\n      OPENMS_PRECONDITION(rows_ == rhs.rows_,\n                          \"Matrices have different column sizes.\");\n      return static_cast<typename Matrix<Value>::Base const&>(*this) < static_cast<typename Matrix<Value>::Base const&>(rhs);\n    }\n\n    /// set matrix to 2D arrays values\n    template <int ROWS, int COLS>\n    void setMatrix(const ValueType matrix[ROWS][COLS])\n    {\n      resize(ROWS, COLS);\n      for (SizeType i = 0; i < this->rows_; ++i)\n      {\n        for (SizeType j = 0; j < this->cols_; ++j)\n        {\n          setValue(i, j, matrix[i][j]);\n        }\n      }\n    }\n\n    /**\n      @brief create gsl_matrix*\n\n      allocate and return an equivalent GSL matrix\n      @note Works only for Matrix<double> and Matrix<float>\n      @note Clean up the gsl_matrix using gsl_matrix_free (gsl_matrix * m)\n    */\n    gsl_matrix* toGslMatrix()\n    {\n      gsl_matrix* m_ptr = gsl_matrix_alloc(rows_, cols_);\n\n      for (size_type i = 0; i < this->rows_; ++i)\n      {\n        for (size_type j = 0; j < this->cols_; ++j)\n        {\n          gsl_matrix_set(m_ptr, i, j, (double) (*this)(i, j));\n        }\n      }\n\n      return m_ptr;\n    }\n\nprotected:\n\n    ///@name Data members\n    //@{\n    /// Number of rows (height of a column)\n    SizeType rows_;\n    /// Number of columns (width of a row)\n    SizeType cols_;\n    //@}\n\n  }; // class Matrix\n\n  // template<> OPENMS_DLLAPI gsl_matrix* Matrix<double>::toGslMatrix();\n  // template<> OPENMS_DLLAPI gsl_matrix* Matrix<float>::toGslMatrix();\n\n  /**\n    @brief Print the contents to a stream.\n\n    @relatesalso Matrix\n  */\n  template <typename Value>\n  std::ostream& operator<<(std::ostream& os, const Matrix<Value>& matrix)\n  {\n    typedef typename Matrix<Value>::size_type size_type;\n    for (size_type i = 0; i < matrix.rows(); ++i)\n    {\n      for (size_type j = 0; j < matrix.cols(); ++j)\n      {\n        os << std::setprecision(6) << std::setw(6) << matrix(i, j) << ' ';\n      }\n      os << std::endl;\n    }\n    return os;\n  }\n\n} // namespace OpenMS\n\n#endif // OPENMS_DATASTRUCTURES_MATRIX_H\n", "meta": {"hexsha": "3c2b039149dcaec122bb3b54767536fb2f9de14f", "size": 12485, "ext": "h", "lang": "C", "max_stars_repo_path": "include/OpenMS/DATASTRUCTURES/Matrix.h", "max_stars_repo_name": "open-ms/all-svn-branches", "max_stars_repo_head_hexsha": "b182ba576e0cbfbe420b8edb0dd1c42bb6c973f3", "max_stars_repo_licenses": ["Zlib", "Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-05-23T03:43:10.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-23T03:43:10.000Z", "max_issues_repo_path": "include/OpenMS/DATASTRUCTURES/Matrix.h", "max_issues_repo_name": "open-ms/all-svn-branches", "max_issues_repo_head_hexsha": "b182ba576e0cbfbe420b8edb0dd1c42bb6c973f3", "max_issues_repo_licenses": ["Zlib", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/OpenMS/DATASTRUCTURES/Matrix.h", "max_forks_repo_name": "open-ms/all-svn-branches", "max_forks_repo_head_hexsha": "b182ba576e0cbfbe420b8edb0dd1c42bb6c973f3", "max_forks_repo_licenses": ["Zlib", "Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0348837209, "max_line_length": 126, "alphanum_fraction": 0.6261914297, "num_tokens": 2878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21206879937726764, "lm_q2_score": 0.033085974694221476, "lm_q1q2_score": 0.007016502929630208}}
{"text": "#ifndef __GSL_PERMUTE_MATRIX_H__\n#define __GSL_PERMUTE_MATRIX_H__\n\n#if !defined( GSL_FUN )\n#  if !defined( GSL_DLL )\n#    define GSL_FUN extern\n#  elif defined( BUILD_GSL_DLL )\n#    define GSL_FUN extern __declspec(dllexport)\n#  else\n#    define GSL_FUN extern __declspec(dllimport)\n#  endif\n#endif\n\n#include <gsl/gsl_permute_matrix_complex_long_double.h>\n#include <gsl/gsl_permute_matrix_complex_double.h>\n#include <gsl/gsl_permute_matrix_complex_float.h>\n\n#include <gsl/gsl_permute_matrix_long_double.h>\n#include <gsl/gsl_permute_matrix_double.h>\n#include <gsl/gsl_permute_matrix_float.h>\n\n#include <gsl/gsl_permute_matrix_ulong.h>\n#include <gsl/gsl_permute_matrix_long.h>\n\n#include <gsl/gsl_permute_matrix_uint.h>\n#include <gsl/gsl_permute_matrix_int.h>\n\n#include <gsl/gsl_permute_matrix_ushort.h>\n#include <gsl/gsl_permute_matrix_short.h>\n\n#include <gsl/gsl_permute_matrix_uchar.h>\n#include <gsl/gsl_permute_matrix_char.h>\n\n#endif /* __GSL_PERMUTE_MATRIX_H__ */\n", "meta": {"hexsha": "4710f1465cae35ec9f9dccb5e2d8c81248cee972", "size": 966, "ext": "h", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_permute_matrix.h", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-28T08:20:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-28T08:20:20.000Z", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_permute_matrix.h", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_permute_matrix.h", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-14T12:45:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-14T12:45:35.000Z", "avg_line_length": 27.6, "max_line_length": 55, "alphanum_fraction": 0.8053830228, "num_tokens": 272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2393493581744072, "lm_q2_score": 0.029312228843432448, "lm_q1q2_score": 0.007015863160336902}}
{"text": "#include <mpi.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <gsl/gsl_math.h>\n\n#include \"allvars.h\"\n#include \"proto.h\"\n\n#ifdef MPISENDRECV_CHECKSUM\n\n#undef MPI_Sendrecv\n\n\nint MPI_Check_Sendrecv(void *sendbuf, int sendcount, MPI_Datatype sendtype,\n\t\t       int dest, int sendtag, void *recvbufreal, int recvcount,\n\t\t       MPI_Datatype recvtype, int source, int recvtag, MPI_Comm comm, MPI_Status * status)\n{\n  int checksumtag = 1000, errtag = 2000;\n  int i, iter = 0, err_flag, err_flag_imported, size_sendtype, size_recvtype;\n  long long sendCheckSum, recvCheckSum, importedCheckSum;\n  unsigned char *p, *buf, *recvbuf;\n\n  if(dest != source)\n    endrun(3);\n\n  MPI_Type_size(sendtype, &size_sendtype);\n  MPI_Type_size(recvtype, &size_recvtype);\n\n  if(dest == ThisTask)\n    {\n      memcpy(recvbufreal, sendbuf, recvcount * size_recvtype);\n      return 0;\n    }\n\n\n  if(!(buf = mymalloc(recvcount * size_recvtype + 1024)))\n    endrun(6);\n\n  for(i = 0, p = buf; i < recvcount * size_recvtype + 1024; i++)\n    *p++ = 255;\n\n  recvbuf = buf + 512;\n\n  MPI_Sendrecv(sendbuf, sendcount, sendtype, dest, sendtag,\n\t       recvbuf, recvcount, recvtype, source, recvtag, comm, status);\n\n  for(i = 0, p = buf; i < 512; i++, p++)\n    {\n      if(*p != 255)\n\t{\n\t  printf\n\t    (\"MPI-ERROR: Task=%d/%s: Recv occured before recv buffer. message-size=%d from %d, i=%d c=%d\\n\",\n\t     ThisTask, getenv(\"HOST\"), recvcount, dest, i, *p);\n\t  fflush(stdout);\n\t  endrun(6);\n\t}\n    }\n\n  for(i = 0, p = recvbuf + recvcount * size_recvtype; i < 512; i++, p++)\n    {\n      if(*p != 255)\n\t{\n\t  printf\n\t    (\"MPI-ERROR: Task=%d/%s: Recv occured after recv buffer. message-size=%d from %d, i=%d c=%d\\n\",\n\t     ThisTask, getenv(\"HOST\"), recvcount, dest, i, *p);\n\t  fflush(stdout);\n\t  endrun(6);\n\t}\n    }\n\n\n  for(i = 0, p = sendbuf, sendCheckSum = 0; i < sendcount * size_sendtype; i++, p++)\n    sendCheckSum += *p;\n\n  importedCheckSum = 0;\n\n  if(dest > ThisTask)\n    {\n      if(sendcount > 0)\n\tMPI_Ssend(&sendCheckSum, sizeof(sendCheckSum), MPI_BYTE, dest, checksumtag, MPI_COMM_WORLD);\n      if(recvcount > 0)\n\tMPI_Recv(&importedCheckSum, sizeof(importedCheckSum), MPI_BYTE, dest, checksumtag, MPI_COMM_WORLD,\n\t\t status);\n    }\n  else\n    {\n      if(recvcount > 0)\n\tMPI_Recv(&importedCheckSum, sizeof(importedCheckSum), MPI_BYTE, dest, checksumtag, MPI_COMM_WORLD,\n\t\t status);\n      if(sendcount > 0)\n\tMPI_Ssend(&sendCheckSum, sizeof(sendCheckSum), MPI_BYTE, dest, checksumtag, MPI_COMM_WORLD);\n    }\n\n  checksumtag++;\n\n  for(i = 0, p = recvbuf, recvCheckSum = 0; i < recvcount * size_recvtype; i++, p++)\n    recvCheckSum += *p;\n\n\n  err_flag = err_flag_imported = 0;\n\n  if(recvCheckSum != importedCheckSum)\n    {\n      printf\n\t(\"MPI-ERROR: Receive error on task=%d/%s from task=%d, message size=%d, sendcount=%d checksums= %d %d  %d %d. Try to fix it...\\n\",\n\t ThisTask, getenv(\"HOST\"), source, recvcount, sendcount, (int) (recvCheckSum >> 32),\n\t (int) recvCheckSum, (int) (importedCheckSum >> 32), (int) importedCheckSum);\n      fflush(stdout);\n\n      err_flag = 1;\n    }\n\n  if(dest > ThisTask)\n    {\n      MPI_Ssend(&err_flag, 1, MPI_INT, dest, errtag, MPI_COMM_WORLD);\n      MPI_Recv(&err_flag_imported, 1, MPI_INT, dest, errtag, MPI_COMM_WORLD, status);\n    }\n  else\n    {\n      MPI_Recv(&err_flag_imported, 1, MPI_INT, dest, errtag, MPI_COMM_WORLD, status);\n      MPI_Ssend(&err_flag, 1, MPI_INT, dest, errtag, MPI_COMM_WORLD);\n    }\n  errtag++;\n\n  if(err_flag > 0 || err_flag_imported > 0)\n    {\n      printf(\"Task=%d is on %s, wants to send %d and has checksum=%d %d of send data\\n\",\n\t     ThisTask, getenv(\"HOST\"), sendcount, (int) (sendCheckSum >> 32), (int) sendCheckSum);\n      fflush(stdout);\n\n      do\n\t{\n\t  sendtag++;\n\t  recvtag++;\n\n\t  for(i = 0, p = recvbuf; i < recvcount * size_recvtype; i++, p++)\n\t    *p = 0;\n\n\t  if((iter & 1) == 0)\n\t    {\n\t      if(dest > ThisTask)\n\t\t{\n\t\t  if(sendcount > 0)\n\t\t    MPI_Ssend(sendbuf, sendcount, sendtype, dest, sendtag, MPI_COMM_WORLD);\n\t\t  if(recvcount > 0)\n\t\t    MPI_Recv(recvbuf, recvcount, recvtype, dest, recvtag, MPI_COMM_WORLD, status);\n\t\t}\n\t      else\n\t\t{\n\t\t  if(recvcount > 0)\n\t\t    MPI_Recv(recvbuf, recvcount, recvtype, dest, recvtag, MPI_COMM_WORLD, status);\n\t\t  if(sendcount > 0)\n\t\t    MPI_Ssend(sendbuf, sendcount, sendtype, dest, sendtag, MPI_COMM_WORLD);\n\t\t}\n\t    }\n\t  else\n\t    {\n\t      if(iter > 5)\n\t\t{\n\t\t  printf(\"we're trying to send each byte now on task=%d (iter=%d)\\n\", ThisTask, iter);\n\t\t  fflush(stdout);\n\t\t  if(dest > ThisTask)\n\t\t    {\n\t\t      for(i = 0, p = sendbuf; i < sendcount * size_sendtype; i++, p++)\n\t\t\tMPI_Ssend(p, 1, MPI_BYTE, dest, i, MPI_COMM_WORLD);\n\t\t      for(i = 0, p = recvbuf; i < recvcount * size_recvtype; i++, p++)\n\t\t\tMPI_Recv(p, 1, MPI_BYTE, dest, i, MPI_COMM_WORLD, status);\n\t\t    }\n\t\t  else\n\t\t    {\n\t\t      for(i = 0, p = recvbuf; i < recvcount * size_recvtype; i++, p++)\n\t\t\tMPI_Recv(p, 1, MPI_BYTE, dest, i, MPI_COMM_WORLD, status);\n\t\t      for(i = 0, p = sendbuf; i < sendcount * size_sendtype; i++, p++)\n\t\t\tMPI_Ssend(p, 1, MPI_BYTE, dest, i, MPI_COMM_WORLD);\n\t\t    }\n\t\t}\n\t      else\n\t\t{\n\t\t  MPI_Sendrecv(sendbuf, sendcount, sendtype, dest, sendtag,\n\t\t\t       recvbuf, recvcount, recvtype, source, recvtag, comm, status);\n\t\t}\n\t    }\n\n\t  importedCheckSum = 0;\n\n\t  for(i = 0, p = sendbuf, sendCheckSum = 0; i < sendcount * size_sendtype; i++, p++)\n\t    sendCheckSum += *p;\n\n\t  printf(\"Task=%d gas send_checksum=%d %d\\n\", ThisTask, (int) (sendCheckSum >> 32),\n\t\t (int) sendCheckSum);\n\t  fflush(stdout);\n\n\t  if(dest > ThisTask)\n\t    {\n\t      if(sendcount > 0)\n\t\tMPI_Ssend(&sendCheckSum, sizeof(sendCheckSum), MPI_BYTE, dest, checksumtag, MPI_COMM_WORLD);\n\t      if(recvcount > 0)\n\t\tMPI_Recv(&importedCheckSum, sizeof(importedCheckSum), MPI_BYTE, dest, checksumtag,\n\t\t\t MPI_COMM_WORLD, status);\n\t    }\n\t  else\n\t    {\n\t      if(recvcount > 0)\n\t\tMPI_Recv(&importedCheckSum, sizeof(importedCheckSum), MPI_BYTE, dest, checksumtag,\n\t\t\t MPI_COMM_WORLD, status);\n\t      if(sendcount > 0)\n\t\tMPI_Ssend(&sendCheckSum, sizeof(sendCheckSum), MPI_BYTE, dest, checksumtag, MPI_COMM_WORLD);\n\t    }\n\n\t  for(i = 0, p = recvbuf, recvCheckSum = 0; i < recvcount; i++, p++)\n\t    recvCheckSum += *p;\n\n\t  err_flag = err_flag_imported = 0;\n\n\t  if(recvCheckSum != importedCheckSum)\n\t    {\n\t      printf\n\t\t(\"MPI-ERROR: Again (iter=%d) a receive error on task=%d/%s from task=%d, message size=%d, checksums= %d %d  %d %d. Try to fix it...\\n\",\n\t\t iter, ThisTask, getenv(\"HOST\"), source, recvcount, (int) (recvCheckSum >> 32),\n\t\t (int) recvCheckSum, (int) (importedCheckSum >> 32), (int) importedCheckSum);\n\t      fflush(stdout);\n\t      err_flag = 1;\n\t    }\n\n\t  if(dest > ThisTask)\n\t    {\n\t      MPI_Ssend(&err_flag, 1, MPI_INT, dest, errtag, MPI_COMM_WORLD);\n\t      MPI_Recv(&err_flag_imported, 1, MPI_INT, dest, errtag, MPI_COMM_WORLD, status);\n\t    }\n\t  else\n\t    {\n\t      MPI_Recv(&err_flag_imported, 1, MPI_INT, dest, errtag, MPI_COMM_WORLD, status);\n\t      MPI_Ssend(&err_flag, 1, MPI_INT, dest, errtag, MPI_COMM_WORLD);\n\t    }\n\n\t  if(err_flag == 0 && err_flag_imported == 0)\n\t    break;\n\n\t  errtag++;\n\t  checksumtag++;\n\t  iter++;\n\t}\n      while(iter < 10);\n\n      if(iter >= 10)\n\t{\n\t  char buf[1000];\n\t  int length;\n\t  FILE *fd;\n\n\t  sprintf(buf, \"send_data_%d.dat\", ThisTask);\n\t  fd = fopen(buf, \"w\");\n\t  length = sendcount * size_sendtype;\n\t  fwrite(&length, 1, sizeof(int), fd);\n\t  fwrite(sendbuf, sendcount, size_sendtype, fd);\n\t  fclose(fd);\n\n\t  sprintf(buf, \"recv_data_%d.dat\", ThisTask);\n\t  fd = fopen(buf, \"w\");\n\t  length = recvcount * size_recvtype;\n\t  fwrite(&length, 1, sizeof(int), fd);\n\t  fwrite(recvbuf, recvcount, size_recvtype, fd);\n\t  fclose(fd);\n\n\t  printf(\"MPI-ERROR: Even 10 trials proved to be insufficient on task=%d/%s. Stopping\\n\", ThisTask,\n\t\t getenv(\"HOST\"));\n\t  fflush(stdout);\n\t  endrun(10);\n\t}\n    }\n\n  memcpy(recvbufreal, recvbuf, recvcount * size_recvtype);\n\n  myfree(buf);\n\n  return 0;\n}\n\n#endif\n", "meta": {"hexsha": "312b98c4172212e65f61967f7aec3b1a1beed0f8", "size": 7912, "ext": "c", "lang": "C", "max_stars_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/checksummed_sendrecv.c", "max_stars_repo_name": "egpbos/egp", "max_stars_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/checksummed_sendrecv.c", "max_issues_repo_name": "egpbos/egp", "max_issues_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/checksummed_sendrecv.c", "max_forks_repo_name": "egpbos/egp", "max_forks_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0567375887, "max_line_length": 137, "alphanum_fraction": 0.6243680485, "num_tokens": 2495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2538610069692489, "lm_q2_score": 0.027585285124714688, "lm_q1q2_score": 0.007002828259293914}}
{"text": "\n#include \"quac_p.h\"\n#include \"quac.h\"\n#include \"operators_p.h\"\n#include \"operators.h\"\n#include <petsc.h>\n\nint petsc_initialized = 0;\nint nid;\nint np;\n\n/*\n * QuaC_initialize initializes petsc, gets each core's nid, and lets the\n * rest of the program know that it has been initialized.\n * Inputs:\n *       int argc, char **args - command line input, for PETSc\n */\nvoid QuaC_initialize(int argc,char **args){\n\n  /* Initialize Petsc */\n  PetscInitialize(&argc,&args,(char*)0,NULL);\n#if !defined(PETSC_USE_COMPLEX)\n  SETERRQ(PETSC_COMM_WORLD,1,\"This example requires complex numbers\");\n#endif\n  /* Get core's id */\n  MPI_Comm_rank(PETSC_COMM_WORLD,&nid);\n  /* Get number of processors */\n  MPI_Comm_size(PETSC_COMM_WORLD,&np);\n\n  petsc_initialized = 1;\n  PetscLogStageRegister(\"Pre-solve\",&pre_solve_stage);\n  PetscLogStageRegister(\"Solve\",&solve_stage);\n  PetscLogStageRegister(\"Post-solve\",&post_solve_stage);\n  /* Register events */\n  PetscClassIdRegister(\"QuaC Class\",&quac_class_id);\n  PetscLogEventRegister(\"add_lin\",quac_class_id,&add_lin_event);\n  PetscLogEventRegister(\"add_to_ham\",quac_class_id,&add_to_ham_event);\n  PetscLogEventRegister(\"add_lin_recovery\",quac_class_id,&add_lin_recovery_event);\n  PetscLogEventRegister(\"_qc_event\",quac_class_id,&_qc_event_function_event);\n  PetscLogEventRegister(\"_qc_postevent\",quac_class_id,&_qc_postevent_function_event);\n  PetscLogEventRegister(\"_apply_gate\",quac_class_id,&_apply_gate_event);\n\n  PetscLogStagePush(pre_solve_stage);\n\n}\n\n/*\n * QuaC_clear clears the internal state of many of QuaC's\n * variables so that multiple systems can be run in one file.\n */\n\nvoid QuaC_clear(){\n  int i;\n  /* Destroy Matrix */\n  MatDestroy(&full_A);\n  MatDestroy(&ham_A);\n  MatDestroy(&full_stiff_A);\n  MatDestroy(&ham_stiff_A);\n\n  for (i=0;i<_num_time_dep;i++){\n    MatDestroy(&_time_dep_list[i].mat);\n  }\n  //stab_added       = 0;\n  _print_dense_ham = 0;\n  _num_time_dep = 0;\n  op_initialized = 0;\n}\n\n\n/*\n * QuaC_finalize finalizes petsc and destroys full_A.\n * The user is responsible for freeing all of the objects\n * using destroy_*\n */\n\nvoid QuaC_finalize(){\n  int i;\n  /* Destroy Matrix */\n  MatDestroy(&full_A);\n  MatDestroy(&ham_A);\n  MatDestroy(&full_stiff_A);\n  MatDestroy(&ham_stiff_A);\n\n  for (i=0;i<_num_time_dep;i++){\n    MatDestroy(&_time_dep_list[i].mat);\n  }\n  /* Finalize Petsc */\n  PetscLogStagePop();\n  PetscFinalize();\n  return;\n}\n\n/*\n * destroy_op frees the memory from op.\n * Inputs:\n *       operator *op - pointer to operator to be freed\n */\n\nvoid destroy_op(operator *op){\n\n  free((*op)->dag);\n  free((*op)->n);\n  free(*op);\n}\n\n/*\n * destroy_vec frees the memory from a vec.\n * Inputs:\n *       vec_op *op - pointer to vec_op to be freed\n */\n\nvoid destroy_vec(vec_op *op){\n  int num_levels,i;\n  num_levels = (*op)[0]->my_levels;\n\n  /* Free each up in the array */\n  for (i=0;i<num_levels;i++){\n    free((*op)[i]);\n  }\n  free(*op);\n}\n", "meta": {"hexsha": "517c66e775aaf7c3780dc9d57ba31c92f3b58f8c", "size": 2897, "ext": "c", "lang": "C", "max_stars_repo_path": "src/quac.c", "max_stars_repo_name": "sgulania/QuaC", "max_stars_repo_head_hexsha": "2b47b378c6b5b823a094e9af79f7cb8eb39dd337", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2017-06-18T02:11:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-28T10:27:57.000Z", "max_issues_repo_path": "src/quac.c", "max_issues_repo_name": "sgulania/QuaC", "max_issues_repo_head_hexsha": "2b47b378c6b5b823a094e9af79f7cb8eb39dd337", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-07-17T15:16:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-03T14:21:56.000Z", "max_forks_repo_path": "src/quac.c", "max_forks_repo_name": "sgulania/QuaC", "max_forks_repo_head_hexsha": "2b47b378c6b5b823a094e9af79f7cb8eb39dd337", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2017-03-13T15:03:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T20:07:22.000Z", "avg_line_length": 23.7459016393, "max_line_length": 85, "alphanum_fraction": 0.7059026579, "num_tokens": 806, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2538609956791997, "lm_q2_score": 0.027585282326718422, "lm_q1q2_score": 0.007002827237552568}}
{"text": "/*\n * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The OpenAirInterface Software Alliance licenses this file to You under\n * the OAI Public License, Version 1.0  (the \"License\"); you may not use this file\n * except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.openairinterface.org/?page_id=698\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *-------------------------------------------------------------------------------\n * For more information about the OpenAirInterface (OAI) Software Alliance:\n *      contact@openairinterface.org\n */\n\n/*! \\file oaisim.c\n * \\brief oaisim top level\n * \\author Navid Nikaein \n * \\date 2013-2015\n * \\version 1.0\n * \\company Eurecom\n * \\email: openair_tech@eurecom.fr\n * \\note\n * \\warning\n */\n\n#include <string.h>\n#include <math.h>\n#include <unistd.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include <cblas.h>\n#include <execinfo.h>\n\n#include \"event_handler.h\"\n#include \"SIMULATION/RF/defs.h\"\n#include \"PHY/types.h\"\n#include \"PHY/defs.h\"\n#include \"PHY/LTE_TRANSPORT/proto.h\"\n#include \"PHY/vars.h\"\n\n#include \"SIMULATION/ETH_TRANSPORT/proto.h\"\n\n//#ifdef OPENAIR2\n#include \"LAYER2/MAC/defs.h\"\n#include \"LAYER2/MAC/proto.h\"\n#include \"LAYER2/MAC/vars.h\"\n#include \"pdcp.h\"\n#include \"RRC/LITE/vars.h\"\n#include \"RRC/NAS/nas_config.h\"\n\n#include \"SCHED/defs.h\"\n#include \"SCHED/vars.h\"\n#include \"system.h\"\n\n\n#include \"PHY/TOOLS/lte_phy_scope.h\"\n\n\n#ifdef SMBV\n// Rohde&Schwarz SMBV100A vector signal generator\n#include \"PHY/TOOLS/smbv.h\"\nchar smbv_fname[] = \"smbv_config_file.smbv\";\nunsigned short smbv_nframes = 4; // how many frames to configure 1,..,4\nunsigned short config_frames[4] = {2,9,11,13};\nunsigned char smbv_frame_cnt = 0;\nuint8_t config_smbv = 0;\nchar smbv_ip[16];\n#endif\n\n#if defined(FLEXRAN_AGENT_SB_IF)\n#   include \"flexran_agent.h\"\n#endif\n\n\n#include \"oaisim_functions.h\"\n\n#include \"oaisim.h\"\n#include \"oaisim_config.h\"\n#include \"UTIL/OCG/OCG_extern.h\"\n#include \"cor_SF_sim.h\"\n#include \"UTIL/OMG/omg_constants.h\"\n#include \"UTIL/FIFO/pad_list.h\"\n#include \"enb_app.h\"\n\n#include \"../PROC/interface.h\"\n#include \"../PROC/channel_sim_proc.h\"\n#include \"../PROC/Tsync.h\"\n#include \"../PROC/Process.h\"\n\n#include \"UTIL/LOG/vcd_signal_dumper.h\"\n#include \"UTIL/OTG/otg_kpi.h\"\n#include \"assertions.h\"\n\n#if defined(ENABLE_ITTI)\n# include \"intertask_interface.h\"\n# include \"create_tasks.h\"\n#endif\n\n#include \"T.h\"\n\n/*\n  DCI0_5MHz_TDD0_t          UL_alloc_pdu;\n  DCI1A_5MHz_TDD_1_6_t      CCCH_alloc_pdu;\n  DCI2_5MHz_2A_L10PRB_TDD_t DLSCH_alloc_pdu1;\n  DCI2_5MHz_2A_M10PRB_TDD_t DLSCH_alloc_pdu2;\n*/\n\n#define UL_RB_ALLOC            computeRIV(lte_frame_parms->N_RB_UL,0,24)\n#define CCCH_RB_ALLOC          computeRIV(lte_frame_parms->N_RB_UL,0,3)\n#define RA_RB_ALLOC            computeRIV(lte_frame_parms->N_RB_UL,0,3)\n#define DLSCH_RB_ALLOC         0x1fff\n\n#define DECOR_DIST             100\n#define SF_VAR                 10\n\n//constant for OAISIM soft realtime calibration\n//#define SF_DEVIATION_OFFSET_NS 100000        /*= 0.1ms : should be as a number of UE */\n//#define SLEEP_STEP_US          100           /*  = 0.01ms could be adaptive, should be as a number of UE */\n//#define K                      2             /* averaging coefficient */\n//#define TARGET_SF_TIME_NS      1000000       /* 1ms = 1000000 ns */\n\nuint8_t usim_test = 0;\n\nframe_t frame = 0;\nchar stats_buffer[16384];\nchannel_desc_t *eNB2UE[NUMBER_OF_eNB_MAX][NUMBER_OF_UE_MAX][MAX_NUM_CCs];\nchannel_desc_t *UE2eNB[NUMBER_OF_UE_MAX][NUMBER_OF_eNB_MAX][MAX_NUM_CCs];\n//Added for PHY abstraction\nnode_desc_t *enb_data[NUMBER_OF_eNB_MAX];\nnode_desc_t *ue_data[NUMBER_OF_UE_MAX];\n\npthread_cond_t sync_cond;\npthread_mutex_t sync_mutex;\nint sync_var=-1;\n\npthread_mutex_t subframe_mutex;\nint subframe_eNB_mask=0,subframe_UE_mask=0;\n\nopenair0_config_t openair0_cfg[MAX_CARDS];\nuint32_t          downlink_frequency[MAX_NUM_CCs][4];\nint32_t           uplink_frequency_offset[MAX_NUM_CCs][4];\nopenair0_rf_map rf_map[MAX_NUM_CCs];\n\n#if defined(ENABLE_ITTI)\nvolatile int             start_eNB = 0;\nvolatile int             start_UE = 0;\n#endif\nvolatile int                    oai_exit = 0;\n\n\n//int32_t **rxdata;\n//int32_t **txdata;\n\n\n// Added for PHY abstraction\nextern node_list* ue_node_list;\nextern node_list* enb_node_list;\nextern int pdcp_period, omg_period;\n\nextern double **s_re, **s_im, **r_re, **r_im, **r_re0, **r_im0;\nint map1, map2;\nextern double **ShaF;\ndouble snr_dB, sinr_dB, snr_direction; //,sinr_direction;\nextern double snr_step;\nextern uint8_t set_sinr;\nextern uint8_t ue_connection_test;\nextern uint8_t set_seed;\nextern uint8_t target_dl_mcs;\nextern uint8_t target_ul_mcs;\nextern uint8_t abstraction_flag;\nextern uint8_t ethernet_flag;\nextern uint16_t Nid_cell;\n\nextern LTE_DL_FRAME_PARMS *frame_parms[MAX_NUM_CCs];\n\ndouble cpuf;\n#include \"threads_t.h\"\nthreads_t threads= {-1,-1,-1,-1,-1,-1,-1};\n\n//#ifdef XFORMS\nint otg_enabled;\nint xforms=0;\n//#endif\n\ntime_stats_t oaisim_stats;\ntime_stats_t oaisim_stats_f;\ntime_stats_t dl_chan_stats;\ntime_stats_t ul_chan_stats;\n\n// this should reflect the channel models in openair1/SIMULATION/TOOLS/defs.h\nmapping small_scale_names[] = { \n  { \"custom\", custom }, { \"SCM_A\", SCM_A },\n  { \"SCM_B\", SCM_B   }, { \"SCM_C\", SCM_C },\n  { \"SCM_D\", SCM_D   }, { \"EPA\",   EPA   },\n  { \"EVA\",   EVA     }, { \"ETU\",   ETU   },\n  { \"MBSFN\", MBSFN },   { \"Rayleigh8\", Rayleigh8 },\n  { \"Rayleigh1\", Rayleigh1 }, { \"Rayleigh1_800\", Rayleigh1_800 },\n  { \"Rayleigh1_corr\", Rayleigh1_corr }, { \"Rayleigh1_anticorr\", Rayleigh1_anticorr },\n  { \"Rice8\", Rice8 }, { \"Rice1\", Rice1 }, { \"Rice1_corr\", Rice1_corr },\n  { \"Rice1_anticorr\", Rice1_anticorr }, { \"AWGN\", AWGN }, { NULL,-1 }\n};\n#if !defined(ENABLE_ITTI)\nstatic void *\nsigh (void *arg);\n#endif\nvoid\noai_shutdown (void);\n\nvoid reset_opp_meas_oaisim (void);\n\nvoid\nhelp (void)\n{\n  printf (\"Usage: oaisim -h -a -F -C tdd_config -K [log_file] -V [vcd_file] -R N_RB_DL -e -x transmission_mode -m target_dl_mcs -r(ate_adaptation) -n n_frames -s snr_dB -k ricean_factor -t max_delay -f forgetting factor -A channel_model -z cooperation_flag -u nb_local_ue -U UE mobility -b nb_local_enb -B eNB_mobility -M ethernet_flag -p nb_master -g multicast_group -l log_level -c ocg_enable -T traffic model -D multicast network device\\n\");\n\n  printf (\"-h provides this help message!\\n\");\n  printf (\"-a Activates PHY abstraction mode\\n\");\n  printf (\"-A set the multipath channel simulation,  options are: SCM_A, SCM_B, SCM_C, SCM_D, EPA, EVA, ETU, Rayleigh8, Rayleigh1, Rayleigh1_corr,Rayleigh1_anticorr, Rice8,, Rice1, AWGN \\n\");\n  printf (\"-b Set the number of local eNB\\n\");\n  printf (\"-B Set the mobility model for eNB, options are: STATIC, RWP, RWALK, \\n\");\n  printf (\"-c [1,2,3,4] Activate the config generator (OCG) to process the scenario descriptor, or give the scenario manually: -c template_1.xml \\n\");\n  printf (\"-C [0-6] Sets TDD configuration\\n\");\n  printf (\"-e Activates extended prefix mode\\n\");\n  printf (\"-E Random number generator seed\\n\");\n  printf (\"-f Set the forgetting factor for time-variation\\n\");\n  printf (\"-F Activates FDD transmission (TDD is default)\\n\");\n  printf (\"-g Set multicast group ID (0,1,2,3) - valid if M is set\\n\");\n  printf (\"-G Enable background traffic \\n\");\n  printf (\"-H Enable handover operation (default disabled) \\n\");\n  printf (\"-I Enable CLI interface (to connect use telnet localhost 1352)\\n\");\n  printf (\"-k Set the Ricean factor (linear)\\n\");\n  printf (\"-K [log_file] Enable ITTI logging into log_file\\n\");\n  printf (\"-l Set the global log level (8:trace, 7:debug, 6:info, 4:warn, 3:error) \\n\");\n  printf (\"-L [0-1] 0 to disable new link adaptation, 1 to enable new link adapatation\\n\");\n  printf (\"-m Gives a fixed DL mcs for eNB scheduler\\n\");\n  printf (\"-M Set the machine ID for Ethernet-based emulation\\n\");\n  printf (\"-n Set the number of frames for the simulation. 0 for no limit\\n\");\n  printf (\"-O [enb_conf_file] eNB configuration file name\\n\");\n  printf (\"-p Set the total number of machine in emulation - valid if M is set\\n\");\n  printf (\"-P [trace type] Enable protocol analyzer. Possible values for OPT:\\n\");\n  printf (\"    - wireshark: Enable tracing of layers above PHY using an UDP socket\\n\");\n  printf (\"    - pcap:      Enable tracing of layers above PHY to a pcap file\\n\");\n  printf (\"    - tshark:    Not implemented yet\\n\");\n  printf (\"-q Enable Openair performance profiler \\n\");\n  printf (\"-Q Activate and set the MBMS service: 0 : not used (default eMBMS disabled), 1: eMBMS and RRC Connection enabled, 2: eMBMS relaying and RRC Connection enabled, 3: eMBMS enabled, RRC Connection disabled, 4: eMBMS relaying enabled, RRC Connection disabled\\n\");\n  printf (\"-R [6,15,25,50,75,100] Sets N_RB_DL\\n\");\n  printf (\"-r Activates rate adaptation (DL for now)\\n\");\n  printf (\"-s snr_dB set a fixed (average) SNR, this deactivates the openair channel model generator (OCM)\\n\");\n  printf (\"-S snir_dB set a fixed (average) SNIR, this deactivates the openair channel model generator (OCM)\\n\");\n  printf (\"-t Gives a fixed UL mcs for eNB scheduler\\n\");\n  printf (\"-T activate the traffic generator. Valide options are m2m,scbr,mcbr,bcbr,auto_pilot,bicycle_race,open_arena,team_fortress,m2m_traffic,auto_pilot_l,auto_pilot_m,auto_pilot_h,auto_pilot_e,virtual_game_l,virtual_game_m,virtual_game_h,virtual_game_f,alarm_humidity,alarm_smoke,alarm_temperature,openarena_dl,openarena_ul,voip_g711,voip_g729,video_vbr_10mbps,video_vbr_4mbps,video_vbr_2mbp,video_vbr_768kbps,video_vbr_384kbps,video_vbr_192kpbs,background_users\\n\");\n  printf (\"-u Set the number of local UE\\n\");\n  printf (\"-U Set the mobility model for UE, options are: STATIC, RWP, RWALK\\n\");\n  printf (\"-V [vcd_file] Enable VCD dump into vcd_file\\n\");\n  printf (\"-w number of CBA groups, if not specified or zero, CBA is inactive\\n\");\n#ifdef SMBV\n  printf (\"-W IP address to connect to Rohde&Schwarz SMBV100A and configure SMBV from config file. -W0 uses default IP 192.168.12.201\\n\");\n#else\n  printf (\"-W [Rohde&Schwarz SMBV100A functions disabled. Recompile with SMBV=1]\\n\");\n#endif\n  printf (\"-x deprecated. Set the transmission mode in config file!\\n\");\n  printf (\"-y Set the number of receive antennas at the UE (1 or 2)\\n\");\n  printf (\"-Y Set the global log verbosity (none, low, medium, high, full) \\n\");\n  printf (\"-z Set the cooperation flag (0 for no cooperation, 1 for delay diversity and 2 for distributed alamouti\\n\");\n  printf (\"-Z Reserved\\n\");\n  printf (\"--xforms Activate the grapical scope\\n\");\n\n#if T_TRACER\n  printf (\"--T_port [port]    use given port\\n\");\n  printf (\"--T_nowait         don't wait for tracer, start immediately\\n\");\n  printf (\"--T_dont_fork      to ease debugging with gdb\\n\");\n#endif\n}\n\npthread_t log_thread;\n\nvoid\nlog_thread_init (void)\n{\n  //create log_list\n  //log_list_init(&log_list);\n#ifndef LOG_NO_THREAD\n\n  log_shutdown = 0;\n\n  if ((pthread_mutex_init (&log_lock, NULL) != 0)\n      || (pthread_cond_init (&log_notify, NULL) != 0)) {\n    return;\n  }\n\n  if (pthread_create (&log_thread, NULL, log_thread_function, (void*) NULL)\n      != 0) {\n    log_thread_finalize ();\n    return;\n  }\n\n#endif\n\n}\n\n//Call it after the last LOG call\nint\nlog_thread_finalize (void)\n{\n  int err = 0;\n\n#ifndef LOG_NO_THREAD\n\n  if (pthread_mutex_lock (&log_lock) != 0) {\n    return -1;\n  }\n\n  log_shutdown = 1;\n\n  /* Wake up LOG thread */\n  if ((pthread_cond_broadcast (&log_notify) != 0)\n      || (pthread_mutex_unlock (&log_lock) != 0)) {\n    err = -1;\n  }\n\n  if (pthread_join (log_thread, NULL) != 0) {\n    err = -1;\n  }\n\n  if (pthread_mutex_unlock (&log_lock) != 0) {\n    err = -1;\n  }\n\n  if (!err) {\n    //log_list_free(&log_list);\n    pthread_mutex_lock (&log_lock);\n    pthread_mutex_destroy (&log_lock);\n    pthread_cond_destroy (&log_notify);\n  }\n\n#endif\n\n  return err;\n}\n\n#if defined(ENABLE_ITTI)\nstatic void set_cli_start(module_id_t module_idP, uint8_t start)\n{\n  if (module_idP < NB_eNB_INST) {\n    oai_emulation.info.cli_start_enb[module_idP] = start;\n  } else {\n    oai_emulation.info.cli_start_ue[module_idP - NB_eNB_INST] = start;\n  }\n}\n#endif\n\n#ifdef OPENAIR2\nint omv_write(int pfd, node_list* enb_node_list, node_list* ue_node_list, Data_Flow_Unit omv_data)\n{\n  module_id_t i, j;\n  omv_data.end = 0;\n\n  //omv_data.total_num_nodes = NB_UE_INST + NB_eNB_INST;\n  for (i = 0; i < NB_eNB_INST; i++) {\n    if (enb_node_list != NULL) {\n      omv_data.geo[i].x = (enb_node_list->node->x_pos < 0.0) ? 0.0 : enb_node_list->node->x_pos;\n      omv_data.geo[i].y = (enb_node_list->node->y_pos < 0.0) ? 0.0 : enb_node_list->node->y_pos;\n      omv_data.geo[i].z = 1.0;\n      omv_data.geo[i].mobility_type = oai_emulation.info.omg_model_enb;\n      omv_data.geo[i].node_type = 0; //eNB\n      enb_node_list = enb_node_list->next;\n      omv_data.geo[i].Neighbors = 0;\n\n      for (j = NB_eNB_INST; j < NB_UE_INST + NB_eNB_INST; j++) {\n        if (is_UE_active (i, j - NB_eNB_INST) == 1) {\n          omv_data.geo[i].Neighbor[omv_data.geo[i].Neighbors] = j;\n          omv_data.geo[i].Neighbors++;\n          LOG_D(\n\t\tOMG,\n\t\t\"[eNB %d][UE %d] is_UE_active(i,j) %d geo (x%d, y%d) num neighbors %d\\n\", i, j-NB_eNB_INST, is_UE_active(i,j-NB_eNB_INST), omv_data.geo[i].x, omv_data.geo[i].y, omv_data.geo[i].Neighbors);\n        }\n      }\n    }\n  }\n\n  for (i = NB_eNB_INST; i < NB_UE_INST + NB_eNB_INST; i++) {\n    if (ue_node_list != NULL) {\n      omv_data.geo[i].x = (ue_node_list->node->x_pos < 0.0) ? 0.0 : ue_node_list->node->x_pos;\n      omv_data.geo[i].y = (ue_node_list->node->y_pos < 0.0) ? 0.0 : ue_node_list->node->y_pos;\n      omv_data.geo[i].z = 1.0;\n      omv_data.geo[i].mobility_type = oai_emulation.info.omg_model_ue;\n      omv_data.geo[i].node_type = 1; //UE\n      //trial\n      omv_data.geo[i].state = 1;\n      omv_data.geo[i].rnti = 88;\n      omv_data.geo[i].connected_eNB = 0;\n      omv_data.geo[i].RSRP = 66;\n      omv_data.geo[i].RSRQ = 55;\n      omv_data.geo[i].Pathloss = 44;\n      omv_data.geo[i].RSSI[0] = 33;\n      omv_data.geo[i].RSSI[1] = 22;\n\n      if ((sizeof(omv_data.geo[0].RSSI) / sizeof(omv_data.geo[0].RSSI[0])) > 2) {\n        omv_data.geo[i].RSSI[2] = 11;\n      }\n\n      ue_node_list = ue_node_list->next;\n      omv_data.geo[i].Neighbors = 0;\n\n      for (j = 0; j < NB_eNB_INST; j++) {\n        if (is_UE_active (j, i - NB_eNB_INST) == 1) {\n          omv_data.geo[i].Neighbor[omv_data.geo[i].Neighbors] = j;\n          omv_data.geo[i].Neighbors++;\n          LOG_D(\n\t\tOMG,\n\t\t\"[UE %d][eNB %d] is_UE_active  %d geo (x%d, y%d) num neighbors %d\\n\", i-NB_eNB_INST, j, is_UE_active(j,i-NB_eNB_INST), omv_data.geo[i].x, omv_data.geo[i].y, omv_data.geo[i].Neighbors);\n        }\n      }\n    }\n  }\n\n  LOG_E(OMG, \"pfd %d \\n\", pfd);\n\n  if (write (pfd, &omv_data, sizeof(struct Data_Flow_Unit)) == -1)\n    perror (\"write omv failed\");\n\n  return 1;\n}\n\nvoid omv_end(int pfd, Data_Flow_Unit omv_data)\n{\n  omv_data.end = 1;\n\n  if (write (pfd, &omv_data, sizeof(struct Data_Flow_Unit)) == -1)\n    perror (\"write omv failed\");\n}\n#endif\n\n#ifdef OPENAIR2\nint pfd[2]; // fd for omv : fixme: this could be a local var\n#endif\n\n#ifdef OPENAIR2\nstatic Data_Flow_Unit omv_data;\n#endif //ALU\nstatic module_id_t UE_inst = 0;\nstatic module_id_t eNB_inst = 0;\n\nPacket_OTG_List_t *otg_pdcp_buffer;\n\ntypedef enum l2l1_task_state_e {\n  L2L1_WAITTING, L2L1_RUNNING, L2L1_TERMINATED,\n} l2l1_task_state_t;\n\nl2l1_task_state_t l2l1_state = L2L1_WAITTING;\n\nextern openair0_timestamp current_eNB_rx_timestamp[NUMBER_OF_eNB_MAX][MAX_NUM_CCs];\nextern openair0_timestamp current_UE_rx_timestamp[NUMBER_OF_UE_MAX][MAX_NUM_CCs];\nextern openair0_timestamp last_eNB_rx_timestamp[NUMBER_OF_eNB_MAX][MAX_NUM_CCs];\nextern openair0_timestamp last_UE_rx_timestamp[NUMBER_OF_UE_MAX][MAX_NUM_CCs];\n\n/*------------------------------------------------------------------------------*/\nvoid *\nl2l1_task (void *args_p)\n{\n\n  int CC_id;\n\n  // Framing variables\n  int32_t sf;\n\n  //char fname[64], vname[64];\n\n  //#ifdef XFORMS\n  // current status is that every UE has a DL scope for a SINGLE eNB (eNB_id=0)\n  // at eNB 0, an UL scope for every UE\n  FD_lte_phy_scope_ue *form_ue[MAX_NUM_CCs][NUMBER_OF_UE_MAX];\n  FD_lte_phy_scope_enb *form_enb[NUMBER_OF_UE_MAX];\n  char title[255];\n  char xname[32] = \"oaisim\";\n  int xargc = 1;\n  char *xargv[1];\n  //#endif\n\n#undef PRINT_STATS /* this undef is to avoid gcc warnings */\n#define PRINT_STATS\n#ifdef PRINT_STATS\n  int len;\n  FILE *UE_stats[NUMBER_OF_UE_MAX];\n  FILE *UE_stats_th[NUMBER_OF_UE_MAX];\n  FILE *eNB_stats[NUMBER_OF_eNB_MAX];\n  FILE *eNB_avg_thr;\n  FILE *eNB_l2_stats;\n  char UE_stats_filename[255];\n  char eNB_stats_filename[255];\n  char UE_stats_th_filename[255];\n  char eNB_stats_th_filename[255];\n#endif\n\n\n  if (xforms==1) {\n    xargv[0] = xname;\n    fl_initialize (&xargc, xargv, NULL, 0, 0);\n    eNB_inst = 0;\n    for (UE_inst = 0; UE_inst < NB_UE_INST; UE_inst++) {\n      for (CC_id=0;CC_id<MAX_NUM_CCs;CC_id++) {\n\t// DL scope at UEs\n\tform_ue[CC_id][UE_inst] = create_lte_phy_scope_ue();\n\tsprintf (title, \"LTE DL SCOPE eNB %d to UE %d CC_id %d\", eNB_inst, UE_inst, CC_id);\n\tfl_show_form (form_ue[CC_id][UE_inst]->lte_phy_scope_ue, FL_PLACE_HOTSPOT, FL_FULLBORDER, title);\n\n\tif (PHY_vars_UE_g[UE_inst][CC_id]->use_ia_receiver == 1) {\n\t  fl_set_button(form_ue[CC_id][UE_inst]->button_0,1);\n\t  fl_set_object_label(form_ue[CC_id][UE_inst]->button_0, \"IA Receiver ON\");\n\t  fl_set_object_color(form_ue[CC_id][UE_inst]->button_0, FL_GREEN, FL_GREEN);\n\t}\n\t\n      }\n      // UL scope at eNB 0\n      form_enb[UE_inst] = create_lte_phy_scope_enb();\n      sprintf (title, \"LTE UL SCOPE UE %d to eNB %d\", UE_inst, eNB_inst);\n      fl_show_form (form_enb[UE_inst]->lte_phy_scope_enb, FL_PLACE_HOTSPOT, FL_FULLBORDER, title);\n      \n    }\n  }\n\n\n#ifdef PRINT_STATS\n\n  for (UE_inst=0; UE_inst<NB_UE_INST; UE_inst++) {\n    sprintf(UE_stats_filename,\"UE_stats%d.txt\",UE_inst);\n    UE_stats[UE_inst] = fopen (UE_stats_filename, \"w\");\n  }\n\n  for (eNB_inst=0; eNB_inst<NB_eNB_INST; eNB_inst++) {\n    sprintf(eNB_stats_filename,\"eNB_stats%d.txt\",eNB_inst);\n    eNB_stats[eNB_inst] = fopen (eNB_stats_filename, \"w\");\n  }\n\n  if(abstraction_flag==0) {\n    for (UE_inst=0; UE_inst<NB_UE_INST; UE_inst++) {\n      /* TODO: transmission_mode is defined per CC, we set 0 for now */\n      sprintf(UE_stats_th_filename,\"UE_stats_th%d_tx%d.txt\",UE_inst,oai_emulation.info.transmission_mode[0]);\n      UE_stats_th[UE_inst] = fopen (UE_stats_th_filename, \"w\");\n    }\n\n    /* TODO: transmission_mode is defined per CC, we set 0 for now */\n    sprintf(eNB_stats_th_filename,\"eNB_stats_th_tx%d.txt\",oai_emulation.info.transmission_mode[0]);\n    eNB_avg_thr = fopen (eNB_stats_th_filename, \"w\");\n  } else {\n    for (UE_inst=0; UE_inst<NB_UE_INST; UE_inst++) {\n      /* TODO: transmission_mode is defined per CC, we set 0 for now */\n      sprintf(UE_stats_th_filename,\"UE_stats_abs_th%d_tx%d.txt\",UE_inst,oai_emulation.info.transmission_mode[0]);\n      UE_stats_th[UE_inst] = fopen (UE_stats_th_filename, \"w\");\n    }\n\n    /* TODO: transmission_mode is defined per CC, we set 0 for now */\n    sprintf(eNB_stats_th_filename,\"eNB_stats_abs_th_tx%d.txt\",oai_emulation.info.transmission_mode[0]);\n    eNB_avg_thr = fopen (eNB_stats_th_filename, \"w\");\n  }\n\n#ifdef OPENAIR2\n  eNB_l2_stats = fopen (\"eNB_l2_stats.txt\", \"w\");\n  LOG_I(EMU,\"eNB_l2_stats=%p\\n\", eNB_l2_stats);\n#endif\n\n#endif\n\n#if defined(ENABLE_ITTI)\n  MessageDef *message_p = NULL;\n  const char *msg_name = NULL;\n  int result;\n\n  itti_mark_task_ready (TASK_L2L1);\n  LOG_I(EMU, \"TASK_L2L1 is READY\\n\");\n\n  if ((oai_emulation.info.nb_enb_local > 0) && \n      (oai_emulation.info.node_function[0] < NGFI_RAU_IF4p5)) {\n    /* Wait for the initialize message */\n    do {\n      if (message_p != NULL) {\n        result = itti_free (ITTI_MSG_ORIGIN_ID(message_p), message_p);\n        AssertFatal (result == EXIT_SUCCESS, \"Failed to free memory (%d)!\\n\", result);\n      }\n\n      itti_receive_msg (TASK_L2L1, &message_p);\n      msg_name = ITTI_MSG_NAME (message_p);\n      LOG_I(EMU, \"TASK_L2L1 received %s in state L2L1_WAITTING\\n\", msg_name);\n\n      switch (ITTI_MSG_ID(message_p)) {\n      case INITIALIZE_MESSAGE:\n        l2l1_state = L2L1_RUNNING;\n        start_eNB = 1;\n        break;\n\n      case ACTIVATE_MESSAGE:\n        set_cli_start(ITTI_MSG_INSTANCE (message_p), 1);\n        break;\n\n      case DEACTIVATE_MESSAGE:\n        set_cli_start(ITTI_MSG_INSTANCE (message_p), 0);\n        break;\n\n      case TERMINATE_MESSAGE:\n        l2l1_state = L2L1_TERMINATED;\n        break;\n\n      default:\n        LOG_E(EMU, \"Received unexpected message %s\\n\", ITTI_MSG_NAME(message_p));\n        break;\n      }\n    } while (l2l1_state == L2L1_WAITTING);\n\n    result = itti_free (ITTI_MSG_ORIGIN_ID(message_p), message_p);\n    AssertFatal (result == EXIT_SUCCESS, \"Failed to free memory (%d)!\\n\", result);\n  }\n\n#endif\n  module_id_t enb_id;\n  module_id_t UE_id;\n  for (enb_id = 0; enb_id < NB_eNB_INST; enb_id++)\n    mac_xface->mrbch_phy_sync_failure (enb_id, 0, enb_id);\n  \n  if (abstraction_flag == 1) {\n    for (UE_id = 0; UE_id < NB_UE_INST; UE_id++)\n      mac_xface->dl_phy_sync_success (UE_id, 0, 0,1);   //UE_id%NB_eNB_INST);\n  }\n  \n  start_meas (&oaisim_stats);\n\n  for (frame = 0;\n       (l2l1_state != L2L1_TERMINATED) && \n\t ((oai_emulation.info.n_frames_flag == 0) ||\n\t  (frame < oai_emulation.info.n_frames));\n       frame++) {\n\n#if defined(ENABLE_ITTI)\n\n    do {\n      // Checks if a message has been sent to L2L1 task\n      itti_poll_msg (TASK_L2L1, &message_p);\n\n      if (message_p != NULL) {\n        msg_name = ITTI_MSG_NAME (message_p);\n        LOG_I(EMU, \"TASK_L2L1 received %s\\n\", msg_name);\n\n        switch (ITTI_MSG_ID(message_p)) {\n        case ACTIVATE_MESSAGE:\n          set_cli_start(ITTI_MSG_INSTANCE (message_p), 1);\n          break;\n\n        case DEACTIVATE_MESSAGE:\n          set_cli_start(ITTI_MSG_INSTANCE (message_p), 0);\n          break;\n\n        case TERMINATE_MESSAGE:\n          l2l1_state = L2L1_TERMINATED;\n          break;\n\n        case MESSAGE_TEST:\n          break;\n\n        default:\n          LOG_E(EMU, \"Received unexpected message %s\\n\", ITTI_MSG_NAME(message_p));\n          break;\n        }\n\n        result = itti_free (ITTI_MSG_ORIGIN_ID(message_p), message_p);\n        AssertFatal (result == EXIT_SUCCESS, \"Failed to free memory (%d)!\\n\", result);\n      }\n    } while(message_p != NULL);\n\n#endif\n\n    //Run the aperiodic user-defined events\n    if (oai_emulation.info.oeh_enabled == 1)\n      execute_events (frame);\n\n    if (ue_connection_test == 1) {\n      if ((frame % 20) == 0) {\n        snr_dB += snr_direction;\n        sinr_dB -= snr_direction;\n      }\n\n      if (snr_dB == -20) {\n        snr_direction = snr_step;\n      } else if (snr_dB == 20) {\n        snr_direction = -snr_step;\n      }\n    }\n\n    oai_emulation.info.frame = frame;\n    //oai_emulation.info.time_ms += 1;\n    oai_emulation.info.time_s += 0.01; // emu time in s, each frame lasts for 10 ms // JNote: TODO check the coherency of the time and frame (I corrected it to 10 (instead of 0.01)\n\n     update_omg (frame); // frequency is defined in the omg_global params configurable by the user\n    update_omg_ocm ();\n\n#ifdef OPENAIR2\n\n    // check if pipe is still open\n    if ((oai_emulation.info.omv_enabled == 1)) {\n      omv_write (pfd[1], enb_node_list, ue_node_list, omv_data);\n    }\n\n#endif\n\n    update_ocm ();\n\n    for (sf = 0; sf < 10; sf++) {\n      LOG_D(EMU,\"************************* Subframe %d\\n\",sf);\n\n      start_meas (&oaisim_stats_f);\n\n      wait_for_slot_isr ();\n\n#if defined(ENABLE_ITTI)\n      itti_update_lte_time(frame % MAX_FRAME_NUMBER, sf<<1);\n#endif\n\n      oai_emulation.info.time_ms = frame * 10 + sf;\n\n#ifdef PROC\n\n    if(Channel_Flag==1)\n      Channel_Func(s_re2,s_im2,r_re2,r_im2,r_re02,r_im02,r_re0_d,r_im0_d,r_re0_u,r_im0_u,eNB2UE,UE2eNB,enb_data,ue_data,abstraction_flag,frame_parms,sf<<1);\n\n    if(Channel_Flag==0)\n#endif\n      { // SUBFRAME INNER PART\n#if defined(ENABLE_ITTI)\n        log_set_instance_type (LOG_INSTANCE_ENB);\n#endif\n\n\tclear_eNB_transport_info (oai_emulation.info.nb_enb_local);\n\n        int all_done=0;\n        while (all_done==0) {\n          int i;\n          all_done = 1;\n          for (i = oai_emulation.info.first_enb_local;\n               i < oai_emulation.info.first_enb_local + oai_emulation.info.nb_enb_local;\n               i++)\n            for (CC_id = 0; CC_id < MAX_NUM_CCs; CC_id++)\n              if (last_eNB_rx_timestamp[i][CC_id] != current_eNB_rx_timestamp[i][CC_id]) {\n                all_done = 0;\n                break;\n              }\n          if (all_done == 1)\n            for (i = 0; i < NB_UE_INST; i++)\n              for (CC_id = 0; CC_id < MAX_NUM_CCs; CC_id++)\n                if (last_UE_rx_timestamp[i][CC_id] != current_UE_rx_timestamp[i][CC_id]) {\n                  all_done = 0;\n                  break;\n                }\n          if (all_done == 0)\n\t    usleep(500);\n        }\n\n        // increment timestamps\n        for (eNB_inst = oai_emulation.info.first_enb_local;\n             (eNB_inst\n              < (oai_emulation.info.first_enb_local\n                 + oai_emulation.info.nb_enb_local));\n             eNB_inst++) {\n          for (CC_id = 0; CC_id < MAX_NUM_CCs; CC_id++)\n            current_eNB_rx_timestamp[eNB_inst][CC_id] += PHY_vars_eNB_g[eNB_inst][CC_id]->frame_parms.samples_per_tti;\n        }\n        for (UE_inst = 0; UE_inst<NB_UE_INST;UE_inst++) {\n          for (CC_id = 0; CC_id < MAX_NUM_CCs; CC_id++)\n            current_UE_rx_timestamp[UE_inst][CC_id] += PHY_vars_UE_g[UE_inst][CC_id]->frame_parms.samples_per_tti;\n        }\n\n        for (eNB_inst = oai_emulation.info.first_enb_local;\n             (eNB_inst\n              < (oai_emulation.info.first_enb_local\n                 + oai_emulation.info.nb_enb_local));\n             eNB_inst++) {\n          if (oai_emulation.info.cli_start_enb[eNB_inst] != 0) {\n        \n\t    /*\n\t    LOG_D(EMU,\n\t\t  \"PHY procedures eNB %d for frame %d, subframe %d TDD %d/%d Nid_cell %d\\n\",\n\t\t  eNB_inst,\n\t\t  frame % MAX_FRAME_NUMBER,\n\t\t  sf,\n\t\t  PHY_vars_eNB_g[eNB_inst][0]->frame_parms.frame_type,\n\t\t  PHY_vars_eNB_g[eNB_inst][0]->frame_parms.tdd_config,\n\t\t  PHY_vars_eNB_g[eNB_inst][0]->frame_parms.Nid_cell);\n            \n\t    */\n#ifdef OPENAIR2\n\t    //Application: traffic gen\n            update_otg_eNB (eNB_inst, oai_emulation.info.time_ms);\n\n            //IP/OTG to PDCP and PDCP to IP operation\n            //        pdcp_run (frame, 1, 0, eNB_inst); //PHY_vars_eNB_g[eNB_id]->Mod_id\n#endif\n           \n\n#ifdef PRINT_STATS\n\n            if((sf==9) && frame%10==0)\n              if(eNB_avg_thr)\n                fprintf(eNB_avg_thr,\"%d %d\\n\",PHY_vars_eNB_g[eNB_inst][0]->proc.proc_rxtx[sf&1].frame_tx,\n                        (PHY_vars_eNB_g[eNB_inst][0]->total_system_throughput)/((PHY_vars_eNB_g[eNB_inst][0]->proc.proc_rxtx[sf&1].frame_tx+1)*10));\n\n            if (eNB_stats[eNB_inst]) {\n              len = dump_eNB_stats(PHY_vars_eNB_g[eNB_inst][0], stats_buffer, 0);\n              rewind (eNB_stats[eNB_inst]);\n              fwrite (stats_buffer, 1, len, eNB_stats[eNB_inst]);\n              fflush(eNB_stats[eNB_inst]);\n            }\n\n#ifdef OPENAIR2\n\n            if (eNB_l2_stats) {\n              len = dump_eNB_l2_stats (stats_buffer, 0);\n              rewind (eNB_l2_stats);\n              fwrite (stats_buffer, 1, len, eNB_l2_stats);\n              fflush(eNB_l2_stats);\n            }\n\n#endif\n#endif\n          }\n        }// eNB_inst loop\n\n        // Call ETHERNET emulation here\n        //emu_transport (frame, last_slot, next_slot, direction, oai_emulation.info.frame_type, ethernet_flag);\n\n#if defined(ENABLE_ITTI)\n        log_set_instance_type (LOG_INSTANCE_UE);\n#endif\n\n\n\t/*\n\tclear_UE_transport_info (oai_emulation.info.nb_ue_local);\n          clear_UE_transport_info (oai_emulation.info.nb_ue_local);\n\n        for (UE_inst = oai_emulation.info.first_ue_local;\n             (UE_inst < (oai_emulation.info.first_ue_local + oai_emulation.info.nb_ue_local));\n             UE_inst++) {\n          if (oai_emulation.info.cli_start_ue[UE_inst] != 0) {\n#if defined(ENABLE_ITTI) && defined(ENABLE_USE_MME)\n\n#else\n\n            if (frame >= (UE_inst * 20)) // activate UE only after 20*UE_id frames so that different UEs turn on separately\n#endif\n            {\n              LOG_D(EMU,\n                    \"PHY procedures UE %d for frame %d, slot %d (subframe TX %d, RX %d)\\n\",\n                    UE_inst, frame % MAX_FRAME_NUMBER, slot, next_slot >> 1,\n                    last_slot >> 1);\n\n              if (PHY_vars_UE_g[UE_inst][0]->UE_mode[0]\n                  != NOT_SYNCHED) {\n                if (frame > 0) {\n                  PHY_vars_UE_g[UE_inst][0]->frame_rx = frame % MAX_FRAME_NUMBER;\n                  PHY_vars_UE_g[UE_inst][0]->slot_rx =  last_slot;\n                  PHY_vars_UE_g[UE_inst][0]->slot_tx = next_slot;\n\n                  if (next_slot > 1)\n                    PHY_vars_UE_g[UE_inst][0]->frame_tx = frame % MAX_FRAME_NUMBER;\n                  else\n                    PHY_vars_UE_g[UE_inst][0]->frame_tx = (frame + 1) % MAX_FRAME_NUMBER;\n#ifdef OPENAIR2\n                  //Application\n                  update_otg_UE (UE_inst, oai_emulation.info.time_ms);\n\n                  //Access layer\n\t\t  //\t\t  PROTOCOL_CTXT_SET_BY_MODULE_ID(&ctxt, UE_inst, ENB_FLAG_NO, NOT_A_RNTI, frame, next_slot>>1, 0);\n\t\t  PROTOCOL_CTXT_SET_BY_MODULE_ID(&ctxt, UE_inst, 0, ENB_FLAG_NO, NOT_A_RNTI, frame % MAX_FRAME_NUMBER, next_slot);\n                  pdcp_run (&ctxt);\n#endif\n\n                  for (CC_id = 0; CC_id < MAX_NUM_CCs;\n                       CC_id++) {\n                    phy_procedures_UE_lte (\n                      PHY_vars_UE_g[UE_inst][CC_id],\n\t\t      0, abstraction_flag,\n                      normal_txrx, no_relay,\n                      NULL);\n                  }\n\n                  ue_data[UE_inst]->tx_power_dBm =\n                    PHY_vars_UE_g[UE_inst][0]->tx_power_dBm;\n                }\n              } else {\n                if (abstraction_flag == 1) {\n                  LOG_E(EMU,\n                        \"sync not supported in abstraction mode (UE%d,mode%d)\\n\",\n                        UE_inst,\n                        PHY_vars_UE_g[UE_inst][0]->UE_mode[0]);\n                  exit (-1);\n                }\n\n                if ((frame > 0)\n                    && (last_slot\n                        == (LTE_SLOTS_PER_FRAME\n                            - 2))) {\n                  initial_sync (PHY_vars_UE_g[UE_inst][0],\n                                normal_txrx);\n\n                }\n              }\n\n#ifdef PRINT_STATS\n\n              if(last_slot==2 && frame%10==0) {\n                if (UE_stats_th[UE_inst]) {\n                  fprintf(UE_stats_th[UE_inst],\"%d %d\\n\",frame%MAX_FRAME_NUMBER, PHY_vars_UE_g[UE_inst][0]->bitrate[0]/1000);\n                }\n              }\n\n              if (UE_stats[UE_inst]) {\n                len = dump_ue_stats (PHY_vars_UE_g[UE_inst][0], stats_buffer, 0, normal_txrx, 0);\n                rewind (UE_stats[UE_inst]);\n                fwrite (stats_buffer, 1, len, UE_stats[UE_inst]);\n                fflush(UE_stats[UE_inst]);\n              }\n\n#endif\n            }\n          }\n        }\n\n#if defined(Rel10) || defined(Rel14)\n\n        for (RN_id=oai_emulation.info.first_rn_local;\n             RN_id<oai_emulation.info.first_rn_local+oai_emulation.info.nb_rn_local;\n             RN_id++) {\n          // UE id and eNB id of the RN\n          UE_inst= oai_emulation.info.first_ue_local+oai_emulation.info.nb_ue_local + RN_id;// NB_UE_INST + RN_id\n          eNB_inst= oai_emulation.info.first_enb_local+oai_emulation.info.nb_enb_local + RN_id;// NB_eNB_INST + RN_id\n\n          // currently only works in FDD\n          if (oai_emulation.info.eMBMS_active_state == 4) {\n            r_type = multicast_relay;\n            //LOG_I(EMU,\"Activating the multicast relaying\\n\");\n          } else {\n            LOG_E(EMU,\"Not supported eMBMS option when relaying is enabled %d\\n\", r_type);\n            exit(-1);\n          }\n\n          PHY_vars_RN_g[RN_id]->frame = frame % MAX_FRAME_NUMBER;\n\n          if ( oai_emulation.info.frame_type == 0) {\n            // RN == UE\n            if (frame>0) {\n              if (PHY_vars_UE_g[UE_inst][0]->UE_mode[0] != NOT_SYNCHED) {\n                LOG_D(EMU,\"[RN %d] PHY procedures UE %d for frame %d, slot %d (subframe TX %d, RX %d)\\n\",\n                      RN_id, UE_inst, frame, slot, next_slot >> 1,last_slot>>1);\n                PHY_vars_UE_g[UE_inst][0]->frame_rx = frame % MAX_FRAME_NUMBER;\n                PHY_vars_UE_g[UE_inst][0]->slot_rx = last_slot;\n                PHY_vars_UE_g[UE_inst][0]->slot_tx = next_slot;\n\n                if (next_slot>1) PHY_vars_UE_g[UE_inst][0]->frame_tx = frame % MAX_FRAME_NUMBER;\n                else PHY_vars_UE_g[UE_inst][0]->frame_tx = (frame+1) % MAX_FRAME_NUMBER;\n\n                phy_procedures_UE_lte (PHY_vars_UE_g[UE_inst][0], 0, abstraction_flag,normal_txrx,\n                                       r_type, PHY_vars_RN_g[RN_id]);\n              } else if (last_slot == (LTE_SLOTS_PER_FRAME-2)) {\n                initial_sync(PHY_vars_UE_g[UE_inst][0],normal_txrx);\n              }\n            }\n\n        emu_transport (frame % MAX_FRAME_NUMBER, sf<<1, ((sf+4)%10)<<1, subframe_select(&PHY_vars_eNB_g[0][0]->frame_parms,sf),\n                       oai_emulation.info.frame_type[0], ethernet_flag);\n\n\tstart_meas (&dl_chan_stats);\n\t\n\tfor (UE_inst = 0; UE_inst < NB_UE_INST; UE_inst++)\n\t  for (CC_id = 0; CC_id < MAX_NUM_CCs; CC_id++) {\n\t    //#warning figure out what to do with UE frame_parms during initial_sync\n\t    do_DL_sig (r_re0,\n\t\t       r_im0,\n\t\t       r_re,\n\t\t       r_im,\n\t\t       s_re,\n\t\t       s_im,\n\t\t       eNB2UE,\n\t\t       enb_data,\n\t\t       ue_data,\n\t\t       PHY_vars_eNB_g[0][CC_id]->proc.proc_rxtx[sf&1].subframe_tx<<1,\n\t\t       abstraction_flag,\n\t\t       &PHY_vars_eNB_g[0][CC_id]->frame_parms,\n\t\t       UE_inst, CC_id);\n\t    do_DL_sig (r_re0,\n\t\t       r_im0,\n\t\t       r_re,\n\t\t       r_im,n\n\n\t\t       s_re,\n\t\t       s_im,\n\t\t       eNB2UE,\n\t\t       enb_data,\n\t\t       ue_data,\n\t\t       (PHY_vars_eNB_g[0][CC_id]->proc.proc_rxtx[sf&1].subframe_tx<<1)+1,\n\t\t       abstraction_flag,\n\t\t       &PHY_vars_eNB_g[0][CC_id]->frame_parms,\n\t\t       UE_inst, CC_id);\n\t  }\n\n\tstop_meas (&dl_chan_stats);\n        \n\n\tstart_meas (&ul_chan_stats);\n\t\n\tfor (CC_id = 0; CC_id < MAX_NUM_CCs; CC_id++) {\n\t  //#warning figure out what to do with UE frame_parms during initial_sync\n\t  do_UL_sig (r_re0, r_im0, r_re, r_im, s_re, s_im, UE2eNB,\n\t\t     enb_data, ue_data,\n\t\t     PHY_vars_UE_g[0][CC_id]->proc.proc_rxtx[sf&1].subframe_tx<<1,\n\t\t     abstraction_flag,\n\t\t     &PHY_vars_eNB_g[0][CC_id]->frame_parms,\n\t\t     frame % MAX_FRAME_NUMBER, CC_id);\n\t  do_UL_sig (r_re0, r_im0, r_re, r_im, s_re, s_im, UE2eNB,\n\t\t     enb_data, ue_data,\n\t\t     (PHY_vars_UE_g[0][CC_id]->proc.proc_rxtx[sf&1].subframe_tx<<1)+1,\n\t\t     abstraction_flag,\n\t\t     &PHY_vars_eNB_g[0][CC_id]->frame_parms,\n\t\t     frame % MAX_FRAME_NUMBER, CC_id);\n\t}\n\t\n\tstop_meas (&ul_chan_stats);\n\n\t*/\n\n\tif ((sf == 0) && ((frame % MAX_FRAME_NUMBER) == 0) && (abstraction_flag == 0)\n\t    && (oai_emulation.info.n_frames == 1)) {\n\t  \n\t  write_output (\"dlchan0.m\",\n\t\t\t\"dlch0\",\n\t\t\t&(PHY_vars_UE_g[0][0]->common_vars.common_vars_rx_data_per_thread[0].dl_ch_estimates[0][0][0]),\n\t\t\t(6\n\t\t\t * (PHY_vars_UE_g[0][0]->frame_parms.ofdm_symbol_size)),\n\t\t\t1, 1);\n\t  write_output (\"dlchan1.m\",\n\t\t\t\"dlch1\",\n\t\t\t&(PHY_vars_UE_g[0][0]->common_vars.common_vars_rx_data_per_thread[0].dl_ch_estimates[1][0][0]),\n\t\t\t(6\n\t\t\t * (PHY_vars_UE_g[0][0]->frame_parms.ofdm_symbol_size)),\n\t\t\t1, 1);\n\t  write_output (\"dlchan2.m\",\n\t\t\t\"dlch2\",\n\t\t\t&(PHY_vars_UE_g[0][0]->common_vars.common_vars_rx_data_per_thread[0].dl_ch_estimates[2][0][0]),\n\t\t\t(6\n\t\t\t * (PHY_vars_UE_g[0][0]->frame_parms.ofdm_symbol_size)),\n\t\t\t1, 1);\n\t  write_output (\"pbch_rxF_comp0.m\",\n\t\t\t\"pbch_comp0\",\n\t\t\tPHY_vars_UE_g[0][0]->pbch_vars[0]->rxdataF_comp[0],\n\t\t\t6 * 12 * 4, 1, 1);\n\t  write_output (\"pbch_rxF_llr.m\", \"pbch_llr\",\n\t\t\tPHY_vars_UE_g[0][0]->pbch_vars[0]->llr,\n\t\t\t(frame_parms[0]->Ncp == 0) ? 1920 : 1728, 1,\n\t\t\t4);\n\t}\n    \n\tstop_meas (&oaisim_stats_f);\n      } // SUBFRAME INNER PART\n\n\n    }\n    /*\n    if ((frame >= 10) && (frame <= 11) && (abstraction_flag == 0)\n#ifdef PROC\n\t&&(Channel_Flag==0)\n#endif\n\t) {\n      sprintf (fname, \"UEtxsig%d.m\", frame % MAX_FRAME_NUMBER);\n      sprintf (vname, \"txs%d\", frame % MAX_FRAME_NUMBER);\n      write_output (fname,\n\t\t    vname,\n\t\t    PHY_vars_UE_g[0][0]->common_vars.txdata[0],\n\t\t    PHY_vars_UE_g[0][0]->frame_parms.samples_per_tti\n\t\t    * 10,\n\t\t    1, 1);\n      sprintf (fname, \"eNBtxsig%d.m\", frame % MAX_FRAME_NUMBER);\n      sprintf (vname, \"txs%d\", frame % MAX_FRAME_NUMBER);\n      write_output (fname,\n\t\t    vname,\n\t\t    PHY_vars_eNB_g[0][0]->common_vars.txdata[0][0],\n\t\t    PHY_vars_UE_g[0][0]->frame_parms.samples_per_tti\n\t\t    * 10,\n\t\t    1, 1);\n      sprintf (fname, \"eNBtxsigF%d.m\", frame % MAX_FRAME_NUMBER);\n      sprintf (vname, \"txsF%d\", frame % MAX_FRAME_NUMBER);\n      write_output (fname,\n\t\t    vname,\n\t\t    PHY_vars_eNB_g[0][0]->common_vars.txdataF[0][0],\n\t\t    PHY_vars_eNB_g[0][0]->frame_parms.symbols_per_tti\n\t\t    * PHY_vars_eNB_g[0][0]->frame_parms.ofdm_symbol_size,\n\t\t    1, 1);\n      sprintf (fname, \"UErxsig%d.m\", frame % MAX_FRAME_NUMBER);\n      sprintf (vname, \"rxs%d\", frame % MAX_FRAME_NUMBER);\n      write_output (fname,\n\t\t    vname,\n\t\t    PHY_vars_UE_g[0][0]->common_vars.rxdata[0],\n\t\t    PHY_vars_UE_g[0][0]->frame_parms.samples_per_tti\n\t\t    * 10,\n\t\t    1, 1);\n      sprintf (fname, \"eNBrxsig%d.m\", frame % MAX_FRAME_NUMBER);\n      sprintf (vname, \"rxs%d\", frame % MAX_FRAME_NUMBER);\n      write_output (fname,\n\t\t    vname,\n\t\t    PHY_vars_eNB_g[0][0]->common_vars.rxdata[0][0],\n\t\t    PHY_vars_UE_g[0][0]->frame_parms.samples_per_tti\n\t\t    * 10,\n\t\t    1, 1);\n    }\n    */\n    \n    //#ifdef XFORMS\n    if (xforms==1) {\n      eNB_inst = 0;\n      \n      for (UE_inst = 0; UE_inst < NB_UE_INST; UE_inst++) {\n\tfor (CC_id=0;CC_id<MAX_NUM_CCs;CC_id++) {\n\t  phy_scope_UE(form_ue[CC_id][UE_inst],\n\t\t   PHY_vars_UE_g[UE_inst][CC_id],\n\t\t   eNB_inst,\n\t\t   UE_inst,\n\t\t   7);\n\t}\n\n\tphy_scope_eNB(form_enb[UE_inst],\n\t\t      PHY_vars_eNB_g[eNB_inst][0],\n\t\t      UE_inst);\n\t\n      }\n    }\n    //#endif\n    \n#ifdef SMBV\n    \n    // Rohde&Schwarz SMBV100A vector signal generator\n    if ((frame % MAX_FRAME_NUMBER == config_frames[0]) || (frame % MAX_FRAME_NUMBER == config_frames[1]) || (frame % MAX_FRAME_NUMBER == config_frames[2]) || (frame % MAX_FRAME_NUMBER == config_frames[3])) {\n      smbv_frame_cnt++;\n    }\n    \n#endif\n    \n  } // frame loop\n\n  stop_meas (&oaisim_stats);\n  oai_shutdown ();\n  \n#ifdef PRINT_STATS\n  \n  for (UE_inst=0; UE_inst<NB_UE_INST; UE_inst++) {\n    if (UE_stats[UE_inst])\n      fclose (UE_stats[UE_inst]);\n    \n    if(UE_stats_th[UE_inst])\n      fclose (UE_stats_th[UE_inst]);\n  }\n  \n  for (eNB_inst=0; eNB_inst<NB_eNB_INST; eNB_inst++) {\n    if (eNB_stats[eNB_inst])\n      fclose (eNB_stats[eNB_inst]);\n  }\n  \n  if (eNB_avg_thr)\n    fclose (eNB_avg_thr);\n  \n  if (eNB_l2_stats)\n    fclose (eNB_l2_stats);\n  \n#endif\n  \n#if defined(ENABLE_ITTI)\n  itti_terminate_tasks(TASK_L2L1);\n#endif\n  \n  return NULL;\n}\n\n#if defined(FLEXRAN_AGENT_SB_IF)\n/*\n * The following two functions are meant to restart *the lte-softmodem* and are\n * here to make oaisim compile. A restart command from the controller will be\n * ignored in oaisim.\n */\nint stop_L1L2(int enb_id)\n{\n  LOG_W(FLEXRAN_AGENT, \"stop_L1L2() not supported in oaisim\\n\");\n  return 0;\n}\n\nint restart_L1L2(int enb_id)\n{\n  LOG_W(FLEXRAN_AGENT, \"restart_L1L2() not supported in oaisim\\n\");\n  return 0;\n}\n#endif\n\n#if T_TRACER\nint T_wait = 1;       /* by default we wait for the tracer */\nint T_port = 2021;    /* default port to listen to to wait for the tracer */\nint T_dont_fork = 0;  /* default is to fork, see 'T_init' to understand */\n#endif\n\nstatic void print_current_directory(void)\n{\n  char dir[8192]; /* arbitrary size (should be big enough) */\n  if (getcwd(dir, 8192) == NULL)\n    printf(\"ERROR getting working directory\\n\");\n  else\n    printf(\"working directory: %s\\n\", dir);\n}\n\n/*------------------------------------------------------------------------------*/\nint\nmain (int argc, char **argv)\n{\n\n  clock_t t;\n\n  print_current_directory();\n\n  start_background_system();\n\n#ifdef SMBV\n  // Rohde&Schwarz SMBV100A vector signal generator\n  strcpy(smbv_ip,DEFAULT_SMBV_IP);\n#endif\n\n#ifdef PROC\n  int node_id;\n  int port,Process_Flag=0,wgt,Channel_Flag=0,temp;\n#endif\n\n  //default parameters\n  oai_emulation.info.n_frames = MAX_FRAME_NUMBER; //1024;          //10;\n  oai_emulation.info.n_frames_flag = 0; //fixme\n  snr_dB = 30;\n\n  //Default values if not changed by the user in get_simulation_options();\n  pdcp_period = 1;\n  omg_period = 1;\n  //Clean ip rule table\n  for(int i =0; i<NUMBER_OF_UE_MAX; i++){\n      char command_line[100];\n      sprintf(command_line, \"while ip rule del table %d; do true; done\",i+201);\n      /* we don't care about return value from system(), but let's the\n       * compiler be silent, so let's do \"if (XX);\"\n       */\n      if (system(command_line)) /* nothing */;\n  }\n  // start thread for log gen\n  log_thread_init ();\n\n  init_oai_emulation (); // to initialize everything !!!\n\n  // get command-line options\n  get_simulation_options (argc, argv); //Command-line options\n\n#if T_TRACER\n  T_init(T_port, T_wait, T_dont_fork);\n#endif\n\n  // Initialize VCD LOG module\n  VCD_SIGNAL_DUMPER_INIT (oai_emulation.info.vcd_file);\n\n#if !defined(ENABLE_ITTI)\n  pthread_t tid;\n  int err;\n  sigset_t sigblock;\n  sigemptyset (&sigblock);\n  sigaddset (&sigblock, SIGHUP);\n  sigaddset (&sigblock, SIGINT);\n  sigaddset (&sigblock, SIGTERM);\n  sigaddset (&sigblock, SIGQUIT);\n  //sigaddset(&sigblock, SIGKILL);\n\n  if ((err = pthread_sigmask (SIG_BLOCK, &sigblock, NULL)) != 0) {\n    printf (\"SIG_BLOCK error\\n\");\n    return -1;\n  }\n\n  if (pthread_create (&tid, NULL, sigh, NULL)) {\n    printf (\"Pthread for tracing Signals is not created!\\n\");\n    return -1;\n  } else {\n    printf (\"Pthread for tracing Signals is created!\\n\");\n  }\n\n#endif\n  // configure oaisim with OCG\n  oaisim_config (); // config OMG and OCG, OPT, OTG, OLG\n\n  if (ue_connection_test == 1) {\n    snr_direction = -snr_step;\n    snr_dB = 20;\n    sinr_dB = -20;\n  }\n\n  pthread_cond_init(&sync_cond,NULL);\n  pthread_mutex_init(&sync_mutex, NULL);\n  pthread_mutex_init(&subframe_mutex, NULL);\n\n#ifdef OPENAIR2\n  init_omv ();\n#endif\n  //Before this call, NB_UE_INST and NB_eNB_INST are not set correctly\n  check_and_adjust_params ();\n\n  set_seed = oai_emulation.emulation_config.seed.value;\n\n  init_otg_pdcp_buffer ();\n\n  init_seed (set_seed);\n\n  init_openair1 ();\n\n  init_openair2 ();\n\n  void init_openair0(void);\n  init_openair0();\n\n  init_ocm ();\n\n#if defined(ENABLE_ITTI)\n  // Note: Cannot handle both RRU/RAU and eNB at the same time, if the first \"eNB\" is an RRU/RAU, no NAS\n  if (oai_emulation.info.node_function[0] < NGFI_RAU_IF4p5) { \n    if (create_tasks(oai_emulation.info.nb_enb_local, \n\t\t     oai_emulation.info.nb_ue_local) < 0) \n      exit(-1); // need a softer mode\n  }\n  else {\n    if (create_tasks(0, \n\t\t     oai_emulation.info.nb_ue_local) < 0) \n      exit(-1); // need a softer mode\n  }\n#endif\n  \n  // wait for all threads to startup \n  sleep(3);\n  printf(\"Sending sync to all threads\\n\");\n\n  pthread_mutex_lock(&sync_mutex);\n  sync_var=0;\n  pthread_cond_broadcast(&sync_cond);\n  pthread_mutex_unlock(&sync_mutex);\n\n#ifdef SMBV\n  // Rohde&Schwarz SMBV100A vector signal generator\n  smbv_init_config(smbv_fname, smbv_nframes);\n  smbv_write_config_from_frame_parms(smbv_fname, &PHY_vars_eNB_g[0][0]->frame_parms);\n#endif\n\n  /* #if defined (FLEXRAN_AGENT_SB_IF)\n  flexran_agent_start();\n  #endif */ \n\n  // add events to future event list: Currently not used\n  //oai_emulation.info.oeh_enabled = 1;\n  if (oai_emulation.info.oeh_enabled == 1)\n    schedule_events ();\n\n  // oai performance profiler is enabled\n  if (oai_emulation.info.opp_enabled == 1)\n    reset_opp_meas_oaisim ();\n\n  cpuf=get_cpu_freq_GHz();\n\n  init_time ();\n\n  init_slot_isr ();\n\n  t = clock ();\n\n  LOG_N(EMU,\n        \">>>>>>>>>>>>>>>>>>>>>>>>>>> OAIEMU initialization done <<<<<<<<<<<<<<<<<<<<<<<<<<\\n\\n\");\n\n#ifndef PACKAGE_VERSION\n#  define PACKAGE_VERSION \"UNKNOWN-EXPERIMENTAL\"\n#endif\n  LOG_I(EMU, \"Version: %s\\n\", PACKAGE_VERSION);\n\n#if defined(ENABLE_ITTI)\n\n  // Handle signals until all tasks are terminated\n  itti_wait_tasks_end();\n\n#else\n\n  if (oai_emulation.info.nb_enb_local > 0) {\n    eNB_app_task (NULL); // do nothing for the moment\n  }\n\n  l2l1_task (NULL);\n#endif\n  t = clock () - t;\n  LOG_I(EMU, \"Duration of the simulation: %f seconds\\n\",\n        ((float) t) / CLOCKS_PER_SEC);\n\n  LOG_N(EMU,\n        \">>>>>>>>>>>>>>>>>>>>>>>>>>> OAIEMU Ending <<<<<<<<<<<<<<<<<<<<<<<<<<\\n\\n\");\n\n  raise (SIGINT);\n  //  oai_shutdown ();\n\n  return (0);\n}\n\nvoid\nreset_opp_meas_oaisim (void)\n{\n  uint8_t eNB_id = 0, UE_id = 0;\n\n  reset_meas (&oaisim_stats);\n  reset_meas (&oaisim_stats_f); // frame\n\n  // init time stats here (including channel)\n  reset_meas (&dl_chan_stats);\n  reset_meas (&ul_chan_stats);\n\n  for (UE_id = 0; UE_id < NB_UE_INST; UE_id++) {\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->phy_proc[0]);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->phy_proc[1]);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->phy_proc_rx[0]);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->phy_proc_rx[1]);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->phy_proc_tx);\n\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->ofdm_demod_stats);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->rx_dft_stats);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_channel_estimation_stats);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_freq_offset_estimation_stats);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_decoding_stats[0]);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_decoding_stats[1]);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_rate_unmatching_stats);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_turbo_decoding_stats);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_deinterleaving_stats);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_llr_stats);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_unscrambling_stats);\n\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_tc_init_stats);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_tc_alpha_stats);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_tc_beta_stats);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_tc_gamma_stats);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_tc_ext_stats);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_tc_intl1_stats);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_tc_intl2_stats);\n\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->tx_prach);\n\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->ofdm_mod_stats);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->ulsch_encoding_stats);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->ulsch_modulation_stats);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->ulsch_segmentation_stats);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->ulsch_rate_matching_stats);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->ulsch_turbo_encoding_stats);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->ulsch_interleaving_stats);\n    reset_meas (&PHY_vars_UE_g[UE_id][0]->ulsch_multiplexing_stats);\n    /*\n     * L2 functions\n     */\n\n    // UE MAC\n    reset_meas (&UE_mac_inst[UE_id].ue_scheduler); // total\n    reset_meas (&UE_mac_inst[UE_id].tx_ulsch_sdu); // inlcude rlc_data_req + mac header gen\n    reset_meas (&UE_mac_inst[UE_id].rx_dlsch_sdu); // include mac_rrc_data_ind or mac_rlc_status_ind+mac_rlc_data_ind and  mac header parser\n    reset_meas (&UE_mac_inst[UE_id].ue_query_mch);\n    reset_meas (&UE_mac_inst[UE_id].rx_mch_sdu); // include rld_data_ind+ parse mch header\n    reset_meas (&UE_mac_inst[UE_id].rx_si); // include rlc_data_ind + mac header parser\n\n    reset_meas (&UE_pdcp_stats[UE_id].pdcp_run);\n    reset_meas (&UE_pdcp_stats[UE_id].data_req);\n    reset_meas (&UE_pdcp_stats[UE_id].data_ind);\n    reset_meas (&UE_pdcp_stats[UE_id].apply_security);\n    reset_meas (&UE_pdcp_stats[UE_id].validate_security);\n    reset_meas (&UE_pdcp_stats[UE_id].pdcp_ip);\n    reset_meas (&UE_pdcp_stats[UE_id].ip_pdcp);\n\n  }\n\n  for (eNB_id = 0; eNB_id < NB_eNB_INST; eNB_id++) {\n\n    for (UE_id = 0; UE_id < NB_UE_INST; UE_id++) {\n      reset_meas (&eNB2UE[eNB_id][UE_id][0]->random_channel);\n      reset_meas (&eNB2UE[eNB_id][UE_id][0]->interp_time);\n      reset_meas (&eNB2UE[eNB_id][UE_id][0]->interp_freq);\n      reset_meas (&eNB2UE[eNB_id][UE_id][0]->convolution);\n      reset_meas (&UE2eNB[UE_id][eNB_id][0]->random_channel);\n      reset_meas (&UE2eNB[UE_id][eNB_id][0]->interp_time);\n      reset_meas (&UE2eNB[UE_id][eNB_id][0]->interp_freq);\n      reset_meas (&UE2eNB[UE_id][eNB_id][0]->convolution);\n    }\n\n    reset_meas (&PHY_vars_eNB_g[eNB_id][0]->phy_proc);\n    reset_meas (&PHY_vars_eNB_g[eNB_id][0]->phy_proc_rx);\n    reset_meas (&PHY_vars_eNB_g[eNB_id][0]->phy_proc_tx);\n    reset_meas (&PHY_vars_eNB_g[eNB_id][0]->rx_prach);\n\n    reset_meas (&PHY_vars_eNB_g[eNB_id][0]->ofdm_mod_stats);\n    reset_meas (&PHY_vars_eNB_g[eNB_id][0]->dlsch_encoding_stats);\n    reset_meas (&PHY_vars_eNB_g[eNB_id][0]->dlsch_modulation_stats);\n    reset_meas (&PHY_vars_eNB_g[eNB_id][0]->dlsch_scrambling_stats);\n    reset_meas (&PHY_vars_eNB_g[eNB_id][0]->dlsch_rate_matching_stats);\n    reset_meas (&PHY_vars_eNB_g[eNB_id][0]->dlsch_turbo_encoding_stats);\n    reset_meas (&PHY_vars_eNB_g[eNB_id][0]->dlsch_interleaving_stats);\n\n    reset_meas (&PHY_vars_eNB_g[eNB_id][0]->ofdm_demod_stats);\n    //reset_meas(&PHY_vars_eNB_g[eNB_id]->rx_dft_stats);\n    //reset_meas(&PHY_vars_eNB_g[eNB_id]->ulsch_channel_estimation_stats);\n    //reset_meas(&PHY_vars_eNB_g[eNB_id]->ulsch_freq_offset_estimation_stats);\n    reset_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_decoding_stats);\n    reset_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_demodulation_stats);\n    reset_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_rate_unmatching_stats);\n    reset_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_turbo_decoding_stats);\n    reset_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_deinterleaving_stats);\n    reset_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_demultiplexing_stats);\n    reset_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_llr_stats);\n    reset_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_tc_init_stats);\n    reset_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_tc_alpha_stats);\n    reset_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_tc_beta_stats);\n    reset_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_tc_gamma_stats);\n    reset_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_tc_ext_stats);\n    reset_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_tc_intl1_stats);\n    reset_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_tc_intl2_stats);\n#ifdef LOCALIZATION\n    reset_meas(&PHY_vars_eNB_g[eNB_id][0]->localization_stats);\n#endif\n\n    /*\n     * L2 functions\n     */\n    // eNB MAC\n    reset_meas (&eNB_mac_inst[eNB_id].eNB_scheduler); // total\n    reset_meas (&eNB_mac_inst[eNB_id].schedule_si); // only schedule + tx\n    reset_meas (&eNB_mac_inst[eNB_id].schedule_ra); // only ra\n    reset_meas (&eNB_mac_inst[eNB_id].schedule_ulsch); // onlu ulsch\n    reset_meas (&eNB_mac_inst[eNB_id].fill_DLSCH_dci); // only dci\n    reset_meas (&eNB_mac_inst[eNB_id].schedule_dlsch_preprocessor); // include rlc_data_req + MAC header gen\n    reset_meas (&eNB_mac_inst[eNB_id].schedule_dlsch); // include rlc_data_req + MAC header gen + pre-processor\n    reset_meas (&eNB_mac_inst[eNB_id].schedule_mch); // only embms\n    reset_meas (&eNB_mac_inst[eNB_id].rx_ulsch_sdu); // include rlc_data_ind + mac header parser\n\n    reset_meas (&eNB_pdcp_stats[eNB_id].pdcp_run);\n    reset_meas (&eNB_pdcp_stats[eNB_id].data_req);\n    reset_meas (&eNB_pdcp_stats[eNB_id].data_ind);\n    reset_meas (&eNB_pdcp_stats[eNB_id].apply_security);\n    reset_meas (&eNB_pdcp_stats[eNB_id].validate_security);\n    reset_meas (&eNB_pdcp_stats[eNB_id].pdcp_ip);\n    reset_meas (&eNB_pdcp_stats[eNB_id].ip_pdcp);\n\n  }\n}\n\nvoid\nprint_opp_meas_oaisim (void)\n{\n\n  uint8_t eNB_id = 0, UE_id = 0;\n\n  print_meas (&oaisim_stats, \"[OAI][total_exec_time]\", &oaisim_stats,\n              &oaisim_stats);\n  print_meas (&oaisim_stats_f, \"[OAI][SF_exec_time]\", &oaisim_stats,\n              &oaisim_stats_f);\n\n  print_meas (&dl_chan_stats, \"[DL][chan_stats]\", &oaisim_stats,\n              &oaisim_stats_f);\n  print_meas (&ul_chan_stats, \"[UL][chan_stats]\", &oaisim_stats,\n              &oaisim_stats_f);\n\n  for (UE_id = 0; UE_id < NB_UE_INST; UE_id++) {\n    for (eNB_id = 0; eNB_id < NB_eNB_INST; eNB_id++) {\n      print_meas (&eNB2UE[eNB_id][UE_id][0]->random_channel,\n                  \"[DL][random_channel]\", &oaisim_stats, &oaisim_stats_f);\n      print_meas (&eNB2UE[eNB_id][UE_id][0]->interp_time,\n                  \"[DL][interp_time]\", &oaisim_stats, &oaisim_stats_f);\n      print_meas (&eNB2UE[eNB_id][UE_id][0]->interp_freq,\n                  \"[DL][interp_freq]\", &oaisim_stats, &oaisim_stats_f);\n      print_meas (&eNB2UE[eNB_id][UE_id][0]->convolution,\n                  \"[DL][convolution]\", &oaisim_stats, &oaisim_stats_f);\n\n      print_meas (&UE2eNB[UE_id][eNB_id][0]->random_channel,\n                  \"[UL][random_channel]\", &oaisim_stats, &oaisim_stats_f);\n      print_meas (&UE2eNB[UE_id][eNB_id][0]->interp_time,\n                  \"[UL][interp_time]\", &oaisim_stats, &oaisim_stats_f);\n      print_meas (&UE2eNB[UE_id][eNB_id][0]->interp_freq,\n                  \"[UL][interp_freq]\", &oaisim_stats, &oaisim_stats_f);\n      print_meas (&UE2eNB[UE_id][eNB_id][0]->convolution,\n                  \"[UL][convolution]\", &oaisim_stats, &oaisim_stats_f);\n    }\n  }\n\n  for (UE_id = 0; UE_id < NB_UE_INST; UE_id++) {\n    print_meas (&PHY_vars_UE_g[UE_id][0]->phy_proc[0], \"[UE][total_phy_proc[0]]\",\n                &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->phy_proc[1], \"[UE][total_phy_proc[1]]\",\n                &oaisim_stats, &oaisim_stats_f);\n\n    print_meas (&PHY_vars_UE_g[UE_id][0]->phy_proc_rx[0],\n                \"[UE][total_phy_proc_rx[0]]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->phy_proc_rx[1],\n                \"[UE][total_phy_proc_rx[1]]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->ofdm_demod_stats,\n                \"[UE][ofdm_demod]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->rx_dft_stats, \"[UE][rx_dft]\",\n                &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_channel_estimation_stats,\n                \"[UE][channel_est]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_freq_offset_estimation_stats,\n                \"[UE][freq_offset]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_llr_stats, \"[UE][llr]\",\n                &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_unscrambling_stats,\n                \"[UE][unscrambling]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_decoding_stats[0],\n                \"[UE][decoding[0]]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_decoding_stats[1],\n                \"[UE][decoding[1]]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_rate_unmatching_stats,\n                \"[UE][rate_unmatching]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_deinterleaving_stats,\n                \"[UE][deinterleaving]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_turbo_decoding_stats,\n                \"[UE][turbo_decoding]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_tc_init_stats,\n                \"[UE][ |_tc_init]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_tc_alpha_stats,\n                \"[UE][ |_tc_alpha]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_tc_beta_stats,\n                \"[UE][ |_tc_beta]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_tc_gamma_stats,\n                \"[UE][ |_tc_gamma]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_tc_ext_stats,\n                \"[UE][ |_tc_ext]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_tc_intl1_stats,\n                \"[UE][ |_tc_intl1]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_tc_intl2_stats,\n                \"[UE][ |_tc_intl2]\", &oaisim_stats, &oaisim_stats_f);\n\n    print_meas (&PHY_vars_UE_g[UE_id][0]->phy_proc_tx,\n                \"[UE][total_phy_proc_tx]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->ofdm_mod_stats, \"[UE][ofdm_mod]\",\n                &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->ulsch_modulation_stats,\n                \"[UE][modulation]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->ulsch_encoding_stats,\n                \"[UE][encoding]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->ulsch_segmentation_stats,\n                \"[UE][segmentation]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->ulsch_rate_matching_stats,\n                \"[UE][rate_matching]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->ulsch_turbo_encoding_stats,\n                \"[UE][turbo_encoding]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->ulsch_interleaving_stats,\n                \"[UE][interleaving]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_UE_g[UE_id][0]->ulsch_multiplexing_stats,\n                \"[UE][multiplexing]\", &oaisim_stats, &oaisim_stats_f);\n\n  }\n\n  for (eNB_id = 0; eNB_id < NB_eNB_INST; eNB_id++) {\n    print_meas (&PHY_vars_eNB_g[eNB_id][0]->phy_proc,\n                \"[eNB][total_phy_proc]\", &oaisim_stats, &oaisim_stats_f);\n\n    print_meas (&PHY_vars_eNB_g[eNB_id][0]->phy_proc_tx,\n                \"[eNB][total_phy_proc_tx]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_eNB_g[eNB_id][0]->ofdm_mod_stats,\n                \"[eNB][ofdm_mod]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_eNB_g[eNB_id][0]->dlsch_modulation_stats,\n                \"[eNB][modulation]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_eNB_g[eNB_id][0]->dlsch_scrambling_stats,\n                \"[eNB][scrambling]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_eNB_g[eNB_id][0]->dlsch_encoding_stats,\n                \"[eNB][encoding]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_eNB_g[eNB_id][0]->dlsch_interleaving_stats,\n                \"[eNB][|_interleaving]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_eNB_g[eNB_id][0]->dlsch_rate_matching_stats,\n                \"[eNB][|_rate_matching]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_eNB_g[eNB_id][0]->dlsch_turbo_encoding_stats,\n                \"[eNB][|_turbo_encoding]\", &oaisim_stats, &oaisim_stats_f);\n\n    print_meas (&PHY_vars_eNB_g[eNB_id][0]->phy_proc_rx,\n                \"[eNB][total_phy_proc_rx]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_eNB_g[eNB_id][0]->ofdm_demod_stats,\n                \"[eNB][ofdm_demod]\", &oaisim_stats, &oaisim_stats_f);\n    //print_meas(&PHY_vars_eNB_g[eNB_id][0]->ulsch_channel_estimation_stats,\"[eNB][channel_est]\");\n    //print_meas(&PHY_vars_eNB_g[eNB_id][0]->ulsch_freq_offset_estimation_stats,\"[eNB][freq_offset]\");\n    //print_meas(&PHY_vars_eNB_g[eNB_id][0]->rx_dft_stats,\"[eNB][rx_dft]\");\n    print_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_demodulation_stats,\n                \"[eNB][demodulation]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_decoding_stats,\n                \"[eNB][decoding]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_deinterleaving_stats,\n                \"[eNB][|_deinterleaving]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_demultiplexing_stats,\n                \"[eNB][|_demultiplexing]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_rate_unmatching_stats,\n                \"[eNB][|_rate_unmatching]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_turbo_decoding_stats,\n                \"[eNB][|_turbo_decoding]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_tc_init_stats,\n                \"[eNB][ |_tc_init]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_tc_alpha_stats,\n                \"[eNB][ |_tc_alpha]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_tc_beta_stats,\n                \"[eNB][ |_tc_beta]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_tc_gamma_stats,\n                \"[eNB][ |_tc_gamma]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_tc_ext_stats,\n                \"[eNB][ |_tc_ext]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_tc_intl1_stats,\n                \"[eNB][ |_tc_intl1]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_tc_intl2_stats,\n                \"[eNB][ |_tc_intl2]\", &oaisim_stats, &oaisim_stats_f);\n\n    print_meas (&PHY_vars_eNB_g[eNB_id][0]->rx_prach, \"[eNB][rx_prach]\",\n                &oaisim_stats, &oaisim_stats_f);\n\n#ifdef LOCALIZATION\n    print_meas(&PHY_vars_eNB_g[eNB_id][0]->localization_stats, \"[eNB][LOCALIZATION]\",&oaisim_stats,&oaisim_stats_f);\n#endif\n  }\n\n  for (UE_id = 0; UE_id < NB_UE_INST; UE_id++) {\n\n    print_meas (&UE_mac_inst[UE_id].ue_scheduler, \"[UE][mac_scheduler]\",\n                &oaisim_stats, &oaisim_stats_f);\n    print_meas (&UE_mac_inst[UE_id].tx_ulsch_sdu, \"[UE][tx_ulsch_sdu]\",\n                &oaisim_stats, &oaisim_stats_f);\n    print_meas (&UE_mac_inst[UE_id].rx_dlsch_sdu, \"[UE][rx_dlsch_sdu]\",\n                &oaisim_stats, &oaisim_stats_f);\n    print_meas (&UE_mac_inst[UE_id].ue_query_mch, \"[UE][query_MCH]\",\n                &oaisim_stats, &oaisim_stats_f);\n    print_meas (&UE_mac_inst[UE_id].rx_mch_sdu, \"[UE][rx_mch_sdu]\",\n                &oaisim_stats, &oaisim_stats_f);\n    print_meas (&UE_mac_inst[UE_id].rx_si, \"[UE][rx_si]\", &oaisim_stats,\n                &oaisim_stats_f);\n\n    print_meas (&UE_pdcp_stats[UE_id].pdcp_run, \"[UE][total_pdcp_run]\",\n                &oaisim_stats, &oaisim_stats_f);\n    print_meas (&UE_pdcp_stats[UE_id].data_req, \"[UE][DL][pdcp_data_req]\",\n                &oaisim_stats, &oaisim_stats_f);\n    print_meas (&UE_pdcp_stats[UE_id].data_ind, \"[UE][UL][pdcp_data_ind]\",\n                &oaisim_stats, &oaisim_stats_f);\n\n    print_meas (&UE_pdcp_stats[UE_id].apply_security,\n                \"[UE][DL][apply_security]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&UE_pdcp_stats[UE_id].validate_security,\n                \"[UE][UL][validate_security]\", &oaisim_stats,\n                &oaisim_stats_f);\n    print_meas (&UE_pdcp_stats[UE_id].ip_pdcp, \"[UE][DL][ip_pdcp]\",\n                &oaisim_stats, &oaisim_stats_f);\n    print_meas (&UE_pdcp_stats[UE_id].pdcp_ip, \"[UE][UL][pdcp_ip]\",\n                &oaisim_stats, &oaisim_stats_f);\n\n  }\n\n  for (eNB_id = 0; eNB_id < NB_eNB_INST; eNB_id++) {\n\n    print_meas (&eNB_mac_inst[eNB_id].eNB_scheduler, \"[eNB][mac_scheduler]\",\n                &oaisim_stats, &oaisim_stats_f);\n    print_meas (&eNB_mac_inst[eNB_id].schedule_si, \"[eNB][DL][SI]\",\n                &oaisim_stats, &oaisim_stats_f);\n    print_meas (&eNB_mac_inst[eNB_id].schedule_ra, \"[eNB][DL][RA]\",\n                &oaisim_stats, &oaisim_stats_f);\n    print_meas (&eNB_mac_inst[eNB_id].fill_DLSCH_dci,\n                \"[eNB][DL/UL][fill_DCI]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&eNB_mac_inst[eNB_id].schedule_dlsch_preprocessor,\n                \"[eNB][DL][preprocessor]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&eNB_mac_inst[eNB_id].schedule_dlsch,\n                \"[eNB][DL][schedule_tx_dlsch]\", &oaisim_stats,\n                &oaisim_stats_f);\n    print_meas (&eNB_mac_inst[eNB_id].schedule_mch, \"[eNB][DL][mch]\",\n                &oaisim_stats, &oaisim_stats_f);\n    print_meas (&eNB_mac_inst[eNB_id].schedule_ulsch, \"[eNB][UL][ULSCH]\",\n                &oaisim_stats, &oaisim_stats_f);\n    print_meas (&eNB_mac_inst[eNB_id].rx_ulsch_sdu,\n                \"[eNB][UL][rx_ulsch_sdu]\", &oaisim_stats, &oaisim_stats_f);\n\n    print_meas (&eNB_pdcp_stats[eNB_id].pdcp_run, \"[eNB][pdcp_run]\",\n                &oaisim_stats, &oaisim_stats_f);\n    print_meas (&eNB_pdcp_stats[eNB_id].data_req,\n                \"[eNB][DL][pdcp_data_req]\", &oaisim_stats, &oaisim_stats_f);\n    print_meas (&eNB_pdcp_stats[eNB_id].data_ind,\n                \"[eNB][UL][pdcp_data_ind]\", &oaisim_stats, &oaisim_stats_f);\n\n    print_meas (&eNB_pdcp_stats[eNB_id].apply_security,\n                \"[eNB][DL][apply_security]\", &oaisim_stats,\n                &oaisim_stats_f);\n    print_meas (&eNB_pdcp_stats[eNB_id].validate_security,\n                \"[eNB][UL][validate_security]\", &oaisim_stats,\n                &oaisim_stats_f);\n    print_meas (&eNB_pdcp_stats[eNB_id].ip_pdcp, \"[eNB][DL][ip_pdcp]\",\n                &oaisim_stats, &oaisim_stats_f);\n    print_meas (&eNB_pdcp_stats[eNB_id].pdcp_ip, \"[eNB][UL][pdcp_ip]\",\n                &oaisim_stats, &oaisim_stats_f);\n\n  }\n\n}\n\n#if !defined(ENABLE_ITTI)\nstatic void *\nsigh (void *arg)\n{\n\n  int signum;\n  sigset_t sigcatch;\n  sigemptyset (&sigcatch);\n  sigaddset (&sigcatch, SIGHUP);\n  sigaddset (&sigcatch, SIGINT);\n  sigaddset (&sigcatch, SIGTERM);\n  sigaddset (&sigcatch, SIGQUIT);\n\n  for (;;) {\n    sigwait (&sigcatch, &signum);\n\n    //sigwait(&sigblock, &signum);\n    switch (signum) {\n    case SIGHUP:\n    case SIGINT:\n    case SIGTERM:\n    case SIGQUIT:\n      fprintf (stderr, \"received signal %d \\n\", signum);\n      // no need for mutx: when ITTI not used, this variable is only accessed by this function\n      l2l1_state = L2L1_TERMINATED;\n      break;\n\n    default:\n      fprintf (stderr, \"Unexpected signal %d \\n\", signum);\n      exit (-1);\n      break;\n    }\n  }\n\n  pthread_exit (NULL);\n}\n#endif /* !defined(ENABLE_ITTI) */\n\nvoid\noai_shutdown (void)\n{\n  static int done = 0;\n\n  if (done)\n    return;\n\n  free (otg_pdcp_buffer);\n  otg_pdcp_buffer = 0;\n\n#ifdef SMBV\n\n  // Rohde&Schwarz SMBV100A vector signal generator\n  if (config_smbv) {\n    smbv_send_config (smbv_fname,smbv_ip);\n  }\n\n#endif\n\n  //Perform KPI measurements\n  if (oai_emulation.info.otg_enabled == 1){\n    LOG_N(EMU,\"calling OTG kpi gen .... \\n\");\n    kpi_gen ();\n  }\n  if (oai_emulation.info.opp_enabled == 1)\n    print_opp_meas_oaisim ();\n\n  // relase all rx state\n  if (ethernet_flag == 1) {\n    emu_transport_release ();\n  }\n\n#ifdef PROC\n\n  if (abstraction_flag == 0 && Channel_Flag==0 && Process_Flag==0)\n#else\n    if (abstraction_flag == 0)\n#endif\n      {\n\t/*\n\t  #ifdef IFFT_FPGA\n\t  free(txdataF2[0]);\n\t  free(txdataF2[1]);\n\t  free(txdataF2);\n\t  free(txdata[0]);\n\t  free(txdata[1]);\n\t  free(txdata);\n\t  #endif\n\t*/\n\t/*\n\tfor (int i = 0; i < 2; i++) {\n\t  free (s_re[i]);\n\t  free (s_im[i]);\n\t  free (r_re[i]);\n\t  free (r_im[i]);\n\t}\n\n\tfree (s_re);\n\tfree (s_im);\n\tfree (r_re);\n\tfree (r_im);\n\ts_re = 0;\n\ts_im = 0;\n\tr_re = 0;\n\tr_im = 0;*/\n\n\tlte_sync_time_free ();\n      }\n\n  // added for PHY abstraction\n  if (oai_emulation.info.ocm_enabled == 1) {\n    for (eNB_inst = 0; eNB_inst < NUMBER_OF_eNB_MAX; eNB_inst++) {\n      free (enb_data[eNB_inst]);\n      enb_data[eNB_inst] = 0;\n    }\n\n    for (UE_inst = 0; UE_inst < NUMBER_OF_UE_MAX; UE_inst++) {\n      free (ue_data[UE_inst]);\n      ue_data[UE_inst] = 0;\n    }\n  } //End of PHY abstraction changes\n\n#ifdef OPENAIR2\n  mac_top_cleanup ();\n#endif\n\n  // stop OMG\n  stop_mobility_generator (omg_param_list); //omg_param_list.mobility_type\n#ifdef OPENAIR2\n\n  if (oai_emulation.info.omv_enabled == 1)\n    omv_end (pfd[1], omv_data);\n\n#endif\n\n  if ((oai_emulation.info.ocm_enabled == 1) && (ethernet_flag == 0)\n      && (ShaF != NULL)) {\n    destroyMat (ShaF, map1, map2);\n    ShaF = 0;\n  }\n\n  if (opt_enabled == 1)\n    terminate_opt ();\n\n  if (oai_emulation.info.cli_enabled)\n    cli_server_cleanup ();\n\n  for (int i = 0; i < NUMBER_OF_eNB_MAX + NUMBER_OF_UE_MAX; i++)\n    if (oai_emulation.info.oai_ifup[i] == 1) {\n      char interfaceName[8];\n      snprintf (interfaceName, sizeof(interfaceName), \"oai%d\", i);\n      bringInterfaceUp (interfaceName, 0);\n    }\n\n  log_thread_finalize ();\n  logClean ();\n  VCD_SIGNAL_DUMPER_CLOSE ();\n\n  done = 1; // prevent next invokation of this function\n\n  LOG_N(EMU,\n        \">>>>>>>>>>>>>>>>>>>>>>>>>>> OAIEMU shutdown <<<<<<<<<<<<<<<<<<<<<<<<<<\\n\\n\");\n}\n\neNB_MAC_INST*\nget_eNB_mac_inst (module_id_t module_idP)\n{\n  return (&eNB_mac_inst[module_idP]);\n}\n\nOAI_Emulation*\nget_OAI_emulation ()\n{\n  return &oai_emulation;\n}\n\n\n", "meta": {"hexsha": "5cb2289b37d91727fbb2e162d7bd740d08d74fbf", "size": 69286, "ext": "c", "lang": "C", "max_stars_repo_path": "targets/SIMU/USER/oaisim.c", "max_stars_repo_name": "kashyab12/flexran-agent", "max_stars_repo_head_hexsha": "acd54a34e1840e4c7f295b134f8f2117b1899e83", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-05T16:22:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-05T16:22:05.000Z", "max_issues_repo_path": "targets/SIMU/USER/oaisim.c", "max_issues_repo_name": "kashyab12/flexran-agent", "max_issues_repo_head_hexsha": "acd54a34e1840e4c7f295b134f8f2117b1899e83", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "targets/SIMU/USER/oaisim.c", "max_forks_repo_name": "kashyab12/flexran-agent", "max_forks_repo_head_hexsha": "acd54a34e1840e4c7f295b134f8f2117b1899e83", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-02-14T16:06:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-05T03:52:29.000Z", "avg_line_length": 34.9752650177, "max_line_length": 471, "alphanum_fraction": 0.6499870104, "num_tokens": 21290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21469142916152645, "lm_q2_score": 0.03258974781971667, "lm_q1q2_score": 0.006996739535428713}}
{"text": "#ifndef PETSC4PY_COMPAT_H\n#define PETSC4PY_COMPAT_H\n\n#include <petsc.h>\n#include \"compat/mpi.h\"\n#include \"compat/hdf5.h\"\n#include \"compat/mumps.h\"\n#include \"compat/hypre.h\"\n#include \"compat/tao.h\"\n\n#endif/*PETSC4PY_COMPAT_H*/\n", "meta": {"hexsha": "d2113763e06f83b7c85386b2b79eca4ec08c07db", "size": 226, "ext": "h", "lang": "C", "max_stars_repo_path": "src/include/compat.h", "max_stars_repo_name": "underworldcode/petsc4py", "max_stars_repo_head_hexsha": "fdfdd79be39b8cbe95cf57010f29a6cb2ef463a6", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/include/compat.h", "max_issues_repo_name": "underworldcode/petsc4py", "max_issues_repo_head_hexsha": "fdfdd79be39b8cbe95cf57010f29a6cb2ef463a6", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/include/compat.h", "max_forks_repo_name": "underworldcode/petsc4py", "max_forks_repo_head_hexsha": "fdfdd79be39b8cbe95cf57010f29a6cb2ef463a6", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.8333333333, "max_line_length": 27, "alphanum_fraction": 0.7566371681, "num_tokens": 69, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.17553805637093017, "lm_q2_score": 0.039638839242782886, "lm_q1q2_score": 0.006958124797477861}}
{"text": "// Author: David Blei (blei@cs.princeton.edu)\n//\n// Copyright 2006 David Blei\n// All Rights Reserved.\n//\n// See the README for this package for details about modifying or\n// distributing this software.\n\n#ifndef PARAMSH\n#define PARAMSH\n\n#define MAX_LINE_LENGTH 100000;\n\n#include \"gsl-wrappers.h\"\n#include <stdlib.h>\n#include <stdio.h>\n#include <gsl/gsl_vector.h>\n#include <string.h>\n\nvoid params_read_string(FILE* f, char* name, char* x);\n\nvoid params_read_int(FILE* f, char* name, int* x);\n\nvoid params_write_int(FILE *, char *, int);\n\nvoid params_read_double(FILE* f, char* name, double* x);\n\nvoid params_write_double(FILE *, char *, double);\n\nvoid params_read_gsl_vector(FILE* f, char* name, gsl_vector** x);\n\nvoid params_write_gsl_vector(FILE *, char* , gsl_vector *);\n\nvoid params_write_gsl_vector_multiline(FILE *, char* , gsl_vector *);\n\nvoid params_write_gsl_matrix(FILE *, char* , gsl_matrix *);\n\nvoid params_write_sparse_gsl_matrix(FILE *, char* , gsl_matrix *);\n\n#endif\n", "meta": {"hexsha": "c78d8fef156a6526663948cfeab7d6477520c48d", "size": 980, "ext": "h", "lang": "C", "max_stars_repo_path": "scripts/lib/DTM/dtm/params.h", "max_stars_repo_name": "iwangjian/dtm-lab", "max_stars_repo_head_hexsha": "07c936c07d268208dcc2f19e07fb8d2a18e39ba8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2018-07-12T11:05:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-22T08:34:34.000Z", "max_issues_repo_path": "scripts/lib/DTM/dtm/params.h", "max_issues_repo_name": "iwangjian/topic-extractor", "max_issues_repo_head_hexsha": "07c936c07d268208dcc2f19e07fb8d2a18e39ba8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/lib/DTM/dtm/params.h", "max_forks_repo_name": "iwangjian/topic-extractor", "max_forks_repo_head_hexsha": "07c936c07d268208dcc2f19e07fb8d2a18e39ba8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-03-15T04:11:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-10T09:29:17.000Z", "avg_line_length": 23.9024390244, "max_line_length": 69, "alphanum_fraction": 0.7346938776, "num_tokens": 246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30735801686526387, "lm_q2_score": 0.02262920180448016, "lm_q1q2_score": 0.006955266589868873}}
{"text": "/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*\n**                                                                                  **\n** This file forms part of the Underworld geophysics modelling application.         **\n**                                                                                  **\n** For full license and copyright information, please refer to the LICENSE.md file  **\n** located at the project root, or contact the authors.                             **\n**                                                                                  **\n**~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/\n#ifndef _writeMat_h\n#define _writeMat_h\n#include <petsc.h>\n#include <petscmat.h>\n#include <petscvec.h>\n\nvoid bsscr_writeMat(Mat A, char name[], char message[]);\nvoid bsscr_writeVec(Vec V, char name[], char message[]);\n#endif\n", "meta": {"hexsha": "c6d25abbaa9f13ac37ca31b3777fe4a6a01792d4", "size": 922, "ext": "h", "lang": "C", "max_stars_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/writeMatVec.h", "max_stars_repo_name": "longgangfan/underworld2", "max_stars_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 116.0, "max_stars_repo_stars_event_min_datetime": "2015-09-28T10:30:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T04:12:38.000Z", "max_issues_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/writeMatVec.h", "max_issues_repo_name": "longgangfan/underworld2", "max_issues_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 561.0, "max_issues_repo_issues_event_min_datetime": "2015-09-29T06:05:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T23:37:29.000Z", "max_forks_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/writeMatVec.h", "max_forks_repo_name": "longgangfan/underworld2", "max_forks_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 68.0, "max_forks_repo_forks_event_min_datetime": "2015-12-14T21:57:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-25T04:54:26.000Z", "avg_line_length": 51.2222222222, "max_line_length": 87, "alphanum_fraction": 0.3644251627, "num_tokens": 291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.29746995506106744, "lm_q2_score": 0.023330769063138846, "lm_q1q2_score": 0.006940202824752055}}
{"text": "/* usleep, inet_aton */\n#define _GNU_SOURCE\n\n#include <stdio.h>\n#include <time.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n#include <pthread.h>\n#include <fcntl.h>\n#include <assert.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <arpa/inet.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_blas.h>\n#include \"agent.h\"\n\n/*\n * Grafo con 6 nodi -> dmax = 5\n * devo prendere una frequenza  fs > 2*dmax/pi\n * e quindi una ts < pi/(2*dmax) = 0.314 sec\n * prendiamo h di runge kutta = ts\n */\n\nint _agents_number = 6;\n\nfloat h = 0.05;\n\nint N = 32768;\n\ndouble x0[6] = {0.00, 0.00, 0.00, 0.00, 0.00, 0.00};\n\ndouble z0[6] = {1.00, 0.00, 0.00, 0.00, 0.00, 0.00};\n\ntypedef enum {\n    log_debug = 1,\n    log_normal = 2,\n    log_details = 4\n} log_t;\n\nint log_level = log_normal;\n\n/*int log_level = log_debug | log_normal | log_details;*/\n\nstruct msg_t {\n    int msg_id;\n    int msg_time;\n    float msg_x;\n    float msg_z;\n};\n\nstruct agent_t {\n    int agent_id;\n    int agent_x;\n    int agent_z;\n    pthread_mutex_t agent_mutex;\n};\n\ntypedef struct msg_t *msg;\n\nstatic pthread_mutex_t agent_class_mutex;\nstatic int agentObjectsNumber = 0;\n\nstatic void initClassAgent() {\n    pthread_mutex_init(&(agent_class_mutex), NULL);\n}\n\nstatic void cleanClassAgent() {\n    pthread_mutex_destroy(&(agent_class_mutex));\n\n}\n\nagent allocAgent() {\n\n    agent agent_M_;\n\n    if (agentObjectsNumber == 0) initClassAgent();\n\n    agentObjectsNumber++;\n\n    agent_M_ = (agent) malloc(sizeof (struct agent_t));\n\n    agent_M_->agent_id = 0;\n    pthread_mutex_init(&(agent_M_->agent_mutex), NULL);\n\n    return agent_M_;\n\n}\n\nvoid freeAgent(agent _F_agent) {\n\n    pthread_mutex_destroy(&(_F_agent->agent_mutex));\n\n    free(_F_agent);\n\n    _F_agent = NULL;\n\n    agentObjectsNumber--;\n\n    if (agentObjectsNumber == 0) cleanClassAgent();\n}\n\nvoid setIdAgent(agent agent_p) {\n    agent_p = NULL;\n}\n\nvoid getIdAgent(agent agent_p) {\n    agent_p = NULL;\n}\n\nvoid setAgentState(agent agent_p) {\n    agent_p = NULL;\n}\n\nvoid getAgentState(agent agent_p) {\n    agent_p = NULL;\n}\n\nstatic int connectTo(char *_ip_address_remote, int _ip_port_remote) {\n\n    int socket_M_;\n\n    struct sockaddr_in sockaddr_in_remote_;\n\n    memset(&sockaddr_in_remote_, 0, sizeof (sockaddr_in_remote_));\n    sockaddr_in_remote_.sin_family = AF_INET;\n    sockaddr_in_remote_.sin_port = htons(_ip_port_remote);\n    inet_aton(_ip_address_remote, &(sockaddr_in_remote_.sin_addr));\n\n    if ((socket_M_ = socket(AF_INET, SOCK_STREAM, 0)) == -1) {\n        perror(\"connectTo: socket() Error\\n\");\n        exit(1);\n    }\n\n    while (connect(socket_M_, (struct sockaddr *) & sockaddr_in_remote_, sizeof (struct sockaddr_in)) == -1) {\n        perror(\"connectTo: connect() Error\\n\");\n        exit(1);\n    }\n\n    return socket_M_;\n}\n\nstatic void sendMsg(int _socket, msg _msg) {\n\n    if (send(_socket, _msg, sizeof (struct msg_t), 0) == -1) {\n        perror(\"sendMsg: send() Error\\n\");\n        exit(1);\n    };\n}\n\nstatic msg recvMsg(int _socket) {\n\n    msg _M_msg = (struct msg_t *) malloc(sizeof (struct msg_t));\n\n    if (recv(_socket, _M_msg, sizeof (struct msg_t), 0) == -1) {\n        perror(\"recvMsg: recv() Error\\n\");\n        exit(1);\n    }\n\n    return _M_msg;\n}\n\nparametri_agent allocParamAgent(int _identity, char *_agent_router_ip, int _port_agent_to_router, int _port_router_to_agent) {\n\n    parametri_agent _M_parametri_agent = (parametri_agent) malloc(sizeof (struct parametri_agent_t));\n\n    _M_parametri_agent->identity = _identity;\n    _M_parametri_agent->agent_router_ip = _agent_router_ip;\n    _M_parametri_agent->port_router_to_agent = _port_router_to_agent;\n    _M_parametri_agent->port_agent_to_router = _port_agent_to_router;\n\n    return _M_parametri_agent;\n}\n\nvoid *runAgent(void *_parametri_agent) {\n\n    parametri_agent _parametri = (parametri_agent) _parametri_agent;\n\n    int _identity = _parametri->identity;\n\n    char *_agent_router_ip;\n    int _port_router_to_agent;\n    int _port_agent_to_router;\n\n    int agent_to_router_socket_;\n    int router_to_agent_socket_;\n\n    int _agent_neighborhood;\n\n    int i, c;\n\n    msg _M_msg_in, _M_msg_out;\n\n    double x[4] = {0.00, 0.00, 0.00, 0.00};\n    double z[4] = {0.00, 0.00, 0.00, 0.00};\n    double r[4] = {0.00, 0.00, 0.00, 0.00};\n    double sx[4] = {0.00, 0.00, 0.00, 0.00};\n    double sz[4] = {0.00, 0.00, 0.00, 0.00};\n\n    FILE *agent_log;\n    char agent_log_file_name[FILENAME_MAX];\n\n    gsl_matrix *_adjacency_matrix;\n    FILE *agent_adjacency_matrix_file;\n\n    _adjacency_matrix = gsl_matrix_alloc(_agents_number, _agents_number);\n    agent_adjacency_matrix_file = fopen(\"adjacency_matrix.txt\", \"r\");\n    gsl_matrix_fscanf(agent_adjacency_matrix_file, _adjacency_matrix);\n    fclose(agent_adjacency_matrix_file);\n\n    /*\n     * Apertura del file di log\n     */\n\n    sprintf(agent_log_file_name, \"agent_%d.log\", _identity);\n\n    agent_log = fopen(agent_log_file_name, \"w\");\n\n    if (agent_log == NULL) {\n        perror(\"Errore apertura file: \\\"agent.log\\\"\\n\");\n        exit(1);\n    };\n\n    setbuf(agent_log, NULL);\n\n    if (log_level & log_debug) fprintf(agent_log, \"A%d: Open log\\n\", _identity);\n\n    if (log_level & log_debug) fprintf(agent_log, \"A%d: Parametri di invocazione:\\n\", _identity);\n\n    if (log_level & log_debug) fprintf(agent_log, \"A%d: > _identity = %d\\n\", _identity, _identity);\n\n    _agent_router_ip = _parametri->agent_router_ip;\n\n    if (log_level & log_debug) fprintf(agent_log, \"A%d: > _agent_router_ip = %s\\n\", _identity, _agent_router_ip);\n\n    _port_agent_to_router = _parametri->port_agent_to_router;\n\n    if (log_level & log_debug) fprintf(agent_log, \"A%d: > _port_agent_to_router = %d\\n\", _identity, _port_agent_to_router);\n\n    _port_router_to_agent = _parametri->port_router_to_agent;\n\n    if (log_level & log_debug) fprintf(agent_log, \"A%d: > _port_router_to_agent = %d\\n\", _identity, _port_router_to_agent);\n\n    if (log_level & log_debug) fprintf(agent_log, \"A%d: Memoria:\\n\", _identity);\n\n    if (log_level & log_debug) fprintf(agent_log, \"A%d: > h = %2.8g\\n\", _identity, h);\n\n    /*\n     * Calcolo del numero di agent vicini attraverso l'analisi della adjacency_matrix\n     */\n\n    _agent_neighborhood = 0;\n\n    for (i = 0; i < _agents_number; i++) {\n\n        _agent_neighborhood = _agent_neighborhood + (int) gsl_matrix_get(_adjacency_matrix, i, _identity - 1);\n\n        if (log_level & log_debug) fprintf(agent_log, \"A%d: > gsl_matrix_get(%d,%d) = %d\\n\", _identity, i, _identity - 1, (int) gsl_matrix_get(_adjacency_matrix, i, _identity - 1));\n    };\n\n    if (log_level & log_debug) fprintf(agent_log, \"A%d: > _agent_neighborhood = %d\\n\", _identity, _agent_neighborhood);\n\n    if (log_level & log_debug) fprintf(agent_log, \"A%d: > _agents_number = %d\\n\", _identity, _agents_number);\n\n    _M_msg_out = (struct msg_t *) malloc(sizeof (struct msg_t));\n\n    if (log_level & log_debug) fprintf(agent_log, \"A%d: > alloc(msg_out)\\n\", _identity);\n\n    if (log_level & log_debug) fprintf(agent_log, \"A%d: Socket:\\n\", _identity);\n\n    agent_to_router_socket_ = connectTo(_agent_router_ip, _port_agent_to_router);\n\n    if (log_level & log_debug) fprintf(agent_log, \"A%d: > connectTo(%s,%d)\\n\", _identity, _agent_router_ip, _port_agent_to_router);\n\n    router_to_agent_socket_ = connectTo(_agent_router_ip, _port_router_to_agent);\n\n    if (log_level & log_debug) fprintf(agent_log, \"A%d: > connectTo(%s,%d)\\n\", _identity, _agent_router_ip, _port_router_to_agent);\n\n    if (log_level & log_debug) fprintf(agent_log, \"A%d: Signal:\\n\", _identity);\n\n    /*\n     * Imposto l'identit\u00e0 dei messaggi in output\n     */\n\n    _M_msg_out->msg_id = _identity;\n\n    /*\n     * Imposto il timer interno\n     */\n\n    _M_msg_out->msg_time = 0;\n\n    /*\n     * Invio di un messaggio contenente la propria identit\u00e0 sui due canali di in/out\n     */\n\n    _M_msg_out->msg_x = 0.00;\n    _M_msg_out->msg_z = 0.00;\n\n    sendMsg(router_to_agent_socket_, _M_msg_out);\n\n    if (log_level & log_debug) fprintf(agent_log, \"A%d: > snd (%d,%d,%2.8g,%2.8g) > %d\\n\", _identity, _M_msg_out->msg_id, _M_msg_out->msg_time, _M_msg_out->msg_x, _M_msg_out->msg_z, _port_router_to_agent);\n\n    sendMsg(agent_to_router_socket_, _M_msg_out);\n\n    if (log_level & log_debug) fprintf(agent_log, \"A%d: > snd (%d,%d,%2.8g,%2.8g) > %d\\n\", _identity, _M_msg_out->msg_id, _M_msg_out->msg_time, _M_msg_out->msg_x, _M_msg_out->msg_z, _port_agent_to_router);\n\n\n    /*\n     * Ciclo principale\n     */\n\n    if (log_level & log_debug) fprintf(agent_log, \"A%d: Loop:\\n\", _identity);\n\n    if (log_level & log_debug) fprintf(agent_log, \"A%d: > for i=[0,%d]\\n\", _identity, N);\n\n    if (log_level & log_debug) fprintf(agent_log, \"A%d: ----- Loop Start -----\\n\", _identity);\n\n    x[0] = x0[_identity - 1];\n    z[0] = z0[_identity - 1];\n\n    for (c = 0; c < N; c++) {\n\n        if (log_level & log_debug) fprintf(agent_log, \"A%d: > i = %d\\n\", _identity, c);\n\n        /*\n         * snd x\n         */\n\n        _M_msg_out->msg_time = 0;\n        _M_msg_out->msg_x = x[0];\n        _M_msg_out->msg_z = z[0];\n        sendMsg(agent_to_router_socket_, _M_msg_out);\n        if (log_level & log_normal) fprintf(agent_log, \"%2.8g %2.8g\\n\", _M_msg_out->msg_x, _M_msg_out->msg_z);\n        if (log_level & log_details) fprintf(agent_log, \"A%d: > snd (%d,%d,%2.8g,%2.8g)\\n\", _identity, _M_msg_out->msg_id, _M_msg_out->msg_time, _M_msg_out->msg_x, _M_msg_out->msg_z);\n\n        /*\n         * k1\n         */\n\n        while (r[0] < _agent_neighborhood) {\n            _M_msg_in = recvMsg(router_to_agent_socket_);\n            if (log_level & log_details) fprintf(agent_log, \"A%d: > rcv (%d,%d,%2.8g,%2.8g)\\n\", _identity, _M_msg_in->msg_id, _M_msg_out->msg_time, _M_msg_in->msg_x, _M_msg_in->msg_z);\n            sx[_M_msg_in->msg_time] = sx[_M_msg_in->msg_time] + _M_msg_in->msg_x;\n            sz[_M_msg_in->msg_time] = sz[_M_msg_in->msg_time] + _M_msg_in->msg_z;\n            r[_M_msg_in->msg_time]++;\n        }\n\n\n        x[1] = r[0] * z[0] - sz[0];\n        z[1] = sx[0] - r[0] * x[0];\n        sx[0] = 0;\n        sz[0] = 0;\n        r[0] = 0;\n\n        _M_msg_out->msg_time = 1;\n        _M_msg_out->msg_x = x[1];\n        _M_msg_out->msg_z = z[1];\n        sendMsg(agent_to_router_socket_, _M_msg_out);\n        if (log_level & log_details) fprintf(agent_log, \"A%d: > snd (%d,%d,%2.8g,%2.8g)\\n\", _identity, _M_msg_out->msg_id, _M_msg_out->msg_time, _M_msg_out->msg_x, _M_msg_out->msg_z);\n\n        /*\n         * k2\n         */\n\n        while (r[1] < _agent_neighborhood) {\n            _M_msg_in = recvMsg(router_to_agent_socket_);\n            if (log_level & log_details) fprintf(agent_log, \"A%d: > rcv (%d,%d,%2.8g,%2.8g)\\n\", _identity, _M_msg_in->msg_id, _M_msg_out->msg_time, _M_msg_in->msg_x, _M_msg_in->msg_z);\n            sx[_M_msg_in->msg_time] = sx[_M_msg_in->msg_time] + _M_msg_in->msg_x;\n            sz[_M_msg_in->msg_time] = sz[_M_msg_in->msg_time] + _M_msg_in->msg_z;\n            r[_M_msg_in->msg_time]++;\n        }\n\n        x[2] = x[1] + h * (r[1] * z[1] - sz[1]) / 2;\n        z[2] = z[1] + h * (sx[1] - r[1] * x[1]) / 2;\n        sx[1] = 0;\n        sz[1] = 0;\n        r[1] = 0;\n\n        _M_msg_out->msg_time = 2;\n        _M_msg_out->msg_x = x[2];\n        _M_msg_out->msg_z = z[2];\n        sendMsg(agent_to_router_socket_, _M_msg_out);\n        if (log_level & log_details) fprintf(agent_log, \"A%d: > snd (%d,%d,%2.8g,%2.8g)\\n\", _identity, _M_msg_out->msg_id, _M_msg_out->msg_time, _M_msg_out->msg_x, _M_msg_out->msg_z);\n\n        /*\n         * k3\n         */\n\n        while (r[2] < _agent_neighborhood) {\n            _M_msg_in = recvMsg(router_to_agent_socket_);\n            if (log_level & log_details) fprintf(agent_log, \"A%d: > rcv (%d,%d,%2.8g,%2.8g)\\n\", _identity, _M_msg_in->msg_id, _M_msg_out->msg_time, _M_msg_in->msg_x, _M_msg_in->msg_z);\n            sx[_M_msg_in->msg_time] = sx[_M_msg_in->msg_time] + _M_msg_in->msg_x;\n            sz[_M_msg_in->msg_time] = sz[_M_msg_in->msg_time] + _M_msg_in->msg_z;\n            r[_M_msg_in->msg_time]++;\n        }\n\n        x[3] = x[1] + h * (r[2] * z[2] - sz[2]) / 2;\n        z[3] = z[1] + h * (sx[2] - r[2] * x[2]) / 2;\n        sx[2] = 0;\n        sz[2] = 0;\n        r[2] = 0;\n\n        _M_msg_out->msg_time = 3;\n        _M_msg_out->msg_x = x[3];\n        _M_msg_out->msg_z = z[3];\n        sendMsg(agent_to_router_socket_, _M_msg_out);\n        if (log_level & log_details) fprintf(agent_log, \"A%d: > snd (%d,%d,%2.8g,%2.8g)\\n\", _identity, _M_msg_out->msg_id, _M_msg_out->msg_time, _M_msg_out->msg_x, _M_msg_out->msg_z);\n\n        /*\n         * k4, x\n         */\n\n        while (r[3] < _agent_neighborhood) {\n            _M_msg_in = recvMsg(router_to_agent_socket_);\n            if (log_level & log_details) fprintf(agent_log, \"A%d: > rcv (%d,%d,%2.8g,%2.8g)\\n\", _identity, _M_msg_in->msg_id, _M_msg_out->msg_time, _M_msg_in->msg_x, _M_msg_in->msg_z);\n            sx[_M_msg_in->msg_time] = sx[_M_msg_in->msg_time] + _M_msg_in->msg_x;\n            sz[_M_msg_in->msg_time] = sz[_M_msg_in->msg_time] + _M_msg_in->msg_z;\n            r[_M_msg_in->msg_time]++;\n        }\n\n        x[0] = x[0] + h * (x[1] + x[2] + x[3] + h * (r[3] * z[3] - sz[3]) / 2) / 3;\n        z[0] = z[0] + h * (z[1] + z[2] + z[3] + h * (sx[3] - r[3] * x[3]) / 2) / 3;\n        sx[3] = 0;\n        sz[3] = 0;\n        r[3] = 0;\n\n    }\n\n    if (log_level & log_debug) fprintf(agent_log, \"A%d: ----- Loop End ------\\n\", _identity);\n\n    if (log_level & log_debug) fprintf(agent_log, \"A%d: Signal:\\n\", _identity);\n\n    /*\n     * Invio del killer message\n     */\n\n    _M_msg_out->msg_id = -1;\n    _M_msg_out->msg_x = 0;\n    _M_msg_out->msg_z = 0;\n\n    sendMsg(agent_to_router_socket_, _M_msg_out);\n\n    if (log_level & log_debug) fprintf(agent_log, \"A%d: > snd (%d,%d,%2.8g,%2.8g) > %d\\n\", _identity, _M_msg_out->msg_id, _M_msg_out->msg_time, _M_msg_out->msg_x, _M_msg_out->msg_z, _port_agent_to_router);\n\n    if (log_level & log_debug) fprintf(agent_log, \"A%d: Socket:\\n\", _identity);\n\n    /*\n     * Chiusura delle sockets\n     */\n\n    close(router_to_agent_socket_);\n\n    if (log_level & log_debug) fprintf(agent_log, \"A%d: > close(%d)\\n\", _identity, _port_router_to_agent);\n\n    close(agent_to_router_socket_);\n\n    if (log_level & log_debug) fprintf(agent_log, \"A%d: > close(%d)\\n\", _identity, _port_agent_to_router);\n\n    if (log_level & log_debug) fprintf(agent_log, \"A%d: Memoria:\\n\", _identity);\n\n    /*\n     * Free delle variabili usate\n     */\n\n    free(_M_msg_out);\n\n    if (log_level & log_debug) fprintf(agent_log, \"A%d: > free(msg_out)\\n\", _identity);\n\n    free(_parametri_agent);\n\n    if (log_level & log_debug) fprintf(agent_log, \"A%d: > parametri\\n\", _identity);\n\n    /*\n     * fflush e chiusura del logfile\n     */\n\n    if (log_level & log_debug) fprintf(agent_log, \"A%d: Close log\\n\", _identity);\n\n    fflush(agent_log);\n\n    fclose(agent_log);\n\n    return NULL;\n}\n", "meta": {"hexsha": "cd307fc7e4a06419fa2c7be2d50231e73d73e10b", "size": 14792, "ext": "c", "lang": "C", "max_stars_repo_path": "agent.c", "max_stars_repo_name": "vittorioc/VirtualAgent", "max_stars_repo_head_hexsha": "0455a86a79ef2c5a817b9a1ec26d9025703d22ab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-01-29T01:05:11.000Z", "max_stars_repo_stars_event_max_datetime": "2017-01-29T01:05:11.000Z", "max_issues_repo_path": "agent.c", "max_issues_repo_name": "vittorioc/VirtualAgent", "max_issues_repo_head_hexsha": "0455a86a79ef2c5a817b9a1ec26d9025703d22ab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "agent.c", "max_forks_repo_name": "vittorioc/VirtualAgent", "max_forks_repo_head_hexsha": "0455a86a79ef2c5a817b9a1ec26d9025703d22ab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2494887526, "max_line_length": 205, "alphanum_fraction": 0.6313547864, "num_tokens": 4762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3451052574867685, "lm_q2_score": 0.020023439535066828, "lm_q1q2_score": 0.006910194256519978}}
{"text": "#ifndef basis_dcab07d2_8e6a_4150_b6fb_1eb09f015f76_h\r\n#define basis_dcab07d2_8e6a_4150_b6fb_1eb09f015f76_h\r\n\r\n#include <gslib\\error.h>\r\n//#include <gslib\\string.h>\r\n#include <gslib\\std.h>\r\n#include <rathen\\config.h>\r\n#include <rathen\\buildin.h>\r\n\r\n__rathen_begin__\r\n\r\nclass __gs_novtable type abstract\r\n{\r\npublic:\r\n    virtual ~type() {}\r\n    virtual const gchar* get_name() const = 0;\r\n    virtual int get_size() const = 0;\r\n    virtual type* get_oprret(const oprinfo& opr) = 0;\r\n    /*\r\n     * Commutative attribute, if an operator was commutative, then a series of transformation could be done\r\n     * in the expression optimization, for example,\r\n     * it would always prefer to put the variables to the left side of the operator, and the constants to the\r\n     * right side, so that we could generate the code try to put the constants within the instructions.\r\n     */\r\n    virtual bool is_comutative(const oprinfo& opr) const\r\n    {\r\n        if (opr.opr == _t(\"=\"))\r\n            return false;\r\n        return true;\r\n    }\r\n    /* Complex attribute, a complex type always has a construction/destruction operation. */\r\n    virtual bool is_complex() const { return false; }\r\n};\r\n\r\nclass __gs_novtable com_type abstract:\r\n    public type\r\n{\r\npublic:\r\n    virtual bool is_complex() const { return true; }\r\n};\r\n\r\nclass type_manager\r\n{\r\npublic:\r\n    typedef std::pair<string, type*> type_pair;\r\n    typedef unordered_map<string, type*> type_map;\r\n    typedef type_map::iterator iterator;\r\n    typedef type_map::const_iterator const_iterator;\r\n\r\npublic:\r\n    static type_manager* get_singleton_ptr()\r\n    {\r\n        static type_manager inst;\r\n        return &inst;\r\n    }\r\n    ~type_manager()\r\n    {\r\n        std::for_each(_tpmap.begin(), _tpmap.end(), [](const type_pair& tp) { delete tp.second; });\r\n        _tpmap.clear();\r\n    }\r\n    type* find_type(const gchar* name) { return find_type(string(name)); }\r\n    type* find_type(const gchar* name, int len) { return find_type(string(name, len)); }\r\n    type* find_type(const string& name)\r\n    {\r\n        auto i = _tpmap.find(name);\r\n        return i == _tpmap.end() ? 0 : i->second;\r\n    }\r\n\r\nprivate:\r\n    type_map    _tpmap;\r\n\r\npublic:\r\n    template<class _cst>\r\n    bool regtype()\r\n    {\r\n        type* t = gs_new(_cst);\r\n        if(!_reginner(t)) { gs_del(type, t); return false; }\r\n        return true;\r\n    }\r\n\r\nprivate:\r\n    type_manager();\r\n    bool _reginner(type* t)\r\n    {\r\n        assert(t);\r\n        if(find_type(t->get_name()))\r\n            return false;\r\n        _tpmap.insert(std::make_pair(string(t->get_name()), t));\r\n        return true;\r\n    }\r\n};\r\n\r\n#define _type_manager type_manager::get_singleton_ptr()\r\n\r\nclass int_type:\r\n    public type\r\n{\r\npublic:\r\n    virtual const gchar* get_name() const { return _t(\"int\"); }\r\n    virtual int get_size() const { return 4; }\r\n    virtual type* get_oprret(const oprinfo& opr) { return this; }   // TODO\r\n};\r\n\r\nclass bool_type:\r\n    public type\r\n{\r\npublic:\r\n    virtual const gchar* get_name() const { return _t(\"bool\"); }\r\n    virtual int get_size() const { return 4; }\r\n    virtual type* get_oprret(const oprinfo& opr) { return this; }   // TODO\r\n};\r\n\r\nclass void_type:\r\n    public type\r\n{\r\npublic:\r\n    virtual const gchar* get_name() const { return _t(\"void\"); }\r\n    virtual int get_size() const { return 0; }\r\n    virtual type* get_oprret(const oprinfo& opr) { return 0; }\r\n};\r\n\r\nclass string_type:\r\n    public com_type\r\n{\r\npublic:\r\n    virtual const gchar* get_name() const { return _t(\"string\"); }\r\n    virtual int get_size() const { return (int)sizeof(gs::string); }\r\n    virtual type* get_oprret(const oprinfo& opr) { return this; }   // TODO\r\n};\r\n\r\nclass __gs_novtable object abstract\r\n{\r\npublic:\r\n    enum\r\n    {\r\n        tag_data,\r\n        tag_const,\r\n        tag_block,\r\n        tag_node,\r\n        tag_scope,\r\n        //tag_\r\n        //...\r\n    };\r\n\r\nprotected:\r\n    string      _name;\r\n\r\npublic:\r\n    object() {}\r\n    virtual ~object() {}\r\n    virtual void set_name(const gchar* name) { _name = name; }\r\n    virtual uint get_tag() const = 0;\r\n    virtual bool is_holder() const = 0;\r\n    virtual const string& get_name() const { return _name; }\r\n};\r\n\r\nstruct unikey\r\n{\r\npublic:\r\n    typedef gchar* vckey;\r\n    typedef const gchar* cckey;\r\n\r\nprotected:\r\n    cckey       _key;\r\n\r\npublic:\r\n    unikey(): _key(0) {}\r\n    unikey(const gchar* k): _key(k) {}\r\n    unikey(const string& k): _key(k.c_str()) {}\r\n    unikey(const object* obj): _key(obj->get_name().c_str()) {}\r\n    const gchar* get_key() const { return _key; }\r\n};\r\n\r\nstruct indexing\r\n{\r\npublic:\r\n    struct hash\r\n    {\r\n        size_t operator()(const unikey& k) const\r\n        { return string_hash(k.get_key()); }\r\n    };\r\n    struct equal\r\n    {\r\n        bool operator()(const unikey& k1, const unikey& k2) const\r\n        { return string_hash(k1.get_key()) == string_hash(k2.get_key()); }\r\n    };\r\n    typedef unordered_map<unikey, object*, hash, equal> unimap;\r\n    typedef unimap::iterator iterator;\r\n    typedef unimap::const_iterator const_iterator;\r\n\r\nprotected:\r\n    unimap      _pairs;\r\n\r\npublic:\r\n    indexing() {}\r\n    ~indexing() {}\r\n    bool add_value(object* ptr)\r\n    {\r\n        assert(ptr);\r\n        if(_pairs.insert(std::make_pair(unikey(ptr), ptr)).second) {\r\n            set_error(_t(\"udt insert dp failed, maybe an error in name mangling.\"));\r\n            return false;\r\n        }\r\n        return true;\r\n    }\r\n    object* find_value(const gchar* name)\r\n    {\r\n        assert(name);\r\n        iterator i = _pairs.find(unikey(name));\r\n        return i == _pairs.end() ? 0 :i->second;\r\n    }\r\n    const object* find_value(const gchar* name) const\r\n    {\r\n        assert(name);\r\n        const_iterator i = _pairs.find(unikey(name));\r\n        return i == _pairs.end() ? 0 : i->second;\r\n    }\r\n};\r\n\r\n// class __gnvt pass_object:\r\n//     virtual public object\r\n// {\r\n// public:\r\n//     virtual bool is_holder() const { return false; }\r\n// };\r\n// \r\n// class __gnvt hold_object:\r\n//     virtual public object\r\n// {\r\n// public:\r\n//     virtual bool is_holder() const { return true; }\r\n//     virtual void add_indexing(object* obj) { _indexing.add_value(obj); }\r\n//     virtual indexing& get_indexing() { return _indexing; }\r\n// \r\n// protected:\r\n//     indexing    _indexing;\r\n// \r\n// public:\r\n//     object* find_object(const gchar* name) { return _indexing.find_value(name); }\r\n//     const object* find_object(const gchar* name) const { return _indexing.find_value(name); }\r\n// };\r\n\r\n// class block:\r\n//     public object\r\n// {\r\n// protected:\r\n//     indexing    _indexing;\r\n// \r\n// public:\r\n//     virtual void add_indexing(object* obj) { _indexing.add_value(obj); }\r\n//     virtual indexing& get_indexing() { return _indexing; }\r\n// \r\n// public:\r\n//     object* find_object(const gchar* name) { return _indexing.find_value(name); }\r\n//     const object* find_object(const gchar* name) const { return _indexing.find_value(name); }\r\n// };\r\n// \r\n// class data:\r\n//     public object\r\n// {\r\n// protected:\r\n//     type*       _type;\r\n// \r\n// public:\r\n//     virtual tag get_tag() const { return tag_data; }\r\n//     virtual void set_type(type* t) { _type = t; }\r\n//     virtual type* get_type() const { return _type; }\r\n// };\r\n// \r\n// class reference:\r\n//     public object\r\n// {\r\n// protected:\r\n//     string      _origin;\r\n// \r\n// public:\r\n//     virtual tag get_tag() const { return tag_const; }\r\n//     virtual void set_origin(const gchar* str, int len) { _origin.assign(str, len); }\r\n//     virtual const gchar* get_origin() const { return _origin.c_str(); }\r\n// \r\n// public:\r\n//     void set_origin(const gchar* str) { set_origin(str, strtool::length(str)); }\r\n// };\r\n\r\n__rathen_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "cc998e860bfb91c1dc9adc42c5529815e467f224", "size": 7694, "ext": "h", "lang": "C", "max_stars_repo_path": "include/rathen/basis.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/rathen/basis.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/rathen/basis.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 26.7152777778, "max_line_length": 110, "alphanum_fraction": 0.6018975825, "num_tokens": 1952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15405757822729724, "lm_q2_score": 0.04468086995462597, "lm_q1q2_score": 0.006883426618298484}}
{"text": "//  This matrix class is a C++ wrapper for the GNU Scientific Library\n//  Copyright (C)  ULP-IPB Strasbourg\n\n//  This program is free software; you can redistribute it and/or modify\n//  it under the terms of the GNU General Public License as published by\n//  the Free Software Foundation; either version 2 of the License, or\n//  (at your option) any later version.\n\n//  This program is distributed in the hope that it will be useful,\n//  but WITHOUT ANY WARRANTY; without even the implied warranty of\n//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n//  GNU General Public License for more details.\n\n//  You should have received a copy of the GNU General Public License\n//  along with this program; if not, write to the Free Software\n//  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\n#ifndef _vector_double_h\n#define _vector_double_h\n\n#ifdef __HP_aCC\n#include <iostream.h>\n#else \n#include <iostream>\n#endif\n\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_blas.h>\n#include <gslwrap/vector_double.h>\n\n//#define NDEBUG 0\n\n#include <assert.h>\nnamespace gsl\n{\n\n#ifndef __HP_aCC\n\tusing std::ostream;\n//using std::string;\n//using std::runtime_error;\n#endif\n\nclass vector_view;\n\nclass vector\n{\nprotected:\n\tgsl_vector *gsldata;\n\tvoid free(){if(gsldata) gsl_vector_free(gsldata);gsldata=NULL;}\n\tvoid alloc(size_t n) {gsldata=gsl_vector_alloc(n);}\n\tvoid calloc(size_t n){gsldata=gsl_vector_calloc(n);}\npublic:\n\ttypedef double value_type;\n\tvector() : gsldata(NULL) {;}\n\tvector( const vector &other ):gsldata(NULL) {copy(other);}\n\ttemplate<class oclass>\n\tvector( const oclass &other ):gsldata(NULL) {copy(other);}\n\t~vector(){free();}\n\tvector(const size_t& n,bool clear=true)\n\t{\n\t\tif(clear){this->calloc(n);}\n\t\telse     {this->alloc(n);}\n\t}\n\tvector(const int& n,bool clear=true)\n\t{\n\t\tif(clear){this->calloc(n);}\n\t\telse     {this->alloc(n);}\n\t}\n\t\n\tvoid resize(size_t n);\n\n\ttemplate <class oclass>\n\t\tvoid copy(const oclass &other)\n\t\t{\n\t\t\tif ( static_cast<const void *>( this ) == static_cast<const void *>( &other ) )\n\t\t\t\treturn;\n\n\t\t\tif (!other.is_set())\n\t\t\t{\n\t\t\t\tgsldata=NULL;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tresize(other.size());\n\t\t\tfor (size_t i=0;i<size();i++)\n\t\t\t{\n\t\t\t\tgsl_vector_set(gsldata, i, (double)other[i]);\n\t\t\t}\n\t\t}\n\tvoid copy(const vector& other);\n\tbool is_set() const{if (gsldata) return true; else return false;}\n//\tvoid clone(vector& other);\n\t\n//\tsize_t size() const {if (!gsldata) {cout << \"vector::size vector not initialized\" << endl; exit(-1);}return gsldata->size;}\n\tsize_t size() const {assert (gsldata); return gsldata->size;}\n\n\t/** for interfacing with gsl c */\n/*  \tgsl_vector       *gslobj()       {if (!gsldata){cout << \"vector::gslobj ERROR, data not initialized!! \" << endl; exit(-1);}return gsldata;} */\n/*  \tconst gsl_vector *gslobj() const {if (!gsldata){cout << \"vector::gslobj ERROR, data not initialized!! \" << endl; exit(-1);}return gsldata;} */\n\tgsl_vector       *gslobj()       {assert(gsldata);return gsldata;}\n\tconst gsl_vector *gslobj() const {assert(gsldata);return gsldata;}\n\n\n\tstatic vector_view create_vector_view( const gsl_vector_view &other );\n\n// ********Accessing vector elements\n\n//  Unlike FORTRAN compilers, C compilers do not usually provide support for range checking of vectors and matrices (2). However, the functions gsl_vector_get and gsl_vector_set can perform range checking for you and report an error if you attempt to access elements outside the allowed range. \n\n//  The functions for accessing the elements of a vector or matrix are defined in `gsl_vector.h' and declared extern inline to eliminate function-call overhead. If necessary you can turn off range checking completely without modifying any source files by recompiling your program with the preprocessor definition GSL_RANGE_CHECK_OFF. Provided your compiler supports inline functions the effect of turning off range checking is to replace calls to gsl_vector_get(v,i) by v->data[i*v->stride] and and calls to gsl_vector_set(v,i,x) by v->data[i*v->stride]=x. Thus there should be no performance penalty for using the range checking functions when range checking is turned off. \n\n//      This function returns the i-th element of a vector v. If i lies outside the allowed range of 0 to n-1 then the error handler is invoked and 0 is returned. \n\tdouble get(size_t i) const {return gsl_vector_get(gsldata,i);}\n\n//      This function sets the value of the i-th element of a vector v to x. If i lies outside the allowed range of 0 to n-1 then the error handler is invoked. \n\tvoid  set(size_t i,double x){gsl_vector_set(gsldata,i,x);}\n\n//      These functions return a pointer to the i-th element of a vector v. If i lies outside the allowed range of 0 to n-1 then the error handler is invoked\n\tdouble       &operator[](size_t i)       { return *gsl_vector_ptr(gsldata,i);}\n\tconst double &operator[](size_t i) const { return *gsl_vector_ptr(gsldata,i);}\n\n\tdouble       &operator()(size_t i)       { return *gsl_vector_ptr(gsldata,i);}\n\tconst double &operator()(size_t i) const { return *gsl_vector_ptr(gsldata,i);}\n\n\n//  ***** Initializing vector elements\n\n//      This function sets all the elements of the vector v to the value x. \n\tvoid set_all(double x){gsl_vector_set_all (gsldata,x);}\n//      This function sets all the elements of the vector v to zero. \n\tvoid set_zero(){gsl_vector_set_zero (gsldata);}\n\n//      This function makes a basis vector by setting all the elements of the vector v to zero except for the i-th element which is set to one. \n\tint set_basis (size_t i) {return gsl_vector_set_basis (gsldata,i);}\n\n//  **** Reading and writing vectors\n\n//  The library provides functions for reading and writing vectors to a file as binary data or formatted text. \n\n\n//      This function writes the elements of the vector v to the stream stream in binary format. The return value is 0 for success and GSL_EFAILED if there was a problem writing to the file. Since the data is written in the native binary format it may not be portable between different architectures. \n\tint fwrite (FILE * stream) const {return gsl_vector_fwrite (stream, gsldata);}\n\n//      This function reads into the vector v from the open stream stream in binary format. The vector v must be preallocated with the correct length since the function uses the size of v to determine how many bytes to read. The return value is 0 for success and GSL_EFAILED if there was a problem reading from the file. The data is assumed to have been written in the native binary format on the same architecture. \n\tint fread (FILE * stream) {return gsl_vector_fread (stream, gsldata);}\n\n\tvoid load( const char *filename );\n\t///\n\tvoid save( const char *filename ) const;\n\n//      This function writes the elements of the vector v line-by-line to the stream stream using the format specifier format, which should be one of the %g, %e or %f formats for floating point numbers and %d for integers. The function returns 0 for success and GSL_EFAILED if there was a problem writing to the file. \n\tint fprintf (FILE * stream, const char * format) const {return gsl_vector_fprintf (stream, gsldata,format) ;}\n\n//      This function reads formatted data from the stream stream into the vector v. The vector v must be preallocated with the correct length since the function uses the size of v to determine how many numbers to read. The function returns 0 for success and GSL_EFAILED if there was a problem reading from the file. \n\tint fscanf (FILE * stream)  {return gsl_vector_fscanf (stream, gsldata); }\n\n\n\n\n//  ******* Vector views\n\n//  In addition to creating vectors from slices of blocks it is also possible to slice vectors and create vector views. For example, a subvector of another vector can be described with a view, or two views can be made which provide access to the even and odd elements of a vector. \n\n//  A vector view is a temporary object, stored on the stack, which can be used to operate on a subset of vector elements. Vector views can be defined for both constant and non-constant vectors, using separate types that preserve constness. A vector view has the type gsl_vector_view and a constant vector view has the type gsl_vector_const_view. In both cases the elements of the view can be accessed as a gsl_vector using the vector component of the view object. A pointer to a vector of type gsl_vector * or const gsl_vector * can be obtained by taking the address of this component with the & operator. \n\n//      These functions return a vector view of a subvector of another vector v. The start of the new vector is offset by offset elements from the start of the original\n//      vector. The new vector has n elements. Mathematically, the i-th element of the new vector v' is given by, \n\n//      v'(i) = v->data[(offset + i)*v->stride]\n\n//      where the index i runs from 0 to n-1. \n\n//      The data pointer of the returned vector struct is set to null if the combined parameters (offset,n) overrun the end of the original vector. \n\n//      The new vector is only a view of the block underlying the original vector, v. The block containing the elements of v is not owned by the new vector. When the\n//      new vector goes out of scope the original vector v and its block will continue to exist. The original memory can only be deallocated by freeing the original vector.\n//      Of course, the original vector should not be deallocated while the new vector is still in use. \n\n//      The function gsl_vector_const_subvector is equivalent to gsl_vector_subvector but can be used for vectors which are declared const. \n\tvector_view subvector (size_t offset, size_t n);\n\tconst vector_view subvector (size_t offset, size_t n) const;\n//\tvector_const_view subvector (size_t offset, size_t n) const;\n\n//  \tclass view\n//  \t{\n//  \t\tgsl_vector_view *gsldata;\n//  \tpublic:\n//  \t\tview();\n//  \t};\n//  \tview subvector(size_t offset, size_t n)\n//  \t{\n//  \t\treturn view(gsl_vector_subvector(gsldata,offset,n);\n//  \t}\n//  \tconst view subvector(size_t offset, size_t n) const\n//  \t{\n//  \t\treturn view(gsl_vector_const_subvector(gsldata,offset,n);\n//  \t}\n\n\n\n//  Function: gsl_vector gsl_vector_subvector_with_stride (gsl_vector *v, size_t offset, size_t stride, size_t n) \n//  Function: gsl_vector_const_view gsl_vector_const_subvector_with_stride (const gsl_vector * v, size_t offset, size_t stride, size_t n) \n//      These functions return a vector view of a subvector of another vector v with an additional stride argument. The subvector is formed in the same way as for\n//      gsl_vector_subvector but the new vector has n elements with a step-size of stride from one element to the next in the original vector. Mathematically,\n//      the i-th element of the new vector v' is given by, \n\n//      v'(i) = v->data[(offset + i*stride)*v->stride]\n\n//      where the index i runs from 0 to n-1. \n\n//      Note that subvector views give direct access to the underlying elements of the original vector. For example, the following code will zero the even elements of the\n//      vector v of length n, while leaving the odd elements untouched, \n\n//      gsl_vector_view v_even = gsl_vector_subvector_with_stride (v, 0, 2, n/2);\n//      gsl_vector_set_zero (&v_even.vector);\n\n//      A vector view can be passed to any subroutine which takes a vector argument just as a directly allocated vector would be, using &view.vector. For example, the\n//      following code computes the norm of odd elements of v using the BLAS routine DNRM2, \n\n//      gsl_vector_view v_odd = gsl_vector_subvector_with_stride (v, 1, 2, n/2);\n//      double r = gsl_blas_dnrm2 (&v_odd.vector);\n\n//      The function gsl_vector_const_subvector_with_stride is equivalent to gsl_vector_subvector_with_stride but can be used for\n//      vectors which are declared const. \n\n//  Function: gsl_vector_view gsl_vector_complex_real (gsl_vector_complex *v) \n//  Function: gsl_vector_const_view gsl_vector_complex_const_real (const gsl_vector_complex *v) \n//      These functions return a vector view of the real parts of the complex vector v. \n\n//      The function gsl_vector_complex_const_real is equivalent to gsl_vector_complex_real but can be used for vectors which are declared\n//      const. \n\n//  Function: gsl_vector_view gsl_vector_complex_imag (gsl_vector_complex *v) \n//  Function: gsl_vector_const_view gsl_vector_complex_const_imag (const gsl_vector_complex *v) \n//      These functions return a vector view of the imaginary parts of the complex vector v. \n\n//      The function gsl_vector_complex_const_imag is equivalent to gsl_vector_complex_imag but can be used for vectors which are declared\n//      const. \n\n//  Function: gsl_vector_view gsl_vector_view_array (double *base, size_t n) \n//  Function: gsl_vector_const_view gsl_vector_const_view_array (const double *base, size_t n) \n//      These functions return a vector view of an array. The start of the new vector is given by base and has n elements. Mathematically, the i-th element of the new\n//      vector v' is given by, \n\n//      v'(i) = base[i]\n\n//      where the index i runs from 0 to n-1. \n\n//      The array containing the elements of v is not owned by the new vector view. When the view goes out of scope the original array will continue to exist. The\n//      original memory can only be deallocated by freeing the original pointer base. Of course, the original array should not be deallocated while the view is still in use. \n\n//      The function gsl_vector_const_view_array is equivalent to gsl_vector_view_array but can be used for vectors which are declared const. \n\n//  Function: gsl_vector_view gsl_vector_view_array_with_stride (double * base, size_t stride, size_t n) \n//  Function: gsl_vector_const_view gsl_vector_const_view_array_with_stride (const double * base, size_t stride, size_t n) \n//      These functions return a vector view of an array base with an additional stride argument. The subvector is formed in the same way as for\n//      gsl_vector_view_array but the new vector has n elements with a step-size of stride from one element to the next in the original array. Mathematically,\n//      the i-th element of the new vector v' is given by, \n\n//      v'(i) = base[i*stride]\n\n//      where the index i runs from 0 to n-1. \n\n//      Note that the view gives direct access to the underlying elements of the original array. A vector view can be passed to any subroutine which takes a vector\n//      argument just as a directly allocated vector would be, using &view.vector. \n\n//      The function gsl_vector_const_view_array_with_stride is equivalent to gsl_vector_view_array_with_stride but can be used for\n//      arrays which are declared const. \n\n\n//  ************* Copying vectors\n\n//  Common operations on vectors such as addition and multiplication are available in the BLAS part of the library (see section BLAS Support). However, it is useful to have a small number of utility functions which do not require the full BLAS code. The following functions fall into this category. \n\n//      This function copies the elements of the vector src into the vector dest.\n\tvector& operator=(const vector& other){copy(other);return (*this);}\n\n//  Function: int gsl_vector_swap (gsl_vector * v, gsl_vector * w) \n//      This function exchanges the elements of the vectors v and w by copying. The two vectors must have the same length. \n\n//  ***** Exchanging elements\n\n//  The following function can be used to exchange, or permute, the elements of a vector. \n\n//  Function: int gsl_vector_swap_elements (gsl_vector * v, size_t i, size_t j) \n//      This function exchanges the i-th and j-th elements of the vector v in-place. \n\tint swap_elements (size_t i, size_t j) {return gsl_vector_swap_elements (gsldata, i,j);}\n\n//  Function: int gsl_vector_reverse (gsl_vector * v) \n//      This function reverses the order of the elements of the vector v. \n\tint reverse () {return  gsl_vector_reverse (gsldata) ;}\n\n// ******* Vector operations\n\n//  The following operations are only defined for real vectors. \n\n//      This function adds the elements of vector b to the elements of vector a, a'_i = a_i + b_i. The two vectors must have the same length. \n\tint operator+=(const vector &other) {return gsl_vector_add (gsldata, other.gsldata);}\n\n//      This function subtracts the elements of vector b from the elements of vector a, a'_i = a_i - b_i. The two vectors must have the same length. \n\tint operator-=(const vector &other) {return gsl_vector_sub (gsldata, other.gsldata);}\n\n//  Function: int gsl_vector_mul (gsl_vector * a, const gsl_vector * b) \n//      This function multiplies the elements of vector a by the elements of vector b, a'_i = a_i * b_i. The two vectors must have the same length. \n\tint operator*=(const vector &other) {return gsl_vector_mul (gsldata, other.gsldata);}\n\n//      This function divides the elements of vector a by the elements of vector b, a'_i = a_i / b_i. The two vectors must have the same length. \n\tint operator/=(const vector &other) {return gsl_vector_div (gsldata, other.gsldata);}\n\n//      This function multiplies the elements of vector a by the constant factor x, a'_i = x a_i. \n\tint operator*=(double x) {return gsl_vector_scale (gsldata, x);}\n\n//  Function: int gsl_vector_add_constant (gsl_vector * a, const double x) \n//      This function adds the constant value x to the elements of the vector a, a'_i = a_i + x. \n\tint operator+=(double x) {return gsl_vector_add_constant (gsldata,x);}\n\n//      This function multiplies the elements of vector a by the constant factor x, a'_i = x a_i. \n\tint operator/=(double x) {return gsl_vector_scale (gsldata, 1/x);}\n\n// bool operators:\n\tbool operator==(const vector& other) const;\n\tbool operator!=(const vector& other) const { return (!((*this)==other));}\n\n// stream output:\n//\tfriend ostream& operator<< ( ostream& os, const vector& vect );\n\t/** returns sum of all the vector elements. */\n    double sum() const;\n\t// returns sqrt(v.t*v);\n    double norm2() const;\n\n\n// **** Finding maximum and minimum elements of vectors\n\n//      This function returns the maximum value in the vector v. \n    double max() const{return gsl_vector_max (gsldata) ;}\n\n//  Function: double gsl_vector_min (const gsl_vector * v) \n//      This function returns the minimum value in the vector v. \n    double min() const{return gsl_vector_min (gsldata) ;}\n\n//  Function: void gsl_vector_minmax (const gsl_vector * v, double * min_out, double * max_out) \n//      This function returns the minimum and maximum values in the vector v, storing them in min_out and max_out. \n\n//      This function returns the index of the maximum value in the vector v. When there are several equal maximum elements then the lowest index is returned. \n\tsize_t max_index(){return gsl_vector_max_index (gsldata);}\n\n//  Function: size_t gsl_vector_min_index (const gsl_vector * v) \n//      This function returns the index of the minimum value in the vector v. When there are several equal minimum elements then the lowest index is returned. \n\tsize_t min_index(){return gsl_vector_min_index (gsldata);}\n\n//  Function: void gsl_vector_minmax_index (const gsl_vector * v, size_t * imin, size_t * imax) \n//      This function returns the indices of the minimum and maximum values in the vector v, storing them in imin and imax. When there are several equal minimum\n//      or maximum elements then the lowest indices are returned. \n\n//  Vector properties\n\n//  Function: int gsl_vector_isnull (const gsl_vector * v) \n//      This function returns 1 if all the elements of the vector v are zero, and 0 otherwise. };\n\tbool isnull(){return gsl_vector_isnull (gsldata);}\n};\n\n// When you add create a view it will stick to its with the view until you call change_view\n// ex:\n// matrix_float m(5,5);\n// vector_float v(5); \n// // ... \n// m.column(3) = v; //the 3rd column of the matrix m will equal v. \nclass vector_view : public vector\n{\n public:\n\tvector_view(const vector&     other) :vector(){init(other);}\n\tvector_view(const vector_view& other):vector(){init(other);}\n\tvector_view(const gsl_vector& gsl_other) : vector() {init_with_gsl_vector(gsl_other);}\n\n\tvoid init(const vector& other);\n\tvoid init_with_gsl_vector(const gsl_vector& gsl_other);\n\tvoid change_view(const vector& other){init(other);}\n private:\n};\n\nostream& operator<< ( ostream& os, const vector & vect );\n\n\n// vector_type<>::type is a template interface to vector_?\n// it is usefull for in templated situations for getting the correct vector type\n#define tmp_type_is\n#ifdef tmp_type_is\ntypedef vector vector_double;\ntemplate<class T> \nstruct vector_type  {typedef vector_double   type;};\n\ntemplate<class T> \nstruct value_type  {typedef double   type;};\n\n#else\ntemplate<> struct vector_type<double> {typedef vector type;};\n#endif\n#undef tmp_type_is\n\n}\n#endif// _vector_double_h\n", "meta": {"hexsha": "6858c596f0b71945fad8b23b07a5b328e29a5041", "size": 20742, "ext": "h", "lang": "C", "max_stars_repo_path": "DTM/dtm-master/gslwrap/include/gslwrap/vector_double.h", "max_stars_repo_name": "boomsbloom/dtm-fmri", "max_stars_repo_head_hexsha": "159aab87f04b745d874b53f64fd30703b4d5a70c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-11-27T01:35:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T01:17:11.000Z", "max_issues_repo_path": "DTM/dtm-master/gslwrap/include/gslwrap/vector_double.h", "max_issues_repo_name": "boomsbloom/dtm-fmri", "max_issues_repo_head_hexsha": "159aab87f04b745d874b53f64fd30703b4d5a70c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DTM/dtm-master/gslwrap/include/gslwrap/vector_double.h", "max_forks_repo_name": "boomsbloom/dtm-fmri", "max_forks_repo_head_hexsha": "159aab87f04b745d874b53f64fd30703b4d5a70c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-11-27T01:35:33.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-27T01:35:33.000Z", "avg_line_length": 51.5970149254, "max_line_length": 675, "alphanum_fraction": 0.7337768778, "num_tokens": 4965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3486451488696663, "lm_q2_score": 0.01971912655911187, "lm_q1q2_score": 0.006874977814781349}}
{"text": "/* -*- linux-c -*- */\n/* fewbody_hier.c\n\n   Copyright (C) 2002-2004 John M. Fregeau\n   \n   This program is free software; you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation; either version 2 of the License, or\n   (at your option) any later version.\n   \n   This program is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n   \n   You should have received a copy of the GNU General Public License\n   along with this program; if not, write to the Free Software\n   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n*/\n\n#include <stdio.h>\n#include <stddef.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <gsl/gsl_rng.h>\n#include \"fewbody.h\"\n\n/* allocate memory for a hier_t */\nvoid fb_malloc_hier(fb_hier_t *hier)\n{\n\tint i;\n\n\thier->hi = (int *) malloc(hier->nstarinit * sizeof(int)) - 1;\n\tfb_create_indices(hier->hi, hier->nstarinit);\n\thier->narr = (int *) malloc((hier->nstarinit-1)*sizeof(int)) - 2;\n\t/* change from malloc to calloc to get rid of harmless valgrind errors...\n\t   the errors occur in fb_normalize(), where uninitialized memory is normalized - \n\t   these are clearly harmless */\n\thier->hier = (fb_obj_t *) calloc(hier->hi[hier->nstarinit] + 1, sizeof(fb_obj_t));\n\tfor (i=0; i<hier->hi[hier->nstarinit]+1; i++) {\n\t\thier->hier[i].ncoll = 0;\n\t\thier->hier[i].id = (long *) malloc(hier->nstarinit * sizeof(long));\n\t}\n\thier->obj = (fb_obj_t **) malloc(hier->nstarinit * sizeof(fb_obj_t *));\n}\n\n/* initialize to a flat hier */\nvoid fb_init_hier(fb_hier_t *hier)\n{\n\tint i;\n\t\n\thier->nobj = hier->nstar;\n\t\n\tfor (i=2; i<=hier->nstar; i++) {\n\t\thier->narr[i] = 0;\n\t}\n\t\n\tfor (i=0; i<hier->nstar; i++) {\n\t\thier->obj[i] = &(hier->hier[hier->hi[1]+i]);\n\t}\n}\n\n/* free memory */\nvoid fb_free_hier(fb_hier_t hier)\n{\n\tint i;\n\n\tfor (i=0; i<hier.hi[hier.nstarinit]+1; i++) {\n\t\tfree(hier.hier[i].id);\n\t}\n\tfree(hier.hi+1);\n\tfree(hier.narr+2);\n\tfree(hier.hier);\n\tfree(hier.obj);\n}\n\n/* trickle down hier */\nvoid fb_trickle(fb_hier_t *hier, double t)\n{\n\tint i, j;\n\t\n\tfor (i=hier->nstar; i>=2; i--) {\n\t\tfor (j=0; j<hier->narr[i]; j++) {\n\t\t\tfb_downsync(&(hier->hier[hier->hi[i] + j]), t);\n\t\t}\n\t}\n}\n\n/* trickle up hier */\nvoid fb_elkcirt(fb_hier_t *hier, double t)\n{\n\tint i, j;\n\t\n\tfor (i=2; i<=hier->nstar; i++) {\n\t\tfor (j=0; j<hier->narr[i]; j++) {\n\t\t\tfb_upsync(&(hier->hier[hier->hi[i] + j]), t);\n\t\t}\n\t}\n}\n\n/* created the index array */\nint fb_create_indices(int *hi, int nstar)\n{\n\tint i, j=0;\n\t\n\tfor (i=1; i<=nstar; i++) {\n\t\thi[i] = j;\n\t\tj += nstar/i;\n\t}\n\t\n\treturn(0);\n}\n\n/* how many members are in the immediate hierarchy */\nint fb_n_hier(fb_obj_t *obj)\n{\n\tif (obj == NULL) {\n\t\treturn(0);\n\t} else if ((obj->obj[0] == NULL) && (obj->obj[1] == NULL)) {\n\t\treturn(1);\n\t} else if ((obj->obj[0]->obj[0] == NULL) && (obj->obj[0]->obj[1] == NULL) && (obj->obj[1]->obj[0] == NULL) && (obj->obj[1]->obj[1] == NULL)) {\n\t\treturn(2);\n\t} else if (((obj->obj[0]->obj[0] == NULL) && (obj->obj[0]->obj[1] == NULL)) || ((obj->obj[1]->obj[0] == NULL) && (obj->obj[1]->obj[1] == NULL))) {\n\t\treturn(3);\n\t} else {\n\t\treturn(4);\n\t}\n}\n\n/* print the hierarchy information */\nchar *fb_sprint_hier(fb_hier_t hier, char string[FB_MAX_STRING_LENGTH])\n{\n\tint i;\n\t\n\tsnprintf(string, FB_MAX_STRING_LENGTH, \"nstar=%d nobj=%d: \", hier.nstar, hier.nobj);\n\tfor (i=0; i<hier.nobj; i++) {\n\t\tsnprintf(&(string[strlen(string)]), FB_MAX_STRING_LENGTH-strlen(string), \" %s\", hier.obj[i]->idstring);\n\t}\n\t\n\treturn(string);\n}\n\n/* print the hierarchy information in a nice human-readable format */\nchar *fb_sprint_hier_hr(fb_hier_t hier, char string[FB_MAX_STRING_LENGTH])\n{\n\tint i;\n\n\t/* zero out string so strlen(string) returns 0 */\n\tstring[0] = '\\0';\n\t\n\t/* loop through objects */\n\tfor (i=0; i<hier.nobj; i++) {\n\t\t/* put a dash inbetween labels */\n\t\tif (i > 0) {\n\t\t\tsnprintf(&(string[strlen(string)]), FB_MAX_STRING_LENGTH-strlen(string), \"-\");\n\t\t}\n\t\t/* a name for each type of hierarchy */\n\t\tif (hier.obj[i]->n == 1) {\n\t\t\tsnprintf(&(string[strlen(string)]), FB_MAX_STRING_LENGTH-strlen(string), \"single\");\n\t\t} else if (hier.obj[i]->n == 2) {\n\t\t\tsnprintf(&(string[strlen(string)]), FB_MAX_STRING_LENGTH-strlen(string), \"binary\");\n\t\t} else if (hier.obj[i]->n == 3) {\n\t\t\tsnprintf(&(string[strlen(string)]), FB_MAX_STRING_LENGTH-strlen(string), \"triple\");\n\t\t} else if (hier.obj[i]->n == 4) {\n\t\t\tsnprintf(&(string[strlen(string)]), FB_MAX_STRING_LENGTH-strlen(string), \"quadruple\");\n\t\t} else if (hier.obj[i]->n == 5) {\n\t\t\tsnprintf(&(string[strlen(string)]), FB_MAX_STRING_LENGTH-strlen(string), \"quintuple\");\n\t\t} else if (hier.obj[i]->n == 6) {\n\t\t\tsnprintf(&(string[strlen(string)]), FB_MAX_STRING_LENGTH-strlen(string), \"sextuple\");\n\t\t} else if (hier.obj[i]->n == 7) {\n\t\t\tsnprintf(&(string[strlen(string)]), FB_MAX_STRING_LENGTH-strlen(string), \"septuple\");\n\t\t} else if (hier.obj[i]->n == 8) {\n\t\t\tsnprintf(&(string[strlen(string)]), FB_MAX_STRING_LENGTH-strlen(string), \"octuple\");\n\t\t} else if (hier.obj[i]->n == 9) {\n\t\t\tsnprintf(&(string[strlen(string)]), FB_MAX_STRING_LENGTH-strlen(string), \"nontuple\");\n\t\t} else if (hier.obj[i]->n == 10) {\n\t\t\tsnprintf(&(string[strlen(string)]), FB_MAX_STRING_LENGTH-strlen(string), \"decituple\");\n\t\t} else {\n\t\t\tsnprintf(&(string[strlen(string)]), FB_MAX_STRING_LENGTH-strlen(string), \"%d\", hier.obj[i]->n);\t\n\t\t\tsnprintf(&(string[strlen(string)]), FB_MAX_STRING_LENGTH-strlen(string), \"tuple\");\n\t\t}\n\t}\n\n\treturn(string);\n}\n\n/* merge the object's properties up---calculate the binary's properties from the\n   stars' properties */\nvoid fb_upsync(fb_obj_t *obj, double t)\n{\n\tint i;\n\tdouble m0, m1, x0[3], x1[3], xrel[3], v0[3], v1[3], vrel[3], E, l0[3], l1[3], l[3];\n\tdouble ypp[3], psi, ecc_anom, L[3], A[3];\n\n\t/* a little bit of paranoia here */\n\tobj->ncoll = 0;\n\tobj->id[0] = -1;\n\n\t/* set time of upsync */\n\tobj->t = t;\n\n\t/* create idstring */\n\tsnprintf(obj->idstring, FB_MAX_STRING_LENGTH, \"[%s %s]\", obj->obj[0]->idstring, obj->obj[1]->idstring);\n\n\t/* update number of stars in hierarchy */\n\tobj->n = obj->obj[0]->n + obj->obj[1]->n;\n\t\n\t/* update mass */\n\tm0 = obj->obj[0]->m;\n\tm1 = obj->obj[1]->m;\n\tobj->m = m0 + m1;\n\n\t/* update position and velocity */\n\tfor (i=0; i<3; i++) {\n\t\tobj->x[i] = (m0*(obj->obj[0]->x[i]) + m1*(obj->obj[1]->x[i])) / (obj->m);\n\t\tobj->v[i] = (m0*(obj->obj[0]->v[i]) + m1*(obj->obj[1]->v[i])) / (obj->m);\n\t}\n\t\n\t/* update semimajor axis */\n\tfor (i=0; i<3; i++) {\n\t\tx0[i] = obj->obj[0]->x[i] - obj->x[i];\n\t\tx1[i] = obj->obj[1]->x[i] - obj->x[i];\n\t\txrel[i] = obj->obj[0]->x[i] - obj->obj[1]->x[i];\n\t\tv0[i] = obj->obj[0]->v[i] - obj->v[i];\n\t\tv1[i] = obj->obj[1]->v[i] - obj->v[i];\n\t\tvrel[i] = obj->obj[0]->v[i] - obj->obj[1]->v[i];\n\t}\n\t\n\tE = 0.5*(m0*fb_dot(v0, v0) + m1*fb_dot(v1, v1)) - m0*m1/fb_mod(xrel);\n\t\n\tif (E >= 0.0) {\n\t\tfprintf(stderr, \"fb_upsync: E = %g >= 0!\\n\", E);\n\t\texit(1);\n\t}\n\t\n\tobj->a = -m0 * m1 / (2.0 * E);\n\n\t/* update angular momentum, Runge-Lenz vector, and eccentricity (using the Runge-Lenz vector) */\n\tfb_cross(x0, v0, l0);\n\tfb_cross(x1, v1, l1);\n\t\n\tfor (i=0; i<3; i++) {\n\t\tL[i] = m0 * l0[i] + m1 * l1[i];\n\t\tl[i] = L[i] * (m0+m1)/(m0*m1);\n\t}\n\t\n\t/* -A = l x v + G M \\hat r */\n\tfb_cross(vrel, l, A);\n\tfor (i=0; i<3; i++) {\n\t\tA[i] -= (m0+m1) * xrel[i]/fb_mod(xrel);\n\t}\n\t\n\tobj->e = fb_mod(A)/(m0+m1);\n\t\n\t/* must be careful with circular orbits, which have a null A vector */\n\tif (obj->e == 0.0) {\n\t\tfor (i=0; i<3; i++) {\n\t\t\tA[i] = xrel[i];\n\t\t}\n\t}\n\t\n\t/* define coord system */\n\tfor (i=0; i<3; i++) {\n\t\tobj->Lhat[i] = L[i]/fb_mod(L); /* z-direction */\n\t\tobj->Ahat[i] = A[i]/fb_mod(A); /* x-direction */\n\t}\n\tfb_cross(obj->Lhat, obj->Ahat, ypp);\n\t\n\t/* and set mean anomaly */\n\tpsi = atan2(fb_dot(x0, ypp), fb_dot(x0, obj->Ahat));\n\tecc_anom = acos((obj->e + cos(psi)) / (1.0 + obj->e * cos(psi)));\n\tif (psi < 0.0) {\n\t\tecc_anom = 2.0 * FB_CONST_PI - ecc_anom;\n\t}\n\tobj->mean_anom = ecc_anom - obj->e * sin(ecc_anom);\n}\n\n/* randomly orient binary */\nvoid fb_randorient(fb_obj_t *obj, gsl_rng *rng)\n{\n\tint i;\n\tdouble theta, phi, omega, xp[3], yp[3], zp[3];\n\t\n\t/* random angles */\n\ttheta = acos(2.0 * gsl_rng_uniform(rng) - 1.0);\n\tphi = 2.0 * FB_CONST_PI * gsl_rng_uniform(rng);\n\tomega = 2.0 * FB_CONST_PI * gsl_rng_uniform(rng);\n\tobj->mean_anom = 2.0 * FB_CONST_PI * gsl_rng_uniform(rng);\n\n\t/* set up coordinate transformations */\n\tzp[0] = -sin(theta) * sin(phi);\n\tzp[1] = sin(theta) * cos(phi);\n\tzp[2] = cos(theta);\n\t\n\txp[0] = cos(phi);\n\txp[1] = sin(phi);\n\txp[2] = 0.0;\n\t\n\tfb_cross(zp, xp, yp);\n\t\n\tfor (i=0; i<3; i++) {\n\t\tobj->Lhat[i] = zp[i];\n\t\tobj->Ahat[i] = xp[i] * cos(omega) + yp[i] * sin(omega);\n\t}\n}\n\n/* merge the object's properties down---calculate the objs' properties from the\n   binary's properties */\nvoid fb_downsync(fb_obj_t *obj, double t)\n{\n\tint i;\n\tdouble xpp[3], ypp[3], zpp[3], er[3], epsi[3];\n\tdouble a, e, m0, m1, omega, mean_anom, ecc_anom, psi, r0, r1, L, psidot, E, r0dot, r0dot2, r1dot;\n\n\t/* we're assuming here that the objs' masses are already set */\n\ta = obj->a;\n\te = obj->e;\n\tm0 = obj->obj[0]->m;\n\tm1 = obj->obj[1]->m;\n\t\n\t/* angular frequency */\n\tomega = sqrt(obj->m/fb_cub(a));\n\t/* mean anomaly, between 0 and 2PI */\n\tmean_anom = (obj->mean_anom + omega * (t - obj->t)) / (2.0 * FB_CONST_PI);\n\tmean_anom = (mean_anom - floor(mean_anom)) * 2.0 * FB_CONST_PI;\n\t/* eccentric anomaly, from solving the Kepler equation */\n\tecc_anom = fb_kepler(e, mean_anom);\n\t/* true anomaly, between 0 and 2PI */\n\tpsi = acos((cos(ecc_anom) - e) / (1.0 - e * cos(ecc_anom)));\n\t/* this step is necessary because acos() returns a value between 0 and PI */\n\tif (ecc_anom > FB_CONST_PI) {\n\t\tpsi = 2.0 * FB_CONST_PI - psi;\n\t}\n\t\n\t/* define vectors, based on angular momentum and Runge-Lenz vectors */\n\tfor (i=0; i<3; i++) {\n\t\tzpp[i] = obj->Lhat[i];\n\t\txpp[i] = obj->Ahat[i];\n\t}\n\tfb_cross(zpp, xpp, ypp);\n\t\n\tfor (i=0; i<3; i++) {\n\t\ter[i] = xpp[i] * cos(psi) + ypp[i] * sin(psi);\n\t\tepsi[i] = ypp[i] * cos(psi) - xpp[i] * sin(psi);\n\t}\n\t\n\t/* determine binary params */\n\tr0 = a * (1.0 - fb_sqr(e)) / ((1.0 + e*cos(psi)) * (1.0 + m0/m1));\n\tr1 = a * (1.0 - fb_sqr(e)) / ((1.0 + e*cos(psi)) * (1.0 + m1/m0));\n\n\tL = m0 * m1 * sqrt((m0+m1)*a*(1.0-fb_sqr(e))) / (m0 + m1);\n\tpsidot = L / (m0 * fb_sqr(r0) + m1 * fb_sqr(r1));\n\tE = -m0 * m1 / (2.0 * a);\n\n\t/* must be careful for circular orbits */\n\tr0dot2 = (E + m0*m1/(r0+r1)) * 2.0 / (m0 * (1.0+m0/m1)) - fb_sqr(r0*psidot);\n\tif (ecc_anom > FB_CONST_PI) {\n\t\tr0dot = -(r0dot2<=0.0?0.0:sqrt(r0dot2));\n\t} else {\n\t\tr0dot = (r0dot2<=0.0?0.0:sqrt(r0dot2));\n\t}\n\tr1dot = m0 * r0dot / m1;\n\t\n\tfor (i=0; i<3; i++) {\n\t\tobj->obj[0]->x[i] = r0 * er[i] + obj->x[i];\n\t\tobj->obj[0]->v[i] = r0dot * er[i] + r0 * psidot * epsi[i] + obj->v[i];\n\t\tobj->obj[1]->x[i] = -r1 * er[i] + obj->x[i];\n\t\tobj->obj[1]->v[i] = -r1dot * er[i] - r1 * psidot * epsi[i] + obj->v[i];\n\t}\n}\n\n/* copy one object to another, being careful about any pointers */\nvoid fb_objcpy(fb_obj_t *obj1, fb_obj_t *obj2)\n{\n\tint i;\n\tlong *longptr;\n\t\n\tfor (i=0; i<obj2->ncoll; i++) {\n\t\tobj1->id[i] = obj2->id[i];\n\t}\n\n\t/* prevent any dangling pointers */\n\tlongptr = obj1->id;\n\t*obj1 = *obj2;\n\tobj1->id = longptr;\n}\n", "meta": {"hexsha": "34fbb90f00d4e92efc39e51f1621abf9dd54fc61", "size": 11217, "ext": "c", "lang": "C", "max_stars_repo_path": "ext/fewbod/fewbody-0.26/fewbody_hier.c", "max_stars_repo_name": "gnodvi/cosmos", "max_stars_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c", "max_stars_repo_licenses": ["PSF-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ext/fewbod/fewbody-0.26/fewbody_hier.c", "max_issues_repo_name": "gnodvi/cosmos", "max_issues_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c", "max_issues_repo_licenses": ["PSF-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-13T20:35:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-13T20:35:46.000Z", "max_forks_repo_path": "ext/fewbod/fewbody-0.26/fewbody_hier.c", "max_forks_repo_name": "gnodvi/cosmos", "max_forks_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c", "max_forks_repo_licenses": ["PSF-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9097938144, "max_line_length": 147, "alphanum_fraction": 0.5950788981, "num_tokens": 4138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31742626558767584, "lm_q2_score": 0.02161533449587041, "lm_q1q2_score": 0.006861274908452612}}
{"text": "#include <config.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_sum.h>\n\ngsl_sum_levin_utrunc_workspace * \ngsl_sum_levin_utrunc_alloc (size_t n)\n{\n  gsl_sum_levin_utrunc_workspace * w;\n\n  if (n == 0)\n    {\n      GSL_ERROR_VAL (\"length n must be positive integer\", GSL_EDOM, 0);\n    }\n\n  w = (gsl_sum_levin_utrunc_workspace *) malloc(sizeof(gsl_sum_levin_utrunc_workspace));\n\n  if (w == NULL)\n    {\n      GSL_ERROR_VAL (\"failed to allocate struct\", GSL_ENOMEM, 0);\n    }\n\n  w->q_num = (double *) malloc (n * sizeof (double));\n\n  if (w->q_num == NULL)\n    {\n      free(w) ; /* error in constructor, prevent memory leak */\n\n      GSL_ERROR_VAL (\"failed to allocate space for q_num\", GSL_ENOMEM, 0);\n    }\n\n  w->q_den = (double *) malloc (n * sizeof (double));\n\n  if (w->q_den == NULL)\n    {\n      free (w->q_num);\n      free (w) ; /* error in constructor, prevent memory leak */\n\n      GSL_ERROR_VAL (\"failed to allocate space for q_den\", GSL_ENOMEM, 0);\n    }\n\n  w->dsum = (double *) malloc (n * sizeof (double));\n\n  if (w->dsum == NULL)\n    {\n      free (w->q_den);\n      free (w->q_num);\n      free (w) ; /* error in constructor, prevent memory leak */\n\n      GSL_ERROR_VAL (\"failed to allocate space for dsum\", GSL_ENOMEM, 0);\n    }\n\n  w->size = n;\n  w->terms_used = 0;\n  w->sum_plain = 0;\n\n  return w;\n}\n\nvoid\ngsl_sum_levin_utrunc_free (gsl_sum_levin_utrunc_workspace * w)\n{\n  RETURN_IF_NULL (w);\n  free (w->dsum);\n  free (w->q_den);\n  free (w->q_num);\n  free (w);\n}\n", "meta": {"hexsha": "81ddf67fecf0c6650801da7f68e2c9c3b91eae9f", "size": 1495, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/sum/work_utrunc.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/sum/work_utrunc.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/sum/work_utrunc.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 21.6666666667, "max_line_length": 88, "alphanum_fraction": 0.618729097, "num_tokens": 475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31742627850202554, "lm_q2_score": 0.02161533032037945, "lm_q1q2_score": 0.006861273862190044}}
{"text": "/* matrix/gsl_matrix_float.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_MATRIX_FLOAT_H__\n#define __GSL_MATRIX_FLOAT_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_inline.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_vector_float.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size1;\n  size_t size2;\n  size_t tda;\n  float * data;\n  gsl_block_float * block;\n  int owner;\n} gsl_matrix_float;\n\ntypedef struct\n{\n  gsl_matrix_float matrix;\n} _gsl_matrix_float_view;\n\ntypedef _gsl_matrix_float_view gsl_matrix_float_view;\n\ntypedef struct\n{\n  gsl_matrix_float matrix;\n} _gsl_matrix_float_const_view;\n\ntypedef const _gsl_matrix_float_const_view gsl_matrix_float_const_view;\n\n/* Allocation */\n\ngsl_matrix_float * \ngsl_matrix_float_alloc (const size_t n1, const size_t n2);\n\ngsl_matrix_float * \ngsl_matrix_float_calloc (const size_t n1, const size_t n2);\n\ngsl_matrix_float * \ngsl_matrix_float_alloc_from_block (gsl_block_float * b, \n                                   const size_t offset, \n                                   const size_t n1, \n                                   const size_t n2, \n                                   const size_t d2);\n\ngsl_matrix_float * \ngsl_matrix_float_alloc_from_matrix (gsl_matrix_float * m,\n                                    const size_t k1, \n                                    const size_t k2,\n                                    const size_t n1, \n                                    const size_t n2);\n\ngsl_vector_float * \ngsl_vector_float_alloc_row_from_matrix (gsl_matrix_float * m,\n                                        const size_t i);\n\ngsl_vector_float * \ngsl_vector_float_alloc_col_from_matrix (gsl_matrix_float * m,\n                                        const size_t j);\n\nvoid gsl_matrix_float_free (gsl_matrix_float * m);\n\n/* Views */\n\n_gsl_matrix_float_view \ngsl_matrix_float_submatrix (gsl_matrix_float * m, \n                            const size_t i, const size_t j, \n                            const size_t n1, const size_t n2);\n\n_gsl_vector_float_view \ngsl_matrix_float_row (gsl_matrix_float * m, const size_t i);\n\n_gsl_vector_float_view \ngsl_matrix_float_column (gsl_matrix_float * m, const size_t j);\n\n_gsl_vector_float_view \ngsl_matrix_float_diagonal (gsl_matrix_float * m);\n\n_gsl_vector_float_view \ngsl_matrix_float_subdiagonal (gsl_matrix_float * m, const size_t k);\n\n_gsl_vector_float_view \ngsl_matrix_float_superdiagonal (gsl_matrix_float * m, const size_t k);\n\n_gsl_vector_float_view\ngsl_matrix_float_subrow (gsl_matrix_float * m, const size_t i,\n                         const size_t offset, const size_t n);\n\n_gsl_vector_float_view\ngsl_matrix_float_subcolumn (gsl_matrix_float * m, const size_t j,\n                            const size_t offset, const size_t n);\n\n_gsl_matrix_float_view\ngsl_matrix_float_view_array (float * base,\n                             const size_t n1, \n                             const size_t n2);\n\n_gsl_matrix_float_view\ngsl_matrix_float_view_array_with_tda (float * base, \n                                      const size_t n1, \n                                      const size_t n2,\n                                      const size_t tda);\n\n\n_gsl_matrix_float_view\ngsl_matrix_float_view_vector (gsl_vector_float * v,\n                              const size_t n1, \n                              const size_t n2);\n\n_gsl_matrix_float_view\ngsl_matrix_float_view_vector_with_tda (gsl_vector_float * v,\n                                       const size_t n1, \n                                       const size_t n2,\n                                       const size_t tda);\n\n\n_gsl_matrix_float_const_view \ngsl_matrix_float_const_submatrix (const gsl_matrix_float * m, \n                                  const size_t i, const size_t j, \n                                  const size_t n1, const size_t n2);\n\n_gsl_vector_float_const_view \ngsl_matrix_float_const_row (const gsl_matrix_float * m, \n                            const size_t i);\n\n_gsl_vector_float_const_view \ngsl_matrix_float_const_column (const gsl_matrix_float * m, \n                               const size_t j);\n\n_gsl_vector_float_const_view\ngsl_matrix_float_const_diagonal (const gsl_matrix_float * m);\n\n_gsl_vector_float_const_view \ngsl_matrix_float_const_subdiagonal (const gsl_matrix_float * m, \n                                    const size_t k);\n\n_gsl_vector_float_const_view \ngsl_matrix_float_const_superdiagonal (const gsl_matrix_float * m, \n                                      const size_t k);\n\n_gsl_vector_float_const_view\ngsl_matrix_float_const_subrow (const gsl_matrix_float * m, const size_t i,\n                               const size_t offset, const size_t n);\n\n_gsl_vector_float_const_view\ngsl_matrix_float_const_subcolumn (const gsl_matrix_float * m, const size_t j,\n                                  const size_t offset, const size_t n);\n\n_gsl_matrix_float_const_view\ngsl_matrix_float_const_view_array (const float * base,\n                                   const size_t n1, \n                                   const size_t n2);\n\n_gsl_matrix_float_const_view\ngsl_matrix_float_const_view_array_with_tda (const float * base, \n                                            const size_t n1, \n                                            const size_t n2,\n                                            const size_t tda);\n\n_gsl_matrix_float_const_view\ngsl_matrix_float_const_view_vector (const gsl_vector_float * v,\n                                    const size_t n1, \n                                    const size_t n2);\n\n_gsl_matrix_float_const_view\ngsl_matrix_float_const_view_vector_with_tda (const gsl_vector_float * v,\n                                             const size_t n1, \n                                             const size_t n2,\n                                             const size_t tda);\n\n/* Operations */\n\nvoid gsl_matrix_float_set_zero (gsl_matrix_float * m);\nvoid gsl_matrix_float_set_identity (gsl_matrix_float * m);\nvoid gsl_matrix_float_set_all (gsl_matrix_float * m, float x);\n\nint gsl_matrix_float_fread (FILE * stream, gsl_matrix_float * m) ;\nint gsl_matrix_float_fwrite (FILE * stream, const gsl_matrix_float * m) ;\nint gsl_matrix_float_fscanf (FILE * stream, gsl_matrix_float * m);\nint gsl_matrix_float_fprintf (FILE * stream, const gsl_matrix_float * m, const char * format);\n \nint gsl_matrix_float_memcpy(gsl_matrix_float * dest, const gsl_matrix_float * src);\nint gsl_matrix_float_swap(gsl_matrix_float * m1, gsl_matrix_float * m2);\n\nint gsl_matrix_float_swap_rows(gsl_matrix_float * m, const size_t i, const size_t j);\nint gsl_matrix_float_swap_columns(gsl_matrix_float * m, const size_t i, const size_t j);\nint gsl_matrix_float_swap_rowcol(gsl_matrix_float * m, const size_t i, const size_t j);\nint gsl_matrix_float_transpose (gsl_matrix_float * m);\nint gsl_matrix_float_transpose_memcpy (gsl_matrix_float * dest, const gsl_matrix_float * src);\n\nfloat gsl_matrix_float_max (const gsl_matrix_float * m);\nfloat gsl_matrix_float_min (const gsl_matrix_float * m);\nvoid gsl_matrix_float_minmax (const gsl_matrix_float * m, float * min_out, float * max_out);\n\nvoid gsl_matrix_float_max_index (const gsl_matrix_float * m, size_t * imax, size_t *jmax);\nvoid gsl_matrix_float_min_index (const gsl_matrix_float * m, size_t * imin, size_t *jmin);\nvoid gsl_matrix_float_minmax_index (const gsl_matrix_float * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);\n\nint gsl_matrix_float_equal (const gsl_matrix_float * a, const gsl_matrix_float * b);\n\nint gsl_matrix_float_isnull (const gsl_matrix_float * m);\nint gsl_matrix_float_ispos (const gsl_matrix_float * m);\nint gsl_matrix_float_isneg (const gsl_matrix_float * m);\nint gsl_matrix_float_isnonneg (const gsl_matrix_float * m);\n\nint gsl_matrix_float_add (gsl_matrix_float * a, const gsl_matrix_float * b);\nint gsl_matrix_float_sub (gsl_matrix_float * a, const gsl_matrix_float * b);\nint gsl_matrix_float_mul_elements (gsl_matrix_float * a, const gsl_matrix_float * b);\nint gsl_matrix_float_div_elements (gsl_matrix_float * a, const gsl_matrix_float * b);\nint gsl_matrix_float_scale (gsl_matrix_float * a, const double x);\nint gsl_matrix_float_add_constant (gsl_matrix_float * a, const double x);\nint gsl_matrix_float_add_diagonal (gsl_matrix_float * a, const double x);\n\n/***********************************************************************/\n/* The functions below are obsolete                                    */\n/***********************************************************************/\nint gsl_matrix_float_get_row(gsl_vector_float * v, const gsl_matrix_float * m, const size_t i);\nint gsl_matrix_float_get_col(gsl_vector_float * v, const gsl_matrix_float * m, const size_t j);\nint gsl_matrix_float_set_row(gsl_matrix_float * m, const size_t i, const gsl_vector_float * v);\nint gsl_matrix_float_set_col(gsl_matrix_float * m, const size_t j, const gsl_vector_float * v);\n/***********************************************************************/\n\n/* inline functions if you are using GCC */\n\nINLINE_DECL float   gsl_matrix_float_get(const gsl_matrix_float * m, const size_t i, const size_t j);\nINLINE_DECL void    gsl_matrix_float_set(gsl_matrix_float * m, const size_t i, const size_t j, const float x);\nINLINE_DECL float * gsl_matrix_float_ptr(gsl_matrix_float * m, const size_t i, const size_t j);\nINLINE_DECL const float * gsl_matrix_float_const_ptr(const gsl_matrix_float * m, const size_t i, const size_t j);\n\n#ifdef HAVE_INLINE\nINLINE_FUN \nfloat\ngsl_matrix_float_get(const gsl_matrix_float * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_VAL(\"first index out of range\", GSL_EINVAL, 0) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_VAL(\"second index out of range\", GSL_EINVAL, 0) ;\n        }\n    }\n#endif\n  return m->data[i * m->tda + j] ;\n} \n\nINLINE_FUN \nvoid\ngsl_matrix_float_set(gsl_matrix_float * m, const size_t i, const size_t j, const float x)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_VOID(\"first index out of range\", GSL_EINVAL) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_VOID(\"second index out of range\", GSL_EINVAL) ;\n        }\n    }\n#endif\n  m->data[i * m->tda + j] = x ;\n}\n\nINLINE_FUN \nfloat *\ngsl_matrix_float_ptr(gsl_matrix_float * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n        }\n    }\n#endif\n  return (float *) (m->data + (i * m->tda + j)) ;\n} \n\nINLINE_FUN \nconst float *\ngsl_matrix_float_const_ptr(const gsl_matrix_float * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n        }\n    }\n#endif\n  return (const float *) (m->data + (i * m->tda + j)) ;\n} \n\n#endif\n\n__END_DECLS\n\n#endif /* __GSL_MATRIX_FLOAT_H__ */\n", "meta": {"hexsha": "9af95e0261ea1aa831c27db5e7d30b4ab728be2f", "size": 12287, "ext": "h", "lang": "C", "max_stars_repo_path": "gsl-2.6/gsl/gsl_matrix_float.h", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gsl-2.6/gsl/gsl_matrix_float.h", "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gsl-2.6/gsl/gsl_matrix_float.h", "max_forks_repo_name": "ielomariala/Hex-Game", "max_forks_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-30T20:40:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-30T20:40:25.000Z", "avg_line_length": 35.0056980057, "max_line_length": 124, "alphanum_fraction": 0.6543501261, "num_tokens": 2900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25982564942392716, "lm_q2_score": 0.026355354184432096, "lm_q1q2_score": 0.006847797016767685}}
{"text": "/* matrix/gsl_matrix_complex_float.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_MATRIX_COMPLEX_FLOAT_H__\n#define __GSL_MATRIX_COMPLEX_FLOAT_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_complex.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_vector_complex_float.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size1;\n  size_t size2;\n  size_t tda;\n  float * data;\n  gsl_block_complex_float * block;\n  int owner;\n} gsl_matrix_complex_float ;\n\ntypedef struct\n{\n  gsl_matrix_complex_float matrix;\n} _gsl_matrix_complex_float_view;\n\ntypedef _gsl_matrix_complex_float_view gsl_matrix_complex_float_view;\n\ntypedef struct\n{\n  gsl_matrix_complex_float matrix;\n} _gsl_matrix_complex_float_const_view;\n\ntypedef const _gsl_matrix_complex_float_const_view gsl_matrix_complex_float_const_view;\n\n\n/* Allocation */\n\ngsl_matrix_complex_float * \ngsl_matrix_complex_float_alloc (const size_t n1, const size_t n2);\n\ngsl_matrix_complex_float * \ngsl_matrix_complex_float_calloc (const size_t n1, const size_t n2);\n\ngsl_matrix_complex_float * \ngsl_matrix_complex_float_alloc_from_block (gsl_block_complex_float * b, \n                                           const size_t offset, \n                                           const size_t n1, const size_t n2, const size_t d2);\n\ngsl_matrix_complex_float * \ngsl_matrix_complex_float_alloc_from_matrix (gsl_matrix_complex_float * b,\n                                            const size_t k1, const size_t k2,\n                                            const size_t n1, const size_t n2);\n\ngsl_vector_complex_float * \ngsl_vector_complex_float_alloc_row_from_matrix (gsl_matrix_complex_float * m,\n                                                const size_t i);\n\ngsl_vector_complex_float * \ngsl_vector_complex_float_alloc_col_from_matrix (gsl_matrix_complex_float * m,\n                                                const size_t j);\n\nvoid gsl_matrix_complex_float_free (gsl_matrix_complex_float * m);\n\n/* Views */\n\n_gsl_matrix_complex_float_view \ngsl_matrix_complex_float_submatrix (gsl_matrix_complex_float * m, \n                            const size_t i, const size_t j, \n                            const size_t n1, const size_t n2);\n\n_gsl_vector_complex_float_view \ngsl_matrix_complex_float_row (gsl_matrix_complex_float * m, const size_t i);\n\n_gsl_vector_complex_float_view \ngsl_matrix_complex_float_column (gsl_matrix_complex_float * m, const size_t j);\n\n_gsl_vector_complex_float_view \ngsl_matrix_complex_float_diagonal (gsl_matrix_complex_float * m);\n\n_gsl_vector_complex_float_view \ngsl_matrix_complex_float_subdiagonal (gsl_matrix_complex_float * m, const size_t k);\n\n_gsl_vector_complex_float_view \ngsl_matrix_complex_float_superdiagonal (gsl_matrix_complex_float * m, const size_t k);\n\n_gsl_matrix_complex_float_view\ngsl_matrix_complex_float_view_array (float * base,\n                             const size_t n1, \n                             const size_t n2);\n\n_gsl_matrix_complex_float_view\ngsl_matrix_complex_float_view_array_with_tda (float * base, \n                                      const size_t n1, \n                                      const size_t n2,\n                                      const size_t tda);\n\n_gsl_matrix_complex_float_view\ngsl_matrix_complex_float_view_vector (gsl_vector_complex_float * v,\n                              const size_t n1, \n                              const size_t n2);\n\n_gsl_matrix_complex_float_view\ngsl_matrix_complex_float_view_vector_with_tda (gsl_vector_complex_float * v,\n                                       const size_t n1, \n                                       const size_t n2,\n                                       const size_t tda);\n\n\n_gsl_matrix_complex_float_const_view \ngsl_matrix_complex_float_const_submatrix (const gsl_matrix_complex_float * m, \n                                  const size_t i, const size_t j, \n                                  const size_t n1, const size_t n2);\n\n_gsl_vector_complex_float_const_view \ngsl_matrix_complex_float_const_row (const gsl_matrix_complex_float * m, \n                            const size_t i);\n\n_gsl_vector_complex_float_const_view \ngsl_matrix_complex_float_const_column (const gsl_matrix_complex_float * m, \n                               const size_t j);\n\n_gsl_vector_complex_float_const_view\ngsl_matrix_complex_float_const_diagonal (const gsl_matrix_complex_float * m);\n\n_gsl_vector_complex_float_const_view \ngsl_matrix_complex_float_const_subdiagonal (const gsl_matrix_complex_float * m, \n                                    const size_t k);\n\n_gsl_vector_complex_float_const_view \ngsl_matrix_complex_float_const_superdiagonal (const gsl_matrix_complex_float * m, \n                                      const size_t k);\n\n_gsl_matrix_complex_float_const_view\ngsl_matrix_complex_float_const_view_array (const float * base,\n                                   const size_t n1, \n                                   const size_t n2);\n\n_gsl_matrix_complex_float_const_view\ngsl_matrix_complex_float_const_view_array_with_tda (const float * base, \n                                            const size_t n1, \n                                            const size_t n2,\n                                            const size_t tda);\n\n_gsl_matrix_complex_float_const_view\ngsl_matrix_complex_float_const_view_vector (const gsl_vector_complex_float * v,\n                                    const size_t n1, \n                                    const size_t n2);\n\n_gsl_matrix_complex_float_const_view\ngsl_matrix_complex_float_const_view_vector_with_tda (const gsl_vector_complex_float * v,\n                                             const size_t n1, \n                                             const size_t n2,\n                                             const size_t tda);\n\n/* Operations */\n\ngsl_complex_float gsl_matrix_complex_float_get(const gsl_matrix_complex_float * m, const size_t i, const size_t j);\nvoid gsl_matrix_complex_float_set(gsl_matrix_complex_float * m, const size_t i, const size_t j, const gsl_complex_float x);\n\ngsl_complex_float * gsl_matrix_complex_float_ptr(gsl_matrix_complex_float * m, const size_t i, const size_t j);\nconst gsl_complex_float * gsl_matrix_complex_float_const_ptr(const gsl_matrix_complex_float * m, const size_t i, const size_t j);\n\nvoid gsl_matrix_complex_float_set_zero (gsl_matrix_complex_float * m);\nvoid gsl_matrix_complex_float_set_identity (gsl_matrix_complex_float * m);\nvoid gsl_matrix_complex_float_set_all (gsl_matrix_complex_float * m, gsl_complex_float x);\n\nint gsl_matrix_complex_float_fread (FILE * stream, gsl_matrix_complex_float * m) ;\nint gsl_matrix_complex_float_fwrite (FILE * stream, const gsl_matrix_complex_float * m) ;\nint gsl_matrix_complex_float_fscanf (FILE * stream, gsl_matrix_complex_float * m);\nint gsl_matrix_complex_float_fprintf (FILE * stream, const gsl_matrix_complex_float * m, const char * format);\n\nint gsl_matrix_complex_float_memcpy(gsl_matrix_complex_float * dest, const gsl_matrix_complex_float * src);\nint gsl_matrix_complex_float_swap(gsl_matrix_complex_float * m1, gsl_matrix_complex_float * m2);\n\nint gsl_matrix_complex_float_swap_rows(gsl_matrix_complex_float * m, const size_t i, const size_t j);\nint gsl_matrix_complex_float_swap_columns(gsl_matrix_complex_float * m, const size_t i, const size_t j);\nint gsl_matrix_complex_float_swap_rowcol(gsl_matrix_complex_float * m, const size_t i, const size_t j);\n\nint gsl_matrix_complex_float_transpose (gsl_matrix_complex_float * m);\nint gsl_matrix_complex_float_transpose_memcpy (gsl_matrix_complex_float * dest, const gsl_matrix_complex_float * src);\n\nint gsl_matrix_complex_float_isnull (const gsl_matrix_complex_float * m);\n\nint gsl_matrix_complex_float_add (gsl_matrix_complex_float * a, const gsl_matrix_complex_float * b);\nint gsl_matrix_complex_float_sub (gsl_matrix_complex_float * a, const gsl_matrix_complex_float * b);\nint gsl_matrix_complex_float_mul_elements (gsl_matrix_complex_float * a, const gsl_matrix_complex_float * b);\nint gsl_matrix_complex_float_div_elements (gsl_matrix_complex_float * a, const gsl_matrix_complex_float * b);\nint gsl_matrix_complex_float_scale (gsl_matrix_complex_float * a, const gsl_complex_float x);\nint gsl_matrix_complex_float_add_constant (gsl_matrix_complex_float * a, const gsl_complex_float x);\nint gsl_matrix_complex_float_add_diagonal (gsl_matrix_complex_float * a, const gsl_complex_float x);\n\n/***********************************************************************/\n/* The functions below are obsolete                                    */\n/***********************************************************************/\nint gsl_matrix_complex_float_get_row(gsl_vector_complex_float * v, const gsl_matrix_complex_float * m, const size_t i);\nint gsl_matrix_complex_float_get_col(gsl_vector_complex_float * v, const gsl_matrix_complex_float * m, const size_t j);\nint gsl_matrix_complex_float_set_row(gsl_matrix_complex_float * m, const size_t i, const gsl_vector_complex_float * v);\nint gsl_matrix_complex_float_set_col(gsl_matrix_complex_float * m, const size_t j, const gsl_vector_complex_float * v);\n\n#ifdef HAVE_INLINE\n\nextern inline \ngsl_complex_float\ngsl_matrix_complex_float_get(const gsl_matrix_complex_float * m, \n                     const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  gsl_complex_float zero = {{0,0}};\n\n  if (i >= m->size1)\n    {\n      GSL_ERROR_VAL(\"first index out of range\", GSL_EINVAL, zero) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_VAL(\"second index out of range\", GSL_EINVAL, zero) ;\n    }\n#endif\n  return *(gsl_complex_float *)(m->data + 2*(i * m->tda + j)) ;\n} \n\nextern inline \nvoid\ngsl_matrix_complex_float_set(gsl_matrix_complex_float * m, \n                     const size_t i, const size_t j, const gsl_complex_float x)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_VOID(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_VOID(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  *(gsl_complex_float *)(m->data + 2*(i * m->tda + j)) = x ;\n}\n\nextern inline \ngsl_complex_float *\ngsl_matrix_complex_float_ptr(gsl_matrix_complex_float * m, \n                             const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  return (gsl_complex_float *)(m->data + 2*(i * m->tda + j)) ;\n} \n\nextern inline \nconst gsl_complex_float *\ngsl_matrix_complex_float_const_ptr(const gsl_matrix_complex_float * m, \n                                   const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  return (const gsl_complex_float *)(m->data + 2*(i * m->tda + j)) ;\n} \n\n#endif /* HAVE_INLINE */\n\n__END_DECLS\n\n#endif /* __GSL_MATRIX_COMPLEX_FLOAT_H__ */\n", "meta": {"hexsha": "8b27958679d65f11a680a1d99a80d0d97f6c2f72", "size": 12051, "ext": "h", "lang": "C", "max_stars_repo_path": "extern/include/gsl/gsl_matrix_complex_float.h", "max_stars_repo_name": "andrewkern/segSiteHMM", "max_stars_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "extern/include/gsl/gsl_matrix_complex_float.h", "max_issues_repo_name": "andrewkern/segSiteHMM", "max_issues_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "extern/include/gsl/gsl_matrix_complex_float.h", "max_forks_repo_name": "andrewkern/segSiteHMM", "max_forks_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.625, "max_line_length": 129, "alphanum_fraction": 0.6985312422, "num_tokens": 2698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2974699426047947, "lm_q2_score": 0.02297736869738237, "lm_q1q2_score": 0.00683507654761954}}
{"text": "/*\n   Copyright [2017-2021] [IBM Corporation]\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n       http://www.apache.org/licenses/LICENSE-2.0\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\n#ifndef MCAS_HSTORE_HEAP_MM_EPHEMERAL_H\n#define MCAS_HSTORE_HEAP_MM_EPHEMERAL_H\n\n#include \"heap_ephemeral.h\"\n\n#include \"hstore_config.h\"\n#include \"histogram_log2.h\"\n#include \"hop_hash_log.h\"\n#include <mm_plugin_itf.h>\n#include \"persistent.h\"\n\n#include <ccpm/interfaces.h> /* ownership_callback, (IHeap_expandable, region_vector_t) */\n#include <common/byte_span.h>\n#include <common/string_view.h>\n#include <nupm/region_descriptor.h>\n#include <gsl/span>\n\n#include <algorithm> /* min, swap */\n#include <cstddef> /* size_t */\n#include <vector>\n\nstruct heap_mm_ephemeral\n\t: private heap_ephemeral\n{\nprivate:\n\tusing byte_span = common::byte_span;\n\n\t/* Although the mm heap tracks managed regions, its definition of a managed\n\t * region probably differs from what hstore needs:\n\t *\n\t * The hstore managed region must include the hstore metadata area, as that\n\t * must be include in the \"maanged regions\" returned through the kvstore\n\t * interface.\n\t *\n\t * The mm heap managed region cannot include the hstore metadata area, as\n\t * that would allow the allocator to use the area for memory allocation.\n\t *\n\t * Therefore, heap_mr_ephemeral keeps its own copy of the managed regions.\n\t */\n\tnupm::region_descriptor _managed_regions;\nprotected:\n\tusing heap_ephemeral::_alloc_mutex;\n\nprotected:\n\tusing hist_type = util::histogram_log2<std::size_t>;\n\thist_type _hist_alloc;\n\thist_type _hist_inject;\n\thist_type _hist_free;\nprivate:\n\t/* Rca_LB seems not to allocate at or above about 2GiB. Limit reporting to 16 GiB. */\n\tstatic constexpr unsigned hist_report_upper_bound = 24U;\n\tstatic constexpr unsigned log_min_alignment = 3U; /* log (sizeof(void *)) */\n\tstatic_assert(sizeof(void *) == 1U << log_min_alignment, \"log_min_alignment does not match sizeof(void *)\");\n\nprotected:\n\tvirtual void add_managed_region_to_heap(byte_span r_heap) = 0;\npublic:\n\ttemplate <bool B>\n\t\tvoid write_hist(const byte_span pool_) const\n\t\t{\n\t\t\tstatic bool suppress = false;\n\t\t\tif ( ! suppress )\n\t\t\t{\n\t\t\t\thop_hash_log<B>::write(LOG_LOCATION, \"pool \", ::base(pool_));\n\t\t\t\tstd::size_t lower_bound = 0;\n\t\t\t\tauto limit = std::min(std::size_t(hist_report_upper_bound), _hist_alloc.data().size());\n\t\t\t\tfor ( unsigned i = log_min_alignment; i != limit; ++i )\n\t\t\t\t{\n\t\t\t\t\tconst std::size_t upper_bound = 1ULL << i;\n\t\t\t\t\thop_hash_log<B>::write(LOG_LOCATION\n\t\t\t\t\t\t, \"[\", lower_bound, \"..\", upper_bound, \"): \"\n\t\t\t\t\t\t, _hist_alloc.data()[i], \" \", _hist_inject.data()[i], \" \", _hist_free.data()[i]\n\t\t\t\t\t\t, \" \"\n\t\t\t\t\t);\n\t\t\t\t\tlower_bound = upper_bound;\n\t\t\t\t}\n\t\t\t\tsuppress = true;\n\t\t\t}\n\t\t}\n\n\tusing common::log_source::debug_level;\n\texplicit heap_mm_ephemeral(\n\t\tunsigned debug_level\n\t\t, nupm::region_descriptor managed_regions\n\t);\n\tvirtual ~heap_mm_ephemeral() {}\n\n\tvirtual std::size_t allocated() const = 0;\n\tvirtual std::size_t capacity() const = 0;\n\n\tvirtual void allocate(persistent_t<void *> &p, std::size_t sz, std::size_t alignment) = 0;\n\tvirtual std::size_t free(persistent_t<void *> &p_, std::size_t sz_) = 0;\n\tvirtual void free_tracked(const void *p, std::size_t sz) = 0;\n\n\tnupm::region_descriptor get_managed_regions() const { return _managed_regions; }\n\tnupm::region_descriptor set_managed_regions(nupm::region_descriptor n)\n\t{\n\t\tusing std::swap;\n\t\tswap(n, _managed_regions);\n\t\treturn n;\n\t}\n\tvoid add_managed_region(byte_span r_full, byte_span r_heap);\n\tvoid reconstitute_managed_region(\n\t\tconst byte_span r_full\n\t\t, const byte_span r_heap\n\t\t, ccpm::ownership_callback_t f\n\t);\n\tvirtual void reconstitute_managed_region_to_heap(byte_span r_heap, ccpm::ownership_callback_t f) = 0;\n\tvirtual bool is_crash_consistent() const = 0;\n\tvirtual bool can_reconstitute() const = 0;\n};\n\n#endif\n", "meta": {"hexsha": "0709690f47969b99c824ab37e8e937ab4bbeba0c", "size": 4237, "ext": "h", "lang": "C", "max_stars_repo_path": "src/components/store/hstore/src/heap_mm_ephemeral.h", "max_stars_repo_name": "omriarad/mcas", "max_stars_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 60.0, "max_stars_repo_stars_event_min_datetime": "2020-04-28T08:15:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T10:35:15.000Z", "max_issues_repo_path": "src/components/store/hstore/src/heap_mm_ephemeral.h", "max_issues_repo_name": "omriarad/mcas", "max_issues_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 66.0, "max_issues_repo_issues_event_min_datetime": "2020-09-03T23:40:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T20:34:52.000Z", "max_forks_repo_path": "src/components/store/hstore/src/heap_mm_ephemeral.h", "max_forks_repo_name": "omriarad/mcas", "max_forks_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2019-11-02T06:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T01:56:42.000Z", "avg_line_length": 33.3622047244, "max_line_length": 109, "alphanum_fraction": 0.7328298324, "num_tokens": 1105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.27512971193602087, "lm_q2_score": 0.024798159024422405, "lm_q1q2_score": 0.006822710348932973}}
{"text": "/* $Id$        */\n/*--------------------------------------------------------------------*/\n/*;  Copyright (C) 2006-2013                                          */\n/*;  Associated Universities, Inc. Washington DC, USA.                */\n/*;                                                                   */\n/*;  This program is free software; you can redistribute it and/or    */\n/*;  modify it under the terms of the GNU General Public License as   */\n/*;  published by the Free Software Foundation; either version 2 of   */\n/*;  the License, or (at your option) any later version.              */\n/*;                                                                   */\n/*;  This program is distributed in the hope that it will be useful,  */\n/*;  but WITHOUT ANY WARRANTY; without even the implied warranty of   */\n/*;  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the    */\n/*;  GNU General Public License for more details.                     */\n/*;                                                                   */\n/*;  You should have received a copy of the GNU General Public        */\n/*;  License along with this program; if not, write to the Free       */\n/*;  Software Foundation, Inc., 675 Massachusetts Ave, Cambridge,     */\n/*;  MA 02139, USA.                                                   */\n/*;                                                                   */\n/*;Correspondence about this software should be addressed as follows: */\n/*;         Internet email: bcotton@nrao.edu.                         */\n/*;         Postal address: William Cotton                            */\n/*;                         National Radio Astronomy Observatory      */\n/*;                         520 Edgemont Road                         */\n/*;                         Charlottesville, VA 22903-2475 USA        */\n/*--------------------------------------------------------------------*/\n\n#include \"ObitIonCal.h\"\n#include \"ObitTableVZ.h\"\n#include \"ObitSkyGeom.h\"\n#include \"ObitPBUtil.h\"\n#include \"ObitZernike.h\"\n#include \"ObitUVUtil.h\"\n#include \"ObitDConCleanVis.h\"\n#include \"ObitTableNX.h\"\n#include \"ObitIoN2SolNTable.h\"\n#include \"ObitTableNI.h\"\n#include \"ObitMem.h\"\n#include \"ObitUtil.h\"\n#if HAVE_GSL==1  /* GSL stuff */\n#include <gsl/gsl_multifit.h>\n#endif /* GSL stuff */\n\n/*----------------Obit: Merx mollis mortibus nuper ------------------*/\n/**\n * \\file ObitIonCal.c\n * ObitIonCal class function definitions.\n * This class is derived from the Obit base class.\n */\n\n/** name of the class defined in this file */\nstatic gchar *myClassName = \"ObitIonCal\";\n\n/** Function to obtain parent ClassInfo */\nstatic ObitGetClassFP ObitParentGetClass = ObitGetClass;\n\n/* Catalog list management */\n/** Calibrator list element structure */\ntypedef struct { \n  /**  catalog celestial position */\n  odouble ra, dec;\n  /** Offset on Zernike plane (deg) */\n  ofloat ZernXY[2];\n  /** shift from reference position */\n  ofloat shift[2];\n  /** expected pixel in reference image */\n  ofloat pixel[2];\n  /** Estimated catalog flux density */\n  ofloat flux;\n  /** measured offset from expected position (deg) */\n  ofloat offset[2];\n  /** measured peak flux density (image units) */\n  ofloat peak;\n  /** measured integrated flux density (image units)  */\n  ofloat fint;\n  /** determined weight */\n  ofloat wt;\n  /** catalog quality code */\n  olong qual;\n  /** calibrator number (0-rel) */\n  olong calNo;\n  /** epoch number */\n  olong epoch;\n}  CalListElem; \n  \n/** Private: CalListElem Constructor  */ \nstatic CalListElem* \nnewCalListElem (odouble ra, odouble dec, ofloat ZernXy[2], ofloat shift[2],\n\t\tofloat pixel[2], ofloat flux, ofloat offset[2],\n\t\tofloat peak, ofloat fint,ofloat wt, olong qual,\n\t\tolong calNo, olong epoch); \n\n/**  Private: Update contents of an CalListElem */\nstatic void\nCalListElemUpdate (CalListElem *elem, odouble ra, odouble dec, \n\t\t   ofloat ZernXY[2], ofloat shift[2], ofloat pixel[2], \n\t\t   ofloat flux, ofloat offset[2], ofloat peak, ofloat fint, \n\t\t   ofloat wt, olong qual, olong calNo, olong epoch); \n\n/**  Private: Print contents of an CalListElem */\nstatic void\nCalListElemPrint (CalListElem *elem, FILE *file);\n\n/** Private: CalListElem Destructor  */ \nstatic void freeCalListElem(CalListElem *me); \n  \n/** CalList structure. */\ntypedef struct {\n  /** Number of entries */\n  olong number;\n  /** glib singly linked list */\n  GSList* list;\n} CalList;\n\n/** Private: CalList structure.constructor. */\nstatic CalList* newCalList (void);\n \n/** Private: Add an CalListElem to the CalList  */\nstatic void CalListAdd (CalList *in, CalListElem *elem);\n\n/** Private: Remove a CalListElem from the list. */\nstatic void CalListRemove (CalList *in, CalListElem *elem);\n\n/** Private: Remove all items from the list. */\nstatic void CalListClear (CalList *in);\n\n/** Private: Remove all items from the list. */\nstatic void CalListPrint (CalList *in, FILE *file);\n\n/** Private: destructor. */\nstatic void freeCalList (CalList *in);\n\n/**\n * ClassInfo structure ObitIonCalClassInfo.\n * This structure is used by class objects to access class functions.\n */\nstatic ObitIonCalClassInfo myClassInfo = {FALSE};\n\n/*--------------- File Global Variables  ----------------*/\n\n\n/*---------------Private function prototypes----------------*/\n/** Private: Initialize newly instantiated object. */\nvoid  ObitIonCalInit  (gpointer in);\n\n/** Private: Deallocate members. */\nvoid  ObitIonCalClear (gpointer in);\n\n/** Private: Set Class function pointers. */\nstatic void ObitIonCalClassInfoDefFn (gpointer inClass);\n\n/** Private: Fit positions of calibrator(s) in an image. */\nstatic void CalPosFit (ObitImage *image, ofloat inPixel[2], olong* imsi, \n\t\t       ofloat pixelOff[2], ofloat* souflx, ofloat* souint,\n\t\t       ObitErr *err);\n\n/** Private: CLEAN failed - mark observations bad. */\nstatic void CalBadTime (ObitIonCal *in, ObitImageMosaic* mosaic, \n\t\t\tolong epoch, ObitErr *err);\n\n/** Private: Lookup calibrators in an image from a catalog. */\nstatic void \nFindCalImage (ObitImage *image, gchar *Catalog, olong catDisk, \n\t      ofloat OutlierFlux, ofloat OutlierSI, olong qual, ofloat AntDiam,\n\t      CalList *calList, olong prtLv, ObitErr *err);\n\n/** Private: Fit Zernike model for single time */\nstatic ofloat\nIonFit1 (olong nobs, olong* isou, ofloat* x, ofloat* y, \n\t ofloat* dx, ofloat* dy, ofloat* w, \n\t olong* ncoef, ofloat* coef, olong prtLv, ObitErr *err);\n\n/** Private: Edit data for single time */\nstatic gboolean\nIonEdit1 (olong nobs, olong* isou, ofloat* x, ofloat* y, \n\t  ofloat* dx, ofloat* dy, ofloat* w, \n\t  ofloat MaxRMS, olong ncoef, ofloat* coef, olong prtLv, \n\t  ObitErr *err);\n\n/** Private: Determine timerange for next segment */\nstatic gboolean NextTime (ObitTableNX *NXtab, ofloat solInt, \n\t\t\t  ofloat timer[2], olong* suba, ObitErr* err);\n\n/** Private: Get calibrator list from an ImageMosaic */\nstatic void \nFindCalMosaic (ObitIonCal *in, ObitImageMosaic *mosaic, \n\t      CalList *calList, olong prtLv, ObitErr *err);\n\n/** Private: Get calibrator info from catalog */\nstatic void \nLookupCals (ObitIonCal *in, ObitImageMosaic *mosaic, CalList *calList, \n\t    olong prtLv, ObitErr *err);\n\n/** Private: Filter and fit multiepoch offset measurements */\nstatic ObitTableNI* \nFitAll (ObitIonCal *in, olong ncoef, \n\tolong nEpoch, ofloat *timeEpoch, ofloat *timeIEpoch, olong *subaEpoch, \n\todouble refFreq, ofloat *seeing, ObitErr* err); \n\n/** Private: convert timerange to a printable string. */\nstatic void TR2String (ofloat timer[2], gchar *msgBuf);\n\n/* Private: Fit time sequence of Zernike models */\nstatic ObitTableNI* \ndoIonFitAll (ObitUV *inUV, ofloat MaxRMS, ofloat MinRat, ofloat FCStrong, gboolean doINEdit, \n\t     olong ncoef, olong nsou, olong* isou, ofloat* x, ofloat* y, \n\t     olong nTime, ofloat* Time, ofloat* TimeI, olong* isuba, \n\t     olong n, olong* iTime, ofloat* xoff, ofloat* yoff, \n\t     ofloat* flux, ofloat *wt, olong* flqual, ofloat* sint, \n\t     olong prtLv, odouble refFreq, ofloat* totRMS, ObitErr* err);\n\n/* Private: Initilize Zernike time series */\nstatic gboolean \ninitIonModel (olong nobs, olong nsou, olong nTime, olong maxcoe, olong* isou, \n\t      olong* iTime, ofloat*  x, ofloat* y, ofloat* dx, ofloat* dy, \n\t      ofloat* w, olong*  flqual, olong* ncoef, gboolean* gotsou, \n\t      gboolean* fitsou, ofloat* soffx, ofloat* soffy, ofloat** coef, \n\t      olong prtLv, ObitErr* err);\n\n/* Private: Least Squares Fit Zernike time series and source offsets */\nstatic void \nFitIonSeries (olong nobs, olong nsou, olong nTime, olong maxcoe, olong* isou, olong* iTime, \n\t      ofloat*  x, ofloat* y, ofloat* dx, ofloat* dy, ofloat* w, olong*  ncoef, \n\t      gboolean* gotsou, gboolean* fitsou, ofloat* soffx, ofloat* soffy, \n\t      ofloat** coef, ofloat* trms, olong prtLv, ObitErr* err) ;\n\n/* Private: Edit data based on Zernike time series  */\nstatic gboolean \nIonEditSeries (olong nobs, olong nsou, olong nTime, \n\t       olong maxcoe, olong* isou, olong* iTime, ofloat*  x, ofloat* y, \n\t       ofloat* dx, ofloat* dy, ofloat* w, ofloat MaxRMS, olong* ncoef, \n\t       ofloat* soffx, ofloat* soffy, ofloat** coef, olong prtLv, ObitErr* err);\n\n/* Private: Time series editing based on amplitudes */\nstatic gboolean \nIonEditAmp (olong nobs, olong nsou, olong nTime, olong* isou, olong* iTime, \n\t    ofloat MinRat, ofloat FCStrong, ofloat*  flux, olong* ncoef, ofloat* wt, \n\t    olong prtLv, ObitErr* err);\n\n/* Private: Edit data for a given source based on Zernike time series */\nstatic void \nIonEditSource (olong source, olong nobs, olong nTime, olong maxcoe, olong nsou, \n\t       olong* isou, olong* iTime, ofloat*  x, ofloat* y, \n\t       ofloat* dx, ofloat* dy, ofloat* w, ofloat MaxRMS, olong* ncoef, \n\t       ofloat* soffx, ofloat* soffy, ofloat** coef, \n\t       ofloat *gdx, ofloat *gdy, olong* stoss, olong prtLv, ObitErr* err);\n\n\n/* Private: Get minimum fluxes for strong (required) calibrators */\nstatic ofloat* \ngetStrong (olong nobs, olong nsou, olong nTime, olong* isou, olong* iTime, \n\t   ofloat MinRat, ofloat FCStrong, ofloat*  flux, olong prtLv, \n\t   ObitErr* err);\n\nstatic void PosImage (ObitImage *image, ofloat pixel[2], ofloat minflux, \n\t\t      ofloat mxcdis, olong FitSize, \n\t\t      ofloat offset[2], ofloat *peak, ofloat *fint, ObitErr *err);\nstatic olong pfit (ofloat a[9][9], ofloat *s, ofloat dx[2], ofloat fblank);\nstatic olong momnt (ofloat ara[9][9], ofloat x, ofloat y, olong nx, olong ny, \n\t\t   ofloat momar[6], ofloat fblank);\nstatic void matvmul (ofloat m[3][3], ofloat vi[3], ofloat vo[3], olong n);\nstatic void rd2zer (odouble ra, odouble dec, ofloat xshift, ofloat yshift, \n\t\t    ofloat* xzer, ofloat* yzer, olong *ierr);\nstatic void zerrot (odouble ra, odouble dec, ofloat xshift, ofloat yshift,\n\t\t    ofloat* rotate);\nstatic void  FitZernike (olong nobs, olong* isou, ofloat *x, ofloat *y, \n\t\t\t ofloat *dx, ofloat *dy, ofloat *wt, \n\t\t\t olong nZern, ofloat *coef);\n\n/*----------------------Public functions---------------------------*/\n/**\n * Constructor.\n * Initializes class if needed on first call.\n * \\param name An optional name for the object.\n * \\return the new object.\n */\nObitIonCal* newObitIonCal (gchar* name)\n{\n  ObitIonCal* out;\n\n  /* Class initialization if needed */\n  if (!myClassInfo.initialized) ObitIonCalClassInit();\n\n  /* allocate/init structure */\n  out = g_malloc0(sizeof(ObitIonCal));\n\n  /* initialize values */\n  if (name!=NULL) out->name = g_strdup(name);\n  else out->name = g_strdup(\"Noname\");\n\n  /* set ClassInfo */\n  out->ClassInfo = (gpointer)&myClassInfo;\n\n  /* initialize other stuff */\n  ObitIonCalInit((gpointer)out);\n\n return out;\n} /* end newObitIonCal */\n\n/**\n * Returns ClassInfo pointer for the class.\n * \\return pointer to the class structure.\n */\ngconstpointer ObitIonCalGetClass (void)\n{\n  /* Class initialization if needed */\n  if (!myClassInfo.initialized) ObitIonCalClassInit();\n\n  return (gconstpointer)&myClassInfo;\n} /* end ObitIonCalGetClass */\n\n/**\n * Make a deep copy of an ObitIonCal.\n * \\param in  The object to copy\n * \\param out An existing object pointer for output or NULL if none exists.\n * \\param err Obit error stack object.\n * \\return pointer to the new object.\n */\nObitIonCal* ObitIonCalCopy  (ObitIonCal *in, ObitIonCal *out, ObitErr *err)\n{\n  const ObitClassInfo *ParentClass;\n  gboolean oldExist;\n  gchar *outName;\n\n  /* error checks */\n  g_assert (ObitErrIsA(err));\n  if (err->error) return out;\n  g_assert (ObitIsA(in, &myClassInfo));\n  if (out) g_assert (ObitIsA(out, &myClassInfo));\n\n  /* Create if it doesn't exist */\n  oldExist = out!=NULL;\n  if (!oldExist) {\n    /* derive object name */\n    outName = g_strconcat (\"Copy: \",in->name,NULL);\n    out = newObitIonCal(outName);\n    g_free(outName);\n  }\n\n  /* deep copy any base class members */\n  ParentClass = myClassInfo.ParentClass;\n  g_assert ((ParentClass!=NULL) && (ParentClass->ObitCopy!=NULL));\n  ParentClass->ObitCopy (in, out, err);\n\n  /*  copy this class */\n  out->myData = ObitUVRef(in->myData);\n\n  return out;\n} /* end ObitIonCalCopy */\n\n/**\n * Make a copy of a object but do not copy the actual data\n * This is useful to create an IonCal similar to the input one.\n * \\param in  The object to copy\n * \\param out An existing object pointer for output, must be defined.\n * \\param err Obit error stack object.\n */\nvoid ObitIonCalClone  (ObitIonCal *in, ObitIonCal *out, ObitErr *err)\n{\n  const ObitClassInfo *ParentClass;\n\n  /* error checks */\n  g_assert (ObitErrIsA(err));\n  if (err->error) return;\n  g_assert (ObitIsA(in, &myClassInfo));\n  g_assert (ObitIsA(out, &myClassInfo));\n\n  /* deep copy any base class members */\n  ParentClass = myClassInfo.ParentClass;\n  g_assert ((ParentClass!=NULL) && (ParentClass->ObitCopy!=NULL));\n  ParentClass->ObitCopy (in, out, err);\n\n  /*  copy this class */\n  out->myData = ObitUVRef(in->myData);\n\n} /* end ObitIonCalClone */\n\n/**\n * Creates an ObitIonCal \n * \\param name  An optional name for the object.\n * \\return the new object.\n */\nObitIonCal* ObitIonCalCreate (gchar* name)\n{\n  ObitIonCal* out;\n\n  /* Create basic structure */\n  out = newObitIonCal (name);\n\n  return out;\n} /* end ObitIonCalCreate */\n\n/**\n * Attach UV data, unreferences any old data\n * \\param in    Object to attach UV data to\n * \\param inUV  UV data to attach\n */\nvoid ObitIonCalSetData (ObitIonCal *in, ObitUV *inUV)\n{\n  in->myData = ObitUVUnref(in->myData);  /* out with the old */\n  in->myData = ObitUVRef(inUV);          /* in with the new */\n} /* end ObitIonCalSetData */\n\n/**\n * Fills the calList member with a list of calibrator sources \n * selected from a given catalog whose position are inside the\n * field of view of image.\n * Previous contents of the CalList are cleared\n * \\param in   IonCal object \n *   Control parameters are on the info member.\n * \\li Catalog     OBIT_char  (?,1,1)  AIPSVZ format FITS catalog for defining outliers, \n *                 'Default' or blank = use default catalog.\n * \\li catDisk     OBIT_int   (1,1,1) FITS disk for catalog [def 1]\n * \\li OutlierFlux OBIT_float (1,1,1)  Minimum estimated flux density include cal. fields\n *                  from Catalog. [default 0.1 Jy ]\n * \\li OutlierSI   OBIT_float (1,1,1) Spectral index to use to convert catalog flux \n *                   density to observed frequency.  [default = -0.75]\n * \\li MaxQual     OBIT_int   (1,1,1) Max. cal. quality code [def 1]\n * \\li prtLv       OBIT_int   (1,1,1) Print level >=2 => give list [def 0]\n *\n * calList Calibrator list each element of which has:\n * \\li ra      position RA (deg) of calibrators\n * \\li dec     position Dec (deg) of calibrators\n * \\li shift   Offset in field [x,y] on unit Zernike circle of position\n * \\li pixel   Expected pixel in reference image\n * \\li flux    Estimated catalog flux density \n * \\li offset  Measured offset [x,y] from expected position (deg)\n * \\li peak    Measured peak flux density (image units)\n * \\li fint    Measured integrated flux density (image units)\n * \\li wt      Determined weight\n * \\li qual    Catalog quality code\n * \\param image   Image object \n * \\param err     Error stack\n */\nvoid ObitIonCalFindImage (ObitIonCal *in, ObitImage* image, ObitErr* err)  \n{\n  CalList *calList;\n  gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};\n  ObitInfoType type;\n  gchar Catalog[257];\n  olong catDisk, qual, prtLv;\n  ofloat OutlierFlux, OutlierSI, AntDiam;\n  gchar *routine = \"ObitIonCalFindImage\";\n\n  /* Error checks */\n  g_assert(ObitErrIsA(err));\n  if (err->error) return ;  /* previous error? */\n  g_assert(ObitIonCalIsA(in));\n\n   /* Clear any entries in calList */\n  calList = (CalList*)in->calList;\n  CalListClear (calList);\n\n  /* Control information. */\n  sprintf (Catalog, \"Default\");\n  ObitInfoListGetTest(in->info, \"Catalog\", &type, dim,  Catalog);\n  if (err->error) Obit_traceback_msg (err, routine, in->name);\n  if (!strncmp(Catalog, \"    \", 4)) sprintf (Catalog, \"Default\");\n  if (!strncmp(Catalog, \"Default\", 7)) sprintf (Catalog, \"NVSSVZ.FIT\");\n  catDisk = 1;\n  ObitInfoListGetTest(in->info, \"CatDisk\",   &type, dim, &catDisk);\n  OutlierFlux = 1.0;\n  ObitInfoListGetTest(in->info, \"OutlierFlux\", &type, dim, &OutlierFlux);\n  OutlierSI = -0.75;\n  ObitInfoListGetTest(in->info, \"OutlierSI\", &type, dim, &OutlierSI);\n  AntDiam = 25.0;\n  ObitInfoListGetTest(in->info, \"AntDiam\", &type, dim, &AntDiam);\n  qual = 1;\n  ObitInfoListGetTest(in->info, \"MaxQual\",   &type, dim, &qual);\n  prtLv = 0;\n  ObitInfoListGetTest(in->info, \"prtLv\",   &type, dim, &prtLv);\n\n  /* Search Catalog */\n  FindCalImage (image, Catalog, catDisk, OutlierFlux, OutlierSI, qual, \n\t\tAntDiam, calList, prtLv, err);\n  if (err->error) Obit_traceback_msg (err, routine, in->name);\n} /* end ObitIonCalFindImage */\n\n/**\n * Determines calibrator position offsets from a single image.\n * Given an image containing calibrator sources, return fitted fluxes \n * and position offsets.  \n * Resultant positions are all referred to a tangent plane at the  \n * pointing center, this is referred to as the Zernike plane as this  \n * plane will be used to fit the phase screen.  The \"Zernike Unit  \n * Circle\" defines the phase screen.  Source position offsets are in  \n * the X and Y (RA, Dec) as defined by this plane.  \n * Routine translated from the AIPSish CALPOS.FOR/CALPOS  \n * \\param in   IonCal object \n *   Control parameters are on the info member.\n * \\li \"FitDist\"  OBIT_int   (1,1,1) dist, from expected location to search \n *                                   asec [10 pixels]\n * \\li \"MinPeak\"  OBIT_float (1,1,1) Min. acceptable image peak (Jy) [1.0]\n * \\li \"MaxDist\"  OBIT_float (1,1,1) Max. distance (deg/10) to accept calibrator [1.]\n * \\li \"MaxWt\"    OBIT_float (1,1,1) Max. weight [10.0]\n * \\li prtLv      OBIT_int   (1,1,1) Print level >=1 => give fits\n * \\param image   Image object \n * \\param calList Calibrator list each element of which has:\n * \\li ra      position RA (deg) of calibrators\n * \\li dec     position Dec (deg) of calibrators\n * \\li shift   Offset in field [x,y] on unit Zernike circle of position\n * \\li pixel   Expected pixel in reference image\n * \\li flux    Estimated catalog flux density \n * \\li offset  Measured offset [x,y] from expected position (deg)\n * \\li peak    Measured peak flux density (image units)\n * \\li fint    Measured integrated flux density (image units)\n * \\li wt      Determined weight\n * \\li qual    Catalog quality code\n * \\param err     Error stack\n */\nvoid ObitIonCalPosMul (ObitIonCal *in, ObitImage* image, ObitErr* err)  \n{\n  olong   i, FitSize, good, imsi[2], epoch=1, prtLv;\n  olong blc[IM_MAXDIM] = {1,1,1,1,1,1,1};\n  olong trc[IM_MAXDIM] = {0,0,0,0,0,0,0};\n  ofloat FitDist, flux;\n  ofloat mxcdis,maxwt;\n  gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};\n  ObitInfoType type;\n  ObitIOSize IOBy;\n  gboolean bad;\n  ofloat offset[2], peak, fint,wt, dist;\n  ofloat area, pixelOff[2];\n  CalListElem *elem=NULL, *nelem=NULL;\n  GSList  *tmp;\n  CalList *calList;\n  gchar *routine = \"ObitIonCalPosMul\";\n\n  /* Error checks */\n  g_assert(ObitErrIsA(err));\n  if (err->error) return ;  /* previous error? */\n  g_assert(ObitIonCalIsA(in));\n\n  calList = (CalList*)in->calList;\n\n  /* Control information. */\n  maxwt = 10.0;\n  ObitInfoListGetTest(in->info, \"MaxWt\",   &type, dim, &maxwt);\n  flux = 1.0;\n  ObitInfoListGetTest(in->info, \"MinPeak\", &type, dim, &flux);\n  mxcdis = 1.0;\n  ObitInfoListGetTest(in->info, \"MaxDist\", &type, dim, &mxcdis);\n  FitDist = 0.0;\n  ObitInfoListGetTest(in->info, \"FitDist\", &type, dim, &FitDist);\n  prtLv = 0;\n  ObitInfoListGetTest(in->info, \"prtLv\",   &type, dim, &prtLv);\n\n  /* Open and read image full plane */\n  IOBy = OBIT_IO_byPlane;\n  dim[0] = 1;\n  ObitInfoListPut (image->info, \"IOBy\", OBIT_long, dim, &IOBy, err);\n  dim[0] = 7;\n  for (i=0; i<IM_MAXDIM; i++) {blc[i] = 1; trc[i] = 0;}\n  ObitInfoListPut (image->info, \"BLC\", OBIT_long, dim, blc, err); \n  ObitInfoListPut (image->info, \"TRC\", OBIT_long, dim, trc, err);\n  image->extBuffer = FALSE;  /* Make sure it has buffer */\n  if (err->error) Obit_traceback_msg (err, routine, image->name);\n  if ((ObitImageOpen (image, OBIT_IO_ReadOnly, err) \n       != OBIT_IO_OK) || (err->error>0)) { /* error test */\n    Obit_log_error(err, OBIT_Error, \n\t\t   \"ERROR opening image %s\", image->name);\n    return;\n  }\n  ObitImageRead (image, NULL, err);\n  if (err->error) Obit_traceback_msg (err, routine, image->name);\n\n  /* Convert FitDist to pixels */\n  if (FitDist<=0.0) FitDist = 10.0 * fabs(image->myDesc->cdelt[0]);\n  FitSize = (olong)((FitDist / fabs(image->myDesc->cdelt[0]))+0.5);\n  FitSize = MAX (10, FitSize);\n  imsi[0] = imsi[1] = FitSize;\n\n  /* Loop over sources */\n  good = 0;\n  tmp = calList->list;\n  while (tmp!=NULL) {   /* loop 100 */\n    elem = (CalListElem*)tmp->data;\n    /* if find epoch > 0 then quit loop */\n    if (elem->epoch>0) break;\n    bad = FALSE;\n\n    /* fit source */\n    CalPosFit (image, elem->pixel, imsi, pixelOff, &peak, &fint, err);\n    if (err->error) Obit_traceback_msg (err, routine, image->name);\n\n    /* find anything? */\n    if (peak<flux) { /* Nope */\n      bad = TRUE;\n    } else { /* yes */\n\n      /* Offset */\n      offset[0] = pixelOff[0] * image->myDesc->cdelt[0];\n      offset[1] = pixelOff[1] * image->myDesc->cdelt[1];\n\n      /* Normalize integrated flux by beam area in pixels */\n      area = 1.1331 * image->myDesc->beamMaj * image->myDesc->beamMin /  \n\t(fabs (image->myDesc->cdelt[0]) * fabs (image->myDesc->cdelt[1])) ;\n      if (area  <  0.001) area = 1.0;\n      fint /= area;\n\n      /* Within maximum distance? */\n      dist = sqrt(elem->ZernXY[0]*elem->ZernXY[0] + elem->ZernXY[1]*elem->ZernXY[1]);\n      if (dist <= mxcdis)  wt = MIN (maxwt, peak);\n      else wt = 0.0;\n      if (bad) wt = 0.0;\n\n      /* Update CalList */\n      nelem = newCalListElem (elem->ra, elem->dec, elem->ZernXY, elem->shift, \n\t\t\t      elem->pixel, elem->flux, offset, peak, fint, wt, \n\t\t\t      elem->qual, elem->calNo, epoch);\n      CalListAdd (calList, nelem);\n      good++;  /* This one OK */\n\n      /* diagnostics? */\n      if (prtLv>=1) {\n\tObit_log_error(err, OBIT_InfoErr, \n\t\t       \"Fit E=%5d C=%5d Z= %7.4f %7.4f off=%7.2f %7.2f Peak=%6.2f int=%6.2f qual=%d\",\n\t\t       epoch, elem->calNo, elem->ZernXY[0], elem->ZernXY[1], \n\t\t       offset[0]*3600.0, offset[1]*3600.0, peak, fint, elem->qual);\n      }\n    } /* End if detected */\n\n    tmp = g_slist_next(tmp);  /* next item in list */\n } /* end loop  L100: over calibrator*/\n\n  /* Close image */\n  ObitImageClose (image, err);\n  if (err->error) Obit_traceback_msg (err, routine, image->name);\n  image->image = ObitImageUnref(image->image);   /* Free buffer */\n\n  /* tell how many */\n  Obit_log_error(err, OBIT_InfoErr, \"%s: Fitted %d calibrator offsets\", \n\t\t routine, good);\n\n} /* end of routine ObitIonCalPosMul */ \n\n/**\n * Fit Zernike model to single epoch image distortion\n * Uses fitted data in calList member.\n * Iteratively edits most discrepant point if needed to get RMS \n * residual down to MaxRMS.\n * \\param in   IonCal object \n *   Control parameters are on the info member.\n * \\li \"nZern\"  OBIT_int   (1,1,1) Zernike polynomial order requested [def 5]\n * \\li \"MaxRMS\" OBIT_float (1,1,1) Target RMS residual (asec), default 10 asec\n * \\li prtLv    OBIT_int   (1,1,1) Print level >=3 => give fitting diagnostics\n *                                 [def. 0]\n * \\param epoch   1-rel time index i measurements\n * \\param coef    [out] Fitted coefficients\n * \\param err     Error stack\n * \\return RMS residual in deg, -1 on error\n */\nofloat ObitIonCalFit1 (ObitIonCal *in, olong epoch, ofloat *coef, \n\t\t       ObitErr* err)  \n{\n  CalListElem *elem=NULL;\n  ofloat out = -1.0;\n  GSList  *tmp;\n  olong nZern, count, badCount, prtLv;\n  gboolean doMore;\n  ofloat rms, MaxRMS, MaxRMS2;\n  ofloat *x=NULL, *y=NULL, *dx=NULL, *dy=NULL, *w=NULL;\n  olong *isou=NULL;\n  gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};\n  ObitInfoType type;\n  CalList *calList;\n  gchar *routine = \"ObitIonCalFit1\";\n\n  /* Error checks */\n  g_assert(ObitErrIsA(err));\n  if (err->error) return out;  /* previous error? */\n  g_assert(ObitIonCalIsA(in));\n\n  calList = (CalList*)in->calList;\n\n  /* Control information. */\n  nZern = 5;\n  ObitInfoListGetTest(in->info, \"nZern\",   &type, dim, &nZern);\n  /* Coerce to range [2,17] */\n  nZern = MAX (2, MIN (17, nZern));\n  MaxRMS = 10.0;\n  ObitInfoListGetTest(in->info, \"MaxRMS\",   &type, dim, &MaxRMS);\n  MaxRMS /= 3600.0;  /* to deg */\n  MaxRMS2 = 2.0 * MaxRMS; /* relax for finding sources */\n  prtLv = 0;\n  ObitInfoListGetTest(in->info, \"prtLv\",   &type, dim, &prtLv);\n\n  /* How many measurements at epoch epoch? */\n  count = 0;\n  /* Loop over calList */\n  tmp = calList->list;\n  while (tmp!=NULL) {\n    elem = (CalListElem*)tmp->data;\n    if (elem->epoch==epoch) count++;\n    if (elem->epoch>epoch) break; /* done? */\n    tmp = g_slist_next(tmp);  /* next item in list */\n  } \n\n  /* allocate memory */\n  x  = g_malloc(count*sizeof(ofloat));\n  y  = g_malloc(count*sizeof(ofloat));\n  dx = g_malloc(count*sizeof(ofloat));\n  dy = g_malloc(count*sizeof(ofloat));\n  w  = g_malloc(count*sizeof(ofloat));\n  isou = g_malloc(count*sizeof(olong));\n\n  /* Copy data to arrays - Loop over calList */\n  tmp = calList->list;\n  count = 0;\n  while (tmp!=NULL) {\n    elem = (CalListElem*)tmp->data;\n    if (elem->epoch==epoch) {\n      /* Unit circle = 10 deg */\n      x[count]    = elem->ZernXY[0];\n      y[count]    = elem->ZernXY[1];\n      dx[count]   = elem->offset[0];\n      dy[count]   = elem->offset[1];\n      w[count]    = elem->wt;\n      isou[count] = count;\n      count++;\n    }\n    if (elem->epoch>epoch) break; /* done? */\n    tmp = g_slist_next(tmp);  /* next item in list */\n  } \n\n  /* Fit model */\n  doMore = TRUE;\n  badCount = 0;\n  while (doMore) {\n    rms = IonFit1 (count, isou, x, y, dx, dy, w, &nZern, coef, prtLv, err);\n    if (rms<MaxRMS2) break;\n    doMore = IonEdit1 (count, isou, x, y, dx, dy, w, MaxRMS2, nZern, coef, prtLv, err);\n    if (doMore) badCount++;\n  }\n\n  /* tell how many flagged */\n  Obit_log_error(err, OBIT_InfoErr, \"%s: Flagged %d of %d calibrators\", \n\t\t routine, badCount, count);\n\n  Obit_log_error(err, OBIT_InfoErr, \"%s: Final RMS %f\", \n\t\t routine, 3600.0*rms);\n  /* cleanup */\n  if (x)    g_free(x);\n  if (y)    g_free(y);\n  if (dy)   g_free(dx);\n  if (dy)   g_free(dy);\n  if (w)    g_free(w);\n  if (isou) g_free(isou);\n\n  return rms;\n} /* end of routine ObitIonCalFit1 */ \n\n/**\n * Ionospheric calibration  for a uv data set.\n * Loops over time slices, imaging and deconvolving selected fields.  \n * Then determines position offsets and fits an ionospheric model.  \n * Results are stored in an 'NI' table attached to inUV.\n * Current maximum 1024 epochs.\n * Routine translated from the AIPSish IONCAL.FOR/IONCAL  \n * \\param in        IonCal object, must have myData UV data attached.\n *                  If myData is a multisource file, then\n *                  selection (1 source) , calibration and editing controls\n *                  must be set on the info member.\n *   Control parameters on the myData info member.\n * \\li Catalog     OBIT_char  (?,1,1)  AIPSVZ format FITS catalog for defining outliers, \n *                 'Default' or blank = use default catalog.\n * \\li catDisk     OBIT_int   (1,1,1)  FITS disk for catalog [def 1]\n * \\li OutlierDist OBIT_float (1,1,1)  How far from pointing to add calibrators\n * \\li OutlierFlux OBIT_float (1,1,1)  Minimum estimated flux density include outlier fields\n *                                     from Catalog. [default 0.1 Jy ]\n * \\li OutlierSI   OBIT_float (1,1,1)  Spectral index to use to convert catalog flux \n *                                     density to observed frequency.  [default = -0.75]\n * \\li Niter       OBIT_int   (1,1,1)  Max. number of components to clean\n * \\li minFlux     OBIT_float (1,1,1)  Minimum flux density to CLEAN\n * \\li autoWindow  OBIT_boolean (1,1,1)True if autoWindow feature wanted.\n * \\li dispURL     OBIT_string (1,1,1) URL of display server\n * \\li do3D        OBIT_bool (1,1,1)   Use 3D imaging? def TRUE.\n *\n *   Control parameters on the in->info member.\n * \\li nZern       OBIT_int   (1,1,1)  Zernike polynomial order requested [def 5]\n * \\li MaxQual     OBIT_int   (1,1,1)  Max. cal. quality code [def 1]\n * \\li prtLv       OBIT_int   (1,1,1)  Print level >=2 => give list [def 0]\n * \\li MaxRMS      OBIT_float (1,1,1)  Maximum allowable RMS in arcsec. [def 20]\n * \\li MinRat      OBIT_float (1,1,1)  Minimum acceptable ratio to average flux  [def 0.1]\n * \\li FCStrong    OBIT_float (1,1,1)  Min. Flux for strong (required) cal [def big]\n * \\li FitDist     OBIT_int   (1,1,1)  Dist, from expected location to search \n *                                      asec [10 pixels]\n * \\li MinPeak     OBIT_float (1,1,1)  Min. acceptable image peak (Jy) [1.0]\n *                 If not given  OutlierFlux is used\n * \\li MaxDist     OBIT_float (1,1,1)  Max. distance (deg/10) to accept calibrator [1.]\n * \\li MaxWt       OBIT_float (1,1,1)  Max. weight [10.0]\n * \\li doINEdit    OBIT_boolean (1,1,1) If true flag solutions for which the seeing \n *                                     residual could not be determined or exceeds \n *                                     MaxRMS [def TRUE] \n * \\li doSN        OBIT_boolean (1,1,1) If true, convert IN table to an SN table \n *                                     attached to inUV. [def False]\n * \\li solInt      OBIT_float  (1,1,1) Solution interval (min). [def 1]\n * \\param err    Error code: 0 => ok, -1 => all data flagged \n */\nvoid ObitIonCaldoCal (ObitIonCal*in, ObitErr* err)\n{\n  const ObitDConCleanVisClassInfo *ClnClass;\n  gboolean doSN;\n  ofloat   solInt, maxWt, Flux, mxcDis, OutlierFlux;\n  olong     qual, prtLv, cprtLv;\n  olong     ncal,  ncoef, suba;\n  olong    i, ver;\n#define MAXEPOCH 1024   /* Maximum number of epochs */\n  olong     nZern, nEpoch=0, subaEpoch[MAXEPOCH];\n  ofloat   timeEpoch[MAXEPOCH], timeIEpoch[MAXEPOCH]; \n  gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};\n  ObitInfoType type;\n  ofloat MaxRMS, off[2], timer[2] = {-1.0e20, 0.0};\n  odouble refFreq=0.0;\n  ObitUV *inUV = NULL;\n  ObitDConCleanVis* myClean=NULL;\n  ObitImageMosaic* myMosaic=NULL;\n  ObitTableNX *NXtab=NULL;\n  ObitTableSN *SNtab=NULL;\n  ObitTableNI *NItab=NULL;\n  CalList *calList;\n  ofloat FOV, oldFOV, Beam[3], seeing, maxGap;\n  gboolean badTime, *gotit=NULL, Tr=TRUE, Fl=FALSE;;\n  odouble obsra, obsdec;\n  gchar msgtxt[101], *Stokes=\"I   \";\n  /* Parameters to copy from inUV to CLEAN object */\n  gchar *ParmList[] = {\"Niter\", \"minFlux\", \"dispURL\", \"autoWindow\", NULL};\n  /* Parameters to copy from inUV to IonCal object */\n  gchar *IonParmList[] = {\"Catalog\", \"CatDisk\", \"OutlierFlux\", \"OutlierSI\", \n\t\t\t  NULL};\n  gchar *routine = \"ObitIonCaldoCal\";\n\n  /*----------------------------------------------------------------------- */\n  /* Previous error condition? */\n  if (err->error) return ;\n  /* Error checks */\n  inUV = in->myData;   /* data on in */\n  g_assert(ObitUVIsA(inUV));\n  \n  /* Get control parameters */\n  qual = 1;\n  ObitInfoListGetTest(in->info, \"MaxQual\", &type, dim, &qual);\n  prtLv = 0;\n  ObitInfoListGetTest(in->info, \"prtLv\", &type, dim, &prtLv);\n  doSN = FALSE;\n  ObitInfoListGetTest(in->info, \"doSN\", &type, dim, &doSN);\n  solInt = 1.0;\n  ObitInfoListGetTest(in->info, \"solInt\", &type, dim, &solInt);\n  if (solInt<=0.0) solInt = 1.0;\n  maxWt = 10.0;\n  ObitInfoListGetTest(in->info, \"MaxWt\",   &type, dim, &maxWt);\n  /* Default MinPeak is &OutlierFlux */\n  Flux = 1.0;\n  if (!ObitInfoListGetTest(in->info, \"MinPeak\", &type, dim, &Flux)) {\n    OutlierFlux = 1.0;\n    ObitInfoListGetTest(in->info, \"OutlierFlux\", &type, dim, &OutlierFlux);\n    Flux = OutlierFlux;\n    dim[0] = dim[1] = dim[2] = 1;\n    ObitInfoListAlwaysPut(in->info, \"MinPeak\", OBIT_float, dim, &Flux); \n  }\n  mxcDis = 1.0;\n  ObitInfoListGetTest(in->info, \"MaxDist\", &type, dim, &mxcDis);\n  MaxRMS = 20.0;\n  ObitInfoListGetTest(in->info, \"MaxRMS\",  &type, dim, &MaxRMS);\n  nZern = 5;\n  ObitInfoListGetTest(in->info, \"nZern\",   &type, dim, &nZern);\n\n  /* Make sure inUV indexed */\n  maxGap = solInt;  /* Max. time gap in indexing */\n  dim[0] = dim[1] = dim[2] = 1;\n  ObitInfoListAlwaysPut(inUV->info, \"maxGap\", OBIT_float, dim, &maxGap);\n  ObitUVUtilIndex(inUV, err);\n  if (err->error) Obit_traceback_msg (err, routine, inUV->name);\n\n  /* Get NX table */\n  ver = 1;\n  NXtab = newObitTableNXValue (\"IonCal NX table\", (ObitData*)inUV, &ver, \n\t\t\t       OBIT_IO_ReadOnly, err);\n  if (err->error) goto cleanup;\n      \n  /* Set FOV to 0 then restore */\n  oldFOV = 0.0;\n  ObitInfoListGetTest(inUV->info, \"FOV\", &type, dim, &oldFOV);\n  FOV = 0.0;\n  ObitInfoListAlwaysPut (inUV->info, \"FOV\", type,   dim, &FOV);\n\n  /* Enable data selection by timerange */\n  dim[0] = 1;\n  ObitInfoListAlwaysPut(inUV->info, \"doCalSelect\", OBIT_bool, dim, &Tr);\n  /* Stokes 'I' */\n  dim[0] = 4;\n  ObitInfoListAlwaysPut(inUV->info, \"Stokes\", OBIT_string, dim, Stokes);\n  \n  /* Create Clean (and calibrator mosaic) */\n  myClean = ObitDConCleanVisCreate (\"IonCal Clean\", inUV, err);\n  if (err->error) goto cleanup;\n  ClnClass = (ObitDConCleanVisClassInfo*)myClean->ClassInfo; /* class structure */\n\n  /* Reset FOV to previous value */\n  ObitInfoListAlwaysPut (inUV->info, \"FOV\", OBIT_float,  dim, &oldFOV);\n\n  /* Local pointer to calibrator mosaic */\n  myMosaic = ObitUVImagerGetMosaic (myClean->imager, err);\n  if (err->error) goto cleanup;\n\n  /* Only summary CLEAN messages */\n  cprtLv = 0; dim[0] = dim[1] = 1;\n  if (prtLv>=4) cprtLv = prtLv;\n  ObitInfoListAlwaysPut (myClean->info, \"prtLv\", OBIT_long, dim, &cprtLv);\n\n  /* No need to cross restore */\n  dim[0] = 1;\n  ObitInfoListAlwaysPut(myClean->info, \"doXRestore\", OBIT_bool, dim, &Fl);\n\n  /* ... or flatten */\n  dim[0] = 1;\n  ObitInfoListAlwaysPut(myClean->info, \"doFlatten\", OBIT_bool, dim, &Fl);\n\n  /* Make beam each time */\n  dim[0] = 1;\n  ObitInfoListAlwaysPut(myClean->info, \"doBeam\", OBIT_bool, dim, &Tr);\n\n  /* ... and weight data */\n  dim[0] = 1;\n  ObitInfoListAlwaysPut(myClean->info, \"doWeight\", OBIT_bool, dim, &Tr);\n\n  /* Copy CLEAN control parameters */\n  ObitInfoListCopyList (inUV->info, myClean->info, ParmList);\n\n  /* Copy IonCal  control parameters */\n  ObitInfoListCopyList (inUV->info, in->info, IonParmList);\n\n  /* Default Beam */\n  Beam[0] = Beam[1] = Beam[2] = 0.0;\n  dim[0] = 3; dim[1] = 1;\n  ObitInfoListAlwaysPut (myClean->info, \"Beam\", OBIT_float, dim, Beam);\n\n  /* Diagnostic info*/\n  if (prtLv>0) {\n    g_snprintf (msgtxt,100,\"calibrating ionosphere, max RMS seeing= %6.2f qual=%5d\", \n\t\tMaxRMS, qual);\n    Obit_log_error(err, OBIT_InfoWarn, msgtxt);\n    \n    g_snprintf (msgtxt,100,\"observing date = %s\", inUV->myDesc->obsdat);\n    Obit_log_error(err, OBIT_InfoWarn, msgtxt);\n    ObitImageDescGetPoint (myMosaic->images[0]->myDesc, &obsra, &obsdec);\n    g_snprintf (msgtxt,100,\"pointing ra=%10.6f dec=%10.6f deg\", obsra, obsdec);\n    Obit_log_error(err, OBIT_InfoWarn, msgtxt);\n  }\n\n  ObitErrLog(err); /* show any messages on err */\n  \n  /* Clear any entries in calList */\n  calList = (CalList*)in->calList;\n  CalListClear (calList);\n\n  /* Generate calibrator list from mosaic */\n  FindCalMosaic (in, myMosaic, calList, prtLv, err);\n  if (err->error) goto cleanup;\n\n  /* arrays per calibrator */\n  ncal = myMosaic->numberImages;\n  gotit = g_malloc(ncal*sizeof(gboolean));  /* calibrator ever found? */\n  for (i=0; i<ncal; i++) gotit[i] = FALSE; /* Not found anything yet. */\n\n  /* How many coefficients to solve  for?  */\n  ncoef = nZern;\n\n  ObitErrLog(err); /* show any messages on err */\n  /* Loop over time slices */\n  for (i=1; i<=100000; i++) { /* loop 500 */\n    if (!NextTime(NXtab, solInt, timer, &suba, err)) break;\n    if (err->error) goto cleanup;\n\n    /* Set timerange, subarray */\n    dim[0] = 2; dim[1] = 1;\n    ObitInfoListAlwaysPut (inUV->info, \"timeRange\", OBIT_float, dim, timer);\n    dim[0] = 1;\n    ObitInfoListAlwaysPut (inUV->info, \"Subarray\", OBIT_long, dim, &suba);\n\n    /* Use fitted beam */\n    dim[0] = 3; dim[1] = 1;\n    ObitInfoListAlwaysPut (myClean->info, \"Beam\", OBIT_float, dim, Beam);\n\n    /* Reset Windows first time */\n    if (i==1) ClnClass->ObitDConCleanDefWindow((ObitDConClean*)myClean, err);\n    if (err->error) goto cleanup;\n\n    ObitErrLog(err);  /* Make sure message stack shown */\n\n    /* Image/deconvolve this one */\n    ClnClass->ObitDConDeconvolve ((ObitDCon*)myClean, err);\n    /* Be somewhat tolerant of failures here */\n    if (myClean->prtLv>2) ObitErrLog(err);  /* Debug errors */\n    if (err->error) {\n       badTime = TRUE;\n       ObitErrClearErr (err); /* Clear error messages and condition */\n    } else badTime = FALSE;\n\n    /* Diagnostic info*/\n    if (prtLv>0) {\n      /* Tell time range */\n      TR2String (timer, msgtxt);\n      Obit_log_error(err, OBIT_InfoErr, \"Timerange %s\", msgtxt);\n      if (myClean->Pixels) {\n\tObit_log_error(err, OBIT_InfoErr, \n\t\t       \"Total CLEAN flux density = %8.1f, resid = %8.1f Jy\", \n\t\t       myClean->Pixels->totalFlux, myClean->Pixels->maxResid);\n      } else {\n\tObit_log_error(err, OBIT_InfoErr, \"CLEAN failed\"); \n      }\n      ObitErrLog(err);\n    } \n\n    /* Save epoch information */\n    nEpoch = i;\n    if (nEpoch<=MAXEPOCH) {\n      subaEpoch[nEpoch-1]  = suba;\n      timeEpoch[nEpoch-1]  = (timer[0]+timer[1]) * 0.5;\n      timeIEpoch[nEpoch-1] = timer[1] - timer[0];\n    } else { /* blew arrays */\n      Obit_log_error(err, OBIT_InfoWarn, \n\t\t     \"%s: Overflowed internal arrays (%d) stopping IonCal\", \n\t\t     routine, MAXEPOCH);\n      break;  /* Full, stop calibrating */\n    }\n\n    /* save image reference frequency */\n    refFreq = myMosaic->images[0]->myDesc->crval[myMosaic->images[0]->myDesc->jlocf];\n\n    /* Do fits to each image in mosaic if CLEAN succeeded */\n    if (!badTime) {\n      /* Digest CLEAN images */\n      ObitIonCalPosMosaic (in, myMosaic, nEpoch, err);\n    } else {\n      /* Mark entries bad */\n      CalBadTime (in, myMosaic, nEpoch, err);\n      Obit_log_error(err, OBIT_InfoWarn, \"%s: CLEAN Failed this time slice\", \n\t\t     routine);\n      /* Mark entries bad */\n    }\n    if (err->error) goto cleanup;\n\n    /* Keep track of epoch times, subarrays */\n\n    /* Diagnostic info*/\n    if (prtLv>0) {\n      /* Print solutions for this epoch */\n      ObitErrLog(err); /* show any messages on err */\n    } \n  } /* end loop  L500: over snapshots */\n\n  /* Fit model, write IN table */\n  NItab = FitAll (in, ncoef, nEpoch, timeEpoch, timeIEpoch, subaEpoch, \n\t\t  refFreq, &seeing, err);\n  \n  /* Save seeing */\n  dim[0] = dim[1] = dim[2] = 1;\n  ObitInfoListAlwaysPut(inUV->info, \"seeing\", OBIT_float, dim, &seeing);\n\n\n  /* If requested convert to SN */\n  if (doSN) {\n    off[0] = off[1] = 0.0;\n    SNtab = ObitIoN2SolNTableConvert (inUV, NItab, NULL, off, err);\n    if (err->error) goto cleanup;\n  } \n \n  /* Cleanup */\n cleanup:  myClean = ObitDConCleanVisUnref(myClean);\n  NXtab = ObitTableNXUnref(NXtab);\n  SNtab = ObitTableSNUnref(SNtab);\n  NItab = ObitTableNIUnref(NItab);\n  if (gotit) g_free(gotit);\n  ObitImageMosaicZapImage (myMosaic, -1, err);\n  myMosaic = ObitImageMosaicUnref (myMosaic);\n  if (err->error) Obit_traceback_msg (err, routine, inUV->name);\n  \n  /* Reset timerange, subarray */\n  dim[0] = 2; dim[1] = 1;\n  timer[0] = -1.0e20; timer[1] = 1.0e20;\n  ObitInfoListAlwaysPut (inUV->info, \"timeRange\", OBIT_float, dim, timer);\n  dim[0] = 1;\n  suba = 0;\n  ObitInfoListAlwaysPut (inUV->info, \"Subarray\", OBIT_long, dim, &suba);\n\n} /* end of routine ObitIonCaldoCal */ \n\n/**\n * Determines calibrator position offsets from images in a mosaic.\n * Asumes given a calList with entries corresponding to entries in an\n * Image mosaic, fit the actual positioins in the mosaic and write new \n * entries in the CalList with offsets for acceptable fits.\n * Resultant positions are all referred to a tangent plane at the  \n * pointing center, this is referred to as the Zernike plane as this  \n * plane will be used to fit the phase screen.  The \"Zernike Unit  \n * Circle\" defines the phase screen.  Source position offsets are in  \n * the X and Y (RA, Dec) as defined by this plane.  \n * Routine adapted from the AIPSish CALPOS.FOR/CALPOS  \n * \\param in   IonCal object \n *   Control parameters are on the info member.\n * \\li \"nZern\"  OBIT_int   (1,1,1) Zernike polynomial order requested [def 5]\n * \\li FitDist  OBIT_int   (1,1,1) dist, from expected location to search \n *                                 asec [10 pixels]  \n * \\li MinPeak  OBIT_float (1,1,1) Min. acceptable image peak (Jy) [1.0]\n * \\li MaxDist  OBIT_float (1,1,1) Max. distance (deg/10) to accept calibrator [1.]\n * \\li MaxWt    OBIT_float (1,1,1) Max. weight [10.0]\n * \\li MaxQual  OBIT_int   (1,1,1) Max. cal. quality code [def 1]\n * \\li prtLv    OBIT_int   (1,1,1) Print level >=1 => give fits\n * \\param mosaic   Image mosaic object \n * \\param calList Calibrator list each element of which has:\n * \\li ra      position RA (deg) of calibrators\n * \\li dec     position Dec (deg) of calibrators\n * \\li shift   Offset in field [x,y] on unit Zernike circle of position\n * \\li pixel   Expected pixel in reference image\n * \\li flux    Estimated catalog flux density \n * \\li offset  Measured offset [x,y] from expected position (deg)\n * \\li peak    Measured peak flux density (image units)\n * \\li fint    Measured integrated flux density (image units)\n * \\li wt      Determined weight\n * \\li qual    Catalog quality code\n * \\param err     Error stack\n * \\param epoch   Epoch number\n */\nvoid ObitIonCalPosMosaic (ObitIonCal *in, ObitImageMosaic* mosaic, \n\t\t\t  olong epoch, ObitErr* err)  \n{\n  olong   field, j, good, FitSize=0, prtLv, ncoef, nobs, maxQual, addSize, nZern;\n  olong number, total;\n  ofloat flux, FitDist, dist;\n  ofloat mxcdis, maxwt, MaxRMS, MaxRMS2, rms;\n  gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};\n  ObitInfoType type;\n  ofloat offset[2], pixel[2], corr[2], coef[17], peak, fint, dr, dd, wt;\n  ObitImage *image=NULL;\n  CalListElem *elem=NULL, *nelem=NULL;\n  GSList  *tmp;\n  CalList *calList;\n  gboolean doMore;\n  ofloat *x=NULL, *y=NULL, *dx=NULL, *dy=NULL, *w=NULL;\n  olong *isou=NULL;\n  gchar *routine = \"ObitIonCalPosMosaic\";\n\n  /* Error checks */\n  g_assert(ObitErrIsA(err));\n  if (err->error) return ;  /* previous error? */\n  g_assert(ObitIonCalIsA(in));\n  g_assert(ObitImageMosaicIsA(mosaic));\n\n  calList = (CalList*)in->calList;\n\n  /* Control information. */\n  maxwt = 10.0;\n  ObitInfoListGetTest(in->info, \"MaxWt\",   &type, dim, &maxwt);\n  flux = 1.0;\n  ObitInfoListGetTest(in->info, \"MinPeak\", &type, dim, &flux);\n  mxcdis = 1.0;\n  ObitInfoListGetTest(in->info, \"MaxDist\", &type, dim, &mxcdis);\n  maxQual = 1;\n  ObitInfoListGetTest(in->info, \"MaxQual\",    &type, dim, &maxQual);\n  FitDist = 0.0;\n  ObitInfoListGetTest(in->info, \"FitDist\", &type, dim, &FitDist);\n  FitDist /= 3600.0; /* to degrees */\n  nZern = 5;\n  ObitInfoListGetTest(in->info, \"nZern\",   &type, dim, &nZern);\n  ncoef = nZern;\n  prtLv = 0;\n  ObitInfoListGetTest(in->info, \"prtLv\",   &type, dim, &prtLv);\n  MaxRMS = 10.0;\n  ObitInfoListGetTest(in->info, \"MaxRMS\",   &type, dim, &MaxRMS);\n  MaxRMS /= 3600.0;  /* to deg */\n  MaxRMS2 = 2.0 * MaxRMS; /* relax for finding sources */\n  /* lenient RMS = 3 pixels\n  MaxRMS = 3.0*fabs(mosaic->images[0]->myDesc->cdelt[0]); */\n\n  /* First pass to get basic geometric distortions */\n  /* allocate memory */\n  nobs = mosaic->numberImages;\n  x    = g_malloc0(nobs*sizeof(ofloat));\n  y    = g_malloc0(nobs*sizeof(ofloat));\n  dx   = g_malloc0(nobs*sizeof(ofloat));\n  dy   = g_malloc0(nobs*sizeof(ofloat));\n  w    = g_malloc0(nobs*sizeof(ofloat));\n  isou = g_malloc0(nobs*sizeof(olong));\n\n  /* Loop getting initial positions */\n  nobs = 0;\n  for (field=0; field<mosaic->numberImages; field++) {\n    image = mosaic->images[field];\n \n    /* Convert FitDist to pixels */\n    if (FitDist<=0.0) FitDist = 10.0 * fabs(image->myDesc->cdelt[0]) / 3600.0;\n    FitSize = (olong)((FitDist / fabs(image->myDesc->cdelt[0]))+0.5);\n    FitSize = MAX (10, FitSize);\n\n    /* Find cal info */\n    tmp = calList->list;\n    while (tmp!=NULL) {   /* loop 100 */\n      elem = (CalListElem*)tmp->data;\n      if (elem->calNo == (field+1)) break;  /* found it */\n      tmp = g_slist_next(tmp);  /* next item in list */\n    } /* end loop  L100: over calibrator list */\n\n    PosImage (image, elem->pixel, flux, mxcdis, FitSize, \n\t      offset, &peak, &fint, err);\n    if (err->error) goto cleanup;\n    \n    if (peak>flux) {  /* Valid datum? */\n      /* Within maximum distance? */\n      dist = sqrt(elem->ZernXY[0]*elem->ZernXY[0] + elem->ZernXY[1]*elem->ZernXY[1]);\n      if (dist <= mxcdis)  w[nobs] = MIN (maxwt, peak);\n      else w[nobs] = 0.0;\n      if (elem->qual>maxQual) w[nobs] = 0.0;  /* Only acceptable quality */\n      x[nobs]    = elem->ZernXY[0];\n      y[nobs]    = elem->ZernXY[1];\n      dx[nobs]   = offset[0];\n      dy[nobs]   = offset[1];\n      isou[nobs] = nobs;\n      nobs++;  /* This one OK */\n      \n      /* diagnostics? */\n      if (prtLv>=3) {\n\tObit_log_error(err, OBIT_InfoErr, \n\t\t       \"Initial E=%5d C=%5d Z= %7.4f %7.4f off=%7.2f %7.2f Peak=%6.2f int=%6.2f qual=%d\",\n\t\t       epoch, elem->calNo, elem->ZernXY[0], elem->ZernXY[1], \n\t\t       offset[0]*3600.0, offset[1]*3600.0, peak, fint, elem->qual);\n      }\n    } /* End if detected */\n    \n  } /* end loop over fields */\n\n  /* Work out Zernike model for field - fit and edit */\n  doMore = TRUE;\n  while (doMore) {\n    rms = IonFit1 (nobs, isou, x, y, dx, dy, w, &ncoef, coef, prtLv, err);\n    if (rms<MaxRMS2) break;\n    doMore = IonEdit1 (nobs, isou, x, y, dx, dy, w, MaxRMS2, ncoef, coef, prtLv, err);\n    if (err->error) goto cleanup;\n   }\n\n  /* Was it happy with the results? */\n  good = 0;\n  for (j=0; j<nobs; j++) if (w[j]>0.0) good++;\n  if ((good<=2) || (rms>MaxRMS2)) { /* need at least 3, no? - use no distortion */\n    ncoef = 2;\n    coef[0] = coef[1] = 0;\n    FitSize = MAX (10, FitSize);\n  } else { /* OK - set size of fitting region */\n    FitSize = 10;\n    /* Add an amount propostional to tip/tilt */\n    addSize = 0.5 + (0.1 * (sqrt (coef[0]*coef[0]+coef[1]*coef[1]) / \n\t\t\t    fabs(mosaic->images[0]->myDesc->cdelt[0])) + \n\t\t     /* Add a tern for the rms residual */\n\t\t     + rms/fabs(mosaic->images[0]->myDesc->cdelt[0]));\n    FitSize += addSize;\n  }\n\n  if (prtLv>=2) {\n    Obit_log_error(err, OBIT_InfoErr, \n\t\t   \"%s: Initial no. cal %d rms %f Search Size %d\",\n\t\t   routine, good, rms*3600.0, FitSize);\n  }\n\n cleanup:\n  if (x)    g_free(x);  x =NULL;\n  if (y)    g_free(y);  y =NULL;\n  if (dx)   g_free(dx); dx=NULL;\n  if (dy)   g_free(dy); dy=NULL;\n  if (w)    g_free(w);  w =NULL;\n  if (isou) g_free(isou);\n  if (err->error) Obit_traceback_msg (err, routine, image->name);\n\n  /* Loop over images getting final positions */\n  good = 0;\n  for (field=0; field<mosaic->numberImages; field++) {\n    image = mosaic->images[field];\n \n    /* Find cal info */\n    tmp = calList->list;\n    while (tmp!=NULL) {   /* loop 100 */\n      elem = (CalListElem*)tmp->data;\n      if (elem->calNo == (field+1)) break;  /* found it */\n      tmp = g_slist_next(tmp);  /* next item in list */\n    } /* end loop  L100: over calibrator list */\n\n    /* Work out expected position */\n    dr = 0.0;\n    dd = 0.0;\n    for (j=0; j<ncoef; j++) {\n      dr += coef[j]*ObitZernikeGradX(j+2, elem->ZernXY[0], elem->ZernXY[1]);\n      dd += coef[j]*ObitZernikeGradY(j+2, elem->ZernXY[0], elem->ZernXY[1]);\n    } \n    corr[0] = dr / image->myDesc->cdelt[0];\n    corr[1] = dd / image->myDesc->cdelt[1];\n    pixel[0] = elem->pixel[0] - corr[0];\n    pixel[1] = elem->pixel[1] - corr[1];\n\n    PosImage (image, pixel, flux, mxcdis, FitSize, \n\t      offset, &peak, &fint, err);\n    if (err->error) Obit_traceback_msg (err, routine, image->name);\n\n    /* Adjust result for quess of position */\n    offset[0] += dr;\n    offset[1] += dd;\n    \n    if (peak>flux) {  /* Valid datum? */\n      /* Within maximum distance? */\n      dist = sqrt(elem->ZernXY[0]*elem->ZernXY[0] + elem->ZernXY[1]*elem->ZernXY[1]);\n      if (dist <= mxcdis)  wt = MIN (maxwt, peak);\n      else wt = 0.0;\n      \n      /* Update CalList */\n      nelem = newCalListElem (elem->ra, elem->dec, elem->ZernXY, elem->shift, \n\t\t\t      elem->pixel, elem->flux, offset, peak, fint, wt, \n\t\t\t      elem->qual, field+1, epoch);\n      CalListAdd (calList, nelem);\n      good++;  /* This one OK */\n      \n      /* diagnostics? */\n      if (prtLv>=1) {\n\tObit_log_error(err, OBIT_InfoErr, \n\t\t       \"Fit E=%5d C=%5d Z= %7.4f %7.4f off=%7.2f %7.2f Peak=%6.2f int=%6.2f qual=%d\",\n\t\t       epoch, elem->calNo, elem->ZernXY[0], elem->ZernXY[1], \n\t\t       offset[0]*3600.0, offset[1]*3600.0, peak, fint, elem->qual);\n      }\n    } /* End if detected */\n    \n  } /* end loop over fields */\n  \n  if (prtLv>=5) {\n    /*ObitMemPrint (stdout);DEBUG*/\n    ObitMemSummary (&number, &total);\n    Obit_log_error(err, OBIT_InfoErr, \"%s: Memory use, %d entries %d MByte)\", \n\t\t routine, number, total);\n  }\n /* tell how many */\n  Obit_log_error(err, OBIT_InfoErr, \"%s: Fitted %d calibrator offsets\", \n\t\t routine, good);\n\n  /* If there aren't any - flag time */\n  if (good<1) {\n    CalBadTime (in, mosaic, epoch, err);\n    Obit_log_error(err, OBIT_InfoWarn, \"%s: CLEAN Failed this time slice\", \n\t\t   routine);\n  }\n} /* end of routine ObitIonCalPosMosaic */ \n\n/**\n * Search for a source at the given position return fitted  \n * flux density and offsets from the expected positions.  \n * A source is only accepted if the peak is within   \n * 0.5*min(imsi[0],imsi[1])  pixels of the center.  \n * \\param image    Image open and plane read and attached\n * \\param pixel    Expected pixel (1-rel) of centroid\n * \\param minflux  Min. allowed peak flux density\n * \\param mxcdis   Max. distance from center - not used here\n * \\param FitSize  Full width in pixels of search window around pixel\n * \\param offset   [out] Offset from expected position in cells\n * \\param peak     [out] Peak flux density\n * \\param fint     [out] integrated flux density\n * \\param err      Error stack \n */\nstatic void PosImage (ObitImage *image, ofloat pixel[2], ofloat minflux, \n\t\t      ofloat mxcdis, olong FitSize, \n\t\t      ofloat offset[2], ofloat *peak, ofloat *fint, ObitErr *err)\n{\n  olong j, imsi[2];\n  olong blc[IM_MAXDIM] = {1,1,1,1,1,1,1};\n  olong trc[IM_MAXDIM] = {0,0,0,0,0,0,0};\n  gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};\n  ObitIOSize IOBy;\n  ofloat area, pixelOff[2];\n  gchar *routine = \"PosImage\";\n\n  /* Open and read image full plane */\n  IOBy = OBIT_IO_byPlane;\n  dim[0] = 1;\n  ObitInfoListAlwaysPut (image->info, \"IOBy\", OBIT_long, dim, &IOBy);\n  dim[0] = 7;\n  for (j=0; j<IM_MAXDIM; j++) {blc[j] = 1; trc[j] = 0;}\n  ObitInfoListAlwaysPut (image->info, \"BLC\", OBIT_long, dim, blc); \n  ObitInfoListAlwaysPut (image->info, \"TRC\", OBIT_long, dim, trc);\n  image->extBuffer = FALSE;  /* Make sure it has buffer */\n  ObitImageOpen (image, OBIT_IO_ReadOnly, err); \n  ObitImageRead (image, NULL, err);\n  if (err->error) Obit_traceback_msg (err, routine, image->name);\n  \n  /* fit source */\n  imsi[0] = imsi[1] = FitSize;\n  CalPosFit (image, pixel, imsi, pixelOff, peak, fint, err);\n  if (err->error) Obit_traceback_msg (err, routine, image->name);\n  \n  /* Close image */\n  ObitImageClose (image, err);\n  if (err->error) Obit_traceback_msg (err, routine, image->name);\n  image->image = ObitImageUnref(image->image);   /* Free buffer */\n  \n  /* find anything? */\n  if (*peak<minflux) { /* Nope */\n    *peak = 0.0;\n  } else { /* yes */\n    \n    /* Offset */\n    offset[0] = pixelOff[0] * image->myDesc->cdelt[0];\n    offset[1] = pixelOff[1] * image->myDesc->cdelt[1];\n    \n    /* Normalize integrated flux by beam area in pixels */\n    area = 1.1331 * image->myDesc->beamMaj * image->myDesc->beamMin /  \n      (fabs (image->myDesc->cdelt[0]) * fabs (image->myDesc->cdelt[1])) ;\n    if (area  <  0.001) area = 1.0;\n    *fint /= area;\n  }\n} /* end PosImage */\n\n/**\n * Initialize global ClassInfo Structure.\n */\nvoid ObitIonCalClassInit (void)\n{\n  if (myClassInfo.initialized) return;  /* only once */\n  \n  /* Set name and parent for this class */\n  myClassInfo.ClassName   = g_strdup(myClassName);\n  myClassInfo.ParentClass = ObitParentGetClass();\n\n  /* Set function pointers */\n  ObitIonCalClassInfoDefFn ((gpointer)&myClassInfo);\n \n  myClassInfo.initialized = TRUE; /* Now initialized */\n \n} /* end ObitIonCalClassInit */\n\n/**\n * Initialize global ClassInfo Function pointers.\n */\nstatic void ObitIonCalClassInfoDefFn (gpointer inClass)\n{\n  ObitIonCalClassInfo *theClass = (ObitIonCalClassInfo*)inClass;\n  ObitClassInfo *ParentClass = (ObitClassInfo*)myClassInfo.ParentClass;\n\n  if (theClass->initialized) return;  /* only once */\n\n  /* Check type of inClass */\n  g_assert (ObitInfoIsA(inClass, (ObitClassInfo*)&myClassInfo));\n\n  /* Initialize (recursively) parent class first */\n  if ((ParentClass!=NULL) && \n      (ParentClass->ObitClassInfoDefFn!=NULL))\n    ParentClass->ObitClassInfoDefFn(theClass);\n\n  /* function pointers defined or overloaded this class */\n  theClass->ObitClassInit = (ObitClassInitFP)ObitIonCalClassInit;\n  theClass->newObit       = (newObitFP)newObitIonCal;\n  theClass->ObitClassInfoDefFn = (ObitClassInfoDefFnFP)ObitIonCalClassInfoDefFn;\n  theClass->ObitGetClass  = (ObitGetClassFP)ObitIonCalGetClass;\n  theClass->ObitCopy      = (ObitCopyFP)ObitIonCalCopy;\n  theClass->ObitClone     = NULL;\n  theClass->ObitClear     = (ObitClearFP)ObitIonCalClear;\n  theClass->ObitInit      = (ObitInitFP)ObitIonCalInit;\n  theClass->ObitIonCalCreate = (ObitIonCalCreateFP)ObitIonCalCreate;\n\n} /* end ObitIonCalClassDefFn */\n\n/*---------------Private functions--------------------------*/\n\n/**\n * Creates empty member objects, initialize reference count.\n * Parent classes portions are (recursively) initialized first\n * \\param inn Pointer to the object to initialize.\n */\nvoid ObitIonCalInit  (gpointer inn)\n{\n  ObitClassInfo *ParentClass;\n  ObitIonCal *in = inn;\n\n  /* error checks */\n  g_assert (in != NULL);\n\n  /* recursively initialize parent class members */\n  ParentClass = (ObitClassInfo*)(myClassInfo.ParentClass);\n  if ((ParentClass!=NULL) && ( ParentClass->ObitInit!=NULL)) \n    ParentClass->ObitInit (inn);\n\n  /* set members in this class */\n  in->thread    = newObitThread();\n  in->info      = newObitInfoList(); \n  in->calList   = (gpointer)newCalList();\n  in->myData    = NULL;\n\n} /* end ObitIonCalInit */\n\n/**\n * Deallocates member objects.\n * Does (recursive) deallocation of parent class members.\n * \\param  inn Pointer to the object to deallocate.\n *           Actually it should be an ObitIonCal* cast to an Obit*.\n */\nvoid ObitIonCalClear (gpointer inn)\n{\n  ObitClassInfo *ParentClass;\n  ObitIonCal *in = inn;\n\n  /* error checks */\n  g_assert (ObitIsA(in, &myClassInfo));\n\n  /* delete this class members */\n  in->thread    = ObitThreadUnref(in->thread);\n  in->info      = ObitInfoListUnref(in->info);\n  freeCalList((CalList*)in->calList); in->calList=NULL;\n  in->myData    = ObitUVUnref(in->myData);\n  \n  /* unlink parent class members */\n  ParentClass = (ObitClassInfo*)(myClassInfo.ParentClass);\n  /* delete parent class members */\n  if ((ParentClass!=NULL) && ( ParentClass->ObitClear!=NULL)) \n    ParentClass->ObitClear (inn);\n  \n} /* end ObitIonCalClear */\n\n/**\n * Search for a source at the given position return fitted  \n * flux density and offsets from the expected positions.  \n * A source is only accepted if the peak is within   \n * 0.5*min(imsi[0],imsi[1])  pixels of the center.  \n * Routine translated from the AIPSish CALPOS.FOR/FXPFIT  \n * \\param image    Image open and plane read and attached\n * \\param inPixel  Expected pixel (1-rel) of centroid\n * \\param imsi     Full width of the window to search around inPixel\n * \\param pixelOff Fitted offset from expected pixel (pixels)\n * \\param souflx   Fitted peak flux density \n *                 Value < 0.0 indicate source not found or \n *                 otherwise unacceptable. \n * \\param souint   Integrated flux density in 9x9 (not normalized by \n *                 beam area) \n * \\param err      Error stack \n */\nstatic void CalPosFit (ObitImage *image, ofloat inPixel[2], olong* imsi, \n\t\t       ofloat pixelOff[2], ofloat* souflx, ofloat* souint,\n\t\t       ObitErr *err)\n{\n  ofloat s, dx[2], dis, maxdis;\n  olong   i1, i2, j1, j2, ic, jc;\n  olong blc[2], trc[2], pos[7], iX, iY, iXp, iYp, iXcen, iYcen;\n  ofloat data[9][9], pixval=0.0, *pixP, sum, fblank= ObitMagicF();\n  ObitFArray *fitData;\n  gchar *routine = \"CalPosFit\";\n\n  /* Initial values */\n  *souflx = -1.0;\n  *souint = -1.0;\n  pixelOff[0] = 0.0;\n  pixelOff[1] = 0.0;\n\n  /* Find peak, copy data */\n  ic = inPixel[0] + 0.5;  /* Closest pixel */\n  jc = inPixel[1] + 0.5;\n  i1 = ic - imsi[0] / 2 ;\n  i2 = ic + (imsi[0] / 2) - 1;\n  j1 = jc - imsi[1] / 2 ;\n  j2 = jc + (imsi[1] / 2) - 1;\n  i1 = MAX (MIN (i1, image->myDesc->inaxes[0]), 1);\n  i2 = MIN (MAX (i2, i1), image->myDesc->inaxes[0]);\n  j1 = MAX (MIN (j1, image->myDesc->inaxes[1]), 1);\n  j2 = MIN (MAX (j2, j1), image->myDesc->inaxes[1]);\n\n  blc[0] = i1-1; blc[1] = j1-1; /* to zero rel */\n  trc[0] = i2-1; trc[1] = j2-1;\n  fitData = ObitFArraySubArr (image->image, blc, trc, err);\n  if (err->error) Obit_traceback_msg (err, routine, image->name);\n\n  /* Peak */\n  s = ObitFArrayMax (fitData, pos);\n  *souflx = s;\n\n  /* use 9x9 values around center */\n  iXcen = pos[0];\n  iYcen = pos[1];\n  sum = 0.0;\n  for (iY=0; iY<9; iY++) {\n    iYp = iYcen + iY - 4;\n    pos[1] = iYp;\n    for (iX=0; iX<9; iX++) {\n      iXp = iXcen + iX - 4;\n      pos[0] = iXp;\n      /* get value */\n      pixP =  ObitFArrayIndex (fitData, pos);\n      if (pixP) pixval = *pixP;  /* in array? */\n      else pixval = fblank;\n      if (pixval!=fblank) {\n\tdata[iY][iX] = pixval;\n\tsum += pixval;\n      } else  /* blank */\n\tdata [iY][iX] = fblank;\n    }\n  }  /*  end of loop loading image data in array */\n\n  /* Cleanup */\n  fitData = ObitFArrayUnref(fitData);\n\n  /* Fit peak in data */\n  if (pfit (data, &s, dx, fblank)) {\n    *souflx = -1.0; /* fit failed */\n    *souint = -1.0;\n    return;\n  } \n\n  *souflx = s;   /* Fitted peak */\n  *souint = sum; /* Integral is sum */\n\n  /* get offset from expected */\n  dx[0] += iXcen;  /* offset in fitData */\n  dx[1] += iYcen;\n  /* revert to 1-rel */\n  pixelOff[0] = (-(dx[0] + blc[0] + 1 - inPixel[0]));\n  pixelOff[1] = (-(dx[1] + blc[1] + 1 - inPixel[1]));\n\n  /* Is he close enough to the center? */\n  maxdis = (0.5 * MIN (imsi[0], imsi[1]))*(0.5 * MIN (imsi[0], imsi[1]));\n  dis = pixelOff[0]*pixelOff[0] + pixelOff[1]*pixelOff[1];\n  if (dis > maxdis) {  /* Nope */\n    *souflx = -1.0;\n    *souint = -1.0;\n    return;\n  } \n\n} /* end of routine CalPosFit */ \n\n/**\n * Searches Catalog for calibrators an image and with an estimated flux\n * density in excess of a given limit taking into account the estimated \n * single-dish beam  \n * Adapted from the AIPSish ADNVSS in $FOURMASS/SUB/ADDFIELDS.FOR\n * \\param image        image in question\n * \\param Catalog      FITS AIPSVZ format catalog file name\n * \\param catDisk      FITS disk number for Catalog\n * \\param OutlierFlux  Minimum estimated flux density \n * \\param OutlierSI    Spectral index to use to convert catalog flux density\n * \\param qual         Maximum qualifier quality code\n * \\param AntDiam      Primary antenna diameter (m) [default 25]\n * \\param calList      calibrator list, a linked list of calibrators\n * \\param prtLv        Print level >=3 => give list\n * \\param err          Error stack, returns if not empty.\n */\nstatic void \nFindCalImage (ObitImage *image, gchar *Catalog, olong catDisk, \n\t      ofloat OutlierFlux, ofloat OutlierSI, olong qual, ofloat AntDiam,\n\t      CalList *calList, olong prtLv, ObitErr *err) \n{\n  olong count, cqual;\n  odouble Freq, ra, dec, ra2000, dc2000, ra2000d, dc2000d;\n  odouble xx, yy, zz, dist, refreq;\n  ofloat radius, radRA, minflx, asize, alpha, pbf;\n  ofloat flux, scale;\n  gboolean doJ2B, doJinc, wanted;\n  olong blc[IM_MAXDIM] = {1,1,1,1,1};\n  olong trc[IM_MAXDIM] = {0,0,0,0,0};\n  olong ver, nrows, irow;\n  olong bad, calNo, ierr, epoch=0;\n  ofloat shift[2], pixel[2], offset[2]={0.0,0.0}, peak=0.0, fint=0.0, wt=0.0;\n  ofloat ZernXY[2];\n  ObitIOCode retCode;\n  ObitImageDesc *desc=NULL;\n  ObitImage *VZImage=NULL;\n  ObitTableVZ *VZTable=NULL;\n  ObitTableVZRow *VZRow=NULL;\n  CalListElem *elem=NULL;\n  gchar *routine = \"FindCalImage\";\n  \n  /* error checks */\n  if (err->error) return;\n  g_assert(ObitImageIsA(image));\n\n  /* get control parameters */\n  minflx = OutlierFlux;\n  alpha  = OutlierSI;\n  asize = AntDiam; \n\n  /* set defaults. */\n  if (asize <= 0.0)  asize  = 25.0;\n  if (alpha == 0.0)  alpha  = -0.75;\n\n\n  /* Is image in B1950? */\n  desc = image->myDesc;\n  doJ2B = (fabs(image->myDesc->equinox-1950.0) < 1.0) ||\n    (fabs(desc->epoch-1950.0) < 1.0);\n\n  /* get j2000 position to lookup in Catalog in radians */\n  ra2000 = DG2RAD * desc->crval[desc->jlocr];\n  dc2000 = DG2RAD * desc->crval[desc->jlocd];;\n  if (doJ2B) ObitSkyGeomBtoJ (&ra2000, &dc2000);\n  ra2000d = ra2000 * RAD2DG;\n  dc2000d = dc2000 * RAD2DG;\n\n  /* set crude search radius = 0.5*sqrt(2)*MAX (x_size, Y_size) */\n  radius = 0.5 * sqrt (2.0) * \n    MIN (fabs(desc->cdelt[desc->jlocr]*desc->inaxes[desc->jlocr]),\n\t fabs(desc->cdelt[desc->jlocd]*desc->inaxes[desc->jlocd]));\n  radRA = radius / cos(dc2000);\n  \n  /* Observing frequency */\n  if (desc->jlocf>=0) Freq = desc->crval[desc->jlocf];\n  else Freq = 1.0e9;\n\n  /* which beam model to use */\n  doJinc = (Freq >= 1.0e9);\n\n  /* Open Catalog (VZ table on an image) */\n  VZImage = newObitImage(\"Catalog image\");\n  ObitImageSetFITS(VZImage, OBIT_IO_byPlane, catDisk, Catalog, blc, trc, err);\n\n  /* Open to fully instantiate */\n  ObitImageOpen(VZImage, OBIT_IO_ReadOnly, err);\n  if (err->error) Obit_traceback_msg (err, routine, VZImage->name);\n\n  /* Now get VZ table */\n  ver = 1;\n  VZTable =  newObitTableVZValue(\"Catalog table\", (ObitData*)VZImage, &ver, \n\t\t\t\t OBIT_IO_ReadOnly, err);\n  ObitTableVZOpen(VZTable, OBIT_IO_ReadOnly, err);\n  VZRow =  newObitTableVZRow (VZTable);  /* Table row */\n  if (err->error) Obit_traceback_msg (err, routine, VZTable->name);\n\n  /* Get table info */\n  refreq = VZTable->refFreq;\n  nrows  = VZTable->myDesc->nrow;\n\n  /* frequency scaling */\n  scale = pow ((Freq / refreq), alpha);\n\n  /* loop through table */\n  count = 0;\n  for (irow= 1; irow<=nrows; irow++) { /* loop 500 */\n    /* read */\n    retCode = ObitTableVZReadRow (VZTable, irow, VZRow, err);\n    if (err->error) Obit_traceback_msg (err, routine, VZTable->name);\n   \n    /* spectral scaling of flux density */\n    flux = VZRow->PeakInt * scale;\n\n    /* position, etc */\n    ra    = VZRow->Ra2000;\n    dec   = VZRow->Dec2000;\n    cqual = VZRow->Quality;\n\n    /* select (crude) */\n    if ((fabs(dc2000d-dec) <= radius)  && (fabs(ra2000d-ra) <= radRA) && \n\t(flux >= minflx)) {\n      /* separation from pointing center */\n      xx = DG2RAD * ra;\n      yy = DG2RAD * dec;\n      zz = sin (yy) * sin (dc2000) + cos (yy) * cos (dc2000) * cos (xx-ra2000);\n      zz = MIN (zz, 1.000);\n      dist = acos (zz) * RAD2DG;\n\n      if (dist>radius) continue;\n\n      /* primary beam correction to flux density */\n      if (doJinc) {\n\tpbf = ObitPBUtilJinc (dist, Freq, asize, 0.05);\n      } else {\n\tpbf = ObitPBUtilPoly (dist, Freq, 0.05);\n      } \n      flux *=  MAX (0.05, pbf); /* Don't trust below 5% */\n      \n      /* Convert position to pixel and see if in image*/\n      bad = \n\tObitSkyGeomXYpix(ra, dec,\n\t\t\t desc->crval[desc->jlocr], desc->crval[desc->jlocd],\n\t\t\t desc->crpix[desc->jlocr], desc->crpix[desc->jlocd],\n\t\t\t desc->cdelt[desc->jlocr], desc->cdelt[desc->jlocd],\n\t\t\t desc->crota[desc->jlocd], &desc->ctype[desc->jlocr][4],\n\t\t\t &pixel[0], &pixel[1]);\n      bad = bad || (pixel[0]<1.0) || (pixel[0]>desc->inaxes[0]) || \n\t(pixel[1]<1.0) || (pixel[1]>desc->inaxes[1]);\n      \n      /* select (fine) */\n      wanted = ((flux >= minflx)  &&  (dist <= radius))  && (bad==0) && (cqual<=qual);\n      if (wanted) {\n\tif (doJ2B) {  /* precess if necessary */\n\t  ra  *= DG2RAD;\n\t  dec *= DG2RAD;\n\t  ObitSkyGeomBtoJ (&ra, &dec);\n\t  ra  *= RAD2DG;\n\t  dec *= RAD2DG;\n\t} \n\n\t/* get shift needed */\n\tObitSkyGeomShiftXY (desc->crval[desc->jlocr], desc->crval[desc->jlocd], \n\t\t\t    desc->crota[desc->jlocd], ra, dec, \n\t\t\t    &shift[0], &shift[1]);\n\n\t/* Offset on Zernike plane */\n\tObitSkyGeomRADec2Zern (desc->crval[desc->jlocr], desc->crval[desc->jlocd], \n\t\t\t       shift[0], shift[1], &ZernXY[0], &ZernXY[1], &ierr);\n\tObit_return_if_fail((ierr==0), err, \n\t\t\t    \"%s: Error projecting onto Zernike Unit circle\", routine);\n\n\t/* Add to CalList */\n\tcalNo = count;\n\telem = newCalListElem (ra, dec, ZernXY, shift, pixel, flux, offset, \n\t\t\t        peak, fint, wt, cqual, calNo, epoch);\n\tCalListAdd (calList, elem);\n\tcount++;\n      } /* end if wanted */ \n    } /* end crude selection */\n  } /* end loop over table */\n\n  /* tell how many */\n  Obit_log_error(err, OBIT_InfoErr, \"%s: Found %d calibrators\", routine, count);\n\n  /* Close up */\n  ObitImageClose(VZImage, err);\n  retCode = ObitTableVZClose(VZTable, err);\n  if (err->error) Obit_traceback_msg (err, routine, VZTable->name);\n  VZImage->image = ObitImageUnref(VZImage->image);   /* Free buffer */\n\n  /* Diagnostics? */\n  if (prtLv>=3) {\n    CalListPrint(calList, stdout); \n  }\n  \n  /* clean up */\n  VZImage = ObitImageUnref(VZImage);\n  VZTable = ObitTableUnref(VZTable);\n  VZRow   = ObitTableRowUnref(VZRow);\n  \n} /* end of routine FindCalImage */ \n\n/**\n * Edit Zernike data.\n * Edit data in attempt to get rms residual under MaxRMS\n * by zeroing weight of most discrepant datum which must have\n * at least 1.5 x the average contribution to the variance.\n * Also checks that there is enough data to overdetermine the model.\n * Routine adapted from the AIPSish IONCAL.FOR/IONEDT \n * \\param nobs Number of observations  \n * \\param isou  Source number per obs.  (0-rel)\n * \\param x     Offset in field X (RA) on unit Zernike circle  per source  \n * \\param y     Offset in field Y (Dec) on unit Zernike circle per source  \n * \\param dx    Apparent RA position shifts on the Zernike plane (deg) \n * \\param dy    Apparent dec position shifts on the Zernike plane (deg) \n * \\param w     Weight per source, may be set to zero,\n * \\param MaxRMS Target RMS residual (units of  dx, dy)\n * \\param ncoef number of coefficients in coef\n * \\param coef  Zernike coefficients to use \n * \\param prtLv Print level >=2 tell about editing\n * \\param err   Error stack\n * \\return True if data was edited \n */\nstatic gboolean\nIonEdit1 (olong nobs, olong* isou, ofloat* x, ofloat* y, ofloat* dx, ofloat* dy, \n\t  ofloat* w, ofloat MaxRMS, olong ncoef, ofloat* coef, olong prtLv, \n\t  ObitErr* err) \n{\n  olong      i, j, is, rmscnt, ibad;\n  gboolean out = FALSE;\n  ofloat    dr, dd, rx, ry, rms;\n  ofloat    *gdx=NULL, *gdy=NULL, var, *ResidV=NULL, baddest;\n  gchar *routine = \"IonEdit1\";\n\n  if (nobs<=0) return FALSE;  /* Something to do? */\n\n  /* Allocate memory */\n  gdx    = g_malloc(nobs*ncoef*sizeof(ofloat));\n  gdy    = g_malloc(nobs*ncoef*sizeof(ofloat));\n  ResidV = g_malloc(nobs*sizeof(ofloat));\n\n  /* Compute Zernike gradients */\n  for (i=0; i<nobs; i++) {\n    is = isou[i];\n    for (j=0; j<ncoef; j++) {\n      gdx[j*nobs+i] = ObitZernikeGradX(j+2, x[is], y[is]);\n      gdy[j*nobs+i] = ObitZernikeGradY(j+2, x[is], y[is]);\n    } /* end loop over coefficients */\n  } /* end loop over sources */\n\n  /* get RMS and residuals */\n  rms = 0.0;\n  rmscnt = 0;\n  for (i=0; i<nobs; i++) {\n    if (w[i] > 0.0) {\n      dr = 0.0;\n      dd = 0.0;\n      for (j=0; j<ncoef; j++) {\n\tdr += coef[j]*gdx[j*nobs+i];\n\tdd += coef[j]*gdy[j*nobs+i];\n      } \n      rx = dx[i] - dr;\n      ry = dy[i] - dd;\n      var = rx*rx + ry*ry;\n      ResidV[i] = var;\n      rms += var;\n      rmscnt++;\n    } \n  } \n\n  /* must have enough data to be over determined */\n  if ((2*rmscnt) < (ncoef+1)) goto cleanup;\n  var = rms/rmscnt;\n  rms = sqrt (var);\n\n  /* Is the current version OK? */\n  if (rms <= MaxRMS) goto cleanup;\n\n  /* find the most discrepent */\n  ibad = -1;\n  baddest = 0.0;\n   for (i=0; i<nobs; i++) {\n     if ((w[i]>0.0) && (ResidV[i]> baddest)) {\n       baddest = ResidV[i];\n       ibad = i;\n     }\n   }\n\n   /* Is the bad one at least 1.5x average variance? */\n   if (baddest<(1.5*var)) goto cleanup;\n\n   w[ibad] = 0.0;  /* Flag it */\n   out = TRUE;     /* Flagged something */\n\n   /* Diagnostics */\n   if (prtLv>=2) {\n     Obit_log_error(err, OBIT_InfoErr, \n\t\t    \"%s: Flag obs %d variance=%f rms=%f\",\n\t\t    routine, ibad+1, baddest*3600.0, rms*3600.0);\n   }\n\n  /* Deallocate memory */\n cleanup: \n   g_free(ResidV);\n   g_free(gdx);\n   g_free(gdy);\n\n  return out;\n} /* end IonEdit1 */ \n\n/**\n * Get timerange of next interval  \n *  Routine translated from the AIPSish IONCAL.FOR/ICNXTI  \n * \\param NXtab    Index table \n * \\param solInt   Solution interval in min. \n * \\param timer    In: previous timerange (days), -1 => none. \n *                 Out: next time range \n * \\param suba     [out] Subarray number \n * \\param err    Error code: 0 => ok, -1 = no more. \n * \\return TRUE if there is more data to process\n */\nstatic gboolean NextTime (ObitTableNX *NXtab, ofloat solInt, \n\t\t\t  ofloat timer[2], olong* suba, ObitErr* err) \n{\n  gboolean out = FALSE;\n  olong  numNX, npiece;\n  olong irow, NXrow=0;\n  ofloat si, tbeg, tend, vtend=0, vtbeg=0, ts, te;\n  ObitTableNXRow *row;\n  gchar *routine = \"NextTime\";\n\n  /* Error checks */\n  if (err->error) return FALSE;  /* previous error? */\n  g_assert(ObitTableNXIsA(NXtab));\n  if (err->error) return FALSE;  /* previous error? */\n\n  /* Create table row */\n  row = newObitTableNXRow (NXtab);\n\n  /* Open table */\n  ObitTableNXOpen(NXtab, OBIT_IO_ReadOnly, err);\n  if (err->error) goto cleanup;\n  numNX = NXtab->myDesc->nrow;\n\n  /* Save initial timerange  */\n  tbeg = timer[0];\n  tend = timer[1];\n  si = solInt / 1440.0;\n  /* Find next scan */\n  for (irow= 1; irow<= numNX; irow++) { /* loop 200 */\n    NXrow = irow;\n    ObitTableNXReadRow (NXtab, NXrow, row, err);\n    if (err->error) goto cleanup;\n    if (row->status<0) continue; /* valid row? */\n    \n    /* time range of this scan */\n    vtbeg = row->Time - 0.5 * row->TimeI;\n    vtend = row->Time + 0.5 * row->TimeI;\n\n    /* Ends before previous start? */\n    if (vtend < tbeg) continue;\n\n    /* Is previous end in this scan? */\n    if ((tend > vtbeg)  &&  (tend < vtend)  && \n\t/* Anything left? */\n\t((tend+0.5*si) < vtend)) break;\n\n    /* Past last scan, take this one */\n    if (tend < vtbeg) break;\n  } /* end loop  L200: */\n\n  out = TRUE;  /* got here without failing */\n\n  /* Are we done? */\n  if ((NXrow == numNX)  &&  ((tend+0.5*si) > vtend)) {\n    out = FALSE;\n    goto cleanup;\n  } \n\n  /* Divide scan into equal pieces */\n  npiece = 0.5 + row->TimeI / si;\n  npiece = MAX (1, npiece);\n  si = row->TimeI / npiece;\n\n  /* which one is this? */\n  ts = MAX (vtbeg, tend);\n  te = ts + si;\n\n  /* Set output */\n  timer[0] = ts;\n  timer[1] = te;\n  *suba = MAX (1, row->SubA);\n\n  /* Found it, close table */\n cleanup: ObitTableNXClose(NXtab, err);\n  row = ObitTableNXRowUnref (row);\n  if (err->error) Obit_traceback_val (err, routine, NXtab->name, out);\n  return out;\n} /* end of routine NextTime */ \n\n\n/**\n * Generate a Calibrator list from an ImageMosaic\n * This assumes that the expected calibrator position is the\n * reference pixel in the image.\n * Calibrators added to CalList as epoch 0;\n * \\param in           IonCal object (used for catalog info )\n * \\param mosaic       Mosaic to use\n * \\param calList      calibrator list, a linked list of calibrators\n * \\param prtLv        Print level >=1, give cal info  >=3 => give full list\n * \\param err          Error stack, returns if not empty.\n */\nstatic void \nFindCalMosaic (ObitIonCal *in, ObitImageMosaic *mosaic, \n\t       CalList *calList, olong prtLv, ObitErr *err)\n{\n  olong field, calNo, cqual, ierr, epoch=0;\n  ofloat  flux, peak=0.0, fint=0.0, wt=0.0;\n  ofloat ZernXY[2], shift[2], pixel[2], offset[2]={0.0,0.0};\n  odouble ra, dec, raPnt, decPnt;\n  ObitImageDesc *desc=NULL;\n  CalListElem *elem=NULL;\n  gchar *routine = \"FindCalMosaic\";\n  \n  /* error checks */\n  if (err->error) return;\n  g_assert(ObitImageMosaicIsA(mosaic));\n\n  /* Get pointing position for offsets */\n  desc = mosaic->images[0]->myDesc;\n  ObitImageDescGetPoint (desc, &raPnt, &decPnt);\n\n  /* Loop over images */\n  for (field=0; field<mosaic->numberImages; field++) {\n    calNo = field+1;\n\n    /* Info from Mosaic */\n    desc = mosaic->images[field]->myDesc;\n    ra  = desc->crval[desc->jlocr];\n    dec = desc->crval[desc->jlocd];\n    pixel[0] = desc->crpix[desc->jlocr];\n    pixel[1] = desc->crpix[desc->jlocd];\n\n    /*  Some items to be filled in from catalog */\n    cqual = -1;\n    flux  = -1.0;\n\n    /* get shift needed */\n    ObitSkyGeomShiftXY (raPnt, decPnt, desc->crota[desc->jlocd], ra, dec, \n\t\t\t&shift[0], &shift[1]);\n    \n    /* Offset on Zernike plane */\n    ObitSkyGeomRADec2Zern ( raPnt, decPnt, shift[0], shift[1],\n\t\t\t    &ZernXY[0], &ZernXY[1], &ierr);\n    Obit_return_if_fail((ierr==0), err,\n\t\t\t\"%s: Error projecting onto Zernike Unit circle\", routine);\n    \n    /* Add to CalList */\n    elem = newCalListElem (ra, dec, ZernXY, shift, pixel, flux, offset, \n\t\t\t   peak, fint, wt, cqual, calNo, epoch);\n    CalListAdd (calList, elem);\n  } /* end loop over fields */\n\n  /* Get calibrator information from calList */\n  LookupCals (in, mosaic, calList, prtLv, err);\n  if (err->error) Obit_traceback_msg (err, routine, in->name);\n\n  /* Diagnostics? */\n  if (prtLv>=3) {\n    CalListPrint(calList, stdout); \n  }\n} /* end FindCalMosaic */\n\n/**\n * Looks up calibrators in calList in the catalog specified (or implied)\n * by in->info and fills in catalog information.\n * Adapted from the AIPSish ADNVSS in $FOURMASS/SUB/ADDFIELDS.FOR\n * \\param in           IonCal with catalog information\n * \\param mosaic       ImageMosaic to describing calList fields\n * \\param calList      calibrator list, a linked list of calibrators\n * \\param prtLv        Print level >=1 => give list\n * \\param err          Error stack, returns if not empty.\n */\nstatic void \nLookupCals (ObitIonCal *in, ObitImageMosaic *mosaic, CalList *calList, \n\t    olong prtLv, ObitErr *err)\n{\n  gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};\n  ObitInfoType type;\n  gchar Catalog[257];\n  olong catDisk;\n\n  olong count, cqual;\n  odouble Freq, ra, dec, rar, decr, raPntr, decPntr;\n  odouble xx, yy, zz, dist, refreq;\n  ofloat radius, radRA, asize, alpha, pbf;\n  ofloat equinox, flux, scale;\n  gboolean doJ2B, doJinc;\n  olong blc[IM_MAXDIM] = {1,1,1,1,1};\n  olong trc[IM_MAXDIM] = {0,0,0,0,0};\n  olong ver, nrows, irow;\n  ObitIOCode retCode;\n  ObitImage *VZImage=NULL;\n  ObitTableVZ *VZTable=NULL;\n  ObitTableVZRow *VZRow=NULL;\n  ObitImageDesc *desc=NULL;\n  GSList *tmp;\n  CalListElem *elem=NULL;\n  gchar *routine = \"LookupCals\";\n  \n  /* error checks */\n  if (err->error) return;\n  g_assert(ObitImageMosaicIsA(mosaic));\n\n  /* get control parameters */\n  /* Control information. */\n  sprintf (Catalog, \"Default\");\n  ObitInfoListGetTest(in->info, \"Catalog\", &type, dim,  Catalog);\n  if (err->error) Obit_traceback_msg (err, routine, in->name);\n  if (!strncmp(Catalog, \"    \", 4)) sprintf (Catalog, \"Default\");\n  if (!strncmp(Catalog, \"Default\", 7)) sprintf (Catalog, \"NVSSVZ.FIT\");\n  catDisk = 1;\n  ObitInfoListGetTest(in->info, \"CatDisk\",   &type, dim, &catDisk);\n  alpha = -0.75;\n  ObitInfoListGetTest(in->info, \"OutlierSI\", &type, dim, &alpha);\n  asize = 25.0;\n  ObitInfoListGetTest(in->info, \"AntDiam\", &type, dim, &asize);\n\n  /* set defaults. */\n  if (asize <= 0.0)  asize  = 25.0;\n  if (alpha == 0.0)  alpha  = -0.75;\n\n  /* set crude search radius = 0.5*sqrt(2)*MAX (x_size, Y_size) */\n  desc = mosaic->images[0]->myDesc;\n  radius = 0.5 * sqrt (2.0) * \n    MIN (fabs(desc->cdelt[desc->jlocr]*desc->inaxes[desc->jlocr]),\n\t fabs(desc->cdelt[desc->jlocd]*desc->inaxes[desc->jlocd]));\n  radRA = radius / cos(desc->crval[desc->jlocd]*DG2RAD);\n  \n  /* Get pointing position for offsets */\n  ObitImageDescGetPoint (desc, &raPntr, &decPntr);\n  raPntr  *= DG2RAD;\n  decPntr *= DG2RAD;\n\n  /* Observing frequency */\n  if (desc->jlocf>=0) Freq = desc->crval[desc->jlocf];\n  else Freq = 1.0e9;\n\n  /* which beam model to use */\n  doJinc = (Freq >= 1.0e9);\n\n  /* Need precession? */\n  equinox = in->myData->myDesc->equinox;  /* Clear up confusion in AIPS */\n  if (equinox<1.0) equinox = in->myData->myDesc->epoch;\n  doJ2B = (equinox!=2000.0) ;  /* need to precess? */\n\n  /* Open Catalog (VZ table on an image) */\n  VZImage = newObitImage(\"Catalog image\");\n  ObitImageSetFITS(VZImage, OBIT_IO_byPlane, catDisk, Catalog, blc, trc, err);\n  if (err->error) goto cleanup;\n\n  /* Open to fully instantiate */\n  ObitImageOpen(VZImage, OBIT_IO_ReadOnly, err);\n  if (err->error) goto cleanup;\n\n  /* Now get VZ table */\n  ver = 1;\n  VZTable =  newObitTableVZValue(\"Catalog table\", (ObitData*)VZImage, &ver, \n\t\t\t\t OBIT_IO_ReadOnly, err);\n  ObitTableVZOpen(VZTable, OBIT_IO_ReadOnly, err);\n  VZRow =  newObitTableVZRow (VZTable);  /* Table row */\n  if (err->error) goto cleanup;\n\n  /* Get table info */\n  refreq = VZTable->refFreq;\n  nrows  = VZTable->myDesc->nrow;\n\n  /* frequency scaling */\n  scale = pow ((Freq / refreq), alpha);\n\n  /* loop through table */\n  count = 0;\n  for (irow= 1; irow<=nrows; irow++) { /* loop 500 */\n    /* read */\n    retCode = ObitTableVZReadRow (VZTable, irow, VZRow, err);\n    if (err->error) goto cleanup;\n   \n    /* spectral scaling of flux density */\n    flux = VZRow->PeakInt * scale;\n\n    /* position, etc */\n    ra    = VZRow->Ra2000;\n    dec   = VZRow->Dec2000;\n    /* Need in 1950? */\n    if (doJ2B) ObitSkyGeomJtoB (&ra, &dec);\n    rar   = ra * DG2RAD;\n    decr  = dec * DG2RAD;\n    cqual = VZRow->Quality;\n\n    /* Loop over calList */\n    tmp = calList->list;\n    while (tmp!=NULL) {\n      elem = (CalListElem*)tmp->data;\n      \n      /* select (crude) */\n      if ((fabs(dec-elem->dec) <= radius)  && (fabs(ra-elem->ra) <= radRA)) {\n\t/* separation from pointing center */\n\txx = DG2RAD * elem->ra;\n\tyy = DG2RAD * elem->dec;\n\tzz = sin (yy) * sin (decr) + cos (yy) * cos (decr) * cos (xx-rar);\n\tzz = MIN (zz, 1.000);\n\tdist = acos (zz) * RAD2DG;\n\t\n\t/* Must be within a pixel */\n\tif (dist<fabs(desc->cdelt[desc->jlocr])) {\n\t  \n\t  /* Distance from pointing center */\n\t  zz = sin (yy) * sin (decPntr) + cos (yy) * cos (decPntr) * cos (xx-raPntr);\n\t  zz = MIN (zz, 1.000);\n\t  dist = acos (zz) * RAD2DG;\n\n\t  /* primary beam correction to flux density */\n\t  if (doJinc) {\n\t    pbf = ObitPBUtilJinc (dist, Freq, asize, 0.05);\n\t  } else {\n\t    pbf = ObitPBUtilPoly (dist, Freq, 0.05);\n\t  } \n\t  flux *= MAX (0.05, pbf); /* Don't trust below 5% */\n\t  \n\t  /* update CalList */\n\t  CalListElemUpdate (elem, elem->ra, elem->dec, elem->ZernXY, elem->shift, \n\t\t\t     elem->pixel, flux, elem->offset, \n\t\t\t     elem->peak, elem->fint, elem->wt, cqual, \n\t\t\t     elem->calNo, elem->epoch);\n\t  count++;\n\n\t  /* Diagnostics? */\n\t  if (prtLv>=1) {\n\t    Obit_log_error(err, OBIT_InfoErr, \n\t\t\t   \"Cal %4d RA=%8.5f Dec=%9.5f Z= %7.4f %7.4f Flux=%6.2f qual=%d\",\n\t\t\t   elem->calNo,  elem->ra, elem->dec, elem->ZernXY[0], elem->ZernXY[1], \n\t\t\t  flux, cqual);\n\t  }\n\t} /* End update entry */\n      } /* end crude selection */\n      tmp = g_slist_next(tmp);  /* next item in list */\n    } /* end loop over calList */\n  } /* end loop over table */\n\n  /* tell how many */\n  Obit_log_error(err, OBIT_InfoErr, \"%s: Found %d calibrators\", routine, count);\n\n  /* Close up */\n  ObitImageClose(VZImage, err);\n  retCode = ObitTableVZClose(VZTable, err);\n  if (err->error) goto cleanup;\n  /* clean up */\n cleanup: VZImage = ObitImageUnref(VZImage);\n  VZTable = ObitTableUnref(VZTable);\n  VZRow   = ObitTableRowUnref(VZRow);\n  if (err->error) Obit_traceback_msg (err, routine, VZTable->name);\n  \n} /* end of routine LookupCals */ \n\n/**\n * Filter position offset solutions and fit Zernike models to each epoch.\n * Results written into NI table which is returned.\n * Routine adapted from the AIPSish IONCAL.FOR/IONFIT \n * \\param in   IonCal object \n *   Control parameters are on the info member.\n * \\li \"FitDist\"  OBIT_int   (1,1,1) dist, from expected location to search \n *                                   asec [10 pixels]\n * \\li \"MinPeak\"  OBIT_float (1,1,1) Min. acceptable image peak (Jy) [1.0]\n * \\li \"MaxDist\"  OBIT_float (1,1,1) Max. distance (deg/10) to accept calibrator [1.]\n * \\li \"MaxWt\"    OBIT_float (1,1,1) Max. weight [10.0]\n * \\li prtLv      OBIT_int   (1,1,1) Print level >=1 => give fits\n * \\param calList Calibrator list each element of which has:\n * \\li ra      position RA (deg) of calibrators\n * \\li dec     position Dec (deg) of calibrators\n * \\li shift   Offset in field [x,y] on unit Zernike circle of position\n * \\li pixel   Expected pixel in reference image\n * \\li flux    Estimated catalog flux density \n * \\li offset  Measured offset [x,y] from expected position (deg)\n * \\li peak    Measured peak flux density (image units)\n * \\li fint    Measured integrated flux density (image units)\n * \\li wt      Determined weight\n * \\li qual    Catalog quality code\n * \\param ncoef      Maximum number of coefficients to fit\n * \\param nEpoch     Number of epochs\n * \\param timeEpoch  Center time of each Epoch (day)\n * \\param timeIEpoch Time interval of each Epoch (day)\n * \\param subaEpoch  Epoch subarray\n * \\param refFreq    Reference Frequency for NI table (Hz)\n * \\param seeing     [out] RMS residual to final fits (asec).\n * \\param err        Error stack\n */\nstatic ObitTableNI* \nFitAll (ObitIonCal *in, olong ncoef, olong nEpoch, \n\tofloat *timeEpoch, ofloat *timeIEpoch, olong *subaEpoch,\n\todouble refFreq, ofloat *seeing, ObitErr* err)  \n{\n  ObitTableNI* out = NULL;\n  ObitUV *inUV=NULL;\n  CalListElem *elem=NULL;\n  GSList  *tmp;\n  CalList *calList;\n  ofloat maxWt, MaxRMS, MinRat, MinPeak, FCStrong;\n  gboolean doINEdit;\n  olong prtLv, nobs, nTime, nsou, maxQual, is;\n  gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};\n  ObitInfoType type;\n  olong *isou=NULL, *iTime=NULL, *flqual=NULL;\n  ofloat *x=NULL, *y=NULL, *xoff=NULL, *yoff=NULL, \n    *flux=NULL, *wt=NULL, *sint=NULL;\n  gchar *routine = \"FitAll\";\n\n  /* Error checks */\n  if (err->error) return NULL;  /* previous error? */\n  g_assert(ObitIonCalIsA(in));\n\n  *seeing = -1.0;\n  calList = (CalList*)in->calList;\n  inUV = in->myData;\n\n  /* Control information. */\n  maxWt = 10.0;\n  ObitInfoListGetTest(in->info, \"MaxWt\",   &type, dim, &maxWt);\n  prtLv = 0;\n  ObitInfoListGetTest(in->info, \"prtLv\",   &type, dim, &prtLv);\n  MaxRMS = 10;\n  ObitInfoListGetTest(in->info, \"MaxRMS\", &type, dim, &MaxRMS);\n  MaxRMS /= 3600.0;  /* to degrees */\n  doINEdit = TRUE;\n  ObitInfoListGetTest(in->info, \"doINEdit\", &type, dim, &doINEdit);\n  maxQual = 1;\n  ObitInfoListGetTest(in->info, \"MaxQual\",   &type, dim, &maxQual);\n  MinRat = 0.1;\n  ObitInfoListGetTest(in->info, \"MinRat\", &type, dim, &MinRat);\n  MinPeak = 1.0;\n  ObitInfoListGetTest(in->info, \"MinPeak\", &type, dim, &MinPeak);\n  FCStrong = 1.0e6;\n  ObitInfoListGetTest(in->info, \"FCStrong\", &type, dim, &FCStrong);\n\n  /* Count number of sources, number of times and number of obs */\n  nobs = nTime = nsou = 0;\n  tmp = calList->list;\n  while (tmp!=NULL) {   /* loop 100 */\n    elem = (CalListElem*)tmp->data;\n    if (elem->epoch > 0) {\n      nobs++;\n      nTime = MAX (nTime, elem->epoch);\n      nsou  = MAX (nsou,  elem->calNo);\n    }\n    /* if find epoch > 0 then quit loop */\n    tmp = g_slist_next(tmp);  /* next item in list */\n } /* end loop  L100: over calibrator*/\n\n  /* Create arrays */\n  isou   = g_malloc0(nobs*sizeof(olong));\n  iTime  = g_malloc0(nobs*sizeof(olong));\n  flqual = g_malloc0(nobs*sizeof(olong));\n  x      = g_malloc0((nsou+1)*sizeof(ofloat));\n  y      = g_malloc0((nsou+1)*sizeof(ofloat));\n  xoff   = g_malloc0(nobs*sizeof(ofloat));\n  yoff   = g_malloc0(nobs*sizeof(ofloat));\n  flux   = g_malloc0(nobs*sizeof(ofloat));\n  wt     = g_malloc0(nobs*sizeof(ofloat));\n  sint   = g_malloc0(nobs*sizeof(ofloat));\n\n  /* Extract data from calList */\n  nobs = 0;\n  tmp = calList->list;\n  while (tmp!=NULL) {   /* loop 100 */\n    elem = (CalListElem*)tmp->data;\n    if (elem->epoch > 0) {\n      isou[nobs]   = elem->calNo-1;\n      iTime[nobs]  = elem->epoch-1;\n      flqual[nobs] = elem->qual;\n      is           = MAX (0, MIN (isou[nobs], nsou));\n      x[is]        = elem->ZernXY[0];\n      y[is]        = elem->ZernXY[1];\n      xoff[nobs]   = elem->offset[0];\n      yoff[nobs]   = elem->offset[1];\n      flux [nobs]  = elem->peak;\n      sint[nobs]   = elem->fint;\n      /* Impose maximum Quality */\n      if (elem->qual<=maxQual) wt[nobs] = elem->wt;\n      else wt[nobs] = 0.0;\n      wt[nobs] = MIN (wt[nobs], maxWt);\n      /* Impose minimum flux density */\n      if (flux[nobs]<MinPeak) wt[nobs] = 0.0;\n      nobs++;\n    }\n    /* if find epoch > 0 then quit loop */\n    tmp = g_slist_next(tmp);  /* next item in list */\n } /* end loop  L100: over calibrator*/\n\n\n  /* do fitting */\n  out = doIonFitAll (inUV, MaxRMS, MinRat, FCStrong, doINEdit, \n\t\t     ncoef, nsou, isou, x, y, nEpoch, \n\t\t     timeEpoch, timeIEpoch, subaEpoch, \n\t\t     nobs, iTime, xoff, yoff, flux, wt, flqual, sint, \n\t\t     prtLv, refFreq, seeing, err);\n\n  /* deallocate arrays */\n  /*    cleanup:*/\n  if (isou) g_free(isou);\n  if (iTime) g_free(iTime);\n  if (flqual) g_free(flqual);\n  if (x) g_free(x);\n  if (y) g_free(y);\n  if (xoff) g_free(xoff);\n  if (yoff) g_free(yoff);\n  if (flux) g_free(flux);\n  if (wt) g_free(wt);\n  if (sint) g_free(sint);\n  if (err->error) Obit_traceback_val (err, routine, in->name, out);\n  return out;\n} /* end of routine FitAll  */ \n\n/**\n * Weighted fit ionospheric model to data using Zernike polynomials.  \n * Also filters data on basis of RMS residual if RMS exceeds MaxRMS.  \n * Writes values to the output IoN (NI) table.  \n * Ignores sources further than 10 degrees from the pointing  \n * Position are all referred to a tangent plane at the  \n * pointing center, this is referred to as the Zernike plane as this  \n * plane will be used to fit the phase screen.  The \"Zernike Unit  \n * Circle\" defines the phase screen.  Source position offsets are in  \n * the x and y (RA, Dec) as defined by this plane.  \n * Routine translated from the AIPSish IONCAL.FOR/IONFIT  \n * Input:  \n * \\param inUV     UV data to which output NI table is to be attached.\n * \\param MaxRMS   Max. allowable RMS before filtering data. (deg) \n * \\param MinRat   Minimum acceptable ratio to average flux \n * \\param FCStrong Min. Flux for strong (required) cal \n * \\param doINEdit if true flag solutions for which the seeing residual \n *                 could not be determined or exceeds MAXRMS \n * \\param ncoef    Number of Zernike coeffients to solve for. \n * \\param nsou     Number of sources \n * \\param isou     Source numbers (0-rel)\n * \\param x        X Offset (RA) in field on unit Zernike circle per source  \n * \\param y        Y Offset (Dec) in field on unit Zernike circle per source  \n * \\param nTime    Number of time intervals \n * \\param Time     Center time of each integration \n * \\param TimeI    Time Interval of each integration \n * \\param isuba    Subarray number per time \n * \\param n        Number of data points (observations)\n * \\param iTime    Time interval number per observation.(0-rel)\n * \\param xoff     Apparent RA position shifts on the Zernike plane (deg) \n *                 per observation\n * \\param yoff     Apparent dec position shifts on the Zernike plane (deg) \n *                 per observation\n * \\param flux     Array of measured peak flux densities \n *                 per observation\n * \\param wt       Array of weights,  per observation\n * \\param flqual   Field quality (crowding) code. Used in determining \n *                 if the apparent position of a source can be moved. \n *                 per observation\n * \\param sint     Array of measured integrated flux densities \n *                 per observation\n * \\param prtLv    Print level >=1 => give fitting diagnostics\n * \\param refFreq    Reference Frequency for NI table (Hz)\n * \\param totRMS   [out] Total residual RMS seeing in asec\n * \\param err      Error stack\n * \\return ObitTableNI into which values were written (ver 1)\n */\n static ObitTableNI* \n doIonFitAll (ObitUV *inUV, ofloat MaxRMS, ofloat MinRat, ofloat FCStrong, gboolean doINEdit, \n\t      olong ncoef, olong nsou, olong* isou, ofloat* x, ofloat* y, \n\t      olong nTime, ofloat* Time, ofloat* TimeI, olong* isuba, \n\t      olong n, olong* iTime, ofloat* xoff, ofloat* yoff, \n\t      ofloat* flux, ofloat *wt, olong* flqual, ofloat* sint, \n\t      olong prtLv, odouble refFreq, ofloat* totRMS, ObitErr* err) \n{\n  ObitTableNI *outTab = NULL;\n  ObitTableNIRow *NIrow=NULL;\n  olong     i, j, ntoss;\n  ofloat   xy, timer[2], fblank = ObitMagicF();\n  gboolean redo, redo2;\n  olong     *mcoef=NULL, ngood, nbad, maxcoef;\n  ofloat   **coef=NULL, *soffx=NULL, *soffy=NULL, *rms=NULL;\n  gboolean *gotsou=NULL, *fitsou=NULL, allFlag, OK;\n  olong ver, rowNo;\n  gchar msgtxt[80];\n  gchar *routine = \"doIonFitAll\";\n\n  /* Error checks */\n  if (err->error) return outTab;  /* previous error? */\n  g_assert(ObitUVIsA(inUV));\n\n  /* Something to do? */\n  if ((n<1) || (nsou<1)) return outTab;\n\n  /* allocate arrays */\n  mcoef  = g_malloc0(nTime*sizeof(olong));\n  rms    = g_malloc0((nTime+1)*sizeof(ofloat));\n  soffx  = g_malloc0(nsou*sizeof(ofloat));\n  soffy  = g_malloc0(nsou*sizeof(ofloat));\n  gotsou = g_malloc0(nsou*sizeof(gboolean));\n  fitsou = g_malloc0(nsou*sizeof(gboolean));\n  coef   = g_malloc0(nTime*sizeof(ofloat*));\n  for (i=0; i<nTime; i++) coef[i] = g_malloc0(ncoef*sizeof(ofloat));\n\n  /* Diagnostics - show input data */\n  if (prtLv>=3) {\n    /* Source info */ \n       for (i=0; i<nsou; i++) {\n       Obit_log_error(err, OBIT_InfoErr, \n       \"Source %4d Zernike offset = %10.6f %10.6f\", i+1, x[i], y[i]);\n       }\n    /* Epoch info */\n    for (i=0; i<nTime; i++) {\n      Obit_log_error(err, OBIT_InfoErr, \n\t\t     \"Time %4d Time %10.6f hr dTime%10.6f min Subarray %4d\", \n\t\t     i+1, Time[i]*24.0, TimeI[i]*1440.0, isuba[i]);\n    }\n    /* Measurement data */\n    for (i=0; i<n; i++) {\n      Obit_log_error(err, OBIT_InfoErr, \n\t\t     \"Obs %4d Time %5d Sou %5d Offset %6.2f %6.2f Peak %6.2f Int %6.2f qual %2d\", \n\t\t     i+1, iTime[i]+1, isou[i]+1, xoff[i]*3600.0, yoff[i]*3600.0, flux[i], sint[i], flqual[i]);\n    }\n    ObitErrLog(err);\n  } /* end diagnostics */\n\n\n  allFlag = TRUE;\n  for (j=0; j<nsou; j++) { /* loop 50 */\n    /* Diagnostics */\n    if (prtLv>=3) {\n      Obit_log_error(err, OBIT_InfoErr, \n\t\t     \"%s: S=%4d x=%10.5f y=%10.5f\", routine, j+1, x[j], y[j]);\n    }\n\n    /* Flag data for sources further than 10 deg (1 on unit circle) */\n    xy = sqrt (x[j]*x[j] + y[j]*y[j]);\n    if (xy > 1.0) {\n      for (i=0; i<n; i++) { /* loop 40 */\n\tif (isou[i] == (j+1)) flux[i] = 0.0;\n      } /* end loop  L40:  */;\n    } \n  } /* end loop  L50:  */\n\n  /* further constraints on weights */\n  for (i=0; i<n; i++) { /* loop 60 */\n    /* Toss data if integrated value less than a third the peak\n    if (sint[i]  <  (0.35*flux[i])) wt[i] = 0.0; */\n    if (sint[i]  <  (0.05*flux[i])) wt[i] = 0.0; /* DEBUG */\n    /* ... more than thrice the peak */\n    if (sint[i]  >  (3.0*flux[i])) wt[i] = 0.0;\n  } /* end loop  L60:  */\n\n  /* Init Ionospheric model */\n  OK = initIonModel (n, nsou, nTime, ncoef, isou, iTime,  x, y, xoff, yoff, wt, \n\t\t     flqual, mcoef, gotsou, fitsou, soffx, soffy, coef, prtLv, err);\n  if (err->error) goto cleanup;\n  if (!OK) {allFlag=TRUE; goto AllBad;}  /* Fell flat */\n\n  /* How many sources actually have  data?  */\n  ngood = 0;\n  for (i=0; i<nsou; i++) { /* loop 70 */\n    if (gotsou[i]) ngood++;\n  } /* end loop  L70:  */\n  \n  /* Fit Ionospheric model if enough  data  */\n  if (ngood > 3)\n    FitIonSeries (n, nsou, nTime, ncoef, isou, iTime,  x, y, xoff, yoff, wt,  \n\t\t  mcoef, gotsou, fitsou, soffx, soffy, coef, rms, prtLv, err);\n  if (err->error) goto cleanup;\n\n  /* If only one source dummy rms at 1 asec */\n  if (ngood==1) {\n    for (i=0; i<nTime; i++) rms[i] = 1.0/ 3600.0;\n  }\n\n  /* Edit Ionospheric model */\n  if (doINEdit  &&  (ngood > 3)) {\n        redo = IonEditSeries (n, nsou, nTime, ncoef, isou, iTime,  x, y, \n\t\t\t      xoff, yoff, wt, MaxRMS, mcoef, \n\t\t\t      soffx, soffy, coef, prtLv, err);\n\tif (err->error) goto cleanup; \n\n\t/* Edit By amplitude */\n\tredo2 = IonEditAmp (n, nsou, nTime, isou, iTime, MinRat,  FCStrong, flux, mcoef, wt, \n\t\t\t    prtLv, err);\n        redo = redo || redo2;\n\tif (err->error) goto cleanup;\n\t\n\t/* Redo Ionospheric model if data edited */\n\tif (redo) {\n\t  OK = initIonModel (n, nsou, nTime, ncoef, isou, iTime,  x, y, xoff, yoff, \n\t\t\t     wt, flqual, mcoef, gotsou, fitsou, soffx, soffy, coef, \n\t\t\t     prtLv, err);\n\t  if (err->error) goto cleanup;\n\t  if (!OK) {allFlag = TRUE; goto AllBad;}\n\t} \n\t\n\t/* Refit Ionospheric model */\n\tFitIonSeries (n, nsou, nTime, ncoef, isou, iTime,  x, y, xoff, yoff, \n\t\t      wt,  mcoef, gotsou, fitsou, soffx, soffy, coef, rms, prtLv, err);\n\tif (err->error) goto cleanup;\n  } /* end editing */\n\n  /* Only take solutions with the maximum number of terms */\n  maxcoef = -1;\n  ntoss = nbad = 0;\n  for (j=0; j<nTime; j++) maxcoef = MAX (maxcoef, mcoef[j]);\n \n  /* Create outputNI table */\n  ver = 1;\n  outTab = newObitTableNIValue (\"IonCal NI table\", (ObitData*)inUV, &ver, \n\t\t\t       OBIT_IO_WriteOnly, ncoef, err);\n  if (err->error) goto cleanup;\n  NIrow = newObitTableNIRow (outTab);       /* Row structure */\n  NIrow->antNo  = 0;  /* No antenna specific */\n  NIrow->SourId = 0;  /* no source ID */\n  \n  /* Clear any existing rows */\n  ObitTableClearRows ((ObitTable*)outTab, err);\n  if (err->error) goto cleanup;\n\n  /* Open output NI table */\n  ObitTableNIOpen (outTab, OBIT_IO_WriteOnly, err);\n  ObitTableNISetRow (outTab, NIrow, err);   /* Attach row for writing */\n  if (err->error) goto cleanup;\n\n  /* Header keywords */\n  outTab->heightIon = 1.0e7;  /* Height of ionosphere = large */ \n  outTab->refFreq = refFreq;  /* image reference freq */\n\n  /* Loop over times writing results */\n  for (i=0; i<nTime; i++) { /* loop 200 */\n    /* Set IN table entry bad if mcoef[i] = 0 */\n    if ((mcoef[i]<maxcoef) && (mcoef[i]>0)) ntoss++;\n    if ((mcoef[i] >= maxcoef) && (rms[i] > 0.0)) {\n      NIrow->weight = 1.0 / MAX (0.001, rms[i]);\n    } else {\n      nbad++;  /* Count the bad */\n      NIrow->weight = 0.0;\n      rms[i] = -1.0;\n      for (j=0; j<ncoef; j++) coef[i][j] = fblank;\n    } \n\n    /* Fill row structure */\n    NIrow->Time  = Time[i];\n    NIrow->TimeI = TimeI[i];\n    NIrow->SubA  = isuba[i];\n    for (j=0; j<ncoef; j++) NIrow->coef[j] = coef[i][j];\n\n    /* Write */\n    rowNo = -1;\n    ObitTableNIWriteRow (outTab, rowNo, NIrow, err);\n    if (err->error) goto cleanup;\n\n\n    /* Tell about it */\n    if (prtLv>=1) {\n      timer[0] = Time[i]-0.5*TimeI[i]; timer[1] = Time[i]+0.5*TimeI[i]; \n      TR2String (timer, msgtxt);\n      Obit_log_error(err, OBIT_InfoErr, \n\t\t     \"%5d Time %s  RMS bias corr resid = %7.1f asec\",i+1, msgtxt,rms[i]*3600.0);\n      /* Give coefficients if fitted */\n      if (NIrow->weight<=0.0) {\n\tObit_log_error(err, OBIT_InfoWarn, \"This interval to be ignored\");\n      } else {  /* OK */\n\tif (maxcoef==2)\n\t  Obit_log_error(err, OBIT_InfoErr, \" %10.2f %10.2f \",\n\t\t\t 3600.0*coef[i][0], 3600.0*coef[i][1]);\n\telse\n\t  Obit_log_error(err, OBIT_InfoErr, \" %10.2f %10.2f %10.2f %10.2f %10.2f\",\n\t\t\t 3600.0*coef[i][0], 3600.0*coef[i][1], 3600.0*coef[i][2],\n\t\t\t 3600.0*coef[i][3], 3600.0*coef[i][4]);\n\tif (maxcoef>5) {\n\t  Obit_log_error(err, OBIT_InfoErr, \" %10.2f %10.2f %10.2f %10.2f %10.2f\",\n\t\t\t 3600.0*coef[i][5], 3600.0*coef[i][6], 3600.0*coef[i][7],\n\t\t\t 3600.0*coef[i][8], 3600.0*coef[i][9]);\n\t}\n\tif (maxcoef>10) {\n\t  Obit_log_error(err, OBIT_InfoErr, \" %10.2f %10.2f %10.2f %10.2f %10.2f\",\n\t\t\t 3600.0*coef[i][10], 3600.0*coef[i][11], 3600.0*coef[i][12],\n\t\t\t 3600.0*coef[i][13], 3600.0*coef[i][14]);\n\t}\n\tif (maxcoef>15) {\n\t  Obit_log_error(err, OBIT_InfoErr, \" %10.2f %10.2f %10.2f %10.2f %10.2f\",\n\t\t\t 3600.0*coef[i][15], 3600.0*coef[i][16], 3600.0*coef[i][17],\n\t\t\t 3600.0*coef[i][18], 3600.0*coef[i][19]);\n\t}\n      }\n    } /* end diagnostics */\n  } /* end loop  L200: */\n\n  /* Close NI table */\n  ObitTableNIClose (outTab, err);\n  if (err->error) goto cleanup;\n\n  /* Total RMS */\n  (*totRMS) = 3600.0 * rms[nTime];\n\n  /* Tell about it */\n  if (prtLv>=1) {\n    if (ntoss>0)\n      Obit_log_error(err, OBIT_InfoErr, \"%s: Flagged %d of %d intervals for too few Zernike coef.\",\n\t\t     routine, ntoss, nTime);\n    if (nbad>0)\n      Obit_log_error(err, OBIT_InfoErr, \"%s: Flagged total %d of %d intervals\",\n\t\t     routine, nbad, nTime);\n    Obit_log_error(err, OBIT_InfoErr, \"Total corrected rms residual = %7.1f asec\",\n\t\t   *totRMS);\n  \n    /* Source offsets */\n    for (i=0; i<nsou; i++) { /* loop 240 */\n      if (gotsou[i]  &&  fitsou[i]) {\n\tObit_log_error(err, OBIT_InfoErr, \"Source %5d offset = %7.1f%7.1f \",\n\t\t       i+1, 3600.0*soffx[i], 3600.0*soffy[i]);\n      } \n    } /* end loop  L240: */\n  } /* end diagnostics */\n\n goto cleanup;\n\n    /* Solution failed */\n AllBad:\n  if (allFlag) Obit_log_error(err, OBIT_Error, \n\t\t\t      \"%s: All ionospheric solutions bad\", routine);\n\n  /* cleanup - deallocate arrays */\n cleanup:\n  NIrow = ObitTableNIRowUnref (NIrow);\n  /* deallocate arrays */\n  if (mcoef)  g_free(mcoef);\n  if (rms)    g_free(rms);\n  if (soffx)  g_free(soffx);\n  if (soffy)  g_free(soffy);\n  if (gotsou) g_free(gotsou);\n  if (fitsou) g_free(fitsou);\n  if (coef)   {\n    for (i=0; i<nTime; i++) g_free(coef[i]);\n    g_free(coef);\n  }\n  if (err->error) Obit_traceback_val (err, routine, inUV->name, outTab);\n\n  return outTab;\n} /* end of routine doIonFitAll */ \n\n/**\n * Initialize Zernike model to apparent position offsets for a time  \n * series allowing for a systematic offset on the apparent source  \n * positions.   \n * Each time is analysed with fixed source positions and the soffx and  \n * soffy are set based on the average residual.  A comparison of the  \n * average residual with the total rms residual is used to decide if an   \n * offset is to be fitted to each source (fitsou). \n * Offsets are only allowed for flqual values > 0 \n * Routine translated from the AIPSish IONCAL.FOR/INCINI  \n * \\param nobs     Number of observations \n * \\param nsou     Number of sources \n * \\param nTime    Number of times   \n * \\param maxcoe   Leading dimension of COEF \n * \\param isou     Source number per obs.  (0-rel)\n * \\param iTime    Time interval number per observation.\n * \\param x        Offset in field X (RA) on unit Zernike circle /source\n * \\param y        Offset in field Y (Dec) on unit Zernike circle /source\n * \\param dx       Apparent RA position shifts on the Zernike plane (deg) /obs\n * \\param dy       Apparent dec position shifts on the Zernike plane (deg) /obs\n * \\param w        Weight of observations  /obs\n * \\param flqual   Field quality (crowding) code. Used in determining \n *                 if the apparent position of a source can be moved. \n * \\param ncoef    Number of coefficents fitted per time \n * \\param gotsou   If true, there is data for this souce \n * \\param fitsou   If true fit offset correction for each source \n * \\param soffx    Initial guess for source offset in x=ra (deg) \n * \\param soffy    Initial guess for source offset in y=dec (deg) \n * \\param coef     Initial guess for Zernike coefficients (term,time) \n * \\param prtLv    Print level >=1 => give fitting diagnostics\n * \\param err      Error/message stack \n * \\return TRUE if data OK, else too little data\n */\nstatic gboolean \ninitIonModel (olong nobs, olong nsou, olong nTime, olong maxcoe, olong* isou, \n\t      olong* iTime, ofloat*  x, ofloat* y, ofloat* dx, ofloat* dy, \n\t      ofloat* w, olong*  flqual, olong* ncoef, gboolean* gotsou, \n\t      gboolean* fitsou, ofloat* soffx, ofloat* soffy, ofloat** coef, \n\t      olong prtLv, ObitErr* err) \n{\n  gboolean out=FALSE;\n  olong   i, j, k, it, is, itim, rmscnt, numobs, numprm, itlast, itb, ite, js, ntgood;\n  olong   qual;\n  ofloat rms, dr, dd, rx, ry, rr;\n  ofloat *sum2p1=NULL, *sum2p2=NULL, *sum3p1=NULL, *sum3p2=NULL;\n  ofloat *tcoef=NULL, *gdx=NULL, *gdy=NULL;\n  gchar *routine = \"initIonModel\";\n\n    /* Error checks */\n  g_assert(ObitErrIsA(err));\n  if (err->error) return out;  /* previous error? */\n\n  /* Initial guess (0's) */\n  for (itim=0; itim<nTime; itim++) { /* loop 30 */\n    ncoef[itim] = 0;\n    for (i=0; i<maxcoe; i++) { /* loop 20 */\n      coef[itim][i] = 0.0;\n    } /* end loop  L20:  */\n  } /* end loop  L30:  */\n\n  /* if only one source just use tip and tilt */\n  if (nsou==1) {\n    for (itim=0; itim<nTime; itim++) { /* loop 30 */\n      if (w[itim]>0.0) {\n\tgotsou[0]     = TRUE;\n\tncoef[itim]   = 2;\n\tcoef[itim][0] = dx[itim];\n\tcoef[itim][1] = dy[itim];\n\tout = TRUE;\n      }\n    }\n    return out;\n  } /* end 1 source */\n\n  /* Allocate work arrays */\n  tcoef  = g_malloc(maxcoe*sizeof(ofloat));\n  gdx    = g_malloc(nsou*maxcoe*sizeof(ofloat));\n  gdy    = g_malloc(nsou*maxcoe*sizeof(ofloat));\n  sum2p1 = g_malloc(nsou*sizeof(ofloat));\n  sum2p2 = g_malloc(nsou*sizeof(ofloat));\n  sum3p1 = g_malloc(nsou*sizeof(ofloat));\n  sum3p2 = g_malloc(nsou*sizeof(ofloat));\n\n  for (is=0; is<nsou; is++) { /* loop 40 */\n    soffx[is] = 0.0;\n    soffy[is] = 0.0;\n    gotsou[is] = FALSE ;\n    fitsou[is] = FALSE ;\n    sum2p1[is] = 0.0;\n    sum2p2[is] = 1.0e-20;\n    sum3p1[is] = 0.0;\n    sum3p2[is] = 1.0e-20;\n  } /* end loop  L40:  */\n\n  /* How many coeffients can actually  be fitted? */\n  for (i=0; i<nobs; i++) { /* loop 60 */\n    it = iTime[i];\n    is = isou[i];\n    if (w[i] > 0.0) {\n      ncoef[it]++;\n      gotsou[is] = TRUE;\n    } \n  } /* end loop  L60:  */\n\n  for (itim=0; itim<nTime; itim++) { /* loop 70 */\n    ncoef[itim] = MIN (maxcoe, ncoef[itim]*2);\n    if (ncoef[itim] < 5) ncoef[itim] =  MIN (2, ncoef[itim]);\n  } /* end loop  L70:  */;\n  \n  /* Compute Zernike gradients */\n  for (i=0; i<nsou; i++) {\n    for (j=0; j<maxcoe; j++) {\n      gdx[j*nsou+i] = ObitZernikeGradX(j+2, x[i], y[i]);\n      gdy[j*nsou+i] = ObitZernikeGradY(j+2, x[i], y[i]);\n    } /* end loop over coefficients */\n  } /* end loop over sources */\n\n  rms = 0.0;\n  rmscnt = 0;\n  numobs = 0;\n  numprm = 0;\n  itlast = 0;\n  itb = 0;\n  ntgood = 0;\n  /* Loop over data fitting each time */\n  for (i=0; i<nobs; i++) { /* loop 200 */\n    it = iTime[i];\n    if ((it > 0)  &&  (ncoef[it] > 0)) {\n      is = isou[i];\n      ite = i-1;\n      /* New time? */\n      if (it != itlast) {\n\tIonFit1 (i-itb, &isou[itb], x, y, &dx[itb], &dy[itb],& w[itb], \n\t\t &ncoef[itlast], &coef[itlast][0], prtLv, err);\n\tnumprm = numprm + ncoef[itlast];\n\tif (ncoef[itlast] > 0) ntgood++;\n\t/* If fewer than 4 sources don't bother */\n\tif (nsou >= 4) {\n\t  \n\t  /* Debug Diagnostics */\n\t  if ((prtLv>=3) && (ncoef[itlast]<5)) {\n\t    Obit_log_error(err, OBIT_InfoErr, \n\t\t\t   \"%s: Bad time=%4d ncoef=%4d numobs=%5d numprm=%5d W= %10.3f %10.3f %10.3f %10.3f %10.3f \",\n\t\t\t   routine, itlast, ncoef[itlast], numobs, numprm, \n\t\t\t   w[itb], w[itb+1], w[itb+2], w[itb+3], w[itb+4]);\n\t  }\n\t  \n\t  /* Get residuals */\n\t  for (j= itb; j<=ite; j++) { /* loop 150 */\n\t    if (w[j] > 0.0) {\n\t      js = isou[j];\n\t      /* current model */\n\t      dr = 0.0;\n\t      dd = 0.0;\n\t      for (k=0; k<ncoef[itlast]; k++) { /* loop 140 */\n\t\t/* model offset */\n\t\tdr += coef[itlast][k]*gdx[k*nsou+js];\n\t\tdd += coef[itlast][k]*gdy[k*nsou+js];\n\t      } /* end loop  L140: */;\n\t      /* Calculate residuals */\n\t      rx = dx[j] - dr;\n\t      ry = dy[j] - dd;\n\t      /* Residual statistics */\n\n\t      /* Debug Diagnostics */\n\t      if (prtLv>=3) {\n\t\tObit_log_error(err, OBIT_InfoErr, \n\t\t\t       \"%s: S=%4d E= %5d resid %10.3f %10.3f ncoef=%4d\",\n\t\t\t       routine, js+1, itlast+1, rx*3600.0, ry*3600.0, ncoef[itlast]);\n\t\tif (fabs(rx)>300.0) \n\t\t  Obit_log_error(err, OBIT_InfoErr, \n\t\t\t\t \"  coef: %10.3f %10.3f %10.3f %10.3f %10.3f \",\n\t\t\t\t coef[itlast][0], coef[itlast][1], coef[itlast][2], \n\t\t\t\t coef[itlast][3], coef[itlast][4]);\n\t      }\n\t      rms += rx*rx + ry*ry;\n\t      rmscnt++;\n\t      /* Accululate sums */\n\t      sum2p1[js] += rx * w[j];\n\t      sum2p2[js] += w[j];\n\t      sum3p1[js] += ry * w[j];\n\t      sum3p2[js] += w[j];\n\t      numobs += 2;\n\t    } /* end if positive weight */ \n\t  } /* end loop  L150: */\n\t} /* end if too few source */\n\t\n\t/* For next time interval */\n\titb = i;\n\titlast = it;\n      } \n    }\n  } /* end loop  L200: */\n  \n\n  /* Last time */\n  itlast = nTime-1;\n  ite = nobs-1;\n  IonFit1 (i-itb,  &isou[itb], x, y, &dx[itb], &dy[itb], &w[itb], \n\t   &ncoef[itlast], &coef[itlast][0], prtLv, err);\n  numprm += ncoef[itlast];\n  if (ncoef[itlast] > 0) ntgood++;\n  \n  /* If fewer than 4 sources don't  bother */\n  if (nsou >= 4) {\n    /* Get residuals */\n    for (j= itb; j<=ite; j++) { /* loop 250 */\n      if (w[j] > 0.0) {\n\tjs = isou[j];\n\t/* current model */\n\tdr = 0.0;\n\tdd = 0.0;\n\tfor (k=0; k<ncoef[itlast]; k++) { /* loop 240 */\n\t  /* model offset */\n\t  dr = dr + coef[itlast][k]*gdx[k*nsou+js];\n\t  dd = dd + coef[itlast][k]*gdy[k*nsou+js];\n\t} /* end loop  L240: */;\n\t/* Calculate residuals */\n\trx = dx[j] - dr;\n\try = dy[j] - dd;\n\trms += rx*rx + ry*ry;\n\trmscnt++;\n\t/* Accululate sums */\n\tsum2p1[js] += rx * w[j];\n\tsum2p2[js] += w[j];\n\tsum3p1[js] += ry * w[j];\n\tsum3p2[js] += w[j];\n\tnumobs += 2;\n      } \n    } /* end loop  L250: */;\n  } /* end if enough data */\n  \n  /* If too few sources skip */\n  if (nsou < 4) goto cleanup;\n  /* Bail out if no data */\n  if (ntgood < 2) \n    Obit_log_error(err, OBIT_Error, \n\t\t   \"%s: Insufficient data for ionospheric model\", routine);\n  \n  /* RMS */\n  if (numobs > numprm)  rms = sqrt ((rms/rmscnt) * (numobs / (numobs - numprm)));\n  else rms = -1.0;\n \n  /* Tell about it */\n  if (prtLv>=1) {\n    Obit_log_error(err, OBIT_InfoErr, \n\t        \"%s: initial rms residual is %17.5f asec\", routine, rms*3600.0);\n  }\n\n  /* Decide which sources to fit and  initial values */\n  for (is=0; is<nsou; is++) { /* loop 300 */\n    if (gotsou[is]) {\n      rx = sum2p1[is] / sum2p2[is];\n      ry = sum3p1[is] / sum3p2[is];\n      rr = sqrt (rx*rx + ry*ry);\n\n      /* Diagnostics */\n      if (prtLv>=3) {\n\tObit_log_error(err, OBIT_InfoErr, \n\t\t       \"%s: source %4d x_off %10.4f y_off %10.4f bad %d\", \n\t\t       routine, is+1, rx*3600.0, ry*3600.0, (rr>(0.5*rms)));\n      }\n\n      /* Find qual */\n      qual = -1;\n      for (k=0; k<nobs; k++) {\n\tif (is == isou[k]) {\n\t  qual = flqual[k];\n\t  break;\n\t}\n      }\n\n      /* Fit if residual > 0.5*RMS  and quality worse than 0 */\n      if ((rr > (0.5*rms))  &&  (qual > 0)) {\n\t/*debug            IF ((RR.GT.(0.5*RMS))) THEN */\n\tsoffx[is] = rx;\n\tsoffy[is] = ry;\n\tfitsou[is] = TRUE;\n      } \n    } \n  } /* end loop  L300: */\n  out = TRUE; /* OK */\n  \n  /* Deallocate work arrays */\n cleanup:\n  if (tcoef)  g_free(tcoef);\n  if (gdx)    g_free(gdx);\n  if (gdy)    g_free(gdy);\n  if (sum2p1) g_free(sum2p1);\n  if (sum2p2) g_free(sum2p2);\n  if (sum3p1) g_free(sum3p1);\n  if (sum3p2) g_free(sum3p2);\n  return out;\n} /* end of routine initIonModel */ \n\n/**\n * Final Ionospheric model for each time, uses fitted source offsets\n * Routine translated from the AIPSish IONCAL.FOR/INCINI  \n * \\param nobs     Number of observations \n * \\param nsou     Number of sources \n * \\param nTime    Number of times   \n * \\param maxcoe   Leading dimension of COEF \n * \\param isou     Source number per obs.  (0-rel)\n * \\param iTime    Time interval number per observation.\n * \\param x        Offset in field X (RA) on unit Zernike circle /source\n * \\param y        Offset in field Y (Dec) on unit Zernike circle /source\n * \\param dx       Apparent RA position shifts on the Zernike plane (deg) /obs\n * \\param dy       Apparent dec position shifts on the Zernike plane (deg) /obs\n * \\param w        Weight of observations  /obs\n * \\param ncoef    Number of coefficents fitted per time \n * \\param fitsou   If true fit offset correction for each source \n * \\param soffx    Source offset in x=ra (deg) \n * \\param soffy    Source offset in y=dec (deg) \n * \\param coef     Initial guess for Zernike coefficients (term,time) , \n *                 updated on return\n * \\param prtLv    Print level >=1 => give fitting diagnostics\n * \\param err      Error/message stack \n * \\return TRUE if data OK, else too little data\n */\nstatic void\nfinalIonModel (olong nobs, olong nsou, olong nTime, olong maxcoe, olong* isou, \n\t       olong* iTime, ofloat*  x, ofloat* y, ofloat* dx, ofloat* dy, \n\t       ofloat* w, olong* ncoef, gboolean* fitsou, \n\t       ofloat* soffx, ofloat* soffy, ofloat** coef, \n\t       olong prtLv, ObitErr* err) \n{\n  olong   i, j, k, it, is, itim, rmscnt, numobs, numprm, itlast, itb, ite, js, ntgood;\n  ofloat rms, dr, dd, rx, ry;\n  ofloat *tcoef=NULL, *gdx=NULL, *gdy=NULL;\n  gchar *routine = \"finalIonModel\";\n\n    /* Error checks */\n  g_assert(ObitErrIsA(err));\n  if (err->error) return;  /* previous error? */\n\n  /* if only one source just use tip and tilt */\n  if (nsou==1) {\n    for (itim=0; itim<nTime; itim++) { /* loop 30 */\n      if (w[itim]>0.0) {\n\tncoef[itim]   = 2;\n\tcoef[itim][0] = dx[itim];\n\tcoef[itim][1] = dy[itim];\n      }\n    }\n  } /* end 1 source */\n\n  /* Allocate work arrays */\n  tcoef  = g_malloc(maxcoe*sizeof(ofloat));\n  gdx    = g_malloc(nsou*maxcoe*sizeof(ofloat));\n  gdy    = g_malloc(nsou*maxcoe*sizeof(ofloat));\n\n  /* Compute Zernike gradients */\n  for (i=0; i<nsou; i++) {\n    for (j=0; j<maxcoe; j++) {\n      gdx[j*nsou+i] = ObitZernikeGradX(j+2, x[i], y[i]);\n      gdy[j*nsou+i] = ObitZernikeGradY(j+2, x[i], y[i]);\n    } /* end loop over coefficients */\n  } /* end loop over sources */\n\n  rms = 0.0;\n  rmscnt = 0;\n  numobs = 0;\n  numprm = 0;\n  itlast = 0;\n  itb = 0;\n  ntgood = 0;\n  /* Loop over data fitting each time */\n  for (i=0; i<nobs; i++) { /* loop 200 */\n    it = iTime[i];\n    if ((it > 0)  &&  (ncoef[it] > 0)) {\n      is = isou[i];\n      ite = i-1;\n      /* New time? */\n      if (it != itlast) {\n\tIonFit1 (i-itb, &isou[itb], x, y, &dx[itb], &dy[itb],& w[itb], \n\t\t &ncoef[itlast], &coef[itlast][0], prtLv, err);\n\tnumprm += ncoef[itlast];\n\tif (ncoef[itlast] > 0) ntgood++;\n\t/* If fewer than 4 sources don't bother */\n\tif (nsou >= 4) {\n\t  \n\t  /* Debug Diagnostics */\n\t  if ((prtLv>=3) && (ncoef[itlast]<5)) {\n\t    Obit_log_error(err, OBIT_InfoErr, \n\t\t\t   \"%s: Bad time=%4d ncoef=%4d numobs=%5d numprm=%5d W= %10.3f %10.3f %10.3f %10.3f %10.3f \",\n\t\t\t   routine, itlast, ncoef[itlast], numobs, numprm, \n\t\t\t   w[itb], w[itb+1], w[itb+2], w[itb+3], w[itb+4]);\n\t  }\n\t  \n\t  /* Get residuals */\n\t  for (j= itb; j<=ite; j++) { /* loop 150 */\n\t    if (w[j] > 0.0) {\n\t      js = isou[j];\n\t      /* current model */\n\t      dr = 0.0;\n\t      dd = 0.0;\n\t      for (k=0; k<ncoef[itlast]; k++) { /* loop 140 */\n\t\t/* model offset */\n\t\tdr += coef[itlast][k]*gdx[k*nsou+js];\n\t\tdd += coef[itlast][k]*gdy[k*nsou+js];\n\t      } /* end loop  L140: */;\n\t      /* Calculate residuals */\n\t      rx = dx[j] - dr;\n\t      ry = dy[j] - dd;\n\t      /* Residual statistics */\n\n\t      /* Debug Diagnostics */\n\t      if (prtLv>=3) {\n\t\tObit_log_error(err, OBIT_InfoErr, \n\t\t\t       \"%s: S=%4d E= %5d resid %10.3f %10.3f ncoef=%4d\",\n\t\t\t       routine, js+1, itlast+1, rx*3600.0, ry*3600.0, ncoef[itlast]);\n\t\tif (fabs(rx)>300.0) \n\t\t  Obit_log_error(err, OBIT_InfoErr, \n\t\t\t\t \"  coef: %10.3f %10.3f %10.3f %10.3f %10.3f \",\n\t\t\t\t coef[itlast][0], coef[itlast][1], coef[itlast][2], \n\t\t\t\t coef[itlast][3], coef[itlast][4]);\n\t      }\n\t      rms += rx*rx + ry*ry;\n\t      rmscnt++;\n\t      numobs += 2;\n\t    } /* end if positive weight */ \n\t  } /* end loop  L150: */\n\t} /* end if too few source */\n\t\n\t/* For next time interval */\n\titb = i;\n\titlast = it;\n      } \n    }\n  } /* end loop  L200: */\n  \n\n  /* Last time */\n  itlast = nTime-1;\n  ite = nobs-1;\n  IonFit1 (i-itb,  &isou[itb], x, y, &dx[itb], &dy[itb], &w[itb], \n\t   &ncoef[itlast], &coef[itlast][0], prtLv, err);\n  numprm += ncoef[itlast];\n  if (ncoef[itlast] > 0) ntgood++;\n  \n  /* If fewer than 4 sources don't  bother */\n  if (nsou >= 4) {\n    /* Get residuals */\n    for (j= itb; j<=ite; j++) { /* loop 250 */\n      if (w[j] > 0.0) {\n\tjs = isou[j];\n\t/* current model */\n\tdr = 0.0;\n\tdd = 0.0;\n\tfor (k=0; k<ncoef[itlast]; k++) { /* loop 240 */\n\t  /* model offset */\n\t  dr = dr + coef[itlast][k]*gdx[k*nsou+js];\n\t  dd = dd + coef[itlast][k]*gdy[k*nsou+js];\n\t} /* end loop  L240: */;\n\t/* Calculate residuals */\n\trx = dx[j] - dr;\n\try = dy[j] - dd;\n\trms += rx*rx + ry*ry;\n\trmscnt++;\n\tnumobs += 2;\n      } \n    } /* end loop  L250: */;\n  } /* end if enough data */\n  \n  /* If too few sources skip */\n  if (nsou < 4) goto cleanup;\n  /* Bail out if no data */\n  if (ntgood < 2) \n    Obit_log_error(err, OBIT_Error, \n\t\t   \"%s: Insufficient data for ionospheric model\", routine);\n  \n  /* RMS */\n  if (numobs > numprm)  rms = sqrt ((rms/rmscnt) * (numobs / (numobs - numprm)));\n  else rms = -1.0;\n \n  /* Tell about it */\n  if (prtLv>=1) {\n    Obit_log_error(err, OBIT_InfoErr, \n\t        \"%s: initial rms residual is %17.5f asec\", routine, rms*3600.0);\n  }\n\n  /* Deallocate work arrays */\n cleanup:\n  if (tcoef)  g_free(tcoef);\n  if (gdx)    g_free(gdx);\n  if (gdy)    g_free(gdy);\n  return;\n} /* end of routine finalIonModel */ \n\n\n\n/**\n * Fit Zernike model to apparent position offsets for a time series  \n * allowing for a systematic offset on the apparent source positions.  \n * Solution uses a relaxation method from Fred Schwab:  \n * Pn+1 = Pn + atan2 (dChi2/dP), (d2Chi2/dP2))  \n * for each parameter P where n or n+1 indicates a given iteration,   \n * dChi2/dP is the first partial derivative of Chi squared wrt P,  \n * d2Chi2/d2P is the second partial derivative of Chi squared wrt P,  \n * Chi2 = Sum (w Abs(dxj - oxk - Sum (Pi Gxik))**2) +   \n * Sum (w Abs(dyj - oyk - Sum (Pi Gyik))**2)  \n * Must be initialized by a call to initIonModel.\n * Routine translated from the AIPSish IONCAL.FOR/IOALFT  \n *  \n * dxj = apparent offset in x of obs j  \n * dyj = apparent offset in y of obs j  \n * oxk = correction to source k offset in x, k = f(j)  \n * oyk = correction to source k offset in y, k = f(j)  \n * Pi  = Zernike coefficient i [COEF(I) below],  \n * Gxik = Zernike x gradient term i for source k        \n * Gyik = Zernike y gradient term i for source k     \n * \\param nobs      Number of observations \n * \\param nsou      Number of sources  \n * \\param nTime     Number of times    \n * \\param maxcoe    Max. number of coefficients\n * \\param isou      Source number per obs.  (0-rel)\n * \\param iTime     Time interval number per observation\n * \\param x         Offset in field X (RA) on unit Zernike circle /source\n * \\param y         Offset in field Y (Dec) on unit Zernike circle /source\n * \\param dx        Apparent RA position shifts on the Zernike plane (deg) \n * \\param dy        Apparent dec position shifts on the Zernike plane \n * \\param w         Weights of observations \n * \\param ncoef     Number of coefficents fitted per time \n * \\param gotsou    If true, there is data for this souce \n * \\param fitsou    If true fit offset correctsion for each source \n * \\param soffx     Correction to source offset in x=ra (deg) \n *                  input: initial guess, output: fitted values \n * \\param soffy     Correction to source offset in y=dec (deg) \n *                  input: initial guess, output: fitted values \n * \\param coef      Zernike coefficients fitted (term,time) \n *                  input: initial guess, output: fitted values \n * \\param trms      RMS residual for each time interval (deg) \n *                  value [nTime+] is the total corrected RMS \n *                  Values corrected for the number of parameters.\n *                  -1 => not determined. \n * \\param prtLv     Print level >=1 => give fitting diagnostics\n * \\param err       Error stack\n */\nstatic void \nFitIonSeries (olong nobs, olong nsou, olong nTime, olong maxcoe, olong* isou, olong* iTime, \n\t      ofloat*  x, ofloat* y, ofloat* dx, ofloat* dy, ofloat* w, olong*  ncoef, \n\t      gboolean* gotsou, gboolean* fitsou, ofloat* soffx, ofloat* soffy, \n\t      ofloat** coef, ofloat* trms, olong prtLv, ObitErr* err) \n{\n  olong   i, j, it, is, itim, rmscnt, numobs, numprm, iter;\n  gboolean   convgd, OK;\n  ofloat      rms=0.0, dr, dd, delta, tol, norm=0.0, test, rx, ry, pd1, pd2, wx, rmslst ;\n  ofloat **sum1p1=NULL, **sum1p2=NULL, *sum2p1=NULL, *sum2p2=NULL, *sum3p1=NULL, *sum3p2=NULL;\n  ofloat **tcoef=NULL, *tsoffx=NULL, *tsoffy=NULL, *gdx=NULL, *gdy=NULL, *sum1=NULL, *sum2=NULL;\n  /* Penalty terms by order of Zernike 1-4 */\n  ofloat pen[]={0.001, 0.001,\n\t\t0.01, 0.01, 0.01,\n\t\t0.03, 0.03, 0.03, 0.03, 0.03, \n\t\t0.05, 0.05, 0.05,0.05,  0.05, 0.05, 0.05, \n\t\t0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08};\n  ofloat *sumWt=NULL;\n  gchar *routine = \"FitIonSeries\";\n\n  /* Error checks */\n  g_assert(ObitErrIsA(err));\n  if (err->error) return ;  /* previous error? */\n\n  /* Allocate work arrays */\n  tsoffx = g_malloc(nsou*sizeof(ofloat));\n  tsoffy = g_malloc(nsou*sizeof(ofloat));\n  gdx    = g_malloc(nsou*maxcoe*sizeof(ofloat));\n  gdy    = g_malloc(nsou*maxcoe*sizeof(ofloat));\n  sum2p1 = g_malloc(nsou*sizeof(ofloat));\n  sum2p2 = g_malloc(nsou*sizeof(ofloat));\n  sum3p1 = g_malloc(nsou*sizeof(ofloat));\n  sum3p2 = g_malloc(nsou*sizeof(ofloat));\n  sum1   = g_malloc(nTime*sizeof(ofloat));\n  sum2   = g_malloc(nTime*sizeof(ofloat));\n  sum1p1 = g_malloc(nTime*sizeof(ofloat*));\n  sum1p2 = g_malloc(nTime*sizeof(ofloat*));\n  tcoef  = g_malloc(nTime*sizeof(ofloat*));\n  sumWt  = g_malloc(nTime*sizeof(ofloat));\n  for (i=0; i<nTime; i++) {\n    sum1p1[i] = g_malloc(maxcoe*sizeof(ofloat));\n    sum1p2[i] = g_malloc(maxcoe*sizeof(ofloat));\n    tcoef[i]  = g_malloc(maxcoe*sizeof(ofloat));\n  }\n\n  /* Compute Zernike gradients */\n  for (i=0; i<nsou; i++) {\n    for (j=0; j<maxcoe; j++) {\n      gdx[j*nsou+i] = ObitZernikeGradX(j+2, x[i], y[i]);\n      gdy[j*nsou+i] = ObitZernikeGradY(j+2, x[i], y[i]);\n    } /* end loop over coefficients */\n  } /* end loop over sources */\n\n  rmslst = 1.0e20;\n  for (i=0; i<nTime; i++) trms[i] = 1.0;\n\n  /* Loop over iterations */\n  for (iter=1; iter<=200; iter++) { /* loop 600 */\n\n    convgd = TRUE;  /* Can decide otherwise: */\n\n    /* Zero sums */\n    for (j=0; j<maxcoe; j++) { /* loop 130 */\n      for (itim=0; itim<nTime; itim++) { /* loop 120 */\n\tsum1p1[itim][j] = 0.0;\n\tsum1p2[itim][j] = 1.0e-20;\n      } /* end loop  L120: */;\n    } /* end loop  L130: */\n    for (j=0; j<nsou; j++) {\n      sum2p1[j] = 0.0;\n      sum2p2[j] = 1.0e-20;\n      sum3p1[j] = 0.0;\n      sum3p2[j] = 1.0e-20;\n    } \n    \n    /* Loop over data doing sums */\n    for (it=0; it<nTime; it++) sumWt[it] = 0.0;\n    for (i=0; i<nobs; i++) { /* loop 200 */\n      if (w[i] > 0.0) {\n\tit = iTime[i];\n\tis = isou[i];\n\tsumWt[it] += w[i];  /* Sum weights per time*/\n\t/* current model */\n\tdr = 0.0;\n\tdd = 0.0;\n\tfor (j=0; j<ncoef[it]; j++) { /* loop 140 */\n\t  /* model offset */\n\t  dr += coef[it][j]*gdx[j*nsou+is];\n\t  dd += coef[it][j]*gdy[j*nsou+is];\n\t} /* end loop  L140: */;\n\t\n\t/* Calculate residuals */\n\tif (fitsou[is]) {\n\t  rx = dx[i] - soffx[is] - dr;\n\t  ry = dy[i] - soffy[is] - dd;\n\t} else {\n\t  rx = dx[i] - dr;\n\t  ry = dy[i] - dd;\n\t}\n\n\t/* Partial derivatives for coef */\n\tfor (j=0; j<ncoef[it]; j++) { /* loop 150 */\n\t  pd1 = -rx * gdx[j*nsou+is] - ry * gdy[j*nsou+is];\n\t  pd2 = gdx[j*nsou+is]*gdx[j*nsou+is] + gdy[j*nsou+is]*gdy[j*nsou+is];\n\n\t  /* Sum */\n\t  sum1p1[it][j] += w[i] * pd1;\n\t  sum1p2[it][j] += w[i] * pd2;\n\t} /* end loop  L150: */;\n\t\n\t/* Fitting this source? */\n\tif (fitsou[is]) {\n\t  /* Partial derivatives for soffx */\n\t  pd1 = -rx;\n\t  pd2 = 1.0;\n\t  /* Sum */\n\t  sum2p1[is] += w[i] * pd1;\n\t  sum2p2[is] += w[i] * pd2;\n\t  /* Partial derivatives for soffy */\n\t  pd1 = -ry;\n\t  pd2 = 1.0;\n\t  /* Sum */\n\t  sum3p1[is] += w[i] * pd1;\n\t  sum3p2[is] += w[i] * pd2;\n\t} \n      } \n    } /* end loop  L200: */\n    \n    /* Penalty functions for non zero higher order Zernike coefs */\n    for (it=0; it<nTime; it++) { /* loop 230 */\n      for (j=0; j<ncoef[it]; j++) { \n\tsum1p1[it][j] += coef[it][j] * sumWt[it]*pen[j];\n\tsum1p2[it][j] += sumWt[it]*pen[j];\n      }\n    }\n\n    /* Update solutions */\n    wx = 1.6;\n    OK = FALSE;\n    while (!OK) {\n      wx = wx * 0.5;\n      /* don't loop forever */\n      if (wx < 1.0e-10) goto converged;\n\n      /* Convergence criterion - lower the bar  */\n      tol = 5.0e-6 + iter * 1.0e-5;\n      norm = 0.0;\n      numobs = 0;\n      numprm = 0;\n\n      /* Coefficients */\n      for (itim=0; itim<nTime; itim++) { /* loop 230 */\n\tif (sumWt[itim] > 0.0) {\n\t  for (j=0; j<ncoef[itim]; j++) { /* loop 220 */\n\t    numprm++;\n\t    delta = atan2 (sum1p1[itim][j], sum1p2[itim][j]);\n\t    test = tol;\n\t    tcoef[itim][j] = coef[itim][j] - wx * delta;\n\n\t    /* DEBUG\n\t       if (fabs(tcoef[itim][j])>1.0) {\n\t       fprintf (stdout, \"Lookout time %d parm %d coef %f part %f %f\\n\",\n\t       itim, j,tcoef[itim][j], sum1p1[itim][j], sum1p2[itim][j]);\n\t       }  End DEBUG */\n\n\t    /* Convergence test */\n\t    convgd = convgd && (fabs(delta) <= test);\n\t    norm += delta*delta;\n\t  } /* end loop  L220: */;\n\t} /* end valid data for interval */\n\telse {  /* don't change coefs */\n\t  for (j=0; j<ncoef[itim]; j++) tcoef[itim][j] = coef[itim][j];\n\t}\n      } /* end loop  L230: */;\n\n      /* Position offsets */\n      for (is=0; is<nsou; is++) { /* loop 250 */\n\tif (gotsou[is]  &&  fitsou[is]) {\n\n\t  /* X offset */\n\t  delta = atan2 (sum2p1[is], sum2p2[is]);\n\t  test = tol ;\n\t  tsoffx[is] = soffx[is] - wx * delta;\n\n\t  /* Convergence test */\n\t  convgd = convgd && (fabs(delta) <= test);\n\t  norm +=delta*delta;\n\n\t  /* Y offset */\n\t  delta = atan2 (sum3p1[is], sum3p2[is]);\n\t  test = tol ;\n\t  tsoffy[is] = soffy[is] - wx * delta;\n\n\t  /* Convergence test */\n\t  convgd = convgd  &&  (fabs(delta) <= test);\n\t  numprm += 2;\n\t  norm += delta*delta;\n\n\t  /* Debug Diagnostics */\n\t  if (prtLv>=4) {\n\t    Obit_log_error(err, OBIT_InfoErr, \n\t\t\t   \"%s: iter %d source %4d off_x=%8.2f off_y=%8.2f delta_y=%8.2f\",\n\t\t\t   routine, iter+1, is+1, soffx[is]*3600.0, soffy[is]*3600.0, delta*3600.0);\n\t  }\n\t  \n\t} else {\n\t  tsoffy[is] = 0.0;\n\t  tsoffx[is] = 0.0;\n\t} \n      } /* end loop  L250: */\n\n      /* Determine RMS */\n      rms    = 0.0;\n      rmscnt = 0;\n\n      /* Time RMS sums */\n      for (j=0; j<nTime; j++) { /* loop 310 */\n\tsum1[j] = 0.0;\n\tsum2[j] = 1.0e-20;\n      } /* end loop  L310: */;\n\n      for (i=0; i<nobs; i++) { /* loop 340 */\n\tif (w[i] > 0.0) {\n\t  it = iTime[i];\n\t  is = isou[i];\n\t  numobs += 2;\n\t  /* current model */\n\t  dr = 0.0;\n\t  dd = 0.0;\n\t  for (j=0; j<ncoef[it]; j++) { /* loop 330 */\n\t    /* model offset */\n\t    dr += tcoef[it][j]*gdx[j*nsou+is];\n\t    dd += tcoef[it][j]*gdy[j*nsou+is];\n\t  } /* end loop  L330: */;\n\n\t  /* Calculate residuals */\n\t  if (fitsou[is]) {\n\t    rx = dx[i] - tsoffx[is] - dr;\n\t    ry = dy[i] - tsoffy[is] - dd;\n\t  } else {\n\t    rx = dx[i] - dr;\n\t    ry = dy[i] - dd;\n\t  }\n\n\t  /* Residual statistics */\n\t  rms += rx*rx + ry*ry;       /* Total */\n\t  rmscnt++;\n\t  sum1[it] += rx*rx + ry*ry;  /* Per time */\n\t  sum2[it] += 1.0;         /* NOTE: this was wrong in AIPS */\n\t  /* DEBUG\n\t  if (it==4)\n\t    fprintf (stdout,\"Src %5d residX %10.5f residY %10.5f model %10.5f%10.5f \\n\",\n\t\t     is+1, rx*3600.0, ry*3600.0, dr*3600.0, dd*3600.0); */\n\t} \n      } /* end loop  L340: */\n\n      /* Force residuals to decrease */\n      if (numobs > numprm) rms = sqrt ((rms/rmscnt) * (numobs / (numobs - numprm)));\n      else rms = -1.0;\n      OK =  (rms <= rmslst);\n      rmslst = rms;\n    } /* end of loop seeking improvement of fit */\n\n    /* Save values */\n    trms[nTime] = rms;  /* total RMS */\n\n    for (j=0; j<nTime; j++) { /* loop 360 */\n      /* Any data and enought deg. of freedom to fit? */\n      if ((sumWt[j]>0.0) && ((2.0*sum2[j]) > (ncoef[j]+1))) {\n\ttrms[j] = sqrt ((sum1[j] / sum2[j]) * \n\t\t\t(2.0*sum2[j] / (2.0*sum2[j] - ncoef[j]))) ;\n\t  /* DEBUG \n\t  if (j==4)\n\t    fprintf (stdout, \"RMS %10.5f\\n\",trms[j]*3600.0);*/\n      } else {\n\ttrms[j] = -1.0;\n      }\n\n      /* DEBUG\n\t if ((fabs(tcoef[j][0])>1.0) || (fabs(tcoef[j][1])>1.0)) {\n\t fprintf (stdout, \"Bother iter %d time %d coef %f %f\\n\",\n\t it, j+1, tcoef[j][0], tcoef[j][1]);\n\t }  End DEBUG */\n      \n      for (i=0; i<ncoef[j]; i++) { /* loop 350 */\n\tcoef[j][i] = tcoef[j][i];\n      } /* end loop  L350: */;\n    } /* end loop  L360: */;\n    \n    for (i=0; i<nsou; i++) { /* loop 370 */\n      soffx[i] = tsoffx[i];\n      soffy[i] = tsoffy[i];\n    } /* end loop  L370: */;\n\n    /* Debug Diagnostics */\n    if ((prtLv>=3) && (iter<=2)) {\n      /*j = nTime-1;\n\tObit_log_error(err, OBIT_InfoErr, \n\t\"iter %4d coef %10.5f %10.5f %10.5f %10.5f %10.5f \",\n\titer, 3600.0*coef[j][0], 3600.0*coef[j][1], 3600.0*coef[j][2], \n\t3600.0*coef[j][3], 3600.0*coef[j][4]);*/\n      Obit_log_error(err, OBIT_InfoErr, \n\t\t     \"iter %4d rms=%10.5f norm=%12.5g\", iter, rms*3600.0, norm);\n    }\n   \n    /* Converged? */\n    if (convgd) break;\n  } /* end loop iteration L600: */;\n\n    /* Converged */\n  converged:\n\n  /* Tell about it */\n  if (prtLv>=2) {\n    Obit_log_error(err, OBIT_InfoErr, \n\t\t   \"%s: No. iteration %5d RMS resid=%17.5f norm=%12.5g\", \n\t\t   routine, iter+1, rms*3600.0, norm);\n  }\n\n  /* Deallocate work arrays */\n  if (tsoffx) g_free(tsoffx);\n  if (tsoffy) g_free(tsoffy);\n  if (sumWt)  g_free(sumWt);\n  if (gdx)    g_free(gdx);\n  if (gdy)    g_free(gdy);\n  if (sum2p1) g_free(sum2p1);\n  if (sum2p2) g_free(sum2p2);\n  if (sum3p1) g_free(sum3p1);\n  if (sum3p2) g_free(sum3p2);\n  if (sum1)   g_free(sum1);\n  if (sum2)   g_free(sum2);\n  if (tcoef) {\n    for (i=0; i<nTime; i++) {\n      if (tcoef[i]) g_free(tcoef[i]);\n    } \n    g_free(tcoef);\n  }\n  if (sum1p1){\n    for (i=0; i<nTime; i++) {\n      if (sum1p1[i]) g_free(sum1p1[i]);\n    } \n    g_free(sum1p1);\n  }\n  if (sum1p2){\n    for (i=0; i<nTime; i++) {\n      if (sum1p2[i]) g_free(sum1p2[i]);\n    } \n    g_free(sum1p2);\n  }\n} /* end of routine FitIonSeries */ \n\n/**\n * Edit ionospheric data based on model fit.  \n * Times with either insufficient data to determine a decent solution  \n * (4 sources) or excessive RMS residuals will be flagged by setting  \n * the corresponding ncoef to zero.  \n * Ant intervals with fewer coefficients in the model than the maximum\n * will be flagged.\n * Routine translated from the AIPSish IONCAL.FOR/IONEDT  \n * \\param nobs      Number of observations \n * \\param nsou      Number of sources  \n * \\param nTime     Number of times  \n * \\param maxcoe    Maximum number of coefficients\n * \\param isou      Source number per obs.  (0-rel)\n * \\param iTime     Time interval number per observation.\n * \\param x         Offset in field X (RA) on unit Zernike circle /source\n * \\param y         Offset in field Y (Dec) on unit Zernike circle  /source\n * \\param dx        Apparent RA position shifts on the Zernike plane (deg)\n * \\param dy        Apparent dec position shifts on the Zernike plane  (deg)\n * \\param w         Weight of observations \n *                  On output, set to zero to remove datum \n * \\param MaxRMS    Maximum acceptable RMS residual (deg) \n * \\param ncoef     Number of coefficents fitted per time \n *                  On output, set to -1 to remove time. \n * \\param soffx     Source offset in x=ra (deg) \n * \\param soffy     Source offset in y=dec (deg) \n * \\param coef     Zernike coefficients (term,time) \n * \\param prtLv    Print level >=1 => give fitting diagnostics\n * \\param err      Error/message stack \n * \\return TRUE if data edited.\n */\nstatic gboolean \nIonEditSeries (olong nobs, olong nsou, olong nTime, \n\tolong maxcoe, olong* isou, olong* iTime, ofloat*  x, ofloat* y, \n\tofloat* dx, ofloat* dy, ofloat* w, ofloat MaxRMS, olong* ncoef, \n\tofloat* soffx, ofloat* soffy, ofloat** coef, olong prtLv, ObitErr* err) \n{\n  gboolean out=FALSE;\n  olong   i, j, it, itlast, itb, ite, count, ntoss, stoss, numt;\n  gboolean  doMore;\n  ofloat    rms;\n  ofloat *lx=NULL, *ly=NULL, *gdx=NULL, *gdy=NULL;\n  gchar *routine = \"IonEditSeries\";\n\n  /* Error checks */\n  if (err->error) return out;  /* previous error? */\n\n  /* Allocate work arrays */\n  gdx    = g_malloc(nsou*maxcoe*sizeof(ofloat));\n  gdy    = g_malloc(nsou*maxcoe*sizeof(ofloat));\n  lx     = g_malloc(nsou*sizeof(ofloat));\n  ly     = g_malloc(nsou*sizeof(ofloat));\n\n  /* Compute Zernike gradients */\n  for (i=0; i<nsou; i++) {\n    for (j=0; j<maxcoe; j++) {\n      gdx[j*nsou+i] = ObitZernikeGradX(j+2, x[i], y[i]);\n      gdy[j*nsou+i] = ObitZernikeGradY(j+2, x[i], y[i]);\n    } /* end loop over coefficients */\n  } /* end loop over sources */\n\n  numt  = 0;\n  ntoss = 0;\n  stoss = 0;\n  itlast = iTime[0];\n  itb = 0;\n  /* Loop over data examining each time */\n  for (i=0; i<nobs; i++) { /* loop 200 */\n    it = iTime[i];\n    ite = i-1;\n    \n    /* New time? Last? */\n    if ((it != itlast)  ||  (i == (nobs-1))) {\n      if (i == (nobs-1)) ite = i;  /* Last? */\n      /* Debug Diagnostics */\n      if (prtLv>=3) {\n\tObit_log_error(err, OBIT_InfoErr, \n\t\t       \"%s: time %4d coef %10.5f %10.5f %10.5f %10.5f %10.5f \",\n\t\t       routine,itlast+1, 3600.0*coef[itlast][0], 3600.0*coef[itlast][1], \n\t\t       3600.0*coef[itlast][2], 3600.0*coef[itlast][3], \n\t\t       3600.0*coef[itlast][4]);\n      }\n      \n      /* Begin editing loop */\n      /* Copy actual source Zernike offsets to lx, ly */\n      count = 0;\n      for (i=itb; i<=ite; i++) {\n\tlx[count] = x[isou[i]];\n\tly[count] = y[isou[i]];\n\tcount++;\n      }\n      \n      /* Fit model/edit loop */\n      doMore = TRUE;\n      while (doMore) {\n\trms = IonFit1 (count, &isou[itb], x, y, &dx[itb], &dy[itb], &w[itb], \n\t\t       &ncoef[itlast], &coef[itlast][0], prtLv, err);\n\tif (rms<MaxRMS) break;  /* Reached goal? */\n\tdoMore = IonEdit1 (count, &isou[itb], x, y, &dx[itb], &dy[itb], &w[itb],  \n\t\t\t   MaxRMS, ncoef[itlast], &coef[itlast][0], prtLv, err);\n\tif (doMore) stoss++;\n      }\n\n      \n      /* If RMS still excessive toss  interval */\n      if (rms > MaxRMS) {\n\tif (prtLv>=2) {\n\tObit_log_error(err, OBIT_InfoErr, \n\t\t       \"%s: Flagged time %d, excessive rms %f > %f\",\n\t\t       routine, itlast+1, rms*3600.0, MaxRMS*3600.0);\n\t}\n\tncoef[itlast] = -1;\n\tntoss++;\n\t/* Reject data */\n\tfor (j= itb; j<=ite; j++) { /* loop 180 */\n\t  w[j] = 0.0;\n\t} /* end loop  L180: */\n      } \n      \n      /* For next time interval */\n      itb = i;\n      itlast = it;\n      numt = MAX (numt, itlast);\n    } /* end if new time */ \n  } /* end loop  L200: */\n\n  /* Filter each source */\n  for (i=0; i<nsou; i++) { /* loop 10 */\n    /* Have adjusted the positions with no source offsets */\n    soffx[i] = 0.0;\n    soffy[i] = 0.0;\n    IonEditSource (i, nobs, nTime, maxcoe, nsou, isou, iTime,  x, y, dx, dy, w, \n\t\t   MaxRMS, ncoef, soffx, soffy, coef, gdx, gdy, &stoss, \n\t\t   prtLv, err);\n  } /* end loop  L10:  */\n\n  /* Tell about it */\n  if (prtLv>=1) {\n    Obit_log_error(err, OBIT_InfoErr, \n\t\t   \"%s: rejected %5d of %5d intervals, %6d single obs.\", \n\t\t   routine, ntoss, numt+1, stoss);\n  }\n  \n  /* Do anything? */\n  out = ((ntoss > 0)  ||  (stoss > 0));\n\n  /* Deallocate work arrays */\n  if (lx)    g_free(lx);\n  if (ly)    g_free(ly);\n  if (gdx)   g_free(gdx);\n  if (gdy)   g_free(gdy);\n  return out;\n} /* end of routine IonEditSeries */ \n\n\n/**\n * Edit times if average measured flux is less that MinRat wrt average \n * Sources brighter than FCStrong are required in all solutions  at al least \n * MinRat of their average.\n * Times will be flagged by setting the corresponding ncoef to zero.  \n * Routine translated from the AIPSish IONCAL.FOR/IONAED  \n * \\param nobs      Number of observations \n * \\param nsou      Number of sources  \n * \\param nTime     Number of times  \n * \\param isou      Source number per obs.  (0-rel)\n * \\param iTime     Time number per obs. \n * \\param MinRat    Minimum acceptable ratio to average flux \n * \\param FCStrong  Min. Flux for strong (required) cal \n * \\param flux      Peak flux density of observations \n * \\param ncoef     Number of coefficents fitted per time \n *                  On output, set to -1 to remove time. \n * \\param wt        Weights of observations, set to 0 if flagged \n * \\param prtLv     Print level >=1 => give fitting diagnostics\n * \\param err       Error/message stack \n * \\return TRUE if data edited.\n */\nstatic gboolean \nIonEditAmp (olong nobs, olong nsou, olong nTime, olong* isou, olong* iTime, \n\t    ofloat MinRat, ofloat FCStrong, ofloat*  flux, olong* ncoef, ofloat* wt, \n\t    olong prtLv, ObitErr* err) \n{\n  gboolean out = FALSE;\n  olong   *cntflx=NULL, i, j, isss, ittt, ilast, drop=0, total, ib, ie;\n  gboolean bad, allStrong;\n  ofloat   *sumflx=NULL, *strong=NULL, sumt1, sumt2;\n  gchar flg[11];\n  gchar *routine = \"IonEditAmp\";\n\n  /* Error checks */\n  g_assert(ObitErrIsA(err));\n  if (err->error) return out;  /* previous error? */\n\n  /* allocate arrays */\n  cntflx  = g_malloc0(nsou*sizeof(olong));\n  sumflx  = g_malloc0(nsou*sizeof(ofloat));\n\n  /* get strong required flux densities */\n  strong = getStrong (nobs, nsou, nTime, isou, iTime, MinRat,  FCStrong, flux, prtLv, err);\n  if (err->error) goto cleanup;\n\n  if (prtLv>=1) {\n    Obit_log_error(err, OBIT_InfoErr, \n\t\t   \"Filtering solutions with min. flux ratio %10.5f\", \n\t\t   MinRat );\n    Obit_log_error(err, OBIT_InfoErr, \n\t\t   \"Strong (required) cal level %10.5f Jy\", \n\t\t   FCStrong);\n  }\n\n  drop = 0;\n  total = 0;\n  /* Average source flux densities */\n  for (i=0; i<nsou; i++) cntflx[i] = 0;\n  for (i=0; i<nsou; i++) sumflx[i] = 0.0;\n  for (i=0; i<nobs; i++) { /* loop 20 */\n    if (flux[i] > 0) {\n      isss = isou[i];\n      cntflx[isss]++;\n      sumflx[isss] += flux[i];\n    } \n  } /* end loop  L20:  */\n\n  /* Normalize */\n  for (i=0; i<nsou; i++) { /* loop 40 */\n    if (cntflx[i] > 0) sumflx[i] /= cntflx[i];\n  } /* end loop  L40:  */;\n\n  /* Loop over times summing measured and averaged fluxes */\n  ilast = 0;\n  ib = 0;\n  ie = 0;\n  sumt1 = 0.0;\n  sumt2 = 0.0;\n  allStrong = TRUE;\n  for (i=0; i<nobs; i++) { /* loop 100 */\n    if (iTime[i] > ilast) {\n      total++;\n      /* New time - check results */\n      if (sumt2 > 0.0) sumt1 /= sumt2;\n      bad = (sumt1  <  MinRat) || (!allStrong);\n      ittt = iTime[i];\n      if (bad) {\n\t/* Flag time/data */\n\tncoef[ittt] = -1;\n\tfor (j= ib; j<= ie; j++) { /* loop 80 */\n\t  flux[j] = 0.0;\n\t  wt[j]   = 0.0;\n\t} /* end loop  L80:  */;\n\tdrop++;\n      } \n      /*   Debug  Diagnostics*/\n      strcpy (flg, \" \");\n      if (bad) strcpy (flg, \"flagged\");\n      if (prtLv>=3) {\n\tObit_log_error(err, OBIT_InfoErr, \n\t\t       \"%s: Time %4d average flux= %10.2f %s\", \n\t\t       routine,ilast, sumt1, flg);\n      }\n      sumt1 = 0.0;\n      sumt2 = 0.0;\n      allStrong = TRUE;\n      ilast = ittt;\n      ib = i;\n    } \n    ie = i;\n\n    /* Check for required calibrators */\n    isss = isou[i];\n    allStrong = allStrong && (flux[i] >= strong[isss]);\n    /* Diagnostics */\n    if ((prtLv>=3) && (flux[i]< strong[isss])) {\n      Obit_log_error(err, OBIT_InfoErr, \n\t\t     \"%s: Flag time %4.4d for source %4.4d since %f < %f\",\n\t\t     routine,iTime[i],isss+1,flux[i],strong[isss]);\n    }\n\n    /* Sum Fluxes and average values for  source.  */\n    if (flux[i] > 0.0) {\n      isss = isou[i];\n      sumt1 += flux[i];\n      sumt2 += sumflx[isss];\n    } \n  } /* end loop  L100: */\n\n  /* Deal with last average */\n  if (sumt2 > 0.0) sumt1 /= sumt2;\n  bad = (sumt1  <  MinRat) || (!allStrong);\n  if (bad) {\n    /* Flag time/data */\n    ncoef[ilast] = -1;\n    for (j= ib; j<= ie; j++) { /* loop 120 */\n      wt[j] = 0.0;\n      flux[j] = 0.0;\n    } /* end loop  L120: */;\n    drop++;\n  }\n\n  /*   Debug Diagnostics */\n  strcpy (flg, \" \");\n  if (bad) strcpy (flg, \"flagged\");\n  if (prtLv>=3) {\n    Obit_log_error(err, OBIT_InfoErr, \n\t\t   \"%s: Time %4d average flux= %10.2f %s\", \n\t\t   routine, ilast, sumt1, flg);\n  }\n\n  /* Tell results */\n  if (prtLv>=1) {\n    Obit_log_error(err, OBIT_InfoErr, \n\t\t   \"%s: reject %4d of %4d times due to low peak\", \n\t\t   routine, drop, total);\n  }\n\n  /* cleanup - deallocate arrays */\n cleanup:\n    if (cntflx) g_free(cntflx);\n    if (sumflx) g_free(sumflx);\n    if (strong) g_free(strong);\n    out = (drop >0);  /* Do anything? */\n    if (err->error) Obit_traceback_val (err, routine, \"editing amp data\", out);\n    return out;\n} /* end of routine IonEditAmp */ \n\n/**\n * Edit ionospheric data based on model fit for a given source.  \n * Routine translated from the AIPSish IONCAL.FOR/INESOU  \n * \\param source    Source number to edit \n * \\param nobs      Number of observations \n * \\param nTime     Number of times \n * \\param maxcoe    Maximum number of coefficients\n * \\param nsou      Number of sources\n * \\param isou      Source number per obs.  (0-rel)\n * \\param iTime     Time interval number per observation.\n * \\param x         Offset in field X (RA) on unit Zernike circle /source\n * \\param y         Offset in field Y (Dec) on unit Zernike circle  /source\n * \\param dx        Apparent RA position shifts on the Zernike plane (deg) \n * \\param dy        Apparent dec position shifts on the Zernike plane (deg) \n * \\param w         Weight of observations \n *                  On output, set to zero to remove datum \n * \\param MaxRMS    Maximum acceptable RMS residual \n * \\param ncoef     Number of coefficents fitted per time \n *                  On output, set to -1 to remove time. \n * \\param soffx     source offset in x=ra (deg) \n * \\param soffy     source offset in y=dec (deg) \n * \\param coef      Zernike coefficients (term,time) \n * \\param gdx       Zernike gradients in X per source, coef\n * \\param gdy       Zernike gradients in Y per source, coef\n * \\param stoss     [in/out] Number of observations rejected \n * \\param prtLv     Print level >=1 => give fitting diagnostics\n * \\param err       Error stack\n */\nstatic void IonEditSource (olong source, olong nobs, olong nTime, olong maxcoe, olong nsou, \n\t\t\t   olong* isou, olong* iTime, ofloat*  x, ofloat* y, \n\t\t\t   ofloat* dx, ofloat* dy, ofloat* w, ofloat MaxRMS, olong* ncoef, \n\t\t\t   ofloat* soffx, ofloat* soffy, ofloat** coef, \n\t\t\t   ofloat *gdx, ofloat *gdy, olong* stoss, olong prtLv, ObitErr* err) \n{\n  olong   i, j, k, it, rmscnt, js, numt, *ktime, count, i1, i2, wid, idt, nt, *iobs;\n  ofloat  rms, dr, dd, sum;\n  ofloat  *resid, rx, ry, test, rmst;\n  gchar *routine = \"IonEditSource\";  \n\n  /* allocate arrays */\n  resid  = g_malloc0(nTime*sizeof(ofloat));\n  ktime  = g_malloc0(nTime*sizeof(olong));\n  iobs   = g_malloc0(nTime*sizeof(olong));\n\n  numt   = 0;\n  rms    = 0.0;\n  rmscnt = 0;\n  /* Loop over data examining each time */\n  for (i=0; i<nobs; i++) { /* loop 200 */\n    if ((isou[i] == source)  &&  (w[i] > 0.0)) {\n      it = iTime[i];\n      ktime[numt] = iTime[i];\n      iobs[numt]  = i;\n      js          = isou[i];\n      /* current model */\n      dr = 0.0;\n      dd = 0.0;\n      for (k=0; k<ncoef[it]; k++) { /* loop 140 */\n\t/* model offset */\n\tdr += coef[it][k]*gdx[k*nsou+js];\n\tdd += coef[it][k]*gdy[k*nsou+js];\n      } /* end loop  L140: */\n\n      /* Calculate residuals */\n      rx = dx[i] - soffx[js] - dr;\n      ry = dy[i] - soffy[js] - dd;\n      resid[numt] = sqrt (rx*rx + ry*ry);\n\n      /* Residual statistics */\n      rms += rx*rx + ry*ry;\n      rmscnt++;\n      numt++;  /* How many found? */\n    } \n  } /* end loop  L200: */;\n\n  /* Enough on this source to bother? */\n  if (numt <= 5) goto cleanup;\n\n  /* Source RMS */\n  rms = sqrt (rms/rmscnt);\n\n  /* Can't be more than target */\n  rmst = MIN (rms, MaxRMS);\n\n  /* Loop comparing with 7 point running mean. */\n  nt = 0;\n  wid = MIN (3, numt/2);\n  /* (Best leave this loop 1-rel indexing) */\n  for (i= 1; i<=numt; i++) { /* loop 300 */\n    sum = 0.0;\n    count = 0;\n    i1 = i - wid;\n    i2 = i + wid;\n    if (i1 < 1) {\n      i2 = MIN (numt, 2*wid+1);\n      i1 = 1;\n    } \n    if (i2 > numt) {\n      i2 = MIN (numt, i2);\n      i1 = MAX (1, i2-2*wid);\n    }\n\n    /* Sum points within WID of current  integration but excluding it. */\n    for (j= i1; j<=i2; j++) { /* loop 210 */\n      idt = abs (ktime[i-1]-ktime[j-1]);\n      if ((idt > 0)  &&  (idt <= wid)) {\n\tsum += resid[j-1];\n\tcount++;\n      } \n    } /* end loop  L210: */\n\n    /* Need at least 2 to compare with */\n    if (count > 1) {\n      test = resid[i-1] - (sum / count);\n      /* Toss it if difference greater than 2 sigma. */\n      if (test > 2.0*rmst) {\n\t(*stoss)++;\n\tnt++;\n\tw[iobs[i-1]] = 0.0;\n      } \n    } else {\n      /* Too little to compare - toss */\n      (*stoss)++;\n      nt++;\n      w[iobs[i-1]] = 0.0;\n    } \n  } /* end loop  L300: */\n\n  /* Tell results */\n  if (prtLv>=1) {\n    Obit_log_error(err, OBIT_InfoErr, \n\t\t   \"%s: Source %4d rejected %4d of %4d RMS = %10.3f\", \n\t\t   routine, source+1, nt, numt, 3600.0*rms);\n  }\n\n  /* deallocate arrays */\n cleanup:\n  if (resid) g_free(resid);\n  if (ktime) g_free(ktime);\n  if (iobs)  g_free(iobs);\n\n} /* end of routine IonEditSource */ \n\n/**\n * Get minimum fluxes for strong (required) calibrators \n * At least max(5, nTime/2) good observations needed for a calibrator \n * to be considered\n * \\param nobs      Number of observations \n * \\param nsou      Number of sources  \n * \\param nTime     Number of times  \n * \\param isou      Source number per obs.  (0-rel)\n * \\param iTime     Time number per obs. \n * \\param MinRat    Minimum acceptable ratio to average flux \n * \\param FCStrong  Min. Flux for strong (required) cal \n * \\param flux      Peak flux density of observations \n * \\param prtLv     Print level >=1 => give fitting diagnostics\n * \\param err       Error/message stack \n * \\return array of minimum required flux density for each source\n */\nstatic ofloat* \ngetStrong (olong nobs, olong nsou, olong nTime, olong* isou, olong* iTime, \n\t   ofloat MinRat, ofloat FCStrong, ofloat*  flux, olong prtLv, \n\t   ObitErr* err)\n{\n  ofloat *strong=NULL;\n  olong   i, ngot, navg, isss, jsou;\n  ofloat   *srtflx=NULL, sflux;\n  gchar *routine = \"getStrong\";\n\n  /* Error checks */\n  g_assert(ObitErrIsA(err));\n  if (err->error) return strong;  /* previous error? */\n\n  /* allocate arrays */\n  strong  = g_malloc0(nsou*sizeof(ofloat));\n  srtflx  = g_malloc0(nTime*sizeof(ofloat));\n\n  /* Loop over sources */\n  for (jsou=0; jsou<nsou; jsou++) {\n    /* Loop over observations collecting */\n    ngot = 0;\n    for (i=0; i<nobs; i++) {\n      if (flux[i] > 0) {\n\tisss = isou[i];\n\tif (isss==jsou) srtflx[ngot++] = flux[i];\n      } \n    } /* end loop over observations  */\n\n    /* Get flux density */\n    navg = MAX (3, ngot/4);\n    if (ngot>=MAX(5, nTime/2))\n      sflux = medianAvg(srtflx, 1, navg, FALSE, ngot);\n    else\n      sflux = 0.0;\n\n    /* Set minimum allowable */\n    if (sflux>=FCStrong) {\n      strong[jsou] = MinRat * sflux;\n      /* Tell results */\n      if (prtLv>=2) {\n\tObit_log_error(err, OBIT_InfoErr, \n\t\t       \"%s: Minimum  flux density for source %4d = %10.3f\", \n\t\t       routine,jsou+1, strong[jsou]);\n      }\n    } else strong[jsou] = -1.0e20;\n  } /* end loop over source  */\n\n  if (srtflx) g_free(srtflx);  /* Cleanup */\n\n  return strong;\n} /* end of routine getStrong */ \n\n/**\n * Fit Zernike model to apparent position offsets.  \n * Solution uses gsl fitting\n * dxj = apparent offset in x of obs j  \n * dyj = apparent offset in y of obs j  \n * Pi  = Zernike coefficient i [COEF(I) below],  \n * Gxij = Zernike x gradient term i for obs j        \n * Gyij = Zernike y gradient term i for obs j        \n * \\param nobs Number of observations  \n * \\param isou  Source number per obs.  (0-rel)\n * \\param x     Offset in field X (RA) on unit Zernike circle  per source  \n * \\param y     Offset in field Y (Dec) on unit Zernike circle per source  \n * \\param dx    Apparent RA position shifts on the Zernike plane (deg) \n * \\param dy    Apparent dec position shifts on the Zernike plane (deg) \n * \\param w     Weight per source.\n * \\param ncoef [in] Maximum number of coefficients\n *              [out] actual number\n * \\param coef  [out] Zernike coefficients fitted \n * \\param prtLv Print level >=3 give diagnostics\n * \\param err   Error stack\n * \\return RMS residual (deg) -1 on failure\n */\nstatic ofloat\nIonFit1 (olong nobs, olong* isou, ofloat* x, ofloat* y, \n\t ofloat* dx, ofloat* dy, ofloat* w, \n\t olong* ncoef, ofloat* coef, olong prtLv, ObitErr* err)\n{\n  olong      i, j, is, rmscnt, mcoef;\n  ofloat out = -1.0;\n  ofloat    rms=0.0, dr, dd, rx, ry;\n  gchar *routine = \"IonFit1\";\n  \n  /* initial values 0 */\n  for (i=0; i<*ncoef; i++) coef[i] = 0.0;\n\n  /* How many coeffients can actually  be fitted? */\n  rmscnt = 0;\n  for (i=0; i<nobs; i++) { /* loop 10 */\n    if (w[i] > 0.0) rmscnt++;\n  } /* end loop  L10:  */;\n  *ncoef = MIN (*ncoef, rmscnt*2);\n  if (*ncoef < 17) (*ncoef) = MIN (10, *ncoef);\n  if (*ncoef < 10) (*ncoef) = MIN (5, *ncoef);\n  if (*ncoef < 5)  (*ncoef) = MIN (2, *ncoef);\n  /* Better have something to work  with */\n  if (*ncoef  <=  0) return out;\n  mcoef = *ncoef;\n\n  /* Use gsl fit */\n  FitZernike ((olong)nobs, isou, x, y, dx, dy, w, (olong)mcoef, coef);\n\n  /* Get RMS */\n  rms = 0.0;\n  rmscnt = 0;\n  for (i=0; i<nobs; i++) {\n    if (w[i] > 0.0) {\n      is = isou[i];\n      dr = 0.0;\n      dd = 0.0;\n      for (j=0; j<mcoef; j++) {\n\tdr += coef[j]*ObitZernikeGradX(j+2, x[is], y[is]);\n\tdd += coef[j]*ObitZernikeGradY(j+2, x[is], y[is]);\n      } \n      rx = dx[i] - dr;\n      ry = dy[i] - dd;\n      rms += rx*rx + ry*ry;\n      rmscnt++;\n      /* Diagnostics */\n      if (prtLv>=3) {\n\tObit_log_error(err, OBIT_InfoErr, \n\t\t       \"%s: obs %5d o=%7.2f %7.2f m=%7.2f %7.2f r=%7.2f %7.2f w=%6.2f\",\n\t\t       routine, i+1, dx[i]*3600.0, dy[i]*3600.0, dr*3600.0, dd*3600.0, \n\t\t       rx*3600.0, ry*3600.0, w[i]);\n      }   /* End Diagnostics */\n    } \n  } /* end print loop */ \n  rms = sqrt (rms/rmscnt);\n  Obit_log_error(err, OBIT_InfoErr, \n\t\t   \"%s: RMS residual=%9.2f asec\",routine, 3600.0*rms);\n  ObitErrLog(err); /* show any messages on err */\n\n  out = rms;\n  return out;\n} /* end IonFit1 */ \n\n/**\n * Make a parabolic least-squares fit to a 9x9 matrix about the\n * peak value in an array and determine strength and position\n * of maximum.\n * 0.5*min(imsi[0],imsi[1])  pixels of the center.  \n * Routine translated from the AIPSish CALPOS.FOR/FXPFIT  \n * \\param a       Data input array[dec][RA] \n * \\param dx      Position of max relative to a[5][5]\n * \\param s       Strength of max \n * \\param fblank  Value for blanked pixel  \n * \\return 0=OK else failed  \n */\nstatic olong pfit (ofloat a[9][9], ofloat *s, ofloat dx[2], ofloat fblank)\n{\n  float  absmax, x, y, temp[6], momar[6], d;\n  float mat[3][3] = {{0.55555, -0.33333, -0.33333}, {-0.33333, 0.5, 0.0},\n\t\t     {-0.33333, 0.0, 0.5}};\n  int ix, iy, ixmax, iymax;\n  /* default return values */\n  dx[0] = 0;\n  dx[1] = 0;\n  *s = a[3][3];\n  /*  find peak in array    */\n  absmax = 0.0; ixmax = -1; iymax = -1;\n  for (ix=0; ix<9; ix++) {\n    for (iy=0; iy<9; iy++) {\n      if ((a[iy][ix]!=fblank) && (fabs(a[iy][ix])>absmax)) \n\t{absmax=fabs(a[iy][ix]); ixmax = ix; iymax = iy;}\n    }\n  }\n  /* check for valid data */\n  if ((ixmax<0) || (iymax<0)) return 1;\n  /*  00, 01, 02, 10, 11, 20 */\n  x = ixmax+1;\n  y = iymax+1;\n  /*  default values       */\n  dx[0] = x - 5.0;\n  dx[1] = y - 5.0;\n  *s = a[iymax][ixmax];\n  if (momnt (a, x, y, 3, 3, momar, fblank)) return 1;\n\n  /*  multiply matrix * even moms  yields const & quadratic terms */\n  temp[0] = momar[0];\n  temp[1] = momar[2];\n  temp[2] = momar[5];\n  matvmul (mat, temp, &temp[3], 3);\n\n  /*  pick up linear & cross term  */\n  temp[0] = momar[1] / 6.;\n  temp[1] = momar[3] / 6.;\n  temp[2] = momar[4] / 4.;\n\n  /*  offset of peak */\n  d = 4.* temp[4] * temp[5] - (temp[2]*temp[2]);\n  if (d==0.0) return 2;\n  dx[0] = (temp[2]*temp[0] - 2.*temp[1]*temp[4]) / d;\n  dx[1] = (temp[2]*temp[1] - 2.*temp[0]*temp[5]) / d;\n  /*  value of peak */\n  *s = temp[3] + dx[0]*(temp[1] + dx[0]*temp[5]\n\t\t\t+ dx[1]*temp[2]) + dx[1]*(temp[0]+dx[1]*temp[4]);\n  dx[0] = dx[0] + x - 5.0;  /* correct wrt center of input array */\n  dx[1] = dx[1] + y - 5.0;\n  return 0;\n} /* end of pfit */\n\n/**\n * Calculate all 0th, 1st, and 2nd moments of a nx*ny subarray of ara\n * centered at x,y.  nx and ny should be odd.\n * \\param ara     Input data array \n * \\param x       x-center for moment calculation (1-rel)\n * \\param nx      # of points to include in x-direction. nx  \n *                should be odd.  \n *                The points will be centered about x (rounded)\n * \\param ny      # of points in y-direction\n * \\param momar   00,10,20,01,11,02 yx-moments of ara  \n * \\param fblank  Value for blanked pixel  \n * \\return 0=OK else failed  1 => subarray doesn't fit in main array \n */\nstatic olong \nmomnt (ofloat ara[9][9], ofloat x, ofloat y, olong nx, olong ny, \n       ofloat momar[6], ofloat fblank)\n  {\n    olong  ind, i, j, k, nj, indx, indy, iax1, iax2, iay1, iay2;\n    ofloat s, t, arg, prod;\n    \n    /*      compute loop limits (1-rel)   */\n    i = x + 0.5;\n    iax1 = i - nx/2;\n    iax2 = iax1 + nx - 1;\n    i = y + 0.5;\n    iay1 = i - ny/2;\n    iay2 = iay1+ ny - 1;\n\n    /*      check loop limits             */\n    if ((iax1<1) || (iax2>9) || (iay1<1) || (iay2>9)) return 1;\n    /*      compute moments               */\n    ind = 0;\n    for (i = 1; i<=3; i++) {\n      nj = 4 - i;\n      for (j=1; j<=nj; j++) {\n\tind = ind + 1;\n\ts = 0.0;\n\tfor (indx=iax1; indx<=iax2; indx++) {\n\t  for (indy=iay1; indy<=iay2; indy++) {\n\t    t = ara[indy-1][indx-1];\n\t    if (t!=fblank) {\n\t      if (i>1) {\n\t\tprod = 1.0; \n\t\targ = indx - x;\n\t\tfor (k=1; k<i; k++) prod *= arg;\n\t\tt = t * prod;}     /* ((indx - x)**(i-1)); */\n\t      if (j>1) {\n\t\tprod = 1.0; \n\t\targ = indy - y;\n\t\tfor (k=1; k<j; k++) prod *= arg;\n\t\tt = t * prod;}  /* ((indy - y)**(j-1));*/\n\t      s = s + t;}\n\t  }\n\t}\n\tmomar[ind-1] = s;\n      }\n    }\n    return 0;\n  }  /* end of momnt */\n\n/**\n *  Matrix-vector multiplication  vo = vi * m  \n * \\param  m      Input matrix      \n * \\param vi      Input vector \n * \\param n       Array dimension  \n * \\param vo      [out] Output vector\n */\nstatic void matvmul (ofloat m[3][3], ofloat vi[3], ofloat vo[3], olong n)\n{\n  int  i, j;\n  float s;\n  \n  for (i=0; i<n; i++) {\n    s = 0.0;\n    for (j=0; j<n; j++) s = s + m[j][i] * vi[j];\n    vo[i] = s;\n  }\n}  /* end of matvmul */\n\n\n/**\n * Converts from celestial coordinates, expressed in terms of  \n * a reference position and a shift from this position to coordinates  \n * in a plane for fitting an Ionospheric phase screen model  \n * consisting of Zernike polynomials.  The output coordinates are  \n * normalized to unity at a 10 deg radius from the reference position.  \n * The coordinates are projected onto a plane tangent to the sky at  \n * the reference position.  \n * Routine translated from the AIPSish ZERGEOM.FOR/RD2ZER \n * \\param ra      Right Ascention of reference position (deg) \n * \\param dec     Declination of reference position (deg) \n * \\param xshift  Shift in X (RA) to desired position (deg) \n * \\param yshift  Shift in Y (Dec) to desired position (deg) \n * \\param xzer    [out] x-coordinate on Zernike plane \n * \\param yzer    [out]  y-coordinate on Zernike plane \n * \\param ierr    0 ok, 1 out of range \n */\nstatic void rd2zer (odouble ra, odouble dec, ofloat xshift, ofloat yshift, \n\t\t    ofloat* xzer, ofloat* yzer, olong *ierr) \n{\n  odouble dx, dy, a, b, ax, ay, xxinc, coss, sins, sint, dt;\n  odouble pi, twopi, zernor;\n\n  /* Constants */\n  pi = 3.14159265358979323846e0;\n  twopi = 2.0e0*pi;\n  /* Zernike normalization to Unit circle (10 deg) */\n  zernor = 1.0 / (10.0e0 * DG2RAD);\n\n  /* initial values */\n  *xzer = 0.0;\n  *yzer = 0.0;\n  *ierr = 0;\n  \n  /* Convert to radians */\n  a = DG2RAD * ra;\n  b = DG2RAD * dec;\n  /* Convert shift to position */\n  xxinc = cos (DG2RAD * dec);\n  if (xxinc != 0) {\n    ax = ra + xshift / xxinc;\n  } else {\n    ax = ra;\n  } \n  ay = dec + yshift;\n  ax = ax * DG2RAD;\n  ay = ay * DG2RAD;\n  \n  /* Get projection cosines */\n  *ierr = 1;\n  if (fabs(ay) > pi/2.0e0) return;\n  if (fabs(b) > pi/2.0e0) return;\n  *ierr = 0;\n  coss = cos (ay);\n  sins = sin (ay);\n  dt = ax - a;\n  if (dt > pi) dt = dt - twopi;\n  if (dt < -pi) dt = dt + twopi;\n  dx = sin (dt) * coss;\n  sint = sins * sin (b) + coss * cos (b) * cos (dt);\n  \n  /* SIN projection */\n  /*      IF (SINT.LT.0.0D0) IERR = 2 */\n  if (sint < 0.0e0) {\n    *ierr= 1;\n    return;\n  } \n  dy = sins * cos (b) - coss * sin (b) * cos (dt);\n\n  /* Normalize to Zernike unit sphere */\n  *xzer = dx * zernor;\n  *yzer = dy * zernor;\n  return;\n} /* end of routine rd2zer */ \n\n/**\n * Given an offset from a given field center, return the rotation of  \n * the coordinates of the offset wrt the field center.  \n * This is just the difference in RA.  \n * Routine translated from the AIPSish ZERGEOM.FOR/ZERROT  \n * \\param ra   Initial RA in degrees: ref point \n * \\param dec   Initial Declination in degrees: ref point \n * \\param xshift   Shift in \"X\" in degrees - simple shifts not -SIN \n * \\param yshift   Shift in \"Y\" in degrees \n * \\param rotate   [out] Image rotation in degrees \n */\nstatic void zerrot (odouble ra, odouble dec, ofloat xshift, ofloat yshift, \n\t\t    ofloat* rotate) \n{\n  odouble xxinc, xra, xdec;\n  \n  /* simple shifts */\n  xdec = dec + yshift;\n  xxinc = cos (DG2RAD * dec);\n  if (xxinc != 0) {\n    xra = ra + xshift / xxinc;\n  } else {\n    xra = ra;\n       } \n  /* Difference in RA */\n  (*rotate) = (ra - xra);\n  /* Fold to range (-180,+180) */\n  if (*rotate > +180.0e0) (*rotate) -= 360.0e0;\n  if (*rotate < -180.0e0) (*rotate) += 360.0e0;\n} /* end of routine zerrot */ \n\n/**\n * Convert a timerange as time in days to a printable string\n * \\param    timer  Beginning time, end time in days\n * \\msgBuff  Human readable string as \"dd/hh:mm:ss.s-dd/hh:mm:ss.s\"\n *           must be allocated at least 30 characters\n */\nstatic void TR2String (ofloat timer[2], gchar *msgBuf)\n{\n  ofloat rtemp, rt1, rt2;\n  olong   id1, id2, it1, it2, it3, it4;\n\n  id1 = timer[0];\n  rtemp = 24.0 * (timer[0] - id1);\n  it1 = rtemp;\n  it1 = MIN (23, it1);\n  rtemp = (rtemp - it1)*60.0;\n  it2 = rtemp;\n  it2 = MIN (59, it2);\n  rt1 = (rtemp - it2)*60.0;\n  id2 = timer[1];\n  rtemp = 24.0 * (timer[1] - id2);\n  it3 = rtemp;\n  it3 = MIN (23, it3);\n  rtemp = (rtemp - it3)*60.0;\n  it4 = rtemp;\n  it4 = MIN (59, it4);\n  rt2 = (rtemp - it4)*60.0;\n  g_snprintf (msgBuf, 30, \"%2.2d/%2.2d:%2.2d:%5.2f-%2.2d/%2.2d:%2.2d:%5.2f\",\n\t      id1, it1, it2, rt1, id2, it3, it4, rt2);\n} /* end of routine TR2String   */ \n\n/*                 CalListElem functions             */\n\n/**\n * CalListElem Constructor\n * \\param ra      Catalog celestial position RA (deg)\n * \\param dec     Catalog celestial position RA (deg)\n * \\param ZernXY  Offset on Zernike plane (deg)\n * \\param shift   Shift from reference position\n * \\param pixel   Expected pixel in reference image\n * \\param flux    Estimated catalog flux density\n * \\param offset  Measured offset from expected position (pixels)\n * \\param peak    Measured peak flux density (image units)\n * \\param fint    Measured integrated flux density (image units)\n * \\param wt      Determined weight\n * \\param qual    Catalog quality code \n * \\param calNo   Calibrator number\n * \\param epoch   Epoch number\n * \\return the new  object.\n */\nstatic CalListElem* \nnewCalListElem (odouble ra, odouble dec, ofloat ZernXY[2], ofloat shift[2],\n\t\tofloat pixel[2], ofloat flux, ofloat offset[2],\n\t\tofloat peak, ofloat fint, ofloat wt,  olong qual,\n\t\tolong calNo, olong epoch)\n{\n  CalListElem *out=NULL;\n\n  out = g_malloc0(sizeof(CalListElem));\n  out->ra        = ra;\n  out->dec       = dec;\n  out->ZernXY[0] = ZernXY[0];\n  out->ZernXY[1] = ZernXY[1];\n  out->shift[0]  = shift[0];\n  out->shift[1]  = shift[1];\n  out->pixel[0]  = pixel[0];\n  out->pixel[1]  = pixel[1];\n  out->flux      = flux;\n  out->offset[0] = offset[0];\n  out->offset[1] = offset[1];\n  out->peak      = peak;\n  out->fint      = fint;\n  out->wt        = wt;\n  out->qual      = qual;\n  out->calNo     = calNo;\n  out->epoch     = epoch;\n  return out;\n} /* end newCalListElem */\n\n/**\n * Update CalListElem\n * \\param elem    CalListElem to update\n * \\param ra      Catalog celestial position RA (deg)\n * \\param dec     Catalog celestial position Dec (deg)\n * \\param ZernXY  Offset on Zernike plane (deg)\n * \\param shift   Shift from reference position\n * \\param pixel   Expected pixel in reference image\n * \\param flux    Estimated catalog flux density\n * \\param offset  Measured offset from expected position (pixels)\n * \\param peak    Measured peak flux density (image units)\n * \\param fint    Measured integrated flux density (image units)\n * \\param wt      Determined weight\n * \\param qual    Catalog quality code \n * \\param calNo   Calibrator number\n * \\param epoch   Epoch number\n * \\return the new  object.\n */\nstatic void\nCalListElemUpdate (CalListElem *elem, odouble ra, odouble dec, \n\t\t   ofloat ZernXY[2], ofloat shift[2], ofloat pixel[2], \n\t\t   ofloat flux, ofloat offset[2], ofloat peak, ofloat fint, \n\t\t   ofloat wt, olong qual, olong calNo, olong epoch)\n{\n  elem->ra        = ra;\n  elem->dec       = dec;\n  elem->ZernXY[0] = ZernXY[0];\n  elem->ZernXY[1] = ZernXY[1];\n  elem->shift[0]  = shift[0];\n  elem->shift[1]  = shift[1];\n  elem->pixel[0]  = pixel[0];\n  elem->pixel[1]  = pixel[1];\n  elem->flux      = flux;\n  elem->offset[0] = offset[0];\n  elem->offset[1] = offset[1];\n  elem->peak      = peak;\n  elem->fint      = fint;\n  elem->wt        = wt;\n  elem->qual      = qual;\n  elem->calNo     = calNo;\n  elem->epoch     = epoch;\n} /* end CalListElemUpdate */\n\n/**\n * Print contents \n * \\param in Object to print\n * \\param file  FILE* to write to\n */\nstatic void CalListElemPrint (CalListElem *in, FILE *file)\n{\n  if (!in) return;\n\n  fprintf (file, \"Cal. no.=%d, epoch=%d\\n\",in->calNo, in->epoch);\n  fprintf (file, \"RA=%lf, Dec=%lf\\n\",in->ra, in->dec);\n  fprintf (file, \"Offset (deg) on Zernike plane [%f,%f]\\n\",\n\t   in->ZernXY[0],in->ZernXY[1]);\n  fprintf (file, \"Position shift (deg) [%f,%f]\\n\",\n\t   in->shift[0],in->shift[1]);\n  fprintf (file, \"Expected pixel [%f,%f]\\n\",\n\t   in->pixel[0],in->pixel[1]);\n  fprintf (file, \"Expected flux density %f, quality %d\\n\",\n\t   in->flux,in->qual);\n  fprintf (file, \"Measured position offset (asec) [%f,%f]\\n\",\n\t   in->offset[0]*3600.0,in->offset[1]*3600.0);\n  fprintf (file, \"Measured peak %f, integ. %f, wt %f\\n\",\n\t   in->peak,in->fint, in->wt);\n\n} /* end CalListElemPrint */\n\n/**\n * Destructor \n * \\param in Object to delete\n */\nstatic void freeCalListElem (CalListElem *in)\n{\n  if (in) g_free(in);\n} /* end freeCalListElem */\n\n\n\n/*  CalList functions */\n/**\n * CalList Constructor\n * \\return the new  CalList structure.\n */\nstatic CalList* newCalList (void)\n{\n  CalList *out=NULL;\n\n  out = g_malloc0(sizeof(CalList));\n  out->number = 0;\n  out->list   = NULL;\n  return out;\n} /* end newCalListElem */\n\n/**\n * Attach elem to list in\n * \\param in   list to add elem to\n * \\param elem the element to add.\n */\nstatic void CalListAdd (CalList *in, CalListElem *elem)\n{\n  /* link to list */\n  in->list = g_slist_append (in->list, elem);\n  in->number++;\n} /* end CalListAdd */\n\n/**\n * Remove elem from list in\n * \\param in   list to remove elem from\n * \\param elem the element to remove.\n */\nstatic void CalListRemove (CalList *in, CalListElem *elem)\n{\n  /* remove from list */\n  in->list = g_slist_remove(in->list, elem);\n  in->number--; /* keep count */  \n} /* end CalListRemove  */\n\n/**\n * Remove all elements from list in\n * \\param in   list to remove elem from\n * \\param elem the element to remove.\n */\nstatic void CalListClear (CalList *in)\n{\n  GSList *tmp;\n\n  if (in==NULL) return;  /* Does it exist? */\n  if (in->list==NULL) return;  /* Anything in it? */\n\n  /* loop through list deleting elements */\n  tmp = in->list;\n  while (tmp!=NULL) {\n    if (tmp->data) freeCalListElem(tmp->data);\n    tmp = g_slist_next(tmp);\n  }\n\n  /* delete members  */\n  g_slist_free(in->list);\n  in->list = NULL;\n  in->number = 0;\n\n} /* end CalListClear  */\n\n/**\n * Print all elements in list in to file\n * \\param in   list to remove elem from\n * \\param elem the element to remove.\n */\nstatic void CalListPrint (CalList *in, FILE *file)\n{\n  GSList *tmp;\n\n  if (in==NULL) return;  /* Does it exist? */\n  if (in->list==NULL) return;  /* Anything in it? */\n\n  fprintf (file, \"Listing Of CalList\\n\");\n\n  /* loop through list deleting elements */\n  tmp = in->list;\n  while (tmp!=NULL) {\n    if (tmp->data) CalListElemPrint(tmp->data, file);\n    tmp = g_slist_next(tmp);\n  }\n\n} /* end CalListPrint  */\n\n/**\n * Destructor \n * \\param in Object to delete\n */\nstatic void freeCalList (CalList *in)\n{\n  /* Clear List */\n  CalListClear(in);\n\n  /* delete object */\n  g_free(in);\n} /* end freeCalListElem */\n\n/**\n * Fit Zernike polynomial to position offset pairs\n * Use gsl package.\n * \\param nobs    Number of data measurements\n * \\param isou    Source number per obs.  (0-rel)\n * \\param x       Zernike X on unit circle per source\n * \\param y       Zernike Y on unit circle per source\n * \\param dx      X offset (deg)\n * \\param dy      X offset (deg)\n * \\param wt      Data weights\n * \\param nZern   Number of Zernike coefficients to fit\n * \\param coef    [out] Zernike coefficients\n */\nvoid  FitZernike (olong nobs, olong* isou, ofloat *x, ofloat *y, \n\t\t  ofloat *dx, ofloat *dy, ofloat *wt, \n\t\t  olong nZern, ofloat *coef)\n{\n#if HAVE_GSL==1  /* GSL stuff */\n  olong i, j, k, is, good, p=nZern, npen;\n  double xi, chisq, sumwt, penWt;\n  gsl_matrix *X, *cov;\n  gsl_vector *yy, *w, *c;\n  gsl_multifit_linear_workspace *work;\n  /* Penalty terms by order of Zernike 1-4 */\n  ofloat pen[]={0.001, 0.001,\n\t\t0.01, 0.01, 0.01,\n\t\t0.03, 0.03, 0.03, 0.03, 0.03, \n\t\t0.05, 0.05, 0.05,0.05,  0.05, 0.05, 0.05, \n\t\t0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08};\n\n  /* Only use good data (2 per measurement) */\n  good = 0;sumwt = 0.0;\n  for (i=0; i<nobs; i++) if (wt[i]>0.0) \n    {good += 2; sumwt += wt[i];}\n\n  /* Number of penalty terms */\n  npen = nZern;\n\n  /* allocate arrays */\n  X    = gsl_matrix_alloc(good+npen, p);\n  yy   = gsl_vector_alloc(good+npen);\n  w    = gsl_vector_alloc(good+npen);\n  c    = gsl_vector_alloc(p);\n  cov  = gsl_matrix_alloc(p, p);\n  work = gsl_multifit_linear_alloc (good+npen, p);\n\n  /* set data */\n  k = 0;\n  for (i=0; i<nobs; i++) {\n    if (wt[i]>0.0) {\n      is = isou[i];\n      /* X offset */\n      gsl_vector_set(yy, k, dx[i]);\n      gsl_vector_set(w, k, wt[i]);\n      for (j=0; j<p; j++) {\n\txi = ObitZernikeGradX(j+2, x[is], y[is]);\n\tgsl_matrix_set(X, k, j, xi);\n      }\n      k++; \n      /* Y offset */\n      gsl_vector_set(yy, k, dy[i]);\n      gsl_vector_set(w, k, wt[i]);\n      for (j=0; j<p; j++) {\n\txi = ObitZernikeGradY(j+2, x[is], y[is]);\n\tgsl_matrix_set(X, k, j, xi);\n      }\n      k++; \n    }\n  }\n\n  /* Penalty terms - try to get coefficients as small as possible */\n  penWt = sumwt / good;  /* Penalty weight data dependency */\n  for (i=0; i<npen; i++) {\n    gsl_vector_set(yy, k, 0.0);\n    gsl_vector_set(w, k, penWt*pen[i]);\n    for (j=0; j<p; j++) {\n      if (j==i) xi = 1.0;\n      else xi = 0.0;\n      gsl_matrix_set(X, k, j, xi);\n    }\n    k++; \n  } /* end penalty loop */\n\n  /* Fit */\n  gsl_multifit_wlinear (X, w, yy, c, cov, &chisq, work);\n\n  /* get results */\n  for (j=0; j<nZern; j++) coef[j] = gsl_vector_get(c, j);\n\n  /* Deallocate arrays */\n  gsl_matrix_free(X);\n  gsl_vector_free(yy);\n  gsl_vector_free(w);\n  gsl_vector_free(c);\n  gsl_matrix_free(cov);\n  gsl_multifit_linear_free (work);\n#else  /* No GSL - stubb */\n  g_error (\"FitZernike: GSL not available - cannot do fit\");\n#endif /* GSL stuff */\n} /* end FitZernike */\n\n/**\n * Called when CLEAN failed to mark first 5 entries as failed.\n * \\param in   IonCal object \n * \\param mosaic   Image mosaic object \n * \\param calList Calibrator list each element of which has:\n * \\li ra      position RA (deg) of calibrators\n * \\li dec     position Dec (deg) of calibrators\n * \\li shift   Offset in field [x,y] on unit Zernike circle of position\n * \\li pixel   Expected pixel in reference image\n * \\li flux    Estimated catalog flux density \n * \\li offset  Measured offset [x,y] from expected position (deg)\n * \\li peak    set to 0.0\n * \\li fint    set to 0.0\n * \\li wt      set to 0.0\n * \\li qual    Catalog quality code\n * \\param err     Error stack\n * \\param epoch   Epoch number\n */\nstatic void CalBadTime (ObitIonCal *in, ObitImageMosaic* mosaic, \n\t\t\tolong epoch, ObitErr* err)  \n{\n  olong   field;\n  ofloat offset[2], peak, fint, wt;\n  ObitImage *image=NULL;\n  CalListElem *elem=NULL, *nelem=NULL;\n  GSList  *tmp;\n  CalList *calList;\n  /*gchar *routine = \"CalBadTime\";*/\n\n  /* Error checks */\n  g_assert(ObitErrIsA(err));\n  if (err->error) return ;  /* previous error? */\n  g_assert(ObitIonCalIsA(in));\n  g_assert(ObitImageMosaicIsA(mosaic));\n\n  calList = (CalList*)in->calList;\n\n  /* do up to 5 fields Loop over images  */\n  for (field=0; field<MIN (5, mosaic->numberImages); field++) {\n    image = mosaic->images[field];\n \n    /* Find cal info */\n    tmp = calList->list;\n    while (tmp!=NULL) {   /* loop 100 */\n      elem = (CalListElem*)tmp->data;\n      if (elem->calNo == (field+1)) break;  /* found it */\n      tmp = g_slist_next(tmp);  /* next item in list */\n    } /* end loop  L100: over calibrator list */\n\n    /* zero it out */\n    offset[0] = offset[1] = 0.0;\n    peak = 0.0;\n    fint = 0.0;\n    wt   = 0.0;\n\n    /* Update CalList */\n    nelem = newCalListElem (elem->ra, elem->dec, elem->ZernXY, elem->shift, \n\t\t\t    elem->pixel, elem->flux, offset, peak, fint, wt, \n\t\t\t    elem->qual, field+1, epoch);\n    CalListAdd (calList, nelem);\n  } /* end loop over fields */\n  \n} /* end of routine CalBadTime */ \n\n", "meta": {"hexsha": "2b570c85d8933d05b1985be7984d23a39a8ad929", "size": 165257, "ext": "c", "lang": "C", "max_stars_repo_path": "ObitSystem/Obit/src/ObitIonCal.c", "max_stars_repo_name": "sarrvesh/Obit", "max_stars_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-08-26T06:53:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-20T01:08:59.000Z", "max_issues_repo_path": "ObitSystem/Obit/src/ObitIonCal.c", "max_issues_repo_name": "sarrvesh/Obit", "max_issues_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ObitSystem/Obit/src/ObitIonCal.c", "max_forks_repo_name": "sarrvesh/Obit", "max_forks_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-08-29T15:12:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:16:08.000Z", "avg_line_length": 33.3246622303, "max_line_length": 99, "alphanum_fraction": 0.6015357897, "num_tokens": 56505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.26284183737131667, "lm_q2_score": 0.025957355596589873, "lm_q1q2_score": 0.006822679038308312}}
{"text": "#define PY_SSIZE_T_CLEAN\n#include <Python.h>\n#include <gsl_vector.h>\n\n#include \"svm_main.h\"\n#include \"test_main.h\"\n\nPyObject* __opt(PyObject* self, PyObject* args) {\n    PyObject* elements;\n    int k_type;    // 1 if RBF kernel is used 0 for my kernel\n\tdouble C;\t// hyperparameter for optimization\n\tif (!PyArg_ParseTuple(args, \"Oid\", &elements, &k_type, &C))\n\t\treturn NULL;\n\n\treturn __get_w_b(elements, k_type, C);\n}\n\nPyObject* __test(PyObject* self, PyObject* args) {\n\tPyObject* training;\n\tPyObject* testing;\n\tPyObject* alphas;\n\tdouble b;\n\tint rbf;\n\tif (!PyArg_ParseTuple(args, \"OOOdi\", &training, &testing, &alphas, &b, &rbf))\n\t\treturn NULL;\n\treturn __test_t(training, testing, alphas, b, rbf);\n}\n\nstatic PyMethodDef methods[] = {\n\t{\"opt\", __opt, METH_VARARGS, \"\"},\n\t{\"test\", __test, METH_VARARGS, \"\"},\n\t{NULL, NULL, 0, NULL}\n};\n\nstatic struct PyModuleDef c_opt = {\n\tPyModuleDef_HEAD_INIT,\n\t\"C OPT\",\n\t\"C interop to optimize a custom implementation of an SVM\",\n\t-1,\n\tmethods\n};\n\nPyMODINIT_FUNC PyInit_c_opt() {\n\treturn PyModule_Create(&c_opt);\n}", "meta": {"hexsha": "125e6729d6b2f26830a202790fdffb17e65ce036", "size": 1046, "ext": "c", "lang": "C", "max_stars_repo_path": "Source/SVM/Source/py_wrapper.c", "max_stars_repo_name": "HARDIntegral/ADHD_Classifier", "max_stars_repo_head_hexsha": "f86c8eafa78ca241919d12134afe796c665f8021", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Source/SVM/Source/py_wrapper.c", "max_issues_repo_name": "HARDIntegral/ADHD_Classifier", "max_issues_repo_head_hexsha": "f86c8eafa78ca241919d12134afe796c665f8021", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/SVM/Source/py_wrapper.c", "max_forks_repo_name": "HARDIntegral/ADHD_Classifier", "max_forks_repo_head_hexsha": "f86c8eafa78ca241919d12134afe796c665f8021", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2444444444, "max_line_length": 78, "alphanum_fraction": 0.6978967495, "num_tokens": 309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38491214448393346, "lm_q2_score": 0.017712299254336712, "lm_q1q2_score": 0.00681767908972792}}
{"text": "//\n// Created by pedram pakseresht on 2/18/21.\n//\n\n// #include <petsc.h>\n\n#include <printf.h>\n#include <stdlib.h>\n\nvoid setNumber(double *zxy);\n\n\nint main( int argc, char *argv[] )\n{\n  double *x = NULL;\n    x = malloc( sizeof(double ));\n    *x =2.0;\n\n printf(\"hello world %g\\n\", *x);\n setNumber(x);\n printf(\"hello world %g\\n\", *x);\n printf(\"size of %lu\", sizeof(double *));\n\n free(x);\n x=NULL;\n\n\n}\n\nvoid setNumber(double *z){\n    printf(\"hello world %g\\n\", *z);\n    *z =1;\n    printf(\"hello world %g\\n\", *z);\n}\n\n\n", "meta": {"hexsha": "a566cd6748e05b77494cc5381eb7b935327089ae", "size": 513, "ext": "c", "lang": "C", "max_stars_repo_path": "pointerExp.c", "max_stars_repo_name": "pakserep/ablateClient", "max_stars_repo_head_hexsha": "c7bb7cf4a4ec706170efd7c06bf8589e30ece47b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pointerExp.c", "max_issues_repo_name": "pakserep/ablateClient", "max_issues_repo_head_hexsha": "c7bb7cf4a4ec706170efd7c06bf8589e30ece47b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pointerExp.c", "max_forks_repo_name": "pakserep/ablateClient", "max_forks_repo_head_hexsha": "c7bb7cf4a4ec706170efd7c06bf8589e30ece47b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.8648648649, "max_line_length": 43, "alphanum_fraction": 0.5730994152, "num_tokens": 162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.12765261868437058, "lm_q2_score": 0.05340333507274787, "lm_q1q2_score": 0.006817075568515158}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/time.h>\n#include <time.h>\n#include <math.h>\n#include <float.h>\n#include \"bingham/util.h\"\n//#include <lapacke.h>\n//#undef I  // fuck C99!\n\nconst color_t colormap[256] =\n  {{0, 0, 131},\n   {0, 0, 135},\n   {0, 0, 139},\n   {0, 0, 143},\n   {0, 0, 147},\n   {0, 0, 151},\n   {0, 0, 155},\n   {0, 0, 159},\n   {0, 0, 163},\n   {0, 0, 167},\n   {0, 0, 171},\n   {0, 0, 175},\n   {0, 0, 179},\n   {0, 0, 183},\n   {0, 0, 187},\n   {0, 0, 191},\n   {0, 0, 195},\n   {0, 0, 199},\n   {0, 0, 203},\n   {0, 0, 207},\n   {0, 0, 211},\n   {0, 0, 215},\n   {0, 0, 219},\n   {0, 0, 223},\n   {0, 0, 227},\n   {0, 0, 231},\n   {0, 0, 235},\n   {0, 0, 239},\n   {0, 0, 243},\n   {0, 0, 247},\n   {0, 0, 251},\n   {0, 0, 255},\n   {0, 4, 255},\n   {0, 8, 255},\n   {0, 12, 255},\n   {0, 16, 255},\n   {0, 20, 255},\n   {0, 24, 255},\n   {0, 28, 255},\n   {0, 32, 255},\n   {0, 36, 255},\n   {0, 40, 255},\n   {0, 44, 255},\n   {0, 48, 255},\n   {0, 52, 255},\n   {0, 56, 255},\n   {0, 60, 255},\n   {0, 64, 255},\n   {0, 68, 255},\n   {0, 72, 255},\n   {0, 76, 255},\n   {0, 80, 255},\n   {0, 84, 255},\n   {0, 88, 255},\n   {0, 92, 255},\n   {0, 96, 255},\n   {0, 100, 255},\n   {0, 104, 255},\n   {0, 108, 255},\n   {0, 112, 255},\n   {0, 116, 255},\n   {0, 120, 255},\n   {0, 124, 255},\n   {0, 128, 255},\n   {0, 131, 255},\n   {0, 135, 255},\n   {0, 139, 255},\n   {0, 143, 255},\n   {0, 147, 255},\n   {0, 151, 255},\n   {0, 155, 255},\n   {0, 159, 255},\n   {0, 163, 255},\n   {0, 167, 255},\n   {0, 171, 255},\n   {0, 175, 255},\n   {0, 179, 255},\n   {0, 183, 255},\n   {0, 187, 255},\n   {0, 191, 255},\n   {0, 195, 255},\n   {0, 199, 255},\n   {0, 203, 255},\n   {0, 207, 255},\n   {0, 211, 255},\n   {0, 215, 255},\n   {0, 219, 255},\n   {0, 223, 255},\n   {0, 227, 255},\n   {0, 231, 255},\n   {0, 235, 255},\n   {0, 239, 255},\n   {0, 243, 255},\n   {0, 247, 255},\n   {0, 251, 255},\n   {0, 255, 255},\n   {4, 255, 251},\n   {8, 255, 247},\n   {12, 255, 243},\n   {16, 255, 239},\n   {20, 255, 235},\n   {24, 255, 231},\n   {28, 255, 227},\n   {32, 255, 223},\n   {36, 255, 219},\n   {40, 255, 215},\n   {44, 255, 211},\n   {48, 255, 207},\n   {52, 255, 203},\n   {56, 255, 199},\n   {60, 255, 195},\n   {64, 255, 191},\n   {68, 255, 187},\n   {72, 255, 183},\n   {76, 255, 179},\n   {80, 255, 175},\n   {84, 255, 171},\n   {88, 255, 167},\n   {92, 255, 163},\n   {96, 255, 159},\n   {100, 255, 155},\n   {104, 255, 151},\n   {108, 255, 147},\n   {112, 255, 143},\n   {116, 255, 139},\n   {120, 255, 135},\n   {124, 255, 131},\n   {128, 255, 128},\n   {131, 255, 124},\n   {135, 255, 120},\n   {139, 255, 116},\n   {143, 255, 112},\n   {147, 255, 108},\n   {151, 255, 104},\n   {155, 255, 100},\n   {159, 255, 96},\n   {163, 255, 92},\n   {167, 255, 88},\n   {171, 255, 84},\n   {175, 255, 80},\n   {179, 255, 76},\n   {183, 255, 72},\n   {187, 255, 68},\n   {191, 255, 64},\n   {195, 255, 60},\n   {199, 255, 56},\n   {203, 255, 52},\n   {207, 255, 48},\n   {211, 255, 44},\n   {215, 255, 40},\n   {219, 255, 36},\n   {223, 255, 32},\n   {227, 255, 28},\n   {231, 255, 24},\n   {235, 255, 20},\n   {239, 255, 16},\n   {243, 255, 12},\n   {247, 255, 8},\n   {251, 255, 4},\n   {255, 255, 0},\n   {255, 251, 0},\n   {255, 247, 0},\n   {255, 243, 0},\n   {255, 239, 0},\n   {255, 235, 0},\n   {255, 231, 0},\n   {255, 227, 0},\n   {255, 223, 0},\n   {255, 219, 0},\n   {255, 215, 0},\n   {255, 211, 0},\n   {255, 207, 0},\n   {255, 203, 0},\n   {255, 199, 0},\n   {255, 195, 0},\n   {255, 191, 0},\n   {255, 187, 0},\n   {255, 183, 0},\n   {255, 179, 0},\n   {255, 175, 0},\n   {255, 171, 0},\n   {255, 167, 0},\n   {255, 163, 0},\n   {255, 159, 0},\n   {255, 155, 0},\n   {255, 151, 0},\n   {255, 147, 0},\n   {255, 143, 0},\n   {255, 139, 0},\n   {255, 135, 0},\n   {255, 131, 0},\n   {255, 128, 0},\n   {255, 124, 0},\n   {255, 120, 0},\n   {255, 116, 0},\n   {255, 112, 0},\n   {255, 108, 0},\n   {255, 104, 0},\n   {255, 100, 0},\n   {255, 96, 0},\n   {255, 92, 0},\n   {255, 88, 0},\n   {255, 84, 0},\n   {255, 80, 0},\n   {255, 76, 0},\n   {255, 72, 0},\n   {255, 68, 0},\n   {255, 64, 0},\n   {255, 60, 0},\n   {255, 56, 0},\n   {255, 52, 0},\n   {255, 48, 0},\n   {255, 44, 0},\n   {255, 40, 0},\n   {255, 36, 0},\n   {255, 32, 0},\n   {255, 28, 0},\n   {255, 24, 0},\n   {255, 20, 0},\n   {255, 16, 0},\n   {255, 12, 0},\n   {255, 8, 0},\n   {255, 4, 0},\n   {255, 0, 0},\n   {251, 0, 0},\n   {247, 0, 0},\n   {243, 0, 0},\n   {239, 0, 0},\n   {235, 0, 0},\n   {231, 0, 0},\n   {227, 0, 0},\n   {223, 0, 0},\n   {219, 0, 0},\n   {215, 0, 0},\n   {211, 0, 0},\n   {207, 0, 0},\n   {203, 0, 0},\n   {199, 0, 0},\n   {195, 0, 0},\n   {191, 0, 0},\n   {187, 0, 0},\n   {183, 0, 0},\n   {179, 0, 0},\n   {175, 0, 0},\n   {171, 0, 0},\n   {167, 0, 0},\n   {163, 0, 0},\n   {159, 0, 0},\n   {155, 0, 0},\n   {151, 0, 0},\n   {147, 0, 0},\n   {143, 0, 0},\n   {139, 0, 0},\n   {135, 0, 0},\n   {131, 0, 0},\n   {128, 0, 0}};\n\n\ndouble get_time_ms()\n{\n  struct timeval tv;\n  struct timezone tz;\n\n  gettimeofday(&tv, &tz);\n\n  return 1000.*tv.tv_sec + tv.tv_usec/1000.;\n}\n\n\n// returns a pointer to the nth word (starting from 0) in string s\nchar *sword(const char *s, const char *delim, int n)\n{\n  if (s == NULL)\n    return NULL;\n\n  s += strspn(s, delim);  // skip over initial delimeters\n\n  int i;\n  for (i = 0; i < n; i++) {\n    s += strcspn(s, delim);  // skip over word\n    s += strspn(s, delim);  // skip over delimeters\n  }\n\n  return (char *)s;\n}\n\n\n// splits a string into k words\nchar **split(const char *s, const char *delim, int *k)\n{\n  const char *sbuf = s + strspn(s, delim);  // skip over initial whitespace\n  s = sbuf;\n\n  // determine the number of words\n  int num_words = 0;\n  while (*s != '\\0') {\n    s = sword(s, delim, 1);\n    num_words++;\n  }\n\n  // fill in the words\n  int i;\n  s = sbuf;\n  char **words;\n  safe_calloc(words, num_words, char *);\n  for (i = 0; i < num_words; i++) {\n    int slen = strcspn(s, delim);  // add \"\\n\" ?\n    safe_calloc(words[i], slen+1, char);  // +1 to null-terminate the string\n    strncpy(words[i], s, slen);\n    s = sword(s, delim, 1);\n  }\n\n  *k = num_words;\n  return words;\n}\n\n\n// compare the first word of s1 with the first word of s2\nint wordcmp(const char *s1, const char *s2, const char *delim)\n{\n  int n1 = strcspn(s1, delim);\n  int n2 = strcspn(s2, delim);\n\n  if (n1 < n2)\n    return -1;\n  else if (n1 > n2)\n    return 1;\n\n  return strncmp(s1, s2, n1);\n}\n\n\n// replace a word in a string array\nvoid replace_word(char **words, int num_words, const char *from, const char *to)\n{\n  int i;\n  for (i = 0; i < num_words; i++) {\n    if (!strcmp(words[i], from)) {\n      safe_realloc(words[i], strlen(to)+1, char);\n      strcpy(words[i], to);\n    }\n  }\n}\n\n\n// computes the log factorial of x\ndouble lfact(int x)\n{\n  static double logf[MAXFACT];\n  static int first = 1;\n  int i;\n\n  if (first) {\n    first = 0;\n    logf[0] = 0;\n    for (i = 1; i < MAXFACT; i++)\n      logf[i] = log(i) + logf[i-1];\n  }\n\n  return logf[x];\n}\n\n\n// computes the factorial of x\ndouble fact(int x)\n{\n  return exp(lfact(x));\n}\n\n\n// computes the surface area of a unit sphere with dimension d\ndouble surface_area_sphere(int d)\n{\n  switch(d) {\n  case 0:\n    return 2;\n  case 1:\n    return 2*M_PI;\n  case 2:\n    return 4*M_PI;\n  case 3:\n    return 2*M_PI*M_PI;\n  }\n\n  return (2*M_PI/((double)d-1))*surface_area_sphere(d-2);\n}\n\n\n// logical not of a binary array\nvoid vnot(int y[], int x[], int n)\n{\n  int i;\n  for (i = 0; i < n; i++)\n    y[i] = !x[i];\n}\n\n\n// count the non-zero elements of x\nint count(int x[], int n)\n{\n  int i;\n  int cnt = 0;\n  for (i = 0; i < n; i++)\n    if (x[i] != 0)\n      cnt++;\n\n  return cnt;\n}\n\n\n// returns a dense array of the indices of x's non-zero elements\nint find(int *k, int x[], int n)\n{\n  int i;\n  int cnt = 0;\n  for (i = 0; i < n; i++)\n    if (x[i] != 0)\n      k[cnt++] = i;\n  return cnt;\n}\n\n\n// returns a sparse array of the indices of x's non-zero elements\nint findinv(int *k, int x[], int n)\n{\n  int i;\n  int cnt = 0;\n  for (i = 0; i < n; i++)\n    if (x[i] != 0)\n      k[i] = cnt++;\n  return cnt;\n}\n\n\n// computes a dense array of the indices of x==a\nint findeq(int *k, int x[], int a, int n)\n{\n  int i;\n  int cnt = 0;\n  if (k != NULL) {\n    for (i = 0; i < n; i++) {\n      if (x[i] == a)\n\tk[cnt++] = i;\n    }\n  }\n  else\n    for (i = 0; i < n; i++)\n      if (x[i] == a)\n\tcnt++;\n  return cnt;\n}\n\n\n// computes the sum of x's elements\ndouble sum(double x[], int n)\n{\n  int i;\n  double y = 0;\n  for (i = 0; i < n; i++)\n    y += x[i];\n  return y;\n}\n\n// computes the product of x's elements\ndouble prod(double x[], int n)\n{\n  int i;\n  double y = 1;\n  for (i = 0; i < n; i++)\n    y *= x[i];\n  return y;\n}\n\n\n// computes the max of x\ndouble arr_max(double x[], int n)\n{\n  int i;\n\n  double y = x[0];\n  for (i = 1; i < n; i++)\n    if (x[i] > y)\n      y = x[i];\n\n  return y;\n}\n\n// computes the max of x\nint arr_max_i(int x[], int n)\n{\n  int i;\n\n  int y = x[0];\n  for (i = 1; i < n; i++)\n    if (x[i] > y)\n      y = x[i];\n\n  return y;\n}\n\n// computes the masked max of x\ndouble arr_max_masked(double x[], int mask[], int n)\n{\n  int i;\n\n  for (i = 0; i < n; i++)\n    if (mask[i])\n      break;\n  if (i==n)\n    return NAN;\n\n  double y = x[i++];\n  for (; i < n; i++)\n    if (mask[i] && (x[i] > y))\n      y = x[i];\n\n  return y;\n}\n\n// computes the masked max of x\nfloat arr_maxf_masked(float x[], int mask[], int n)\n{\n  int i;\n\n  for (i = 0; i < n; i++)\n    if (mask[i])\n      break;\n  if (i==n)\n    return NAN;\n\n  float y = x[i++];\n  for (; i < n; i++)\n    if (mask[i] && (x[i] > y))\n      y = x[i];\n\n  return y;\n}\n\n// computes the min of x\ndouble arr_min(double x[], int n)\n{\n  int i;\n\n  double y = x[0];\n  for (i = 1; i < n; i++)\n    if (x[i] < y)\n      y = x[i];\n\n  return y;\n}\n\n// computes the min of x\nint arr_min_i(int x[], int n)\n{\n  int i;\n\n  int y = x[0];\n  for (i = 1; i < n; i++)\n    if (x[i] < y)\n      y = x[i];\n\n  return y;\n}\n\n// computes the masked min of x\ndouble arr_min_masked(double x[], int mask[], int n)\n{\n  int i;\n\n  for (i = 0; i < n; i++)\n    if (mask[i] != 0)\n      break;\n  if (i==n)\n    return NAN;\n\n  double y = x[i++];\n  for (; i < n; i++)\n    if (mask[i] && (x[i] < y))\n      y = x[i];\n\n  return y;\n}\n\n// computes the masked min of x\nfloat arr_minf_masked(float x[], int mask[], int n)\n{\n  int i;\n\n  for (i = 0; i < n; i++)\n    if (mask[i])\n      break;\n  if (i==n)\n    return NAN;\n\n  float y = x[i++];\n  for (; i < n; i++)\n    if (mask[i] && (x[i] < y))\n      y = x[i];\n\n  return y;\n}\n\n// returns the index of the max of x\nint find_max(double x[], int n)\n{\n  int i;\n  int idx = 0;\n  for (i = 1; i < n; i++)\n    if (x[i] > x[idx])\n      idx = i;\n  return idx;\n}\n\n// returns the index of the min of x\nint find_min(double x[], int n)\n{\n  int i;\n  int idx = 0;\n  for (i = 1; i < n; i++)\n    if (x[i] < x[idx])\n      idx = i;\n  return idx;\n}\n\n// returns the index of the max of x\nint find_imax(int x[], int n)\n{\n  int i;\n  int idx = 0;\n  for (i = 1; i < n; i++)\n    if (x[i] > x[idx])\n      idx = i;\n  return idx;\n}\n\n// returns the index of the min of x\nint find_imin(int x[], int n)\n{\n  int i;\n  int idx = 0;\n  for (i = 1; i < n; i++)\n    if (x[i] < x[idx])\n      idx = i;\n  return idx;\n}\n\n// computes the sum of x's elements\nint isum(int x[], int n)\n{\n  int i;\n  int y = 0;\n  for (i = 0; i < n; i++)\n    y += x[i];\n  return y;\n}\n\n// computes the max of x\nint imax(int x[], int n)\n{\n  int i;\n\n  int y = x[0];\n  for (i = 1; i < n; i++)\n    if (x[i] > y)\n      y = x[i];\n\n  return y;\n}\n\n\n// computes the min of x\nint imin(int x[], int n)\n{\n  int i;\n\n  int y = x[0];\n  for (i = 1; i < n; i++)\n    if (x[i] < y)\n      y = x[i];\n\n  return y;\n}\n\n\n// computes the norm of x\ndouble norm(double x[], int n)\n{\n  double d = 0.0;\n  int i;\n\n  for (i = 0; i < n; i++)\n    d += x[i]*x[i];\n\n  return sqrt(d);\n}\n\n// computes the norm of x-y\ndouble dist(double x[], double y[], int n)\n{\n  double d = 0.0;\n  int i;\n\n  for (i = 0; i < n; i++)\n    d += (x[i]-y[i])*(x[i]-y[i]);\n\n  return sqrt(d);\n}\n\n\n// computes the norm^2 of x-y\ndouble dist2(double x[], double y[], int n)\n{\n  double d = 0.0;\n  int i;\n\n  for (i = 0; i < n; i++)\n    d += (x[i]-y[i])*(x[i]-y[i]);\n\n  return d;\n}\n\n\n// computes the dot product of z and y\ndouble dot(double x[], double y[], int n)\n{\n  int i;\n  double z = 0.0;\n  for (i = 0; i < n; i++)\n    z += x[i]*y[i];\n  return z;\n}\n\n\n//computes the cross product of x and y\nvoid cross(double z[3], double x[3], double y[3])\n{\n  z[0] = x[1]*y[2] - x[2]*y[1];\n  z[1] = x[2]*y[0] - x[0]*y[2];\n  z[2] = x[0]*y[1] - x[1]*y[0];\n}\n\nvoid cross4d(double w[4], double x[4], double y[4], double z[4]) {\n  double **V = new_matrix2(4, 3);\n  int i;\n  for (i = 0; i < 4; ++i) {\n    V[i][0] = x[i];\n    V[i][1] = y[1];\n    V[i][2] = z[i];\n  }\n  double **W = new_matrix2(3, 3);\n  int indices[4][3] = {{2, 3, 4}, {1, 3, 4}, {1, 2, 4}, {1, 2, 3}};\n  int cut_axis = 0;\n  double dmax = 0;\n  for (i = 0; i < 4; ++i) {\n    reorder_rows(W, V, indices[i], 3, 3);\n    double tmp = fabs(det(W, 3));\n    if (dmax < tmp) {\n      dmax = tmp;\n      cut_axis = i;\n    }    \n  }\n  double *c0 = V[cut_axis];\n  int uncut_axis[3];\n  for (i = 0; i < cut_axis; ++i) {\n    uncut_axis[i] = i;\n    w[i] = 0;\n  }\n  for (i = cut_axis + 1; i < 4; ++i) {\n    uncut_axis[i-1] = i;\n    w[i] = 0;\n  }\n  w[cut_axis] = 1;\n  reorder_rows(W, V, uncut_axis, 3, 3);\n  inv(W, W, 3);\n  mult(c0, c0, -1, 3);\n  \n  double tmp[3];\n  matrix_vec_mult(tmp, W, c0, 3, 3); \n  for (i = 0; i < 3; ++i) {\n    w[uncut_axis[i]] = tmp[i];\n  }\n  free_matrix2(V);\n  free_matrix2(W);\n}\n\n// adds two vectors, z = x+y\nvoid add(double z[], double x[], double y[], int n)\n{\n  int i;\n  for (i = 0; i < n; i++)\n    z[i] = x[i] + y[i];\n}\n\n\n// subtracts two vectors, z = x-y\nvoid sub(double z[], double x[], double y[], int n)\n{\n  int i;\n  for (i = 0; i < n; i++)\n    z[i] = x[i] - y[i];\n}\n\n\n// multiplies a vector by a scalar, y = c*x\nvoid mult(double y[], double x[], double c, int n)\n{\n  int i;\n  for (i = 0; i < n; i++)\n    y[i] = c*x[i];\n}\n\n// computes the cumulative sum of x\nvoid cumsum(double y[], double x[], int n)\n{\n  int i;\n  double c = 0;\n  for (i = 0; i < n; i++) {\n    c += x[i];\n    y[i] = c;\n  }\n}\n\n// takes absolute value element-wise\nvoid vec_func(double y[], double x[], double n, double (*f)(double)) {\n  int i;\n  for (i = 0; i < n; ++i) {\n    y[i] = (*f)(x[i]);\n  }\n}\n\n// sets y = x/norm(x)\nvoid normalize(double y[], double x[], int n)\n{\n  double d = norm(x, n);\n  int i;\n  for (i = 0; i < n; i++)\n    y[i] = x[i]/d;\n}\n\n\n// sets y = x/sum(x)\nvoid normalize_pmf(double y[], double x[], int n)\n{\n  double d = sum(x, n);\n  int i;\n  for (i = 0; i < n; i++)\n    y[i] = x[i]/d;\n}\n\n\n// multiplies two vectors, z = x.*y\nvoid vmult(double z[], double x[], double y[], int n)\n{\n  int i;\n  for (i = 0; i < n; i++)\n    z[i] = x[i]*y[i];\n}\n\n\n// averages two vectors, z = (x+y)/2\nvoid avg(double z[], double x[], double y[], int n)\n{\n  add(z, x, y, n);\n  mult(z, z, .5, n);\n}\n\n\n// averages two vectors, z = w*x+(1-w)*y\nvoid wavg(double z[], double x[], double y[], double w, int n)\n{\n  int i;\n  for (i = 0; i < n; i++)\n    z[i] = w*x[i] + (1-w)*y[i];\n}\n\n\n// averages three vectors, y = (x1+x2+x3)/3\nvoid avg3(double y[], double x1[], double x2[], double x3[], int n)\n{\n  add(y, x1, x2, n);\n  add(y, y, x3, n);\n  mult(y, y, 1/3.0, n);\n}\n\n\n// calculate the projection of x onto y\nvoid proj(double z[], double x[], double y[], int n)\n{\n  double u[n];  // y's unit vector\n  double d = norm(y, n);\n  mult(u, y, 1/d, n);\n  mult(z, u, dot(x,u,n), n);\n}\n\n\n// binary search to find i s.t. A[i-1] <= x < A[i]\nint binary_search(double x, double *A, int n)\n{\n  int i0 = 0;\n  int i1 = n-1;\n  int i;\n\n  while (i0 <= i1) {\n    i = (i0 + i1) / 2;\n    if (x > A[i])\n      i0 = i + 1;\n    else if (i > 0 && x < A[i-1])\n      i1 = i-1;\n    else\n      break;\n  }\n\n  if (i0 <= i1)\n    return i;\n\n  return n-1;\n}\n\nvoid plane_from_3points(double *coeffs, double *p0, double *p1, double *p2)\n{\n    double diff1[3], diff2[3];\n    sub(diff1, p1, p0, 3);\n    sub(diff2, p2, p0, 3);\n    double normal[3];\n    cross(normal, diff1, diff2);\n    normalize(normal, normal, 3);\n    double flip = normal[2] > 0.0 ? -1.0 : 1.0; // flip normal towards camera\n    \n    coeffs[0] = normal[0] * flip;\n    coeffs[1] = normal[1] * flip;\n    coeffs[2] = normal[2] * flip;\n    coeffs[3] = -dot(normal, p0, 3) * flip;\n}\n\n// quaternion multiplication:  z = x*y\nvoid quaternion_mult(double z[4], double x[4], double y[4])\n{\n  double a = x[0];\n  double b = x[1];\n  double c = x[2];\n  double d = x[3];\n  double y0 = y[0];\n  double y1 = y[1];\n  double y2 = y[2];\n  double y3 = y[3];\n\n  z[0] = a*y0 - b*y1 - c*y2 - d*y3;\n  z[1] = b*y0 + a*y1 - d*y2 + c*y3;\n  z[2] = c*y0 + d*y1 + a*y2 - b*y3;\n  z[3] = d*y0 - c*y1 + b*y2 + a*y3;\n}\n\n\n// invert a quaternion\nvoid quaternion_inverse(double q_inv[4], double q[4])\n{\n  q_inv[0] = q[0];\n  q_inv[1] = -q[1];\n  q_inv[2] = -q[2];\n  q_inv[3] = -q[3];\n}\n\n\n// quaternion exponentiation (q2 = q^a)\nvoid quaternion_pow(double q2[4], double q[4], double a)\n{\n  double u[3];  // axis of rotation\n  normalize(u, &q[1], 3);\n  double w = MIN(MAX(q[0], -1.0), 1.0);  // for numerical stability\n  double theta2 = acos(w);  // theta / 2.0\n  double s = sin(a*theta2);\n  q2[0] = cos(a*theta2);\n  mult(&q2[1], u, s, 3);\n}\n\n\n// quaternion interpolation (slerp)\nvoid quaternion_interpolation(double q[4], double q0[4], double q1[4], double t)\n{\n  double q0_inv[4], q01[4];\n  quaternion_inverse(q0_inv, q0);\n  quaternion_mult(q01, q1, q0_inv);\n  quaternion_pow(q01, q01, t);\n  quaternion_mult(q, q01, q0);\n}\n\n\n// convert a rotation matrix to a unit quaternion\nvoid rotation_matrix_to_quaternion(double *q, double **R)\n{\n  double S;\n  double tr = R[0][0] + R[1][1] + R[2][2];\n  if (tr > 0) {\n    S = sqrt(tr+1.0) * 2;  // S=4*qw\n    q[0] = 0.25 * S;\n    q[1] = (R[2][1] - R[1][2]) / S;\n    q[2] = (R[0][2] - R[2][0]) / S;\n    q[3] = (R[1][0] - R[0][1]) / S;\n  }\n  else if ((R[0][0] > R[1][1]) && (R[0][0] > R[2][2])) {\n    S = sqrt(1.0 + R[0][0] - R[1][1] - R[2][2]) * 2;  // S=4*qx \n    q[0] = (R[2][1] - R[1][2]) / S;\n    q[1] = 0.25 * S;\n    q[2] = (R[0][1] + R[1][0]) / S; \n    q[3] = (R[0][2] + R[2][0]) / S; \n  }\n  else if (R[1][1] > R[2][2]) {\n    S = sqrt(1.0 + R[1][1] - R[0][0] - R[2][2]) * 2;  // S=4*qy\n    q[0] = (R[0][2] - R[2][0]) / S;\n    q[1] = (R[0][1] + R[1][0]) / S; \n    q[2] = 0.25 * S;\n    q[3] = (R[1][2] + R[2][1]) / S; \n  }\n  else {\n    S = sqrt(1.0 + R[2][2] - R[0][0] - R[1][1]) * 2;  // S=4*qz\n    q[0] = (R[1][0] - R[0][1]) / S;\n    q[1] = (R[0][2] + R[2][0]) / S;\n    q[2] = (R[1][2] + R[2][1]) / S;\n    q[3] = 0.25 * S;\n  }\n\n  normalize(q, q, 4);\n}\n\n\n// convert a unit quaternion to a rotation matrix\nvoid quaternion_to_rotation_matrix(double **R, double *q)\n{\n  double a = q[0];\n  double b = q[1];\n  double c = q[2];\n  double d = q[3];\n\n  R[0][0] = a*a + b*b - c*c - d*d;\n  R[0][1] = 2*b*c - 2*a*d;\n  R[0][2] = 2*b*d + 2*a*c;\n  R[1][0] = 2*b*c + 2*a*d;\n  R[1][1] = a*a - b*b + c*c - d*d;\n  R[1][2] = 2*c*d - 2*a*b;\n  R[2][0] = 2*b*d - 2*a*c;\n  R[2][1] = 2*c*d + 2*a*b;\n  R[2][2] = a*a - b*b - c*c + d*d;\n}\n\nint find_first_non_zero(double *v, int n)\n{\n  int i;\n  for (i = 0; i < n; ++i) {\n    if (v[i] != 0.)\n      return i;\n  }\n  return -1;\n}\n\nint find_first_lt(double *x, double a, int n)\n{\n  int i;\n  for (i = 0; i < n; ++i)\n    if (x[i] < a)\n      break;\n  return i;\n}\n\nint find_first_gt(double *x, double a, int n)\n{\n  int i;\n  for (i = 0; i < n; ++i)\n    if (x[i] > a)\n      break;\n  return i;\n}\n\n/*\nshort *ismember(double *A, double *B, int n, int m) {\n  short *C;\n  safe_calloc(C, n, short);\n  int i, j;\n  // NOTE(sanja): this can be done in O(n log n + m) if necessary. Also, SSE2-able :)\n  for (i = 0; i < n; ++i) {\n    for (j = 0; j < m; ++j) {\n      if (double_is_equal(A[i], B[j])) {\n\tC[i] = 1;\n\tbreak;\n      }\n    }\n  }\n  return C;\n}\n\nshort *ismemberi(int *A, int *B, int n, int m) {\n  short *C;\n  safe_calloc(C, n, short);\n  int i, j;\n  // NOTE(sanja): this can be done in O(n log n + m) if necessary. Also, SSE2-able :)\n  for (i = 0; i < n; ++i) {\n    for (j = 0; j < m; ++j) {\n      if (A[i] == B[j]) {\n\tC[i] = 1;\n\tbreak;\n      }\n    }\n  }\n  return C;\n}\n*/\n\n// check if y contains x\nint ismemberi(int x, int *y, int n)\n{\n  int i;\n  for (i = 0; i < n; ++i)\n    if (x == y[i])\n      return 1;\n  return 0;\n}\n\n// reverses an array of doubles (safe for x==y)\nvoid reverse(double *y, double *x, int n)\n{\n  int i;\n  for (i = 0; i < n/2; i++) {\n    double tmp = x[i];\n    y[i] = x[n-i-1];\n    y[n-i-1] = tmp;\n  }\n}\n\n// reverses an array of ints (safe for x==y)\nvoid reversei(int *y, int *x, int n)\n{\n  int i;\n  for (i = 0; i < n/2; i++) {\n    int tmp = x[i];\n    y[i] = x[n-i-1];\n    y[n-i-1] = tmp;\n  }\n}\n\n// reorder an array of doubles (safe for x==y)\nvoid reorder(double *y, double *x, int *idx, int n)\n{\n  int i;\n  double *y2 = y;\n  if (x==y)\n    safe_calloc(y2, n, double);\n  for (i = 0; i < n; i++)\n    y2[i] = x[idx[i]];\n  if (x==y) {\n    memcpy(y, y2, n*sizeof(double));\n    free(y2);\n  }\n}\n\n// reorder an array of ints (safe for x==y)\nvoid reorderi(int *y, int *x, int *idx, int n)\n{\n  int i;\n  int *y2 = y;\n  if (x==y)\n    safe_calloc(y2, n, int);\n  for (i = 0; i < n; i++)\n    y2[i] = x[idx[i]];\n  if (x==y) {\n    memcpy(y, y2, n*sizeof(int));\n    free(y2);\n  }\n}\n\n// add an element to the front of a list\nilist_t *ilist_add(ilist_t *x, int a)\n{\n  ilist_t *head;\n  safe_malloc(head, 1, ilist_t);\n  head->x = a;\n  head->next = x;\n  head->len = (x ? 1 + x->len : 1);\n\n  return head;\n}\n\n\n// check if a list contains an element\nint ilist_contains(ilist_t *x, int a)\n{\n  if (!x)\n    return 0;\n\n  ilist_t *tmp;\n  for (tmp = x; tmp; tmp = tmp->next)\n    if (tmp->x == a)\n      return 1;\n  return 0;\n}\n\n\n// find the index of an element in a list (or -1 if not found)\nint ilist_find(ilist_t *x, int a)\n{\n  int i = 0;\n  ilist_t *tmp;\n  for (tmp = x; tmp; tmp = tmp->next) {\n    if (tmp->x == a)\n      return i;\n    i++;\n  }\n\n  return -1;\n}\n\n\n// free a list\nvoid ilist_free(ilist_t *x)\n{\n  ilist_t *tmp, *tmp2;\n  tmp = x;\n  while (tmp) {\n    tmp2 = tmp->next;\n    free(tmp);\n    tmp = tmp2;\n  }  \n}\n\n\nstatic void init_rand()\n{\n  static int first = 1;\n  if (first) {\n    first = 0;\n    int seed = time(NULL); \n    //    seed = 1371836140;\n    //int seed = 1368560954; <-- Crashes straw bowl on 3/9\n    //1368457226; <--- Shows overlap on 5/3\n    printf(\"********* seed = %d\\n\", seed);\n    srand (seed);\n  }\n}\n\n\n// returns a random int between 0 and n-1\nint irand(int n)\n{\n  init_rand();\n\n  if (n < 0)\n    printf(\"Negative n: %d\\n\", n);\n  return rand() % n;\n}\n\n\n// returns a random double in [0,1]\ndouble frand()\n{\n  init_rand();\n\n  return fabs(rand()) / (double)RAND_MAX;\n}\n\n\n// samples d integers from 0:n-1 uniformly without replacement\nvoid randperm(int *x, int n, int d)\n{\n  init_rand();\n\n  int i;\n\n  if (d > n) {\n    fprintf(stderr, \"Error: d > n in randperm()\\n\");\n    return;\n  }\n  \n  // sample a random starting point\n  int i0 = rand() % n;\n\n  // use a random prime step to cycle through x\n  static const int big_primes[100] = {996311, 163573, 481123, 187219, 963323, 103769, 786979, 826363, 874891, 168991, 442501, 318679, 810377, 471073, 914519, 251059, 321983, 220009, 211877, 875339, 605603, 578483, 219619, 860089, 644911, 398819, 544927, 444043, 161717, 301447, 201329, 252731, 301463, 458207, 140053, 906713, 946487, 524389, 522857, 387151, 904283, 415213, 191047, 791543, 433337, 302989, 445853, 178859, 208499, 943589, 957331, 601291, 148439, 296801, 400657, 829637, 112337, 134707, 240047, 669667, 746287, 668243, 488329, 575611, 350219, 758449, 257053, 704287, 252283, 414539, 647771, 791201, 166031, 931313, 787021, 520529, 474667, 484361, 358907, 540271, 542251, 825829, 804709, 664843, 423347, 820367, 562577, 398347, 940349, 880603, 578267, 644783, 611833, 273001, 354329, 506101, 292837, 851017, 262103, 288989};\n\n  int step = big_primes[rand() % 100];\n\n  int idx = i0;\n  for (i = 0; i < d; i++) {\n    x[i] = idx;\n    idx = (idx + step) % n;\n  }\n\n  /*\n  if (d > 2*sqrt(n*log(n))) {\n    double r[n];\n    int idx[n];\n    for (i = 0; i < n; i++)\n      r[i] = frand();\n    sort_indices(r, idx, n);\n    memcpy(x, idx, d*sizeof(int));\n  }\n  else {\n    for (i = 0; i < d; i++) {\n      while (1) {\n\tx[i] = rand() % n;\n\tfor (j = 0; j < i; j++)\n\t  if (x[j] == x[i])\n\t    break;\n\tif (j == i)  // x[i] is unique\n\t  break;\n      }\n    }\n  }\n  */\n}\n\n// approximation to the inverse error function\ndouble erfinv(double x)\n{\n  if (x < 0)\n    return -erfinv(-x);\n\n  double a = .147;\n\n  double y1 = (2/(M_PI*a) + log(1-x*x)/2.0);\n  double y2 = sqrt(y1*y1 - (1/a)*log(1-x*x));\n  double y3 = sqrt(y2 - y1);\n  \n  return y3;\n}\n\n\n// generate a random sample from a normal distribution\ndouble normrand(double mu, double sigma)\n{\n  double u = frand();\n  \n  return mu + sigma*sqrt(2.0)*erfinv(2*u-1);\n}\n\n\n// compute the pdf of a normal random variable\ndouble normpdf(double x, double mu, double sigma)\n{\n  double dx = x - mu;\n\n  return exp(-dx*dx / (2*sigma*sigma)) / (sqrt(2*M_PI) * sigma);\n}\n\n\n// samples from the probability mass function w with n elements\nint pmfrand(double *w, int n) {\n\n  int i;\n  double r = frand();\n  double wtot = 0;\n  for (i = 0; i < n; i++) {\n    wtot += w[i];\n    if (wtot >= r)\n      return i;\n  }\n\n  return 0;\n}\n\n// samples from the cumulative mass function w with n elements (much faster than pmfrand)\nint cmfrand(double *w, int n)\n{\n  double r = frand();\n  return binary_search(r, w, n);\n}\n\n// sample from a multivariate normal\nvoid mvnrand(double *x, double *mu, double **S, int d)\n{\n  double z[d], **V = new_matrix2(d,d);\n  eigen_symm(z,V,S,d);\n  int i;\n  for (i = 0; i < d; i++)\n    z[i] = sqrt(z[i]);\n\n  mvnrand_pcs(x,mu,z,V,d);\n\n  free_matrix2(V);\n}\n\ndouble mvnpdf(double *x, double *mu, double **S, int d)\n{\n  double **S_inv = new_matrix2(d,d);\n  inv(S_inv, S, d);\n  \n  double dx[d];\n  sub(dx, x, mu, d);\n  double S_inv_dx[d];\n  matrix_vec_mult(S_inv_dx, S_inv, dx, d, d);\n  double dm = dot(dx, S_inv_dx, d);\n\n  double p = exp(-.5*dm) / sqrt(pow(2*M_PI, d) * det(S,d));\n\n  free_matrix2(S_inv);\n\n  return p;\n\n}\n\n/* compute a multivariate normal pdf\ndouble mvnpdf(double *x, double *mu, double **S, int d)\n{\n  double z[d], **V = new_matrix2(d,d);\n  eigen_symm(z,V,S,d);\n  int i;\n  for (i = 0; i < d; i++)\n    z[i] = sqrt(z[i]);\n\n  printf(\"S = [%f %f %f; %f %f %f; %f %f %f]\\n\", S[0][0], S[0][1], S[0][2], S[1][0], S[1][1], S[1][2], S[2][0], S[2][1], S[2][2]); //dbug\n  printf(\"z = [%f, %f, %f]\\n\", z[0], z[1], z[2]); //dbug\n\n  double p = mvnpdf_pcs(x,mu,z,V,d);\n\n  free_matrix2(V);\n  return p;\n}\n*/\n\n// sample from a multivariate normal in principal components form\nvoid mvnrand_pcs(double *x, double *mu, double *z, double **V, int d)\n{\n  int i;\n  double s, v[d];\n\n  memcpy(x, mu, d*sizeof(double));\n\n  for (i = 0; i < d; i++) {\n    s = normrand(0, z[i]);\n    mult(v, V[i], s, d);  // v = s*V[i]\n    add(x, x, v, d);      // x += v\n  }\n}\n\n\n// compute a multivariate normal pdf in principal components form\ndouble mvnpdf_pcs(double *x, double *mu, double *z, double **V, int d)\n{\n  int i;\n  double xv, dx[d];\n  sub(dx, x, mu, d);  // dx = x - mu\n\n  double logp = -(d/2)*log(2*M_PI) - log(prod(z,d));\n  for (i = 0; i < d; i++) {\n    xv = dot(dx, V[i], d) / z[i];\n    logp -= 0.5*xv*xv;\n  }\n\n  return exp(logp);\n}\n\n\n// sample from an angular central gaussian in principal components form\nvoid acgrand_pcs(double *x, double *z, double **V, int d)\n{\n  int i;\n  double mu[d];\n  for (i = 0; i < d; i++)\n    mu[i] = 0;\n\n  mvnrand_pcs(x, mu, z, V, d);\n  normalize(x, x, d);\n}\n\n\n// compute an angular central gaussian pdf in principal components form\ndouble acgpdf_pcs(double *x, double *z, double **V, int d)\n{\n  int i;\n  double p = 1 / (prod(z,d) * surface_area_sphere(d-1));\n  double xv, md = 0;  // mahalanobis distance\n  for (i = 0; i < d; i++) {\n    xv = dot(x, V[i], d) / z[i];\n    md += xv*xv;\n  }\n  p *= pow(md, -d/2);\n  \n  return p;\n}\n\n\n// create a new n-by-m-by-p 3d matrix of doubles\ndouble ***new_matrix3(int n, int m, int p)\n{\n  if (n*m*p == 0) return NULL;\n  int i;\n  double **X2 = new_matrix2(n*m, p);\n  double ***X;\n  safe_malloc(X, n, double**);\n  for (i = 0; i < n; i++)\n    X[i] = X2 + m*i;\n\n  return X;\n}\n\n// free a 3d matrix\nvoid free_matrix3(double ***X)\n{\n  free_matrix2(X[0]);\n  free(X);\n}\n\n// create a new n-by-m-by-p 3d matrix of floats\nfloat ***new_matrix3f(int n, int m, int p)\n{\n  if (n*m*p == 0) return NULL;\n  int i;\n  float **X2 = new_matrix2f(n*m, p);\n  float ***X;\n  safe_malloc(X, n, float**);\n  for (i = 0; i < n; i++)\n    X[i] = X2 + m*i;\n\n  return X;\n}\n\n// free a 3d matrix\nvoid free_matrix3f(float ***X)\n{\n  free_matrix2f(X[0]);\n  free(X);\n}\n\n// copy a 3d matrix of doubles: Y = X\nvoid matrix3_copy(double ***Y, double ***X, int n, int m, int p)\n{\n  memcpy(Y[0][0], X[0][0], n*m*p*sizeof(double));\n}\n\n// clone a 3d matrix of doubles: Y = new(X)\ndouble ***matrix3_clone(double ***X, int n, int m, int p)\n{\n  double ***Y = new_matrix3(n,m,p);\n  matrix3_copy(Y, X, n, m, p);\n\n  return Y;\n}\n\n// create a new n-by-m 2d matrix of doubles\ndouble **new_matrix2(int n, int m)\n{\n  if (n*m == 0) return NULL;\n  int i;\n  double *raw, **X;\n  safe_calloc(raw, n*m, double);\n  safe_malloc(X, n, double*);\n\n  for (i = 0; i < n; i++)\n    X[i] = raw + m*i;\n\n  return X;\n}\n\nvoid add_rows_matrix2(double ***X, int n, int m, int new_n)\n{\n  int i;\n  double *raw = (*X)[0];\n  safe_realloc(raw, m * new_n, double);\n  safe_realloc(*X, new_n, double*);\n  for (i = 0; i < new_n; i++)\n    (*X)[i] = raw + m*i;\n}\n\nvoid add_rows_matrix2i(int ***X, int n, int m, int new_n)\n{\n  int i;\n  int *raw = (*X)[0];\n  safe_realloc(raw, m * new_n, int);\n  safe_realloc(*X, new_n, int*);\n  for (i = 0; i < new_n; i++)\n    (*X)[i] = raw + m*i;\n}\n\n\n/*\nvoid resize_matrix2(double ***X, int n, int m, int n2, int m2)\n{\n  if (m2 == m)\n    add_rows_matrix2(X, n, m, n2);\n  else {\n    \n  }\n}\n*/\n\n// create a new n-by-m 2d matrix of floats\nfloat **new_matrix2f(int n, int m)\n{\n  if (n*m == 0) return NULL;\n  int i;\n  float *raw, **X;\n  safe_calloc(raw, n*m, float);\n  safe_malloc(X, n, float*);\n\n  for (i = 0; i < n; i++)\n    X[i] = raw + m*i;\n\n  return X;\n}\n\n// create a new n-by-m 2d matrix of ints\nint **new_matrix2i(int n, int m)\n{\n  if (n*m == 0) return NULL;\n  int i, *raw, **X;\n  safe_calloc(raw, n*m, int);\n  safe_malloc(X, n, int*);\n\n  for (i = 0; i < n; i++)\n    X[i] = raw + m*i;\n\n  return X;\n}\n\n// create a new n-by-m 2d matrix of chars\nchar **new_matrix2c(int n, int m)\n{\n  if (n*m == 0) return NULL;\n  int i;\n  char *raw, **X;\n  safe_calloc(raw, n*m, char);\n  safe_malloc(X, n, char*);\n\n  for (i = 0; i < n; i++)\n    X[i] = raw + m*i;\n\n  return X;\n}\n\n// create a new n-by-m 2d matrix of doubles\ndouble **new_matrix2_data(int n, int m, double *data)\n{\n  double **X = new_matrix2(n,m);\n  memcpy(X[0], data, n*m*sizeof(double));\n  return X;\n}\n\n// create a new n-by-m 2d matrix of floats\nfloat **new_matrix2f_data(int n, int m, float *data)\n{\n  float **X = new_matrix2f(n,m);\n  memcpy(X[0], data, n*m*sizeof(float));\n  return X;\n}\n\n// create a new n-by-m 2d matrix of ints\nint **new_matrix2i_data(int n, int m, int *data)\n{\n  int **X = new_matrix2i(n,m);\n  memcpy(X[0], data, n*m*sizeof(int));\n  return X;\n}\n\n// create a new n-by-m 2d matrix of chars\nchar **new_matrix2c_data(int n, int m, char *data)\n{\n  char **X = new_matrix2c(n,m);\n  memcpy(X[0], data, n*m*sizeof(char));\n  return X;\n}\n\n/*\ndouble **add_matrix_row(double **X, int n, int m)\n{\n  //printf(\"DANGER! Reallocating matrix rows is not tested yet!\\n\");\n  double *raw = X[0];\n  safe_realloc(raw, (n + 1) * m, double);\n  safe_realloc(X, n+1, double*);\n  X[n] = raw + m * n;\n\n  return X;\n}\n*/\n\ndouble **new_identity_matrix2(int n) {\n  double **mat = new_matrix2(n, n);\n  int i;\n  for (i = 0; i < n; ++i)\n    mat[i][i] = 1;\n  return mat;\n}\n\nint **new_identity_matrix2i(int n) {\n  int **mat = new_matrix2i(n, n);\n  int i;\n  for (i = 0; i < n; ++i)\n    mat[i][i] = 1;\n  return mat;\n}\n\ndouble **new_diag_matrix2(double *diag, int n) {\n  double **mat = new_matrix2(n, n);\n  int i;\n  for (i = 0; i < n; ++i) {\n    mat[i][i] = diag[i];\n  }\n  return mat;\n}\n\nint **new_diag_matrix2i(int *diag, int n) {\n  int **mat = new_matrix2i(n, n);\n  int i;\n  for (i = 0; i < n; ++i) {\n    mat[i][i] = diag[i];\n  }\n  return mat;\n}\n\n// free a 2d matrix of doubles\nvoid free_matrix2(double **X)\n{\n  if (X == NULL) return;\n  free(X[0]);\n  free(X);\n}\n\n// free a 2d matrix of floats\nvoid free_matrix2f(float **X)\n{\n  if (X == NULL) return;\n  free(X[0]);\n  free(X);\n}\n\n// free a 2d matrix of ints\nvoid free_matrix2i(int **X)\n{\n  if (X == NULL) return;\n  free(X[0]);\n  free(X);\n}\n\n// free a 2d matrix of chars\nvoid free_matrix2c(char **X)\n{\n  if (X == NULL) return;\n  free(X[0]);\n  free(X);\n}\n\n/*\n * Write a matrix in the following format.\n *\n * <nrows> <ncols>\n * <row 1>\n * <row 2>\n * ...\n */\nvoid save_matrix(const char *fout, double **X, int n, int m)\n{\n  //fprintf(stderr, \"saving matrix to %s\\n\", fout);\n\n  FILE *f = fopen(fout, \"w\");\n  int i, j;\n\n  fprintf(f, \"%d %d\\n\", n, m);\n  for (i = 0; i < n; i++) {\n    for (j = 0; j < m; j++)\n      fprintf(f, \"%f \", X[i][j]);\n    fprintf(f, \"\\n\");\n  }\n\n  fclose(f);\n}\n\nvoid save_matrixi(const char *fout, int **X, int n, int m)\n{\n  //fprintf(stderr, \"saving matrix to %s\\n\", fout);\n\n  FILE *f = fopen(fout, \"w\");\n  int i, j;\n\n  fprintf(f, \"%d %d\\n\", n, m);\n  for (i = 0; i < n; i++) {\n    for (j = 0; j < m; j++)\n      fprintf(f, \"%d \", X[i][j]);\n    fprintf(f, \"\\n\");\n  }\n\n  fclose(f);\n}\n\n/*\n * Write a 3d matrix in the following format.\n *\n * <ntabs> <nrows> <ncols>\n * <tab 1 row 1>\n * <tab 1 row 2>\n * ...\n * <tab 2 row 1>\n * <tab 2 row 2>\n * ...\n */\nvoid save_matrix3(const char *fout, double ***X, int n, int m, int p)\n{\n  //fprintf(stderr, \"saving matrix3 to %s\\n\", fout);\n\n  FILE *f = fopen(fout, \"w\");\n  int i, j, k;\n\n  fprintf(f, \"%d %d %d\\n\", n, m, p);\n  for (i = 0; i < n; i++) {\n    for (j = 0; j < m; j++) {\n      for (k = 0; k < p; k++)\n\tfprintf(f, \"%f \", X[i][j][k]);\n      fprintf(f, \"\\n\");\n    }\n  }\n\n  fclose(f);\n}\n\n/*\n * Load a matrix in the following format.\n *\n * <nrows> <ncols>\n * <row 1>\n * <row 2>\n * ...\n */\ndouble **load_matrix(char *fin, int *n, int *m)\n{\n  FILE *f = fopen(fin, \"r\");\n\n  if (f == NULL) {\n    fprintf(stderr, \"Invalid filename: %s\\n\", fin);\n    return NULL;\n  }\n\n  char sbuf0[128], *s = sbuf0;\n  if (fgets(s, 128, f) == NULL || sscanf(s, \"%d %d\", n, m) < 2) {\n    fprintf(stderr, \"Corrupt matrix header in file %s\\n\", fin);\n    fclose(f);\n    return NULL;\n  }\n\n  double **X = new_matrix2(*n, *m);\n\n  const int CHARS_PER_FLOAT = 20;\n  const int buflen = CHARS_PER_FLOAT * (*m);\n  char sbuf[buflen];\n\n  int i, j;\n  for (i = 0; i < *n; i++) {\n    s = sbuf;\n    if (fgets(s, buflen, f) == NULL)\n      break;\n    for (j = 0; j < *m; j++) {\n      if (sscanf(s, \"%lf\", &X[i][j]) < 1)\n\tbreak;\n      s = sword(s, \" \\t\", 1);\n    }\n    if (j < *m)\n      break;\n  }\n  if (i < *n) {\n    fprintf(stderr, \"Corrupt matrix file '%s' at line %d, element %d\\n\", fin, i+2, j+1);\n    fclose(f);\n    free_matrix2(X);\n    return NULL;\n  }\n\n  fclose(f);\n\n  return X;\n}\n\n/*\n * Load a 3d matrix in the following format.\n *\n * <ntabs> <nrows> <ncols>\n * <tab 1 row 1>\n * <tab 1 row 2>\n * ...\n * <tab 2 row 1>\n * <tab 2 row 2>\n * ...\n */\ndouble ***load_matrix3(char *fin, int *n, int *m, int *p)\n{\n  FILE *f = fopen(fin, \"r\");\n\n  if (f == NULL) {\n    fprintf(stderr, \"Invalid filename: %s\\n\", fin);\n    return NULL;\n  }\n\n  char sbuf0[128], *s = sbuf0;\n  if (fgets(s, 128, f) == NULL || sscanf(s, \"%d %d %d\", n, m, p) < 3) {\n    fprintf(stderr, \"Corrupt matrix header in file %s\\n\", fin);\n    fclose(f);\n    return NULL;\n  }\n\n  double ***X = new_matrix3(*n, *m, *p);\n\n  const int CHARS_PER_FLOAT = 20;\n  const int buflen = CHARS_PER_FLOAT * (*p);\n  char sbuf[buflen];\n\n  int i, j, k;\n  for (i = 0; i < *n; i++) {\n    for (j = 0; j < *m; j++) {\n      s = sbuf;\n      if (fgets(s, buflen, f) == NULL)\n\tbreak;\n      for (k = 0; k < *p; k++) {\n\tif (sscanf(s, \"%lf\", &X[i][j][k]) < 1)\n\t  break;\n\ts = sword(s, \" \\t\", 1);\n      }\n      if (k < *p)\n\tbreak;\n    }\n    if (j < *m)\n      break;\n  }\n  if (i < *n) {\n    fprintf(stderr, \"Corrupt matrix file '%s' at line %d\\n\", fin, i*(*m)+j+2);\n    fclose(f);\n    free_matrix3(X);\n    return NULL;\n  }\n\n  fclose(f);\n\n  return X;\n}\n\n\n// calculate the area of a triangle\ndouble triangle_area(double x[], double y[], double z[], int n)\n{\n  double a = dist(x, y, n);\n  double b = dist(x, z, n);\n  double c = dist(y, z, n);\n  double s = .5*(a + b + c);\n\n  return sqrt(s*(s-a)*(s-b)*(s-c));\n}\n\n\n// calculate the volume of a tetrahedron\ndouble tetrahedron_volume(double x1[], double x2[], double x3[], double x4[], int n)\n{\n  double U = dist2(x1, x2, n);\n  double V = dist2(x1, x3, n);\n  double W = dist2(x2, x3, n);\n  double u = dist2(x3, x4, n);\n  double v = dist2(x2, x4, n);\n  double w = dist2(x1, x4, n);\n\n  double a = v+w-U;\n  double b = w+u-V;\n  double c = u+v-W;\n\n  return sqrt( (4*u*v*w - u*a*a - v*b*b - w*c*c + a*b*c) ) / 12.0 ;\n}\n\n\n// calculate the volume of a tetrahedron\ninline double tetrahedron_volume_old(double x[], double y[], double z[], double w[], int n)\n{\n  // make an orthonormal basis in the xyz plane (with x at the origin)\n  double u[n], v[n], v_proj[n];\n  sub(u, y, x, n);             // u = y-x\n  sub(v, z, x, n);             // v = z-x\n  proj(v_proj, v, u, n);       // project v onto u\n  sub(v, v, v_proj, n);        // v -= v_proj\n  mult(u, u, 1/norm(u,n), n);  // normalize u\n  mult(v, v, 1/norm(v,n), n);  // normalize v\n\n  // project (w-x) onto xyz plane\n  double w2[n], wu[n], wv[n], w_proj[n];\n  sub(w2, w, x, n);            // w2 = w-x\n  proj(wu, w2, u, n);          // project w2 onto u\n  proj(wv, w2, v, n);          // project w2 onto v\n  add(w_proj, wu, wv, n);      // w_proj = wu + wv\n  sub(w2, w2, w_proj, n);      // w2 -= w_proj\n\n  double h = norm(w2, n);  // height\n  double A = triangle_area(x, y, z, n);\n\n  return h*A/3.0;\n}\n\n\n// transpose a matrix\nvoid transpose(double **Y, double **X, int n, int m)\n{\n  double **X2 = X;\n  if (Y == X)\n    X2 = matrix_clone(X,n,m);\n\n  int i, j;\n  for (i = 0; i < n; i++)\n    for (j = 0; j < m; j++)\n      Y[j][i] = X2[i][j];\n\n  if (Y == X)\n    free_matrix2(X2);\n}\n\n\n/*\nint test_matrix_copy()\n{\n  double X_data[6] = {1,2,3,4,5,6};\n  double **X = new_matrix2_data(3,2, X_data);\n\n  //double **X = new_matrix2(2,2);\n  //X[0][0] = 1;\n  //X[0][1] = 2;\n  //X[1][0] = 3;\n  //X[1][1] = 4;\n\n  \n\n  \n  // 1 2\n  // 3 4\n\n\n}\n*/\n\n// matrix copy, Y = X \nvoid matrix_copy(double **Y, double **X, int n, int m)\n{\n  memcpy(Y[0], X[0], n*m*sizeof(double));\n}\n\n\n// matrix clone, Y = new(X)\ndouble **matrix_clone(double **X, int n, int m)\n{\n  double **Y = new_matrix2(n,m);\n  matrix_copy(Y, X, n, m);\n\n  return Y;\n}\n\n\n// matrix addition, Z = X+Y\nvoid matrix_add(double **Z, double **X, double **Y, int n, int m)\n{\n  add(Z[0], X[0], Y[0], n*m);\n}\n\n// matrix subtraction, Z = X-Y\nvoid matrix_sub(double **Z, double **X, double **Y, int n, int m)\n{\n  sub(Z[0], X[0], Y[0], n*m);\n}\n\n// matrix multiplication, Z = X*Y, where X is n-by-p and Y is p-by-m\nvoid matrix_mult(double **Z, double **X, double **Y, int n, int p, int m)\n{\n  double **Z2 = (Z==X || Z==Y ? new_matrix2(n,m) : Z);\n  int i, j, k;\n  for (i = 0; i < n; i++) {     // row i\n    for (j = 0; j < m; j++) {   // column j\n      Z2[i][j] = 0;\n      for (k = 0; k < p; k++)\n\tZ2[i][j] += X[i][k]*Y[k][j];\n    }\n  }\n  if (Z==X || Z==Y) {\n    matrix_copy(Z, Z2, n, m);\n    free_matrix2(Z2);\n  }\n}\n\n\n// matrix-vector multiplication, y = A*x\nvoid matrix_vec_mult(double *y, double **A, double *x, int n, int m)\n{\n  int i;\n  if (y == x) {\n    double z[m];\n    memcpy(z, x, m*sizeof(double));\n    for (i = 0; i < n; i++)\n      y[i] = dot(A[i], z, m);\n  }\n  else\n    for (i = 0; i < n; i++)\n      y[i] = dot(A[i], x, m);\n}\n\n// vector-matrix multiplication, y = x*A\nvoid vec_matrix_mult(double *y, double *x, double **A, int n, int m)\n{\n  int i, j;\n  if (y == x) {\n    double z[n];\n    memcpy(z, x, n*sizeof(double));\n    for (j = 0; j < m; j++) {\n      y[j] = 0;\n      for (i = 0; i < n; i++)\n\ty[j] += z[i]*A[i][j];\n    }\n  }\n  else {\n    for (j = 0; j < m; j++) {\n      y[j] = 0;\n      for (i = 0; i < n; i++)\n\ty[j] += x[i]*A[i][j];\n    }\n  }\n}\n\n// matrix element-wise multiplication\nvoid matrix_elt_mult(double **Z, double **X, double **Y, int n, int m) {\n  int i, j;\n  for (i = 0; i < n; ++i) {\n    for (j = 0; j < m; ++j) {\n      Z[i][j] = X[i][j] * Y[i][j];\n    }\n  }\n}\n\nvoid matrix_pow(double **Y, double **X, int n, int m, double pw) {\n  int i, j;\n  for (i = 0; i < n; ++i)\n    for (j = 0; j < m; ++j)\n      Y[i][j] = pow(X[i][j], pw);\n}\n\nvoid matrix_sum(double y[], double **X, int n, int m) {\n  int i, j;\n  memset(y, 0, n * sizeof(double));\n  for (i = 0; i < n; ++i) {\n    for (j = 0; j < m; ++j) {\n      y[j] += X[i][j];\n    }\n  }\n}\n\n// outer product of x and y, Z = x'*y\nvoid outer_prod(double **Z, double x[], double y[], int n, int m)\n{\n  int i, j;\n  for (i = 0; i < n; i++)\n    for (j = 0; j < m; j++)\n      Z[i][j] = x[i]*y[j];\n}\n\n\n// row vector min\nvoid row_min(double *y, double **X, int n, int m)\n{\n  int i,j;\n  memcpy(y, X[0], m*sizeof(double));\n  for (i = 1; i < n; i++)\n    for (j = 0; j < m; j++)\n      if (X[i][j] < y[j])\n\ty[j] = X[i][j];\n}\n\n\n// row vector max\nvoid row_max(double *y, double **X, int n, int m)\n{\n  int i,j;\n  memcpy(y, X[0], m*sizeof(double));\n  for (i = 1; i < n; i++)\n    for (j = 0; j < m; j++)\n      if (X[i][j] > y[j])\n\ty[j] = X[i][j];\n}\n\n\n// row vector mean \n// NOTE(sanja): this is adding up columns, not rows.\nvoid mean(double *mu, double **X, int n, int m)\n{\n  memset(mu, 0, m*sizeof(double));  // mu = 0\n\n  int i, j;\n  for (i = 0; i < n; i++)\n    for (j = 0; j < m; j++)\n      mu[j] += X[i][j];\n\n  mult(mu, mu, 1/(double)n, m);\n}\n\nvoid variance(double *vars, double **X, int n, int m)\n{\n  double mu[m];\n  mean(mu, X, n, m);\n  memset(vars, 0, m*sizeof(double));\n  int i, j;\n  for (i = 0; i < n; i++) {\n    for (j = 0; j < m; j++) {\n      double dx = X[i][j] - mu[j];\n      vars[j] += dx*dx;\n    }\n  }\n  mult(vars, vars, 1/(double)n, m);\n}\n\n// compute the covariance of the rows of X, given mean mu\nvoid cov(double **S, double **X, double *mu, int n, int m)\n{\n  int i, j, k;\n\n  memset(S[0], 0, m*m*sizeof(double));\n  double dx[m];\n\n  if (m == 3) {\n    for (i = 0; i < n; i++) {\n      dx[0] = X[i][0] - mu[0];\n      dx[1] = X[i][1] - mu[1];\n      dx[2] = X[i][2] - mu[2];\n      S[0][0] += dx[0]*dx[0];\n      S[0][1] += dx[0]*dx[1];\n      S[0][2] += dx[0]*dx[2];\n      S[1][0] += dx[1]*dx[0];\n      S[1][1] += dx[1]*dx[1];\n      S[1][2] += dx[1]*dx[2];\n      S[2][0] += dx[2]*dx[0];\n      S[2][1] += dx[2]*dx[1];\n      S[2][2] += dx[2]*dx[2];\n    }\n  }\n  else {\n    for (i = 0; i < n; i++) {\n      sub(dx, X[i], mu, m);\n      for (j = 0; j < m; j++)\n\tfor (k = 0; k < m; k++)\n\t  S[j][k] += dx[j]*dx[k];\n    }\n  }\n\n  /*\n  double **dX = matrix_clone(X, n, m);\n  if (mu != NULL)\n    for (i = 0; i < n; i++)\n      sub(dX[i], X[i], mu, m);\n  double **dXt = new_matrix2(m, n);\n  transpose(dXt, dX, n, m);\n  matrix_mult(S, dXt, dX, m, n, m);\n  */\n  mult(S[0], S[0], 1/(double)n, m*m);\n\n  //free_matrix2(dX);\n  //free_matrix2(dXt);\n}\n\n\n// weighted row vector mean\nvoid wmean(double *mu, double **X, double *w, int n, int m)\n{\n  memset(mu, 0, m*sizeof(double));  // mu = 0\n\n  int i, j;\n  for (i = 0; i < n; i++)\n    for (j = 0; j < m; j++)\n      mu[j] += w[i]*X[i][j];\n\n  mult(mu, mu, 1.0/sum(w,n), m);\n}\n\n\n// compute the weighted covariance of the rows of X, given mean mu\nvoid wcov(double **S, double **X, double *w, double *mu, int n, int m)\n{\n  int i;\n\n  memset(S[0], 0, m*m*sizeof(double));\n\n  double **Si = new_matrix2(m,m);\n  for (i = 0; i < n; i++) {\n    outer_prod(Si, X[i], X[i], m, m);\n    mult(Si[0], Si[0], w[i], m*m);\n    matrix_add(S, S, Si, m, m);\n  }\n\n  mult(S[0], S[0], 1.0/sum(w,n), m*m);\n\n  if (mu != NULL) {\n    double **S_mu = new_matrix2(m,m);\n    outer_prod(S_mu, mu, mu, m, m);\n    sub(S[0], S[0], S_mu[0], m*m);\n    free_matrix2(S_mu);\n  }\n}\n\n\n// solve the equation Ax = b, where A is a square n-by-n matrix\nvoid solve(double *x, double **A, double *b, int n)\n{\n  double **A_inv = new_matrix2(n,n);\n  inv(A_inv, A, n);\n\n  int i;\n  for (i = 0; i < n; i++)\n    x[i] = dot(A_inv[i], b, n);\n\n  free_matrix2(A_inv);\n}\n\n\n// compute the determinant of the n-by-n matrix X\ndouble det(double **X, int n)\n{\n  if (n == 1)\n    return X[0][0];\n\n  else if (n == 2)\n    return X[0][0]*X[1][1] - X[0][1]*X[1][0];\n\n  else if (n == 3) {\n    double a = X[0][0];\n    double b = X[0][1];\n    double c = X[0][2];\n    double d = X[1][0];\n    double e = X[1][1];\n    double f = X[1][2];\n    double g = X[2][0];\n    double h = X[2][1];\n    double i = X[2][2];\n    return a*e*i - a*f*h + b*f*g - b*d*i + c*d*h - c*e*g;\n  }\n\n  else if (n == 4) {\n    double a00 = X[0][0];\n    double a01 = X[0][1];\n    double a02 = X[0][2];\n    double a03 = X[0][3];\n    double a10 = X[1][0];\n    double a11 = X[1][1];\n    double a12 = X[1][2];\n    double a13 = X[1][3];\n    double a20 = X[2][0];\n    double a21 = X[2][1];\n    double a22 = X[2][2];\n    double a23 = X[2][3];\n    double a30 = X[3][0];\n    double a31 = X[3][1];\n    double a32 = X[3][2];\n    double a33 = X[3][3];\n\n    return a00*a11*a22*a33 - a00*a11*a23*a32 - a00*a12*a21*a33 + a00*a12*a23*a31 + a00*a13*a21*a32\n      - a00*a13*a22*a31 - a01*a10*a22*a33 + a01*a10*a23*a32 + a01*a12*a20*a33 - a01*a12*a23*a30\n      - a01*a13*a20*a32 + a01*a13*a22*a30 + a02*a10*a21*a33 - a02*a10*a23*a31 - a02*a11*a20*a33\n      + a02*a11*a23*a30 + a02*a13*a20*a31 - a02*a13*a21*a30 - a03*a10*a21*a32 + a03*a10*a22*a31\n      + a03*a11*a20*a32 - a03*a11*a22*a30 - a03*a12*a20*a31 + a03*a12*a21*a30;\n\n  }\n\n  else {\n    fprintf(stderr, \"Error: det() not supported for > 4x4 matrices\\n\");\n    exit(1);\n  }\n\n  return 0;\n}\n\n\n// compute the inverse (Y) of the n-by-n matrix X\nvoid inv(double **Y, double **X, int n)\n{\n  double d = det(X,n);\n\n  if (n == 1)\n    Y[0][0] = 1/d;\n\n  else if (n == 2) {\n    Y[0][0] = X[1][1] / d;\n    Y[0][1] = -X[0][1] / d;\n    Y[1][0] = -X[1][0] / d;\n    Y[1][1] = X[0][0] / d;\n  }\n\n  else if (n == 3) {\n    Y[0][0] = (X[1][1]*X[2][2] - X[1][2]*X[2][1]) / d;\n    Y[0][1] = (X[0][2]*X[2][1] - X[0][1]*X[2][2]) / d;\n    Y[0][2] = (X[0][1]*X[1][2] - X[0][2]*X[1][1]) / d;\n    Y[1][0] = (X[1][2]*X[2][0] - X[1][0]*X[2][2]) / d;\n    Y[1][1] = (X[0][0]*X[2][2] - X[0][2]*X[2][0]) / d;\n    Y[1][2] = (X[0][2]*X[1][0] - X[0][0]*X[1][2]) / d;\n    Y[2][0] = (X[1][0]*X[2][1] - X[1][1]*X[2][0]) / d;\n    Y[2][1] = (X[0][1]*X[2][0] - X[0][0]*X[2][1]) / d;\n    Y[2][2] = (X[0][0]*X[1][1] - X[0][1]*X[1][0]) / d;\n  }\n\n  else if (n == 4) {\n    double a00 = X[0][0];\n    double a01 = X[0][1];\n    double a02 = X[0][2];\n    double a03 = X[0][3];\n    double a10 = X[1][0];\n    double a11 = X[1][1];\n    double a12 = X[1][2];\n    double a13 = X[1][3];\n    double a20 = X[2][0];\n    double a21 = X[2][1];\n    double a22 = X[2][2];\n    double a23 = X[2][3];\n    double a30 = X[3][0];\n    double a31 = X[3][1];\n    double a32 = X[3][2];\n    double a33 = X[3][3];\n\n    Y[0][0] = (a11*a22*a33 - a11*a23*a32 - a12*a21*a33 + a12*a23*a31 + a13*a21*a32 - a13*a22*a31) / d;\n    Y[0][1] = (a01*a23*a32 - a01*a22*a33 + a02*a21*a33 - a02*a23*a31 - a03*a21*a32 + a03*a22*a31) / d;\n    Y[0][2] = (a01*a12*a33 - a01*a13*a32 - a02*a11*a33 + a02*a13*a31 + a03*a11*a32 - a03*a12*a31) / d;\n    Y[0][3] = (a01*a13*a22 - a01*a12*a23 + a02*a11*a23 - a02*a13*a21 - a03*a11*a22 + a03*a12*a21) / d;\n    Y[1][0] = (a10*a23*a32 - a10*a22*a33 + a12*a20*a33 - a12*a23*a30 - a13*a20*a32 + a13*a22*a30) / d;\n    Y[1][1] = (a00*a22*a33 - a00*a23*a32 - a02*a20*a33 + a02*a23*a30 + a03*a20*a32 - a03*a22*a30) / d;\n    Y[1][2] = (a00*a13*a32 - a00*a12*a33 + a02*a10*a33 - a02*a13*a30 - a03*a10*a32 + a03*a12*a30) / d;\n    Y[1][3] = (a00*a12*a23 - a00*a13*a22 - a02*a10*a23 + a02*a13*a20 + a03*a10*a22 - a03*a12*a20) / d;\n    Y[2][0] = (a10*a21*a33 - a10*a23*a31 - a11*a20*a33 + a11*a23*a30 + a13*a20*a31 - a13*a21*a30) / d;\n    Y[2][1] = (a00*a23*a31 - a00*a21*a33 + a01*a20*a33 - a01*a23*a30 - a03*a20*a31 + a03*a21*a30) / d;\n    Y[2][2] = (a00*a11*a33 - a00*a13*a31 - a01*a10*a33 + a01*a13*a30 + a03*a10*a31 - a03*a11*a30) / d;\n    Y[2][3] = (a00*a13*a21 - a00*a11*a23 + a01*a10*a23 - a01*a13*a20 - a03*a10*a21 + a03*a11*a20) / d;\n    Y[3][0] = (a10*a22*a31 - a10*a21*a32 + a11*a20*a32 - a11*a22*a30 - a12*a20*a31 + a12*a21*a30) / d;\n    Y[3][1] = (a00*a21*a32 - a00*a22*a31 - a01*a20*a32 + a01*a22*a30 + a02*a20*a31 - a02*a21*a30) / d;\n    Y[3][2] = (a00*a12*a31 - a00*a11*a32 + a01*a10*a32 - a01*a12*a30 - a02*a10*a31 + a02*a11*a30) / d;\n    Y[3][3] = (a00*a11*a22 - a00*a12*a21 - a01*a10*a22 + a01*a12*a20 + a02*a10*a21 - a02*a11*a20) / d;\n  }\n\n  else {\n    fprintf(stderr, \"Error: inv() not supported for > 4x4 matrices\\n\");\n    exit(1);\n  }\n}\n\n/**\n * Solves the quadratic equation: f(x) = a*x^2 + b*x + c\n * Sets x[0] and x[1] to be the real roots of f(x), if found.\n * Returns the number of real roots found.\n */\nint solve_quadratic(double *x, double a, double b, double c)\n{\n  double s2 = b*b - 4*a*c;\n  if (s2 < 0.0)\n    return 0;\n\n  double s = sqrt(s2);\n  x[0] = .5*(-b + s)/a;\n  x[1] = .5*(-b - s)/a;\n\n  return 2;\n}\n\n/**\n * Solves the cubic equation: f(x) = a*x^3 + b*x^2 + c*x + d\n * Sets x[0], x[1], and x[2] to be the real roots of f(x), if found.\n * Returns the number of real roots found.\n *\nint solve_cubic(double *x, double a, double b, double c, double d)\n{\n  double p = -b/(3.0*a);\n  double q = p*p*p + (b*c - 3.0*a*d)/(6*a*a);\n  double r = c/(3.0*a);\n    \n}\n*/\n\n\n/**\n * Compute the eigenvalues z and eigenvectors V of a real symmetric n-by-n matrix X\n * The eigenvalues, z, will be sorted from smallest to largest in magnitude, and the\n * eigenvectors will be stored in the rows of V.\n * @param X (input) Symmetric n-by-n matrix\n * @param n (input) Dimensionality of X\n * @param z (output) Eigenvalues of X, from smallest to largest in magnitude\n * @param V (output) Eigenvectors of X, in the rows\n */\n\n/*\nvoid eigen_symm(double z[], double **V, double **X, int n)\n{\n  double **Vt = matrix_clone(X,n,n);\n  double z2[n];\n  int i, j;\n\n  //TODO: replace this with solve_cubic() for n < 4\n\n  int info = LAPACKE_dsyevd(LAPACK_COL_MAJOR, 'V', 'U', n, Vt[0], n, z2);\n  if (info)\n    fprintf(stderr, \"Error: eigen_symm failed to converge!\\n\");\n\n  // sort eigenvalues\n  double tolerance = 1e-10;\n  int idx[n];\n  sort_indices(z2, idx, n);\n  if (z2[idx[0]] < -tolerance)  // negative eigenvalues --> sort in reverse order\n    reversei(idx, idx, n);\n  for (i = 0; i < n; i++)\n    z[i] = z2[idx[i]];\n  for (i = 0; i < n; i++)\n    for (j = 0; j < n; j++)\n      V[i][j] = Vt[j][idx[i]];\n\n  //cleanup\n  free_matrix2(Vt);\n}\n*/\n\n\nvoid eigen_symm_2d(double z[], double **V, double **X)\n{\n  double a = X[0][0];\n  double b = X[0][1];\n  double c = X[1][1];\n\n  const double epsilon = 1e-16;\n\n  if (b*b < epsilon * fabs(a*c)) {\n    if (fabs(a) < fabs(c)) {\n      z[0] = a;\n      z[1] = c;\n      V[0][0] = V[1][1] = 1.0;\n      V[0][1] = V[1][0] = 0.0;\n    }\n    else {\n      z[0] = c;\n      z[1] = a;\n      V[0][0] = V[1][1] = 0.0;\n      V[0][1] = V[1][0] = 1.0;\n    }\n    return;\n  }\n\n  double s = sqrt((a+c)*(a+c) + 4.*(b*b-a*c));\n  double z1 = (a+c+s)/2.;\n  double z2 = (a+c-s)/2.;\n  if (fabs(z1) < fabs(z2)) {\n    z[0] = z1;\n    z[1] = z2;\n  }\n  else {\n    z[1] = z1;\n    z[0] = z2;\n  }\n\n  double d0 = hypot(b, z[0]-a);\n  double d1 = hypot(b, z[1]-a);\n  V[0][0] = b/d0;\n  V[0][1] = (z[0]-a)/d0;\n  V[1][0] = b/d1;\n  V[1][1] = (z[1]-a)/d1;\n}\n\n\nvoid eigen_symm(double z[], double **V, double **X, int n)\n{\n  if (n == 2) {\n    eigen_symm_2d(z,V,X);\n    return;\n  }\n\n  // naive Jacobi method\n  int i, j;\n  double tolerance = 1e-10;\n  double **A = matrix_clone(X,n,n);\n  double **B = new_matrix2(n,n);\n  double **G = new_matrix2(n,n);\n  double **Gt = new_matrix2(n,n);\n\n  int cnt = 1; //dbug\n\n  // initialize V = I\n  for (i = 0; i < n; i++) {\n    V[i][i] = 1;\n    for (j = i+1; j < n; j++)\n      V[i][j] = V[j][i] = 0;\n  }\n\n  //printf(\"break 1\\n\");  //dbug\n\n  while (1) {\n\n    //dbug\n    //printf(\"A:\\n\");\n    //print_matrix(A, n, n);\n    //printf(\"\\n\");\n\n    // check for convergence\n    double d_off = 0, d_diag = 0;\n    for (i = 0; i < n; i++) {\n      d_diag += A[i][i]*A[i][i];\n      for (j = i+1; j < n; j++)\n\td_off = MAX(d_off, fabs(A[i][j]));\n    }\n    d_diag = sqrt(d_diag / (double)n);\n    if (d_off < MAX(tolerance * d_diag, tolerance))\n      break;\n\n    //dbug\n    if (cnt++ % 1000 == 0) {\n      printf(\"d_off = %e, d_diag = %e\\n\", d_off, d_diag);  //dbug\n      if (!isfinite(d_off) || !isfinite(d_diag))\n\treturn;\n    }\n\n    // find largest pivot\n    double pivot = 0;\n    int ip=0, jp=0;\n    for (i = 0; i < n; i++) {\n      for (j = i+1; j < n; j++) {\n\tdouble p = fabs(A[i][j]);\n\tif (p > pivot) {\n\t  pivot = p;\n\t  ip = i;\n\t  jp = j;\n\t}\n      }\n    }\n\n    //printf(\"pivot = %f, ip = %d, jp = %d\\n\", pivot, ip, jp);  //dbug\n    \n    // compute Givens cos, sin\n    double a = (A[jp][jp] - A[ip][ip]) / (2 * A[ip][jp]);\n    double t = 1 / (fabs(a) + sqrt(1 + a*a));  // tan\n    if (a < 0)\n      t = -t;\n    double c = 1 / sqrt(1 + t*t);  // cos\n    double s = t*c;  // sin\n\n    //printf(\"a = %f, t = %f, c = %f, s = %f\\n\", a, t, c, s);  //dbug\n\n    // compute Givens rotation matrix\n    for (i = 0; i < n; i++) {\n      G[i][i] = 1;\n      for (j = i+1; j < n; j++)\n\tG[i][j] = G[j][i] = 0;\n    }\n    G[ip][ip] = G[jp][jp] = c;\n    G[ip][jp] = s;\n    G[jp][ip] = -s;\n\n    //dbug\n    //printf(\"givens rotation matrix:\\n\");\n    //print_matrix(G, n, n);\n    //printf(\"\\n\");\n    \n    // compute new A\n    transpose(Gt, G, n, n);\n    matrix_mult(B, A, G, n, n, n);   // B = A*G\n    matrix_mult(A, Gt, B, n, n, n);  // A = Gt*B\n    \n    // compute new V (with eigenvectors in the rows)\n    matrix_mult(B, Gt, V, n, n, n);  // B = Gt*V\n    matrix_copy(V, B, n, n);     // V = B;\n  }\n\n  //printf(\"break 2\\n\");  //dbug\n\n  // sort eigenvalues\n  int idx[n];\n  double z2[n];\n  for (i = 0; i < n; i++)\n    z[i] = A[i][i];\n  sort_indices(z, idx, n);\n  if (z[idx[0]] < -tolerance) {  // negative eigenvalues --> sort in reverse order\n    reversei(idx, idx, n);\n    //for (i = 0; i < n/2; i++) {\n    //  int tmp = idx[i];\n    //  idx[i] = idx[n-i-1];\n    //  idx[n-i-1] = tmp;\n    //}\n  }\n  for (i = 0; i < n; i++)\n    z2[i] = z[idx[i]];\n  for (i = 0; i < n; i++)\n    z[i] = z2[i];\n  for (i = 0; i < n; i++)\n    for (j = 0; j < n; j++)\n      B[i][j] = V[idx[i]][j];\n  matrix_copy(V, B, n, n);\n\n  free_matrix2(A);\n  free_matrix2(B);\n  free_matrix2(G);\n  free_matrix2(Gt);\n}\n\n\n// reorder the rows of X, Y = X(idx,:)\nvoid reorder_rows(double **Y, double **X, int *idx, int n, int m)\n{\n  int i;\n  double **Y2 = (X==Y ? new_matrix2(n,m) : Y);\n  for (i = 0; i < n; i++)\n    memcpy(Y2[i], X[idx[i]], m*sizeof(double));\n  if (X==Y) {\n    matrix_copy(Y, Y2, n, m);\n    free_matrix2(Y2);\n  }\n}\n\n// reorder the rows of X, Y = X(idx,:)\nvoid reorder_rowsi(int **Y, int **X, int *idx, int n, int m)\n{\n  int i;\n  int **Y2 = (X==Y ? new_matrix2i(n,m) : Y);\n  for (i = 0; i < n; i++)\n    memcpy(Y2[i], X[idx[i]], m*sizeof(int));\n  if (X==Y) {\n    memcpy(Y[0], Y2[0], n*m*sizeof(int));\n    free_matrix2i(Y2);\n  }\n}\n\nvoid repmat(double **B, double **A, int rep_n, int rep_m, int n, int m)\n{\n  int i, rep_i, rep_j;\n\n  // copy A into top-left corner of B\n  if (A != B)\n    for (i = 0; i < n; ++i)\n      memcpy(B[i], A[i], m * sizeof(double)); \n\n  // repeat top-left corner to the right\n  for (i = 0; i < n; ++i)\n    for (rep_j = 1; rep_j < rep_m; ++rep_j)\n      memcpy(&B[i][rep_j * m], B[i], m * sizeof(double)); \n\n  // repeat top of B downwards\n  for (rep_i = 1; rep_i < rep_n; ++rep_i)\n    memcpy(B[rep_i * n], B[0], m * rep_m * n * sizeof(double));\n}\n\nvoid repmati(int **B, int **A, int rep_n, int rep_m, int n, int m)\n{\n  int i, rep_i, rep_j;\n\n  // copy A into top-left corner of B\n  if (A != B)\n    for (i = 0; i < n; ++i)\n      memcpy(B[i], A[i], m * sizeof(int)); \n\n  // repeat top-left corner to the right\n  for (i = 0; i < n; ++i)\n    for (rep_j = 1; rep_j < rep_m; ++rep_j)\n      memcpy(&B[i][rep_j * m], B[i], m * sizeof(int)); \n\n  // repeat top of B downwards\n  for (rep_i = 1; rep_i < rep_n; ++rep_i)\n    memcpy(B[rep_i * n], B[0], m * rep_m * n * sizeof(int));\n}\n\n/*\n * blur matrix with a 3x3 gaussian filter with sigma=.5\n */\nvoid blur_matrix(double **dst, double **src, int n, int m)\n{\n  double G[3] = {.6193, .0838, .0113};\n\n  double **I = (dst==src ? new_matrix2(n,m) : dst);\n  memcpy(I[0], src[0], n*m*sizeof(double));\n\n  int i,j;\n  for (i = 1; i < n-1; i++)\n    for (j = 1; j < m-1; j++)\n      I[i][j] = G[0]*src[i][j] + G[1]*(src[i+1][j] + src[i-1][j] + src[i][j+1] + src[i][j-1]) + G[2]*(src[i+1][j+1] + src[i+1][j-1] + src[i-1][j+1] + src[i-1][j-1]);\n\n  if (dst==src) {\n    memcpy(dst[0], I[0], n*m*sizeof(double));\n    free_matrix2(I);\n  }\n}\n\n/*\n * blur masked matrix with a 3x3 gaussian filter with sigma=.5\n */\nvoid blur_matrix_masked(double **dst, double **src, int **mask, int n, int m)\n{\n  double G[3] = {.6193, .0838, .0113};\n\n  double **I = (dst==src ? new_matrix2(n,m) : dst);\n  memcpy(I[0], src[0], n*m*sizeof(double));\n\n  int i,j;\n  for (i = 1; i < n-1; i++) {\n    for (j = 1; j < m-1; j++) {\n      double x[9] = {mask[i][j] ? src[i][j] : 0., mask[i+1][j] ? src[i+1][j] : 0., mask[i-1][j] ? src[i-1][j] : 0., mask[i][j+1] ? src[i][j+1] : 0., mask[i][j-1] ? src[i][j-1] : 0.,\n\t\t  mask[i+1][j+1] ? src[i+1][j+1] : 0., mask[i+1][j-1] ? src[i+1][j-1] : 0., mask[i-1][j+1] ? src[i-1][j+1] : 0., mask[i-1][j-1] ? src[i-1][j-1] : 0.};\n\n      double v = G[0]*x[0] + G[1]*(x[1] + x[2] + x[3] + x[4]) + G[2]*(x[5] + x[6] + x[7] + x[8]);\n\n      int n0 = !!mask[i][j];\n      int n1 = !!mask[i+1][j] + !!mask[i-1][j] + !!mask[i][j+1] + !!mask[i][j-1];\n      int n2 = !!mask[i+1][j+1] + !!mask[i-1][j-1] + !!mask[i-1][j+1] + !!mask[i+1][j-1];\n      double g_tot = n0*G[0] + n1*G[1] + n2*G[2];\n\n      I[i][j] = v / g_tot;\n    }\n  }\n\n  if (dst==src) {\n    memcpy(dst[0], I[0], n*m*sizeof(double));\n    free_matrix2(I);\n  }\n}\n\nvoid print_matrix(double **X, int n, int m)\n{\n  int i, j;\n  for (i = 0; i < n; i++) {\n    for (j = 0; j < m; j++)\n      printf(\"%f \", X[i][j]);\n    printf(\"\\n\");\n  }\n}\n\n\n// perform linear regression: dot(b,x[i]) = y[i], i=1..n\nvoid linear_regression(double *b, double **X, double *y, int n, int d)\n{\n  double **Xt = new_matrix2(d,n);\n  transpose(Xt,X,n,d);\n\n  double **XtX = new_matrix2(d,d);\n  matrix_mult(XtX,Xt,X,d,n,d);\n\n  double Xty[d];\n  matrix_vec_mult(Xty,Xt,y,d,n);\n\n  solve(b, XtX, Xty, d);\n\n  free_matrix2(Xt);\n  free_matrix2(XtX);\n}\n\n\n// fit a polynomial: \\sum{b[i]*x[j]^i} = y[j], i=1..n, j=1..d\nvoid polynomial_regression(double *b, double *x, double *y, int n, int d)\n{\n  double **X = new_matrix2(n,d);\n\n  int i, j;\n  for (i = 0; i < n; i++)\n    X[i][0] = 1;\n\n  for (i = 0; i < n; i++)\n    for (j = 1; j < d; j++)\n      X[i][j] = X[i][j-1]*x[i];\n\n  linear_regression(b,X,y,n,d);\n\n  free_matrix2(X);\n}\n\n\n\n\n\n\n/* create a new graph\ngraph_t *graph_new(int num_vertices, int edge_capacity)\n{\n  int i;\n  graph_t *g = (graph_t *)malloc(sizeof(graph_t));\n\n  g->nv = num_vertices;\n  g->vertices = (vertex_t *)calloc(g->nv, sizeof(vertex_t));\n  for (i = 0; i < g->nv; i++)\n    g->vertices[i].index = i;\n\n  g->ne = 0;\n  g->_edge_capacity = edge_capacity;\n  g->edges = (edge_t *)calloc(edge_capacity, sizeof(edge_t));\n\n  return g;\n}\n*/\n\n\n// free a graph\nvoid graph_free(graph_t *g)\n{\n  int i;\n  free(g->edges);\n  for (i = 0; i < g->nv; i++) {\n    free(g->vertices[i].edges);\n    ilist_free(g->vertices[i].neighbors);\n  }\n  free(g);\n}\n\n\n/* add an edge to a graph\nvoid graph_add_edge(graph_t *g, int i, int j)\n{\n  ilist\n  for \n\n\n  if (g->ne == g->_edge_capacity) {\n    g->_edge_capacity *= 2;\n    g->edges = (edge_t *)realloc(g->edges, g->_edge_capacity * sizeof(edge_t));\n  }\n\n  g->edges[g->ne].i = i;\n  g->edges[g->ne].j = j;\n  g->ne++;\n\n  g->vertices[i]\n}\n*/\n\n\n// find the index of an edge in a graph\nint graph_find_edge(graph_t *g, int i, int j)\n{\n  int k = ilist_find(g->vertices[i].neighbors, j);\n\n  if (k < 0)\n    return -1;\n\n  return g->vertices[i].edges[k];\n}\n\n\n// smooth the edges of a graph\nvoid graph_smooth(double **dst, double **src, graph_t *g, int d, double w)\n{\n  int i, j;\n  double p[d];\n  ilist_t *v;\n\n  if (dst != src)\n    memcpy(dst[0], src[0], d*g->nv*sizeof(double));\n\n  for (i = 0; i < g->nv; i++) {\n    memset(p, 0, d * sizeof(double));                        // p = 0\n    for (v = g->vertices[i].neighbors; v; v = v->next) {\n      j = v->x;\n      add(p, p, dst[j], d);                                  // p += dst[j]\n    }\n    mult(p, p, 1/norm(p, d), d);                             // p = p/norm(p)\n\n    wavg(dst[i], p, dst[i], w, d);                           // dst[i] = w*p + (1-w)*dst[i]\n  }\n}\n\n\nstatic int dcomp(const void *px, const void *py)\n{\n  double x = *(double *)px;\n  double y = *(double *)py;\n\n  if (x == y)\n    return 0;\n\n  return (x < y ? -1 : 1);\n}\n\n// sample uniformly from a simplex S with n vertices\nvoid sample_simplex(double x[], double **S, int n, int d)\n{\n  int i;\n\n  // get n-1 uniform samples, u, on [0,1], and sort them\n  double u[n];\n  for (i = 0; i < n-1; i++)\n    u[i] = frand();\n  u[n-1] = 1;\n\n  qsort((void *)u, n-1, sizeof(double), dcomp);\n\n  // mixing coefficients are the order statistics of u\n  double c[n];\n  c[0] = u[0];\n  for (i = 1; i < n; i++)\n    c[i] = u[i] - u[i-1];\n\n  // x = sum(c[i]*S[i])\n  mult(x, S[0], c[0], d);\n  for (i = 1; i < n; i++) {\n    double y[d];\n    mult(y, S[i], c[i], d);\n    add(x, x, y, d);\n  }\n}\n\n\n/*******************\ntypedef struct {\n  int nv;\n  int ne;\n  int nf;\n  int *vertices;\n  edge_t *edges;\n  face_t *faces;\n  int *nvn;  // # vertex neighbors\n  int *nen;  // # edge neighbors\n  int **vertex_neighbors;  // vertex -> {vertices}\n  int **vertex_edges;      // vertex -> {edges}\n  int **edge_neighbors;    // edge -> {vertices}\n  int **edge_faces;        // edge -> {faces}\n  // internal vars\n  int _vcap;\n  int _ecap;\n  int _fcap;\n  int *_vncap;\n  int *_encap;\n} meshgraph_t;\n******************/\n\n\n/*\n * Create a new meshgraph with initial vertex capacity 'vcap' and degree capacity 'dcap'.\n */\nmeshgraph_t *meshgraph_new(int vcap, int dcap)\n{\n  int i;\n  meshgraph_t *g;\n  safe_calloc(g, 1, meshgraph_t);\n\n  safe_malloc(g->vertices, vcap, int);\n  safe_malloc(g->edges, vcap, edge_t);\n  safe_malloc(g->faces, vcap, face_t);\n\n  g->_vcap = g->_ecap = g->_fcap = vcap;\n  safe_malloc(g->_vncap, vcap, int);\n  safe_malloc(g->_encap, vcap, int);\n\n  safe_malloc(g->vertex_neighbors, vcap, int *);\n  safe_malloc(g->vertex_edges, vcap, int *);\n  safe_calloc(g->nvn, vcap, int);\n  for (i = 0; i < vcap; i++) {\n    safe_malloc(g->vertex_neighbors[i], dcap, int);\n    safe_malloc(g->vertex_edges[i], dcap, int);\n    g->_vncap[i] = dcap;\n  }\n\n  safe_malloc(g->edge_neighbors, vcap, int *);\n  safe_malloc(g->edge_faces, vcap, int *);\n  safe_calloc(g->nen, vcap, int);\n  for (i = 0; i < vcap; i++) {\n    safe_malloc(g->edge_neighbors[i], dcap, int);\n    safe_malloc(g->edge_faces[i], dcap, int);\n    g->_encap[i] = dcap;\n  }\n\n  return g;\n}\n\n\nvoid meshgraph_free(meshgraph_t *g)\n{\n  int i;\n\n  free(g->vertices);\n  free(g->edges);\n  free(g->faces);\n  free(g->nvn);\n  free(g->nen);\n  free(g->_vncap);\n  free(g->_encap);\n\n  for (i = 0; i < g->nv; i++) {\n    free(g->vertex_neighbors[i]);\n    free(g->vertex_edges[i]);\n  }\n  free(g->vertex_neighbors);\n  free(g->vertex_edges);\n\n  for (i = 0; i < g->ne; i++) {\n    free(g->edge_neighbors[i]);\n    free(g->edge_faces[i]);\n  }\n  free(g->edge_neighbors);\n  free(g->edge_faces);\n\n  free(g);\n}\n\n\nint meshgraph_find_edge(meshgraph_t *g, int i, int j)\n{\n  int n;\n  for (n = 0; n < g->nvn[i]; n++)\n    if (g->vertex_neighbors[i][n] == j)\n      return g->vertex_edges[i][n];\n\n  return -1;\n}\n\n\nint meshgraph_find_face(meshgraph_t *g, int i, int j, int k)\n{\n  int e = meshgraph_find_edge(g, i, j);\n  if (e < 0)\n    return -1;\n\n  int n;\n  for (n = 0; n < g->nen[e]; n++)\n    if (g->edge_neighbors[e][n] == k)\n      return g->edge_faces[e][n];\n\n  return -1;\n}\n\n\nstatic inline int meshgraph_add_vertex_neighbor(meshgraph_t *g, int i, int vertex, int edge)\n{\n  int n = g->nvn[i];\n  if (n == g->_vncap[i]) {\n    g->_vncap[i] *= 2;\n    safe_realloc(g->vertex_neighbors[i], g->_vncap[i], int);\n    safe_realloc(g->vertex_edges[i], g->_vncap[i], int);\n  }\n  g->vertex_neighbors[i][n] = vertex;\n  g->vertex_edges[i][n] = edge;\n  g->nvn[i]++;\n\n  return n;\n}\n\n\nint meshgraph_add_edge(meshgraph_t *g, int i, int j)\n{\n  //printf(\"meshgraph_add_edge(%d, %d)\\n\", i, j);\n\n  int edge = meshgraph_find_edge(g, i, j);\n  if (edge >= 0)\n    return edge;\n\n  //printf(\"  break 1\\n\");\n\n  // add the edge\n  if (g->ne == g->_ecap) {\n    int old_ecap = g->_ecap;\n    g->_ecap *= 2;\n    safe_realloc(g->edges, g->_ecap, edge_t);\n    safe_realloc(g->edge_neighbors, g->_ecap, int *);\n    safe_realloc(g->edge_faces, g->_ecap, int *);\n    safe_realloc(g->nen, g->_ecap, int);\n    safe_realloc(g->_encap, g->_ecap, int);\n\n    //printf(\"  break 1.1\\n\");\n\n    int e;\n    for (e = old_ecap; e < g->_ecap; e++) {\n      //printf(\"    e = %d\\n\", e);\n      g->nen[e] = 0;\n      int dcap = g->_encap[0];\n\n      //printf(\"    dcap = %d\\n\", dcap);\n\n      safe_malloc(g->edge_neighbors[e], dcap, int);\n\n      //printf(\"    break 1.1.1\\n\");\n\n      safe_malloc(g->edge_faces[e], dcap, int);\n\n      //printf(\"    break 1.1.2\\n\");\n\n      g->_encap[e] = dcap;\n    }\n  }\n\n  //printf(\"  break 2\\n\");\n\n  edge = g->ne;\n  g->edges[edge].i = i;\n  g->edges[edge].j = j;\n  g->ne++;\n\n  //printf(\"  break 3\\n\");\n\n  // add the vertex neighbors\n  meshgraph_add_vertex_neighbor(g, i, j, edge);\n  meshgraph_add_vertex_neighbor(g, j, i, edge);\n\n  //printf(\"  break 4\\n\");\n\n  return edge;\n}\n\n\nstatic inline int meshgraph_add_edge_neighbor(meshgraph_t *g, int i, int vertex, int face)\n{\n  int n = g->nen[i];\n\n  //printf(\"g->nen[%d] = %d, g->_encap[%d] = %d\\n\", i, n, i, g->_encap[i]);\n\n  if (n == g->_encap[i]) {\n\n    //printf(\"n == g->_encap[%d]\\n\", i);\n\n    g->_encap[i] *= 2;\n    safe_realloc(g->edge_neighbors[i], g->_encap[i], int);\n    safe_realloc(g->edge_faces[i], g->_encap[i], int);\n  }\n\n  //printf(\"  break 1\\n\");\n\n  g->edge_neighbors[i][n] = vertex;\n\n  //printf(\"  break 2\\n\");\n\n  g->edge_faces[i][n] = face;\n\n  //printf(\"  break 3\\n\");\n\n  g->nen[i]++;\n\n  return n;\n}\n\n\nint meshgraph_add_face(meshgraph_t *g, int i, int j, int k)\n{\n  //printf(\"meshgraph_add_face(%d, %d, %d)\\n\", i, j, k);\n\n  int face = meshgraph_find_face(g, i, j, k);\n  if (face >= 0)\n    return face;\n\n  //printf(\"  break 1\\n\");\n\n  // add the edges\n  int edge_ij = meshgraph_add_edge(g, i, j);\n  int edge_ik = meshgraph_add_edge(g, i, k);\n  int edge_jk = meshgraph_add_edge(g, j, k);\n\n  //printf(\"  break 2\\n\");\n\n  // add the face\n  //printf(\"g->nf = %d, g->_fcap = %d\\n\", g->nf, g->_fcap);\n\n  if (g->nf == g->_fcap) {\n    g->_fcap *= 2;\n    safe_realloc(g->faces, g->_fcap, face_t);\n  }\n  face = g->nf;\n  g->faces[face].i = i;\n  g->faces[face].j = j;\n  g->faces[face].k = k;\n  g->nf++;\n\n  //printf(\"  break 3\\n\");\n\n  // add the edge neighbors\n  meshgraph_add_edge_neighbor(g, edge_ij, k, face);\n  meshgraph_add_edge_neighbor(g, edge_ik, j, face);\n  meshgraph_add_edge_neighbor(g, edge_jk, i, face);\n\n  //printf(\"  break 4\\n\");\n\n  return face;\n}\n\n\nstatic int _sortable_cmp(const void *x1, const void *x2)\n{\n  double v1 = ((sortable_t *)x1)->value;\n  double v2 = ((sortable_t *)x2)->value;\n\n  if (v1 == v2)\n    return 0;\n\n  if (v1 < v2 || isnan(v1))\n    return -1;\n\n  return 1;\n}\n\n// sort an array of weighted data using qsort\nvoid sort_data(sortable_t *x, size_t n)\n{\n  qsort(x, n, sizeof(sortable_t), _sortable_cmp);\n}\n\n\n// sort the indices of x (leaving x unchanged)\nvoid sort_indices(double *x, int *idx, int n)\n{\n  int i;\n  sortable_t *s;\n  int *xi;\n  safe_malloc(s, n, sortable_t);\n  safe_malloc(xi, n, int);\n\n  for (i = 0; i < n; i++) {\n    xi[i] = i;\n    s[i].value = x[i];\n    s[i].data = (void *)(&xi[i]);\n  }\n\n  sort_data(s, n);\n\n  for (i = 0; i < n; i++)\n    idx[i] = *(int *)(s[i].data);\n\n  free(s);\n  free(xi);\n}\n\n\n/*\n * fills idx with the indices of the k min entries of x\n *   --> works by maintaining the invariant that idx[0] always has the\n *       largest x value of the min k found so far\n */       \nvoid mink(double *x, int *idx, int n, int k)\n{\n  int i, j;\n\n  // initialize idx with 1:k\n  for (i = 0; i < k; i++)\n    idx[i] = i;\n\n  // maintain invariant\n  for (i = 1; i < k; i++) {\n    if (x[idx[i]] > x[idx[0]]) {\n      int tmp = idx[i];\n      idx[i] = idx[0];\n      idx[0] = tmp;\n    }\n  }\n\n  // process the rest of x\n  for (i = k; i < n; i++) {\n    if (x[i] < x[idx[0]]) {\n      idx[0] = i;\n\n      // maintain invariant\n      for (j = 1; j < k; j++) {\n\tif (x[idx[j]] > x[idx[0]]) {\n\t  int tmp = idx[j];\n\t  idx[j] = idx[0];\n\t  idx[0] = tmp;\n\t}\n      }\n    }\n  }\n\n  // sort the min k values\n  double xmink[k];\n  int idx2[k];\n  for (i = 0; i < k; i++)\n    xmink[i] = x[idx[i]];\n  sort_indices(xmink, idx2, k);\n  for (i = 0; i < k; i++)\n    idx2[i] = idx[idx2[i]];\n  for (i = 0; i < k; i++)\n    idx[i] = idx2[i];\n}\n\nshort double_is_equal(double a, double b)\n{\n  return fabs(a - b) < 0.00001;\n}\n\n// fast select algorithm\nint qselect(double *x, int n, int k)\n{\n  if (n == 1)\n    return 0;\n\n  double pivot = x[k];\n\n  // partition x into y < pivot, z > pivot\n  int i, ny=0, nz=0;\n  for (i = 0; i < n; i++) {\n    if (x[i] < pivot)\n      ny++;\n    else if (x[i] > pivot)\n      nz++;\n  }\n\n  if (k < ny) {\n    double *y;\n    int *yi;\n    safe_calloc(y, ny, double);\n    safe_calloc(yi, ny, int);\n    ny = 0;\n    for (i = 0; i < n; i++) {\n      if (x[i] < pivot) {\n\tyi[ny] = i;\n\ty[ny++] = x[i];\n      }\n    }\n    i = yi[qselect(y, ny, k)];\n    free(y);\n    free(yi);\n    return i;\n  }\n\n  else if (k >= n - nz) {\n    double *z;\n    int *zi;\n    safe_calloc(z, nz, double);\n    safe_calloc(zi, nz, int);\n    nz = 0;\n    for (i = 0; i < n; i++) {\n      if (x[i] > pivot) {\n\tzi[nz] = i;\n\tz[nz++] = x[i];\n      }\n    }\n    i = zi[qselect(z, nz, k-(n-nz))];\n    free(z);\n    free(zi);\n    return i;\n  }\n\n  return k;\n}\n\n\nstatic kdtree_t *build_kdtree(double **X, int *xi, int n, int d, int depth)\n{\n  if (n == 0)\n    return NULL;\n\n  int i, axis = depth % d;\n  kdtree_t *node;\n  safe_calloc(node, 1, kdtree_t);\n  node->axis = axis;\n\n  double *x;\n  safe_calloc(x, n, double);\n  for (i = 0; i < n; i++)\n    x[i] = X[i][axis];\n\n  int median = qselect(x, n, n/2);\n\n  // node location\n  node->i = xi[median];\n  node->d = d;\n  safe_malloc(node->x, d, double);\n  memcpy(node->x, X[median], d*sizeof(double));\n\n  // node bbox init:  bbox_min = bbox_max = x\n  safe_malloc(node->bbox_min, d, double);\n  safe_malloc(node->bbox_max, d, double);\n  memcpy(node->bbox_min, node->x, d*sizeof(double));\n  memcpy(node->bbox_max, node->x, d*sizeof(double));\n\n  // partition x into y < pivot, z > pivot\n  double pivot = x[median];\n  int ny=0, nz=0;\n  for (i = 0; i < n; i++) {\n    if (i == median)\n      continue;\n    if (x[i] <= pivot)\n      ny++;\n    else if (x[i] > pivot)\n      nz++;\n  }\n\n  //printf(\"n = %d, d = %d, depth = %d, axis = %d --> median = %d, X[median] = (%f, %f, %f), ny = %d, nz = %d\\n\",\n  //\t n, d, depth, axis, median, X[median][0], X[median][1], X[median][2], ny, nz);\n\n\n  if (ny > 0) {\n    double **Y = new_matrix2(ny, d);\n    int *yi;\n    safe_calloc(yi, ny, int);\n    ny = 0;\n    for (i = 0; i < n; i++) {\n      if (i == median)\n\tcontinue;\n      if (x[i] <= pivot) {\n\tyi[ny] = xi[i];\n\tmemcpy(Y[ny], X[i], d*sizeof(double));\n\tny++;\n      }\n    }\n    node->left = build_kdtree(Y, yi, ny, d, depth+1);\n\n    // update bbox\n    for (i = 0; i < d; i++) {\n      if (node->left->bbox_min[i] < node->bbox_min[i])\n\tnode->bbox_min[i] = node->left->bbox_min[i];\n      if (node->left->bbox_max[i] > node->bbox_max[i])\n\tnode->bbox_max[i] = node->left->bbox_max[i];\n    }\n\n    free_matrix2(Y);\n    free(yi);\n  }\n\n  if (nz > 0) {\n    double **Z = new_matrix2(nz, d);\n    int *zi;\n    safe_calloc(zi, nz, int);\n    nz = 0;\n    for (i = 0; i < n; i++) {\n      if (i == median)\n\tcontinue;\n      if (x[i] > pivot) {\n\tzi[nz] = xi[i];\n\tmemcpy(Z[nz], X[i], d*sizeof(double));\n\tnz++;\n      }\n    }\n    node->right = build_kdtree(Z, zi, nz, d, depth+1);\n\n    // update bbox\n    for (i = 0; i < d; i++) {\n      if (node->right->bbox_min[i] < node->bbox_min[i])\n\tnode->bbox_min[i] = node->right->bbox_min[i];\n      if (node->right->bbox_max[i] > node->bbox_max[i])\n\tnode->bbox_max[i] = node->right->bbox_max[i];\n    }\n\n    free_matrix2(Z);\n    free(zi);\n  }\n\n  free(x);\n  return node;\n}\n\n\nkdtree_t *kdtree(double **X, int n, int d)\n{\n  int i, *xi;\n  safe_malloc(xi, n, int);\n  for (i = 0; i < n; i++)\n    xi[i] = i;\n\n  kdtree_t *tree = build_kdtree(X, xi, n, d, 0);\n\n  free(xi);\n  return tree;\n}\n\n\nstatic kdtree_t *kdtree_NN_node(kdtree_t *tree, double *x, kdtree_t *best)\n{\n  if (tree == NULL)\n    return best;\n\n  //printf(\"node %d\", tree->i);\n\n  int i, d = tree->d;\n  double dbest = (best ? dist(x, best->x, d) : DBL_MAX);\n\n  // first, check if any node in tree can possibly be better than 'best'\n  if (best) {\n    double y[d];  // closest point on the tree's bbox to x\n    for (i = 0; i < d; i++) {\n      if (x[i] < tree->bbox_min[i])\n\ty[i] = tree->bbox_min[i];\n      else if (x[i] > tree->bbox_max[i])\n\ty[i] = tree->bbox_max[i];\n      else\n\ty[i] = x[i];\n    }\n    if (dist(y, x, d) >= dbest) {  // 'best' is closer than the closest possible point in tree, so return\n      //printf(\"  --> pruned!\\n\");\n      return best;\n    }\n  }\n\n  int axis = tree->axis;\n  kdtree_t *nn = best;\n\n  // compare with the node itself\n  double dtree = dist(x, tree->x, d);\n  //printf(\" (%f)\", dtree);\n  if (dtree < dbest) {\n    nn = tree;\n    dbest = dtree;\n    //printf(\" --> new best\");\n  }\n  //printf(\"\\n\");\n\n  // compare with the NN in each sub-tree\n  if (x[axis] <= tree->x[axis]) {\n    nn = kdtree_NN_node(tree->left, x, nn);\n    nn = kdtree_NN_node(tree->right, x, nn);\n  }\n  else if (x[axis] > tree->x[axis]) {\n    nn = kdtree_NN_node(tree->right, x, nn);\n    nn = kdtree_NN_node(tree->left, x, nn);\n  }\n\n  //dbest = dist(x, nn->x, d);\n  //printf(\" ... return %d (%f)\\n\", nn->i, dbest);\n\n  return nn;\n}\n\nint kdtree_NN(kdtree_t *tree, double *x)\n{\n  kdtree_t *nn = kdtree_NN_node(tree, x, NULL);\n  return (nn ? nn->i : -1);\n}\n\n\nvoid kdtree_free(kdtree_t *tree)\n{\n  if (tree == NULL)\n    return;\n\n  kdtree_free(tree->left);\n  kdtree_free(tree->right);\n\n  free(tree->x);\n  free(tree->bbox_min);\n  free(tree->bbox_max);\n\n  free(tree);\n}\n\n// RGB to CIELAB color space\nvoid rgb2lab(double lab[], double rgb[])\n{\n  double R = rgb[0];\n  double G = rgb[1];\n  double B = rgb[2];\n\n  //if (R > 1.0 || G > 1.0 || B > 1.0) {\n  R /= 255.0;\n  G /= 255.0;\n  B /= 255.0;\n  //}\n  \n  // set a threshold\n  double T = 0.008856;\n  \n  // RGB to XYZ\n  double X = 0.412453*R + 0.357580*G + 0.180423*B;\n  double Y = 0.212671*R + 0.715160*G + 0.072169*B;\n  double Z = 0.019334*R + 0.119193*G + 0.950227*B;\n\n  // normalize for D65 white point\n  X /= 0.950456;\n  Z /= 1.088754;\n\n  double X3 = pow(X, 1/3.);\n  double Y3 = pow(Y, 1/3.);\n  double Z3 = pow(Z, 1/3.);\n\n  double fX = (X>T ? X3 : 7.787*X + 16/116.);\n  double fY = (Y>T ? Y3 : 7.787*Y + 16/116.);\n  double fZ = (Z>T ? Z3 : 7.787*Z + 16/116.);\n\n  lab[0] = (Y>T ? 116*Y3 - 16.0 : 903.3*Y);\n  lab[1] = 500*(fX - fY);\n  lab[2] = 200*(fY - fZ);\n}\n\n// CIELAB to RGB color space\nvoid lab2rgb(double rgb[], double lab[])\n{\n  // Thresholds\n  double T1 = 0.008856;\n  double T2 = 0.206893;\n\n  double L = lab[0];\n  double a = lab[1];\n  double b = lab[2];\n\n  // Compute Y\n  double fY = pow((L + 16) / 116., 3);\n  int YT = (fY > T1);\n  if (!YT)\n    fY = L / 903.3;\n  double Y = fY;\n\n  // Alter fY slightly for further calculations\n  fY = (YT ? pow(fY, 1/3.) : 7.787 * fY + 16/116.);\n\n  // Compute X\n  double fX = a / 500. + fY;\n  int XT = fX > T2;\n  double X = (XT ? pow(fX, 3) : (fX - 16/116.) / 7.787);\n\n  // Compute Z\n  double fZ = fY - b / 200.;\n  int ZT = fZ > T2;\n  double Z = (ZT ? pow(fZ, 3) : (fZ - 16/116.) / 7.787);\n\n  // Normalize for D65 white point\n  X = X * 0.950456;\n  Z = Z * 1.088754;\n\n  // XYZ to RGB\n  double R =  3.240479*X - 1.537150*Y - 0.498535*Z;\n  double G = -0.969256*X + 1.875992*Y + 0.041556*Z;\n  double B =  0.055648*X - 0.204043*Y + 1.057311*Z;\n\n  rgb[0] = 255*MAX(MIN(R, 1.0), 0.0);\n  rgb[1] = 255*MAX(MIN(G, 1.0), 0.0);\n  rgb[2] = 255*MAX(MIN(B, 1.0), 0.0);\n}\n", "meta": {"hexsha": "f4b775f3cf1ff6f52d0da2df746cf0309c91df7f", "size": 75731, "ext": "c", "lang": "C", "max_stars_repo_path": "c/util.c", "max_stars_repo_name": "adamconkey/bingham", "max_stars_repo_head_hexsha": "a3948cba29bb1288c3ab97141479273d493a139a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 35.0, "max_stars_repo_stars_event_min_datetime": "2015-06-23T02:49:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T14:19:23.000Z", "max_issues_repo_path": "c/util.c", "max_issues_repo_name": "adamconkey/bingham", "max_issues_repo_head_hexsha": "a3948cba29bb1288c3ab97141479273d493a139a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2015-06-10T08:13:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T22:38:55.000Z", "max_forks_repo_path": "c/util.c", "max_forks_repo_name": "adamconkey/bingham", "max_forks_repo_head_hexsha": "a3948cba29bb1288c3ab97141479273d493a139a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-06-12T18:28:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T22:05:44.000Z", "avg_line_length": 20.4678378378, "max_line_length": 838, "alphanum_fraction": 0.508167065, "num_tokens": 30542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34510528442897664, "lm_q2_score": 0.01971912709919374, "lm_q1q2_score": 0.006805174966258397}}
{"text": "/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*\n**                                                                                  **\n** This file forms part of the Underworld geophysics modelling application.         **\n**                                                                                  **\n** For full license and copyright information, please refer to the LICENSE.md file  **\n** located at the project root, or contact the authors.                             **\n**                                                                                  **\n**~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/\n\n#include <mpi.h>\n#include <StGermain/StGermain.h>\n#include <StgDomain/StgDomain.h>\n#include <StgFEM/StgFEM.h>\n#include <petsc.h>\n\n#include \"types.h\"\n#include \"SemiLagrangianIntegrator.h\"\n\n#include <assert.h>\n\n/** Textual name of this class */\nconst Type SemiLagrangianIntegrator_Type = \"SemiLagrangianIntegrator\";\n\nSemiLagrangianIntegrator* _SemiLagrangianIntegrator_New(  SEMILAGRANGIANINTEGRATOR_DEFARGS  )\n{\n   SemiLagrangianIntegrator*\t\tself;\n\n   /* Allocate memory */\n   assert( _sizeOfSelf >= sizeof(SemiLagrangianIntegrator) );\n   /* The following terms are parameters that have been passed into this function but are being set before being passed onto the parent */\n   /* This means that any values of these parameters that are passed into this function are not passed onto the parent function\n      and so should be set to ZERO in any children of this class. */\n   nameAllocationType = NON_GLOBAL;\n\n   self = (SemiLagrangianIntegrator*) _Stg_Component_New(  STG_COMPONENT_PASSARGS  );\n\n   /* General info */\n   self->variableList = Stg_ObjectList_New();\n   self->varStarList  = Stg_ObjectList_New();\n   self->varOldList   = Stg_ObjectList_New();\n\n   return self;\n}\n\nvoid* _SemiLagrangianIntegrator_Copy( void* slIntegrator, void* dest, Bool deep, Name nameExt, PtrMap* ptrMap ) {\n   SemiLagrangianIntegrator*\t\tself = (SemiLagrangianIntegrator*)slIntegrator;\n   SemiLagrangianIntegrator*\t\tnewSemiLagrangianIntegrator;\n   PtrMap*\t\t\tmap = ptrMap;\n   Bool\t\t\townMap = False;\n\n   if( !map ) {\n      map = PtrMap_New( 10 );\n      ownMap = True;\n   }\n\n   newSemiLagrangianIntegrator = _Stg_Component_Copy( self, dest, deep, nameExt, map );\n\n   if( deep ) {\n      if( (newSemiLagrangianIntegrator->velocityField = PtrMap_Find( map, self->velocityField )) == NULL ) {\n         newSemiLagrangianIntegrator->velocityField = Stg_Class_Copy( self->velocityField, NULL, deep, nameExt, map );\n         PtrMap_Append( map, self->velocityField, newSemiLagrangianIntegrator->velocityField );\n      }\n   }\n   else {\n      newSemiLagrangianIntegrator->velocityField = Stg_Class_Copy( self->velocityField, NULL, deep, nameExt, map );\n   }\n\n   if( ownMap ) {\n      Stg_Class_Delete( map );\n   }\n\n   return (void*)newSemiLagrangianIntegrator;\n}\n\n\nvoid _SemiLagrangianIntegrator_Delete( void* slIntegrator ) {\n   SemiLagrangianIntegrator*\t\tself = (SemiLagrangianIntegrator*)slIntegrator;\n   Stg_Class_Delete( self->variableList );\n   Stg_Class_Delete( self->varStarList );\n   Stg_Class_Delete( self->varOldList );\n}\n\nvoid _SemiLagrangianIntegrator_Print( void* slIntegrator, Stream* stream ) {\n   SemiLagrangianIntegrator*\t\tself = (SemiLagrangianIntegrator*)slIntegrator;\n\n   _Stg_Component_Print( self, stream );\n\n   Journal_PrintPointer( stream, self->velocityField );\n}\n\nvoid* _SemiLagrangianIntegrator_DefaultNew( Name name ) {\n   /* Variables set in this function */\n   SizeT                                              _sizeOfSelf = sizeof(SemiLagrangianIntegrator);\n   Type                                                      type = SemiLagrangianIntegrator_Type;\n   Stg_Class_DeleteFunction*                              _delete = _SemiLagrangianIntegrator_Delete;\n   Stg_Class_PrintFunction*                                _print = _SemiLagrangianIntegrator_Print;\n   Stg_Class_CopyFunction*                                  _copy = _SemiLagrangianIntegrator_Copy;\n   Stg_Component_DefaultConstructorFunction*  _defaultConstructor = _SemiLagrangianIntegrator_DefaultNew;\n   Stg_Component_ConstructFunction*                    _construct = _SemiLagrangianIntegrator_AssignFromXML;\n   Stg_Component_BuildFunction*                            _build = _SemiLagrangianIntegrator_Build;\n   Stg_Component_InitialiseFunction*                  _initialise = _SemiLagrangianIntegrator_Initialise;\n   Stg_Component_ExecuteFunction*                        _execute = _SemiLagrangianIntegrator_Execute;\n   Stg_Component_DestroyFunction*                        _destroy = _SemiLagrangianIntegrator_Destroy;\n\n   /* Variables that are set to ZERO are variables that will be set either by the current _New function or another parent _New function further up the hierachy */\n   AllocationType  nameAllocationType = NON_GLOBAL /* default value NON_GLOBAL */;\n\n   return (void*)_SemiLagrangianIntegrator_New(  SEMILAGRANGIANINTEGRATOR_PASSARGS  );\n}\n\nvoid _SemiLagrangianIntegrator_AssignFromXML( void* slIntegrator, Stg_ComponentFactory* cf, void* data ) {\n   SemiLagrangianIntegrator*\tself \t\t= (SemiLagrangianIntegrator*)slIntegrator;\n   Dictionary*\t\t\tdict;\n   Dictionary_Entry_Value*\t\tdev;\n   unsigned\t\t\tfield_i;\n   Name\t\t\t\tfieldName;\n   FeVariable*\t   feVariable;\n\n   Stg_Component_AssignFromXML( self, cf, data, False );\n\n   self->context = Stg_ComponentFactory_ConstructByKey( cf, self->name, (Dictionary_Entry_Key)\"Context\", FiniteElementContext, False, data );\n   if( !self->context  )\n      self->context = Stg_ComponentFactory_ConstructByName( cf, (Name)\"context\", FiniteElementContext, True, data  );\n\n   self->velocityField = Stg_ComponentFactory_ConstructByKey( cf, self->name, (Dictionary_Entry_Key)\"VelocityField\", FeVariable, False, NULL  );\n   self->advectedField = Stg_ComponentFactory_ConstructByKey( cf, self->name, (Dictionary_Entry_Key)\"AdvectedField\", FeVariable, False, NULL  );\n\n   dict = Dictionary_Entry_Value_AsDictionary( Dictionary_Get( cf->componentDict, (Dictionary_Entry_Key)self->name )  );\n   dev  = Dictionary_Get( dict, (Dictionary_Entry_Key)\"fields\" );\n   for( field_i = 0; field_i < Dictionary_Entry_Value_GetCount( dev ); field_i += 3  ) {\n      fieldName = Dictionary_Entry_Value_AsString( Dictionary_Entry_Value_GetElement( dev, field_i ) );\n      feVariable = Stg_ComponentFactory_ConstructByName( cf, (Name)fieldName, FeVariable, True, data  );\n      Stg_ObjectList_Append( self->variableList, feVariable );\n\n      /* the corresponding _* field */\n      fieldName = Dictionary_Entry_Value_AsString( Dictionary_Entry_Value_GetElement( dev, field_i + 1 ) );\n      feVariable = Stg_ComponentFactory_ConstructByName( cf, (Name)fieldName, FeVariable, True, data  );\n      Stg_ObjectList_Append( self->varStarList, feVariable );\n\n      /* the corresponding old field */\n      fieldName = Dictionary_Entry_Value_AsString( Dictionary_Entry_Value_GetElement( dev, field_i + 2 ) );\n      feVariable = Stg_ComponentFactory_ConstructByName( cf, (Name)fieldName, FeVariable, True, data  );\n      Stg_ObjectList_Append( self->varOldList, feVariable );\n   }\n\n//   self->sle = Stg_ComponentFactory_ConstructByKey( cf, self->name, (Dictionary_Entry_Key)\"SLE\", Energy_SLE, False, NULL  );\n\n   /* for problems with temporally evolving velocity */\n   self->prevVelField = Stg_ComponentFactory_ConstructByKey( cf, self->name, (Dictionary_Entry_Key)\"PreviousTimeStepVelocityField\", FeVariable, False, data );\n   if( self->prevVelField  ) {\n      EP_AppendClassHook( Context_GetEntryPoint( self->context, AbstractContext_EP_UpdateClass ), SemiLagrangianIntegrator_UpdatePreviousVelocityField, self );\n      EP_InsertClassHookAfter( Context_GetEntryPoint( self->context, AbstractContext_EP_UpdateClass ), \"SemiLagrangianIntegrator_UpdatePreviousVelocityField\", SemiLagrangianIntegrator_InitSolve, self );\n   } else {\n      EP_AppendClassHook( Context_GetEntryPoint( self->context, AbstractContext_EP_UpdateClass ), SemiLagrangianIntegrator_InitSolve, self );\n   }\n\n//   if( self->sle ) {\n//      /** also set sle to run where required */\n//      EP_InsertClassHookAfter( Context_GetEntryPoint( self->context, AbstractContext_EP_UpdateClass ), \"SemiLagrangianIntegrator_InitSolve\", SystemLinearEquations_GetRunEPFunction(), self->sle );\n//      /** remember to disable the standard run at execute */\n//      SystemLinearEquations_SetRunDuringExecutePhase( self->sle, False);\n//   }\n\n   self->isConstructed = True;\n}\n\nvoid _SemiLagrangianIntegrator_Build( void* slIntegrator, void* data ) {\n   SemiLagrangianIntegrator*\tself \t\t= (SemiLagrangianIntegrator*)slIntegrator;\n   FeVariable*\t\t\tfeVariable;\n   FeVariable*\t\t\tfeVarOld;\n   FeVariable*\t\t\tfeVarStar;\n   unsigned\t\t\t   field_i;\n\n   if(self->velocityField) Stg_Component_Build(self->velocityField, data, False);\n   if(self->advectedField) Stg_Component_Build(self->advectedField, data, False);\n   if(self->prevVelField)  Stg_Component_Build(self->prevVelField , data, False);\n\n   for( field_i = 0; field_i < self->variableList->count; field_i++ ) {\n      feVariable = (FeVariable*) self->variableList->data[field_i];\n      feVarOld   = (FeVariable*) self->varOldList->data[field_i];\n      feVarStar  = (FeVariable*) self->varStarList->data[field_i];\n      if(feVariable) Stg_Component_Build(feVariable, data, False);\n      if(feVarOld  ) Stg_Component_Build(feVarOld  , data, False);\n      if(feVarStar ) Stg_Component_Build(feVarStar , data, False);\n   }\n}\n\nvoid _SemiLagrangianIntegrator_Initialise( void* slIntegrator, void* data ) {\n   SemiLagrangianIntegrator*\tself \t\t= (SemiLagrangianIntegrator*)slIntegrator;\n   FeVariable*\t\t\tfeVariable;\n   FeVariable*\t\t\tfeVarOld;\n   FeVariable*\t\t\tfeVarStar;\n   unsigned\t\t\t   field_i;\n\n   if(self->velocityField) Stg_Component_Initialise(self->velocityField, data, False);\n   if(self->advectedField) Stg_Component_Initialise(self->advectedField, data, False);\n   if(self->prevVelField) {\n      Stg_Component_Initialise(self->prevVelField , data, False);\n      SemiLagrangianIntegrator_UpdatePreviousVelocityField( slIntegrator, NULL );\n   }\n\n   for( field_i = 0; field_i < self->variableList->count; field_i++ ) {\n      feVariable = (FeVariable*) self->variableList->data[field_i];\n      feVarOld   = (FeVariable*) self->varOldList->data[field_i];\n      feVarStar  = (FeVariable*) self->varStarList->data[field_i];\n      if(feVariable) Stg_Component_Initialise(feVariable, data, False);\n      if(feVarOld  ) Stg_Component_Initialise(feVarOld  , data, False);\n      if(feVarStar ) Stg_Component_Initialise(feVarStar , data, False);\n   }\n}\n\nvoid _SemiLagrangianIntegrator_Execute( void* slIntegrator, void* data ) {\n}\n\nvoid _SemiLagrangianIntegrator_Destroy( void* slIntegrator, void* data ) {\n   SemiLagrangianIntegrator*\tself \t= (SemiLagrangianIntegrator*)slIntegrator;\n   FeVariable*\t\t\tfeVariable;\n   FeVariable*\t\t\tfeVarOld;\n   FeVariable*\t\t\tfeVarStar;\n   unsigned\t\t\t   field_i;\n\n   if(self->velocityField) Stg_Component_Destroy(self->velocityField, data, False);\n   if(self->advectedField) Stg_Component_Destroy(self->advectedField, data, False);\n   if(self->prevVelField)  Stg_Component_Destroy(self->prevVelField , data, False);\n\n   for( field_i = 0; field_i < self->variableList->count; field_i++ ) {\n      feVariable = (FeVariable*) self->variableList->data[field_i];\n      feVarOld   = (FeVariable*) self->varOldList->data[field_i];\n      feVarStar  = (FeVariable*) self->varStarList->data[field_i];\n      if(feVariable) Stg_Component_Destroy(feVariable, data, False);\n      if(feVarOld  ) Stg_Component_Destroy(feVarOld  , data, False);\n      if(feVarStar ) Stg_Component_Destroy(feVarStar , data, False);\n   }\n}\n\nvoid SemiLagrangianIntegrator_InitSolve( void* _self, void* _context ) {\n   SemiLagrangianIntegrator*\tself\t\t\t= (SemiLagrangianIntegrator*) _self;\n   unsigned\t\t\t   field_i, node_i;\n   FeVariable*\t\t\tfeVariable;\n   FeVariable*\t\t\tfeVarOld;\n   FeVariable*\t\t\tfeVarStar;\n   double            phi[3];\n   unsigned\t\t\t   lMeshSize;\n   FeMesh*\t\t\t\tmesh;\n\n   for( field_i = 0; field_i < self->variableList->count; field_i++ ) {\n      feVariable = (FeVariable*) self->variableList->data[field_i];\n      feVarStar  = (FeVariable*) self->varStarList->data[field_i];\n      feVarOld   = (FeVariable*) self->varOldList->data[field_i];\n\n      /* we're assuming that the solution vector has already been updated onto the FeVariable (in the SLE class) */\n      mesh = feVariable->feMesh;\n      lMeshSize = Mesh_GetLocalSize( mesh, MT_VERTEX );\n      for( node_i = 0; node_i < lMeshSize; node_i++ ) {\n         FeVariable_GetValueAtNode( feVariable, node_i, phi );\n         FeVariable_SetValueAtNode( feVarOld, node_i, phi );\n      }\n      FeVariable_SyncShadowValues( feVarOld );\n\n      /* generate the _* field */\n      SemiLagrangianIntegrator_Solve( self, feVarOld, feVarStar );\n   }\n}\n\n#define INV6 0.166666666667\n\nvoid IntegrateRungeKutta( FeVariable* velocityField, double dt, double* origin, double* position ) {\n   unsigned\t\tndims\t\t     = Mesh_GetDimSize( velocityField->feMesh );\n   unsigned\t\tdim_i;\n   double\t\t\tmin[3], max[3];\n   double\t\t\tk[4][3];\n   double\t\t\tcoordPrime[3];\n   unsigned*\t\tperiodic\t     = ((CartesianGenerator*)velocityField->feMesh->generator)->periodic;\n\n   Mesh_GetGlobalCoordRange( velocityField->feMesh, min, max );\n\n   FieldVariable_InterpolateValueAt( velocityField, origin, k[0] );\n   for( dim_i = 0; dim_i < ndims; dim_i++ ) {\n      coordPrime[dim_i] = origin[dim_i] - 0.5 * dt * k[0][dim_i];\n      PeriodicUpdate( coordPrime, min, max, dim_i, periodic[dim_i] );\n   }\n   FieldVariable_InterpolateValueAt( velocityField, coordPrime, k[1] );\n\n   for( dim_i = 0; dim_i < ndims; dim_i++ ) {\n      coordPrime[dim_i] = origin[dim_i] - 0.5 * dt * k[1][dim_i];\n      PeriodicUpdate( coordPrime, min, max, dim_i, periodic[dim_i] );\n   }\n   FieldVariable_InterpolateValueAt( velocityField, coordPrime, k[2] );\n\n   for( dim_i = 0; dim_i < ndims; dim_i++ ) {\n      coordPrime[dim_i] = origin[dim_i] - dt * k[2][dim_i];\n      PeriodicUpdate( coordPrime, min, max, dim_i, periodic[dim_i] );\n   }\n   FieldVariable_InterpolateValueAt( velocityField, coordPrime, k[3] );\n\n   for( dim_i = 0; dim_i < ndims; dim_i++ ) {\n      position[dim_i] = origin[dim_i] -\n         INV6 * dt * ( k[0][dim_i] + 2.0 * k[1][dim_i] + 2.0 * k[2][dim_i] + k[3][dim_i] );\n      PeriodicUpdate( position, min, max, dim_i, periodic[dim_i] );\n   }\n}\n\n/* 2nd order acurate runge kutta algorithm for interpolating backwards in time through a temporally evolving velocity field\n   Durran, D. \"Numerical Methods for Wave Equations in Geophysical Fluid Dynamics\" (1999), pages 310-313\n\n   u(t^(n+0.5)) = 1.5u(t^n) - 0.5u(t^(n-1))\n   x_* = x^(n+1) - 0.5*dt*u(x^(n+1),t^n)\n   x_j^n = x^(n+1) - dt*u(x_*,t^(n+0.5))\n\n   Force term:\n      F = 0.5*[3*S(x_j^n,t^n) - S(x_j^(n-1),t^(n-1))]\n */\nvoid IntegrateRungeKutta_StgVariableVelocity( FeVariable* currVelField, FeVariable* interVelField, double dt, double* origin, double* position ) {\n   unsigned\t\tnDims\t\t     = Mesh_GetDimSize( currVelField->feMesh );\n   unsigned\t\tdim_i;\n   double\t\t\tmin[3], max[3];\n   double\t\t\tmidPoint[3];\n   double\t\t\tvelCurr[3], velInter[3];\n   CartesianGenerator*\tgen\t\t     = (CartesianGenerator*)currVelField->feMesh->generator;\n\n   Mesh_GetGlobalCoordRange( currVelField->feMesh, min, max );\n\n   FieldVariable_InterpolateValueAt( currVelField, origin, velCurr );\n   for( dim_i = 0; dim_i < nDims; dim_i++ ) {\n      midPoint[dim_i] = origin[dim_i] - 0.5 * dt * velCurr[dim_i];\n      PeriodicUpdate( midPoint, min, max, dim_i, gen->periodic[dim_i] );\n   }\n\n   FieldVariable_InterpolateValueAt( interVelField, midPoint, velInter );\n\n   /* 2nd order approximation of velocity at time current + dt/2 */\n   for( dim_i = 0; dim_i < nDims; dim_i++ ) {\n      position[dim_i] = origin[dim_i] - dt * velInter[dim_i];\n      PeriodicUpdate( position, min, max, dim_i, gen->periodic[dim_i] );\n   }\n}\n\n/* for case of temporally evolving velocity field, when we need to integrate backwards in time\n * throught this to find our take off point */\nvoid SemiLagrangianIntegrator_UpdatePreviousVelocityField( void* _self, void* _context ) {\n   SemiLagrangianIntegrator*\tself\t\t= (SemiLagrangianIntegrator*) _self;\n   FeVariable*\t\t\tcurrVelField\t= self->velocityField;\n   FeVariable*\t\t\tprevVelField\t= self->prevVelField;\n   unsigned\t\t\tnode_i;\n   double\t\t\t\tvel[3];\n\n   for( node_i = 0; node_i < Mesh_GetLocalSize( currVelField->feMesh, MT_VERTEX ); node_i++ ) {\n      FeVariable_GetValueAtNode( currVelField, node_i, vel );\n      FeVariable_SetValueAtNode( prevVelField, node_i, vel );\n   }\n\n   FeVariable_SyncShadowValues( currVelField );\n   FeVariable_SyncShadowValues( prevVelField );\n}\n\n/* cubic Lagrangian interpoation in 1-D */\nvoid InterpLagrange( double x, double* coords, double (*values)[3], unsigned numdofs, double* result ) {\n   unsigned\tnode_i, dof_i;\n   unsigned\totherIndices[3];\n   unsigned\totherIndexCount, otherIndex_i;\n   double\t\tfactor;\n\n   for( dof_i = 0; dof_i < numdofs; dof_i++ )\n      result[dof_i] = 0.0;\n\n   for( node_i = 0; node_i < 4; node_i++ ) {\n      otherIndexCount = 0;\n      for( otherIndex_i = 0; otherIndex_i < 4; otherIndex_i++ )\n         if( otherIndex_i != node_i )\n            otherIndices[otherIndexCount++] = otherIndex_i;\n\n      factor = 1.0;\n      for( otherIndex_i = 0; otherIndex_i < 3; otherIndex_i++ )\n         factor *= ( x - coords[otherIndices[otherIndex_i]] ) / ( coords[node_i] - coords[otherIndices[otherIndex_i]] );\n\n      for( dof_i = 0; dof_i < numdofs; dof_i++ ) {\n         result[dof_i] += ( values[node_i][dof_i] * factor );\n      }\n   }\n}\n\nBool PeriodicUpdate( double* pos, double* min, double* max, unsigned dim, Bool isPeriodic ) {\n  if( pos[dim] < min[dim] ) {\n    pos[dim] = (isPeriodic) ? max[dim] - min[dim] + pos[dim] : min[dim];\n    return True;\n  }\n  if( pos[dim] > max[dim] ) {\n    pos[dim] = (isPeriodic) ? min[dim] - max[dim] + pos[dim] : max[dim];\n    return True;\n  }\n\n  return False;\n}\n\nBool BicubicInterpolatorNew( FeVariable* feVariable, FeVariable* stencilField, double* position, unsigned* sizes, double* result ) {\n  /* Calculated the BicubicInterpolation of the feVariable at position\n   *\n   * Input Args:\n   *   feVariable: the field to be interpolated at `position`.\n   *   stencilField: the field of initial spline stencils for each node.\n   *   position:   the position of interpolatation.\n   *   sizes:      memory chunk of size = sizeof(double)*dim.\n   *   results:    the interpolated value.\n   *\n   *\n   * Returns Values:\n   *  True: if interpolation successful\n   *  False: position is not in 'domain' of local processor\n   */\n\n   FeMesh*\tfeMesh = feVariable->feMesh;\n   unsigned\tnInc ;\n   int    ijk[3];\n   int\t\tx_i, y_i, z_i, *inc;\n   double localMin[3], localMax[3], double_ijk[3];\n   Index  gNode_I, lNode_I, elementIndex;\n   double px[4], py[4], pz[4];\n   unsigned\tnodeIndex[4][4];\n   unsigned\tnode_I3D[4][4][4];\n   unsigned\tnDims   = Mesh_GetDimSize( feMesh );\n   unsigned\tnumdofs = feVariable->dofLayout->dofCounts[0];\n   double   ptsX[4][3], ptsY[4][3], ptsZ[4][3];\n   Bool     inDomain  = True;\n\n   inDomain = Mesh_SearchElements( feMesh, position, &elementIndex ); // get the element id\n\n   if (!inDomain) return False;\n\n   FeMesh_GetElementNodes( feMesh, elementIndex, feVariable->inc ); // get the incidence graph (inc.) of nodes on the element\n   nInc = IArray_GetSize( feVariable->inc );                        // from inc. get the number of nodes on the element\n   inc = IArray_GetPtr( feVariable->inc );                          // get the node ids from inc.\n\n   FeVariable_GetValueAtNode( stencilField, inc[0], &(double_ijk[0]) );\n   ijk[0] = lround(double_ijk[0]);\n   ijk[1] = lround(double_ijk[1]);\n   ijk[2] = lround(double_ijk[2]);\n\n   /* interpolate using Lagrange's formula */\n   if( nDims == 2 ) {\n      for( y_i = 0; y_i < 4; y_i++ )\n         for( x_i = 0; x_i < 4; x_i++ ) {\n            gNode_I = ijk[0] + x_i + ( ijk[1] + y_i ) * sizes[0];\n            if( !Mesh_GlobalToDomain( feMesh, MT_VERTEX, gNode_I, &lNode_I ) ){\n              printf(\"Error in %s, trying to build an interpolation to position (%g, %g) using node %d, a non domain node, in interpolator.\\n\", __func__, position[0], position[1], gNode_I);\n              abort();\n            }\n            else\n               nodeIndex[x_i][y_i] = lNode_I;\n         }\n   }\n   else {\n      for( z_i = 0; z_i < 4; z_i++ )\n         for( y_i = 0; y_i < 4; y_i++ )\n            for( x_i = 0; x_i < 4; x_i++ ) {\n               gNode_I = ijk[0] + x_i + ( ijk[1] + y_i ) * sizes[0] + ( ijk[2] + z_i ) * sizes[0] * sizes[1];\n               if( !Mesh_GlobalToDomain( feMesh, MT_VERTEX, gNode_I, &lNode_I ) ) {\n                 printf(\"Error in %s, trying to build an interpolation to position (%g, %g, %g) using node %d, a non domain node, in interpolator.\\n\", __func__, position[0], position[1], position[2], gNode_I);\n                 abort();\n               }\n               else\n                  node_I3D[x_i][y_i][z_i] = lNode_I;\n            }\n   }\n\n   if( nDims == 3 ) {\n      for( x_i = 0; x_i < 4; x_i++ )\n         px[x_i] = Mesh_GetVertex( feMesh, node_I3D[x_i][0][0] )[0];\n      for( y_i = 0; y_i < 4; y_i++ )\n         py[y_i] = Mesh_GetVertex( feMesh, node_I3D[0][y_i][0] )[1];\n      for( z_i = 0; z_i < 4; z_i++ )\n         pz[z_i] = Mesh_GetVertex( feMesh, node_I3D[0][0][z_i] )[2];\n\n      for( z_i = 0; z_i < 4; z_i++ ) {\n         for( y_i = 0; y_i < 4; y_i++ ) {\n            for( x_i = 0; x_i < 4; x_i++ )\n               FeVariable_GetValueAtNode( feVariable, node_I3D[x_i][y_i][z_i], ptsX[x_i] );\n\n            InterpLagrange( position[0], px, ptsX, numdofs, ptsY[y_i] );\n         }\n\n         InterpLagrange( position[1], py, ptsY, numdofs, ptsZ[z_i] );\n      }\n\n      InterpLagrange( position[2], pz, ptsZ, numdofs, result );\n   }\n   else {\n      for( x_i = 0; x_i < 4; x_i++ )\n         px[x_i] = Mesh_GetVertex( feMesh, nodeIndex[x_i][0] )[0];\n      for( y_i = 0; y_i < 4; y_i++ )\n         py[y_i] = Mesh_GetVertex( feMesh, nodeIndex[0][y_i] )[1];\n\n      for( y_i = 0; y_i < 4; y_i++ ) {\n         for( x_i = 0; x_i < 4; x_i++ )\n            FeVariable_GetValueAtNode( feVariable, nodeIndex[x_i][y_i], ptsX[x_i] );\n\n         InterpLagrange( position[0], px, ptsX, numdofs, ptsY[y_i] );\n      }\n\n      InterpLagrange( position[1], py, ptsY, numdofs, result );\n   }\n\n   return True;\n}\n\n\n\nBool SemiLagrangianIntegrator_PointsAreClose( double* p1, double* p2, int dim, double rtol, double atol ) {\n  /* check if two points are within rtol (relative tolerance) \n   * or atol (absolute tolerance)\n   * \n   * Intput Parameters:\n   *  p1   : point 1\n   *  p2   : point 2\n   *  dim  : the dimensions of points\n   *  rtol : the relative tolerance\n   *  atol : the absolute tolerance\n   *\n   * Return Values:\n   *  True:  if points are close\n   *  False: if points are not close \n   */\n\n  double disp[3], p2_norm, length;\n\n  StGermain_VectorSubtraction(disp, p1, p2, dim); // displacement vector\n  length  = StGermain_VectorMagnitude(disp, dim); // length of vector\n  p2_norm = StGermain_VectorMagnitude(p2, dim);   // original size of p2\n\n  if (length < rtol*p2_norm + atol) return True;\n\n  return False;\n}\n\nvoid SemiLagrangianIntegrator_BuildStaticStencils( FeVariable* stencilField ) {\n  /* Function to build the node indices for cubic interpolation.\n   * The idea is to find a record the starting node indices (ijk) for each interpolant stencil.\n   *\n   * **NOTE**: We never want to Sync the stencilField FeVariable shadow values, ie.\n   *  FeVariable_SyncShadowValues( stencilField ), because the field contains processor\n   *  specific ordering and Syncing with shadow space will produce erroroneous starting indicies\n   *\n   */\n\n  FeMesh* feMesh = stencilField->feMesh;\n  Grid **grid;\n  int d_i,ijk[3];\n  double double_ijk[3];\n  unsigned *sizes,try,nDims,n_i, nNodes;\n  Index gNode_I;\n\n  nDims = Mesh_GetDimSize( feMesh );\n  nNodes = Mesh_GetDomainSize( feMesh, MT_VERTEX );\n  grid = (Grid**)ExtensionManager_Get( feMesh->info, feMesh, feMesh->vertGridId  );\n  sizes = Grid_GetSizes(*grid);\n\n  for( n_i=0; n_i<nNodes; n_i++) {\n    /* For every domain node, build the stencil starting location, ijk */\n    gNode_I = Mesh_DomainToGlobal( feMesh, MT_VERTEX, n_i );\n    Grid_Lift( *grid, gNode_I, ijk );\n\n    /* for every dim try go one node back */\n    for(d_i=0; d_i<nDims; d_i++) {\n      if( ijk[d_i] == 0 ) { continue; } // skip if at 0\n      ijk[d_i]--;\n      try = Grid_Project( *grid, ijk );\n      // if not in domain space don't go back one\n      if( !Mesh_GlobalToDomain( feMesh, MT_VERTEX, try, &try ) ) {\n        ijk[d_i]++;\n      }\n    }\n\n    /* for every dim try go 3 forward */\n    for(d_i=0; d_i<nDims; d_i++) {\n      ijk[d_i]+=3;\n\n      // if we go off the edge, go back one\n      if( ijk[d_i] >= sizes[d_i] ) {\n        ijk[d_i] -= 4;\n        continue;\n      }\n      try = Grid_Project( *grid, ijk );\n      // if not in domain space go back one, else reset\n      if( !Mesh_GlobalToDomain( feMesh, MT_VERTEX, try, &try ) ) {\n        ijk[d_i]-=4;\n      } else {\n        ijk[d_i]-=3;\n      }\n    }\n\n    double_ijk[0] = (double)ijk[0];\n    double_ijk[1] = (double)ijk[1];\n    double_ijk[2] = (double)ijk[2];\n\n    // save ijk as the starting point\n    FeVariable_SetValueAtNode( stencilField, n_i, &(double_ijk[0]) );\n   }\n}\n\n\nvoid SemiLagrangianIntegrator_SolveNew( FeVariable* variableField, double dt, FeVariable* velocityField, FeVariable* varStarField, FeVariable* stencilField ) {\n  /* Function evaluates varStarField - an interpolation of variableField taken at the departure points.\n   * Departure points are positions taken from the nodes and advected backwards along the characteristic curves.\n   * The interpolation method used is a cubic spline and the implementation is only compatible with orthogonal meshes.\n   *\n   * Input Args:\n   *   feVariable:    the original field to be interpolated.\n   *   dt:            the time step size to go backwards along the characteristic, it should NOT be > CFL condition. \n   *   velocityField: the velocity field used to go backward.\n   *   stencilField:  the field of initial spline stencils for each node.\n   *   varStarField:  the resultant field of interpolated variableField taken at the departure points.\n   *\n   */\n\n\n   FeMesh*   feMesh   = variableField->feMesh;\n   unsigned  meshSize = Mesh_GetLocalSize( feMesh, MT_VERTEX );\n   unsigned  nDims    = Mesh_GetDimSize( feMesh );\n   Grid**    nodegrid = (Grid**) Mesh_GetExtension( feMesh, Grid*,  feMesh->vertGridId );\n   unsigned* sizes    = Grid_GetSizes( *nodegrid );\n\n   unsigned  node_I;\n   double    var[3], x_i[3], delta[3], minLength, *x_0;\n   Bool      result;\n   \n   Mesh_GetMinimumSeparation( feMesh, &minLength, delta );\n\n   /* sync parallel field variables to get shadow values */\n   FeVariable_SyncShadowValues( velocityField );\n   FeVariable_SyncShadowValues( variableField );\n   \n   /* assume that the variable mesh is the same as the velocity mesh */\n   for( node_I = 0; node_I < meshSize; node_I++ ) {\n      /* find the position back in time (u*), x_i */\n      x_0 = Mesh_GetVertex(feMesh, node_I);\n      IntegrateRungeKutta( velocityField, dt, x_0, x_i );\n\n      /* if the new x_i is \"close\" to original node, don't Bicubuic Interpolate, take original node value */\n      if( SemiLagrangianIntegrator_PointsAreClose(x_i, x_0, nDims, 0, 1e-6*minLength) ) {\n        FeVariable_GetValueAtNode( variableField, node_I, var );\n      } else {\n        result = BicubicInterpolatorNew(variableField, stencilField, x_i, sizes, var);\n\n        /* if BicubicInerpolator returns false, x_i was not found in domain space.\n         * Fallback to using the node value. */\n        if(result == False) { FeVariable_GetValueAtNode( variableField, node_I, var ); }\n      }\n\n      FeVariable_SetValueAtNode( varStarField, node_I, var );\n   } \n\n   /* sync interpolated values */\n   FeVariable_SyncShadowValues( varStarField );\n}\n\nBool BicubicInterpolator( FeVariable* feVariable, double* position, double* delta, unsigned* nNodes, double* result ) {\n  /* Calculated the BicubicInterpolation of the feVariable at position\n   *\n   * Input Args:\n   *   feVariable: the field to be interpolated at `position`.\n   *   position:   the position of interpolatation.\n   *   delta:      memory chunk of size = sizeof(double)*dim.\n   *   nNodes:     numbers of nodes in ijk representation.\n   *   results:    the interpolated value.\n   *\n   *\n   * Returns Values:\n   *  True: if interpolation successful\n   *  False: position is not in 'domain' of local processor\n   */\n\n   FeMesh*\tfeMesh\t\t\t= feVariable->feMesh;\n   unsigned\tnInc ;\n   int    ijk[3];\n   int\t\tx_i, y_i, z_i, *inc;\n   double localMin[3], localMax[3];\n   Index  gNode_I, lNode_I, elementIndex;\n   double px[4], py[4], pz[4];\n   unsigned\tnodeIndex[4][4];\n   unsigned\tnode_I3D[4][4][4];\n   unsigned\tnDims   = Mesh_GetDimSize( feMesh );\n   unsigned\tnumdofs = feVariable->dofLayout->dofCounts[0];\n   double   ptsX[4][3], ptsY[4][3], ptsZ[4][3];\n   Bool     inDomain  = True;\n\n   inDomain = Mesh_SearchElements( feMesh, position, &elementIndex ); // get the element id\n\n   if (!inDomain) return False;\n\n   FeMesh_GetElementNodes( feMesh, elementIndex, feVariable->inc ); // get the incidence graph (inc.) of nodes on the element\n   nInc = IArray_GetSize( feVariable->inc );                        // from inc. get the number of nodes on the element\n   inc = IArray_GetPtr( feVariable->inc );                          // get the node ids from inc.\n\n   if( nInc % 3 == 0 ) /* quadratic elements */ {\n      delta[0] = Mesh_GetVertex( feMesh, inc[1] )[0] - Mesh_GetVertex( feMesh, inc[0] )[0];\n      delta[1] = Mesh_GetVertex( feMesh, inc[3] )[1] - Mesh_GetVertex( feMesh, inc[0] )[1];\n      if( nDims == 3 )\n         delta[2] = Mesh_GetVertex( feMesh, inc[9] )[2] - Mesh_GetVertex( feMesh, inc[0] )[2];\n   }\n   else {\n      delta[0] = Mesh_GetVertex( feMesh, inc[1] )[0] - Mesh_GetVertex( feMesh, inc[0] )[0];\n      delta[1] = Mesh_GetVertex( feMesh, inc[2] )[1] - Mesh_GetVertex( feMesh, inc[0] )[1];\n      if( nDims == 3 )\n         delta[2] = Mesh_GetVertex( feMesh, inc[4] )[2] - Mesh_GetVertex( feMesh, inc[0] )[2];\n   }\n\n   Mesh_GetLocalCoordRange( feMesh, localMin, localMax );\n   gNode_I = Mesh_DomainToGlobal( feMesh, MT_VERTEX, inc[0] );\n\n   {\n    Grid **grid;\n    int d_i;\n    unsigned *sizes;\n    grid = (Grid**)ExtensionManager_Get( feMesh->info, feMesh, feMesh->vertGridId  );\n    Grid_Lift( *grid, gNode_I, ijk );\n    sizes = Grid_GetSizes(*grid);\n\n    if( nInc % 2 == 0 ) {\n      unsigned try;\n      /* for every dim try go one node back */\n      for(d_i=0; d_i<nDims; d_i++) {\n        if( ijk[d_i] == 0 ) { continue; } // skip if at 0\n        ijk[d_i]--;\n        try = Grid_Project( *grid, ijk );\n        // if not in domain space don't go back one\n        if( !Mesh_GlobalToDomain( feMesh, MT_VERTEX, try, &try ) ) {\n          ijk[d_i]++;\n        }\n      }\n      /* for every dim try go 3 forward */\n      for(d_i=0; d_i<nDims; d_i++) {\n        ijk[d_i]+=3;\n\n        // if we go off the edge, go back one\n        if( ijk[d_i] >= sizes[d_i] ) {\n          ijk[d_i] -= 4;\n          continue;\n        }\n        try = Grid_Project( *grid, ijk );\n        // if not in domain space go back one, else reset\n        if( !Mesh_GlobalToDomain( feMesh, MT_VERTEX, try, &try ) ) {\n          ijk[d_i]-=4;\n        } else {\n          ijk[d_i]-=3;\n        }\n      }\n    }\n   }\n\n   /* interpolate using Lagrange's formula */\n   if( nDims == 2 ) {\n      for( y_i = 0; y_i < 4; y_i++ )\n         for( x_i = 0; x_i < 4; x_i++ ) {\n            gNode_I = ijk[0] + x_i + ( ijk[1] + y_i ) * nNodes[0];\n            if( !Mesh_GlobalToDomain( feMesh, MT_VERTEX, gNode_I, &lNode_I ) ){\n              printf(\"Error in BicubicInterpolator(), trying to build an interpolation to position (%g, %g) using node %d, a non domain node, in interpolator.\\n\", position[0], position[1], gNode_I);\n              abort();\n            }\n            else\n               nodeIndex[x_i][y_i] = lNode_I;\n         }\n   }\n   else {\n      for( z_i = 0; z_i < 4; z_i++ )\n         for( y_i = 0; y_i < 4; y_i++ )\n            for( x_i = 0; x_i < 4; x_i++ ) {\n               gNode_I = ijk[0] + x_i + ( ijk[1] + y_i ) * nNodes[0] + ( ijk[2] + z_i ) * nNodes[0] * nNodes[1];\n               if( !Mesh_GlobalToDomain( feMesh, MT_VERTEX, gNode_I, &lNode_I ) ) {\n                 printf(\"Error in BicubicInterpolator(), trying to build an interpolation to position (%g, %g, %g) using node %d, a non domain node, in interpolator.\\n\", position[0], position[1], position[2], gNode_I);\n                 abort();\n               }\n               else\n                  node_I3D[x_i][y_i][z_i] = lNode_I;\n            }\n   }\n\n   if( nDims == 3 ) {\n      for( x_i = 0; x_i < 4; x_i++ )\n         px[x_i] = Mesh_GetVertex( feMesh, node_I3D[x_i][0][0] )[0];\n      for( y_i = 0; y_i < 4; y_i++ )\n         py[y_i] = Mesh_GetVertex( feMesh, node_I3D[0][y_i][0] )[1];\n      for( z_i = 0; z_i < 4; z_i++ )\n         pz[z_i] = Mesh_GetVertex( feMesh, node_I3D[0][0][z_i] )[2];\n\n      for( z_i = 0; z_i < 4; z_i++ ) {\n         for( y_i = 0; y_i < 4; y_i++ ) {\n            for( x_i = 0; x_i < 4; x_i++ )\n               FeVariable_GetValueAtNode( feVariable, node_I3D[x_i][y_i][z_i], ptsX[x_i] );\n\n            InterpLagrange( position[0], px, ptsX, numdofs, ptsY[y_i] );\n         }\n\n         InterpLagrange( position[1], py, ptsY, numdofs, ptsZ[z_i] );\n      }\n\n      InterpLagrange( position[2], pz, ptsZ, numdofs, result );\n   }\n   else {\n      for( x_i = 0; x_i < 4; x_i++ )\n         px[x_i] = Mesh_GetVertex( feMesh, nodeIndex[x_i][0] )[0];\n      for( y_i = 0; y_i < 4; y_i++ )\n         py[y_i] = Mesh_GetVertex( feMesh, nodeIndex[0][y_i] )[1];\n\n      for( y_i = 0; y_i < 4; y_i++ ) {\n         for( x_i = 0; x_i < 4; x_i++ )\n            FeVariable_GetValueAtNode( feVariable, nodeIndex[x_i][y_i], ptsX[x_i] );\n\n         InterpLagrange( position[0], px, ptsX, numdofs, ptsY[y_i] );\n      }\n\n      InterpLagrange( position[1], py, ptsY, numdofs, result );\n   }\n\n   return True;\n}\n\n\nvoid SemiLagrangianIntegrator_Solve( void* slIntegrator, FeVariable* variableField, FeVariable* varStarField ) {\n   SemiLagrangianIntegrator*\tself \t\t     = (SemiLagrangianIntegrator*)slIntegrator;\n   FiniteElementContext*\t\tcontext\t\t     = self->context;\n   unsigned\t\t\tnode_I;\n   FeMesh*\t\t\tfeMesh\t\t     = variableField->feMesh;\n   unsigned\t\t\tmeshSize\t     = Mesh_GetLocalSize( feMesh, MT_VERTEX );\n   FeVariable*\t\t\tvelocityField\t     = self->velocityField;\n   double\t\t\t\tdt\t\t     = AbstractContext_Dt( context );\n   unsigned\t\t\tdim_I;\n   unsigned\t\t\tnDims\t\t     = Mesh_GetDimSize( feMesh );\n   double\t\t\t\tposition[3];\n   double\t\t\t\tvar[3];\n   Grid**\t\t\t\tgrid\t\t     = (Grid**) Mesh_GetExtension( feMesh, Grid*,  feMesh->elGridId );\n   unsigned*    sizes\t\t     = Grid_GetSizes( *grid );\n   unsigned\t\t\tnNodes[3];\n   double\t\t\t\tdelta[3];\n   unsigned\t\t\tnInc;\n   int*         inc;\n\n   FeMesh_GetElementNodes( variableField->feMesh, 0, variableField->inc );\n   nInc = IArray_GetSize( variableField->inc );\n   inc = IArray_GetPtr( variableField->inc );\n\n   delta[0] = Mesh_GetVertex( feMesh, inc[1] )[0] - Mesh_GetVertex( feMesh, inc[0] )[0];\n   if( nInc % 3 == 0 ) /* quadratic elements */ {\n      delta[1] = Mesh_GetVertex( feMesh, inc[3] )[1] - Mesh_GetVertex( feMesh, inc[0] )[1];\n      if( nDims == 3 )\n         delta[2] = Mesh_GetVertex( feMesh, inc[9] )[2] - Mesh_GetVertex( feMesh, inc[0] )[2];\n      for( dim_I = 0; dim_I < nDims; dim_I++ )\n         nNodes[dim_I] = 2 * sizes[dim_I] + 1;\n   }\n   else {\n      delta[1] = Mesh_GetVertex( feMesh, inc[2] )[1] - Mesh_GetVertex( feMesh, inc[0] )[1];\n      if( nDims == 3 )\n         delta[2] = Mesh_GetVertex( feMesh, inc[4] )[2] - Mesh_GetVertex( feMesh, inc[0] )[2];\n\n      for( dim_I = 0; dim_I < nDims; dim_I++ )\n         nNodes[dim_I] = sizes[dim_I] + 1;\n   }\n\n   FeVariable_SyncShadowValues( velocityField );\n   FeVariable_SyncShadowValues( variableField );\n\n   /* assume that the variable mesh is the same as the velocity mesh */\n   for( node_I = 0; node_I < meshSize; node_I++ ) {\n      /* find the position back in time (u*) */\n      IntegrateRungeKutta( velocityField, dt, Mesh_GetVertex(feMesh, node_I), position );\n\n      /* create a bicubic interpolation of variableField at u* */\n      BicubicInterpolator( variableField, position, delta, nNodes, var );\n\n      FeVariable_SetValueAtNode( varStarField, node_I, var );\n   }\n   FeVariable_SyncShadowValues( varStarField );\n}\n", "meta": {"hexsha": "74449ba60667dca412a76ec8b162cacbb104dcea", "size": 36483, "ext": "c", "lang": "C", "max_stars_repo_path": "underworld/libUnderworld/StgFEM/Utils/src/SemiLagrangianIntegrator.c", "max_stars_repo_name": "longgangfan/underworld2", "max_stars_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 116.0, "max_stars_repo_stars_event_min_datetime": "2015-09-28T10:30:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T04:12:38.000Z", "max_issues_repo_path": "underworld/libUnderworld/StgFEM/Utils/src/SemiLagrangianIntegrator.c", "max_issues_repo_name": "longgangfan/underworld2", "max_issues_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 561.0, "max_issues_repo_issues_event_min_datetime": "2015-09-29T06:05:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T23:37:29.000Z", "max_forks_repo_path": "underworld/libUnderworld/StgFEM/Utils/src/SemiLagrangianIntegrator.c", "max_forks_repo_name": "longgangfan/underworld2", "max_forks_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 68.0, "max_forks_repo_forks_event_min_datetime": "2015-12-14T21:57:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-25T04:54:26.000Z", "avg_line_length": 41.8383027523, "max_line_length": 218, "alphanum_fraction": 0.6416687224, "num_tokens": 10937, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25386099567919973, "lm_q2_score": 0.026759282700350304, "lm_q1q2_score": 0.006793138149972113}}
{"text": "/************************************************************************\n Tuple.h.h - Copyright marcello\n\n Here you can write a license for your code, some comments or any other\n information you want to have in your generated code. To to this simply\n configure the \"headings\" directory in uml to point to a directory\n where you have your heading files.\n\n or you can just replace the contents of this file with your own.\n If you want to do this, this file is located at\n\n /usr/share/apps/umbrello/headings/heading.h\n\n -->Code Generators searches for heading files based on the file extension\n i.e. it will look for a file name ending in \".h\" to include in C++ header\n files, and for a file name ending in \".java\" to include in all generated\n java code.\n If you name the file \"heading.<extension>\", Code Generator will always\n choose this file even if there are other files with the same extension in the\n directory. If you name the file something else, it must be the only one with that\n extension in the directory to guarantee that Code Generator will choose it.\n\n you can use variables in your heading files which are replaced at generation\n time. possible variables are : author, date, time, filename and filepath.\n just write %variable_name%\n\n This file was generated on Sat Nov 10 2007 at 15:05:38\n The original location of this file is /home/marcello/Projects/fitted/Developing/Tuple.h\n **************************************************************************/\n\n#ifndef TUPLE_H\n#define TUPLE_H\n\n#include <fstream>\n#include <vector>\n//#include <gsl/gsl_vector.h>\n\n//<< Sam\ntypedef enum\n{\n  L1,\n  L2,\n  Linfty\n} NormType;\n\nusing namespace std;\n\nnamespace PoliFitted\n{\n\n/**\n * Tuples are sequence containers representing arrays with additional functionalities.\n *\n * Just like arrays, tuples use contiguous storage locations for their elements, which\n * means that their elements can also be accessed using offsets on regular pointers to its elements,\n * and just as efficiently as in arrays.\n *\n * Like arrays, internally, tuples do not store information about the dimension that must be handled\n * manually from outside the class.\n */\nclass Tuple\n{\n  public:\n\n    /**\n     * Converts N vectors to a single tuple obtained by\n     * concatenation of the vectors (double) in the given order\n     * Vectors are received as sequence of const_iterator:\n     * v1.begin, v1.end, v2.begin, v2.end, v3.begin ...\n     *\n     * @param count    final number of elements of the tuple.\n     Sum of size of each vector\n     * @param ...      sequence of const_iterator (begin,end,begin,end,...)\n     * @return the reference of the new tuple\n     */\n    //static Tuple* CONVERT(unsigned int count, ...);\n\n    // Constructors/Destructors\n    //\n\n    /**\n     * Empty Constructor\n     */\n    Tuple();\n\n    /**\n     * Construct a tuple of specified size\n     * @param size the size of the tuple\n     */\n    Tuple(unsigned int size);\n\n    /**\n     * Empty Destructor\n     */\n    ~Tuple();\n\n    /**\n     * Returns a reference to the element at position \\f$pos\\f$ in the tuple.\n     *\n     * Programs should never call this function with an argument \\f$pos\\f$ that is\n     * out of range, since this causes undefined behavior.\n     * @brief Access element\n     * @param pos Position of an element in the container. Notice that the first element has a position of 0 (not 1).\n     * @return The element at the specified position in the tuple.\n     */\n    float& operator[](const unsigned int pos);\n\n    /**\n     * Returns a reference to the element at position \\f$pos\\f$ in the tuple.\n     *\n     * The function does not automatically check whether \\f$pos\\f$ is within the\n     * bounds of valid elements in the vector.\n     * Programs should never call this function with an argument \\f$pos\\f$ that is\n     * out of range, since this causes undefined behavior.\n     *\n     * @brief Access element\n     * @param pos Position of an element in the container. Notice that the first element has a position of 0 (not 1).\n     * @return The element at the specified position in the container.\n     */\n    float& at(const unsigned int pos);\n\n    /**\n     * Compute a distance between the current and a given tuple. In other words,\n     * it computes the p-norm between tuples.\n     * \\a p must be one of: \"L1\", \"L2\", \"Linfty\". \"L1\" is the absolute distance,\n     * \"L2\" is the Euclidean distance, and \"Linfty\" is the maximum norm.\n     * The norm is computed taking into account the first \\a size elements of\n     * the current and given tuples.\n     *\n     * Programs should never call this function with an argument \\f$size\\f$ that is\n     * out of range for one of the two tuples, since this causes undefined behavior.\n     *\n     * @brief Distance computation\n     * @param t An other tuple.\n     * @param size the number of elements to be considered.\n     * @param type the norm type\n     * @return the \\a p-norm\n     */\n    float Distance(Tuple* t, unsigned int size, NormType type = L2);\n\n    /**\n     * Assigns new contents to the tuple, replacing its current contents, without modifying its size.\n     *\n     * Since the dimension of the tuple is not changed accordingly to the given array,\n     * the behavior is undefined when \\a size is greater than the current tuple dimension.\n     * In this case it is necessary to call the complementary function Tuple::Resize.\n     *\n     * The tuple is filled starting from the first elements.\n     *\n     * @brief Assign elements\n     * @param values Array storing the new elements.\n     * @param size The size of the given array\n     */\n    void SetValues(float* values, unsigned int size);\n\n    /**\n     * Returns a direct pointer to the memory array used internally by the tuple to store its owned elements.\n     *\n     * Because elements in the tuple are guaranteed to be stored in contiguous storage locations in the same\n     * order as represented by the tuple, the pointer retrieved can be offset to access any element in the array.\n     * @brief Access data\n     * @return A pointer to the first element in the array used internally by the tuple.\n     */\n    float* GetValues();\n\n    /**\n     * Returns a clone of the tuple by copying the first \\a input_size elements.\n     *\n     * @brief Clone object\n     * @param input_size the number of elements to be copied\n     * @return A pointer to the new tuple.\n     */\n    Tuple* Clone(unsigned int input_size);\n\n    /**\n     * Resizes the container so that it contains \\a new_size elements.\n     *\n     * If \\a new_size is smaller than the current container size, the content is reduced to its first n elements,\n     * removing those beyond (and destroying them).\n     * If \\a new_size is greater than the current container size, the content is expanded by inserting at the end\n     * as many elements as needed to reach a size of \\a new_size.\n     * The value of the newly allocated portion is indeterminate.\n     *\n     * Notice that this function changes the actual content of the container by inserting or erasing elements\n     * from it.\n     *\n     * @brief Change size\n     * @param new_size New container size, expressed in number of elements.\n     */\n    void Resize(unsigned int new_size);\n\n    template<class T>\n    T* GetValues(unsigned int input_size);\n\n    //gsl_vector* GetGSLVector(unsigned int input_size);\n\n    std::vector<double> ToVector(unsigned int input_size);\n\n  protected:\n\n  private:\n\n    float* mValues;\n\n};\n\ninline float& Tuple::at(const unsigned int pos)\n{\n  return mValues[pos];\n}\n\ninline float& Tuple::operator[](const unsigned int pos)\n{\n  return mValues[pos];\n}\n\ninline void Tuple::SetValues(float* values, unsigned int size)\n{\n  for (unsigned int i = 0; i < size; i++)\n  {\n    mValues[i] = values[i];\n  }\n}\n\ninline float* Tuple::GetValues()\n{\n  return mValues;\n}\n\ntemplate<class T>\ninline T* Tuple::GetValues(unsigned int input_size)\n{\n  T* values = new T[input_size];\n  for (unsigned int i = 0; i < input_size; i++)\n  {\n    values[i] = (T) mValues[i];\n  }\n  return values;\n}\n\n/*inline gsl_vector* Tuple::GetGSLVector(unsigned int input_size)\n {\n gsl_vector* values = gsl_vector_alloc(input_size);\n for (unsigned int i = 0; i < input_size; i++)\n {\n gsl_vector_set(values, i, mValues[i]);\n }\n return values;\n }*/\n\ninline std::vector<double> Tuple::ToVector(unsigned int input_size)\n{\n  std::vector<double> values;\n  for (unsigned int i = 0; i < input_size; i++)\n  {\n    values.push_back(mValues[i]);\n  }\n  return values;\n}\n\n}\n\n#endif // TUPLE_H\n", "meta": {"hexsha": "d4f014027a4b32d2c226a90f4313284eb91e1407", "size": 8462, "ext": "h", "lang": "C", "max_stars_repo_path": "cpp_models/libsrc/RLLib/util/TreeFitted/Tuple.h", "max_stars_repo_name": "akangasr/sdirl", "max_stars_repo_head_hexsha": "b8b2bf34fea1b1f0c2f9961a9ad9c1ad34396f5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp_models/libsrc/RLLib/util/TreeFitted/Tuple.h", "max_issues_repo_name": "akangasr/sdirl", "max_issues_repo_head_hexsha": "b8b2bf34fea1b1f0c2f9961a9ad9c1ad34396f5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp_models/libsrc/RLLib/util/TreeFitted/Tuple.h", "max_forks_repo_name": "akangasr/sdirl", "max_forks_repo_head_hexsha": "b8b2bf34fea1b1f0c2f9961a9ad9c1ad34396f5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.053030303, "max_line_length": 117, "alphanum_fraction": 0.6733632711, "num_tokens": 1963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.256832002764217, "lm_q2_score": 0.02635535504477578, "lm_q1q2_score": 0.006768898619711775}}
{"text": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#pragma once\n#ifndef COMMON_H\n#define COMMON_H\n\n// Since we call cblas_dgemm in openmp for loop,\n// we call \"extension\" APIs for setting the number of threads.\n#ifdef USE_INTEL_MKL\n#include <mkl.h>\n\t#if INTEL_MKL_VERSION < 20170000\n\t\t// Will throw an error at development time in non-standard settings\n\t\tPLEASE DONOT COMPILE SHARED LIBRARIES WITH OLDER MKL VERSIONS\n\t#endif\n#include <mkl_service.h>\nextern \"C\" void mkl_set_num_threads(int numThreads);\n#else\n#include <cblas.h>\nextern \"C\" void openblas_set_num_threads(int numThreads);\n#endif\n\ntemplate<class FP>\nsize_t computeNNZ(FP* arr, int limit) {\n    size_t nnz = 0;\n#ifndef USE_INTEL_MKL\n#pragma omp parallel for reduction(+: nnz)\n#endif\n    for(int i=0; i<limit; i++)\n        nnz += (arr[i]!=0) ? 1 : 0;\n    return nnz;\n}\n\nstatic int SYSDS_CURRENT_NUM_THREADS = -1;\nstatic void setNumThreadsForBLAS(int numThreads) {\n\tif (SYSDS_CURRENT_NUM_THREADS != numThreads) {\n#ifdef USE_OPEN_BLAS\n\t\topenblas_set_num_threads(numThreads);\n#else\n\t\tmkl_set_num_threads(numThreads);\n#endif\n\t\tSYSDS_CURRENT_NUM_THREADS = numThreads;\n\t}\n}\n\n#endif // COMMON_H\n", "meta": {"hexsha": "34f98017655cb56730cc24264ba412d49ac3c3ef", "size": 1907, "ext": "h", "lang": "C", "max_stars_repo_path": "src/main/cpp/common.h", "max_stars_repo_name": "Shafaq-Siddiqi/systemml", "max_stars_repo_head_hexsha": "eca11c6fe9cff88df2e1960caf1b0cff9bf2b2b6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 372.0, "max_stars_repo_stars_event_min_datetime": "2017-06-09T01:02:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-24T05:45:00.000Z", "max_issues_repo_path": "src/main/cpp/common.h", "max_issues_repo_name": "ywcb00/systemds", "max_issues_repo_head_hexsha": "5cc523971854cdf4f22e6199987a86e213fae4e2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 418.0, "max_issues_repo_issues_event_min_datetime": "2017-06-08T16:27:44.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-25T12:15:54.000Z", "max_forks_repo_path": "src/main/cpp/common.h", "max_forks_repo_name": "ywcb00/systemds", "max_forks_repo_head_hexsha": "5cc523971854cdf4f22e6199987a86e213fae4e2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 190.0, "max_forks_repo_forks_event_min_datetime": "2017-06-08T19:32:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-15T12:26:12.000Z", "avg_line_length": 30.2698412698, "max_line_length": 69, "alphanum_fraction": 0.7477713686, "num_tokens": 493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23370636758849891, "lm_q2_score": 0.028870910288603967, "lm_q1q2_score": 0.0067473155725230535}}
{"text": "#pragma once\n\n#include \"Cesium3DTiles/Library.h\"\n#include \"CesiumGltf/Model.h\"\n#include <functional>\n#include <glm/mat4x4.hpp>\n#include <gsl/span>\n#include <optional>\n\nnamespace Cesium3DTiles {\n\n/**\n * @brief Functions for loading and processing glTF models.\n *\n * This class offers basic functions for loading glTF models as\n * `CesiumGltf::Model` instances, and for processing the mesh primitives that\n * appear in the resulting models.\n */\nclass CESIUM3DTILES_API Gltf final {\n\npublic:\n  /** @brief This class cannot be instantiated */\n  Gltf() = delete;\n\n  /**\n   * @brief A callback function for {@link Gltf::forEachPrimitiveInScene}.\n   */\n  typedef void ForEachPrimitiveInSceneCallback(\n      CesiumGltf::Model& gltf,\n      CesiumGltf::Node& node,\n      CesiumGltf::Mesh& mesh,\n      CesiumGltf::MeshPrimitive& primitive,\n      const glm::dmat4& transform);\n\n  /**\n   * @brief Apply the given callback to all relevant primitives.\n   *\n   * If the given `sceneID` is non-negative and exists in the given glTF,\n   * then the given callback will be applied to all meshes of this scene.\n   *\n   * If the given `sceneId` is negative, then the meshes that the callback\n   * will be applied to depends on the structure of the glTF model:\n   *\n   * * If the glTF model has a default scene, then it will\n   *   be applied to all meshes of the default scene.\n   * * Otherwise, it will be applied to all meshes of the the first scene.\n   * * Otherwise (if the glTF model does not contain any scenes), it will\n   *   be applied to all meshes that can be found by starting a traversal\n   *   at the root node.\n   * * Otherwise (if there are no scenes and no nodes), then all meshes\n   *   will be traversed.\n   *\n   * @param gltf The glTF model.\n   * @param sceneID The scene ID (index)\n   * @param callback The callback to apply\n   */\n  static void forEachPrimitiveInScene(\n      CesiumGltf::Model& gltf,\n      int sceneID,\n      std::function<ForEachPrimitiveInSceneCallback>&& callback);\n\n  /**\n   * @brief A callback function for {@link Gltf::forEachPrimitiveInScene}.\n   */\n  typedef void ForEachPrimitiveInSceneConstCallback(\n      const CesiumGltf::Model& gltf,\n      const CesiumGltf::Node& node,\n      const CesiumGltf::Mesh& mesh,\n      const CesiumGltf::MeshPrimitive& primitive,\n      const glm::dmat4& transform);\n\n  /** @copydoc Gltf::forEachPrimitiveInScene() */\n  static void forEachPrimitiveInScene(\n      const CesiumGltf::Model& gltf,\n      int sceneID,\n      std::function<ForEachPrimitiveInSceneConstCallback>&& callback);\n};\n\n} // namespace Cesium3DTiles\n", "meta": {"hexsha": "648931f8ea345d6dc5e8e7eabde7c3bf574a85d0", "size": 2571, "ext": "h", "lang": "C", "max_stars_repo_path": "Cesium3DTiles/include/Cesium3DTiles/Gltf.h", "max_stars_repo_name": "zy6p/cesium-native", "max_stars_repo_head_hexsha": "d7b02d0c229e54e626e313bf2cfab31ed6e8ac3b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-27T04:47:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-27T04:47:23.000Z", "max_issues_repo_path": "Cesium3DTiles/include/Cesium3DTiles/Gltf.h", "max_issues_repo_name": "zy6p/cesium-native", "max_issues_repo_head_hexsha": "d7b02d0c229e54e626e313bf2cfab31ed6e8ac3b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cesium3DTiles/include/Cesium3DTiles/Gltf.h", "max_forks_repo_name": "zy6p/cesium-native", "max_forks_repo_head_hexsha": "d7b02d0c229e54e626e313bf2cfab31ed6e8ac3b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1375, "max_line_length": 77, "alphanum_fraction": 0.6993387787, "num_tokens": 677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19436781101874465, "lm_q2_score": 0.03461884008418183, "lm_q1q2_score": 0.006728788167170397}}
{"text": "/* vector/gsl_vector_long_double.h\r\n * \r\n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\r\n * \r\n * This program is free software; you can redistribute it and/or modify\r\n * it under the terms of the GNU General Public License as published by\r\n * the Free Software Foundation; either version 3 of the License, or (at\r\n * your option) any later version.\r\n * \r\n * This program is distributed in the hope that it will be useful, but\r\n * WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n * General Public License for more details.\r\n * \r\n * You should have received a copy of the GNU General Public License\r\n * along with this program; if not, write to the Free Software\r\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r\n */\r\n\r\n#ifndef __GSL_VECTOR_LONG_DOUBLE_H__\r\n#define __GSL_VECTOR_LONG_DOUBLE_H__\r\n\r\n#if !defined( GSL_FUN )\r\n#  if !defined( GSL_DLL )\r\n#    define GSL_FUN extern\r\n#  elif defined( BUILD_GSL_DLL )\r\n#    define GSL_FUN extern __declspec(dllexport)\r\n#  else\r\n#    define GSL_FUN extern __declspec(dllimport)\r\n#  endif\r\n#endif\r\n\r\n#include <stdlib.h>\r\n#include <gsl/gsl_types.h>\r\n#include <gsl/gsl_errno.h>\r\n#include <gsl/gsl_inline.h>\r\n#include <gsl/gsl_check_range.h>\r\n#include <gsl/gsl_block_long_double.h>\r\n\r\n#undef __BEGIN_DECLS\r\n#undef __END_DECLS\r\n#ifdef __cplusplus\r\n# define __BEGIN_DECLS extern \"C\" {\r\n# define __END_DECLS }\r\n#else\r\n# define __BEGIN_DECLS /* empty */\r\n# define __END_DECLS /* empty */\r\n#endif\r\n\r\n__BEGIN_DECLS\r\n\r\ntypedef struct \r\n{\r\n  size_t size;\r\n  size_t stride;\r\n  long double *data;\r\n  gsl_block_long_double *block;\r\n  int owner;\r\n} \r\ngsl_vector_long_double;\r\n\r\ntypedef struct\r\n{\r\n  gsl_vector_long_double vector;\r\n} _gsl_vector_long_double_view;\r\n\r\ntypedef _gsl_vector_long_double_view gsl_vector_long_double_view;\r\n\r\ntypedef struct\r\n{\r\n  gsl_vector_long_double vector;\r\n} _gsl_vector_long_double_const_view;\r\n\r\ntypedef const _gsl_vector_long_double_const_view gsl_vector_long_double_const_view;\r\n\r\n\r\n/* Allocation */\r\n\r\nGSL_FUN gsl_vector_long_double *gsl_vector_long_double_alloc (const size_t n);\r\nGSL_FUN gsl_vector_long_double *gsl_vector_long_double_calloc (const size_t n);\r\n\r\nGSL_FUN gsl_vector_long_double *gsl_vector_long_double_alloc_from_block (gsl_block_long_double * b,\r\n                                                     const size_t offset, \r\n                                                     const size_t n, \r\n                                                     const size_t stride);\r\n\r\nGSL_FUN gsl_vector_long_double *gsl_vector_long_double_alloc_from_vector (gsl_vector_long_double * v,\r\n                                                      const size_t offset, \r\n                                                      const size_t n, \r\n                                                      const size_t stride);\r\n\r\nGSL_FUN void gsl_vector_long_double_free (gsl_vector_long_double * v);\r\n\r\n/* Views */\r\n\r\nGSL_FUN _gsl_vector_long_double_view \r\ngsl_vector_long_double_view_array (long double *v, size_t n);\r\n\r\nGSL_FUN _gsl_vector_long_double_view \r\ngsl_vector_long_double_view_array_with_stride (long double *base,\r\n                                         size_t stride,\r\n                                         size_t n);\r\n\r\nGSL_FUN _gsl_vector_long_double_const_view \r\ngsl_vector_long_double_const_view_array (const long double *v, size_t n);\r\n\r\nGSL_FUN _gsl_vector_long_double_const_view \r\ngsl_vector_long_double_const_view_array_with_stride (const long double *base,\r\n                                               size_t stride,\r\n                                               size_t n);\r\n\r\nGSL_FUN _gsl_vector_long_double_view \r\ngsl_vector_long_double_subvector (gsl_vector_long_double *v, \r\n                            size_t i, \r\n                            size_t n);\r\n\r\nGSL_FUN _gsl_vector_long_double_view \r\ngsl_vector_long_double_subvector_with_stride (gsl_vector_long_double *v, \r\n                                        size_t i,\r\n                                        size_t stride,\r\n                                        size_t n);\r\n\r\nGSL_FUN _gsl_vector_long_double_const_view \r\ngsl_vector_long_double_const_subvector (const gsl_vector_long_double *v, \r\n                                  size_t i, \r\n                                  size_t n);\r\n\r\nGSL_FUN _gsl_vector_long_double_const_view \r\ngsl_vector_long_double_const_subvector_with_stride (const gsl_vector_long_double *v, \r\n                                              size_t i, \r\n                                              size_t stride,\r\n                                              size_t n);\r\n\r\n/* Operations */\r\n\r\nGSL_FUN void gsl_vector_long_double_set_zero (gsl_vector_long_double * v);\r\nGSL_FUN void gsl_vector_long_double_set_all (gsl_vector_long_double * v, long double x);\r\nGSL_FUN int gsl_vector_long_double_set_basis (gsl_vector_long_double * v, size_t i);\r\n\r\nGSL_FUN int gsl_vector_long_double_fread (FILE * stream, gsl_vector_long_double * v);\r\nGSL_FUN int gsl_vector_long_double_fwrite (FILE * stream, const gsl_vector_long_double * v);\r\nGSL_FUN int gsl_vector_long_double_fscanf (FILE * stream, gsl_vector_long_double * v);\r\nGSL_FUN int gsl_vector_long_double_fprintf (FILE * stream, const gsl_vector_long_double * v,\r\n                              const char *format);\r\n\r\nGSL_FUN int gsl_vector_long_double_memcpy (gsl_vector_long_double * dest, const gsl_vector_long_double * src);\r\n\r\nGSL_FUN int gsl_vector_long_double_reverse (gsl_vector_long_double * v);\r\n\r\nGSL_FUN int gsl_vector_long_double_swap (gsl_vector_long_double * v, gsl_vector_long_double * w);\r\nGSL_FUN int gsl_vector_long_double_swap_elements (gsl_vector_long_double * v, const size_t i, const size_t j);\r\n\r\nGSL_FUN long double gsl_vector_long_double_max (const gsl_vector_long_double * v);\r\nGSL_FUN long double gsl_vector_long_double_min (const gsl_vector_long_double * v);\r\nGSL_FUN void gsl_vector_long_double_minmax (const gsl_vector_long_double * v, long double * min_out, long double * max_out);\r\n\r\nGSL_FUN size_t gsl_vector_long_double_max_index (const gsl_vector_long_double * v);\r\nGSL_FUN size_t gsl_vector_long_double_min_index (const gsl_vector_long_double * v);\r\nGSL_FUN void gsl_vector_long_double_minmax_index (const gsl_vector_long_double * v, size_t * imin, size_t * imax);\r\n\r\nGSL_FUN int gsl_vector_long_double_add (gsl_vector_long_double * a, const gsl_vector_long_double * b);\r\nGSL_FUN int gsl_vector_long_double_sub (gsl_vector_long_double * a, const gsl_vector_long_double * b);\r\nGSL_FUN int gsl_vector_long_double_mul (gsl_vector_long_double * a, const gsl_vector_long_double * b);\r\nGSL_FUN int gsl_vector_long_double_div (gsl_vector_long_double * a, const gsl_vector_long_double * b);\r\nGSL_FUN int gsl_vector_long_double_scale (gsl_vector_long_double * a, const double x);\r\nGSL_FUN int gsl_vector_long_double_add_constant (gsl_vector_long_double * a, const double x);\r\n\r\nGSL_FUN int gsl_vector_long_double_isnull (const gsl_vector_long_double * v);\r\nGSL_FUN int gsl_vector_long_double_ispos (const gsl_vector_long_double * v);\r\nGSL_FUN int gsl_vector_long_double_isneg (const gsl_vector_long_double * v);\r\nGSL_FUN int gsl_vector_long_double_isnonneg (const gsl_vector_long_double * v);\r\n\r\nGSL_FUN INLINE_DECL long double gsl_vector_long_double_get (const gsl_vector_long_double * v, const size_t i);\r\nGSL_FUN INLINE_DECL void gsl_vector_long_double_set (gsl_vector_long_double * v, const size_t i, long double x);\r\nGSL_FUN INLINE_DECL long double * gsl_vector_long_double_ptr (gsl_vector_long_double * v, const size_t i);\r\nGSL_FUN INLINE_DECL const long double * gsl_vector_long_double_const_ptr (const gsl_vector_long_double * v, const size_t i);\r\n\r\n#ifdef HAVE_INLINE\r\n\r\nINLINE_FUN\r\nlong double\r\ngsl_vector_long_double_get (const gsl_vector_long_double * v, const size_t i)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(i >= v->size))\r\n    {\r\n      GSL_ERROR_VAL (\"index out of range\", GSL_EINVAL, 0);\r\n    }\r\n#endif\r\n  return v->data[i * v->stride];\r\n}\r\n\r\nINLINE_FUN\r\nvoid\r\ngsl_vector_long_double_set (gsl_vector_long_double * v, const size_t i, long double x)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(i >= v->size))\r\n    {\r\n      GSL_ERROR_VOID (\"index out of range\", GSL_EINVAL);\r\n    }\r\n#endif\r\n  v->data[i * v->stride] = x;\r\n}\r\n\r\nINLINE_FUN\r\nlong double *\r\ngsl_vector_long_double_ptr (gsl_vector_long_double * v, const size_t i)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(i >= v->size))\r\n    {\r\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\r\n    }\r\n#endif\r\n  return (long double *) (v->data + i * v->stride);\r\n}\r\n\r\nINLINE_FUN\r\nconst long double *\r\ngsl_vector_long_double_const_ptr (const gsl_vector_long_double * v, const size_t i)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(i >= v->size))\r\n    {\r\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\r\n    }\r\n#endif\r\n  return (const long double *) (v->data + i * v->stride);\r\n}\r\n#endif /* HAVE_INLINE */\r\n\r\n__END_DECLS\r\n\r\n#endif /* __GSL_VECTOR_LONG_DOUBLE_H__ */\r\n\r\n\r\n", "meta": {"hexsha": "abd22aa6ced4461b73567adb2f739fc8aa840a49", "size": 9057, "ext": "h", "lang": "C", "max_stars_repo_path": "deps/include/gsl/gsl_vector_long_double.h", "max_stars_repo_name": "berkus/music-cs", "max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "deps/include/gsl/gsl_vector_long_double.h", "max_issues_repo_name": "berkus/music-cs", "max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "deps/include/gsl/gsl_vector_long_double.h", "max_forks_repo_name": "berkus/music-cs", "max_forks_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.0546218487, "max_line_length": 125, "alphanum_fraction": 0.69813404, "num_tokens": 2074, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22541660542786957, "lm_q2_score": 0.02976009652753961, "lm_q1q2_score": 0.0067084199364437075}}
{"text": "#ifndef SPC_UTILS_H\n#define SPC_UTILS_H\n\nvoid init_search (const char *string);  /* Pbmsrch.C      */\nchar *strsearch (const char *string);   /* Pbmsrch.C      */\n\n\n#include <stddef.h>\n#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <ctype.h>\n#include <limits.h>\n#include <math.h>\n\n#include <gsl/gsl_version.h>\n#include <gsl/gsl_nan.h>\n#include <gsl/gsl_sys.h>\n#include <gsl/gsl_vector.h>\n\n#include \"aXe_errors.h\"\n#include \"aXe_grism.h\"\n\n#define LAMBDACENTRAL 8000.0\n#define COLNAMELENGTH 12\n#define MAXCOLS       200\n\n/**\n * Structure: sexcol\n * Structure for a column header\n */\ntypedef struct sexcol\n{\n  char name[COLNAMELENGTH];\n  int  number;\n}\nsexcol;\n\n/**\n * Structure: colinfo\n * Structure for the table header\n */\ntypedef struct colinfo\n{\n  int numcols;\n  sexcol columns[MAXCOLS];\n}\ncolinfo;\n\nextern int\nis_valid_entry(double mag);\n\nextern int\nget_valid_entries(const gsl_vector *magnitudes);\n\nextern int\ncheck_worldcoo_input(const colinfo * actcatinfo, const int thsky);\n\nextern int\ncheck_imagecoo_input(const colinfo * actcatinfo);\n\nextern void\nmake_GOL_header(FILE *fout, const colinfo * actcatinfo,\n                const gsl_vector * waves, const gsl_vector * cnums,\n                const px_point backwin_cols, const px_point modinfo_cols);\n\nextern colinfo *\nget_sex_col_descr (char *filename);\n\nextern double\nget_col_value (const colinfo * actcatinfo, const char key[],\n               gsl_vector * v, int fatal);\n\nextern double\nget_col_value2 (const colinfo * actcatinfo, const char key[],\n                gsl_vector * v, int fatal);\n\nextern int\nline_is_valid (const colinfo * actcatinfo, char line[]);\n\nextern int\nget_magauto_col(const gsl_vector *wavelength, const gsl_vector *colnums,\n                const double lambda_mark);\n\nextern int\nhas_magnitudes(const colinfo * actcatinfo);\n\nextern px_point\nhas_backwindow(const colinfo * actcatinfo);\n\nextern px_point\nhas_modelinfo(const colinfo * actcatinfo);\n\nextern int \nget_magcols(const colinfo * actcatinfo, gsl_vector *wavelength,\n            gsl_vector *colnums);\n\nextern int\nresolve_colname(const char colname[]);\n\nextern void\nget_columname(const colinfo * actcatinfo, const int colnum, char colname[]);\n\nextern int\nget_columnumber(const char cname[], const colinfo * actcatinfo);\n\n\nextern char *\nrmlead (char *str);\n\nextern char *\nstptok (const char *s, char *tok, size_t toklen, char *brk);\n\n#define      strMove(d,s) memmove(d,s,strlen(s)+1)\n\nextern void\nlv1ws (char *str);\n\nextern int\nisnum2(char *string);\n\nextern gsl_vector *\nstring_to_gsl_array (char *str);\n\nextern void\ncheck_libraries (void);\n\nextern observation *\nload_dummy_observation (void);\n#endif\n", "meta": {"hexsha": "8068bc2b1ca2e1e6d23100ca0dcf80740460c92d", "size": 2653, "ext": "h", "lang": "C", "max_stars_repo_path": "cextern/src/spc_utils.h", "max_stars_repo_name": "sosey/pyaxe", "max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cextern/src/spc_utils.h", "max_issues_repo_name": "sosey/pyaxe", "max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cextern/src/spc_utils.h", "max_forks_repo_name": "sosey/pyaxe", "max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.2519083969, "max_line_length": 76, "alphanum_fraction": 0.7252167358, "num_tokens": 698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3451052709578724, "lm_q2_score": 0.01941934924651655, "lm_q1q2_score": 0.006701719783544649}}
{"text": "#pragma once\n\n\n\n#include <map>\n#include <set>\n\n\n#ifdef _NOGSL\nclass gsl_vector;\n#else\n#include <gsl/gsl_vector.h>\n#endif\n\nclass Interface;\n\nclass SymbolicEvaluator {\n\tdouble otherError = 1;\npublic:\n\tvirtual void setInputs(Interface* inputValues_p) = 0;\n    \n    virtual void run(const gsl_vector* ctrls_p, const set<int>& nodesSubset) = 0;\n    virtual void run(const gsl_vector* ctrls_p) = 0;\n    \n    virtual double getErrorOnConstraint(int nodeid, gsl_vector* grad) = 0;\n    virtual double getErrorOnConstraint(int nodeid) = 0;\n\n    virtual double getErrorForAsserts(const set<int>& nodeid, gsl_vector* grad) = 0;\n\tvirtual double getErrorForAssert(int assertId, gsl_vector* grad)=0;\n\n    virtual double dist(int nid) = 0;\n    virtual double dist(int nid, gsl_vector* grad) = 0;\n\n\n    \n\tvirtual void print() = 0;\n\tvirtual void printFull() = 0;\n\n\tvoid resetOtherError() {\n\t\totherError = 1;\n\t}\n\n\tvoid setOtherError(double error) {\n\t\totherError = error;\n\t}\n\n\tdouble getOtherError() {\n\t\treturn otherError;\n\t}\n\n\tbool isSetOtherError() {\n\t\treturn otherError != 1;\n\t}\n};\n", "meta": {"hexsha": "e0bdf6f32cb3c45d2f603f07fcfd64ec840f4354", "size": 1065, "ext": "h", "lang": "C", "max_stars_repo_path": "src/SketchSolver/NumericalSynthesis/SymbolicEvaluators/SymbolicEvaluator.h", "max_stars_repo_name": "natebragg/sketch-backend", "max_stars_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_stars_repo_licenses": ["X11"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2020-08-20T14:54:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T00:28:40.000Z", "max_issues_repo_path": "src/SketchSolver/NumericalSynthesis/SymbolicEvaluators/SymbolicEvaluator.h", "max_issues_repo_name": "natebragg/sketch-backend", "max_issues_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_issues_repo_licenses": ["X11"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-01T16:53:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T04:02:09.000Z", "max_forks_repo_path": "src/SketchSolver/NumericalSynthesis/SymbolicEvaluators/SymbolicEvaluator.h", "max_forks_repo_name": "natebragg/sketch-backend", "max_forks_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_forks_repo_licenses": ["X11"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-04T20:47:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-06T01:45:04.000Z", "avg_line_length": 19.3636363636, "max_line_length": 84, "alphanum_fraction": 0.7014084507, "num_tokens": 292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.290980853917813, "lm_q2_score": 0.022977369408242198, "lm_q1q2_score": 0.006685974571195348}}
{"text": "/*\n * BaseMaster.h\n *\n *  Created on: Aug 7, 2014\n *      Author: thardin\n */\n\n#ifndef BASEMASTER_H_\n#define BASEMASTER_H_\n\n#include \"FMIClient.h\"\n#include <zmq.hpp>\n#ifdef USE_GPL\n#include <gsl/gsl_multiroots.h>\n#include \"common/fmigo_storage.h\"\nusing namespace fmigo_storage;\n#endif\n#include <chrono>\n\nnamespace fmitcp_master {\n    class BaseMaster {\n        int rendezvous;\n        //t1 = time at which to perform next step\n        std::chrono::high_resolution_clock::time_point t1;\n\n#ifdef USE_MPI\n        std::string m_mpi_str;\n#endif\n    protected:\n        std::vector<FMIClient*> m_clients;\n        std::vector<WeakConnection> m_weakConnections;\n        OutputRefsType clientWeakRefs;\n\n        InputRefsValuesType initialNonReals;  //for loop solver\n\n#ifdef USE_GPL\n        class FmigoStorage m_fmigoStorage;//(std::vector<size_t>(0));\n#endif\n\n    public:\n\n        zmq::socket_t rep_socket;\n        bool initing, paused, running;\n        bool zmqControl;\n        int m_pendingRequests;\n        double t; //current time\n\n        explicit BaseMaster(zmq::context_t &context, std::vector<FMIClient*> clients, std::vector<WeakConnection> weakConnections);\n        virtual ~BaseMaster() {\n          info(\"%i rendezvous\\n\", rendezvous);\n          int messages = 0;\n          for(auto client: m_clients)\n            messages += client->messages;\n          info(\"%i messages\\n\", messages);\n        }\n\n#ifdef USE_GPL\n        static int loop_residual_f(const gsl_vector *x, void *params, gsl_vector *f);\n\n        inline FmigoStorage & get_storage(){return m_fmigoStorage;}\n        void storage_alloc(const std::vector<FMIClient*> &clients){\n            vector<size_t> states({});\n            vector<size_t> indicators({});\n            for(auto client: clients) {\n                states.push_back(client->getNumContinuousStates());\n                indicators.push_back(client->getNumEventIndicators());\n            }\n            get_storage().allocate_storage(states,indicators);\n        }\n#endif\n      virtual std::string getFieldNames() const {return \"\";}\n      virtual void writeFields(bool last, FILE *outfile) {}\n        void solveLoops();\n        virtual void prepare() {};\n        virtual void runIteration(double t, double dt) = 0;\n\n#define on(name) void name(FMIClient* slave) {}\n        on(onSlaveInstantiated)\n        on(onSlaveInitialized)\n        on(onSlaveTerminated)\n        on(onSlaveFreed)\n        on(onSlaveStepped)\n        on(onSlaveGotVersion)\n        on(onSlaveSetReal)\n        on(onSlaveGotState)\n        on(onSlaveSetState)\n        on(onSlaveFreedState)\n        on(onSlaveDirectionalDerivative)\n\n        //T is needed because func maybe of a function in Client (from which FMIClient is derived)\n        void queueMessage(std::vector<FMIClient*> fmus, std::string str) {\n            for (auto it = fmus.begin(); it != fmus.end(); it++) {\n                (*it)->queueMessage(str);\n            }\n        }\n\n        //like queueMessage() but only for one FMU\n        void queueMessage(FMIClient *fmu, std::string str) {\n            fmu->queueMessage(str);\n        }\n\n        //queueMessage() followed by wait() (blocking)\n        void sendWait(std::vector<FMIClient*> fmus, std::string str) {\n            queueMessage(fmus, str);\n            wait();\n        }\n\n        //like sendWait() but only for one FMU (blocking)\n        void sendWait(FMIClient *fmu, std::string str) {\n            queueMessage(fmu, str);\n            wait();\n        }\n\n        void wait();\n\n        void resetT1();\n        //wait for t1, advance t1 by timeStep\n        void waitupT1(double timeStep);\n        void handleZmqControl();\n\n        void queueValueRequests();\n        //if cset_set == true then only delete values for FMUs whose ID is in cset\n        void deleteCachedValues(bool cset_set = false, const fmitcp::int_set& cset = fmitcp::int_set());\n    };\n};\n\n#endif /* BASEMASTER_H_ */\n", "meta": {"hexsha": "eb1c3878cac74782d368c6ecf7a82c816c73a82a", "size": 3885, "ext": "h", "lang": "C", "max_stars_repo_path": "include/master/BaseMaster.h", "max_stars_repo_name": "Tjoppen/fmigo", "max_stars_repo_head_hexsha": "0ad5e82b49a973cf710f85daa9dffc45261b36ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-12-18T16:35:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-14T07:38:05.000Z", "max_issues_repo_path": "include/master/BaseMaster.h", "max_issues_repo_name": "Tjoppen/fmigo", "max_issues_repo_head_hexsha": "0ad5e82b49a973cf710f85daa9dffc45261b36ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/master/BaseMaster.h", "max_forks_repo_name": "Tjoppen/fmigo", "max_forks_repo_head_hexsha": "0ad5e82b49a973cf710f85daa9dffc45261b36ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-20T15:50:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T15:50:01.000Z", "avg_line_length": 30.3515625, "max_line_length": 131, "alphanum_fraction": 0.6154440154, "num_tokens": 914, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24220562872535947, "lm_q2_score": 0.02758528032814983, "lm_q1q2_score": 0.00668131016544482}}
{"text": "/* Author:  G. Jungman */\r\n\r\n        \r\n/* Convenience header */\r\n#ifndef __GSL_SPECFUNC_H__\r\n#define __GSL_SPECFUNC_H__\r\n\r\n#if !defined( GSL_FUN )\r\n#  if !defined( GSL_DLL )\r\n#    define GSL_FUN extern\r\n#  elif defined( BUILD_GSL_DLL )\r\n#    define GSL_FUN extern __declspec(dllexport)\r\n#  else\r\n#    define GSL_FUN extern __declspec(dllimport)\r\n#  endif\r\n#endif\r\n\r\n#include <gsl/gsl_sf.h>\r\n\r\n#endif /* __GSL_SPECFUNC_H__ */\r\n", "meta": {"hexsha": "7a7205db14cb83be512b60ca6f6c37911a16b14f", "size": 426, "ext": "h", "lang": "C", "max_stars_repo_path": "deps/include/gsl/gsl_specfunc.h", "max_stars_repo_name": "berkus/music-cs", "max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z", "max_issues_repo_path": "deps/include/gsl/gsl_specfunc.h", "max_issues_repo_name": "berkus/music-cs", "max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z", "max_forks_repo_path": "deps/include/gsl/gsl_specfunc.h", "max_forks_repo_name": "berkus/music-cs", "max_forks_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 20.2857142857, "max_line_length": 49, "alphanum_fraction": 0.6666666667, "num_tokens": 118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.18713269122913015, "lm_q2_score": 0.03567855254395119, "lm_q1q2_score": 0.006676623556709514}}
{"text": "/* matrix/gsl_matrix_complex_long_double.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_MATRIX_COMPLEX_LONG_DOUBLE_H__\n#define __GSL_MATRIX_COMPLEX_LONG_DOUBLE_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_complex.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_vector_complex_long_double.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size1;\n  size_t size2;\n  size_t tda;\n  long double * data;\n  gsl_block_complex_long_double * block;\n  int owner;\n} gsl_matrix_complex_long_double ;\n\ntypedef struct\n{\n  gsl_matrix_complex_long_double matrix;\n} _gsl_matrix_complex_long_double_view;\n\ntypedef _gsl_matrix_complex_long_double_view gsl_matrix_complex_long_double_view;\n\ntypedef struct\n{\n  gsl_matrix_complex_long_double matrix;\n} _gsl_matrix_complex_long_double_const_view;\n\ntypedef const _gsl_matrix_complex_long_double_const_view gsl_matrix_complex_long_double_const_view;\n\n\n/* Allocation */\n\ngsl_matrix_complex_long_double * \ngsl_matrix_complex_long_double_alloc (const size_t n1, const size_t n2);\n\ngsl_matrix_complex_long_double * \ngsl_matrix_complex_long_double_calloc (const size_t n1, const size_t n2);\n\ngsl_matrix_complex_long_double * \ngsl_matrix_complex_long_double_alloc_from_block (gsl_block_complex_long_double * b, \n                                           const size_t offset, \n                                           const size_t n1, const size_t n2, const size_t d2);\n\ngsl_matrix_complex_long_double * \ngsl_matrix_complex_long_double_alloc_from_matrix (gsl_matrix_complex_long_double * b,\n                                            const size_t k1, const size_t k2,\n                                            const size_t n1, const size_t n2);\n\ngsl_vector_complex_long_double * \ngsl_vector_complex_long_double_alloc_row_from_matrix (gsl_matrix_complex_long_double * m,\n                                                const size_t i);\n\ngsl_vector_complex_long_double * \ngsl_vector_complex_long_double_alloc_col_from_matrix (gsl_matrix_complex_long_double * m,\n                                                const size_t j);\n\nvoid gsl_matrix_complex_long_double_free (gsl_matrix_complex_long_double * m);\n\n/* Views */\n\n_gsl_matrix_complex_long_double_view \ngsl_matrix_complex_long_double_submatrix (gsl_matrix_complex_long_double * m, \n                            const size_t i, const size_t j, \n                            const size_t n1, const size_t n2);\n\n_gsl_vector_complex_long_double_view \ngsl_matrix_complex_long_double_row (gsl_matrix_complex_long_double * m, const size_t i);\n\n_gsl_vector_complex_long_double_view \ngsl_matrix_complex_long_double_column (gsl_matrix_complex_long_double * m, const size_t j);\n\n_gsl_vector_complex_long_double_view \ngsl_matrix_complex_long_double_diagonal (gsl_matrix_complex_long_double * m);\n\n_gsl_vector_complex_long_double_view \ngsl_matrix_complex_long_double_subdiagonal (gsl_matrix_complex_long_double * m, const size_t k);\n\n_gsl_vector_complex_long_double_view \ngsl_matrix_complex_long_double_superdiagonal (gsl_matrix_complex_long_double * m, const size_t k);\n\n_gsl_vector_complex_long_double_view\ngsl_matrix_complex_long_double_subrow (gsl_matrix_complex_long_double * m,\n                                 const size_t i, const size_t offset,\n                                 const size_t n);\n\n_gsl_vector_complex_long_double_view\ngsl_matrix_complex_long_double_subcolumn (gsl_matrix_complex_long_double * m,\n                                    const size_t j, const size_t offset,\n                                    const size_t n);\n\n_gsl_matrix_complex_long_double_view\ngsl_matrix_complex_long_double_view_array (long double * base,\n                             const size_t n1, \n                             const size_t n2);\n\n_gsl_matrix_complex_long_double_view\ngsl_matrix_complex_long_double_view_array_with_tda (long double * base, \n                                      const size_t n1, \n                                      const size_t n2,\n                                      const size_t tda);\n\n_gsl_matrix_complex_long_double_view\ngsl_matrix_complex_long_double_view_vector (gsl_vector_complex_long_double * v,\n                              const size_t n1, \n                              const size_t n2);\n\n_gsl_matrix_complex_long_double_view\ngsl_matrix_complex_long_double_view_vector_with_tda (gsl_vector_complex_long_double * v,\n                                       const size_t n1, \n                                       const size_t n2,\n                                       const size_t tda);\n\n\n_gsl_matrix_complex_long_double_const_view \ngsl_matrix_complex_long_double_const_submatrix (const gsl_matrix_complex_long_double * m, \n                                  const size_t i, const size_t j, \n                                  const size_t n1, const size_t n2);\n\n_gsl_vector_complex_long_double_const_view \ngsl_matrix_complex_long_double_const_row (const gsl_matrix_complex_long_double * m, \n                            const size_t i);\n\n_gsl_vector_complex_long_double_const_view \ngsl_matrix_complex_long_double_const_column (const gsl_matrix_complex_long_double * m, \n                               const size_t j);\n\n_gsl_vector_complex_long_double_const_view\ngsl_matrix_complex_long_double_const_diagonal (const gsl_matrix_complex_long_double * m);\n\n_gsl_vector_complex_long_double_const_view \ngsl_matrix_complex_long_double_const_subdiagonal (const gsl_matrix_complex_long_double * m, \n                                    const size_t k);\n\n_gsl_vector_complex_long_double_const_view \ngsl_matrix_complex_long_double_const_superdiagonal (const gsl_matrix_complex_long_double * m, \n                                      const size_t k);\n\n_gsl_vector_complex_long_double_const_view\ngsl_matrix_complex_long_double_const_subrow (const gsl_matrix_complex_long_double * m,\n                                       const size_t i, const size_t offset,\n                                       const size_t n);\n\n_gsl_vector_complex_long_double_const_view\ngsl_matrix_complex_long_double_const_subcolumn (const gsl_matrix_complex_long_double * m,\n                                          const size_t j, const size_t offset,\n                                          const size_t n);\n\n_gsl_matrix_complex_long_double_const_view\ngsl_matrix_complex_long_double_const_view_array (const long double * base,\n                                   const size_t n1, \n                                   const size_t n2);\n\n_gsl_matrix_complex_long_double_const_view\ngsl_matrix_complex_long_double_const_view_array_with_tda (const long double * base, \n                                            const size_t n1, \n                                            const size_t n2,\n                                            const size_t tda);\n\n_gsl_matrix_complex_long_double_const_view\ngsl_matrix_complex_long_double_const_view_vector (const gsl_vector_complex_long_double * v,\n                                    const size_t n1, \n                                    const size_t n2);\n\n_gsl_matrix_complex_long_double_const_view\ngsl_matrix_complex_long_double_const_view_vector_with_tda (const gsl_vector_complex_long_double * v,\n                                             const size_t n1, \n                                             const size_t n2,\n                                             const size_t tda);\n\n/* Operations */\n\nvoid gsl_matrix_complex_long_double_set_zero (gsl_matrix_complex_long_double * m);\nvoid gsl_matrix_complex_long_double_set_identity (gsl_matrix_complex_long_double * m);\nvoid gsl_matrix_complex_long_double_set_all (gsl_matrix_complex_long_double * m, gsl_complex_long_double x);\n\nint gsl_matrix_complex_long_double_fread (FILE * stream, gsl_matrix_complex_long_double * m) ;\nint gsl_matrix_complex_long_double_fwrite (FILE * stream, const gsl_matrix_complex_long_double * m) ;\nint gsl_matrix_complex_long_double_fscanf (FILE * stream, gsl_matrix_complex_long_double * m);\nint gsl_matrix_complex_long_double_fprintf (FILE * stream, const gsl_matrix_complex_long_double * m, const char * format);\n\nint gsl_matrix_complex_long_double_memcpy(gsl_matrix_complex_long_double * dest, const gsl_matrix_complex_long_double * src);\nint gsl_matrix_complex_long_double_swap(gsl_matrix_complex_long_double * m1, gsl_matrix_complex_long_double * m2);\n\nint gsl_matrix_complex_long_double_swap_rows(gsl_matrix_complex_long_double * m, const size_t i, const size_t j);\nint gsl_matrix_complex_long_double_swap_columns(gsl_matrix_complex_long_double * m, const size_t i, const size_t j);\nint gsl_matrix_complex_long_double_swap_rowcol(gsl_matrix_complex_long_double * m, const size_t i, const size_t j);\n\nint gsl_matrix_complex_long_double_transpose (gsl_matrix_complex_long_double * m);\nint gsl_matrix_complex_long_double_transpose_memcpy (gsl_matrix_complex_long_double * dest, const gsl_matrix_complex_long_double * src);\n\nint gsl_matrix_complex_long_double_equal (const gsl_matrix_complex_long_double * a, const gsl_matrix_complex_long_double * b);\n\nint gsl_matrix_complex_long_double_isnull (const gsl_matrix_complex_long_double * m);\nint gsl_matrix_complex_long_double_ispos (const gsl_matrix_complex_long_double * m);\nint gsl_matrix_complex_long_double_isneg (const gsl_matrix_complex_long_double * m);\nint gsl_matrix_complex_long_double_isnonneg (const gsl_matrix_complex_long_double * m);\n\nint gsl_matrix_complex_long_double_add (gsl_matrix_complex_long_double * a, const gsl_matrix_complex_long_double * b);\nint gsl_matrix_complex_long_double_sub (gsl_matrix_complex_long_double * a, const gsl_matrix_complex_long_double * b);\nint gsl_matrix_complex_long_double_mul_elements (gsl_matrix_complex_long_double * a, const gsl_matrix_complex_long_double * b);\nint gsl_matrix_complex_long_double_div_elements (gsl_matrix_complex_long_double * a, const gsl_matrix_complex_long_double * b);\nint gsl_matrix_complex_long_double_scale (gsl_matrix_complex_long_double * a, const gsl_complex_long_double x);\nint gsl_matrix_complex_long_double_add_constant (gsl_matrix_complex_long_double * a, const gsl_complex_long_double x);\nint gsl_matrix_complex_long_double_add_diagonal (gsl_matrix_complex_long_double * a, const gsl_complex_long_double x);\n\n/***********************************************************************/\n/* The functions below are obsolete                                    */\n/***********************************************************************/\nint gsl_matrix_complex_long_double_get_row(gsl_vector_complex_long_double * v, const gsl_matrix_complex_long_double * m, const size_t i);\nint gsl_matrix_complex_long_double_get_col(gsl_vector_complex_long_double * v, const gsl_matrix_complex_long_double * m, const size_t j);\nint gsl_matrix_complex_long_double_set_row(gsl_matrix_complex_long_double * m, const size_t i, const gsl_vector_complex_long_double * v);\nint gsl_matrix_complex_long_double_set_col(gsl_matrix_complex_long_double * m, const size_t j, const gsl_vector_complex_long_double * v);\n/***********************************************************************/\n\n/* inline functions if you are using GCC */\n\nINLINE_DECL gsl_complex_long_double gsl_matrix_complex_long_double_get(const gsl_matrix_complex_long_double * m, const size_t i, const size_t j);\nINLINE_DECL void gsl_matrix_complex_long_double_set(gsl_matrix_complex_long_double * m, const size_t i, const size_t j, const gsl_complex_long_double x);\n\nINLINE_DECL gsl_complex_long_double * gsl_matrix_complex_long_double_ptr(gsl_matrix_complex_long_double * m, const size_t i, const size_t j);\nINLINE_DECL const gsl_complex_long_double * gsl_matrix_complex_long_double_const_ptr(const gsl_matrix_complex_long_double * m, const size_t i, const size_t j);\n\n#ifdef HAVE_INLINE\n\nINLINE_FUN \ngsl_complex_long_double\ngsl_matrix_complex_long_double_get(const gsl_matrix_complex_long_double * m, \n                     const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      gsl_complex_long_double zero = {{0,0}};\n\n      if (i >= m->size1)\n        {\n          GSL_ERROR_VAL(\"first index out of range\", GSL_EINVAL, zero) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_VAL(\"second index out of range\", GSL_EINVAL, zero) ;\n        }\n    }\n#endif\n  return *(gsl_complex_long_double *)(m->data + 2*(i * m->tda + j)) ;\n} \n\nINLINE_FUN \nvoid\ngsl_matrix_complex_long_double_set(gsl_matrix_complex_long_double * m, \n                     const size_t i, const size_t j, const gsl_complex_long_double x)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_VOID(\"first index out of range\", GSL_EINVAL) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_VOID(\"second index out of range\", GSL_EINVAL) ;\n        }\n    }\n#endif\n  *(gsl_complex_long_double *)(m->data + 2*(i * m->tda + j)) = x ;\n}\n\nINLINE_FUN \ngsl_complex_long_double *\ngsl_matrix_complex_long_double_ptr(gsl_matrix_complex_long_double * m, \n                             const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n        }\n    }\n#endif\n  return (gsl_complex_long_double *)(m->data + 2*(i * m->tda + j)) ;\n} \n\nINLINE_FUN \nconst gsl_complex_long_double *\ngsl_matrix_complex_long_double_const_ptr(const gsl_matrix_complex_long_double * m, \n                                   const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n        }\n    }\n#endif\n  return (const gsl_complex_long_double *)(m->data + 2*(i * m->tda + j)) ;\n} \n\n#endif /* HAVE_INLINE */\n\n__END_DECLS\n\n#endif /* __GSL_MATRIX_COMPLEX_LONG_DOUBLE_H__ */\n", "meta": {"hexsha": "9e2c3dbe19c5c7f966296069dc379db9f2954dd1", "size": 15032, "ext": "h", "lang": "C", "max_stars_repo_path": "gsl-2.6/gsl/gsl_matrix_complex_long_double.h", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gsl-2.6/gsl/gsl_matrix_complex_long_double.h", "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gsl-2.6/gsl/gsl_matrix_complex_long_double.h", "max_forks_repo_name": "ielomariala/Hex-Game", "max_forks_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-30T20:40:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-30T20:40:25.000Z", "avg_line_length": 42.7045454545, "max_line_length": 159, "alphanum_fraction": 0.7085550825, "num_tokens": 3226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2689414330889797, "lm_q2_score": 0.02479816123161473, "lm_q1q2_score": 0.006669253019602044}}
{"text": "#if !defined(fvSupport_h)\n#define fvSupport_h\n\n#include <petsc.h>\n\n/**\n * reproduces the petsc call with grad fixes for multiple fields\n * @param dm\n * @param fvm\n * @param locX\n * @param grad\n * @return\n */\nPETSC_EXTERN PetscErrorCode DMPlexGetDataFVM_MulfiField(DM dm, PetscFV fv, Vec *cellgeom, Vec *facegeom, DM *gradDM);\n\n/**\n * Check to make sure local ghost boundary have valid gradient values\n */\nPETSC_EXTERN PetscErrorCode ABLATE_FillGradientBoundary(DM dm, PetscFV auxFvm, Vec localXVec, Vec gradLocalVec);\n\n#endif", "meta": {"hexsha": "c63af99fc08c753a53641fadd4c25c49cbcd9c4a", "size": 525, "ext": "h", "lang": "C", "max_stars_repo_path": "ablateCore/flow/fvSupport.h", "max_stars_repo_name": "mtmcgurn-buffalo/ablate", "max_stars_repo_head_hexsha": "35ee9a30277908775a61d78462ea9724ee631a9b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ablateCore/flow/fvSupport.h", "max_issues_repo_name": "mtmcgurn-buffalo/ablate", "max_issues_repo_head_hexsha": "35ee9a30277908775a61d78462ea9724ee631a9b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2020-12-28T16:05:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-12T14:36:22.000Z", "max_forks_repo_path": "ablateCore/flow/fvSupport.h", "max_forks_repo_name": "mtmcgurn-buffalo/ablate", "max_forks_repo_head_hexsha": "35ee9a30277908775a61d78462ea9724ee631a9b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-22T14:16:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-22T14:16:59.000Z", "avg_line_length": 25.0, "max_line_length": 117, "alphanum_fraction": 0.7523809524, "num_tokens": 149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2689414096510108, "lm_q2_score": 0.024798157853259208, "lm_q1q2_score": 0.006669251529803816}}
{"text": "/**\n * This file is part of the Contour terminal project\n *   Copyright (c) 2019-2021 Christian Parpart <christian@parpart.family>\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n#pragma once\n\n#include <gsl/span>\n#include <gsl/span_ext>\n\n#include <algorithm>\n#include <cassert>\n#include <iterator>\n#include <stdexcept>\n#include <vector>\n\nnamespace crispy\n{\n\ntemplate <typename T, typename Vector>\nstruct RingIterator;\ntemplate <typename T, typename Vector>\nstruct RingReverseIterator;\n\n/**\n * Implements an efficient ring buffer over type T\n * and the underlying storage Vector.\n */\ntemplate <typename T, typename Vector = std::vector<T>>\nclass basic_ring\n{\n  public:\n    using value_type = T;\n    using iterator = RingIterator<value_type, Vector>;\n    using const_iterator = RingIterator<value_type const, Vector>;\n    using reverse_iterator = RingReverseIterator<value_type, Vector>;\n    using const_reverse_iterator = RingReverseIterator<value_type const, Vector>;\n    using difference_type = long;\n    using offset_type = long;\n\n    basic_ring() = default;\n    basic_ring(basic_ring const&) = default;\n    basic_ring& operator=(basic_ring const&) = default;\n    basic_ring(basic_ring&&) noexcept = default;\n    basic_ring& operator=(basic_ring&&) noexcept = default;\n    virtual ~basic_ring() = default;\n\n    explicit basic_ring(Vector storage): _storage(std::move(storage)) {}\n\n    value_type const& operator[](offset_type i) const noexcept\n    {\n        return _storage[size_t(offset_type(_zero + size()) + i) % size()];\n    }\n    value_type& operator[](offset_type i) noexcept\n    {\n        return _storage[size_t(offset_type(_zero + size()) + i) % size()];\n    }\n\n    value_type const& at(offset_type i) const noexcept\n    {\n        return _storage[size_t(_zero + size() + i) % size()];\n    }\n    value_type& at(offset_type i) noexcept\n    {\n        return _storage[size_t(offset_type(_zero + size()) + i) % size()];\n    }\n\n    Vector& storage() noexcept { return _storage; }\n    Vector const& storage() const noexcept { return _storage; }\n    std::size_t zero_index() const noexcept { return _zero; }\n\n    void rezero(iterator i);\n    void rezero();\n\n    std::size_t size() const noexcept { return _storage.size(); }\n\n    // positvie count rotates right, negative count rotates left\n    void rotate(int count) noexcept { _zero = size_t(offset_type(_zero + size()) - count) % size(); }\n\n    void rotate_left(std::size_t count) noexcept { _zero = (_zero + size() + count) % size(); }\n    void rotate_right(std::size_t count) noexcept { _zero = (_zero + size() - count) % size(); }\n    void unrotate() { _zero = 0; }\n\n    value_type& front() noexcept { return at(0); }\n    value_type const& front() const noexcept { return at(0); }\n\n    value_type& back()\n    {\n        if (size() == 0)\n            throw std::length_error(\"empty\");\n\n        return at(static_cast<offset_type>(size()) - 1);\n    }\n\n    value_type const& back() const\n    {\n        if (size() == 0)\n            throw std::length_error(\"empty\");\n\n        return at(static_cast<offset_type>(size()) - 1);\n    }\n\n    iterator begin() noexcept { return iterator { this, 0 }; }\n    iterator end() noexcept { return iterator { this, static_cast<difference_type>(size()) }; }\n\n    const_iterator cbegin() const noexcept\n    {\n        return const_iterator { (basic_ring<value_type const, Vector>*) this, 0 };\n    }\n    const_iterator cend() const noexcept\n    {\n        return const_iterator { (basic_ring<value_type const, Vector>*) this,\n                                static_cast<difference_type>(size()) };\n    }\n\n    const_iterator begin() const noexcept { return cbegin(); }\n    const_iterator end() const noexcept { return cend(); }\n\n    reverse_iterator rbegin() noexcept;\n    reverse_iterator rend() noexcept;\n\n    const_reverse_iterator rbegin() const noexcept;\n    const_reverse_iterator rend() const noexcept;\n\n    gsl::span<value_type> span(offset_type start, size_t count) noexcept\n    {\n        auto a = std::next(begin(), start);\n        auto b = std::next(a, count);\n        return gsl::make_span(a, b);\n    }\n\n    gsl::span<value_type const> span(offset_type start, size_t count) const noexcept\n    {\n        auto a = std::next(begin(), start);\n        auto b = std::next(a, count);\n        return gsl::make_span(a, b);\n    }\n\n  protected:\n    Vector _storage;\n    std::size_t _zero = 0;\n};\n\n/**\n * Implements an efficient ring buffer over type T\n * and the underlying dynamic storage type Vector<T, Allocator>.\n */\ntemplate <typename T,\n          template <typename, typename> class Container = std::vector,\n          typename Allocator = std::allocator<T>>\nclass ring: public basic_ring<T, Container<T, Allocator>>\n{\n  public:\n    using basic_ring<T, Container<T, Allocator>>::basic_ring;\n\n    ring(size_t capacity, T value): ring(Container<T, Allocator>(capacity, value)) {}\n    explicit ring(size_t capacity): ring(capacity, T {}) {}\n\n    size_t size() const noexcept { return this->_storage.size(); }\n\n    void reserve(size_t capacity) { this->_storage.reserve(capacity); }\n    void resize(size_t newSize)\n    {\n        this->rezero();\n        this->_storage.resize(newSize);\n    }\n    void clear()\n    {\n        this->_storage.clear();\n        this->_zero = 0;\n    }\n    void push_back(T const& _value) { this->_storage.push_back(_value); }\n\n    void push_back(T&& _value) { this->emplace_back(std::move(_value)); }\n\n    template <typename... Args>\n    void emplace_back(Args&&... args)\n    {\n        this->_storage.emplace_back(std::forward<Args>(args)...);\n    }\n\n    void pop_front() { this->_storage.erase(this->_storage.begin()); }\n};\n\n/// Fixed-size basic_ring<T> implementation\ntemplate <typename T, std::size_t N>\nusing fixed_size_ring = basic_ring<T, std::array<T, N>>;\n\n// {{{ iterator\ntemplate <typename T, typename Vector>\nstruct RingIterator\n{\n    using iterator_category = std::random_access_iterator_tag;\n    using value_type = T;\n    using difference_type = long;\n    using pointer = T*;\n    using reference = T&;\n\n    basic_ring<T, Vector>* ring {};\n    difference_type current {};\n\n    RingIterator(basic_ring<T, Vector>* aRing, difference_type aCurrent): ring { aRing }, current { aCurrent }\n    {\n    }\n\n    RingIterator() = default;\n\n    RingIterator(RingIterator const&) = default;\n    RingIterator& operator=(RingIterator const&) = default;\n\n    RingIterator(RingIterator&&) noexcept = default;\n    RingIterator& operator=(RingIterator&&) noexcept = default;\n\n    RingIterator& operator++() noexcept\n    {\n        ++current;\n        return *this;\n    }\n\n    RingIterator operator++(int) noexcept\n    {\n        auto old = *this;\n        ++(*this);\n        return old;\n    }\n\n    RingIterator& operator--() noexcept\n    {\n        --current;\n        return *this;\n    }\n\n    RingIterator operator--(int) noexcept\n    {\n        auto old = *this;\n        --(*this);\n        return old;\n    }\n\n    RingIterator& operator+=(int n) noexcept\n    {\n        current += n;\n        return *this;\n    }\n    RingIterator& operator-=(int n) noexcept\n    {\n        current -= n;\n        return *this;\n    }\n\n    RingIterator operator+(difference_type n) noexcept { return RingIterator { ring, current + n }; }\n    RingIterator operator-(difference_type n) noexcept { return RingIterator { ring, current - n }; }\n\n    RingIterator operator+(RingIterator const& rhs) const noexcept\n    {\n        return RingIterator { ring, current + rhs.current };\n    }\n    difference_type operator-(RingIterator const& rhs) const noexcept { return current - rhs.current; }\n\n    friend RingIterator operator+(difference_type n, RingIterator a)\n    {\n        return RingIterator { a.ring, n + a.current };\n    }\n    friend RingIterator operator-(difference_type n, RingIterator a)\n    {\n        return RingIterator { a.ring, n - a.current };\n    }\n\n    bool operator==(RingIterator const& rhs) const noexcept { return current == rhs.current; }\n    bool operator!=(RingIterator const& rhs) const noexcept { return current != rhs.current; }\n\n    T& operator*() noexcept { return (*ring)[current]; }\n    T const& operator*() const noexcept { return (*ring)[current]; }\n\n    T* operator->() noexcept { return &(*ring)[current]; }\n    T* operator->() const noexcept { return &(*ring)[current]; }\n};\n// }}}\n\n// {{{ reverse iterator\ntemplate <typename T, typename Vector>\nstruct RingReverseIterator\n{\n    using iterator_category = std::random_access_iterator_tag;\n    using value_type = T;\n    using difference_type = long;\n    using pointer = T*;\n    using reference = T&;\n\n    basic_ring<T, Vector>* ring;\n    difference_type current;\n\n    RingReverseIterator(basic_ring<T, Vector>* _ring, difference_type _current):\n        ring { _ring }, current { _current }\n    {\n    }\n\n    RingReverseIterator(RingReverseIterator const&) = default;\n    RingReverseIterator& operator=(RingReverseIterator const&) = default;\n\n    RingReverseIterator(RingReverseIterator&&) noexcept = default;\n    RingReverseIterator& operator=(RingReverseIterator&&) noexcept = default;\n\n    RingReverseIterator& operator++() noexcept\n    {\n        ++current;\n        return *this;\n    }\n    RingReverseIterator& operator++(int) noexcept { return ++(*this); }\n\n    RingReverseIterator& operator--() noexcept\n    {\n        --current;\n        return *this;\n    }\n    RingReverseIterator& operator--(int) noexcept { return --(*this); }\n\n    RingReverseIterator& operator+=(int n) noexcept\n    {\n        current += n;\n        return *this;\n    }\n    RingReverseIterator& operator-=(int n) noexcept\n    {\n        current -= n;\n        return *this;\n    }\n\n    RingReverseIterator operator+(difference_type n) noexcept\n    {\n        return RingReverseIterator { ring, current + n };\n    }\n    RingReverseIterator operator-(difference_type n) noexcept\n    {\n        return RingReverseIterator { ring, current - n };\n    }\n\n    RingReverseIterator operator+(RingReverseIterator const& rhs) const noexcept\n    {\n        return RingReverseIterator { ring, current + rhs.current };\n    }\n    difference_type operator-(RingReverseIterator const& rhs) const noexcept { return current - rhs.current; }\n\n    friend RingReverseIterator operator+(difference_type n, RingReverseIterator a)\n    {\n        return RingReverseIterator { a.ring, n + a.current };\n    }\n    friend RingReverseIterator operator-(difference_type n, RingReverseIterator a)\n    {\n        return RingReverseIterator { a.ring, n - a.current };\n    }\n\n    bool operator==(RingReverseIterator const& rhs) const noexcept { return current == rhs.current; }\n    bool operator!=(RingReverseIterator const& rhs) const noexcept { return current != rhs.current; }\n\n    T& operator*() noexcept { return (*ring)[ring->size() - current - 1]; }\n    T const& operator*() const noexcept { return (*ring)[ring->size() - current - 1]; }\n\n    T* operator->() noexcept { return &(*ring)[static_cast<difference_type>(ring->size()) - current - 1]; }\n\n    T* operator->() const noexcept\n    {\n        return &(*ring)[static_cast<difference_type>(ring->size()) - current - 1];\n    }\n};\n// }}}\n\n// {{{ basic_ring<T> impl\ntemplate <typename T, typename Vector>\ntypename basic_ring<T, Vector>::reverse_iterator basic_ring<T, Vector>::rbegin() noexcept\n{\n    return reverse_iterator { this, 0 };\n}\n\ntemplate <typename T, typename Vector>\ntypename basic_ring<T, Vector>::reverse_iterator basic_ring<T, Vector>::rend() noexcept\n{\n    return reverse_iterator { this, size() };\n}\n\ntemplate <typename T, typename Vector>\ntypename basic_ring<T, Vector>::const_reverse_iterator basic_ring<T, Vector>::rbegin() const noexcept\n{\n    return const_reverse_iterator { (basic_ring<T const, Vector>*) this, 0 };\n}\n\ntemplate <typename T, typename Vector>\ntypename basic_ring<T, Vector>::const_reverse_iterator basic_ring<T, Vector>::rend() const noexcept\n{\n    return const_reverse_iterator { (basic_ring<T const, Vector>*) this,\n                                    static_cast<difference_type>(size()) };\n}\n\ntemplate <typename T, typename Vector>\nvoid basic_ring<T, Vector>::rezero()\n{\n    std::rotate(begin(), std::next(begin(), static_cast<difference_type>(_zero)), end()); // shift-left\n    _zero = 0;\n}\n\ntemplate <typename T, typename Vector>\nvoid basic_ring<T, Vector>::rezero(iterator i)\n{\n    std::rotate(begin(), std::next(begin(), i.current), end()); // shift-left\n    _zero = 0;\n}\n// }}}\n\n} // namespace crispy\n", "meta": {"hexsha": "162bdf592babbc636b8c2efebc8c5f2956c9bd0c", "size": 12794, "ext": "h", "lang": "C", "max_stars_repo_path": "src/crispy/ring.h", "max_stars_repo_name": "sebastianrakel/contour", "max_stars_repo_head_hexsha": "f0004230be75bb99fc899851a216f41d1dca2a81", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-08-14T22:29:57.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-19T08:57:15.000Z", "max_issues_repo_path": "src/crispy/ring.h", "max_issues_repo_name": "sebastianrakel/contour", "max_issues_repo_head_hexsha": "f0004230be75bb99fc899851a216f41d1dca2a81", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 69.0, "max_issues_repo_issues_event_min_datetime": "2019-08-17T18:57:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-22T23:25:49.000Z", "max_forks_repo_path": "src/crispy/ring.h", "max_forks_repo_name": "christianparpart/libterminal", "max_forks_repo_head_hexsha": "0e6d75a2042437084c9f9880a5c8b5661a02da07", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6076555024, "max_line_length": 110, "alphanum_fraction": 0.6558543067, "num_tokens": 2989, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.28140560742914383, "lm_q2_score": 0.023689473108725215, "lm_q1q2_score": 0.0066663505698371876}}
{"text": "/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */\n/*\n *     Copyright 2018 Couchbase, Inc.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n */\n#pragma once\n\n#include <array>\n#include <gsl/gsl>\n#include <optional>\n#include <type_traits>\n\nnamespace couchbase::protocol\n{\n\n/**\n * Helper code for encode and decode of LEB128 values.\n * - mcbp encodes collection-ID as an unsigned LEB128\n * - see https://en.wikipedia.org/wiki/LEB128\n */\n\nstruct Leb128NoThrow {\n};\n\n/**\n * decode_unsigned_leb128 returns the decoded T and a const_byte_buffer\n * initialised with the data following the leb128 data. This form of the decode\n * does not throw for invalid input and the caller should always check\n * second.data() for success or error (see returns info).\n *\n * @param buf buffer containing a leb128 encoded value (of size T)\n * @returns On error a std::pair where first is set to 0 and second is nullptr/0\n *          const_byte_buffer. On success a std::pair where first is the decoded\n *          value and second is a buffer initialised with the data following the\n *          leb128 data.\n */\ntemplate<class T>\ntypename std::enable_if_t<std::is_unsigned_v<T>, std::pair<T, std::string_view>>\ndecode_unsigned_leb128(std::string_view buf, struct Leb128NoThrow /* unused */)\n{\n    T rv = static_cast<uint8_t>(buf[0]) & 0x7fULL;\n    size_t end = 0;\n    if ((static_cast<uint8_t>(buf[0]) & 0x80ULL) == 0x80ULL) {\n        T shift = 7;\n        // shift in the remaining data\n        for (end = 1; end < buf.size(); end++) {\n            rv |= (static_cast<uint8_t>(buf[end]) & 0x7fULL) << shift;\n            if ((static_cast<uint8_t>(buf[end]) & 0x80ULL) == 0) {\n                break; // no more\n            }\n            shift += 7;\n        }\n\n        // We should of stopped for a stop byte, not the end of the buffer\n        if (end == buf.size()) {\n            return { 0, std::string_view{} };\n        }\n    }\n    // Return the decoded value and a buffer for any remaining data\n    return { rv, std::string_view{ buf.data() + end + 1, buf.size() - (end + 1) } };\n}\n\n/**\n * decode_unsigned_leb128 returns the decoded T and a const_byte_buffer\n * initialised with the data following the leb128 data. This form of the decode\n * throws for invalid input.\n *\n * @param buf buffer containing a leb128 encoded value (of size T)\n * @returns std::pair first is the decoded value and second a buffer for the\n *          remaining data (size will be 0 for no more data)\n * @throws std::invalid_argument if buf[0] does not encode a leb128 value with\n *         a stop byte.\n */\ntemplate<class T>\ntypename std::enable_if_t<std::is_unsigned_v<T>, std::pair<T, std::string_view>>\ndecode_unsigned_leb128(std::string_view buf)\n{\n    if (buf.size() > 0) {\n        auto rv = decode_unsigned_leb128<T>(buf, Leb128NoThrow());\n        if (rv.second.data()) {\n            return rv;\n        }\n    }\n    throw std::invalid_argument(\"decode_unsigned_leb128: invalid buf size:\" + std::to_string(buf.size()));\n}\n\n/**\n * @return a buffer to the data after the leb128 prefix\n */\ntemplate<class T>\ntypename std::enable_if_t<std::is_unsigned_v<T>, std::string_view>\nskip_unsigned_leb128(std::string_view buf)\n{\n    return decode_unsigned_leb128<T>(buf).second;\n}\n\n// Empty, non specialised version of the decoder class\ntemplate<class T, class Enable = void>\nclass unsigned_leb128\n{\n};\n\n/**\n * For encoding a unsigned T leb128, class constructs from a T value and\n * provides a const_byte_buffer for access to the encoded\n */\ntemplate<class T>\nclass unsigned_leb128<T, typename std::enable_if_t<std::is_unsigned_v<T>>>\n{\n  public:\n    explicit unsigned_leb128(T in)\n    {\n        while (in > 0) {\n            auto byte = gsl::narrow_cast<uint8_t>(in & 0x7fULL);\n            in >>= 7;\n\n            // In has more data?\n            if (in > 0) {\n                byte |= 0x80;\n                encodedData[encodedSize - 1U] = byte;\n                // Increase the size\n                encodedSize++;\n            } else {\n                encodedData[encodedSize - 1U] = byte;\n            }\n        }\n    }\n\n    [[nodiscard]] std::string get() const\n    {\n        return { begin(), end() };\n    }\n\n    [[nodiscard]] const uint8_t* begin() const\n    {\n        return encodedData.data();\n    }\n\n    [[nodiscard]] const uint8_t* end() const\n    {\n        return encodedData.data() + encodedSize;\n    }\n\n    [[nodiscard]] const uint8_t* data() const\n    {\n        return encodedData.data();\n    }\n\n    [[nodiscard]] size_t size() const\n    {\n        return encodedSize;\n    }\n\n    constexpr static size_t getMaxSize()\n    {\n        return maxSize;\n    }\n\n  private:\n    // Larger T may need a larger array\n    static_assert(sizeof(T) <= 8, \"Class is only valid for uint 8/16/64\");\n\n    // value is large enough to store ~0 as leb128\n    static constexpr size_t maxSize = sizeof(T) + (((sizeof(T) + 1) / 8) + 1);\n    std::array<uint8_t, maxSize> encodedData{};\n    uint8_t encodedSize{ 1 };\n};\n\n} // namespace couchbase::protocol\n", "meta": {"hexsha": "65411a35922f61eb62ca982521350de19b3d5182", "size": 5538, "ext": "h", "lang": "C", "max_stars_repo_path": "ext/couchbase/protocol/unsigned_leb128.h", "max_stars_repo_name": "avsej/couchbase-ruby-client", "max_stars_repo_head_hexsha": "fc1ae7706d3b1eb3e35f02a005327411ec34a00f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-05-18T09:47:40.000Z", "max_stars_repo_stars_event_max_datetime": "2015-05-18T09:47:40.000Z", "max_issues_repo_path": "ext/couchbase/protocol/unsigned_leb128.h", "max_issues_repo_name": "avsej/couchbase-ruby-client", "max_issues_repo_head_hexsha": "fc1ae7706d3b1eb3e35f02a005327411ec34a00f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ext/couchbase/protocol/unsigned_leb128.h", "max_forks_repo_name": "avsej/couchbase-ruby-client", "max_forks_repo_head_hexsha": "fc1ae7706d3b1eb3e35f02a005327411ec34a00f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-12-29T07:07:27.000Z", "max_forks_repo_forks_event_max_datetime": "2016-12-29T07:07:27.000Z", "avg_line_length": 30.5966850829, "max_line_length": 106, "alphanum_fraction": 0.6325388227, "num_tokens": 1434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2450850021044189, "lm_q2_score": 0.02716923399726585, "lm_q1q2_score": 0.00665877177139535}}
{"text": "#pragma once\n\n#include <gsl/string_span>\n#include <string>\n\n#include \"params.h\"\n\nnamespace particles {\n\nclass ParserParams {\npublic:\n\n\tstatic PartSysParam* Parse(PartSysParamId id,\n\t\t\t\t\t\t\t   gsl::cstring_span<> value,\n\t                           float emitterLifespan,\n\t                           float particleLifespan,\n\t                           bool& success);\n\n\tstatic PartSysParam* Parse(gsl::cstring_span<> value,\n\t                           float defaultValue,\n\t                           float parentLifespan,\n\t                           bool& success);\n\n\tstatic PartSysParamKeyframes* ParseKeyframes(gsl::cstring_span<> value, float parentLifespan);\n\n\tstatic PartSysParamRandom* ParseRandom(gsl::cstring_span<> value);\n\n\tstatic PartSysParamSpecial* ParseSpecial(gsl::cstring_span<> value);\n\n\tstatic PartSysParamConstant* ParseConstant(gsl::cstring_span<> value, float defaultValue, bool& success);\n\n};\n\n}\n", "meta": {"hexsha": "b093f03202cd20000f3fc32f12f18d1f3b7334af", "size": 915, "ext": "h", "lang": "C", "max_stars_repo_path": "ParticleSystems/include/particles/parser_params.h", "max_stars_repo_name": "edoipi/TemplePlus", "max_stars_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 69.0, "max_stars_repo_stars_event_min_datetime": "2015-05-05T14:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T06:13:04.000Z", "max_issues_repo_path": "ParticleSystems/include/particles/parser_params.h", "max_issues_repo_name": "edoipi/TemplePlus", "max_issues_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 457.0, "max_issues_repo_issues_event_min_datetime": "2015-05-01T22:07:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T02:19:10.000Z", "max_forks_repo_path": "ParticleSystems/include/particles/parser_params.h", "max_forks_repo_name": "edoipi/TemplePlus", "max_forks_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2016-02-04T21:19:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T23:14:51.000Z", "avg_line_length": 26.1428571429, "max_line_length": 106, "alphanum_fraction": 0.6327868852, "num_tokens": 185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3174262655876759, "lm_q2_score": 0.020964238409618103, "lm_q1q2_score": 0.006654599909254792}}
{"text": "//**************************************************************************\\\n//* This file is property of and copyright by the ALICE Project            *\\\n//* ALICE Experiment at CERN, All rights reserved.                         *\\\n//*                                                                        *\\\n//* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no>        *\\\n//*                  for The ALICE HLT Project.                            *\\\n//*                                                                        *\\\n//* Permission to use, copy, modify and distribute this software and its   *\\\n//* documentation strictly for non-commercial purposes is hereby granted   *\\\n//* without fee, provided that the above copyright notice appears in all   *\\\n//* copies and that both the copyright notice and this permission notice   *\\\n//* appear in the supporting documentation. The authors make no claims     *\\\n//* about the suitability of this software for any purpose. It is          *\\\n//* provided \"as is\" without express or implied warranty.                  *\\\n//**************************************************************************\n\n/// \\file GPUO2InterfaceConfiguration.h\n/// \\author David Rohr\n\n#ifndef GPUO2INTERFACECONFIGURATION_H\n#define GPUO2INTERFACECONFIGURATION_H\n\n#ifndef HAVE_O2HEADERS\n#define HAVE_O2HEADERS\n#endif\n#ifndef GPUCA_TPC_GEOMETRY_O2\n#define GPUCA_TPC_GEOMETRY_O2\n#endif\n#ifndef GPUCA_O2_INTERFACE\n#define GPUCA_O2_INTERFACE\n#endif\n\n#include <memory>\n#include <array>\n#include <vector>\n#include <functional>\n#include <gsl/gsl>\n#include \"GPUSettings.h\"\n#include \"GPUDataTypes.h\"\n#include \"GPUHostDataTypes.h\"\n#include \"GPUOutputControl.h\"\n#include \"DataFormatsTPC/Constants.h\"\n\nclass TH1F;\nclass TH1D;\nclass TH2F;\n\nnamespace o2\n{\nnamespace tpc\n{\nclass TrackTPC;\nclass Digit;\n} // namespace tpc\nnamespace gpu\n{\nclass TPCFastTransform;\nclass GPUReconstruction;\nstruct GPUSettingsO2;\n\nstruct GPUInterfaceQAOutputs {\n  const std::vector<TH1F>* hist1;\n  const std::vector<TH2F>* hist2;\n  const std::vector<TH1D>* hist3;\n};\n\nstruct GPUInterfaceOutputs : public GPUTrackingOutputs {\n  GPUInterfaceQAOutputs qa;\n};\n\n// Full configuration structure with all available settings of GPU...\nstruct GPUO2InterfaceConfiguration {\n  GPUO2InterfaceConfiguration() = default;\n  ~GPUO2InterfaceConfiguration() = default;\n  GPUO2InterfaceConfiguration(const GPUO2InterfaceConfiguration&) = default;\n\n  // Settings for the Interface class\n  struct GPUInterfaceSettings {\n    int dumpEvents = 0;\n    bool outputToExternalBuffers = false;\n    float memoryBufferScaleFactor = 1.f;\n    // These constants affect GPU memory allocation only and do not limit the CPU processing\n    unsigned long maxTPCZS = 8192ul * 1024 * 1024;\n    unsigned int maxTPCHits = 1024 * 1024 * 1024;\n    unsigned int maxTRDTracklets = 128 * 1024;\n    unsigned int maxITSTracks = 96 * 1024;\n  };\n\n  GPUSettingsDeviceBackend configDeviceBackend;\n  GPUSettingsProcessing configProcessing;\n  GPUSettingsGRP configGRP;\n  GPUSettingsRec configReconstruction;\n  GPUSettingsDisplay configDisplay;\n  GPUSettingsQA configQA;\n  GPUInterfaceSettings configInterface;\n  GPURecoStepConfiguration configWorkflow;\n  GPUCalibObjects configCalib;\n\n  GPUSettingsO2 ReadConfigurableParam();\n\n private:\n  friend class GPUReconstruction;\n  GPUSettingsO2 ReadConfigurableParam_internal();\n};\n\n} // namespace gpu\n} // namespace o2\n\n#endif\n", "meta": {"hexsha": "e5b81b0489f3bb0a3415d29dd51a7185a1ff06e4", "size": 3425, "ext": "h", "lang": "C", "max_stars_repo_path": "GPU/GPUTracking/Interface/GPUO2InterfaceConfiguration.h", "max_stars_repo_name": "chengtt0406/AliRoot", "max_stars_repo_head_hexsha": "c1d89b133b433f608b2373112d3608d8cec26095", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 52.0, "max_stars_repo_stars_event_min_datetime": "2016-12-11T13:04:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T11:49:35.000Z", "max_issues_repo_path": "GPU/GPUTracking/Interface/GPUO2InterfaceConfiguration.h", "max_issues_repo_name": "chengtt0406/AliRoot", "max_issues_repo_head_hexsha": "c1d89b133b433f608b2373112d3608d8cec26095", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1388.0, "max_issues_repo_issues_event_min_datetime": "2016-11-01T10:27:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T15:26:09.000Z", "max_forks_repo_path": "GPU/GPUTracking/Interface/GPUO2InterfaceConfiguration.h", "max_forks_repo_name": "chengtt0406/AliRoot", "max_forks_repo_head_hexsha": "c1d89b133b433f608b2373112d3608d8cec26095", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 275.0, "max_forks_repo_forks_event_min_datetime": "2016-06-21T20:24:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T13:06:19.000Z", "avg_line_length": 31.1363636364, "max_line_length": 92, "alphanum_fraction": 0.6738686131, "num_tokens": 766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.17553807362342938, "lm_q2_score": 0.03789242567892773, "lm_q1q2_score": 0.006651563408597941}}
{"text": "/*\n * Copyright 2017 RIS.\n * Authored by Ron Dahlgren <ron@red83.net>\n */\n#ifndef GLOBALS_H_\n#define GLOBALS_H_\n\n#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n\n#include <GL/glew.h>\n#include <GLFW/glfw3.h>\n\n#include <unistd.h>\n#include <ctype.h>\n#include <math.h>\n#include <getopt.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <stdint.h>\n#include <string.h>\n#include <stdlib.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_vector.h>\n\ntypedef int sd_result;\n\nstatic const sd_result SD_OK = 0;\nstatic const sd_result SD_RENDER_INIT_FAILURE = 1;\nstatic const sd_result SD_WINDOW_CREATION_FAILURE = 2;\nstatic const sd_result SD_NO_FREE_HANDLES = 3;\nstatic const sd_result SD_CHECK_ERRNO = 4;\nstatic const sd_result SD_GEN_ERROR = 5;\nstatic const sd_result SD_SCRIPT_SYNTAX = 6;\nstatic const sd_result SD_SCRIPT_TYPE_ERROR = 7;\nstatic const sd_result SD_SCRIPT_GENERAL_ERROR = 8;\nstatic const sd_result SD_FAILED_TO_READ_NUMBER = 9;\n\n// Transform component indication flags\nstatic const uint8_t XFORM_X_AXIS =         (1 << 0);\nstatic const uint8_t XFORM_Y_AXIS =         (1 << 1);\nstatic const uint8_t XFORM_Z_AXIS =         (1 << 2);\nstatic const uint8_t XFORM_TRANSLATION =    (1 << 3);\nstatic const uint8_t XFORM_TRANSLATION_X =  (1 << 4);\nstatic const uint8_t XFORM_TRANSLATION_Y =  (1 << 5);\nstatic const uint8_t XFORM_TRANSLATION_Z =  (1 << 6);\n\n#endif\n", "meta": {"hexsha": "172c3348045509ec909c622f345cf029090e05ce", "size": 1388, "ext": "h", "lang": "C", "max_stars_repo_path": "src/globals.h", "max_stars_repo_name": "influenza/c8", "max_stars_repo_head_hexsha": "2cc34f384cedce9626e76be8ea22e5967db1b69b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/globals.h", "max_issues_repo_name": "influenza/c8", "max_issues_repo_head_hexsha": "2cc34f384cedce9626e76be8ea22e5967db1b69b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/globals.h", "max_forks_repo_name": "influenza/c8", "max_forks_repo_head_hexsha": "2cc34f384cedce9626e76be8ea22e5967db1b69b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2156862745, "max_line_length": 54, "alphanum_fraction": 0.7406340058, "num_tokens": 393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30735801686526387, "lm_q2_score": 0.02161533158090494, "lm_q1q2_score": 0.006643645448592052}}
{"text": "#pragma once\n\n#include <gsl.h>\n#include <boost/optional.hpp>\n\n#include <mitkPythonService.h>\n\n#include <QObject>\n#include <QSet>\n#include <QString>\n#include <QVariant>\n#include <QVariantList>\n#include <QVector>\n\n#include <SolidData.h>\n#include <FaceIdentifier.h>\n#include <ISolverStudyData.h>\n#include <MeshData.h>\n#include <VesselForestData.h>\n#include <PCMRIData.h>\n\n#include \"PythonSolverSetupServiceActivator.h\"\n#include <PythonSolverSetupManager.h>\n#include \"PythonSolverSetupServiceExports.h\"\n\nnamespace crimson\n{\n\nclass   FaceTypeQtWrapper : public QObject\n{\n    Q_OBJECT\npublic:\n    Q_ENUMS(FaceType);\n    enum FaceType {\n        ftCapInflow = FaceIdentifier::ftCapInflow,\n        ftCapOutflow = FaceIdentifier::ftCapOutflow,\n        ftWall = FaceIdentifier::ftWall,\n\n        ftUndefined = FaceIdentifier::ftUndefined\n    };\n};\n\nclass   ArrayDataTypeQtWrapper : public QObject\n{\n    Q_OBJECT\npublic:\n    Q_ENUMS(ArrayDataType);\n    enum class ArrayDataType {\n        Int = 0,\n        Double = 1,\n    };\n};\n\nclass   PyFaceIdentifier\n{\npublic:\n    static PythonQtObjectPtr cppToPy(const FaceIdentifier& cppFaceId)\n    {\n        auto pythonService = PythonSolverSetupServiceActivator::getPythonService();\n\n        pythonService->Execute(\"import CRIMSONCore\");\n\n        QVariantList parentSolidIndices;\n        for (const auto& parentSolidIndex : cppFaceId.parentSolidIndices) {\n            parentSolidIndices << QString::fromStdString(parentSolidIndex);\n        }\n\n        auto result = PythonQtObjectPtr{pythonService->GetPythonManager()->mainContext().call(\n            \"CRIMSONCore.FaceIdentifier.FaceIdentifier\",\n            QVariantList{static_cast<FaceTypeQtWrapper::FaceType>(cppFaceId.faceType), parentSolidIndices})};\n        Ensures(!result.isNull());\n        return result;\n    }\n\n    static boost::optional<FaceIdentifier> pyToCpp(PythonQtObjectPtr pyFaceId)\n    {\n        FaceIdentifier cppFaceId;\n\n        QVariant faceIdVariant = pyFaceId.getVariable(\"faceType\");\n        if (!faceIdVariant.canConvert<int>()) {\n            MITK_ERROR << \"Face identifier not recognized - wrong faceType (expected int)\";\n            return boost::none;\n        }\n        cppFaceId.faceType = static_cast<FaceIdentifier::FaceType>(faceIdVariant.toInt());\n\n        QVariant parentSolidIndicesVariant = pyFaceId.getVariable(\"parentSolidIndices\");\n        if (!parentSolidIndicesVariant.canConvert<QVariantList>()) {\n            MITK_ERROR << \"Face identifier not recognized - wrong parentSolidIndices (expected list of strings)\";\n            return boost::none;\n        }\n\n        for (const auto& parentSolidIndexVariant : parentSolidIndicesVariant.toList()) {\n            if (!parentSolidIndexVariant.canConvert<QString>()) {\n                MITK_ERROR << \"Face identifier not recognized - wrong item in parentSolidIndices (expected string)\";\n                return boost::none;\n            }\n\n            cppFaceId.parentSolidIndices.insert(parentSolidIndexVariant.toString().toStdString());\n        }\n\n        return cppFaceId;\n    }\n};\n\nclass   Utils : public QObject\n{\n    Q_OBJECT\npublic slots:\n    void static_Utils_reloadAll() { crimson::PythonSolverSetupServiceActivator::reloadPythonSolverSetups(true); }\n\n    void static_Utils_logError(QString message) { MITK_ERROR << message.toStdString(); }\n\n    void static_Utils_logWarning(QString message) { MITK_WARN << message.toStdString(); }\n\n    void static_Utils_logInformation(QString message) { MITK_INFO << message.toStdString(); }\n};\n\nclass   SolidDataQtWrapper : public QObject\n{\n    Q_OBJECT\npublic:\n\tSolidDataQtWrapper()\n        : _brep(nullptr)\n    {\n    }\n\tSolidDataQtWrapper(gsl::not_null<const SolidData*> brep)\n        : _brep(brep)\n    {\n    }\n\n\tSolidDataQtWrapper(const SolidDataQtWrapper& other)\n        : _brep(other._brep)\n    {\n    }\n\npublic slots:\n\n    QVector<double> getFaceNormal(PythonQtObjectPtr pyFaceIdentifier) const\n    {\n        Expects(_brep != nullptr);\n        auto cppFaceIdOptional = PyFaceIdentifier::pyToCpp(pyFaceIdentifier);\n\n        if (!cppFaceIdOptional) {\n            return {};\n        }\n\n        auto normal = _brep->getFaceNormal(cppFaceIdOptional.get());\n        return QVector<double>{normal[0], normal[1], normal[2]};\n    }\n\n    double getDistanceToFaceEdge(PythonQtObjectPtr pyFaceIdentifier, double x, double y, double z) const\n    {\n        Expects(_brep != nullptr);\n        auto cppFaceIdOptional = PyFaceIdentifier::pyToCpp(pyFaceIdentifier);\n\n        if (!cppFaceIdOptional) {\n            return 0;\n        }\n\n        auto pos = mitk::Point3D{};\n        pos[0] = x;\n        pos[1] = y;\n        pos[2] = z;\n        return _brep->getDistanceToFaceEdge(cppFaceIdOptional.get(), pos);\n    }\n\n    PythonQtObjectPtr getFaceIdentifierForModelFace(int faceIndex) const\n    {\n        Expects(_brep != nullptr);\n        auto identifierOpt = _brep->getFaceIdentifierMap().getFaceIdentifierForModelFace(faceIndex);\n        return identifierOpt ? PyFaceIdentifier::cppToPy(identifierOpt.get()) : nullptr;\n    }\n\n    int getNumberOfModelFaces() const\n    {\n        Expects(_brep != nullptr);\n        return _brep->getFaceIdentifierMap().getNumberOfModelFaces();\n    }\n\n    int getNumberOfFaceIdentifiers() const\n    {\n        Expects(_brep != nullptr);\n        return _brep->getFaceIdentifierMap().getNumberOfFaceIdentifiers();\n    }\n\n    int faceIdentifierIndex(PythonQtObjectPtr pyFaceIdentifier) const\n    {\n        Expects(_brep != nullptr);\n\n        auto cppFaceIdOptional = PyFaceIdentifier::pyToCpp(pyFaceIdentifier);\n\n        if (!cppFaceIdOptional) {\n            return 0;\n        }\n\n        return _brep->getFaceIdentifierMap().faceIdentifierIndex(cppFaceIdOptional.get());\n    }\n\n    PythonQtObjectPtr getFaceIdentifier(int uniqueFaceId) const\n    {\n        Expects(_brep != nullptr);\n        return PyFaceIdentifier::cppToPy(_brep->getFaceIdentifierMap().getFaceIdentifier(uniqueFaceId));\n    }\n\n    QVector<int> getModelFacesForFaceIdentifier(PythonQtObjectPtr pyFaceIdentifier) const\n    {\n        Expects(_brep != nullptr);\n        auto cppFaceIdOptional = PyFaceIdentifier::pyToCpp(pyFaceIdentifier);\n\n        if (!cppFaceIdOptional) {\n            return {};\n        }\n\n        return QVector<int>::fromStdVector(_brep->getFaceIdentifierMap().getModelFacesForFaceIdentifier(cppFaceIdOptional.get()));\n    }\n\nprivate:\n\tconst SolidData* _brep;\n};\n\nclass   MeshDataQtWrapper : public QObject\n{\n    Q_OBJECT\npublic:\n    MeshDataQtWrapper()\n        : _mesh(nullptr)\n    {\n    }\n    MeshDataQtWrapper(gsl::not_null<const MeshData*> mesh)\n        : _mesh(mesh)\n    {\n    }\n\n    MeshDataQtWrapper(const MeshDataQtWrapper& other)\n        : _mesh(other._mesh)\n    {\n    }\n\npublic slots:\n\n    int getNNodes() const\n    {\n        Expects(_mesh != nullptr);\n        return _mesh->getNNodes();\n    }\n\n    int getNEdges() const\n    {\n        Expects(_mesh != nullptr);\n        return _mesh->getNEdges();\n    }\n\n    int getNFaces() const\n    {\n        Expects(_mesh != nullptr);\n        return _mesh->getNFaces();\n    }\n\n    int getNElements() const\n    {\n        Expects(_mesh != nullptr);\n        return _mesh->getNElements();\n    }\n\n    QVector<double> getNodeCoordinates(int nodeIndex) const\n    {\n        Expects(_mesh != nullptr);\n        auto coords = _mesh->getNodeCoordinates(nodeIndex);\n        return QVector<double>{coords[0], coords[1], coords[2]};\n    }\n\n    QVector<int> getElementNodeIds(int elementIndex) const\n    {\n        Expects(_mesh != nullptr);\n        return QVector<int>::fromStdVector(_mesh->getElementNodeIds(elementIndex));\n    }\n\n    QVector<int> getAdjacentElements(int elementIndex) const\n    {\n        Expects(_mesh != nullptr);\n        return QVector<int>::fromStdVector(_mesh->getAdjacentElements(elementIndex));\n    }\n\n    QVector<int> getNodeIdsForFace(PythonQtObjectPtr pyFaceIdentifier) const\n    {\n        Expects(_mesh != nullptr);\n        auto cppFaceIdOptional = PyFaceIdentifier::pyToCpp(pyFaceIdentifier);\n\n        if (!cppFaceIdOptional) {\n            return {};\n        }\n\n        return QVector<int>::fromStdVector(_mesh->getNodeIdsForFace(cppFaceIdOptional.get()));\n    }\n\n    QVariantList getMeshFaceInfoForFace(PythonQtObjectPtr pyFaceIdentifier) const // TODO: QVector<QVector<int>>\n    {\n        Expects(_mesh != nullptr);\n        auto cppFaceIdOptional = PyFaceIdentifier::pyToCpp(pyFaceIdentifier);\n\n        if (!cppFaceIdOptional) {\n            return {};\n        }\n\n        auto faceInfos = _mesh->getMeshFaceInfoForFace(cppFaceIdOptional.get());\n\n        auto out = QVariantList{};\n        out.reserve(faceInfos.size());\n        std::transform(\n            faceInfos.begin(), faceInfos.end(), std::back_inserter(out),\n            [](const crimson::MeshData::MeshFaceInfo& info) {\n                return QVariant::fromValue(QVector<int>{info.elementId, info.globalFaceId, info.nodeIds[0], info.nodeIds[1], info.nodeIds[2]});\n            });\n        return out;\n    }\n\nprivate:\n    const MeshData* _mesh;\n};\n\nclass   VesselForestDataQtWrapper : public QObject\n{\n    Q_OBJECT\npublic:\n    using UIDToVesselPathDataMap = std::unordered_map<std::string, const VesselPathAbstractData*>;\n\n    VesselForestDataQtWrapper()\n        : _vesselForest(nullptr)\n    {\n    }\n    VesselForestDataQtWrapper(gsl::not_null<const VesselForestData*> data, UIDToVesselPathDataMap uidToVesselPathDataMap)\n        : _vesselForest(data)\n        , _uidToVesselPathDataMap(std::move(uidToVesselPathDataMap))\n    {\n    }\n\n    VesselForestDataQtWrapper(const VesselForestDataQtWrapper& other)\n        : _vesselForest(other._vesselForest)\n        , _uidToVesselPathDataMap(other._uidToVesselPathDataMap)\n    {\n    }\n//    VesselForestDataQtWrapper(const VesselForestDataQtWrapper&) = default;\n\n    const UIDToVesselPathDataMap& getUIDToVesselPathDataMap() const { return _uidToVesselPathDataMap; }\n\npublic slots:\n    QVariantMap getActiveConnectedComponentsMap() const\n    {\n        Expects(_vesselForest != nullptr);\n\n        auto result = QVariantMap{};\n        for (const auto& uidComponentIndexPair : _vesselForest->computeActiveConnectedComponents()) {\n            result[QString::fromStdString(uidComponentIndexPair.first)] = uidComponentIndexPair.second;\n        }\n\n        return result;\n    }\n\n    QVariantList getClosestPoint(PythonQtObjectPtr pyFaceIdentifier, double x, double y, double z) const\n    {\n        Expects(_vesselForest != nullptr);\n\n        auto closestPathInfo = _getClosestVesselPath(pyFaceIdentifier, x, y, z);\n        if (!closestPathInfo.vesselPath) {\n            return {};\n        }\n\n        return QVariantList{closestPathInfo.distance, closestPathInfo.t};\n    }\n\n    QVector<double> getVesselPathCoordinateFrame(PythonQtObjectPtr pyFaceIdentifier, double x, double y, double z) const\n    {\n        auto closestPathInfo = _getClosestVesselPath(pyFaceIdentifier, x, y, z);\n        if (!closestPathInfo.vesselPath) {\n            return{};\n        }\n\n        auto pt = closestPathInfo.vesselPath->getPosition(closestPathInfo.t);\n        auto tangent = closestPathInfo.vesselPath->getTangentVector(closestPathInfo.t);\n        auto normal = closestPathInfo.vesselPath->getNormalVector(closestPathInfo.t);\n\n        return QVector<double>{pt[0], pt[1], pt[2], tangent[0], tangent[1], tangent[2], normal[0], normal[1], normal[2]};\n    }\n\nprivate:\n    struct ClosestVesselPathInfo {\n        const VesselPathAbstractData* vesselPath = nullptr;\n        double distance = 0;\n        double t = 0;\n    };\n\n    ClosestVesselPathInfo _getClosestVesselPath(PythonQtObjectPtr pyFaceIdentifier, double x, double y, double z) const\n    {\n        auto cppFaceIdOptional = PyFaceIdentifier::pyToCpp(pyFaceIdentifier);\n\n        if (!cppFaceIdOptional) {\n            return {};\n        }\n\n        auto&& parentSolidIndices = cppFaceIdOptional->parentSolidIndices;\n\n        auto result = ClosestVesselPathInfo{};\n\n        auto pos = mitk::Point3D{};\n        mitk::FillVector3D(pos, x, y, z);\n        for (const auto& vesselUID : parentSolidIndices) {\n            auto closestPointRequestResult = _uidToVesselPathDataMap.at(vesselUID)->getClosestPoint(pos);\n\n            auto d = closestPointRequestResult.closestPoint.EuclideanDistanceTo(pos);\n            if (result.vesselPath == nullptr || d < result.distance) {\n                result.vesselPath = _uidToVesselPathDataMap.at(vesselUID);\n                result.t = closestPointRequestResult.t;\n                result.distance = d;\n            }\n        }\n\n        return result;\n    }\n\n\n    const VesselForestData* _vesselForest;\n    UIDToVesselPathDataMap _uidToVesselPathDataMap;\n};\n\nclass   PCMRIDataQtWrapper : public QObject\n{\n\tQ_OBJECT\npublic:\n\tPCMRIDataQtWrapper()\n\t\t: _pcmriData(nullptr)\n\t{\n\t}\n\tPCMRIDataQtWrapper(gsl::not_null<const PCMRIData*> pcmriData)\n\t\t: _pcmriData(pcmriData)\n\t{\n\t}\n\n\tPCMRIDataQtWrapper(const PCMRIDataQtWrapper& other)\n\t\t: _pcmriData(other._pcmriData)\n\t{\n\t}\n\npublic slots:\n\n\tQVector<double> getTimepoints() const\n\t{\n\t\tExpects(_pcmriData != nullptr);\n\t\treturn QVector<double>::fromStdVector(_pcmriData->getTimepoints());\n\t}\n\n\tQVector<double> getFlowWaveform() const\n\t{\n\t\tExpects(_pcmriData != nullptr);\n\t\treturn QVector<double>::fromStdVector(_pcmriData->getFlowWaveform());\n\t}\n\n\tQVector<double> getSingleMappedPCMRIvector(int pointIndex, int timepointIndex) const\n\t{\n\t\tExpects(_pcmriData != nullptr);\n\t\tauto coords = _pcmriData->getSingleMappedPCMRIvector(pointIndex, timepointIndex);\n\t\treturn QVector<double>{coords[0], coords[1], coords[2]};\n\t}\n\nprivate:\n\tconst PCMRIData* _pcmriData;\n};\n}\n\nQ_DECLARE_METATYPE(crimson::SolidDataQtWrapper)\nQ_DECLARE_METATYPE(crimson::MeshDataQtWrapper)\nQ_DECLARE_METATYPE(crimson::VesselForestDataQtWrapper)\nQ_DECLARE_METATYPE(crimson::PCMRIDataQtWrapper)\n", "meta": {"hexsha": "fbfcf15b77ac0ab3d0e6b4ac9260367f3d52cd47", "size": 13708, "ext": "h", "lang": "C", "max_stars_repo_path": "Modules/PythonSolverSetupService/src/PythonQtWrappers.h", "max_stars_repo_name": "carthurs/CRIMSONGUI", "max_stars_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-09-17T18:55:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T02:52:38.000Z", "max_issues_repo_path": "Modules/PythonSolverSetupService/src/PythonQtWrappers.h", "max_issues_repo_name": "carthurs/CRIMSONGUI", "max_issues_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Modules/PythonSolverSetupService/src/PythonQtWrappers.h", "max_forks_repo_name": "carthurs/CRIMSONGUI", "max_forks_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-05-19T09:02:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-26T17:39:57.000Z", "avg_line_length": 28.9809725159, "max_line_length": 143, "alphanum_fraction": 0.6761744966, "num_tokens": 3334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3073580168652638, "lm_q2_score": 0.0216153315021221, "lm_q1q2_score": 0.006643645424377512}}
{"text": "/**\r\n * @copyright (c) 2012- King Abdullah University of Science and\r\n *                      Technology (KAUST). All rights reserved.\r\n **/\r\n\r\n\r\n/**\r\n * @file testing/testing_helper.h\r\n\r\n * KBLAS is a high performance CUDA library for subset of BLAS\r\n *    and LAPACK routines optimized for NVIDIA GPUs.\r\n * KBLAS is provided by KAUST.\r\n *\r\n * @version 3.0.0\r\n * @author Wajih Halim Boukaram\r\n * @author Ali Charara\r\n * @date 2018-11-14\n **/\r\n\r\n#ifndef __TESTING_HELPER_H__\r\n#define __TESTING_HELPER_H__\r\n\r\n#include <cuda.h>\r\n#include <cuda_runtime.h>\r\n#include <cuda_runtime_api.h>\r\n#include <cublas_v2.h>\r\n#include <kblas.h>\r\n#include <cusolverDn.h>\r\n\r\n#ifdef USE_MAGMA\r\n#include <magma_v2.h>\r\n#endif\r\n#ifdef USE_MKL\r\n#include <mkl.h>\r\n#else\r\n#include <cblas.h>\t\t//TODO: if MKL not set we need to use other libs\r\n#include <lapacke.h>\r\n#endif\r\n#ifdef USE_OPENMP\r\n#include <omp.h>\r\n#endif\r\n#include <kblas.h>\r\n\r\n#ifdef __cplusplus\r\nextern \"C\" {\r\n#endif\r\n\r\ninline int iDivUp( int a, int b ) { return (a % b != 0) ? (a / b + 1) : (a / b); }\r\n\r\n#define kmin(a,b) ((a)>(b)?(b):(a))\r\n#define kmax(a,b) ((a)<(b)?(b):(a))\r\nint kblas_roundup(int x, int y);\r\n\r\n////////////////////////////////////////////////////////////\r\n// Error checking\r\n////////////////////////////////////////////////////////////\r\n#define check_error(ans) { gpuAssert((ans), __FILE__, __LINE__); }\r\nvoid gpuAssert(cudaError_t code, const char *file, int line);\r\n\r\n#define check_cublas_error(ans) { gpuCublasAssert((ans), __FILE__, __LINE__); }\r\nvoid gpuCublasAssert(cublasStatus_t code, const char *file, int line);\r\n\r\n#define check_kblas_error(ans) { gpuKblasAssert((ans), __FILE__, __LINE__); }\r\nvoid gpuKblasAssert(int code, const char *file, int line);\r\n\r\n#define check_cusolver_error(ans) { gpuCusolverAssert((ans), __FILE__, __LINE__); }\r\nvoid gpuCusolverAssert(cusolverStatus_t code, const char *file, int line);\r\n\r\n////////////////////////////////////////////////////////////\r\n// Timers and related stuff\r\n////////////////////////////////////////////////////////////\r\ndouble gettime(void);\r\n\r\nstruct GPU_Timer;\r\ntypedef GPU_Timer* GPU_Timer_t;\r\n\r\nGPU_Timer_t newGPU_Timer(cudaStream_t stream);\r\nvoid deleteGPU_Timer(GPU_Timer_t timer);\r\nvoid gpuTimerTic(GPU_Timer_t timer);\r\nvoid gpuTimerRecordEnd(GPU_Timer_t timer);\r\ndouble gpuTimerToc(GPU_Timer_t timer);\r\n\r\nvoid avg_and_stdev(double* values, int num_vals, double* avg, double* std_dev, int warmup);\r\n\r\n////////////////////////////////////////////////////////////\r\n// Generate array of pointers from a strided array\r\n////////////////////////////////////////////////////////////\r\nvoid generateDArrayOfPointers(double* original_array, double** array_of_arrays, int stride, int num_arrays, cudaStream_t stream);\r\nvoid generateSArrayOfPointers(float* original_array, float** array_of_arrays, int stride, int num_arrays, cudaStream_t stream);\r\nvoid generateDArrayOfPointersHost(double* original_array, double** array_of_arrays, int stride, int num_arrays);\r\nvoid generateSArrayOfPointersHost(float* original_array, float** array_of_arrays, int stride, int num_arrays);\r\n\r\n// Reductions \r\nint getMaxElement(int* a, size_t elements, cudaStream_t stream);\r\nint getMinElement(int* a, size_t elements, cudaStream_t stream);\r\n\r\n////////////////////////////////////////////////////////////\r\n// Allocations\r\n////////////////////////////////////////////////////////////\r\n#define TESTING_MALLOC_CPU( ptr, T, size)                       \\\r\n{\t\t\t\\\r\n  if ( (ptr = (T*) malloc( (size)*sizeof( T ) ) ) == NULL) {    \\\r\n    fprintf( stderr, \"!!!! malloc_cpu failed for: %s\\n\", #ptr ); \\\r\n    exit(-1);                                                   \\\r\n  } \\\r\n}\r\n#define TESTING_MALLOC_DEV( ptr, T, size) check_error( cudaMalloc( (void**)&ptr, (size)*sizeof(T) ) )\r\n#define TESTING_MALLOC_PIN( ptr, T, size) check_error( cudaHostAlloc ( (void**)&ptr, (size)*sizeof( T ), cudaHostAllocPortable  ))\r\n\r\n#define TESTING_FREE_CPU(ptr)\t{ if( (ptr) ) free( (ptr) ); }\r\n#define TESTING_FREE_DEV(ptr)\tcheck_error( cudaFree( (ptr) ) );\r\n\r\n////////////////////////////////////////////////////////////\r\n// Data generation\r\n////////////////////////////////////////////////////////////\r\nvoid generateDrandom(double* random_data, long num_elements, int num_ops);\r\nvoid generateSrandom(float* random_data, long num_elements, int num_ops);\r\nvoid srand_matrix(long rows, long cols, float* A, long LDA);\r\nvoid drand_matrix(long rows, long cols, double* A, long LDA);\r\nvoid crand_matrix(long rows, long cols, cuFloatComplex* A, long LDA);\r\nvoid zrand_matrix(long rows, long cols, cuDoubleComplex* A, long LDA);\r\n\r\nvoid smatrix_make_hpd(int N, float* A, int lda);\r\nvoid dmatrix_make_hpd(int N, double* A, int lda);\r\nvoid cmatrix_make_hpd(int N, cuFloatComplex* A, int lda);\r\nvoid zmatrix_make_hpd(int N, cuDoubleComplex* A, int lda);\r\n\r\nvoid generateRandDimensions(int minDim, int maxDim, int* randDims, int seed, int num_ops);\r\nvoid fillIntArray(int* array_vals, int value, int num_elements);\r\n\r\nvoid fillGPUIntArray(int* array_vals, int value, int num_elements, cudaStream_t stream);\r\nvoid copyGPUPointerArray(void** originalPtrs, void** copyPtrs, int num_ptrs, cudaStream_t stream);\r\n\r\n// set cond = 0 to use exp decay\r\nvoid generateDrandomMatrices(\r\n\tdouble* M_strided, int stride_M, double* svals_strided, int stride_S, int rows, int cols,\r\n\tdouble cond, double exp_decay, int seed, int num_ops, int threads\r\n);\r\nvoid generateSrandomMatrices(\r\n\tfloat* M_strided, int stride_M, float* svals_strided, int stride_S, int rows, int cols,\r\n\tfloat cond, float exp_decay, int seed, int num_ops, int threads\r\n);\r\n\r\n// Mode = 0: use provided singualr values\r\n// Mode = 1: sets singular values to random numbers in the range (1/cond, 1) \r\n// Mode = 2: generate singular values such that S(i) = exp(-exp_decay * i); \r\n//\t     \t where exp_decay is a random value between exp_decay_min and exp_decay_max\r\nvoid generateDrandomMatricesArray(\r\n\tdouble** M_ptrs, int* ldm_array, double** svals_ptrs, int *rows_array, int *cols_array,\r\n\tint mode, double cond, double exp_decay_min, double exp_decay_max, int seed, int num_ops, int threads\r\n);\r\nvoid generateSrandomMatricesArray(\r\n\tfloat** M_ptrs, int* ldm_array, float** svals_ptrs, int *rows_array, int *cols_array,\r\n\tint mode, float cond, float exp_decay_min, float exp_decay_max, int seed, int num_ops, int threads\r\n);\r\n\r\nvoid generateSsingular_values(float** svals_ptrs, int rank, float min_sval, float max_sval, int seed, int batchCount);\r\nvoid generateDsingular_values(double** svals_ptrs, int rank, double min_sval, double max_sval, int seed, int batchCount);\r\n\r\n////////////////////////////////////////////////////////////\r\n// Result checking\r\n////////////////////////////////////////////////////////////\r\n// Vectors\r\nfloat sget_max_error(float* ref, float *res, int n, int inc);\r\ndouble dget_max_error(double* ref, double *res, int n, int inc);\r\nfloat cget_max_error(cuFloatComplex* ref, cuFloatComplex *res, int n, int inc);\r\ndouble zget_max_error(cuDoubleComplex* ref, cuDoubleComplex *res, int n, int inc);\r\n// Matrices\r\nfloat sget_max_error_matrix(float* ref, float *res, long m, long n, long lda);\r\ndouble dget_max_error_matrix(double* ref, double *res, long m, long n, long lda);\r\nfloat cget_max_error_matrix(cuFloatComplex* ref, cuFloatComplex *res, long m, long n, long lda);\r\ndouble zget_max_error_matrix(cuDoubleComplex* ref, cuDoubleComplex *res, long m, long n, long lda);\r\n\r\ndouble dget_max_error_matrix_uplo(double* ref, double *res, long m, long n, long lda, char uplo);\r\n// float sget_max_error_matrix_uplo(float* ref, float *res, long m, long n, long lda, char uplo);\r\n// double dget_max_error_matrix_symm(double* ref, double *res, long m, long n, long lda, char uplo);\r\n\r\n#define printMatrix(m, n, A, lda, out) { \\\r\n  for(int r = 0; r < (m); r++){ \\\r\n    for(int c = 0; c < (n); c++){ \\\r\n      fprintf((out), \"%.7e  \", (A)[r + c * (lda)]); \\\r\n    } \\\r\n    fprintf((out), \"\\n\"); \\\r\n  } \\\r\n  fprintf((out), \"\\n\"); \\\r\n}\r\n\r\n////////////////////////////////////////////////////////////\r\n// Command line parser\r\n////////////////////////////////////////////////////////////\r\n#define MAX_NTEST 1000\r\n\r\ntypedef struct kblas_opts\r\n{\r\n\t// matrix size\r\n\tint ntest;\r\n\tint msize[ MAX_NTEST ];\r\n\tint nsize[ MAX_NTEST ];\r\n\tint ksize[ MAX_NTEST ];\r\n\tint rsize[ MAX_NTEST ];\r\n\r\n\t// scalars\r\n\tint devices[MAX_NGPUS];\r\n\tint nstream;\r\n\tint ngpu;\r\n\tint niter;\r\n\tint nruns;\r\n\tdouble      tolerance;\r\n\tint check;\r\n\tint verbose;\r\n\tint nb;\r\n\tint db;\r\n\tint custom;\r\n\tint warmup;\r\n\tint time;\r\n\tint lapack;\r\n\tint magma;\r\n\tint svd;\r\n\tint cuda;\r\n\tint nonUniform;\r\n\t//int bd[KBLAS_BACKDOORS];\r\n\tint batchCount;\r\n\tint strided;\r\n\tint btest, batch[MAX_NTEST];\r\n\tint rtest, rank[MAX_NTEST];\r\n\tint omp_numthreads;\r\n  char LR;//Low rank format\r\n  int version;\r\n\r\n\t// lapack flags\r\n\tchar uplo;\r\n\tchar transA;\r\n\tchar transB;\r\n\tchar side;\r\n\tchar diag;\r\n} kblas_opts;\r\n\r\nint parse_opts(int argc, char** argv, kblas_opts *opts);\r\n\r\n#ifdef __cplusplus\r\n}\r\n#endif\r\n\r\n\r\n#ifdef __cplusplus\r\n\r\n#define kmin(a,b) ((a)>(b)?(b):(a))\r\n#define kmax(a,b) ((a)<(b)?(b):(a))\r\n\r\n#include \"kblas_operators.h\"\r\ntemplate<class T, class T_complex>\r\nT get_magnitude(T_complex a){ return sqrt(a.x * a.x + a.y * a.y); }\r\ntemplate<class T>\r\nT get_magnitude(T ax, T ay){ return sqrt(ax * ax + ay * ay); }\r\n\r\ntemplate<typename T>\r\nbool kblas_laisnan(T val1, T val2){\r\n  return val1 != val2;\r\n}\r\n\r\ntemplate<typename T>\r\nbool kblas_isnan(T val){\r\n  return kblas_laisnan(val,val);\r\n}\r\n\r\ninline float Xabs(float a){return fabs(a);}\r\ninline double Xabs(double a){return fabs(a);}\r\ninline float Xabs(cuFloatComplex a){return get_magnitude<float,cuFloatComplex>(a);}\r\ninline double Xabs(cuDoubleComplex a){return get_magnitude<double,cuDoubleComplex>(a);}\r\n\r\ntemplate<class T>\r\nvoid matrix_make_hpd(int N, T* A, int lda, T diag)\r\n{\r\n  ssize_t ldas = ssize_t(lda);\r\n  for(ssize_t i = 0; i < ssize_t(N); i++)\r\n  {\r\n    A[i + i * ldas] = A[i + i * ldas] + diag;\r\n    for(ssize_t j = 0; j < i; j++){\r\n      A[j + i*ldas] = A[i + j*ldas];\r\n    }\r\n  }\r\n}\r\n\r\ntemplate<typename T, typename R>\r\nR kblas_lange(char type, int M, int N, T* arr, int lda){\r\n  R value = make_zero<R>();\r\n  R temp;\r\n  for(int j = 0; j < N; j++){\r\n    for(int i = 0; i < M; i++){\r\n      temp = Xabs(arr[i + j * lda]);\r\n      if( kblas_isnan(temp) ){\r\n        value = temp;\r\n        printf(\"NAN encountered (%d,%d)\\n\", i, j);\r\n        return value;\r\n      }\r\n      if( value < temp)\r\n        value = temp;\r\n    }\r\n  }\r\n  return value;\r\n}\r\n\r\ntemplate<typename T>\r\nvoid kblasXaxpy (int n, T alpha, const T *x, int incx, T *y, int incy){\r\n  int ix = 0, iy = 0;\r\n  if(incx < 0) ix = 1 - n * incx;\r\n  if(incy < 0) iy = 1 - n * incy;\r\n  for(int i = 0; i < n; i++, ix+=incx, iy+=incy){\r\n    y[iy] += alpha * x[ix];\r\n  }\r\n}\r\n\r\ntemplate<class T>\r\nvoid hilbertMatrix(int m, int n, T* A, int lda, T scal){\r\n  for(int r = 0; r < m; r++){\r\n    for(int c = 0; c < n; c++){\r\n      A[r + c*lda] = T(scal)/T(r+c+1);\r\n    }\r\n  }\r\n}\r\n\r\n#endif //__cplusplus\r\n\r\n#ifdef DBG_MSG\r\n#define ECHO_I(_val) printf(\"%s(%d) \", #_val, (_val));fflush( stdout )\r\n#define ECHO_f(_val) printf(\"%s(%e) \", #_val, (_val));fflush( stdout )\r\n#define ECHO_p(_val) printf(\"%s(%p) \", #_val, (_val));fflush( stdout )\r\n#define ECHO_LN printf(\"\\n\");fflush( stdout )\r\n#else\r\n#define ECHO_I(_val)\r\n#define ECHO_f(_val)\r\n#define ECHO_p(_val)\r\n#define ECHO_LN\r\n#endif\r\n\r\n#endif // __TESTING_HELPER_H__\r\n", "meta": {"hexsha": "9acc479f3fb2097bed52541312d962576556e528", "size": 11392, "ext": "h", "lang": "C", "max_stars_repo_path": "testing/testing_helper.h", "max_stars_repo_name": "ecrc/kblas-gpu", "max_stars_repo_head_hexsha": "fc8ad5ad471161d80746b462ecdf0d440923b46f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 41.0, "max_stars_repo_stars_event_min_datetime": "2016-08-28T08:32:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T12:33:28.000Z", "max_issues_repo_path": "testing/testing_helper.h", "max_issues_repo_name": "ecrc/kblas-gpu", "max_issues_repo_head_hexsha": "fc8ad5ad471161d80746b462ecdf0d440923b46f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2016-10-04T09:46:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-18T21:43:51.000Z", "max_forks_repo_path": "testing/testing_helper.h", "max_forks_repo_name": "ecrc/kblas-gpu", "max_forks_repo_head_hexsha": "fc8ad5ad471161d80746b462ecdf0d440923b46f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-09-06T09:06:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-03T08:33:39.000Z", "avg_line_length": 33.8041543027, "max_line_length": 131, "alphanum_fraction": 0.6213132022, "num_tokens": 3067, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09268778365193332, "lm_q2_score": 0.0715911920164097, "lm_q1q2_score": 0.006635628917000999}}
{"text": "//          Copyright Jean Pierre Cimalando 2019.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE.md or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n#pragma once\n#include \"keystate.h\"\n#include \"instruments/synth_fx.h\"\n#include <gsl/gsl>\n#include <string>\n#include <vector>\n#include <bitset>\n\nstruct Player_Song_Metadata {\n    std::string name;\n    std::string author;\n    std::vector<std::string> text;\n    char format[32] = {};\n    unsigned track_count = 0;\n};\n\nstruct Player_State {\n    Keyboard_State kb;\n    unsigned repeat_mode = 0;\n    double time_position = 0;\n    double duration = 0;\n    double tempo = 0;\n    unsigned speed = 100;\n    std::string file_path;\n    Player_Song_Metadata song_metadata;\n    std::bitset<16> channel_enabled;\n    float audio_levels[10] {};\n    int fx_parameters[Synth_Fx::Parameter_Count] {};\n};\n", "meta": {"hexsha": "cefb5ec58b9ad723ed0af7629f245b6729b396f5", "size": 897, "ext": "h", "lang": "C", "max_stars_repo_path": "sources/player/state.h", "max_stars_repo_name": "jpcima/smf-dsp", "max_stars_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2020-07-08T15:23:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T23:08:17.000Z", "max_issues_repo_path": "sources/player/state.h", "max_issues_repo_name": "jpcima/smf-dsp", "max_issues_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2020-07-05T23:59:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-16T20:44:07.000Z", "max_forks_repo_path": "sources/player/state.h", "max_forks_repo_name": "jpcima/smf-dsp", "max_forks_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-07-10T18:48:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-22T08:05:13.000Z", "avg_line_length": 25.6285714286, "max_line_length": 61, "alphanum_fraction": 0.6800445931, "num_tokens": 228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2628418373713166, "lm_q2_score": 0.025178839460401403, "lm_q1q2_score": 0.006618052426649315}}
{"text": "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\n#pragma once\n\n#include <gsl/span>\n\nnamespace onnxruntime {\nnamespace contrib {\n\ntemplate <typename T>\nclass IAttentionMechanism {\n public:\n  virtual ~IAttentionMechanism() = default;\n\n  virtual void PrepareMemory(\n    const gsl::span<const T>& memory,\n    const gsl::span<const int>& memory_sequence_lengths) = 0;\n\n  virtual void Compute(\n    const gsl::span<const T>& query,\n    const gsl::span<const T>& prev_alignment,\n    const gsl::span<T>& output,\n    const gsl::span<T>& alignment) const = 0;\n\n  virtual const gsl::span<const T> Values() const = 0;\n\n  virtual const gsl::span<const T> Keys() const = 0;\n\n  virtual int GetMaxMemorySteps() const = 0;\n\n  virtual bool NeedPrevAlignment() const = 0;\n};\n\n}\n}\n", "meta": {"hexsha": "c648536f997c578ffd008e8c22410eb5a112296e", "size": 808, "ext": "h", "lang": "C", "max_stars_repo_path": "onnxruntime/contrib_ops/cpu/attnlstm/attention_mechanism.h", "max_stars_repo_name": "hqucms/onnxruntime", "max_stars_repo_head_hexsha": "6e4e76414639f50836a64546603c8957227857b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-18T14:04:42.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-04T12:49:01.000Z", "max_issues_repo_path": "onnxruntime/contrib_ops/cpu/attnlstm/attention_mechanism.h", "max_issues_repo_name": "hqucms/onnxruntime", "max_issues_repo_head_hexsha": "6e4e76414639f50836a64546603c8957227857b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-10-08T14:20:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-19T16:56:52.000Z", "max_forks_repo_path": "onnxruntime/contrib_ops/cpu/attnlstm/attention_mechanism.h", "max_forks_repo_name": "hqucms/onnxruntime", "max_forks_repo_head_hexsha": "6e4e76414639f50836a64546603c8957227857b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-06-05T19:52:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-30T13:58:13.000Z", "avg_line_length": 21.8378378378, "max_line_length": 61, "alphanum_fraction": 0.698019802, "num_tokens": 201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25091278688527247, "lm_q2_score": 0.026355351603401207, "lm_q1q2_score": 0.006612894720150631}}
{"text": "/*\nODE: a program to get optime Runge-Kutta and multi-steps methods.\n\nCopyright 2011-2019, Javier Burguete Tolosa.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n\t1. Redistributions of source code must retain the above copyright notice,\n\t\tthis list of conditions and the following disclaimer.\n\n\t2. Redistributions in binary form must reproduce the above copyright notice,\n\t\tthis list of conditions and the following disclaimer in the\n\t\tdocumentation and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``AS IS'' AND ANY EXPRESS OR\nIMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT\nSHALL Javier Burguete Tolosa OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\nADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n/**\n * \\file utils.c\n * \\brief Source file with util functions.\n * \\author Javier Burguete Tolosa.\n * \\copyright Copyright 2011-2019.\n */\n#define _GNU_SOURCE\n#include <stdio.h>\n#include <math.h>\n#include <libxml/parser.h>\n#include <glib.h>\n#include <libintl.h>\n#include <gsl/gsl_rng.h>\n#include \"config.h\"\n#include \"utils.h\"\n\ngchar *error_message = NULL;    ///< error message string.\n\n/**\n * Function to print an error message.\n */\nvoid\nshow_error (const char *message)        ///< error message string.\n{\n  printf (\"%s\\n%s\\n\", _(\"ERROR!\"), message);\n}\n\n/**\n * Function to get an integer number of a XML node property.\n *\n * \\return Integer number value.\n */\nint\nxml_node_get_int (xmlNode * node,       ///< XML node.\n                  const xmlChar * prop, ///< XML property.\n                  int *error_code)      ///< Error code.\n{\n  int i = 0;\n  xmlChar *buffer;\n  buffer = xmlGetProp (node, prop);\n  if (!buffer)\n    *error_code = 1;\n  else\n    {\n      if (sscanf ((char *) buffer, \"%d\", &i) != 1)\n        *error_code = 2;\n      else\n        *error_code = 0;\n      xmlFree (buffer);\n    }\n  return i;\n}\n\n/**\n * Function to get an unsigned integer number of a XML node property.\n *\n * \\return Unsigned integer number value.\n */\nunsigned int\nxml_node_get_uint (xmlNode * node,      ///< XML node.\n                   const xmlChar * prop,        ///< XML property.\n                   int *error_code)     ///< Error code.\n{\n  unsigned int i = 0;\n  xmlChar *buffer;\n  buffer = xmlGetProp (node, prop);\n  if (!buffer)\n    *error_code = 1;\n  else\n    {\n      if (sscanf ((char *) buffer, \"%u\", &i) != 1)\n        *error_code = 2;\n      else\n        *error_code = 0;\n      xmlFree (buffer);\n    }\n  return i;\n}\n\n/**\n * Function to get an unsigned integer number of a XML node property with a\n *   default value.\n *\n * \\return Unsigned integer number value.\n */\nunsigned int\nxml_node_get_uint_with_default (xmlNode * node, ///< XML node.\n                                const xmlChar * prop,   ///< XML property.\n                                unsigned int default_value,\n                                ///< default value.\n                                int *error_code)        ///< Error code.\n{\n  unsigned int i;\n  if (xmlHasProp (node, prop))\n    i = xml_node_get_uint (node, prop, error_code);\n  else\n    {\n      i = default_value;\n      *error_code = 0;\n    }\n  return i;\n}\n\n/**\n * Function to get an long double number of a XML node property.\n *\n * \\return Long double number value.\n */\nlong double\nxml_node_get_float (xmlNode * node,     ///< XML node.\n                    const xmlChar * prop,       ///< XML property.\n                    int *error_code)    ///< Error code.\n{\n  long double x = 0.L;\n  xmlChar *buffer;\n  buffer = xmlGetProp (node, prop);\n  if (!buffer)\n    *error_code = 1;\n  else\n    {\n      if (sscanf ((char *) buffer, \"%Lg\", &x) != 1)\n        *error_code = 2;\n      else\n        *error_code = 0;\n      xmlFree (buffer);\n    }\n  return x;\n}\n\n/**\n * Function to read the minimum, the interval and the random function type of a\n * variable on a XML node.\n *\n * \\return 1 on success, 0 on error.\n */\nint\nread_variable (xmlNode * node,  ///< XML node.\n               long double *minimum,    ///< minimum value.\n               long double *interval,   ///< interval value.\n               unsigned int *type,      ///< random function type.\n               unsigned int n)  ///< variable number.\n{\n  char number[16];\n  gchar *buffer;\n  xmlChar *prop;\n  int code;\n\n  if (!node)\n    {\n      error_message = g_strdup (_(\"No XML node\"));\n      goto exit_on_error;\n    }\n  if (xmlStrcmp (node->name, XML_VARIABLE))\n    {\n      error_message = g_strdup (_(\"Bad XML node\"));\n      goto exit_on_error;\n    }\n  minimum[n] = xml_node_get_float (node, XML_MINIMUM, &code);\n  if (code)\n    {\n      error_message = g_strdup (_(\"Bad minimum\"));\n      goto exit_on_error;\n    }\n  interval[n] = xml_node_get_float (node, XML_INTERVAL, &code);\n  if (code)\n    {\n      error_message = g_strdup (_(\"Bad interval\"));\n      goto exit_on_error;\n    }\n  prop = xmlGetProp (node, XML_TYPE);\n  if (!prop || !xmlStrcmp (prop, XML_RANDOM))\n    type[n] = RANDOM_TYPE_UNIFORM;\n  else if (!xmlStrcmp (prop, XML_BOTTOM))\n    type[n] = RANDOM_TYPE_BOTTOM;\n  else if (!xmlStrcmp (prop, XML_EXTREME))\n    type[n] = RANDOM_TYPE_EXTREME;\n  else if (!xmlStrcmp (prop, XML_TOP))\n    type[n] = RANDOM_TYPE_TOP;\n  else if (!xmlStrcmp (prop, XML_REGULAR))\n    type[n] = RANDOM_TYPE_REGULAR;\n  else if (!xmlStrcmp (prop, XML_ORTHOGONAL))\n    type[n] = RANDOM_TYPE_ORTHOGONAL;\n  else\n    {\n      xmlFree (prop);\n      error_message = g_strdup (_(\"Bad random type function\"));\n      goto exit_on_error;\n    }\n  xmlFree (prop);\n  return 1;\n\nexit_on_error:\n  snprintf (number, 16, \"%u\", n + 1);\n  buffer = error_message;\n  error_message\n    = g_strconcat (_(\"Variable\"), \" \", number, \":\\n\", error_message, NULL);\n  g_free (buffer);\n  return 0;\n}\n\n/**\n * Function to set the precision in a maxima program file.\n */\nvoid\nprint_maxima_precision (FILE * file)    ///< maxima program file.\n{\n  fprintf (file, \"fpprec:%u;\\nfpprintprec:fpprec;\\n\", MAXIMA_PRECISION);\n}\n", "meta": {"hexsha": "94e2fc5d13dbc0950cb3267527be911308039fe8", "size": 6492, "ext": "c", "lang": "C", "max_stars_repo_path": "utils.c", "max_stars_repo_name": "jburguete/ode", "max_stars_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utils.c", "max_issues_repo_name": "jburguete/ode", "max_issues_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils.c", "max_forks_repo_name": "jburguete/ode", "max_forks_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5084745763, "max_line_length": 80, "alphanum_fraction": 0.6281577326, "num_tokens": 1659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1824255149165352, "lm_q2_score": 0.03622005495467345, "lm_q1q2_score": 0.006607462175411506}}
{"text": "#ifndef OPENMC_TALLIES_FILTER_COLLISIONS_H\n#define OPENMC_TALLIES_FILTER_COLLISIONS_H\n\n#include <vector>\n#include <unordered_map>\n#include <gsl/gsl>\n\n#include \"openmc/tallies/filter.h\"\n\nnamespace openmc {\n\n//==============================================================================\n//! Bins the incident neutron energy.\n//==============================================================================\n\nclass CollisionFilter : public Filter {\npublic:\n  //----------------------------------------------------------------------------\n  // Constructors, destructors\n\n  ~CollisionFilter() = default;\n\n  //----------------------------------------------------------------------------\n  // Methods\n\n  std::string type() const override { return \"collision\"; }\n\n  void from_xml(pugi::xml_node node) override;\n\n  void get_all_bins(const Particle& p, TallyEstimator estimator, \n    FilterMatch& match) const override;\n\n  void to_statepoint(hid_t filter_group) const override;\n\n  std::string text_label(int bin) const override;\n\n  //----------------------------------------------------------------------------\n  // Accessors\n\n  const std::vector<int>& bins() const { return bins_; }\n  void set_bins(gsl::span<const int> bins);\n\nprotected:\n  //----------------------------------------------------------------------------\n  // Data members\n\n  std::vector<int> bins_;\n\n  std::unordered_map<int,int> map_;\n\n};\n\n} // namespace openmc\n#endif // OPENMC_TALLIES_FILTER_COLLISIONS_H\n", "meta": {"hexsha": "45e6d940546529b513cbce55b37e52221c273a2a", "size": 1466, "ext": "h", "lang": "C", "max_stars_repo_path": "include/openmc/tallies/filter_collision.h", "max_stars_repo_name": "HunterBelanger/openmc", "max_stars_repo_head_hexsha": "7f7977091df7552449cff6c3b96a1166e4b43e45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-18T16:09:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-18T16:09:59.000Z", "max_issues_repo_path": "include/openmc/tallies/filter_collision.h", "max_issues_repo_name": "HunterBelanger/openmc", "max_issues_repo_head_hexsha": "7f7977091df7552449cff6c3b96a1166e4b43e45", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/openmc/tallies/filter_collision.h", "max_forks_repo_name": "HunterBelanger/openmc", "max_forks_repo_head_hexsha": "7f7977091df7552449cff6c3b96a1166e4b43e45", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6545454545, "max_line_length": 80, "alphanum_fraction": 0.4938608458, "num_tokens": 268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15002883194322006, "lm_q2_score": 0.04401865221440602, "lm_q1q2_score": 0.006604066975442172}}
{"text": "/****************************************************************************\n *                                                                          *\n *  Author : lukasz.iwaszkiewicz@gmail.com                                  *\n *  ~~~~~~~~                                                                *\n *  License : see COPYING file for details.                                 *\n *  ~~~~~~~~~                                                               *\n ****************************************************************************/\n\n#pragma once\n#include <chrono>\n#include <cstdint>\n#include <gsl/gsl>\n#include <iostream>\n#include <vector>\n\nnamespace tp {\nclass CanFrame;\n\n/**\n * @brief The TimeProvider struct\n * TODO if I'm not mistaken, those classes ought to have 100\u00b5s resolutiuon instead of 1ms (1000\u00b5s).\n */\nstruct ChronoTimeProvider {\n        long operator() () const\n        {\n                using namespace std::chrono;\n                system_clock::time_point now = system_clock::now ();\n                auto duration = now.time_since_epoch ();\n                return duration_cast<milliseconds> (duration).count ();\n        }\n};\n\nstruct CoutPrinter {\n        template <typename T> void operator() (T &&a) { std::cout << std::forward<T> (a) << std::endl; }\n};\n\n/**\n * Buffer for all input and ouptut operations\n */\nusing IsoMessage = std::vector<uint8_t>;\n\n} // namespace tp\n", "meta": {"hexsha": "1e79cc1a30e0f1b1f61278f76aebc1708994fd92", "size": 1402, "ext": "h", "lang": "C", "max_stars_repo_path": "src/StlTypes.h", "max_stars_repo_name": "semasquare/cpp-can-isotp", "max_stars_repo_head_hexsha": "8f6b487de162e4c7e871d33ce9cdb4329eff9d5d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-09-17T15:01:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-09T20:32:58.000Z", "max_issues_repo_path": "src/StlTypes.h", "max_issues_repo_name": "semasquare/cpp-can-isotp", "max_issues_repo_head_hexsha": "8f6b487de162e4c7e871d33ce9cdb4329eff9d5d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-02T19:05:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-26T15:32:11.000Z", "max_forks_repo_path": "src/StlTypes.h", "max_forks_repo_name": "semasquare/cpp-can-isotp", "max_forks_repo_head_hexsha": "8f6b487de162e4c7e871d33ce9cdb4329eff9d5d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-09-15T06:14:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-31T07:40:34.000Z", "avg_line_length": 32.6046511628, "max_line_length": 104, "alphanum_fraction": 0.4265335235, "num_tokens": 248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19930799790404566, "lm_q2_score": 0.03308597672022804, "lm_q1q2_score": 0.006594299778808514}}
{"text": "#pragma once\n\n#include <gsl/gsl>\n#include <DirectXMath.h>\n#include <vector>\n#include <memory>\n#include <string>\n#include <cstdint>\n\nnamespace Library\n{\n\tclass Model;\n\tclass Bone;\n\tclass Keyframe;\n\tclass OutputStreamHelper;\n\tclass InputStreamHelper;\n\n\tstruct BoneAnimationData final\n\t{\n\t\tstd::uint32_t BoneIndex{ 0 };\n\t\tstd::vector<std::shared_ptr<Keyframe>> Keyframes;\n\t};\n\n    class BoneAnimation final\n    {\n    public:\n\t\tBoneAnimation(Model& model, InputStreamHelper& streamHelper);\n\t\tBoneAnimation(Model& model, const BoneAnimationData& boneAnimationData);\n\t\tBoneAnimation(Model& model, BoneAnimationData&& boneAnimationData);\n\t\tBoneAnimation(const BoneAnimation&) = default;\n\t\tBoneAnimation(BoneAnimation&& rhs) = default;\n\t\tBoneAnimation& operator=(const BoneAnimation& rhs) = default;\n\t\tBoneAnimation& operator=(BoneAnimation&& rhs) = default;\n\t\t~BoneAnimation() = default;\n\n\t\tBone& GetBone();\n\t\tstd::vector<std::shared_ptr<Keyframe>>& Keyframes();\n\n\t\tstd::uint32_t GetTransform(float time, DirectX::XMFLOAT4X4& transform) const;\n\t\tvoid GetTransformAtKeyframe(std::uint32_t keyframeIndex, DirectX::XMFLOAT4X4& transform) const;\n\t\tvoid GetInteropolatedTransform(float time, DirectX::XMFLOAT4X4& transform) const;\n\n\t\tvoid Save(OutputStreamHelper& streamHelper);\n\n    private:\n\t\tvoid Load(InputStreamHelper& streamHelper);\n\t\tstd::uint32_t FindKeyframeIndex(float time) const;\n\n\t\tModel* mModel;\n\t\tstd::weak_ptr<Bone> mBone;\n\t\tstd::vector<std::shared_ptr<Keyframe>> mKeyframes;\n    };\n}\n", "meta": {"hexsha": "1cf41c9e4d32a0d514a71befe1ec3af945b0d459", "size": 1489, "ext": "h", "lang": "C", "max_stars_repo_path": "source/Library.Shared/BoneAnimation.h", "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/Library.Shared/BoneAnimation.h", "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/Library.Shared/BoneAnimation.h", "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5740740741, "max_line_length": 97, "alphanum_fraction": 0.7528542646, "num_tokens": 379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3140505578320071, "lm_q2_score": 0.02096424269141278, "lm_q1q2_score": 0.006583832111763761}}
{"text": "/* vector/gsl_vector_uint.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_VECTOR_UINT_H__\n#define __GSL_VECTOR_UINT_H__\n\n#if !defined( GSL_FUN )\n#  if !defined( GSL_DLL )\n#    define GSL_FUN extern\n#  elif defined( BUILD_GSL_DLL )\n#    define GSL_FUN extern __declspec(dllexport)\n#  else\n#    define GSL_FUN extern __declspec(dllimport)\n#  endif\n#endif\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_inline.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_block_uint.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size;\n  size_t stride;\n  unsigned int *data;\n  gsl_block_uint *block;\n  int owner;\n} \ngsl_vector_uint;\n\ntypedef struct\n{\n  gsl_vector_uint vector;\n} _gsl_vector_uint_view;\n\ntypedef _gsl_vector_uint_view gsl_vector_uint_view;\n\ntypedef struct\n{\n  gsl_vector_uint vector;\n} _gsl_vector_uint_const_view;\n\ntypedef const _gsl_vector_uint_const_view gsl_vector_uint_const_view;\n\n\n/* Allocation */\n\nGSL_FUN gsl_vector_uint *gsl_vector_uint_alloc (const size_t n);\nGSL_FUN gsl_vector_uint *gsl_vector_uint_calloc (const size_t n);\n\nGSL_FUN gsl_vector_uint *gsl_vector_uint_alloc_from_block (gsl_block_uint * b,\n                                                     const size_t offset, \n                                                     const size_t n, \n                                                     const size_t stride);\n\nGSL_FUN gsl_vector_uint *gsl_vector_uint_alloc_from_vector (gsl_vector_uint * v,\n                                                      const size_t offset, \n                                                      const size_t n, \n                                                      const size_t stride);\n\nGSL_FUN void gsl_vector_uint_free (gsl_vector_uint * v);\n\n/* Views */\n\nGSL_FUN _gsl_vector_uint_view \ngsl_vector_uint_view_array (unsigned int *v, size_t n);\n\nGSL_FUN _gsl_vector_uint_view \ngsl_vector_uint_view_array_with_stride (unsigned int *base,\n                                         size_t stride,\n                                         size_t n);\n\nGSL_FUN _gsl_vector_uint_const_view \ngsl_vector_uint_const_view_array (const unsigned int *v, size_t n);\n\nGSL_FUN _gsl_vector_uint_const_view \ngsl_vector_uint_const_view_array_with_stride (const unsigned int *base,\n                                               size_t stride,\n                                               size_t n);\n\nGSL_FUN _gsl_vector_uint_view \ngsl_vector_uint_subvector (gsl_vector_uint *v, \n                            size_t i, \n                            size_t n);\n\nGSL_FUN _gsl_vector_uint_view \ngsl_vector_uint_subvector_with_stride (gsl_vector_uint *v, \n                                        size_t i,\n                                        size_t stride,\n                                        size_t n);\n\nGSL_FUN _gsl_vector_uint_const_view \ngsl_vector_uint_const_subvector (const gsl_vector_uint *v, \n                                  size_t i, \n                                  size_t n);\n\nGSL_FUN _gsl_vector_uint_const_view \ngsl_vector_uint_const_subvector_with_stride (const gsl_vector_uint *v, \n                                              size_t i, \n                                              size_t stride,\n                                              size_t n);\n\n/* Operations */\n\nGSL_FUN void gsl_vector_uint_set_zero (gsl_vector_uint * v);\nGSL_FUN void gsl_vector_uint_set_all (gsl_vector_uint * v, unsigned int x);\nGSL_FUN int gsl_vector_uint_set_basis (gsl_vector_uint * v, size_t i);\n\nGSL_FUN int gsl_vector_uint_fread (FILE * stream, gsl_vector_uint * v);\nGSL_FUN int gsl_vector_uint_fwrite (FILE * stream, const gsl_vector_uint * v);\nGSL_FUN int gsl_vector_uint_fscanf (FILE * stream, gsl_vector_uint * v);\nGSL_FUN int gsl_vector_uint_fprintf (FILE * stream, const gsl_vector_uint * v,\n                              const char *format);\n\nGSL_FUN int gsl_vector_uint_memcpy (gsl_vector_uint * dest, const gsl_vector_uint * src);\n\nGSL_FUN int gsl_vector_uint_reverse (gsl_vector_uint * v);\n\nGSL_FUN int gsl_vector_uint_swap (gsl_vector_uint * v, gsl_vector_uint * w);\nGSL_FUN int gsl_vector_uint_swap_elements (gsl_vector_uint * v, const size_t i, const size_t j);\n\nGSL_FUN unsigned int gsl_vector_uint_max (const gsl_vector_uint * v);\nGSL_FUN unsigned int gsl_vector_uint_min (const gsl_vector_uint * v);\nGSL_FUN void gsl_vector_uint_minmax (const gsl_vector_uint * v, unsigned int * min_out, unsigned int * max_out);\n\nGSL_FUN size_t gsl_vector_uint_max_index (const gsl_vector_uint * v);\nGSL_FUN size_t gsl_vector_uint_min_index (const gsl_vector_uint * v);\nGSL_FUN void gsl_vector_uint_minmax_index (const gsl_vector_uint * v, size_t * imin, size_t * imax);\n\nGSL_FUN int gsl_vector_uint_add (gsl_vector_uint * a, const gsl_vector_uint * b);\nGSL_FUN int gsl_vector_uint_sub (gsl_vector_uint * a, const gsl_vector_uint * b);\nGSL_FUN int gsl_vector_uint_mul (gsl_vector_uint * a, const gsl_vector_uint * b);\nGSL_FUN int gsl_vector_uint_div (gsl_vector_uint * a, const gsl_vector_uint * b);\nGSL_FUN int gsl_vector_uint_scale (gsl_vector_uint * a, const unsigned int x);\nGSL_FUN int gsl_vector_uint_add_constant (gsl_vector_uint * a, const double x);\nGSL_FUN int gsl_vector_uint_axpby (const unsigned int alpha, const gsl_vector_uint * x, const unsigned int beta, gsl_vector_uint * y);\nGSL_FUN unsigned int gsl_vector_uint_sum (const gsl_vector_uint * a);\n\nGSL_FUN int gsl_vector_uint_equal (const gsl_vector_uint * u, \n                            const gsl_vector_uint * v);\n\nGSL_FUN int gsl_vector_uint_isnull (const gsl_vector_uint * v);\nGSL_FUN int gsl_vector_uint_ispos (const gsl_vector_uint * v);\nGSL_FUN int gsl_vector_uint_isneg (const gsl_vector_uint * v);\nGSL_FUN int gsl_vector_uint_isnonneg (const gsl_vector_uint * v);\n\nGSL_FUN INLINE_DECL unsigned int gsl_vector_uint_get (const gsl_vector_uint * v, const size_t i);\nGSL_FUN INLINE_DECL void gsl_vector_uint_set (gsl_vector_uint * v, const size_t i, unsigned int x);\nGSL_FUN INLINE_DECL unsigned int * gsl_vector_uint_ptr (gsl_vector_uint * v, const size_t i);\nGSL_FUN INLINE_DECL const unsigned int * gsl_vector_uint_const_ptr (const gsl_vector_uint * v, const size_t i);\n\n#ifdef HAVE_INLINE\n\nINLINE_FUN\nunsigned int\ngsl_vector_uint_get (const gsl_vector_uint * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= v->size))\n    {\n      GSL_ERROR_VAL (\"index out of range\", GSL_EINVAL, 0);\n    }\n#endif\n  return v->data[i * v->stride];\n}\n\nINLINE_FUN\nvoid\ngsl_vector_uint_set (gsl_vector_uint * v, const size_t i, unsigned int x)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= v->size))\n    {\n      GSL_ERROR_VOID (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  v->data[i * v->stride] = x;\n}\n\nINLINE_FUN\nunsigned int *\ngsl_vector_uint_ptr (gsl_vector_uint * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= v->size))\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return (unsigned int *) (v->data + i * v->stride);\n}\n\nINLINE_FUN\nconst unsigned int *\ngsl_vector_uint_const_ptr (const gsl_vector_uint * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= v->size))\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return (const unsigned int *) (v->data + i * v->stride);\n}\n#endif /* HAVE_INLINE */\n\n__END_DECLS\n\n#endif /* __GSL_VECTOR_UINT_H__ */\n\n\n", "meta": {"hexsha": "816129051705621ee9b192c23c05638f9df7bc61", "size": 8310, "ext": "h", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_vector_uint.h", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-28T08:20:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-28T08:20:20.000Z", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_vector_uint.h", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_vector_uint.h", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-14T12:45:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-14T12:45:35.000Z", "avg_line_length": 34.1975308642, "max_line_length": 134, "alphanum_fraction": 0.6891696751, "num_tokens": 2027, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.28140560742914383, "lm_q2_score": 0.02333077110040581, "lm_q1q2_score": 0.006565409813300011}}
{"text": "#ifndef __RNG_H__\n#define __RNG_H__\n#include <gsl/gsl_rng.h>\nextern const gsl_rng_type *rng_T;\nextern gsl_rng *rng_R;\n#endif\n", "meta": {"hexsha": "7cc081bb3622b9a218ea0eca57172adc536d0de3", "size": 125, "ext": "h", "lang": "C", "max_stars_repo_path": "rng.h", "max_stars_repo_name": "ai-ku/scode", "max_stars_repo_head_hexsha": "4b7a1b3cc0a943c290c57fce50a61e3792da4ae4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-01-06T16:46:05.000Z", "max_stars_repo_stars_event_max_datetime": "2016-07-21T18:29:03.000Z", "max_issues_repo_path": "rng.h", "max_issues_repo_name": "ai-ku/scode", "max_issues_repo_head_hexsha": "4b7a1b3cc0a943c290c57fce50a61e3792da4ae4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-01-06T18:20:04.000Z", "max_issues_repo_issues_event_max_datetime": "2015-02-03T17:43:04.000Z", "max_forks_repo_path": "rng.h", "max_forks_repo_name": "ai-ku/scode", "max_forks_repo_head_hexsha": "4b7a1b3cc0a943c290c57fce50a61e3792da4ae4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.8571428571, "max_line_length": 33, "alphanum_fraction": 0.792, "num_tokens": 39, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24798743735585305, "lm_q2_score": 0.026355355713931997, "lm_q1q2_score": 0.006535797124099935}}
{"text": "// Copyright 2019 John McFarlane\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#ifndef WSS_BOARD_PREMIUMS_H\n#define WSS_BOARD_PREMIUMS_H\n\n#include <gsl/string_span>\n\n#include \"board.h\"\n\nenum class premium {\n    normal,\n    dl,\n    tl,\n    dw,\n    tw\n};\n\nconstexpr std::array<int, 5> letter_multipliers {\n        1,\n        2,\n        3,\n        1,\n        1\n};\n\nconstexpr std::array<int, 5> word_multipliers {\n        1,\n        1,\n        1,\n        2,\n        3\n};\n\nauto load_board_premiums(gsl::cstring_span<> filename)\n-> std::optional<board<premium>>;\n\n#endif //WSS_BOARD_PREMIUMS_H\n", "meta": {"hexsha": "7810b6823be2e1ca25fe7f932d5971e0cbf97401", "size": 1101, "ext": "h", "lang": "C", "max_stars_repo_path": "src/play/board_premiums.h", "max_stars_repo_name": "johnmcfarlane/wss", "max_stars_repo_head_hexsha": "2772e303f79360056dd9f879198e6af207397dcc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-02-04T09:40:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T17:23:02.000Z", "max_issues_repo_path": "src/play/board_premiums.h", "max_issues_repo_name": "johnmcfarlane/wss", "max_issues_repo_head_hexsha": "2772e303f79360056dd9f879198e6af207397dcc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 21.0, "max_issues_repo_issues_event_min_datetime": "2019-10-28T22:07:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-18T23:55:35.000Z", "max_forks_repo_path": "src/play/board_premiums.h", "max_forks_repo_name": "johnmcfarlane/wss", "max_forks_repo_head_hexsha": "2772e303f79360056dd9f879198e6af207397dcc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-23T18:04:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T18:04:41.000Z", "avg_line_length": 22.02, "max_line_length": 75, "alphanum_fraction": 0.6702997275, "num_tokens": 285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24798743735585302, "lm_q2_score": 0.026355351029838825, "lm_q1q2_score": 0.006535795962503672}}
{"text": "#ifndef __e23673_LIBRARIES_H\n#define __e23673_LIBRARIES_H\n\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <limits.h>\n\n/* GNU Scientific library: */\n#include <gsl/gsl_rng.h>\n\n#include \"parsing.h\"\n#include \"dev_random.h\"\n#include \"mersenne_twister.h\"\n#include \"random_numbers.h\"\n\n\n#endif\n", "meta": {"hexsha": "c026eb7272ab949c0823ffa6069026f8ebcae1df", "size": 327, "ext": "h", "lang": "C", "max_stars_repo_path": "reference/26_Mersenne_Twister/src/libraries.h", "max_stars_repo_name": "gmagannaDevelop/TousAntiCovid", "max_stars_repo_head_hexsha": "7174845b0614b6a20e48834d5a76579cfbf80bd6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-12-09T00:10:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T23:00:30.000Z", "max_issues_repo_path": "reference/26_Mersenne_Twister/src/libraries.h", "max_issues_repo_name": "gmagannaDevelop/TousAntiCovid", "max_issues_repo_head_hexsha": "7174845b0614b6a20e48834d5a76579cfbf80bd6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-12-25T16:51:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-17T11:51:06.000Z", "max_forks_repo_path": "reference/26_Mersenne_Twister/src/libraries.h", "max_forks_repo_name": "gmagannaDevelop/TousAntiCovid", "max_forks_repo_head_hexsha": "7174845b0614b6a20e48834d5a76579cfbf80bd6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-12-22T18:51:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-22T14:27:12.000Z", "avg_line_length": 15.5714285714, "max_line_length": 29, "alphanum_fraction": 0.7400611621, "num_tokens": 88, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.16238003666671086, "lm_q2_score": 0.04023793845148978, "lm_q1q2_score": 0.0065338379211457645}}
{"text": "#pragma once\n\n#include <gsl\\gsl>\n#include <winrt\\Windows.Foundation.h>\n#include <d3d11.h>\n#include \"DrawableGameComponent.h\"\n#include \"MatrixHelper.h\"\n#include \"PointLight.h\"\n\nnamespace Rendering\n{\n\tclass EnvironmentMappingMaterial;\n\n\tclass EnvironmentMappingDemo final : public Library::DrawableGameComponent\n\t{\n\tpublic:\n\t\tEnvironmentMappingDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera);\n\t\tEnvironmentMappingDemo(const EnvironmentMappingDemo&) = delete;\n\t\tEnvironmentMappingDemo(EnvironmentMappingDemo&&) = default;\n\t\tEnvironmentMappingDemo& operator=(const EnvironmentMappingDemo&) = default;\t\t\n\t\tEnvironmentMappingDemo& operator=(EnvironmentMappingDemo&&) = default;\n\t\t~EnvironmentMappingDemo();\n\n\t\tfloat AmbientLightIntensity() const;\n\t\tvoid SetAmbientLightIntensity(float intensity);\n\n\t\tfloat EnvironmentIntensity() const;\n\t\tvoid SetEnvironmentIntensity(float intensity);\n\n\t\tfloat ReflectionAmount() const;\n\t\tvoid SetReflectionAmount(float amount);\n\n\t\tvirtual void Initialize() override;\n\t\tvirtual void Draw(const Library::GameTime& gameTime) override;\n\n\tprivate:\n\t\tinline static const float RotationRate{ DirectX::XM_PI };\n\n\t\tstd::shared_ptr<EnvironmentMappingMaterial> mMaterial;\n\t\tDirectX::XMFLOAT4X4 mWorldMatrix{ Library::MatrixHelper::Identity };\n\t\twinrt::com_ptr<ID3D11Buffer> mVertexBuffer;\n\t\twinrt::com_ptr<ID3D11Buffer> mIndexBuffer;\n\t\tstd::uint32_t mIndexCount{ 0 };\n\t\tbool mUpdateMaterial{ true };\n\t};\n}", "meta": {"hexsha": "db8194d46f1899ba13ad81ae77e27c5378efa918", "size": 1448, "ext": "h", "lang": "C", "max_stars_repo_path": "source/5.2_Environment_Mapping/EnvironmentMappingDemo.h", "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/5.2_Environment_Mapping/EnvironmentMappingDemo.h", "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/5.2_Environment_Mapping/EnvironmentMappingDemo.h", "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4782608696, "max_line_length": 94, "alphanum_fraction": 0.7866022099, "num_tokens": 336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34158249943831703, "lm_q2_score": 0.019124036925589262, "lm_q1q2_score": 0.006532436332393449}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <gsl/gsl_block.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_errno.h>\n\n/* Block IO */\nint mgsl_block_fwrite(const char *filename, const gsl_block *b)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_fwrite(fp, b) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_fread(const char *filename, gsl_block *b)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_fread(fp, b) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_fprintf(const char *filename, const gsl_block *b, const char *format)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_fprintf(fp, b, format) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_fscanf(const char *filename, gsl_block *b)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_fscanf(fp, b) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_float_fwrite(const char *filename, const gsl_block_float *b)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_float_fwrite(fp, b) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_float_fread(const char *filename, gsl_block_float *b)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_float_fread(fp, b) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_float_fprintf(const char *filename, const gsl_block_float *b, const char *format)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_float_fprintf(fp, b, format) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_float_fscanf(const char *filename, gsl_block_float *b)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_float_fscanf(fp, b) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_int_fwrite(const char *filename, const gsl_block_int *b)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_int_fwrite(fp, b) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_int_fread(const char *filename, gsl_block_int *b)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_int_fread(fp, b) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_int_fprintf(const char *filename, const gsl_block_int *b, const char *format)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_int_fprintf(fp, b, format) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_int_fscanf(const char *filename, gsl_block_int *b)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_int_fscanf(fp, b) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_uint_fwrite(const char *filename, const gsl_block_uint *b)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_uint_fwrite(fp, b) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_uint_fread(const char *filename, gsl_block_uint *b)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_uint_fread(fp, b) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_uint_fprintf(const char *filename, const gsl_block_uint *b, const char *format)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_uint_fprintf(fp, b, format) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_uint_fscanf(const char *filename, gsl_block_uint *b)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_uint_fscanf(fp, b) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_long_fwrite(const char *filename, const gsl_block_long *b)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_long_fwrite(fp, b) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_long_fread(const char *filename, gsl_block_long *b)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_long_fread(fp, b) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_long_fprintf(const char *filename, const gsl_block_long *b, const char *format)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_long_fprintf(fp, b, format) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_long_fscanf(const char *filename, gsl_block_long *b)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_long_fscanf(fp, b) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_ulong_fwrite(const char *filename, const gsl_block_ulong *b)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_ulong_fwrite(fp, b) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_ulong_fread(const char *filename, gsl_block_ulong *b)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_ulong_fread(fp, b) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_ulong_fprintf(const char *filename, const gsl_block_ulong *b, const char *format)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_ulong_fprintf(fp, b, format) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_ulong_fscanf(const char *filename, gsl_block_ulong *b)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_ulong_fscanf(fp, b) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_short_fwrite(const char *filename, const gsl_block_short *b)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_short_fwrite(fp, b) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_short_fread(const char *filename, gsl_block_short *b)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_short_fread(fp, b) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_short_fprintf(const char *filename, const gsl_block_short *b, const char *format)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_short_fprintf(fp, b, format) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_short_fscanf(const char *filename, gsl_block_short *b)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_short_fscanf(fp, b) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_ushort_fwrite(const char *filename, const gsl_block_ushort *b)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_ushort_fwrite(fp, b) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_ushort_fread(const char *filename, gsl_block_ushort *b)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_ushort_fread(fp, b) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_ushort_fprintf(const char *filename, const gsl_block_ushort *b, const char *format)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_ushort_fprintf(fp, b, format) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_ushort_fscanf(const char *filename, gsl_block_ushort *b)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_ushort_fscanf(fp, b) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_char_fwrite(const char *filename, const gsl_block_char *b)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_char_fwrite(fp, b) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_char_fread(const char *filename, gsl_block_char *b)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_char_fread(fp, b) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_char_fprintf(const char *filename, const gsl_block_char *b, const char *format)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_char_fprintf(fp, b, format) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_char_fscanf(const char *filename, gsl_block_char *b)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_char_fscanf(fp, b) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_uchar_fwrite(const char *filename, const gsl_block_uchar *b)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_uchar_fwrite(fp, b) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_uchar_fread(const char *filename, gsl_block_uchar *b)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_uchar_fread(fp, b) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_uchar_fprintf(const char *filename, const gsl_block_uchar *b, const char *format)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_uchar_fprintf(fp, b, format) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_uchar_fscanf(const char *filename, gsl_block_uchar *b)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_uchar_fscanf(fp, b) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_complex_fwrite(const char *filename, const gsl_block_complex *b)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_complex_fwrite(fp, b) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_complex_fread(const char *filename, gsl_block_complex *b)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_complex_fread(fp, b) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_complex_fprintf(const char *filename, const gsl_block_complex *b, const char *format)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_complex_fprintf(fp, b, format) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_complex_fscanf(const char *filename, gsl_block_complex *b)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_complex_fscanf(fp, b) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_complex_float_fwrite(const char *filename, const gsl_block_complex_float *b)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_complex_float_fwrite(fp, b) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_complex_float_fread(const char *filename, gsl_block_complex_float *b)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_complex_float_fread(fp, b) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_complex_float_fprintf(const char *filename, const gsl_block_complex_float *b, const char *format)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_complex_float_fprintf(fp, b, format) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_block_complex_float_fscanf(const char *filename, gsl_block_complex_float *b)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_block_complex_float_fscanf(fp, b) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\n/* Vector IO */\nint mgsl_vector_fwrite(const char *filename, const gsl_vector *v)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_fwrite(fp, v) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_fread(const char *filename, gsl_vector *v)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_fread(fp, v) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_fprintf(const char *filename, const gsl_vector *v, const char *format)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_fprintf(fp, v, format) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_fscanf(const char *filename, gsl_vector *v)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_fscanf(fp, v) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_float_fwrite(const char *filename, const gsl_vector_float *v)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_float_fwrite(fp, v) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_float_fread(const char *filename, gsl_vector_float *v)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_float_fread(fp, v) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_float_fprintf(const char *filename, const gsl_vector_float *v, const char *format)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_float_fprintf(fp, v, format) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_float_fscanf(const char *filename, gsl_vector_float *v)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_float_fscanf(fp, v) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_int_fwrite(const char *filename, const gsl_vector_int *v)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_int_fwrite(fp, v) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_int_fread(const char *filename, gsl_vector_int *v)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_int_fread(fp, v) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_int_fprintf(const char *filename, const gsl_vector_int *v, const char *format)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_int_fprintf(fp, v, format) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_int_fscanf(const char *filename, gsl_vector_int *v)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_int_fscanf(fp, v) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_uint_fwrite(const char *filename, const gsl_vector_uint *v)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_uint_fwrite(fp, v) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_uint_fread(const char *filename, gsl_vector_uint *v)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_uint_fread(fp, v) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_uint_fprintf(const char *filename, const gsl_vector_uint *v, const char *format)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_uint_fprintf(fp, v, format) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_uint_fscanf(const char *filename, gsl_vector_uint *v)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_uint_fscanf(fp, v) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_long_fwrite(const char *filename, const gsl_vector_long *v)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_long_fwrite(fp, v) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_long_fread(const char *filename, gsl_vector_long *v)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_long_fread(fp, v) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_long_fprintf(const char *filename, const gsl_vector_long *v, const char *format)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_long_fprintf(fp, v, format) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_long_fscanf(const char *filename, gsl_vector_long *v)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_long_fscanf(fp, v) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_ulong_fwrite(const char *filename, const gsl_vector_ulong *v)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_ulong_fwrite(fp, v) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_ulong_fread(const char *filename, gsl_vector_ulong *v)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_ulong_fread(fp, v) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_ulong_fprintf(const char *filename, const gsl_vector_ulong *v, const char *format)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_ulong_fprintf(fp, v, format) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_ulong_fscanf(const char *filename, gsl_vector_ulong *v)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_ulong_fscanf(fp, v) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_short_fwrite(const char *filename, const gsl_vector_short *v)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_short_fwrite(fp, v) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_short_fread(const char *filename, gsl_vector_short *v)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_short_fread(fp, v) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_short_fprintf(const char *filename, const gsl_vector_short *v, const char *format)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_short_fprintf(fp, v, format) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_short_fscanf(const char *filename, gsl_vector_short *v)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_short_fscanf(fp, v) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_ushort_fwrite(const char *filename, const gsl_vector_ushort *v)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_ushort_fwrite(fp, v) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_ushort_fread(const char *filename, gsl_vector_ushort *v)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_ushort_fread(fp, v) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_ushort_fprintf(const char *filename, const gsl_vector_ushort *v, const char *format)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_ushort_fprintf(fp, v, format) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_ushort_fscanf(const char *filename, gsl_vector_ushort *v)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_ushort_fscanf(fp, v) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_char_fwrite(const char *filename, const gsl_vector_char *v)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_char_fwrite(fp, v) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_char_fread(const char *filename, gsl_vector_char *v)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_char_fread(fp, v) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_char_fprintf(const char *filename, const gsl_vector_char *v, const char *format)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_char_fprintf(fp, v, format) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_char_fscanf(const char *filename, gsl_vector_char *v)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_char_fscanf(fp, v) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_uchar_fwrite(const char *filename, const gsl_vector_uchar *v)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_uchar_fwrite(fp, v) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_uchar_fread(const char *filename, gsl_vector_uchar *v)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_uchar_fread(fp, v) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_uchar_fprintf(const char *filename, const gsl_vector_uchar *v, const char *format)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_uchar_fprintf(fp, v, format) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_uchar_fscanf(const char *filename, gsl_vector_uchar *v)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_uchar_fscanf(fp, v) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_complex_fwrite(const char *filename, const gsl_vector_complex *v)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_complex_fwrite(fp, v) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_complex_fread(const char *filename, gsl_vector_complex *v)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_complex_fread(fp, v) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_complex_fprintf(const char *filename, const gsl_vector_complex *v, const char *format)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_complex_fprintf(fp, v, format) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_complex_fscanf(const char *filename, gsl_vector_complex *v)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_complex_fscanf(fp, v) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_complex_float_fwrite(const char *filename, const gsl_vector_complex_float *v)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_complex_float_fwrite(fp, v) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_complex_float_fread(const char *filename, gsl_vector_complex_float *v)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_complex_float_fread(fp, v) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_complex_float_fprintf(const char *filename, const gsl_vector_complex_float *v, const char *format)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_complex_float_fprintf(fp, v, format) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_vector_complex_float_fscanf(const char *filename, gsl_vector_complex_float *v)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_vector_complex_float_fscanf(fp, v) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\n/* Vector view */\ngsl_vector_view *alloc_gsl_vector_view(void)\n{\n  gsl_vector_view *c = calloc(1, sizeof(gsl_vector_view));\n  return c;\n}\n\nvoid free_gsl_vector_view(gsl_vector_view *c)\n{\n  if(c != NULL){\n    free(c);\n    c = NULL;\n  }\n}\n\ngsl_vector *mgsl_vector_subvector(gsl_vector_view *view, gsl_vector *v, size_t offset, size_t n)\n{\n  *view = gsl_vector_subvector(v, offset, n);\n  return &view->vector;\n}\n\ngsl_vector *mgsl_vector_subvector_with_stride(gsl_vector_view *view, gsl_vector *v, size_t offset, size_t stride, size_t n)\n{\n  *view = gsl_vector_subvector_with_stride(v, offset, stride, n);\n  return &view->vector;\n}\n\ngsl_vector *mgsl_vector_complex_real(gsl_vector_view *view, gsl_vector_complex *v)\n{\n  *view = gsl_vector_complex_real(v);\n  return &view->vector;\n}\n\ngsl_vector *mgsl_vector_complex_imag(gsl_vector_view *view, gsl_vector_complex *v)\n{\n  *view = gsl_vector_complex_imag(v);\n  return &view->vector;\n}\n\ngsl_vector_float *mgsl_vector_complex_float_real(gsl_vector_float_view *view, gsl_vector_complex_float *v)\n{\n  *view = gsl_vector_complex_float_real(v);\n  return &view->vector;\n}\n\ngsl_vector_float *mgsl_vector_complex_float_imag(gsl_vector_float_view *view, gsl_vector_complex_float *v)\n{\n  *view = gsl_vector_complex_float_imag(v);\n  return &view->vector;\n}\n\ngsl_vector *mgsl_vector_view_array(gsl_vector_view *view, double *base, size_t n)\n{\n  *view = gsl_vector_view_array(base, n);\n  return &view->vector;\n}\n\ngsl_vector *mgsl_vector_view_array_with_stride(gsl_vector_view *view, double *base, size_t stride, size_t n)\n{\n  *view = gsl_vector_view_array_with_stride(base, stride, n);\n  return &view->vector;\n}\n\ngsl_vector_float_view *alloc_gsl_vector_float_view(void)\n{\n  gsl_vector_float_view *c = calloc(1, sizeof(gsl_vector_float_view));\n  return c;\n}\n\nvoid free_gsl_vector_float_view(gsl_vector_float_view *c)\n{\n  if(c != NULL){\n    free(c);\n    c = NULL;\n  }\n}\n\ngsl_vector_float *mgsl_vector_float_subvector(gsl_vector_float_view *view, gsl_vector_float *v, size_t offset, size_t n)\n{\n  *view = gsl_vector_float_subvector(v, offset, n);\n  return &view->vector;\n}\n\ngsl_vector_float *mgsl_vector_float_subvector_with_stride(gsl_vector_float_view *view, gsl_vector_float *v, size_t offset, size_t stride, size_t n)\n{\n  *view = gsl_vector_float_subvector_with_stride(v, offset, stride, n);\n  return &view->vector;\n}\n\ngsl_vector_float *mgsl_vector_float_view_array(gsl_vector_float_view *view, float *base, size_t n)\n{\n  *view = gsl_vector_float_view_array(base, n);\n  return &view->vector;\n}\n\ngsl_vector_float *mgsl_vector_float_view_array_with_stride(gsl_vector_float_view *view, float *base, size_t stride, size_t n)\n{\n  *view = gsl_vector_float_view_array_with_stride(base, stride, n);\n  return &view->vector;\n}\n\ngsl_vector_int_view *alloc_gsl_vector_int_view(void)\n{\n  gsl_vector_int_view *c = calloc(1, sizeof(gsl_vector_int_view));\n  return c;\n}\n\nvoid free_gsl_vector_int_view(gsl_vector_int_view *c)\n{\n  if(c != NULL){\n    free(c);\n    c = NULL;\n  }\n}\n\ngsl_vector_int *mgsl_vector_int_subvector(gsl_vector_int_view *view, gsl_vector_int *v, size_t offset, size_t n)\n{\n  *view = gsl_vector_int_subvector(v, offset, n);\n  return &view->vector;\n}\n\ngsl_vector_int *mgsl_vector_int_subvector_with_stride(gsl_vector_int_view *view, gsl_vector_int *v, size_t offset, size_t stride, size_t n)\n{\n  *view = gsl_vector_int_subvector_with_stride(v, offset, stride, n);\n  return &view->vector;\n}\n\ngsl_vector_int *mgsl_vector_int_view_array(gsl_vector_int_view *view, int *base, size_t n)\n{\n  *view = gsl_vector_int_view_array(base, n);\n  return &view->vector;\n}\n\ngsl_vector_int *mgsl_vector_int_view_array_with_stride(gsl_vector_int_view *view, int *base, size_t stride, size_t n)\n{\n  *view = gsl_vector_int_view_array_with_stride(base, stride, n);\n  return &view->vector;\n}\n\ngsl_vector_uint_view *alloc_gsl_vector_uint_view(void)\n{\n  gsl_vector_uint_view *c = calloc(1, sizeof(gsl_vector_uint_view));\n  return c;\n}\n\nvoid free_gsl_vector_uint_view(gsl_vector_uint_view *c)\n{\n  if(c != NULL){\n    free(c);\n    c = NULL;\n  }\n}\n\ngsl_vector_uint *mgsl_vector_uint_subvector(gsl_vector_uint_view *view, gsl_vector_uint *v, size_t offset, size_t n)\n{\n  *view = gsl_vector_uint_subvector(v, offset, n);\n  return &view->vector;\n}\n\ngsl_vector_uint *mgsl_vector_uint_subvector_with_stride(gsl_vector_uint_view *view, gsl_vector_uint *v, size_t offset, size_t stride, size_t n)\n{\n  *view = gsl_vector_uint_subvector_with_stride(v, offset, stride, n);\n  return &view->vector;\n}\n\ngsl_vector_uint *mgsl_vector_uint_view_array(gsl_vector_uint_view *view, unsigned int *base, size_t n)\n{\n  *view = gsl_vector_uint_view_array(base, n);\n  return &view->vector;\n}\n\ngsl_vector_uint *mgsl_vector_uint_view_array_with_stride(gsl_vector_uint_view *view, unsigned int *base, size_t stride, size_t n)\n{\n  *view = gsl_vector_uint_view_array_with_stride(base, stride, n);\n  return &view->vector;\n}\n\ngsl_vector_long_view *alloc_gsl_vector_long_view(void)\n{\n  gsl_vector_long_view *c = calloc(1, sizeof(gsl_vector_long_view));\n  return c;\n}\n\nvoid free_gsl_vector_long_view(gsl_vector_long_view *c)\n{\n  if(c != NULL){\n    free(c);\n    c = NULL;\n  }\n}\n\ngsl_vector_long *mgsl_vector_long_subvector(gsl_vector_long_view *view, gsl_vector_long *v, size_t offset, size_t n)\n{\n  *view = gsl_vector_long_subvector(v, offset, n);\n  return &view->vector;\n}\n\ngsl_vector_long *mgsl_vector_long_subvector_with_stride(gsl_vector_long_view *view, gsl_vector_long *v, size_t offset, size_t stride, size_t n)\n{\n  *view = gsl_vector_long_subvector_with_stride(v, offset, stride, n);\n  return &view->vector;\n}\n\ngsl_vector_long *mgsl_vector_long_view_array(gsl_vector_long_view *view, long *base, size_t n)\n{\n  *view = gsl_vector_long_view_array(base, n);\n  return &view->vector;\n}\n\ngsl_vector_long *mgsl_vector_long_view_array_with_stride(gsl_vector_long_view *view, long *base, size_t stride, size_t n)\n{\n  *view = gsl_vector_long_view_array_with_stride(base, stride, n);\n  return &view->vector;\n}\n\ngsl_vector_ulong_view *alloc_gsl_vector_ulong_view(void)\n{\n  gsl_vector_ulong_view *c = calloc(1, sizeof(gsl_vector_ulong_view));\n  return c;\n}\n\nvoid free_gsl_vector_ulong_view(gsl_vector_ulong_view *c)\n{\n  if(c != NULL){\n    free(c);\n    c = NULL;\n  }\n}\n\ngsl_vector_ulong *mgsl_vector_ulong_subvector(gsl_vector_ulong_view *view, gsl_vector_ulong *v, size_t offset, size_t n)\n{\n  *view = gsl_vector_ulong_subvector(v, offset, n);\n  return &view->vector;\n}\n\ngsl_vector_ulong *mgsl_vector_ulong_subvector_with_stride(gsl_vector_ulong_view *view, gsl_vector_ulong *v, size_t offset, size_t stride, size_t n)\n{\n  *view = gsl_vector_ulong_subvector_with_stride(v, offset, stride, n);\n  return &view->vector;\n}\n\ngsl_vector_ulong *mgsl_vector_ulong_view_array(gsl_vector_ulong_view *view, unsigned long *base, size_t n)\n{\n  *view = gsl_vector_ulong_view_array(base, n);\n  return &view->vector;\n}\n\ngsl_vector_ulong *mgsl_vector_ulong_view_array_with_stride(gsl_vector_ulong_view *view, unsigned long *base, size_t stride, size_t n)\n{\n  *view = gsl_vector_ulong_view_array_with_stride(base, stride, n);\n  return &view->vector;\n}\n\ngsl_vector_short_view *alloc_gsl_vector_short_view(void)\n{\n  gsl_vector_short_view *c = calloc(1, sizeof(gsl_vector_short_view));\n  return c;\n}\n\nvoid free_gsl_vector_short_view(gsl_vector_short_view *c)\n{\n  if(c != NULL){\n    free(c);\n    c = NULL;\n  }\n}\n\ngsl_vector_short *mgsl_vector_short_subvector(gsl_vector_short_view *view, gsl_vector_short *v, size_t offset, size_t n)\n{\n  *view = gsl_vector_short_subvector(v, offset, n);\n  return &view->vector;\n}\n\ngsl_vector_short *mgsl_vector_short_subvector_with_stride(gsl_vector_short_view *view, gsl_vector_short *v, size_t offset, size_t stride, size_t n)\n{\n  *view = gsl_vector_short_subvector_with_stride(v, offset, stride, n);\n  return &view->vector;\n}\n\ngsl_vector_short *mgsl_vector_short_view_array(gsl_vector_short_view *view, short *base, size_t n)\n{\n  *view = gsl_vector_short_view_array(base, n);\n  return &view->vector;\n}\n\ngsl_vector_short *mgsl_vector_short_view_array_with_stride(gsl_vector_short_view *view, short *base, size_t stride, size_t n)\n{\n  *view = gsl_vector_short_view_array_with_stride(base, stride, n);\n  return &view->vector;\n}\n\ngsl_vector_ushort_view *alloc_gsl_vector_ushort_view(void)\n{\n  gsl_vector_ushort_view *c = calloc(1, sizeof(gsl_vector_ushort_view));\n  return c;\n}\n\nvoid free_gsl_vector_ushort_view(gsl_vector_ushort_view *c)\n{\n  if(c != NULL){\n    free(c);\n    c = NULL;\n  }\n}\n\ngsl_vector_ushort *mgsl_vector_ushort_subvector(gsl_vector_ushort_view *view, gsl_vector_ushort *v, size_t offset, size_t n)\n{\n  *view = gsl_vector_ushort_subvector(v, offset, n);\n  return &view->vector;\n}\n\ngsl_vector_ushort *mgsl_vector_ushort_subvector_with_stride(gsl_vector_ushort_view *view, gsl_vector_ushort *v, size_t offset, size_t stride, size_t n)\n{\n  *view = gsl_vector_ushort_subvector_with_stride(v, offset, stride, n);\n  return &view->vector;\n}\n\ngsl_vector_ushort *mgsl_vector_ushort_view_array(gsl_vector_ushort_view *view, unsigned short *base, size_t n)\n{\n  *view = gsl_vector_ushort_view_array(base, n);\n  return &view->vector;\n}\n\ngsl_vector_ushort *mgsl_vector_ushort_view_array_with_stride(gsl_vector_ushort_view *view, unsigned short *base, size_t stride, size_t n)\n{\n  *view = gsl_vector_ushort_view_array_with_stride(base, stride, n);\n  return &view->vector;\n}\n\ngsl_vector_char_view *alloc_gsl_vector_char_view(void)\n{\n  gsl_vector_char_view *c = calloc(1, sizeof(gsl_vector_char_view));\n  return c;\n}\n\nvoid free_gsl_vector_char_view(gsl_vector_char_view *c)\n{\n  if(c != NULL){\n    free(c);\n    c = NULL;\n  }\n}\n\ngsl_vector_char *mgsl_vector_char_subvector(gsl_vector_char_view *view, gsl_vector_char *v, size_t offset, size_t n)\n{\n  *view = gsl_vector_char_subvector(v, offset, n);\n  return &view->vector;\n}\n\ngsl_vector_char *mgsl_vector_char_subvector_with_stride(gsl_vector_char_view *view, gsl_vector_char *v, size_t offset, size_t stride, size_t n)\n{\n  *view = gsl_vector_char_subvector_with_stride(v, offset, stride, n);\n  return &view->vector;\n}\n\ngsl_vector_char *mgsl_vector_char_view_array(gsl_vector_char_view *view, char *base, size_t n)\n{\n  *view = gsl_vector_char_view_array(base, n);\n  return &view->vector;\n}\n\ngsl_vector_char *mgsl_vector_char_view_array_with_stride(gsl_vector_char_view *view, char *base, size_t stride, size_t n)\n{\n  *view = gsl_vector_char_view_array_with_stride(base, stride, n);\n  return &view->vector;\n}\n\ngsl_vector_uchar_view *alloc_gsl_vector_uchar_view(void)\n{\n  gsl_vector_uchar_view *c = calloc(1, sizeof(gsl_vector_uchar_view));\n  return c;\n}\n\nvoid free_gsl_vector_uchar_view(gsl_vector_uchar_view *c)\n{\n  if(c != NULL){\n    free(c);\n    c = NULL;\n  }\n}\n\ngsl_vector_uchar *mgsl_vector_uchar_subvector(gsl_vector_uchar_view *view, gsl_vector_uchar *v, size_t offset, size_t n)\n{\n  *view = gsl_vector_uchar_subvector(v, offset, n);\n  return &view->vector;\n}\n\ngsl_vector_uchar *mgsl_vector_uchar_subvector_with_stride(gsl_vector_uchar_view *view, gsl_vector_uchar *v, size_t offset, size_t stride, size_t n)\n{\n  *view = gsl_vector_uchar_subvector_with_stride(v, offset, stride, n);\n  return &view->vector;\n}\n\ngsl_vector_uchar *mgsl_vector_uchar_view_array(gsl_vector_uchar_view *view, unsigned char *base, size_t n)\n{\n  *view = gsl_vector_uchar_view_array(base, n);\n  return &view->vector;\n}\n\ngsl_vector_uchar *mgsl_vector_uchar_view_array_with_stride(gsl_vector_uchar_view *view, unsigned char *base, size_t stride, size_t n)\n{\n  *view = gsl_vector_uchar_view_array_with_stride(base, stride, n);\n  return &view->vector;\n}\n\ngsl_vector_complex_view *alloc_gsl_vector_complex_view(void)\n{\n  gsl_vector_complex_view *c = calloc(1, sizeof(gsl_vector_complex_view));\n  return c;\n}\n\nvoid free_gsl_vector_complex_view(gsl_vector_complex_view *c)\n{\n  if(c != NULL){\n    free(c);\n    c = NULL;\n  }\n}\n\ngsl_vector_complex *mgsl_vector_complex_subvector(gsl_vector_complex_view *view, gsl_vector_complex *v, size_t offset, size_t n)\n{\n  *view = gsl_vector_complex_subvector(v, offset, n);\n  return &view->vector;\n}\n\ngsl_vector_complex *mgsl_vector_complex_subvector_with_stride(gsl_vector_complex_view *view, gsl_vector_complex *v, size_t offset, size_t stride, size_t n)\n{\n  *view = gsl_vector_complex_subvector_with_stride(v, offset, stride, n);\n  return &view->vector;\n}\n\ngsl_vector_complex *mgsl_vector_complex_view_array(gsl_vector_complex_view *view, double *base, size_t n)\n{\n  *view = gsl_vector_complex_view_array(base, n);\n  return &view->vector;\n}\n\ngsl_vector_complex *mgsl_vector_complex_view_array_with_stride(gsl_vector_complex_view *view, double *base, size_t stride, size_t n)\n{\n  *view = gsl_vector_complex_view_array_with_stride(base, stride, n);\n  return &view->vector;\n}\n\ngsl_vector_complex_float_view *alloc_gsl_vector_complex_float_view(void)\n{\n  gsl_vector_complex_float_view *c = calloc(1, sizeof(gsl_vector_complex_float_view));\n  return c;\n}\n\nvoid free_gsl_vector_complex_float_view(gsl_vector_complex_float_view *c)\n{\n  if(c != NULL){\n    free(c);\n    c = NULL;\n  }\n}\n\ngsl_vector_complex_float *mgsl_vector_complex_float_subvector(gsl_vector_complex_float_view *view, gsl_vector_complex_float *v, size_t offset, size_t n)\n{\n  *view = gsl_vector_complex_float_subvector(v, offset, n);\n  return &view->vector;\n}\n\ngsl_vector_complex_float *mgsl_vector_complex_float_subvector_with_stride(gsl_vector_complex_float_view *view, gsl_vector_complex_float *v, size_t offset, size_t stride, size_t n)\n{\n  *view = gsl_vector_complex_float_subvector_with_stride(v, offset, stride, n);\n  return &view->vector;\n}\n\ngsl_vector_complex_float *mgsl_vector_complex_float_view_array(gsl_vector_complex_float_view *view, float *base, size_t n)\n{\n  *view = gsl_vector_complex_float_view_array(base, n);\n  return &view->vector;\n}\n\ngsl_vector_complex_float *mgsl_vector_complex_float_view_array_with_stride(gsl_vector_complex_float_view *view, float *base, size_t stride, size_t n)\n{\n  *view = gsl_vector_complex_float_view_array_with_stride(base, stride, n);\n  return &view->vector;\n}\n\n/* Complex vectors */\nvoid mgsl_vector_complex_get(gsl_vector_complex *v, size_t i, gsl_complex *res)\n{\n  *res = gsl_vector_complex_get(v, i);\n}\n\nvoid mgsl_vector_complex_set(gsl_vector_complex *v, size_t i, gsl_complex *x)\n{\n  gsl_vector_complex_set(v, i, *x);\n}\n\nvoid mgsl_vector_complex_float_get(gsl_vector_complex_float *v, size_t i, gsl_complex_float *res)\n{\n  *res = gsl_vector_complex_float_get(v, i);\n}\n\nvoid mgsl_vector_complex_float_set(gsl_vector_complex_float *v, size_t i, gsl_complex_float *x)\n{\n  gsl_vector_complex_float_set(v, i, *x);\n}\n\nvoid mgsl_vector_complex_set_all(gsl_vector_complex *v, gsl_complex *x)\n{\n  gsl_vector_complex_set_all(v, *x);\n}\n\nvoid mgsl_vector_complex_float_set_all(gsl_vector_complex_float *v, gsl_complex_float *x)\n{\n  gsl_vector_complex_float_set_all(v, *x);\n}\n\nint mgsl_vector_complex_scale(gsl_vector_complex *a, gsl_complex *x)\n{\n  return gsl_vector_complex_scale(a, *x);\n}\n\nint mgsl_vector_complex_float_scale(gsl_vector_complex_float *a, gsl_complex_float *x)\n{\n  return gsl_vector_complex_float_scale(a, *x);\n}\n\nint mgsl_vector_complex_add_constant(gsl_vector_complex *a, gsl_complex *x)\n{\n  return gsl_vector_complex_add_constant(a, *x);\n}\n\nint mgsl_vector_complex_float_add_constant(gsl_vector_complex_float *a, gsl_complex_float *x)\n{\n  return gsl_vector_complex_float_add_constant(a, *x);\n}\n\n/* Matrix IO */\nvoid mgsl_matrix_complex_get(gsl_matrix_complex *v, size_t i, size_t j, gsl_complex *res)\n{\n  *res = gsl_matrix_complex_get(v, i, j);\n}\n\nvoid mgsl_matrix_complex_set(gsl_matrix_complex *v, size_t i, size_t j, gsl_complex *x)\n{\n  gsl_matrix_complex_set(v, i, j, *x);\n}\n\nvoid mgsl_matrix_complex_float_get(gsl_matrix_complex_float *v, size_t i, size_t j, gsl_complex_float *res)\n{\n  *res = gsl_matrix_complex_float_get(v, i, j);\n}\n\nvoid mgsl_matrix_complex_float_set(gsl_matrix_complex_float *v, size_t i, size_t j, gsl_complex_float *x)\n{\n  gsl_matrix_complex_float_set(v, i, j, *x);\n}\n\nvoid mgsl_matrix_complex_set_all(gsl_matrix_complex *v, gsl_complex *x)\n{\n  gsl_matrix_complex_set_all(v, *x);\n}\n\nvoid mgsl_matrix_complex_float_set_all(gsl_matrix_complex_float *v, gsl_complex_float *x)\n{\n  gsl_matrix_complex_float_set_all(v, *x);\n}\n\nint mgsl_matrix_fwrite(const char *filename, const gsl_matrix *m)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_fwrite(fp, m) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_fread(const char *filename, gsl_matrix *m)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_fread(fp, m) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_fprintf(const char *filename, const gsl_matrix *m, const char *format)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_fprintf(fp, m, format) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_fscanf(const char *filename, gsl_matrix *m)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_fscanf(fp, m) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_float_fwrite(const char *filename, const gsl_matrix_float *m)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_float_fwrite(fp, m) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_float_fread(const char *filename, gsl_matrix_float *m)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_float_fread(fp, m) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_float_fprintf(const char *filename, const gsl_matrix_float *m, const char *format)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_float_fprintf(fp, m, format) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_float_fscanf(const char *filename, gsl_matrix_float *m)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_float_fscanf(fp, m) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_int_fwrite(const char *filename, const gsl_matrix_int *m)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_int_fwrite(fp, m) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_int_fread(const char *filename, gsl_matrix_int *m)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_int_fread(fp, m) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_int_fprintf(const char *filename, const gsl_matrix_int *m, const char *format)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_int_fprintf(fp, m, format) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_int_fscanf(const char *filename, gsl_matrix_int *m)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_int_fscanf(fp, m) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_uint_fwrite(const char *filename, const gsl_matrix_uint *m)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_uint_fwrite(fp, m) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_uint_fread(const char *filename, gsl_matrix_uint *m)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_uint_fread(fp, m) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_uint_fprintf(const char *filename, const gsl_matrix_uint *m, const char *format)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_uint_fprintf(fp, m, format) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_uint_fscanf(const char *filename, gsl_matrix_uint *m)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_uint_fscanf(fp, m) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_long_fwrite(const char *filename, const gsl_matrix_long *m)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_long_fwrite(fp, m) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_long_fread(const char *filename, gsl_matrix_long *m)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_long_fread(fp, m) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_long_fprintf(const char *filename, const gsl_matrix_long *m, const char *format)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_long_fprintf(fp, m, format) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_long_fscanf(const char *filename, gsl_matrix_long *m)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_long_fscanf(fp, m) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_ulong_fwrite(const char *filename, const gsl_matrix_ulong *m)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_ulong_fwrite(fp, m) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_ulong_fread(const char *filename, gsl_matrix_ulong *m)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_ulong_fread(fp, m) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_ulong_fprintf(const char *filename, const gsl_matrix_ulong *m, const char *format)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_ulong_fprintf(fp, m, format) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_ulong_fscanf(const char *filename, gsl_matrix_ulong *m)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_ulong_fscanf(fp, m) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_short_fwrite(const char *filename, const gsl_matrix_short *m)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_short_fwrite(fp, m) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_short_fread(const char *filename, gsl_matrix_short *m)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_short_fread(fp, m) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_short_fprintf(const char *filename, const gsl_matrix_short *m, const char *format)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_short_fprintf(fp, m, format) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_short_fscanf(const char *filename, gsl_matrix_short *m)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_short_fscanf(fp, m) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_ushort_fwrite(const char *filename, const gsl_matrix_ushort *m)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_ushort_fwrite(fp, m) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_ushort_fread(const char *filename, gsl_matrix_ushort *m)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_ushort_fread(fp, m) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_ushort_fprintf(const char *filename, const gsl_matrix_ushort *m, const char *format)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_ushort_fprintf(fp, m, format) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_ushort_fscanf(const char *filename, gsl_matrix_ushort *m)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_ushort_fscanf(fp, m) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_char_fwrite(const char *filename, const gsl_matrix_char *m)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_char_fwrite(fp, m) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_char_fread(const char *filename, gsl_matrix_char *m)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_char_fread(fp, m) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_char_fprintf(const char *filename, const gsl_matrix_char *m, const char *format)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_char_fprintf(fp, m, format) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_char_fscanf(const char *filename, gsl_matrix_char *m)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_char_fscanf(fp, m) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_uchar_fwrite(const char *filename, const gsl_matrix_uchar *m)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_uchar_fwrite(fp, m) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_uchar_fread(const char *filename, gsl_matrix_uchar *m)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_uchar_fread(fp, m) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_uchar_fprintf(const char *filename, const gsl_matrix_uchar *m, const char *format)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_uchar_fprintf(fp, m, format) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_uchar_fscanf(const char *filename, gsl_matrix_uchar *m)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_uchar_fscanf(fp, m) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_complex_fwrite(const char *filename, const gsl_matrix_complex *m)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_complex_fwrite(fp, m) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_complex_fread(const char *filename, gsl_matrix_complex *m)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_complex_fread(fp, m) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_complex_fprintf(const char *filename, const gsl_matrix_complex *m, const char *format)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_complex_fprintf(fp, m, format) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_complex_fscanf(const char *filename, gsl_matrix_complex *m)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_complex_fscanf(fp, m) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_complex_float_fwrite(const char *filename, const gsl_matrix_complex_float *m)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_complex_float_fwrite(fp, m) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_complex_float_fread(const char *filename, gsl_matrix_complex_float *m)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_complex_float_fread(fp, m) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_complex_float_fprintf(const char *filename, const gsl_matrix_complex_float *m, const char *format)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"w\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_complex_float_fprintf(fp, m, format) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\nint mgsl_matrix_complex_float_fscanf(const char *filename, gsl_matrix_complex_float *m)\n{\n  FILE *fp;\n  if((fp = fopen(filename, \"r\")) == NULL) return GSL_EFAILED;\n  if(gsl_matrix_complex_float_fscanf(fp, m) != GSL_SUCCESS) return GSL_EFAILED;\n  fclose(fp);\n  return GSL_SUCCESS;\n}\n\n/* Matrix view */\ngsl_matrix_view *alloc_gsl_matrix_view(void)\n{\n  gsl_matrix_view *m = calloc(1, sizeof(gsl_matrix_view));\n  return m;\n}\n\nvoid free_gsl_matrix_view(gsl_matrix_view *m)\n{\n  if(m != NULL){\n    free(m);\n    m = NULL;\n  }\n}\n\ngsl_matrix *mgsl_matrix_submatrix(gsl_matrix_view *view, gsl_matrix *m, size_t k1, size_t k2, size_t n1, size_t n2)\n{\n  *view = gsl_matrix_submatrix(m, k1, k2, n1, n2);\n  return &view->matrix;\n}\n\ngsl_matrix *mgsl_matrix_view_array(gsl_matrix_view *view, double *base, size_t n1, size_t n2)\n{\n  *view = gsl_matrix_view_array(base, n1, n2);\n  return &view->matrix;\n}\n\ngsl_matrix *mgsl_matrix_view_array_with_tda(gsl_matrix_view *view, double *base, size_t n1, size_t n2, size_t tda)\n{\n  *view = gsl_matrix_view_array_with_tda(base, n1, n2, tda);\n  return &view->matrix;\n}\n\ngsl_matrix *mgsl_matrix_view_vector(gsl_matrix_view *view, gsl_vector *v, size_t n1, size_t n2)\n{\n  *view = gsl_matrix_view_vector(v, n1, n2);\n  return &view->matrix;\n}\n\ngsl_matrix *mgsl_matrix_view_vector_with_tda(gsl_matrix_view *view, gsl_vector *v, size_t n1, size_t n2, size_t tda)\n{\n  *view = gsl_matrix_view_vector_with_tda(v, n1, n2, tda);\n  return &view->matrix;\n}\n\ngsl_matrix_float_view *alloc_gsl_matrix_float_view(void)\n{\n  gsl_matrix_float_view *m = calloc(1, sizeof(gsl_matrix_float_view));\n  return m;\n}\n\nvoid free_gsl_matrix_float_view(gsl_matrix_float_view *m)\n{\n  if(m != NULL){\n    free(m);\n    m = NULL;\n  }\n}\n\ngsl_matrix_float *mgsl_matrix_float_submatrix(gsl_matrix_float_view *view, gsl_matrix_float *m, size_t k1, size_t k2, size_t n1, size_t n2)\n{\n  *view = gsl_matrix_float_submatrix(m, k1, k2, n1, n2);\n  return &view->matrix;\n}\n\ngsl_matrix_float *mgsl_matrix_float_view_array(gsl_matrix_float_view *view, float *base, size_t n1, size_t n2)\n{\n  *view = gsl_matrix_float_view_array(base, n1, n2);\n  return &view->matrix;\n}\n\ngsl_matrix_float *mgsl_matrix_float_view_array_with_tda(gsl_matrix_float_view *view, float *base, size_t n1, size_t n2, size_t tda)\n{\n  *view = gsl_matrix_float_view_array_with_tda(base, n1, n2, tda);\n  return &view->matrix;\n}\n\ngsl_matrix_float *mgsl_matrix_float_view_vector(gsl_matrix_float_view *view, gsl_vector_float *v, size_t n1, size_t n2)\n{\n  *view = gsl_matrix_float_view_vector(v, n1, n2);\n  return &view->matrix;\n}\n\ngsl_matrix_float *mgsl_matrix_float_view_vector_with_tda(gsl_matrix_float_view *view, gsl_vector_float *v, size_t n1, size_t n2, size_t tda)\n{\n  *view = gsl_matrix_float_view_vector_with_tda(v, n1, n2, tda);\n  return &view->matrix;\n}\n\ngsl_matrix_int_view *alloc_gsl_matrix_int_view(void)\n{\n  gsl_matrix_int_view *m = calloc(1, sizeof(gsl_matrix_int_view));\n  return m;\n}\n\nvoid free_gsl_matrix_int_view(gsl_matrix_int_view *m)\n{\n  if(m != NULL){\n    free(m);\n    m = NULL;\n  }\n}\n\ngsl_matrix_int *mgsl_matrix_int_submatrix(gsl_matrix_int_view *view, gsl_matrix_int *m, size_t k1, size_t k2, size_t n1, size_t n2)\n{\n  *view = gsl_matrix_int_submatrix(m, k1, k2, n1, n2);\n  return &view->matrix;\n}\n\ngsl_matrix_int *mgsl_matrix_int_view_array(gsl_matrix_int_view *view, int *base, size_t n1, size_t n2)\n{\n  *view = gsl_matrix_int_view_array(base, n1, n2);\n  return &view->matrix;\n}\n\ngsl_matrix_int *mgsl_matrix_int_view_array_with_tda(gsl_matrix_int_view *view, int *base, size_t n1, size_t n2, size_t tda)\n{\n  *view = gsl_matrix_int_view_array_with_tda(base, n1, n2, tda);\n  return &view->matrix;\n}\n\ngsl_matrix_int *mgsl_matrix_int_view_vector(gsl_matrix_int_view *view, gsl_vector_int *v, size_t n1, size_t n2)\n{\n  *view = gsl_matrix_int_view_vector(v, n1, n2);\n  return &view->matrix;\n}\n\ngsl_matrix_int *mgsl_matrix_int_view_vector_with_tda(gsl_matrix_int_view *view, gsl_vector_int *v, size_t n1, size_t n2, size_t tda)\n{\n  *view = gsl_matrix_int_view_vector_with_tda(v, n1, n2, tda);\n  return &view->matrix;\n}\n\ngsl_matrix_uint_view *alloc_gsl_matrix_uint_view(void)\n{\n  gsl_matrix_uint_view *m = calloc(1, sizeof(gsl_matrix_uint_view));\n  return m;\n}\n\nvoid free_gsl_matrix_uint_view(gsl_matrix_uint_view *m)\n{\n  if(m != NULL){\n    free(m);\n    m = NULL;\n  }\n}\n\ngsl_matrix_uint *mgsl_matrix_uint_submatrix(gsl_matrix_uint_view *view, gsl_matrix_uint *m, size_t k1, size_t k2, size_t n1, size_t n2)\n{\n  *view = gsl_matrix_uint_submatrix(m, k1, k2, n1, n2);\n  return &view->matrix;\n}\n\ngsl_matrix_uint *mgsl_matrix_uint_view_array(gsl_matrix_uint_view *view, unsigned int *base, size_t n1, size_t n2)\n{\n  *view = gsl_matrix_uint_view_array(base, n1, n2);\n  return &view->matrix;\n}\n\ngsl_matrix_uint *mgsl_matrix_uint_view_array_with_tda(gsl_matrix_uint_view *view, unsigned int *base, size_t n1, size_t n2, size_t tda)\n{\n  *view = gsl_matrix_uint_view_array_with_tda(base, n1, n2, tda);\n  return &view->matrix;\n}\n\ngsl_matrix_uint *mgsl_matrix_uint_view_vector(gsl_matrix_uint_view *view, gsl_vector_uint *v, size_t n1, size_t n2)\n{\n  *view = gsl_matrix_uint_view_vector(v, n1, n2);\n  return &view->matrix;\n}\n\ngsl_matrix_uint *mgsl_matrix_uint_view_vector_with_tda(gsl_matrix_uint_view *view, gsl_vector_uint *v, size_t n1, size_t n2, size_t tda)\n{\n  *view = gsl_matrix_uint_view_vector_with_tda(v, n1, n2, tda);\n  return &view->matrix;\n}\n\ngsl_matrix_long_view *alloc_gsl_matrix_long_view(void)\n{\n  gsl_matrix_long_view *m = calloc(1, sizeof(gsl_matrix_long_view));\n  return m;\n}\n\nvoid free_gsl_matrix_long_view(gsl_matrix_long_view *m)\n{\n  if(m != NULL){\n    free(m);\n    m = NULL;\n  }\n}\n\ngsl_matrix_long *mgsl_matrix_long_submatrix(gsl_matrix_long_view *view, gsl_matrix_long *m, size_t k1, size_t k2, size_t n1, size_t n2)\n{\n  *view = gsl_matrix_long_submatrix(m, k1, k2, n1, n2);\n  return &view->matrix;\n}\n\ngsl_matrix_long *mgsl_matrix_long_view_array(gsl_matrix_long_view *view, long *base, size_t n1, size_t n2)\n{\n  *view = gsl_matrix_long_view_array(base, n1, n2);\n  return &view->matrix;\n}\n\ngsl_matrix_long *mgsl_matrix_long_view_array_with_tda(gsl_matrix_long_view *view, long *base, size_t n1, size_t n2, size_t tda)\n{\n  *view = gsl_matrix_long_view_array_with_tda(base, n1, n2, tda);\n  return &view->matrix;\n}\n\ngsl_matrix_long *mgsl_matrix_long_view_vector(gsl_matrix_long_view *view, gsl_vector_long *v, size_t n1, size_t n2)\n{\n  *view = gsl_matrix_long_view_vector(v, n1, n2);\n  return &view->matrix;\n}\n\ngsl_matrix_long *mgsl_matrix_long_view_vector_with_tda(gsl_matrix_long_view *view, gsl_vector_long *v, size_t n1, size_t n2, size_t tda)\n{\n  *view = gsl_matrix_long_view_vector_with_tda(v, n1, n2, tda);\n  return &view->matrix;\n}\n\ngsl_matrix_ulong_view *alloc_gsl_matrix_ulong_view(void)\n{\n  gsl_matrix_ulong_view *m = calloc(1, sizeof(gsl_matrix_ulong_view));\n  return m;\n}\n\nvoid free_gsl_matrix_ulong_view(gsl_matrix_ulong_view *m)\n{\n  if(m != NULL){\n    free(m);\n    m = NULL;\n  }\n}\n\ngsl_matrix_ulong *mgsl_matrix_ulong_submatrix(gsl_matrix_ulong_view *view, gsl_matrix_ulong *m, size_t k1, size_t k2, size_t n1, size_t n2)\n{\n  *view = gsl_matrix_ulong_submatrix(m, k1, k2, n1, n2);\n  return &view->matrix;\n}\n\ngsl_matrix_ulong *mgsl_matrix_ulong_view_array(gsl_matrix_ulong_view *view, unsigned long *base, size_t n1, size_t n2)\n{\n  *view = gsl_matrix_ulong_view_array(base, n1, n2);\n  return &view->matrix;\n}\n\ngsl_matrix_ulong *mgsl_matrix_ulong_view_array_with_tda(gsl_matrix_ulong_view *view, unsigned long *base, size_t n1, size_t n2, size_t tda)\n{\n  *view = gsl_matrix_ulong_view_array_with_tda(base, n1, n2, tda);\n  return &view->matrix;\n}\n\ngsl_matrix_ulong *mgsl_matrix_ulong_view_vector(gsl_matrix_ulong_view *view, gsl_vector_ulong *v, size_t n1, size_t n2)\n{\n  *view = gsl_matrix_ulong_view_vector(v, n1, n2);\n  return &view->matrix;\n}\n\ngsl_matrix_ulong *mgsl_matrix_ulong_view_vector_with_tda(gsl_matrix_ulong_view *view, gsl_vector_ulong *v, size_t n1, size_t n2, size_t tda)\n{\n  *view = gsl_matrix_ulong_view_vector_with_tda(v, n1, n2, tda);\n  return &view->matrix;\n}\n\ngsl_matrix_short_view *alloc_gsl_matrix_short_view(void)\n{\n  gsl_matrix_short_view *m = calloc(1, sizeof(gsl_matrix_short_view));\n  return m;\n}\n\nvoid free_gsl_matrix_short_view(gsl_matrix_short_view *m)\n{\n  if(m != NULL){\n    free(m);\n    m = NULL;\n  }\n}\n\ngsl_matrix_short *mgsl_matrix_short_submatrix(gsl_matrix_short_view *view, gsl_matrix_short *m, size_t k1, size_t k2, size_t n1, size_t n2)\n{\n  *view = gsl_matrix_short_submatrix(m, k1, k2, n1, n2);\n  return &view->matrix;\n}\n\ngsl_matrix_short *mgsl_matrix_short_view_array(gsl_matrix_short_view *view, short *base, size_t n1, size_t n2)\n{\n  *view = gsl_matrix_short_view_array(base, n1, n2);\n  return &view->matrix;\n}\n\ngsl_matrix_short *mgsl_matrix_short_view_array_with_tda(gsl_matrix_short_view *view, short *base, size_t n1, size_t n2, size_t tda)\n{\n  *view = gsl_matrix_short_view_array_with_tda(base, n1, n2, tda);\n  return &view->matrix;\n}\n\ngsl_matrix_short *mgsl_matrix_short_view_vector(gsl_matrix_short_view *view, gsl_vector_short *v, size_t n1, size_t n2)\n{\n  *view = gsl_matrix_short_view_vector(v, n1, n2);\n  return &view->matrix;\n}\n\ngsl_matrix_short *mgsl_matrix_short_view_vector_with_tda(gsl_matrix_short_view *view, gsl_vector_short *v, size_t n1, size_t n2, size_t tda)\n{\n  *view = gsl_matrix_short_view_vector_with_tda(v, n1, n2, tda);\n  return &view->matrix;\n}\n\ngsl_matrix_ushort_view *alloc_gsl_matrix_ushort_view(void)\n{\n  gsl_matrix_ushort_view *m = calloc(1, sizeof(gsl_matrix_ushort_view));\n  return m;\n}\n\nvoid free_gsl_matrix_ushort_view(gsl_matrix_ushort_view *m)\n{\n  if(m != NULL){\n    free(m);\n    m = NULL;\n  }\n}\n\ngsl_matrix_ushort *mgsl_matrix_ushort_submatrix(gsl_matrix_ushort_view *view, gsl_matrix_ushort *m, size_t k1, size_t k2, size_t n1, size_t n2)\n{\n  *view = gsl_matrix_ushort_submatrix(m, k1, k2, n1, n2);\n  return &view->matrix;\n}\n\ngsl_matrix_ushort *mgsl_matrix_ushort_view_array(gsl_matrix_ushort_view *view, unsigned short *base, size_t n1, size_t n2)\n{\n  *view = gsl_matrix_ushort_view_array(base, n1, n2);\n  return &view->matrix;\n}\n\ngsl_matrix_ushort *mgsl_matrix_ushort_view_array_with_tda(gsl_matrix_ushort_view *view, unsigned short *base, size_t n1, size_t n2, size_t tda)\n{\n  *view = gsl_matrix_ushort_view_array_with_tda(base, n1, n2, tda);\n  return &view->matrix;\n}\n\ngsl_matrix_ushort *mgsl_matrix_ushort_view_vector(gsl_matrix_ushort_view *view, gsl_vector_ushort *v, size_t n1, size_t n2)\n{\n  *view = gsl_matrix_ushort_view_vector(v, n1, n2);\n  return &view->matrix;\n}\n\ngsl_matrix_ushort *mgsl_matrix_ushort_view_vector_with_tda(gsl_matrix_ushort_view *view, gsl_vector_ushort *v, size_t n1, size_t n2, size_t tda)\n{\n  *view = gsl_matrix_ushort_view_vector_with_tda(v, n1, n2, tda);\n  return &view->matrix;\n}\n\ngsl_matrix_char_view *alloc_gsl_matrix_char_view(void)\n{\n  gsl_matrix_char_view *m = calloc(1, sizeof(gsl_matrix_char_view));\n  return m;\n}\n\nvoid free_gsl_matrix_char_view(gsl_matrix_char_view *m)\n{\n  if(m != NULL){\n    free(m);\n    m = NULL;\n  }\n}\n\ngsl_matrix_char *mgsl_matrix_char_submatrix(gsl_matrix_char_view *view, gsl_matrix_char *m, size_t k1, size_t k2, size_t n1, size_t n2)\n{\n  *view = gsl_matrix_char_submatrix(m, k1, k2, n1, n2);\n  return &view->matrix;\n}\n\ngsl_matrix_char *mgsl_matrix_char_view_array(gsl_matrix_char_view *view, char *base, size_t n1, size_t n2)\n{\n  *view = gsl_matrix_char_view_array(base, n1, n2);\n  return &view->matrix;\n}\n\ngsl_matrix_char *mgsl_matrix_char_view_array_with_tda(gsl_matrix_char_view *view, char *base, size_t n1, size_t n2, size_t tda)\n{\n  *view = gsl_matrix_char_view_array_with_tda(base, n1, n2, tda);\n  return &view->matrix;\n}\n\ngsl_matrix_char *mgsl_matrix_char_view_vector(gsl_matrix_char_view *view, gsl_vector_char *v, size_t n1, size_t n2)\n{\n  *view = gsl_matrix_char_view_vector(v, n1, n2);\n  return &view->matrix;\n}\n\ngsl_matrix_char *mgsl_matrix_char_view_vector_with_tda(gsl_matrix_char_view *view, gsl_vector_char *v, size_t n1, size_t n2, size_t tda)\n{\n  *view = gsl_matrix_char_view_vector_with_tda(v, n1, n2, tda);\n  return &view->matrix;\n}\n\ngsl_matrix_uchar_view *alloc_gsl_matrix_uchar_view(void)\n{\n  gsl_matrix_uchar_view *m = calloc(1, sizeof(gsl_matrix_uchar_view));\n  return m;\n}\n\nvoid free_gsl_matrix_uchar_view(gsl_matrix_uchar_view *m)\n{\n  if(m != NULL){\n    free(m);\n    m = NULL;\n  }\n}\n\ngsl_matrix_uchar *mgsl_matrix_uchar_submatrix(gsl_matrix_uchar_view *view, gsl_matrix_uchar *m, size_t k1, size_t k2, size_t n1, size_t n2)\n{\n  *view = gsl_matrix_uchar_submatrix(m, k1, k2, n1, n2);\n  return &view->matrix;\n}\n\ngsl_matrix_uchar *mgsl_matrix_uchar_view_array(gsl_matrix_uchar_view *view, unsigned char *base, size_t n1, size_t n2)\n{\n  *view = gsl_matrix_uchar_view_array(base, n1, n2);\n  return &view->matrix;\n}\n\ngsl_matrix_uchar *mgsl_matrix_uchar_view_array_with_tda(gsl_matrix_uchar_view *view, unsigned char *base, size_t n1, size_t n2, size_t tda)\n{\n  *view = gsl_matrix_uchar_view_array_with_tda(base, n1, n2, tda);\n  return &view->matrix;\n}\n\ngsl_matrix_uchar *mgsl_matrix_uchar_view_vector(gsl_matrix_uchar_view *view, gsl_vector_uchar *v, size_t n1, size_t n2)\n{\n  *view = gsl_matrix_uchar_view_vector(v, n1, n2);\n  return &view->matrix;\n}\n\ngsl_matrix_uchar *mgsl_matrix_uchar_view_vector_with_tda(gsl_matrix_uchar_view *view, gsl_vector_uchar *v, size_t n1, size_t n2, size_t tda)\n{\n  *view = gsl_matrix_uchar_view_vector_with_tda(v, n1, n2, tda);\n  return &view->matrix;\n}\n\ngsl_matrix_complex_view *alloc_gsl_matrix_complex_view(void)\n{\n  gsl_matrix_complex_view *m = calloc(1, sizeof(gsl_matrix_complex_view));\n  return m;\n}\n\nvoid free_gsl_matrix_complex_view(gsl_matrix_complex_view *m)\n{\n  if(m != NULL){\n    free(m);\n    m = NULL;\n  }\n}\n\ngsl_matrix_complex *mgsl_matrix_complex_submatrix(gsl_matrix_complex_view *view, gsl_matrix_complex *m, size_t k1, size_t k2, size_t n1, size_t n2)\n{\n  *view = gsl_matrix_complex_submatrix(m, k1, k2, n1, n2);\n  return &view->matrix;\n}\n\ngsl_matrix_complex *mgsl_matrix_complex_view_array(gsl_matrix_complex_view *view, double *base, size_t n1, size_t n2)\n{\n  *view = gsl_matrix_complex_view_array(base, n1, n2);\n  return &view->matrix;\n}\n\ngsl_matrix_complex *mgsl_matrix_complex_view_array_with_tda(gsl_matrix_complex_view *view, double *base, size_t n1, size_t n2, size_t tda)\n{\n  *view = gsl_matrix_complex_view_array_with_tda(base, n1, n2, tda);\n  return &view->matrix;\n}\n\ngsl_matrix_complex *mgsl_matrix_complex_view_vector(gsl_matrix_complex_view *view, gsl_vector_complex *v, size_t n1, size_t n2)\n{\n  *view = gsl_matrix_complex_view_vector(v, n1, n2);\n  return &view->matrix;\n}\n\ngsl_matrix_complex *mgsl_matrix_complex_view_vector_with_tda(gsl_matrix_complex_view *view, gsl_vector_complex *v, size_t n1, size_t n2, size_t tda)\n{\n  *view = gsl_matrix_complex_view_vector_with_tda(v, n1, n2, tda);\n  return &view->matrix;\n}\n\ngsl_matrix_complex_float_view *alloc_gsl_matrix_complex_float_view(void)\n{\n  gsl_matrix_complex_float_view *m = calloc(1, sizeof(gsl_matrix_complex_float_view));\n  return m;\n}\n\nvoid free_gsl_matrix_complex_float_view(gsl_matrix_complex_float_view *m)\n{\n  if(m != NULL){\n    free(m);\n    m = NULL;\n  }\n}\n\ngsl_matrix_complex_float *mgsl_matrix_complex_float_submatrix(gsl_matrix_complex_float_view *view, gsl_matrix_complex_float *m, size_t k1, size_t k2, size_t n1, size_t n2)\n{\n  *view = gsl_matrix_complex_float_submatrix(m, k1, k2, n1, n2);\n  return &view->matrix;\n}\n\ngsl_matrix_complex_float *mgsl_matrix_complex_float_view_array(gsl_matrix_complex_float_view *view, float *base, size_t n1, size_t n2)\n{\n  *view = gsl_matrix_complex_float_view_array(base, n1, n2);\n  return &view->matrix;\n}\n\ngsl_matrix_complex_float *mgsl_matrix_complex_float_view_array_with_tda(gsl_matrix_complex_float_view *view, float *base, size_t n1, size_t n2, size_t tda)\n{\n  *view = gsl_matrix_complex_float_view_array_with_tda(base, n1, n2, tda);\n  return &view->matrix;\n}\n\ngsl_matrix_complex_float *mgsl_matrix_complex_float_view_vector(gsl_matrix_complex_float_view *view, gsl_vector_complex_float *v, size_t n1, size_t n2)\n{\n  *view = gsl_matrix_complex_float_view_vector(v, n1, n2);\n  return &view->matrix;\n}\n\ngsl_matrix_complex_float *mgsl_matrix_complex_float_view_vector_with_tda(gsl_matrix_complex_float_view *view, gsl_vector_complex_float *v, size_t n1, size_t n2, size_t tda)\n{\n  *view = gsl_matrix_complex_float_view_vector_with_tda(v, n1, n2, tda);\n  return &view->matrix;\n}\n\n/* Matrix row and column view */\ngsl_vector *mgsl_matrix_row(gsl_vector_view *view, gsl_matrix *m, size_t i)\n{\n  *view = gsl_matrix_row(m, i);\n  return &view->vector;\n}\n\ngsl_vector_float *mgsl_matrix_float_row(gsl_vector_float_view *view, gsl_matrix_float *m, size_t i)\n{\n  *view = gsl_matrix_float_row(m, i);\n  return &view->vector;\n}\n\ngsl_vector_int *mgsl_matrix_int_row(gsl_vector_int_view *view, gsl_matrix_int *m, size_t i)\n{\n  *view = gsl_matrix_int_row(m, i);\n  return &view->vector;\n}\n\ngsl_vector_uint *mgsl_matrix_uint_row(gsl_vector_uint_view *view, gsl_matrix_uint *m, size_t i)\n{\n  *view = gsl_matrix_uint_row(m, i);\n  return &view->vector;\n}\n\ngsl_vector_long *mgsl_matrix_long_row(gsl_vector_long_view *view, gsl_matrix_long *m, size_t i)\n{\n  *view = gsl_matrix_long_row(m, i);\n  return &view->vector;\n}\n\ngsl_vector_ulong *mgsl_matrix_ulong_row(gsl_vector_ulong_view *view, gsl_matrix_ulong *m, size_t i)\n{\n  *view = gsl_matrix_ulong_row(m, i);\n  return &view->vector;\n}\n\ngsl_vector_short *mgsl_matrix_short_row(gsl_vector_short_view *view, gsl_matrix_short *m, size_t i)\n{\n  *view = gsl_matrix_short_row(m, i);\n  return &view->vector;\n}\n\ngsl_vector_ushort *mgsl_matrix_ushort_row(gsl_vector_ushort_view *view, gsl_matrix_ushort *m, size_t i)\n{\n  *view = gsl_matrix_ushort_row(m, i);\n  return &view->vector;\n}\n\ngsl_vector_char *mgsl_matrix_char_row(gsl_vector_char_view *view, gsl_matrix_char *m, size_t i)\n{\n  *view = gsl_matrix_char_row(m, i);\n  return &view->vector;\n}\n\ngsl_vector_uchar *mgsl_matrix_uchar_row(gsl_vector_uchar_view *view, gsl_matrix_uchar *m, size_t i)\n{\n  *view = gsl_matrix_uchar_row(m, i);\n  return &view->vector;\n}\n\ngsl_vector_complex *mgsl_matrix_complex_row(gsl_vector_complex_view *view, gsl_matrix_complex *m, size_t i)\n{\n  *view = gsl_matrix_complex_row(m, i);\n  return &view->vector;\n}\n\ngsl_vector_complex_float *mgsl_matrix_complex_float_row(gsl_vector_complex_float_view *view, gsl_matrix_complex_float *m, size_t i)\n{\n  *view = gsl_matrix_complex_float_row(m, i);\n  return &view->vector;\n}\n\ngsl_vector *mgsl_matrix_column(gsl_vector_view *view, gsl_matrix *m, size_t j)\n{\n  *view = gsl_matrix_column(m, j);\n  return &view->vector;\n}\n\ngsl_vector_float *mgsl_matrix_float_column(gsl_vector_float_view *view, gsl_matrix_float *m, size_t j)\n{\n  *view = gsl_matrix_float_column(m, j);\n  return &view->vector;\n}\n\ngsl_vector_int *mgsl_matrix_int_column(gsl_vector_int_view *view, gsl_matrix_int *m, size_t j)\n{\n  *view = gsl_matrix_int_column(m, j);\n  return &view->vector;\n}\n\ngsl_vector_uint *mgsl_matrix_uint_column(gsl_vector_uint_view *view, gsl_matrix_uint *m, size_t j)\n{\n  *view = gsl_matrix_uint_column(m, j);\n  return &view->vector;\n}\n\ngsl_vector_long *mgsl_matrix_long_column(gsl_vector_long_view *view, gsl_matrix_long *m, size_t j)\n{\n  *view = gsl_matrix_long_column(m, j);\n  return &view->vector;\n}\n\ngsl_vector_ulong *mgsl_matrix_ulong_column(gsl_vector_ulong_view *view, gsl_matrix_ulong *m, size_t j)\n{\n  *view = gsl_matrix_ulong_column(m, j);\n  return &view->vector;\n}\n\ngsl_vector_short *mgsl_matrix_short_column(gsl_vector_short_view *view, gsl_matrix_short *m, size_t j)\n{\n  *view = gsl_matrix_short_column(m, j);\n  return &view->vector;\n}\n\ngsl_vector_ushort *mgsl_matrix_ushort_column(gsl_vector_ushort_view *view, gsl_matrix_ushort *m, size_t j)\n{\n  *view = gsl_matrix_ushort_column(m, j);\n  return &view->vector;\n}\n\ngsl_vector_char *mgsl_matrix_char_column(gsl_vector_char_view *view, gsl_matrix_char *m, size_t j)\n{\n  *view = gsl_matrix_char_column(m, j);\n  return &view->vector;\n}\n\ngsl_vector_uchar *mgsl_matrix_uchar_column(gsl_vector_uchar_view *view, gsl_matrix_uchar *m, size_t j)\n{\n  *view = gsl_matrix_uchar_column(m, j);\n  return &view->vector;\n}\n\ngsl_vector_complex *mgsl_matrix_complex_column(gsl_vector_complex_view *view, gsl_matrix_complex *m, size_t j)\n{\n  *view = gsl_matrix_complex_column(m, j);\n  return &view->vector;\n}\n\ngsl_vector_complex_float *mgsl_matrix_complex_float_column(gsl_vector_complex_float_view *view, gsl_matrix_complex_float *m, size_t j)\n{\n  *view = gsl_matrix_complex_float_column(m, j);\n  return &view->vector;\n}\n\ngsl_vector *mgsl_matrix_subrow(gsl_vector_view *view, gsl_matrix *m, size_t i, size_t offset, size_t n)\n{\n  *view = gsl_matrix_subrow(m, i, offset, n);\n  return &view->vector;\n}\n\ngsl_vector_float *mgsl_matrix_float_subrow(gsl_vector_float_view *view, gsl_matrix_float *m, size_t i, size_t offset, size_t n)\n{\n  *view = gsl_matrix_float_subrow(m, i, offset, n);\n  return &view->vector;\n}\n\ngsl_vector_int *mgsl_matrix_int_subrow(gsl_vector_int_view *view, gsl_matrix_int *m, size_t i, size_t offset, size_t n)\n{\n  *view = gsl_matrix_int_subrow(m, i, offset, n);\n  return &view->vector;\n}\n\ngsl_vector_uint *mgsl_matrix_uint_subrow(gsl_vector_uint_view *view, gsl_matrix_uint *m, size_t i, size_t offset, size_t n)\n{\n  *view = gsl_matrix_uint_subrow(m, i, offset, n);\n  return &view->vector;\n}\n\ngsl_vector_long *mgsl_matrix_long_subrow(gsl_vector_long_view *view, gsl_matrix_long *m, size_t i, size_t offset, size_t n)\n{\n  *view = gsl_matrix_long_subrow(m, i, offset, n);\n  return &view->vector;\n}\n\ngsl_vector_ulong *mgsl_matrix_ulong_subrow(gsl_vector_ulong_view *view, gsl_matrix_ulong *m, size_t i, size_t offset, size_t n)\n{\n  *view = gsl_matrix_ulong_subrow(m, i, offset, n);\n  return &view->vector;\n}\n\ngsl_vector_short *mgsl_matrix_short_subrow(gsl_vector_short_view *view, gsl_matrix_short *m, size_t i, size_t offset, size_t n)\n{\n  *view = gsl_matrix_short_subrow(m, i, offset, n);\n  return &view->vector;\n}\n\ngsl_vector_ushort *mgsl_matrix_ushort_subrow(gsl_vector_ushort_view *view, gsl_matrix_ushort *m, size_t i, size_t offset, size_t n)\n{\n  *view = gsl_matrix_ushort_subrow(m, i, offset, n);\n  return &view->vector;\n}\n\ngsl_vector_char *mgsl_matrix_char_subrow(gsl_vector_char_view *view, gsl_matrix_char *m, size_t i, size_t offset, size_t n)\n{\n  *view = gsl_matrix_char_subrow(m, i, offset, n);\n  return &view->vector;\n}\n\ngsl_vector_uchar *mgsl_matrix_uchar_subrow(gsl_vector_uchar_view *view, gsl_matrix_uchar *m, size_t i, size_t offset, size_t n)\n{\n  *view = gsl_matrix_uchar_subrow(m, i, offset, n);\n  return &view->vector;\n}\n\ngsl_vector_complex *mgsl_matrix_complex_subrow(gsl_vector_complex_view *view, gsl_matrix_complex *m, size_t i, size_t offset, size_t n)\n{\n  *view = gsl_matrix_complex_subrow(m, i, offset, n);\n  return &view->vector;\n}\n\ngsl_vector_complex_float *mgsl_matrix_complex_float_subrow(gsl_vector_complex_float_view *view, gsl_matrix_complex_float *m, size_t i, size_t offset, size_t n)\n{\n  *view = gsl_matrix_complex_float_subrow(m, i, offset, n);\n  return &view->vector;\n}\n\ngsl_vector *mgsl_matrix_subcolumn(gsl_vector_view *view, gsl_matrix *m, size_t j, size_t offset, size_t n)\n{\n  *view = gsl_matrix_subcolumn(m, j, offset, n);\n  return &view->vector;\n}\n\ngsl_vector_float *mgsl_matrix_float_subcolumn(gsl_vector_float_view *view, gsl_matrix_float *m, size_t j, size_t offset, size_t n)\n{\n  *view = gsl_matrix_float_subcolumn(m, j, offset, n);\n  return &view->vector;\n}\n\ngsl_vector_int *mgsl_matrix_int_subcolumn(gsl_vector_int_view *view, gsl_matrix_int *m, size_t j, size_t offset, size_t n)\n{\n  *view = gsl_matrix_int_subcolumn(m, j, offset, n);\n  return &view->vector;\n}\n\ngsl_vector_uint *mgsl_matrix_uint_subcolumn(gsl_vector_uint_view *view, gsl_matrix_uint *m, size_t j, size_t offset, size_t n)\n{\n  *view = gsl_matrix_uint_subcolumn(m, j, offset, n);\n  return &view->vector;\n}\n\ngsl_vector_long *mgsl_matrix_long_subcolumn(gsl_vector_long_view *view, gsl_matrix_long *m, size_t j, size_t offset, size_t n)\n{\n  *view = gsl_matrix_long_subcolumn(m, j, offset, n);\n  return &view->vector;\n}\n\ngsl_vector_ulong *mgsl_matrix_ulong_subcolumn(gsl_vector_ulong_view *view, gsl_matrix_ulong *m, size_t j, size_t offset, size_t n)\n{\n  *view = gsl_matrix_ulong_subcolumn(m, j, offset, n);\n  return &view->vector;\n}\n\ngsl_vector_short *mgsl_matrix_short_subcolumn(gsl_vector_short_view *view, gsl_matrix_short *m, size_t j, size_t offset, size_t n)\n{\n  *view = gsl_matrix_short_subcolumn(m, j, offset, n);\n  return &view->vector;\n}\n\ngsl_vector_ushort *mgsl_matrix_ushort_subcolumn(gsl_vector_ushort_view *view, gsl_matrix_ushort *m, size_t j, size_t offset, size_t n)\n{\n  *view = gsl_matrix_ushort_subcolumn(m, j, offset, n);\n  return &view->vector;\n}\n\ngsl_vector_char *mgsl_matrix_char_subcolumn(gsl_vector_char_view *view, gsl_matrix_char *m, size_t j, size_t offset, size_t n)\n{\n  *view = gsl_matrix_char_subcolumn(m, j, offset, n);\n  return &view->vector;\n}\n\ngsl_vector_uchar *mgsl_matrix_uchar_subcolumn(gsl_vector_uchar_view *view, gsl_matrix_uchar *m, size_t j, size_t offset, size_t n)\n{\n  *view = gsl_matrix_uchar_subcolumn(m, j, offset, n);\n  return &view->vector;\n}\n\ngsl_vector_complex *mgsl_matrix_complex_subcolumn(gsl_vector_complex_view *view, gsl_matrix_complex *m, size_t j, size_t offset, size_t n)\n{\n  *view = gsl_matrix_complex_subcolumn(m, j, offset, n);\n  return &view->vector;\n}\n\ngsl_vector_complex_float *mgsl_matrix_complex_float_subcolumn(gsl_vector_complex_float_view *view, gsl_matrix_complex_float *m, size_t j, size_t offset, size_t n)\n{\n  *view = gsl_matrix_complex_float_subcolumn(m, j, offset, n);\n  return &view->vector;\n}\n\ngsl_vector *mgsl_matrix_diagonal(gsl_vector_view *view, gsl_matrix *m)\n{\n  *view = gsl_matrix_diagonal(m);\n  return &view->vector;\n}\n\ngsl_vector_float *mgsl_matrix_float_diagonal(gsl_vector_float_view *view, gsl_matrix_float *m)\n{\n  *view = gsl_matrix_float_diagonal(m);\n  return &view->vector;\n}\n\ngsl_vector_int *mgsl_matrix_int_diagonal(gsl_vector_int_view *view, gsl_matrix_int *m)\n{\n  *view = gsl_matrix_int_diagonal(m);\n  return &view->vector;\n}\n\ngsl_vector_uint *mgsl_matrix_uint_diagonal(gsl_vector_uint_view *view, gsl_matrix_uint *m)\n{\n  *view = gsl_matrix_uint_diagonal(m);\n  return &view->vector;\n}\n\ngsl_vector_long *mgsl_matrix_long_diagonal(gsl_vector_long_view *view, gsl_matrix_long *m)\n{\n  *view = gsl_matrix_long_diagonal(m);\n  return &view->vector;\n}\n\ngsl_vector_ulong *mgsl_matrix_ulong_diagonal(gsl_vector_ulong_view *view, gsl_matrix_ulong *m)\n{\n  *view = gsl_matrix_ulong_diagonal(m);\n  return &view->vector;\n}\n\ngsl_vector_short *mgsl_matrix_short_diagonal(gsl_vector_short_view *view, gsl_matrix_short *m)\n{\n  *view = gsl_matrix_short_diagonal(m);\n  return &view->vector;\n}\n\ngsl_vector_ushort *mgsl_matrix_ushort_diagonal(gsl_vector_ushort_view *view, gsl_matrix_ushort *m)\n{\n  *view = gsl_matrix_ushort_diagonal(m);\n  return &view->vector;\n}\n\ngsl_vector_char *mgsl_matrix_char_diagonal(gsl_vector_char_view *view, gsl_matrix_char *m)\n{\n  *view = gsl_matrix_char_diagonal(m);\n  return &view->vector;\n}\n\ngsl_vector_uchar *mgsl_matrix_uchar_diagonal(gsl_vector_uchar_view *view, gsl_matrix_uchar *m)\n{\n  *view = gsl_matrix_uchar_diagonal(m);\n  return &view->vector;\n}\n\ngsl_vector_complex *mgsl_matrix_complex_diagonal(gsl_vector_complex_view *view, gsl_matrix_complex *m)\n{\n  *view = gsl_matrix_complex_diagonal(m);\n  return &view->vector;\n}\n\ngsl_vector_complex_float *mgsl_matrix_complex_float_diagonal(gsl_vector_complex_float_view *view, gsl_matrix_complex_float *m)\n{\n  *view = gsl_matrix_complex_float_diagonal(m);\n  return &view->vector;\n}\n\ngsl_vector *mgsl_matrix_subdiagonal(gsl_vector_view *view, gsl_matrix *m, size_t k)\n{\n  *view = gsl_matrix_subdiagonal(m, k);\n  return &view->vector;\n}\n\ngsl_vector_float *mgsl_matrix_float_subdiagonal(gsl_vector_float_view *view, gsl_matrix_float *m, size_t k)\n{\n  *view = gsl_matrix_float_subdiagonal(m, k);\n  return &view->vector;\n}\n\ngsl_vector_int *mgsl_matrix_int_subdiagonal(gsl_vector_int_view *view, gsl_matrix_int *m, size_t k)\n{\n  *view = gsl_matrix_int_subdiagonal(m, k);\n  return &view->vector;\n}\n\ngsl_vector_uint *mgsl_matrix_uint_subdiagonal(gsl_vector_uint_view *view, gsl_matrix_uint *m, size_t k)\n{\n  *view = gsl_matrix_uint_subdiagonal(m, k);\n  return &view->vector;\n}\n\ngsl_vector_long *mgsl_matrix_long_subdiagonal(gsl_vector_long_view *view, gsl_matrix_long *m, size_t k)\n{\n  *view = gsl_matrix_long_subdiagonal(m, k);\n  return &view->vector;\n}\n\ngsl_vector_ulong *mgsl_matrix_ulong_subdiagonal(gsl_vector_ulong_view *view, gsl_matrix_ulong *m, size_t k)\n{\n  *view = gsl_matrix_ulong_subdiagonal(m, k);\n  return &view->vector;\n}\n\ngsl_vector_short *mgsl_matrix_short_subdiagonal(gsl_vector_short_view *view, gsl_matrix_short *m, size_t k)\n{\n  *view = gsl_matrix_short_subdiagonal(m, k);\n  return &view->vector;\n}\n\ngsl_vector_ushort *mgsl_matrix_ushort_subdiagonal(gsl_vector_ushort_view *view, gsl_matrix_ushort *m, size_t k)\n{\n  *view = gsl_matrix_ushort_subdiagonal(m, k);\n  return &view->vector;\n}\n\ngsl_vector_char *mgsl_matrix_char_subdiagonal(gsl_vector_char_view *view, gsl_matrix_char *m, size_t k)\n{\n  *view = gsl_matrix_char_subdiagonal(m, k);\n  return &view->vector;\n}\n\ngsl_vector_uchar *mgsl_matrix_uchar_subdiagonal(gsl_vector_uchar_view *view, gsl_matrix_uchar *m, size_t k)\n{\n  *view = gsl_matrix_uchar_subdiagonal(m, k);\n  return &view->vector;\n}\n\ngsl_vector_complex *mgsl_matrix_complex_subdiagonal(gsl_vector_complex_view *view, gsl_matrix_complex *m, size_t k)\n{\n  *view = gsl_matrix_complex_subdiagonal(m, k);\n  return &view->vector;\n}\n\ngsl_vector_complex_float *mgsl_matrix_complex_float_subdiagonal(gsl_vector_complex_float_view *view, gsl_matrix_complex_float *m, size_t k)\n{\n  *view = gsl_matrix_complex_float_subdiagonal(m, k);\n  return &view->vector;\n}\n\ngsl_vector *mgsl_matrix_superdiagonal(gsl_vector_view *view, gsl_matrix *m, size_t k)\n{\n  *view = gsl_matrix_superdiagonal(m, k);\n  return &view->vector;\n}\n\ngsl_vector_float *mgsl_matrix_float_superdiagonal(gsl_vector_float_view *view, gsl_matrix_float *m, size_t k)\n{\n  *view = gsl_matrix_float_superdiagonal(m, k);\n  return &view->vector;\n}\n\ngsl_vector_int *mgsl_matrix_int_superdiagonal(gsl_vector_int_view *view, gsl_matrix_int *m, size_t k)\n{\n  *view = gsl_matrix_int_superdiagonal(m, k);\n  return &view->vector;\n}\n\ngsl_vector_uint *mgsl_matrix_uint_superdiagonal(gsl_vector_uint_view *view, gsl_matrix_uint *m, size_t k)\n{\n  *view = gsl_matrix_uint_superdiagonal(m, k);\n  return &view->vector;\n}\n\ngsl_vector_long *mgsl_matrix_long_superdiagonal(gsl_vector_long_view *view, gsl_matrix_long *m, size_t k)\n{\n  *view = gsl_matrix_long_superdiagonal(m, k);\n  return &view->vector;\n}\n\ngsl_vector_ulong *mgsl_matrix_ulong_superdiagonal(gsl_vector_ulong_view *view, gsl_matrix_ulong *m, size_t k)\n{\n  *view = gsl_matrix_ulong_superdiagonal(m, k);\n  return &view->vector;\n}\n\ngsl_vector_short *mgsl_matrix_short_superdiagonal(gsl_vector_short_view *view, gsl_matrix_short *m, size_t k)\n{\n  *view = gsl_matrix_short_superdiagonal(m, k);\n  return &view->vector;\n}\n\ngsl_vector_ushort *mgsl_matrix_ushort_superdiagonal(gsl_vector_ushort_view *view, gsl_matrix_ushort *m, size_t k)\n{\n  *view = gsl_matrix_ushort_superdiagonal(m, k);\n  return &view->vector;\n}\n\ngsl_vector_char *mgsl_matrix_char_superdiagonal(gsl_vector_char_view *view, gsl_matrix_char *m, size_t k)\n{\n  *view = gsl_matrix_char_superdiagonal(m, k);\n  return &view->vector;\n}\n\ngsl_vector_uchar *mgsl_matrix_uchar_superdiagonal(gsl_vector_uchar_view *view, gsl_matrix_uchar *m, size_t k)\n{\n  *view = gsl_matrix_uchar_superdiagonal(m, k);\n  return &view->vector;\n}\n\ngsl_vector_complex *mgsl_matrix_complex_superdiagonal(gsl_vector_complex_view *view, gsl_matrix_complex *m, size_t k)\n{\n  *view = gsl_matrix_complex_superdiagonal(m, k);\n  return &view->vector;\n}\n\ngsl_vector_complex_float *mgsl_matrix_complex_float_superdiagonal(gsl_vector_complex_float_view *view, gsl_matrix_complex_float *m, size_t k)\n{\n  *view = gsl_matrix_complex_float_superdiagonal(m, k);\n  return &view->vector;\n}\n", "meta": {"hexsha": "88cd776c6575befa7c10cef5bb762cd4bf6a122f", "size": 86727, "ext": "c", "lang": "C", "max_stars_repo_path": "src/matrix.c", "max_stars_repo_name": "frithnanth/raku-Math-Libgsl-Matrix", "max_stars_repo_head_hexsha": "2f6c28062734dba9bf8be1b28f5b04d5344becec", "max_stars_repo_licenses": ["Artistic-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-15T13:54:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T16:00:28.000Z", "max_issues_repo_path": "src/matrix.c", "max_issues_repo_name": "frithnanth/raku-Math-Libgsl-Matrix", "max_issues_repo_head_hexsha": "2f6c28062734dba9bf8be1b28f5b04d5344becec", "max_issues_repo_licenses": ["Artistic-2.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-07-17T07:16:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-12T05:09:26.000Z", "max_forks_repo_path": "src/matrix.c", "max_forks_repo_name": "frithnanth/raku-Math-Libgsl-Matrix", "max_forks_repo_head_hexsha": "2f6c28062734dba9bf8be1b28f5b04d5344becec", "max_forks_repo_licenses": ["Artistic-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-07-17T06:58:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-30T16:00:43.000Z", "avg_line_length": 29.8852515507, "max_line_length": 179, "alphanum_fraction": 0.7512769956, "num_tokens": 25271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19436782968560462, "lm_q2_score": 0.033589503594335136, "lm_q1q2_score": 0.006528718913847736}}
{"text": "/*****************************************************************\\\n           __\n          / /\n\t\t / /                     __  __\n\t\t/ /______    _______    / / / / ________   __       __\n\t   / ______  \\  /_____  \\  / / / / / _____  | / /      / /\n\t  / /      | / _______| / / / / / / /____/ / / /      / /\n\t / /      / / / _____  / / / / / / _______/ / /      / /\n\t/ /      / / / /____/ / / / / / / |______  / |______/ /\n   /_/      /_/ |________/ / / / /  \\_______/  \\_______  /\n                          /_/ /_/                     / /\n\t\t\t                                         / /\n\t\t                                            /_/\n\n  ---------------------------------------------------------------\n\n  Copyright (c) 2007-2011 - Rodrigo Braz Monteiro.\n  This file is subject to the terms of halley_license.txt.\n\n\\*****************************************************************/\n\n#pragma once\n\n#include <gsl/gsl>\n#include \"halley/maths/vector2.h\"\n#include \"halley/text/halleystring.h\"\n#include \"halley/resources/resource.h\"\n#include \"halley/file/path.h\"\n#include \"halley/maths/rect.h\"\n#include \"halley/maths/colour.h\"\n\nnamespace Halley {\n\tclass ResourceDataStatic;\n\tclass ResourceLoader;\n\n\tclass Image final : public Resource {\n\tpublic:\n\t\tenum class Format {\n\t\t\tUndefined,\n\t\t\tIndexed,\n\t\t\tRGB,\n\t\t\tRGBA,\n\t\t\tRGBAPremultiplied,\n\t\t\tSingleChannel\n\t\t};\n\n\t\tImage(Format format = Format::RGBA, Vector2i size = {});\n\t\tImage(gsl::span<const gsl::byte> bytes, Format format = Format::Undefined);\n\t\texplicit Image(const ResourceDataStatic& data);\n\t\tImage(const ResourceDataStatic& data, const Metadata& meta);\n\t\tImage(Image&& other);\n\t\t~Image();\n\n\t\tstd::unique_ptr<Image> clone();\n\n\t\tvoid setSize(Vector2i size);\n\n\t\tvoid load(gsl::span<const gsl::byte> bytes, Format format = Format::Undefined);\n\t\tBytes savePNGToBytes(bool allowDepthReduce = true) const;\n\t\tBytes saveQOIToBytes() const;\n\t\tstatic Vector2i getImageSize(gsl::span<const gsl::byte> bytes);\n\t\tstatic Format getImageFormat(gsl::span<const gsl::byte> bytes);\n\n\t\tstatic bool isQOI(gsl::span<const gsl::byte> bytes);\n\t\tstatic bool isPNG(gsl::span<const gsl::byte> bytes);\n\n\t\tgsl::span<unsigned char> getPixelBytes();\n\t\tgsl::span<const unsigned char> getPixelBytes() const;\n\t\tgsl::span<const unsigned char> getPixelBytesRow(int x0, int x1, int y) const;\n\t\t\n\t\tint getPixel4BPP(Vector2i pos) const;\n\t\tint getPixelAlpha(Vector2i pos) const;\n\t\tgsl::span<int> getPixels4BPP();\n\t\tgsl::span<const int> getPixels4BPP() const;\n\t\tgsl::span<const int> getPixelRow4BPP(int x0, int x1, int y) const;\n\t\tsize_t getByteSize() const;\n\n\t\tstatic unsigned int convertRGBAToInt(unsigned int r, unsigned int g, unsigned int b, unsigned int a=255);\n\t\tstatic void convertIntToRGBA(unsigned int col, unsigned int& r, unsigned int& g, unsigned int& b, unsigned int& a);\n\t\tstatic Colour4c convertIntToColour(unsigned int col);\n\n\t\tunsigned int getWidth() const { return w; }\n\t\tunsigned int getHeight() const { return h; }\n\t\tVector2i getSize() const { return Vector2i(int(w), int(h)); }\n\n\t\tint getBytesPerPixel() const;\n\t\tFormat getFormat() const;\n\n\t\tRect4i getTrimRect() const;\n\t\tRect4i getRect() const;\n\n\t\tvoid clear(int colour);\n\t\tvoid blitFrom(Vector2i pos, gsl::span<const unsigned char> buffer, size_t width, size_t height, size_t pitch, size_t srcBpp);\n\t\tvoid blitFromRotated(Vector2i pos, gsl::span<const unsigned char> buffer, size_t width, size_t height, size_t pitch, size_t bpp);\n\t\tvoid blitFrom(Vector2i pos, const Image& srcImg, bool rotated = false);\n\t\tvoid blitFrom(Vector2i pos, const Image& srcImg, Rect4i srcArea, bool rotated = false);\n\t\tvoid blitDownsampled(Image& src, int scale);\n\n\t\tvoid drawImageAlpha(const Image& src, Vector2i pos, uint8_t opacity = 255);\n\t\tvoid drawImageAdd(const Image& src, Vector2i pos, uint8_t opacity = 255);\n\t\tvoid drawImageLighten(const Image& src, Vector2i pos, uint8_t opacity = 255);\n\n\t\tstatic std::unique_ptr<Image> loadResource(ResourceLoader& loader);\n\t\tconstexpr static AssetType getAssetType() { return AssetType::Image; }\n\t\tvoid reload(Resource&& resource) override;\n\n\t\tImage& operator=(const Image& o) = delete;\n\t\tImage& operator=(Image&& o) = default;\n\n\t\tvoid serialize(Serializer& s) const;\n\t\tvoid deserialize(Deserializer& s);\n\n\t\tvoid preMultiply();\n\n\t\tResourceMemoryUsage getMemoryUsage() const override;\n\n\tprivate:\n\t\tstd::unique_ptr<unsigned char, void(*)(unsigned char*)> px;\n\t\tsize_t dataLen = 0;\n\t\tunsigned int w = 0;\n\t\tunsigned int h = 0;\n\t\tFormat format = Format::Undefined;\n\t};\n\n\ttemplate <>\n\tstruct EnumNames<Image::Format> {\n\t\tconstexpr std::array<const char*, 6> operator()() const {\n\t\t\treturn{{\n\t\t\t\t\"undefined\",\n\t\t\t\t\"indexed\",\n\t\t\t\t\"rgb\",\n\t\t\t\t\"rgba\",\n\t\t\t\t\"rgba_premultiplied\",\n\t\t\t\t\"single_channel\"\n\t\t\t}};\n\t\t}\n\t};\n}\n", "meta": {"hexsha": "969ba4c00327b968f8a70f4d6d11543385053890", "size": 4710, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engine/utils/include/halley/file_formats/image.h", "max_stars_repo_name": "amrezzd/halley", "max_stars_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/engine/utils/include/halley/file_formats/image.h", "max_issues_repo_name": "amrezzd/halley", "max_issues_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engine/utils/include/halley/file_formats/image.h", "max_forks_repo_name": "amrezzd/halley", "max_forks_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8848920863, "max_line_length": 131, "alphanum_fraction": 0.6267515924, "num_tokens": 1274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23651622568252115, "lm_q2_score": 0.027585280228221404, "lm_q1q2_score": 0.006524366363973602}}
{"text": "// This file is part of playd.\n// playd is licensed under the MIT licence: see LICENSE.txt.\n\n/**\n * @file\n * The Ring_buffer class.\n */\n\n#ifndef PLAYD_RING_BUFFER_HPP\n#define PLAYD_RING_BUFFER_HPP\n\n#include <atomic>\n#include <mutex>\n#include <vector>\n\n#undef max\n#include <gsl/gsl>\n\nnamespace Playd::Audio\n{\n/**\n * A concurrent ring buffer.\n *\n * This is not particularly efficient, but does the job for playd.\n * It uses two release-acquire-atomic counters to store read and write.\n */\nclass RingBuffer\n{\npublic:\n\t/**\n\t * Constructs a Ring_buffer.\n\t * @param capacity The capacity of the ring buffer, in bytes.\n\t */\n\texplicit RingBuffer(size_t capacity);\n\n\t/// Destructs a Ring_buffer.\n\t~RingBuffer() = default;\n\n\t/// Deleted copy constructor.\n\tRingBuffer(const RingBuffer &) = delete;\n\n\t/// Deleted copy-assignment.\n\tRingBuffer &operator=(const RingBuffer &) = delete;\n\n\t/**\n\t * The current write capacity.\n\t * @return The number of samples this ring buffer has space to store.\n\t * @see Write\n\t */\n\tsize_t WriteCapacity() const;\n\n\t/**\n\t * The current read capacity.\n\t * @return The number of samples available in this ring buffer.\n\t * @see Read\n\t */\n\tsize_t ReadCapacity() const;\n\n\t/**\n\t * Writes samples from a span into the ring buffer.\n\t *\n\t * * Precondition: @a src is a valid span.\n\t * * Postcondition: The ringbuffer has been written to with the contents\n\t *     of the first WriteCapacity() bytes of @a src.\n\t *\n\t * @param src The span of bytes to write into the ring buffer.\n\t * @return The number of bytes written.\n\t * @see WriteCapacity\n\t */\n\tsize_t Write(gsl::span<const std::byte> src);\n\n\t/**\n\t * Reads samples from the ring buffer into an array.\n\t * To read one sample, pass a count of 1 and take a pointer to the\n\t * sample variable.\n\t *\n\t * * Precondition: @a dest is a valid span.\n\t * * Postcondition: The first ReadCapacity() bytes of @a dest have been\n\t *     filled with the appropriate number of bytes from the front of the\n\t *     ring buffer.\n\t *\n\t * @param dest The span of bytes to fill with bytes read from the ring\n\t *  buffer.\n\t * @return The number of bytes read.\n\t * @see ReadCapacity\n\t */\n\tsize_t Read(gsl::span<std::byte> dest);\n\n\t/// Empties the ring buffer.\n\tvoid Flush();\n\nprivate:\n\t/// Empties the ring buffer without acquiring locks.\n\tvoid FlushInner();\n\n\tstd::vector<std::byte> buffer; ///< The array used by the ringbuffer.\n\n\tstd::vector<std::byte>::const_iterator r_it; ///< The read iterator.\n\tstd::vector<std::byte>::iterator w_it;       ///< The write iterator.\n\n\tstd::atomic<size_t> count; ///< The current read capacity.\n\t// Write capacity is the total buffer capacity minus count.\n\n\tstd::mutex r_lock; ///< The read lock.\n\tstd::mutex w_lock; ///< The write lock.\n};\n\n} // namespace Playd::Audio\n\n#endif // PLAYD_RINGBUFFER_HPP\n", "meta": {"hexsha": "422ee667e807b6aca297a7bd3ee26de577d88e44", "size": 2774, "ext": "h", "lang": "C", "max_stars_repo_path": "src/audio/ringbuffer.h", "max_stars_repo_name": "UniversityRadioYork/ury-playd", "max_stars_repo_head_hexsha": "dc072e4934acb21b9dddb225818732bd27671ae0", "max_stars_repo_licenses": ["BSL-1.0", "MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-02-11T20:33:45.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-19T20:01:51.000Z", "max_issues_repo_path": "src/audio/ringbuffer.h", "max_issues_repo_name": "UniversityRadioYork/ury-playd", "max_issues_repo_head_hexsha": "dc072e4934acb21b9dddb225818732bd27671ae0", "max_issues_repo_licenses": ["BSL-1.0", "MIT"], "max_issues_count": 56.0, "max_issues_repo_issues_event_min_datetime": "2015-01-01T19:22:34.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-28T13:48:14.000Z", "max_forks_repo_path": "src/audio/ringbuffer.h", "max_forks_repo_name": "UniversityRadioYork/ury-playd", "max_forks_repo_head_hexsha": "dc072e4934acb21b9dddb225818732bd27671ae0", "max_forks_repo_licenses": ["BSL-1.0", "MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-09-04T23:04:46.000Z", "max_forks_repo_forks_event_max_datetime": "2017-02-23T12:41:21.000Z", "avg_line_length": 24.990990991, "max_line_length": 73, "alphanum_fraction": 0.6870944484, "num_tokens": 702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20946968133032526, "lm_q2_score": 0.031143827724615873, "lm_q1q2_score": 0.006523687668881836}}
{"text": "#ifndef MODULE_WASM_TABLE_H\n#define MODULE_WASM_TABLE_H\n\n#include \"function/TableFunction.h\"\n#include <gsl/span>\n\nnamespace wasm {\n\nstruct WasmTable {\n\n\tusing wasm_external_kind_type = parse::Table;\n\tusing any_function_type = std::optional<\n\t\n\tgsl::span<any_function_type> get_segment(std::size_t offset, std::size_t length)\n\t{\n\t\tassert(offset <= table_.size());\n\t\tassert((table_.size() - offset) >= lenfth);\n\t\treturn gsl::span<TableFunction>(table_.data() + offset, length);\n\t}\n\t\n\tfriend bool matches(const WasmTable& self, const parse::Table& tp)\n\t{\n\t\treturn self.table_.size() >= tp.size() and (\n\t\t\tself.maximum_ == tp.maximum.value_or(std::numeric_limits<std::size_t>::max())\n\t\t);\n\t}\n\n\tconst any_function_type& at(wasm_uint32_t idx) const\n\t{ return table_.at(idx); }\n\t\n\tany_function_type& at(wasm_uint32_t idx)\n\t{ return table_.at(idx); }\n\t\nprivate:\n\tstd::vector<table_function_type> table_;\n\tconst std::size_t maximum_ = std::numeric_limits<std::size_t>::max();\n};\n\n} /* namespace wasm */\n\n#endif /* MODULE_WASM_TABLE_H */\n", "meta": {"hexsha": "76a30b50566578c0361d7ee21d9ed1edb9810bfc", "size": 1028, "ext": "h", "lang": "C", "max_stars_repo_path": "include/module/WasmTable.h", "max_stars_repo_name": "tvanslyke/wasm-cpp", "max_stars_repo_head_hexsha": "8a56c1706e2723ece36e3642bae9e36792dbd7b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/module/WasmTable.h", "max_issues_repo_name": "tvanslyke/wasm-cpp", "max_issues_repo_head_hexsha": "8a56c1706e2723ece36e3642bae9e36792dbd7b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/module/WasmTable.h", "max_forks_repo_name": "tvanslyke/wasm-cpp", "max_forks_repo_head_hexsha": "8a56c1706e2723ece36e3642bae9e36792dbd7b2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4761904762, "max_line_length": 81, "alphanum_fraction": 0.71692607, "num_tokens": 272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.26588047309981694, "lm_q2_score": 0.024423090231629235, "lm_q1q2_score": 0.006493622785345099}}
{"text": "#pragma once\n#include <string>\n#include <type_traits>\n#include <tuple>\n#include <gsl.h>\n#include \"roster.h\"\n#include \"timestamp.h\"\n#include <boost/multi_index/sequenced_index.hpp>\n\nclass Grade\n{\npublic:\n\tclass Key\n\t{\n\tprivate:\n\t\tRoster const& roster_;\n\t\tstd::string grader_email_;\n\t\tstd::string student_name_;\n\n\tprivate:\n\t\tfriend bool operator==(const Key lhs, const Key rhs)\n\t\t{\n\t\t\tconst auto result{ lhs.grader_email_ == rhs.grader_email_ && lhs.student_name_ == rhs.student_name_ };\n\t\t\treturn result;\n\t\t}\n\n\tpublic:\n\t\texplicit Key(Roster const& roster);\n\n\t\tstd::string getGraderEmail() const\n\t\t{\n\t\t\tExpects(!grader_email_.empty() && roster_.is_email_good(grader_email_));\n\t\t\treturn grader_email_;\n\t\t}\n\n\t\tvoid setGraderEmail(const std::string grader_email)\n\t\t{\n\t\t\tExpects(!grader_email.empty() && roster_.is_email_good(grader_email));\n\t\t\tgrader_email_ = grader_email;\n\t\t}\n\n\t\tstd::string getStudentName() const\n\t\t{\n\t\t\tExpects(!student_name_.empty());\n\t\t\treturn student_name_;\n\t\t}\n\n\t\tvoid setStudentName(const std::string student_name)\n\t\t{\n\t\t\tExpects(!student_name.empty());\n\t\t\tstudent_name_ = student_name;\n\t\t}\n\n        bool is_good() const;\n\t};\n\nprivate:\n    Roster const& roster_;\n\tKey key_;\n\tTimestamp timestamp_{};\n\tunsigned score_{ 0 };\n\npublic:\n\tbool is_good() const;\n\n\tKey getKey() const\n\t{\n\t\treturn key_;\n\t}\n\n\tTimestamp getTimestamp() const\n\t{\n\t\treturn timestamp_;\n\t}\n\n\tunsigned getScore() const\n\t{\n\t\treturn score_;\n\t}\n\nprivate:\n\tvoid setTimestamp(const Timestamp timestamp)\n\t{\n\t\tExpects(timestamp.is_good());\n\t\ttimestamp_ = timestamp;\n\t}\n\n\tfriend std::istream& operator>>(std::istream& is, Grade& grade)\n\t{\n\t\tTimestamp timestamp;\n\n\t\tis >> timestamp;\n\t\tEnsures(timestamp.is_good());\n\t\tgrade.setTimestamp(timestamp);\n\t\t\n\t\tchar grader_email_cstr[256]{};\n\t\tconstexpr auto max_grader_len{ std::extent<decltype(grader_email_cstr)>::value };\n\t\tis.getline(grader_email_cstr, max_grader_len, ',');\n\t\tauto const grader_len{ strlen(grader_email_cstr) };\n\t\tEnsures(grader_len > 0 && grader_len < max_grader_len);\n\n\t\tgrade.key_.setGraderEmail(grader_email_cstr);\n\n\t\tis.ignore(std::numeric_limits<std::streamsize>::max(), ',');\n\n\t\tchar student_name_cstr[256]{};\n\t\tconstexpr auto max_student_name_len{ std::extent<decltype(student_name_cstr)>::value };\n\t\tis.getline(student_name_cstr, max_student_name_len, ',');\n\t\tauto const student_len{ strlen(student_name_cstr) };\n\t\tEnsures(student_len > 0 && student_len < max_student_name_len);\n\n\t\tgrade.key_.setStudentName(student_name_cstr);\n\n\t\tEnsures(grade.is_good());\n\n\t\tis.seekg(-2, std::ios_base::end);\n\n\t\tauto const is_comma{ is.peek()==',' };\n\n\t\tif (is_comma)\n\t\t{\n\t\t\tis.ignore();\n\t\t}\n\n\t\tauto grade_value{ std::numeric_limits<int>::max() };\n\n\t\tis >> grade_value;\n\n\t\tEnsures(grade_value >= 0 && grade_value<(10+1) && is.eof());\n\n\t\tgrade.score_ = 10 * grade_value;\n\n\t\tEnsures(grade.score_ >= 0 && grade.score_ < (100+1));\n\n\t\treturn is;\n\t}\n\npublic:\n\texplicit Grade(Roster const& roster);\n};\n\n", "meta": {"hexsha": "9be8018ecbd3dc25662204aa25d89df931283bd1", "size": 2930, "ext": "h", "lang": "C", "max_stars_repo_path": "SRSGrade/grade.h", "max_stars_repo_name": "labermt/SRSGrade", "max_stars_repo_head_hexsha": "2e5f274dbaba950a9ec406b77544be2ca210a8ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SRSGrade/grade.h", "max_issues_repo_name": "labermt/SRSGrade", "max_issues_repo_head_hexsha": "2e5f274dbaba950a9ec406b77544be2ca210a8ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SRSGrade/grade.h", "max_forks_repo_name": "labermt/SRSGrade", "max_forks_repo_head_hexsha": "2e5f274dbaba950a9ec406b77544be2ca210a8ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.6338028169, "max_line_length": 105, "alphanum_fraction": 0.7010238908, "num_tokens": 808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22815649166448126, "lm_q2_score": 0.02843603088352899, "lm_q1q2_score": 0.006487865043248814}}
{"text": "/* vector/gsl_vector_complex_double.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_VECTOR_COMPLEX_DOUBLE_H__\n#define __GSL_VECTOR_COMPLEX_DOUBLE_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_complex.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_vector_double.h>\n#include <gsl/gsl_vector_complex.h>\n#include <gsl/gsl_block_complex_double.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size;\n  size_t stride;\n  double *data;\n  gsl_block_complex *block;\n  int owner;\n} gsl_vector_complex;\n\ntypedef struct\n{\n  gsl_vector_complex vector;\n} _gsl_vector_complex_view;\n\ntypedef _gsl_vector_complex_view gsl_vector_complex_view;\n\ntypedef struct\n{\n  gsl_vector_complex vector;\n} _gsl_vector_complex_const_view;\n\ntypedef const _gsl_vector_complex_const_view gsl_vector_complex_const_view;\n\n/* Allocation */\n\ngsl_vector_complex *gsl_vector_complex_alloc (const size_t n);\ngsl_vector_complex *gsl_vector_complex_calloc (const size_t n);\n\ngsl_vector_complex *\ngsl_vector_complex_alloc_from_block (gsl_block_complex * b, \n                                           const size_t offset, \n                                           const size_t n, \n                                           const size_t stride);\n\ngsl_vector_complex *\ngsl_vector_complex_alloc_from_vector (gsl_vector_complex * v, \n                                             const size_t offset, \n                                             const size_t n, \n                                             const size_t stride);\n\nvoid gsl_vector_complex_free (gsl_vector_complex * v);\n\n/* Views */\n\n_gsl_vector_complex_view\ngsl_vector_complex_view_array (double *base,\n                                     size_t n);\n\n_gsl_vector_complex_view\ngsl_vector_complex_view_array_with_stride (double *base,\n                                                 size_t stride,\n                                                 size_t n);\n\n_gsl_vector_complex_const_view\ngsl_vector_complex_const_view_array (const double *base,\n                                           size_t n);\n\n_gsl_vector_complex_const_view\ngsl_vector_complex_const_view_array_with_stride (const double *base,\n                                                       size_t stride,\n                                                       size_t n);\n\n_gsl_vector_complex_view\ngsl_vector_complex_subvector (gsl_vector_complex *base,\n                                         size_t i, \n                                         size_t n);\n\n\n_gsl_vector_complex_view \ngsl_vector_complex_subvector_with_stride (gsl_vector_complex *v, \n                                                size_t i, \n                                                size_t stride, \n                                                size_t n);\n\n_gsl_vector_complex_const_view\ngsl_vector_complex_const_subvector (const gsl_vector_complex *base,\n                                               size_t i, \n                                               size_t n);\n\n\n_gsl_vector_complex_const_view \ngsl_vector_complex_const_subvector_with_stride (const gsl_vector_complex *v, \n                                                      size_t i, \n                                                      size_t stride, \n                                                      size_t n);\n\n_gsl_vector_view\ngsl_vector_complex_real (gsl_vector_complex *v);\n\n_gsl_vector_view \ngsl_vector_complex_imag (gsl_vector_complex *v);\n\n_gsl_vector_const_view\ngsl_vector_complex_const_real (const gsl_vector_complex *v);\n\n_gsl_vector_const_view \ngsl_vector_complex_const_imag (const gsl_vector_complex *v);\n\n\n/* Operations */\n\ngsl_complex \ngsl_vector_complex_get (const gsl_vector_complex * v, const size_t i);\n\nvoid gsl_vector_complex_set (gsl_vector_complex * v, const size_t i,\n                                   gsl_complex z);\n\ngsl_complex \n*gsl_vector_complex_ptr (gsl_vector_complex * v, const size_t i);\n\nconst gsl_complex \n*gsl_vector_complex_const_ptr (const gsl_vector_complex * v, const size_t i);\n\nvoid gsl_vector_complex_set_zero (gsl_vector_complex * v);\nvoid gsl_vector_complex_set_all (gsl_vector_complex * v,\n                                       gsl_complex z);\nint gsl_vector_complex_set_basis (gsl_vector_complex * v, size_t i);\n\nint gsl_vector_complex_fread (FILE * stream,\n                                    gsl_vector_complex * v);\nint gsl_vector_complex_fwrite (FILE * stream,\n                                     const gsl_vector_complex * v);\nint gsl_vector_complex_fscanf (FILE * stream,\n                                     gsl_vector_complex * v);\nint gsl_vector_complex_fprintf (FILE * stream,\n                                      const gsl_vector_complex * v,\n                                      const char *format);\n\nint gsl_vector_complex_memcpy (gsl_vector_complex * dest, const gsl_vector_complex * src);\n\nint gsl_vector_complex_reverse (gsl_vector_complex * v);\n\nint gsl_vector_complex_swap (gsl_vector_complex * v, gsl_vector_complex * w);\nint gsl_vector_complex_swap_elements (gsl_vector_complex * v, const size_t i, const size_t j);\n\nint gsl_vector_complex_isnull (const gsl_vector_complex * v);\nint gsl_vector_complex_ispos (const gsl_vector_complex * v);\nint gsl_vector_complex_isneg (const gsl_vector_complex * v);\n\n#ifdef HAVE_INLINE\n\nextern inline\ngsl_complex\ngsl_vector_complex_get (const gsl_vector_complex * v,\n                              const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      gsl_complex zero = {{0, 0}};\n      GSL_ERROR_VAL (\"index out of range\", GSL_EINVAL, zero);\n    }\n#endif\n  return *GSL_COMPLEX_AT (v, i);\n}\n\nextern inline\nvoid\ngsl_vector_complex_set (gsl_vector_complex * v,\n                              const size_t i, gsl_complex z)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_VOID (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  *GSL_COMPLEX_AT (v, i) = z;\n}\n\nextern inline\ngsl_complex *\ngsl_vector_complex_ptr (gsl_vector_complex * v,\n                              const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return GSL_COMPLEX_AT (v, i);\n}\n\nextern inline\nconst gsl_complex *\ngsl_vector_complex_const_ptr (const gsl_vector_complex * v,\n                                    const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return GSL_COMPLEX_AT (v, i);\n}\n\n\n#endif /* HAVE_INLINE */\n\n__END_DECLS\n\n#endif /* __GSL_VECTOR_COMPLEX_DOUBLE_H__ */\n", "meta": {"hexsha": "ec7cf731dea8b97e8c5c3df0de1052f8e4d8426b", "size": 7518, "ext": "h", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/vector/gsl_vector_complex_double.h", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/vector/gsl_vector_complex_double.h", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/vector/gsl_vector_complex_double.h", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 30.314516129, "max_line_length": 94, "alphanum_fraction": 0.6366054802, "num_tokens": 1594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3040416749665474, "lm_q2_score": 0.02128734985311502, "lm_q1q2_score": 0.006472241504939977}}
{"text": "/*\nCopyright (c) 2015, Patrick Weltevrede\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <gsl/gsl_sort_float.h>\n#include <gsl/gsl_statistics_float.h>\n#include <gsl/gsl_integration.h>\n#include \"psrsalsa.h\"\nint filterPApoints(datafile_definition *datafile, verbose_definition verbose)\n{\n  int dPa_polnr;\n  long i, j, nrpoints;\n  float *olddata;\n  if(datafile->poltype != POLTYPE_ILVPAdPA && datafile->poltype != POLTYPE_PAdPA && datafile->poltype != POLTYPE_ILVPAdPATEldEl) {\n    printerror(verbose.debug, \"ERROR filterPApoints: Data doesn't appear to have poltype ILVPAdPA, PAdPA or ILVPAdPATEldEl.\");\n    return -1;\n  }\n  if(datafile->poltype == POLTYPE_ILVPAdPA && datafile->NrPols != 5) {\n    printerror(verbose.debug, \"ERROR filterPApoints: 5 polarization channels were expected, but there are only %ld.\", datafile->NrPols);\n    return -1;\n  }else if(datafile->poltype == POLTYPE_ILVPAdPATEldEl && datafile->NrPols != 8) {\n    printerror(verbose.debug, \"ERROR filterPApoints: 8 polarization channels were expected, but there are only %ld.\", datafile->NrPols);\n    return -1;\n  }else if(datafile->poltype == POLTYPE_PAdPA && datafile->NrPols != 2) {\n    printerror(verbose.debug, \"ERROR filterPApoints: 2 polarization channels were expected, but there are only %ld.\", datafile->NrPols);\n    return -1;\n  }\n  if(datafile->NrSubints > 1 || datafile->NrFreqChan > 1) {\n    printerror(verbose.debug, \"ERROR filterPApoints: Can only do this opperation if there is one subint and one frequency channel.\");\n    return -1;\n  }\n  if(datafile->tsampMode != TSAMPMODE_LONGITUDELIST) {\n    printerror(verbose.debug, \"ERROR filterPApoints: Expected pulse longitudes to be defined.\");\n    return -1;\n  }\n  if(datafile->poltype == POLTYPE_ILVPAdPA || datafile->poltype == POLTYPE_ILVPAdPATEldEl) {\n    dPa_polnr = 4;\n  }else if(datafile->poltype == POLTYPE_PAdPA) {\n    dPa_polnr = 1;\n  }\n  nrpoints = 0;\n  for(i = 0; i < datafile->NrBins; i++) {\n    if(datafile->data[i+dPa_polnr*datafile->NrBins] > 0 && isfinite(datafile->data[i+dPa_polnr*datafile->NrBins])) {\n      nrpoints++;\n    }\n  }\n  if(verbose.verbose)\n    printf(\"Keeping %ld significant PA points\\n\", nrpoints);\n  olddata = datafile->data;\n  datafile->data = (float *)malloc(nrpoints*datafile->NrPols*sizeof(float));\n  if(datafile->data == NULL) {\n    printerror(verbose.debug, \"ERROR filterPApoints: Memory allocation error.\");\n    return -1;\n  }\n  j = 0;\n  for(i = 0; i < datafile->NrBins; i++) {\n    if(olddata[i+dPa_polnr*datafile->NrBins] > 0 && isfinite(olddata[i+dPa_polnr*datafile->NrBins])) {\n      if(datafile->poltype == POLTYPE_ILVPAdPA) {\n datafile->data[j+0*nrpoints] = olddata[i+0*datafile->NrBins];\n datafile->data[j+1*nrpoints] = olddata[i+1*datafile->NrBins];\n datafile->data[j+2*nrpoints] = olddata[i+2*datafile->NrBins];\n datafile->data[j+3*nrpoints] = olddata[i+3*datafile->NrBins];\n datafile->data[j+4*nrpoints] = olddata[i+4*datafile->NrBins];\n      }else if(datafile->poltype == POLTYPE_ILVPAdPATEldEl) {\n datafile->data[j+0*nrpoints] = olddata[i+0*datafile->NrBins];\n datafile->data[j+1*nrpoints] = olddata[i+1*datafile->NrBins];\n datafile->data[j+2*nrpoints] = olddata[i+2*datafile->NrBins];\n datafile->data[j+3*nrpoints] = olddata[i+3*datafile->NrBins];\n datafile->data[j+4*nrpoints] = olddata[i+4*datafile->NrBins];\n datafile->data[j+5*nrpoints] = olddata[i+5*datafile->NrBins];\n datafile->data[j+6*nrpoints] = olddata[i+6*datafile->NrBins];\n datafile->data[j+7*nrpoints] = olddata[i+7*datafile->NrBins];\n      }else {\n datafile->data[j+0*nrpoints] = olddata[i+0*datafile->NrBins];\n datafile->data[j+1*nrpoints] = olddata[i+1*datafile->NrBins];\n      }\n      datafile->tsamp_list[j] = datafile->tsamp_list[i];\n      j++;\n    }\n  }\n  free(olddata);\n  datafile->NrBins = nrpoints;\n  return datafile->NrBins;\n}\nint make_paswing_fromIQUV_remove_lowS2N_points_sp_isLsignificant(float sigma_limit, int sigmaI, float dataL, float rmsI, float rmsL, verbose_definition verbose)\n{\n  if(sigmaI == 0) {\n    if(dataL < sigma_limit*rmsL) {\n      return 0;\n    }\n    return 1;\n  }else {\n    if(dataL < sigma_limit*rmsI) {\n      return 0;\n    }\n    return 1;\n  }\n}\nint make_paswing_fromIQUV_remove_lowS2N_points_sp_isPsignificant(float sigma_limit, int sigmaI, float dataP, float rmsI, float rmsP, verbose_definition verbose)\n{\n  if(sigmaI == 0) {\n    if(dataP < sigma_limit*rmsP) {\n      return 0;\n    }\n    return 1;\n  }else {\n    if(dataP < sigma_limit*rmsI) {\n      return 0;\n    }\n    return 1;\n  }\n}\nint make_paswing_fromIQUV_remove_lowS2N_points_sp_isVsignificant(float sigma_limit, int sigmaI, float dataV, float rmsI, float rmsV, verbose_definition verbose)\n{\n  if(sigmaI == 0) {\n    if(fabs(dataV) < sigma_limit*rmsV) {\n      return 0;\n    }\n    return 1;\n  }else {\n    if(fabs(dataV) < sigma_limit*rmsI) {\n      return 0;\n    }\n    return 1;\n  }\n}\nvoid make_paswing_fromIQUV_remove_lowS2N_points_sp(float sigma_limit, int sigmaI, int nrBins, float *dataL, float *dataP, float *dataPA, float *dataPaErr, float *dataEll, float *dataEllErr, float rmsI, float rmsL, float rmsP, pulselongitude_regions_definition *onpulse, verbose_definition verbose)\n{\n  long j;\n  if(sigma_limit < 0) {\n    return;\n  }\n  for(j = 0; j < nrBins; j++) {\n    int issignificant;\n    issignificant = 1;\n    if(onpulse != NULL) {\n      if(checkRegions(j, onpulse, 0, verbose) == 0) {\n issignificant = 0;\n      }\n    }\n    if(dataL != NULL && (dataPA != NULL || dataPaErr != NULL)) {\n      if(issignificant == 0 || make_paswing_fromIQUV_remove_lowS2N_points_sp_isLsignificant(sigma_limit, sigmaI, dataL[j], rmsI, rmsL, verbose) == 0) {\n if(dataPA != NULL) {\n   dataPA[j] = 0;\n }\n if(dataPaErr != NULL) {\n   dataPaErr[j] = -1;\n }\n      }\n    }\n    if(dataP != NULL && (dataEll != NULL || dataEllErr != NULL)) {\n      if(issignificant == 0 || make_paswing_fromIQUV_remove_lowS2N_points_sp_isPsignificant(sigma_limit, sigmaI, dataP[j], rmsI, rmsP, verbose) == 0) {\n if(dataEll != NULL) {\n   dataEll[j] = 0;\n }\n if(dataEllErr != NULL) {\n   dataEllErr[j] = -1;\n }\n      }\n    }\n  }\n}\nint make_paswing_fromIQUV_sp(float *dataI, float *dataQ, float *dataU, float *dataV, int nrBins, float *dataL, float *dataP, float *dataPA, float *dataPaErr, float *dataEll, float *dataEllErr, float *baseline_intensity, float *rmsI, float *rmsQ, float *rmsU, float *rmsV, float *rmsL, float *rmsP, float *medianL, float *medianP, pulselongitude_regions_definition onpulse, int normalize, int correctLbias, int correctPbias, float correctQV, float correctV, float paoffset, int rms_file_nrBins, float *rms_file_I, float *rms_file_Q, float *rms_file_U, float *rms_file_V, float rebin_factor, verbose_definition verbose)\n{\n  int rms_file_specified;\n  float *Loffpulse, *Poffpulse, median_L, median_P;\n  double ymax, avrgI, RMSI, RMSQ, RMSU, RMSV, RMSL, RMSP;\n  long i, nrOffpulseBins;\n  rms_file_specified = 1;\n  if(rms_file_I == NULL) {\n    rms_file_I = dataI;\n    rms_file_Q = dataQ;\n    rms_file_U = dataU;\n    rms_file_V = dataV;\n    rms_file_nrBins = nrBins;\n    rms_file_specified = 0;\n  }\n  Loffpulse = (float *)malloc(rms_file_nrBins*sizeof(float));\n  Poffpulse = (float *)malloc(rms_file_nrBins*sizeof(float));\n  if(Loffpulse == NULL || Poffpulse == NULL) {\n    fflush(stdout);\n    printerror(verbose.debug, \"ERROR make_paswing_fromIQUV_sp: Memory allocation error.\");\n    return 0;\n  }\n  if(normalize == 0) {\n    ymax = 1;\n  }else {\n    ymax = dataI[0];\n    for(i = 1; i < nrBins; i++) {\n      if(dataI[i] > ymax) {\n ymax = dataI[i];\n      }\n    }\n    if(ymax == 0) {\n      ymax = 1;\n    }\n  }\n  if(ymax != 1.0 || correctQV != 1.0 || correctV != 1.0) {\n    for(i = 0; i < nrBins; i++) {\n      dataI[i] /= ymax;\n      dataQ[i] /= correctQV*ymax;\n      dataU[i] /= ymax;\n      dataV[i] /= correctV*correctQV*ymax;\n    }\n    if(rms_file_specified) {\n      for(i = 0; i < rms_file_nrBins; i++) {\n rms_file_I[i] /= ymax;\n rms_file_Q[i] /= correctQV*ymax;\n rms_file_U[i] /= ymax;\n rms_file_V[i] /= correctV*correctQV*ymax;\n      }\n    }\n  }\n  nrOffpulseBins = 0;\n  avrgI = 0;\n  RMSI = 0;\n  RMSQ = 0;\n  RMSU = 0;\n  RMSV = 0;\n  RMSL = 0;\n  RMSP = 0;\n  for(i = 0; i < rms_file_nrBins; i++) {\n    if(checkRegions(i, &onpulse, 0, verbose) == 0) {\n      double sampleI2, sampleQ2, sampleU2, sampleV2;\n      avrgI += rms_file_I[i];\n      sampleI2 = rms_file_I[i]*rms_file_I[i];\n      sampleQ2 = rms_file_Q[i]*rms_file_Q[i];\n      sampleU2 = rms_file_U[i]*rms_file_U[i];\n      sampleV2 = rms_file_V[i]*rms_file_V[i];\n      RMSI += sampleI2;\n      RMSQ += sampleQ2;\n      RMSU += sampleU2;\n      RMSV += sampleV2;\n      RMSL += sampleQ2+sampleU2;\n      RMSP += sampleQ2+sampleU2+sampleV2;\n      Loffpulse[nrOffpulseBins] = sqrt(sampleQ2+sampleU2);\n      Poffpulse[nrOffpulseBins] = sqrt(sampleQ2+sampleU2+sampleV2);\n      nrOffpulseBins++;\n    }\n  }\n  avrgI /= (double)nrOffpulseBins;\n  RMSI = sqrt(RMSI/(double)nrOffpulseBins);\n  RMSQ = sqrt(RMSQ/(double)nrOffpulseBins);\n  RMSU = sqrt(RMSU/(double)nrOffpulseBins);\n  RMSV = sqrt(RMSV/(double)nrOffpulseBins);\n  RMSL = sqrt(RMSL/(double)nrOffpulseBins);\n  RMSP = sqrt(RMSP/(double)nrOffpulseBins);\n  if(rms_file_specified) {\n    double scale = 1.0/sqrt(rebin_factor);\n    RMSI *= scale;\n    RMSQ *= scale;\n    RMSU *= scale;\n    RMSV *= scale;\n    RMSL *= scale;\n    RMSP *= scale;\n  }\n  gsl_sort_float(Loffpulse, 1, nrOffpulseBins);\n  median_L = gsl_stats_float_median_from_sorted_data(Loffpulse, 1, nrOffpulseBins);\n  gsl_sort_float(Poffpulse, 1, nrOffpulseBins);\n  median_P = gsl_stats_float_median_from_sorted_data(Poffpulse, 1, nrOffpulseBins);\n  if(baseline_intensity != NULL)\n    *baseline_intensity = avrgI;\n  if(rmsI != NULL)\n    *rmsI = RMSI;\n  if(rmsQ != NULL)\n    *rmsQ = RMSQ;\n  if(rmsU != NULL)\n    *rmsU = RMSU;\n  if(rmsV != NULL)\n    *rmsV = RMSV;\n  if(rmsL != NULL)\n    *rmsL = RMSL;\n  if(rmsP != NULL)\n    *rmsP = RMSP;\n  if(medianL != NULL)\n    *medianL = median_L;\n  if(medianP != NULL)\n    *medianP = median_P;\n  for(i = 0; i < nrBins; i++) {\n    double sampleQ2, sampleU2, sampleV2, sampleL, sampleP;\n    sampleQ2 = dataQ[i]*dataQ[i];\n    sampleU2 = dataU[i]*dataU[i];\n    sampleV2 = dataV[i]*dataV[i];\n    sampleL = sqrt(sampleQ2+sampleU2);\n    if(correctLbias == 0) {\n      sampleL -= median_L;\n    }else if(correctLbias == 1) {\n      double junk = (sqrt(0.5*(RMSQ*RMSQ+RMSU*RMSU))/sampleL);\n      if(junk < 1.0) {\n sampleL *= sqrt(1.0-junk*junk);\n      }else {\n sampleL = 0.0;\n      }\n    }\n    if(dataL != NULL) {\n      dataL[i] = sampleL;\n    }\n    sampleP = sqrt(sampleQ2+sampleU2+sampleV2);\n    if(correctPbias == 0) {\n      sampleP -= median_P;\n    }\n    if(dataP != NULL) {\n      dataP[i] = sampleP;\n    }\n    if(dataPA != NULL) {\n      dataPA[i] = 90.0*atan2(dataU[i], dataQ[i])/M_PI;\n      if(paoffset != 0.0) {\n dataPA[i] += paoffset;\n dataPA[i] = derotate_180_small_double(dataPA[i]);\n      }\n    }\n    if(dataPaErr != NULL) {\n      if(sampleQ2 == 0 && sampleU2 == 0) {\n dataPaErr[i] = 0;\n      }else {\n dataPaErr[i] = sqrt(sampleQ2*RMSU*RMSU + sampleU2*RMSQ*RMSQ);\n dataPaErr[i] /= 2.0*(sampleQ2 + sampleU2);\n dataPaErr[i] *= 180.0/M_PI;\n      }\n    }\n    if(dataEll != NULL) {\n      if(sampleQ2 == 0 && sampleU2 == 0 && sampleV2 == 0) {\n dataEll[i] = 0;\n      }\n      double value;\n      value = dataV[i]/sqrt(sampleQ2+sampleU2+sampleV2);\n      if(value < -1.0) {\n value = -1.0;\n      }else if(value > 1.0) {\n value = 1.0;\n      }\n      dataEll[i] = 90.0*asin(value)/M_PI;\n    }\n    if(dataEllErr != NULL) {\n      if(dataQ[i] == 0 && dataU[i] == 0 && dataV[i] == 0) {\n dataEllErr[i] = -1;\n      }\n      dataEllErr[i] = sampleV2*(sampleQ2*RMSQ*RMSQ+sampleU2*RMSU*RMSU);\n      dataEllErr[i] += (sampleQ2+sampleU2)*(sampleQ2+sampleU2)*RMSV*RMSV;\n      dataEllErr[i] /= 4.0*(sampleQ2+sampleU2);\n      dataEllErr[i] = sqrt(dataEllErr[i]);\n      dataEllErr[i] /= (sampleQ2+sampleU2+sampleV2);\n      dataEllErr[i] *= 180.0/M_PI;\n    }\n  }\n  free(Loffpulse);\n  free(Poffpulse);\n  return 1;\n}\nvoid make_paswing_fromIQUV_reportRMS(long pulsenr, long freqnr, int extended, int spstat, float rmsI, float rmsQ, float rmsU, float rmsV, float rmsL, float rmsP, float medianL, float medianP, float baseline_intensity, verbose_definition verbose)\n{\n  int indent;\n  if(spstat == 0) {\n    for(indent = 0; indent < verbose.indent; indent++) printf(\" \");\n    fprintf(stdout, \"  PA conversion output for subint %ld frequency channel %ld:\\n\", pulsenr, freqnr);\n  }\n  for(indent = 0; indent < verbose.indent; indent++) printf(\" \");\n  fprintf(stdout, \"    Avrg baseline Stokes I:   %f (only reported, not subtracted)\\n\", baseline_intensity);\n  for(indent = 0; indent < verbose.indent; indent++) printf(\" \");\n  fprintf(stdout, \"    RMS I:                    %f\\n\", rmsI);\n  for(indent = 0; indent < verbose.indent; indent++) printf(\" \");\n  fprintf(stdout, \"    RMS Q:                    %f\\n\", rmsQ);\n  for(indent = 0; indent < verbose.indent; indent++) printf(\" \");\n  fprintf(stdout, \"    RMS U:                    %f\\n\", rmsU);\n  for(indent = 0; indent < verbose.indent; indent++) printf(\" \");\n  fprintf(stdout, \"    RMS V:                    %f\\n\", rmsV);\n  for(indent = 0; indent < verbose.indent; indent++) printf(\" \");\n  fprintf(stdout, \"    RMS L (before de-bias):   %f\\n\", rmsL);\n  if(extended) {\n    for(indent = 0; indent < verbose.indent; indent++) printf(\" \");\n    fprintf(stdout, \"    RMS sqrt(Q^2+U^2+V^2):    %f\\n\", rmsP);\n  }\n  for(indent = 0; indent < verbose.indent; indent++) printf(\" \");\n  fprintf(stdout, \"    Median L:                 %f\\n\", medianL);\n  if(extended) {\n    for(indent = 0; indent < verbose.indent; indent++) printf(\" \");\n    fprintf(stdout, \"    Median sqrt(Q^2+U^2+V^2): %f\\n\", medianP);\n  }\n}\nint make_paswing_fromIQUV(datafile_definition *datafile, int extended, int spstat, float sigma_limit, int sigmaI, pulselongitude_regions_definition onpulse, int normalize, int correctLbias, int correctPbias, float correctQV, float correctV, int nolongitudes, float loffset, float paoffset, datafile_definition *rms_file, float rebin_factor, int onpulseonly, verbose_definition verbose)\n{\n  int indent, output_nr_pols;\n  long i, pulsenr, freqnr;\n  float *newdata, *newdata_current_pulse;\n  if(verbose.verbose) {\n    for(indent = 0; indent < verbose.indent; indent++) printf(\" \");\n    printf(\"Constructing PA and degree of linear polarization\");\n    if(extended)\n      printf(\", total polarization and ellipticity\");\n    if(rms_file != NULL)\n      printf(\" (using a seperate file to determine the off-pulse rms)\");\n    printf(\"\\n\");\n    for(indent = 0; indent < verbose.indent; indent++) printf(\" \");\n    printf(\"  Reference frequency for PA is \");\n    if(datafile->isDeFarad) {\n      if((datafile->freq_ref > -1.1 && datafile->freq_ref < -0.9) || (datafile->freq_ref > 0.99e10 && datafile->freq_ref < 1.01e10))\n printf(\"infinity\\n\");\n      else if(datafile->freq_ref < 0)\n printf(\"unknown\\n\");\n      else\n printf(\"%f MHz\\n\", datafile->freq_ref);\n    }else {\n      if(datafile->NrFreqChan == 1)\n printf(\"%lf MHz\\n\", get_centre_frequency(*datafile, verbose));\n      else\n printf(\"observing frequencies of individual frequency channels\\n\");\n    }\n    for(indent = 0; indent < verbose.indent; indent++) printf(\" \");\n    printf(\"  \");\n    switch(correctLbias) {\n    case -1: printf(\"No L de-bias applied\"); break;\n    case 0: printf(\"De-bias L using median noise subtraction\"); break;\n    case 1: printf(\"De-bias L using Wardle & Kronberg correction\"); break;\n    default: printerror(verbose.debug, \"ERROR make_paswing_fromIQUV: Undefined L de-bias method specified.\"); return 0;\n    }\n    if(extended) {\n      switch(correctPbias) {\n      case -1: printf(\", no P de-bias applied\"); break;\n      case 0: printf(\", de-bias P using median noise subtraction\"); break;\n      case 1: printf(\", de-bias P using Wardle & Kronberg like correction\"); break;\n      default: printerror(verbose.debug, \"ERROR make_paswing_fromIQUV: Undefined P de-bias method specified.\"); return 0;\n      }\n    }\n    if(correctQV != 1 || correctV != 1)\n      printf(\", Q correction factor %f, V correction factor %f\", 1.0/correctQV, 1.0/(correctQV*correctV));\n    if(normalize)\n      printf(\", output is normalised\");\n    if(loffset != 0)\n      printf(\", pulse longitude shifted by %f deg\\n\", loffset);\n    if(paoffset != 0)\n      printf(\", PA shifted by %f deg\\n\", paoffset);\n    printf(\"\\n\");\n  }\n  if(datafile->NrPols != 4) {\n    fflush(stdout);\n    printerror(verbose.debug, \"ERROR make_paswing_fromIQUV: Expected 4 input polarizations.\");\n    return 0;\n  }\n  if(rms_file != NULL) {\n    if(rms_file->NrPols != 4) {\n      fflush(stdout);\n      printerror(verbose.debug, \"ERROR make_paswing_fromIQUV: Expected 4 input polarizations.\");\n      return 0;\n    }\n  }\n  if(datafile->poltype != POLTYPE_STOKES) {\n    if(datafile->poltype == POLTYPE_UNKNOWN) {\n      printwarning(verbose.debug, \"WARNING make_paswing_fromIQUV: Polarization state unknown, it is assumed the data are Stokes parameters.\");\n    }else {\n      printerror(verbose.debug, \"ERROR make_paswing_fromIQUV: Please convert data into Stokes parameters first.\");\n      return 0;\n    }\n  }\n  if(rms_file != NULL) {\n    if(rms_file->poltype != POLTYPE_STOKES) {\n      if(rms_file->poltype == POLTYPE_UNKNOWN) {\n printwarning(verbose.debug, \"WARNING make_paswing_fromIQUV: Polarization state of the data to be used to determine the off-pulse rms is unknown. It is assumed the data are Stokes parameters.\");\n      }else {\n printerror(verbose.debug, \"ERROR make_paswing_fromIQUV: Please convert data to be used to determine the off-pulse rms into Stokes parameters first.\");\n return 0;\n      }\n    }\n  }\n  if(datafile->tsampMode != TSAMPMODE_FIXEDTSAMP) {\n    fflush(stdout);\n    printerror(verbose.debug, \"ERROR make_paswing_fromIQUV: It is expected that the input has a uniform time sampling.\");\n    return 0;\n  }\n  if(correctQV == 0) {\n    fflush(stdout);\n    printerror(verbose.debug, \"ERROR make_paswing_fromIQUV: correctQV is set to zero, you probably want this to be 1.\");\n    return 0;\n  }\n  if(correctV == 0) {\n    fflush(stdout);\n    printerror(verbose.debug, \"ERROR make_paswing_fromIQUV: correctV is set to zero, you probably want this to be 1.\");\n    return 0;\n  }\n  if(datafile->isDebase == 0) {\n    fflush(stdout);\n    printerror(verbose.debug, \"ERROR make_paswing_fromIQUV: Please remove baseline first, i.e. use pmod -debase.\");\n    return 0;\n  }else if(datafile->isDebase != 1) {\n    fflush(stdout);\n    printwarning(verbose.debug, \"WARNING make_paswing_fromIQUV: Unknown baseline removal state. It will be assumed the baseline has already removed from the data.\");\n  }\n  if(rms_file != NULL) {\n    if(rms_file->isDebase == 0) {\n      fflush(stdout);\n      printerror(verbose.debug, \"ERROR make_paswing_fromIQUV: Please remove baseline first, i.e. use pmod -debase.\");\n      return 0;\n    }else if(rms_file->isDebase != 1) {\n      fflush(stdout);\n      printwarning(verbose.debug, \"WARNING make_paswing_fromIQUV: Unknown baseline removal state. It is assumed the baseline has already removed from the data.\");\n    }\n    if(datafile->NrSubints != rms_file->NrSubints) {\n      printerror(verbose.debug, \"ERROR make_paswing_fromIQUV: Number of subintegrations is different in the data to be used to determine the off-pulse rms compared to the data used to compute the polarization information.\");\n return 0;\n    }\n    if(datafile->NrFreqChan != rms_file->NrFreqChan) {\n      printerror(verbose.debug, \"ERROR make_paswing_fromIQUV: Number of frequency channels is different in the data to be used to determine the off-pulse rms compared to the data used to compute the polarization information (%ld != %ld).\", rms_file->NrFreqChan, datafile->NrFreqChan);\n return 0;\n    }\n    if(correctLbias == 0) {\n      printerror(verbose.debug, \"ERROR make_paswing_fromIQUV: Subtracting the median of L is not supported when a separate file is used for the off-pulse statistics.\");\n      return 0;\n    }\n    if(extended && correctPbias == 0) {\n      printerror(verbose.debug, \"ERROR make_paswing_fromIQUV: Subtracting the median of P is not supported when a separate file is used for the off-pulse statistics.\");\n      return 0;\n    }\n  }\n  if(normalize && (datafile->NrSubints > 1 || datafile->NrFreqChan > 1)) {\n    if(spstat == 0) {\n      fflush(stdout);\n      printwarning(verbose.debug, \"WARNING make_paswing_fromIQUV: Normalization of the polarization information will cause all subintegrations/frequency channels to be normalised individually. This may not be desired.\");\n    }\n  }\n  if(extended) {\n    output_nr_pols = 8;\n  }else {\n    output_nr_pols = 5;\n  }\n  if(spstat == 0) {\n    newdata = (float *)malloc(datafile->NrBins*datafile->NrSubints*datafile->NrFreqChan*output_nr_pols*sizeof(float));\n  }else {\n    newdata = (float *)malloc(datafile->NrBins*output_nr_pols*sizeof(float));\n    newdata_current_pulse = (float *)malloc(datafile->NrBins*output_nr_pols*sizeof(float));\n  }\n  if(datafile->offpulse_rms != NULL) {\n    free(datafile->offpulse_rms);\n  }\n  if(spstat == 0) {\n    datafile->offpulse_rms = (float *)malloc(datafile->NrSubints*datafile->NrFreqChan*output_nr_pols*sizeof(float));\n  }else {\n    datafile->offpulse_rms = (float *)malloc(output_nr_pols*sizeof(float));\n  }\n  if(newdata == NULL || datafile->offpulse_rms == NULL\n     ) {\n    fflush(stdout);\n    printerror(verbose.debug, \"ERROR make_paswing_fromIQUV: Memory allocation error.\");\n    return 0;\n  }\n  if(nolongitudes == 0) {\n    datafile->tsamp_list = (double *)malloc(datafile->NrBins*sizeof(double));\n    if(datafile->tsamp_list == NULL) {\n      fflush(stdout);\n      printerror(verbose.debug, \"ERROR make_paswing_fromIQUV: Memory allocation error.\");\n      return 0;\n    }\n    for(i = 0; i < datafile->NrBins; i++) {\n      datafile->tsamp_list[i] = get_pulse_longitude(*datafile, 0, i, verbose);\n      datafile->tsamp_list[i] += loffset;\n    }\n  }\n  float *dataI, *dataQ, *dataU, *dataV, *newdataL, *newdataP, *newdataPa, *newdataPaErr, *newdataEll, *newdataEllErr;\n  float baseline_intensity, rmsI, rmsQ, rmsU, rmsV, rmsL, rmsP, medianL, medianP;\n  for(pulsenr = 0; pulsenr < datafile->NrSubints; pulsenr++) {\n    for(freqnr = 0; freqnr < datafile->NrFreqChan; freqnr++) {\n      int normalize_sp;\n      dataI = &(datafile->data[datafile->NrBins*(0+datafile->NrPols*(freqnr+pulsenr*datafile->NrFreqChan))]);\n      dataQ = &(datafile->data[datafile->NrBins*(1+datafile->NrPols*(freqnr+pulsenr*datafile->NrFreqChan))]);\n      dataU = &(datafile->data[datafile->NrBins*(2+datafile->NrPols*(freqnr+pulsenr*datafile->NrFreqChan))]);\n      dataV = &(datafile->data[datafile->NrBins*(3+datafile->NrPols*(freqnr+pulsenr*datafile->NrFreqChan))]);\n      if(spstat == 0) {\n newdataL = &(newdata[datafile->NrBins*(1+output_nr_pols*(freqnr+datafile->NrFreqChan*pulsenr))]);\n newdataPa = &(newdata[datafile->NrBins*(3+output_nr_pols*(freqnr+datafile->NrFreqChan*pulsenr))]);\n newdataPaErr = &(newdata[datafile->NrBins*(4+output_nr_pols*(freqnr+datafile->NrFreqChan*pulsenr))]);\n normalize_sp = normalize;\n      }else {\n newdataL = &(newdata_current_pulse[datafile->NrBins*1]);\n newdataPa = NULL;\n newdataPaErr = NULL;\n normalize_sp = 0;\n      }\n      if(extended == 0) {\n newdataP = NULL;\n newdataEll = NULL;\n newdataEllErr = NULL;\n      }else {\n if(spstat == 0) {\n   newdataP = &(newdata[datafile->NrBins*(5+output_nr_pols*(freqnr+datafile->NrFreqChan*pulsenr))]);\n   newdataEll = &(newdata[datafile->NrBins*(6+output_nr_pols*(freqnr+datafile->NrFreqChan*pulsenr))]);\n   newdataEllErr = &(newdata[datafile->NrBins*(7+output_nr_pols*(freqnr+datafile->NrFreqChan*pulsenr))]);\n }else {\n   newdataP = &(newdata_current_pulse[datafile->NrBins*5]);\n   newdataEll = NULL;\n   newdataEllErr = NULL;\n }\n      }\n      long rms_file_nrBins;\n      float *rms_file_I, *rms_file_Q, *rms_file_U, *rms_file_V;\n      if(rms_file != NULL) {\n rms_file_nrBins = rms_file->NrBins;\n rms_file_I = &(rms_file->data[rms_file->NrBins*(0+rms_file->NrPols*(freqnr+pulsenr*rms_file->NrFreqChan))]);\n rms_file_Q = &(rms_file->data[rms_file->NrBins*(1+rms_file->NrPols*(freqnr+pulsenr*rms_file->NrFreqChan))]);\n rms_file_U = &(rms_file->data[rms_file->NrBins*(2+rms_file->NrPols*(freqnr+pulsenr*rms_file->NrFreqChan))]);\n rms_file_V = &(rms_file->data[rms_file->NrBins*(3+rms_file->NrPols*(freqnr+pulsenr*rms_file->NrFreqChan))]);\n      }else {\n rms_file_nrBins = 0;\n rms_file_I = NULL;\n rms_file_Q = NULL;\n rms_file_U = NULL;\n rms_file_V = NULL;\n      }\n      if(make_paswing_fromIQUV_sp(dataI, dataQ, dataU, dataV, datafile->NrBins, newdataL, newdataP, newdataPa, newdataPaErr, newdataEll, newdataEllErr, &baseline_intensity, &rmsI, &rmsQ, &rmsU, &rmsV, &rmsL, &rmsP, &medianL, &medianP, onpulse, normalize_sp, correctLbias, correctPbias, correctQV, correctV, paoffset, rms_file_nrBins, rms_file_I, rms_file_Q, rms_file_U, rms_file_V, rebin_factor, verbose) == 0) {\n printerror(verbose.debug, \"ERROR make_paswing_fromIQUV: Calculating polarization products failed.\");\n return 0;\n      }\n      pulselongitude_regions_definition *onpulse_ptr;\n      onpulse_ptr = NULL;\n      if(onpulseonly) {\n onpulse_ptr = &onpulse;\n      }\n      make_paswing_fromIQUV_remove_lowS2N_points_sp(sigma_limit, sigmaI, datafile->NrBins, newdataL, newdataP, newdataPa, newdataPaErr, newdataEll, newdataEllErr, rmsI, rmsL, rmsP, onpulse_ptr, verbose);\n      if(spstat == 0) {\n for(i = 0; i < datafile->NrBins; i++) {\n   newdata[datafile->NrBins*(0+output_nr_pols*(freqnr+datafile->NrFreqChan*pulsenr))+i] = dataI[i];\n   newdata[datafile->NrBins*(2+output_nr_pols*(freqnr+datafile->NrFreqChan*pulsenr))+i] = dataV[i];\n        }\n datafile->offpulse_rms[0+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] = rmsI;\n datafile->offpulse_rms[1+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] = rmsL;\n datafile->offpulse_rms[2+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] = rmsV;\n datafile->offpulse_rms[3+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] = -1;\n datafile->offpulse_rms[4+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] = -1;\n if(extended) {\n   datafile->offpulse_rms[5+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] = rmsP;\n   datafile->offpulse_rms[6+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] = -1;\n   datafile->offpulse_rms[7+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] = -1;\n }\n      }\n      if(verbose.verbose) {\n if(spstat == 0 && ((freqnr == 0 && pulsenr == 0) || verbose.debug)) {\n   if(datafile->NrFreqChan > 1 || datafile->NrSubints > 1) {\n     for(indent = 0; indent < verbose.indent; indent++) printf(\" \");\n     fprintf(stdout, \"    Statistics based on first processed pulse\\n\");\n   }\n   if(extended) {\n     make_paswing_fromIQUV_reportRMS(pulsenr, freqnr, extended, spstat, datafile->offpulse_rms[0+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)], rmsQ, rmsU, datafile->offpulse_rms[2+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)], datafile->offpulse_rms[1+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)], datafile->offpulse_rms[5+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)], medianL, medianP, baseline_intensity, verbose);\n   }else {\n     make_paswing_fromIQUV_reportRMS(pulsenr, freqnr, extended, spstat, datafile->offpulse_rms[0+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)], rmsQ, rmsU, datafile->offpulse_rms[2+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)], datafile->offpulse_rms[1+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)], 0.0, medianL, 0.0, baseline_intensity, verbose);\n   }\n }\n      }\n    }\n  }\n  free(datafile->data);\n  datafile->data = newdata;\n  if(nolongitudes == 0) {\n    datafile->tsampMode = TSAMPMODE_LONGITUDELIST;\n  }\n  datafile->NrPols = output_nr_pols;\n  if(extended) {\n    datafile->poltype = POLTYPE_ILVPAdPATEldEl;\n  }else {\n    datafile->poltype = POLTYPE_ILVPAdPA;\n  }\n  return 1;\n}\nvoid paswing_remove_observed_PA_swing_sp(float *dataPA, float *dataPAerr, float *dataPAref, float *dataPArefErr, int nrBins, int add, verbose_definition verbose)\n{\n  int ok;\n  long j;\n  for(j = 0; j < nrBins; j++) {\n    ok = 1;\n    if(dataPAerr != NULL) {\n      if(dataPAerr[j] < 0) {\n ok = 0;\n      }\n    }\n    if(dataPArefErr != NULL) {\n      if(dataPArefErr[j] < 0) {\n ok = 0;\n dataPA[j] = 0;\n if(dataPAerr != NULL) {\n   dataPAerr[j] = -1;\n }\n      }\n    }\n    if(ok) {\n      if(add) {\n dataPA[j] += dataPAref[j];\n      }else {\n dataPA[j] -= dataPAref[j];\n      }\n      dataPA[j] = derotate_180(dataPA[j]) - 90;\n      if(dataPAerr != NULL && dataPArefErr != NULL) {\n dataPAerr[j] = sqrt(dataPAerr[j]*dataPAerr[j]+dataPArefErr[j]*dataPArefErr[j]);\n      }\n    }else {\n      dataPA[j] = 0;\n      if(dataPAerr != NULL) {\n dataPAerr[j] = -1;\n      }\n    }\n  }\n}\nint paswing_remove_observed_PA_swing(datafile_definition *datafile, datafile_definition datafile_reference, int add, verbose_definition verbose)\n{\n  int pachannel_ref, pachannelerr_ref, pachannel, pachannelerr;\n  if(datafile->poltype != POLTYPE_ILVPAdPA && datafile->poltype != POLTYPE_PAdPA && datafile->poltype != POLTYPE_ILVPAdPATEldEl) {\n    printerror(verbose.debug, \"ERROR paswing_remove_observed_PA_swing: Data doesn't appear to have poltype ILVPAdPA, PAdPA or ILVPAdPATEldEl.\");\n    return 0;\n  }\n  if(datafile_reference.poltype != POLTYPE_ILVPAdPA && datafile_reference.poltype != POLTYPE_PAdPA && datafile_reference.poltype != POLTYPE_ILVPAdPATEldEl) {\n    printerror(verbose.debug, \"ERROR paswing_remove_observed_PA_swing: Data in the reference doesn't appear to have poltype ILVPAdPA, PAdPA or ILVPAdPATEldEl.\");\n    return 0;\n  }\n  if(datafile->poltype == POLTYPE_ILVPAdPA && datafile->NrPols != 5) {\n    printerror(verbose.debug, \"ERROR paswing_remove_observed_PA_swing: 5 polarization channels were expected, but there are only %ld.\", datafile->NrPols);\n    return 0;\n  }else if(datafile->poltype == POLTYPE_ILVPAdPATEldEl && datafile->NrPols != 8) {\n    printerror(verbose.debug, \"ERROR paswing_remove_observed_PA_swing: 8 polarization channels were expected, but there are only %ld.\", datafile->NrPols);\n    return 0;\n  }else if(datafile->poltype == POLTYPE_PAdPA && datafile->NrPols != 2) {\n    printerror(verbose.debug, \"ERROR paswing_remove_observed_PA_swing: 2 polarization channels were expected, but there are only %ld.\", datafile->NrPols);\n    return 0;\n  }\n  if(datafile_reference.poltype == POLTYPE_ILVPAdPA && datafile_reference.NrPols != 5) {\n    printerror(verbose.debug, \"ERROR paswing_remove_observed_PA_swing: 5 polarization channels were expected in the reference, but there are only %ld.\", datafile_reference.NrPols);\n    return 0;\n  }else if(datafile_reference.poltype == POLTYPE_ILVPAdPATEldEl && datafile_reference.NrPols != 8) {\n    printerror(verbose.debug, \"ERROR paswing_remove_observed_PA_swing: 8 polarization channels were expected in the reference, but there are only %ld.\", datafile_reference.NrPols);\n    return 0;\n  }else if(datafile_reference.poltype == POLTYPE_PAdPA && datafile_reference.NrPols != 2) {\n    printerror(verbose.debug, \"ERROR paswing_remove_observed_PA_swing: 2 polarization channels were expected in the reference, but there are only %ld.\", datafile_reference.NrPols);\n    return 0;\n  }\n  if(datafile_reference.NrBins != datafile->NrBins) {\n    printerror(verbose.debug, \"ERROR paswing_remove_observed_PA_swing: Mismatch in the number of bins in the data and the reference (%ld != %ld).\", datafile->NrBins, datafile_reference.NrBins);\n    return 0;\n  }\n  if(datafile_reference.NrFreqChan != 1) {\n    printerror(verbose.debug, \"ERROR paswing_remove_observed_PA_swing: The number of frequency channels in the reference should be 1 (it is %ld).\", datafile_reference.NrFreqChan);\n    return 0;\n  }\n  if(datafile_reference.NrSubints != 1) {\n    printerror(verbose.debug, \"ERROR paswing_remove_observed_PA_swing: The number of subints in the reference should be 1 (it is %ld).\", datafile_reference.NrSubints);\n    return 0;\n  }\n  if(datafile->poltype == POLTYPE_ILVPAdPA || datafile->poltype == POLTYPE_ILVPAdPATEldEl) {\n    pachannel = 3;\n    pachannelerr = 4;\n  }else if(datafile->poltype == POLTYPE_PAdPA) {\n    pachannel = 0;\n    pachannelerr = 1;\n  }\n  if(datafile_reference.poltype == POLTYPE_ILVPAdPA || datafile_reference.poltype == POLTYPE_ILVPAdPATEldEl) {\n    pachannel_ref = 3;\n    pachannelerr_ref = 4;\n  }else if(datafile_reference.poltype == POLTYPE_PAdPA) {\n    pachannel_ref = 0;\n    pachannelerr_ref = 1;\n  }\n  long i, f;\n  for(i = 0; i < datafile->NrSubints; i++) {\n    for(f = 0; f < datafile->NrFreqChan; f++) {\n      paswing_remove_observed_PA_swing_sp(&(datafile->data[datafile->NrBins*(pachannel + datafile->NrPols*(f+datafile->NrFreqChan*i))]), &(datafile->data[datafile->NrBins*(pachannelerr + datafile->NrPols*(f+datafile->NrFreqChan*i))]), &(datafile_reference.data[datafile->NrBins*pachannel_ref]), &(datafile_reference.data[datafile->NrBins*pachannelerr_ref]), datafile->NrBins, add, verbose);\n    }\n  }\n  return 1;\n}\nint writePPOLHeader(datafile_definition datafile, int argc, char **argv, verbose_definition verbose)\n{\n  char *txt;\n  txt = malloc(10000);\n  if(txt == NULL) {\n    fflush(stdout);\n    printerror(verbose.debug, \"ERROR writePPOLHeader: Memory allocation error.\");\n    return 0;\n  }\n  constructCommandLineString(txt, 10000, argc, argv, verbose);\n  fprintf(datafile.fptr_hdr, \"#ppol file: %s\\n\", txt);\n  free(txt);\n  return 1;\n}\nint readPPOLHeader(datafile_definition *datafile, int extended, verbose_definition verbose)\n{\n  float dummy_float;\n  int ret, maxlinelength, nrwords;\n  char *txt, *ret_ptr, *word_ptr;\n  maxlinelength = 2000;\n  txt = malloc(maxlinelength);\n  if(txt == NULL) {\n    fflush(stdout);\n    printerror(verbose.debug, \"ERROR readPPOLHeader: Memory allocation error.\");\n    return 0;\n  }\n  datafile->isFolded = 1;\n  datafile->foldMode = FOLDMODE_FIXEDPERIOD;\n  datafile->fixedPeriod = 0;\n  datafile->tsampMode = TSAMPMODE_LONGITUDELIST;\n  datafile->fixedtsamp = 0;\n  datafile->tsubMode = TSUBMODE_FIXEDTSUB;\n  if(datafile->tsub_list != NULL)\n    free(datafile->tsub_list);\n  datafile->tsub_list = (double *)malloc(sizeof(double));\n  if(datafile->tsub_list == NULL) {\n    fflush(stdout);\n    printerror(verbose.debug, \"ERROR readPPOLHeader: Memory allocation error\");\n    return 0;\n  }\n  datafile->tsub_list[0] = 0;\n  datafile->NrSubints = 1;\n  datafile->NrFreqChan = 1;\n  datafile->datastart = 0;\n  rewind(datafile->fptr);\n  ret = fread(txt, 1, 3, datafile->fptr);\n  txt[3] = 0;\n  if(ret != 3) {\n    fflush(stdout);\n    printerror(verbose.debug, \"ERROR readPPOLHeader: cannot read from file.\");\n    free(txt);\n    return 0;\n  }\n  if(strcmp(txt, \"#pp\") != 0\n) {\n    fflush(stdout);\n    printwarning(verbose.debug, \"WARNING readPPOLHeader: File does not appear to be in PPOL or PPOLSHORT format. I will try to load file, but this will probably fail. Did you run ppol first?\");\n  }\n  skipallhashedlines(datafile);\n  datafile->NrBins = 0;\n  dummy_float = 0;\n  do {\n    ret_ptr = fgets(txt, maxlinelength, datafile->fptr);\n    if(ret_ptr != NULL) {\n      if(txt[0] != '#') {\n if(extended) {\n   word_ptr = pickWordFromString(txt, 2, &nrwords, 1, ' ', verbose);\n   if(nrwords != 10 && nrwords != 14) {\n     fflush(stdout);\n     printerror(verbose.debug, \"ERROR readPPOLHeader: Line should have 10 or 14 words, got %d\", nrwords);\n     if(nrwords == 3)\n       printerror(verbose.debug, \"                             Maybe file is in format %s?\", returnFileFormat_str(PPOL_SHORT_format));\n     printerror(verbose.debug, \"                             Line: '%s'.\", txt);\n     free(txt);\n     return 0;\n   }\n   if(nrwords == 10) {\n     datafile->poltype = POLTYPE_ILVPAdPA;\n     datafile->NrPols = 5;\n   }else {\n     datafile->poltype = POLTYPE_ILVPAdPATEldEl;\n     datafile->NrPols = 8;\n   }\n }else {\n   word_ptr = pickWordFromString(txt, 1, &nrwords, 1, ' ', verbose);\n   if(nrwords != 3) {\n     fflush(stdout);\n     printerror(verbose.debug, \"ERROR readPPOLHeader: Line should have 3 words, got %d\", nrwords);\n     if(nrwords == 10)\n       printerror(verbose.debug, \"                             Maybe file is in format %s?\", returnFileFormat_str(PPOL_format));\n     printerror(verbose.debug, \"                             Line: '%s'.\", txt);\n     free(txt);\n     return 0;\n   }\n }\n ret = sscanf(word_ptr, \"%f\", &dummy_float);\n if(ret != 1) {\n   fflush(stdout);\n   printerror(verbose.debug, \"ERROR readPPOLHeader: Cannot interpret as a float: '%s'.\", txt);\n   free(txt);\n   return 0;\n }\n if(dummy_float >= 360) {\n   fflush(stdout);\n   printwarning(verbose.debug, \"WARNING: IGNORING POINTS AT PULSE LONGITUDES > 360 deg.\");\n }else {\n   (datafile->NrBins)++;\n }\n      }\n    }\n  }while(ret_ptr != NULL && dummy_float < 360);\n  if(extended == 0) {\n    datafile->poltype = POLTYPE_PAdPA;\n    datafile->NrPols = 2;\n  }\n  fflush(stdout);\n  if(verbose.verbose) fprintf(stdout, \"Going to load %ld points from %s\\n\", datafile->NrBins, datafile->filename);\n  if(datafile->NrBins == 0) {\n    fflush(stdout);\n    printerror(verbose.debug, \"ERROR readPPOLHeader: No data in %s\", datafile->filename);\n    free(txt);\n    return 0;\n  }\n  fseek(datafile->fptr, datafile->datastart, SEEK_SET);\n  free(txt);\n  if(datafile->offpulse_rms != NULL) {\n    free(datafile->offpulse_rms);\n    datafile->offpulse_rms = NULL;\n  }\n  if(extended) {\n    datafile->offpulse_rms = (float *)malloc(datafile->NrSubints*datafile->NrFreqChan*datafile->NrPols*sizeof(float));\n    if(datafile->offpulse_rms == NULL) {\n      fflush(stdout);\n      printerror(verbose.debug, \"ERROR readPPOLHeader: Memory allocation error\");\n      return 0;\n    }\n  }\n  datafile->tsamp_list = (double *)malloc(datafile->NrBins*sizeof(double));\n  if(datafile->tsamp_list == NULL) {\n    fflush(stdout);\n    printerror(verbose.debug, \"ERROR readPPOLHeader: Memory allocation error\");\n    return 0;\n  }\n  return 1;\n}\nint readPPOLfile(datafile_definition *datafile, float *data, int extended, float add_longitude_shift, verbose_definition verbose)\n{\n  int maxlinelength;\n  long i, k, dummy_long;\n  char *txt, *ret_ptr;\n  if(datafile->NrBins == 0) {\n    fflush(stdout);\n    printerror(verbose.debug, \"ERROR readPPOLfile: No data in %s\", datafile->filename);\n    return 0;\n  }\n  maxlinelength = 2000;\n  txt = malloc(maxlinelength);\n  if(txt == NULL) {\n    fflush(stdout);\n    printerror(verbose.debug, \"ERROR readPPOLfile: Memory allocation error.\");\n    return 0;\n  }\n  fseek(datafile->fptr, datafile->datastart, SEEK_SET);\n  k = 0;\n  if(extended) {\n    datafile->offpulse_rms[3] = -1;\n    datafile->offpulse_rms[4] = -1;\n    if(datafile->NrPols == 8) {\n      datafile->offpulse_rms[6] = -1;\n      datafile->offpulse_rms[7] = -1;\n    }\n  }\n  for(i = 0; i < datafile->NrBins; i++) {\n    ret_ptr = fgets(txt, maxlinelength, datafile->fptr);\n    if(ret_ptr == NULL) {\n      fflush(stdout);\n      printerror(verbose.debug, \"ERROR readPPOLfile: Cannot read next line, should not happen after successfully reading in header\");\n      free(txt);\n      return 0;\n    }\n    if(txt[0] != '#') {\n      if(extended == 0) {\n sscanf(txt, \"%lf %f %f\", &(datafile->tsamp_list[k]), &(data[k]), &(data[k+datafile->NrBins]));\n      }else {\n if(datafile->NrPols == 8) {\n   sscanf(txt, \"%ld %lf %f %f %f %f %f %f %f %f %f %f %f %f\", &dummy_long, &(datafile->tsamp_list[k]), &(data[k]), &(datafile->offpulse_rms[0]), &(data[k+datafile->NrBins]), &(datafile->offpulse_rms[1]), &(data[k+2*datafile->NrBins]), &(datafile->offpulse_rms[2]), &(data[k+3*datafile->NrBins]), &(data[k+4*datafile->NrBins]), &(data[k+5*datafile->NrBins]), &(datafile->offpulse_rms[5]), &(data[k+6*datafile->NrBins]), &(data[k+7*datafile->NrBins]));\n }else {\n   sscanf(txt, \"%ld %lf %f %f %f %f %f %f %f %f\", &dummy_long, &(datafile->tsamp_list[k]), &(data[k]), &(datafile->offpulse_rms[0]), &(data[k+datafile->NrBins]), &(datafile->offpulse_rms[1]), &(data[k+2*datafile->NrBins]), &(datafile->offpulse_rms[2]), &(data[k+3*datafile->NrBins]), &(data[k+4*datafile->NrBins]));\n }\n      }\n      datafile->tsamp_list[k] += add_longitude_shift;\n      if(datafile->tsamp_list[k] >= 0 && datafile->tsamp_list[k] < 360) {\n   k++;\n      }else {\n fflush(stdout);\n printwarning(verbose.debug, \"WARNING readPPOLfile: IGNORING POINTS AT PULSE LONGITUDES outside range 0 ... 360 deg.\");\n      }\n    }\n  }\n  if(k != datafile->NrBins) {\n    fflush(stdout);\n    printerror(verbose.debug, \"WARNING readPPOLfile: The nr of bins read in is different as determined from header. Something is wrong.\");\n    return 0;\n  }\n  fflush(stdout);\n  if(verbose.verbose) fprintf(stdout, \"readPPOLfile: Accepted %ld points\\n\", datafile->NrBins);\n     free(txt);\n  return 1;\n}\nint writePPOLfile(datafile_definition datafile, float *data, int extended, int onlysignificantPA, int twoprofiles, float PAoffset, verbose_definition verbose)\n{\n  long j;\n  if(datafile.poltype != POLTYPE_ILVPAdPA && datafile.poltype != POLTYPE_PAdPA && datafile.poltype != POLTYPE_ILVPAdPATEldEl) {\n    printerror(verbose.debug, \"ERROR writePPOLfile: Data doesn't appear to have poltype ILVPAdPA, PAdPA or ILVPAdPATEldEl (it is %d).\", datafile.poltype);\n    return 0;\n  }\n  if(datafile.poltype == POLTYPE_ILVPAdPA && datafile.NrPols != 5) {\n    printerror(verbose.debug, \"ERROR writePPOLfile: 5 polarization channels were expected, but there are %ld.\", datafile.NrPols);\n    return 0;\n  }else if(datafile.poltype == POLTYPE_PAdPA && datafile.NrPols != 2) {\n    printerror(verbose.debug, \"ERROR writePPOLfile: 2 polarization channels were expected, but there are %ld.\", datafile.NrPols);\n    return 0;\n  }else if(datafile.poltype == POLTYPE_ILVPAdPATEldEl && datafile.NrPols != 8) {\n    printerror(verbose.debug, \"ERROR writePPOLfile: 8 polarization channels were expected, but there are %ld.\", datafile.NrPols);\n    return 0;\n  }\n  if(datafile.NrSubints > 1 || datafile.NrFreqChan > 1) {\n    printerror(verbose.debug, \"ERROR writePPOLfile: Can only do this opperation if there is one subint and one frequency channel.\");\n    return 0;\n  }\n  if(datafile.tsampMode != TSAMPMODE_LONGITUDELIST) {\n    printerror(verbose.debug, \"ERROR writePPOLfile: Expected pulse longitudes to be defined.\");\n    return 0;\n  }\n  int pa_offset, dpa_offset;\n  if(datafile.poltype == POLTYPE_ILVPAdPA || datafile.poltype == POLTYPE_ILVPAdPATEldEl) {\n    pa_offset = 3;\n    dpa_offset = 4;\n  }else if(datafile.poltype == POLTYPE_PAdPA) {\n    pa_offset = 0;\n    dpa_offset = 1;\n  }\n  for(j = 0; j < datafile.NrBins; j++) {\n    if(data[j+dpa_offset*datafile.NrBins] > 0 || onlysignificantPA == 0) {\n      if(extended) {\n fprintf(datafile.fptr, \"%ld %e %e %e %e %e %e %e %e %e\", j, datafile.tsamp_list[j], data[j], datafile.offpulse_rms[0], data[j+datafile.NrBins], datafile.offpulse_rms[1], data[j+2*datafile.NrBins], datafile.offpulse_rms[2], data[j+pa_offset*datafile.NrBins]+PAoffset, data[j+dpa_offset*datafile.NrBins]);\n if(datafile.poltype == POLTYPE_ILVPAdPATEldEl)\n   fprintf(datafile.fptr, \" %e %e %e %e\", data[j+5*datafile.NrBins], datafile.offpulse_rms[5], data[j+6*datafile.NrBins], data[j+7*datafile.NrBins]);\n fprintf(datafile.fptr, \"\\n\");\n      }else {\n fprintf(datafile.fptr, \"%e %e %e\\n\", datafile.tsamp_list[j], data[j+pa_offset*datafile.NrBins]+PAoffset, data[j+dpa_offset*datafile.NrBins]);\n      }\n    }\n  }\n  if(twoprofiles) {\n    for(j = 0; j < datafile.NrBins; j++) {\n      if(data[j+dpa_offset*datafile.NrBins] > 0 || onlysignificantPA == 0) {\n if(extended) {\n   fprintf(datafile.fptr, \"%ld %e %e %e %e %e %e %e %e %e\", j, datafile.tsamp_list[j]+360, data[j], datafile.offpulse_rms[0], data[j+datafile.NrBins], datafile.offpulse_rms[1], data[j+2*datafile.NrBins], datafile.offpulse_rms[2], data[j+pa_offset*datafile.NrBins]+PAoffset, data[j+dpa_offset*datafile.NrBins]);\n   if(datafile.poltype == POLTYPE_ILVPAdPATEldEl)\n     fprintf(datafile.fptr, \" %e %e %e %e\", data[j+5*datafile.NrBins], datafile.offpulse_rms[5], data[j+6*datafile.NrBins], data[j+7*datafile.NrBins]);\n   fprintf(datafile.fptr, \"\\n\");\n }else {\n   fprintf(datafile.fptr, \"%e %e %e\\n\", datafile.tsamp_list[j]+360, data[j]+PAoffset, data[j+dpa_offset*datafile.NrBins]);\n }\n      }\n    }\n  }\n  return 1;\n}\nint make_pa_distribution(datafile_definition datain, datafile_definition *dataout, int nrbins, int normalise, int weighttype, datafile_definition *pamask, float pamask_value, int ellipticity, verbose_definition verbose)\n{\n  long i, j, f, nrpointsadded, nrpointsadded_max, binnr;\n  float dpa;\n  if(datain.NrSubints <= 1 && datain.NrFreqChan <= 1) {\n    fflush(stdout);\n    printerror(verbose.debug, \"ERROR make_pa_distribution: Need more than a single subints and frequency channel to make a PA distribution\");\n    return 0;\n  }\n  if(datain.poltype != POLTYPE_ILVPAdPA && datain.poltype != POLTYPE_PAdPA && datain.poltype != POLTYPE_ILVPAdPATEldEl) {\n    printerror(verbose.debug, \"ERROR make_pa_distribution: Data doesn't appear to have poltype ILVPAdPA, ILVPAdPATEldEl or PAdPA.\");\n    return 0;\n  }\n  if(ellipticity && datain.poltype != POLTYPE_ILVPAdPATEldEl) {\n    printerror(verbose.debug, \"ERROR make_pa_distribution: The data isn't of polarization type ILVPAdPATEldEl, while the ellipticity distribution was requested.\");\n    return 0;\n  }\n  if(datain.poltype == POLTYPE_ILVPAdPA && datain.NrPols != 5) {\n    printerror(verbose.debug, \"ERROR make_pa_distribution: 5 polarization channels were expected, but there are %ld.\", datain.NrPols);\n    return 0;\n  }else if(datain.poltype == POLTYPE_ILVPAdPATEldEl && datain.NrPols != 8) {\n    printerror(verbose.debug, \"ERROR make_pa_distribution: 8 polarization channels were expected, but there are %ld.\", datain.NrPols);\n    return 0;\n  }else if(datain.poltype == POLTYPE_PAdPA && datain.NrPols != 2) {\n    printerror(verbose.debug, \"ERROR make_pa_distribution: 2 polarization channels were expected, but there are %ld.\", datain.NrPols);\n    return 0;\n  }\n  if(pamask != NULL) {\n    if(datain.NrBins != pamask->NrBins) {\n      printerror(verbose.debug, \"ERROR make_pa_distribution: Applying a PA mask only works when the input data has the same number of pulse longitude bins compared to that of the provided mask. (the input data has %ld pulse longitude bins, while the mask has %ld).\", datain.NrBins, pamask->NrBins);\n      return 0;\n    }\n    if(nrbins != pamask->NrSubints) {\n      printerror(verbose.debug, \"ERROR make_pa_distribution: Applying a PA mask only works when generating a PA-distribution with an equal number of PA bins compared to that of the provided mask. (now %ld pa bins are requested, while the mask has %ld pa-bins defined).\", nrbins, pamask->NrSubints);\n      return 0;\n    }\n    if(pamask->NrFreqChan > 1) {\n      printerror(verbose.debug, \"ERROR make_pa_distribution: Applying a PA mask only works when the mask has one frequency channel defined. There are currently %ld channels defined).\", pamask->NrFreqChan);\n      return 0;\n    }\n  }\n  cleanPSRData(dataout, verbose);\n  copy_params_PSRData(datain, dataout, verbose);\n  dataout->format = MEMORY_format;\n  dataout->NrSubints = nrbins;\n  dataout->NrPols = 1;\n  dataout->NrFreqChan = 1;\n  if(ellipticity == 0)\n    dataout->gentype = GENTYPE_PADIST;\n  else\n    dataout->gentype = GENTYPE_ELLDIST;\n  dataout->tsubMode = TSUBMODE_FIXEDTSUB;\n  if(dataout->tsub_list != NULL)\n    free(dataout->tsub_list);\n  dataout->tsub_list = (double *)malloc(sizeof(double));\n  if(dataout->tsub_list == NULL) {\n    fflush(stdout);\n    printerror(verbose.debug, \"ERROR make_pa_distribution: Memory allocation error\");\n    return 0;\n  }\n  dataout->tsub_list[0] = get_tobs(datain, verbose);\n  dataout->yrangeset = 1;\n  if(ellipticity == 0) {\n    dataout->yrange[0] = -90.0+0.5*180.0/(float)(nrbins);\n    dataout->yrange[1] = 90.0-0.5*180.0/(float)(nrbins);\n  }else {\n    dataout->yrange[0] = -45.0+0.5*90.0/(float)(nrbins);\n    dataout->yrange[1] = 45.0-0.5*90.0/(float)(nrbins);\n  }\n  dataout->data = (float *)calloc(dataout->NrSubints*dataout->NrBins*dataout->NrPols*dataout->NrFreqChan, sizeof(float));\n  if(dataout->data == NULL) {\n    fflush(stdout);\n    printerror(verbose.debug, \"ERROR make_pa_distribution: Cannot allocate memory for data.\");\n    return 0;\n  }\n  if(ellipticity == 0) {\n    dpa = 180.0/(float)nrbins;\n  }else {\n    dpa = 90.0/(float)nrbins;\n  }\n  int pa_chan, dpa_chan, weight_chan;\n  if(datain.poltype == POLTYPE_ILVPAdPA || datain.poltype == POLTYPE_ILVPAdPATEldEl) {\n    if(ellipticity == 0) {\n      pa_chan = 3;\n      dpa_chan = 4;\n    }else {\n      pa_chan = 6;\n      dpa_chan = 7;\n    }\n    if(weighttype == 0) {\n      weight_chan = -1;\n    }else if(weighttype == 1) {\n      weight_chan = 1;\n    }else if(weighttype == 2) {\n      weight_chan = 2;\n    }else if(weighttype == 3) {\n      weight_chan = 0;\n    }else if(weighttype == 4) {\n      weight_chan = 5;\n      if(datain.poltype != POLTYPE_ILVPAdPATEldEl) {\n printerror(verbose.debug, \"ERROR make_pa_distribution: Weighting by the total polarization is requested, but that is not appears to be defined in the input data.\");\n return 0;\n      }\n    }else {\n      printerror(verbose.debug, \"ERROR make_pa_distribution: Unsupported weighttype is specified.\");\n      return 0;\n    }\n  }else {\n    pa_chan = 0;\n    dpa_chan = 1;\n    if(weighttype != 0) {\n      printerror(verbose.debug, \"ERROR make_pa_distribution: Data only has PA values defined, so weighting is not supported.\");\n      return 0;\n    }\n  }\n  nrpointsadded_max = 0;\n  for(j = 0; j < datain.NrBins; j++) {\n    nrpointsadded = 0;\n    for(i = 0; i < datain.NrSubints; i++) {\n      for(f = 0; f < datain.NrFreqChan; f++) {\n float paerr;\n paerr = datain.data[j+datain.NrBins*(dpa_chan+datain.NrPols*(f+datain.NrFreqChan*i))];\n if(paerr > 0) {\n   float pa = derotate_180_small_double(datain.data[j+datain.NrBins*(pa_chan+datain.NrPols*(f+datain.NrFreqChan*i))]);\n   float weight = 1.0;\n   if(weighttype != 0) {\n     weight = datain.data[j+datain.NrBins*(weight_chan+datain.NrPols*(f+datain.NrFreqChan*i))];\n     if(weighttype == 2) {\n       weight = fabs(weight);\n     }\n   }\n   if(ellipticity == 0) {\n     if(pa == 90.0)\n       binnr = 0;\n     else\n       binnr = (pa + 90.0)/dpa;\n   }else {\n     if(pa == 45.0)\n       binnr = 0;\n     else\n       binnr = (pa + 45.0)/dpa;\n   }\n   if(binnr < 0 || binnr >= nrbins) {\n     fflush(stdout);\n     printerror(verbose.debug, \"ERROR make_pa_distribution: %ld %f %f BUG!!!!!!!!!!!!!!!\", binnr, datain.data[j+datain.NrBins*(pa_chan+datain.NrPols*(f+datain.NrFreqChan*i))], dpa);\n     return 0;\n   }\n   dataout->data[j+dataout->NrBins*binnr] += weight;\n   nrpointsadded++;\n }\n if(pamask != NULL) {\n   float value;\n   if(paerr <= 0) {\n     value = 0;\n   }else {\n     value = pamask->data[j+pamask->NrBins*(0+pamask->NrPols*(0+pamask->NrFreqChan*binnr))];\n   }\n   if(isnan(pamask_value)) {\n     int curpol;\n     for(curpol = 0; curpol < datain.NrPols; curpol++) {\n       datain.data[j+datain.NrBins*(curpol+datain.NrPols*(f+datain.NrFreqChan*i))] = value;\n     }\n   }else {\n     if(value < pamask_value-0.01 || value > pamask_value+0.01 || paerr <= 0) {\n       int curpol;\n       for(curpol = 0; curpol < datain.NrPols; curpol++) {\n  datain.data[j+datain.NrBins*(curpol+datain.NrPols*(f+datain.NrFreqChan*i))] = 0;\n       }\n     }\n   }\n }\n      }\n    }\n    if(nrpointsadded > nrpointsadded_max)\n      nrpointsadded_max = nrpointsadded;\n  }\n  if(normalise) {\n    if(nrpointsadded_max > 0) {\n      for(i = 0; i < nrbins; i++) {\n for(j = 0; j < datain.NrBins; j++) {\n   dataout->data[j+datain.NrBins*i] /= (float)nrpointsadded_max;\n }\n      }\n    }\n  }\n  return 1;\n}\nint make_polarization_projection_map(datafile_definition datafile, float *map, int nrx, int nry, float background, int binnr, pulselongitude_regions_definition onpulse, int weighting, float threshold, int projection, float rot_long, float rot_lat, float conalselection, datafile_definition *subtract_pa_data, verbose_definition verbose)\n{\n  int ok;\n  long i, xi, yi, pulsenr;\n  float longitude, stokesI, L, P, latitude, x, y, weight;\n  if(projection < 1 || projection > 3) {\n    fflush(stdout);\n    printerror(verbose.debug, \"ERROR make_projection_map_formIQUV: Projection type is not implemented.\");\n    return 0;\n  }\n  if(datafile.NrFreqChan != 1) {\n    fflush(stdout);\n    printerror(verbose.debug, \"ERROR make_projection_map_formIQUV: Expected 1 frequency channel.\");\n    return 0;\n  }\n  if(datafile.poltype == POLTYPE_ILVPAdPATEldEl) {\n    if(datafile.NrPols != 8) {\n      fflush(stdout);\n      printerror(verbose.debug, \"ERROR make_projection_map_formIQUV: Expected 8 input polarizations when reading in data containing PA's and ellipticities.\");\n      return 0;\n    }\n  }else {\n    if(datafile.NrPols != 4) {\n      fflush(stdout);\n      printerror(verbose.debug, \"ERROR make_projection_map_formIQUV: Expected 4 input polarizations.\");\n      return 0;\n    }\n  }\n  if(subtract_pa_data != NULL) {\n    if(subtract_pa_data->NrBins != datafile.NrBins) {\n      printerror(verbose.debug, \"ERROR make_projection_map_formIQUV: The reference PA-swing has a different number of pulse phase bins compared to the input data.\");\n      return 0;\n    }\n    if(subtract_pa_data->NrFreqChan != 1) {\n      fflush(stdout);\n      printerror(verbose.debug, \"ERROR make_projection_map_formIQUV: The reference PA-swing should have a single frequency channel.\");\n      return 0;\n    }\n    if(subtract_pa_data->NrSubints != 1) {\n      fflush(stdout);\n      printerror(verbose.debug, \"ERROR make_projection_map_formIQUV: The reference PA-swing should have a single subint.\");\n      return 0;\n    }\n  }\n  rot_long *= M_PI/180.0;\n  rot_lat *= M_PI/180.0;\n  float *normmap;\n  if(weighting == 2) {\n    normmap = malloc(nrx*nry*sizeof(float));\n    if(normmap == NULL) {\n      printerror(verbose.debug, \"ERROR make_projection_map_formIQUV: Memory allocation error.\");\n      return 0;\n    }\n  }\n  for(xi = 0; xi < nrx; xi++) {\n    for(yi = 0; yi < nry; yi++) {\n      map[xi+nrx*yi] = 0;\n      if(weighting == 2) {\n normmap[xi+nrx*yi] = 0;\n      }\n    }\n  }\n  for(pulsenr = 0; pulsenr < datafile.NrSubints; pulsenr++) {\n    for(i = 0; i < (datafile.NrBins); i++) {\n      ok = 1;\n      if(binnr >= 0) {\n if(i != binnr)\n   ok = 0;\n      }else if(binnr == -1) {\n if(checkRegions(i, &onpulse, 0, verbose) == 0) {\n   ok = 0;\n }\n      }\n      if(ok) {\n if(datafile.poltype == POLTYPE_ILVPAdPATEldEl) {\n   longitude = 2.0*datafile.data[i+datafile.NrBins*datafile.NrPols*pulsenr+3*(datafile.NrBins)]*M_PI/180.0;\n   L = datafile.data[i+datafile.NrBins*datafile.NrPols*pulsenr+1*(datafile.NrBins)];\n   latitude = 2.0*datafile.data[i+datafile.NrBins*datafile.NrPols*pulsenr+6*(datafile.NrBins)]*M_PI/180.0;\n   if(datafile.data[i+datafile.NrBins*datafile.NrPols*pulsenr+4*(datafile.NrBins)] < 0 || datafile.data[i+datafile.NrBins*datafile.NrPols*pulsenr+7*(datafile.NrBins)] < 0) {\n     longitude = latitude = sqrt(-1.0);\n   }\n }else {\n   longitude = atan2(datafile.data[i+datafile.NrBins*datafile.NrPols*pulsenr+2*(datafile.NrBins)],datafile.data[i+datafile.NrBins*datafile.NrPols*pulsenr+(datafile.NrBins)]);\n   L = sqrt(datafile.data[i+datafile.NrBins*datafile.NrPols*pulsenr+2*(datafile.NrBins)]*datafile.data[i+datafile.NrBins*datafile.NrPols*pulsenr+2*(datafile.NrBins)] + datafile.data[i+datafile.NrBins*datafile.NrPols*pulsenr+(datafile.NrBins)]*datafile.data[i+datafile.NrBins*datafile.NrPols*pulsenr+(datafile.NrBins)]);\n   latitude = atan(datafile.data[i+datafile.NrBins*datafile.NrPols*pulsenr+3*(datafile.NrBins)]/L);\n }\n if(subtract_pa_data != NULL) {\n   int pachannel_subtract_fin;\n   if(subtract_pa_data->poltype == POLTYPE_ILVPAdPATEldEl) {\n     pachannel_subtract_fin = 3;\n   }else {\n     pachannel_subtract_fin = subtract_pa_data->NrPols-2;\n   }\n   longitude -= 2.0*subtract_pa_data->data[i+subtract_pa_data->NrBins*(pachannel_subtract_fin)]*M_PI/180.0;\n }\n if(!isnan(latitude)) {\n   if(conalselection > 0) {\n     double sphericaldistance;\n     sphericaldistance = acos(cos(latitude-rot_lat)*cos(longitude+rot_long))*180.0/M_PI;\n     if(sphericaldistance > conalselection) {\n       latitude = sqrt(-1.0);\n     }\n   }\n }\n if(!isnan(latitude)) {\n   if(weighting) {\n     if(weighting != 3) {\n       if(datafile.poltype == POLTYPE_ILVPAdPATEldEl) {\n  P = datafile.data[i+datafile.NrBins*datafile.NrPols*pulsenr+5*(datafile.NrBins)];\n       }else {\n  P = sqrt(L*L+datafile.data[i+datafile.NrBins*datafile.NrPols*pulsenr+3*(datafile.NrBins)]*datafile.data[i+datafile.NrBins*datafile.NrPols*pulsenr+3*(datafile.NrBins)]);\n       }\n     }\n     if(weighting == 2 || weighting == 3) {\n       stokesI = datafile.data[i+datafile.NrBins*datafile.NrPols*pulsenr];\n     }\n   }\n   if(projection == 1) {\n     projectionHammerAitoff_xy(longitude, latitude, rot_long, rot_lat, &x, &y);\n     weight = 1;\n   }else if(projection == 2) {\n     projection_sphere_xy(longitude, latitude, rot_long, rot_lat, &x, &y, &weight);\n   }else if(projection == 3) {\n     projection_longlat_xy(longitude, latitude, rot_long, rot_lat, &x, &y);\n     weight = 1;\n     x /= 80.0;\n     y /= 80.0;\n   }\n   xi = 0.5*nrx + x*nrx/4.5;\n   yi = 0.5*nry + y*nry/2.25;\n   if(weighting == 0) {\n     map[xi+nrx*yi] += 1.0*weight;\n   }else {\n     if(weighting == 3) {\n       map[xi+nrx*yi] += stokesI*weight;\n     }else {\n       map[xi+nrx*yi] += P*weight;\n     }\n     if(weighting == 2) {\n       normmap[xi+nrx*yi] += stokesI*weight;\n     }\n   }\n }\n      }\n    }\n  }\n  if((weighting == 1 || weighting == 2) && threshold > 0) {\n    float maxvalue = map[0];\n    for(xi = 0; xi < nrx; xi++) {\n      for(yi = 0; yi < nry; yi++) {\n if(map[xi+nrx*yi] > maxvalue) {\n   maxvalue = map[xi+nrx*yi];\n }\n      }\n    }\n    for(xi = 0; xi < nrx; xi++) {\n      for(yi = 0; yi < nry; yi++) {\n if(map[xi+nrx*yi] < threshold*maxvalue) {\n   map[xi+nrx*yi] = 0;\n }\n      }\n    }\n  }\n  if(weighting == 2) {\n    for(xi = 0; xi < nrx; xi++) {\n      for(yi = 0; yi < nry; yi++) {\n if(normmap[xi+nrx*yi] != 0.0) {\n   map[xi+nrx*yi] /= normmap[xi+nrx*yi];\n   if(map[xi+nrx*yi] < 0) {\n     map[xi+nrx*yi] = 0;\n   }\n   if(map[xi+nrx*yi] > 1) {\n     map[xi+nrx*yi] = 1;\n   }\n }else {\n   map[xi+nrx*yi] = 0;\n }\n      }\n    }\n    free(normmap);\n  }\n  return 1;\n}\n", "meta": {"hexsha": "a1cb26e03ae91facc7a33aad8b259c1335cd1f83", "size": 59286, "ext": "c", "lang": "C", "max_stars_repo_path": "src/lib/psrio_paswing.c", "max_stars_repo_name": "weltevrede/psrsalsa", "max_stars_repo_head_hexsha": "4c5b1b32513174ec1f6929905e67c8b9ca44e008", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-09-05T23:22:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-11T14:12:18.000Z", "max_issues_repo_path": "src/lib/psrio_paswing.c", "max_issues_repo_name": "weltevrede/psrsalsa", "max_issues_repo_head_hexsha": "4c5b1b32513174ec1f6929905e67c8b9ca44e008", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-04-26T13:35:30.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-20T08:49:57.000Z", "max_forks_repo_path": "src/lib/psrio_paswing.c", "max_forks_repo_name": "weltevrede/psrsalsa", "max_forks_repo_head_hexsha": "4c5b1b32513174ec1f6929905e67c8b9ca44e008", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-04-09T09:04:46.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-16T15:24:07.000Z", "avg_line_length": 41.8390966831, "max_line_length": 755, "alphanum_fraction": 0.6713558007, "num_tokens": 18613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.26894142136999516, "lm_q2_score": 0.024053554993252985, "lm_q1q2_score": 0.006468997268886802}}
{"text": "#include \"uavsar.h\"\n#include \"asf_meta.h\"\n#include \"asf_endian.h\"\n#include <ctype.h>\n\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_multiroots.h>\n\n#define SQR(x) (x*x)\n#define FLOAT_COMPARE_TOLERANCE(a, b, t) (fabs (a - b) <= t ? 1: 0)\n#define ASF_EXPORT_FLOAT_MICRON 0.000000001\n#define FLOAT_EQUIVALENT(a, b) (FLOAT_COMPARE_TOLERANCE \\\n                                (a, b, ASF_EXPORT_FLOAT_MICRON))\n#define MAX_LINE 512\n\nchar **get_uavsar_products(const char *data_type, char *type, int *num_product)\n{  \n  char *rest, *token;\n  int ii, product_count;\n  char *tmp = (char *) MALLOC(sizeof(char)*60);\n  strcpy(tmp, data_type);\n\n  if (strcmp_case(type, \"POLSAR\") == 0) {\n    product_count = 5;\n    if (strcmp_case(tmp, \"ALL\") == 0)\n      sprintf(tmp, \"SLC,MLC,DAT,GRD,HGT\");\n  }\n  else if (strcmp_case(type, \"INSAR\") == 0) {\n    product_count = 9;\n    if (strcmp_case(tmp, \"ALL\") == 0)\n      sprintf(tmp, \"AMP,INT,UNW,COR,AMP_GRD,INT_GRD,UNW_GRD,COR_GRD,HGT_GRD\");\n  }\n\n  char **product = (char **) MALLOC(sizeof(char*) * product_count);\n  for (ii = 0; ii < product_count; ii++) {\n    product[ii] = (char *) MALLOC(sizeof(char)*10);\n    strcpy(product[ii], \"\");\n  }\n\n  ii = 0;\n  while ((token = strtok_r(tmp, \",\", &rest))) {\n    strcpy(product[ii], token);\n    tmp = rest;\n    ii++;\n  }\n\n  *num_product = ii;\n\n  return product;\n}\n\nint parse_annotation_line(char *line, char *key, char *value)\n{\n  char *ks = line, *ke = line, *vs = line, *ve = line, *b = line;\n\n  while(isspace(*b)) ks = ++b; // Move forward past the whitespace to the beginning of the key\n\n  if(*b == ';' || *b == '\\0') {\n    // This line has nothing interesting, return nothing\n    *key = *value = '\\0';\n    return 1;\n  }\n\n  while(*b != '(' && *b != '\\0' && *b != '=') ++b; // Advance to a delimiter; either an equals sign, a '(' (to denote the beginning of the unit specification) or the end of the line\n  \n  if(*b == '\\0') return 0; // Unexpected end-of-line\n\n  ke = b - 1;\n  while(isspace(*ke)) --ke; // Back up until we hit the end of the key\n\n  while(*b != '\\0' && *b != '=') b++; // Advance to the equals sign\n\n  if(*b == '\\0') return 0; // Unexpected end-of-line\n\n  b++;\n  while(isspace(*b) && *b != '\\0') b++; // Move forward past the whitespace to the beginning of the value\n\n  if(*b == '\\0') return 0; // Unexpected end-of-line\n\n  vs = b++;\n  while(*b != ';' && *b != '\\0') ++b; // Move forward to the end of the line or the beginning of a comment\n\n  ve = b - 1;\n  while(isspace(*ve)) --ve; // Back up until we hit the end of the key\n\n  strncpy(key, ks, ke - ks + 1);\n  key[ke-ks+1] = '\\0';\n  strncpy(value, vs, ve - vs + 1);\n  value[ve-vs+1] = '\\0';\n\n  return 1;\n}\n\nint check_file(const char *path, char *line, char **fileName)\n{\n  char *p, *r;\n  p = strchr(line, '=');\n  char *file = (char *) MALLOC(sizeof(char)*255);\n  strcpy(file, p+1);\n  r = strchr(file, ';');\n  if (r)\n    r[0] = '\\0';\n  *fileName = MALLOC(sizeof(char)*(strlen(path) + strlen(file) + 32));\n  strcpy(*fileName, path);\n  char *trimmed_file = trim_spaces(file);\n  strcat(*fileName, trimmed_file);\n  FREE(file);\n  FREE(trimmed_file);\n  p = strchr(line, ';');\n  long long size;\n  sscanf(p+12, \"%lld\", &size);\n  if (fileExists(*fileName) && fileSize(*fileName) == size)\n    return TRUE;\n  else\n    return FALSE;\n}\n\nvoid\nget_uavsar_file_names(const char *dataFile, uavsar_type_t type,\n                      char ***pDataName, char ***pElement,\n                      int **pDataType, int *nBands)\n{\n  int ii, slc = 0, mlc = 0, dat = 0, grd = 0, hgt = 0;\n  int igram = 0, unw = 0, cor = 0, amp = 0;\n  int igram_grd = 0, unw_grd = 0, cor_grd = 0, amp_grd = 0, hgt_grd = 0;\n\n  char *file = (char *) MALLOC(sizeof(char) * 1024);\n  char **dataName = (char **) MALLOC(6 * sizeof(char *));\n  char **element = (char **) MALLOC(6 * sizeof(char *));\n  int *dataType = (int *) MALLOC(6 * sizeof(int));\n  for (ii = 0; ii < 6; ii++) {\n    dataName[ii] = (char *) MALLOC(sizeof(char) * 512);\n    element[ii] = (char *) MALLOC(sizeof(char) * 10);\n  }\n  *pDataName = dataName;\n  *pElement = element;\n  *pDataType = dataType;\n  *nBands = 0;\n\n  char *path = get_dirname(dataFile);\n\n  char line[MAX_LINE], key[MAX_LINE], value[MAX_LINE];\n  FILE *fp = FOPEN(dataFile, \"r\");\n  while (fgets(line, MAX_LINE, fp)) {\n    if(!parse_annotation_line(line, key, value)) {\n      asfPrintWarning(\"Unable to parse line in annotation file: %s\", line);\n      continue;\n    }\n    if (!strcmp(key, \"\"))\n      continue;\n    if (type == POLSAR_SLC) {\n      if (!strcmp(key, \"slcHH\")) {\n        if (check_file(path, line, &file)) {\n          strcpy(dataName[slc], file);\n          strcpy(element[slc], \"HH\");\n          dataType[slc] = 1;\n          slc++;\n        }\n      }\n      else if (!strcmp(key, \"slcHV\")) {\n        if (check_file(path, line, &file)) {\n          strcpy(dataName[slc], file);\n          strcpy(element[slc], \"HV\");\n          dataType[slc] = 1;\n          slc++;\n        }\n      }\n      else if (!strcmp(key, \"slcVH\")) {\n        if (check_file(path, line, &file)) {\n          strcpy(dataName[slc], file);\n          strcpy(element[slc], \"VH\");\n          dataType[slc] = 1;\n          slc++;\n        }\n      }\n      else if (!strcmp(key, \"slcVV\")) {\n        if (check_file(path, line, &file)) {\n          strcpy(dataName[slc], file);\n          strcpy(element[slc], \"VV\");\n          dataType[slc] = 1;\n          slc++;\n        }\n      }\n      *nBands = slc;\n    }\n    else if (type == POLSAR_MLC) {\n      if (!strcmp(key, \"mlcHHHH\")) {\n        if (check_file(path, line, &file)) {\n          strcpy(dataName[mlc], file);\n          strcpy(element[mlc], \"C11\");\n          dataType[mlc] = 0;\n          mlc++;\n        }\n      }\n      else if (!strcmp(key, \"mlcHVHV\")) {\n        if (check_file(path, line, &file)) {\n          strcpy(dataName[mlc], file);\n          strcpy(element[mlc], \"C22\");\n          dataType[mlc] = 0;\n          mlc++;\n        }\n      }\n      else if (!strcmp(key, \"mlcVVVV\")) {\n        if (check_file(path, line, &file)) {\n          strcpy(dataName[mlc], file);\n          strcpy(element[mlc], \"C33\");\n          dataType[mlc] = 0;\n          mlc++;\n        }\n      }\n      else if (!strcmp(key, \"mlcHHHV\")) {\n        if (check_file(path, line, &file)) {\n          strcpy(dataName[mlc], file);\n          strcpy(element[mlc], \"C12\");\n          dataType[mlc] = 1;\n          mlc++;\n        }\n      }\n      else if (!strcmp(key, \"mlcHHVV\")) {\n        if (check_file(path, line, &file)) {\n          strcpy(dataName[mlc], file);\n          strcpy(element[mlc], \"C13\");\n          dataType[mlc] = 1;\n          mlc++;\n        }\n      }\n      else if (!strcmp(key, \"mlcHVVV\")) {\n        if (check_file(path, line, &file)) {\n          strcpy(dataName[mlc], file);\n          strcpy(element[mlc], \"C23\");\n          dataType[mlc] = 1;\n          mlc++;\n        }\n      }\n      *nBands = mlc;\n    }\n    else if (type == POLSAR_DAT) {\n      if (!strcmp(key, \"dat\")) {\n        if (check_file(path, line, &file)) {\n          strcpy(dataName[dat], file);\n          dat++;\n        }\n      }\n      *nBands = dat;\n    }\n    else if (type == POLSAR_GRD) {\n      if (!strcmp(key, \"grdHHHH\")) {\n        if (check_file(path, line, &file)) {\n          strcpy(dataName[grd], file);\n          strcpy(element[grd], \"C11\");\n          dataType[grd] = 0;\n          grd++;\n        }\n      }\n      else if (!strcmp(key, \"grdHVHV\")) {\n        if (check_file(path, line, &file)) {\n          strcpy(dataName[grd], file);\n          strcpy(element[grd], \"C22\");\n          dataType[grd] = 0;\n          grd++;\n        }\n      }\n      else if (!strcmp(key, \"grdVVVV\")) {\n        if (check_file(path, line, &file)) {\n          strcpy(dataName[grd], file);\n          strcpy(element[grd], \"C33\");\n          dataType[grd] = 0;\n          grd++;\n        }\n      }\n      else if (!strcmp(key, \"grdHHHV\")) {\n        if (check_file(path, line, &file)) {\n          strcpy(dataName[grd], file);\n          strcpy(element[grd], \"C12\");\n          dataType[grd] = 1;\n          grd++;\n        }\n      }\n      else if (!strcmp(key, \"grdHHVV\")) {\n        if (check_file(path, line, &file)) {\n          strcpy(dataName[grd], file);\n          strcpy(element[grd], \"C13\");\n          dataType[grd] = 1;\n          grd++;\n        }\n      }\n      else if (!strcmp(key, \"grdHVVV\")) {\n        if (check_file(path, line, &file)) {\n          strcpy(dataName[grd], file);\n          strcpy(element[grd], \"C23\");\n          dataType[grd] = 1;\n          grd++;\n        }\n      }\n      *nBands = grd;\n    }\n    else if (type == POLSAR_HGT) {\n      if (!strcmp(key, \"hgt\")) {\n        if (check_file(path, line, &file)) {\n          strcpy(dataName[hgt], file);\n          strcpy(element[hgt], \"HH\");\n          dataType[hgt] = 0;\n          hgt++;\n        }\n      }\n      *nBands = hgt;\n    }\n    else if (type == INSAR_AMP) {\n      if (!strcmp(key, \"Slant Range Amplitude of Pass 1\")) {\n        if (check_file(path, line, &file)) {\n          strcpy(dataName[amp], file);\n          strcpy(element[amp], \"HH\");\n          dataType[amp] = 0;\n          amp++;\n        }\n      }\n      else if (!strcmp(key, \"Slant Range Amplitude of Pass 2\")) {\n        if (check_file(path, line, &file)) {\n          strcpy(dataName[amp], file);\n          strcpy(element[amp], \"HH\");\n          dataType[amp] = 0;\n          amp++;\n        }\n      }\n      *nBands = amp;\n    }\n    else if (type == INSAR_AMP_GRD) {\n      if (!strcmp(key, \"Ground Range Amplitude of Pass 1\")) {\n        if (check_file(path, line, &file)) {\n          strcpy(dataName[amp_grd], file);\n          strcpy(element[amp_grd], \"HH\");\n          dataType[amp_grd] = 0;\n          amp_grd++;\n        }\n      }\n      else if (!strcmp(key, \"Ground Range Amplitude of Pass 2\")) {\n        if (check_file(path, line, &file)) {\n          strcpy(dataName[amp_grd], file);\n          strcpy(element[amp_grd], \"HH\");\n          dataType[amp_grd] = 0;\n          amp_grd++;\n        }\n      }\n      *nBands = amp_grd;\n    }\n    else if (type == INSAR_INT) {\n      if (!strcmp(key, \"Slant Range Interferogram\")) {\n        if (check_file(path, line, &file)) {\n          strcpy(dataName[igram], file);\n          strcpy(element[igram], \"HH\");\n          dataType[igram] = 1;\n          igram++;\n        }\n      }\n      *nBands = igram;\n    }\n    else if (type == INSAR_INT_GRD) {\n      if (!strcmp(key, \"Ground Range Interferogram\")) {\n        if (check_file(path, line, &file)) {\n          strcpy(dataName[igram_grd], file);\n          strcpy(element[igram_grd], \"HH\");\n          dataType[igram_grd] = 1;\n          igram_grd++;\n        }\n      }\n      *nBands = igram_grd;\n    }\n    else if (type == INSAR_UNW) {\n      if (!strcmp(key, \"Slant Range Unwrapped Phase\")) {\n        if (check_file(path, line, &file)) {\n          strcpy(dataName[unw], file);\n          strcpy(element[unw], \"HH\");\n          dataType[unw] = 0;\n          unw++;\n        }\n      }\n      *nBands = unw;\n    }\n    else if (type == INSAR_UNW_GRD) {\n      if (!strcmp(key, \"Ground Range Unwrapped Phase\")) {\n        if (check_file(path, line, &file)) {\n          strcpy(dataName[unw_grd], file);\n          strcpy(element[unw_grd], \"HH\");\n          dataType[unw_grd] = 0;\n          unw_grd++;\n        }\n      }\n      *nBands = unw_grd;\n    }\n    else if (type == INSAR_COR) {\n      if (!strcmp(key, \"Slant Range Correlation\")) {\n        if (check_file(path, line, &file)) {\n          strcpy(dataName[cor], file);\n          strcpy(element[cor], \"HH\");\n          dataType[cor] = 0;\n          cor++;\n        }\n      }\n      *nBands = cor;\n    }\n    else if (type == INSAR_COR_GRD) {\n      if (!strcmp(key, \"Ground Range Correlation\")) {\n        if (check_file(path, line, &file)) {\n          strcpy(dataName[cor_grd], file);\n          strcpy(element[cor_grd], \"HH\");\n          dataType[cor_grd] = 0;\n          cor_grd++;\n        }\n      }\n      *nBands = cor_grd;\n    }\n    else if (type == INSAR_HGT_GRD) {\n      if (!strcmp(key, \"DEM Used in Ground Projection\")) {\n        if (check_file(path, line, &file)) {\n          strcpy(dataName[hgt_grd], file);\n          strcpy(element[hgt_grd], \"HH\");\n          dataType[hgt_grd] = 0;\n          hgt_grd++;\n        }\n      }\n      *nBands = hgt_grd;\n    }\n  }\n\n  FCLOSE(fp);\n  FREE(file);\n}\n\nuavsar_polsar *\nread_uavsar_polsar_params(const char *dataFile, uavsar_type_t type)\n{\n  uavsar_polsar *params = (uavsar_polsar *) MALLOC(sizeof(uavsar_polsar));\n\n  // Determine ID\n  char *dirName = (char *) MALLOC(sizeof(char) * 1024);\n  char *fileName = (char *) MALLOC(sizeof(char) * 1024);\n  split_dir_and_file(dataFile, dirName, fileName);\n  sprintf(params->id, \"%s\", stripExt(fileName));\n\n  // Read annotation file\n  char line[MAX_LINE], key[MAX_LINE], value[MAX_LINE];\n  FILE *fp = FOPEN(dataFile, \"r\");\n  while (fgets(line, MAX_LINE, fp)) {\n    if(!parse_annotation_line(line, key, value)) {\n      asfPrintWarning(\"Unable to parse line in annotation file: %s\", line);\n      continue;\n    }\n    if (!strcmp(key, \"\"))\n      continue;\n    if (!strcmp(key, \"Site Description\"))\n      strcpy(params->site, value);\n    if (!strcmp(key, \"Acquisition Mode\"))\n      strcpy(params->acquisition_mode, value);\n    if (type == POLSAR_SLC) {\n      params->type = POLSAR_SLC;\n      if (!strcmp(key, \"slc_mag.set_rows\"))\n        params->row_count = atoi(value);\n      else if (!strcmp(key, \"slc_mag.set_cols\"))\n        params->column_count = atoi(value);\n      else if (!strcmp(key, \"slc_mag.set_proj\"))\n        strcpy(params->projection, value);\n      else if (!strcmp(key, \"slc_mag.row_addr\"))\n        params->along_track_offset = atof(value);\n      else if (!strcmp(key, \"slc_mag.col_addr\"))\n        params->cross_track_offset = atof(value);\n      else if (!strcmp(key, \"slc_mag.row_mult\"))\n        params->azimuth_pixel_spacing = atof(value);\n      else if (!strcmp(key, \"slc_mag.col_mult\"))\n        params->range_pixel_spacing = atof(value);\n      else if (!strcmp(key, \"slc_mag.val_size\"))\n        params->bytes_per_pixel = atoi(value);\n      else if (!strcmp(key, \"slc_mag.val_frmt\"))\n        strcpy(params->value_format, value);\n      params->range_look_count = 1;\n      params->azimuth_look_count = 1;\n      if (!strcmp(key, \"SLC Data Units\"))\n        strcpy(params->data_units, value);\n    }\n    else if (type == POLSAR_MLC) {\n      params->type = POLSAR_MLC;\n      if (!strcmp(key, \"mlc_pwr.set_rows\"))\n        params->row_count = atoi(value);\n      else if (!strcmp(key, \"mlc_pwr.set_cols\"))\n        params->column_count = atoi(value);\n      else if (!strcmp(key, \"mlc_pwr.set_proj\"))\n        strcpy(params->projection, value);\n      else if (!strcmp(key, \"mlc_pwr.row_addr\"))\n        params->along_track_offset = atof(value);\n      else if (!strcmp(key, \"mlc_pwr.col_addr\"))\n        params->cross_track_offset = atof(value);\n      else if (!strcmp(key, \"mlc_pwr.row_mult\"))\n        params->azimuth_pixel_spacing = atof(value);\n      else if (!strcmp(key, \"mlc_pwr.col_mult\"))\n        params->range_pixel_spacing = atof(value);\n      else if (!strcmp(key, \"mlc_pwr.val_size\"))\n        params->bytes_per_pixel = atoi(value);\n      else if (!strcmp(key, \"mlc_pwr.val_frmt\"))\n        strcpy(params->value_format, value);\n      else if (!strcmp(key, \"Number of Range Looks in MLC\"))\n        params->range_look_count = atoi(value);\n      else if (!strcmp(key, \"Number of Azimuth Looks in MLC\"))\n        params->azimuth_look_count = atoi(value);\n      else if (!strcmp(key, \"MLC Data Units\"))\n        strcpy(params->data_units, value);\n      params->range_look_count = 1;\n      params->azimuth_look_count = 1;\n    }\n    else if (type == POLSAR_DAT) {\n      params->type = POLSAR_DAT;\n      if (!strcmp(key, \"dat.set_rows\"))\n        params->row_count = atoi(value);\n      else if (!strcmp(key, \"dat.set_cols\"))\n        params->column_count = atoi(value);\n      else if (!strcmp(key, \"dat.set_proj\"))\n        strcpy(params->projection, value);\n      else if (!strcmp(key, \"dat.row_addr\"))\n        params->along_track_offset = atof(value);\n      else if (!strcmp(key, \"dat.col_addr\"))\n        params->cross_track_offset = atof(value);\n      else if (!strcmp(key, \"dat.row_mult\"))\n        params->azimuth_pixel_spacing = atof(value);\n      else if (!strcmp(key, \"dat.col_mult\"))\n        params->range_pixel_spacing = atof(value);\n      else if (!strcmp(key, \"dat.val_size\"))\n        params->bytes_per_pixel = atoi(value);\n      else if (!strcmp(key, \"dat.val_frmt\"))\n        strcpy(params->value_format, value);\n      params->range_look_count = 1;\n      params->azimuth_look_count = 1;\n      strcpy(params->data_units, MAGIC_UNSET_STRING);\n    }\n    else if (type == POLSAR_GRD) {\n      params->type = POLSAR_GRD;\n      if (!strcmp(key, \"grd_pwr.set_rows\"))\n        params->row_count = atoi(value);\n      else if (!strcmp(key, \"grd_pwr.set_cols\"))\n        params->column_count = atoi(value);\n      else if (!strcmp(key, \"grd_pwr.set_proj\"))\n        strcpy(params->projection, value);\n      else if (!strcmp(key, \"grd_pwr.row_addr\"))\n        params->along_track_offset = atof(value);\n      else if (!strcmp(key, \"grd_pwr.col_addr\"))\n        params->cross_track_offset = atof(value);\n      else if (!strcmp(key, \"grd_pwr.row_mult\"))\n        params->azimuth_pixel_spacing = atof(value);\n      else if (!strcmp(key, \"grd_pwr.col_mult\"))\n        params->range_pixel_spacing = atof(value);\n      else if (!strcmp(key, \"grd_pwr.val_size\"))\n        params->bytes_per_pixel = atoi(value);\n      else if (!strcmp(key, \"grd_pwr.val_frmt\"))\n        strcpy(params->value_format, value);\n      else if (!strcmp(key, \"Number of Range Looks in MLC\"))\n        params->range_look_count = atoi(value);\n      else if (!strcmp(key, \"Number of Azimuth Looks in MLC\"))\n        params->azimuth_look_count = atoi(value);\n      else if (!strcmp(key, \"GRD Data Units\"))\n        strcpy(params->data_units, value);\n    }\n    else if (type == POLSAR_HGT) {\n      params->type = POLSAR_HGT;\n      if (!strcmp(key, \"hgt.set_rows\"))\n        params->row_count = atoi(value);\n      else if (!strcmp(key, \"hgt.set_cols\"))\n        params->column_count = atoi(value);\n      else if (!strcmp(key, \"hgt.set_proj\"))\n        strcpy(params->projection, value);\n      else if (!strcmp(key, \"hgt.row_addr\"))\n        params->along_track_offset = atof(value);\n      else if (!strcmp(key, \"hgt.col_addr\"))\n        params->cross_track_offset = atof(value);\n      else if (!strcmp(key, \"hgt.row_mult\"))\n        params->azimuth_pixel_spacing = atof(value);\n      else if (!strcmp(key, \"hgt.col_mult\"))\n        params->range_pixel_spacing = atof(value);\n      else if (!strcmp(key, \"hgt.val_size\"))\n        params->bytes_per_pixel = atoi(value);\n      else if (!strcmp(key, \"hgt.val_frmt\"))\n        strcpy(params->value_format, value);\n      params->range_look_count = 1;\n      params->azimuth_look_count = 1;\n      if (!strcmp(key, \"HGT Data Units\"))\n        strcpy(params->data_units, value);\n    }\n    if (!strcmp(key, \"set_hddr\"))\n      params->header_bytes = atoi(value);\n    else if (!strcmp(key, \"set_tail\"))\n      params->tail_bytes = atoi(value);\n    else if (!strcmp(key, \"set_plat\"))\n      params->lat_peg_point = atof(value);\n    else if (!strcmp(key, \"set_plon\"))\n      params->lon_peg_point = atof(value);\n    else if (!strcmp(key, \"set_phdg\"))\n      params->head_peg_point = atof(value);\n    else if (!strcmp(key, \"val_endi\"))\n      strcpy(params->endianess, value);\n    else if (!strcmp(key, \"val_mult\"))\n      params->data_scale = atof(value);\n    else if (!strcmp(key, \"val_addr\"))\n      params->data_shift = atof(value);\n    else if (!strcmp(key, \"val_minv\"))\n      params->min_value = atof(value);\n    else if (!strcmp(key, \"val_maxv\"))\n      params->max_value = atof(value);\n    else if (!strcmp(key, \"Center Wavelength\"))\n      params->wavelength = atof(value);\n    else if (!strcmp(key, \"Ellipsoid Semi-major Axis\"))\n      params->semi_major = atof(value);\n    else if (!strcmp(key, \"Ellipsoid Eccentricity Squared\"))\n      params->eccentricity = atof(value);\n    else if (!strcmp(key, \"Look Direction\"))\n      strcpy(params->look_direction, value);\n    else if (!strcmp(key, \"Range Spacing per Bin\"))\n      params->range_spacing = atof(value);\n    else if (!strcmp(key, \"Azimuth Spacing\"))\n      params->azimuth_spacing = atof(value);\n    else if (!strcmp(key, \"Image Starting Range\"))\n      params->slant_range_first_pixel = atof(value);\n    else if (!strcmp(key, \"Global Average Yaw\"))\n      params->yaw = atof(value);\n    else if (!strcmp(key, \"Global Average Pitch\"))\n      params->pitch = atof(value);\n    else if (!strcmp(key, \"Global Average Roll\"))\n      params->roll = atof(value);\n    else if (!strcmp(key, \"Global Average Altitude\"))\n      params->altitude = atof(value);\n    else if (!strcmp(key, \"Average GPS Altitude\"))\n      params->altitude = atof(value);\n    else if (!strcmp(key, \"Global Average Terrain Height\"))\n      params->terrain_height = atof(value);\n    else if (!strcmp(key, \"Global Average Squint Angle\"))\n      params->squint_angle = atof(value);\n    else if (!strcmp(key, \"Pulse Length\"))\n      params->pulse_length = atof(value);\n    else if (!strcmp(key, \"Steering Angle\"))\n      params->steering_angle = atof(value);\n    else if (!strcmp(key, \"Bandwidth\"))\n      params->bandwidth = atof(value);\n    else if (!strcmp(key, \"Approximate Upper Left Latitude\"))\n      params->lat_upper_left = atof(value);\n    else if (!strcmp(key, \"Approximate Upper Left Longitude\"))\n      params->lon_upper_left = atof(value);\n    else if (!strcmp(key, \"Approximate Upper Right Latitude\"))\n      params->lat_upper_right = atof(value);\n    else if (!strcmp(key, \"Approximate Upper Right Longitude\"))\n      params->lon_upper_right = atof(value);\n    else if (!strcmp(key, \"Approximate Lower Left Latitude\"))\n      params->lat_lower_left = atof(value);\n    else if (!strcmp(key, \"Approximate Lower Left Longitude\"))\n      params->lon_lower_left = atof(value);\n    else if (!strcmp(key, \"Approximate Lower Right Latitude\"))\n      params->lat_lower_right = atof(value);\n    else if (!strcmp(key, \"Approximate Lower Right Longitude\"))\n      params->lon_lower_right = atof(value);\n    else if (!strcmp(key, \"Date of Acquisition\"))\n      strcpy(params->acquisition_date, value);\n    else if (!strcmp(key, \"Processor Version Number\"))\n      strcpy(params->processor, value);\n  }\n  FCLOSE(fp);\n\n  return params;\n}\n\nuavsar_insar *\nread_uavsar_insar_params(const char *dataFile, uavsar_type_t type)\n{\n  uavsar_insar *params = (uavsar_insar *) MALLOC(sizeof(uavsar_insar));\n  char time1[50], time2[50];\n\n  // Determine ID\n  char *dirName = (char *) MALLOC(sizeof(char) * 1024);\n  char *fileName = (char *) MALLOC(sizeof(char) * 1024);\n  split_dir_and_file(dataFile, dirName, fileName);\n  sprintf(params->id, \"%s\", stripExt(fileName));\n\n  // Read annotation file\n  char line[MAX_LINE], key[MAX_LINE], value[MAX_LINE];\n  FILE *fp = FOPEN(dataFile, \"r\");\n  while (fgets(line, MAX_LINE, fp)) {\n    if(!parse_annotation_line(line, key, value)) {\n      asfPrintWarning(\"Unable to parse line in annotation file: %s\", line);\n      continue;\n    }\n    if(!strcmp(key, \"\"))\n      continue;\n    if (!strcmp(key, \"Site Description\"))\n      strcpy(params->site, value);\n    if (!strcmp(key, \"Processing Mode\"))\n      strcpy(params->processing_mode, value);\n    if (!strcmp(key, \"Polarization\"))\n      strcpy(params->polarization, value);\n    if (!strcmp(key, \"Number of Looks in Range\"))\n      params->range_look_count = atoi(value);\n    if (!strcmp(key, \"Number of Looks in Azimuth\"))\n      params->azimuth_look_count = atoi(value);\n    if (type == INSAR_INT) {\n      params->type = INSAR_INT;\n      if (!strcmp(key, \"Interferogram Bytes Per Pixel\"))\n        params->bytes_per_pixel = atoi(value);\n      else if (!strcmp(key, \"Interferogram Pixel Format\"))\n        strcpy(params->value_format, value);\n      else if (!strcmp(key, \"Interferogram Units\"))\n        strcpy(params->data_units, value);\n    }\n    else if (type == INSAR_UNW) {\n      params->type = INSAR_UNW;\n      if (!strcmp(key, \"Unwrapped Phase Bytes Per Pixel\"))\n        params->bytes_per_pixel = atoi(value);\n      else if (!strcmp(key, \"Unwrapped Phase Pixel Format\"))\n        strcpy(params->value_format, value);\n      else if (!strcmp(key, \"Unwrapped Phase Units\"))\n        strcpy(params->data_units, value);\n    }\n    else if (type == INSAR_COR) {\n      params->type = INSAR_COR;\n      if (!strcmp(key, \"Correlation Bytes Per Pixel\"))\n        params->bytes_per_pixel = atoi(value);\n      else if (!strcmp(key, \"Correlation Pixel Format\"))\n        strcpy(params->value_format, value);\n      else if (!strcmp(key, \"Correlation Units\"))\n        strcpy(params->data_units, value);\n    }\n    else if (type == INSAR_AMP) {\n      params->type = INSAR_AMP;\n      if (!strcmp(key, \"Amplitude Bytes Per Pixel\"))\n        params->bytes_per_pixel = atoi(value);\n      else if (!strcmp(key, \"Amplitude Pixel Format\"))\n        strcpy(params->value_format, value);\n      else if (!strcmp(key, \"Amplitude Units\"))\n        strcpy(params->data_units, value);\n    }\n    if (type >= INSAR_AMP && type <= INSAR_COR) {\n      if (!strcmp(key, \"Slant Range Data Azimuth Lines\"))\n        params->row_count = atoi(value);\n      else if (!strcmp(key, \"Slant Range Data Range Samples\"))\n        params->column_count = atoi(value);\n      else if (!strcmp(key, \"slt.set_proj\"))\n        strcpy(params->projection, value);\n      else if (!strcmp(key, \"slt.row_addr\"))\n        params->along_track_offset = atof(value);\n      else if (!strcmp(key, \"slt.col_addr\"))\n        params->cross_track_offset = atof(value);\n      else if (!strcmp(key, \"Slant Range Data at Near Range\")) {\n        params->slant_range_first_pixel = atof(value);\n        params->slant_range_first_pixel /= 1000.0;\n      }\n      else if (!strcmp(key, \"Slant Range Data Azimuth Spacing\"))\n        params->azimuth_pixel_spacing = atof(value);\n      else if (!strcmp(key, \"Slant Range Data Range Spacing\"))\n        params->range_pixel_spacing = atof(value);\n    }\n    else if (type >= INSAR_AMP_GRD && type <= INSAR_HGT_GRD) {\n      if (!strcmp(key, \"Ground Range Data Latitude Lines\"))\n        params->row_count = atoi(value);\n      else if (!strcmp(key, \"Ground Range Data Longitude Samples\"))\n        params->column_count = atoi(value);\n      else if (!strcmp(key, \"grd.set_proj\"))\n        strcpy(params->projection, value);\n      else if (!strcmp(key, \"grd.row_addr\"))\n        params->along_track_offset = atof(value);\n      else if (!strcmp(key, \"grd.col_addr\"))\n        params->cross_track_offset = atof(value);\n      else if (!strcmp(key, \"Ground Range Data Latitude Spacing\"))\n        params->azimuth_pixel_spacing = atof(value);\n      else if (!strcmp(key, \"Ground Range Data Longitude Spacing\"))\n        params->range_pixel_spacing = atof(value);\n    }\n    if (type == INSAR_INT_GRD) {\n      params->type = INSAR_INT_GRD;\n      if (!strcmp(key, \"Interferogram Bytes Per Pixel\"))\n        params->bytes_per_pixel = atoi(value);\n      else if (!strcmp(key, \"Interferogram Pixel Format\"))\n        strcpy(params->value_format, value);\n      else if (!strcmp(key, \"Interferogram Units\"))\n        strcpy(params->data_units, value);\n    }\n    else if (type == INSAR_UNW_GRD) {\n      params->type = INSAR_UNW_GRD;\n      if (!strcmp(key, \"Unwrapped Phase Bytes Per Pixel\"))\n        params->bytes_per_pixel = atoi(value);\n      else if (!strcmp(key, \"Unwrapped Phase Pixel Format\"))\n        strcpy(params->value_format, value);\n      else if (!strcmp(key, \"Unwrapped Phase Units\"))\n        strcpy(params->data_units, value);\n    }\n    else if (type == INSAR_COR_GRD) {\n      params->type = INSAR_COR_GRD;\n      if (!strcmp(key, \"Correlation Bytes Per Pixel\"))\n        params->bytes_per_pixel = atoi(value);\n      else if (!strcmp(key, \"Correlation Pixel Format\"))\n        strcpy(params->value_format, value);\n      else if (!strcmp(key, \"Correlation Units\"))\n        strcpy(params->data_units, value);\n    }\n    else if (type == INSAR_AMP_GRD) {\n      params->type = INSAR_AMP_GRD;\n      if (!strcmp(key, \"Amplitude Bytes Per Pixel\"))\n        params->bytes_per_pixel = atoi(value);\n      else if (!strcmp(key, \"Amplitude Pixel Format\"))\n        strcpy(params->value_format, value);\n      else if (!strcmp(key, \"Amplitude Units\"))\n        strcpy(params->data_units, value);\n    }\n    else if (type == INSAR_HGT_GRD) {\n      params->type = INSAR_HGT_GRD;\n      if (!strcmp(key, \"DEM Bytes Per Pixel\"))\n        params->bytes_per_pixel = atoi(value);\n      else if (!strcmp(key, \"DEM Pixel Format\"))\n        strcpy(params->value_format, value);\n      else if (!strcmp(key, \"DEM Units\"))\n        strcpy(params->data_units, value);\n    }\n    if (!strcmp(key, \"set_hddr\"))\n      params->header_bytes = atoi(value);\n    else if (!strcmp(key, \"set_tail\"))\n      params->tail_bytes = atoi(value);\n    else if (!strcmp(key, \"set_plat\"))\n      params->lat_peg_point = atof(value);\n    else if (!strcmp(key, \"set_plon\"))\n      params->lon_peg_point = atof(value);\n    else if (!strcmp(key, \"set_phdg\"))\n      params->head_peg_point = atof(value);\n    else if (!strcmp(key, \"val_endi\"))\n      strcpy(params->endianess, value);\n    else if (!strcmp(key, \"val_mult\"))\n      params->data_scale = atof(value);\n    else if (!strcmp(key, \"val_addr\"))\n      params->data_shift = atof(value);\n    else if (!strcmp(key, \"val_minv\"))\n      params->min_value = atof(value);\n    else if (!strcmp(key, \"val_maxv\"))\n      params->max_value = atof(value);\n    else if (!strcmp(key, \"Center Wavelength\"))\n      params->wavelength = atof(value);\n    else if (!strcmp(key, \"Ellipsoid Semi-major Axis\"))\n      params->semi_major = atof(value);\n    else if (!strcmp(key, \"Ellipsoid Eccentricity Squared\"))\n      params->eccentricity = atof(value);\n    else if (!strcmp(key, \"Look Direction\"))\n      strcpy(params->look_direction, value);\n    else if (!strcmp(key, \"Range Spacing per Bin\"))\n      params->range_spacing = atof(value);\n    else if (!strcmp(key, \"Azimuth Spacing\"))\n      params->azimuth_spacing = atof(value);\n    else if (!strcmp(key, \"Image Starting Range\"))\n      params->slant_range_first_pixel = atof(value);\n    else if (!strcmp(key, \"Global Average Yaw\"))\n      params->yaw = atof(value);\n    else if (!strcmp(key, \"Global Average Pitch\"))\n      params->pitch = atof(value);\n    else if (!strcmp(key, \"Global Average Roll\"))\n      params->roll = atof(value);\n    else if (!strcmp(key, \"Global Average Altitude\"))\n      params->altitude = atof(value);\n    else if (!strcmp(key, \"Average GPS Altitude\"))\n      params->altitude = atof(value);\n    else if (!strcmp(key, \"Global Average Terrain Height\"))\n      params->terrain_height = atof(value);\n    else if (!strcmp(key, \"Global Average Squint Angle\"))\n      params->squint_angle = atof(value);\n    else if (!strcmp(key, \"Pulse Length\"))\n      params->pulse_length = atof(value);\n    else if (!strcmp(key, \"Steering Angle\"))\n      params->steering_angle = atof(value);\n    else if (!strcmp(key, \"Bandwidth\"))\n      params->bandwidth = atof(value);\n    else if (!strcmp(key, \"Approximate Upper Left Latitude\")) {\n      if (strcmp_case(value, \"N/A\") == 0)\n        params->lat_upper_left = MAGIC_UNSET_DOUBLE;\n      else\n        params->lat_upper_left = atof(value);\n    }\n    else if (!strcmp(key, \"Approximate Upper Left Longitude\")) {\n      if (strcmp_case(value, \"N/A\") == 0)\n        params->lon_upper_left = MAGIC_UNSET_DOUBLE;\n      else\n        params->lon_upper_left = atof(value);\n    }\n    else if (!strcmp(key, \"Approximate Upper Right Latitude\")) {\n      if (strcmp_case(value, \"N/A\") == 0)\n        params->lat_upper_right = MAGIC_UNSET_DOUBLE;\n      else\n        params->lat_upper_right = atof(value);\n    }\n    else if (!strcmp(key, \"Approximate Upper Right Longitude\")) {\n      if (strcmp_case(value, \"N/A\") == 0)\n        params->lon_upper_right = MAGIC_UNSET_DOUBLE;\n      else\n        params->lon_upper_right = atof(value);\n    }\n    else if (!strcmp(key, \"Approximate Lower Left Latitude\")) {\n      if (strcmp_case(value, \"N/A\") == 0)\n        params->lat_lower_left = MAGIC_UNSET_DOUBLE;\n      else\n        params->lat_lower_left = atof(value);\n    }\n    else if (!strcmp(key, \"Approximate Lower Left Longitude\")) {\n      if (strcmp_case(value, \"N/A\") == 0)\n        params->lon_lower_left = MAGIC_UNSET_DOUBLE;\n      else\n        params->lon_lower_left = atof(value);\n    }\n    else if (!strcmp(key, \"Approximate Lower Right Latitude\")) {\n      if (strcmp_case(value, \"N/A\") == 0)\n        params->lat_lower_right = MAGIC_UNSET_DOUBLE;\n      else\n        params->lat_lower_right = atof(value);\n    }\n    else if (!strcmp(key, \"Approximate Lower Right Longitude\")) {\n      if (strcmp_case(value, \"N/A\") == 0)\n        params->lon_lower_right = MAGIC_UNSET_DOUBLE;\n      else\n        params->lon_lower_right = atof(value);\n    }\n    else if (!strcmp(key, \"Time of Acquisition for Pass 1\"))\n      strcpy(time1, value);\n    else if (!strcmp(key, \"Time of Acquisition for Pass 2\"))\n      strcpy(time2, value);\n    else if (!strcmp(key, \"Processor Version Number\"))\n      strcpy(params->processor, value);\n  }\n  FCLOSE(fp);\n\n  sprintf(params->acquisition_date, \"%s, %s\", time1, time2);\n\n  return params;\n}\n\nint sign(char byteBuf)\n{\n  if (byteBuf < 0)\n    return -1;\n  else\n    return 1;\n}\n\nchar *check_data_type(const char *inFileName)\n{\n  char line[MAX_LINE], key[MAX_LINE], value[MAX_LINE];\n  char *type = (char *) MALLOC(sizeof(char)*25);\n  FILE *fp = FOPEN(inFileName, \"r\");\n  while (fgets(line, MAX_LINE, fp)) {\n    if(!parse_annotation_line(line, key, value)) {\n      asfPrintWarning(\"Unable to parse line in annotation file: %s\", line);\n      continue;\n    }\n    if (!strcmp(key, \"\"))\n      continue;\n    if (!strcmp(key, \"Acquisition Mode\"))\n      strcpy(type, value);\n    else if (!strcmp(key, \"Processing Mode\"))\n      strcpy(type, value);\n    else if (strcmp_case(type, \"RPI\") == 0)\n      sprintf(type, \"InSAR\");\n  }\n  FCLOSE(fp);\n\n  return type;\n}\n\nvoid import_uavsar(const char *inFileName, int line, int sample, int width,\n\t\t   int height, radiometry_t radiometry,\n\t\t   const char *data_type, const char *outBaseName) {\n\n  // UAVSAR comes in two flavors: InSAR and PolSAR\n  // Things look similar to AirSAR data, just organized a little different.\n  // There does not seem to be a consistent identifier in the annotation file,\n  // that would allow us to easily identify the data set as UAVSAR. No mention\n  // of UAVSAR whatsoever.\n\n  // The data can come in a large variety of flavors (single look versus multi-\n  // look, derived magnitude and phase, etc.). I assume we can take anything or\n  // nothing from this menu. The different files have different dimensions,\n  // so we will need to generate several output images to accommodate that.\n\n  // PolSAR data\n  // slc - Single look complex slant range data \n  // mlc - Multilook cross product slant range data\n  // dat - Compressed Stokes matrix of multilooked data\n  // grd - Ground range projected (equi-rectangular) and multilooked data\n  // hgt - Digital elevation model projected in projection\n  // slc_mag and slc_phase - 8 bytes per pixel derived from slc\n  // mlc_mag and mlc_phase - 8 bytes per pixel derived from mlc\n\n  // InSAR data\n  // int - Slant range interferogram\n  // unw - Slant range unwrapped phase\n  // cor - Slant range correlation\n  // amp - Slant range amplitudes\n  // int_grd - Ground range interferogram\n  // unw_grd - Ground range unwrapped phase\n  // cor_grd - Ground range correlation\n  // amp_grd - Ground range amplitudes\n  // hgt_grd - Digital elevation model in ground projection\n\n  FILE *fpIn, *fpOut;\n  int ii, kk, ll, nn, pp, nBands, ns, *dataType, product_count;\n  int multi = FALSE;\n  float *floatAmp, *floatPhase, *floatAmpBuf, *amp, re, im;\n  float *floatComplexReal, *floatComplexImag;\n  float *floatComplexBuf;\n  char **dataName, **element, **product, tmp[50];\n  char *type;\n  char *outName = (char *) MALLOC(sizeof(char)*(strlen(outBaseName)+15));\n  uavsar_polsar *polsar_params;\n  uavsar_insar *insar_params;\n  meta_parameters *metaIn, *metaOut;\n\n  type = check_data_type(inFileName);\n  asfPrintStatus(\"   Data type: %s\\n\", type);\n  product = get_uavsar_products(data_type, type, &product_count);\n  if (product_count > 1)\n    multi = TRUE;\n\n  for (pp = 0; pp < product_count; pp++) {\n\n    // InSAR data\n    // Ground range interferogram\n    if (strcmp_case(type, \"InSAR\") == 0 && \n\tstrcmp_case(product[pp], \"INT_GRD\") == 0) {\n      get_uavsar_file_names(inFileName, INSAR_INT_GRD, &dataName, &element,\n\t\t\t    &dataType, &nBands);\n      if (!nBands) {\n\tasfPrintWarning(\"Ground range interferogram does not exist. \"\n\t\t\t\"Will skip the ingest.\\n\");\n\tcontinue;\n      }\n      insar_params = \n\tread_uavsar_insar_params(inFileName, INSAR_INT_GRD);\n      metaIn = uavsar_insar2meta(insar_params);\n      metaOut = uavsar_insar2meta(insar_params);\n      ns = metaIn->general->sample_count;\n      nn = 0;\n      floatAmp = (float *) CALLOC(ns, sizeof(float));\n      floatPhase = (float *) CALLOC(ns, sizeof(float));\n      floatComplexBuf = (float *) CALLOC(2*ns, sizeof(float));\n      outName = (char *) MALLOC(sizeof(char)*(strlen(outBaseName)+15));\n      metaOut->general->band_count = 2;\n      if (multi)\n\toutName = appendToBasename(outBaseName, \"_int_grd.img\");\n      else\n\toutName = appendExt(outBaseName, \".img\");\n      asfPrintStatus(\"\\nGround range interferogram:\\n\");\n      fpOut = FOPEN(outName, \"wb\");\n      char *filename = get_filename(dataName[nn]);\n      asfPrintStatus(\"Ingesting %s ...\\n\", filename);\n      FREE(filename);\n      fpIn = FOPEN(dataName[nn], \"rb\");\n      sprintf(metaOut->general->bands, \"INTERFEROGRAM_AMP,INTERFEROGRAM_PHASE\");\n      for (ii=0; ii<metaIn->general->line_count; ii++) {\n\tmetaIn->general->sample_count = 2*ns;\n\tget_float_line(fpIn, metaIn, ii, floatComplexBuf);\n\tfor (kk=0; kk<ns; kk++) {\n\t  re = floatComplexBuf[kk*2];\n\t  im = floatComplexBuf[kk*2+1];\n\t  ieee_big32(re);\n\t  ieee_big32(im);\n\t  floatAmp[kk] = hypot(re,im);\n\t  floatPhase[kk] = atan2_check(im,re);\n\t}\n\tput_band_float_line(fpOut, metaOut, 0, ii, floatAmp);\n\tput_band_float_line(fpOut, metaOut, 1, ii, floatPhase);\n\tasfLineMeter(ii, metaIn->general->line_count);\n      }\n      FCLOSE(fpIn);\n      FCLOSE(fpOut);\n      meta_write(metaOut, outName);\n      FREE(floatAmp);\n      FREE(floatPhase);\n      FREE(floatComplexBuf);\n      FREE(outName);\n      meta_free(metaIn);\n      meta_free(metaOut);\n      FREE(insar_params);\n    }\n    \n    // Ground range unwrapped phase\n    if (strcmp_case(type, \"InSAR\") == 0 &&\n\tstrcmp_case(product[pp], \"UNW_GRD\") == 0) {\n      get_uavsar_file_names(inFileName, INSAR_UNW_GRD, &dataName, &element,\n\t\t\t    &dataType, &nBands);\n      if (!nBands) {\n\tasfPrintWarning(\"Ground range unwrapped phase does not exist. \"\n\t\t\t\"Will skip the ingest.\\n\");\n\tcontinue;\n      }\n      insar_params = \n\tread_uavsar_insar_params(inFileName, INSAR_UNW_GRD);\n      metaIn = uavsar_insar2meta(insar_params);\n      metaOut = uavsar_insar2meta(insar_params);\n      ns = metaOut->general->sample_count;\n      nn = 0;\n      floatAmpBuf = (float *) MALLOC(sizeof(float)*ns);\n      outName = (char *) MALLOC(sizeof(char)*(strlen(outBaseName)+15));\n      if (multi)\n\toutName = appendToBasename(outBaseName, \"_unw_grd.img\");\n      else\n\toutName = appendExt(outBaseName, \".img\");\n      asfPrintStatus(\"\\nGround range unwrapped phase:\\n\");\n      char *filename = get_filename(dataName[nn]);\n      asfPrintStatus(\"Ingesting %s ...\\n\", filename);\n      FREE(filename);\n      fpIn = FOPEN(dataName[nn], \"rb\");\n      fpOut = FOPEN(outName, \"wb\");\n      strcpy(metaOut->general->bands, \"UNWRAPPED_PHASE\");\n      for (ii=0; ii<metaIn->general->line_count; ii++) {\n\tget_float_line(fpIn, metaIn, ii, floatAmpBuf);\n\tfor (kk=0; kk<metaIn->general->sample_count; kk++)\n\t  ieee_big32(floatAmpBuf[kk]);\n\tput_float_line(fpOut, metaOut, ii, floatAmpBuf);\n      asfLineMeter(ii, metaIn->general->line_count);\n      }\n      FCLOSE(fpIn);\n      FCLOSE(fpOut);\n      meta_write(metaOut, outName);\n      FREE(floatAmpBuf);\n      FREE(outName);\n      meta_free(metaIn);\n      meta_free(metaOut);\n      FREE(insar_params);\n    }    \n    \n    // Ground range correlation image\n    if (strcmp_case(type, \"InSAR\") == 0 &&\n\tstrcmp_case(product[pp], \"COR_GRD\") == 0) {\n      get_uavsar_file_names(inFileName, INSAR_COR_GRD, &dataName, &element,\n\t\t\t    &dataType, &nBands);\n      if (!nBands) {\n\tasfPrintWarning(\"Ground range correlation image does not exist. \"\n\t\t\t\"Will skip the ingest.\\n\");\n\tcontinue;\n      }\n      insar_params = \n\tread_uavsar_insar_params(inFileName, INSAR_COR_GRD);\n      metaIn = uavsar_insar2meta(insar_params);\n      metaOut = uavsar_insar2meta(insar_params);\n      ns = metaOut->general->sample_count;\n      nn = 0;\n      floatAmpBuf = (float *) MALLOC(sizeof(float)*ns);\n      if (multi)\n\toutName = appendToBasename(outBaseName, \"_cor_grd.img\");\n      else\n\toutName = appendExt(outBaseName, \".img\");\n      asfPrintStatus(\"\\nGround range correlation image:\\n\");\n      char *filename = get_filename(dataName[nn]);\n      asfPrintStatus(\"Ingesting %s ...\\n\", filename);\n      FREE(filename);\n      fpIn = FOPEN(dataName[nn], \"rb\");\n      fpOut = FOPEN(outName, \"wb\");\n      strcpy(metaOut->general->bands, \"COHERENCE\");\n      for (ii=0; ii<metaIn->general->line_count; ii++) {\n\tget_float_line(fpIn, metaIn, ii, floatAmpBuf);\n\tfor (kk=0; kk<metaIn->general->sample_count; kk++)\n\t  ieee_big32(floatAmpBuf[kk]);\n\tput_float_line(fpOut, metaOut, ii, floatAmpBuf);\n\tasfLineMeter(ii, metaIn->general->line_count);\n      }\n      FCLOSE(fpIn);\n      FCLOSE(fpOut);\n      meta_write(metaOut, outName);\n      FREE(floatAmpBuf);\n      FREE(outName);\n      meta_free(metaIn);\n      meta_free(metaOut);\n      FREE(insar_params);\n    }    \n    \n    // Ground range amplitude images\n    if (strcmp_case(type, \"InSAR\") == 0 &&\n\tstrcmp_case(product[pp], \"AMP_GRD\") == 0) {\n      get_uavsar_file_names(inFileName, INSAR_AMP_GRD, &dataName, &element,\n\t\t\t    &dataType, &nBands);\n      if (!nBands) {\n\tasfPrintWarning(\"Ground range amplitude images does not exist. \"\n\t\t\t\"Will skip the ingest.\\n\");\n\tcontinue;\n      }\n      insar_params = \n\tread_uavsar_insar_params(inFileName, INSAR_AMP_GRD);\n      metaIn = uavsar_insar2meta(insar_params);\n      metaOut = uavsar_insar2meta(insar_params);\n      metaOut->general->band_count = 2;\n      ns = metaOut->general->sample_count;\n      nn = 0;\n      floatAmpBuf = (float *) MALLOC(sizeof(float)*ns);\n      outName = (char *) MALLOC(sizeof(char)*(strlen(outBaseName)+15));\n      if (multi)\n\toutName = appendToBasename(outBaseName, \"_amp_grd.img\");\n      else\n\toutName = appendExt(outBaseName, \".img\");\n      fpOut = FOPEN(outName, \"wb\");\n      strcpy(metaOut->general->bands, \"AMP1,AMP2\");\n      asfPrintStatus(\"\\nGround range amplitude images:\\n\");\n      for (nn=0; nn<nBands; nn++) {\n        char *filename = get_filename(dataName[nn]);\n        asfPrintStatus(\"Ingesting %s ...\\n\", filename);\n        FREE(filename);\n\tfpIn = FOPEN(dataName[nn], \"rb\");\n\tfor (ii=0; ii<metaIn->general->line_count; ii++) {\n\t  get_float_line(fpIn, metaIn, ii, floatAmpBuf);\n\t  for (kk=0; kk<metaIn->general->sample_count; kk++)\n\t    ieee_big32(floatAmpBuf[kk]);\n\t  put_band_float_line(fpOut, metaOut, nn, ii, floatAmpBuf);\n\t  asfLineMeter(ii, metaIn->general->line_count);\n\t}\n\tFCLOSE(fpIn);\n      }\n      FCLOSE(fpOut);\n      meta_write(metaOut, outName);\n      FREE(floatAmpBuf);\n      FREE(outName);\n      meta_free(metaIn);\n      meta_free(metaOut);\n      FREE(insar_params);\n    }    \n    \n    // Ground range digital elevation model\n    if (strcmp_case(type, \"InSAR\") == 0 &&\n\tstrcmp_case(product[pp], \"HGT_GRD\") == 0) {\n      get_uavsar_file_names(inFileName, INSAR_HGT_GRD, &dataName, &element,\n\t\t\t    &dataType, &nBands);\n      if (!nBands) {\n\tasfPrintWarning(\"Ground range digital elevation model does not exist. \"\n\t\t\t\"Will skip the ingest.\\n\");\n\tcontinue;\n      }\n      insar_params = \n\tread_uavsar_insar_params(inFileName, INSAR_HGT_GRD);\n      metaIn = uavsar_insar2meta(insar_params);\n      metaOut = uavsar_insar2meta(insar_params);\n      ns = metaOut->general->sample_count;\n      nn = 0;\n      floatAmpBuf = (float *) MALLOC(sizeof(float)*ns);\n      outName = (char *) MALLOC(sizeof(char)*(strlen(outBaseName)+15));\n      if (multi)\n\toutName = appendToBasename(outBaseName, \"_hgt_grd.img\");\n      else\n\toutName = appendExt(outBaseName, \".img\");\n      fpOut = FOPEN(outName, \"wb\");\n      strcpy(metaOut->general->bands, \"HEIGHT\");\n      asfPrintStatus(\"\\nGround range digital elevation model:\\n\");\n      for (nn=0; nn<nBands; nn++) {\n        char *filename = get_filename(dataName[nn]);\n        asfPrintStatus(\"Ingesting %s ...\\n\", filename);\n        FREE(filename);\n\tfpIn = FOPEN(dataName[nn], \"rb\");\n\tfor (ii=0; ii<metaIn->general->line_count; ii++) {\n\t  get_float_line(fpIn, metaIn, ii, floatAmpBuf);\n\t  for (kk=0; kk<metaIn->general->sample_count; kk++)\n\t    ieee_big32(floatAmpBuf[kk]);\n\t  put_band_float_line(fpOut, metaOut, nn, ii, floatAmpBuf);\n\t  asfLineMeter(ii, metaIn->general->line_count);\n\t}\n\tFCLOSE(fpIn);\n      }\n      FCLOSE(fpOut);\n      meta_write(metaOut, outName);\n      FREE(floatAmpBuf);\n      FREE(outName);\n      meta_free(metaIn);\n      meta_free(metaOut);\n      FREE(insar_params);\n    }\n    \n    // Slant range interferogram\n    if (strcmp_case(type, \"InSAR\") == 0 &&\n\tstrcmp_case(product[pp], \"INT\") == 0) {\n      get_uavsar_file_names(inFileName, INSAR_INT, &dataName, &element,\n\t\t\t    &dataType, &nBands);\n      if (!nBands) {\n\tasfPrintWarning(\"Slant range interferogram does not exist. \"\n\t\t\t\"Will skip the ingest.\\n\");\n\tcontinue;\n      }\n      insar_params = \n\tread_uavsar_insar_params(inFileName, INSAR_INT);\n      metaIn = uavsar_insar2meta(insar_params);\n      metaOut = uavsar_insar2meta(insar_params);\n      ns = metaIn->general->sample_count;\n      nn = 0;\n      floatAmp = (float *) CALLOC(ns, sizeof(float));\n      floatPhase = (float *) CALLOC(ns, sizeof(float));\n      floatComplexBuf = (float *) CALLOC(2*ns, sizeof(float));\n      outName = (char *) MALLOC(sizeof(char)*(strlen(outBaseName)+15));\n      if (multi)\n\toutName = appendToBasename(outBaseName, \"_int.img\");\n      else\n\toutName = appendExt(outBaseName, \".img\");\n      metaOut->general->band_count = 2;\n      if (multi)\n\toutName = appendToBasename(outBaseName, \"_int.img\");\n      else\n\toutName = appendExt(outBaseName, \".img\");\n      asfPrintStatus(\"\\nSlant range interferogram:\\n\");\n      fpOut = FOPEN(outName, \"wb\");\n      char *filename = get_filename(dataName[nn]);\n      asfPrintStatus(\"Ingesting %s ...\\n\", filename);\n      FREE(filename);\n      fpIn = FOPEN(dataName[nn], \"rb\");\n      sprintf(metaOut->general->bands, \"INTERFEROGRAM_AMP,INTERFEROGRAM_PHASE\");\n      for (ii=0; ii<metaIn->general->line_count; ii++) {\n\tmetaIn->general->sample_count = 2*ns;\n\tget_float_line(fpIn, metaIn, ii, floatComplexBuf);\n\tfor (kk=0; kk<ns; kk++) {\n\t  re = floatComplexBuf[kk*2];\n\t  im = floatComplexBuf[kk*2+1];\n\t  ieee_big32(re);\n\t  ieee_big32(im);\n\t  floatAmp[kk] = hypot(re,im);\n\t  floatPhase[kk] = atan2_check(im,re);\n\t}\n\tput_band_float_line(fpOut, metaOut, 0, ii, floatAmp);\n\tput_band_float_line(fpOut, metaOut, 1, ii, floatPhase);\n\tasfLineMeter(ii, metaIn->general->line_count);\n      }\n      FCLOSE(fpIn);\n      FCLOSE(fpOut);\n      meta_write(metaOut, outName);\n      FREE(floatAmp);\n      FREE(floatPhase);\n      FREE(floatComplexBuf);\n      FREE(outName);\n      meta_free(metaIn);\n      meta_free(metaOut);\n      FREE(insar_params);\n    }\n    \n    // Slant range unwrapped phase\n    if (strcmp_case(type, \"InSAR\") == 0 && \n\tstrcmp_case(product[pp], \"UNW\") == 0) {\n      get_uavsar_file_names(inFileName, INSAR_UNW, &dataName, &element,\n\t\t\t    &dataType, &nBands);\n      if (!nBands) {\n\tasfPrintWarning(\"Slant range unwrapped phase does not exist. \"\n\t\t\t\"Will skip the ingest.\\n\");\n\tcontinue;\n      }\n      insar_params = \n\tread_uavsar_insar_params(inFileName, INSAR_UNW);\n      metaIn = uavsar_insar2meta(insar_params);\n      metaOut = uavsar_insar2meta(insar_params);\n      ns = metaOut->general->sample_count;\n      nn = 0;\n      floatAmpBuf = (float *) MALLOC(sizeof(float)*ns);\n      outName = (char *) MALLOC(sizeof(char)*(strlen(outBaseName)+15));\n      if (multi)\n\toutName = appendToBasename(outBaseName, \"_unw.img\");\n      else\n\toutName = appendExt(outBaseName, \".img\");\n      asfPrintStatus(\"\\nSlant range unwrapped phase:\\n\");\n      char *filename = get_filename(dataName[nn]);\n      asfPrintStatus(\"Ingesting %s ...\\n\", filename);\n      FREE(filename);\n      fpIn = FOPEN(dataName[nn], \"rb\");\n      fpOut = FOPEN(outName, \"wb\");\n      strcpy(metaOut->general->bands, \"UNWRAPPED_PHASE\");\n      for (ii=0; ii<metaIn->general->line_count; ii++) {\n\tget_float_line(fpIn, metaIn, ii, floatAmpBuf);\n\tfor (kk=0; kk<metaIn->general->sample_count; kk++)\n\t  ieee_big32(floatAmpBuf[kk]);\n\tput_float_line(fpOut, metaOut, ii, floatAmpBuf);\n\tasfLineMeter(ii, metaIn->general->line_count);\n      }\n      FCLOSE(fpIn);\n      FCLOSE(fpOut);\n      meta_write(metaOut, outName);\n      FREE(floatAmpBuf);\n      FREE(outName);\n      meta_free(metaIn);\n      meta_free(metaOut);\n      FREE(insar_params);\n    }    \n    \n    // Slant range correlation image\n    if (strcmp_case(type, \"InSAR\") == 0 && \n\tstrcmp_case(product[pp], \"COR\") == 0) {\n      get_uavsar_file_names(inFileName, INSAR_COR, &dataName, &element,\n\t\t\t    &dataType, &nBands);\n      if (!nBands) {\n\tasfPrintWarning(\"Slant range correlation image does not exist. \"\n\t\t\t\"Will skip the ingest.\\n\");\n\tcontinue;\n      }\n      insar_params = \n\tread_uavsar_insar_params(inFileName, INSAR_COR);\n      metaIn = uavsar_insar2meta(insar_params);\n      metaOut = uavsar_insar2meta(insar_params);\n      ns = metaOut->general->sample_count;\n      nn = 0;\n      floatAmpBuf = (float *) MALLOC(sizeof(float)*ns);\n      outName = (char *) MALLOC(sizeof(char)*(strlen(outBaseName)+15));\n      if (multi)\n\toutName = appendToBasename(outBaseName, \"_cor.img\");\n      else\n\toutName = appendExt(outBaseName, \".img\");\n      asfPrintStatus(\"\\nSlant range correlation image:\\n\");\n      char *filename = get_filename(dataName[nn]);\n      asfPrintStatus(\"Ingesting %s ...\\n\", filename);\n      FREE(filename);\n      fpIn = FOPEN(dataName[nn], \"rb\");\n      fpOut = FOPEN(outName, \"wb\");\n      strcpy(metaOut->general->bands, \"COHERENCE\");\n      for (ii=0; ii<metaIn->general->line_count; ii++) {\n\tget_float_line(fpIn, metaIn, ii, floatAmpBuf);\n\tfor (kk=0; kk<metaIn->general->sample_count; kk++)\n\t  ieee_big32(floatAmpBuf[kk]);\n\tput_float_line(fpOut, metaOut, ii, floatAmpBuf);\n\tasfLineMeter(ii, metaIn->general->line_count);\n      }\n      FCLOSE(fpIn);\n      FCLOSE(fpOut);\n      meta_write(metaOut, outName);\n      FREE(floatAmpBuf);\n      FREE(outName);\n      meta_free(metaIn);\n      meta_free(metaOut);\n      FREE(insar_params);\n    }    \n    \n    // Slant range amplitude images\n    if (strcmp_case(type, \"InSAR\") == 0 &&\n\tstrcmp_case(product[pp], \"AMP\") == 0) {\n      get_uavsar_file_names(inFileName, INSAR_AMP, &dataName, &element,\n\t\t\t    &dataType, &nBands);\n      if (!nBands) {\n\tasfPrintWarning(\"Slant range amplitude images does not exist. \"\n\t\t\t\"Will skip the ingest.\\n\");\n\tcontinue;\n      }\n      insar_params = \n\tread_uavsar_insar_params(inFileName, INSAR_AMP);\n      metaIn = uavsar_insar2meta(insar_params);\n      metaOut = uavsar_insar2meta(insar_params);\n      metaOut->general->band_count = 2;\n      ns = metaOut->general->sample_count;\n      nn = 0;\n      floatAmpBuf = (float *) MALLOC(sizeof(float)*ns);\n      outName = (char *) MALLOC(sizeof(char)*(strlen(outBaseName)+15));\n      if (multi)\n\toutName = appendToBasename(outBaseName, \"_amp.img\");\n      else\n\toutName = appendExt(outBaseName, \".img\");\n      fpOut = FOPEN(outName, \"wb\");\n      strcpy(metaOut->general->bands, \"AMP1,AMP2\");\n      asfPrintStatus(\"\\nSlant range amplitude images:\\n\");\n      for (nn=0; nn<nBands; nn++) {\n        char *filename = get_filename(dataName[nn]);\n        asfPrintStatus(\"Ingesting %s ...\\n\", filename);\n        FREE(filename);\n\tfpIn = FOPEN(dataName[nn], \"rb\");\n\tfor (ii=0; ii<metaIn->general->line_count; ii++) {\n\t  get_float_line(fpIn, metaIn, ii, floatAmpBuf);\n\t  for (kk=0; kk<metaIn->general->sample_count; kk++)\n\t    ieee_big32(floatAmpBuf[kk]);\n\t  put_band_float_line(fpOut, metaOut, nn, ii, floatAmpBuf);\n\t  asfLineMeter(ii, metaIn->general->line_count);\n\t}\n\tFCLOSE(fpIn);\n      }\n      FCLOSE(fpOut);\n      meta_write(metaOut, outName);\n      FREE(floatAmpBuf);\n      FREE(outName);\n      meta_free(metaIn);\n      meta_free(metaOut);\n      FREE(insar_params);\n    }    \n    \n    // PolSAR data\n    // Single look complex data\n    if (strcmp_case(type, \"PolSAR\") == 0 &&\n\tstrcmp_case(product[pp], \"SLC\") == 0) {\n      asfPrintWarning(\"Ingest of SLC data is currently not supported!\\n\");\n      /*\n      get_uavsar_file_names(inFileName, POLSAR_SLC, &dataName, &element,\n\t\t\t    &dataType, &nBands);\n      polsar_params = \n\tread_uavsar_polsar_params(inFileName, POLSAR_SLC);\n      metaIn = uavsar_polsar2meta(polsar_params);\n      metaOut = uavsar_polsar2meta(polsar_params);\n      if (multi)\n\toutName = appendToBasename(outBaseName, \"_slc.img\");\n      else\n\toutName = appendExt(outBaseName, \".img\");\n      for (ii=0; ii<nBands; ii++)\n\tprintf(\"file: %s\\n\", dataName[ii]);\n      //meta_write(metaOut, outName);\n      meta_free(metaIn);\n      meta_free(metaOut);\n      FREE(polsar_params);\n      */\n    }\n    \n    // Multilooked data\n    if (strcmp_case(type, \"PolSAR\") == 0  &&\n\tstrcmp_case(product[pp], \"MLC\") == 0) {\n      get_uavsar_file_names(inFileName, POLSAR_MLC, &dataName, &element,\n\t\t\t    &dataType, &nBands);\n      if (!nBands) {\n\tasfPrintWarning(\"Slant range multilooked data do not exist. \"\n\t\t\t\"Will skip the ingest.\\n\");\n\tcontinue;\n      }\n      polsar_params = \n\tread_uavsar_polsar_params(inFileName, POLSAR_MLC);\n      metaIn = uavsar_polsar2meta(polsar_params);\n      metaOut = uavsar_polsar2meta(polsar_params);\n      ns = metaIn->general->sample_count;\n      amp = (float *) MALLOC(sizeof(float)*ns);\n      floatAmp = (float *) MALLOC(sizeof(float)*ns);\n      floatAmpBuf = (float *) MALLOC(sizeof(float)*ns);\n      floatComplexReal = (float *) MALLOC(sizeof(float)*ns);\n      floatComplexImag = (float *) MALLOC(sizeof(float)*ns);\n      floatComplexBuf = (float *) MALLOC(sizeof(float)*2*ns);\n      outName = (char *) MALLOC(sizeof(char)*(strlen(outBaseName)+15));\n      metaOut->general->band_count = ll = 1;\n      if (multi)\n\toutName = appendToBasename(outBaseName, \"_mlc.img\");\n      else\n\toutName = appendExt(outBaseName, \".img\");\n      asfPrintStatus(\"\\nMultilooked data:\\n\");\n      fpOut = FOPEN(outName, \"wb\");\n      for (nn=0; nn<nBands; nn++) {\n        char *filename = get_filename(dataName[nn]);\n        asfPrintStatus(\"Ingesting %s ...\\n\", filename);\n        FREE(filename);\n\tif (dataType[nn] == 0)\n\t  metaOut->general->band_count += 1;\n\telse\n\t  metaOut->general->band_count += 2;\n\tfpIn = FOPEN(dataName[nn], \"rb\");\n\tif (nn == 0)\n\t  sprintf(metaOut->general->bands, \"AMP,%s\", element[0]);\n\telse {\n\t  if (dataType[nn])\n\t    sprintf(tmp, \",%s_real,%s_imag\", element[nn], element[nn]);\n\t  else\n\t    sprintf(tmp, \",%s\", element[nn]);\n\t  strcat(metaOut->general->bands, tmp);\n\t}\n\tfor (ii=0; ii<metaIn->general->line_count; ii++) {\n\t  if (dataType[nn]) {\n\t    metaIn->general->sample_count = 2*ns;\n\t    get_float_line(fpIn, metaIn, ii, floatComplexBuf);\n\t    for (kk=0; kk<ns; kk++) {\n\t      floatComplexReal[kk] = floatComplexBuf[kk*2];\n\t      floatComplexImag[kk] = floatComplexBuf[kk*2+1];\n\t      ieee_big32(floatComplexReal[kk]);\n\t      ieee_big32(floatComplexImag[kk]);\n\t    }\n\t    put_band_float_line(fpOut, metaOut, ll, ii, floatComplexReal);\n\t    put_band_float_line(fpOut, metaOut, ll+1, ii, floatComplexImag);\n\t  }\n\t  else {\n\t    metaIn->general->sample_count = ns;\n\t    get_float_line(fpIn, metaIn, ii, floatAmpBuf);\n\t    if (nn == 0) {\n\t      for (kk=0; kk<ns; kk++) {\n\t\tieee_big32(floatAmpBuf[kk]);\n\t\tfloatAmp[kk] = sqrt(floatAmpBuf[kk]);\n\t      }\n\t    }\n\t    else {\n\t      for (kk=0; kk<ns; kk++) \n\t\tieee_big32(floatAmpBuf[kk]);\n\t    }\n\t    put_band_float_line(fpOut, metaOut, ll, ii, floatAmpBuf);\n\t  }\n\t  asfLineMeter(ii, metaIn->general->line_count);      \n\t}\n\tif (dataType[nn])\n\t  ll += 2;\n\telse\n\t  ll++;\n\tFCLOSE(fpIn);\n      }\n      FCLOSE(fpOut);\n      meta_write(metaOut, outName);\n      FREE(amp);\n      FREE(floatAmp);\n      FREE(floatAmpBuf);\n      FREE(floatComplexReal);\n      FREE(floatComplexImag);\n      FREE(floatComplexBuf);\n      FREE(outName);\n      meta_free(metaIn);\n      meta_free(metaOut);\n      FREE(polsar_params);\n    }    \n    \n    // Compressed Stokes matrix\n    if (strcmp_case(type, \"PolSAR\") == 0 &&\n\tstrcmp_case(product[pp], \"DAT\") == 0) {\n      get_uavsar_file_names(inFileName, POLSAR_DAT, &dataName, &element,\n\t\t\t    &dataType, &nBands);\n      if (!nBands) {\n\tasfPrintWarning(\"Slant range Stokes matrix does not exist. \"\n\t\t\t\"Will skip the ingest.\\n\");\n\tcontinue;\n      }\n      polsar_params = \n\tread_uavsar_polsar_params(inFileName, POLSAR_DAT);\n      metaIn = uavsar_polsar2meta(polsar_params);\n      metaOut = uavsar_polsar2meta(polsar_params);\n      outName = (char *) MALLOC(sizeof(char)*(strlen(outBaseName)+15));\n      if (multi)\n\toutName = appendToBasename(outBaseName, \"_dat.img\");\n      else\n\toutName = appendExt(outBaseName, \".img\");\n      metaOut->general->band_count = 9;\n      asfPrintStatus(\"\\nCompressed Stokes matrix:\\n\");\n      char *filename = get_filename(dataName[0]);\n      asfPrintStatus(\"Ingesting %s ...\\n\", filename);\n      FREE(filename);\n      if (radiometry == r_AMP)\n\tstrcpy(metaOut->general->bands,\n\t       \"AMP,AMP_HH,PHASE_HH,AMP_HV,PHASE_HV,AMP_VH,PHASE_VH,\"\t\\\n\t       \"AMP_VV,PHASE_VV\");\n      else if (radiometry == r_SIGMA)\n\tstrcpy(metaOut->general->bands,\n\t       \"AMP,SIGMA-AMP-HH,SIGMA-PHASE-HH,SIGMA-AMP-HV,SIGMA-PHASE-HV,\" \\\n\t       \"SIGMA-AMP-VH,SIGMA-PHASE-VH,SIGMA-AMP-VV,SIGMA-PHASE-VV\");\n      else if (radiometry == r_SIGMA_DB)\n\tstrcpy(metaOut->general->bands,\n\t       \"AMP,SIGMA_DB-AMP-HH,SIGMA_DB-PHASE-HH,SIGMA_DB-AMP-HV,\"\t\\\n\t       \"SIGMA_DB-PHASE-HV,SIGMA_DB-AMP-VH,SIGMA_DB-PHASE-VH,\"\t\\\n\t       \"SIGMA_DB-AMP-VV,SIGMA_DB-PHASE-VV\");\n      int ns = metaOut->general->sample_count;\n      float total_power, ysca, amp, phase;\n      complexFloat cpx;\n      float *power = (float *) MALLOC(sizeof(float)*ns);\n      float *shh_amp = (float *) MALLOC(sizeof(float)*ns);\n      float *shh_phase = (float *) MALLOC(sizeof(float)*ns);\n      float *shv_amp = (float *) MALLOC(sizeof(float)*ns);\n      float *shv_phase = (float *) MALLOC(sizeof(float)*ns);\n      float *svh_amp = (float *) MALLOC(sizeof(float)*ns);\n      float *svh_phase = (float *) MALLOC(sizeof(float)*ns);\n      float *svv_amp = (float *) MALLOC(sizeof(float)*ns);\n      float *svv_phase = (float *) MALLOC(sizeof(float)*ns);\n      char *byteBuf = (char *) MALLOC(sizeof(char)*10);\n      fpIn = FOPEN(dataName[0], \"rb\");\n      fpOut = FOPEN(outName, \"wb\");\n      for (ii=0; ii<metaOut->general->line_count; ii++) {\n\tfor (kk=0; kk<metaOut->general->sample_count; kk++) {\n\t  FREAD(byteBuf, sizeof(char), 10, fpIn);\n          //float m11, m12, m13, m14, m22, m23, m24, m33, m34, m44;\n\t  // Scale is always 1.0 according to Bruce Chapman\n\t  //m11 = ((float)byteBuf[1]/254.0 + 1.5) * pow(2, byteBuf[0]);\n\t  //m12 = (float)byteBuf[2] * m11 / 127.0;\n\t  //m13 = sign(byteBuf[3]) * SQR((float)byteBuf[3] / 127.0) * m11;\n\t  //m14 = sign(byteBuf[4]) * SQR((float)byteBuf[4] / 127.0) * m11;\n\t  //m23 = sign(byteBuf[5]) * SQR((float)byteBuf[5] / 127.0) * m11;\n\t  //m24 = sign(byteBuf[6]) * SQR((float)byteBuf[6] / 127.0) * m11;\n\t  //m33 = (float)byteBuf[7] * m11 / 127.0;\n\t  //m34 = (float)byteBuf[8] * m11 / 127.0;\n\t  //m44 = (float)byteBuf[9] * m11 / 127.0;\n\t  //m22 = 1 - m33 -m44;\n\t  total_power =\n\t    ((float)byteBuf[1]/254.0 + 1.5) * pow(2, byteBuf[0]);\n\t  ysca = 2.0 * sqrt(total_power);\n\t  power[kk] = sqrt(total_power);\n\t  cpx.real = (float)byteBuf[2] * ysca / 127.0;\n\t  cpx.imag = (float)byteBuf[3] * ysca / 127.0;\n\t  amp = sqrt(cpx.real*cpx.real + cpx.imag*cpx.imag);\n\t  phase = atan2(cpx.imag, cpx.real);\n\t  if (radiometry == r_AMP) {\n\t    shh_amp[kk] = amp;\n\t    shh_phase[kk] = phase;\n\t  }\n\t  else if (radiometry == r_SIGMA) {\n\t    shh_amp[kk] = amp*amp;\n\t    shh_phase[kk] = phase;\n\t  }\n\t  else if (radiometry == r_SIGMA_DB) {\n\t    shh_amp[kk] = amp;\n\t    shh_phase[kk] = phase;\n\t  }\n\t  cpx.real = (float)byteBuf[4] * ysca / 127.0;\n\t  cpx.imag = (float)byteBuf[5] * ysca / 127.0;\n\t  amp = sqrt(cpx.real*cpx.real + cpx.imag*cpx.imag);\n\t  phase = atan2(cpx.imag, cpx.real);\n\t  if (radiometry == r_AMP) {\n\t    shv_amp[kk] = amp;\n\t    shv_phase[kk] = phase;\n\t  }\n\t  else if (radiometry == r_SIGMA) {\n\t    shv_amp[kk] = amp*amp;\n\t    shv_phase[kk] = phase;\n\t  }\n\t  else if (radiometry == r_SIGMA_DB) {\n\t    shv_amp[kk] = amp;\n\t    shv_phase[kk] = phase;\n\t  }\n\t  cpx.real = (float)byteBuf[6] * ysca / 127.0;\n\t  cpx.imag = (float)byteBuf[7] * ysca / 127.0;\n\t  amp = sqrt(cpx.real*cpx.real + cpx.imag*cpx.imag);\n\t  phase = atan2(cpx.imag, cpx.real);\n\t  if (radiometry == r_AMP) {\n\t    svh_amp[kk] = amp;\n\t    svh_phase[kk] = phase;\n\t  }\n\t  else if (radiometry == r_SIGMA) {\n\t    svh_amp[kk] = amp*amp;\n\t    svh_phase[kk] = phase;\n\t  }\n\t  else if (radiometry == r_SIGMA_DB) {\n\t    svh_amp[kk] = amp;\n\t    svh_phase[kk] = phase;\n\t  }\n\t  cpx.real = (float)byteBuf[8] * ysca / 127.0;\n\t  cpx.imag = (float)byteBuf[9] * ysca / 127.0;\n\t  amp = sqrt(cpx.real*cpx.real + cpx.imag*cpx.imag);\n\t  phase = atan2(cpx.imag, cpx.real);\n\t  if (radiometry == r_AMP) {\n\t    svv_amp[kk] = amp;\n\t    svv_phase[kk] = phase;\n\t  }\n\t  else if (radiometry == r_SIGMA) {\n\t    svv_amp[kk] = amp*amp;\n\t    svv_phase[kk] = phase;\n\t  }\n\t  else if (radiometry == r_SIGMA_DB) {\n\t    svv_amp[kk] = amp;\n\t    svv_phase[kk] = phase;\n\t  }\n\t}\n\tput_band_float_line(fpOut, metaOut, 0, ii, power);\n\tput_band_float_line(fpOut, metaOut, 1, ii, shh_amp);\n\tput_band_float_line(fpOut, metaOut, 2, ii, shh_phase);\n\tput_band_float_line(fpOut, metaOut, 3, ii, shv_amp);\n\tput_band_float_line(fpOut, metaOut, 4, ii, shv_phase);\n\tput_band_float_line(fpOut, metaOut, 5, ii, svh_amp);\n\tput_band_float_line(fpOut, metaOut, 6, ii, svh_phase);\n\tput_band_float_line(fpOut, metaOut, 7, ii, svv_amp);\n\tput_band_float_line(fpOut, metaOut, 8, ii, svv_phase);\n\tasfLineMeter(ii, metaOut->general->line_count);\n      }\n      FCLOSE(fpIn);\n      FCLOSE(fpOut);\n      FREE(power);\n      FREE(shh_amp);\n      FREE(shh_phase);\n      FREE(shv_amp);\n      FREE(shv_phase);\n      FREE(svh_amp);\n      FREE(svh_phase);\n      FREE(svv_amp);\n      FREE(svv_phase);\n      meta_write(metaOut, outName);\n      meta_free(metaIn);\n      meta_free(metaOut);\n      FREE(outName);\n      FREE(polsar_params);\n    }\n    \n    // Ground range projected data\n    if (strcmp_case(type, \"PolSAR\") == 0 &&\n\tstrcmp_case(product[pp], \"GRD\") == 0) {\n      get_uavsar_file_names(inFileName, POLSAR_GRD, &dataName, &element,\n\t\t\t    &dataType, &nBands);\n      if (!nBands) {\n\tasfPrintWarning(\"Ground range projected data do not exist. \"\n\t\t\t\"Will skip the ingest.\\n\");\n\tcontinue;\n      }\n      polsar_params = \n\tread_uavsar_polsar_params(inFileName, POLSAR_GRD);\n      metaIn = uavsar_polsar2meta(polsar_params);\n      metaOut = uavsar_polsar2meta(polsar_params);\n      ns = metaIn->general->sample_count;\n      floatAmpBuf = (float *) CALLOC(ns, sizeof(float));\n      floatComplexReal = (float *) CALLOC(ns, sizeof(float));\n      floatComplexImag = (float *) CALLOC(ns, sizeof(float));\n      floatComplexBuf = (float *) CALLOC(2*ns, sizeof(float));\n      outName = (char *) MALLOC(sizeof(char)*(strlen(outBaseName)+15));\n      metaOut->general->band_count = ll = 0;\n      if (multi)\n\toutName = appendToBasename(outBaseName, \"_grd.img\");\n      else\n\toutName = appendExt(outBaseName, \".img\");\n      asfPrintStatus(\"\\nGround range projected data:\\n\");\n      fpOut = FOPEN(outName, \"wb\");\n      for (nn=0; nn<nBands; nn++) {\n        char *filename = get_filename(dataName[nn]);\n        asfPrintStatus(\"Ingesting %s ...\\n\", filename);\n        FREE(filename);\n\tif (dataType[nn])\n\t  metaOut->general->band_count += 2;\n\telse\n\t  metaOut->general->band_count += 1;\n\tfpIn = FOPEN(dataName[nn], \"rb\");\n\tif (nn == 0)\n\t  sprintf(metaOut->general->bands, \"%s\", element[0]);\n\telse {\n\t  if (dataType[nn])\n\t    sprintf(tmp, \",%s_real,%s_imag\", element[nn], element[nn]);\n\t  else\n\t    sprintf(tmp, \",%s\", element[nn]);\n\t  strcat(metaOut->general->bands, tmp);\n\t}\n\tif (dataType[nn]) {\n\t  for (ii=0; ii<metaIn->general->line_count; ii++) {\n\t    metaIn->general->sample_count = 2*ns;\n\t    get_float_line(fpIn, metaIn, ii, floatComplexBuf);\n\t    for (kk=0; kk<ns; kk++) {\n\t      floatComplexReal[kk] = floatComplexBuf[kk*2];\n\t      floatComplexImag[kk] = floatComplexBuf[kk*2+1];\n\t      ieee_big32(floatComplexReal[kk]);\n\t      ieee_big32(floatComplexImag[kk]);\n\t    }\n\t    put_band_float_line(fpOut, metaOut, ll, ii, floatComplexReal);\n\t    put_band_float_line(fpOut, metaOut, ll+1, ii, floatComplexImag);\n\t    asfLineMeter(ii, metaIn->general->line_count);\n\t  }\n\t}\n\telse {\n\t  for (ii=0; ii<metaIn->general->line_count; ii++) {\n\t    metaIn->general->sample_count = ns;\n\t    get_float_line(fpIn, metaIn, ii, floatAmpBuf);\n\t    for (kk=0; kk<ns; kk++)\n\t      ieee_big32(floatAmpBuf[kk]);\n\t    put_band_float_line(fpOut, metaOut, ll, ii, floatAmpBuf);\n\t    asfLineMeter(ii, metaIn->general->line_count);      \n\t  }\n\t}\n\tFCLOSE(fpIn);\n\tif (dataType[nn])\n\t  ll += 2;\n\telse\n\t  ll++;\n      }\n      FCLOSE(fpOut);\n      meta_write(metaOut, outName);\n      FREE(floatAmpBuf);\n      FREE(floatComplexReal);\n      FREE(floatComplexImag);\n      FREE(floatComplexBuf);\n      FREE(outName);\n      meta_free(metaIn);\n      meta_free(metaOut);\n      FREE(polsar_params);\n    }\n    \n    // Digital elevation model\n    if (strcmp_case(type, \"PolSAR\") == 0 &&\n\tstrcmp_case(product[pp], \"HGT\") == 0) {\n      get_uavsar_file_names(inFileName, POLSAR_HGT, &dataName, &element,\n\t\t\t    &dataType, &nBands);\n      if (!nBands) {\n\tasfPrintWarning(\"Digital elevation model does not exist. \"\n\t\t\t\"Will skip the ingest.\\n\");\n\tcontinue;\n      }\n      polsar_params = \n\tread_uavsar_polsar_params(inFileName, POLSAR_HGT);\n      metaIn = uavsar_polsar2meta(polsar_params);\n      metaOut = uavsar_polsar2meta(polsar_params);\n      ns = metaOut->general->sample_count;\n      floatAmpBuf = (float *) MALLOC(sizeof(float)*ns);\n      outName = (char *) MALLOC(sizeof(char)*(strlen(outBaseName)+15));\n      if (multi)\n\toutName = appendToBasename(outBaseName, \"_hgt.img\");\n      else\n\toutName = appendExt(outBaseName, \".img\");\n      asfPrintStatus(\"\\nDigital elevation model:\\n\");\n      nn=0;\n      char *filename = get_filename(dataName[nn]);\n      asfPrintStatus(\"Ingesting %s ...\\n\", filename);\n      FREE(filename);\n      fpIn = FOPEN(dataName[nn], \"rb\");\n      fpOut = FOPEN(outName, \"wb\");\n      strcpy(metaOut->general->bands, \"HEIGHT\");\n      for (ii=0; ii<metaIn->general->line_count; ii++) {\n\tget_float_line(fpIn, metaIn, ii, floatAmpBuf);\n\tfor (kk=0; kk<metaIn->general->sample_count; kk++)\n\t  ieee_big32(floatAmpBuf[kk]);\n\tput_float_line(fpOut, metaOut, ii, floatAmpBuf);\n\tasfLineMeter(ii, metaIn->general->line_count);\n      }\n      FCLOSE(fpIn);\n      FCLOSE(fpOut);\n      meta_write(metaOut, outName);\n      FREE(floatAmpBuf);\n      FREE(outName);\n      meta_free(metaIn);\n      meta_free(metaOut);\n      FREE(polsar_params);\n    }    \n  }\n  if (strcmp_case(type, \"PolSAR\") == 0)\n    product_count = 5;\n  else if (strcmp_case(type, \"InSAR\") == 0)\n    product_count = 9;\n  for (pp=0; pp<product_count; pp++)\n    FREE(product[pp]);\n  FREE(product);\n  FREE(type);\n}\n\nvoid read_meta_uavsar(const char *inFileName, const char *outBaseName) \n{\n  int pp, product_count, *dataType, nBands;\n  char *type = check_data_type(inFileName);\n  char **product = get_uavsar_products(\"ALL\", type, &product_count);\n  char **dataName, **element;\n  char *outName = (char *) MALLOC(sizeof(char)*255);\n  uavsar_polsar *polsar_params;\n  uavsar_insar *insar_params;\n  meta_parameters *meta;\n  \n  for (pp = 0; pp < product_count; pp++) {\n\n    // InSAR\n    if (strcmp_case(type, \"InSAR\") == 0 && \n\tstrcmp_case(product[pp], \"INT_GRD\") == 0) {\n      get_uavsar_file_names(inFileName, INSAR_INT_GRD, &dataName, &element,\n\t\t\t    &dataType, &nBands);\n      if (!nBands)\n\tcontinue;\n      insar_params = \n\tread_uavsar_insar_params(inFileName, INSAR_INT_GRD);\n      meta = uavsar_insar2meta(insar_params);\n      sprintf(outName, \"%s_int_grd.xml\", outBaseName);\n      meta_write_xml(meta, outName);\n      FREE(outName);\n      meta_free(meta);\n      FREE(insar_params);\n      FREE(dataType);\n    }\n    if (strcmp_case(type, \"InSAR\") == 0 &&\n\tstrcmp_case(product[pp], \"UNW_GRD\") == 0) {\n      get_uavsar_file_names(inFileName, INSAR_UNW_GRD, &dataName, &element,\n\t\t\t    &dataType, &nBands);\n      if (!nBands)\n\tcontinue;\n      insar_params = \n\tread_uavsar_insar_params(inFileName, INSAR_UNW_GRD);\n      meta = uavsar_insar2meta(insar_params);\n      sprintf(outName, \"%s_unw_grd.xml\", outBaseName);\n      meta_write_xml(meta, outName);\n      FREE(outName);\n      meta_free(meta);\n      FREE(insar_params);\n      FREE(dataType);\n    }\n    if (strcmp_case(type, \"InSAR\") == 0 &&\n\tstrcmp_case(product[pp], \"COR_GRD\") == 0) {\n      get_uavsar_file_names(inFileName, INSAR_COR_GRD, &dataName, &element,\n\t\t\t    &dataType, &nBands);\n      if (!nBands)\n\tcontinue;\n      insar_params = \n\tread_uavsar_insar_params(inFileName, INSAR_COR_GRD);\n      meta = uavsar_insar2meta(insar_params);\n      sprintf(outName, \"%s_cor_grd.xml\", outBaseName);\n      meta_write_xml(meta, outName);\n      FREE(outName);\n      meta_free(meta);\n      FREE(insar_params);\n      FREE(dataType);\n    }\n    if (strcmp_case(type, \"InSAR\") == 0 &&\n\tstrcmp_case(product[pp], \"AMP_GRD\") == 0) {\n      get_uavsar_file_names(inFileName, INSAR_AMP_GRD, &dataName, &element,\n\t\t\t    &dataType, &nBands);\n      if (!nBands)\n\tcontinue;\n      insar_params = \n\tread_uavsar_insar_params(inFileName, INSAR_AMP_GRD);\n      meta = uavsar_insar2meta(insar_params);\n      sprintf(outName, \"%s_amp_grd.xml\", outBaseName);\n      meta_write_xml(meta, outName);\n      FREE(outName);\n      meta_free(meta);\n      FREE(insar_params);\n      FREE(dataType);\n    }\n    if (strcmp_case(type, \"InSAR\") == 0 &&\n\tstrcmp_case(product[pp], \"HGT_GRD\") == 0) {\n      get_uavsar_file_names(inFileName, INSAR_HGT_GRD, &dataName, &element,\n\t\t\t    &dataType, &nBands);\n      if (!nBands)\n\tcontinue;\n      insar_params = \n\tread_uavsar_insar_params(inFileName, INSAR_HGT_GRD);\n      meta = uavsar_insar2meta(insar_params);\n      sprintf(outName, \"%s_hgt_grd.xml\", outBaseName);\n      meta_write_xml(meta, outName);\n      FREE(outName);\n      meta_free(meta);\n      FREE(insar_params);\n      FREE(dataType);\n    }\n    if (strcmp_case(type, \"InSAR\") == 0 &&\n\tstrcmp_case(product[pp], \"INT\") == 0) {\n      get_uavsar_file_names(inFileName, INSAR_INT, &dataName, &element,\n\t\t\t    &dataType, &nBands);\n      if (!nBands)\n\tcontinue;\n      insar_params = \n\tread_uavsar_insar_params(inFileName, INSAR_INT);\n      meta = uavsar_insar2meta(insar_params);\n      sprintf(outName, \"%s_int.xml\", outBaseName);\n      meta_write_xml(meta, outName);\n      FREE(outName);\n      meta_free(meta);\n      FREE(insar_params);\n      FREE(dataType);\n    }\n    if (strcmp_case(type, \"InSAR\") == 0 && \n\tstrcmp_case(product[pp], \"UNW\") == 0) {\n      get_uavsar_file_names(inFileName, INSAR_UNW, &dataName, &element,\n\t\t\t    &dataType, &nBands);\n      if (!nBands)\n\tcontinue;\n      insar_params = \n\tread_uavsar_insar_params(inFileName, INSAR_UNW);\n      meta = uavsar_insar2meta(insar_params);\n      sprintf(outName, \"%s_unw.xml\", outBaseName);\n      meta_write_xml(meta, outName);\n      FREE(outName);\n      meta_free(meta);\n      FREE(insar_params);\n      FREE(dataType);\n    }\n    if (strcmp_case(type, \"InSAR\") == 0 && \n\tstrcmp_case(product[pp], \"COR\") == 0) {\n      get_uavsar_file_names(inFileName, INSAR_COR, &dataName, &element,\n\t\t\t    &dataType, &nBands);\n      if (!nBands)\n\tcontinue;\n      insar_params = \n\tread_uavsar_insar_params(inFileName, INSAR_COR);\n      meta = uavsar_insar2meta(insar_params);\n      sprintf(outName, \"%s_cor.xml\", outBaseName);\n      meta_write_xml(meta, outName);\n      FREE(outName);\n      meta_free(meta);\n      FREE(insar_params);\n      FREE(dataType);\n    }\n    if (strcmp_case(type, \"InSAR\") == 0 &&\n\tstrcmp_case(product[pp], \"AMP\") == 0) {\n      get_uavsar_file_names(inFileName, INSAR_AMP, &dataName, &element,\n\t\t\t    &dataType, &nBands);\n      if (!nBands)\n\tcontinue;\n      insar_params = \n\tread_uavsar_insar_params(inFileName, INSAR_AMP);\n      meta = uavsar_insar2meta(insar_params);\n      sprintf(outName, \"%s_amp.xml\", outBaseName);\n      meta_write_xml(meta, outName);\n      FREE(outName);\n      meta_free(meta);\n      FREE(insar_params);\n      FREE(dataType);\n    }\n    // PolSAR\n    if (strcmp_case(type, \"PolSAR\") == 0  &&\n\tstrcmp_case(product[pp], \"MLC\") == 0) {\n      get_uavsar_file_names(inFileName, POLSAR_MLC, &dataName, &element,\n\t\t\t    &dataType, &nBands);\n      if (!nBands)\n\tcontinue;\n      polsar_params = \n\tread_uavsar_polsar_params(inFileName, POLSAR_MLC);\n      meta = uavsar_polsar2meta(polsar_params);\n      sprintf(outName, \"%s_mlc.xml\", outBaseName);\n      meta_write_xml(meta, outName);\n      FREE(outName);\n      meta_free(meta);\n      FREE(insar_params);\n      FREE(dataType);\n    }\n    if (strcmp_case(type, \"PolSAR\") == 0 &&\n\tstrcmp_case(product[pp], \"DAT\") == 0) {\n      get_uavsar_file_names(inFileName, POLSAR_DAT, &dataName, &element,\n\t\t\t    &dataType, &nBands);\n      if (!nBands)\n\tcontinue;\n      polsar_params = \n\tread_uavsar_polsar_params(inFileName, POLSAR_DAT);\n      meta = uavsar_polsar2meta(polsar_params);\n      sprintf(outName, \"%s_dat.xml\", outBaseName);\n      meta_write_xml(meta, outName);\n      FREE(outName);\n      meta_free(meta);\n      FREE(insar_params);\n      FREE(dataType);\n    }\n    if (strcmp_case(type, \"PolSAR\") == 0 &&\n\tstrcmp_case(product[pp], \"GRD\") == 0) {\n      get_uavsar_file_names(inFileName, POLSAR_GRD, &dataName, &element,\n\t\t\t    &dataType, &nBands);\n      if (!nBands)\n\tcontinue;\n      polsar_params = \n\tread_uavsar_polsar_params(inFileName, POLSAR_GRD);\n      meta = uavsar_polsar2meta(polsar_params);\n      sprintf(outName, \"%s_grd.xml\", outBaseName);\n      meta_write_xml(meta, outName);\n      FREE(outName);\n      meta_free(meta);\n      FREE(insar_params);\n      FREE(dataType);\n    }\n    if (strcmp_case(type, \"PolSAR\") == 0 &&\n\tstrcmp_case(product[pp], \"HGT\") == 0) {\n      get_uavsar_file_names(inFileName, POLSAR_HGT, &dataName, &element,\n\t\t\t    &dataType, &nBands);\n      if (!nBands)\n\tcontinue;\n      polsar_params = \n\tread_uavsar_polsar_params(inFileName, POLSAR_HGT);\n      meta = uavsar_polsar2meta(polsar_params);\n      sprintf(outName, \"%s_hgt.xml\", outBaseName);\n      meta_write_xml(meta, outName);\n      FREE(outName);\n      meta_free(meta);\n      FREE(insar_params);\n      FREE(dataType);\n    }\n  }\n  for (pp=0; pp<product_count; pp++)\n    FREE(product[pp]);\n  FREE(product);\n  FREE(type);\n}\n", "meta": {"hexsha": "5978d4272a0286cc6ceb88b9496cfa0f88e8c618", "size": 74920, "ext": "c", "lang": "C", "max_stars_repo_path": "src/libasf_import/import_uavsar.c", "max_stars_repo_name": "glshort/MapReady", "max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z", "max_issues_repo_path": "src/libasf_import/import_uavsar.c", "max_issues_repo_name": "glshort/MapReady", "max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libasf_import/import_uavsar.c", "max_forks_repo_name": "glshort/MapReady", "max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z", "avg_line_length": 35.157203191, "max_line_length": 181, "alphanum_fraction": 0.6147624132, "num_tokens": 21669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1895211004851209, "lm_q2_score": 0.03410042963877804, "lm_q1q2_score": 0.006462750952156648}}
{"text": "// --------------------------------------------------------------------------\n//                   OpenMS -- Open-Source Mass Spectrometry\n// --------------------------------------------------------------------------\n// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,\n// ETH Zurich, and Freie Universitaet Berlin 2002-2013.\n//\n// This software is released under a three-clause BSD license:\n//  * Redistributions of source code must retain the above copyright\n//    notice, this list of conditions and the following disclaimer.\n//  * Redistributions in binary form must reproduce the above copyright\n//    notice, this list of conditions and the following disclaimer in the\n//    documentation and/or other materials provided with the distribution.\n//  * Neither the name of any author or any participating institution\n//    may be used to endorse or promote products derived from this software\n//    without specific prior written permission.\n// For a full list of authors, refer to the file AUTHORS.\n// --------------------------------------------------------------------------\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING\n// INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// --------------------------------------------------------------------------\n// $Maintainer: Lars Nilse $\n// $Authors: Steffen Sass, Holger Plattfaut, Bastian Blank $\n// --------------------------------------------------------------------------\n\n#ifndef OPENMS_FILTERING_DATAREDUCTION_SILACFILTERING_H\n#define OPENMS_FILTERING_DATAREDUCTION_SILACFILTERING_H\n\n#include <OpenMS/KERNEL/StandardTypes.h>\n#include <OpenMS/KERNEL/MSExperiment.h>\n#include <OpenMS/CONCEPT/ProgressLogger.h>\n#include <OpenMS/DATASTRUCTURES/DRange.h>\n#include <OpenMS/TRANSFORMATIONS/FEATUREFINDER/PeakWidthEstimator.h>\n\n#include <gsl/gsl_interp.h>\n#include <gsl/gsl_spline.h>\n#include <list>\n#include <map>\n#include <vector>\n\nnamespace OpenMS\n{\n  class SILACFilter;\n\n  /**\n    @brief Filtering for SILAC data.\n\n    This filtering can be used to extract SILAC features from an MS experiment.\n    Several SILACFilters can be added to the filtering to search for specific SILAC patterns.\n\n    @see SILACFilter\n  */\n  class OPENMS_DLLAPI SILACFiltering :\n    public ProgressLogger\n  {\npublic:\n    typedef std::vector<SILACFilter> Filters;\n\n    /**\n     * @brief holds all filters used in the filtering\n     */\n    Filters filters_;\n\n    /**\n     * @brief Wrapper class for spectrum interpolation\n     */\n    class OPENMS_DLLAPI SpectrumInterpolation\n    {\nprivate:\n      gsl_interp_accel * current_;\n      gsl_spline * spline_;\n\npublic:\n      SpectrumInterpolation(const MSSpectrum<> &, const SILACFiltering &);\n      ~SpectrumInterpolation();\n\n      DoubleReal operator()(DoubleReal mz) const\n      {\n        return gsl_spline_eval(spline_, mz, current_);\n      }\n\n    };\n\nprivate:\n    /**\n     * @brief minimal intensity of SILAC features\n     */\n    DoubleReal intensity_cutoff_;\n\n    /**\n     * @brief raw data\n     */\n    MSExperiment<Peak1D> & exp_;\n\n    /**\n     * @brief picked data\n     */\n    MSExperiment<Peak1D> picked_exp_;\n\n    /**\n     * @brief picked data seeds\n     */\n    MSExperiment<Peak1D> picked_exp_seeds_;\n\n    /**\n     * Filename base for debugging output\n     */\n    const String debug_filebase_;\n\n    /**\n     * @brief pick data seeds\n     */\n    void pickSeeds_();\n\n    /**\n     * @brief apply filtering to picked data seeds\n     */\n    void filterSeeds_();\n\npublic:\n\n    /// peak-width equation\n    const PeakWidthEstimator::Result peak_width;\n\n    /**\n     * @brief detailed constructor\n     * @param exp raw data\n     * @param intensity_cutoff minimal intensity of SILAC features\n     */\n    SILACFiltering(MSExperiment<Peak1D> & exp, const PeakWidthEstimator::Result &, const DoubleReal intensity_cutoff, const String debug_filebase_ = \"\");\n\n    /**\n     * @brief adds a new filter to the filtering\n     * @param filter filter to add\n     */\n    void addFilter(SILACFilter & filter);\n\n    /**\n     * @brief starts the filtering based on the added filters\n     */\n    void filterDataPoints();\n\n    /**\n     * @brief structure for blacklist\n     * @param range m/z and RT interval to be blacklisted\n     * @param charge charge of the generating filter\n     * @param mass_separations mass separations of the generating filter\n     * @param relative_peak_position m/z position of the blacklisted area relative to the mono-isotopic peak of the unlabelled peptide\n     */\n    struct BlacklistEntry\n    {\n      DRange<2> range;\n      Int charge;\n      std::vector<DoubleReal> mass_separations;\n      DoubleReal relative_peak_position;\n    };\n\n    /**\n     * @brief holds the range that is blacklisted for other filters and the filter that generated the blacklist entry\n     */\n    std::multimap<DoubleReal, BlacklistEntry> blacklist;\n  };\n}\n\n#endif /* SILACFILTERING_H_ */\n", "meta": {"hexsha": "586f7868706a92d4fb06b7ca76706b8453b6bca7", "size": 5574, "ext": "h", "lang": "C", "max_stars_repo_path": "include/OpenMS/FILTERING/DATAREDUCTION/SILACFiltering.h", "max_stars_repo_name": "open-ms/all-svn-branches", "max_stars_repo_head_hexsha": "b182ba576e0cbfbe420b8edb0dd1c42bb6c973f3", "max_stars_repo_licenses": ["Zlib", "Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-05-23T03:43:10.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-23T03:43:10.000Z", "max_issues_repo_path": "src/openms/include/OpenMS/FILTERING/DATAREDUCTION/SILACFiltering.h", "max_issues_repo_name": "kreinert/OpenMS", "max_issues_repo_head_hexsha": "45455356482ce5ab35e32e445609b291ec78a6d6", "max_issues_repo_licenses": ["Zlib", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/openms/include/OpenMS/FILTERING/DATAREDUCTION/SILACFiltering.h", "max_forks_repo_name": "kreinert/OpenMS", "max_forks_repo_head_hexsha": "45455356482ce5ab35e32e445609b291ec78a6d6", "max_forks_repo_licenses": ["Zlib", "Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8514285714, "max_line_length": 153, "alphanum_fraction": 0.6548259778, "num_tokens": 1200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.399811640739795, "lm_q2_score": 0.01615283251326241, "lm_q1q2_score": 0.006458090469722551}}
{"text": "#include <stdio.h>\n#include <sys/mman.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <string.h>\n#include <semaphore.h>\n#include <signal.h>\n#include <sys/stat.h>\n#include <sys/times.h>\n#include <time.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n#include \"circular_buffer.h\"\n#include \"colorprint.h\"\n\nbool running = true;\npid_t pid;\ncircular_buffer *addr;\ndouble total_wait_time = 0.0;\ndouble total_blocked_time = 0.0;\nint total_consumed_messages = 0;\n\nsem_t *sem_mem_id;\nsem_t *sem_pro_id;\nsem_t *sem_con_id;\n\n\n\nvoid print_stats()\n{\n  struct tms cpu_times;\n  times(&cpu_times);\n  printf_color(1, \"[cyan]Tiempo de espera total:[/cyan] [yellow]%f s[/yellow]\\n\", total_wait_time);\n  printf_color(1, \"[cyan]Tiempo bloqueado total:[/cyan] [yellow]%f s[/yellow]\\n\", total_blocked_time);\n  printf_color(1, \"[cyan]Mensajes consumidos:[/cyan] [yellow]%i[/yellow]\\n\", total_consumed_messages);\n  printf_color(1, \"[cyan]Tiempo de usuario:[/cyan] [yellow]%ld[/yellow]\\n\", (long)cpu_times.tms_utime);\n  printf_color(1, \"[cyan]Tiempo de kernel:[/cyan] [yellow]%ld[/yellow]\\n\", (long)cpu_times.tms_stime);\n}\n\nvoid exit_by_id()\n{\n  printf_color(1, \"[bb][lw][info][/lw][/bb] Consumidor finalizado por ID (aleatorio). PID: %d.\\n\", pid);\n  print_stats();\n}\n\nvoid exit_by_finalizer()\n{\n  printf_color(1, \"[bb][lw][info][/lw][/bb] Consumidor cerrado por finalizador. PID: %d.\\n\", pid);\n  print_stats();\n}\n\nvoid intHandler(int dummy)\n{\n  printf(\"Finalizaci\u00f3n forzada.\\n\");\n  addr->current_consumers--;\n  print_stats();\n  exit(0);\n}\n\nint main(int argc, char *argv[])\n{\n  signal(SIGINT, intHandler);\n\n  const gsl_rng_type *T;\n  gsl_rng *r;\n  gsl_rng_env_setup();\n  T = gsl_rng_default;\n  r = gsl_rng_alloc(T);\n  gsl_ran_poisson(r, 5);\n\n  int fd;\n  time_t rawtime;\n  struct tm *timeinfo;\n\n  // Get argv\n  if (argc < 3)\n  {\n    printf_color(1, \"[red][br][lw][error][/lw][/br] No se han dado todos los argumentos necesarios.[/red]\\n\");\n    return -1;\n  }\n  char buffer_name[strlen(argv[1])];\n  strcpy(buffer_name, argv[1]);\n  int wait_time = atoi(argv[2]);\n\n  // Initialize strings for semaphore names\n  char *sem_mem_name_base = \"semaphore_memory_\";\n  char *sem_con_name_base = \"semaphore_consumers_\";\n  char *sem_prod_name_base = \"semaphore_producers_\";\n\n  char sem_mem_name[strlen(buffer_name) + strlen(sem_mem_name_base)];\n  char sem_con_name[strlen(buffer_name) + strlen(sem_con_name_base)];\n  char sem_prod_name[strlen(buffer_name) + strlen(sem_prod_name_base)];\n\n  strcpy(sem_mem_name, sem_mem_name_base);\n  strcat(sem_mem_name, buffer_name);\n  strcpy(sem_con_name, sem_con_name_base);\n  strcat(sem_con_name, buffer_name);\n  strcpy(sem_prod_name, sem_prod_name_base);\n  strcat(sem_prod_name, buffer_name);\n\n  pid = getpid();\n\n  printf_color(1, \"[bb][lw][info][/lw][/bb] Inicializando consumidor. PID: %d.\\n\", pid);\n  printf_color(1, \"[bb][lw][info][/lw][/bb] Nombre de buffer dado: %s.\\n\", buffer_name);\n  printf_color(1, \"[bb][lw][info][/lw][/bb] Tiempo de espera promedio: %i ms.\\n\\n\", wait_time);\n\n  // get shared memory file descriptor (NOT a file)\n  fd = shm_open(buffer_name, O_RDWR, S_IRUSR | S_IWUSR);\n  if (fd == -1)\n  {\n    printf_color(1, \"[br][lw][error][/lw][/br] [red]El buffer no se ha inicializado.[/red]\\n\");\n    return 10;\n  }\n\n  // Get shared memory size from file descriptor\n  struct stat finfo;\n  fstat(fd, &finfo);\n  off_t shared_memory_size = finfo.st_size;\n\n  // map shared memory to process address space\n  addr = mmap(NULL, shared_memory_size, PROT_WRITE, MAP_SHARED, fd, 0);\n  if (addr == MAP_FAILED)\n  {\n    printf_color(1, \"[br][lw][error][/lw][/br] [red]No se ha podido asignar suficiente memoria al proceso.[/red]\\n\");\n    return 30;\n  }\n\n  // Initialize semaphores\n  sem_mem_id = sem_open(sem_mem_name, O_CREAT, 0600, 1);\n  if (sem_mem_id == SEM_FAILED)\n  {\n    perror(\"SEMAPHORE_MEMORY_SYNC  : [sem_open] Failed\\n\");\n  }\n\n  sem_pro_id = sem_open(sem_prod_name, O_CREAT, 0600, addr->buffer_size);\n  if (sem_pro_id == SEM_FAILED)\n  {\n    perror(\"SEMAPHORE_MEMORY_SYNC  : [sem_open] Failed\\n\");\n  }\n\n  sem_con_id = sem_open(sem_con_name, O_CREAT, 0600, 0);\n  if (sem_con_id == SEM_FAILED)\n  {\n    perror(\"SEMAPHORE_MEMORY_SYNC  : [sem_open] Failed\\n\");\n  }\n\n  sem_wait(sem_mem_id);\n  addr->current_consumers++;\n  addr->total_consumers++;\n  sem_post(sem_mem_id);\n\n  int current_slot = 0;\n  long long t = 0;\n\n  while (running)\n  {\n    t = current_timestamp();\n\n    sem_wait(sem_con_id);\n    sem_wait(sem_mem_id);\n\n    // Add to total blocked time\n    t = current_timestamp() - t;\n    total_blocked_time = total_blocked_time + t / 1000.0;\n\n    current_slot = addr->next_message_to_consume;\n\n    cbuffer_message message = consume_message(addr);\n    total_consumed_messages++;\n\n    printf_color(1, \"\\n[bb]--------------------------------------------[/bb]\\n\");\n    printf_color(1, \"[cyan]Consumidor PID:[/cyan] [yellow]%i[/yellow]\\n\", pid);\n    printf_color(1, \"[cyan]Recibido mensaje del productor PID:[/cyan] [yellow]%i[/yellow]\\n\", message.producer_id);\n    printf_color(1, \"[cyan]Le\u00eddo del slot [yellow]%i[/yellow] del buffer[/cyan]\\n\", current_slot);\n    printf_color(1, \"[cyan]Contenido del mensaje:[/cyan] [yellow]%i[/yellow]\\n\", message.content);\n    printf_color(1, \"[cyan]N\u00famero m\u00e1gico:[/cyan] [yellow]%i[/yellow]\\n\", message.random);\n\n    time(&rawtime);\n    timeinfo = localtime(&rawtime);\n    printf_color(1, \"[cyan]Hora actual:[/cyan] [yellow]%s[/yellow]\", asctime(timeinfo));\n    printf_color(1, \"[cyan]Consumidores conectados:[/cyan] [yellow]%i[/yellow]\\n\", addr->current_consumers);\n    printf_color(1, \"[cyan]Productores conectados:[/cyan] [yellow]%i[/yellow]\\n\", addr->current_producers);\n\n    printf_color(1, \"[bb]--------------------------------------------[/bb]\\n\\n\");\n\n    sem_post(sem_mem_id);\n    sem_post(sem_pro_id); //+1 al semaforo para que consuman\n\n    if (message.type == KILL_CONSUMER)\n    {\n      running = false;\n      sem_wait(sem_con_id);\n      addr->current_consumers--;\n      sem_post(sem_mem_id);\n      exit_by_finalizer();\n    }\n    else if (message.random == pid % 6)\n    {\n      running = false;\n      sem_wait(sem_con_id);\n      addr->current_consumers--;\n      addr->consumers_killed_by_id++;\n      sem_post(sem_mem_id);\n      exit_by_id();\n    }\n    else\n    {\n      int random_wait = gsl_ran_poisson(r, wait_time);\n      //       int random_wait = gsl_ran_exponential(r,2000);\n      printf_color(1, \"[green]*********** Esperando %d ms ***********[/green]\\n\", random_wait);\n      total_wait_time = total_wait_time + random_wait / 1000.0;\n      //       sleep(random_wait/1000);\n      usleep(random_wait * 1000);\n    }\n  }\n\n  gsl_rng_free(r);\n  return 0;\n}\n", "meta": {"hexsha": "264344b3df8cb25c330f3b682966d72c7c82fbac", "size": 6620, "ext": "c", "lang": "C", "max_stars_repo_path": "consumer.c", "max_stars_repo_name": "JosephTico/semaforos-bozon-circular", "max_stars_repo_head_hexsha": "cc296bff171b36f8cb5db230e666507b7cd25fda", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "consumer.c", "max_issues_repo_name": "JosephTico/semaforos-bozon-circular", "max_issues_repo_head_hexsha": "cc296bff171b36f8cb5db230e666507b7cd25fda", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "consumer.c", "max_forks_repo_name": "JosephTico/semaforos-bozon-circular", "max_forks_repo_head_hexsha": "cc296bff171b36f8cb5db230e666507b7cd25fda", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0909090909, "max_line_length": 117, "alphanum_fraction": 0.665407855, "num_tokens": 1942, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1919327772028789, "lm_q2_score": 0.033589502264131835, "lm_q1q2_score": 0.006446926454417212}}
{"text": "#ifndef VM_ALLOC_STACK_RESOURCE_H\n#define VM_ALLOC_STACK_RESOURCE_H\n\n#include \"vm/alloc/memory_resource.h\"\n#include <gsl/span>\n#include <cstddef>\n\nnamespace wasm {\n\nstruct StackOverflowError:\n\tpublic std::bad_alloc\n{\n\tStackOverflowError(const char* pos, std::size_t count):\n\t\tstd::bad_alloc(), at(pos), requested(count)\n\t{\n\t\t\n\t}\n\n\tconst char* const at;\n\tconst std::size_t requested;\n};\n\nstruct BadAlignmentError:\n\tpublic std::bad_alloc\n{\n\tStackOverflowError(std::size_t req):\n\t\tstd::bad_alloc(), requested(req)\n\t{\n\t\t\n\t}\n\n\tconst std::size_t requested;\n};\n\nstruct StackResource:\n\tpublic pmr::memory_resource\n{\n\n\tstatic constexpr const std::size_t max_alignment = alignof(std::max_align_t);\n\n\tStackResource(char* base, std::size_t count):\n\t\tStackResource(gsl::span<char>(base, count))\n\t{\n\t\t\n\t}\n\t\n\tStackResource(gsl::span<char> buff):\n\t\tbase_(buff.data()),\n\t\tbuffer_(buff)\n\t{\n\t\tassert(buffer_.data() == base_);\n\t}\n\t\n\tStackResource(const StackResource& other) = delete;\n\n\tvoid* expand(void* p, std::size_t old_size, std::size_t new_size, std::size_t alignment)\n\t{\n\t\tassert(pos + bytes <= buffer_.data());\n\t\tassert(pos >= base_);\n\t\tassert((pos < buffer_.data()) or (old_size == 0u));\n\t\tassert(\n\t\t\t(pos == (buffer_.data() - bytes_adj))\n\t\t\tand \"Can only reallocate the most-recent allocation from a stack resource.\"\n\t\t);\n\t\tassert(new_size > old_size);\n\t\tassert((old_size == 0u) or is_aligned(pos, old_size, max_alignment));\n\t\tauto new_size_adj = adjusted_size(new_size);\n\t\tauto old_size_adj = adjusted_size(old_size);\n\t\tassert(new_size_adj >= old_size_adj);\n\t\tauto alloc_size = static_cast<std::size_t>(new_size_adj - old_size_adj);\n\t\tassert((alloc_size % max_alignment) == 0u);\n\t\tif(alloc_size == 0u);\n\t\t\treturn p;\n\t\tif(alloc_size > buffer_.size())\n\t\t\tthrow StackOverflowError(buffer_.data(), alloc_size);\n\t\tbuffer_ = buffer.subspan(alloc_size);\n\t\treturn p;\n\t}\n\n\tvoid* contract(void* p, std::size_t old_size, std::size_t new_size) override\n\t{\n\t\t_assert_invariants();\n\t\tconst char* pos = static_cast<const char*>(p);\n\t\tassert(pos + bytes <= buffer_.data());\n\t\tassert(pos >= base_);\n\t\tassert((pos < buffer_.data()) or (old_size == 0u));\n\t\tassert(\n\t\t\t(pos == (buffer_.data() - old_size))\n\t\t\tand \"Can only reallocate the most-recent allocation from a stack resource.\"\n\t\t);\n\t\tassert(new_size < old_size);\n\t\tassert(is_aligned(pos, old_size, max_alignment));\n\t\tauto new_size_adj = adjusted_size(new_size);\n\t\tauto old_size_adj = adjusted_size(old_size);\n\t\tassert(old_size_adj >= new_size_adj);\n\t\tstd::size_t dist = old_size_adj - new_size_adj;\n\t\tif(dist == 0u);\n\t\t\treturn p;\n\t\tassert(static_cast<std::ptrdiff_t>(dist) == (buffer_.data() - pos));\n\t\tbuffer_ = gsl::span<char>(p, buffer_.size() + dist);\n\t\t_assert_invariants();\n\t\treturn p;\n\t}\n\n\tstd::size_t capacity() const\n\t{ return (buffer_.data() + buffer_.size()) - base_; }\n\n\tgsl::span<const char> inspect() const\n\t{ return gsl::span<const char>(base_, buffer_.data() - base_); }\n\nprivate:\n\t\n\tstatic bool is_power_of_two(std::size_t value)\n\t{\n\t\tassert(value > 0u);\n\t\treturn not static_cast<bool>(value & (value - 1u));\n\t}\n\n\tstatic bool is_aligned(const char* p, std::size_t count, std::size_t alignment)\n\t{\n\t\tassert(is_power_of_two(alignment));\n\t\treturn p == std::align(alignment, 1u, p, count);\n\t}\n\n\tstatic char* ensure_aligned(char*& base, std::size_t& count)\n\t{\n\t\tassert(base);\n\t\tassert(count);\n\t\tif(not std::align(alignof(std::max_align_t), 1u, base, count))\n\t\t\tthrow std::invalid_argument(\"Pointer-size pair could not be aligned in 'StackResource' constructor.\");\n\t}\n\n\tstatic std::size_t adjust_size(std::size_t size)\n\t{\n\t\tauto err = size % max_alignment;\n\t\tif(err != 0u)\n\t\t\tsize += max_alignment - err;\n\t\treturn size;\n\t}\n\n\tvoid do_deallocate(void* p, std::size_t bytes, std::size_t alignment) override\n\t{\n\t\t_assert_invariants();\n\t\tconst char* pos = static_cast<const char*>(p);\n\t\tstd::size_t alloc_size = adjusted_size(bytes);\n\t\tassert(is_aligned(pos, alloc_size, max_alignment));\n\t\tassert(std::distance(base_, buffer_.data()) >= alloc_size);\n\t\tassert(\n\t\t\tpos + alloc_size == buffer_.data()\n\t\t\tand \"Attempt to deallocate memory from a StackResource in non FIFO order.\"\n\t\t);\n\t\tassert((pos < buffer_.data()) or (bytes == 0u));\n\t\tassert(pos >= base_);\n\t\tbuffer_ = gsl::span<char>(pos, buffer_.size() + alloc_size);\n\t\t_assert_invariants();\n\t}\n\n\tvoid* do_allocate(std::size_t bytes, std::size_t alignment) override\n\t{\n\t\t_assert_invariants();\n\t\tvoid* pos = buffer_.data();\n\t\tif(alignment > max_alignment)\n\t\t\tthrow BadAlignmentError(alignment);\n\t\tstd::size_t alloc_size = adjusted_size(bytes);\n\t\tstd::size_t len = buffer_.size();\n\t\tif(buffer.size() < alloc_size)\n\t\t\tthrow StackOverflowError(buffer_.data(), bytes);\n\t\tbuffer_ = buffer_.subspan(alloc_size);\n\t\t_assert_invariants();\n\t\treturn pos;\n\t}\n\n\tvoid _assert_invariants() const\n\t{\n\t\tauto buff_pos = buffer_.data();\n\t\tassert(base_ <= buff_pos);\n\t\tauto allocd = static_cast<std::size_t>(buff_pos - base_);\n\t\tassert(allocd == 0u or is_aligned(base_, allocd, max_alignment));\n\t\tassert(buffer_.size() == 0u or is_aligned(buff_pos, buffer_.size(), max_alignment));\n\t}\n\t\n\tbool do_is_equal(const pmr::memory_resource& other) const override\n\t{\n\t\tif(this == &other)\n\t\t\treturn true;\n\t\treturn false;\n\t}\n\nprivate:\n\tchar* const base_;\n\tgsl::span<char> buffer_;\n};\n\n\ntemplate <class T>\nstruct SimpleStack\n{\n\tusing value_type             = T;\n\tusing size_type              = std::size_t;\n\tusing difference_type        = std::ptrdiff_t;\n\tusing reference              = value_type&;\n\tusing const_reference        = const value_type&;\n\tusing pointer                = value_type*;\n\tusing const_pointer          = const value_type*;\n\tusing iterator               = std::reverse_iterator<pointer>;\n\tusing const_iterator         = std::reverse_iterator<const_pointer>;\n\tusing reverse_iterator       = std::reverse_iterator<iterator>;\n\tusing const_reverse_iterator = std::reverse_iterator<const_iterator>;\n\n\tSimpleStack(StackResource& resource):\n\t\tresource_(resource),\n\t\tbase_(resource_.allocate(0u, alignof(T))),\n\t\tcount_(0u)\n\t{\n\t\t\n\t}\n\n\t~SimpleStack()\n\t{\n\t\tstd::destroy(begin(), end());\n\t\tresource_.deallocate(data(), size() * sizeof(T), alignof(T));\n\t}\n\n\tSimpleStack() = delete;\n\tSimpleStack(const SimpleStack&) = delete;\n\tSimpleStack(SimpleStack&&) = delete;\n\n\tSimpleStack& operator=(const SimpleStack&) = delete;\n\tSimpleStack& operator=(SimpleStack&&) = delete;\n\n\t/// @name Iterators \n\t/// @{\n\n\titerator begin()\n\t{ return std::make_reverse_iterator(data() + size()); }\n\n\tconst_iterator begin() const\n\t{ return cbegin(); }\n\n\tconst_iterator cbegin() const\n\t{ return std::make_reverse_iterator(data() + size()); }\n\n\treverse_iterator rbegin() \n\t{ return std::make_reverse_iterator(end()); }\n\n\tconst_reverse_iterator rbegin() const\n\t{ return crbegin(); }\n\n\tconst_reverse_iterator crbegin() const\n\t{ return std::make_reverse_iterator(cend()); }\n\n\titerator end()\n\t{ return std::make_reverse_iterator(data()); }\n\n\tconst_iterator end() const\n\t{ return cend(); }\n\n\tconst_iterator cend() const\n\t{ return std::make_reverse_iterator(data()); }\n\n\treverse_iterator rend() \n\t{ return std::make_reverse_iterator(begin()); }\n\n\tconst_reverse_iterator rend() const\n\t{ return crend(); }\n\n\tconst_reverse_iterator crend() const\n\t{ return std::make_reverse_iterator(cbegin()); }\n\n\t/// @} Iterators\n\n\t/// @name Modifiers\n\t/// @{\n\n\tvoid push(const T& value)\n\t{ emplace(value); }\n\n\tvoid push(T&& value)\n\t{ emplace(std::move(value)); }\n\n\ttemplate <class ... Args>\n\treference emplace(Args&& ... args)\n\t{\n\t\talloc_n(1u);\n\t\tpointer p = ::new (base_ + (size() - 1)) T(std::forward<Args>(args)...);\n\t\treturn *p;\n\t}\n\n\ttemplate <class ... Args>\n\treference replace_top(Args&& ... args)\n\t{\n\t\tassert(size() > 0u);\n\t\tpointer p = std::addressof(top());\n\t\tdestroy_at(p);\n\t\tp = ::new (p) T(std::forward<Args>(args)...);\n\t\treturn *std::launder(p);\n\t}\n\n\tvalue_type pop()\n\t{\n\t\tassert(not empty());\n\t\tauto v = top();\n\t\tpop(1u);\n\t\treturn v;\n\t}\n\n\tvoid pop_n(std::size_t n)\n\t{\n\t\tassert(n > 0u);\n\t\tassert(size() >= n);\n\t\tstd::destroy(begin(), begin() + n);\n\t\tdealloc_n(n);\n\t}\n\n\t/// @} Modifiers\n\n\t/// @name Element Access\n\t/// @{\n\n\tconst_reference top() const\n\t{\n\t\tassert(not empty());\n\t\treturn base_[size() - 1];\n\t}\n\n\treference top()\n\t{\n\t\tassert(not empty());\n\t\treturn base_[size() - 1u];\n\t}\n\n\tconst_reference operator[](size_type i) const\n\t{\n\t\tassert(not empty());\n\t\tassert(i < size());\n\t\treturn data()[((size() - 1) - i)];\n\t}\n\n\treference operator[](size_type i)\n\t{ return const_cast<reference>(std::as_const(*this)[i]); }\n\n\tconst_reference at(size_type i) const\n\t{\n\t\tif(i < size())\n\t\t\treturn (*this)[i];\n\t\tthrow std::out_of_range(\"Attempt to access value in stack at an out-of-range depth.\");\n\t}\n\n\treference at(size_type i)\n\t{ return const_cast<reference>(std::as_const(*this).at(i)); }\n\n\tconst_pointer data() const\n\t{ return base_; }\n\n\tpointer data()\n\t{ return base_; }\n\n\t/// @} Element Access\n\n\t/// @name Capacity\n\t/// @{\n\n\tsize_type size() const\n\t{ return count_; }\n\n\tsize_type max_size() const\n\t{ return std::numeric_limits<std::size_t>::max() / sizeof(T); }\n\n\tbool empty() const\n\t{ return size() == 0u; }\n\n\t/// @} Capacity\n\n\tconst StackResource& get_resource() const\n\t{ return resource_; }\n\n\tStackResource& get_resource()\n\t{ return resource_; }\n\nprivate:\n\tvoid alloc_n(std::size_t n)\n\t{\n\t\tassert(n > 0u);\n\t\tT* pos = static_cast<T*>(resource_.expand(base_, sizeof(T) * n, alignof(T)));\n\t\tassert(pos == base_);\n\t\tbase_ = pos;\n\t\tcount_ += n;\n\t}\n\t\n\tvoid dealloc_n(std::size_t n)\n\t{\n\t\tassert(n > 0u);\n\t\tassert(count_ >= n);\n\t\tT* pos = static_cast<T*>(resource_.contract(base_, n * sizeof(T), alignof(T)));\n\t\tbase_ = pos;\n\t\tcount_ -= n;\n\t}\n\n\n\tStackResource& resource_;\n\tT* base_;\n\tstd::size_t count_;\n};\n\n\n} /* namespace wasm */\n\n\n\n#endif /* VM_ALLOC_STACK_RESOURCE_H */\n", "meta": {"hexsha": "a8386c85d9b48c3454aab2a95601bbcf781086d3", "size": 9691, "ext": "h", "lang": "C", "max_stars_repo_path": "include/vm/alloc/StackResource.h", "max_stars_repo_name": "tvanslyke/wasm-cpp", "max_stars_repo_head_hexsha": "8a56c1706e2723ece36e3642bae9e36792dbd7b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/vm/alloc/StackResource.h", "max_issues_repo_name": "tvanslyke/wasm-cpp", "max_issues_repo_head_hexsha": "8a56c1706e2723ece36e3642bae9e36792dbd7b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/vm/alloc/StackResource.h", "max_forks_repo_name": "tvanslyke/wasm-cpp", "max_forks_repo_head_hexsha": "8a56c1706e2723ece36e3642bae9e36792dbd7b2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5790754258, "max_line_length": 105, "alphanum_fraction": 0.6719636776, "num_tokens": 2630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2720245628973633, "lm_q2_score": 0.02368947254868805, "lm_q1q2_score": 0.006444118415325954}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef tree_5172eda7_51f9_405a_9f3b_bcaa5e4243c1_h\r\n#define tree_5172eda7_51f9_405a_9f3b_bcaa5e4243c1_h\r\n\r\n#include <assert.h>\r\n#include <gslib/std.h>\r\n#include <gslib/string.h>\r\n\r\n__gslib_begin__\r\n\r\nstruct _tree_trait_copy {};\r\nstruct _tree_trait_detach {};\r\n\r\ntemplate<class _node>\r\nstruct _treenode_list\r\n{\r\npublic:\r\n    typedef _node mynode;\r\n    typedef _treenode_list<_node> mylist;\r\n\r\nprotected:\r\n    mynode*         _first;\r\n    mynode*         _last;\r\n    int             _size;\r\n\r\npublic:\r\n    _treenode_list() { reset(); }\r\n    _treenode_list(mynode* node) { setup(node, node, 1); }\r\n    _treenode_list(mynode* first, mynode* last, int size) { setup(first, last, size); }\r\n    _treenode_list(mynode* first, mynode* last) { setup(first, last, count_nodes(first, last)); }\r\n    bool empty() const { return !_size; }\r\n    int size() const { return _size; }\r\n    mynode* front() const { return _first; }\r\n    mynode* back() const { return _last; }\r\n    template<class _lambda>\r\n    void for_each(_lambda lam) { for_each(_first, _last, lam); }\r\n\r\npublic:\r\n    void setup(mynode* first, mynode* last, int size)\r\n    {\r\n        _first = first;\r\n        _last = last;\r\n        _size = size;\r\n    }\r\n    void reset()\r\n    {\r\n        _first = _last = nullptr;\r\n        _size = 0;\r\n    }\r\n    void swap(mylist& that)\r\n    {\r\n        gs_swap(_first, that._first);\r\n        gs_swap(_last, that._last);\r\n        gs_swap(_size, that._size);\r\n    }\r\n    void erase(mynode* node)\r\n    {\r\n        assert(node);\r\n        mynode* prev = node->prev();\r\n        mynode* next = node->next();\r\n        join(prev, next);\r\n        if(node == _first)\r\n            _first = next;\r\n        if(node == _last)\r\n            _last = prev;\r\n        node->_prev = node->_next = nullptr;\r\n        _size --;\r\n    }\r\n    void init(mynode* node)\r\n    {\r\n        assert(node);\r\n        assert(!_first && !_last && !_size);\r\n        _first = _last = node;\r\n        _size = 1;\r\n    }\r\n    void insert_before(mynode* pos, mynode* node)\r\n    {\r\n        assert(node);\r\n        if(pos == nullptr)\r\n            return init(node);\r\n        join(pos->prev(), node);\r\n        join(node, pos);\r\n        if(pos == _first)\r\n            _first = node;\r\n        _size ++;\r\n    }\r\n    void insert_after(mynode* pos, mynode* node)\r\n    {\r\n        assert(node);\r\n        if(pos == nullptr)\r\n            return init(node);\r\n        join(node, pos->next());\r\n        join(pos, node);\r\n        if(pos == _last)\r\n            _last = node;\r\n        _size ++;\r\n    }\r\n    void connect(mylist& that)\r\n    {\r\n        if(empty())\r\n            return swap(that);\r\n        else if(that.empty())\r\n            return;\r\n        assert(!empty() && !that.empty());\r\n        join(back(), that.front());\r\n        _size += that.size();\r\n        _last = that.back();\r\n        that.reset();\r\n    }\r\n\r\npublic:\r\n    static int count_nodes(mynode* first, mynode* last)\r\n    {\r\n        assert(first && last);\r\n        int c = 0;\r\n        mynode* n = first;\r\n        for(;;) {\r\n            c ++;\r\n            if(n == last)\r\n                return c;\r\n            n = n->next();\r\n        }\r\n        return c;\r\n    }\r\n    static void join(mynode* node1, mynode* node2)\r\n    {\r\n        if(node1 != nullptr)\r\n            node1->_next = node2;\r\n        if(node2 != nullptr)\r\n            node2->_prev = node1;\r\n    }\r\n    template<class _lambda>\r\n    static void for_each(mynode* first, mynode* last, _lambda lam)\r\n    {\r\n        if(!first)\r\n            return;\r\n        for(mynode* node = first; node != last; ) {\r\n            mynode* next = node->next();\r\n            lam(node);\r\n            node = next;\r\n        }\r\n        lam(last);\r\n    }\r\n};\r\n\r\ntemplate<class _wrapper>\r\nstruct _treenode_default_wrapper\r\n{\r\n    typedef _wrapper wrapper;\r\n    typedef _treenode_default_wrapper<wrapper> default_wrapper;\r\n    typedef _treenode_list<wrapper> children;\r\n    template<class, class, class> friend class tree;\r\n    template<class> friend struct _treenode_list;\r\n\r\nprotected:\r\n    wrapper*        _parent;\r\n    wrapper*        _prev;\r\n    wrapper*        _next;\r\n    children        _children;\r\n\r\npublic:\r\n    default_wrapper() { _parent = _prev = _next = nullptr; }\r\n    int childs() const { return _children.size(); }\r\n    wrapper* parent() const { return _parent; }\r\n    wrapper* prev() const { return _prev; }\r\n    wrapper* next() const { return _next; }\r\n    wrapper* child() const { return _children.empty() ? nullptr : _children.front(); }\r\n    wrapper* last_child() const { return _children.empty() ? nullptr : _children.back(); }\r\n    void birth_before(wrapper* pos, wrapper* node) { return _children.insert_before(pos, node); }\r\n    void birth_after(wrapper* pos, wrapper* node) { return _children.insert_after(pos, node); }\r\n    void erase(wrapper* node) { return _children.erase(node); }\r\n    void acquire_children(children& chs)\r\n    {\r\n        chs.for_each([this](wrapper* w) { w->_parent = static_cast<wrapper*>(this); });\r\n        _children.swap(chs);\r\n    }\r\n    void swap_children(wrapper& w)\r\n    {\r\n        children t;\r\n        t.swap(_children);\r\n        w.acquire_children(t);\r\n        acquire_children(t);\r\n    }\r\n    void reset_children() { _children.reset(); }\r\n    template<class _lambda>\r\n    void for_each(_lambda lam) { _children.for_each(lam); }\r\n};\r\n\r\ntemplate<class _ty>\r\nstruct _treenode_cpy_wrapper:\r\n    public _treenode_default_wrapper<_treenode_cpy_wrapper<_ty> >\r\n{\r\n    typedef _ty value;\r\n    typedef _treenode_cpy_wrapper<_ty> wrapper;\r\n    typedef _treenode_list<wrapper> children;\r\n    typedef _tree_trait_copy tsf_behavior;\r\n    template<class, class, class> friend class tree;\r\n\r\nprotected:\r\n    value           _value;\r\n\r\npublic:\r\n    value* get_ptr() { return &_value; }\r\n    const value* get_ptr() const { return &_value; }\r\n    value& get_ref() { return _value; }\r\n    const value& get_ref() const { return _value; }\r\n    template<class _ctor>\r\n    void born() {}\r\n    void born() {}\r\n    void kill() {}\r\n    void copy(const wrapper* a) { _value = a->_value; }\r\n    void attach(wrapper* a) { !!error!! }\r\n};\r\n\r\ntemplate<class _ty>\r\nstruct _treenode_wrapper:\r\n    public _treenode_default_wrapper<_treenode_wrapper<_ty> >\r\n{\r\n    typedef _ty value;\r\n    typedef _treenode_wrapper<_ty> wrapper;\r\n    typedef _treenode_list<wrapper> children;\r\n    typedef _tree_trait_detach tsf_behavior;\r\n    template<class, class, class> friend class tree;\r\n\r\nprotected:\r\n    value*          _value;\r\n\r\npublic:\r\n    wrapper() { _value = nullptr; }\r\n    value* get_ptr() const { return _value; }\r\n    value& get_ref() const { return *_value; }\r\n    template<class _ctor>\r\n    void born() { _value = new _ctor; }\r\n    template<class _ctor, class _a1>\r\n    void born(_a1& a) { _value = new _ctor(a); }\r\n    template<class _ctor, class _a1, class _a2>\r\n    void born(_a1& a, _a2& b) { _value = new _ctor(a, b); }\r\n    template<class _ctor, class _a1, class _a2, class _a3>\r\n    void born(_a1& a, _a2& b, _a3& c) { _value = new _ctor(a, b, c); }\r\n    void born() { _value = new value; }\r\n    void kill() { delete _value; }\r\n    void copy(const wrapper* a) { assert(!\"prevent.\"); }\r\n    void attach(wrapper* a)\r\n    {\r\n        assert(a && a->_value);\r\n        kill();\r\n        _value = a->_value;\r\n        a->_value = nullptr;\r\n    }\r\n};\r\n\r\ntemplate<class _wrapper>\r\nstruct _tree_allocator\r\n{\r\n    typedef _wrapper wrapper;\r\n    static wrapper* born() { return new wrapper; }\r\n    static void kill(wrapper* w) { delete w; }\r\n};\r\n\r\ntemplate<class _val>\r\nstruct _treenode_val\r\n{\r\n    typedef _val value;\r\n    typedef const _val const_value;\r\n    template<class, class, class> friend class tree;\r\n    union\r\n    {\r\n        value*          _vptr;\r\n        const_value*    _cvptr;\r\n    };\r\n    value* get_wrapper() const { return _vptr; }\r\n    operator bool() const { return _vptr != nullptr; }\r\n\r\nprotected:\r\n    value* vparent() const { return _vptr ? _vptr->_parent : nullptr; }\r\n    value* vchild() const { return _vptr ? _vptr->front() : nullptr; }\r\n    value* vchild_last() const { return _vptr ? _vptr->back() : nullptr; }\r\n    value* vsibling() const {  return _vptr ? _vptr->next() : nullptr; }\r\n    value* vsibling_last() const { return _vptr ? _vptr->prev() : nullptr; }\r\n\r\nprotected:\r\n    template<class _lambda, class _value>\r\n    static void preorder_traversal(_lambda lam, _value* v)\r\n    {\r\n        assert(v);\r\n        lam(v);\r\n        for(_value* w = v->child(); w; w = w->next())\r\n            preorder_traversal(lam, w);\r\n    }\r\n    template<class _lambda, class _value>\r\n    static void postorder_traversal(_lambda lam, _value* v)\r\n    {\r\n        assert(v);\r\n        for(_value* w = v->child(); w; w = w->next())\r\n            postorder_traversal(lam, w);\r\n        lam(v);\r\n    }\r\n\r\npublic:\r\n    template<class _lambda>\r\n    void preorder_traversal(_lambda lam) { if(_vptr) preorder_traversal(lam, _vptr); }\r\n    template<class _lambda>\r\n    void preorder_traversal(_lambda lam) const { if(_cvptr) preorder_traversal(lam, _cvptr); }\r\n    template<class _lambda>\r\n    void postorder_traversal(_lambda lam) { if(_vptr) postorder_traversal(lam, _vptr); }\r\n    template<class _lambda>\r\n    void postorder_traversal(_lambda lam) const { if(_cvptr) postorder_traversal(lam, _cvptr); }\r\n};\r\n\r\ntemplate<class _ty,\r\n    class _wrapper = _treenode_cpy_wrapper<_ty> >\r\nclass _tree_const_iterator:\r\n    public _treenode_val<_wrapper>\r\n{\r\npublic:\r\n    typedef _ty value;\r\n    typedef _wrapper wrapper;\r\n    typedef _tree_const_iterator<value, wrapper> iterator;\r\n    template<class, class, class> friend class tree;\r\n    \r\npublic:\r\n    iterator(const wrapper* w = nullptr) { _cvptr = w; }\r\n    bool is_valid() const { return _cvptr != nullptr; }\r\n    const value* get_ptr() const { return _cvptr->get_ptr(); }\r\n    const value* operator->() const { return _cvptr->get_ptr(); }\r\n    const value& operator*() const { return _cvptr->get_ref(); }\r\n    int childs() const { return _cvptr->childs(); }\r\n    int siblings() const { return _cvptr->parent() ? _cvptr->parent()->childs() : 1; }\r\n    bool is_root() const { return _cvptr ? !_cvptr->parent() : false; }\r\n    bool is_leaf() const { return _cvptr ? !_cvptr->childs() : false; }\r\n    bool operator==(const iterator& that) const { return _cvptr == that._cvptr; }\r\n    bool operator!=(const iterator& that) const { return _cvptr != that._cvptr; }\r\n    iterator child() const { return _cvptr ? iterator(_cvptr->child()) : iterator(); }\r\n    iterator last_child() const { return _cvptr ? iterator(_cvptr->last_child()) : iterator(); }\r\n    iterator parent() const { return _cvptr ? iterator(_cvptr->parent()) : iterator(); }\r\n    iterator next() const { return _cvptr ? iterator(_cvptr->next()) : iterator(); }\r\n    iterator prev() const { return _cvptr ? iterator(_cvptr->prev()) : iterator(); }\r\n    iterator root() const\r\n    {\r\n        if(const wrapper* w = _cvptr)\r\n        {\r\n            for( ; w->parent(); w = w->parent());\r\n            return iterator(w);\r\n        }\r\n        return iterator();\r\n    }\r\n    iterator eldest() const\r\n    {\r\n        if(const wrapper* w = _cvptr ? _cvptr->parent() : nullptr)\r\n            return iterator(w->child());\r\n        return iterator();\r\n    }\r\n    iterator youngest() const\r\n    {\r\n        if(const wrapper* w = _cvptr ? _cvptr->parent() : nullptr)\r\n            return iterator(w->last_child());\r\n        return iterator();\r\n    }\r\n};\r\n\r\ntemplate<class _ty,\r\n    class _wrapper = _treenode_cpy_wrapper<_ty> >\r\nclass _tree_iterator:\r\n    public _tree_const_iterator<_ty, _wrapper>\r\n{\r\npublic:\r\n    typedef _ty value;\r\n    typedef _wrapper wrapper;\r\n    typedef _tree_const_iterator<value, wrapper> superref;\r\n    typedef _tree_const_iterator<value, wrapper> const_iterator;\r\n    typedef _tree_iterator<value, wrapper> iterator;\r\n    template<class, class, class> friend class tree;\r\n\r\npublic:\r\n    iterator(wrapper* w = nullptr): superref(w) {}\r\n    value* get_ptr() const { return _vptr->get_ptr(); }\r\n    value* operator->() const { return _vptr->get_ptr(); }\r\n    value& operator*() const { return _vptr->get_ref(); }\r\n    bool operator==(const iterator& that) const { return _vptr == that._vptr; }\r\n    bool operator!=(const iterator& that) const { return _vptr != that._vptr; }\r\n    bool operator==(const const_iterator& that) const { return _vptr == that._vptr; }\r\n    bool operator!=(const const_iterator& that) const { return _vptr != that._vptr; }\r\n    operator const_iterator() { return const_iterator(_cvptr); }\r\n    void to_root() { while(wrapper* w = _vptr->parent()) _vptr = w; }\r\n    void to_child() { _vptr = _vptr->child(); }\r\n    void to_last_child() { _vptr = _vptr->last_child(); }\r\n    void to_parent() { _vptr = _vptr->parent(); }\r\n    void to_next() { _vptr = _vptr->next(); }\r\n    void to_prev() { _vptr = _vptr->prev(); }\r\n    void to_eldest() { if(wrapper* w = _vptr->parent()) _vptr = w->child(); }\r\n    void to_youngest() { if(wrapper* w = _vptr->parent()) _vptr = w->last_child(); }\r\n    iterator root() const\r\n    {\r\n        iterator i(_vptr);\r\n        i.to_root();\r\n        return i;\r\n    }\r\n    iterator child() const { return _vptr ? iterator(_vptr->child()) : iterator(); }\r\n    iterator last_child() const { return _vptr ? iterator(_vptr->last_child()) : iterator(); }\r\n    iterator parent() const { return _vptr ? iterator(_vptr->parent()) : iterator(); }\r\n    iterator next() const { return _vptr ? iterator(_vptr->next()) : iterator(); }\r\n    iterator prev() const { return _vptr ? iterator(_vptr->prev()) : iterator(); }\r\n    iterator eldest() const\r\n    {\r\n        iterator i(_vptr);\r\n        i.to_eldest();\r\n        return i;\r\n    }\r\n    iterator youngest() const\r\n    {\r\n        iterator i(_vptr);\r\n        i.to_youngest();\r\n        return i;\r\n    }\r\n};\r\n\r\ntemplate<class _ty, \r\n    class _wrapper = _treenode_cpy_wrapper<_ty>,\r\n    class _alloc = _tree_allocator<_wrapper> >\r\nclass tree:\r\n    public _treenode_val<_wrapper>\r\n{\r\npublic:\r\n    typedef _ty value;\r\n    typedef _wrapper wrapper;\r\n    typedef _alloc alloc;\r\n    typedef tree<value, wrapper, alloc> myref;\r\n    typedef _tree_const_iterator<value, wrapper> const_iterator;\r\n    typedef _tree_iterator<value, wrapper> iterator;\r\n    friend class const_iterator;\r\n    friend class iterator;\r\n\r\npublic:\r\n    tree() { _vptr = nullptr; }\r\n    ~tree() { destroy(); }\r\n    void destroy() { erase(get_root()); }\r\n    void clear() { destroy(); }\r\n    void swap(myref& that) { gs_swap(_vptr, that._vptr); }\r\n    iterator get_root() { return iterator(_vptr); }\r\n    const_iterator get_root() const { return const_iterator(_cvptr); }\r\n    bool is_valid() const { return _cvptr != nullptr; }\r\n    iterator insert(iterator i) { return insert<value>(i); }\r\n    iterator insert_after(iterator i) { return insert_after<value>(i); }\r\n    iterator birth(iterator i) { return birth<value>(i); }\r\n    iterator birth_tail(iterator i) { return birth_tail<value>(i); }\r\n\r\npublic:\r\n    bool is_root(const_iterator i) const\r\n    {\r\n        if(!i.is_valid())\r\n            return false;\r\n        return _cvptr == i._cvptr;\r\n    }\r\n    bool is_mine(const_iterator i) const\r\n    {\r\n        if(!i.is_valid())\r\n            return false;\r\n        return is_root(i.root());\r\n    }\r\n    void set_root(wrapper* w)\r\n    {\r\n        assert(!_vptr && \"use attach method.\");\r\n        _vptr = w;\r\n    }\r\n    void erase(iterator i)\r\n    {\r\n        if(!i.is_valid())\r\n            return;\r\n        if(is_root(i)) {\r\n            _erase(i);\r\n            _vptr = nullptr;\r\n        }\r\n        else {\r\n            wrapper* w = i._vptr;\r\n            wrapper* p = w->parent();\r\n            p->erase(w);\r\n            _erase(i);\r\n        }\r\n    }\r\n    template<class _ctor>\r\n    iterator insert(iterator i)\r\n    {\r\n        if(!i.is_valid())\r\n            return _cvptr ? get_root() : _init<_ctor>();\r\n        wrapper* w = i._vptr;\r\n        wrapper* p = w->_parent;\r\n        wrapper* n = alloc::born();\r\n        n->born<_ctor>();\r\n        p->birth_before(w, n);\r\n        n->_parent = p;\r\n        return iterator(n);\r\n    }\r\n    template<class _ctor>\r\n    iterator insert_after(iterator i)\r\n    {\r\n        if(!i.is_valid())\r\n            return _cvptr ? get_root() : _init<_ctor>();\r\n        wrapper* w = i._vptr;\r\n        wrapper* p = w->_parent;\r\n        wrapper* n = alloc::born();\r\n        n->born<_ctor>();\r\n        p->birth_after(w, n);\r\n        n->_parent = p;\r\n        return iterator(n);\r\n    }\r\n    template<class _ctor>\r\n    iterator birth(iterator i)\r\n    {\r\n        if(!i.is_valid())\r\n            return _cvptr ? get_root() : _init<_ctor>();\r\n        wrapper* w = i._vptr;\r\n        wrapper* n = alloc::born();\r\n        n->born<_ctor>();\r\n        w->birth_before(w->child(), n);\r\n        n->_parent = w;\r\n        return iterator(n);\r\n    }\r\n    template<class _ctor>\r\n    iterator birth_tail(iterator i)\r\n    {\r\n        if(!i.is_valid())\r\n            return _cvptr ? get_root() : _init<_ctor>();\r\n        wrapper* w = i._vptr;\r\n        wrapper* n = alloc::born();\r\n        n->born<_ctor>();\r\n        w->birth_after(w->last_child(), n);\r\n        n->_parent = w;\r\n        return iterator(n);\r\n    }\r\n    myref& detach(myref& subtree, iterator i)\r\n    {\r\n        if(!i.is_valid() || !is_mine(i))\r\n            return subtree;\r\n        if(is_root(i))\r\n            _vptr = nullptr;\r\n        else {\r\n            wrapper* m = i._vptr;\r\n            wrapper* p = m->_parent;\r\n            p->erase(m);\r\n            m->_parent = nullptr;\r\n        }\r\n        subtree.~tree();\r\n        new (&subtree) tree(i);\r\n        return subtree;\r\n    }\r\n    template<class _tsftrait>\r\n    void transfer(wrapper* src, wrapper* des)\r\n    {\r\n    }\r\n    template<>\r\n    void transfer<_tree_trait_copy>(wrapper* src, wrapper* des)\r\n    {\r\n        assert(src && des);\r\n        des->copy(src);\r\n        des->swap_children(*src);\r\n        src->for_each([&](wrapper* w) { _erase(w); });\r\n        src->reset_children();\r\n    }\r\n    template<>\r\n    void transfer<_tree_trait_detach>(wrapper* src, wrapper* des)\r\n    {\r\n        assert(src && des);\r\n        des->attach(src);\r\n        des->swap_children(*src);\r\n        src->for_each([&](wrapper* w) { _erase(w); });\r\n        src->reset_children();\r\n    }\r\n    void attach(myref& subtree, iterator i)\r\n    {\r\n        assert(i.is_valid() && is_mine(i));\r\n        wrapper* w = subtree.get_root()._vptr;\r\n        assert(w);\r\n        transfer<wrapper::tsf_behavior>(w, i._vptr);\r\n        w = i._vptr;\r\n        for(wrapper* c = w->child(); c; c = c->next())\r\n            c->_parent = w;\r\n    }\r\n    template<class _ctor>\r\n    iterator swap(iterator p, myref& that)\r\n    {\r\n        assert(this != &that);\r\n        if(p == get_root()) {\r\n            swap(that);\r\n            return get_root();\r\n        }\r\n        iterator prevsib, grand;\r\n        prevsib = p.prev();\r\n        grand = p.parent();\r\n        assert(prevsib || grand);\r\n        myref t;\r\n        detach(t, p);\r\n        auto pos = prevsib ? insert_after<_ctor>(prevsib) : birth<_ctor>(grand);\r\n        assert(pos);\r\n        attach(that, pos);\r\n        that.swap(t);\r\n        return pos;\r\n    }\r\n\r\npublic:\r\n    template<class lambda>\r\n    void for_each(lambda lam) { for_each(get_root(), lam); }\r\n    template<class lambda>\r\n    void for_each(iterator i, lambda lam)\r\n    {\r\n        if(i.is_valid()) {\r\n            for(iterator j = i.child(); j.is_valid(); j.to_next())\r\n                for_each(j, lam);\r\n            lam(i.get_ptr());\r\n        }\r\n    }\r\n    template<class lambda>\r\n    void const_for_each(lambda lam) const { const_for_each(get_root(), lam); }\r\n    template<class lambda>\r\n    void const_for_each(const_iterator i, lambda lam) const\r\n    {\r\n        if(i.is_valid()) {\r\n            for(const_iterator j = i.child(); j.is_valid(); j = j.next())\r\n                for_each(j, lam);\r\n            lam(i.get_ptr());\r\n        }\r\n    }\r\n\r\nprotected:\r\n    tree(iterator i) { _vptr = i._vptr; }\r\n    void _erase(iterator i) { _erase(i.get_wrapper()); }\r\n    void _erase(wrapper* w)\r\n    {\r\n        assert(w);\r\n        for(auto* c = w->child(); c;) {\r\n            auto* n = c->next();\r\n            _erase(c);\r\n            c = n;\r\n        }\r\n        w->kill();\r\n        alloc::kill(w);\r\n    }\r\n    template<class _ctor>\r\n    iterator _init()\r\n    {\r\n        _vptr = alloc::born();\r\n        _vptr->born<_ctor>();\r\n        _vptr->_parent = nullptr;\r\n        return iterator(_vptr);\r\n    }\r\n\r\npublic:\r\n    bool debug_check(iterator i)\r\n    {\r\n        iterator f = i.prev(), b = i.next();\r\n        if(f.is_valid() && f.next() != i) { assert(0); return false; }\r\n        if(b.is_valid() && b.prev() != i) { assert(0); return false; }\r\n        for(iterator j = i.child(); j.is_valid(); j.to_next())\r\n            if(j.parent() != i) { assert(0); return false; }\r\n        return true;\r\n    }\r\n};\r\n\r\ntemplate<class _tree>\r\nclass _print_tree\r\n{\r\npublic:\r\n    typedef _tree tree;\r\n    typedef typename tree::value value;\r\n    typedef typename tree::iterator iterator;\r\n    typedef typename tree::const_iterator const_iterator;\r\n\r\nprotected:\r\n    tree&       _inst;\r\n    string      _src;\r\n\r\npublic:\r\n    _print_tree(tree& t):\r\n        _inst(t)\r\n    {\r\n    }\r\n    const gchar* print()\r\n    {\r\n        _src.clear();\r\n        append(_inst.get_root(), 0);\r\n        return _src.c_str();\r\n    }\r\n\r\nprotected:\r\n    string decorate(const_iterator i, int level)\r\n    {\r\n        if(!i.is_valid())\r\n            return string();\r\n        string r, a;\r\n        for(int j = 0; j < level; j ++)\r\n            r.append(_t(\"  \"));\r\n        i.is_leaf() ? r.append(_t(\"+ \")) : r.append(_t(\"- \"));\r\n        i.is_root() ? r.append(_t(\"root(\")) : a.format(_t(\"level%d(\"), level);\r\n        r.append(a);\r\n        r.append(i->to_string());\r\n        r.append(_t(\")\\n\"));\r\n        return r;\r\n    }\r\n    void append(const_iterator i, int level)\r\n    {\r\n        if(!i.is_valid())\r\n            return;\r\n        _src.append(decorate(i, level).c_str());\r\n        level ++;\r\n        for(i.to_child(); i.is_valid(); i.to_next())\r\n            append(i, level);\r\n    }\r\n};\r\n\r\n__gslib_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "9ce4e5bffdeb28937b8b42b663730725b8194de2", "size": 23287, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gslib/tree.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/gslib/tree.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gslib/tree.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 31.554200542, "max_line_length": 98, "alphanum_fraction": 0.5685575643, "num_tokens": 5908, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14414883832589578, "lm_q2_score": 0.04468087504301395, "lm_q1q2_score": 0.006440696232834969}}
{"text": "/* altHtmlPages.c - Program to create a web based browser\n   of altsplice predicitions. */\n\n#include \"common.h\"\n#include \"bed.h\"\n#include \"hash.h\"\n#include \"options.h\"\n#include \"chromKeeper.h\"\n#include \"binRange.h\"\n#include \"obscure.h\"\n#include \"linefile.h\"\n#include \"dystring.h\"\n#include \"altGraphX.h\"\n#include \"altSpliceSite.h\"\n#include \"hdb.h\"\n#include \"dnaseq.h\"\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_statistics_double.h>\n\nstruct junctSet \n/* A set of beds with a common start or end. */\n{\n    struct junctSet *next;   /* Next in list. */\n    char *chrom;                /* Chromosome. */\n    int chromStart;             /* Smallest start. */\n    int chromEnd;               /* Largest end. */\n    char *name;                 /* Name of junction. */\n    int junctCount;             /* Number of junctions in set. */\n    char strand[2];             /* + or - depending on which strand. */\n    int genePSetCount;          /* Number of gene probe sets. */\n    char **genePSets;           /* Gene probe set name. */\n    char *hName;                /* Human name for locus or affy id if not present. */\n    int maxJunctCount;          /* Maximum size of bedArray. */\n    char **junctPSets;          /* Beds in the cluster. */\n    int junctDupCount;          /* Number of redundant junctions in set. */\n    int maxJunctDupCount;       /* Maximum size of bedDupArray. */\n    char **dupJunctPSets;       /* Redundant beds in the cluster. */\n    int junctUsedCount;         /* Number of juction sets used. */\n    char **junctUsed;           /* Names of actual junction probe sets used. */\n    boolean cassette;           /* Is cassette exon set? */\n    char *exonPsName;           /* Cassette exon probe set if available. */\n    double **junctProbs;        /* Matrix of junction probabilities, rows are junctUsed. */ \n    double **geneProbs;         /* Matrix of gene set probabilities, rows are genePSets. */\n    double *exonPsProbs;        /* Exon probe set probabilities if cassette. */\n    double **junctIntens;       /* Matrix of junction intensities, rows are junctUsed. */ \n    double **geneIntens;        /* Matrix of gene set intensities, rows are genePSets. */\n    double *exonPsIntens;       /* Exon probe set intensities if cassette. */\n    boolean expressed;          /* TRUE if one form of this junction set is expressed. */\n    boolean altExpressed;       /* TRUE if more than one form of this junction set is expressed. */\n    double score;               /* Score of being expressed overall. */\n    double exonCorr;            /* Correlation of exon probe set with include junction if appropriate. */\n    double exonSkipCorr;        /* Correlation of exon probe set with skip junction if appropriate. */\n    double probCorr;            /* Correlation of exon probe set prob and include probs. */\n    double probSkipCorr;        /* Correlation of exon probe set prob skip junction if appropriate. */\n    double exonSjPercent;       /* Percentage of includes confirmed by exon probe set. */\n    double sjExonPercent;       /* Percentage of exons confirmed by sj probe set. */\n    int exonAgree;              /* Number of times exon agrees with matched splice junction */\n    int exonDisagree;           /* Number of times exon disagrees with matched splice junction. */\n    int sjAgree;                /* Number of times sj agrees with matched exon */\n    int sjDisagree;             /* Number of times sj disagrees with matched exon. */\n    int sjExp;                  /* Number of times sj expressed. */\n    int exonExp;                /* Number of times exon expressed. */\n    int spliceType;             /* Type of splicing event. */\n};\n\nstruct resultM \n/* Wrapper for a matrix of results. */\n{\n    struct hash *nameIndex;  /* Hash with integer index for each row name. */\n    int colCount;            /* Number of columns in matrix. */\n    char **colNames;         /* Column Names for matrix. */\n    int rowCount;            /* Number of rows in matrix. */\n    char **rowNames;         /* Row names for matrix. */\n    double **matrix;         /* The actual data for the resultM. */\n};\n\nstruct altCounts\n{\n    char *gene; /*Name of gene. */\n    int count; /* Number of alternative sites possible. */\n    int jsExpressed; /* Number of alternative sites where one isoform expressed. */\n    int jsAltExpressed; /* Number of alternative sites that are alternatively expressed. */\n};\n\n\nstatic struct optionSpec optionSpecs[] = \n/* Our acceptable options to be called with. */\n{\n    {\"help\", OPTION_BOOLEAN},\n    {\"junctFile\", OPTION_STRING},\n    {\"probFile\", OPTION_STRING},\n    {\"intensityFile\", OPTION_STRING},\n    {\"bedFile\", OPTION_STRING},\n    {\"sortByExonCorr\", OPTION_BOOLEAN},\n    {\"sortByExonPercent\", OPTION_BOOLEAN},\n    {\"htmlPrefix\", OPTION_STRING},\n    {\"hybeFile\", OPTION_STRING},\n    {\"presThresh\", OPTION_FLOAT},\n    {\"absThresh\", OPTION_FLOAT},\n    {\"strictDisagree\", OPTION_BOOLEAN},\n    {\"exonStats\", OPTION_STRING},\n    {\"spreadSheet\", OPTION_STRING},\n    {\"doSjRatios\", OPTION_BOOLEAN},\n    {\"log2Ratio\", OPTION_BOOLEAN},\n    {\"ratioFile\", OPTION_STRING},\n    {\"junctPsMap\", OPTION_STRING},\n    {\"agxFile\", OPTION_STRING},\n    {\"db\", OPTION_STRING},\n    {\"spliceTypes\", OPTION_STRING},\n    {\"tissueSpecific\", OPTION_STRING},\n    {\"outputDna\", OPTION_STRING},\n    {\"cassetteBed\", OPTION_STRING},\n    {\"geneStats\", OPTION_STRING},\n    {\"tissueExpThresh\", OPTION_INT},\n    {\"geneJsStats\", OPTION_STRING},\n    {\"brainSpecific\", OPTION_STRING},\n    {NULL, 0}\n};\n\nstatic char *optionDescripts[] = \n/* Description of our options for usage summary. */\n{\n    \"Display this message.\",\n    \"File containing junctionSets from plotAndCountAltsMultGs.R log.\",\n    \"File containing summarized probability of expression for each probe set.\",\n    \"File containing expression values for each probe set.\",\n    \"File containing beds for each probe set.\",\n    \"Flag to sort by exon correlation when present.\",\n    \"Flag to sort by exon percent agreement with splice junction when present.\",\n    \"Prefix for html files, i.e. <prefix>lists.html and <prefix>frame.html\",\n    \"File giving names and ids for hybridizations.\",\n    \"Optional threshold at which to call expressed.\",\n    \"Optional threshold at which to call not expressed.\",\n    \"Call disagreements only if below absense threshold instead of below present thresh.\",\n    \"File to output confirming exon stats to.\",\n    \"File to output spreadsheet format picks to.\",\n    \"[optional] Calculate ratios of sj to other sj in same junction set.\",\n    \"[optional] Transform ratios with log base 2.\",\n    \"[optional] File to store sjRatios in.\",\n    \"[optional] Print out the probe sets in a junction set and quit.\",\n    \"[optional] File with graphs to determine types.\",\n    \"[optional] Database that graphs are from.\",\n    \"[optional] Try to determine types of splicing in junction sets.\",\n    \"[optional] Output tissues specific isoforms to file specified.\",\n    \"[optional] Output dna associated with a junction to this file.\",\n    \"[optional] Output splice sites for cassette exons.\",\n    \"[optional] Output stats about genes, junctions expressed, junctions alt to file name.\",\n    \"[optional] Number of tissues that must express a probe set before considred expressed.\",\n    \"[optional] Print out junction sets per gene stats.\",\n    \"[optional] Output brain specific isoforms to file specified.\",\n};\n\n\nint tissueExpThresh = 0;   /* Number of tissues that must express probe set. */\ndouble presThresh = 0;     /* Probability above which we consider\n\t\t\t    * something expressed. */\ndouble absThresh = 0;      /* Probability below which we consider\n\t\t\t    * something not expressed. */\ndouble disagreeThresh = 0; /* Probability below which we consider\n\t\t\t    * something to disagree. */\nFILE *exonPsStats = NULL;  /* File to output exon probe set \n\t\t\t      confirmation stats into. */\nFILE *geneCounts = NULL;   /* Print out the gene junction counts. */\nboolean doJunctionTypes = FALSE;  /* Should we try to determine what type of splice type is out there? */ \nFILE *bedJunctTypeOut =   NULL;   /* File to write out bed types to. */\nstruct hash *junctBedHash = NULL;\nFILE *cassetteBedOut = NULL;      /* File to write cassette bed records to. */\n/* Counts of different alternative splicing \n   events. */\nint alt3Count = 0;\nint alt3SoftCount = 0;\nint alt5Count = 0;\nint alt5SoftCount = 0;\nint altCassetteCount = 0;\nint otherCount = 0;\n\n/* Counts of different alternative splicing \n   events that are expressed. */\nint alt3ExpCount = 0;\nint alt3SoftExpCount = 0;\nint alt5ExpCount = 0;\nint alt5SoftExpCount = 0;\nint altCassetteExpCount = 0;\nint otherExpCount = 0;\n\n/* Counts of different alternative splicing \n   events that are expressed. */\nint alt3ExpAltCount = 0;\nint alt3SoftExpAltCount = 0;\nint alt5ExpAltCount = 0;\nint alt5SoftExpAltCount = 0;\nint altCassetteExpAltCount = 0;\nint otherExpAltCount = 0;\n\nint noDna = 0;\nint withDna = 0;\nvoid usage()\n/** Print usage and quit. */\n{\nint i=0;\nwarn(\"altHtmlPages - Program to create a web based browser\\n\"\n     \"of altsplice predicitions. Now extended to do some intitial\\n\"\n     \"analysis as well.\\n\"\n     \"options are:\");\nfor(i=0; i<ArraySize(optionSpecs) -1; i++)\n    fprintf(stderr, \"  -%s -- %s\\n\", optionSpecs[i].name, optionDescripts[i]);\nerrAbort(\"\\nusage:\\n   \");\n}\n\nvoid printJunctSetProbes(struct junctSet *jsList)\n/* Print out a mapping from junctionSets to probe sets. */\n{\nchar *fileName = optionVal(\"junctPsMap\",NULL);\nFILE *out = NULL;\nint i = 0;\nstruct junctSet *js = NULL;\n\nassert(fileName);\nout = mustOpen(fileName, \"w\");\nfor(js = jsList; js != NULL; js = js->next)\n    {\n    for(i = 0; i < js->maxJunctCount; i++)\n\tfprintf(out, \"%s\\t%s\\n\", js->name, js->junctPSets[i]);\n    for(i = 0; i < js->junctDupCount; i++)\n\tfprintf(out, \"%s\\t%s\\n\", js->name, js->dupJunctPSets[i]);\n    for(i = 0; i < js->genePSetCount; i++)\n\tfprintf(out, \"%s\\t%s\\n\", js->name, js->genePSets[i]);\n    }\ncarefulClose(&out);\n}\n\nstruct resultM *readResultMatrix(char *fileName)\n/* Read in an R style result table. */\n{\nstruct lineFile *lf = lineFileOpen(fileName, TRUE);\nstruct resultM *rM = NULL;\nchar **words = NULL;\nint colCount=0, i=0;\nchar *line = NULL;\ndouble **M = NULL;\nint rowCount =0;\nint rowMax = 1000;\nchar **rowNames = NULL;\nchar **colNames = NULL;\nstruct hash *iHash = newHash(12);\nchar buff[256];\nchar *tmp;\n/* Get the headers. */\nlineFileNextReal(lf, &line);\nwhile(line[0] == '\\t')\n    line++;\ncolCount = chopString(line, \"\\t\", NULL, 0);\nAllocArray(colNames, colCount);\nAllocArray(words, colCount+1);\nAllocArray(rowNames, rowMax);\nAllocArray(M, rowMax);\ntmp = cloneString(line);\nchopByChar(tmp, '\\t', colNames, colCount);\nwhile(lineFileNextRow(lf, words, colCount+1))\n    {\n    if(rowCount+1 >=rowMax)\n\t{\n\tExpandArray(rowNames, rowMax, 2*rowMax);\n\tExpandArray(M, rowMax, 2*rowMax);\n\trowMax = rowMax*2;\n\t}\n    safef(buff, sizeof(buff), \"%s\", words[0]);\n    tmp=strchr(buff,':');\n    if(tmp != NULL)\n\t{\n\tassert(tmp);\n\ttmp=strchr(tmp+1,':');\n\tassert(tmp);\n\ttmp[0]='\\0';\n\t}\n    hashAddInt(iHash, buff, rowCount);\n    rowNames[rowCount] = cloneString(words[0]);\n    AllocArray(M[rowCount], colCount);\n    for(i=1; i<=colCount; i++) /* Starting at 1 here as name is 0. */\n\t{\n\tM[rowCount][i-1] = atof(words[i]);\n\t}\n    rowCount++;\n    }\nAllocVar(rM);\nrM->nameIndex = iHash;\nrM->colCount = colCount;\nrM->colNames = colNames;\nrM->rowCount = rowCount;\nrM->rowNames = rowNames;\nrM->matrix = M;\nreturn rM;\n}\n\nstruct junctSet *junctSetLoad(char *row[], int colCount)\n/* Load up a junct set. */\n{\nstruct junctSet *js = NULL;\nint index = 1;\nint count = 0;\nAllocVar(js);\nif(colCount > 14)\n    index = 1;\nelse\n    index = 0;\njs->chrom = cloneString(row[index++]);\njs->chromStart = sqlUnsigned(row[index++]);\njs->chromEnd = sqlUnsigned(row[index++]);\njs->name = cloneString(row[index++]);\njs->junctCount = js->maxJunctDupCount = sqlUnsigned(row[index++]);\njs->strand[0] = row[index++][0];\njs->genePSetCount = sqlUnsigned(row[index++]);\nsqlStringDynamicArray(row[index++], &js->genePSets, &count);\njs->hName = cloneString(row[index++]);\nsqlStringDynamicArray(row[index++], &js->junctPSets, &js->maxJunctCount);\njs->junctDupCount = sqlUnsigned(row[index++]);\nsqlStringDynamicArray(row[index++], &js->dupJunctPSets, &count);\njs->cassette = atoi(row[index++]);\njs->exonPsName = cloneString(row[index++]);\nif(colCount != 14) /* If the junctions used fields not present fill them in later. */\n    {\n    js->junctUsedCount = sqlUnsigned(row[index++]);\n    sqlStringDynamicArray(row[index++], &js->junctUsed, &count);\n    }\njs->spliceType = altOther;\nreturn js;\n}\n\nstruct junctSet *junctSetLoadAll(char *fileName)\n/* Load all of the junct sets out of a fileName. */\n{\nstruct junctSet *list = NULL, *el = NULL;\nstruct lineFile *lf = lineFileOpen(fileName, TRUE);\nint numFields = 0;\nchar *line = NULL;\nchar **row = NULL;\nlineFileNextReal(lf, &line);\nnumFields = chopByWhite(line, NULL, 0);\nassert(numFields);\nlineFileReuse(lf);\nAllocArray(row, numFields);\nwhile(lineFileNextRowTab(lf, row, numFields))\n    {\n    el = junctSetLoad(row, numFields);\n    slAddHead(&list, el);\n    }\nlineFileClose(&lf);\nslReverse(&lf);\nreturn list;\n}\n\nvoid fillInProbs(struct junctSet *jsList, struct resultM *probM)\n/* Fill in the probability of expression for each junctSet's junction\n   and gene probe sets. */\n{\nstruct junctSet *js = NULL;\nint i = 0, j = 0;\nfor(js = jsList; js != NULL; js = js->next)\n    {\n    /* Allocate junction probability matrix arrays. */\n    AllocArray(js->junctProbs, js->junctUsedCount);\n    for(i = 0; i < js->junctUsedCount; i++)\n\tAllocArray(js->junctProbs[i], probM->colCount);\n    \n    /* Fill in the values. */\n    for(i = 0; i < js->junctUsedCount; i++)\n\t{\n\tint row = hashIntValDefault(probM->nameIndex, js->junctUsed[i], -1);\n\tif(row != -1)\n\t    {\n\t    for(j = 0; j < probM->colCount; j++) \n\t\tjs->junctProbs[i][j] = probM->matrix[row][j];\n\t    }\n\telse\n\t    {\n\t    for(j = 0; j < probM->colCount; j++) \n\t\tjs->junctProbs[i][j] = -1;\n\t    }\n\t}\n\n    /* Allocate memory for gene sets. */\n    AllocArray(js->geneProbs, js->genePSetCount);\n    for(i = 0; i < js->genePSetCount; i++)\n\tAllocArray(js->geneProbs[i], probM->colCount);\n\n    /* Fill in the values. */\n    for(i = 0; i < js->genePSetCount; i++)\n\t{\n\tint row = hashIntValDefault(probM->nameIndex, js->genePSets[i], -1);\n\tif(row != -1)\n\t    {\n\t    for(j = 0; j < probM->colCount; j++) \n\t\tjs->geneProbs[i][j] = probM->matrix[row][j];\n\t    }\n\telse\n\t    {\n\t    for(j = 0; j < probM->colCount; j++) \n\t\tjs->geneProbs[i][j] = -1;\n\t    }\n\t}\n\n    /* Allocate the cassette exon probabilities if present. */\n    if(js->cassette && differentWord(js->exonPsName, \"NA\"))\n\t{\n\tint row = hashIntValDefault(probM->nameIndex, js->exonPsName, -1);\n\tif(row != -1)\n\t    {\n\t    AllocArray(js->exonPsProbs, probM->colCount);\n\t    for(j = 0; j < probM->colCount; j++)\n\t\tjs->exonPsProbs[j] = probM->matrix[row][j];\n\t    }\n\t}\n    }\n}\n\nvoid fillInIntens(struct junctSet *jsList, struct resultM *intenM)\n/* Fill in the intenability of expression for each junctSet's junction\n   and gene probe sets. */\n{\nstruct junctSet *js = NULL;\nint i = 0, j = 0;\nfor(js = jsList; js != NULL; js = js->next)\n    {\n    /* Allocate junction intenability matrix arrays. */\n    AllocArray(js->junctIntens, js->junctUsedCount);\n    for(i = 0; i < js->junctUsedCount; i++)\n\tAllocArray(js->junctIntens[i], intenM->colCount);\n    \n    /* Fill in the values. */\n    for(i = 0; i < js->junctUsedCount; i++)\n\t{\n\tint row = hashIntValDefault(intenM->nameIndex, js->junctUsed[i], -1);\n\tif(row != -1)\n\t    {\n\t    for(j = 0; j < intenM->colCount; j++) \n\t\tjs->junctIntens[i][j] = intenM->matrix[row][j];\n\t    }\n\telse\n\t    {\n\t    for(j = 0; j < intenM->colCount; j++) \n\t\tjs->junctIntens[i][j] = -1;\n\t    }\n\t}\n\n    /* Allocate memory for gene sets. */\n    AllocArray(js->geneIntens, js->genePSetCount);\n    for(i = 0; i < js->genePSetCount; i++)\n\tAllocArray(js->geneIntens[i], intenM->colCount);\n\n    /* Fill in the values. */\n    for(i = 0; i < js->genePSetCount; i++)\n\t{\n\tint row = hashIntValDefault(intenM->nameIndex, js->genePSets[i], -1);\n\tif(row != -1)\n\t    {\n\t    for(j = 0; j < intenM->colCount; j++) \n\t\tjs->geneIntens[i][j] = intenM->matrix[row][j];\n\t    }\n\telse\n\t    {\n\t    for(j = 0; j < intenM->colCount; j++) \n\t\tjs->geneIntens[i][j] = -1;\n\t    }\n\t}\n\n    /* Allocate the cassette exon intenabilities if present. */\n    if(js->cassette && differentWord(js->exonPsName, \"NA\"))\n\t{\n\tint row = hashIntValDefault(intenM->nameIndex, js->exonPsName, -1);\n\tif(row != -1)\n\t    {\n\t    AllocArray(js->exonPsIntens, intenM->colCount);\n\t    for(j = 0; j < intenM->colCount; j++)\n\t\tjs->exonPsIntens[j] = intenM->matrix[row][j];\n\t    }\n\t}\n    }\n}\n\ndouble covariance(double *X, double *Y, int count)\n/* Compute the covariance for two vectors. \n   cov(X,Y) = E[XY] - E[X]E[Y] \n   page 326 Sheldon Ross \"A First Course in Probability\" 1998\n*/\n{\ndouble cov = gsl_stats_covariance(X, 1, Y, 1, count);\nreturn cov;\n}\n\ndouble correlation(double *X, double *Y, int count)\n/* Compute the correlation between X and Y \n   correlation(X,Y) = cov(X,Y)/ squareRt(var(X)var(Y))\n   page 332 Sheldon Ross \"A First Course in Probability\" 1998\n*/\n{\ndouble varX = gsl_stats_variance(X, 1, count);\ndouble varY = gsl_stats_variance(Y, 1, count);\ndouble covXY = gsl_stats_covariance(X, 1, Y, 1, count);\n\ndouble correlation = covXY / sqrt(varX *varY);\nreturn correlation;\n}\n\ndouble calcMinCorrelation(struct junctSet *js, int *expressed, int tissueCount, int colCount)\n/* Loop through all combinations of junction sets that are expressed\n   and calculate the minimum correlation between the two in tissues\n   if they are expressed in at least 1. */\n{\ndouble minCorr = 2; /* Correlation always <= 1, 2 is a good max. */\ndouble corr = 0;\nint i = 0, j = 0;\nfor(i = 0; i < js->junctUsedCount; i++)\n    {\n    /* If there isn't any expression for this junction don't bother. */\n    if(expressed[i] == 0)\n\tcontinue;\n    for(j = 0; j < js->junctUsedCount; j++)\n\t{\n\t/* Corralation when i == j is 1, don't bother. */\n\tif(i == j)\n\t    continue;\n\n\t/* If there isn't any expression for this junction don't bother. */\n\tif(expressed[j] == 0)\n\t    continue;\n\n\t/* Calculate correlation. */\n\tcorr = correlation(js->junctIntens[i], js->junctIntens[j], colCount);\n\tif(minCorr > corr)\n\t    minCorr = corr;\n\t}\n    }\nreturn minCorr;\n}\n\nint includeJsIx(struct junctSet *js, struct hash *bedHash)\n/* Return the index of the include junction for a cassette exon. */\n{\nint includeIx = 0;\nstruct bed *bed1 = NULL, *bed2 = NULL;\n\nassert(js->cassette);\nif(js->junctUsedCount < 2)\n    return 0;\n\nbed1 = hashMustFindVal(bedHash, js->junctUsed[0]);\nbed2 = hashMustFindVal(bedHash, js->junctUsed[1]);\nif(bed1->chromEnd - bed1->chromStart > bed2->chromEnd - bed2->chromStart)\n    includeIx = 1;\nelse\n    includeIx = 0;\nreturn includeIx;\n}\n\nint skipJsIx(struct junctSet *js, struct hash *bedHash)\n/* Return the index of the skip junction for a cassette exon. */\n{\nint skipIx = 0;\nstruct bed *bed1 = NULL, *bed2 = NULL;\n\nassert(js->cassette);\nif(js->junctUsedCount < 2)\n    return 0;\n\nbed1 = hashMustFindVal(bedHash, js->junctUsed[0]);\nbed2 = hashMustFindVal(bedHash, js->junctUsed[1]);\nif(bed1->chromEnd - bed1->chromStart > bed2->chromEnd - bed2->chromStart)\n    skipIx = 0;\nelse\n    skipIx = 1;\nreturn skipIx;\n}\n\nboolean geneExpressed(struct junctSet *js, int colIx)\n/* Is the gene at junctIx expressed above the \n   threshold in colIx? */\n{\nint i = 0;\nfor(i = 0; i < js->genePSetCount; i++)\n    {\n    if(js->geneProbs[i][colIx] >= presThresh)\n\treturn TRUE;\n    }\nreturn FALSE;\n}\n\nboolean junctionExpressed(struct junctSet *js, int colIx, int junctIx)\n/* Is the junction at junctIx expressed above the \n   thresnhold in colIx? */\n{\nboolean geneExp = FALSE;\nboolean junctExp = FALSE;\nint i = 0;\ngeneExp = geneExpressed(js, colIx);\nif(geneExp && js->junctProbs[junctIx][colIx] >= presThresh)\n    junctExp = TRUE;\nreturn junctExp;\n}\n\nboolean exonExpressed(struct junctSet *js, int colIx)\n/* Is the junction at junctIx expressed above the \n   threshold in colIx? */\n{\nboolean geneExp = FALSE;\nboolean exonExp = FALSE;\nint i = 0;\nfor(i = 0; i < js->genePSetCount; i++)\n    {\n    if(js->geneProbs[i][colIx] >= presThresh)\n\tgeneExp = TRUE;\n    }\nif(geneExp && js->exonPsProbs[colIx] >= presThresh)\n    exonExp = TRUE;\nreturn exonExp;\n}\n\n\ndouble calcExonPercent(struct junctSet *js, struct hash *bedHash, struct resultM *probM)\n/* Calculate how often the exon probe set is called expressed\n   when probe set is. */\n{\nint includeIx = includeJsIx(js, bedHash);\nint both = 0;\nint jsOnly = 0;\ndouble percent = 0;\nint i = 0;\nfor(i = 0; i < probM->colCount; i++)\n    {\n    if(junctionExpressed(js, i, includeIx) &&\n       js->exonPsProbs[i] >= presThresh)\n\t{\n\tboth++;\n\tjsOnly++;\n\tjs->exonAgree++;\n\t}\n    else if(junctionExpressed(js, i, includeIx) &&\n\t    js->exonPsProbs[i] < disagreeThresh)\n\t{\n\tjs->exonDisagree++;\n\tjsOnly++;\n\t}\n    }\nif(jsOnly > 0)\n    percent = (double)both/jsOnly;\nelse \n    percent = -1;\nreturn percent;\n}\n\ndouble calcSjPercent(struct junctSet *js, struct hash *bedHash, struct resultM *probM)\n/* Calculate how often the sj probe set is called expressed\n   when exon probe set is. */\n{\nint includeIx = includeJsIx(js, bedHash);\nint both = 0;\nint exonOnly = 0;\ndouble percent = 0;\nint i = 0;\nfor(i = 0; i < probM->colCount; i++)\n    {\n    if(junctionExpressed(js, i, includeIx) &&\n       js->exonPsProbs[i] >= presThresh)\n\t{\n\tboth++;\n\texonOnly++;\n\tjs->sjAgree++;\n\t}\n    else if(exonExpressed(js, i) &&\n\t    js->junctProbs[includeIx][i] < disagreeThresh)\n\t{\n\texonOnly++;\n\tjs->sjDisagree++;\n\t}\n    }\nif(exonOnly > 0)\n    percent = (double)both/exonOnly;\nelse \n    percent = -1;\nreturn percent;\n}\n\ndouble calcExonSjCorrelation(struct junctSet *js, struct hash *bedHash, struct resultM *intenM)\n/* Calcualate the correltation between the exon probe\n   set and the appropriate splice junction set. */\n{\ndouble corr = -2;\nint includeIx = includeJsIx(js, bedHash);\ncorr = correlation(js->junctIntens[includeIx], js->exonPsIntens, intenM->colCount);\nreturn corr;\n}\n\ndouble calcExonSjSkipCorrelation(struct junctSet *js, struct hash *bedHash, struct resultM *intenM)\n/* Calcualate the correltation between the exon probe\n   set and the appropriate skip splice junction set. */\n{\ndouble corr = -2;\nint skipIx = skipJsIx(js, bedHash);\ncorr = correlation(js->junctIntens[skipIx], js->exonPsIntens, intenM->colCount);\nreturn corr;\n}\n\ndouble calcExonSjProbCorrelation(struct junctSet *js, struct hash *bedHash, struct resultM *probM)\n/* Calcualate the correltation between the exon probe\n   set and the appropriate splice junction set. */\n{\ndouble corr = -2;\nint includeIx = includeJsIx(js, bedHash);\ncorr = correlation(js->junctProbs[includeIx], js->exonPsProbs, probM->colCount);\nreturn corr;\n}\n\ndouble calcExonSjSkipProbCorrelation(struct junctSet *js, struct hash *bedHash, struct resultM *probM)\n/* Calcualate the correltation between the exon probe\n   set and the appropriate splice junction set. */\n{\ndouble corr = -2;\nint skipIx = skipJsIx(js, bedHash);\ncorr = correlation(js->junctProbs[skipIx], js->exonPsProbs, probM->colCount);\nreturn corr;\n}\n\nvoid calcExonCorrelation(struct junctSet *jsList, struct hash *bedHash, \n\t\t\t struct resultM *intenM, struct resultM *probM)\n/* Calculate exon correlation if available. */\n{\nstruct junctSet *js = NULL;\nfor(js = jsList; js != NULL; js = js->next)\n    {\n    if(js->junctUsedCount == 2 &&\n       js->cassette == 1 && differentWord(js->exonPsName, \"NA\") && \n       js->exonPsIntens != NULL && js->exonPsProbs != NULL) \n\t{\n\tjs->exonCorr = calcExonSjCorrelation(js, bedHash, intenM);\n\tjs->exonSkipCorr = calcExonSjSkipCorrelation(js, bedHash, intenM);\n\tjs->probCorr = calcExonSjProbCorrelation(js, bedHash, probM);\n\tjs->probSkipCorr = calcExonSjSkipProbCorrelation(js, bedHash, probM);\n\tjs->exonSjPercent = calcExonPercent(js, bedHash, probM);\n\tjs->sjExonPercent = calcSjPercent(js, bedHash, probM);\n\tif(js->altExpressed && exonPsStats)\n\t    fprintf(exonPsStats, \"%s\\t%.2f\\t%.2f\\t%.2f\\t%d\\t%d\\t%d\\t%d\\t%.2f\\t%.2f\\t%.2f\\n\", \n\t\t    js->exonPsName, js->exonCorr, js->exonSjPercent, js->sjExonPercent, \n\t\t    js->exonAgree, js->exonDisagree, js->sjAgree, js->sjDisagree, js->probCorr,\n\t\t    js->exonSkipCorr, js->probSkipCorr);\n\t}\n    }\n}\n\n\nvoid countExpSpliceType(int type)\n/* Record the counts of different alt-splice types. */\n{\nswitch(type)\n    {\n    case alt3Prime:\n\talt3ExpCount++;\n\tbreak;\n    case alt5Prime:\n\talt5ExpCount++;\n\tbreak;\n    case alt3PrimeSoft:\n\talt3SoftExpCount++;\n\tbreak;\n    case alt5PrimeSoft:\n\talt5SoftExpCount++;\n\tbreak;\n    case altCassette:\n\taltCassetteExpCount++;\n\tbreak;\n    case altOther:\n\totherExpCount++;\n\tbreak;\n    deafult:\n\twarn(\"Don't recognize type: %d\", type);\n    }\n}\n\nvoid countExpAltSpliceType(int type)\n/* Record the counts of different alt-splice types. */\n{\nswitch(type)\n    {\n    case alt3Prime:\n\talt3ExpAltCount++;\n\tbreak;\n    case alt5Prime:\n\talt5ExpAltCount++;\n\tbreak;\n    case alt3PrimeSoft:\n\talt3SoftExpAltCount++;\n\tbreak;\n    case alt5PrimeSoft:\n\talt5SoftExpAltCount++;\n\tbreak;\n    case altCassette:\n\taltCassetteExpAltCount++;\n\tbreak;\n    case altOther:\n\totherExpAltCount++;\n\tbreak;\n    deafult:\n\twarn(\"Don't recognize type: %d\", type);\n    }\n}\n\nvoid logOneJunctSet(struct hash *geneHash, struct junctSet *js)\n/* Log that a gene is expressed. */\n{\nstruct altCounts *ac = NULL;\nac = hashFindVal(geneHash, js->genePSets[0]);\nif(ac == NULL)\n    {\n    AllocVar(ac);\n    ac->gene = js->genePSets[0];\n    ac->count++;\n    hashAdd(geneHash, js->genePSets[0], ac);\n    }\nelse\n    ac->count++;\n}\n\n\nvoid logOneExpressed(struct hash *geneHash, struct junctSet *js)\n/* Log an expressed event. */\n{\nstruct altCounts *ac = NULL;\nac = hashMustFindVal(geneHash, js->genePSets[0]);\nac->jsExpressed++;\n}\n\nvoid logOneAltExpressed(struct hash *geneHash, struct junctSet *js)\n/* Log an AltExpressed event. */\n{\nstruct altCounts *ac = NULL;\nac = hashMustFindVal(geneHash, js->genePSets[0]);\nac->jsAltExpressed++;\n}\n\nvoid printAltCounts(void *val)\n/* Print out the junction sets. */\n{\nstruct altCounts *ac = (struct altCounts *)val;\nif(geneCounts != NULL)\n    fprintf(geneCounts, \"%s\\t%d\\t%d\\t%d\\n\", ac->gene, ac->count,\n\t    ac->jsExpressed, ac->jsAltExpressed);\n}\n\nint calcExpressed(struct junctSet *jsList, struct resultM *probMat)\n/* Loop through and calculate expression and score where score is correlation. */\n{\nstruct junctSet *js = NULL;\nint i = 0, j = 0, k = 0;\ndouble minCor = 2; /* Correlation is always between -1 and 1, 2 is\n\t\t    * good max. */\nstruct hash *geneHash = newHash(10);\nchar *geneJsOutName = optionVal(\"geneJsStats\", NULL);\nchar *geneOutName = optionVal(\"geneStats\", NULL);\nFILE *geneOut = NULL;\ndouble *X = NULL;\ndouble *Y = NULL;\nint elementCount;\nint colCount = probMat->colCount;\nint rowCount = probMat->rowCount;     \nint colIx = 0, junctIx = 0;           /* Column and Junction indexes. */\nint junctOneExp = 0, junctTwoExp = 0; /* What are the counts of\n\t\t\t\t       * expressed and alts. */\ntissueExpThresh = optionInt(\"tissueExpThresh\",1);\nif(geneOutName != NULL)\n    geneOut = mustOpen(geneOutName, \"w\");\nif(geneJsOutName != NULL)\n    geneCounts = mustOpen(geneJsOutName, \"w\");\nfor(js = jsList; js != NULL; js = js->next)\n    {\n    int **expressed = NULL;\n    int totalTissues = 0;\n    int junctExpressed = 0;\n    int geneExpCount = 0;\n    int altExpTissues = 0;\n    int jsExpCount = 0;\n    AllocArray(expressed, js->junctUsedCount);\n    for(i = 0; i < js->junctUsedCount; i++)\n\tAllocArray(expressed[i], colCount);\n    \n    /* Loop through and see how many junctions\n       are actually expressed and in how many tissues. */\n    for(colIx = 0; colIx < colCount; colIx++)\n\t{\n\tint anyExpressed = 0;\n\tint jsExpressed = 0;\n\tif(geneExpressed(js, colIx))\n\t    geneExpCount++;\n\tfor(junctIx = 0; junctIx < js->junctUsedCount; junctIx++)\n\t    {\n\t    if(junctionExpressed(js, colIx, junctIx) == TRUE)\n\t\t{\n\t\texpressed[junctIx][colIx]++;\n\t\tif(expressed[junctIx][colIx] >= tissueExpThresh)\n\t\t    anyExpressed++;\n\t\t}\n\t    if(js->junctProbs[junctIx][colIx] >= presThresh)\n\t\tjsExpressed++;\n\t    }\n\tif(anyExpressed > 0)\n\t    totalTissues++;\n\tif(jsExpressed >= tissueExpThresh)\n\t    jsExpCount++;\n\n\tif(jsExpressed >= tissueExpThresh * 2)\n\t    altExpTissues++;\n\t}\n    \n    /* Set number expressed. */\n    for(i = 0; i < js->junctUsedCount; i++)\n\t{\n\tfor(j = 0; j < colCount; j++)\n\t    {\n\t    int numTissueExpressed = 0;\n\t    if(expressed[i][j])\n\t\t{\n\t\t/* If this junction has been expressed more than\n\t\t   the threshold stop counting and move on to the \n\t\t   next on. */\n\t\tif(++numTissueExpressed >= tissueExpThresh)\n\t\t    {\n\t\t    junctExpressed++;\n\t\t    break;\n\t\t    }\n\t\t}\n\t    }\n\t}\n    \n    /* Record that there is a junction set for this gene. */\n    logOneJunctSet(geneHash, js);\n\n    /* If one tissue expressed set is expressed. */\n    if(junctExpressed >= 1)\n\t{\n\tjs->expressed = TRUE;\n\tlogOneExpressed(geneHash, js);\n\tjunctOneExp++;\n\t}\n    \n    /* If two tissues are expressed set is alternative expressed. */\n    if(junctExpressed >= 2)\n\t{\n\tjs->altExpressed = TRUE;\n\tlogOneAltExpressed(geneHash, js);\n\tjunctTwoExp++;\n\t}\n    if(js->altExpressed == TRUE)\n\t{\n\tjs->score = calcMinCorrelation(js, expressed[0], totalTissues, colCount);\n/*\tcountExpSpliceType(js->spliceType);*/\n\t}\n    else\n\tjs->score = BIGNUM;\n    if(geneOut) \n\t{\n\tchar *tmpName = cloneString(js->junctUsed[0]);\n\tchar *tmp = NULL;\n\ttmp = strchr(tmpName, '@');\n\tassert(tmp);\n\t*tmp = '\\0';\n\tfprintf(geneOut, \"%s\\t%s\\t%d\\t%d\\t%d\\n\", js->name, tmpName, geneExpCount, jsExpCount, altExpTissues);\n\tfreez(&tmpName);\n\t}\n    for(i = 0; i < js->junctUsedCount; i++)\n\tfreez(&expressed[i]);\n    freez(&expressed);\n    }\ncarefulClose(&geneOut);\nhashTraverseVals(geneHash, printAltCounts);\nfreeHashAndVals(&geneHash);\ncarefulClose(&geneCounts);\nwarn(\"%d junctions expressed above p-val %.2f, %d alternative (%.2f%%)\",\n     junctOneExp, presThresh, junctTwoExp, 100*((double)junctTwoExp/junctOneExp));\n}\n\nint junctSetScoreCmp(const void *va, const void *vb)\n/* Compare to sort based on score, smallest to largest. */\n{\nconst struct junctSet *a = *((struct junctSet **)va);\nconst struct junctSet *b = *((struct junctSet **)vb);\nif( a->score > b->score)\n    return 1;\nelse if(a->score < b->score)\n    return -1;\nreturn 0;\t    \n}\n\nint junctSetExonCorrCmp(const void *va, const void *vb)\n/* Compare to sort based on score, smallest to largest. */\n{\nconst struct junctSet *a = *((struct junctSet **)va);\nconst struct junctSet *b = *((struct junctSet **)vb);\nif( a->exonCorr > b->exonCorr)\n    return -1;\nelse if(a->exonCorr < b->exonCorr)\n    return 1;\nreturn 0;\t    \n}\n\nint junctSetExonPercentCmp(const void *va, const void *vb)\n/* Compare to sort based on score, smallest to largest. */\n{\nconst struct junctSet *a = *((struct junctSet **)va);\nconst struct junctSet *b = *((struct junctSet **)vb);\ndouble dif = a->exonSjPercent > b->exonSjPercent;\nif(dif == 0)\n    {\n    if( a->exonCorr > b->exonCorr)\n\treturn -1;\n    else if(a->exonCorr < b->exonCorr)\n\treturn 1;\n    }\nif( a->exonSjPercent > b->exonSjPercent)\n    return -1;\nelse if(a->exonSjPercent < b->exonSjPercent)\n    return 1;\nreturn 0;\t    \n}\n\nvoid makePlotLinks(struct junctSet *js, struct dyString *buff)\n{\ndyStringClear(buff);\ndyStringPrintf(buff, \"<a target=\\\"plots\\\" href=\\\"./noAltTranStartJunctSet/altPlot/%s.%d-%d.%s.png\\\">[all]</a> \",\n\t       js->chrom, js->chromStart, js->chromEnd, js->hName);\ndyStringPrintf(buff, \"<a target=\\\"plots\\\" href=\\\"./noAltTranStartJunctSet/altPlot.median/%s.%d-%d.%s.png\\\">[median]</a> \",\n\t       js->chrom, js->chromStart, js->chromEnd, js->hName);\n}\n\nvoid makeJunctMdbGenericLink(struct junctSet *js, struct dyString *buff, char *name, struct resultM *probM, char *suffix)\n{\nint offSet = 100;\nint i = 0;\ndyStringClear(buff);\ndyStringPrintf(buff, \"<a target=\\\"plots\\\" href=\\\"http://mdb1-sugnet.gi.ucsc.edu/cgi-bin/mdbSpliceGraph?mdbsg.calledSelf=on&coordString=%s:%c:%s:%d-%d&mdbsg.cs=%d&mdbsg.ce=%d&mdbsg.expName=%s&mdbsg.probeSummary=on&mdbsg.toScale=on%s\\\">\", \n\t       \"mm2\", js->strand[0], js->chrom, js->chromStart, js->chromEnd, \n\t       js->chromStart - offSet, js->chromEnd + offSet, \"AffyMouseSplice1-02-2004\", suffix);\ndyStringPrintf(buff, \"%s\", name);\ndyStringPrintf(buff, \"</a> \");\n}\n\n\nvoid makeJunctExpressedTissues(struct junctSet *js, struct dyString *buff, int junctIx, struct resultM *probM)\n{\nint offSet = 100;\nint i = 0;\nstruct dyString *dy = newDyString(1048);\nchar anchor[128];\ndyStringClear(buff);\nfor(i = 0; i < probM->colCount; i++)\n    {\n    if(js->junctProbs[junctIx][i] >= presThresh && \n       geneExpressed(js, i))\n\t{\n\tsafef(anchor, sizeof(anchor), \"#%s\", probM->colNames[i]);\n\tmakeJunctMdbGenericLink(js, dy, probM->colNames[i], probM, anchor);\n\tdyStringPrintf(buff, \"%s, \", dy->string);\n\t}\n    }\ndyStringFree(&dy);\n}\n\n/* void makeJunctExpressedTissues(struct junctSet *js, struct dyString *buff, int junctIx, struct resultM *probM) */\n/* { */\n/* int offSet = 100; */\n/* int i = 0; */\n/* dyStringClear(buff); */\n/* for(i = 0; i < probM->colCount; i++) */\n/*     { */\n/*     if(js->junctProbs[junctIx][i] >= presThresh &&  */\n/*        geneExpressed(js, i)) */\n/* \tdyStringPrintf(buff, \"%s, \", probM->colNames[i]); */\n/*     } */\n/* } */\n\nvoid makeJunctExpressedLink(struct junctSet *js, struct dyString *buff, int junctIx, struct resultM *probM)\n{\nint offSet = 100;\nint i = 0;\ndyStringClear(buff);\ndyStringPrintf(buff, \"<a target=\\\"plots\\\" href=\\\"http://mdb1-sugnet.gi.ucsc.edu/cgi-bin/mdbSpliceGraph?mdbsg.calledSelf=on&coordString=%s:%c:%s:%d-%d&mdbsg.cs=%d&mdbsg.ce=%d&mdbsg.expName=%s&mdbsg.probeSummary=on&mdbsg.toScale=on\\\">\", \n\t       \"mm2\", js->strand[0], js->chrom, js->chromStart, js->chromEnd, \n\t       js->chromStart - offSet, js->chromEnd + offSet, \"AffyMouseSplice1-02-2004\");\nfor(i = 0; i < probM->colCount; i++)\n    {\n    if(js->junctProbs[junctIx][i] >= presThresh && \n       geneExpressed(js, i))\n\tdyStringPrintf(buff, \"%s,\", probM->colNames[i]);\n    }\ndyStringPrintf(buff, \"</a> \");\n}\n\n\nvoid makeJunctNotExpressedTissues(struct junctSet *js, struct dyString *buff, int junctIx, struct resultM *probM)\n{\nint offSet = 100;\nint i = 0;\nstruct dyString *dy = newDyString(1048);\nchar anchor[128];\ndyStringClear(buff);\n\nfor(i = 0; i < probM->colCount; i++)\n    {\n    if(js->junctProbs[junctIx][i] <= absThresh)\n\t{\n\tsafef(anchor, sizeof(anchor), \"#%s\", probM->colNames[i]);\n\tmakeJunctMdbGenericLink(js, dy, probM->colNames[i], probM, anchor);\n\tdyStringPrintf(buff, \"%s, \", dy->string);\n\t}\n    }\ndyStringFree(&dy);\n}\n\nvoid makeJunctMdbLink(struct junctSet *js, struct hash *bedHash,\n\t\t      struct dyString *buff, int junctIx, struct resultM *probM)\n{\nint offSet = 100;\nint i = 0;\ndyStringClear(buff);\ndyStringPrintf(buff, \"<a target=\\\"plots\\\" href=\\\"http://mdb1-sugnet.gi.ucsc.edu/cgi-bin/mdbSpliceGraph?mdbsg.calledSelf=on&coordString=%s:%c:%s:%d-%d&mdbsg.cs=%d&mdbsg.ce=%d&mdbsg.expName=%s&mdbsg.probeSummary=on&mdbsg.toScale=on\\\">\", \n\t       \"mm2\", js->strand[0], js->chrom, js->chromStart, js->chromEnd, \n\t       js->chromStart - offSet, js->chromEnd + offSet, \"AffyMouseSplice1-02-2004\");\ndyStringPrintf(buff, \"%s\", js->junctUsed[junctIx]);\ndyStringPrintf(buff, \"</a> \");\nif(js->cassette == 1 && js->exonPsProbs != NULL) \n    {\n    if(junctIx == includeJsIx(js, bedHash))\n\t{\n\tdyStringPrintf(buff, \"<b> Inc.</b>\");\n\t}\n    }\n}\n\nvoid makeGbCoordLink(struct junctSet *js, int chromStart, int chromEnd, struct dyString *buff)\n/* Make a link to the genome browser with links highlighted. */\n{\nint junctIx = 0;\nint offSet = 100;\ndyStringClear(buff);\ndyStringPrintf(buff, \"<a target=\\\"browser\\\" href=\\\"http://hgwdev-sugnet.gi.ucsc.edu/cgi-bin/hgTracks?position=%s:%d-%d&splicesPFt=red&splicesPlt=or&splicesP_name=\", js->chrom, chromStart - offSet, chromEnd + offSet);\nfor(junctIx = 0; junctIx < js->junctUsedCount; junctIx++)\n    dyStringPrintf(buff, \"%s \", js->junctUsed[junctIx]);\nif(js->exonPsName != NULL && differentWord(js->exonPsName, \"NA\"))\n    dyStringPrintf(buff, \"%s \", js->exonPsName);\ndyStringPrintf(buff, \"\\\">%s</a>\", js->name);\n}\n\nvoid makeGbClusterLink(struct junctSet *js, struct dyString *buff)\n{\nmakeGbCoordLink(js, js->chromStart, js->chromEnd, buff);\n}\n\nvoid makeGbLink(struct junctSet *js, struct dyString *buff)\n{\nint junctIx = 0;\nint offSet = 100;\ndyStringClear(buff);\nif(js->hName[0] != 'G' || strlen(js->hName) != 8)\n    {\n    dyStringPrintf(buff, \"<a target=\\\"browser\\\" href=\\\"http://hgwdev-sugnet.gi.ucsc.edu/cgi-bin/hgTracks?position=%s&splicesPFt=red&splicesPlt=or&splicesP_name=\", js->hName);\n    for(junctIx = 0; junctIx < js->junctUsedCount; junctIx++)\n\tdyStringPrintf(buff, \"%s \", js->junctUsed[junctIx]);\n    dyStringPrintf(buff, \"\\\">%s</a>\", js->hName);\n    }\nelse\n    dyStringPrintf(buff, \"%s\", js->hName);\n}\n\nchar *spliceTypeName(int t)\n/* Return the splice type names. */\n{\nswitch(t) \n    {\n    case alt5Prime:\n\treturn \"alt5\";\n    case alt3Prime:\n\treturn \"alt3\";\n    case altCassette:\n\treturn \"altCass\";\n    case altRetInt:\n\treturn \"altRetInt\";\n    case altOther:\n\treturn \"altOther\";\n    case alt3PrimeSoft:\n\treturn \"txEnd\";\n    case alt5PrimeSoft:\n\treturn \"txStart\";\n    default:\n\treturn \"unknown\";\n    }\nreturn NULL;\n}\n\nvoid outputLinks(struct junctSet **jsList, struct hash *bedHash, struct resultM *probM, FILE *out)\n/* Output a report for each junction set. */\n{\nstruct junctSet *js = NULL;\nint colIx = 0, junctIx = 0;\nstruct dyString *dy = newDyString(2048);\nif(optionExists(\"sortByExonCorr\")) \n    slSort(jsList, junctSetExonCorrCmp);\nelse if(optionExists(\"sortByExonPercent\"))\n    slSort(jsList, junctSetExonPercentCmp);\nelse\n    slSort(jsList, junctSetScoreCmp);\nfprintf(out, \"<ol>\\n\");\nfor(js = *jsList; js != NULL; js = js->next)\n    {\n    if(js->score <= 1)\n\t{\n\tchar affyName[256];\n\tboolean gray = FALSE;\n\tchar *tmp = NULL;\n\tchar *col = NULL;\n\tfprintf(out, \"<li>\");\n\tfprintf(out, \"<table bgcolor=\\\"#000000\\\" border=0 cellspacing=0 cellpadding=1><tr><td>\");\n\tfprintf(out, \"<table bgcolor=\\\"#FFFFFF\\\" width=100%%>\\n\");\n\tfprintf(out, \"<tr><td bgcolor=\\\"#7896be\\\">\");\n\tmakeGbClusterLink(js, dy);\n\tfprintf(out, \"<b>Id:</b> %s \", dy->string);\n\tmakeGbLink(js, dy);\n\tfprintf(out, \"<b>GeneName:</b> %s \", dy->string);\n\tmakePlotLinks(js, dy);\n\tfprintf(out, \"<b>Plots:</b> %s \", dy->string);\n\tfprintf(out, \"<b>Score:</b> %.2f\", js->score);\n\tfprintf(out, \"<b> Type:</b> %s\", spliceTypeName(js->spliceType));\n\tsafef(affyName, sizeof(affyName), \"%s\", js->junctUsed[0]);\n\ttmp = strchr(affyName, '@');\n\tassert(tmp);\n\t*tmp = '\\0';\n\tfprintf(out, \"<a target=_new href=\\\"https://bioinfo.affymetrix.com/Collab/\"\n\t\t\"Manuel_Ares/WebTools/asViewer.asp?gene=%s\\\"> <b> Affy </b></a>\\n\", affyName);\n\tfprintf(out, \"</td></tr>\\n<tr><td>\");\n\tif(js->cassette == 1 && js->exonPsProbs != NULL)\n\t    {\n\t    fprintf(out, \n\t\t    \"<b>Exon Corr:</b> %.2f <b>Exon %%:</b> %.2f <b>Junct %%:</b> %.2f \"\n\t\t    \"<b>Expressed:</b> %d</td></tr><tr><td>\\n\",\n\t\t    js->exonCorr, js->exonSjPercent, js->sjExonPercent, js->exonAgree + js->exonDisagree);\n\t    fprintf(out, \"<b>Exon ps:</b> %s</td></tr><tr><td>\\n\", js->exonPsName);\n\t    }\n\tfprintf(out, \"<table width=100%%>\\n\");\n\n\tfor(junctIx = 0; junctIx < js->junctUsedCount; junctIx++)\n\t    {\n\t    col = \"#bebebe\";\n\t    makeJunctMdbLink(js, bedHash, dy, junctIx, probM);\n\t    fprintf(out, \"<tr><td bgcolor=\\\"%s\\\"><b>Junct:</b> %s</td></tr>\", col, dy->string);\n\t    makeJunctExpressedTissues(js, dy, junctIx, probM);\n\t    col = \"#ffffff\";\n\t    fprintf(out, \"<tr><td bgcolor=\\\"%s\\\"><b>Exp:</b> %s </td></tr>\",col, dy->string);\n\t    makeJunctNotExpressedTissues(js, dy, junctIx, probM);\n\t    fprintf(out, \"<tr><td bgcolor=\\\"%s\\\"><b>Not Exp:</b> %s </td></tr>\", col, dy->string);\n\t    }\n\tfprintf(out, \"</table></td></tr>\\n\");\n\tfprintf(out, \"</table></td></tr></table><br></li>\\n\");\n\t}\n    }\n}\n\nchar *findBestDuplicate(struct junctSet *js, struct resultM *intenM)\n/* Loop through the junction duplicate set and see which one\n   has the best correlation to a gene set. */\n{\ndouble bestCorr = -2;\ndouble corr = 0;\nint gsRow = 0;\nint sjRow = 0;\nchar *bestJunct = NULL;\nint junctIx = 0, geneIx = 0;\nfor(junctIx = 0; junctIx < js->junctDupCount; junctIx++)\n    {\n    for(geneIx = 0; geneIx < js->genePSetCount; geneIx++)\n\t{\n\tgsRow = hashIntValDefault(intenM->nameIndex, js->genePSets[geneIx], -1);\n\tsjRow = hashIntValDefault(intenM->nameIndex, js->dupJunctPSets[junctIx], -1);\n\tif(gsRow == -1 || sjRow == -1)\n\t    continue;\n\tcorr = correlation(intenM->matrix[gsRow], intenM->matrix[sjRow], intenM->colCount);\n\tif(corr >= bestCorr)\n\t    {\n\t    bestCorr = corr;\n\t    bestJunct = js->dupJunctPSets[junctIx];\n\t    }\n\t}\n    }\nreturn bestJunct;\n}\n\ndouble identity(double d) \n/* Return d. Seems dumb but avoids a lot of if/else blocks... */\n{\nreturn d;\n}\n\ndouble log2(double d)\n/* Return log base 2 of d. */\n{\ndouble ld = 0;\nassert(d != 0);\nld = log(d)/log(2);\nreturn ld;\n}\n\nvoid calcJunctSetRatios(struct junctSet *jsList, struct resultM *intenM)\n/* Caluclate the ratio of junction to every other junction in \n   the set. */\n{\nchar *outFile = optionVal(\"ratioFile\", NULL);\nboolean doLog = optionExists(\"log2Ratio\");\nstruct junctSet *js = NULL;\nint i = 0, j = 0, expIx = 0;\nint numIx = 0, denomIx = 0;\nFILE *out = NULL;\nFILE *redundant = NULL;\ndouble **mat = intenM->matrix;\nint colCount = intenM->colCount;\ndouble (*transform)(double d) = NULL;\nstruct hash *nIndex = intenM->nameIndex;\nchar buff[4096];\n\n\nif(outFile == NULL)\n    errAbort(\"Must specify a ratioFile to print ratios to.\");\n\nif(doLog)\n    transform = log2;\nelse\n    transform = identity;\nsafef(buff, sizeof(buff), \"%s.redundant\", outFile);\nredundant = mustOpen(buff, \"w\");\nout = mustOpen(outFile, \"w\");\n/* Print the header. */\nfprintf(out, \"YORF\\tNAME\\t\");\nfor(i = 0; i < colCount-1; i++)\n    fprintf(out, \"%s\\t\", intenM->colNames[i]);\nfprintf(out, \"%s\\n\", intenM->colNames[i]);\nfor(js = jsList; js != NULL; js = js->next) \n    {\n    char **jPSets = js->junctPSets;\n    char **djPSets = js->dupJunctPSets;\n    int jCount = js->maxJunctCount;\n    int dCount = js->junctDupCount;\n    char *gsName = NULL;\n    if(strstr(js->genePSets[0], \"EX\") && js->genePSetCount == 2)\n\tgsName = js->genePSets[1];\n    else\n\tgsName = js->genePSets[0];\n\t    \n    for(i = 0; i < jCount; i++)\n\t{\n\tnumIx = hashIntValDefault(nIndex, jPSets[i], -1);\n\tif(numIx == -1)\n\t    errAbort(\"Can't find %s in hash.\", jPSets[i]);\n\n\t/* Calc ratios for the rest of the probe sets. */\n\tfor(j = i+1; j < jCount; j++)\n\t    {\n\t    denomIx = hashIntValDefault(nIndex, jPSets[j], -1);\n\t    if(numIx == -1)\n\t\terrAbort(\"Can't find %s in hash.\", jPSets[j]);\n\t    fprintf(out, \"%s;%s\\t%s\\t\", jPSets[i], jPSets[j], gsName);\n\t    for(expIx = 0; expIx < colCount - 1; expIx++)\n\t\t{\n\t\tassert(pow(2,mat[denomIx][expIx]) != 0);\n\t\tfprintf(out, \"%f\\t\", transform(pow(2,mat[numIx][expIx]) / pow(2,mat[denomIx][expIx])) );\n\t\t}\n\t    fprintf(out, \"%f\\n\", transform(pow(2,mat[numIx][expIx]) / pow(2,mat[denomIx][expIx])) );\n\t    }\n\t/* Calc ratios for the dup probe sets. */\n\tif(dCount > 1)\n\t    fprintf(redundant, \"%s\", js->name);\n\tfor(j = 0; j < dCount; j++)\n\t    {\n\t    denomIx = hashIntValDefault(nIndex, djPSets[j], -1);\n\t    if(numIx == -1)\n\t\terrAbort(\"Can't find %s in hash.\", djPSets[j]);\n\t    fprintf(out, \"%s;%s\\t%s\\t\", jPSets[i], djPSets[j], gsName);\n\t    if(dCount > 1)\n\t\tfprintf(redundant, \"\\t%s;%s\", jPSets[i], djPSets[j]);\n\t    for(expIx = 0; expIx < colCount - 1; expIx++)\n\t\t{\n\t\tassert(pow(2,mat[denomIx][expIx]) != 0);\n\t\tfprintf(out, \"%f\\t\", transform(pow(2,mat[numIx][expIx]) / pow(2,mat[denomIx][expIx])) );\n\t\t}\n\t    fprintf(out, \"%f\\n\", transform(pow(2,mat[numIx][expIx]) / pow(2,mat[denomIx][expIx])) );\n\t    }\n\tif(dCount > 1)\n\t    fprintf( redundant, \"\\n\");\n\t}\n    \n    /* Get the ratios of the duplicate probes to eachother. */\n    for(i = 0; i < dCount; i++)\n\t{\n\tnumIx = hashIntValDefault(nIndex, djPSets[i], -1);\n\tif(numIx == -1)\n\t    errAbort(\"Can't find %s in hash.\", djPSets[i]);\n\n\t/* Calc ratios for the rest of the dup probe sets. */\n\tfor(j = i+1; j < dCount; j++)\n\t    {\n\t    denomIx = hashIntValDefault(nIndex, djPSets[j], -1);\n\t    if(numIx == -1)\n\t\terrAbort(\"Can't find %s in hash.\", djPSets[j]);\n\t    fprintf(out, \"%s;%s\\t%s\\t\", djPSets[i], djPSets[j], gsName);\n\t    for(expIx = 0; expIx < colCount - 1; expIx++)\n\t\t{\n\t\tassert(pow(2,mat[denomIx][expIx]) != 0);\n\t\tfprintf(out, \"%f\\t\", transform(pow(2,mat[numIx][expIx]) / pow(2,mat[denomIx][expIx])) );\n\t\t}\n\t    fprintf(out, \"%f\\n\", transform(pow(2,mat[numIx][expIx]) / pow(2,mat[denomIx][expIx])) );\n\t    }\n\t}\n    }\ncarefulClose(&out);\ncarefulClose(&redundant);\n}\n\n\nvoid fillInJunctUsed(struct junctSet *jsList, struct resultM *intenM)\n/* If it isn't already determined, figures out which junctions we're\n   using. */\n{\nstruct junctSet *js = NULL;\nchar *bestDup = NULL;\nint i = 0;\nfor(js = jsList; js != NULL; js = js->next)\n    {\n    if(js->junctUsedCount != 0) /* If it has already been filled in forget about it. */\n\tcontinue;\n    if(js->junctDupCount == 0)  /* Trivial if there are no redundant sets to choose from. */\n\t{\n\tjs->junctUsedCount = js->maxJunctCount;\n\tAllocArray(js->junctUsed, js->junctUsedCount);\n\tfor(i = 0; i < js->junctUsedCount; i++)\n\t    js->junctUsed[i] = cloneString(js->junctPSets[i]);\n\t}\n    else /* Go find the redundant junction that correlates best with a gene probe set. */\n\t{\n\tjs->junctUsedCount = js->maxJunctCount + 1;\n\tAllocArray(js->junctUsed, js->junctUsedCount);\n\tfor(i = 0; i < js->junctUsedCount - 1; i++)\n\t    js->junctUsed[i] = cloneString(js->junctPSets[i]);\n\tbestDup = findBestDuplicate(js, intenM);\n\tif(bestDup != NULL)\n\t    js->junctUsed[i] = cloneString(bestDup);\n\telse\n\t    js->junctUsedCount--;\n\t}\n    }\n}\n\t\nstruct hash *hashBeds(char *fileName)\n/* Hash all of the beds in a file. */\n{\nstruct bed *bedList = NULL, *bed = NULL;\nstruct hash *bedHash = newHash(12);\n\nbedList = bedLoadAll(fileName);\nfor(bed = bedList; bed != NULL; bed = bed->next)\n  {\n    hashAddUnique(bedHash, bed->name, bed);\n  }\nreturn bedHash;\n}\n\nint agxVertexByPos(struct altGraphX *agx, int position)\n/* Return the vertex index by to position. */\n{\n  int *vPos = agx->vPositions;\n  int vC = agx->vertexCount;\n  int i = 0;\n  for(i = 0; i < vC; i++)\n    if(vPos[i] == position)\n      return i;\n  return -1;\n}\n\nint bedSpliceStart(const struct bed *bed)\n/* Return the start of the bed splice site. */\n{\nassert(bed->blockSizes);\nreturn bed->chromStart + bed->blockSizes[0];\n}\n\nint bedSpliceEnd(const struct bed *bed)\n/* Return the end of the bed splice site. */\n{\nassert(bed->blockSizes);\nreturn bed->chromStart + bed->chromStarts[1];\n}\n\nboolean connectToDownStreamSoft(struct altGraphX *ag, bool **em, int v)\n/* Does this vertex (v) connect to a downstream vertex to \n   create an soft ended exon. */\n{\nint i = 0;\nint vC = ag->vertexCount;\nunsigned char *vT = ag->vTypes;\nfor(i = 0; i < vC; i++)\n    {\n    if(em[v][i] && vT[i] == ggSoftEnd && \n       getSpliceEdgeType(ag, altGraphXGetEdgeNum(ag, v, i)) == ggExon)\n\treturn TRUE;\n    }\nreturn FALSE;\n}\n\nboolean connectToUpstreamSoft(struct altGraphX *ag, bool **em, int v)\n/* Does this vertex (v) connect to a upstream vertex to \n   create an soft started exon. */\n{\nint i = 0;\nint vC = ag->vertexCount;\nunsigned char *vT = ag->vTypes;\nfor(i = 0; i < vC; i++)\n    {\n    if(em[i][v] && vT[i] == ggSoftStart && \n       getSpliceEdgeType(ag, altGraphXGetEdgeNum(ag, i, v)) == ggExon)\n\treturn TRUE;\n    }\nreturn FALSE;\n}\n\nint translateStrand(int type, char strand)\n/* Translate the type by strand. If the strand is negative\n   both alt3Prime and alt5Prime are flipped. */\n{\nboolean isNeg = strand == '-';\nif(type == alt3Prime && isNeg)\n    type = alt5Prime;\nelse if(type == alt3PrimeSoft && isNeg)\n    type = alt5PrimeSoft;\nelse if(type == alt5Prime && isNeg)\n    type = alt3Prime;\nelse if(type == alt5PrimeSoft && isNeg)\n    type = alt3PrimeSoft;\nreturn type;\n}\n\nvoid outputJunctDna(char *bedName, struct altGraphX *ag, FILE *dnaOut)\n/* Write out the dna for a given junction in the\n   sense orientation. */\n{\nstruct bed *bed = NULL;\nbool **em = NULL;\nunsigned char *vTypes = NULL;\nint *vPos = NULL;\nint start1 = -1, end1 = -1, start2 = -1, end2 = -1;\nstruct dnaSeq *upSeq1 = NULL, *downSeq1 = NULL, *exonSeq1 = NULL;\nstruct dnaSeq *upSeq2 = NULL, *downSeq2 = NULL, *exonSeq2 = NULL;\nbed = hashMustFindVal(junctBedHash, bedName);\nem = altGraphXCreateEdgeMatrix(ag);\nend1 = agxVertexByPos(ag, bedSpliceStart(bed));\nstart2 = agxVertexByPos(ag, bedSpliceEnd(bed));\n\nif(end1 == -1 || start2 == -1)\n    {\n    altGraphXFreeEdgeMatrix(&em, ag->vertexCount);\n    noDna++;\n    return;\n    }\n    \nend2 = agxFindClosestDownstreamVertex(ag, em, start2);\nstart1 = agxFindClosestUpstreamVertex(ag, em, end1);\nif(end2 == -1 || start1 == -1)\n    {\n    altGraphXFreeEdgeMatrix(&em, ag->vertexCount);\n    noDna++;\n    return;\n    }\nvPos = ag->vPositions;\nupSeq1 = hChromSeq(bed->chrom, vPos[start1]-200, vPos[start1]);\nexonSeq1 = hChromSeq(bed->chrom, vPos[start1], vPos[end1]);\ndownSeq1 = hChromSeq(bed->chrom, vPos[end1], vPos[end1]+200);\nupSeq2 = hChromSeq(bed->chrom, vPos[start2]-200, vPos[start2]);\nexonSeq2 = hChromSeq(bed->chrom, vPos[start2], vPos[end2]);\ndownSeq2 = hChromSeq(bed->chrom, vPos[end2], vPos[end2]+200);\n\nif(bed->strand[0] == '-')\n    {\n    reverseComplement(upSeq1->dna, upSeq1->size);\n    reverseComplement(exonSeq1->dna, exonSeq1->size);\n    reverseComplement(downSeq1->dna, downSeq1->size);\n    reverseComplement(upSeq2->dna, upSeq2->size);\n    reverseComplement(exonSeq2->dna, exonSeq2->size);\n    reverseComplement(downSeq2->dna, downSeq2->size);\n    fprintf(dnaOut, \"%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\n\",\n\t    bedName, downSeq2->dna, exonSeq2->dna, upSeq2->dna, \n\t    downSeq1->dna, exonSeq1->dna, upSeq1->dna);\n    }\nelse\n    {\n    fprintf(dnaOut, \"%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\n\",\n\t    bedName, upSeq1->dna, exonSeq1->dna, upSeq2->dna, \n\t    upSeq2->dna, exonSeq2->dna, downSeq2->dna);\n    }\ndnaSeqFree(&upSeq1);\ndnaSeqFree(&exonSeq1);\ndnaSeqFree(&downSeq1);\ndnaSeqFree(&upSeq2);\ndnaSeqFree(&exonSeq2);\ndnaSeqFree(&downSeq2);\naltGraphXFreeEdgeMatrix(&em, ag->vertexCount);\nwithDna++;\n}\n\nvoid outputDnaForJunctSet(struct junctSet *js, FILE *dnaOut)\n/* For each junction in a junction set. Cut out the dna for the exon\n   associated with it.  Format is junctName 3'intron exon '5intron\n*/\n{\nbool **em = NULL;\nint type = -1;\nstruct binElement *be = NULL, *beList = NULL, *beStrand = NULL;\nunsigned char *vTypes = NULL;\nstruct altGraphX *ag = NULL, *agList = NULL;\nint i = 0;\nbeList = chromKeeperFind(js->chrom, js->chromStart, js->chromEnd);\nfor(be = beList; be != NULL; be = be->next)\n    {\n    ag = be->val;\n    if(ag->strand[0] == js->strand[0])\n\tslSafeAddHead(&agList, ag);\n    }\nslFreeList(&beList);\n\n/* Can't do much with no graphs or too many graphs. */\nif(agList == NULL || slCount(agList) != 1)\n    return;\nag = agList;\n\n/* Do the individual junctions. */\nfor(i = 0; i < js->maxJunctCount; i++)\n    {\n    outputJunctDna(js->junctPSets[i], ag, dnaOut);\n    }\nfor(i = 0; i < js->junctDupCount; i++)\n    {\n    outputJunctDna(js->dupJunctPSets[i], ag, dnaOut);\n    }\n\n}\nvoid outputDnaForAllJuctSets(struct junctSet *jsList)\n/* Loop through and output dna for all of the junctions. */\n{\nchar *db = optionVal(\"db\", NULL);\nchar *dnaFile = optionVal(\"outputDna\", NULL);\nFILE *dnaOut = NULL;\nstruct junctSet *js = NULL;\nif(db == NULL)\n    errAbort(\"Must specify db when specifying outputDna.\");\nassert(dnaFile);\nhSetDb(db);\ndnaOut = mustOpen(dnaFile, \"w\");\nfor(js = jsList; js != NULL; js = js->next)\n    {\n    outputDnaForJunctSet(js, dnaOut);\n    }\nwarn(\"%d with dna, %d without dna\", withDna, noDna);\ncarefulClose(&dnaOut);\n}\n\nvoid outputCassetteBed(struct junctSet *js, struct bed *bedUp, struct bed *bedDown,\n\t\t   struct altGraphX *ag, bool **em, int start, int ve1, int ve2,\n\t\t   int altBpStart, int altBpEnd)\n/* Write out a cassette bed to a file. */\n{\nstruct bed bed; \nif(js->altExpressed && cassetteBedOut)\n    {\n    bed.chrom = bedUp->chrom;\n    bed.chromStart = ag->vPositions[altBpStart];\n    bed.chromEnd = ag->vPositions[altBpEnd];\n    bed.name = js->name;\n    bed.strand[0] = bedUp->strand[0];\n    bed.score = altCassette;\n    bedTabOutN(&bed,6,cassetteBedOut);\n    }\n}\n\nint spliceTypeForJunctSet(struct junctSet *js)\n/* Determine the alternative splicing type for a junction set.  This\n function is a little long as I have to convert into altGraphX and do\n some strand specific things. */\n{\nbool **em = NULL;\nint type = -1;\nstruct binElement *be = NULL;\nint ssPos[4];\nint ssCount = 0;\nstruct bed *bedUp = NULL, *bedDown = NULL;\nunsigned char *vTypes = NULL;\nstruct altGraphX *ag = NULL;\n\n/* Can't have more than three introns and be a simple\n   process. */\nif(js->maxJunctCount + js->junctDupCount > 3)\n    return -1;\n\nbe = chromKeeperFind(js->chrom, js->chromStart, js->chromEnd);\nif(slCount(be) == 1)\n    ag = be->val;\nslFreeList(&be);\nif(ag == NULL)\n    return -1;\n\nvTypes = ag->vTypes;\nem = altGraphXCreateEdgeMatrix(ag);\n/* Get the beds. If their are enough primar junctions\n use them. Otherwise use the duplicates. */\nif(js->maxJunctCount >= 2)\n    {\n    bedUp = hashMustFindVal(junctBedHash, js->junctPSets[0]);\n    bedDown = hashMustFindVal(junctBedHash, js->junctPSets[1]);\n    }\nelse\n    {\n    bedUp = hashMustFindVal(junctBedHash, js->junctPSets[0]);\n    bedDown = hashMustFindVal(junctBedHash, js->dupJunctPSets[0]);\n    }\n\n/* Sort the beds. */\nif(bedUp->chromStart > bedDown->chromStart ||\n   (bedDown->chromStart == bedDown->chromStart && \n    bedUp->chromEnd > bedDown->chromEnd))\n    {\n    struct bed *tmp = bedUp;\n    bedUp = bedDown;\n    bedDown = tmp;\n    }\n\n/* If same start type check for alternative 3' splice. */\nif(bedUp->chromStart == bedDown->chromStart)\n    {\n    int start = -1, ve1 = -1, ve2 = -2;\n    int altBpStart = 0, altBpEnd = 0, firstVertex = 0, lastVertex = 0;\n    int isThreePrime = -1;\n    start = agxVertexByPos(ag, bedSpliceStart(bedUp));\n    ve1 = agxVertexByPos(ag, bedSpliceEnd(bedUp));\n    ve2 = agxVertexByPos(ag, bedSpliceEnd(bedDown));\n    isThreePrime = agxIsAlt3Prime(ag, em, start, ve1, ve2,\n\t\t\t\t  &altBpStart, &altBpEnd, &firstVertex, &lastVertex);\n    if(isThreePrime)\n\ttype = alt3Prime;\n    else if(agxIsAlt3PrimeSoft(ag, em, start, ve1, ve2,\n\t\t\t       &altBpStart,  &altBpEnd, &firstVertex, &lastVertex))\n\t{\n\ttype = alt3PrimeSoft;\n\t}\n    else if(agxIsCassette(ag, em, start, ve1, ve2, \n\t\t\t  &altBpStart,  &altBpEnd, &firstVertex, &lastVertex))\n\t{\n\ttype = altCassette;\n\tjs->cassette = TRUE;\n\t}\n/*     outputAlt3Dna(js, bedUp, bedDown, ag, em, start, ve1, ve2, altBpStart, altBpEnd) */\n    if(type == altCassette)\n\toutputCassetteBed(js, bedUp, bedDown, ag, em, start, ve1, ve2, altBpStart, altBpEnd);\n    type = translateStrand(type, ag->strand[0]);\n    }\n/* If same end then check for an alternative 5' splice site. */\nelse if(bedUp->chromEnd == bedDown->chromEnd)\n    {\n    int start1 = -1, start2 = -1, ve1 = -1, ve2 = -2;\n    int altBpStart = 0, altBpEnd = 0, firstVertex = 0, lastVertex = 0;\n    int isFivePrime = -1;\n    ve1 = agxVertexByPos(ag, bedSpliceStart(bedUp));\n    ve2 = agxVertexByPos(ag, bedSpliceStart(bedDown));\n    start1 = agxFindClosestUpstreamVertex(ag, em, ve1);\n    start2 = agxFindClosestUpstreamVertex(ag, em, ve2);\n    if(start1 == start2)\n\t{\n\tif(agxIsAlt5Prime(ag, em, start1, ve1, ve2,\n\t\t\t  &altBpStart, &altBpEnd, &firstVertex, &lastVertex))\n\t    type = alt5Prime;\n\t}\n    else if(agxIsAlt5PrimeSoft(ag, em, start1, start2, ve1, ve2, \n\t\t\t       &altBpStart, &altBpEnd, &firstVertex, &lastVertex)) \n        /* Check for alternative transcription starts. */\n\t{\n\ttype = alt5PrimeSoft;\n\t}\n    else  /* Could be a cassette. */\n\t{\n\tint start = -1;\n\tint end = agxVertexByPos(ag, bedSpliceEnd(bedDown));\n\tstart = agxVertexByPos(ag, bedSpliceStart(bedUp));\n\tif(agxIsCassette(ag, em, start, start2, end,\n\t\t\t &altBpStart, &altBpEnd, &firstVertex, &lastVertex)) \n\t    {\n\t    type = altCassette;\n\t    js->cassette = TRUE;\n\t    }\n\tif(type == altCassette)\n\t    outputCassetteBed(js, bedUp, bedDown, ag, em, start, ve1, ve2, altBpStart, altBpEnd);\n\t}\n\n    type = translateStrand(type, ag->strand[0]);\n    }\nif(js->cassette && type != altCassette)\n    js->cassette == FALSE;\naltGraphXFreeEdgeMatrix(&em, ag->vertexCount);\nreturn type;\n}\n\nvoid countSpliceType(int type)\n/* Record the counts of different alt-splice types. */\n{\nswitch(type)\n    {\n    case alt3Prime:\n\talt3Count++;\n\tbreak;\n    case alt5Prime:\n\talt5Count++;\n\tbreak;\n    case alt3PrimeSoft:\n\talt3SoftCount++;\n\tbreak;\n    case alt5PrimeSoft:\n\talt5SoftCount++;\n\tbreak;\n    case altCassette:\n\taltCassetteCount++;\n\tbreak;\n    default:\n\totherCount++;\n    }\n}\n\n    \nvoid outputBedsForJunctSet(int type, struct junctSet *js)\n/* Write out the beds for the junction set with the \n   type as the scores. */\n{\nstruct bed *bed = NULL;\nint i = 0;\nfor(i = 0; i < js->maxJunctCount; i++)\n    {\n    bed = hashFindVal(junctBedHash, js->junctPSets[i]);\n    bed->score = type;\n    bedTabOutN(bed, 12, bedJunctTypeOut);\n    }\nfor(i = 0; i < js->junctDupCount; i++)\n    {\n    bed = hashFindVal(junctBedHash, js->dupJunctPSets[i]);\n    bed->score = type;\n    bedTabOutN(bed, 12, bedJunctTypeOut);\n    }\n}\n\nvoid determineSpliceTypes(struct junctSet *jsList)\n{\nint type = -1;\nstruct junctSet *js = NULL;\nfor(js = jsList; js != NULL; js = js->next)\n    {\n      type = spliceTypeForJunctSet(js);\n      if(type == -1)\n\t  type = altOther;\n      js->spliceType = type;\n      countSpliceType(type);\n      outputBedsForJunctSet(type, js);\n    }\n}\n\nvoid outputTissueSpecific(struct junctSet *jsList, struct resultM *probM, struct hash *bedHash)\n/* Output alternatively spliced isoforms that are tissue specific. */\n{\nstruct junctSet *js = NULL;\nchar *tissueSpecific = optionVal(\"tissueSpecific\", NULL);\nFILE *tsOut = NULL;\nint tsCount = 0;\ntissueExpThresh = optionInt(\"tissueExpThresh\",1);\nassert(tissueSpecific);\ntsOut = mustOpen(tissueSpecific, \"w\");\nfor(js = jsList; js != NULL; js = js->next)\n    {\n    int junctIx = 0;\n    if(js->altExpressed != TRUE)\n\tcontinue;\n    for(junctIx = 0; junctIx < js->junctUsedCount; junctIx++)\n\t{\n\tboolean isSkip = FALSE;\n\tboolean isInclude = FALSE;\n\tint count = 0;\n\tint tissueIx = 0;\n\tint colIx = 0, rowIx = 0;\n\tif(js->spliceType == altCassette)\n\t    {\n\t    isSkip = (skipJsIx(js, bedHash) == junctIx);\n\t    isInclude = (includeJsIx(js, bedHash) == junctIx);\n\t    }\n\tfor(colIx = 0; colIx < probM->colCount; colIx++)\n\t    {\n\t    if(junctionExpressed(js, colIx, junctIx) == TRUE)\n\t\t{\n\n\t\ttissueIx = colIx;\n\t\tcount++;\n\t\t}\n\t    }\n\tif(count == 1)\n\t    {\n\t    int otherJunctIx = 0;\n\t    /* Require that at least one other junction is expressed in another tissue. */\n\t    for(otherJunctIx = 0; otherJunctIx < js->junctUsedCount; otherJunctIx++)\n\t\t{   \n\t\tint otherColIx = 0;\n\t\tif(otherJunctIx == junctIx)\n\t\t    continue;\n\t\tfor(otherColIx = 0; otherColIx < probM->colCount; otherColIx++)\n\t\t    {\n\t\t    if(otherColIx == tissueIx)\n\t\t\tcontinue;\n\t\t    if(junctionExpressed(js, otherColIx, otherJunctIx)) \n\t\t\t{\n\t\t\tfprintf(tsOut, \"%s\\t%s\\t%d\\t%d\\t%d\\n\", js->junctUsed[junctIx], probM->colNames[tissueIx], \n\t\t\t\tjs->spliceType, isSkip, isInclude);\n\t\t\ttsCount++;\n\t\t\totherJunctIx = js->junctUsedCount+1; /* To end the outer loop. */\n\t\t\tbreak; /* to end the inner loop. */\n\t\t\t}\n\t\t    }\n\t\t}\n\t    }\n\t}\n    }\nwarn(\"%d junctions are tissue specific\", tsCount);\ncarefulClose(&tsOut);\n}\n\nvoid outputBrainSpecific(struct junctSet *jsList, struct resultM *probM, struct hash *bedHash)\n/* Output alternatively spliced isoforms that are brain specific. */\n{\nstruct junctSet *js = NULL;\nchar *brainSpecific = optionVal(\"brainSpecific\", NULL);\nFILE *bsOut = NULL;\nint bsCount = 0;\nboolean *isBrain = NULL;\nint i = 0, j = 0;\nchar *brainTissues[] = {\"cerebellum\",\"cerebral_hemisphere\",\"cortex\",\"medial_eminence\",\"olfactory_bulb\",\"pinealgland\",\"thalamus\"};\ntissueExpThresh = optionInt(\"tissueExpThresh\",1);\nassert(brainSpecific);\nAllocArray(isBrain, probM->colCount);\nfor(i = 0; i < probM->colCount; i++)\n    {\n    for(j = 0; j < ArraySize(brainTissues); j++) \n\t{\n\tif(sameWord(brainTissues[j], probM->colNames[i])) \n\t    {\n\t    isBrain[i] = TRUE;\n\t    break;\n\t    }\n\t}\n    }\n\nbsOut = mustOpen(brainSpecific, \"w\");\nfor(js = jsList; js != NULL; js = js->next)\n    {\n    int junctIx = 0;\n/*     if(js->altExpressed != TRUE) */\n/* \tcontinue; */\n    for(junctIx = 0; junctIx < js->junctUsedCount; junctIx++)\n\t{\n\tboolean isSkip = FALSE;\n\tboolean isInclude = FALSE;\n\tint count = 0;\n\tint brainIx = 0;\n\tint colIx = 0, rowIx = 0;\n\tfor(colIx = 0; colIx < probM->colCount; colIx++)\n\t    {\n\t    if((junctionExpressed(js, colIx, junctIx) == TRUE ||\n\t\tgeneExpressed(js, colIx) == TRUE)\n\t\t&& isBrain[colIx])\n\t\t{\n\t\tbrainIx = colIx;\n\t\tif(js->spliceType == altCassette)\n\t\t    {\n\t\t    isSkip = (skipJsIx(js, bedHash) == junctIx);\n\t\t    isInclude = (includeJsIx(js, bedHash) == junctIx);\n\t\t    }\n\t\tcount++;\n\t\t}\n\t    else if(junctionExpressed(js, colIx, junctIx) == TRUE && !isBrain[colIx])\n\t\t{\n\t\tcount = -1;\n\t\tbreak;\n\t\t}\n\t    }\n\tif(count >= tissueExpThresh)\n\t    {\n\t    int otherJunctIx = 0;\n\t    /* Require that at least one other junction is expressed in another non-brain tissue. */\n\t    for(otherJunctIx = 0; otherJunctIx < js->junctUsedCount; otherJunctIx++)\n\t\t{   \n\t\tint otherJunctExpCount = 0;\n\t\tint otherColIx = 0;\n\t\tif(otherJunctIx == junctIx)\n\t\t    continue;\n\t\tfor(otherColIx = 0; otherColIx < probM->colCount; otherColIx++)\n\t\t    {\n\t\t    if(isBrain[otherColIx])\n\t\t\tcontinue;\n\t\t    if(junctionExpressed(js, otherColIx, otherJunctIx)) \n\t\t\t{\n\t\t\totherJunctExpCount++;\n\t\t\tif(otherJunctExpCount >= tissueExpThresh)\n\t\t\t    {\n\t\t\t    int includeIx = junctIx;\n\t\t\t    int before = 0;\n\t\t\t    if(js->spliceType == altCassette)\n\t\t\t\tincludeIx = includeJsIx(js, bedHash);\n\t\t\t    \n\t\t\t    fprintf(bsOut, \"%s\\t%s\\t%d\\t%d\\t%d\\n\", js->name, probM->colNames[brainIx], \n\t\t\t\t    js->spliceType, isSkip, isInclude);\n\t\t\t    bsCount++;\n\t\t\t    otherJunctIx = js->junctUsedCount+1; /* To end the outer loop. */\n\t\t\t    break; /* to end the inner loop. */\n\t\t\t    }\n\t\t\t}\n\t\t    }\n\t\t}\n\t    }\n\t}\n    }\nfreez(&isBrain);\nwarn(\"%d junctions are brain specific\", bsCount);\ncarefulClose(&bsOut);\n}\n\nvoid altHtmlPages(char *junctFile, char *probFile, char *intensityFile, char *bedFile)\n/* Do a top level summary. */\n{\nstruct junctSet *jsList = NULL;\nstruct junctSet *js = NULL;\nstruct resultM *probM = NULL;\nstruct resultM *intenM = NULL;\nint setCount = 0;\nint junctIx = 0, i = 0;\nFILE *htmlOut = NULL;\nFILE *htmlFrame = NULL;\nFILE *spreadSheet = NULL;\nchar *spreadSheetName = optionVal(\"spreadSheet\", NULL);\nchar *browserName = \"hgwdev-sugnet.cse\";\nchar nameBuff[2048];\nchar *htmlPrefix = optionVal(\"htmlPrefix\", \"\");\nstruct hash *bedHash = NULL;\nchar *db = \"mm2\";\n\nassert(junctFile);\njsList = junctSetLoadAll(junctFile);\nwarn(\"Loaded %d records from %s\", slCount(jsList), junctFile);\nif(optionExists(\"junctPsMap\"))\n    {\n    printJunctSetProbes(jsList);\n    exit(0);\n    }\nassert(intensityFile);\n\nintenM = readResultMatrix(intensityFile);\nwarn(\"Loaded %d rows and %d columns from %s\", intenM->rowCount, intenM->colCount, intensityFile);\nif(optionExists(\"doSjRatios\"))\n    {\n    calcJunctSetRatios(jsList, intenM);\n    exit(0);\n    }\n\nassert(probFile);\nassert(bedFile);\nprobM = readResultMatrix(probFile);\nwarn(\"Loaded %d rows and %d columns from %s\", probM->rowCount, probM->colCount, probFile);\n\nfillInJunctUsed(jsList, intenM);\nfillInProbs(jsList, probM);\nfillInIntens(jsList, intenM);\nbedHash = hashBeds(bedFile);\njunctBedHash = bedHash;\ncalcExpressed(jsList, probM);\n\nif(doJunctionTypes)\n    {\n    determineSpliceTypes(jsList);\n    warn(\"%d altCassette, %d alt3, %d alt5, %d altTranStart %d altTranEnd, %d other\",\n\t altCassetteCount, alt3Count, alt5SoftCount, \n\t alt5Count, alt3SoftCount, otherCount);\n    for(js = jsList; js != NULL; js = js->next)\n\t{\n\tif(js->expressed)\n\t    countExpSpliceType(js->spliceType);\n\tif(js->altExpressed)\n\t    countExpAltSpliceType(js->spliceType);\n\t}\n    warn(\"%d altCassette, %d alt3, %d alt5, %d altTranStart %d altTranEnd, %d other expressed\",\n\t altCassetteExpCount, alt3ExpCount, alt5SoftExpCount, \n\t alt5ExpCount, alt3SoftExpCount, otherExpCount);\n    warn(\"%d altCassette, %d alt3, %d alt5, %d altTranStart %d altTranEnd, %d other expressed alternatively\",\n\t altCassetteExpAltCount, alt3ExpAltCount, alt5SoftExpAltCount, \n\t alt5ExpAltCount, alt3SoftExpAltCount, otherExpAltCount);\n    }\ncalcExonCorrelation(jsList, bedHash, intenM, probM);\nwarn(\"Calculating expression\");\n\nif(optionExists(\"tissueSpecific\"))\n    {\n    outputTissueSpecific(jsList, probM, bedHash);\n    }\n\nif(optionExists(\"brainSpecific\"))\n    {\n    outputBrainSpecific(jsList, probM, bedHash);\n    }\n\nif(optionExists(\"outputDna\"))\n    outputDnaForAllJuctSets(jsList);\n\n/* Write out the lists. */\nwarn(\"Writing out links.\");\nsafef(nameBuff, sizeof(nameBuff), \"%s%s\", htmlPrefix, \"lists.html\");\nhtmlOut = mustOpen(nameBuff, \"w\");\nfprintf(htmlOut, \"<html><body>\\n\");\noutputLinks(&jsList, bedHash, probM, htmlOut);\nfprintf(htmlOut, \"</body></html>\\n\");\ncarefulClose(&htmlOut);\n\n/* Loop through and output a spreadsheet compatible file\n   with the names of junction sets. */\nif(spreadSheetName != NULL)\n    {\n    spreadSheet = mustOpen(spreadSheetName, \"w\");\n    for(js = jsList; js != NULL; js = js->next) \n\t{\n\tif(js->altExpressed) \n\t    {\n\t    fprintf(spreadSheet, \"%s\\t%s\\t\", js->hName,  js->name);\n\t    for(junctIx = 0; junctIx < js->junctUsedCount; junctIx++)\n\t\t{\n\t\tfprintf(spreadSheet, \"\\t%s\\t\", js->junctUsed[junctIx]);\n\t\tfor(i = 0; i < probM->colCount; i++)\n\t\t    {\n\t\t    if(js->junctProbs[junctIx][i] >= presThresh && \n\t\t       geneExpressed(js, i))\n\t\t\tfprintf(spreadSheet, \"%s,\", probM->colNames[i]);\n\t\t    }\n\t\t}\n\t    fprintf(spreadSheet, \"\\n\");\n\t    }\n\t}\n    carefulClose(&spreadSheet);\n    }\n\n\n/* Write out the frames. */\nsafef(nameBuff, sizeof(nameBuff), \"%s%s\", htmlPrefix, \"frame.html\");\nhtmlFrame = mustOpen(nameBuff, \"w\");\nfprintf(htmlFrame, \"<html><head><title>Junction Sets</title></head>\\n\"\n\t\"<frameset cols=\\\"30%,70%\\\">\\n\"\n\t\"   <frame name=\\\"_list\\\" src=\\\"./%s%s\\\">\\n\"\n\t\"   <frameset rows=\\\"50%,50%\\\">\\n\"\n\t\"      <frame name=\\\"browser\\\" src=\\\"http://%s.ucsc.edu/cgi-bin/hgTracks?db=%s&position=%s:%d-%d\\\">\\n\"\n\t\"      <frame name=\\\"plots\\\" src=\\\"http://%s.ucsc.edu/cgi-bin/hgTracks?db=%s&position=%s:%d-%d\\\">\\n\"\n\t\"   </frameset>\\n\"\n\t\"</frameset>\\n\"\n\t\"</html>\\n\", htmlPrefix, \"lists.html\", \n\tbrowserName, db, jsList->chrom, jsList->chromStart, jsList->chromEnd,\n\tbrowserName, db, jsList->chrom, jsList->chromStart, jsList->chromEnd);\n}\n\nvoid agxLoadChromKeeper(char *file)\n     /* Load the agx's in the file into the chromKeeper. */\n{\n  char *db = optionVal(\"db\", NULL);\n  struct altGraphX *agx = NULL, *agxList = NULL;\n  if(db == NULL)\n    errAbort(\"Must specify a database when loading agxs.\");\n  chromKeeperInit(db);\n  agxList = altGraphXLoadAll(file);\n  for(agx = agxList; agx != NULL; agx = agx->next)\n    {\n      chromKeeperAdd(agx->tName, agx->tStart, agx->tEnd, agx);\n    }\n  doJunctionTypes = TRUE;\n}\n\nint main(int argc, char *argv[])\n{\nchar *exonPsFile = NULL;\nFILE *agxFile = NULL;\nchar *agxFileName = NULL;\nchar *cassetteBedOutName = NULL;\n\nif(argc == 1)\n    usage();\noptionInit(&argc, argv, optionSpecs);\nif(optionExists(\"help\"))\n    usage();\npresThresh = optionFloat(\"presThresh\", .9);\nabsThresh = optionFloat(\"absThresh\", .1);\nagxFileName = optionVal(\"agxFile\", NULL);\n\nif(agxFileName != NULL)\n    {\n    char *spliceTypeFile = optionVal(\"spliceTypes\", NULL);\n    if(spliceTypeFile == NULL)\n\terrAbort(\"Must specify spliceTypes flag when specifying agxFile\");\n    bedJunctTypeOut = mustOpen(spliceTypeFile, \"w\");\n    agxLoadChromKeeper(agxFileName);\n    }\ncassetteBedOutName = optionVal(\"cassetteBed\", NULL);\nif(cassetteBedOutName != NULL)\n    {\n    cassetteBedOut = mustOpen(cassetteBedOutName, \"w\");\n    }\n\nif((exonPsFile = optionVal(\"exonStats\", NULL)) != NULL)\n    {\n    exonPsStats = mustOpen(exonPsFile, \"w\");\n    fprintf(exonPsStats, \n\t    \"#name\\tcorrelation\\texonSjPercent\\tsjExonPercent\\t\"\n\t    \"exonAgree\\texonDisagree\\tsjAgree\\tsjDisagree\\tprobCorr\\tskipCorr\\tskipProbCorr\\n\");\n    }\nif(optionExists(\"strictDisagree\"))\n    disagreeThresh = absThresh;\nelse\n    disagreeThresh = presThresh;\naltHtmlPages(optionVal(\"junctFile\", NULL), optionVal(\"probFile\", NULL), \n\t     optionVal(\"intensityFile\", NULL), optionVal(\"bedFile\", NULL));\ncarefulClose(&exonPsStats);\ncarefulClose(&bedJunctTypeOut);\ncarefulClose(&cassetteBedOut);\nreturn 0;\n}\n", "meta": {"hexsha": "c832b9dfe7e3ddc2dd8ded76f7e7904e3ef42d76", "size": 68135, "ext": "c", "lang": "C", "max_stars_repo_path": "src/hg/altSplice/affySplice/altHtmlPages.c", "max_stars_repo_name": "andypohl/kent", "max_stars_repo_head_hexsha": "af7a004c8f3fa909cd8c2cfc2e5bea60e3421cd1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 171.0, "max_stars_repo_stars_event_min_datetime": "2015-04-22T15:16:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T20:21:53.000Z", "max_issues_repo_path": "src/hg/altSplice/affySplice/altHtmlPages.c", "max_issues_repo_name": "andypohl/kent", "max_issues_repo_head_hexsha": "af7a004c8f3fa909cd8c2cfc2e5bea60e3421cd1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 60.0, "max_issues_repo_issues_event_min_datetime": "2016-10-03T15:15:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T15:21:52.000Z", "max_forks_repo_path": "src/hg/altSplice/affySplice/altHtmlPages.c", "max_forks_repo_name": "andypohl/kent", "max_forks_repo_head_hexsha": "af7a004c8f3fa909cd8c2cfc2e5bea60e3421cd1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 80.0, "max_forks_repo_forks_event_min_datetime": "2015-04-16T10:39:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T16:36:30.000Z", "avg_line_length": 30.485458613, "max_line_length": 237, "alphanum_fraction": 0.6546855507, "num_tokens": 21553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.013848610749758829, "lm_q1q2_score": 0.006438240898901279}}
{"text": "#ifndef PyGSL_BLOCK_HELPERS_H\n#define PyGSL_BLOCK_HELPERS_H 1\n/*\n * Author:  Pierre Schnizer\n *\n *\n */\n\n/*****************************************************************************\n * The functions in this file are implemented in src/init/block_helpers*     *\n * These functions try to simplify the conversion between the PyArrayObjects *\n * and the gsl_vector and gsl_matrix types. Further they try to provide a    *\n * compatibility layer for the different implementations of the              *\n * PyArrayObjects (Numeric, numarray, numpy). All code using the functions   *\n * must:                                                                     *\n *       Use these functions here :-)\t\t\t\t\t     *\n *       Declare all varibales referencing dimensions and indexing arrays    *\n *       \"PyGSL_array_index_t\"\t\t\t\t\t\t     *\n *       Expect these variables to be either of type int or long. This most  *\n *       probable is only noticable on 64bit architectures.\t\t     *\n *****************************************************************************/\n/*\n#define PY_ARRAY_UNIQUE_SYMBOL PyGSL_PY_ARRAY_API\n*/\n\n#ifndef _PyGSL_API_MODULE\n/*\n * Not possible to just import the declaration of the PyArrayObject struct. The\n * pointer comes along as well ...\n *\n */\n#ifndef PyGSL_IMPORT_ARRAY\n#define NO_IMPORT_ARRAY\n#endif\n#endif  /* _PyGSL_API_MODULE */\n#include <pygsl/intern.h>\n#include <pygsl/utils.h>\n#include <pygsl/general_helpers.h>\n#include <limits.h>\n/*\n * Build array info out of various parts.\n *\n * array_flag \n */\n\n#if ULONG_MAX < 0xffffff\n#error \"unsigned long not big enough for array info\"\n#else \ntypedef unsigned long PyGSL_array_info_t;\n#endif\n\n\n\n/* typedef Py_ssize_t PyGSL_array_index_t; */\n/*\n#if PY_VERSION_HEX < 0x02050000\ntypedef int Py_ssize_t;\n#endif\n*/\n#include <pygsl/arrayobject.h>\n#ifdef PyGSL_NUMPY\n#include <numpy/arrayobject.h>\n#endif\n#ifdef PyGSL_NUMERIC\n#include <Numeric/arrayobject.h>\n#endif\n#ifdef PyGSL_NUMARRAY\n#include <numarray/libnumarray.h>\n#endif\n#if (!defined PyGSL_NUMPY) && (!defined  PyGSL_NUMERIC) && (!defined PyGSL_NUMARRAY)\n#error \"Neither numpy nor numarray nor Numeric is defined!\"\n#endif\n/* \n *  required for 64 bit machines; backward compability. I rather perfer\n *  to declare it as a long as its just my functions.\n *\n *  For now I keep it as the same type as the underlaying array package\n *  uses for its conversions.\n */\n#ifdef PyGSL_NUMERIC\ntypedef int PyGSL_array_index_t;\n#endif\n#ifdef PyGSL_NUMARRAY\ntypedef maybelong PyGSL_array_index_t;\n#endif\n#ifdef PyGSL_NUMPY\n/* typedef intp PyGSL_array_index_t; */\ntypedef npy_intp PyGSL_array_index_t;\n#endif \n\n\n\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n\nenum PyGSL_Array_Flags {\n     PyGSL_NON_CONTIGUOUS = 0,\n     PyGSL_CONTIGUOUS = 1,\n     /* Additional flags needed for numarray and numpy */\n     PyGSL_INPUT_ARRAY = 2,\n     PyGSL_OUTPUT_ARRAY = 4,\n     PyGSL_IO_ARRAY = 8,\n};\n\n/*\n * Convienience functions for handling the flags\n */\n#define PyGSL_GET_ARRAYFLAG(flag) (( (flag) >>  0) & 0x000000ff)\n#define PyGSL_GET_ARRAYTYPE(flag) (( (flag) >>  8) & 0x000000ff)\n#define PyGSL_GET_TYPESIZE(flag)  (( (flag) >> 16) & 0x000000ff)\n#define PyGSL_GET_ARGNUM(flag)    (( (flag) >> 24) & 0x000000ff) \n\n#define PyGSL_BUILD_ARRAY_INFO(array_flag, array_type, type_size, argnum) \\\n(\\\n (  ((array_flag) & 0x000000ff) <<  0) + \\\n (  ((array_type) & 0x000000ff) <<  8) + \\\n (  ((type_size)  & 0x000000ff) << 16) + \\\n (  ((argnum)     & 0x000000ff) << 24)   \\\n)\n\n#define PyGSL_DARRAY_INFO(array_flag, argnum)  \\\n   PyGSL_BUILD_ARRAY_INFO(array_flag, PyArray_DOUBLE, sizeof(double), argnum) \n#define PyGSL_DARRAY_CINPUT(argnum)  PyGSL_DARRAY_INFO(PyGSL_CONTIGUOUS     | PyGSL_INPUT_ARRAY, argnum) \n#define PyGSL_DARRAY_INPUT(argnum)   PyGSL_DARRAY_INFO(PyGSL_NON_CONTIGUOUS | PyGSL_INPUT_ARRAY, argnum) \n\n/*\n * PyGSL_New_Array:\n *                Generate an new array with the specified dimensions.\n *\n *                The numpy backend expects an array of int, whereas \n *                the numarray backend expects  an array of long\n */\nPyGSL_API_EXTERN PyArrayObject *\nPyGSL_New_Array(int nd,  PyGSL_array_index_t *dimensions, int type);\n\n/*\n * PyGSL_Copy_Array:\n *\n *                 Copy an array. The output array will have the same\n *                 size as the input array.\n */\nPyGSL_API_EXTERN PyArrayObject *\nPyGSL_Copy_Array(PyArrayObject *, int type);\n\n/*\n * PyGSL_STRIDE_RECALC:\n *                                Recalc a stride and check if it is okay\n *\n * Numpy calculates strides in bytes, gsl as multiple of the basis type size\n *\n * Return value:\n *         -1: Conversion Failed\n *         pos : recalculated stride\n */\nPyGSL_API_EXTERN int \nPyGSL_stride_recalc(PyGSL_array_index_t strides, int basis_type_size,\n\t\t    PyGSL_array_index_t * stride_recalc);\n\n\n\n\n/*\n * PyGSL_PyArray_generate_gsl_vector_view :\n *                                 Generate an new array of given dimensions .\n *\n *  This function will try to convert the object, to a Python integer and \n *  generate an apropriate one dimensional numpy array.\n *\n * Input : \n *         object              : a general python object\n *         array_type          : the required C type for the array\n *         argument number     : The argument number. Used for error reporting\n *\n * Output: \n *                             : a pointer to a PyArrayObject or NULL in case \n *                              of error. This object must be dereferenced.\n */\nPyGSL_API_EXTERN PyArrayObject * \nPyGSL_PyArray_generate_gsl_vector_view(PyObject *src,\n\t\t\t\t       int array_type,\n\t\t\t\t       int argnum);\n\n/*\n * PyGSL_PyArray_generate_gsl_matrix_view :\n *                                 Generate an new array of given dimensions .\n *\n *  This function will try to convert the object, to a sequence of two Python \n *  integer and generate an apropriate two dimensional numpy array.\n *\n * Input : \n *         object              : a general python object\n *         array_type          : the required C type for the array\n *         argument number     : The argument number. Used for error reporting\n *\n * Output: \n *                             : a pointer to a PyArrayObject or NULL in case \n *                              of error. This object must be dereferenced.\n */\nPyGSL_API_EXTERN PyArrayObject * \nPyGSL_PyArray_generate_gsl_matrix_view(PyObject *src,\n\t\t\t\t       int array_type,\n\t\t\t\t       int argnum);\n\n\n\n/*\n * Check if a python object can be used as a vector. If so return an\n *  approbriate python array object.\n *\n *\n * Input:\n *      src        ... the python object\n *      size       ... the required size. Pass -1 if it should not be checked.\n *\n *      array_type ... the required type.\n *      flag       ... shall be an input or output or inout array?\n *                 ... shall it be contiguous?\n *      argnum     ... the positional argument number. Used when reporting an\n *                     error\n *      \n *                     Information if the stride of the vector should be\n *                     recalulated to the native C type.\n *      type_size  ... the size of the native C type (typically sizeof(type)).\n *                     If stride is NULL this value is without meaning.\n *\n *      *stride    ... the recalculated stride. If NULL stride will not be\n *                      recalulated, and the following items can be of any value\n *\n *      info       ... info structure passed by callbacks for reporting an error\n *\n *     Convienience macros:\n *                PyGSL_DVECTOR_CHECK(src, size, flag, argnum, stride, info)\n */\nPyGSL_API_EXTERN PyArrayObject *\nPyGSL_vector_check(PyObject *src, PyGSL_array_index_t size, PyGSL_array_info_t ainfo,\n\t\t   PyGSL_array_index_t *stride, PyGSL_error_info * info);\n\n\n/*\n * Check if a python object can be used as a vector. If so return an\n * approbriate python array object.\n *\n *\n * Input:\n *      src        ... the python object\n *\n *      size1      ... the required size of the first dimension.  Pass -1 if it\n *                     should not be checked.\n *      size2     ...  the required size of the second dimension. Pass -1 if it\n *                     should not be checked.\n *\n *      array_type ... the required type.\n *      flag       ... shall be an input or output or inout array?\n *                     shall it be contiguous?\n *      argnum     ... the positional argument number. Used when reporting an\n *                     error\n *      \n *                     Information if the stride of the vector should be \n *                     recalulated to the native C type.\n *      type_size  ... the size of the native C type (typically sizeof(type)).\n *                     If stride is NULL this value is without meaning.\n *\n *      *stride1   ... the recalculated stride. If NULL stride will not be\n *                      recalulated, and the following items can be of any value\n *      *stride2   ... the recalculated stride. If NULL stride will not be\n *                      recalulated, and the following items can be of any value\n *\n *      info       ... info structure passed by callbacks for reporting an error\n *\n *     Convienience macros:\n *       PyGSL_DMATRIX_CHECK(src, size1, size2, flag, argnum, stride1, stride2, info)\n */\nPyGSL_API_EXTERN PyArrayObject *\nPyGSL_matrix_check(PyObject *src, PyGSL_array_index_t size1, PyGSL_array_index_t size2, \n\t\t   PyGSL_array_info_t ainfo,\n\t\t   PyGSL_array_index_t *stride1, PyGSL_array_index_t *stride2,\n\t\t   PyGSL_error_info * info);\n\n/*\n * PyGSL_copy_pyarray_to_gslvector\n *                           Copy the contents of a pyarray to a gsl_vector.\n *\n *\n * Input :\n *         f                   : a pointer to the target vector\n *         object              : a general python object\n *         n                   : number of elements\n *         info                : a PyGSL_Error_info struct. Used for error\n *                               reporting during callback evaluation. Pass\n *                               NULL if not needed.\n *\n * Output: \n *                             : GSL_SUCCESS | GSL_FAILURE\n *\n */\nPyGSL_API_EXTERN int\nPyGSL_copy_pyarray_to_gslvector(gsl_vector *f, PyObject *object, PyGSL_array_index_t n, \n\t\t\t\tPyGSL_error_info * info);\n\n/*\n * PyGSL_copy_pyarray_to_gslmatrix\n *                           Copy the contents of a pyarray to a gsl_matrix.\n *\n *\n * Input :\n *         f                   : a pointer to the target gsl_vector\n *         object              : a general python object referring to a numpy \n *                               array\n *         n                   : number of elements in the first dimension\n *         p                   : number of elements in the second dimension\n *         info                : a PyGSL_error_info struct. Used for error\n *                               reporting during callback evaluation. Pass\n *                               NULL if not needed.\n *\n * Output: \n *                             : GSL_SUCCESS | GSL_FAILURE\n *\n */\nPyGSL_API_EXTERN int\nPyGSL_copy_pyarray_to_gslmatrix(gsl_matrix *f, PyObject *object,  PyGSL_array_index_t n,\n\t\t\t\tPyGSL_array_index_t p, PyGSL_error_info * info);\n\nPyGSL_API_EXTERN PyArrayObject * \nPyGSL_vector_or_double(PyObject *src, PyGSL_array_info_t ainfo, PyGSL_array_index_t size,\n\t\t       PyGSL_error_info * info);\n\n\n/*\n * PyGSL_copy_gslvector_to_pyarrary :\n *                Generate a new numpy array of approbriate size and copy the\n *                data of the vector to it.\n *\n *\n * Input : \n *              x              : a gsl_vector\n * Output: \n *                             : a pointer to a PyArrayObject or NULL in case \n *                              of error. This object must be dereferenced.\n */\nPyGSL_API_EXTERN PyArrayObject *\nPyGSL_copy_gslvector_to_pyarray(const gsl_vector *x);\n\n/*\n * PyGSL_copy_gslmatrix_to_pyarrary :\n *                Generate a new numpy array of approbriate size and copy the\n *                data of the matrix to it.\n *\n *\n * Input : \n *              x              : a gsl_matrix\n * Output: \n *                             : a pointer to a PyArrayObject or NULL in case \n *                              of error. This object must be dereferenced.\n */\nPyGSL_API_EXTERN PyArrayObject *\nPyGSL_copy_gslmatrix_to_pyarray(const gsl_matrix *x);\n#ifndef _PyGSL_API_MODULE\n#define PyGSL_stride_recalc \\\n(*(int (*)(PyGSL_array_index_t, int, PyGSL_array_index_t * ))                                        PyGSL_API[PyGSL_stride_recalc_NUM])\n#define  PyGSL_New_Array  \\\n(*(PyArrayObject * (*)(int, PyGSL_array_index_t *, int))                              PyGSL_API[PyGSL_PyArray_new_NUM])\n#define  PyGSL_Copy_Array  \\\n(*(PyArrayObject * (*)(PyArrayObject *))                               PyGSL_API[PyGSL_PyArray_copy_NUM])\n#ifdef NO_PyGSL_LEGACY\n#define  PyGSL_PyArray_prepare_gsl_vector_view  \\\n(*(PyArrayObject * (*)(PyObject *, int, int,  PyGSL_array_index_t, int, PyGSL_error_info *)) \\\n                                                                     PyGSL_API[PyGSL_PyArray_prepare_gsl_vector_view_NUM])\n#define  PyGSL_PyArray_prepare_gsl_matrix_view  \\\n(*(PyArrayObject * (*)(PyObject *, int, int,  PyGSL_array_index_t, PyGSL_array_index_t, int, PyGSL_error_info *)) \\\n                                                                     PyGSL_API[PyGSL_PyArray_prepare_gsl_matrix_view_NUM])\n#endif /* NO_PyGSL_LEGACY */\n#define PyGSL_PyArray_generate_gsl_vector_view \\\n(*(PyArrayObject *(*)(PyObject *, int, int))          PyGSL_API[PyGSL_PyArray_generate_gsl_vector_view_NUM]) \n\n#define PyGSL_PyArray_generate_gsl_matrix_view \\\n(*(PyArrayObject *(*)(PyObject *, int, int))          PyGSL_API[PyGSL_PyArray_generate_gsl_matrix_view_NUM]) \n\n#define PyGSL_copy_pyarray_to_gslvector \\\n(*(int (*) (gsl_vector *, PyObject *, PyGSL_array_index_t, PyGSL_error_info *))      PyGSL_API[PyGSL_copy_pyarray_to_gslvector_NUM])\n#define PyGSL_copy_pyarray_to_gslmatrix \\\n(*(int (*) (gsl_matrix *, PyObject *, PyGSL_array_index_t, PyGSL_array_index_t, PyGSL_error_info *)) PyGSL_API[PyGSL_copy_pyarray_to_gslmatrix_NUM])\n\n#define PyGSL_copy_gslvector_to_pyarray \\\n (*(PyArrayObject * (*)(const gsl_vector *))                         PyGSL_API[ PyGSL_copy_gslvector_to_pyarray_NUM])\n\n#define PyGSL_copy_gslmatrix_to_pyarray \\\n (*(PyArrayObject * (*)(const gsl_matrix *))                         PyGSL_API[ PyGSL_copy_gslmatrix_to_pyarray_NUM])\n\n\n#define  PyGSL_vector_or_double  \\\n(*(PyArrayObject * (*)(PyObject *, PyGSL_array_info_t , PyGSL_array_index_t, PyGSL_error_info *)) \\\n                                                                     PyGSL_API[PyGSL_vector_or_double_NUM])\n\n#define PyGSL_vector_check  \\\n(*(PyArrayObject * (*) (PyObject *, PyGSL_array_index_t, \\\n PyGSL_array_info_t, PyGSL_array_index_t *, PyGSL_error_info *)) \\\n                                                                      PyGSL_API[PyGSL_vector_check_NUM])\n\n#define PyGSL_matrix_check  \\\n(*(PyArrayObject * (*) (PyObject *, PyGSL_array_index_t, PyGSL_array_index_t, \\\n PyGSL_array_info_t, PyGSL_array_index_t *, PyGSL_array_index_t *, PyGSL_error_info *)) \\\n                                                                      PyGSL_API[PyGSL_matrix_check_NUM])\n\n#define PyGSL_array_check (*(int (*)(PyObject *))  PyGSL_API[PyGSL_array_check_NUM])\n#define PyGSL_array_return(ob) ((PyObject *) ob)\n#endif /* _PyGSL_API_MODULE */\n\n#define PyGSL_STRIDE_RECALC(strides, basis_type_size, stride_recalc) \\\n      ( \\\n           (((strides) % (basis_type_size)) == 0) \\\n         ? \\\n           ( ((*(stride_recalc)) = (strides) / (basis_type_size)), GSL_SUCCESS ) \\\n         : \\\n           PyGSL_stride_recalc(strides, basis_type_size, stride_recalc) \\\n     )\n/*\n#define PyGSL_DVECTOR_CHECK(src, size, info, stride, info) \\\nPyGSL_vector_check(src, size, PyArray_DOUBLE, sizeof(double), flag, argnum, stride, info)\n\n#define PyGSL_DMATRIX_CHECK(src, size1, size2, flag, argnum, stride1, stride2, info) \\\nPyGSL_vector_check(src, size1, size2, PyArray_DOUBLE, sizeof(double), flag, argnum, stride1, stride2, info)\n*/\n\n#ifdef PyGSL_NUMPY\n#include <pygsl/block_helpers_numpy.h>\n#endif\n\n#ifdef PyGSL_NUMERIC\n#include <pygsl/block_helpers_numeric.h>\n#endif\n\n#ifdef PyGSL_NUMARRAY\n#include <pygsl/block_helpers_numarray.h>\n#endif\n\n#endif /* PyGSL_BLOCK_HELPERS_H */\n", "meta": {"hexsha": "1e9bade888d0827a4f723637767a2909475c0614", "size": 16254, "ext": "h", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/Include/pygsl/block_helpers.h", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/Include/pygsl/block_helpers.h", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/Include/pygsl/block_helpers.h", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 37.1945080092, "max_line_length": 148, "alphanum_fraction": 0.62833764, "num_tokens": 3983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16238005288069604, "lm_q2_score": 0.03963884307173048, "lm_q1q2_score": 0.006436557434117207}}
{"text": "/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @file tirific.c\n   @brief Translation and recreation of tirific.f\n   Is a code to apply simulated annealing fitting datacubes to a cube, currently in the gipsy environment.\n   Guideline how to hack into it, without a guarantee:\n\n   Check: interpinit, interpover\n\nThis was commented hdu stuff\n   i) Introducing a new singular parameter:\n   1. Chose a struct of the four loginf headerinf ringparms and fitparms to include the parameter as a component.\n   2. Add the parameter into the identifyer list: Add the parameter identifyer as the last element in the first PRIMPOS list (after comment \"Not in first header\" but before \"Third hdu\"). Change all numbers in the PRIMPOS list (also after the comment) such that the numbers following the added identifyer are increased by 1. Increase the PRIMHDN_SINGLE symbolic constant by 1.\n   3. Change the functions primpos_numtype() and primpos_value() hdl_init() by adding the new parameter at exactly the same place that it was added to the identifyer list.\n   4. Go into the get_hdrinf(), get_loginf(), get_ringparms(), get_fitparms() functions and include the io of the parameter.\n   5. Change the code as you like.\n\n   ii) Introducing a new parameter for the second hdu (fit parameters)\n   1. The place to add the parameter as a new component is the varlel struct\n   2. Add the parameter into the identifyer list: Add the parameter identifyer as the last element in the second PRIMPOS list (before comment \"\"). Change all numbers in the PRIMPOS list (also after the comment) such that the numbers following the added identifyer are increased by 1. Include the parameter as a symbolic constant in the the _SECPOS list. Increase PRIMHDN_SINGLE symbolic constant by 1 and the SECHDN_MULTI by 1.\n   3.  Change the functions primpos_numtype() and primpos_value() hdl_init() by adding the new parameter at exactly the same place that it was added to the identifyer list.\n   4. Check the functions get_fitparms(), secpos_value(), fillhdvarele() for a correct handling of the new parameter, best by simply copying the lines concerning another parameter.\n   5. That should be it. The parameter will be read and written and you can do what you like with it.\n\n   iii) Introducing a new parameter for the third hdu\n   1. Chose a struct of the four loginf headerinf ringparms and fitparms to include the parameter as a component, most likely to chose is the loginf struct that contains information about io.\n   2. Add the parameter into the identifyer list: Add the parameter identifyer as the last element in the first PRIMPOS list (after comment \"Third hdu\"). Change all numbers in the PRIMPOS list (also after the comment) such that the numbers following the added identifyer are increased by 1. Increase the PRIMHDN_SINGLE symbolic constant by 1. Add in the same way a new identifyer to the _TABNR list and change the constant OUTTABNR\n   3. Change the functions primpos_numtype() and primpos_value() hdl_init() by adding the new parameter at exactly the same place that it was added to the identifyer list.\n   4. Check the functions prepout(), writeoutput(), open_hdu_3, create_hdu_3(), writeasctable() (Only a suggestion).\n   5. Change the code as you like.\n\n   iv) Adding a completely new ring parameter (such as dispersion)\n   \n   1. The place to add the parameter as a new component is the ringparms struct.\n   2. Add the parameter into the identifyer list: Add the parameter identifyer as the last element in the  PXXXXX and XXXXX list. If it is a single parameter, change the NSPARAMS by adding 1, if it is a parameter for all rings, add 1 to the NPARAMS symbolic constant. \n   3.  Change the function hdl_init() by adding the new parameter at exactly the same place that it was added to the identifyer list.\n   4. Check the functions dparamtointern(), dinterntoparam(), simpleinterntoglob(), simpleglobtointern(), globtointern(), interntoglob(), changetointern(), get_ringparms(), writeoutarray() for a correct handling of the new parameter. Check the graphics descriptor functions gr_ ...\n   5. That should be it. The parameter will be read and written and you can do what you like with it.\n\n   @todo check if the position ange read from dataset is correct\n   @todo think about the degrees of freedom at the start of metropolis\n   @todo check for leakage about line 5000 (varlel ll may not be deallocated properly)\n   @todo removed the automatic logfile length control in function open_hdu3() for stability reasons (it doesn't work) This has to be checked.\n   @todo Made logfile specification necessary to run tirific, because it doesn't run properly without a logfile. Before searching bugs, check whether the possibility not to have a logfile should be removed entirely.\n   @todo Error source sorting the file at the end of histout? Probably not...\n   @todo coolgal was not working, for some inexplicable reason the program crashed calling convolgaussfft in gridnconvol. The temporal workaround is to accept a memory leak in the cubarithm routine padcubex (...)\n   @todo There is a way to confuse the output routines for fitmode= 2. Take loops= 0. Then let it run once, then change the parameters and let it run a second time. Since I have no idea and this possibility is rather a relict, I leave it at that for now.\n\n   @todo Last change was to include pointsource lists. The next thing\n   to do is to get a generic enlargement of possible parameters. This\n   will not happen for a while (the reason to write thigs down\n   accurately). The new functions srprep() and srconst() gridpoint()\n   that control the generation of a model already contain the\n   parameter mode (which might be deleted, because there is a better\n   variant). The plan is to run a check on starting time of the\n   program, which calculations have to be done at runtime and control\n   this by the use of pointers to functions that are in the ringparms\n   struct. If e.g. a parameter is constant and will not be changed, a\n   whole section of calculation can be omitted. The simplest example\n   is the introduction of a vertical height of a disk. Calculations by\n   adding something to z in srconst can be omitted, if the user has\n   set this value uniformely to 0 and doesn't intend to change the\n   height. The idea is to include a pointer to a function in the\n   ringparms struct, that points to a function that either does the\n   calculations or that does nothing. If now srprep or srconst is\n   called, they will use the predefined pointers in a sensible series,\n   doing either a calculation or nothing.\n\n   @todo check for the necessity for a flushing of parameters in the function interpover\n\n   $Source: /Volumes/DATA_J_II/data/CVS/tirific/src/tirific_new.c,v $\n   $Date: 2011/05/25 22:25:26 $\n   $Revision: 1.26 $\n   $Author: jozsa $\n   $Log: tirific_new.c,v $\n   Revision 1.26  2011/05/25 22:25:26  jozsa\n   Left work\n\n   Revision 1.25  2011/05/11 13:37:12  jozsa\n   Left work\n\n   Revision 1.24  2011/05/10 00:30:16  jozsa\n   Left work\n\n   Revision 1.23  2011/05/04 01:51:03  jozsa\n   test\n\n   Revision 1.22  2011/05/04 01:08:25  jozsa\n   Left work\n\n   Revision 1.21  2011/05/04 01:03:41  jozsa\n   several changes to make genfitting possible\n\n   Revision 1.20  2011/03/23 22:32:29  jozsa\n   removed hdu 1 and 2, with that all storage of input parameters, left simple check whether tirific has created the file\n\n   Revision 1.19  2010/10/14 12:09:46  jozsa\n   Bugfix: With multiple disks, chkchange did not recognise the disk number correctly\n\n   Revision 1.18  2010/07/28 23:04:19  jozsa\n   Left work\n\n   Revision 1.17  2010/04/12 23:15:45  jozsa\n   included a few things, next is correction of coolgal\n\n   Revision 1.16  2010/04/01 09:24:19  jozsa\n   included and hopefully debugged: radial/vertical movement/gradients of those in z/azimuthal harmonics in velocity and surface brightness. To do 1) subclouds 2) Gaussian variations in azimuth 3) portions of a disk 4) 4 disks\n\n   Revision 1.15  2010/03/18 15:49:39  jozsa\n   implemented interpolation over passive parameters: indexing; implemented new syntax for parameter specification\n\n   Revision 1.14  2010/03/08 23:55:38  jozsa\n   left work\n\n   Revision 1.13  2010/03/02 08:23:08  jozsa\n   several changes, from the following versions on hdu2 is only partially checked for changes against the .def file\n\n   Revision 1.12  2009/08/04 16:28:33  jozsa\n   Left work\n\n   Revision 1.11  2009/05/27 15:07:38  jozsa\n   Left work\n\n   Revision 1.10  2008/10/10 15:42:40  jozsa\n   Introduced radial motion VPS1=\n\n   Revision 1.9  2008/07/30 16:22:42  jozsa\n   Some issue with accuracy in fillhdvarele()\n\n   Revision 1.8  2008/06/05 13:04:09  jozsa\n   left work\n\n   Revision 1.12  2008/02/18 16:47:23  gjozsa\n   graphics SDIS output\n\n   Revision 1.11  2008/02/13 16:43:47  gjozsa\n   silly bug\n\n   Revision 1.10  2008/01/16 11:17:24  gjozsa\n   bugfix concerning sdis\n\n   Revision 1.9  2008/01/09 17:50:50  gjozsa\n   minor bug\n\n   Revision 1.8  2008/01/09 17:25:52  gjozsa\n   introduced ring-dependent dispersion without performance loss\n\n   Revision 1.7  2007/08/23 15:23:26  gjozsa\n   Left work\n\n   Revision 1.5  2007/08/16 15:12:05  gjozsa\n   Left work\n\n   Revision 1.4  2007/08/15 16:28:23  gjozsa\n   Left work\n\n   Revision 1.3  2007/08/14 17:09:58  gjozsa\n   Left work\n\n   Revision 1.2  2007/07/25 17:17:09  gjozsa\n   Left work\n\n   Revision 1.1  2007/07/05 16:16:24  gjozsa\n   added to cvs control\n\n   Revision 1.66  2007/03/23 17:21:09  gjozsa\n   Changed back the changes from rev. 1.64, instead corrected the gridding: If the velocity increases with channel number, the pa changes by 180 deg w.r.t version pre-1.64, otherways it stays. For post-1.64 one has to change the pa by changing its signum and adding or subtracting 180 deg.\n\n   Revision 1.65  2007/02/23 10:28:10  gjozsa\n   BUGFIX in tirout: Works now for TIRACC > 6. Enlargened accuracy in textlog.\n\n   Revision 1.64  2007/01/17 15:54:52  gjozsa\n   Changed coordinate system in srconst by mirroring pp[0] to get a right hand coordinate system. In order not to change the pa definition changed the conversion functions interntoglob globtointern etc. Also did some changes to the graphics functions of which I don't know the effect. One can spot the changes via searching for 180.0 and DEGTORAD in the source\n\n   Revision 1.63  2006/12/11 12:42:07  gjozsa\n   BUGFIX: removed reading beam from header: too much confusion\n\n   Revision 1.62  2006/11/22 14:16:21  gjozsa\n   Bugfix concerning RASH and horizontal/vertical lines\n\n   Revision 1.61  2006/11/10 15:53:10  gjozsa\n   minor bugfix\n\n   Revision 1.60  2006/11/09 14:42:55  gjozsa\n   minor change\n\n   Revision 1.59  2006/11/08 14:05:03  gjozsa\n   included line drawing with keywords GR_VERL_i GR_HORL_i GR_VLVA_i GR_HLVA_i GR_VLCA_i GR_HLCA_i\n\n   Revision 1.58  2006/11/03 12:08:59  gjozsa\n   Small bugfix\n\n   Revision 1.57  2006/11/03 10:57:38  gjozsa\n   Introduced logarithmic scaling keywords: GR_XLOG, GR_YLOG_i, introduced hms dms for xpos and ypos in graphics output, introduced keywords RFREQ (restfrequency in Hertz) and ITOU (conversion factor from intensity in Jy/squarearcsec in u/squarecentimeter), changed DOUBLE_ACCURACY to 3E-15 to account for near zero events\n\n   Revision 1.56  2006/07/18 09:33:02  gjozsa\n   Left work\n\n   Revision 1.55  2006/04/11 11:46:00  gjozsa\n   Removed the positive SBR restriction in input\n\n   Revision 1.54  2006/04/06 10:40:25  gjozsa\n   Bugfix: Call of engalmod_chflgs() after changing the input cube after chisquare initialisation\n\n   Revision 1.53  2006/04/03 11:47:57  gjozsa\n   Left work\n\n   Revision 1.52  2005/10/12 14:50:59  gjozsa\n   Not really a Bugfix: Corrected the calculation of the ring normal vector\n\n   Revision 1.51  2005/10/12 09:53:45  gjozsa\n   Included Brigg's plots\n\n   Revision 1.50  2005/09/29 17:46:00  gjozsa\n   BUGFIX in the golden_section() function: refreshing pointsource lists is a crucial point\n\n   Revision 1.49  2005/08/25 10:15:05  gjozsa\n   Slight bug in the plot routines\n\n   Revision 1.48  2005/08/18 13:06:52  gjozsa\n   Left work\n\n   Revision 1.47  2005/08/15 13:15:03  gjozsa\n   BUGFIX: At 12523, not copying to the par array will result in funny results, when the only output is a .def file. Don't know whether this will cause sequals\n\n   Revision 1.45  2005/07/27 14:27:34  gjozsa\n   Again improved the graphics output\n\n   Revision 1.44  2005/07/27 14:01:30  gjozsa\n   Improved the graphics output\n\n   Revision 1.43  2005/06/28 13:28:08  gjozsa\n   Changed the out of range behaviour in golden_section()\n\n   Revision 1.42  2005/06/24 16:44:51  gjozsa\n   added interpolation possibility for the TIRDEF= output, not yet for TIRSMOOTH=\n\n   Revision 1.41  2005/06/24 12:00:30  gjozsa\n   Left work\n\n   Revision 1.43  2005/06/17 14:56:45  gjozsa\n   Bugfix\n\n   Revision 1.42  2005/06/17 14:50:45  gjozsa\n   Bugfix\n\n   Revision 1.41  2005/06/17 14:23:48  gjozsa\n   Added penalty for outliers\n\n   Revision 1.40  2005/06/13 10:40:29  gjozsa\n   Added possibility just to examine results\n\n   Revision 1.39  2005/06/09 14:07:45  gjozsa\n   Left work\n\n   Revision 1.38  2005/06/09 08:22:58  gjozsa\n   BUGFIX: Multiple Parameter fitting was not working properly, fixed that\n   Revision 1.37  2005/05/25 15:47:39  gjozsa\n   Added inclinogram output\n\n   Revision 1.36  2005/05/24 15:59:08  gjozsa\n   Added LON and LMV to table output\n\n   Revision 1.34  2005/05/24 10:42:03  gjozsa\n   Included graphics\n\n   Revision 1.33  2005/05/03 12:42:18  gjozsa\n   Left work\n\n   Revision 1.32  2005/04/28 12:44:44  gjozsa\n   bugfix\n\n   Revision 1.31  2005/04/28 10:13:47  gjozsa\n   Full introduction of pointsource lists\n\n   Revision 1.28  2005/04/26 11:44:53  gjozsa\n   Seems to work\n\n   Revision 1.25  2005/04/20 14:33:39  gjozsa\n   bug\n\n   Revision 1.24  2005/04/20 13:26:25  gjozsa\n   Left work\n\n   Revision 1.23  2005/04/19 13:58:50  gjozsa\n   Left work\n\n   Revision 1.22  2005/04/19 15:29:28  gjozsa\n   Finished the output functions\n\n   Revision 1.21  2005/04/19 10:59:13  gjozsa\n   Extended the possibilities for the histogram output\n\n   Revision 1.19  2005/04/19 07:44:43  gjozsa\n   Left work\n\n   Revision 1.18  2005/04/18 15:53:40  gjozsa\n   Added histogram functions\n\n   Revision 1.17  2005/04/18 15:02:02  gjozsa\n   Included TIR functions\n\n   Revision 1.16  2005/04/15 15:52:09  gjozsa\n   Left work\n\n   Revision 1.15  2005/04/15 15:39:13  gjozsa\n   Bugfix: in fct get_ringparms, documented as BUGFIX , in fct decodestring, also reported\n\n   Revision 1.14  2005/04/14 14:26:05  gjozsa\n   Left work\n\n   Revision 1.13  2005/04/14 10:32:16  gjozsa\n   Left work\n\n   Revision 1.10  2005/04/12 14:54:33  gjozsa\n   Changed the character of PARMAX= and PARMIN=\n\n   Revision 1.9  2005/04/11 14:23:37  gjozsa\n   Left work\n\n   Revision 1.8  2005/04/08 15:30:40  gjozsa\n   Taking into account the whole cube now, no counting for the user\n\n   Revision 1.7  2005/04/08 07:27:44  gjozsa\n   Bugfixes\n\n   Revision 1.6  2005/04/08 07:25:59  gjozsa\n   Bugfixes\n\n   Revision 1.5  2005/04/07 15:15:16  gjozsa\n   Bugfix in galmod(): subring velocity was overwritten by a radius, I hacked a bit, not nic at the moment\n\n   Revision 1.3  2005/04/06 15:46:25  gjozsa\n   Bugfixes, included monitoring of golden_section\n\n   Revision 1.2  2005/04/05 16:06:06  gjozsa\n   Left work\n\n   Revision 1.1  2005/04/05 11:07:37  gjozsa\n   The former tiridev, officially release 1\n\n   Revision 1.41  2005/04/04 08:42:09  gjozsa\n   removed bug\n\n   Revision 1.40  2005/04/01 15:31:54  gjozsa\n   Introduced writecubup and a lot of debugging, check whether the output is not too large\n\n   Revision 1.39  2005/03/29 15:56:24  gjozsa\n   left work\n\n   Revision 1.36  2005/03/25 18:17:20  gjozsa\n   Left work\n\n   Revision 1.35  2005/03/23 17:48:49  gjozsa\n   Implemented hdu_3 support, seems to work\n\n   Revision 1.32  2005/03/23 13:44:33  gjozsa\n   Implemented and tested 2nd hdu i/o\n\n   Revision 1.31  2005/03/22 17:48:07  gjozsa\n   Left work\n\n   Revision 1.30  2005/03/21 18:54:17  gjozsa\n   Left work\n\n   Revision 1.29  2005/03/19 17:55:52  gjozsa\n   Left work\n\n   Revision 1.26  2005/03/17 18:00:50  gjozsa\n   Left work\n\n   Revision 1.25  2005/03/16 17:52:00  gjozsa\n   Left work\n\n   Revision 1.23  2005/03/15 18:53:08  gjozsa\n   Left work\n\n   Revision 1.22  2005/03/15 17:28:59  gjozsa\n   Last changes to get a clear program structure, not ideal, but ok. Some debugging, deleting the fortran thingies\n\n   Revision 1.21  2005/03/12 16:48:33  gjozsa\n   Removed all clutter from readringparms and associated structs\n\n   Revision 1.19  2005/03/12 13:24:49  gjozsa\n   Removed all clutter from hdrinit\n\n   Revision 1.17  2005/03/12 11:37:46  gjozsa\n   Rearranged completely galmod, debugged and tested version of new galmod, including convolution routines, changed position angle to angle with respect to minor\n\n   Revision 1.16  2005/03/11 17:45:55  gjozsa\n   Left work\n\n   Revision 1.15  2005/03/10 17:56:39  gjozsa\n   Left work\n\n   Revision 1.13  2005/03/08 17:55:07  gjozsa\n   Left work\n\n   Revision 1.12  2005/03/05 17:56:09  gjozsa\n   Left work\n\n   Revision 1.11  2005/03/04 18:13:53  gjozsa\n   Left work\n\n   Revision 1.10  2005/03/03 18:00:49  gjozsa\n   Left work\n\n   Revision 1.9  2005/03/02 17:56:09  gjozsa\n   Left work\n\n   Revision 1.8  2005/03/01 17:46:21  gjozsa\n   Left work\n\n   Revision 1.6  2005/02/25 18:13:08  gjozsa\n   Left work\n\n   Revision 1.5  2005/02/25 13:34:29  gjozsa\n   cube io finished\n\n   Revision 1.4  2005/02/25 11:38:27  gjozsa\n   Created a header struct\n\n   Revision 1.3  2005/02/24 17:48:46  gjozsa\n   Left work\n\n\n*/\n/* ------------------------------------------------------------ */\n\n\n\n/*\n               tirific.dc1\n\nProgram:       TIRIFIC (Version 2.3.11)\n\nPurpose:       Fit a tilted-ring model to a datacube\n\nCategory:      FITTING\n\nFile:          tirific.c\n\nAuthors:       Gyula Jozsa\n               Franz Kenn\n               Tom Oosterloo\n               Uli Klein\n\nTirific is a routine that fits a simple tilted-ring model to a\ndatacube INSET=. In this description we try to show all aspects of its\nfunctionality, starting with a description how the program generates a\nmodel datacube, how the goodness-of-fit is calculated, and what\npossibilities exist to reach a \"best-fit\" model.\n\n               ------------ !!!!NOTE!!!!  ------------\n\nTirific is still under construction and in a test phase and does not\nyet implement all functionality that will be reached with time\nmoving. There are many betterments that are already on our todo list,\nranging from speed improvements to a completely different\nuser-interface. The tirific source is held extremely flexible, such\nthat any user can hack easily hack away, but in any case, we are open\nfor any suggestion (and one will of course be to introduce a\nradius-dependent velocity dispersion) and wishes and especially, we\nare happy about any bug report. For receiving update reports, critics,\nwishes, bug reports, send a mail to:\n\njozsa@astron.nl\n\n */\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/* EXTERNAL INCLUDES */\n/* ------------------------------------------------------------ */\n#include <stdio.h>\n#include <string.h>\n#include <float.h>\n#include <limits.h>\n#include <sys/stat.h>\n#include <gft.h>\n#include <gsl/gsl_interp.h>\n#include <gsl/gsl_spline.h>\n#ifdef OPENMPTIR\n#include <omp.h>\n#endif\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/* INTERNAL INCLUDES */\n/* ------------------------------------------------------------ */\n\n/* This is generated by the makefile and contains the gipsy header\n   files. I found no other than this disgusting way. If this module is\n   being changed, the makefile has to be changed accordingly. I found\n   no way around this */\n/* #include \"gipsylinc.c\" */\n#include <engalmod.h>\n#include <maths.h>\n#include <ftstab.h>\n/* #include <ftsoutput.h> */\n/* #include <gridnconvol.h> */\n#include <cubarithm.h>\n#include <pgp.h>\n#include <simparse.h>\n#include <fourat.h>\n#include \"opsystems.h\"\n#include <tirific_identifyers.h>\n#include <tirific_defaults.h>\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @def _MEMORY_HERE_ON\n   @brief Controls the use of the memory_here module\n\n   If you don't want to use the memory_here facility comment this\n   define, otherways it will be included.\n\n*/\n/* ------------------------------------------------------------ */\n/* #define _MEMORY_HERE_ON */\n/* #include <memory_here.h> */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/* PRIVATE SYMBOLIC CONSTANTS */\n/* ------------------------------------------------------------ */\n#define MAXNUR 128\n#define MAXNAX 5\n#define MAXNSUBS 2048\n#define MAXVARY MAXNUR*9+1\n\n\n/* Primary beam correction, since I am not sure at all if this should end up in the final code ... */\n/* #define PBCORR 1 */\n\n#ifdef PBCORR\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @define PBNTELS\n   @brief Number of telescopes for which primary beam correction can be done\n*/\n/* ------------------------------------------------------------ */\n#define PBNTELS 2\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @define PBWSRT\n   @brief Number of the WSRT for primary beam correction\n*/\n/* ------------------------------------------------------------ */\n#define PBWSRT 1\n#define PBWSRT_2 2\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @define PBWSRTCONST_1\n   @brief Constant used for WSRT primary beam correction\n\n   60.7492*pi/180/3600\n\n*/\n/* ------------------------------------------------------------ */\n#define PBWSRTCONST_1 0.2945204323623329E-03\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @define PBWSRTCONST_2\n   @brief Constant used for WSRT primary beam correction\n\n   68*pi/180/3600\n\n*/\n/* ------------------------------------------------------------ */\n#define PBWSRTCONST_2 0.3296733193565160E-03\n\n/* primary beam correction end */\n#endif\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @define FLOAT_ACCURACY\n   @brief Tolerance for floats\n*/\n/* ------------------------------------------------------------ */\n#define FLOAT_ACCURACY 1.0E-7\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @define DOUBLE_ACCURACY\n   @brief Tolerance for floats\n*/\n/* ------------------------------------------------------------ */\n#define DOUBLE_ACCURACY 4.0E-14\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @define VARYSTRELES\n   @brief Number of words in the varystr table in function readfit()\n*/\n/* ------------------------------------------------------------ */\n#define VARYSTRELES 3000\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @define VARYHSTRELES\n   @brief Length of the varyhstr in function readfit()\n*/\n/* ------------------------------------------------------------ */\n#define VARYHSTRELES 3000\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @define MAXVERHOLINES\n   @brief maximum of vertical and horizontal lines in graphout\n*/\n/* ------------------------------------------------------------ */\n#define MAXVERHOLINES 10\n\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @define NDISKS\n   @brief Number of disks, given at compile time\n*/\n/* ------------------------------------------------------------ */\n/* #define ndisks 2 */\n\n\n  \n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @define RA2AS\n   @brief Conversion factor from rad to arcsec\n*/\n/* ------------------------------------------------------------ */\n#define RA2AS 206264.8062470964\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @define DEGTORAD\n   @brief Conversion factor from deg to rad\n*/\n/* ------------------------------------------------------------ */\n#define DEGTORAD 0.0174532925199433\n#define RADTODEG 57.29577951308232\n#define ARCSECTODEG  0.00027777777777777777778\n#define DEGTOARCSEC 3600.\n\n#define TWOPI 6.283185307179586\n#define SQRTOFTWOPI 2.5066282746310005\n#define PIHALF 1.570796326794897\n#define SQRTOFPIHALF 0.886226925452758\n#define HPBWTOSIGMATOFORTH 0.03252139032821276\n#define SPEEDOFLIGHT 2.99792458E5\n#define HIRESFREQ 1.420405751786E9\n#define HICONVERSION 1.248683E24\n#define UTOSOLAR 8.01325e-21\n#define CONVTHREEDBEAM 2.412273945579840982\n#define HUGE_DBL (DBL_MAX/100.)\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @define BMAJ_PRIMPOS @brief Position of the value for BMAJ in the\n   first description table, in case that it's not in the first header,\n   identifyer for primpos_numtype()\n*/\n/* ------------------------------------------------------------ */\n#define BMAJ_PRIMPOS      1\n#define BMIN_PRIMPOS      2\n#define BPA_PRIMPOS       3\n#define RMS_PRIMPOS       4\n#define NUR_PRIMPOS       5\n#define RADSEP_PRIMPOS    6\n#define WEIGHT_PRIMPOS    7\n#define MODE_PRIMPOS      8\n#define ISEED_PRIMPOS     9\n#define LOOPS_PRIMPOS    10\n#define NCORES_PRIMPOS   11\n#define ISEED_2_PRIMPOS  12\n#define ANSTART_PRIMPOS  13\n#define ANEND_PRIMPOS    14\n#define ANSTEPS_PRIMPOS  15\n#define INIMODE_PRIMPOS  16\n#define FITMODE_PRIMPOS  17\n#define OUTCUBUP_PRIMPOS 18\n#define DISTANCE_PRIMPOS 19\n#define PENALTY_PRIMPOS  20\n#define RFREQ_PRIMPOS    21\n#define ITOU_PRIMPOS     22\n#define MAXITER_PRIMPOS  23\n#define CALLITE_PRIMPOS  24\n#define SIZE_PRIMPOS     25\n#define PSSE_PRIMPOS     26 /* PSWARM seed */\n#define PSNP_PRIMPOS     27 /* PSWARM number of particles */\n#define PSCO_PRIMPOS     28 /* PSWARM cognition parameter */\n#define PSSO_PRIMPOS     29 /* PSWARM social parameter */\n#define PSMV_PRIMPOS     30 /* PSWARM maximum velocity */\n#define PSNF_PRIMPOS     31 /* PSWARM number of function evaluations to go from initial weight to final weight */\n#define PSII_PRIMPOS     32 /* PSWARM initial weight */\n#define PSFI_PRIMPOS     33 /* PSWARM final weight */\n#define PSID_PRIMPOS     34 /* PSWARM increase delta */\n#define PSDD_PRIMPOS     35 /* PSWARM decrease delta */                                                            \n#define INTY_PRIMPOS     36 /* interpolation type */                                                            \n#define INDINTY_PRIMPOS  37 /* interpolation type */                                                            \n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @define LASTSING_PRIMPOS\n   @brief Last entry in primpos not counted by disk\n*/\n/* ------------------------------------------------------------ */\n#define LASTSING_PRIMPOS    37\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @define #define LTYPE_MDPRIMPOS\n   @brief Last entry in primpos not counted by disk\n*/\n/* ------------------------------------------------------------ */\n#define LTYPE_MDPRIMPOS    1\n#define CFLUX_MDPRIMPOS    2\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @define NUMB_MDPRIMPOS\n   @brief Number of primpos entries with multiple disks\n*/\n/* ------------------------------------------------------------ */\n#define NUMB_MDPRIMPOS    2\n\n/* #define cflux_primpos    (SIZE_PRIMPOS+LTYPE_MDPRIMPOS*ndisks) */\n\n/* Not in first header */\n/* #define PARMAX_PRIMPOS   (cflux_primpos+ndisks) */\n/* #define PARMIN_PRIMPOS   (cflux_primpos+ndisks+1) */\n/* #define MODERATE_PRIMPOS (cflux_primpos+ndisks+2) */\n/* #define DELSTART_PRIMPOS (cflux_primpos+ndisks+3) */\n/* #define DELEND_PRIMPOS   (cflux_primpos+ndisks+4) */\n/* #define ITESTART_PRIMPOS (cflux_primpos+ndisks+5) */\n/* #define ITEEND_PRIMPOS   (cflux_primpos+ndisks+6) */\n/* #define SATDELT_PRIMPOS  (cflux_primpos+ndisks+7) */\n/* #define MINDELTA_PRIMPOS (cflux_primpos+ndisks+8) */\n/* #define ELEMENTS_PRIMPOS (cflux_primpos+ndisks+9) */\n\n/* Third hdu */\n/* #define CHISQ_PRIMPOS    (cflux_primpos+ndisks+10) */\n/* #define RCHISQ_PRIMPOS   (cflux_primpos+ndisks+11) */\n/* #define LOOPNR_PRIMPOS   (cflux_primpos+ndisks+12) */\n/* #define ACCEPT_PRIMPOS   (cflux_primpos+ndisks+13) */\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @define PRIMHDN_SINGLE\n   @brief Number of first singular values in the first header\n*/\n/* ------------------------------------------------------------ */\n/* #define PRIMHDN_SINGLE (LASTSING_PRIMPOS+NUMB_MDPRIMPOS*ndisks) */\n/* #define PRIMHDN_SINGLE (cflux_primpos+ndisks) */\n/* #define PRIMHDN_SINGLE (cflux_primpos+ndisks-1) */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @define PARMAX_SECPOS\n   @brief Position of the value for BMAJ in the first description table\n*/\n/* ------------------------------------------------------------ */\n/* #define PARMAX_SECPOS   1 */\n/* #define PARMIN_SECPOS   2 */\n/* #define MODERATE_SECPOS 3 */\n/* #define DELSTART_SECPOS 4 */\n/* #define DELEND_SECPOS   5 */\n/* #define ITESTART_SECPOS 6 */\n/* #define ITEEND_SECPOS   7 */\n/* #define SATDELT_SECPOS  8 */\n/* #define MINDELTA_SECPOS  9 */\n/* #define ELEMENTS_SECPOS  10 */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @define SECHDN_MULTI\n   @brief Number of columns in the second header\n*/\n/* ------------------------------------------------------------ */\n#define SECHDN_MULTI 10\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @define CHISQ_TABNR\n   @brief Position of the variable in the outarray after the par content\n*/\n/* ------------------------------------------------------------ */\n#define CHISQ_TABNR  1\n#define RCHISQ_TABNR 2\n#define LOOPNR_TABNR 3\n#define ACCEPT_TABNR 4\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @define OUTTABNR\n   @brief Number of additional entries in the outtab\n*/\n/* ------------------------------------------------------------ */\n#define OUTTABNR 4\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @define WANGLE_GRAPHNR\n   @brief Description of a number of a special graphics output, note that the position in array is (NPARAMS+(ndisks-1)*NDPARAMS+WA_GRAPHNR), which is the old definition\n*/\n/* ------------------------------------------------------------ */\n/* #define WA_GRAPHNR   (NPARAMS+(ndisks-1)*NDPARAMS+1) */\n/* #define DENS_GRAPHNR (NPARAMS+(ndisks-1)*NDPARAMS+2) */\n/* #define WOLD_GRAPHNR (NPARAMS+(ndisks-1)*NDPARAMS+3) */\n/* #define TIP_GRAPHNR  (NPARAMS+(ndisks-1)*NDPARAMS+4) */\n/* #define LON_GRAPHNR  (NPARAMS+(ndisks-1)*NDPARAMS+5) */\n/* #define RASH_GRAPHNR (NPARAMS+(ndisks-1)*NDPARAMS+6) */\n/* #define DESH_GRAPHNR (NPARAMS+(ndisks-1)*NDPARAMS+7) */\n\n#define WA_GRAPHNR   1\n#define DENS_GRAPHNR 2\n#define WOLD_GRAPHNR 3\n#define TIP_GRAPHNR  4\n#define LON_GRAPHNR  5\n#define RASH_GRAPHNR 6\n#define DESH_GRAPHNR 7\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @define MAXGRAPHS\n   @brief Maximum allowed number of viewgraphs on one page\n*/\n/* ------------------------------------------------------------ */\n#define MAXGRAPHS 20\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @define GRAPHNR\n   @brief Number of additional entries for graphics\n*/\n/* ------------------------------------------------------------ */\n#define GRAPHNR 5\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @define GR_INTERP_NUMLINES_DEFAULT\n   @brief Number of interpolating lines in graphics when interpolating in a curved way (really not important)\n*/\n/* ------------------------------------------------------------ */\n#define GR_INTERP_NUMLINES_DEFAULT 500\n\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @define PSW_PSSE_DEF\n   @brief Default value for PSSE parameter for pswarm\n\n*/\n/* ------------------------------------------------------------ */\n#define PSW_PSSE_DEF 42    /* PSWARM seed */\t\t\t\t\t\t\t\t\t   \n#define PSW_PSNP_DEF 42\t   /* PSWARM number of particles */\t\t\t\t\t\t\t   \n#define PSW_PSCO_DEF 0.5   /* PSWARM cognition parameter */\t\t\t\t\t\t\t   \n#define PSW_PSSO_DEF 0.5   /* PSWARM social parameter */\t\t\t\t\t\t\t   \n#define PSW_PSMV_DEF 0.5   /* PSWARM maximum velocity */\t\t\t\t\t\t\t   \n#define PSW_PSNF_DEF 8000  /* PSWARM number of function evaluations to go from initial weight to final weight */  \n#define PSW_PSII_DEF 0.9   /* PSWARM initial weight */\t\t\t\t\t\t\t\t   \n#define PSW_PSFI_DEF 0.4   /* PSWARM final weight */\t\t\t\t\t\t\t\t   \n#define PSW_PSID_DEF 2.\t   /* PSWARM increase delta */\t\t\t\t\t\t\t\t   \n#define PSW_PSDD_DEF 0.5   /* PSWARM decrease delta */                                                            \n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @define EXMAXMETRO\n   @brief Maximum number of allowed attempts to make a model \"out of range\"\n\n   The user has the possibility to give a minimum and a maximum for a\n   given entry in the VARYSING and VARYMULT. If one of the parameters\n   is changed to a value out of range, then the model will be\n   discarded, and a new attempt will be done. To prevent an endless\n   loop, the number of maximal attempts is given. chprm_metro will\n   return 0 in that case.\n\n*/\n/* ------------------------------------------------------------ */\n#define EXMAXMETRO 100000\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @define MAGNIFICNR\n   @brief The number with which the delta is multiplied with at most\n\n   To make the iteration method a bit more effective, for each\n   unsuccessful step to surround a minimum, the delta is multiplied\n   with a number. After several steps, the number with which the\n   original delta is multiplied is big. If we have repeated this enlargement\n   MAGNIFICNR of times we won't do it anymore.\n*/\n/* ------------------------------------------------------------ */\n#define MAGNIFICNR 100\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @define AFAC\n   @brief A constant needed for the golden section\n\n   omega = (3-sqrt(5))/2 0.3819660112501052\n   AFAC = (1-omega)/omega\n   BFAC = 1-omega = omega/(1-omega)\n*/\n/* ------------------------------------------------------------ */\n#define AFAC 1.618033988749894\n#define BFAC 0.6180339887498948\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @define OUTRANGEFAC\n   @brief Factor to multiply the chisquare by if out of range\n*/\n/* ------------------------------------------------------------ */\n#define OUTRANGEFAC 2.0\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/* PRIVATE MACROS */\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/* PRIVATE STRUCTS */\n/* ------------------------------------------------------------ */\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @struct loginf\n   @brief Information about logfiles\n\n   The struct contains all necessary information and the location of\n   structures concerning logfiles.\n\n*/\n/* ------------------------------------------------------------ */\ntypedef struct loginf\n{\n  /** @brief Name of the logfile */\n  char *logname;\n\n  /** @brief Logfile present or not, 0 present, 1 not present */\n  int logpres;\n\n  /** @brief Name of the text logfile */\n  char *textlog; \n\n  /** @brief Name of the progress logfile Kamphuis addition*/\n  char *progresslog; \n\n  /** @brief Name of the output table */\n  char *table; \n\n  /** @brief Distance of object */\n  double distance;\n\n  /** @brief reference x position */\n  double xref;\n\n  /** @brief reference y position */\n  double yref;\n\n  /** @brief Stream of the text logfile */\n  FILE *tstream; \n\n  /** @brief An array of length nur*NPARAMS+nur*NDPARAMS+5 containing the output numbers */\n  double *outarray;\n\n  /** @brief An clone of outarray, supposed to contain any final values; the name is historical */\n  double *grid;\n\n  /** @brief An clone of outarray, supposed to contain any final errors; the name is historical */\n  double *radius;\n\n  /** @brief An clone of outarray */\n  double *regist;\n\n  /** @brief A signal for an encountered change */\n  int changes;\n\n  /** @brief Number of cores */\n  int ncores;\n\n} loginf;\n\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @struct startinf\n   @brief Information about the running status of the program\n\n   The struct contains all control structures connected to rerunning\n   tirific after a full fitting cycle. The idea is to check whether a\n   file with the name startname has changed its last modified time\n   stamp (most conveniently, the user can choose the .def file for\n   that. Once this is done, tirific is rerun omitting the fft\n   initialisation and the reading of inset and corresponding\n   parameters.\n\n*/\n/* ------------------------------------------------------------ */\ntypedef struct startinf\n{\n  /** @brief all about text io */\n  simparse_scn_arel **arel;\n\n  /** @brief Name of the restart file */\n  char *restartname;\n\n  /** @brief Indicator if this is the first run or a consecutive one */\n  int firstrun;\n\n  /** @brief Indicator of the restartid */\n  int restartid;\n\n  /** @brief time stamp for file */\n  time_t timestamp;\n\n  /** @brief container for file statistics */\n  struct stat *filestat;\n\n} startinf;\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @struct hdrinf\n   @brief Information about a cube\n\n   The struct contains all necessary information and the location of\n   structures concerning a datacube that is needed by other functions\n   in this module than hdr_init(). It is initialised by hdr_init. As\n   memeory allocation has to take place as early as possible, this is\n   done by hdr_init(). At the stage of hdr_init(), the chisquare\n   evaluation will already being initialised, hence the struct\n   contains the pointer to the chisquare, also.\n\n*/\n/* ------------------------------------------------------------ */\ntypedef struct hdrinf\n{\n  /** @brief O/I E The name of the input set */\n  char *inset; \n\n    /** @brief The outset name */\n  char *outset;\n\n  /** @brief Every outcubup loops there will be an update of the output cube */\n  int outcubup;\n\n  /** @brief axis numbers (obsolete) */\n  /* int inaxperm[MAXNAX]; */\n\n  /** @brief The reference pixels in the set */\n  double setcrpix[3]; \n  \n  /** @brief Conversion factor from grid units to userdeltunit */\n  double deltgridtouser[3];\n  \n  /** @brief Conversion factor from grids to userglobunit */\n  double globgridtouser[3]; \n\n  /** @brief Conversion factor from cuniti to userglobunit always [1., 1., 0.001] */\n  double globsettouser[3]; \n\n  /** @brief The reference values in user units */\n  double userglobcrval[3]; \n\n  /** @brief The cdelt values in user units */\n  double userglobcdelt[3];\n\n  /** @brief The signum of the velocity direction, this is positive if the velocity decreases with channels in the cube, since the internal velocity direction points to the observer */\n  float signv;\n\n  /** @brief Conversion factor from HI column density to intensity */\n  double jygridtouser;\n  \n  /** @brief E O beam major and minor axis and beam position angle */\n  float bmaj, bmin, bpa;\n\n  /** @brief sigma rms in the map */\n  float rms;\n\n  /** @brief rest frequency */\n  double rfreq;\n\n  /** @brief conversion from Jy/sqarearcsecond to atoms per square centimeter */\n  double itou;\n\n  /** @brief E The size of the cube in axis 1 */\n  int bsize1;  \n\n  /** @brief E The size of the cube in axis 1 */\n  int bcsize1;  \n\n  /** @brief E The size of the cube in axis 2 */\n  int bsize2;  \n\n  /** @brief The total number of pixels in one plane plus padding */\n  int nprof;\n  \n  /** @brief E Number of subsets, that is the number of planes read */\n  int nsubs; \n\n   /** @brief So-called coordinate words describing axes (obsolete) */\n  /* int *cwlo;  */\n\n  /** @brief So-called coordinate words describing axes (obsolete) */\n  /* int *cwhi; */\n\n  /** @brief Coordinate description (coordinate words) of the subsets (planes) (obsolete) */\n  /* int *insubs; */\n\n  /** The input cube, full struct (done) */\n  Cube *oric;\n\n  /** The output cube, full struct (done) */\n  Cube *modelc;\n\n  /** The cool cube */\n  Cube *coolcube;\n\n  /** Half the size in z of the cool cube */\n  float coolhalfc;\n\n  /** nprof of the cool cube */\n  int nprofcool;\n\n  /** nprof of the cool cube */\n  int coolbin;\n\n  /** @brief The cube himself, pixels only (done) */\n  /* float *ori; */\n  \n  /** @brief The model, pixels only (done) */\n  /* float *model; */ \n\n  /** @brief The chisquare */\n  double chi2;\n  \n  /** @brief An old chisquare */\n  double oldchi2;\n\n#ifdef PBCORR\n\n  /** @brief Primary beam */\n  float *primbeam;\n\n#endif\n\n} hdrinf;\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @struct varlel\n   @brief Element of a linked list, describing the change of the model\n   \n   varlel is an element of a linked list that describes the change of\n   the model. Each element contains a list of numbers (int) that are\n   the component numbers of the parameter in the par array of the\n   ringparms struct, the number of adressed elements, and a delta\n   which controls the variation of the parameters at a time.\n*/\n/* ------------------------------------------------------------ */\ntypedef struct varlel\n{\n  /** @brief The number of elements */\n  int nelem;\n\n  /** @brief numbers of the elements in the varlist */\n  int *elements;\n\n  /** @brief The parameter maximum */\n  double parmax;\n\n  /** @brief The parameter minimum */\n  double parmin;\n\n  /** @brief moderating steps */\n  int moderate;\n\n  /** @brief The starting delta */\n  double delstart;\n\n  /** @brief The end delta */\n  double delend;\n\n  /** @brief The starting number of iterations */\n  double itestart;\n\n  /** @brief The ending number of iterations */\n  double iteend;\n\n  /** @brief The delta for the satisfaction */\n  double satdelt;\n\n  /** @brief Delta to stop the iteration process */\n  double mindelta;\n\n  /** @brief Indicator for a change in genfit: 0 not changed, 1: change */\n  int indicator;\n\n  /** @brief The next element */\n  struct varlel *next;\n} varlel;\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @struct srd\n   @brief Sub-ring-descriptor\n\n   Contains a preprocessed description of a subring, such as\n   floating-point pre-calculations. Is touched by function srinit(),\n */\n/* ------------------------------------------------------------ */\ntypedef struct srd\n{\n  /** @brief Sin of the inclination */\n  float sini;\n\n  /** @brief Cos of inclination */\n  float cosi;\n\n  /** @brief Sin of position angle */\n  float sinp;\n\n  /** @brief Cos of position angle */\n  float cosp;\n\n  /** @brief Sin velocity, 1st order */\n  float vps1;\n\n  /** @brief Cos velocity, 1st order */\n  float vpc1;\n\n  /** @brief Sin velocity, 2nd order */\n  float vps2;\n\n  /** @brief Cos velocity, 2nd order */\n  float vpc2;\n\n  /** @brief Sin velocity, 3rd order */\n  float vps3;\n\n  /** @brief Cos velocity, 3rd order */\n  float vpc3;\n\n  /** @brief Sin velocity, 4th order */\n  float vps4;\n\n  /** @brief Cos velocity, 4th order */\n  float vpc4;\n\n  /** @brief Sin velocity, 1st order */\n  float ras1;\n\n  /** @brief Cos velocity, 1st order */\n  float rac1;\n\n  /** @brief Sin velocity, 2nd order */\n  float ras2;\n\n  /** @brief Cos velocity, 2nd order */\n  float rac2;\n\n  /** @brief Sin velocity, 3rd order */\n  float ras3;\n\n  /** @brief Cos velocity, 3rd order */\n  float rac3;\n\n  /** @brief Sin velocity, 4th order */\n  float ras4;\n\n  /** @brief Cos velocity, 4th order */\n  float rac4;\n\n  /** @brief Sin velocity, 1st order */\n  float ros1;\n\n  /** @brief Cos velocity, 1st order */\n  float roc1;\n\n  /** @brief Sin velocity, 2nd order */\n  float ros2;\n\n  /** @brief Cos velocity, 2nd order */\n  float roc2;\n\n  /** @brief Sin velocity, 3rd order */\n  float ros3;\n\n  /** @brief Cos velocity, 3rd order */\n  float roc3;\n\n  /** @brief Sin velocity, 4th order */\n  float ros4;\n\n  /** @brief Cos velocity, 4th order */\n  float roc4;\n\n  /** @brief Sin warp, 1st order */\n  float wps1;\n\n  /** @brief Cos warp, 1st order */\n  float wpc1;\n\n  /** @brief Sin warp, 2nd order */\n  float wps2;\n\n  /** @brief Cos warp, 2nd order */\n  float wpc2;\n\n  /** @brief Sin warp, 3rd order */\n  float wps3;\n\n  /** @brief Cos warp, 3rd order */\n  float wpc3;\n\n  /** @brief Sin warp, 4th order */\n  float wps4;\n\n  /** @brief Cos warp, 4th order */\n  float wpc4;\n\n  /** @brief Inverse of the sum of absolute surface brightnesses, all modes */\n  float sbrmax;\n\n  /** @brief NORMALISED surface brightness, 0th order */\n  float spb0;\n  float sps1;\n  float spc1;\n  float sps2;\n  float spc2;\n  float sps3;\n  float spc3;\n  float sps4;\n  float spc4;\n\n  /** @brief Gaussian dispersion in radians */\n  float gaudi[4];\n\n  /** @brief allowed ranges in radians */\n  float ranges[2][4];\n\n  /** @brief indicator if out of range */\n  int outofrange;\n\n  /** @brief Number of pointsources */\n  long n;\n\n  /** @brief Number of pointsources from normal/harmonics calculation*/\n  long nharmnorm;\n\n  /** @brief Number of pointsources from Gaussian calculation */\n  long ngaussian[4];\n\n  /** @brief Number of pointsources with positive flux */\n  long npos;\n\n  /** @brief Number of pointsources with negative flux */\n  long nneg;\n\n  /** @brief Number of pointsources outside the cube */\n  long outn;\n\n  /** @brief Number of negative pointsources outside the cube */\n/*   long outnpos; */\n\n  /** @brief Number of positive pointsources outside the cube */\n/*   long outnneg; */\n\n#ifdef PBCORR\n  /** @brief method to grid the point sources */\n  void (*gridpoint)(hdrinf *hdr, void (*fill_pbcfac)(hdrinf *hdr, struct srd **sd, int disk, int srnr, long *pnr, int *grid), float *modpar, int nr, struct srd **sd, int srnr, long *pnr, float *pp, int signum, long *npoints, int disk);\n\n  /** @brief method to put the point sources onto the cube */\n  int (*srput)(void (*corr_pbcfac)(struct srd **sd, int disk, int srnr, long grid), struct srd **sd, float *modpar, int nr, double *cflux, double radsep, int srnr, long *fluxpoints, int disk);\n#else\n  /** @brief method to grid the point sources */\n  void (*gridpoint)(hdrinf *hdr, float *modpar, int nr, struct srd **sd, int srnr, long *pnr, float *pp, int signum, long *npoints, int disk);\n\n  /** @brief method to put the point sources onto the cube */\n  int (*srput)(struct srd **sd, float *modpar, int nr, double *cflux, double radsep, int srnr, long *fluxpoints, int disk);\n#endif\n\n  /** @brief Flux of one pointsource */\n  float pf;\n\n  /** @brief Pointsource list, an array of pointers to points in the cube */\n  float **pl;\n\n#ifdef PBCORR\n  /** @brief primary beam factor list, an array of floats, used for primary beam correction */\n  float *pbfac;\n#endif\n\n  /** @brief length of pointsource list */\n  long pllength;\n\n  /** @brief Number of subclouds */\n  int nsubcl;\n\n  /** @brief Number of outliers (for parallel bookkeeping) */\n  long outpoints;\n\n  /** @brief Number of clouds equivalent to flux (positive minus negative, for parallel bookkeeping) */\n  int allnpoints;\n\n  /** @brief Number of clouds equivalent to flux (positive minus negative, for parallel bookkeeping) */\n  long fluxpoints;\n\n  /** @brief Number of subclouds, inverted */\n  float nsubclinv;\n\n  /** @brief The seed for random number generator (from ringparms) */\n  int iseed2[2];\n\n  /** @brief The seed for random number generator (from inf_smi) */\n  int iseed[2];\n\n  /** @brief The seed for random number generator (from inf_sdis) */\n  int siseed[2];\n\n  /** @brief The allocated permanent random generator (from inf_smi) */\n  maths_rstrf *randstr;\n\n  /** @brief The allocated permanent random generator (from inf_sdis) */\n  maths_rstrf *srandstr;\n\n  /** @brief The allocated permanent random generator (from ringparms) */\n  maths_rstrf *permrandstr;\n\n  /** @brief The allocated permanent random generator (from inf_gau) */\n  maths_rstrf *grandstr[4];\n\n  /** @brief Number saved for zprof */\n  float y2;\n\n} srd;\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @struct inlistel\n   @brief A linked list of integers\n */\n/* ------------------------------------------------------------ */\ntypedef struct inlistel\n{\n  int i;\n  struct inlistel *next;\n} inlistel;\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @struct inf_smi\n   @brief struct to handle the harmonic terms in surface brightness\n */\n/* ------------------------------------------------------------ */\ntypedef struct inf_smi {\n\n  /** @brief The seed for random number generator */\n  /* parallel changed this */ /* int iseed[2]; */\n\n  /** @brief function initialising the rng */\n  void (*rndmf_init)(void *rpm, int srnr, int disk);\n\n  /** @brief The allocated permanent random generator */\n  /* parallel changed this */   /* maths_rstrf *randstr; */\n\n  /** @brief The function to prepare the subring variable sbrmax */\n  void (*srprsbrmax)(void *rpm, int srnr, int disk);\n\n  /** @brief The function to prepare the subring variables, term zeroth order */\n  void (*srprb0)(void *rpm, int srnr, int disk);\n\n  /** @brief The function to prepare the subring variables, sin term first order */\n  void (*srprs1)(void *rpm, int srnr, int disk);\n\n  /** @brief The function to prepare the subring variables, cos term first order */\n  void (*srprc1)(void *rpm, int srnr, int disk);\n\n  /** @brief The function to prepare the subring variables, sin term second order */\n  void (*srprs2)(void *rpm, int srnr, int disk);\n\n  /** @brief The function to prepare the subring variables, cos term second order */\n  void (*srprc2)(void *rpm, int srnr, int disk);\n\n  /** @brief The function to prepare the subring variables, sin term third order */\n  void (*srprs3)(void *rpm, int srnr, int disk);\n\n  /** @brief The function to prepare the subring variables, cos term third order */\n  void (*srprc3)(void *rpm, int srnr, int disk);\n\n  /** @brief The function to prepare the subring variables, sin term fourth order */\n  void (*srprs4)(void *rpm, int srnr, int disk);\n\n  /** @brief The function to prepare the subring variables, cos term fourth order */\n  void (*srprc4)(void *rpm, int srnr, int disk);\n\n  /** @brief The function to add the zeroth order term, sin component */\n  void (*prb0)(void *rpm, float *flux, int srnr, float sinaz, float cosaz, int disk);\n\n  /** @brief The function to add the first order term, sin component */\n  void (*prs1)(void *rpm, float *flux, int srnr, float sinaz, float cosaz, int disk);\n\n  /** @brief The function to add the first order term, cos component */\n  void (*prc1)(void *rpm, float *flux, int srnr, float sinaz, float cosaz, int disk);\n\n  /** @brief The function to add the second order term, sin component */\n  void (*prs2)(void *rpm, float *flux, int srnr, float sinaz, float cosaz, int disk);\n\n  /** @brief The function to add the second order term, cos component */\n  void (*prc2)(void *rpm, float *flux, int srnr, float sinaz, float cosaz, int disk);\n\n  /** @brief The function to add the third order term, sin component */\n  void (*prs3)(void *rpm, float *flux, int srnr, float sinaz, float cosaz, int disk);\n\n  /** @brief The function to add the third order term, cos component */\n  void (*prc3)(void *rpm, float *flux, int srnr, float sinaz, float cosaz, int disk);\n\n  /** @brief The function to add the fourh order term, sin component */\n  void (*prs4)(void *rpm, float *flux, int srnr, float sinaz, float cosaz, int disk);\n\n  /** @brief The function to add the fourth order term, cos component */\n  void (*prc4)(void *rpm, float *flux, int srnr, float sinaz, float cosaz, int disk);\n\n  /** @brief Function to determine the cloud number */\n  void (*getcloudnumber) (void *rpm, int srnr, int disk);\n\n  /** @brief Function returning azimuth and flux signum of new point source */\n  void (*getaz)(void* rpm, float *az, float *cosaz, float *sinaz, int *signum, int srnr, int disk);\n\n} inf_smi;\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @struct inf_gau\n   @brief struct to handle the Gaussian terms in surface brightness\n */\n/* ------------------------------------------------------------ */\ntypedef struct inf_gau {\n\n  void (*srpr0) (void *rpm, int srnr, int i, int disk);\n  void (*srpr1) (void *rpm, int srnr, int i, int disk);\n  void (*srpr2) (void *rpm, int srnr, int i, int disk);\n  void (*srpr3) (void *rpm, int srnr, int i, int disk);\n\n  /** @brief function initialising the rng, nth Gaussian */\n  void (*rndmf_init0)(void *rpm, int srnr, int i, int disk);\n  void (*rndmf_init1)(void *rpm, int srnr, int i, int disk);\n  void (*rndmf_init2)(void *rpm, int srnr, int i, int disk);\n  void (*rndmf_init3)(void *rpm, int srnr, int i, int disk);\n\n  /** @brief The allocated random generators */\n     /* parallel changed this */ /* maths_rstrf *randstr[4]; */\n\n  /** @brief Function to determine the cloud number */\n  void (*getcloudnumber0) (void *rpm, int srnr, int i, int disk);\n  void (*getcloudnumber1) (void *rpm, int srnr, int i, int disk);\n  void (*getcloudnumber2) (void *rpm, int srnr, int i, int disk);\n  void (*getcloudnumber3) (void *rpm, int srnr, int i, int disk);\n\n} inf_gau;\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @struct inf_sdis\n   @brief struct to handle the ring dependent dispersion\n */\n/* ------------------------------------------------------------ */\ntypedef struct inf_sdis {\n\n  /** @brief The seed for the velocity dispersional random number generator */\n  /* parallel changed this */ /* int iseed[2]; */\n\n  /** @brief The allocated permanent random generator */\n  /* parallel changed this */ /* maths_rstrf *randstr; */\n\n  /** @brief function initialising the dispersion rng */\n  void (*rndmf_init)(void *rpm, int srnr, int disk);\n\n  /** @brief The function to calculate the ring-dependent dispersion */\n  void (*pr)(void *rpm, float *v, float *vold, int srnr, int disk);\n\n  /** @brief The function to forward the rng */\n  void (*pr_empty)(void *rpm, int srnr, int disk);\n\n  /** @brief The function to calculate and grid the ring-dependent dispersion over and over again */\n  void (*repeater)(void *rpm, float *pp, float vold, int srnr, hdrinf *hdr, long *j, int signum, long *npoints, int disk);\n\n  /** @brief The function to change the numbers of cloud flux and cloud number */\n  void (*chclfl)(void *rpm, int srnr, int disk);\n\n} inf_sdis;\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @struct inf_azi\n   @brief struct to handle the ring dependent dispersion\n */\n/* ------------------------------------------------------------ */\ntypedef struct inf_azi {\n\n  /** @brief Preparing the ranges from the parameters and other things */\n  void (*srpr0) (void *rpm, int srnr, int i, int disk);\n  void (*srpr1) (void *rpm, int srnr, int i, int disk);\n\n  /** @brief The function to check if a point source is accepted */\n  void (*setoutrange)(int *outofrange);\n\n  /** @brief The function to check if a point source is accepted */\n  void (*pr0)(float *azi, float ranges[2][4], int *outofrange, int i);\n  void (*pr1)(float *azi, float ranges[2][4], int *outofrange, int i);\n\n  /** @brief The function to shape the point source */\n  int (*srshape)(void *rpm, float *pp, float sinaz, float cosaz, int srnr, int outofrange, int disk);\n\n  /** @brief Function correcting for the point source number */\n  void (*corrp)(void *rpm, int srnr, int *outofrange, int signum);\n} inf_azi;\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @struct inf_vrad\n   @brief struct to handle the vertical gradient in rotation velocity\n */\n/* ------------------------------------------------------------ */\ntypedef struct inf_vrad {\n\n  /** @brief The function to calculate the radial term */\n  void (*pr)(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\n\n} inf_vrad;\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @struct inf_vver\n   @brief struct to handle the vertical gradient in rotation velocity\n */\n/* ------------------------------------------------------------ */\ntypedef struct inf_vver {\n\n  /** @brief The function to calculate the radial term */\n  void (*pr)(void *rpm, float *v, int srnr, int disk);\n  void (*pr_rota)(void *rpm, float *v, float *v2, int srnr, int disk);\n\n} inf_vver;\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @struct inf_dvro\n   @brief struct to handle the vertical gradient in rotation velocity\n */\n/* ------------------------------------------------------------ */\ntypedef struct inf_dvro {\n\n  /** @brief The function to calculate the radial term */\n  void (*pr)(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\n\n} inf_dvro;\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @struct inf_dvra\n   @brief struct to handle the vertical gradient in rotation velocity\n */\n/* ------------------------------------------------------------ */\ntypedef struct inf_dvra {\n\n  /** @brief The function to calculate the radial term */\n  void (*pr)(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\n\n} inf_dvra;\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @struct inf_dvve\n   @brief struct to handle the vertical gradient in rotation velocity\n */\n/* ------------------------------------------------------------ */\ntypedef struct inf_dvve {\n\n  /** @brief The function to calculate the radial term */\n  void (*pr)(void *rpm, float *point, int srnr, int disk);\n\n} inf_dvve;\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @struct inf_vm0\n   @brief struct to handle the planar s1 term\n */\n/* ------------------------------------------------------------ */\ntypedef struct inf_vm0 {\n\n  /** @brief The function to calculate the radial term */\n  void (*pr)(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\n\n} inf_vm0;\n\ntypedef struct inf_vm1 {\n\n  /** @brief The function to calculate the radial term, sin component */\n  void (*prs)(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\n\n  /** @brief The function to calculate the radial term, cos component */\n  void (*prc)(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\n\n  /** @brief The function to prepare the subring variables */\n  void (*srprs)(void *rpm, int srnr, int disk);\n\n  /** @brief The function to prepare the subring variables */\n  void (*srprc)(void *rpm, int srnr, int disk);\n} inf_vm1;\n\ntypedef struct inf_vm2 {\n\n  /** @brief The function to calculate the radial term, sin component */\n  void (*prs)(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\n\n  /** @brief The function to calculate the radial term, cos component */\n  void (*prc)(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\n\n  /** @brief The function to prepare the subring variables */\n  void (*srprs)(void *rpm, int srnr, int disk);\n\n  /** @brief The function to prepare the subring variables */\n  void (*srprc)(void *rpm, int srnr, int disk);\n} inf_vm2;\n\ntypedef struct inf_vm3 {\n\n  /** @brief The function to calculate the radial term, sin component */\n  void (*prs)(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\n\n  /** @brief The function to calculate the radial term, cos component */\n  void (*prc)(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\n\n  /** @brief The function to prepare the subring variables */\n  void (*srprs)(void *rpm, int srnr, int disk);\n\n  /** @brief The function to prepare the subring variables */\n  void (*srprc)(void *rpm, int srnr, int disk);\n\n} inf_vm3;\n\ntypedef struct inf_vm4 {\n\n  /** @brief The function to calculate the radial term, sin component */\n  void (*prs)(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\n\n  /** @brief The function to calculate the radial term, cos component */\n  void (*prc)(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\n\n  /** @brief The function to prepare the subring variables */\n  void (*srprs)(void *rpm, int srnr, int disk);\n\n  /** @brief The function to prepare the subring variables */\n  void (*srprc)(void *rpm, int srnr, int disk);\n\n} inf_vm4;\n\n\ntypedef struct inf_ro1 {\n\n  /** @brief The function to calculate the radial term, sin component */\n  void (*prs)(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\n\n  /** @brief The function to calculate the radial term, cos component */\n  void (*prc)(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\n\n  /** @brief The function to prepare the subring variables */\n  void (*srprs)(void *rpm, int srnr, int disk);\n\n  /** @brief The function to prepare the subring variables */\n  void (*srprc)(void *rpm, int srnr, int disk);\n} inf_ro1;\n\ntypedef struct inf_ro2 {\n\n  /** @brief The function to calculate the radial term, sin component */\n  void (*prs)(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\n\n  /** @brief The function to calculate the radial term, cos component */\n  void (*prc)(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\n\n  /** @brief The function to prepare the subring variables */\n  void (*srprs)(void *rpm, int srnr, int disk);\n\n  /** @brief The function to prepare the subring variables */\n  void (*srprc)(void *rpm, int srnr, int disk);\n} inf_ro2;\n\ntypedef struct inf_ro3 {\n\n  /** @brief The function to calculate the radial term, sin component */\n  void (*prs)(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\n\n  /** @brief The function to calculate the radial term, cos component */\n  void (*prc)(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\n\n  /** @brief The function to prepare the subring variables */\n  void (*srprs)(void *rpm, int srnr, int disk);\n\n  /** @brief The function to prepare the subring variables */\n  void (*srprc)(void *rpm, int srnr, int disk);\n\n} inf_ro3;\n\ntypedef struct inf_ro4 {\n\n  /** @brief The function to calculate the radial term, sin component */\n  void (*prs)(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\n\n  /** @brief The function to calculate the radial term, cos component */\n  void (*prc)(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\n\n  /** @brief The function to prepare the subring variables */\n  void (*srprs)(void *rpm, int srnr, int disk);\n\n  /** @brief The function to prepare the subring variables */\n  void (*srprc)(void *rpm, int srnr, int disk);\n\n} inf_ro4;\n\n\ntypedef struct inf_ra1 {\n\n  /** @brief The function to calculate the radial term, sin component */\n  void (*prs)(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\n\n  /** @brief The function to calculate the radial term, cos component */\n  void (*prc)(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\n\n  /** @brief The function to prepare the subring variables */\n  void (*srprs)(void *rpm, int srnr, int disk);\n\n  /** @brief The function to prepare the subring variables */\n  void (*srprc)(void *rpm, int srnr, int disk);\n} inf_ra1;\n\ntypedef struct inf_ra2 {\n\n  /** @brief The function to calculate the radial term, sin component */\n  void (*prs)(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\n\n  /** @brief The function to calculate the radial term, cos component */\n  void (*prc)(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\n\n  /** @brief The function to prepare the subring variables */\n  void (*srprs)(void *rpm, int srnr, int disk);\n\n  /** @brief The function to prepare the subring variables */\n  void (*srprc)(void *rpm, int srnr, int disk);\n} inf_ra2;\n\ntypedef struct inf_ra3 {\n\n  /** @brief The function to calculate the radial term, sin component */\n  void (*prs)(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\n\n  /** @brief The function to calculate the radial term, cos component */\n  void (*prc)(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\n\n  /** @brief The function to prepare the subring variables */\n  void (*srprs)(void *rpm, int srnr, int disk);\n\n  /** @brief The function to prepare the subring variables */\n  void (*srprc)(void *rpm, int srnr, int disk);\n\n} inf_ra3;\n\ntypedef struct inf_ra4 {\n\n  /** @brief The function to calculate the radial term, sin component */\n  void (*prs)(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\n\n  /** @brief The function to calculate the radial term, cos component */\n  void (*prc)(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\n\n  /** @brief The function to prepare the subring variables */\n  void (*srprs)(void *rpm, int srnr, int disk);\n\n  /** @brief The function to prepare the subring variables */\n  void (*srprc)(void *rpm, int srnr, int disk);\n\n} inf_ra4;\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @struct inf_wm0\n   @brief struct to handle the planar s1 term\n */\n/* ------------------------------------------------------------ */\ntypedef struct inf_wm0 {\n\n  /** @brief The function to calculate the radial term */\n  void (*pr)(void *rpm, float *z, int srnr, float sinaz, float cosaz, int disk);\n} inf_wm0;\n\ntypedef struct inf_wm1 {\n\n  /** @brief The function to calculate the radial term, sin component */\n  void (*prs)(void *rpm, float *z, int srnr, float sinaz, float cosaz, int disk);\n\n  /** @brief The function to calculate the radial term, cos component */\n  void (*prc)(void *rpm, float *z, int srnr, float sinaz, float cosaz, int disk);\n\n  /** @brief The function to prepare the subring variables */\n  void (*srprs)(void *rpm, int srnr, int disk);\n\n  /** @brief The function to prepare the subring variables */\n  void (*srprc)(void *rpm, int srnr, int disk);\n} inf_wm1;\n\ntypedef struct inf_wm2 {\n\n  /** @brief The function to calculate the radial term, sin component */\n  void (*prs)(void *rpm, float *z, int srnr, float sinaz, float cosaz, int disk);\n\n  /** @brief The function to calculate the radial term, cos component */\n  void (*prc)(void *rpm, float *z, int srnr, float sinaz, float cosaz, int disk);\n\n  /** @brief The function to prepare the subring variables */\n  void (*srprs)(void *rpm, int srnr, int disk);\n\n  /** @brief The function to prepare the subring variables */\n  void (*srprc)(void *rpm, int srnr, int disk);\n} inf_wm2;\n\ntypedef struct inf_wm3 {\n\n  /** @brief The function to calculate the radial term, sin component */\n  void (*prs)(void *rpm, float *z, int srnr, float sinaz, float cosaz, int disk);\n\n  /** @brief The function to calculate the radial term, cos component */\n  void (*prc)(void *rpm, float *z, int srnr, float sinaz, float cosaz, int disk);\n\n  /** @brief The function to prepare the subring variables */\n  void (*srprs)(void *rpm, int srnr, int disk);\n\n  /** @brief The function to prepare the subring variables */\n  void (*srprc)(void *rpm, int srnr, int disk);\n\n} inf_wm3;\n\ntypedef struct inf_wm4 {\n\n  /** @brief The function to calculate the radial term, sin component */\n  void (*prs)(void *rpm, float *z, int srnr, float sinaz, float cosaz, int disk);\n\n  /** @brief The function to calculate the radial term, cos component */\n  void (*prc)(void *rpm, float *z, int srnr, float sinaz, float cosaz, int disk);\n\n  /** @brief The function to prepare the subring variables */\n  void (*srprs)(void *rpm, int srnr, int disk);\n\n  /** @brief The function to prepare the subring variables */\n  void (*srprc)(void *rpm, int srnr, int disk);\n\n} inf_wm4;\n\n\ntypedef struct inf_ls0 {\n\n  /** @brief The function to calculate a shift along the major axis */\n  void (*pr)(void *rpm, float *z, int srnr, float sinaz, float cosaz, int disk);\n} inf_ls0;\n\ntypedef struct inf_lc0 {\n\n  /** @brief The function to calculate a shift along the major axis */\n  void (*pr)(void *rpm, float *z, int srnr, float sinaz, float cosaz, int disk);\n} inf_lc0;\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/* \n   @struct ringparms\n   @brief All variables that are needed for the description of the rings\n\n   @li @c float @c x  x position in arcsec (grids)\n*/\n/* ------------------------------------------------------------ */\ntypedef struct ringparms\n{\n  /** @brief Number of disks */\n  int ndisks;\n\n  /** @brief Number of rings */\n  int nur;\n\n  /** @brief Array of size nur*(NPARAMS+(ndisks-1)*NDPARAMS)+1 containing the parameters */\n  double *par;\n\n  /* Layer type */\n  int *ltype; \n\n  /** @brief Array of same size containing the previous parameters */\n  double *oldpar;\n\n  /** @brief Array tracking if a parameter has changed, for use in chkchange */\n  int *chapar;\n\n  /** @brief Subset separation in grids */\n  double radsep; \n\n  /** @brief number of subrings */\n  int nr;\n  \n  /** @brief big version of par, for all subrings */\n  float *modpar;\n\n  /** @brief array of interpolation objects, for each parameter class one */\n  gsl_interp **gsl_interparray;\n\n  /** @brief array of interpolation lookup objects */\n  gsl_interp_accel **gsl_interp_accelarray;\n\n  /** @brief array of smoothing schemes for each parameter: 0: linear 1: spline 2: Akima */ \n  int *smothcar;\n\n  /** @brief array of interpolation objects, for each parameter class one */\n  gsl_interp **gsl_indinterparray;\n\n  /** @brief array of interpolation lookup objects */\n  gsl_interp_accel **gsl_indinterp_accelarray;\n\n  /** @brief array of smoothing schemes for each parameter for indexing: 0: linear 1: spline 2: Akima */ \n  int *smothindcar;\n\n  /** @brief dummy of size nur used in interpolation: array of binary values 1: active, 0: indexed */\n  int *actarray;\n\n  /** @brief dummy of size nur used in interpolation: array of indices of current parameter array */\n  int *actindar;\n\n  /** @brief dummy of size nur used in interpolation: input to interpolation function, y */\n  double *interar;\n\n  /** @brief dummy of size nur used in interpolation: input to interpolation function, x */\n  double *radar;\n\n  /** @brief Flux of one cloud */\n  double *cflux;\n\n  /** @brief Noise weighting */\n  float weight;\n\n  /** @brief Memory mode */\n  int mode;\n\n  /** @brief Initialisation mode */\n  int inimode;\n\n  /** @brief The allocated permanent random generator */\n  /* parallel changed this */ /* maths_rstrf *permrandstr[ndisks]; */\n\n  /** @brief One seed argument for the permanent random number generator */\n  /* parallel changed this */ int iseed2;\n\n  /** @brief A list of subring descriptors */\n  srd **sd;\n\n  /** @brief The number of pointsources outside the cube */\n  long outpoints;\n\n  /** @brief A dummy for use in writemodel */\n  int *allnpoints;\n\n  /** @brief A dummy for use in writemodel */\n  long *fluxpoints;\n\n  /** @brief The penalty for outlyers */\n  double penalty;\n\n  /** @brief The factor for penalties sigmax^2*sigmay^2/sigma_rms^2 */\n  double penfact;\n\n  /** @brief struct to handle the ring dispersion */\n  inf_sdis **inf_sdisv;\n\n  /** @brief structs to handle radial, vertical velocities and vertical gradients */\n  inf_vrad  **inf_vradv;\n  inf_vver  **inf_vverv;\n  inf_dvro  **inf_dvrov;\n  inf_dvra  **inf_dvrav;\n  inf_dvve  **inf_dvvev;\n\n\n  /** @brief struct to handle the planar s0 term */\n  inf_vm0 **inf_vm0v;\n  inf_vm1 **inf_vm1v;\n  inf_vm2 **inf_vm2v;\n  inf_vm3 **inf_vm3v;\n  inf_vm4 **inf_vm4v;\n  \n  /** @brief struct to handle the planar s0 term */\n  inf_ra1 **inf_ra1v;\n  inf_ra2 **inf_ra2v;\n  inf_ra3 **inf_ra3v;\n  inf_ra4 **inf_ra4v;\n  \n  /** @brief struct to handle the planar s0 term */\n  inf_ro1 **inf_ro1v;\n  inf_ro2 **inf_ro2v;\n  inf_ro3 **inf_ro3v;\n  inf_ro4 **inf_ro4v;\n  \n  /** @brief struct to handle the warp s0 term */\n  inf_wm0 **inf_wm0v;\n  inf_wm1 **inf_wm1v;\n  inf_wm2 **inf_wm2v;\n  inf_wm3 **inf_wm3v;\n  inf_wm4 **inf_wm4v;\n\n  /** @brief struct to handle the lopsidedness sin and cos term */\n  inf_ls0  **inf_ls0v;\n  inf_lc0  **inf_lc0v;\n\n  /** @brief struct to handle the surface brightness distribution */\n  inf_smi  **inf_smiv;\n\n  /** @brief struct to handle the surface brightness distribution, Gaussian arms */\n  inf_gau  **inf_gauv;\n\n  /** @brief struct to handle excluding ranges */\n  inf_azi  **inf_aziv;\n\n#ifdef PBCORR\n\n  /** @brief Function to allocate the primary beam factor list */\n  void (*alloc_pbcfac)(struct ringparms *rpm, int srnr, int disk);\n\n  /** @brief Function to deallocate the primary beam factor list */\n  void (*dealloc_pbcfac)(struct ringparms *rpm, int srnr, int disk);\n\n  /** @brief Function to fill the primary beam factor list */\n  void (*fill_pbcfac)(hdrinf *hdr, struct srd **sd, int disk, int srnr, long *pnr, int *grid);\n\n  /** @brief Function to fold in the primary beam factor list when constructing the cube*/\n  void (*corr_pbcfac)(struct srd **sd, int disk, int srnr, long grid);\n\n#endif\n\n} ringparms;\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/* \n   @struct reg_cont\n   @brief A container to handle regularisation\n\n*/\n/* ------------------------------------------------------------ */\ntypedef struct reg_cont\n{\n  /** @brief fourat container (see fourat.h) */\n  fourat_container *fc;\n\n  /** @brief Correct position in the par array */\n  int posoffirst;\n\n  /** @brief pointer to correct position in the par array */\n  double *first;\n\n  /** @brief start of the step for penalising */\n  double regthre;\n\n  /** @brief width of the step for penalising */\n  double regwidt;\n\n  /* amplitude of the step for penalising */\n  double regampl;\n\n  /* step for amplitude per loop */\n  double regaste;\n\n  /* step for amplitude per loop */\n  double regampd;\n\n  /** @brief ratio, for storage */\n  double ratio;\n} reg_cont;\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/* \n   @struct fitparms\n   @brief All variables that are needed for the description of the fitting process\n\n   @li @c float @c x  x position in arcsec (grids)\n*/\n/* ------------------------------------------------------------ */\ntypedef struct fitparms\n{\n  /** @brief The list for variation of parameters */\n  varlel *varylist;\n\n  /** @brief Number of models to compute */\n  int loops; \n\n  /** @brief Start annealing factor */\n/*   double anstart; */\n  \n  /** @brief Stop annealing factor */\n/*   double anend;  */\n\n  /** @brief Annealing steps */\n/*   int ansteps; */\n\n  /** @brief The initialised normal random generator */\n  maths_rstr *normrandstr; \n\n  /** @brief Random number initialisation */\n  int iseed[2];\n\n  /** @brief The fitting procedure: 0: annealing, 1: golden section */\n  int fitmode;\n\n  /** @brief The number of the current loop minus one */\n  long loopnr;\n\n  /** @brief The number of models calculated, only in use for fitmode > 1 */\n  long recnr;\n\n  /** @brief An indicator if something is out of range */\n  int outofrange;\n\n  /** @brief The current number of pointsources */\n  int *npoints;\n\n  /** @brief The fitter */\n  gft_mst *gft_mstv;\n\n  /** @brief The container of additional arguments*/\n  void *adar;\n\n  /** @brief Total maximum iterations for gft */\n  int maxiter;\n\n  /** @brief Total maximum steps per iteration for gft */\n  int callite;\n\n  /** @brief Size of solution relative to minsteps (grid normalisation) */\n  double size;\n\n  /** @brief PSWARM seed */\n  int psse;\n  \n  /** @brief PSWARM number of particles */\n  int psnp;\n  \n  /** @brief PSWARM cognition parameter */\n  double psco;\n  \n  /** @brief PSWARM social parameter */\n  double psso;\n  \n  /** @brief PSWARM maximum velocity */\n  double psmv;\n  \n  /** @brief PSWARM number of function evaluations to go from initial weight to final weight */\n  int psnf;\n  \n  /** @brief PSWARM initial weight */\n  double psii;\n  \n  /** @brief PSWARM final weight */\n  double psfi;\n  \n  /** @brief PSWARM increase delta */\n  double psid;\n  \n  /** @brief PSWARM decrease delta */\n  double psdd;\n  \n  /** @brief The input of vary, saved for output */\n  char *varyhstr;\n  \n  /** @brief  The index and dependencies*/\n  decomp_inlist *index;\n  \n  /** @brief Monitoring: variable to report on the number of point sources contributing to flux*/\n  long *fluxpoints;\n  \n  /** @brief  Container for regularisation */\n  reg_cont **reg_contv;\n  \n  /** @brief Monitoring variable for use in genfit */\n  size_t mon_alloops;\n\n  /** @brief Monitoring variable for use in genfit */\n  size_t mon_niters;\n\n  /** @brief Monitoring variable for use in genfit */\n  size_t mon_iters;\n\n  /** @brief Monitoring variable for use in genfit */\n  size_t mon_alliter;\n\n  /** @brief Monitoring variable for use in genfit */\n  size_t mon_allcalls;\n\n  /** @brief Monitoring variable for use in genfit */\n  size_t mon_calls_st;\n\n  /** @brief Monitoring variable for use in genfit */\n  size_t mon_ncalls_st;\n\n  /** @brief Monitoring variable for use in genfit */\n  size_t mon_maxiter;\n\n  /** @brief Monitoring variable for use in genfit */\n  size_t mon_loops;\n\n  /** @brief Monitoring variable for use in genfit */\n  double mon_bestchisq;\n\n  /** @brief Monitoring variable for use in genfit */\n  double mon_actchisq;\n\n  /** @brief Monitoring variable for use in genfit */\n  double mon_dsize;\n\n  /** @brief Monitoring variable for use in genfit */\n  double *mon_dpar;\n\n  /** @brief Monitoring variable for use in genfit */\n  double mon_stopsize;\n\n  /** @brief Monitoring variable for use in genfit */\n  double mon_size;\n\n  /** @brief Monitoring variable for use in genfit */\n  int mon_npar_cur;\n\n  /** @brief Monitoring variable for use in genfit */\n  int mon_npar;\n\n  /** @brief Monitoring variable for use in genfit */\n  int mon_ring;\n\n  /** @brief Monitoring variable for use in genfit */\n  int *mon_repnpoints;\n\n  /** @brief Monitoring variable for use in genfit */\n  double *mon_totalflux;\n\n  /** @brief Monitoring variable for use in genfit */\n  char mon_key[20];\n\n  /** @brief degrees of freedom */\n  double dof;\n\n} fitparms;\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/* \n   @struct adar\n   @brief additional arguments to be read by the fitting function passed to gft\n\n   This is practically everything\n*/\n/* ------------------------------------------------------------ */\ntypedef struct adar\n{\n  /** @brief The startinf struct */\n  startinf *startinfv; \n\n  /** @brief The loginf struct */\n  loginf *log;\n\n  /** @brief The hdrinf struct */\n  hdrinf *hdr;\n\n  /* @brief The ring parameters */\n  ringparms *rpm;\n\n  /* @brief The fitparms struct */\n  fitparms *fit;\n} adar;\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/* \n   @struct vector\n   @brief A threedimensional vector\n\n   @li @c float @c x  x position in arcsec (grids)\n*/\n/* ------------------------------------------------------------ */\ntypedef struct vector\n{\n  /** @brief x component */\n  double x;\n\n  /** @brief y component */\n  double y;\n\n  /** @brief z component */\n  double z;\n\n} vector;\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/* (PRIVATE) GLOBAL VARIABLES */\n/* ------------------------------------------------------------ */\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @var errno\n   @brief Needed by giplib for no obvious reason\n*/\n/* ------------------------------------------------------------ */\nint errno;\n\n/* Check for the beam read-in and the map unit read-in if changing this, also check function makecoolhdr() (obsolete) */\n/* static char userdeltunit[] = \"ARCSEC\"; */\n/* static char user3deltunit[] = \"KM/S\"; */\n/* static char userglobunit[] = \"DEGREE\"; */\n/* static char user3globunit[] = \"KM/S\"; */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/* PRIVATE TYPEDEFS */\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/* PRIVATE FUNCTION DECLARATIONS */\n/* ------------------------------------------------------------ */\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static int create_defaults_from_dcp(hdrinf * hdr, decomp_listel *decomp_listelv, double *parmax, double *parmin, int *moderate, double *delstart, double *delend, int *itestart, int *iteend, double *satdelt, double *mindelta, int nur, int ndisks, int fitmode)\n   @brief Creates defaults from a decomp list\n\n   The arrays need to be allocated and will be filled with the appropriate defaults depending on the contents of decomp_listelv.\n\n   @param hdr (hdrinf *)    A header descriptor struct, properly filled.\n   @param decomp_listelv (decomp_listel *) decomp array as returned by decomp_get() from the simparse module\n   @param parmax         (double *)        Parameter maxima\n   @param parmin         (double *)        Parameter minima\n   @param moderate       (int *)           Moderate array\n   @param delstart       (double *)        Delstart array\n   @param delend         (double *)        Delend array\n   @param itestart       (int *)           Itestart array\n   @param iteend         (int *)           Iteend array\n   @param satdelt        (double *)        Satdelt array\n   @param mindelta       (double *)        Mindelta array\n   @param nur            (int)             Number of rings\n   @param ndisks         (int)             Number of disks\n   @param fitmode        (int)             Fitmode\n\n   @return (success) int create_varylist_from_dcp: 0\n           (error)   1;\n*/\n/* ------------------------------------------------------------ */\nstatic int create_defaults_from_dcp(hdrinf * hdr, decomp_listel *decomp_listelv, double *parmax, double *parmin, int *moderate, double *delstart, double *delend, int *itestart, int *iteend, double *satdelt, double *mindelta, int nur, int ndisks, int fitmode);\n\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static  varlel *create_varylist_from_dcp(hdrinf * hdr, decomp_listel *decomp_listelv, double *parmax, double *parmin, int *moderate, double *delstart, double *delend, int *itestart, int *iteend, double *satdelt, double *mindelta, int nur, int ndisks)\n   @brief Creates a varlel list from a decomp list\n\n   The arrays need to be allocated and need to contain as many elements as input groups are recorded in decomp_listelv.\n\n   @param hdr (hdrinf *)    A header descriptor struct, properly filled.\n   @param decomp_listelv (decomp_listel *) decomp array as returned by decomp_get() from the simparse module\n   @param parmax         (double *)        Parameter maxima\n   @param parmin         (double *)        Parameter minima\n   @param moderate       (int *)           Moderate array\n   @param delstart       (double *)        Delstart array\n   @param delend         (double *)        Delend array\n   @param itestart       (int *)           Itestart array\n   @param iteend         (int *)           Iteend array\n   @param satdelt        (double *)        Satdelt array\n   @param mindelta       (double *)        Mindelta array\n   @param nur            (int)             Number of rings\n   @param ndisks         (int)             Number of disks\n\n   @return (success) varlel *create_varylist_from_dcp: NULL terminated varylist\n           (error)   NULL;\n*/\n/* ------------------------------------------------------------ */\nstatic  varlel *create_varylist_from_dcp(hdrinf * hdr, decomp_listel *decomp_listelv, double *parmax, double *parmin, int *moderate, double *delstart, double *delend, int *itestart, int *iteend, double *satdelt, double *mindelta, int nur, int ndisks);\n\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static char *gluetodecomp(char **inputofvarymult, char **inputofvarysing)\n   @brief Creates a decomp-readable list from inputofvarymult and inputofvarysing\n\n   For compatibility reasons, the VARYMULT= and VARYSING= parameters\n   are still allowed. This creates a string from a char ** array as\n   given by sparsenext that uses whitespaces to separate the input\n   fields from varymult and varysing to create an equivalent string\n   for the VARY= parameter.\n\n   @param inputofvarysing  (char **) A NULL-terminated list of strings\n   @param inputofvarymult  (char **) A NULL-terminated list of strings\n\n   @return (success) gluetodecomp (char *) allocated array\n           (error) NULL if memory allocation fails\n*/\n/* ------------------------------------------------------------ */\nstatic char *gluetodecomp(char **inputofvarymult, char **inputofvarysing);\n\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static int writemodel(hdrinf *origin, ringparms *rpm, fitparms *fit, double *par, decomp_inlist *index);\n   @brief Writes the model to the output\n\n   @param origin (hdrinf *)       header info struct initialised by get_hdrinf()\n   @param rpm    (ringparms *)    properly configured ringparms struct\n   @param fit    (fitparms *)     properly configured fitparms struct\n   @param par    (double *)       properly configured parameter list, the values of which get used\n   @param index  (decomp_index *) index list as returned in simparse\n\n   @return (success) 1;\n           (error) 0;\n*/\n/* ------------------------------------------------------------ */\nstatic int writemodel(hdrinf *origin, ringparms *rpm, fitparms *fit, double *par, decomp_inlist *index);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static int anyout_tir(int *device, char *message)\n   @brief wrapper to call anyout_c from gipsy\n   \n   For the description of the input parameters see GIPSY, char gets\n   converted via fchar and int gets converted via cast to fint\n\n   @param device       (int *) (dummy)\n   @param message     (char *)\nTIR_ONLY\n  @return see anyout_c, return is casted to int, -1 on memory problems\n*/\n/* ------------------------------------------------------------ */\nstatic int anyout_tir(int *device, char *message);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static int anyout_cor(FILE *device, char *message)\n   @brief Print a message to device\n   \n   The function should be preferred to anyout_tir.\n\n   @param device      (FILE *) the stream\n   @param message     (char *) the message\nTIR_ONLY\n  @return compare anyout_c, return is casted to int, -1 on memory problems\n*/\n/* ------------------------------------------------------------ */\n/* static int anyout_cor(FILE *device, char *message); */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static int error_tir(int *device, char *message)\n   @brief wrapper to call error_c from gipsy\n   \n   For the description of the input parameters see GIPSY, here: issue a message through stderr, abort only for *device == 4\n\n   @param device       (int *)\n   @param message     (char *)\n\nTIR_ONLY\n\n  @return see error_c, return is casted to int, -1 on memory problems\n*/\n/* ------------------------------------------------------------ */\nstatic int error_tir(int *device, char *message);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static int cancel_tir(simparse_scn_arel **arel, char *parname, int depth)\n   @brief cancelling user input\n   \n   This is basically synonymous to simparse_scn_arellist.\n\n  @param simparse_scn_arellist (simparse_scn_arel **) Allocated simparse_scn_arel NULL-terminated list.\n  @param key (char *) Key to remove\n  @param depth (int)  Number of simparse_scn_arellist structs to correct, starting at 0. This can be used to e.g. correct the first two structs (e.g. user input and command line, but not any input file with depth = 1) only.\n\nTIR_ONLY.\n\n  @return see cancel_c, return is casted to int, -1 on memory problems\n*/\n/* ------------------------------------------------------------ */\nstatic int cancel_tir(simparse_scn_arel **arel, char *parname, int depth);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static int userint_tir(simparse_scn_arel **arel, int *anarray, int *elements, int *defaultstat, char *keyword, char *message)\n   @brief wrapper to call userchar_c from gipsy\n   \n   Attempt to get as close to the gipsy stuff as possible.\n\n   @param arel        (simparse_scn_arel **)\n   @param astring     (int *)\n   @param elements    (int  *)\n   @param defaultstat (int  *)\n   @param keyword     (char *)\n   @param message     (char *)\n\nTIR_ONLY.\n\n  @return see userint_c, return is casted to int, -1 on memory problems\n*/\n/* ------------------------------------------------------------ */\nstatic int userint_tir(simparse_scn_arel **arel, int *anarray, int *elements, int *defaultstat, char *keyword, char *message);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static int userdble_tir(simparse_scn_arel **arel, double *anarray, int *elements, int *defaultstat, char *keyword, char *message)\n   @brief wrapper to call userchar_c from gipsy\n   \n   Attempt to get as close to the gipsy stuff as possible.\n\n   @param arel        (simparse_scn_arel **) Input struct.\n   @param astring     (double *)\n   @param elements    (int  *)\n   @param defaultstat (int  *)\n   @param keyword     (char *)\n   @param message     (char *)\n\nTIR_ONLY.\n\n  @return see userint_c, return is casted to int, -1 on memory problems\n*/\n/* ------------------------------------------------------------ */\nstatic int userdble_tir(simparse_scn_arel **arel, double *anarray, int *elements, int *defaultstat, char *keyword, char *message);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static int userreal_tir(simparse_scn_arel **arel, float *anarray, int *elements, int *defaultstat, char *keyword, char *message)\n   @brief wrapper to call userreal_c from gipsy\n   \n   For the description of the input parameters see GIPSY, char gets\n   converted via fchar\n\n   @param arel        (simparse_scn_arel **) Input struct.\n   @param anarray     (float *)\n   @param elements    (int  *)\n   @param defaultstat (int  *)\n   @param keyword     (char *)\n   @param message     (char *)\n\nTIR_ONLY.\n\n  @return see userreal_c, -1 on memory problems\n*/\n/* ------------------------------------------------------------ */\nstatic int userreal_tir(simparse_scn_arel **arel, float *anarray, int *elements, int *defaultstat, char *keyword, char *message);\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static double gchsq_gen_start(double *vector, void *rest);\n   @brief function passed to gft\n\n   The function receives a vector of fit parameters from the gft\n   module and returns the chisquare. Used only once on initialisation of the fitter.\n\n   @param vector (double *)  An array of fit parameters\n   @param rest   (void *)    concealed adar struct\n   @return double gchsq_gen  The chisquared\n*/\n/* ------------------------------------------------------------ */\nstatic double gchsq_gen_start(double *vector, void *rest);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static double gchsq_gen(double *vector, void *rest);\n   @brief function passed to gft\n\n   The function receives a vector of fit parameters from the gft\n   module and returns the chisquare.  rest is a concealed adar struct\n   that contains the necessary connections to the fit parameters. In\n   case of an interrupted fitting process, this routine will read the\n   logfile instead of producing a real fit. If the recovery of\n   information has finished, the function replaces itself by\n   gchsq_gen2, the \"real\" function to get the chisquare.\n\n   @param vector (double *)  An array of fit parameters\n   @param rest   (void *)    concealed adar struct\n   @return double gchsq_gen  The chisquared\n*/\n/* ------------------------------------------------------------ */\nstatic double gchsq_gen(double *vector, void *rest);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static double gchsq_gen2(double *vector, void *rest);\n   @brief function passed to gft\n\n   The function receives a vector of fit parameters from the gft\n   module and returns the chisquare (checking for constraints in\n   parameter space), producing an appropriate output to the logfile,\n   the textlog, the screen, and occasionally a best-fit data cube.\n   rest is a concealed adar struct that contains the necessary\n   connections to the fit parameters.\n\n   @param vector (double *)  An array of fit parameters\n   @param rest   (void *)    concealed adar struct\n   @return double gchsq_gen  The chisquared\n*/\n/* ------------------------------------------------------------ */\nstatic double gchsq_gen2(double *vector, void *rest);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static loginf *create_loginf(void)\n   @brief Creates a loginf structure\n\n   Creates a hdrinf structure allocating and if necessary initialising\n   all structs and arrays.\n\n   @return (success) hdrinf create_hdrinf: Allocated and initialised\n   hdrinf struct\\n \n           (error): NULL\n*/\n/* ------------------------------------------------------------ */\nstatic loginf *create_loginf(void);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static void destroy_loginf(loginf *hdr, int ndisks)\n   @brief Destroys a loginf structure\n\n   Destroys a loginf structure deallocating all arrays. A\n   non-allocated array has to be terminated (has to have a NULL value)\n   to get the function work properly.\n\n   @param hdr (loginf *) A loginf struct to be destroyed\n   @param ndisks (int)   Number of disks, only used in function call hdl_init()\n\n   @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void destroy_loginf(loginf *hdr, int ndisks);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static loginf *get_loginf(startinf *startinfv, loginf *loginfv)\n   @brief Initialisation of the program concerning logfiles\n\n   Takes over all logfile related io, returns an allocated loginf struct.\n\n\n\n   @return (success) loginf *get_loginf: A loginf struct with the acquired info\n           (error) NULL\n*/\n/* ------------------------------------------------------------ */\nstatic loginf *get_loginf(startinf *startinfv, loginf *loginfv);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static startinf *create_startinf(void)\n   @brief Creates a startinf structure\n\n   Creates a hdrinf structure allocating and if necessary initialising\n   all structs and arrays.\n\n   @return (success) startinf create_startinf: Allocated and initialised\n   startinf struct\\n \n           (error): NULL\n*/\n/* ------------------------------------------------------------ */\nstatic startinf *create_startinf(void);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static void destroy_startinf(startinf *startinfv, int ndisks)\n   @brief Destroys a startinf structure\n\n   Destroys a startinf structure deallocating all arrays. A\n   non-allocated array has to be terminated (has to have a NULL value)\n   to get the function work properly.\n\n   @param startinfv (startinf *) A startinf struct to be destroyed\n   @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void destroy_startinf(startinf *startinfv);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static startinf *get_startinf(int argc, char **argv)\n   @brief Initialisation of the program concerning restart information\n\n   Takes over all startfile related io, returns an allocated startinf struct. Starts command line and file io.\n\n   @param argc (int) Number of command line arguments (as argument to main)\n   @param argv (char *) Array of command line arguments\n\n   @return (success) startinf *get_startinf: A startinf struct with the acquired info\n           (error) NULL\n*/\n/* ------------------------------------------------------------ */\nstatic startinf *get_startinf(int argc, char **argv);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n@fn static int check_restart(startinf *startinfv, hdrinf *hdr, ringparms *rpm, loginf *log)\n   @brief Checks switches and returns an answer whether to restart\n\n   Takes as an input a pointer to a (properly allocated) startinf\n   struct and returns an answer whether to restart. If restart, checks\n   if rpm -> par needs to be put into intern status. If NULL is passed\n   for rpm, then this will not be done. If rpm is not NULL, then it\n   needs to be properly allocated. hdr and log must be properly allocated and filled if rpm <> 0\n\n   1: The restartfile is read out, and checked for existence or the firstrun switch is set to 1.\n   0: If restartfile is not defined or not existent and firstrun = 0\n\n   @param startinfv (startinf *) A startinf struct to be destroyed\n   @param hdr (hdrinf *) A hdr descriptor struct, properly filled.\n   @param rpm (ringparms *) A ring parameter descriptor struct, properly filled or NULL\n   @param log (loginf *)    A log descriptor struct, properly filled or NULL\n\n   @return (success) 1 if a restart is appropriate\n           (error) 0 if stopping is recommended\n*/\n/* ------------------------------------------------------------ */\nstatic int check_restart(startinf *startinfv, hdrinf *hdr, ringparms *rpm, loginf *log);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static void loop_restart(startinf *startinfv)\n   @brief Check if restartfile exists and loop until its last change time stamp has changed with respect to the value stored in startinfv, make some switches afterwards\n\n   Set the value of firstrun in startinfv to 0. Check if restartfile\n   has been defined in startinfv, and check if a time stamp can be\n   retrieved. If either one or the other fails, return (leading to a\n   breakout of the restart loop via function check_restart). If\n   successful, repeat time stamp request, until the retrieved time\n   stamp changes with respect to the one stored in startinfv ->\n   timestamp. If that occurs, update startinfv -> startfile from the\n   input (command line or .def file) of the parameter RESTARTNAME=.\n\n   @param startinfv (startinf *) A startinf struct \n   @return int loop_restart(): 0 all ok\n                               1 malloc problems\n*/\n/* ------------------------------------------------------------ */\nstatic int loop_restart(startinf *startinfv);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static hdrinf *create_hdrinf()\n   @brief Creates a hdrinf structure\n\n   Creates a hdrinf structure allocating and if necessary initialising\n   all arrays\n\n   @return (success) hdrinf create_hdrinf: Allocated and initialised\n   hdrinf struct\\n \n           (error): NULL\n*/\n/* ------------------------------------------------------------ */\nstatic hdrinf *create_hdrinf(void);\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static void destroy_hdrinf(hdrinf *hdr)\n   @brief Destroys a hdrinf structure\n\n   Destroys a hdrinf structure deallocating all arrays. A\n   non-allocated array has to be terminated (has to have a NULL value)\n   to get the function work properly\n\n   @param hdr (hdrinf *) A hdrinf struct to be destroyed\n\n   @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void destroy_hdrinf(hdrinf *hdr);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static hdrinf *get_hdrinf(startinf *startinfv, loginf *log, hdrinf *hdrinfv)\n   @brief Initialisation of the program concerning info from the dataset\n\n   Takes over all dataset related io, returns an allocated hdrinf struct, with all the current rubbish.\n   @param log (startinf *) A start descriptor struct, properly filled.\n   @param log (loginf *) A log descriptor struct, properly filled.\n   @param log (hdrinf *) A hdr descriptor struct, properly filled.\n\n    @return (success) hdrinf *get_hdrinf: A hdrinf struct with the acquired info and rubbish\n           (error) NULL\n*/\n/* ------------------------------------------------------------ */\nstatic hdrinf *get_hdrinf(startinf *startinfv, loginf *log, hdrinf *hdrinfv);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n@fn static int get_parameter_double(startinf *startinfv, loginf *log, hdrinf *hdr, ringparms *rpm, char *message, char *parname, int force)\n   @brief Get a double parameter from the .def file\n\n   Reads in and checks a double parameter from the .def file for consistency with the logfile.\n\n   @param startinfv (startinf *) A startinf descriptor struct, properly filled.\n   @param log (loginf *)    A log descriptor struct, properly filled.\n   @param hdr (hdrinf *)    A header descriptor struct, properly filled.\n   @param rpm (ringparms *) A ring parameter descriptor struct, properly filled.\n   @param message (char *)  Message to display\n   @param parname (char *)  The parameter name\n   @param ident (int)       The parameter identification (PXXX)\n   @param force (int)       same as def parameter from Gipsy. If 2, hidden, 4 not hidden.\n \n  @return int get_parameter_double; 0(success) 1(error)\n*/\n/* ------------------------------------------------------------ */\nstatic int get_parameter_double(startinf *startinfv, loginf *log, hdrinf *hdr, ringparms *rpm, char *message, char *parname, int ident, int force);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static srd *create_srd(int n)\n   @brief Creates a list of subring descriptors with n elements\n\n   The pointsource lists are terminated with NULL\n\n   @param n (int) Number of subrings to allocate the list for\n\n   @return (success) srd *create_srd: Allocated and initialised\n   srd list\\n \n           (error): NULL\n*/\n/* ------------------------------------------------------------ */\nstatic srd *create_srd(int n);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static void destroy_srd(srd *sd, int n)\n   @brief Destroys a list of subring descriptors\n\n   The pointsource lists shold be terminated with NULL if they are\n   deallocated\n\n   @param sd (srd *) The list to destroy\n   @param n (int)    Number of elements of the list.\n\n   @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void destroy_srd(srd *sd, int n);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static ringparms *create_ringparms(int ndisks)\n   @brief Creates a ringparms structure\n\n   Creates a ringparms structure allocating and if necessary initialising\n   all arrays\n\n   @param ndisks (int) number of disks\n\n   @return (success) ringparms *create_ringparms: Allocated and initialised\n   hdrinf struct\\n \n           (error): NULL\n*/\n/* ------------------------------------------------------------ */\nstatic ringparms *create_ringparms(int ndisks);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static void destroy_ringparms(ringparms *hdr)\n   @brief Destroys a ringparms structure\n\n   Destroys a ringparms structure deallocating all arrays. A\n   non-allocated array has to be terminated (has to have a NULL value)\n   to get the function work properly\n\n   @param hdr (ringparms *) A hdrinf struct to be destroyed\n\n   @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void destroy_ringparms(ringparms *hdr);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static ringparms *get_ringparms(startinf *startinfv, loginf *log, hdrinf *hdr, ringparms *ringparmsv)\n   @brief Fill the ringparms struct from the input\n\n   Reads in properly the ringparms struct.\n\n   @param startinfv (startinf *) A start descriptor struct, properly filled.\n   @param hdr (hdrinf *) A header descriptor struct, properly filled.\n   @param log (loginf *) A log descriptor struct, properly filled.\n   @param ringparmsv (ringparms *) A ringparms descriptor struct, properly filled or NULL.\n\n   @return    @return (success) ringparms *get_ringparms: A ringparms struct with the acquired info and rubbish\n           (error) NULL\n*/\n/* ------------------------------------------------------------ */\nstatic ringparms *get_ringparms(startinf *startinfv, loginf *log, hdrinf *hdr, ringparms *ringparmsv);\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static fitparms *create_fitparms(ringparms *rpm)\n   @brief Creates a fitparms structure\n\n   Creates a fitparms structure allocating and if necessary initialising\n   all arrays\n\n   @param rpm (ringparms *) A ring parameter descriptor struct, properly filled.\n\n\n   @return (success) fitparms *create_fitparms: Allocated and initialised\n   fitparms struct\\n \n           (error): NULL\n*/\n/* ------------------------------------------------------------ */\nstatic fitparms *create_fitparms(ringparms *rpm);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static void destroy_fitparms(fitparms *hdr)\n   @brief Destroys a fitparms structure\n\n   Destroys a fitparms structure deallocating all arrays. A\n   non-allocated array has to be terminated (has to have a NULL value)\n   to get the function work properly\n\n   @param hdr (fitparms *) A hdrinf struct to be destroyed\n\n   @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void destroy_fitparms(fitparms *hdr);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static fitparms *get_fitparms(startinf *startinfv, loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fitparmsv)\n   @brief Fill the fitparms struct from the input\n\n   Reads in properly the fitparms struct. If run a second time only reads in the required parameters.\n\n   @param startinfv (startinf *) A start descriptor struct, properly filled.\n   @param log (hdrinf *) A log descriptor struct, properly filled.\n   @param hdr (hdrinf *) A header descriptor struct, properly filled.\n   @param rpm (ringparms *) A ring parameter descriptor struct, properly filled.\n   @param fitparmsv (fitparms *) A fit descriptor struct, properly filled or NULL.\n\n   @return    @return (success) fitparms *get_fitparms: A fitparms struct with the acquired info and rubbish\n           (error) NULL\n*/\n/* ------------------------------------------------------------ */\nstatic fitparms *get_fitparms(startinf *startinfv, loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fitparmsv);\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static double dparamtointern(double value, int par, hdrinf *hdr, int ndisks)\n   @brief conversion of some units\n\nConverts the input as being coordinates given by the user to inernal (grid-) units. Caution!!! For the conversion of absolute map coordinates this function is not appropriate.\n Use globtointern instead!\n\n   RADI    1  \n   VROT    2  \n   Z0      3  \n   SBR    4  \n   INCL    5  \n   PA      6  \n   XPOS    7  \n   YPOS    8  \n   VSYS    9  \n   CONDISP 10\n   \n   @param value (double)   value to convert\n   @param par   (char)     type of parameter (see above)\n   @param hdr   (hdrinf *) The properly configured header description struct\n   @param ndisks   (int)   Number of disks\n\n   @return double paramtointern: converted value\n*/\n/* ------------------------------------------------------------ */\nstatic double dparamtointern(double value, int par, hdrinf *hdr, int ndisks);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static double ddparamtointern(double value, int par, hdrinf *hdr, int ndisks)\n   @brief conversion of some units\n\nConverts the input as being coordinates given by the user to inernal (grid-) units, used only for differential quantities (as in the fitparms)\n Use globtointern instead!\n\n   RADI    1  \n   VROT    2  \n   Z0      3  \n   SBR    4  \n   INCL    5  \n   PA      6  \n   XPOS    7  \n   YPOS    8  \n   VSYS    9  \n   CONDISP 10\n   \n   @param value (double)   value to convert\n   @param par   (char)     type of parameter (see above)\n   @param hdr   (hdrinf *) The properly configured header description struct\n   @param ndisks   (int)   Number of disks\n\n   @return double ddparamtointern: converted value\n*/\n/* ------------------------------------------------------------ */\nstatic double ddparamtointern(double value, int par, hdrinf *hdr, int ndisks);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static double dinterntoparam(double value, int par, hdrinf *hdr, int ndisks)\n   @brief conversion of some units\n\nConverts the input as being inernal (map-) coordinates to units as given by the user. Caution!!! For the conversion of map coordinates this function is, strictly speaking, not appropriate.\n Use globtointern instead!\n\n   RADI    1  \n   VROT    2  \n   Z0      3  \n   SBR    4  \n   INCL    5  \n   PA      6  \n   XPOS    7  \n   YPOS    8  \n   VSYS    9  \n   CONDISP 10\n   \n   @param value (double)   value to convert\n   @param par   (char)     type of parameter (see above)\n   @param hdr   (hdrinf *) The properly configured header description struct\n   @param ndisks   (int)   Number of disks\n\n   @return double dinterntoparam: converted value\n*/\n/* ------------------------------------------------------------ */\nstatic double dinterntoparam(double value, int par, hdrinf *hdr, int ndisks);\n\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static double ddinterntoparam(double value, int par, hdrinf *hdr, int ndisks)\n   @brief conversion of some units\n\nConverts the input as being inernal (map-) coordinates to units as given by the user, used only for differential quantities (as in the fitparms).\n\n   RADI    1  \n   VROT    2  \n   Z0      3  \n   SBR    4  \n   INCL    5  \n   PA      6  \n   XPOS    7  \n   YPOS    8  \n   VSYS    9  \n   CONDISP 10\n   \n   @param value (double)   value to convert\n   @param par   (char)     type of parameter (see above)\n   @param hdr   (hdrinf *) The properly configured header description struct\n   @param ndisks   (int)   Number of disks\n\n   @return double ddinterntoparam: converted value\n*/\n/* ------------------------------------------------------------ */\nstatic double ddinterntoparam(double value, int par, hdrinf *hdr, int ndisks);\n\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static double simpleinterntoglob(double value, int par, hdrinf *hdr)\n   @brief conversion of some units\n\n   Converts the input globals as being inernal (map-) coordinates to units as\n   given by the user in a simple way for the use as min and max.\n\n   RADI    1  \n   VROT    2  \n   Z0      3  \n   SBR    4  \n   INCL    5  \n   PA      6  \n   XPOS    7  \n   YPOS    8  \n   VSYS    9  \n   CONDISP 10\n\n   @param value (double)   value to convert\n   @param par   (char)     type of parameter (see above)\n   @param hdr   (hdrinf *) The properly configured header description struct\n\n   @return double simpleinterntoglob: converted value\n*/\n/* ------------------------------------------------------------ */\n/* static double simpleinterntoglob(double value, int par, hdrinf *hdr); */\n\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static double simpleglobtointern(double value, int par, hdrinf *hdr, int ndisks)\n   @brief conversion of some units\n\n   Converts the input globals as being global coordinates to internal\n   map units as given by the user in a simplified way, for the use as min and max.\n\n   RADI    1  \n   VROT    2  \n   Z0      3  \n   SBR    4  \n   INCL    5  \n   PA      6  \n   XPOS    7  \n   YPOS    8  \n   VSYS    9  \n   CONDISP 10\n  \n   @param value (double)   value to convert\n   @param par   (char)     type of parameter (see above)\n   @param hdr   (hdrinf *) The properly configured header description struct\n   @param ndisks   (int)   Number of disks\n\n   @return double simpleglobtointern: converted value\n*/\n/* ------------------------------------------------------------ */\nstatic double simpleglobtointern(double value, int par, hdrinf *hdr, int ndisks);\n\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static double vusertointern(double value, hdrinf *hdr)\n   @brief conversion of absolute velocity units\n\nConverts the input as being absolute velocity coordinates given by the user to inernal (grid-) units. \n\n   \n   @param value (double)   value to convert\n   @param hdr   (hdrinf *) The properly configured header description struct\n\n   @return double vusertointern: converted value\n*/\n/* ------------------------------------------------------------ */\n/* static double vusertointern(double value, hdrinf *hdr); */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static double vinterntouser(double value, hdrinf *hdr)\n   @brief conversion of absolute velocity units\n\nConverts the input as being absolute velocity coordinates in the internal map to units given by the user.\n   \n   @param value (double)   value to convert\n   @param hdr   (hdrinf *) The properly configured header description struct\n\n   @return double vinterntouser: converted value\n*/\n/* ------------------------------------------------------------ */\n/* static double vinterntouser(double value, hdrinf *hdr); */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static void globtointern(double *invalue, double *outvalue, hdrinf *hdr)\n   @brief conversion of map units\n\n   Converts the input as being (map-) coordinates to internal units. \n\n   \n   @param invalue (double *)  values to convert, x, y, v.\n   @param outvalue (double *)  converted values, x, y, v.\n   @param hdr   (hdrinf *) The properly configured header description struct\n\n   @return double dinterntoparam: converted value\n*/\n/* ------------------------------------------------------------ */\nstatic void globtointern(double *invalue, double *outvalue, hdrinf *hdr);\n\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static void interntoglob(double *invalue, double *outvalue, hdrinf *hdr)\n   @brief conversion of map units\n\n   Converts the input as being internal units to (map-) coordinates. \n\n   \n   @param value (double *)  values to convert, x, y, v.\n   @param outvalue (double *)  converted values, x, y, v.\n   @param hdr   (hdrinf *) The properly configured header description struct\n\n   @return double dinterntoparam: converted value\n*/\n/* ------------------------------------------------------------ */\nstatic void interntoglob(double *invalue, double *outvalue, hdrinf *hdr);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static void changetointern(double *params, int nur, hdrinf *hdr, int ndisks)\n   @brief Change the parameter list params to internal units as if being user units\n   \n   @param params (double *) parameter list, nur*(NPARAMS+(ndisks-1)*NDPARAMS)+NSPARAMS elements\n   @param nur    (int)      number of rings\n   @param hdr    (hdrinf *) A properly configured hdrinf struct\n   @param ndisks (int)      Number of disks\n\n   @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void changetointern(double *params, int nur, hdrinf *hdr, int ndisks);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/*\n   @fn static int par2int(char *par);\n   @brief Identification of string keywords with numbers\n\n   Identifies the input string (No whitespaces to be passed) and\n   returns it's identification. This is somewhat critical and\n   dependent on the implementation of the ftstab module, call\n   ftstab_hdlreset_() before using:\n\n   default   par2int=0\n   \"RADI\"    par2int=1\n   \"VROT\"    par2int=2\n   \"Z0\"      par2int=3\n   \"SBR\"    par2int=4\n   \"INCL\"    par2int=5\n   \"PA\"      par2int=6\n   \"XPOS\"    par2int=7\n   \"YPOS\"    par2int=8\n   \"VSYS\"    par2int=9\n   \"CONDISP\"  par2int=10\n\n   @param par (char *) A string to pass to the function\n   @return int par2int: The identifyer as defined above.\n*/\n/* ------------------------------------------------------------ */\n/*   int ftstab_gtitln_(char *titl); */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/*\n   @fn static void int2par(char *key, int par);\n   @brief Identification of numbers with string keywords\n\n   Identifies the input number and\n   returns it's identification keyword in a string key. This is somewhat critical and\n   dependent on the implementation of the ftstab module, call\n   ftstab_hdlreset_() before using:\n\n   \"DEFAULT\" par2int=0 \n   \"RADI\"    par2int=1\n   \"VROT\"    par2int=2\n   \"Z0\"      par2int=3\n   \"SBR\"    par2int=4\n   \"INCL\"    par2int=5\n   \"PA\"      par2int=6\n   \"XPOS\"    par2int=7\n   \"YPOS\"    par2int=8\n   \"VSYS\"    par2int=9\n   \"CONDISP  par2int=10\n\n   @param par (char *) A string to pass to the function\n   @return int par2int: The identifyer as defined above.\n*/\n/* ------------------------------------------------------------ */\n/* int ftstab_putcoltitl(char *key, int coltitle); */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static varlel *appendvarlel(varlel *last)\n   @brief Constructor of an element of the varlel list\n\n   Appends a varlel struct (terminated) to the last and returns a\n   pointer to the appended element\n\n   @param last (varlel *) The last varlel element (or NULL)\n\n     @return (success) varlel *appendvarlel: The new element of the list\n             (error) NULL\n*/\n/* ------------------------------------------------------------ */\nstatic varlel *appendvarlel(varlel *last);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static void destroyvarlel(varlel *first)\n   @brief Destructor of a varlel list\n\n   Destroys a varlel list from first on. The element before first will\n   not be terminated, while the list has to be terminated. All\n   elements arrays have to be dynamically allocated in case of nelem\n   != 0.\n\n   @param first (varlel *) The first varlel element to destroy(or NULL)\n\n   @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void destroyvarlel(varlel *first);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static inlistel *appendinlistel(inlistel *last)\n   @brief Constructor of an element of a inlistel list\n\n   Appends a inlistel struct (terminated) to the last and returns a\n   pointer to the appended element\n\n   @param last (inlistel *) The last varlel element (or NULL)\n\n     @return (success) inlistel *appendinlistel: The new element of the list\n             (error) NULL\n*/\n/* ------------------------------------------------------------ */\n/* static inlistel *appendinlistel(inlistel *last); */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static int galmod(hdrinf *hdr, ringparms *rpm, int fitmode, varlel *varele, decomp_index *index, long *fluxpoints, int *allnpoints)\n   @brief Core to construct a pointsource cube from a parameter list\n\n   This is the part where the things that are done with galmod are\n   done. It is detached from the structure that passes packages of\n   descriptors, because it can, in principle be used everywhere.  With\n   the fitmode and varele, the interpolation of rings and the\n   calculation of pointsources will be done only, if parameters have\n   currently been changed. For this, the information contained in the\n   varlel element is used. If NULL is passed, then everything will be\n   calculated freshly. NULL should always be passed, if not sure\n   whether the parameters have been interpolated correctly in a\n   previous run or if interpover was used as a stand-alone or not at\n   all before.\n\n   @param hdr        (hdrinf *)    header information struct\n   @param rpm        (ringparms *) Ring parameter information struct\n   @param fit        (fitparms *)  Properly allocated fitparms struct\n   @param varele     (varlel *)    Actual element that is processed in the varlel list\n   @param index      (decomp_inlist *) An index- and dependency list as provided by simparse function decomp_get_inlist()\n   @param fluxpoints (long *)          number of pointsources contributing to flux (in case of mixed negative and positive clouds this number is not identical to the number of point sources)\n     @return (success) int galmod: 1\n             (error) 0\n*/\n/* ------------------------------------------------------------ */\nstatic int galmod(hdrinf *hdr, ringparms *rpm, int fitmode, varlel *varele, decomp_inlist *index, long *fluxpoints, int *allnpoints);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static int changedependent(ringparms *rpm, double *par, decomp_inlist *index, varlel *varele, int fitmode, int *chapar)\n   @brief Takes the parameter list and changes the parameters on the index\n\n   Takes the parameter list and identifies parameters on the index in\n   decomp_inlist, then interpolates between the parameters\n   that the parameter on the index depends on\n\n   @param rpm      (ringparms *)     Ring parameter information struct\n   @param par      (double *)        Parameter list\n   @param index    (decomp_inlist *) An index- and dependency list as provided by simparse function decomp_get_inlist()\n   @param chapar   (int *)           array of parameters that change\n\n   @return (success) int changedependent: number of indexed parameters\n           (error) -1\n\n*/\n/* ------------------------------------------------------------ */\nstatic int changedependent(ringparms *rpm, double *par, decomp_inlist *index, int *chapar);\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static void interpover(ringparms *rpm, double radsep, int fitmode, varlel *varele)\n   @brief Constructs the modpar array by interpolating over the par array\n\n   Constructs the modpar array by interpolating over the parameters,\n   that are a content of the varlel item. If fitmode = 0, then varele\n   is taken as the first item in a ll, and the function will scan\n   through all elements of this ll, if fitmode = 1, then only the\n   actually passed element will be scanned. If NULL is passed as a\n   value of varele, then all parameters are changed or \"touched\" even\n   if they stay the same value.\n\n   @param rpm     (ringparms *)     Ring parameter information struct\n   @param radsep  (double)          Radius separation of subring in appropriate units\n   @param fitmode (int)             Fit mode to check for\n   @param varele  (varlel *)        Parameter list element.\n   @param index   (decomp_inlist *) an index list as defined in simparse \n   @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void interpover(ringparms *rpm, double radsep, int fitmode, varlel *varele, decomp_inlist *index);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static void interpinit(ringparms *rpm, double radsep, int disk)\n   @brief Constructs the modpar array by interpolating over the par array \n\n   This is the same as interpover but without checking the varlel\n   list. Should always be used if the par parameter list has been\n   changed without consulting the varlel list.\n\n   @param rpm    (ringparms *) Ring parameter information struct\n   @param radsep (double)      Radius separation of subring in appropriate units\n   @param disk    (int)     disk number; if the disk is not fitted, 0 is returned.\n\n   @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void interpinit(ringparms *rpm, double radsep, int disk);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static int chkchangep(varlel *varele, int fitmode, int parnr, int nur)\n  @brief Help function to interpover: Check if the modpar array has to be changed for a parameter\n  \n  If in the previous parameter change a change of the parameter has\n   occured, this function will return 1, 0 otherways.\n  \n  @param varele (varlel *) Actual element of the varlel list, or the\n  first element in case of fitmode = 0\n  \n  @param fitmode (int)     Fitmode 0: Metropolis, 1: Golden section\n  parameter information struct \n  @param ringnr  (int)     Number of ring to be checked\n  @param nur      (int)     Number of rings\n\n  @return int chkchange: 1 if change for parameter has occured, 0 if not\n*/\n/* ------------------------------------------------------------ */\nstatic int chkchangep(varlel *varele, int fitmode, int parnr, int nur);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void srprep(ringparms *rpm, int srnr, long mode, int disk)\n  @brief Preparation of a srd struct\n  \n  Precalculations for the calculation of a ring.\n  \n  @param rpm  (ringparms *) Properly configured ringparms struct\n  @param srnr (int *)       Number of the subring (start with 0)\n  @param mode (long)        Dummy at the moment  \n  @param disk (int)         Disk number\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void srprep(ringparms *rpm, int srnr, long mode, int disk);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static long srconst(hdrinf *hdr, ringparms *rpm, int srnr, long mode, int disk)\n  @brief Generation of a pointsource list\n  \n  Generates a pointsource list that is attached to the appropriate srd struct\n\n  @param hdr  (hdrinf *)    Properly configured hdrinf struct\n  @param rpm  (ringparms *) Properly configured ringparms struct\n  @param srnr (int *)       Number of the subring (start with 0)\n  @param mode (long)        Dummy at the moment  \n  @param disk (int)         Disk number\n\n  @return long srconst: Number of pointsources outside the cube\n*/\n/* ------------------------------------------------------------ */\nstatic long srconst(hdrinf *hdr, ringparms *rpm, int srnr, long mode, int disk);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static int srshape(hdrinf *hdr, ringparms *rpm, float sinaz, float cosaz, int srnr, long mode, int disk)\n  @brief Determines the coordinates of a point source\n  \n  Subroutine to srconst. After the calculation of the azimuth of a\n  point source, the coordinates are transformed according to the\n  parameters in this function.\n\n  @param rpm   (ringparms *) Properly configured ringparms struct\n  @param pp    (float *)     Point source coordinates\n  @param sinaz (float)       sine of azimuth\n  @param cosaz (float)       cosine of azimuth\n  @param srnr  (int *)       Number of the subring (start with 0)\n  @param disk (int)         Disk number\n\n  @return long srconst: Number of pointsources outside the cube\n*/\n/* ------------------------------------------------------------ */\nstatic void srshape(ringparms *rpm, float *pp, float sinaz, float cosaz, int srnr, int disk);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void gridpoint_norm(hdrinf *hdr, void (*fill_pbcfac)(hdrinf *hdr, float *primbeam, struct srd **sd, int disk, int srnr, long *pnr, int *grid), float *modpar, int nr, struct srd **sd, int srnr, long *pnr, float *pp, int signum, long *npoints, int disk)\n  @brief Grids a point to a pointsource list\n  \n  Grids the point point (6 phase-space coords) in a list of pointers to the cube hdr ->\n  model. If the point doesn't fit the cube, the pointsource number of\n  the subring will be redced by 1, if it fits, pnr will be increased\n  by one. Called by srconst.\n  This function changes only the n variable in the pointsource descriptor.\n\n  @param hdr    (hdrinf *)    Properly configured hdrinf struct\n  @param modpar (float *)     Properly configured array of subring descriptors\n  @param nr     (int *)       Properly number of subrings\n  @param sd     (srd **)       Properly configured subring descriptor\n  @param srnr   (int)         Number of the subring (start with 0)\n  @param pnr    (long *)       Number of the pointsource (start with 0)\n  @param pp     (float *)     Number of the subring (start with 0)\n  @param signum  (int)         Indicates negative point source, dummy in this function  \n  @param npoints (long *)     Number of maximal points in specific structure\n  @param disk (int)         Disk number\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\n#ifdef PBCORR\nstatic void gridpoint_norm(hdrinf *hdr, void (*fill_pbcfac)(hdrinf *hdr, struct srd **sd, int disk, int srnr, long *pnr, int *grid), float *modpar, int nr, struct srd **sd, int srnr, long *pnr, float *pp, int signum, long *npoints, int disk);\n#else\nstatic void gridpoint_norm(hdrinf *hdr, float *modpar, int nr, struct srd **sd, int srnr, long *pnr, float *pp, int signum, long *npoints, int disk);\n#endif\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void gridpoint_mixed(hdrinf *hdr, void (*fill_pbcfac)(hdrinf *hdr, float *primbeam, struct srd **sd, int disk, int srnr, long *pnr, int *grid), float *modpar, int nr, struct srd **sd, int srnr, long *pnr, float *pp, int signum, long *npoints, int disk)\n  @brief Grids a point to a pointsource list\n  \n  Grids the point point (6 phase-space coords) in a list of pointers\n  to the cube hdr -> model. If the point doesn't fit the cube, the\n  pointsource number of the subring will be redced by 1, if it fits,\n  pnr will be increased by one. Called by srconst.  This function\n  changes not only the n variable in the pointsource descriptor, but\n  also the nneg and npos variable. Positive clouds are gridded on the\n  beginning of the pl array, negative clouds at the end.\n\n  @param hdr    (hdrinf *)    Properly configured hdrinf struct\n  @param modpar (float *)     Properly configured array of subring descriptors\n  @param nr     (int *)       Properly number of subrings\n  @param sd     (srd **)       Properly configured subring descriptor\n  @param srnr   (int)         Number of the subring (start with 0)\n  @param pnr    (long *)       Number of the pointsource (start with 0)\n  @param pp     (float *)     Number of the subring (start with 0)\n  @param signum (int)         Indicates negative source, needed for this function\n  @param npoints (long *)     Number of maximal points in specific structure\n  @param disk (int)           Disk number\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\n#ifdef PBCORR\nstatic void gridpoint_mixed(hdrinf *hdr, void (*fill_pbcfac)(hdrinf *hdr, struct srd **sd, int disk, int srnr, long *pnr, int *grid), float *modpar, int nr, struct srd **sd, int srnr, long *pnr, float *pp, int signum, long *npoints, int disk);\n#else\nstatic void gridpoint_mixed(hdrinf *hdr, float *modpar, int nr, struct srd **sd, int srnr, long *pnr, float *pp, int signum, long *npoints, int disk);\n#endif\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static int srput_norm(void (*corr_pbcfac)(struct srd **sd, int disk, int srnr, long *pnr, long grid), struct sdr **sd, float *modpar, int nr, double *cflux, double radsep, int srnr, long *fluxpoints, int disk)\n  @brief Puts a pointsource list on a cube\n  \n  Puts the srnrth pointsource list in rpm on the cube by adding the\n  flux in the list pointwise. In case of exclusively positive or exclusively negative clouds.\n\n  @param hdr    (hdrinf *) Properly configured hdrinf struct\n  @param sd     (srd **)    Properly configured subring descriptor\n  @param modpar (float *)  Properly configured subring parameter array\n  @param nr     (int)      Number of subrings\n  @param cflux  (double *) Cloudflux as determined in the ringparms struct\n  @param radsep (double)   Separation of subrings in pixel\n  @param srnr   (int)      Subring number\n  @param disk (int)        Disk number\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\n#ifdef PBCORR \nstatic int srput_norm(void (*corr_pbcfac)(struct srd **sd, int disk, int srnr, long grid), struct srd **sd, float *modpar, int nr, double *cflux, double radsep, int srnr, long *fluxpoints, int disk);\n#else\nstatic int srput_norm(struct srd **sd, float *modpar, int nr, double *cflux, double radsep, int srnr, long *fluxpoints, int disk);\n#endif\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static int srput_mixed(void (*corr_pbcfac)(struct srd **sd, int disk, int srnr, long *pnr, long grid), struct sdr **sd, float *modpar, int nr, double *cflux, double radsep, int srnr, long *fluxpoints, int disk)\n  @brief Puts a pointsource list on a cube\n  \n  Puts the srnrth pointsource list in rpm on the cube by adding the\n  flux in the list pointwise. In case of mixed positive and negative clouds.\n\n  @param hdr    (hdrinf *) Properly configured hdrinf struct\n  @param sd     (srd *)    Properly configured subring descriptor\n  @param modpar (float *)  Properly configured subring parameter array\n  @param nr     (int)      Number of subrings\n  @param cflux  (double *)   Cloudflux as determined in the ringparms struct\n  @param radsep (double)   Separation of subrings in pixel\n  @param srnr   (int)      Subring number\n  @param disk (int)        Disk number\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\n#ifdef PBCORR\nstatic int srput_mixed(void (*corr_pbcfac)(struct srd **sd, int disk, int srnr, long grid), struct srd **sd, float *modpar, int nr, double *cflux, double radsep, int srnr, long *fluxpoints, int disk);\n#else\nstatic int srput_mixed(struct srd **sd, float *modpar, int nr, double *cflux, double radsep, int srnr, long *fluxpoints, int disk);\n#endif\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static int metropolis(loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit)\n   @brief Metropolis algorithm\n\n   This is the part where the Metropolis iterations are done.\n\n   @param log      (loginf *)    log information struct\n   @param hdr      (hdrinf *)    header information struct\n   @param rpm      (ringparms *) Ring parameter information struct\n   @param fit      (fitparms *)  fit parameter information struct\n\n   @return (success) int metropolis: 1\n           (error) 0\n*/\n/* ------------------------------------------------------------ */\n/* static int metropolis(loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit); */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static int genfit(startinf *startinfv, loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit)\n   @brief Generic gft fit algorithm\n\n   This is the part where the generic fitting with gft is done.\n\n   @param startifv    (startinf *)    Properly configured startinf struct\n   @param log      (loginf *)    log information struct\n   @param hdr      (hdrinf *)    header information struct\n   @param rpm      (ringparms *) Ring parameter information struct\n   @param fit      (fitparms *)  fit parameter information struct\n\n   @return (success) int genfit: 1\n           (error) 0\n*/\n/* ------------------------------------------------------------ */\nstatic int genfit(startinf *startinfv, loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static void destroyinlistel(inlistel *first)\n   @brief Destructor of a inlistel list\n\n   Destroys a inlistel list from first on. The element before first will\n   not be terminated, while the list has to be terminated.\n\n   @param first (inlistel *) The first inlistel element to destroy(or NULL)\n\n   @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void destroyinlistel(inlistel *first);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static int decodestr(char *string, int *array, int max)\n   @brief decodes an input string\n\n   The input string of varymult and varystr has to be a:b where a is\n   less or equal b, b is less than the number of rings (in this\n   function given by the max parameter), and a is greater than 0. If\n   the string is of that structure, the function returns 1 and a and b\n   are put into array as integers, 0 otherways.\n\n   @param string (char *) Input string\n   @int   array  (int *)  Array to contain a and b\n   @param max    (int)    The maximum value that may be read\n \n   @return (success) int decodestr 1\n           (error) 0\n*/\n/* ------------------------------------------------------------ */\n/* static int decodestr(char *string, int *array, int max); */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static void prepout(loginf *log, headerinf *hdr, ringparms *rpm)\n   @brief Opens a file and puts an old-style ascii header to the top\n\n   Opens a file and puts an ascii header to the top, as in the old\n   version of tirific. This function needs ftstab to be initialised as\n   is done in get_ringparms(). The result is put to the component tstream of log.\n\n   @param log (loginf *)    Log description object\n   @param hdr (hdrinf *)    header description object\n   @param rpm (ringparms *) Ring parameter description object\n\n   @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void prepout(loginf *log, hdrinf *hdr, ringparms *rpm);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static void writeoutput(loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit, char accept, double dof, int modcount, double rchisq)\n   @brief Writes the information contained in rpm -> oldpar to the output\n\n   @param log      (loginf *)    log information struct\n   @param hdr      (hdrinf *)    header information struct\n   @param rpm      (ringparms *) Ring parameter information struct\n   @param fit      (fitparms *)  Fit parameter information struct\n   @param accept   (char)        Indicator whether the last model was accepted\n   @param dof      (double)      Degrees of freedom\n   @param modcount (int)         Number of the model\n   @param rchisq   (double)      Reduced chi2\n\n   @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void writeoutput(loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit, char accept, double dof, int modcount, double rchisq);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static void writeoutputread(loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit, char accept, double dof, int modcount, double rchisq)\n   @brief Writes the information contained in rpm -> oldpar to the output\n\n   @param log      (loginf *)    log information struct\n   @param hdr      (hdrinf *)    header information struct\n   @param rpm      (ringparms *) Ring parameter information struct\n   @param fit      (fitparms *)  Fit parameter information struct\n   @param accept   (char)        Indicator whether the last model was accepted\n   @param dof      (double)         Degrees of freedom\n   @param modcount (int)         Number of the model\n   @param rchisq   (double)      Reduced chi2\n\n   @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void writeoutputread(loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit, char accept, double dof, int modcount, double rchisq);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static void writeouttext(loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit, char accept, int dof, int modcount)\n   @brief Writes the information contained in rpm -> oldpar to the text output only\n\n   @param log      (loginf *)    log information struct\n   @param hdr      (hdrinf *)    header information struct\n   @param rpm      (ringparms *) Ring parameter information struct\n   @param fit      (fitparms *)  Fit parameter information struct\n   @param accept   (char)        Indicator whether the last model was accepted\n   @param dof      (int)         Degrees of freedom\n   @param modcount (int)         Number of the model\n   @param proba    (double)      Probability of acceptance\n\n   @return void\n*/\n/* ------------------------------------------------------------ */\n/* static void writeouttext(loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit, char accept, int dof, int modcount, double proba); */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n@fn static void writeoutarray(loginf *log, hdrinf *hdr, ringparms *rpm, double *par, char accept, double chisquare, int modcount, double dof, double chisquare_red)\n   @brief Writes the information contained in par to the output array of rpm\n\n   @param log       (loginf *)    log information struct\n   @param hdr       (hdrinf *)    header information struct\n   @param rpm       (ringparms *) Ring parameter information struct\n   @param par       (double *)    The input parameter array\n   @param accept    (char)        Indicator whether the last model was accepted\n   @param chisquare (double)      Degrees of freedom\n   @param modcount  (int)         Number of the model\n   @param dof       (double)      Degrees of freedom\n   @param chisquare_red  (double) reduced chisquare, direct input\n\n   @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void writeoutarray(loginf *log, hdrinf *hdr, ringparms *rpm, double *par, char accept, double chisquare, int modcount, double dof, double chisquare_red);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static void writeoutarrayerr(hdrinf *hdr, ringparms *rpm, double *par, double *errors, char accept, double chisquare, int modcount, double dof)\n   @brief Writes the information contained in rpm -> par to the output array errors\n\n   @param hdr       (hdrinf *)    header information struct\n   @param rpm       (ringparms *) Ring parameter information struct\n   @param par       (double *)    array containing errors in intrinsic units, must have length of any output array\n   @param errors    (double *)    output array, must have length of any output array\n   @param accept    (char)        Indicator whether the last model was accepted\n   @param chisquare (double)      Degrees of freedom\n   @param modcount  (int)         Number of the model\n   @param dof       (double)      Degrees of freedom\n\n   @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void writeoutarrayerr(hdrinf *hdr, ringparms *rpm, double *par, double *errors, char accept, double chisquare, int modcount, double dof);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static int chprm_metro(varlel *varylist, double *oldpar, double *newpar, maths_rstr *rnd, double deltfact)\n   @brief Changes the parameters in par according to varylist\n\n   Each parameter that is contained in the parameter lists of varylist\n   will be changed randomly. It will be increased or diminished by a\n   number in-between 0 and the delta of the element of the\n   varylist. All parameters adressed in one varylist component will be\n   changed by the same amount. The output is into newpar, while oldpar\n   contains the input parameters to change.\n\n   @param varylist (varlel *)     Information structure to vary the\n   parameters (must be properly configured according to par)\n   @param oldpar   (double *)     Old parameter list\n   @param newpar   (double *)     New parameter list\n   @param rnd      (maths_rstr *) An initialised random generator struct\n   @param loopnr   (double)       Number of actual loop\n\n   @return int chprm_metro: 1 if successful, 0 if a given number FALSEATTEMPTS of attempts to change the model towards an invalid value is exceeded.\n*/\n/* ------------------------------------------------------------ */\n/* static int chprm_metro(varlel *varylist, double *oldpar, double *newpar, maths_rstr *rnd, long loopnr); */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static int chprm_gen(double *parms; varlel *varylist, double *newpar)\n   @brief Changes the parameters in par according to parms\n\n   Each parameter that is contained in the parameter lists of varylist\n   will be changed according to the parms array as passed by the gft\n   fit routine. parms should contain as many parameters as varlel\n   elements are present in the ll. Differences in the actual\n   parameters are kept.\n\n   @param parms (double *)        Parameters as passed by the gft routine\n   @param varylist (varlel *)     Information structure to vary the\n   parameters (must be properly configured according to par)\n   @param newpar   (double *)     New parameter list\n\n   @return int chprm_gen: 0 if successful, n>0 counting the parameters\n   out-of-range. The changes will take place nevertheless.\n*/\n/* ------------------------------------------------------------ */\nstatic int chprm_gen(double *parms, varlel *varylist, double *newpar);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static float zprof(int option, maths_rstrf *permrandstr)\n   @brief Delivers a random variable according to a profile identifyer\n\n   Function to get random deviates for various functions.  The double\n   precision variable fdev contains the random deviate.  If nran is\n   within a factor two of the largest possible integer then integer\n   overflow could occur.  DOUBLE PRECISION FUNCTION\n   fdev(option,nran,iran,idum) Type of distribution function for the\n   random deviates.  \n   Options:\n\n   option = 1 -- Gaussian deviates.\n   option = 2 -- Sech2 deviates.\n   option = 3 -- Exponential deviates.\n   option = 4 -- Lorentzian deviates.\n   option = 5 -- Box deviates. (is also default)\n   option = 6 -- Reset the rng for gaussian\n\n   @param option      (int)         The type of the random variate\n   @param permrandstrf (maths_rstr *) An initialised random number control object from this module\n\n   @return float zprof: A random number distributed specified by option\n*/\n/* ------------------------------------------------------------ */\nstatic float zprof(int option, maths_rstrf *permrandstr, float *y2);\n\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void hdl_init(int ndisks)\n  @brief Initializes the standard header context table\n\n  @param ndisks (int) Number of disks\n*/\n/* ------------------------------------------------------------ */\nstatic int hdl_init(int ndisks);\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static int create_hdu_3(loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit);\n  @brief Opens if necessary creates the third hdu\n\n  Will Create a third hdu of the logfile.\n\n   @param log (loginf *)    log information struct\n   @param hdr (hdrinf *)    header information struct\n   @param rpm (ringparms *) Ring parameter information struct\n   @param fit (fitparms *)  Fit parameter information struct\n\n   @return (success) int create_hdu_3: 0\\\\\n           (error) 1\n*/\n/* ------------------------------------------------------------ */\n/* static int create_hdu_3(loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit); */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static int open_hdu_3(loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit);\n  @brief Opens if necessary creates the third hdu\n\n  Will Create a third hdu of the logfile.\n\n  @param log (loginf *)    log information struct\n  @param hdr (hdrinf *)    header information struct\n  @param rpm (ringparms *) Ring parameter information struct\n  @param fit (fitparms *)  Fit parameter information struct\n\n   @return (success) int create_hdu_3: 0 \\\\\n           (error) 1: Memory error\n                   2: User decides not to fit\n*/\n/* ------------------------------------------------------------ */\nstatic int open_hdu_3(loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static int create_hdu_1(log, hdr, rpm, fit)\n  @brief Creates a fits table and puts the global information to the fits table\n\n  Will create a ftstab fits table with the first hdu from the\n  information acquired in the description objects.\n\n   @param log       (loginf *)    log information struct\n   @param hdr       (hdrinf *)    header information struct\n   @param rpm       (ringparms *) Ring parameter information struct\n   @param fit       (fitparms *)  Fit parameter information struct\n\n   @return (success) int create_hdu_1: 0\\\\\n           (error) 1\n*/\n/* ------------------------------------------------------------ */\n/* static int create_hdu_1(loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit); */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static int create_hdu_2(char *logname, varlel *varylist, varlel **pointarray, int nur, hdrinf *hdr) \n\n  @brief Creates a second hdu of a fits table and puts the fit\n  information contained in the varlel ll to the fits table\n\n  Creates a second hdu of a fits table (deleting consequent elements)\n  and puts the fit information contained in the varlel ll to the fits\n  table. For a proper functionality make sure that the first hdu is already created.\n\n  @param logname    (char *)    The name of the logfile\n  @param varylist   (varlel *)  A properly configured varylist\n  @param pointarray (varlel **) Array with pointers to varlels of the size of elements of deltas given by the user   \n  @param nur        (int)       Number of rings\n  @param hdr        (hdrinf *)  Properly configured headerinf struct\n\n   @return (success) int create_hdu_1: 0\\\\\n           (error) 1\n*/\n/* ------------------------------------------------------------ */\n/* static int create_hdu_2(char *logname, varlel *varylist, varlel **pointarray, int nur, hdrinf *hdr); */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static int change_hdu_2(varlel *varylist, varlel **pointarray, int nur, hdrinf *hdr) \n\n  @brief Creates a second hdu of a fits table and puts the fit\n  information contained in the varlel ll to the fits table\n\n  Changes a second hdu of a fits table (deleting consequent elements)\n  and puts the fit information contained in the varlel ll to the fits\n  table. For a proper functionality make sure that the first hdu is already created and the second is opened. This is only of use if both tables have the identical size.\n\n  @param varylist   (varlel *)  A properly configured varylist\n  @param pointarray (varlel **) Array with pointers to varlels of the size of elements of deltas given by the user   \n  @param nur        (int)       Number of rings\n  @param hdr        (hdrinf *)  Properly configured headerinf struct\n\n   @return (success) int change_hdu_2: 0\\\\\n           (error) 1\n*/\n/* ------------------------------------------------------------ */\n/* static int change_hdu_2(varlel *varylist, varlel **pointarray, int nur, hdrinf *hdr); */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static int primpos_numtype(int ident)\n  @brief Returns the ftstab numerical type of a PRIMPOS identifyer\n\n  @param ident (int) PRIMPOS idendifyer\n\n  @return int primpos_numtype: Numerical type identifyer as in ftstab module\n*/\n/* ------------------------------------------------------------ */\n/* static int primpos_numtype(int ident); */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static double primpos_value(int ident, loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit)\n  @brief Returns the value of a PRIMPOS identifyer from a varele pointer\n\n  @param ident      (int)        identifyer\n  @param log       (loginf *)    log information struct\n  @param hdr       (hdrinf *)    header information struct\n  @param rpm       (ringparms *) Ring parameter information struct\n  @param fit       (fitparms *)  Fit parameter information struct\n\n  @return double primpos_value: value of a PRIMPOS identifyer\n*/\n/* ------------------------------------------------------------ */\n/* static double primpos_value(int ident, loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit); */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static double secpos_value(int ident, varele *varylist, int nur, hdrinf *hdr, int element)\n  @brief Returns the value of a SECPOS identifyer from a varele pointer\n\n  @param ident    (int)      SECPOS idendifyer\n  @param varylist (varele *) pointer to the varele from which the values are extracted\n  @param nur      (int)      Number of rings\n  @param hdr      (hdrinf *) Properly configured headerinf struct\n  @param element  (int)      Number of the element (start with 0) in case of ELEMENTS\n\n  @return double secpos_value: value of a SECPOS identifyer\n*/\n/* ------------------------------------------------------------ */\n/* static double secpos_value(int ident, varlel *varylist, int nur, hdrinf *hdr, int element); */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static int comparevarlel(varlel *varlel1, varlel *varlel2)\n  @brief Checks if the varlels are identical\n\n  @param varlel1 (varlel *) first varlel element\n  @param varlel2 (varlel *) second varlel element\n\n  @return int comparevarlel: 0 if they contain identical values, 1 if they are fatally different, -1, if they are different but contain the same number of elements\n*/\n/* ------------------------------------------------------------ */\n/* static int comparevarlel(varlel *varlel1, varlel *varlel2); */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static int fillhdvarele(varlel *varele, int i, double *array,\n  int parameter, double *parmax, double *parmin, int *moderate, double\n  *delstart, double *delend, int *itestart, int *iteend, double\n  *satdelt, double *mindelta, hdrinf *hdr, loginf *log)\n\n  @brief Puts the values of the arrays into varele, checking for mismatch with array\n\n  Puts the values of the global variables of a varele struct into\n  varele from the single arrays, checking for mismatch with the\n  content of array. If there is any mismatch the user will be\n  prompted. Will return 1 if the user decides to abort. Will return 0\n  if the user does not want to abort. The user is only prompted once\n  and the keyword \"proceed\" has to be canceled afterwards.\n\n  @param varele    (varlel *) An element of the varlist\n  @param i         (int)      The position in the arrays\n  @param parameter (int)      The parameter identification\n  @param array     (double *) The array that will be checked\n  @param parmax    (double *) Parameter list with maxima\n  @param parmin    (double *) Parameter list with minima\n  @param moderate  (int    *) Parameter list with moderate values\n  @param delstart  (double *) Parameter list with delstart values\n  @param delend    (double *) Parameter list with delend values\n  @param itestart  (int    *) Parameter list with itestart values\n  @param iteend    (int    *) Parameter list with iteend values\n  @param satdelt   (double *) Parameter list with satdelt values\n  @param mindelta  (double *) Parameter list with mindelta values\n  @param hdr       (hdrinf *) Properly configured hdrinf struct\n  @param log       (loginf *) Properly configured loginf struct\n  \n  @return int fillhdvarele 1 In case of an error, 0 if everything is ok\n*/\n/* ------------------------------------------------------------ */\n/* static int fillhdvarele(varlel *varele, int i, double *array, int parameter, double *parmax, double *parmin, int *moderate, double *delstart, double *delend, int *itestart, int *iteend, double *satdelt, double *mindelta, hdrinf *hdr, loginf *log); */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static int putmetresults(loginf *log, ringparms *rpm, fitparms *fit)\n  @brief Calculates and puts the results of the fitting procedure\n\n  This function needs the logfile opened by ftstab module at the third\n  extension\n\n  @param  log (loginf *)    Properly configured loginf struct\n  @param  rpm (ringparms *) Properly configured ringparms struct\n  @param  fit (fitparms *)  Properly configured fitparms struct\n\n  @return (success) int putresults: 1\n          (error)   0\n*/\n/* ------------------------------------------------------------ */\n/* static int putmetresults(loginf *log, ringparms *rpm, fitparms *fit); */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static int putgenresults(startinf *startinfv, loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit)\n  @brief Calculates and puts the results of the fitting procedure\n\n  This function needs the logfile opened by ftstab module at the third\n  extension\n\n  @param  startinfv (startinf *)    Properly configured loginf struct\n  @param  log (hdrinf *)    Properly configured hdrinf struct\n  @param  log (loginf *)    Properly configured loginf struct\n  @param  rpm (ringparms *) Properly configured ringparms struct\n  @param  fit (fitparms *)  Properly configured fitparms struct\n\n  @return (success) int putresults: 1\n          (error)   0\n*/\n/* ------------------------------------------------------------ */\nstatic int putgenresults(startinf *startinfv, loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static int golden_section(startinf *startinfv, loginf *log, ringparms *rpm, fitparms *fit)\n  @brief A golden section iteration\n\n  The other working horse, a golden section iteration.\n\n  @param  startinfv (startinf *)    Properly configured loginf struct\n  @param  log (loginf *)    Properly configured loginf struct\n  @param  hdr (hdrinf *)    Properly configured hdrinf struct\n  @param  rpm (ringparms *) Properly configured ringparms struct\n  @param  fit (fitparms *)  Properly configured fitparms struct\n\n  @return int golden_section: Always 1...\n*/\n/* ------------------------------------------------------------ */\nstatic int golden_section(startinf *startinfv, loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit);\n  \n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static int putgoldresults(loginf *log, ringparms *rpm, fitparms *fit)\n  @brief Calculates and puts the results of the fitting procedure\n\n  This function needs the logfile opened by ftstab module at the third\n  extension\n\n  @param  log (loginf *)    Properly configured loginf struct\n  @param  rpm (ringparms *) Properly configured ringparms struct\n  @param  fit (fitparms *)  Properly configured fitparms struct\n\n  @return (success) int putresults: 1\n          (error)   0\n*/\n/* ------------------------------------------------------------ */\nstatic int putgoldresults(loginf *log, ringparms *rpm, fitparms *fit);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static int writeasctable(startinf *startinfv, loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit);\n  @brief Writes an ascii table with the results\n\n  This function needs the logfile opened by ftstab module at the third\n  extension\n\n  @param  startinfv (startinf *)    Properly configured loginf struct\n  @param  log (loginf *)    Properly configured loginf struct\n  @param  hdr (hdrinf *)    Properly configured hdrinf struct\n  @param  rpm (ringparms *) Properly configured ringparms struct\n  @param  fit (fitparms *)  Properly configured fitparms struct\n  @return (success) int writeasctable: 1\n          (error)   0\n*/\n/* ------------------------------------------------------------ */\nstatic int writeasctable(startinf *startinfv, loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit);\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static int writebigasctable(startinf *startinfv, loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit);\n  @brief Writes an ascii table with the results\n\n  This function needs the logfile opened by ftstab module at the third\n  extension. This will list all properties for the subrings.\n\n  @param  startinfv (startinf *)    Properly configured startinf struct\n  @param  log (loginf *)    Properly configured loginf struct\n  @param  hdr (hdrinf *)    Properly configured hdrinf struct\n  @param  rpm (ringparms *) Properly configured ringparms struct\n  @param  fit (fitparms *)  Properly configured fitparms struct\n  @return (success) int writeasctable: 1\n          (error)   0\n*/\n/* ------------------------------------------------------------ */\nstatic int writebigasctable(startinf *startinfv, loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit);\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static int coolgal(startinf *startinfv, loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit)\n  @brief Produces a 3d fits image of the model.\n\n  Prompts the user for a name (hidden) of an output cube. This will be a 3d image of the galaxy. As a smoothing value the largest hpbw is used in all three directions. This function will deallocate and reallocate the model and the original cube, such that this function should be called last before the program is being left. The extension of the output cube in the third dimension is the largest dimension in x-y. \n\n  @param  startinfv (startinf *)  Properly configured startinf struct\n  @param  log (loginf *)    Properly configured loginf struct\n  @param  hdr (hdrinf *)    Properly configured hdrinf struct\n  @param  rpm (ringparms *) Properly configured ringparms struct\n  @param  fit (fitparms *)  Properly configured fitparms struct\n  @return (success) int coolgal: 1\n          (error)   0\n*/\n/* ------------------------------------------------------------ */\nstatic int coolgal(startinf *startinfv, loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit);\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static qfits_header *makecoolhdr(hdrinf *hdr, double beamsizeindeg)\n  @brief Produces a header struct for coolgal output\n\n  Produces a qfits_header object suitable for the coolgal output.\n\n  @param  hdr (hdrinf *)           Properly configured hdrinf struct\n  @param  beamsizeindeg (double *) 1d beam size in degrees\n\n  @return (success) qfits_header *makecoolhdr: The properly configured header\n          (error)   NULL\n*/\n/* ------------------------------------------------------------ */\nstatic qfits_header *makecoolhdr(hdrinf *hdr, double beamsizeindeg);\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static int makecoolpoints(Cube *cube, hdrinf *hdr, ringparms *rpm, fitparms *fit)\n  @brief Makes a 3d pointsource model and packs in on cube\n\n  @param cube (Cube *)      The cube onto which the model is gridded\n  @param hdr  (hdrinf *)    Properly configured hdrinf struct\n  @param rpm  (ringparms *) Properly configured ringparms struct\n  @param rpm  (fitparms *)  Properly configured fitparms struct\n  @return (success) int makecoolpoints: 1\n          (error)   0\n*/\n/* ------------------------------------------------------------ */\nstatic int makecoolpoints(Cube *cube, hdrinf *hdr, ringparms *rpm, fitparms *fit);\n\n  \n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void tirout_a(simparse_scn_arel **arel, FILE *stream, char *keyword, char *input, fitparms *fit)\n  @brief Copies a part of the tirific input to a stream\n\n  @param stream  (FILE *) An open stream\n  @param keyword (char *) Name of the keyword as given in gipsy  \n  @param input   (char *) Allocated string of length VARYHSTRELES (including terminating '\\0')\n  @return tirout_a (success) 0\n                   (error) 1\n*/ \n/* ------------------------------------------------------------ */\nstatic int tirout_a(simparse_scn_arel **arel, FILE *stream, char *keyword);\n\n  \n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n@fn static int tirout(startinf *startinfv, loginf *log, ringparms *rpm, fitparms *fit, int nrplts)\n  @brief Produces one or two tirific logfiles containing the results\n\n  @param startifv    (startinf *)    Properly configured startinf struct\n  @param log    (loginf *)    Properly configured loginf struct\n  @param rpm    (ringparms *) Properly configured ringparms struct\n  @param fit    (fitparms *)  Properly configured fitparms struct\n  @param nrplts (int)         Number of plots as inquired with graphout()\n  @return (success) int tirout: 1\n          (error)   0\n*/\n/* ------------------------------------------------------------ */\nstatic int tirout(startinf *startinfv, loginf *log, ringparms *rpm, fitparms *fit, int nrplts);\n\n  \n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n@fn static int progressout(startinf *startinfv, char *message)\n  @brief Produces a file containing only the message\n\n  Kamphuis addition\n\n  @param startifv    (startinf *)    Properly configured startinf struct\n  @param message    (char *)\n  @return (success) int progressout: 1\n          (error)   0\n*/\n/* ------------------------------------------------------------ */\nstatic int progressout(startinf *startinfv, char *message);  \n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n@fn static int progressfinished(startinf *startinfv)\n  @brief Appends a message to the progress file at the end of the fitting procedure.\n\n  Kamphuis addition\n\n  @param startifv    (startinf *)    Properly configured startinf struct\n  @return (success) int tirout: 1\n          (error)   0\n*/\n/* ------------------------------------------------------------ */\nstatic int progressfinished(startinf *startinfv);  \n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static int histout(ringparms *rpm)\n  @brief Produces the histogram output of tirific\n\n  @param rpm  (ringparms *) Properly configured ringparms struct\n  @return (success) int tirout: 1\n          (error)   0\n*/\n/* ------------------------------------------------------------ */\n/* static int histout(ringparms *rpm); */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static int rectout(loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit)\n  @brief Produces the rectify output of tirific\n\n  @param log  (loginf *)    Properly configured loginf struct\n  @param hdr  (hdrinf *)    Properly configured hdrinf struct\n  @param rpm  (ringparms *) Properly configured ringparms struct\n  @param fit    (fitparms *)  Properly configured fitparms struct\n  @return (success) int rectout: 1\n          (error)   0\n*/\n/* ------------------------------------------------------------ */\n/* static int rectout(loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit); */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void rectout_a(FILE *stream)\n  @brief Output of fixed stuff to a file\n\n  @param stream  (FILE *) An open stream\n  @return void\n*/\n/* ------------------------------------------------------------ */\n/* static void rectout_a(FILE *stream); */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void rectout_b(FILE *stream)\n  @brief Output of fixed stuff to a file\n\n  @param stream  (FILE *) An open stream\n  @return void\n*/\n/* ------------------------------------------------------------ */\n/* static void rectout_b(FILE *stream); */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static int tiltout(startinf *startinfv, loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit)\n  @brief Produces the tiltogram output of tirific\n\n  @param startinfv  (startinf *)    Properly configured startinf struct\n  @param log  (loginf *)    Properly configured loginf struct\n  @param hdr  (hdrinf *)    Properly configured hdrinf struct\n  @param rpm  (ringparms *) Properly configured ringparms struct\n  @param fit  (fitparms *)  Properly configured fitparms struct\n  @return (success) int tiltout: 1\n          (error)   0\n*/\n/* ------------------------------------------------------------ */\nstatic int tiltout(startinf *startinfv, loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static int briggsout(startinf *startinfv, loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit)\n  @brief Produces a tip-lon diagram\n\n  @param startinfv  (startinf *)    Properly configured startinf struct\n  @param log  (loginf *)    Properly configured loginf struct\n  @param hdr  (hdrinf *)    Properly configured hdrinf struct\n  @param rpm  (ringparms *) Properly configured ringparms struct\n  @param fit  (fitparms *)  Properly configured fitparms struct\n  @return (success) int graphout: 1\n          (error)   0\n*/\n/* ------------------------------------------------------------ */\nstatic int briggsout(startinf *startinfv, loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static int graphout(startinf *startinfv, loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit)\n  @brief Produces the graphics output of tirific\n\n  @param startinfv  (startinf *)    Properly configured startinf struct\n  @param log  (loginf *)    Properly configured loginf struct\n  @param hdr  (hdrinf *)    Properly configured hdrinf struct\n  @param rpm  (ringparms *) Properly configured ringparms struct\n  @param fit  (fitparms *)  Properly configured fitparms struct\n  @return (success) int graphout: 1\n          (error)   0\n*/\n/* ------------------------------------------------------------ */\nstatic int graphout(startinf *startinfv, loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static int get_graphnr(char *string, int ndisks)\n  @brief Identifies a graphics output number\n\n  @param string (char *) String to identify\n   @param ndisks (int)    Number of disks\n\n  @return (success) int get_graphnr: Number of the graphics number as defined by _GRAPHNR plus NPARAMS\n          (error)   0\n*/\n/* ------------------------------------------------------------ */\nstatic int get_graphnr(char *string, int ndisks);\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void gr_fillscaling(loginf *log, hdrinf *hdr, int ident, float *scale, float *zero, int ndisks)\n  @brief Returns the scale for one unit to the alternative unit\n\n  The plot output of tirific imposes two axis descriptions on the\n  plots. The scales are connected via valright =\n  scale*valleft+zero. This function returns these values.\n\n  @param log   (loginf *) Properly configured loginf struct\n  @param hdr  (hdrinf *)    Properly configured hdrinf struct\n  @param ident (int)      Identification as output of ftstab_gtitln_ or get_graphnr\n  @param scale (float *)  The scale from left hand border to right hand border of a plot (output)\n   @param scale (float *) The zero from left hand border to right hand border of a plot (output)\n   @param ndisks (int)    Number of disks\n \n  @return (success) int get_graphnr: Number of the graphics number as defined by _GRAPHNR plus NPARAMS\n          (error)   0\n*/\n/* ------------------------------------------------------------ */\nstatic void gr_fillscaling(loginf *log, hdrinf *hdr, int ident, float *scale, float *zero, int ndisks);\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void gr_fillaxis(int ident, char *string, int ndisks)\n  @brief Returns an axis descriptor string suitable for the use in the pgp module\n\n  It is no error to pass NULL.\n\n  @param ident  (int)    Identification as output of ftstab_gtitln_ or get_graphnr\n  @param string (char *) String to fill (At least characters) or NULL\n   @param ndisks (int)    Number of disks\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void gr_fillaxis(int ident, char *string, int ndisks);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void gr_fillunit(int ident, char *string, int ndisks)\n  @brief Returns an unit string suitable for the use in the pgp module\n\n  It is no error to pass NULL.\n\n  @param ident  (int)    Identification as output of ftstab_gtitln_ or get_graphnr\n  @param string (char *) String to fill (At least characters) or NULL\n   @param ndisks (int)    Number of disks\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void gr_fillunit(int ident, char *string, int ndisks);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void gr_fillaltunit(int ident, char *string, int ndisks)\n  @brief Returns an alternative unit string suitable for the use in the pgp module\n\n  It is no error to pass NULL.\n\n  @param ident  (int)    Identification as output of ftstab_gtitln_ or get_graphnr\n  @param string (char *) String to fill (At least characters) or NULL\n   @param ndisks (int)    Number of disks\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void gr_fillaltunit(int ident, char *string, int ndisks);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void gr_filllegend(int ident, char *string, int ndisks)\n  @brief Returns a legend string suitable for the use in the pgp module\n\n  It is no error to pass NULL.\n\n  @param ident  (int)    Identification as output of ftstab_gtitln_ or get_graphnr\n  @param string (char *) String to fill (At least characters) or NULL\n  @param ndisks (int)             Number of disks\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void gr_filllegend(int ident, char *string, int ndisks);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static int fillgrapharray(startinf *startinfv, hdrinf *hdr, ringparms *rpm, decomp_inlist *index, int ident, float *array, float *larray, int ndisks)\n  @brief Fills two arrays for graphics use\n\n  The arrays array and larray are filled with the values contained in\n  rpm -> par and rpm -> modpar according to the parameter\n  required. par and modpar should contain the values in user\n  units. The parameter is decoded via an integer ident as returned by\n  get_graphident(). array and larray should be large enough.\n\n  @param startinfv    (startinf *)        Properly configured startinf struct\n  @param hdr    (hdrinf *)        Properly configured hdrinf struct\n  @param rpm    (ringparms *)     Properly configured rinparms struct\n  @param index  (decomp_inlist *) Index list as defined in simparse\n  @param ident  (int)             Identity of the value asked for as given by get_graphident()\n  @param array  (float *)         Array that contains the ring parameters\n  @param errarr\n  @param larray (float *)         Array containing the subring parameters\n  @param ndisks (int)             Number of disks\n  \n  @return (success) 1\n          (error)   0\n*/\n/* ------------------------------------------------------------ */\nstatic int fillgrapharray(startinf *startinfv, hdrinf *hdr, ringparms *rpm, int ident, float *array, float *larray, int ndisks);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static int gr_deleteindexed(int nur, int ident, float *xarray, float *yarray, float *yerrarray, decomp_inlist *index, int ndisks);\n)\n  @brief Deletes indexed points from three arrays\n\n  Uses an index list as defined in simparse to identify indexed\n  parameters in xarray, yarray, and yerrarray and deletes them. The\n  arrays are not reallocated, but all parameters are shift towards a\n  lower index if a data point is on the index. Returns the number of\n  points that are not on the index.\n\n  @param nur       (int)             Number of rings\n  @param ident     (int)             Identity of the parameter asked for as returned by get_graphident()\n  @param xarray    (float *)         Array, x-axis\n  @param yarray    (float *)         Array, y-axis\n  @param yerrarray (float *)         Array, errors\n  @param index     (decomp_inlist *) index list as defined in simparse\n  @param ndisks (int)    Number of disks\n\n  @return int gr_deleteindexed: number of parameters not on the index\n*/\n/* ------------------------------------------------------------ */\nstatic int gr_deleteindexed(int nur, int ident, float *xarray, float *yarray, float *yerrarray, decomp_inlist *index, int ndisks);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static int get_graphident(char *string, char *axis, char *unit, char *altunit, char *legend, int ndisks)\n  @brief Returns the identifyer of a graphics output\n\n  The function returns the identifyer of a graphics output identifyer. The value is not negative if the string input is identified with a variable parameter, or with a valid other graphics output keystring. In case of a variable parameter identifyer, this is identical with the RADI, etc identifyer, otherways with the NPARAMS+WANGLE_GRAPHNR, ... . At the same time the strings axis unit and legend are filled with appropriate values to produce an output with the pgp module. If the value of axis, unit, and legend are NULL, this is no error. If, however, one of those is not NULL, the strings must have at least a minimum length as given below. \n\n  @param string  (char *) Input string that should be scanned\n  @param axis    (char *) Output, axis descriptor string (at least 4 characters)\n  @param unit    (char *) Output, unit string (at least 30 characters)\n  @param altunit (char *) Output, Alternative unit string to the right (top) axis (at least 30 characters)\n  @param legend  (char *) Output, legend string (at least 80 characters)\n  @param ndisks  (int)    Input, number of disks\n\n  @return (success) int get_graphident: Identification for a graphics output\n          (error)   -1 In case of an invalid string\n*/\n/* ------------------------------------------------------------ */\nstatic int get_graphident(char *string, char *axis, char *unit, char *altunit, char *legend, int ndisks);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static int renzo(startinf *startinfv, loginf *log, hdrinf *hdr, ringparms *rpm)\n  @brief Produces a renzogram with the rings\n\n  @param startinfv  (startinf *)    Properly configured startinf struct\n  @param hdr  (hdrinf *)    Properly configured hdrinf struct\n  @param rpm  (ringparms *) Properly configured ringparms struct\n  @return (success) int renzo: 0\n          (error)   1\n*/\n/* ------------------------------------------------------------ */\nstatic int renzo(startinf *startinfv, loginf *log, hdrinf *hdr, ringparms *rpm);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static qfits_header *makerenzohdr(hdrinf *hdr, int planes, int refine)\n  @brief Produces a header struct for renzogram output\n\n  Produces a qfits_header object suitable for the renzogram output.\n\n  @param  hdr    (hdrinf *) Properly configured hdrinf struct\n  @param  planes (int)      Number of planes\n  @param  refine (int)      How many pixels in the outcube fit in one pixel of the incube.\n\n  @return (success) qfits_header *makecoolhdr: The properly configured header\n          (error)   NULL\n*/\n/* ------------------------------------------------------------ */\nstatic qfits_header *makerenzohdr(hdrinf *hdr, int planes, int refine);\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static int destroy_inf_sdis(inf_sdis *int_sdisv)\n  @brief deallocates an inf_sdis struct\n\n  @param  int_sdisv (hdrinf *) sdis struct\n\n  @return (success) 0\n          (error)   1\n*/\n/* ------------------------------------------------------------ */\nstatic int destroy_inf_sdis(inf_sdis *int_sdisv);\nstatic int destroy_inf_vrad(inf_vrad *int_vradv);\nstatic int destroy_inf_vver(inf_vver *int_vverv);\nstatic int destroy_inf_dvro(inf_dvro *int_dvrov);\nstatic int destroy_inf_dvra(inf_dvra *int_dvrav);\nstatic int destroy_inf_dvve(inf_dvve *int_dvvev);\nstatic int destroy_inf_vm0(inf_vm0 *int_vm0v);\nstatic int destroy_inf_vm1(inf_vm1 *int_vm1v);\nstatic int destroy_inf_vm2(inf_vm2 *int_vm2v);\nstatic int destroy_inf_vm3(inf_vm3 *int_vm3v);\nstatic int destroy_inf_vm4(inf_vm4 *int_vm4v);\nstatic int destroy_inf_ra1(inf_ra1 *int_ra1v);\nstatic int destroy_inf_ra2(inf_ra2 *int_ra2v);\nstatic int destroy_inf_ra3(inf_ra3 *int_ra3v);\nstatic int destroy_inf_ra4(inf_ra4 *int_ra4v);\nstatic int destroy_inf_ro1(inf_ro1 *int_ro1v);\nstatic int destroy_inf_ro2(inf_ro2 *int_ro2v);\nstatic int destroy_inf_ro3(inf_ro3 *int_ro3v);\nstatic int destroy_inf_ro4(inf_ro4 *int_ro4v);\nstatic int destroy_inf_wm0(inf_wm0 *int_wm0v);\nstatic int destroy_inf_wm1(inf_wm1 *int_wm1v);\nstatic int destroy_inf_wm2(inf_wm2 *int_wm2v);\nstatic int destroy_inf_wm3(inf_wm3 *int_wm3v);\nstatic int destroy_inf_wm4(inf_wm4 *int_wm4v);\nstatic int destroy_inf_ls0 (inf_ls0  *int_ls0v);\nstatic int destroy_inf_lc0 (inf_lc0  *int_lc0v);\nstatic int destroy_inf_smi (inf_smi  *inf_smiv);\nstatic int destroy_inf_gau (inf_gau  *inf_gauv);\nstatic int destroy_inf_azi (inf_azi  *inf_gauv);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static inf_sdis *create_inf_sdis(void)\n  @brief Allocates an sdis struct and substructures\n\n  @param  void\n\n  @return (success) pointer to inf_sdis struct\n          (error)   NULL\n*/\n/* ------------------------------------------------------------ */\nstatic inf_sdis *create_inf_sdis(void);\nstatic inf_vrad *create_inf_vrad(void);\nstatic inf_vver *create_inf_vver(void);\nstatic inf_dvro *create_inf_dvro(void);\nstatic inf_dvra *create_inf_dvra(void);\nstatic inf_dvve *create_inf_dvve(void);\nstatic inf_vm0 *create_inf_vm0(void);\nstatic inf_vm1 *create_inf_vm1(void);\nstatic inf_vm2 *create_inf_vm2(void);\nstatic inf_vm3 *create_inf_vm3(void);\nstatic inf_vm4 *create_inf_vm4(void);\nstatic inf_ra1 *create_inf_ra1(void);\nstatic inf_ra2 *create_inf_ra2(void);\nstatic inf_ra3 *create_inf_ra3(void);\nstatic inf_ra4 *create_inf_ra4(void);\nstatic inf_ro1 *create_inf_ro1(void);\nstatic inf_ro2 *create_inf_ro2(void);\nstatic inf_ro3 *create_inf_ro3(void);\nstatic inf_ro4 *create_inf_ro4(void);\nstatic inf_wm1 *create_inf_wm1(void);\nstatic inf_wm0 *create_inf_wm0(void);\nstatic inf_wm2 *create_inf_wm2(void);\nstatic inf_wm3 *create_inf_wm3(void);\nstatic inf_wm4 *create_inf_wm4(void);\nstatic inf_ls0  *create_inf_ls0 (void);\nstatic inf_lc0  *create_inf_lc0 (void);\nstatic inf_smi *create_inf_smi (void);\nstatic inf_gau *create_inf_gau (void);\nstatic inf_azi *create_inf_azi (void);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static int chkb_zero(ringparms *rpm, fitparms *fit, int ident)\n  @brief check if the function should be activated\n\n  Basically checks if the parameter with the name ident is nonzero in the input and if it is fitted.\n\n  @param rpm   (ringparms *) Properly configured ringparms struct\n  @param fit   (ringparms *) Properly configured fitparms struct\n  @param ident (int *)       identification (PXXX)\n\n  @return 0: activate function (either nonzero or fitted)\n          1: do not activate function\n*/\n/* ------------------------------------------------------------ */\nstatic int chkb_zero(ringparms *rpm, fitparms *fit, int ident);\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static int chkb_val(ringparms *rpm, fitparms *fit, int ident, double val)\n  @brief check if the function should be activated\n\n  Basically checks if the parameter with the name ident is not val in the input and if it is fitted.\n\n  @param rpm   (ringparms *) Properly configured ringparms struct\n  @param fit   (ringparms *) Properly configured fitparms struct\n  @param ident (int *)       identification (PXXX)\n  @param val   (double *)    The value that every parameter should have\n\n  @return 0: activate function (either non-90 or fitted)\n          1: do not activate function\n*/\n/* ------------------------------------------------------------ */\nstatic int chkb_val(ringparms *rpm, fitparms *fit, int ident, double val);\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static int chkb_sdis(ringparms *rpm, fitparms *fit)\n  @brief Optionally allocates and puts correct switches in the sdis struct\n\n  Basically checks in which way the ring-dependent dispersion is taken\n  into account, allocates (or doesn't allocate) structures and sets\n  the correct function pointers. If the dispersion is 0 throughout and\n  is not fitted, no random component is added to the velocity of point\n  sources (otherways, a random component is calculated, but it is 0\n  anyway).\n\n  @param rpm  (ringparms *) Properly configured ringparms struct\n  @param fit  (ringparms *) Properly configured fitparms struct\n\n  @return (success) 0\n          (error)   1: memory problems\n*/\n/* ------------------------------------------------------------ */\nstatic int chkb_sdis(ringparms *rpm, fitparms *fit);\nstatic int chkb_vrad(ringparms *rpm, fitparms *fit);\nstatic int chkb_vver(ringparms *rpm, fitparms *fit);\nstatic int chkb_dvro(ringparms *rpm, fitparms *fit);\nstatic int chkb_dvra(ringparms *rpm, fitparms *fit);\nstatic int chkb_dvve(ringparms *rpm, fitparms *fit);\nstatic int chkb_vm0 (ringparms *rpm, fitparms *fit);\nstatic int chkb_vm1(ringparms *rpm, fitparms *fit);\nstatic int chkb_vm2(ringparms *rpm, fitparms *fit);\nstatic int chkb_vm3(ringparms *rpm, fitparms *fit);\nstatic int chkb_vm4(ringparms *rpm, fitparms *fit);\nstatic int chkb_ra1(ringparms *rpm, fitparms *fit);\nstatic int chkb_ra2(ringparms *rpm, fitparms *fit);\nstatic int chkb_ra3(ringparms *rpm, fitparms *fit);\nstatic int chkb_ra4(ringparms *rpm, fitparms *fit);\nstatic int chkb_ro1(ringparms *rpm, fitparms *fit);\nstatic int chkb_ro2(ringparms *rpm, fitparms *fit);\nstatic int chkb_ro3(ringparms *rpm, fitparms *fit);\nstatic int chkb_ro4(ringparms *rpm, fitparms *fit);\nstatic int chkb_wm0 (ringparms *rpm, fitparms *fit);\nstatic int chkb_wm1(ringparms *rpm, fitparms *fit);\nstatic int chkb_wm2(ringparms *rpm, fitparms *fit);\nstatic int chkb_wm3(ringparms *rpm, fitparms *fit);\nstatic int chkb_wm4(ringparms *rpm, fitparms *fit);\nstatic int chkb_ls0 (ringparms *rpm, fitparms *fit);\nstatic int chkb_lc0 (ringparms *rpm, fitparms *fit);\nstatic int chkb_smi (ringparms *rpm, fitparms *fit);\nstatic int chkb_gau (ringparms *rpm, fitparms *fit);\nstatic int chkb_azi (ringparms *rpm, fitparms *fit);\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void rndmf_init_sdis_pas(ringparms *rpm, int srnr, int disk)\n  @brief Initialises the rng internal to the calulation of sdis\n\n  @param rpm  (void *)   properly allocated ringparms struct\n  @param srnr (int)      sub-ring number \n  @param disk    (int)         disk number\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void rndmf_init_sdis_act(void *rpm, int srnr, int disk);\nstatic void rndmf_init_gau_act(void *rpm, int srnr, int i, int disk);\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void rndmf_init_sdis_pas(void *rpm, int srnr, int disk)\n  @brief dummy function doing nothing instead of rndmf_init_sdis_act\n\n  @param rpm  (void *)   meaningless\n  @param srnr (int)      meaningless \n  @param disk    (int)         disk number\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void rndmf_init_sdis_pas(void *rpm, int srnr, int disk);\nstatic void rndmf_init_gau_pas(void *rpm, int srnr, int i, int disk);\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void chclfl_sdis_act(void *rpm, int srnr, int disk)\n  @brief Change the cloud flux and the cloud numbers depending on the number of subrings\n\n  @param rpm  (void *)   properly configured ringparms struct, casted to void\n  @param srnr (int)      subring number\n  @param disk    (int)         disk number\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void chclfl_sdis_act(void *rpm, int srnr, int disk);\nstatic void chclfl_sdis_pas(void *rpm, int srnr, int disk);\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void pr_sdis_empty_act(void *rpm, int srnr, int disk)\n  @brief Use the random number generator instead of creating point sources\n\n  @param rpm  (void *)   properly configured ringparms struct, casted to void\n  @param srnr (int)      subring number\n  @param disk    (int)         disk number\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void pr_sdis_empty_act(void *rpm, int srnr, int disk);\nstatic void pr_sdis_empty_pas(void *rpm, int srnr, int disk);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void pr_sdis_repeater_act(void *rpm, int srnr, int disk)\n  @brief Repeat a sequence of changing the velocity and gridding\n\n  @param rpm     (void *)   properly configured ringparms struct, casted to void\n  @param pp,     (float *)  point source coordinates\n  @param vold    (float)    old velocity of point source\n  @param srnr    (int)      subring number\n  @param hdr     (hdrinf *) properly configured hdrinf struct\n  @param j       (long *)   point source number\n  @param signum  (int)      signum of flux of point source\n  @param npoints (long *)   number of points\n  @param disk    (int)         disk number\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void sdis_repeater_act(void *rpm, float *pp, float vold, int srnr, hdrinf *hdr, long *j, int signum, long *npoints, int disk);\nstatic void sdis_repeater_pas(void *rpm, float *pp, float vold, int srnr, hdrinf *hdr, long *j, int signum, long *npoints, int disk);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void pr_sdis_act(ringparms *rpm, float v, int srnr, int disk)\n  @brief calculates random velocity component and adds it to the input\n\n  @param rpm     (ringparms *) Properly structured ringparms struct\n  @param v       (float *)     Original velocity on input, will be changed\n  @param vold    (float *)     Output: original velocity on input\n  @param srnr    (int)         sub-ring number\n  @param disk    (int)         disk number\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void pr_sdis_act(void *rpm, float *v, float *vold, int srnr, int disk);\nstatic void pr_vrad_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\n/* Note that the whole 6d point must be passed */\nstatic void pr_vver_act(void *rpm, float *point, int srnr, int disk);\nstatic void pr_dvro_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_dvra_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_dvve_act(void *rpm, float *v, int srnr, int disk);\nstatic void pr_dvro_act2(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_dvra_act2(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_dvve_act2(void *rpm, float *v, int srnr, int disk);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void gau_getcloudnumber_act(ringparms *rpm, int srnr, int number, int disk)\n  @brief returns a cloud number solving an integral\n\n  Gaussian spiral arm or bar, generating cloud number for Gaussian number\n\n  @param rpm     (ringparms *) Properly structured ringparms struct\n  @param srnr    (int)         sub-ring number\n  @param number  (int)         Number of arm\n  @param disk    (int)         disk number\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void gau_getcloudnumber_act(void *rpm, int srnr, int number, int disk);\n/* Dummy instead */\nstatic void gau_getcloudnumber_pas(void *rpm, int srnr, int number, int disk);\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void gau_getaz(ringparms *rpm, int pgaip, maths_rstrf *randstr, int pgaid, float *az, float *sinaz, float *cosaz, int srnr, int disk)\n  @brief returns an azimuth\n\n  Returns new azimuth of point source, for a given Gaussian\n\n  @param rpm     (ringparms *) Properly structured ringparms struct\n  @param pgaip   (int)         Number of parameter for the Gaussian phase, PGA1P, PGA2P, PGA3P, or PGA4P\n  @param randstr (maths_rstrf) Randum number generator struct, gau_inf -> randstr1/randstr2/randstr3/randstr4\n  @param pgaid   (int)         Number of parameter for the Gaussian dispersion, 0, 1, 2, or 3\n  @param az      (float *)     Output: azimuth\n  @param cosaz   (float *)     Output: cosine of azimuth\n  @param sinaz   (float *)     Output: sine of azimuth\n  @param srnr    (int)         sub-ring number\n  @param disk    (int)         disk number\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void gau_getaz(ringparms *rpm, int pgaip, maths_rstrf *randstr, int pgaid, float *az, float *sinaz, float *cosaz, int srnr, int disk);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void pr_vver_rota_act(void *rpm, float *vz, float *vz2, int srnr, int disk) \n  @brief Adds the cosine component when rotating about\n  inclination, in case that the vertical velocity is nonzero\n\n  @param rpm     (ringparms *) Properly structured ringparms struct\n  @param vz      (float *)     Original velocity on input, z component\n  @param vz2     (float *)     Original velocity on output, z-component, will be changed\n  @param srnr    (int)         sub-ring number\n  @param disk    (int)         disk number\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void pr_vver_rota_act(void *rpm, float *vz, float *vz2, int srnr, int disk);\nstatic void pr_vver_rota_pas(void *rpm, float *vz, float *vz2, int srnr, int disk);\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void srpr_vmi_pas(void *rpm, int srnr, int disk)\n  @brief dummy instead of pr_m1_act\n\n  @param rpm     (void *)  Properly structured ringparms struct\n  @param srnr    (int)     sub-ring number\n  @param disk    (int)     disk number\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void srpr_vmi_pas(void *rpm, int srnr, int disk);\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void srpr_wm1s_act(ringparms *rpm int srnr, int disk)\n  @brief calculates warp sin component and adds it to the subring\n\n  @param rpm     (ringparms *) Properly structured ringparms struct\n  @param srnr    (int)         sub-ring number\n  @param disk    (int)     disk number\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void srpr_wm1s_act(void *rpm, int srnr, int disk);\nstatic void srpr_wm2s_act(void *rpm, int srnr, int disk);\nstatic void srpr_wm3s_act(void *rpm, int srnr, int disk);\nstatic void srpr_wm4s_act(void *rpm, int srnr, int disk);\nstatic void srpr_wm1c_act(void *rpm, int srnr, int disk);\nstatic void srpr_wm2c_act(void *rpm, int srnr, int disk);\nstatic void srpr_wm3c_act(void *rpm, int srnr, int disk);\nstatic void srpr_wm4c_act(void *rpm, int srnr, int disk);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void srpr_wmi_pas(void *rpm, int srnr, int disk)\n  @brief dummy instead of pr_m1_act\n\n  @param rpm     (void *)  Properly structured ringparms struct\n  @param srnr    (int)     sub-ring number\n  @param disk    (int)     disk number\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void srpr_wmi_pas(void *rpm, int srnr, int disk);\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void srpr_vm1s_act(ringparms *rpm int srnr, int disk)\n  @brief calculates velocity sin component and adds it to the subring\n\n  @param rpm     (ringparms *) Properly structured ringparms struct\n  @param srnr    (int)         sub-ring number\n  @param disk    (int)     disk number\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void srpr_vm1s_act(void *rpm, int srnr, int disk);\nstatic void srpr_vm2s_act(void *rpm, int srnr, int disk);\nstatic void srpr_vm3s_act(void *rpm, int srnr, int disk);\nstatic void srpr_vm4s_act(void *rpm, int srnr, int disk);\nstatic void srpr_vm1c_act(void *rpm, int srnr, int disk);\nstatic void srpr_vm2c_act(void *rpm, int srnr, int disk);\nstatic void srpr_vm3c_act(void *rpm, int srnr, int disk);\nstatic void srpr_vm4c_act(void *rpm, int srnr, int disk);\n\nstatic void srpr_ra1s_act(void *rpm, int srnr, int disk);\nstatic void srpr_ra2s_act(void *rpm, int srnr, int disk);\nstatic void srpr_ra3s_act(void *rpm, int srnr, int disk);\nstatic void srpr_ra4s_act(void *rpm, int srnr, int disk);\nstatic void srpr_ra1c_act(void *rpm, int srnr, int disk);\nstatic void srpr_ra2c_act(void *rpm, int srnr, int disk);\nstatic void srpr_ra3c_act(void *rpm, int srnr, int disk);\nstatic void srpr_ra4c_act(void *rpm, int srnr, int disk);\n\nstatic void srpr_ro1s_act(void *rpm, int srnr, int disk);\nstatic void srpr_ro2s_act(void *rpm, int srnr, int disk);\nstatic void srpr_ro3s_act(void *rpm, int srnr, int disk);\nstatic void srpr_ro4s_act(void *rpm, int srnr, int disk);\nstatic void srpr_ro1c_act(void *rpm, int srnr, int disk);\nstatic void srpr_ro2c_act(void *rpm, int srnr, int disk);\nstatic void srpr_ro3c_act(void *rpm, int srnr, int disk);\nstatic void srpr_ro4c_act(void *rpm, int srnr, int disk);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void pr_vmi_pas(void *rpm, float v, int srnr, float sinaz, float cosaz, int disk)\n  @brief dummy instead of pr_vm1-4s/c_act\n\n  @param rpm     (void *)  Properly structured ringparms struct\n  @param v       (float *) Original velocity on input, will be changed\n  @param srnr    (int)     sub-ring number\n  @param sinaz   (float)   sine of the azimuth\n  @param cosaz   (float)   cosine of the azimuth\n  @param disk    (int)     disk number\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void pr_vmi_pas(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void pr_vm1s_act(ringparms *rpm, float v, int srnr, float sinaz, float cosaz, int disk)\n  @brief calculates s1 component and adds it to the input\n\n  @param rpm     (ringparms *) Properly structured ringparms struct\n  @param v       (float *)     Original velocity on input, will be changed\n  @param srnr    (int)         sub-ring number\n  @param sinaz   (float)   sine of the azimuth\n  @param cosaz   (float)   cosine of the azimuth\n  @param disk    (int)     disk number\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void pr_vm1s_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_vm2s_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_vm3s_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_vm4s_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_vm1c_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_vm2c_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_vm3c_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_vm4c_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_vm0_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\n\nstatic void pr_ra1s_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_ra2s_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_ra3s_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_ra4s_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_ra1c_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_ra2c_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_ra3c_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_ra4c_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\n\nstatic void pr_ro1s_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_ro2s_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_ro3s_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_ro4s_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_ro1c_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_ro2c_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_ro3c_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_ro4c_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void srpr_smi_pas(void *rpm, int srnr, int disk)\n  @brief dummy instead of pr_m1_act\n\n  @param rpm     (void *)  Properly structured ringparms struct\n  @param srnr    (int)     sub-ring number\n  @param disk    (int)     disk number\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void srpr_smi_pas(void *rpm, int srnr, int disk);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void srpr_sm1s_act(ringparms *rpm int srn, int diskr)\n  @brief calculates surface brightness sin component and adds it to the subring\n\n  @param rpm     (ringparms *) Properly structured ringparms struct\n  @param srnr    (int)         sub-ring number\n  @param disk    (int)     disk number\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void srpr_sm0b_act(void *rpm, int srnr, int disk);\nstatic void srpr_sm1s_act(void *rpm, int srnr, int disk);\nstatic void srpr_sm2s_act(void *rpm, int srnr, int disk);\nstatic void srpr_sm3s_act(void *rpm, int srnr, int disk);\nstatic void srpr_sm4s_act(void *rpm, int srnr, int disk);\nstatic void srpr_sm1c_act(void *rpm, int srnr, int disk);\nstatic void srpr_sm2c_act(void *rpm, int srnr, int disk);\nstatic void srpr_sm3c_act(void *rpm, int srnr, int disk);\nstatic void srpr_sm4c_act(void *rpm, int srnr, int disk);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void pr_smi_pas(void *rpm, float v, int srnr, float sinaz, float cosaz, int disk)\n  @brief dummy instead of pr_vm1-4s/c_act\n\n  @param rpm     (void *)  Properly structured ringparms struct\n  @param sbr     (float *) Original surface brightness on input, will not be changed\n  @param srnr    (int)     sub-ring number\n  @param sinaz   (float)   sine of the azimuth\n  @param cosaz   (float)   cosine of the azimuth\n  @param disk    (int)     disk number\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void pr_smi_pas(void *rpm, float *sbr, int srnr, float sinaz, float cosaz, int disk);\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void pr_sm0b_pas(void *rpm, float *sbr, int srnr, float sinaz, float cosaz, int disk)\n  @brief dummy instead of pr_sm0b_act(), replaces *sbr with 0.0\n\n  @param rpm     (void *)  Properly structured ringparms struct\n  @param sbr     (float *) Original surface brightness on input, will not be changed\n  @param srnr    (int)     sub-ring number\n  @param sinaz   (float)   sine of the azimuth\n  @param cosaz   (float)   cosine of the azimuth\n  @param disk    (int)     disk number\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void pr_sm0b_pas(void *rpm, float *sbr, int srnr, float sinaz, float cosaz, int disk);\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void pr_sm1s_act(ringparms *rpm, float *sbr, int srnr, float sinaz, float cosaz, int disk)\n  @brief calculates s1 component and adds it to the input\n\n  @param rpm     (ringparms *) Properly structured ringparms struct\n  @param sbr     (float *)     Original surface brightness on input, will be changed\n  @param srnr    (int)         sub-ring number\n  @param sinaz   (float)   sine of the azimuth\n  @param cosaz   (float)   cosine of the azimuth\n  @param disk    (int)     disk number\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void pr_sm0b_act(void *rpm, float *sbr, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_sm1s_act(void *rpm, float *sbr, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_sm2s_act(void *rpm, float *sbr, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_sm3s_act(void *rpm, float *sbr, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_sm4s_act(void *rpm, float *sbr, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_sm1c_act(void *rpm, float *sbr, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_sm2c_act(void *rpm, float *sbr, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_sm3c_act(void *rpm, float *sbr, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_sm4c_act(void *rpm, float *sbr, int srnr, float sinaz, float cosaz, int disk);\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void smi_sbrmax_act(void *rpm, int srnr, int disk)\n  @brief calculates the sum of absolute amplitudes of surface brightness modes and puts that number in the sbrmax variable of the subring structure\n\n  @param rpm     (ringparms *) Properly structured ringparms struct\n  @param srnr    (int)         sub-ring number\n  @param disk    (int)         disk number\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void smi_sbrmax_act(void *rpm, int srnr, int disk);\nstatic void smi_sbrmax_pas(void *rpm, int srnr, int disk);\n\n\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void smi_getaz_harm(void *rpm, float *az, float *cosaz, float *sinaz, int *signum, int srnr, int disk)\n  @brief returns an azimuth\n\n  If harmonics in the surface brightness are used, then the\n  distribution of point sources is not uniform. The function will take\n  care of a correct distribution of point sources returned.\n\n  @param rpm     (void *)      Properly structured ringparms struct, casted to void\n  @param cosaz   (float *)     Output: azimuth\n  @param cosaz   (float *)     Output: cosine of azimuth\n  @param sinaz   (float *)     Output: sine of azimuth\n  @param signum  (int *)       Output: signum of point source flux\n  @param srnr    (int)         sub-ring number\n  @param disk    (int)         disk number\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void smi_getaz_harm(void *rpm, float *az, float *cosaz, float *sinaz, int *signum, int srnr, int disk);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void smi_getaz_cons(void *rpm, float *az, float *cosaz, float *sinaz, int *signum, int srnr, int disk)\n  @brief returns an azimuth\n\n  Returns new azimuth of point source, without harmics\n\n  @param rpm     (void *)      Properly structured ringparms struct, casted to void\n  @param az   (float *)        Output: azimuth\n  @param cosaz   (float *)     Output: cosine of azimuth\n  @param sinaz   (float *)     Output: sine of azimuth\n  @param signum  (int *)       Output: signum of point source flux\n  @param srnr    (int)         sub-ring number\n  @param disk    (int)         disk number\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void smi_getaz_cons(void *rpm, float *az, float *cosaz, float *sinaz, int *signum, int srnr, int disk);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void smi_getcloudnumber_harm(ringparms *rpm, int srnr, int disk)\n  @brief returns a cloud number solving an integral\n\n  If harmonics in the surface brightness are used, then the\n  distribution of point sources is not uniform. In the case of\n  negative clouds, this function needs to be invoked to determine the\n  cloud number instead of the much simpler smi_getcloudnumber_norm\n\n  @param rpm     (ringparms *) Properly structured ringparms struct\n  @param srnr    (int)         sub-ring number\n  @param disk    (int)         disk number\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void smi_getcloudnumber_harm(void *rpm, int srnr, int disk);\nstatic void smi_getcloudnumber_norm(void *rpm, int srnr, int disk);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void rndmf_init_sdis_pas(ringparms *rpm, int srnr, int disk)\n  @brief Initialises the rng internal to the calulation of sdis\n\n  @param rpm  (void *)   properly allocated ringparms struct\n  @param srnr (int)      sub-ring number \n  @param disk (int)         disk number\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void rndmf_init_smi_act(void *rpm, int srnr, int disk);\nstatic void rndmf_init_smi_pas(void *rpm, int srnr, int disk);\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void srpr_gau_act(ringparms *rpm, int srnr, int number, int disk)\n  @brief calculates surface brightness Gaussian dispersion in rad and adds it to the ring\n\n  @param rpm     (ringparms *) Properly structured ringparms struct\n  @param srnr    (int)         sub-ring number\n  @param number  (int)         number of Gaussian component\n  @param disk (int)         disk number\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void srpr_gau_act(void *rpm, int srnr, int number, int disk);\nstatic void srpr_gau_pas(void *rpm, int srnr, int number, int disk);\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void srpr_azi_act(ringparms *rpm, int srnr, int number, int disk)\n  @brief calculates ranges for the exclusion from the model\n\n  @param rpm     (ringparms *) Properly structured ringparms struct\n  @param srnr    (int)         sub-ring number\n  @param number  (int)         number of segment\n  @param disk (int)         disk number\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void srpr_azi_act(void *rpm, int srnr, int number, int disk);\nstatic void srpr_azi_pas(void *rpm, int srnr, int number, int disk);\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void setoutrange_azi_act(int *outofrange)\n  @brief sets outofrange to 1\n\n  @param outofrnage (int *)       Output: outofrange changes to 1\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void setoutrange_azi_act(int *outofrange);\nstatic void setoutrange_azi_pas(int *outofrange);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void pr_azi_act(float *azi, float ranges[2][4], int *outofrange, int i)\n  @brief calculates ranges for the exclusion from the model\n\n  @param azi        (float *)     Azimuth\n  @param ranges     (float[2][4]) the ranges to check (these are 8 ranges)\n  @param outofrnage (int *)       Output: outofrange changes to 0 if the azimuth is in the range defined by ranges         \n  @param i          (int)         Sub-range to check 0 or 1\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void pr_azi_act(float *azi, float ranges[2][4], int *outofrange, int i);\nstatic void pr_azi_pas(float *azi, float ranges[2][4], int *outofrange, int i);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void srshape_azi_act(void *rpm, float *pp, float sinaz, float cosaz, int srnr, int outofrange, int disk)\n  @brief Shape the point source\n\n  Changes the coordinates of the pointsource using srshape, if\n  outofrange == 0, if outofrange == 1, pp[0] = -1 and nothing is done\n  except for stepping forward in the rngs. The passive version only\n  calls srshape.\n\n  @param rpm        (void *)  Properly structured ringparms struct\n  @param pp         (float *) Output: position of point source\n  @param sinaz      (float)   sine of the azimuth\n  @param cosaz      (float)   cosine of the azimuth\n  @param srnr       (int)     sub-ring number\n  @param outofrnage (int *)   outofrange 0 means do a normal shaping, 1 means do \"nothing\"         \n  @param disk (int)         disk number\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic int srshape_azi_act(void *rpm, float *pp, float sinaz, float cosaz, int srnr, int outofrange, int disk);\nstatic int srshape_azi_pas(void *rpm, float *pp, float sinaz, float cosaz, int srnr, int outofrange, int disk);\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void srshape_azi_act(void *rpm, int srnr, int outofrange, int signum)\n  @brief Shape the point source\n\n  Changes the coordinates of the pointsource using srshape, if\n  outofrange == 0, if outofrange == 1, pp[0] = -1 and nothing is done\n  except for stepping forward in the rngs. The passive version only\n  calls srshape.\n\n  @param rpm        (void *)  Properly structured ringparms struct\n  @param srnr       (int)     sub-ring number\n  @param outofrange (int)     outofrange 0 means do a normal shaping, 1 means do \"nothing\"         \n  @param signum     (int)     Dummy probably\n  @param disk (int)         disk number\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void corrp_azi_act(void *rpm, int srnr, int *outofrange, int signum);\nstatic void corrp_azi_pas(void *rpm, int srnr, int *outofrange, int signum);\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void pr_wmi_pas(void *rpm, float v, int srnr, float sinaz, float cosaz, int disk)\n  @brief dummy instead of pr_vm1-4s/c_act\n\n  @param rpm     (void *)  Properly structured ringparms struct\n  @param z       (float *) Original heigt on input, will be changed\n  @param srnr    (int)     sub-ring number\n  @param sinaz   (float)   sine of the azimuth\n  @param cosaz   (float)   cosine of the azimuth\n  @param disk (int)         disk number\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void pr_wmi_pas(void *rpm, float *z, int srnr, float sinaz, float cosaz, int disk);\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void pr_wm0_act(ringparms *rpm, float *z, int srnr, float sinaz, float cosaz, int disk)\n  @brief calculates m0 component and adds it to the input\n\n  @param rpm     (void *)  Properly structured ringparms struct\n  @param z       (float *) Original height above plane, will be changed\n  @param srnr    (int)     sub-ring number\n  @param sinaz   (float)   sine of the azimuth\n  @param cosaz   (float)   cosine of the azimuth\n  @param disk (int)         disk number\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic  void pr_wm0_act(void *rpm, float *z, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_wm1s_act(void *rpm, float *z, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_wm2s_act(void *rpm, float *z, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_wm3s_act(void *rpm, float *z, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_wm4s_act(void *rpm, float *z, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_wm1c_act(void *rpm, float *z, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_wm2c_act(void *rpm, float *z, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_wm3c_act(void *rpm, float *z, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_wm4c_act(void *rpm, float *z, int srnr, float sinaz, float cosaz, int disk);\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void pr_ls0_pas(void *rpm, float *x, int srnr, float sinaz, float cosaz, int disk)\n  @brief dummy instead of pr_ls0_act\n\n  @param rpm     (void *)  Properly structured ringparms struct\n  @param x       (float *) Original height above plane, will be changed\n  @param srnr    (int)     sub-ring number\n  @param sinaz   (float)   sine of the azimuth\n  @param cosaz   (float)   cosine of the azimuth\n  @param disk (int)         disk number\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void pr_ls0_pas(void *rpm, float *x, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_lc0_pas(void *rpm, float *x, int srnr, float sinaz, float cosaz, int disk);\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void pr_ws1_act(ringparms *rpm, float *x, int srnr, float sinaz, float cosaz, int disk)\n  @brief calculates shift component and adds it to the input\n\n  @param rpm     (void *)  Properly structured ringparms struct\n  @param x       (float *) Original height above plane, will be changed\n  @param srnr    (int)     sub-ring number\n  @param sinaz   (float)   sine of the azimuth\n  @param cosaz   (float)   cosine of the azimuth\n  @param disk (int)         disk number\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void pr_ls0_act(void *rpm, float *x, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_lc0_act(void *rpm, float *x, int srnr, float sinaz, float cosaz, int disk);\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void pr_sdis_pas(void *rpm, float v, int srnr, int disk)\n  @brief dummy instead of pr_sdis_act\n\n  @param rpm     (void *)  Properly structured ringparms struct\n  @param v       (float *) Original velocity on input, will be changed\n  @param vold    (float *)     Output: original velocity on input\n  @param srnr    (int)     sub-ring number\n  @param disk (int)         disk number\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void pr_sdis_pas(void *rpm, float *v, float *vold, int srnr, int disk);\nstatic void pr_vrad_pas(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk);\n/* Note that the whole 6d point must be passed */\nstatic void pr_vver_pas(void *rpm, float *point, int srnr, int disk);\nstatic void pr_dvro_pas(void *rpm, float *point, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_dvra_pas(void *rpm, float *point, int srnr, float sinaz, float cosaz, int disk);\nstatic void pr_dvve_pas(void *rpm, float *point, int srnr, int disk);\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static int activateftstab(startinf *startinfv, loginf *log, ringparms *rpm)\n  @brief Starts up the ftstab machinery\n\n  This sets up the ftstab module to work writing to (or appending to\n  the existent) the logfile. It sets the logfile -> logpres parameter\n  to 0 if the logfile is present, to 1 otherwise. An error is returned\n  if the user interrupts the progress, the logfile is not a fits\n  table, or if a logfile has been requested, but couldn't be\n  opened. If no logfile is requested, no error is returned\n\n  @param log     (loginf *)  Properly structured loginf struct\n  @param rpm     (ringparms *)  Properly allocated ringparms struct\n\n  @return int activateftstab: 0 (success)\n                              >0 (error)\n*/\n/* ------------------------------------------------------------ */\nstatic int activateftstab(startinf *startinfv, loginf *log, ringparms *rpm);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static int int tir_get_grid(loginf *log, ringparms *rpm, double *array)\n  @brief Copy log -> grid to array\n\n  The arrays must have a dimension of nur*NPARAMS+nur*NDPARAMS+5\n\n  @param log     (loginf *)  Properly structured loginf struct\n  @param rpm     (ringparms *)  Properly structured ringparms struct\n  @param array   (double *)  Array of dimension nur*NPARAMS+nur*NDPARAMS+5\n\n  @return int tir_get_grid: 0 (success)\n                              >0 (error)\n*/\n/* ------------------------------------------------------------ */\nstatic int tir_get_grid(loginf *log, ringparms *rpm, double *array);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static double tir_get_colgrid(loginf *log, ringparms *rpm, int i)\n  @brief Returns log -> grid[i-1]\n\n  The arrays must have a dimension of nur*NPARAMS+nur*NDPARAMS+5\n\n  @param log     (loginf *)  Properly structured loginf struct\n  @param rpm     (ringparms *)  Properly structured ringparms struct\n  @param i   (int *)  column number, starting at 1\n\n  @return double tir_get_colgrid\n*/\n/* ------------------------------------------------------------ */\nstatic double tir_get_colgrd(loginf *log, ringparms *rpm, int i);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static double tir_get_colrad(loginf *log, ringparms *rpm, int i)\n  @brief Returns log -> radius[i-1]\n\n  The arrays must have a dimension of nur*NPARAMS+nur*NDPARAMS+5\n\n  @param log     (loginf *)  Properly structured loginf struct\n  @param rpm     (ringparms *)  Properly structured ringparms struct\n  @param i   (int *)  column number, starting at 1\n\n  @return double tir_get_colrad\n*/\n/* ------------------------------------------------------------ */\nstatic double tir_get_colrad(loginf *log, ringparms *rpm, int i);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static int int tir_get_radius(loginf *log, ringparms *rpm, double *array)\n  @brief Copy log -> radius to array\n\n  The arrays must have a dimension of nur*NPARAMS+nur*NDPARAMS+5\n\n  @param log     (loginf *)  Properly structured loginf struct\n  @param rpm     (ringparms *)  Properly structured ringparms struct\n  @param array   (double *)  Array of dimension nur*NPARAMS+nur*NDPARAMS+5\n\n  @return int tir_get_radius: 0 (success)\n                              >0 (error)\n*/\n/* ------------------------------------------------------------ */\nstatic int tir_get_radius(loginf *log, ringparms *rpm, double *array);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static int int tir_put_register(loginf *log, ringparms *rpm, double *array)\n  @brief Copy array to log -> regist\n\n  The arrays must have a dimension of nur*NPARAMS+nur*NDPARAMS+5\n\n  @param log     (loginf *)  Properly structured loginf struct\n  @param rpm     (ringparms *)  Properly structured ringparms struct\n  @param array   (double *)  Array of dimension nur*NPARAMS+nur*NDPARAMS+5\n\n  @return int tir_get_radius: 0 (success)\n                              >0 (error)\n*/\n/* ------------------------------------------------------------ */\nstatic int tir_put_register(loginf *log, ringparms *rpm, double *array);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static int int tir_get_register(loginf *log, ringparms *rpm, double *array)\n  @brief Copy log -> regist to array\n\n  The arrays must have a dimension of nur*NPARAMS+nur*NDPARAMS+5\n\n  @param log     (loginf *)  Properly structured loginf struct\n  @param rpm     (ringparms *)  Properly structured ringparms struct\n  @param array   (double *)  Array of dimension nur*NPARAMS+nur*NDPARAMS+5\n\n  @return int tir_get_radius: 0 (success)\n                              >0 (error)\n*/\n/* ------------------------------------------------------------ */\nstatic int tir_get_register(loginf *log, ringparms *rpm, double *array);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static int tir_fillhd(loginf *log, int i, double radius, double grid)\n  @brief Fill the i-1 th position of log -> grid and log -> radius with grid and radius\n\n  @param log      (loginf *)  Properly structured loginf struct\n  @param i        (int)       Properly structured ringparms struct\n  @param radius   (double)  Array of dimension nur*NPARAMS+nur*NDPARAMS+5\n  @param grid     (double)  Array of dimension nur*NPARAMS+nur*NDPARAMS+5\n\n  @return int tir_get_radius: 0 (success)\n                              >0 (error)\n*/\n/* ------------------------------------------------------------ */\nstatic int tir_fillhd(loginf *log, int i, double radius, double grid);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static int dec_fill(ringparms *rpm, decomp_control *decomp_controlv)\n  @brief Fill a simparse decomp struct with parameter information\n\n  @param rpm                (ringparms) properly configured ringparms struct\n  @param decomp_controlv    (decomp_control *)  Allocated simparse decomp control structure \n\n  @return 0: success\n          1: memory problems\n*/\n/* ------------------------------------------------------------ */\nstatic int dec_fill(ringparms *rpm, decomp_control *decomp_controlv);\n\n#ifdef PBCORR\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void alloc_pbcfac_act(ringparms *rpm, int srnr, int disk)\n  @brief Allocate memory for primary beam factors\n\n  same function pas doesn't do anything.\n\n  @param rpm  (ringparms *)   properly allocated ringparms struct\n  @param srnr (int)      sub-ring number \n  @param disk (int)      disk number\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void alloc_pbcfac_act(ringparms *rpm, int srnr, int disk);\nstatic void alloc_pbcfac_pas(ringparms *rpm, int srnr, int disk);\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void dealloc_pbcfac_act(ringparms *rpm, int srnr, int disk)\n  @brief Deallocate memory for primary beam factors\n\n  same function pas doesn't do anything.\n\n  @param rpm  (ringparms *)   properly allocated ringparms struct\n  @param srnr (int)      sub-ring number \n  @param disk (int)      disk number\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void dealloc_pbcfac_act(ringparms *rpm, int srnr, int disk);\nstatic void dealloc_pbcfac_pas(ringparms *rpm, int srnr, int disk);\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void fill_pbcfac_act((ringparms *rpm, struct srd **sd, int disk, int srnr, long *pnr, int *grid)\n  @brief Fill the pbfac array with the right numbers\n\n  same function pas doesn't do anything.\n\n  @param hdr    (hdrinf *)                  properly allocated headerinf struct\n  @param sd     (struct srd *[ndisks])      sub-ring array \n  @param disk   (int)                       disk number\n  @param srnr   (int)                       sub-ring number\n  @param pnr    (long *)                      point number\n  @param grid   (int *)                     grid position\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void fill_pbcfac_act(hdrinf *hdr, struct srd **sd, int disk, int srnr, long *pnr, int *grid);\nstatic void fill_pbcfac_pas(hdrinf *hdr, struct srd **sd, int disk, int srnr, long *pnr, int *grid);\n\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void corr_pbcfac_act(struct srd **sd, int disk, int srnr, long pnr)\n  @brief Apply the pbfac array with the right numbers\n\n  same function pas doesn't do anything.\n\n  @param sd     (struct srd **)      sub-ring array \n  @param disk   (int)                disk number\n  @param srnr   (int)                sub-ring number\n  @param pnr    (long)               point number\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\n/* static void corr_pbcfac_act(struct srd *sd[ndisks], int disk, int srnr, long pnr); */\n/* static void corr_pbcfac_pas(struct srd *sd[ndisks], int disk, int srnr, long pnr); */\nstatic void corr_pbcfac_act(struct srd **sd, int disk, int srnr, long pnr);\nstatic void corr_pbcfac_pas(struct srd **sd, int disk, int srnr, long pnr);\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n  @fn static void chkb_pbcorr(hdrinf *hdr, ringparms *rpm)\n  @brief Link correct funtions for bpcorr\n\n  same function pas doesn't do anything.\n\n  @param hdr   (hdrinf *)    correctly allocated hdrinf struct\n  @param rpm   (ringparms *) correctly allocated ringparms struct\n\n  @return void\n*/\n/* ------------------------------------------------------------ */\nstatic void chkb_pbcorr(hdrinf *hdr, ringparms *rpm);\n\n#endif\n\n/*************/\n/* Addendums under construction */\n/*************/\n/* #include \"constr.h\" */\n/*************/\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static reg_cont *reg_cont_const(int nregs)\n   @brief Constructs a NULL-terminated array of n (empty) reg_containers\n\n   Constructs a NULL-terminated array of n (empty) reg_containers. The fc members are allocated.\n\n\n   @param  nregs (int)       number of single fc_containers\n\n   @return (success) reg_cont *reg_cont_const Allocated array of reg_containers\n           (error) NULL\n*/\n/* ------------------------------------------------------------ */\nstatic reg_cont **reg_cont_const(int nregs);\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static int reg_cont_destr(reg_cont **reg_contv)\n   @brief Constructs a NULL-terminated array of n (empty) reg_containers\n\n   Destructor of an array of pointers to regularisation containers as constructed with reg_cont_const().\n\n   @param  reg_contv (reg_cont) regularisaton container to be destroyed.\n\n   @return (success) reg_cont *reg_cont_const Allocated array of reg_containers\n           (error) NULL\n*/\n/* ------------------------------------------------------------ */\nstatic int reg_cont_destr(reg_cont **reg_contv);\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static reg_cont **reg_cont_get(startinf *startinfv, ringparms *rpm, fitparms *fit)\n   @brief Get the regularisation list from user input\n\n   Reads in the regularisation information from the input.\n\n   @param startinfv (startinf *)   A start descriptor struct, properly filled.\n   @param rpm (ringparms *)   A ring parameter descriptor struct, properly filled.\n   @param fit (fitparms *)    A fit parameter descriptor struct, properly filled.\n\n   @return (success) reg_cont **reg_cont_get regularisation struct\n           (error) 1: NULL memory problems\n*/\n/* ------------------------------------------------------------ */\nstatic reg_cont **reg_cont_get(startinf *startinfv, hdrinf *hdr, ringparms *rpm, fitparms *fit);\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/**\n   @fn static double reg_do(reg_cont **reg_contv, int loop, double chisquare)\n   @brief Change the chisquare penalising Fourier modes\n\n   For each entry in the reg_contv list, the vector reg_contv[i] ->\n   first that has been specified on input with the function\n   reg_cont_get() will be read as an input vector into reg_contv[i] ->\n   fc to then determine the ratio of the modes specified on\n   input. This is done in the following way (see fourat.h): \n\n   i) the input array is interpolated (or extrapolated) between the active elements as\n   specified in REGPARA=.\n\n   ii) The interpolated array is Fourier-transformed.\n\n   iii) The amplitudes of the orders specified in numerator (REGNUME=) are summed\n   and divided by the sum of the amplitudes of the orders specified in\n   denominator (REGDENO=), or, if greater than zero, by the amplitudes specified in REGAMPD=,  the ratio being r.\n\n   iv) r is used to determine an addition to the chisquare >= 0, following a smooth step\n   determined by regthre (REGTHRE= threshold above which the result is\n   > 1), regwidt (REGWIDT=, width of step, the maximum is reached if r\n   = regthre+regwidt), regampl (REGAMPL=, amplitude of step in first\n   loop), and regaste (REGASTE=, each loop the step amplitude is\n   increased by this value).\n\n   v) The factors for each regularised groups are added to 1 (, stored, ) and returned.\n\n   @param reg_contv (reg_cont **)   A NULL-terminated list of regularisation structs\n   @param loop      (int)           Loop number\n   @param chisquare (double)        Input chisquare\n\n   @return double reg_do: Product of ratios of modes\n*/\n/* ------------------------------------------------------------ */\nstatic double reg_do(reg_cont **reg_contv, int loop, double chisquare);\n\n\n\nstatic int writecoolmodel(startinf *startinfv, loginf *log, hdrinf *origin, ringparms *rpm, fitparms *fit, double *par, decomp_inlist *index);\nstatic int galmodcool(hdrinf *hdr, ringparms *rpm, int fitmode, varlel *varele, decomp_inlist *index, long *fluxpoints, int *allnpoints);\nstatic long srconstcool(hdrinf *hdr, ringparms *rpm, int srnr, long mode, int disk);\nstatic int srshape_azi_pascool(void *rpm, float *pp, float sinaz, float cosaz, int srnr, int outofrange, int disk);\nstatic int srshape_azi_actcool(void *rpm, float *pp, float sinaz, float cosaz, int srnr, int outofrange, int disk);\nstatic void srshapecool(ringparms *rpm, float *pp, float sinaz, float cosaz, int srnr, int disk);\n#ifdef PBCORR\nstatic void gridpoint_mixedcool(hdrinf *hdr, void (*fill_pbcfac)(hdrinf *hdr, struct srd **sd, int disk, int srnr, long *pnr, int *grid), float *modpar, int nr, struct srd **sd, int srnr, long *pnr, float *pp, int signum, long *npoints, int disk);\n#else\nstatic void gridpoint_mixedcool(hdrinf *hdr, float *modpar, int nr, struct srd **sd, int srnr, long *pnr, float *pp, int signum, long *npoints, int disk);\n#endif\n#ifdef PBCORR\nstatic void gridpoint_normcool(hdrinf *hdr, void (*fill_pbcfac)(hdrinf *hdr, struct srd **sd, int disk, int srnr, long *pnr, int *grid), float *modpar, int nr, struct srd **sd, int srnr, long *pnr, float *pp, int signum, long *npoints, int disk);\n#else\nstatic void gridpoint_normcool(hdrinf *hdr, float *modpar, int nr, struct srd **sd, int srnr, long *pnr, float *pp, int signum, long *npoints, int disk);\n#endif\nstatic void sdis_repeater_actcool(void *rpm, float *pp, float vold, int srnr, hdrinf *hdr, long *j, int signum, long *npoints, int disk);\nstatic void sdis_repeater_pascool(void *rpm, float *pp, float vold, int srnr, hdrinf *hdr, long *j, int signum, long *npoints, int disk);\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n/* FUNCTION CODE */\n/* ------------------------------------------------------------ */\n\nint main(int argc, char *argv[])\n{\n  startinf *startinfv = NULL;\n  loginf *log = NULL;\n  hdrinf *hdr = NULL;\n  ringparms *rpm = NULL;\n  fitparms *fit = NULL;\n  int i = 0;\n  int j;\n  int nrplts;\n  char mes[81];\n\n  printf(\"\\n\");\n  printf(\"#####################\\n\");\n  printf(\"# TiRiFiC v. 2.3.11 #\\n\");\n  printf(\"#####################\\n\");\n  printf(\"\\n\");\n\n  if (!(startinfv = get_startinf(argc, argv)))\n    goto error;\n\n  while (check_restart(startinfv, hdr, rpm, log)) {\n    \n    if (!(log = get_loginf(startinfv, log)))\n      goto error;\n\n    if (!(hdr = get_hdrinf(startinfv, log, hdr)))\n      goto error;\n    \n    if (!(rpm = get_ringparms(startinfv, log, hdr, rpm)))\n      goto error;\n\n    if (!(fit = get_fitparms(startinfv, log, hdr, rpm, fit))) {\n      goto error;\n    }\n\n    if ((j = open_hdu_3(log, hdr, rpm, fit)) == 1) {\n      goto error;\n    }\n\n    \n    /*   else if (j == 2) */\n    /*     ; */\n    /*   else if (j == 0)  */\n    \n    prepout(log, hdr, rpm);    \n\n    if (fit -> fitmode == METROPOLIS) { \n    /*       if (!metropolis(log, hdr, rpm, fit)) { */\n    /* \tgoto error; */\n    /*       } */\n    /*       if (!putmetresults(log, rpm, fit)) { */\n    /* \tgoto error; */\n    /*       } */\n        ;\n      }\n      else if (fit -> fitmode == GOLDEN_SECTION) { \n        if (!golden_section(startinfv, log, hdr, rpm, fit))\n    \tgoto error;\n\t\n        if (!putgoldresults(log, rpm, fit))\n    \tgoto error;\n      }\n      else if (fit -> fitmode > GOLDEN_SECTION) {\n        if (!genfit(startinfv, log, hdr, rpm, fit))\n    \tgoto error;\n\n        if (!putgenresults(startinfv, log, hdr, rpm, fit))\n    \tgoto error;\n      }\n    \n    /* put the results in an ascii table */\n    writeasctable(startinfv, log, hdr, rpm, fit);\n    \n    /* Put the results for each subring in an ascii table */\n    writebigasctable(startinfv, log, hdr, rpm, fit);\n\n    /* Graphics */\n    nrplts = graphout(startinfv, log, hdr, rpm, fit);\n   \n    nrplts = ((nrplts))?nrplts:1;\n   \n    briggsout(startinfv, log, hdr, rpm, fit);\n   \n    /* Output of a def file */\n    tirout(startinfv, log, rpm, fit, nrplts);\n    \n\n    /* Output of a histogram */\n    /*   histout(rpm); */\n    \n    /* Rectify output */\n    /*   rectout(log, hdr, rpm, fit); */\n    \n    /* Tiltogram output */\n    tiltout(startinfv, log, hdr, rpm, fit);\n    \n    /* Write the output cube */\n    i = 1;\n    if ((*hdr -> outset != '\\0')) {\n    \n      /* We read all values into the par array */\n      tir_get_grid(log, rpm, log -> outarray);\n    \n      for (i = 0; i < rpm -> nur*(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)+NSPARAMS; ++i)\n        rpm -> oldpar[i] = log -> outarray[i];\n    \n      changetointern(rpm -> oldpar, rpm -> nur, hdr, rpm -> ndisks);\n    \n      /* Now we write it */\n      writemodel(hdr, rpm, fit, rpm -> oldpar, fit -> index);\n    }\n\n    /* Renzo */\n    renzo(startinfv, log, hdr, rpm);\n\n    /* Cool */\n    coolgal(startinfv, log, hdr, rpm, fit);\n\n    /* Cool again */\n    writecoolmodel(startinfv, log, hdr, rpm, fit, rpm -> oldpar, fit -> index);\n \n    if ((log -> tstream))\n      fclose(log -> tstream);\n    log -> tstream = NULL;\n\n    /* Close the progress file, Kamphuis addition */\n    progressfinished(startinfv);\n\n    loop_restart(startinfv);\n  }\n\n  /* if ((*hdr -> outset != '\\0')) */\n  /*   gds_close_tir(hdr -> outset, &i); */\n\n    /*   ftstab_putminmax_(); */\n  ftstab_close_();\n  ftstab_flush_();\n  ftstab_hdlreset_();\n  hdl_init(rpm -> ndisks);\n  destroy_startinf(startinfv);\n  destroy_loginf(log, rpm -> ndisks);\n  destroy_hdrinf(hdr);\n  destroy_fitparms(fit);\n  destroy_ringparms(rpm);\n\n  /* finis_c(); */\n\n  /* fprintf(stderr,\"Got here: end\\n\");*/\n  \n  return 1;\n\n error:\n  i = 0;\n  sprintf(mes, \"ABORTING: Memory problems, unwise parameters, user abort\");\n  anyout_tir(&i, mes);\n\n  if ((log))\n    destroy_loginf(log, rpm -> ndisks);\n  if ((hdr))\n    destroy_hdrinf(hdr);\n  if ((rpm))\n    destroy_ringparms(rpm);\n  if ((fit))\n    destroy_fitparms(fit);\n\n  ftstab_close_();\n  ftstab_flush_();\n\n  /* finis_c(); */\n  return 0;\n}\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Returns a gipsy compatible char array */\n\nstatic int tir_get_grid(loginf *log, ringparms *rpm, double *array)\n{\n  int i;\n  for (i = 0; i < (rpm -> nur*(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)+NSPARAMS+OUTTABNR); ++i)\n    array[i] = log -> grid[i];\n  return 0;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Returns a gipsy compatible char array */\n\nstatic double tir_get_colgrd(loginf *log, ringparms *rpm, int i)\n{\n  return log -> grid[i-1];\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Returns a gipsy compatible char array */\n\nstatic double tir_get_colrad(loginf *log, ringparms *rpm, int i)\n{\n  return log -> radius[i-1];\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/*  */\n\nstatic int tir_get_radius(loginf *log, ringparms *rpm, double *array)\n{\n  int i;\n  for (i = 0; i < (rpm -> nur*(NPARAMS+(rpm -> ndisks -1)*NDPARAMS)+NSPARAMS+OUTTABNR); ++i)\n    array[i] = log -> radius[i];\n  return 0;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/*  */\n\nstatic int tir_get_register(loginf *log, ringparms *rpm, double *array)\n{\n  int i;\n  for (i = 0; i < (rpm -> nur*(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)+NSPARAMS+OUTTABNR); ++i)\n    array[i] = log -> regist[i];\n  return 0;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/*  */\n\nstatic int tir_put_register(loginf *log, ringparms *rpm, double *array)\n{\n  int i;\n  for (i = 0; i < (rpm -> nur*(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)+NSPARAMS+OUTTABNR); ++i)\n    log -> regist[i] = array[i];\n  return 0;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Returns a gipsy compatible char array */\n\nstatic int tir_fillhd(loginf *log, int i, double radius, double grid)\n{\n  log -> grid[i] = grid;\n  log -> radius[i] = radius;\n  return 0;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* testing ftstab */\n\nstatic int activateftstab(startinf *startinfv, loginf *log, ringparms *rpm)\n{\n  int def;\n  char mes[101];\n  char mon_key[20];\n  char value[20];\n  int anint = 0;\n  int logfile_present = 0;\n  int logfile_faulty = 0;\n  int logfile_not_tir = 0;\n  int nel = 1;\n\n  /* If there is no logfile specified we simply terminate the logname */\n  if (*log -> logname == '\\0') {\n    free(log -> logname);\n    log -> logname = NULL;\n  }\n\n  log -> logpres = 1;\n\n  /* Close and reopen ftstab */\n  if (!startinfv -> firstrun)\n    ftstab_close_();\n\n  /* initialise */\n  /* Initialise the table content object */\n  ftstab_flush_();\n  \n  /* Virginalise the header information table */\n  ftstab_hdlreset_();\n  \n  /* Initialising the logfile info: change */\n  \n  /* This defines possible table items, their numbers (PPARAM+1),\n     type, unit, scaling, it does not create a table */\n  hdl_init(rpm -> ndisks);\n\n\n  if ((log -> logname)) {\n    \n    /* Check if the logfile already exists and tell the user if yes */\n    if (!(rename(log -> logname, log -> logname))) {\n      sprintf(mes, \"LOGFILE present\");\n      anyout_tir(&anint,mes);\n      logfile_present = 1;\n    }\n    \n    if (!startinfv -> firstrun){\n      sprintf(mes, \"multiple runs, will overwrite LOGFILE\");\n      anyout_tir(&anint,mes);\n      logfile_present = 1;\n    }\n      \n    /* open */\n    /* returns 0 if file is present and could not be opened, 2 if no file is present and could also not be opened, something else if there is an error. (name,\n       extension, mode (2: append), extension, history header, don't\n       care.) Have to admit that this is a bit obscure, so I hope it still works.*/\n    log -> logpres = ftstab_fopen(log -> logname, 1, 2, 1);\n    \n    /* An error occured connected to the opening of the logfile, inform the user */\n    if (log -> logpres && (log -> logpres != 2)) {\n      sprintf(mes, \"LOGFILE faulty\");\n      anyout_tir(&anint,mes);\n      logfile_faulty = 1;\n    }\n    \n    if (!(log -> logpres)) {\n      sprintf(mon_key, \"CREATOR\");\n      if (ftstab_getcard(0, mon_key, value, 1)) {\n\tif (strcmp(value, \"'TIRIFIC '\")){\n\t  logfile_not_tir = 1;\n\t}\n      }\n      else \n\tlogfile_not_tir = 1;\n\n      if (logfile_not_tir) {\n\tsprintf(mes, \"LOGFILE not created by TiRiFiC\");\n\tanyout_tir(&anint,mes);\n      }\n    }\n    \n\n    /* Ask what to do (only if this is a single run) */\n    if ((logfile_present)) {\n      if (startinfv -> firstrun) {\n\tsprintf(mes, \"continue [0]\");\n\tanyout_tir(&anint,mes);\n\tsprintf(mes, \"delete logfile and continue [1]\");\n\tanyout_tir(&anint,mes);\n\tsprintf(mes, \"stop [everything else, e.g. 2]\");\n\tanyout_tir(&anint,mes);\n\tdef = 1;\n\tnel = 1;\n\tanint = 0;\n\tsprintf(mes, \"0, 1, or 2 [0]?\");\n\tuserint_tir(startinfv -> arel, &anint, &nel, &def, \"ACTION\", mes);\n      \n\t/* fprintf(\"\", startinf -> arel -> keyvallipre -> key); */\n\t\n\t/* We proceed and at the moment reset PROCEED */\n\t/* cancel_tir(startinfv -> arel, \"ACTION=\", 0); */\n      }\n      else {\n\tanint = 1;\n      }\n      if (anint) {\n\tif (anint == 1) {\n\t  /* Close the file, delete it, and open it again */\n\t  ftstab_close_();\n\t  ftstab_flush_();\n\t  ftstab_hdlreset_();\n\t  hdl_init(rpm -> ndisks);\n\t  remove(log -> logname);\n\t  log -> logpres = ftstab_fopen(log -> logname, 1, 2, 1);\n\t}\n\telse {\n\t  /* Close the file, and stop */\n\t  ftstab_close_();\n\t  ftstab_flush_();\n\t  ftstab_hdlreset_();\n\t  hdl_init(rpm -> ndisks);\n\t  log -> logpres = 1;\n\t  goto error;\n\t}\n      }\n      \n      /* If the logfile was faulty, we close anyway */\n      else if (logfile_faulty) {\n\tftstab_close_();\n\tftstab_flush_();\n\tftstab_hdlreset_();\n\thdl_init(rpm -> ndisks);\n\tlog -> logpres = 1;\n\tsprintf(mes, \"LOGFILE faulty, this never works.\");\n\tanyout_tir(&anint,mes);\n\tgoto error;\n      }\n    }\n\n    /* I think the following should only be done if a file is not present, in which case the answer is 2 */\n    if (log -> logpres == 2) {\n      \n      /* create a column, check what happens if there is already a table\n\t object, success is 1, not 0 (verra old code) */\n      ftstab_inithd(1L);\n      \n      /* now fill the column with information, columns start at 0 */\n/*       output = ftstab_fillhd(0L, NPARAMS+(rpm -> ndisks-1)*NDPARAMS+NSPARAMS+PRIMHDN_SINGLE+SECHDN_MULTI+CHISQ_TABNR, COLTYPE_DOUBLE, 0.0, -1.0); */\n      ftstab_fillhd(0L, NPARAMS+(rpm -> ndisks-1)*NDPARAMS+NSPARAMS+(LASTSING_PRIMPOS+NUMB_MDPRIMPOS*rpm -> ndisks)+SECHDN_MULTI+CHISQ_TABNR, COLTYPE_DOUBLE, 0.0, -1.0);\n    }\n            \n    /* Now open the file and put some text there (or vice versa) */\n    if (log -> logpres) {\n      ftstab_genhd(0);\n      \n      /* probably the only thing that we'll do */\n      sprintf(mon_key, \"CREATOR\");\n      sprintf(value, \"TIRIFIC\");\n      \n      ftstab_putcard(0, mon_key, value);\n      \n      if ((log -> logpres = ftstab_fopen(log -> logname, 1, 2, 1))) {\n\tgoto error;\n      }  \n    }\n\n  }\n\n  /* Logfile is open or not present */\n  return 0;\n\n error:\n  /* Whenever we got here, there was an error, such that we should stop. Logfile is closed */\n  return 1;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Creates a startinf structure */\n\nstatic startinf *create_startinf(void)\n{\n  startinf *startinfv;\n  \n  /* Allocate the struct */\n  if (!(startinfv = (startinf *) malloc(sizeof(startinf))))\n    return NULL;\n  \n  /* First set all pointers to 0 and initialise some pointers */\n  startinfv -> arel = NULL;\n  startinfv -> restartname = NULL;\n  startinfv -> restartid = 0;\n  startinfv -> firstrun = 1;\n  /* if (!(startinfv -> restartname =  getfcharray(200, NULL))) */\n  /*   goto error; */\n  if (!((startinfv -> filestat) = (struct stat *) malloc(sizeof(struct stat)))) {\n    goto error;\n  }\n  \n  return startinfv;\n  \n error:\n  destroy_startinf(startinfv);\n  return NULL;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Destroys a loginf structure */\n\nstatic void destroy_startinf(startinf *startinfv)\n{\n  /* Make it safer against unwarranted use */\n  if (!(startinfv))\n    return;\n\n  /* Deallocate */\n  if ((startinfv -> arel)) {\n    simparse_scn_arellist_dest(startinfv -> arel);\n  }\n  if (startinfv -> restartname) {\n    free(startinfv -> restartname);\n  }\n  if (startinfv -> filestat) {\n    free(startinfv -> filestat);\n  }\n\n  free(startinfv);\n\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Initialisation of the program concerning info from the dataset */\nstatic startinf *get_startinf(int argc, char **argv) \n{\n  startinf *startinfv;\n  /* char mes[81]; */\n  /* int def, nel; */\n    int i, blen, blin;\n  char *buffer = NULL;\n  int nread, nreturned;\n  char *returnedc;\n  int *prompt = NULL, *restartid = NULL;\n  int restartdef = 0;\n  int promptdef = 0;\n  int keypres;\n  char **varystr = NULL;\n\n  /* Try to allocate */\n  if (!(startinfv = create_startinf()))\n    goto error;\n  \n  /* Get the command line into a buffer */\n\n  /* first count */\n  blen = 0;\n  for (i = 1; i < argc; ++i) {\n    blen = blen + strlen(argv[i]) + 1;\n  }\n\n  ++blen;\n\n  /* Then allocate */\n  if (!(buffer = (char *) malloc(blen*sizeof(char))))\n    goto error;\n\n  /* Then fill */\n  if (argc == 1) {\n    buffer[0] = '\\0';\n  }\n\n  blen = 0;\n  for (i = 1; i < argc; ++i) {\n    memcpy(buffer+blen, argv[i], blin = strlen(argv[i]));\n    blen = blen + blin;\n    if (i < (argc - 1))\n      buffer[blen] = ' ';\n    else \n      buffer[blen] = '\\0';\n\n    ++blen;\n  }\n\n  /* Now get the key struct */\n  if (!(startinfv -> arel = simparse_scn_arel_insert(NULL, \"Command line\", buffer, NULL)))\n    goto error;\n\n  /* An input of restartid != 0 on the command line is an error */\n  if (simparse_scn_arel_readval_int(startinfv -> arel, \"RESTARTID\", \"ID of restart process [0]\", 1, &restartdef, 1, 1, 0, 0, &keypres, &nread, &nreturned, &restartid))\n    goto error;\n\n  if (*restartid) {\n    fprintf(stderr, \"Error: cannot define RESTARTID=%i, other than RESTARTID=0 on command line.\\n(Would lead to an endless loop.)\\n\", *restartid);\n    goto error;\n  }\n\n  free(restartid); \n  \n  /* Read out the file name */\n  if (simparse_scn_arel_readval_string(startinfv -> arel, \"DEFFILE\", \"Provide default file name (default: no file).\", 0, NULL, 0, -1, 0, 0, &keypres, &nread, &nreturned, &returnedc))\n    goto error;\n  \n  if ((returnedc[0]))\n    printf(\"Using default file with name: %s\\n\", returnedc);\n\n  if (!(startinfv -> arel = simparse_scn_arel_insert(startinfv -> arel, NULL, NULL, returnedc)))\n    goto error;\n\n  free(returnedc);\n\n  /* Check if prompting */\n  if (simparse_scn_arel_readval_int(startinfv -> arel, \"PROMPT\", \"Prompt on error or terminate on error (prompt: 1, terminate: 0)? [0]\", 1, &promptdef, 1, 1, 0, 0, &keypres, &nread, &nreturned, &prompt))\n    goto error;\n\n  /* Switch prompting on or off */\n  simparse_scn_arel_onerror_prompt(startinfv -> arel, *prompt);\n  if ((*prompt))\n    printf(\"Will prompt on error.\\n\");\n  else\n    printf(\"Will terminate on error.\\n\");\n\n  free(prompt);\n\n  /* The startfile */\n  /* cancel_tir(startinfv -> arel, \"RESTARTNAME\"); */\n\n  if ((startinfv -> restartname)) {\n    free(startinfv -> restartname);\n    startinfv -> restartname = NULL;\n  }\n\n  if (varystr) {\n    freeparsed(varystr);\n    varystr = NULL;\n  }\n\n  if (simparse_scn_arel_readval_stringlist(startinfv -> arel, \"RESTARTNAME\", \"Give restartfile name.\", 0, NULL, 0, -1, 0, 0, &keypres, &nread, &nreturned, &varystr))\n    goto error;\n  \n  if ((varystr[0])) {\n    if (!(startinfv -> restartname = simparse_copystring(varystr[0]))) {\n      goto error;\n    }\n  }\n  else {\n    if (!(startinfv -> restartname = simparse_copystring(\"\"))) {\n      goto error;\n    }\n  }\n  freeparsed(varystr);\n  varystr = NULL;\n\n  if (simparse_scn_arel_readval_int(startinfv -> arel, \"RESTARTID\", \"ID of restart process [0]\", 1, &restartdef, 1, 1, 0, 0, &keypres, &nread, &nreturned, &restartid))\n    goto error;\n  startinfv -> restartid = *restartid;\n  \n  /* The startfile */\n  /* sprintf(mes, \"Give restartfile name.\"); */\n  /*   for (i = 0; i < 200; ++i) */\n  /*   startinfv -> restartname[i] = ' '; */\n  /* startinfv -> restartname[200] = '\\0'; */\n\n  /* def = 2; */\n  /* nel = 1; */\n  /* userchar_tir(startinfv -> restartname, &nel, &def, \"RESTARTNAME=\", mes); */\n  /* termsinglestr(startinfv -> restartname); */\n\n  free(buffer);\n  free(restartid);\n  return startinfv;\n  \n error:\n  if ((startinfv)) {\n    /* Stop the logfile io, also put ndisks = 1, is irrelevant */\n    destroy_startinf(startinfv);\n  }\n  \n  if ((buffer))\n    free(buffer);\n  if ((prompt))\n    free(prompt);\n  if ((startinfv -> arel))\n    simparse_scn_arellist_dest(startinfv -> arel);\n\n  return NULL;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Return 1 if restart, 0 else */\n\nstatic int check_restart(startinf *startinfv, hdrinf *hdr, ringparms *rpm, loginf *log)\n{\n  int retval,i;\n\n  if (strlen(startinfv -> restartname)) {\n\n    /* Check if file information can be acquired and fill stuff */\n    if (stat(startinfv -> restartname, startinfv -> filestat)) {\n      retval = 0;\n    }\n    else {\n      startinfv -> timestamp = startinfv -> filestat -> st_mtime;\n      retval = 1;\n    }\n  }\n  else {\n    retval = 0;\n  }\n\n  if (startinfv -> firstrun)\n    retval = 1;\n\n  if ((retval)) {\n    if ((rpm)) {\n      \n      /* We read all values into the par array and to be sure make oldpar and par equal */\n      tir_get_grid(log, rpm, log -> outarray);\n      \n      for (i = 0; i < rpm -> nur*(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)+NSPARAMS; ++i)\n        rpm -> oldpar[i] = log -> outarray[i];\n      \n      changetointern(rpm -> oldpar, rpm -> nur, hdr, rpm -> ndisks);\n      \n      for (i = 0; i < rpm -> nur*(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)+NSPARAMS; ++i)\n        rpm -> par[i] = rpm -> oldpar[i];\n    }\n  }\n\n  return retval;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Check if restartfile exists and loop until its last change time stamp has changed with respect to the value stored in startinfv, make some switches afterwards */\n\nstatic int loop_restart(startinf *startinfv)\n{\n  /* char mes[81]; */\n  /* int def, nel, i; */\n  char **varystr = NULL;\n  int *restartid = NULL;\n  int keypres, nread, nreturned;\n  simparse_scn_keyvalli **keyvallifile;\n  \n  /* If the function is called, this should be done */\n  startinfv -> firstrun = 0;\n\n  /* Check if file is named */\n  if (strlen(startinfv -> restartname)) {\n    \n    /* Check if file information can be acquired and fill stuff */\n    if (stat(startinfv -> restartname, startinfv -> filestat)) {\n\n      /* Notice that tirific will not wait until the restartfile is created */\n      return 0;\n    }\n    else {\n      fflush(NULL);\n      printf(\"Waiting for file %s to change\", startinfv -> restartname);\n      if (startinfv -> restartid) {\n\t/* GJnew */\n\t/* if ((keyvallifile = simparse_scn_keyvallilist_gfrfi(startinfv -> arel[2] -> orifilename))) { */\n\t    printf(\" and RESTARTID= %i to change in %s.\\n\", startinfv -> restartid, startinfv -> arel[2] -> orifilename);\n\t    /*       } */\n      }\n      else {\n\tprintf(\".\\n\");\n      }\n\t\t\n      /* Run a loop until the timestamps are the same or the file becomes unreadable */\n      while (startinfv -> timestamp >= startinfv -> filestat -> st_mtime) {\n\t\t  if (stat(startinfv -> restartname, startinfv -> filestat)) {\n\t\t\t break;\n\t\t  }\n      }\n      printf(\"File %s has changed.\", startinfv -> restartname);\n\n      /* Now refresh the input name and read it in again (not sure if this works or if the .def file has to be reread into some buffer before */\n\t\t/* Changed this here */\n      cancel_tir(startinfv -> arel, \"RESTARTNAME=\", 1);\n      \n      /* Just make sure that the file is re-read */\n\n      /* This may add an extra layer of security of sync */\n      do {\n\tif ((restartid))\n\t   free(restartid);\n\tif (startinfv -> arel && startinfv -> arel[1] && startinfv -> arel[2]) {\n\t  if ((keyvallifile = simparse_scn_keyvallilist_gfrfi(startinfv -> arel[2] -> orifilename))) {\n\t    simparse_scn_keyvallilist_dest(startinfv -> arel[2] -> keyvallifile);\n\t    startinfv -> arel[2] -> keyvallifile = keyvallifile;\n\t  }\n\t  else {\n\t    simparse_scn_arel_timestamp_early(startinfv -> arel[2]);\n\t  }\n\t}\n\tif (simparse_scn_arel_readval_int(startinfv -> arel, \"RESTARTID=\", \"ID of restart process [0]\", 1, &startinfv -> restartid, 1, 1, 0, 0, &keypres, &nread, &nreturned, &restartid)) \n\t  goto error;\n      } while ((*restartid == startinfv -> restartid) && (startinfv -> restartid != 0));\n\t\n      startinfv -> restartid = *restartid;\n\t\n      if ((startinfv -> restartname)) {\n\tfree(startinfv -> restartname);\n\tstartinfv -> restartname = NULL;\n      }\n\t\t\n      /* sprintf(mes, \"Give restartfile name.\"); */\n      /* for (i = 0; i < 200; ++i) */\n      /* \tstartinfv -> restartname[i] = ' '; */\n      /* startinfv -> restartname[200] = '\\0'; */\n\t\t\n      /* def = 4; */\n      /* nel = 1; */\n      /* userchar_tir(startinfv -> restartname, &nel, &def, \"RESTARTNAME=\", mes); */\n      /* termsinglestr(startinfv -> restartname); */\n\t\t\n      /* Let's do this by default */\n      if (varystr) {\n\t\t  freeparsed(varystr);\n\t\t  varystr = NULL;\n      }\n\t\t\n      if (simparse_scn_arel_readval_stringlist(startinfv -> arel, \"RESTARTNAME\", \"Give name of file to restart.\", 0, NULL, 0, -1, 0, 0, &keypres, &nread, &nreturned, &varystr))\n\t\t  goto error;\n      \n      if ((varystr[0])) {\n\t\t  if (!(startinfv -> restartname = simparse_copystring(varystr[0]))) {\n\t\t\t goto error;\n\t\t  }\n      }\n      else {\n\t\t  if (!(startinfv -> restartname = simparse_copystring(\"\"))) {\n\t\t\t goto error;\n\t\t  }\n      }\n      freeparsed(varystr);\n      varystr = NULL;\n\n\t\t/* *** */\n/*       if (simparse_scn_arel_readval_stringlist(startinfv -> arel, \"BILLIBULLY\", \"Give name of file to restart.\", 0, NULL, 0, -1, 0, 0, &keypres, &nread, &nreturned, &varystr)) */\n/* \t\t  goto error; */\n      \n/*       if ((varystr[0])) { */\n/* \t\t  fprintf(stderr,\"bill: |%s|\\n\",varystr[0]); */\n/*       } */\n/*       freeparsed(varystr); */\n/*       varystr = NULL; */\n\n/* \t\tfprintf(stderr, \"RESTARTNAME: %s\", startinfv -> restartname); */\n\t\t/* *** */\n    }\n  }\n  else {\n    return 0;\n  }\n\n  if ((varystr)) {\n    freeparsed(varystr);\n  }\n  /* GJnew */\n    if ((restartid))\n      free(restartid); \n  return 0;\n  \n error:\n  if ((varystr)) {\n    freeparsed(varystr);\n  }\n  if ((restartid))\n    free(restartid);\n  return 1;\n  \n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Creates a loginf structure */\n\nstatic loginf *create_loginf(void)\n{\n  loginf *log;\n  \n  /* Allocate the struct */\n  if (!(log = (loginf *) malloc(sizeof(loginf))))\n    return NULL;\n  \n  /* First set all pointers to 0 and initialise some pointers */\n  log -> logname = NULL;\n  log -> logpres = 1;\n  log -> tstream = NULL;\n  log -> textlog = NULL;\n\n  /* Kamphuis addition */\n  log -> progresslog = NULL;\n  log -> table = NULL;\n  log -> outarray = NULL;\n  log -> grid = NULL;\n  log -> radius = NULL;\n  log -> regist = NULL;\n  log -> changes = 0;\n\n  /* Allocate and terminate */\n  /* if (!(log -> logname =  getfcharray(200, NULL))) */\n  /*   goto error; */\n  /* if (!(log -> textlog =  getfcharray(200, NULL))) */\n  /*   goto error; */\n  /* if (!(log -> progresslog =  getfcharray(200, NULL))) */\n  /*   goto error; */\n  /* if (!(log -> table =  getfcharray(200, NULL))) */\n  /*   goto error; */\n  log -> logname = NULL;\n  log -> textlog = NULL;\n  log -> progresslog = NULL;\n  log -> table = NULL;\n\n  return log;\n  \n /* error: */\n  /* Note: at this point, number of disks is unknown, but also irrelevant */\n  /* destroy_loginf(log, 1); */\n  /* return NULL; */\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Destroys a loginf structure */\n\nstatic void destroy_loginf(loginf *log, int ndisks)\n{\n\n  /* Make it safer against unwarranted use */\n  if (!(log))\n    return;\n\n  /* Deallocate */\n  if (log -> logname) {\n    free(log -> logname);\n    log -> logname = NULL;\n\n    if (!(log -> logpres)) {\n      ftstab_flush_();\n      ftstab_hdlreset_();\n      hdl_init(ndisks);\n    }\n  }\n\n  if (log -> textlog != NULL) {\n    free(log -> textlog);\n    log -> textlog = NULL;\n  }\n\n  /* Kamphuis addition */\n  if (log -> progresslog != NULL) {\n    free(log -> progresslog);\n    log -> progresslog = NULL;\n  }\n  if (log -> table != NULL) {\n    free(log -> table);\n    log -> table = NULL;\n  }\n  if (log -> grid != NULL) {\n    free(log -> grid);\n    log -> grid = NULL;\n  }\n  if (log -> radius != NULL) {\n    free(log -> radius);\n    log -> radius = NULL;\n  }\n  if (log -> regist != NULL) {\n    free(log -> regist);\n    log -> regist = NULL;\n  }\n  if (log -> outarray != NULL) {\n    free(log -> outarray);\n    log -> outarray = NULL;\n  }\n  free(log);\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Creates a hdrinf structure */\n\nstatic hdrinf *create_hdrinf(void)\n{\n  hdrinf *create_hdrinf;\n\n  /* Allocate the struct */\n  if (!(create_hdrinf = (hdrinf *) malloc(sizeof(hdrinf))))\n    return NULL;\n  \n  /* First set all pointers to 0 */\n  create_hdrinf -> inset = NULL;\n  /* create_hdrinf -> insubs = NULL; */\n  /* create_hdrinf -> cwlo = NULL; */\n  /* create_hdrinf -> cwhi = NULL; */\n  /* create_hdrinf -> ori = NULL; */\n  create_hdrinf -> oric = NULL;\n  /* create_hdrinf -> model = NULL; */\n  create_hdrinf -> modelc = NULL;\n  create_hdrinf -> coolcube = NULL;\n  create_hdrinf -> outset = NULL;\n  create_hdrinf -> chi2 = DBL_MAX;\n  create_hdrinf -> oldchi2 = DBL_MAX;\n#ifdef PBCORR\n  create_hdrinf -> primbeam = NULL;\n#endif\n\n\n  /* Allocate and initialise the arrays */\n  \n  /* Allocate inset, we allow for more than 18 characters */\n  /* if (!(create_hdrinf -> inset = getfcharray(200, NULL)))\n     goto error;*/\n  \n  /* Allocate coordinate descriptor array */\n  /* GJnew: removed this, lead to leakage */\n  /* if (!(create_hdrinf -> insubs = (int *) malloc(MAXNSUBS*sizeof(int)))) */\n  /*   goto error; */\n\n  /* Allocate outset, we allow for more than 18 characters */\n  /* if (!(create_hdrinf -> outset =  getfcharray(200, NULL))) */\n  /*   goto error; */\n\n  return create_hdrinf;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Destroys a hdrinf structure */\n\nstatic void destroy_hdrinf(hdrinf *hdr)\n{\n  /* Make it safer against unwarranted use */\n  if (!(hdr))\n    return;\n \n  if (hdr -> inset !=  NULL)\n    free(hdr -> inset);\n  /* if (hdr ->insubs != NULL) */\n  /*   free(hdr -> insubs); */\n\n  /* if (hdr -> cwhi != NULL) */\n  /*   free(hdr -> cwhi); */\n  /* if (hdr -> cwlo != NULL) */\n  /*   free(hdr -> cwlo); */\n  if (hdr -> oric != NULL)\n    cubarithm_cube_destroy(hdr -> oric);\n  if (hdr -> modelc != NULL)\n    cubarithm_cube_destroy(hdr -> modelc);\n  if (hdr -> coolcube != NULL)\n    cubarithm_cube_destroy(hdr -> coolcube);\n  /* These are just the same as the points array in oric and modelc */\n  /* if (hdr -> ori != NULL) */\n  /*   free_engalmod(hdr -> ori); */\n  /* if (hdr -> model != NULL) */\n  /*   free_engalmod(hdr -> model); */\n  if (hdr -> outset != NULL)\n    free(hdr -> outset);\n#ifdef PBCORR\n  if ((hdr -> primbeam))\n    free((hdr -> primbeam));\n#endif\n\n\n  /* Deallocate the struct */\n  free(hdr);\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Initialisation of the program concerning info from the dataset */\nstatic loginf *get_loginf(startinf *startinfv, loginf *loginfv) \n{\n  loginf *log;\n  char mes[81];\n  int def, nel;\n  int nread, nreturned, keypres;\n\n\n  /* There's two possibilities: this is the first pass, which means to create the loginf structure, or this is the second pass, in which case we don't do anything */\n\n  if (!startinfv -> firstrun)\n    return loginfv;\n\n  /* Try to allocate */\n  if (!(log = create_loginf()))\n    goto error;\n\n#ifdef OPENMPTIR\n  /* The very first thing to do is to ask for the number of cores */\n  log -> ncores = 1;\n  def = 5;\n  \n  sprintf(mes, \"Give maximum number of cores. [1]\");\n  \n  nel = 1;\n  userint_tir(startinfv -> arel, &log -> ncores, &nel, &def, \"NCORES=\", mes);\n  while (log -> ncores < 1) {\n    sprintf(mes, \"Should be at least one, eh?\");\n    cancel_tir(startinfv -> arel, \"NCORES=\", 2);\n    userint_tir(startinfv -> arel, &log -> ncores, &nel, &def, \"NCORES=\", mes);\n  }\n  omp_set_num_threads(log -> ncores);\n#else\n  log -> ncores = 1;\n#endif\n\n  /* First thing to do is the logfile and the text logfile */\n  \n  /* The logfile */\n  if (simparse_scn_arel_readval_string(startinfv -> arel, \"LOGNAME\", \"Provide logfile name (default: no file).\", 0, \"\", 0, -1, 0, 0, &keypres, &nread, &nreturned, &(log -> logname)))\n    goto error;\n\n  /* sprintf(mes, \"Give logfile name.\"); */\n  /* for (i = 0; i < 200; ++i) */\n  /*   log -> logname[i] = ' '; */\n  /* log -> logname[200] = '\\0'; */\n  \n  /* Formerly def = 5 */\n  /* def = 5; */\n  /* nel = 1; */\n  /* userchar_tir(log -> logname, &nel, &def, \"LOGNAME=\", mes); */\n  \n  /* This puts an \\0 to the end of the text */\n  /* termsinglestr(log -> logname); */\n\n  /* The text logfile */\n  if (simparse_scn_arel_readval_string(startinfv -> arel, \"TEXTLOG\", \"Provide text logfile name (default: no file).\", 0, \"\", 0, -1, 0, 0, &keypres, &nread, &nreturned, &(log -> textlog)))\n    goto error;\n\n    /* for (i = 0; i < 200; ++i) */\n    /*   log -> textlog[i] = ' '; */\n    /* log -> textlog[200] = '\\0'; */\n    /* def = 2; */\n    \n    /* sprintf(mes, \"Give text logfile name.\"); */\n    /* nel = 1; */\n    /* userchar_tir(log -> textlog, &nel, &def, \"TEXTLOG=\", mes); */\n    \n    /* This puts an \\n to the end of the text */\n    /* termsinglestr(log -> textlog); */\n    \n    /* The Prgress LOG  Kamphuis addition */\n  if (simparse_scn_arel_readval_string(startinfv -> arel, \"PROGRESSLOG\", \"Provide progress logfile name (default: no file).\", 0, \"\", 0, -1, 0, 0, &keypres, &nread, &nreturned, &(log -> progresslog)))\n    goto error;\n\n    /* for (i = 0; i < 200; ++i) */\n    /*   log -> progresslog[i] = ' '; */\n    /* log -> progresslog[200] = '\\0'; */\n    /* def = 2; */\n    \n    /* sprintf(mes, \"Give progress logfile name.\"); */\n    /* nel = 1; */\n    /* userchar_tir(log -> progresslog, &nel, &def, \"PROGRESSLOG=\", mes); */\n    \n    /* This puts an \\n to the end of the text */\n    /* termsinglestr(log -> progresslog); */\n    /* Kamphuis addition end */\n    \n    /* The result name */\n  if (simparse_scn_arel_readval_string(startinfv -> arel, \"TABLE\", \"Give output table name (default: no file).\", 0, \"\", 0, -1, 0, 0, &keypres, &nread, &nreturned, &(log -> table)))\n    goto error;\n\n    /* for (i = 0; i < 200; ++i) */\n    /*   log -> table[i] = ' '; */\n    /* log -> table[200] = '\\0'; */\n    \n    \n    /* sprintf(mes, \"Give output table name.\"); */\n    /* nel = 1; */\n    /* def = 2; */\n    \n    /* userchar_tir(log -> table, &nel, &def, \"TABLE=\", mes); */\n    \n    /* This puts an \\0 to the end of the text */\n    /* termsinglestr(log -> table); */\n    \n    \n    /* Now get the distance of the object */\n    log -> distance = 10;\n    def = 2;\n    \n    sprintf(mes,\"Distance in Mpc [10]\");\n    nel = 1;\n    userdble_tir(startinfv -> arel, &log -> distance, &nel, &def, \"DISTANCE=\", mes);\n    while (log -> distance <= 0) {\n      sprintf(mes,\"DISTANCE must be greater than zero.\");\n      log -> distance = 10;\n      cancel_tir(startinfv -> arel, \"DISTANCE=\", 2);\n      userdble_tir(startinfv -> arel, &log -> distance, &nel, &def, \"DISTANCE=\", mes);\n    }\n\n  return log;\n\n error:\n  if ((log)) {\n    /* Stop the logfile io, also put ndisks = 1, is irrelevant */\n    destroy_loginf(log, 1);\n  }\n  return NULL;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Initialisation of the program concerning info from the dataset */\nstatic hdrinf *get_hdrinf(startinf *startinfv, loginf *log, hdrinf *hdrinfv) \n{\n  hdrinf *hdr = NULL; /* The output */\n\n  int dev;      /* Output device */\n  int def;      /* Any default mode */\n  int nel;      /* Number of elements */\n  int class;    /* A class for the input of a set */\n  /* int classdim; */ /* Some other thing necessary for io of datasets */\n  /* int option; */   /* Input to gdsbox */\n  int err;      /* Error code */\n  int outerr;   /* Error heaviness for output */\n  /* int level; */    /* Strange level thingy */\n  char mes[81];  /* Any message */\n  /* char manual = 0; */ /* Signal for manual input */\n\n  /* char ciax[9]; */ /* Keyword holder */\n  /* char value[21]; */ /* Value holder */ \n  /* int i,j; */         /* Control variable */\n\n  /* double deltsettouser[3]; */ /* Conversion factor from cuniti to userdeltunit */\n  /* double setcdelt[3]; */ /* The cdelts in the set */\n  /* double setcrval[3]; */ /* The reference values in the set */\n  /* double userdeltcdelt[3]; */ /* The cdelt in delta user units */\n\n  /* dummies */\n  /* int inaxcount[MAXNAX]; */\n  /* int outaxperm[MAXNAX]; */\n  /* int outaxcount[MAXNAX]; */\n  /* int outsubs[MAXNSUBS]; */\n  /* int blo[3]; */ /* Contains lower values for subset dimensions for 2 axes */\n  /* int bhi[3]; */ /* Contains higher values for subset dimensions for 2 axes */\n  /* double vardouble; */ /* Any double */\n\n  /* Just to pass pointers (FORTRAN ...) */\n  /* int maxnsubs = MAXNSUBS; */\n  /* int maxnax = MAXNAX; */\n\n\n  int nread, nreturned, keypres;\n  char errormes[120];\n  char **stringlist = NULL;\n  simparse_scn_arel *temparel;\n\n\n  /* Everything in the header will be read once and not multiple times */\n  if (!startinfv -> firstrun) {\n    if ((hdrinfv)) {\n\n      if ((hdrinfv -> outset)) {\n\tfree(hdrinfv -> outset);\n\thdrinfv -> outset = NULL;\n\tif (simparse_scn_arel_readval_stringlist(startinfv -> arel, \"OUTSET\", \"Give output cube name.\", 0, NULL, 0, 1, 0, 0, &keypres, &nread, &nreturned, &stringlist))\n\t  goto error;\n  \n\tif ((stringlist[0])) {\n\t  if (!(hdrinfv -> outset = simparse_copystring(stringlist[0]))) {\n\t    goto error;\n\t}\n\t}\n\telse {\n\t  if (!(hdrinfv -> outset = simparse_copystring(\"\")))\n\t    goto error;\n\t}\n\t\n\tfreeparsed(stringlist);\n\tstringlist = NULL;\n      }\n    }\n    return hdrinfv;\n  }\n\n  if (!(hdr = create_hdrinf()))\n    goto error;\n\n  /* Get cube name */\n  if (simparse_scn_arel_readval_stringlist(startinfv -> arel, \"INSET\", \"Give input cube name (no default).\", 0, NULL, 1, 1, 1, 0, &keypres, &nread, &nreturned, &stringlist))\n    goto error;\n\n  if (!(hdr -> inset = simparse_copystring(stringlist[0])))\n    goto error;\n\n  freeparsed(stringlist);\n  stringlist = NULL;\n\n  /* Read the cube */\n\n  /* This is a trick to temporarily disable any other than hand input */\n  temparel = startinfv -> arel[1];\n  startinfv -> arel[1] = NULL;\n\n  while (cubarithm_readcube(hdr -> inset, &(hdr -> oric), errormes)) {\n\n    /* There was an error */\n    fprintf(stderr, \"INSET %s\\n\", errormes);\n\n    /* Free the name */\n    free(hdr -> inset);\n    hdr -> inset = NULL;\n\n    /* Doe this */\n    cancel_tir(startinfv -> arel, \"INSET\", 0);\n\n    /* Read another name from prompt or stop */\n    if (simparse_scn_arel_readval_stringlist(startinfv -> arel, \"INSET\", \"Give input cube name (no default).\", 0, NULL, 1, 1, 1, 0, &keypres, &nread, &nreturned, &stringlist)) {\n      startinfv -> arel[1] = temparel;\n      goto error;\n    }\n\n    /* Put in the name */\n    if (!(hdr -> inset = simparse_copystring(stringlist[0])))\n      goto error;\n\n    freeparsed(stringlist);\n    stringlist = NULL;\n  }\n\n  /* Reverse trick */\n  startinfv -> arel[1] = temparel;\n\n  /* Getting a copy is easy */\n  if (!(hdr -> modelc = cubarithm_copycube(hdr -> oric)))\n    goto error;\n\n  /* padding (don't forget!) */\n  padcubex(hdr -> oric);\n  padcubex(hdr -> modelc);\n\n  /* Linking, too (is absolutely dangerous and should be removed) */\n  /* hdr -> ori = hdr -> oric -> points; */\n  /* hdr -> model = hdr -> modelc ->points; */\n\n  /* Input set and subsets and box are in any case necessary, even with a present logfile */\n  /* err = 0; */\n  /* sprintf(mes, \"Give input set and subsets.\"); */\n  /* def = 0; */\n  /* dev = 0; */\n  /* class = 1; */\n  /* classdim = 2; */\n  \n  /* Get information about input dataset */\n  hdr -> nsubs = hdr -> oric -> size_v;\n\n  /* hdr -> nsubs = gdsinp_tir(hdr -> inset, hdr -> insubs, &maxnsubs, &def, \"INSET=\", mes, &dev, hdr -> inaxperm, inaxcount, &maxnax, &class, &classdim); */\n  /* termsinglestr(hdr -> inset); */\n  \n  /* A box has to be defined inside the specified set, on default whole dataset , not exactly understood */\n  /* sprintf((mes), \"Give area of operation.\"); */\n  /* def = 1; */\n  /* dev = 1; */\n  /* option = 1; */\n  /* gdsbox_tir(blo, bhi, hdr -> inset, hdr -> insubs, &maxnsubs, &def, \"BOX=\", mes, &dev, &option); */\n  /* def = 0; */\n  \n  /* The degree of error is not warning (1) but fatal (4) */\n  /* outerr = 4; */\n  \n  /* Check the dataset */\n  /* for (i = 0; i < 3; ++i) { */\n    \n    /* This is a simple check if CTYPEi is present in the header */\n    /* err = 0; */\n    /* sprintf(ciax, \"CTYPE%i\", hdr -> inaxperm[i]); */\n    \n    /* /\\* For level refer to the description *\\/ */\n    /* level = 0; */\n    /* for (j = 0; j < 20; ++j) */\n    /* \tvalue[j] = ' '; */\n    /*   value[20] = '\\0'; */\n    /*   gdsd_rchar_tir(hdr -> inset, ciax, &level, value, &err); */\n    /*   if (err < 0) { */\n    /* \tsprintf(mes, \"Header: CTYPE%i not found.\", i); */\n    /* \terror_tir(&outerr, mes); */\n    /*   } */\n      \n      /* This is a simple check if CUNITi is present in the header */\n      /* err = 0; */\n      /* sprintf(ciax, \"CUNIT%i\", hdr -> inaxperm[i]); */\n      /* for (j = 0; j < 20; ++j) */\n      /* \tvalue[j] = ' '; */\n      /* value[20] = '\\0'; */\n      /* gdsd_rchar_tir(hdr -> inset, ciax, &(level), value, &err); */\n      /* if (err < 0) { */\n      /* \tsprintf(mes, \"Header: CUNIT%i not found.\", i); */\n      /* \terror_tir(&outerr, mes); */\n      /* } */\n      \n      /* This is a check whether the cunit can be converted to modelspacunit, modelmapunit, respectively. At the same time deltsettouser and  globsettouser is filled with that conversion factor */\n      /* if (i < 2) { */\n      /* \terr = factor_tir(value, userdeltunit, deltsettouser+i); */\n      /* \tif (err) { */\n      /* \t  dev = 0; */\n      /* \t  sprintf(mes, \"Header: Invalid CUNIT%i\", i); */\n      /* \t  error_tir(&outerr, mes); */\n      /* \t} */\n      /* \tfactor_tir(value, userglobunit, hdr -> globsettouser+i); */\n      /* } */\n      /* else { */\n      /* \terr = factor_tir(value, user3deltunit, deltsettouser+i); */\n      /* \tif (err) { */\n      /* \t  sprintf(mes, \"Header: Invalid CUNIT%i\", i); */\n      /* \t  error_tir(&outerr, mes); */\n      /* } */\n      /* \tfactor_tir(value, user3globunit, hdr -> globsettouser+i); */\n      /* \terr = 0; */\n      /* } */\n \n  hdr -> globsettouser[0] = 1.;     \n  hdr -> globsettouser[1] = 1.;     \n  hdr -> globsettouser[2] = 0.001;     \n        \n      /* Now check the cdelt */\n      /* sprintf(ciax, \"CDELT%i\",  hdr -> inaxperm[i]); */\n      /* for (j = 0; j < 20; ++j) */\n      /* \tvalue[j] = ' '; */\n      /* value[20] = '\\0'; */\n      \n      /* level = 0; */\n      /* gdsd_rdble_tir(hdr -> inset, ciax, &level, setcdelt+i, &err); */\n      /* if (err < 0) { */\n      /* \tsprintf(mes, \"Header: CDELT%i not found.\", i); */\n      /* \terror_tir(&outerr, mes); */\n      /* } */\n      /* err = 0; */\n      \n      /* Now the crpix */\n      /* sprintf(ciax, \"CRPIX%i\",  hdr -> inaxperm[i]); */\n      /* for (j = 0; j < 20; ++j) */\n      /* \tvalue[j] = ' '; */\n      /* value[20] = '\\0'; */\n      \n      /* For level refer to the description */\n      /* level = 0; */\n      /* gdsd_rdble_tir(hdr -> inset, ciax, &level, hdr -> setcrpix+i, &err); */\n      /* if (err < 0) { */\n      /* \tsprintf(mes, \"Header: CRPIX%i not found.\", i); */\n      /* \terror_tir(&dev, mes); */\n      /* } */\n      \n  hdr -> setcrpix[0] = hdr -> oric -> refpix_x;     \n  hdr -> setcrpix[1] = hdr -> oric -> refpix_y;     \n  hdr -> setcrpix[2] = hdr -> oric -> refpix_v;     \n\n  /* Now the crval */\n  /* sprintf(ciax, \"CRVAL%i\",  hdr -> inaxperm[i]); */\n  /* for (j = 0; j < 20; ++j) */\n  /* \tvalue[j] = ' '; */\n  /* value[20] = '\\0'; */\n  \n  /* For level refer to the description */\n  /* level = 0; */\n  /* gdsd_rdble_tir(hdr -> inset, ciax, &level, setcrval+i, &err); */\n  /* if (err < 0) { */\n  /* \tsprintf(mes, \"Header: CRVAL%i not found.\", i); */\n  /* \terror_tir(&dev, mes); */\n  /* } */\n      \n  /* hdr -> setcrval[0] = hdr -> oric -> refval_x;      */\n  /* hdr -> setcrval[1] = hdr -> oric -> refval_y;      */\n  /* hdr -> setcrval[2] = hdr -> oric -> refval_v;      */\n     \n  /* The cdelt of the axis in user units, the size of a grid in user units */\n  /* userdeltcdelt[i] = setcdelt[i]*deltsettouser[i]; */\n  hdr -> userglobcdelt[0] = hdr -> oric -> delt_x*hdr -> globsettouser[0];\n  hdr -> userglobcdelt[1] = hdr -> oric -> delt_y*hdr -> globsettouser[1];\n  hdr -> userglobcdelt[2] = hdr -> oric -> delt_v*hdr -> globsettouser[2];\n      \n      /* The conversion factors for the user */\n  hdr -> deltgridtouser[0] = fabs(hdr -> oric -> delt_x*DEGTOARCSEC);\n  hdr -> deltgridtouser[1] = fabs(hdr -> oric -> delt_y*DEGTOARCSEC);\n  hdr -> deltgridtouser[2] = fabs(hdr -> oric -> delt_v*hdr -> globsettouser[2]);\n\n  hdr -> globgridtouser[0] = fabs(hdr -> oric -> delt_x);\n  hdr -> globgridtouser[1] = fabs(hdr -> oric -> delt_y);\n  hdr -> globgridtouser[2] = fabs(hdr -> oric -> delt_v*hdr -> globsettouser[2]);\n\n      /* hdr -> globgridtouser[i] = fabs(hdr -> userglobcdelt[i]); */\n      \n      /* The reference values of the axis in user units */\n  hdr -> userglobcrval[0] = hdr -> oric -> refval_x*1.;     \n  hdr -> userglobcrval[1] = hdr -> oric -> refval_y*1.;     \n  hdr -> userglobcrval[2] = hdr -> oric -> refval_v*hdr -> globsettouser[2];     \n    \n  hdr -> signv = -hdr -> oric -> delt_v/fabs(hdr -> oric -> delt_v);\n    \n  /* Calculate the size of the cube in grids along axis 1 and 2 */\n  /* hdr -> bsize1=bhi[0]-blo[0]+1; */\n  /* hdr -> bsize2=bhi[1]-blo[1]+1; */\n  hdr -> bsize1 = hdr -> oric -> size_x;\n  hdr -> bsize2 = hdr -> oric -> size_y;\n\n  /* This is to make a bit more space, take care for allocation */\n  hdr -> bcsize1= 2*(hdr -> bsize1/2+1);\n    \n    \n    /* The size of the cube in grids along axis 3 is given by hdr -> nsubs, get the values of the max and min grid */\n    /* i = 0; */\n    /* blo[2] = gdsc_grid_tir(hdr -> inset, hdr -> inaxperm+2, hdr -> insubs+i, &err); */\n    /* i = hdr -> nsubs-1; */\n    /* bhi[2] = gdsc_grid_tir(hdr -> inset, hdr -> inaxperm+2, hdr -> insubs+i, &err); */\n    \n    /* Get beam properties */\n    /* BUGFIX: removed the possibility to read beam properties from header */\n    \n    /* First check whether this goes automatic */\n  err = 0;\n\n    /* If the cdelt is the same for both spatial axes, go on */ \n  if (fabs(hdr -> userglobcdelt[0]) != fabs(hdr -> userglobcdelt[1])) {\n    anyout_tir(&outerr, \"cdelt of axis1 and axis2 are different\");\n    err = 1;\n  }\n\n\n  /* err = 0; */\n  \n  /* check if major axis can be read from the dataset */\n  /* gdsd_rdble_tir(hdr -> inset, \"BMAJ\", &level, &vardouble, &err); */\n  /* if (err < 0) */\n  \n  /* This is a signal have it manually */\n  /* \tmanual = 1; */\n  /* else { */\n  /* \touterr = 0; */\n  \n  /* This is done under the assumption that the beam is given in set units, i.e. degrees */\n  hdr -> bmaj = (float) hdr -> oric -> bmaj/fabs(hdr -> oric -> delt_y);\n  /*       sprintf(mes, \"Beam major axis in arcsec: %f\", hdr -> bmaj*fabs(setcdelt[0])); */\n  /*       anyout_tir(&outerr, mes); */\n  /* } */\n  /* err = 0; */\n  \n  /* check if minor axis can be read from the dataset */\n  /* gdsd_rdble_tir(hdr -> inset, \"BMIN\", &level, &vardouble, &err); */\n  /* if (err < 0) */\n  \n  /* This is a signal have it manually */\n  /* \tmanual = 1; */\n  /* else { */\n  /* \touterr = 0; */\n  /* This is done under the assumption that the beam is given in set units */\n  /* hdr -> bmin = (float) vardouble/fabs(setcdelt[1]); */\n  hdr -> bmin = (float) hdr -> oric -> bmin/fabs(hdr -> oric -> delt_y);\n  /*       sprintf(mes, \"Beam minor axis in arcsec: %f\", hdr -> bmin*fabs(setcdelt[1])); */\n  /*       anyout_tir(&outerr, mes); */\n  /* } */\n  /* err = 0; */\n  \n  /* check for the bpa */\n  /* gdsd_rdble_tir(hdr -> inset, \"BPA\", &level, &vardouble, &err); */\n  /* if (err < 0) */\n  \n  /* This is a signal have it manually */\n  /* \tmanual = 1; */\n  /* else { */\n      /* \touterr = 0; */\n  /* CAUTION !!!!! This is done under the assumption that the bpa is always in deg */\n  hdr -> bpa = (float) hdr -> oric -> bpa;\n  /*       sprintf(mes, \"Beam position angle in degrees: %f\", hdr -> bpa); */\n  /*       anyout_tir(&outerr, mes); */\n  /*   } */\n  /* } */\n  \n  /* If the cdelts are different we pose a warning and enforce manual reading */\n  /* else { */\n  /*   outerr = 0; */\n  /*   anyout_tir(&outerr, \"cdelt of axis1 and axis2 are different\"); */\n  /* } */\n  \n  /* Read beam properties manually */\n  \n  \n  /* BUGFIX: removed the possibility to read beam properties from header. This caused too much confusion */\n  /* manual = 1; */\n  \n  /* The beam major and minor axis has to be read in manually */\n  if ((hdr -> bmaj <= 0) || (err) ) {\n\n    /* If a proper logfile is present, we set a default and the beam properties are hidden */\n    def = 4;\n    \n    sprintf(mes, \"Give HPBW of the gaussian beam, major axis, in arcsec.\");\n    nel = 1;\n    userreal_tir(startinfv -> arel, &hdr -> bmaj, &nel, &def, \"BMAJ=\", mes);\n    \n    sprintf(mes, \"Give HPBW of the gaussian beam, minor axis, in arcsec.\");\n    nel = 1;\n    userreal_tir(startinfv -> arel, &hdr -> bmin, &nel, &def, \"BMIN=\", mes);\n    \n    sprintf(mes, \"Give BPA of the gaussian beam in degrees.\");\n    nel = 1;\n    userreal_tir(startinfv -> arel, &hdr -> bpa, &nel, &def, \"BPA=\", mes);\n    \n    /* Convert from arcsec to grids */\n    hdr -> bmaj = hdr -> bmaj/hdr -> deltgridtouser[0];\n    hdr -> bmin = hdr -> bmin/hdr -> deltgridtouser[0];\n  }\n  \n  /* Check for the correct intensity units */\n  err = 0;\n  /* for (j = 0; j < 20; ++j) */\n  /*   value[j] = ' '; */\n  /* value[20] = '\\0'; */\n  /* gdsd_rchar_tir(hdr -> inset, \"BUNIT\", hdr -> insubs, value, &err); */\n  /* if ((err == 0) || (err == hdr -> insubs[0])) { */\n  if (!strcmp(hdr -> oric -> unit, \"JY/BEAM\") || !strcmp(hdr -> oric -> unit, \"jy/beam\")) {\n    sprintf(mes,\"Units in the maps should be JY/BEAM, found: |%s|\", hdr -> oric -> unit);\n    /* dev = 0; */\n    anyout_tir(&dev, mes);\n    /* outerr = 1; */\n    anyout_tir(&outerr, \"Check if that is ok.\");\n  }\n  /* } */\n  /* else { */\n  /*   outerr = 1; */\n  /*   error_tir(&outerr, \"No units in the maps found.\"); */\n  /* } */\n  \n  /* Allocate memory for cwlo and -hi */\n  /* if (!(hdr -> cwhi = (int *) malloc(hdr -> nsubs*sizeof(int)))) */\n  /*   goto error; */\n  /* if (!(hdr -> cwlo = (int *) malloc(hdr -> nsubs*sizeof(int)))) */\n  /*   goto error; */\n  \n  /* check the subset grid and set it: The grid value is the relative position with respect to the reference pixel as integer */\n  /* for (i = 0; i < 0+hdr -> nsubs; ++i) { */\n  /*   hdr -> cwlo[i] = gdsc_fill_tir(hdr -> inset,hdr -> insubs+i, blo); */\n  /*   hdr -> cwhi[i] = gdsc_fill_tir(hdr -> inset,hdr -> insubs+i, bhi); */\n  /* } */\n  \n  /* Input of rms */\n  err = 0;\n  /* level = 0 ; */\n  /* gdsd_rreal_tir(hdr -> inset, \"RMS\", &level, &hdr -> rms, &err); */\n  /* if (err < 0) { */\n  def = 4;\n  \n  \n  sprintf(mes, \"Give sigma_rms for input map in map units. [Jy/beam]\");\n  nel = 1;\n  userreal_tir(startinfv -> arel, &hdr -> rms, &nel, &def, \"RMS=\", mes);\n  while (hdr -> rms <= 0) {\n    sprintf(mes, \"Sigma must be positive\");\n    anyout_tir(&nel, mes);\n    cancel_tir(startinfv -> arel, \"RMS\", 2);\n    sprintf(mes, \"Give sigma_rms for input map in map units. [Jy/beam]\");\n    nel = 1;\n    userreal_tir(startinfv -> arel, &hdr -> rms, &nel, &def, \"RMS=\", mes);\n  }\n  /* } */\n  \n  /* Determine conversion factor for HI column density => intensity */  \n  hdr -> itou = HICONVERSION;\n  \n  \n  sprintf(mes, \"Give intensity to surface density conversion\");\n  def = 2;\n  nel = 1;\n  err = 0;\n  while (!(err)) {\n    userdble_tir(startinfv -> arel, &hdr -> itou, &nel, &def, \"ITOU=\", mes);\n    if (hdr -> itou <= 0.0) {\n      sprintf(mes, \"Must be positive! %f\",hdr -> itou);\n      cancel_tir(startinfv -> arel, \"ITOU=\", 2);\n      def = 1;\n    }\n    else \n      err = 1;\n  }\n  \n  /* Get rest frequency */\n  hdr -> rfreq = HIRESFREQ;\n  \n  sprintf(mes, \"Give rest frequency\");\n  def = 2;\n  nel = 1;\n  err = 0;\n  while (!(err)) {\n    userdble_tir(startinfv -> arel, &hdr -> rfreq, &nel, &def, \"RFREQ=\", mes);\n    if (hdr -> rfreq <= 0.0) {\n      sprintf(mes, \"Must be positive!\");\n      cancel_tir(startinfv -> arel, \"RFREQ=\", 2);\n      def = 1;\n    }\n    else \n      err = 1;\n  }\n  \n  /*******************/\n  /*******************/\n  \n  \n  /* Don't try to do this again! */\n  /*  hdr -> cd2i = 1.5147016e-21 + fabs(hdr -> cdelt3)*pow(hdr -> cdelt3*hdr -> midgrid/hdr -> freq0+2.9979246e5/hdr -> drval3, 2); */\n  /* Determine conversion factor for Jy/arcsec^2 to Jy/pixel, deltgridtouser is in arcsec */\n  hdr -> jygridtouser = hdr -> deltgridtouser[2]/fabs(hdr -> deltgridtouser[0]*hdr -> deltgridtouser[1]);\n  \n  \n  /* This could in principle be done elsewhere..., but we can also place it here */\n  hdr -> nprof = hdr -> bsize1*hdr -> bsize2;\n  \n  /* Reserve memory */\n  /* if (!(hdr -> ori = (float *) malloc_engalmod(hdr -> bcsize1*hdr -> bsize2*hdr -> nsubs*sizeof(float)))) { */\n  /*   dev = 0; */\n  /*   anyout_tir(&dev, \"Not enough memory to hold a single cube\"); */\n  /*   goto error; */\n  /* } */\n  \n  /* if (!(hdr -> model = (float *) malloc_engalmod(hdr -> bcsize1*hdr -> bsize2*hdr -> nsubs*sizeof(float)))) { */\n  /*   anyout_tir(&dev, \"Not enough memory to hold two cubes\"); */\n  /*   goto error; */\n  /* } */\n  \n  /* Default is nothing */\n  /* for (i = 0; i < 200; ++i) */\n  /*   hdr -> outset[i] = ' '; */\n  /* hdr -> outset[200] = '\\0'; */\n  /* def = 5; */\n  \n  /* class = 1; */\n  /* i = 0; */\n  \n  /* sprintf(mes, \"Give output set\"); */\n  /* while(!(i)) { */\n  /*   userchar_tir(hdr -> outset, &class, &def, \"OUTSET=\", mes); */\n  /*   if (!strcmp(hdr -> inset, hdr -> outset)) { */\n  /* \tdev = 0; */\n  /* \tsprintf(mes, \"Must differ from inset name %s\", hdr -> inset); */\n  /* \tanyout_tir(&dev, mes); */\n  /* \tcancel_tir(startinfv -> arel, \"OUTSET=\"); */\n  /* \tdef = 5; */\n  /*   } */\n  /*   else */\n  /* \t++i; */\n  /* } */\n  /* termsinglestr(hdr -> outset); */\n  \n  /* If there is an outset, we will open it, else we terminate it */\n  /* if ((hdr -> outset[0])) { */\n  /*   i = 1; */\n  /* Copy the information of inset to outset prior to reading it */\n  /* gdsasn_tir(\"INSET=\", \"OUTSET\", &i); */\n  /* gdscss_tir(\"OUTSET\", blo, bhi); */\n  \n  /* def = 102; */\n  /* class = 0; */\n  /* gdsout_tir(hdr -> outset, outsubs, &hdr -> nsubs, &def, \"OUTSET\", \"mes\", &class , outaxperm, outaxcount, &maxnax); */\n  \n  /* We want to get the number to refresh the output cube */\n  if (simparse_scn_arel_readval_stringlist(startinfv -> arel, \"OUTSET\", \"Give output cube name.\", 0, NULL, 0, 1, 0, 0, &keypres, &nread, &nreturned, &stringlist))\n    goto error;\n  \n  if ((stringlist[0])) {\n    if (!(hdr -> outset = simparse_copystring(stringlist[0])))\n      goto error;\n  }\n  else {\n    if (!(hdr -> outset = simparse_copystring(\"\")))\n      goto error;\n  }\n  \n  freeparsed(stringlist);\n  \n  /* Default */\n  hdr -> outcubup = 1000000;\n  \n  def = 2;\n  nel = 1;\n  class = 0;\n  \n  while (!(class)) {\n    userint_tir(startinfv -> arel, &(hdr -> outcubup), &nel, &def, \"OUTCUBUP=\", mes);\n    \n    if (hdr -> outcubup < 1) {\n      sprintf(mes, \"Outcubup is least 1!\");\n      cancel_tir(startinfv -> arel, \"OUTCUBUP=\", 2);\n      def = 1;\n      class = 0;\n    }\n    else {\n      ++class;\n    }\n  }\n  \n  \n  \n  /* Finished */\n  return hdr;\n  \n error:\n  if (hdr)\n    destroy_hdrinf(hdr);\n  if (log)\n    /* Number of disks is irrelevant at this point */\n    destroy_loginf(log, 1);\n  if (stringlist)\n    freeparsed(stringlist);\n  \n  return NULL;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Creates a ringparms structure */\nstatic ringparms *create_ringparms(int ndisks)\n{\n  ringparms *create_ringparms;\n  int i;\n\n  if (!(create_ringparms = (ringparms *) malloc(sizeof(ringparms))))\n    goto error;\n\n  /* Put numbers in the size descriptors */\n\n  /* put number to ndisks member */\n  create_ringparms -> ndisks = ndisks;\n\n  /* Initialise all the pointers */\n  create_ringparms -> par = NULL;\n  create_ringparms -> oldpar = NULL;\n  create_ringparms -> chapar = NULL;\n  create_ringparms -> modpar = NULL;\n  create_ringparms -> gsl_interparray = NULL;\n  create_ringparms -> gsl_interp_accelarray = NULL;\n  create_ringparms -> smothcar = NULL;\n  create_ringparms -> gsl_indinterparray = NULL;\n  create_ringparms -> gsl_indinterp_accelarray = NULL;\n  create_ringparms -> smothindcar = NULL;\n  create_ringparms -> actarray = NULL;\n  create_ringparms -> actindar = NULL;\n  create_ringparms -> interar = NULL;\n  create_ringparms -> radar = NULL;\n  create_ringparms -> ltype = NULL;\n  create_ringparms -> cflux = NULL;\n  create_ringparms -> allnpoints = NULL;\n  create_ringparms -> fluxpoints = NULL;\n\n    create_ringparms -> sd        = NULL;\n    create_ringparms -> inf_sdisv = NULL;\n    create_ringparms -> inf_vradv = NULL;\n    create_ringparms -> inf_vverv = NULL;\n    create_ringparms -> inf_dvrov = NULL;\n    create_ringparms -> inf_dvrav = NULL;\n    create_ringparms -> inf_dvvev = NULL;\n    create_ringparms -> inf_vm0v  = NULL;\n    create_ringparms -> inf_vm1v  = NULL;\n    create_ringparms -> inf_vm2v  = NULL;\n    create_ringparms -> inf_vm3v  = NULL;\n    create_ringparms -> inf_vm4v  = NULL;\n    create_ringparms -> inf_ra1v  = NULL;\n    create_ringparms -> inf_ra2v  = NULL;\n    create_ringparms -> inf_ra3v  = NULL;\n    create_ringparms -> inf_ra4v  = NULL;\n    create_ringparms -> inf_ro1v  = NULL;\n    create_ringparms -> inf_ro2v  = NULL;\n    create_ringparms -> inf_ro3v  = NULL;\n    create_ringparms -> inf_ro4v  = NULL;\n    create_ringparms -> inf_wm0v  = NULL;\n    create_ringparms -> inf_wm1v  = NULL;\n    create_ringparms -> inf_wm2v  = NULL;\n    create_ringparms -> inf_wm3v  = NULL;\n    create_ringparms -> inf_wm4v  = NULL;\n    create_ringparms -> inf_ls0v  = NULL;\n    create_ringparms -> inf_lc0v  = NULL;\n    create_ringparms -> inf_smiv  = NULL;\n    create_ringparms -> inf_gauv  = NULL;\n    create_ringparms -> inf_aziv  = NULL;\n\n    if (!(create_ringparms -> sd        = (srd       **) malloc(create_ringparms -> ndisks*sizeof(srd      *)))) goto error; for (i = 0; i < create_ringparms -> ndisks; ++i) {create_ringparms ->       sd[i] = NULL;}\n    if (!(create_ringparms -> inf_sdisv = (inf_sdis **) malloc(create_ringparms -> ndisks*sizeof(inf_sdis *)))) goto error; for (i = 0; i < create_ringparms -> ndisks; ++i) {create_ringparms -> inf_sdisv[i] = NULL;}\n    if (!(create_ringparms -> inf_vradv = (inf_vrad **) malloc(create_ringparms -> ndisks*sizeof(inf_vrad *)))) goto error; for (i = 0; i < create_ringparms -> ndisks; ++i) {create_ringparms -> inf_vradv[i] = NULL;}\n    if (!(create_ringparms -> inf_vverv = (inf_vver **) malloc(create_ringparms -> ndisks*sizeof(inf_vver *)))) goto error; for (i = 0; i < create_ringparms -> ndisks; ++i) {create_ringparms -> inf_vverv[i] = NULL;}\n    if (!(create_ringparms -> inf_dvrov = (inf_dvro **) malloc(create_ringparms -> ndisks*sizeof(inf_dvro *)))) goto error; for (i = 0; i < create_ringparms -> ndisks; ++i) {create_ringparms -> inf_dvrov[i] = NULL;}\n    if (!(create_ringparms -> inf_dvrav = (inf_dvra **) malloc(create_ringparms -> ndisks*sizeof(inf_dvra *)))) goto error; for (i = 0; i < create_ringparms -> ndisks; ++i) {create_ringparms -> inf_dvrav[i] = NULL;}\n    if (!(create_ringparms -> inf_dvvev = (inf_dvve **) malloc(create_ringparms -> ndisks*sizeof(inf_dvve *)))) goto error; for (i = 0; i < create_ringparms -> ndisks; ++i) {create_ringparms -> inf_dvvev[i] = NULL;}\n    if (!(create_ringparms -> inf_vm0v  = (inf_vm0  **) malloc(create_ringparms -> ndisks*sizeof(inf_vm0  *)))) goto error; for (i = 0; i < create_ringparms -> ndisks; ++i) {create_ringparms ->  inf_vm0v[i] = NULL;}\n    if (!(create_ringparms -> inf_vm1v  = (inf_vm1  **) malloc(create_ringparms -> ndisks*sizeof(inf_vm1  *)))) goto error; for (i = 0; i < create_ringparms -> ndisks; ++i) {create_ringparms ->  inf_vm1v[i] = NULL;}\n    if (!(create_ringparms -> inf_vm2v  = (inf_vm2  **) malloc(create_ringparms -> ndisks*sizeof(inf_vm2  *)))) goto error; for (i = 0; i < create_ringparms -> ndisks; ++i) {create_ringparms ->  inf_vm2v[i] = NULL;}\n    if (!(create_ringparms -> inf_vm3v  = (inf_vm3  **) malloc(create_ringparms -> ndisks*sizeof(inf_vm3  *)))) goto error; for (i = 0; i < create_ringparms -> ndisks; ++i) {create_ringparms ->  inf_vm3v[i] = NULL;}\n    if (!(create_ringparms -> inf_vm4v  = (inf_vm4  **) malloc(create_ringparms -> ndisks*sizeof(inf_vm4  *)))) goto error; for (i = 0; i < create_ringparms -> ndisks; ++i) {create_ringparms ->  inf_vm4v[i] = NULL;}\n\n    if (!(create_ringparms -> inf_ra1v  = (inf_ra1  **) malloc(create_ringparms -> ndisks*sizeof(inf_ra1  *)))) goto error; for (i = 0; i < create_ringparms -> ndisks; ++i) {create_ringparms ->  inf_ra1v[i] = NULL;}\n    if (!(create_ringparms -> inf_ra2v  = (inf_ra2  **) malloc(create_ringparms -> ndisks*sizeof(inf_ra2  *)))) goto error; for (i = 0; i < create_ringparms -> ndisks; ++i) {create_ringparms ->  inf_ra2v[i] = NULL;}\n    if (!(create_ringparms -> inf_ra3v  = (inf_ra3  **) malloc(create_ringparms -> ndisks*sizeof(inf_ra3  *)))) goto error; for (i = 0; i < create_ringparms -> ndisks; ++i) {create_ringparms ->  inf_ra3v[i] = NULL;}\n    if (!(create_ringparms -> inf_ra4v  = (inf_ra4  **) malloc(create_ringparms -> ndisks*sizeof(inf_ra4  *)))) goto error; for (i = 0; i < create_ringparms -> ndisks; ++i) {create_ringparms ->  inf_ra4v[i] = NULL;}\n    if (!(create_ringparms -> inf_ro1v  = (inf_ro1  **) malloc(create_ringparms -> ndisks*sizeof(inf_ro1  *)))) goto error; for (i = 0; i < create_ringparms -> ndisks; ++i) {create_ringparms ->  inf_ro1v[i] = NULL;}\n    if (!(create_ringparms -> inf_ro2v  = (inf_ro2  **) malloc(create_ringparms -> ndisks*sizeof(inf_ro2  *)))) goto error; for (i = 0; i < create_ringparms -> ndisks; ++i) {create_ringparms ->  inf_ro2v[i] = NULL;}\n    if (!(create_ringparms -> inf_ro3v  = (inf_ro3  **) malloc(create_ringparms -> ndisks*sizeof(inf_ro3  *)))) goto error; for (i = 0; i < create_ringparms -> ndisks; ++i) {create_ringparms ->  inf_ro3v[i] = NULL;}\n    if (!(create_ringparms -> inf_ro4v  = (inf_ro4  **) malloc(create_ringparms -> ndisks*sizeof(inf_ro4  *)))) goto error; for (i = 0; i < create_ringparms -> ndisks; ++i) {create_ringparms ->  inf_ro4v[i] = NULL;}\n\n    if (!(create_ringparms -> inf_wm0v  = (inf_wm0  **) malloc(create_ringparms -> ndisks*sizeof(inf_wm0  *)))) goto error; for (i = 0; i < create_ringparms -> ndisks; ++i) {create_ringparms ->  inf_wm0v[i] = NULL;}\n    if (!(create_ringparms -> inf_wm1v  = (inf_wm1  **) malloc(create_ringparms -> ndisks*sizeof(inf_wm1  *)))) goto error; for (i = 0; i < create_ringparms -> ndisks; ++i) {create_ringparms ->  inf_wm1v[i] = NULL;}\n    if (!(create_ringparms -> inf_wm2v  = (inf_wm2  **) malloc(create_ringparms -> ndisks*sizeof(inf_wm2  *)))) goto error; for (i = 0; i < create_ringparms -> ndisks; ++i) {create_ringparms ->  inf_wm2v[i] = NULL;}\n    if (!(create_ringparms -> inf_wm3v  = (inf_wm3  **) malloc(create_ringparms -> ndisks*sizeof(inf_wm3  *)))) goto error; for (i = 0; i < create_ringparms -> ndisks; ++i) {create_ringparms ->  inf_wm3v[i] = NULL;}\n    if (!(create_ringparms -> inf_wm4v  = (inf_wm4  **) malloc(create_ringparms -> ndisks*sizeof(inf_wm4  *)))) goto error; for (i = 0; i < create_ringparms -> ndisks; ++i) {create_ringparms ->  inf_wm4v[i] = NULL;}\n    if (!(create_ringparms -> inf_ls0v  = (inf_ls0  **) malloc(create_ringparms -> ndisks*sizeof(inf_ls0  *)))) goto error; for (i = 0; i < create_ringparms -> ndisks; ++i) {create_ringparms ->  inf_ls0v[i] = NULL;}\n    if (!(create_ringparms -> inf_lc0v  = (inf_lc0  **) malloc(create_ringparms -> ndisks*sizeof(inf_lc0  *)))) goto error; for (i = 0; i < create_ringparms -> ndisks; ++i) {create_ringparms ->  inf_lc0v[i] = NULL;}\n    if (!(create_ringparms -> inf_smiv  = (inf_smi  **) malloc(create_ringparms -> ndisks*sizeof(inf_smi  *)))) goto error; for (i = 0; i < create_ringparms -> ndisks; ++i) {create_ringparms ->  inf_smiv[i] = NULL;}\n    if (!(create_ringparms -> inf_gauv  = (inf_gau  **) malloc(create_ringparms -> ndisks*sizeof(inf_gau  *)))) goto error; for (i = 0; i < create_ringparms -> ndisks; ++i) {create_ringparms ->  inf_gauv[i] = NULL;}\n    if (!(create_ringparms -> inf_aziv  = (inf_azi  **) malloc(create_ringparms -> ndisks*sizeof(inf_azi  *)))) goto error; for (i = 0; i < create_ringparms -> ndisks; ++i) {create_ringparms ->  inf_aziv[i] = NULL;}\n\n  /* Now allocate more memory */\n  if (!(create_ringparms -> ltype = (int *) malloc(create_ringparms -> ndisks*sizeof(int))))\n    goto error;\n\n  if (!(create_ringparms -> cflux = (double *) malloc(create_ringparms -> ndisks*sizeof(double))))\n    goto error;\n  if (!(create_ringparms -> allnpoints = (int *) malloc(create_ringparms -> ndisks*sizeof(int))))\n    goto error;\n  if (!(create_ringparms -> fluxpoints = (long *) malloc(create_ringparms -> ndisks*sizeof(long))))\n    goto error;\n\n\n  return create_ringparms;\n  \n error:\n  destroy_ringparms(create_ringparms);\n  return NULL;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Destroys a ringparms structure */\nvoid destroy_ringparms(ringparms *prm)\n{  \n\n  int i;\n\n  /* Check if it is there */\n  if (!(prm))\n    return;\n\n  if ((prm -> par))\n    free(prm -> par);\n  if ((prm -> oldpar))\n    free(prm -> oldpar);\n  if ((prm -> chapar))\n    free(prm -> chapar);\n\n  if ((prm -> gsl_interparray)) {\n    for (i = 0; i < prm -> ndisks*NDPARAMS; ++i) {\n\tif ((prm -> gsl_interparray[i]))\n\t  gsl_interp_free(prm -> gsl_interparray[i]);\n    }\n    free(prm -> gsl_interparray);\n  }\n  if ((prm -> gsl_interp_accelarray)) {\n    for (i = 0; i < prm -> ndisks*NDPARAMS; ++i) {\n      if ((prm -> gsl_interp_accelarray[i]))\n\tgsl_interp_accel_free(prm -> gsl_interp_accelarray[i]);\n    }\n    free(prm -> gsl_interp_accelarray);\n  }\n    \n  if ((prm -> smothcar))\n    free(prm -> smothcar);\n  if ((prm -> gsl_indinterparray)) {\n    for (i = 0; i < prm -> ndisks*NDPARAMS; ++i) {\n\tif ((prm -> gsl_indinterparray[i]))\n\t  gsl_interp_free(prm -> gsl_indinterparray[i]);\n    }\n    free(prm -> gsl_indinterparray);\n  }\n  if ((prm -> gsl_indinterp_accelarray)) {\n    for (i = 0; i < prm -> ndisks*NDPARAMS; ++i) {\n      if ((prm -> gsl_indinterp_accelarray[i]))\n\tgsl_interp_accel_free(prm -> gsl_indinterp_accelarray[i]);\n    }\n    free(prm -> gsl_indinterp_accelarray);\n  }\n  if ((prm -> smothindcar))\n    free(prm -> smothindcar);\n  if ((prm -> actarray))\n    free(prm -> actarray);\n  if ((prm -> actindar))\n    free(prm -> actindar);\n  if ((prm -> interar  ))\n    free(prm -> interar  );\n  if ((prm -> radar   ))\n    free(prm -> radar   );\n\n  if (prm -> ltype)\n    free(prm -> ltype);\n  if (prm -> cflux)\n    free(prm -> cflux);\n  \n  /* GJnew */\n  if (prm -> allnpoints)\n    free(prm -> allnpoints);\n  if (prm -> fluxpoints)\n    free(prm -> fluxpoints);\n\n  if (prm -> sd        != NULL) {for (i = 0; i < prm -> ndisks; ++i) {if (prm -> sd[i]        != NULL) destroy_srd(prm ->  sd[i], prm -> nr);}  free(prm -> sd);}\n  if (prm -> inf_sdisv != NULL) {for (i = 0; i < prm -> ndisks; ++i) {if (prm -> inf_sdisv[i] != NULL) destroy_inf_sdis(prm -> inf_sdisv[i]);}  free(prm -> inf_sdisv);}\n  if (prm -> inf_vradv != NULL) {for (i = 0; i < prm -> ndisks; ++i) {if (prm -> inf_vradv[i] != NULL) destroy_inf_vrad(prm -> inf_vradv[i]);}  free(prm -> inf_vradv);}\n  if (prm -> inf_vverv != NULL) {for (i = 0; i < prm -> ndisks; ++i) {if (prm -> inf_vverv[i] != NULL) destroy_inf_vver(prm -> inf_vverv[i]);}  free(prm -> inf_vverv);}\n  if (prm -> inf_dvrov != NULL) {for (i = 0; i < prm -> ndisks; ++i) {if (prm -> inf_dvrov[i] != NULL) destroy_inf_dvro(prm -> inf_dvrov[i]);}  free(prm -> inf_dvrov);}\n  if (prm -> inf_dvrav != NULL) {for (i = 0; i < prm -> ndisks; ++i) {if (prm -> inf_dvrav[i] != NULL) destroy_inf_dvra(prm -> inf_dvrav[i]);}  free(prm -> inf_dvrav);}\n  if (prm -> inf_dvvev != NULL) {for (i = 0; i < prm -> ndisks; ++i) {if (prm -> inf_dvvev[i] != NULL) destroy_inf_dvve(prm -> inf_dvvev[i]);}  free(prm -> inf_dvvev);}\n  if (prm -> inf_vm0v  != NULL) {for (i = 0; i < prm -> ndisks; ++i) {if (prm ->  inf_vm0v[i] != NULL) destroy_inf_vm0(prm ->   inf_vm0v[i]);}  free(prm -> inf_vm0v);}\n  if (prm -> inf_vm1v  != NULL) {for (i = 0; i < prm -> ndisks; ++i) {if (prm ->  inf_vm1v[i] != NULL) destroy_inf_vm1(prm ->   inf_vm1v[i]);}  free(prm -> inf_vm1v);}\n  if (prm -> inf_vm2v  != NULL) {for (i = 0; i < prm -> ndisks; ++i) {if (prm ->  inf_vm2v[i] != NULL) destroy_inf_vm2(prm ->   inf_vm2v[i]);}  free(prm -> inf_vm2v);}\n  if (prm -> inf_vm3v  != NULL) {for (i = 0; i < prm -> ndisks; ++i) {if (prm ->  inf_vm3v[i] != NULL) destroy_inf_vm3(prm ->   inf_vm3v[i]);}  free(prm -> inf_vm3v);}\n  if (prm -> inf_vm4v  != NULL) {for (i = 0; i < prm -> ndisks; ++i) {if (prm ->  inf_vm4v[i] != NULL) destroy_inf_vm4(prm ->   inf_vm4v[i]);}  free(prm -> inf_vm4v);}\n\n  if (prm -> inf_ra1v  != NULL) {for (i = 0; i < prm -> ndisks; ++i) {if (prm ->  inf_ra1v[i] != NULL) destroy_inf_ra1(prm ->   inf_ra1v[i]);}  free(prm -> inf_ra1v);}\n  if (prm -> inf_ra2v  != NULL) {for (i = 0; i < prm -> ndisks; ++i) {if (prm ->  inf_ra2v[i] != NULL) destroy_inf_ra2(prm ->   inf_ra2v[i]);}  free(prm -> inf_ra2v);}\n  if (prm -> inf_ra3v  != NULL) {for (i = 0; i < prm -> ndisks; ++i) {if (prm ->  inf_ra3v[i] != NULL) destroy_inf_ra3(prm ->   inf_ra3v[i]);}  free(prm -> inf_ra3v);}\n  if (prm -> inf_ra4v  != NULL) {for (i = 0; i < prm -> ndisks; ++i) {if (prm ->  inf_ra4v[i] != NULL) destroy_inf_ra4(prm ->   inf_ra4v[i]);}  free(prm -> inf_ra4v);}\n  if (prm -> inf_ro1v  != NULL) {for (i = 0; i < prm -> ndisks; ++i) {if (prm ->  inf_ro1v[i] != NULL) destroy_inf_ro1(prm ->   inf_ro1v[i]);}  free(prm -> inf_ro1v);}\n  if (prm -> inf_ro2v  != NULL) {for (i = 0; i < prm -> ndisks; ++i) {if (prm ->  inf_ro2v[i] != NULL) destroy_inf_ro2(prm ->   inf_ro2v[i]);}  free(prm -> inf_ro2v);}\n  if (prm -> inf_ro3v  != NULL) {for (i = 0; i < prm -> ndisks; ++i) {if (prm ->  inf_ro3v[i] != NULL) destroy_inf_ro3(prm ->   inf_ro3v[i]);}  free(prm -> inf_ro3v);}\n  if (prm -> inf_ro4v  != NULL) {for (i = 0; i < prm -> ndisks; ++i) {if (prm ->  inf_ro4v[i] != NULL) destroy_inf_ro4(prm ->   inf_ro4v[i]);}  free(prm -> inf_ro4v);}\n  if (prm -> inf_wm0v  != NULL) {for (i = 0; i < prm -> ndisks; ++i) {if (prm ->  inf_wm0v[i] != NULL) destroy_inf_wm0(prm ->   inf_wm0v[i]);}  free(prm -> inf_wm0v);}\n  if (prm -> inf_wm1v  != NULL) {for (i = 0; i < prm -> ndisks; ++i) {if (prm ->  inf_wm1v[i] != NULL) destroy_inf_wm1(prm ->   inf_wm1v[i]);}  free(prm -> inf_wm1v);}\n  if (prm -> inf_wm2v  != NULL) {for (i = 0; i < prm -> ndisks; ++i) {if (prm ->  inf_wm2v[i] != NULL) destroy_inf_wm2(prm ->   inf_wm2v[i]);}  free(prm -> inf_wm2v);}\n  if (prm -> inf_wm3v  != NULL) {for (i = 0; i < prm -> ndisks; ++i) {if (prm ->  inf_wm3v[i] != NULL) destroy_inf_wm3(prm ->   inf_wm3v[i]);}  free(prm -> inf_wm3v);}\n  if (prm -> inf_wm4v  != NULL) {for (i = 0; i < prm -> ndisks; ++i) {if (prm ->  inf_wm4v[i] != NULL) destroy_inf_wm4(prm ->   inf_wm4v[i]);}  free(prm -> inf_wm4v);}\n  if (prm -> inf_ls0v  != NULL) {for (i = 0; i < prm -> ndisks; ++i) {if (prm ->  inf_ls0v[i] != NULL) destroy_inf_ls0(prm ->   inf_ls0v[i]);}  free(prm -> inf_ls0v);}\n  if (prm -> inf_lc0v  != NULL) {for (i = 0; i < prm -> ndisks; ++i) {if (prm ->  inf_lc0v[i] != NULL) destroy_inf_lc0(prm ->   inf_lc0v[i]);}  free(prm -> inf_lc0v);}\n  if (prm -> inf_smiv  != NULL) {for (i = 0; i < prm -> ndisks; ++i) {if (prm ->  inf_smiv[i] != NULL) destroy_inf_smi(prm ->   inf_smiv[i]);}  free(prm -> inf_smiv);}\n  if (prm -> inf_gauv  != NULL) {for (i = 0; i < prm -> ndisks; ++i) {if (prm ->  inf_gauv[i] != NULL) destroy_inf_gau(prm ->   inf_gauv[i]);}  free(prm -> inf_gauv);}\n  if (prm -> inf_aziv  != NULL) {for (i = 0; i < prm -> ndisks; ++i) {if (prm ->  inf_aziv[i] != NULL) destroy_inf_azi(prm ->   inf_aziv[i]);}  free(prm -> inf_aziv);}\n\n\n  for (i = 0; i < prm -> ndisks; ++i) {\n/*     if((prm -> permrandstr[i])) */\n/*       free(prm -> permrandstr[i]); */\n/*     if((prm -> inf_sdisv[i])) */\n/*       destroy_inf_sdis(prm -> inf_sdisv[i]); */\n/*      if((prm -> inf_vradv[i])) */\n/*       destroy_inf_vrad(prm -> inf_vradv[i]); */\n/*     if((prm -> inf_vverv[i])) */\n/*       destroy_inf_vver(prm -> inf_vverv[i]); */\n/*     if((prm -> inf_dvrov[i])) */\n/*       destroy_inf_dvro(prm -> inf_dvrov[i]); */\n/*     if((prm -> inf_dvrav[i])) */\n/*       destroy_inf_dvra(prm -> inf_dvrav[i]); */\n/*     if((prm -> inf_dvvev[i])) */\n/*       destroy_inf_dvve(prm -> inf_dvvev[i]); */\n/*     if((prm ->  inf_vm1v[i])) */\n/*       destroy_inf_vm1(prm ->  inf_vm1v[i]); */\n/*     if((prm ->  inf_vm0v[i] )) */\n/*       destroy_inf_vm0 (prm ->  inf_vm0v[i] ); */\n/*    if((prm ->  inf_vm2v[i])) */\n/*       destroy_inf_vm2(prm ->  inf_vm2v[i]); */\n/*     if((prm ->  inf_vm3v[i])) */\n/*       destroy_inf_vm3(prm ->  inf_vm3v[i]); */\n/*     if((prm ->  inf_vm4v[i])) */\n/*       destroy_inf_vm4(prm ->  inf_vm4v[i]); */\n/*     if((prm ->  inf_wm1v[i])) */\n/*       destroy_inf_wm1(prm ->  inf_wm1v[i]); */\n/*     if((prm ->  inf_wm0v[i] )) */\n/*       destroy_inf_wm0 (prm ->  inf_wm0v[i] ); */\n/*     if((prm ->  inf_wm2v[i])) */\n/*       destroy_inf_wm2(prm ->  inf_wm2v[i]); */\n/*     if((prm ->  inf_wm3v[i])) */\n/*       destroy_inf_wm3(prm ->  inf_wm3v[i]); */\n/*     if((prm ->  inf_wm4v[i])) */\n/*       destroy_inf_wm4(prm ->  inf_wm4v[i]); */\n/*     if((prm ->  inf_ls0v[i] )) */\n/*       destroy_inf_ls0 (prm ->  inf_ls0v[i] ); */\n/*     if((prm ->  inf_lc0v[i] )) */\n/*       destroy_inf_lc0 (prm ->  inf_lc0v[i] ); */\n/*     if((prm ->  inf_smiv[i] )) */\n/*       destroy_inf_smi (prm ->  inf_smiv[i] ); */\n/*     if((prm ->  inf_gauv[i] )) */\n/*       destroy_inf_gau (prm ->  inf_gauv[i] ); */\n/*     if((prm ->  inf_aziv[i] )) */\n/*       destroy_inf_azi (prm ->  inf_aziv[i] );    */\n  }\n  if (prm -> modpar != NULL)\n    free(prm -> modpar);\n  free(prm);\n\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Creates a list of subring descriptors with n elements */\nstatic srd *create_srd(int n)\n{\n  int i;\n\n  srd *sd;\n  if (!(sd = (srd *) malloc(n*sizeof(srd))))\n    return NULL;\n\n  for (i = 0; i < n; ++i) {\n    (sd+i) -> pl = NULL;\n#ifdef PBCORR\n    (sd+i) -> pbfac = NULL;\n#endif\n    (sd+i) -> permrandstr = NULL;\n    (sd+i) -> randstr = NULL;\n    (sd+i) -> grandstr[0] = NULL;\n    (sd+i) -> grandstr[1] = NULL;\n    (sd+i) -> grandstr[2] = NULL;\n    (sd+i) -> grandstr[3] = NULL;\n    (sd+i) -> srandstr = NULL;\n\n    /* There is only one dispersion */\n    (sd+i) -> nsubcl = 1;\n    (sd+i) -> nsubclinv = 1.0;\n    (sd+i) -> y2 = -1024.0;\n  }\n  return sd;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Creates a list of subring descriptors with n elements */\nstatic void destroy_srd(srd *sd, int n)\n{\n  int i;\n\n  if (!(sd))\n    return;\n\n  for (i = 0; i < n; ++i) {\n    free(sd[i].pl);\n\n#ifdef PBCORR\n    if (sd[i].pbfac)\n      free(sd[i].pbfac);\n#endif\n\n    if (sd[i].permrandstr)\n      free(sd[i].permrandstr);\n    if (sd[i].randstr)\n      free(sd[i].randstr);\n    if (sd[i].grandstr[0])\n      free(sd[i].grandstr[0]);\n    if (sd[i].grandstr[1])\n      free(sd[i].grandstr[1]);\n    if (sd[i].grandstr[2])\n      free(sd[i].grandstr[2]);\n    if (sd[i].grandstr[3])\n      free(sd[i].grandstr[3]);\n    if (sd[i].srandstr)\n      free(sd[i].srandstr);\n  }\n  free(sd);\n\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Fill the ringparms struct from the input */\nstatic ringparms *get_ringparms(startinf *startinfv, loginf *log, hdrinf *hdr, ringparms *ringparmsv)\n{\n  ringparms *rpm;\n  double globin[3];  /* For the conversion of coordinates in map units */\n  double globout[3]; /* For the conversion of coordinates in map units */\n  \n  /* Private control and changing variables */\n  int def;      /* Any default mode */\n  int nel;      /* Number of elements */\n  int err;      /* Error code */\n  int dummy;\n  char mes[81];  /* Any message */\n  char placer[10];\n  int inty, indinty; /* interpolation type */\n  const gsl_interp_type * intytype; /* same, only internal to gsl */\n  const gsl_interp_type * indintytype; /* same, only internal to gsl */\n\n  int i,j = 0; /* Simple control variables */\n  int disk; /* number of the disk */\n  /* Read values that are needed only in this module */\n  int mode; /* For memory handling */\n  int ndisks;\n  int pcondisp, condisp;\n\n/* primary beam stuff */\n#ifdef PBCORR\n  int pbtel;\n  double pbrefpix[2];\n  double pbreffreq;\n  double pbdoublev1, pbdoublev2, pbradius, pbwsrtconst;\n  int dev = 1;\n#endif\n\n  /* Get the number of disks */\n  /* Default */\n  if (startinfv -> firstrun) {\n  def = 2;\n  ndisks = 0;\n  nel = 1;\n  \n  userint_tir(startinfv -> arel, &ndisks, &nel, &def, \"NDISKS=\", mes);\n  \n  if (ndisks < 1)\n    ndisks = NDISKS;\n  \n  /* Get the struct */\n  if (!(rpm = create_ringparms(ndisks))) \n    goto error;\n  }\n  else {\n    rpm = ringparmsv;\n  }\n\n  /* Activate the logfile info, the reason that the function is called here is that the number of disks is required */\n\n  /* Now we try to open the table object with the logfile name */\n  if (activateftstab(startinfv, log, rpm)) {\n    goto error;\n  }\n\n  if (startinfv -> firstrun) {\n    /* Get the number of rings */\n    /* Default */\n    def = 0;\n    \n    i = 0;\n    sprintf(mes, \"Give number of rings.\");\n    while (!(i)) {\n      nel = 1;\n      userint_tir(startinfv -> arel, &rpm -> nur, &nel, &def, \"NUR=\", mes);\n      \n      if (rpm -> nur < 2) {\n\tsprintf(mes, \"At least 2!\");\n\tcancel_tir(startinfv -> arel, \"NUR=\", 2);\n\ti = 0;\n      }\n      else {\n\t\n\t/* Do some allocation that hides some variables in this function */\n\tif (!(rpm -> par = (double *) malloc((rpm -> nur*(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)+NSPARAMS)*sizeof(double))))\n\t  goto error;\n\t/* Do some allocation that hides some variables in this function */\n\tif (!(rpm -> oldpar = (double *) malloc((rpm -> nur*(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)+NSPARAMS)*sizeof(double))))\n\t  goto error;\n\t/* Do some allocation that hides some variables in this function, same size as par and oldpar to ease indexing */\n\tif (!(rpm -> chapar = (int *) malloc((rpm -> nur*(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)+NSPARAMS)*sizeof(int))))\n\t  goto error;\n\tfor (j = 0; j < (rpm -> nur*(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)+NSPARAMS); ++j)\n\t  rpm -> chapar[j] = 0;\n\n\t/* Allocate the interpolation structures */\n\tif (!(rpm -> gsl_interparray = (gsl_interp **) malloc(rpm -> ndisks*NDPARAMS*sizeof(gsl_interp *))))\n\t  goto error;\n\tfor (j = 0; j < rpm -> ndisks*NDPARAMS; ++j)\n\t  rpm -> gsl_interparray[j] = NULL;\n\tif (!(rpm -> gsl_interp_accelarray = (gsl_interp_accel **) malloc(rpm -> ndisks*NDPARAMS*sizeof(gsl_interp_accel *))))\n\t      goto error;\t\n\tfor (j = 0; j < rpm -> ndisks*NDPARAMS; ++j)\n\t  rpm -> gsl_interp_accelarray[j] = NULL;\n\tif (!(rpm -> smothcar = (int *) malloc(rpm -> ndisks*NDPARAMS*sizeof(int))))\n\t      goto error;\n\tif (!(rpm -> gsl_indinterparray = (gsl_interp **) malloc(rpm -> ndisks*NDPARAMS*sizeof(gsl_interp *))))\n\t  goto error;\n\tfor (j = 0; j < rpm -> ndisks*NDPARAMS; ++j)\n\t  rpm -> gsl_indinterparray[j] = NULL;\n\tif (!(rpm -> gsl_indinterp_accelarray = (gsl_interp_accel **) malloc(rpm -> ndisks*NDPARAMS*sizeof(gsl_interp_accel *))))\n\t      goto error;\t\n\tfor (j = 0; j < rpm -> ndisks*NDPARAMS; ++j)\n\t  rpm -> gsl_indinterp_accelarray[j] = NULL;\n\tif (!(rpm -> smothindcar = (int *) malloc(rpm -> ndisks*NDPARAMS*sizeof(int))))\n\t      goto error;\n\tif (!(rpm -> actarray = (int *) malloc(rpm -> nur * sizeof(int))))\n\t  goto error;\n\tif (!(rpm -> actindar = (int *) malloc(rpm -> nur * sizeof(int))))\n\t  goto error;\n\tif (!(rpm -> interar = (double *) malloc(rpm -> nur * sizeof(double))))\n\t  goto error;\n\tif (!(rpm -> radar = (double *) malloc(rpm -> nur * sizeof(double))))\n\t  goto error;\n\t\n\t++i;\n      }\n    }\n\n    /* The output array contains rpm -> maxparnur + 3 fields (3 -> chisquare, accept, number) */\n    if (!(log -> outarray = (double *) malloc (((NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+NSPARAMS+OUTTABNR) * sizeof(double))))\n      goto error;\n    if (!(log -> grid     = (double *) malloc (((NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+NSPARAMS+OUTTABNR) * sizeof(double))))\n      goto error;\n    if (!(log -> radius   = (double *) malloc (((NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+NSPARAMS+OUTTABNR) * sizeof(double))))\n      goto error;\n    if (!(log -> regist   = (double *) malloc (((NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+NSPARAMS+OUTTABNR) * sizeof(double))))\n      goto error;\n    \n    /* Get the subring width in grid units */\n    /* Default */\n    rpm -> radsep = 0.75;\n    \n    sprintf(mes, \"Give subring width (grids)\");\n    def = 2;\n    nel = 1;\n    err = 0;\n    while (!(err)) {\n      userdble_tir(startinfv -> arel, &rpm -> radsep, &nel, &def, \"RADSEP=\", mes);\n      if (rpm -> radsep <= 0.0) {\n\tsprintf(mes, \"Must be positive!\");\n\tcancel_tir(startinfv -> arel, \"RADSEP=\", 2);\n\tdef = 1;\n      }\n      else \n\terr = 1;\n    }\n\n    /* Get the default interpolation method */\n    /* 0: linear, 1: natural spline, default 0 */\n    inty = INTERP_LINEAR;\n    \n    sprintf(mes, \"Give default interpolation type\");\n    def = 2;\n    nel = 1;\n    err = 0;\n    while (!(err)) {\n      userint_tir(startinfv -> arel, &inty, &nel, &def, \"INTY=\", mes);\n      if (inty < 0 || inty >= INTERP_NUMBER) {\n\tsprintf(mes, \"Must lie between %i and %i!\", 0, INTERP_NUMBER-1);\n\tcancel_tir(startinfv -> arel, \"INTY=\", 2);\n\tdef = 1;\n      }\n      else \n\terr = 1;\n    }\n\n    /* Now allocate all the interpolation structs and \"accelerators\" */\n    switch (inty) {\n    case INTERP_LINEAR:\n      intytype = gsl_interp_linear;\n      break;\n\n    case INTERP_CSPLINE:\n      if (rpm -> nur > 2){\n\tintytype = gsl_interp_cspline;\n      }\n      else {\n\tsprintf(mes, \"Must have at least 3 radii for spline, using linear\");\n\tanyout_tir(&err, mes);\n\tintytype = gsl_interp_linear;\n      }\n      break;\n    \n    case INTERP_AKIMA:\n      if (rpm -> nur > 4) {\n\tintytype = gsl_interp_akima;\n      }\n      else {\n\tsprintf(mes, \"Must have at least 5 radii for Akima\");\n\tanyout_tir(&err, mes);\n\tif (rpm -> nur > 2) {\n\t  sprintf(mes, \"Using natural cubic spline\");\n\t  anyout_tir(&err, mes);\n\t  intytype = gsl_interp_cspline;\n\t}\n\telse {\n\t  sprintf(mes, \"Using linear\");\n\t  anyout_tir(&err, mes);\n\t  intytype = gsl_interp_linear;\n\t}\n      }\n      break;\n\n    /* No real default */\n    default:\n      break;\n    }\n\n    /* Real allocation here */\n    for (i = 0; i < rpm -> ndisks*NDPARAMS; ++i) {\n      if (!(rpm -> gsl_interparray[i] = gsl_interp_alloc(intytype, rpm -> nur)))\n\tgoto error;\n      /* printf(\"%s\"); */\n\n      if (!(rpm -> gsl_interp_accelarray[i] = gsl_interp_accel_alloc()))\n\tgoto error;\n      rpm -> smothcar[i] = inty;\n    }\n\n        /* Get the default interpolation method */\n    /* 0: linear, 1: natural spline, default 0 */\n    indinty = inty;\n    \n    sprintf(mes, \"Give default interpolation type\");\n    def = 2;\n    nel = 1;\n    err = 0;\n    while (!(err)) {\n      userint_tir(startinfv -> arel, &indinty, &nel, &def, \"INDINTY=\", mes);\n      if (indinty < 0 || indinty >= INTERP_NUMBER) {\n\tsprintf(mes, \"Must lie between %i and %i!\", 0, INTERP_NUMBER-1);\n\tcancel_tir(startinfv -> arel, \"INDINTY=\", 2);\n\tdef = 1;\n      }\n      else \n\terr = 1;\n    }\n\n    /* Now allocate all the interpolation structs and \"accelerators\" */\n    switch (indinty) {\n    case INTERP_LINEAR:\n      indintytype = gsl_interp_linear;\n      break;\n\n    case INTERP_CSPLINE:\n      if (rpm -> nur > 2)\n\tindintytype = gsl_interp_cspline;\n      else {\n\tsprintf(mes, \"Must have at least 3 radii for spline, using linear\");\n\tanyout_tir(&err, mes);\n\tindintytype = gsl_interp_linear;\n      }\n      break;\n    \n    case INTERP_AKIMA:\n      if (rpm -> nur > 4) {\n\tindintytype = gsl_interp_akima;\n      }\n      else {\n\tsprintf(mes, \"Must have at least 5 radii for Akima\");\n\tanyout_tir(&err, mes);\n\tif (rpm -> nur > 2) {\n\t  sprintf(mes, \"Using natural cubic spline\");\n\t  anyout_tir(&err, mes);\n\t  indintytype = gsl_interp_cspline;\n\t}\n\telse {\n\t  sprintf(mes, \"Using linear\");\n\t  anyout_tir(&err, mes);\n\t  indintytype = gsl_interp_linear;\n\t}\n      }\n      break;\n\n    /* No real default */\n    default:\n      break;\n    }\n\n    /* Real allocation here */\n    for (i = 0; i < rpm -> ndisks*NDPARAMS; ++i) {\n      if (!(rpm -> gsl_indinterparray[i] = gsl_interp_alloc(indintytype, rpm -> nur)))\n\tgoto error;\n      /* printf(\"%s\"); */\n\n      if (!(rpm -> gsl_indinterp_accelarray[i] = gsl_interp_accel_alloc()))\n\tgoto error;\n      rpm -> smothindcar[i] = indinty;\n    }\n\n    /* Now get all sorts of parameters */\n    \n    /* Radii is the most complicated */\n    err = 0;\n    while (!(err)) {\n      get_parameter_double(startinfv, log, hdr, rpm, \"Give Radii. (arcsec)\", \"RADI=\", PRADI, 4);\n      \n      /* Enforce the first radius to be 0 */\n      if (rpm -> par[0] != 0.0) {\n\t\t  sprintf(mes, \"First radius has to be 0.0\");\n\t\t  anyout_tir(&err, mes);\n\t\t  \n\t\t  /* The difference to reject is unclear to me */  \n\t\t  cancel_tir(startinfv -> arel, \"RADI=\", 2);\n      }\n      else {\n\t\t  \n\t\t  /* Now check whether the modpar array can be constructed */\n\t\t  /* Identify the number of subrings, the max radius of a subring is the max radius in parameter struct plus the half of the width of a subring, which is ususally 0.75 pixels  */\n\t\t  rpm -> nr = ((int) (rpm -> par[(PRADI+1)*rpm -> nur-1]/rpm -> radsep-0.5))+1;\n\t\t  \n\t\t  /* ndisk construction */\n\t\t  /* Allocation of subring array */\n\t\t  if (!(rpm -> modpar = (float *) malloc((NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nr*sizeof(float))))\n\t\t\t goto error;\n\t\t  \n\t\t  err = 1;\n\t\t  for (i = 1; i < rpm -> nur; ++i) {\n\t\t\t \n\t\t\t /* Check if the choice of radii is sensible */\n\t\t\t if ((rpm -> par[PRADI*rpm -> nur+i-1]+rpm -> radsep) >= (rpm -> par[PRADI*rpm -> nur+i])) {\n\t\t\t\tsprintf(mes, \"Radius separation too small or radii not in increasing order.\");\n\t\t\t\terr = 0;\n\t\t\t\tanyout_tir(&err, mes);\n\t\t\t\tcancel_tir(startinfv -> arel, \"RADI=\", 2);\n\t\t\t\tbreak;\n\t\t\t }\n\t\t  }\n      }\n    }\n  }\n  /* other parameters */\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give circular velocities. (km/s)\",                                \"VROT=\", PVROT, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give radial velocities. (km/s)\",                                  \"VRAD=\", PVRAD, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give vertical velocities. (km/s)\",                                \"VVER=\", PVVER, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give vertical gradient of circular velocities. (km/s)\",           \"DVRO=\", PDVRO, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give vertical gradient of radial velocities. (km/s)\",             \"DVRA=\", PDVRA, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give vertical gradient of vertical velocities. (km/s)\",           \"DVVE=\", PDVVE, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give start height for change of circular velocities. (km/s)\",     \"ZDRO=\", PZDRO, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give start height for change of radial velocities. (km/s)\",       \"ZDRA=\", PZDRA, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give start height for change of vertical velocities. (km/s)\",     \"ZDVE=\", PZDVE, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give dispersion (SDIS) of rings. (km/s)\",                         \"SDIS=\", PSDIS, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give number of sub-clouds\",                                       \"CLNR=\", PCLNR, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give radial velocity term\",                                       \"VM0A=\", PVM0A, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give velocity m1 term, amp  \",                                    \"VM1A=\", PVM1A, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give velocity m1 term, phase\",                                    \"VM1P=\", PVM1P, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give velocity m2 term, amp  \",                                    \"VM2A=\", PVM2A, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give velocity m2 term, phase\",                                    \"VM2P=\", PVM2P, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give velocity m3 term, amp  \",                                    \"VM3A=\", PVM3A, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give velocity m3 term, phase\",                                    \"VM3P=\", PVM3P, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give velocity m4 term, amp  \",                                    \"VM4A=\", PVM4A, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give velocity m4 term, phase\",                                    \"VM4P=\", PVM4P, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give tangential velocity m1 term, phase\",                         \"RO1A=\", PRO1A, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give tangential velocity m1 term, phase\",                         \"RO1P=\", PRO1P, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give tangential velocity m2 term, amp  \",                         \"RO2A=\", PRO2A, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give tangential velocity m2 term, phase\",                         \"RO2P=\", PRO2P, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give tangential velocity m3 term, amp  \",                         \"RO3A=\", PRO3A, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give tangential velocity m3 term, phase\",                         \"RO3P=\", PRO3P, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give tangential velocity m4 term, amp  \",                         \"RO4A=\", PRO4A, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give tangential velocity m4 term, phase\",                         \"RO4P=\", PRO4P, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give radial velocity m1 term, phase\",                             \"RA1A=\", PRA1A, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give radial velocity m1 term, phase\",                             \"RA1P=\", PRA1P, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give radial velocity m2 term, amp  \",                             \"RA2A=\", PRA2A, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give radial velocity m2 term, phase\",                             \"RA2P=\", PRA2P, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give radial velocity m3 term, amp  \",                             \"RA3A=\", PRA3A, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give radial velocity m3 term, phase\",                             \"RA3P=\", PRA3P, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give radial velocity m4 term, amp  \",                             \"RA4A=\", PRA4A, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give radial velocity m4 term, phase\",                             \"RA4P=\", PRA4P, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give 0th order warp term\",                                        \"WM0A=\", PWM0A, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give warp m1 term, amp  \",                                        \"WM1A=\", PWM1A, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give warp m1 term, phase\",                                        \"WM1P=\", PWM1P, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give warp m2 term, amp  \",                                        \"WM2A=\", PWM2A, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give warp m2 term, phase\",                                        \"WM2P=\", PWM2P, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give warp m3 term, amp  \",                                        \"WM3A=\", PWM3A, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give warp m3 term, phase\",                                        \"WM3P=\", PWM3P, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give warp m4 term, amp  \",                                        \"WM4A=\", PWM4A, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give warp m4 term, phase\",                                        \"WM4P=\", PWM4P, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give S0 lopsided term\",                                           \"LS0=\",  PLS0,  2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give C0 lopsided term\",                                           \"LC0=\",  PLC0,  2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give scale-height (Z0) of rings. (arcsec)\",                       \"Z0=\",   PZ0,   2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give surface-brightness of rings. (Jy/(arcsec*arcsec))\",          \"SBR=\",  PSBR,  2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give surface brightness m1 term, amp   (Jy/(arcsec*arcsec))\",     \"SM1A=\", PSM1A, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give surface brightness m1 term, phase (deg)\",                    \"SM1P=\", PSM1P, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give surface brightness m2 term, amp   (Jy/(arcsec*arcsec))\",     \"SM2A=\", PSM2A, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give surface brightness m2 term, phase (deg)\",                    \"SM2P=\", PSM2P, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give surface brightness m3 term, amp   (Jy/(arcsec*arcsec))\",     \"SM3A=\", PSM3A, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give surface brightness m3 term, phase (deg)\",                    \"SM3P=\", PSM3P, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give surface brightness m4 term, amp   (Jy/(arcsec*arcsec))\",     \"SM4A=\", PSM4A, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give surface brightness m4 term, phase (deg)\",                    \"SM4P=\", PSM4P, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give peak surface brigtness for Gaussian 1 (Jy/(arcsec*arcsec))\", \"GA1A\",  PGA1A, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give azimuth of Gaussian 1 (deg)\",                                \"GA1P\",  PGA1P, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give dispersion of Gaussian 1 (arcsec)\",                          \"GA1D\",  PGA1D, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give peak surface brigtness for Gaussian 2 (Jy/(arcsec*arcsec))\", \"GA2A\",  PGA2A, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give azimuth of Gaussian 2 (deg)\",                                \"GA2P\",  PGA2P, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give dispersion of Gaussian 2 (arcsec)\",                          \"GA2D\",  PGA2D, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give peak surface brigtness for Gaussian 3 (Jy/(arcsec*arcsec))\", \"GA3A\",  PGA3A, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give azimuth of Gaussian 3 (deg)\",                                \"GA3P\",  PGA3P, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give dispersion of Gaussian 3 (arcsec)\",                          \"GA3D\",  PGA3D, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give peak surface brigtness for Gaussian 4 (Jy/(arcsec*arcsec))\", \"GA4A\",  PGA4A, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give azimuth of Gaussian 4 (deg)\",                                \"GA4P\",  PGA4P, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give dispersion of Gaussian 4 (arcsec)\",                          \"GA4D\",  PGA4D, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give azimuth of simulted range 1 (deg)\",                          \"AZ1P\",  PAZ1P, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give width of simulted range 1 (deg)\",                            \"AZ1W\",  PAZ1W, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give azimuth of simulted range 2 (deg)\",                          \"AZ2P\",  PAZ2P, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give width of simulted range 2 (deg)\",                            \"AZ2W\",  PAZ2W, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give inclinations of rings. (degrees)\",                           \"INCL=\", PINCL, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give position angle of rings. (degrees)\",                         \"PA=\",   PPA,   2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give Right Ascensions of ring centres. (degrees)\",                \"XPOS=\", PXPOS, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give Declinations of ring centres. (degrees)\",                    \"YPOS=\", PYPOS, 2);\n  get_parameter_double(startinfv, log, hdr, rpm, \"Give systemic velocities of rings in (km/s).\",                    \"VSYS=\", PVSYS, 2);\n  \n  /* We do this ndisks time */\t\t\t\t\t\t\t\t\t\t \n  for (disk = 1; disk < rpm -> ndisks; ++disk) {\t\t\t\t\t\t\t\t\t \n    sprintf(placer, \"VROT_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give circular velocities. (km/s)\",                                placer, PRPARAMS+disk*NDPARAMS+PVROT, 2);\n    sprintf(placer, \"VRAD_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give radial velocities. (km/s)\",                                  placer, PRPARAMS+disk*NDPARAMS+PVRAD, 2);\n    sprintf(placer, \"VVER_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give vertical velocities. (km/s)\",                                placer, PRPARAMS+disk*NDPARAMS+PVVER, 2);\n    sprintf(placer, \"DVRO_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give vertical gradient of circular velocities. (km/s)\",           placer, PRPARAMS+disk*NDPARAMS+PDVRO, 2);\n    sprintf(placer, \"DVRA_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give vertical gradient of radial velocities. (km/s)\",             placer, PRPARAMS+disk*NDPARAMS+PDVRA, 2);\n    sprintf(placer, \"DVVE_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give vertical gradient of vertical velocities. (km/s)\",           placer, PRPARAMS+disk*NDPARAMS+PDVVE, 2);\n    sprintf(placer, \"ZDRO_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give start height for change of circular velocities. (km/s)\",     placer, PRPARAMS+disk*NDPARAMS+PZDRO, 2);\n    sprintf(placer, \"ZDRA_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give start height for change of velocities. (km/s)\",              placer, PRPARAMS+disk*NDPARAMS+PZDRA, 2);\n    sprintf(placer, \"ZDVE_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give start height for change of vertical velocities. (km/s)\",     placer, PRPARAMS+disk*NDPARAMS+PZDVE, 2);\n    sprintf(placer, \"SDIS_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give dispersion (SDIS) of rings. (km/s)\",                         placer, PRPARAMS+disk*NDPARAMS+PSDIS, 2);\n    sprintf(placer, \"CLNR_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give number of sub-clouds\",                                       placer, PRPARAMS+disk*NDPARAMS+PCLNR, 2);\n    sprintf(placer, \"VM0A_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give radial velocity term\",                                       placer, PRPARAMS+disk*NDPARAMS+PVM0A, 2);\n    sprintf(placer, \"VM1A_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give velocity m1 term, amp  \",                                    placer, PRPARAMS+disk*NDPARAMS+PVM1A, 2);\n    sprintf(placer, \"VM1P_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give velocity m1 term, phase\",                                    placer, PRPARAMS+disk*NDPARAMS+PVM1P, 2);\n    sprintf(placer, \"VM2A_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give velocity m2 term, amp  \",                                    placer, PRPARAMS+disk*NDPARAMS+PVM2A, 2);\n    sprintf(placer, \"VM2P_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give velocity m2 term, phase\",                                    placer, PRPARAMS+disk*NDPARAMS+PVM2P, 2);\n    sprintf(placer, \"VM3A_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give velocity m3 term, amp  \",                                    placer, PRPARAMS+disk*NDPARAMS+PVM3A, 2);\n    sprintf(placer, \"VM3P_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give velocity m3 term, phase\",                                    placer, PRPARAMS+disk*NDPARAMS+PVM3P, 2);\n    sprintf(placer, \"VM4A_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give velocity m4 term, amp  \",                                    placer, PRPARAMS+disk*NDPARAMS+PVM4A, 2);\n    sprintf(placer, \"VM4P_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give velocity m4 term, phase\",                                    placer, PRPARAMS+disk*NDPARAMS+PVM4P, 2);\n    sprintf(placer, \"RA1A_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give radial velocity m1 term, amp  \",                             placer, PRPARAMS+disk*NDPARAMS+PRA1A, 2);\n    sprintf(placer, \"RA1P_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give radial velocity m1 term, phase\",                             placer, PRPARAMS+disk*NDPARAMS+PRA1P, 2);\n    sprintf(placer, \"RA2A_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give radial velocity m2 term, amp  \",                             placer, PRPARAMS+disk*NDPARAMS+PRA2A, 2);\n    sprintf(placer, \"RA2P_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give radial velocity m2 term, phase\",                             placer, PRPARAMS+disk*NDPARAMS+PRA2P, 2);\n    sprintf(placer, \"RA3A_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give radial velocity m3 term, amp  \",                             placer, PRPARAMS+disk*NDPARAMS+PRA3A, 2);\n    sprintf(placer, \"RA3P_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give radial velocity m3 term, phase\",                             placer, PRPARAMS+disk*NDPARAMS+PRA3P, 2);\n    sprintf(placer, \"RA4A_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give radial velocity m4 term, amp  \",                             placer, PRPARAMS+disk*NDPARAMS+PRA4A, 2);\n    sprintf(placer, \"RA4P_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give radial velocity m4 term, phase\",                             placer, PRPARAMS+disk*NDPARAMS+PRA4P, 2);\n    sprintf(placer, \"RO1A_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give tangential velocity m1 term, amp  \",                         placer, PRPARAMS+disk*NDPARAMS+PRO1A, 2);\n    sprintf(placer, \"RO1P_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give tangential velocity m1 term, phase\",                         placer, PRPARAMS+disk*NDPARAMS+PRO1P, 2);\n    sprintf(placer, \"RO2A_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give tangential velocity m2 term, amp  \",                         placer, PRPARAMS+disk*NDPARAMS+PRO2A, 2);\n    sprintf(placer, \"RO2P_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give tangential velocity m2 term, phase\",                         placer, PRPARAMS+disk*NDPARAMS+PRO2P, 2);\n    sprintf(placer, \"RO3A_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give tangential velocity m3 term, amp  \",                         placer, PRPARAMS+disk*NDPARAMS+PRO3A, 2);\n    sprintf(placer, \"RO3P_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give tangential velocity m3 term, phase\",                         placer, PRPARAMS+disk*NDPARAMS+PRO3P, 2);\n    sprintf(placer, \"RO4A_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give tangential velocity m4 term, amp  \",                         placer, PRPARAMS+disk*NDPARAMS+PRO4A, 2);\n    sprintf(placer, \"RO4P_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give tangential velocity m4 term, phase\",                         placer, PRPARAMS+disk*NDPARAMS+PRO4P, 2);\n    sprintf(placer, \"WM0A_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give 0th order warp term\",                                        placer, PRPARAMS+disk*NDPARAMS+PWM0A, 2);\n    sprintf(placer, \"WM1A_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give warp m1 term, amp  \",                                        placer, PRPARAMS+disk*NDPARAMS+PWM1A, 2);\n    sprintf(placer, \"WM1P_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give warp m1 term, phase\",                                        placer, PRPARAMS+disk*NDPARAMS+PWM1P, 2);\n    sprintf(placer, \"WM2A_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give warp m2 term, amp  \",                                        placer, PRPARAMS+disk*NDPARAMS+PWM2A, 2);\n    sprintf(placer, \"WM2P_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give warp m2 term, phase\",                                        placer, PRPARAMS+disk*NDPARAMS+PWM2P, 2);\n    sprintf(placer, \"WM3A_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give warp m3 term, amp  \",                                        placer, PRPARAMS+disk*NDPARAMS+PWM3A, 2);\n    sprintf(placer, \"WM3P_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give warp m3 term, phase\",                                        placer, PRPARAMS+disk*NDPARAMS+PWM3P, 2);\n    sprintf(placer, \"WM4A_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give warp m4 term, amp  \",                                        placer, PRPARAMS+disk*NDPARAMS+PWM4A, 2);\n    sprintf(placer, \"WM4P_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give warp m4 term, phase\",                                        placer, PRPARAMS+disk*NDPARAMS+PWM4P, 2);\n    sprintf(placer, \"LS0_%i=\" , disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give S0 lopsided term\",                                           placer, PRPARAMS+disk*NDPARAMS+PLS0,  2);\n    sprintf(placer, \"LC0_%i=\" , disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give C0 lopsided term\",                                           placer, PRPARAMS+disk*NDPARAMS+PLC0,  2);\n    sprintf(placer, \"Z0_%i=\"  , disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give scale-height (Z0) of rings. (arcsec)\",                       placer, PRPARAMS+disk*NDPARAMS+PZ0,   2);\n    sprintf(placer, \"SBR_%i=\" , disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give surface-brightness of rings. (Jy/(arcsec*arcsec))\",          placer, PRPARAMS+disk*NDPARAMS+PSBR,  2);\n    sprintf(placer, \"SM1A_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give surface brightness m1 term, amp   (Jy/(arcsec*arcsec))\",     placer, PRPARAMS+disk*NDPARAMS+PSM1A, 2);\n    sprintf(placer, \"SM1P_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give surface brightness m1 term, phase (deg)\",                    placer, PRPARAMS+disk*NDPARAMS+PSM1P, 2);\n    sprintf(placer, \"SM2A_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give surface brightness m2 term, amp   (Jy/(arcsec*arcsec))\",     placer, PRPARAMS+disk*NDPARAMS+PSM2A, 2);\n    sprintf(placer, \"SM2P_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give surface brightness m2 term, phase (deg)\",                    placer, PRPARAMS+disk*NDPARAMS+PSM2P, 2);\n    sprintf(placer, \"SM3A_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give surface brightness m3 term, amp   (Jy/(arcsec*arcsec))\",     placer, PRPARAMS+disk*NDPARAMS+PSM3A, 2);\n    sprintf(placer, \"SM3P_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give surface brightness m3 term, phase (deg)\",                    placer, PRPARAMS+disk*NDPARAMS+PSM3P, 2);\n    sprintf(placer, \"SM4A_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give surface brightness m4 term, amp   (Jy/(arcsec*arcsec))\",     placer, PRPARAMS+disk*NDPARAMS+PSM4A, 2);\n    sprintf(placer, \"SM4P_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give surface brightness m4 term, phase (deg)\",                    placer, PRPARAMS+disk*NDPARAMS+PSM4P, 2);\n    sprintf(placer, \"GA1A_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give peak surface brigtness for Gaussian 1 (Jy/(arcsec*arcsec))\", placer, PRPARAMS+disk*NDPARAMS+PGA1A, 2);\n    sprintf(placer, \"GA1P_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give azimuth of Gaussian 1 (deg)\",                                placer, PRPARAMS+disk*NDPARAMS+PGA1P, 2);\n    sprintf(placer, \"GA1D_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give dispersion of Gaussian 1 (arcsec)\",                          placer, PRPARAMS+disk*NDPARAMS+PGA1D, 2);\n    sprintf(placer, \"GA2A_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give peak surface brigtness for Gaussian 2 (Jy/(arcsec*arcsec))\", placer, PRPARAMS+disk*NDPARAMS+PGA2A, 2);\n    sprintf(placer, \"GA2P_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give azimuth of Gaussian 2 (deg)\",                                placer, PRPARAMS+disk*NDPARAMS+PGA2P, 2);\n    sprintf(placer, \"GA2D_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give dispersion of Gaussian 2 (arcsec)\",                          placer, PRPARAMS+disk*NDPARAMS+PGA2D, 2);\n    sprintf(placer, \"GA3A_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give peak surface brigtness for Gaussian 3 (Jy/(arcsec*arcsec))\", placer, PRPARAMS+disk*NDPARAMS+PGA3A, 2);\n    sprintf(placer, \"GA3P_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give azimuth of Gaussian 3 (deg)\",                                placer, PRPARAMS+disk*NDPARAMS+PGA3P, 2);\n    sprintf(placer, \"GA3D_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give dispersion of Gaussian 3 (arcsec)\",                          placer, PRPARAMS+disk*NDPARAMS+PGA3D, 2);\n    sprintf(placer, \"GA4A_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give peak surface brigtness for Gaussian 4 (Jy/(arcsec*arcsec))\", placer, PRPARAMS+disk*NDPARAMS+PGA4A, 2);\n    sprintf(placer, \"GA4P_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give azimuth of Gaussian 4 (deg)\",                                placer, PRPARAMS+disk*NDPARAMS+PGA4P, 2);\n    sprintf(placer, \"GA4D_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give dispersion of Gaussian 4 (arcsec)\",                          placer, PRPARAMS+disk*NDPARAMS+PGA4D, 2);\n    sprintf(placer, \"AZ1P_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give azimuth of simulted range 1 (deg)\",                          placer, PRPARAMS+disk*NDPARAMS+PAZ1P, 2);\n    sprintf(placer, \"AZ1W_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give width of simulted range 1 (deg)\",                            placer, PRPARAMS+disk*NDPARAMS+PAZ1W, 2);\n    sprintf(placer, \"AZ2P_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give azimuth of simulted range 2 (deg)\",                          placer, PRPARAMS+disk*NDPARAMS+PAZ2P, 2);\n    sprintf(placer, \"AZ2W_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give width of simulted range 2 (deg)\",                            placer, PRPARAMS+disk*NDPARAMS+PAZ2W, 2);\n    sprintf(placer, \"INCL_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give inclinations of rings. (degrees)\",                           placer, PRPARAMS+disk*NDPARAMS+PINCL, 2);\n    sprintf(placer, \"PA_%i=\"  , disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give position angle of rings. (degrees)\",                         placer, PRPARAMS+disk*NDPARAMS+PPA,   2);\n    sprintf(placer, \"XPOS_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give Right Ascensions of ring centres. (degrees)\",                placer, PRPARAMS+disk*NDPARAMS+PXPOS, 2);\n    sprintf(placer, \"YPOS_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give Declinations of ring centres. (degrees)\",                    placer, PRPARAMS+disk*NDPARAMS+PYPOS, 2);\n    sprintf(placer, \"VSYS_%i=\", disk+1);get_parameter_double(startinfv, log, hdr, rpm, \"Give systemic velocities of rings in (km/s).\",                    placer, PRPARAMS+disk*NDPARAMS+PVSYS, 2);\n  }\n\n  /* Now, we have to convert the triplets into internal units */\n  for (disk = 0; disk < rpm -> ndisks; ++disk){\n    for (i = 0; i < rpm -> nur; ++i) {\n      globin[0] = rpm -> par[(PRPARAMS+disk*NDPARAMS+PXPOS)*rpm -> nur+i];\n      globin[1] = rpm -> par[(PRPARAMS+disk*NDPARAMS+PYPOS)*rpm -> nur+i];\n      globin[2] = rpm -> par[(PRPARAMS+disk*NDPARAMS+PVSYS)*rpm -> nur+i];\n      \n      globtointern(globin, globout, hdr);\n      \n      rpm -> par[(PRPARAMS+disk*NDPARAMS+PXPOS)*rpm -> nur+i] = globout[0];\n      rpm -> par[(PRPARAMS+disk*NDPARAMS+PYPOS)*rpm -> nur+i] = globout[1];\n      rpm -> par[(PRPARAMS+disk*NDPARAMS+PVSYS)*rpm -> nur+i] = globout[2];\n    }\n  }\n\n  /* Global velocity dispersion */\n  /* Default */\n    def = 0;\n  \n\n  sprintf(mes, \"Give global velicity dipersion (km/s)\");\n  nel = 1;\n\n  /* this is variable with disk */\n  pcondisp = (NPARAMS + (rpm -> ndisks - 1)*NDPARAMS);\n  condisp = pcondisp+1;\n\n  /* This is the ninth parameter sequence */\n  if (!startinfv -> firstrun) {\n    cancel_tir(startinfv -> arel, \"CONDISP=\", 0);\n  }\n  userdble_tir(startinfv -> arel, rpm -> par+(pcondisp)*rpm -> nur, &nel, &def, \"CONDISP=\", mes);\n  \n  /* it should be positive */\n  while (rpm -> par[(pcondisp)*rpm -> nur] < 0) {\n    sprintf(mes, \"Negative velocity dispersion not allowed.\");\n    cancel_tir(startinfv -> arel, \"CONDISP\", 2);\n    userdble_tir(startinfv -> arel, rpm -> par+(pcondisp)*rpm -> nur, &nel, &def, \"CONDISP=\", mes);\n  }\n\n  /* Change the value to grid units */\n  rpm -> par[(pcondisp)*rpm ->nur] = dparamtointern(rpm -> par[(pcondisp)*rpm ->nur], condisp, hdr, rpm -> ndisks);\n\n  /* The layer type */\n    rpm -> ltype[0] = 0;\n    def = 5;\n\n  sprintf(mes, \"Give type of layer. [list options]\");\n  nel = 1;\n \n  if (!startinfv -> firstrun) {\n    cancel_tir(startinfv -> arel, \"LTYPE=\", 0);\n  }\n\n  while(!rpm -> ltype[0]) {\n    userint_tir(startinfv -> arel, rpm -> ltype+0, &nel, &def, \"LTYPE=\", mes);\n    if((rpm -> ltype[0]) < 1 || (rpm -> ltype[0] > 5)) {\n      rpm -> ltype[0] = 0;\n      anyout_tir(rpm -> ltype+0, \" Ltype:\");\n      anyout_tir(rpm -> ltype+0, \" 1 -- Gaussian layer\");\n      anyout_tir(rpm -> ltype+0, \" 2 -- Sech2 layer\");\n      anyout_tir(rpm -> ltype+0, \" 3 -- Exponential layer\");\n      anyout_tir(rpm -> ltype+0, \" 4 -- Lorentzian layer\");\n      anyout_tir(rpm -> ltype+0, \" 5 -- Box layer\");\n      cancel_tir(startinfv -> arel, \"LTYPE=\", 2);\n    }\n  }\n\n\n  /* Do this ndisks-1 times more */\n  for (i = 1; i < rpm -> ndisks; ++i) {\n    \n    sprintf(placer, \"LTYPE_%i=\", i+1);\n    if (!startinfv -> firstrun) {\n      cancel_tir(startinfv -> arel, placer, 0);\n    }\n\n    /* The layer type */\n    rpm -> ltype[i] = rpm -> ltype[i-1];\n    def = 2;\n    \n    sprintf(mes, \"Give type of layer %i. [list options]\", i+1);\n    nel = 1;\n    \n    dummy = 0;\n\n    while(!(dummy)) {\n      userint_tir(startinfv -> arel, rpm -> ltype+i, &nel, &def, placer, mes);\n      dummy = 1;\n      if((rpm -> ltype[i]) < 1 || (rpm -> ltype[i] > 5)) {\n\tdef = 5;\n\tdummy = 0;\n\tanyout_tir(rpm -> ltype+i, \" Ltype:\");\n\tanyout_tir(rpm -> ltype+i, \" 1 -- Gaussian layer\");\n\tanyout_tir(rpm -> ltype+i, \" 2 -- Sech2 layer\");\n\tanyout_tir(rpm -> ltype+i, \" 3 -- Exponential layer\");\n\tanyout_tir(rpm -> ltype+i, \" 4 -- Lorentzian layer\");\n\tanyout_tir(rpm -> ltype+i, \" 5 -- Box layer\");\n\tcancel_tir(startinfv -> arel, placer, 2);\n      }\n    }\n  }\n\n  /* cloud flux */\n    rpm -> cflux[0] = 1e-5;\n    def = 5;\n\n  sprintf(mes,\"Cloud flux in (Jy*km/s) [1E-5]\");\n  nel = 1;\n  if (!startinfv -> firstrun) {\n    cancel_tir(startinfv -> arel, \"CFLUX=\", 0);\n  }\n  userdble_tir(startinfv -> arel, rpm -> cflux+0, &nel, &def, \"CFLUX=\", mes);\n  while (rpm ->cflux[0] <= 0) {\n    sprintf(mes,\"CFLUX must be greater than zero.\");\n    rpm -> cflux[0] = 1e-5;\n    cancel_tir(startinfv -> arel, \"CFLUX=\", 2);\n    userdble_tir(startinfv -> arel, rpm -> cflux+0, &nel, &def, \"CFLUX=\", mes);\n  }\n\n  for (i = 1; i < rpm -> ndisks; ++i) {\n    \n    sprintf(placer, \"CFLUX_%i=\", i+1);\n    if (!startinfv -> firstrun) {\n      cancel_tir(startinfv -> arel, placer, 0);\n    }\n\n      rpm -> cflux[i] = rpm -> cflux[i-1];\n      def = 2;\n    \n    \n    sprintf(mes,\"Cloud flux (%i) in (Jy*km/s) [1E-5]\", i+1);\n    nel = 1;\n    userdble_tir(startinfv -> arel, rpm -> cflux+i, &nel, &def, placer, mes);\n    while (rpm ->cflux[i] <= 0) {\n      def = 5;\n      sprintf(mes,\"CFLUX must be greater than zero.\");\n      rpm -> cflux[i] = 1e-5;\n      cancel_tir(startinfv -> arel, placer, 2);\n      userdble_tir(startinfv -> arel, rpm -> cflux+i, &nel, &def, placer, mes);\n    }\n  }\n\n  /* Initialise the io */\n /* Now initialise the chisquare derivation (convolution) routines */\n\n  if (startinfv -> firstrun) {\n\n  /* Input noiseweight */\n    rpm -> weight = 1.0;\n    def = 5;\n\n  sprintf(mes, \"Give noise weighting (0.0 means inf). [%f]\", rpm -> weight);\n  nel = 1;\n  userreal_tir(startinfv -> arel, &rpm -> weight, &nel, &def, \"WEIGHT=\", mes);\n  \n  /* Input PENALTY */\n    rpm -> penalty = 1.0;\n    def = 2;\n\n    sprintf(mes, \"Give Penalty for outlyers [%f]\", rpm -> penalty);\n  nel = 1;\n  userdble_tir(startinfv -> arel, &rpm -> penalty, &nel, &def, \"PENALTY=\", mes);\n  \n  /* Now we recalculate the penalty */\n  rpm -> penalty = rpm -> cflux[0]*rpm -> penalty*SQRTOFPIHALF*((double) hdr -> bmaj)*((double) hdr -> bmaj)*((double) hdr -> bmin)*((double) hdr -> bmin)*HPBWTOSIGMATOFORTH/((double)(hdr -> rms*hdr -> rms));\n\n  /* Input inimode */\n    rpm -> inimode = 1;\n    def = 5;\n\n#ifdef PBCORR\n\n  /* Primary beam correction */\n\n  def = 2;\n  nel = 1;\n  pbtel = 0;  \n  \n  userint_tir(startinfv -> arel, &pbtel, &nel, &def, \"PBTEL=\", mes);  \n  \n  /* We only take action if something gets specified */\n  if ((pbtel > 0) && (pbtel <= PBNTELS)) {\n\n    if (!(hdr -> primbeam = (float *) malloc(hdr -> bsize1*hdr -> bsize2*sizeof(float)))) {\n      anyout_tir(&dev, \"Not enough memory\");\n      goto error;\n    }\n\n    /* Ask for reference pixel and frequency */\n    sprintf(mes, \"Give pbc reference pixel, starting at 0 0 in the lower left corner [centre]\");\n    pbrefpix[0] = hdr -> bsize1/2-0.5;\n    pbrefpix[1] = hdr -> bsize2/2-0.5;\n    def = 2;\n    nel = 2;\n    userdble_tir(startinfv -> arel, pbrefpix, &nel, &def, \"PBREFPIX=\", mes);\n    \n    /* Ask for reference frequency */\n    sprintf(mes, \"Give pbc reference frequency (GHz) [1.4]\");\n    pbreffreq = HIRESFREQ*1.0E-9;\n    def = 2;\n    nel = 2;\n    err = 1;\n    \n    userdble_tir(startinfv -> arel, &pbreffreq, &nel, &def, \"PBREFFREQ=\", mes);\n    \n    switch(pbtel) {\n    case PBWSRT:\n    case PBWSRT_2:\n      while ((err)) {\n\tif ((pbreffreq < 8) && (pbreffreq > 0.5)) {\n\t  --err;\n\t}\n\telse {\n\t  def = 1;\n\t  anyout_tir(&dev, \"Must lie between 0.5 and 8.0\");\n\t  cancel_tir(startinfv -> arel, \"PBREFFREQ=\", 2);\n\t  pbreffreq = HIRESFREQ*1.0E-9;\n\t  userdble_tir(startinfv -> arel, &pbreffreq, &nel, &def, \"PBREFFREQ=\", mes);\t\n\t}    \n      }\n      break;\n      \n    default:\n      ;\n    }\n   \n    switch(pbtel) {\n    case PBWSRT:\n    case PBWSRT_2:\n\n      /* (cos((pi/180)*c * nu/GHz * r/deg ))^6, c = 60.7492, (cos(c1* nu/GHz * r/deg))^6, c1 = 1.0602735280990601 (estimated from HPBW in Miriad), nu: frequency in GHz, r: radius in deg */\n      /* hdr -> deltgridtouser[0,1] gives conversion from pixel to arcsec */\n      /* rp = sqrt((x-refpixx)^2+(y-refpixy)^2): radius in pixel */\n      /* r = sqrt(((x-refpixx)*hdr->deltgridtouser[0])^2+((y-refpixy)*hdr->deltgridtouser[1])^2)/3600.0 */\n      /* neclecting the frequency dependency results in an error of 1-2/1000 at half power. The uncertainty in the parameters is much larger */\n      /* An experiment shows that this conforms with the miriad primary beam correction for the WSRT at a level of 0.002 percent, so to float precision level */\n      /* A communication with T.A. results in the fact that one should use c = 68 instead. Details are here:  Popping & Braun 2008, A&A 479, 903 */\n          \n      switch(pbtel) {\n      case PBWSRT:\n\tpbwsrtconst = PBWSRTCONST_1;\n\tbreak;\n      case PBWSRT_2:\n\tpbwsrtconst = PBWSRTCONST_2;\n\tbreak;\n      }\n\n      for (i = 0; i < hdr -> bsize1; ++i) {\n#ifdef OPENMPTIR\n#pragma omp parallel for private(pbdoublev1,pbdoublev2,pbradius)\n#endif\n\tfor (j = 0; j < hdr -> bsize2; ++j) {\n\t   pbdoublev1 = (((double) i)-pbrefpix[0])*hdr->deltgridtouser[0];\n\t   pbdoublev2 = (((double) j)-pbrefpix[1])*hdr->deltgridtouser[1];\n\t   pbradius = (pbwsrtconst*pbreffreq*sqrt(pbdoublev1*pbdoublev1+pbdoublev2*pbdoublev2));\n\t  if (pbradius < PIHALF)\n\t    hdr -> primbeam[i+hdr -> bsize1*j] = pow(cos(pbradius),6);\n\t  else \n\t    hdr -> primbeam[i+hdr -> bsize1*j] = 0.0;\n\t}\n      } \n      break;\n      \n    default:\n      break;\n    }\n  }\n\n  /* Now arrange for the correct links */\n  chkb_pbcorr(hdr, rpm);\n#endif\n\n  sprintf(mes, \"Give initialisation time 0 short, 3 long [1]\");\n  nel = 1;\n  err = 0;\n  while (!(err)) {\n    userint_tir(startinfv -> arel, &(rpm -> inimode), &nel, &def, \"INIMODE=\", mes);\n    if (rpm -> inimode < 0 || rpm -> inimode > 3) {\n      sprintf(mes, \"Out of range %i\", rpm -> inimode);\n      cancel_tir(startinfv -> arel, \"INIMODE=\", 2);\n      rpm -> inimode = 1;\n      def = 5;\n    }\n    else\n      err = 1;\n  }\n\n  /* Input mode */\n    rpm -> mode = 3;\n    def = 5;\n\n/*   sprintf(mes, \"Give memory consumption mode. [list options]\"); */\n/*   nel = 1; */\n/*   i = 0; */\n/*   while (!(i)) { */\n/*     userint_tir(&rpm -> mode, &nel, &def, \"MEMMODE=\", mes); */\n/*     if (rpm -> mode < 0 || rpm -> mode > 3) { */\n/*       anyout_tir(&i, \" MemMode:\"); */\n/*       anyout_tir(&i, \"       0 -- in-place, no boost.\"); */\n/*       anyout_tir(&i, \"       1 -- in-place, using boost.\"); */\n/*       anyout_tir(&i, \"       2 -- out-place, no boost.\"); */\n/*       anyout_tir(&i, \"       3 -- out-place, using boost.\"); */\n/*       cancel_tir(startinfv -> arel, \"MEMMODE=\"); */\n/*       rpm -> mode = 3; */\n/*       def = 5; */\n/*     } */\n/*     else */\n/*       i = 1; */\n/*   } */\n  mode = rpm -> mode*2;\n  if ((rpm -> weight)) \n    ++mode;\n\n/*   sprintf(obsmes, */\n/* \t  \"ori[0]:   %f\\n\" */\n/* \t  \"model[0]: %f\\n\" */\n/* \t  \"bsize1:   %i\\n\" */\n/* \t  \"bsize2:   %i\\n\" */\n/* \t  \"nsubs:    %i\\n\" */\n/*           \"bmaj:     %f\\n\" */\n/* \t  \"bmin:     %f\\n\" */\n/*           \"bpa:      %f\\n\" */\n/* \t  \"cflux[0]: %f\\n\" */\n/* \t  \"rms:      %f\\n\" */\n/*           \"mode:     %i\\n\" */\n/*           \"2*(bsize1/2+1): %i\\n\" */\n/* \t  \"chi2 (random):  %f\\n\" */\n/* \t  \"weight:         %f\\n\" */\n/* \t  \"inimode:        %i\\n\" */\n/* \t  \"ncores:         %i\\n\",  */\n/* hdr -> oric -> points[0], hdr -> modelc -> points[0], hdr -> bsize1, hdr -> bsize2, hdr -> nsubs, hdr -> bmaj, hdr -> bmin, hdr -> bpa, rpm -> cflux[0], hdr -> rms, mode, 2*(hdr -> bsize1/2+1), hdr -> chi2, rpm -> weight, rpm -> inimode, log -> ncores */\n/* \t  ); */\n/*   anyout_tir(&obsint, obsmes); */\n\n  /* Try to initialise the chisquare machinery */\n  while (mode >= 0 && mode < 8) {   \n    if (!initchisquare_c(hdr -> oric -> points, hdr -> modelc -> points, hdr -> bsize1, hdr -> bsize2, hdr -> nsubs, hdr -> bmaj, hdr -> bmin, hdr -> bpa, 1, rpm -> cflux[0], hdr -> rms, mode, 2*(hdr -> bsize1/2+1), &hdr -> chi2, rpm -> weight, rpm -> inimode, log -> ncores)) {\n    mode = mode-2;\n    j = 0;\n    }\n    else {\n      mode = 8;\n    }\n  }\n\n  j = 4;\n  if (mode < 8)\n    error_tir(&j,\"Error initializing chi^2 derivation control.\");\n  \n  /* Write inset data into ori array  (has been done since long)*/\n  /* nel = 0; */\n  /* def = 4; */\n  \n  /* for (i = 0; i < hdr -> nsubs; ++i) { */\n  /*   j=i*hdr -> nprof; */\n  /*   gdsi_read_tir(hdr -> inset, hdr -> cwlo+i, hdr -> cwhi+i, hdr -> ori+j, &hdr -> nprof, &k, &nel); */\n  /*   if ((nel)) { */\n  /*     error_tir(&def, \"Unable to read inset.\"); */\n  /*   } */\n  /* } */\n  \n  /* close inset (not needed anymore ?) */\n  /* gds_close_tir(hdr -> inset, &def); */\n  \n  /* Now the cube has to be rearranged, because it is padded */\n  /* for(k = hdr -> nsubs-1; k >= 0; --k) { */\n  /*   for(j = hdr -> bsize2-1; j >= 0; --j) { */\n  /*     for(i = hdr -> bsize1-1; i >= 0; --i) { */\n  /* \thdr -> ori[i+2*(hdr -> bsize1/2+1)*(j+hdr -> bsize2*k)] = hdr -> ori[i+hdr -> bsize1*(j+hdr -> bsize2*k)]; */\n  /*     } */\n  /*   } */\n  /* } */\n\n  /* The cube has changed, therefore we need to do this */\n  engalmod_chflgs(); \n\n  /* Also, we change the nprof */\n  hdr -> nprof = hdr -> bcsize1*hdr -> bsize2;\n  \n\n  /* We initialise the sd array */\n  for (i = 0; i < rpm -> ndisks; ++i) {\n    if (!(rpm -> sd[i] = create_srd(rpm -> nr)))\n      goto error;\n    for (j = 0; j < rpm -> nr; ++j) {\n      if (!(rpm -> sd[i][j].permrandstr = (maths_rstrf *) malloc(sizeof(maths_rstrf))))\n\t\t  goto error;\n      rpm -> sd[i][j].randstr = NULL;\n      rpm -> sd[i][j].grandstr[0] = NULL;\n      rpm -> sd[i][j].grandstr[1] = NULL;\n      rpm -> sd[i][j].grandstr[2] = NULL;\n      rpm -> sd[i][j].grandstr[3] = NULL;\n      rpm -> sd[i][j].srandstr = NULL;\n    }\n  }\n  }\n  /* Get the info for the single-model random-number generator */\n  /* First from the log if present */\n    rpm -> iseed2 = 1803;\n    def = 2;\n   \n  sprintf(mes, \"Give one integer to initialize RNG. [1803]\");\n  \n  if (!startinfv -> firstrun)\n    cancel_tir(startinfv -> arel, \"ISEED=\", 0);\n\n  nel = 1;\n  userint_tir(startinfv -> arel, &rpm -> iseed2, &nel, &def, \"ISEED=\", mes);\n  while (rpm -> iseed2 < 0 || rpm -> iseed2 > 31328) {\n    sprintf(mes, \"Iseed out of range.\");\n    cancel_tir(startinfv -> arel, \"ISEED=\", 2);\n    def = 5;\n    userint_tir(startinfv -> arel, &rpm -> iseed2, &nel, &def, \"ISEED=\", mes);\n  }\n\n  for (i = 0; i < rpm -> ndisks; ++i) {\n\n    for (j = 0; j < rpm -> nr; ++j) {\n      rpm -> sd[i][j].iseed2[0] = rpm -> iseed2;\n    }\n  }\n\n  return rpm;\n  \n  error:\n  destroy_ringparms(rpm);\n  if (hdr)\n    destroy_hdrinf(hdr);\n  if (log)\n    destroy_loginf(log, rpm -> ndisks);\n  \n  return NULL;\n  \n  }\n  \n  /* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Creates a fitparms structure */\nstatic fitparms *create_fitparms(ringparms *rpm)\n{\n  fitparms *fit;\n\n  if (!(fit = (fitparms *) malloc(sizeof(fitparms))))\n    return NULL;\n\n  fit -> varylist = NULL;\n  fit -> normrandstr = NULL;\n  fit -> gft_mstv = NULL;\n  fit -> varyhstr = NULL;\n  fit -> index = NULL;\n  fit -> mon_dpar = NULL;\n  fit -> reg_contv = NULL;\n  fit -> npoints = NULL;\n\n  /* Allocate the memory */\n  if (!(fit -> normrandstr = (maths_rstr *) malloc(sizeof(maths_rstr))))\n     goto error;\n\n  if (!(fit -> npoints = (int *) malloc(rpm -> ndisks*sizeof(int))))\n     goto error;\n  if (!(fit -> fluxpoints = (long *) malloc(rpm -> ndisks*sizeof(long))))\n     goto error;\n  if (!(fit -> mon_repnpoints = (int *) malloc(rpm -> ndisks*sizeof(int))))\n     goto error;\n  if (!(fit -> mon_totalflux = (double *) malloc(rpm -> ndisks*sizeof(double))))\n     goto error;\n\n  return fit;\n\n error:\n  destroy_fitparms(fit);\n  return NULL;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Destroys a fitparms structure */\nvoid destroy_fitparms(fitparms *fit)\n{\n  /* Check if it is there */\n  if (!(fit))\n    return;\n\n  if ((fit -> varylist))\n    destroyvarlel(fit -> varylist);\n  if((fit -> normrandstr))\n    free(fit -> normrandstr);\n  if((fit -> npoints))\n    free(fit -> npoints);\n  if((fit -> fluxpoints))\n    free(fit -> fluxpoints);\n  if((fit -> mon_repnpoints))\n    free(fit -> mon_repnpoints);\n  if((fit -> mon_totalflux))\n    free(fit -> mon_totalflux);\n  if((fit -> gft_mstv))\n    gft_mst_destr(fit -> gft_mstv);\n  if((fit -> varyhstr))\n    free(fit -> varyhstr);\n  if((fit -> mon_dpar))\n    free(fit -> mon_dpar);\n  if((fit -> index))\n    decomp_inlist_dest(fit->index);\n  if ((fit -> reg_contv))\n    reg_cont_destr(fit -> reg_contv);\n  if ((fit -> adar))\n    free(fit -> adar);\n\n  free(fit);\n    return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Fill the fitparms struct from the input */\nstatic fitparms *get_fitparms(startinf *startinfv, loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fitparmsv)\n{\n  fitparms *fit;\n\n  /* Private control and changing variables */\n  int def;      /* Any default mode */\n  int nel;      /* Number of elements */\n  int nread;    /* Number of read elements */\n  char mes[81];  /* Any message */\n  int errcode = 1; /* another error code */\n  int anint;\n\n  int i, j, k; /* Simple control variables */\n\n  /* Private input lists */\n  varlel **pointarray = NULL;\n  double *parmax = NULL;\n  double *parmin = NULL;\n  int *moderate = NULL;\n  double *delstart = NULL;\n  double *delend = NULL;\n  int *itestart = NULL;\n  int *iteend = NULL;\n  double *satdelt = NULL;\n  double *mindelta = NULL;\n\n  char *varyhstr = NULL;\n  char **varystr= NULL; /* An array of short strings to hold some input strings */\n  char **inputofvarysing = NULL;\n  char **inputofvarymult = NULL;\n  char *dcperr;\n\n  decomp_control decomp_controlv = NULL;\n  decomp_listel *decomp_listelv = NULL;\n\n  inlistel *flistel = NULL;\n  varlel *varele;\n  varlel *varylist = NULL;\n  size_t size_tv; /* dummy */\n\n  /* diverse */\n  adar *adarv = NULL;\n\n  double *array = NULL; /* An array to contain a row */\n\n  /* arel output */\n  int nreadl, nreturned, keypres;\n\n  int neill;\n\n\n  /* Get the struct */\n  if (!startinfv -> firstrun) {\n    destroy_fitparms(fitparmsv);\n\n    /* These are all the parameters that need to be re-read */\n    cancel_tir(startinfv -> arel, \"FITMODE=\", 0);\n    cancel_tir(startinfv -> arel, \"LOOPS=\", 0);\n    cancel_tir(startinfv -> arel, \"MAXITER=\", 0);\n    cancel_tir(startinfv -> arel, \"CALLITE=\", 0);\n    cancel_tir(startinfv -> arel, \"SIZE=\", 0);\n    cancel_tir(startinfv -> arel, \"PSSE=\", 0); /* only fitmode = PSWARM */\n    cancel_tir(startinfv -> arel, \"PSNP=\", 0); /* only fitmode = PSWARM */\n    cancel_tir(startinfv -> arel, \"PSCO=\", 0); /* only fitmode = PSWARM */\n    cancel_tir(startinfv -> arel, \"PSSO=\", 0); /* only fitmode = PSWARM */\n    cancel_tir(startinfv -> arel, \"PSMV=\", 0); /* only fitmode = PSWARM */\n    cancel_tir(startinfv -> arel, \"PSNF=\", 0); /* only fitmode = PSWARM */\n    cancel_tir(startinfv -> arel, \"PSIW=\", 0); /* only fitmode = PSWARM */\n    cancel_tir(startinfv -> arel, \"PSFW=\", 0); /* only fitmode = PSWARM */\n    cancel_tir(startinfv -> arel, \"PSID=\", 0); /* only fitmode = PSWARM */\n    cancel_tir(startinfv -> arel, \"PSDD=\", 0); /* only fitmode = PSWARM */\n    cancel_tir(startinfv -> arel, \"VARINDX=\", 0);\n    cancel_tir(startinfv -> arel, \"VARY=\", 0);\n    cancel_tir(startinfv -> arel, \"VARYSING=\", 0);\n    cancel_tir(startinfv -> arel, \"VARYMULT=\", 0);\n    cancel_tir(startinfv -> arel, \"PARMAX=\", 0);\n    cancel_tir(startinfv -> arel, \"PARMIN=\", 0);\n    cancel_tir(startinfv -> arel, \"MODERATE=\", 0);\n    cancel_tir(startinfv -> arel, \"DELSTART=\", 0);\n    cancel_tir(startinfv -> arel, \"DELEND=\", 0);\n    cancel_tir(startinfv -> arel, \"ITESTART=\", 0); /* (only fitmode = golden section) */\n    cancel_tir(startinfv -> arel, \"ITEEND=\", 0); /* (only fitmode = golden section) */\n    cancel_tir(startinfv -> arel, \"MINDELTA=\", 0);\n  }\n\n  if (!(fit = create_fitparms(rpm))) {\n    goto error;\n  }\n\n  /* Input fitmode */\n    fit -> fitmode = 2;\n    def = 1;\n\n  sprintf(mes, \"Give fitting mode 2: golden section, 3: simplex [2]\");\n  nel = 1;\n  userint_tir(startinfv -> arel, &fit -> fitmode, &nel, &def, \"FITMODE=\", mes);\n  \n  if ((fit -> fitmode == METROPOLIS)) {\n    sprintf(mes, \"Method not existent (currently no Metropolis)\");\n    anyout_tir(&def, mes);\n    goto error;\n  }\n\n  /* now we plug in the next generation fit codes */\n  if (fit -> fitmode > 1) {\n\n    /* Allocate the fit control object */\n    if (!(fit -> gft_mstv = gft_mst_const()))\n      goto error;\n\n    /* Try to specify method */\n    i = fit -> fitmode-1;\n\n    if ((j = gft_mst_put(fit -> gft_mstv, &i, GFT_INPUT_METHOD))) {\n      if (j & 64) {\n\tdef = 1;\n\tsprintf(mes, \"Method not existent\");\n\tanyout_tir(&def, mes);\n\tgoto error;\n      }\n    }\n    gft_mst_putf(fit -> gft_mstv, &gchsq_gen_start, GFT_INPUT_GCHSQ);\n\n    /* Try to allocate the arguments struct and link */\n    if (!(adarv = (adar *) malloc(sizeof(adar))))\n      goto error;\n\n    fit -> adar = (void *) adarv;\n    adarv -> startinfv = startinfv;\n    adarv -> log = log;\n    adarv -> hdr = hdr;\n    adarv -> rpm = rpm;\n    adarv -> fit = fit;\n\n    /* Pack it into gft */\n    gft_mst_put(fit -> gft_mstv, fit -> adar, GFT_INPUT_ADAR);\n\n  }\n\n  /* Input loops */\n    fit -> loops = 500000;\n    def = 1;\n\n  sprintf(mes, \"Give number of loops to process. [500000]\");\n  nel = 1;\n  userint_tir(startinfv -> arel, &fit -> loops, &nel, &def, \"LOOPS=\", mes);\n    \n  /* Get the total maximum number of iterations */\n  if (fit -> fitmode > GOLDEN_SECTION) {\n    fit -> maxiter = 5000000;\n    def = 1;\n    \n    sprintf(mes, \"Give maximum number of total iterations. [5000000]\");\n    nel = 1;\n    userint_tir(startinfv -> arel, &fit -> maxiter, &nel, &def, \"MAXITER=\", mes);\n    \n    fit -> callite = 5000000;\n    def = 1;\n    \n    sprintf(mes, \"Give maximum number of steps per iteration. [5000000]\");\n    nel = 1;\n    userint_tir(startinfv -> arel, &fit -> callite, &nel, &def, \"CALLITE=\", mes);\n    \n    fit -> size = 1.0;\n    def = 1;\n    \n    sprintf(mes, \"Give stop size relative to minsteps. [1.0]\");\n    nel = 1;\n    userdble_tir(startinfv -> arel, &fit -> size, &nel, &def, \"SIZE=\", mes);\n  }\n\n  /* in case of PSWARM, we need these here, again propagating the defaults */\n  if (fit -> fitmode == PSWARM) {\n    fit -> psse = PSW_PSSE_DEF;\n    def = 2;\n    sprintf(mes, \"Give seed for PSWARM rng. [42]\");\n    nel = 1;\n    userint_tir(startinfv -> arel, &fit -> psse, &nel, &def, \"PSSE=\", mes);\n\n    fit -> psnp = PSW_PSNP_DEF;\n    def = 2;\n    sprintf(mes, \"Give swarm size for PSWARM. [42]\");\n    nel = 1;\n    userint_tir(startinfv -> arel, &fit -> psnp, &nel, &def, \"PSNP=\", mes);\n\n    fit -> psco = PSW_PSCO_DEF;\n    def = 2;\n    sprintf(mes, \"Give cognition parameter for PSWARM. [0.5]\");\n    nel = 1;\n    userdble_tir(startinfv -> arel, &fit -> psco, &nel, &def, \"PSCO=\", mes);\n\n    fit -> psso = PSW_PSSO_DEF;\n    def = 2;\n    sprintf(mes, \"Give social parameter for PSWARM. [0.5]\");\n    nel = 1;\n    userdble_tir(startinfv -> arel, &fit -> psso, &nel, &def, \"PSSO=\", mes);\n\n    fit -> psmv = PSW_PSMV_DEF;\n    def = 2;\n    sprintf(mes, \"Give maximum velocity for PSWARM. [1.0]\");\n    nel = 1;\n    userdble_tir(startinfv -> arel, &fit -> psmv, &nel, &def, \"PSMV=\", mes);\n\n    fit -> psnf = PSW_PSNF_DEF;\n    def = 2;    \n    sprintf(mes, \"Number of Evaluations from initial inertia to final inertia for PSWARM. [8000]\");\n    nel = 1;\n    userint_tir(startinfv -> arel, &fit -> psnf, &nel, &def, \"PSNF=\", mes);\n    \n    fit -> psii = PSW_PSII_DEF;\n    def = 2;\n    sprintf(mes, \"Give initial inertia for PSWARM. [0.9]\");\n    nel = 1;\n    userdble_tir(startinfv -> arel, &fit -> psii, &nel, &def, \"PSII=\", mes);\n\n    fit -> psfi = PSW_PSFI_DEF;\n    def = 2;\n    sprintf(mes, \"Give final inertia for PSWARM. [0.4]\");\n    nel = 1;\n    userdble_tir(startinfv -> arel, &fit -> psfi, &nel, &def, \"PSFI=\", mes);\n\n    fit -> psid = PSW_PSID_DEF;\n    def = 2;    \n    sprintf(mes, \"Give increase factor for delta for grid search. [2.0]\");\n    nel = 1;\n    userdble_tir(startinfv -> arel, &fit -> psid, &nel, &def, \"PSID=\", mes);\n\n    fit -> psdd = PSW_PSDD_DEF;\n    def = 2;\n    sprintf(mes, \"Give decrease factor for delta for grid search. [2.0]\");\n    nel = 1;\n    userdble_tir(startinfv -> arel, &fit -> psdd, &nel, &def, \"PSDD=\", mes);\n  }\n  /* We are through with the first hdu, so it will be created if not already existent */\n  /******************/\n  /******************/\n  /* This was commented hdu stuff */\n  /*   if ((log -> logname) && (log -> logpres)) { */\n  /*     if ((create_hdu_1(log, hdr, rpm, fit))) */\n  /*       goto error; */\n  /*   } */\n  /*   ftstab_close_(); */\n  /******************/\n  /******************/\n\n  /* Make a flush and don't forget to recreate the hdrlist */\n/*   ftstab_flush_(); */\n/*   ftstab_hdlreset_(); */\n/*   hdl_init(); */\n  \n  /* Now open the second hdu, if possible and if we expect one */\n/*   if ((log -> logname) && !(log -> logpres)) { */\n    \n/*      Try to open the file to check if it is already present */\n/*     log -> logpres = ftstab_fopen(log -> logname, 2, 2, 1); */\n    \n/*     Furthermore we will simply overwrite the extension  */\n/*     ftstab_close_(); */\n/*     ftstab_flush_();   */\n/*     ftstab_hdlreset_(); */\n/*     hdl_init(); */\n/*     log -> logpres = 1; */\n    \n/*   } */\n  \n  /*****************************/\n  /******* new way to read parameters ********/\n  /*****************************/\n\n\n  /* The complicated varystr */\n  /* Finally, no static arrays any more */\n  /* if (!(varystr = (char **) malloc(VARYSTRELES*sizeof(char *)))) */\n  /*   goto error; */\n  /* if (!(varyhstr = getfcharray(VARYHSTRELES, NULL))) */\n  /*   goto error; */\n  \n  /* get the dcp control structure */\n  if (!(decomp_controlv = decomp_init()))\n    goto error;\n  \n  /* Fill the dcp control structure with parameter information */\n  if ((dec_fill(rpm, decomp_controlv)))\n    goto error;\n  \n    /* Now get the indexed parameters, for that we know only one group */\n  decomp_putsep(decomp_controlv, '\\0', '\\0', ':');\n  \n  errcode = 2;\n  \n  /* Get the index array */\n  neill = 0;\n  while (errcode) {\n    \n    def = 1;\n    \n    /* nel = usertext_tir(varyhstr, &def, \"VARINDX=\",mes); */\n    /* varyhstr[nel] = '\\0'; */\n    if (simparse_scn_arel_readval_string(startinfv -> arel, \"VARINDX\", \"Give fitting index.\", 0, \"\", 0, -1, neill, 0, &keypres, &nreadl, &nreturned, &varyhstr)) {\n      goto error;\n    }\n    /* Interlude: Change the case if it is lower case */\n    i = 0;\n    while (varyhstr[i]) {\n      if (varyhstr[i] >= 'a' && varyhstr[i] <= 'z')\n\tvaryhstr[i] = varyhstr[i]+'A'-'a';\n      ++i;\n    }\n    \n    /* Interpret this */\n    if ((errcode = decomp_get(decomp_controlv, varyhstr, &decomp_listelv, 0))){\n      if (errcode == 1)\n\tgoto error;\n      else {\n\tsprintf(mes, \"VARINDX: \");\n\tif (decomp_errmsg(decomp_controlv))\n\t  strncpy(mes+9,decomp_errmsg(decomp_controlv),72);\n\tcancel_tir(startinfv -> arel, \"VARINDX=\", 2);\n\tprintf(\"report err here\\n\");\n\tanyout_tir(&def, mes);\n\tprintf(\"report err here\\n\");\n\tneill = 1;\n      }\n    }\n  }\n  \n  /* Now use this to prepare an index and change the input method */\n  decomp_index(decomp_controlv, (decomp_listelv) -> nuel, (decomp_listelv) -> poli);\n  \n  /* Deallocate what we don't need anymore, or rather, again */\n  decomp_list_dest(decomp_listelv);\n  decomp_listelv = NULL;\n  \n  errcode = 1;\n  k = 0;\n  \n  /* Get the vary array */\n  neill = 0;\n  while (errcode) {\n    nel = 0;\n    def = 1;\n    \n    if (errcode == 2)\n      cancel_tir(startinfv -> arel, \"VARY=\", 2);\n    sprintf(mes, \"Give fit parameters\");\n    if ((varyhstr))\n      free(varyhstr);\n\n    /* flushfcharray(VARYHSTRELES, varyhstr); */\n    /* nel = usertext_tir(varyhstr, &def, \"VARY=\", mes); */\n    if (simparse_scn_arel_readval_string(startinfv -> arel, \"VARY\", \"Give fitting index.\", 0, \"\", 0, -1, neill, 0, &keypres, &nreadl, &nreturned, &varyhstr)) {\n      goto error;\n    }\n\n    /* only if this is 0, we ask (completely hidden) for an input in the old style */\n    if (!strlen(varyhstr)) {\n\n      /* Read in and make a decomp-interpretable string of varysing and varymult */\n      nel = 0;\n      \n      if ((errcode == 2) && (k == 1))\n\tcancel_tir(startinfv -> arel, \"VARYSING=\", 2);\n      /* sprintf(mes, \"Give fit parameters, single\"); */\n      /* flushfcharray(VARYHSTRELES, varyhstr); */\n      /* nel = usertext_tir(varyhstr, &def, \"VARYSING=\",mes); */\n      if ((varyhstr)) {\n\tfree(varyhstr);\n\tvaryhstr = NULL;\n      }\n\n      if (simparse_scn_arel_readval_string(startinfv -> arel, \"VARYSING\", \"Give fit parameters, single.\", 0, \"\", 0, -1, 0, 0, &keypres, &nreadl, &nreturned, &varyhstr))\n\tgoto error;\n\n      if (!(inputofvarysing = sparsenext(\" \\t\", \"\", \"\", \"\", \"\", \"\", -1, &varyhstr, &anint, 1, 1)))\n\tgoto error;\n      \n      if (errcode == 2 && (k == 1))\n\tcancel_tir(startinfv -> arel, \"VARYMULT=\", 2);\n      /* sprintf(mes, \"Give fit parameters, multi\"); */\n      /* flushfcharray(VARYHSTRELES, varyhstr); */\n      /* nel = usertext_tir(varyhstr, &def, \"VARYMULT=\",mes); */\n      /* varyhstr[nel] = '\\0'; */\n      if ((varyhstr)) {\n\tfree(varyhstr);\n\tvaryhstr = NULL;\n      }\n\n      if (simparse_scn_arel_readval_string(startinfv -> arel, \"VARYMULT\", \"Give fit parameters, multi.\", 0, \"\", 0, -1, 0, 0, &keypres, &nreadl, &nreturned, &varyhstr))\n\tgoto error;\n\n      if (!(inputofvarymult = sparsenext(\" \\t\", \"\", \"\", \"\", \"\", \"\", -1, &varyhstr, &anint, 1, 1)))\n\tgoto error;\n\n      /* flushfcharray(VARYHSTRELES, varyhstr); */\n      if ((varyhstr)) {\n\tfree(varyhstr);\n\tvaryhstr = NULL;\n      }\n      if (!(varyhstr = gluetodecomp(inputofvarymult, inputofvarysing)))\n\tgoto error;\n      \n      if (inputofvarysing)\n\tfreeparsed(inputofvarysing);\n      inputofvarysing = NULL;\n      \n      if (inputofvarymult)\n\tfreeparsed(inputofvarymult);\n      inputofvarymult = NULL;\n      \n      k = 1;\n    }\n\n    /* Interlude: Change the case if it is lower case */\n    i = 0;\n    while (varyhstr[i]) {\n      if (varyhstr[i] >= 'a' && varyhstr[i] <= 'z')\n\tvaryhstr[i] = varyhstr[i]+'A'-'a';\n      ++i;\n    }\n    \n    decomp_putsep(decomp_controlv, ',', '!', ':');\n    \n    /* Interpret this */\n    if ((errcode = decomp_get(decomp_controlv, varyhstr, &decomp_listelv, 0))){\n      if (errcode == 1)\n\tgoto error;\n      else {\n\tsprintf(mes, \"VARY (error also occurs for VARYSING and VARYMULT): \");\n\tif ((dcperr = decomp_errmsg(decomp_controlv)))\n\t  strncpy(mes+6, dcperr, 74);\n\tanyout_tir(&def, mes);\n\tneill = 1;\n      }\n    }\n  }\n\n  /* We safe the varyhstr */\n  fit -> varyhstr = varyhstr;\n  varyhstr = NULL;\n  \n  /* We create the index list */\n  if (!(fit -> index = decomp_inlist_init()))\n    goto error;\n  if ((neill = decomp_get_inlist(decomp_controlv, fit -> index))) {\n    if (neill == 2)\n      printf(\"Syntax error in VARINDX\\n\");\n    goto error;\n  }\n  \n  /* Now that we have that array, we can get the other parameters, allocate space for that: count the numbers of parameters needed */\n  k = 0;\n  /* m = 0; */\n  \n  if (decomp_listelv) {\n    i = 0;\n    while ((decomp_listelv+i) -> nuel != -1) {\n      k = (decomp_listelv+i) -> grnr+1;\n      ++i;\n    }\n  }\n\n\n  if (varyhstr) {\n    free(varyhstr);\n    varyhstr = NULL;\n  }\n\n  /* I think this makes no sense, except to make it freeable at the end of this function */\n  /* if (!(varyhstr = getfcharray(VARYHSTRELES, NULL))) */\n  /*   goto error; */\n  \n  /* Do some allocations */\n  \n  /* Allocate the pointarray */\n  if (!(pointarray = (varlel **) malloc(k*sizeof(varlel *))))\n    goto error;\n  \n  /* Allocate the other stuff */\n  if (!(parmax = (double *) malloc(k*sizeof(double))))\n    goto error;\n  if (!(parmin = (double *) malloc(k*sizeof(double))))\n    goto error;\n  if (!(moderate = (int *) malloc(k*sizeof(int))))\n    goto error;\n  if (!(delstart = (double *) malloc(k*sizeof(double))))\n    goto error;\n  if (!(delend = (double *) malloc(k*sizeof(double))))\n    goto error;\n  if (!(itestart = (int *) malloc(k*sizeof(int))))\n    goto error;\n  if (!(iteend = (int *) malloc(k*sizeof(int))))\n    goto error;\n  if (!(satdelt = (double *) malloc(k*sizeof(double))))\n    goto error;\n  if (!(mindelta = (double *) malloc(k*sizeof(double))))\n    goto error;\n  \n  /* Read in all the stuff from the logfile */\n  nel = k;\n\n  /* Create defaults for the case that the user is too lazy */\n  if (create_defaults_from_dcp(hdr, decomp_listelv, parmax, parmin, moderate, delstart, delend, itestart, iteend, satdelt, mindelta, rpm -> nur, rpm -> ndisks, fit -> fitmode))\n    goto error;\n\n  /* Now read in everything from the input */\n  \n  /* Get the steps */  \n  /*   sprintf(mes, \"Give maximal variation deltas (in the same order)\"); */\n  /*   def = 4; */\n  /*   userdble_tir(startinfv -> arel, steps, &nel, &def, \"STEPS=\", mes); */\n  \n  /* Now read in everything from the user input */\n  \n  /* The default is +inf */\n  /* for (i = 0; i < k; ++i) { */\n  /*   parmax[i] = DBL_MAX; */\n  /*   parmin[i] = -DBL_MAX; */\n  /*   moderate[i] = 0; */\n    \n  /* } */\n\n  /* We have created defaults, and the user is allowed to make use of them, hence no longer def = 4, but def = 2 */\n  def = 2;\n  \n  /* Get the parmax */\n  sprintf(mes, \"Give parameter maximum (in the same order)\");\n  userdble_tir(startinfv -> arel, parmax, &nel, &def, \"PARMAX=\", mes);\n\n  /* Get the parmin */\n  sprintf(mes, \"Give parameter minimum (in the same order)\");\n  userdble_tir(startinfv -> arel, parmin, &nel, &def, \"PARMIN=\", mes);\n  \n  /* Get the moderating steps */\n  if (fit -> fitmode != PSWARM) {\n    sprintf(mes, \"Give moderating steps (in the same order)\");\n    userint_tir(startinfv -> arel, moderate, &nel, &def, \"MODERATE=\", mes);\n\n    /* I have no patience programming a warning. If a negative value is\n       given, it will be changed to positive */\n    for (i = 0; i < k; ++i) {\n      if (moderate[i] < 0)\n\tmoderate[i] = -moderate[i];\n    }\n\n    /* Get the start delta */\n    sprintf(mes, \"Give the start delta (in the same order)\");\n    userdble_tir(startinfv -> arel, delstart, &nel, &def, \"DELSTART\", mes);\n\n    /* Get the end delta */\n\n    /* No longer defaults to startdelta, but to defaults */\n    /* if (def == 5) { */\n    /*   for (i = 0; i < k; ++i) */\n    /* \tdelend[i] = delstart[i]; */\n    /* } */\n    sprintf(mes, \"Give the end delta (in the same order)\");\n    userdble_tir(startinfv -> arel, delend, &nel, &def, \"DELEND\", mes);\n  }\n  else {\n    for (i = 0; i < k; ++i) {\n      moderate[i] = 0;\n    }\n  }\n  /* These are not required for fitmode metropolis (which currently does not exist) */\n\n  if (fit -> fitmode >= GOLDEN_SECTION) {\n    /* Get the itestart */\n    /* defaul = defaul%4; */\n    \n    if (fit -> fitmode == GOLDEN_SECTION) {\n      sprintf(mes, \"Give starting number of iterations\");\n      nread = userint_tir(startinfv -> arel, itestart, &nel, &def, \"ITESTART\", mes);\n      \n      /* I have no patience programming a warning. If a negative value is\n\t given, it will be changed to positive and 0 will be changed to 1 */\n      for (i = 0; i < k; ++i) {\n\tif (itestart[i] < 0)\n\t  itestart[i] = -itestart[i];\n\tif (itestart[i] == 0)\n\t  itestart[i] = 1;\n\tif (i >= nread || fit -> fitmode > GOLDEN_SECTION) {\n\t  if (i > 0)\n\t    itestart[i] = itestart[i-1];\n\t}\n      }\n      \n      /* Get the iteend */\n      /* Defaults to itestart */\n      /* if (def%4 == 1) {  */\n      /* \tfor (i = 0; i < k; ++i) */\n      /* \t  iteend[i] = itestart[i]; */\n      /* } */\n      \n      /* def = def%4; */\n      sprintf(mes, \"Give final number of iterations (in the same order)\");\n      nread = userint_tir(startinfv -> arel, iteend, &nel, &def, \"ITEEND\", mes);\n      \n      /* I have no patience programming a warning. If a negative value is\n\t given, it will be changed to positive and 0 will be changed to 1 */\n      for (i = 0; i < k; ++i) {\n\tif (iteend[i] < 0)\n\t  iteend[i] = -iteend[i];\n\tif (iteend[i] == 1)\n\t  iteend[i] = 1;\n\tif (i >= nread || fit -> fitmode > GOLDEN_SECTION) {\n\t  if (i > 0)\n\t    iteend[i] = iteend[i-1];\n\t}\n      }\n\n      /* if (defaul != 2) */\n      /* \tdefaul |= 4; */\n      /* if (def != 2) */\n      /* \tdef |= 4; */\n    \n      /* Get the satisfaction delta*/\n      sprintf(mes, \"Give the satisfaction deltas (in the same order)\");\n      userdble_tir(startinfv -> arel, satdelt, &nel, &def, \"SATDELT=\", mes);\n\n      /* dito */\n      for (i = 0; i < k; ++i) {\n\tif (satdelt[i] < 0)\n\t  satdelt[i] = -satdelt[i];\n      }\n    }\n    else {\n      for (i = 0; i < k; ++i) {\n\titestart[i] = 0;\n\titeend[i] = 0;\n\tsatdelt[i] = 0.0;\n      }\n    }\n\n    /* if (defaul != 2) */\n    /*   defaul |= 4; */\n    /* if (def != 2) */\n    /*   def |= 4; */\n\n    /* Get the minimum deltas */\n    sprintf(mes, \"Give the minimum deltas (in the same order)\");\n    userdble_tir(startinfv -> arel, mindelta, &nel, &def, \"MINDELTA=\", mes);\n\n    /* dito */\n    for (i = 0; i < k; ++i) {\n      if (mindelta[i] < 0)\n\tmindelta[i] = -mindelta[i];\n    }\n  }\n  /* else { */\n  /*   for (i = 0; i < k; ++i) { */\n  /*     mindelta[i] = 0.0; */\n  /*   } */\n  /* } */\n\n  /* We create a varylist linked list from the input and link it into fit -> varylist */\n  /* ndisk construction */\n  /* The only possibility for an error is memory problems */\n\n  if (!(fit -> varylist = create_varylist_from_dcp(hdr, decomp_listelv, parmax, parmin, moderate, delstart, delend, itestart, iteend, satdelt, mindelta, rpm -> nur, rpm -> ndisks)))\n    goto error;\n  \n  /* At the end we will check out and initialise certain behaviour dependent on the choice of parameters */\n\n  /* ndisk construction */\n  chkb_sdis(rpm,fit);\n  chkb_vrad(rpm,fit);\n  chkb_vver(rpm,fit);\n  chkb_dvro(rpm,fit);\n  chkb_dvra(rpm,fit);\n  chkb_dvve(rpm,fit);\n  chkb_vm0(rpm,fit);\n  chkb_vm1(rpm,fit);\n  chkb_vm2(rpm,fit);\n  chkb_vm3(rpm,fit);\n  chkb_vm4(rpm,fit);\n  chkb_ra1(rpm,fit);\n  chkb_ra2(rpm,fit);\n  chkb_ra3(rpm,fit);\n  chkb_ra4(rpm,fit);\n  chkb_ro1(rpm,fit);\n  chkb_ro2(rpm,fit);\n  chkb_ro3(rpm,fit);\n  chkb_ro4(rpm,fit);\n  chkb_wm0(rpm,fit);\n  chkb_wm1(rpm,fit);\n  chkb_wm2(rpm,fit);\n  chkb_wm3(rpm,fit);\n  chkb_wm4(rpm,fit);\n  chkb_ls0(rpm,fit);\n  chkb_lc0(rpm,fit);\n  chkb_smi(rpm,fit);\n  chkb_gau(rpm,fit);\n  chkb_azi(rpm,fit);\n\n  /* These are now not necessary anymore, they exist in any case */\n  free(parmax);\n  parmax = NULL;\n  free(parmin);\n  parmin = NULL;\n  free(moderate);\n  moderate = NULL;\n  free(delstart);\n  delstart = NULL;\n  free(delend);\n  delend = NULL;\n  free(itestart);\n  itestart = NULL;\n  free(iteend);\n  iteend = NULL;\n  free(satdelt);\n  satdelt = NULL;\n  free(mindelta);\n  mindelta = NULL;\n  if (array)\n    free(array);\n  array = NULL;\n\n  /* Now write the second hdu if warranted */\n  /* We are thru with the second hdu, so it will be created if not already existent */\n/******************/\n/******************/\n  /* This was commented hdu stuff */\n/*   if ((log -> logname) && (log -> logpres)) { */\n/*     if ((create_hdu_2(log -> logname, fit -> varylist, pointarray, rpm -> nur, hdr))) */\n/*       goto error; */\n/*   } */\n/*   ftstab_close_(); */\n  \n  /* Make a flush and don't forget to recreate the hdrlist */\n/*   ftstab_flush_(); */\n/*   ftstab_hdlreset_(); */\n/*   hdl_init(); */\n\n  /* Calculate degrees of freedom here */\n  /* Count the number of parameters and put them in */\n  varele = fit -> varylist;\n  i = 0;\n  while (varele) {\n    ++i;\n    varele = varele -> next;\n  }\n  fit -> dof = ((double) (hdr -> bsize1*hdr -> bsize2*hdr -> nsubs)/(CONVTHREEDBEAM*hdr -> bmaj*hdr -> bmin))-((double) i);\n\n  \n  /* Now make the arrangements for the minimiser */\n  if (fit -> fitmode > GOLDEN_SECTION) {\n    \n    /* Count the number of parameters and put them in */\n    varele = fit -> varylist;\n    i = 0;\n    while (varele) {\n      ++i;\n      varele = varele -> next;\n    }\n\n    fit -> mon_npar = i;\n\n    size_tv = i;\n    gft_mst_put(fit -> gft_mstv, &size_tv, GFT_INPUT_NPAR);\n\n    /* Allocate the mon_dpar array and initialise */\n    if (!i)\n      ++i;\n\n    if (!(fit -> mon_dpar = (double *) malloc (i*sizeof(double))))\n      goto error;\n\n    fit -> mon_dpar[0] = 0.0;\n\n    /* Allocate a double array for generic use */\n/*     if (!(array = (double *) malloc (i*sizeof(double)))) */\n/*       goto error; */\n    \n    /* Now put in the start parameters, is done in genfit */\n/*     i = 0; */\n/*     varele = fit -> varylist; */\n/*     while (varele) { */\n/*       array[i] = rpm -> par[varele -> elements[0]]; */\n/*       ++i; */\n/*       varele = varele -> next; */\n/*     } */\n/*     gft_mst_put(fit -> gft_mstv, array, GFT_INPUT_SPAR); */\n  } \n  \n  /* Reset the touched array */\n  for (i = rpm -> nur*NSSDPARAMS; i < rpm->nur *(NSSDPARAMS+NDPARAMS*rpm->ndisks); ++i) {\n    rpm -> chapar[i] = 1;\n  }\n\n  /* Count the number of parameters and put them in */\n  /* varele = fit -> varylist; */\n  /* i = 0; */\n  /* while (varele) { */\n  /*   printf(\"varylist entry: %i\\n\",i); */\n  /*   printf(\"elements:\"); */\n  /*   for (j = 0; j < varele -> nelem; ++j) { */\n  /*     printf(\" %i\", varele -> elements[j]); */\n  /*   } */\n  /*     printf(\"\\n         \"); */\n  /*   for (j = 0; j < varele -> nelem; ++j) { */\n  /*     printf(\" %i\", varele -> elements[j]%rpm -> nur); */\n  /*   } */\n  /*     printf(\"\\n\"); */\n  /*     printf(\"\\n\"); */\n  /*   ++i; */\n  /*   varele = varele -> next; */\n  /* } */\n\n  /* Interpolate over the index once */\n  if (changedependent(rpm, rpm -> par, fit -> index, rpm -> chapar) < 0)\n    goto error;\n\n  /* Deallocate things */\n  if ((array))\n    free(array);\n  \n  if ((pointarray))\n    free(pointarray);\n    \n  if (varylist && varylist != fit -> varylist)\n    destroyvarlel(varylist);\n  \n  /* if ((varystr)) { */\n  /*   free(varystr); */\n  /* } */\n  \n  if ((varyhstr))\n    free(varyhstr);\n\n  if ((flistel))\n    destroyinlistel(flistel);\n  \n  if ((decomp_controlv)) \n    decomp_dest(decomp_controlv);\n\n  if ((decomp_listelv))\n    decomp_list_dest(decomp_listelv);\n  \n  if (inputofvarysing)\n    freeparsed(inputofvarysing);\n  \n  if (inputofvarymult)\n    freeparsed(inputofvarymult);\n\n  if (!(fit -> reg_contv =  reg_cont_get(startinfv, hdr, rpm, fit)))\n    goto error;\n\n  return fit;\n  \n error:\n  destroy_fitparms(fit);\n  \n  if ((adarv))\n    free(adarv);\n  \n  if (varylist)\n    destroyvarlel(varylist);\n  \n  if ((flistel))\n    destroyinlistel(flistel);\n  \n  if ((varystr)) {\n    free(varystr);\n  }\n  if ((varyhstr))\n    free(varyhstr);\n  \n  /* Allocate the pointarray */\n  if ((pointarray))\n    free(pointarray);\n  \n  /* Allocate the */\n  if ((parmax))\n    free(parmax);\n  \n  /* Allocate the */\n  if ((parmin))\n    free(parmin);\n    \n  /* Allocate the */\n  if ((moderate))\n    free(moderate);\n    \n  /* Allocate the */\n  if ((delstart))\n    free(delstart);\n    \n  /* Allocate the */\n  if ((delend))\n    free(delend);\n    \n  /* Allocate the */\n  if ((itestart))\n    free(itestart);\n    \n  /* Allocate the */\n  if ((iteend))\n    free(iteend);\n    \n  if ((satdelt))\n    free(satdelt);\n    \n  if ((mindelta))\n    free(mindelta);\n    \n  if ((array))\n    free(array);\n\n  if (inputofvarysing)\n    freeparsed(inputofvarysing);\n\n  if (inputofvarymult)\n    freeparsed(inputofvarymult);\n\n  if ((decomp_controlv)) \n    decomp_dest(decomp_controlv);\n  \n  if ((decomp_listelv))\n    decomp_list_dest(decomp_listelv);\n\n  /*   if ((elements)) */\n  /*     free(elements); */\n      /******/   \n\n  return NULL;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\nstatic  varlel *create_varylist_from_dcp(hdrinf *hdr, decomp_listel *decomp_listelv, double *parmax, double *parmin, int *moderate, double *delstart, double *delend, int *itestart, int *iteend, double *satdelt, double *mindelta, int nur, int ndisks)\n{\n  varlel *varylist = NULL, *varyfirst = NULL;\n  int i = 0, j;\n  /******/\n  /******/\n/*   int obsint = 0; */\n/*   char obsmes[200]; */\n  /******/   \n\n  if (!(decomp_listelv))\n    goto error;\n\n  if (!(varyfirst = appendvarlel(NULL)))\n    goto error;\n\n  varylist = varyfirst;\n\n  while (((decomp_listelv+i) -> nuel) != -1) {\n    varylist -> nelem = (decomp_listelv + i) -> nuel;\n    \n    if (varylist -> nelem > 0) {\n      if (!((varylist -> elements) = (int *) malloc(varylist -> nelem * sizeof(int))))\n\t\t  goto error;\n    \n    \n      for (j = 0; j < varylist -> nelem; ++j) \n\t\t  varylist -> elements[j] = (decomp_listelv+i) -> poli[j];\n\n      /* poli[j] is the list of elements PXPOS etc., meaning that poli[0] points to the appropriate parameter */\n      \n      varylist -> parmax   = simpleglobtointern(parmax[(decomp_listelv + i) -> grnr], varylist -> nelem > 0?varylist -> elements[0]/nur+1:0, hdr, ndisks);\n      varylist -> parmin   = simpleglobtointern(parmin[(decomp_listelv + i) -> grnr], varylist -> nelem > 0?varylist -> elements[0]/nur+1:0, hdr, ndisks);   \n      varylist -> moderate = moderate[(decomp_listelv + i) -> grnr]; \n      varylist -> delstart = ddparamtointern(delstart[(decomp_listelv + i) -> grnr], varylist -> nelem > 0?varylist -> elements[0]/nur+1:0, hdr, ndisks); \n      varylist -> delend   = ddparamtointern(delend[(decomp_listelv + i) -> grnr], varylist -> nelem > 0?varylist -> elements[0]/nur+1:0, hdr, ndisks);   \n      varylist -> itestart = itestart[(decomp_listelv + i) -> grnr]; \n      varylist -> iteend   = iteend[(decomp_listelv + i) -> grnr];   \n      varylist -> satdelt  = ddparamtointern(satdelt[(decomp_listelv + i) -> grnr], varylist -> nelem > 0?varylist -> elements[0]/nur+1:0, hdr, ndisks);  \n      varylist -> mindelta = ddparamtointern(mindelta[(decomp_listelv + i) -> grnr], varylist -> nelem > 0?varylist -> elements[0]/nur+1:0, hdr, ndisks);\n      varylist -> indicator = 0;\n\n      varylist = appendvarlel(varylist);\n    }\n    ++i;\n  }\n  \n  varylist -> nelem = -1;\n  varylist -> elements = NULL;\n  \n  \n  /* The next stuff is a bit unfortunate, but we need a NULL-terminated list */\n  varylist = varyfirst;\n\n  if (varylist)\n    while (varylist -> nelem > -1 && varylist -> next -> nelem > -1)\n      varylist = varylist -> next;\n\n  if (varylist -> nelem > -1) {\n    free(varylist -> next);\n    varylist -> next = NULL;\n  }\n  else {\n    free(varylist);\n    return NULL;\n  }\n  \n  return varyfirst;\n  \n error:\n  destroyvarlel(varyfirst);\n  return NULL;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\nstatic int create_defaults_from_dcp(hdrinf *hdr, decomp_listel *decomp_listelv, double *parmax, double *parmin, int *moderate, double *delstart, double *delend, int *itestart, int *iteend, double *satdelt, double *mindelta, int nur, int ndisks, int fitmode)\n{\n  int i = 0, parnum;\n  double value;\n  /******/\n  /******/\n/*   int obsint = 0; */\n/*   char obsmes[200]; */\n  /******/   \n\n  if (!(decomp_listelv))\n    goto error;\n\n  while (((decomp_listelv+i) -> nuel) != -1) {\n    \n    if ((decomp_listelv + i) -> nuel > 0) {\n\n      parnum = (decomp_listelv+i) -> poli[0];\n\n      /* poli[j] is the list of elements PXPOS etc., meaning that poli[0] points to the appropriate parameter */\n      \n      if (tirific_defaults_fitdefromident(parnum, nur, ndisks, fitmode, TIRIDENT_PARMAX  , &value)) return 1; parmax  [(decomp_listelv + i) -> grnr] = value;\n      if (tirific_defaults_fitdefromident(parnum, nur, ndisks, fitmode, TIRIDENT_PARMIN  , &value)) return 1; parmin  [(decomp_listelv + i) -> grnr] = value;\n      if (tirific_defaults_fitdefromident(parnum, nur, ndisks, fitmode, TIRIDENT_MODERATE, &value)) return 1; moderate[(decomp_listelv + i) -> grnr] = value;\n      if (tirific_defaults_fitdefromident(parnum, nur, ndisks, fitmode, TIRIDENT_DELSTART, &value)) return 1; delstart[(decomp_listelv + i) -> grnr] = value;\n      if (tirific_defaults_fitdefromident(parnum, nur, ndisks, fitmode, TIRIDENT_DELEND  , &value)) return 1; delend  [(decomp_listelv + i) -> grnr] = value;\n      if (tirific_defaults_fitdefromident(parnum, nur, ndisks, fitmode, TIRIDENT_ITESTART, &value)) return 1; itestart[(decomp_listelv + i) -> grnr] = value;\n      if (tirific_defaults_fitdefromident(parnum, nur, ndisks, fitmode, TIRIDENT_ITEEND  , &value)) return 1; iteend  [(decomp_listelv + i) -> grnr] = value;\n      if (tirific_defaults_fitdefromident(parnum, nur, ndisks, fitmode, TIRIDENT_SATDELT , &value)) return 1; satdelt [(decomp_listelv + i) -> grnr] = value;\n      if (tirific_defaults_fitdefromident(parnum, nur, ndisks, fitmode, TIRIDENT_MINDELTA, &value)) return 1; mindelta[(decomp_listelv + i) -> grnr] = value;\n    }\n    ++i;\n  }\n  \n  return 0;\n  \n error:\n  return 1;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Conversion of some units */\nstatic double simpleglobtointern(double value, int par, hdrinf *hdr, int ndisks)\n{\n  int condisp;\n\n  condisp = (NPARAMS + (ndisks - 1)*NDPARAMS)+1;\n\n  if (par == RADI) \n    return value/hdr -> deltgridtouser[0];\n\n  if (par == (condisp))\n    return value/hdr -> deltgridtouser[2];\n\n\n  par = (par-NSSDPARAMS-1)%NDPARAMS + NSSDPARAMS + 1;\n  if (par == VROT)\n    return value/hdr -> deltgridtouser[2];\n  if (par == VRAD)\n    return value/hdr -> deltgridtouser[2];\n  if (par == VVER)\n    return value/hdr -> deltgridtouser[2];\n  if (par == DVRO)\n    return value/hdr -> deltgridtouser[2]*hdr -> deltgridtouser[0];\n  if (par == DVRA)\n    return value/hdr -> deltgridtouser[2]*hdr -> deltgridtouser[0];\n  if (par == DVVE)\n    return value/hdr -> deltgridtouser[2]*hdr -> deltgridtouser[0];\n  if (par == ZDRO)    \n    return value/hdr -> deltgridtouser[0];\n  if (par == ZDRA)    \n    return value/hdr -> deltgridtouser[0];\n  if (par == ZDVE)    \n    return value/hdr -> deltgridtouser[0];\n  if (par == Z0)    \n     /* Formerly) deltgridtouser[2]; */\n    return value/hdr -> deltgridtouser[0];\n  if (par == SBR)\n    return value/hdr -> jygridtouser;\n  if (par == SM1A)\n    return value/hdr -> jygridtouser;\n  if (par == SM1P)\n    return DEGTORAD*value;\n  if (par == SM2A)\n    return value/hdr -> jygridtouser;\n  if (par == SM2P)\n    return DEGTORAD*value;\n  if (par == SM3A)\n    return value/hdr -> jygridtouser;\n  if (par == SM3P)\n    return DEGTORAD*value;\n  if (par == SM4A)\n    return value/hdr -> jygridtouser;\n  if (par == SM4P)\n    return DEGTORAD*value;\n\n  if (par == GA1A)\n    return value/hdr -> jygridtouser;\n  if (par == GA1P)\n    return DEGTORAD*value;\n  if (par == GA1D)\n    return value/hdr -> deltgridtouser[0];\n/*     return DEGTORAD*value; */\n  if (par == GA2A)\n    return value/hdr -> jygridtouser;\n  if (par == GA2P)\n    return DEGTORAD*value;\n  if (par == GA2D)\n    return value/hdr -> deltgridtouser[0];\n/*     return DEGTORAD*value; */\n  if (par == GA3A)\n    return value/hdr -> jygridtouser;\n  if (par == GA3P)\n    return DEGTORAD*value;\n  if (par == GA3D)\n    return value/hdr -> deltgridtouser[0];\n/*     return DEGTORAD*value; */\n  if (par == GA4A)\n    return value/hdr -> jygridtouser;\n  if (par == GA4P)\n    return DEGTORAD*value;\n  if (par == GA4D)\n    return value/hdr -> deltgridtouser[0];\n/*     return DEGTORAD*value; */\n  if (par == AZ1P)\n    return DEGTORAD*value;\n  if (par == AZ1W)\n    return DEGTORAD*value;\n  if (par == AZ2P)\n    return DEGTORAD*value;\n  if (par == AZ2W)\n    return DEGTORAD*value;\n  if (par == INCL)\n    return DEGTORAD*value;\n  if (par == PA) \n    return DEGTORAD*(value+180);\n    /* globtointern */\n  if (par == XPOS)   \n    return (value - hdr -> userglobcrval[0])/hdr -> userglobcdelt[0]+(hdr -> setcrpix[0]-1.0);\n  if (par == YPOS)   \n    return (value - hdr -> userglobcrval[1])/hdr -> userglobcdelt[1]+(hdr -> setcrpix[1]-1.0);\n  if (par == VSYS)\n    return (value - hdr -> userglobcrval[2])/hdr -> userglobcdelt[2]+(hdr -> setcrpix[2]-1.0);\n  if (par == SDIS)\n    return value/hdr -> deltgridtouser[2];\n  if (par == CLNR)\n    return value;\n  if (par == VM0A)\n    return value/hdr -> deltgridtouser[2];\n  if (par == VM1A)\n    return value/hdr -> deltgridtouser[2];\n  if (par == VM1P)\n    return DEGTORAD*value;\n  if (par == VM2A)\n    return value/hdr -> deltgridtouser[2];\n  if (par == VM2P)\n    return DEGTORAD*value;\n  if (par == VM3A)\n    return value/hdr -> deltgridtouser[2];\n  if (par == VM3P)\n    return DEGTORAD*value;\n  if (par == VM4A)\n    return value/hdr -> deltgridtouser[2];\n  if (par == VM4P)\n    return DEGTORAD*value;\n  if (par == RA1A)\n    return value/hdr -> deltgridtouser[2];\n  if (par == RA1P)\n    return DEGTORAD*value;\n  if (par == RA2A)\n    return value/hdr -> deltgridtouser[2];\n  if (par == RA2P)\n    return DEGTORAD*value;\n  if (par == RA3A)\n    return value/hdr -> deltgridtouser[2];\n  if (par == RA3P)\n    return DEGTORAD*value;\n  if (par == RA4A)\n    return value/hdr -> deltgridtouser[2];\n  if (par == RA4P)\n    return DEGTORAD*value;\n  if (par == RO1A)\n    return value/hdr -> deltgridtouser[2];\n  if (par == RO1P)\n    return DEGTORAD*value;\n  if (par == RO2A)\n    return value/hdr -> deltgridtouser[2];\n  if (par == RO2P)\n    return DEGTORAD*value;\n  if (par == RO3A)\n    return value/hdr -> deltgridtouser[2];\n  if (par == RO3P)\n    return DEGTORAD*value;\n  if (par == RO4A)\n    return value/hdr -> deltgridtouser[2];\n  if (par == RO4P)\n    return DEGTORAD*value;\n  if (par == WM0A)\n    return value/hdr -> deltgridtouser[0];\n  if (par == WM1A)\n    return value/hdr -> deltgridtouser[0];\n  if (par == WM1P)\n    return DEGTORAD*value;\n  if (par == WM2A)\n    return value/hdr -> deltgridtouser[0];\n  if (par == WM2P)\n    return DEGTORAD*value;\n  if (par == WM3A)\n    return value/hdr -> deltgridtouser[0];\n  if (par == WM3P)\n    return DEGTORAD*value;\n  if (par == WM4A)\n    return value/hdr -> deltgridtouser[0];\n  if (par == WM4P)\n    return DEGTORAD*value;\n  if (par == LS0) \n    return value/hdr -> deltgridtouser[0];\n  if (par == LC0) \n    return value/hdr -> deltgridtouser[0];\n\n      return value;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Conversion of some units */\nstatic double dparamtointern(double value, int par, hdrinf *hdr, int ndisks)\n{\n  int condisp;\n  condisp = (NPARAMS + (ndisks - 1)*NDPARAMS)+1;\n\n    if (RADI == par)\n    return value/hdr -> deltgridtouser[0];\n  if (condisp == par)\n    return value/hdr -> deltgridtouser[2];\n\n  par = (par-NSSDPARAMS-1)%NDPARAMS + NSSDPARAMS+1;\n\n  if (VROT == par)\n    return value/hdr -> deltgridtouser[2];\n  if (VRAD == par)\n    return value/hdr -> deltgridtouser[2];\n  if (VVER == par)\n    return value/hdr -> deltgridtouser[2];\n  if (DVRO == par)\n    return value/hdr -> deltgridtouser[2]*hdr -> deltgridtouser[0];\n  if (DVRA == par)\n    return value/hdr -> deltgridtouser[2]*hdr -> deltgridtouser[0];\n  if (DVVE == par)\n    return value/hdr -> deltgridtouser[2]*hdr -> deltgridtouser[0];\n  if (ZDRO == par)    \n    return value/hdr -> deltgridtouser[0];\n  if (ZDRA == par)    \n    return value/hdr -> deltgridtouser[0];\n  if (ZDVE == par)    \n    return value/hdr -> deltgridtouser[0];\n  if (Z0 == par)    \n    return value/hdr -> deltgridtouser[0];\n  if (SBR == par)\n    return value/hdr -> jygridtouser;\n  if (SM1A == par)\n    return value/hdr -> jygridtouser;\n  if (SM1P == par)\n    return DEGTORAD*value;\n  if (SM2A == par)\n    return value/hdr -> jygridtouser;\n  if (SM2P == par)\n    return DEGTORAD*value;\n  if (SM3A == par)\n    return value/hdr -> jygridtouser;\n  if (SM3P == par)\n    return DEGTORAD*value;\n  if (SM4A == par)\n    return value/hdr -> jygridtouser;\n  if (SM4P == par)\n    return DEGTORAD*value;\n  if (GA1A == par)\n    return value/hdr -> jygridtouser;\n  if (GA1P == par)\n    return DEGTORAD*value;\n  if (GA1D == par)\n    return value/hdr -> deltgridtouser[0];\n/*     return DEGTORAD*value; */\n  if (GA2A == par)\n    return value/hdr -> jygridtouser;\n  if (GA2P == par)\n    return DEGTORAD*value;\n  if (GA2D == par)\n    return value/hdr -> deltgridtouser[0];\n/*     return DEGTORAD*value; */\n  if (GA3A == par)\n    return value/hdr -> jygridtouser;\n  if (GA3P == par)\n    return DEGTORAD*value;\n  if (GA3D == par)\n    return value/hdr -> deltgridtouser[0];\n/*     return DEGTORAD*value; */\n  if (GA4A == par)\n    return value/hdr -> jygridtouser;\n  if (GA4P == par)\n    return DEGTORAD*value;\n  if (GA4D == par)\n    return value/hdr -> deltgridtouser[0];\n/*     return DEGTORAD*value; */\n  if (AZ1P == par)\n    return DEGTORAD*value;\n  if (AZ1W == par)\n    return DEGTORAD*value;\n  if (AZ2P == par)\n    return DEGTORAD*value;\n  if (AZ2W == par)\n    return DEGTORAD*value;\n  if (INCL == par)\n    return DEGTORAD*value;\n  if (PA == par) \n    return DEGTORAD*(value+180);\n  if (XPOS == par)   \n    return value/hdr -> globgridtouser[0];\n  if (YPOS == par)   \n    return value/hdr -> globgridtouser[1];\n  if (VSYS == par)\n    return value/hdr -> globgridtouser[2];\n  if (SDIS == par)\n    return value/hdr -> deltgridtouser[2];\n  if (CLNR == par)\n    return value;\n  if (VM0A == par)\n    return value/hdr -> deltgridtouser[2];\n    /* These are the new ones */\n  if (VM1A == par)\n    return value/hdr -> deltgridtouser[2];\n  if (VM1P == par)\n    return DEGTORAD*value;\n  if (VM2A == par)\n    return value/hdr -> deltgridtouser[2];\n  if (VM2P == par)\n    return DEGTORAD*value;\n  if (VM3A == par)\n    return value/hdr -> deltgridtouser[2];\n  if (VM3P == par)\n    return DEGTORAD*value;\n  if (VM4A == par)\n    return value/hdr -> deltgridtouser[2];\n  if (VM4P == par)\n    return DEGTORAD*value;\n  if (RA1A == par)\n    return value/hdr -> deltgridtouser[2];\n  if (RA1P == par)\n    return DEGTORAD*value;\n  if (RA2A == par)\n    return value/hdr -> deltgridtouser[2];\n  if (RA2P == par)\n    return DEGTORAD*value;\n  if (RA3A == par)\n    return value/hdr -> deltgridtouser[2];\n  if (RA3P == par)\n    return DEGTORAD*value;\n  if (RA4A == par)\n    return value/hdr -> deltgridtouser[2];\n  if (RA4P == par)\n    return DEGTORAD*value;\n  if (RO1A == par)\n    return value/hdr -> deltgridtouser[2];\n  if (RO1P == par)\n    return DEGTORAD*value;\n  if (RO2A == par)\n    return value/hdr -> deltgridtouser[2];\n  if (RO2P == par)\n    return DEGTORAD*value;\n  if (RO3A == par)\n    return value/hdr -> deltgridtouser[2];\n  if (RO3P == par)\n    return DEGTORAD*value;\n  if (RO4A == par)\n    return value/hdr -> deltgridtouser[2];\n  if (RO4P == par)\n    return DEGTORAD*value;\n  if (WM0A == par)\n    return value/hdr -> deltgridtouser[0];\n  if (WM1A == par)\n    return value/hdr -> deltgridtouser[0];\n  if (WM1P == par)\n    return DEGTORAD*value;\n  if (WM2A == par)\n    return value/hdr -> deltgridtouser[0];\n  if (WM2P == par)\n    return DEGTORAD*value;\n  if (WM3A == par)\n    return value/hdr -> deltgridtouser[0];\n  if (WM3P == par)\n    return DEGTORAD*value;\n  if (WM4A == par)\n    return value/hdr -> deltgridtouser[0];\n  if (WM4P == par)\n    return DEGTORAD*value;\n  if (LC0 == par) \n    return value/hdr -> deltgridtouser[0];\n  if (LS0 == par) \n    return value/hdr -> deltgridtouser[0];\n    return value;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Conversion of some units */\nstatic double ddparamtointern(double value, int par, hdrinf *hdr, int ndisks)\n{\n  int condisp;\n  condisp = (NPARAMS + (ndisks - 1)*NDPARAMS)+1;\n\n  if (RADI == par)\n    return value/hdr -> deltgridtouser[0];\n  if ((condisp) == par)\n    return value/hdr -> deltgridtouser[2];\n\n   par = (par-NSSDPARAMS-1)%NDPARAMS + NSSDPARAMS+1;\n  if (VROT == par)\n    return value/hdr -> deltgridtouser[2];\n  if (VRAD == par)\n    return value/hdr -> deltgridtouser[2];\n  if (VVER == par)\n    return value/hdr -> deltgridtouser[2];\n  if (DVRO == par)\n    return value/hdr -> deltgridtouser[2]*hdr -> deltgridtouser[0];\n  if (DVRA == par)\n    return value/hdr -> deltgridtouser[2]*hdr -> deltgridtouser[0];\n  if (DVVE == par)\n    return value/hdr -> deltgridtouser[2]*hdr -> deltgridtouser[0];\n  if (Z0 == par)    \n    return value/hdr -> deltgridtouser[0];\n  if (ZDRO == par)    \n    return value/hdr -> deltgridtouser[0];\n  if (ZDRA == par)    \n    return value/hdr -> deltgridtouser[0];\n  if (ZDVE == par)    \n    return value/hdr -> deltgridtouser[0];\n  if (SBR == par)\n    return value/hdr -> jygridtouser;\n  if (SM1A == par)\n    return value/hdr -> jygridtouser;\n  if (SM1P == par)\n    return DEGTORAD*value;\n  if (SM2A == par)\n    return value/hdr -> jygridtouser;\n  if (SM2P == par)\n    return DEGTORAD*value;\n  if (SM3A == par)\n    return value/hdr -> jygridtouser;\n  if (SM3P == par)\n    return DEGTORAD*value;\n  if (SM4A == par)\n    return value/hdr -> jygridtouser;\n  if (SM4P == par)\n    return DEGTORAD*value;\n  if (GA1A == par)\n    return value/hdr -> jygridtouser;\n  if (GA1P == par)\n    return DEGTORAD*value;\n  if (GA1D == par)\n    return value/hdr -> deltgridtouser[0];\n    /*     return DEGTORAD*value; */\n  if (GA2A == par)\n    return value/hdr -> jygridtouser;\n  if (GA2P == par)\n    return DEGTORAD*value;\n  if (GA2D == par)\n    return value/hdr -> deltgridtouser[0];\n    /*     return DEGTORAD*value; */\n  if (GA3A == par)\n    return value/hdr -> jygridtouser;\n  if (GA3P == par)\n    return DEGTORAD*value;\n  if (GA3D == par)\n    return value/hdr -> deltgridtouser[0];\n    /*     return DEGTORAD*value; */\n  if (GA4A == par)\n    return value/hdr -> jygridtouser;\n  if (GA4P == par)\n    return DEGTORAD*value;\n  if (GA4D == par)\n    return value/hdr -> deltgridtouser[0];\n    /*     return DEGTORAD*value; */\n  if (AZ1P == par)\n    return DEGTORAD*value;\n  if (AZ1W == par)\n    return DEGTORAD*value;\n  if (AZ2P == par)\n    return DEGTORAD*value;\n  if (AZ2W == par)\n    return DEGTORAD*value;\n  if (INCL == par)\n    return DEGTORAD*value;\n  if (PA == par) \n    return DEGTORAD*(value);\n  if (XPOS == par)   \n    return value/hdr -> globgridtouser[0];\n  if (YPOS == par)   \n    return value/hdr -> globgridtouser[1];\n  if (VSYS == par)\n    return value/hdr -> globgridtouser[2];\n  if (SDIS == par)\n    return value/hdr -> deltgridtouser[2];\n  if (CLNR == par)\n    return value;\n  if (VM0A == par)\n    return value/hdr -> deltgridtouser[2];\n    /* These are the new ones */\n  if (VM1A == par)\n    return value/hdr -> deltgridtouser[2];\n  if (VM1P == par)\n    return DEGTORAD*value;\n  if (VM2A == par)\n    return value/hdr -> deltgridtouser[2];\n  if (VM2P == par)\n    return DEGTORAD*value;\n  if (VM3A == par)\n    return value/hdr -> deltgridtouser[2];\n  if (VM3P == par)\n    return DEGTORAD*value;\n  if (VM4A == par)\n    return value/hdr -> deltgridtouser[2];\n  if (VM4P == par)\n    return DEGTORAD*value;\n  if (RA1A == par)\n    return value/hdr -> deltgridtouser[2];\n  if (RA1P == par)\n    return DEGTORAD*value;\n  if (RA2A == par)\n    return value/hdr -> deltgridtouser[2];\n  if (RA2P == par)\n    return DEGTORAD*value;\n  if (RA3A == par)\n    return value/hdr -> deltgridtouser[2];\n  if (RA3P == par)\n    return DEGTORAD*value;\n  if (RA4A == par)\n    return value/hdr -> deltgridtouser[2];\n  if (RA4P == par)\n    return DEGTORAD*value;\n  if (RO1A == par)\n    return value/hdr -> deltgridtouser[2];\n  if (RO1P == par)\n    return DEGTORAD*value;\n  if (RO2A == par)\n    return value/hdr -> deltgridtouser[2];\n  if (RO2P == par)\n    return DEGTORAD*value;\n  if (RO3A == par)\n    return value/hdr -> deltgridtouser[2];\n  if (RO3P == par)\n    return DEGTORAD*value;\n  if (RO4A == par)\n    return value/hdr -> deltgridtouser[2];\n  if (RO4P == par)\n    return DEGTORAD*value;\n  if (WM0A == par)\n    return value/hdr -> deltgridtouser[0];\n  if (WM1A == par)\n    return value/hdr -> deltgridtouser[0];\n  if (WM1P == par)\n    return DEGTORAD*value;\n  if (WM2A == par)\n    return value/hdr -> deltgridtouser[0];\n  if (WM2P == par)\n    return DEGTORAD*value;\n  if (WM3A == par)\n    return value/hdr -> deltgridtouser[0];\n  if (WM3P == par)\n    return DEGTORAD*value;\n  if (WM4A == par)\n    return value/hdr -> deltgridtouser[0];\n  if (WM4P == par)\n    return DEGTORAD*value;\n  if (LC0 == par) \n    return value/hdr -> deltgridtouser[0];\n  if (LS0 == par) \n    return value/hdr -> deltgridtouser[0];\n\n    return value;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Conversion of some units */\nstatic double dinterntoparam(double value, int par, hdrinf *hdr, int ndisks)\n{\n  int condisp;\n  condisp = (NPARAMS + (ndisks - 1)*NDPARAMS)+1;\n\n\n  if (RADI == par)\n    return value*hdr -> deltgridtouser[0];\n  if ((condisp) == par)\n    return value*hdr -> deltgridtouser[2];\n\n  par = (par-NSSDPARAMS-1)%NDPARAMS + NSSDPARAMS + 1;\n\n  if (VROT == par)   \n    return value*hdr -> deltgridtouser[2];\n  if (VRAD == par)\n    return value*hdr -> deltgridtouser[2];\n  if (VVER == par)\n    return value*hdr -> deltgridtouser[2];\n  if (DVRO == par)\n    return value*hdr -> deltgridtouser[2]/hdr -> deltgridtouser[0];\n  if (DVRA == par)\n    return value*hdr -> deltgridtouser[2]/hdr -> deltgridtouser[0];\n  if (DVVE == par)\n    return value*hdr -> deltgridtouser[2]/hdr -> deltgridtouser[0];\n  if (Z0 == par)     \n    return value*hdr -> deltgridtouser[1];\n  if (ZDRO == par)     \n    return value*hdr -> deltgridtouser[1];\n  if (ZDRA == par)     \n    return value*hdr -> deltgridtouser[1];\n  if (ZDVE == par)     \n    return value*hdr -> deltgridtouser[1];\n  if (SBR == par)\n    return value*hdr -> jygridtouser;\n  if (SM1A == par)\n    return value*hdr -> jygridtouser;\n  if (SM1P == par)\n    return RADTODEG*value;\n  if (SM2A == par)\n    return value*hdr -> jygridtouser;\n  if (SM2P == par)\n    return RADTODEG*value;\n  if (SM3A == par)\n    return value*hdr -> jygridtouser;\n  if (SM3P == par)\n    return RADTODEG*value;\n  if (SM4A == par)\n    return value*hdr -> jygridtouser;\n  if (SM4P == par)\n    return RADTODEG*value;\n  if (GA1A == par)\n    return value*hdr -> jygridtouser;\n  if (GA1P == par)\n    return RADTODEG*value;\n  if (GA1D == par)\n    return value*hdr -> deltgridtouser[0];\n/*     return RADTODEG*value; */\n  if (GA2A == par)\n    return value*hdr -> jygridtouser;\n  if (GA2P == par)\n    return RADTODEG*value;\n  if (GA2D == par)\n    return value*hdr -> deltgridtouser[0];\n/*     return RADTODEG*value; */\n  if (GA3A == par)\n    return value*hdr -> jygridtouser;\n  if (GA3P == par)\n    return RADTODEG*value;\n  if (GA3D == par)\n    return value*hdr -> deltgridtouser[0];\n/*     return RADTODEG*value; */\n  if (GA4A == par)\n    return value*hdr -> jygridtouser;\n  if (GA4P == par)\n    return RADTODEG*value;\n  if (GA4D == par)\n    return value*hdr -> deltgridtouser[0];\n/*     return RADTODEG*value; */\n  if (AZ1P == par)\n    return RADTODEG*value;\n  if (AZ1W == par)\n    return RADTODEG*value;\n  if (AZ2P == par)\n    return RADTODEG*value;\n  if (AZ2W == par)\n    return RADTODEG*value;\n  if (INCL == par)\n    return RADTODEG*value;\n  if (PA == par) \n    return RADTODEG*value-180;\n  if (XPOS == par)   \n    return value*hdr -> globgridtouser[0];\n  if (YPOS == par)   \n    return value*hdr -> globgridtouser[1];\n  if (VSYS == par)\n    return value*hdr -> globgridtouser[2];\n  if (condisp == par)\n    return value*hdr -> deltgridtouser[2];\n  if (SDIS == par)\n    return value*hdr -> deltgridtouser[2];\n  if (CLNR == par)\n    return value;\n    /* These are the new ones */\n  if (VM1A == par)\n    return value*hdr -> deltgridtouser[2];\n  if (VM1P == par)\n    return RADTODEG*value;\n  if (VM2A == par)\n    return value*hdr -> deltgridtouser[2];\n  if (VM2P == par)\n    return RADTODEG*value;\n  if (VM3A == par)\n    return value*hdr -> deltgridtouser[2];\n  if (VM3P == par)\n    return RADTODEG*value;\n  if (VM4A == par)\n    return value*hdr -> deltgridtouser[2];\n  if (VM4P == par)\n    return RADTODEG*value;\n  if (RA1A == par)\n    return value*hdr -> deltgridtouser[2];\n  if (RA1P == par)\n    return RADTODEG*value;\n  if (RA2A == par)\n    return value*hdr -> deltgridtouser[2];\n  if (RA2P == par)\n    return RADTODEG*value;\n  if (RA3A == par)\n    return value*hdr -> deltgridtouser[2];\n  if (RA3P == par)\n    return RADTODEG*value;\n  if (RA4A == par)\n    return value*hdr -> deltgridtouser[2];\n  if (RA4P == par)\n    return RADTODEG*value;\n  if (RO1A == par)\n    return value*hdr -> deltgridtouser[2];\n  if (RO1P == par)\n    return RADTODEG*value;\n  if (RO2A == par)\n    return value*hdr -> deltgridtouser[2];\n  if (RO2P == par)\n    return RADTODEG*value;\n  if (RO3A == par)\n    return value*hdr -> deltgridtouser[2];\n  if (RO3P == par)\n    return RADTODEG*value;\n  if (RO4A == par)\n    return value*hdr -> deltgridtouser[2];\n  if (RO4P == par)\n    return RADTODEG*value;\n  if (VM0A == par) \n    return value*hdr -> deltgridtouser[2];\n  if (WM0A == par) \n    return value*hdr -> deltgridtouser[0];\n  if (WM1A == par)\n    return value*hdr -> deltgridtouser[0];\n  if (WM1P == par)\n    return RADTODEG*value;\n  if (WM2A == par)\n    return value*hdr -> deltgridtouser[0];\n  if (WM2P == par)\n    return RADTODEG*value;\n  if (WM3A == par)\n    return value*hdr -> deltgridtouser[0];\n  if (WM3P == par)\n    return RADTODEG*value;\n  if (WM4A == par)\n    return value*hdr -> deltgridtouser[0];\n  if (WM4P == par)\n    return RADTODEG*value;\n  if (LC0 == par) \n    return value*hdr -> deltgridtouser[0];\n  if (LS0 == par) \n    return value*hdr -> deltgridtouser[0];\n\n    return value;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Conversion of some units */\nstatic double ddinterntoparam(double value, int par, hdrinf *hdr, int ndisks)\n{\n  int condisp;\n  condisp = (NPARAMS + (ndisks - 1)*NDPARAMS)+1;\n\n\n  if (RADI == par)\n    return value*hdr -> deltgridtouser[0];\n  if ((condisp) == par)\n    return value*hdr -> deltgridtouser[2];\n\n  par = (par-NSSDPARAMS-1)%NDPARAMS + NSSDPARAMS + 1;\n\n  if (VROT == par)   \n    return value*hdr -> deltgridtouser[2];\n  if (VRAD == par)\n    return value*hdr -> deltgridtouser[2];\n  if (VVER == par)\n    return value*hdr -> deltgridtouser[2];\n  if (DVRO == par)\n    return value*hdr -> deltgridtouser[2]/hdr -> deltgridtouser[0];\n  if (DVRA == par)\n    return value*hdr -> deltgridtouser[2]/hdr -> deltgridtouser[0];\n  if (DVVE == par)\n    return value*hdr -> deltgridtouser[2]/hdr -> deltgridtouser[0];\n  if (ZDRO == par)     \n    return value*hdr -> deltgridtouser[1];\n  if (ZDRA == par)     \n    return value*hdr -> deltgridtouser[1];\n  if (ZDVE == par)     \n    return value*hdr -> deltgridtouser[1];\n  if (Z0 == par)     \n    return value*hdr -> deltgridtouser[1];\n  if (SBR == par)\n    return value*hdr -> jygridtouser;\n  if (SM1A == par)\n    return value*hdr -> jygridtouser;\n  if (SM1P == par)\n    return RADTODEG*value;\n  if (SM2A == par)\n    return value*hdr -> jygridtouser;\n  if (SM2P == par)\n    return RADTODEG*value;\n  if (SM3A == par)\n    return value*hdr -> jygridtouser;\n  if (SM3P == par)\n    return RADTODEG*value;\n  if (SM4A == par)\n    return value*hdr -> jygridtouser;\n  if (SM4P == par)\n    return RADTODEG*value;\n  if (GA1A == par)\n    return value*hdr -> jygridtouser;\n  if (GA1P == par)\n    return RADTODEG*value;\n  if (GA1D == par)\n    return value*hdr -> deltgridtouser[0];\n/*     return RADTODEG*value; */\n  if (GA2A == par)\n    return value*hdr -> jygridtouser;\n  if (GA2P == par)\n    return RADTODEG*value;\n  if (GA2D == par)\n    return value*hdr -> deltgridtouser[0];\n/*     return RADTODEG*value; */\n  if (GA3A == par)\n    return value*hdr -> jygridtouser;\n  if (GA3P == par)\n    return RADTODEG*value;\n  if (GA3D == par)\n    return value*hdr -> deltgridtouser[0];\n/*     return RADTODEG*value; */\n  if (GA4A == par)\n    return value*hdr -> jygridtouser;\n  if (GA4P == par)\n    return RADTODEG*value;\n  if (GA4D == par)\n    return value*hdr -> deltgridtouser[0];\n/*     return RADTODEG*value; */\n  if (AZ1P == par)\n    return RADTODEG*value;\n  if (AZ1W == par)\n    return RADTODEG*value;\n  if (AZ2P == par)\n    return RADTODEG*value;\n  if (AZ2W == par)\n    return RADTODEG*value;\n  if (INCL == par)\n    return RADTODEG*value;\n  if (PA == par) \n    return RADTODEG*value;\n  if (XPOS == par)   \n    return value*hdr -> globgridtouser[0];\n  if (YPOS == par)   \n    return value*hdr -> globgridtouser[1];\n  if (VSYS == par)\n    return value*hdr -> globgridtouser[2];\n  if (condisp == par)\n    return value*hdr -> deltgridtouser[2];\n  if (SDIS == par)\n    return value*hdr -> deltgridtouser[2];\n  if (CLNR == par)\n    return value;\n  if (VM1A == par)\n    return value*hdr -> deltgridtouser[2];\n  if (VM1P == par)\n    return RADTODEG*value;\n    /* These are the new ones */\n  if (VM1A == par)\n    return value*hdr -> deltgridtouser[2];\n  if (VM1P == par)\n    return RADTODEG*value;\n  if (VM2A == par)\n    return value*hdr -> deltgridtouser[2];\n  if (VM2P == par)\n    return RADTODEG*value;\n  if (VM3A == par)\n    return value*hdr -> deltgridtouser[2];\n  if (VM3P == par)\n    return RADTODEG*value;\n  if (VM4A == par)\n    return value*hdr -> deltgridtouser[2];\n  if (VM4P == par)\n    return RADTODEG*value;\n  if (RA1A == par)\n    return value*hdr -> deltgridtouser[2];\n  if (RA1P == par)\n    return RADTODEG*value;\n  if (RA2A == par)\n    return value*hdr -> deltgridtouser[2];\n  if (RA2P == par)\n    return RADTODEG*value;\n  if (RA3A == par)\n    return value*hdr -> deltgridtouser[2];\n  if (RA3P == par)\n    return RADTODEG*value;\n  if (RA4A == par)\n    return value*hdr -> deltgridtouser[2];\n  if (RA4P == par)\n    return RADTODEG*value;\n  if (RO1A == par)\n    return value*hdr -> deltgridtouser[2];\n  if (RO1P == par)\n    return RADTODEG*value;\n  if (RO2A == par)\n    return value*hdr -> deltgridtouser[2];\n  if (RO2P == par)\n    return RADTODEG*value;\n  if (RO3A == par)\n    return value*hdr -> deltgridtouser[2];\n  if (RO3P == par)\n    return RADTODEG*value;\n  if (RO4A == par)\n    return value*hdr -> deltgridtouser[2];\n  if (RO4P == par)\n    return RADTODEG*value;\n  if (VM0A == par) \n    return value*hdr -> deltgridtouser[2];\n  if (WM0A == par) \n    return value*hdr -> deltgridtouser[0];\n  if (WM1A == par)\n    return value*hdr -> deltgridtouser[0];\n  if (WM1P == par)\n    return RADTODEG*value;\n  if (WM2A == par)\n    return value*hdr -> deltgridtouser[0];\n  if (WM2P == par)\n    return RADTODEG*value;\n  if (WM3A == par)\n    return value*hdr -> deltgridtouser[0];\n  if (WM3P == par)\n    return RADTODEG*value;\n  if (WM4A == par)\n    return value*hdr -> deltgridtouser[0];\n  if (WM4P == par)\n    return RADTODEG*value;\n  if (LC0 == par) \n    return value*hdr -> deltgridtouser[0];\n  if (LS0 == par) \n    return value*hdr -> deltgridtouser[0];\n\n    return value;\n  \n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* conversion of map units */\nstatic void globtointern(double *invalue, double *outvalue, hdrinf *hdr)\n{\n  /* int transformation = 0; */\n  double world[3];\n  /* double proutvalue[3]; */\n\n  /* int vint; */\n\n  /* For the sake of velocity, we know the following transformations, if we'd know that we would not require invalue, we could be even faster */\n  world[0] = invalue[0]; /* deg */\n  world[1] = invalue[1]; /* deg */\n  world[2] = invalue[2]*1000.; /* m/s from km/s, I hope */\n\n  /*The function converts directly from w to absolute pixels */\n  cubarithm_w2p(hdr -> oric -> wcs, world, outvalue);\n\n  /* cubarithm_w2p(hdr -> oric -> wcs, world, proutvalue); */\n\n  /* outvalue[0] = proutvalue[0]+hdr -> setcrpix[0]-1; */\n  /* outvalue[1] = proutvalue[1]+hdr -> setcrpix[1]-1; */\n  /* outvalue[2] = proutvalue[2]+hdr -> setcrpix[2]-1; */\n\n  /* below that line, it's very old stuff */\n  /*********************/\n\n  /* Transform the map units into grids */\n  /* dbldbl[0] = invalue[0]/hdr -> globsettouser[0]; */\n  /* dbldbl[1] = invalue[1]/hdr -> globsettouser[1]; */\n\n  /* Get the map unit belonging to velocity */\n  /* outvalue[2] = (invalue[2] - hdr -> userglobcrval[2])/hdr -> userglobcdelt[2]+(hdr -> setcrpix[2]-1.0); */\n\n  /* We assign this to a grid position */\n  /* vint = roundnormal(outvalue[2]); */\n\n  /* There are maximal and minimal values that can be set */\n  /* if (vint < 0) */\n  /*   vint = 0; */\n  /* if (vint >= hdr -> nsubs) */\n  /*   vint =  hdr -> nsubs-1; */\n\n  /* Now do the transformation, it should work */\n  /* cotrans_tir(hdr -> inset, &hdr -> insubs[vint], dbldbl, outvalue, &transformation); */\n \n /* Now we have grids that we have to transform to maps */\n  /* outvalue[0] = outvalue[0]+hdr -> setcrpix[0]-1; */\n  /* outvalue[1] = outvalue[1]+hdr -> setcrpix[1]-1; */\n\n  /* Again, the map unit belonging to velocity, because cotrans does a nasty thing */\n  /* outvalue[2] = (invalue[2] - hdr -> userglobcrval[2])/hdr -> userglobcdelt[2]+(hdr -> setcrpix[2]-1.0); */\n\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* conversion of map units */\nstatic void interntoglob(double *invalue, double *outvalue, hdrinf *hdr)\n{\n  /* int transformation = 1; */\n  /* double dbldbl[2]; */\n  /* int vint; */\n  /* double relpix[3]; */\n  double abspix[3];\n\n  /* Transform the map units into grid units, this is absolute pixel values, starting at 0 */\n  abspix[0] = invalue[0];\n  abspix[1] = invalue[1];\n  abspix[2] = invalue[2];\n\n  /* This would be relative values, as formerly required by gipsy */\n  /* relpix[0] = invalue[0]-hdr -> setcrpix[0]+1; */\n  /* relpix[1] = invalue[1]-hdr -> setcrpix[1]+1; */\n  /* relpix[2] = invalue[2]-hdr -> setcrpix[2]+1; */\n\n  /* cubarithm_p2w(hdr -> oric -> wcs, relpix, outvalue); */\n  cubarithm_p2w(hdr -> oric -> wcs, abspix, outvalue);\n\n  /* This is to take into account that the global units are always degrees (as in tirific) and m/s (which is 1/1000 the tirific unit) */\n  outvalue[2] = outvalue[2]*0.001;\n\n  /* We assign the velocity to a map position */\n  /* vint = roundnormal(invalue[2]); */\n\n  /* There are maximal and minimal values that can be set */\n  /* if (vint < 0) */\n  /*   vint = 0; */\n  /* if (vint >= hdr -> nsubs) */\n  /*   vint =  hdr -> nsubs-1; */\n\n  /* Now do the transformation, it should work */\n  /* cotrans_tir(hdr -> inset, &hdr -> insubs[vint], dbldbl, outvalue, &transformation); */\n\n  /* Get the user unit belonging to velocity */\n  /* outvalue[0] = outvalue[0]*hdr -> globsettouser[0]; */\n  /*   outvalue[1] = outvalue[1]*hdr -> globsettouser[1]; */\n  /* outvalue[2] = (invalue[2]-hdr -> setcrpix[2]+1)*hdr -> userglobcdelt[2]+hdr -> userglobcrval[2]; */\n\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Change the parameter list params to internal units as if being user units */\nstatic void changetointern(double *params, int nur, hdrinf *hdr, int ndisks)\n{\n  /* OK */\n  int i,j,k,disk;\n  double globin[3];\n  double globout[3];\n  int condisp, pcondisp;\n\n/*   for (i = 0; i < nur; ++i) { */\n      \n    /* Some of the easily convertable thingies */\n/*     params[PRADI*nur+i] = dparamtointern(params[PRADI*nur+i], RADI, hdr); */\n/*   } */\n\n  /* This is all very simple */\n  for (disk = 0; disk < ndisks; ++disk){\n    j = PRPARAMS+disk*NDPARAMS;\n\n    for (i = 0; i < nur; ++i) {\n      for (k = 0; k < NDPARAMS; ++k) {\n\tif ((k != PXPOS) && (k != PYPOS) &&(k != PVSYS))\n\t  params[(j+k)*nur+i] = dparamtointern(params[(j+k)*nur+i], j+k+1, hdr, ndisks);\n      }\n\n      /* Now, we have to convert the triplets into internal units */\n      globin[0] = params[(j+PXPOS)*nur+i];\n      globin[1] = params[(j+PYPOS)*nur+i];\n      globin[2] = params[(j+PVSYS)*nur+i];\n      \n      globtointern(globin, globout, hdr);\n      \n      params[(j+PXPOS)*nur+i] = globout[0];\n      params[(j+PYPOS)*nur+i] = globout[1];\n      params[(j+PVSYS)*nur+i] = globout[2];\n    }\n  }\n  pcondisp = (NPARAMS + (ndisks - 1)*NDPARAMS);\n  condisp = pcondisp + 1;\n  params[pcondisp*nur] = dparamtointern(params[pcondisp*nur], condisp, hdr, ndisks);\n\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Constructor of an element of the varlel list */\nstatic varlel *appendvarlel(varlel *last)\n{\n  varlel *out;\n\n  if (!(out = (varlel *) malloc(sizeof(varlel))))\n    return NULL;\n\n  if ((last))\n    last -> next = out;\n\n  /* \"Terminate\" */\n  out -> elements = NULL;\n  out -> nelem = 0;\n  out -> next = NULL;\n\n  return out;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Destructor of a varlel list */\nstatic void destroyvarlel(varlel *first)\n{\n  varlel *next;\n\n  while ((first)) {\n    /* Convention is that elements is dynamically allocated */\n    if ((first -> nelem) > 0)\n      free(first -> elements);\n    next = first -> next;\n    free(first);\n    first = next;\n  }\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* write the output cube */\n\nstatic int writemodel(hdrinf *origin, ringparms *rpm, fitparms *fit, double *par, decomp_inlist *index)\n{\n  int i=0;\n  /* char mes[200]; */\n  int pcondisp;\n  /* int checki = 0, checkia = 0; */\n\n/*   int allnpoints[ndisks]; */\n\n\n  pcondisp = (NPARAMS + (rpm -> ndisks - 1)*NDPARAMS);\n\n  /* If outset is not defined, we stop here */\n  if (*origin -> outset == '\\0') {\n    return 1;\n  }\n\n  /* We have to put the current best values to the cube */\n  for (i = 0; i < rpm -> nur*(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)+NSPARAMS; ++i) {\n    rpm -> par[i] = par[i];\n\n  }\n\n  for (i = rpm -> nur*NSSDPARAMS; i < rpm->nur *(NSSDPARAMS+NDPARAMS*rpm->ndisks); ++i)\n    rpm -> chapar[i] = 1;\n  \n  if (changedependent(rpm, rpm -> par, fit -> index, rpm -> chapar) < 0)\n    goto error;\n\n  /* Testing */\n  /* for(k = 0; k < origin -> nsubs; ++k) */\n  /*   for(j = 0; j < origin -> bsize2; ++j) */\n  /*     for(i = 0; i < origin -> bsize1; ++i) */\n  /* \tif (origin -> modelc -> points[i+2*(origin -> bsize1/2+1)*(j+origin -> bsize2*k)] > 0.) */\n  /* \t  checkia = 1; */\n  /* if (checkia == 1) */\n  /*   printf(\"Is not empty\\n\"); */\n  /* else { */\n  /*   printf(\"Is empty\\n\"); */\n  /* } */\n\n  /* Then we generate the cube and convolve it */\n  galmod(origin, rpm, 1, NULL, index, rpm -> fluxpoints, rpm -> allnpoints);\n\n  origin -> chi2 = getchisquare_c(rpm -> par[(pcondisp)*rpm -> nur]);\n\n  /* Regularise */\n  origin -> chi2 = reg_do(fit -> reg_contv, (fit -> mon_alloops == fit -> loops)?fit -> loops - 1:fit -> mon_alloops, origin -> chi2);\n\n  /* Correct the chisquare taking into account the outliers, don't know if that is necessary here... */\n  origin -> chi2 = origin -> chi2+((double) rpm -> outpoints)*rpm -> penalty;\n\n  /* Now rearrange the cube */\n  /* for(k = 0; k < origin -> nsubs; ++k) */\n  /*   for(j = 0; j < origin -> bsize2; ++j) */\n  /*     for(i = 0; i < origin -> bsize1; ++i) */\n  /* \torigin -> model[i+origin -> bsize1*(j+origin -> bsize2*k)] = origin -> model[i+2*(origin -> bsize1/2+1)*(j+origin -> bsize2*k)]; */\n  /* origin -> primbeam[i+origin -> bsize1*(j)]; */\n\n  /* Write the cube plane by plane, really too lazy to track min and max */\n\n  /* change this first */\n  /* origin -> nprof = origin -> bsize1*origin -> bsize2; */\n\n /* for (i = 0; i < origin -> nsubs; ++i) { */\n /*   j=i*origin -> nprof; */\n\n   /* My god, this has to be set, otherways: crash... */\n /*   l = 0; */\n /*   gdsi_write_tir(origin -> outset, origin -> cwlo+i, origin -> cwhi+i, origin -> model+j, &origin -> nprof, &k, &l); */\n /*   if (l) { */\n /*     i = 1; */\n /*     sprintf(mes, \"Unable to write outset with error %i.\", l); */\n /*     error_tir(&i, mes); */\n /*     return 0; */\n /*   } */\n /* } */\n\n  /* This should do */\n  cubarithm_writecube(origin -> modelc, origin -> outset, NULL);\n\n /* Now change this back */\n /* origin -> nprof = origin -> bcsize1*origin -> bsize2; */\n\n return 1;\n\n error:\n return 0;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* write the output cube */\n\nstatic int writecoolmodel(startinf *startinfv, loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit, double *par, decomp_inlist *index)\n{\n  int i=0;\n  char *coolname = NULL;\n  char **varystr = NULL;\n  int keypres, nread, nreturned;\n\n  char mes[81];\n  int def;\n  int nel;\n  int err;\n\n  /* These should be replaced with the default cube stuff */\n  qfits_header *header;\n  Cube *thecube = NULL;\n  double beam;\n  float *expfcs;\n  float sincosofangle[2];\n\n  long fluxpoints;\n  int allnpoints;\n\n  /* pcondisp = (NPARAMS + (rpm -> ndisks - 1)*NDPARAMS); */\n\n  if (simparse_scn_arel_readval_stringlist(startinfv -> arel, \"COOLGAL\", \"Give cool name.\", 0, NULL, 0, -1, 0, 0, &keypres, &nread, &nreturned, &varystr))\n    goto error;\n  \n  if ((varystr[0])) {\n    if (!(coolname = simparse_copystring(varystr[0]))) {\n      goto error;\n    }\n  }\n  else {\n    if (!(coolname = simparse_copystring(\"\"))) {\n      goto error;\n    }\n  }\n  \n  freeparsed(varystr);\n  varystr = NULL;\n\n  /* The default is to do nothing */\n  if (*coolname == '\\0') {\n    free(coolname);\n    return 1;\n  }\n  \n  /* Now we want the binning number */\n  sprintf(mes, \"Give cool binning\");\n  def = 2;\n  nel = 1;\n  err = 1;\n  hdr -> coolbin = 1;\n  while((err)) {\n    userint_tir(startinfv -> arel, &(hdr -> coolbin), &nel, &def, \"COOLBIN=\", mes);\n    if (hdr -> coolbin >= 1) {\n      err = 0;\n    }\n    else {\n      sprintf(mes, \"COOLBIN should be >= 1\");\n      cancel_tir(startinfv -> arel, \"COOLBIN=\", 2);\n      hdr -> coolbin = 1;\n      def = 1;\n    }\n  } \n\n  /* Now ask if the user wants a specific kind of beam, the default being the max beam */\n  sprintf(mes, \"Give 3d beam size (arcsec)\");\n  beam = hdr -> deltgridtouser[0]*((double) hdr -> bmaj);\n  def = 2;\n  nel = 1;\n  err = 1;\n  beam = 10;\n  while((err)) {\n    userdble_tir(startinfv -> arel, &beam, &nel, &def, \"COOLBEAM=\", mes);\n    if (beam >= 0.0) {\n      err = 0;\n    }\n    else {\n      sprintf(mes, \"COOLBEAM should be >= 0\");\n      cancel_tir(startinfv -> arel, \"COOLBEAM=\", 2);\n      beam = hdr -> deltgridtouser[0]*((double) hdr -> bmaj);\n      def = 1;\n    }\n  } \n  \n  /* Transfer the beam into deg */\n  beam = hdr -> globgridtouser[0]*beam/hdr -> deltgridtouser[0];\n  \n  /* Make a header, if the beam is 0, we normalise everything such that the units get right */\n  if (!(header = makecoolhdr(hdr, ((beam))?beam:sqrt(TWOPI)/(hdr -> globgridtouser[0]*0.42466090014401))))\n    return 1;\n  \n  /* Transfer the beam back to grid units */\n  beam = beam*hdr -> coolbin/(hdr -> globgridtouser[0]);\n    \n  /* Now arrange the cube */\n  if (!(thecube = (Cube *) malloc(sizeof(Cube))))\n    goto error;\n\n  thecube -> refpix_x = 0;\n  thecube -> refpix_y = 0;\n  thecube -> refpix_v = 0;\n  thecube -> size_x = hdr -> bsize1*hdr -> coolbin;\n  thecube -> size_y = hdr -> bsize2*hdr -> coolbin;\n  thecube -> size_v = (thecube -> size_x > thecube -> size_y)?thecube -> size_x:thecube -> size_y;\n  thecube -> scale = 1.0;\n  thecube -> padding = 0;\n\n  /* As a precaution, these are not required, but must be set to NULL to avoid a free on some non-alloced stuff */\n  thecube -> type_x = NULL;\n  thecube -> type_y = NULL;\n  thecube -> type_v = NULL;\n  thecube -> epoch = NULL;\n  thecube -> type = NULL;\n  thecube -> unit = NULL;\n\n  thecube -> asciiheader = NULL;\n  thecube -> points = NULL;\n  thecube -> wcs = NULL;\n\n  /* This is required for gridding */\n  hdr -> coolhalfc = ((float) thecube -> size_v)/2;\n  hdr -> nprofcool = thecube -> size_x*thecube -> size_y;\n\n  tir_get_grid(log, rpm, log -> outarray);\n\n  for (i = 0; i < rpm -> nur*(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)+NSPARAMS; ++i)\n    rpm -> par[i] = log -> outarray[i];\n\n  /*     Convert the read parameter list to internal units */\n  changetointern(rpm -> par, rpm -> nur, hdr, rpm -> ndisks);\n\n  /* provide some info */\n  nel=1;\n  sprintf(mes, \"Cool number of bytes used: %lu\", thecube -> size_x*thecube -> size_y*thecube -> size_v*sizeof(float));\n  anyout_tir(&nel, mes);\n\n  /* Now we allocate the cube, not caring for the padding, this will be done automatically */\n  if (!(thecube -> points = (float *) fftwf_malloc(thecube -> size_x*thecube -> size_y*thecube -> size_v*sizeof(float)))) {\n    ftsout_header_destroy(header);\n    return 1;\n  }\n\n  hdr -> coolcube = thecube;\n\n  /* We have to put the current best values to the cube */\n  for (i = 0; i < rpm -> nur*(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)+NSPARAMS; ++i) {\n    rpm -> par[i] = par[i];\n  }\n\n  for (i = rpm -> nur*NSSDPARAMS; i < rpm->nur *(NSSDPARAMS+NDPARAMS*rpm->ndisks); ++i)\n    rpm -> chapar[i] = 1;\n  \n  /* correct dependent parameters */\n  if (changedependent(rpm, rpm -> par, fit -> index, rpm -> chapar) < 0)\n    goto error;\n\n  /* Then we generate the cube and convolve it */\n  galmodcool(hdr, rpm, 1, NULL, index, &fluxpoints, &allnpoints);\n\n    /* Convolve it */\n  sincosofangle[0] = 0;\n  sincosofangle[1] = 1;\n  \n  if (!(expfcs = expofacsfft(0.42466090014401*beam, 0.42466090014401*beam, 0.42466090014401*beam, sincosofangle))) {\n    ftsout_header_destroy(header);\n    return 1;\n  }\n  \n  /* Now, the normalisation is the fifth factor, we multiply it with this */\n  expfcs[4] = expfcs[4]*sqrtf(TWOPI)*0.42466090014401*beam;\n\n  /* This is the actual convolution */\n\n  if ((beam)) {\n    convolgaussfft(thecube, expfcs);\n  }\n\n  /* Output it */\n  ftsout_writecube(coolname, thecube, header);\n\n  /* Deallocate everything */\n    ftsout_header_destroy(header);\n    free(thecube -> points);\n    thecube -> points = NULL;\n    free(expfcs);\n\n /* Finally */\n  if ((coolname))\n    free(coolname);\n  if ((varystr))\n    freeparsed(varystr);\n  return 1;\n\n error:\n  /* Strangely, for this function, 0 returned means error. This is an old functino... */\n  if ((thecube)) {\n    if (hdr -> coolcube)\n      cubarithm_cube_destroy(hdr -> coolcube);\n    else\n      cubarithm_cube_destroy(thecube);\n  }\n  if ((coolname))\n    free(coolname);\n  if ((varystr))\n    freeparsed(varystr);\n  return 0;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Destructor of a inlistel list */\nstatic void destroyinlistel(inlistel *first)\n{\n  inlistel *next;\n\n  while ((first)) {\n    /* Convention is that elements is dynamically allocated */\n    next = first -> next;\n    free(first);\n    first = next;\n  }\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Opens a file and puts an old-style ascii header to the top */\n\nstatic void prepout(loginf *log, hdrinf *hdr, ringparms *rpm)\n{\n  int i, j;\n  char key[21];\n\n  /* Start with the usual check */\n  if (*log -> textlog == '\\0')\n    return;\n\n  /* We try to open write append without header if the file exists,\n     without checking the content, first closing if this exists */\n  if ((log -> tstream)) {\n    fclose(log -> tstream);\n    log -> tstream = NULL;\n  }\n  if (!(log -> tstream = fopen(log -> textlog, \"r\"))) {\n\n    /* If the file doesn't exist we compose a header */\n    if ((log -> tstream = fopen(log -> textlog, \"w\"))) {\n\n    /* Turn off the buffering for tstream */\n    setbuf(log -> tstream, NULL);\n\n      fprintf(log -> tstream, \" MODEL# \");\n\n      /* We now compose a header entry for each keyword including radius */\n      for (i = 1; i <= (NPARAMS+(rpm -> ndisks-1)*NDPARAMS); ++i) {\n for (j = 0; j < rpm -> nur; ++j) {\n   /* Put the title */\n   ftstab_putcoltitl(key, i);\n   fprintf(log -> tstream, \"%6s\", key);\n   \n   /* Now with an underscore the radius */\n   fprintf(log -> tstream, \"_%04.1f \", dinterntoparam(rpm -> par[PRADI+j], RADI, hdr, rpm -> ndisks));\n }\n      }\n      for (i = 1; i <= NSPARAMS; ++i) {\n\tftstab_putcoltitl(key, i+(NPARAMS+(rpm -> ndisks-1)*NDPARAMS));\n\tfprintf(log -> tstream, \"%11s\", key);\n      }\n\n      /* The chisquare, the reduced chisquare and acceptance */\n      ftstab_putcoltitl(key, NPARAMS+(rpm -> ndisks-1)*NDPARAMS+NSPARAMS+(LASTSING_PRIMPOS+NUMB_MDPRIMPOS*rpm -> ndisks)+SECHDN_MULTI+CHISQ_TABNR);\n      fprintf(log -> tstream, \"%23s\", key);\n      ftstab_putcoltitl(key, NPARAMS+(rpm -> ndisks-1)*NDPARAMS+NSPARAMS+(LASTSING_PRIMPOS+NUMB_MDPRIMPOS*rpm -> ndisks)+SECHDN_MULTI+RCHISQ_TABNR);\n      fprintf(log -> tstream, \"%23s\", key);\n      ftstab_putcoltitl(key, NPARAMS+(rpm -> ndisks-1)*NDPARAMS+NSPARAMS+(LASTSING_PRIMPOS+NUMB_MDPRIMPOS*rpm -> ndisks)+SECHDN_MULTI+ACCEPT_TABNR);\n      fprintf(log -> tstream, \"%10s\", key);\n\n      fprintf(log -> tstream,\"\\n\");\n    }\n  }\n  else {\n    log -> tstream = fopen(log -> textlog, \"a\");\n\n    /* Turn off the buffering for tstream */\n    setbuf(log -> tstream, NULL);\n  }\n\n  return;\n}\n\n\n\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Generic fitting using the gft */\nstatic int genfit(startinf *startinfv, loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit)\n{\n  double indpoints; /* Independent data points */\n  double *dblarray = NULL;\n  double change;\n  double dpar;\n  size_t npar;\n  size_t asize_t = 1, hereiter;\n  int maxmod, anintege; /* maximum occurrence of moderate */\n  \n  int i,j,k;\n  varlel *nextvarlel;\n  \n  /* This block is for reporting at the end only */\n  char mes[2160]; /* Any message: this is really not clever hardcoding. For many disks this will cause a crash */\n  int dev = 1;\n  int disk;\n  size_t length;\n  varlel *varele;\n\n  /* Count the number of entries in the varylist */\n  npar = 0;\n  maxmod = 0;\n  nextvarlel = fit -> varylist;\n  while ((nextvarlel)) {\n    ++npar;\n    if (nextvarlel -> moderate > maxmod)\n      maxmod = nextvarlel -> moderate;\n    nextvarlel = nextvarlel -> next;\n  }\n  \n  /* Now ensure that the indexed parameters are aligned */\n  for (i = rpm -> nur*NSSDPARAMS; i < rpm->nur *(NSSDPARAMS+NDPARAMS*rpm->ndisks); ++i)\n    rpm -> chapar[i] = chkchangep(fit -> varylist, fit -> fitmode, i, rpm -> nur);\n\n  /* When starting make one run of interpover, but first ensure a proper interpolation of the indexed parameters */\n  if (changedependent(rpm, rpm -> par, fit -> index, rpm -> chapar) < 0)\n    goto error;\n\n  interpover(rpm, rpm -> radsep, 0, NULL, fit -> index);\n  \n  /* The degrees of freedom are determined by the amount of variable\n     parameters, we do it VERY roughly. If there is a parameter varied\n     twice, this is not true anymore. Independent pixels are\n     determined by the assumption that HPBW in v is two pixels */\n  indpoints = (double) (hdr -> bsize1*hdr -> bsize2*hdr -> nsubs)/(CONVTHREEDBEAM*hdr -> bmaj*hdr -> bmin);\n  gft_mst_put(fit -> gft_mstv, &indpoints, GFT_INPUT_INDPOINTS);\n      \n  /* Get the number of function calls per iteration */\n  hereiter = fit -> callite;\n  gft_mst_put(fit -> gft_mstv, &hereiter, GFT_INPUT_NCALLS_ST);\n    \n  /* Do the first initialisation */\n  gft_mst_act(fit -> gft_mstv, GFT_ACT_INIT);\n  \n  /* Now check if there are enough loops, iterations, and parameters to fit */\n  if (npar > 0 && fit -> loops > 0 && fit -> maxiter > 0) {\n    \n    /* allocate */\n    if (!(dblarray = (double *) malloc(npar*sizeof(double))))\n      goto error;\n    \n    /* The stopsize is 1 */\n    *dblarray = fit -> size;\n    gft_mst_put(fit -> gft_mstv, dblarray, GFT_INPUT_STOPSIZE);\n    \n    /* Get the number of total iterations left to be made */\n    hereiter = fit -> maxiter;\n    gft_mst_put(fit -> gft_mstv, &hereiter, GFT_INPUT_NITERS);\n\n    /* PSWARM input */\n    if (fit -> fitmode == PSWARM) {\n      anintege = fit -> psse; gft_mst_put(fit -> gft_mstv, &anintege, GFT_INPUT_SEED   );\n      anintege = fit -> psnp; gft_mst_put(fit -> gft_mstv, &anintege, GFT_INPUT_PSNPART);\n      *dblarray = fit -> psco; gft_mst_put(fit -> gft_mstv, dblarray, GFT_INPUT_PSCOGNI);\n      *dblarray = fit -> psso; gft_mst_put(fit -> gft_mstv, dblarray, GFT_INPUT_PSSOCIA);\n      *dblarray = fit -> psmv; gft_mst_put(fit -> gft_mstv, dblarray, GFT_INPUT_PSMAXVF);\n      anintege = fit -> psnf; gft_mst_put(fit -> gft_mstv, &anintege, GFT_INPUT_PSNITFI);\n      *dblarray = fit -> psii; gft_mst_put(fit -> gft_mstv, dblarray, GFT_INPUT_PSINIIN);\n      *dblarray = fit -> psfi; gft_mst_put(fit -> gft_mstv, dblarray, GFT_INPUT_PSFININ);\n      *dblarray = fit -> psid; gft_mst_put(fit -> gft_mstv, dblarray, GFT_INPUT_PSINCDE);\n      *dblarray = fit -> psdd; gft_mst_put(fit -> gft_mstv, dblarray, GFT_INPUT_PSDECDE);\n    }  \n    /* As long as there is moderation, we do this */\n    while (fit -> loopnr <= fit -> loops && fit -> loopnr <= maxmod) {\n      \n     /* The first guess is in rpm -> par */\n      nextvarlel = fit -> varylist;\n      i = 0;\n      while (nextvarlel) {\n\tdblarray[i] = rpm -> par[nextvarlel -> elements[0]];\n\tnextvarlel = nextvarlel -> next;\n\t++i;\n      }\n      gft_mst_put(fit -> gft_mstv, dblarray, GFT_INPUT_SPAR);\n      \n      /* Choose the origin to be identical */\n      gft_mst_put(fit -> gft_mstv, dblarray, GFT_INPUT_OPAR);\n      \n      /* Calculate the start deltas */\n      nextvarlel = fit -> varylist;\n      i = 0;\n      while (nextvarlel) {\n\tdblarray[i] = fit -> loopnr <= nextvarlel -> moderate?((double) (fit -> loopnr - 1))*(nextvarlel -> delend - nextvarlel -> delstart)/((double) nextvarlel -> moderate)+nextvarlel -> delstart:nextvarlel -> delend;\n\tnextvarlel = nextvarlel -> next;\n\t++i;\n      }\n      gft_mst_put(fit -> gft_mstv, dblarray, GFT_INPUT_DPAR);\n\n      /* Calculate the satisfaction deltas or grid normalisation */\n      /* ERROR SOURCE: This is done many times, but positioning it in front of the loops will lead to a segfault. This is a noted but in gft */\n      nextvarlel = fit -> varylist;\n      i = 0;\n      while (nextvarlel) {\n\tdblarray[i] = nextvarlel -> mindelta;\n\tnextvarlel = nextvarlel -> next;\n\t++i;\n      }\n\n      gft_mst_put(fit -> gft_mstv, dblarray, GFT_INPUT_NDPAR);\n\n      /* Put the number of loops to 1 */\n      asize_t = 1;\n      gft_mst_put(fit -> gft_mstv, &asize_t, GFT_INPUT_LOOPS);\n      \n      /* Now DO it */\n      gft_mst_act(fit -> gft_mstv, GFT_ACT_START);\n       \n      /* At the end, in this loop, copy the results to the parameters */\n      gft_mst_get(fit -> gft_mstv, dblarray, GFT_OUTPUT_SOLPAR);\n\n      nextvarlel = fit -> varylist;\n      j = 0;\n      while ((nextvarlel)) {\n\tchange = dblarray[j] - rpm -> par[nextvarlel -> elements[0]];\n\t\n\t/* Every adressant of elements will be changed by the same amount */\n\tfor (i = 0; i < nextvarlel -> nelem; ++i)\n\t  rpm -> par[nextvarlel -> elements[i]] = rpm -> par[nextvarlel -> elements[i]]+change;\n\t++j;\n\tnextvarlel = nextvarlel -> next;\n      }\n\n      /* BUGFIX: change this according to the current solution */\n      for (i = rpm -> nur*NSSDPARAMS; i < rpm ->nur *(NSSDPARAMS+NDPARAMS*rpm -> ndisks); ++i)\n\trpm -> chapar[i] = chkchangep(fit -> varylist, fit -> fitmode, i, rpm -> nur);\n      /*    rpm -> chapar[i] = 1; */\n      \n      if (changedependent(rpm, rpm -> par, fit -> index, rpm -> chapar) < 0)\n\tgoto error;\n      \n      ++fit -> loopnr;\n    }\n    \n    /* The rest of the loops is run within the gft, possibly getting errors */\n    \n    if (fit -> loopnr <= fit -> loops) {\n      \n      /* The first guess is in rpm -> par */\n      nextvarlel = fit -> varylist;\n      i = 0;\n      while (nextvarlel) {\n\tdblarray[i] = rpm -> par[nextvarlel -> elements[0]];\n\tnextvarlel = nextvarlel -> next;\n\t++i;\n      }\n      gft_mst_put(fit -> gft_mstv, dblarray, GFT_INPUT_SPAR);\n      \n      /* Choose the origin to be identical */\n      gft_mst_put(fit -> gft_mstv, dblarray, GFT_INPUT_OPAR);\n      \n      /* Get the start deltas */\n      nextvarlel = fit -> varylist;\n      i = 0;\n      while (nextvarlel) {\n\tdblarray[i] = nextvarlel -> delend;\n\tnextvarlel = nextvarlel -> next;\n\t++i;\n      }\n      gft_mst_put(fit -> gft_mstv, dblarray, GFT_INPUT_DPAR);\n      \n      /* Calculate the satisfaction deltas or grid normalisation */\n      /* ERROR SOURCE: This is done many times, but positioning it in front of the loops will lead to a segfault. This is a noted but in gft */\n      nextvarlel = fit -> varylist;\n      i = 0;\n      while (nextvarlel) {\n\tdblarray[i] = nextvarlel -> mindelta;\n\tnextvarlel = nextvarlel -> next;\n\t++i;\n      }\n      gft_mst_put(fit -> gft_mstv, dblarray, GFT_INPUT_NDPAR);\n\n      /* Put the number of loops to the remaining number of loops */\n      asize_t = fit -> loops - fit -> loopnr+1;\n      gft_mst_put(fit -> gft_mstv, &asize_t, GFT_INPUT_LOOPS);\n      \n      /* Now DO it */\n      gft_mst_act(fit -> gft_mstv, GFT_ACT_START);\n    }\n  }\n  else {\n    /* No iterations have been made, which means that we have to do something */\n    \n    i = gft_mst_act(fit -> gft_mstv, GFT_ACT_INIT);\n\n    /* Some initialisation here? */\n    gft_mst_get(fit -> gft_mstv, &fit -> mon_alloops   , GFT_OUTPUT_ALLOOPS);\n    gft_mst_get(fit -> gft_mstv, &fit -> mon_niters    , GFT_OUTPUT_NITERS);\n    gft_mst_get(fit -> gft_mstv, &fit -> mon_iters     , GFT_OUTPUT_ITERS);\n    gft_mst_get(fit -> gft_mstv, &fit -> mon_alliter   , GFT_OUTPUT_ALLITER);\n    gft_mst_get(fit -> gft_mstv, &fit -> mon_allcalls  , GFT_OUTPUT_ALLCALLS);\n    gft_mst_get(fit -> gft_mstv, &fit -> mon_calls_st  , GFT_OUTPUT_CALLS_ST);\n    gft_mst_get(fit -> gft_mstv, &fit -> mon_ncalls_st , GFT_OUTPUT_NCALLS_ST);\n    gft_mst_get(fit -> gft_mstv, &fit -> mon_npar_cur  , GFT_OUTPUT_NPAR_CUR);\n    gft_mst_get(fit -> gft_mstv, &fit -> mon_dsize     , GFT_OUTPUT_DSIZE);\n    gft_mst_get(fit -> gft_mstv, fit -> mon_dpar      , GFT_OUTPUT_NDPAR);\n    gft_mst_get(fit -> gft_mstv, &fit -> mon_stopsize  , GFT_OUTPUT_STOPSIZE);\n    fit -> mon_maxiter = fit -> maxiter;\n    fit -> mon_loops = fit -> loops;\n    \n    varele = fit -> varylist;\n    i = 0;\n    if (fit -> mon_npar_cur > -1) {\n      while (i < fit -> mon_npar_cur) {\n\tvarele = varele -> next;\n\t++i;\n      }\n      ftstab_putcoltitl(fit -> mon_key, (*varele -> elements)/rpm -> nur+1);\n    }\n    else {\n      sprintf(fit -> mon_key,\"GEN\");\n    }\n    \n    fit -> mon_dsize = ddinterntoparam(fit -> mon_dsize, (*varele -> elements)/rpm -> nur+1, hdr, rpm -> ndisks);\n    for (k = 0; k < fit -> mon_npar; ++k) {\n      fit -> mon_dpar[k] = ddinterntoparam(fit -> mon_dpar[k], (*varele -> elements)/rpm -> nur+1, hdr, rpm -> ndisks);\n    }\n    fit -> mon_ring = (*varele -> elements)%rpm -> nur+1;\n    for (disk = 0; disk < rpm -> ndisks; ++disk){\n      fit -> mon_repnpoints[disk] = fit -> npoints[disk];\n      fit -> mon_totalflux[disk] = fit -> fluxpoints[disk]*rpm -> cflux[disk]*hdr -> deltgridtouser[2];\n    }\n  }\n\n  /* Report */\n  /* Find the chisquare of the latest iteration */\n  gft_mst_get(fit -> gft_mstv, &fit -> mon_bestchisq , GFT_OUTPUT_BESTCHISQ);\n  gft_mst_get(fit -> gft_mstv, &fit -> mon_actchisq  , GFT_OUTPUT_ACTCHISQ);\n  gft_mst_get(fit -> gft_mstv, &fit -> mon_size      , GFT_OUTPUT_SIZE);\n\n  if ((fit -> mon_allcalls)) {\n\n    /* find the right dpar */\n    if (fit -> mon_npar_cur > -1) {\n      dpar = fit -> mon_dpar[fit -> mon_npar_cur];\n    }\n    else {\n      dpar = fit -> mon_dpar[0];\n    }\n\n    sprintf(mes,\n\t    \"L:%lu/%lu \"    /* loops/number of loops */\n\t    \"I:%02lu/%.1E \"    /* iterations in loop/max iterations */\n\t    \"M:%02lu/%.1E/%03lu \"    /* models in iteration / max models / total models / total models */\n\t    \"P:%-6s \"             /* Parameter name */\n            \"R:%02i \"          /* First ring number */\n\t    \"A:%+.1E/%+.1E \"  /* Alteration in parameter, start change */\n\t    \"N:%.1E\",          /* Number of pointsources */\n\t    (unsigned long) (fit -> mon_alloops+1), (unsigned long) fit -> mon_loops,   /* loops run in total/final number of loops */\n\t    (unsigned long) fit -> mon_alliter+1, (double) fit -> mon_niters,    /* iterations in loop/maximum iterations in loop */\n\t    (unsigned long) fit -> mon_calls_st+1, (double) fit -> mon_ncalls_st, (unsigned long) fit -> mon_allcalls,  /* Models in loop/total models */\n\t    fit -> mon_key,\n\t    fit -> mon_ring,\n\t    fit -> mon_dsize,\n\t    dpar,\n\t    (double) fit -> mon_repnpoints[0]);\n    for (disk = 1; disk < rpm -> ndisks; ++disk) {\n      length = strlen(mes);\n      sprintf(mes+length, \n\t      \"/%.1E\",       /* Number of pointsources */\n\t      (double) fit -> mon_repnpoints[disk]);\n    }\n    length = strlen(mes);\n    sprintf(mes+length, \n\t    \" F:%+.1E\",     /* Total flux */\n\t    fit -> mon_totalflux[0]);\n    for (disk = 1; disk < rpm -> ndisks; ++disk) {\n      length = strlen(mes);\n      sprintf(mes+length, \n\t      \"/%+.1E\",\n\t      fit -> mon_totalflux[disk]);\n    }\n    length = strlen(mes);\n    sprintf(mes+length, \n\t    \" C:%.3E \"          /* current chisquare */\n/* \t    \"B:%.3E \"  */         /* current best (solution) chisquare */\n\t    \"S:%+.1E\",      /* Current size */\n\t    fit -> mon_actchisq,                      /* current chisquare */\n/* \t    fit -> mon_bestchisq,      */                /* current minimum chisquare */\n\t    fit -> mon_size                           /* Current size */\n\t    );\n  }\n  else {\n    sprintf(mes, \"Start\\n\");                   \n  }\n  anyout_tir(&dev, mes);\n\n  /*Output of a progress file Kamphuis addition */\n  progressout(startinfv, mes);\n\n/* Now keep everything in mind for the final (This is not necessarily necessary, but we do it anyway) */\n  gft_mst_get(fit -> gft_mstv, &fit -> mon_alloops   , GFT_OUTPUT_ALLOOPS);\n  gft_mst_get(fit -> gft_mstv, &fit -> mon_niters    , GFT_OUTPUT_NITERS);\n  gft_mst_get(fit -> gft_mstv, &fit -> mon_iters     , GFT_OUTPUT_ITERS);\n  gft_mst_get(fit -> gft_mstv, &fit -> mon_alliter   , GFT_OUTPUT_ALLITER);\n  gft_mst_get(fit -> gft_mstv, &fit -> mon_allcalls  , GFT_OUTPUT_ALLCALLS);\n  gft_mst_get(fit -> gft_mstv, &fit -> mon_calls_st  , GFT_OUTPUT_CALLS_ST);\n  gft_mst_get(fit -> gft_mstv, &fit -> mon_ncalls_st , GFT_OUTPUT_NCALLS_ST);\n  gft_mst_get(fit -> gft_mstv, &fit -> mon_npar_cur  , GFT_OUTPUT_NPAR_CUR);\n  gft_mst_get(fit -> gft_mstv, &fit -> mon_dsize     , GFT_OUTPUT_DSIZE);\n  gft_mst_get(fit -> gft_mstv, fit  -> mon_dpar      , GFT_OUTPUT_NDPAR);\n  gft_mst_get(fit -> gft_mstv, &fit -> mon_stopsize  , GFT_OUTPUT_STOPSIZE);\n  fit -> mon_maxiter = fit -> maxiter;\n  fit -> mon_loops = fit -> loops;\n\n  varele = fit -> varylist;\n  i = 0;\n  if (fit -> mon_npar_cur > -1) {\n    while (i < fit -> mon_npar_cur) {\n      varele = varele -> next;\n      ++i;\n    }\n    ftstab_putcoltitl(fit -> mon_key, (*varele -> elements)/rpm -> nur+1);\n  }\n  else {\n    sprintf(fit -> mon_key,\"GEN\");\n  }\n\n  fit -> mon_dsize = ddinterntoparam(fit -> mon_dsize, (*varele -> elements)/rpm -> nur+1, hdr, rpm -> ndisks);\n  \n  for (k = 0; k < fit -> mon_npar; ++k) {\n    fit -> mon_dpar[k] = ddinterntoparam(fit -> mon_dpar[k], (*varele -> elements)/rpm -> nur+1, hdr, rpm -> ndisks);\n  }\n  fit -> mon_ring = (*varele -> elements)%rpm -> nur+1;\n  for (disk = 0; disk < rpm -> ndisks; ++disk) {\n    fit -> mon_repnpoints[disk] = fit -> npoints[disk];\n    fit -> mon_totalflux[disk] = fit -> fluxpoints[disk]*rpm -> cflux[disk]*hdr -> deltgridtouser[2];\n  }\n\n  /* What has to be done is to get the output right, but this is done in putgenresults */\n  if ((dblarray))\n    free(dblarray);\n\n  return 1;\n\n error:\n  if ((dblarray))\n     free(dblarray);\n  return 0;\n}\n\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* function passed to gft */\nstatic double gchsq_gen_start(double *vector, void *rest)\n{\n  double gchsq_genv;\n  double chimult;\n  int i;\n  varlel *varele;\n  int disk;\n\n  /************************/\n  /************************/\n  adar *adarv;\n  /************************/\n\n/* We get all the info from the additional arguments */\n  adarv = (adar *) rest;\n\n  /* Change them */\n    /* If they get out of range, we multiply the chisquare by OUTRANGEFAC */\n  chimult = pow(OUTRANGEFAC,chprm_gen(vector, adarv -> fit -> varylist, adarv -> rpm -> par));\n  \n  /* Now ensure that the indexed parameters are aligned */\n  for (i = adarv -> rpm -> nur*NSSDPARAMS; i < adarv -> rpm ->nur *(NSSDPARAMS+NDPARAMS*adarv -> rpm -> ndisks); ++i)\n    adarv -> rpm -> chapar[i] = 1;\n  \n  if (changedependent(adarv -> rpm, adarv -> rpm -> par, adarv -> fit -> index, adarv -> rpm -> chapar) < 0)\n    goto error;\n\n  /* When starting make one run of interpover */\n  interpover(adarv -> rpm, adarv -> rpm -> radsep, 1, NULL, adarv -> fit -> index);\n\n  /* Do make the model */\n  galmod(adarv -> hdr, adarv -> rpm, GENFIT, adarv -> fit -> varylist, adarv -> fit -> index, adarv -> fit -> fluxpoints, adarv -> fit -> npoints);\n  \n  /* Get the chisquare, formerly using PCONDISP (NPARAMS + (ndisks - 1)*NDPARAMS) */\n  gchsq_genv = getchisquare_c(adarv -> rpm -> par[((NPARAMS + (adarv -> rpm -> ndisks - 1)*NDPARAMS))*adarv -> rpm -> nur]);\n\n  /* Regularise and get alloops first */\n  gft_mst_get(adarv -> fit -> gft_mstv, &adarv -> fit -> mon_alloops   , GFT_OUTPUT_ALLOOPS);\n\n  gchsq_genv = reg_do(adarv -> fit -> reg_contv, (adarv -> fit -> mon_alloops == adarv -> fit -> loops)?adarv -> fit -> loops - 1:adarv -> fit -> mon_alloops, gchsq_genv);\n  \n  /* Correct the chisquare taking into account the outliers */\n  adarv -> hdr -> chi2 = chimult*(gchsq_genv+((double) adarv -> rpm -> outpoints)*adarv -> rpm -> penalty);\n\n/* Now keep everything in mind for the next iteration */\n  gft_mst_get(adarv -> fit -> gft_mstv, &adarv -> fit -> mon_alloops   , GFT_OUTPUT_ALLOOPS);\n  gft_mst_get(adarv -> fit -> gft_mstv, &adarv -> fit -> mon_niters    , GFT_OUTPUT_NITERS);\n  gft_mst_get(adarv -> fit -> gft_mstv, &adarv -> fit -> mon_iters     , GFT_OUTPUT_ITERS);\n  gft_mst_get(adarv -> fit -> gft_mstv, &adarv -> fit -> mon_alliter   , GFT_OUTPUT_ALLITER);\n  gft_mst_get(adarv -> fit -> gft_mstv, &adarv -> fit -> mon_allcalls  , GFT_OUTPUT_ALLCALLS);\n  gft_mst_get(adarv -> fit -> gft_mstv, &adarv -> fit -> mon_calls_st  , GFT_OUTPUT_CALLS_ST);\n  gft_mst_get(adarv -> fit -> gft_mstv, &adarv -> fit -> mon_ncalls_st , GFT_OUTPUT_NCALLS_ST);\n  gft_mst_get(adarv -> fit -> gft_mstv, &adarv -> fit -> mon_npar_cur  , GFT_OUTPUT_NPAR_CUR);\n  gft_mst_get(adarv -> fit -> gft_mstv, &adarv -> fit -> mon_bestchisq , GFT_OUTPUT_BESTCHISQ);\n  gft_mst_get(adarv -> fit -> gft_mstv, &adarv -> fit -> mon_actchisq  , GFT_OUTPUT_ACTCHISQ);\n  gft_mst_get(adarv -> fit -> gft_mstv, &adarv -> fit -> mon_dsize     , GFT_OUTPUT_DSIZE);\n  gft_mst_get(adarv -> fit -> gft_mstv, adarv -> fit -> mon_dpar      , GFT_OUTPUT_DPAR);\n  gft_mst_get(adarv -> fit -> gft_mstv, &adarv -> fit -> mon_stopsize  , GFT_OUTPUT_STOPSIZE);\n  gft_mst_get(adarv -> fit -> gft_mstv, &adarv -> fit -> mon_size      , GFT_OUTPUT_SIZE);\n  adarv -> fit -> mon_maxiter = adarv -> fit -> maxiter;\n  adarv -> fit -> mon_loops = adarv -> fit -> loops;\n\n  varele = adarv -> fit -> varylist;\n  i = 0;\n  if (adarv -> fit -> mon_npar_cur > -1) {\n    while (i < adarv -> fit -> mon_npar_cur) {\n      varele = varele -> next;\n      ++i;\n    }\n    ftstab_putcoltitl(adarv -> fit -> mon_key, (*varele -> elements)/adarv -> rpm -> nur+1);\n  }\n  else {\n    sprintf(adarv -> fit -> mon_key,\"GEN\");\n  }\n\n  adarv -> fit -> mon_dsize = ddinterntoparam(adarv -> fit -> mon_dsize, (*varele -> elements)/adarv -> rpm -> nur+1, adarv -> hdr, adarv -> rpm -> ndisks);\n  for (i = 0; i < adarv -> fit -> mon_npar; ++i) {\n    adarv -> fit -> mon_dpar[i] = ddinterntoparam(adarv -> fit -> mon_dpar[i], (*varele -> elements)/adarv -> rpm -> nur+1, adarv -> hdr, adarv -> rpm -> ndisks);\n  }\n  \n  adarv -> fit -> mon_ring = (*varele -> elements)%adarv -> rpm -> nur+1;\n  for (disk = 0; disk < adarv -> rpm -> ndisks; ++disk){\n    adarv -> fit -> mon_repnpoints[disk] = adarv -> fit -> npoints[disk];\n    adarv -> fit -> mon_totalflux[disk] = adarv -> fit -> fluxpoints[disk]*adarv -> rpm -> cflux[disk]*adarv -> hdr -> deltgridtouser[2];\n  }\n\n /* Change the fitting function */\n i = gft_mst_putf(adarv -> fit -> gft_mstv, &gchsq_gen, GFT_INPUT_GCHSQ_REP);\n\n  return adarv -> hdr -> chi2;\n\n error:\n  return -1.0;\n}\n\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* function passed to gft */\nstatic double gchsq_gen(double *vector, void *rest)\n{\n  char mes[160]; /* Any message */\n  int dev = 1;\n  double gchsq_genv;\n  size_t length;\n  /* double chimult; */\n  double dpar;\n  varlel *varele;\n  int i,k;\n  int disk;\n\n  /************************/\n  /************************/\n  adar *adarv;\n  /************************/\n\n/* We get all the info from the additional arguments */\n  adarv = (adar *) rest;\n\n  /* We read from the logfile */\n\n  if (ftstab_get_value(adarv -> fit -> recnr+1L, 1L, &gchsq_genv)) {\n\n  /* Find the chisquare of the latest iteration */\n  gft_mst_get(adarv -> fit -> gft_mstv, &adarv -> fit -> mon_bestchisq , GFT_OUTPUT_BESTCHISQ);\n  gft_mst_get(adarv -> fit -> gft_mstv, &adarv -> fit -> mon_actchisq  , GFT_OUTPUT_ACTCHISQ);\n  gft_mst_get(adarv -> fit -> gft_mstv, &adarv -> fit -> mon_size      , GFT_OUTPUT_SIZE);\n\n\n  /* report what we have, if textlog, we assume that it has been written already */\n  if (!(adarv -> fit -> recnr)) {\n    sprintf(mes, \"Start recalling\\n\");                   \n    anyout_tir(&dev, mes);\n    adarv -> fit -> mon_dsize = 0;\n  }\n\n  /* Now find dpar */\n  if (adarv -> fit -> mon_npar_cur > -1) {\n    dpar = adarv -> fit -> mon_dpar[adarv -> fit -> mon_npar_cur];\n  }\n  else {\n    dpar = adarv -> fit -> mon_dpar[0];\n  }\n    sprintf(mes,\n\t    \"L:%lu/%lu \"    /* loops/number of loops */\n\t    \"I:%02lu/%.1E \"    /* iterations in loop/max iterations */\n\t    \"M:%02lu/%.1E/%03lu \"    /* models in iteration / max models / total models / total models */\n\t    \"P:%-6s \"             /* Parameter name */\n            \"R:%02i \"          /* First ring number */\n\t    \"A:%+.1E/%+.1E \",  /* Alteration in parameter, start change */\n\t    (unsigned long) (adarv -> fit -> mon_alloops+1), (unsigned long) adarv -> fit -> mon_loops,   /* loops run in total/final number of loops */\n\t    (unsigned long) adarv -> fit -> mon_alliter+1, (double) adarv -> fit -> mon_niters,    /* iterations in loop/maximum iterations in loop */\n\t    (unsigned long) adarv -> fit -> mon_calls_st+1, (double) adarv -> fit -> mon_ncalls_st, (unsigned long) adarv -> fit -> mon_allcalls,  /* Models in loop/total models */\n\t    adarv -> fit -> mon_key,\n\t    adarv -> fit -> mon_ring,\n\t    adarv -> fit -> mon_dsize,\n\t    dpar);\n    length = strlen(mes);\n    sprintf(mes+length, \n\t    \" C:%.9E \"          /* current chisquare */\n/* \t    \"B:%.3E \"  */         /* current best (solution) chisquare */\n\t    \"S:%+.1E\",      /* Current size */\n\t    adarv -> fit -> mon_actchisq,                      /* current chisquare */\n/* \t    adarv -> fit -> mon_bestchisq,      */                /* current minimum chisquare */\n\t    adarv -> fit -> mon_size                           /* Current size */\n\t    );\n  \n  anyout_tir(&dev, mes);\n\n  /*Output of a progress file Kamphuis addition */\n  progressout(adarv -> startinfv, mes);\n\n   /* Change them */\n  /* chimult = pow(OUTRANGEFAC,chprm_gen(vector, adarv -> fit -> varylist, adarv -> rpm -> par)); */\n  pow(OUTRANGEFAC,chprm_gen(vector, adarv -> fit -> varylist, adarv -> rpm -> par));\n/*   if (chprm_gen(vector, adarv -> fit -> varylist, adarv -> rpm -> par)) */\n    \n/*     If they get out of range, we multiply the chisquare by OUTRANGEFAC  */\n/*     chimult = OUTRANGEFAC; */\n/*   else */\n/*     chimult = 1.0; */\n \n    /* Now ensure that the indexed parameters are aligned */\n  for (i = adarv -> rpm -> nur*NSSDPARAMS; i < adarv -> rpm->nur *(NSSDPARAMS+NDPARAMS*adarv -> rpm->ndisks); ++i) {\n    adarv -> rpm -> chapar[i] = chkchangep(adarv -> fit -> varylist, adarv -> fit -> fitmode, i, adarv -> rpm -> nur);\n  }\n  if (changedependent(adarv -> rpm, adarv -> rpm -> par, adarv -> fit -> index, adarv -> rpm -> chapar) < 0)\n    goto error;\n\n  /* Do make the model */\n/*   galmod(adarv -> hdr, adarv -> rpm, GENFIT, adarv -> fit -> varylist, adarv -> fit -> index, fluxpoints, adarv -> fit -> npoints); */\n\n  /* Get the chisquare */\n/*   gchsq_genv = getchisquare_c(adarv -> rpm -> par[((NPARAMS + (adarv -> rpm -> ndisks - 1)*NDPARAMS))*adarv -> rpm -> nur]); */\n\n  /* Correct the chisquare taking into account the outliers */\n  adarv -> hdr -> chi2 = adarv -> hdr -> oldchi2 = gchsq_genv;\n\n  /* Now change this for the next iteration */\n/*   for (disk = 0; disk < rpm -> ndisks; ++disk) { */\n/*     adarv -> fit -> fluxpoints[disk] = fluxpoints[disk]; */\n/*   } */\n  \n  ++adarv -> fit -> recnr;\n  \n    /* Produce output */\n    writeoutputread(adarv -> log, adarv -> hdr, adarv -> rpm, adarv -> fit, 0, adarv -> fit -> dof, adarv -> fit -> recnr, -1.0);\n    \n\n/* Now keep everything in mind for the next iteration */\n  gft_mst_get(adarv -> fit -> gft_mstv, &adarv -> fit -> mon_alloops   , GFT_OUTPUT_ALLOOPS);\n  gft_mst_get(adarv -> fit -> gft_mstv, &adarv -> fit -> mon_niters    , GFT_OUTPUT_NITERS);\n  gft_mst_get(adarv -> fit -> gft_mstv, &adarv -> fit -> mon_iters     , GFT_OUTPUT_ITERS);\n  gft_mst_get(adarv -> fit -> gft_mstv, &adarv -> fit -> mon_alliter   , GFT_OUTPUT_ALLITER);\n  gft_mst_get(adarv -> fit -> gft_mstv, &adarv -> fit -> mon_allcalls  , GFT_OUTPUT_ALLCALLS);\n  gft_mst_get(adarv -> fit -> gft_mstv, &adarv -> fit -> mon_calls_st  , GFT_OUTPUT_CALLS_ST);\n  gft_mst_get(adarv -> fit -> gft_mstv, &adarv -> fit -> mon_ncalls_st , GFT_OUTPUT_NCALLS_ST);\n  gft_mst_get(adarv -> fit -> gft_mstv, &adarv -> fit -> mon_npar_cur  , GFT_OUTPUT_NPAR_CUR);\n  gft_mst_get(adarv -> fit -> gft_mstv, &adarv -> fit -> mon_dsize     , GFT_OUTPUT_DSIZE);\n  gft_mst_get(adarv -> fit -> gft_mstv, adarv -> fit -> mon_dpar      , GFT_OUTPUT_NDPAR);\n  gft_mst_get(adarv -> fit -> gft_mstv, &adarv -> fit -> mon_stopsize  , GFT_OUTPUT_STOPSIZE);\n  adarv -> fit -> mon_maxiter = adarv -> fit -> maxiter;\n  adarv -> fit -> mon_loops = adarv -> fit -> loops;\n\n  varele = adarv -> fit -> varylist;\n  i = 0;\n  if (adarv -> fit -> mon_npar_cur > -1) {\n    while (i < adarv -> fit -> mon_npar_cur) {\n      varele = varele -> next;\n      ++i;\n    }\n    ftstab_putcoltitl(adarv -> fit -> mon_key, (*varele -> elements)/adarv -> rpm -> nur+1);\n  }\n  else {\n    sprintf(adarv -> fit -> mon_key,\"GEN\");\n  }\n\n  adarv -> fit -> mon_dsize = ddinterntoparam(adarv -> fit -> mon_dsize, (*varele -> elements)/adarv -> rpm -> nur+1, adarv -> hdr, adarv -> rpm -> ndisks);\n  for (k = 0; k < adarv -> fit -> mon_npar; ++k) {\n    adarv -> fit -> mon_dpar[k] = ddinterntoparam(adarv -> fit -> mon_dpar[k], (*varele -> elements)/adarv -> rpm -> nur+1, adarv -> hdr, adarv -> rpm -> ndisks);\n  }\n  adarv -> fit -> mon_ring = (*varele -> elements)%adarv -> rpm -> nur+1;\n  for (disk = 0; disk < adarv -> rpm -> ndisks; ++disk){\n    adarv -> fit -> mon_repnpoints[disk] = adarv -> fit -> npoints[disk];\n    adarv -> fit -> mon_totalflux[disk] = adarv -> fit -> fluxpoints[disk]*adarv -> rpm -> cflux[disk]*adarv -> hdr -> deltgridtouser[2];\n  }\n\n  }\n  else {\n    /* ERROR SOURCE: Some initialisation here ? */\n    gchsq_genv = gchsq_gen2(vector, rest);\n\n    /* Change the fitting function */\n    gft_mst_putf(adarv -> fit -> gft_mstv, &gchsq_gen2, GFT_INPUT_GCHSQ_REP);\n\n  }\n\n  return gchsq_genv;\n\n error:\n  return -1.0;\n}\n\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* function passed to gft */\nstatic double gchsq_gen2(double *vector, void *rest)\n{\n  char mes[260]; /* Any message */\n  int dev = 1;\n  double gchsq_genv = 0;\n  double chimult;\n  double dpar;\n  int i,k;\n  int disk;\n  size_t length;\n  varlel *varele;\n\n  /************************/\n  /************************/\n  adar *adarv;\n  /************************/\n\n\n\n  /* We get all the info from the additional arguments */\n  adarv = (adar *) rest;\n\n  /* Find the chisquare of the latest iteration */\n  gft_mst_get(adarv -> fit -> gft_mstv, &adarv -> fit -> mon_bestchisq , GFT_OUTPUT_BESTCHISQ);\n  gft_mst_get(adarv -> fit -> gft_mstv, &adarv -> fit -> mon_actchisq  , GFT_OUTPUT_ACTCHISQ);\n  gft_mst_get(adarv -> fit -> gft_mstv, &adarv -> fit -> mon_size      , GFT_OUTPUT_SIZE);\n\n\n  /* report what we have, if textlog, we assume that it has been written already */\n  if (!(adarv -> fit -> mon_allcalls)) {\n    sprintf(mes, \"Start\\n\");                   \n    anyout_tir(&dev, mes);\n    adarv -> fit -> mon_dsize = 0;\n  }\n\n  /* Now find dpar */\n  if (adarv -> fit -> mon_npar_cur > -1) {\n    dpar = adarv -> fit -> mon_dpar[adarv -> fit -> mon_npar_cur];\n  }\n  else {\n    dpar = adarv -> fit -> mon_dpar[0];\n  }\n\n    sprintf(mes,\n\t    \"L:%lu/%lu \"    /* loops/number of loops */\n\t    \"I:%02lu/%.1E \"    /* iterations in loop/max iterations */\n\t    \"M:%02lu/%.1E/%03lu \"    /* models in iteration / max models / total models / total models */\n\t    \"P:%-6s \"             /* Parameter name */\n            \"R:%02i \"          /* First ring number */\n\t    \"A:%+.1E/%+.1E \"  /* Alteration in parameter, start change */\n\t    \"N:%.1E\",          /* Number of pointsources */\n\t    (unsigned long) (adarv -> fit -> mon_alloops+1), (unsigned long) adarv -> fit -> mon_loops,   /* loops run in total/final number of loops */\n\t    (unsigned long) adarv -> fit -> mon_alliter+1, (double) adarv -> fit -> mon_niters,    /* iterations in loop/maximum iterations in loop */\n\t    (unsigned long) adarv -> fit -> mon_calls_st+1, (double) adarv -> fit -> mon_ncalls_st, (unsigned long) adarv -> fit -> mon_allcalls,  /* Models in loop/total models */\n\t    adarv -> fit -> mon_key,\n\t    adarv -> fit -> mon_ring,\n\t    adarv -> fit -> mon_dsize,\n\t    dpar,\n\t    (double) adarv -> fit -> mon_repnpoints[0]);\n    for (disk = 1; disk < adarv -> rpm -> ndisks; ++disk) {\n      length = strlen(mes);\n      sprintf(mes+length, \n\t      \"/%.1E\",       /* Number of pointsources */\n\t      (double) adarv -> fit -> mon_repnpoints[disk]);\n    }\n    length = strlen(mes);\n    sprintf(mes+length, \n\t    \" F:%+.1E\",     /* Total flux */\n\t    adarv -> fit -> mon_totalflux[0]);\n    for (disk = 1; disk < adarv -> rpm -> ndisks; ++disk) {\n      length = strlen(mes);\n      sprintf(mes+length, \n\t      \"/%+.1E\",\n\t      adarv -> fit -> mon_totalflux[disk]);\n    }\n    length = strlen(mes);\n    sprintf(mes+length, \n\t    \" C:%.7E \"          /* current chisquare */\n/* \t    \"B:%.3E \"  */         /* current best (solution) chisquare */\n\t    \"S:%+.1E\",      /* Current size */\n\t    adarv -> fit -> mon_actchisq,                      /* current chisquare */\n/* \t    adarv -> fit -> mon_bestchisq,      */                /* current minimum chisquare */\n\t    adarv -> fit -> mon_size                           /* Current size */\n\t    );\n  \n  anyout_tir(&dev, mes);\n\n  /*Output of a progress file Kamphuis addition */\n  progressout(adarv -> startinfv, mes);\n\n   /* Change them */\n  chimult = pow(OUTRANGEFAC,chprm_gen(vector, adarv -> fit -> varylist, adarv -> rpm -> par));\n/*   if (chprm_gen(vector, adarv -> fit -> varylist, adarv -> rpm -> par)) */\n    \n/*     If they get out of range, we multiply the chisquare by OUTRANGEFAC  */\n/*     chimult = OUTRANGEFAC; */\n/*   else */\n/*     chimult = 1.0; */\n \n  /* Now ensure that the indexed parameters are aligned */\n  for (i = adarv -> rpm -> nur*NSSDPARAMS; i < adarv -> rpm->nur *(NSSDPARAMS+NDPARAMS*adarv -> rpm->ndisks); ++i)\n    adarv -> rpm -> chapar[i] = chkchangep(adarv -> fit -> varylist, adarv -> fit -> fitmode, i, adarv -> rpm -> nur);\n\n  if (changedependent(adarv -> rpm, adarv -> rpm -> par, adarv -> fit -> index, adarv -> rpm -> chapar) < 0)\n    goto error;\n\n  /* Do make the model */\n  galmod(adarv -> hdr, adarv -> rpm, GENFIT, adarv -> fit -> varylist, adarv -> fit -> index, adarv -> rpm -> fluxpoints, adarv -> fit -> npoints);\n\n  /* Get the chisquare, formerly using pcondisp */\n  gchsq_genv = getchisquare_c(adarv -> rpm -> par[((NPARAMS + (adarv -> rpm -> ndisks - 1)*NDPARAMS))*adarv -> rpm -> nur]);\n\n  /* Regularise */\n/* First recall the loop number, keep everything in mind for the next iteration */\n  gft_mst_get(adarv -> fit -> gft_mstv, &adarv -> fit -> mon_alloops   , GFT_OUTPUT_ALLOOPS);\n  gchsq_genv = reg_do(adarv -> fit -> reg_contv, (adarv -> fit -> mon_alloops == adarv -> fit -> loops)?adarv -> fit -> loops - 1:adarv -> fit -> mon_alloops, gchsq_genv);\n\n  /* Correct the chisquare taking into account the outliers */\n  adarv -> hdr -> chi2 = chimult*(gchsq_genv+((double) adarv -> rpm -> outpoints)*adarv -> rpm -> penalty);\n\n\n  /* Now change this for the next iteration */\n  for (disk = 0; disk < adarv -> rpm -> ndisks; ++disk) {\n    adarv -> fit -> fluxpoints[disk] = adarv -> rpm -> fluxpoints[disk];\n  }\n  \n  ++adarv -> fit -> recnr;\n  \n  /* Write an output cube */\n  if ((*adarv -> hdr -> outset != '\\0')) {\n    if (!(adarv -> fit -> recnr%adarv -> hdr -> outcubup)) {\n\n      /*   for (i = 0; i < adarv -> rpm -> nur*(NPARAMS+(adarv -> rpm -> ndisks-1)*NDPARAMS)+NSPARAMS; ++i) */\n      /*     adarv -> rpm -> oldpar[i] = adarv -> rpm -> par[i]; */\n      \n      writemodel(adarv -> hdr, adarv -> rpm, adarv -> fit, adarv -> rpm -> par, adarv -> fit -> index);\n    }\n  }    \n\n\n    /* Produce output */\n    adarv -> hdr -> oldchi2 = adarv -> hdr -> chi2;\n\n    /* correct this fitting */\n    writeoutput(adarv -> log, adarv -> hdr, adarv -> rpm, adarv -> fit, 0, adarv -> fit -> dof, adarv -> fit -> recnr, -1.0);\n    \n    /* Read out the same number, it might have changed by an epsilon */\n    gchsq_genv = adarv -> hdr -> oldchi2;\n\n    /* Correct this fitting */\n    gchsq_genv = 1.0;\n    ftstab_get_value(adarv -> fit -> recnr, 1L, &gchsq_genv);\n\n/* Now keep everything in mind for the next iteration */\n  gft_mst_get(adarv -> fit -> gft_mstv, &adarv -> fit -> mon_alloops   , GFT_OUTPUT_ALLOOPS);\n  gft_mst_get(adarv -> fit -> gft_mstv, &adarv -> fit -> mon_niters    , GFT_OUTPUT_NITERS);\n  gft_mst_get(adarv -> fit -> gft_mstv, &adarv -> fit -> mon_iters     , GFT_OUTPUT_ITERS);\n  gft_mst_get(adarv -> fit -> gft_mstv, &adarv -> fit -> mon_alliter   , GFT_OUTPUT_ALLITER);\n  gft_mst_get(adarv -> fit -> gft_mstv, &adarv -> fit -> mon_allcalls  , GFT_OUTPUT_ALLCALLS);\n  gft_mst_get(adarv -> fit -> gft_mstv, &adarv -> fit -> mon_calls_st  , GFT_OUTPUT_CALLS_ST);\n  gft_mst_get(adarv -> fit -> gft_mstv, &adarv -> fit -> mon_ncalls_st , GFT_OUTPUT_NCALLS_ST);\n  gft_mst_get(adarv -> fit -> gft_mstv, &adarv -> fit -> mon_npar_cur  , GFT_OUTPUT_NPAR_CUR);\n  gft_mst_get(adarv -> fit -> gft_mstv, &adarv -> fit -> mon_dsize     , GFT_OUTPUT_DSIZE);\n  gft_mst_get(adarv -> fit -> gft_mstv, adarv -> fit -> mon_dpar      , GFT_OUTPUT_NDPAR);\n  gft_mst_get(adarv -> fit -> gft_mstv, &adarv -> fit -> mon_stopsize  , GFT_OUTPUT_STOPSIZE);\n  adarv -> fit -> mon_maxiter = adarv -> fit -> maxiter;\n  adarv -> fit -> mon_loops = adarv -> fit -> loops;\n\n  varele = adarv -> fit -> varylist;\n  i = 0;\n  if (adarv -> fit -> mon_npar_cur > -1) {\n    while (i < adarv -> fit -> mon_npar_cur) {\n      varele = varele -> next;\n      ++i;\n    }\n    ftstab_putcoltitl(adarv -> fit -> mon_key, (*varele -> elements)/adarv -> rpm -> nur+1);\n  }\n  else {\n    sprintf(adarv -> fit -> mon_key,\"GEN\");\n  }\n\n  adarv -> fit -> mon_dsize = ddinterntoparam(adarv -> fit -> mon_dsize, (*varele -> elements)/adarv -> rpm -> nur+1, adarv -> hdr, adarv -> rpm -> ndisks);\n    for (k = 0; k < adarv -> fit -> mon_npar; ++k) {\n      adarv -> fit -> mon_dpar[k] = ddinterntoparam(adarv -> fit -> mon_dpar[k], (*varele -> elements)/adarv -> rpm -> nur+1, adarv -> hdr, adarv -> rpm -> ndisks);\n    }\n  adarv -> fit -> mon_ring = (*varele -> elements)%adarv -> rpm -> nur+1;\n  for (disk = 0; disk < adarv -> rpm -> ndisks; ++disk){\n    adarv -> fit -> mon_repnpoints[disk] = adarv -> fit -> npoints[disk];\n    adarv -> fit -> mon_totalflux[disk] = adarv -> fit -> fluxpoints[disk]*adarv -> rpm -> cflux[disk]*adarv -> hdr -> deltgridtouser[2];\n  }\n\n    \n    return gchsq_genv;\n\n error:\n    return -1.0;\n}\n\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Interpolate over the par list to get the modpar */\n\nstatic void interpinit(ringparms *rpm, double radsep, int disk)\n{\n  int i,j,jp,k;\n  /* float width; */\n  /* float dpardr[NPARAMS]; */\n  /* float dr; */\n  int n2, n1;\n  \n\n  /* In the modpar array interpolate over all rings */\n  for (i = 1; i < rpm -> nur; ++i) {\n    \n    /* This is the actual width between two radii */\n    /* Obsolete when using GSL */\n    /* width = rpm -> par[PRADI*rpm -> nur+i] - rpm -> par[PRADI*rpm -> nur+i-1]; */\n    \n    /* These are the rings to be calculated */\n    n2 = (int) (rpm -> par[PRADI*rpm -> nur+i]/radsep-0.5); \n    n1 = ((int) (rpm -> par[PRADI*rpm -> nur+i-1]/radsep+0.5)); \n    \n    /* in-between two rings, the slope is determined */\n/* \tfor (j = NPARAMS+(disk-1)*NDPARAMS; j < NPARAMS+disk*NDPARAMS; ++j) { */\n\n\n    for (jp = NPARAMS-NDPARAMS; jp < NPARAMS; ++jp) {\n      \n      j = jp + disk*NDPARAMS;\n\n      /* If the parameter is in the list */\n      /* Obsolete when using GSL */\n      /* dpardr[jp]= (rpm -> par[j*rpm -> nur+i]-rpm -> par[j*rpm -> nur+i-1])/width; */\n\n      /* Not sure if this is required, but do it anyway */\n      gsl_interp_accel_reset(rpm -> gsl_interp_accelarray[j-NSSDPARAMS]);\n\n      /* Very sure that this is a requirement; a test has shown that this should be ouside an omp pragma, not sure why */\n      gsl_interp_init(rpm -> gsl_interparray[j-NSSDPARAMS],rpm -> par+PRADI*rpm -> nur, rpm -> par + rpm -> nur*j, rpm -> nur);\n    }\n\n    /* D*mn GSL! GSL interpolation is not compatible with OMP anyway */\n/* #ifdef OPENMPTIR */\n/* #pragma  omp parallel for schedule(dynamic) */\n/* #endif */\n    for (jp = NPARAMS-NDPARAMS; jp < NPARAMS; ++jp) {\n      \n      j = jp + disk*NDPARAMS;\n\n      /* If the parameter is in the list */\n      /* Obsolete when using GSL */\n      /* dpardr[jp]= (rpm -> par[j*rpm -> nur+i]-rpm -> par[j*rpm -> nur+i-1])/width; */\n\n      /* Not sure if this is required, but do it anyway */\n      gsl_interp_accel_reset(rpm -> gsl_interp_accelarray[j-NSSDPARAMS]);\n\n      /* Very sure that this is a requirement; a test has shown */\n      gsl_interp_init(rpm -> gsl_interparray[j-NSSDPARAMS],rpm -> par+PRADI*rpm -> nur, rpm -> par + rpm -> nur*j, rpm -> nur);\n\n      for (k = n1; k <= n2; ++k) {\n\t/* for each parameter the intepolation is done */\n\trpm -> modpar[PRADI*rpm -> nr+k] = ((float) k)*radsep+radsep/2.0;\n\t/* Obsolete when using GSL */\n\t/* dr = rpm -> modpar[PRADI*rpm -> nr+k]-rpm -> par[PRADI*rpm -> nur+i-1];  */\n\t/* rpm -> modpar[j*rpm -> nr+k] = rpm -> par[j*rpm -> nur+i-1]+dpardr[jp]*dr;  */\n\t/* if (k == n1) { */\n\t/*   fprintf(stderr,\"Alpha j: %i n1: %i n2: %i %i %f %f\\n\",j,n1,n2,k,rpm -> modpar[PRADI*rpm -> nr+k],rpm -> par[PRADI*rpm -> nur+i-1]); */\n\t/* } */\n\t/* if (k == n2) { */\n\t/*   fprintf(stderr,\"Omega %i %f %f\\n\",k,rpm -> modpar[PRADI*rpm -> nr+k],rpm -> par[PRADI*rpm -> nur+i]); */\n\t/* } */\n\trpm -> modpar[j*rpm -> nr+k] = gsl_interp_eval(rpm -> gsl_interparray[j-NSSDPARAMS], rpm -> par+PRADI*rpm -> nur, rpm -> par + rpm -> nur*j, rpm -> modpar[PRADI*rpm -> nr+k], rpm -> gsl_interp_accelarray[j-NSSDPARAMS]);\n      }\n    }\n\n    /* Now change the pre-processed parameters and terminate the pointsource lists */\n    for (k = n1; k <= n2; ++k)\n      srprep(rpm, k, 0, disk);\n  } \n}\n\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Interpolate over the par list to get the modpar */\n\nstatic void interpover(ringparms *rpm, double radsep, int fitmode, varlel *varele, decomp_inlist *index)\n{\n  int i,j,jp,k,disk;\n  /* float width; */\n  /* float dpardr[NPARAMS]; */\n  /* float dr; */\n  int n1, n2, s, e;\n  \n  \n  /* Check if we initialise */\n  if (!(varele)) {\n    for (disk = 0; disk < rpm -> ndisks; ++disk) {\n      interpinit(rpm, radsep, disk);\n    }\n    return;\n  }\n\n  /* Switch on all indicators right to a range that should be interpolated over, depending on interpolation method */\n  for (disk = 0; disk < rpm -> ndisks; ++disk) {\n    \n    for (jp = 0; jp < NDPARAMS; ++jp) {\n      \n      for (i = 1; i < rpm -> nur; ++i) {\n\tif (rpm -> chapar[(NDPARAMS*disk+jp+NSSDPARAMS)*rpm -> nur+i])\n\t  break;\n      }\n      if (i < rpm -> nur) {\n\tif (rpm -> smothcar[jp+disk*NDPARAMS] == INTERP_AKIMA) {\n\t  s = -2;\n\t  e = 4;\n\t}\n\telse if (rpm -> smothcar[jp+disk*NDPARAMS] == INTERP_CSPLINE) {\n\t  s = 1;\n\t  e = rpm -> nur;\n\t}\n\telse {\n\t  s = 1;\n\t  e = 2;\n\t}\n\tfor (i = 0; i < rpm -> nur; ++i) {\n\t  if (rpm -> chapar[(NDPARAMS*disk+jp+NSSDPARAMS)*rpm -> nur+i] == 1) {\n\t    for (k = s; k < e; ++k) {\n\t      if ((k+i) >= rpm -> nur)\n\t\tbreak;\n\t      if ((k+i) > -1) {\n\t\trpm -> chapar[(NDPARAMS*disk+jp+NSSDPARAMS)*rpm -> nur+k+i] = 2;\n\t      }\n\t    }\n\t    /* i = i+k; */\n\t  }\n\t}\n      }\n    }\n  }\n  \n  /* printf(\"paraf:\"); */\n  /* for (i = rpm -> nur*NSSDPARAMS; i < rpm->nur *(NSSDPARAMS+NDPARAMS*rpm->ndisks); ++i) */\n  /*   if (rpm -> chapar[i]) */\n  /*     printf(\" %i\", i); */\n  /* printf(\" \"); */\n\n  for (disk = 0; disk < rpm -> ndisks; ++disk) {\n    \n    /* In the modpar array interpolate over all rings */\n    for (i = 1; i < rpm -> nur; ++i) {\n      \n\t/* These are the subrings to be calculated */\n      n2 = (int) (rpm -> par[PRADI*rpm -> nur+i]/radsep-0.5); \n      n1 = ((int) (rpm -> par[PRADI*rpm -> nur+i-1]/radsep+0.5)); \n      \n      /* D*mn GSL! GSL interpolation is not compatible with OMP anyway */\n      /* #ifdef OPENMPTIR */\n      /* #pragma omp parallel for schedule(dynamic) */\n      /* #endif */\n      for (jp = 0; jp < NDPARAMS; ++jp) {\n\n\tj = NSSDPARAMS+jp+disk*NDPARAMS;\n\t\n\t/* If the parameter is in the list */\n\tif (rpm -> chapar[j*rpm -> nur+i]) {\n\t  \n\t  /* Obsolete when using GSL */\n\t  /* dpardr[jp]= (rpm -> par[j*rpm -> nur+i]-rpm -> par[j*rpm -> nur+i-1])/width; */\n\t  \n\t  /* GSL Re-initialise interpolation, don't know if required, but well ... */\n\t  gsl_interp_accel_reset(rpm -> gsl_interp_accelarray[j-NSSDPARAMS]);\n\t  \n\t  for (k = n1; k <= n2; ++k) {\n\t    /* Obsolete when using GSL */\t    \n\t    /* dr = rpm -> modpar[PRADI*rpm -> nr+k]-rpm -> par[PRADI*rpm -> nur+i-1]; */\n\t    \n\t    /* for each parameter the intepolation is done */\n\t    /* Obsolete when using GSL */\t    \n\t    /* rpm -> modpar[j*rpm -> nr+k] = rpm -> par[j*rpm -> nur+i-1]+dpardr[jp]*dr; */\n\t    rpm -> modpar[j*rpm -> nr+k] = gsl_interp_eval (rpm -> gsl_interparray[j-NSSDPARAMS], rpm -> par, rpm -> par + rpm -> nur*j, rpm -> modpar[PRADI*rpm -> nr+k], rpm -> gsl_interp_accelarray[j-NSSDPARAMS]);\n\t  }\n\t  /* Now change the pre-processed parameters and terminate the pointsource lists */\n\t  for (k = n1; k <= n2; ++k)\n\t    srprep(rpm, k, 0, disk);\n\t}\n      }\n    }\n  }\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Generation of a pointsource list */\nstatic void srprep(ringparms *rpm, int srnr, long mode, int disk)\n{\n  (*(rpm -> inf_smiv[disk] -> srprsbrmax))((void *) rpm, srnr, disk);\n  (*(rpm -> inf_smiv[disk] -> srprb0))((void *) rpm, srnr, disk);\n  (*(rpm -> inf_smiv[disk] -> srprs1))((void *) rpm, srnr, disk);\n  (*(rpm -> inf_smiv[disk] -> srprs2))((void *) rpm, srnr, disk);\n  (*(rpm -> inf_smiv[disk] -> srprs3))((void *) rpm, srnr, disk);\n  (*(rpm -> inf_smiv[disk] -> srprs4))((void *) rpm, srnr, disk);\n  (*(rpm -> inf_smiv[disk] -> srprc1))((void *) rpm, srnr, disk);\n  (*(rpm -> inf_smiv[disk] -> srprc2))((void *) rpm, srnr, disk);\n  (*(rpm -> inf_smiv[disk] -> srprc3))((void *) rpm, srnr, disk);\n  (*(rpm -> inf_smiv[disk] -> srprc4))((void *) rpm, srnr, disk);\n  (*(rpm -> inf_gauv[disk] -> srpr0))((void *) rpm, srnr, 0, disk);\n  (*(rpm -> inf_gauv[disk] -> srpr1))((void *) rpm, srnr, 1, disk);\n  (*(rpm -> inf_gauv[disk] -> srpr2))((void *) rpm, srnr, 2, disk);\n  (*(rpm -> inf_gauv[disk] -> srpr3))((void *) rpm, srnr, 3, disk);\n  \n  /* Reset the number of point sources */\n  rpm -> sd[disk][srnr].n = \n    rpm -> sd[disk][srnr].nneg =  \n    rpm -> sd[disk][srnr].npos = 0;\n  rpm -> sd[disk][srnr].nharmnorm = \n    rpm -> sd[disk][srnr].ngaussian[0] = \n    rpm -> sd[disk][srnr].ngaussian[1] = \n    rpm -> sd[disk][srnr].ngaussian[2] = \n    rpm -> sd[disk][srnr].ngaussian[3] = 0;\n  \n  /* Calculate the cloudnumber, rounded down; this will fill the harmnorm variables */\n  (*(rpm -> inf_smiv[disk] -> getcloudnumber))((void *) rpm, srnr, disk);\n  (*(rpm -> inf_gauv[disk] -> getcloudnumber0))((void *) rpm, srnr, 0, disk);\n  (*(rpm -> inf_gauv[disk] -> getcloudnumber1))((void *) rpm, srnr, 1, disk);\n  (*(rpm -> inf_gauv[disk] -> getcloudnumber2))((void *) rpm, srnr, 2, disk);\n  (*(rpm -> inf_gauv[disk] -> getcloudnumber3))((void *) rpm, srnr, 3, disk);\n  \n  /* Change the number of point sources and the cloud flux */\n  (*(rpm -> inf_sdisv[disk] -> chclfl))((void *) rpm, srnr, disk);\n  \n  rpm -> sd[disk][srnr].pllength = rpm -> sd[disk][srnr].n;\n  \n  /* We decide to change the cloudflux a bit instead of accepting an error in the ringflux */\n  /*   rpm -> sd[disk][srnr].pf = ringflux/rpm -> sd[disk][srnr].n; */\n  \n  if (rpm -> sd[disk][srnr].n > 0) {\n    \n    /* We calculate cos's and sins and reset the random number generator */\n    rpm -> sd[disk][srnr].sini=sinf(rpm -> modpar[(PRPARAMS+disk*NDPARAMS+PINCL)*rpm -> nr+srnr]);\n    rpm -> sd[disk][srnr].cosi=cosf(rpm -> modpar[(PRPARAMS+disk*NDPARAMS+PINCL)*rpm -> nr+srnr]);\n    rpm -> sd[disk][srnr].sinp=sinf(rpm -> modpar[(PRPARAMS+disk*NDPARAMS+PPA)*rpm -> nr+srnr]);\n    rpm -> sd[disk][srnr].cosp=cosf(rpm -> modpar[(PRPARAMS+disk*NDPARAMS+PPA)*rpm -> nr+srnr]);\n    \n    /* prepare the subrings for harmonics info */\n    /* velocity */\n    (*(rpm -> inf_vm1v[disk] -> srprs))((void *) rpm, srnr, disk);\n    (*(rpm -> inf_vm1v[disk] -> srprc))((void *) rpm, srnr, disk);\n    (*(rpm -> inf_vm2v[disk] -> srprs))((void *) rpm, srnr, disk);\n    (*(rpm -> inf_vm2v[disk] -> srprc))((void *) rpm, srnr, disk);\n    (*(rpm -> inf_vm3v[disk] -> srprs))((void *) rpm, srnr, disk);\n    (*(rpm -> inf_vm3v[disk] -> srprc))((void *) rpm, srnr, disk);\n    (*(rpm -> inf_vm4v[disk] -> srprs))((void *) rpm, srnr, disk);\n    (*(rpm -> inf_vm4v[disk] -> srprc))((void *) rpm, srnr, disk); \n    \n    (*(rpm -> inf_ra1v[disk] -> srprs))((void *) rpm, srnr, disk);\n    (*(rpm -> inf_ra1v[disk] -> srprc))((void *) rpm, srnr, disk);\n    (*(rpm -> inf_ra2v[disk] -> srprs))((void *) rpm, srnr, disk);\n    (*(rpm -> inf_ra2v[disk] -> srprc))((void *) rpm, srnr, disk);\n    (*(rpm -> inf_ra3v[disk] -> srprs))((void *) rpm, srnr, disk);\n    (*(rpm -> inf_ra3v[disk] -> srprc))((void *) rpm, srnr, disk);\n    (*(rpm -> inf_ra4v[disk] -> srprs))((void *) rpm, srnr, disk);\n    (*(rpm -> inf_ra4v[disk] -> srprc))((void *) rpm, srnr, disk); \n    \n    (*(rpm -> inf_ro1v[disk] -> srprs))((void *) rpm, srnr, disk);\n    (*(rpm -> inf_ro1v[disk] -> srprc))((void *) rpm, srnr, disk);\n    (*(rpm -> inf_ro2v[disk] -> srprs))((void *) rpm, srnr, disk);\n    (*(rpm -> inf_ro2v[disk] -> srprc))((void *) rpm, srnr, disk);\n    (*(rpm -> inf_ro3v[disk] -> srprs))((void *) rpm, srnr, disk);\n    (*(rpm -> inf_ro3v[disk] -> srprc))((void *) rpm, srnr, disk);\n    (*(rpm -> inf_ro4v[disk] -> srprs))((void *) rpm, srnr, disk);\n    (*(rpm -> inf_ro4v[disk] -> srprc))((void *) rpm, srnr, disk); \n    \n    /* warps */\n    (*(rpm -> inf_wm1v[disk] -> srprs))((void *) rpm, srnr, disk);\n    (*(rpm -> inf_wm1v[disk] -> srprc))((void *) rpm, srnr, disk);\n    (*(rpm -> inf_wm2v[disk] -> srprs))((void *) rpm, srnr, disk);\n    (*(rpm -> inf_wm2v[disk] -> srprc))((void *) rpm, srnr, disk);\n    (*(rpm -> inf_wm3v[disk] -> srprs))((void *) rpm, srnr, disk);\n    (*(rpm -> inf_wm3v[disk] -> srprc))((void *) rpm, srnr, disk);\n    (*(rpm -> inf_wm4v[disk] -> srprs))((void *) rpm, srnr, disk);\n    (*(rpm -> inf_wm4v[disk] -> srprc))((void *) rpm, srnr, disk); \n    \n    /* Azimuth ranges */\n    (*(rpm -> inf_aziv[disk] -> srpr0))((void *) rpm, srnr, 0, disk); \n    (*(rpm -> inf_aziv[disk] -> srpr1))((void *) rpm, srnr, 1, disk); \n  }\n  \n  /* free the pointsource list */\n  if ((rpm -> sd[disk][srnr].pl)) {\n    free(rpm -> sd[disk][srnr].pl);\n    rpm -> sd[disk][srnr].pl = NULL;\n  }\n#ifdef PBCORR\n  rpm -> dealloc_pbcfac(rpm, srnr, disk);\n#endif\n  \n  \n  \n  return;\n}\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Grids a point to a pointsource list */\n#ifdef PBCORR\nstatic void gridpoint_norm(hdrinf *hdr, void (*fill_pbcfac)(hdrinf *hdr, struct srd **sd, int disk, int srnr, long *pnr, int *grid), float *modpar, int nr, struct srd **sd, int srnr, long *pnr, float *pp, int signum, long *npoints, int disk)\n#else\nstatic void gridpoint_norm(hdrinf *hdr, float *modpar, int nr, struct srd **sd, int srnr, long *pnr, float *pp, int signum, long *npoints, int disk)\n#endif\n{\n  int grid[3];\n\n  /* of course we could make it even shorter, but we'll leave it at that. Next thingy is to grid the pointsource */\n  grid[0] = roundnormal(modpar[(PRPARAMS+disk*NDPARAMS+PXPOS)*nr+srnr]-pp[1]);\n  \n  if (grid[0] >= 0 && grid[0] < hdr -> bsize1) {\n    \n    grid[1] = roundnormal(modpar[(PRPARAMS+disk*NDPARAMS+PYPOS)*nr+srnr]+pp[0]);\n    if (grid[1] >= 0 && grid[1] < hdr -> bsize2) {\n      /* */\n      grid[2] = roundnormal((modpar[(PRPARAMS+disk*NDPARAMS+PVSYS)*nr+srnr]+hdr -> signv*pp[5]));\n      /*       grid[2] = roundnormal((modpar[(PRPARAMS+disk*NDPARAMS+PVSYS)*nr+srnr]+pp[4])); */\n      if (grid[2] >= 0 && grid[2] < hdr -> nsubs) {\n\t\n\t/* This is the position in the linear cube array */\n\tsd[disk][srnr].pl[*pnr] = hdr -> modelc -> points +(grid[0]+ hdr -> bcsize1*(grid[1])+hdr -> nprof*(grid[2]));\n\n\t/* And this is for the primary beam correction */\n\n#ifdef PBCORR\n\tfill_pbcfac(hdr, sd, disk, srnr, pnr, grid);\n#endif\n\n\t++(*pnr);\n      }\n      else {\n\t--sd[disk][srnr].n;\n\t*npoints -= 1;\n\t++sd[disk][srnr].outn;\n      }\n    }\n    else {\n      --sd[disk][srnr].n;\n      *npoints -= 1;\n      ++sd[disk][srnr].outn;\n    }\n  }\n  else {\n    --sd[disk][srnr].n;\n    *npoints -= 1;\n    ++sd[disk][srnr].outn;\n  }\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Grids a point to a pointsource list */\n#ifdef PBCORR\nstatic void gridpoint_mixed(hdrinf *hdr, void (*fill_pbcfac)(hdrinf *hdr, struct srd **sd, int disk, int srnr, long *pnr, int *grid), float *modpar, int nr, struct srd **sd, int srnr, long *pnr, float *pp, int signum, long *npoints, int disk)\n#else\nstatic void gridpoint_mixed(hdrinf *hdr, float *modpar, int nr, struct srd **sd, int srnr, long *pnr, float *pp, int signum, long *npoints, int disk)\n#endif\n{\n  int grid[3];\n  \n  /* of course we could make it even shorter, but we'll leave it at that. Next thingy is to grid the pointsource */\n  grid[0] = roundnormal(modpar[(PRPARAMS+disk*NDPARAMS+PXPOS)*nr+srnr]-pp[1]);\n  \n  if (grid[0] >= 0 && grid[0] < hdr -> bsize1) {\n    \n    grid[1] = roundnormal(modpar[(PRPARAMS+disk*NDPARAMS+PYPOS)*nr+srnr]+pp[0]);\n    if (grid[1] >= 0 && grid[1] < hdr -> bsize2) {\n      /* For the sake of clarity, we kill the subsnuma operation in the source, in principle thus allowing only for the radio convention for velocity, but gaining an understanding of the code. What is seen here should not be done. It's really not what anyone should wish for. */\n      grid[2] = roundnormal((modpar[(PRPARAMS+disk*NDPARAMS+PVSYS)*nr+srnr]+hdr -> signv*pp[5]));\n      /*       grid[2] = roundnormal((modpar[(PRPARAMS+disk*NDPARAMS+PVSYS)*nr+srnr]+pp[4])); */\n      if (grid[2] >= 0 && grid[2] < hdr -> nsubs) {\n\t\n\t/* This is the position in the linear cube array */\n\tif (signum) {\n\t  sd[disk][srnr].pl[sd[disk][srnr].npos] = hdr -> modelc -> points +(grid[0]+ hdr -> bcsize1*(grid[1])+hdr -> nprof*(grid[2]));\n\t  ++sd[disk][srnr].npos;\n\t}\n\telse {\n\t  ++sd[disk][srnr].nneg;\n\t  sd[disk][srnr].pl[sd[disk][srnr].pllength-sd[disk][srnr].nneg] = hdr -> modelc -> points+(grid[0]+ hdr -> bcsize1*(grid[1])+hdr -> nprof*(grid[2]));\n\t}\n\n#ifdef PBCORR\n\tfill_pbcfac(hdr, sd, disk, srnr, pnr, grid);\n#endif\n\n\t++(*pnr);\n      }\n      else {\n\t--sd[disk][srnr].n;\n\t*npoints -= 1;\n\t++sd[disk][srnr].outn;\n/* \tif (signum) { */\n/* \t  ++sd[disk][srnr].outnpos; */\n/* \t} */\n/* \telse { */\n/* \t  ++sd[disk][srnr].outnneg; */\n/* \t} */\n      }\n    }\n    else {\n      --sd[disk][srnr].n;\n      *npoints -= 1;\n      ++sd[disk][srnr].outn;\n/*       if (signum) { */\n/* \t++sd[disk][srnr].outnpos; */\n/*       } */\n/*       else { */\n/* \t++sd[disk][srnr].outnneg; */\n/*       } */\n    }\n  }\n  else {\n    --sd[disk][srnr].n;\n    *npoints -= 1;\n    ++sd[disk][srnr].outn;\n/*     if (signum) { */\n/*       ++sd[disk][srnr].outnpos; */\n/*     } */\n/*     else { */\n/*       ++sd[disk][srnr].outnneg; */\n/*     } */\n  }\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Grids a point to a pointsource list */\n#ifdef PBCORR\nstatic void gridpoint_normcool(hdrinf *hdr, void (*fill_pbcfac)(hdrinf *hdr, struct srd **sd, int disk, int srnr, long *pnr, int *grid), float *modpar, int nr, struct srd **sd, int srnr, long *pnr, float *pp, int signum, long *npoints, int disk)\n#else\nstatic void gridpoint_normcool(hdrinf *hdr, float *modpar, int nr, struct srd **sd, int srnr, long *pnr, float *pp, int signum, long *npoints, int disk)\n#endif\n{\n  int grid[3];\n\n  /* of course we could make it even shorter, but we'll leave it at that. Next thingy is to grid the pointsource */\n  grid[0] = roundnormal((modpar[(PRPARAMS+disk*NDPARAMS+PXPOS)*nr+srnr]-pp[1])*((float) hdr->coolbin));\n  \n  if (grid[0] >= 0 && grid[0] < hdr -> coolcube -> size_x) {\n    \n    grid[1] = roundnormal((modpar[(PRPARAMS+disk*NDPARAMS+PYPOS)*nr+srnr]+pp[0])*((float) hdr->coolbin));\n    if (grid[1] >= 0 && grid[1] < hdr -> coolcube -> size_y) {\n      /* */\n      grid[2] = roundnormal(hdr -> coolhalfc+pp[2]*((float) hdr->coolbin));\n      /*       grid[2] = roundnormal((modpar[(PRPARAMS+disk*NDPARAMS+PVSYS)*nr+srnr]+pp[4])); */\n      if (grid[2] >= 0 && grid[2] < hdr -> coolcube -> size_v) {\n\t\n\t/* This is the position in the linear cube array */\n\tsd[disk][srnr].pl[*pnr] = hdr -> coolcube -> points +(grid[0]+ hdr -> coolcube -> size_x*(grid[1])+hdr -> nprofcool*(grid[2]));\n\n\t/* And this is for the primary beam correction */\n\n#ifdef PBCORR\n\tfill_pbcfac(hdr, sd, disk, srnr, pnr, grid);\n#endif\n\n\t++(*pnr);\n      }\n      else {\n\t--sd[disk][srnr].n;\n\t*npoints -= 1;\n\t++sd[disk][srnr].outn;\n      }\n    }\n    else {\n      --sd[disk][srnr].n;\n      *npoints -= 1;\n      ++sd[disk][srnr].outn;\n    }\n  }\n  else {\n    --sd[disk][srnr].n;\n    *npoints -= 1;\n    ++sd[disk][srnr].outn;\n  }\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Grids a point to a pointsource list */\n#ifdef PBCORR\nstatic void gridpoint_mixedcool(hdrinf *hdr, void (*fill_pbcfac)(hdrinf *hdr, struct srd **sd, int disk, int srnr, long *pnr, int *grid), float *modpar, int nr, struct srd **sd, int srnr, long *pnr, float *pp, int signum, long *npoints, int disk)\n#else\nstatic void gridpoint_mixedcool(hdrinf *hdr, float *modpar, int nr, struct srd **sd, int srnr, long *pnr, float *pp, int signum, long *npoints, int disk)\n#endif\n{\n  int grid[3];\n  \n  /* of course we could make it even shorter, but we'll leave it at that. Next thingy is to grid the pointsource */\n  grid[0] = roundnormal((modpar[(PRPARAMS+disk*NDPARAMS+PXPOS)*nr+srnr]-pp[1])*((float) hdr->coolbin));\n  \n  if (grid[0] >= 0 && grid[0] < hdr -> coolcube -> size_x) {\n    \n    grid[1] = roundnormal((modpar[(PRPARAMS+disk*NDPARAMS+PYPOS)*nr+srnr]+pp[0])*((float) hdr->coolbin));\n    if (grid[1] >= 0 && grid[1] < hdr -> bsize2) {\n      /* For the sake of clarity, we kill the subsnuma operation in the source, in principle thus allowing only for the radio convention for velocity, but gaining an understanding of the code. What is seen here should not be done. It's really not what anyone should wish for. */\n      grid[2] = roundnormal(hdr -> coolhalfc+pp[2]*((float) hdr->coolbin));\n      /*       grid[2] = roundnormal((modpar[(PRPARAMS+disk*NDPARAMS+PVSYS)*nr+srnr]+pp[4])); */\n      if (grid[2] >= 0 && grid[2] < hdr -> coolcube -> size_v) {\n\t\n\t/* This is the position in the linear cube array */\n\tif (signum) {\n\t  sd[disk][srnr].pl[sd[disk][srnr].npos] = hdr -> coolcube -> points +(grid[0]+ hdr -> coolcube -> size_x*(grid[1])+hdr -> nprofcool*(grid[2]));\n\t  ++sd[disk][srnr].npos;\n\t}\n\telse {\n\t  ++sd[disk][srnr].nneg;\n\t  sd[disk][srnr].pl[sd[disk][srnr].pllength-sd[disk][srnr].nneg] = hdr -> coolcube -> points+(grid[0]+ hdr -> coolcube -> size_x*(grid[1])+hdr -> nprofcool*(grid[2]));\n\t}\n\n#ifdef PBCORR\n\tfill_pbcfac(hdr, sd, disk, srnr, pnr, grid);\n#endif\n\n\t++(*pnr);\n      }\n      else {\n\t--sd[disk][srnr].n;\n\t*npoints -= 1;\n\t++sd[disk][srnr].outn;\n/* \tif (signum) { */\n/* \t  ++sd[disk][srnr].outnpos; */\n/* \t} */\n/* \telse { */\n/* \t  ++sd[disk][srnr].outnneg; */\n/* \t} */\n      }\n    }\n    else {\n      --sd[disk][srnr].n;\n      *npoints -= 1;\n      ++sd[disk][srnr].outn;\n/*       if (signum) { */\n/* \t++sd[disk][srnr].outnpos; */\n/*       } */\n/*       else { */\n/* \t++sd[disk][srnr].outnneg; */\n/*       } */\n    }\n  }\n  else {\n    --sd[disk][srnr].n;\n    *npoints -= 1;\n    ++sd[disk][srnr].outn;\n/*     if (signum) { */\n/*       ++sd[disk][srnr].outnpos; */\n/*     } */\n/*     else { */\n/*       ++sd[disk][srnr].outnneg; */\n/*     } */\n  }\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Grids a point to a pointsource list */\n#ifdef PBCORR\nstatic int srput_mixed(void (*corr_pbcfac)(struct srd **sd, int disk, int srnr, long grid), struct srd **sd, float *modpar, int nr, double *cflux, double radsep, int srnr, long *fluxpoints, int disk)\n#else\nstatic int srput_mixed(struct srd **sd, float *modpar, int nr, double *cflux, double radsep, int srnr, long *fluxpoints, int disk)\n#endif\n{\n  long i;\n  int negstop;\n\n/*   ringflux = TWOPI*modpar[PRADI*nr+srnr]*radsep*modpar[PSBR*nr+srnr]/cflux; */\n\n  /* Calculate the point source flux */\n\n  /* These lines are a nice idea, however, if the total surface density is close to zero, this becomes probably more inaccurate than what we've left */\n/*   if ((cloudsum = sd[disk][srnr].npos+sd[disk][srnr].outnpos-sd[disk][srnr].nneg-sd[disk][srnr].outnneg)  > 0) { */\n/*     sd[disk][srnr].pf = TWOPI*modpar[PRADI*nr+srnr]*radsep*modpar[PSBR*nr+srnr]/fabs(cloudsum); */\n/*   } */\n/*   else */\n\n/* Kamphuis bugfix */\n/*   sd[disk][srnr].pf = cflux[0]*sd[disk][srnr].nsubclinv; -> */\n  sd[disk][srnr].pf = cflux[disk]*sd[disk][srnr].nsubclinv;\n\n/*   if (!(sd[disk][srnr].pf)) */\n/*     sd[disk][srnr].pf = cflux[0]; */\n\n#ifdef PBCORR\n  for (i = 0; i < sd[disk][srnr].npos; ++i)\n    corr_pbcfac(sd, disk, srnr, i);\n#else\n  for (i = 0; i < sd[disk][srnr].npos; ++i)\n    *(sd[disk][srnr].pl[i]) += sd[disk][srnr].pf;\n#endif\n\n  sd[disk][srnr].pf = -sd[disk][srnr].pf;\n\n  /* Here I don't trust the compiler a bit */\n  negstop = sd[disk][srnr].pllength-sd[disk][srnr].nneg-1;\n\n#ifdef PBCORR\n  for (i = sd[disk][srnr].pllength-1; i > negstop; --i)\n    corr_pbcfac(sd, disk, srnr, i);\n#else\n  for (i = sd[disk][srnr].pllength-1; i > negstop; --i)\n    *(sd[disk][srnr].pl[i]) += sd[disk][srnr].pf;\n#endif\n\n  /* Don't need that anymore, but it would be good to have) */\n/*   forget((void **) &sd[disk][srnr].pl); */\n\n  /* Add to number of points contributing to flux */\n  /*   fluxpoints[disk] = */\n  sd[disk][srnr].fluxpoints = (sd[disk][srnr].npos-sd[disk][srnr].nneg)/sd[disk][srnr].nsubcl;\n\n  /* Return number of pointsources */\n  return sd[disk][srnr].allnpoints = (sd[disk][srnr].npos+sd[disk][srnr].nneg)/sd[disk][srnr].nsubcl;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Grids a point to a pointsource list */\n#ifdef PBCORR\nstatic int srput_norm(void (*corr_pbcfac)(struct srd **sd, int disk, int srnr, long grid), struct srd **sd, float *modpar, int nr, double *cflux, double radsep, int srnr, long *fluxpoints, int disk)\n#else\nstatic int srput_norm(struct srd **sd, float *modpar, int nr, double *cflux, double radsep, int srnr, long *fluxpoints, int disk)\n#endif\n{\n  long i;\n  /****************/\n  /****************/\n/*       int obsint = 1;  */\n/*       char obsmes[81];  */\n  /****************/\n  /******/\n  /******/\n/*       if (srnr == 0) { */\n/* \tsprintf(obsmes, \"ya got here: srput_norm disk: %i n: %i\", disk, (int) sd[disk][srnr].n);   */\n/*       anyout_tir(&obsint, obsmes); */\n/*       } */\n  /******/\n\n  /* What was the pointsource flux, note that this is done now in parallel (danger?) */\n#ifdef PBCORR\n  for (i = 0; i < sd[disk][srnr].n; ++i)\n    corr_pbcfac(sd, disk, srnr, i);\n#else\n  for (i = 0; i < sd[disk][srnr].n; ++i)\n    *(sd[disk][srnr].pl[i]) += sd[disk][srnr].pf;\n#endif\n\n  /* Don't need that anymore, but it would be good to have) */\n/*   forget((void **) &sd[disk][srnr].pl); */\n\n/*   fluxpoints[disk]  */\n    sd[disk][srnr].fluxpoints = sd[disk][srnr].n*(sd[disk][srnr].pf>0?1:-1)/sd[disk][srnr].nsubcl;\n\n  /* Return number of pointsources */\n  return sd[disk][srnr].allnpoints = sd[disk][srnr].n/sd[disk][srnr].nsubcl;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Generation of a pointsource list */\nstatic long srconst(hdrinf *hdr, ringparms *rpm, int srnr, long mode, int disk)\n{\n  int i;\n\n  /* The next four variables were declared static before, but now we use parallel code, such that it might be a bad idea */\n  float az;\n  float cosaz; /* The cos of the az (memory wasting) */\n  float sinaz; /* The sin of the az (memory wasting) */\n  float pp[6]; /* Cartesian coordinates in phase-space, x,y,z,vx,vy,vz */\n                      /*                                       x: DEC, y: RA, z: LOS towards observer */\n  char mes[180];\n  int err = 4;\n  int signum;\n  long npoints, j;\n  int dummyint;\n  \n\n\n  /* First check if we do anything but remembering */\n  if (rpm -> sd[disk][srnr].pl) {\n/*     remember((void **) &rpm -> sd[disk][srnr].pl); */\n    return rpm -> sd[disk][srnr].outpoints = rpm -> sd[disk][srnr].outn/rpm -> sd[disk][srnr].nsubcl;\n  }\n\n  /* Now we try to allocate */\n  if ((rpm -> sd[disk][srnr].n)){\n    if (!(rpm -> sd[disk][srnr].pl = (float **) malloc(rpm -> sd[disk][srnr].n*sizeof(float *)))) {\n      /* Catastrophy, simply stop */\n      sprintf(mes, \"Too many pointsources, increase PFLUX\");\n      error_tir(&err, mes);\n    }\n#ifdef PBCORR\n    rpm -> alloc_pbcfac(rpm, srnr, disk);\n#endif\n  }\n\n  /* If there's no pointsource we allocate nevertheless for the smallest thing possible */\n  else {\n    if (!(rpm -> sd[disk][srnr].pl = (float **) malloc(sizeof(float *)))) {\n\n      /* Catastrophy, simply stop */\n      sprintf(mes, \"Too many pointsources, increase PFLUX\");\n      error_tir(&err, mes);\n    }\n    \n#ifdef PBCORR\n    rpm -> alloc_pbcfac(rpm, srnr, disk);\n#endif\n\n    /* Changed this, but not sure */\n    rpm -> sd[disk][srnr].outn = rpm -> sd[disk][srnr].nneg = rpm -> sd[disk][srnr].npos = 0;\n    return rpm -> sd[disk][srnr].outpoints = 0;\n  }\n\n  /* Initialise random generators */\n  rpm -> sd[disk][srnr].iseed2[1] = srnr+disk;\n  maths_rndmf_init(rpm -> sd[disk][srnr].iseed2, rpm -> sd[disk][srnr].permrandstr);\n  \n  /* reset the  zprof */ \n  zprof(6, rpm -> sd[disk][srnr].permrandstr, &(rpm -> sd[disk][srnr].y2));\n\n  /* Do the same for variable functions */\n  (*(rpm -> inf_sdisv[disk] -> rndmf_init))((void *) rpm, srnr, disk);\n  (*(rpm -> inf_smiv[disk] -> rndmf_init))((void *) rpm, srnr, disk);\n  (*(rpm -> inf_gauv[disk] -> rndmf_init0))((void *) rpm, srnr, 0,disk);\n  (*(rpm -> inf_gauv[disk] -> rndmf_init1))((void *) rpm, srnr, 1,disk);\n  (*(rpm -> inf_gauv[disk] -> rndmf_init2))((void *) rpm, srnr, 2,disk);\n  (*(rpm -> inf_gauv[disk] -> rndmf_init3))((void *) rpm, srnr, 3,disk);\n\n  /* Reset the counters */\n  j = 0;\n  rpm -> sd[disk][srnr].outn = 0;\n/*   rpm -> sd[disk][srnr].outnpos = */\n/*   rpm -> sd[disk][srnr].outnneg = 0; */\n\n  npoints = rpm -> sd[disk][srnr].nharmnorm;\n\n  signum = rpm -> modpar[(PRPARAMS+disk*NDPARAMS+PSBR)*rpm -> nr+srnr] > 0?1:0;\n\n  while (j < npoints) {\n\n    /* Calculate azimuth sine and cosine, conventional */\n    (*(rpm -> inf_smiv[disk] -> getaz))((void *) rpm, &az, &sinaz, &cosaz, &signum, srnr, disk);\n\n    /* Check if the azimuth is ok */\n/*     rpm -> sd[disk][srnr].outofrange = 1; */\n    (*(rpm -> inf_aziv[disk] -> setoutrange))(&(rpm -> sd[disk][srnr].outofrange));\n    (*(rpm -> inf_aziv[disk] -> pr0))(&az, rpm -> sd[disk][srnr].ranges, &(rpm -> sd[disk][srnr].outofrange), 0);\n    (*(rpm -> inf_aziv[disk] -> pr1))(&az, rpm -> sd[disk][srnr].ranges, &(rpm -> sd[disk][srnr].outofrange), 1);\n\n    /* Put the point source where it belongs */\n\t/* Put the point source where it belongs */\n\tdummyint = (*(rpm -> inf_aziv[disk] -> srshape))(rpm, pp, sinaz, cosaz, srnr, rpm -> sd[disk][srnr].outofrange, disk);\n/*     (*(rpm -> inf_aziv[disk] -> srshape))((void *) rpm, pp, sinaz, cosaz, srnr, rpm -> sd[disk][srnr].outofrange, disk); */\n    /* srshape(rpm, pp, sinaz, cosaz, srnr); */\n\n    /* Add ring-dependent dispersion, if activated */\n    (*(rpm -> inf_sdisv[disk] -> pr))((void *) rpm, pp+5, &az, srnr, disk);\n\n    /* Grid the point sources */\n#ifdef PBCORR\n    (*(rpm -> sd[disk][srnr].gridpoint))(hdr, rpm -> fill_pbcfac, rpm -> modpar, rpm -> nr, rpm -> sd, srnr, &j, pp, signum, &npoints, disk);\n#else\n    (*(rpm -> sd[disk][srnr].gridpoint))(hdr, rpm -> modpar, rpm -> nr, rpm -> sd, srnr, &j, pp, signum, &npoints, disk);\n#endif\n    /* Correct for the number of point sources if necessary */\n    rpm -> inf_aziv[disk] -> corrp((void *) rpm, srnr, &(rpm -> sd[disk][srnr].outofrange), signum);\n\n    (*(rpm -> inf_sdisv[disk] -> repeater))((void *) rpm, pp, az, srnr, hdr, &j, signum, &npoints, disk);\n\n    if (dummyint)\n      rpm -> sd[disk][srnr].outn = rpm -> sd[disk][srnr].outn-rpm -> sd[disk][srnr].nsubcl;\n  }\n\n\n  /* This is a departure from the policy of doing the best to prevent\n     the program from slowing down when including new parameters,\n     albeit a small one */\n\n  for (i = 0; i < 4; ++i) {\n\n    if ((rpm -> sd[disk][srnr].ngaussian[i])) {\n\n      npoints = npoints + rpm -> sd[disk][srnr].ngaussian[i];\n      \n      /* Determine point source flux */\n      \n      signum = rpm -> modpar[((PRPARAMS+disk*NDPARAMS+PGA1A)+3*i)*rpm -> nr+srnr] > 0?1:0;\n\n      while (j < npoints) {\n\t\n\t/* Calculate azimuth sine and cosine, Gaussian */\n\tgau_getaz(rpm, (PRPARAMS+disk*NDPARAMS+PGA1P)+3*i, rpm -> sd[disk][srnr].grandstr[i], i, &az, &sinaz, &cosaz, srnr, disk);\n\n\t/* Check if the azimuth is ok */\n/* \trpm -> sd[disk][srnr].outofrange = 0; */\n\t(*(rpm -> inf_aziv[disk] -> setoutrange))(&(rpm -> sd[disk][srnr].outofrange));\n\t(*(rpm -> inf_aziv[disk] -> pr0))(&az, rpm -> sd[disk][srnr].ranges, &(rpm -> sd[disk][srnr].outofrange), 0);\n \t(*(rpm -> inf_aziv[disk] -> pr1))(&az, rpm -> sd[disk][srnr].ranges, &(rpm -> sd[disk][srnr].outofrange), 1);\n\t\n\t/* Put the point source where it belongs */\n\tdummyint = (*(rpm -> inf_aziv[disk] -> srshape))(rpm, pp, sinaz, cosaz, srnr, rpm -> sd[disk][srnr].outofrange, disk);\n\t\n\t/* \tsrshape(rpm, pp, sinaz, cosaz, srnr); */\n\t\n\t/* Add ring-dependent dispersion, if activated (why here and not in srshape?) */\n\t(*(rpm -> inf_sdisv[disk] -> pr))((void *) rpm, pp+5, &az, srnr, disk);\n\t\n#ifdef PBCORR\n\t/* Grid the point sources */\n\t(*(rpm -> sd[disk][srnr].gridpoint))(hdr, rpm -> fill_pbcfac, rpm -> modpar, rpm -> nr, rpm -> sd, srnr, &j, pp, signum, &npoints, disk);\n#else\n\t/* Grid the point sources */\n\t(*(rpm -> sd[disk][srnr].gridpoint))(hdr, rpm -> modpar, rpm -> nr, rpm -> sd, srnr, &j, pp, signum, &npoints, disk);\n#endif\t\n\t/* Correct for the number of point sources if necessary */\n\t(*(rpm -> inf_aziv[disk] -> corrp))((void *) rpm, srnr, &(rpm -> sd[disk][srnr].outofrange), signum);\n\n\t(*(rpm -> inf_sdisv[disk] -> repeater))((void *) rpm, pp, az, srnr, hdr, &j, signum, &npoints, disk);\n\n\tif (dummyint)\n\t  rpm -> sd[disk][srnr].outn = rpm -> sd[disk][srnr].outn-rpm -> sd[disk][srnr].nsubcl;\n\n      }\n    }\n  }\n\n  return rpm -> sd[disk][srnr].outpoints = rpm -> sd[disk][srnr].outn/rpm -> sd[disk][srnr].nsubcl;\n}\n\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Generation of a pointsource list */\nstatic long srconstcool(hdrinf *hdr, ringparms *rpm, int srnr, long mode, int disk)\n{\n  int i;\n\n  /* The next four variables were declared static before, but now we use parallel code, such that it might be a bad idea */\n  float az;\n  float cosaz; /* The cos of the az (memory wasting) */\n  float sinaz; /* The sin of the az (memory wasting) */\n  float pp[6]; /* Cartesian coordinates in phase-space, x,y,z,vx,vy,vz */\n                      /*                                       x: DEC, y: RA, z: LOS towards observer */\n  char mes[180];\n  int err = 4;\n  int signum;\n  long npoints, j;\n  int dummyint;\n  \n\n  /* First check if we do anything but remembering */\n  /* if (rpm -> sd[disk][srnr].pl) { */\n/*     remember((void **) &rpm -> sd[disk][srnr].pl); */\n  /*   return rpm -> sd[disk][srnr].outpoints = rpm -> sd[disk][srnr].outn/rpm -> sd[disk][srnr].nsubcl; */\n  /* } */\n  \n  /* Now we try to allocate */\n  if ((rpm -> sd[disk][srnr].n)){\n    if (!(rpm -> sd[disk][srnr].pl = (float **) malloc(rpm -> sd[disk][srnr].n*sizeof(float *)))) {\n      /* Catastrophy, simply stop */\n      sprintf(mes, \"Too many pointsources, increase PFLUX\");\n      error_tir(&err, mes);\n    }\n#ifdef PBCORR\n    rpm -> alloc_pbcfac(rpm, srnr, disk);\n#endif\n  }\n\n  /* If there's no pointsource we allocate nevertheless for the smallest thing possible */\n  else {\n    if (!(rpm -> sd[disk][srnr].pl = (float **) malloc(sizeof(float *)))) {\n\n      /* Catastrophy, simply stop */\n      sprintf(mes, \"Too many pointsources, increase PFLUX\");\n      error_tir(&err, mes);\n    }\n    \n#ifdef PBCORR\n    rpm -> alloc_pbcfac(rpm, srnr, disk);\n#endif\n\n    /* Changed this, but not sure */\n    rpm -> sd[disk][srnr].outn = rpm -> sd[disk][srnr].nneg = rpm -> sd[disk][srnr].npos = 0;\n    return rpm -> sd[disk][srnr].outpoints = 0;\n  }\n\n  /* Initialise random generators */\n  rpm -> sd[disk][srnr].iseed2[1] = srnr+disk;\n  maths_rndmf_init(rpm -> sd[disk][srnr].iseed2, rpm -> sd[disk][srnr].permrandstr);\n  \n  /* reset the  zprof */ \n  zprof(6, rpm -> sd[disk][srnr].permrandstr, &(rpm -> sd[disk][srnr].y2));\n\n  /* Do the same for variable functions */\n  (*(rpm -> inf_sdisv[disk] -> rndmf_init))((void *) rpm, srnr, disk);\n  (*(rpm -> inf_smiv[disk] -> rndmf_init))((void *) rpm, srnr, disk);\n  (*(rpm -> inf_gauv[disk] -> rndmf_init0))((void *) rpm, srnr, 0,disk);\n  (*(rpm -> inf_gauv[disk] -> rndmf_init1))((void *) rpm, srnr, 1,disk);\n  (*(rpm -> inf_gauv[disk] -> rndmf_init2))((void *) rpm, srnr, 2,disk);\n  (*(rpm -> inf_gauv[disk] -> rndmf_init3))((void *) rpm, srnr, 3,disk);\n\n  /* Reset the counters */\n  j = 0;\n  rpm -> sd[disk][srnr].outn = 0;\n/*   rpm -> sd[disk][srnr].outnpos = */\n/*   rpm -> sd[disk][srnr].outnneg = 0; */\n\n  npoints = rpm -> sd[disk][srnr].nharmnorm;\n\n  signum = rpm -> modpar[(PRPARAMS+disk*NDPARAMS+PSBR)*rpm -> nr+srnr] > 0?1:0;\n\n  while (j < npoints) {\n\n    /* Calculate azimuth sine and cosine, conventional */\n    (*(rpm -> inf_smiv[disk] -> getaz))((void *) rpm, &az, &sinaz, &cosaz, &signum, srnr, disk);\n\n    /* Check if the azimuth is ok */\n/*     rpm -> sd[disk][srnr].outofrange = 1; */\n    (*(rpm -> inf_aziv[disk] -> setoutrange))(&(rpm -> sd[disk][srnr].outofrange));\n    (*(rpm -> inf_aziv[disk] -> pr0))(&az, rpm -> sd[disk][srnr].ranges, &(rpm -> sd[disk][srnr].outofrange), 0);\n    (*(rpm -> inf_aziv[disk] -> pr1))(&az, rpm -> sd[disk][srnr].ranges, &(rpm -> sd[disk][srnr].outofrange), 1);\n\n    /* Put the point source where it belongs */\n\t/* Put the point source where it belongs */\n\tdummyint = (*(rpm -> inf_aziv[disk] -> srshape))(rpm, pp, sinaz, cosaz, srnr, rpm -> sd[disk][srnr].outofrange, disk);\n/*     (*(rpm -> inf_aziv[disk] -> srshape))((void *) rpm, pp, sinaz, cosaz, srnr, rpm -> sd[disk][srnr].outofrange, disk); */\n    /* srshape(rpm, pp, sinaz, cosaz, srnr); */\n\n    /* Add ring-dependent dispersion, if activated */\n    /* (*(rpm -> inf_sdisv[disk] -> pr))((void *) rpm, pp+5, &az, srnr, disk); */\n\n    /* Grid the point sources */\n#ifdef PBCORR\n    (*(rpm -> sd[disk][srnr].gridpoint))(hdr, rpm -> fill_pbcfac, rpm -> modpar, rpm -> nr, rpm -> sd, srnr, &j, pp, signum, &npoints, disk);\n#else\n    (*(rpm -> sd[disk][srnr].gridpoint))(hdr, rpm -> modpar, rpm -> nr, rpm -> sd, srnr, &j, pp, signum, &npoints, disk);\n#endif\n    /* Correct for the number of point sources if necessary */\n    rpm -> inf_aziv[disk] -> corrp((void *) rpm, srnr, &(rpm -> sd[disk][srnr].outofrange), signum);\n\n    (*(rpm -> inf_sdisv[disk] -> repeater))((void *) rpm, pp, az, srnr, hdr, &j, signum, &npoints, disk);\n\n    if (dummyint)\n      rpm -> sd[disk][srnr].outn = rpm -> sd[disk][srnr].outn-rpm -> sd[disk][srnr].nsubcl;\n  }\n\n\n  /* This is a departure from the policy of doing the best to prevent\n     the program from slowing down when including new parameters,\n     albeit a small one */\n\n  for (i = 0; i < 4; ++i) {\n\n    if ((rpm -> sd[disk][srnr].ngaussian[i])) {\n\n      npoints = npoints + rpm -> sd[disk][srnr].ngaussian[i];\n      \n      /* Determine point source flux */\n      \n      signum = rpm -> modpar[((PRPARAMS+disk*NDPARAMS+PGA1A)+3*i)*rpm -> nr+srnr] > 0?1:0;\n\n      while (j < npoints) {\n\t\n\t/* Calculate azimuth sine and cosine, Gaussian */\n\tgau_getaz(rpm, (PRPARAMS+disk*NDPARAMS+PGA1P)+3*i, rpm -> sd[disk][srnr].grandstr[i], i, &az, &sinaz, &cosaz, srnr, disk);\n\n\t/* Check if the azimuth is ok */\n/* \trpm -> sd[disk][srnr].outofrange = 0; */\n\t(*(rpm -> inf_aziv[disk] -> setoutrange))(&(rpm -> sd[disk][srnr].outofrange));\n\t(*(rpm -> inf_aziv[disk] -> pr0))(&az, rpm -> sd[disk][srnr].ranges, &(rpm -> sd[disk][srnr].outofrange), 0);\n \t(*(rpm -> inf_aziv[disk] -> pr1))(&az, rpm -> sd[disk][srnr].ranges, &(rpm -> sd[disk][srnr].outofrange), 1);\n\t\n\t/* Put the point source where it belongs */\n\tdummyint = (*(rpm -> inf_aziv[disk] -> srshape))(rpm, pp, sinaz, cosaz, srnr, rpm -> sd[disk][srnr].outofrange, disk);\n\t\n\t/* \tsrshape(rpm, pp, sinaz, cosaz, srnr); */\n\t\n\t/* Add ring-dependent dispersion, if activated (why here and not in srshape?) */\n/* \t(*(rpm -> inf_sdisv[disk] -> pr))((void *) rpm, pp+5, &az, srnr, disk); */\n\t\n#ifdef PBCORR\n\t/* Grid the point sources */\n\t(*(rpm -> sd[disk][srnr].gridpoint))(hdr, rpm -> fill_pbcfac, rpm -> modpar, rpm -> nr, rpm -> sd, srnr, &j, pp, signum, &npoints, disk);\n#else\n\t/* Grid the point sources */\n\t(*(rpm -> sd[disk][srnr].gridpoint))(hdr, rpm -> modpar, rpm -> nr, rpm -> sd, srnr, &j, pp, signum, &npoints, disk);\n#endif\t\n\t/* Correct for the number of point sources if necessary */\n\t(*(rpm -> inf_aziv[disk] -> corrp))((void *) rpm, srnr, &(rpm -> sd[disk][srnr].outofrange), signum);\n\n\t(*(rpm -> inf_sdisv[disk] -> repeater))((void *) rpm, pp, az, srnr, hdr, &j, signum, &npoints, disk);\n\n\tif (dummyint)\n\t  rpm -> sd[disk][srnr].outn = rpm -> sd[disk][srnr].outn-rpm -> sd[disk][srnr].nsubcl;\n\n      }\n    }\n  }\n\n  return rpm -> sd[disk][srnr].outpoints = rpm -> sd[disk][srnr].outn/rpm -> sd[disk][srnr].nsubcl;\n}\n\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Generation of a pointsource list */\nstatic void srshape(ringparms *rpm, float *pp, float sinaz, float cosaz, int srnr, int disk)\n{\n  float r;\n  float pp2[6];\n    \n  /* The probability for the radius is weighted by r, and this is no approximation, hence a speed brake, should be removed at some point */\n  r = sqrtf((rpm -> modpar[PRADI*rpm -> nr+srnr]-0.5*rpm -> radsep)*(rpm -> modpar[PRADI*rpm -> nr+srnr]-0.5*rpm -> radsep)+2*rpm -> radsep*rpm -> modpar[PRADI*rpm -> nr+srnr]*maths_rndmf(rpm -> sd[disk][srnr].permrandstr));\n  \n  \n  /* Calculate the coordinates of the point source before rotation */\n    pp[0] = cosaz*r;\n    pp[1] = sinaz*r;\n    pp[2] = zprof(rpm -> ltype[disk],  rpm -> sd[disk][srnr].permrandstr, &(rpm -> sd[disk][srnr].y2))*rpm -> modpar[(PRPARAMS+disk*NDPARAMS+PZ0)*rpm -> nr+srnr];\n\n    pp[4] = cosaz*rpm -> modpar[(PRPARAMS+disk*NDPARAMS+PVROT)*rpm -> nr+srnr];\n\n/* Here comes the harmonic velocity terms */\n    (*(rpm -> inf_ro1v[disk] -> prs))((void *) rpm, pp+4, srnr, sinaz, cosaz, disk);\n    (*(rpm -> inf_ro2v[disk] -> prs))((void *) rpm, pp+4, srnr, sinaz, cosaz, disk);\n    (*(rpm -> inf_ro3v[disk] -> prs))((void *) rpm, pp+4, srnr, sinaz, cosaz, disk);\n    (*(rpm -> inf_ro4v[disk] -> prs))((void *) rpm, pp+4, srnr, sinaz, cosaz, disk);\n    (*(rpm -> inf_ro1v[disk] -> prc))((void *) rpm, pp+4, srnr, sinaz, cosaz, disk);\n    (*(rpm -> inf_ro2v[disk] -> prc))((void *) rpm, pp+4, srnr, sinaz, cosaz, disk);\n    (*(rpm -> inf_ro3v[disk] -> prc))((void *) rpm, pp+4, srnr, sinaz, cosaz, disk);\n    (*(rpm -> inf_ro4v[disk] -> prc))((void *) rpm, pp+4, srnr, sinaz, cosaz, disk);\n \n    /* vertical gradient in rotation velocity */\n    (*(rpm -> inf_dvrov[disk] -> pr)) ((void *) rpm, pp, srnr, sinaz, cosaz, disk);\n\n    /* Radial velocity term */\n    (*(rpm -> inf_vradv[disk] -> pr)) ((void *) rpm, pp+4, srnr, sinaz, cosaz, disk);\n\n    /* Here comes the harmonic velocity terms */\n    (*(rpm -> inf_ra1v[disk] -> prs))((void *) rpm, pp+4, srnr, sinaz, cosaz, disk);\n    (*(rpm -> inf_ra2v[disk] -> prs))((void *) rpm, pp+4, srnr, sinaz, cosaz, disk);\n    (*(rpm -> inf_ra3v[disk] -> prs))((void *) rpm, pp+4, srnr, sinaz, cosaz, disk);\n    (*(rpm -> inf_ra4v[disk] -> prs))((void *) rpm, pp+4, srnr, sinaz, cosaz, disk);\n    (*(rpm -> inf_ra1v[disk] -> prc))((void *) rpm, pp+4, srnr, sinaz, cosaz, disk);\n    (*(rpm -> inf_ra2v[disk] -> prc))((void *) rpm, pp+4, srnr, sinaz, cosaz, disk);\n    (*(rpm -> inf_ra3v[disk] -> prc))((void *) rpm, pp+4, srnr, sinaz, cosaz, disk);\n    (*(rpm -> inf_ra4v[disk] -> prc))((void *) rpm, pp+4, srnr, sinaz, cosaz, disk);\n \n    /* vertical gradient in radial velocity */\n    (*(rpm -> inf_dvrav[disk] -> pr)) ((void *) rpm, pp, srnr, sinaz, cosaz, disk);\n\n    pp[5] = 0.0;\n\n    /* Vertical velocity term */\n    (*(rpm -> inf_vverv[disk] -> pr)) ((void *) rpm, pp, srnr, disk);\n\n    /* vertical gradient in vertical velocity */\n    (*(rpm -> inf_dvvev[disk] -> pr)) ((void *) rpm, pp, srnr, disk);\n\n    /* We do the warp harmonics here */\n    (*(rpm -> inf_wm1v[disk] -> prs))((void *) rpm, pp+2, srnr, sinaz, cosaz, disk);\n    (*(rpm -> inf_wm2v[disk] -> prs))((void *) rpm, pp+2, srnr, sinaz, cosaz, disk);\n    (*(rpm -> inf_wm3v[disk] -> prs))((void *) rpm, pp+2, srnr, sinaz, cosaz, disk);\n    (*(rpm -> inf_wm4v[disk] -> prs))((void *) rpm, pp+2, srnr, sinaz, cosaz, disk);\n    (*(rpm -> inf_wm1v[disk] -> prc))((void *) rpm, pp+2, srnr, sinaz, cosaz, disk);\n    (*(rpm -> inf_wm2v[disk] -> prc))((void *) rpm, pp+2, srnr, sinaz, cosaz, disk);\n    (*(rpm -> inf_wm3v[disk] -> prc))((void *) rpm, pp+2, srnr, sinaz, cosaz, disk);\n    (*(rpm -> inf_wm4v[disk] -> prc))((void *) rpm, pp+2, srnr, sinaz, cosaz, disk);\n    (*(rpm -> inf_wm0v[disk] -> pr)) ((void *) rpm, pp+2, srnr, sinaz, cosaz, disk);\n\n\n    /* Now rotate about the x-axis by i */\n    pp2[0] = pp[0];\n    pp2[1] = pp[1]*rpm -> sd[disk][srnr].cosi-pp[2]*rpm -> sd[disk][srnr].sini;\n\n    /* Now we shift */\n\n    (*(rpm -> inf_lc0v[disk] -> pr))((void *) rpm, pp2+0, srnr, sinaz, cosaz, disk);\n    (*(rpm -> inf_ls0v[disk] -> pr))((void *) rpm, pp2+1, srnr, sinaz, cosaz, disk);\n\n\n/*     pp2[2] = pp[1]*rpm -> sd[disk][srnr].sini+pp[2]*rpm -> sd[disk][srnr].cosi; */\n/*     pp2[3] = pp[3]; */\n/*     pp2[4] = pp[4]*rpm -> sd[disk][srnr].cosi-pp[5]*rpm -> sd[disk][srnr].sini; */\n/*     pp2[5] = pp[4]*rpm -> sd[disk][srnr].sini+pp[5]*rpm -> sd[disk][srnr].cosi; */\n\n    pp2[5] = pp[4]*rpm -> sd[disk][srnr].sini;\n\n    /* But if we did a vertical velocity component */\n    (*(rpm -> inf_vverv[disk] -> pr_rota)) ((void *) rpm, pp+5, pp2+5, srnr, disk);\n\n/* Here comes the harmonic velocity terms */\n    (*(rpm -> inf_vm1v[disk] -> prs))((void *) rpm, pp2+5, srnr, sinaz, cosaz, disk);\n    (*(rpm -> inf_vm2v[disk] -> prs))((void *) rpm, pp2+5, srnr, sinaz, cosaz, disk);\n    (*(rpm -> inf_vm3v[disk] -> prs))((void *) rpm, pp2+5, srnr, sinaz, cosaz, disk);\n    (*(rpm -> inf_vm4v[disk] -> prs))((void *) rpm, pp2+5, srnr, sinaz, cosaz, disk);\n    (*(rpm -> inf_vm1v[disk] -> prc))((void *) rpm, pp2+5, srnr, sinaz, cosaz, disk);\n    (*(rpm -> inf_vm2v[disk] -> prc))((void *) rpm, pp2+5, srnr, sinaz, cosaz, disk);\n    (*(rpm -> inf_vm3v[disk] -> prc))((void *) rpm, pp2+5, srnr, sinaz, cosaz, disk);\n    (*(rpm -> inf_vm4v[disk] -> prc))((void *) rpm, pp2+5, srnr, sinaz, cosaz, disk);\n    (*(rpm -> inf_vm0v[disk] -> pr))((void *) rpm, pp2+5, srnr, sinaz, cosaz, disk);\n\n    /* Now rotate about the z-axis by pa */\n/*     pp[0] = pp2[0]*rpm -> sd[disk][srnr].cosp-pp2[1]*rpm -> sd[disk][srnr].sinp; */\n/*     pp[1] = pp2[0]*rpm -> sd[disk][srnr].sinp+pp2[1]*rpm -> sd[disk][srnr].cosp; */\n/*     pp[2] = pp2[2]; */\n/*     pp[3] = pp2[3]*rpm -> sd[disk][srnr].cosp-pp2[4]*rpm -> sd[disk][srnr].sinp; */\n/*     pp[4] = pp2[3]*rpm -> sd[disk][srnr].sinp+pp2[4]*rpm -> sd[disk][srnr].cosp; */\n/*     pp[5] = pp2[5]; */\n\n    /* Here's the shortcut version */\n    pp[0] = pp2[0]*rpm -> sd[disk][srnr].cosp-pp2[1]*rpm -> sd[disk][srnr].sinp;\n    pp[1] = pp2[0]*rpm -> sd[disk][srnr].sinp+pp2[1]*rpm -> sd[disk][srnr].cosp;\n    pp[5] = pp2[5];\n\nreturn;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Generation of a pointsource list */\nstatic void srshapecool(ringparms *rpm, float *pp, float sinaz, float cosaz, int srnr, int disk)\n{\n  float r;\n  float pp2[6];\n    \n  /* The probability for the radius is weighted by r, and this is no approximation, hence a speed brake, should be removed at some point */\n  r = sqrtf((rpm -> modpar[PRADI*rpm -> nr+srnr]-0.5*rpm -> radsep)*(rpm -> modpar[PRADI*rpm -> nr+srnr]-0.5*rpm -> radsep)+2*rpm -> radsep*rpm -> modpar[PRADI*rpm -> nr+srnr]*maths_rndmf(rpm -> sd[disk][srnr].permrandstr));\n  \n  \n  /* Calculate the coordinates of the point source before rotation */\n    pp[0] = cosaz*r;\n    pp[1] = sinaz*r;\n    pp[2] = zprof(rpm -> ltype[disk],  rpm -> sd[disk][srnr].permrandstr, &(rpm -> sd[disk][srnr].y2))*rpm -> modpar[(PRPARAMS+disk*NDPARAMS+PZ0)*rpm -> nr+srnr];\n\n    /* pp[4] = cosaz*rpm -> modpar[(PRPARAMS+disk*NDPARAMS+PVROT)*rpm -> nr+srnr]; */\n\n/* Here comes the harmonic velocity terms */\n    /* (*(rpm -> inf_ro1v[disk] -> prs))((void *) rpm, pp+4, srnr, sinaz, cosaz, disk); */\n    /* (*(rpm -> inf_ro2v[disk] -> prs))((void *) rpm, pp+4, srnr, sinaz, cosaz, disk); */\n    /* (*(rpm -> inf_ro3v[disk] -> prs))((void *) rpm, pp+4, srnr, sinaz, cosaz, disk); */\n    /* (*(rpm -> inf_ro4v[disk] -> prs))((void *) rpm, pp+4, srnr, sinaz, cosaz, disk); */\n    /* (*(rpm -> inf_ro1v[disk] -> prc))((void *) rpm, pp+4, srnr, sinaz, cosaz, disk); */\n    /* (*(rpm -> inf_ro2v[disk] -> prc))((void *) rpm, pp+4, srnr, sinaz, cosaz, disk); */\n    /* (*(rpm -> inf_ro3v[disk] -> prc))((void *) rpm, pp+4, srnr, sinaz, cosaz, disk); */\n    /* (*(rpm -> inf_ro4v[disk] -> prc))((void *) rpm, pp+4, srnr, sinaz, cosaz, disk); */\n \n    /* vertical gradient in rotation velocity */\n    /* (*(rpm -> inf_dvrov[disk] -> pr)) ((void *) rpm, pp, srnr, sinaz, cosaz, disk); */\n\n    /* Radial velocity term */\n    /* (*(rpm -> inf_vradv[disk] -> pr)) ((void *) rpm, pp+4, srnr, sinaz, cosaz, disk); */\n\n    /* Here comes the harmonic velocity terms */\n    /* (*(rpm -> inf_ra1v[disk] -> prs))((void *) rpm, pp+4, srnr, sinaz, cosaz, disk); */\n    /* (*(rpm -> inf_ra2v[disk] -> prs))((void *) rpm, pp+4, srnr, sinaz, cosaz, disk); */\n    /* (*(rpm -> inf_ra3v[disk] -> prs))((void *) rpm, pp+4, srnr, sinaz, cosaz, disk); */\n    /* (*(rpm -> inf_ra4v[disk] -> prs))((void *) rpm, pp+4, srnr, sinaz, cosaz, disk); */\n    /* (*(rpm -> inf_ra1v[disk] -> prc))((void *) rpm, pp+4, srnr, sinaz, cosaz, disk); */\n    /* (*(rpm -> inf_ra2v[disk] -> prc))((void *) rpm, pp+4, srnr, sinaz, cosaz, disk); */\n    /* (*(rpm -> inf_ra3v[disk] -> prc))((void *) rpm, pp+4, srnr, sinaz, cosaz, disk); */\n    /* (*(rpm -> inf_ra4v[disk] -> prc))((void *) rpm, pp+4, srnr, sinaz, cosaz, disk); */\n \n    /* vertical gradient in radial velocity */\n    /* (*(rpm -> inf_dvrav[disk] -> pr)) ((void *) rpm, pp, srnr, sinaz, cosaz, disk); */\n\n    /* pp[5] = 0.0; */\n\n    /* Vertical velocity term */\n    /* (*(rpm -> inf_vverv[disk] -> pr)) ((void *) rpm, pp, srnr, disk); */\n\n    /* vertical gradient in vertical velocity */\n    /* (*(rpm -> inf_dvvev[disk] -> pr)) ((void *) rpm, pp, srnr, disk); */\n\n    /* We do the warp harmonics here */\n    (*(rpm -> inf_wm1v[disk] -> prs))((void *) rpm, pp+2, srnr, sinaz, cosaz, disk);\n    (*(rpm -> inf_wm2v[disk] -> prs))((void *) rpm, pp+2, srnr, sinaz, cosaz, disk);\n    (*(rpm -> inf_wm3v[disk] -> prs))((void *) rpm, pp+2, srnr, sinaz, cosaz, disk);\n    (*(rpm -> inf_wm4v[disk] -> prs))((void *) rpm, pp+2, srnr, sinaz, cosaz, disk);\n    (*(rpm -> inf_wm1v[disk] -> prc))((void *) rpm, pp+2, srnr, sinaz, cosaz, disk);\n    (*(rpm -> inf_wm2v[disk] -> prc))((void *) rpm, pp+2, srnr, sinaz, cosaz, disk);\n    (*(rpm -> inf_wm3v[disk] -> prc))((void *) rpm, pp+2, srnr, sinaz, cosaz, disk);\n    (*(rpm -> inf_wm4v[disk] -> prc))((void *) rpm, pp+2, srnr, sinaz, cosaz, disk);\n    (*(rpm -> inf_wm0v[disk] -> pr)) ((void *) rpm, pp+2, srnr, sinaz, cosaz, disk);\n\n\n    /* Now rotate about the x-axis by i */\n    pp2[0] = pp[0];\n    pp2[1] = pp[1]*rpm -> sd[disk][srnr].cosi-pp[2]*rpm -> sd[disk][srnr].sini;\n\t pp2[2] = pp[1]*rpm -> sd[disk][srnr].sini+pp[2]*rpm -> sd[disk][srnr].cosi;\n\n    /* Now we shift */\n    (*(rpm -> inf_lc0v[disk] -> pr))((void *) rpm, pp2+0, srnr, sinaz, cosaz, disk);\n    (*(rpm -> inf_ls0v[disk] -> pr))((void *) rpm, pp2+1, srnr, sinaz, cosaz, disk);\n\n\n/*     pp2[2] = pp[1]*rpm -> sd[disk][srnr].sini+pp[2]*rpm -> sd[disk][srnr].cosi; */\n/*     pp2[3] = pp[3]; */\n/*     pp2[4] = pp[4]*rpm -> sd[disk][srnr].cosi-pp[5]*rpm -> sd[disk][srnr].sini; */\n/*     pp2[5] = pp[4]*rpm -> sd[disk][srnr].sini+pp[5]*rpm -> sd[disk][srnr].cosi; */\n\n    /* pp2[5] = pp[4]*rpm -> sd[disk][srnr].sini; */\n\n    /* But if we did a vertical velocity component */\n    /* (*(rpm -> inf_vverv[disk] -> pr_rota)) ((void *) rpm, pp+5, pp2+5, srnr, disk); */\n\n/* Here comes the harmonic velocity terms */\n    /* (*(rpm -> inf_vm1v[disk] -> prs))((void *) rpm, pp2+5, srnr, sinaz, cosaz, disk); */\n    /* (*(rpm -> inf_vm2v[disk] -> prs))((void *) rpm, pp2+5, srnr, sinaz, cosaz, disk); */\n    /* (*(rpm -> inf_vm3v[disk] -> prs))((void *) rpm, pp2+5, srnr, sinaz, cosaz, disk); */\n    /* (*(rpm -> inf_vm4v[disk] -> prs))((void *) rpm, pp2+5, srnr, sinaz, cosaz, disk); */\n    /* (*(rpm -> inf_vm1v[disk] -> prc))((void *) rpm, pp2+5, srnr, sinaz, cosaz, disk); */\n    /* (*(rpm -> inf_vm2v[disk] -> prc))((void *) rpm, pp2+5, srnr, sinaz, cosaz, disk); */\n    /* (*(rpm -> inf_vm3v[disk] -> prc))((void *) rpm, pp2+5, srnr, sinaz, cosaz, disk); */\n    /* (*(rpm -> inf_vm4v[disk] -> prc))((void *) rpm, pp2+5, srnr, sinaz, cosaz, disk); */\n    /* (*(rpm -> inf_vm0v[disk] -> pr))((void *) rpm, pp2+5, srnr, sinaz, cosaz, disk); */\n\n    /* Now rotate about the z-axis by pa */\n/*     pp[0] = pp2[0]*rpm -> sd[disk][srnr].cosp-pp2[1]*rpm -> sd[disk][srnr].sinp; */\n/*     pp[1] = pp2[0]*rpm -> sd[disk][srnr].sinp+pp2[1]*rpm -> sd[disk][srnr].cosp; */\n/*     pp[2] = pp2[2]; */\n/*     pp[3] = pp2[3]*rpm -> sd[disk][srnr].cosp-pp2[4]*rpm -> sd[disk][srnr].sinp; */\n/*     pp[4] = pp2[3]*rpm -> sd[disk][srnr].sinp+pp2[4]*rpm -> sd[disk][srnr].cosp; */\n/*     pp[5] = pp2[5]; */\n\n    /* Here's the shortcut version */\n    pp[0] = pp2[0]*rpm -> sd[disk][srnr].cosp-pp2[1]*rpm -> sd[disk][srnr].sinp;\n    pp[1] = pp2[0]*rpm -> sd[disk][srnr].sinp+pp2[1]*rpm -> sd[disk][srnr].cosp;\n\t pp[2] = pp2[2];\n\n    /* pp[5] = pp2[5]; */\n\nreturn;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Help function to interpover: Check if the modpar array in the range\n   of a ring has to be changed */\nstatic int chkchangep(varlel *varele, int fitmode, int parnr, int nur)\n{\n  int i, param;\n  /* int k; */\n\n  /* If fitmode is Golden Section, we check only the actual varele element */\n  if ((fitmode == GOLDEN_SECTION)) {\n    for (i = 0; i < varele -> nelem; ++i) {\n      \n      /* If the ring itself or the ting before has been changed, we return */\n      if (parnr == varele -> elements[i])\n\treturn 1;\n      \n      /* Don't know whether the second logical is a good idea */\n      /* if ((parnr == param+1) && ((param+1)%nur)) */\n      /* \treturn 1; */\n      \n      /* for (j = 0; j < index -> nuel; ++j) { */\n      /* \tif (index -> inpal[j] == varele -> elements[i] || index -> inpah[j] == varele -> elements[i]) { */\n      /* \t  if (parnr == (param = index -> ipa[j])) { */\n      /* \t    return 1; */\n      /* \t  } */\n      /* \t  if ((parnr == param+1) && ((param+1)%nur)) { */\n      /* \t    return 1; */\n      /* \t  } */\n      /* \t} */\n      /* }       */\n    }\n  }\n  \n  /* Fitmode is Metropolis, we check the whole list */\n  else {\n    /* k = 0; */\n    while ((varele)) {\n      /* fprintf(stderr,\"This is the number: %i\\n\", k); */\n\t/* if (k == 2) { */\n\t/*   if (parnr == 131) */\n\t/*     printf(\"Should get there... %i   \", k); */\n\t/* } */\n      if ((varele -> indicator)) {\n\t/* if (k == 2) { */\n\t/*    if (parnr == 131)  */\n\t/*    printf(\"got here!   \");  */\n\t/* } */\n\tfor (i = 0; i < varele -> nelem; ++i) {\n\t  /* If the ring itself or the ting before has been changed, we return */\n\t  if (parnr == (param = varele -> elements[i])) {\n\t    /* if (parnr == 131) */\n\t    /*   printf(\"ding... \"); */\n\t    return 1;\n\t  }\n\t  /* param = varele -> elements[i]; */\n\t  /* if ((parnr == param+1) && ((param+1)%nur)) { */\n\t  /*   if (parnr == 131) */\n\t  /*     printf(\"dong... \"); */\n\t  /*   return 1; */\n\t  /* }\t   */\n\t  /* for (j = 0; j < index -> nuel; ++j) { */\n\t  /*   if (index -> inpal[j] == varele -> elements[i] || index -> inpah[j] == varele -> elements[i]) { */\n\t  /*     if (parnr == (param = index -> ipa[j])) { */\n\t  /* \treturn 1; */\n\t  /*     } */\n\t  /*     if ((parnr == param+1) && ((param+1)%nur)) { */\n\t  /* \treturn 1; */\n\t  /*     } */\n\t  /*   } */\n\t  /* }       */\n\t}\n      }\n      varele = varele -> next;\n      /* ++k; */\n    }\n  }\n  \n  /* The parameter is not in there */\n  return 0;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Takes the parameter list and changes the parameters on the index */\nstatic int changedependent(ringparms *rpm, double *par, decomp_inlist *index, int *chapar)\n{\n  int i,j,k,counts;\n  int nactive; /* number of active points (not indexed) */\n  gsl_interp *gsl_interpv = NULL; /* interpolation function */\n  gsl_interp_accel *gsl_interp_accelv = NULL; /* interpolation function accelerator */\n  double dummy;\n\n  /* fprintf(stderr,\"got here\\n\"); */\n\n  if (!(index -> nuel))\n    return 0;\n  \n  /* index is strictly sorted */\n  counts = 0;\n  \n  /* BUGFIX: this outer loop is required to catch a situation where a parameter is interpolated over but does not belong to a group which is fitted */\n  while (counts < index -> nuel) {\n  /* loop over all parameters except the radii */\n  for (j = NSSDPARAMS; j < NSSDPARAMS+rpm -> ndisks*NDPARAMS; ++j) {\n    nactive = 0;\n\n    /* Check if any of the parameters in that parameter group has changed */\n    for (i = 0; i < rpm -> nur; ++i) {\n      if (chapar[j*rpm->nur+i]) {\n\tbreak;\n      }\n    }\n    \n    /* Only if there was a change, we need to interpolate in that group */\n    if (i < rpm -> nur) {\n\tfor (i = 0; i < rpm -> nur; ++i) {\n\t  rpm -> actindar[i] = j*rpm -> nur + i;\n\t  if (index -> ipa[counts] == rpm -> actindar[i]) {\n\t    rpm -> actarray[i] = 0;\n\t    ++counts;\n\t  }\n\t  else {\n\t    rpm -> actarray[i] = 1;\n\t    ++nactive;\n\t  }\n     }\n      /* fprintf(stderr,\"got here2\\n\"); */\n      \n      /* Now evaluate a few situations */\n      \n      /* If there has been no dependent parameter, we do not need to do anything */\n      if (nactive != rpm -> nur) {\n\t\n\t/* Only one active parameter for all */\n\tif (nactive == 1) {\n\t  for (i = 0; i < rpm -> nur; ++i) {\n\t    par[j*rpm -> nur + i] = par[index -> inpal[counts-1]];\n\t    chapar[j*rpm -> nur + i] = 1;\n\t  }\n\t}\n\t\n\t/* Otherwise interpolation */\n\telse {\n\t  i = 0;\n\t  while (!(rpm -> actarray[i]))\n\t    ++i;\n\t  if (i) {\n\t    rpm -> actarray[0] = 1;\n\t    par[j*rpm -> nur] = par[rpm -> actindar[i]];\n\t    chapar[j*rpm -> nur] = 1;\n\t  }\n\n\t  i = rpm -> nur-1;\n\t  while (!(rpm -> actarray[i]))\n\t    --i;\n\t  if (i != (rpm -> nur-1)) {\n\t    rpm -> actarray[rpm -> nur-1] = 1;\n\t    par[(j+1)*rpm -> nur-1] = par[rpm -> actindar[i]];\n\t    chapar[(j+1)*rpm -> nur-1] = 1;\n\t  }\n\n\t  /* Now fill the arrays to be passed to the interpolator */\n\t  k = 0;\n\t  for (i = 0; i < rpm -> nur; ++i) {\n\t    if (rpm -> actarray[i]) {\n\t      rpm -> radar[k] = par[PRADI*rpm -> nur+i];\n\t      rpm -> interar[k] = par[rpm -> actindar[i]];\n\t      ++k;\n\t    }\n\t  }\n\t  \n\t  /* Interpolate: use the appropriate mode, same as defined in rpm -> smothcar (user input indy) unless number of available points is 2, which entails linear */\n\t  \n\t  /* This we need in any case */\n\t  if (!(gsl_interp_accelv = gsl_interp_accel_alloc()))\n\t    goto error;\n\t  \n\t  /* Linear */\n\t  if ((k < 3) || rpm -> smothindcar[j-NPARAMS+NDPARAMS] == INTERP_LINEAR  ) {\n\t    if (!(gsl_interpv = gsl_interp_alloc (gsl_interp_linear, k)))\n\t      goto error;\n\t  }\n\t  \n\t  /* Spline */\n\t  else if (k < 5 || rpm -> smothindcar[j-NPARAMS+NDPARAMS] == INTERP_CSPLINE) {\n\t    if (!(gsl_interpv = gsl_interp_alloc (gsl_interp_cspline, k)))\n\t      goto error;\n\t  }\n\t  \n\t  /* Akima */\n\t  else if (rpm -> smothindcar[j-NPARAMS+NDPARAMS] == INTERP_AKIMA) {\n\t    if (!(gsl_interpv = gsl_interp_alloc (gsl_interp_akima, k)))\n\t      goto error;\n\t  }\n\t  \n\t  /* Something's wrong */\n\t  else\n\t    goto error;\n\t  \n\t  gsl_interp_init (gsl_interpv, rpm -> radar, rpm -> interar, k);\n\t  \n\t  /* Now interpolate where required */\n\t  \n\t  for (i = 0; i < rpm -> nur; ++i) {\n\t    /* fprintf(stderr,\"got here number: %i %i\\n\", i, rpm -> actarray[i]); */\n\t    if (!(rpm -> actarray[i])) {\n\t      dummy = par[rpm -> actindar[i]];\n\t      par[rpm -> actindar[i]] = gsl_interp_eval(gsl_interpv, rpm -> radar, rpm -> interar, par[PRADI*rpm -> nur+i], gsl_interp_accelv);\n\t      /* If there was a change, we note it down */\n\t      if (par[rpm -> actindar[i]] != dummy) {\n\t\t/* fprintf(stderr,\"Found this to have changed: %i\\n\", i); */\n\t\trpm -> chapar[rpm -> actindar[i]] = 1;\n\t      }\n\t    }\n\t  }\n\t}\n\t\n\tgsl_interp_free(gsl_interpv);\n\tgsl_interp_accel_free(gsl_interp_accelv);\n      }\n      if (counts == index -> nuel)\n\tbreak;\n    }\n  }\n  ++counts;\n  }\n  /*\n    #ifdef OPENMPTIR\n    #pragma omp parallel for schedule(dynamic)\n    #endif\n    for (i = 0; i < index -> nuel; ++i) { */\n  /* First check if the upper and the lower index are identical */\n  /*    if (index -> inpal[i] == index -> inpah[i]) {\n\tif (index -> ipa[i] != index -> inpal[i]) {\n\tpar[index -> ipa[i]] = par[index -> inpal[i]];\n\t}\n\t}\n\telse {\n  */\n  /* And interpolate the parameter */\n  /*      par[index -> ipa[i]] = par[index -> inpal[i]]+(par[PRADI*rpm -> nur+index -> ripa[i]]-par[PRADI*rpm -> nur+index -> rinpal[i]])*(par[index -> inpah[i]]-par[index -> inpal[i]])/(par[PRADI*rpm -> nur+index -> rinpah[i]] - par[PRADI*rpm -> nur+index -> rinpal[i]]);\n\t  }\n\t  } */\n  \n  \n  return index -> nuel;\n  \n error:\n  if (gsl_interpv)\n    gsl_interp_free(gsl_interpv);\n  if (gsl_interp_accelv)\n    gsl_interp_accel_free(gsl_interp_accelv);\n  return -1;\n}\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Core to construct a pointsource cube from a parameter list */\nstatic int galmod(hdrinf *hdr, ringparms *rpm, int fitmode, varlel *varele, decomp_inlist *index, long *fluxpoints, int *allnpoints)\n{ int i;\n  int disk, allnpoint = 0;\n  \n  interpover(rpm, rpm -> radsep, fitmode, varele, index);\n  \n\n  /* Initialise the model array */\n  /*   for (i = 0; i < hdr -> bcsize1*hdr -> bsize2*hdr -> nsubs; ++i) */\n  \n#ifdef OPENMPTIR\n#pragma omp parallel for schedule(dynamic)\n#endif\n  for (i = 0; i < hdr -> nprof*hdr -> nsubs; ++i)\n\thdr -> modelc -> points[i] = 0;\n  \n  /* Initialise the chisquare */\n  /*    hdr -> chi2 = 0; */\n  \n  rpm -> outpoints = 0;\n\n  for (disk = 0; disk < rpm -> ndisks; ++disk) {\n    \n    allnpoints[disk] = 0; \n    fluxpoints[disk] = 0; \n    \n    /* Do all the loops */\n#ifdef OPENMPTIR\n#pragma omp parallel for schedule(dynamic)\n#endif\n    for (i = 0; i < rpm -> nr; ++i) {\n      /*       rpm -> outpoints +=  */\n      srconst(hdr, rpm, i, 0, disk);\n    }\n\n    /* non-parallel bookkeeping */\n    for (i = 0; i < rpm -> nr; ++i) {\n\n      /* now create the clouds and grid them, seems to go well, although there is an additional component there */\n      /*       allnpoints[disk] +=  */\n#ifdef PBCORR\n      (*(rpm -> sd[disk][i].srput))(rpm -> corr_pbcfac, rpm -> sd, rpm -> modpar, rpm -> nr, rpm -> cflux, rpm -> radsep, i, fluxpoints, disk);\n#else\n      (*(rpm -> sd[disk][i].srput))(rpm -> sd, rpm -> modpar, rpm -> nr, rpm -> cflux, rpm -> radsep, i, fluxpoints, disk);\n#endif\n\n      /* this should be correct */\n      rpm -> outpoints += rpm -> sd[disk][i].outpoints;\n\n      /* this might not be correct */\n      allnpoints[disk] += rpm -> sd[disk][i].allnpoints;\n\n      fluxpoints[disk] += rpm -> sd[disk][i].fluxpoints;\n    }\n  }\n\n\n  /* We return the number of clouds */\n  for (disk = 0; disk < rpm -> ndisks; ++disk)\n    allnpoint += allnpoints[disk];\n\n  return allnpoint;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Core to construct a pointsource cube from a parameter list */\nstatic int galmodcool(hdrinf *hdr, ringparms *rpm, int fitmode, varlel *varele, decomp_inlist *index, long *fluxpoints, int *allnpoints)\n{ int i;\n  int disk, allnpoint = 0;\n  int numpixs;\n  \n  interpover(rpm, rpm -> radsep, fitmode, varele, index);\n\n  /* Initialise the model array */\n  /*   for (i = 0; i < hdr -> bcsize1*hdr -> bsize2*hdr -> nsubs; ++i) */\n  numpixs = hdr -> coolcube -> size_x*hdr -> coolcube -> size_y*hdr -> coolcube -> size_v;\n#ifdef OPENMPTIR\n#pragma omp parallel for schedule(dynamic)\n#endif\n  for (i = 0; i < numpixs; ++i)\n\thdr -> coolcube -> points[i] = 0;\n  \n  /* Initialise the chisquare */\n  /*    hdr -> chi2 = 0; */\n  \n  rpm -> outpoints = 0;\n\n  for (disk = 0; disk < rpm -> ndisks; ++disk) {\n    \n    allnpoints[disk] = 0; \n    fluxpoints[disk] = 0; \n\n    /* Make sure that the correct function is linked for srconst */\n    if (rpm -> inf_aziv[disk] -> srshape == srshape_azi_act) {\n      rpm -> inf_aziv[disk] -> srshape = srshape_azi_actcool;\n    }\n    else {\n      rpm -> inf_aziv[disk] -> srshape = srshape_azi_pascool;\n    }\n    /* Link the correct gridpoint function */\n    if (rpm -> inf_sdisv[disk] -> repeater == sdis_repeater_act) {\n      rpm -> inf_sdisv[disk] -> repeater = sdis_repeater_actcool;\n    }\n    else {\n      rpm -> inf_sdisv[disk] -> repeater = sdis_repeater_pascool;\n    }\n\n    for (i = 0; i < rpm -> nr; ++i) {\n      if (rpm -> sd[disk][i].gridpoint == gridpoint_norm) {\n\trpm -> sd[disk][i].gridpoint = gridpoint_normcool;\n      }\n      else {\n\trpm -> sd[disk][i].gridpoint = gridpoint_mixedcool;\n      }\n    }\n        \n    /* Do all the loops */\n#ifdef OPENMPTIR\n#pragma omp parallel for schedule(dynamic)\n#endif\n    for (i = 0; i < rpm -> nr; ++i) {\n      /*       rpm -> outpoints +=  */\n      srconstcool(hdr, rpm, i, 0, disk);\n    }\n\n    /* non-parallel bookkeeping */\n    for (i = 0; i < rpm -> nr; ++i) {\n\n      /* now create the clouds and grid them, seems to go well, although there is an additional component there */\n      /*       allnpoints[disk] +=  */\n#ifdef PBCORR\n      (*(rpm -> sd[disk][i].srput))(rpm -> corr_pbcfac, rpm -> sd, rpm -> modpar, rpm -> nr, rpm -> cflux, rpm -> radsep, i, fluxpoints, disk);\n#else\n      (*(rpm -> sd[disk][i].srput))(rpm -> sd, rpm -> modpar, rpm -> nr, rpm -> cflux, rpm -> radsep, i, fluxpoints, disk);\n#endif\n\n      /* this should be correct */\n      rpm -> outpoints += rpm -> sd[disk][i].outpoints;\n\n      /* this might not be correct */\n      allnpoints[disk] += rpm -> sd[disk][i].allnpoints;\n\n      fluxpoints[disk] += rpm -> sd[disk][i].fluxpoints;\n    }\n\n    /* Make sure that the correct function is linked for srconst at the end*/\n    if (rpm -> inf_aziv[disk] -> srshape == srshape_azi_actcool) {\n      rpm -> inf_aziv[disk] -> srshape = srshape_azi_act;\n    }\n    else {\n      rpm -> inf_aziv[disk] -> srshape = srshape_azi_pas;\n    }\n    \n    if (rpm -> inf_sdisv[disk] -> repeater == sdis_repeater_actcool) {\n      rpm -> inf_sdisv[disk] -> repeater = sdis_repeater_act;\n    }\n    else {\n      rpm -> inf_sdisv[disk] -> repeater = sdis_repeater_pas;\n    }\n        /* Link the correct gridpoint function back */\n    for (i = 0; i < rpm -> nr; ++i) {\n      if (rpm -> sd[disk][i].gridpoint == gridpoint_normcool) {\n\trpm -> sd[disk][i].gridpoint = gridpoint_norm;\n      }\n      else {\n\trpm -> sd[disk][i].gridpoint = gridpoint_mixed;\n      }\n    }\n  }\n\n\n  /* We return the number of clouds */\n  for (disk = 0; disk < rpm -> ndisks; ++disk)\n    allnpoint += allnpoints[disk];\n\n  return allnpoint;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Changes the parameters in par according to parms */\nstatic int chprm_gen(double *parms, varlel *varylist, double *newpar)\n{\n  int i,j = 0;\n  int outofrange = 0;\n  double oldzero = 0.0;\n  \n  /* As long as there is any element of varylist we continue */\n  while ((varylist)) {\n    \n    varylist -> indicator = 0;\n    \n    oldzero = newpar[varylist -> elements[0]];\n    \n    if (!(parms[j] == oldzero)) {\n      \n      varylist -> indicator = 1;\n      /* Every adressant of elements will be changed by the same amount */\n      for (i = 0; i < varylist -> nelem; ++i) {\n\tnewpar[varylist -> elements[i]] = newpar[varylist -> elements[i]]-oldzero+parms[j];\n\t\n\t/* And it will be checked whether on of them is out of range */\n\tif (maths_checkinbetw(varylist -> parmax, varylist -> parmin, newpar[varylist -> elements[i]])) {\t  \n\t  ++outofrange;\n\t}\n      }\n    }\n    ++j;\n    varylist = varylist -> next;\n  }\n  \n  return outofrange;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Writes the information contained in rpm -> par to the output */\nstatic void writeoutput(loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit, char accept, double dof, int modcount, double rchisq)\n{\n  int i;\n/*   char mes[80]; */\n/*   int dev = 0; */\n  if (fit -> fitmode > GOLDEN_SECTION)\n    writeoutarray(log, hdr, rpm, rpm -> par, accept, hdr -> oldchi2, modcount, dof, rchisq);\n  else\n    writeoutarray(log, hdr, rpm, rpm -> oldpar, accept, hdr -> oldchi2, modcount, dof, -1.0);\n\n  if ((log -> tstream)) {\n    fprintf(log -> tstream, \"%7i \",  (int) log -> outarray[(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+LOOPNR_TABNR]); \n    for (i = 0; i < (NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur + NSPARAMS; ++i) {\n      fprintf(log -> tstream, \"%12.9e \", log -> outarray[i]);\n    }\n    fprintf(log -> tstream, \"%.16e \", log -> outarray[(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+NSPARAMS-1+CHISQ_TABNR]);\n    fprintf(log -> tstream, \"%.16e \", log -> outarray[(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+NSPARAMS-1+RCHISQ_TABNR]);\n    fprintf(log -> tstream, \"%9i\\n\", (int) log -> outarray[(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+NSPARAMS-1+ACCEPT_TABNR]);\n  }\n  \n  if (!(log -> logpres)) {\n    ftstab_appendrow_(log -> outarray+(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+NSPARAMS-1+CHISQ_TABNR);\n  }\n  tir_put_register(log, rpm, log -> outarray);\n\n  /* Comment on it */\n/*   dev = 0; */\n/*   if (fit -> fitmode == METROPOLIS) */\n/*     sprintf(mes, \"Model %i, chisquare %E, relative probability: %E\", (int) log -> outarray[(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+LOOPNR_TABNR], hdr -> chi2, proba); */\n/*   else if (fit -> fitmode == GOLDEN_SECTION) */\n/*     sprintf(mes, \"Loop %i, %i iterations since start, chisquare %E\", (int) log -> outarray[(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+LOOPNR_TABNR],  (int) proba, hdr -> oldchi2); */\n/*   anyout_tir(&dev, mes); */\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Writes the information contained in rpm -> par to the output */\nstatic void writeoutputread(loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit, char accept, double dof, int modcount, double rchisq)\n{\n  int i;\n/*   char mes[80]; */\n/*   int dev = 0; */\n  if (fit -> fitmode > GOLDEN_SECTION)\n    writeoutarray(log, hdr, rpm, rpm -> par, accept, hdr -> oldchi2, modcount, dof, rchisq);\n  else\n    writeoutarray(log, hdr, rpm, rpm -> oldpar, accept, hdr -> oldchi2, modcount, dof, -1.0);\n\n  if ((log -> tstream)) {\n    fprintf(log -> tstream, \"%7i \",  (int) log -> outarray[(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+LOOPNR_TABNR]); \n    for (i = 0; i < (NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur + NSPARAMS; ++i) {\n      fprintf(log -> tstream, \"%12.9e \", log -> outarray[i]);\n    }\n    fprintf(log -> tstream, \"%.16e \", log -> outarray[(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+NSPARAMS-1+CHISQ_TABNR]);\n    fprintf(log -> tstream, \"%.16e \", log -> outarray[(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+NSPARAMS-1+RCHISQ_TABNR]);\n    fprintf(log -> tstream, \"%9i\\n\", (int) log -> outarray[(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+NSPARAMS-1+ACCEPT_TABNR]);\n  }\n  \n  tir_put_register(log, rpm, log -> outarray);\n\n  /* Comment on it */\n/*   dev = 0; */\n/*   if (fit -> fitmode == METROPOLIS) */\n/*     sprintf(mes, \"Model %i, chisquare %E, relative probability: %E\", (int) log -> outarray[(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+LOOPNR_TABNR], hdr -> chi2, proba); */\n/*   else if (fit -> fitmode == GOLDEN_SECTION) */\n/*     sprintf(mes, \"Loop %i, %i iterations since start, chisquare %E\", (int) log -> outarray[(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+LOOPNR_TABNR],  (int) proba, hdr -> oldchi2); */\n/*   anyout_tir(&dev, mes); */\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Writes the information contained in rpm -> par to the output array of rpm */\nvoid writeoutarray(loginf *log, hdrinf *hdr, ringparms *rpm, double *par, char accept, double chisquare, int modcount, double dof, double chisquare_red)\n{\n  int i;\n  double globin[3];\n  double globout[3];\n  int disk;\n  int condisp, pcondisp;\n\n  /************/\n  /************/\n  /* int obsint = 0; */\n  /* char obsmes[80]; */\n  /************/\n\n  /* Fill the output array */\n  for (i = 0; i < rpm -> nur; ++i) {\n    log -> outarray[PRADI*rpm -> nur+i] = dinterntoparam(par[PRADI*rpm -> nur+i], RADI, hdr, rpm -> ndisks);\n    for (disk = 0; disk < rpm -> ndisks; ++disk) {\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PVROT)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PVROT)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ VROT, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PVRAD)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PVRAD)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ VRAD, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PVVER)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PVVER)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ VVER, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PDVRO)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PDVRO)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ DVRO, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PDVRA)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PDVRA)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ DVRA, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PDVVE)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PDVVE)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ DVVE, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PZDRO)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PZDRO)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ ZDRO, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PZDRA)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PZDRA)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ ZDRA, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PZDVE)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PZDVE)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ ZDVE, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PZ0  )*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PZ0  )*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ Z0  , hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PSBR )*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PSBR )*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ SBR , hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PSM1A)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PSM1A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ SM1A, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PSM1P)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PSM1P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ SM1P, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PSM2A)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PSM2A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ SM2A, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PSM2P)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PSM2P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ SM2P, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PSM3A)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PSM3A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ SM3A, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PSM3P)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PSM3P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ SM3P, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PSM4A)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PSM4A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ SM4A, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PSM4P)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PSM4P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ SM4P, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PGA1A)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PGA1A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ GA1A, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PGA1P)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PGA1P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ GA1P, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PGA1D)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PGA1D)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ GA1D, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PGA2A)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PGA2A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ GA2A, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PGA2P)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PGA2P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ GA2P, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PGA2D)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PGA2D)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ GA2D, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PGA3A)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PGA3A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ GA3A, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PGA3P)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PGA3P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ GA3P, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PGA3D)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PGA3D)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ GA3D, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PGA4A)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PGA4A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ GA4A, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PGA4P)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PGA4P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ GA4P, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PGA4D)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PGA4D)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ GA4D, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PAZ1P)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PAZ1P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ AZ1P, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PAZ1W)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PAZ1W)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ AZ1W, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PAZ2P)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PAZ2P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ AZ2P, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PAZ2W)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PAZ2W)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ AZ2W, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PINCL)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PINCL)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ INCL, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PPA  )*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PPA  )*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ PA  , hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PSDIS)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PSDIS)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ SDIS, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PCLNR)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PCLNR)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ CLNR, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PVM0A)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PVM0A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ VM0A, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PVM1A)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PVM1A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ VM1A, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PVM1P)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PVM1P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ VM1P, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PVM2A)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PVM2A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ VM2A, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PVM2P)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PVM2P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ VM2P, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PVM3A)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PVM3A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ VM3A, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PVM3P)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PVM3P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ VM3P, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PVM4A)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PVM4A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ VM4A, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PVM4P)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PVM4P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ VM4P, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PRA1A)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PRA1A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ RA1A, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PRA1P)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PRA1P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ RA1P, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PRA2A)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PRA2A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ RA2A, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PRA2P)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PRA2P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ RA2P, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PRA3A)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PRA3A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ RA3A, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PRA3P)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PRA3P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ RA3P, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PRA4A)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PRA4A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ RA4A, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PRA4P)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PRA4P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ RA4P, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PRO1A)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PRO1A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ RO1A, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PRO1P)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PRO1P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ RO1P, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PRO2A)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PRO2A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ RO2A, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PRO2P)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PRO2P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ RO2P, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PRO3A)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PRO3A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ RO3A, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PRO3P)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PRO3P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ RO3P, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PRO4A)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PRO4A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ RO4A, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PRO4P)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PRO4P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ RO4P, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PWM0A)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PWM0A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ WM0A, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PWM1A)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PWM1A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ WM1A, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PWM1P)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PWM1P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ WM1P, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PWM2A)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PWM2A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ WM2A, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PWM2P)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PWM2P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ WM2P, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PWM3A)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PWM3A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ WM3A, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PWM3P)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PWM3P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ WM3P, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PWM4A)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PWM4A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ WM4A, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PWM4P)*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PWM4P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ WM4P, hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PLS0 )*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PLS0 )*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ LS0 , hdr, rpm -> ndisks);\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PLC0 )*rpm -> nur+i] = dinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PLC0 )*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ LC0 , hdr, rpm -> ndisks);\n\n      /* Now, we have to convert the triplets into internal units */\n      globin[0] = par[(PRPARAMS+disk*NDPARAMS+PXPOS)*rpm -> nur+i];\n      globin[1] = par[(PRPARAMS+disk*NDPARAMS+PYPOS)*rpm -> nur+i];\n      globin[2] = par[(PRPARAMS+disk*NDPARAMS+PVSYS)*rpm -> nur+i];\n\n      interntoglob(globin, globout, hdr);\n   \n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PXPOS)*rpm -> nur+i] = globout[0];\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PYPOS)*rpm -> nur+i] = globout[1];\n      log -> outarray[(PRPARAMS+disk*NDPARAMS+PVSYS)*rpm -> nur+i] = globout[2];\n    }\n  }\n  pcondisp = (NPARAMS + (rpm -> ndisks - 1)*NDPARAMS);\n  condisp = pcondisp +1;\n\n  log -> outarray[pcondisp*rpm -> nur] = dinterntoparam(par[pcondisp*rpm -> nur], condisp, hdr, rpm -> ndisks);\n\n  /* Chisquare */\n  log -> outarray[(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+NSPARAMS-1+CHISQ_TABNR] = chisquare;\n  if (chisquare_red >= 0.0)\n    log -> outarray[(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+NSPARAMS-1+RCHISQ_TABNR] = chisquare_red;\n  else\n    log -> outarray[(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+NSPARAMS-1+RCHISQ_TABNR] = chisquare/dof;\n\n  /* Acceptance */\n  log -> outarray[(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+NSPARAMS-1+ACCEPT_TABNR] = (double) accept;\n\n  /* model number */\n  log -> outarray[(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+NSPARAMS-1+LOOPNR_TABNR] = (double) modcount;\n\n  return;\n}\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Writes the information contained in rpm -> par to the output array of rpm */\nstatic void writeoutarrayerr(hdrinf *hdr, ringparms *rpm, double *par, double *errors, char accept, double chisquare, int modcount, double dof)\n{\n  int i;\n  int disk;\n  /************/\n  /************/\n  /* int obsint = 0; */\n  /* char obsmes[80]; */\n  /************/\n  int condisp, pcondisp;\n\n\n  for (i = 0; i < rpm -> nur; ++i) {\n    errors[PRADI*rpm -> nur+i] = ddinterntoparam(par[PRADI*rpm -> nur+i], RADI, hdr, rpm -> ndisks);\n    for (disk = 0; disk < rpm -> ndisks; ++disk) {\n      errors[(PRPARAMS+disk*NDPARAMS+PVROT)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PVROT)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ VROT, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PVRAD)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PVRAD)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ VRAD, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PVVER)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PVVER)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ VVER, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PDVRO)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PDVRO)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ DVRO, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PDVRA)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PDVRA)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ DVRA, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PDVVE)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PDVVE)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ DVVE, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PZDRO)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PZDRO)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ ZDRO, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PZDRA)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PZDRA)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ ZDRA, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PZDVE)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PZDVE)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ ZDVE, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PZ0  )*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PZ0  )*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ Z0  , hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PSBR )*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PSBR )*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ SBR , hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PSM1A)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PSM1A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ SM1A, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PSM1P)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PSM1P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ SM1P, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PSM2A)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PSM2A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ SM2A, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PSM2P)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PSM2P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ SM2P, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PSM3A)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PSM3A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ SM3A, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PSM3P)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PSM3P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ SM3P, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PSM4A)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PSM4A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ SM4A, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PSM4P)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PSM4P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ SM4P, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PGA1A)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PGA1A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ GA1A, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PGA1P)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PGA1P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ GA1P, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PGA1D)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PGA1D)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ GA1D, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PGA2A)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PGA2A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ GA2A, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PGA2P)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PGA2P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ GA2P, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PGA2D)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PGA2D)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ GA2D, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PGA3A)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PGA3A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ GA3A, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PGA3P)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PGA3P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ GA3P, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PGA3D)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PGA3D)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ GA3D, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PGA4A)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PGA4A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ GA4A, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PGA4P)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PGA4P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ GA4P, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PGA4D)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PGA4D)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ GA4D, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PAZ1P)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PAZ1P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ AZ1P, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PAZ1W)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PAZ1W)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ AZ1W, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PAZ2P)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PAZ2P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ AZ2P, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PAZ2W)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PAZ2W)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ AZ2W, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PINCL)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PINCL)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ INCL, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PPA  )*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PPA  )*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ PA  , hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PXPOS)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PXPOS)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ XPOS, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PYPOS)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PYPOS)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ YPOS, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PVSYS)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PVSYS)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ VSYS, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PVM0A)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PVM0A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ VM0A, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PVM1A)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PVM1A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ VM1A, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PVM1P)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PVM1P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ VM1P, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PVM2A)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PVM2A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ VM2A, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PVM2P)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PVM2P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ VM2P, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PVM3A)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PVM3A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ VM3A, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PVM3P)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PVM3P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ VM3P, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PVM4A)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PVM4A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ VM4A, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PVM4P)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PVM4P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ VM4P, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PRA1A)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PRA1A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ RA1A, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PRA1P)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PRA1P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ RA1P, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PRA2A)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PRA2A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ RA2A, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PRA2P)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PRA2P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ RA2P, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PRA3A)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PRA3A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ RA3A, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PRA3P)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PRA3P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ RA3P, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PRA4A)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PRA4A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ RA4A, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PRA4P)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PRA4P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ RA4P, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PRO1A)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PRO1A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ RO1A, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PRO1P)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PRO1P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ RO1P, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PRO2A)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PRO2A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ RO2A, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PRO2P)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PRO2P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ RO2P, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PRO3A)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PRO3A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ RO3A, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PRO3P)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PRO3P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ RO3P, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PRO4A)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PRO4A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ RO4A, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PRO4P)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PRO4P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ RO4P, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PWM0A)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PWM0A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ WM0A, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PWM1A)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PWM1A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ WM1A, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PWM1P)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PWM1P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ WM1P, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PWM2A)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PWM2A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ WM2A, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PWM2P)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PWM2P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ WM2P, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PWM3A)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PWM3A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ WM3A, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PWM3P)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PWM3P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ WM3P, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PWM4A)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PWM4A)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ WM4A, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PWM4P)*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PWM4P)*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ WM4P, hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PLS0 )*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PLS0 )*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ LS0 , hdr, rpm -> ndisks);\n      errors[(PRPARAMS+disk*NDPARAMS+PLC0 )*rpm -> nur+i] = ddinterntoparam(par[(PRPARAMS+disk*NDPARAMS+PLC0 )*rpm -> nur+i], PRPARAMS+disk*NDPARAMS+ LC0 , hdr, rpm -> ndisks);\n    }\n  }\n\n  pcondisp = (NPARAMS + (rpm -> ndisks - 1)*NDPARAMS);\n  condisp = pcondisp +1;\n  errors[(pcondisp)*rpm -> nur] = ddinterntoparam(par[(pcondisp)*rpm -> nur], condisp, hdr, rpm -> ndisks);\n  \n  /* Chisquare */\n  errors[(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+NSPARAMS-1+CHISQ_TABNR] = chisquare;\n\n  errors[(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+NSPARAMS-1+RCHISQ_TABNR] = chisquare/dof;\n  \n  /* Acceptance */\n  errors[(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+NSPARAMS-1+ACCEPT_TABNR] = (double) accept;\n\n  /* model number */\n  errors[(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+NSPARAMS-1+LOOPNR_TABNR] = (double) modcount;\n\n  return;\n}\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Delivers a random variable according to a profile identifyer */\nstatic float zprof(int option, maths_rstrf *permrandstr, float *y2)\n{\n\n  /* Note: y1 is basically uninitialised for case 1 UNLESS it is initialised by calling zprof(6,randstr) before. This is (hopefully done throughout the program) */\n\n  float  x1, x2, w;\n  static float y1 = 0.0;\n\n/*   static float y2; */\n\n  switch (option) {\n  case 1:\n    if (*y2 < -1000.0) { \n      \n      /* According to http://www.taygeta.com/random/gaussian.html a gaussian distribution with sigma = 1 and mean 0, unfortunately two independent numbers are generated */\n      do {\n\tx1 = 2.0*maths_rndmf(permrandstr)-1.0;\n\tx2 = 2.0*maths_rndmf(permrandstr)-1.0;\n\tw = x1*x1+x2*x2;\n    } while (w >= 1.0);\n      \n      w = sqrtf((-2.0*logf(w))/w);\n      y1 = x1*w;\n      *y2 = x2*w;\n    } \n     else { \n       y1 = *y2;\n       *y2 = -1024.0;\n     } \n    break;\n\n    /* Sech2 */\n  case 2:\n    /* sech2: 0.5*sech^2(x) or  1/(2*Z0)*sech^2(z/Z0) (normalised to 1) */\n    while (!((x1 = 2.0*maths_rndmf(permrandstr)-1.0)-1.0))\n      ;\n    /* Note that this is the same as 0.5 log(p/(1-p)) if p varies from 0 to 1, so this is correct */\n    y1 = atanhf(x1);\n    break;\n    \n    /* exponential exp(-|x|)/2 or with Z0 exp(-|x/Z0|)/(2*Z0) (normalised to 1) */\n  case 3:\n    while (!((x1 = 2.0*maths_rndmf(permrandstr)-1.0)))\n      ;\n    if (x1 > 0.0) \n      y1 = -logf(x1);\n    else if (x1 < 0.0) \n      y1 = logf(-x1);\n    break;\n    \n  case 4:\n    /* Lorentzian layer: (1/pi)/(x^2+1) or with Z0: Z0/(pi*(x^2+Z0^2)) (normalised to 1) */ \n    while (!((x1 = 2.0*maths_rndmf(permrandstr)-1.0)-1.0))\n      ;\n\n    /* this is correct */\n    y1 = tanf(PIHALF*x1);\n    break;\n    \n  case 6:\n    *y2 = -1024.0;\n    y1 = 0.0;\n    break;\n    \n  default:\n    /* Uniform layer 1/2 for -1<x<1 0 otherwise or with Z0: 1/(2*Z0) for -Z0<z<Z0 0 otherwise */\n    y1 = 2.0*maths_rndmf(permrandstr)-1.0;\n    break;\n  }\n  \n  return y1;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Initializes the standard header context table */\nstatic int hdl_init(int ndisks)\n{\n  int disk;\n  char placer[9];\n\n\n  if (ftstab_hdladditem(\"RADI\", \"ANGLE\"     , \"arcsec\"            , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"VROT\", \"VELO\"      , \"km/s\"              , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"VRAD\", \"VELO\"      , \"km/s\"              , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"VVER\", \"VELO\"      , \"km/s\"              , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"DVRO\", \"VELO/ANGLE\", \"km/s/arcsec\"       , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"DVRA\", \"VELO/ANGLE\", \"km/s/arcsec\"       , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"DVVE\", \"VELO/ANGLE\", \"km/s/arcsec\"       , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"ZDRO\", \"ANGLE\"     , \"arcsec\"            , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"ZDRA\", \"ANGLE\"     , \"arcsec\"            , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"ZDVE\", \"ANGLE\"     , \"arcsec\"            , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"Z0\"  , \"ANGLE\"     , \"arcsec\"            , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"SBR\" , \"FLUX\"      , \"Jy*m/(s*arcsec**2)\", 0.0, 1000.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"SM1A\", \"FLUX\"      , \"Jy*m/(s*arcsec**2)\", 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"SM1P\", \"ANGLE\"     , \"deg\"               , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"SM2A\", \"FLUX\"      , \"Jy*m/(s*arcsec**2)\", 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"SM2P\", \"ANGLE\"     , \"deg\"               , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"SM3A\", \"FLUX\"      , \"Jy*m/(s*arcsec**2)\", 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"SM3P\", \"ANGLE\"     , \"deg\"               , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"SM4A\", \"FLUX\"      , \"Jy*m/(s*arcsec**2)\", 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"SM4P\", \"ANGLE\"     , \"deg\"               , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"GA1A\", \"FLUX\"      , \"Jy*m/(s*arcsec**2)\", 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"GA1P\", \"ANGLE\"     , \"deg\"               , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"GA1D\", \"ANGLE\"     , \"arcsec\"            , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"GA2A\", \"FLUX\"      , \"Jy*m/(s*arcsec**2)\", 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"GA2P\", \"ANGLE\"     , \"deg\"               , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"GA2D\", \"ANGLE\"     , \"arcsec\"            , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"GA3A\", \"FLUX\"      , \"Jy*m/(s*arcsec**2)\", 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"GA3P\", \"ANGLE\"     , \"deg\"               , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"GA3D\", \"ANGLE\"     , \"arcsec\"            , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"GA4A\", \"FLUX\"      , \"Jy*m/(s*arcsec**2)\", 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"GA4P\", \"ANGLE\"     , \"deg\"               , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"GA4D\", \"ANGLE\"     , \"arcsec\"            , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"AZ1P\", \"ANGLE\"     , \"deg\"               , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"AZ1W\", \"ANGLE\"     , \"deg\"               , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"AZ2P\", \"ANGLE\"     , \"deg\"               , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"AZ2W\", \"ANGLE\"     , \"deg\"               , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"INCL\", \"ANGLE\"     , \"deg\"               , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"PA\"  , \"ANGLE\"     , \"deg\"               , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"XPOS\", \"ANGLE\"     , \"deg\"               , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"YPOS\", \"ANGLE\"     , \"deg\"               , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"VSYS\", \"VELO\"      , \"km/s\"              , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"SDIS\", \"VELO\"      , \"km/s\"              , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"CLNR\", \"NATURAL\"   , \" \"                 , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"VM0A\", \"VELO\"      , \"km/s\"              , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"VM1A\", \"VELO\"      , \"km/s\"              , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"VM1P\", \"ANGLE\"     , \"deg\"               , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"VM2A\", \"VELO\"      , \"km/s\"              , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"VM2P\", \"ANGLE\"     , \"deg\"               , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"VM3A\", \"VELO\"      , \"km/s\"              , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"VM3P\", \"ANGLE\"     , \"deg\"               , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"VM4A\", \"VELO\"      , \"km/s\"              , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"VM4P\", \"ANGLE\"     , \"deg\"               , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"WM0A\", \"ANGLE\"     , \"arcsec\"            , 0.0,    1.0) < 0)    { return 0;}       \n  if (ftstab_hdladditem(\"WM1A\", \"ANGLE\"     , \"arcsec\"            , 0.0,    1.0) < 0)    { return 0;}       \n  if (ftstab_hdladditem(\"WM1P\", \"ANGLE\"     , \"deg\"               , 0.0,    1.0) < 0)    { return 0;}       \n  if (ftstab_hdladditem(\"WM2A\", \"ANGLE\"     , \"arcsec\"            , 0.0,    1.0) < 0)    { return 0;}       \n  if (ftstab_hdladditem(\"WM2P\", \"ANGLE\"     , \"deg\"               , 0.0,    1.0) < 0)    { return 0;}       \n  if (ftstab_hdladditem(\"WM3A\", \"ANGLE\"     , \"arcsec\"            , 0.0,    1.0) < 0)    { return 0;}       \n  if (ftstab_hdladditem(\"WM3P\", \"ANGLE\"     , \"deg\"               , 0.0,    1.0) < 0)    { return 0;}       \n  if (ftstab_hdladditem(\"WM4A\", \"ANGLE\"     , \"arcsec\"            , 0.0,    1.0) < 0)    { return 0;}       \n  if (ftstab_hdladditem(\"WM4P\", \"ANGLE\"     , \"deg\"               , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"LS0\" , \"ANGLE\"     , \"arcsec\"            , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"LC0\" , \"ANGLE\"     , \"arcsec\"            , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"RO1A\", \"VELO\"      , \"km/s\"              , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"RO1P\", \"ANGLE\"     , \"deg\"               , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"RO2A\", \"VELO\"      , \"km/s\"              , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"RO2P\", \"ANGLE\"     , \"deg\"               , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"RO3A\", \"VELO\"      , \"km/s\"              , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"RO3P\", \"ANGLE\"     , \"deg\"               , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"RO4A\", \"VELO\"      , \"km/s\"              , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"RO4P\", \"ANGLE\"     , \"deg\"               , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"RA1A\", \"VELO\"      , \"km/s\"              , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"RA1P\", \"ANGLE\"     , \"deg\"               , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"RA2A\", \"VELO\"      , \"km/s\"              , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"RA2P\", \"ANGLE\"     , \"deg\"               , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"RA3A\", \"VELO\"      , \"km/s\"              , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"RA3P\", \"ANGLE\"     , \"deg\"               , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"RA4A\", \"VELO\"      , \"km/s\"              , 0.0,    1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"RA4P\", \"ANGLE\"     , \"deg\"               , 0.0,    1.0) < 0)    { return 0;}\n\n  for (disk = 1; disk < ndisks; ++disk) {\n\n    sprintf(placer, \"VROT_%i\", disk+1);       if (ftstab_hdladditem(placer, \"VELO\",       \"km/s\",               0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"VRAD_%i\", disk+1);       if (ftstab_hdladditem(placer, \"VELO\",       \"km/s\",               0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"VVER_%i\", disk+1);       if (ftstab_hdladditem(placer, \"VELO\",       \"km/s\",               0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"DVRO_%i\", disk+1);       if (ftstab_hdladditem(placer, \"VELO/ANGLE\", \"km/s/arcsec\",        0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"DVRA_%i\", disk+1);       if (ftstab_hdladditem(placer, \"VELO/ANGLE\", \"km/s/arcsec\",        0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"DVVE_%i\", disk+1);       if (ftstab_hdladditem(placer, \"VELO/ANGLE\", \"km/s/arcsec\",        0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"ZDRO_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",       \"arcsec\",            0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"ZDRA_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",       \"arcsec\",            0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"ZDVE_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",       \"arcsec\",            0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"Z0_%i\"  , disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"arcsec\",             0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"SBR_%i\" , disk+1);       if (ftstab_hdladditem(placer, \"FLUX\",       \"Jy*m/(s*arcsec**2)\", 0.0, 1000.0) < 0)         { return 0;}\n    sprintf(placer, \"SM1A_%i\", disk+1);       if (ftstab_hdladditem(placer, \"FLUX\",       \"Jy*m/(s*arcsec**2)\", 0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"SM1P_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"deg\",                0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"SM2A_%i\", disk+1);       if (ftstab_hdladditem(placer, \"FLUX\",       \"Jy*m/(s*arcsec**2)\", 0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"SM2P_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"deg\",                0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"SM3A_%i\", disk+1);       if (ftstab_hdladditem(placer, \"FLUX\",       \"Jy*m/(s*arcsec**2)\", 0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"SM3P_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"deg\",                0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"SM4A_%i\", disk+1);       if (ftstab_hdladditem(placer, \"FLUX\",       \"Jy*m/(s*arcsec**2)\", 0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"SM4P_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"deg\",                0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"GA1A_%i\", disk+1);       if (ftstab_hdladditem(placer, \"FLUX\",       \"Jy*m/(s*arcsec**2)\", 0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"GA1P_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"deg\",                0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"GA1D_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"arcsec\",             0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"GA2A_%i\", disk+1);       if (ftstab_hdladditem(placer, \"FLUX\",       \"Jy*m/(s*arcsec**2)\", 0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"GA2P_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"deg\",                0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"GA2D_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"arcsec\",             0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"GA3A_%i\", disk+1);       if (ftstab_hdladditem(placer, \"FLUX\",       \"Jy*m/(s*arcsec**2)\", 0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"GA3P_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"deg\",                0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"GA3D_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"arcsec\",             0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"GA4A_%i\", disk+1);       if (ftstab_hdladditem(placer, \"FLUX\",       \"Jy*m/(s*arcsec**2)\", 0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"GA4P_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"deg\",                0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"GA4D_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"arcsec\",             0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"AZ1P_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"deg\",                0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"AZ1W_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"deg\",                0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"AZ2P_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"deg\",                0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"AZ2W_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"deg\",                0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"INCL_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"deg\",                0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"PA_%i\"  , disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"deg\",                0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"XPOS_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"deg\",                0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"YPOS_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"deg\",                0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"VSYS_%i\", disk+1);       if (ftstab_hdladditem(placer, \"VELO\",       \"km/s\",               0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"SDIS_%i\", disk+1);       if (ftstab_hdladditem(placer, \"VELO\",       \"km/s\",               0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"CLNR_%i\", disk+1);       if (ftstab_hdladditem(placer, \"NATURAL\",    \" \",                  0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"VM0A_%i\", disk+1);       if (ftstab_hdladditem(placer, \"VELO\",       \"km/s\",               0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"VM1A_%i\", disk+1);       if (ftstab_hdladditem(placer, \"VELO\",       \"km/s\",               0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"VM1P_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"deg\",                0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"VM2A_%i\", disk+1);       if (ftstab_hdladditem(placer, \"VELO\",       \"km/s\",               0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"VM2P_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"deg\",                0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"VM3A_%i\", disk+1);       if (ftstab_hdladditem(placer, \"VELO\",       \"km/s\",               0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"VM3P_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"deg\",                0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"VM4A_%i\", disk+1);       if (ftstab_hdladditem(placer, \"VELO\",       \"km/s\",               0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"VM4P_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"deg\",                0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"WM0A_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"arcsec\",             0.0,    1.0) < 0)         { return 0;}       \n    sprintf(placer, \"WM1A_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"arcsec\",             0.0,    1.0) < 0)         { return 0;}       \n    sprintf(placer, \"WM1P_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"deg\",                0.0,    1.0) < 0)         { return 0;}       \n    sprintf(placer, \"WM2A_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"arcsec\",             0.0,    1.0) < 0)         { return 0;}       \n    sprintf(placer, \"WM2P_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"deg\",                0.0,    1.0) < 0)         { return 0;}       \n    sprintf(placer, \"WM3A_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"arcsec\",             0.0,    1.0) < 0)         { return 0;}       \n    sprintf(placer, \"WM3P_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"deg\",                0.0,    1.0) < 0)         { return 0;}       \n    sprintf(placer, \"WM4A_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"arcsec\",             0.0,    1.0) < 0)         { return 0;}       \n    sprintf(placer, \"WM4P_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"deg\",                0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"LS0_%i\" , disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"arcsec\",             0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"LC0_%i\" , disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"arcsec\",             0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"RO1A_%i\", disk+1);       if (ftstab_hdladditem(placer, \"VELO\",       \"km/s\",               0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"RO1P_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"deg\",                0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"RO2A_%i\", disk+1);       if (ftstab_hdladditem(placer, \"VELO\",       \"km/s\",               0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"RO2P_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"deg\",                0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"RO3A_%i\", disk+1);       if (ftstab_hdladditem(placer, \"VELO\",       \"km/s\",               0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"RO3P_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"deg\",                0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"RO4A_%i\", disk+1);       if (ftstab_hdladditem(placer, \"VELO\",       \"km/s\",               0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"RO4P_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"deg\",                0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"RA1A_%i\", disk+1);       if (ftstab_hdladditem(placer, \"VELO\",       \"km/s\",               0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"RA1P_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"deg\",                0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"RA2A_%i\", disk+1);       if (ftstab_hdladditem(placer, \"VELO\",       \"km/s\",               0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"RA2P_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"deg\",                0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"RA3A_%i\", disk+1);       if (ftstab_hdladditem(placer, \"VELO\",       \"km/s\",               0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"RA3P_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"deg\",                0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"RA4A_%i\", disk+1);       if (ftstab_hdladditem(placer, \"VELO\",       \"km/s\",               0.0,    1.0) < 0)         { return 0;}\n    sprintf(placer, \"RA4P_%i\", disk+1);       if (ftstab_hdladditem(placer, \"ANGLE\",      \"deg\",                0.0,    1.0) < 0)         { return 0;}\n  }      \n\n  if (ftstab_hdladditem(\"CONDISP\" , \"VELO\"   , \"km/s\"        , 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"BMAJ\"    , \"ANGLE\"  , \"arcsec\"      , 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"BMIN\"    , \"ANGLE\"  , \"arcsec\"      , 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"BPA\"     , \"ANGLE\"  , \"deg\"         , 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"RMS\"     , \"FLUX\"   , \"Jy*km/s*beam\", 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"NUR\"     , \"NATURAL\", \" \"           , 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"RADSEP\"  , \"ANGLE\"  , \"arcsec\"      , 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"WEIGHT\"  , \"NATURAL\", \" \"           , 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"MODE\"    , \"NATURAL\", \" \"           , 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"ISEED\"  , \"NATURAL\", \" \"           , 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"LOOPS\"   , \"NATURAL\", \" \"           , 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"NCORES\"  , \"NATURAL\", \" \"           , 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"ISEED_2\" , \"NATURAL\", \" \"           , 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"ANSTART\" , \"NATURAL\", \" \"           , 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"ANEND\"   , \"NATURAL\", \" \"           , 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"ANSTEPS\" , \"NATURAL\", \" \"           , 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"INIMODE\" , \"NATURAL\", \" \"           , 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"FITMODE\" , \"NATURAL\", \" \"           , 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"OUTCUBUP\", \"NATURAL\", \" \"           , 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"DISTANCE\", \"NATURAL\", \" \"           , 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"PENALTY\" , \"NATURAL\", \" \"           , 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"RFREQ\"   , \"NATURAL\", \" \"           , 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"ITOU\"    , \"NATURAL\", \" \"           , 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"MAXITER\" , \"NATURAL\", \" \"           , 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"CALLITE\" , \"NATURAL\", \" \"           , 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"SIZE\"    , \"NATURAL\", \" \"           , 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"PSSE\"    , \"NATURAL\", \" \"           , 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"PSNP\"    , \"NATURAL\", \" \"           , 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"PSCO\"    , \"NATURAL\", \" \"           , 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"PSSO\"    , \"NATURAL\", \" \"           , 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"PSMV\"    , \"NATURAL\", \" \"           , 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"PSNF\"    , \"NATURAL\", \" \"           , 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"PSII\"    , \"NATURAL\", \" \"           , 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"PSFI\"    , \"NATURAL\", \" \"           , 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"PSID\"    , \"NATURAL\", \" \"           , 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"PSDD\"    , \"NATURAL\", \" \"           , 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"NUR\"     , \"NATURAL\", \" \"           , 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"INTY\"    , \"NATURAL\", \" \"           , 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"INDINTY\" , \"NATURAL\", \" \"           , 0.0, 1.0) < 0)    { return 0;}\n  for (disk = 1; disk < ndisks; ++disk) {\n    /* NOTE: this used to be sprintf(placer, \"LTYPE_%i\" , disk+1); */\n    sprintf(placer, \"LTYPE_%i\" , disk+1);\n    if (ftstab_hdladditem(placer, \"NATURAL\", \" \", 0.0, 1.0) < 0)\n      { return 0;}\n  }\n  if (ftstab_hdladditem(\"CFLUX\", \"FLUX\", \"Jy*km/s\", 0.0, 1.0) < 0)    { return 0;}\n  for (disk = 1; disk < ndisks; ++disk) {\n    /* NOTE: this used to be sprintf(placer, \"CFLUX_%i\" , disk+1); */\n    sprintf(placer, \"CFLUX_%i\" , disk+1);\n    if (ftstab_hdladditem(placer, \"FLUX\", \"Jy*km/s\", 0.0, 1.0) < 0)\n      { return 0;}\n  }\n\n  /* Second hdu */\n  if (ftstab_hdladditem(\"PARMAX\"  , \"NATURAL\", \" \", 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"PARMIN\"  , \"NATURAL\", \" \", 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"MODERATE\", \"NATURAL\", \" \", 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"DELSTART\", \"NATURAL\", \" \", 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"DELEND\"  , \"NATURAL\", \" \", 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"ITESTART\", \"NATURAL\", \" \", 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"ITEEND\"  , \"NATURAL\", \" \", 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"SATDELT\" , \"NATURAL\", \" \", 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"MINDELTA\", \"NATURAL\", \" \", 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"ELEMENTS\", \"NATURAL\", \" \", 0.0, 1.0) < 0)    { return 0;}\n\n  /* Third hdu */\n  if (ftstab_hdladditem(\"CHISQ\"   , \"NATURAL\", \" \", 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"RCHISQ\"  , \"NATURAL\", \" \", 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"LOOPNR\"  , \"NATURAL\", \" \", 0.0, 1.0) < 0)    { return 0;}\n  if (ftstab_hdladditem(\"ACCEPT\"  , \"NATURAL\", \" \", 0.0, 1.0) < 0)    { return 0;}\n  return 1;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Opens if necessary creat the third hdu */\nstatic int open_hdu_3(loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit)\n{\n  if (fit -> fitmode == GOLDEN_SECTION) {\n    /* Now we get the number of loops */\n      fit -> loopnr = 0;\n  }\n  else if (fit -> fitmode > GOLDEN_SECTION) {\n      fit -> recnr = 0;\n      fit -> loopnr = 1;\n  }\n  else\n    goto error;\n\n  return 0;\n\n error:\n  return 1;\n}\n\n/* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Calculates and puts the results of the fitting procedure */\nstatic int putgenresults(startinf *startinfv, loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit)\n{\n  double *errors = NULL, *array = NULL;\n  int i;\n  size_t size_tv, length;\n  double doublev, chimult = 1.0;\n  char solpres = 1;\n  int disk;\n  char mes[200];\n  int dev = 1;\n  double solchisq;\n\n    /* Get the best-fit chisquare and check if we had a solution*/\n  if (gft_mst_get(fit -> gft_mstv, &solchisq, GFT_OUTPUT_SOLCHSQ)) {\n    if (!gft_mst_get(fit -> gft_mstv, &fit -> mon_bestchisq, GFT_OUTPUT_BESTCHISQ))\n      solpres = 2;\n    else \n      solpres = 0;\n  }\n\n  gft_mst_get(fit -> gft_mstv, &fit -> mon_size, GFT_OUTPUT_SIZE);\n\n  /* Allocate the error array */\n  if (!(errors = (double *) malloc(((NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+NSPARAMS+OUTTABNR)*sizeof(double))))\n    goto error;\n    \n\n  /* Get the number of elements in varlist */\n  if (solpres) {\n    gft_mst_get(fit -> gft_mstv, &size_tv, GFT_OUTPUT_NPAR);\n    \n    /* Allocate a double array of this length */\n    if ((size_tv)) {\n      if (!(array = (double *) malloc (size_tv*sizeof(double))))\n\t\t  goto error;\n    }\n    \n    if ((solpres == 1)) {\n      for (i = 0; i < (NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+NSPARAMS+OUTTABNR; ++i)\n\t\t  errors[i] = 0.0;\n\t\t\n      /* Get the best-fit parameters therein */\n      if (gft_mst_get(fit -> gft_mstv, array, GFT_OUTPUT_SOLPAR)) {\n\t\t  free(array);\n\t\t  free(errors);\n\t\t  return 1;\n      }\n    }\n    else if (solpres == 2) {\n      if (gft_mst_get(fit -> gft_mstv, array, GFT_OUTPUT_BESTPAR)) {\n\tfree(array);\n\tfree(errors);\n\treturn 1;\n      }\n    }\n  }\n\n  /* Now calculate the parameters from that and copy to oldpar */\n  if (solpres){\n    chimult = pow(OUTRANGEFAC,chprm_gen(array, fit -> varylist, rpm -> par));\n/*     if (chprm_gen(array, fit -> varylist, rpm -> par)) */\n    \n/*       If they get out of range, we multiply the chisquare by OUTRANGEFAC  */\n/*       chimult = OUTRANGEFAC; */\n/*     else */\n/*       chimult = 1.0; */\n  }\n\n  /* Now ensure that the indexed parameters are aligned */\n  for (i = rpm -> nur*NSSDPARAMS; i < rpm -> nur *(NSSDPARAMS+NDPARAMS*rpm->ndisks); ++i) {\n    rpm -> chapar[i] = chkchangep(fit -> varylist, fit -> fitmode, i, rpm -> nur);\n  }\n\n  if (changedependent(rpm, rpm -> par, fit -> index, rpm -> chapar) < 0)\n    goto error;\n\n  /* When ending make one run of interpover */\n  interpover(rpm, rpm -> radsep, 1, NULL, fit -> index);\n\n  /* Do make the model */\n  galmod(hdr, rpm, GENFIT, fit -> varylist, fit -> index, fit -> fluxpoints, fit -> npoints);\n\n  /* Get the chisquare */  \n\n  /* use here the usual replacement of PCONDISP */\n  doublev = chimult*(reg_do(fit -> reg_contv, (fit -> mon_alloops == fit -> loops)?fit -> loops - 1:fit -> mon_alloops, getchisquare_c(rpm -> par[((NPARAMS + (rpm -> ndisks - 1)*NDPARAMS))*rpm -> nur]))+((double) rpm -> outpoints)*rpm -> penalty);\n\n  /* report */\n  sprintf(mes, \n\t  \"Finished \"      /* Fitting */\n\t  \"N:%d\",          /* Number of pointsources */\n\t  fit -> npoints[0]);\n  for (disk = 1; disk < rpm -> ndisks; ++disk) {\n    length = strlen(mes);\n    sprintf(mes+length, \n\t    \"/%d\",       /* Number of pointsources */\n\t    fit -> npoints[disk]);\n  }\n  length = strlen(mes);\n  sprintf(mes+length, \n\t  \" F:%.2E\",     /* Total flux */\n\t  fit -> fluxpoints[0]*rpm -> cflux[0]*hdr -> deltgridtouser[2]);\n  for (disk = 1; disk < rpm -> ndisks; ++disk) {\n    length = strlen(mes);\n    sprintf(mes+length, \n\t    \"/%.2E\",\n\t    fit -> fluxpoints[disk]*rpm -> cflux[disk]*hdr -> deltgridtouser[2]);\n  }\n  length = strlen(mes);\n  sprintf(mes+length, \n\t  \" C:%E \"          /* current chisquare */\n\t  \" S:%E \",          /* size */\n\t\t\t doublev,      /* current minimum chisquare */\n\t  fit -> mon_size    /* size */\n\t  );\n  anyout_tir(&dev, mes);\n\n  /* New Kamphuis */\n  if (startinfv -> restartid) {\n    length = strlen(mes);\n    sprintf(mes+length, \n\t    \" R:%i \",          /* current restart-id */\n\t    startinfv -> restartid    /* size */\n\t    );\n  }\n  progressout(startinfv, mes);\n\n  /* error source ? */\n\n  for (i = 0; i < (NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+NSPARAMS; ++i) {\n    rpm -> oldpar[i] = rpm -> par[i];\n  }\n\n  /* This does not work for some reason, has to be addressed in gft. Nasty hack? */\n  /*\n if (gft_mst_get(fit -> gft_mstv, &doublev2, GFT_OUTPUT_SOLCHSQRED)) {\n   gft_mst_get(fit -> gft_mstv, &doublev2, GFT_OUTPUT_ACTCHISQRED);\n   gft_mst_get(fit -> gft_mstv, &doublev, GFT_OUTPUT_ACTCHISQ);\n }\n  */\n\n  /* instead we use what we get from the last model */\n\n  /* make the output array */\n writeoutarray(log, hdr, rpm, rpm -> par, 1, doublev, fit -> recnr, fit -> dof, -1.0);\n \n  /* Errors are 0 if there are none, we use the par array to indicate that */\n  for (i = 0; i < (NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur + NSPARAMS; ++i)\n    rpm -> par[i] = 0.0;\n\n  /* get the errors */\n  if (!gft_mst_get(fit -> gft_mstv, array, GFT_OUTPUT_SOLERR))\n    chprm_gen(array, fit -> varylist, rpm -> par);\n    \n  /* Go through the parameters */\n  writeoutarrayerr(hdr, rpm, rpm -> par, errors, 1, 0.0, 0, fit -> dof);\n\n  /* Put it to the grid */\n  for (i = 0; i < (NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+NSPARAMS+OUTTABNR; ++i) {\n/*     ftstab_fillhd(i, ftstab_get_coltit(i+1), ftstab_get_coltyp(i+1), errors[i], log -> outarray[i]); */\n    tir_fillhd(log, i, errors[i], log -> outarray[i]);\n  }\n  /* Apply the changes */\n/*   if (!ftstab_clearhd(0)) */\n/*     goto error; */\n\n  for (i = 0; i < (NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+NSPARAMS; ++i) {\n    rpm -> par[i] = rpm -> oldpar[i];\n  }\n\n  if ((errors))\n    free(errors);\n \n  if ((array))\n    free(array);\n\n  return 1;\n\n error:\n  if ((errors))\n    free(errors);\n  if ((array))\n    free(array);\n  return 0;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* A golden section iteration */\nstatic int golden_section(startinf *startinfv, loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit)\n{\n  int i,j;\n  int accept = 1;\n  long bigloops;\n  varlel *varele;\n  varlel *varele2;\n  double delta;\n  double delta_start;\n  int maxiter;\n  int curiter;\n  int satisfied;\n  int globiter = 0;\n  int globiter_old;\n  int def = 1;\n  char mes[300];\n  char key[20];\n  double *prevresult;\n  int nmax = 0;\n  double chimult;\n  /*  double mdelt; */\n  int disk;\n  size_t length;\n\n\n     for (i=0; i<100000000; ++i)\n       ;\n\n  /* Get the number of elements in the varlist */\n  varele = fit -> varylist;\n  \n  i = 0;\n  while (varele) {\n    ++i;\n    nmax = (nmax > varele -> nelem) ? nmax: varele -> nelem;\n    varele = varele -> next;\n  }\n\n  /* The degrees of freedom are determined by the amount of variable\n     parameters, we do it VERY roughly. If there is a parameter varied\n     twice, this is not true anymore */\n  /* dof = (hdr -> bsize1-1)*hdr -> bsize2* hdr -> nsubs-i; */\n  \n  /* We allocate the prevresult array */\n  if (!(prevresult = (double *) malloc(nmax*sizeof(double))))\n    return 0;\n  \n  /* Now get the number of big loops */\n/*   if (ftstab_get_rownr_()) */\n/*     bigloops = (fit -> loopnr)/i+1+!((fit -> loopnr)%i); */\n/*   else { */\n  bigloops = 0;\n/*   } */\n  bigloops = (fit -> loopnr != 0)?(fit -> loopnr-1)/i+1:0;\n  \n  /* Now put the pointer to the next element in the varlel */\n  if ((fit -> loopnr))\n    i = (fit -> loopnr-1)%i;\n  else\n    i = 0;\n\n  varele = fit -> varylist;\n  for (j = 0; j < i; ++j)\n    varele = varele -> next;\n  \n  for (i = rpm -> nur*NSSDPARAMS; i < rpm->nur *(NSSDPARAMS+NDPARAMS*rpm->ndisks); ++i)\n    rpm -> chapar[i] = 1;\n\n  /* The new parameter list will be created */\n  if (!(fit -> loopnr)) {\n    if (changedependent(rpm, rpm -> par, fit -> index, rpm -> chapar) < 0)\n      goto error;\n    for (i = 0; i < rpm -> nur*(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)+NSPARAMS; ++i)\n      rpm -> oldpar[i] = rpm -> par[i];\n  }\n  else {\n    if (changedependent(rpm, rpm -> oldpar, fit -> index, rpm -> chapar) < 0)\n      goto error;\n    for (i = 0; i < rpm -> nur*(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)+NSPARAMS; ++i)\n      rpm -> par[i] = rpm -> oldpar[i];\n  }\n\n  /* When starting make one run of interpover */\n  interpover(rpm, rpm -> radsep, 1, NULL, fit -> index);\n\n/* Get the old chisqare or initialise */\n  if ((fit -> loopnr)) {\n    hdr -> oldchi2 = log -> outarray[(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+NSPARAMS+CHISQ_TABNR-1];\n    satisfied = log -> outarray[(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+NSPARAMS+ACCEPT_TABNR-1];\n  }  \n  else {\n\n     /* addendum: change penalising strategy also for this task */\n     varele2 = fit -> varylist;\n     chimult = 1.0;\n     while(varele2) {\n       for (i = 0; i < varele2 -> nelem; ++i) {\n\t if (maths_checkinbetw(varele2 -> parmax, varele2 -> parmin, rpm -> par[varele2 -> elements[i]])) {\n\t   \n\t   /* If they get out of range, we multiply the chisquare by OUTRANGEFAC */\n\t   chimult = chimult*OUTRANGEFAC;\n\t   break;\n\t }\n       }\n       varele2 = varele2 -> next;\n     }\n\n    /* Do it */\n    galmod(hdr, rpm, 1, varele, fit -> index, rpm -> fluxpoints, fit -> npoints);\n\n    /* Get the chisquare */\n    hdr -> chi2 = getchisquare_c(rpm -> par[((NPARAMS + (rpm -> ndisks - 1)*NDPARAMS))*rpm -> nur]);\n \n    /* Regularise */\n    hdr -> chi2 = reg_do(fit -> reg_contv, fit -> loopnr, hdr -> chi2);\n\n    /* For bookkeeping */\n    fit -> mon_alloops = fit -> loopnr;\n\n    /* Correct the chisquare taking into account the outliers, don't know if that is necessary here... */\n    hdr -> chi2 = chimult*(hdr -> chi2+((double) rpm -> outpoints)*rpm -> penalty);\n\n    /* Copy it */\n    hdr -> oldchi2 = hdr -> chi2;\n    \n    /* Write the output */\n    satisfied = 1;\n    \n    /* Starting */\n    sprintf(mes, \"START\");\n    \n    anyout_tir(&def, mes);\n    writeoutput(log, hdr, rpm, fit, satisfied, fit -> dof, bigloops, globiter);\n    ++fit -> loopnr;\n    ++bigloops;\n  }\n\n  /* This will run until the bigloops is reached */\n  while (bigloops <= fit -> loops) {\n    \n    /* We go through the varylist */\n    while(varele) {\n       \n      /* Record where we started */\n      for (i = 0; i < varele -> nelem; ++i)\n\tprevresult[i] = rpm -> oldpar[varele -> elements[i]];\n      \n      /* Reset the old chisquare */\n      /* chi2_old = hdr -> oldchi2 ; */\n      \n      globiter_old = globiter;\n      \n      /* Calculate the delta */\n      if (bigloops - varele -> moderate <= 0)\n\tdelta = (bigloops-1)*(varele -> delend-varele -> delstart)/varele -> moderate+varele -> delstart;\n      else\n\tdelta = varele -> delend;\n      \n      \n      delta_start = delta;\n      \n      /* Calculate the number of steps */\n      if (bigloops - varele -> moderate <= 0)\n\tmaxiter = ((bigloops-1)*(varele -> iteend-varele -> itestart))/varele -> moderate+varele -> itestart;\n      else\n\tmaxiter = varele -> iteend;\n      \n      /* The first iteration */\n      curiter = 0;\n      accept = 1;\n      \n      /* We go on searching until we find a lower chisquare and then a higher chisquare */\n      while (1) {\n \n\t/* If the maximum number of iterations is reached break out, deeply disappointed */\n\tif (curiter == maxiter) {\n\t  accept = 0;\n\t  satisfied = 0;\n\t  break;\n\t}\n \n\t/* Change the params */\n\tfor (i = 0; i < varele -> nelem; ++i)\n\t  rpm -> par[varele -> elements[i]] = rpm -> oldpar[varele -> elements[i]] + delta;\n\n\t/* addendum: change penalising strategy also for this task */\n     /* addendum: change penalising strategy also for this task */\n     varele2 = fit -> varylist;\n     chimult = 1.0;\n     while(varele2) {\n       for (i = 0; i < varele2 -> nelem; ++i) {\n\t if (maths_checkinbetw(varele2 -> parmax, varele2 -> parmin, rpm -> par[varele2 -> elements[i]])) {\n\t   \n\t   /* If they get out of range, we multiply the chisquare by OUTRANGEFAC */\n\t   chimult = chimult*OUTRANGEFAC;\n\t   break;\n\t }\n       }\n       varele2 = varele2 -> next;\n     }\n\n     /* Reset the touched array */\n     for (i = rpm -> nur*NSSDPARAMS; i < rpm->nur *(NSSDPARAMS+NDPARAMS*rpm->ndisks); ++i)\n       rpm -> chapar[i] = chkchangep(varele, fit -> fitmode, i, rpm -> nur);\n\n     /* check and change the index */\n     if (changedependent(rpm, rpm -> par, fit -> index, rpm -> chapar) < 0)\n       goto error;\n\n     /* Do it */\n     for (i = 0; i < rpm -> ndisks; ++i)\n       rpm -> fluxpoints[i] = 0;\n     galmod(hdr, rpm, 1, varele, fit -> index, rpm -> fluxpoints, fit -> npoints);\n\n\t++globiter;\n \n\t/* Get the chisquare */\n\thdr -> chi2 = getchisquare_c(rpm -> par[((NPARAMS + (rpm -> ndisks - 1)*NDPARAMS))*rpm -> nur]);\n \n\t/* Regularise */\n\thdr -> chi2 = reg_do(fit -> reg_contv, bigloops-1, hdr -> chi2);\n\tfit -> mon_alloops = bigloops-1;\n\n\t/* Correct the chisquare taking into account the outliers, don't know if that is necessary here... */\n\thdr -> chi2 = chimult*(hdr -> chi2+((double) rpm -> outpoints)*rpm -> penalty);\n \n\t/* \tftstab_putcoltitl(key, ftstab_get_coltit(*varele -> elements+1)); */\n\tftstab_putcoltitl(key, (*varele -> elements)/rpm -> nur+1);\n\n\t/* Report Search minimum, big loops, keyword loops, total models, keyword, first ringnumber, keyword models/maxmodels, number of pointsources, total flux, current minimum chisquare, trial chisquare, difference, current stepwidth, start stepwidth. In principle, this should be a status report, but gipsy... crashes when you interrupt the task if you change the length MSGLEN of the status line in taskcom.h */\n\tsprintf(mes, \n\t\t\"SM \"         /* Searching minimum */\n\t\t\"BL:%li \"       /* Big loops */\n\t\t\"KL:%li \"       /* Keyword loops */\n\t\t\"TM:%i \"     /* Total models */\n\t\t\"KW:%s \"       /* Keyword */ \n\t\t\"FR:%i \"       /* First ringnumber */\n\t\t\"KM:%i\"        /* Keyword models */\n\t\t\"/%i \"         /* Keyword maxmodels */\n\t\t\"NP:%d\",       /* Number of pointsources */\n\t\tbigloops,                /* Big loops */         \n\t\tfit -> loopnr,                       /* Keyword loops */        \n\t\tglobiter,                /* Total models */        \n\t\tkey,                 /* Keyword */ \n\t\t(*varele -> elements/rpm -> nur < (NPARAMS+(rpm -> ndisks-1)*NDPARAMS))?*varele -> elements%rpm -> nur+1:1,                  /* First ringnumber */  \n\t\tglobiter-globiter_old,                      /* Keyword models */        \n\t\tmaxiter,                /* Keyword maxmodels */        \n\t\tfit -> npoints[0]);               /* Number of pointsources */       \n\tfor (disk = 1; disk < rpm -> ndisks; ++disk) {\n\t  length = strlen(mes);\n\t  sprintf(mes+length, \n\t\t  \"/%d\",       /* Number of pointsources */\n\t\t  fit -> npoints[disk]);\n\t}\n\tlength = strlen(mes);\n\tsprintf(mes+length, \n\t\t\" TF:%.2E\",     /* Total flux */\n\t\trpm -> fluxpoints[0]*rpm -> cflux[0]);\n\tfor (disk = 1; disk < rpm -> ndisks; ++disk) {\n\t  length = strlen(mes);\n\t  sprintf(mes+length, \n\t\t  \"/%.2E\",\n\t\t  rpm -> fluxpoints[disk]*rpm -> cflux[disk]);\n\t}\n \n\tlength = strlen(mes);\n\tsprintf(mes+length, \n\t\t\" CC:%E \"       /* current minimum chisquare */\n\t\t\"DC:%+.1E \"       /* Difference */\n\t\t\"SW:%+.2E\"       /* Current stepwidth */\n\t\t\"/%.2E \"         /* Start stepwidth */\n\t\t\"AC:%i\",      /* Acceptance flag */                                          \n\t\thdr -> oldchi2,               /* current minimum chisquare */       \n\t\thdr -> oldchi2-hdr -> chi2,                                                     /* Difference */ \n\t\tddinterntoparam(delta, (*varele -> elements)/rpm -> nur +1, hdr, rpm -> ndisks),         /* Current stepwidth */        \n\t\tddinterntoparam(delta_start, (*varele -> elements)/rpm -> nur +1, hdr, rpm -> ndisks),   /* Start stepwidth */           \n\t\tsatisfied               /* Acceptance flag */           \n\t\t);                              \n\tanyout_tir(&def, mes);\n\n\t/* Now compare */\n\tif (hdr -> chi2 >= hdr -> oldchi2) {\n   \n\t  /* If the number of iterations is larger than 1, we stop it here */\n\t  if (curiter > 0) {\n\t    delta = BFAC*delta;\n\t    ++curiter;\n\t    break;\n\t  }\n\t  /* If not we search in the other direction */\n\t  else {\n\t    delta = -delta;\n\t  }\n\t}\n\telse {\n   \n\t  /* Now overwrite the oldparams */\n\t  for (i = 0; i < varele -> nelem; ++i)\n\t    rpm -> oldpar[varele -> elements[i]] = rpm -> oldpar[varele -> elements[i]] + delta;\n\n\t  /* check and change the index */\n\n\t  if (changedependent(rpm, rpm -> oldpar, fit -> index, rpm -> chapar) < 0)\n\t    goto error;\n\n\t  /* Now enlarge the delta and accept the chisquare */\n\t  hdr -> oldchi2 = hdr -> chi2;\n\t  if (curiter < MAGNIFICNR) \n\t    delta = AFAC*delta;\n\t}\n \n\t++curiter;\n      }\n      \n      /* search = 1; */\n      \n      if ((accept)) {\n\t/* We go on searching to find the minimum in the knowledge that we are nearly there */\n\twhile (1) {\n   \n\t  /* If the maximum number of iterations is reached break out, deeply disappointed */\n\t  if (curiter == maxiter) {\n\t    satisfied = 0;\n\t    break;\n\t  }\n   \n\t  /* Change the delta */\n\t  delta = BFAC * delta;\n   \n\t  /* Check if we break out because of too small deltas*/\n\t  if (fabs(delta) < varele -> mindelta)\n\t    break;\n   \n\t  for (i = 0; i < varele -> nelem; ++i)\n\t    rpm -> par[varele -> elements[i]] = rpm -> oldpar[varele -> elements[i]] + delta;\n   \n     /* addendum: change penalising strategy also for this task */\n     varele2 = fit -> varylist;\n     chimult = 1.0;\n     while(varele2) {\n       for (i = 0; i < varele2 -> nelem; ++i) {\n\t if (maths_checkinbetw(varele2 -> parmax, varele2 -> parmin, rpm -> par[varele2 -> elements[i]])) {\n\t   \n\t   /* If they get out of range, we multiply the chisquare by OUTRANGEFAC */\n\t   chimult = chimult*OUTRANGEFAC;\n\t   break;\n\t }\n       }\n       varele2 = varele2 -> next;\n     }\n\t  /* check out the indexed parameters */\n     for (i = rpm -> nur*NSSDPARAMS; i < rpm->nur *(NSSDPARAMS+NDPARAMS*rpm->ndisks); ++i)\n       rpm -> chapar[i] = chkchangep(varele, fit -> fitmode, i, rpm -> nur);\n\n     if (changedependent(rpm, rpm -> par, fit -> index, rpm -> chapar) < 0)\n       goto error;\n\n     /* We don't have to check whether we broke out of range */\n     \n     /* Do it */\n     galmod(hdr, rpm, 1, varele, fit -> index, rpm -> fluxpoints, fit -> npoints);\n     ++globiter;\n     \n     /* Get the chisquare */\n\t  hdr -> chi2 = getchisquare_c(rpm -> par[((NPARAMS + (rpm -> ndisks - 1)*NDPARAMS))*rpm -> nur]);\n   \n\t  /* Regularise */\n\t  hdr -> chi2 = reg_do(fit -> reg_contv, bigloops-1, hdr -> chi2);\n\t  fit -> mon_alloops = bigloops-1;\n\n\t  /* Correct the chisquare taking into account the outliers, don't know if that is necessary here... */\n\t  hdr -> chi2 = chimult*(hdr -> chi2+((double) rpm -> outpoints)*rpm -> penalty);\n   \n\t  /* Report Found minimum, big loops,  total models, keyword loops, keyword, first ringnumber, keyword models/maxmodels, number of pointsources, total flux, current minimum chisquare, trial chisquare, difference, current stepwidth, start stepwidth */\n   \n\t  /* Report Search minimum, big loops, keyword loops, total models, keyword, first ringnumber, keyword models/maxmodels, number of pointsources, total flux, current minimum chisquare, trial chisquare, difference, current stepwidth, start stepwidth */\n\t  sprintf(mes, \n\t\t  \"FM \"         /* Searching minimum */\n\t\t  \"BL:%li \"       /* Big loops */\n\t\t  \"KL:%li \"       /* Keyword loops */\n\t\t  \"TM:%i \"     /* Total models */\n\t\t  \"KW:%s \"       /* Keyword */ \n\t\t  \"FR:%i \"       /* First ringnumber */\n\t\t  \"KM:%i\"        /* Keyword models */\n\t\t  \"/%i \"         /* Keyword maxmodels */\n\t\t  \"NP:%d\",       /* Number of pointsources */\n\t\t  bigloops,                /* Big loops */         \n\t\t  fit -> loopnr,                       /* Keyword loops */        \n\t\t  globiter,                /* Total models */        \n\t\t  key,                 /* Keyword */ \n\t\t  (*varele -> elements/rpm -> nur < (NPARAMS+(rpm -> ndisks-1)*NDPARAMS))?*varele -> elements%rpm -> nur+1:1,                  /* First ringnumber */  \n\t\t  globiter-globiter_old,                      /* Keyword models */        \n\t\t  maxiter,                /* Keyword maxmodels */        \n\t\t  fit -> npoints[0]);               /* Number of pointsources */       \n\t  for (disk = 1; disk < rpm -> ndisks; ++disk) {\n\t    length = strlen(mes);\n\t    sprintf(mes+length, \n\t\t    \"/%d\",       /* Number of pointsources */\n\t\t    fit -> npoints[disk]);\n\t  }\n\t  length = strlen(mes);\n\t  sprintf(mes+length, \n\t\t  \" TF:%.2E\",     /* Total flux */\n\t\t  rpm -> fluxpoints[0]*rpm -> cflux[0]);\n\t  for (disk = 1; disk < rpm -> ndisks; ++disk) {\n\t    length = strlen(mes);\n\t    sprintf(mes+length, \n\t\t    \"/%.2E\",\n\t\t    rpm -> fluxpoints[disk]*rpm -> cflux[disk]);\n\t  }\n \n\t  length = strlen(mes);\n\t  sprintf(mes+length, \n\t\t  \" CC:%E \"       /* current minimum chisquare */\n\t\t  \"DC:%+.1E \"       /* Difference */\n\t\t  \"SW:%+.2E\"       /* Current stepwidth */\n\t\t  \"/%.2E \"         /* Start stepwidth */\n\t\t  \"AC:%i\",      /* Acceptance flag */                                          \n\t\t  hdr -> oldchi2,               /* current minimum chisquare */       \n\t\t  hdr -> oldchi2-hdr -> chi2,                                                     /* Difference */ \n\t\t  ddinterntoparam(delta, (*varele -> elements)/rpm -> nur+1, hdr, rpm -> ndisks),         /* Current stepwidth */        \n\t\t  ddinterntoparam(delta_start, (*varele -> elements)/rpm -> nur+1, hdr, rpm -> ndisks),   /* Start stepwidth */           \n\t\t  satisfied               /* Acceptance flag */           \n\t\t  );\n\t  anyout_tir(&def, mes);\n   \n\t  /* Now compare */\n\t  if (hdr -> chi2 >= hdr -> oldchi2) {\n\t    delta = -delta;\n\t  }\n\t  else {\n\t    /* Now overwrite the oldparams */\n     \n\t    for (i = 0; i < varele -> nelem; ++i)\n\t      rpm -> oldpar[varele -> elements[i]] = rpm -> oldpar[varele -> elements[i]] + delta;\n\n\t    for (i = rpm -> nur*NSSDPARAMS; i < rpm->nur *(NSSDPARAMS+NDPARAMS*rpm->ndisks); ++i)\n\t      rpm -> chapar[i] = chkchangep(varele, fit -> fitmode, i, rpm -> nur);\n\n\t\t /* check out the indexed parameters */\n\t    if (changedependent(rpm, rpm -> oldpar, fit -> index, rpm -> chapar) < 0)\n\t      goto error;\n\n\t    hdr -> oldchi2 = hdr -> chi2;\n\t  }\n\t  ++curiter;\n\t}\n      }\n      \n      /*Output of a progress file Kamphuis addition */\n      progressout(startinfv, mes);\n\n      /* We have to check whether we have changed too much to be satisfied */\n      if ((satisfied)) {\n\t\n\t/* We only have to check one variable */\n\tif (fabs(rpm -> oldpar[varele -> elements[0]]-prevresult[0]) > varele -> satdelt) {\n\t  satisfied = 0;\n\t}\n      }\n      \n      /* Check the range of the params, this is old */ \n      /* Deleted everything START */\n      /*       for (i = 0; i < varele -> nelem; ++i) { */\n      /* \tif (maths_checkinbetw(varele -> parmax, varele -> parmin, rpm -> oldpar[varele -> elements[i]])) { */\n      \n      /* Comment on that */\n      /* \t  sprintf(mes, \"Parameter out of range, interpolating\"); */\n      /* \t  anyout_tir(&def, mes); */\n      \n      /***************/\n      /* This is new */\n      /***************/\n      \n      /* Find out what has happened */\n      /* mdelt = 0 */\t  \n      /* \t  mdelt = fabs(prevresult[i] - rpm -> oldpar[varele -> elements[i]])/2.0; */\n      \n      /* \t  if (varele -> parmax > varele -> parmin) { */\n      /* \t    if (rpm -> oldpar[varele -> elements[i]] < varele -> parmin) { */\n      /* \t      while (i < varele -> nelem) { */\n      /* \t\tmdelt = (((prevresult[i]-varele -> parmin)/2.0) < mdelt)?((prevresult[i]-varele -> parmin)/2.0):mdelt; */ \n      /* \t\tmdelt = (fabs(prevresult[i]-varele -> parmin) < mdelt)?(fabs(prevresult[i]-varele -> parmin)/2.0):mdelt; */\n      /* \t\t++i; */\n      /* \t      } */\n      /* \t      mdelt = -mdelt; */\n      /* \t    } */\n      /* \t    else { */\n      /* \t      while (i < varele -> nelem) { */\n      /* \t\t\t\tmdelt = (((varele -> parmax-prevresult[i])/2.0) < mdelt)?(((varele -> parmax-prevresult[i])/2.0)/2.0):mdelt; */ \n      /* \t\tmdelt = (fabs(prevresult[i]-varele -> parmax) < mdelt)?(fabs(prevresult[i]-varele -> parmax)/2.0):mdelt; */\n      /* \t\t++i; */\n      /* \t      } */\n      /* \t    } */\n      /* \t  } */\n      /* \t  else { */\n      /* \t    if (rpm -> oldpar[varele -> elements[i]] < varele -> parmax) { */\n      /* \t      while (i < varele -> nelem) { */\n      /* \t\t \t\tmdelt = (((prevresult[i]-varele -> parmax)/2.0) < mdelt)?((prevresult[i]-varele -> parmax)/2.0):mdelt; */\n      /* \t\tmdelt = (fabs(prevresult[i]-varele -> parmax) < mdelt)?(fabs(prevresult[i]-varele -> parmax)/2.0):mdelt; */\n      /* \t\t++i; */\n      /* \t      } */\n      /* \t      mdelt = -mdelt; */\n      /* \t    } */\n      /* \t    else { */\n      /* \t      while (i < varele -> nelem) { */\n      /* \t\t \t\tmdelt = (((varele -> parmin-prevresult[i])/2.0) < mdelt)?(((varele -> parmin-prevresult[i])/2.0)/2.0):mdelt; */ \n      /* \t\tmdelt = (fabs(prevresult[i]-varele -> parmin) < mdelt)?(fabs(prevresult[i]-varele -> parmin)/2.0):mdelt; */\n      /* \t\t++i; */\n      /* \t      } */\n      /* \t    } */\n      /* \t  } */\n      \n      /* change all the values: new */\n      /* \t  for (i = 0; i < varele -> nelem; ++i) */\n      /* \t    rpm -> par[varele -> elements[i]] = rpm -> oldpar[varele -> elements[i]] = prevresult[i]+mdelt; */\n      \n      /* check out the indexed parameters */\n      /* \t  changedependent(rpm, rpm -> par, fit -> index); */\n      /* \t  changedependent(rpm, rpm -> oldpar, fit -> index); */\n      \n      /* write back all the values: old */\n      /*    for (i = 0; i < varele -> nelem; ++i) */\n      /*      rpm -> par[varele -> elements[i]] = rpm -> oldpar[varele -> elements[i]] = prevresult[i]; */\n\t  \n      /* This is crucial at that point */\n      /* \t  interpover(rpm, rpm -> radsep, 1, varele, fit -> index); */\n\t  \n      /* Do it */\n      /*  \t  galmod(hdr, rpm, 1, varele, fit -> index, fluxpoints, fit -> npoints); */\n   \n      /* Get the chisquare */\n      /*  \t  hdr -> chi2 = getchisquare_c(rpm -> par[(PCONDISP)*rpm -> nur]); */\n      \n      /* Regularise */\n      /* \t  hdr -> chi2 = reg_do(fit -> reg_contv, bigloops-1, hdr -> chi2); */\n      /* \t  fit -> mon_alloops = bigloops-1; */\n      \n      /* Correct the chisquare taking into account the outliers, don't know if that is necessary here... */\n      /* \t  hdr -> chi2 = hdr -> chi2+((double) rpm -> outpoints)*rpm -> penalty; */\n      \n      /* \t  hdr -> oldchi2 = hdr -> chi2; */\n\n      /* \t  satisfied = 0; */\n      /* \t  break; */\n      /* \t} */\n      /*       } */\n     \n      /* BUGFIXED? The following lines were not present in the previous version */\n      /* Write oldpar into par */\n      for (i = 0; i < varele -> nelem; ++i)\n\trpm -> par[varele -> elements[i]] = rpm -> oldpar[varele -> elements[i]];\n      \n      /* check out the indexed parameters */\n      for (i = rpm -> nur*NSSDPARAMS; i < rpm->nur *(NSSDPARAMS+NDPARAMS*rpm->ndisks); ++i)\n\trpm -> chapar[i] = 1;\n\n      if (changedependent(rpm, rpm -> par, fit -> index, rpm -> chapar) < 0)\n\tgoto error;\n      \n      /* BUGFIX: This seems to be very important in order not to loose pointsources; if not done, a pointsource list might be terminated the wrong way */\n      interpover(rpm, rpm -> radsep, 1, varele, fit -> index);\n      \n      writeoutput(log, hdr, rpm, fit, satisfied, fit -> dof, fit -> loopnr, globiter);\n\n      varele = varele -> next;\n      \n      /* Now we document on the results */\n      ++fit -> loopnr;\n      \n      if ((*hdr -> outset != '\\0')) {\n\tif (!(fit -> loopnr%hdr -> outcubup)) {\n\t  writemodel(hdr, rpm, fit, rpm -> oldpar, fit -> index);\n\t}\n      }\n    }\n    \n    /* If we are still satisfied, we break, because we have results, which is documented also in outarray[(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+NSPARAMS-1+ACCEPT_TABNR] */\n    if ((satisfied)) {\n      break;\n    }\n\n    /* We start at the start of the varylist again */\n    varele = fit -> varylist;\n    \n    ++bigloops;\n    satisfied = 1;\n  }\n\n  free(prevresult);\n  return 1;\n\n error:\n  return 0;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Calculates and puts the results of the fitting procedure */\nstatic int putgoldresults(loginf *log, ringparms *rpm, fitparms *fit)\n{\n  int i;\n  \n  /* The best value is at the end */\n/*   ftstab_get_row(fit -> loopnr, log -> outarray); */\n/* This is probably stupid, but, well... */\n  tir_get_register(log, rpm, log -> outarray);\n  \n  /* Put it to the grid */\n  for (i = 0; i < (NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+NSPARAMS+OUTTABNR; ++i)\n/*     ftstab_fillhd(i, ftstab_get_coltit(i+1), ftstab_get_coltyp(i+1), COLRADI_DEFAULT, log -> outarray[i]); */\n    tir_fillhd(log, i, COLRADI_DEFAULT, log -> outarray[i]);  \n\n\n  /* Apply the changes */\n/*   if (!ftstab_clearhd(0)) */\n/*     goto error; */\n  \n  return 1;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Writes an ascii table with the results */\nstatic int writeasctable(startinf *startinfv, loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit)\n{\n  int def = 2;\n  int nel = 1;\n  int rring;\n  int err = 1;\n  char mes[81];\n\n  FILE *stream;\n  int i, j;\n  char key[21];\n  char key2[26];\n  double value;\n  double delta;\n  double vsys;\n  double nu;\n  double nv[3];\n  double nvtot[3];\n  double nrefr[3];\n\n  double cosp;\n  double sinp;\n  double sini;\n  double cosi;\n  double pp[3];\n  double posin[3];\n  double posout[3];\n\n\n  /**********/\n  /**********/\n  /* int obsint; */\n  /* char obsmes[81]; */\n  /*********/\n\n  /* First check if there was an input */\n  if (*log -> table == '\\0')\n    return 1;\n  \n  /* Also check if there was a logfile and stop if there wasn't */\n/*   if (*log -> logname == '\\0') */\n/*     return 0; */\n\n  rring = rpm -> nur >= 5?5:rpm -> nur;\n\n  /* Get the reference ring */\n  sprintf(mes, \"Give reference ring for warp angle calculation\");\n  while ((err)) {\n    userint_tir(startinfv -> arel, &rring, &nel, &def, \"REFRING=\", mes);\n    if (rring <= 0 || rring > rpm -> nur) {\n      sprintf(mes, \"REFRING: impossible number\");\n      cancel_tir(startinfv -> arel, \"REFRING=\", 2);\n      def = 4;\n    } \n    else\n      err = 0;\n  }\n\n  /* Try to open the output file */\n  if (!(stream = fopen(log -> table, \"r\"))) {\n    \n    /* If the file doesn't exist we compose a header */\n    if (!(stream = fopen(log -> table, \"w\"))) {\n      return 0;\n    }\n  }\n  else {\n    if (!(stream = fopen(log -> table, \"a\")))\n      return 0;\n    fprintf(stream, \"\\n\");\n  }\n  \n  /* Now we put some general information, commented */\n  fprintf(stream, \"# tirific version 1\\n\");\n  fprintf(stream, \"# logfile: %s\\n\", log -> logname);\n  \n  \n  if (fit -> fitmode >= GOLDEN_SECTION) {\n    fprintf(stream, \"# fitmode was golden section or higher\\n\");\n    fprintf(stream, \"# last acceptance was (1 accepted, 0 not accepted): %f\\n\", log -> outarray[(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+NSPARAMS+ACCEPT_TABNR-1]);\n  }  \n  else {\n    fprintf(stream, \"# fitmode was metropolis\\n\");\n  }\n  /* The chisquare makes only sense in case of zero errors */\n/*   fprintf(stream, \"# Chisquare: %f\\n# Reduced Chisquare: %f\\n\",  */\n/* ftstab_get_colgrd((NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+NSPARAMS+CHISQ_TABNR),  */\n/* ftstab_get_colgrd((NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+NSPARAMS+RCHISQ_TABNR)); */\n  fprintf(stream, \"# Chisquare: %f\\n# Reduced Chisquare: %f\\n\", tir_get_colgrd(log, rpm, (NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+NSPARAMS+CHISQ_TABNR), tir_get_colgrd(log, rpm, (NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+NSPARAMS+RCHISQ_TABNR));\n  \n  /* We comment the header */\n  fprintf(stream, \"# \");\n\n  /* We now compose a header entry for each keyword including radius */\n  for (i = 1; i <= (NPARAMS+(rpm -> ndisks-1)*NDPARAMS)+NSPARAMS; ++i) {\n    /* Put the title */\n    ftstab_putcoltitl(key, i);\n    fprintf(stream, \"%19s \", key);\n    sprintf(key2, \"DELTA%s\", key);\n    fprintf(stream, \"%19s \", key2);\n  }\n\n  /* Now we include some specials */\n\n    sprintf(key, \"RADI/kpc\");\n    fprintf(stream, \"%19s \", key);\n    sprintf(key2, \"DELTA%s\", key);\n    fprintf(stream, \"%19s \", key2);\n\n    sprintf(key, \"SBR/cm^(-2)\");\n    fprintf(stream, \"%19s \", key);\n    sprintf(key2, \"DELTA%s\", key);\n    fprintf(stream, \"%19s \", key2);\n\n    sprintf(key, \"SBR/(msol/(pc^2))\");\n    fprintf(stream, \"%19s \", key);\n    sprintf(key2, \"DELTA%s\", key);\n    fprintf(stream, \"%19s \", key2);\n\n    sprintf(key, \"WA_old (deg)\");\n    fprintf(stream, \"%19s \", key);\n\n    sprintf(key, \"WA_new (deg)\");\n    fprintf(stream, \"%19s \", key);\n\n    sprintf(key, \"LON_ASC_RA (deg)\");\n    fprintf(stream, \"%19s \", key);\n\n    sprintf(key, \"LON_ASC_DEC (deg)\");\n    fprintf(stream, \"%19s \", key);\n\n    sprintf(key, \"LON_DSC_RA (deg)\");\n    fprintf(stream, \"%19s \", key);\n\n    sprintf(key, \"LON_DSC_DEC (deg)\");\n    fprintf(stream, \"%19s \", key);\n\n    sprintf(key, \"LMV_APP_RA (deg)\");\n    fprintf(stream, \"%19s \", key);\n\n    sprintf(key, \"LMV_APP_DEC (deg)\");\n    fprintf(stream, \"%19s \", key);\n\n    sprintf(key, \"LMV_REC_RA (deg)\");\n    fprintf(stream, \"%19s \", key);\n\n    sprintf(key, \"LMV_REC_DEC (deg)\");\n    fprintf(stream, \"%19s \", key);\n\n    fprintf(stream, \"\\n\");\n    fprintf(stream, \"  \");\n\n    /* We read all values into the outarray */\n    tir_get_grid(log, rpm, log -> outarray);\n\n    for (j = 0; j < rpm -> nur*(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)+NSPARAMS; ++j)\n      rpm -> par[j] = log -> outarray[j];\n\n    /* We convert to internal units and interpolate over */\n    changetointern(rpm -> par, rpm -> nur, hdr, rpm -> ndisks);\n\n    for (i = rpm -> nur*NSSDPARAMS; i < rpm->nur *(NSSDPARAMS+NDPARAMS*rpm->ndisks); ++i)\n      rpm -> chapar[i] = chkchangep(fit -> varylist, fit -> fitmode, i, rpm -> nur);\n    \n    if (changedependent(rpm, rpm -> par, fit -> index, rpm -> chapar) < 0)\n      goto error;\n\n    interpover(rpm, rpm -> radsep, 0, NULL, fit -> index);\n\n    for (i = 0; i < 3; ++i) {\n      nvtot[i] = 0;\n    }\n\n    /* Now we calculate the direction of the total angular momentum of the observed component */\n    for (j = 0; j < rpm -> nr; ++j) {\n      /* We don't do a relativistic correction */\n      value = pow(rpm -> modpar[PRADI*rpm -> nr+j],2)*rpm -> modpar[PVROT*rpm -> nr+j]*rpm -> modpar[PSBR*rpm -> nr+j];\n      nvtot[0] = nvtot[0]+(double) value*sin(rpm -> modpar[PINCL*rpm -> nr+j])*sin(rpm -> modpar[PPA*rpm -> nr+j]);\n      nvtot[1] = nvtot[1]-(double) value*sin(rpm -> modpar[PINCL*rpm -> nr+j])*cos(rpm -> modpar[PPA*rpm -> nr+j]);\n      nvtot[2] = nvtot[2]+(double) value*cos(rpm -> modpar[PINCL*rpm -> nr+j]);\n    }\n\n    value = sqrt(pow(nvtot[0],2)+pow(nvtot[1],2)+pow(nvtot[2],2));\n    nvtot[0] = nvtot[0]/value;\n    nvtot[1] = nvtot[1]/value;\n    nvtot[2] = nvtot[2]/value;\n\n    /* Now get the normal vector of the reference ring */\n    nrefr[0] = sinf(rpm -> par[PINCL*rpm -> nur+rring-1])*sinf(rpm -> par[PPA*rpm -> nur+rring-1]);\n    nrefr[1] = -sinf(rpm -> par[PINCL*rpm -> nur+rring-1])*cosf(rpm -> par[PPA*rpm -> nur+rring-1]);\n    nrefr[2] = cosf(rpm -> par[PINCL*rpm -> nur+rring-1]);\n\n    /* Now we read in the values, we should have a third extension opened */\n    for (j = 1; j <= rpm -> nur; ++j) {\n      for (i = 0; i < (NPARAMS+(rpm -> ndisks-1)*NDPARAMS); ++i) {\n /* Put the title */\n\tvalue = tir_get_colgrd(log, rpm, i*rpm -> nur+j);\n\tdelta = tir_get_colrad(log, rpm, i*rpm -> nur+j);\n fprintf(stream, \"%+.12E %+.12E \", value, delta);\n      }\n      \n      /* The single parameters */\n      for (i = 0; i < NSPARAMS; ++i) {\n\tvalue = tir_get_colgrd(log, rpm, (NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+i+1);\n\tdelta = tir_get_colrad(log, rpm, (NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+i+1);\n fprintf(stream, \"%+.12E %+.12E \", value, delta);\n      }\n\n      /* Now the specials */\n      \n      /* Calculate the radius in kpc */\n      value = tir_get_colgrd(log, rpm, PRADI*rpm -> nur+j);\n      delta = tir_get_colrad(log, rpm, PRADI*rpm -> nur+j);\n\n      /* Let's be slow, as this is only output */\n      value = value*1000*log -> distance*TWOPI/(360*60*60);\n      delta = delta*1000*log -> distance*TWOPI/(360*60*60);\n      fprintf(stream, \"%+.12E %+.12E \", value, delta);\n      \n      /* Calculate the approximate frequency */\n      vsys = tir_get_colgrd(log, rpm, PVSYS*rpm -> nur+j);\n      nu = (SPEEDOFLIGHT-vsys)*hdr -> rfreq/SPEEDOFLIGHT;\n\n      value = tir_get_colgrd(log, rpm, PSBR*rpm -> nur+j);\n      delta = tir_get_colrad(log, rpm, PSBR*rpm -> nur+j);\n\n      /* The intensity in the restframe scales like */\n      value = hdr -> itou*value*pow(hdr -> rfreq/nu,4);\n      delta = hdr -> itou*delta*pow(hdr -> rfreq/nu,4);\n      fprintf(stream, \"%+.12E %+.12E \", value, delta);\n \n      /* Now we convert to Msol/pc^2 */\n      value = UTOSOLAR*value;\n      delta = UTOSOLAR*delta;\n      fprintf(stream, \"%+.12E %+.12E \", value, delta);\n      fprintf(stream, \"   \");\n\n      /* Get the normal vector of the current ring */\n      nv[0] = sin(rpm -> par[PINCL*rpm -> nur+j-1])*sin(rpm -> par[PPA*rpm -> nur+j-1]);\n      nv[1] = -sin(rpm -> par[PINCL*rpm -> nur+j-1])*cos(rpm -> par[PPA*rpm -> nur+j-1]);\n      nv[2] = cos(rpm -> par[PINCL*rpm -> nur+j-1]);\n      \n      /* Here is the scalar product with the reference ring */\n      value = nv[0]*nrefr[0]+nv[1]*nrefr[1]+nv[2]*nrefr[2];\n\n      /* This is the arcus */\n      value = value>1?0.0:RADTODEG*acos(value);\n      fprintf(stream, \"%+.12E \", value);\n\n      /* Here is the scalar product with the reference frame */\n      value = nv[0]*nvtot[0]+nv[1]*nvtot[1]+nv[2]*nvtot[2];\n\n      /* This is the arcus */\n      value = value>1?0.0:RADTODEG*acos(value);\n      fprintf(stream, \"%+.12E \", value);\n\n      /* LON and maximum velocity coordinates */\n      cosi = cos(rpm -> par[PINCL*rpm -> nur+j-1]);\n      sini = sin(rpm -> par[PINCL*rpm -> nur+j-1]);\n      cosp = cos(rpm -> par[PPA*rpm -> nur+j-1]);\n      sinp = sin(rpm -> par[PPA*rpm -> nur+j-1]);\n\n      /* Ascending LON */\n\n      /* Position */\n      posin[0] = 0;\n      posin[1] = rpm -> par[PRADI*rpm -> nur+j-1];\n      posin[2] = 0;\n\n      /* Velocity will not be regarded*/\n\n      /* Rotate about x-axis */\n      maths_rotax(cosi, sini, posin, pp);\n\n      /* Rotate about z-axis */\n      maths_rotaz(cosp, sinp, pp, posout);\n\n      /* Add central coordinates */\n      posout[0] = posout[0]+rpm -> par[PXPOS*rpm -> nur+j-1];\n      posout[1] = posout[1]+rpm -> par[PYPOS*rpm -> nur+j-1];\n      posout[2] = rpm -> par[PVSYS*rpm -> nur+j-1];\n\n      /* Change into user coordinates */\n      interntoglob(posout, pp, hdr);\n\n      /* Print */\n      fprintf(stream, \"%+.12E \", pp[0]);\n      fprintf(stream, \"%+.12E \", pp[1]);\n\n      /* Descending LON */\n\n      /* Position */\n      posin[0] = 0;\n      posin[1] = -rpm -> par[PRADI*rpm -> nur+j-1];\n      posin[2] = 0;\n\n      /* Velocity will not be regarded*/\n\n      /* Rotate about x-axis */\n      maths_rotax(cosi, sini, posin, pp);\n\n      /* Rotate about z-axis */\n      maths_rotaz(cosp, sinp, pp, posout);\n\n      /* Add central coordinates */\n      posout[0] = posout[0]+rpm -> par[PXPOS*rpm -> nur+j-1];\n      posout[1] = posout[1]+rpm -> par[PYPOS*rpm -> nur+j-1];\n      posout[2] = rpm -> par[PVSYS*rpm -> nur+j-1];\n\n      /* Change into user coordinates */\n      interntoglob(posout, pp, hdr);\n\n      /* Print */\n      fprintf(stream, \"%+.12E \", pp[0]);\n      fprintf(stream, \"%+.12E \", pp[1]);\n\n      /* Approaching Maximum Velocity */\n\n      /* Position */\n      posin[0] = -rpm -> par[PRADI*rpm -> nur+j-1];\n      posin[1] = 0;\n      posin[2] = 0;\n\n      /* Velocity will not be regarded*/\n\n      /* Rotate about x-axis */\n      maths_rotax(cosi, sini, posin, pp);\n\n      /* Rotate about z-axis */\n      maths_rotaz(cosp, sinp, pp, posout);\n\n      /* Add central coordinates */\n      posout[0] = posout[0]+rpm -> par[PXPOS*rpm -> nur+j-1];\n      posout[1] = posout[1]+rpm -> par[PYPOS*rpm -> nur+j-1];\n      posout[2] = rpm -> par[PVSYS*rpm -> nur+j-1];\n\n      /* Change into user coordinates */\n      interntoglob(posout, pp, hdr);\n\n      /* Print */\n      fprintf(stream, \"%+.12E \", pp[0]);\n      fprintf(stream, \"%+.12E \", pp[1]);\n\n      /* Receding Maximum Velocity */\n\n      /* Position */\n      posin[0] = rpm -> par[PRADI*rpm -> nur+j-1];\n      posin[1] = 0;\n      posin[2] = 0;\n\n      /* Velocity will not be regarded*/\n\n      /* Rotate about x-axis */\n      maths_rotax(cosi, sini, posin, pp);\n\n      /* Rotate about z-axis */\n      maths_rotaz(cosp, sinp, pp, posout);\n\n      /* Add central coordinates */\n      posout[0] = posout[0]+rpm -> par[PXPOS*rpm -> nur+j-1];\n      posout[1] = posout[1]+rpm -> par[PYPOS*rpm -> nur+j-1];\n      posout[2] = rpm -> par[PVSYS*rpm -> nur+j-1];\n\n      /* Change into user coordinates */\n      interntoglob(posout, pp, hdr);\n\n      /* Print */\n      fprintf(stream, \"%+.12E \", pp[0]);\n      fprintf(stream, \"%+.12E \", pp[1]);\n\n      fprintf(stream, \"\\n  \");\n    }\n    \n  fclose(stream);\n  return 1;\n\n error:\n  return 0;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Writes an ascii table with the results */\nstatic int writebigasctable(startinf *startinfv, loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit)\n{\n  int def = 2;\n  int nel = 1;\n  int rring = 5;\n  int err = 1;\n  char mes[81];\n\n  FILE *stream;\n  int i, j;\n  /* char key[201]; */\n  char *key = NULL;\n  double value;\n  double vsys;\n  double nu;\n  double nv[3];\n  double nvtot[3];\n  double nrefr[3];\n\n  double cosp;\n  double sinp;\n  double sini;\n  double cosi;\n  double pp[3];\n  double posin[3];\n  double posout[3];\n\n  char **varystr = NULL;\n  int keypres, nread, nreturned;\n\n\n\n  if ((key)) {\n    free(key);\n    key = NULL;\n  }\n\n  if (varystr) {\n    freeparsed(varystr);\n    varystr = NULL;\n  }\n\n  if (simparse_scn_arel_readval_stringlist(startinfv -> arel, \"BIGTABLE\", \"Give big table name.\", 0, NULL, 0, -1, 0, 0, &keypres, &nread, &nreturned, &varystr))\n    goto error;\n  \n  if ((varystr[0])) {\n    if (!(key = simparse_copystring(varystr[0]))) {\n      goto error;\n    }\n  }\n  else {\n    if (!(key = simparse_copystring(\"\"))) {\n      goto error;\n    }\n  }\n  \n  freeparsed(varystr);\n  varystr = NULL;\n  \n  /* If there is no input we stop here */\n  if (*key == '\\0') {\n    free(key);\n    return 1;\n  }\n  \n  /* Check if there was a logfile and stop if there wasn't */\n  /*   if (*log -> logname == '\\0') */\n  /*     return 0; */\n  \n  /* Get the reference ring */\n  sprintf(mes, \"Give reference ring for warp angle calculation\");\n  while ((err)) {\n    userint_tir(startinfv -> arel, &rring, &nel, &def, \"REFRING=\", mes);\n    if (rring <= 0 || rring > rpm -> nur) {\n      sprintf(mes, \"REFRING: impossible number\");\n      cancel_tir(startinfv -> arel, \"REFRING=\", 2);\n      def = 4;\n    } \n    else\n      err = 0;\n  }\n\n  /* Try to open the output file */\n  if (!(stream = fopen(key, \"r\"))) {\n    \n    /* If the file doesn't exist we compose a header */\n    if (!(stream = fopen(key, \"w\"))) {\n      return 0;\n    }\n  }\n  else {\n    if (!(stream = fopen(key, \"a\")))\n      return 0;\n    fprintf(stream, \"\\n\");\n  }\n  \n  /* Now we put some general information, commented */\n  fprintf(stream, \"# tirific version 1\\n\");\n  fprintf(stream, \"# logfile: %s\\n\", log -> logname);\n  \n  \n  if (fit -> fitmode >= GOLDEN_SECTION) {\n    fprintf(stream, \"# fitmode was golden section\\n\");\n    fprintf(stream, \"# last acceptance was (1 accepted, 0 not accepted): %f\\n\", log -> outarray[(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+NSPARAMS+ACCEPT_TABNR-1]);\n  }  \n  else {\n    fprintf(stream, \"# fitmode was metropolis\\n\");\n  }\n  /* The chisquare makes only sense in case of zero errors */\n  if (tir_get_colrad(log, rpm, (PRADI)*rpm -> nur+1) == 0.0) {\n    fprintf(stream, \"# Chisquare: %f\\n# Reduced Chisquare: %f\\n\", tir_get_colgrd(log, rpm, (NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+NSPARAMS+CHISQ_TABNR), tir_get_colgrd(log, rpm, (NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+NSPARAMS+RCHISQ_TABNR));\n  }\n\n  /* We comment the header */\n  fprintf(stream, \"# \");\n\n  /* We now compose a header entry for each keyword including radius */\n  for (i = 1; i <= (NPARAMS+(rpm -> ndisks-1)*NDPARAMS)+NSPARAMS; ++i) {\n    /* Put the title */\n    ftstab_putcoltitl(key, i);\n    fprintf(stream, \"%19s \", key);\n  }\n\n  /* Now we include some specials */\n\n    sprintf(key, \"RADI/kpc\");\n    fprintf(stream, \"%19s \", key);\n\n    sprintf(key, \"SBR/cm^(-2)\");\n    fprintf(stream, \"%19s \", key);\n\n    sprintf(key, \"SBR/(msol/(pc^2))\");\n    fprintf(stream, \"%19s \", key);\n\n    sprintf(key, \"WA_old (deg)\");\n    fprintf(stream, \"%19s \", key);\n\n    sprintf(key, \"WA_new (deg)\");\n    fprintf(stream, \"%19s \", key);\n\n    sprintf(key, \"LON_ASC_RA (deg)\");\n    fprintf(stream, \"%19s \", key);\n\n    sprintf(key, \"LON_ASC_DEC (deg)\");\n    fprintf(stream, \"%19s \", key);\n\n    sprintf(key, \"LON_DSC_RA (deg)\");\n    fprintf(stream, \"%19s \", key);\n\n    sprintf(key, \"LON_DSC_DEC (deg)\");\n    fprintf(stream, \"%19s \", key);\n\n    sprintf(key, \"LMV_APP_RA (deg)\");\n    fprintf(stream, \"%19s \", key);\n\n    sprintf(key, \"LMV_APP_DEC (deg)\");\n    fprintf(stream, \"%19s \", key);\n\n    sprintf(key, \"LMV_REC_RA (deg)\");\n    fprintf(stream, \"%19s \", key);\n\n    sprintf(key, \"LMV_REC_DEC (deg)\");\n    fprintf(stream, \"%19s \", key);\n\n    fprintf(stream, \"\\n\");\n    fprintf(stream, \"  \");\n\n    /* We read all values into the par array */\n    tir_get_grid(log, rpm, log -> outarray);\n\n    for (j = 0; j < rpm -> nur*(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)+NSPARAMS; ++j)\n      rpm -> par[j] = log -> outarray[j];\n\n    /* We con't convert to internal units and interpolate over */\n/*     changetointern(rpm -> par, rpm -> nur, hdr, rpm -> ndisks); */\n\n    for (i = rpm -> nur*NSSDPARAMS; i < rpm->nur *(NSSDPARAMS+NDPARAMS*rpm->ndisks); ++i)\n      rpm -> chapar[i] = 1;\n    \n    if (changedependent(rpm, rpm -> par, fit -> index, rpm -> chapar) < 0)\n      goto error;\n\n    interpover(rpm, dinterntoparam(rpm -> radsep, RADI, hdr, rpm -> ndisks), 0, NULL, fit -> index);\n\n    for (i = 0; i < 3; ++i) {\n      nvtot[i] = 0;\n    }\n\n    /* Now we calculate the direction of the total angular momentum of the observed component */\n    for (j = 0; j < rpm -> nr; ++j) {\n\n      /* We don't do a relativistic correction for this */\n      value = pow(rpm -> modpar[PRADI*rpm -> nr+j],2)*rpm -> modpar[PVROT*rpm -> nr+j]*rpm -> modpar[PSBR*rpm -> nr+j];\n      nvtot[0] = nvtot[0]+(double) value*sin(DEGTORAD*rpm -> modpar[PINCL*rpm -> nr+j])*sin(DEGTORAD*rpm -> modpar[PPA*rpm -> nr+j]);\n      nvtot[1] = nvtot[1]-(double) value*sin(DEGTORAD*rpm -> modpar[PINCL*rpm -> nr+j])*cos(DEGTORAD*rpm -> modpar[PPA*rpm -> nr+j]);\n      nvtot[2] = nvtot[2]+(double) value*cos(DEGTORAD*rpm -> modpar[PINCL*rpm -> nr+j]);\n    }\n\n    value = sqrt(pow(nvtot[0],2)+pow(nvtot[1],2)+pow(nvtot[2],2));\n    nvtot[0] = nvtot[0]/value;\n    nvtot[1] = nvtot[1]/value;\n    nvtot[2] = nvtot[2]/value;\n\n    /* Now get the normal vector of the reference ring */\n    nrefr[0] = sinf(DEGTORAD*rpm -> par[PINCL*rpm -> nur+rring-1])*sinf(DEGTORAD*rpm -> par[PPA*rpm -> nur+rring-1]);\n    nrefr[1] = -sinf(DEGTORAD*rpm -> par[PINCL*rpm -> nur+rring-1])*cosf(DEGTORAD*rpm -> par[PPA*rpm -> nur+rring-1]);\n    nrefr[2] = cosf(DEGTORAD*rpm -> par[PINCL*rpm -> nur+rring-1]);\n \n    /* Now we read in the values */\n    for (j = 0; j < rpm -> nr; ++j) {\n      for (i = 0; i < (NPARAMS+(rpm -> ndisks-1)*NDPARAMS); ++i) {\n value = rpm -> modpar[i*rpm -> nr+j];\n fprintf(stream, \"%+.12E \", value);\n      }\n      /* The single parameters */\n      for (i = 0; i < NSPARAMS; ++i) {\n\tvalue = tir_get_colgrd(log, rpm, (NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+i+1);\n fprintf(stream, \"%+.12E \", value);\n      }\n      /* Now the specials */\n      \n      /* Calculate the radius in kpc */\n      value = rpm -> modpar[PRADI*rpm -> nr+j];\n      \n      /* Let's be slow, as this is only output */\n      value = value*1000*log -> distance*TWOPI/(360*60*60);\n      fprintf(stream, \"%+.12E \", value);\n      \n      /* Calculate the approximate frequency */\n      vsys = rpm -> modpar[PVSYS*rpm -> nr+j];\n      nu = (SPEEDOFLIGHT-vsys)*hdr -> rfreq/SPEEDOFLIGHT;\n      \n      value = rpm -> modpar[PSBR*rpm -> nr+j];\n\n      /* The intensity in the restframe scales like */\n      value = hdr -> itou*value*pow(hdr -> rfreq/nu,4);\n      fprintf(stream, \"%+.12E \", value);\n \n      /* Now we convert to Msol/pc^2 */\n      value = UTOSOLAR*value;\n      fprintf(stream, \"%+.12E \", value);\n    \n      /* Get the normal vector of the current ring */\n      nv[0] = sin(DEGTORAD*rpm -> modpar[PINCL*rpm -> nr+j])*sin(DEGTORAD*rpm -> modpar[PPA*rpm -> nr+j]);\n      nv[1] = -sin(DEGTORAD*rpm -> modpar[PINCL*rpm -> nr+j])*cos(DEGTORAD*rpm -> modpar[PPA*rpm -> nr+j]);\n      nv[2] = cos(DEGTORAD*rpm -> modpar[PINCL*rpm -> nr+j]);\n      \n      /* Here is the scalar product with the reference ring */\n      value = nv[0]*nrefr[0]+nv[1]*nrefr[1]+nv[2]*nrefr[2];\n\n      /* This is the arcus */\n      value = value>1?0.0:RADTODEG*acos(value);\n      fprintf(stream, \"%+.12E \", value);\n\n      /* Here is the scalar product with the reference frame */\n      value = nv[0]*nvtot[0]+nv[1]*nvtot[1]+nv[2]*nvtot[2];\n\n      /* This is the arcus */\n      value = value>1?0.0:RADTODEG*acos(value);\n      fprintf(stream, \"%+.12E \", value);\n\n      /* LON and maximum velocity coordinates */\n      cosi = cos(DEGTORAD*rpm -> modpar[PINCL*rpm -> nr+j]);\n      sini = sin(DEGTORAD*rpm -> modpar[PINCL*rpm -> nr+j]);\n      cosp = cos(DEGTORAD*rpm -> modpar[PPA*rpm -> nr+j]);\n      sinp = sin(DEGTORAD*rpm -> modpar[PPA*rpm -> nr+j]);\n\n      /* Ascending LON */\n\n      /* Position */\n      posin[0] = 0;\n      posin[1] = dparamtointern(rpm -> modpar[PRADI*rpm -> nr+j], RADI, hdr, rpm -> ndisks);\n      posin[2] = 0;\n\n      /* Velocity will not be regarded*/\n\n      /* Rotate about x-axis */\n      maths_rotax(cosi, sini, posin, pp);\n\n      /* Rotate about z-axis */\n      maths_rotaz(cosp, sinp, pp, posout);\n\n      /* Get central coordinates */\n      posin[0] = rpm -> modpar[PXPOS*rpm -> nr+j];\n      posin[1] = rpm -> modpar[PYPOS*rpm -> nr+j];\n      posin[2] = rpm -> modpar[PVSYS*rpm -> nr+j];\n      globtointern(posin, pp, hdr);\n\n      /* Add central coordinates */\n      posout[0] = posout[0]+pp[0];\n      posout[1] = posout[1]+pp[1];\n      posout[2] = pp[2];\n\n      /* Change into user coordinates */\n      interntoglob(posout, pp, hdr);\n\n      /* Print */\n      fprintf(stream, \"%+.12E \", pp[0]);\n      fprintf(stream, \"%+.12E \", pp[1]);\n\n      /* Descending LON */\n\n      /* Position */\n      posin[0] = 0;\n      posin[1] = -dparamtointern(rpm -> modpar[PRADI*rpm -> nr+j], RADI, hdr, rpm -> ndisks);\n      posin[2] = 0;\n\n      /* Velocity will not be regarded*/\n\n      /* Rotate about x-axis */\n      maths_rotax(cosi, sini, posin, pp);\n\n      /* Rotate about z-axis */\n      maths_rotaz(cosp, sinp, pp, posout);\n\n      /* Get central coordinates */\n      posin[0] = rpm -> modpar[PXPOS*rpm -> nr+j];\n      posin[1] = rpm -> modpar[PYPOS*rpm -> nr+j];\n      posin[2] = rpm -> modpar[PVSYS*rpm -> nr+j];\n      globtointern(posin, pp, hdr);\n\n      /* Add central coordinates */\n      posout[0] = posout[0]+pp[0];\n      posout[1] = posout[1]+pp[1];\n      posout[2] = pp[2];\n\n      /* Change into user coordinates */\n      interntoglob(posout, pp, hdr);\n\n      /* Print */\n      fprintf(stream, \"%+.12E \", pp[0]);\n      fprintf(stream, \"%+.12E \", pp[1]);\n\n      /* Approaching Maximum Velocity */\n      posin[0] = -dparamtointern(rpm -> modpar[PRADI*rpm -> nr+j], RADI, hdr, rpm -> ndisks);;\n      posin[1] = 0;\n      posin[2] = 0;\n\n      /* Velocity will not be regarded*/\n\n      /* Rotate about x-axis */\n      maths_rotax(cosi, sini, posin, pp);\n\n      /* Rotate about z-axis */\n      maths_rotaz(cosp, sinp, pp, posout);\n\n      /* Get central coordinates */\n      posin[0] = rpm -> modpar[PXPOS*rpm -> nr+j];\n      posin[1] = rpm -> modpar[PYPOS*rpm -> nr+j];\n      posin[2] = rpm -> modpar[PVSYS*rpm -> nr+j];\n      globtointern(posin, pp, hdr);\n\n      /* Add central coordinates */\n      posout[0] = posout[0]+pp[0];\n      posout[1] = posout[1]+pp[1];\n      posout[2] = pp[2];\n\n      /* Change into user coordinates */\n      interntoglob(posout, pp, hdr);\n\n      /* Print */\n      fprintf(stream, \"%+.12E \", pp[0]);\n      fprintf(stream, \"%+.12E \", pp[1]);\n\n      /* Receding Maximum Velocity */\n      posin[0] = dparamtointern(rpm -> modpar[PRADI*rpm -> nr+j], RADI, hdr, rpm -> ndisks);;\n      posin[1] = 0;\n      posin[2] = 0;\n\n      /* Velocity will not be regarded*/\n\n      /* Rotate about x-axis */\n      maths_rotax(cosi, sini, posin, pp);\n\n      /* Rotate about z-axis */\n      maths_rotaz(cosp, sinp, pp, posout);\n\n      /* Get central coordinates */\n      posin[0] = rpm -> modpar[PXPOS*rpm -> nr+j];\n      posin[1] = rpm -> modpar[PYPOS*rpm -> nr+j];\n      posin[2] = rpm -> modpar[PVSYS*rpm -> nr+j];\n      globtointern(posin, pp, hdr);\n\n      /* Add central coordinates */\n      posout[0] = posout[0]+pp[0];\n      posout[1] = posout[1]+pp[1];\n      posout[2] = pp[2];\n\n      /* Change into user coordinates */\n      interntoglob(posout, pp, hdr);\n\n      /* Print */\n      fprintf(stream, \"%+.12E \", pp[0]);\n      fprintf(stream, \"%+.12E \", pp[1]);\n\n      fprintf(stream, \"\\n  \");\n    }\n  fclose(stream);\n\n  /* Finally */\n  if ((key))\n    free(key);\n  if ((varystr))\n    freeparsed(varystr);\n  return 1;\n\n error:\n  /* Strangely, for this function, 0 returned means error. This is an old functino... */\n  if ((key))\n    free(key);\n  if ((varystr))\n    freeparsed(varystr);\n  return 0;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Make a qfits header suitable for coolgal output */\nstatic qfits_header *makecoolhdr(hdrinf *hdr, double beamsizeindeg) \n{\n  /* char key[9]; */\n  char value[21];\n  /* int j; */\n  /* int level = 0; */\n  /* int err = 0; */\n  int sizez;\n  qfits_header *header = NULL;\n\n  /* The bitpix is -32 */\n  if (!(header = ftsout_putcard(header, \"BITPIX\",\"-32\"))) \n    goto error;\n\n  /* The number of axes is set to three */\n  if (!ftsout_putcard(header, \"NAXIS\",\"3\")) \n    goto error;\n\n  /* Now get the axis numbers */\n  sprintf(value, \"%i\", hdr -> bsize1*hdr->coolbin);\n  if (!ftsout_putcard(header, \"NAXIS1\",value))\n    goto error;\n  sprintf(value, \"%i\", hdr -> bsize2*hdr->coolbin);\n  if (!ftsout_putcard(header, \"NAXIS2\",value))\n    goto error;\n\n  /* The third axis is simply the maximum spatial size */\n  sprintf(value, \"%i\", sizez = ((hdr -> bsize2 > hdr -> bsize1)?hdr -> bsize2:hdr -> bsize1)*hdr->coolbin);\n  if (!ftsout_putcard(header, \"NAXIS3\",value))\n    goto error;\n\n  /* May contain an extension */\n  if (!ftsout_putcard(header, \"EXTEND\",\"T\"))\n    goto error;\n  \n  /* These are clear */\n  if (!ftsout_putcard(header, \"BSCALE\",\"1\"))\n    goto error;\n  if (!ftsout_putcard(header, \"BZERO\",\"0\"))\n    goto error;\n\n  /* The bunit is Jy*km/s/beam, while this is the 3d beam */\n  if (!ftsout_putcard(header, \"BUNIT\",\"'JY*(KM/S)/BEAM'\"))\n    goto error;\n\n  /* The cdelt is taken from the hdr struct, this should be ok with the unit being DEGREE*/  \n  sprintf(value, \"%.12E\", hdr -> userglobcdelt[0]/((double) hdr -> coolbin));\n  if (!ftsout_putcard(header, \"CDELT1\", value))\n    goto error;\n\n  /* The crpix is copied from the header of the inset */\n  sprintf(value, \"%.12E\", hdr -> setcrpix[0]*((double) hdr -> coolbin));\n  if (!ftsout_putcard(header, \"CRPIX1\", value))\n    goto error;\n\n  /* The crval in user units -> degree */\n  sprintf(value, \"%.12E\", hdr -> userglobcrval[0]);\n  if (!ftsout_putcard(header, \"CRVAL1\", value))\n    goto error;\n\n  /* This is nasty, because we have to re-read the info */\n  /* sprintf(key, \"CTYPE%i\", hdr -> inaxperm[0]); */\n  /* for (j = 0; j < 20; ++j) */\n  /*   value[j] = ' '; */\n  /* value[20] = '\\0'; */\n  /* gdsd_rchar_tir(hdr -> inset, key, &(level), value, &err); */\n\n  /* Type */\n  if (!ftsout_putcard(header, \"CTYPE1\", hdr -> oric -> type_x))\n    goto error;\n  /* if (!ftsout_putcard(header, \"CUNIT1\", \"'DEGREE            '\")) */\n  /*   goto error; */\n  \n  /* The cdelt is taken from the hdr struct, this should be ok with the unit being DEGREE*/  \n  sprintf(value, \"%.12E\", hdr -> userglobcdelt[1]/((double) hdr -> coolbin));\n  if (!ftsout_putcard(header, \"CDELT2\", value))\n    goto error;\n\n  /* The crpix is copied from the header of the inset */\n  sprintf(value, \"%.12E\", hdr -> setcrpix[1]*((double) hdr -> coolbin));\n  if (!ftsout_putcard(header, \"CRPIX2\", value))\n    goto error;\n\n  /* The crval in user units -> degree */\n  sprintf(value, \"%.12E\", hdr -> userglobcrval[1]);\n  if (!ftsout_putcard(header, \"CRVAL2\", value))\n    goto error;\n\n  /* This is nasty, because we have to re-read the info */\n  /* sprintf(key, \"CTYPE%i\", hdr -> inaxperm[1]); */\n  /* for (j = 0; j < 20; ++j) */\n  /*   value[j] = ' '; */\n  /* value[20] = '\\0'; */\n  /* gdsd_rchar_tir(hdr -> inset, key, &(level), value, &err); */\n  if (!ftsout_putcard(header, \"CTYPE2\", hdr -> oric -> type_y))\n    goto error;\n  /* if (!ftsout_putcard(header, \"CUNIT2\", \"'DEGREE            '\")) */\n  /*   goto error; */\n\n  if (!ftsout_putcard(header, \"EPOCH\", hdr -> oric -> epoch))\n    goto error;\n\n  /* The third axis is the artificial one */\n\n  /* The cdelt is copied from the inset */\n  sprintf(value, \"%.12E\", fabs(hdr -> userglobcdelt[0])/((double) hdr -> coolbin));\n  if (!ftsout_putcard(header, \"CDELT3\", value))\n    goto error;\n\n  /* crpix is in the middle */\n  sprintf(value, \"%.12E\", ((double) sizez)/2.0);\n  if (!ftsout_putcard(header, \"CRPIX3\", value))\n    goto error;\n\n  /* This is exactly 0 */\n  if (!ftsout_putcard(header, \"CRVAL3\", \"0.0\"))\n    goto error;\n\n  /* The type is somthing without projection, this should do */\n  if (!ftsout_putcard(header, \"CTYPE3\", \"'ANGLE             '\"))\n    goto error;\n\n  /* This is DEGREE again */\n  /* if (!ftsout_putcard(header, \"CUNIT3\", \"'DEGREE            '\")) */\n  /*   goto error; */\n\n  /* Fourth axis is velocity, one pixel with the width of the whole cube to give plotting programs an orientation */\n/*   if (!ftsout_putcard(header, \"CDELT4\", \"1.0\")) */\n/*     goto error; */\n/*   if (!ftsout_putcard(header, \"CRPIX4\", \"1.0\")) */\n/*     goto error; */\n/*   if (!ftsout_putcard(header, \"CRVAL4\", \"0.0\")) */\n/*     goto error; */\n/*   if (!ftsout_putcard(header, \"CTYPE4\", \"' '\")) */\n/*     goto error; */\n/*   if (!ftsout_putcard(header, \"CUNIT4\", \"'Y'\")) */\n/*     goto error; */\n\n/* Now we just put the beam properties, symmetric beam */\n  sprintf(value, \"%.12E\", beamsizeindeg);\n  if (!ftsout_putcard(header, \"BMAJ\", value))\n    goto error;\n  sprintf(value, \"%.12E\", beamsizeindeg);\n  if (!ftsout_putcard(header, \"BMIN\", value))\n    goto error;\n  if (!ftsout_putcard(header, \"BPA\", \"0\"))\n    goto error;\n\n  return header;\n  \n error:\n  if ((header)) \n    ftsout_header_destroy(header);\n  header = NULL;\n  return header;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Produces a 3d fits image of the model */\nstatic int coolgal(startinf *startinfv, loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit)\n{\n  int i;\n  char *coolname = NULL;\n  char mes[81];\n  int def;\n  int nel;\n  int err;\n  qfits_header *header;\n  Cube thecube;\n  double beam;\n  float *expfcs;\n  float sincosofangle[2];\n    \n  char **varystr = NULL;\n  int keypres, nread, nreturned;\n\n\n  /* First check if the user wants a coolgal output */\n  /* sprintf(mes, \"Give cool name.\"); */\n  /* for (i = 0; i < 200; ++i) */\n  /*   coolname[i] = ' '; */\n  /* coolname[200] = '\\0'; */\n  /* def = 2; */\n  /* nel = 1; */\n  \n  /* userchar_tir(coolname, &nel, &def, \"COOLGAL=\", mes); */\n  /* termsinglestr(coolname); */\n\n  /* cancel_tir(startinfv -> arel, \"COOLGAL\"); */\n\n  if ((coolname)) {\n    free(coolname);\n    coolname = NULL;\n  }\n\n  if (varystr) {\n    freeparsed(varystr);\n    varystr = NULL;\n  }\n\n  if (simparse_scn_arel_readval_stringlist(startinfv -> arel, \"COOLGALPAST\", \"Give cool name.\", 0, NULL, 0, -1, 0, 0, &keypres, &nread, &nreturned, &varystr))\n    goto error;\n  \n  if ((varystr[0])) {\n    if (!(coolname = simparse_copystring(varystr[0]))) {\n      goto error;\n    }\n  }\n  else {\n    if (!(coolname = simparse_copystring(\"\"))) {\n      goto error;\n    }\n  }\n  \n  freeparsed(varystr);\n  varystr = NULL;\n  \n  /* The default is to do nothing */\n  if (*coolname == '\\0') {\n    free(coolname);\n    return 1;\n  }\n  /* Now ask if the user wants a specific kind of beam, the default being the max beam */\n  sprintf(mes, \"Give 3d beam size (arcsec)\");\n  beam = hdr -> deltgridtouser[0]*((double) hdr -> bmaj);\n  def = 2;\n  nel = 1;\n  err = 1;\n  beam = 10;\n  while((err)) {\n    userdble_tir(startinfv -> arel, &beam, &nel, &def, \"COOLBEAM=\", mes);\n    if (beam >= 0.0) {\n      err = 0;\n    }\n    else {\n      sprintf(mes, \"COOLBEAM should be >= 0\");\n      cancel_tir(startinfv -> arel, \"COOLBEAM=\", 2);\n      beam = hdr -> deltgridtouser[0]*((double) hdr -> bmaj);\n      def = 1;\n    }\n  } \n  \n  /* Transfer the beam into deg */\n  beam = hdr -> globgridtouser[0]*beam/hdr -> deltgridtouser[0];\n  \n  /* Make a header, if the beam is 0, we normalise everything such that the units get right */\n  if (!(header = makecoolhdr(hdr, ((beam))?beam:sqrt(TWOPI)/(hdr -> globgridtouser[0]*0.42466090014401))))\n    return 1;\n  \n  /* Transfer the beam back to grid units */\n  beam = beam/hdr -> globgridtouser[0];\n    \n  /* Now arrange the cube */\n  thecube.refpix_x = 0;\n  thecube.refpix_y = 0;\n  thecube.refpix_v = 0;\n  thecube.size_x = hdr -> bsize1;\n  thecube.size_y = hdr -> bsize2;\n  thecube.size_v = (thecube.size_x > thecube.size_y)?thecube.size_x:thecube.size_y;\n  thecube.scale = 1.0;\n  thecube.padding = 0;\n  \n  /* After that, we can deallocate to get some memory, but first I try\n     not to do so and see how that works. */\n  \n/* We read in the values, this should be possible and make sense */ \n    tir_get_grid(log, rpm, log -> outarray);\n\n  for (i = 0; i < rpm -> nur*(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)+NSPARAMS; ++i)\n    rpm -> par[i] = log -> outarray[i];\n\n  /*     Convert the read parameter list to internal units */\n  changetointern(rpm -> par, rpm -> nur, hdr, rpm -> ndisks);\n  \n\n  /* provide some info */\n  nel=1;\n  sprintf(mes, \"cool number of bytes used: %lu\", thecube.size_x*thecube.size_y*thecube.size_v*sizeof(float));\n  anyout_tir(&nel, mes);\n\n  /* Now we allocate the cube, not caring for the padding, this will be done automatically */\n  if (!(thecube.points = (float *) malloc(thecube.size_x*thecube.size_y*thecube.size_v*sizeof(float)))) {\n    ftsout_header_destroy(header);\n    return 1;\n  }\n  \n  /* Make the cube */\n  makecoolpoints(&thecube, hdr, rpm, fit);\n\n  /* Convolve it */\n  sincosofangle[0] = 0;\n  sincosofangle[1] = 1;\n  \n  if (!(expfcs = expofacsfft(0.42466090014401*beam, 0.42466090014401*beam, 0.42466090014401*beam, sincosofangle))) {\n    ftsout_header_destroy(header);\n    free(thecube.points);\n    return 1;\n  }\n  \n  /* Now, the normalisation is the fifth factor, we multiply it with this */\n  expfcs[4] = expfcs[4]*sqrtf(TWOPI)*0.42466090014401*beam;\n\n  /* This is the actual convolution */\n\n  if ((beam)) {\n    convolgaussfft(&thecube, expfcs);\n  }\n\n  /* Output it */\n  ftsout_writecube(coolname, &thecube, header);\n\n  /* Deallocate everything */\n    ftsout_header_destroy(header);\n    free(thecube.points);\n    free(expfcs);\n\n /* Finally */\n  if ((coolname))\n    free(coolname);\n  if ((varystr))\n    freeparsed(varystr);\n  return 1;\n\n error:\n  /* Strangely, for this function, 0 returned means error. This is an old functino... */\n  if ((coolname))\n    free(coolname);\n  if ((varystr))\n    freeparsed(varystr);\n  return 0;\n\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Makes a 3d pointsource model and packs in on cube */\nstatic int makecoolpoints(Cube *cube, hdrinf *hdr, ringparms *rpm, fitparms *fit)\n{\n  int i,j,k;\n  float ringflux; /* Total flux of a subring */\n  int nc; /* Cloudnumber of a subring */\n  float cfluxcorr; /* The correct flux of a pointsource */\n  float sininc;\n  float cosinc;\n  float sinpa;\n  float cospa;\n  float r; /* A radius */\n  float az; /* Azimuth of pointsource */\n  float cosaz; /* The cosine of the az (memory wasting) */\n  float sinaz; /* The sine of the az (memory wasting) */\n  int grid[3]; /* Grid positions */\n  int totflux = 0;\n  float z0; /* The central plane for the z */\n  float pp[6]; /* Cartesian coordinates in phase-space, x,y,z,vx,vy,vz */\n                      /*                                       x: DEC, y: LOS, z: RA */\n  float pp2[6]; /* Cartesian coordinates in phase-space, x,y,z,vx,vy,vz */\n\n\n  int disk;\n\n  z0 = ((float) cube -> size_v)/2;\n\n  interpover(rpm, rpm -> radsep, 0, NULL, fit -> index);\n  \n  /* Initialise the model array */\n  cuberase(cube); \n  \n  for (disk = 0; disk < rpm -> ndisks; ++disk) {\n\n    /* Do all the loops */\n    for (i = 0; i < rpm -> nr; ++i) {\n      \n      /* Calculate the ringflux */\n      ringflux = TWOPI*rpm -> modpar[PRADI*rpm -> nr+i]*rpm -> radsep*rpm -> modpar[(PRPARAMS+disk*NDPARAMS+PSBR)*rpm -> nr+i];\n      /* Calculate the cloudnumber, rounded down, Kamphuis bugfix */\n      nc = (int) (ringflux/rpm -> cflux[disk]);\n      \n      /* We decide to change the cloudflux a bit instead of accepting an error in the ringflux */\n      cfluxcorr = ringflux/nc;\n      if (nc > 0) {\n\t\n\t/* We calculate cos's and sins and reset the random number generator */\n\tsininc=sinf(rpm -> modpar[(PRPARAMS+disk*NDPARAMS+PINCL)*rpm -> nr+i]);\n\tcosinc=cosf(rpm -> modpar[(PRPARAMS+disk*NDPARAMS+PINCL)*rpm -> nr+i]);;\n\tsinpa=sinf(rpm -> modpar[(PRPARAMS+disk*NDPARAMS+PPA)*rpm -> nr+i]);\n\tcospa=cosf(rpm -> modpar[(PRPARAMS+disk*NDPARAMS+PPA)*rpm -> nr+i]);\n\trpm -> sd[disk][i].iseed2[1] = i;\n\tmaths_rndmf_init(rpm -> sd[disk][i].iseed2, rpm -> sd[disk][i].permrandstr);\n\t\n\t/* reset the  zprof */ \n\tzprof(6, rpm -> sd[disk][i].permrandstr, &(rpm -> sd[disk][i].y2));\n\t\n\t/* now create the clouds and grid them */\n\tfor (j = 0; j < nc; ++j) {\n\t  \n\t  /* The probability for the #radius is weighted by r, and this is no approximation */\n\t  r = sqrtf((rpm -> modpar[PRADI*rpm -> nr+i]-0.5*rpm -> radsep)*(rpm -> modpar[PRADI*rpm -> nr+i]-0.5*rpm -> radsep)+2*rpm -> radsep*rpm -> modpar[PRADI*rpm -> nr+i]*maths_rndmf(rpm -> sd[disk][i].permrandstr));\n\t  \n\t  /* Azimuth is easy */\n\t  az = TWOPI*maths_rndmf(rpm -> sd[disk][i].permrandstr);\n\t  cosaz = cosf(az);\n\t  sinaz = sinf(az);\n\t  \n\t  /* Now, these are the cartesian coordinates, if you look face-on at the ring in the system of the ring, x eastwards, y to the north, z along los from you to the source */\n\t  /*       x = cosaz*r; */\n\t  /*       y = sinaz*r; */\n\t  /*       z = zprof(ltype)*modpar[PZ0*rpm -> nr+i]; */\n\t  /*       vx = -sinaz*modpar[PVROT*rpm -> nr+i]; */\n\t  /*       vy = cosaz*modpar[PVROT*rpm -> nr+i]; */\n\t  /*       vz = 0; */\n\t  \n\t  /* Now, the whole system will be rotated about the x-axis with the amount of the inclination */\n\t  /*       xp  = x; */\n\t  /*       yp  = cosinc*y-sininc*z; */\n\t  /*       zp  = sininc*y+cosinc*z; */\n\t  /*       vxp = vx; */\n\t  /*       vyp = cosinc*vy-sininc*vz; */\n\t  /*       vzp = sininc*vy+cosinc*vz; */\n\t  \n \n\t  /*  Now we rotate about the z-axis with pa, because in this module the pa is defined as the angle with the minor axis */\n\t  /*       x = xp*cos(-pa)-yp*sin(-pa)    or x = xp*cospa-yp*sinpa;      */\n\t  /*       y = xp*sin(-pa)+yp*cos(-pa)    or y = xp*sinpa+yp*cospa;     */\n\t  /*       z = zp;                        or z = zp;                     */         \n\t  /*       vx = vxp*cos(-pa)-vyp*sin(-pa) or vx = vxp*cospa-vyp*sinpa;   */\n\t  /*       vy = vxp*sin(-pa)+vyp*cos(-pa) or vy = vxp*sinpa+vyp*cospa;  */\n\t  /*       vz = vzp;                      or vz = vzp;                   */\n\t\n\t  /*  z = zprof(rpm -> ltype[0], rpm -> permrandstr)*rpm -> modpar[PZ0*rpm -> nr+i]; */\n\t  /*  x = (cosaz*r)*cospa-(cosinc*(sinaz*r)-sininc*z)*sinpa;  */\n\t  /*  y = (cosaz*r)*sinpa+(cosinc*(sinaz*r)-sininc*z)*cospa; */\n\t  /* Instead of vz this is the z component in the middle of the cube */\n\t  /*  z = sininc*sinaz*r+cosinc*z; */\n\t  /*  vz = (sininc*cosaz*rpm -> modpar[PVROT*rpm -> nr+i]); */\n\t  /* Calculate the coordinates of the point source before rotation */\n\t  pp[0] = cosaz*r;\n\t  pp[1] = sinaz*r;\n\t  pp[2] = zprof(rpm -> ltype[disk],  rpm -> sd[disk][i].permrandstr, &(rpm -> sd[disk][i].y2))*rpm -> modpar[(PRPARAMS+disk*NDPARAMS+PZ0)*rpm -> nr+i];\n\t  \n\t  (*(rpm -> inf_wm1v[disk] -> prs))((void *) rpm, pp+2, i, sinaz, cosaz, disk);\n\t  (*(rpm -> inf_wm2v[disk] -> prs))((void *) rpm, pp+2, i, sinaz, cosaz, disk);\n\t  (*(rpm -> inf_wm3v[disk] -> prs))((void *) rpm, pp+2, i, sinaz, cosaz, disk);\n\t  (*(rpm -> inf_wm4v[disk] -> prs))((void *) rpm, pp+2, i, sinaz, cosaz, disk);\n\t  (*(rpm -> inf_wm1v[disk] -> prc))((void *) rpm, pp+2, i, sinaz, cosaz, disk);\n\t  (*(rpm -> inf_wm2v[disk] -> prc))((void *) rpm, pp+2, i, sinaz, cosaz, disk);\n\t  (*(rpm -> inf_wm3v[disk] -> prc))((void *) rpm, pp+2, i, sinaz, cosaz, disk);\n\t  (*(rpm -> inf_wm4v[disk] -> prc))((void *) rpm, pp+2, i, sinaz, cosaz, disk);\n\t  (*(rpm -> inf_wm0v[disk] -> pr)) ((void *) rpm, pp+2, i, sinaz, cosaz, disk);\n\t\n\t  /* Now rotate about the x-axis by i */\n\t  pp2[0] = pp[0];\n\t  pp2[1] = pp[1]*cosinc-pp[2]*sininc;\n\t  pp2[2] = pp[1]*sininc+pp[2]*cosinc;\n\t  \n\t  /* Now we shift */\n\t  \n\t  (*(rpm -> inf_lc0v[disk] -> pr))((void *) rpm, pp2+0, i, sinaz, cosaz, disk);\n\t  (*(rpm -> inf_ls0v[disk] -> pr))((void *) rpm, pp2+1, i, sinaz, cosaz, disk);\n\t  \n\t  /* Now rotate about the z-axis by pa */\n\t  pp[0] = pp2[0]*cospa-pp2[1]*sinpa;\n\t  pp[1] = pp2[0]*sinpa+pp2[1]*cospa;\n\t  pp[2] = pp2[2];\n\t  \n\t  /* Here's the shortcut version */\n\t  /*     pp[0] = pp2[0]*cospa-pp2[1]*sinpa; */\n\t  /*     pp[1] = pp2[0]*sinpa+pp2[1]*cospa; */\n\t  /*     pp[2] = pp[1]*sininc+pp[2]*cosinc; */\n\t  \n\t  /* of course we could make it even shorter, but we'll leave it at that. Next thingy is to grid the pointsource */\n\t  grid[0] = roundnormal(rpm -> modpar[(PRPARAMS+disk*NDPARAMS+PXPOS)*rpm -> nr+i]-pp[1]);\n\t  \n\t  if (grid[0] >= 0 && grid[0] < cube -> size_x) {\n\t    \n\t    grid[1] = roundnormal(rpm -> modpar[(PRPARAMS+disk*NDPARAMS+PYPOS)*rpm -> nr+i]+pp[0]);\n\t    if (grid[1] >= 0 && grid[1] < cube -> size_y) {\n\t      /* For the sake of clearity, we kill the subsnuma operation in the source, in principle thus allowing only for the radio convention for velocity, but gaining an understanding of the code. What is seen here should not be done. It's really not what anyone should wish for. */\n\t      grid[2] = roundnormal((z0-pp[2]));\n\t      if (grid[2] >= 0 && grid[2] < cube -> size_v) {\n\t\t++totflux;\n\t\t/* This is the position in the linear cube array */\n\t\tk = grid[0]+ cube -> size_x*(grid[1]+cube -> size_y*grid[2]);\n\t\t\n\t\tcube -> points[k] = cube -> points[k]+cfluxcorr;\n\t      }\n\t    }\n\t  }\n\t}\n      }\n    }\n  }\n\n  /* We return the number of clouds */\n  return totflux;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Produces a progress file at every ring loop and write the last line. Kamphuis addition */\nstatic int progressout(startinf *startinfv, char *message)\n{\n  /* int i; */\n  /* int def = 2; */\n  /* int nel = 1; */\n  FILE *stream;\n  char *progname = NULL;\n  /* int obsint = 0;\n     char obsmes[180];*/\n  /* char mes[100]; */\n  char *currentname;\n\n  char **varystr = NULL;\n  int keypres, nread, nreturned;\n\n  /* for (i = 0; i < 200; ++i) { */\n  /*   progname[i] = ' '; */\n  /* } */\n  /* progname[200] = '\\0'; */\n \n  /* Ask the user what to do */\n  /* sprintf(mes, \"Give a progress file name for no point actually when you can read this\"); */\n  /* userchar_tir(progname, &nel, &def, \"PROGRESSLOG=\", mes); */\n  /* termsinglestr(progname); */\n  /* cancel_tir(startinfv -> arel, \"PROGRESSLOG\"); */\n\n  if (simparse_scn_arel_readval_stringlist(startinfv -> arel, \"PROGRESSLOG\", \"Give a progress file name for no point actually when you can read this.\", 0, NULL, 0, -1, 0, 0, &keypres, &nread, &nreturned, &varystr))\n    goto error;\n  \n  if ((varystr[0])) {\n    if (!(progname = simparse_copystring(varystr[0]))) {\n      goto error;\n    }\n  }\n  else {\n    if (!(progname = simparse_copystring(\"\"))) {\n      goto error;\n    }\n  }\n  \n  freeparsed(varystr);\n  varystr = NULL;\n\n  /* i = 0; */\n  currentname = progname;\n  \n  if (*currentname != '\\0') {\n      \n      /* Try to open the output, we overwrite */\n    if (!(stream = fopen(currentname, \"w\")))\n      goto error;\n      \n      /* Now put the first line, copy from input */\n    fprintf(stream,\"%s\",message);\n    fprintf(stream, \"\\n\");\n    /* and close again otherwise the file stays unreadable */\n        fflush(stream); \n    fclose(stream);\n     fflush(NULL); \n    }\n\n  if ((progname))\n    free(progname);\n  if ((varystr))\n    freeparsed(varystr);\n  return 0;\n  \n  error:\n  \n  if ((progname))\n    free(progname);\n  if ((varystr))\n    freeparsed(varystr);\n  return 1;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Appends a message to the progress file at the end of the fitting procedure. Kamphuis addition */\nstatic int progressfinished(startinf *startinfv)\n{\n  /* int i; */\n  /* int def = 2; */\n  /* int nel = 1; */\n  FILE *stream;\n  char *progname = NULL;\n  /* int obsint = 0;\n     char obsmes[180];*/\n  /* char mes[100]; */\n  char *currentname;\n\n  char **varystr = NULL;\n  int keypres, nread, nreturned;\n\n  /* for (i = 0; i < 200; ++i) { */\n  /*   progname[i] = ' '; */\n  /* } */\n  /* progname[200] = '\\0'; */\n \n  \n  /* Ask the user what to do */\n  /* sprintf(mes, \"Give a progress file name for no point actually when you can read this\"); */\n  /* userchar_tir(progname, &nel, &def, \"PROGRESSLOG=\", mes); */\n  /* termsinglestr(progname); */\n\n  /* i = 0; */\n  /* cancel_tir(startinfv -> arel, \"PROGRESSLOG\"); */\n\n  if (simparse_scn_arel_readval_stringlist(startinfv -> arel, \"PROGRESSLOG\", \"Give a progress file name for no point actually when you can read this.\", 0, NULL, 0, -1, 0, 0, &keypres, &nread, &nreturned, &varystr))\n    goto error;\n  \n  if ((varystr[0])) {\n    if (!(progname = simparse_copystring(varystr[0]))) {\n      goto error;\n    }\n  }\n  else {\n    if (!(progname = simparse_copystring(\"\"))) {\n      goto error;\n    }\n  }\n  \n  freeparsed(varystr);\n  varystr = NULL;\n\n  currentname = progname;\n  \n  if (*currentname != '\\0') {\n      \n      /* Try to open the output, we append */\n    if (!(stream = fopen(currentname, \"a\")))\n      goto error;\n      \n      /* Now put the first line, copy from input */\n    fprintf(stream,\"<STATUS> Tirific Finished\");\n    fprintf(stream, \"\\n\");\n    /* and close again otherwise the file stays unreadable */\n    fclose(stream);  \n    }\n\n  if ((progname))\n    free(progname);\n  if ((varystr))\n    freeparsed(varystr);\n  return 1;\n  \n  error:\n  \n  if ((progname))\n    free(progname);\n  if ((varystr))\n    freeparsed(varystr);\n  return 0;\n} \n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Produces one or two tirific logfiles containing the results */\nstatic int tirout(startinf *startinfv, loginf *log, ringparms *rpm, fitparms *fit, int nrplts)\n{\n  int i, j, k, l, m, n;\n  int def = 2;\n  int nel = 1;\n  int acc;\n  int len;\n  char *defname = NULL;\n  char *deintername = NULL;\n  char key[9];\n  char *currentname;\n  char mes[81];\n  FILE *stream;\n  /* char input[VARYHSTRELES]; */ /* Has the length of the maximum input */\n  char format[8];\n  char format2[8];\n  /* double *smarray = NULL; */\n  double *reparray = NULL;\n  double smsum, smweightsum, weight, lm1;\n  char inqstr[13];\n\n  int nrings;\n  int ringnr;\n  double *radii = NULL;\n  int givrad;\n  double dpdr;\n  int disk;\n  char placer[10];\n\n  char **varystr = NULL;\n  int keypres, nread, nreturned;\n\n  time_t restimest = 0;\n\n\n  /* Initialise the input arrays */\n  /* for (i = 0; i < 200; ++i) { */\n  /*   defname[i] = ' '; */\n  /*   deintername[i] = ' '; */\n  /* } */\n  /* defname[200] = '\\0'; */\n  /* deintername[200] = '\\0'; */\n  \n  /* Ask the user what to do */\n  /* sprintf(mes, \"Give a .def file name for best results output\"); */\n  /* userchar_tir(defname, &nel, &def, \"TIRDEF=\", mes); */\n  /* termsinglestr(defname); */\n  \n  /* sprintf(mes, \"Give a file name for smoothed results output\"); */\n  /* userchar_tir(deintername, &nel, &def, \"TIRSMO=\", mes); */\n  /* termsinglestr(deintername); */\n  \n  /* cancel_tir(startinfv -> arel, \"TIRDEF\"); */\n\n  if (simparse_scn_arel_readval_stringlist(startinfv -> arel, \"TIRDEF\", \"Give a progress file name for no point actually when you can read this.\", 0, NULL, 0, -1, 0, 0, &keypres, &nread, &nreturned, &varystr))\n    goto error;\n  \n  if ((varystr[0])) {\n    if (!(defname = simparse_copystring(varystr[0]))) {\n      goto error;\n    }\n  }\n  else {\n    if (!(defname = simparse_copystring(\"\"))) {\n      goto error;\n    }\n  }\n  \n  freeparsed(varystr);\n  varystr = NULL;\n\n  /* cancel_tir(startinfv -> arel, \"TIRSMO\"); */\n\n  if (simparse_scn_arel_readval_stringlist(startinfv -> arel, \"TIRSMO\", \"Give a progress file name for no point actually when you can read this.\", 0, NULL, 0, -1, 0, 0, &keypres, &nread, &nreturned, &varystr))\n    goto error;\n  \n  if ((varystr[0])) {\n    if (!(deintername = simparse_copystring(varystr[0]))) {\n      goto error;\n    }\n  }\n  else {\n    if (!(deintername = simparse_copystring(\"\"))) {\n      goto error;\n    }\n  }\n  \n  freeparsed(varystr);\n  varystr = NULL;\n\n  sprintf(mes, \"Give accuracy of def file output [2]\");\n  i = 1;\n  acc = 5;\n  def = 2;\n  while ((i)) {\n    userint_tir(startinfv -> arel, &acc, &nel, &def, \"TIRACC=\", mes);\n    if (acc < 1 || acc > 99) {\n      sprintf(mes, \"TIRACC: Must be larger than 0\");\n      def = 4;\n      cancel_tir(startinfv -> arel, \"TIRACC=\", 2);\n    }\n    else \n      --i;\n  }\n  \n  def = 2;\n  if (*deintername != '\\0') {\n    /* Smoothing kernel is a Hanning function h(k) = (Sum_l =\n       -(len-1)/2, ..., (len-1)/2\n       f(k+l)*(1+cos(2pi*l/(len-1))))/(Sum_l = -(len-1)/2, ...,\n       (len-1)/2 (1+cos(2pi*l/(len-1)))), while the at the edges the\n       function plus weights are evaluated only where defined */\n\n    sprintf(mes, \"Give length of smoothing kernel [5]\");\n    i = 1;\n    len = 5;\n    while ((i)) {\n      userint_tir(startinfv -> arel, &len, &nel, &def, \"TIRLEN=\", mes);\n      if (len < 2 || len > 99) {\n\tsprintf(mes, \"TIRLEN: Must be larger than 1\");\n\tdef = 4;\n\tcancel_tir(startinfv -> arel, \"TIRLEN=\", 2);\n      }\n      else if ((float) (len/2) == ((float) len) / 2.) {\n\tsprintf(mes, \"TIRLEN: Must be odd %f %f\", ((float) (len/2)), (((float) len) / 2.) );\n\tdef = 4;\n\tcancel_tir(startinfv -> arel, \"TIRLEN=\", 2);\n      }\n      else \n\t--i;\n    }\n    \n    /* Allocate the array for smoothing */\n    /* if (!(smarray = (double *) malloc((rpm -> nur*(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)+NSPARAMS)*sizeof(double)))) */\n    /* \t  goto error; */\n  }\n\n  /* Query the number of rings */\n  sprintf(mes, \"Give number of rings [%i]\", rpm -> nur);\n  i = 1;\n  def = 2;\n  nel = 1;\n  nrings = rpm -> nur;\n  while ((i)) {\n    userint_tir(startinfv -> arel, &nrings, &nel, &def, \"TIRNR=\", mes);\n    if (nrings < 2) {\n      sprintf(mes, \"TIRNR: Must be larger than 1\");\n      def = 4;\n      cancel_tir(startinfv -> arel, \"TIRNR=\", 2);\n    }\n    else \n      --i;\n  }\n  \n  /* Now allocate the radius array */\n  if (!(radii = (double *) malloc(nrings*sizeof(double))))\n    goto error;\n  \n  /* We read all values into the outarray */\n  tir_get_grid(log, rpm, log -> outarray);\n\n  /* BUGFIX: We copy that to the par array */\n  for (i = 0; i < rpm -> nur*(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)+NSPARAMS; ++i){\n    rpm -> par[i] = log -> outarray[i];\n  }\n\n  /* Now ask the user to give the radii */\n  sprintf(mes, \"Give radii\");\n  i = 1;\n  def = 2;\n  nel = nrings;\n\n  while ((i)) {\n\n    /* Fill it with the old values */\n    for (ringnr = 0; (ringnr < nrings) && (ringnr < rpm -> nur); ++ringnr) {\n      radii[ringnr] = rpm -> par[PRADI*rpm -> nur+ringnr];\n    }\n    \n    /* Fill the rest, extrapolating with the last stepwidth, this should work */\n    while (ringnr < nrings) {\n      radii[ringnr] = 2*radii[ringnr-1]-radii[ringnr-2];\n      ++ringnr;\n    }\n\n    /* Check if we can interpolate */\n    givrad = userdble_tir(startinfv -> arel, radii, &nel, &def, \"TIRRAD=\", mes);\n    if ((givrad < 2) && (givrad != 0)) {\n      sprintf(mes, \"TIRRAD: give more than 1 element\");\n      def = 4;\n      cancel_tir(startinfv -> arel, \"TIRRAD=\", 2);\n    }\n    else {\n\n      /* Check the first radius */\n      if (radii[0] != 0.0) {\n\tsprintf(mes, \"TIRRAD: First radius has to be 0.0\");\n\tdef = 4;\n\tcancel_tir(startinfv -> arel, \"TIRRAD=\", 2);\n      }\n      else {\n\n\t/* Extrapolate */\n\tif ((givrad))\n\t  while (givrad < nrings) {\n\t    radii[givrad] = 2*radii[givrad-1]-radii[givrad-2];\n\t    ++givrad;\n\t  }\n\n\t/* Check if the radii are in ascending order */\n\tfor (ringnr = 1; ringnr < nrings; ++ringnr) {\n\t  if (radii[ringnr] <= radii[ringnr-1]) {\n\t    i = 2;\n\t    break;\n\t  }\n\t}\n\tif (i == 2) {\n\t  sprintf(mes, \"TIRRAD: Radii must be in ascending order %i %f %f %f\", ringnr, radii[ringnr], radii[ringnr-1], radii[ringnr-2]);\n\t  def = 4;\n\t  i = 1;\n\t  cancel_tir(startinfv -> arel, \"TIRRAD=\", 2);\n\t}\n\telse\n\t  i = 0;\n      }\n    }\n  }\n  \n\n\n  /* Now we should have a proper array with radii */\n\n\n  /* Construct the format strings, a bit tricky */\n  *format = '%';\n  sprintf(format+1, \"+.%iE\", acc);\n  if (acc > 9)\n    sprintf(format+6, \" \");\n  else \n    sprintf(format+5, \" \");\n  *format2 = '%';\n  sprintf(format2+1, \"+.%iE\", acc+3);\n  if (acc > 6)\n    sprintf(format2+6, \" \");\n  else \n    sprintf(format2+5, \" \");\n  \n  i = 0;\n  currentname = defname;\n\n  /* From here on we freeze the input def */\n  if (startinfv -> arel[2]) {\n    if (!strcmp(startinfv -> arel[2] -> orifilename,currentname)) {\n      fprintf(stderr, \"Warning: Input deffile will be overwritten by output deffile\\n\");\n      simparse_scn_arel_timestamp_late(startinfv -> arel[2]);\n    }\n    else if (!strcmp(startinfv -> arel[2] -> orifilename,deintername)) {\n      fprintf(stderr, \"Warning: Input deffile will be overwritten by output smoothed deffile\\n\");\n      simparse_scn_arel_timestamp_late(startinfv -> arel[2]);\n    }\n    restimest = startinfv -> arel[2] -> timestamp;\n  }\n\n  while (i < 2) {\n    \n    if (*currentname != '\\0') {\n      \n      /* Try to open the output, we overwrite */\n      if (!(stream = fopen(currentname, \"w\")))\n\tgoto error;\n      \n      /* Now put the first line, copy from input */\n      tirout_a(startinfv -> arel, stream, \"LOGNAME=\");\n      /* Action should be taken over from prompt */\n      tirout_a(startinfv -> arel, stream, \"ACTION=\");\n      tirout_a(startinfv -> arel, stream, \"PROMPT=\");\n      tirout_a(startinfv -> arel, stream, \"NCORES=\");\n      fprintf(stream, \"\\n\");\n      tirout_a(startinfv -> arel, stream, \"INSET=\");\n      /* tirout_a(startinfv -> arel, stream, \"BOX=\"); */\n      tirout_a(startinfv -> arel, stream, \"OUTSET=\");\n      tirout_a(startinfv -> arel, stream, \"OUTCUBUP=\");\n      fprintf(stream, \"\\n\");\n      /*       tirout_a(startinfv -> arel, stream, \"OKAY=\"); */\n      tirout_a(startinfv -> arel, stream, \"PROGRESSLOG=\");\n      tirout_a(startinfv -> arel, stream, \"TEXTLOG=\");\n      fprintf(stream, \"\\n\");\n      tirout_a(startinfv -> arel, stream, \"BMIN=\");\n      tirout_a(startinfv -> arel, stream, \"BMAJ=\");\n      tirout_a(startinfv -> arel, stream, \"BPA=\");\n      tirout_a(startinfv -> arel, stream, \"RMS=\");\n      fprintf(stream, \"\\n\");\n      tirout_a(startinfv -> arel, stream, \"NDISKS=\");\n      fprintf(stream, \"NUR= %i\", nrings);\n      fprintf(stream, \"\\n\");\n \n      /* Now it depends on the file we are outputting */\n      if (currentname == defname) {\n\treparray = rpm -> par;\n      }\n      else {\n\tlm1 =len-1;\n\n\t/* Here, we have to filter */\n\tfor (j = 0; j < (NPARAMS+(rpm -> ndisks-1)*NDPARAMS); ++j) {\n\t  \n\t  /* Important: do not Hanning smooth the radii */\n\t  if (j != PRADI) {\n\t  {\n     \t    \n\t    for (k = 0; k < rpm -> nur; ++k) {\n\n\t      smsum = 0.0;\n\t      smweightsum = 0.0;\n\t      for (l = -len/2+1; l < len/2+1-1; ++l) {\n\t\t/* if we exceed the ringnumbers, we take in the values at\n\t\t   the border */\n\t\t/* if ((k+l) < 0) { */\n\t\t/*   valcur = rpm -> par[j*rpm -> nur]; */\n\t\t/* } */\n\t\t/* else if ((k+l) > rpm -> nur - 1) { */\n\t\t/*   valcur = rpm -> par[(j+1)*rpm -> nur-1]; */\n\t\t/* } */\n\t\t/* else { */\n\t\tm = k+l;\n\t\tif (m >= 0 && m < rpm -> nur) {\n\t\t  weight = 0.5*(1+cos(TWOPI*l/lm1));\n\t\t  smsum = smsum + weight * rpm -> par[j*rpm -> nur+m];\n\t\t  smweightsum = smweightsum + weight;\n\t\t}\n\t      }\n\n\t      /* Use outarray as a buffer */\n\t      log -> outarray[j*rpm -> nur+k] = smsum/smweightsum;\n\n\t\t/* Sort the array */\n\t      /* maths_bubble(smarray, len); */\n       \n\t      /* if (!(j == PRADI) && ((n = ((j-NSSDPARAMS)%NDPARAMS + NSSDPARAMS)) == PXPOS || n == PYPOS)) */\n\t      /* \tfprintf(stream, format2, smarray[(len-1)/2]); */\n\t      /* else */\n\t      /* \tfprintf(stream, format, smarray[(len-1)/2]); */\n\t      \n\t    }\n\t  }\n      \n\t}\n\t}\n\treparray = log -> outarray;\n      }\n\n      /* put out the radii */\n      ftstab_putcoltitl(key, RADI);\n      fprintf(stream, \"%8s= \", key);\n      for (m = 0; m < nrings; ++m) {\n\tfprintf(stream, format, radii[m]);\n      }\n      fprintf(stream, \"\\n\");\n\n      for (j = NSSDPARAMS; j < (NPARAMS+(rpm -> ndisks-1)*NDPARAMS); ++j) {\n\t\n\t/************/\n\t/************/\n\tk = 0;\n\twhile (k < rpm -> nur) {\n\t  if ((reparray[j*rpm -> nur+k]))\n\t    break;\n\t    ++k;\n\t}\n\tif (k < rpm -> nur) {\n\t  \n\t  /************/\n\t  \n\t  /* Put the title */\n\t  ftstab_putcoltitl(key, j+1);\n\t  fprintf(stream, \"%8s= \", key);\n\t  \t  \n\t    for (m = 0; m < nrings; ++m) {\n\t      \n\t      /* Not sure if this is required, but do it anyway */\n\t      gsl_interp_accel_reset(rpm -> gsl_interp_accelarray[j-NSSDPARAMS]);\n\t      \n\t      /* Very sure that this is a requirement; a test has shown */\n\t      /* gsl_interp_init(rpm -> gsl_interparray[j-NSSDPARAMS],rpm -> par+PRADI*rpm -> nur, rpm -> par + rpm -> nur*j, rpm -> nur); */\n\t      gsl_interp_init(rpm -> gsl_interparray[j-NSSDPARAMS],reparray+PRADI*rpm -> nur, reparray + rpm -> nur*j, rpm -> nur);\n\t      \n\t      /* Search the first radius that is greater than the current, don't care about efficiency */\n\t      /* for (k = 1; k < rpm -> nur; ++k) { */\n\t      /* \tif (radii[m] < reparray[PRADI*rpm -> nur+k]) */\n\t      /* \t  break; */\n\t      /* } */\n\t      \n\t      /* Now we can interpolate or extrapolate */\n\t      /* Check for radius here */\n\t      if ( radii[m] < reparray[PRADI*rpm -> nur+rpm -> nur-1]) {\n\t\t/* dpdr = (reparray[j*rpm -> nur+k]-reparray[j*rpm -> nur+k-1])/(reparray[PRADI*rpm -> nur+k]-reparray[PRADI*rpm -> nur+k-1]); */\n\t\t/* dpdr = reparray[j*rpm -> nur+k-1]+dpdr*(radii[m]-reparray[PRADI*rpm -> nur+k-1]); */\n\t\tdpdr = gsl_interp_eval(rpm -> gsl_interparray[j-NSSDPARAMS], rpm -> par+PRADI*rpm -> nur, rpm -> par + rpm -> nur*j, radii[m], rpm -> gsl_interp_accelarray[j-NSSDPARAMS]);\n\t      }\n\t      else {\n\t\tdpdr = reparray[(j+1)*rpm -> nur-1];\n\t      }\n\n\t      if (!(j == PRADI) && ((n = ((j-NSSDPARAMS)%NDPARAMS + NSSDPARAMS)) == PXPOS || n == PYPOS)) {\n\t\tfprintf(stream, format2, dpdr);\n\t      }\n\t      else {\n\t      \tfprintf(stream, format, dpdr);\n\t      }\n\t    } \n\t    fprintf(stream, \"\\n\");\n\t}   \n      }\n      \n      for (j = 0; j < NSPARAMS; ++j) {\n\t  ftstab_putcoltitl(key, (NPARAMS+(rpm -> ndisks-1)*NDPARAMS)+j+1);\n\t  fprintf(stream, \"%8s= \", key);\n\t  fprintf(stream, format, rpm -> par[(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur+j]);\n\t}\n            \n\n   \n      fprintf(stream, \"\\n\");\n      tirout_a(startinfv -> arel, stream, \"LTYPE=\");\n      for (disk = 1; disk < rpm -> ndisks; ++disk) {\n\tsprintf(placer, \"LTYPE_%i=\" , disk+1);\t\n\ttirout_a(startinfv -> arel, stream, placer);\n      }\n      \n      /* Now put the rest of the input to the file */\n      fprintf(stream, \"\\n\");\n      tirout_a(startinfv -> arel, stream, \"CFLUX=\");\n      for (disk = 1; disk < rpm -> ndisks; ++disk) {\n\tsprintf(placer, \"CFLUX_%i=\" , disk+1);\t\n\ttirout_a(startinfv -> arel, stream, placer);\n      }\n      tirout_a(startinfv -> arel, stream, \"PENALTY=\");\n      tirout_a(startinfv -> arel, stream, \"WEIGHT=\");\n      tirout_a(startinfv -> arel, stream, \"RADSEP=\");\n      /*       tirout_a(startinfv -> arel, stream, \"MEMMODE=\"); */\n      tirout_a(startinfv -> arel, stream, \"INIMODE=\");\n      tirout_a(startinfv -> arel, stream, \"ISEED=\");\n      fprintf(stream, \"\\n\");\n      tirout_a(startinfv -> arel, stream, \"FITMODE=\");\n      tirout_a(startinfv -> arel, stream, \"LOOPS=\");\n      tirout_a(startinfv -> arel, stream, \"MAXITER=\");\n      tirout_a(startinfv -> arel, stream, \"CALLITE=\");\n      tirout_a(startinfv -> arel, stream, \"SIZE=\");\n      tirout_a(startinfv -> arel, stream, \"INTY=\");\n      tirout_a(startinfv -> arel, stream, \"INDINTY=\");\n      \n      /* We want to hide the whole pswarm issue from the user, so we only spit it out if there have been changes to the defaults */\n      if (fit -> psse != PSW_PSSE_DEF) tirout_a(startinfv -> arel, stream, \"PSSE=\");\n      if (fit -> psnp != PSW_PSNP_DEF) tirout_a(startinfv -> arel, stream, \"PSNP=\");\n      if (fit -> psco != PSW_PSCO_DEF) tirout_a(startinfv -> arel, stream, \"PSCO=\");\n      if (fit -> psso != PSW_PSSO_DEF) tirout_a(startinfv -> arel, stream, \"PSSO=\");\n      if (fit -> psmv != PSW_PSMV_DEF) tirout_a(startinfv -> arel, stream, \"PSMV=\");\n      if (fit -> psnf != PSW_PSNF_DEF) tirout_a(startinfv -> arel, stream, \"PSNF=\");\n      if (fit -> psii != PSW_PSII_DEF) tirout_a(startinfv -> arel, stream, \"PSII=\");\n      if (fit -> psfi != PSW_PSFI_DEF) tirout_a(startinfv -> arel, stream, \"PSFI=\");\n      if (fit -> psid != PSW_PSID_DEF) tirout_a(startinfv -> arel, stream, \"PSID=\");\n      if (fit -> psdd != PSW_PSDD_DEF) tirout_a(startinfv -> arel, stream, \"PSDD=\");\n\t\n      fprintf(stream, \"\\n\");\n      /*       tirout_a(startinfv -> arel, stream, \"ANSTART=\"); */\n      /*       tirout_a(startinfv -> arel, stream, \"ANEND=\"); */\n      /*       tirout_a(startinfv -> arel, stream, \"ANSTEPS=\"); */\n      /*       tirout_a(startinfv -> arel, stream, \"ISEED=\"); */\n      /*       fprintf(stream, \"\\n\"); */\n      fprintf(stream, \"VARY= %s\\n\", fit -> varyhstr);\n      tirout_a(startinfv -> arel, stream, \"VARINDX=\");\n      /*       tirout_a(startinfv -> arel, stream, \"VARYMULT=\"); */\n      /*       tirout_a(startinfv -> arel, stream, \"VARYSING= \"); */\n      tirout_a(startinfv -> arel, stream, \"PARMAX=\");\n      tirout_a(startinfv -> arel, stream, \"PARMIN=\");\n      tirout_a(startinfv -> arel, stream, \"MODERATE=\");\n      tirout_a(startinfv -> arel, stream, \"DELSTART=\");\n      tirout_a(startinfv -> arel, stream, \"DELEND=\");\n      tirout_a(startinfv -> arel, stream, \"ITESTART=\");\n      tirout_a(startinfv -> arel, stream, \"ITEEND=\");\n      tirout_a(startinfv -> arel, stream, \"SATDELT=\");\n      tirout_a(startinfv -> arel, stream, \"MINDELTA=\");\n      fprintf(stream, \"\\n\");\n      tirout_a(startinfv -> arel, stream, \"REGPARA=\");\n      if ((fit -> reg_contv[0])) {\n\ttirout_a(startinfv -> arel, stream, \"REGDENO=\");\n\ttirout_a(startinfv -> arel, stream, \"REGNUME=\");\n\ttirout_a(startinfv -> arel, stream, \"REGTHRE=\");\n\ttirout_a(startinfv -> arel, stream, \"REGWIDT=\");\n\ttirout_a(startinfv -> arel, stream, \"REGAMPL=\");\n\ttirout_a(startinfv -> arel, stream, \"REGASTE=\");\n\ttirout_a(startinfv -> arel, stream, \"REGAMPD=\");\n      }\n      fprintf(stream, \"\\n\");\n      /*       tirout_a(startinfv -> arel, stream, \"TABLE=\"); */\n      /*       tirout_a(startinfv -> arel, stream, \"DISTANCE=\"); */\n      /*       tirout_a(startinfv -> arel, stream, \"REFRING=\"); */\n      /*       tirout_a(startinfv -> arel, stream, \"BIGTABLE=\"); */\n      fprintf(stream, \"\\n\");\n      tirout_a(startinfv -> arel, stream, \"TIRDEF=\");\n      tirout_a(startinfv -> arel, stream, \"TIRSMO=\");\n      /*       tirout_a(startinfv -> arel, stream, \"TIRACC=\"); */\n      /*       tirout_a(startinfv -> arel, stream, \"TIRLEN=\"); */\n      fprintf(stream, \"\\n\");\n      /*       tirout_a(startinfv -> arel, stream, \"HISNAME=\"); */\n      /*       tirout_a(startinfv -> arel, stream, \"HISTARTROW=\"); */\n      /*       tirout_a(startinfv -> arel, stream, \"HISTENDROW=\"); */\n      /*       tirout_a(startinfv -> arel, stream, \"HISKEY1=\"); */\n      /*       tirout_a(startinfv -> arel, stream, \"HISRING1=\"); */\n      /*       tirout_a(startinfv -> arel, stream, \"HISMIN1=\"); */\n      /*       tirout_a(startinfv -> arel, stream, \"HISMAX1=\"); */\n      /*       tirout_a(startinfv -> arel, stream, \"HISBINS1=\"); */\n      /*       tirout_a(startinfv -> arel, stream, \"HISDELTA1=\"); */\n      /*       tirout_a(startinfv -> arel, stream, \"HISKEY2=\"); */\n      /*       tirout_a(startinfv -> arel, stream, \"HISRING2=\"); */\n      /*       tirout_a(startinfv -> arel, stream, \"HISMIN2=\"); */\n      /*       tirout_a(startinfv -> arel, stream, \"HISMAX2=\"); */\n      /*       tirout_a(startinfv -> arel, stream, \"HISBINS2=\"); */\n      /*       tirout_a(startinfv -> arel, stream, \"HISDELTA2=\"); */\n      /*       fprintf(stream, \"\\n\"); */\n      tirout_a(startinfv -> arel, stream, \"COOLGAL=\");\n      tirout_a(startinfv -> arel, stream, \"COOLBEAM=\");\n      fprintf(stream, \"\\n\");\n      /*       tirout_a(startinfv -> arel, stream, \"RECT=\"); */\n      /*       tirout_a(startinfv -> arel, stream, \"BIGRECT=\"); */\n      /*       fprintf(stream, \"\\n\"); */\n      tirout_a(startinfv -> arel, stream, \"TILT=\");\n      tirout_a(startinfv -> arel, stream, \"BIGTILT=\");\n      fprintf(stream, \"\\n\");\n      /*       tirout_a(startinfv -> arel, stream, \"INCLINO=\");    */\n      /*       tirout_a(startinfv -> arel, stream, \"IN_REFINE=\"); */\n      fprintf(stream, \"\\n\");\n      tirout_a(startinfv -> arel, stream, \"GR_DEVICE=\");\n      tirout_a(startinfv -> arel, stream, \"GR_PARMS=\");\n      tirout_a(startinfv -> arel, stream, \"GR_XMIN=\");\n      tirout_a(startinfv -> arel, stream, \"GR_XMAX=\");\n      tirout_a(startinfv -> arel, stream, \"GR_MR=\");\n      tirout_a(startinfv -> arel, stream, \"GR_ML=\");\n      tirout_a(startinfv -> arel, stream, \"GR_TXHT=\");\n      tirout_a(startinfv -> arel, stream, \"GR_SBHT=\");\n      tirout_a(startinfv -> arel, stream, \"GR_LGND=\");\n      tirout_a(startinfv -> arel, stream, \"GR_SBRP=\");\n\n      for (j = 1; j <= nrplts; ++j) {\n\tfprintf(stream, \"\\n\");\n\tsprintf(inqstr, \"GR_COL_%i=\", j);\n\ttirout_a(startinfv -> arel, stream, inqstr);\n\tsprintf(inqstr, \"GR_LINES_%i=\", j);\n\ttirout_a(startinfv -> arel, stream, inqstr);\n\tsprintf(inqstr, \"GR_INTERP_%i=\", j);\n\ttirout_a(startinfv -> arel, stream, inqstr);\n\tsprintf(inqstr, \"GR_ERRB_%i=\", j);\n\ttirout_a(startinfv -> arel, stream, inqstr);\n\tsprintf(inqstr, \"GR_YMIN_%i=\", j);\n\ttirout_a(startinfv -> arel, stream, inqstr);\n\tsprintf(inqstr, \"GR_YMAX_%i=\", j);\n\ttirout_a(startinfv -> arel, stream, inqstr);\n\t/*  sprintf(inqstr, \"GR_NPAD_%i=\", j); */\n\t/*  tirout_a(startinfv -> arel, stream, inqstr); */\n\t/*  sprintf(inqstr, \"GR_XPAD_%i=\", j); */\n\t/*  tirout_a(startinfv -> arel, stream, inqstr); */\n\t/*  sprintf(inqstr, \"GR_YPAD_%i=\", j); */\n\t/*  tirout_a(startinfv -> arel, stream, inqstr); */\n\t/*  sprintf(inqstr, \"GR_ERAD_%i=\", j); */\n\t/*  tirout_a(startinfv -> arel, stream, inqstr); */\n\t/*  sprintf(inqstr, \"GR_EBAD_%i=\", j); */\n\t/*  tirout_a(startinfv -> arel, stream, inqstr); */\n\t/*  sprintf(inqstr, \"GR_COAD_%i=\", j); */\n\t/*  tirout_a(startinfv -> arel, stream, inqstr); */\n\t/*  sprintf(inqstr, \"GR_LIAD_%i=\", j); */\n\t/*  tirout_a(startinfv -> arel, stream, inqstr); */\n\t/*  sprintf(inqstr, \"GR_INTERPAD_%i_%i=\", j); */\n\t/*  tirout_a(startinfv -> arel, stream, inqstr); */\n      }\n      fclose(stream);\n    }\n    currentname = deintername;\n    ++i;\n  }\n  \n  if (startinfv -> arel[2]) {\n    startinfv -> arel[2] -> timestamp = restimest;\n  }\n\n\n  /* Reset outarray to the original state */\n  for (i = 0; i < rpm -> nur*(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)+NSPARAMS; ++i){\n    log -> outarray[i] = rpm -> par[i];\n  }\n\n  \n  free(radii);\n  if ((defname))\n    free(defname);\n  if ((deintername))\n    free(deintername);\n  if ((varystr))\n    freeparsed(varystr);\n  return 1;\n  \n error:\n  if ((radii))\n    free(radii);\n  if ((defname))\n    free(defname);\n  if ((deintername))\n    free(deintername);\n  if ((varystr))\n    freeparsed(varystr);\n\n  return 0;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Copies a part of the gipsy input to a stream */\nstatic int tirout_a(simparse_scn_arel **arel, FILE *stream, char *keyword)\n{\n  /* int def = 2; */\n  /* int length; */\n  /* char mes[2]; */\n  /* int i; */\n  char *varyhstr = NULL;\n  int keypres, nread, nreturned;\n\n  if (simparse_scn_arel_readval_stringwhitesp(arel, keyword, \"\", 0, \"\", 0, -1, 0, 0, &keypres, &nread, &nreturned, &varyhstr)) {\n    if ((varyhstr))\n      free(varyhstr);\n    return 1;\n  }\n  fprintf(stream, \"%s%s\\n\", keyword, varyhstr);\n  free(varyhstr);\n  return 0;\n\n  /* sprintf(mes, \"A\"); */\n\n  /* Initialise */\n  /* { */\n  /*   for (i = 0; i < VARYHSTRELES-2; ++i) { */\n  /*     input[i] = ' '; */\n  /*   } */\n  /*   input[i] = '\\0'; */\n    \n    /* Get the value */\n    /* length = usertext_tir(input, &def, keyword,mes); */\n    /* input[length] = '\\0'; */\n    \n    /* Copy it into the file */\n  /*   fprintf(stream, \"%s %s\\n\", keyword); */\n  /* } */\n\n  return 0;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Get a double parameter */\nstatic int get_parameter_double(startinf *startinfv, loginf *log, hdrinf *hdr, ringparms *rpm, char *mess, char *parname, int ident, int force)\n{\n  int def;      /* Any default mode */\n  int nel;      /* Number of elements */\n  int i; /* Simple control variables */\n  int nident;\n\n  /**************/\n  /**************/\n/*        int obsint = 0; */\n/*        char obsmes[80];  */\n  /**************/\n\n\n       /* Make this transformation to identify higher-order VSYS XPOS and YPOS */\n  nident = (ident-NSSDPARAMS)%NDPARAMS + NSSDPARAMS;\n\n  /* Read values that are needed only in this module */\n\n  /* First from the log if present */\n  /* Default is 0 */\n  for (i = 0; i < rpm -> nur; ++i)\n    *(rpm -> par + rpm -> nur*ident+i) = 0.0;\n  def = force;\n    \n  nel = 0;\n\n  /* This is the third parameter sequence */\n  if (!(startinfv -> firstrun))\n    cancel_tir(startinfv -> arel, parname, 0);\n\n  nel = userdble_tir(startinfv -> arel, rpm -> par+ident*rpm -> nur, &rpm -> nur, &def, parname, mess);\n  \n  if (!nel)\n    nel = rpm -> nur;\n  \n  /* Check for errors and extrapolate */\n\n  for (i = 0; i < rpm -> nur; ++i) {\n    if (i > nel-1) {\n      rpm -> par[ident*rpm -> nur+i] = rpm -> par[ident*rpm -> nur+nel-1];\n    }\n    else {\n      if ((ident == PRADI) || !(nident == PXPOS || nident == PVSYS || nident == PYPOS)) {\n\t\t  rpm -> par[ident*rpm ->nur+i] =  dparamtointern(rpm -> par[ident*rpm ->nur+i], ident+1, hdr, rpm -> ndisks);\n      }\n    }\n  }\n    \n  return 0;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Produces the tiltogram output of tirific */\nstatic int tiltout(startinf *startinfv, loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit)\n{\n  int i,j;\n\n  /* int def = 2; */\n  /* int nel = 1; */\n  /* char mes[81]; */\n  char *filename = NULL;\n  qfits_header *header = NULL;\n  float *array = NULL;\n  double nrefr[3];\n  double nr[3];\n  char value[21];\n\n  char **varystr = NULL;\n  int keypres, nread, nreturned;\n\n\n\n  /* Initialise the input array */\n  /* for (i = 0; i < 200; ++i) { */\n  /*   filename[i] = ' '; */\n  /* } */\n  /* filename[200] = '\\0'; */\n  \n  /* sprintf(mes, \"Give a filename for a tiltogram output\"); */\n  /* userchar_tir(filename, &nel, &def, \"TILT=\", mes); */\n  /* termsinglestr(filename); */\n\n  /* cancel_tir(startinfv -> arel, \"TILT\"); */\n\n  if (simparse_scn_arel_readval_stringlist(startinfv -> arel, \"TILT\", \"Give a filename for a tiltogram output.\", 0, NULL, 0, -1, 0, 0, &keypres, &nread, &nreturned, &varystr))\n    goto error;\n  \n  if ((varystr[0])) {\n    if (!(filename = simparse_copystring(varystr[0]))) {\n      goto error;\n    }\n  }\n  else {\n    if (!(filename = simparse_copystring(\"\"))) {\n      goto error;\n    }\n  }\n  \n  freeparsed(varystr);\n  varystr = NULL;\n\n  \n  if (*filename != '\\0') {\n    \n    if (rpm -> nur < 2)\n      return 1;\n    \n    /* Read in the values */\n    tir_get_grid(log, rpm, log -> outarray);\n    \n    /* Make a header */\n    /* The bitpix is -32 */\n    if (!(header = ftsout_putcard(header, \"BITPIX\",\"-32\"))) \n      goto error;\n    \n    /* The number of axes is set to three */\n    if (!ftsout_putcard(header, \"NAXIS\",\"2\")) \n      goto error;\n    \n    /* Now get the axis numbers */\n    sprintf(value, \"%i\", rpm -> nur);\n    if (!ftsout_putcard(header, \"NAXIS1\",value))\n      goto error;\n    sprintf(value, \"%i\", rpm -> nur);\n    if (!ftsout_putcard(header, \"NAXIS2\",value))\n      goto error;\n    \n    /* May contain an extension */\n    if (!ftsout_putcard(header, \"EXTEND\",\"T\"))\n      goto error;\n    \n    /* These are clear */\n    if (!ftsout_putcard(header, \"BSCALE\",\"1\"))\n      goto error;\n    if (!ftsout_putcard(header, \"BZERO\",\"0\"))\n      goto error;\n    \n    /* The bunit is Jy*km/s/beam, while this is the 3d beam */\n    if (!ftsout_putcard(header, \"BUNIT\",\"'deg               '\"))\n      goto error;\n    \n    /* The cdelt is the difference between the first two rings */  \n    sprintf(value, \"%.12E\", log -> outarray[PRADI*rpm -> nur+1]-log -> outarray[PRADI*rpm -> nur]);\n    if (!ftsout_putcard(header, \"CDELT1\", value))\n      goto error;\n    \n    /* The crpix is 1 */\n    sprintf(value, \"%.12E\", 1.0);\n    if (!ftsout_putcard(header, \"CRPIX1\", value))\n      goto error;\n    \n    /* The crval in user units -> arcsec is 0 */\n    sprintf(value, \"%.12E\", 0.0);\n    if (!ftsout_putcard(header, \"CRVAL1\", value))\n      goto error;\n    \n    /* ctype is angle ... */\n    if (!ftsout_putcard(header, \"CTYPE1\", \"'ANGLE   '\"))\n      goto error;\n    if (!ftsout_putcard(header, \"CUNIT1\", \"'arcsec            '\"))\n      goto error;\n    \n    /* The cdelt is the difference between the first two rings */  \n    sprintf(value, \"%.12E\", log -> outarray[PRADI*rpm -> nur+1]-log -> outarray[PRADI*rpm -> nur]);\n    if (!ftsout_putcard(header, \"CDELT2\", value))\n      goto error;\n    \n    /* The crpix is 1 */\n    sprintf(value, \"%.12E\", 1.0);\n    if (!ftsout_putcard(header, \"CRPIX2\", value))\n      goto error;\n    \n    /* The crval in user units -> arcsec is 0 */\n    sprintf(value, \"%.12E\", 0.0);\n    if (!ftsout_putcard(header, \"CRVAL2\", value))\n      goto error;\n    \n    /* ctype is angle ... */\n    if (!ftsout_putcard(header, \"CTYPE2\", \"'ANGLE   '\"))\n      goto error;\n    if (!ftsout_putcard(header, \"CUNIT2\", \"'arcsec            '\"))\n      goto error;\n    \n    /* After that allocate the memory */\n    if (!(array = (float *) malloc(rpm -> nur*rpm -> nur*sizeof(float))))\n      goto error;\n    \n    /* Convert to internal units (radian) */\n    for (i = 0; i < (NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur + NSPARAMS; ++i) {\n      rpm -> par[i] = log -> outarray[i];\n    }\n    changetointern(rpm -> par, rpm -> nur, hdr, rpm -> ndisks);\n\n    /* Now fill the array */\n    for (i = 0; i < rpm -> nur; ++i) {\n      /* Now get the normal vector of the reference ring */\n      nrefr[0] = sin(rpm -> par[PINCL*rpm -> nur+i])*sinf(rpm -> par[PPA*rpm -> nur+i]);\n      nrefr[1] = -sin(rpm -> par[PINCL*rpm -> nur+i])*cosf(rpm -> par[PPA*rpm -> nur+i]);\n      nrefr[2] = cos(rpm -> par[PINCL*rpm -> nur+i]);\n      \n      /* Now we read in the values */\n      for (j = 0; j < rpm -> nur; ++j) {\n nr[0] = sin(rpm -> par[PINCL*rpm -> nur+j])*sinf(rpm -> par[PPA*rpm -> nur+j]);\n nr[1] = -sin(rpm -> par[PINCL*rpm -> nur+j])*cosf(rpm -> par[PPA*rpm -> nur+j]);\n nr[2] = cos(rpm -> par[PINCL*rpm -> nur+j]);\n\n /* This is the arcus */\n array[i+rpm -> nur*j] = (nr[0]*nrefr[0]+nr[1]*nrefr[1]+nr[2]*nrefr[2]) > 1?0.0:RADTODEG*acos(nr[0]*nrefr[0]+nr[1]*nrefr[1]+nr[2]*nrefr[2]);\n      }\n    }\n\n    /* Put it to the disk */\n    ftsout_writeimage(filename, array, header, rpm -> nur, rpm -> nur);\n\n    /* Clear things */\n    ftsout_header_destroy(header);\n    free(array);\n  }\n  /* Initialise the input array */\n  /* for (i = 0; i < 19; ++i) { */\n  /*   filename[i] = ' '; */\n  /* } */\n  /* filename[i] = '\\0'; */\n  \n  /* sprintf(mes, \"Give a filename for a big tiltogram output\"); */\n  /* userchar_tir(filename, &nel, &def, \"BIGTILT=\", mes); */\n  /* termsinglestr(filename); */\n  \n  if ((filename)){\n    free(filename);\n    filename = NULL;\n  }\n\n  /* cancel_tir(startinfv -> arel, \"BIGTILT\"); */\n\n  if (simparse_scn_arel_readval_stringlist(startinfv -> arel, \"BIGTILT\", \"Give a filename for a big tiltogram output\", 0, NULL, 0, -1, 0, 0, &keypres, &nread, &nreturned, &varystr))\n    goto error;\n  \n  if ((varystr[0])) {\n    if (!(filename = simparse_copystring(varystr[0]))) {\n      goto error;\n    }\n  }\n  else {\n    if (!(filename = simparse_copystring(\"\"))) {\n      goto error;\n    }\n  }\n  \n  freeparsed(varystr);\n  varystr = NULL;\n\n  if (*filename != '\\0') {\n    \n    if (rpm -> nr < 2)\n      return 1;\n    \n    /* Make a header */\n    /* The bitpix is -32 */\n    header = NULL;\n\n    if (!(header = ftsout_putcard(header, \"BITPIX\",\"-32\"))) \n      goto error;\n    \n    /* The number of axes is set to three */\n    if (!ftsout_putcard(header, \"NAXIS\",\"2\")) \n      goto error;\n    \n    /* Now get the axis numbers */\n    sprintf(value, \"%i\", rpm -> nr);\n    if (!ftsout_putcard(header, \"NAXIS1\",value))\n      goto error;\n    sprintf(value, \"%i\", rpm -> nr);\n    if (!ftsout_putcard(header, \"NAXIS2\",value))\n      goto error;\n    \n    /* May contain an extension */\n    if (!ftsout_putcard(header, \"EXTEND\",\"T\"))\n      goto error;\n    \n    /* These are clear */\n    if (!ftsout_putcard(header, \"BSCALE\",\"1\"))\n      goto error;\n    if (!ftsout_putcard(header, \"BZERO\",\"0\"))\n      goto error;\n    \n    /* The bunit is Jy*km/s/beam, while this is the 3d beam */\n    if (!ftsout_putcard(header, \"BUNIT\",\"'deg     '\"))\n      goto error;\n    \n    /* The cdelt is the width of one ring */  \n    sprintf(value, \"%.12E\", dinterntoparam(rpm -> radsep, RADI, hdr, rpm -> ndisks));\n    if (!ftsout_putcard(header, \"CDELT1\", value))\n      goto error;\n    \n    /* The crpix is 1 */\n    sprintf(value, \"%.12E\", 1.0);\n    if (!ftsout_putcard(header, \"CRPIX1\", value))\n      goto error;\n    \n    /* The crval in user units -> arcsec is 1/2 radsep */\n    sprintf(value, \"%.12E\", dinterntoparam(rpm -> radsep, RADI, hdr, rpm -> ndisks)/2);\n    if (!ftsout_putcard(header, \"CRVAL1\", value))\n      goto error;\n    \n    /* ctype is angle ... */\n    if (!ftsout_putcard(header, \"CTYPE1\", \"'ANGLE             '\"))\n      goto error;\n    if (!ftsout_putcard(header, \"CUNIT1\", \"'arcsec            '\"))\n      goto error;\n    \n    /* The cdelt is the width of one ring */  \n    sprintf(value, \"%.12E\", dinterntoparam(rpm -> radsep, RADI, hdr, rpm -> ndisks));\n    if (!ftsout_putcard(header, \"CDELT2\", value))\n      goto error;\n    \n    /* The crpix is 1 */\n    sprintf(value, \"%.12E\", 1.0);\n    if (!ftsout_putcard(header, \"CRPIX2\", value))\n      goto error;\n    \n    /* The crval in user units -> arcsec is 1/2 radsep */\n    sprintf(value, \"%.12E\", dinterntoparam(rpm -> radsep, RADI, hdr, rpm -> ndisks)/2);\n    if (!ftsout_putcard(header, \"CRVAL2\", value))\n      goto error;\n    \n    /* ctype is angle ... */\n    if (!ftsout_putcard(header, \"CTYPE2\", \"'ANGLE             '\"))\n      goto error;\n    if (!ftsout_putcard(header, \"CUNIT2\", \"'arcsec            '\"))\n      goto error;\n    \n    /* After that allocate the memory */\n    if (!(array = (float *) malloc(rpm -> nr*rpm -> nr*sizeof(float))))\n      goto error;\n\n    /* Read in the values */\n    tir_get_grid(log, rpm, log -> outarray);\n\n    /* Convert to internal units (radian) */\n    for (i = 0; i < (NPARAMS+(rpm -> ndisks-1)*NDPARAMS)*rpm -> nur + NSPARAMS; ++i) {\n      rpm -> par[i] = log -> outarray[i];\n    }\n    changetointern(rpm -> par, rpm -> nur, hdr, rpm -> ndisks);\n    for (i = rpm -> nur*NSSDPARAMS; i < rpm->nur *(NSSDPARAMS+NDPARAMS*rpm->ndisks); ++i)\n      rpm -> chapar[i] = 1;\n    if (changedependent(rpm, rpm -> par, fit -> index, rpm -> chapar) < 0)\n      goto error;\n    interpover(rpm, rpm -> radsep, 0, NULL, fit -> index);\n\n    /* Now fill the array */\n    for (i = 0; i < rpm -> nr; ++i) {\n      /* Now get the normal vector of the reference ring */\n      nrefr[0] = sin(rpm -> modpar[PINCL*rpm -> nr+i])*sinf(rpm -> modpar[PPA*rpm -> nr+i]);\n      nrefr[1] = -sin(rpm -> modpar[PINCL*rpm -> nr+i])*cosf(rpm -> modpar[PPA*rpm -> nr+i]);\n      nrefr[2] = cos(rpm -> modpar[PINCL*rpm -> nr+i]);\n      \n      /* Now we read in the values */\n      for (j = 0; j < rpm -> nr; ++j) {\n nr[0] = sin(rpm -> modpar[PINCL*rpm -> nr+j])*sinf(rpm -> modpar[PPA*rpm -> nr+j]);\n nr[1] = -sin(rpm -> modpar[PINCL*rpm -> nr+j])*cosf(rpm -> modpar[PPA*rpm -> nr+j]);\n nr[2] = cos(rpm -> modpar[PINCL*rpm -> nr+j]);\n\n /* This is the arcus */\n array[i+rpm -> nr*j] = (nr[0]*nrefr[0]+nr[1]*nrefr[1]+nr[2]*nrefr[2]) > 1?0.0:RADTODEG*acos(nr[0]*nrefr[0]+nr[1]*nrefr[1]+nr[2]*nrefr[2]);\n      }\n    }\n\n    /* Put it to the disk */\n    ftsout_writeimage(filename, array, header, rpm -> nr, rpm -> nr);\n\n    /* Clear things */\n    ftsout_header_destroy(header);\n    free(array);\n  }\n  free(filename);\n\n  return 1;\n\n error:\n  if ((header))\n    ftsout_header_destroy(header);\n  if ((array))\n    free(array);\n  if ((filename))\n    free(filename);\n  if ((varystr))\n    freeparsed(varystr);\n  return 0;\n}\n\n/* ------------------------------------------------------------ */\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Produces the tip-lon output of tirific  */\n\nstatic int briggsout(startinf *startinfv, loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit)\n{  \n  char mes[81];\n  int i, j, ok, nel, def, dev;\n\n  char *br_device = NULL;\n  double br_pa;\n  float pa_float;\n  double br_incl;\n  double pa;\n  double inc;\n  int br_annr;\n  float rmax;\n  float *br_angl = NULL;\n\n  int br_swdth;\n  int br_cwdth;\n  int br_lwdth;\n  int br_col = 1;\n  int br_refl;\n  int numplpts;\n\n  float *xarray = NULL;\n  float *xlarray = NULL;\n  float *yarray = NULL;\n  float *dummyarray = NULL;\n  float *ylarray = NULL;\n\n  double nrefr[3];\n  double rota[3];\n\n  int nread, nreturned, keypres;\n  char **varystr = NULL;\n\n  /**************/\n   /**************/ \n/*     int obsint = 0;   */\n/*     char obsmes[80];   */\n  /**************/\n  /**************/\n  /**************/\n/* sprintf(obsmes, \"graph: x: %.2f y: %.2f\", x,y); */\n/* anyout_tir(&obsint, obsmes); */\n  /**************/\n\n  /* Keywords:\n     BR_DEVICE= pgplot device\n     BR_PA= position angle of reference ring\n     BR_INCL= inclination of reference ring\n     BR_ANNR= circles to plot\n     BR_ANGL= circle radii in deg\n     BR_SWDTH= dot width\n     BR_CWDTH= circle width\n     BR_LWDTH= line width\n     BR_REFL= Plot reference line?\n     BR_COL= Colour of dots and lines\n  */\n\n\n  /* Ask the user for the output device */\n  /* for (j = 0; j < 200; ++j) { */\n  /*   br_device[j] = ' '; */\n  /* } */\n  /* br_device[200] = '\\0'; */\n  \n  /* sprintf(mes, \"Give graphics (pgplot) device:\"); */\n  /* def = 2; */\n  /* nel = 1; */\n  /* userchar_tir(br_device, &nel, &def, \"BR_DEVICE=\", mes); */\n  /* termsinglestr(br_device); */\n\n  /* cancel_tir(startinfv -> arel, \"BR_DEVICE\"); */\n\n  if (simparse_scn_arel_readval_stringlist(startinfv -> arel, \"BR_DEVICE\", \"Give a progress file name for no point actually when you can read this.\", 0, NULL, 0, -1, 0, 0, &keypres, &nread, &nreturned, &varystr))\n    goto error;\n  \n  if ((varystr[0])) {\n    if (!(br_device = simparse_copystring(varystr[0]))) {\n      goto error;\n    }\n  }\n  else {\n    if (!(br_device = simparse_copystring(\"\"))) {\n      goto error;\n    }\n  }\n  \n  freeparsed(varystr);\n  varystr = NULL;\n\n  \n  /* If there was no input we return */\n  if (*br_device == '\\0') {\n    free(br_device);\n    return 0;\n  }\n  \n  /* Check if there was a logfile and stop if there wasn't */\n/*   if (*log -> logname == '\\0') */\n/*     return 0; */\n  \n  /* Ask for the reference position angle, default 0 */\n  sprintf(mes, \"Give Briggs reference position angle\");\n  br_pa = 0;\n  def = 2;\n  nel = 1;\n  userdble_tir(startinfv -> arel, &br_pa, &nel, &def, \"BR_PA=\", mes);\n\n  /* Ask for the reference inclination, default 0 */\n  sprintf(mes, \"Give Briggs reference position angle\");\n  br_incl = 0;\n  def = 2;\n  nel = 1;\n  userdble_tir(startinfv -> arel, &br_incl, &nel, &def, \"BR_INCL=\", mes);\n\n  /* Then get the stuff in radian */\n  inc = DEGTORAD*br_incl;\n  pa = DEGTORAD*br_pa;\n\n  /* Ask for the angles to plot rings for */\n  ok = 0;\n  def = 2;\n\n  while (ok == 0) {\n    sprintf(mes, \"Give number of Briggs angles\");\n    br_annr = 0;\n    nel = 1;\n    userint_tir(startinfv -> arel, &br_annr, &nel, &def, \"BR_ANNR=\", mes);\n\n    if (br_annr < 0) {\n      dev = 0;\n      sprintf(mes, \"Must be a positive number\");\n      anyout_tir(&dev,mes);\n      cancel_tir(startinfv -> arel, \"BR_ANNR=\", 2);\n      def = 0;\n    }\n    else \n      ok = 1;\n  }\n\n  /* Symbol width */\n  ok = 0;\n  def = 2;\n  while (ok == 0) {\n    sprintf(mes, \"Give width of dots (1-201) [5]\");\n    br_swdth = 10;\n    nel = 1;\n    userint_tir(startinfv -> arel, &br_swdth, &nel, &def, \"BR_SWDTH=\", mes);\n\n    if ((br_swdth < 1) || (br_swdth > 201)) {\n      dev = 0;\n      sprintf(mes, \"Must be in-between 1 and 201\");\n      anyout_tir(&dev,mes);\n      cancel_tir(startinfv -> arel, \"BR_SWDTH=\", 2);\n      def = 1;\n    }\n    else \n      ok = 1;\n  }\n\n  /* circle width */\n  ok = 0;\n  def = 2;\n  while (ok == 0) {\n    sprintf(mes, \"Give width of circles (1-201) [1]\");\n    br_cwdth = 2;\n    nel = 1;\n    userint_tir(startinfv -> arel, &br_cwdth, &nel, &def, \"BR_CWDTH=\", mes);\n\n    if ((br_cwdth < 1) || (br_cwdth > 201)) {\n      dev = 0;\n      sprintf(mes, \"Must be in-between 1 and 201\");\n      anyout_tir(&dev,mes);\n      cancel_tir(startinfv -> arel, \"BR_CWDTH=\", 2);\n      def = 1;\n    }\n    else \n      ok = 1;\n  }\n\n  /* line width */\n  ok = 0;\n  def = 2;\n  while (ok == 0) {\n    sprintf(mes, \"Give width of lines (1-201) [1]\");\n    br_lwdth = 2;\n    nel = 1;\n    userint_tir(startinfv -> arel, &br_lwdth, &nel, &def, \"BR_LWDTH=\", mes);\n\n    if ((br_lwdth < 1) || (br_lwdth > 201)) {\n      dev = 0;\n      sprintf(mes, \"Must be in-between 1 and 201\");\n      anyout_tir(&dev,mes);\n      cancel_tir(startinfv -> arel, \"BR_LWDTH=\", 2);\n      def = 1;\n    }\n    else \n      ok = 1;\n  }\n\n  /* Ask whether to plot the reference line */\n    sprintf(mes, \"Plot reference line? [1]\");\n    def = 2;\n    br_refl = 1;\n    nel = 1;\n    userint_tir(startinfv -> arel, &br_refl, &nel, &def, \"BR_REFL=\", mes);\n\n  /* Ask for colour */\n    sprintf(mes, \"Colour of dots and lines\");\n    br_col = 1;\n    def = 2;\n    nel = 1;\n    userint_tir(startinfv -> arel, &br_col, &nel, &def, \"BR_COL=\", mes);\n\n  /* Allocate memory */\n    if (!(xarray = (float *) malloc((rpm -> nur*(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)+NSPARAMS)*sizeof(float))))\n    goto error;\n  \n    if (!(yarray = (float *) malloc((rpm -> nur*(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)+NSPARAMS)*sizeof(float))))\n    goto error;\n\n    if (!(dummyarray = (float *) malloc((rpm -> nur*(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)+NSPARAMS)*sizeof(float))))\n    goto error;\n\n    if (!(xlarray = (float *) malloc((rpm -> nr*(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)+NSPARAMS)*sizeof(float))))\n    goto error;\n  \n    if (!(ylarray = (float *) malloc((rpm -> nr*(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)+NSPARAMS)*sizeof(float))))\n    goto error;\n\n  /* We read all values into the outarray */\n    tir_get_grid(log, rpm, log -> outarray);\n\n  /* And then into the par array */\n  for (j = 0; j < rpm -> nur*(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)+NSPARAMS; ++j)\n    rpm -> par[j] = log -> outarray[j];\n  \n  /* Interpolate over */\n  for (i = rpm -> nur*NSSDPARAMS; i < rpm->nur *(NSSDPARAMS+NDPARAMS*rpm->ndisks); ++i)\n    rpm -> chapar[i] = 1;\n  \n  if (changedependent(rpm, rpm -> par, fit -> index, rpm -> chapar) < 0)\n    goto error;\n\n  interpover(rpm, dinterntoparam(rpm -> radsep, RADI, hdr, rpm -> ndisks), 0, NULL, fit -> index);\n\n  /* Now fill the arrays */\n  for (j = 0; j < rpm -> nur; ++j) {\n\n    /* Normal vector of current ring */\n    nrefr[0] = sin(DEGTORAD*rpm -> par[PINCL*rpm -> nur+j])*sin(DEGTORAD*rpm -> par[PPA*rpm -> nur+j]);\n    nrefr[1] = -sin(DEGTORAD*rpm -> par[PINCL*rpm -> nur+j])*cos(DEGTORAD*rpm -> par[PPA*rpm -> nur+j]);\n    nrefr[2] = cos(DEGTORAD*rpm -> par[PINCL*rpm -> nur+j]);\n    \n    /* Rotate the ring clockwise about the LOS */\n    rota[0] = cos(pa)*nrefr[0]+sin(pa)*nrefr[1];\n    rota[1] = -sin(pa)*nrefr[0]+cos(pa)*nrefr[1];\n    rota[2] = nrefr[2];\n\n    /* Then rotate the ring about the x axis, clockwise */\n    rota[1] = cos(inc)*rota[1]+sin(inc)*rota[2];\n\n    /* Finally get back to the original position with a clockwise rotation about the LOS */\n    xarray[j] = rota[0];\n    yarray[j] = rota[1];\n\n  /**************/\n/*  sprintf(obsmes, \"graph: x: %.2f y: %.2f\",  xarray[j],yarray[j]); */\n/*  anyout_tir(&obsint, obsmes); */\n  /**************/\n\n/*      xarray[j] = cos(pa)*rota[0]-sin(pa)*rota[1];  */\n/*      yarray[j] = sin(pa)*rota[0]+cos(pa)*rota[1];  */\n  }\n\n  /* Do the same with the large array */\n  for (j = 0; j < rpm -> nr; ++j) {\n\n    /* Normal vector of current ring */\n    nrefr[0] = sin(DEGTORAD*rpm -> modpar[PINCL*rpm -> nr+j])*sin(DEGTORAD*rpm -> modpar[PPA*rpm -> nr+j]);\n    nrefr[1] = -sin(DEGTORAD*rpm -> modpar[PINCL*rpm -> nr+j])*cos(DEGTORAD*rpm -> modpar[PPA*rpm -> nr+j]);\n    nrefr[2] = cos(DEGTORAD*rpm -> modpar[PINCL*rpm -> nr+j]);\n    \n    /* Rotate the ring clockwise about the LOS */\n    rota[0] = cos(pa)*nrefr[0]+sin(pa)*nrefr[1];\n    rota[1] = -sin(pa)*nrefr[0]+cos(pa)*nrefr[1];\n    rota[2] = nrefr[2];\n\n    /* Then rotate the ring about the x axis, clockwise */\n    rota[1] = cos(inc)*rota[1]+sin(inc)*rota[2];\n\n    /* Finally get back to the original position with a clockwise rotation about the LOS */\n     xlarray[j] = cos(pa)*rota[0]-sin(pa)*rota[1]; \n     ylarray[j] = sin(pa)*rota[0]+cos(pa)*rota[1]; \n     xlarray[j] = rota[0];\n     ylarray[j] = rota[1];\n\n\n\n}\n\n  /* In order to provide the user with some suggestion */\n  rmax = 0;\n  for (j = 0; j < rpm -> nur; ++j) {\n    if (rmax < sqrt(xarray[j]*xarray[j]+yarray[j]*yarray[j]))\n      rmax = sqrt(xarray[j]*xarray[j]+yarray[j]*yarray[j]);\n  }\n  for (j = 0; j < rpm -> nr; ++j) {\n    if (rmax < sqrt(xlarray[j]*xlarray[j]+ylarray[j]*ylarray[j]))\n      rmax = sqrt(xlarray[j]*xlarray[j]+ylarray[j]*ylarray[j]);\n  }\n  if (rmax > 1.0)\n    rmax = 1.0;\n  rmax = asin(rmax)/DEGTORAD;\n\n  if ((br_annr)) {\n    if (!(br_angl = (float *) malloc(br_annr*sizeof(float))))\n      goto error;\n\n    /* Now get the numbers */\n    sprintf(mes, \"Give %i Briggs angles, calculated max: %.1f\",br_annr,rmax);\n    def = 5;\n    nel = br_annr;\n    userreal_tir(startinfv -> arel, br_angl, &nel, &def, \"BR_ANGL=\", mes);\n  }\n\n  /* Calculate the proper radii for the rings */\n  for (j = 0; j < br_annr; ++j)\n    br_angl[j] = sin(DEGTORAD*br_angl[j]);\n\n  /* Now pass it to the graphics */\n  pgp_opendev(br_device);\n\n\n  pa_float = br_pa;\n\n  /* remove indexed data points */\n  numplpts = gr_deleteindexed(rpm -> nur, (NPARAMS+(rpm -> ndisks-1)*NDPARAMS+1), xarray, yarray, dummyarray, fit -> index, rpm -> ndisks);\n/*   numplpts = rpm -> nur; */\n\n  /* then plot */\n  if (!numplpts)\n    numplpts = 1;\n  pgp_polar(numplpts, xarray, yarray, rpm -> nr, xlarray, ylarray, br_annr, br_angl, (br_refl)?(&pa_float):NULL, br_lwdth, br_cwdth, br_swdth, br_col);\n\n  /* Once we got here, we ask the user if to continue */\n  sprintf(mes, \"Continue (Press return)?\");\n  def = 1;\n  nel = 1;\n  userint_tir(startinfv -> arel, &br_swdth, &nel, &def, \"BR_CONT=\", mes);\n\n  /* Then we stop it */\n  pgp_end();\n\n    free(xarray);\n    free(xlarray);\n    free(yarray);\n    free(dummyarray);\n    free(ylarray);\n    if ((br_angl))\n      free(br_angl);\n\n  if ((br_device))\n    free(br_device);\n  return 0;\n\n error:\n  if ((br_angl))\n    free(br_angl);\n  if ((xarray))\n    free(xarray);\n  if ((xlarray))\n    free(xlarray);\n  if ((yarray))\n    free(yarray);\n  if ((dummyarray))\n    free(dummyarray);\n  if ((ylarray))\n    free(ylarray);\n  if ((br_device))\n    free(br_device);\n  if ((varystr))\n    freeparsed(varystr);\n\n  return 1;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Produces the graphics output of tirific  */\n\nstatic int graphout(startinf *startinfv, loginf *log, hdrinf *hdr, ringparms *rpm, fitparms *fit)\n{\n  pgp_gdsc *gdsc = NULL;\n  float *xarray = NULL;\n  float *xarray2 = NULL;\n  float *yarray = NULL;\n  float *yerrarray = NULL;\n  float *xlarray = NULL;\n  float *ylarray = NULL;\n  float xmin;\n  float xmax;\n  float ymin;\n  float ymax;\n  int bars;\n  float barwidth;\n  int posrefr;\n  double xrefp;\n  double yrefp;\n  \n  char **varystr = NULL;\n  char *varyhstr = NULL;\n  char *strbef = NULL;\n  \n  int i, j, k, dev, def, nel, inword, nrplts, dummy;\n  char mes[200];\n  char *pgdevice = NULL;\n  \n  char inqstr[24];\n  int colour;\n  int lines;\n  int interp;\n  int errbars;\n  int symb;\n  int fill;\n  float sizer;\n  \n  char leftdeschi[8];\n  char rightdeschi[8];\n  char leftdesclo[30];\n  char rightdesclo[30];\n  char bottomdeschi[8];\n  char bottomdesclo[30];\n  char topdesclo[30];\n  char topdeschi[30];\n  \n  float lrzero;\n  float lrscale;\n  float btzero;\n  float btscale;\n  int xlog;\n  int ylog;\n  int numplpts, ident;\n  \n  char legend[80];\n  \n  int pltlegend;\n  \n  int nradd = 0;\n  int *npadd = NULL;\n  float **xval = NULL;\n  float **yval = NULL;\n  float **errb = NULL;\n  int *erad = NULL;\n  int *adcol = NULL;\n  int *adfill = NULL;\n  int *adsymb = NULL;\n  int *adlines = NULL;\n  int *adinterp = NULL;\n  float *adsizer = NULL; \n  \n  int verln, horln;\n  float *vertarray = NULL, *horarray = NULL;\n  int *vertcarray = NULL, *horcarray = NULL;\n  float vhlxs[2],vhlys[2];\n  \n  int keypres, nread, nreturned;\n  \n  \n  \n  /* Ask the user for the output device */\n  /* for (i = 0; i < 200; ++i) { */\n  /*   pgdevice[i] = ' '; */\n  /* } */\n  /* pgdevice[200] = '\\0'; */\n  \n  /* sprintf(mes, \"Give graphics (pgplot) device:\"); */\n  /* def = 2; */\n  /* nel = 1; */\n  /* userchar_tir(pgdevice, &nel, &def, \"GR_DEVICE=\", mes); */\n  /* termsinglestr(pgdevice); */\n  \n  /* cancel_tir(startinfv -> arel, \"GR_DEVICE\"); */\n  \n  if (simparse_scn_arel_readval_stringlist(startinfv -> arel, \"GR_DEVICE\", \"Give graphics (pgplot) device.\", 0, NULL, 0, -1, 0, 0, &keypres, &nread, &nreturned, &varystr)) {\n    goto error;\n  }\n  \n  if ((varystr[0])) {\n    if (!(pgdevice = simparse_copystring(varystr[0]))) {\n      goto error;\n    }\n  }\n  else {\n    if (!(pgdevice = simparse_copystring(\"\"))) {\n      goto error;\n    }\n  }\n  \n  freeparsed(varystr);\n  varystr = NULL;\n  \n  /* If there was no input we return */\n  if (*pgdevice == '\\0') {\n    free(pgdevice);\n    return 0;\n  }\n  /* Check if there was a logfile and stop if there wasn't */\n  /*   if (*log -> logname == '\\0') */\n  /*     return 0; */\n  \n  /* Allocate the complicated varystr */\n  if (!(varystr = (char **) malloc(MAXGRAPHS*sizeof(char *))))\n    goto error;\n  /* if (!(varyhstr = getfcharray(VARYHSTRELES, NULL))) */\n  /*   goto error; */\n  \n  /* Then ask for the things to plot */\n  /* sprintf(mes, \"Give parameters to plot\"); */\n  /* def = 0; */\n  /* nel = usertext_tir(varyhstr, &def, \"GR_PARMS=\",mes); */\n  \n  /* Terminate the string */\n  /* varyhstr[nel] = '\\0'; */\n  \n  if ((varyhstr))\n    free(varyhstr);\n  if (simparse_scn_arel_readval_string(startinfv -> arel, \"GR_PARMS\", \"Give parameters to plot.\", 0, \"\", 0, -1, 0, 0, &keypres, &nread, &nreturned, &varyhstr)) {\n    goto error;\n  }\n  \n  /* Change the case if it is lower case */\n  i = 0;\n  while (varyhstr[i]) {\n    if (varyhstr[i] >= 'a' && varyhstr[i] <= 'z')\n      varyhstr[i] = varyhstr[i]+'A'-'a';\n    ++i;\n  }\n  \n  /* Now hack it into peaces, fill varystr, ignoring wrong parameters */\n  inword = 0;\n  i = 0;\n  nrplts = 0;\n  \n  while (varyhstr[i] != '\\0') {\n    \n    if ((inword)) {\n      if (varyhstr[i] == ' ' || varyhstr[i] == '\\t') {\n\tvaryhstr[i] = '\\0';\n\t\n\tif ((ident = get_graphident(strbef, NULL, NULL, NULL, NULL, rpm -> ndisks)) > 0) {\n\t  varystr[nrplts] = strbef;\n\t  ++nrplts;\n\t}\n\tinword = 0;\n      }\n      else if (varyhstr[i+1] == '\\0') {\n\t\n\tif ((ident = get_graphident(strbef, NULL, NULL, NULL, NULL, rpm -> ndisks)) > 0) {\n\t  varystr[nrplts] = strbef;\n\t  ++nrplts;\n\t}\n      }\n    }\n    else if (varyhstr[i] != ' ' && varyhstr[i] != '\\t') {\n      if (nrplts < MAXGRAPHS)\n\tstrbef = varyhstr+i;\n      inword = 1;\n    }\n    ++i;\n  }\n  \n  dev = 1;\n  if (nrplts < 2) {\n    sprintf(mes, \"Something wrong with GR_PARMS=, no output\");\n    anyout_tir(&dev, mes);\n  }\n  \n  /* Allocate memory for the output */\n  if (!(xarray = (float *) malloc((rpm -> nur*(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)+NSPARAMS)*sizeof(float))))\n    goto error;\n  \n  if (!(xarray2 = (float *) malloc((rpm -> nur*(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)+NSPARAMS)*sizeof(float))))\n    goto error;\n  \n  if (!(yarray = (float *) malloc((rpm -> nur*(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)+NSPARAMS)*sizeof(float))))\n    goto error;\n  \n  if (!(yerrarray = (float *) malloc((rpm -> nur*(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)+NSPARAMS)*sizeof(float))))\n    goto error;\n  \n  if (!(xlarray = (float *) malloc((rpm -> nr*(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)+NSPARAMS)*sizeof(float))))\n    goto error;\n  \n  if (!(ylarray = (float *) malloc((rpm -> nr*(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)+NSPARAMS)*sizeof(float))))\n    goto error;\n  \n  /* We read all values into the outarray */\n  tir_get_grid(log, rpm, log -> outarray);\n  \n  /* Then into the par array */\n  for (j = 0; j < rpm -> nur*(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)+NSPARAMS; ++j)\n    rpm -> par[j] = log -> outarray[j];\n  \n  /* Get the reference positions */\n  \n  /* First ask for the reference ring */\n  sprintf(mes, \"Position reference ring [1]\");\n  def = 2;\n  nel = 1;\n  posrefr = 1;\n  userint_tir(startinfv -> arel, &posrefr, &nel, &def, \"GR_PRFR=\", mes);\n  if ((posrefr < 1) || (posrefr >  rpm -> nur))\n    posrefr = 1;\n  else\n    --posrefr;\n  \n  /* Then this will be a default for the reference position */\n  sprintf(mes, \"Reference Right Ascension [%.3f]\",rpm -> par[PXPOS*rpm -> nur+posrefr]);\n  def = 2;\n  nel = 1;\n  xrefp = rpm -> par[PXPOS*rpm -> nur+posrefr];\n  userdble_tir(startinfv -> arel, &xrefp, &nel, &def, \"GR_PRFX=\", mes);\n  \n  /* Export this to log */\n  log -> xref = xrefp;\n  \n  sprintf(mes, \"Reference Declination [%.3f]\",rpm -> par[PYPOS*rpm -> nur+posrefr]);\n  def = 2;\n  nel = 1;\n  yrefp = rpm -> par[PYPOS*rpm -> nur+posrefr];\n  userdble_tir(startinfv -> arel, &yrefp, &nel, &def, \"GR_PRFY=\", mes);\n  \n  /* Export this to log */\n  log -> yref = yrefp;\n  \n  /* Interpolate over */\n  for (i = rpm -> nur*NSSDPARAMS; i < rpm->nur *(NSSDPARAMS+NDPARAMS*rpm->ndisks); ++i)\n    rpm -> chapar[i] = 1;\n    \n  if (changedependent(rpm, rpm -> par, fit -> index, rpm -> chapar) < 0)\n    goto error;\n\n  interpover(rpm, barwidth = dinterntoparam(rpm -> radsep, RADI, hdr, rpm -> ndisks), 0, NULL, fit -> index);\n  \n  /* Now prepare the arrays for x */\n  \n  fillgrapharray(startinfv, hdr, rpm, ident = get_graphident(varystr[0], NULL, NULL, NULL, NULL, rpm -> ndisks), xarray, xlarray, rpm -> ndisks);\n  \n  /* Get the scale and the identity card */\n  gr_fillscaling(log, hdr, get_graphident(varystr[0], bottomdeschi, bottomdesclo, topdesclo, legend, rpm -> ndisks), &btscale, &btzero, rpm -> ndisks);\n  \n  /* Inquire whether to plot subrings */\n  sprintf(mes, \"Plot values for subrings 1/0? [1]\");\n  def = 2;\n  nel = 1;\n  bars = 1;\n  userint_tir(startinfv -> arel, &bars, &nel, &def, \"GR_SBRP=\", mes);\n  \n  /* Get min */\n  xmin = xarray[0];\n  for (i = 1; i < rpm -> nur; ++i)\n    xmin = (xmin > xarray[i])?xarray[i]:xmin;\n  if ((bars))\n    for (i = 0; i < rpm -> nr; ++i)\n      xmin = (xmin > xlarray[i])?xlarray[i]:xmin;\n  \n  /* Get max */\n  xmax = xarray[0];\n  for (i = 1; i < rpm -> nur; ++i)\n    xmax = (xmax < xarray[i])?xarray[i]:xmax;\n  if ((bars))\n    for (i = 0; i < rpm -> nr; ++i)\n      xmax = (xmax < xlarray[i])?xlarray[i]:xmax;\n  \n  /* Inquire min and max */\n  sprintf(mes, \"Give minimum of x-axis [%f]\", xmin);\n  def = 2;\n  nel = 1;\n  userreal_tir(startinfv -> arel, &xmin, &nel, &def, \"GR_XMIN=\", mes);\n  sprintf(mes, \"Give maximum of x-axis [%f]\", xmax);\n  def = 2;\n  nel = 1;\n  userreal_tir(startinfv -> arel, &xmax, &nel, &def, \"GR_XMAX=\", mes);\n  \n  /* Inquire x-axis style */\n  sprintf(mes, \"Logarithmic scaling of x-axis? (1/0)\");\n  xlog = 0;\n  def = 2;\n  nel = 1;\n  userint_tir(startinfv -> arel, &xlog, &nel, &def, \"GR_XLOG=\", mes);\n  \n  if ((xlog))\n    xlog = 1;\n  \n  /* In case of SBR, the right hand is SD */\n  if (ident == SBR)\n    gr_fillaxis((NPARAMS+(rpm -> ndisks-1)*NDPARAMS+DENS_GRAPHNR), topdeschi, rpm -> ndisks);\n  else if (ident == XPOS) {\n    gr_fillaxis((NPARAMS+(rpm -> ndisks-1)*NDPARAMS+RASH_GRAPHNR), topdeschi, rpm -> ndisks);\n    xlog = 2;\n  }\n  else if (ident == YPOS) {\n    gr_fillaxis((NPARAMS+(rpm -> ndisks-1)*NDPARAMS+DESH_GRAPHNR), topdeschi, rpm -> ndisks);\n    xlog = 3;\n  }\n  else {\n    gr_fillaxis(ident, topdeschi, rpm -> ndisks);\n  }\n  \n  /* Ask whether to plot a legend */\n  sprintf(mes, \"Plot legend (1/0)?\");\n  def = 2;\n  nel = 1;\n  pltlegend = 1;\n  userint_tir(startinfv -> arel, &pltlegend, &nel, &def, \"GR_LGND=\", mes);\n  \n  /* Now initialise the graphics */\n  pgp_opendev(pgdevice);\n  \n  /* Generate the standard frame information */\n  gdsc = pgp_gdsc_default(nrplts-1, 2, (pltlegend)?((nrplts+1)/2):0, 1.0);\n  \n  /* Make the adjustment of left and right frame possible */\n  sprintf(mes, \"Give right hand margin\");\n  def = 2;\n  nel = 1;\n  userreal_tir(startinfv -> arel, &gdsc -> rightmargin, &nel, &def, \"GR_MR=\", mes);\n  sprintf(mes, \"Give left hand margin\");\n  def = 2;\n  nel = 1;\n  userreal_tir(startinfv -> arel, &gdsc -> leftmargin, &nel, &def, \"GR_ML=\", mes);\n  \n  /* Ask for the height of text and symbols */\n  sprintf(mes, \"Give height of Text\");\n  def = 2;\n  nel = 1;\n  userreal_tir(startinfv -> arel, &gdsc -> numberheight, &nel, &def, \"GR_TXHT=\", mes);\n  \n  sprintf(mes, \"Give height of symbols\");\n  def = 2;\n  nel = 1;\n  userreal_tir(startinfv -> arel, &gdsc -> symbolheight, &nel, &def, \"GR_SBHT=\", mes);\n  \n  /* Legendheight and axdescheight are 1 by default, we leave it at that */\n  \n  /* Put the x axis descriptor */\n  if ((pltlegend))\n    pgp_legend(gdsc, 1, 1, legend);\n  \n  /* Plot everything */\n  for (i = 1; i < nrplts; ++i) {\n    def = 2;\n    nel = 1;\n    \n    /* Inquire colour */\n    colour = i;\n    sprintf(inqstr, \"GR_COL_%i=\", i);\n    sprintf(mes, \"Give Colour of plot %i\", i);\n    userint_tir(startinfv -> arel, &colour, &nel, &def, inqstr, mes);\n    \n    /* Inquire symbol */\n    symb = -1;\n    sprintf(inqstr, \"GR_SYMB_%i=\", i);\n    sprintf(mes, \"Give symbol for plot %i\", i);\n    userint_tir(startinfv -> arel, &symb, &nel, &def, inqstr, mes);\n    \n    /* Inquire fill */\n    fill = 0;\n    /*     sprintf(inqstr, \"GR_EMTY_%i=\", i); */\n    /*     sprintf(mes, \"Fill symbol for plot %i? (0)\", i); */\n    /*     userint_tir(startinfv -> arel, &fill, &nel, &def, inqstr, mes); */\n    \n    /* Inquire sizer */\n    sizer = 1.0;\n    sprintf(inqstr, \"GR_SIZE_%i=\", i);\n    sprintf(mes, \"Relative size of symbol for plot %i? (0)\", i);\n    userreal_tir(startinfv -> arel, &sizer, &nel, &def, inqstr, mes);\n    \n    /* Inquire lines */\n    lines = 0;\n    sprintf(inqstr, \"GR_LINES_%i=\", i);\n    sprintf(mes, \"Plot lines 1/0? [0]\");\n    userint_tir(startinfv -> arel, &lines, &nel, &def, inqstr, mes);\n    \n    /* Inquire lines interpolation type */\n    switch (rpm -> smothcar[ident-1+NPARAMS-NDPARAMS]) {\n    case PGP_I_CSPLINE:\n      interp = 1;\n      break;\n    case PGP_I_AKIMA:\n      interp = 2;\n      break;\n    default:\n      interp = 0;\n      break;\n    }\n    sprintf(inqstr, \"GR_INTERP_%i=\", i);\n    sprintf(mes, \"Interpolation 0: linear, 1: cubic spline, 2: Akima [0]\");\n    userint_tir(startinfv -> arel, &interp, &nel, &def, inqstr, mes);\n    switch (interp) {\n    case 1:\n      interp = PGP_I_CSPLINE;\n      break;\n    case 2:\n      interp = PGP_I_AKIMA;\n      break;\n    default:\n      interp = PGP_I_LINEAR;\n      break;\n    }\n    \n    /* Inqurie number of small interpolating lines, once for all */\n    gdsc -> interp_numlines = GR_INTERP_NUMLINES_DEFAULT;\n    sprintf(inqstr, \"GR_INTERP_NUMLINES=\");\n    sprintf(mes, \"Number of small straight lines when interpolating [%i]\", gdsc -> interp_numlines);\n    userint_tir(startinfv -> arel, &(gdsc -> interp_numlines), &nel, &def, inqstr, mes);\n\n    /* Inquire errorbars */\n    errbars = 0;\n    sprintf(inqstr, \"GR_ERRB_%i=\", i);\n    sprintf(mes, \"Plot errorbars 1/0? [0]\");\n    userint_tir(startinfv -> arel, &errbars, &nel, &def, inqstr, mes);\n    \n    /* Inquire logarithmic scaling */\n    ylog = 0;\n    sprintf(inqstr, \"GR_YLOG_%i=\", i);\n    sprintf(mes, \"y-axis logarithmic scaling 1/0? [0]\");\n    userint_tir(startinfv -> arel, &ylog, &nel, &def, inqstr, mes);\n    \n    if ((ylog))\n      ylog = 1;\n    \n    /* Get number of vertical lines */\n    verln = 0;\n    nel = 1;\n    sprintf(inqstr, \"GR_VERL_%i=\", i);\n    sprintf(mes, \"How many vertical lines for plot %i?\", i);\n    userint_tir(startinfv -> arel, &verln, &nel, &def, inqstr, mes);\n    verln = verln > 0 ? verln : -verln;\n    \n    if ((verln)) {\n      \n      /* allocate */\n      if (!(vertarray = (float *) malloc(verln*sizeof(float))))\n\tgoto error;\n      \n      if (!(vertcarray = (int *) malloc(verln*sizeof(int))))\n\tgoto error;\n      \n      for (j = 0; j < verln; ++j)\n\tvertarray[j] = 0.0;\n      \n      for (j = 0; j < verln; ++j)\n\tvertcarray[j] = 1;\n      \n      sprintf(mes, \"Give values for vertical lines\");\n      def = 2;\n      nel = verln;\n      sprintf(inqstr, \"GR_VLVA_%i=\", i);\n      userreal_tir(startinfv -> arel, vertarray, &nel, &def, inqstr, mes);\n      \n      sprintf(mes, \"Give colours for vertical lines\");\n      def = 2;\n      nel = verln;\n      sprintf(inqstr, \"GR_VLCA_%i=\", i);\n      userint_tir(startinfv -> arel, vertcarray, &nel, &def, inqstr, mes);\n      \n      for (j = 0; j < verln; ++j)\n\tvertcarray[j] = vertcarray[j] > 0 ?  vertcarray[j] : - vertcarray[j];\n    }\n    \n    /* Get number of horizontal lines */\n    horln = 0;\n    nel = 1;\n    sprintf(inqstr, \"GR_HORL_%i=\", i);\n    sprintf(mes, \"How many horizontal lines for plot %i?\", i);\n    userint_tir(startinfv -> arel, &horln, &nel, &def, inqstr, mes);\n    horln = horln > 0 ? horln : -horln;\n    \n    if ((horln)) {\n      \n      /* allocate */\n      if (!(horarray = (float *) malloc(horln*sizeof(float))))\n\tgoto error;\n      \n      if (!(horcarray = (int *) malloc(horln*sizeof(int))))\n\tgoto error;\n      \n      for (j = 0; j < horln; ++j)\n\thorarray[j] = 0.0;\n      \n      for (j = 0; j < horln; ++j)\n\thorcarray[j] = 1;\n      \n      sprintf(mes, \"Give values for horizontal lines of plot %i\",i);\n      sprintf(inqstr, \"GR_HLVA_%i=\", i);\n      def = 2;\n      nel = horln;\n      userreal_tir(startinfv -> arel, horarray, &nel, &def, inqstr, mes);\n      \n      sprintf(mes, \"Give colours for horizontal lines of plot %i\", i);\n      def = 2;\n      nel = horln;\n      sprintf(inqstr, \"GR_HLCA_%i=\", i);\n      userint_tir(startinfv -> arel, horcarray, &nel, &def, inqstr, mes);\n      \n      for (j = 0; j < verln; ++j)\n\thorcarray[j] = horcarray[j] > 0 ?  horcarray[j] : - horcarray[j];\n    }\n    \n    /* Fill yerrarray */\n    if ((errbars)) {\n      \n      /* We read all values into the outarray */\n      tir_get_radius(log, rpm, log -> outarray);\n      \n      for (j = 0; j < rpm -> nur*(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)+NSPARAMS; ++j)\n\trpm -> par[j] = log -> outarray[j];\n      \n      fillgrapharray(startinfv, hdr, rpm, ident, yerrarray, ylarray, rpm -> ndisks);\n      \n      /* Give the user the possibility to put own errorbars */\n      def = 2;\n      nel = rpm -> nur;\n      sprintf(mes, \"Give own errorbars\");\n      sprintf(inqstr, \"GR_ERRV_%i=\", i);\n      userreal_tir(startinfv -> arel, yerrarray, &nel, &def, inqstr, mes);\n    }\n    else {\n      for (j = 0; j < rpm -> nur; ++j)\n\tyerrarray[j] = 0;\n    }      \n    \n    /* Fill yarray */\n    \n    /* We read all values into the outarray */\n    tir_get_grid(log, rpm, log -> outarray);\n    \n    for (j = 0; j < rpm -> nur*(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)+NSPARAMS; ++j)\n      rpm -> par[j] = log -> outarray[j];\n    \n    /* Central coordinates get the head cut off */\n    /*     for (j = 0; j < rpm -> nur; ++j) { */\n    /*       rpm -> par[PXPOS*rpm -> nur+j] = rpm -> par[PXPOS*rpm -> nur+j]-((int) rpm -> par[(PXPOS+1)*rpm -> nur-1]); */\n    /*       rpm -> par[PYPOS*rpm -> nur+j] = rpm -> par[PYPOS*rpm -> nur+j]-((int) rpm -> par[(PYPOS+1)*rpm -> nur-1]); */\n    /*     } */\n    \n    fillgrapharray(startinfv, hdr, rpm, ident = get_graphident(varystr[i], NULL, NULL, NULL, NULL, rpm -> ndisks), yarray, ylarray, rpm -> ndisks);\n    \n    /* Inquire number of additional arrays */\n    sprintf(mes, \"Give number of additional rows for plot %i: [0]\", i);\n    sprintf(inqstr, \"GR_NRAD_%i=\", i);\n    def = 2;\n    nel = 1;\n    nradd = 0;\n    userint_tir(startinfv -> arel, &nradd, &nel, &def, inqstr, mes);\n\n    /* Reserve memory */\n    if (nradd > 0) {\n      if (!(npadd = (int *) malloc(nradd*sizeof(int))))\n\tgoto error;\n      if (!(erad = (int *) malloc(nradd*sizeof(int))))\n\tgoto error;\n      if (!(adcol = (int *) malloc(nradd*sizeof(int))))\n\tgoto error;\n      if (!(adsymb = (int *) malloc(nradd*sizeof(int))))\n\tgoto error;\n      if (!(adfill = (int *) malloc(nradd*sizeof(int))))\n\tgoto error;\n      if (!(adlines = (int *) malloc(nradd*sizeof(int))))\n\tgoto error;\n      if (!(adinterp = (int *) malloc(nradd*sizeof(int))))\n\tgoto error;\n      if (!(adsizer = (float *) malloc(nradd*sizeof(float))))\n\tgoto error;\n      if (!(xval = (float **) malloc(nradd*sizeof(float *))))\n\tgoto error;\n      for (k = 0; k < nradd; ++k) {\n\txval[k] = NULL;\n      }\n      if (!(yval = (float **) malloc(nradd*sizeof(float *))))\n\tgoto error;\n      for (k = 0; k < nradd; ++k) {\n\tyval[k] = NULL;\n      }\n      if (!(errb = (float **) malloc(nradd*sizeof(float *))))\n\tgoto error;\n      for (k = 0; k < nradd; ++k) {\n\terrb[k] = NULL;\n      }\n    }\n    \n    /* Now get the info about all the additional points */\n    for (k = 0; k < nradd; ++k) {\n      \n      /* Inquire number of additional points */\n      sprintf(mes, \"Give number of additional points for plot %i (%i): [0]\", i, k+1);\n      sprintf(inqstr, \"GR_NPAD_%i_%i=\", i, k+1);\n      \n      npadd[k] = -1;\n      while(npadd[k] < 0) {\n\tdef = 4;\n\tnel = 1;\n\tnpadd[k] = 0;\n\tuserint_tir(startinfv -> arel, npadd+k, &nel, &def, inqstr, mes);\n\tif (npadd[k] < 0) {\n\t  sprintf(mes, \"Must be at least 0\");\n\t  anyout_tir(&nel, mes);\n\t  cancel_tir(startinfv -> arel, inqstr, 2);\n\t}\n      }\n      \n      if ((npadd[k])) {\n\t\n\t/* Reserve memory */\n\tif (!(xval[k] = (float *) malloc(npadd[k]*sizeof(float))))\n\t  goto error;\n\tif (!(yval[k] = (float *) malloc(npadd[k]*sizeof(float))))\n\t  goto error;\n\tif (!(errb[k] = (float *) malloc(npadd[k]*sizeof(float))))\n\t  goto error;\n\t\n\t/* Inquire points */\n\tsprintf(mes, \"Give additional points, x axis for plot %i (%i):\", i, k+1);\n\tsprintf(inqstr, \"GR_XPAD_%i_%i=\", i, k+1);\n\tdef = 4;\n\tnel = npadd[k];\n\tuserreal_tir(startinfv -> arel, xval[k], &nel, &def, inqstr, mes);\n\t\n\tsprintf(mes, \"Give additional points, y axis for plot %i (%i):\", i, k+1);\n\tsprintf(inqstr, \"GR_YPAD_%i_%i=\", i, k+1);\n\tuserreal_tir(startinfv -> arel, yval[k], &nel, &def, inqstr, mes);\n\t\n\t/* Inquire errorbars */\n\tsprintf(mes, \"Errorbars to additional points of plot %i (%i) (1/0)?\", i, k+1);\n\tsprintf(inqstr, \"GR_ERAD_%i_%i=\", i, k+1);\n\tdef = 2;\n\tnel = 1;\n\terad[k] = 0;\n\tuserint_tir(startinfv -> arel, &erad[k], &nel, &def, inqstr, mes);\n\t\n\tif ((erad[k])) {\n\t  \n\t  /* Get the errorbars */\n\t  sprintf(mes, \"Give errorbars for additional points of plot %i (%i):\", i, k+1);\n\t  sprintf(inqstr, \"GR_EBAD_%i_%i=\", i, k+1);\n\t  def = 4;\n\t  nel = npadd[k];\n\t  userreal_tir(startinfv -> arel, errb[k], &nel, &def, inqstr, mes);\n\t}\n\telse {\n\t  for (j = 0; j < npadd[k]; ++j)\n\t    (errb[k])[j] = 0;\n\t}\n\t\n\t/* Inquire colour */\n\tsprintf(mes, \"Give colour of additional points of plot %i (%i):\", i, k+1);\n\tsprintf(inqstr, \"GR_COAD_%i_%i\", i, k+1);\n\tdef = 2;\n\tnel = 1;\n\tadcol[k] = i;\n\tuserint_tir(startinfv -> arel, adcol+k, &nel, &def, inqstr, mes);\n\t\n\t/* Inquire symbol */\n\tsprintf(mes, \"Give symbol of additional points of plot %i (-1):\", i);\n\tsprintf(inqstr, \"GR_SYAD_%i_%i\", i, k+1);\n\tdef = 2;\n\tnel = 1;\n\tadsymb[k] = -1;\n\tuserint_tir(startinfv -> arel, adsymb+k, &nel, &def, inqstr, mes);\n\t\n\t/* Inquire emptyness */\n\tsprintf(mes, \"Symbols of additional points of plot %i empty: (1)\", i);\n\tsprintf(inqstr, \"GR_EMAD_%i_%i\", i, k+1);\n\tdef = 2;\n\tnel = 1;\n\tadfill[k] = 0;\n\t/*  userint_tir(startinfv -> arel, adfill+k, &nel, &def, inqstr, mes); */\n\t\n\t/* Inquire sizer */\n\tsprintf(mes, \"Size of additional points relative to standard size\");\n\tsprintf(inqstr, \"GR_SIAD_%i_%i\", i, k+1);\n\tdef = 2;\n\tnel = 1;\n\tadsizer[k] = 1.0;\n\tuserreal_tir(startinfv -> arel, adsizer+k, &nel, &def, inqstr, mes);\n\t\n\t/* Inquire lines */\n\tsprintf(mes, \"Draw lines between additional points of plot %i (%i) (1/0)?\", i, k+1);\n\tsprintf(inqstr, \"GR_LIAD_%i_%i\", i, k+1);\n\tdef = 2;\n\tnel = 1;\n\tadlines[k] = 0;\n\tuserint_tir(startinfv -> arel, adlines+k, &nel, &def, inqstr, mes);\n\t\n\tswitch (interp) {\n\tcase PGP_I_CSPLINE:\n\t  adinterp[k] = 1;\n\t  break;\n\tcase PGP_I_AKIMA:\n\t  adinterp[k] = 2;\n\t  break;\n\tdefault:\n\t  adinterp[k] = 0;\n\t  break;\n\t}\n\t/***/\n\t/***/\n\t/***/\n\t/*\tfprintf(stderr,\"Got here\"); */\n\t/***/\n\tsprintf(inqstr, \"GR_INTERPAD_%i_%i=\", i, k+1);\n\tsprintf(mes, \"Interpolation between additional points plot %i (%i), 0: linear, 1: cubic spline, 2: Akima [0]\", i, k+1);\n\tuserint_tir(startinfv -> arel, adinterp+k, &nel, &def, inqstr, mes);\n\tswitch (adinterp[k]) {\n\tcase 1:\n\t  adinterp[k] = PGP_I_CSPLINE;\n\t  break;\n\tcase 2:\n\t  adinterp[k] = PGP_I_AKIMA;\n\t  break;\n\tdefault:\n\t  adinterp[k] = PGP_I_LINEAR;\n\t  break;\n\t}\n      }\n    }\n      \n    /* Inquire min and max */\n    ymin = yarray[0]-fabs(yerrarray[0]);\n    for (j = 1; j < rpm -> nur; ++j)\n      ymin = (ymin > (yarray[j]-fabs(yerrarray[j])))?(yarray[j]-fabs(yerrarray[j])):ymin;\n    if ((bars))\n      for (j = 0; j < rpm -> nr; ++j)\n\tymin = (ymin > ylarray[j])?ylarray[j]:ymin;\n    for (k = 0; k < nradd; ++k) {\n      for (j = 0; j < npadd[k]; ++j)\n\tymin = (ymin > ((yval[k])[j]-fabs((errb[k])[j])))?((yval[k])[j]-fabs((errb[k])[j])):ymin;\n    }\n      \n    ymax = yarray[0]+fabs(yerrarray[0]);\n    for (j = 1; j < rpm -> nur; ++j)\n      ymax = (ymax < (yarray[j]+fabs(yerrarray[j])))?(yarray[j]+fabs(yerrarray[j])):ymax;\n    if ((bars))\n      for (j = 0; j < rpm -> nr; ++j)\n\tymax = (ymax < ylarray[j])?ylarray[j]:ymax;\n    for (k = 0; k < nradd; ++k) {\n      for (j = 0; j < npadd[k]; ++j)\n\tymax = (ymax < ((yval[k])[j]+fabs((errb[k])[j])))?((yval[k])[j]+fabs((errb[k])[j])):ymax;\n    }\n    /* Ask */\n    sprintf(inqstr, \"GR_YMIN_%i=\", i);\n    sprintf(mes, \"Give minimum of y-axis %i: [%f]\", i, ymin);\n    def = 2;\n    nel = 1;\n    userreal_tir(startinfv -> arel, &ymin, &nel, &def, inqstr, mes);\n    sprintf(inqstr, \"GR_YMAX_%i=\", i);\n    sprintf(mes, \"Give maximum of y-axis %i: [%f]\", i, ymax);\n    def = 2;\n    nel = 1;\n    userreal_tir(startinfv -> arel, &ymax, &nel, &def, inqstr, mes);\n      \n    /* Fill the y axis descriptors and scalings */\n    /* Get the scale and the identity card */\n    gr_fillscaling(log, hdr, get_graphident(varystr[i], leftdeschi, leftdesclo, rightdesclo, legend, rpm -> ndisks), &lrscale, &lrzero, rpm -> ndisks);\n      \n    /* In case of SBR, the right hand is SD */\n    if (ident == SBR)\n      gr_fillaxis((NPARAMS+(rpm -> ndisks-1)*NDPARAMS+DENS_GRAPHNR), rightdeschi, rpm -> ndisks);\n    else if (ident == XPOS) {\n      gr_fillaxis((NPARAMS+(rpm -> ndisks-1)*NDPARAMS+RASH_GRAPHNR), rightdeschi, rpm -> ndisks);\n      ylog = 2;\n    }\n    else if (ident == YPOS) {\n      gr_fillaxis((NPARAMS+(rpm -> ndisks-1)*NDPARAMS+DESH_GRAPHNR), rightdeschi, rpm -> ndisks);\n      ylog = 3;\n    }\n    else\n      gr_fillaxis(ident, rightdeschi, rpm -> ndisks);\n      \n    /* Plot the box */\n    pgp_openbox(gdsc, i, xmin, xmax, ymin, ymax, leftdeschi, leftdesclo, rightdeschi, rightdesclo, bottomdeschi, bottomdesclo, topdeschi, topdesclo, lrzero, lrscale, btzero, btscale, xlog, ylog);\n      \n    /* Plot additional points */\n    if (nradd > 0) {\n      for (k = 0; k < nradd; ++k) {\n\tif ((npadd[k])) {\n\t    \n\t  pgp_marker(gdsc, npadd[k], xval[k], yval[k], adcol[k], adfill[k], adsymb[k], adsizer[k]);\n\t    \n\t  /* Plot errorbars */\n\t  if ((erad[k]))\n\t    pgp_errby(gdsc, npadd[k], xval[k], yval[k], errb[k], adcol[k]);\n\t    \n\t  /* Plot lines */\n\t  if ((adlines[k])) {\n\t    gdsc -> interptype_lines = adinterp[k];\n\t    pgp_lines(gdsc, npadd[k], xval[k], yval[k], adcol[k]);\n\t  }\n\n\t  /* Free memory */\n\t  free(xval[k]);\n\t  xval[k] = NULL;\n\t  free(yval[k]);\n\t  yval[k] = NULL;\n\t  free(errb[k]);\n\t  errb[k] = NULL;\n\t}\n      }\n\t\n      /* free stuff */\n      free(npadd);\n      free(erad);\n      free(adcol);\n      free(adlines);\n      free(xval);\n      free(yval);\n      free(errb);\n    }\n      \n    /* Plot bars */\n    if ((bars)) \n      pgp_bars(gdsc, rpm -> nr, xlarray, ylarray, barwidth, colour);\n\n    /* Plot lines */\n    if ((lines)) {\n      gdsc -> interptype_lines = interp;\n      pgp_lines(gdsc, rpm -> nur, xarray, yarray, colour);\n    }\n\n    /* Copy the x array and remove points */\n    for (j = 0; j < rpm -> nur; ++j)\n      xarray2[j] = xarray[j];\n    numplpts = gr_deleteindexed(rpm -> nur, ident, xarray2, yarray, yerrarray, fit -> index, rpm -> ndisks);\n      \n    if (numplpts) {\n\t\n      /* Plot errorbars */\n      if ((errbars))\n\tpgp_errby(gdsc, numplpts, xarray2, yarray, yerrarray, colour);\n\t\n      /* Plot the points */\n      pgp_marker(gdsc, numplpts, xarray2, yarray, colour, fill, symb, sizer);\n    }\n      \n    /* plot horizontal lines */\n    if ((horln)) {\n      for (j = 0; j < horln; ++j) {\n\tvhlys[0] = vhlys[1] = horarray[j];\n\t  \n\tif (xmin == xmax) { \n\t  vhlxs[0] = 1000000.0*xarray[0]+0.1;\n\t  vhlxs[1] = -1000000.0*xarray[0]-0.1;\n\t}\n\telse {\n\t  vhlxs[0] = (xmin+xmax)/2.0-1000000.0*(xmax-xmin);\n\t  vhlxs[1] = (xmin+xmax)/2.0+1000000.0*(xmax-xmin);\n\t}\n\tdummy = gdsc -> interptype_lines;\n\tgdsc -> interptype_lines = PGP_I_LINEAR;\n\tpgp_lines(gdsc, 2, vhlxs, vhlys, horcarray[j]);\n\tgdsc -> interptype_lines = dummy;\n      }\n      free(horarray);\n      free(horcarray);\n    }\n      \n    /* plot vertical lines */\n    if ((verln)) {\n      for (j = 0; j < verln; ++j) {\n\tvhlxs[0] = vhlxs[1] = vertarray[j];\n\tif (ymin == ymax) { \n\t  vhlys[0] = 1000000.0*yarray[0]+0.1;\n\t  vhlys[1] = -1000000.0*yarray[0]-0.1;\n\t}\n\telse {\n\t  vhlys[0] = (ymin+ymax)/2.0-1000000.0*(ymax-ymin);\n\t  vhlys[1] = (ymin+ymax)/2.0+1000000.0*(ymax-ymin);\n\t}\n\t/* Switch off interpolation scheme before plotting and reinstate */\n\tdummy = gdsc -> interptype_lines;\n\tgdsc -> interptype_lines = PGP_I_LINEAR;\n\tpgp_lines(gdsc, 2, vhlxs, vhlys, vertcarray[j]);\n\tgdsc -> interptype_lines = dummy;\n      }\n      free(vertarray);\n      free(vertcarray);\n    }\n      \n    /* Put the legend line */\n    if ((pltlegend))\n      pgp_legend(gdsc, i%2+1, i/2+1, legend);\n  }\n    \n  /* Free memory */\n  free(varystr);\n  free(varyhstr);\n  free(xarray);\n  free(xarray2);\n  free(yarray);\n  free(yerrarray);\n  free(xlarray);\n  free(ylarray);\n  free(pgdevice);\n    \n  /* Once we got here, we ask the user if to continue */\n  sprintf(mes, \"Continue (Press return)?\");\n  def = 1;\n  nel = 1;\n  userint_tir(startinfv -> arel, &pltlegend, &nel, &def, \"GR_CONT=\", mes);\n    \n    \n  /* Then we stop it */\n  pgp_end();\n    \n  return nrplts-1;\n    \n error:\n  if ((varystr))\n    free(varystr);\n  if ((varyhstr))\n    free(varyhstr);\n  if ((xarray))\n    free(xarray);\n  if ((xarray2))\n    free(xarray2);\n  if ((yarray))\n    free(yarray);\n  if ((yerrarray))\n    free(yerrarray);\n  if ((xlarray))\n    free(xlarray);\n  if ((ylarray))\n    free(ylarray);\n    \n  if ((npadd))\n    free(npadd);\n  if ((erad))\n    free(erad);\n  if ((adcol))\n    free(adcol);\n  if ((adsymb))\n    free(adsymb);\n  if ((adfill))\n    free(adfill);\n  if ((adlines))\n    free(adlines);\n  if ((adsizer))\n    free(adsizer);\n  if ((vertarray))\n    free(vertarray);\n  if ((horarray))\n    free(horarray);\n  if ((vertcarray))\n    free(vertcarray);\n  if ((horcarray))\n    free(horcarray);\n    \n  if ((xval)) {\n    for (i = 0; i < nradd; ++i) {\n      if ((xval[i]))\n\tfree(xval[i]);\n    }\n    free(xval);\n  }\n    \n  if ((yval)) {\n    for (i = 0; i < nradd; ++i) {\n      if ((yval[i]))\n\tfree(yval[i]);\n    }\n    free(yval);\n  }\n    \n  if ((errb)) {\n    for (i = 0; i < nradd; ++i) {\n      if ((errb[i]))\n\tfree(errb[i]);\n    }\n    free(errb);\n  }\n    \n  if ((pgdevice))\n    free(pgdevice);\n    \n  return 0;\n}\n  \n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Returns the identifyer of a graphics output */\nstatic int get_graphident(char *string, char *axis, char *unit, char *altunit, char *legend, int ndisks)\n{\n  int ident;\n\n  /* First check if there is a string */\n  if (!string)\n    return -1;\n  \n  /* Now check if it can be identified with a variable parameter itself */\n  if(((ident = ftstab_gtitln_(string)) <= 0))\n    ident = get_graphnr(string, ndisks);\n  else if (ident > (NPARAMS+(ndisks-1)*NDPARAMS))\n    return -1;\n  \n  if (ident == 0)\n    return -1;\n \n \n  /* Now fill the strings */\n  gr_fillaxis(ident, axis, ndisks);\n  gr_fillunit(ident, unit, ndisks);\n  gr_fillaltunit(ident, altunit, ndisks);\n  gr_filllegend(ident, legend, ndisks);\n\n  /* Finis */\n  return ident;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Identifies a graphics output number */\nstatic int get_graphnr(char *string, int ndisks)\n{\n  if (!strcmp(string, \"WA\"))\n    return NPARAMS+(ndisks-1)*NDPARAMS+WA_GRAPHNR;\n  if (!strcmp(string, \"DENS\"))\n    return NPARAMS+(ndisks-1)*NDPARAMS+DENS_GRAPHNR;\n  if (!strcmp(string, \"WOLD\"))\n    return NPARAMS+(ndisks-1)*NDPARAMS+WOLD_GRAPHNR;\n  if (!strcmp(string, \"TIP\"))\n    return NPARAMS+(ndisks-1)*NDPARAMS+TIP_GRAPHNR;\n  if (!strcmp(string, \"LON\"))\n    return NPARAMS+(ndisks-1)*NDPARAMS+LON_GRAPHNR;\n  return -1;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Returns an axis descriptor string suitable for the use in the pgp module */\nstatic void gr_fillaxis(int ident, char *string, int ndisks)\n{\n  int disk;\n\n  if ((string)) {\n    if (ident ==RADI) {\n      sprintf(string, \"R\");\n      return;\n    }\n    if (ident ==VROT) {\n      sprintf(string, \"VROT\");\n      return;\n    }\n    if (ident ==VRAD) {\n      sprintf(string, \"VRAD\");\n      return;\n    }\n    if (ident ==VVER) {\n      sprintf(string, \"VVER\");\n      return;\n    }\n    if (ident ==DVRO) {\n      sprintf(string, \"DVRO\");\n      return;\n    }\n    if (ident ==DVRA) {\n      sprintf(string, \"DVRA\");\n      return;\n    }\n    if (ident ==DVVE) {\n      sprintf(string, \"DVVE\");\n      return;\n    }\n    if (ident ==ZDRO) {\n      sprintf(string, \"ZDRO\");\n      return;\n    }\n    if (ident ==ZDRA) {\n      sprintf(string, \"ZDRA\");\n      return;\n    }\n    if (ident ==ZDVE) {\n      sprintf(string, \"ZDVE\");\n      return;\n    }\n    if (ident ==Z0) {\n      sprintf(string, \"SCHT\");\n      return;\n    }\n    if (ident ==SDIS) {\n      sprintf(string, \"DISP\");\n      return;\n    }\n    if (ident ==CLNR) {\n      sprintf(string, \"CLNR\");\n      return;\n    }\n    if (ident ==VM0A ) {\n      sprintf(string, \"VM0A\");\n      return;\n    }\n    if (ident ==VM1A) {\n      sprintf(string, \"VM1A\");\n      return;\n    }\n    if (ident ==VM1P) {\n      sprintf(string, \"VM1P\");\n      return;\n    }\n    if (ident ==VM2A) {\n      sprintf(string, \"VM2A\");\n      return;\n    }\n    if (ident ==VM2P) {\n      sprintf(string, \"VM2P\");\n      return;\n    }\n    if (ident ==VM3A) {\n      sprintf(string, \"VM3A\");\n      return;\n    }\n    if (ident ==VM3P) {\n      sprintf(string, \"VM3P\");\n      return;\n    }\n    if (ident ==VM4A) {\n      sprintf(string, \"VM4A\");\n      return;\n    }\n    if (ident ==VM4P) {\n      sprintf(string, \"VM4P\");\n      return;\n    }\n\n    if (ident ==RA1A) {\n      sprintf(string, \"RA1A\");\n      return;\n    }\n    if (ident ==RA1P) {\n      sprintf(string, \"RA1P\");\n      return;\n    }\n    if (ident ==RA2A) {\n      sprintf(string, \"RA2A\");\n      return;\n    }\n    if (ident ==RA2P) {\n      sprintf(string, \"RA2P\");\n      return;\n    }\n    if (ident ==RA3A) {\n      sprintf(string, \"RA3A\");\n      return;\n    }\n    if (ident ==RA3P) {\n      sprintf(string, \"RA3P\");\n      return;\n    }\n    if (ident ==RA4A) {\n      sprintf(string, \"RA4A\");\n      return;\n    }\n    if (ident ==RA4P) {\n      sprintf(string, \"RA4P\");\n      return;\n    }\n    if (ident ==RO1A) {\n      sprintf(string, \"RO1A\");\n      return;\n    }\n    if (ident ==RO1P) {\n      sprintf(string, \"RO1P\");\n      return;\n    }\n    if (ident ==RO2A) {\n      sprintf(string, \"RO2A\");\n      return;\n    }\n    if (ident ==RO2P) {\n      sprintf(string, \"RO2P\");\n      return;\n    }\n    if (ident ==RO3A) {\n      sprintf(string, \"RO3A\");\n      return;\n    }\n    if (ident ==RO3P) {\n      sprintf(string, \"RO3P\");\n      return;\n    }\n    if (ident ==RO4A) {\n      sprintf(string, \"RO4A\");\n      return;\n    }\n    if (ident ==RO4P) {\n      sprintf(string, \"RO4P\");\n      return;\n    }\n    if (ident ==WM0A  ) {\n      sprintf(string, \"WM0A\");\n      return;\n    }\n    if (ident ==WM1A ) {\n      sprintf(string, \"WM1A\");\n      return;\n    }\n    if (ident ==WM1P ) {\n      sprintf(string, \"WM1P\");\n      return;\n    }\n    if (ident ==WM2A ) {\n      sprintf(string, \"WM2A\");\n      return;\n    }\n    if (ident ==WM2P ) {\n      sprintf(string, \"WM2P\");\n      return;\n    }\n    if (ident ==WM3A ) {\n      sprintf(string, \"WM3A\");\n      return;\n    }\n    if (ident ==WM3P ) {\n      sprintf(string, \"WM3P\");\n      return;\n    }\n    if (ident ==WM4A ) {\n      sprintf(string, \"WM4A\");\n      return;\n    }\n    if (ident ==WM4P ) {\n      sprintf(string, \"WM4P\");\n      return;\n    }\n    if (ident ==LS0 ) {\n      sprintf(string, \"LS0\");\n      return;\n    }\n    if (ident ==LC0 ) {\n      sprintf(string, \"LC0\");\n      return;\n    }\n    if (ident ==SBR) {\n      sprintf(string, \"SBR\");\n      return;\n    }\n    if (ident ==SM1A) {\n      sprintf(string, \"SM1A\");\n      return;\n    }\n    if (ident ==SM1P) {\n      sprintf(string, \"SM1P\");\n      return;\n    }\n    if (ident ==SM2A) {\n      sprintf(string, \"SM2A\");\n      return;\n    }\n    if (ident ==SM2P) {\n      sprintf(string, \"SM2P\");\n      return;\n    }\n    if (ident ==SM3A) {\n      sprintf(string, \"SM3A\");\n      return;\n    }\n    if (ident ==SM3P) {\n      sprintf(string, \"SM3P\");\n      return;\n    }\n    if (ident ==SM4A) {\n      sprintf(string, \"SM4A\");\n      return;\n    }\n    if (ident ==SM4P) {\n      sprintf(string, \"SM4P\");\n      return;\n    }\n    if (ident ==GA1A) {\n      sprintf(string, \"GA1A\");\n      return;\n    }\n    if (ident ==GA1P) {\n      sprintf(string, \"GA1P\");\n      return;\n    }\n    if (ident ==GA1D) {\n      sprintf(string, \"GA1D\");\n      return;\n    }\n    if (ident ==GA2A) {\n      sprintf(string, \"GA2A\");\n      return;\n    }\n    if (ident ==GA2P) {\n      sprintf(string, \"GA2P\");\n      return;\n    }\n    if (ident ==GA2D) {\n      sprintf(string, \"GA2D\");\n      return;\n    }\n    if (ident ==GA3A) {\n      sprintf(string, \"GA3A\");\n      return;\n    }\n    if (ident ==GA3P) {\n      sprintf(string, \"GA3P\");\n      return;\n    }\n    if (ident ==GA3D) {\n      sprintf(string, \"GA3D\");\n      return;\n    }\n    if (ident ==GA4A) {\n      sprintf(string, \"GA4A\");\n      return;\n    }\n    if (ident ==GA4P) {\n      sprintf(string, \"GA4P\");\n      return;\n    }\n    if (ident ==GA4D) {\n      sprintf(string, \"GA4D\");\n      return;\n    }\n    if (ident ==AZ1P) {\n      sprintf(string, \"AZ1P\");\n      return;\n    }\n    if (ident ==AZ1W) {\n      sprintf(string, \"AZ1W\");\n      return;\n    }\n    if (ident ==AZ2P) {\n      sprintf(string, \"AZ2P\");\n      return;\n    }\n    if (ident ==AZ2W) {\n      sprintf(string, \"AZ2W\");\n      return;\n    }\n    if (ident ==INCL) {\n      sprintf(string, \"INCL\");\n      return;\n    }\n    if (ident ==PA) {\n      sprintf(string, \"PA\");\n      return;\n    }\n    if (ident ==XPOS) {\n      sprintf(string, \"RA\");\n      return;\n    }\n    if (ident ==YPOS) {\n      sprintf(string, \"DEC\");\n      return;\n    }\n    if (ident ==VSYS) {\n      sprintf(string, \"VSYS\");\n      return;\n    }\n    if (ident == (NPARAMS+(ndisks-1)*NDPARAMS+WA_GRAPHNR)) {\n      sprintf(string, \"WA\");\n      return;\n    }\n    if (ident == (NPARAMS+(ndisks-1)*NDPARAMS+DENS_GRAPHNR)) {\n      sprintf(string, \"SD\");\n      return;\n    }\n    if (ident == (NPARAMS+(ndisks-1)*NDPARAMS+WOLD_GRAPHNR)) {\n      sprintf(string, \"WAOL\");\n      return;\n    }\n    if (ident == (NPARAMS+(ndisks-1)*NDPARAMS+TIP_GRAPHNR)) {\n      sprintf(string, \"TIP\");\n      return;\n    }\n    if (ident == (NPARAMS+(ndisks-1)*NDPARAMS+LON_GRAPHNR)) {\n      sprintf(string, \"LON\");\n      return;\n    }\n    if (ident == (NPARAMS+(ndisks-1)*NDPARAMS+DESH_GRAPHNR)) {\n      sprintf(string, \"DESH\");\n      return;\n    }\n    if (ident == (NPARAMS+(ndisks-1)*NDPARAMS+RASH_GRAPHNR)) {\n      sprintf(string, \"RASH\");\n      return;\n    }\n    \n    for (disk = 1; disk < ndisks; ++disk) {\n      if (ident == VROT+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"VROT_%i\", disk+1);         return;   }\n      if (ident == VRAD+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"VRAD_%i\", disk+1);         return;   }\n      if (ident == VVER+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"VVER_%i\", disk+1);         return;   }\n      if (ident == DVRO+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"DVRO_%i\", disk+1);         return;   }\n      if (ident == DVRA+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"DVRA_%i\", disk+1);         return;   }\n      if (ident == DVVE+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"DVVE_%i\", disk+1);         return;   }\n      if (ident == ZDRO+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"ZDRO_%i\", disk+1);         return;   }\n      if (ident == ZDRA+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"ZDRA_%i\", disk+1);         return;   }\n      if (ident == ZDVE+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"ZDVE_%i\", disk+1);         return;   }\n      if (ident == Z0  +PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"SCHT_%i\", disk+1);         return;   }\n      if (ident == SDIS+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"DISP_%i\", disk+1);         return;   }\n      if (ident == CLNR+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"CLNR_%i\", disk+1);         return;   }\n      if (ident == VM0A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"VM0A_%i\", disk+1);         return;   }\n      if (ident == VM1A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"VM1A_%i\", disk+1);         return;   }\n      if (ident == VM1P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"VM1P_%i\", disk+1);         return;   }\n      if (ident == VM2A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"VM2A_%i\", disk+1);         return;   }\n      if (ident == VM2P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"VM2P_%i\", disk+1);         return;   }\n      if (ident == VM3A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"VM3A_%i\", disk+1);         return;   }\n      if (ident == VM3P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"VM3P_%i\", disk+1);         return;   }\n      if (ident == VM4A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"VM4A_%i\", disk+1);         return;   }\n      if (ident == VM4P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"VM4P_%i\", disk+1);         return;   }\n      if (ident == RA1A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"RA1A_%i\", disk+1);         return;   }\n      if (ident == RA1P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"RA1P_%i\", disk+1);         return;   }\n      if (ident == RA2A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"RA2A_%i\", disk+1);         return;   }\n      if (ident == RA2P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"RA2P_%i\", disk+1);         return;   }\n      if (ident == RA3A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"RA3A_%i\", disk+1);         return;   }\n      if (ident == RA3P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"RA3P_%i\", disk+1);         return;   }\n      if (ident == RA4A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"RA4A_%i\", disk+1);         return;   }\n      if (ident == RA4P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"RA4P_%i\", disk+1);         return;   }\n      if (ident == RO1A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"RO1A_%i\", disk+1);         return;   }\n      if (ident == RO1P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"RO1P_%i\", disk+1);         return;   }\n      if (ident == RO2A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"RO2A_%i\", disk+1);         return;   }\n      if (ident == RO2P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"RO2P_%i\", disk+1);         return;   }\n      if (ident == RO3A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"RO3A_%i\", disk+1);         return;   }\n      if (ident == RO3P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"RO3P_%i\", disk+1);         return;   }\n      if (ident == RO4A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"RO4A_%i\", disk+1);         return;   }\n      if (ident == RO4P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"RO4P_%i\", disk+1);         return;   }\n      if (ident == WM0A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"WM0A_%i\", disk+1);         return;   }\n      if (ident == WM1A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"WM1A_%i\", disk+1);         return;   }\n      if (ident == WM1P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"WM1P_%i\", disk+1);         return;   }\n      if (ident == WM2A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"WM2A_%i\", disk+1);         return;   }\n      if (ident == WM2P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"WM2P_%i\", disk+1);         return;   }\n      if (ident == WM3A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"WM3A_%i\", disk+1);         return;   }\n      if (ident == WM3P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"WM3P_%i\", disk+1);         return;   }\n      if (ident == WM4A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"WM4A_%i\", disk+1);         return;   }\n      if (ident == WM4P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"WM4P_%i\", disk+1);         return;   }\n      if (ident == LS0 +PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"LS0_%i\",  disk+1);         return;   }\n      if (ident == LC0 +PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"LC0_%i\",  disk+1);         return;   }\n      if (ident == SBR +PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"SBR_%i\",  disk+1);         return;   }\n      if (ident == SM1P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"SM1P_%i\", disk+1);         return;   }\n      if (ident == SM2A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"SM2A_%i\", disk+1);         return;   }\n      if (ident == SM2P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"SM2P_%i\", disk+1);         return;   }\n      if (ident == SM3A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"SM3A_%i\", disk+1);         return;   }\n      if (ident == SM3P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"SM3P_%i\", disk+1);         return;   }\n      if (ident == SM4A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"SM4A_%i\", disk+1);         return;   }\n      if (ident == SM4P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"SM4P_%i\", disk+1);         return;   }\n      if (ident == GA1A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"GA1A_%i\", disk+1);         return;   }\n      if (ident == GA1P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"GA1P_%i\", disk+1);         return;   }\n      if (ident == GA1D+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"GA1D_%i\", disk+1);         return;   }\n      if (ident == GA2A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"GA2A_%i\", disk+1);         return;   }\n      if (ident == GA2P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"GA2P_%i\", disk+1);         return;   }\n      if (ident == GA2D+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"GA2D_%i\", disk+1);         return;   }\n      if (ident == GA3A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"GA3A_%i\", disk+1);         return;   }\n      if (ident == GA3P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"GA3P_%i\", disk+1);         return;   }\n      if (ident == GA3D+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"GA3D_%i\", disk+1);         return;   }\n      if (ident == GA4A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"GA4A_%i\", disk+1);         return;   }\n      if (ident == GA4P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"GA4P_%i\", disk+1);         return;   }\n      if (ident == GA4D+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"GA4D_%i\", disk+1);         return;   }\n      if (ident == AZ1P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"AZ1P_%i\", disk+1);         return;   }\n      if (ident == AZ1W+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"AZ1W_%i\", disk+1);         return;   }\n      if (ident == AZ2P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"AZ2P_%i\", disk+1);         return;   }\n      if (ident == AZ2W+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"AZ2W_%i\", disk+1);         return;   }\n      if (ident == INCL+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"INCL_%i\", disk+1);         return;   }\n      if (ident == PA  +PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"PA_%i\",   disk+1);         return;   }\n      if (ident == XPOS+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"XPOS_%i\", disk+1);         return;   }\n      if (ident == YPOS+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"YPOS_%i\", disk+1);         return;   }\n      if (ident == VSYS+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"VSYS_%i\", disk+1);         return;   }\n    }\n  }\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Returns an unit string suitable for the use in the pgp module */\nvoid gr_fillunit(int ident, char *string, int ndisks)\n{\n  if ((string)) {\n    \n    if (ident == RADI) {\n      sprintf(string, \"arcsec\");\n      return;\n    }\n    if (ident == (NPARAMS+(ndisks-1)*NDPARAMS+WA_GRAPHNR)) {\n      sprintf(string, \"degree\");\n      return;\n    }\n    if (ident == (NPARAMS+(ndisks-1)*NDPARAMS+DENS_GRAPHNR)) {\n      sprintf(string, \"cm\\\\u-2\");\n      return;\n    }\n    if (ident == (NPARAMS+(ndisks-1)*NDPARAMS+WOLD_GRAPHNR)) {\n      sprintf(string, \"degree\");\n      return;\n    }\n    if (ident == (NPARAMS+(ndisks-1)*NDPARAMS+TIP_GRAPHNR)) {\n      sprintf(string, \"degree\");\n      return;\n    }\n    if (ident == (NPARAMS+(ndisks-1)*NDPARAMS+LON_GRAPHNR)) {\n      sprintf(string, \"degree\");\n      return;\n    }\n\n    ident = (ident-NSSDPARAMS-1)%NDPARAMS + NSSDPARAMS + 1;\n    switch (ident) {\n    case VROT:\n      sprintf(string, \"km\\\\.s\\\\u-1\");\n      return;\n    case VRAD:\n      sprintf(string, \"km\\\\.s\\\\u-1\");\n      return;\n    case VVER:\n      sprintf(string, \"km\\\\.s\\\\u-1\");\n      return;\n    case DVRO:\n      sprintf(string, \"km\\\\.s\\\\u-1\\\\d\\\\.arcsec\\\\u-1\");\n      return;\n    case DVRA:\n      sprintf(string, \"km\\\\.s\\\\u-1\\\\d\\\\.arcsec\\\\u-1\");\n      return;\n    case DVVE:\n      sprintf(string, \"km\\\\.s\\\\u-1\\\\d\\\\.arcsec\\\\u-1\");\n      return;\n    case ZDRO:\n      sprintf(string, \"arcsec\");\n      return;\n    case ZDRA:\n      sprintf(string, \"arcsec\");\n      return;\n    case ZDVE:\n      sprintf(string, \"arcsec\");\n      return;\n    case Z0:\n      sprintf(string, \"arcsec\");\n      return;\n    case SDIS:\n      sprintf(string, \"km\\\\.s\\\\u-1\");\n      return;\n    case CLNR:\n      sprintf(string, \" \");\n      return;\n    case VM0A :\n      sprintf(string, \"km\\\\.s\\\\u-1\");\n      return;\n    case VM1A:\n      sprintf(string, \"km\\\\.s\\\\u-1\");\n      return;\n    case VM1P:\n      sprintf(string, \"degree\");\n      return;\n    case VM2A:\n      sprintf(string, \"km\\\\.s\\\\u-1\");\n      return;\n    case VM2P:\n      sprintf(string, \"degree\");\n      return;\n    case VM3A:\n      sprintf(string, \"km\\\\.s\\\\u-1\");\n      return;\n    case VM3P:\n      sprintf(string, \"degree\");\n      return;\n    case VM4A:\n      sprintf(string, \"km\\\\.s\\\\u-1\");\n      return;\n    case VM4P:\n      sprintf(string, \"degree\");\n      return;\n    case RA1A:\n      sprintf(string, \"km\\\\.s\\\\u-1\");\n      return;\n    case RA1P:\n      sprintf(string, \"degree\");\n      return;\n    case RA2A:\n      sprintf(string, \"km\\\\.s\\\\u-1\");\n      return;\n    case RA2P:\n      sprintf(string, \"degree\");\n      return;\n    case RA3A:\n      sprintf(string, \"km\\\\.s\\\\u-1\");\n      return;\n    case RA3P:\n      sprintf(string, \"degree\");\n      return;\n    case RA4A:\n      sprintf(string, \"km\\\\.s\\\\u-1\");\n      return;\n    case RA4P:\n      sprintf(string, \"degree\");\n      return;\n    case RO1A:\n      sprintf(string, \"km\\\\.s\\\\u-1\");\n      return;\n    case RO1P:\n      sprintf(string, \"degree\");\n      return;\n    case RO2A:\n      sprintf(string, \"km\\\\.s\\\\u-1\");\n      return;\n    case RO2P:\n      sprintf(string, \"degree\");\n      return;\n    case RO3A:\n      sprintf(string, \"km\\\\.s\\\\u-1\");\n      return;\n    case RO3P:\n      sprintf(string, \"degree\");\n      return;\n    case RO4A:\n      sprintf(string, \"km\\\\.s\\\\u-1\");\n      return;\n    case RO4P:\n      sprintf(string, \"degree\");\n      return;\n    case WM0A  :\n      sprintf(string, \"arcsec\");\n      return;\n    case WM1A :\n      sprintf(string, \"arcsec\");\n      return;\n    case WM1P :\n      sprintf(string, \"degree\");\n      return;\n    case WM2A :\n      sprintf(string, \"arcsec\");\n      return;\n    case WM2P :\n      sprintf(string, \"degree\");\n      return;\n    case WM3A :\n      sprintf(string, \"arcsec\");\n      return;\n    case WM3P :\n      sprintf(string, \"degree\");\n      return;\n    case WM4A :\n      sprintf(string, \"arcsec\");\n      return;\n    case WM4P :\n      sprintf(string, \"degree\");\n      return;\n    case LS0 :\n      sprintf(string, \"arcsec\");\n      return;\n    case LC0 :\n      sprintf(string, \"arcsec\");\n      return;\n    case SBR:\n      sprintf(string, \"Jy\\\\.km\\\\.s\\\\u-1\\\\d\\\\.arcsec\\\\u-2\");\n      return;\n    case SM1A:\n      sprintf(string, \"Jy\\\\.km\\\\.s\\\\u-1\\\\d\\\\.arcsec\\\\u-2\");\n      return;\n    case SM1P:\n      sprintf(string, \"degree\");\n      return;\n    case SM2A:\n      sprintf(string, \"Jy\\\\.km\\\\.s\\\\u-1\\\\d\\\\.arcsec\\\\u-2\");\n      return;\n    case SM2P:\n      sprintf(string, \"degree\");\n      return;\n    case SM3A:\n      sprintf(string, \"Jy\\\\.km\\\\.s\\\\u-1\\\\d\\\\.arcsec\\\\u-2\");\n      return;\n    case SM3P:\n      sprintf(string, \"degree\");\n      return;\n    case SM4A:\n      sprintf(string, \"Jy\\\\.km\\\\.s\\\\u-1\\\\d\\\\.arcsec\\\\u-2\");\n      return;\n    case SM4P:\n      sprintf(string, \"degree\");\n      return;\n    case GA1A:\n      sprintf(string, \"Jy\\\\.km\\\\.s\\\\u-1\\\\d\\\\.arcsec\\\\u-2\");\n      return;    \n    case GA1P:\n      sprintf(string, \"degree\");\n      return;\n    case GA1D:\n      sprintf(string, \"arcsec\");\n      return;\n    case GA2A:\n      sprintf(string, \"Jy\\\\.km\\\\.s\\\\u-1\\\\d\\\\.arcsec\\\\u-2\");\n      return;\n    case GA2P:\n      sprintf(string, \"degree\");\n      return;\n    case GA2D:\n      sprintf(string, \"arcsec\");\n      return;\n    case GA3A:\n      sprintf(string, \"Jy\\\\.km\\\\.s\\\\u-1\\\\d\\\\.arcsec\\\\u-2\");\n      return;\n    case GA3P:\n      sprintf(string, \"degree\");\n      return;\n    case GA3D:\n      sprintf(string, \"arcsec\");\n      return;\n    case GA4A:\n      sprintf(string, \"Jy\\\\.km\\\\.s\\\\u-1\\\\d\\\\.arcsec\\\\u-2\");\n      return;\n    case GA4P:\n      sprintf(string, \"degree\");\n      return;\n    case GA4D:\n      sprintf(string, \"arcsec\");\n      return;\n    case AZ1P:\n      sprintf(string, \"degree\");\n      return;\n    case AZ1W:\n      sprintf(string, \"degree\");\n      return;\n    case AZ2P:\n      sprintf(string, \"degree\");\n      return;\n    case AZ2W:\n      sprintf(string, \"degree\");\n      return;\n    case INCL:\n      sprintf(string, \"degree\");\n      return;\n    case PA:\n      sprintf(string, \"degree\");\n      return;\n    case XPOS:\n      sprintf(string, \"hh mm ss.s\");\n      return;\n    case YPOS:\n      sprintf(string, \"dd mm ss.s\");\n      return;\n    case VSYS:\n      sprintf(string, \"km\\\\.s\\\\u-1\");\n      return;\n    }\n  }\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Returns an alternative unit string suitable for the use in the pgp module */\nstatic void gr_fillaltunit(int ident, char *string, int ndisks)\n{\n  if ((string)) {\n    if (ident == RADI) {\n      sprintf(string, \"kpc\");\n      return;\n    }\n    if (ident == (NPARAMS+(ndisks-1)*NDPARAMS+WA_GRAPHNR)) {\n      sprintf(string, \"degree\");\n      return;\n    }\n    if (ident == (NPARAMS+(ndisks-1)*NDPARAMS+DENS_GRAPHNR)) {\n      sprintf(string, \"M\\\\d\\\\(2281)\\\\u\\\\.pc\\\\u-2\");\n      return;\n    }\n    if (ident == (NPARAMS+(ndisks-1)*NDPARAMS+WOLD_GRAPHNR)) {\n      sprintf(string, \"degree\");\n      return;\n    }\n    if (ident == (NPARAMS+(ndisks-1)*NDPARAMS+TIP_GRAPHNR)) {\n      sprintf(string, \"degree\");\n      return;\n    }\n    if (ident == (NPARAMS+(ndisks-1)*NDPARAMS+LON_GRAPHNR)) {\n      sprintf(string, \"degree\");\n      return;\n    }    \n\n    ident = (ident-NSSDPARAMS-1)%NDPARAMS + NSSDPARAMS + 1;\n    switch (ident) {\n    case VROT:\n      sprintf(string, \"km\\\\.s\\\\u-1\");\n      return;\n    case VRAD:\n      sprintf(string, \"km\\\\.s\\\\u-1\");\n      return;\n    case VVER:\n      sprintf(string, \"km\\\\.s\\\\u-1\");\n      return;\n    case DVRO:\n      sprintf(string, \"km\\\\.s\\\\u-1\\\\d\\\\.pc\\\\u-1\");\n      return;\n    case DVRA:\n      sprintf(string, \"km\\\\.s\\\\u-1\\\\d\\\\.pc\\\\u-1\");\n      return;\n    case DVVE:\n      sprintf(string, \"km\\\\.s\\\\u-1\\\\d\\\\.pc\\\\u-1\");\n      return;\n    case ZDRA:\n      sprintf(string, \"pc\");\n      return;\n    case ZDRO:\n      sprintf(string, \"pc\");\n      return;\n    case ZDVE:\n      sprintf(string, \"pc\");\n      return;\n    case Z0:\n      sprintf(string, \"pc\");\n      return;\n    case SDIS:\n      sprintf(string, \"km\\\\.s\\\\u-1\");\n      return;\n    case CLNR:\n      sprintf(string, \" \");\n      return;\n    case VM0A :\n      sprintf(string, \"km\\\\.s\\\\u-1\");\n      return;\n    case VM1A:\n      sprintf(string, \"km\\\\.s\\\\u-1\");\n      return;\n    case VM1P:\n      sprintf(string, \"degree\");\n      return;\n    case VM2A:\n      sprintf(string, \"km\\\\.s\\\\u-1\");\n      return;\n    case VM2P:\n      sprintf(string, \"degree\");\n      return;\n    case VM3A:\n      sprintf(string, \"km\\\\.s\\\\u-1\");\n      return;\n    case VM3P:\n      sprintf(string, \"degree\");\n      return;\n    case VM4A:\n      sprintf(string, \"km\\\\.s\\\\u-1\");\n      return;\n    case VM4P:\n      sprintf(string, \"degree\");\n      return;\n    case RA1A:\n      sprintf(string, \"km\\\\.s\\\\u-1\");\n      return;\n    case RA1P:\n      sprintf(string, \"degree\");\n      return;\n    case RA2A:\n      sprintf(string, \"km\\\\.s\\\\u-1\");\n      return;\n    case RA2P:\n      sprintf(string, \"degree\");\n      return;\n    case RA3A:\n      sprintf(string, \"km\\\\.s\\\\u-1\");\n      return;\n    case RA3P:\n      sprintf(string, \"degree\");\n      return;\n    case RA4A:\n      sprintf(string, \"km\\\\.s\\\\u-1\");\n      return;\n    case RA4P:\n      sprintf(string, \"degree\");\n      return;\n    case RO1A:\n      sprintf(string, \"km\\\\.s\\\\u-1\");\n      return;\n    case RO1P:\n      sprintf(string, \"degree\");\n      return;\n    case RO2A:\n      sprintf(string, \"km\\\\.s\\\\u-1\");\n      return;\n    case RO2P:\n      sprintf(string, \"degree\");\n      return;\n    case RO3A:\n      sprintf(string, \"km\\\\.s\\\\u-1\");\n      return;\n    case RO3P:\n      sprintf(string, \"degree\");\n      return;\n    case RO4A:\n      sprintf(string, \"km\\\\.s\\\\u-1\");\n      return;\n    case RO4P:\n      sprintf(string, \"degree\");\n      return;\n    case WM0A  :\n      sprintf(string, \"pc\");\n      return;\n    case WM1A :\n      sprintf(string, \"pc\");\n      return;\n    case WM1P :\n      sprintf(string, \"degree\");\n      return;\n    case WM2A :\n      sprintf(string, \"pc\");\n      return;\n    case WM2P :\n      sprintf(string, \"degree\");\n      return;\n    case WM3A :\n      sprintf(string, \"pc\");\n      return;\n    case WM3P :\n      sprintf(string, \"degree\");\n      return;\n    case WM4A :\n      sprintf(string, \"pc\");\n      return;\n    case WM4P :\n      sprintf(string, \"degree\");\n      return;\n    case LS0 :\n      sprintf(string, \"pc\");\n      return;\n    case LC0 :\n      sprintf(string, \"pc\");\n      return;\n    case SBR:\n      sprintf(string, \"cm\\\\u-2\");\n      return;\n    case SM1A:\n      sprintf(string, \"cm\\\\u-2\");\n      return;\n    case SM1P:\n      sprintf(string, \"degree\");\n      return;\n    case SM2A:\n      sprintf(string, \"cm\\\\u-2\");\n      return;\n    case SM2P:\n      sprintf(string, \"degree\");\n      return;\n    case SM3A:\n      sprintf(string, \"cm\\\\u-2\");\n      return;\n    case SM3P:\n      sprintf(string, \"degree\");\n      return;\n    case SM4A:\n      sprintf(string, \"cm\\\\u-2\");\n      return;\n    case SM4P:\n      sprintf(string, \"degree\");\n      return;\n    case GA1A:\n      sprintf(string, \"cm\\\\u-2\");\n      return;    \n    case GA1P:\n      sprintf(string, \"degree\");\n      return;\n    case GA1D:\n      sprintf(string, \"pc\");\n      return;\n    case GA2A:\n      sprintf(string, \"cm\\\\u-2\");\n      return;\n    case GA2P:\n      sprintf(string, \"degree\");\n      return;\n    case GA2D:\n      sprintf(string, \"pc\");\n      return;\n    case GA3A:\n      sprintf(string, \"cm\\\\u-2\");\n      return;\n    case GA3P:\n      sprintf(string, \"degree\");\n      return;\n    case GA3D:\n      sprintf(string, \"pc\");\n      return;\n    case GA4A:\n      sprintf(string, \"cm\\\\u-2\");\n      return;\n    case GA4P:\n      sprintf(string, \"degree\");\n      return;\n    case GA4D:\n      sprintf(string, \"pc\");\n      return;\n    case AZ1P:\n      sprintf(string, \"degree\");\n      return;\n    case AZ1W:\n      sprintf(string, \"degree\");\n      return;\n    case AZ2P:\n      sprintf(string, \"degree\");\n      return;\n    case AZ2W:\n      sprintf(string, \"degree\");\n      return;\n    case INCL:\n      sprintf(string, \"rad\");\n      return;    \n    case PA:  \n      sprintf(string, \"rad\");\n      return;\n    case XPOS:\n      sprintf(string, \"kpc\");\n      return;\n    case YPOS:\n      sprintf(string, \"kpc\");\n      return;\n    case VSYS:\n      sprintf(string, \"km\\\\.s\\\\u-1\");\n      return;\n    }\n  }\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/*  */\n\nstatic int gr_deleteindexed(int nur, int ident, float *xarray, float *yarray, float *yerrarray, decomp_inlist *index, int ndisks)\n{\n  int i = 0, j , k, l, m, ident2;\n  \n  ident2 = ident;\n  \n  if (ident > 0) {\n    if (ident == (NPARAMS+(ndisks-1)*NDPARAMS+WA_GRAPHNR) || ident == (NPARAMS+(ndisks-1)*NDPARAMS+WOLD_GRAPHNR) || ident == (NPARAMS+(ndisks-1)*NDPARAMS+TIP_GRAPHNR) || ident == (NPARAMS+(ndisks-1)*NDPARAMS+LON_GRAPHNR)) {\n      ident = PA;\n      ident2 = INCL;\n    }\n    else if (ident == (NPARAMS+(ndisks-1)*NDPARAMS+DENS_GRAPHNR)){\n      ident = ident2 = SBR;\n    }\n  }\n  \n  l = nur;\n  \n  for (i = 0; i < nur; ++i) {\n    for (m = 0; m < index -> nuel; ++m) {\n      if ((ident-1)*nur+i == index -> ipa[m]) {\n\tfor (j = 0; j < index -> nuel; ++j) {\n\t  if ((ident2-1)*nur+i == index -> ipa[j]) {\n\t    for (k = i-nur+l+1; k < nur; ++k) {\n\t      xarray[k-1] = xarray[k];\n\t      yarray[k-1] = yarray[k];\n\t      yerrarray[k-1] = yerrarray[k];\n\t    }\n\t    --l;\n\t    m = index -> nuel;\n\t    break;\n\t  }\n\t}\n      }\n    }\n  }\n\n  return l;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Fills two arrays for graphics use */\nstatic int fillgrapharray(startinf *startinfv, hdrinf *hdr, ringparms *rpm, int ident, float *array, float *larray, int ndisks)\n{\n  int i, j;\n  \n  int def = 2;\n  int nel = 1;\n  int rring = 5;\n  int err = 1;\n  int gr_tlr = 0;\n  char mes[81];\n  \n  double br_incl;\n  double br_pa;\n  double gr_tll;\n  double nv[3];\n  double nrefr[3];\n  double value;\n  double vsys, nu;\n  double rescval;\n  double x,y;\n  \n      \n\n  /* Check if it can be done */\n  if (ident > 0) {\n    if (ident <= (NPARAMS+(ndisks-1)*NDPARAMS)) {\n      \n      /* Simply put the values into the arrays */\n      for (i = 0; i < rpm -> nur; ++i)\n\tarray[i] = rpm -> par[(ident-1)*rpm -> nur+i];\n      for (i = 0; i < rpm -> nr; ++i)\n\tlarray[i] = rpm -> modpar[(ident-1)*rpm -> nr+i];\n    }\n    else if (ident == (NPARAMS+(rpm -> ndisks-1)*NDPARAMS+WA_GRAPHNR) || ident == (NPARAMS+(rpm -> ndisks-1)*NDPARAMS+WOLD_GRAPHNR)) {\n      if (ident == (NPARAMS+(rpm -> ndisks-1)*NDPARAMS+WA_GRAPHNR)) {\n\t\n\t/* Calculate the normal vector of the reference */\n\tfor (i = 0; i < 3; ++i) {\n\t  nrefr[i] = 0;\n\t}\n\t\n\t/* Now we calculate the direction of the total angular momentum of the observed component */\n\tfor (j = 0; j < rpm -> nr; ++j) {\n   \n\t  /* We don't do a relativistic correction for this */\n\t  value = pow(rpm -> modpar[PRADI*rpm -> nr+j],2)*rpm -> modpar[PVROT*rpm -> nr+j]*rpm -> modpar[PSBR*rpm -> nr+j];\n\t  nrefr[0] = nrefr[0]+(double) value*sin(DEGTORAD*rpm -> modpar[PINCL*rpm -> nr+j])*sin(DEGTORAD*rpm -> modpar[PPA*rpm -> nr+j]);\n\t  nrefr[1] = nrefr[1]-(double) value*sin(DEGTORAD*rpm -> modpar[PINCL*rpm -> nr+j])*cos(DEGTORAD*rpm -> modpar[PPA*rpm -> nr+j]);\n\t  nrefr[2] = nrefr[2]+(double) value*cos(DEGTORAD*rpm -> modpar[PINCL*rpm -> nr+j]);\n\t}\n\t\n\tvalue = sqrt(pow(nrefr[0],2)+pow(nrefr[1],2)+pow(nrefr[2],2));\n\tnrefr[0] = nrefr[0]/value;\n\tnrefr[1] = nrefr[1]/value;\n\tnrefr[2] = nrefr[2]/value;\n      }\n      \n      else {\n\t\n\t/* Get the reference ring */\n\tsprintf(mes, \"Give reference ring for warp angle calculation\");\n\twhile ((err)) {\n\t  userint_tir(startinfv -> arel, &rring, &nel, &def, \"REFRING=\", mes);\n\t  if (rring <= 0 || rring > rpm -> nur) {\n\t    sprintf(mes, \"REFRING: impossible number\");\n\t    cancel_tir(startinfv -> arel, \"REFRING=\", 2);\n\t    def = 4;\n\t  } \n\t  else\n\t    err = 0;\n\t}\n\t\n\t/* Now get the normal vector of the reference ring */\n\tnrefr[0] = sinf(DEGTORAD*rpm -> par[PINCL*rpm -> nur+rring-1])*sinf(DEGTORAD*rpm -> par[PPA*rpm -> nur+rring-1]);\n\tnrefr[1] = -sinf(DEGTORAD*rpm -> par[PINCL*rpm -> nur+rring-1])*cosf(DEGTORAD*rpm -> par[PPA*rpm -> nur+rring-1]);\n\tnrefr[2] = cosf(DEGTORAD*rpm -> par[PINCL*rpm -> nur+rring-1]);\n      }\n      \n      /* Now calculate the inclination of the rings with the refring */\n      for (j = 0; j < rpm -> nur; ++j) {\n\tnv[0] = sin(DEGTORAD*rpm -> par[PINCL*rpm -> nur+j])*sin(DEGTORAD*rpm -> par[PPA*rpm -> nur+j]);\n\tnv[1] = -sin(DEGTORAD*rpm -> par[PINCL*rpm -> nur+j])*cos(DEGTORAD*rpm -> par[PPA*rpm -> nur+j]);\n\tnv[2] = cos(DEGTORAD*rpm -> par[PINCL*rpm -> nur+j]);\n\t\n\t/* Here is the scalar product with the reference ring */\n\tvalue = nv[0]*nrefr[0]+nv[1]*nrefr[1]+nv[2]*nrefr[2];\n\t\n\t/* This is the arcus */\n\tarray[j] = value>1?0.0:RADTODEG*acos(value);\n      }\n      \n      /* Now calculate the inclination of the subrings with the refring */\n      for (j = 0; j < rpm -> nr; ++j) {\n\tnv[0] = sin(DEGTORAD*rpm -> modpar[PINCL*rpm -> nr+j])*sin(DEGTORAD*rpm -> modpar[PPA*rpm -> nr+j]);\n\tnv[1] = -sin(DEGTORAD*rpm -> modpar[PINCL*rpm -> nr+j])*cos(DEGTORAD*rpm -> modpar[PPA*rpm -> nr+j]);\n\tnv[2] = cos(DEGTORAD*rpm -> modpar[PINCL*rpm -> nr+j]);\n\t\n\t/* Here is the scalar product with the reference ring */\n\tvalue = nv[0]*nrefr[0]+nv[1]*nrefr[1]+nv[2]*nrefr[2];\n\t\n\t/* This is the arcus */\n\tlarray[j] = value>1?0.0:RADTODEG*acos(value);\n      }\n    }\n    else if (ident == (NPARAMS+(ndisks-1)*NDPARAMS+DENS_GRAPHNR)){\n      \n      /* We do it properly */\n      for (j = 0; j < rpm -> nur; ++j) {\n\tvsys = rpm -> par[PVSYS*rpm -> nur+j];\n\tnu = (SPEEDOFLIGHT-vsys)*HIRESFREQ/SPEEDOFLIGHT;\n\tvalue = rpm -> par[PSBR*rpm -> nur+j];\n\t\n\t/* The intensity in the restframe scales like */\n\tarray[j] = hdr -> itou*value*pow(HIRESFREQ/nu,4);\n      }\n      for (j = 0; j < rpm -> nr; ++j) {\n\tvsys = rpm -> modpar[PVSYS*rpm -> nr+j];\n\tnu = (SPEEDOFLIGHT-vsys)*HIRESFREQ/SPEEDOFLIGHT;\n\tvalue = rpm -> modpar [PSBR*rpm -> nr+j];\n\t\n\t/* The intensity in the restframe scales like */\n\tlarray[j] = hdr -> itou*value*pow(HIRESFREQ/nu,4);\n      }\n    }\n    else if (ident == (NPARAMS+(ndisks-1)*NDPARAMS+TIP_GRAPHNR) || ident == (NPARAMS+(ndisks-1)*NDPARAMS+LON_GRAPHNR)) {\n      \n      /* Ask for the reference position angle, default 0 */\n      sprintf(mes, \"Give Briggs reference position angle\");\n      br_pa = 0;\n      def = 2;\n      nel = 1;\n      userdble_tir(startinfv -> arel, &br_pa, &nel, &def, \"BR_PA=\", mes);\n      \n      /* Ask for the reference inclination, default 0 */\n      sprintf(mes, \"Give Briggs reference inclination\");\n      br_incl = 0;\n      def = 2;\n      nel = 1;\n      userdble_tir(startinfv -> arel, &br_incl, &nel, &def, \"BR_INCL=\", mes);\n      \n      /* Ask for the angle range, 0: 10-360, 1:-180-180 */\n      sprintf(mes, \"Give range for tiplon diagram 0: 10-360, 1:-180-180\");\n      gr_tlr = 0;\n      def = 2;\n      nel = 1;\n      userint_tir(startinfv -> arel, &gr_tlr, &nel, &def, \"GR_TLR=\", mes);\n\n      \n      /* Then get the stuff in radian */\n      br_incl = DEGTORAD*br_incl;\n      br_pa = DEGTORAD*br_pa;\n\n      if (ident == (NPARAMS+(ndisks-1)*NDPARAMS+TIP_GRAPHNR)) {\n\tfor (j = 0; j < rpm -> nur; ++j) {\n\t  \n\t  /* We get the radian position angle and the radian inclination */\n\t  nrefr[0] = DEGTORAD*rpm -> par[PINCL*rpm -> nur+j];\n\t  nrefr[1] = DEGTORAD*rpm -> par[PPA*rpm -> nur+j];\n   \n\t  /* Then we do this: */\n\t  value = sin(br_incl)*sin(nrefr[0])*cos(nrefr[1]-br_pa)+cos(br_incl)*cos(nrefr[0]);\n\t  array[j] = value>1?0.0:RADTODEG*acos(value);\n\t  /**************/\n\t  /**************/\n\t  /*     sprintf(obsmes, \"tip: %.2f\",array[j]);  */\n\t  /*     anyout_tir(&obsint, obsmes);  */\n\t  /**************/\n\t  \n\t}\n\tfor (j = 0; j < rpm -> nr; ++j) {\n\t  \n\t  /* We get the radian position angle and the radian inclination */\n\t  nrefr[0] = DEGTORAD*rpm -> modpar[PINCL*rpm -> nr+j];\n\t  nrefr[1] = DEGTORAD*rpm -> modpar[PPA*rpm -> nr+j];\n\t  \n\t  /* Then we do this: */\n\t  value = sin(br_incl)*sin(nrefr[0])*cos(nrefr[1]-br_pa)+cos(br_incl)*cos(nrefr[0]);\n\t  larray[j] = value>1?0.0:RADTODEG*acos(value);\n\t}\n      }\n      else {\n\t\n\t/* First scan for the first point where pa and incl are different */\n\trescval = 0.0;\n\tfor (j = 0; j < rpm -> nr; ++j) { \n\t  nrefr[0] = DEGTORAD*rpm -> modpar[PINCL*rpm -> nr+j]; \n\t  nrefr[1] = DEGTORAD*rpm -> modpar[PPA*rpm -> nr+j];\n\t  \n\t  if (maths_checkeq(nrefr[0], br_incl, 1.0E-6) || maths_checkeq(nrefr[1], br_pa, FLOAT_ACCURACY)) {\n\t    \n\t    x = sin(nrefr[0])*sin(nrefr[1]-br_pa);\n\t    y = -cos(br_incl)*sin(nrefr[0])*cos(nrefr[1]-br_pa)+sin(br_incl)*cos(nrefr[0]);\n\t    \n\t    if (y == 0)\n\t      y = 1E-15;\n\t    \n\t    rescval = (x/y);\n\t    \n\t    if ((x<=0) && (y > 0))\n\t      rescval = -atan(rescval);\n\t    if ((x>=0) && (y > 0))\n\t      rescval = TWOPI-atan(rescval);\n\t    \n\t    if ((x>=0) && (y < 0))\n\t      rescval = TWOPI/2-atan(rescval);\n\t    if ((x<=0) && (y < 0))\n\t      rescval = TWOPI/2-atan(rescval);\n\t    break; \n\t  }\n\t}\n\t\n\t/* Ask for the reference LON */\n\tsprintf(mes, \"Give value for indefinite LON\");\n\tgr_tll = RADTODEG*rescval;\n\tdef = 2;\n\tnel = 1;\n\tuserdble_tir(startinfv -> arel, &gr_tll, &nel, &def, \"GR_TLL=\", mes);\n\trescval = DEGTORAD*gr_tll;\n\t/* sprintf(obsmes, \"graph: %.2f\", gr_tll); */\n\t/* anyout_tir(&obsint, obsmes); */\n \n\tfor (j = 0; j < rpm -> nr; ++j) {\n   \n\t  /* We get the radian position angle and the radian inclination */\n\t  nrefr[0] = DEGTORAD*rpm -> modpar[PINCL*rpm -> nr+j];\n\t  nrefr[1] = DEGTORAD*rpm -> modpar[PPA*rpm -> nr+j];\n   \n\t  /* Then we do this: */\n\t  if (maths_checkeq(nrefr[0], br_incl, 1.0E-6) || maths_checkeq(nrefr[1], br_pa, FLOAT_ACCURACY)) {\n     \n\t    x = sin(nrefr[0])*sin(nrefr[1]-br_pa);\n\t    y = -cos(br_incl)*sin(nrefr[0])*cos(nrefr[1]-br_pa)+sin(br_incl)*cos(nrefr[0]);\n     \n\t    if (y == 0.0)\n\t      y = 1E-15;\n     \n\t    value = (x/y);\n     \n\t    if ((x<=0) && (y > 0))\n\t      value = -atan(value);\n\t    if ((x>=0) && (y > 0))\n\t      value = TWOPI-atan(value);\n\t    if ((x>=0) && (y < 0))\n\t      value = TWOPI/2-atan(value);\n\t    if ((x<=0) && (y < 0))\n\t      value = TWOPI/2-atan(value);\n\t    else if ((x<=0) && (y == 0)) \n\t      value = TWOPI/4;\n\t    else if ((x>=0) && (y == 0)) \n\t      value = 3*TWOPI/4;\n\t  }\n\t  else \n\t    value = rescval;\n   \n\t  larray[j] = RADTODEG*value;\n\t  if ((gr_tlr)) {\n\t    if ((larray[j] > 180))\n\t      larray[j] = larray[j]-360.0;\n\t  }\n   \n\t}\n\tfor (j = 0; j < rpm -> nur; ++j) {\n   \n\t  /* We get the radian position angle and the radian inclination */\n\t  nrefr[0] = DEGTORAD*rpm -> par[PINCL*rpm -> nur+j];\n\t  nrefr[1] = DEGTORAD*rpm -> par[PPA*rpm -> nur+j];\n   \n\t  /* Then we do this: */\n\t  if (maths_checkeq(nrefr[0], br_incl, 1.0E-6) || maths_checkeq(nrefr[1], br_pa, FLOAT_ACCURACY)) {\n     \n\t    x = sin(nrefr[0])*sin(nrefr[1]-br_pa);\n\t    y = -cos(br_incl)*sin(nrefr[0])*cos(nrefr[1]-br_pa)+sin(br_incl)*cos(nrefr[0]);\n     \n     \n\t    value = (x/y);\n     \n\t    /**************/\n\t    /**************/\n\t    /* sprintf(obsmes, \"graph: x: %.2f y: %.2f\", x,y); */\n\t    /* anyout_tir(&obsint, obsmes); */\n\t    /**************/\n     \n\t    if ((x<=0) && (y > 0))\n\t      value = -atan(value);\n\t    else if ((x>=0) && (y > 0))\n\t      value = TWOPI-atan(value);\n\t    else if ((x>=0) && (y < 0))\n\t      value = TWOPI/2-atan(value);\n\t    else if ((x<=0) && (y < 0))\n\t      value = TWOPI/2-atan(value);\n\t    else if ((x<=0) && (y == 0)) \n\t      value = TWOPI/4;\n\t    else if ((x>=0) && (y == 0)) \n\t      value = 3*TWOPI/4;\n\t  }\n\t  else \n\t    value = rescval;\n   \n\t  array[j] = RADTODEG*value;\n   \n\t  if ((gr_tlr)) {\n\t    if ((array[j] > 180))\n\t      array[j] = array[j]-360.0;\n\t  }\n\t  /**************/\n\t  /**************/\n\t  /*    sprintf(obsmes, \"lon: %.2f\",array[j]); */\n\t  /*    anyout_tir(&obsint, obsmes); */\n\t  /**************/\n   \n   \n   \n\t}\n      }\n    }\n  }\n  return 1;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Returns a legend string suitable for the use in the pgp module */\nstatic void gr_filllegend(int ident, char *string, int ndisks)\n{\n\n  int disk;\n\n  if ((string)) {\n    if (ident == RADI) {        sprintf(string, \"R: Radius\");      return;}\n    if (ident == VROT) {        sprintf(string, \"VROT: Rotation velocity\"                   );     return;}\n    if (ident == VRAD) {        sprintf(string, \"VRAD: Radial velocity\"                     );     return;}\n    if (ident == VVER) {        sprintf(string, \"VROT: Vertical velocity\"                   );     return;}\n    if (ident == DVRO) {        sprintf(string, \"DVRO: Gradient of rotation velocity\"       );     return;}\n    if (ident == DVRA) {        sprintf(string, \"DVRA: Gradient of radial velocity\"         );     return;}\n    if (ident == DVVE) {        sprintf(string, \"VROT: Gradient of vertical velocity\"       );     return;}\n    if (ident == ZDRO) {        sprintf(string, \"ZDRO: Onset rotation change\"               );     return;}\n    if (ident == ZDRA) {        sprintf(string, \"ZDRA: Onset radial v change\"               );     return;}\n    if (ident == ZDVE) {        sprintf(string, \"ZDVE: Onset vertical v change\"             );     return;}\n    if (ident == Z0) {          sprintf(string, \"SCHT: Scaleheight\"                         );     return;}\n    if (ident == SDIS) {        sprintf(string, \"DISP: Dispersion\"                          );     return;}\n    if (ident == CLNR) {        sprintf(string, \"CLNR: Sub-Cloud number\"                    );     return;}\n    if (ident == VM0A) {        sprintf(string, \"VM0A: Velocity harmonics, 0th order\"       );     return;}\n    if (ident == VM1A) {        sprintf(string, \"VM1A: Velocity harmonics, 1st order, amp\"  );     return;}\n    if (ident == VM1P) {        sprintf(string, \"VM1P: Velocity harmonics, 1st order, phase\");     return;}\n    if (ident == VM2A) {        sprintf(string, \"VM2A: Velocity harmonics, 2nd order, amp\"  );     return;}\n    if (ident == VM2P) {        sprintf(string, \"VM2P: Velocity harmonics, 2nd order, phase\");     return;}\n    if (ident == VM3A) {        sprintf(string, \"VM3A: Velocity harmonics, 3rd order, amp\"  );     return;}\n    if (ident == VM3P) {        sprintf(string, \"VM3P: Velocity harmonics, 3rd order, phase\");     return;}\n    if (ident == VM4A) {        sprintf(string, \"VM4A: Velocity harmonics, 4th order, amp\"  );     return;}\n    if (ident == VM4P) {        sprintf(string, \"VM4P: Velocity harmonics, 4th order, phase\");     return;}\n\n    if (ident == RA1A) {        sprintf(string, \"RA1A: Velocity harmonics (radial), 1st order, amp\"  );     return;}\n    if (ident == RA1P) {        sprintf(string, \"RA1P: Velocity harmonics (radial), 1st order, phase\");     return;}\n    if (ident == RA2A) {        sprintf(string, \"RA2A: Velocity harmonics (radial), 2nd order, amp\"  );     return;}\n    if (ident == RA2P) {        sprintf(string, \"RA2P: Velocity harmonics (radial), 2nd order, phase\");     return;}\n    if (ident == RA3A) {        sprintf(string, \"RA3A: Velocity harmonics (radial), 3rd order, amp\"  );     return;}\n    if (ident == RA3P) {        sprintf(string, \"RA3P: Velocity harmonics (radial), 3rd order, phase\");     return;}\n    if (ident == RA4A) {        sprintf(string, \"RA4A: Velocity harmonics (radial), 4th order, amp\"  );     return;}\n    if (ident == RA4P) {        sprintf(string, \"RA4P: Velocity harmonics (radial), 4th order, phase\");     return;}\n    if (ident == RO1A) {        sprintf(string, \"RO1A: Velocity harmonics (tangential), 1st order, amp\"  );     return;}\n    if (ident == RO1P) {        sprintf(string, \"RO1P: Velocity harmonics (tangential), 1st order, phase\");     return;}\n    if (ident == RO2A) {        sprintf(string, \"RO2A: Velocity harmonics (tangential), 2nd order, amp\"  );     return;}\n    if (ident == RO2P) {        sprintf(string, \"RO2P: Velocity harmonics (tangential), 2nd order, phase\");     return;}\n    if (ident == RO3A) {        sprintf(string, \"RO3A: Velocity harmonics (tangential), 3rd order, amp\"  );     return;}\n    if (ident == RO3P) {        sprintf(string, \"RO3P: Velocity harmonics (tangential), 3rd order, phase\");     return;}\n    if (ident == RO4A) {        sprintf(string, \"RO4A: Velocity harmonics (tangential), 4th order, amp\"  );     return;}\n    if (ident == RO4P) {        sprintf(string, \"RO4P: Velocity harmonics (tangential), 4th order, phase\");     return;}\n    if (ident == SBR) {         sprintf(string, \"SBR: Surface brightness\"                   );     return;}\n    if (ident == SM1A) {        sprintf(string, \"SM1A: Sbr harmonics, 1st order, amp\"       );     return;}\n    if (ident == SM1P) {        sprintf(string, \"SM1P: Sbr harmonics, 1st order, phase\"     );     return;}\n    if (ident == SM2A) {        sprintf(string, \"SM2A: Sbr harmonics, 2nd order, amp\"       );     return;}\n    if (ident == SM2P) {        sprintf(string, \"SM2P: Sbr harmonics, 2nd order, phase\"     );     return;}\n    if (ident == SM3A) {        sprintf(string, \"SM3A: Sbr harmonics, 3rd order, amp\"       );     return;}\n    if (ident == SM3P) {        sprintf(string, \"SM3P: Sbr harmonics, 3rd order, phase\"     );     return;}\n    if (ident == SM4A) {        sprintf(string, \"SM4A: Sbr harmonics, 4th order, amp\"       );     return;}\n    if (ident == SM4P) {        sprintf(string, \"SM4P: Sbr harmonics, 4th order, phase\"     );     return;}\n    if (ident == GA1A) {        sprintf(string, \"GA1A: Sbr Gaussian 1, amplitude\"           );     return;}\n    if (ident == GA1P) {        sprintf(string, \"GA1P: Sbr Gaussian 1, , phase\"             );     return;}\n    if (ident == GA1D) {        sprintf(string, \"GA1D: Sbr Gaussian 1, dispersion\"          );     return;}\n    if (ident == GA2A) {        sprintf(string, \"GA2A: Sbr Gaussian 2, amplitude\"           );     return;}\n    if (ident == GA2P) {        sprintf(string, \"GA2P: Sbr Gaussian 2, , phase\"             );     return;}\n    if (ident == GA2D) {        sprintf(string, \"GA2D: Sbr Gaussian 2, dispersion\"          );     return;}\n    if (ident == GA3A) {        sprintf(string, \"GA3A: Sbr Gaussian 3, amplitude\"           );     return;}\n    if (ident == GA3P) {        sprintf(string, \"GA3P: Sbr Gaussian 3, , phase\"             );     return;}\n    if (ident == GA3D) {        sprintf(string, \"GA3D: Sbr Gaussian 3, dispersion\"          );     return;}\n    if (ident == GA4A) {        sprintf(string, \"GA4A: Sbr Gaussian 4, amplitude\"           );     return;}\n    if (ident == GA4P) {        sprintf(string, \"GA4P: Sbr Gaussian 4, , phase\"             );     return;}\n    if (ident == GA4D) {        sprintf(string, \"GA4D: Sbr Gaussian 4, dispersion\"          );     return;}\n    if (ident == AZ1P) {        sprintf(string, \"AZ1P: Model range 1, position\"             );     return;}\n    if (ident == AZ1W) {        sprintf(string, \"AZ1W: Model range 1, width\"                );     return;}\n    if (ident == AZ2P) {        sprintf(string, \"AZ2P: Model range 2, position\"             );     return;}\n    if (ident == AZ2W) {        sprintf(string, \"AZ2W: Model range 2, width\"                );     return;}\n    if (ident == INCL) {        sprintf(string, \"INCL: Inclination\"                         );     return;}\n    if (ident == PA) {          sprintf(string, \"PA: Position angle\"                        );     return;}\n    if (ident == XPOS) {        sprintf(string, \"RA: Right ascension of centre\"             );     return;}\n    if (ident == YPOS) {        sprintf(string, \"DEC: Declination of centre\"                );     return;}\n    if (ident == VSYS)  {        sprintf(string, \"VSYS: Systemic velocity\"                   );     return;}\n    if (ident == (NPARAMS+(ndisks-1)*NDPARAMS+WA_GRAPHNR)) {  sprintf(string, \"WA: Warp angle\"                            );     return;}\n    if (ident == (NPARAMS+(ndisks-1)*NDPARAMS+DENS_GRAPHNR)) {sprintf(string, \"SD: Surface density\"                       );     return;}\n    if (ident == (NPARAMS+(ndisks-1)*NDPARAMS+WOLD_GRAPHNR)) {sprintf(string, \"WAOL: Warp angle, old definition\"          );     return;}\n    if (ident == (NPARAMS+(ndisks-1)*NDPARAMS+TIP_GRAPHNR))  {sprintf(string, \"TIP: Tip angle\"                            );     return;}\n    if (ident == (NPARAMS+(ndisks-1)*NDPARAMS+LON_GRAPHNR))  {sprintf(string, \"LON: LON angle\"                            );     return;}\n    \n\n    for (disk = 1; disk < ndisks; ++disk) {\n      if (ident == VROT+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"VROT_%i Rotation velocity disk %i\", disk+1, disk+1                  );     return;}\n      if (ident == VRAD+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"VRAD_%i Radial velocity disk %i\", disk+1, disk+1                    );     return;}\n      if (ident == VVER+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"VROT_%i Vertical velocity disk %i\", disk+1, disk+1                  );     return;}\n      if (ident == DVRO+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"DVRO_%i Gradient of rotation velocity disk %i\", disk+1, disk+1      );     return;}\n      if (ident == DVRA+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"DVRA_%i Gradient of radial velocity disk %i\", disk+1, disk+1        );     return;}\n      if (ident == DVVE+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"DVVE_%i Gradient of vertical velocity disk %i\", disk+1, disk+1      );     return;}\n      if (ident == ZDRO+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"ZDRO_%i Onset rotation change disk %i\", disk+1, disk+1      );     return;}\n      if (ident == ZDRA+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"ZDRA_%i Onset radial v change %i\", disk+1, disk+1        );     return;}\n      if (ident == ZDVE+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"ZDVE_%i Onset vertical v change disk %i\", disk+1, disk+1      );     return;}\n      if (ident == Z0  +PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"SCHT_%i Scaleheight disk %i\", disk+1, disk+1                        );     return;}\n      if (ident == SDIS+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"DISP_%i Dispersion disk %i\", disk+1, disk+1                         );     return;}\n      if (ident == CLNR+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"CLNR_%i Sub-Cloud number disk %i\", disk+1, disk+1                   );     return;}\n      if (ident == VM0A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"VM0A_%i Velocity harmonics, 0th order disk %i\", disk+1, disk+1      );     return;}\n      if (ident == VM1A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"VM1A_%i Velocity harmonics, 1st order, amp disk %i\", disk+1, disk+1 );     return;}\n      if (ident == VM1P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"VM1P_%i Velocity harmonics, 1st order, phase disk %i\", disk+1, disk+1);     return;}\n      if (ident == VM2A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"VM2A_%i Velocity harmonics, 2nd order, amp disk %i\", disk+1, disk+1 );     return;}\n      if (ident == VM2P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"VM2P_%i Velocity harmonics, 2nd order, phase disk %i\", disk+1, disk+1);     return;}\n      if (ident == VM3A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"VM3A_%i Velocity harmonics, 3rd order, amp disk %i\", disk+1, disk+1 );     return;}\n      if (ident == VM3P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"VM3P_%i Velocity harmonics, 3rd order, phase disk %i\", disk+1, disk+1);     return;}\n      if (ident == VM4A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"VM4A_%i Velocity harmonics, 4th order, amp disk %i\", disk+1, disk+1 );     return;}\n      if (ident == VM4P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"VM4P_%i Velocity harmonics, 4th order, phase disk %i\", disk+1, disk+1);     return;}\n\n      if (ident == RA1A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"RA1A_%i Velocity harmonics (radial), 1st order, amp disk %i\", disk+1, disk+1 );     return;}\n      if (ident == RA1P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"RA1P_%i Velocity harmonics (radial), 1st order, phase disk %i\", disk+1, disk+1);     return;}\n      if (ident == RA2A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"RA2A_%i Velocity harmonics (radial), 2nd order, amp disk %i\", disk+1, disk+1 );     return;}\n      if (ident == RA2P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"RA2P_%i Velocity harmonics (radial), 2nd order, phase disk %i\", disk+1, disk+1);     return;}\n      if (ident == RA3A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"RA3A_%i Velocity harmonics (radial), 3rd order, amp disk %i\", disk+1, disk+1 );     return;}\n      if (ident == RA3P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"RA3P_%i Velocity harmonics (radial), 3rd order, phase disk %i\", disk+1, disk+1);     return;}\n      if (ident == RA4A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"RA4A_%i Velocity harmonics (radial), 4th order, amp disk %i\", disk+1, disk+1 );     return;}\n      if (ident == RA4P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"RA4P_%i Velocity harmonics (radial), 4th order, phase disk %i\", disk+1, disk+1);     return;}\n      if (ident == RO1A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"RO1A_%i Velocity harmonics (tangential), 1st order, amp disk %i\", disk+1, disk+1 );     return;}\n      if (ident == RO1P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"RO1P_%i Velocity harmonics (tangential), 1st order, phase disk %i\", disk+1, disk+1);     return;}\n      if (ident == RO2A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"RO2A_%i Velocity harmonics (tangential), 2nd order, amp disk %i\", disk+1, disk+1 );     return;}\n      if (ident == RO2P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"RO2P_%i Velocity harmonics (tangential), 2nd order, phase disk %i\", disk+1, disk+1);     return;}\n      if (ident == RO3A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"RO3A_%i Velocity harmonics (tangential), 3rd order, amp disk %i\", disk+1, disk+1 );     return;}\n      if (ident == RO3P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"RO3P_%i Velocity harmonics (tangential), 3rd order, phase disk %i\", disk+1, disk+1);     return;}\n      if (ident == RO4A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"RO4A_%i Velocity harmonics (tangential), 4th order, amp disk %i\", disk+1, disk+1 );     return;}\n      if (ident == RO4P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"RO4P_%i Velocity harmonics (tangential), 4th order, phase disk %i\", disk+1, disk+1);     return;}\n      if (ident == SBR +PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"SBR_%i Surface brightness disk %i\", disk+1, disk+1                  );     return;}\n      if (ident == SM1A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"SM1A_%i Sbr harmonics, 1st order, amp disk %i\", disk+1, disk+1      );     return;}\n      if (ident == SM1P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"SM1P_%i Sbr harmonics, 1st order, phase disk %i\", disk+1, disk+1    );     return;}\n      if (ident == SM2A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"SM2A_%i Sbr harmonics, 2nd order, amp disk %i\", disk+1, disk+1      );     return;}\n      if (ident == SM2P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"SM2P_%i Sbr harmonics, 2nd order, phase disk %i\", disk+1, disk+1    );     return;}\n      if (ident == SM3A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"SM3A_%i Sbr harmonics, 3rd order, amp disk %i\", disk+1, disk+1      );     return;}\n      if (ident == SM3P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"SM3P_%i Sbr harmonics, 3rd order, phase disk %i\", disk+1, disk+1    );     return;}\n      if (ident == SM4A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"SM4A_%i Sbr harmonics, 4th order, amp disk %i\", disk+1, disk+1      );     return;}\n      if (ident == SM4P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"SM4P_%i Sbr harmonics, 4th order, phase disk %i\", disk+1, disk+1    );     return;}\n      if (ident == GA1A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"GA1A_%i Sbr Gaussian 1, amplitude disk %i\", disk+1, disk+1          );     return;}\n      if (ident == GA1P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"GA1P_%i Sbr Gaussian 1, , phase disk %i\", disk+1, disk+1            );     return;}\n      if (ident == GA1D+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"GA1D_%i Sbr Gaussian 1, dispersion disk %i\", disk+1, disk+1         );     return;}\n      if (ident == GA2A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"GA2A_%i Sbr Gaussian 2, amplitude disk %i\", disk+1, disk+1          );     return;}\n      if (ident == GA2P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"GA2P_%i Sbr Gaussian 2, , phase disk %i\", disk+1, disk+1            );     return;}\n      if (ident == GA2D+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"GA2D_%i Sbr Gaussian 2, dispersion disk %i\", disk+1, disk+1         );     return;}\n      if (ident == GA3A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"GA3A_%i Sbr Gaussian 3, amplitude disk %i\", disk+1, disk+1          );     return;}\n      if (ident == GA3P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"GA3P_%i Sbr Gaussian 3, , phase disk %i\", disk+1, disk+1            );     return;}\n      if (ident == GA3D+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"GA3D_%i Sbr Gaussian 3, dispersion disk %i\", disk+1, disk+1         );     return;}\n      if (ident == GA4A+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"GA4A_%i Sbr Gaussian 4, amplitude disk %i\", disk+1, disk+1          );     return;}\n      if (ident == GA4P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"GA4P_%i Sbr Gaussian 4, , phase disk %i\", disk+1, disk+1            );     return;}\n      if (ident == GA4D+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"GA4D_%i Sbr Gaussian 4, dispersion disk %i\", disk+1, disk+1         );     return;}\n      if (ident == AZ1P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"AZ1P_%i Model range 1, position disk %i\", disk+1, disk+1            );     return;}\n      if (ident == AZ1W+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"AZ1W_%i Model range 1, width disk %i\", disk+1, disk+1               );     return;}\n      if (ident == AZ2P+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"AZ2P_%i Model range 2, position disk %i\", disk+1, disk+1            );     return;}\n      if (ident == AZ2W+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"AZ2W_%i Model range 2, width disk %i\", disk+1, disk+1               );     return;}\n      if (ident == INCL+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"INCL_%i Inclination disk %i\", disk+1, disk+1                        );     return;}\n      if (ident == PA  +PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"PA_%i Position angle disk %i\", disk+1, disk+1                       );     return;}\n      if (ident == XPOS+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"XPOS_%i Right ascension of centre disk %i\", disk+1, disk+1            );     return;}\n      if (ident == YPOS+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"YPOS_%i Declination of centre disk %i\", disk+1, disk+1               );     return;}\n      if (ident == VSYS+PRPARAMS+disk*NDPARAMS) {         sprintf(string, \"VSYS_%i Systemic velocity disk %i\", disk+1, disk+1                  );     return;}\n    }\n    string[0] = '\\0'; return;\n\n  }\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Returns the scale for one unit to the alternative unit */\nstatic void gr_fillscaling(loginf *log, hdrinf *hdr, int ident, float *scale, float *zero, int ndisks)\n{\n  \n  if (ident == RADI) {\n    *scale = 1000.0*log -> distance*TWOPI/(360*60*60);\n    *zero = 0.0;\n    return;\n  }\n  if (ident == (NPARAMS+(ndisks-1)*NDPARAMS+WA_GRAPHNR)) {\n    *scale = 1.0;\n    *zero = 0.0;\n    return;\n  }\n  if (ident == (NPARAMS+(ndisks-1)*NDPARAMS+DENS_GRAPHNR)) {\n    *scale = UTOSOLAR;\n    *zero = 0.0;\n    return;\n  }\n  if (ident == (NPARAMS+(ndisks-1)*NDPARAMS+WOLD_GRAPHNR)) {\n    *scale = 1.0;\n    *zero = 0.0;\n    return;\n  }\n  if (ident == (NPARAMS+(ndisks-1)*NDPARAMS+TIP_GRAPHNR)) {\n    *scale = 1.0;\n    *zero = 0.0;\n    return;\n  }\n  if (ident == (NPARAMS+(ndisks-1)*NDPARAMS+LON_GRAPHNR)) {\n    *scale = 1.0;\n    *zero = 0.0;\n    return;\n  }\n  *scale = 1.0;\n  *zero = 0.0;\n  \n/*   ident = ident%NDPARAMS?ident%NDPARAMS:NDPARAMS; */\n  ident = (ident-NSSDPARAMS-1)%NDPARAMS + NSSDPARAMS + 1;\n  switch (ident) {\n  case VROT:\n    *scale = 1.0;\n    *zero = 0.0;\n    return;\n  case VRAD:\n    *scale = 1.0;\n    *zero = 0.0;\n    return;\n  case VVER:\n    *scale = 1.0;\n    *zero = 0.0;\n    return;\n  case DVRO:\n    *scale = 1.0/(log -> distance*TWOPI/(360.0*60.0*60.0)*1000000.0);\n    *zero = 0.0;\n    return;\n  case DVRA:\n    *scale = 1.0/(log -> distance*TWOPI/(360.0*60.0*60.0)*1000000.0);\n    *zero = 0.0;\n    return;\n  case DVVE:\n    *scale = 1.0/(log -> distance*TWOPI/(360.0*60.0*60.0)*1000000.0);\n    *zero = 0.0;\n    return;\n  case ZDRO:\n    *scale = log -> distance*TWOPI/(360.0*60.0*60.0)*1000000.0;\n    *zero = 0.0;\n    return;\n  case ZDRA:\n    *scale = log -> distance*TWOPI/(360.0*60.0*60.0)*1000000.0;\n    *zero = 0.0;\n    return;\n  case ZDVE:\n    *scale = log -> distance*TWOPI/(360.0*60.0*60.0)*1000000.0;\n    *zero = 0.0;\n    return;\n  case Z0:\n    *scale = log -> distance*TWOPI/(360.0*60.0*60.0)*1000000.0;\n    *zero = 0.0;\n    return;\n  case SDIS:\n    *scale = 1.0;\n    *zero = 0.0;\n    return;\n  case CLNR:\n    *scale = 1.0;\n    *zero = 0.0;\n    return;\n  case VM0A:    *scale = 1.0;    *zero = 0.0;    return;\n  case VM1A:    *scale = 1.0;    *zero = 0.0;    return;\n  case VM1P:    *scale = 1.0;    *zero = 0.0;    return;\n  case VM2A:    *scale = 1.0;    *zero = 0.0;    return;\n  case VM2P:    *scale = 1.0;    *zero = 0.0;    return;\n  case VM3A:    *scale = 1.0;    *zero = 0.0;    return;\n  case VM3P:    *scale = 1.0;    *zero = 0.0;    return;\n  case VM4A:    *scale = 1.0;    *zero = 0.0;    return;\n  case VM4P:    *scale = 1.0;    *zero = 0.0;    return;\n  case RA1A:    *scale = 1.0;    *zero = 0.0;    return;\n  case RA1P:    *scale = 1.0;    *zero = 0.0;    return;\n  case RA2A:    *scale = 1.0;    *zero = 0.0;    return;\n  case RA2P:    *scale = 1.0;    *zero = 0.0;    return;\n  case RA3A:    *scale = 1.0;    *zero = 0.0;    return;\n  case RA3P:    *scale = 1.0;    *zero = 0.0;    return;\n  case RA4A:    *scale = 1.0;    *zero = 0.0;    return;\n  case RA4P:    *scale = 1.0;    *zero = 0.0;    return;\n  case RO1A:    *scale = 1.0;    *zero = 0.0;    return;\n  case RO1P:    *scale = 1.0;    *zero = 0.0;    return;\n  case RO2A:    *scale = 1.0;    *zero = 0.0;    return;\n  case RO2P:    *scale = 1.0;    *zero = 0.0;    return;\n  case RO3A:    *scale = 1.0;    *zero = 0.0;    return;\n  case RO3P:    *scale = 1.0;    *zero = 0.0;    return;\n  case RO4A:    *scale = 1.0;    *zero = 0.0;    return;\n  case RO4P:    *scale = 1.0;    *zero = 0.0;    return;\n  case WM0A  :\n    *scale = log -> distance*TWOPI/(360.0*60.0*60.0)*1000000.0;\n    *zero = 0.0;\n    return;\n  case WM1A :\n    *scale = log -> distance*TWOPI/(360.0*60.0*60.0)*1000000.0;\n    *zero = 0.0;\n    return;\n  case WM1P :\n    *scale = 1.0;\n    *zero = 0.0;\n    return;\n  case WM2A :\n    *scale = log -> distance*TWOPI/(360.0*60.0*60.0)*1000000.0;\n    *zero = 0.0;\n    return;\n  case WM2P :\n    *scale = 1.0;\n    *zero = 0.0;\n    return;\n  case WM3A :\n    *scale = log -> distance*TWOPI/(360.0*60.0*60.0)*1000000.0;\n    *zero = 0.0;\n    return;\n  case WM3P :\n    *scale = 1.0;\n    *zero = 0.0;\n    return;\n  case WM4A :\n    *scale = log -> distance*TWOPI/(360.0*60.0*60.0)*1000000.0;\n    *zero = 0.0;\n    return;\n  case WM4P :\n    *scale = 1.0;\n    *zero = 0.0;\n    return;\n\n  case LS0 :\n    *scale = log -> distance*TWOPI/(360.0*60.0*60.0)*1000000.0;\n    *zero = 0.0;\n    return;\n  case LC0 :\n    *scale = log -> distance*TWOPI/(360.0*60.0*60.0)*1000000.0;\n    *zero = 0.0;    \n    return;\n  case SBR:\n    *scale = hdr -> itou;\n    *zero = 0.0;\n    return;\n  case SM1A:    *scale = hdr -> itou;    *zero = 0.0;    return;\n  case SM1P:    *scale = 1.0;    *zero = 0.0;    return;\n  case SM2A:    *scale = hdr -> itou;    *zero = 0.0;    return;\n  case SM2P:    *scale = 1.0;    *zero = 0.0;    return;\n  case SM3A:    *scale = hdr -> itou;    *zero = 0.0;    return;\n  case SM3P:    *scale = 1.0;    *zero = 0.0;    return;\n  case SM4A:    *scale = hdr -> itou;    *zero = 0.0;    return;\n  case SM4P:    *scale = 1.0;    *zero = 0.0;    return;\n\n  case GA1A:    *scale = hdr -> itou;    *zero = 0.0;    return;\n  case GA1P:    *scale = 1.0;    *zero = 0.0;    return;\n  case GA1D:    *scale = log -> distance*TWOPI/(360.0*60.0*60.0)*1000000.0;    *zero = 0.0;    return;\n  case GA2A:    *scale = hdr -> itou;    *zero = 0.0;    return;\n  case GA2P:    *scale = 1.0;    *zero = 0.0;    return;\n  case GA2D:    *scale = log -> distance*TWOPI/(360.0*60.0*60.0)*1000000.0;    *zero = 0.0;    return;\n  case GA3A:    *scale = hdr -> itou;    *zero = 0.0;    return;\n  case GA3P:    *scale = 1.0;    *zero = 0.0;    return;\n  case GA3D:    *scale = log -> distance*TWOPI/(360.0*60.0*60.0)*1000000.0;    *zero = 0.0;    return;\n  case GA4A:    *scale = hdr -> itou;    *zero = 0.0;    return;\n  case GA4P:    *scale = 1.0;    *zero = 0.0;    return;\n  case GA4D:    *scale = log -> distance*TWOPI/(360.0*60.0*60.0)*1000000.0;    *zero = 0.0;    return;\n  case AZ1P:    *scale = 1.0;    *zero = 0.0;    return;\n  case AZ1W:    *scale = 1.0;    *zero = 0.0;    return;\n  case AZ2P:    *scale = 1.0;    *zero = 0.0;    return;\n  case AZ2W:    *scale = 1.0;    *zero = 0.0;    return;\n\n  case INCL:\n    *scale = DEGTORAD;\n    *zero = 0.0;\n    return;\n  case PA:\n    *scale = DEGTORAD;\n    *zero = DEGTORAD*180.0;\n    return;\n  case XPOS:\n    *scale = 1000.0*log -> distance*TWOPI*cos(fabs(log -> yref)*TWOPI/360.0)/360.0;\n    *zero =  1000.0*(-log -> xref)*log -> distance*TWOPI*cos(fabs(log -> yref)*TWOPI/360.0)/360.0;\n    return;\n  case YPOS:\n    *scale = 1000.0*log -> distance*TWOPI/360.0;\n    *zero = 1000.0*(-log -> yref)*log -> distance*TWOPI/360.0;\n    return;\n  case VSYS:\n    *scale = 1.0;\n    *zero = 0.0;\n    return;\n  }\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Produces a renzogram with the rings */\nstatic int renzo(startinf *startinfv, loginf *log, hdrinf *hdr, ringparms *rpm)\n{\n  int i,j,k;\n  char *renzoname = NULL;\n  char mes[81];\n  int def;\n  int nel;\n  qfits_header *header = NULL;\n  Cube thecube;\n  int refine;\n\n  double majhax;\n  double minhax;\n  double point[3];\n  int keypres, nread, nreturned;\n  char **varystr = NULL;\n \n  /* First check if the user wants a renzogram output */\n  /* sprintf(mes, \"Give inclinogram name:\"); */\n  /* for (i = 0; i < 200; ++i) */\n  /*   renzoname[i] = ' '; */\n  /* renzoname[200] = '\\0'; */\n  /* def = 2; */\n  /* nel = 1; */\n  \n  /* userchar_tir(renzoname, &nel, &def, \"INCLINO=\", mes); */\n  /* termsinglestr(renzoname); */\n  \n  /* The default is to do nothing */\n   /* cancel_tir(startinfv -> arel, \"INCLINO\"); */\n\n  if (simparse_scn_arel_readval_stringlist(startinfv -> arel, \"INCLINO\", \"Give graphics (pgplot) device.\", 0, NULL, 0, -1, 0, 0, &keypres, &nread, &nreturned, &varystr))\n    goto error;\n  \n  if ((varystr[0])) {\n    if (!(renzoname = simparse_copystring(varystr[0]))) {\n      goto error;\n    }\n  }\n  else {\n    if (!(renzoname = simparse_copystring(\"\"))) {\n      goto error;\n    }\n  }\n  \n  freeparsed(varystr);\n  varystr = NULL;\n\n  if (*renzoname == '\\0') {\n    free(renzoname);\n    return 1;\n  }\n  \n  /* Ask for refinement */\n  sprintf(mes, \"Give inclinogram refinement:\");\n  def = 2;\n  nel = 1;\n\n  while (refine <= 0) {\n    refine = 1;\n    userint_tir(startinfv -> arel, &refine, &nel, &def, \"IN_REFINE=\", mes);\n    if (refine <= 0) {\n      cancel_tir(startinfv -> arel, \"IN_REFINE=\", 2);\n      sprintf(mes, \"IN_REFINE= must be greater than 0\");\n      def = 1;\n    }\n  }\n\n  if (!(header = makerenzohdr(hdr, rpm -> nur, refine)))\n    return 1;\n\n  /* Now arrange the cube */\n  thecube.refpix_x = 0;\n  thecube.refpix_y = 0;\n  thecube.refpix_v = 0;\n  thecube.size_x = hdr -> bsize1*refine;\n  thecube.size_y = hdr -> bsize2*refine;\n  thecube.size_v = rpm -> nur;\n  thecube.scale = 1.0;\n  thecube.padding = 0;\n  thecube.points = NULL;\n\n  /* Allocate the cube */\n  if (!(thecube.points = (float *) malloc(thecube.size_x*thecube.size_y*thecube.size_v*sizeof(float))))\n    goto error;\n\n  /* Now get the best-fit values and turn them into internal units */\n\n  /* We read all values into the par array */\n  tir_get_grid(log, rpm, log -> outarray);\n\n  for (j = 0; j < rpm -> nur*(NPARAMS+(rpm -> ndisks-1)*NDPARAMS)+NSPARAMS; ++j)\n    rpm -> par[j] = log -> outarray[j];\n  \n  /* We convert to internal units and interpolate over */\n  changetointern(rpm -> par, rpm -> nur, hdr, rpm -> ndisks);\n\n  /* Now se go through the planes, and hence the rings */\n  for (i = 0; i < thecube.size_v; ++i) {\n    \n    /* First calculate the major and the minor half axis */\n    majhax = rpm -> par[PRADI*rpm -> nur+i]*refine;\n    minhax = fabs(cos(rpm -> par[PINCL*rpm -> nur+i]))*majhax;\n\n    /* Each point in the plane will be put to the origin, then be rotated back */\n    for (j = 0; j < thecube.size_x; ++j) {\n      for (k = 0; k < thecube.size_y; ++k) {\n point[0] = cos(rpm -> par[PPA*rpm -> nur+i])*(((double) j) - ((rpm -> par[PXPOS*rpm -> nur+i]+0.5)*refine-0.5))+sin(rpm -> par[PPA*rpm -> nur+i])*(((double) k) - ((rpm -> par[PYPOS*rpm -> nur+i]+0.5)*refine-0.5));\n point[1] = -sin(rpm -> par[PPA*rpm -> nur+i])*(((double) j) - ((rpm -> par[PXPOS*rpm -> nur+i]+0.5)*refine-0.5))+cos(rpm -> par[PPA*rpm -> nur+i])*(((double) k) - ((rpm -> par[PYPOS*rpm -> nur+i]+0.5)*refine-0.5));\n \n if ((minhax > 0.5)) {\n /* Now check if the position is inside an ellipse, if yes, the point is 1, if not 0 */\n if (((minhax*point[0])*(minhax*point[0])+(majhax*point[1])*(majhax*point[1])) > (minhax*minhax*majhax*majhax))\n   thecube.points[j+thecube.size_x*(k+thecube.size_y*i)] = 0;\n else\n   thecube.points[j+thecube.size_x*(k+thecube.size_y*i)] = 1;\n }\n else {\n\n /* We want to prevent that nothing is drawn, so we plot a line if minhax is 0 */\n   if (!maths_checkinbetw(1,-1,point[1]) && (point[0]*point[0] <= majhax*majhax))\n     thecube.points[j+thecube.size_x*(k+thecube.size_y*i)] = 1;\n   else\n     thecube.points[j+thecube.size_x*(k+thecube.size_y*i)] = 0;\n }\n      }\n\n    }\n\n    /* If the major axis is 0, we draw a point */\n    if (majhax < 1)\n      thecube.points[roundnormal((rpm -> par[PXPOS*rpm -> nur+i]+0.5)*refine-0.5)+thecube.size_x*(roundnormal((rpm -> par[PYPOS*rpm -> nur+i]+0.5)*refine-0.5)+thecube.size_y*i)] = 1;\n  }\n  \n  /* Output it */\n  ftsout_writecube(renzoname, &thecube, header);\n  \n  /* Deallocate everything */\n    ftsout_header_destroy(header);\n    free(thecube.points);\n\n    /* Return, deeply satisfied */\n    if ((renzoname))\n      free(renzoname);\n    if (varystr)\n      freeparsed(varystr);\n\n    return 0;\n\n error:\n  if ((header))\n    ftsout_header_destroy(header);\n  if ((thecube.points))\n    free((thecube.points));\n  if ((renzoname))\n    free(renzoname);\n  if (varystr)\n    freeparsed(varystr);\n  return 0;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Make a qfits header suitable for coolgal output */\nstatic qfits_header *makerenzohdr(hdrinf *hdr, int planes, int refine) \n{\n  /*  char key[9] */ \n  char value[21];\n  /* int j; */\n  /* int level = 0; */\n  /* int err = 0; */\n  qfits_header *header = NULL;\n\n  /* The bitpix is -32 */\n  if (!(header = ftsout_putcard(header, \"BITPIX\",\"-32\"))) \n    goto error;\n\n  /* The number of axes is set to three */\n  if (!ftsout_putcard(header, \"NAXIS\",\"3\")) \n    goto error;\n\n  /* Now get the axis numbers */\n  sprintf(value, \"%i\", hdr -> bsize1*refine);\n  if (!ftsout_putcard(header, \"NAXIS1\",value))\n    goto error;\n  sprintf(value, \"%i\", hdr -> bsize2*refine);\n  if (!ftsout_putcard(header, \"NAXIS2\",value))\n    goto error;\n\n  /* The third axis is simply the number of planes */\n  sprintf(value, \"%i\", planes );\n  if (!ftsout_putcard(header, \"NAXIS3\",value))\n    goto error;\n\n  /* May contain an extension */\n  if (!ftsout_putcard(header, \"EXTEND\",\"T\"))\n    goto error;\n  \n  /* These are clear */\n  if (!ftsout_putcard(header, \"BSCALE\",\"1\"))\n    goto error;\n  if (!ftsout_putcard(header, \"BZERO\",\"0\"))\n    goto error;\n\n  /* The bunit is nothing */\n  if (!ftsout_putcard(header, \"BUNIT\",\"' '\"))\n    goto error;\n\n  /* The cdelt is taken from the hdr struct, this should be ok with the unit being DEGREE*/  \n  sprintf(value, \"%.12E\", hdr -> userglobcdelt[0]/refine);\n  if (!ftsout_putcard(header, \"CDELT1\", value))\n    goto error;\n\n  /* The crpix is copied from the header of the inset */\n  sprintf(value, \"%.12E\", (hdr -> setcrpix[0]-0.5)*refine+0.5);\n  if (!ftsout_putcard(header, \"CRPIX1\", value))\n    goto error;\n\n  /* The crval in user units -> degree */\n  sprintf(value, \"%.12E\", hdr -> userglobcrval[0]);\n  if (!ftsout_putcard(header, \"CRVAL1\", value))\n    goto error;\n\n  /* This is nasty, because we have to re-read the info */\n  /* sprintf(key, \"CTYPE%i\", hdr -> inaxperm[0]); */\n  /* for (j = 0; j < 20; ++j) */\n  /*   value[j] = ' '; */\n  /* value[20] = '\\0'; */\n  /* gdsd_rchar_tir(hdr -> inset, key, &(level), value, &err); */\n\n  if (!ftsout_putcard(header, \"CTYPE1\", hdr -> oric -> type_x))\n    goto error;\n  if (!ftsout_putcard(header, \"CUNIT1\", \"'DEGREE            '\"))\n    goto error;\n  \n  /* The cdelt is taken from the hdr struct, this should be ok with the unit being DEGREE*/  \n  sprintf(value, \"%.12E\", hdr -> userglobcdelt[1]/refine);\n  if (!ftsout_putcard(header, \"CDELT2\", value))\n    goto error;\n\n  /* The crpix is copied from the header of the inset */\n  sprintf(value, \"%.12E\", (hdr -> setcrpix[1]-0.5)*refine+0.5);\n  if (!ftsout_putcard(header, \"CRPIX2\", value))\n    goto error;\n\n  /* The crval in user units -> degree */\n  sprintf(value, \"%.12E\", hdr -> userglobcrval[1]);\n  if (!ftsout_putcard(header, \"CRVAL2\", value))\n    goto error;\n\n  /* This is nasty, because we have to re-read the info */\n  /* sprintf(key, \"CTYPE%i\", hdr -> inaxperm[1]); */\n  /* for (j = 0; j < 20; ++j) */\n  /*   value[j] = ' '; */\n  /* value[20] = '\\0'; */\n  /* gdsd_rchar_tir(hdr -> inset, key, &(level), value, &err); */\n\n\n  if (!ftsout_putcard(header, \"CTYPE2\", hdr -> oric -> type_y))\n    goto error;\n  if (!ftsout_putcard(header, \"CUNIT2\", \"'DEGREE            '\"))\n    goto error;\n\n  /* The third axis is the artificial one */\n\n  /* The cdelt is 1 */\n  sprintf(value, \"%.12E\", 1.0);\n  if (!ftsout_putcard(header, \"CDELT3\", value))\n    goto error;\n\n/* crpix is at the start */\n  sprintf(value, \"%.12E\", 1.0);\n  if (!ftsout_putcard(header, \"CRPIX3\", value))\n    goto error;\n\n  /* This is exactly 0 */\n  if (!ftsout_putcard(header, \"CRVAL3\", \"1.0\"))\n    goto error;\n\n  /* The type is somthing without projection, this should do */\n  if (!ftsout_putcard(header, \"CTYPE3\", \"' '\"))\n    goto error;\n\n  /* This is nothing again */\n  if (!ftsout_putcard(header, \"CUNIT3\", \"' '\"))\n    goto error;\n\n  return header;\n  \n error:\n  if ((header)) \n    ftsout_header_destroy(header);\n  header = NULL;\n  return header;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* deallocates an inf_sdis struct */\nstatic int destroy_inf_sdis(inf_sdis *int_sdisv)\n{\n  if (!(int_sdisv))\n    return 0;\n\n/*   if ((int_sdisv -> randstr)) */\n/*     free(int_sdisv -> randstr); */\n  free(int_sdisv);\n  return 0;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* allocates an inf_sdis struct */\nstatic inf_sdis *create_inf_sdis(void)\n{\n  inf_sdis *create_inf_sdis = NULL;\n  if (!(create_inf_sdis = (inf_sdis *) malloc(sizeof(inf_sdis))))\n    return create_inf_sdis;\n\n/*   create_inf_sdis -> randstr = NULL; */\n\n  return create_inf_sdis;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* allocates an inf_smi struct */\nstatic inf_smi *create_inf_smi(void)\n{\n  inf_smi *create_inf_smi = NULL;\n  if (!(create_inf_smi = (inf_smi *) malloc(sizeof(inf_smi))))\n    return create_inf_smi;\n  \n/*   create_inf_smi -> randstr = NULL; */\n\n  return create_inf_smi;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* deallocates an inf_sdis struct */\nstatic int destroy_inf_smi(inf_smi *inf_smiv)\n{\n  if (!(inf_smiv))\n    return 0;\n\n/*     if ((inf_smiv -> randstr)) */\n/*       free(inf_smiv -> randstr); */\n\n  free(inf_smiv);\n  return 0;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    \n\n/* Optionally allocates and puts correct switches in the vm1 struct */    \nstatic int chkb_smi(ringparms *rpm, fitparms *fit) \n{ \n  int actiflag, disk, srnr;\n  \n  for (disk = 0; disk < rpm -> ndisks; ++ disk) {\n    \n    if (!(rpm -> inf_smiv[disk])) \n    if (!(rpm -> inf_smiv[disk] = create_inf_smi())) \n      return 1;\n    \n    actiflag = 0;\n\n    /* check out subring calculation and calculation of surface density */\n    /* Zeroth order */\n    \n    /* First order */\n    if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PSM1A))) { \n      rpm -> inf_smiv[disk] -> prs1 = rpm -> inf_smiv[disk] -> prc1 = &pr_smi_pas; \n      rpm -> inf_smiv[disk] -> srprs1 = rpm -> inf_smiv[disk] -> srprc1 = &srpr_smi_pas;\n    } \n    else {\n      actiflag = 1;\n      rpm -> inf_smiv[disk] -> prs1 = &pr_sm1s_act; \n      rpm -> inf_smiv[disk] -> prc1 = &pr_sm1c_act; \n      rpm -> inf_smiv[disk] -> srprs1 = &srpr_sm1s_act;\n      rpm -> inf_smiv[disk] -> srprc1 = &srpr_sm1c_act;\n      \n      if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PSM1P))) { \n\trpm -> inf_smiv[disk] -> prs1 = &pr_smi_pas; \n\trpm -> inf_smiv[disk] -> srprs1 = &srpr_smi_pas;\n      }\n      else if ((chkb_val(rpm, fit, PRPARAMS+disk*NDPARAMS+PSM1P, PIHALF))) { \n\trpm -> inf_smiv[disk] -> prc1 = &pr_smi_pas; \n\trpm -> inf_smiv[disk] -> srprc1 = &srpr_smi_pas;\n      }\n    }\n    \n    /* second order */\n    if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PSM2A))) { \n      rpm -> inf_smiv[disk] -> prs2 = rpm -> inf_smiv[disk] -> prc2 = &pr_smi_pas; \n      rpm -> inf_smiv[disk] -> srprs2 = rpm -> inf_smiv[disk] -> srprc2 = &srpr_smi_pas;\n    } \n    else {\n      actiflag = 1;\n      rpm -> inf_smiv[disk] -> prs2 = &pr_sm2s_act; \n      rpm -> inf_smiv[disk] -> prc2 = &pr_sm2c_act; \n      rpm -> inf_smiv[disk] -> srprs2 = &srpr_sm2s_act;\n      rpm -> inf_smiv[disk] -> srprc2 = &srpr_sm2c_act;\n      \n      if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PSM2P))) { \n\trpm -> inf_smiv[disk] -> prs2 = &pr_smi_pas; \n\trpm -> inf_smiv[disk] -> srprs2 = &srpr_smi_pas;\n      }\n      else if ((chkb_val(rpm, fit, PRPARAMS+disk*NDPARAMS+PSM2P, PIHALF))) { \n\trpm -> inf_smiv[disk] -> prs2 = &pr_smi_pas; \n\trpm -> inf_smiv[disk] -> srprs2 = &srpr_smi_pas;\n      }\n    }\n    \n    /* third order */\n    if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PSM3A))) { \n      rpm -> inf_smiv[disk] -> prs3 = rpm -> inf_smiv[disk] -> prc3 = &pr_smi_pas; \n      rpm -> inf_smiv[disk] -> srprs3 = rpm -> inf_smiv[disk] -> srprc3 = &srpr_smi_pas;\n    }\n    else {\n      actiflag = 1;\n      rpm -> inf_smiv[disk] -> prs3 = &pr_sm3s_act; \n      rpm -> inf_smiv[disk] -> prc3 = &pr_sm3c_act; \n      rpm -> inf_smiv[disk] -> srprs3 = &srpr_sm3s_act;\n      rpm -> inf_smiv[disk] -> srprc3 = &srpr_sm3c_act;\n      \n      if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PSM3P))) { \n\trpm -> inf_smiv[disk] -> prs3 = &pr_smi_pas; \n\trpm -> inf_smiv[disk] -> srprs3 = &srpr_smi_pas;\n      }\n      else if ((chkb_val(rpm, fit, PRPARAMS+disk*NDPARAMS+PSM3P, PIHALF))) { \n\trpm -> inf_smiv[disk] -> prc3 = &pr_smi_pas; \n\trpm -> inf_smiv[disk] -> srprc3 = &srpr_smi_pas;\n      }\n    }\n    \n    /* fourth order */\n    if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PSM4A))) { \n      rpm -> inf_smiv[disk] -> prs4 = rpm -> inf_smiv[disk] -> prc4 = &pr_smi_pas; \n      rpm -> inf_smiv[disk] -> srprs4 = rpm -> inf_smiv[disk] -> srprc4 = &srpr_smi_pas;\n    } \n    else {\n      actiflag = 1;\n      rpm -> inf_smiv[disk] -> prs4 = &pr_sm4s_act; \n      rpm -> inf_smiv[disk] -> prc4 = &pr_sm4c_act; \n      rpm -> inf_smiv[disk] -> srprs4 = &srpr_sm4s_act;\n      rpm -> inf_smiv[disk] -> srprc4 = &srpr_sm4c_act;\n      \n      if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PSM4P))) { \n\trpm -> inf_smiv[disk] -> prs4 = &pr_smi_pas; \n\trpm -> inf_smiv[disk] -> srprs4 = &srpr_smi_pas;\n      }\n      else if ((chkb_val(rpm, fit, PRPARAMS+disk*NDPARAMS+PSM4P, PIHALF))) { \n\trpm -> inf_smiv[disk] -> prs4 = &pr_smi_pas; \n\trpm -> inf_smiv[disk] -> srprs4 = &srpr_smi_pas;\n      }\n    }\n    \n    /* we allocate the rng, since we will need it */\n    if ((actiflag)) {\n\n      for (srnr = 0; srnr < rpm -> nr; ++srnr)\n      if (!(rpm -> sd[disk][srnr].randstr))\n\tif (!(rpm -> sd[disk][srnr].randstr = (maths_rstrf *) malloc(sizeof(maths_rstrf))))\n\t  goto error;\n      \n      rpm -> inf_smiv[disk] -> prb0 = &pr_sm0b_act;\n      rpm -> inf_smiv[disk] -> srprb0 = &srpr_sm0b_act;\n      rpm -> inf_smiv[disk] -> srprsbrmax = &smi_sbrmax_act;\n      rpm -> inf_smiv[disk] -> getaz = &smi_getaz_harm;\n      rpm -> inf_smiv[disk] -> getcloudnumber = &smi_getcloudnumber_harm;\n      rpm -> inf_smiv[disk] -> rndmf_init = &rndmf_init_smi_act;\n    }\n    else {\n      rpm -> inf_smiv[disk] -> prb0 = &pr_sm0b_pas;\n      rpm -> inf_smiv[disk] -> srprsbrmax = &smi_sbrmax_pas;\n      rpm -> inf_smiv[disk] -> srprb0 = &srpr_smi_pas;\n      rpm -> inf_smiv[disk] -> getaz = &smi_getaz_cons;\n      rpm -> inf_smiv[disk] -> getcloudnumber = &smi_getcloudnumber_norm;\n      rpm -> inf_smiv[disk] -> rndmf_init = &rndmf_init_smi_pas;\n    }\n  }\n  return 0;\n\n error:\n  for (disk = 0; disk < rpm -> ndisks; ++disk) {\n    destroy_inf_smi(rpm -> inf_smiv[disk]);\n    rpm -> inf_smiv[disk] = NULL;\n  }\n  return 1;\n}    \n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* dummy function */\nstatic void srpr_smi_pas(void *rpm, int srnr, int disk)\n{\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates surface brightness sin component and adds it to the subring */\nstatic void srpr_sm0b_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].spb0 = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PSBR)*prm -> nr+srnr]*prm -> sd[disk][srnr].sbrmax;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates surface brightness sin component and adds it to the subring */\nstatic void srpr_sm1s_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].sps1 = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PSM1A)*prm -> nr+srnr]*sinf(prm -> modpar[(PRPARAMS+disk*NDPARAMS+PSM1P)*prm -> nr+srnr])*prm -> sd[disk][srnr].sbrmax;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates surface brightness sin component and adds it to the subring */\nstatic void srpr_sm1c_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].spc1 = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PSM1A)*prm -> nr+srnr]*cosf(prm -> modpar[(PRPARAMS+disk*NDPARAMS+PSM1P)*prm -> nr+srnr])*prm -> sd[disk][srnr].sbrmax;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates surface brightness sin component and adds it to the subring */\nstatic void srpr_sm2s_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].sps2 = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PSM2A)*prm -> nr+srnr]*sinf(2.0*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PSM2P)*prm -> nr+srnr])*prm -> sd[disk][srnr].sbrmax;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates surface brightness sin component and adds it to the subring */\nstatic void srpr_sm2c_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].spc2 = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PSM2A)*prm -> nr+srnr]*cosf(2.0*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PSM2P)*prm -> nr+srnr])*prm -> sd[disk][srnr].sbrmax;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates surface brightness sin component and adds it to the subring */\nstatic void srpr_sm3s_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].sps3 = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PSM3A)*prm -> nr+srnr]*sinf(3.0*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PSM3P)*prm -> nr+srnr])*prm -> sd[disk][srnr].sbrmax;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates surface brightness sin component and adds it to the subring */\nstatic void srpr_sm3c_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].spc3 = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PSM3A)*prm -> nr+srnr]*cosf(3.0*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PSM3P)*prm -> nr+srnr])*prm -> sd[disk][srnr].sbrmax;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates surface brightness sin component and adds it to the subring */\nstatic void srpr_sm4s_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].sps4 = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PSM4A)*prm -> nr+srnr]*sinf(4.0*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PSM4P)*prm -> nr+srnr])*prm -> sd[disk][srnr].sbrmax;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates surface brightness sin component and adds it to the subring */\nstatic void srpr_sm4c_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].spc4 = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PSM4A)*prm -> nr+srnr]*cosf(4.0*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PSM4P)*prm -> nr+srnr])*prm -> sd[disk][srnr].sbrmax;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates surface brightness sin component and adds it to the subring */\nstatic void smi_getcloudnumber_harm(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n  float nor;\n  float ringflux;\n\n  prm = (ringparms *) rpm;\n\n  /* Normalise to point source number instead of surface brightness */\n\n  if (fabs(prm -> modpar[(PRPARAMS+disk*NDPARAMS+PSBR)*prm -> nr+srnr])-(fabs(prm -> modpar[(PRPARAMS+disk*NDPARAMS+PSM1A)*prm -> nr+srnr])+fabs(prm -> modpar[(PRPARAMS+disk*NDPARAMS+PSM2A)*prm -> nr+srnr])+fabs(prm -> modpar[(PRPARAMS+disk*NDPARAMS+PSM3A)*prm -> nr+srnr])+fabs(prm -> modpar[(PRPARAMS+disk*NDPARAMS+PSM4A)*prm -> nr+srnr])) >= 0.0) {\n\n    ringflux = TWOPI*prm -> modpar[PRADI*prm -> nr+srnr]*prm -> radsep*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PSBR)*prm -> nr+srnr];\n\n    /* This is the integral if there is no negative flux (because the integral of a harmonic function with order > 0 is 0), Kamphuis bugfix */\n    /* prm -> sd[disk][srnr].nharmnorm = (long) (ringflux/prm -> cflux[0]); -> */\n    prm -> sd[disk][srnr].nharmnorm = (long) (ringflux/prm -> cflux[disk]);\n    \n    /* correct the point source flux */\n    if ((prm -> sd[disk][srnr].nharmnorm))\n      prm -> sd[disk][srnr].pf = fabs(ringflux)/prm -> sd[disk][srnr].nharmnorm;\n    else\n      /* Kamphuis bugfix */\n/*       prm -> sd[disk][srnr].pf = prm -> cflux[0]; */\n      prm -> sd[disk][srnr].pf = prm -> cflux[disk];\n\n    /* We allow for a negative pointsource flux, even if it makes no sense */\n    if (prm -> sd[disk][srnr].nharmnorm < 0) {\n      prm -> sd[disk][srnr].nharmnorm = -prm -> sd[disk][srnr].nharmnorm;\n    }\n\n    /* We determine the gridder to be the \"normal\" one */\n    prm -> sd[disk][srnr].gridpoint = &gridpoint_norm;\n    prm -> sd[disk][srnr].srput = &srput_norm;\n  }\n  else {\n    \n    /* Normalise to point source number instead of surface brightness */\n    /* Kamphuis bugfix */\n/*     nor = prm -> modpar[PRADI*prm -> nr+srnr]*prm -> radsep/prm -> cflux[0]; -> */\n    nor = prm -> modpar[PRADI*prm -> nr+srnr]*prm -> radsep/prm -> cflux[disk];\n    \n    /* Negative flux occurs, which is why we have to calculate the full integral (numerically) */\n    prm -> sd[disk][srnr].nharmnorm = \n      (long) maths_intabsfou4(\n\t\t\t      nor*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PSBR)*prm -> nr+srnr], \n\t\t\t      nor*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PSM1A)*prm -> nr+srnr], \n\t\t\t      prm -> modpar[(PRPARAMS+disk*NDPARAMS+PSM1P)*prm -> nr+srnr],\n\t\t\t      nor*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PSM2A)*prm -> nr+srnr], \n\t\t\t      prm -> modpar[(PRPARAMS+disk*NDPARAMS+PSM2P)*prm -> nr+srnr],\n\t\t\t      nor*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PSM3A)*prm -> nr+srnr], \n\t\t\t      prm -> modpar[(PRPARAMS+disk*NDPARAMS+PSM3P)*prm -> nr+srnr],\n\t\t\t      nor*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PSM4A)*prm -> nr+srnr], \n\t\t\t      prm -> modpar[(PRPARAMS+disk*NDPARAMS+PSM4P)*prm -> nr+srnr]\n    );\n\n    /* We determine the gridder to be the \"mixed\" one */\n    prm -> sd[disk][srnr].gridpoint = &gridpoint_mixed;\n    prm -> sd[disk][srnr].srput = &srput_mixed;\n\n    /* We reset the number of positive and negative point sources */\n  }\n  \n  /* Change the number of point sources */\n  prm -> sd[disk][srnr].n += prm -> sd[disk][srnr].nharmnorm;\n\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates surface brightness sin component and adds it to the subring */\nstatic void smi_getcloudnumber_norm(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n  float ringflux;\n  prm = (ringparms *) rpm;\n\n  ringflux = TWOPI*prm -> modpar[PRADI*prm -> nr+srnr]*prm -> radsep*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PSBR)*prm -> nr+srnr];\n\n  /* This is the integral if there is no negative flux (because the integral of a harmonic function with order > 0 is 0) */\n  /* Kamphuis bugfix */\n/*   prm -> sd[disk][srnr].nharmnorm = (long) (ringflux/prm -> cflux[0]); -> */\n  prm -> sd[disk][srnr].nharmnorm = (long) (ringflux/prm -> cflux[disk]);\n\n  /* correct the point source flux */\n  if ((prm -> sd[disk][srnr].nharmnorm))\n    prm -> sd[disk][srnr].pf = fabs(ringflux)/prm -> sd[disk][srnr].nharmnorm;\n  else\n    /* Kamphuis bugfix */\n/*     prm -> sd[disk][srnr].pf = prm -> cflux[0]; -> */\n    prm -> sd[disk][srnr].pf = prm -> cflux[disk];\n\n  /* We allow for a negative pointsource flux, even if it makes no sense */\n  if (prm -> sd[disk][srnr].nharmnorm < 0) {\n    prm -> sd[disk][srnr].nharmnorm = -prm -> sd[disk][srnr].nharmnorm;\n  }\n\n  prm -> sd[disk][srnr].n += prm -> sd[disk][srnr].nharmnorm;\n\n  prm -> sd[disk][srnr].gridpoint = &gridpoint_norm;\n  prm -> sd[disk][srnr].srput = &srput_norm;\n\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* dummy instead of pr_smis/c_act */\nstatic void pr_smi_pas(void *rpm, float *sbr, int srnr, float sinaz, float cosaz, int disk)\n{\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial surface brightness component and adds it to the input */\nstatic void pr_sm0b_pas(void *rpm, float *sbr, int srnr, float sinaz, float cosaz, int disk)\n{\n  *sbr = 0.0;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial surface brightness component and adds it to the input */\nstatic void pr_sm0b_act(void *rpm, float *sbr, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *sbr = prm -> sd[disk][srnr].spb0;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial surface brightness component and adds it to the input */\nstatic void pr_sm1s_act(void *rpm, float *sbr, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *sbr = *sbr+sinaz*prm -> sd[disk][srnr].sps1;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial surface brightness component and adds it to the input */\nstatic void pr_sm2s_act(void *rpm, float *sbr, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *sbr = *sbr+(2.0*sinaz*cosaz)* prm -> sd[disk][srnr].sps2;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial surface brightness component and adds it to the input */\nstatic void pr_sm3s_act(void *rpm, float *sbr, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *sbr = *sbr+(3.0*sinaz-4.0*sinaz*sinaz*sinaz)*prm  -> sd[disk][srnr].sps3;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial surface brightness component and adds it to the input */\nstatic void pr_sm4s_act(void *rpm, float *sbr, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *sbr = *sbr+(8.0*sinaz*cosaz*cosaz*cosaz-4.0*sinaz*cosaz)* prm -> sd[disk][srnr].sps4;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial surface brightness component and adds it to the input */\nstatic void pr_sm1c_act(void *rpm, float *sbr, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *sbr = *sbr+cosaz* prm -> sd[disk][srnr].spc1;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial surface brightness component and adds it to the input */\nstatic void pr_sm2c_act(void *rpm, float *sbr, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *sbr = *sbr+(1.0-2.0*sinaz*sinaz)*prm -> sd[disk][srnr].spc2;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial surface brightness component and adds it to the input */\nstatic void pr_sm3c_act(void *rpm, float *sbr, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *sbr = *sbr+(4.0*cosaz*cosaz*cosaz-3.0*cosaz)*prm -> sd[disk][srnr].spc3;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial surface brightness component and adds it to the input */\nstatic void pr_sm4c_act(void *rpm, float *sbr, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *sbr = *sbr+(8.0*cosaz*cosaz*cosaz*cosaz-8.0*cosaz*cosaz+1.0)*prm -> sd[disk][srnr].spc4;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial surface brightness component and adds it to the input */\nstatic void smi_getaz_cons(void *rpm, float *az, float *sinaz, float *cosaz, int *signum, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n\n  *az = TWOPI*maths_rndmf(prm -> sd[disk][srnr].permrandstr);\n  *cosaz = cosf(*az);\n  *sinaz = sinf(*az);\n\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial surface brightness component and adds it to the input */\nstatic void smi_getaz_harm(void *rpm, float *az, float *sinaz, float *cosaz, int *signum, int srnr, int disk)\n{\n  ringparms *prm;\n  float sbr;\n\n  prm = (ringparms *) rpm;\n\n  while (1) {\n    *az = TWOPI*maths_rndmf(prm -> sd[disk][srnr].permrandstr);\n    *cosaz = cosf(*az);\n    *sinaz = sinf(*az);\n\n    /* Caution!!! This function replaces sbr with the constant value */ \n    (*(prm -> inf_smiv[disk] -> prb0))(rpm, &sbr, srnr, *sinaz, *cosaz, disk);\n\n    /* Caution!!! The following functions add to sbr */\n    (*(prm -> inf_smiv[disk] -> prs1))(rpm, &sbr, srnr, *sinaz, *cosaz, disk);\n    (*(prm -> inf_smiv[disk] -> prs2))(rpm, &sbr, srnr, *sinaz, *cosaz, disk);\n    (*(prm -> inf_smiv[disk] -> prs3))(rpm, &sbr, srnr, *sinaz, *cosaz, disk);\n    (*(prm -> inf_smiv[disk] -> prs4))(rpm, &sbr, srnr, *sinaz, *cosaz, disk);\n    (*(prm -> inf_smiv[disk] -> prc1))(rpm, &sbr, srnr, *sinaz, *cosaz, disk);\n    (*(prm -> inf_smiv[disk] -> prc2))(rpm, &sbr, srnr, *sinaz, *cosaz, disk);\n    (*(prm -> inf_smiv[disk] -> prc3))(rpm, &sbr, srnr, *sinaz, *cosaz, disk);\n    (*(prm -> inf_smiv[disk] -> prc4))(rpm, &sbr, srnr, *sinaz, *cosaz, disk);\n\n    if (maths_rndmf(prm -> sd[disk][srnr].randstr) <= fabs(sbr))\n      break;\n    else {\n      /* This is to keep the pointsource lists similar */\n      maths_rndmf(prm -> sd[disk][srnr].permrandstr);\n/*       zprof(prm -> ltype[0],  prm -> sd[disk][srnr].permrandstr)*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PZ0)*prm -> nr+srnr]; */\n      zprof(prm -> ltype[disk],  prm -> sd[disk][srnr].permrandstr, &(prm -> sd[disk][srnr].y2));\n      (*(prm -> inf_sdisv[disk] -> pr_empty))(rpm, srnr, disk);\n    }\n  }\n\n  if (sbr >= 0)\n    *signum = 1;\n  else \n    *signum = 0;\n\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates the sum of absolute amplitudes of surface brightness modes and puts that number in the sbrmax variable of the subring structure */\nstatic void smi_sbrmax_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n  double sbrmax;\n  prm = (ringparms *) rpm;\n\n  sbrmax = (fabs(prm -> modpar[(PRPARAMS+disk*NDPARAMS+PSBR)*prm -> nr+srnr])+fabs(prm -> modpar[(PRPARAMS+disk*NDPARAMS+PSM1A)*prm -> nr+srnr])+fabs(prm -> modpar[(PRPARAMS+disk*NDPARAMS+PSM2A)*prm -> nr+srnr])+fabs(prm -> modpar[(PRPARAMS+disk*NDPARAMS+PSM3A)*prm -> nr+srnr])+fabs(prm -> modpar[(PRPARAMS+disk*NDPARAMS+PSM4A)*prm -> nr+srnr]));\n  if (sbrmax != 0.0)\n    prm -> sd[disk][srnr].sbrmax = 1.0/sbrmax;\n  else\n    sbrmax = 2.0;\n\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial surface brightness component and adds it to the input */\nstatic void smi_sbrmax_pas(void *rpm, int srnr, int disk)\n{\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n\n\n\n\n\n\n\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    \n\n/* Optionally allocates and puts correct switches in the vm1 struct */    \nstatic int chkb_gau(ringparms *rpm, fitparms *fit) \n{ \n  int actiflag, disk, srnr;\n\n  for (disk = 0; disk < rpm -> ndisks; ++ disk) {\n    if (!(rpm -> inf_gauv[disk])) \n      if (!(rpm -> inf_gauv[disk] = create_inf_gau())) \n\treturn 1;\n    \n    actiflag = 0;\n\n    /* check out subring calculation and calculation of surface density */\n    \n    /* First order */\n    if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PGA1A))) { \n      rpm -> inf_gauv[disk] -> srpr0 = &srpr_gau_pas; \n      rpm -> inf_gauv[disk] -> rndmf_init0 = &rndmf_init_gau_pas; \n      rpm -> inf_gauv[disk] -> getcloudnumber0 = gau_getcloudnumber_pas;\n    } \n    else {\n      rpm -> inf_gauv[disk] -> srpr0 = &srpr_gau_act; \n      rpm -> inf_gauv[disk] -> rndmf_init0 = &rndmf_init_gau_act; \n      rpm -> inf_gauv[disk] -> getcloudnumber0 = gau_getcloudnumber_act;\n      for (srnr = 0; srnr < rpm -> nr; ++srnr) {\n      if (!(rpm -> sd[disk][srnr].grandstr[0]))\n\tif (!(rpm -> sd[disk][srnr].grandstr[0] = (maths_rstrf *) malloc(sizeof(maths_rstrf))))\n\t  goto error;\n      }\n      actiflag = 1;\n    }\n    \n    if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PGA2A))) { \n      rpm -> inf_gauv[disk] -> srpr1 = &srpr_gau_pas; \n      rpm -> inf_gauv[disk] -> rndmf_init1 = &rndmf_init_gau_pas; \n      rpm -> inf_gauv[disk] -> getcloudnumber1 = gau_getcloudnumber_pas;\n    } \n    else {\n      rpm -> inf_gauv[disk] -> srpr1 = &srpr_gau_act; \n      rpm -> inf_gauv[disk] -> rndmf_init1 = &rndmf_init_gau_act; \n      rpm -> inf_gauv[disk] -> getcloudnumber1 = gau_getcloudnumber_act;\n      for (srnr = 0; srnr < rpm -> nr; ++srnr) {\n\tif (!(rpm -> sd[disk][srnr].grandstr[1]))\n\t  if (!(rpm -> sd[disk][srnr].grandstr[1] = (maths_rstrf *) malloc(sizeof(maths_rstrf))))\n\t    goto error;\n      }    \n      actiflag = 1;\n    }\n    \n    if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PGA3A))) { \n      rpm -> inf_gauv[disk] -> srpr2 = &srpr_gau_pas; \n      rpm -> inf_gauv[disk] -> rndmf_init2 = &rndmf_init_gau_pas; \n      rpm -> inf_gauv[disk] -> getcloudnumber2 = gau_getcloudnumber_pas;\n  } \n    else {\n      rpm -> inf_gauv[disk] -> srpr2 = &srpr_gau_act; \n      rpm -> inf_gauv[disk] -> rndmf_init2 = &rndmf_init_gau_act; \n      rpm -> inf_gauv[disk] -> getcloudnumber2 = gau_getcloudnumber_act;\n      for (srnr = 0; srnr < rpm -> nr; ++srnr) {\n\tif (!(rpm -> sd[disk][srnr].grandstr[2]))\n\t  if (!(rpm -> sd[disk][srnr].grandstr[2] = (maths_rstrf *) malloc(sizeof(maths_rstrf))))\n\t    goto error;\n      }\n      actiflag = 1;\n    }\n    \n    if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PGA4A))) { \n      rpm -> inf_gauv[disk] -> srpr3 = &srpr_gau_pas; \n      rpm -> inf_gauv[disk] -> rndmf_init3 = &rndmf_init_gau_pas; \n      rpm -> inf_gauv[disk] -> getcloudnumber3 = gau_getcloudnumber_pas;\n    } \n    else {\n      rpm -> inf_gauv[disk] -> srpr3 = &srpr_gau_act; \n      rpm -> inf_gauv[disk] -> rndmf_init3 = &rndmf_init_gau_act; \n      rpm -> inf_gauv[disk] -> getcloudnumber3 = gau_getcloudnumber_act;\n      for (srnr = 0; srnr < rpm -> nr; ++srnr) {\n\tif (!(rpm -> sd[disk][srnr].grandstr[3]))\n\t  if (!(rpm -> sd[disk][srnr].grandstr[3] = (maths_rstrf *) malloc(sizeof(maths_rstrf))))\n\t    goto error;\n      }\n      actiflag = 1;\n    }\n    \n    if ((actiflag)) {\n      ;\n    }\n  }\n  return 0;\n\n error:\n  for (disk = 0; disk < rpm -> ndisks; ++disk) {\n    destroy_inf_gau(rpm -> inf_gauv[disk]);\n    rpm -> inf_gauv[disk] = NULL;\n  }\n  return 1;\n}    \n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* allocates an inf_gau struct */\nstatic inf_gau *create_inf_gau(void)\n{\n  inf_gau *create_inf_gau = NULL;\n\n  if (!(create_inf_gau = (inf_gau *) malloc(sizeof(inf_gau))))\n    return create_inf_gau;\n\n/*   for (i = 0; i < 4; ++i) */\n/*     create_inf_gau -> randstr[i] = NULL; */\n\n  return create_inf_gau;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* deallocates an inf_gau struct */\nstatic int destroy_inf_gau(inf_gau *inf_gauv)\n{\n  if (!(inf_gauv))\n    return 0;\n\n/*   for (i = 0; i < 4; ++i) { */\n/*     if ((inf_gauv -> randstr[i])) */\n/*       free(inf_gauv -> randstr[i]); */\n/*   } */\n  free(inf_gauv);\n  return 0;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates Gaussian surface brightness dispersion in rad and adds it to the subring */\n static void srpr_gau_act(void *rpm, int srnr, int number, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].gaudi[number] = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PGA1D+3*number)*prm -> nr+srnr]/prm -> modpar[PRADI*prm -> nr+srnr];\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Dummy */\n static void srpr_gau_pas(void *rpm, int srnr, int number, int disk)\n{\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Initialises the rng internal to the calulation of sdis */\n static void rndmf_init_gau_act(void *rpm, int srnr, int n, int disk)\n{\n  ringparms *prm;\n  int iseed[2];\n\n  prm = (ringparms *) rpm;\n  iseed[0] = prm -> iseed2+2+n;\n  iseed[1] = srnr;\n\n  /* Reset things */\n  maths_rndmf_init(iseed, prm -> sd[disk][srnr].grandstr[n]);\n  zprof(6, prm -> sd[disk][srnr].grandstr[n], &(prm -> sd[disk][srnr].y2));\n\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* dummy function doing nothing instead of rndmf_init_sdis_act */\n static void rndmf_init_gau_pas(void *rpm, int srnr, int n, int disk)\n{\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates surface brightness sin component and adds it to the subring */\nstatic void gau_getcloudnumber_act(void *rpm, int srnr, int group, int disk)\n{\n  ringparms *prm;\n  float ringflux;\n\n  prm = (ringparms *) rpm;\n\n  /* This defines the amplitude as a real peak value in total surface brightness */\n  ringflux = SQRTOFTWOPI*prm -> modpar[PRADI*prm -> nr+srnr]*prm -> radsep*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PGA1A+3*group)*prm -> nr+srnr]*prm  -> sd[disk][srnr].gaudi[group];\n\n/* This defines the amplitude as the surface brightness averaged over a complete ring */\n/*   ringflux = TWOPI*prm -> modpar[PRADI*prm -> nr+srnr]*prm -> radsep*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PGA1A+3*group)*prm -> nr+srnr]; */\n\n  /* This is the integral if there is no negative flux (because the integral of a harmonic function with order > 0 is 0) */\n  prm -> sd[disk][srnr].ngaussian[group] = (long) fabs(ringflux/prm -> sd[disk][srnr].pf);\n  prm -> sd[disk][srnr].n += prm -> sd[disk][srnr].ngaussian[group];\n\n  /* Change the gridding method if the flux signum of the point sources differs from what we have in the constant expression */\n  if (prm -> sd[disk][srnr].gridpoint == &gridpoint_norm) {\n    if ((prm -> sd[disk][srnr].pf > 0 && ringflux < 0) || (prm -> sd[disk][srnr].pf < 0 && ringflux > 0)) {\n        prm -> sd[disk][srnr].gridpoint = &gridpoint_mixed;\n\tprm -> sd[disk][srnr].srput = &srput_mixed;\n    } \n  }\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates surface brightness sin component and adds it to the subring */\nstatic void gau_getcloudnumber_pas(void *rpm, int srnr, int group, int disk)\n{\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* get azimuth from Gaussian descriptors */\nstatic void gau_getaz(ringparms *prm, int pgaip, maths_rstrf *randstr, int pgaid, float *az, float *sinaz, float *cosaz, int srnr, int disk)\n{\n  *az = fmodf(prm -> modpar[pgaip*prm -> nr+srnr]+zprof(1, randstr, &(prm -> sd[disk][srnr].y2))*prm  -> sd[disk][srnr].gaudi[pgaid], TWOPI);\n  while (*az < 0.0)\n    *az = *az+TWOPI;\n/* *az = prm -> modpar[pgaip*prm -> nr+srnr]+zprof(1, randstr)*prm  -> sd[disk][srnr].gaudi[pgaid]; */\n/*   *az = prm -> modpar[(PRPARAMS+disk*NDPARAMS+pgaip)*prm -> nr+srnr]+zprof(1, randstr)*prm  -> sd[disk][srnr].gaudi[pgaid]; */\n/*   az = prm -> modpar[(PRPARAMS+disk*NDPARAMS+pgaip)*prm -> nr+srnr]+zprof(1, randstr)*prm -> modpar[(PRPARAMS+disk*NDPARAMS+pgaid)*prm -> nr+srnr]; */\n  *sinaz = sinf(*az);\n  *cosaz = cosf(*az);\n\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n\n\n\n\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* allocates an inf_azi struct */\nstatic inf_azi *create_inf_azi(void)\n{\n  inf_azi *create_inf_azi = NULL;\n\n  if (!(create_inf_azi = (inf_azi *) malloc(sizeof(inf_azi))))\n    return create_inf_azi;\n\n  return create_inf_azi;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* deallocates an inf_azi struct */\nstatic int destroy_inf_azi(inf_azi *inf_aziv)\n{\n  if (!(inf_aziv))\n    return 0;\n\n  free(inf_aziv);\n  return 0;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    \n\n/* Optionally allocates and puts correct switches in the vm1 struct */    \nstatic int chkb_azi(ringparms *rpm, fitparms *fit) \n{ \n  int actiflag, disk;\n\n  for (disk = 0; disk < rpm -> ndisks; ++ disk) {\n\n    actiflag = 0;\n\n    if (!(rpm -> inf_aziv[disk])) \n      if (!(rpm -> inf_aziv[disk] = create_inf_azi())) \n\treturn 1;\n    \n    rpm -> inf_aziv[disk] -> pr0 = &pr_azi_pas; \n    rpm -> inf_aziv[disk] -> pr1 = &pr_azi_pas; \n\n    /* First range */\n    if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PAZ1W))) { \n      rpm -> inf_aziv[disk] -> srpr0 = &srpr_azi_pas; \n    } \n    else {\n      rpm -> inf_aziv[disk] -> srpr0 = &srpr_azi_act; \n      rpm -> inf_aziv[disk] -> pr0 = &pr_azi_act; \n      actiflag = 1;\n    }\n    \n    /* Second range */\n    if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PAZ2W))) { \n      rpm -> inf_aziv[disk] -> srpr1 = &srpr_azi_pas; \n    } \n    else {\n      rpm -> inf_aziv[disk] -> srpr1 = &srpr_azi_act;\n      rpm -> inf_aziv[disk] -> pr1 = &pr_azi_act; \n      actiflag = 1;\n    }\n    \n    rpm -> inf_aziv[disk] -> srshape = &srshape_azi_pas; \n    rpm -> inf_aziv[disk] -> corrp = &corrp_azi_pas; \n    rpm -> inf_aziv[disk] -> setoutrange = &setoutrange_azi_pas; \n    \n    if ((actiflag)) {\n      rpm -> inf_aziv[disk] -> srshape = &srshape_azi_act; \n      rpm -> inf_aziv[disk] -> corrp = &corrp_azi_act;\n      rpm -> inf_aziv[disk] -> setoutrange = &setoutrange_azi_act; \n    }\n  }  \n   \n  return 0;\n      \n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates Gaussian surface brightness dispersion in rad and adds it to the subring */\nstatic void srpr_azi_act(void *rpm, int srnr, int number, int disk)\n{\n  ringparms *prm;\n  float azi;\n \n  prm = (ringparms *) rpm;\n\n  azi = fmodf(prm -> modpar[(PRPARAMS+disk*NDPARAMS+PAZ1P+2*number)*prm -> nr+srnr],TWOPI);\n  \n  while (azi < 0.0)\n    azi = azi+TWOPI;\n  \n  prm -> sd[disk][srnr].ranges[number][0] = azi-0.5*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PAZ1W+2*number)*prm -> nr+srnr];\n  prm -> sd[disk][srnr].ranges[number][1] = azi+0.5*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PAZ1W+2*number)*prm -> nr+srnr];\n  \n  if (prm -> sd[disk][srnr].ranges[number][1] > TWOPI) {\n    prm -> sd[disk][srnr].ranges[number][2] = prm -> sd[disk][srnr].ranges[number][0]-TWOPI;\n    prm -> sd[disk][srnr].ranges[number][3] = prm -> sd[disk][srnr].ranges[number][1]-TWOPI;\n  }\n  else {\n    prm -> sd[disk][srnr].ranges[number][2] = prm -> sd[disk][srnr].ranges[number][0]+TWOPI;\n    prm -> sd[disk][srnr].ranges[number][3] = prm -> sd[disk][srnr].ranges[number][1]+TWOPI;\n  }\n\n  prm -> sd[disk][srnr].outofrange = 1;\n\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Dummy */\nstatic void srpr_azi_pas(void *rpm, int srnr, int number, int disk)\n{\n  ringparms *prm;\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].outofrange = 0;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Check if azimuth is in allowed range and put switches */\nstatic void pr_azi_pas(float *azi, float ranges[2][4], int *outofrange, int i)\n{\n/*   *outofrange = 0; */\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Check if azimuth is in allowed range and put switches */\nstatic void setoutrange_azi_pas(int *outofrange)\n{\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Check if azimuth is in allowed range and put switches */\nstatic void setoutrange_azi_act(int *outofrange)\n{\n  *outofrange = 1;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Check if azimuth is in allowed range and put switches */\nstatic void pr_azi_act(float *azi, float ranges[2][4], int *outofrange, int i)\n{\n/*   if ((*outofrange)) { */\n/*     if (maths_checkinbetwf(ranges[i][0], ranges[i][1], *azi) || maths_checkinbetwf(ranges[i][2], ranges[i][3], *azi)) { */\n/*       *outofrange = 0; */\n/*     } */\n/*   } */\n\n/* Changed to this */\n/*   *outofrange = 1; */\n  if (maths_checkinbetwf(ranges[i][0], ranges[i][1], *azi) || maths_checkinbetwf(ranges[i][2], ranges[i][3], *azi)) {\n    *outofrange = 0;\n  }\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Generation of a pointsource list */\nstatic int srshape_azi_act(void *rpm, float *pp, float sinaz, float cosaz, int srnr, int outofrange, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n\n  if ((outofrange)) {\n    maths_rndmf(prm -> sd[disk][srnr].permrandstr);\n    zprof(prm -> ltype[disk],  prm -> sd[disk][srnr].permrandstr, &(prm -> sd[disk][srnr].y2));\n\n    /* This shift by 5000000 pixels should do, one could do more elegant, but I'm tired */\n     pp[1] = 5000000.;\n     return 1;\n  }\n  else {\n    srshape(prm, pp, sinaz, cosaz, srnr, disk);\n  }\n  \n  return 0;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Generation of a pointsource list */\nstatic int srshape_azi_pas(void *rpm, float *pp, float sinaz, float cosaz, int srnr, int outofrange, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n\n  srshape(prm, pp, sinaz, cosaz, srnr, disk);\n\n  return 0;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Generation of a pointsource list */\nstatic int srshape_azi_actcool(void *rpm, float *pp, float sinaz, float cosaz, int srnr, int outofrange, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n\n  if ((outofrange)) {\n    maths_rndmf(prm -> sd[disk][srnr].permrandstr);\n    zprof(prm -> ltype[disk],  prm -> sd[disk][srnr].permrandstr, &(prm -> sd[disk][srnr].y2));\n\n    /* This shift by 5000000 pixels should do, one could do more elegant, but I'm tired */\n     pp[1] = 5000000.;\n     return 1;\n  }\n  else {\n    srshapecool(prm, pp, sinaz, cosaz, srnr, disk);\n  }\n  \n  return 0;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Generation of a pointsource list */\nstatic int srshape_azi_pascool(void *rpm, float *pp, float sinaz, float cosaz, int srnr, int outofrange, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n\n  srshapecool(prm, pp, sinaz, cosaz, srnr, disk);\n\n  return 0;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Generation of a pointsource list */\nstatic void corrp_azi_act(void *rpm, int srnr, int *outofrange, int signum)\n{\n  /* ringparms *prm; */\n\n  /* prm = (ringparms *) rpm; */\n\n/*   if ((*outofrange)) { */\n/*     --prm -> sd[disk][srnr].outn; */\n/*   } */\n\n  *outofrange = 1;\n\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Generation of a pointsource list */\nstatic void corrp_azi_pas(void *rpm, int srnr, int *outofrange, int signum)\n{\n return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* allocates an inf_vrad  struct */   static inf_vrad *create_inf_vrad(void)    {    inf_vrad  *create_inf_vrad= NULL;    if (!(create_inf_vrad = (inf_vrad *) malloc(sizeof(inf_vrad))))    return create_inf_vrad;    return create_inf_vrad;   }    /* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* allocates an inf_vver  struct */   static inf_vver *create_inf_vver(void)    {    inf_vver  *create_inf_vver= NULL;    if (!(create_inf_vver = (inf_vver *) malloc(sizeof(inf_vver))))    return create_inf_vver;    return create_inf_vver;   }    /* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* allocates an inf_dvro  struct */   static inf_dvro *create_inf_dvro(void)    {    inf_dvro  *create_inf_dvro= NULL;    if (!(create_inf_dvro = (inf_dvro *) malloc(sizeof(inf_dvro))))    return create_inf_dvro;    return create_inf_dvro;   }    /* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* allocates an inf_dvra  struct */   static inf_dvra *create_inf_dvra(void)    {    inf_dvra  *create_inf_dvra= NULL;    if (!(create_inf_dvra = (inf_dvra *) malloc(sizeof(inf_dvra))))    return create_inf_dvra;    return create_inf_dvra;   }    /* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* allocates an inf_dvve  struct */   static inf_dvve *create_inf_dvve(void)    {    inf_dvve  *create_inf_dvve= NULL;    if (!(create_inf_dvve = (inf_dvve *) malloc(sizeof(inf_dvve))))    return create_inf_dvve;    return create_inf_dvve;   }    /* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* allocates an inf_vm0  struct */   static inf_vm0 *create_inf_vm0(void)    {    inf_vm0  *create_inf_vm0= NULL;    if (!(create_inf_vm0 = (inf_vm0 *) malloc(sizeof(inf_vm0))))    return create_inf_vm0;    return create_inf_vm0;   }    /* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* allocates an inf_vm1 struct */    static inf_vm1 *create_inf_vm1(void)    {    inf_vm1 *create_inf_vm1 = NULL;    if (!(create_inf_vm1 = (inf_vm1 *) malloc(sizeof(inf_vm1))))    return create_inf_vm1;    return create_inf_vm1;   }    /* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* allocates an inf_vm2 struct */    static inf_vm2 *create_inf_vm2(void)    {    inf_vm2 *create_inf_vm2 = NULL;    if (!(create_inf_vm2 = (inf_vm2 *) malloc(sizeof(inf_vm2))))    return create_inf_vm2;    return create_inf_vm2;   }    /* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* allocates an inf_vm3 struct */    static inf_vm3 *create_inf_vm3(void)    {    inf_vm3 *create_inf_vm3 = NULL;    if (!(create_inf_vm3 = (inf_vm3 *) malloc(sizeof(inf_vm3))))    return create_inf_vm3;    return create_inf_vm3;   }    /* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* allocates an inf_vm4 struct */    static inf_vm4 *create_inf_vm4(void)    {    inf_vm4 *create_inf_vm4 = NULL;    if (!(create_inf_vm4 = (inf_vm4 *) malloc(sizeof(inf_vm4))))    return create_inf_vm4;    return create_inf_vm4;   }    /* ------------------------------------------------------------ */\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* allocates an inf_ra1 struct */    static inf_ra1 *create_inf_ra1(void)    {    inf_ra1 *create_inf_ra1 = NULL;    if (!(create_inf_ra1 = (inf_ra1 *) malloc(sizeof(inf_ra1))))    return create_inf_ra1;    return create_inf_ra1;   }    /* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* allocates an inf_ra2 struct */    static inf_ra2 *create_inf_ra2(void)    {    inf_ra2 *create_inf_ra2 = NULL;    if (!(create_inf_ra2 = (inf_ra2 *) malloc(sizeof(inf_ra2))))    return create_inf_ra2;    return create_inf_ra2;   }    /* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* allocates an inf_ra3 struct */    static inf_ra3 *create_inf_ra3(void)    {    inf_ra3 *create_inf_ra3 = NULL;    if (!(create_inf_ra3 = (inf_ra3 *) malloc(sizeof(inf_ra3))))    return create_inf_ra3;    return create_inf_ra3;   }    /* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* allocates an inf_ra4 struct */    static inf_ra4 *create_inf_ra4(void)    {    inf_ra4 *create_inf_ra4 = NULL;    if (!(create_inf_ra4 = (inf_ra4 *) malloc(sizeof(inf_ra4))))    return create_inf_ra4;    return create_inf_ra4;   }    /* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* allocates an inf_ro1 struct */    static inf_ro1 *create_inf_ro1(void)    {    inf_ro1 *create_inf_ro1 = NULL;    if (!(create_inf_ro1 = (inf_ro1 *) malloc(sizeof(inf_ro1))))    return create_inf_ro1;    return create_inf_ro1;   }    /* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* allocates an inf_ro2 struct */    static inf_ro2 *create_inf_ro2(void)    {    inf_ro2 *create_inf_ro2 = NULL;    if (!(create_inf_ro2 = (inf_ro2 *) malloc(sizeof(inf_ro2))))    return create_inf_ro2;    return create_inf_ro2;   }    /* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* allocates an inf_ro3 struct */    static inf_ro3 *create_inf_ro3(void)    {    inf_ro3 *create_inf_ro3 = NULL;    if (!(create_inf_ro3 = (inf_ro3 *) malloc(sizeof(inf_ro3))))    return create_inf_ro3;    return create_inf_ro3;   }    /* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* allocates an inf_ro4 struct */    static inf_ro4 *create_inf_ro4(void)    {    inf_ro4 *create_inf_ro4 = NULL;    if (!(create_inf_ro4 = (inf_ro4 *) malloc(sizeof(inf_ro4))))    return create_inf_ro4;    return create_inf_ro4;   }    /* ------------------------------------------------------------ */\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* allocates an inf_wm0   struct */    static inf_wm0   *create_inf_wm0  (void)    {    inf_wm0   *create_inf_wm0   = NULL;    if (!(create_inf_wm0   = (inf_wm0   *) malloc(sizeof(inf_wm0  ))))    return create_inf_wm0  ;    return create_inf_wm0  ;   }    /* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* allocates an inf_wm1  struct */    static inf_wm1  *create_inf_wm1 (void)    {    inf_wm1  *create_inf_wm1  = NULL;    if (!(create_inf_wm1  = (inf_wm1  *) malloc(sizeof(inf_wm1 ))))    return create_inf_wm1 ;    return create_inf_wm1 ;   }    /* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* allocates an inf_wm2  struct */    static inf_wm2  *create_inf_wm2 (void)    {    inf_wm2  *create_inf_wm2  = NULL;    if (!(create_inf_wm2  = (inf_wm2  *) malloc(sizeof(inf_wm2 ))))    return create_inf_wm2 ;    return create_inf_wm2 ;   }    /* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* allocates an inf_wm3  struct */    static inf_wm3  *create_inf_wm3 (void)    {    inf_wm3  *create_inf_wm3  = NULL;    if (!(create_inf_wm3  = (inf_wm3  *) malloc(sizeof(inf_wm3 ))))    return create_inf_wm3 ;    return create_inf_wm3 ;   }    /* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* allocates an inf_wm4  struct */    static inf_wm4  *create_inf_wm4 (void)    {    inf_wm4  *create_inf_wm4  = NULL;    if (!(create_inf_wm4  = (inf_wm4  *) malloc(sizeof(inf_wm4 ))))    return create_inf_wm4 ;    return create_inf_wm4 ;   }    /* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* allocates an inf_ls0  struct */    static inf_ls0  *create_inf_ls0 (void)    {    inf_ls0  *create_inf_ls0  = NULL;    if (!(create_inf_ls0  = (inf_ls0  *) malloc(sizeof(inf_ls0 ))))    return create_inf_ls0 ;    return create_inf_ls0 ;   }    /* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* allocates an inf_lc0  struct */    static inf_lc0  *create_inf_lc0 (void)    {    inf_lc0  *create_inf_lc0  = NULL;    if (!(create_inf_lc0  = (inf_lc0  *) malloc(sizeof(inf_lc0 ))))    return create_inf_lc0 ;    return create_inf_lc0 ;   }    /* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* deallocates an inf_vm0  struct */    static int destroy_inf_vrad (inf_vrad  *int_vradv )    {    if (!(int_vradv ))     return 0;    free(int_vradv );    return 0;    }    /* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* deallocates an inf_vm0  struct */    static int destroy_inf_vver (inf_vver  *int_vverv )    {    if (!(int_vverv ))     return 0;    free(int_vverv );    return 0;    }    /* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* deallocates an inf_vm0  struct */    static int destroy_inf_dvro (inf_dvro  *int_dvrov )    {    if (!(int_dvrov ))     return 0;    free(int_dvrov );    return 0;    }    /* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* deallocates an inf_vm0  struct */    static int destroy_inf_dvra (inf_dvra  *int_dvrav )    {    if (!(int_dvrav ))     return 0;    free(int_dvrav );    return 0;    }    /* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* deallocates an inf_vm0  struct */    static int destroy_inf_dvve (inf_dvve  *int_dvvev )    {    if (!(int_dvvev ))     return 0;    free(int_dvvev );    return 0;    }    /* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* deallocates an inf_vm0  struct */    static int destroy_inf_vm0 (inf_vm0  *int_vm0v )    {    if (!(int_vm0v ))     return 0;    free(int_vm0v );    return 0;    }    /* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* deallocates an inf_vm1 struct */    static int destroy_inf_vm1(inf_vm1 *int_vm1v)    {    if (!(int_vm1v))    return 0;    free(int_vm1v);    return 0;    }    /* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* deallocates an inf_vm2 struct */    static int destroy_inf_vm2(inf_vm2 *int_vm2v)    {    if (!(int_vm2v))    return 0;    free(int_vm2v);    return 0;    }    /* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* deallocates an inf_vm3 struct */    static int destroy_inf_vm3(inf_vm3 *int_vm3v)    {    if (!(int_vm3v))    return 0;    free(int_vm3v);    return 0;    }    /* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* deallocates an inf_vm4 struct */    static int destroy_inf_vm4(inf_vm4 *int_vm4v)    {    if (!(int_vm4v))    return 0;    free(int_vm4v);    return 0;    }    /* ------------------------------------------------------------ */\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* deallocates an inf_ra1 struct */    static int destroy_inf_ra1(inf_ra1 *int_ra1v)    {    if (!(int_ra1v))    return 0;    free(int_ra1v);    return 0;    }    /* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* deallocates an inf_ra2 struct */    static int destroy_inf_ra2(inf_ra2 *int_ra2v)    {    if (!(int_ra2v))    return 0;    free(int_ra2v);    return 0;    }    /* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* deallocates an inf_ra3 struct */    static int destroy_inf_ra3(inf_ra3 *int_ra3v)    {    if (!(int_ra3v))    return 0;    free(int_ra3v);    return 0;    }    /* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* deallocates an inf_ra4 struct */    static int destroy_inf_ra4(inf_ra4 *int_ra4v)    {    if (!(int_ra4v))    return 0;    free(int_ra4v);    return 0;    }    /* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* deallocates an inf_ro1 struct */    static int destroy_inf_ro1(inf_ro1 *int_ro1v)    {    if (!(int_ro1v))    return 0;    free(int_ro1v);    return 0;    }    /* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* deallocates an inf_ro2 struct */    static int destroy_inf_ro2(inf_ro2 *int_ro2v)    {    if (!(int_ro2v))    return 0;    free(int_ro2v);    return 0;    }    /* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* deallocates an inf_ro3 struct */    static int destroy_inf_ro3(inf_ro3 *int_ro3v)    {    if (!(int_ro3v))    return 0;    free(int_ro3v);    return 0;    }    /* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* deallocates an inf_ro4 struct */    static int destroy_inf_ro4(inf_ro4 *int_ro4v)    {    if (!(int_ro4v))    return 0;    free(int_ro4v);    return 0;    }    /* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* deallocates an inf_wm0  struct */    static int destroy_inf_wm0 (inf_wm0  *int_wm0v )    {    if (!(int_wm0v ))     return 0;    free(int_wm0v );    return 0;    }    /* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* deallocates an inf_wm1 struct */    static int destroy_inf_wm1(inf_wm1 *int_wm1v)    {    if (!(int_wm1v))    return 0;    free(int_wm1v);    return 0;    }    /* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* deallocates an inf_wm2 struct */    static int destroy_inf_wm2(inf_wm2 *int_wm2v)    {    if (!(int_wm2v))    return 0;    free(int_wm2v);    return 0;    }    /* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* deallocates an inf_wm3 struct */    static int destroy_inf_wm3(inf_wm3 *int_wm3v)    {    if (!(int_wm3v))    return 0;    free(int_wm3v);    return 0;    }    /* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* deallocates an inf_wm4 struct */    static int destroy_inf_wm4(inf_wm4 *int_wm4v)    {    if (!(int_wm4v))    return 0;    free(int_wm4v);    return 0;    }    /* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* deallocates an inf_ls0  struct */    static int destroy_inf_ls0 (inf_ls0  *int_ls0v )    {    if (!(int_ls0v ))    return 0;    free(int_ls0v );    return 0;    }    /* ------------------------------------------------------------ */\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    /* deallocates an inf_lc0  struct */    static int destroy_inf_lc0 (inf_lc0  *int_lc0v )    {    if (!(int_lc0v ))    return 0;    free(int_lc0v );    return 0;    }    /* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Initialises the rng internal to the calulation of sdis */\nstatic void rndmf_init_sdis_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].siseed[0] = prm -> iseed2+1+disk;\n  prm -> sd[disk][srnr].siseed[1] = srnr;\n\n  /* Reset things */\n  maths_rndmf_init(prm -> sd[disk][srnr].siseed, prm -> sd[disk][srnr].srandstr);\n  zprof(6, prm -> sd[disk][srnr].srandstr, &(prm -> sd[disk][srnr].y2));\n\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* dummy function doing nothing instead of rndmf_init_sdis_act */\nstatic void rndmf_init_sdis_pas(void *rpm, int srnr, int disk)\n{\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Re-calculates point source numbers and fluxes depending on sub-cloud number */\nstatic void chclfl_sdis_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n  int clouds;\n\n  prm = (ringparms *) rpm;\n\n  prm -> sd[disk][srnr].nsubcl = (clouds = roundnormal(prm -> modpar[(PRPARAMS+disk*NDPARAMS+PCLNR)*prm -> nr+srnr])) > 0?clouds:1;\n  prm -> sd[disk][srnr].nsubclinv = 1.0/((float) prm -> sd[disk][srnr].nsubcl);\n\n  prm -> sd[disk][srnr].pf = prm -> sd[disk][srnr].pf*prm -> sd[disk][srnr].nsubclinv;\n  prm -> sd[disk][srnr].nharmnorm = prm -> sd[disk][srnr].nharmnorm*prm -> sd[disk][srnr].nsubcl;\n  prm -> sd[disk][srnr].ngaussian[0] = prm -> sd[disk][srnr].ngaussian[0]*prm -> sd[disk][srnr].nsubcl;\n  prm -> sd[disk][srnr].ngaussian[1] = prm -> sd[disk][srnr].ngaussian[1]*prm -> sd[disk][srnr].nsubcl;\n  prm -> sd[disk][srnr].ngaussian[2] = prm -> sd[disk][srnr].ngaussian[2]*prm -> sd[disk][srnr].nsubcl;\n  prm -> sd[disk][srnr].ngaussian[3] = prm -> sd[disk][srnr].ngaussian[3]*prm -> sd[disk][srnr].nsubcl;\n  prm -> sd[disk][srnr].n = prm -> sd[disk][srnr].n *prm -> sd[disk][srnr].nsubcl;\n\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Re-calculates point source numbers and fluxes depending on sub-cloud number */\nstatic void chclfl_sdis_pas(void *rpm, int srnr, int disk)\n{\n  return;\n}\n\n/* ------------------------------------------------------------ */\n/* LOOK HERE */\n\n\n\n\n\n\n\n\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Initialises the rng internal to the calulation of sdis */\nstatic void rndmf_init_smi_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].iseed[0] = prm -> iseed2+2+disk;\n  prm -> sd[disk][srnr].iseed[1] = srnr+1;\n\n  /* Reset the rng */\n  maths_rndmf_init(prm -> sd[disk][srnr].iseed, prm -> sd[disk][srnr].randstr);\n\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* dummy function doing nothing instead of rndmf_init_sdis_act */\nstatic void rndmf_init_smi_pas(void *rpm, int srnr, int disk)\n{\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* dummy instead of pr_sdis_act */\nstatic void pr_sdis_pas(void *rpm, float *v, float *vold, int srnr, int disk)\n{\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates random velocity component and adds it to the input */\nstatic void pr_sdis_act(void *rpm, float *v, float *vold, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *vold = *v;\n  *v = *v+zprof(1, prm -> sd[disk][srnr].srandstr, &(prm -> sd[disk][srnr].y2))*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PSDIS)*prm -> nr+srnr];\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates random velocity component and adds it to the input, repeats the process a few times */\nstatic void sdis_repeater_act(void *rpm, float *pp, float vold, int srnr, hdrinf *hdr, long *j, int signum, long *npoints, int disk)\n{\n  ringparms *prm;\n  int i;\n\n  prm = (ringparms *) rpm;\n\n  for (i = 1; i < prm -> sd[disk][srnr].nsubcl; ++i) {\n    pp[5] = vold+zprof(1, prm -> sd[disk][srnr].srandstr, &(prm -> sd[disk][srnr].y2))*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PSDIS)*prm -> nr+srnr];\n\n#ifdef PBCORR\n    (*(prm -> sd[disk][srnr].gridpoint))(hdr, prm -> fill_pbcfac, prm -> modpar, prm -> nr, prm -> sd, srnr, j, pp, signum, npoints, disk);\n#else\n    (*(prm -> sd[disk][srnr].gridpoint))(hdr, prm -> modpar, prm -> nr, prm -> sd, srnr, j, pp, signum, npoints, disk);\n#endif\n\n    (*(prm -> inf_aziv[disk] -> corrp))(rpm, srnr, &(prm -> sd[disk][srnr].outofrange), signum);\n  }\n\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* dummy */\nstatic void sdis_repeater_pas(void *rpm, float *pp, float vold, int srnr, hdrinf *hdr, long *j, int signum, long *npoints, int disk)\n{\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates random velocity component and adds it to the input, repeats the process a few times */\nstatic void sdis_repeater_actcool(void *rpm, float *pp, float vold, int srnr, hdrinf *hdr, long *j, int signum, long *npoints, int disk)\n{\n  ringparms *prm;\n  int i;\n\n  prm = (ringparms *) rpm;\n\n  for (i = 1; i < prm -> sd[disk][srnr].nsubcl; ++i) {\n    /* pp[5] = vold+zprof(1, prm -> sd[disk][srnr].srandstr, &(prm -> sd[disk][srnr].y2))*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PSDIS)*prm -> nr+srnr]; */\n\n#ifdef PBCORR\n    (*(prm -> sd[disk][srnr].gridpoint))(hdr, prm -> fill_pbcfac, prm -> modpar, prm -> nr, prm -> sd, srnr, j, pp, signum, npoints, disk);\n#else\n    (*(prm -> sd[disk][srnr].gridpoint))(hdr, prm -> modpar, prm -> nr, prm -> sd, srnr, j, pp, signum, npoints, disk);\n#endif\n\n    (*(prm -> inf_aziv[disk] -> corrp))(rpm, srnr, &(prm -> sd[disk][srnr].outofrange), signum);\n  }\n\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* dummy */\nstatic void sdis_repeater_pascool(void *rpm, float *pp, float vold, int srnr, hdrinf *hdr, long *j, int signum, long *npoints, int disk)\n{\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* dummy instead of pr_sdis_act */\nstatic void pr_sdis_empty_pas(void *rpm, int srnr, int disk)\n{\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates random velocity component and adds it to the input */\nstatic void pr_sdis_empty_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n  int i;\n\n  prm = (ringparms *) rpm;\n\n  for (i = 0; i < prm -> sd[disk][srnr].nsubcl; ++i)\n    zprof(1, prm -> sd[disk][srnr].srandstr, &(prm -> sd[disk][srnr].y2));\n\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial velocity component and adds it to the input */\nstatic void pr_vrad_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *v = *v+sinaz*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PVRAD)*prm -> nr+srnr];\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Dummy */\nstatic void pr_vrad_pas(void *rpm, float *point, int srnr, float sinaz, float cosaz, int disk)\n{\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a vertical velocity component and adds it to the input */\nstatic void pr_vver_act(void *rpm, float *point, int srnr, int disk)\n{\n  ringparms *prm;\n\n\n  prm = (ringparms *) rpm;\n\n  /* Now, this is a bit more complex */\n  if (point[2] > 0.0)\n    point[5] = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PVVER)*prm -> nr+srnr];\n  else\n    point[5] = -prm -> modpar[(PRPARAMS+disk*NDPARAMS+PVVER)*prm -> nr+srnr];\n\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Dummy */\nstatic void pr_vver_pas(void *rpm, float *point, int srnr, int disk)\n{\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial velocity component and adds it to the input */\nstatic void pr_vver_rota_act(void *rpm, float *vz, float *vz2, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n\n  *vz2 = *vz2+*vz*prm -> sd[disk][srnr].cosi;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Dummy */\nstatic void pr_vver_rota_pas(void *rpm, float *vz, float *vz2, int srnr, int disk)\n{\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial velocity component and adds it to the input */\nstatic void pr_dvro_act(void *rpm, float *point, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  point[4] = point[4]+cosaz*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PDVRO)*prm -> nr+srnr]*fabs(point[2]);\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial velocity component and adds it to the input, starting at zdro */\nstatic void pr_dvro_act2(void *rpm, float *point, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  if (fabs(point[2]) >= fabs(prm -> modpar[(PRPARAMS+disk*NDPARAMS+PZDRO)*prm -> nr+srnr])) {\n    point[4] = point[4]+cosaz*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PDVRO)*prm -> nr+srnr]*(fabs(point[2])-fabs(prm -> modpar[(PRPARAMS+disk*NDPARAMS+PZDRO)*prm -> nr+srnr]));\n  }\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Dummy */\nstatic void pr_dvro_pas(void *rpm, float *point, int srnr, float sinaz, float cosaz, int disk)\n{\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial velocity component and adds it to the input */\nstatic void pr_dvra_act(void *rpm, float *point, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n    prm = (ringparms *) rpm;\n    point[4] = point[4]+sinaz*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PDVRA)*prm -> nr+srnr]*fabs(point[2]);\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial velocity component and adds it to the input, starting at zdra */\nstatic void pr_dvra_act2(void *rpm, float *point, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n    prm = (ringparms *) rpm;\n    if (fabs(point[2]) > fabs(prm -> modpar[(PRPARAMS+disk*NDPARAMS+PZDRA)*prm -> nr+srnr]))\n      point[4] = point[4]+sinaz*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PDVRA)*prm -> nr+srnr]*(fabs(point[2]) - fabs(prm -> modpar[(PRPARAMS+disk*NDPARAMS+PDVRA)*prm -> nr+srnr]));\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Dummy */\nstatic void pr_dvra_pas(void *rpm, float *point, int srnr, float sinaz, float cosaz, int disk)\n{\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial velocity component and adds it to the input */\nstatic void pr_dvve_act(void *rpm, float *point, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  \n  /* Now, this should do, the signum of the z-component is the signum of z */\n point[5] = point[5]+prm -> modpar[(PRPARAMS+disk*NDPARAMS+PDVVE)*prm -> nr+srnr]*point[2];\n\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial velocity component and adds it to the input, if the scale height is above a certain value */\nstatic void pr_dvve_act2(void *rpm, float *point, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  \n  /* Now, this should do, the signum of the z-component is the signum of z */\n  if (fabs(point[2]) > fabs(prm -> modpar[(PRPARAMS+disk*NDPARAMS+PZDVE)*prm -> nr+srnr])) {\n    if (point[2] > 0.0)\n      point[5] = point[5]+prm -> modpar[(PRPARAMS+disk*NDPARAMS+PDVVE)*prm -> nr+srnr]*(point[2]-fabs(prm -> modpar[(PRPARAMS+disk*NDPARAMS+PZDVE)*prm -> nr+srnr]));\n    else \n      point[5] = point[5]+prm -> modpar[(PRPARAMS+disk*NDPARAMS+PDVVE)*prm -> nr+srnr]*(point[2]+fabs(prm -> modpar[(PRPARAMS+disk*NDPARAMS+PZDVE)*prm -> nr+srnr]));\n  }\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Dummy */\nstatic void pr_dvve_pas(void *rpm, float *point, int srnr, int disk)\n{\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* dummy function */\nstatic void srpr_vmi_pas(void *rpm, int srnr, int disk)\n{\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates velocity sin component and adds it to the subring */\nstatic void srpr_vm1s_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].vps1 = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PVM1A)*prm -> nr+srnr]*sinf(prm -> modpar[(PRPARAMS+disk*NDPARAMS+PVM1P)*prm -> nr+srnr]);\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates velocity sin component and adds it to the subring */\nstatic void srpr_vm1c_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].vpc1 = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PVM1A)*prm -> nr+srnr]*cosf(prm -> modpar[(PRPARAMS+disk*NDPARAMS+PVM1P)*prm -> nr+srnr]);\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates velocity sin component and adds it to the subring */\nstatic void srpr_vm2s_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].vps2 = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PVM2A)*prm -> nr+srnr]*sinf(2.0*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PVM2P)*prm -> nr+srnr]);\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates velocity sin component and adds it to the subring */\nstatic void srpr_vm2c_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].vpc2 = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PVM2A)*prm -> nr+srnr]*cosf(2.0*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PVM2P)*prm -> nr+srnr]);\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates velocity sin component and adds it to the subring */\nstatic void srpr_vm3s_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].vps3 = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PVM3A)*prm -> nr+srnr]*sinf(3.0*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PVM3P)*prm -> nr+srnr]);\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates velocity sin component and adds it to the subring */\nstatic void srpr_vm3c_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].vpc3 = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PVM3A)*prm -> nr+srnr]*cosf(3.0*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PVM3P)*prm -> nr+srnr]);\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates velocity sin component and adds it to the subring */\nstatic void srpr_vm4s_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].vps4 = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PVM4A)*prm -> nr+srnr]*sinf(4.0*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PVM4P)*prm -> nr+srnr]);\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates velocity sin component and adds it to the subring */\nstatic void srpr_vm4c_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].vpc4 = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PVM4A)*prm -> nr+srnr]*cosf(4.0*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PVM4P)*prm -> nr+srnr]);\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* dummy instead of pr_vmis/c_act */\nstatic void pr_vmi_pas(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk)\n{\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial velocity component and adds it to the input */\nstatic void pr_vm0_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *v = *v+prm -> modpar[(PRPARAMS+disk*NDPARAMS+PVM0A)*prm -> nr+srnr];\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial velocity component and adds it to the input */\nstatic void pr_vm1s_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *v = *v+sinaz*prm -> sd[disk][srnr].vps1;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial velocity component and adds it to the input */\nstatic void pr_vm2s_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *v = *v+(2.0*sinaz*cosaz)* prm -> sd[disk][srnr].vps2;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial velocity component and adds it to the input */\nstatic void pr_vm3s_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *v = *v+(3.0*sinaz-4.0*sinaz*sinaz*sinaz)*prm  -> sd[disk][srnr].vps3;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial velocity component and adds it to the input */\nstatic void pr_vm4s_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *v = *v+(8.0*sinaz*cosaz*cosaz*cosaz-4.0*sinaz*cosaz)* prm -> sd[disk][srnr].vps4;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial velocity component and adds it to the input */\nstatic void pr_vm1c_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *v = *v+cosaz* prm -> sd[disk][srnr].vpc1;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial velocity component and adds it to the input */\nstatic void pr_vm2c_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *v = *v+(1.0-2.0*sinaz*sinaz)*prm -> sd[disk][srnr].vpc2;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial velocity component and adds it to the input */\nstatic void pr_vm3c_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *v = *v+(4.0*cosaz*cosaz*cosaz-3.0*cosaz)*prm -> sd[disk][srnr].vpc3;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial velocity component and adds it to the input */\nstatic void pr_vm4c_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *v = *v+(8.0*cosaz*cosaz*cosaz*cosaz-8.0*cosaz*cosaz+1.0)*prm -> sd[disk][srnr].vpc4;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* dummy function */\nstatic void srpr_rai_pas(void *rpm, int srnr, int disk)\n{\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates velocity sin component and adds it to the subring */\nstatic void srpr_ra1s_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].ras1 = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PRA1A)*prm -> nr+srnr]*sinf(prm -> modpar[(PRPARAMS+disk*NDPARAMS+PRA1P)*prm -> nr+srnr]);\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates velocity sin component and adds it to the subring */\nstatic void srpr_ra1c_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].rac1 = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PRA1A)*prm -> nr+srnr]*cosf(prm -> modpar[(PRPARAMS+disk*NDPARAMS+PRA1P)*prm -> nr+srnr]);\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates velocity sin component and adds it to the subring */\nstatic void srpr_ra2s_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].ras2 = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PRA2A)*prm -> nr+srnr]*sinf(2.0*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PRA2P)*prm -> nr+srnr]);\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates velocity sin component and adds it to the subring */\nstatic void srpr_ra2c_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].rac2 = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PRA2A)*prm -> nr+srnr]*cosf(2.0*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PRA2P)*prm -> nr+srnr]);\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates velocity sin component and adds it to the subring */\nstatic void srpr_ra3s_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].ras3 = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PRA3A)*prm -> nr+srnr]*sinf(3.0*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PRA3P)*prm -> nr+srnr]);\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates velocity sin component and adds it to the subring */\nstatic void srpr_ra3c_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].rac3 = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PRA3A)*prm -> nr+srnr]*cosf(3.0*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PRA3P)*prm -> nr+srnr]);\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates velocity sin component and adds it to the subring */\nstatic void srpr_ra4s_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].ras4 = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PRA4A)*prm -> nr+srnr]*sinf(4.0*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PRA4P)*prm -> nr+srnr]);\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates velocity sin component and adds it to the subring */\nstatic void srpr_ra4c_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].rac4 = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PRA4A)*prm -> nr+srnr]*cosf(4.0*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PRA4P)*prm -> nr+srnr]);\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* dummy instead of pr_rais/c_act */\nstatic void pr_rai_pas(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk)\n{\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial velocity component and adds it to the input */\nstatic void pr_ra1s_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *v = *v+sinaz*sinaz*prm -> sd[disk][srnr].ras1;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial velocity component and adds it to the input */\nstatic void pr_ra2s_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *v = *v+sinaz*(2.0*sinaz*cosaz)* prm -> sd[disk][srnr].ras2;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial velocity component and adds it to the input */\nstatic void pr_ra3s_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *v = *v+sinaz*(3.0*sinaz-4.0*sinaz*sinaz*sinaz)*prm  -> sd[disk][srnr].ras3;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial velocity component and adds it to the input */\nstatic void pr_ra4s_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *v = *v+sinaz*(8.0*sinaz*cosaz*cosaz*cosaz-4.0*sinaz*cosaz)* prm -> sd[disk][srnr].ras4;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial velocity component and adds it to the input */\nstatic void pr_ra1c_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *v = *v+sinaz*cosaz* prm -> sd[disk][srnr].rac1;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial velocity component and adds it to the input */\nstatic void pr_ra2c_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *v = *v+sinaz*(1.0-2.0*sinaz*sinaz)*prm -> sd[disk][srnr].rac2;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial velocity component and adds it to the input */\nstatic void pr_ra3c_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *v = *v+sinaz*(4.0*cosaz*cosaz*cosaz-3.0*cosaz)*prm -> sd[disk][srnr].rac3;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial velocity component and adds it to the input */\nstatic void pr_ra4c_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *v = *v+sinaz*(8.0*cosaz*cosaz*cosaz*cosaz-8.0*cosaz*cosaz+1.0)*prm -> sd[disk][srnr].rac4;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* dummy function */\nstatic void srpr_roi_pas(void *rpm, int srnr, int disk)\n{\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates velocity sin component and adds it to the subring */\nstatic void srpr_ro1s_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].ros1 = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PRO1A)*prm -> nr+srnr]*sinf(prm -> modpar[(PRPARAMS+disk*NDPARAMS+PRO1P)*prm -> nr+srnr]);\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates velocity sin component and adds it to the subring */\nstatic void srpr_ro1c_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].roc1 = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PRO1A)*prm -> nr+srnr]*cosf(prm -> modpar[(PRPARAMS+disk*NDPARAMS+PRO1P)*prm -> nr+srnr]);\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates velocity sin component and adds it to the subring */\nstatic void srpr_ro2s_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].ros2 = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PRO2A)*prm -> nr+srnr]*sinf(2.0*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PRO2P)*prm -> nr+srnr]);\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates velocity sin component and adds it to the subring */\nstatic void srpr_ro2c_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].roc2 = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PRO2A)*prm -> nr+srnr]*cosf(2.0*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PRO2P)*prm -> nr+srnr]);\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates velocity sin component and adds it to the subring */\nstatic void srpr_ro3s_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].ros3 = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PRO3A)*prm -> nr+srnr]*sinf(3.0*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PRO3P)*prm -> nr+srnr]);\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates velocity sin component and adds it to the subring */\nstatic void srpr_ro3c_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].roc3 = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PRO3A)*prm -> nr+srnr]*cosf(3.0*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PRO3P)*prm -> nr+srnr]);\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates velocity sin component and adds it to the subring */\nstatic void srpr_ro4s_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].ros4 = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PRO4A)*prm -> nr+srnr]*sinf(4.0*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PRO4P)*prm -> nr+srnr]);\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates velocity sin component and adds it to the subring */\nstatic void srpr_ro4c_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].roc4 = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PRO4A)*prm -> nr+srnr]*cosf(4.0*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PRO4P)*prm -> nr+srnr]);\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* dummy instead of pr_rois/c_act */\nstatic void pr_roi_pas(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk)\n{\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial velocity component and adds it to the input */\nstatic void pr_ro1s_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *v = *v+cosaz*sinaz*prm -> sd[disk][srnr].ros1;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial velocity component and adds it to the input */\nstatic void pr_ro2s_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *v = *v+cosaz*(2.0*sinaz*cosaz)* prm -> sd[disk][srnr].ros2;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial velocity component and adds it to the input */\nstatic void pr_ro3s_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *v = *v+cosaz*(3.0*sinaz-4.0*sinaz*sinaz*sinaz)*prm  -> sd[disk][srnr].ros3;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial velocity component and adds it to the input */\nstatic void pr_ro4s_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *v = *v+cosaz*(8.0*sinaz*cosaz*cosaz*cosaz-4.0*sinaz*cosaz)* prm -> sd[disk][srnr].ros4;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial velocity component and adds it to the input */\nstatic void pr_ro1c_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *v = *v+cosaz*cosaz* prm -> sd[disk][srnr].roc1;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial velocity component and adds it to the input */\nstatic void pr_ro2c_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *v = *v+cosaz*(1.0-2.0*sinaz*sinaz)*prm -> sd[disk][srnr].roc2;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial velocity component and adds it to the input */\nstatic void pr_ro3c_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *v = *v+cosaz*(4.0*cosaz*cosaz*cosaz-3.0*cosaz)*prm -> sd[disk][srnr].roc3;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial velocity component and adds it to the input */\nstatic void pr_ro4c_act(void *rpm, float *v, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *v = *v+cosaz*(8.0*cosaz*cosaz*cosaz*cosaz-8.0*cosaz*cosaz+1.0)*prm -> sd[disk][srnr].roc4;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates warp sin component and adds it to the subring */\nstatic void srpr_wm1s_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].wps1 = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PWM1A)*prm -> nr+srnr]*sinf(prm -> modpar[(PRPARAMS+disk*NDPARAMS+PWM1P)*prm -> nr+srnr]);\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* dummy function */\nstatic void srpr_wmi_pas(void *rpm, int srnr, int disk)\n{\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates warp cos component and adds it to the subring */\nstatic void srpr_wm1c_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].wpc1 = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PWM1A)*prm -> nr+srnr]*cosf(prm -> modpar[(PRPARAMS+disk*NDPARAMS+PWM1P)*prm -> nr+srnr]);\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates warp sin component and adds it to the subring */\nstatic void srpr_wm2s_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].wps2 = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PWM2A)*prm -> nr+srnr]*sinf(2.0*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PWM2P)*prm -> nr+srnr]);\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates warp cos component and adds it to the subring */\nstatic void srpr_wm2c_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].wpc2 = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PWM2A)*prm -> nr+srnr]*cosf(2.0*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PWM2P)*prm -> nr+srnr]);\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates warp sin component and adds it to the subring */\nstatic void srpr_wm3s_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].wps3 = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PWM3A)*prm -> nr+srnr]*sinf(3.0*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PWM3P)*prm -> nr+srnr]);\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates warp cos component and adds it to the subring */\nstatic void srpr_wm3c_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].wpc3 = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PWM3A)*prm -> nr+srnr]*cosf(3.0*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PWM3P)*prm -> nr+srnr]);\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates warp sin component and adds it to the subring */\nstatic void srpr_wm4s_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].wps4 = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PWM4A)*prm -> nr+srnr]*sinf(4.0*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PWM4P)*prm -> nr+srnr]);\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates warp cos component and adds it to the subring */\nstatic void srpr_wm4c_act(void *rpm, int srnr, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  prm -> sd[disk][srnr].wpc4 = prm -> modpar[(PRPARAMS+disk*NDPARAMS+PWM4A)*prm -> nr+srnr]*cosf(4.0*prm -> modpar[(PRPARAMS+disk*NDPARAMS+PWM4P)*prm -> nr+srnr]);\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* dummy instead of pr_wmis/c_act */\nstatic void pr_wmi_pas(void *rpm, float *z, int srnr, float sinaz, float cosaz, int disk)\n{\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a warp m=0 component and adds it to the input */\nstatic void pr_wm0_act(void *rpm, float *z, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *z = *z+prm -> modpar[(PRPARAMS+disk*NDPARAMS+PWM0A)*prm -> nr+srnr];\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a warp component and adds it to the input */\nstatic void pr_wm1s_act(void *rpm, float *z, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *z = *z+sinaz*prm -> sd[disk][srnr].wps1;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a warp component and adds it to the input */\nstatic void pr_wm2s_act(void *rpm, float *z, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *z = *z+(2.0*sinaz*cosaz)* prm -> sd[disk][srnr].wps2;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a warp component and adds it to the input */\nstatic void pr_wm3s_act(void *rpm, float *z, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *z = *z+(3.0*sinaz-4.0*sinaz*sinaz*sinaz)*prm  -> sd[disk][srnr].wps3;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a warp component and adds it to the input */\nstatic void pr_wm4s_act(void *rpm, float *z, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *z = *z+(8.0*sinaz*cosaz*cosaz*cosaz-4.0*sinaz*cosaz)* prm -> sd[disk][srnr].wps4;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a warp component and adds it to the input */\nstatic void pr_wm1c_act(void *rpm, float *z, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *z = *z+cosaz* prm -> sd[disk][srnr].wpc1;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a warp component and adds it to the input */\nstatic void pr_wm2c_act(void *rpm, float *z, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *z = *z+(1.0-2.0*sinaz*sinaz)*prm -> sd[disk][srnr].wpc2;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a warp component and adds it to the input */\nstatic void pr_wm3c_act(void *rpm, float *z, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *z = *z+(4.0*cosaz*cosaz*cosaz-3.0*cosaz)*prm -> sd[disk][srnr].wpc3;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a warp component and adds it to the input */\nstatic void pr_wm4c_act(void *rpm, float *z, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *z = *z+(8.0*cosaz*cosaz*cosaz*cosaz-8.0*cosaz*cosaz+1.0)*prm -> sd[disk][srnr].wpc4;\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* dummy instead of pr_ls0_act */\nstatic void pr_ls0_pas(void *rpm, float *y, int srnr, float sinaz, float cosaz, int disk)\n{\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial velocity component and adds it to the input */\nstatic void pr_ls0_act(void *rpm, float *y, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *y = *y+prm -> modpar[(PRPARAMS+disk*NDPARAMS+PLS0)*prm -> nr+srnr];\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* dummy instead of pr_lc0_act */\nstatic void pr_lc0_pas(void *rpm, float *x, int srnr, float sinaz, float cosaz, int disk)\n{\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* calculates a radial velocity component and adds it to the input */\nstatic void pr_lc0_act(void *rpm, float *x, int srnr, float sinaz, float cosaz, int disk)\n{\n  ringparms *prm;\n\n  prm = (ringparms *) rpm;\n  *x = *x+prm -> modpar[(PRPARAMS+disk*NDPARAMS+PLC0)*prm -> nr+srnr];\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* wrapper to call userdble_c from gipsy */\nstatic  int userdble_tir(simparse_scn_arel **arel, double *anarray, int *elements, int *defaultstat, char *keyword, char *message)\n{\n  int nread, nreturned, keypres;\n  double *retarray = NULL;\n  int i;\n\n  int ndef = 0, min = 0, max = -1, keyreq = 0, ltmax = 0;\n\n  /*\n  def 0/1: no default/default\n  def 2: hidden\n  def 4 exact number\n  from doc:\n  All these routines are integer functions which return the number of items entered by the user\n\n  0 --- no default is possible\n  1 --- user is prompted, but default is taken when user types RETURN\n  2 --- user is not prompted and default is taken unless the input was pre-specified\n  4 --- (added to any of the above values) the user is required to enter the exact number of items\n  */\n\n  min = *elements; \n  max = *elements;\n\n  if (*defaultstat & 1) {\n    /* user is prompted, but default is taken when user types RETURN: keyreq = 1 */\n    ndef = *elements; keyreq = 1; ltmax = 0;\n  }\n  else {\n    /* No default is possible:  */\n    ndef = 0; keyreq = 1; ltmax = 0;\n  }\n  if (*defaultstat & 2) {\n    /* user is not prompted and default is taken unless the input was pre-specified */\n    ndef = *elements; keyreq = 0; ltmax = 0;\n  }\n  if (*defaultstat & 4) {\n\n    /* the user is required to enter the exact number of items */\n    ndef = 0; ltmax = 1;\n  }\n\n  if (simparse_scn_arel_readval_double(arel, keyword, message, ndef, anarray, min, max, keyreq, ltmax, &keypres, &nread, &nreturned, &retarray)) {\n    if (retarray)\n      free(retarray);\n    return -1;\n  }\n\n  nreturned = (nreturned > *elements)?*elements:nreturned;\n\n  for (i = 0; i < nreturned; ++i)\n   anarray[i] = retarray[i];\n\n  if (retarray) {\n    free(retarray);\n  }\n\n  return nread;\n\n/*  fint felements, fdefaultstat; */\n /*  int userdble_tir; */\n  \n /*  felements = (fint) *elements; */\n /*  fdefaultstat = (fint) *defaultstat; */\n\n /*  userdble_tir = (int) userdble_c(anarray, &felements, &fdefaultstat, tofchar(keyword), tofchar(message)); */\n\n /* *elements = (int) felements; */\n /* *defaultstat = (int) fdefaultstat; */\n\n /* return userdble_tir; */\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* wrapper to call userreal_c from gipsy */\nstatic  int userreal_tir(simparse_scn_arel **arel, float *anarray, int *elements, int *defaultstat, char *keyword, char *message)\n{\n  int nread, nreturned, keypres;\n  float *retarray = NULL;\n  int i;\n\n  int ndef = 0, min = 0, max = -1, keyreq = 0, ltmax = 0;\n\n  /*\n  def 0/1: no default/default\n  def 2: hidden\n  def 4 exact number\n  from doc:\n  All these routines are integer functions which return the number of items entered by the user\n\n  0 --- no default is possible\n  1 --- user is prompted, but default is taken when user types RETURN\n  2 --- user is not prompted and default is taken unless the input was pre-specified\n  4 --- (added to any of the above values) the user is required to enter the exact number of items\n  */\n\n  min = *elements; \n  max = *elements;\n\n  if (*defaultstat & 1) {\n    /* user is prompted, but default is taken when user types RETURN: keyreq = 1 */\n    ndef = *elements; keyreq = 1; ltmax = 0;\n  }\n  else {\n    /* No default is possible:  */\n    ndef = 0; keyreq = 1; ltmax = 0;\n  }\n  if (*defaultstat & 2) {\n    /* user is not prompted and default is taken unless the input was pre-specified */\n    ndef = *elements; keyreq = 0; ltmax = 0;\n  }\n  if (*defaultstat & 4) {\n\n    /* the user is required to enter the exact number of items */\n    ndef = 0; ltmax = 1;\n  }\n\n  if (simparse_scn_arel_readval_float(arel, keyword, message, ndef, anarray, min, max, keyreq, ltmax, &keypres, &nread, &nreturned, &retarray)) {\n    if (retarray)\n      free(retarray);\n    return -1;\n  }\n\n  nreturned = (nreturned > *elements)?*elements:nreturned;\n\n  for (i = 0; i < nreturned; ++i)\n   anarray[i] = retarray[i];\n\n  if (retarray) {\n    free(retarray);\n  }\n\n  return nread;\n\n /*  fint felements, fdefaultstat; */\n /*  int userreal_tir; */\n  \n /*  felements = (fint) *elements; */\n /*  fdefaultstat = (fint) *defaultstat; */\n\n /*  userreal_tir = (int) userreal_c(anarray, &felements, &fdefaultstat, tofchar(keyword), tofchar(message)); */\n\n /* *elements = (int) felements; */\n /* *defaultstat = (int) fdefaultstat; */\n\n /* return userreal_tir; */\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* wrapper to imitate userint_c from gipsy */\nstatic  int userint_tir(simparse_scn_arel **arel, int *anarray, int *elements, int *defaultstat, char *keyword, char *message)\n{\n  int nread, nreturned, keypres;\n  int *retarray = NULL;\n  int i;\n\n  int ndef = 0, min = 0, max = -1, keyreq = 0, ltmax = 0;\n\n  /*\n  def 0/1: no default/default\n  def 2: hidden\n  def 4 exact number\n  from doc:\n  All these routines are integer functions which return the number of items entered by the user\n\n  0 --- no default is possible\n  1 --- user is prompted, but default is taken when user types RETURN\n  2 --- user is not prompted and default is taken unless the input was pre-specified\n  4 --- (added to any of the above values) the user is required to enter the exact number of items\n  */\n  min = *elements; \n  max = *elements;\n\n  if (*defaultstat & 1) {\n    /* user is prompted, but default is taken when user types RETURN: keyreq = 1 */\n    ndef = *elements; keyreq = 1; ltmax = 0;\n  }\n  else {\n    /* No default is possible:  */\n    ndef = 0; keyreq = 1; ltmax = 0;\n  }\n  if (*defaultstat & 2) {\n    /* user is not prompted and default is taken unless the input was pre-specified */\n    ndef = *elements; keyreq = 0; ltmax = 0;\n  }\n  if (*defaultstat & 4) {\n\n    /* the user is required to enter the exact number of items */\n    ndef = 0; ltmax = 1;\n  }\n\n  if (simparse_scn_arel_readval_int(arel, keyword, message, ndef, anarray, min, max, keyreq, ltmax, &keypres, &nread, &nreturned, &retarray)) {\n    if (retarray)\n      free(retarray);\n    return -1;\n  }\n\n  nreturned = (nreturned > *elements)?*elements:nreturned;\n\n  for (i = 0; i < nreturned; ++i)\n   anarray[i] = retarray[i];\n\n  if (retarray) {\n    free(retarray);\n  }\n\n  /* I think it's this silly choice */\n  /* All these routines are integer functions which return the number of items entered by the user. */\n  return nread;\n\n /*  fint *fanarray, felements, fdefaultstat; */\n /*  int i, userint_tir; */\n\n /*  if (*elements > 0){ */\n /*    if (!(fanarray = (fint *) malloc(*elements*sizeof(fint)))) */\n /*      return -1; */\n /*  } */\n /*  else  */\n /*    fanarray = NULL; */\n  \n /*  for (i = 0; i < *elements; ++i) { */\n /*    fanarray[i] = (fint) anarray[i]; */\n /*  } */\n\n /*  felements = (fint) *elements; */\n /*  fdefaultstat = (fint) *defaultstat; */\n\n /*  userint_tir = (int) userint_c(fanarray, &felements, &fdefaultstat, tofchar(keyword), tofchar(message)); */\n\n /* for (i = 0; i < *elements; ++i) { */\n /*    anarray[i] = (int) fanarray[i]; */\n /*  } */\n\n /* *elements = (int) felements; */\n /* *defaultstat = (int) fdefaultstat; */\n\n /* return userint_tir; */\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* wrapper to call error_c from gipsy */\nstatic  int error_tir(int *device, char *message)\n{\n /*  fint fdevice; */\n\n /*  fdevice = (fint) *device; */\n\n /*  error_c(&fdevice, tofchar(message)); */\n\n /* *device = (int) fdevice; */\n\n  fprintf(stderr, \"shitty%s\\n\", message);\n\n  if (*device == 4) {\n    exit(1);\n  }\n\n return 0;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* wrapper to call anyout_c from gipsy */\nstatic  int anyout_tir(int *device, char *message)\n{\n /*  fint fdevice; */\n\n /*  fdevice = (fint) *device; */\n\n /*  anyout_c(&fdevice, tofchar(message)); */\n\n /* *device = (int) fdevice; */\n\n  printf(\"%s\\n\", message);\n\n return 0;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* wrapper to call anyout_c from gipsy */\n/* static  int anyout_cor(FILE *device, char *message) */\n/* { */\n/*   if ((device)) */\n/*     fprintf(device, \"%s\\n\", message); */\n/*   else */\n/*     printf(\"%s\\n\", message); */\n\n/*  return 0; */\n/* } */\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* wrapper to call cancel_c from gipsy */\nstatic  int cancel_tir(simparse_scn_arel **arelv, char *parname, int depth)\n{\n  /* cancel_c(tofchar(parname)); */\n  simparse_scn_arel_deepcancelkey(arelv, parname, depth);\n\n  return 0;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Optionally allocates and puts correct switches in the sdis struct */\nstatic int chkb_sdis(ringparms *rpm, fitparms *fit)\n{\n\n  int disk, srnr;\n\n  for (disk = 0; disk < rpm -> ndisks; ++ disk) {\n    \n    /* We allocate the sdis struct */\n    if (!rpm -> inf_sdisv[disk])\n      if (!(rpm -> inf_sdisv[disk] = create_inf_sdis()))\n\treturn 1;\n    \n    rpm -> inf_sdisv[disk] -> repeater = &sdis_repeater_pas;\n    rpm -> inf_sdisv[disk] -> chclfl = &chclfl_sdis_pas;\n    \n    /* If we fit ... */\n    if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PSDIS))) {\n      \n      /* We point to the right functions */\n      rpm -> inf_sdisv[disk] -> rndmf_init = &rndmf_init_sdis_pas;\n      rpm -> inf_sdisv[disk] -> pr = &pr_sdis_pas;\n      rpm -> inf_sdisv[disk] -> pr_empty = &pr_sdis_empty_pas;\n    }\n    else {\n      \n      /* we allocate the rng */\n      for (srnr = 0; srnr < rpm -> nr; ++srnr) {\n\tif (!(rpm -> sd[disk][srnr].srandstr))\n\t  if (!(rpm -> sd[disk][srnr].srandstr = (maths_rstrf *) malloc(sizeof(maths_rstrf))))\n\t    goto error;\n      }\n\n      /* We point to the right functions */\n      rpm -> inf_sdisv[disk] -> rndmf_init = &rndmf_init_sdis_act;\n      rpm -> inf_sdisv[disk] -> pr = &pr_sdis_act;\n      rpm -> inf_sdisv[disk] -> pr_empty = &pr_sdis_empty_act;\n      \n      /* Do we fit more than one subcloud ? */\n      if (!(chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PCLNR))) {\n\trpm -> inf_sdisv[disk] -> repeater = &sdis_repeater_act;\n\trpm -> inf_sdisv[disk] -> chclfl = &chclfl_sdis_act;\n      }\n    }\n  }\n  return 0;\n\n error:\n  for (disk = 0; disk < rpm -> ndisks; ++disk) {\n    destroy_inf_sdis(rpm -> inf_sdisv[disk]);\n    rpm -> inf_sdisv[disk] = NULL;\n  }\n  return 1;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Optionally allocates and puts correct switches in the vm0 struct */\nstatic int chkb_vrad(ringparms *rpm, fitparms *fit)\n{\n  int disk;\n\n  for (disk = 0; disk < rpm -> ndisks; ++ disk) {\n    \n    /* We allocate the vrad struct */\n\n    if (!(rpm -> inf_vradv[disk]))\n      if (!(rpm -> inf_vradv[disk] = create_inf_vrad()))\n\tgoto error;\n    \n    /* If we fit ... */\n    if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PVRAD))) {\n      /* We point to the right functions */\n      rpm -> inf_vradv[disk] -> pr = &pr_vrad_pas;\n      \n    }\n    else {\n      \n      /* We point to the right functions */\n    rpm -> inf_vradv[disk] -> pr = &pr_vrad_act;\n    }\n  }\n\n  return 0;\n \n error:\n  for (disk = 0; disk < rpm -> ndisks; ++disk) {\n    destroy_inf_vrad(rpm -> inf_vradv[disk]);\n    rpm -> inf_vradv[disk] = NULL;\n  }\n  return 1;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Optionally allocates and puts correct switches in the vm0 struct */\nstatic int chkb_vver(ringparms *rpm, fitparms *fit)\n{\n\n  int disk;\n\n  for (disk = 0; disk < rpm -> ndisks; ++ disk) {\n    \n    /* We allocate the vver struct */\n    if (!(rpm -> inf_vverv[disk])) {\n      if (!(rpm -> inf_vverv[disk] = create_inf_vver()))\n\tgoto error;\n    }\n    \n    /* If we fit ... */\n    if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PVVER))) {\n      /* We point to the right functions */\n      rpm -> inf_vverv[disk] -> pr = &pr_vver_pas;\n      rpm -> inf_vverv[disk] -> pr_rota = &pr_vver_rota_pas;\n    }\n    else {\n      \n      /* We point to the right functions */\n      rpm -> inf_vverv[disk] -> pr = &pr_vver_act;\n      rpm -> inf_vverv[disk] -> pr_rota = &pr_vver_rota_act;\n    }\n    \n  }\n    return 0;\n\n error:\n  for (disk = 0; disk < rpm -> ndisks; ++disk) {\n    destroy_inf_vver(rpm -> inf_vverv[disk]);\n    rpm -> inf_vverv[disk] = NULL;\n  }\n  return 1;\n\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Optionally allocates and puts correct switches in the vm0 struct */\nstatic int chkb_dvro(ringparms *rpm, fitparms *fit)\n{\n  int disk;\n\n  for (disk = 0; disk < rpm -> ndisks; ++ disk) {\n    \n    /* We allocate the dvro struct */\n    if (!(rpm -> inf_dvrov[disk]))\n      if (!(rpm -> inf_dvrov[disk] = create_inf_dvro()))\n\tgoto error;\n    \n    /* If we fit ... */\n    if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PDVRO))) {\n\n    /* We point to the right functions */\n      rpm -> inf_dvrov[disk] -> pr = &pr_dvro_pas;\n      \n    }\n    else {\n      \n      /* If we fit with an inner flat part */\n\n      if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PZDRO))) {\n\trpm -> inf_dvrov[disk] -> pr = &pr_dvro_act;\n      }\n      else {\n\trpm -> inf_dvrov[disk] -> pr = &pr_dvro_act2;\n      }\n    }\n  }\n\n  return 0;\n error:\n  for (disk = 0; disk < rpm -> ndisks; ++disk) {\n    destroy_inf_dvro(rpm -> inf_dvrov[disk]);\n    rpm -> inf_dvrov[disk] = NULL;\n  }\n  return 1;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Optionally allocates and puts correct switches in the vm0 struct */\nstatic int chkb_dvra(ringparms *rpm, fitparms *fit)\n{\n  int disk;\n\n  for (disk = 0; disk < rpm -> ndisks; ++ disk) {\n    \n    /* We allocate the vrad struct */\n    if (!(rpm -> inf_dvrav[disk]))\n      if (!(rpm -> inf_dvrav[disk] = create_inf_dvra()))\n\tgoto error;\n    \n    /* If we fit ... */\n    if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PDVRA))) {\n      /* We point to the right functions */\n      rpm -> inf_dvrav[disk] -> pr = &pr_dvra_pas;\n      \n    }\n    else {\n      \n      if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PZDRA))) {\n      /* We point to the right functions */\n\trpm -> inf_dvrav[disk] -> pr = &pr_dvra_act;\n      }\n      else {\n\trpm -> inf_dvrav[disk] -> pr = &pr_dvra_act2;\t\n      }\n    }\n  }\n  return 0;\n error:\n  for (disk = 0; disk < rpm -> ndisks; ++disk) {\n    destroy_inf_dvra(rpm -> inf_dvrav[disk]);\n    rpm -> inf_dvrav[disk] = NULL;\n  }\n  return 1;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Optionally allocates and puts correct switches in the vm0 struct */\nstatic int chkb_dvve(ringparms *rpm, fitparms *fit)\n{\n  int disk;\n\n  for (disk = 0; disk < rpm -> ndisks; ++ disk) {\n    \n    /* We allocate the vrad struct */\n    if (!(rpm -> inf_dvvev[disk]))\n      if (!(rpm -> inf_dvvev[disk] = create_inf_dvve()))\n\tgoto error;\n    \n    /* If we fit ... */\n    if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PDVVE))) {\n      \n      /* We point to the right functions */\n      rpm -> inf_dvvev[disk] -> pr = &pr_dvve_pas;\n      \n    }\n    else {\n      \n      if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PZDVE))) {\n\n\t/* We point to the right functions */\n\trpm -> inf_dvvev[disk] -> pr = &pr_dvve_act;\n      }\n      else {\n\trpm -> inf_dvvev[disk] -> pr = &pr_dvve_act2;\n      }\n\n      /* allocate the vver struct*/\n      chkb_vver((void *) rpm, fit);\n\n      /* Ensure that the right type of rotation takes place ERROR SOURCE?*/\n      rpm -> inf_vverv[disk] -> pr_rota = &pr_vver_rota_act;\n\n    }\n  }\n  return 0;\n\n error:\n  for (disk = 0; disk < rpm -> ndisks; ++disk) {\n    destroy_inf_dvve(rpm -> inf_dvvev[disk]);\n    rpm -> inf_dvvev[disk] = NULL;\n  }\n  return 1;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Optionally allocates and puts correct switches in the vm0 struct */\nstatic int chkb_vm0(ringparms *rpm, fitparms *fit)\n{\n  int disk;\n\n  for (disk = 0; disk < rpm -> ndisks; ++ disk) {\n    \n    /* We allocate the vm0 struct */\n    if (!(rpm -> inf_vm0v[disk]))\n      if (!(rpm -> inf_vm0v[disk] = create_inf_vm0()))\n\tgoto error;\n    \n  /* If we fit ... */\n    if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PVM0A))) {\n      /* We point to the right functions */\n      rpm -> inf_vm0v[disk] -> pr = &pr_vmi_pas;\n      \n    }\n    else {\n      \n    /* We point to the right functions */\n\n      rpm -> inf_vm0v[disk] -> pr = &pr_vm0_act;\n    }\n  }\n  return 0;\n  \n error:\n  for (disk = 0; disk < rpm -> ndisks; ++disk) {\n    destroy_inf_vm0(rpm -> inf_vm0v[disk]);\n    rpm -> inf_vm0v[disk] = NULL;\n  }\n  return 1;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    \n\n/* Optionally allocates and puts correct switches in the vm1 struct */    \nstatic int chkb_vm1(ringparms *rpm, fitparms *fit) \n{ \n  int disk;\n\n  for (disk = 0; disk < rpm -> ndisks; ++ disk) {\n    \n    if (!(rpm -> inf_vm1v[disk])) \n      if (!(rpm -> inf_vm1v[disk] = create_inf_vm1())) \n\tgoto error; \n\n    if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PVM1A))) { \n      rpm -> inf_vm1v[disk] -> prs = rpm -> inf_vm1v[disk] -> prc = &pr_vmi_pas; \n      rpm -> inf_vm1v[disk] -> srprs = rpm -> inf_vm1v[disk] -> srprc = &srpr_vmi_pas;\n    } \n    else {\n      rpm -> inf_vm1v[disk] -> prs = &pr_vm1s_act; \n      rpm -> inf_vm1v[disk] -> prc = &pr_vm1c_act; \n      rpm -> inf_vm1v[disk] -> srprs = &srpr_vm1s_act;\n      rpm -> inf_vm1v[disk] -> srprc = &srpr_vm1c_act;\n\n      if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PVM1P))) { \n\trpm -> inf_vm1v[disk] -> prs = &pr_vmi_pas; \n\trpm -> inf_vm1v[disk] -> srprs = &srpr_vmi_pas;\n      }\n      else if ((chkb_val(rpm, fit, PRPARAMS+disk*NDPARAMS+PVM1P, PIHALF))) { \n\trpm -> inf_vm1v[disk] -> prc = &pr_vmi_pas; \n\trpm -> inf_vm1v[disk] -> srprc = &srpr_vmi_pas;\n      }\n    }\n  }\n\n  return 0;\n  \n error:\n  for (disk = 0; disk < rpm -> ndisks; ++disk) {\n    destroy_inf_vm1(rpm -> inf_vm1v[disk]);\n      rpm -> inf_vm1v[disk] = NULL;\n  }\n  return 1;\n}    \n\n/* ------------------------------------------------------------ */\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    \n\n/* Optionally allocates and puts correct switches in the vm2 struct */    \nstatic int chkb_vm2(ringparms *rpm, fitparms *fit) \n{ \n  int disk;\n\n  for (disk = 0; disk < rpm -> ndisks; ++ disk) {\n    \n    if (!(rpm -> inf_vm2v[disk])) \n      if (!(rpm -> inf_vm2v[disk] = create_inf_vm2())) \n\tgoto error;\n \n    if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PVM2A))) { \n      rpm -> inf_vm2v[disk] -> prs = rpm -> inf_vm2v[disk] -> prc = &pr_vmi_pas; \n    rpm -> inf_vm2v[disk] -> srprs = rpm -> inf_vm2v[disk] -> srprc = &srpr_vmi_pas;\n    } \n    else {\n      rpm -> inf_vm2v[disk] -> prs = &pr_vm2s_act; \n      rpm -> inf_vm2v[disk] -> prc = &pr_vm2c_act; \n      rpm -> inf_vm2v[disk] -> srprs = &srpr_vm2s_act;\n      rpm -> inf_vm2v[disk] -> srprc = &srpr_vm2c_act;\n      \n      if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PVM2P))) { \n      rpm -> inf_vm2v[disk] -> prs = &pr_vmi_pas; \n      rpm -> inf_vm2v[disk] -> srprs = &srpr_vmi_pas;\n      }\n      else if ((chkb_val(rpm, fit, PRPARAMS+disk*NDPARAMS+PVM2P, PIHALF))) { \n\trpm -> inf_vm2v[disk] -> prs = &pr_vmi_pas; \n\trpm -> inf_vm2v[disk] -> srprs = &srpr_vmi_pas;\n      }\n    }\n  }\n  return 0;\n  \n error:\n  for (disk = 0; disk < rpm -> ndisks; ++disk) {\n    destroy_inf_vm2(rpm -> inf_vm2v[disk]);\n    rpm -> inf_vm2v[disk] = NULL;\n  }\n  return 1;\n}    \n\n/* ------------------------------------------------------------ */\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    \n\n/* Optionally allocates and puts correct switches in the vm3 struct */    \nstatic int chkb_vm3(ringparms *rpm, fitparms *fit) \n{ \n  int disk;\n  \n  for (disk = 0; disk < rpm -> ndisks; ++ disk) {\n    \n    if (!(rpm -> inf_vm3v[disk])) \n      if (!(rpm -> inf_vm3v[disk] = create_inf_vm3())) \n\tgoto error;\n \n    if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PVM3A))) { \n      rpm -> inf_vm3v[disk] -> prs = rpm -> inf_vm3v[disk] -> prc = &pr_vmi_pas; \n      rpm -> inf_vm3v[disk] -> srprs = rpm -> inf_vm3v[disk] -> srprc = &srpr_vmi_pas;\n    } \n    else {\n      rpm -> inf_vm3v[disk] -> prs = &pr_vm3s_act; \n      rpm -> inf_vm3v[disk] -> prc = &pr_vm3c_act; \n      rpm -> inf_vm3v[disk] -> srprs = &srpr_vm3s_act;\n      rpm -> inf_vm3v[disk] -> srprc = &srpr_vm3c_act;\n      \n      if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PVM3P))) { \n\trpm -> inf_vm3v[disk] -> prs = &pr_vmi_pas; \n\trpm -> inf_vm3v[disk] -> srprs = &srpr_vmi_pas;\n      }\n      else if ((chkb_val(rpm, fit, PRPARAMS+disk*NDPARAMS+PVM3P, PIHALF))) { \n\trpm -> inf_vm3v[disk] -> prc = &pr_vmi_pas; \n\trpm -> inf_vm3v[disk] -> srprc = &srpr_vmi_pas;\n      }\n    }\n  }\n  return 0;\n \n error:\n  for (disk = 0; disk < rpm -> ndisks; ++disk) {\n    destroy_inf_vm3(rpm -> inf_vm3v[disk]);\n    rpm -> inf_vm3v[disk] = NULL;\n  }\n  return 1;\n}    \n\n/* ------------------------------------------------------------ */\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    \n\n/* Optionally allocates and puts correct switches in the vm4 struct */    \nstatic int chkb_vm4(ringparms *rpm, fitparms *fit) \n{ \n  int disk;\n  \n  for (disk = 0; disk < rpm -> ndisks; ++ disk) {\n    \n    if (!(rpm -> inf_vm4v[disk])) \n      if (!(rpm -> inf_vm4v[disk] = create_inf_vm4())) \n\tgoto error;\n    \n    if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PVM4A))) { \n      rpm -> inf_vm4v[disk] -> prs = rpm -> inf_vm4v[disk] -> prc = &pr_vmi_pas; \n      rpm -> inf_vm4v[disk] -> srprs = rpm -> inf_vm4v[disk] -> srprc = &srpr_vmi_pas;\n    } \n    else {\n      rpm -> inf_vm4v[disk] -> prs = &pr_vm4s_act; \n      rpm -> inf_vm4v[disk] -> prc = &pr_vm4c_act; \n      rpm -> inf_vm4v[disk] -> srprs = &srpr_vm4s_act;\n      rpm -> inf_vm4v[disk] -> srprc = &srpr_vm4c_act;\n      \n      if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PVM4P))) { \n\trpm -> inf_vm4v[disk] -> prs = &pr_vmi_pas; \n\trpm -> inf_vm4v[disk] -> srprs = &srpr_vmi_pas;\n      }\n      else if ((chkb_val(rpm, fit, PRPARAMS+disk*NDPARAMS+PVM4P, PIHALF))) { \n\trpm -> inf_vm4v[disk] -> prs = &pr_vmi_pas; \n\trpm -> inf_vm4v[disk] -> srprs = &srpr_vmi_pas;\n      }\n    }\n  }\n  return 0;\n  \n error:\n  for (disk = 0; disk < rpm -> ndisks; ++disk) {\n    destroy_inf_vm4(rpm -> inf_vm4v[disk]);\n    rpm -> inf_vm4v[disk] = NULL;\n  }\n  return 1;\n}    \n\n/* ------------------------------------------------------------ */\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    \n\n/* Optionally allocates and puts correct switches in the ra1 struct */    \nstatic int chkb_ra1(ringparms *rpm, fitparms *fit) \n{ \n  int disk;\n\n  for (disk = 0; disk < rpm -> ndisks; ++ disk) {\n    \n    if (!(rpm -> inf_ra1v[disk])) \n      if (!(rpm -> inf_ra1v[disk] = create_inf_ra1())) \n\tgoto error; \n\n    if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PRA1A))) { \n      rpm -> inf_ra1v[disk] -> prs = rpm -> inf_ra1v[disk] -> prc = &pr_rai_pas; \n      rpm -> inf_ra1v[disk] -> srprs = rpm -> inf_ra1v[disk] -> srprc = &srpr_rai_pas;\n    } \n    else {\n      rpm -> inf_ra1v[disk] -> prs = &pr_ra1s_act; \n      rpm -> inf_ra1v[disk] -> prc = &pr_ra1c_act; \n      rpm -> inf_ra1v[disk] -> srprs = &srpr_ra1s_act;\n      rpm -> inf_ra1v[disk] -> srprc = &srpr_ra1c_act;\n\n      if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PRA1P))) { \n\trpm -> inf_ra1v[disk] -> prs = &pr_rai_pas; \n\trpm -> inf_ra1v[disk] -> srprs = &srpr_rai_pas;\n      }\n      else if ((chkb_val(rpm, fit, PRPARAMS+disk*NDPARAMS+PRA1P, PIHALF))) { \n\trpm -> inf_ra1v[disk] -> prc = &pr_rai_pas; \n\trpm -> inf_ra1v[disk] -> srprc = &srpr_rai_pas;\n      }\n    }\n  }\n\n  return 0;\n  \n error:\n  for (disk = 0; disk < rpm -> ndisks; ++disk) {\n    destroy_inf_ra1(rpm -> inf_ra1v[disk]);\n      rpm -> inf_ra1v[disk] = NULL;\n  }\n  return 1;\n}    \n\n/* ------------------------------------------------------------ */\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    \n\n/* Optionally allocates and puts correct switches in the ra2 struct */    \nstatic int chkb_ra2(ringparms *rpm, fitparms *fit) \n{ \n  int disk;\n\n  for (disk = 0; disk < rpm -> ndisks; ++ disk) {\n    \n    if (!(rpm -> inf_ra2v[disk])) \n      if (!(rpm -> inf_ra2v[disk] = create_inf_ra2())) \n\tgoto error;\n \n    if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PRA2A))) { \n      rpm -> inf_ra2v[disk] -> prs = rpm -> inf_ra2v[disk] -> prc = &pr_rai_pas; \n    rpm -> inf_ra2v[disk] -> srprs = rpm -> inf_ra2v[disk] -> srprc = &srpr_rai_pas;\n    } \n    else {\n      rpm -> inf_ra2v[disk] -> prs = &pr_ra2s_act; \n      rpm -> inf_ra2v[disk] -> prc = &pr_ra2c_act; \n      rpm -> inf_ra2v[disk] -> srprs = &srpr_ra2s_act;\n      rpm -> inf_ra2v[disk] -> srprc = &srpr_ra2c_act;\n      \n      if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PRA2P))) { \n      rpm -> inf_ra2v[disk] -> prs = &pr_rai_pas; \n      rpm -> inf_ra2v[disk] -> srprs = &srpr_rai_pas;\n      }\n      else if ((chkb_val(rpm, fit, PRPARAMS+disk*NDPARAMS+PRA2P, PIHALF))) { \n\trpm -> inf_ra2v[disk] -> prs = &pr_rai_pas; \n\trpm -> inf_ra2v[disk] -> srprs = &srpr_rai_pas;\n      }\n    }\n  }\n  return 0;\n  \n error:\n  for (disk = 0; disk < rpm -> ndisks; ++disk) {\n    destroy_inf_ra2(rpm -> inf_ra2v[disk]);\n    rpm -> inf_ra2v[disk] = NULL;\n  }\n  return 1;\n}    \n\n/* ------------------------------------------------------------ */\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    \n\n/* Optionally allocates and puts correct switches in the ra3 struct */    \nstatic int chkb_ra3(ringparms *rpm, fitparms *fit) \n{ \n  int disk;\n  \n  for (disk = 0; disk < rpm -> ndisks; ++ disk) {\n    \n    if (!(rpm -> inf_ra3v[disk])) \n      if (!(rpm -> inf_ra3v[disk] = create_inf_ra3())) \n\tgoto error;\n \n    if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PRA3A))) { \n      rpm -> inf_ra3v[disk] -> prs = rpm -> inf_ra3v[disk] -> prc = &pr_rai_pas; \n      rpm -> inf_ra3v[disk] -> srprs = rpm -> inf_ra3v[disk] -> srprc = &srpr_rai_pas;\n    } \n    else {\n      rpm -> inf_ra3v[disk] -> prs = &pr_ra3s_act; \n      rpm -> inf_ra3v[disk] -> prc = &pr_ra3c_act; \n      rpm -> inf_ra3v[disk] -> srprs = &srpr_ra3s_act;\n      rpm -> inf_ra3v[disk] -> srprc = &srpr_ra3c_act;\n      \n      if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PRA3P))) { \n\trpm -> inf_ra3v[disk] -> prs = &pr_rai_pas; \n\trpm -> inf_ra3v[disk] -> srprs = &srpr_rai_pas;\n      }\n      else if ((chkb_val(rpm, fit, PRPARAMS+disk*NDPARAMS+PRA3P, PIHALF))) { \n\trpm -> inf_ra3v[disk] -> prc = &pr_rai_pas; \n\trpm -> inf_ra3v[disk] -> srprc = &srpr_rai_pas;\n      }\n    }\n  }\n  return 0;\n \n error:\n  for (disk = 0; disk < rpm -> ndisks; ++disk) {\n    destroy_inf_ra3(rpm -> inf_ra3v[disk]);\n    rpm -> inf_ra3v[disk] = NULL;\n  }\n  return 1;\n}    \n\n/* ------------------------------------------------------------ */\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    \n\n/* Optionally allocates and puts correct switches in the ra4 struct */    \nstatic int chkb_ra4(ringparms *rpm, fitparms *fit) \n{ \n  int disk;\n  \n  for (disk = 0; disk < rpm -> ndisks; ++ disk) {\n    \n    if (!(rpm -> inf_ra4v[disk])) \n      if (!(rpm -> inf_ra4v[disk] = create_inf_ra4())) \n\tgoto error;\n    \n    if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PRA4A))) { \n      rpm -> inf_ra4v[disk] -> prs = rpm -> inf_ra4v[disk] -> prc = &pr_rai_pas; \n      rpm -> inf_ra4v[disk] -> srprs = rpm -> inf_ra4v[disk] -> srprc = &srpr_rai_pas;\n    } \n    else {\n      rpm -> inf_ra4v[disk] -> prs = &pr_ra4s_act; \n      rpm -> inf_ra4v[disk] -> prc = &pr_ra4c_act; \n      rpm -> inf_ra4v[disk] -> srprs = &srpr_ra4s_act;\n      rpm -> inf_ra4v[disk] -> srprc = &srpr_ra4c_act;\n      \n      if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PRA4P))) { \n\trpm -> inf_ra4v[disk] -> prs = &pr_rai_pas; \n\trpm -> inf_ra4v[disk] -> srprs = &srpr_rai_pas;\n      }\n      else if ((chkb_val(rpm, fit, PRPARAMS+disk*NDPARAMS+PRA4P, PIHALF))) { \n\trpm -> inf_ra4v[disk] -> prs = &pr_rai_pas; \n\trpm -> inf_ra4v[disk] -> srprs = &srpr_rai_pas;\n      }\n    }\n  }\n  return 0;\n  \n error:\n  for (disk = 0; disk < rpm -> ndisks; ++disk) {\n    destroy_inf_ra4(rpm -> inf_ra4v[disk]);\n    rpm -> inf_ra4v[disk] = NULL;\n  }\n  return 1;\n}    \n\n/* ------------------------------------------------------------ */\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    \n\n/* Optionally allocates and puts correct switches in the ro1 struct */    \nstatic int chkb_ro1(ringparms *rpm, fitparms *fit) \n{ \n  int disk;\n\n  for (disk = 0; disk < rpm -> ndisks; ++ disk) {\n    \n    if (!(rpm -> inf_ro1v[disk])) \n      if (!(rpm -> inf_ro1v[disk] = create_inf_ro1())) \n\tgoto error; \n\n    if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PRO1A))) { \n      rpm -> inf_ro1v[disk] -> prs = rpm -> inf_ro1v[disk] -> prc = &pr_roi_pas; \n      rpm -> inf_ro1v[disk] -> srprs = rpm -> inf_ro1v[disk] -> srprc = &srpr_roi_pas;\n    } \n    else {\n      rpm -> inf_ro1v[disk] -> prs = &pr_ro1s_act; \n      rpm -> inf_ro1v[disk] -> prc = &pr_ro1c_act; \n      rpm -> inf_ro1v[disk] -> srprs = &srpr_ro1s_act;\n      rpm -> inf_ro1v[disk] -> srprc = &srpr_ro1c_act;\n\n      if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PRO1P))) { \n\trpm -> inf_ro1v[disk] -> prs = &pr_roi_pas; \n\trpm -> inf_ro1v[disk] -> srprs = &srpr_roi_pas;\n      }\n      else if ((chkb_val(rpm, fit, PRPARAMS+disk*NDPARAMS+PRO1P, PIHALF))) { \n\trpm -> inf_ro1v[disk] -> prc = &pr_roi_pas; \n\trpm -> inf_ro1v[disk] -> srprc = &srpr_roi_pas;\n      }\n    }\n  }\n\n  return 0;\n  \n error:\n  for (disk = 0; disk < rpm -> ndisks; ++disk) {\n    destroy_inf_ro1(rpm -> inf_ro1v[disk]);\n      rpm -> inf_ro1v[disk] = NULL;\n  }\n  return 1;\n}    \n\n/* ------------------------------------------------------------ */\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    \n\n/* Optionally allocates and puts correct switches in the ro2 struct */    \nstatic int chkb_ro2(ringparms *rpm, fitparms *fit) \n{ \n  int disk;\n\n  for (disk = 0; disk < rpm -> ndisks; ++ disk) {\n    \n    if (!(rpm -> inf_ro2v[disk])) \n      if (!(rpm -> inf_ro2v[disk] = create_inf_ro2())) \n\tgoto error;\n \n    if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PRO2A))) { \n      rpm -> inf_ro2v[disk] -> prs = rpm -> inf_ro2v[disk] -> prc = &pr_roi_pas; \n    rpm -> inf_ro2v[disk] -> srprs = rpm -> inf_ro2v[disk] -> srprc = &srpr_roi_pas;\n    } \n    else {\n      rpm -> inf_ro2v[disk] -> prs = &pr_ro2s_act; \n      rpm -> inf_ro2v[disk] -> prc = &pr_ro2c_act; \n      rpm -> inf_ro2v[disk] -> srprs = &srpr_ro2s_act;\n      rpm -> inf_ro2v[disk] -> srprc = &srpr_ro2c_act;\n      \n      if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PRO2P))) { \n      rpm -> inf_ro2v[disk] -> prs = &pr_roi_pas; \n      rpm -> inf_ro2v[disk] -> srprs = &srpr_roi_pas;\n      }\n      else if ((chkb_val(rpm, fit, PRPARAMS+disk*NDPARAMS+PRO2P, PIHALF))) { \n\trpm -> inf_ro2v[disk] -> prs = &pr_roi_pas; \n\trpm -> inf_ro2v[disk] -> srprs = &srpr_roi_pas;\n      }\n    }\n  }\n  return 0;\n  \n error:\n  for (disk = 0; disk < rpm -> ndisks; ++disk) {\n    destroy_inf_ro2(rpm -> inf_ro2v[disk]);\n    rpm -> inf_ro2v[disk] = NULL;\n  }\n  return 1;\n}    \n\n/* ------------------------------------------------------------ */\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    \n\n/* Optionally allocates and puts correct switches in the ro3 struct */    \nstatic int chkb_ro3(ringparms *rpm, fitparms *fit) \n{ \n  int disk;\n  \n  for (disk = 0; disk < rpm -> ndisks; ++ disk) {\n    \n    if (!(rpm -> inf_ro3v[disk])) \n      if (!(rpm -> inf_ro3v[disk] = create_inf_ro3())) \n\tgoto error;\n \n    if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PRO3A))) { \n      rpm -> inf_ro3v[disk] -> prs = rpm -> inf_ro3v[disk] -> prc = &pr_roi_pas; \n      rpm -> inf_ro3v[disk] -> srprs = rpm -> inf_ro3v[disk] -> srprc = &srpr_roi_pas;\n    } \n    else {\n      rpm -> inf_ro3v[disk] -> prs = &pr_ro3s_act; \n      rpm -> inf_ro3v[disk] -> prc = &pr_ro3c_act; \n      rpm -> inf_ro3v[disk] -> srprs = &srpr_ro3s_act;\n      rpm -> inf_ro3v[disk] -> srprc = &srpr_ro3c_act;\n      \n      if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PRO3P))) { \n\trpm -> inf_ro3v[disk] -> prs = &pr_roi_pas; \n\trpm -> inf_ro3v[disk] -> srprs = &srpr_roi_pas;\n      }\n      else if ((chkb_val(rpm, fit, PRPARAMS+disk*NDPARAMS+PRO3P, PIHALF))) { \n\trpm -> inf_ro3v[disk] -> prc = &pr_roi_pas; \n\trpm -> inf_ro3v[disk] -> srprc = &srpr_roi_pas;\n      }\n    }\n  }\n  return 0;\n \n error:\n  for (disk = 0; disk < rpm -> ndisks; ++disk) {\n    destroy_inf_ro3(rpm -> inf_ro3v[disk]);\n    rpm -> inf_ro3v[disk] = NULL;\n  }\n  return 1;\n}    \n\n/* ------------------------------------------------------------ */\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    \n\n/* Optionally allocates and puts correct switches in the ro4 struct */    \nstatic int chkb_ro4(ringparms *rpm, fitparms *fit) \n{ \n  int disk;\n  \n  for (disk = 0; disk < rpm -> ndisks; ++ disk) {\n    \n    if (!(rpm -> inf_ro4v[disk])) \n      if (!(rpm -> inf_ro4v[disk] = create_inf_ro4())) \n\tgoto error;\n    \n    if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PRO4A))) { \n      rpm -> inf_ro4v[disk] -> prs = rpm -> inf_ro4v[disk] -> prc = &pr_roi_pas; \n      rpm -> inf_ro4v[disk] -> srprs = rpm -> inf_ro4v[disk] -> srprc = &srpr_roi_pas;\n    } \n    else {\n      rpm -> inf_ro4v[disk] -> prs = &pr_ro4s_act; \n      rpm -> inf_ro4v[disk] -> prc = &pr_ro4c_act; \n      rpm -> inf_ro4v[disk] -> srprs = &srpr_ro4s_act;\n      rpm -> inf_ro4v[disk] -> srprc = &srpr_ro4c_act;\n      \n      if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PRO4P))) { \n\trpm -> inf_ro4v[disk] -> prs = &pr_roi_pas; \n\trpm -> inf_ro4v[disk] -> srprs = &srpr_roi_pas;\n      }\n      else if ((chkb_val(rpm, fit, PRPARAMS+disk*NDPARAMS+PRO4P, PIHALF))) { \n\trpm -> inf_ro4v[disk] -> prs = &pr_roi_pas; \n\trpm -> inf_ro4v[disk] -> srprs = &srpr_roi_pas;\n      }\n    }\n  }\n  return 0;\n  \n error:\n  for (disk = 0; disk < rpm -> ndisks; ++disk) {\n    destroy_inf_ro4(rpm -> inf_ro4v[disk]);\n    rpm -> inf_ro4v[disk] = NULL;\n  }\n  return 1;\n}    \n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Optionally allocates and puts correct switches in the wm0 struct */\nstatic int chkb_wm0(ringparms *rpm, fitparms *fit)\n{\n  int disk;\n  \n  for (disk = 0; disk < rpm -> ndisks; ++ disk) {\n    \n    /* We allocate the wm0 struct */\n    if (!(rpm -> inf_wm0v[disk]))\n      if (!(rpm -> inf_wm0v[disk] = create_inf_wm0()))\n\tgoto error;\n    \n    /* If we fit ... */\n    if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PWM0A))) {\n      /* We point to the right functions */\n      rpm -> inf_wm0v[disk] -> pr = &pr_wmi_pas;\n\n    }\n    else {\n      \n      /* We point to the right functions */\n      rpm -> inf_wm0v[disk] -> pr = &pr_wm0_act;\n    }\n  }\n  return 0;\n  \n error:\n  for (disk = 0; disk < rpm -> ndisks; ++disk) {\n    destroy_inf_wm0(rpm -> inf_wm0v[disk]);\n    rpm -> inf_wm0v[disk] = NULL;\n  }\n  return 1;\n}\n\n/* ------------------------------------------------------------ */\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    \n\n/* Optionally allocates and puts correct switches in the wm1 struct */    \nstatic int chkb_wm1(ringparms *rpm, fitparms *fit) \n{ \n  int disk;\n  \n  for (disk = 0; disk < rpm -> ndisks; ++ disk) {\n    if (!(rpm -> inf_wm1v[disk])) \n      if (!(rpm -> inf_wm1v[disk] = create_inf_wm1())) \n\tgoto error; \n\n    if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PWM1A))) { \n      rpm -> inf_wm1v[disk] -> prs = rpm -> inf_wm1v[disk] -> prc = &pr_wmi_pas; \n      rpm -> inf_wm1v[disk] -> srprs = rpm -> inf_wm1v[disk] -> srprc = &srpr_wmi_pas;\n    } \n    else {\n      rpm -> inf_wm1v[disk] -> prs = &pr_wm1s_act; \n      rpm -> inf_wm1v[disk] -> prc = &pr_wm1c_act; \n      rpm -> inf_wm1v[disk] -> srprs = &srpr_wm1s_act;\n      rpm -> inf_wm1v[disk] -> srprc = &srpr_wm1c_act;\n      \n      if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PWM1P))) { \n\trpm -> inf_wm1v[disk] -> prs = &pr_wmi_pas; \n\trpm -> inf_wm1v[disk] -> srprs = &srpr_wmi_pas;\n      }\n      else if ((chkb_val(rpm, fit, PRPARAMS+disk*NDPARAMS+PWM1P, PIHALF))) { \n\trpm -> inf_wm1v[disk] -> prc = &pr_wmi_pas; \n\trpm -> inf_wm1v[disk] -> srprc = &srpr_wmi_pas;\n      }\n    }\n  }\n  return 0;\n  \n error:\n  for (disk = 0; disk < rpm -> ndisks; ++disk) {\n    destroy_inf_wm1(rpm -> inf_wm1v[disk]);\n    rpm -> inf_wm1v[disk] = NULL;\n  }\n  return 1;\n}    \n  \n/* ------------------------------------------------------------ */\n  \n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    \n\n/* Optionally allocates and puts correct switches in the wm2 struct */    \nstatic int chkb_wm2(ringparms *rpm, fitparms *fit) \n{ \n  int disk;\n  \n  for (disk = 0; disk < rpm -> ndisks; ++ disk) {\n    if (!(rpm -> inf_wm2v[disk])) \n      if (!(rpm -> inf_wm2v[disk] = create_inf_wm2())) \n\tgoto error; \n    if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PWM2A))) { \n      rpm -> inf_wm2v[disk] -> prs = rpm -> inf_wm2v[disk] -> prc = &pr_wmi_pas; \n      rpm -> inf_wm2v[disk] -> srprs = rpm -> inf_wm2v[disk] -> srprc = &srpr_wmi_pas;\n    } \n    else {\n      rpm -> inf_wm2v[disk] -> prs = &pr_wm2s_act; \n      rpm -> inf_wm2v[disk] -> prc = &pr_wm2c_act; \n      rpm -> inf_wm2v[disk] -> srprs = &srpr_wm2s_act;\n      rpm -> inf_wm2v[disk] -> srprc = &srpr_wm2c_act;\n      \n      if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PWM2P))) { \n\trpm -> inf_wm2v[disk] -> prs = &pr_wmi_pas; \n\trpm -> inf_wm2v[disk] -> srprs = &srpr_wmi_pas;\n      }\n      else if ((chkb_val(rpm, fit, PRPARAMS+disk*NDPARAMS+PWM2P, PIHALF))) { \n\trpm -> inf_wm2v[disk] -> prs = &pr_wmi_pas; \n\trpm -> inf_wm2v[disk] -> srprs = &srpr_wmi_pas;\n      }\n    }\n  }\n  return 0;\n  \n error:\n  for (disk = 0; disk < rpm -> ndisks; ++disk) {\n    destroy_inf_wm2(rpm -> inf_wm2v[disk]);\n    rpm -> inf_wm2v[disk] = NULL;\n  }\n  return 1;\n}    \n\n/* ------------------------------------------------------------ */\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    \n\n/* Optionally allocates and puts correct switches in the wm3 struct */    \nstatic int chkb_wm3(ringparms *rpm, fitparms *fit) \n{ \n  int disk;\n  \n  for (disk = 0; disk < rpm -> ndisks; ++ disk) {\n    if (!(rpm -> inf_wm3v[disk])) \n      if (!(rpm -> inf_wm3v[disk] = create_inf_wm3())) \n\tgoto error; \n    if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PWM3A))) { \n      rpm -> inf_wm3v[disk] -> prs = rpm -> inf_wm3v[disk] -> prc = &pr_wmi_pas; \n      rpm -> inf_wm3v[disk] -> srprs = rpm -> inf_wm3v[disk] -> srprc = &srpr_wmi_pas;\n    } \n    else {\n      rpm -> inf_wm3v[disk] -> prs = &pr_wm3s_act; \n      rpm -> inf_wm3v[disk] -> prc = &pr_wm3c_act; \n      rpm -> inf_wm3v[disk] -> srprs = &srpr_wm3s_act;\n      rpm -> inf_wm3v[disk] -> srprc = &srpr_wm3c_act;\n      \n      if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PWM3P))) { \n\trpm -> inf_wm3v[disk] -> prs = &pr_wmi_pas; \n\trpm -> inf_wm3v[disk] -> srprs = &srpr_wmi_pas;\n      }\n      else if ((chkb_val(rpm, fit, PRPARAMS+disk*NDPARAMS+PWM3P, PIHALF))) { \n\trpm -> inf_wm3v[disk] -> prc = &pr_wmi_pas; \n\trpm -> inf_wm3v[disk] -> srprc = &srpr_wmi_pas;\n      }\n    }\n  }\n  return 0;\n  \n error:\n  for (disk = 0; disk < rpm -> ndisks; ++disk) {\n    destroy_inf_wm3(rpm -> inf_wm3v[disk]);\n    rpm -> inf_wm3v[disk] = NULL;\n  }\n  return 1;\n}    \n\n/* ------------------------------------------------------------ */\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    \n\n/* Optionally allocates and puts correct switches in the wm4 struct */    \nstatic int chkb_wm4(ringparms *rpm, fitparms *fit) \n{ \n  int disk;\n  \n  for (disk = 0; disk < rpm -> ndisks; ++ disk) {\n    if (!(rpm -> inf_wm4v[disk])) \n      if (!(rpm -> inf_wm4v[disk] = create_inf_wm4())) \n\tgoto error; \n    if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PWM4A))) { \n      rpm -> inf_wm4v[disk] -> prs = rpm -> inf_wm4v[disk] -> prc = &pr_wmi_pas; \n      rpm -> inf_wm4v[disk] -> srprs = rpm -> inf_wm4v[disk] -> srprc = &srpr_wmi_pas;\n    } \n    else {\n      rpm -> inf_wm4v[disk] -> prs = &pr_wm4s_act; \n      rpm -> inf_wm4v[disk] -> prc = &pr_wm4c_act; \n      rpm -> inf_wm4v[disk] -> srprs = &srpr_wm4s_act;\n      rpm -> inf_wm4v[disk] -> srprc = &srpr_wm4c_act;\n      \n      if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PWM4P))) { \n      rpm -> inf_wm4v[disk] -> prs = &pr_wmi_pas; \n      rpm -> inf_wm4v[disk] -> srprs = &srpr_wmi_pas;\n      }\n      else if ((chkb_val(rpm, fit, PRPARAMS+disk*NDPARAMS+PWM4P, PIHALF))) { \n\trpm -> inf_wm4v[disk] -> prs = &pr_wmi_pas; \n\trpm -> inf_wm4v[disk] -> srprs = &srpr_wmi_pas;\n      }\n    }\n  }\n  return 0;\n  \n  error:\n  for (disk = 0; disk < rpm -> ndisks; ++disk) {\n    destroy_inf_wm4(rpm -> inf_wm4v[disk]);\n    rpm -> inf_wm4v[disk] = NULL;\n  }\n  return 1;\n}    \n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    \n\n/* Optionally allocates and puts correct switches in the ls0  struct */    \nstatic int chkb_ls0 (ringparms *rpm, fitparms *fit)    \n{    \n  int disk;\n  \n  for (disk = 0; disk < rpm -> ndisks; ++ disk) {\n    if (!(rpm -> inf_ls0v[disk]))\n      if (!(rpm -> inf_ls0v[disk]  = create_inf_ls0 ()))\n\tgoto error;    \n\n    if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PLS0 ))) {\n      rpm -> inf_ls0v[disk]  -> pr = &pr_ls0_pas;     \n    }    \n    else {\n      rpm -> inf_ls0v[disk]  -> pr = &pr_ls0_act;     \n    }   \n  } \n  return 0;    \n  \n error:\n  for (disk = 0; disk < rpm -> ndisks; ++disk) {\n    destroy_inf_ls0(rpm -> inf_ls0v[disk]);\n    rpm -> inf_ls0v[disk] = NULL;\n  }\n  return 1;\n}    \n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */    \n\n/* Optionally allocates and puts correct switches in the lc0  struct */    \nstatic int chkb_lc0 (ringparms *rpm, fitparms *fit)    \n{    \n  int disk;\n  \n  for (disk = 0; disk < rpm -> ndisks; ++ disk) {\n    if (!(rpm -> inf_lc0v[disk]))    \n      if (!(rpm -> inf_lc0v[disk]  = create_inf_lc0 ()))    \n\tgoto error;    \n    if ((chkb_zero(rpm, fit, PRPARAMS+disk*NDPARAMS+PLC0 ))) {\n      rpm -> inf_lc0v[disk]  -> pr = &pr_lc0_pas;     \n    }    \n    else {   \n      rpm -> inf_lc0v[disk]  -> pr = &pr_lc0_act;  \n    }\n  }\n  return 0;  \n  \n  error:\n  for (disk = 0; disk < rpm -> ndisks; ++disk) {\n    destroy_inf_lc0(rpm -> inf_lc0v[disk]);\n    rpm -> inf_lc0v[disk] = NULL;\n  }\n  return 1;\n} \n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* check if the function should be activated */\nstatic int chkb_zero(ringparms *rpm, fitparms *fit, int ident)\n{\n  return chkb_val(rpm, fit, ident, 0.0);\n}\n\n/* ------------------------------------------------------------ */\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* check if the function should be activated */\nstatic int chkb_val(ringparms *rpm, fitparms *fit, int ident, double val)\n{\n  int i, yesno = 1;\n  varlel *varele;\n\n  /* We check if this is unequal zero in the input */\n  for (i=0; i < rpm -> nur; ++i) {\n    if (rpm -> par[ident*rpm -> nur+i] != val) {\n      yesno = 0;\n      break;\n    }\n  }\n\n  /* We check if this is fitted going through all the elements */\n  varele = fit -> varylist;\n  while ((varele)) {\n    for (i = 0; i < varele -> nelem; ++i) {\n      if (varele -> elements[i]/rpm -> nur == ident)\n yesno = 0;\n    }\n    varele = varele -> next;\n  }\n\n  return yesno;\n}\n\n/* ------------------------------------------------------------ */\n\n/*************/\n/* Addendums under construction */\n/*************/\n/* #include \"constr.c\" */\n/*************/\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Constructs a NULL-terminated array of n (empty) reg_containers */\nstatic reg_cont **reg_cont_const(int nregs)\n{\n  reg_cont **reg_cont_const = NULL;\n  int i;\n\n  if (nregs < 0)\n    return NULL;\n\n  if (!(reg_cont_const = (reg_cont **) malloc ((nregs+1)*sizeof(reg_cont *))))\n    return NULL;\n\n  for (i = 0; i <= nregs; ++i)\n    reg_cont_const[i] = NULL;\n\n  for (i = 0; i < nregs; ++i) {\n    if (!(reg_cont_const[i] = (reg_cont *) malloc (sizeof(reg_cont)))) {\n      reg_cont_destr(reg_cont_const);\n      return NULL;\n    }\n  }\n\n  for (i = 0; i < nregs; ++i) {\n    if (!(reg_cont_const[i] -> fc = fourat_container_const())) {\n      reg_cont_destr(reg_cont_const);\n      return NULL;\n    }\n  }\n\n  return reg_cont_const;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Constructs a NULL-terminated array of n (empty) reg_containers */\nstatic int reg_cont_destr(reg_cont **reg_contv)\n{\n  int i = 0;\n\n  if (!reg_contv)\n    return 1;\n\n  while ((reg_contv[i])) {\n    if ((reg_contv[i] -> fc)) {\n      fourat_container_destr(reg_contv[i] -> fc);\n    }\n    free(reg_contv[i]);\n    ++i;\n  }\n\n  free(reg_contv);\n  \n  return 0;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Get the regularisation list from user input */\nstatic reg_cont **reg_cont_get(startinf *startinfv, hdrinf *hdr, ringparms *rpm, fitparms *fit)\n{\n  reg_cont **reg_cont_get = NULL;\n  \n  /**************/\n   /**************/ \n/*   int obsint = 0; */\n/*   char obsmes[200]; */\n/*   double *obsdouble; */\n  /**************/\n\n  /* Simple control stuff */\n  int nel, def, i, j, k;\n  char mes[81];  /* Any message */\n  int errcode = 1, outside = 0; /* another error code */\n  \n  char *varyhstr= NULL;\n  char **varystr = NULL;\n  char *dummystr = NULL;\n  decomp_control decomp_controlv = NULL;\n  decomp_listel *decomp_listelvact = NULL;\n  decomp_listel *decomp_listelvden = NULL;\n  decomp_listel *decomp_listelvnum = NULL;\n  decomp_listel *decomp_listelvdum = NULL;\n  char *dcperr;\n  int par = 0;\n  int maxorder;\n  int nregs;\n  int anint;\n  \n  double *regthre = NULL, *regwidt = NULL, *regampl = NULL, *regaste = NULL, *regampd = NULL;\n  \n  int nreadl, nreturned, keypres;\n\n  /* The complicated varystr */\n  /*   if (!(varystr = (char **) malloc(VARYSTRELES*sizeof(char *)))) */\n  /*     goto error; */\n  /* if (!(varyhstr = getfcharray(VARYHSTRELES, NULL))) */\n  /*   goto error; */\n  \n  /* get the dcp control structure */\n  if (!(decomp_controlv = decomp_init()))\n    goto error;\n  \n  /* Fill the dcp control structure with parameter information */\n  if ((dec_fill(rpm, decomp_controlv)))\n    goto error;\n  \n  /* First we fetch the list of parameters that should be regulated */\n  errcode = 1;\n  \n  /* Get the array */\n  while (errcode) {\n    \n    nel = 0;\n    def = 1;\n    \n    if (errcode == 2)\n      cancel_tir(startinfv -> arel, \"REGPARA=\", 2);\n    \n    /* sprintf(mes, \"Give parameters to regularise\"); */\n    /* flushfcharray(VARYHSTRELES, varyhstr); */\n    /* nel = usertext_tir(varyhstr, &def, \"REGPARA=\", mes); */\n    if ((varyhstr)) {\n      free(varyhstr);\n      varyhstr = NULL;\n    }\n    if (simparse_scn_arel_readval_string(startinfv -> arel, \"REGPARA\", \"Give parameters to regularise.\", 0, \"\", 0, -1, 0, 0, &keypres, &nreadl, &nreturned, &varyhstr))\n      goto error;\n    \n    /* Interlude: Change the case if it is lower case */\n    i = 0;\n    while (varyhstr[i]) {\n      if (varyhstr[i] >= 'a' && varyhstr[i] <= 'z') {\n\tvaryhstr[i] = varyhstr[i]+'A'-'a';\n      }\n      ++i;\n    }\n    \n    decomp_putsep(decomp_controlv, ',', '\\0', ':');\n    if ((decomp_listelvact))\n      decomp_list_dest(decomp_listelvact);\n    decomp_listelvact = NULL;\n    \n    /* Interpret this */\n    if ((errcode = decomp_get(decomp_controlv, varyhstr, &decomp_listelvact, 0))){\n      if (errcode == 1)\n\tgoto error;\n      else {\n\tsprintf(mes, \"REGPARA: \");\n\tif ((dcperr = decomp_errmsg(decomp_controlv)))\n\t  strncpy(mes+9, dcperr, 71);\n\tanyout_tir(&def, mes);\n      }\n    }\n    \n    /* Now do a sanity check: no group is allowed to point to intrinsically different elements */\n    \n    outside = 0;\n    \n    if (decomp_listelvact) {\n      i = 0;\n      nregs = 0;\n      while ((decomp_listelvact+i) -> nuel != -1) {\n\t++nregs;\n\tif (((decomp_listelvact+i) -> nuel)) {\n\t  par = (decomp_listelvact+i) -> poli[0] / rpm -> nur;\n\t}\n\tfor (j = 0; j < (decomp_listelvact+i) -> nuel; ++j){\n\t  if (par != (decomp_listelvact+i) -> poli[j] / rpm -> nur) {\n\t    outside = 1;\n\t  }\n\t  par = (decomp_listelvact+i) -> poli[j] / rpm -> nur;\n\t}\n\t++i;\n      }\n    }\n    else {\n      nregs = 0;\n    }\n    \n    if ((outside)) {\n      sprintf(mes,\"REGPARA: one parameter only between commas.\");\n      anyout_tir(&def, mes);\n      errcode |= 2;\n    }\n  }\n  \n  /* Provide an array of reg_conts */\n  if (!(reg_cont_get = reg_cont_const(nregs)))\n    goto error;\n  \n  /* proceed if there is more than 0 elements */\n  if ((nregs)) {\n    /* Now read in the lists */\n    \n    /* calculate the maximum order */\n    maxorder = rpm -> nur/2;\n    \n    /* Read in an array of arrays from den */\n    \n    \n    /* Reallocate the thingy */\n    decomp_dest(decomp_controlv);\n    if (!(decomp_controlv = decomp_init()))\n      goto error;\n    \n    /* Feed it with exactly one thing */\n    /*     if ((decomp_inp(decomp_controlv, \"D\", 0, maxorder)))  */\n    if ((decomp_inp(decomp_controlv, \"D\", 1, maxorder)))\n      goto error;\n    decomp_putsep(decomp_controlv, '\\0', '\\0', ':');\n    \n    errcode = 3;\n    def = 1;\n    \n    while (errcode) {\n      \n      if (errcode != 3)\n\tcancel_tir(startinfv -> arel, \"REGDENO=\", 2);\n      \n      errcode = 0;\n      \n      sprintf(mes, \"Enter denominator\");\n      /* flushfcharray(VARYHSTRELES, varyhstr); */\n      /* nel = usertext_tir(varyhstr, &def, \"REGDENO=\", mes); */\n      if ((varyhstr)) {\n\tfree(varyhstr);\n\tvaryhstr = NULL;\n      }\n\n      if (simparse_scn_arel_readval_string(startinfv -> arel, \"REGDENO\", mes, 0, \"\", 0, -1, 0, 0, &keypres, &nreadl, &nreturned, &varyhstr))\n\tgoto error;\n\n      /* Is this empty? */\n      if ((varystr)) {\n\tfreeparsed(varystr);\n\t/* \ti = 0; */\n\t/* \twhile(varystr[i]) { */\n\t/* \t  free(varystr[i]); */\n\t/* \t  ++i; */\n\t/* \t} */\n\t\n\t/* \tfree(varystr); */\n\tvarystr = NULL;\n      }\n      \n      if (!(varystr = sparsenext(\",\", \"\", \"\\t\", \"\", \"\", \"\", -1, &varyhstr, &anint, 0, 1))) {\n\tsprintf(mes,\"Please enter sufficient parameters for REGDENO.\");\n\tanyout_tir(&def, mes);\n\terrcode = 1;\n      }\n      else {\n\t\n\t/* It has to have exactly nreg elements, and determine the maximum length of the arrays */\n\ti = 0;\n\tj = 0;\n\twhile ((varystr[i])) {\n\t  if ((k = strlen(varystr[i])) > j) {\n\t    j = k;\n\t  }\n\t  ++i;\n\t}\n\t\n\tif (i != nregs) {\n\t  sprintf(mes,\"Please enter sufficient parameters for REGDENO.\");\n\t  anyout_tir(&def, mes);\n\t  errcode = 1;\n\t}\n\telse {\n\t  \n\t  if (!(decomp_listelvden = (decomp_listel *) malloc((nregs+1)*sizeof(decomp_listel))))\n\t    goto error;\n\t  \n\t  /* Now read in the single arrays for regd */\n\t  if ((dummystr)) {\n\t    free(dummystr);\n\t    dummystr = NULL;\n\t  }\n\t  if (!(dummystr = (char *) malloc((j+3)*sizeof(char))))\n\t    goto error;\n\t  \n\t  for (i = 0; i < nregs; ++i) {\n\t    sprintf(dummystr,\"D \");\n\t    sprintf(dummystr+2,\"%s\",varystr[i]);\n\t    \n\t    \n\t    if ((decomp_listelvdum)) {\n\t      free(decomp_listelvdum);\n\t      decomp_listelvdum = NULL;\n\t    }\n\t    \n\t    if ((errcode = decomp_get(decomp_controlv, dummystr, &decomp_listelvdum, 1))){\n\t      if (errcode == 1)\n\t\tgoto error;\n\t      else {\n\t\tsprintf(mes, \"REGDENO: \");\n\t\tif ((dcperr = decomp_errmsg(decomp_controlv)))\n\t\t  strncpy(mes+9, dcperr, 71);\n\t\tanyout_tir(&def, mes);\n\t      }\n\t    }\n\t    if (decomp_listelvdum) {\n\t      if (decomp_listelvdum -> nuel < 1) {\n\t\tsprintf(mes,\"Enter sufficient parameters for REGDENO.\");\n\t\tanyout_tir(&def, mes);\n\t\terrcode = 1;\n\t      }\n\t      else {\n\t\tfor (k = 0; k < decomp_listelvdum -> nuel; ++k) {\n\t\t  if ((decomp_listelvdum -> poli[k] < 0) || (decomp_listelvdum -> poli[k] > maxorder)) {\n\t\t    errcode = 1;\n\t\t    break;\n\t\t  }\n\t\t}\n\t\tif (errcode == 1) {\n\t\t  sprintf(mes,\"Order is between %i and %i\", 0, maxorder);\n\t\t  anyout_tir(&def, mes);\n\t\t}\n\t      }\n\t    }\t    \n\t    if ((errcode)) {\n\t      break;\n\t    }\n\t    (decomp_listelvden+i) -> nuel = decomp_listelvdum -> nuel;\n\t    (decomp_listelvden+i) -> poli = decomp_listelvdum -> poli;\n\t  }\t  \n\t  while (i < nregs) {\n\t    (decomp_listelvden+i) -> nuel = 0;\n\t    (decomp_listelvden+i) -> poli = NULL;\n\t    ++i;\n\t  }\n\t  (decomp_listelvden+nregs) -> nuel = -1;\n\t  (decomp_listelvden+nregs) -> poli = NULL;\n\t}\n      }\n    }\n    \n    \n    errcode = 3;\n    \n    while (errcode) {\n      \n      if (errcode != 3)\n\tcancel_tir(startinfv -> arel, \"REGNUME=\", 2);\n      \n      errcode = 0;\n      /* flushfcharray(VARYHSTRELES, varyhstr); */\n      /* nel = usertext_tir(varyhstr, &def, \"REGNUME=\", mes); */\n      \n      if ((varyhstr)) {\n\tfree(varyhstr);\n\tvaryhstr = NULL;\n      }\n      sprintf(mes,\"Please enter sufficient parameters for REGNUME.\");\n      if (simparse_scn_arel_readval_string(startinfv -> arel, \"REGNUME\", mes, 0, \"\", 0, -1, 0, 0, &keypres, &nreadl, &nreturned, &varyhstr))\n\tgoto error;\n      \n      /* Is this empty? */\n      if ((varystr)) {\n\tfreeparsed(varystr);\n\t/* \ti = 0; */\n\t/* \twhile(varystr[i]) { */\n\t/* \t  free(varystr[i]); */\n\t/* \t  ++i; */\n\t/* \t} */\n\t\n\t/* \tfree(varystr); */\n\tvarystr = NULL;\n      }\n      \n      \n      if (!(varystr = sparsenext(\",\", \"\", \"\\t\", \"\", \"\", \"\", -1, &varyhstr, &anint, 0, 1))) {\n\tsprintf(mes,\"Please enter sufficient parameters for REGNUME.\");\n\tanyout_tir(&def, mes);\n\terrcode = 1;\n      }\n      else {\n\t\n\t/* It has to have exactly nreg elements, and determine the maximum length of the arrays */\n\ti = 0;\n\tj = 0;\n\twhile ((varystr[i])) {\n\t  if ((k = strlen(varystr[i])) > j) {\n\t    j = k;\n\t  }\n\t  ++i;\n\t}\n\tif (i != nregs) {\n\t  sprintf(mes,\"Please enter sufficient parameters for REGNUME.\");\n\t  anyout_tir(&def, mes);\n\t  errcode = 1;\n\t}\n\telse {\n\t  \n\t  \n\t  if (!(decomp_listelvnum = (decomp_listel *) malloc((nregs+1)*sizeof(decomp_listel))))\n\t    goto error;\n\t  \n\t  /* Now read in the single arrays for regd */\n\t  if ((dummystr)) {\n\t    free(dummystr);\n\t    dummystr = NULL;\n\t  }\n\t  if (!(dummystr = (char *) malloc((j+3)*sizeof(char))))\n\t    goto error;\n\t  \n\t  for (i = 0; i < nregs; ++i) {\n\t    sprintf(dummystr,\"D \");\n\t    sprintf(dummystr+2,\"%s\",varystr[i]);\n\t    \n\t    if ((decomp_listelvdum)) {\n\t      free(decomp_listelvdum);\n\t      decomp_listelvdum = NULL;\n\t    }\n\t    \n\t    if ((errcode = decomp_get(decomp_controlv, dummystr, &decomp_listelvdum, 1))){\n\t      if (errcode == 1)\n\t\tgoto error;\n\t      else {\n\t\tsprintf(mes, \"REGNUME: \");\n\t\tif ((dcperr = decomp_errmsg(decomp_controlv)))\n\t\t  strncpy(mes+9, dcperr, 71);\n\t\tanyout_tir(&def, mes);\n\t      }\n\t    }\n\t    if (decomp_listelvdum) {\n\t      if (decomp_listelvdum -> nuel < 1) {\n\t\tsprintf(mes,\"Please enter sufficient parameters for REGNUME.\");\n\t\tanyout_tir(&def, mes);\n\t\terrcode = 1;\n\t      }\n\t      else {\n\t\tfor (k = 0; k < decomp_listelvdum -> nuel; ++k) {\n\t\t  if ((decomp_listelvdum -> poli[k] < 0) || (decomp_listelvdum -> poli[k] > maxorder)) {\n\t\t    errcode = 1;\n\t\t    break;\n\t\t  }\n\t\t}\n\t\tif (errcode == 1) {\n\t\t  sprintf(mes,\"Order is between %i and %i\", 0, maxorder);\n\t\t  anyout_tir(&def, mes);\n\t\t}\n\t      }\n\t    }\n\t    \n\t    if ((errcode)) {\n\t      break;\n\t    }\n\t    (decomp_listelvnum+i) -> nuel = decomp_listelvdum -> nuel;\n\t    (decomp_listelvnum+i) -> poli = decomp_listelvdum -> poli;\n\t  }\n\t  while (i < nregs) {\n\t    (decomp_listelvnum+i) -> nuel = 0;\n\t    (decomp_listelvnum+i) -> poli = NULL;\n\t    ++i;\n\t  }\n\t  (decomp_listelvnum+nregs) -> nuel = -1;\n\t  (decomp_listelvnum+nregs) -> poli = NULL;\n\t}\n      }\n    }\n    \n\n    /* Allocate and read in the three additional quantities */\n    if (!(regthre = (double *) malloc(nregs*sizeof(double))))\n      goto error;\n    if (!(regwidt = (double *) malloc(nregs*sizeof(double))))\n      goto error;\n    if (!(regampl = (double *) malloc(nregs*sizeof(double))))\n      goto error;\n    if (!(regaste = (double *) malloc(nregs*sizeof(double))))\n    goto error;\n    if (!(regampd = (double *) malloc(nregs*sizeof(double))))\n    goto error;\n    \n    def = 0;\n    \n    /* Get the regthre */\n    errcode = 1;\n    sprintf(mes, \"Give ratio threshold (in the same order)\");\n    while (errcode) {\n      errcode = 0;\n      nel = userdble_tir(startinfv -> arel, regthre, &nregs, &def, \"REGTHRE=\", mes);\n      if (!nel) {\n\tsprintf(mes, \"Something went wrong. Give REGTHRE=\");\n\tcancel_tir(startinfv -> arel, \"REGTHRE=\", 2);\n\terrcode = 1;\n      }\n      while (nel < nregs) {\n\tregthre[nel] = regthre[nel-1];\n\t++nel;\n      }\n    }\n    \n    /* Get the regwidt */\n    errcode = 1;\n    sprintf(mes, \"Give ratio step width (in the same order)\");\n    while (errcode) {\n      errcode = 0;\n      nel = userdble_tir(startinfv -> arel, regwidt, &nregs, &def, \"REGWIDT=\", mes);\n      if (!nel) {\n\tsprintf(mes, \"Something went wrong. Give REGWIDT=\");\n\tcancel_tir(startinfv -> arel, \"REGWIDT=\", 2);\n\terrcode = 1;\n      }\n      while (nel < nregs) {\n\tregwidt[nel] = regwidt[nel-1];\n\t++nel;\n      }\n    }\n    \n    /* Get the regampl */\n    errcode = 1;\n    sprintf(mes, \"Give parameter step amplitude (in the same order)\");\n    while (errcode) {\n      errcode = 0;\n      nel = userdble_tir(startinfv -> arel, regampl, &nregs, &def, \"REGAMPL=\", mes);\n      if (!nel) {\n\tsprintf(mes, \"Something went wrong. Give REGAMPL=\");\n\tcancel_tir(startinfv -> arel, \"REGAMPL=\", 2);\n\terrcode = 1;\n      }\n      while (nel < nregs) {\n\tregampl[nel] = regampl[nel-1];\n\t++nel;\n      }\n    }\n    \n    /* Get the regaste */\n    errcode = 1;\n    /* Notice that this is additive; the chisquared of an empty cube is N_x*N_y*N_v */\n    sprintf(mes, \"Give parameter amplitude increase per loop\");\n    while (errcode) {\n      errcode = 0;\n      nel = userdble_tir(startinfv -> arel, regaste, &nregs, &def, \"REGASTE=\", mes);\n      if (!nel) {\n\tsprintf(mes, \"Something went wrong. Give REGASTE=\");\n\tcancel_tir(startinfv -> arel, \"REGASTE=\", 2);\n\terrcode = 1;\n      }\n      while (nel < nregs) {\n\tregaste[nel] = regaste[nel-1];\n\t++nel;\n      }\n    }    \n\n    /* Get the regampd */\n    errcode = 1;\n    /* Notice that this is additive; the chisquared of an empty cube is N_x*N_y*N_v */\n    sprintf(mes, \"Give absolute denominator (>0)\");\n    while (errcode) {\n      errcode = 0;\n      nel = userdble_tir(startinfv -> arel, regampd, &nregs, &def, \"REGAMPD=\", mes);\n      if (!nel) {\n\tsprintf(mes, \"Something went wrong. Give REGAMPD=\");\n\tcancel_tir(startinfv -> arel, \"REGAMPD=\", 2);\n\terrcode = 1;\n      }\n      while (nel < nregs) {\n\tregampd[nel] = regampd[nel-1];\n\t++nel;\n      }\n    }    \n  }\n  \n  /* Now that we have the three arrays of listels, we continue with filling and initialising the fourat structure */\n  for (i = 0; i < nregs; ++i) {\n    fourat_put_length(reg_cont_get[i] -> fc, rpm -> nur, (decomp_listelvact+i) -> nuel, (decomp_listelvnum+i) -> nuel, (decomp_listelvden+i) -> nuel, HUGE_DBL);\n    \n    if (fourat_meminit(reg_cont_get[i] -> fc)) {\n      goto error;\n    }\n    \n    /* Put the position of the first element into the struct */\n    reg_cont_get[i] -> posoffirst = ((decomp_listelvact+i) -> poli[0]/rpm -> nur)*rpm -> nur;\n    reg_cont_get[i] -> first = rpm -> par + reg_cont_get[i] -> posoffirst;\n    \n    /* Recalculate the numbers from the active parameters to the relative positions w.r.t. the first element */\n    for (j = 0; j < (decomp_listelvact+i) -> nuel; ++j)\n      (decomp_listelvact+i) -> poli[j] = (decomp_listelvact+i) -> poli[j] % rpm -> nur;\n    \n    /* Then read in the vectors */\n    fourat_put_vectors(reg_cont_get[i] -> fc, reg_cont_get[i] -> first, (decomp_listelvact+i) -> poli, (decomp_listelvnum+i) -> poli, (decomp_listelvden+i) -> poli);\n    \n    /* Initialise again */\n    fourat_init(reg_cont_get[i] -> fc);\n    \n    /* clear up the other parameters */\n    reg_cont_get[i] -> regthre = regthre[i];\n    reg_cont_get[i] -> regwidt = regwidt[i];\n    reg_cont_get[i] -> regampl = regampl[i];\n    reg_cont_get[i] -> regaste = regaste[i];\n\n    /* Transfer to intrinsic coordinates and include normalisation */\n    if (regampd[i] > 0.0){\n      reg_cont_get[i] -> regampd = ((double) rpm -> nur) * fabs(dparamtointern(regampd[i], reg_cont_get[i] -> posoffirst/rpm -> nur+1, hdr, rpm -> ndisks));\n    }\n    else {\n      reg_cont_get[i] -> regampd = regampd[i];\n    }\n  }\n  \n  if ((varyhstr))\n    free(varyhstr);\n  if ((varystr))\n    freeparsed(varystr);\n  if ((decomp_controlv)) \n    decomp_dest(decomp_controlv);\n  if ((decomp_listelvact))\n    decomp_list_dest(decomp_listelvact);\n  if ((decomp_listelvden))\n    decomp_list_dest(decomp_listelvden);\n  if ((decomp_listelvnum))\n    decomp_list_dest(decomp_listelvnum);\n  if ((dummystr))\n    free(dummystr);\n  if((regthre))\n    free(regthre);\n  if ((regwidt))\n    free(regwidt);\n  if ((regampl))\n    free(regampl);\n  if ((regaste))\n    free(regaste);\n  if ((regampd))\n    free(regampd);\n  \n  /**********/\n  /**********/\n  /**********/\n  \n  /* Provide an overview, testing only */\n\n/*   sprintf(obsmes,\"Testing things\"); */\n/*   anyout_tir(&obsint, obsmes); */\n\n/*   if (!(obsdouble = (double *) malloc(rpm -> nur * sizeof(double)))) */\n/*     goto error; */\n\n  /* Count the numbers of regularisation groups */\n/*   for (nregs = 0; reg_cont_get[nregs]; ++nregs) */\n/*     ; */\n\n  /* Go through the list and read out the input */\n/*   for (i = 0; i < nregs; ++i) { */\n\n/*     sprintf(obsmes, \"Group %i, parameter \", i); */\n\n     /* what is the name of the first element? */ \n/*     ftstab_putcoltitl(obsmes+strlen(obsmes), reg_cont_get[i] -> posoffirst/rpm -> nur+1); */\n/*     anyout_tir(&obsint, obsmes); */\n\n    /* what are the values (note that this requires hdr, which is not usually passed by the function and has to be included in the input for this test */\n\n/*     sprintf(obsmes, \"Values: \"); */\n\n/*     for (j = 0; j < rpm -> nur; ++j) { */\n/*       sprintf(obsmes+strlen(obsmes), \"%.1E \", dinterntoparam(*(reg_cont_get[i] -> first+j), reg_cont_get[i] -> posoffirst/rpm -> nur+1, hdr, rpm -> ndisks)); */\n/*     } */\n/*       anyout_tir(&obsint, obsmes); */\n\n/*       sprintf(obsmes, \"Active ringnumbers: \"); */\n/*     for (j = 0; j < reg_cont_get[i] -> fc -> nact; ++j) { */\n/*       sprintf(obsmes+strlen(obsmes), \"%i \", reg_cont_get[i] -> fc -> act[j]); */\n/*     } */\n/*       anyout_tir(&obsint, obsmes); */\n\n/*       sprintf(obsmes, \"Orders numerator: \"); */\n/*     for (j = 0; j < reg_cont_get[i] -> fc -> nnum; ++j) { */\n/*       sprintf(obsmes+strlen(obsmes), \"%i \", reg_cont_get[i] -> fc -> num[j]); */\n/*     } */\n/*       anyout_tir(&obsint, obsmes); */\n\n/*       sprintf(obsmes, \"Orders denominator: \"); */\n/*     for (j = 0; j < reg_cont_get[i] -> fc -> nden; ++j) { */\n/*       sprintf(obsmes+strlen(obsmes), \"%i \", reg_cont_get[i] -> fc -> den[j]); */\n/*     } */\n/*       anyout_tir(&obsint, obsmes); */\n\n/*       sprintf(obsmes, \"Huge value: %.1E %.1E\", reg_cont_get[i] -> fc -> huge_dbl, HUGE_DBL); */\n/*       anyout_tir(&obsint, obsmes); */\n\n/*       sprintf(obsmes, \"Regthre: %.1E\", reg_cont_get[i] -> regthre); */\n/*       anyout_tir(&obsint, obsmes); */\n\n/*       sprintf(obsmes, \"Regwidt: %.1E\", reg_cont_get[i] -> regwidt); */\n/*       anyout_tir(&obsint, obsmes); */\n\n/*       sprintf(obsmes, \"Regampl: %.1E\", reg_cont_get[i] -> regampl); */\n/*       anyout_tir(&obsint, obsmes); */\n\n/*       sprintf(obsmes, \"Regaste: %.1E\", reg_cont_get[i] -> regaste); */\n/*       anyout_tir(&obsint, obsmes); */\n\n/*       sprintf(obsmes, \"Regampd: %.1E\", reg_cont_get[i] -> regampd); */\n/*       anyout_tir(&obsint, obsmes); */\n\n      /* Usage of smoothstep */\n/*       sprintf(obsmes, \"Smoothstep: f(%.1E) = %.1E,  f(%.1E) = %.1E, f(%.1E) = %.1E\", reg_cont_get[i] -> regthre, maths_hard_step(reg_cont_get[i] -> regthre, reg_cont_get[i] -> regwidt, 0.0, reg_cont_get[i] -> regampl, reg_cont_get[i] -> regthre), reg_cont_get[i] -> regthre+reg_cont_get[i] -> regwidt/2, maths_hard_step(reg_cont_get[i] -> regthre, reg_cont_get[i] -> regwidt, 0.0, reg_cont_get[i] -> regampl, reg_cont_get[i] -> regthre+reg_cont_get[i] -> regwidt/2), reg_cont_get[i] -> regthre+reg_cont_get[i] -> regwidt, maths_hard_step(reg_cont_get[i] -> regthre, reg_cont_get[i] -> regwidt, 0.0, reg_cont_get[i] -> regampl-1.0, reg_cont_get[i] -> regthre+reg_cont_get[i] -> regwidt)); */\n/*       anyout_tir(&obsint, obsmes); */\n\n\n/*   } */\n  /**********/\n\n  /* done */\n  return reg_cont_get;\n\n error:\n if (varyhstr)\n   free(varyhstr);\n  if ((varystr))\n    freeparsed(varystr);\n  if ((decomp_controlv)) \n    decomp_dest(decomp_controlv);\n  if ((decomp_listelvact))\n    decomp_list_dest(decomp_listelvact);\n  if ((decomp_listelvden))\n    decomp_list_dest(decomp_listelvden);\n  if ((decomp_listelvnum))\n    decomp_list_dest(decomp_listelvnum);\n  reg_cont_destr(reg_cont_get);\n  if ((dummystr))\n    free(dummystr);\n  if((regthre))\n    free(regthre);\n  if ((regwidt))\n    free(regwidt);\n  if ((regampl))\n    free(regampl);\n  if ((regaste))\n    free(regaste);\n  if ((regampd))\n    free(regampd);\n\n return NULL;\n}\n\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Constructs a NULL-terminated array of n (empty) reg_containers */\nstatic double reg_do(reg_cont **reg_contv, int loopnr, double chisquare)\n{\n  double reg_do = 0.0;\n  double addchisq = 0.0;\n  int i = 0;\n  int def = 0;\n  char mes[100];\n\n  /**************/\n   /**************/ \n/*   int obsint = 0; */\n/*   char obsmes[200]; */\n  /**************/\n\n\n  if (!reg_contv)\n    return 1.0;\n\n  while ((reg_contv[i])) {\n\n    /* read in the parameter */\n    fourat_put_array(reg_contv[i] -> fc, reg_contv[i] -> first);\n\n    /* Calculate the ratio */\n    if (reg_contv[i] -> regampd > 0.0) {\n      fourat_rat(reg_contv[i] -> fc, &(reg_contv[i] -> ratio), FOURAT_RAT_SUM);\n      /*********/\n/*       sprintf(mes, \"Amp (reg): %.2E Amp (par): %.2E Amp (fourat): %.2E\", reg_contv[i] -> regampd, *(reg_contv[i] -> first), reg_contv[i] -> ratio); */\n/*       anyout_tir(&def, mes); */\n\n      reg_contv[i] -> ratio = reg_contv[i] -> ratio/reg_contv[i] -> regampd;\n    }\n    else {\n      fourat_rat(reg_contv[i] -> fc, &(reg_contv[i] -> ratio), FOURAT_RAT_RATIO);\n    }\n    addchisq = maths_hard_step(reg_contv[i] -> regthre, reg_contv[i] -> regwidt, 0, (reg_contv[i] -> regampl+loopnr*reg_contv[i] -> regaste), reg_contv[i] -> ratio);\n\n    /* Calculate reg_do */\n    reg_do = reg_do+addchisq;\n\n    sprintf(mes, \"REG group: %i, mode ratio: %.2E, additional chi2: %.2E\", i+1, reg_contv[i] -> ratio, addchisq);\n    anyout_tir(&def, mes);\n\n    ++i;\n  }\n\n  if ((i)) {\n    sprintf(mes, \"REG total additional chi2: %.2E\", reg_do);\n    anyout_tir(&def, mes);\n  }\n\n  /* That's it */\n  return reg_do+chisquare;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\nstatic int dec_fill(ringparms *rpm, decomp_control *decomp_controlv)\n{  \n  int disk;\n  char placer[9];\n\n  /* ndisk construction */\n\n  /* radially dependent parameters */\n  if ((decomp_inp(decomp_controlv, \"RADI\", rpm -> nur*PRADI, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"VROT\", rpm -> nur*PVROT, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"VRAD\", rpm -> nur*PVRAD, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"VVER\", rpm -> nur*PVVER, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"DVRO\", rpm -> nur*PDVRO, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"DVRA\", rpm -> nur*PDVRA, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"DVVE\", rpm -> nur*PDVVE, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"ZDRO\", rpm -> nur*PZDRO, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"ZDRA\", rpm -> nur*PZDRA, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"ZDVE\", rpm -> nur*PZDVE, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"Z0\",   rpm -> nur*PZ0  , rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"SBR\",  rpm -> nur*PSBR , rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"SM1A\", rpm -> nur*PSM1A, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"SM1P\", rpm -> nur*PSM1P, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"SM2A\", rpm -> nur*PSM2A, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"SM2P\", rpm -> nur*PSM2P, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"SM3A\", rpm -> nur*PSM3A, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"SM3P\", rpm -> nur*PSM3P, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"SM4A\", rpm -> nur*PSM4A, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"SM4P\", rpm -> nur*PSM4P, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"GA1A\", rpm -> nur*PGA1A, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"GA1P\", rpm -> nur*PGA1P, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"GA1D\", rpm -> nur*PGA1D, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"GA2A\", rpm -> nur*PGA2A, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"GA2P\", rpm -> nur*PGA2P, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"GA2D\", rpm -> nur*PGA2D, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"GA3A\", rpm -> nur*PGA3A, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"GA3P\", rpm -> nur*PGA3P, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"GA3D\", rpm -> nur*PGA3D, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"GA4A\", rpm -> nur*PGA4A, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"GA4P\", rpm -> nur*PGA4P, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"GA4D\", rpm -> nur*PGA4D, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"AZ1P\", rpm -> nur*PAZ1P, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"AZ1W\", rpm -> nur*PAZ1W, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"AZ2P\", rpm -> nur*PAZ2P, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"AZ2W\", rpm -> nur*PAZ2W, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"INCL\", rpm -> nur*PINCL, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"PA\",   rpm -> nur*PPA  , rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"XPOS\", rpm -> nur*PXPOS, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"YPOS\", rpm -> nur*PYPOS, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"VSYS\", rpm -> nur*PVSYS, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"SDIS\", rpm -> nur*PSDIS, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"CLNR\", rpm -> nur*PCLNR, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"VM0A\", rpm -> nur*PVM0A, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"VM1A\", rpm -> nur*PVM1A, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"VM1P\", rpm -> nur*PVM1P, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"VM2A\", rpm -> nur*PVM2A, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"VM2P\", rpm -> nur*PVM2P, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"VM3A\", rpm -> nur*PVM3A, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"VM3P\", rpm -> nur*PVM3P, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"VM4A\", rpm -> nur*PVM4A, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"VM4P\", rpm -> nur*PVM4P, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"RA1A\", rpm -> nur*PRA1A, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"RA1P\", rpm -> nur*PRA1P, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"RA2A\", rpm -> nur*PRA2A, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"RA2P\", rpm -> nur*PRA2P, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"RA3A\", rpm -> nur*PRA3A, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"RA3P\", rpm -> nur*PRA3P, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"RA4A\", rpm -> nur*PRA4A, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"RA4P\", rpm -> nur*PRA4P, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"RO1A\", rpm -> nur*PRO1A, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"RO1P\", rpm -> nur*PRO1P, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"RO2A\", rpm -> nur*PRO2A, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"RO2P\", rpm -> nur*PRO2P, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"RO3A\", rpm -> nur*PRO3A, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"RO3P\", rpm -> nur*PRO3P, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"RO4A\", rpm -> nur*PRO4A, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"RO4P\", rpm -> nur*PRO4P, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"WM0A\", rpm -> nur*PWM0A, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"WM1A\", rpm -> nur*PWM1A, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"WM1P\", rpm -> nur*PWM1P, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"WM2A\", rpm -> nur*PWM2A, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"WM2P\", rpm -> nur*PWM2P, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"WM3A\", rpm -> nur*PWM3A, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"WM3P\", rpm -> nur*PWM3P, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"WM4A\", rpm -> nur*PWM4A, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"WM4P\", rpm -> nur*PWM4P, rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"LS0\",  rpm -> nur*PLS0 , rpm -> nur))) goto error;\n  if ((decomp_inp(decomp_controlv, \"LC0\",  rpm -> nur*PLC0 , rpm -> nur))) goto error;\n\n  for (disk = 1; disk < rpm -> ndisks; ++disk) {\n    sprintf(placer, \"VROT_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PVROT)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"VRAD_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PVRAD)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"VVER_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PVVER)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"DVRO_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PDVRO)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"DVRA_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PDVRA)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"DVVE_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PDVVE)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"ZDRO_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PZDRO)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"ZDRA_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PZDRA)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"ZDVE_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PZDVE)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"Z0_%i\"  , disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PZ0  )*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"SBR_%i\" , disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PSBR )*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"SM1A_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PSM1A)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"SM1P_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PSM1P)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"SM2A_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PSM2A)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"SM2P_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PSM2P)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"SM3A_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PSM3A)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"SM3P_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PSM3P)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"SM4A_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PSM4A)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"SM4P_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PSM4P)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"GA1A_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PGA1A)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"GA1P_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PGA1P)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"GA1D_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PGA1D)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"GA2A_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PGA2A)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"GA2P_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PGA2P)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"GA2D_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PGA2D)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"GA3A_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PGA3A)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"GA3P_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PGA3P)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"GA3D_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PGA3D)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"GA4A_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PGA4A)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"GA4P_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PGA4P)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"GA4D_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PGA4D)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"AZ1P_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PAZ1P)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"AZ1W_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PAZ1W)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"AZ2P_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PAZ2P)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"AZ2W_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PAZ2W)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"INCL_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PINCL)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"PA_%i\"  , disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PPA  )*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"XPOS_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PXPOS)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"YPOS_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PYPOS)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"VSYS_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PVSYS)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"SDIS_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PSDIS)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"CLNR_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PCLNR)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"VM0A_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PVM0A)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"VM1A_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PVM1A)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"VM1P_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PVM1P)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"VM2A_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PVM2A)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"VM2P_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PVM2P)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"VM3A_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PVM3A)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"VM3P_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PVM3P)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"VM4A_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PVM4A)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"VM4P_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PVM4P)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"RO1A_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PRO1A)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"RO1P_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PRO1P)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"RO2A_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PRO2A)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"RO2P_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PRO2P)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"RO3A_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PRO3A)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"RO3P_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PRO3P)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"RO4A_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PRO4A)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"RO4P_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PRO4P)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"RA1A_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PRA1A)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"RA1P_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PRA1P)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"RA2A_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PRA2A)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"RA2P_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PRA2P)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"RA3A_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PRA3A)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"RA3P_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PRA3P)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"RA4A_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PRA4A)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"RA4P_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PRA4P)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"WM0A_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PWM0A)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"WM1A_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PWM1A)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"WM1P_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PWM1P)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"WM2A_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PWM2A)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"WM2P_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PWM2P)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"WM3A_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PWM3A)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"WM3P_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PWM3P)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"WM4A_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PWM4A)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"WM4P_%i\", disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PWM4P)*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"LS0_%i\" , disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PLS0 )*rpm -> nur, rpm -> nur))) goto error;\n    sprintf(placer, \"LC0_%i\" , disk+1); if ((decomp_inp(decomp_controlv, placer, (PRPARAMS+disk*NDPARAMS+PLC0 )*rpm -> nur, rpm -> nur))) goto error;\n  }\n  /* global parameters, this needs to be changed somewhat when there is more than one */\n  if ((decomp_inp(decomp_controlv, \"CONDISP\", rpm -> nur*(NPARAMS + (rpm -> ndisks - 1)*NDPARAMS), 0))) goto error;\n\n  return 0;\n\n error:\n  decomp_dest(decomp_controlv);\n  return 1;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Creates a decomp-readable list from inputofvarymult and inputofvarysing and puts it into varyhstr */\nstatic char *gluetodecomp(char **inputofvarymult, char **inputofvarysing)\n{\n  int i, length = 0;\n  char *returnstring = NULL;\n\n  /* varyhstr[0] = '\\0'; */\n  i = 0;\n  while (inputofvarymult[i] != NULL) {\n    if (strpbrk(inputofvarymult[i],\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\")) {\n      length = length + strlen(\", !\");\n      length = length + strlen(inputofvarymult[i]);\n    }\n    else {\n      length = length + strlen(\" \");\n      length = length + strlen(inputofvarymult[i]);\n    }\n    ++i;\n  }\n  i = 0;\n  while (inputofvarysing[i] != NULL) {\n    if (strpbrk(inputofvarysing[i],\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\")) {\n      length = length + strlen(\", \");\n      length = length + strlen(inputofvarysing[i]);\n    }\n    else {\n      length = length + strlen(\" \");\n      length = length + strlen(inputofvarysing[i]);\n    }\n    ++i;\n  }\n\n  if (length > 1) {\n    if (!(returnstring = (char *) malloc((length+1)*sizeof(char))))\n      return NULL;\n    returnstring[length] = '\\0';\n  }\n  else {\n    if (!(returnstring = (char *) malloc(2*sizeof(char))))\n      return NULL;\n    returnstring[0] = '\\0';\n    returnstring[1] = '\\0';\n  }\n\n  i = length = 0;\n  while (inputofvarymult[i] != NULL) {\n    if (strpbrk(inputofvarymult[i],\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\")) {\n      strcpy(returnstring+length, \", !\");\n      length = length + strlen(\", !\");\n      strcpy(returnstring+length, inputofvarymult[i]);\n      length = length + strlen(inputofvarymult[i]);\n    }\n    else {\n\tstrncpy(returnstring+length, \" \", 1);\n      length = length + strlen(\" \");\n      strcpy(returnstring+length, inputofvarymult[i]);\n      length = length + strlen(inputofvarymult[i]);\n    }\n    ++i;\n  }\n\n  while (inputofvarysing[i] != NULL) {\n    if (strpbrk(inputofvarysing[i],\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\")) {\n      strcpy(returnstring+length, \", \");\n      length = length + strlen(\", \");\n      strcpy(returnstring+length, inputofvarysing[i]);\n      length = length + strlen(inputofvarysing[i]);\n    }\n    else {\n      strcpy(returnstring+length, \" \");\n      length = length + strlen(\" \");\n      strcpy(returnstring+length, inputofvarysing[i]);\n      length = length + strlen(inputofvarysing[i]);\n    }\n    ++i;\n  }\n\n  \n  if (strlen(returnstring))\n    returnstring[0] = ' ';\n\n  return returnstring;\n}\n\n/* ------------------------------------------------------------ */\n\n\n#ifdef PBCORR\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Allocate memory for primary beam factors */\nstatic void alloc_pbcfac_act(ringparms *rpm, int srnr, int disk)\n{\n  static char mes[180];\n  static int err = 1;\n  static long length;\n\n  if (!(length = rpm -> sd[disk][srnr].n))\n    length = 1;\n\n  if (!(rpm -> sd[disk][srnr].pbfac = (float *) malloc(length*sizeof(float)))) {\n    /* Catastrophy, simply stop */\n    sprintf(mes, \"Too many pointsources, increase PFLUX\");\n    error_tir(&err, mes);\n  }\n\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Allocate memory for primary beam factors, dummy */\nstatic void alloc_pbcfac_pas(ringparms *rpm, int srnr, int disk)\n{\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Deallocate memory for primary beam factors */\nstatic void dealloc_pbcfac_act(ringparms *rpm, int srnr, int disk)\n{\n  if ((rpm -> sd[disk][srnr].pbfac)){\n    free(rpm -> sd[disk][srnr].pbfac);\n    rpm -> sd[disk][srnr].pbfac = NULL;\n  }\n\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Deallocate memory for primary beam factors, dummy */\nstatic void dealloc_pbcfac_pas(ringparms *rpm, int srnr, int disk)\n{\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Fill the pbfac array with the right numbers */\nstatic void fill_pbcfac_act(hdrinf *hdr, struct srd **sd, int disk, int srnr, long *pnr, int *grid)\n{\n  sd[disk][srnr].pbfac[*pnr] = hdr -> primbeam[grid[0]+ hdr -> bsize1*(grid[1])];\n\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Fill the pbfac array with the right numbers, dummy */\nstatic void fill_pbcfac_pas(hdrinf *hdr, struct srd **sd, int disk, int srnr, long *pnr, int *grid)\n{\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Function to fold in the primary beam factor list when constructing the cube */\nstatic void corr_pbcfac_act(struct srd **sd, int disk, int srnr, long pnr)\n{\n  *(sd[disk][srnr].pl[pnr]) += sd[disk][srnr].pf*sd[disk][srnr].pbfac[pnr];\n\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Function to fold in the primary beam factor list when constructing the cube */\nstatic void corr_pbcfac_pas(struct srd **sd, int disk, int srnr, long pnr)\n{\n\n  *(sd[disk][srnr].pl[pnr]) += sd[disk][srnr].pf;\n\n  return;\n}\n\n/* ------------------------------------------------------------ */\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */\n\n/* Function to fold in the primary beam factor list when constructing the cube */\nstatic void chkb_pbcorr(hdrinf *hdr, ringparms *rpm)\n{\n\n  if (hdr -> primbeam) {\n    rpm -> alloc_pbcfac = alloc_pbcfac_act;\n    rpm -> dealloc_pbcfac = dealloc_pbcfac_act;\n    rpm -> fill_pbcfac = fill_pbcfac_act;\n    rpm -> corr_pbcfac = corr_pbcfac_act;\n  }\n  else {\n    rpm -> alloc_pbcfac = alloc_pbcfac_pas;\n    rpm -> dealloc_pbcfac = dealloc_pbcfac_pas;\n    rpm -> fill_pbcfac = fill_pbcfac_pas;\n    rpm -> corr_pbcfac = corr_pbcfac_pas;\n  }\n}\n\n/* ------------------------------------------------------------ */\n\n\n#endif\n\n\n\n\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ \n\n   $Log: tirific_new.c,v $\n   Revision 1.26  2011/05/25 22:25:26  jozsa\n   Left work\n\n   Revision 1.25  2011/05/11 13:37:12  jozsa\n   Left work\n\n   Revision 1.24  2011/05/10 00:30:16  jozsa\n   Left work\n\n   Revision 1.23  2011/05/04 01:51:03  jozsa\n   test\n\n   Revision 1.22  2011/05/04 01:08:25  jozsa\n   Left work\n\n   Revision 1.21  2011/05/04 01:03:41  jozsa\n   several changes to make genfitting possible\n\n   Revision 1.20  2011/03/23 22:32:29  jozsa\n   removed hdu 1 and 2, with that all storage of input parameters, left simple check whether tirific has created the file\n\n   Revision 1.19  2010/10/14 12:09:46  jozsa\n   Bugfix: With multiple disks, chkchange did not recognise the disk number correctly\n\n   Revision 1.18  2010/07/28 23:04:19  jozsa\n   Left work\n\n   Revision 1.17  2010/04/12 23:15:45  jozsa\n   included a few things, next is correction of coolgal\n\n   Revision 1.16  2010/04/01 09:24:19  jozsa\n   included and hopefully debugged: radial/vertical movement/gradients of those in z/azimuthal harmonics in velocity and surface brightness. To do 1) subclouds 2) Gaussian variations in azimuth 3) portions of a disk 4) 4 disks\n\n   Revision 1.15  2010/03/18 15:49:39  jozsa\n   implemented interpolation over passive parameters: indexing; implemented new syntax for parameter specification\n\n   Revision 1.14  2010/03/08 23:55:38  jozsa\n   left work\n\n   Revision 1.13  2010/03/02 08:23:08  jozsa\n   several changes, from the following versions on hdu2 is only partially checked for changes against the .def file\n\n   Revision 1.12  2009/08/04 16:28:33  jozsa\n   Left work\n\n   Revision 1.11  2009/05/27 15:07:38  jozsa\n   Left work\n\n   Revision 1.10  2008/10/10 15:42:40  jozsa\n   Introduced radial motion VPS1=\n\n   Revision 1.9  2008/07/30 16:22:42  jozsa\n   Some issue with accuracy in fillhdvarele()\n\n   Revision 1.8  2008/06/05 13:04:09  jozsa\n   left work\n\n   Revision 1.12  2008/02/18 16:47:23  gjozsa\n   graphics SDIS output\n\n   Revision 1.11  2008/02/13 16:43:47  gjozsa\n   silly bug\n\n   Revision 1.10  2008/01/16 11:17:24  gjozsa\n   bugfix concerning sdis\n\n   Revision 1.9  2008/01/09 17:50:50  gjozsa\n   minor bug\n\n   Revision 1.8  2008/01/09 17:25:52  gjozsa\n   introduced ring-dependent dispersion without performance loss\n\n   Revision 1.7  2007/08/23 15:23:26  gjozsa\n   Left work\n\n   Revision 1.5  2007/08/16 15:12:05  gjozsa\n   Left work\n\n   Revision 1.4  2007/08/15 16:28:23  gjozsa\n   Left work\n\n   Revision 1.3  2007/08/14 17:09:58  gjozsa\n   Left work\n\n   Revision 1.2  2007/07/25 17:17:09  gjozsa\n   Left work\n\n   Revision 1.1  2007/07/05 16:16:24  gjozsa\n   added to cvs control\n\n   Revision 1.66  2007/03/23 17:21:09  gjozsa\n   Changed back the changes from rev. 1.64, instead corrected the gridding: If the velocity increases with channel number, the pa changes by 180 deg w.r.t version pre-1.64, otherways it stays. For post-1.64 one has to change the pa by changing its signum and adding or subtracting 180 deg.\n\n   Revision 1.65  2007/02/23 10:28:10  gjozsa\n   BUGFIX in tirout: Works now for TIRACC > 6. Enlargened accuracy in textlog.\n\n   Revision 1.64  2007/01/17 15:54:52  gjozsa\n   Changed coordinate system in srconst by mirroring pp[0] to get a right hand coordinate system. In order not to change the pa definition changed the conversion functions interntoglob globtointern etc. Also did some changes to the graphics functions of which I don't know the effect. One can spot the changes via searching for 180.0 and DEGTORAD in the source\n\n   Revision 1.63  2006/12/11 12:42:07  gjozsa\n   BUGFIX: removed reading beam from header: too much confusion\n\n   Revision 1.62  2006/11/22 14:16:21  gjozsa\n   Bugfix concerning RASH and horizontal/vertical lines\n\n   Revision 1.61  2006/11/10 15:53:10  gjozsa\n   minor bugfix\n\n   Revision 1.60  2006/11/09 14:42:55  gjozsa\n   minor change\n\n   Revision 1.59  2006/11/08 14:05:03  gjozsa\n   included line drawing with keywords GR_VERL_i GR_HORL_i GR_VLVA_i GR_HLVA_i GR_VLCA_i GR_HLCA_i\n\n   Revision 1.58  2006/11/03 12:08:59  gjozsa\n   Small bugfix\n\n   Revision 1.57  2006/11/03 10:57:38  gjozsa\n   Introduced logarithmic scaling keywords: GR_XLOG, GR_YLOG_i, introduced hms dms for xpos and ypos in graphics output, introduced keywords RFREQ (restfrequency in Hertz) and ITOU (conversion factor from intensity in Jy/squarearcsec in u/squarecentimeter), changed DOUBLE_ACCURACY to 3E-15 to account for near zero events\n\n   Revision 1.56  2006/07/18 09:33:02  gjozsa\n   Left work\n\n   Revision 1.55  2006/04/11 11:46:00  gjozsa\n   Removed the positive SBR restriction in input\n\n   Revision 1.54  2006/04/06 10:40:25  gjozsa\n   Bugfix: Call of engalmod_chflgs() after changing the input cube after chisquare initialisation\n\n   Revision 1.53  2006/04/03 11:47:57  gjozsa\n   Left work\n\n   Revision 1.52  2005/10/12 14:50:59  gjozsa\n   Not really a Bugfix: Corrected the calculation of the ring normal vector\n\n   Revision 1.51  2005/10/12 09:53:45  gjozsa\n   Included Brigg's plots\n\n   Revision 1.50  2005/09/29 17:46:00  gjozsa\n   BUGFIX in the golden_section() function: refreshing pointsource lists is a crucial point\n\n   Revision 1.49  2005/08/25 10:15:05  gjozsa\n   Slight bug in the plot routines\n\n   Revision 1.48  2005/08/18 13:06:52  gjozsa\n   Left work\n\n   Revision 1.47  2005/08/15 13:15:03  gjozsa\n   BUGFIX: At 12523, not copying to the par array will result in funny results, when the only output is a .def file. Don't know whether this will cause sequals\n\n   Revision 1.45  2005/07/27 14:27:34  gjozsa\n   Again improved the graphics output\n\n   Revision 1.44  2005/07/27 14:01:30  gjozsa\n   Improved the graphics output\n\n   Revision 1.43  2005/06/28 13:28:08  gjozsa\n   Changed the out of range behaviour in golden_section()\n\n   Revision 1.42  2005/06/24 16:44:51  gjozsa\n   added interpolation possibility for the TIRDEF= output, not yet for TIRSMOOTH=\n\n   Revision 1.41  2005/06/24 12:00:30  gjozsa\n   Left work\n\n   Revision 1.43  2005/06/17 14:56:45  gjozsa\n   Bugfix\n\n   Revision 1.42  2005/06/17 14:50:45  gjozsa\n   Bugfix\n\n   Revision 1.41  2005/06/17 14:23:48  gjozsa\n   Added penalty for outliers\n\n   Revision 1.40  2005/06/13 10:40:29  gjozsa\n   Added possibility just to examine results\n\n   Revision 1.39  2005/06/09 14:07:45  gjozsa\n   Left work\n\n   Revision 1.38  2005/06/09 08:22:58  gjozsa\n   BUGFIX: Multiple Parameter fitting was not working properly, fixed that\n\n   Revision 1.37  2005/05/25 15:47:39  gjozsa\n   Added inclinogram output\n\n   Revision 1.36  2005/05/24 15:59:08  gjozsa\n   Added LON and LMV to table output\n\n   Revision 1.34  2005/05/24 10:42:03  gjozsa\n   Included graphics\n\n   Revision 1.33  2005/05/03 12:42:18  gjozsa\n   Left work\n\n   Revision 1.32  2005/04/28 12:44:44  gjozsa\n   bugfix\n\n   Revision 1.31  2005/04/28 10:13:47  gjozsa\n   Full introduction of pointsource lists\n\n   Revision 1.28  2005/04/26 11:44:53  gjozsa\n   Seems to work\n\n   Revision 1.25  2005/04/20 14:33:39  gjozsa\n   bug\n\n   Revision 1.24  2005/04/20 13:26:25  gjozsa\n   Left work\n\n   Revision 1.23  2005/04/19 13:58:50  gjozsa\n   Left work\n\n   Revision 1.22  2005/04/19 15:29:28  gjozsa\n   Finished the output functions\n\n   Revision 1.21  2005/04/19 10:59:13  gjozsa\n   Extended the possibilities for the histogram output\n\n   Revision 1.19  2005/04/19 07:44:43  gjozsa\n   Left work\n\n   Revision 1.18  2005/04/18 15:53:40  gjozsa\n   Added histogram functions\n\n   Revision 1.17  2005/04/18 15:02:02  gjozsa\n   Included TIR functions\n\n   Revision 1.16  2005/04/15 15:52:09  gjozsa\n   Left work\n\n   Revision 1.15  2005/04/15 15:39:13  gjozsa\n   Bugfix: in fct get_ringparms, documented as BUGFIX , in fct decodestring, also reported\n\n   Revision 1.14  2005/04/14 14:26:05  gjozsa\n   Left work\n\n   Revision 1.13  2005/04/14 10:32:16  gjozsa\n   Left work\n\n   Revision 1.10  2005/04/12 14:54:33  gjozsa\n   Changed the character of PARMAX= and PARMIN=\n\n   Revision 1.9  2005/04/11 14:23:37  gjozsa\n   Left work\n\n   Revision 1.8  2005/04/08 15:30:40  gjozsa\n   Taking into account the whole cube now, no counting for the user\n\n   Revision 1.7  2005/04/08 07:27:44  gjozsa\n   Bugfixes\n\n   Revision 1.6  2005/04/08 07:25:59  gjozsa\n   Bugfixes\n\n   Revision 1.5  2005/04/07 15:15:16  gjozsa\n   Bugfix in galmod(): subring velocity was overwritten by a radius, I hacked a bit, not nic at the moment\n\n   Revision 1.3  2005/04/06 15:46:25  gjozsa\n   Bugfixes, included monitoring of golden_section\n\n   Revision 1.2  2005/04/05 16:06:06  gjozsa\n   Left work\n\n   Revision 1.1  2005/04/05 11:07:37  gjozsa\n   The former tiridev, officially release 1\n\n   Revision 1.41  2005/04/04 08:42:09  gjozsa\n   removed bug\n\n   Revision 1.40  2005/04/01 15:31:54  gjozsa\n   Introduced writecubup and a lot of debugging, check whether the output is not too large\n\n   Revision 1.39  2005/03/29 15:56:24  gjozsa\n   left work\n\n   Revision 1.36  2005/03/25 18:17:20  gjozsa\n   Left work\n\n   Revision 1.35  2005/03/23 17:48:49  gjozsa\n   Implemented hdu_3 support, seems to work\n\n   Revision 1.32  2005/03/23 13:44:33  gjozsa\n   Implemented and tested 2nd hdu i/o\n\n   Revision 1.31  2005/03/22 17:48:07  gjozsa\n   Left work\n\n   Revision 1.30  2005/03/21 18:54:17  gjozsa\n   Left work\n\n   Revision 1.29  2005/03/19 17:55:52  gjozsa\n   Left work\n\n   Revision 1.26  2005/03/17 18:00:50  gjozsa\n   Left work\n\n   Revision 1.25  2005/03/16 17:52:00  gjozsa\n   Left work\n\n   Revision 1.23  2005/03/15 18:53:08  gjozsa\n   Left work\n\n   Revision 1.22  2005/03/15 17:28:59  gjozsa\n   Last changes to get a clear program structure, not ideal, but ok. Some debugging, deleting the fortran thingies\n\n   Revision 1.21  2005/03/12 16:48:33  gjozsa\n   Removed all clutter from readringparms and associated structs\n\n   Revision 1.19  2005/03/12 13:24:49  gjozsa\n   Removed all clutter from hdrinit\n\n   Revision 1.17  2005/03/12 11:37:46  gjozsa\n   Rearranged completely galmod, debugged and tested version of new galmod, including convolution routines, changed position angle to angle with respect to minor\n\n   Revision 1.16  2005/03/11 17:45:55  gjozsa\n   Left work\n\n   Revision 1.15  2005/03/10 17:56:39  gjozsa\n   Left work\n\n   Revision 1.13  2005/03/08 17:55:07  gjozsa\n   Left work\n\n   Revision 1.12  2005/03/05 17:56:09  gjozsa\n   Left work\n\n   Revision 1.11  2005/03/04 18:13:53  gjozsa\n   Left work\n\n   Revision 1.10  2005/03/03 18:00:49  gjozsa\n   Left work\n\n   Revision 1.9  2005/03/02 17:56:09  gjozsa\n   Left work\n\n   Revision 1.8  2005/03/01 17:46:21  gjozsa\n   Left work\n\n   Revision 1.6  2005/02/25 18:13:08  gjozsa\n   Left work\n\n   Revision 1.5  2005/02/25 13:34:29  gjozsa\n   cube io finished\n\n   Revision 1.4  2005/02/25 11:38:27  gjozsa\n   Created a header struct\n\n   Revision 1.3  2005/02/24 17:48:46  gjozsa\n   Left work\n\n   Revision 1.2  2004/12/09 16:17:14  gjozsa\n   Changed some floating point operations from double to float accuracy\n\n   Revision 1.1.1.1  2004/10/29 11:13:20  gjozsa\n   Added to CVS control\n\n\n   ------------------------------------------------------------ */\n", "meta": {"hexsha": "831de2b4fd4c581b2a97a4725d71a98c1203c007", "size": 1036304, "ext": "c", "lang": "C", "max_stars_repo_path": "src/tirific.c", "max_stars_repo_name": "kernsuite-debian/tirific", "max_stars_repo_head_hexsha": "05fddee80e715dfee5d0f4e2f994b2f17c5d2ca9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-07-01T12:07:09.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-04T08:22:01.000Z", "max_issues_repo_path": "src/tirific.c", "max_issues_repo_name": "gigjozsa/tirific", "max_issues_repo_head_hexsha": "462a58a8312ce437ac5e2c87060cde751774f1de", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-02-24T12:40:08.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-20T06:37:26.000Z", "max_forks_repo_path": "src/tirific.c", "max_forks_repo_name": "kernsuite-debian/tirific", "max_forks_repo_head_hexsha": "05fddee80e715dfee5d0f4e2f994b2f17c5d2ca9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-08-28T03:17:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T15:02:35.000Z", "avg_line_length": 36.2661067367, "max_line_length": 693, "alphanum_fraction": 0.5616450385, "num_tokens": 321297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.26284183737131667, "lm_q2_score": 0.024423087568798997, "lm_q1q2_score": 0.006419409210863692}}
{"text": "#ifndef __GSL_SORT_H__\n#define __GSL_SORT_H__\n\n#include <gsl/gsl_sort_long_double.h>\n#include <gsl/gsl_sort_double.h>\n#include <gsl/gsl_sort_float.h>\n\n#include <gsl/gsl_sort_ulong.h>\n#include <gsl/gsl_sort_long.h>\n\n#include <gsl/gsl_sort_uint.h>\n#include <gsl/gsl_sort_int.h>\n\n#include <gsl/gsl_sort_ushort.h>\n#include <gsl/gsl_sort_short.h>\n\n#include <gsl/gsl_sort_uchar.h>\n#include <gsl/gsl_sort_char.h>\n\n#endif /* __GSL_SORT_H__ */\n", "meta": {"hexsha": "b1496c2efbfe8973743213f869d15bf416bc40d0", "size": 435, "ext": "h", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/sort/gsl_sort.h", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 77.0, "max_stars_repo_stars_event_min_datetime": "2015-01-18T00:45:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-24T22:20:56.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/sort/gsl_sort.h", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/sort/gsl_sort.h", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 20.7142857143, "max_line_length": 37, "alphanum_fraction": 0.7747126437, "num_tokens": 136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18242554158599958, "lm_q2_score": 0.03514484905358528, "lm_q1q2_score": 0.0064113181225585}}
{"text": "#include \"airsar.h\"\n#include \"asf_meta.h\"\n#include <ctype.h>\n\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_multiroots.h>\n\n#define SQR(x) (x*x)\n\nstatic char *get_airsar(char *buf, char *str)\n{\n  char *p, *q;\n\n  static char value[51];\n  memset(value,0,51);\n\n  q = (char *) CALLOC(51,sizeof(char));\n  p = strstr(buf, str);\n  if (p) {\n    strncpy(q, p, 50);\n    strcpy(value, q+strlen(str));\n    //printf(\"%s: %s\\n\", str, value);\n  }\n  else\n    strcpy(value, \"\");\n\n  FREE(q);\n\n  return value;\n}\n\nairsar_header *read_airsar_header(const char *dataFile)\n{\n  airsar_header *header = NULL;\n  FILE *fp;\n  char buf[4400], *value;\n  double version;\nprintf(\"\\n\\ndataFile: %s\\n\\n\", dataFile);\n  // Allocate memory and file handling\n  value = (char *) MALLOC(sizeof(char)*25);\n  header = (airsar_header *) CALLOC(1, sizeof(airsar_header));\n  fp = FOPEN(dataFile, \"r\");\n  if (fgets(buf, 4400, fp) == NULL)\n    asfPrintError(\"Could not read general header\\n\");\n  FCLOSE(fp);\n\n  // Check for the processor version\n  // We take this as an indicator that we actually deal with AirSAR data\n  version = atof(get_airsar(buf, \"JPL AIRCRAFT SAR PROCESSOR VERSION\"));\n\n  // Read general header\n  if (version > 0.0) {\n    header->record_length = atoi(get_airsar(buf, \"RECORD LENGTH IN BYTES =\"));\n    header->number_records = atoi(get_airsar(buf, \"NUMBER OF HEADER RECORDS =\"));\n    header->sample_count =\n      atoi(get_airsar(buf, \"NUMBER OF SAMPLES PER RECORD =\"));\n    header->line_count =\n      atoi(get_airsar(buf, \"NUMBER OF LINES IN IMAGE =\"));\n    sprintf(header->processor, \"%s\",\n      trim_spaces(get_airsar(buf, \"JPL AIRCRAFT SAR PROCESSOR VERSION\")));\n    value = trim_spaces(get_airsar(buf, \"DATA TYPE =\"));\n    if (strcmp(value, \"INTEGER*2\") == 0)\n      header->data_type = INTEGER16;\n    sprintf(header->range_projection, \"%s\",\n\t    trim_spaces(get_airsar(buf, \"RANGE PROJECTION =\")));\n    header->x_pixel_size =\n      atof(get_airsar(buf, \"RANGE PIXEL SPACING (METERS) =\"));\n    header->y_pixel_size =\n      atof(get_airsar(buf, \"AZIMUTH PIXEL SPACING (METERS) =\"));\n    header->first_data_offset =\n      atoi(get_airsar(buf, \"BYTE OFFSET OF FIRST DATA RECORD =\"));\n    if (header->first_data_offset == 0)\n      header->first_data_offset = header->record_length*header->number_records;\n    header->parameter_header_offset =\n      atoi(get_airsar(buf, \"BYTE OFFSET OF PARAMETER HEADER =\"));\n    header->calibration_header_offset =\n      atoi(get_airsar(buf, \"BYTE OFFSET OF CALIBRATION HEADER =\"));\n    header->dem_header_offset =\n      atoi(get_airsar(buf, \"BYTE OFFSET OF DEM HEADER =\"));\n  }\n\n  return header;\n}\n\nairsar_param_header *read_airsar_params(const char *dataFile)\n{\n  airsar_param_header *params=NULL;\n  airsar_header *header = read_airsar_header(dataFile);\n  FILE *fp;\n  char *buf;\n  int size;\n\n  // Allocate memory and file handling\n  params = (airsar_param_header *) CALLOC(1, sizeof(airsar_param_header));\n  if (header->calibration_header_offset > 0)\n    size = header->calibration_header_offset - header->parameter_header_offset;\n  else if (header->dem_header_offset > 0)\n    size = header->dem_header_offset - header->parameter_header_offset;\n  else\n    size = header->first_data_offset - header->parameter_header_offset;\n  buf = (char *) MALLOC(sizeof(char)*size);\n  fp = FOPEN(dataFile, \"r\");\n  FSEEK(fp, header->parameter_header_offset, 1);\n  if (fgets(buf, size, fp) == NULL)\n    asfPrintError(\"Could not read parameter header\\n\");\n  FCLOSE(fp);\n\n  // Read parameter header\n  sprintf(params->site_name, \"%s\",\n\t  trim_spaces(get_airsar(buf, \"SITE NAME\")));\n  sprintf(params->cct_type, \"%s\",\n\t  trim_spaces(get_airsar(buf, \"CCT TYPE\")));\n  params->cct_id = atoi(get_airsar(buf, \"CCT ID\"));\n  params->start_lat =\n    atof(get_airsar(buf,\n\t\t    \"LATITUDE AT START OF SCENE (DEGREES)\"));\n  params->start_lon =\n    atof(get_airsar(buf,\n\t\t    \"LONGITUDE AT START OF SCENE (DEGREES)\"));\n  params->end_lat =\n    atof(get_airsar(buf,\n\t\t    \"LATITUDE AT END OF SCENE (DEGREES)\"));\n  params->end_lon =\n    atof(get_airsar(buf,\n\t\t    \"LONGITUDE AT END OF SCENE (DEGREES)\"));\n  sprintf(params->acquisition_date, \"%s\",\n\t  trim_spaces(get_airsar(buf,\n\t\t\t\t \"DATE OF ACQUISITION (GMT)\")));\n  params->acquisition_seconds =\n    atof(get_airsar(buf,\n\t\t    \"TIME OF ACQUISITION: SECONDS IN DAY\"));\n  sprintf(params->frequencies, \"%s\",\n\t  trim_spaces(get_airsar(buf,\n\t\t\t\t \"FREQUENCIES COLLECTED\")));\n  params->prf =\n    atof(get_airsar(buf, \"PRF AT START OF TRANSFER (HZ)\"));\n  params->range_sampling_rate =\n    atof(get_airsar(buf, \"SAMPLING RATE (MHZ)\"));\n  params->chirp_bandwidth =\n    atof(get_airsar(buf, \"CHIRP BANDWIDTH (MHZ)\"));\n  params->pulse_length =\n    atof(get_airsar(buf, \"PULSE LENGTH (MICROSECONDS)\"));\n  params->wavelength =\n    atof(get_airsar(buf, \"PROCESSOR WAVELENGTH (METERS)\"));\n  params->near_slant_range =\n    atof(get_airsar(buf, \"NEAR SLANT RANGE (METERS)\"));\n  params->far_slant_range =\n    atof(get_airsar(buf, \"FAR SLANT RANGE (METERS)\"));\n  params->near_look_angle =\n    atof(get_airsar(buf, \"NEAR LOOK ANGLE (DEGREES)\"));\n  params->far_look_angle =\n    atof(get_airsar(buf, \"FAR LOOK ANGLE (DEGEES)\"));\n  params->azimuth_look_count =\n    atoi(get_airsar(buf,\n\t\t    \"NUMBER OF LOOKS PROCESSED IN AZIMUTH\"));\n  params->range_look_count =\n    atoi(get_airsar(buf,\n\t\t    \"NUMBER OF LOOKS PROCESSED IN RANGE\"));\n  params->deskewed =\n    atoi(get_airsar(buf,\n\t\t    \"DESKEW FLAG (1=DESKEWED, 2=NOT DESKEWED)\"));\n  params->sr_sample_spacing =\n    atof(get_airsar(buf,\n\t\t    \"SLANT RANGE SAMPLE SPACING (METERS)\"));\n  params->slant_range_resolution =\n    atof(get_airsar(buf,\n\t\t    \"NOMINAL SLANT RANGE RESOLUTION (METERS)\"));\n  params->azimuth_sample_spacing =\n    atof(get_airsar(buf, \"AZIMUTH SAMPLE SPACING (METERS)\"));\n  params->azimuth_resolution =\n    atof(get_airsar(buf,\n\t\t    \"NOMINAL AZIMUTH RESOLUTION (METERS)\"));\n  params->center_lat =    atof(get_airsar(buf, \"IMAGE CENTER LATITUDE (DEGREES)\"));\n  params->center_lon =\n    atof(get_airsar(buf,\n\t\t    \"IMAGE CENTER LONGITUDE (DEGREES)\"));\n  params->scale_factor =\n    atof(get_airsar(buf, \"GENERAL SCALE FACTOR\"));\n  params->cal_factor_hh =\n    atof(get_airsar(buf, \"CALIBRATION FACTOR APPLIED, DB, HH\"));\n  params->cal_factor_hv =\n    atof(get_airsar(buf, \"CALIBRATION FACTOR APPLIED, DB, HV\"));\n  params->cal_factor_vh =\n    atof(get_airsar(buf, \"CALIBRATION FACTOR APPLIED, DB, VH\"));\n  params->cal_factor_vv =\n    atof(get_airsar(buf, \"CALIBRATION FACTOR APPLIED, DB, VV\"));\n  params->gps_altitude =\n    atof(get_airsar(buf, \"GPS ALTITUDE, M\"));\n  params->lat_peg_point =\n    atof(get_airsar(buf, \"LATITUDE OF PEG POINT\"));\n  params->lon_peg_point =\n    atof(get_airsar(buf, \"LONGITUDE OF PEG POINT\"));\n  params->head_peg_point =\n    atof(get_airsar(buf, \"HEADING AT PEG POINT\"));\n  params->along_track_offset =\n    atof(get_airsar(buf, \"ALONG-TRACK OFFSET S0  (M)\"));\n  params->cross_track_offset =\n    atof(get_airsar(buf, \"CROSS-TRACK OFFSET C0  (M)\"));\n\n  return params;\n}\n\nairsar_dem_header *read_airsar_dem(const char *dataFile)\n{\n  airsar_dem_header *dem = NULL;\n  airsar_header *header = read_airsar_header(dataFile);\n  FILE *fp;\n  char *buf;\n  int size;\n\n  // Allocate memory and file handling\n  dem = (airsar_dem_header *) CALLOC(1, sizeof(airsar_dem_header));\n  size = header->first_data_offset - header->dem_header_offset;\n  buf = (char *) MALLOC(sizeof(char)*size);\n  fp = FOPEN(dataFile, \"r\");\n  FSEEK(fp, header->dem_header_offset, 1);\n  if (fgets(buf, size, fp) == NULL)\n    asfPrintError(\"Could not read parameter header\\n\");\n  FCLOSE(fp);\n\n  // Read DEM header\n  dem->elevation_offset = atof(get_airsar(buf, \"ELEVATION OFFSET (M) =\"));\n  dem->elevation_increment =\n    atof(get_airsar(buf, \"ELEVATION INCREMENT (M) =\"));\n  dem->corner1_lat = atof(get_airsar(buf, \"LATITUDE OF CORNER 1 =\"));\n  dem->corner1_lon = atof(get_airsar(buf, \"LONGITUDE OF CORNER 1 =\"));\n  dem->corner2_lat = atof(get_airsar(buf, \"LATITUDE OF CORNER 2 =\"));\n  dem->corner2_lon = atof(get_airsar(buf, \"LONGITUDE OF CORNER 2 =\"));\n  dem->corner3_lat = atof(get_airsar(buf, \"LATITUDE OF CORNER 3 =\"));\n  dem->corner3_lon = atof(get_airsar(buf, \"LONGITUDE OF CORNER 3 =\"));\n  dem->corner4_lat = atof(get_airsar(buf, \"LATITUDE OF CORNER 4 =\"));\n  dem->corner4_lon = atof(get_airsar(buf, \"LONGITUDE OF CORNER 4 =\"));\n  dem->lat_peg_point =\n    atof(get_airsar(buf, \"LATITUDE OF PEG POINT =\"));\n  dem->lon_peg_point =\n    atof(get_airsar(buf, \"LONGITUDE OF PEG POINT =\"));\n  dem->head_peg_point =\n    atof(get_airsar(buf, \"HEADING AT PEG POINT (DEGREES) =\"));\n  dem->along_track_offset =\n    atof(get_airsar(buf, \"ALONG-TRACK OFFSET S0 (M) =\"));\n  dem->cross_track_offset =\n    atof(get_airsar(buf, \"CROSS-TRACK OFFSET C0 (M) =\"));\n\n  return dem;\n}\n\nairsar_cal_header *read_airsar_cal(const char *dataFile)\n{\n  airsar_cal_header *cal = NULL;\n  airsar_header *header = read_airsar_header(dataFile);\n  FILE *fp;\n  char *buf;\n  int size;\n\n  // Allocate memory and file handling\n  cal = (airsar_cal_header *) CALLOC(1, sizeof(airsar_cal_header));\n  size = header->first_data_offset - header->calibration_header_offset;\n  buf = (char *) MALLOC(sizeof(char)*size);\n  fp = FOPEN(dataFile, \"r\");\n  FSEEK(fp, header->calibration_header_offset, 1);\n  if (fgets(buf, size, fp) == NULL)\n    asfPrintError(\"Could not read parameter header\\n\");\n  FCLOSE(fp);\n\n  // Read DEM header\n  cal->scale_factor =\n    atof(get_airsar(buf, \"GENERAL SCALE FACTOR (dB)\"));\n  cal->hh_amp_cal_factor =\n    atof(get_airsar(buf, \"HH AMPLITUDE CALIBRATION FACTOR (dB)\"));\n  cal->hv_amp_cal_factor =\n    atof(get_airsar(buf, \"HV AMPLITUDE CALIBRATION FACTOR (dB)\"));\n  cal->vh_amp_cal_factor =\n    atof(get_airsar(buf, \"VH AMPLITUDE CALIBRATION FACTOR (dB)\"));\n  cal->vv_amp_cal_factor =\n    atof(get_airsar(buf, \"VV AMPLITUDE CALIBRATION FACTOR (dB)\"));\n  cal->hh_phase_cal_factor =\n    atof(get_airsar(buf, \"HH PHASE CALIBRATION FACTOR (DEGREES)\"));\n  cal->hv_phase_cal_factor =\n    atof(get_airsar(buf, \"HV PHASE CALIBRATION FACTOR (DEGREES)\"));\n  cal->vh_phase_cal_factor =\n    atof(get_airsar(buf, \"VH PHASE CALIBRATION FACTOR (DEGREES)\"));\n  cal->vv_phase_cal_factor =\n    atof(get_airsar(buf, \"VV PHASE CALIBRATION FACTOR (DEGREES)\"));\n  cal->hh_noise_sigma0 =\n    atof(get_airsar(buf, \"HH NOISE EQUIVALENT SIGMA ZERO (dB)\"));\n  cal->hv_noise_sigma0 =\n    atof(get_airsar(buf, \"HV NOISE EQUIVALENT SIGMA ZERO (dB)\"));\n  cal->vv_noise_sigma0 =\n    atof(get_airsar(buf, \"VV NOISE EQUIVALENT SIGMA ZERO (dB)\"));\n  cal->byte_offset_hh_corr =\n    atof(get_airsar(buf, \"BYTE OFFSET TO HH CORRECTION VECTOR\"));\n  cal->byte_offset_hv_corr =\n    atof(get_airsar(buf, \"BYTE OFFSET TO HV CORRECTION VECTOR\"));\n  cal->byte_offset_vv_corr =\n    atof(get_airsar(buf, \"BYTE OFFSET TO VV CORRECTION VECTOR\"));\n  cal->num_bytes_corr =\n    atof(get_airsar(buf, \"NUMBER OF BYTES IN CORRECTION VECTORS\"));\n\n  return cal;\n}\n\nstatic airsar_general *read_airsar_general(const char *inBaseName)\n{\n  // Read general metadata file\n  airsar_general *general=NULL;\n  char line[256]=\"\", *value, *p, *q;\n\n  general = (airsar_general *) CALLOC(1, sizeof(airsar_general));\n\n  char *metaFile = MALLOC(sizeof(char)*(strlen(inBaseName)+20));\n  if (!fileExists(inBaseName))\n    sprintf(metaFile, \"%s_meta.airsar\", inBaseName);\n  else {\n    strcpy(metaFile, inBaseName);\n    q = strstr(inBaseName, \"_meta.airsar\");\n    if (q)\n      *q = '\\0';\n  }\n\n  FILE *fpIn = FOPEN(metaFile, \"r\");\n\n  while (NULL != fgets(line, 255, fpIn)) {\n    p = strchr(line, '=');\n    if (p) {\n      value = p+1;\n      if (strncmp(line, \"SCENE ID\", 8) == 0)\n        sprintf(general->scene_id, \"%s\", value);\n      else if (strncmp(line, \"Name of Flight-line\", 19) == 0)\n        sprintf(general->flight_line, \"%s\", value);\n      else if (strncmp(line, \"Date of Acquistion\", 18) == 0)\n        sprintf(general->date_acquisition, \"%s\", value);\n      else if (strncmp(line, \"Date of Processing\", 18) == 0)\n        sprintf(general->date_processing, \"%s\", value);\n      else if (strncmp(line, \"Radar Projection (for highest freq product)\",\n               43) == 0)\n        sprintf(general->radar_projection, \"%s\", value);\n      else if (strncmp(line, \"Width in Km(for highest freq product)\", 37) == 0)\n        general->width = atof(value);\n      else if (strncmp(line, \"Length in Km(for highest freq product)\", 38) == 0)\n        general->length = atof(value);\n      else if (strncmp(line, \"Range pixel spacing\", 19) == 0)\n        general->range_pixel_spacing = atof(value);\n      else if (strncmp(line, \"Azimuth pixel spacing\", 21) == 0)\n        general->azimuth_pixel_spacing = atof(value);\n      else if (strncmp(line, \"Corner 1 latitude in degrees\", 28) == 0)\n        general->corner1_lat = atof(value);\n      else if (strncmp(line, \"Corner 1 longitude in degrees\", 29) == 0)\n        general->corner1_lon = atof(value);\n      else if (strncmp(line, \"Corner 2 latitude in degrees\", 28) == 0)\n        general->corner2_lat = atof(value);\n      else if (strncmp(line, \"Corner 2 longitude in degrees\", 29) == 0)\n        general->corner2_lon = atof(value);\n      else if (strncmp(line, \"Corner 3 latitude in degrees\", 28) == 0)\n        general->corner3_lat = atof(value);\n      else if (strncmp(line, \"Corner 3 longitude in degrees\", 29) == 0)\n        general->corner3_lon = atof(value);\n      else if (strncmp(line, \"Corner 4 latitude in degrees\", 28) == 0)\n        general->corner4_lat = atof(value);\n      else if (strncmp(line, \"Corner 4 longitude in degrees\", 29) == 0)\n        general->corner4_lon = atof(value);\n      else if (strncmp(line, \"C-band Radar Bandwidth in MHZ\", 29) == 0)\n        general->c_bandwidth = atof(value);\n      else if (strncmp(line, \"L-band Radar Bandwidth in MHZ\", 29) == 0)\n        general->l_bandwidth = atof(value);\n      else if (strncmp(line, \"P-band Radar Bandwidth in MHZ\", 29) == 0)\n        general->p_bandwidth = atof(value);\n      else if (strncmp(line, \"AIRSAR Mode\", 11) == 0)\n        sprintf(general->mode, \"%s\", value);\n      else if (strncmp(line, \"C-band Polarimetric data\", 24) == 0) {\n        if (strncmp(value, \"Yes\", 3) == 0)\n            general->c_pol_data = TRUE;\n        else if (strncmp(value, \"None\", 4) == 0)\n            general->c_pol_data = FALSE;\n      }\n      else if (strncmp(line, \"L-band Polarimetric data\", 24) == 0) {\n        if (strncmp(value, \"Yes\", 3) == 0)\n            general->l_pol_data = TRUE;\n        else if (strncmp(value, \"None\", 4) == 0)\n            general->l_pol_data = FALSE;\n      }\n      else if (strncmp(line, \"P-band Polarimetric data\", 24) == 0) {\n        if (strncmp(value, \"Yes\", 3) == 0)\n            general->p_pol_data = TRUE;\n        else if (strncmp(value, \"None\", 4) == 0)\n            general->p_pol_data = FALSE;\n      }\n      else if (strncmp(line, \"C-band Cross Track Interferometric data\", 39) == 0) {\n        if (strncmp(value, \"Yes\", 3) == 0)\n            general->c_cross_data = TRUE;\n        else if (strncmp(value, \"None\", 4) == 0)\n            general->c_cross_data = FALSE;\n      }\n      else if (strncmp(line, \"L-band Cross Track Interferometric data\", 39) == 0) {\n        if (strncmp(value, \"Yes\", 3) == 0)\n            general->l_cross_data = TRUE;\n        else if (strncmp(value, \"None\", 4) == 0)\n            general->l_cross_data = FALSE;\n      }\n      else if (strncmp(line, \"C-band Along Track Interferometric data\", 39) == 0) {\n        if (strncmp(value, \"Yes\", 3) == 0)\n            general->c_along_data = TRUE;\n        else if (strncmp(value, \"None\", 4) == 0)\n        general->c_along_data = FALSE;\n      }\n      else if (strncmp(line, \"L-band Along Track Interferometric data\", 39) == 0) {\n        if (strncmp(value, \"Yes\", 3) == 0)\n            general->l_along_data = TRUE;\n        else if (strncmp(value, \"None\", 4) == 0)\n            general->l_along_data = FALSE;\n      }\n      else if (strncmp(line, \"Interferometry Baseline Length\", 30) == 0)\n        sprintf(general->baseline, \"%s\", value);\n      else if (strncmp(line, \"Single Frequency/Channel band 1\", 31) == 0)\n        sprintf(general->frequency_band1, \"%s\", value);\n      else if (strncmp(line, \"Single Frequency/Channel band 2\", 31) == 0)\n        sprintf(general->frequency_band2, \"%s\", value);\n      else if (strncmp(line, \"Single Frequency/Channel band 3\", 31) == 0)\n        sprintf(general->frequency_band3, \"%s\", value);\n      else if (strncmp(line, \"Data Format for band 1\", 22) == 0)\n        sprintf(general->format_band1, \"%s\", value);\n      else if (strncmp(line, \"Data Format for band 2\", 22) == 0)\n        sprintf(general->format_band2, \"%s\", value);\n      else if (strncmp(line, \"Data Format for band 3\", 22) == 0)\n        sprintf(general->format_band3, \"%s\", value);\n    }\n  }\n  FCLOSE(fpIn);\n\n  free(metaFile);\n  return general;\n}\n\nmeta_parameters *import_airsar_meta(const char *dataName,\n\t\t\t\t    const char *inBaseName, int force)\n{\n  airsar_general *general = NULL;\n  airsar_header *header = read_airsar_header(dataName);\n  airsar_param_header *params = read_airsar_params(dataName);\n  airsar_dem_header *dem = NULL;\n  airsar_cal_header *cal = NULL;\n\n  if (!force || inBaseName)\n    general = read_airsar_general(inBaseName);\n\n  if (!force && (general->c_cross_data || general->l_cross_data)) {\n    // Figure out the whether we have a DEM header\n    char *demFile;\n    demFile = (char *) MALLOC(sizeof(char)*1024);\n    int found_c_dem = FALSE, found_l_dem = FALSE, found_p_dem = FALSE;\n\n    // The C-Band DEM is the preferred file for extracting the metadata.\n    // Look for that first. If no DEM is around then error out.\n    sprintf(demFile, \"%s_c.demi2\", inBaseName);\n    if (fileExists(demFile))\n      found_c_dem = TRUE;\n    sprintf(demFile, \"%s_l.demi2\", inBaseName);\n    if (fileExists(demFile))\n      found_l_dem = TRUE;\n    sprintf(demFile, \"%s_p.demi2\", inBaseName);\n    if (fileExists(demFile))\n      found_p_dem = TRUE;\n    if (!found_c_dem && !found_l_dem && !found_p_dem)\n      return NULL;\n\n    // Assign the correct DEM for generating the AirSAR metadata\n    if (found_c_dem)\n      sprintf(demFile, \"%s_c.demi2\", inBaseName);\n    else if (found_l_dem)\n      sprintf(demFile, \"%s_l.demi2\", inBaseName);\n    else if (found_p_dem)\n      sprintf(demFile, \"%s_p.demi2\", inBaseName);\n\n    dem = read_airsar_dem(demFile);\n  }\n  if (!dem && header->dem_header_offset > 0)\n    dem = read_airsar_dem(dataName);\n  if (header->calibration_header_offset > 0)\n    cal = read_airsar_cal(dataName);\n\n  meta_parameters *ret = airsar2meta(header, params, dem);\n\n  // For old AirSAR data, we need to extract the corner coordinates out of the\n  // general header file. If that is not available than we can't do any\n  // geocoding later.\n  if (strcmp_case(ret->general->sensor, \"AIRSAR\") == 0 &&\n      strstr(ret->general->processor, \"3.56\")) {\n    if (inBaseName) {\n      FREE(ret->airsar);\n      ret->airsar = NULL;\n      ret->location->lat_start_near_range = general->corner1_lat;\n      ret->location->lon_start_near_range = general->corner1_lon;\n      ret->location->lat_start_far_range = general->corner2_lat;\n      ret->location->lon_start_far_range = general->corner2_lon;\n      ret->location->lat_end_near_range = general->corner4_lat;\n      ret->location->lon_end_near_range = general->corner4_lon;\n      ret->location->lat_end_far_range = general->corner3_lat;\n      ret->location->lon_end_far_range = general->corner3_lon;\n      double lat, lon;\n      double yLine, xSamp;\n      meta_get_lineSamp(ret, 37.7697, -122.5218, 0.0, &yLine, &xSamp);\n      printf(\"center: line: %.3lf, sample: %.3lf\\n\", yLine, xSamp);\n      meta_get_latLon(ret, 0, 0, 0.0, &lat, &lon);\n      printf(\"start near - lat: %.4lf, lon: %.4lf\\n\", lat, lon);\n      meta_get_lineSamp(ret, ret->location->lat_start_near_range,\n\t\t\tret->location->lon_start_near_range, 0.0, \n\t\t\t&yLine, &xSamp);\n      printf(\"start near - line: %.3lf, sample: %.3lf, lat: %.4lf, lon: %.4lf\\n\"\n\t     ,yLine, xSamp, ret->location->lat_start_near_range,\n\t     ret->location->lon_start_near_range);\n      meta_get_latLon(ret, 0, ret->general->sample_count, 0.0, &lat, &lon);\n      printf(\"start far - lat: %.4lf, lon: %.4lf\\n\", lat, lon);\n      meta_get_lineSamp(ret, ret->location->lat_start_far_range,\n\t\t\tret->location->lon_start_far_range, 0.0, \n\t\t\t&yLine, &xSamp);\n      printf(\"start far - line: %.3lf, sample: %.3lf, lat: %.4lf, lon: %.4lf\\n\",\n\t     yLine, xSamp, ret->location->lat_start_far_range,\n\t     ret->location->lon_start_far_range);\n      meta_get_latLon(ret, ret->general->line_count, 0, 0.0, &lat, &lon);\n      printf(\"end near - lat: %.4lf, lon: %.4lf\\n\", lat, lon);\n      meta_get_lineSamp(ret, ret->location->lat_end_near_range,\n\t\t\tret->location->lon_end_near_range, 0.0, \n\t\t\t&yLine, &xSamp);\n      printf(\"end near - line: %.3lf, sample: %.3lf, lat: %.4lf, lon: %.4lf\\n\", \n\t     yLine, xSamp, ret->location->lat_end_near_range,\n\t     ret->location->lon_end_near_range);\n      meta_get_latLon(ret, ret->general->line_count, \n\t\t      ret->general->sample_count, 0.0, &lat, &lon);\n      printf(\"end far - lat: %.4lf, lon: %.4lf\\n\", lat, lon);\n      meta_get_lineSamp(ret, ret->location->lat_end_far_range,\n\t\t\tret->location->lon_end_far_range, 0.0, \n\t\t\t&yLine, &xSamp);\n      printf(\"end far - line: %.3lf, sample: %.3lf, lat: %.4lf, lon: %.4lf\\n\", \n\t     yLine, xSamp, ret->location->lat_end_far_range,\n\t     ret->location->lon_end_far_range);\n\n    }\n    else\n      asfPrintWarning(\"No main header file available to extract location \"\n\t\t      \"information. Can't geocode this data later\\n\");\n  }\n\n  if (general)\n    FREE(general);\n  FREE(header);\n  FREE(params);\n  if (dem)\n    FREE(dem);\n\n  return ret;\n}\n\n//static void fudge_airsar_params(meta_parameters *meta);\n\nint ingest_insar_data(const char *inBaseName, const char *outBaseName,\n\t\t      char band)\n{\n  airsar_header *header;\n  meta_parameters *metaIn, *metaOut;\n  FILE *fpIn, *fpOut;\n  char *inFile=NULL, *outFile=NULL;\n  int ii, kk, line_offset, ret=FALSE;\n  float *floatBuf=NULL;\n\n  // Generate metadata file\n  inFile = (char *) MALLOC(sizeof(char)*255);\n  outFile = (char *) MALLOC(sizeof(char)*255);\n\n  // Ingest the DEM\n  sprintf(inFile, \"%s_%c.demi2\", inBaseName, band);\n  if (!fileExists(inFile))\n    asfPrintStatus(\"   Could not find DEM file (%s) ...\\n\", inFile);\n  else {\n    asfPrintStatus(\"   Ingesting DEM ...\\n\");\n    sprintf(outFile, \"%s_%c_dem.img\", outBaseName, band);\n    header = read_airsar_header(inFile);\n    metaIn = import_airsar_meta(inFile, inBaseName, FALSE);\n    line_offset = header->first_data_offset/metaIn->general->sample_count/2;\n    metaIn->general->line_count += line_offset;\n    metaOut = import_airsar_meta(inFile, inBaseName, FALSE);\n    metaIn->general->data_type = INTEGER16;\n    metaOut->general->data_type = REAL32;\n    floatBuf = (float *) MALLOC(sizeof(float)*metaIn->general->sample_count);\n    fpIn = FOPEN(inFile, \"rb\");\n    fpOut = FOPEN(outFile, \"wb\");\n    for (ii=0; ii<metaOut->general->line_count; ii++) {\n      get_float_line(fpIn, metaIn, ii+line_offset, floatBuf);\n      for (kk=0; kk<metaIn->general->sample_count; kk++)\n\tfloatBuf[kk] = floatBuf[kk]*metaIn->airsar->elevation_increment +\n\t  metaIn->airsar->elevation_offset;\n      put_float_line(fpOut, metaOut, ii, floatBuf);\n      asfLineMeter(ii, metaOut->general->line_count);\n    }\n    FCLOSE(fpIn);\n    FCLOSE(fpOut);\n    metaOut->general->image_data_type = DEM;\n    strcpy(metaOut->general->bands, \"DEM\");\n    //fudge_airsar_params(metaOut);\n    meta_write(metaOut, outFile);\n    FREE(header);\n    ret = TRUE;\n  }\n\n  // Ingest amplitude image\n  sprintf(inFile, \"%s_%c.vvi2\", inBaseName, band);\n  if (!fileExists(inFile))\n    asfPrintStatus(\"   Could not find amplitude file (%s) ...\\n\", inFile);\n  else {\n    asfPrintStatus(\"   Ingesting amplitude image ...\\n\");\n    sprintf(outFile, \"%s_%c_vv.img\", outBaseName, band);\n    header = read_airsar_header(inFile);\n    line_offset = header->first_data_offset/metaIn->general->sample_count/2;\n    metaIn->general->line_count = metaOut->general->line_count + line_offset;\n    metaIn->general->data_type = INTEGER16;\n    metaOut->general->data_type = REAL32;\n    floatBuf = (float *) MALLOC(sizeof(float)*metaIn->general->sample_count);\n    fpIn = FOPEN(inFile, \"rb\");\n    fpOut = FOPEN(outFile, \"wb\");\n    for (ii=0; ii<metaOut->general->line_count; ii++) {\n      get_float_line(fpIn, metaIn, ii+line_offset, floatBuf);\n      put_float_line(fpOut, metaOut, ii, floatBuf);\n      asfLineMeter(ii, metaOut->general->line_count);\n    }\n    FCLOSE(fpIn);\n    FCLOSE(fpOut);\n    metaOut->general->image_data_type = AMPLITUDE_IMAGE;\n    strcpy(metaOut->general->bands, \"AMP\");\n    //fudge_airsar_params(metaOut);\n    meta_write(metaOut, outFile);\n    FREE(header);\n    ret = TRUE;\n  }\n\n  // Ingest coherence image\n  sprintf(inFile, \"%s_%c.corgr\", inBaseName, band);\n  if (!fileExists(inFile))\n    asfPrintStatus(\"   Could not find coherence image (%s) ...\\n\", inFile);\n  else {\n    asfPrintStatus(\"   Ingesting coherence image ...\\n\");\n    sprintf(outFile, \"%s_%c_coh.img\", outBaseName, band);\n    header = read_airsar_header(inFile);\n    line_offset = header->first_data_offset / metaIn->general->sample_count;\n    metaIn->general->line_count = metaOut->general->line_count + line_offset;\n    metaIn->general->data_type = BYTE;\n    metaOut->general->data_type = REAL32;\n    floatBuf = (float *) MALLOC(sizeof(float)*metaIn->general->sample_count);\n    fpIn = FOPEN(inFile, \"rb\");\n    fpOut = FOPEN(outFile, \"wb\");\n    for (ii=0; ii<metaOut->general->line_count; ii++) {\n      get_float_line(fpIn, metaIn, ii+line_offset, floatBuf);\n      put_float_line(fpOut, metaOut, ii, floatBuf);\n      asfLineMeter(ii, metaOut->general->line_count);\n    }\n    FCLOSE(fpIn);\n    FCLOSE(fpOut);\n    metaOut->general->image_data_type = COHERENCE_IMAGE;\n    strcpy(metaOut->general->bands, \"COH\");\n    //fudge_airsar_params(metaOut);\n    meta_write(metaOut, outFile);\n    FREE(header);\n    ret = TRUE;\n  }\n\n  // Clean up\n  if (floatBuf)\n    FREE(floatBuf);\n  if (inFile)\n    FREE(inFile);\n  if (outFile)\n    FREE(outFile);\n\n  return ret;\n}\n\nstatic int sign(char byteBuf)\n{\n  if (byteBuf < 0)\n    return -1;\n  else\n    return 1;\n}\n\nint ingest_polsar_data(const char *inBaseName, const char *outBaseName,\n\t\t       radiometry_t radiometry, char band)\n{\n  FILE *fpIn, *fpOut;\n  char *inFile, *outFile;\n  int ii, kk, ret;\n  char *byteBuf;\n  float *power, *shh_amp, *shh_phase, *shv_amp, *shv_phase, *svh_amp;\n  float *svh_phase, *svv_amp, *svv_phase;\n  float total_power, ysca, amp, phase;\n  float m11, m12, m13, m14, m22, m23, m24, m33, m34, m44;\n  complexFloat cpx;\n\n  // Allocate memory\n  inFile = (char *) MALLOC(sizeof(char)*255);\n  outFile = (char *) MALLOC(sizeof(char)*255);\n\n  // Ingest polarimetric data\n  sprintf(inFile, \"%s_%c.datgr\", inBaseName, band);\n  if (!fileExists(inFile))\n    sprintf(inFile, \"%s_%c.dat\", inBaseName, band);\n  if (!fileExists(inFile)) {\n    asfPrintStatus(\"   Cound not find polarimetric data set (%s_%c) ...\\n\",\n\t\t   inBaseName, band);\n    return FALSE;\n  }\n  else {\n    meta_parameters *meta = import_airsar_meta(inFile, inBaseName, FALSE);\n    meta->general->data_type = REAL32;\n    meta->general->image_data_type = POLARIMETRIC_IMAGE;\n    meta->general->band_count = 9;\n    if (radiometry == r_AMP)\n      strcpy(meta->general->bands,\n\t     \"AMP,AMP_HH,PHASE_HH,AMP_HV,PHASE_HV,AMP_VH,PHASE_VH,\"\\\n\t     \"AMP_VV,PHASE_VV\");\n    else if (radiometry == r_SIGMA)\n      strcpy(meta->general->bands,\n\t     \"AMP,SIGMA-AMP-HH,SIGMA-PHASE-HH,SIGMA-AMP-HV,SIGMA-PHASE-HV,\"\\\n\t     \"SIGMA-AMP-VH,SIGMA-PHASE-VH,SIGMA-AMP-VV,SIGMA-PHASE-VV\");\n    else if (radiometry == r_SIGMA_DB)\n      strcpy(meta->general->bands,\n\t     \"AMP,SIGMA_DB-AMP-HH,SIGMA_DB-PHASE-HH,SIGMA_DB-AMP-HV,\"\\\n\t     \"SIGMA_DB-PHASE-HV,SIGMA_DB-AMP-VH,SIGMA_DB-PHASE-VH,\"\\\n\t     \"SIGMA_DB-AMP-VV,SIGMA_DB-PHASE-VV\");\n    power = (float *) MALLOC(sizeof(float)*meta->general->sample_count);\n    shh_amp = (float *) MALLOC(sizeof(float)*meta->general->sample_count);\n    shh_phase = (float *) MALLOC(sizeof(float)*meta->general->sample_count);\n    shv_amp = (float *) MALLOC(sizeof(float)*meta->general->sample_count);\n    shv_phase = (float *) MALLOC(sizeof(float)*meta->general->sample_count);\n    svh_amp = (float *) MALLOC(sizeof(float)*meta->general->sample_count);\n    svh_phase = (float *) MALLOC(sizeof(float)*meta->general->sample_count);\n    svv_amp = (float *) MALLOC(sizeof(float)*meta->general->sample_count);\n    svv_phase = (float *) MALLOC(sizeof(float)*meta->general->sample_count);\n    byteBuf = (char *) MALLOC(sizeof(char)*10);\n    airsar_header *header = read_airsar_header(inFile);\n//    airsar_param_header *params = read_airsar_params(inFile);\n    long offset = header->first_data_offset;\n    sprintf(outFile, \"%s_%c.img\", outBaseName, band);\n    fpIn = FOPEN(inFile, \"rb\");\n    fpOut = FOPEN(outFile, \"wb\");\n    FSEEK(fpIn, offset, SEEK_SET);\n    for (ii=0; ii<meta->general->line_count; ii++) {\n      for (kk=0; kk<meta->general->sample_count; kk++) {\n\tFREAD(byteBuf, sizeof(char), 10, fpIn);\n\t// Scale is always 1.0 according to Bruce Chapman\n\tm11 = ((float)byteBuf[1]/254.0 + 1.5) * pow(2, byteBuf[0]);\n\tm12 = (float)byteBuf[2] * m11 / 127.0;\n\tm13 = sign(byteBuf[3]) * SQR((float)byteBuf[3] / 127.0) * m11;\n\tm14 = sign(byteBuf[4]) * SQR((float)byteBuf[4] / 127.0) * m11;\n\tm23 = sign(byteBuf[5]) * SQR((float)byteBuf[5] / 127.0) * m11;\n\tm24 = sign(byteBuf[6]) * SQR((float)byteBuf[6] / 127.0) * m11;\n\tm33 = (float)byteBuf[7] * m11 / 127.0;\n\tm34 = (float)byteBuf[8] * m11 / 127.0;\n\tm44 = (float)byteBuf[9] * m11 / 127.0;\n\tm22 = 1 - m33 -m44;\n\ttotal_power =\n\t  ((float)byteBuf[1]/254.0 + 1.5) * pow(2, byteBuf[0]);\n\tysca = 2.0 * sqrt(total_power);\n\tpower[kk] = sqrt(total_power);\n\tcpx.real = (float)byteBuf[2] * ysca / 127.0;\n\tcpx.imag = (float)byteBuf[3] * ysca / 127.0;\n\tamp = sqrt(cpx.real*cpx.real + cpx.imag*cpx.imag);\n\tphase = atan2(cpx.imag, cpx.real);\n\tif (radiometry == r_AMP) {\n\t  shh_amp[kk] = amp;\n\t  shh_phase[kk] = phase;\n\t}\n\telse if (radiometry == r_SIGMA) {\n\t  shh_amp[kk] = amp*amp;\n\t  shh_phase[kk] = phase;\n\t}\n\telse if (radiometry == r_SIGMA_DB) {\n\t  shh_amp[kk] = amp;\n\t  shh_phase[kk] = phase;\n\t}\n\tcpx.real = (float)byteBuf[4] * ysca / 127.0;\n\tcpx.imag = (float)byteBuf[5] * ysca / 127.0;\n\tamp = sqrt(cpx.real*cpx.real + cpx.imag*cpx.imag);\n\tphase = atan2(cpx.imag, cpx.real);\n\tif (radiometry == r_AMP) {\n\t  shv_amp[kk] = amp;\n\t  shv_phase[kk] = phase;\n\t}\n\telse if (radiometry == r_SIGMA) {\n\t  shv_amp[kk] = amp*amp;\n\t  shv_phase[kk] = phase;\n\t}\n\telse if (radiometry == r_SIGMA_DB) {\n\t  shv_amp[kk] = amp;\n\t  shv_phase[kk] = phase;\n\t}\n\tcpx.real = (float)byteBuf[6] * ysca / 127.0;\n\tcpx.imag = (float)byteBuf[7] * ysca / 127.0;\n\tamp = sqrt(cpx.real*cpx.real + cpx.imag*cpx.imag);\n\tphase = atan2(cpx.imag, cpx.real);\n\tif (radiometry == r_AMP) {\n\t  svh_amp[kk] = amp;\n\t  svh_phase[kk] = phase;\n\t}\n\telse if (radiometry == r_SIGMA) {\n\t  svh_amp[kk] = amp*amp;\n\t  svh_phase[kk] = phase;\n\t}\n\telse if (radiometry == r_SIGMA_DB) {\n\t  svh_amp[kk] = amp;\n\t  svh_phase[kk] = phase;\n\t}\n\tcpx.real = (float)byteBuf[8] * ysca / 127.0;\n\tcpx.imag = (float)byteBuf[9] * ysca / 127.0;\n\tamp = sqrt(cpx.real*cpx.real + cpx.imag*cpx.imag);\n\tphase = atan2(cpx.imag, cpx.real);\n\tif (radiometry == r_AMP) {\n\t  svv_amp[kk] = amp;\n\t  svv_phase[kk] = phase;\n\t}\n\telse if (radiometry == r_SIGMA) {\n\t  svv_amp[kk] = amp*amp;\n\t  svv_phase[kk] = phase;\n\t}\n\telse if (radiometry == r_SIGMA_DB) {\n\t  svv_amp[kk] = amp;\n\t  svv_phase[kk] = phase;\n\t}\n      }\n      put_band_float_line(fpOut, meta, 0, ii, power);\n      put_band_float_line(fpOut, meta, 1, ii, shh_amp);\n      put_band_float_line(fpOut, meta, 2, ii, shh_phase);\n      put_band_float_line(fpOut, meta, 3, ii, shv_amp);\n      put_band_float_line(fpOut, meta, 4, ii, shv_phase);\n      put_band_float_line(fpOut, meta, 5, ii, svh_amp);\n      put_band_float_line(fpOut, meta, 6, ii, svh_phase);\n      put_band_float_line(fpOut, meta, 7, ii, svv_amp);\n      put_band_float_line(fpOut, meta, 8, ii, svv_phase);\n      asfLineMeter(ii, meta->general->line_count);\n    }\n    FCLOSE(fpIn);\n    FCLOSE(fpOut);\n    meta_write(meta, outFile);\n\n    // Clean up\n    FREE(power);\n    FREE(shh_amp);\n    FREE(shh_phase);\n    FREE(shv_amp);\n    FREE(shv_phase);\n    FREE(svh_amp);\n    FREE(svh_phase);\n    FREE(svv_amp);\n    FREE(svv_phase);\n    FREE(inFile);\n    FREE(outFile);\n    FREE(byteBuf);\n\n    ret = TRUE;\n  }\n\n\n  return ret;\n}\n\nvoid import_airsar(const char *inBaseName, radiometry_t radiometry,\n\t\t   const char *outBaseName)\n{\n  char inFile[1024];\n  int found_c_dem = FALSE, found_l_dem = FALSE;\n\n  // Check radiometry\n  if (radiometry != r_AMP &&\n      radiometry != r_SIGMA && radiometry != r_SIGMA_DB) {\n    asfPrintWarning(\"Radiometry other than AMPLITUDE and SIGMA is not \"\n\t\t    \"supported for AirSAR data.\\nDefaulting back to \"\n\t\t    \"AMPLITUDE.\\n\");\n    radiometry = r_AMP;\n  }\n\n  airsar_general *general = read_airsar_general(inBaseName);\n\n  // Check for existence of DEMs.\n  // The C-Band DEM is the preferred file for extracting the metadata.\n  // Look for that first. If no DEM is around then error out.\n  if (general->c_cross_data || general->l_cross_data) {\n    sprintf(inFile, \"%s_c.demi2\", inBaseName);\n    if (fileExists(inFile))\n      found_c_dem = TRUE;\n    sprintf(inFile, \"%s_l.demi2\", inBaseName);\n    if (fileExists(inFile))\n      found_l_dem = TRUE;\n    if (!found_c_dem && found_l_dem)\n      asfPrintWarning(\"Could not find C-band DEM.\\nRequired for most reliable \"\n\t\t      \"metadata extraction\\n\");\n    if (!found_c_dem && !found_l_dem)\n      asfPrintError(\"Could not find any DEM.\\nCan't reliably import this \"\n\t\t    \"Airsar data.\\n\");\n  }\n\n  // Check for interferometric data\n  if (general->c_cross_data) {\n    asfPrintStatus(\"\\n   Ingesting C-band cross track interferometric data ...\"\n           \"\\n\\n\");\n    ingest_insar_data(inBaseName, outBaseName, 'c');\n  }\n  if (general->l_cross_data) {\n    asfPrintStatus(\"\\n   Ingesting L-band cross track interferometric data ...\"\n           \"\\n\\n\");\n    ingest_insar_data(inBaseName, outBaseName, 'l');\n  }\n\n  // Kept out the along-track interferometric data for the moment.\n  // Only a few data sets were acquired that way and we have no real way\n  // to verify the results.\n\n  // Check for polarimetric data\n  if (general->c_pol_data) {\n    asfPrintStatus(\"\\n   Ingesting C-band polarimetric data ...\\n\\n\");\n    ingest_polsar_data(inBaseName, outBaseName, radiometry, 'c');\n  }\n  if (general->l_pol_data) {\n    asfPrintStatus(\"\\n   Ingesting L-band polarimetric data ...\\n\\n\");\n    ingest_polsar_data(inBaseName, outBaseName, radiometry, 'l');\n  }\n  if (general->p_pol_data) {\n    asfPrintStatus(\"\\n   Ingesting P-band polarimetric data ...\\n\\n\");\n    ingest_polsar_data(inBaseName, outBaseName, radiometry, 'p');\n  }\n\n  FREE(general);\n}\n\n// The purpose of this code is to refine the values of the along\n// and cross track offsets, so that the meta_get_latLon() value\n// returned at the corners of the image matches what the correct\n// corner lat/lon values are, from the metadata.  Why do we believe\n// the corners locations more than the given along/cross track\n// offsets?  From the data sets we've been looking at, it seems like\n// the corner coords are good, but the offsets aren't...\n\n// We just do a 2-d minimization of the total error (in line/sample\n// space -- not lat/lon (minimizing in lat/lon coords would favor\n// minimizing the lon difference near the poles)) between the\n// corner coordinates.\nstruct fudge_airsar_params {\n        meta_parameters *meta;\n};\n\nstatic int\ngetObjective(const gsl_vector *x, void *params, gsl_vector *f)\n{\n  double c0 = gsl_vector_get(x,0);\n  double s0 = gsl_vector_get(x,1);\n\n  if (!meta_is_valid_double(c0) || !meta_is_valid_double(s0)) {\n    // This does happen sometimes, when we've already found the root\n    return GSL_FAILURE;\n  }\n\n  struct fudge_airsar_params *p = (struct fudge_airsar_params *)params;\n  meta_parameters *meta = p->meta;\n\n  int nl = meta->general->line_count;\n  int ns = meta->general->sample_count;\n\n  double old_c0 = meta->airsar->cross_track_offset;\n  double old_s0 = meta->airsar->along_track_offset;\n  meta->airsar->cross_track_offset = c0;\n  meta->airsar->along_track_offset = s0;\n\n  double line, samp, err = 0.;\n\n  meta_get_lineSamp(meta, meta->location->lat_start_near_range,\n                          meta->location->lon_start_near_range,\n                    0., &line, &samp);\n  err += hypot(line,samp);\n\n  meta_get_lineSamp(meta, meta->location->lat_start_far_range,\n                          meta->location->lon_start_far_range,\n                    0., &line, &samp);\n  err += hypot(line,samp-(double)ns);\n\n  meta_get_lineSamp(meta, meta->location->lat_end_near_range,\n                          meta->location->lon_end_near_range,\n                    0., &line, &samp);\n  err += hypot(line-(double)nl,samp);\n\n  meta_get_lineSamp(meta, meta->location->lat_end_far_range,\n                          meta->location->lon_end_far_range,\n                    0., &line, &samp);\n  err += hypot(line-(double)nl,samp-(double)ns);\n\n  //printf(\"getObjective> [%f,%f] -> %f\\n\", c0, s0, err);\n\n  gsl_vector_set(f,0,err);\n  gsl_vector_set(f,1,err);\n\n  meta->airsar->cross_track_offset = old_c0;\n  meta->airsar->along_track_offset = old_s0;\n\n  return GSL_SUCCESS;\n}\n/*\nstatic void coarse_search(double c0_extent_min, double c0_extent_max,\n                          double s0_extent_min, double s0_extent_max,\n                          double *c0_min, double *s0_min,\n                          meta_parameters *meta)\n{\n    struct fudge_airsar_params params;\n    params.meta = meta;\n\n    double the_min = 9999999;\n    double min_c0=99, min_s0=99;\n    int i,j,k=6;\n    double c0_extent = c0_extent_max - c0_extent_min;\n    double s0_extent = s0_extent_max - s0_extent_min;\n    gsl_vector *v = gsl_vector_alloc(2);\n    gsl_vector *u = gsl_vector_alloc(2);\n    //printf(\"           \");\n    //for (j = 0; j <= k; ++j) {\n    //    double s0 = s0_extent_min + ((double)j)/k*s0_extent;\n    //    printf(\"%9.3f \", s0);\n    //}\n    //printf(\"\\n           \");\n    //for (j = 0; j <= k; ++j)\n    //    printf(\"--------- \");\n    //printf(\"\\n\");\n    for (i = 0; i <= k; ++i) {\n        double c0 = c0_extent_min + ((double)i)/k*c0_extent;\n        //printf(\"%9.3f | \", c0);\n\n        for (j = 0; j <= k; ++j) {\n            double s0 = s0_extent_min + ((double)j)/k*s0_extent;\n\n            gsl_vector_set(v, 0, c0);\n            gsl_vector_set(v, 1, s0);\n            getObjective(v,(void*)(&params), u);\n            double n = gsl_vector_get(u,0);\n            //printf(\"%9.3f \", n);\n            if (n<the_min) {\n                the_min=n;\n                min_c0=gsl_vector_get(v,0);\n                min_s0=gsl_vector_get(v,1);\n            }\n        }\n        //printf(\"\\n\");\n    }\n\n    *c0_min = min_c0;\n    *s0_min = min_s0;\n\n    gsl_vector_free(v);\n    gsl_vector_free(u);\n}\n*/\n/*\nstatic void\ngenerate_start(meta_parameters *meta, double c0, double s0,\n               double *start_c0, double *start_s0)\n{\n    int i;\n\n    double extent_c0_min = -100000. + c0;\n    double extent_c0_max = 100000. + c0;\n\n    double extent_s0_min = -100000. + s0;\n    double extent_s0_max = 100000. + s0;\n\n    double c0_range = extent_c0_max - extent_c0_min;\n    double s0_range = extent_s0_max - extent_s0_min;\n\n    for (i=0; i<12; ++i)\n    //for (i=0; i<4; ++i)\n    {\n        coarse_search(extent_c0_min, extent_c0_max,\n                      extent_s0_min, extent_s0_max,\n                      start_c0, start_s0, meta);\n\n        c0_range /= 3.;\n        s0_range /= 3.;\n\n        extent_c0_min = *start_c0 - c0_range/2.;\n        extent_c0_max = *start_c0 + c0_range/2.;\n\n        extent_s0_min = *start_s0 - s0_range/2.;\n        extent_s0_max = *start_s0 + s0_range/2.;\n\n        //printf(\"refining search to region: cross: (%9.3f,%9.3f)\\n\"\n        //       \"                           along: (%9.3f,%9.3f)\\n\",\n        //       extent_c0_min, extent_c0_max,\n        //       extent_s0_min, extent_s0_max);\n    }\n}\n*/\n/*\nstatic void show_error(meta_parameters *meta, const char *descrip)\n{\n  int nl = meta->general->line_count;\n  int ns = meta->general->sample_count;\n  double line, samp, err=0;\n\n  asfPrintStatus(\"Computing known corner coordinates vs. calculated \"\n                 \"metadata differences:\\n\");\n\n  meta_get_lineSamp(meta, meta->location->lat_start_near_range,\n                          meta->location->lon_start_near_range,\n                    0., &line, &samp);\n  asfPrintStatus(\"  Start Near: %f (%d) %f (%d)\\n\", line, 0, samp, 0);\n  err += hypot(line, samp);\n\n  meta_get_lineSamp(meta, meta->location->lat_start_far_range,\n                          meta->location->lon_start_far_range,\n                    0., &line, &samp);\n  asfPrintStatus(\"  Start Far: %f (%d) %f (%d)\\n\", line, 0, samp, ns);\n  err += hypot(line, samp-(double)ns);\n\n  meta_get_lineSamp(meta, meta->location->lat_end_near_range,\n                          meta->location->lon_end_near_range,\n                    0., &line, &samp);\n  asfPrintStatus(\"  End Near: %f (%d) %f (%d)\\n\", line, nl, samp, 0);\n  err += hypot(line-(double)nl, samp);\n\n  meta_get_lineSamp(meta, meta->location->lat_end_far_range,\n                          meta->location->lon_end_far_range,\n                    0., &line, &samp);\n  asfPrintStatus(\"  End Far: %f (%d) %f (%d)\\n\", line, nl, samp, ns);\n  err += hypot(line-(double)nl, samp-(double)ns);\n\n  asfPrintStatus(\"%s, average corner error: %.2f pixels\\n\", descrip, err/4.);\n}\n*/\n/*\nstatic void fudge_airsar_params(meta_parameters *meta)\n{\n  int status, iter = 0, max_iter = 1000;\n  const gsl_multiroot_fsolver_type *T;\n  gsl_multiroot_fsolver *s;\n  gsl_error_handler_t *prev;\n  struct fudge_airsar_params params;\n  const size_t n = 2;\n  double c0_initial, s0_initial;\n  double out_c0, out_s0;\n\n  params.meta = meta;\n\n  asfPrintStatus(\"Refining airsar cross-track and along-track offsets to \"\n         \"match corner locations.\\n\");\n\n  show_error(meta, \"Prior to airsar geolocation refinement\");\n\n  asfPrintStatus(\"Prior to coarse refinement (original metadata values):\\n\");\n  asfPrintStatus(\"  cross track offset: %.1fm\\n\",\n                 meta->airsar->cross_track_offset);\n  asfPrintStatus(\"  along track offset: %.1fm\\n\",\n                 meta->airsar->along_track_offset);\n  generate_start(meta, meta->airsar->cross_track_offset,\n                 meta->airsar->along_track_offset, &c0_initial, &s0_initial);\n  asfPrintStatus(\"Starting iterative search with:\\n\");\n  asfPrintStatus(\"  cross track offset: %.1fm\\n\", c0_initial);\n  asfPrintStatus(\"  along track offset: %.1fm\\n\", s0_initial);\n\n  gsl_multiroot_function F = {&getObjective, n, &params};\n  gsl_vector *x = gsl_vector_alloc(n);\n\n  gsl_vector_set (x, 0, c0_initial);\n  gsl_vector_set (x, 1, s0_initial);\n\n  T = gsl_multiroot_fsolver_hybrid;\n  s = gsl_multiroot_fsolver_alloc(T, n);\n  gsl_multiroot_fsolver_set(s, &F, x);\n\n  prev = gsl_set_error_handler_off();\n\n  do {\n    ++iter;\n    status = gsl_multiroot_fsolver_iterate(s);\n\n    // abort if stuck\n    if (status) break;\n\n    status = gsl_multiroot_test_residual (s->f, 1e-8);\n  } while (status == GSL_CONTINUE && iter < max_iter);\n\n  // we allow GSL_ENOPROG (not making progress), since often the coarse\n  // search ends up at or very close to the minimum\n  if (status == GSL_SUCCESS || status == GSL_ENOPROG) {\n    asfPrintStatus(\"Converged after %d iteration%s.\\n\",\n                   iter, iter==1 ? \"\" : \"s\");\n    out_c0 = gsl_vector_get(s->x, 0);\n    out_s0 = gsl_vector_get(s->x, 1);\n\n    asfPrintStatus(\"Final values:\\n\");\n    asfPrintStatus(\"  cross track offset: %.1fm [adjusted by %.1fm]\\n\",\n                   out_c0, fabs(out_c0-meta->airsar->cross_track_offset));\n    asfPrintStatus(\"  along track offset: %.1fm [adjusted by %.1fm]\\n\",\n                   out_s0, fabs(out_s0-meta->airsar->along_track_offset));\n\n    meta->airsar->cross_track_offset = out_c0;\n    meta->airsar->along_track_offset = out_s0;\n\n    show_error(meta, \"After airsar geolocation refinement\");\n  }\n  else {\n    asfPrintStatus(\"After %d iterations, failed to converge:\\n  %s\\n\"\n                   \"Metadata parameters left unchanged.\\n\",\n                   iter, gsl_strerror(status));\n    out_c0 = out_s0 = 0;\n  }\n\n  gsl_multiroot_fsolver_free(s);\n  gsl_vector_free(x);\n  gsl_set_error_handler(prev);\n\n}\n*/\n\nvoid read_meta_airsar(char *inBaseName, char *outBaseName)\n{\n  airsar_general *general = read_airsar_general(inBaseName);\n  char *inFile = (char *) MALLOC(sizeof(char)*255);\n  char *outFile = (char *) MALLOC(sizeof(char)*255);\n  airsar_header *header;\n  meta_parameters *meta;\n  int line_offset;\n  \n  if (general->c_cross_data) {\n    sprintf(inFile, \"%s_c.demi2\", inBaseName);\n    if (fileExists(inFile)) {\n      asfPrintStatus(\"C-band DEM ...\\n\");\n      sprintf(outFile, \"%s_c_dem.xml\", outBaseName);\n      meta = import_airsar_meta(inFile, inBaseName, FALSE);\n      meta->general->data_type = REAL32;\n      meta->general->image_data_type = DEM;\n      strcpy(meta->general->bands, \"DEM\");\n      meta_write_xml(meta, outFile);\n      meta_free(meta);\n    }\n    sprintf(inFile, \"%s_c.vvi2\", inBaseName);\n    if (fileExists(inFile)) {\n      asfPrintStatus(\"C-band amplitude image ...\\n\");\n      sprintf(outFile, \"%s_c_vv.xml\", outBaseName);\n      meta = import_airsar_meta(inFile, inBaseName, FALSE);\n      meta->general->data_type = REAL32;\n      meta->general->image_data_type = AMPLITUDE_IMAGE;\n      strcpy(meta->general->bands, \"AMP\");\n      meta_write_xml(meta, outFile);\n      meta_free(meta);\n    }\n    sprintf(inFile, \"%s_c.corgr\", inBaseName);\n    if (fileExists(inFile)) {\n      asfPrintStatus(\"C-band coherence image ...\\n\");\n      sprintf(outFile, \"%s_c_coh.xml\", outBaseName);\n      meta = import_airsar_meta(inFile, inBaseName, FALSE);\n      meta->general->data_type = REAL32;\n      meta->general->image_data_type = COHERENCE_IMAGE;\n      strcpy(meta->general->bands, \"COH\");\n      meta_write_xml(meta, outFile);\n      meta_free(meta);\n    }\n  }\n  if (general->l_cross_data) {\n    sprintf(inFile, \"%s_l.demi2\", inBaseName);\n    if (fileExists(inFile)) {\n      asfPrintStatus(\"L-band DEM ...\\n\");\n      sprintf(outFile, \"%s_l_dem.xml\", outBaseName);\n      meta = import_airsar_meta(inFile, inBaseName, FALSE);\n      meta->general->data_type = REAL32;\n      meta->general->image_data_type = DEM;\n      strcpy(meta->general->bands, \"DEM\");\n      meta_write_xml(meta, outFile);\n      meta_free(meta);\n    }\n    sprintf(inFile, \"%s_l.vvi2\", inBaseName);\n    if (fileExists(inFile)) {\n      asfPrintStatus(\"L-band amplitude image ...\\n\");\n      sprintf(outFile, \"%s_l_vv.xml\", outBaseName);\n      meta = import_airsar_meta(inFile, inBaseName, FALSE);\n      meta->general->data_type = REAL32;\n      meta->general->image_data_type = AMPLITUDE_IMAGE;\n      strcpy(meta->general->bands, \"AMP\");\n      meta_write_xml(meta, outFile);\n      meta_free(meta);\n    }\n    sprintf(inFile, \"%s_l.corgr\", inBaseName);\n    if (fileExists(inFile)) {\n      asfPrintStatus(\"L-band coherence image ...\\n\");\n      sprintf(outFile, \"%s_l_coh.xml\", outBaseName);\n      meta = import_airsar_meta(inFile, inBaseName, FALSE);\n      meta->general->data_type = REAL32;\n      meta->general->image_data_type = COHERENCE_IMAGE;\n      strcpy(meta->general->bands, \"COH\");\n      meta_write_xml(meta, outFile);\n      meta_free(meta);\n    }\n  }\n  if (general->c_pol_data) {\n    sprintf(inFile, \"%s_c.datgr\", inBaseName);\n    if (!fileExists(inFile))\n      sprintf(inFile, \"%s_c.dat\", inBaseName);\n    if (fileExists(inFile)) {\n      asfPrintStatus(\"C-band polarimetric data set ...\\n\");\n      meta = import_airsar_meta(inFile, inBaseName, FALSE);\n      meta->general->data_type = REAL32;\n      meta->general->image_data_type = POLARIMETRIC_IMAGE;\n      meta->general->band_count = 9;\n      strcpy(meta->general->bands,\n\t     \"AMP,AMP_HH,PHASE_HH,AMP_HV,PHASE_HV,AMP_VH,PHASE_VH,\"\t\\\n\t     \"AMP_VV,PHASE_VV\");\n      sprintf(outFile, \"%s_c.xml\", outBaseName);\n      meta_write_xml(meta, outFile);\n      meta_free(meta);\n    }      \n  }\n  if (general->l_pol_data) {\n    sprintf(inFile, \"%s_l.datgr\", inBaseName);\n    if (!fileExists(inFile))\n      sprintf(inFile, \"%s_l.dat\", inBaseName);\n    if (fileExists(inFile)) {\n      asfPrintStatus(\"L-band polarimetric data set ...\\n\");\n      meta = import_airsar_meta(inFile, inBaseName, FALSE);\n      meta->general->data_type = REAL32;\n      meta->general->image_data_type = POLARIMETRIC_IMAGE;\n      meta->general->band_count = 9;\n      strcpy(meta->general->bands,\n\t     \"AMP,AMP_HH,PHASE_HH,AMP_HV,PHASE_HV,AMP_VH,PHASE_VH,\"\t\\\n\t     \"AMP_VV,PHASE_VV\");\n      sprintf(outFile, \"%s_l.xml\", outBaseName);\n      meta_write_xml(meta, outFile);\n      meta_free(meta);\n    }      \n  }\n  if (general->p_pol_data) {\n    sprintf(inFile, \"%s_p.datgr\", inBaseName);\n    if (!fileExists(inFile))\n      sprintf(inFile, \"%s_p.dat\", inBaseName);\n    if (fileExists(inFile)) {\n      asfPrintStatus(\"P-band polarimetric data set ...\\n\");\n      meta = import_airsar_meta(inFile, inBaseName, FALSE);\n      meta->general->data_type = REAL32;\n      meta->general->image_data_type = POLARIMETRIC_IMAGE;\n      meta->general->band_count = 9;\n      strcpy(meta->general->bands,\n\t     \"AMP,AMP_HH,PHASE_HH,AMP_HV,PHASE_HV,AMP_VH,PHASE_VH,\"\t\\\n\t     \"AMP_VV,PHASE_VV\");\n      sprintf(outFile, \"%s_p.xml\", outBaseName);\n      meta_write_xml(meta, outFile);\n      meta_free(meta);\n    }      \n  }\n\n  FREE(general);\n}\n", "meta": {"hexsha": "b6bdadc179b72e7f484c521e4405a1f74ca1e67f", "size": 49356, "ext": "c", "lang": "C", "max_stars_repo_path": "src/libasf_import/import_airsar.c", "max_stars_repo_name": "glshort/MapReady", "max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z", "max_issues_repo_path": "src/libasf_import/import_airsar.c", "max_issues_repo_name": "glshort/MapReady", "max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libasf_import/import_airsar.c", "max_forks_repo_name": "glshort/MapReady", "max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z", "avg_line_length": 36.5059171598, "max_line_length": 83, "alphanum_fraction": 0.6456763109, "num_tokens": 14858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3007455664065234, "lm_q2_score": 0.02128735280242586, "lm_q1q2_score": 0.006402076975861058}}
{"text": "#include <gsl/gsl_errno.h>\n#include <gsl/block/gsl_block.h>\n\n#define BASE_DOUBLE\n#include <gsl/templates_on.h>\n#include <gsl/block/block_source.c>\n#include <gsl/templates_off.h>\n#undef BASE_DOUBLE\n\n", "meta": {"hexsha": "493c63d6ccfff66c9b1dd9369adb0ada32166fd9", "size": 198, "ext": "c", "lang": "C", "max_stars_repo_path": "Cartwheel/cartwheel-3d/gsl/block/block.c", "max_stars_repo_name": "MontyThibault/centre-of-mass-awareness", "max_stars_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Cartwheel/cartwheel-3d/gsl/block/block.c", "max_issues_repo_name": "MontyThibault/centre-of-mass-awareness", "max_issues_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cartwheel/cartwheel-3d/gsl/block/block.c", "max_forks_repo_name": "MontyThibault/centre-of-mass-awareness", "max_forks_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.8, "max_line_length": 35, "alphanum_fraction": 0.7727272727, "num_tokens": 52, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30074559147595986, "lm_q2_score": 0.021287350706862853, "lm_q1q2_score": 0.006402076879291661}}
{"text": "#ifndef PLV_DAL_BLOCKCHAIN_STORAGE_H\n#define PLV_DAL_BLOCKCHAIN_STORAGE_H\n\n#include <plv/io/file.h>\n#include <plv/serializers/netstring.h>\n#include <gsl/gsl_assert>\n#include <memory>\n#include <vector>\n#include \"chunkiterator.h\"\n#include \"metablock.h\"\n#include \"storage.h\"\n\nnamespace plv::dal\n{\nclass BlockchainStorage : public Storage\n{\npublic:\n    BlockchainStorage(std::shared_ptr<ChunkIterator> chunkIter, std::shared_ptr<io::File> file)\n        : file_(file), chunkIterator_(chunkIter)\n    {\n    }\n\n    auto indexStorage() -> void override\n    {\n        using namespace serializers::netstring;\n        metaBlocks_.clear();\n        auto chunkOpt = chunkIterator_->getNext();\n        while (chunkOpt.has_value())\n        {\n            uint32_t objectIdx = 0;\n            do\n            {\n                auto chunk                     = chunkOpt->getData().substr(objectIdx);\n                auto [blockStart, blockLength] = decodeOffsetAndLength(chunk);\n                metaBlocks_.emplace_back(chunkOpt->getOffset() + objectIdx + blockStart, blockLength);\n                objectIdx += calculateOffsetOfNextObject(blockStart, blockLength);\n            } while (objectIdx < chunkOpt->getChunkSize() - 1);\n            chunkOpt = chunkIterator_->getNext();\n        }\n    }\n\n    auto getBlock(Id id) -> Buffer override\n    {\n        Expects(id < metaBlocks_.size());\n        auto metaBlock = metaBlocks_[id];\n        Buffer buffer(metaBlock.blockSize, 0);\n        file_->read(buffer, metaBlock.blockOffset, metaBlock.blockSize);\n        return buffer;\n    }\n\n    auto addBlock(BufferView block) -> void override\n    {\n        using namespace serializers::netstring;\n        auto blockSerialized           = encode(block);\n        auto [blockStart, blockLength] = decodeOffsetAndLength(blockSerialized);\n        metaBlocks_.emplace_back(file_->getSize() + blockStart, blockLength);\n        file_->write(blockSerialized);\n    }\n    /*\n        auto getBlock(const datamodel::MetaBlock& metaBlock) -> datamodel::Block\n        {\n            datamodel::Block block{};\n            Buffer buffer(metaBlock.blockSize, 0);\n            file_->read(buffer, metaBlock.blockOffset, metaBlock.blockSize);\n            auto [hash, consumed] = netstring::decode(buffer);\n            std::copy(std::begin(hash), std::end(hash), block.prevBlockHash.data());\n            auto remaining = metaBlock.blockSize - consumed;\n            while (remaining > 0)\n            {\n                auto nextData                  = buffer.substr(consumed, remaining);\n                auto [dataElement, consumedDE] = netstring::decode(nextData);\n                block.dataElements.emplace_back(dataElement);\n                remaining -= consumedDE;\n                consumed += consumedDE;\n            }\n            return block;\n        }\n\n        auto getBlockPrevHash(const datamodel::MetaBlock& metaBlock) -> datamodel::Block\n        {\n            datamodel::Block block{};\n            Buffer buffer(metaBlock.blockSize, 0);\n            file_->read(buffer, metaBlock.blockOffset, metaBlock.blockSize);\n            auto [hash, consumed] = netstring::decode(buffer);\n            std::copy(std::begin(hash), std::end(hash), block.prevBlockHash.data());\n            auto remaining = metaBlock.blockSize - consumed;\n            while (remaining > 0)\n            {\n                auto nextData                  = buffer.substr(consumed, remaining);\n                auto [dataElement, consumedDE] = netstring::decode(nextData);\n                block.dataElements.emplace_back(dataElement);\n                remaining -= consumedDE;\n                consumed += consumedDE;\n            }\n            return block;\n        }\n    */\n    auto getChainLength() -> Size override\n    {\n        return metaBlocks_.size();\n    }\n\n    auto getStorageSize() -> Size override\n    {\n        return file_->getSize();\n    }\n\n    auto isIndexed() -> bool override\n    {\n        return !(metaBlocks_.size() == 0 && file_->getSize() != 0);\n    }\n\nprivate:\n    std::shared_ptr<io::File> file_{};\n    std::shared_ptr<ChunkIterator> chunkIterator_{};\n    std::vector<dal::MetaBlock> metaBlocks_{};\n    bool indexed_{false};\n};\n}  // namespace plv::dal\n#endif  // PLV_DAL_BLOCKCHAIN_STORAGE_H", "meta": {"hexsha": "9f80b5f16f620d70493465c35336e40cb82493f7", "size": 4228, "ext": "h", "lang": "C", "max_stars_repo_path": "plv/dal/blockchainstorage.h", "max_stars_repo_name": "tymion/blockchain", "max_stars_repo_head_hexsha": "929c8f895182b180f27e3191c9090eb42f55b801", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "plv/dal/blockchainstorage.h", "max_issues_repo_name": "tymion/blockchain", "max_issues_repo_head_hexsha": "929c8f895182b180f27e3191c9090eb42f55b801", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "plv/dal/blockchainstorage.h", "max_forks_repo_name": "tymion/blockchain", "max_forks_repo_head_hexsha": "929c8f895182b180f27e3191c9090eb42f55b801", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2333333333, "max_line_length": 102, "alphanum_fraction": 0.5979186377, "num_tokens": 920, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.27825678173200435, "lm_q2_score": 0.022977367693815597, "lm_q1q2_score": 0.006393608387154055}}
{"text": "/************************************************************************\n Dataset.h.h - Copyright marcello\n\n Here you can write a license for your code, some comments or any other\n information you want to have in your generated code. To to this simply\n configure the \"headings\" directory in uml to point to a directory\n where you have your heading files.\n\n or you can just replace the contents of this file with your own.\n If you want to do this, this file is located at\n\n /usr/share/apps/umbrello/headings/heading.h\n\n -->Code Generators searches for heading files based on the file extension\n i.e. it will look for a file name ending in \".h\" to include in C++ header\n files, and for a file name ending in \".java\" to include in all generated\n java code.\n If you name the file \"heading.<extension>\", Code Generator will always\n choose this file even if there are other files with the same extension in the\n directory. If you name the file something else, it must be the only one with that\n extension in the directory to guarantee that Code Generator will choose it.\n\n you can use variables in your heading files which are replaced at generation\n time. possible variables are : author, date, time, filename and filepath.\n just write %variable_name%\n\n This file was generated on Sat Nov 10 2007 at 15:05:38\n The original location of this file is /home/marcello/Projects/fitted/Developing/Dataset.h\n **************************************************************************/\n\n#ifndef DATASET_H\n#define DATASET_H\n\n#include <vector>\n#include <set>\n#include <map>\n\n//#include <gsl/gsl_matrix.h>\n\n#include \"Sample.h\"\n\n//<< Sam\nnamespace PoliFitted\n{\n\ntypedef enum\n{\n  OVERWRITE,\n  APPEND\n} ModalityType;\ntypedef enum\n{\n  EUCLIDEAN,\n  MANHATTAN,\n  MAHALANOBIS\n} MetricType;\n\n/**\n * Represents an in-memory cache of numeric data.\n * A Dataset is nothing more than what its name implies: a set of data.\n * Since each data is a sample, the dataset can be split into input and\n * output data. In contrast with the Sample class, the\n * dataset stores the information related to the dimension of the input and output\n * tuples.\n *\n * Advanced features include iterator, random subsampling, normalization,\n * statistical data, import and export.\n *\n * @brief In-memory cache of numeric data.\n */\nclass Dataset: public vector<Sample*>\n{\n  public:\n\n    // Constructors/Destructors\n    //\n\n    /**\n     * Empty Constructor\n     */\n    Dataset(unsigned int input_size = 1, unsigned int output_size = 1);\n\n    /**\n     * Empty Destructor\n     */\n    virtual ~Dataset();\n\n    /**\n     * Destroys the content of the dataset but not the dataset itself.\n     *\n     * The input data of each sample are destroyed only if \\a clear_input\n     * is set to true.\n     *\n     * @brief Clear tuple\n     * @param clear_input If true the input data are destrayed, false otherwise.\n     */\n    void Clear(bool clear_input = false);\n\n    /**\n     * @brief Set input data dimension\n     * @param size The dimension of the input data.\n     */\n    void SetInputSize(unsigned int size);\n\n    /**\n     * @brief Set output data dimension\n     * @param size The dimension of the output data.\n     */\n    void SetOutputSize(unsigned int size);\n\n    /**\n     * @brief Return the input dimension.\n     * @return The dimension of the input component of each sample.\n     */\n    unsigned int GetInputSize();\n\n    /**\n     * @brief Return the output dimension.\n     * @return The dimension of the output component of each sample.\n     */\n    unsigned int GetOutputSize();\n\n    /**\n     * Adds a new element at the end of the dataset, after its current last element.\n     * This effectively increases the container size by one, which causes an automatic\n     * allocation of a new samples initialized with the given input and output tuples.\n     *\n     * @brief Add element at the end.\n     * @param input The input tuple to be added.\n     * @param output The output tuple to be added.\n     */\n    void AddSample(Tuple* input, Tuple* output);\n\n    /**\n     * Returns a pointer to a newly created memory array storing\n     * the elements of the dataset.\n     * Data are stored linearly in the new array \\f$A\\f$. For any\n     * sample in the dataset, input elements are stored before\n     * output elements. As a consequence the dimension of the\n     * array \\f$A\\f$ is \\f$n_{el} * (input_dim + output_dim)\\f$.\n     * \\f[ A = {input_i(1),\\dots,input_i(m), output_i(1),\\dots,output_i(n)}_{i=0}^{n_{el}-1}\\f]\n     *\n     * @brief Get a copy of the elements.\n     * @return A reference to the first element of an array storing\n     * the dataset elements\n     */\n    //double* GetMatrix();\n    /**\n     * Returns a pointer to a newly created GSL matrix storing\n     * the elements of the dataset. Each row represents a sample\n     * of the dataset. For any\n     * sample in the dataset, input elements are stored before\n     * output elements. As a consequence the dimension of the\n     * array \\f$A\\f$ is \\f$n_{el} \\times (input_dim + output_dim)\\f$.\n     * The element M(i,j) corresponds to the i-th sample of the dataset,\n     * if j is less then input_dimension corresponds to the j-th element\n     * of the input tuple. If j is greater or equal than the input_dimension,\n     * M(i,j) corresponds to the (j-input_dimension) element of the output\n     * tuple.\n     *\n     * @brief Get a copy of the elements.\n     * @return A GSL matrix storing the dataset elements\n     */\n    //gsl_matrix* GetGSLMatrix();\n    /**\n     *\n     */\n    //gsl_matrix* GetCovarianceMatrix();\n    /**\n     * Clone the current instance filling the new dataset with\n     * a clone of each sample. This function performs a deep copy.\n     *\n     * @brief Clone object\n     * @return A newly created dataset.\n     *\n     * @see Sample::Clone\n     */\n    Dataset* Clone();\n\n    /**\n     * @brief Resize the output tuple of each sample\n     * @param new_size the new size of the output tuple\n     */\n    void ResizeOutput(unsigned int new_size);\n\n    /**\n     *\n     */\n    Dataset* GetReducedDataset(unsigned int size, bool random = false);\n\n    /**\n     *\n     */\n    Dataset* GetReducedDataset(float proportion, bool random = false);\n\n    /**\n     *\n     */\n    void GetTrainAndTestDataset(unsigned int num_partitions, unsigned int partition,\n        Dataset* train_ds, Dataset* test_ds);\n\n    /**\n     *\n     */\n    vector<Dataset*> SplitDataset(unsigned int parts);\n\n    /**\n     *\n     */\n    map<float, Dataset*> SplitByAttribute(unsigned int attribute);\n\n    /**\n     *\n     */\n    Dataset* ExtractNewDataset(set<unsigned int> inputs, set<unsigned int> outputs);\n\n    /**\n     *\n     */\n    Sample* GetNearestNeighbor(Tuple& input, MetricType metric = EUCLIDEAN);\n\n    /**\n     *\n     */\n    void Save(string filename, ModalityType modality = OVERWRITE);\n\n    /**\n     *\n     */\n    void Load(string filename);\n\n    /**\n     *\n     */\n    Dataset* NormalizeMinMax(vector<pair<float, float> >& input_parameters,\n        vector<pair<float, float> >& output_parameters);\n\n    /**\n     *\n     */\n    Dataset* NormalizeOutputMinMax(vector<pair<float, float> >& output_parameters);\n\n    /**\n     * @brief Mean of the first output element.\n     * @return The mean value of the first output element.\n     */\n    float Mean();\n\n    /**\n     * @brief Variance of the first output element.\n     * @return The variance value of the first output element.\n     */\n    float Variance();\n\n    /**\n     * Insert a formatted representation of the dataset into the given output stream.\n     *\n     * @brief Insert formatted output\n     * @param out Output stream object where characters are inserted.\n     * @param ds Dataset to be printed out\n     * @return The reference to the stream it receives\n     */\n    friend ofstream& operator<<(ofstream& out, PoliFitted::Dataset& ds);\n\n    /**\n     * Extract formatted input from the stream and fill the dataset\n     * accordingly to that information.\n     *\n     * @brief Extract formatted input\n     * @param in Input stream object from which characters are extracted.\n     * @param ds where the extracted information are stored.\n     * @return The reference to the stream it receives\n     */\n    friend ifstream& operator>>(ifstream& in, PoliFitted::Dataset& ds);\n\n  protected:\n\n  private:\n    unsigned int mInputSize;\n    unsigned int mOutputSize;\n    float mMean;\n    float mVariance;\n\n    /**\n     * @brief Compute mean and variance of the first output element.\n     */\n    void ComputeMeanVariance();\n\n};\n\ninline void Dataset::SetInputSize(unsigned int size)\n{\n  mInputSize = size;\n}\n\ninline void Dataset::SetOutputSize(unsigned int size)\n{\n  mOutputSize = size;\n}\n\ninline unsigned int Dataset::GetInputSize()\n{\n  return mInputSize;\n}\n\ninline unsigned int Dataset::GetOutputSize()\n{\n  return mOutputSize;\n}\n\ninline void Dataset::AddSample(Tuple* input, Tuple* output)\n{\n  push_back(new Sample(input, output));\n}\n\ninline void Dataset::Save(string filename, ModalityType modality)\n{\n  ofstream log_file;\n  if (modality == OVERWRITE)\n  {\n    log_file.open(filename.c_str(), ios::out);\n  }\n  else\n  {\n    log_file.open(filename.c_str(), ios::out | ios::app);\n  }\n  if (log_file.is_open())\n  {\n    log_file << *(this);\n  }\n  log_file.close();\n}\n\ninline void Dataset::Load(string filename)\n{\n  ifstream log_file;\n  log_file.open(filename.c_str(), ios::in);\n  log_file >> *(this);\n  log_file.close();\n}\n\n}\n\n#endif // DATASET_H\n", "meta": {"hexsha": "dff57ca3f643ebed7a49825c098d15bbd04fe0fe", "size": 9386, "ext": "h", "lang": "C", "max_stars_repo_path": "cpp_models/libsrc/RLLib/util/TreeFitted/Dataset.h", "max_stars_repo_name": "akangasr/sdirl", "max_stars_repo_head_hexsha": "b8b2bf34fea1b1f0c2f9961a9ad9c1ad34396f5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp_models/libsrc/RLLib/util/TreeFitted/Dataset.h", "max_issues_repo_name": "akangasr/sdirl", "max_issues_repo_head_hexsha": "b8b2bf34fea1b1f0c2f9961a9ad9c1ad34396f5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp_models/libsrc/RLLib/util/TreeFitted/Dataset.h", "max_forks_repo_name": "akangasr/sdirl", "max_forks_repo_head_hexsha": "b8b2bf34fea1b1f0c2f9961a9ad9c1ad34396f5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2057971014, "max_line_length": 95, "alphanum_fraction": 0.6517153207, "num_tokens": 2189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2538610069692489, "lm_q2_score": 0.02517884005474028, "lm_q1q2_score": 0.006391925690614026}}
{"text": "/****************************************************************************\n *                                                                          *\n *  Author : lukasz.iwaszkiewicz@gmail.com                                  *\n *  ~~~~~~~~                                                                *\n *  License : see COPYING file for details.                                 *\n *  ~~~~~~~~~                                                               *\n ****************************************************************************/\n\n#pragma once\n#include \"Condition.h\"\n#include <gsl/gsl>\n\n/**\n * Sequence is like AndCondition, but inputs must fulfill conditions in order.\n */\ntemplate <typename EventT = LIB_STATE_MACHINE_DEFAULT_EVENT_TYPE> class SequenceCondition : public Condition<EventT> {\npublic:\n        using EventType = EventT;\n\n        SequenceCondition (Condition<EventT> *a, Condition<EventT> *b) : a (a), b (b) {}\n        virtual ~SequenceCondition () = default;\n\n        bool getResult () const override { return a->getResult () && b->getResult (); }\n        void reset () override\n        {\n                a->reset ();\n                b->reset ();\n        }\n\n        bool check (EventType  &event, EventType &retainedEvent) const override\n        {\n                if (!a->getResult ()) {\n                        a->check (event, retainedEvent);\n                }\n\n                if (a->getResult () && !b->getResult ()) {\n                        b->check (event, retainedEvent);\n                }\n\n                return getResult ();\n        }\n\nprivate:\n        gsl::not_null <Condition<EventType>*> a;\n        gsl::not_null <Condition<EventType>*> b;\n};\n\ntemplate <typename EventT = LIB_STATE_MACHINE_DEFAULT_EVENT_TYPE> SequenceCondition<EventT> *seq (Condition<EventT> *a, Condition<EventT> *b)\n{\n        return new SequenceCondition<EventT> (a, b);\n}\n\n", "meta": {"hexsha": "27318c6a3ceed87547d9b973ff28cbba91aba217", "size": 1890, "ext": "h", "lang": "C", "max_stars_repo_path": "src/SequenceCondition.h", "max_stars_repo_name": "iwasz/libstatemachine", "max_stars_repo_head_hexsha": "6e6accc3085bd2d5ea130665a9618b16fea38980", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SequenceCondition.h", "max_issues_repo_name": "iwasz/libstatemachine", "max_issues_repo_head_hexsha": "6e6accc3085bd2d5ea130665a9618b16fea38980", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SequenceCondition.h", "max_forks_repo_name": "iwasz/libstatemachine", "max_forks_repo_head_hexsha": "6e6accc3085bd2d5ea130665a9618b16fea38980", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.6603773585, "max_line_length": 141, "alphanum_fraction": 0.4391534392, "num_tokens": 337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21469141911224193, "lm_q2_score": 0.029760091149257793, "lm_q1q2_score": 0.006389236201743826}}
{"text": "/* err/strerror.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <gsl/gsl_errno.h>\n\nconst char *\ngsl_strerror (const int gsl_errno)\n{\n  switch (gsl_errno)\n    {\n    case GSL_SUCCESS:\n      return \"success\" ;\n    case GSL_FAILURE:\n      return \"failure\" ;\n    case GSL_CONTINUE:\n      return \"the iteration has not converged yet\";\n    case GSL_EDOM:\n      return \"input domain error\" ;\n    case GSL_ERANGE:\n      return \"output range error\" ;\n    case GSL_EFAULT:\n      return \"invalid pointer\" ;\n    case GSL_EINVAL:\n      return \"invalid argument supplied by user\" ;\n    case GSL_EFAILED:\n      return \"generic failure\" ;\n    case GSL_EFACTOR:\n      return \"factorization failed\" ;\n    case GSL_ESANITY:\n      return \"sanity check failed - shouldn't happen\" ;\n    case GSL_ENOMEM:\n      return \"malloc failed\" ;\n    case GSL_EBADFUNC:\n      return \"problem with user-supplied function\";\n    case GSL_ERUNAWAY:\n      return \"iterative process is out of control\";\n    case GSL_EMAXITER:\n      return \"exceeded max number of iterations\" ;\n    case GSL_EZERODIV:\n      return \"tried to divide by zero\" ;\n    case GSL_EBADTOL:\n      return \"specified tolerance is invalid or theoretically unattainable\" ;\n    case GSL_ETOL:\n      return \"failed to reach the specified tolerance\" ;\n    case GSL_EUNDRFLW:\n      return \"underflow\" ;\n    case GSL_EOVRFLW:\n      return \"overflow\" ;\n    case GSL_ELOSS:\n      return \"loss of accuracy\" ;\n    case GSL_EROUND:\n      return \"roundoff error\" ;\n    case GSL_EBADLEN:\n      return \"matrix/vector sizes are not conformant\" ;\n    case GSL_ENOTSQR:\n      return \"matrix not square\" ;\n    case GSL_ESING:\n      return \"singularity or extremely bad function behavior detected\" ;\n    case GSL_EDIVERGE:\n      return \"integral or series is divergent\" ;\n    case GSL_EUNSUP:\n      return \"the required feature is not supported by this hardware platform\";\n    case GSL_EUNIMPL:\n      return \"the requested feature is not (yet) implemented\";\n    case GSL_ECACHE:\n      return \"cache limit exceeded\";\n    case GSL_ETABLE:\n      return \"table limit exceeded\";\n    case GSL_ENOPROG:\n      return \"iteration is not making progress towards solution\";\n    case GSL_ENOPROGJ:\n      return \"jacobian evaluations are not improving the solution\";\n    case GSL_ETOLF:\n      return \"cannot reach the specified tolerance in F\";\n    case GSL_ETOLX:\n      return \"cannot reach the specified tolerance in X\";\n    case GSL_ETOLG:\n      return \"cannot reach the specified tolerance in gradient\";\n    case GSL_EOF:\n      return \"end of file\";\n    default:\n      return \"unknown error code\" ;\n    }\n}\n", "meta": {"hexsha": "49f57c04f05aa3b20b13a34e4f2eac1fb9d51602", "size": 3396, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/err/strerror.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/err/strerror.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/err/strerror.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 33.2941176471, "max_line_length": 81, "alphanum_fraction": 0.6878680801, "num_tokens": 830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21733752104706247, "lm_q2_score": 0.029312228207457856, "lm_q1q2_score": 0.00637064701497467}}
{"text": "#pragma once\n\n#include \"BoundingVolume.h\"\n#include \"Library.h\"\n#include \"TileContentLoadResult.h\"\n#include \"TileContentLoader.h\"\n#include \"TileID.h\"\n#include \"TileRefine.h\"\n\n#include <CesiumAsync/AsyncSystem.h>\n#include <CesiumAsync/Future.h>\n#include <CesiumAsync/HttpHeaders.h>\n#include <CesiumAsync/IAssetAccessor.h>\n#include <CesiumGltfReader/GltfReader.h>\n\n#include <glm/mat4x4.hpp>\n#include <gsl/span>\n#include <spdlog/fwd.h>\n\n#include <cstddef>\n#include <optional>\n\nnamespace CesiumGeospatial {\nclass GlobeRectangle;\n}\n\nnamespace Cesium3DTilesSelection {\n\nclass Tileset;\n\n/**\n * @brief Creates {@link TileContentLoadResult} from glTF data.\n */\nclass CESIUM3DTILESSELECTION_API GltfContent final : public TileContentLoader {\npublic:\n  /**\n   * @copydoc TileContentLoader::load\n   *\n   * The result will only contain the `model`. Other fields will be\n   * empty or have default values.\n   */\n  CesiumAsync::Future<std::unique_ptr<TileContentLoadResult>>\n  load(const TileContentLoadInput& input) override;\n\n  /**\n   * @brief Create a {@link TileContentLoadResult} from the given data.\n   *\n   * (Only public to be called from `Batched3DModelContent`)\n   *\n   * @param asyncSystem The async system to use for requesting any external\n   * content.\n   * @param pLogger Only used for logging\n   * @param url The URL, only used for logging\n   * @param headers The http headers to use for resolving any external content.\n   * @param pAssetAccessor The asset accessor to use to resolve external\n   * content.\n   * @param data The actual glTF data\n   * @param contentOptions The content options for loading this glTF.\n   * @return The {@link TileContentLoadResult}\n   */\n  static CesiumAsync::Future<std::unique_ptr<TileContentLoadResult>> load(\n      const CesiumAsync::AsyncSystem& asyncSystem,\n      const std::shared_ptr<spdlog::logger>& pLogger,\n      const std::string& url,\n      const CesiumAsync::HttpHeaders& headers,\n      const std::shared_ptr<CesiumAsync::IAssetAccessor>& pAssetAccessor,\n      const gsl::span<const std::byte>& data,\n      const TilesetContentOptions& contentOptions);\n\n  /**\n   * @brief Creates texture coordinates for mapping {@link RasterOverlay} tiles\n   * to {@link Tileset} tiles.\n   *\n   * Generates new texture coordinates for the `gltf` using the given\n   * `projections`. The first new texture coordinate (`u` or `s`) will be 0.0 at\n   * the `minimumX` of the given `rectangle` and 1.0 at the `maximumX`. The\n   * second texture coordinate (`v` or `t`) will be 0.0 at the `minimumY` of\n   * the given `rectangle` and 1.0 at the `maximumY`.\n   *\n   * Coordinate values for vertices in between these extremes are determined by\n   * projecting the vertex position with the `projection` and then computing the\n   * fractional distance of that projected position between the minimum and\n   * maximum.\n   *\n   * Projected positions that fall outside the `globeRectangle` will be clamped\n   * to the edges, so the coordinate values will never be less then 0.0 or\n   * greater than 1.0.\n   *\n   * These texture coordinates are stored in the provided glTF, and a new\n   * primitive attribute named `_CESIUMOVERLAY_n` is added to each primitive,\n   * where `n` starts with the `firstTextureCoordinateID` passed to this\n   * function and increases with each projection.\n   *\n   * @param gltf The glTF model.\n   * @param modelToEcefTransform The transformation of this glTF to ECEF\n   * coordinates.\n   * @param firstTextureCoordinateID The texture coordinate ID of the first\n   * projection.\n   * @param globeRectangle The rectangle that all projected vertex positions are\n   * expected to lie within. If this parameter is std::nullopt, it is computed\n   * from the vertices.\n   * @param projections The projections for which to generate texture\n   * coordinates. There is a linear relationship between the coordinates of this\n   * projection and the generated texture coordinates.\n   * @return The detailed of the generated texture coordinates.\n   */\n  static std::optional<TileContentDetailsForOverlays>\n  createRasterOverlayTextureCoordinates(\n      CesiumGltf::Model& gltf,\n      const glm::dmat4& modelToEcefTransform,\n      int32_t firstTextureCoordinateID,\n      const std::optional<CesiumGeospatial::GlobeRectangle>& globeRectangle,\n      std::vector<CesiumGeospatial::Projection>&& projections);\n\n  /**\n   * @brief Computes a bounding region from the vertex positions in a glTF\n   * model.\n   *\n   * If the glTF model spans the anti-meridian, the west and east longitude\n   * values will be in the usual -PI to PI range, but east will have a smaller\n   * value than west.\n   *\n   * @param gltf The model.\n   * @param transform The transform from model coordinates to ECEF coordinates.\n   * @return The computed bounding region.\n   */\n  static CesiumGeospatial::BoundingRegion computeBoundingRegion(\n      const CesiumGltf::Model& gltf,\n      const glm::dmat4& transform);\n\n  /**\n   * @brief Applies the glTF's RTC_CENTER, if any, to the given rootTransform.\n   *\n   * @param gltf\n   * @param rootTransform\n   * @return glm::dmat4x4\n   */\n\n  /**\n   * @brief Applies the glTF's RTC_CENTER, if any, to the given transform.\n   *\n   * If the glTF has a `CESIUM_RTC` extension, this function will multiply the\n   * given matrix with the (translation) matrix that is created from the\n   * `RTC_CENTER` in the. If the given model does not have this extension, then\n   * this function will return the `rootTransform` unchanged.\n   *\n   * @param model The glTF model\n   * @param rootTransform The matrix that will be multiplied with the transform\n   * @return The result of multiplying the `RTC_CENTER` with the\n   * `rootTransform`.\n   */\n  static glm::dmat4x4 applyRtcCenter(\n      const CesiumGltf::Model& gltf,\n      const glm::dmat4x4& rootTransform);\n\n  /**\n   * @brief Applies the glTF's `gltfUpAxis`, if any, to the given transform.\n   *\n   * By default, the up-axis of a glTF model will the the Y-axis.\n   *\n   * If the tileset that contained the model had the `asset.gltfUpAxis` string\n   * property, then the information about the up-axis has been stored in as a\n   * number property called `gltfUpAxis` in the `extras` of the given model.\n   *\n   * Depending on whether this value is `CesiumGeometry::Axis::X`, `Y`, or `Z`,\n   * the given matrix will be multiplied with a matrix that converts the\n   * respective axis to be the Z-axis, as required by the 3D Tiles standard.\n   *\n   * @param model The glTF model\n   * @param rootTransform The matrix that will be multiplied with the transform\n   * @return The result of multiplying the `rootTransform` with the\n   * `gltfUpAxis`.\n   */\n  static glm::dmat4x4 applyGltfUpAxisTransform(\n      const CesiumGltf::Model& model,\n      const glm::dmat4x4& rootTransform);\n\nprivate:\n  static CesiumGltfReader::GltfReader _gltfReader;\n};\n\n} // namespace Cesium3DTilesSelection\n", "meta": {"hexsha": "4d00aa989da2245d8d1d14a50aa38fb83d7b6d91", "size": 6854, "ext": "h", "lang": "C", "max_stars_repo_path": "Cesium3DTilesSelection/include/Cesium3DTilesSelection/GltfContent.h", "max_stars_repo_name": "yieryi/cesium-native", "max_stars_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Cesium3DTilesSelection/include/Cesium3DTilesSelection/GltfContent.h", "max_issues_repo_name": "yieryi/cesium-native", "max_issues_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cesium3DTilesSelection/include/Cesium3DTilesSelection/GltfContent.h", "max_forks_repo_name": "yieryi/cesium-native", "max_forks_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4535519126, "max_line_length": 80, "alphanum_fraction": 0.7217683105, "num_tokens": 1761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2309197629292718, "lm_q2_score": 0.027585279928436127, "lm_q1q2_score": 0.00636998630141207}}
{"text": "/*! \\file allvars.h\n *  \\brief declares global variables.\n *\n *  This file declares all global variables and structures. Further variables should be added here, and declared as\n *  \\e \\b extern. The actual existence of these variables is provided by the file \\ref allvars.cxx. To produce\n *  \\ref allvars.cxx from \\ref allvars.h, do the following:\n *\n *     \\arg Erase all \\#define's, typedef's, and enum's\n *     \\arg add \\#include \"allvars.h\", delete the \\#ifndef ALLVARS_H conditional\n *     \\arg delete all keywords 'extern'\n *     \\arg delete all struct definitions enclosed in {...}, e.g.\n *        \"extern struct global_data_all_processes {....} All;\"\n *        becomes \"struct global_data_all_processes All;\"\n */\n\n#ifndef ALLVARS_H\n#define ALLVARS_H\n\n#include <cstdio>\n#include <cstdlib>\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <cmath>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <getopt.h>\n#include <sys/stat.h>\n#include <sys/timeb.h>\n\n#include <gsl/gsl_heapsort.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_roots.h>\n\n\n///\\name Include for NBodyFramework library.\n//@{\n///nbody code\n#include <NBody.h>\n///Math code\n#include <NBodyMath.h>\n///Binary KD-Tree code\n#include <KDTree.h>\n///Extra routines that analyze a distribution of particles\n#include <Analysis.h>\n//@}\n\n// ///\\name for checking the endian of floats\n//#include <endianutils.h>\n\n///if using OpenMP API\n#ifdef USEOPENMP\n#include <omp.h>\n#endif\n\n///if using HDF API\n#ifdef USEHDF\n#include \"H5Cpp.h\"\n#ifndef H5_NO_NAMESPACE\nusing namespace H5;\n#endif\n#endif\n\n///if using ADIOS API\n#ifdef USEADIOS\n#include \"adios.h\"\n#endif\n\n//#include \"swiftinterface.h\"\n//\n//using namespace Swift;\nusing namespace std;\nusing namespace Math;\nusing namespace NBody;\n\n//-- Structures and external variables\n\n/// \\defgroup PARTTYPES Particle types\n//@{\n#define  GASTYPE 0\n#define  DARKTYPE 1\n#define  DARK2TYPE 2\n#define  DARK3TYPE 3\n#define  STARTYPE 4\n#define  BHTYPE 5\n#define  WINDTYPE 6\n#define  NPARTTYPES 7\n//number of baryon types +1, to store all baryons\n#define  NBARYONTYPES 5\n//@}\n\n/// \\defgroup SEARCHTYPES Specify particle type to be searched, all, dm only, separate\n//@{\n#define  PSTALL 1\n#define  PSTDARK 2\n#define  PSTSTAR 3\n#define  PSTGAS 4\n#define  PSTBH 5\n#define  PSTNOBH 6\n//@}\n\n/// \\defgroup STRUCTURETYPES Specific structure type, allow for other types beside HALO\n//@{\n/// \\todo note that here I have set background group type to a halo structure type but that can be changed\n#define HALOSTYPE 10\n#define HALOCORESTYPE 5\n#define WALLSTYPE 1\n#define VOIDSTYPE 2\n#define FILAMENTSTYPE 3\n#define BGTYPE 10\n#define GROUPNOPARENT -1\n#define FOF3DTYPE 7\n#define FOF3DGROUP -2\n//@}\n\n/// \\defgroup FOFTYPES FOF search types\n//@{\n//subsets made\n///call \\ref FOFStreamwithprob\n#define  FOFSTPROB 1\n///6D FOF search but only with outliers\n#define  FOF6DSUBSET 7\n///like \\ref FOFStreamwithprob search but search is limited to nearest physical neighbours\n#define  FOFSTPROBNN 9\n///like \\ref FOFStreamwithprob search but here linking length adjusted by velocity offset, smaller lengths for larger velocity offsets\n#define  FOFSTPROBLX 10\n///like \\ref FOFSTPROBLX but for NN search\n#define  FOFSTPROBNNLX 11\n///like \\ref FOFSTPROBNN but there is not linking length applied just use nearest neighbours\n#define  FOFSTPROBNNNODIST 12\n//for iterative method with FOFStreamwithprob\n//#define  FOFSTPROBIT 13\n#define  FOFSTPROBSCALEELL 13\n//#define  FOFSTPROBIT 13\n#define  FOFSTPROBSCALEELLNN 14\n//solely phase-space tensor core growth substructure search\n#define  FOF6DCORE 6\n\n///phase-space FOF but no subset produced\n#define  FOFSTNOSUBSET 2\n///no subsets made, just 6d (with each 6dfof search using 3d fof velocity dispersion,)\n#define  FOF6DADAPTIVE 3\n///6d fof but only use single velocity dispersion from largest 3d fof object\n#define  FOF6D 4\n///3d search\n#define  FOF3D 5\n//@}\n\n/// \\defgroup INTERATIVESEARCHPARAMS for iterative subsubstructure search\n//@{\n/// this is minimum particle number size for a subsearch to proceed whereby substructure split up into CELLSPLITNUM new cells\n#define  MINCELLSIZE 100\n#define  CELLSPLITNUM 8\n#define  MINSUBSIZE MINCELLSIZE*CELLSPLITNUM\n#define  MAXSUBLEVEL 8\n/// maximum fraction a cell can take of a halo\n#define  MAXCELLFRACTION 0.1\n//@}\n\n///\\defgroup GRIDTYPES Type of Grid structures\n//@{\n#define  PHYSENGRID 1\n#define  PHASEENGRID 2\n#define  PHYSGRID 3\n//@}\n\n/// \\name Max number of neighbouring cells used in interpolation of background velocity field.\n//@{\n\n//if cells were cubes this would be all the neighbours that full enclose the cube, 6 faces+20 diagonals\n//using daganoals may not be ideal. Furthermore, code using adaptive grid that if effectively produces\n//cell that are rectangular prisms. Furthermore, not all cells will share a boundary with another cell.\n//So just consider \"faces\".\n#define MAXNGRID 6\n\n//@}\n\n///\\defgroup INPUTTYPES defining types of input\n//@{\n#define  NUMINPUTS 5\n#define  IOGADGET 1\n#define  IOHDF 2\n#define  IOTIPSY 3\n#define  IORAMSES 4\n#define  IONCHILADA 5\n//@}\n\n\n///\\defgroup OUTPUTTYPES defining format types of output\n//@{\n#define OUTASCII 0\n#define OUTBINARY 1\n#define OUTHDF 2\n#define OUTADIOS 3\n//@}\n\n/// \\name For Unbinding\n//@{\n\n///number below which just use PP calculation for potential, which occurs roughly at when n~2*log(n) (from scaling of n^2 vs n ln(n) for PP vs tree and factor of 2 is\n///for extra overhead in producing tree. For reasonable values of n (>100) this occurs at ~100. Here to account for extra memory need for tree, we use n=3*log(n) or 150\n#define UNBINDNUM 150\n///when unbinding check to see if system is bound and least bound particle is also bound\n#define USYSANDPART 0\n///when unbinding check to see if least bound particle is also bound\n#define UPART 1\n///use the bulk centre of mass velocity to define velocity reference frame when determining if particle bound\n#define CMVELREF 0\n///use the particle at potential minimum. Issues if too few particles used as particles will move in and out of deepest point of the potential well\n#define POTREF 1\n\n//@}\n\n/// \\name For Tree potential calculation\n//@{\n\n///leafflag indicating in tree-calculation of potential, reached a leaf node that does not satisfy mono-pole approx\n#define leafflag 1\n///split flag means node not used as subcells are searched\n#define splitflag -1\n///cellflag means a node that is not necessarily a leaf node can be approximated by mono-pole\n#define cellflag 0\n\n//@}\n\n/// \\defgroup OMPLIMS For determining whether loop contains enough for openm to be worthwhile.\n//@{\n#define ompsearchnum 50000\n#define ompunbindnum 1000\n#define ompperiodnum 50000\n#define omppropnum 50000\n//@}\n\n\n///\\name halo id modifers used with current snapshot value to make temporally unique halo identifiers\n#ifdef LONGINT\n#define HALOIDSNVAL 1000000000000L\n#else\n#define HALOIDSNVAL 1000000\n#endif\n\n///\\defgroup GASPARAMS Useful constants for gas\n//@{\n///mass of helium relative to hydrogen\n#define M_HetoM_H 4.0026\n//@}\n\n\n/// Structure stores unbinding information\nstruct UnbindInfo\n{\n    ///\\name flag whether unbind groups, keep bg potential when unbinding, type of unbinding and reference frame\n    //@{\n    int unbindflag,bgpot,unbindtype,cmvelreftype;\n    //@}\n    ///boolean as to whether code calculate potentials or potentials are externally provided\n    bool icalculatepotential;\n    ///fraction of potential energy that kinetic energy is allowed to be and consider particle bound\n    Double_t Eratio;\n    ///minimum bound mass fraction\n    Double_t minEfrac;\n    ///when to recalculate kinetic energies if cmvel has changed enough\n    Double_t cmdelta;\n    ///maximum fraction of particles to remove when unbinding in one given unbinding step\n    Double_t maxunbindfrac;\n    ///minimum number of particles to use to calculate reference frame if using particles around deepest potential well as reference frame\n    Int_t Npotref;\n    ///fraction of number of particles to use to calculate reference frame if using particles around deepest potential well as reference frame\n    Double_t fracpotref;\n    ///\\name gravity and tree potential calculation;\n    //@{\n    int BucketSize;\n    Double_t TreeThetaOpen;\n    ///softening length\n    Double_t eps;\n    //@}\n    UnbindInfo(){\n        icalculatepotential=true;\n        unbindflag=0;\n        bgpot=1;\n        unbindtype=UPART;\n        cmvelreftype=CMVELREF;\n        cmdelta=0.02;\n        Eratio=1.0;\n        minEfrac=1.0;\n        BucketSize=8;\n        TreeThetaOpen=0.7;\n        eps=0.0;\n        maxunbindfrac=0.05;\n        Npotref=10;\n        fracpotref=0.1;\n    }\n};\n\n/// Structure stores information used when calculating bulk (sub)structure properties\n/// which is used in \\ref substructureproperties.cxx\nstruct PropInfo\n{\n    //interate till this much mass in contained in a spherical region to calculate cm quantities\n    Double_t cmfrac,cmadjustfac;\n\n    PropInfo(){\n        cmfrac=0.1;\n        cmadjustfac=0.7;\n    }\n};\n\n/* Structure to hold the location of a top-level cell. */\nstruct cell_loc {\n\n    /* Coordinates x,y,z */\n    double loc[3];\n\n};\n\n/// Options structure stores useful variables that have user determined values which are altered by \\ref GetArgs in \\ref ui.cxx\nstruct Options\n{\n    ///\\name filenames\n    //@{\n    char *fname,*outname,*smname,*pname,*gname;\n    char *ramsessnapname;\n    //@}\n    ///input format\n    int inputtype;\n    ///number of snapshots\n    int num_files,snum;\n    ///if parallel reading, number of files read in parallel\n    int nsnapread;\n    ///for output, specify the formats, ie. many separate files\n    int iseparatefiles;\n    ///for output specify the format HDF, binary or ascii \\ref OUTHDF, \\ref OUTBINARY, \\ref OUTASCII\n    int ibinaryout;\n    ///for extended output allowing extraction of particles\n    int iextendedoutput;\n    /// output extra fields in halo properties\n    int iextrahalooutput;\n    ///disable particle id related output like fof.grp or catalog_group data. Useful if just want halo properties\n    ///and not interested in tracking. Code writes halo properties catalog and exits.\n    int inoidoutput;\n    ///return propery data in in comoving little h units instead of standard physical units\n    int icomoveunit;\n    /// input is a cosmological simulation so can use box sizes, cosmological parameters, etc to set scales\n    int icosmologicalin;\n    /// input buffer size when reading data\n    long int inputbufsize;\n    /// mpi paritcle buffer size when sending input particle information\n    long int mpiparticletotbufsize,mpiparticlebufsize;\n    /// mpi factor by which to multiple the memory allocated, ie: buffer region\n    /// to reduce likelihood of having to expand/allocate new memory\n    Double_t mpipartfac;\n\n    ///\\name length,m,v,grav conversion units\n    //@{\n    Double_t L, M, U, V, G;\n    Double_t lengthtokpc, velocitytokms, masstosolarmass;\n    //@}\n    ///period (comove)\n    Double_t p;\n    ///\\name scale factor, Hubunit, h, cosmology, virial density. These are used if linking lengths are scaled or trying to define virlevel using the cosmology\n    //@{\n    Double_t a,H,h, Omega_m, Omega_b, Omega_cdm, Omega_Lambda, w_de, rhobg, virlevel, virBN98;\n    int comove;\n    /// to store the internal code unit to kpc and the distance^2 of 30 kpc, and 50 kpc\n    Double_t lengthtokpc30pow2, lengthtokpc50pow2;\n    //@}\n\n    ///to store number of each particle types so that if only searching one particle type, assumes order of gas, dark (halo, disk,bulge), star, special or sink for pfof tipsy style output\n    Int_t numpart[NPARTTYPES];\n\n    ///\\name parameters that control the local and average volumes used to calculate the local velocity density and the mean field, also the size of the leafnode in the kd-tree used when searching the tree for fof neighbours\n    //@{\n    int Nvel, Nsearch, Bsize;\n    Int_t Ncell;\n    Double_t Ncellfac;\n    //@}\n    ///minimum group size\n    int MinSize;\n    ///allows for field halos to have a different minimum size\n    int HaloMinSize;\n    ///Significance parameter for groups\n    Double_t siglevel;\n\n    ///whether to search for substructures at all\n    int iSubSearch;\n    ///type of search\n    int foftype,fofbgtype;\n    ///grid type, physical, physical+entropy splitting criterion, phase+entropy splitting criterion. Note that this parameter should not be changed from the default value\n    int gridtype;\n    ///flag indicating search all particle types or just dark matter\n    int partsearchtype;\n    ///flag indicating a separate baryonic search is run, looking for all particles that are associated in phase-space\n    ///with dark matter particles that belong to a structure\n    int iBaryonSearch;\n    ///flag indicating if move to CM frame for substructure search\n    int icmrefadjust;\n\n    ///threshold on particle ELL value, normalized logarithmic distance from predicted maxwellian velocity density.\n    Double_t ellthreshold;\n    ///\\name fofstream search parameters\n    //@{\n    Double_t thetaopen,Vratio,ellphys;\n    //@}\n    ///fof6d search parameters\n    Double_t ellvel;\n    ///scaling for ellphs and ellvel\n    Double_t ellxscale,ellvscale;\n    ///flag to use iterative method\n    int iiterflag;\n    ///\\name factors used to multiply the input values to find initial candidate particles and for mergering groups in interative search\n    //@{\n    Double_t ellfac,ellxfac,vfac,thetafac,nminfac;\n    Double_t fmerge;\n    //@}\n    ///factors to alter halo linking length search (related to substructure search)\n    //@{\n    Double_t ellhalophysfac,ellhalovelfac;\n    //@}\n    ///\\name parameters related to 3DFOF search & subsequent 6DFOF search\n    //@{\n    Double_t ellhalo6dxfac;\n    Double_t ellhalo6dvfac;\n    int iKeepFOF;\n    Int_t num3dfof;\n    //@}\n    //@{\n    ///\\name factors used to check for halo mergers, large background substructures and store the velocity scale when searching for associated baryon substructures\n    //@{\n    Double_t HaloMergerSize,HaloMergerRatio,HaloSigmaV,HaloVelDispScale,HaloLocalSigmaV;\n    Double_t fmergebg;\n    //@}\n    ///flag indicating a single halo is passed or must run search for FOF haloes\n    Int_t iSingleHalo;\n    ///flag indicating haloes are to be check for self-boundness after being searched for substructure\n    Int_t iBoundHalos;\n    /// store denv ratio statistics\n    //@{\n    int idenvflag;\n    Double_t denvstat[3];\n    //@}\n    ///verbose output flag\n    int iverbose;\n    ///whether or not to write a fof.grp tipsy like array file\n    int iwritefof;\n    ///whether mass properties for field objects are inclusive\n    int iInclusiveHalo;\n\n    ///if no mass value stored then store global mass value\n    Double_t MassValue;\n\n    ///structure that contains variables for unbinding\n    UnbindInfo uinfo;\n    ///structure that contains variables for property calculation\n    PropInfo pinfo;\n\n    ///effective resolution for zoom simulations\n    Int_t Neff;\n\n    ///if during substructure search, want to also search for larger substructures\n    //using the more time consuming local velocity calculations (partly in lieu of using the faster core search)\n    int iLargerCellSearch;\n\n    ///\\name extra stuff for halo merger check and identification of multiple halo core and flag for fully adaptive linking length using number density of candidate objects\n    //@{\n    /// run halo core search for mergers\n    int iHaloCoreSearch;\n    ///maximum sublevel at which we search for phase-space cores\n    int maxnlevelcoresearch;\n    ///parameters associated with phase-space search for cores of mergers\n    Double_t halocorexfac, halocorevfac, halocorenfac, halocoresigmafac;\n    ///x and v space linking lengths calculated for each object\n    int iAdaptiveCoreLinking;\n    ///use phase-space tensor core assignment\n    int iPhaseCoreGrowth;\n    ///number of iterations\n    int halocorenumloops;\n    ///factor by which one multiples the configuration space dispersion when looping for cores\n    Double_t halocorexfaciter;\n    ///factor by which one multiples the velocity space dispersion when looping for cores\n    Double_t halocorevfaciter;\n    ///factor by which one multiples the min num when looping for cores\n    Double_t halocorenumfaciter;\n    ///factor by which a core must be seperated from main core in phase-space in sigma units\n    Double_t halocorephasedistsig;\n    //@}\n    ///for storing a snapshot value to make halo ids unique across snapshots\n    long long snapshotvalue;\n\n    ///\\name for reading gadget info with lots of extra sph, star and bh blocks\n    //@{\n    int gnsphblocks,gnstarblocks,gnbhblocks;\n    //@}\n\n    /// \\name Extra HDF flags indicating the existence of extra baryonic/dm particle types\n    //@{\n    /// input naming convention\n    int ihdfnameconvention;\n    /// input contains star particles\n    int iusestarparticles;\n    /// input contains black hole/sink particles\n    int iusesinkparticles;\n    /// input contains wind particles\n    int iusewindparticles;\n    /// input contains tracer particles\n    int iusetracerparticles;\n    /// input contains extra dark type particles\n    int iuseextradarkparticles;\n    //@}\n\n    /// if want full spherical overdensity, factor by which size is multiplied to get\n    ///bucket of particles\n    Double_t SphericalOverdensitySeachFac;\n    ///if want to the particle IDs that are within the SO overdensity of a halo\n    int iSphericalOverdensityPartList;\n    /// \\name Extra variables to store information useful in zoom simluations\n    //@{\n    /// store the lowest dark matter particle mass\n    Double_t zoomlowmassdm;\n    //@}\n\n    ///\\name extra runtime flags\n    //@{\n    ///scale lengths. Useful if searching single halo system and which to automatically scale linking lengths\n    int iScaleLengths;\n\n    // Swift simulation information\n    //Swift::siminfo swiftsiminfo;\n\n    double spacedimension[3];\n        \n    /* Number of top-level cells. */\n    int numcells;\n\n    /* Number of top-level cells in each dimension. */\n    int numcellsperdim;\n\n    /* Locations of top-level cells. */\n    cell_loc *cellloc;\n\n    /*! Top-level cell width. */\n    double cellwidth[3];\n\n    /*! Inverse of the top-level cell width. */\n    double icellwidth[3];\n\n    /*! Holds the node ID of each top-level cell. */\n    const int *cellnodeids;\n\n    //@}\n    Options()\n    {\n        L = 1.0;\n        M = 1.0;\n        V = 1.0;\n        G = 1.0;\n        p = 0.0;\n\n        a = 1.0;\n        H = 0.;\n        h = 1.0;\n        Omega_m = 1.0;\n        Omega_Lambda = 0.0;\n        Omega_b = 0.0;\n        Omega_cdm = Omega_m;\n        rhobg = 1.0;\n        virlevel = -1;\n        comove=0;\n        H=100.0;//value of Hubble flow in h 1 km/s/Mpc\n        MassValue=1.0;\n\n        inputtype=IOGADGET;\n\n        num_files=1;\n        nsnapread=1;\n\n        fname=outname=smname=pname=gname=outname=NULL;\n\n        Bsize=16;\n        Nvel=32;\n        Nsearch=256;\n        Ncellfac=0.01;\n\n        iSubSearch=1;\n        partsearchtype=PSTALL;\n        for (int i=0;i<NPARTTYPES;i++)numpart[i]=0;\n        foftype=FOFSTPROB;\n        gridtype=PHYSENGRID;\n        fofbgtype=FOF6D;\n        idenvflag=0;\n        iBaryonSearch=0;\n        icmrefadjust=1;\n\n        Neff=-1;\n\n        ellthreshold=1.5;\n        thetaopen=0.05;\n        Vratio=1.25;\n        ellphys=0.2;\n        MinSize=20;\n        HaloMinSize=-1;\n        siglevel=2.0;\n        ellvel=0.5;\n        ellxscale=ellvscale=1.0;\n        ellhalophysfac=ellhalovelfac=1.0;\n        ellhalo6dxfac=1.0;\n        ellhalo6dvfac=1.25;\n\n        iiterflag=0;\n        ellfac=2.5;\n        ellxfac=3.0;\n        vfac=1.0;\n        thetafac=1.0;\n        nminfac=0.5;\n        fmerge=0.25;\n\n        HaloMergerSize=10000;\n        HaloMergerRatio=0.2;\n        HaloVelDispScale=0;\n        fmergebg=0.5;\n        iSingleHalo=0;\n        iBoundHalos=0;\n        iInclusiveHalo=0;\n        iKeepFOF=0;\n\n        iLargerCellSearch=0;\n\n        iHaloCoreSearch=0;\n        iAdaptiveCoreLinking=0;\n        iPhaseCoreGrowth=1;\n        maxnlevelcoresearch=5;\n        halocorexfac=0.5;\n        halocorevfac=2.0;\n        halocorenfac=0.1;\n        halocoresigmafac=2.0;\n        halocorenumloops=3;\n        halocorexfaciter=0.75;\n        halocorevfaciter=0.75;\n        halocorenumfaciter=1.0;\n        halocorephasedistsig=2.0;\n\n        iverbose=0;\n        iwritefof=0;\n        iseparatefiles=0;\n        ibinaryout=0;\n        iextrahalooutput=0;\n        iextendedoutput=0;\n        inoidoutput=0;\n        icomoveunit=0;\n        icosmologicalin=1;\n\n        iusestarparticles=1;\n        iusesinkparticles=1;\n        iusewindparticles=0;\n        iusetracerparticles=0;\n#ifdef HIGHRES\n        iuseextradarkparticles=1;\n#else\n        iuseextradarkparticles=0;\n#endif\n\n        snapshotvalue=0;\n\n        gnsphblocks=4;\n        gnstarblocks=2;\n        gnbhblocks=2;\n\n        iScaleLengths=0;\n\n        inputbufsize=100000;\n\n        mpiparticletotbufsize=-1;\n        mpiparticlebufsize=-1;\n\n        lengthtokpc=-1.0;\n        velocitytokms=-1.0;\n        masstosolarmass=-1.0;\n\n        lengthtokpc30pow2=30.0*30.0;\n        lengthtokpc30pow2=50.0*50.0;\n\n        SphericalOverdensitySeachFac=1.25;\n        iSphericalOverdensityPartList=0;\n\n        mpipartfac=0.1;\n#if USEHDF\n        ihdfnameconvention=0;\n#endif\n    }\n};\n\nstruct ConfigInfo{\n    //list the name of the info\n    vector<string> nameinfo;\n    //vector<float> datainfo;\n    vector<string> datainfo;\n    //vector<int> datatype;\n    ConfigInfo(Options &opt){\n        //if compiler is super old and does not have at least std 11 implementation to_string does not exist\n#ifndef OLDCCOMPILER\n        //general search operations\n        nameinfo.push_back(\"Particle_search_type\");\n        datainfo.push_back(to_string(opt.partsearchtype));\n        nameinfo.push_back(\"FoF_search_type\");\n        datainfo.push_back(to_string(opt.foftype));\n        nameinfo.push_back(\"FoF_Field_search_type\");\n        datainfo.push_back(to_string(opt.fofbgtype));\n        nameinfo.push_back(\"Search_for_substructure\");\n        datainfo.push_back(to_string(opt.iSubSearch));\n        nameinfo.push_back(\"Keep_FOF\");\n        datainfo.push_back(to_string(opt.iKeepFOF));\n        nameinfo.push_back(\"Iterative_searchflag\");\n        datainfo.push_back(to_string(opt.iiterflag));\n        nameinfo.push_back(\"Unbind_flag\");\n        datainfo.push_back(to_string(opt.uinfo.unbindflag));\n        nameinfo.push_back(\"Baryon_searchflag\");\n        datainfo.push_back(to_string(opt.iBaryonSearch));\n        nameinfo.push_back(\"CMrefadjustsubsearch_flag\");\n        datainfo.push_back(to_string(opt.icmrefadjust));\n        nameinfo.push_back(\"Halo_core_search\");\n        datainfo.push_back(to_string(opt.iHaloCoreSearch));\n        nameinfo.push_back(\"Use_adaptive_core_search\");\n        datainfo.push_back(to_string(opt.iAdaptiveCoreLinking));\n        nameinfo.push_back(\"Use_phase_tensor_core_growth\");\n        datainfo.push_back(to_string(opt.iPhaseCoreGrowth));\n\n        //local field parameters\n        nameinfo.push_back(\"Cell_fraction\");\n        datainfo.push_back(to_string(opt.Ncellfac));\n        nameinfo.push_back(\"Grid_type\");\n        datainfo.push_back(to_string(opt.gridtype));\n        nameinfo.push_back(\"Nsearch_velocity\");\n        datainfo.push_back(to_string(opt.Nvel));\n        nameinfo.push_back(\"Nsearch_physical\");\n        datainfo.push_back(to_string(opt.Nsearch));\n\n        //substructure search parameters\n        nameinfo.push_back(\"Outlier_threshold\");\n        datainfo.push_back(to_string(opt.ellthreshold));\n        nameinfo.push_back(\"Significance_level\");\n        datainfo.push_back(to_string(opt.siglevel));\n        nameinfo.push_back(\"Velocity_ratio\");\n        datainfo.push_back(to_string(opt.Vratio));\n        nameinfo.push_back(\"Velocity_opening_angle\");\n        datainfo.push_back(to_string(opt.thetaopen));\n        nameinfo.push_back(\"Physical_linking_length\");\n        datainfo.push_back(to_string(opt.ellphys));\n        nameinfo.push_back(\"Velocity_linking_length\");\n        datainfo.push_back(to_string(opt.ellvel));\n        nameinfo.push_back(\"Minimum_size\");\n        datainfo.push_back(to_string(opt.MinSize));\n\n        //field object specific searches\n        nameinfo.push_back(\"Minimum_halo_size\");\n        datainfo.push_back(to_string(opt.HaloMinSize));\n        nameinfo.push_back(\"Halo_linking_length_factor\");\n        datainfo.push_back(to_string(opt.ellhalophysfac));\n        nameinfo.push_back(\"Halo_velocity_linking_length_factor\");\n        datainfo.push_back(to_string(opt.ellhalovelfac));\n\n        //specific to 6DFOF field search\n        nameinfo.push_back(\"Halo_6D_linking_length_factor\");\n        datainfo.push_back(to_string(opt.ellhalo6dxfac));\n        nameinfo.push_back(\"Halo_6D_vel_linking_length_factor\");\n        datainfo.push_back(to_string(opt.ellhalo6dvfac));\n\n        //specific search for 6d fof core searches\n        nameinfo.push_back(\"Halo_core_ellx_fac\");\n        datainfo.push_back(to_string(opt.halocorexfac));\n        nameinfo.push_back(\"Halo_core_ellv_fac\");\n        datainfo.push_back(to_string(opt.halocorevfac));\n        nameinfo.push_back(\"Halo_core_ncellfac\");\n        datainfo.push_back(to_string(opt.halocorenfac));\n        nameinfo.push_back(\"Halo_core_adaptive_sigma_fac\");\n        datainfo.push_back(to_string(opt.halocoresigmafac));\n        nameinfo.push_back(\"Halo_core_num_loops\");\n        datainfo.push_back(to_string(opt.halocorenumloops));\n        nameinfo.push_back(\"Halo_core_loop_ellx_fac\");\n        datainfo.push_back(to_string(opt.halocorexfaciter));\n        nameinfo.push_back(\"Halo_core_loop_ellv_fac\");\n        datainfo.push_back(to_string(opt.halocorevfaciter));\n        nameinfo.push_back(\"Halo_core_loop_elln_fac\");\n        datainfo.push_back(to_string(opt.halocorenumfaciter));\n        nameinfo.push_back(\"Halo_core_phase_significance\");\n        datainfo.push_back(to_string(opt.halocorephasedistsig));\n\n\n        //for changing factors used in iterative search\n        nameinfo.push_back(\"Iterative_threshold_factor\");\n        datainfo.push_back(to_string(opt.ellfac));\n        nameinfo.push_back(\"Iterative_linking_length_factor\");\n        datainfo.push_back(to_string(opt.ellxfac));\n        nameinfo.push_back(\"Iterative_Vratio_factor\");\n        datainfo.push_back(to_string(opt.vfac));\n        nameinfo.push_back(\"Iterative_ThetaOp_factor\");\n        datainfo.push_back(to_string(opt.thetafac));\n\n        //for changing effective resolution when rescaling linking lengh\n        nameinfo.push_back(\"Effective_resolution\");\n        datainfo.push_back(to_string(opt.Neff));\n\n        //for changing effective resolution when rescaling linking lengh\n        nameinfo.push_back(\"Singlehalo_search\");\n        datainfo.push_back(to_string(opt.iSingleHalo));\n\n        //units, cosmology\n        nameinfo.push_back(\"Length_unit\");\n        datainfo.push_back(to_string(opt.L));\n        nameinfo.push_back(\"Velocity_unit\");\n        datainfo.push_back(to_string(opt.V));\n        nameinfo.push_back(\"Mass_unit\");\n        datainfo.push_back(to_string(opt.M));\n        nameinfo.push_back(\"Hubble_unit\");\n        datainfo.push_back(to_string(opt.H));\n        nameinfo.push_back(\"Gravity\");\n        datainfo.push_back(to_string(opt.G));\n        nameinfo.push_back(\"Mass_value\");\n        datainfo.push_back(to_string(opt.MassValue));\n        nameinfo.push_back(\"Length_unit_to_kpc\");\n        datainfo.push_back(to_string(opt.lengthtokpc));\n        nameinfo.push_back(\"Velocity_to_kms\");\n        datainfo.push_back(to_string(opt.velocitytokms));\n        nameinfo.push_back(\"Mass_to_solarmass\");\n        datainfo.push_back(to_string(opt.masstosolarmass));\n\n        nameinfo.push_back(\"Period\");\n        datainfo.push_back(to_string(opt.p));\n        nameinfo.push_back(\"Scale_factor\");\n        datainfo.push_back(to_string(opt.a));\n        nameinfo.push_back(\"h_val\");\n        datainfo.push_back(to_string(opt.h));\n        nameinfo.push_back(\"Omega_m\");\n        datainfo.push_back(to_string(opt.Omega_m));\n        nameinfo.push_back(\"Omega_Lambda\");\n        datainfo.push_back(to_string(opt.Omega_Lambda));\n        nameinfo.push_back(\"Critical_density\");\n        datainfo.push_back(to_string(opt.rhobg));\n        nameinfo.push_back(\"Virial_density\");\n        datainfo.push_back(to_string(opt.virlevel));\n        nameinfo.push_back(\"Omega_cdm\");\n        datainfo.push_back(to_string(opt.Omega_cdm));\n        nameinfo.push_back(\"Omega_b\");\n        datainfo.push_back(to_string(opt.Omega_b));\n        nameinfo.push_back(\"w_of_DE\");\n        datainfo.push_back(to_string(opt.w_de));\n\n        //unbinding\n        nameinfo.push_back(\"Softening_length\");\n        datainfo.push_back(to_string(opt.uinfo.eps));\n        nameinfo.push_back(\"Allowed_kinetic_potential_ratio\");\n        datainfo.push_back(to_string(opt.uinfo.Eratio));\n        nameinfo.push_back(\"Min_bound_mass_frac\");\n        datainfo.push_back(to_string(opt.uinfo.minEfrac));\n        nameinfo.push_back(\"Bound_halos\");\n        datainfo.push_back(to_string(opt.iBoundHalos));\n        nameinfo.push_back(\"Keep_background_potential\");\n        datainfo.push_back(to_string(opt.uinfo.bgpot));\n        nameinfo.push_back(\"Kinetic_reference_frame_type\");\n        datainfo.push_back(to_string(opt.uinfo.cmvelreftype));\n        nameinfo.push_back(\"Min_npot_ref\");\n        datainfo.push_back(to_string(opt.uinfo.Npotref));\n        nameinfo.push_back(\"Frac_pot_ref\");\n        datainfo.push_back(to_string(opt.uinfo.fracpotref));\n        nameinfo.push_back(\"Unbinding_type\");\n        datainfo.push_back(to_string(opt.uinfo.unbindtype));\n\n        //other options\n        nameinfo.push_back(\"Verbose\");\n        datainfo.push_back(to_string(opt.iverbose));\n        nameinfo.push_back(\"Write_group_array_file\");\n        datainfo.push_back(to_string(opt.iwritefof));\n        nameinfo.push_back(\"Snapshot_value\");\n        datainfo.push_back(to_string(opt.snapshotvalue));\n        nameinfo.push_back(\"Inclusive_halo_masses\");\n        datainfo.push_back(to_string(opt.iInclusiveHalo));\n\n        //io related\n        nameinfo.push_back(\"Cosmological_input\");\n        datainfo.push_back(to_string(opt.icosmologicalin));\n        nameinfo.push_back(\"Input_chunk_size\");\n        datainfo.push_back(to_string(opt.inputbufsize));\n        nameinfo.push_back(\"MPI_particle_total_buf_size\");\n        datainfo.push_back(to_string(opt.mpiparticletotbufsize));\n        nameinfo.push_back(\"Separate_output_files\");\n        datainfo.push_back(to_string(opt.iseparatefiles));\n        nameinfo.push_back(\"Binary_output\");\n        datainfo.push_back(to_string(opt.ibinaryout));\n        nameinfo.push_back(\"Comoving_units\");\n        datainfo.push_back(to_string(opt.icomoveunit));\n        nameinfo.push_back(\"Extended_output\");\n        datainfo.push_back(to_string(opt.iextendedoutput));\n\n        //gadget io related to extra info for sph, stars, bhs,\n        nameinfo.push_back(\"NSPH_extra_blocks\");\n        datainfo.push_back(to_string(opt.gnsphblocks));\n        nameinfo.push_back(\"NStar_extra_blocks\");\n        datainfo.push_back(to_string(opt.gnstarblocks));\n        nameinfo.push_back(\"NBH_extra_blocks\");\n        datainfo.push_back(to_string(opt.gnbhblocks));\n\n        //mpi related configuration\n        nameinfo.push_back(\"MPI_part_allocation_fac\");\n        datainfo.push_back(to_string(opt.mpiparticletotbufsize));\n#endif\n    }\n};\n\nstruct SimInfo{\n    //list the name of the info\n    vector<string> nameinfo;\n    vector<string> datainfo;\n\n    SimInfo(Options &opt){\n        //if compiler is super old and does not have at least std 11 implementation to_string does not exist\n#ifndef OLDCCOMPILER\n        nameinfo.push_back(\"Cosmological_Sim\");\n        datainfo.push_back(to_string(opt.icosmologicalin));\n        if (opt.icosmologicalin) {\n            nameinfo.push_back(\"ScaleFactor\");\n            datainfo.push_back(to_string(opt.a));\n            nameinfo.push_back(\"h_val\");\n            datainfo.push_back(to_string(opt.h));\n            nameinfo.push_back(\"Omega_m\");\n            datainfo.push_back(to_string(opt.Omega_m));\n            nameinfo.push_back(\"Omega_Lambda\");\n            datainfo.push_back(to_string(opt.Omega_Lambda));\n            nameinfo.push_back(\"Omega_cdm\");\n            datainfo.push_back(to_string(opt.Omega_cdm));\n            nameinfo.push_back(\"Omega_b\");\n            datainfo.push_back(to_string(opt.Omega_b));\n            nameinfo.push_back(\"w_of_DE\");\n            datainfo.push_back(to_string(opt.w_de));\n            nameinfo.push_back(\"Period\");\n            datainfo.push_back(to_string(opt.p));\n            nameinfo.push_back(\"Hubble_unit\");\n            datainfo.push_back(to_string(opt.H));\n        }\n        else{\n            nameinfo.push_back(\"Time\");\n            datainfo.push_back(to_string(opt.a));\n            nameinfo.push_back(\"Period\");\n            datainfo.push_back(to_string(opt.p));\n        }\n\n        //units\n        nameinfo.push_back(\"Length_unit\");\n        datainfo.push_back(to_string(opt.L));\n        nameinfo.push_back(\"Velocity_unit\");\n        datainfo.push_back(to_string(opt.V));\n        nameinfo.push_back(\"Mass_unit\");\n        datainfo.push_back(to_string(opt.M));\n        nameinfo.push_back(\"Gravity\");\n        datainfo.push_back(to_string(opt.G));\n#ifdef NOMASS\n        nameinfo.push_back(\"Mass_value\");\n        datainfo.push_back(to_string(opt.MassValue));\n#endif\n\n#endif\n    }\n};\n\n\nstruct UnitInfo{\n    //list the name of the info\n    vector<string> nameinfo;\n    vector<string> datainfo;\n\n    UnitInfo(Options &opt){\n        //if compiler is super old and does not have at least std 11 implementation to_string does not exist\n#ifndef OLDCCOMPILER\n        nameinfo.push_back(\"Cosmological_Sim\");\n        datainfo.push_back(to_string(opt.icosmologicalin));\n        nameinfo.push_back(\"Comoving_or_Physical\");\n        datainfo.push_back(to_string(opt.icomoveunit));\n        //units\n        nameinfo.push_back(\"Length_unit_to_kpc\");\n        datainfo.push_back(to_string(opt.lengthtokpc));\n        nameinfo.push_back(\"Velocity_unit_to_kms\");\n        datainfo.push_back(to_string(opt.velocitytokms));\n        nameinfo.push_back(\"Mass_unit_to_solarmass\");\n        datainfo.push_back(to_string(opt.masstosolarmass));\n#endif\n    }\n};\n\n/// N-dim grid cell\nstruct GridCell\n{\n    int ndim;\n    Int_t gid;\n    //middle of cell, and boundaries of cell\n    Double_t xm[6], xbl[6],xbu[6];\n    //mass, radial size of in cell\n    Double_t mass, rsize;\n    //number of particles in cell\n    Int_t nparts,*nindex;\n    //neighbouring grid cells and distance from cell centers\n    Int_t nnidcells[MAXNGRID];\n    Double_t nndist[MAXNGRID];\n    Double_t den;\n    GridCell(int N=3){\n        ndim=N;\n        nparts=0;\n        den=0;\n    }\n    ~GridCell(){\n        if (nparts>0)delete nindex;\n    }\n};\n\n/*! structure stores bulk properties like\n    \\f$ m,\\ (x,y,z)_{\\rm cm},\\ (vx,vy,vz)_{\\rm cm},\\ V_{\\rm max},\\ R_{\\rm max}, \\f$\n    which is calculated in \\ref substructureproperties.cxx\n*/\nstruct PropData\n{\n    ///\\name order in structure hierarchy and number of subhaloes\n    //@{\n    long long haloid,hostid,directhostid, hostfofid;\n    Int_t numsubs;\n    //@}\n\n    ///\\name properties of total object including DM, gas, stars, bh, etc\n    //@{\n    ///number of particles\n    Int_t num;\n    ///number of particles in FOF envelop\n    Int_t gNFOF;\n    ///centre of mass\n    Coordinate gcm, gcmvel;\n    ///Position of most bound particle\n    Coordinate gpos, gvel;\n    ///\\name physical properties regarding mass, size\n    //@{\n    Double_t gmass,gsize,gMvir,gRvir,gRmbp,gmaxvel,gRmaxvel,gMmaxvel,gRhalfmass;\n    Double_t gM200c,gR200c,gM200m,gR200m,gMFOF,gM500c,gR500c,gMBN98,gRBN98;\n    //@}\n    ///\\name physical properties for shape/mass distribution\n    //@{\n    ///axis ratios\n    Double_t gq,gs;\n    ///eigenvector\n    Matrix geigvec;\n    //@}\n    ///\\name physical properties for velocity\n    //@{\n    ///velocity dispersion\n    Double_t gsigma_v;\n    ///dispersion tensor\n    Matrix gveldisp;\n    //@}\n    ///physical properties for dynamical state\n    Double_t Efrac,Pot,T;\n    ///physical properties for angular momentum\n    Coordinate gJ, gJ200m, gJ200c;\n    ///Keep track of position of least unbound particle and most bound particle pid\n    Int_t iunbound,ibound;\n    ///Type of structure\n    int stype;\n    ///concentration (and related quantity used to calculate a concentration)\n    Double_t cNFW, VmaxVvir2;\n    ///Bullock & Peebles spin parameters\n    Double_t glambda_B,glambda_P;\n    ///measure of rotational support\n    Double_t Krot;\n    //@}\n\n    ///\\name halo properties within RVmax\n    //@{\n    Double_t RV_q,RV_s;\n    Matrix RV_eigvec;\n    Double_t RV_sigma_v;\n    Matrix RV_veldisp;\n    Coordinate RV_J;\n    Double_t RV_lambda_B,RV_lambda_P;\n    Double_t RV_Krot;\n    //@}\n\n#ifdef GASON\n    ///\\name gas specific quantities\n    //@{\n    ///number of particles\n    int n_gas;\n    ///mass\n    Double_t M_gas, M_gas_rvmax,M_gas_30kpc,M_gas_50kpc, M_gas_500c;\n    ///pos/vel info\n    Coordinate cm_gas,cmvel_gas;\n    ///velocity/angular momentum info\n    Double_t Krot_gas;\n    Coordinate L_gas;\n    Matrix veldisp_gas;\n    ///morphology\n    Double_t Rhalfmass_gas,q_gas,s_gas;\n    Matrix eigvec_gas;\n    ///mean temperature,metallicty,star formation rate\n    Double_t Temp_gas,Z_gas,SFR_gas;\n    ///physical properties for dynamical state\n    Double_t Efrac_gas,Pot_gas,T_gas;\n    //@}\n#endif\n\n#ifdef STARON\n    ///\\name star specific quantities\n    //@{\n    ///number of particles\n    int n_star;\n    ///mass\n    Double_t M_star, M_star_rvmax, M_star_30kpc, M_star_50kpc, M_star_500c;\n    ///pos/vel info\n    Coordinate cm_star,cmvel_star;\n    ///velocity/angular momentum info\n    Double_t Krot_star;\n    Coordinate L_star;\n    Matrix veldisp_star;\n    ///morphology\n    Double_t Rhalfmass_star,q_star,s_star;\n    Matrix eigvec_star;\n    ///mean age,metallicty\n    Double_t t_star,Z_star;\n    ///physical properties for dynamical state\n    Double_t Efrac_star,Pot_star,T_star;\n    //@}\n#endif\n\n#ifdef BHON\n    ///\\name black hole specific quantities\n    //@{\n    ///number of BH\n    int n_bh;\n    ///mass\n    Double_t M_bh;\n    ///mean accretion rate,metallicty\n    Double_t acc_bh;\n    //@}\n#endif\n\n#ifdef HIGHRES\n    ///\\name low resolution interloper particle specific quantities\n    //@{\n    ///number of interloper low res particles\n    int n_interloper;\n    ///mass\n    Double_t M_interloper;\n    //@}\n#endif\n\n    PropData(){\n        num=gNFOF=0;\n        gmass=gsize=gRmbp=gmaxvel=gRmaxvel=gRvir=gR200m=gR200c=gRhalfmass=Efrac=Pot=T=0.;\n        gMFOF=0;\n        gM500c=gR500c=0;\n        gMBN98=gRBN98=0;\n        gcm[0]=gcm[1]=gcm[2]=gcmvel[0]=gcmvel[1]=gcmvel[2]=0.;\n        gJ[0]=gJ[1]=gJ[2]=0;\n        gJ200m[0]=gJ200m[1]=gJ200m[2]=0;\n        gJ200c[0]=gJ200c[1]=gJ200c[2]=0;\n        gveldisp=Matrix(0.);\n        gq=gs=1.0;\n        Krot=0.;\n\n        RV_sigma_v=0;\n        RV_q=RV_s=1.;\n        RV_J[0]=RV_J[1]=RV_J[2]=0;\n        RV_veldisp=Matrix(0.);\n        RV_eigvec=Matrix(0.);\n        RV_lambda_B=RV_lambda_P=RV_Krot=0;\n\n#ifdef GASON\n        M_gas_rvmax=M_gas_30kpc=M_gas_50kpc=0;\n        n_gas=M_gas=Efrac_gas=0;\n        cm_gas[0]=cm_gas[1]=cm_gas[2]=cmvel_gas[0]=cmvel_gas[1]=cmvel_gas[2]=0.;\n        L_gas[0]=L_gas[1]=L_gas[2]=0;\n        q_gas=s_gas=1.0;\n        Rhalfmass_gas=0;\n        eigvec_gas=Matrix(1,0,0,0,1,0,0,0,1);\n        Temp_gas=Z_gas=SFR_gas=0.0;\n        veldisp_gas=Matrix(0.);\n        Krot_gas=T_gas=Pot_gas=0;\n#endif\n#ifdef STARON\n        M_star_rvmax=M_star_30kpc=M_star_50kpc=0;\n        n_star=M_star=Efrac_star=0;\n        cm_star[0]=cm_star[1]=cm_star[2]=cmvel_star[0]=cmvel_star[1]=cmvel_star[2]=0.;\n        L_star[0]=L_star[1]=L_star[2]=0;\n        q_star=s_star=1.0;\n        Rhalfmass_star=0;\n        eigvec_star=Matrix(1,0,0,0,1,0,0,0,1);\n        t_star=Z_star=0.;\n        veldisp_star=Matrix(0.);\n        Krot_star=T_star=Pot_star=0;\n#endif\n#ifdef BHON\n        n_bh=M_bh=0;\n        acc_bh=0;\n#endif\n#ifdef HIGHRES\n        n_interloper=M_interloper=0;\n#endif\n    }\n    ///equals operator, useful if want inclusive information before substructure search\n    PropData& operator=(const PropData &p){\n        num=p.num;\n        gcm=p.gcm;gcmvel=p.gcmvel;\n        gpos=p.gpos;gvel=p.gvel;\n        gmass=p.gmass;gsize=p.gsize;\n        gMvir=p.gMvir;gRvir=p.gRvir;gRmbp=p.gRmbp;\n        gmaxvel=gmaxvel=p.gmaxvel;gRmaxvel=p.gRmaxvel;gMmaxvel=p.gMmaxvel;\n        gM200c=p.gM200c;gR200c=p.gR200c;\n        gM200m=p.gM200m;gR200m=p.gR200m;\n        gM500c=p.gM500c;gR500c=p.gR500c;\n        gMBN98=p.gMBN98;gRBN98=p.gRBN98;\n        gNFOF=p.gNFOF;\n        gMFOF=p.gMFOF;\n        return *this;\n    }\n\n    ///converts the properties data into comoving little h values\n    ///so masses, positions have little h values and positions are comoving\n    void ConverttoComove(Options &opt){\n        gcm=gcm*opt.h/opt.a;\n        gpos=gpos*opt.h/opt.a;\n        gmass*=opt.h;\n        gMvir*=opt.h;\n        gM200c*=opt.h;\n        gM200m*=opt.h;\n        gM500c*=opt.h;\n        gMBN98*=opt.h;\n        gMFOF*=opt.h;\n        gsize*=opt.h/opt.a;\n        gRmbp*=opt.h/opt.a;\n        gRmaxvel*=opt.h/opt.a;\n        gRvir*=opt.h/opt.a;\n        gR200c*=opt.h/opt.a;\n        gR200m*=opt.h/opt.a;\n        gR500c*=opt.h/opt.a;\n        gRBN98*=opt.h/opt.a;\n        gJ=gJ*opt.h*opt.h/opt.a;\n        gJ200m=gJ200m*opt.h*opt.h/opt.a;\n        gJ200c=gJ200c*opt.h*opt.h/opt.a;\n        RV_J=RV_J*opt.h*opt.h/opt.a;\n#ifdef GASON\n        M_gas*=opt.h;\n        M_gas_rvmax*=opt.h;\n        M_gas_30kpc*=opt.h;\n        M_gas_50kpc*=opt.h;\n        M_gas_500c*=opt.h;\n\n        cm_gas=cm_gas*opt.h/opt.a;\n        Rhalfmass_gas*=opt.h/opt.a;\n        L_gas=L_gas*opt.h*opt.h/opt.a;\n#endif\n#ifdef STARON\n        M_star*=opt.h;\n        M_star_rvmax*=opt.h;\n        M_star_30kpc*=opt.h;\n        M_star_50kpc*=opt.h;\n        M_star_500c*=opt.h;\n        cm_star=cm_star*opt.h/opt.a;\n        Rhalfmass_star*=opt.h/opt.a;\n        L_star=L_star*opt.h*opt.h/opt.a;\n#endif\n#ifdef BHON\n        M_bh*=opt.h;\n#endif\n#ifdef HIGHRES\n        M_interloper*=opt.h;\n#endif\n    }\n\n    ///write (append) the properties data to an already open binary file\n    void WriteBinary(fstream &Fout, Options&opt){\n        long long lval;\n        long unsigned idval;\n        unsigned int ival;\n        double val, val3[3],val9[9];\n        idval=haloid;\n        Fout.write((char*)&idval,sizeof(idval));\n        lval=ibound;\n        Fout.write((char*)&lval,sizeof(idval));\n        lval=hostid;\n        Fout.write((char*)&lval,sizeof(idval));\n        idval=numsubs;\n        Fout.write((char*)&idval,sizeof(idval));\n        idval=num;\n        Fout.write((char*)&idval,sizeof(idval));\n        ival=stype;\n        Fout.write((char*)&ival,sizeof(ival));\n        if (opt.iKeepFOF==1) {\n            idval=directhostid;\n            Fout.write((char*)&idval,sizeof(idval));\n            idval=hostfofid;\n            Fout.write((char*)&idval,sizeof(idval));\n        }\n\n        val=gMvir;\n        Fout.write((char*)&val,sizeof(val));\n\n        for (int k=0;k<3;k++) val3[k]=gcm[k];\n        Fout.write((char*)val3,sizeof(val)*3);\n        for (int k=0;k<3;k++) val3[k]=gpos[k];\n        Fout.write((char*)val3,sizeof(val)*3);\n        for (int k=0;k<3;k++) val3[k]=gcmvel[k];\n        Fout.write((char*)val3,sizeof(val)*3);\n        for (int k=0;k<3;k++) val3[k]=gvel[k];\n        Fout.write((char*)val3,sizeof(val)*3);\n\n        val=gmass;\n        Fout.write((char*)&val,sizeof(val));\n        val=gMFOF;\n        Fout.write((char*)&val,sizeof(val));\n        val=gM200m;\n        Fout.write((char*)&val,sizeof(val));\n        val=gM200c;\n        Fout.write((char*)&val,sizeof(val));\n        val=gMBN98;\n        Fout.write((char*)&val,sizeof(val));\n\n        val=Efrac;\n        Fout.write((char*)&val,sizeof(val));\n\n        val=gRvir;\n        Fout.write((char*)&val,sizeof(val));\n        val=gsize;\n        Fout.write((char*)&val,sizeof(val));\n        val=gR200m;\n        Fout.write((char*)&val,sizeof(val));\n        val=gR200c;\n        Fout.write((char*)&val,sizeof(val));\n        val=gRBN98;\n        Fout.write((char*)&val,sizeof(val));\n        val=gRhalfmass;\n        Fout.write((char*)&val,sizeof(val));\n        val=gRmaxvel;\n        Fout.write((char*)&val,sizeof(val));\n\n        val=gmaxvel;\n        Fout.write((char*)&val,sizeof(val));\n        val=gsigma_v;\n        Fout.write((char*)&val,sizeof(val));\n        for (int k=0;k<3;k++) for (int n=0;n<3;n++) val9[k*3+n]=gveldisp(k,n);\n        Fout.write((char*)val9,sizeof(val)*9);\n\n        val=glambda_B;\n        Fout.write((char*)&val,sizeof(val));\n        for (int k=0;k<3;k++) val3[k]=gJ[k];\n        Fout.write((char*)val3,sizeof(val)*3);\n\n        val=gq;\n        Fout.write((char*)&val,sizeof(val));\n        val=gs;\n        Fout.write((char*)&val,sizeof(val));\n        for (int k=0;k<3;k++) for (int n=0;n<3;n++) val9[k*3+n]=geigvec(k,n);\n        Fout.write((char*)val9,sizeof(val)*9);\n\n        val=cNFW;\n        Fout.write((char*)&val,sizeof(val));\n        val=Krot;\n        Fout.write((char*)&val,sizeof(val));\n        val=T;\n        Fout.write((char*)&val,sizeof(val));\n        val=Pot;\n        Fout.write((char*)&val,sizeof(val));\n\n        val=RV_sigma_v;\n        Fout.write((char*)&val,sizeof(val));\n        for (int k=0;k<3;k++) for (int n=0;n<3;n++) val9[k*3+n]=RV_veldisp(k,n);\n        Fout.write((char*)val9,sizeof(val)*9);\n\n        val=RV_lambda_B;\n        Fout.write((char*)&val,sizeof(val));\n        for (int k=0;k<3;k++) val3[k]=RV_J[k];\n        Fout.write((char*)val3,sizeof(val)*3);\n\n        val=RV_q;\n        Fout.write((char*)&val,sizeof(val));\n        val=RV_s;\n        Fout.write((char*)&val,sizeof(val));\n        for (int k=0;k<3;k++) for (int n=0;n<3;n++) val9[k*3+n]=RV_eigvec(k,n);\n        Fout.write((char*)val9,sizeof(val)*9);\n\n#ifdef GASON\n        idval=n_gas;\n        Fout.write((char*)&idval,sizeof(idval));\n        val=M_gas;\n        Fout.write((char*)&val,sizeof(val));\n        val=M_gas_rvmax;\n        Fout.write((char*)&val,sizeof(val));\n        val=M_gas_30kpc;\n        Fout.write((char*)&val,sizeof(val));\n        val=M_gas_500c;\n        Fout.write((char*)&val,sizeof(val));\n\n        for (int k=0;k<3;k++) val3[k]=cm_gas[k];\n        Fout.write((char*)val3,sizeof(val)*3);\n        for (int k=0;k<3;k++) val3[k]=cmvel_gas[k];\n        Fout.write((char*)val3,sizeof(val)*3);\n\n        val=Efrac_gas;\n        Fout.write((char*)&val,sizeof(val));\n\n        val=Rhalfmass_gas;\n        Fout.write((char*)&val,sizeof(val));\n\n        for (int k=0;k<3;k++) for (int n=0;n<3;n++) val9[k*3+n]=veldisp_gas(k,n);\n        Fout.write((char*)val9,sizeof(val)*9);\n\n        for (int k=0;k<3;k++) val3[k]=L_gas[k];\n        Fout.write((char*)val3,sizeof(val)*3);\n\n        val=q_gas;\n        Fout.write((char*)&val,sizeof(val));\n        val=s_gas;\n        Fout.write((char*)&val,sizeof(val));\n        for (int k=0;k<3;k++) for (int n=0;n<3;n++) val9[k*3+n]=eigvec_gas(k,n);\n        Fout.write((char*)val9,sizeof(val)*9);\n\n        val=Krot_gas;\n        Fout.write((char*)&val,sizeof(val));\n        val=Temp_gas;\n        Fout.write((char*)&val,sizeof(val));\n\n#ifdef STARON\n        val=Z_gas;\n        Fout.write((char*)&val,sizeof(val));\n        val=SFR_gas;\n        Fout.write((char*)&val,sizeof(val));\n#endif\n#endif\n\n#ifdef STARON\n        idval=n_star;\n        Fout.write((char*)&idval,sizeof(idval));\n        val=M_star;\n        Fout.write((char*)&val,sizeof(val));\n        val=M_star_rvmax;\n        Fout.write((char*)&val,sizeof(val));\n        val=M_star_30kpc;\n        Fout.write((char*)&val,sizeof(val));\n        val=M_star_500c;\n        Fout.write((char*)&val,sizeof(val));\n\n        for (int k=0;k<3;k++) val3[k]=cm_star[k];\n        Fout.write((char*)val3,sizeof(val)*3);\n        for (int k=0;k<3;k++) val3[k]=cmvel_star[k];\n        Fout.write((char*)val3,sizeof(val)*3);\n\n        val=Efrac_star;\n        Fout.write((char*)&val,sizeof(val));\n\n        val=Rhalfmass_star;\n        Fout.write((char*)&val,sizeof(val));\n\n        for (int k=0;k<3;k++) for (int n=0;n<3;n++) val9[k*3+n]=veldisp_star(k,n);\n        Fout.write((char*)val9,sizeof(val)*9);\n\n        for (int k=0;k<3;k++) val3[k]=L_star[k];\n        Fout.write((char*)val3,sizeof(val)*3);\n\n        val=q_star;\n        Fout.write((char*)&val,sizeof(val));\n        val=s_star;\n        Fout.write((char*)&val,sizeof(val));\n        for (int k=0;k<3;k++) for (int n=0;n<3;n++) val9[k*3+n]=eigvec_star(k,n);\n        Fout.write((char*)val9,sizeof(val)*9);\n\n        val=Krot_star;\n        Fout.write((char*)&val,sizeof(val));\n        val=t_star;\n        Fout.write((char*)&val,sizeof(val));\n        val=Z_star;\n        Fout.write((char*)&val,sizeof(val));\n\n#endif\n\n#ifdef BHON\n        idval=n_bh;\n        Fout.write((char*)&idval,sizeof(idval));\n        val=M_bh;\n        Fout.write((char*)&val,sizeof(val));\n#endif\n#ifdef HIGHRES\n        idval=n_interloper;\n        Fout.write((char*)&idval,sizeof(idval));\n        val=M_interloper;\n        Fout.write((char*)&val,sizeof(val));\n#endif\n    }\n\n    ///write (append) the properties data to an already open ascii file\n    void WriteAscii(fstream &Fout, Options&opt){\n        Fout<<haloid<<\" \";\n        Fout<<ibound<<\" \";\n        Fout<<hostid<<\" \";\n        Fout<<numsubs<<\" \";\n        Fout<<num<<\" \";\n        Fout<<stype<<\" \";\n        if (opt.iKeepFOF==1) {\n            Fout<<directhostid<<\" \";\n            Fout<<hostfofid<<\" \";\n        }\n        Fout<<gMvir<<\" \";\n        for (int k=0;k<3;k++) Fout<<gcm[k]<<\" \";\n        for (int k=0;k<3;k++) Fout<<gpos[k]<<\" \";\n        for (int k=0;k<3;k++) Fout<<gcmvel[k]<<\" \";\n        for (int k=0;k<3;k++) Fout<<gvel[k]<<\" \";\n        Fout<<gmass<<\" \";\n        Fout<<gMFOF<<\" \";\n        Fout<<gM200m<<\" \";\n        Fout<<gM200c<<\" \";\n        Fout<<gMBN98<<\" \";\n        Fout<<Efrac<<\" \";\n        Fout<<gRvir<<\" \";\n        Fout<<gsize<<\" \";\n        Fout<<gR200m<<\" \";\n        Fout<<gR200c<<\" \";\n        Fout<<gRBN98<<\" \";\n        Fout<<gRhalfmass<<\" \";\n        Fout<<gRmaxvel<<\" \";\n        Fout<<gmaxvel<<\" \";\n        Fout<<gsigma_v<<\" \";\n        for (int k=0;k<3;k++) for (int n=0;n<3;n++) Fout<<gveldisp(k,n)<<\" \";\n        Fout<<glambda_B<<\" \";\n        for (int k=0;k<3;k++) Fout<<gJ[k]<<\" \";\n        Fout<<gq<<\" \";\n        Fout<<gs<<\" \";\n        for (int k=0;k<3;k++) for (int n=0;n<3;n++) Fout<<geigvec(k,n)<<\" \";\n        Fout<<cNFW<<\" \";\n        Fout<<Krot<<\" \";\n        Fout<<T<<\" \";\n        Fout<<Pot<<\" \";\n\n        Fout<<RV_sigma_v<<\" \";\n        for (int k=0;k<3;k++) for (int n=0;n<3;n++) Fout<<RV_veldisp(k,n)<<\" \";\n        Fout<<RV_lambda_B<<\" \";\n        for (int k=0;k<3;k++) Fout<<RV_J[k]<<\" \";\n        Fout<<RV_q<<\" \";\n        Fout<<RV_s<<\" \";\n        for (int k=0;k<3;k++) for (int n=0;n<3;n++) Fout<<RV_eigvec(k,n)<<\" \";\n\n#ifdef GASON\n        Fout<<n_gas<<\" \";\n        Fout<<M_gas<<\" \";\n        Fout<<M_gas_rvmax<<\" \";\n        Fout<<M_gas_30kpc<<\" \";\n        //Fout<<M_gas_50kpc<<\" \";\n        Fout<<M_gas_500c<<\" \";\n        for (int k=0;k<3;k++) Fout<<cm_gas[k]<<\" \";\n        for (int k=0;k<3;k++) Fout<<cmvel_gas[k]<<\" \";\n        Fout<<Efrac_gas<<\" \";\n        Fout<<Rhalfmass_gas<<\" \";\n        for (int k=0;k<3;k++) for (int n=0;n<3;n++) Fout<<veldisp_gas(k,n)<<\" \";\n        for (int k=0;k<3;k++) Fout<<L_gas[k]<<\" \";\n        Fout<<q_gas<<\" \";\n        Fout<<s_gas<<\" \";\n        for (int k=0;k<3;k++) for (int n=0;n<3;n++) Fout<<eigvec_gas(k,n)<<\" \";\n        Fout<<Krot_gas<<\" \";\n        Fout<<Temp_gas<<\" \";\n#ifdef STARON\n        Fout<<Z_gas<<\" \";\n        Fout<<SFR_gas<<\" \";\n#endif\n#endif\n\n#ifdef STARON\n        Fout<<n_star<<\" \";\n        Fout<<M_star<<\" \";\n        Fout<<M_star_rvmax<<\" \";\n        Fout<<M_star_30kpc<<\" \";\n        //Fout<<M_star_50kpc<<\" \";\n        Fout<<M_star_500c<<\" \";\n        for (int k=0;k<3;k++) Fout<<cm_star[k]<<\" \";\n        for (int k=0;k<3;k++) Fout<<cmvel_star[k]<<\" \";\n        Fout<<Efrac_star<<\" \";\n        Fout<<Rhalfmass_star<<\" \";\n        for (int k=0;k<3;k++) for (int n=0;n<3;n++) Fout<<veldisp_star(k,n)<<\" \";\n        for (int k=0;k<3;k++) Fout<<L_star[k]<<\" \";\n        Fout<<q_star<<\" \";\n        Fout<<s_star<<\" \";\n        for (int k=0;k<3;k++) for (int n=0;n<3;n++) Fout<<eigvec_star(k,n)<<\" \";\n        Fout<<Krot_star<<\" \";\n        Fout<<t_star<<\" \";\n        Fout<<Z_star<<\" \";\n#endif\n\n#ifdef BHON\n        Fout<<n_bh<<\" \";\n        Fout<<M_bh<<\" \";\n#endif\n#ifdef HIGHRES\n        Fout<<n_interloper<<\" \";\n        Fout<<M_interloper<<\" \";\n#endif\n        Fout<<endl;\n    }\n#ifdef USEHDF\n    ///write (append) the properties data to an already open hdf file\n    void WriteHDF(H5File &Fhdf, DataSpace *&dataspaces, DataSet *&datasets, Options&opt){\n    };\n#endif\n};\n\n/*! Structures stores header info of the data writen by the \\ref PropData data structure,\n    specifically the \\ref PropData::WriteBinary, \\ref PropData::WriteAscii, \\ref PropData::WriteHDF routines\n    Must ensure that these routines are all altered together so that the io makes sense.\n*/\nstruct PropDataHeader{\n    //list the header info\n    vector<string> headerdatainfo;\n#ifdef USEHDF\n    vector<PredType> predtypeinfo;\n#endif\n#ifdef USEADIOS\n    vector<ADIOS_DATATYPES> adiospredtypeinfo;\n#endif\n    PropDataHeader(Options&opt){\n        int sizeval;\n#ifdef USEHDF\n        vector<PredType> desiredproprealtype;\n        if (sizeof(Double_t)==sizeof(double)) desiredproprealtype.push_back(PredType::NATIVE_DOUBLE);\n        else desiredproprealtype.push_back(PredType::NATIVE_FLOAT);\n#endif\n#ifdef USEADIOS\n        vector<ADIOS_DATATYPES> desiredadiosproprealtype;\n        if (sizeof(Double_t)==sizeof(double)) desiredadiosproprealtype.push_back(ADIOS_DATATYPES::adios_double);\n        else desiredadiosproprealtype.push_back(ADIOS_DATATYPES::adios_real);\n#endif\n\n        headerdatainfo.push_back(\"ID\");\n        headerdatainfo.push_back(\"ID_mbp\");\n        headerdatainfo.push_back(\"hostHaloID\");\n        headerdatainfo.push_back(\"numSubStruct\");\n        headerdatainfo.push_back(\"npart\");\n        headerdatainfo.push_back(\"Structuretype\");\n        if (opt.iKeepFOF==1){\n            headerdatainfo.push_back(\"hostDirectHaloID\");\n            headerdatainfo.push_back(\"hostFOFID\");\n        }\n\n        //if using hdf, store the type\n#ifdef USEHDF\n        predtypeinfo.push_back(PredType::STD_U64LE);\n        predtypeinfo.push_back(PredType::STD_I64LE);\n        predtypeinfo.push_back(PredType::STD_I64LE);\n        predtypeinfo.push_back(PredType::STD_U64LE);\n        predtypeinfo.push_back(PredType::STD_U64LE);\n        predtypeinfo.push_back(PredType::STD_I32LE);\n        if (opt.iKeepFOF==1){\n            predtypeinfo.push_back(PredType::STD_I64LE);\n            predtypeinfo.push_back(PredType::STD_I64LE);\n        }\n#endif\n#ifdef USEADIOS\n        adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_long);\n        adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_long);\n        adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_integer);\n        if (opt.iKeepFOF==1){\n            adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_long);\n            adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_long);\n        }\n#endif\n\n        headerdatainfo.push_back(\"Mvir\");\n        headerdatainfo.push_back(\"Xc\");\n        headerdatainfo.push_back(\"Yc\");\n        headerdatainfo.push_back(\"Zc\");\n        headerdatainfo.push_back(\"Xcmbp\");\n        headerdatainfo.push_back(\"Ycmbp\");\n        headerdatainfo.push_back(\"Zcmbp\");\n        headerdatainfo.push_back(\"VXc\");\n        headerdatainfo.push_back(\"VYc\");\n        headerdatainfo.push_back(\"VZc\");\n        headerdatainfo.push_back(\"VXcmbp\");\n        headerdatainfo.push_back(\"VYcmbp\");\n        headerdatainfo.push_back(\"VZcmbp\");\n        headerdatainfo.push_back(\"Mass_tot\");\n        headerdatainfo.push_back(\"Mass_FOF\");\n        headerdatainfo.push_back(\"Mass_200mean\");\n        headerdatainfo.push_back(\"Mass_200crit\");\n        headerdatainfo.push_back(\"Mass_BN98\");\n        headerdatainfo.push_back(\"Efrac\");\n        headerdatainfo.push_back(\"Rvir\");\n        headerdatainfo.push_back(\"R_size\");\n        headerdatainfo.push_back(\"R_200mean\");\n        headerdatainfo.push_back(\"R_200crit\");\n        headerdatainfo.push_back(\"R_BN98\");\n        headerdatainfo.push_back(\"R_HalfMass\");\n        headerdatainfo.push_back(\"Rmax\");\n        headerdatainfo.push_back(\"Vmax\");\n        headerdatainfo.push_back(\"sigV\");\n        headerdatainfo.push_back(\"veldisp_xx\");\n        headerdatainfo.push_back(\"veldisp_xy\");\n        headerdatainfo.push_back(\"veldisp_xz\");\n        headerdatainfo.push_back(\"veldisp_yx\");\n        headerdatainfo.push_back(\"veldisp_yy\");\n        headerdatainfo.push_back(\"veldisp_yz\");\n        headerdatainfo.push_back(\"veldisp_zx\");\n        headerdatainfo.push_back(\"veldisp_zy\");\n        headerdatainfo.push_back(\"veldisp_zz\");\n        headerdatainfo.push_back(\"lambda_B\");\n        headerdatainfo.push_back(\"Lx\");\n        headerdatainfo.push_back(\"Ly\");\n        headerdatainfo.push_back(\"Lz\");\n        headerdatainfo.push_back(\"q\");\n        headerdatainfo.push_back(\"s\");\n        headerdatainfo.push_back(\"eig_xx\");\n        headerdatainfo.push_back(\"eig_xy\");\n        headerdatainfo.push_back(\"eig_xz\");\n        headerdatainfo.push_back(\"eig_yx\");\n        headerdatainfo.push_back(\"eig_yy\");\n        headerdatainfo.push_back(\"eig_yz\");\n        headerdatainfo.push_back(\"eig_zx\");\n        headerdatainfo.push_back(\"eig_zy\");\n        headerdatainfo.push_back(\"eig_zz\");\n        headerdatainfo.push_back(\"cNFW\");\n        headerdatainfo.push_back(\"Krot\");\n        headerdatainfo.push_back(\"Ekin\");\n        headerdatainfo.push_back(\"Epot\");\n\n        //some properties within RVmax\n        headerdatainfo.push_back(\"RVmax_sigV\");\n        headerdatainfo.push_back(\"RVmax_veldisp_xx\");\n        headerdatainfo.push_back(\"RVmax_veldisp_xy\");\n        headerdatainfo.push_back(\"RVmax_veldisp_xz\");\n        headerdatainfo.push_back(\"RVmax_veldisp_yx\");\n        headerdatainfo.push_back(\"RVmax_veldisp_yy\");\n        headerdatainfo.push_back(\"RVmax_veldisp_yz\");\n        headerdatainfo.push_back(\"RVmax_veldisp_zx\");\n        headerdatainfo.push_back(\"RVmax_veldisp_zy\");\n        headerdatainfo.push_back(\"RVmax_veldisp_zz\");\n        headerdatainfo.push_back(\"RVmax_lambda_B\");\n        headerdatainfo.push_back(\"RVmax_Lx\");\n        headerdatainfo.push_back(\"RVmax_Ly\");\n        headerdatainfo.push_back(\"RVmax_Lz\");\n        headerdatainfo.push_back(\"RVmax_q\");\n        headerdatainfo.push_back(\"RVmax_s\");\n        headerdatainfo.push_back(\"RVmax_eig_xx\");\n        headerdatainfo.push_back(\"RVmax_eig_xy\");\n        headerdatainfo.push_back(\"RVmax_eig_xz\");\n        headerdatainfo.push_back(\"RVmax_eig_yx\");\n        headerdatainfo.push_back(\"RVmax_eig_yy\");\n        headerdatainfo.push_back(\"RVmax_eig_yz\");\n        headerdatainfo.push_back(\"RVmax_eig_zx\");\n        headerdatainfo.push_back(\"RVmax_eig_zy\");\n        headerdatainfo.push_back(\"RVmax_eig_zz\");\n\n#ifdef USEHDF\n        sizeval=predtypeinfo.size();\n        for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(desiredproprealtype[0]);\n#endif\n#ifdef USEADIOS\n        sizeval=adiospredtypeinfo.size();\n        for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(desiredadiosproprealtype[0]);\n#endif\n\n#ifdef GASON\n        headerdatainfo.push_back(\"n_gas\");\n#ifdef USEHDF\n        predtypeinfo.push_back(PredType::STD_U64LE);\n#endif\n#ifdef USEADIOS\n        adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n#endif\n        headerdatainfo.push_back(\"M_gas\");\n        headerdatainfo.push_back(\"M_gas_Rvmax\");\n        headerdatainfo.push_back(\"M_gas_30kpc\");\n        //headerdatainfo.push_back(\"M_gas_50kpc\");\n        headerdatainfo.push_back(\"M_gas_500c\");\n        headerdatainfo.push_back(\"Xc_gas\");\n        headerdatainfo.push_back(\"Yc_gas\");\n        headerdatainfo.push_back(\"Zc_gas\");\n        headerdatainfo.push_back(\"VXc_gas\");\n        headerdatainfo.push_back(\"VYc_gas\");\n        headerdatainfo.push_back(\"VZc_gas\");\n        headerdatainfo.push_back(\"Efrac_gas\");\n        headerdatainfo.push_back(\"R_HalfMass_gas\");\n        headerdatainfo.push_back(\"veldisp_xx_gas\");\n        headerdatainfo.push_back(\"veldisp_xy_gas\");\n        headerdatainfo.push_back(\"veldisp_xz_gas\");\n        headerdatainfo.push_back(\"veldisp_yx_gas\");\n        headerdatainfo.push_back(\"veldisp_yy_gas\");\n        headerdatainfo.push_back(\"veldisp_yz_gas\");\n        headerdatainfo.push_back(\"veldisp_zx_gas\");\n        headerdatainfo.push_back(\"veldisp_zy_gas\");\n        headerdatainfo.push_back(\"veldisp_zz_gas\");\n        headerdatainfo.push_back(\"Lx_gas\");\n        headerdatainfo.push_back(\"Ly_gas\");\n        headerdatainfo.push_back(\"Lz_gas\");\n        headerdatainfo.push_back(\"q_gas\");\n        headerdatainfo.push_back(\"s_gas\");\n        headerdatainfo.push_back(\"eig_xx_gas\");\n        headerdatainfo.push_back(\"eig_xy_gas\");\n        headerdatainfo.push_back(\"eig_xz_gas\");\n        headerdatainfo.push_back(\"eig_yx_gas\");\n        headerdatainfo.push_back(\"eig_yy_gas\");\n        headerdatainfo.push_back(\"eig_yz_gas\");\n        headerdatainfo.push_back(\"eig_zx_gas\");\n        headerdatainfo.push_back(\"eig_zy_gas\");\n        headerdatainfo.push_back(\"eig_zz_gas\");\n        headerdatainfo.push_back(\"Krot_gas\");\n        headerdatainfo.push_back(\"T_gas\");\n#ifdef STARON\n        headerdatainfo.push_back(\"Zmet_gas\");\n        headerdatainfo.push_back(\"SFR_gas\");\n#endif\n#ifdef USEHDF\n        sizeval=predtypeinfo.size();\n        for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(desiredproprealtype[0]);\n#endif\n#ifdef USEADIOS\n        sizeval=adiospredtypeinfo.size();\n        for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(desiredadiosproprealtype[0]);\n#endif\n#endif\n\n#ifdef STARON\n        headerdatainfo.push_back(\"n_star\");\n#ifdef USEHDF\n        predtypeinfo.push_back(PredType::STD_U64LE);\n#endif\n#ifdef USEADIOS\n        adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n#endif\n        headerdatainfo.push_back(\"M_star\");\n        headerdatainfo.push_back(\"M_star_Rvmax\");\n        headerdatainfo.push_back(\"M_star_30kpc\");\n        //headerdatainfo.push_back(\"M_star_50kpc\");\n        headerdatainfo.push_back(\"M_star_500c\");\n        headerdatainfo.push_back(\"Xc_star\");\n        headerdatainfo.push_back(\"Yc_star\");\n        headerdatainfo.push_back(\"Zc_star\");\n        headerdatainfo.push_back(\"VXc_star\");\n        headerdatainfo.push_back(\"VYc_star\");\n        headerdatainfo.push_back(\"VZc_star\");\n        headerdatainfo.push_back(\"Efrac_star\");\n        headerdatainfo.push_back(\"R_HalfMass_star\");\n        headerdatainfo.push_back(\"veldisp_xx_star\");\n        headerdatainfo.push_back(\"veldisp_xy_star\");\n        headerdatainfo.push_back(\"veldisp_xz_star\");\n        headerdatainfo.push_back(\"veldisp_yx_star\");\n        headerdatainfo.push_back(\"veldisp_yy_star\");\n        headerdatainfo.push_back(\"veldisp_yz_star\");\n        headerdatainfo.push_back(\"veldisp_zx_star\");\n        headerdatainfo.push_back(\"veldisp_zy_star\");\n        headerdatainfo.push_back(\"veldisp_zz_star\");\n        headerdatainfo.push_back(\"Lx_star\");\n        headerdatainfo.push_back(\"Ly_star\");\n        headerdatainfo.push_back(\"Lz_star\");\n        headerdatainfo.push_back(\"q_star\");\n        headerdatainfo.push_back(\"s_star\");\n        headerdatainfo.push_back(\"eig_xx_star\");\n        headerdatainfo.push_back(\"eig_xy_star\");\n        headerdatainfo.push_back(\"eig_xz_star\");\n        headerdatainfo.push_back(\"eig_yx_star\");\n        headerdatainfo.push_back(\"eig_yy_star\");\n        headerdatainfo.push_back(\"eig_yz_star\");\n        headerdatainfo.push_back(\"eig_zx_star\");\n        headerdatainfo.push_back(\"eig_zy_star\");\n        headerdatainfo.push_back(\"eig_zz_star\");\n        headerdatainfo.push_back(\"Krot_star\");\n        headerdatainfo.push_back(\"tage_star\");\n        headerdatainfo.push_back(\"Zmet_star\");\n#ifdef USEHDF\n        sizeval=predtypeinfo.size();\n        for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(desiredproprealtype[0]);\n#endif\n#ifdef USEADIOS\n        sizeval=adiospredtypeinfo.size();\n        for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(desiredadiosproprealtype[0]);\n#endif\n#endif\n\n#ifdef BHON\n        headerdatainfo.push_back(\"n_bh\");\n#ifdef USEHDF\n        predtypeinfo.push_back(PredType::STD_U64LE);\n#endif\n#ifdef USEADIOS\n        adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n#endif\n        headerdatainfo.push_back(\"M_bh\");\n#ifdef USEHDF\n        sizeval=predtypeinfo.size();\n        for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(desiredproprealtype[0]);\n#endif\n#ifdef USEADIOS\n        sizeval=adiospredtypeinfo.size();\n        for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(desiredadiosproprealtype[0]);\n#endif\n#endif\n\n\n#ifdef HIGHRES\n        headerdatainfo.push_back(\"n_interloper\");\n#ifdef USEHDF\n        predtypeinfo.push_back(PredType::STD_U64LE);\n#endif\n#ifdef USEADIOS\n        adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n#endif\n        headerdatainfo.push_back(\"M_interloper\");\n#ifdef USEHDF\n        sizeval=predtypeinfo.size();\n        for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(desiredproprealtype[0]);\n#endif\n#ifdef USEADIOS\n        sizeval=adiospredtypeinfo.size();\n        for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(desiredadiosproprealtype[0]);\n#endif\n#endif\n        //additional information about a halo\n        if (opt.iextrahalooutput) {\n\n        }\n\n    }\n};\n\n/*! Structure used to keep track of a structure's parent structure\n    note that level could be sim->halo->subhalo->subsubhalo\n    or even sim->wall/void/filament->halo->substructure->subsubstructure\n    here sim is stype=0,gid=0, and the other structure types are to be defined.\n    The data structure is meant to be traversed from\n        - level 0 structures (\"field\" objects)\n        - level 0 pointer to nextlevel\n        - nextlevel containing nginlevel objects\n*/\nstruct StrucLevelData\n{\n    ///structure type and number in current level of hierarchy\n    Int_t stype,nsinlevel;\n    ///points to the the head pfof address of the group and parent\n    Particle **Phead;\n    Int_t **gidhead;\n    ///parent pointers point to the address of the parents gidhead and Phead\n    Particle **Pparenthead;\n    Int_t **gidparenthead;\n    ///add uber parent pointer (that is pointer to field halo)\n    Int_t **giduberparenthead;\n    ///allowing for multiple structure types at a given level in the hierarchy\n    Int_t *stypeinlevel;\n    StrucLevelData *nextlevel;\n    StrucLevelData(Int_t numgroups=-1){\n        if (numgroups<=0) {\n            Phead=NULL;\n            Pparenthead=NULL;\n            gidhead=NULL;\n            gidparenthead=NULL;\n            giduberparenthead=NULL;\n            nextlevel=NULL;\n            stypeinlevel=NULL;\n            nsinlevel=0;\n        }\n        else Allocate(numgroups);\n    }\n    ///just allocate memory\n    void Allocate(Int_t numgroups){\n        nsinlevel=numgroups;\n        Phead=new Particle*[numgroups+1];\n        gidhead=new Int_t*[numgroups+1];\n        stypeinlevel=new Int_t[numgroups+1];\n        gidparenthead=new Int_t*[numgroups+1];\n        giduberparenthead=new Int_t*[numgroups+1];\n        nextlevel=NULL;\n    }\n    ///initialize\n    void Initialize(){\n        for (Int_t i=1;i<=nsinlevel;i++) {gidhead[i]=NULL;gidparenthead[i]=NULL;giduberparenthead[i]=NULL;}\n    }\n    ~StrucLevelData(){\n        if (nextlevel!=NULL) delete nextlevel;\n        nextlevel=NULL;\n        if (nsinlevel>0) {\n            delete[] Phead;\n            delete[] gidhead;\n            delete[] stypeinlevel;\n            delete[] gidparenthead;\n            delete[] giduberparenthead;\n        }\n    }\n};\n\n#if defined(USEHDF)||defined(USEADIOS)\n///store the names of datasets in catalog output\nstruct DataGroupNames {\n    ///store names of catalog group files\n    vector<string> prop;\n#ifdef USEHDF\n    //store the data type\n    vector<PredType> propdatatype;\n#endif\n#ifdef USEADIOS\n    vector<ADIOS_DATATYPES> adiospropdatatype;\n#endif\n\n    ///store names of catalog group files\n    vector<string> group;\n#ifdef USEHDF\n    vector<PredType> groupdatatype;\n#endif\n#ifdef USEADIOS\n    vector<ADIOS_DATATYPES> adiosgroupdatatype;\n#endif\n\n    ///store the names of catalog particle files\n    vector<string> part;\n#ifdef USEHDF\n    vector<PredType> partdatatype;\n#endif\n#ifdef USEADIOS\n    vector<ADIOS_DATATYPES> adiospartdatatype;\n#endif\n\n    ///store the names of catalog particle files\n    vector<string> types;\n#ifdef USEHDF\n    vector<PredType> typesdatatype;\n#endif\n#ifdef USEADIOS\n    vector<ADIOS_DATATYPES> adiostypesdatatype;\n#endif\n\n    ///store the names of catalog particle files\n    vector<string> hierarchy;\n#ifdef USEHDF\n    vector<PredType> hierarchydatatype;\n#endif\n#ifdef USEADIOS\n    vector<ADIOS_DATATYPES> adioshierarchydatatype;\n#endif\n\n    ///store names of catalog group files\n    vector<string> SO;\n#ifdef USEHDF\n    vector<PredType> SOdatatype;\n#endif\n#ifdef USEADIOS\n    vector<ADIOS_DATATYPES> SOdatatype;\n#endif\n\n    DataGroupNames(){\n        prop.push_back(\"File_id\");\n        prop.push_back(\"Num_of_files\");\n        prop.push_back(\"Num_of_groups\");\n        prop.push_back(\"Total_num_of_groups\");\n        prop.push_back(\"Cosmological_Sim\");\n        prop.push_back(\"Comoving_or_Physical\");\n        prop.push_back(\"Period\");\n        prop.push_back(\"Time\");\n        prop.push_back(\"Length_unit_to_kpc\");\n        prop.push_back(\"Velocity_to_kms\");\n        prop.push_back(\"Mass_unit_to_solarmass\");\n#ifdef USEHDF\n        propdatatype.push_back(PredType::STD_I32LE);\n        propdatatype.push_back(PredType::STD_I32LE);\n        propdatatype.push_back(PredType::STD_U64LE);\n        propdatatype.push_back(PredType::STD_U64LE);\n        propdatatype.push_back(PredType::STD_U32LE);\n        propdatatype.push_back(PredType::STD_U32LE);\n        propdatatype.push_back(PredType::NATIVE_FLOAT);\n        propdatatype.push_back(PredType::NATIVE_FLOAT);\n        propdatatype.push_back(PredType::NATIVE_FLOAT);\n        propdatatype.push_back(PredType::NATIVE_FLOAT);\n        propdatatype.push_back(PredType::NATIVE_FLOAT);\n#endif\n#ifdef USEADIOS\n        adiospropdatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adiospropdatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adiospropdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiospropdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiospropdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_integer);\n        adiospropdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_integer);\n        adiospropdatatype.push_back(ADIOS_DATATYPES::adios_real);\n        adiospropdatatype.push_back(ADIOS_DATATYPES::adios_real);\n        adiospropdatatype.push_back(ADIOS_DATATYPES::adios_real);\n        adiospropdatatype.push_back(ADIOS_DATATYPES::adios_real);\n        adiospropdatatype.push_back(ADIOS_DATATYPES::adios_real);\n#endif\n\n        group.push_back(\"File_id\");\n        group.push_back(\"Num_of_files\");\n        group.push_back(\"Num_of_groups\");\n        group.push_back(\"Total_num_of_groups\");\n        group.push_back(\"Group_Size\");\n        group.push_back(\"Offset\");\n        group.push_back(\"Offset_unbound\");\n#ifdef USEHDF\n        groupdatatype.push_back(PredType::STD_I32LE);\n        groupdatatype.push_back(PredType::STD_I32LE);\n        groupdatatype.push_back(PredType::STD_U64LE);\n        groupdatatype.push_back(PredType::STD_U64LE);\n        groupdatatype.push_back(PredType::STD_U32LE);\n        groupdatatype.push_back(PredType::STD_U64LE);\n        groupdatatype.push_back(PredType::STD_U64LE);\n#endif\n#ifdef USEADIOS\n        adiosgroupdatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adiosgroupdatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adiosgroupdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiosgroupdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiosgroupdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_integer);\n        adiosgroupdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiosgroupdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n#endif\n\n        part.push_back(\"File_id\");\n        part.push_back(\"Num_of_files\");\n        part.push_back(\"Num_of_particles_in_groups\");\n        part.push_back(\"Total_num_of_particles_in_all_groups\");\n        part.push_back(\"Particle_IDs\");\n#ifdef USEHDF\n        partdatatype.push_back(PredType::STD_I32LE);\n        partdatatype.push_back(PredType::STD_I32LE);\n        partdatatype.push_back(PredType::STD_U64LE);\n        partdatatype.push_back(PredType::STD_U64LE);\n        partdatatype.push_back(PredType::STD_I64LE);\n#endif\n#ifdef USEADIOS\n        adiospartdatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adiospartdatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adiospartdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiospartdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiospartdatatype.push_back(ADIOS_DATATYPES::adios_long);\n#endif\n\n        types.push_back(\"File_id\");\n        types.push_back(\"Num_of_files\");\n        types.push_back(\"Num_of_particles_in_groups\");\n        types.push_back(\"Total_num_of_particles_in_all_groups\");\n        types.push_back(\"Particle_types\");\n#ifdef USEHDF\n        typesdatatype.push_back(PredType::STD_I32LE);\n        typesdatatype.push_back(PredType::STD_I32LE);\n        typesdatatype.push_back(PredType::STD_U64LE);\n        typesdatatype.push_back(PredType::STD_U64LE);\n        typesdatatype.push_back(PredType::STD_U16LE);\n#endif\n#ifdef USEADIOS\n        adiostypesdatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adiostypesdatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adiostypesdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiostypesdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiostypesdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_short);\n#endif\n\n        hierarchy.push_back(\"File_id\");\n        hierarchy.push_back(\"Num_of_files\");\n        hierarchy.push_back(\"Num_of_groups\");\n        hierarchy.push_back(\"Total_num_of_groups\");\n        hierarchy.push_back(\"Number_of_substructures_in_halo\");\n        hierarchy.push_back(\"Parent_halo_ID\");\n#ifdef USEHDF\n        hierarchydatatype.push_back(PredType::STD_I32LE);\n        hierarchydatatype.push_back(PredType::STD_I32LE);\n        hierarchydatatype.push_back(PredType::STD_U64LE);\n        hierarchydatatype.push_back(PredType::STD_U64LE);\n        hierarchydatatype.push_back(PredType::STD_U32LE);\n        hierarchydatatype.push_back(PredType::STD_I64LE);\n#endif\n#ifdef USEADIOS\n        adioshierarchydatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adioshierarchydatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adioshierarchydatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adioshierarchydatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adioshierarchydatatype.push_back(ADIOS_DATATYPES::adios_unsigned_integer);\n        adioshierarchydatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n#endif\n        SO.push_back(\"File_id\");\n        SO.push_back(\"Num_of_files\");\n        SO.push_back(\"Num_of_SO_regions\");\n        SO.push_back(\"Total_num_of_SO_regions\");\n        SO.push_back(\"Num_of_particles_in_SO_regions\");\n        SO.push_back(\"Total_num_of_particles_in_SO_regions\");\n        SO.push_back(\"SO_size\");\n        SO.push_back(\"Offset\");\n        SO.push_back(\"Particle_IDs\");\n#ifdef USEHDF\n        SOdatatype.push_back(PredType::STD_I32LE);\n        SOdatatype.push_back(PredType::STD_I32LE);\n        SOdatatype.push_back(PredType::STD_U64LE);\n        SOdatatype.push_back(PredType::STD_U64LE);\n        SOdatatype.push_back(PredType::STD_U64LE);\n        SOdatatype.push_back(PredType::STD_U64LE);\n        SOdatatype.push_back(PredType::STD_U32LE);\n        SOdatatype.push_back(PredType::STD_U64LE);\n        SOdatatype.push_back(PredType::STD_I64LE);\n#endif\n#ifdef USEADIOS\n        adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_integer);\n        adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_integer);\n        adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long);\n        adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_long);\n#endif\n    }\n};\n#endif\n\n///if using MPI API\n#ifdef USEMPI\n#include <mpi.h>\n///Includes external global variables used for MPI version of code\n#include \"mpivar.h\"\n#endif\n\nextern StrucLevelData *psldata;\n\n#endif\n", "meta": {"hexsha": "4ffada1de5ec148c5200017196530d8ad80fdbaf", "size": 76946, "ext": "h", "lang": "C", "max_stars_repo_path": "stf/src/allvars.h", "max_stars_repo_name": "broukema/VELOCIraptor-STF", "max_stars_repo_head_hexsha": "f18cb8bf088065f9361fc537d4e5858962499a21", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stf/src/allvars.h", "max_issues_repo_name": "broukema/VELOCIraptor-STF", "max_issues_repo_head_hexsha": "f18cb8bf088065f9361fc537d4e5858962499a21", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stf/src/allvars.h", "max_forks_repo_name": "broukema/VELOCIraptor-STF", "max_forks_repo_head_hexsha": "f18cb8bf088065f9361fc537d4e5858962499a21", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7072620659, "max_line_length": 224, "alphanum_fraction": 0.6640761053, "num_tokens": 20814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29421497216298875, "lm_q2_score": 0.021615331777862058, "lm_q1q2_score": 0.006359554237317451}}
{"text": "/**\n * \\file BaseFilter.h\n */\n\n#ifndef ATK_CORE_BASEFILTER_H\n#define ATK_CORE_BASEFILTER_H\n\n#include <cstdint>\n#include <string>\n#include <vector>\n\n#include <boost/dynamic_bitset/dynamic_bitset.hpp>\n#include <gsl/gsl>\n\n#include <ATK/config.h>\n#include <ATK/Core/config.h>\n\n#if ATK_PROFILING == 1\n#include <chrono>\n#endif\n\n#if ATK_USE_THREADPOOL == 1\n#include <tbb/queuing_mutex.h>\n#endif\n\nnamespace ATK\n{\n  /// Base class for all filters\n  class BaseFilter\n  {\n  public:\n    BaseFilter(const BaseFilter&) = delete;\n    BaseFilter& operator=(const BaseFilter&) = delete;\n    /*!\n     * @brief Constructor for the core filter\n     * @param nb_input_ports is the total number of input ports of this filter\n     * @param nb_output_ports is the total number of output ports of this filter\n     */\n    ATK_CORE_EXPORT BaseFilter(gsl::index nb_input_ports, gsl::index nb_output_ports);\n    /// Move constructor\n    ATK_CORE_EXPORT BaseFilter(BaseFilter&& other) noexcept;\n    /// Destructor\n    virtual ATK_CORE_EXPORT ~BaseFilter();\n    \n    /*!\n     * @brief Links this filter port to another filter's output port\n     * @param input_port is the port number where this filter will receive something\n     * @param filter is a pointer to the previous filter\n     * @param output_port is the port number where this filter will be connected\n     */\n    ATK_CORE_EXPORT virtual void set_input_port(gsl::index input_port, gsl::not_null<BaseFilter*> filter, gsl::index output_port) = 0;\n    ATK_CORE_EXPORT virtual void set_input_port(gsl::index input_port, BaseFilter& filter, gsl::index output_port);\n    \n    /// Starts processing after calling reset\n    ATK_CORE_EXPORT void process(gsl::index size);\n    /// As process, but doesn't call process_impl\n    ATK_CORE_EXPORT void dryrun(gsl::index size);\n\n#if ATK_USE_THREADPOOL == 1\n    /// Allows threaded processing\n    ATK_CORE_EXPORT void process_parallel(gsl::index size);\n#endif\n\n    /*!\n     * @brief Setup the input sampling rate, must be in sync with the rest of the pipeline\n     * @param rate is the input sampling rate of the plugin\n     */\n    ATK_CORE_EXPORT void set_input_sampling_rate(gsl::index rate);\n    /// Returns this filter internal input sampling rate\n    ATK_CORE_EXPORT gsl::index get_input_sampling_rate() const;\n    /*!\n    * @brief Setup the output sampling rate, must be in sync with the rest of the pipeline\n    * @param rate is the output sampling rate of the plugin\n    */\n    ATK_CORE_EXPORT void set_output_sampling_rate(gsl::index rate);\n    /// Returns this filter internal output sampling rate\n    ATK_CORE_EXPORT gsl::index get_output_sampling_rate() const;\n    \n    /// Returns this filter number of input ports\n    ATK_CORE_EXPORT gsl::index get_nb_input_ports() const;\n    /*!\n    * @brief Changes the number of input ports\n    * Will trigger a full setup\n    * @param nb_ports is the new number of input ports of the plugin\n    */\n    ATK_CORE_EXPORT virtual void set_nb_input_ports(gsl::index nb_ports);\n    /// Returns this filter number of input ports\n    ATK_CORE_EXPORT gsl::index get_nb_output_ports() const;\n    /*!\n    * @brief Changes the number of output ports\n    * Will trigger a full setup\n    * @param nb_ports is the new number of output ports of the plugin\n    */\n    ATK_CORE_EXPORT virtual void set_nb_output_ports(gsl::index nb_ports);\n    /// Returns this filter input delay (additional pre-0 samples)\n    ATK_CORE_EXPORT void set_input_delay(gsl::index delay);\n    /// Returns this filter input delay (additional pre-0 samples)\n    ATK_CORE_EXPORT gsl::index get_input_delay() const;\n    /// Returns this filter output delay (additional pre-0 samples)\n    ATK_CORE_EXPORT void set_output_delay(gsl::index delay);\n    /// Returns this filter output delay (additional pre-0 samples)\n    ATK_CORE_EXPORT gsl::index get_output_delay() const;\n    /*!\n    * @brief Changes the filter's latency\n    * @param latency is the new latency\n    */\n    ATK_CORE_EXPORT virtual void set_latency(gsl::index latency);\n    /// Returns this filter latency\n    ATK_CORE_EXPORT gsl::index get_latency() const;\n    /// Returns the pipeline global latency from this plugin\n    ATK_CORE_EXPORT gsl::index get_global_latency() const;\n\n    /// Resets the internal state of the filter (mandatory before processing a new clip in a DAW for instance)\n    ATK_CORE_EXPORT virtual void full_setup();\n\n    /// Resets the filter so that it will process something if needed\n    void reset();\n    /// Returns the type that the filter processes\n    virtual int get_type() const = 0;\n    /// Starts processing without calling reset\n    template<bool must_process>\n    void process_conditionnally(gsl::index size);\n#if ATK_USE_THREADPOOL == 1\n    /// Starts parallel processing without calling reset\n    void process_conditionnally_parallel(gsl::index size);\n#endif\n  \n  protected:\n    /// The actual filter processing part\n    virtual void process_impl(gsl::index size) const = 0;\n\n    /// Prepares the filter by retrieving the inputs arrays\n    virtual void prepare_process(gsl::index size) = 0;\n    /// Prepares the filter by resizing the outputs arrays\n    virtual void prepare_outputs(gsl::index size) = 0;\n    /// Changes the internal check to allow a disconnected input port\n    void allow_inactive_connection(unsigned int port);\n    \n    /// Use this call to recompute internal parameters\n    ATK_CORE_EXPORT virtual void setup();\n\n    /// Number of input ports\n    gsl::index nb_input_ports = 0;\n    /// Number of output ports\n    gsl::index nb_output_ports = 0;\n    /// Input sampling rate of the plugin\n    gsl::index input_sampling_rate = 0;\n    /// Output sampling rate of the plugin\n    gsl::index output_sampling_rate = 0;\n    /// The connections to the output pins of some filters\n    std::vector<std::pair<gsl::index, BaseFilter*> > connections;\n\n    /// Input delay of the input port\n    gsl::index input_delay = 0;\n    /// Output delay of the input port\n    gsl::index output_delay = 0;\n    \n    /// Latency of the plugin\n    gsl::index latency = 0;\n    /// Last processed size\n    gsl::index last_size = 0;\n\n  private:\n    boost::dynamic_bitset<> input_mandatory_connection;\n    bool is_reset = false;\n#if ATK_PROFILING == 1\n    std::string class_name;\n    std::chrono::steady_clock::duration input_conversion_time;\n    std::chrono::steady_clock::duration output_conversion_time;\n    std::chrono::steady_clock::duration process_time;\n#endif\n#if ATK_USE_THREADPOOL == 1\n    tbb::queuing_mutex mutex;\n#endif\n  };\n}\n\n#endif\n\n", "meta": {"hexsha": "e13fbaa86ecfbe7e363c594c816936a08ef825f9", "size": 6507, "ext": "h", "lang": "C", "max_stars_repo_path": "ATK/Core/BaseFilter.h", "max_stars_repo_name": "D-J-Roberts/AudioTK", "max_stars_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 249.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T13:36:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T18:47:46.000Z", "max_issues_repo_path": "ATK/Core/BaseFilter.h", "max_issues_repo_name": "D-J-Roberts/AudioTK", "max_issues_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2015-07-28T15:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-11T14:18:19.000Z", "max_forks_repo_path": "ATK/Core/BaseFilter.h", "max_forks_repo_name": "D-J-Roberts/AudioTK", "max_forks_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 48.0, "max_forks_repo_forks_event_min_datetime": "2015-08-15T12:08:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-07T02:33:07.000Z", "avg_line_length": 36.15, "max_line_length": 134, "alphanum_fraction": 0.7144613493, "num_tokens": 1500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23651624720889436, "lm_q2_score": 0.026759284737740304, "lm_q1q2_score": 0.00632900560416458}}
{"text": "#ifndef PyGSL_ERROR_HELPER_H\n#define PyGSL_ERROR_HELPER_H 1\n#include <pygsl/intern.h>\n#include <pygsl/utils.h>\n#include <gsl/gsl_errno.h>\n#include <pygsl/errorno.h>\n\n/*\n * 22 Sep. 2009 Pierre Schnizer\n * Uncomment only if trouble with the gsl error handler (e.g. when using\n * Python with threading support (typical ufuncs). At the time of this writing\n * the error handler would call python to find the approbriate python exception\n *\n * So I used to uncomment the macro as well as the function to ensure that \n * gsl_error was not called any more within the pygsl wrappper\n */\n/*\n#undef GSL_ERROR\n#undef GSL_ERROR_VAL\n#undef GSL_ERROR_NULL\n#define gsl_error()\n*/\n/*\n * handle gsl error flags.\n *\n * If a flag arrives check if there was already a python error. If so leave it alone.\n * We cannot return two exceptions. \n *\n * Otherwise:\n *       Should I put an exception up? E.g. some function not conforming to GSL \n *       Convention returning a flag, instead of calling gsl_error?\n *       Currently I follow that idea. But I have no more information about the reason\n *       than the flag.\n *\n * Return:\n *       GSL_SUCCESS ... No errornous call\n *       GSL_FAILURE ...    errornous call\n *\n * If you need to return the flag e.g. \"int gsl_odeiv_iterate( ... \" use \n * PyGSL_error_flag_to_pyint instead!\n * \n */\n\nPyGSL_API_EXTERN int  \nPyGSL_error_flag(long flag);\n\n/*\n * Handles gsl_error flags.\n * It differs from the above that it returns the integer. \n *\n * Negative values mean something like go one with the iteration. These are \n * converted to an python integer. Positive values flag a problem. These are \n * converted to python exceptions.\n */\nPyGSL_API_EXTERN PyObject * \nPyGSL_error_flag_to_pyint(long flag);\n\n\n/*\n * Add a Python trace back frame to the python interpreter.\n * Input :\n *     module   ... the module. Pass NULL if not known.\n *     filename ... The filename to list in the stack frame. Pass NULL if not \n *                  known.\n *     funcname ... The function name to list in the stack frame. Pass NULL if\n *                  not known.\n *     lineno   ... The Linenumber where the error occurred.\n */\nPyGSL_API_EXTERN void \nPyGSL_add_traceback(PyObject *module, const char *filename, const char *funcname, int lineno);\n\nPyGSL_API_EXTERN int\nPyGSL_warning(const char *, const char*, int, int);\n\n#ifndef _PyGSL_API_MODULE\n/* Section for modules importing the functions */\n#define PyGSL_error_flag           (*(int (*)(long))                                         PyGSL_API[PyGSL_error_flag_NUM])\n#define PyGSL_error_flag_to_pyint  (*(PyObject * (*)(long))                                  PyGSL_API[PyGSL_error_flag_to_pyint_NUM])\n#define PyGSL_add_traceback        (*(void (*)(PyObject *, const char *, const char *, int)) PyGSL_API[PyGSL_add_traceback_NUM])      \n#define PyGSL_warning              (*(int (*)(const char *, const char *, int, int))         PyGSL_API[PyGSL_warning_NUM])\n\n#endif /* _PyGSL_API_MODULE */\n\n#define PyGSL_ERROR_FLAG(flag)                                              \\\n(((long) flag == GSL_SUCCESS) && (!PyErr_Occurred())) ? GSL_SUCCESS :       \\\n                     PyGSL_error_flag((long) (flag))\n\n#define PyGSL_ERROR_FLAG_TO_PYINT(flag)                                     \\\n(((long) flag <= 0) && (!PyErr_Occurred())) ? PyInt_FromLong((long) flag) : \\\n                     PyGSL_error_flag_to_pyint((long) (flag))\n\n#endif /* PyGSL_ERROR_HELPER_H  */\n", "meta": {"hexsha": "cf6f0fe2d37451ce1d933530a8ce616def0c3a9f", "size": 3427, "ext": "h", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/Include/pygsl/error_helpers.h", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/Include/pygsl/error_helpers.h", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/Include/pygsl/error_helpers.h", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 36.8494623656, "max_line_length": 134, "alphanum_fraction": 0.6609279253, "num_tokens": 829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22541660542786957, "lm_q2_score": 0.028007523749820695, "lm_q1q2_score": 0.0063133609301250174}}
{"text": "/*\n * Copyright 2017 Daniel Eachern Huang\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#ifndef AUGUR_HDR_H\n#define AUGUR_HDR_H\n\n#ifdef AUGURCPU\n\n\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n\ntypedef gsl_rng augur_rng;\n\n#ifndef EXTERNC\n#define EXTERNC\n#endif\n\n#ifndef __HOSTORDEV__\n#define __HOSTORDEV__\n#endif\n\n#ifndef __HOSTDEV__\n#define __HOSTDEV__\n#endif\n\n\n\n\n\n\n#else\n\n\n\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n\n#include <math.h>\n\n#include <curand.h>\n#include <curand_kernel.h>\n\n#include <thrust/transform_reduce.h>\n#include <thrust/inner_product.h>\n#include <thrust/device_ptr.h>\n#include <thrust/functional.h>\n#include <thrust/execution_policy.h>\n\ntypedef curandState_t augur_rng;\n\n#ifndef EXTERNC\n#define EXTERNC extern \"C\"\n#endif\n\n#ifndef __HOSTORDEV__\n#define __HOSTORDEV__ EXTERNC __device__\n#endif\n\n#ifndef __HOSTDEV__\n#define __HOSTDEV__ EXTERNC __host__ __device__\n#endif\n\n#define THRDS        256\n#define BLKS(x)      ((int) ceil(((double) x) / THRDS))\n\n#endif\n\n\n\n\n\n\n\n#endif\n", "meta": {"hexsha": "b061ffaa9d6aea5069351ab4f060061c4bd36897", "size": 1528, "ext": "h", "lang": "C", "max_stars_repo_path": "cbits/augur_hdr.h", "max_stars_repo_name": "rjnw/augurv2", "max_stars_repo_head_hexsha": "0430482297e81288d58a16d43a98ea9d0196d640", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2017-03-06T19:51:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-18T15:07:41.000Z", "max_issues_repo_path": "cbits/augur_hdr.h", "max_issues_repo_name": "rjnw/augurv2", "max_issues_repo_head_hexsha": "0430482297e81288d58a16d43a98ea9d0196d640", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-09-20T19:18:13.000Z", "max_issues_repo_issues_event_max_datetime": "2017-09-20T19:38:00.000Z", "max_forks_repo_path": "cbits/augur_hdr.h", "max_forks_repo_name": "rjnw/augurv2", "max_forks_repo_head_hexsha": "0430482297e81288d58a16d43a98ea9d0196d640", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-10-10T21:55:18.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-18T20:17:36.000Z", "avg_line_length": 17.1685393258, "max_line_length": 75, "alphanum_fraction": 0.7467277487, "num_tokens": 390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24220562872535947, "lm_q2_score": 0.025957357857117395, "lm_q1q2_score": 0.006287018179832268}}
{"text": "// Copyright (C) 2015 Vincent Lejeune\n// For conditions of distribution and use, see copyright notice in License.txt\n#pragma once\n\n#include <vector>\n#include <tuple>\n#include <array>\n#include <memory>\n#include <gsl/gsl>\n#include <variant>\n#include <optional>\n#include \"..\\Core\\SColor.h\"\n\nnamespace irr\n{\n\tnamespace video\n\t{\n\t\tenum class E_INDEX_TYPE\n\t\t{\n\t\t\tEIT_16BIT,\n\t\t\tEIT_32BIT\n\t\t};\n\n\t\tenum class E_POLYGON_MODE\n\t\t{\n\t\t\tEPM_FILL,\n\t\t\tEPM_LINE,\n\t\t\tEPM_POINT\n\t\t};\n\n\t\tenum class E_CULL_MODE\n\t\t{\n\t\t\tECM_NONE,\n\t\t\tECM_FRONT,\n\t\t\tECM_BACK,\n\t\t\tECM_FRONT_AND_BACK\n\t\t};\n\n\t\tenum class E_FRONT_FACE\n\t\t{\n\t\t\tEFF_CCW,\n\t\t\tEFF_CW\n\t\t};\n\n\t\tenum class E_SAMPLE_COUNT\n\t\t{\n\t\t\tESC_1,\n\t\t\tESC_2,\n\t\t\tESC_4,\n\t\t\tESC_8\n\t\t};\n\n\t\tenum class E_PRIMITIVE_TYPE\n\t\t{\n\t\t\tEPT_POINTS,\n\t\t\tEPT_LINE_STRIP,\n\t\t\tEPT_LINES,\n\t\t\tEPT_TRIANGLE_STRIP,\n\t\t\tEPT_TRIANGLES,\n\t\t};\n\n\t\tenum class E_COMPARE_FUNCTION\n\t\t{\n\t\t\tECF_LESS,\n\t\t\tECF_LEQUAL,\n\t\t\tECF_NEVER,\n\t\t};\n\n\t\tenum class E_STENCIL_OP\n\t\t{\n\t\t\tESO_KEEP,\n\t\t};\n\n\t\tenum class E_ASPECT\n\t\t{\n\t\t\tEA_COLOR,\n\t\t\tEA_DEPTH,\n\t\t\tEA_STENCIL,\n\t\t\tEA_DEPTH_STENCIL\n\t\t};\n\n\t\tenum class E_MEMORY_POOL\n\t\t{\n\t\t\tEMP_CPU_WRITEABLE,\n\t\t\tEMP_GPU_LOCAL,\n\t\t\tEMP_CPU_READABLE,\n\t\t};\n\n\t\tenum class E_TEXTURE_TYPE\n\t\t{\n\t\t\tETT_2D,\n\t\t\tETT_CUBE,\n\t\t};\n\t}\n}\n\nenum class RESOURCE_USAGE\n{\n\tPRESENT,\n\tCOPY_DEST,\n\tCOPY_SRC,\n\tRENDER_TARGET,\n\tREAD_GENERIC,\n\tDEPTH_WRITE,\n\tundefined,\n\tuav,\n};\n\nenum image_flags\n{\n\tusage_transfer_src = 0x1,\n\tusage_transfer_dst = 0x2,\n\tusage_sampled = 0x4,\n\tusage_render_target = 0x8,\n\tusage_depth_stencil = 0x10,\n\tusage_input_attachment = 0x20,\n\tusage_cube = 0x40,\n};\n\nenum buffer_flags\n{\n\tnone = 0,\n\tusage_uav = 0x1,\n\tusage_texel_buffer = 0x2,\n    usage_buffer_transfer_src = 0x4,\n\tusage_uniform = 0x8,\n\tusage_index = 0x10,\n\tusage_vertex = 0x20,\n};\n\nenum class SAMPLER_TYPE\n{\n\tNEAREST,\n\tBILINEAR_CLAMPED,\n\tTRILINEAR,\n\tANISOTROPIC,\n};\n\nstruct MipLevelData\n{\n\tuint64_t Offset;\n\tuint32_t Width;\n\tuint32_t Height;\n\tuint32_t RowPitch;\n};\n\n\nenum class RESOURCE_VIEW\n{\n\tCONSTANTS_BUFFER,\n\tINPUT_ATTACHMENT,\n\tSHADER_RESOURCE,\n\tTEXEL_BUFFER,\n\tSAMPLER,\n\tUAV_BUFFER,\n\tUAV_IMAGE,\n};\n\nenum class shader_stage\n{\n\tvertex_shader,\n\tfragment_shader,\n\tall,\n};\n\n\n\nstruct range_of_descriptors\n{\n\tconst RESOURCE_VIEW range_type;\n\tconst uint32_t bind_point;\n\tconst uint32_t count;\n\n\tconstexpr range_of_descriptors(const RESOURCE_VIEW rt, const uint32_t bindpoint, const uint32_t range_size)\n\t\t: range_type(rt), bind_point(bindpoint), count(range_size)\n\t{}\n};\n\nstruct descriptor_set\n{\n\tconst std::vector<range_of_descriptors> descriptors_ranges;\n\tconst shader_stage stage;\n\n\tdescriptor_set(const std::initializer_list<range_of_descriptors>& ranges, const shader_stage& st)\n\t\t: descriptors_ranges(ranges), stage(st)\n\t{ }\n};\n\nstruct pipeline_vertex_attributes\n{\n\tuint32_t location;\n\tirr::video::ECOLOR_FORMAT format;\n\tuint32_t binding;\n\tuint32_t stride;\n\tuint32_t offset;\n};\n/*\tVkPipelineColorBlendAttachmentState blend_attachment_state{ true, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE , VK_BLEND_OP_ADD, VK_BLEND_FACTOR_ONE , VK_BLEND_FACTOR_ONE , VK_BLEND_OP_ADD, -1 };\nVkPipelineColorBlendStateCreateInfo blend_state{ VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, nullptr, 0, false, VK_LOGIC_OP_NO_OP, 1, &blend_attachment_state };*/\n\nenum class blend_factor\n{\n\tzero,\n\tone,\n};\n\nenum class blend_op\n{\n\tadd\n};\n\nstruct color_output\n{\n\tbool blend;\n\tblend_op op;\n\tblend_factor src_color;\n\tblend_factor src_alpha;\n\tblend_factor dst_color;\n\tblend_factor dst_alpha;\n};\n\nstruct compute_pipeline_state_description\n{\n\tstd::vector<uint32_t> compute_binary;\n\n\tcompute_pipeline_state_description set_compute_shader(gsl::span<const uint32_t> code)\n\t{\n\t\tstd::copy(code.begin(), code.end(), std::back_inserter(compute_binary));\n\t\treturn *this;\n\t}\n};\n\nstruct graphic_pipeline_state_description\n{\n\tstd::vector<uint32_t> vertex_binary;\n\tstd::vector<uint32_t> fragment_binary;\n\n\n\tstd::vector<pipeline_vertex_attributes> attributes;\n\tstd::vector<color_output> color_outputs;\n\n\tbool rasterization_depth_clamp_enable;\n\tbool rasterization_discard_enable;\n\tirr::video::E_POLYGON_MODE rasterization_polygon_mode;\n\tirr::video::E_CULL_MODE rasterization_cull_mode;\n\tirr::video::E_FRONT_FACE rasterization_front_face;\n\tbool rasterization_depth_bias_enable;\n\tfloat rasterization_depth_bias_constant_factor;\n\tfloat rasterization_depth_bias_clamp;\n\tfloat rasterization_depth_bias_slope_factor;\n\tfloat rasterization_line_width;\n\tbool rasterization_conservative_enable;\n\n\tbool multisample_multisample_enable;\n\tirr::video::E_SAMPLE_COUNT multisample_sample_count;\n\tfloat multisample_min_sample_shading;\n\t// sample mask ?\n\tbool multisample_alpha_to_coverage;\n\tbool multisample_alpha_to_one;\n\n\tirr::video::E_PRIMITIVE_TYPE input_assembly_topology;\n\tbool input_assembly_primitive_restart;\n\n\tbool depth_stencil_depth_test;\n\tbool depth_stencil_depth_write;\n\tirr::video::E_COMPARE_FUNCTION depth_stencil_depth_compare_op;\n\tbool depth_stencil_depth_clip_enable;\n\tbool depth_stencil_stencil_test;\n\tirr::video::E_STENCIL_OP depth_stencil_front_stencil_fail_op;\n\tirr::video::E_STENCIL_OP depth_stencil_front_stencil_depth_fail_op;\n\tirr::video::E_STENCIL_OP depth_stencil_front_stencil_pass_op;\n\tirr::video::E_COMPARE_FUNCTION depth_stencil_front_stencil_compare_op;\n\tirr::video::E_STENCIL_OP depth_stencil_back_stencil_fail_op;\n\tirr::video::E_STENCIL_OP depth_stencil_back_stencil_depth_fail_op;\n\tirr::video::E_STENCIL_OP depth_stencil_back_stencil_pass_op;\n\tirr::video::E_COMPARE_FUNCTION depth_stencil_back_stencil_compare_op;\n\tfloat depth_stencil_min_depth_clip;\n\tfloat depth_stencil_max_depth_clip;\n\n\tstatic graphic_pipeline_state_description get()\n\t{\n\t\treturn graphic_pipeline_state_description(false, false, irr::video::E_POLYGON_MODE::EPM_FILL, irr::video::E_CULL_MODE::ECM_BACK, irr::video::E_FRONT_FACE::EFF_CW, false, 0.f, 0.f, 0.f, 1.f, false,\n\t\t\tfalse, irr::video::E_SAMPLE_COUNT::ESC_1, 0.f, false, false, irr::video::E_PRIMITIVE_TYPE::EPT_TRIANGLES, false, true, true, irr::video::E_COMPARE_FUNCTION::ECF_LESS, false, false,\n\t\t\tirr::video::E_STENCIL_OP::ESO_KEEP, irr::video::E_STENCIL_OP::ESO_KEEP, irr::video::E_STENCIL_OP::ESO_KEEP, irr::video::E_COMPARE_FUNCTION::ECF_NEVER,\n\t\t\tirr::video::E_STENCIL_OP::ESO_KEEP, irr::video::E_STENCIL_OP::ESO_KEEP, irr::video::E_STENCIL_OP::ESO_KEEP, irr::video::E_COMPARE_FUNCTION::ECF_NEVER,\n\t\t\t0.f, 1.f);\n\t}\n\n\tgraphic_pipeline_state_description set_depth_compare_function(irr::video::E_COMPARE_FUNCTION depth_compare) const\n\t{\n\t\treturn graphic_pipeline_state_description(rasterization_depth_clamp_enable,\n\t\t\trasterization_discard_enable,\n\t\t\trasterization_polygon_mode,\n\t\t\trasterization_cull_mode,\n\t\t\trasterization_front_face,\n\t\t\trasterization_depth_bias_enable,\n\t\t\trasterization_depth_bias_constant_factor,\n\t\t\trasterization_depth_bias_clamp,\n\t\t\trasterization_depth_bias_slope_factor,\n\t\t\trasterization_line_width,\n\t\t\trasterization_conservative_enable,\n\t\t\tmultisample_multisample_enable,\n\t\t\tmultisample_sample_count,\n\t\t\tmultisample_min_sample_shading,\n\t\t\tmultisample_alpha_to_coverage,\n\t\t\tmultisample_alpha_to_one,\n\t\t\tinput_assembly_topology,\n\t\t\tinput_assembly_primitive_restart,\n\t\t\tdepth_stencil_depth_test,\n\t\t\tdepth_stencil_depth_write,\n\t\t\tdepth_compare,\n\t\t\tdepth_stencil_depth_clip_enable,\n\t\t\tdepth_stencil_stencil_test,\n\t\t\tdepth_stencil_front_stencil_fail_op,\n\t\t\tdepth_stencil_front_stencil_depth_fail_op,\n\t\t\tdepth_stencil_front_stencil_pass_op,\n\t\t\tdepth_stencil_front_stencil_compare_op,\n\t\t\tdepth_stencil_back_stencil_fail_op,\n\t\t\tdepth_stencil_back_stencil_depth_fail_op,\n\t\t\tdepth_stencil_back_stencil_pass_op,\n\t\t\tdepth_stencil_back_stencil_compare_op,\n\t\t\tdepth_stencil_min_depth_clip,\n\t\t\tdepth_stencil_max_depth_clip);\n\t}\n\n\tgraphic_pipeline_state_description set_depth_write(bool depthwrite) const\n\t{\n\t\treturn graphic_pipeline_state_description(rasterization_depth_clamp_enable,\n\t\t\trasterization_discard_enable,\n\t\t\trasterization_polygon_mode,\n\t\t\trasterization_cull_mode,\n\t\t\trasterization_front_face,\n\t\t\trasterization_depth_bias_enable,\n\t\t\trasterization_depth_bias_constant_factor,\n\t\t\trasterization_depth_bias_clamp,\n\t\t\trasterization_depth_bias_slope_factor,\n\t\t\trasterization_line_width,\n\t\t\trasterization_conservative_enable,\n\t\t\tmultisample_multisample_enable,\n\t\t\tmultisample_sample_count,\n\t\t\tmultisample_min_sample_shading,\n\t\t\tmultisample_alpha_to_coverage,\n\t\t\tmultisample_alpha_to_one,\n\t\t\tinput_assembly_topology,\n\t\t\tinput_assembly_primitive_restart,\n\t\t\tdepth_stencil_depth_test,\n\t\t\tdepthwrite,\n\t\t\tdepth_stencil_depth_compare_op,\n\t\t\tdepth_stencil_depth_clip_enable,\n\t\t\tdepth_stencil_stencil_test,\n\t\t\tdepth_stencil_front_stencil_fail_op,\n\t\t\tdepth_stencil_front_stencil_depth_fail_op,\n\t\t\tdepth_stencil_front_stencil_pass_op,\n\t\t\tdepth_stencil_front_stencil_compare_op,\n\t\t\tdepth_stencil_back_stencil_fail_op,\n\t\t\tdepth_stencil_back_stencil_depth_fail_op,\n\t\t\tdepth_stencil_back_stencil_pass_op,\n\t\t\tdepth_stencil_back_stencil_compare_op,\n\t\t\tdepth_stencil_min_depth_clip,\n\t\t\tdepth_stencil_max_depth_clip);\n\t}\n\n\tgraphic_pipeline_state_description set_depth_test(bool depth_test) const\n\t{\n\t\treturn graphic_pipeline_state_description(rasterization_depth_clamp_enable,\n\t\t\trasterization_discard_enable,\n\t\t\trasterization_polygon_mode,\n\t\t\trasterization_cull_mode,\n\t\t\trasterization_front_face,\n\t\t\trasterization_depth_bias_enable,\n\t\t\trasterization_depth_bias_constant_factor,\n\t\t\trasterization_depth_bias_clamp,\n\t\t\trasterization_depth_bias_slope_factor,\n\t\t\trasterization_line_width,\n\t\t\trasterization_conservative_enable,\n\t\t\tmultisample_multisample_enable,\n\t\t\tmultisample_sample_count,\n\t\t\tmultisample_min_sample_shading,\n\t\t\tmultisample_alpha_to_coverage,\n\t\t\tmultisample_alpha_to_one,\n\t\t\tinput_assembly_topology,\n\t\t\tinput_assembly_primitive_restart,\n\t\t\tdepth_test,\n\t\t\tdepth_stencil_depth_write,\n\t\t\tdepth_stencil_depth_compare_op,\n\t\t\tdepth_stencil_depth_clip_enable,\n\t\t\tdepth_stencil_stencil_test,\n\t\t\tdepth_stencil_front_stencil_fail_op,\n\t\t\tdepth_stencil_front_stencil_depth_fail_op,\n\t\t\tdepth_stencil_front_stencil_pass_op,\n\t\t\tdepth_stencil_front_stencil_compare_op,\n\t\t\tdepth_stencil_back_stencil_fail_op,\n\t\t\tdepth_stencil_back_stencil_depth_fail_op,\n\t\t\tdepth_stencil_back_stencil_pass_op,\n\t\t\tdepth_stencil_back_stencil_compare_op,\n\t\t\tdepth_stencil_min_depth_clip,\n\t\t\tdepth_stencil_max_depth_clip);\n\t}\n\n\tgraphic_pipeline_state_description set_vertex_shader(gsl::span<const uint32_t> binary)\n\t{\n\t\tstd::copy(binary.begin(), binary.end(), std::back_inserter(vertex_binary));\n\t\treturn *this;\n\t}\n\n\tgraphic_pipeline_state_description set_fragment_shader(gsl::span<const uint32_t> binary)\n\t{\n\t\tstd::copy(binary.begin(), binary.end(), std::back_inserter(fragment_binary));\n\t\treturn *this;\n\t}\n\n\tgraphic_pipeline_state_description set_vertex_attributes(const gsl::span<pipeline_vertex_attributes> &attributes_)\n\t{\n\t\tattributes = std::vector<pipeline_vertex_attributes>(attributes_.begin(), attributes_.end());\n\t\treturn *this;\n\t}\n\n\tgraphic_pipeline_state_description set_color_outputs(const gsl::span<color_output> &color_outputs_)\n\t{\n\t\tcolor_outputs = std::vector<color_output>(color_outputs_.begin(), color_outputs_.end());\n\t\treturn *this;\n\t}\n\n\tgraphic_pipeline_state_description()\n\t{\n\n\t}\n\nprivate:\n\tgraphic_pipeline_state_description(\n\t\tbool depth_clamp_enable,\n\t\tbool rasterizer_discard_enable,\n\t\tirr::video::E_POLYGON_MODE polygon_mode,\n\t\tirr::video::E_CULL_MODE cull_mode,\n\t\tirr::video::E_FRONT_FACE front_face,\n\t\tbool depth_bias_enable,\n\t\tfloat depth_bias_constant_factor,\n\t\tfloat depth_bias_clamp,\n\t\tfloat depth_bias_slope_factor,\n\t\tfloat line_width,\n\t\tbool conservative_enable,\n\t\tbool multisample_enable,\n\t\tirr::video::E_SAMPLE_COUNT sample_count,\n\t\tfloat min_sample_shading,\n\t\tbool alpha_to_coverage,\n\t\tbool alpha_to_one,\n\t\tirr::video::E_PRIMITIVE_TYPE topology,\n\t\tbool primitive_restart,\n\t\tbool depth_test,\n\t\tbool depth_write,\n\t\tirr::video::E_COMPARE_FUNCTION depth_compare_op,\n\t\tbool depth_clip_enable,\n\t\tbool stencil_test,\n\t\tirr::video::E_STENCIL_OP front_stencil_fail_op,\n\t\tirr::video::E_STENCIL_OP front_stencil_depth_fail_op,\n\t\tirr::video::E_STENCIL_OP front_stencil_pass_op,\n\t\tirr::video::E_COMPARE_FUNCTION front_stencil_compare_op,\n\t\tirr::video::E_STENCIL_OP back_stencil_fail_op,\n\t\tirr::video::E_STENCIL_OP back_stencil_depth_fail_op,\n\t\tirr::video::E_STENCIL_OP back_stencil_pass_op,\n\t\tirr::video::E_COMPARE_FUNCTION back_stencil_compare_op,\n\t\tfloat min_depth_clip,\n\t\tfloat max_depth_clip\n\t)\n\t\t: rasterization_depth_clamp_enable(depth_clamp_enable),\n\t\trasterization_discard_enable(rasterizer_discard_enable),\n\t\trasterization_polygon_mode(polygon_mode),\n\t\trasterization_cull_mode(cull_mode),\n\t\trasterization_front_face(front_face),\n\t\trasterization_depth_bias_enable(depth_bias_enable),\n\t\trasterization_depth_bias_constant_factor(depth_bias_constant_factor),\n\t\trasterization_depth_bias_clamp(depth_bias_clamp),\n\t\trasterization_depth_bias_slope_factor(depth_bias_slope_factor),\n\t\trasterization_line_width(line_width),\n\t\trasterization_conservative_enable(conservative_enable),\n\t\tmultisample_multisample_enable(multisample_enable),\n\t\tmultisample_sample_count(sample_count),\n\t\tmultisample_min_sample_shading(min_sample_shading),\n\t\tmultisample_alpha_to_coverage(alpha_to_coverage),\n\t\tmultisample_alpha_to_one(alpha_to_one),\n\t\tinput_assembly_topology(topology),\n\t\tinput_assembly_primitive_restart(primitive_restart),\n\t\tdepth_stencil_depth_test(depth_test),\n\t\tdepth_stencil_depth_write(depth_write),\n\t\tdepth_stencil_depth_compare_op(depth_compare_op),\n\t\tdepth_stencil_depth_clip_enable(depth_clip_enable),\n\t\tdepth_stencil_stencil_test(stencil_test),\n\t\tdepth_stencil_front_stencil_fail_op(front_stencil_fail_op),\n\t\tdepth_stencil_front_stencil_depth_fail_op(front_stencil_depth_fail_op),\n\t\tdepth_stencil_front_stencil_pass_op(front_stencil_pass_op),\n\t\tdepth_stencil_front_stencil_compare_op(front_stencil_compare_op),\n\t\tdepth_stencil_back_stencil_fail_op(back_stencil_fail_op),\n\t\tdepth_stencil_back_stencil_depth_fail_op(back_stencil_depth_fail_op),\n\t\tdepth_stencil_back_stencil_pass_op(back_stencil_pass_op),\n\t\tdepth_stencil_back_stencil_compare_op(back_stencil_compare_op),\n\t\tdepth_stencil_min_depth_clip(min_depth_clip),\n\t\tdepth_stencil_max_depth_clip(max_depth_clip)\n\t{ }\n};\n\nstruct framebuffer_t {\n\tvirtual ~framebuffer_t() {}\n};\n\nstruct pipeline_state_t {\n\tvirtual ~pipeline_state_t() {}\n};\n\nstruct compute_pipeline_state_t {\n\tvirtual ~compute_pipeline_state_t() {}\n};\n\nstruct pipeline_layout_t {\n\tvirtual ~pipeline_layout_t() {}\n};\n\nstruct render_pass_t {\n\tvirtual ~render_pass_t() {}\n};\n\nusing clear_value_t = std::variant<std::array<float, 4>, std::tuple<float, uint8_t> >;\n\nstruct image_view_t {\n\tvirtual ~image_view_t() {}\n};\n\nstruct sampler_t {\n\tvirtual ~sampler_t() {}\n};\n\nstruct buffer_view_t {\n\tvirtual ~buffer_view_t() {}\n};\n\nstruct allocated_descriptor_set {\n};\n\nstruct descriptor_set_layout {\n\tvirtual ~descriptor_set_layout() {}\n};\n\nstruct buffer_t {\n\tvirtual void* map_buffer() = 0;\n\tvirtual void unmap_buffer() = 0;\n\n\tvirtual ~buffer_t() {}\n};\n\nstruct image_t {\n\tvirtual ~image_t() {}\n};\n\nstruct descriptor_storage_t {\n\tvirtual std::unique_ptr<allocated_descriptor_set> allocate_descriptor_set_from_cbv_srv_uav_heap(uint32_t starting_index, const std::vector<descriptor_set_layout*> layouts, uint32_t descriptors_count) = 0;\n\tvirtual std::unique_ptr<allocated_descriptor_set> allocate_descriptor_set_from_sampler_heap(uint32_t starting_index, const std::vector<descriptor_set_layout*> layouts, uint32_t descriptors_count) = 0;\n\tvirtual ~descriptor_storage_t() {};\n};\n\nstruct command_list_t {\n\tvirtual void bind_graphic_descriptor(uint32_t bindpoint, const allocated_descriptor_set& descriptor_set, pipeline_layout_t& sig) = 0;\n\tvirtual void bind_compute_descriptor(uint32_t bindpoint, const allocated_descriptor_set& descriptor_set, pipeline_layout_t& sig) = 0;\n\tvirtual void copy_buffer_to_image_subresource(image_t& destination_image, uint32_t destination_subresource, buffer_t& source, uint64_t offset_in_buffer,\n\t\tuint32_t width, uint32_t height, uint32_t row_pitch, irr::video::ECOLOR_FORMAT format) = 0;\n\tvirtual void set_pipeline_barrier(image_t& resource, RESOURCE_USAGE before, RESOURCE_USAGE after, uint32_t subresource, irr::video::E_ASPECT) = 0;\n\tvirtual void set_uav_flush(image_t& resource) = 0;\n\n\tvirtual void set_viewport(float x, float width, float y, float height, float min_depth, float max_depth) = 0;\n\tvirtual void set_scissor(uint32_t left, uint32_t right, uint32_t top, uint32_t bottom) = 0;\n\tvirtual void set_graphic_pipeline(pipeline_state_t& pipeline) = 0;\n\tvirtual void set_graphic_pipeline_layout(pipeline_layout_t& sig) = 0;\n\tvirtual void set_compute_pipeline(compute_pipeline_state_t& pipeline) = 0;\n\tvirtual void set_compute_pipeline_layout(pipeline_layout_t& sig) = 0;\n\tvirtual void set_descriptor_storage_referenced(descriptor_storage_t& main_heap, descriptor_storage_t* sampler_heap = nullptr) = 0;\n\tvirtual void bind_index_buffer(buffer_t& buffer, uint64_t offset, uint32_t size, irr::video::E_INDEX_TYPE type) = 0;\n\tvirtual void bind_vertex_buffers(uint32_t first_bind, const std::vector<std::tuple<buffer_t&, uint64_t, uint32_t, uint32_t> > &buffer_offset_stride_size) = 0;\n\tvirtual void draw_indexed(uint32_t index_count, uint32_t instance_count, uint32_t base_index, int32_t base_vertex, uint32_t base_instance) = 0;\n\tvirtual void draw_non_indexed(uint32_t vertex_count, uint32_t instance_count, int32_t base_vertex, uint32_t base_instance) = 0;\n\tvirtual void dispatch(uint32_t x, uint32_t y, uint32_t z) = 0;\n\tvirtual void copy_buffer(buffer_t& src, uint64_t src_offset, buffer_t& dst, uint64_t dst_offset, uint64_t size) = 0;\n\n\tvirtual void clear_depth_stencil(image_t &img, float depth) = 0;\n\tvirtual void clear_depth_stencil(image_t &img, uint8_t stencil) = 0;\n\tvirtual void clear_depth_stencil(image_t &img, float depth, uint8_t stencil) = 0;\n\tvirtual void clear_color(image_t &img, const std::array<float, 4> &clear_colors) = 0;\n\n\tvirtual void begin_renderpass(render_pass_t& rp, framebuffer_t& fbo,\n\t\tgsl::span<clear_value_t> clear_values,\n\t\tuint32_t width, uint32_t height) = 0;\n\tvirtual void next_subpass() = 0;\n\tvirtual void end_renderpass() = 0;\n\n\tvirtual void make_command_list_executable() = 0;\n\tvirtual void start_command_list_recording(struct command_list_storage_t& storage) = 0;\n};\n\nstruct semaphore_t {\n\tvirtual ~semaphore_t() {};\n};\n\nstruct fence_t {\n\tvirtual ~fence_t() {};\n};\n\n\nstruct command_list_storage_t {\n\tvirtual std::unique_ptr<command_list_t> create_command_list() = 0;\n\tvirtual void reset_command_list_storage() = 0;\n\tvirtual ~command_list_storage_t() {}\n};\n\nstruct command_queue_t {\n\tvirtual void submit_executable_command_list(command_list_t& command_list, semaphore_t* wait_sem) = 0;\n\tvirtual void wait_for_command_queue_idle() = 0;\n};\n\nstruct swap_chain_t {\n\tvirtual ~swap_chain_t() {}\n\tvirtual uint32_t get_next_backbuffer_id(semaphore_t& semaphore) = 0;\n\tvirtual std::vector<std::unique_ptr<image_t>> get_image_view_from_swap_chain() = 0;\n\tvirtual void present(command_queue_t& cmdqueue, uint32_t backbuffer_index) = 0;\n};\n\nstruct device_t {\n\tvirtual std::unique_ptr<command_list_storage_t> create_command_storage() = 0;\n\tvirtual std::unique_ptr<buffer_t> create_buffer(size_t size, irr::video::E_MEMORY_POOL memory_pool, uint32_t flags) = 0;\n\tvirtual std::unique_ptr<buffer_view_t> create_buffer_view(buffer_t&, irr::video::ECOLOR_FORMAT, uint64_t offset, uint32_t size) = 0;\n\tvirtual void set_constant_buffer_view(const allocated_descriptor_set& descriptor_set, uint32_t offset_in_set, uint32_t binding_location, buffer_t& buffer, uint32_t buffer_size, uint64_t offset_in_buffer = 0) = 0;\n\tvirtual void set_uniform_texel_buffer_view(const allocated_descriptor_set& descriptor_set, uint32_t offset_in_set, uint32_t binding_location, buffer_view_t& buffer_view) = 0;\n\tvirtual void set_uav_buffer_view(const allocated_descriptor_set& descriptor_set, uint32_t offset_in_set, uint32_t binding_location, buffer_t& buffer, uint64_t offset, uint32_t size) = 0;\n\tvirtual std::unique_ptr<image_t> create_image(irr::video::ECOLOR_FORMAT format, uint32_t width, uint32_t height, uint16_t mipmap, uint32_t layers, uint32_t flags, clear_value_t *clear_value) = 0;\n\tvirtual std::unique_ptr<image_view_t> create_image_view(image_t& img, irr::video::ECOLOR_FORMAT fmt, uint16_t base_mipmap, uint16_t mipmap_count, uint16_t base_layer, uint16_t layer_count, irr::video::E_TEXTURE_TYPE texture_type, irr::video::E_ASPECT aspect = irr::video::E_ASPECT::EA_COLOR) = 0;\n\tvirtual void set_image_view(const allocated_descriptor_set& descriptor_set, uint32_t offset, uint32_t binding_location, image_view_t& img_view) = 0;\n\tvirtual void set_input_attachment(const allocated_descriptor_set& descriptor_set, uint32_t offset, uint32_t binding_location, image_view_t& img_view) = 0;\n\tvirtual void set_uav_image_view(const allocated_descriptor_set& descriptor_set, uint32_t offset, uint32_t binding_location, image_view_t& img_view) = 0;\n\tvirtual void set_sampler(const allocated_descriptor_set& descriptor_set, uint32_t offset, uint32_t binding_location, sampler_t& sampler) = 0;\n\tvirtual std::unique_ptr<sampler_t> create_sampler(SAMPLER_TYPE sampler_type) = 0;\n\tvirtual std::unique_ptr<descriptor_storage_t> create_descriptor_storage(uint32_t num_sets, const std::vector<std::tuple<RESOURCE_VIEW, uint32_t> > &num_descriptors) = 0;\n\tvirtual std::unique_ptr<framebuffer_t> create_frame_buffer(gsl::span<const image_view_t*> render_targets, uint32_t width, uint32_t height, render_pass_t* render_pass) = 0;\n\tvirtual std::unique_ptr<framebuffer_t> create_frame_buffer(gsl::span<const image_view_t*> render_targets, const image_view_t& depth_stencil_texture, uint32_t width, uint32_t height, render_pass_t* render_pass) = 0;\n\tvirtual std::unique_ptr<descriptor_set_layout> get_object_descriptor_set(const descriptor_set &ds) = 0;\n\tvirtual std::unique_ptr<pipeline_state_t> create_graphic_pso(const graphic_pipeline_state_description&, const render_pass_t&, const pipeline_layout_t&, const uint32_t& subpass) = 0;\n\tvirtual std::unique_ptr<compute_pipeline_state_t> create_compute_pso(const compute_pipeline_state_description&, const pipeline_layout_t&) = 0;\n\tvirtual std::unique_ptr<pipeline_layout_t> create_pipeline_layout(gsl::span<const descriptor_set_layout *>) = 0;\n\tvirtual std::unique_ptr<fence_t> create_fence() = 0;\n\tvirtual std::unique_ptr<semaphore_t> create_semaphore() = 0;\n\n\tvirtual std::unique_ptr<render_pass_t> create_ibl_sky_pass(const irr::video::ECOLOR_FORMAT&) = 0;\n\tvirtual std::unique_ptr<render_pass_t> create_object_sunlight_pass(const irr::video::ECOLOR_FORMAT&) = 0;\n\tvirtual std::unique_ptr<render_pass_t> create_ssao_pass() = 0;\n\tvirtual std::unique_ptr<render_pass_t> create_blit_pass(const irr::video::ECOLOR_FORMAT& color_format) = 0;\n\n\tvirtual ~device_t() {};\n};\n\nclear_value_t get_clear_value(irr::video::ECOLOR_FORMAT format, float depth, uint8_t stencil);\nclear_value_t get_clear_value(irr::video::ECOLOR_FORMAT format, const std::array<float,4> &color);\n", "meta": {"hexsha": "ce6fe09ef845b3925e6325e6d8d5b1192f010e4e", "size": 22822, "ext": "h", "lang": "C", "max_stars_repo_path": "include/API/GfxApi.h", "max_stars_repo_name": "vlj/YAGF", "max_stars_repo_head_hexsha": "139ddc9c7d3552f383e235715713c30684b7067f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2015-04-16T19:41:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-23T23:30:18.000Z", "max_issues_repo_path": "include/API/GfxApi.h", "max_issues_repo_name": "vlj/YAGF", "max_issues_repo_head_hexsha": "139ddc9c7d3552f383e235715713c30684b7067f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2015-04-16T19:46:53.000Z", "max_issues_repo_issues_event_max_datetime": "2017-11-16T03:06:58.000Z", "max_forks_repo_path": "include/API/GfxApi.h", "max_forks_repo_name": "vlj/YAGF", "max_forks_repo_head_hexsha": "139ddc9c7d3552f383e235715713c30684b7067f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-11-18T16:23:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-31T04:40:05.000Z", "avg_line_length": 34.7896341463, "max_line_length": 297, "alphanum_fraction": 0.8121549382, "num_tokens": 5917, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2689414330889797, "lm_q2_score": 0.023330768086948492, "lm_q1q2_score": 0.006274610204370561}}
{"text": "#ifndef QDM_PARAMETERS_H\n#define QDM_PARAMETERS_H 1\n\n#include <gsl/gsl_vector.h>\n\ntypedef struct {\n  unsigned long int rng_seed;\n\n  int acc_check;\n  int burn;\n  int iter;\n  int knot_try;\n  int spline_df;\n  int thin;\n\n  double month;\n  double knot;\n\n  double tau_high;\n  double tau_low;\n\n  double theta_min;\n  double theta_tune_sd;\n\n  double xi_high;\n  double xi_low;\n  double xi_prior_mean;\n  double xi_prior_var;\n  double xi_tune_sd;\n\n  double bound;\n\n  int debug;\n  int tau_table;\n\n  bool truncate;\n} qdm_parameters;\n\nvoid\nqdm_parameters_fprint(\n    FILE *f,\n    const qdm_parameters *p\n);\n\nint\nqdm_parameters_write(\n    hid_t id,\n    const qdm_parameters *p\n);\n\nint\nqdm_parameters_read(\n    hid_t id,\n    qdm_parameters *p\n);\n\n#endif /* QDM_PARAMETERS_H */\n", "meta": {"hexsha": "a11d17c59c63173159d277e37a20473844146851", "size": 760, "ext": "h", "lang": "C", "max_stars_repo_path": "include/qdm/parameters.h", "max_stars_repo_name": "calebcase/qdm", "max_stars_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/qdm/parameters.h", "max_issues_repo_name": "calebcase/qdm", "max_issues_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-03-06T18:09:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-22T20:22:53.000Z", "max_forks_repo_path": "include/qdm/parameters.h", "max_forks_repo_name": "calebcase/qdm", "max_forks_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.1034482759, "max_line_length": 29, "alphanum_fraction": 0.7105263158, "num_tokens": 211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.17781087819190095, "lm_q2_score": 0.03514484741138068, "lm_q1q2_score": 0.0062491361821379555}}
{"text": "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT license.\n\n#pragma once\n\n#include <type_traits>\n#include <algorithm>\n#include <limits>\n#include <iostream>\n#include <cstring>\n#include \"seal/memorymanager.h\"\n#include \"seal/serialization.h\"\n#include \"seal/util/pointer.h\"\n#include \"seal/util/defines.h\"\n#include \"seal/util/common.h\"\n#ifdef SEAL_USE_MSGSL_SPAN\n#include <gsl/span>\n#endif\n\nnamespace seal\n{\n    class Ciphertext;\n\n    // Forward-declaring the deflate_size_bound function\n    namespace util::ztools\n    {\n        SEAL_NODISCARD std::size_t deflate_size_bound(std::size_t in_size) noexcept;\n    }\n\n    /**\n    A resizable container for storing an array of arithmetic data types or\n    SEAL_BYTE types (e.g., std::byte). The allocations are done from a memory\n    pool. The IntArray class is mainly intended for internal use and provides\n    the underlying data structure for Plaintext and Ciphertext classes.\n\n    @par Size and Capacity\n    IntArray allows the user to pre-allocate memory (capacity) for the array\n    in cases where the array is known to be resized in the future and memory\n    moves are to be avoided at the time of resizing. The size of the IntArray\n    can never exceed its capacity. The capacity and size can be changed using\n    the reserve and resize functions, respectively.\n\n    @par Thread Safety\n    In general, reading from IntArray is thread-safe as long as no other thread\n    is concurrently mutating it.\n    */\n    template<typename T_,\n        typename = std::enable_if_t<std::is_arithmetic<T_>::value ||\n            std::is_same<typename std::decay<T_>::type, SEAL_BYTE>::value>>\n    class IntArray\n    {\n        friend class Ciphertext;\n\n    public:\n        using T = typename std::decay<T_>::type;\n\n        /**\n        Creates a new IntArray. No memory is allocated by this constructor.\n\n        @param[in] pool The MemoryPoolHandle pointing to a valid memory pool\n        @throws std::invalid_argument if pool is uninitialized\n        */\n        IntArray(MemoryPoolHandle pool = MemoryManager::GetPool()) :\n            pool_(std::move(pool))\n        {\n            if (!pool_)\n            {\n                throw std::invalid_argument(\"pool is uninitialized\");\n            }\n        }\n\n        /**\n        Creates a new IntArray with given size.\n\n        @param[in] size The size of the array\n        @param[in] pool The MemoryPoolHandle pointing to a valid memory pool\n        @throws std::invalid_argument if pool is uninitialized\n        */\n        explicit IntArray(std::size_t size,\n            MemoryPoolHandle pool = MemoryManager::GetPool()) :\n            pool_(std::move(pool))\n        {\n            if (!pool_)\n            {\n                throw std::invalid_argument(\"pool is uninitialized\");\n            }\n\n            // Reserve memory, resize, and set to zero\n            resize(size);\n        }\n\n        /**\n        Creates a new IntArray with given capacity and size.\n\n        @param[in] capacity The capacity of the array\n        @param[in] size The size of the array\n        @param[in] pool The MemoryPoolHandle pointing to a valid memory pool\n        @throws std::invalid_argument if capacity is less than size\n        @throws std::invalid_argument if pool is uninitialized\n        */\n        explicit IntArray(std::size_t capacity, std::size_t size,\n            MemoryPoolHandle pool = MemoryManager::GetPool()) :\n            pool_(std::move(pool))\n        {\n            if (!pool_)\n            {\n                throw std::invalid_argument(\"pool is uninitialized\");\n            }\n            if (capacity < size)\n            {\n                throw std::invalid_argument(\"capacity cannot be smaller than size\");\n            }\n\n            // Reserve memory, resize, and set to zero\n            reserve(capacity);\n            resize(size);\n        }\n\n        /**\n        Creates a new IntArray with given size wrapping a given pointer. This\n        constructor allocates no memory. If the IntArray goes out of scope, the\n        Pointer object given here is destroyed. On resizing the IntArray to larger\n        size, the data will be copied over to a new allocation from the memory pool\n        pointer to by the given MemoryPoolHandle and the Pointer object given here\n        will subsequently be destroyed. Unlike the other constructors, this one\n        exposes the option of not automatically zero-filling the allocated memory.\n\n        @param[in] ptr An initial Pointer object to wrap\n        @param[in] capacity The capacity of the array\n        @param[in] size The size of the array\n        @param[in] fill_zero If true, fills ptr with zeros\n        @param[in] pool The MemoryPoolHandle pointing to a valid memory pool\n        @throws std::invalid_argument if ptr is null and capacity is positive\n        @throws std::invalid_argument if capacity is less than size\n        @throws std::invalid_argument if pool is uninitialized\n        */\n        explicit IntArray(util::Pointer<T> &&ptr,\n            std::size_t capacity, std::size_t size, bool fill_zero,\n            MemoryPoolHandle pool = MemoryManager::GetPool()) :\n            pool_(std::move(pool)),\n            capacity_(capacity)\n        {\n            if (!ptr && capacity)\n            {\n                throw std::invalid_argument(\"ptr cannot be null\");\n            }\n            if (!pool_)\n            {\n                throw std::invalid_argument(\"pool is uninitialized\");\n            }\n            if (capacity < size)\n            {\n                throw std::invalid_argument(\"capacity cannot be smaller than size\");\n            }\n\n            // Grab the given Pointer\n            data_ = std::move(ptr);\n\n            // Resize, and optionally set to zero\n            resize(size, fill_zero);\n        }\n\n        /**\n        Creates a new IntArray with given size wrapping a given pointer. This\n        constructor allocates no memory. If the IntArray goes out of scope, the\n        Pointer object given here is destroyed. On resizing the IntArray to larger\n        size, the data will be copied over to a new allocation from the memory pool\n        pointer to by the given MemoryPoolHandle and the Pointer object given here\n        will subsequently be destroyed. Unlike the other constructors, this one\n        exposes the option of not automatically zero-filling the allocated memory.\n\n        @param[in] ptr An initial Pointer object to wrap\n        @param[in] size The size of the array\n        @param[in] fill_zero If true, fills ptr with zeros\n        @param[in] pool The MemoryPoolHandle pointing to a valid memory pool\n        @throws std::invalid_argument if ptr is null and size is positive\n        @throws std::invalid_argument if pool is uninitialized\n        */\n        explicit IntArray(util::Pointer<T> &&ptr, std::size_t size, bool fill_zero,\n            MemoryPoolHandle pool = MemoryManager::GetPool()) :\n            IntArray(std::move(ptr), size, size, fill_zero, std::move(pool))\n        {\n        }\n\n        /**\n        Constructs a new IntArray by copying a given one.\n\n        @param[in] copy The IntArray to copy from\n        */\n        IntArray(const IntArray<T> &copy) :\n            pool_(MemoryManager::GetPool()),\n            capacity_(copy.size_),\n            size_(copy.size_),\n            data_(util::allocate<T>(copy.size_, pool_))\n        {\n            // Copy over value\n            std::copy_n(copy.cbegin(), copy.size_, begin());\n        }\n\n        /**\n        Constructs a new IntArray by moving a given one.\n\n        @param[in] source The IntArray to move from\n        */\n        IntArray(IntArray<T> &&source) noexcept :\n            pool_(std::move(source.pool_)),\n            capacity_(source.capacity_),\n            size_(source.size_),\n            data_(std::move(source.data_))\n        {\n        }\n\n        /**\n        Destroys the IntArray.\n        */\n        ~IntArray()\n        {\n            release();\n        }\n\n        /**\n        Returns a pointer to the beginning of the array data.\n        */\n        SEAL_NODISCARD inline T *begin() noexcept\n        {\n            return data_.get();\n        }\n\n        /**\n        Returns a constant pointer to the beginning of the array data.\n        */\n        SEAL_NODISCARD inline const T *cbegin() const noexcept\n        {\n            return data_.get();\n        }\n\n        /**\n        Returns a pointer to the end of the array data.\n        */\n        SEAL_NODISCARD inline T *end() noexcept\n        {\n            return size_ ? begin() + size_ : begin();\n        }\n\n        /**\n        Returns a constant pointer to the end of the array data.\n        */\n        SEAL_NODISCARD inline const T *cend() const noexcept\n        {\n            return size_ ? cbegin() + size_ : cbegin();\n        }\n#ifdef SEAL_USE_MSGSL_SPAN\n        /**\n        Returns a span pointing to the beginning of the IntArray.\n        */\n        SEAL_NODISCARD inline gsl::span<T> span()\n        {\n            return gsl::span<T>(\n                begin(), static_cast<std::ptrdiff_t>(size_));\n        }\n\n        /**\n        Returns a span pointing to the beginning of the IntArray.\n        */\n        SEAL_NODISCARD inline gsl::span<const T> span() const\n        {\n            return gsl::span<const T>(\n                cbegin(), static_cast<std::ptrdiff_t>(size_));\n        }\n#endif\n        /**\n        Returns a constant reference to the array element at a given index.\n        This function performs bounds checking and will throw an error if\n        the index is out of range.\n\n        @param[in] index The index of the array element\n        @throws std::out_of_range if index is out of range\n        */\n        SEAL_NODISCARD inline const T &at(std::size_t index) const\n        {\n            if (index >= size_)\n            {\n                throw std::out_of_range(\"index must be within [0, size)\");\n            }\n            return data_[index];\n        }\n\n        /**\n        Returns a reference to the array element at a given index. This\n        function performs bounds checking and will throw an error if the\n        index is out of range.\n\n        @param[in] index The index of the array element\n        @throws std::out_of_range if index is out of range\n        */\n        SEAL_NODISCARD inline T &at(std::size_t index)\n        {\n            if (index >= size_)\n            {\n                throw std::out_of_range(\"index must be within [0, size)\");\n            }\n            return data_[index];\n        }\n\n        /**\n        Returns a constant reference to the array element at a given index.\n        This function does not perform bounds checking.\n\n        @param[in] index The index of the array element\n        */\n        SEAL_NODISCARD inline const T &operator [](std::size_t index) const\n        {\n            return data_[index];\n        }\n\n        /**\n        Returns a reference to the array element at a given index. This\n        function does not perform bounds checking.\n\n        @param[in] index The index of the array element\n        */\n        SEAL_NODISCARD inline T &operator [](std::size_t index)\n        {\n            return data_[index];\n        }\n\n        /**\n        Returns whether the array has size zero.\n        */\n        SEAL_NODISCARD inline bool empty() const noexcept\n        {\n            return (size_ == 0);\n        }\n\n        /**\n        Returns the largest possible array size.\n        */\n        SEAL_NODISCARD inline std::size_t max_size() const noexcept\n        {\n            return std::numeric_limits<std::size_t>::max();\n        }\n\n        /**\n        Returns the size of the array.\n        */\n        SEAL_NODISCARD inline std::size_t size() const noexcept\n        {\n            return size_;\n        }\n\n        /**\n        Returns the capacity of the array.\n        */\n        SEAL_NODISCARD inline std::size_t capacity() const noexcept\n        {\n            return capacity_;\n        }\n\n        /**\n        Returns the currently used MemoryPoolHandle.\n        */\n        SEAL_NODISCARD inline MemoryPoolHandle pool() const noexcept\n        {\n            return pool_;\n        }\n\n        /**\n        Releases any allocated memory to the memory pool and sets the size\n        and capacity of the array to zero.\n        */\n        inline void release() noexcept\n        {\n            capacity_ = 0;\n            size_ = 0;\n            data_.release();\n        }\n\n        /**\n        Sets the size of the array to zero. The capacity is not changed.\n        */\n        inline void clear() noexcept\n        {\n            size_ = 0;\n        }\n\n        /**\n        Allocates enough memory for storing a given number of elements without\n        changing the size of the array. If the given capacity is smaller than\n        the current size, the size is automatically set to equal the new capacity.\n\n        @param[in] capacity The capacity of the array\n        */\n        inline void reserve(std::size_t capacity)\n        {\n            std::size_t copy_size = std::min(capacity, size_);\n\n            // Create new allocation and copy over value\n            auto new_data(util::allocate<T>(capacity, pool_));\n            std::copy_n(cbegin(), copy_size, new_data.get());\n            std::swap(data_, new_data);\n\n            // Set the coeff_count and capacity\n            capacity_ = capacity;\n            size_ = copy_size;\n        }\n\n        /**\n        Reallocates the array so that its capacity exactly matches its size.\n        */\n        inline void shrink_to_fit()\n        {\n            reserve(size_);\n        }\n\n        /**\n        Resizes the array to given size. When resizing to larger size the data\n        in the array remains unchanged and any new space is initialized to zero\n        if fill_zero is set to true; when resizing to smaller size the last\n        elements of the array are dropped. If the capacity is not already large\n        enough to hold the new size, the array is also reallocated.\n\n        @param[in] size The size of the array\n        @param[in] fill_zero If true, fills expanded space with zeros\n        */\n        inline void resize(std::size_t size, bool fill_zero = true)\n        {\n            if (size <= capacity_)\n            {\n                // Are we changing size to bigger within current capacity?\n                // If so, need to set top terms to zero\n                if (size > size_ && fill_zero)\n                {\n                    std::fill(end(), begin() + size, T(0));\n                }\n\n                // Set the size\n                size_ = size;\n\n                return;\n            }\n\n            // At this point we know for sure that size_ <= capacity_ < size so need\n            // to reallocate to bigger\n            auto new_data(util::allocate<T>(size, pool_));\n            std::copy_n(cbegin(), size_, new_data.get());\n            if (fill_zero)\n            {\n                std::fill(new_data.get() + size_, new_data.get() + size, T(0));\n            }\n            std::swap(data_, new_data);\n\n            // Set the coeff_count and capacity\n            capacity_ = size;\n            size_ = size;\n        }\n\n        /**\n        Copies a given IntArray to the current one.\n\n        @param[in] assign The IntArray to copy from\n        */\n        inline IntArray<T> &operator =(const IntArray<T> &assign)\n        {\n            // Check for self-assignment\n            if (this == &assign)\n            {\n                return *this;\n            }\n\n            // First resize to correct size\n            resize(assign.size_);\n\n            // Size is guaranteed to be OK now so copy over\n            std::copy_n(assign.cbegin(), assign.size_, begin());\n\n            return *this;\n        }\n\n        /**\n        Moves a given IntArray to the current one.\n\n        @param[in] assign The IntArray to move from\n        */\n        IntArray<T> &operator =(IntArray<T> &&assign) noexcept\n        {\n            capacity_ = assign.capacity_;\n            size_ = assign.size_;\n            data_ = std::move(assign.data_);\n            pool_ = std::move(assign.pool_);\n\n            return *this;\n        }\n\n        /**\n        Returns an upper bound on the size of the IntArray, as if it was written\n        to an output stream.\n\n        @param[in] compr_mode The compression mode\n        @throws std::invalid_argument if the compression mode is not supported\n        @throws std::logic_error if the size does not fit in the return type\n        */\n        SEAL_NODISCARD inline std::streamoff save_size(\n            compr_mode_type compr_mode) const\n        {\n            std::size_t members_size = Serialization::ComprSizeEstimate(\n                util::add_safe(\n                    sizeof(std::uint64_t), // size_\n                    util::mul_safe(size_, sizeof(T))), // data_\n                compr_mode);\n\n            return util::safe_cast<std::streamoff>(util::add_safe(\n                sizeof(Serialization::SEALHeader),\n                members_size\n            ));\n        }\n\n        /**\n        Saves the IntArray to an output stream. The output is in binary format\n        and not human-readable. The output stream must have the \"binary\" flag set.\n\n        @param[out] stream The stream to save the IntArray to\n        @param[in] compr_mode The desired compression mode\n        @throws std::logic_error if the data to be saved is invalid, if compression\n        mode is not supported, or if compression failed\n        @throws std::runtime_error if I/O operations failed\n        */\n        inline std::streamoff save(\n            std::ostream &stream,\n            compr_mode_type compr_mode = Serialization::compr_mode_default) const\n        {\n            using namespace std::placeholders;\n            return Serialization::Save(\n                std::bind(&IntArray<T_>::save_members, this, _1),\n                save_size(compr_mode_type::none),\n                stream, compr_mode);\n        }\n\n        /**\n        Loads a IntArray from an input stream overwriting the current IntArray.\n        This function takes optionally a bound on the size for the loaded IntArray\n        and throws an exception if the size indicated by the loaded metadata exceeds\n        the provided value. The check is omitted if in_size_bound is zero.\n\n        @param[in] stream The stream to load the IntArray from\n        @param[in] in_size_bound A bound on the size of the loaded IntArray\n        @throws std::logic_error if the loaded data is invalid, if the loaded size\n        exceeds in_size_bound, or if decompression failed\n        @throws std::runtime_error if I/O operations failed\n        */\n        inline std::streamoff load(\n            std::istream &stream, std::size_t in_size_bound = 0)\n        {\n            using namespace std::placeholders;\n            return Serialization::Load(\n                std::bind(&IntArray<T_>::load_members, this, _1, in_size_bound),\n                stream);\n        }\n\n        /**\n        Saves the IntArray to a given memory location. The output is in binary\n        format and not human-readable.\n\n        @param[out] out The memory location to write the SmallModulus to\n        @param[in] size The number of bytes available in the given memory location\n        @param[in] compr_mode The desired compression mode\n        @throws std::invalid_argument if out is null or if size is too small to\n        contain a SEALHeader\n        @throws std::logic_error if the data to be saved is invalid, if compression\n        mode is not supported, or if compression failed\n        @throws std::runtime_error if I/O operations failed\n        */\n        inline std::streamoff save(\n            SEAL_BYTE *out,\n            std::size_t size,\n            compr_mode_type compr_mode = Serialization::compr_mode_default) const\n        {\n            using namespace std::placeholders;\n            return Serialization::Save(\n                std::bind(&IntArray<T_>::save_members, this, _1),\n                save_size(compr_mode_type::none),\n                out, size, compr_mode);\n        }\n\n        /**\n        Loads a IntArray from a given memory location overwriting the current\n        IntArray. This function takes optionally a bound on the size for the loaded\n        IntArray and throws an exception if the size indicated by the loaded\n        metadata exceeds the provided value. The check is omitted if in_size_bound\n        is zero.\n\n        @param[in] in The memory location to load the SmallModulus from\n        @param[in] size The number of bytes available in the given memory location\n        @param[in] in_size_bound A bound on the size of the loaded IntArray\n        @throws std::invalid_argument if in is null or if size is too small to\n        contain a SEALHeader\n        @throws std::logic_error if the loaded data is invalid, if the loaded size\n        exceeds in_size_bound, or if decompression failed\n        @throws std::runtime_error if I/O operations failed\n        */\n        inline std::streamoff load(\n            const SEAL_BYTE *in, std::size_t size, std::size_t in_size_bound = 0)\n        {\n            using namespace std::placeholders;\n            return Serialization::Load(\n                std::bind(&IntArray<T_>::load_members, this, _1, in_size_bound),\n                in, size);\n        }\n\n    private:\n        void save_members(std::ostream &stream) const\n        {\n            auto old_except_mask = stream.exceptions();\n            try\n            {\n                // Throw exceptions on std::ios_base::badbit and std::ios_base::failbit\n                stream.exceptions(std::ios_base::badbit | std::ios_base::failbit);\n\n                std::uint64_t size64 = size_;\n                stream.write(reinterpret_cast<const char*>(&size64), sizeof(std::uint64_t));\n                if (size_)\n                {\n                    stream.write(reinterpret_cast<const char*>(cbegin()),\n                        util::safe_cast<std::streamsize>(util::mul_safe(size_, sizeof(T))));\n                }\n            }\n            catch (const std::ios_base::failure &)\n            {\n                stream.exceptions(old_except_mask);\n                throw std::runtime_error(\"I/O error\");\n            }\n            catch (...)\n            {\n                stream.exceptions(old_except_mask);\n                throw;\n            }\n            stream.exceptions(old_except_mask);\n        }\n\n        void load_members(std::istream &stream, std::size_t in_size_bound)\n        {\n            auto old_except_mask = stream.exceptions();\n            try\n            {\n                // Throw exceptions on std::ios_base::badbit and std::ios_base::failbit\n                stream.exceptions(std::ios_base::badbit | std::ios_base::failbit);\n\n                std::uint64_t size64 = 0;\n                stream.read(reinterpret_cast<char*>(&size64), sizeof(std::uint64_t));\n\n                // Check (optionally) that the size in the metadata does not exceed\n                // in_size_bound\n                if (in_size_bound && util::unsigned_gt(size64, in_size_bound))\n                {\n                    throw std::logic_error(\"unexpected size\");\n                }\n\n                // Set new size; this is potentially unsafe if size64 was not checked\n                // against expected_size\n                resize(util::safe_cast<std::size_t>(size64));\n\n                // Read data\n                if (size_)\n                {\n                    stream.read(reinterpret_cast<char*>(begin()),\n                        util::safe_cast<std::streamsize>(util::mul_safe(size_, sizeof(T))));\n                }\n            }\n            catch (const std::ios_base::failure &)\n            {\n                stream.exceptions(old_except_mask);\n                throw std::runtime_error(\"I/O error\");\n            }\n            catch (...)\n            {\n                stream.exceptions(old_except_mask);\n                throw;\n            }\n            stream.exceptions(old_except_mask);\n        }\n\n        MemoryPoolHandle pool_;\n\n        std::size_t capacity_ = 0;\n\n        std::size_t size_ = 0;\n\n        util::Pointer<T> data_;\n    };\n}\n", "meta": {"hexsha": "7609262c2144faaed7d36f8c8f365a01ef8d0c24", "size": 24026, "ext": "h", "lang": "C", "max_stars_repo_path": "native/src/seal/intarray.h", "max_stars_repo_name": "nitrieu/SEAL", "max_stars_repo_head_hexsha": "9fc376c19488be2bfd213780ee06789754f4b2c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2019-12-02T09:26:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T03:59:25.000Z", "max_issues_repo_path": "native/src/seal/intarray.h", "max_issues_repo_name": "nitrieu/SEAL", "max_issues_repo_head_hexsha": "9fc376c19488be2bfd213780ee06789754f4b2c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-09-14T06:19:36.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-14T06:19:36.000Z", "max_forks_repo_path": "native/src/seal/intarray.h", "max_forks_repo_name": "nitrieu/SEAL", "max_forks_repo_head_hexsha": "9fc376c19488be2bfd213780ee06789754f4b2c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2019-12-02T22:02:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-10T02:17:06.000Z", "avg_line_length": 34.8202898551, "max_line_length": 92, "alphanum_fraction": 0.5724215433, "num_tokens": 4998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2227001285074597, "lm_q2_score": 0.028007521721541584, "lm_q1q2_score": 0.00623727868656278}}
{"text": "/// @brief Compile-time configurable Policy-based ring buffer\n///\n/// `RingBuffer` has an API matching `std::vector` in its default configuration or can be configured\n/// to provide a subset of that API, but provide lock-free concurrency\n#pragma once\n\n#include <Hyperion/BasicTypes.h>\n#include <Hyperion/Concepts.h>\n#include <Hyperion/HyperionDef.h>\n#include <Hyperion/Memory.h>\n#include <atomic>\n#include <compare>\n#include <gsl/gsl>\n#include <iostream>\n#include <iterator>\n#include <limits>\n#include <tuple>\n\nnamespace hyperion {\n\n\t/// @brief The thread-safety type of the `RingBuffer`\n\tenum class RingBufferType : usize {\n\t\tNotThreadSafe = 0,\n\t\tThreadSafe = 1\n\t};\n\n\tIGNORE_PADDING_START\n\t/// @brief A simple Ring Buffer implementation.\n\t/// Supports resizing, writing, reading, erasing, and provides mutable and immutable\n\t/// random access iterators.\n\t///\n\t/// # Iterator Invalidation\n\t/// * Iterators are lazily evaluated, so will only ever be invalidated at their current state.\n\t/// Performing any mutating operation (mutating the iterator, not the underlying data) on them\n\t/// will re-sync them with their associated `RingBuffer`.\n\t/// The following operations will invalidate an iterator's current state:\n\t/// - Read-only operations: never\n\t/// - clear: always\n\t/// - reserve: only if the `RingBuffer` changed capacity\n\t/// - erase: Erased elements and all following elements\n\t/// - push_back, emplace_back: only `end()` until `capacity()` is reached,\n\t///   then `begin()` and `end()`\n\t/// - insert, emplace: only the element at the position inserted/emplaced\n\t/// - pop_back: the element removed and `end()`\n\t/// - pop_front: the element removed and `begin()`\n\t///\n\t/// @tparam T - The type to store in the `RingBuffer`. Must Be Default Constructible.\n\t/// Does not currently support `T` of array types (eg, `T` = `U[]` or `T` = `U[N]`)\n\ttemplate<concepts::DefaultConstructible T,\n\t\t\t RingBufferType ThreadSafety = RingBufferType::NotThreadSafe,\n\t\t\t template<typename ElementType> typename Allocator = std::allocator>\n\tclass RingBuffer {\n\t  public:\n\t\t/// Default capacity of `RingBuffer`\n\t\tstatic const constexpr usize DEFAULT_CAPACITY = 16;\n\t\tusing allocator_traits = std::allocator_traits<Allocator<T>>;\n\t\tusing unique_pointer\n\t\t\t= decltype(allocate_unique<T[]>(std::declval<Allocator<T[]>>(), // NOLINT\n\t\t\t\t\t\t\t\t\t\t\tDEFAULT_CAPACITY));\n\n\t\t/// @brief Random-Access Bidirectional iterator for `RingBuffer`\n\t\t/// @note All navigation operators are checked such that any movement past `begin()` or\n\t\t/// `end()` is ignored.\n\t\tclass Iterator {\n\t\t  public:\n\t\t\tusing iterator_category = std::random_access_iterator_tag;\n\t\t\tusing difference_type = std::ptrdiff_t;\n\t\t\tusing value_type = T;\n\t\t\tusing pointer = value_type*;\n\t\t\tusing reference = value_type&;\n\n\t\t\tconstexpr explicit Iterator(pointer ptr,\n\t\t\t\t\t\t\t\t\t\tRingBuffer* containerPtr,\n\t\t\t\t\t\t\t\t\t\tusize currentIndex) noexcept\n\t\t\t\t: m_ptr(ptr), m_container_ptr(containerPtr), m_current_index(currentIndex) {\n\t\t\t}\n\t\t\tconstexpr Iterator(const Iterator& iter) noexcept = default;\n\t\t\tconstexpr Iterator(Iterator&& iter) noexcept = default;\n\t\t\t~Iterator() noexcept = default;\n\n\t\t\t/// @brief Returns the index in the `RingBuffer` that corresponds\n\t\t\t/// to the element this iterator points to\n\t\t\t///\n\t\t\t/// @return The index corresponding with the element this points to\n\t\t\t[[nodiscard]] inline constexpr auto get_index() const noexcept -> usize {\n\t\t\t\treturn m_current_index;\n\t\t\t}\n\n\t\t\tconstexpr auto operator=(const Iterator& iter) noexcept -> Iterator& = default;\n\t\t\tconstexpr auto operator=(Iterator&& iter) noexcept -> Iterator& = default;\n\n\t\t\tinline constexpr auto operator==(const Iterator& rhs) const noexcept -> bool {\n\t\t\t\treturn m_ptr == rhs.m_ptr;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator!=(const Iterator& rhs) const noexcept -> bool {\n\t\t\t\treturn m_ptr != rhs.m_ptr;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator*() const noexcept -> reference {\n\t\t\t\treturn *m_ptr;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator->() noexcept -> pointer {\n\t\t\t\treturn m_ptr;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator++() noexcept -> Iterator& {\n\t\t\t\tm_current_index++;\n\t\t\t\tif(m_current_index >= m_container_ptr->capacity()) {\n\t\t\t\t\tm_current_index = m_container_ptr->capacity();\n\t\t\t\t\tm_ptr = m_container_ptr->end().m_ptr;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tm_ptr = &(*m_container_ptr)[m_current_index];\n\t\t\t\t}\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator++(int) noexcept -> Iterator {\n\t\t\t\tIterator temp = *this;\n\t\t\t\t++(*this);\n\t\t\t\treturn temp;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator--() noexcept -> Iterator& {\n\t\t\t\tif(m_current_index == 0) {\n\t\t\t\t\treturn *this;\n\t\t\t\t}\n\n\t\t\t\tm_current_index--;\n\t\t\t\tm_ptr = &(*m_container_ptr)[m_current_index];\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator--(int) noexcept -> Iterator {\n\t\t\t\tIterator temp = *this;\n\t\t\t\t--(*this);\n\t\t\t\treturn temp;\n\t\t\t}\n\n\t\t\tinline constexpr auto\n\t\t\toperator+(concepts::Integral auto rhs) const noexcept -> Iterator {\n\t\t\t\tconst auto diff = static_cast<usize>(rhs);\n\t\t\t\tif(rhs < 0) {\n\t\t\t\t\treturn std::move(*this - -rhs);\n\t\t\t\t}\n\n\t\t\t\tauto temp = *this;\n\t\t\t\ttemp.m_current_index += diff;\n\t\t\t\tif(temp.m_current_index > temp.m_container_ptr->capacity()) {\n\t\t\t\t\ttemp.m_current_index = temp.m_container_ptr->capacity();\n\t\t\t\t\ttemp.m_ptr = temp.m_container_ptr->end().m_ptr;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\ttemp.m_ptr = &(*temp.m_container_ptr)[temp.m_current_index];\n\t\t\t\t}\n\t\t\t\treturn temp;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator+=(concepts::Integral auto rhs) noexcept -> Iterator& {\n\t\t\t\t*this = std::move(*this + rhs);\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\tinline constexpr auto\n\t\t\toperator-(concepts::Integral auto rhs) const noexcept -> Iterator {\n\t\t\t\tconst auto diff = static_cast<usize>(rhs);\n\t\t\t\tif(rhs < 0) {\n\t\t\t\t\treturn std::move(*this + -rhs);\n\t\t\t\t}\n\n\t\t\t\tauto temp = *this;\n\t\t\t\tif(diff > temp.m_current_index) {\n\t\t\t\t\ttemp.m_ptr = temp.m_container_ptr->begin().m_ptr;\n\t\t\t\t\ttemp.m_current_index = 0;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\ttemp.m_current_index -= diff;\n\t\t\t\t\ttemp.m_ptr = &(*temp.m_container_ptr)[temp.m_current_index];\n\t\t\t\t}\n\t\t\t\treturn temp;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator-=(concepts::Integral auto rhs) noexcept -> Iterator& {\n\t\t\t\t*this = std::move(*this - rhs);\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator-(const Iterator& rhs) const noexcept -> difference_type {\n\t\t\t\treturn static_cast<std::ptrdiff_t>(m_current_index)\n\t\t\t\t\t   - static_cast<std::ptrdiff_t>(rhs.m_current_index);\n\t\t\t}\n\n\t\t\tinline constexpr auto operator[](concepts::Integral auto index) noexcept -> Iterator {\n\t\t\t\treturn std::move(*this + index);\n\t\t\t}\n\n\t\t\tinline constexpr auto operator>(const Iterator& rhs) const noexcept -> bool {\n\t\t\t\treturn m_current_index > rhs.m_current_index;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator<(const Iterator& rhs) const noexcept -> bool {\n\t\t\t\treturn m_current_index < rhs.m_current_index;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator>=(const Iterator& rhs) const noexcept -> bool {\n\t\t\t\treturn m_current_index >= rhs.m_current_index;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator<=(const Iterator& rhs) const noexcept -> bool {\n\t\t\t\treturn m_current_index <= rhs.m_current_index;\n\t\t\t}\n\n\t\t  private:\n\t\t\tpointer m_ptr;\n\t\t\tRingBuffer* m_container_ptr = nullptr;\n\t\t\tusize m_current_index = 0;\n\t\t};\n\n\t\t/// @brief Read-only Random-Access Bidirectional iterator for `RingBuffer`\n\t\t/// @note All navigation operators are checked such that any movement past `begin()` or\n\t\t/// `end()` is ignored.\n\t\tclass ConstIterator {\n\t\t  public:\n\t\t\tusing iterator_category = std::random_access_iterator_tag;\n\t\t\tusing difference_type = std::ptrdiff_t;\n\t\t\tusing value_type = T;\n\t\t\tusing pointer = const value_type*;\n\t\t\tusing reference = const value_type&;\n\n\t\t\tconstexpr explicit ConstIterator(pointer ptr,\n\t\t\t\t\t\t\t\t\t\t\t RingBuffer* containerPtr,\n\t\t\t\t\t\t\t\t\t\t\t usize currentIndex) noexcept\n\t\t\t\t: m_ptr(ptr), m_container_ptr(containerPtr), m_current_index(currentIndex) {\n\t\t\t}\n\t\t\tconstexpr ConstIterator(const ConstIterator& iter) noexcept = default;\n\t\t\tconstexpr ConstIterator(ConstIterator&& iter) noexcept = default;\n\t\t\t~ConstIterator() noexcept = default;\n\n\t\t\t/// @brief Returns the index in the `RingBuffer` that corresponds\n\t\t\t/// to the element this iterator points to\n\t\t\t///\n\t\t\t/// @return The index corresponding with the element this points to\n\t\t\t[[nodiscard]] inline constexpr auto get_index() const noexcept -> usize {\n\t\t\t\treturn m_current_index;\n\t\t\t}\n\n\t\t\tconstexpr auto\n\t\t\toperator=(const ConstIterator& iter) noexcept -> ConstIterator& = default;\n\t\t\tconstexpr auto operator=(ConstIterator&& iter) noexcept -> ConstIterator& = default;\n\n\t\t\tinline constexpr auto operator==(const ConstIterator& rhs) const noexcept -> bool {\n\t\t\t\treturn m_ptr == rhs.m_ptr;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator!=(const ConstIterator& rhs) const noexcept -> bool {\n\t\t\t\treturn m_ptr != rhs.m_ptr;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator*() const noexcept -> reference {\n\t\t\t\treturn *m_ptr;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator->() const noexcept -> pointer {\n\t\t\t\treturn m_ptr;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator++() noexcept -> ConstIterator& {\n\t\t\t\tm_current_index++;\n\t\t\t\tif(m_current_index >= m_container_ptr->capacity()) {\n\t\t\t\t\tm_current_index = m_container_ptr->capacity();\n\t\t\t\t\tm_ptr = m_container_ptr->end().m_ptr;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tm_ptr = &(*m_container_ptr)[m_current_index];\n\t\t\t\t}\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator++(int) noexcept -> ConstIterator {\n\t\t\t\tConstIterator temp = *this;\n\t\t\t\t++(*this);\n\t\t\t\treturn temp;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator--() noexcept -> ConstIterator& {\n\t\t\t\tif(m_current_index == 0) {\n\t\t\t\t\treturn *this;\n\t\t\t\t}\n\n\t\t\t\tm_current_index--;\n\t\t\t\tm_ptr = &(*m_container_ptr)[m_current_index];\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator--(int) noexcept -> ConstIterator {\n\t\t\t\tConstIterator temp = *this;\n\t\t\t\t--(*this);\n\t\t\t\treturn temp;\n\t\t\t}\n\n\t\t\tinline constexpr auto\n\t\t\toperator+(concepts::Integral auto rhs) const noexcept -> ConstIterator {\n\t\t\t\tconst auto diff = static_cast<usize>(rhs);\n\t\t\t\tif(rhs < 0) {\n\t\t\t\t\treturn std::move(*this - -rhs);\n\t\t\t\t}\n\n\t\t\t\tauto temp = *this;\n\t\t\t\ttemp.m_current_index += diff;\n\t\t\t\tif(temp.m_current_index > temp.m_container_ptr->capacity()) {\n\t\t\t\t\ttemp.m_current_index = temp.m_container_ptr->capacity();\n\t\t\t\t\ttemp.m_ptr = temp.m_container_ptr->end().m_ptr;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\ttemp.m_ptr = &(*temp.m_container_ptr)[temp.m_current_index];\n\t\t\t\t}\n\t\t\t\treturn temp;\n\t\t\t}\n\n\t\t\tinline constexpr auto\n\t\t\toperator+=(concepts::Integral auto rhs) noexcept -> ConstIterator& {\n\t\t\t\t*this = std::move(*this + rhs);\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\tinline constexpr auto\n\t\t\toperator-(concepts::Integral auto rhs) const noexcept -> ConstIterator {\n\t\t\t\tconst auto diff = static_cast<usize>(rhs);\n\t\t\t\tif(rhs < 0) {\n\t\t\t\t\treturn std::move(*this + -rhs);\n\t\t\t\t}\n\n\t\t\t\tauto temp = *this;\n\t\t\t\tif(diff > temp.m_current_index) {\n\t\t\t\t\ttemp.m_ptr = temp.m_container_ptr->begin().m_ptr;\n\t\t\t\t\ttemp.m_current_index = 0;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\ttemp.m_current_index -= diff;\n\t\t\t\t\ttemp.m_ptr = &(*temp.m_container_ptr)[temp.m_current_index];\n\t\t\t\t}\n\t\t\t\treturn temp;\n\t\t\t}\n\n\t\t\tinline constexpr auto\n\t\t\toperator-=(concepts::Integral auto rhs) noexcept -> ConstIterator& {\n\t\t\t\t*this = std::move(*this - rhs);\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\tinline constexpr auto\n\t\t\toperator-(const ConstIterator& rhs) const noexcept -> difference_type {\n\t\t\t\treturn static_cast<std::ptrdiff_t>(m_current_index)\n\t\t\t\t\t   - static_cast<std::ptrdiff_t>(rhs.m_current_index);\n\t\t\t}\n\n\t\t\tinline constexpr auto\n\t\t\toperator[](concepts::Integral auto index) const noexcept -> ConstIterator {\n\t\t\t\treturn std::move(*this + index);\n\t\t\t}\n\n\t\t\tinline constexpr auto operator>(const ConstIterator& rhs) const noexcept -> bool {\n\t\t\t\treturn m_current_index > rhs.m_current_index;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator<(const ConstIterator& rhs) const noexcept -> bool {\n\t\t\t\treturn m_current_index < rhs.m_current_index;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator>=(const ConstIterator& rhs) const noexcept -> bool {\n\t\t\t\treturn m_current_index >= rhs.m_current_index;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator<=(const ConstIterator& rhs) const noexcept -> bool {\n\t\t\t\treturn m_current_index <= rhs.m_current_index;\n\t\t\t}\n\n\t\t  private:\n\t\t\tpointer m_ptr;\n\t\t\tRingBuffer* m_container_ptr = nullptr;\n\t\t\tusize m_current_index = 0;\n\t\t};\n\n\t\t/// @brief Creates a `RingBuffer` with default capacity\n\t\tconstexpr RingBuffer() noexcept = default;\n\n\t\t/// @brief Creates a `RingBuffer` with (at least) the given initial capacity\n\t\t///\n\t\t/// @param intitial_capacity - The initial capacity of the `RingBuffer`\n\t\tconstexpr explicit RingBuffer(usize intitial_capacity) noexcept\n\t\t\t: m_buffer(allocate_unique<T[]>(m_allocator, intitial_capacity + 1)), // NOLINT\n\t\t\t  m_loop_index(intitial_capacity),\n\t\t\t  m_capacity(intitial_capacity + 1) {\n\t\t}\n\n\t\t/// @brief Constructs a new `RingBuffer` with the given initial capacity and\n\t\t/// fills it with `default_value`\n\t\t///\n\t\t/// @param intitial_capacity - The initial capacity of the `RingBuffer`\n\t\t/// @param default_value - The value to fill the `RingBuffer` with\n\t\tconstexpr RingBuffer(\n\t\t\tusize intitial_capacity,\n\t\t\tconst T& default_value) noexcept requires concepts::CopyConstructible<T>\n\t\t\t: m_buffer(allocate_unique<T[]>(m_allocator, // NOLINT\n\t\t\t\t\t\t\t\t\t\t\tintitial_capacity + 1,\n\t\t\t\t\t\t\t\t\t\t\tdefault_value)),\n\t\t\t  m_write_index(intitial_capacity),\n\t\t\t  m_start_index(0_usize), // NOLINT\n\t\t\t  m_loop_index(intitial_capacity),\n\t\t\t  m_capacity(intitial_capacity + 1) {\n\t\t}\n\n\t\tconstexpr RingBuffer(\n\t\t\tstd::initializer_list<T> values) noexcept requires concepts::MoveAssignable<T>\n\t\t\t: m_buffer(allocate_unique<T[]>(m_allocator, // NOLINT\n\t\t\t\t\t\t\t\t\t\t\tvalues.size() + 1)),\n\t\t\t  m_loop_index(values.size()),\n\t\t\t  m_capacity(values.size() + 1) {\n\n\t\t\tfor(auto&& val : values) {\n\t\t\t\tpush_back(std::move(val));\n\t\t\t}\n\t\t}\n\n\t\tconstexpr RingBuffer(const RingBuffer& buffer) noexcept requires concepts::CopyAssignable<T>\n\t\t\t: m_buffer(allocate_unique<T[]>(m_allocator, buffer.m_capacity)), // NOLINT\n\t\t\t  m_write_index(0_usize),\t\t\t\t\t\t\t\t\t\t  // NOLINT\n\t\t\t  m_start_index(0_usize),\t\t\t\t\t\t\t\t\t\t  // NOLINT\n\t\t\t  m_loop_index(buffer.m_loop_index),\n\t\t\t  m_capacity(buffer.m_capacity) {\n\t\t\tconst auto size = m_buffer.size();\n\t\t\tfor(auto i = 0_usize; i < size; ++i) {\n\t\t\t\tpush_back(buffer.m_buffer[i]);\n\t\t\t}\n\t\t\t// clang-format off\n\t\t\tm_start_index = buffer.m_start_index; // NOLINT(cppcoreguidelines-prefer-member-initializer)\n\t\t\tm_write_index = buffer.m_write_index; // NOLINT(cppcoreguidelines-prefer-member-initializer)\n\t\t\t// clang-format on\n\t\t}\n\n\t\tconstexpr RingBuffer(RingBuffer&& buffer) noexcept\n\t\t\t: m_allocator(buffer.m_allocator),\n\t\t\t  m_buffer(std::move(buffer.m_buffer)),\n\t\t\t  m_write_index(buffer.m_write_index),\n\t\t\t  m_start_index(buffer.m_start_index),\n\t\t\t  m_loop_index(buffer.m_loop_index),\n\t\t\t  m_capacity(buffer.m_capacity) {\n\t\t\tbuffer.m_capacity = 0_usize;\n\t\t\tbuffer.m_loop_index = 0_usize;\n\t\t\tbuffer.m_write_index = 0_usize;\n\t\t\tbuffer.m_start_index = 0_usize;\n\t\t\tbuffer.m_buffer = nullptr;\n\t\t}\n\n\t\t~RingBuffer() noexcept = default;\n\n\t\t/// @brief Returns the element at the given index.\n\t\t/// @note This is not checked in the same manner as STL containers:\n\t\t/// if index >= capacity, the element at capacity - 1 is returned.\n\t\t///\n\t\t/// @param index - The index of the desired element\n\t\t///\n\t\t/// @return The element at the given index, or at capacity - 1 if index >= capacity\n\t\t[[nodiscard]] inline constexpr auto at(concepts::Integral auto index) noexcept -> T& {\n\t\t\tauto i = get_adjusted_internal_index(index);\n\n\t\t\treturn m_buffer[i]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\n\t\t}\n\n\t\t/// @brief Returns the first element in the `RingBuffer`\n\t\t///\n\t\t/// @return The first element\n\t\t[[nodiscard]] inline constexpr auto front() noexcept -> T& {\n\t\t\treturn m_buffer\n\t\t\t\t[m_start_index]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\n\t\t}\n\n\t\t/// @brief Returns the last element in the `RingBuffer`\n\t\t/// @note If <= 1 elements are in the `RingBuffer`, this will be the same as `front`\n\t\t///\n\t\t/// @return The last element\n\t\t[[nodiscard]] inline constexpr auto back() noexcept -> T& {\n\t\t\tconst auto index = (m_start_index + size() - 1) % (m_capacity);\n\n\t\t\treturn m_buffer[index]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\n\t\t}\n\n\t\t/// @brief Returns a pointer to the underlying data in the `RingBuffer`.\n\t\t/// @note This is not sorted in any way to match the representation used by the `RingBuffer`\n\t\t///\n\t\t/// @return A pointer to the underlying data\n\t\t[[nodiscard]] inline constexpr auto data() noexcept -> T* {\n\t\t\treturn m_buffer;\n\t\t}\n\n\t\t/// @brief Returns whether the `RingBuffer` is empty\n\t\t///\n\t\t/// @return `true` if the `RingBuffer` is empty, `false` otherwise\n\t\t[[nodiscard]] inline constexpr auto empty() const noexcept -> bool {\n\t\t\treturn m_write_index == m_start_index;\n\t\t}\n\n\t\t/// @brief Returns whether the `RingBuffer` is full\n\t\t///\n\t\t/// @return `true` if the `RingBuffer` is full, `false` otherwise\n\t\t[[nodiscard]] inline constexpr auto full() const noexcept -> bool {\n\t\t\treturn size() == m_capacity - 1;\n\t\t}\n\n\t\t/// @brief Returns the current number of elements in the `RingBuffer`\n\t\t///\n\t\t/// @return The current number of elements\n\t\t[[nodiscard]] inline constexpr auto size() const noexcept -> usize {\n\t\t\treturn m_write_index >= m_start_index ? (m_write_index - m_start_index) :\n\t\t\t\t\t\t\t\t\t\t\t\t\t  (m_capacity - (m_start_index - m_write_index));\n\t\t}\n\n\t\t/// @brief Returns the maximum possible number of elements this `RingBuffer` could store\n\t\t/// if grown to maximum possible capacity\n\t\t///\n\t\t/// @return The maximum possible number of storable elements\n\t\t[[nodiscard]] inline constexpr auto max_size() const noexcept -> usize {\n\t\t\treturn allocator_traits::max_size(m_allocator) - 1;\n\t\t}\n\n\t\t/// @brief Returns the current capacity of the `RingBuffer`;\n\t\t/// the number of elements it can currently store\n\t\t///\n\t\t/// @return The current capacity\n\t\t[[nodiscard]] inline constexpr auto capacity() const noexcept -> usize {\n\t\t\treturn m_capacity - 1;\n\t\t}\n\n\t\t/// @brief Reserves more storage for the `RingBuffer`. If `new_capacity` is > capacity,\n\t\t/// then the capacity of the `RingBuffer` will be extended until at least `new_capacity`\n\t\t/// elements can be stored.\n\t\t/// @note Memory contiguity is maintained, so no **elements** will be lost or invalidated.\n\t\t/// However, all iterators and references to elements will be invalidated.\n\t\t///\n\t\t/// @param new_capacity - The new capacity of the `RingBuffer`\n\t\tinline constexpr auto reserve(usize new_capacity) noexcept -> void {\n\t\t\t// we only need to do anything if `new_capacity` is actually larger than `m_capacity`\n\t\t\tif(new_capacity > m_capacity) {\n\t\t\t\tauto temp\n\t\t\t\t\t= allocate_unique<T[], Allocator<T[]>>(m_allocator, new_capacity + 1); // NOLINT\n\t\t\t\tauto span = gsl::make_span(&temp[0], new_capacity + 1);\n\t\t\t\tstd::copy(begin(), end(), span.begin());\n\t\t\t\tm_buffer = std::move(temp);\n\t\t\t\tm_start_index = 0;\n\t\t\t\tm_write_index = m_loop_index + 1;\n\t\t\t\tm_loop_index = new_capacity;\n\t\t\t\tm_capacity = new_capacity + 1;\n\t\t\t}\n\t\t}\n\n\t\t/// @brief Erases all elements from the `RingBuffer`\n\t\tinline constexpr auto clear() noexcept -> void {\n\t\t\tm_start_index = 0;\n\t\t\tm_write_index = 0;\n\t\t}\n\n\t\t/// @brief Inserts the given element at the end of the `RingBuffer`\n\t\t/// @note if `size() == capacity()` then this loops and overwrites `front()`\n\t\t///\n\t\t/// @param value - the element to insert\n\t\tinline constexpr auto\n\t\tpush_back(const T& value) noexcept -> void requires concepts::CopyAssignable<T> {\n\t\t\t// NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)\n\t\t\tm_buffer[m_write_index] = value;\n\n\t\t\tincrement_indices();\n\t\t}\n\n\t\t/// @brief Inserts the given element at the end of the `RingBuffer`\n\t\t/// @note if `size() == capacity()` then this loops and overwrites `front()`\n\t\t///\n\t\t/// @param value - the element to insert\n\t\tinline constexpr auto\n\t\tpush_back(T&& value) noexcept -> void requires concepts::MoveAssignable<T> {\n\t\t\t// NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)\n\t\t\tm_buffer[m_write_index] = std::move(value);\n\n\t\t\tincrement_indices();\n\t\t}\n\n\t\t/// @brief Constructs the given element in place at the end of the `RingBuffer`\n\t\t/// @note if `size() == capacity()` then this loops and overwrites `front()`\n\t\t///\n\t\t/// @tparam Args - The types of the element's constructor arguments\n\t\t/// @param args - The constructor arguments for the element\n\t\t///\n\t\t/// @return A reference to the element constructed at the end of the `RingBuffer`\n\t\ttemplate<typename... Args>\n\t\trequires concepts::ConstructibleFrom<T, Args...>\n\t\tinline constexpr auto emplace_back(Args&&... args) noexcept -> T& {\n\t\t\tallocator_traits::template construct<T>(m_allocator,\n\t\t\t\t\t\t\t\t\t\t\t\t\t&m_buffer[m_write_index], // NOLINT\n\t\t\t\t\t\t\t\t\t\t\t\t\tstd::forward<Args>(args)...);\n\n\t\t\tauto index = m_write_index;\n\n\t\t\tincrement_indices();\n\n\t\t\treturn m_buffer[index]; // NOLINT\n\t\t}\n\n\t\t/// @brief Constructs the given element in place at the location\n\t\t/// indicated by the `Iterator` `position`\n\t\t///\n\t\t/// @tparam Args - The types of the element's constructor arguments\n\t\t/// @param position - `Iterator` indicating where in the `RingBuffer` to construct the\n\t\t/// element\n\t\t/// @param args - The constructor arguments for the element\n\t\t///\n\t\t/// @return A reference to the element constructed at the location indicated by `position`\n\t\ttemplate<typename... Args>\n\t\trequires concepts::ConstructibleFrom<T, Args...>\n\t\tinline constexpr auto emplace(const Iterator& position, Args&&... args) noexcept -> T& {\n\t\t\tauto index = get_adjusted_internal_index(position.get_index());\n\n\t\t\tallocator_traits::template construct<T>(m_allocator,\n\t\t\t\t\t\t\t\t\t\t\t\t\t&m_buffer[index], // NOLINT\n\t\t\t\t\t\t\t\t\t\t\t\t\tstd::forward<Args>(args)...);\n\n\t\t\treturn m_buffer[index]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\n\t\t}\n\n\t\t/// @brief Constructs the given element in place at the location\n\t\t/// indicated by the `ConstIterator` `position`\n\t\t///\n\t\t/// @tparam Args - The types of the element's constructor arguments\n\t\t/// @param position - `ConstIterator` indicating where in the `RingBuffer` to construct the\n\t\t/// element\n\t\t/// @param args - The constructor arguments for the element\n\t\t///\n\t\t/// @return A reference to the element constructed at the location indicated by `position`\n\t\ttemplate<typename... Args>\n\t\tinline constexpr auto\n\t\templace(const ConstIterator& position, Args&&... args) noexcept -> T& {\n\t\t\tauto index = get_adjusted_internal_index(position.get_index());\n\n\t\t\tallocator_traits::template construct<T>(m_allocator,\n\t\t\t\t\t\t\t\t\t\t\t\t\t&m_buffer[index], // NOLINT\n\t\t\t\t\t\t\t\t\t\t\t\t\tstd::forward<Args>(args)...);\n\n\t\t\treturn m_buffer[index]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\n\t\t}\n\n\t\t/// @brief Assigns the given element to the position indicated\n\t\t/// by the `Iterator` `position`\n\t\t/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`\n\t\t///\n\t\t/// @param position - `Iterator` indicating where in the `RingBuffer` to place the element\n\t\t/// @param element - The element to store in the `RingBuffer`\n\t\tinline constexpr auto insert(const Iterator& position, const T& element) noexcept\n\t\t\t-> void requires concepts::CopyAssignable<T> {\n\t\t\tinsert_internal(position.get_index(), element);\n\t\t}\n\n\t\t/// @brief Assigns the given element to the position indicated\n\t\t/// by the `Iterator` `position`\n\t\t/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`\n\t\t///\n\t\t/// @param position - `Iterator` indicating where in the `RingBuffer` to place the element\n\t\t/// @param element - The element to store in the `RingBuffer`\n\t\tinline constexpr auto insert(const Iterator& position, T&& element) noexcept -> void {\n\t\t\tinsert_internal(position.get_index(), std::forward<T>(element));\n\t\t}\n\n\t\t/// @brief Assigns the given element to the position indicated\n\t\t/// by the `ConstIterator` `position`\n\t\t/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`\n\t\t///\n\t\t/// @param position - `ConstIterator` indicating where in the `RingBuffer` to place the\n\t\t/// element\n\t\t/// @param element - The element to store in the `RingBuffer`\n\t\tinline constexpr auto insert(const ConstIterator& position, const T& element) noexcept\n\t\t\t-> void requires concepts::CopyAssignable<T> {\n\t\t\tinsert_internal(position.get_index(), element);\n\t\t}\n\n\t\t/// @brief Assigns the given element to the position indicated\n\t\t/// by the `ConstIterator` `position`\n\t\t/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`\n\t\t///\n\t\t/// @param position - `ConstIterator` indicating where in the `RingBuffer` to place the\n\t\t/// element\n\t\t/// @param element - The element to store in the `RingBuffer`\n\t\tinline constexpr auto insert(const ConstIterator& position, T&& element) noexcept -> void {\n\t\t\tinsert_internal(position.get_index(), std::forward<T>(element));\n\t\t}\n\n\t\t/// @brief Constructs the given element at the insertion position indicated\n\t\t/// by the `ConstIterator` `position`\n\t\t/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`\n\t\t///\n\t\t/// @param position - `ConstIterator` indicating where in the `RingBuffer` to place the\n\t\t/// element\n\t\t/// @param args - The arguments to the constructor for\n\t\t/// the element to store in the `RingBuffer`\n\t\ttemplate<typename... Args>\n\t\trequires concepts::ConstructibleFrom<T, Args...>\n\t\tinline constexpr auto\n\t\tinsert_emplace(const Iterator& position, Args&&... args) noexcept -> T& {\n\t\t\treturn insert_emplace_internal(position.get_index(), std::forward<Args>(args)...);\n\t\t}\n\n\t\t/// @brief Constructs the given element at the insertion position indicated\n\t\t/// by the `ConstIterator` `position`\n\t\t/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`\n\t\t///\n\t\t/// @param position - `ConstIterator` indicating where in the `RingBuffer` to place the\n\t\t/// element\n\t\t/// @param args - The arguments to the constructor for\n\t\t/// the element to store in the `RingBuffer`\n\t\ttemplate<typename... Args>\n\t\trequires concepts::ConstructibleFrom<T, Args...>\n\t\tinline constexpr auto\n\t\tinsert_emplace(const ConstIterator& position, Args&&... args) noexcept -> T& {\n\t\t\treturn insert_emplace_internal(position.get_index(), std::forward<Args>(args)...);\n\t\t}\n\n\t\t/// @brief Erases the element at the given `position`, moving other elements backward\n\t\t/// in the buffer to maintain contiguity\n\t\t///\n\t\t/// @param position - The element to erase\n\t\t///\n\t\t/// @return `Iterator` pointing to the element after the one erased\n\t\tinline constexpr auto erase(const Iterator& position) noexcept -> Iterator {\n\t\t\treturn erase_internal(position.get_index());\n\t\t}\n\n\t\t/// @brief Erases the element at the given `position`, moving other elements backward\n\t\t/// in the buffer to maintain contiguity\n\t\t///\n\t\t/// @param position - The element to erase\n\t\t///\n\t\t/// @return `Iterator` pointing to the element after the one erased\n\t\tinline constexpr auto erase(const ConstIterator& position) noexcept -> Iterator {\n\t\t\treturn erase_internal(position.get_index());\n\t\t}\n\n\t\t/// @brief Erases the range of elements in [`first`, `last`)\n\t\t/// Returns an `Iterator` to the element after the last one erased\n\t\t/// @note In the case `first` >= `last`, no elements are erased and `last` is returned;\n\t\t///\n\t\t/// @param first - The first element in the range to erase\n\t\t/// @param last - The last element in the range\n\t\t///\n\t\t/// @return `Iterator` pointing to the element after the last one erased\n\t\tinline constexpr auto\n\t\terase(const Iterator& first, const Iterator& last) noexcept -> Iterator {\n\t\t\tif(first >= last) {\n\t\t\t\treturn last;\n\t\t\t}\n\n\t\t\treturn erase_internal(first.get_index(), last.get_index());\n\t\t}\n\n\t\t/// @brief Erases the range of elements in [`first`, `last`)\n\t\t/// Returns an `Iterator` to the element after the last one erased\n\t\t/// @note In the case `first` >= `last`, no elements are erased and `last` is returned;\n\t\t///\n\t\t/// @param first - The first element in the range to erase\n\t\t/// @param last - The last element in the range\n\t\t///\n\t\t/// @return `Iterator` pointing to the element after the last one erased\n\t\tinline constexpr auto\n\t\terase(const ConstIterator& first, const ConstIterator& last) noexcept -> Iterator {\n\t\t\tif(first >= last) {\n\t\t\t\treturn last;\n\t\t\t}\n\n\t\t\treturn erase_internal(first.get_index(), last.get_index());\n\t\t}\n\n\t\t/// @brief Removes the last element in the `RingBuffer` and returns it\n\t\t///\n\t\t/// @return The last element in the `RingBuffer`\n\t\t[[nodiscard]] inline constexpr auto\n\t\tpop_back() noexcept -> T requires concepts::Copyable<T> {\n\t\t\tT back_ = back();\n\t\t\tdecrement_write();\n\t\t\treturn back_;\n\t\t}\n\n\t\t/// @brief Removes the first element in the `RingBuffer` and returns it\n\t\t///\n\t\t/// @return The first element in the `RingBuffer`\n\t\t[[nodiscard]] inline constexpr auto\n\t\tpop_front() noexcept -> T requires concepts::Copyable<T> {\n\t\t\tT front_ = front();\n\t\t\tincrement_start();\n\t\t\treturn front_;\n\t\t}\n\n\t\t/// @brief Returns a Random Access Bidirectional iterator over the `RingBuffer`,\n\t\t/// at the beginning\n\t\t///\n\t\t/// @return The iterator, at the beginning\n\t\t[[nodiscard]] inline constexpr auto begin() -> Iterator {\n\t\t\tT* p = &m_buffer\n\t\t\t\t\t   [m_start_index]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\n\n\t\t\treturn Iterator(p, this, 0_usize);\n\t\t}\n\n\t\t/// @brief Returns a Random Access Bidirectional iterator over the `RingBuffer`,\n\t\t/// at the end\n\t\t///\n\t\t/// @return The iterator, at the end\n\t\t[[nodiscard]] inline constexpr auto end() -> Iterator {\n\t\t\tT* p = &m_buffer\n\t\t\t\t\t   [m_write_index]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\n\n\t\t\treturn Iterator(p, this, size());\n\t\t}\n\n\t\t/// @brief Returns a Random Access Bidirectional read-only iterator over the `RingBuffer`,\n\t\t/// at the beginning\n\t\t///\n\t\t/// @return The iterator, at the beginning\n\t\t[[nodiscard]] inline constexpr auto cbegin() -> ConstIterator {\n\t\t\tT* p = &m_buffer\n\t\t\t\t\t   [m_start_index]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\n\n\t\t\treturn ConstIterator(p, this, 0_usize);\n\t\t}\n\n\t\t/// @brief Returns a Random Access Bidirectional read-only iterator over the `RingBuffer`,\n\t\t/// at the end\n\t\t///\n\t\t/// @return The iterator, at the end\n\t\t[[nodiscard]] inline constexpr auto cend() -> ConstIterator {\n\t\t\tT* p = &m_buffer\n\t\t\t\t\t   [m_write_index]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\n\t\t\treturn ConstIterator(p, this, size());\n\t\t}\n\n\t\t/// @brief Unchecked access-by-index operator\n\t\t///\n\t\t/// @param index - The index to get the corresponding element for\n\t\t///\n\t\t/// @return - The element at index\n\t\t[[nodiscard]] inline constexpr auto\n\t\toperator[](concepts::Integral auto index) noexcept -> T& {\n\t\t\tauto i = get_adjusted_internal_index(index);\n\n\t\t\treturn m_buffer[i]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\n\t\t}\n\n\t\tconstexpr auto operator=(const RingBuffer& buffer) noexcept\n\t\t\t-> RingBuffer& requires concepts::CopyAssignable<T> {\n\t\t\tif(this == &buffer) {\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\tauto temp = allocate_unique<T[]>(m_allocator, buffer.m_capacity); // NOLINT\n\t\t\tconst auto size = buffer.size();\n\t\t\tfor(auto i = 0_usize; i < size; ++i) {\n\t\t\t\ttemp[i] = buffer.m_buffer[i];\n\t\t\t}\n\t\t\tm_buffer = std::move(temp);\n\t\t\tm_capacity = buffer.m_capacity;\n\t\t\tm_start_index = buffer.m_start_index;\n\t\t\tm_write_index = buffer.m_write_index;\n\t\t\tm_loop_index = buffer.m_loop_index;\n\t\t\treturn *this;\n\t\t}\n\t\tconstexpr auto operator=(RingBuffer&& buffer) noexcept -> RingBuffer& {\n\t\t\tm_allocator = buffer.m_allocator;\n\t\t\tm_buffer = std::move(buffer.m_buffer);\n\t\t\tm_write_index = buffer.m_write_index;\n\t\t\tm_start_index = buffer.m_start_index;\n\t\t\tm_loop_index = buffer.m_loop_index;\n\t\t\tm_capacity = buffer.m_capacity;\n\t\t\tbuffer.m_buffer = nullptr;\n\t\t\tbuffer.m_write_index = 0_usize;\n\t\t\tbuffer.m_start_index = 0_usize;\n\t\t\tbuffer.m_capacity = 0_usize;\n\t\t\treturn *this;\n\t\t}\n\n\t  private:\n\t\tstatic const constexpr usize DEFAULT_CAPACITY_INTERNAL = DEFAULT_CAPACITY + 1;\n\t\tAllocator<T> m_allocator = Allocator<T>();\n\t\tunique_pointer m_buffer\n\t\t\t= allocate_unique<T[]>(m_allocator, DEFAULT_CAPACITY_INTERNAL); // NOLINT\n\t\tusize m_write_index = 0_usize;\n\t\tusize m_start_index = 0_usize;\n\t\tusize m_loop_index = DEFAULT_CAPACITY;\n\t\tusize m_capacity = DEFAULT_CAPACITY_INTERNAL;\n\n\t\t/// @brief Converts the given `RingBuffer` index into the corresponding index into then\n\t\t/// underlying `T` array\n\t\t///\n\t\t/// @param index - The `RingBuffer` index to convert\n\t\t///\n\t\t/// @return The corresponding index into the underlying `T` array\n\t\t[[nodiscard]] inline constexpr auto\n\t\tget_adjusted_internal_index(concepts::Integral auto index) const noexcept -> usize {\n\t\t\tauto i = static_cast<usize>(index);\n\t\t\treturn (m_start_index + i) % (m_capacity);\n\t\t}\n\n\t\t/// @brief Converts the given index into the underlying `T` array into\n\t\t/// a using facing index into the `RingBuffer`\n\t\t///\n\t\t/// @param index - The internal index\n\t\t///\n\t\t/// @return The corresponding user-facing index\n\t\t[[nodiscard]] inline constexpr auto\n\t\tget_external_index_from_internal(concepts::Integral auto index) const noexcept -> usize {\n\t\t\tauto i = static_cast<usize>(index);\n\t\t\tif(i >= m_start_index && i <= m_loop_index) {\n\t\t\t\treturn i - m_start_index;\n\t\t\t}\n\t\t\telse if(i < m_start_index) {\n\t\t\t\treturn m_capacity - (m_start_index - i);\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn m_capacity - 1;\n\t\t\t}\n\t\t}\n\n\t\t/// @brief Used to increment the start and write indices into the underlying `T` array,\n\t\t/// and the size property, after pushing an element at the back,\n\t\t/// maintaining the logical `RingBuffer` structure\n\t\tinline constexpr auto increment_indices() noexcept -> void {\n\t\t\tm_write_index = (m_write_index + 1) % (m_capacity);\n\n\t\t\t// if write index is at start, we need to push start forward to maintain\n\t\t\t// the \"invalid\" spacer element for this.end()\n\t\t\tif(m_write_index == m_start_index) {\n\t\t\t\tm_start_index = (m_start_index + 1) % (m_capacity);\n\t\t\t}\n\t\t}\n\n\t\t/// @brief Used to increment the start index into the underlying `T` array\n\t\t/// and the size property after popping an element from the front,\n\t\t/// maintaining the logical `RingBuffer` structure\n\t\tinline constexpr auto increment_start() noexcept -> void {\n\t\t\tif(m_start_index != m_write_index) {\n\t\t\t\tm_start_index = (m_start_index + 1) % (m_capacity);\n\t\t\t}\n\t\t}\n\n\t\t/// @brief Used to decrement the write index into the underlying `T` array\n\t\t/// when popping an element from the back\n\t\tinline constexpr auto decrement_write() noexcept -> void {\n\t\t\tif(m_write_index == 0_usize) {\n\t\t\t\tm_write_index = m_capacity - 1;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tm_write_index--;\n\t\t\t}\n\t\t}\n\n\t\tinline constexpr auto\n\t\tdecrement_write_n(concepts::UnsignedIntegral auto n) noexcept -> void {\n\t\t\tauto amount_to_decrement = static_cast<usize>(n);\n\t\t\tif(amount_to_decrement > m_write_index) {\n\t\t\t\tamount_to_decrement -= m_write_index;\n\t\t\t\tm_write_index = (m_capacity - 1) - amount_to_decrement;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tm_write_index -= amount_to_decrement;\n\t\t\t}\n\t\t}\n\n\t\t/// @brief Inserts the given element at the position indicated\n\t\t/// by the `external_index`\n\t\t/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`\n\t\t///\n\t\t/// @param external_index - The user-facing index into the `RingBuffer` to insert the\n\t\t/// element at\n\t\t/// @param elem - The element to store in the `RingBuffer`\n\t\tinline constexpr auto\n\t\tinsert_internal(usize external_index, const T& elem) noexcept -> void {\n\t\t\tauto index = get_adjusted_internal_index(external_index);\n\n\t\t\tif(index == m_write_index) {\n\t\t\t\templace_back(elem);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconst auto size_ = size();\n\t\t\t\tauto num_to_move = size_ - external_index;\n\t\t\t\tauto j = num_to_move - 1;\n\n\t\t\t\t// if we're full, drop the last element in the buffer\n\t\t\t\tif(size_ == m_capacity - 1) [[likely]] { // NOLINT\n\t\t\t\t\tnum_to_move--;\n\t\t\t\t\tj--;\n\t\t\t\t\tindex++;\n\t\t\t\t}\n\n\t\t\t\tfor(auto i = 0_usize; i < num_to_move; ++i, --j) {\n\t\t\t\t\tif constexpr(concepts::MoveAssignable<T>) {\n\t\t\t\t\t\tm_buffer[get_adjusted_internal_index(size_ - i)]\n\t\t\t\t\t\t\t= std::move(m_buffer[get_adjusted_internal_index(external_index + j)]);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tm_buffer[get_adjusted_internal_index(size_ - i)]\n\t\t\t\t\t\t\t= m_buffer[get_adjusted_internal_index(external_index + j)];\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tm_buffer[index] = elem;\n\t\t\t\tincrement_indices();\n\t\t\t}\n\t\t}\n\n\t\t/// @brief Inserts the given element at the position indicated\n\t\t/// by the `external_index`\n\t\t/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`\n\t\t///\n\t\t/// @param external_index - The user-facing index into the `RingBuffer` to insert the\n\t\t/// element at\n\t\t/// @param elem - The element to store in the `RingBuffer`\n\t\tinline constexpr auto insert_internal(usize external_index, T&& elem) noexcept -> void {\n\t\t\tauto index = get_adjusted_internal_index(external_index);\n\n\t\t\tif(index == m_write_index) {\n\t\t\t\templace_back(std::move(elem));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconst auto size_ = size();\n\t\t\t\tauto num_to_move = size_ - external_index;\n\t\t\t\tauto j = num_to_move - 1;\n\n\t\t\t\t// if we're full, drop the last element in the buffer\n\t\t\t\tif(size_ == m_capacity - 1) [[likely]] { // NOLINT\n\t\t\t\t\tnum_to_move--;\n\t\t\t\t\tj--;\n\t\t\t\t\tindex++;\n\t\t\t\t}\n\n\t\t\t\tfor(auto i = 0_usize; i < num_to_move; ++i, --j) {\n\t\t\t\t\tif constexpr(concepts::MoveAssignable<T>) {\n\t\t\t\t\t\tm_buffer[get_adjusted_internal_index(size_ - i)]\n\t\t\t\t\t\t\t= std::move(m_buffer[get_adjusted_internal_index(external_index + j)]);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tm_buffer[get_adjusted_internal_index(size_ - i)]\n\t\t\t\t\t\t\t= m_buffer[get_adjusted_internal_index(external_index + j)];\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tm_buffer[index] = std::move(elem);\n\t\t\t\tincrement_indices();\n\t\t\t}\n\t\t}\n\n\t\t/// @brief Constructs the given element at the insertion position indicated\n\t\t/// by the `external_index`\n\t\t/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`\n\t\t///\n\t\t/// @param external_index - The user-facing index into the `RingBuffer` to insert the\n\t\t/// element at\n\t\t/// @param args - The arguments to the constructor for\n\t\t/// the element to store in the `RingBuffer`\n\t\ttemplate<typename... Args>\n\t\trequires concepts::ConstructibleFrom<T, Args...>\n\t\tinline constexpr auto\n\t\tinsert_emplace_internal(usize external_index, Args&&... args) noexcept -> T& {\n\t\t\tauto index = get_adjusted_internal_index(external_index);\n\n\t\t\tif(index == m_write_index) {\n\t\t\t\treturn emplace_back(std::forward<Args>(args)...);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconst auto size_ = size();\n\t\t\t\tauto num_to_move = size_ - external_index;\n\t\t\t\tauto j = num_to_move - 1;\n\n\t\t\t\t// if we're full, drop the last element in the buffer\n\t\t\t\tif(size_ == m_capacity - 1) [[likely]] { // NOLINT\n\t\t\t\t\tnum_to_move--;\n\t\t\t\t\tj--;\n\t\t\t\t\tindex++;\n\t\t\t\t}\n\n\t\t\t\tfor(auto i = 0_usize; i < num_to_move; ++i, --j) {\n\t\t\t\t\tif constexpr(concepts::MoveAssignable<T>) {\n\t\t\t\t\t\tm_buffer[get_adjusted_internal_index(size_ - i)]\n\t\t\t\t\t\t\t= std::move(m_buffer[get_adjusted_internal_index(external_index + j)]);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tm_buffer[get_adjusted_internal_index(size_ - i)]\n\t\t\t\t\t\t\t= m_buffer[get_adjusted_internal_index(external_index + j)];\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tallocator_traits::template construct<T>(m_allocator,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t&m_buffer[index],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tstd::forward<Args>(args)...);\n\n\t\t\t\tincrement_indices();\n\t\t\t\treturn m_buffer[index];\n\t\t\t}\n\t\t}\n\n\t\t/// @brief Erases the element at the given index, returning an `Iterator` to the element\n\t\t/// after the removed one\n\t\t///\n\t\t/// @param external_index - The index to the element to remove. This should be a\n\t\t/// `RingBuffer` index: IE, not an internal one into the `T` array\n\t\t///\n\t\t/// @return `Iterator` pointing to the element after the one removed\n\t\t[[nodiscard]] inline constexpr auto\n\t\terase_internal(usize external_index) noexcept -> Iterator {\n\t\t\tconst auto index = get_adjusted_internal_index(external_index);\n\n\t\t\tif(index == m_write_index) [[unlikely]] { // NOLINT\n\t\t\t\treturn end();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconst auto size_ = size();\n\t\t\t\tauto num_to_move = (size_ - 1) - external_index;\n\t\t\t\tconst auto pos_to_move = external_index + 1;\n\t\t\t\tconst auto pos_to_replace = external_index;\n\t\t\t\tfor(auto i = 0_usize; i < num_to_move; ++i) {\n\t\t\t\t\tif constexpr(concepts::MoveAssignable<T>) {\n\t\t\t\t\t\tm_buffer[get_adjusted_internal_index(pos_to_replace + i)]\n\t\t\t\t\t\t\t= std::move(m_buffer[get_adjusted_internal_index(pos_to_move + i)]);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tm_buffer[get_adjusted_internal_index(pos_to_replace + i)]\n\t\t\t\t\t\t\t= m_buffer[get_adjusted_internal_index(pos_to_move + i)];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tdecrement_write();\n\n\t\t\t\treturn begin() + external_index;\n\t\t\t}\n\t\t}\n\n\t\t/// @brief Erases the range of elements in [`first`, `last`)\n\t\t/// Returns an `Iterator` to the element after the last one erased\n\t\t///\n\t\t/// @param first - The first index in the range to erase. This should be a `RingBuffer`\n\t\t/// index: IE, not an internal one into the `T` array\n\t\t/// @param last - The last index` in the range to erase. This should be a `RingBuffer`\n\t\t/// index: IE, not an internal one into the `T` array\n\t\t///\n\t\t/// @return `Iterator` pointing to the element after the last one erased\n\t\t[[nodiscard]] inline constexpr auto\n\t\terase_internal(usize first, usize last) noexcept -> Iterator {\n\t\t\tconst auto size_ = size();\n\t\t\tconst auto last_internal = get_adjusted_internal_index(last);\n\t\t\tconst auto num_to_remove = (last - first);\n\n\t\t\tif(last_internal > m_write_index) {\n\t\t\t\tif(m_write_index > m_start_index) {\n\t\t\t\t\tdecrement_write_n(num_to_remove);\n\t\t\t\t}\n\t\t\t\telse if(m_write_index < m_start_index) {\n\t\t\t\t\tauto num_after_start_index\n\t\t\t\t\t\t= (m_write_index > num_to_remove ? m_write_index - num_to_remove : 0_usize);\n\t\t\t\t\tauto num_before_start_index = num_to_remove - num_after_start_index;\n\t\t\t\t\tif(num_after_start_index > 0) {\n\t\t\t\t\t\tnum_after_start_index--;\n\t\t\t\t\t\tm_write_index = (m_capacity - 1) - num_after_start_index;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tdecrement_write_n(num_before_start_index);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn end();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconst auto num_to_move = size_ - last;\n\t\t\t\tconst auto pos_to_move = last;\n\t\t\t\tconst auto pos_to_replace = first;\n\t\t\t\tfor(auto i = 0_usize; i < num_to_move; ++i) {\n\t\t\t\t\tif constexpr(concepts::MoveAssignable<T>) {\n\t\t\t\t\t\tm_buffer[get_adjusted_internal_index(pos_to_replace + i)]\n\t\t\t\t\t\t\t= std::move(m_buffer[get_adjusted_internal_index(pos_to_move + i)]);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tm_buffer[get_adjusted_internal_index(pos_to_replace + i)]\n\t\t\t\t\t\t\t= m_buffer[get_adjusted_internal_index(pos_to_move + i)];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tdecrement_write_n(num_to_remove);\n\n\t\t\t\treturn begin() + first;\n\t\t\t}\n\t\t}\n\t};\n\n\t/// @brief A simple Ring Buffer implementation.\n\t/// Supports resizing, writing, reading, erasing, and provides mutable and immutable\n\t/// random access iterators.\n\t///\n\t/// # Iterator Invalidation\n\t/// * Iterators are lazily evaluated, so will only ever be invalidated at their current state.\n\t/// Performing any mutating operation (mutating the iterator, not the underlying data) on them\n\t/// will re-sync them with their associated `RingBuffer`.\n\t/// The following operations will invalidate an iterator's current state:\n\t/// - Read-only operations: never\n\t/// - clear: always\n\t/// - reserve: only if the `RingBuffer` changed capacity\n\t/// - erase: Erased elements and all following elements\n\t/// - push_back, emplace_back: only `end()` until `capacity()` is reached,\n\t///   then `begin()` and `end()`\n\t/// - insert, emplace: only the element at the position inserted/emplaced\n\t/// - pop_back: the element removed and `end()`\n\t/// - pop_front: the element removed and `begin()`\n\t///\n\t/// @tparam T - The type to store in the `RingBuffer`. Must Be Default Constructible.\n\t/// Does not currently support `T` of array types (eg, `T` = `U[]` or `T` = `U[N]`)\n\ttemplate<concepts::DefaultConstructible T, template<typename ElementType> typename Allocator>\n\tclass RingBuffer<T, RingBufferType::ThreadSafe, Allocator> {\n\t  public:\n\t\tusing index_type = u32;\n\n\t\t/// Default capacity of `RingBuffer`\n\t\tstatic const constexpr index_type DEFAULT_CAPACITY = 16;\n\n\t\tstruct Element {\n\t\t\tstd::shared_ptr<T> m_element = nullptr;\n\n\t\t\tconstexpr Element() noexcept = default;\n\t\t\texplicit constexpr Element(const std::shared_ptr<T>& element) noexcept\n\t\t\t\t: m_element(element) {\n\t\t\t}\n\t\t\texplicit constexpr Element(std::shared_ptr<T> element) noexcept\n\t\t\t\t: m_element(std::move(element)) {\n\t\t\t}\n\t\t\texplicit constexpr Element(T* element) noexcept : m_element(element) {\n\t\t\t}\n\t\t\tconstexpr Element(Allocator<Element>& alloc, const T& element) noexcept\n\t\t\t\t: m_element(std::allocate_shared<T, Allocator<Element>>(alloc, element)) {\n\t\t\t}\n\t\t\tconstexpr Element(Allocator<Element>& alloc, T&& element) noexcept\n\t\t\t\t: m_element(std::allocate_shared<T, Allocator<Element>>(alloc, element)) {\n\t\t\t}\n\t\t\ttemplate<typename... Args>\n\t\t\trequires concepts::ConstructibleFrom<T, Args...>\n\t\t\texplicit constexpr Element(Allocator<Element>& alloc, Args&&... args) noexcept\n\t\t\t\t: m_element(\n\t\t\t\t\tstd::allocate_shared<T, Allocator<Element>>(alloc,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstd::forward<Args>(args)...)) {\n\t\t\t}\n\t\t\tconstexpr Element(const Element& element) noexcept = default;\n\t\t\tconstexpr Element(Element&& element) noexcept = default;\n\t\t\tconstexpr ~Element() noexcept = default;\n\n\t\t\tinline constexpr auto operator=(const Element& element) noexcept -> Element& = default;\n\t\t\tinline constexpr auto operator=(Element&& element) noexcept -> Element& = default;\n\t\t\tinline constexpr auto\n\t\t\toperator=(const std::shared_ptr<T>& element) noexcept -> Element& {\n\t\t\t\tm_element = element;\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\tinline constexpr auto operator=(std::shared_ptr<T>&& element) noexcept -> Element& {\n\t\t\t\tm_element = std::move(element);\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\t// inline constexpr auto operator=(const T& element) noexcept -> Element& {\n\t\t\t//\tm_element = std::make_shared<T>(element);\n\t\t\t//\treturn *this;\n\t\t\t// }\n\t\t\t// inline constexpr auto operator=(T&& element) noexcept -> Element& {\n\t\t\t//\tm_element = std::make_shared<T>(element);\n\t\t\t//\treturn *this;\n\t\t\t// }\n\n\t\t\tinline constexpr auto operator==(const Element& element) const noexcept -> bool {\n\t\t\t\treturn *m_element == *(element.m_element);\n\t\t\t}\n\n\t\t\tinline constexpr auto operator!=(const Element& element) const noexcept -> bool {\n\t\t\t\treturn *(m_element) != *(element.m_element);\n\t\t\t}\n\n\t\t\t// friend inline constexpr auto\n\t\t\t// operator==(const Element& lhs, const T& rhs) noexcept -> bool {\n\t\t\t//\treturn (*lhs.m_element) == rhs;\n\t\t\t// }\n\n\t\t\t// friend inline constexpr auto\n\t\t\t// operator!=(const Element& lhs, const T& rhs) noexcept -> bool {\n\t\t\t//\treturn (*lhs.m_element) != rhs;\n\t\t\t// }\n\n\t\t\tinline constexpr operator T&() noexcept { // NOLINT\n\t\t\t\treturn *m_element;\n\t\t\t}\n\t\t\tinline constexpr operator const T&() const noexcept { // NOLINT\n\t\t\t\treturn *m_element;\n\t\t\t}\n\t\t\tinline constexpr auto operator*() noexcept -> T& {\n\t\t\t\treturn *m_element;\n\t\t\t}\n\t\t\tinline constexpr auto operator*() const noexcept -> const T& {\n\t\t\t\treturn *m_element;\n\t\t\t}\n\t\t\tinline constexpr auto operator->() noexcept -> T* {\n\t\t\t\treturn m_element.get();\n\t\t\t}\n\t\t\tinline constexpr auto operator->() const noexcept -> const T* {\n\t\t\t\treturn m_element.get();\n\t\t\t}\n\t\t};\n\t\tusing allocator_traits = std::allocator_traits<Allocator<Element>>;\n\t\tusing unique_pointer\n\t\t\t= decltype(allocate_unique<Element[]>(std::declval<Allocator<Element[]>>(), // NOLINT\n\t\t\t\t\t\t\t\t\t\t\t\t  DEFAULT_CAPACITY));\n\n\t\t/// @brief Random-Access Bidirectional iterator for `RingBuffer`\n\t\t/// @note All navigation operators are checked such that any movement past `begin()` or\n\t\t/// `end()` is ignored.\n\t\tclass Iterator {\n\t\t  public:\n\t\t\tusing iterator_category = std::random_access_iterator_tag;\n\t\t\tusing difference_type = std::ptrdiff_t;\n\t\t\tusing value_type = Element;\n\t\t\tusing pointer = Element;\n\t\t\tusing reference = Element&;\n\n\t\t\tconstexpr explicit Iterator(pointer ptr,\n\t\t\t\t\t\t\t\t\t\tRingBuffer* containerPtr,\n\t\t\t\t\t\t\t\t\t\tindex_type currentIndex) noexcept\n\t\t\t\t: m_ptr(ptr), m_container_ptr(containerPtr), m_current_index(currentIndex) {\n\t\t\t}\n\t\t\tconstexpr Iterator(const Iterator& iter) noexcept = default;\n\t\t\tconstexpr Iterator(Iterator&& iter) noexcept = default;\n\t\t\t~Iterator() noexcept = default;\n\n\t\t\t/// @brief Returns the index in the `RingBuffer` that corresponds\n\t\t\t/// to the element this iterator points to\n\t\t\t///\n\t\t\t/// @return The index corresponding with the element this points to\n\t\t\t[[nodiscard]] inline constexpr auto get_index() const noexcept -> index_type {\n\t\t\t\treturn m_current_index;\n\t\t\t}\n\n\t\t\tconstexpr auto operator=(const Iterator& iter) noexcept -> Iterator& = default;\n\t\t\tconstexpr auto operator=(Iterator&& iter) noexcept -> Iterator& = default;\n\n\t\t\tinline constexpr auto operator==(const Iterator& rhs) const noexcept -> bool {\n\t\t\t\treturn m_ptr == rhs.m_ptr;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator!=(const Iterator& rhs) const noexcept -> bool {\n\t\t\t\treturn m_ptr != rhs.m_ptr;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator*() noexcept -> reference {\n\t\t\t\treturn m_ptr;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator->() noexcept -> pointer {\n\t\t\t\treturn m_ptr;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator++() noexcept -> Iterator& {\n\t\t\t\tm_current_index++;\n\t\t\t\tif(m_current_index >= m_container_ptr->capacity()) {\n\t\t\t\t\tm_current_index = m_container_ptr->capacity();\n\t\t\t\t\tm_ptr = m_container_ptr->end().m_ptr;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tm_ptr = (*m_container_ptr)[m_current_index];\n\t\t\t\t}\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator++(int) noexcept -> Iterator {\n\t\t\t\tIterator temp = *this;\n\t\t\t\t++(*this);\n\t\t\t\treturn temp;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator--() noexcept -> Iterator& {\n\t\t\t\tif(m_current_index == 0) {\n\t\t\t\t\treturn *this;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tm_current_index--;\n\t\t\t\t\tm_ptr = (*m_container_ptr)[m_current_index];\n\t\t\t\t}\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator--(int) noexcept -> Iterator {\n\t\t\t\tIterator temp = *this;\n\t\t\t\t--(*this);\n\t\t\t\treturn temp;\n\t\t\t}\n\n\t\t\tinline constexpr auto\n\t\t\toperator+(concepts::Integral auto rhs) const noexcept -> Iterator {\n\t\t\t\tconst auto diff = static_cast<index_type>(rhs);\n\t\t\t\tif(rhs < 0) {\n\t\t\t\t\treturn std::move(*this - -rhs);\n\t\t\t\t}\n\n\t\t\t\tauto temp = *this;\n\t\t\t\ttemp.m_current_index += diff;\n\t\t\t\tif(temp.m_current_index > temp.m_container_ptr->capacity()) {\n\t\t\t\t\ttemp.m_current_index = temp.m_container_ptr->capacity();\n\t\t\t\t\ttemp.m_ptr = temp.m_container_ptr->end().m_ptr;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\ttemp.m_ptr = (*temp.m_container_ptr)[temp.m_current_index];\n\t\t\t\t}\n\t\t\t\treturn temp;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator+=(concepts::Integral auto rhs) noexcept -> Iterator& {\n\t\t\t\t*this = std::move(*this + rhs);\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\tinline constexpr auto\n\t\t\toperator-(concepts::Integral auto rhs) const noexcept -> Iterator {\n\t\t\t\tconst auto diff = static_cast<index_type>(rhs);\n\t\t\t\tif(rhs < 0) {\n\t\t\t\t\treturn std::move(*this + -rhs);\n\t\t\t\t}\n\n\t\t\t\tauto temp = *this;\n\t\t\t\tif(diff > temp.m_current_index) {\n\t\t\t\t\ttemp.m_ptr = temp.m_container_ptr->begin().m_ptr;\n\t\t\t\t\ttemp.m_current_index = 0;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\ttemp.m_current_index -= diff;\n\t\t\t\t\ttemp.m_ptr = (*temp.m_container_ptr)[temp.m_current_index];\n\t\t\t\t}\n\t\t\t\treturn temp;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator-=(concepts::Integral auto rhs) noexcept -> Iterator& {\n\t\t\t\t*this = std::move(*this - rhs);\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator-(const Iterator& rhs) const noexcept -> difference_type {\n\t\t\t\treturn static_cast<std::ptrdiff_t>(m_current_index)\n\t\t\t\t\t   - static_cast<std::ptrdiff_t>(rhs.m_current_index);\n\t\t\t}\n\n\t\t\tinline constexpr auto operator[](concepts::Integral auto index) noexcept -> Iterator {\n\t\t\t\treturn std::move(*this + index);\n\t\t\t}\n\n\t\t\tinline constexpr auto operator>(const Iterator& rhs) const noexcept -> bool {\n\t\t\t\treturn m_current_index > rhs.m_current_index;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator<(const Iterator& rhs) const noexcept -> bool {\n\t\t\t\treturn m_current_index < rhs.m_current_index;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator>=(const Iterator& rhs) const noexcept -> bool {\n\t\t\t\treturn m_current_index >= rhs.m_current_index;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator<=(const Iterator& rhs) const noexcept -> bool {\n\t\t\t\treturn m_current_index <= rhs.m_current_index;\n\t\t\t}\n\n\t\t  private:\n\t\t\tpointer m_ptr;\n\t\t\tRingBuffer* m_container_ptr = nullptr;\n\t\t\tindex_type m_current_index = 0;\n\t\t};\n\n\t\t/// @brief Read-only Random-Access Bidirectional iterator for `RingBuffer`\n\t\t/// @note All navigation operators are checked such that any movement past `begin()` or\n\t\t/// `end()` is ignored.\n\t\tclass ConstIterator {\n\t\t  public:\n\t\t\tusing iterator_category = std::random_access_iterator_tag;\n\t\t\tusing difference_type = std::ptrdiff_t;\n\t\t\tusing value_type = Element;\n\t\t\tusing pointer = const Element;\n\t\t\tusing reference = const Element&;\n\n\t\t\tconstexpr explicit ConstIterator(pointer ptr,\n\t\t\t\t\t\t\t\t\t\t\t RingBuffer* containerPtr,\n\t\t\t\t\t\t\t\t\t\t\t index_type currentIndex) noexcept\n\t\t\t\t: m_ptr(ptr), m_container_ptr(containerPtr), m_current_index(currentIndex) {\n\t\t\t}\n\t\t\tconstexpr ConstIterator(const ConstIterator& iter) noexcept = default;\n\t\t\tconstexpr ConstIterator(ConstIterator&& iter) noexcept = default;\n\t\t\t~ConstIterator() noexcept = default;\n\n\t\t\t/// @brief Returns the index in the `RingBuffer` that corresponds\n\t\t\t/// to the element this iterator points to\n\t\t\t///\n\t\t\t/// @return The index corresponding with the element this points to\n\t\t\t[[nodiscard]] inline constexpr auto get_index() const noexcept -> index_type {\n\t\t\t\treturn m_current_index;\n\t\t\t}\n\n\t\t\tconstexpr auto\n\t\t\toperator=(const ConstIterator& iter) noexcept -> ConstIterator& = default;\n\t\t\tconstexpr auto operator=(ConstIterator&& iter) noexcept -> ConstIterator& = default;\n\n\t\t\tinline constexpr auto operator==(const ConstIterator& rhs) const noexcept -> bool {\n\t\t\t\treturn m_ptr == rhs.m_ptr;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator!=(const ConstIterator& rhs) const noexcept -> bool {\n\t\t\t\treturn m_ptr != rhs.m_ptr;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator*() const noexcept -> reference {\n\t\t\t\treturn m_ptr;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator->() const noexcept -> pointer {\n\t\t\t\treturn m_ptr;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator++() noexcept -> ConstIterator& {\n\t\t\t\tm_current_index++;\n\t\t\t\tif(m_current_index >= m_container_ptr->capacity()) {\n\t\t\t\t\tm_current_index = m_container_ptr->capacity();\n\t\t\t\t\tm_ptr = m_container_ptr->end().m_ptr;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tm_ptr = (*m_container_ptr)[m_current_index];\n\t\t\t\t}\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator++(int) noexcept -> ConstIterator {\n\t\t\t\tConstIterator temp = *this;\n\t\t\t\t++(*this);\n\t\t\t\treturn temp;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator--() noexcept -> ConstIterator& {\n\t\t\t\tif(m_current_index == 0) {\n\t\t\t\t\treturn *this;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tm_current_index--;\n\t\t\t\t\tm_ptr = (*m_container_ptr)[m_current_index];\n\t\t\t\t}\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator--(int) noexcept -> ConstIterator {\n\t\t\t\tConstIterator temp = *this;\n\t\t\t\t--(*this);\n\t\t\t\treturn temp;\n\t\t\t}\n\n\t\t\tinline constexpr auto\n\t\t\toperator+(concepts::Integral auto rhs) const noexcept -> ConstIterator {\n\t\t\t\tconst auto diff = static_cast<index_type>(rhs);\n\t\t\t\tif(rhs < 0) {\n\t\t\t\t\treturn std::move(*this - -rhs);\n\t\t\t\t}\n\n\t\t\t\tauto temp = *this;\n\t\t\t\ttemp.m_current_index += diff;\n\t\t\t\tif(temp.m_current_index > temp.m_container_ptr->capacity()) {\n\t\t\t\t\ttemp.m_current_index = temp.m_container_ptr->capacity();\n\t\t\t\t\ttemp.m_ptr = temp.m_container_ptr->end().m_ptr;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\ttemp.m_ptr = (*temp.m_container_ptr)[temp.m_current_index];\n\t\t\t\t}\n\t\t\t\treturn temp;\n\t\t\t}\n\n\t\t\tinline constexpr auto\n\t\t\toperator+=(concepts::Integral auto rhs) noexcept -> ConstIterator& {\n\t\t\t\t*this = std::move(*this + rhs);\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\tinline constexpr auto\n\t\t\toperator-(concepts::Integral auto rhs) const noexcept -> ConstIterator {\n\t\t\t\tconst auto diff = static_cast<index_type>(rhs);\n\t\t\t\tif(rhs < 0) {\n\t\t\t\t\treturn std::move(*this + -rhs);\n\t\t\t\t}\n\n\t\t\t\tauto temp = *this;\n\t\t\t\tif(diff > temp.m_current_index) {\n\t\t\t\t\ttemp.m_ptr = temp.m_container_ptr->begin().m_ptr;\n\t\t\t\t\ttemp.m_current_index = 0;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\ttemp.m_current_index -= diff;\n\t\t\t\t\ttemp.m_ptr = (*temp.m_container_ptr)[temp.m_current_index];\n\t\t\t\t}\n\t\t\t\treturn temp;\n\t\t\t}\n\n\t\t\tinline constexpr auto\n\t\t\toperator-=(concepts::Integral auto rhs) noexcept -> ConstIterator& {\n\t\t\t\t*this = std::move(*this - rhs);\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\tinline constexpr auto\n\t\t\toperator-(const ConstIterator& rhs) const noexcept -> difference_type {\n\t\t\t\treturn static_cast<std::ptrdiff_t>(m_current_index)\n\t\t\t\t\t   - static_cast<std::ptrdiff_t>(rhs.m_current_index);\n\t\t\t}\n\n\t\t\tinline constexpr auto\n\t\t\toperator[](concepts::Integral auto index) const noexcept -> ConstIterator {\n\t\t\t\treturn std::move(*this + index);\n\t\t\t}\n\n\t\t\tinline constexpr auto operator>(const ConstIterator& rhs) const noexcept -> bool {\n\t\t\t\treturn m_current_index > rhs.m_current_index;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator<(const ConstIterator& rhs) const noexcept -> bool {\n\t\t\t\treturn m_current_index < rhs.m_current_index;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator>=(const ConstIterator& rhs) const noexcept -> bool {\n\t\t\t\treturn m_current_index >= rhs.m_current_index;\n\t\t\t}\n\n\t\t\tinline constexpr auto operator<=(const ConstIterator& rhs) const noexcept -> bool {\n\t\t\t\treturn m_current_index <= rhs.m_current_index;\n\t\t\t}\n\n\t\t  private:\n\t\t\tpointer m_ptr;\n\t\t\tRingBuffer* m_container_ptr = nullptr;\n\t\t\tindex_type m_current_index = 0;\n\t\t};\n\n\t\t/// @brief Creates a `RingBuffer` with default capacity\n\t\tconstexpr RingBuffer() noexcept = default;\n\n\t\t/// @brief Creates a `RingBuffer` with (at least) the given initial capacity\n\t\t///\n\t\t/// @param intitial_capacity - The initial capacity of the `RingBuffer`\n\t\tconstexpr explicit RingBuffer(index_type intitial_capacity) noexcept\n\t\t\t: m_buffer(allocate_unique<Element[]>(m_allocator, // NOLINT\n\t\t\t\t\t\t\t\t\t\t\t\t  intitial_capacity + 1,\n\t\t\t\t\t\t\t\t\t\t\t\t  m_allocator)),\n\t\t\t  m_state(intitial_capacity + 1) {\n\t\t}\n\n\t\t/// @brief Constructs a new `RingBuffer` with the given initial capacity and\n\t\t/// fills it with `default_value`\n\t\t///\n\t\t/// @param intitial_capacity - The initial capacity of the `RingBuffer`\n\t\t/// @param default_value - The value to fill the `RingBuffer` with\n\t\tconstexpr RingBuffer(\n\t\t\tindex_type intitial_capacity,\n\t\t\tconst T& default_value) noexcept requires concepts::CopyConstructible<T>\n\t\t\t: m_buffer(allocate_unique<Element[]>(m_allocator, // NOLINT\n\t\t\t\t\t\t\t\t\t\t\t\t  intitial_capacity + 1,\n\t\t\t\t\t\t\t\t\t\t\t\t  m_allocator,\n\t\t\t\t\t\t\t\t\t\t\t\t  default_value)),\n\t\t\t  m_state(intitial_capacity + 1, 0U, intitial_capacity) {\n\t\t}\n\n\t\tconstexpr RingBuffer(const RingBuffer& buffer) noexcept requires concepts::CopyAssignable<T>\n\t\t\t: m_buffer(allocate_unique<Element[]>(m_allocator, // NOLINT\n\t\t\t\t\t\t\t\t\t\t\t\t  buffer.m_capacity,\n\t\t\t\t\t\t\t\t\t\t\t\t  m_allocator)),\n\t\t\t  m_state(buffer.m_capacity) {\n\t\t\tconst auto size = buffer.size();\n\t\t\tfor(auto i = 0_u32; i < size; ++i) {\n\t\t\t\tpush_back(buffer.m_buffer[i]);\n\t\t\t}\n\t\t\tm_state = buffer.m_state;\n\t\t}\n\n\t\tconstexpr RingBuffer(RingBuffer&& buffer) noexcept\n\t\t\t: m_allocator(buffer.m_allocator),\n\t\t\t  m_buffer(std::move(buffer.m_buffer)),\n\t\t\t  m_state(buffer.m_state) {\n\t\t\tbuffer.m_state.update(0U, 0U, 0U);\n\t\t\tbuffer.m_buffer = nullptr;\n\t\t}\n\n\t\t~RingBuffer() noexcept = default;\n\n\t\t/// @brief Returns the element at the given index.\n\t\t/// @note This is not checked in the same manner as STL containers:\n\t\t/// if index >= capacity, the element at capacity - 1 is returned.\n\t\t///\n\t\t/// @param index - The index of the desired element\n\t\t///\n\t\t/// @return The element at the given index, or at capacity - 1 if index >= capacity\n\t\t[[nodiscard]] inline constexpr auto at(concepts::Integral auto index) noexcept -> Element {\n\t\t\tconst auto i = m_state.adjusted_index(static_cast<index_type>(index));\n\n\t\t\treturn m_buffer[i]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\n\t\t}\n\n\t\t/// @brief Returns the first element in the `RingBuffer`\n\t\t///\n\t\t/// @return The first element\n\t\t[[nodiscard]] inline constexpr auto front() noexcept -> Element {\n\t\t\treturn m_buffer\n\t\t\t\t[m_state.start()]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\n\t\t}\n\n\t\t/// @brief Returns the last element in the `RingBuffer`\n\t\t/// @note If <= 1 elements are in the `RingBuffer`, this will be the same as `front`\n\t\t///\n\t\t/// @return The last element\n\t\t[[nodiscard]] inline constexpr auto back() noexcept -> Element {\n\t\t\tconst auto index = m_state.back();\n\n\t\t\treturn m_buffer[index]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\n\t\t}\n\n\t\t/// @brief Returns a pointer to the underlying data in the `RingBuffer`.\n\t\t/// @note This is not sorted in any way to match the representation used by the `RingBuffer`\n\t\t///\n\t\t/// @return A pointer to the underlying data\n\t\t[[nodiscard]] inline constexpr auto data() noexcept -> Element* {\n\t\t\treturn m_buffer;\n\t\t}\n\n\t\t/// @brief Returns whether the `RingBuffer` is empty\n\t\t///\n\t\t/// @return `true` if the `RingBuffer` is empty, `false` otherwise\n\t\t[[nodiscard]] inline constexpr auto empty() const noexcept -> bool {\n\t\t\treturn m_state.empty();\n\t\t}\n\n\t\t/// @brief Returns whether the `RingBuffer` is full\n\t\t///\n\t\t/// @return `true` if the `RingBuffer` is full, `false` otherwise\n\t\t[[nodiscard]] inline constexpr auto full() const noexcept -> bool {\n\t\t\treturn m_state.full();\n\t\t}\n\n\t\t/// @brief Returns the current number of elements in the `RingBuffer`\n\t\t///\n\t\t/// @return The current number of elements\n\t\t[[nodiscard]] inline constexpr auto size() const noexcept -> index_type {\n\t\t\treturn m_state.size();\n\t\t}\n\n\t\t/// @brief Returns the maximum possible number of elements this `RingBuffer` could store\n\t\t/// if grown to maximum possible capacity\n\t\t///\n\t\t/// @return The maximum possible number of storable elements\n\t\t[[nodiscard]] inline constexpr auto max_size() const noexcept -> index_type {\n\t\t\treturn m_state.max_size();\n\t\t}\n\n\t\t/// @brief Returns the current capacity of the `RingBuffer`;\n\t\t/// the number of elements it can currently store\n\t\t///\n\t\t/// @return The current capacity\n\t\t[[nodiscard]] inline constexpr auto capacity() const noexcept -> index_type {\n\t\t\treturn m_state.capacity() - 1;\n\t\t}\n\n\t\t/// @brief Reserves more storage for the `RingBuffer`. If `new_capacity` is > capacity,\n\t\t/// then the capacity of the `RingBuffer` will be extended until at least `new_capacity`\n\t\t/// elements can be stored.\n\t\t/// @note Memory contiguity is maintained, so no **elements** will be lost or invalidated.\n\t\t/// However, all iterators and references to elements will be invalidated.\n\t\t///\n\t\t/// @param new_capacity - The new capacity of the `RingBuffer`\n\t\tinline constexpr auto reserve(index_type new_capacity) noexcept -> void {\n\t\t\tauto capacity_ = m_state.capacity();\n\n\t\t\t// we only need to do anything if `new_capacity` is actually larger than `m_capacity`\n\t\t\tif(new_capacity > capacity_ - 1) {\n\t\t\t\tauto temp = allocate_unique<Element[]>(m_allocator, // NOLINT\n\t\t\t\t\t\t\t\t\t\t\t\t\t   new_capacity + 1,\n\t\t\t\t\t\t\t\t\t\t\t\t\t   m_allocator);\n\t\t\t\tauto span = gsl::make_span(&temp[0], new_capacity + 1);\n\t\t\t\tstd::copy(begin(), end(), span.begin());\n\t\t\t\tm_buffer = std::move(temp);\n\t\t\t\tm_state.update(0U, capacity_, new_capacity + 1);\n\t\t\t}\n\t\t}\n\n\t\t/// @brief Erases all elements from the `RingBuffer`\n\t\tinline constexpr auto clear() noexcept -> void {\n\t\t\tm_state.clear();\n\t\t}\n\n\t\t/// @brief Inserts the given element at the end of the `RingBuffer`\n\t\t/// @note if `size() == capacity()` then this loops and overwrites `front()`\n\t\t///\n\t\t/// @param value - the element to insert\n\t\tinline constexpr auto\n\t\tpush_back(const T& value) noexcept -> void requires concepts::CopyAssignable<T> {\n\t\t\tm_buffer[m_state.write()] // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\n\t\t\t\t= Element(m_allocator, value);\n\n\t\t\tm_state.increment_indices();\n\t\t}\n\n\t\t/// @brief Inserts the given element at the end of the `RingBuffer`\n\t\t/// @note if `size() == capacity()` then this loops and overwrites `front()`\n\t\t///\n\t\t/// @param value - the element to insert\n\t\tinline constexpr auto push_back(T&& value) noexcept -> void {\n\t\t\tm_buffer[m_state.write()] // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\n\t\t\t\t= Element(m_allocator, std::forward<T>(value));\n\n\t\t\tm_state.increment_indices();\n\t\t}\n\n\t\t/// @brief Inserts the given element at the end of the `RingBuffer`\n\t\t/// @note if `size() == capacity()` then this loops and overwrites `front()`\n\t\t///\n\t\t/// @param element - the element to insert\n\t\tinline constexpr auto push_back(const Element& element) noexcept -> void {\n\t\t\tm_buffer[m_state.write()] // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\n\t\t\t\t= element;\n\n\t\t\tm_state.increment_indices();\n\t\t}\n\n\t\t/// @brief Inserts the given element at the end of the `RingBuffer`\n\t\t/// @note if `size() == capacity()` then this loops and overwrites `front()`\n\t\t///\n\t\t/// @param element - the element to insert\n\t\tinline constexpr auto push_back(Element&& element) noexcept -> void {\n\t\t\tm_buffer[m_state.write()] // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\n\t\t\t\t= std::forward<Element>(element);\n\t\t\tm_state.increment_indices();\n\t\t}\n\n\t\t/// @brief Constructs the given element in place at the end of the `RingBuffer`\n\t\t/// @note if `size() == capacity()` then this loops and overwrites `front()`\n\t\t///\n\t\t/// @tparam Args - The types of the element's constructor arguments\n\t\t/// @param args - The constructor arguments for the element\n\t\t///\n\t\t/// @return A reference to the element constructed at the end of the `RingBuffer`\n\t\ttemplate<typename... Args>\n\t\trequires concepts::ConstructibleFrom<T, Args...>\n\t\tinline constexpr auto emplace_back(Args&&... args) noexcept -> Element {\n\t\t\tconst auto index = m_state.write();\n\n\t\t\tallocator_traits::template construct<Element>(\n\t\t\t\tm_allocator,\n\t\t\t\t&m_buffer[index], // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\n\t\t\t\tstd::allocate_shared<T, Allocator<Element>>(m_allocator,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstd::forward<Args>(args)...));\n\n\t\t\tm_state.increment_indices();\n\n\t\t\treturn m_buffer[index]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\n\t\t}\n\n\t\t/// @brief Constructs the given element in place at the location\n\t\t/// indicated by the `Iterator` `position`\n\t\t///\n\t\t/// @tparam Args - The types of the element's constructor arguments\n\t\t/// @param position - `Iterator` indicating where in the `RingBuffer` to construct the\n\t\t/// element\n\t\t/// @param args - The constructor arguments for the element\n\t\t///\n\t\t/// @return A reference to the element constructed at the location indicated by `position`\n\t\ttemplate<typename... Args>\n\t\trequires concepts::ConstructibleFrom<T, Args...>\n\t\tinline constexpr auto\n\t\templace(const Iterator& position, Args&&... args) noexcept -> Element {\n\t\t\tconst auto index = m_state.get_adjusted_internal_index(position.get_index());\n\n\t\t\tallocator_traits::template construct<Element>(\n\t\t\t\tm_allocator,\n\t\t\t\t&m_buffer[index], // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\n\t\t\t\tstd::allocate_shared<T, Allocator<Element>>(m_allocator,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstd::forward<Args>(args)...));\n\n\t\t\treturn m_buffer[index]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\n\t\t}\n\n\t\t/// @brief Constructs the given element in place at the location\n\t\t/// indicated by the `ConstIterator` `position`\n\t\t///\n\t\t/// @tparam Args - The types of the element's constructor arguments\n\t\t/// @param position - `ConstIterator` indicating where in the `RingBuffer` to construct the\n\t\t/// element\n\t\t/// @param args - The constructor arguments for the element\n\t\t///\n\t\t/// @return A reference to the element constructed at the location indicated by `position`\n\t\ttemplate<typename... Args>\n\t\tinline constexpr auto\n\t\templace(const ConstIterator& position, Args&&... args) noexcept -> Element {\n\t\t\tconst auto index = m_state.get_adjusted_internal_index(position.get_index());\n\n\t\t\tallocator_traits::template construct<Element>(\n\t\t\t\tm_allocator,\n\t\t\t\t&m_buffer[index], // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\n\t\t\t\tstd::allocate_shared<T, Allocator<Element>>(m_allocator,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstd::forward<Args>(args)...));\n\n\t\t\treturn m_buffer[index]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\n\t\t}\n\n\t\t/// @brief Assigns the given element to the position indicated\n\t\t/// by the `Iterator` `position`\n\t\t/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`\n\t\t///\n\t\t/// @param position - `Iterator` indicating where in the `RingBuffer` to place the element\n\t\t/// @param element - The element to store in the `RingBuffer`\n\t\tinline constexpr auto insert(const Iterator& position, const T& element) noexcept\n\t\t\t-> void requires concepts::CopyAssignable<T> {\n\t\t\tinsert_internal(position.get_index(), element);\n\t\t}\n\n\t\t/// @brief Assigns the given element to the position indicated\n\t\t/// by the `Iterator` `position`\n\t\t/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`\n\t\t///\n\t\t/// @param position - `Iterator` indicating where in the `RingBuffer` to place the element\n\t\t/// @param element - The element to store in the `RingBuffer`\n\t\tinline constexpr auto insert(const Iterator& position, T&& element) noexcept -> void {\n\t\t\tinsert_internal(position.get_index(), std::forward<T>(element));\n\t\t}\n\n\t\t/// @brief Assigns the given element to the position indicated\n\t\t/// by the `ConstIterator` `position`\n\t\t/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`\n\t\t///\n\t\t/// @param position - `ConstIterator` indicating where in the `RingBuffer` to place the\n\t\t/// element\n\t\t/// @param element - The element to store in the `RingBuffer`\n\t\tinline constexpr auto insert(const ConstIterator& position, const T& element) noexcept\n\t\t\t-> void requires concepts::CopyAssignable<T> {\n\t\t\tinsert_internal(position.get_index(), element);\n\t\t}\n\n\t\t/// @brief Assigns the given element to the position indicated\n\t\t/// by the `ConstIterator` `position`\n\t\t/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`\n\t\t///\n\t\t/// @param position - `ConstIterator` indicating where in the `RingBuffer` to place the\n\t\t/// element\n\t\t/// @param element - The element to store in the `RingBuffer`\n\t\tinline constexpr auto insert(const ConstIterator& position, T&& element) noexcept -> void {\n\t\t\tinsert_internal(position.get_index(), std::forward<T>(element));\n\t\t}\n\n\t\t/// @brief Constructs the given element at the insertion position indicated\n\t\t/// by the `ConstIterator` `position`\n\t\t/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`\n\t\t///\n\t\t/// @param position - `ConstIterator` indicating where in the `RingBuffer` to place the\n\t\t/// element\n\t\t/// @param args - The arguments to the constructor for\n\t\t/// the element to store in the `RingBuffer`\n\t\ttemplate<typename... Args>\n\t\trequires concepts::ConstructibleFrom<T, Args...>\n\t\tinline constexpr auto\n\t\tinsert_emplace(const Iterator& position, Args&&... args) noexcept -> Element {\n\t\t\treturn insert_emplace_internal(position.get_index(), std::forward<Args>(args)...);\n\t\t}\n\n\t\t/// @brief Constructs the given element at the insertion position indicated\n\t\t/// by the `ConstIterator` `position`\n\t\t/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`\n\t\t///\n\t\t/// @param position - `ConstIterator` indicating where in the `RingBuffer` to place the\n\t\t/// element\n\t\t/// @param args - The arguments to the constructor for\n\t\t/// the element to store in the `RingBuffer`\n\t\ttemplate<typename... Args>\n\t\trequires concepts::ConstructibleFrom<T, Args...>\n\t\tinline constexpr auto\n\t\tinsert_emplace(const ConstIterator& position, Args&&... args) noexcept -> Element {\n\t\t\treturn insert_emplace_internal(position.get_index(), std::forward<Args>(args)...);\n\t\t}\n\n\t\t/// @brief Erases the element at the given `position`, moving other elements backward\n\t\t/// in the buffer to maintain contiguity\n\t\t///\n\t\t/// @param position - The element to erase\n\t\t///\n\t\t/// @return `Iterator` pointing to the element after the one erased\n\t\tinline constexpr auto erase(const Iterator& position) noexcept -> Iterator {\n\t\t\treturn erase_internal(position.get_index());\n\t\t}\n\n\t\t/// @brief Erases the element at the given `position`, moving other elements backward\n\t\t/// in the buffer to maintain contiguity\n\t\t///\n\t\t/// @param position - The element to erase\n\t\t///\n\t\t/// @return `Iterator` pointing to the element after the one erased\n\t\tinline constexpr auto erase(const ConstIterator& position) noexcept -> Iterator {\n\t\t\treturn erase_internal(position.get_index());\n\t\t}\n\n\t\t/// @brief Erases the range of elements in [`first`, `last`)\n\t\t/// Returns an `Iterator` to the element after the last one erased\n\t\t/// @note In the case `first` >= `last`, no elements are erased and `last` is returned;\n\t\t///\n\t\t/// @param first - The first element in the range to erase\n\t\t/// @param last - The last element in the range\n\t\t///\n\t\t/// @return `Iterator` pointing to the element after the last one erased\n\t\tinline constexpr auto\n\t\terase(const Iterator& first, const Iterator& last) noexcept -> Iterator {\n\t\t\tif(first >= last) {\n\t\t\t\treturn last;\n\t\t\t}\n\n\t\t\treturn erase_internal(first.get_index(), last.get_index());\n\t\t}\n\n\t\t/// @brief Erases the range of elements in [`first`, `last`)\n\t\t/// Returns an `Iterator` to the element after the last one erased\n\t\t/// @note In the case `first` >= `last`, no elements are erased and `last` is returned;\n\t\t///\n\t\t/// @param first - The first element in the range to erase\n\t\t/// @param last - The last element in the range\n\t\t///\n\t\t/// @return `Iterator` pointing to the element after the last one erased\n\t\tinline constexpr auto\n\t\terase(const ConstIterator& first, const ConstIterator& last) noexcept -> Iterator {\n\t\t\tif(first >= last) {\n\t\t\t\treturn last;\n\t\t\t}\n\n\t\t\treturn erase_internal(first.get_index(), last.get_index());\n\t\t}\n\n\t\t/// @brief Removes the last element in the `RingBuffer` and returns it\n\t\t///\n\t\t/// @return The last element in the `RingBuffer`\n\t\t[[nodiscard]] inline constexpr auto pop_back() noexcept -> Element {\n\t\t\tElement back_ = back();\n\t\t\tm_state.decrement_write();\n\t\t\treturn back_;\n\t\t}\n\n\t\t/// @brief Removes the first element in the `RingBuffer` and returns it\n\t\t///\n\t\t/// @return The first element in the `RingBuffer`\n\t\t[[nodiscard]] inline constexpr auto pop_front() noexcept -> Element {\n\t\t\tElement front_ = front();\n\t\t\tm_state.increment_start();\n\t\t\treturn front_;\n\t\t}\n\n\t\t/// @brief Returns a Random Access Bidirectional iterator over the `RingBuffer`,\n\t\t/// at the beginning\n\t\t///\n\t\t/// @return The iterator, at the beginning\n\t\t[[nodiscard]] inline constexpr auto begin() -> Iterator {\n\t\t\t// clang-format off\n\t\t\tElement p = m_buffer[m_state.start()]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\n\t\t\t// clang-format on\n\n\t\t\treturn Iterator(p, this, 0U);\n\t\t}\n\n\t\t/// @brief Returns a Random Access Bidirectional iterator over the `RingBuffer`,\n\t\t/// at the end\n\t\t///\n\t\t/// @return The iterator, at the end\n\t\t[[nodiscard]] inline constexpr auto end() -> Iterator {\n\t\t\t// clang-format off\n\t\t\tElement p = m_buffer[m_state.write()]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\n\t\t\t// clang-format on\n\n\t\t\treturn Iterator(p, this, m_state.size());\n\t\t}\n\n\t\t/// @brief Returns a Random Access Bidirectional read-only iterator over the `RingBuffer`,\n\t\t/// at the beginning\n\t\t///\n\t\t/// @return The iterator, at the beginning\n\t\t[[nodiscard]] inline constexpr auto cbegin() -> ConstIterator {\n\t\t\t// clang-format off\n\t\t\tElement p = m_buffer[m_state.start()]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\n\t\t\t// clang-format on\n\n\t\t\treturn ConstIterator(p, this, 0U);\n\t\t}\n\n\t\t/// @brief Returns a Random Access Bidirectional read-only iterator over the `RingBuffer`,\n\t\t/// at the end\n\t\t///\n\t\t/// @return The iterator, at the end\n\t\t[[nodiscard]] inline constexpr auto cend() -> ConstIterator {\n\t\t\t// clang-format off\n\t\t\tElement p = m_buffer[m_state.write()]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\n\t\t\t// clang-format on\n\n\t\t\treturn ConstIterator(p, this, m_state.size());\n\t\t}\n\n\t\t/// @brief Unchecked access-by-index operator\n\t\t///\n\t\t/// @param index - The index to get the corresponding element for\n\t\t///\n\t\t/// @return - The element at index\n\t\t[[nodiscard]] inline constexpr auto\n\t\toperator[](concepts::Integral auto index) noexcept -> Element {\n\t\t\tconst auto i = m_state.adjusted_index(static_cast<index_type>(index));\n\n\t\t\treturn m_buffer[i]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\n\t\t}\n\n\t\tconstexpr auto operator=(const RingBuffer& buffer) noexcept\n\t\t\t-> RingBuffer& requires concepts::CopyAssignable<T> {\n\t\t\tif(this == &buffer) {\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\tauto temp = allocate_unique<Element[]>(m_allocator, // NOLINT\n\t\t\t\t\t\t\t\t\t\t\t\t   buffer.m_capacity,\n\t\t\t\t\t\t\t\t\t\t\t\t   m_allocator);\n\t\t\tconst auto size = buffer.size();\n\t\t\tfor(auto i = 0_u32; i < size; ++i) {\n\t\t\t\ttemp[i]\t\t\t\t\t  // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\n\t\t\t\t\t= buffer.m_buffer[i]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)\n\t\t\t}\n\t\t\tm_buffer = std::move(temp);\n\t\t\tm_state = m_buffer.m_state;\n\t\t\treturn *this;\n\t\t}\n\t\tconstexpr auto operator=(RingBuffer&& buffer) noexcept -> RingBuffer& {\n\t\t\tm_allocator = buffer.m_allocator;\n\t\t\tm_buffer = std::move(buffer.m_buffer);\n\t\t\tm_state = m_buffer.m_state;\n\t\t\tbuffer.m_buffer = nullptr;\n\t\t\tbuffer.m_state.update(0U, 0U, 0U);\n\t\t\treturn *this;\n\t\t}\n\n\t  private:\n\t\tstatic const constexpr u32 DEFAULT_CAPACITY_INTERNAL = DEFAULT_CAPACITY + 1;\n\n\t\tclass State {\n\t\t  public:\n\t\t\tusing merged_type = uint64_t;\n\t\t\tusing atomic_index_type = std::atomic<index_type>;\n\t\t\tusing atomic_merged_type = std::atomic<merged_type>;\n\n\t\t\tconstexpr State() noexcept = default;\n\t\t\texplicit constexpr State(index_type capacity) noexcept : m_capacity(capacity) {\n\t\t\t}\n\t\t\texplicit constexpr State(index_type capacity, // NOLINT\n\t\t\t\t\t\t\t\t\t index_type start,\n\t\t\t\t\t\t\t\t\t index_type write) noexcept\n\t\t\t\t: m_indices(merge_indices(start, write)), m_capacity(capacity) {\n\t\t\t}\n\t\t\tconstexpr State(const State& state) noexcept\n\t\t\t\t: m_indices(state.m_indices.load()), m_capacity(state.m_capacity.load()) {\n\t\t\t}\n\t\t\tconstexpr State(State&& state) noexcept\n\t\t\t\t: m_indices(state.m_indices.load()), m_capacity(state.m_capacity.load()) {\n\t\t\t}\n\t\t\tconstexpr ~State() noexcept = default;\n\n\t\t\tinline constexpr auto\n\t\t\tupdate(index_type start, index_type write, index_type capacity) // NOLINT\n\t\t\t\tnoexcept -> void {\n\t\t\t\tauto indices = m_indices.load();\n\t\t\t\twhile(!m_indices.compare_exchange_weak(indices, merge_indices(start, write))) {\n\t\t\t\t}\n\n\t\t\t\tauto capacity_ = m_capacity.load();\n\t\t\t\twhile(!m_capacity.compare_exchange_weak(capacity_, capacity)) {\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t[[nodiscard]] inline constexpr auto start() const noexcept -> index_type {\n\t\t\t\treturn start(m_indices.load());\n\t\t\t}\n\n\t\t\t[[nodiscard]] inline constexpr auto write() const noexcept -> index_type {\n\t\t\t\treturn write(m_indices.load());\n\t\t\t}\n\n\t\t\t[[nodiscard]] inline constexpr auto\n\t\t\tindices() const noexcept -> std::tuple<index_type, index_type> {\n\t\t\t\tconst auto val = m_indices.load();\n\t\t\t\treturn {start(val), write(val)};\n\t\t\t}\n\n\t\t\t[[nodiscard]] inline constexpr auto capacity() const noexcept -> index_type {\n\t\t\t\treturn m_capacity.load();\n\t\t\t}\n\n\t\t\t[[nodiscard]] inline constexpr auto max_size() const noexcept -> index_type {\n\t\t\t\treturn std::numeric_limits<index_type>::max() - 1;\n\t\t\t}\n\n\t\t\t[[nodiscard]] inline constexpr auto loop_index() const noexcept -> index_type {\n\t\t\t\treturn m_capacity.load() - 1;\n\t\t\t}\n\n\t\t\t[[nodiscard]] inline constexpr auto size() const noexcept -> index_type {\n\t\t\t\tconst auto indices = m_indices.load();\n\t\t\t\tconst auto capacity_ = m_capacity.load();\n\t\t\t\tconst auto start_ = start(indices);\n\t\t\t\tconst auto write_ = write(indices);\n\t\t\t\treturn write_ >= start_ ? (write_ - start_) : (capacity_ - (start_ - write_));\n\t\t\t}\n\n\t\t\t[[nodiscard]] inline constexpr auto\n\t\t\tsize(concepts::UnsignedIntegral auto start,\n\t\t\t\t concepts::UnsignedIntegral auto write,\n\t\t\t\t concepts::UnsignedIntegral auto capacity) const noexcept -> index_type {\n\t\t\t\tconst auto start_ = static_cast<index_type>(start);\n\t\t\t\tconst auto write_ = static_cast<index_type>(write);\n\t\t\t\tconst auto capacity_ = static_cast<index_type>(capacity);\n\t\t\t\treturn static_cast<index_type>(write_ >= start_ ? (write_ - start_) :\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(capacity_ - (start_ - write_)));\n\t\t\t}\n\n\t\t\t[[nodiscard]] inline constexpr auto empty() const noexcept -> bool {\n\t\t\t\treturn size() == 0_u32;\n\t\t\t}\n\n\t\t\t[[nodiscard]] inline constexpr auto full() const noexcept -> bool {\n\t\t\t\tconst auto indices = m_indices.load();\n\t\t\t\tconst auto capacity_ = m_capacity.load();\n\t\t\t\tconst auto start_ = start(indices);\n\t\t\t\tconst auto write_ = write(indices);\n\t\t\t\tconst auto size_\n\t\t\t\t\t= write_ >= start_ ? (write_ - start_) : (capacity_ - (start_ - write_));\n\t\t\t\treturn size_ == capacity_ - 1;\n\t\t\t}\n\n\t\t\tinline constexpr auto clear() noexcept -> void {\n\t\t\t\tauto indices = m_indices.load();\n\t\t\t\twhile(!m_indices.compare_exchange_weak(indices, merge_indices(0U, 0U))) {\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t[[nodiscard]] inline constexpr auto\n\t\t\tadjusted_index(concepts::UnsignedIntegral auto index) const noexcept -> index_type {\n\t\t\t\tconst auto i = static_cast<index_type>(index);\n\t\t\t\treturn (start() + i) % capacity();\n\t\t\t}\n\n\t\t\t[[nodiscard]] inline constexpr auto\n\t\t\tadjusted_index(concepts::UnsignedIntegral auto index,\n\t\t\t\t\t\t   concepts::UnsignedIntegral auto start,\n\t\t\t\t\t\t   concepts::UnsignedIntegral auto capacity) const noexcept -> index_type {\n\t\t\t\tconst auto i = static_cast<index_type>(index);\n\t\t\t\tconst auto start_ = static_cast<index_type>(start);\n\t\t\t\tconst auto capacity_ = static_cast<index_type>(capacity);\n\t\t\t\treturn (start_ + i) % (capacity_);\n\t\t\t}\n\n\t\t\t[[nodiscard]] inline constexpr auto back() const noexcept -> index_type {\n\t\t\t\tconst auto indices = m_indices.load();\n\t\t\t\tconst auto capacity_ = m_capacity.load();\n\n\t\t\t\treturn adjusted_index(size(start(indices), write(indices), capacity_) - 1,\n\t\t\t\t\t\t\t\t\t  start(indices),\n\t\t\t\t\t\t\t\t\t  capacity_);\n\t\t\t}\n\n\t\t\tinline constexpr auto increment_indices() noexcept -> void {\n\t\t\t\tauto indices = m_indices.load();\n\t\t\t\tconst auto capacity_ = m_capacity.load();\n\t\t\t\tif(start(indices) == ((write(indices) + 1) % capacity_)) [[likely]] { // NOLINT\n\n\t\t\t\t\twhile(!m_indices.compare_exchange_weak(\n\t\t\t\t\t\tindices,\n\t\t\t\t\t\tmerge_indices((start(indices) + 1) % capacity_,\n\t\t\t\t\t\t\t\t\t  (write(indices) + 1) % capacity_)))\n\t\t\t\t\t{ }\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\twhile(!(m_indices.compare_exchange_weak(\n\t\t\t\t\t\tindices,\n\t\t\t\t\t\tmerge_indices(start(indices), (write(indices) + 1) % capacity_))))\n\t\t\t\t\t{ }\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tinline constexpr auto increment_start() noexcept -> void {\n\t\t\t\tauto indices = m_indices.load();\n\t\t\t\tconst auto capacity_ = m_capacity.load();\n\t\t\t\tif(start(indices) != (write(indices))) {\n\t\t\t\t\twhile(!(m_indices.compare_exchange_weak(\n\t\t\t\t\t\tindices,\n\t\t\t\t\t\tmerge_indices((start(indices) + 1) % capacity_, write(indices)))))\n\t\t\t\t\t{ }\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tinline constexpr auto decrement_write() noexcept -> void {\n\t\t\t\tauto indices = m_indices.load();\n\t\t\t\tif(write(indices) == 0U) {\n\t\t\t\t\tconst auto capacity_ = m_capacity.load();\n\t\t\t\t\twhile(!m_indices.compare_exchange_weak(\n\t\t\t\t\t\tindices,\n\t\t\t\t\t\tmerge_indices(start(indices), capacity_ - 1))) {\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\twhile(!m_indices.compare_exchange_weak(\n\t\t\t\t\t\tindices,\n\t\t\t\t\t\tmerge_indices(start(indices), write(indices) - 1))) {\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tinline constexpr auto\n\t\t\tdecrement_write_n(concepts::UnsignedIntegral auto n) noexcept -> void {\n\t\t\t\tauto indices = m_indices.load();\n\t\t\t\tconst auto capacity_ = m_capacity.load();\n\n\t\t\t\tauto amount_to_decrement = static_cast<index_type>(n);\n\t\t\t\tif(amount_to_decrement > write(indices)) {\n\t\t\t\t\tamount_to_decrement -= write(indices);\n\t\t\t\t\twhile(!m_indices.compare_exchange_weak(\n\t\t\t\t\t\tindices,\n\t\t\t\t\t\tmerge_indices(start(indices), (capacity_ - 1) - amount_to_decrement)))\n\t\t\t\t\t{ }\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\twhile(!m_indices.compare_exchange_weak(\n\t\t\t\t\t\tindices,\n\t\t\t\t\t\tmerge_indices(start(indices), write(indices) - amount_to_decrement)))\n\t\t\t\t\t{ }\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tinline constexpr auto\n\t\t\tset_write(concepts::UnsignedIntegral auto index) noexcept -> void {\n\t\t\t\tconst auto index_ = static_cast<index_type>(index);\n\t\t\t\tauto indices = m_indices.load();\n\t\t\t\twhile(!m_indices.compare_exchange_weak(indices,\n\t\t\t\t\t\t\t\t\t\t\t\t\t   merge_indices(start(indices), index_))) {\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconstexpr auto operator=(const State& state) noexcept -> State& {\n\t\t\t\tif(&state == this) {\n\t\t\t\t\treturn *this;\n\t\t\t\t}\n\t\t\t\tm_indices.store(state.m_indices);\n\t\t\t\tm_capacity.store(state.m_capacity);\n\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\tconstexpr auto operator=(State&& state) noexcept -> State& {\n\t\t\t\tm_indices.store(state.m_indices);\n\t\t\t\tm_capacity.store(state.m_capacity);\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t  private:\n\t\t\tstatic constexpr u32 START_SHIFT = 32_u32;\n\t\t\tstatic constexpr merged_type MASK = 0x0000'0000'FFFF'FFFF_u32;\n\t\t\tatomic_merged_type m_indices = 0_usize;\n\t\t\tatomic_index_type m_capacity = DEFAULT_CAPACITY_INTERNAL;\n\n\t\t\t[[nodiscard]] inline static constexpr auto\n\t\t\tmerge_indices(index_type start, index_type write) noexcept -> merged_type {\n\t\t\t\treturn (static_cast<merged_type>(start) << START_SHIFT) | write;\n\t\t\t}\n\n\t\t\t[[nodiscard]] inline static constexpr auto\n\t\t\tstart(merged_type indices) noexcept -> index_type {\n\t\t\t\treturn static_cast<index_type>((indices >> START_SHIFT) & MASK);\n\t\t\t}\n\n\t\t\t[[nodiscard]] inline static constexpr auto\n\t\t\twrite(merged_type indices) noexcept -> index_type {\n\t\t\t\treturn static_cast<index_type>(indices & MASK);\n\t\t\t}\n\t\t};\n\n\t\tAllocator<Element> m_allocator = Allocator<Element>();\n\t\tunique_pointer m_buffer = allocate_unique<Element[]>(m_allocator, // NOLINT\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t DEFAULT_CAPACITY_INTERNAL,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t m_allocator);\n\t\tState m_state = State();\n\n\t\t/// @brief Inserts the given element at the position indicated\n\t\t/// by the `external_index`\n\t\t/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`\n\t\t///\n\t\t/// @param external_index - The user-facing index into the `RingBuffer` to insert the\n\t\t/// element at\n\t\t/// @param elem - The element to store in the `RingBuffer`\n\t\tinline constexpr auto\n\t\tinsert_internal(index_type external_index, const T& elem) noexcept -> void {\n\t\t\tconst auto [start, write] = m_state.indices();\n\t\t\tconst auto capacity_ = m_state.capacity();\n\t\t\tauto index = m_state.adjusted_index(external_index, start, capacity_);\n\n\t\t\tif(index == write) {\n\t\t\t\templace_back(elem);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconst auto size_ = m_state.size(start, write, capacity_);\n\t\t\t\tauto num_to_move = size_ - external_index;\n\t\t\t\tauto j = num_to_move - 1;\n\n\t\t\t\tif(size_ == capacity_ - 1) [[likely]] { // NOLINT\n\t\t\t\t\tnum_to_move--;\n\t\t\t\t\tj--;\n\t\t\t\t\tindex++;\n\t\t\t\t}\n\n\t\t\t\tfor(auto i = 0_u32; i < num_to_move; ++i, --j) {\n\t\t\t\t\tm_buffer[m_state.adjusted_index(size_ - i, start, capacity_)] = std::move(\n\t\t\t\t\t\tm_buffer[m_state.adjusted_index(external_index + j, start, capacity_)]);\n\t\t\t\t}\n\n\t\t\t\tm_buffer[index] = Element(m_allocator, elem);\n\t\t\t\tm_state.increment_indices();\n\t\t\t}\n\t\t}\n\n\t\t/// @brief Inserts the given element at the position indicated\n\t\t/// by the `external_index`\n\t\t/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`\n\t\t///\n\t\t/// @param external_index - The user-facing index into the `RingBuffer` to insert the\n\t\t/// element at\n\t\t/// @param elem - The element to store in the `RingBuffer`\n\t\tinline constexpr auto\n\t\tinsert_internal(index_type external_index, T&& elem) noexcept -> void {\n\t\t\tconst auto [start, write] = m_state.indices();\n\t\t\tconst auto capacity_ = m_state.capacity();\n\t\t\tauto index = m_state.adjusted_index(external_index, start, capacity_);\n\n\t\t\tif(index == write) {\n\t\t\t\templace_back(std::forward<T>(elem));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconst auto size_ = m_state.size(start, write, capacity_);\n\t\t\t\tauto num_to_move = size_ - external_index;\n\t\t\t\tauto j = num_to_move - 1;\n\n\t\t\t\tif(size_ == capacity_ - 1) [[likely]] { // NOLINT\n\t\t\t\t\tnum_to_move--;\n\t\t\t\t\tj--;\n\t\t\t\t\tindex++;\n\t\t\t\t}\n\n\t\t\t\tfor(auto i = 0_u32; i < num_to_move; ++i, --j) {\n\t\t\t\t\tm_buffer[m_state.adjusted_index(size_ - i, start, capacity_)] = std::move(\n\t\t\t\t\t\tm_buffer[m_state.adjusted_index(external_index + j, start, capacity_)]);\n\t\t\t\t}\n\n\t\t\t\tm_buffer[index] = Element(m_allocator, std::forward<T>(elem));\n\t\t\t\tm_state.increment_indices();\n\t\t\t}\n\t\t}\n\n\t\t/// @brief Constructs the given element at the insertion position indicated\n\t\t/// by the `external_index`\n\t\t/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`\n\t\t///\n\t\t/// @param external_index - The user-facing index into the `RingBuffer` to insert the\n\t\t/// element at\n\t\t/// @param args - The arguments to the constructor for\n\t\t/// the element to store in the `RingBuffer`\n\t\ttemplate<typename... Args>\n\t\trequires concepts::ConstructibleFrom<T, Args...>\n\t\tinline constexpr auto\n\t\tinsert_emplace_internal(index_type external_index, Args&&... args) noexcept -> Element {\n\t\t\tconst auto [start, write] = m_state.indices();\n\t\t\tconst auto capacity_ = m_state.capacity();\n\t\t\tauto index = m_state.adjusted_index(external_index, start, capacity_);\n\n\t\t\tif(index == write) {\n\t\t\t\treturn emplace_back(std::forward<Args>(args)...);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconst auto size_ = m_state.size(start, write, capacity_);\n\t\t\t\tauto num_to_move = size_ - external_index;\n\t\t\t\tauto j = num_to_move - 1;\n\n\t\t\t\tif(size_ == capacity_ - 1) [[likely]] { // NOLINT\n\t\t\t\t\tnum_to_move--;\n\t\t\t\t\tj--;\n\t\t\t\t\tindex++;\n\t\t\t\t}\n\n\t\t\t\tfor(auto i = 0_u32; i < num_to_move; ++i, --j) {\n\t\t\t\t\tm_buffer[m_state.adjusted_index(size_ - i, start, capacity_)] = std::move(\n\t\t\t\t\t\tm_buffer[m_state.adjusted_index(external_index + j, start, capacity_)]);\n\t\t\t\t}\n\n\t\t\t\tallocator_traits::template construct<Element>(\n\t\t\t\t\tm_allocator,\n\t\t\t\t\t&m_buffer[index],\n\t\t\t\t\tstd::allocate_shared<T, Allocator<Element>>(m_allocator,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstd::forward<Args>(args)...));\n\t\t\t\tm_state.increment_indices();\n\t\t\t\treturn m_buffer[index];\n\t\t\t}\n\t\t}\n\n\t\t/// @brief Erases the element at the given index, returning an `Iterator` to the element\n\t\t/// after the removed one\n\t\t///\n\t\t/// @param external_index - The index to the element to remove. This should be a\n\t\t/// `RingBuffer` index: IE, not an internal one into the `T` array\n\t\t///\n\t\t/// @return `Iterator` pointing to the element after the one removed\n\t\t[[nodiscard]] inline constexpr auto\n\t\terase_internal(index_type external_index) noexcept -> Iterator {\n\t\t\tconst auto [start, write] = m_state.indices();\n\t\t\tconst auto capacity_ = m_state.capacity();\n\t\t\tconst auto index = m_state.adjusted_index(external_index, start, capacity_);\n\n\t\t\tif(index == write) [[unlikely]] { // NOLINT\n\t\t\t\treturn end();\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// const auto size_ = size(start, write);\n\t\t\t\tconst auto size_ = m_state.size(start, write, capacity_);\n\t\t\t\tconst auto num_to_move = (size_ - 1) - external_index;\n\t\t\t\tconst auto pos_to_move = external_index + 1;\n\t\t\t\tconst auto pos_to_replace = external_index;\n\t\t\t\tfor(auto i = 0_u32; i < num_to_move; ++i) {\n\t\t\t\t\tm_buffer[m_state.adjusted_index(pos_to_replace + i, start, capacity_)]\n\t\t\t\t\t\t= m_buffer[m_state.adjusted_index(pos_to_move + i, start, capacity_)];\n\t\t\t\t}\n\t\t\t\tm_state.decrement_write();\n\n\t\t\t\treturn begin() + external_index;\n\t\t\t}\n\t\t}\n\n\t\t/// @brief Erases the range of elements in [`first`, `last`)\n\t\t/// Returns an `Iterator` to the element after the last one erased\n\t\t///\n\t\t/// @param first - The first index in the range to erase. This should be a `RingBuffer`\n\t\t/// index: IE, not an internal one into the `T` array\n\t\t/// @param last - The last index` in the range to erase. This should be a `RingBuffer`\n\t\t/// index: IE, not an internal one into the `T` array\n\t\t///\n\t\t/// @return `Iterator` pointing to the element after the last one erased\n\t\t[[nodiscard]] inline constexpr auto\n\t\terase_internal(index_type first, index_type last) noexcept -> Iterator { // NOLINT\n\t\t\tconst auto [start, write] = m_state.indices();\n\t\t\tconst auto capacity_ = m_state.capacity();\n\t\t\tconst auto size_ = m_state.size(start, write, capacity_);\n\t\t\tconst auto last_internal = m_state.adjusted_index(last, start, capacity_);\n\t\t\tconst auto num_to_remove = (last - first);\n\n\t\t\tif(last_internal == write) {\n\n\t\t\t\tif(write > start) {\n\t\t\t\t\tm_state.decrement_write_n(num_to_remove);\n\t\t\t\t}\n\t\t\t\telse if(write < start) {\n\t\t\t\t\tauto num_after_start_index\n\t\t\t\t\t\t= (write > num_to_remove) ? write - num_to_remove : 0_u32;\n\t\t\t\t\tauto num_before_start_index = num_to_remove - num_after_start_index;\n\t\t\t\t\tif(num_after_start_index > 0) {\n\t\t\t\t\t\tnum_after_start_index--;\n\t\t\t\t\t\tm_state.set_write(m_state.loop_index() - num_after_start_index);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tm_state.decrement_write_n(num_before_start_index);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn end();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconst auto num_to_move = size_ - last;\n\t\t\t\tconst auto pos_to_move = last;\n\t\t\t\tconst auto pos_to_replace = first;\n\t\t\t\tfor(auto i = 0_u32; i < num_to_move; ++i) {\n\t\t\t\t\tm_buffer[m_state.adjusted_index(pos_to_replace + i, start, capacity_)]\n\t\t\t\t\t\t= m_buffer[m_state.adjusted_index(pos_to_move + i, start, capacity_)];\n\t\t\t\t}\n\t\t\t\tm_state.decrement_write_n(num_to_remove);\n\n\t\t\t\treturn begin() + first;\n\t\t\t}\n\t\t}\n\t};\n\tIGNORE_PADDING_STOP\n\n} // namespace hyperion\n", "meta": {"hexsha": "8efba2d4a150fcb026a74b07ae958184857a9988", "size": 92308, "ext": "h", "lang": "C", "max_stars_repo_path": "include/Hyperion/RingBuffer.h", "max_stars_repo_name": "braxtons12/Hyperion-Utils", "max_stars_repo_head_hexsha": "3873a116e2ea76fc74c9c056925f3740eee6dcd8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/Hyperion/RingBuffer.h", "max_issues_repo_name": "braxtons12/Hyperion-Utils", "max_issues_repo_head_hexsha": "3873a116e2ea76fc74c9c056925f3740eee6dcd8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/Hyperion/RingBuffer.h", "max_forks_repo_name": "braxtons12/Hyperion-Utils", "max_forks_repo_head_hexsha": "3873a116e2ea76fc74c9c056925f3740eee6dcd8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.6401544402, "max_line_length": 100, "alphanum_fraction": 0.6801577328, "num_tokens": 23261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18010667288817792, "lm_q2_score": 0.03461884244969336, "lm_q1q2_score": 0.00623508453285429}}
{"text": "// Copyright (c) 2015-2016, Massachusetts Institute of Technology\n// Copyright (c) 2016-2017 Sandia Corporation\n// Copyright (c) 2017 NTESS, LLC.\n\n// This file is part of the Compressed Continuous Computation (C3) Library\n// Author: Alex A. Gorodetsky \n// Contact: alex@alexgorodetsky.com\n\n// All rights reserved.\n\n// Redistribution and use in source and binary forms, with or without modification, \n// are permitted provided that the following conditions are met:\n\n// 1. Redistributions of source code must retain the above copyright notice, \n//    this list of conditions and the following disclaimer.\n\n// 2. Redistributions in binary form must reproduce the above copyright notice, \n//    this list of conditions and the following disclaimer in the documentation \n//    and/or other materials provided with the distribution.\n\n// 3. Neither the name of the copyright holder nor the names of its contributors \n//    may be used to endorse or promote products derived from this software \n//    without specific prior written permission.\n\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" \n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE \n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE \n// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE \n// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL \n// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR \n// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER \n// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, \n// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n//Code\n\n\n#ifndef LINALG_H\n#define LINALG_H\n\n#ifdef __APPLE__\n    #include <Accelerate/Accelerate.h>\n    /* #include \"/System/Library/Frameworks/Accelerate.framework/Versions/Current/Frameworks/vecLib.framework/Headers/clapack.h\" */\n\n    #define dgetri_(X, Y, Z, A , B, C, D ) \\\n            ( dgetri_( (__CLPK_integer *) X, Y, (__CLPK_integer *) Z, (__CLPK_integer *) A, \\\n                        B, (__CLPK_integer *)C , (__CLPK_integer *) D) )\n    #define dgetrf_(X, Y, Z, A ,B, C ) \\\n            ( dgetrf_( (__CLPK_integer *) X,(__CLPK_integer *) Y, Z, (__CLPK_integer *) A, \\\n                       (__CLPK_integer *) B, (__CLPK_integer *)C ))\n    #define dorgqr_(X,Y,Z,A,B,C,D,E,F) \\\n            ( dorgqr_( (__CLPK_integer *) X, (__CLPK_integer *) Y, (__CLPK_integer *) Z, A, \\\n                       (__CLPK_integer *) B, C , D, (__CLPK_integer *) E, (__CLPK_integer *)F) )\n    #define dgeqrf_(X, Y, Z, A , B, C, D, E ) \\\n            ( dgeqrf_( (__CLPK_integer *) X,  (__CLPK_integer *)Y, Z, (__CLPK_integer *) A, \\\n                        B, C, (__CLPK_integer *) D, (__CLPK_integer *) E) )\n\n    #define dorgrq_(X,Y,Z,A,B,C,D,E,F) \\\n            ( dorgrq_( (__CLPK_integer *) X, (__CLPK_integer *) Y, (__CLPK_integer *) Z, A, \\\n                       (__CLPK_integer *) B, C , D, (__CLPK_integer *) E, (__CLPK_integer *)F) )\n    #define dgerqf_(X, Y, Z, A , B, C, D, E ) \\\n            ( dgerqf_( (__CLPK_integer *) X,  (__CLPK_integer *)Y, Z, (__CLPK_integer *) A, \\\n                        B, C, (__CLPK_integer *) D, (__CLPK_integer *) E) )\n\n    #define dgesdd_(X,Y,Z,A,B,C,D,E,F,G,H,I,J,K) \\\n            ( dgesdd_(X, (__CLPK_integer *)Y, (__CLPK_integer *)Z, A, (__CLPK_integer *) B,\\\n                C,D,(__CLPK_integer *) E, F, (__CLPK_integer *) G, H, (__CLPK_integer *) I,\\\n                (__CLPK_integer *) J, (__CLPK_integer *) K ) )\n\n    #define dgebal_(X, Y, Z, A , B, C, D, E ) \\\n            ( dgebal_( X,  (__CLPK_integer *)Y, Z, (__CLPK_integer *) A, \\\n                   (__CLPK_integer *) B, (__CLPK_integer *)C, D, (__CLPK_integer *) E) )\n\n    #define dpotrf_(X,Y,Z,A,B) \\\n            ( dpotrf_(X, (__CLPK_integer *)Y, Z, (__CLPK_integer *) A, (__CLPK_integer *) B ))\n\n    #define dpotri_(X,Y,Z,A,B) \\\n            ( dpotri_(X, (__CLPK_integer *)Y, Z, (__CLPK_integer *) A, (__CLPK_integer *) B ))\n\n    #define dtrtri_(X,Y,Z,A,B,C) \\\n            ( dtrtri_(X,Y, (__CLPK_integer *)Z, A, (__CLPK_integer *) B, (__CLPK_integer *) C ))\n\n    #define dgesv_(X,Y,Z,A,B,C,D,E) \\\n            ( dgesv_((__CLPK_integer *)X, (__CLPK_integer *)Y, Z, (__CLPK_integer *) A, (__CLPK_integer *) B, \\\n                C, (__CLPK_integer *) D, (__CLPK_integer *) E))\n\n    #define dhseqr_(X, Y, Z, A , B, C, D, E,F,G,H,I,J,K ) \\\n            ( dhseqr_( X, Y, (__CLPK_integer *)Z, (__CLPK_integer *)A, \\\n                   (__CLPK_integer *) B, C, (__CLPK_integer *)D, E, F, G, (__CLPK_integer *) H, \\\n                   I, (__CLPK_integer *) J, (__CLPK_integer *)K ) )\n\n    #define dsyev_(A,B,C,D,E,F,G,H,J) \\\n        ( dsyev_(A,B,(__CLPK_integer *) C,D,(__CLPK_integer *) E,F, \\\n            G, (__CLPK_integer *) H, (__CLPK_integer *) J) )\n\n    #define dgeev_(X, Y, Z, A , B, C, D, E,F,G,H,I,J,K ) \\\n            ( dgeev_( X, Y, (__CLPK_integer *)Z, A, \\\n                   (__CLPK_integer *) B, C, D, E, (__CLPK_integer *) F, G, (__CLPK_integer *) H, \\\n                   I, (__CLPK_integer *) J, (__CLPK_integer *)K ) )\n\n    #define dstegr_(X,Y,Z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q) \\\n            ( dstegr_(X,Y,(__CLPK_integer *)Z,A,B,C,D,\\\n                   (__CLPK_integer *)E,(__CLPK_integer *)F,G,(__CLPK_integer *)H, \\\n                   I,J,(__CLPK_integer *)K,(__CLPK_integer *)L,M,(__CLPK_integer *)N, \\\n                   (__CLPK_integer *)O,(__CLPK_integer *)P,(__CLPK_integer *)Q))\n\n    #define dgelsd_(X,Y,Z,A,B,C,D,E,F,G,H,I,J,K)                         \\\n            ( dgelsd_( (__CLPK_integer *)X, (__CLPK_integer *)Y, (__CLPK_integer *)Z, \\\n                       (__CLPK_doublereal *)A, (__CLPK_integer *)B, (__CLPK_doublereal *)C,  \\\n                       (__CLPK_integer *)D, (__CLPK_doublereal *) E, \\\n\t                   (__CLPK_doublereal *)F, (__CLPK_integer *)G, (__CLPK_doublereal *)H, \\\n                       (__CLPK_integer *)I, (__CLPK_integer *)J, (__CLPK_integer *)K)) \n#else\n    /* #include <gsl/gsl_cblas.h> */\n    #include <cblas.h>\n\nvoid dgetri_(int * X, double *Y, int * Z, int * A, double *B, int *C , int * D);\nvoid dgetrf_(int * X,int * Y, double*Z, int * A, int * B, int *C );\nvoid dorgqr_(int * X, int * Y, int * Z, double *A,int * B, double *C , double *D, int * E, int *F);\nvoid dgeqrf_(int *X, int *Y, double *Z, int * A, double * B, double * C, int * D, int * E);\nvoid dgeev_(char * X, char *Y, int * Z, double *A, int * B, double * C, double *D, double *E,\n            int * F, double *G, int * H, double *, int *, int *K);\nvoid dgebal_(char *X,  int *Y, double *Z, int * A, int * B, int *C, double *D, int * E);\nvoid dhseqr_(char *X, char *Y, int *Z, int *A,int * B, double *C, int *D,\n             double *E, double *F, double *G, int * H, double *, int *, int *K );\nvoid dorgrq_(int * X, int * Y, int * Z, double *A,int * B, double *C , double *D, int * E, int *F);\nvoid dgerqf_(int * X,  int *Y, double *Z, int * A, double *B, double *C, int * D, int * E);\nvoid dgesdd_(char *X, int * Y, int *Z, double *A, int * B,double * C,double * D,\n             int * E,double * F, int * G, double *H, int *, int *, int * K );\nvoid dstev_(char *X,  int *Y, double *Z, double *A, double *B, int *C, double *D, int * E);\nvoid dsyev_(char *A,char *B,int * C,double *D,int * E,double *F, double *G, int* H, int * J);\nvoid dpotrf_(char *X, int*Y, double *Z, int * A, int * B );\nvoid dpotri_(char *X, int*Y, double *Z, int * A, int* B);\nvoid dtrtri_(char *X,char*Y, int *Z, double *A, int * B, int * C);\nvoid dgesv_(int *X, int *Y, double*Z, int * A, int * B,double*C, int * D, int * E);\nvoid dgelsd_(int *X, int *Y, int *Z, double *A, int *B, double *C, \n             int *D, double * E, double *F, int *G, double *H, int *,int *, int *K);\n\n#endif\n\n#include \"matrix_util.h\"\n\nvoid c3linalg_multiple_vec_mat(size_t, size_t, size_t, const double *, size_t,\n                               const double *, size_t, double *,size_t);\nvoid c3linalg_multiple_mat_vec(size_t, size_t, size_t, const double *, size_t,\n                               const double *, size_t, double *,size_t);\nint qr(size_t, size_t, double *, size_t);\nvoid rq_with_rmult(size_t, size_t, double *, size_t, size_t, size_t, double *, size_t);\nvoid svd(size_t, size_t, size_t, double *, double *, double *, double *);\nsize_t truncated_svd(size_t, size_t, size_t, double *, double **, double **, double **, double);\nsize_t pinv(size_t, size_t, size_t, double *, double *, double);\n\ndouble norm2(double *, int);\ndouble norm2diff(double *, double *, int);\ndouble mean(double *, size_t);\ndouble mean_size_t(size_t *, size_t);\n\nstruct mat * kron(const struct mat *, const struct mat *);\nvoid kron_col(int, int, double *, int, int, int, double *, int, double *, int);\nvoid vec_kron(size_t, size_t, double *, size_t, size_t, size_t, \n        double *, size_t, double *, double, double *);\nvoid vec_kronl(size_t, size_t, double *, size_t, size_t, size_t, \n        double *, size_t, long double *, double, long double *);\n\n// decompositions\nstruct fiber_list{\n    size_t index;\n    double * vals;\n    struct fiber_list * next;\n};\nstruct fiber_info{\n    size_t nfibers;\n    struct fiber_list * head;\n};\nvoid AddFiber(struct fiber_list **, size_t, double *, size_t);\nint IndexExists(struct fiber_list *, size_t);\ndouble * getIndex(struct fiber_list *, size_t);\nvoid DeleteFiberList(struct fiber_list **);\n\nstruct sk_decomp {\n    size_t n;\n    size_t m;\n    size_t rank;\n    size_t * rows_kept;\n    size_t * cols_kept;\n    size_t cross_rank;\n    double * cross_inv;\n    struct fiber_info * row_vals;\n    struct fiber_info * col_vals;\n    int success;\n};\n\nvoid init_skf(struct sk_decomp **, size_t, size_t, size_t);\nvoid sk_decomp_to_full(struct sk_decomp *, double *);\nvoid free_skf(struct sk_decomp **);\n\n/* int comp_pivots(const double *, int, int, int *); */\nint maxvol_rhs(const double *, size_t, size_t, size_t *, double *); //\nint skeleton(double *, size_t, size_t, size_t, size_t *, size_t *, double);\nint skeleton_func(double (*A)(int,int, int, void*), void *, size_t, \n                size_t, size_t, size_t *, size_t *, double);\nint\nskeleton_func2(int (*Ap)(double *, double, size_t, size_t, double *,\n                void *),\n                   void *, struct sk_decomp **,  double *, double *, \n                   double);\nvoid linear_ls(size_t, size_t, double *, double *, double *);\n#endif\n", "meta": {"hexsha": "d5ad0581e6007f648dd0837c56e6ad60f97f8ae9", "size": 10527, "ext": "h", "lang": "C", "max_stars_repo_path": "c3/lib_linalg/linalg.h", "max_stars_repo_name": "goroda/Compressed-Continuous-Computation", "max_stars_repo_head_hexsha": "ecfa401306457b9476c0252dc9cc086ec3fdacfb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 45.0, "max_stars_repo_stars_event_min_datetime": "2017-03-01T18:53:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T21:08:03.000Z", "max_issues_repo_path": "c3/lib_linalg/linalg.h", "max_issues_repo_name": "goroda/Compressed-Continuous-Computation", "max_issues_repo_head_hexsha": "ecfa401306457b9476c0252dc9cc086ec3fdacfb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2015-12-18T15:50:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-22T23:49:15.000Z", "max_forks_repo_path": "c3/lib_linalg/linalg.h", "max_forks_repo_name": "goroda/Compressed-Continuous-Computation", "max_forks_repo_head_hexsha": "ecfa401306457b9476c0252dc9cc086ec3fdacfb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-09-18T19:46:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-24T01:58:02.000Z", "avg_line_length": 50.1285714286, "max_line_length": 131, "alphanum_fraction": 0.6057756246, "num_tokens": 3189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2628418258225589, "lm_q2_score": 0.0236894701793002, "lm_q1q2_score": 0.006226583594696326}}
{"text": "#pragma once\n\n#include <gsl/gsl>\n#include <fmt/format.h>\n\n#include \"temple_enums.h\"\n\n// Define objHndl as a struct that contains just the handle value\n#pragma pack(push, 1)\nstruct objHndl {\n\tuint64_t handle;\n\n\texplicit operator bool() const {\n\t\treturn !!handle;\n\t}\n\n\tobjHndl& operator=(uint64_t handle) {\n\t\tthis->handle = handle;\n\t\treturn *this;\n\t}\n\n\tuint32_t GetHandleLower() const {\n\t\treturn (uint32_t)(handle & 0xffffffff);\n\t}\n\n\tuint32_t GetHandleUpper() const {\n\t\treturn (uint32_t)((handle >> 32) & 0xffffffff);\n\t}\n\n\tstatic objHndl FromUpperAndLower(uint32_t upper, uint32_t lower) {\n\t\treturn{\n\t\t\t(((uint64_t) upper) << 32)\n\t\t\t| (((uint64_t)lower) & 0xFFFFFFFF)\n\t\t};\n\t}\n\n\tstatic const objHndl null;\n\n};\n#pragma pack(pop)\n\n/**\n * Compares two object handles for equality. They are equal if their\n * handle value is equal.\n */\ninline bool operator ==(const objHndl &a, const objHndl &b) {\n\treturn a.handle == b.handle;\n}\ninline bool operator !=(const objHndl &a, const objHndl &b) {\n\treturn a.handle != b.handle;\n}\ninline bool operator <(const objHndl &a, const objHndl &b) {\n\treturn a.handle < b.handle;\n}\ninline bool operator >(const objHndl &a, const objHndl &b) {\n\treturn a.handle > b.handle;\n}\n\nvoid format_arg(fmt::BasicFormatter<char> &f, const char *&format_str, const objHndl &s);\n\nnamespace std {\n\ttemplate <> struct hash<objHndl> {\n\t\tsize_t operator()(const objHndl &x) const {\n\t\t\treturn std::hash<uint64_t>()(x.handle);\n\t\t}\n\t};\n}\n\ntypedef uint32_t _fieldIdx;\ntypedef uint32_t _fieldSubIdx;\ntypedef uint32_t _mapNum;\ntypedef uint32_t _key;\n\n#pragma pack(push, 8)\n\nenum class ObjectIdKind : uint16_t {\n\tNull = 0,\n\tPrototype = 1,\n\tPermanent = 2,\n\tPositional = 3,\n\tHandle = 0xFFFE,\n\tBlocked = 0xFFFF\n};\n\nunion ObjectIdBody {\n\tGUID guid;\n\tuint32_t protoId;\n\tobjHndl handle;\n\tstruct {\n\t\tint x;\n\t\tint y;\n\t\tint tempId;\n\t\tint mapId;\n\t} pos;\n};\n\nstruct ObjectId {\n\tObjectIdKind subtype = ObjectIdKind::Null;\n\tint unk = 0;\n\tObjectIdBody body;\n\n\tbool IsNull() const {\n\t\treturn subtype == ObjectIdKind::Null;\n\t}\n\n\tbool IsPermanent() const {\n\t\treturn subtype == ObjectIdKind::Permanent;\n\t}\n\n\tbool IsPrototype() const {\n\t\treturn subtype == ObjectIdKind::Prototype;\n\t}\n\t\n\tbool IsPositional() const {\n\t\treturn subtype == ObjectIdKind::Positional;\n\t}\n\n\tbool IsHandle() const {\n\t\treturn subtype == ObjectIdKind::Handle;\n\t}\n\t\n\tbool IsBlocked() const {\n\t\treturn subtype == ObjectIdKind::Blocked;\n\t}\n\n\t// Can this object id be persisted and later restored to a handle?\n\tbool IsPersistable() const {\n\t\treturn IsNull() || IsPermanent() || IsPrototype() || IsPositional();\n\t}\n\n\tint GetPrototypeId() const {\n\t\tExpects(IsPrototype());\n\t\treturn body.protoId;\n\t}\n\n\tobjHndl GetHandle() const {\n\t\tExpects(IsHandle());\n\t\treturn body.handle;\n\t}\n\n\toperator bool() const {\n\t\treturn !IsNull();\n\t}\n\n\tbool operator ==(const ObjectId &other) const;\n\n\tstd::string ToString() const;\n\n\t// Randomly generates a GUID and returns an object id that contains it\n\tstatic ObjectId CreatePermanent();\n\n\t// Creates a positional object id\n\tstatic ObjectId CreatePositional(int mapId, int tileX, int tileY, int tempId);\n\n\t// Creates a prototype object id\n\tstatic ObjectId CreatePrototype(uint16_t prototypeId);\n\n\t// Creates a null object id\n\tstatic ObjectId CreateNull() {\n\t\tObjectId result;\n\t\tresult.subtype = ObjectIdKind::Null;\n\t\treturn result;\n\t}\n\n\tstatic ObjectId CreateHandle(objHndl handle);\n\n};\n#pragma pack(pop)\n\nconst int testSizeofObjectId = sizeof(ObjectId); // should be 24", "meta": {"hexsha": "024ac1f5b999f6376c5beb32041ce89529c05423", "size": 3447, "ext": "h", "lang": "C", "max_stars_repo_path": "TemplePlus/obj_structs.h", "max_stars_repo_name": "edoipi/TemplePlus", "max_stars_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 69.0, "max_stars_repo_stars_event_min_datetime": "2015-05-05T14:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T06:13:04.000Z", "max_issues_repo_path": "TemplePlus/obj_structs.h", "max_issues_repo_name": "edoipi/TemplePlus", "max_issues_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 457.0, "max_issues_repo_issues_event_min_datetime": "2015-05-01T22:07:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T02:19:10.000Z", "max_forks_repo_path": "TemplePlus/obj_structs.h", "max_forks_repo_name": "edoipi/TemplePlus", "max_forks_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2016-02-04T21:19:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T23:14:51.000Z", "avg_line_length": 20.2764705882, "max_line_length": 89, "alphanum_fraction": 0.7003191181, "num_tokens": 928, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25091277568224823, "lm_q2_score": 0.02479815776316973, "lm_q1q2_score": 0.0062221745961632095}}
{"text": "/*\nMPCOTool:\nThe Multi-Purposes Calibration and Optimization Tool. A software to perform\ncalibrations or optimizations of empirical parameters.\n\nAUTHORS: Javier Burguete and Borja Latorre.\n\nCopyright 2012-2019, AUTHORS.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n    1. Redistributions of source code must retain the above copyright notice,\n        this list of conditions and the following disclaimer.\n\n    2. Redistributions in binary form must reproduce the above copyright notice,\n        this list of conditions and the following disclaimer in the\n        documentation and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY AUTHORS ``AS IS'' AND ANY EXPRESS OR IMPLIED\nWARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT\nSHALL AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\nBUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING\nIN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY\nOF SUCH DAMAGE.\n*/\n\n/**\n * \\file optimize.c\n * \\brief Source file to define the optimization functions.\n * \\authors Javier Burguete and Borja Latorre.\n * \\copyright Copyright 2012-2019, all rights reserved.\n */\n#define _GNU_SOURCE\n#include \"config.h\"\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <sys/param.h>\n#include <gsl/gsl_rng.h>\n#include <libxml/parser.h>\n#include <libintl.h>\n#include <glib.h>\n#include <glib/gstdio.h>\n#include <json-glib/json-glib.h>\n#ifdef G_OS_WIN32\n#include <windows.h>\n#elif !defined(__BSD_VISIBLE) && !defined(NetBSD)\n#include <alloca.h>\n#endif\n#if HAVE_MPI\n#include <mpi.h>\n#endif\n#include \"genetic/genetic.h\"\n#include \"utils.h\"\n#include \"experiment.h\"\n#include \"variable.h\"\n#include \"input.h\"\n#include \"optimize.h\"\n\n#define DEBUG_OPTIMIZE 0        ///< Macro to debug optimize functions.\n\n/**\n * \\def RM\n * \\brief Macro to define the shell remove command.\n */\n#ifdef G_OS_WIN32\n#define RM \"del\"\n#else\n#define RM \"rm\"\n#endif\n\nOptimize optimize[1];           ///< Optimization data.\nunsigned int nthreads_climbing;\n///< Number of threads for the hill climbing method.\n\nstatic void (*optimize_algorithm) ();\n///< Pointer to the function to perform a optimization algorithm step.\nstatic double (*optimize_estimate_climbing) (unsigned int variable,\n                                             unsigned int estimate);\n///< Pointer to the function to estimate the climbing.\nstatic double (*optimize_norm) (unsigned int simulation);\n///< Pointer to the error norm function.\n\n/**\n * Function to write the simulation input file.\n */\nstatic inline void\noptimize_input (unsigned int simulation,        ///< Simulation number.\n                char *input,    ///< Input file name.\n                GMappedFile * stencil)  ///< Template of the input file name.\n{\n  char buffer[32], value[32];\n  GRegex *regex;\n  FILE *file;\n  char *buffer2, *buffer3 = NULL, *content;\n  gsize length;\n  unsigned int i;\n\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_input: start\\n\");\n#endif\n\n  // Checking the file\n  if (!stencil)\n    goto optimize_input_end;\n\n  // Opening stencil\n  content = g_mapped_file_get_contents (stencil);\n  length = g_mapped_file_get_length (stencil);\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_input: length=%lu\\ncontent:\\n%s\", length, content);\n#endif\n  file = g_fopen (input, \"w\");\n\n  // Parsing stencil\n  for (i = 0; i < optimize->nvariables; ++i)\n    {\n#if DEBUG_OPTIMIZE\n      fprintf (stderr, \"optimize_input: variable=%u\\n\", i);\n#endif\n      snprintf (buffer, 32, \"@variable%u@\", i + 1);\n      regex = g_regex_new (buffer, (GRegexCompileFlags) 0, (GRegexMatchFlags) 0,\n                           NULL);\n      if (i == 0)\n        {\n          buffer2 = g_regex_replace_literal (regex, content, length, 0,\n                                             optimize->label[i],\n                                             (GRegexMatchFlags) 0, NULL);\n#if DEBUG_OPTIMIZE\n          fprintf (stderr, \"optimize_input: buffer2\\n%s\", buffer2);\n#endif\n        }\n      else\n        {\n          length = strlen (buffer3);\n          buffer2 = g_regex_replace_literal (regex, buffer3, length, 0,\n                                             optimize->label[i],\n                                             (GRegexMatchFlags) 0, NULL);\n          g_free (buffer3);\n        }\n      g_regex_unref (regex);\n      length = strlen (buffer2);\n      snprintf (buffer, 32, \"@value%u@\", i + 1);\n      regex = g_regex_new (buffer, (GRegexCompileFlags) 0, (GRegexMatchFlags) 0,\n                           NULL);\n      snprintf (value, 32, format[optimize->precision[i]],\n                optimize->value[simulation * optimize->nvariables + i]);\n\n#if DEBUG_OPTIMIZE\n      fprintf (stderr, \"optimize_input: value=%s\\n\", value);\n#endif\n      buffer3 = g_regex_replace_literal (regex, buffer2, length, 0, value,\n                                         (GRegexMatchFlags) 0, NULL);\n      g_free (buffer2);\n      g_regex_unref (regex);\n    }\n\n  // Saving input file\n  fwrite (buffer3, strlen (buffer3), sizeof (char), file);\n  g_free (buffer3);\n  fclose (file);\n\noptimize_input_end:\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_input: end\\n\");\n#endif\n  return;\n}\n\n/**\n * Function to parse input files, simulating and calculating the objective \n *   function.\n *\n * \\return Objective function value.\n */\nstatic double\noptimize_parse (unsigned int simulation,        ///< Simulation number.\n                unsigned int experiment)        ///< Experiment number.\n{\n  unsigned int i;\n  double e;\n  char buffer[512], input[MAX_NINPUTS][32], output[32], result[32], *buffer2,\n    *buffer3, *buffer4;\n  FILE *file_result;\n\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_parse: start\\n\");\n  fprintf (stderr, \"optimize_parse: simulation=%u experiment=%u\\n\",\n           simulation, experiment);\n#endif\n\n  // Opening input files\n  for (i = 0; i < optimize->ninputs; ++i)\n    {\n      snprintf (&input[i][0], 32, \"input-%u-%u-%u\", i, simulation, experiment);\n#if DEBUG_OPTIMIZE\n      fprintf (stderr, \"optimize_parse: i=%u input=%s\\n\", i, &input[i][0]);\n#endif\n      optimize_input (simulation, &input[i][0], optimize->file[i][experiment]);\n    }\n  for (; i < MAX_NINPUTS; ++i)\n    strcpy (&input[i][0], \"\");\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_parse: parsing end\\n\");\n#endif\n\n  // Performing the simulation\n  snprintf (output, 32, \"output-%u-%u\", simulation, experiment);\n  buffer2 = g_path_get_dirname (optimize->simulator);\n  buffer3 = g_path_get_basename (optimize->simulator);\n  buffer4 = g_build_filename (buffer2, buffer3, NULL);\n  snprintf (buffer, 512, \"\\\"%s\\\" %s %s %s %s %s %s %s %s %s\",\n            buffer4, input[0], input[1], input[2], input[3], input[4],\n            input[5], input[6], input[7], output);\n  g_free (buffer4);\n  g_free (buffer3);\n  g_free (buffer2);\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_parse: %s\\n\", buffer);\n#endif\n  if (system (buffer) == -1)\n    error_message = buffer;\n\n  // Checking the objective value function\n  if (optimize->evaluator)\n    {\n      snprintf (result, 32, \"result-%u-%u\", simulation, experiment);\n      buffer2 = g_path_get_dirname (optimize->evaluator);\n      buffer3 = g_path_get_basename (optimize->evaluator);\n      buffer4 = g_build_filename (buffer2, buffer3, NULL);\n      snprintf (buffer, 512, \"\\\"%s\\\" %s %s %s\",\n                buffer4, output, optimize->experiment[experiment], result);\n      g_free (buffer4);\n      g_free (buffer3);\n      g_free (buffer2);\n#if DEBUG_OPTIMIZE\n      fprintf (stderr, \"optimize_parse: %s\\n\", buffer);\n      fprintf (stderr, \"optimize_parse: result=%s\\n\", result);\n#endif\n      if (system (buffer) == -1)\n        error_message = buffer;\n      file_result = g_fopen (result, \"r\");\n      e = atof (fgets (buffer, 512, file_result));\n      fclose (file_result);\n    }\n  else\n    {\n#if DEBUG_OPTIMIZE\n      fprintf (stderr, \"optimize_parse: output=%s\\n\", output);\n#endif\n      strcpy (result, \"\");\n      file_result = g_fopen (output, \"r\");\n      e = atof (fgets (buffer, 512, file_result));\n      fclose (file_result);\n    }\n\n  // Removing files\n#if !DEBUG_OPTIMIZE\n  for (i = 0; i < optimize->ninputs; ++i)\n    {\n      if (optimize->file[i][0])\n        {\n          snprintf (buffer, 512, RM \" %s\", &input[i][0]);\n          if (system (buffer) == -1)\n            error_message = buffer;\n        }\n    }\n  snprintf (buffer, 512, RM \" %s %s\", output, result);\n  if (system (buffer) == -1)\n    error_message = buffer;\n#endif\n\n  // Processing pending events\n  if (show_pending)\n    show_pending ();\n\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_parse: end\\n\");\n#endif\n\n  // Returning the objective function\n  return e * optimize->weight[experiment];\n}\n\n/**\n * Function to calculate the Euclidian error norm.\n *\n * \\return Euclidian error norm.\n */\nstatic double\noptimize_norm_euclidian (unsigned int simulation)       ///< simulation number.\n{\n  double e, ei;\n  unsigned int i;\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_norm_euclidian: start\\n\");\n#endif\n  e = 0.;\n  for (i = 0; i < optimize->nexperiments; ++i)\n    {\n      ei = optimize_parse (simulation, i);\n      e += ei * ei;\n    }\n  e = sqrt (e);\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_norm_euclidian: error=%lg\\n\", e);\n  fprintf (stderr, \"optimize_norm_euclidian: end\\n\");\n#endif\n  return e;\n}\n\n/**\n * Function to calculate the maximum error norm.\n *\n * \\return Maximum error norm.\n */\nstatic double\noptimize_norm_maximum (unsigned int simulation) ///< simulation number.\n{\n  double e, ei;\n  unsigned int i;\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_norm_maximum: start\\n\");\n#endif\n  e = 0.;\n  for (i = 0; i < optimize->nexperiments; ++i)\n    {\n      ei = fabs (optimize_parse (simulation, i));\n      e = fmax (e, ei);\n    }\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_norm_maximum: error=%lg\\n\", e);\n  fprintf (stderr, \"optimize_norm_maximum: end\\n\");\n#endif\n  return e;\n}\n\n/**\n * Function to calculate the P error norm.\n *\n * \\return P error norm.\n */\nstatic double\noptimize_norm_p (unsigned int simulation)       ///< simulation number.\n{\n  double e, ei;\n  unsigned int i;\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_norm_p: start\\n\");\n#endif\n  e = 0.;\n  for (i = 0; i < optimize->nexperiments; ++i)\n    {\n      ei = fabs (optimize_parse (simulation, i));\n      e += pow (ei, optimize->p);\n    }\n  e = pow (e, 1. / optimize->p);\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_norm_p: error=%lg\\n\", e);\n  fprintf (stderr, \"optimize_norm_p: end\\n\");\n#endif\n  return e;\n}\n\n/**\n * Function to calculate the taxicab error norm.\n *\n * \\return Taxicab error norm.\n */\nstatic double\noptimize_norm_taxicab (unsigned int simulation) ///< simulation number.\n{\n  double e;\n  unsigned int i;\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_norm_taxicab: start\\n\");\n#endif\n  e = 0.;\n  for (i = 0; i < optimize->nexperiments; ++i)\n    e += fabs (optimize_parse (simulation, i));\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_norm_taxicab: error=%lg\\n\", e);\n  fprintf (stderr, \"optimize_norm_taxicab: end\\n\");\n#endif\n  return e;\n}\n\n/**\n * Function to print the results.\n */\nstatic void\noptimize_print ()\n{\n  unsigned int i;\n  char buffer[512];\n#if HAVE_MPI\n  if (optimize->mpi_rank)\n    return;\n#endif\n  printf (\"%s\\n\", _(\"Best result\"));\n  fprintf (optimize->file_result, \"%s\\n\", _(\"Best result\"));\n  printf (\"error = %.15le\\n\", optimize->error_old[0]);\n  fprintf (optimize->file_result, \"error = %.15le\\n\", optimize->error_old[0]);\n  for (i = 0; i < optimize->nvariables; ++i)\n    {\n      snprintf (buffer, 512, \"%s = %s\\n\",\n                optimize->label[i], format[optimize->precision[i]]);\n      printf (buffer, optimize->value_old[i]);\n      fprintf (optimize->file_result, buffer, optimize->value_old[i]);\n    }\n  fflush (optimize->file_result);\n}\n\n/**\n * Function to save in a file the variables and the error.\n */\nstatic void\noptimize_save_variables (unsigned int simulation,       ///< Simulation number.\n                         double error)  ///< Error value.\n{\n  unsigned int i;\n  char buffer[64];\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_save_variables: start\\n\");\n#endif\n  for (i = 0; i < optimize->nvariables; ++i)\n    {\n      snprintf (buffer, 64, \"%s \", format[optimize->precision[i]]);\n      fprintf (optimize->file_variables, buffer,\n               optimize->value[simulation * optimize->nvariables + i]);\n    }\n  fprintf (optimize->file_variables, \"%.14le\\n\", error);\n  fflush (optimize->file_variables);\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_save_variables: end\\n\");\n#endif\n}\n\n/**\n * Function to save the best simulations.\n */\nstatic void\noptimize_best (unsigned int simulation, ///< Simulation number.\n               double value)    ///< Objective function value.\n{\n  unsigned int i, j;\n  double e;\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_best: start\\n\");\n  fprintf (stderr, \"optimize_best: nsaveds=%u nbest=%u\\n\",\n           optimize->nsaveds, optimize->nbest);\n#endif\n  if (optimize->nsaveds < optimize->nbest\n      || value < optimize->error_best[optimize->nsaveds - 1])\n    {\n      if (optimize->nsaveds < optimize->nbest)\n        ++optimize->nsaveds;\n      optimize->error_best[optimize->nsaveds - 1] = value;\n      optimize->simulation_best[optimize->nsaveds - 1] = simulation;\n      for (i = optimize->nsaveds; --i;)\n        {\n          if (optimize->error_best[i] < optimize->error_best[i - 1])\n            {\n              j = optimize->simulation_best[i];\n              e = optimize->error_best[i];\n              optimize->simulation_best[i] = optimize->simulation_best[i - 1];\n              optimize->error_best[i] = optimize->error_best[i - 1];\n              optimize->simulation_best[i - 1] = j;\n              optimize->error_best[i - 1] = e;\n            }\n          else\n            break;\n        }\n    }\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_best: end\\n\");\n#endif\n}\n\n/**\n * Function to optimize sequentially.\n */\nstatic void\noptimize_sequential ()\n{\n  unsigned int i;\n  double e;\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_sequential: start\\n\");\n  fprintf (stderr, \"optimize_sequential: nstart=%u nend=%u\\n\",\n           optimize->nstart, optimize->nend);\n#endif\n  for (i = optimize->nstart; i < optimize->nend; ++i)\n    {\n      e = optimize_norm (i);\n      optimize_best (i, e);\n      optimize_save_variables (i, e);\n      if (e < optimize->threshold)\n        {\n          optimize->stop = 1;\n          break;\n        }\n#if DEBUG_OPTIMIZE\n      fprintf (stderr, \"optimize_sequential: i=%u e=%lg\\n\", i, e);\n#endif\n    }\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_sequential: end\\n\");\n#endif\n}\n\n/**\n * Function to optimize on a thread.\n *\n * \\return NULL.\n */\nstatic void *\noptimize_thread (ParallelData * data)   ///< Function data.\n{\n  unsigned int i, thread;\n  double e;\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_thread: start\\n\");\n#endif\n  thread = data->thread;\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_thread: thread=%u start=%u end=%u\\n\", thread,\n           optimize->thread[thread], optimize->thread[thread + 1]);\n#endif\n  for (i = optimize->thread[thread]; i < optimize->thread[thread + 1]; ++i)\n    {\n      e = optimize_norm (i);\n      g_mutex_lock (mutex);\n      optimize_best (i, e);\n      optimize_save_variables (i, e);\n      if (e < optimize->threshold)\n        optimize->stop = 1;\n      g_mutex_unlock (mutex);\n      if (optimize->stop)\n        break;\n#if DEBUG_OPTIMIZE\n      fprintf (stderr, \"optimize_thread: i=%u e=%lg\\n\", i, e);\n#endif\n    }\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_thread: end\\n\");\n#endif\n  g_thread_exit (NULL);\n  return NULL;\n}\n\n/**\n * Function to merge the 2 optimization results.\n */\nstatic inline void\noptimize_merge (unsigned int nsaveds,   ///< Number of saved results.\n                unsigned int *simulation_best,\n                ///< Array of best simulation numbers.\n                double *error_best)\n                ///< Array of best objective function values.\n{\n  unsigned int i, j, k, s[optimize->nbest];\n  double e[optimize->nbest];\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_merge: start\\n\");\n#endif\n  i = j = k = 0;\n  do\n    {\n      if (i == optimize->nsaveds)\n        {\n          s[k] = simulation_best[j];\n          e[k] = error_best[j];\n          ++j;\n          ++k;\n          if (j == nsaveds)\n            break;\n        }\n      else if (j == nsaveds)\n        {\n          s[k] = optimize->simulation_best[i];\n          e[k] = optimize->error_best[i];\n          ++i;\n          ++k;\n          if (i == optimize->nsaveds)\n            break;\n        }\n      else if (optimize->error_best[i] > error_best[j])\n        {\n          s[k] = simulation_best[j];\n          e[k] = error_best[j];\n          ++j;\n          ++k;\n        }\n      else\n        {\n          s[k] = optimize->simulation_best[i];\n          e[k] = optimize->error_best[i];\n          ++i;\n          ++k;\n        }\n    }\n  while (k < optimize->nbest);\n  optimize->nsaveds = k;\n  memcpy (optimize->simulation_best, s, k * sizeof (unsigned int));\n  memcpy (optimize->error_best, e, k * sizeof (double));\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_merge: end\\n\");\n#endif\n}\n\n/**\n * Function to synchronise the optimization results of MPI tasks.\n */\n#if HAVE_MPI\nstatic void\noptimize_synchronise ()\n{\n  unsigned int i, nsaveds, simulation_best[optimize->nbest], stop;\n  double error_best[optimize->nbest];\n  MPI_Status mpi_stat;\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_synchronise: start\\n\");\n#endif\n  if (optimize->mpi_rank == 0)\n    {\n      for (i = 1; (int) i < ntasks; ++i)\n        {\n          MPI_Recv (&nsaveds, 1, MPI_INT, i, 1, MPI_COMM_WORLD, &mpi_stat);\n          MPI_Recv (simulation_best, nsaveds, MPI_INT, i, 1,\n                    MPI_COMM_WORLD, &mpi_stat);\n          MPI_Recv (error_best, nsaveds, MPI_DOUBLE, i, 1,\n                    MPI_COMM_WORLD, &mpi_stat);\n          optimize_merge (nsaveds, simulation_best, error_best);\n          MPI_Recv (&stop, 1, MPI_UNSIGNED, i, 1, MPI_COMM_WORLD, &mpi_stat);\n          if (stop)\n            optimize->stop = 1;\n        }\n      for (i = 1; (int) i < ntasks; ++i)\n        MPI_Send (&optimize->stop, 1, MPI_UNSIGNED, i, 1, MPI_COMM_WORLD);\n    }\n  else\n    {\n      MPI_Send (&optimize->nsaveds, 1, MPI_INT, 0, 1, MPI_COMM_WORLD);\n      MPI_Send (optimize->simulation_best, optimize->nsaveds, MPI_INT, 0, 1,\n                MPI_COMM_WORLD);\n      MPI_Send (optimize->error_best, optimize->nsaveds, MPI_DOUBLE, 0, 1,\n                MPI_COMM_WORLD);\n      MPI_Send (&optimize->stop, 1, MPI_UNSIGNED, 0, 1, MPI_COMM_WORLD);\n      MPI_Recv (&stop, 1, MPI_UNSIGNED, 0, 1, MPI_COMM_WORLD, &mpi_stat);\n      if (stop)\n        optimize->stop = 1;\n    }\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_synchronise: end\\n\");\n#endif\n}\n#endif\n\n/**\n * Function to optimize with the sweep algorithm.\n */\nstatic void\noptimize_sweep ()\n{\n  unsigned int i, j, k, l;\n  double e;\n  GThread *thread[nthreads];\n  ParallelData data[nthreads];\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_sweep: start\\n\");\n#endif\n  for (i = 0; i < optimize->nsimulations; ++i)\n    {\n      k = i;\n      for (j = 0; j < optimize->nvariables; ++j)\n        {\n          l = k % optimize->nsweeps[j];\n          k /= optimize->nsweeps[j];\n          e = optimize->rangemin[j];\n          if (optimize->nsweeps[j] > 1)\n            e += l * (optimize->rangemax[j] - optimize->rangemin[j])\n              / (optimize->nsweeps[j] - 1);\n          optimize->value[i * optimize->nvariables + j] = e;\n        }\n    }\n  optimize->nsaveds = 0;\n  if (nthreads <= 1)\n    optimize_sequential ();\n  else\n    {\n      for (i = 0; i < nthreads; ++i)\n        {\n          data[i].thread = i;\n          thread[i]\n            = g_thread_new (NULL, (GThreadFunc) optimize_thread, &data[i]);\n        }\n      for (i = 0; i < nthreads; ++i)\n        g_thread_join (thread[i]);\n    }\n#if HAVE_MPI\n  // Communicating tasks results\n  optimize_synchronise ();\n#endif\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_sweep: end\\n\");\n#endif\n}\n\n/**\n * Function to optimize with the Monte-Carlo algorithm.\n */\nstatic void\noptimize_MonteCarlo ()\n{\n  unsigned int i, j;\n  GThread *thread[nthreads];\n  ParallelData data[nthreads];\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_MonteCarlo: start\\n\");\n#endif\n  for (i = 0; i < optimize->nsimulations; ++i)\n    for (j = 0; j < optimize->nvariables; ++j)\n      optimize->value[i * optimize->nvariables + j]\n        = optimize->rangemin[j] + gsl_rng_uniform (optimize->rng)\n        * (optimize->rangemax[j] - optimize->rangemin[j]);\n  optimize->nsaveds = 0;\n  if (nthreads <= 1)\n    optimize_sequential ();\n  else\n    {\n      for (i = 0; i < nthreads; ++i)\n        {\n          data[i].thread = i;\n          thread[i]\n            = g_thread_new (NULL, (GThreadFunc) optimize_thread, &data[i]);\n        }\n      for (i = 0; i < nthreads; ++i)\n        g_thread_join (thread[i]);\n    }\n#if HAVE_MPI\n  // Communicating tasks results\n  optimize_synchronise ();\n#endif\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_MonteCarlo: end\\n\");\n#endif\n}\n\n/**\n * Function to optimize with the orthogonal sampling algorithm.\n */\nstatic void\noptimize_orthogonal ()\n{\n  unsigned int i, j, k, l;\n  double e;\n  GThread *thread[nthreads];\n  ParallelData data[nthreads];\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_orthogonal: start\\n\");\n#endif\n  for (i = 0; i < optimize->nsimulations; ++i)\n    {\n      k = i;\n      for (j = 0; j < optimize->nvariables; ++j)\n        {\n          l = k % optimize->nsweeps[j];\n          k /= optimize->nsweeps[j];\n          e = optimize->rangemin[j];\n          if (optimize->nsweeps[j] > 1)\n            e += (l + gsl_rng_uniform (optimize->rng))\n              * (optimize->rangemax[j] - optimize->rangemin[j])\n              / optimize->nsweeps[j];\n          optimize->value[i * optimize->nvariables + j] = e;\n        }\n    }\n  optimize->nsaveds = 0;\n  if (nthreads <= 1)\n    optimize_sequential ();\n  else\n    {\n      for (i = 0; i < nthreads; ++i)\n        {\n          data[i].thread = i;\n          thread[i]\n            = g_thread_new (NULL, (GThreadFunc) optimize_thread, &data[i]);\n        }\n      for (i = 0; i < nthreads; ++i)\n        g_thread_join (thread[i]);\n    }\n#if HAVE_MPI\n  // Communicating tasks results\n  optimize_synchronise ();\n#endif\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_orthogonal: end\\n\");\n#endif\n}\n\n/**\n * Function to save the best simulation in a hill climbing method.\n */\nstatic void\noptimize_best_climbing (unsigned int simulation,        ///< Simulation number.\n                        double value)   ///< Objective function value.\n{\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_best_climbing: start\\n\");\n  fprintf (stderr,\n           \"optimize_best_climbing: simulation=%u value=%.14le best=%.14le\\n\",\n           simulation, value, optimize->error_best[0]);\n#endif\n  if (value < optimize->error_best[0])\n    {\n      optimize->error_best[0] = value;\n      optimize->simulation_best[0] = simulation;\n#if DEBUG_OPTIMIZE\n      fprintf (stderr,\n               \"optimize_best_climbing: BEST simulation=%u value=%.14le\\n\",\n               simulation, value);\n#endif\n    }\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_best_climbing: end\\n\");\n#endif\n}\n\n/**\n * Function to estimate the hill climbing sequentially.\n */\nstatic inline void\noptimize_climbing_sequential (unsigned int simulation)  ///< Simulation number.\n{\n  double e;\n  unsigned int i, j;\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_climbing_sequential: start\\n\");\n  fprintf (stderr, \"optimize_climbing_sequential: nstart_climbing=%u \"\n           \"nend_climbing=%u\\n\",\n           optimize->nstart_climbing, optimize->nend_climbing);\n#endif\n  for (i = optimize->nstart_climbing; i < optimize->nend_climbing; ++i)\n    {\n      j = simulation + i;\n      e = optimize_norm (j);\n      optimize_best_climbing (j, e);\n      optimize_save_variables (j, e);\n      if (e < optimize->threshold)\n        {\n          optimize->stop = 1;\n          break;\n        }\n#if DEBUG_OPTIMIZE\n      fprintf (stderr, \"optimize_climbing_sequential: i=%u e=%lg\\n\", i, e);\n#endif\n    }\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_climbing_sequential: end\\n\");\n#endif\n}\n\n/**\n * Function to estimate the hill climbing on a thread.\n *\n * \\return NULL\n */\nstatic void *\noptimize_climbing_thread (ParallelData * data)  ///< Function data.\n{\n  unsigned int i, thread;\n  double e;\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_climbing_thread: start\\n\");\n#endif\n  thread = data->thread;\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_climbing_thread: thread=%u start=%u end=%u\\n\",\n           thread,\n           optimize->thread_climbing[thread],\n           optimize->thread_climbing[thread + 1]);\n#endif\n  for (i = optimize->thread_climbing[thread];\n       i < optimize->thread_climbing[thread + 1]; ++i)\n    {\n      e = optimize_norm (i);\n      g_mutex_lock (mutex);\n      optimize_best_climbing (i, e);\n      optimize_save_variables (i, e);\n      if (e < optimize->threshold)\n        optimize->stop = 1;\n      g_mutex_unlock (mutex);\n      if (optimize->stop)\n        break;\n#if DEBUG_OPTIMIZE\n      fprintf (stderr, \"optimize_climbing_thread: i=%u e=%lg\\n\", i, e);\n#endif\n    }\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_climbing_thread: end\\n\");\n#endif\n  g_thread_exit (NULL);\n  return NULL;\n}\n\n/**\n * Function to estimate a component of the hill climbing vector.\n */\nstatic double\noptimize_estimate_climbing_random (unsigned int variable,\n                                   ///< Variable number.\n                                   unsigned int estimate\n                                   __attribute__((unused)))\n  ///< Estimate number.\n{\n  double x;\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_estimate_climbing_random: start\\n\");\n#endif\n  x = optimize->climbing[variable]\n    + (1. - 2. * gsl_rng_uniform (optimize->rng)) * optimize->step[variable];\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_estimate_climbing_random: climbing%u=%lg\\n\",\n           variable, x);\n  fprintf (stderr, \"optimize_estimate_climbing_random: end\\n\");\n#endif\n  return x;\n}\n\n/**\n * Function to estimate a component of the hill climbing vector.\n */\nstatic double\noptimize_estimate_climbing_coordinates (unsigned int variable,\n                                        ///< Variable number.\n                                        unsigned int estimate)\n                                        ///< Estimate number.\n{\n  double x;\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_estimate_climbing_coordinates: start\\n\");\n#endif\n  x = optimize->climbing[variable];\n  if (estimate >= (2 * variable) && estimate < (2 * variable + 2))\n    {\n      if (estimate & 1)\n        x += optimize->step[variable];\n      else\n        x -= optimize->step[variable];\n    }\n#if DEBUG_OPTIMIZE\n  fprintf (stderr,\n           \"optimize_estimate_climbing_coordinates: climbing%u=%lg\\n\",\n           variable, x);\n  fprintf (stderr, \"optimize_estimate_climbing_coordinates: end\\n\");\n#endif\n  return x;\n}\n\n/**\n * Function to do a step of the hill climbing method.\n */\nstatic inline void\noptimize_step_climbing (unsigned int simulation)        ///< Simulation number.\n{\n  GThread *thread[nthreads_climbing];\n  ParallelData data[nthreads_climbing];\n  unsigned int i, j, k, b;\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_step_climbing: start\\n\");\n#endif\n  for (i = 0; i < optimize->nestimates; ++i)\n    {\n      k = (simulation + i) * optimize->nvariables;\n      b = optimize->simulation_best[0] * optimize->nvariables;\n#if DEBUG_OPTIMIZE\n      fprintf (stderr, \"optimize_step_climbing: simulation=%u best=%u\\n\",\n               simulation + i, optimize->simulation_best[0]);\n#endif\n      for (j = 0; j < optimize->nvariables; ++j, ++k, ++b)\n        {\n#if DEBUG_OPTIMIZE\n          fprintf (stderr,\n                   \"optimize_step_climbing: estimate=%u best%u=%.14le\\n\",\n                   i, j, optimize->value[b]);\n#endif\n          optimize->value[k]\n            = optimize->value[b] + optimize_estimate_climbing (j, i);\n          optimize->value[k] = fmin (fmax (optimize->value[k],\n                                           optimize->rangeminabs[j]),\n                                     optimize->rangemaxabs[j]);\n#if DEBUG_OPTIMIZE\n          fprintf (stderr,\n                   \"optimize_step_climbing: estimate=%u variable%u=%.14le\\n\",\n                   i, j, optimize->value[k]);\n#endif\n        }\n    }\n  if (nthreads_climbing == 1)\n    optimize_climbing_sequential (simulation);\n  else\n    {\n      for (i = 0; i <= nthreads_climbing; ++i)\n        {\n          optimize->thread_climbing[i]\n            = simulation + optimize->nstart_climbing\n            + i * (optimize->nend_climbing - optimize->nstart_climbing)\n            / nthreads_climbing;\n#if DEBUG_OPTIMIZE\n          fprintf (stderr,\n                   \"optimize_step_climbing: i=%u thread_climbing=%u\\n\",\n                   i, optimize->thread_climbing[i]);\n#endif\n        }\n      for (i = 0; i < nthreads_climbing; ++i)\n        {\n          data[i].thread = i;\n          thread[i] = g_thread_new\n            (NULL, (GThreadFunc) optimize_climbing_thread, &data[i]);\n        }\n      for (i = 0; i < nthreads_climbing; ++i)\n        g_thread_join (thread[i]);\n    }\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_step_climbing: end\\n\");\n#endif\n}\n\n/**\n * Function to optimize with a hill climbing method.\n */\nstatic inline void\noptimize_climbing ()\n{\n  unsigned int i, j, k, b, s, adjust;\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_climbing: start\\n\");\n#endif\n  for (i = 0; i < optimize->nvariables; ++i)\n    optimize->climbing[i] = 0.;\n  b = optimize->simulation_best[0] * optimize->nvariables;\n  s = optimize->nsimulations;\n  adjust = 1;\n  for (i = 0; i < optimize->nsteps; ++i, s += optimize->nestimates, b = k)\n    {\n#if DEBUG_OPTIMIZE\n      fprintf (stderr, \"optimize_climbing: step=%u old_best=%u\\n\",\n               i, optimize->simulation_best[0]);\n#endif\n      optimize_step_climbing (s);\n      k = optimize->simulation_best[0] * optimize->nvariables;\n#if DEBUG_OPTIMIZE\n      fprintf (stderr, \"optimize_climbing: step=%u best=%u\\n\",\n               i, optimize->simulation_best[0]);\n#endif\n      if (k == b)\n        {\n          if (adjust)\n            for (j = 0; j < optimize->nvariables; ++j)\n              optimize->step[j] *= 0.5;\n          for (j = 0; j < optimize->nvariables; ++j)\n            optimize->climbing[j] = 0.;\n          adjust = 1;\n        }\n      else\n        {\n          for (j = 0; j < optimize->nvariables; ++j)\n            {\n#if DEBUG_OPTIMIZE\n              fprintf (stderr,\n                       \"optimize_climbing: best%u=%.14le old%u=%.14le\\n\",\n                       j, optimize->value[k + j], j, optimize->value[b + j]);\n#endif\n              optimize->climbing[j]\n                = (1. - optimize->relaxation) * optimize->climbing[j]\n                + optimize->relaxation\n                * (optimize->value[k + j] - optimize->value[b + j]);\n#if DEBUG_OPTIMIZE\n              fprintf (stderr, \"optimize_climbing: climbing%u=%.14le\\n\",\n                       j, optimize->climbing[j]);\n#endif\n            }\n          adjust = 0;\n        }\n    }\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_climbing: end\\n\");\n#endif\n}\n\n/**\n * Function to calculate the objective function of an entity.\n *\n * \\return objective function value.\n */\nstatic double\noptimize_genetic_objective (Entity * entity)    ///< entity data.\n{\n  unsigned int j;\n  double objective;\n  char buffer[64];\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_genetic_objective: start\\n\");\n#endif\n  for (j = 0; j < optimize->nvariables; ++j)\n    {\n      optimize->value[entity->id * optimize->nvariables + j]\n        = genetic_get_variable (entity, optimize->genetic_variable + j);\n    }\n  objective = optimize_norm (entity->id);\n  g_mutex_lock (mutex);\n  for (j = 0; j < optimize->nvariables; ++j)\n    {\n      snprintf (buffer, 64, \"%s \", format[optimize->precision[j]]);\n      fprintf (optimize->file_variables, buffer,\n               genetic_get_variable (entity, optimize->genetic_variable + j));\n    }\n  fprintf (optimize->file_variables, \"%.14le\\n\", objective);\n  g_mutex_unlock (mutex);\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_genetic_objective: end\\n\");\n#endif\n  return objective;\n}\n\n/**\n * Function to optimize with the genetic algorithm.\n */\nstatic void\noptimize_genetic ()\n{\n  double *best_variable = NULL;\n  char *best_genome = NULL;\n  double best_objective = 0.;\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_genetic: start\\n\");\n  fprintf (stderr, \"optimize_genetic: ntasks=%u nthreads=%u\\n\", ntasks,\n           nthreads);\n  fprintf (stderr,\n           \"optimize_genetic: nvariables=%u population=%u generations=%u\\n\",\n           optimize->nvariables, optimize->nsimulations, optimize->niterations);\n  fprintf (stderr,\n           \"optimize_genetic: mutation=%lg reproduction=%lg adaptation=%lg\\n\",\n           optimize->mutation_ratio, optimize->reproduction_ratio,\n           optimize->adaptation_ratio);\n#endif\n  genetic_algorithm_default (optimize->nvariables,\n                             optimize->genetic_variable,\n                             optimize->nsimulations,\n                             optimize->niterations,\n                             optimize->mutation_ratio,\n                             optimize->reproduction_ratio,\n                             optimize->adaptation_ratio,\n                             optimize->seed,\n                             optimize->threshold,\n                             &optimize_genetic_objective,\n                             &best_genome, &best_variable, &best_objective);\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_genetic: the best\\n\");\n#endif\n  optimize->error_old = (double *) g_malloc (sizeof (double));\n  optimize->value_old\n    = (double *) g_malloc (optimize->nvariables * sizeof (double));\n  optimize->error_old[0] = best_objective;\n  memcpy (optimize->value_old, best_variable,\n          optimize->nvariables * sizeof (double));\n  g_free (best_genome);\n  g_free (best_variable);\n  optimize_print ();\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_genetic: end\\n\");\n#endif\n}\n\n/**\n * Function to save the best results on iterative methods.\n */\nstatic inline void\noptimize_save_old ()\n{\n  unsigned int i, j;\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_save_old: start\\n\");\n  fprintf (stderr, \"optimize_save_old: nsaveds=%u\\n\", optimize->nsaveds);\n#endif\n  memcpy (optimize->error_old, optimize->error_best,\n          optimize->nbest * sizeof (double));\n  for (i = 0; i < optimize->nbest; ++i)\n    {\n      j = optimize->simulation_best[i];\n#if DEBUG_OPTIMIZE\n      fprintf (stderr, \"optimize_save_old: i=%u j=%u\\n\", i, j);\n#endif\n      memcpy (optimize->value_old + i * optimize->nvariables,\n              optimize->value + j * optimize->nvariables,\n              optimize->nvariables * sizeof (double));\n    }\n#if DEBUG_OPTIMIZE\n  for (i = 0; i < optimize->nvariables; ++i)\n    fprintf (stderr, \"optimize_save_old: best variable %u=%lg\\n\",\n             i, optimize->value_old[i]);\n  fprintf (stderr, \"optimize_save_old: end\\n\");\n#endif\n}\n\n/**\n * Function to merge the best results with the previous step best results on\n *   iterative methods.\n */\nstatic inline void\noptimize_merge_old ()\n{\n  unsigned int i, j, k;\n  double v[optimize->nbest * optimize->nvariables], e[optimize->nbest],\n    *enew, *eold;\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_merge_old: start\\n\");\n#endif\n  enew = optimize->error_best;\n  eold = optimize->error_old;\n  i = j = k = 0;\n  do\n    {\n      if (*enew < *eold)\n        {\n          memcpy (v + k * optimize->nvariables,\n                  optimize->value\n                  + optimize->simulation_best[i] * optimize->nvariables,\n                  optimize->nvariables * sizeof (double));\n          e[k] = *enew;\n          ++k;\n          ++enew;\n          ++i;\n        }\n      else\n        {\n          memcpy (v + k * optimize->nvariables,\n                  optimize->value_old + j * optimize->nvariables,\n                  optimize->nvariables * sizeof (double));\n          e[k] = *eold;\n          ++k;\n          ++eold;\n          ++j;\n        }\n    }\n  while (k < optimize->nbest);\n  memcpy (optimize->value_old, v, k * optimize->nvariables * sizeof (double));\n  memcpy (optimize->error_old, e, k * sizeof (double));\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_merge_old: end\\n\");\n#endif\n}\n\n/**\n * Function to refine the search ranges of the variables in iterative \n *   algorithms.\n */\nstatic inline void\noptimize_refine ()\n{\n  unsigned int i, j;\n  double d;\n#if HAVE_MPI\n  MPI_Status mpi_stat;\n#endif\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_refine: start\\n\");\n#endif\n#if HAVE_MPI\n  if (!optimize->mpi_rank)\n    {\n#endif\n      for (j = 0; j < optimize->nvariables; ++j)\n        {\n          optimize->rangemin[j] = optimize->rangemax[j]\n            = optimize->value_old[j];\n        }\n      for (i = 0; ++i < optimize->nbest;)\n        {\n          for (j = 0; j < optimize->nvariables; ++j)\n            {\n              optimize->rangemin[j]\n                = fmin (optimize->rangemin[j],\n                        optimize->value_old[i * optimize->nvariables + j]);\n              optimize->rangemax[j]\n                = fmax (optimize->rangemax[j],\n                        optimize->value_old[i * optimize->nvariables + j]);\n            }\n        }\n      for (j = 0; j < optimize->nvariables; ++j)\n        {\n          d = optimize->tolerance\n            * (optimize->rangemax[j] - optimize->rangemin[j]);\n          switch (optimize->algorithm)\n            {\n            case ALGORITHM_MONTE_CARLO:\n              d *= 0.5;\n              break;\n            default:\n              if (optimize->nsweeps[j] > 1)\n                d /= optimize->nsweeps[j] - 1;\n              else\n                d = 0.;\n            }\n          optimize->rangemin[j] -= d;\n          optimize->rangemin[j]\n            = fmax (optimize->rangemin[j], optimize->rangeminabs[j]);\n          optimize->rangemax[j] += d;\n          optimize->rangemax[j]\n            = fmin (optimize->rangemax[j], optimize->rangemaxabs[j]);\n          printf (\"%s min=%lg max=%lg\\n\", optimize->label[j],\n                  optimize->rangemin[j], optimize->rangemax[j]);\n          fprintf (optimize->file_result, \"%s min=%lg max=%lg\\n\",\n                   optimize->label[j], optimize->rangemin[j],\n                   optimize->rangemax[j]);\n        }\n#if HAVE_MPI\n      for (i = 1; (int) i < ntasks; ++i)\n        {\n          MPI_Send (optimize->rangemin, optimize->nvariables, MPI_DOUBLE, i,\n                    1, MPI_COMM_WORLD);\n          MPI_Send (optimize->rangemax, optimize->nvariables, MPI_DOUBLE, i,\n                    1, MPI_COMM_WORLD);\n        }\n    }\n  else\n    {\n      MPI_Recv (optimize->rangemin, optimize->nvariables, MPI_DOUBLE, 0, 1,\n                MPI_COMM_WORLD, &mpi_stat);\n      MPI_Recv (optimize->rangemax, optimize->nvariables, MPI_DOUBLE, 0, 1,\n                MPI_COMM_WORLD, &mpi_stat);\n    }\n#endif\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_refine: end\\n\");\n#endif\n}\n\n/**\n * Function to do a step of the iterative algorithm.\n */\nstatic void\noptimize_step ()\n{\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_step: start\\n\");\n#endif\n  optimize_algorithm ();\n  if (optimize->nsteps)\n    optimize_climbing ();\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_step: end\\n\");\n#endif\n}\n\n/**\n * Function to iterate the algorithm.\n */\nstatic inline void\noptimize_iterate ()\n{\n  unsigned int i;\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_iterate: start\\n\");\n#endif\n  optimize->error_old = (double *) g_malloc (optimize->nbest * sizeof (double));\n  optimize->value_old =\n    (double *) g_malloc (optimize->nbest * optimize->nvariables *\n                         sizeof (double));\n  optimize_step ();\n  optimize_save_old ();\n  optimize_refine ();\n  optimize_print ();\n  for (i = 1; i < optimize->niterations && !optimize->stop; ++i)\n    {\n      optimize_step ();\n      optimize_merge_old ();\n      optimize_refine ();\n      optimize_print ();\n    }\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_iterate: end\\n\");\n#endif\n}\n\n/**\n * Function to free the memory used by the Optimize struct.\n */\nvoid\noptimize_free ()\n{\n  unsigned int i, j;\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_free: start\\n\");\n#endif\n  for (j = 0; j < optimize->ninputs; ++j)\n    {\n      for (i = 0; i < optimize->nexperiments; ++i)\n        g_mapped_file_unref (optimize->file[j][i]);\n      g_free (optimize->file[j]);\n    }\n  g_free (optimize->error_old);\n  g_free (optimize->value_old);\n  g_free (optimize->value);\n  g_free (optimize->genetic_variable);\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_free: end\\n\");\n#endif\n}\n\n/**\n * Function to open and perform a optimization.\n */\nvoid\noptimize_open ()\n{\n  GTimeZone *tz;\n  GDateTime *t0, *t;\n  unsigned int i, j;\n\n#if DEBUG_OPTIMIZE\n  char *buffer;\n  fprintf (stderr, \"optimize_open: start\\n\");\n#endif\n\n  // Getting initial time\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_open: getting initial time\\n\");\n#endif\n  tz = g_time_zone_new_utc ();\n  t0 = g_date_time_new_now (tz);\n\n  // Obtaining and initing the pseudo-random numbers generator seed\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_open: getting initial seed\\n\");\n#endif\n  if (optimize->seed == DEFAULT_RANDOM_SEED)\n    optimize->seed = input->seed;\n  gsl_rng_set (optimize->rng, optimize->seed);\n\n  // Replacing the working directory\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_open: replacing the working directory\\n\");\n#endif\n  g_chdir (input->directory);\n\n  // Getting results file names\n  optimize->result = input->result;\n  optimize->variables = input->variables;\n\n  // Obtaining the simulator file\n  optimize->simulator = input->simulator;\n\n  // Obtaining the evaluator file\n  optimize->evaluator = input->evaluator;\n\n  // Reading the algorithm\n  optimize->algorithm = input->algorithm;\n  switch (optimize->algorithm)\n    {\n    case ALGORITHM_MONTE_CARLO:\n      optimize_algorithm = optimize_MonteCarlo;\n      break;\n    case ALGORITHM_SWEEP:\n      optimize_algorithm = optimize_sweep;\n      break;\n    case ALGORITHM_ORTHOGONAL:\n      optimize_algorithm = optimize_orthogonal;\n      break;\n    default:\n      optimize_algorithm = optimize_genetic;\n      optimize->mutation_ratio = input->mutation_ratio;\n      optimize->reproduction_ratio = input->reproduction_ratio;\n      optimize->adaptation_ratio = input->adaptation_ratio;\n    }\n  optimize->nvariables = input->nvariables;\n  optimize->nsimulations = input->nsimulations;\n  optimize->niterations = input->niterations;\n  optimize->nbest = input->nbest;\n  optimize->tolerance = input->tolerance;\n  optimize->nsteps = input->nsteps;\n  optimize->nestimates = 0;\n  optimize->threshold = input->threshold;\n  optimize->stop = 0;\n  if (input->nsteps)\n    {\n      optimize->relaxation = input->relaxation;\n      switch (input->climbing)\n        {\n        case CLIMBING_METHOD_COORDINATES:\n          optimize->nestimates = 2 * optimize->nvariables;\n          optimize_estimate_climbing = optimize_estimate_climbing_coordinates;\n          break;\n        default:\n          optimize->nestimates = input->nestimates;\n          optimize_estimate_climbing = optimize_estimate_climbing_random;\n        }\n    }\n\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_open: nbest=%u\\n\", optimize->nbest);\n#endif\n  optimize->simulation_best\n    = (unsigned int *) alloca (optimize->nbest * sizeof (unsigned int));\n  optimize->error_best = (double *) alloca (optimize->nbest * sizeof (double));\n\n  // Reading the experimental data\n#if DEBUG_OPTIMIZE\n  buffer = g_get_current_dir ();\n  fprintf (stderr, \"optimize_open: current directory=%s\\n\", buffer);\n  g_free (buffer);\n#endif\n  optimize->nexperiments = input->nexperiments;\n  optimize->ninputs = input->experiment->ninputs;\n  optimize->experiment\n    = (char **) alloca (input->nexperiments * sizeof (char *));\n  optimize->weight = (double *) alloca (input->nexperiments * sizeof (double));\n  for (i = 0; i < input->experiment->ninputs; ++i)\n    optimize->file[i] = (GMappedFile **)\n      g_malloc (input->nexperiments * sizeof (GMappedFile *));\n  for (i = 0; i < input->nexperiments; ++i)\n    {\n#if DEBUG_OPTIMIZE\n      fprintf (stderr, \"optimize_open: i=%u\\n\", i);\n#endif\n      optimize->experiment[i] = input->experiment[i].name;\n      optimize->weight[i] = input->experiment[i].weight;\n#if DEBUG_OPTIMIZE\n      fprintf (stderr, \"optimize_open: experiment=%s weight=%lg\\n\",\n               optimize->experiment[i], optimize->weight[i]);\n#endif\n      for (j = 0; j < input->experiment->ninputs; ++j)\n        {\n#if DEBUG_OPTIMIZE\n          fprintf (stderr, \"optimize_open: stencil%u\\n\", j + 1);\n#endif\n          optimize->file[j][i]\n            = g_mapped_file_new (input->experiment[i].stencil[j], 0, NULL);\n        }\n    }\n\n  // Reading the variables data\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_open: reading variables\\n\");\n#endif\n  optimize->label = (char **) alloca (input->nvariables * sizeof (char *));\n  j = input->nvariables * sizeof (double);\n  optimize->rangemin = (double *) alloca (j);\n  optimize->rangeminabs = (double *) alloca (j);\n  optimize->rangemax = (double *) alloca (j);\n  optimize->rangemaxabs = (double *) alloca (j);\n  optimize->step = (double *) alloca (j);\n  j = input->nvariables * sizeof (unsigned int);\n  optimize->precision = (unsigned int *) alloca (j);\n  optimize->nsweeps = (unsigned int *) alloca (j);\n  optimize->nbits = (unsigned int *) alloca (j);\n  for (i = 0; i < input->nvariables; ++i)\n    {\n      optimize->label[i] = input->variable[i].name;\n      optimize->rangemin[i] = input->variable[i].rangemin;\n      optimize->rangeminabs[i] = input->variable[i].rangeminabs;\n      optimize->rangemax[i] = input->variable[i].rangemax;\n      optimize->rangemaxabs[i] = input->variable[i].rangemaxabs;\n      optimize->precision[i] = input->variable[i].precision;\n      optimize->step[i] = input->variable[i].step;\n      optimize->nsweeps[i] = input->variable[i].nsweeps;\n      optimize->nbits[i] = input->variable[i].nbits;\n    }\n  if (input->algorithm == ALGORITHM_SWEEP\n      || input->algorithm == ALGORITHM_ORTHOGONAL)\n    {\n      optimize->nsimulations = 1;\n      for (i = 0; i < input->nvariables; ++i)\n        {\n          optimize->nsimulations *= optimize->nsweeps[i];\n#if DEBUG_OPTIMIZE\n          fprintf (stderr, \"optimize_open: nsweeps=%u nsimulations=%u\\n\",\n                   optimize->nsweeps[i], optimize->nsimulations);\n#endif\n        }\n    }\n  if (optimize->nsteps)\n    optimize->climbing\n      = (double *) alloca (optimize->nvariables * sizeof (double));\n\n  // Setting error norm\n  switch (input->norm)\n    {\n    case ERROR_NORM_EUCLIDIAN:\n      optimize_norm = optimize_norm_euclidian;\n      break;\n    case ERROR_NORM_MAXIMUM:\n      optimize_norm = optimize_norm_maximum;\n      break;\n    case ERROR_NORM_P:\n      optimize_norm = optimize_norm_p;\n      optimize->p = input->p;\n      break;\n    default:\n      optimize_norm = optimize_norm_taxicab;\n    }\n\n  // Allocating values\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_open: allocating variables\\n\");\n  fprintf (stderr, \"optimize_open: nvariables=%u algorithm=%u\\n\",\n           optimize->nvariables, optimize->algorithm);\n#endif\n  optimize->genetic_variable = NULL;\n  if (optimize->algorithm == ALGORITHM_GENETIC)\n    {\n      optimize->genetic_variable = (GeneticVariable *)\n        g_malloc (optimize->nvariables * sizeof (GeneticVariable));\n      for (i = 0; i < optimize->nvariables; ++i)\n        {\n#if DEBUG_OPTIMIZE\n          fprintf (stderr, \"optimize_open: i=%u min=%lg max=%lg nbits=%u\\n\",\n                   i, optimize->rangemin[i], optimize->rangemax[i],\n                   optimize->nbits[i]);\n#endif\n          optimize->genetic_variable[i].minimum = optimize->rangemin[i];\n          optimize->genetic_variable[i].maximum = optimize->rangemax[i];\n          optimize->genetic_variable[i].nbits = optimize->nbits[i];\n        }\n    }\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_open: nvariables=%u nsimulations=%u\\n\",\n           optimize->nvariables, optimize->nsimulations);\n#endif\n  optimize->value = (double *)\n    g_malloc ((optimize->nsimulations\n               + optimize->nestimates * optimize->nsteps)\n              * optimize->nvariables * sizeof (double));\n\n  // Calculating simulations to perform for each task\n#if HAVE_MPI\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_open: rank=%u ntasks=%u\\n\",\n           optimize->mpi_rank, ntasks);\n#endif\n  optimize->nstart = optimize->mpi_rank * optimize->nsimulations / ntasks;\n  optimize->nend = (1 + optimize->mpi_rank) * optimize->nsimulations / ntasks;\n  if (optimize->nsteps)\n    {\n      optimize->nstart_climbing\n        = optimize->mpi_rank * optimize->nestimates / ntasks;\n      optimize->nend_climbing\n        = (1 + optimize->mpi_rank) * optimize->nestimates / ntasks;\n    }\n#else\n  optimize->nstart = 0;\n  optimize->nend = optimize->nsimulations;\n  if (optimize->nsteps)\n    {\n      optimize->nstart_climbing = 0;\n      optimize->nend_climbing = optimize->nestimates;\n    }\n#endif\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_open: nstart=%u nend=%u\\n\", optimize->nstart,\n           optimize->nend);\n#endif\n\n  // Calculating simulations to perform for each thread\n  optimize->thread\n    = (unsigned int *) alloca ((1 + nthreads) * sizeof (unsigned int));\n  for (i = 0; i <= nthreads; ++i)\n    {\n      optimize->thread[i] = optimize->nstart\n        + i * (optimize->nend - optimize->nstart) / nthreads;\n#if DEBUG_OPTIMIZE\n      fprintf (stderr, \"optimize_open: i=%u thread=%u\\n\", i,\n               optimize->thread[i]);\n#endif\n    }\n  if (optimize->nsteps)\n    optimize->thread_climbing = (unsigned int *)\n      alloca ((1 + nthreads_climbing) * sizeof (unsigned int));\n\n  // Opening result files\n  optimize->file_result = g_fopen (optimize->result, \"w\");\n  optimize->file_variables = g_fopen (optimize->variables, \"w\");\n\n  // Performing the algorithm\n  switch (optimize->algorithm)\n    {\n      // Genetic algorithm\n    case ALGORITHM_GENETIC:\n      optimize_genetic ();\n      break;\n\n      // Iterative algorithm\n    default:\n      optimize_iterate ();\n    }\n\n  // Getting calculation time\n  t = g_date_time_new_now (tz);\n  optimize->calculation_time = 0.000001 * g_date_time_difference (t, t0);\n  g_date_time_unref (t);\n  g_date_time_unref (t0);\n  g_time_zone_unref (tz);\n  printf (\"%s = %.6lg s\\n\", _(\"Calculation time\"), optimize->calculation_time);\n  fprintf (optimize->file_result, \"%s = %.6lg s\\n\",\n           _(\"Calculation time\"), optimize->calculation_time);\n\n  // Closing result files\n  fclose (optimize->file_variables);\n  fclose (optimize->file_result);\n\n#if DEBUG_OPTIMIZE\n  fprintf (stderr, \"optimize_open: end\\n\");\n#endif\n}\n", "meta": {"hexsha": "1660a2e592a65c0c3f8271c8d7479baab8a7a492", "size": 51080, "ext": "c", "lang": "C", "max_stars_repo_path": "4.0.5/optimize.c", "max_stars_repo_name": "jburguete/mpcotool", "max_stars_repo_head_hexsha": "e8a6a9713d4ef73b0aa8a0a552d91117ebd22610", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-17T14:59:29.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-17T14:59:29.000Z", "max_issues_repo_path": "4.0.5/optimize.c", "max_issues_repo_name": "jburguete/mpcotool", "max_issues_repo_head_hexsha": "e8a6a9713d4ef73b0aa8a0a552d91117ebd22610", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-03-08T17:02:14.000Z", "max_issues_repo_issues_event_max_datetime": "2016-03-08T17:02:14.000Z", "max_forks_repo_path": "4.0.5/optimize.c", "max_forks_repo_name": "jburguete/mpcotool", "max_forks_repo_head_hexsha": "e8a6a9713d4ef73b0aa8a0a552d91117ebd22610", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6804183614, "max_line_length": 80, "alphanum_fraction": 0.6170516836, "num_tokens": 13215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22815650216092534, "lm_q2_score": 0.027169229074096458, "lm_q1q2_score": 0.006198836271954764}}
{"text": "#ifndef ENTITY_H_\n#define ENTITY_H_\n\n#include <vector>\n#include <memory>\n#include <utility>\n#include <gsl.h>\n#include \"Component.h\"\n\nusing std::vector;\nusing std::unique_ptr;\nusing std::make_unique;\nusing std::move;\nusing std::forward;\n\nclass Entity\n{\npublic:\n\n    static void test();\n\n    template <typename C, typename... Args>\n    void addComponent(Args &&... args);\n\n    template <typename C>\n    C * getComponent() const;\n\nprivate:\n\n    Component * getComponent(Component::Id _id, Component::Id _mask) const;\n\n    vector<unique_ptr<Component>> m_components;\n    vector<Component::Id> m_componentIds;      // invariant : m_components.size() == m_componentIds.size()\n};\n\ntemplate<typename C, typename ...Args>\ninline void Entity::addComponent(Args && ...args)\n{\n    Expects(IdInfoOf<C>::value.isRegistered() != 0);\n    m_components.emplace_back(make_unique<C>(forward<Args>(args)...));\n    m_componentIds.emplace_back(IdInfoOf<C>::value.getId());\n}\n\ntemplate<typename C>\ninline C * Entity::getComponent() const\n{\n    auto & idInfo = IdInfoOf<C>::value;\n    auto id = idInfo.getId();\n    auto mask = idInfo.getMaskId();\n    return static_cast<C*>(getComponent(id, mask));\n}\n\n#endif // ENTITY_H_\n", "meta": {"hexsha": "089b25c174dd38af5893113bf4aa75df725ac1d7", "size": 1197, "ext": "h", "lang": "C", "max_stars_repo_path": "GetComponent/include/Entity.h", "max_stars_repo_name": "Onduril/GetComponent", "max_stars_repo_head_hexsha": "84ad449d9e6f242d77fe4774791e5db5356b75b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GetComponent/include/Entity.h", "max_issues_repo_name": "Onduril/GetComponent", "max_issues_repo_head_hexsha": "84ad449d9e6f242d77fe4774791e5db5356b75b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GetComponent/include/Entity.h", "max_forks_repo_name": "Onduril/GetComponent", "max_forks_repo_head_hexsha": "84ad449d9e6f242d77fe4774791e5db5356b75b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.1666666667, "max_line_length": 106, "alphanum_fraction": 0.6892230576, "num_tokens": 290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.17328821446825263, "lm_q2_score": 0.03567854933968074, "lm_q1q2_score": 0.006182672109890729}}
{"text": "#pragma once\n\n#include <cstddef>\n#include <memory>\n#include <iostream>\n#include <array>\n#include <gsl\\gsl>\n#include \"../utils/CRSP.h\"\n#include \"./Pool.h\"\n#include \"../math/OtherMath.h\"\n#include \"../types/def.h\"\n\n\nnamespace config {\n    /**\n    Default pool size for our Small Memory Allocator pools.\n    */\n    constexpr size_t sma_pool_size = 1024 * 1024;\n\tconstexpr size_t sma_pool_amount = 10;\n}  // namespace config\n\n\n/**\nOur allocator class that will be the general interface for any future\nallocation. Inherits from the Curiously Recurring Singleton Pattern in order to \nhave just one global one.\n\n@see CRSP\n*/\nclass SmallMemoryAllocator : public CRSP<SmallMemoryAllocator> {\nprivate:\n    friend class CRSP<SmallMemoryAllocator>;\n\n    SmallMemoryAllocator();\n    ~SmallMemoryAllocator();\n\npublic:\n    Pool * get_pool_for_size(size_t size);\n\n    bool fits(size_t size) const;\n\n    void* alloc(size_t size);\n\n    template <typename T>\n    T* alloc() {\n        return reinterpret_cast<T*>(alloc(sizeof(T)));\n    }\n\n    void dealloc(void* elem);\n\n    void print_status(std::ostream& stream);\n\n    void print_status(void* elem, std::ostream& stream) const;\n\nprivate:\n\tsize_t get_pool_index(size_t size) const;\n\n    std::array<std::unique_ptr<Pool>, config::sma_pool_amount> m_pool_array{};\n\tstd::array<size_t, config::sma_pool_amount + 1> m_extra_requested_elements{};\n    std::array<size_t, config::sma_pool_amount> m_max_allocated_elements{};\n\n\n    byte* m_general_pool{ nullptr };\n};\n\n", "meta": {"hexsha": "26d6192988ec2d6bb228cceb4cf28b351461eb63", "size": 1489, "ext": "h", "lang": "C", "max_stars_repo_path": "NGene/src/memory/SmallMemoryAllocator.h", "max_stars_repo_name": "osor-io/NGene", "max_stars_repo_head_hexsha": "c28887f233d3485b9e95fa3882a0333e4180c655", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-05-14T14:57:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T04:00:41.000Z", "max_issues_repo_path": "NGene/src/memory/SmallMemoryAllocator.h", "max_issues_repo_name": "osor-io/NGene", "max_issues_repo_head_hexsha": "c28887f233d3485b9e95fa3882a0333e4180c655", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NGene/src/memory/SmallMemoryAllocator.h", "max_forks_repo_name": "osor-io/NGene", "max_forks_repo_head_hexsha": "c28887f233d3485b9e95fa3882a0333e4180c655", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-03-07T12:53:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-14T14:57:31.000Z", "avg_line_length": 22.5606060606, "max_line_length": 80, "alphanum_fraction": 0.7092008059, "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18952110964056457, "lm_q2_score": 0.032589745823072315, "lm_q1q2_score": 0.00617644479129262}}
{"text": "\n#pragma once\n\n#include <gsl/gsl>\n\n/*\n\tHelper class for reading structured binary data from a \n\tmemory stream.\n*/\nclass BinaryReader {\npublic:\n\n\texplicit BinaryReader(gsl::span<uint8_t> data) : mData(data) {}\n\n\ttemplate<typename T>\n\tT Read() {\n\t\tExpects(mData.size() >= sizeof(T));\n\t\tauto result{ *reinterpret_cast<T*>(&mData[0]) };\n\t\tmData = mData.subspan(sizeof(T));\n\t\treturn result;\n\t}\n\n\tstd::string ReadFixedString(size_t length) {\n\t\tExpects(mData.size() >= (int) length);\n\t\tstd::string result(length, '\\0');\n\t\tmemcpy(&result[0], &mData[0], length);\n\t\tresult.resize(result.length());\n\t\tmData = mData.subspan(length);\n\t\treturn result;\n\t}\n\n\tbool AtEnd() const {\n\t\treturn mData.size() == 0;\n\t}\n\nprivate:\n\tgsl::span<uint8_t> mData;\n};\n", "meta": {"hexsha": "7ab02719e299ad5d4927b33053f8379c261f6e03", "size": 735, "ext": "h", "lang": "C", "max_stars_repo_path": "Infrastructure/include/infrastructure/binaryreader.h", "max_stars_repo_name": "edoipi/TemplePlus", "max_stars_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 69.0, "max_stars_repo_stars_event_min_datetime": "2015-05-05T14:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T06:13:04.000Z", "max_issues_repo_path": "Infrastructure/include/infrastructure/binaryreader.h", "max_issues_repo_name": "edoipi/TemplePlus", "max_issues_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 457.0, "max_issues_repo_issues_event_min_datetime": "2015-05-01T22:07:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T02:19:10.000Z", "max_forks_repo_path": "Infrastructure/include/infrastructure/binaryreader.h", "max_forks_repo_name": "edoipi/TemplePlus", "max_forks_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2016-02-04T21:19:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T23:14:51.000Z", "avg_line_length": 18.8461538462, "max_line_length": 64, "alphanum_fraction": 0.6639455782, "num_tokens": 204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.19193277720287893, "lm_q2_score": 0.032100705443805444, "lm_q1q2_score": 0.0061611775460011535}}
{"text": "#pragma once\n\n#include \"Utils.h\"\n\n#include <algorithm>\n#include <array>\n#include <atomic>\n#include <deque>\n#include <functional>\n#include <initializer_list>\n#include <limits>\n#include <memory>\n#include <mutex>\n#include <set>\n#include <vector>\n\n#include <gsl/gsl>\n\nnamespace indexes::utils {\ntemplate <typename epoch_t, typename ReclaimedType,\n          int ReclamationThreshold = 1000, typename Enable = void>\nclass EpochManager;\n\n// Provides support for epoch based reclaimation.\ntemplate <typename epoch_t, typename ReclaimedType, int ReclamationThreshold>\nclass EpochManager<\n    epoch_t, ReclaimedType, ReclamationThreshold,\n    typename std::enable_if_t<\n        (ReclamationThreshold > 0) && std::is_integral_v<epoch_t> &&\n        !std::is_same_v<epoch_t, bool> && !std::is_same_v<epoch_t, char>>> {\n  // Calling thread must be registered by calling `RegisterThread` before using\n  // epoch based safe memory reclamation.\n\n  using ReclaimedPtrType = ReclaimedType *;\n\npublic:\n  // It is undefined behaviour to use epoch manager, without registering the\n  // thread. Returns false, if active registered thread count is more than\n  // `MAX_THREADS`. If returned false, thread is not registered.\n\n  // enter_epoch guarantees that all shared objects, accessed by the calling\n  // thread, after enter_epoch is called are safe.\n  // Recursive calls are allowed\n  inline void enter_epoch() {\n    auto &pd = m_local_epoch[ThreadRegistry::ThreadID()];\n\n    if (pd.nested_level == 0) {\n      pd.epoch.store(now(), std::memory_order_release);\n      std::atomic_thread_fence(std::memory_order_acquire);\n    }\n    pd.nested_level++;\n  }\n\n  // exit_epoch marks quiescent state of the calling thread, when nesting\n  // becomes 0.\n  // Enables reclaimation of objects retired before calling thread's epoch.\n  inline void exit_epoch() {\n    auto &pd = m_local_epoch[ThreadRegistry::ThreadID()];\n\n    pd.nested_level--;\n    if (pd.nested_level == 0)\n      pd.epoch.store(QUIESCENT_STATE, std::memory_order_release);\n  }\n\n  // Switch to new epoch and return old epoch\n  inline epoch_t switch_epoch() { return m_global_epoch++; }\n\n  // Returns current threads epoch\n  inline epoch_t my_epoch() {\n    return m_local_epoch[ThreadRegistry::ThreadID()].epoch.load(\n        std::memory_order_relaxed);\n  }\n\n  // Return current epoch\n  inline epoch_t now() const { return m_global_epoch; }\n\n  // retire objects and start a new epoch.\n  // Objects will be reclaimed at a suitable and safe epoch.\n  // When reclaimed `reclaimer` will be called for each reclaimed object.\n  void\n  retire_in_new_epoch(std::function<void(ReclaimedPtrType object)> reclaimer,\n                      gsl::span<ReclaimedPtrType> objects) {\n    retire(reclaimer, objects, switch_epoch());\n  }\n\n  inline void\n  retire_in_new_epoch(std::function<void(ReclaimedPtrType object)> reclaimer,\n                      ReclaimedPtrType object) {\n    retire_in_new_epoch(reclaimer, {&object, 1});\n  }\n\n  // retire objects in current (without starting new epoch) epoch.\n  // Objects will be reclaimed at a suitable and safe epoch.\n  // When reclaimed `reclaimer` will be called for each reclaimed object.\n  void retire_in_current_epoch(\n      std::function<void(ReclaimedPtrType object)> reclaimer,\n      gsl::span<ReclaimedPtrType> objects) {\n    retire(reclaimer, objects, now());\n  }\n\n  inline void retire_in_current_epoch(\n      std::function<void(ReclaimedPtrType object)> reclaimer,\n      ReclaimedPtrType object) {\n    retire_in_current_epoch(reclaimer, {&object, 1});\n  }\n\n  // Reclaim objects which are safe to reclaim.\n  // Returns # objects still not reclaimed (but retired).\n  // A long running thread using an epoch could prevent\n  // reclaimation of objects visible to that thread.\n  size_t do_reclaim() {\n    return reclaim_in_retire_list(m_retire_list[ThreadRegistry::ThreadID()],\n                                  get_min_used_epoch());\n  }\n\n  void reclaim_all() {\n    epoch_t min_used_epoch = get_min_used_epoch();\n\n    for (auto &retire_list : m_retire_list) {\n      reclaim_in_retire_list(retire_list, min_used_epoch);\n    }\n  }\n\n  // Getter/Setter for reclaimation threshold.\n  // # objects to collect before triggering reclaimation.\n  // A low value means possibly reduced peak memory consumption, but would less\n  // performance, because of frequent calls to `DoReclaim`.\n  void set_reclamation_threshold(int threshold) {\n    if (threshold > 0)\n      m_reclaimation_threshold = threshold;\n  }\n\n  int get_reclamation_threshold(int threshold) {\n    return m_reclaimation_threshold;\n  }\n\n  EpochManager()\n      : m_reclaimation_threshold{ReclamationThreshold}, m_global_epoch{0},\n        m_local_epoch(ThreadRegistry::MAX_THREADS),\n        m_retire_list(ThreadRegistry::MAX_THREADS) {}\n\n  EpochManager(const EpochManager &) = delete;\n  EpochManager(EpochManager &&) = delete;\n\nprivate:\n  class Retiree {\n  public:\n    Retiree(ReclaimedPtrType object,\n            std::function<void(ReclaimedPtrType object)> reclaimer,\n            epoch_t retired_epoch)\n        : m_object(object), m_retired_epoch(retired_epoch),\n          m_reclaimer(reclaimer) {}\n\n    // Can reclaim this object after the given `epoch`\n    bool can_reclaim(epoch_t epoch) const { return epoch > m_retired_epoch; }\n\n    void reclaim() { return m_reclaimer(m_object); }\n\n  private:\n    // Object to reclaim safely.\n    ReclaimedPtrType m_object;\n    // Epoch on which the object was retired.\n    epoch_t m_retired_epoch;\n    // Callback to call during reclaimation.\n    std::function<void(ReclaimedPtrType object)> m_reclaimer;\n  };\n\n  static size_t reclaim_in_retire_list(std::deque<Retiree> &retire_list,\n                                       epoch_t min_used_epoch) {\n    auto begin = std::begin(retire_list);\n    auto reclaim_upto = begin;\n\n    for (auto &retiree : retire_list) {\n      if (!retiree.can_reclaim(min_used_epoch))\n        break;\n\n      retiree.reclaim();\n      reclaim_upto++;\n    }\n\n    size_t num_reclaimed = reclaim_upto - begin;\n\n    if (num_reclaimed) {\n      retire_list.erase(begin, reclaim_upto);\n      retire_list.shrink_to_fit();\n    }\n\n    return retire_list.size();\n  }\n\n  epoch_t get_min_used_epoch() {\n    return std::min_element(std::begin(m_local_epoch),\n                            std::begin(m_local_epoch) +\n                                ThreadRegistry::MaxThreadID() + 1,\n                            [](const auto &a, const auto &b) {\n                              return a.epoch.load() < b.epoch.load();\n                            })\n        ->epoch;\n  }\n\n  void retire(std::function<void(ReclaimedPtrType object)> reclaimer,\n              gsl::span<ReclaimedPtrType> objects, epoch_t retired_epoch) {\n    auto &retire_list = m_retire_list[ThreadRegistry::ThreadID()];\n\n    for (auto object : objects)\n      retire_list.emplace_back(object, reclaimer, retired_epoch);\n\n    if (static_cast<int>(retire_list.size()) >= m_reclaimation_threshold)\n      do_reclaim();\n  }\n\n  // Reclaimation threshold. Default 1000 objects\n  std::atomic<int> m_reclaimation_threshold;\n\n  // Global epoch\n  std::atomic<epoch_t> m_global_epoch;\n\n  // Quiescent state\n  static constexpr epoch_t QUIESCENT_STATE =\n      std::numeric_limits<epoch_t>::max();\n\n  struct alignas(128) PrivateData {\n    std::atomic<epoch_t> epoch = QUIESCENT_STATE;\n    int nested_level = 0;\n  };\n\n  // Thread local epoch, denotes the epoch of each thread.\n  // Accessed using `slot` by each thread.\n  std::vector<PrivateData> m_local_epoch;\n\n  // Thread local retire list. Accessed using `slot` by each thread.\n  std::vector<std::deque<Retiree>> m_retire_list;\n};\n} // namespace indexes::utils\n", "meta": {"hexsha": "352397aa938d1d93e76d907acee4ec5552b24b08", "size": 7620, "ext": "h", "lang": "C", "max_stars_repo_path": "include/indexes/utils/EpochManager.h", "max_stars_repo_name": "harikrishnan94/InMemIndexes", "max_stars_repo_head_hexsha": "e4027ba2151be57a59034d04dba7d0f2a8e75fef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-07-31T04:06:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-27T20:03:10.000Z", "max_issues_repo_path": "include/indexes/utils/EpochManager.h", "max_issues_repo_name": "harikrishnan94/bwtree", "max_issues_repo_head_hexsha": "e4027ba2151be57a59034d04dba7d0f2a8e75fef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/indexes/utils/EpochManager.h", "max_forks_repo_name": "harikrishnan94/bwtree", "max_forks_repo_head_hexsha": "e4027ba2151be57a59034d04dba7d0f2a8e75fef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4255319149, "max_line_length": 79, "alphanum_fraction": 0.6902887139, "num_tokens": 1798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18010665528475028, "lm_q2_score": 0.034100422276653664, "lm_q1q2_score": 0.0061417130000456805}}
{"text": "#ifndef _RNG_INTERNAL_H\n#define _RNG_INTERNAL_H\n\n#include <gsl/gsl_rng.h>\n\nstruct _ccs_rng_data_s {\n\tconst gsl_rng_type *rng_type;\n\tgsl_rng            *rng;\n};\n\ntypedef struct _ccs_rng_data_s _ccs_rng_data_t;\n\nstruct _ccs_rng_ops_s {\n\t_ccs_object_ops_t obj_ops;\n};\ntypedef struct _ccs_rng_ops_s _ccs_rng_ops_t;\n\nstruct _ccs_rng_s {\n\t_ccs_object_internal_t obj;\n\t_ccs_rng_data_t *data;\n};\n\n#endif //_RNG_INTERNAL_H\n", "meta": {"hexsha": "c847e62cb17a5cf5c471b4fd4635e5579d55d49b", "size": 414, "ext": "h", "lang": "C", "max_stars_repo_path": "src/rng_internal.h", "max_stars_repo_name": "deephyper/CCS", "max_stars_repo_head_hexsha": "dd8c976eca2a510c995862cc5c871e81932f3ff4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-29T16:31:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T16:31:28.000Z", "max_issues_repo_path": "src/rng_internal.h", "max_issues_repo_name": "deephyper/CCS", "max_issues_repo_head_hexsha": "dd8c976eca2a510c995862cc5c871e81932f3ff4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-15T10:37:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-15T10:48:24.000Z", "max_forks_repo_path": "src/rng_internal.h", "max_forks_repo_name": "deephyper/CCS", "max_forks_repo_head_hexsha": "dd8c976eca2a510c995862cc5c871e81932f3ff4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-16T18:20:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-07T17:54:11.000Z", "avg_line_length": 17.25, "max_line_length": 47, "alphanum_fraction": 0.7826086957, "num_tokens": 127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.22541660542786957, "lm_q2_score": 0.02716923212646138, "lm_q1q2_score": 0.006124396078028743}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdarg.h>\n#include <math.h>\n\n#include <gsl/gsl_errno.h>\n\n#include \"ccl.h\"\n\n// Error handling policy: whether to exit on error (C default) or continue \n// (Python or other binding default)\nstatic CCLErrorPolicy _ccl_error_policy = CCL_ERROR_POLICY_EXIT;\n\n// Debug mode policy: whether to print error messages as they are raised. This \n// is useful for the Python wrapper, which normally allows errors to be \n// overwritten by the C code until control returns to Python. If debug mode is \n// switched on, the errors are always printed by the C code when they occur.\n// Setting the debug mode to warning allows ccl_raise_warning to print warnings\n// but keeps the behavior of ccl_raise_exception as if debug mode is set to off.\nstatic CCLDebugModePolicy _ccl_debug_mode_policy = CCL_DEBUG_MODE_WARNING;\n\n// Set error policy\nvoid ccl_set_error_policy(CCLErrorPolicy error_policy)\n{\n  _ccl_error_policy = error_policy;\n}\n\n// Set debug mode policy\nvoid ccl_set_debug_policy(CCLDebugModePolicy debug_policy)\n{\n    _ccl_debug_mode_policy = debug_policy;\n}\n\n// Convenience function to raise exceptions in an appropriate way\nvoid ccl_raise_exception(int err, const char* msg, ...)\n{  \n  char message[256];\n\n  va_list va;\n  va_start(va, msg);\n  vsnprintf(message, 250, msg, va);\n  va_end(va);\n\n  // Print error message and exit if fatal errors are enabled\n  if ((_ccl_error_policy == CCL_ERROR_POLICY_EXIT) && (err)) {\n    fprintf(stderr, \"ERROR %d: %s\\n\", err, message);\n    exit(1);\n  }\n  // Print error message and exit if debug output is enabled\n  else if ((_ccl_debug_mode_policy == CCL_DEBUG_MODE_ON) && (err)){\n    fprintf(stderr, \"ERROR %d: %s\\n\", err, message);\n  }\n}\n\n// Convenience function to handle warnings\nvoid ccl_raise_warning(int err, const char* msg, ...)\n{\n  char message[256];\n\n  va_list va;\n  va_start(va, msg);\n  vsnprintf(message, 250, msg, va);\n  va_end(va);\n\n  // For now just print warning to stderr if debug is enabled.\n  // TODO: Implement some kind of error stack that can be passed on to, e.g.,\n  // the python binding.\n  if( (_ccl_debug_mode_policy == CCL_DEBUG_MODE_ON) \n      || (_ccl_debug_mode_policy == CCL_DEBUG_MODE_WARNING) ) {\n    fprintf(stderr, \"WARNING: %s\\n\", message);\n  }\n}\n\n// Convenience function to handle warnings\nvoid ccl_raise_gsl_warning(int gslstatus, const char* msg, ...)\n{\n  char message[256];\n\n  va_list va;\n  va_start(va, msg);\n  vsnprintf(message, 250, msg, va);\n  va_end(va);\n\n  ccl_raise_warning(gslstatus, \"%s GSL error: %s\", message, gsl_strerror(gslstatus));\n  return;\n}\n\nvoid ccl_check_status(ccl_cosmology *cosmo, int * status)\n{\n\t\n  switch (*status) {\n  case 0: // all good, nothing to do\n    return;\n  case CCL_ERROR_LINSPACE:\t// spacing allocation error, always terminate\t\t\n    ccl_raise_exception(*status, cosmo->status_message);\n  case CCL_ERROR_SPLINE:\t// spline allocation error, always terminate\t\n    ccl_raise_exception(*status, cosmo->status_message);\n  case CCL_ERROR_COMPUTECHI:\t// compute_chi error //RH\n    ccl_raise_exception(*status, cosmo->status_message);\n  case CCL_ERROR_HMF_INTERP: // terminate if hmf definition not supported\n    ccl_raise_exception(*status, cosmo->status_message);\n  case CCL_ERROR_NU_INT: // error in getting the neutrino integral spline: exit. No status_message in cosmo because can't pass cosmology to the function.\n    ccl_raise_exception(*status, \"Error, in ccl_neutrinos.c. ccl_calculate_nu_phasespace_spline(): Error in setting neutrino phasespace spline.\");\n  case CCL_ERROR_NU_SOLVE: // error in converting Omeganuh2-> Mnu: exit. No status_message in cosmo because can't pass cosmology to the function.\n    ccl_raise_exception(*status, \"Error, in ccl_neutrinos.c. Omeganuh2_to_Mnu(): Root finding did not converge.\");\n    // TODO: Implement softer error handling, e.g. for integral convergence here\t\n  default: \n    ccl_raise_exception(*status, cosmo->status_message);\n  }\n}\n\n/* ------- ROUTINE: ccl_check_status_nocosmo ------\n   INPUTS: pointer to a status integer\n   TASK: Perform a check on status for the case where it is not possible to have a cosmology object where the status check is required.\n*/\nvoid ccl_check_status_nocosmo(int * status)\n{\n  switch (*status) {\n  case 0: // Nothing to do\n    return;\n  case CCL_ERROR_LINSPACE:\n    // Spacing allocation error, always terminate\n    ccl_raise_exception(*status, \"CCL_ERROR_LINSPACE: Spacing allocation error.\");\n  case CCL_ERROR_SPLINE:\n    // Spline allocation error, always terminate\n    ccl_raise_exception(*status, \"CCL_ERROR_SPLINE: Spline allocation error.\");\n  case CCL_ERROR_COMPUTECHI:\n    // Compute_chi error\n    ccl_raise_exception(*status, \n             \"CCL_ERROR_COMPUTECHI: Comoving distance chi computation failed.\");\n  case CCL_ERROR_HMF_INTERP:\n    // Terminate if hmf definition not supported\n    ccl_raise_exception(*status, \n          \"CCL_ERROR_HMF_INTERP: Halo mass function definition not supported.\");\n  case CCL_ERROR_NU_INT:\n    // Error in getting the neutrino integral spline: exit. No status_message \n    // in cosmo because can't pass cosmology to the function.\n    ccl_raise_exception(*status, \n      \"CCL_ERROR_NU_INT: Error getting the neutrino phase-space integral spline.\");\n  case CCL_ERROR_NU_SOLVE:\n    // Error in converting Omeganuh2-> Mnu: exit. No status_message in cosmo \n    // because can't pass cosmology to the function.\n    ccl_raise_exception(*status, \n                      \"CCL_ERROR_NU_SOLVE: Error converting Omeganuh2 -> Mnu.\");\n  case CCL_ERROR_MNU_UNPHYSICAL:\n    // Error in the sum of mnu or Omeganu passed for the hierarchy requested.\n\t  ccl_raise_exception(*status, \n      \"CCL_ERROR_MNU_UNPHYSICAL: Sum of neutrinos masses for this Omeganu value is incompatible with the requested mass hierarchy.\");\n  case CCL_ERROR_NOT_IMPLEMENTED: \n    ccl_raise_exception(*status, \n      \"CCL_ERROR_NOT_IMPLEMENTED: the type of m_nu specified is not supported.\");\n  default:\n    ccl_raise_exception(*status, \n             \"Unrecognized error code (see gsl_errno.h for error codes 1-32).\");\n  }\n}\n", "meta": {"hexsha": "e83167c2feec4367b86d32c61d1cd19ed6d48cbf", "size": 6061, "ext": "c", "lang": "C", "max_stars_repo_path": "src/ccl_error.c", "max_stars_repo_name": "Russell-Jones-OxPhys/CCL", "max_stars_repo_head_hexsha": "1cdc4ecb8ae6fb23806540b39799cc3317473e71", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ccl_error.c", "max_issues_repo_name": "Russell-Jones-OxPhys/CCL", "max_issues_repo_head_hexsha": "1cdc4ecb8ae6fb23806540b39799cc3317473e71", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ccl_error.c", "max_forks_repo_name": "Russell-Jones-OxPhys/CCL", "max_forks_repo_head_hexsha": "1cdc4ecb8ae6fb23806540b39799cc3317473e71", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.6050955414, "max_line_length": 153, "alphanum_fraction": 0.7346972447, "num_tokens": 1570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.17106117477479593, "lm_q2_score": 0.03567855344114697, "lm_q1q2_score": 0.006103215265907938}}
{"text": "#include <stdlib.h>\n#include <stdio.h>\n\n//#define VERY_VERBOSE\n\n#define MSG(x) { printf(x); fflush(stdout); }\n#define MSGF(x) { printf x ; fflush(stdout); }\n\n#include \"buffer.h\"\n\nstatic void test_buffer()\n{\n}\n\n#include \"array.h\"\n\nstatic void test_array()\n{\n\tint k;\n\tconst int * p;\n\tconst int * q;\n\tOLIO_ARRAY_STACK(st, int, 64);\n\tolio_array * hp;\n\n\tOLIO_ARRAY_ALLOC(hp, int, 0);\n\n\tprintf(\"[testing array...]\\n\"); fflush(stdout);\n\n\tMSGF((\"st %u\\n\", st->base.allocated));\n\tMSGF((\"hp %u\\n\", hp->base.allocated));\n\n#define ARRAY_COUNT 1000\n\n\tMSG(\"appending to arrays...\\n\");\n\tfor (k = 0; k < ARRAY_COUNT; k++) {\n\t\tolio_array_append(st, &k, 1);\n\t\tolio_array_append(hp, &k, 1);\n\t}\n\n\tMSG(\"prepending to arrays...\\n\");\n\tfor (k = 0; k < ARRAY_COUNT; k++) {\n\t\tolio_array_prepend(st, &k, 1);\n\t\tolio_array_prepend(hp, &k, 1);\n\t}\n\n\tMSG(\"inserting to arrays...\\n\");\n\tfor (k = 0; k <= ARRAY_COUNT * 2; k++) {\n\t\tolio_array_insert(st, k * 2, &k, 1);\n\t\tolio_array_insert(hp, k * 2, &k, 1);\n\t}\n\n\tMSG(\"checking array contents...\\n\");\n\tp = olio_array_contents(st);\n\tq = olio_array_contents(hp);\n\tfor (k = 0; k < ARRAY_COUNT; k++) {\n\t\tif (p[k * 2 + 1] != ARRAY_COUNT - 1 - k ||\n\t\t\tp[k * 2 + 1 + ARRAY_COUNT * 2] != k)\n\t\t\tMSG(\"ERROR: odd numbered stack item not as expected\\n\");\n\n\t\tif (p[k * 2] != k ||\n\t\t\tp[k * 2 + ARRAY_COUNT * 2] != k + ARRAY_COUNT)\n\t\t\tMSG(\"ERROR: even numbered stack item not as expected\\n\");\n\n\t\tif (q[k * 2 + 1] != ARRAY_COUNT - 1 - k ||\n\t\t\tq[k * 2 + 1 + ARRAY_COUNT * 2] != k)\n\t\t\tMSG(\"ERROR: odd numbered heap item not as expected\\n\");\n\n\t\tif (q[k * 2] != k ||\n\t\t\tq[k * 2 + ARRAY_COUNT * 2] != k + ARRAY_COUNT)\n\t\t\tMSG(\"ERROR: even numbered heap item not as expected\\n\");\n\t}\n\tif (p[ARRAY_COUNT * 4] != ARRAY_COUNT * 2) \n\t\tMSG(\"ERROR: last item in stack array not as expected\\n\");\n\tif (q[ARRAY_COUNT * 4] != ARRAY_COUNT * 2) \n\t\tMSG(\"ERROR: last item in heap array not as expected\\n\");\n\n#ifdef VERY_VERBOSE\n\tfor (k = 0; k < olio_array_length(st) ||\n\t\tk < olio_array_length(hp); k++) {\n\t\tMSGF((\"%i: st % 4i hp % 4i\\n\", k, \n\t\t\t(k < olio_array_length(st)) ? p[k] : -1,\n\t\t\t(k < olio_array_length(hp)) ? q[k] : -1));\n\t}\n#endif\n\n\tMSGF((\"st %p = %p\\n\", st->base.data, st->stack));\n\tMSGF((\"hp %p = %p\\n\", hp->base.data, hp->stack));\n\n\tMSG(\"freeing arrays...\\n\");\n\tolio_array_free(st);\n\tolio_array_free(hp);\n}\n\n#include \"string.h\"\n\nstatic void test_string()\n{\n}\n\n#include \"graph.h\"\n\nstatic void test_graph()\n{\n\tint rc;\n\tolio_graph g;\n\n\tprintf(\"[testing graph...]\\n\"); fflush(stdout);\n\n\tprintf(\"graph initialization...\\n\"); fflush(stdout);\n\tolio_graph_init(&g, 10);\n\t\n\tprintf(\"graph setting edges...\\n\"); fflush(stdout);\n\tolio_graph_set_edge(&g, 0, 1, 10);\n\tolio_graph_set_edge(&g, 1, 2, 10);\n\n\tprintf(\"graph testing cyclic...\\n\"); fflush(stdout);\n\trc = olio_graph_acyclic(&g);\n\tif (rc == 0) {\n\t\tprintf(\"ERROR: graph NOT acyclic\\n\"); fflush(stdout);\n\t}\n\n\tprintf(\"graph setting edges...\\n\"); fflush(stdout);\n\tolio_graph_set_edge(&g, 2, 0, 10);\n\n\tMSG(\"graph testing cyclic...\\n\");\n\trc = olio_graph_acyclic(&g);\n\tif (rc != 0) MSG(\"ERROR: graph NOT cyclic\\n\");\n\n\tMSG(\"freeing graph...\\n\");\n\tolio_graph_free(&g);\n}\n\n#include \"skiplist.h\"\n\nstatic void test_skiplist()\n{\n\tuint32_t test_data[] = {0xf, 0x436, 0x53547, 0x65, 0x54, 0x5654, 0x8756, 0x8767};\n\n\tolio_skiplist sk;\n\tint i;\n\n\tprintf(\"sizeof(entry) = %li\\n\", sizeof(olio_skiplist_entry));\n\tprintf(\"sizeof(block) = %li\\n\", sizeof(olio_skiplist_block));\n\tprintf(\"sizeof(skiplist) = %li\\n\", sizeof(olio_skiplist));\n\n\tolio_skiplist_init(&sk);\n\tprintf(\"adding...\\n\");\n\tfor (i = 0; i < sizeof(test_data) / sizeof(uint32_t); i++) {\n\t\tint rv = olio_skiplist_add(&sk, test_data[i], (void*) test_data[i]);\n\t\tprintf(\"k: 0x%x, rv: %i\\n\", test_data[i], rv);\n\t}\n\n\tprintf(\"searching...\\n\");\n\tfor (i = 0; i < sizeof(test_data) / sizeof(uint32_t); i++) {\n\t\tvoid * d = olio_skiplist_find(&sk, test_data[i]);\n\t\tprintf(\"k: 0x%x, data: %p\\n\", test_data[i], d);\n\t}\n\n\tolio_skiplist_display(&sk);\n\n\tprintf(\"freeing...\\n\");\n\tolio_skiplist_free(&sk);\n\n\tolio_skiplist_display(&sk);\n\n\tolio_skiplist_init(&sk);\n\tprintf(\"adding...\\n\");\n\tfor (i = 0; i < sizeof(test_data) / sizeof(uint32_t); i++) {\n\t\tint rv = olio_skiplist_add(&sk, test_data[i], (void*) test_data[i]);\n\t\tprintf(\"k: 0x%x, rv: %i\\n\", test_data[i], rv);\n\t}\n\t\n\tprintf(\"deleting...\\n\");\n\tfor (i = 0; i < sizeof(test_data) / sizeof(uint32_t); i++) {\n\t\tvoid * d;\n\t\tint rv = olio_skiplist_remove(&sk, test_data[i], &d);\n\t\tprintf(\"k: 0x%x, rv: %i, data: %p\\n\", test_data[i], rv, d);\n\t\tolio_skiplist_display(&sk);\n\t}\n\n\tprintf(\"freeing...\\n\");\n\tolio_skiplist_free(&sk);\n\n\tolio_skiplist_display(&sk);\n}\n\n#include \"error.h\"\n\nstatic void test_error()\n{\n}\n\n#ifdef HAVE_GSL\n#include <gsl/gsl_rng.h>\n#include \"random.h\"\n\ngsl_rng * gsl;\nolio_random olio;\n\nstatic void test_random()\n{\n    uint32_t seed;\n    uint32_t a, b;\n    long i;\n    \n    printf(\"[testing random...]\\n\"); fflush(stdout);\n    \n    gsl = gsl_rng_alloc(gsl_rng_mt19937);\n    \n    //for (seed = 0; seed < 1000; seed++) \n    {\n\tseed = 0;\n\tgsl_rng_set(gsl, 0);\n\tolio_random_set_seed(&olio, 4357);\n\tfor (i = 0; i < 10000; i++) {\n\t    a = gsl_rng_uniform_int(gsl, 0xffffffff);\n\t    b = olio_random_integer(&olio);\n\t    if (a != b) {\n\t\tprintf(\"mismatch\\n\");\n\t    }\n\t}\n    }\n    gsl_rng_free(gsl);\n}\n#else\nstatic void test_random() {}\n#endif\n\n#include \"phash.h\"\n#include \"hash.h\"\n\nstatic void test_hashes()\n{\n    unsigned long i;\n    const char * s[] = {\n\t\"alpha\", \"beta\", \"gamma\", \"delta\", \"epsilon\",\n\t\"lamda\", \"mu\", \"nu\", \"omicron\", \"pi\", \"phi\", \"psi\",\n\t\"tau\", \"theta\", \"zeta\", NULL\n    };\n    \n    olio_phash_build m;\n    int rc;\n  \n    printf(\"[testing hashes...]\\n\"); fflush(stdout);\n\n    rc = olio_phash_init(&m, NULL);\n    if (rc == -1) {\n\tprintf(\"error, aborting\\n\");\n\texit(1);\n    }\n    \n    for (i = 0; s[i] != NULL; i++) {\n\trc = olio_phash_add_entry(&m, s[i], strlen(s[i]), i * 1000);\n\tif (rc == -1) {\n\t    printf(\"error, aborting\\n\");\n\t    exit(1);\n\t}\n    }\n    \n    rc = olio_phash_generate(&m, 1000, 1);\n    if (rc < 0) {\n\tprintf(\"error, aborting\\n\");\n\texit(1);\n    }\n    if (rc > 0) {\n\tprintf(\"failed to generate with attempt/extra limits\\n\");\n\texit(1);\n    }\t\n    \n    printf(\"phash generated:\\n\");\n    printf(\"A hash: %08x\\nB hash: %08x\\nG size: %u\\n\",\n\t   m.phash->a_hash_seed, m.phash->b_hash_seed, \n\t   m.phash->g_table_size);\n    \n    printf(\"{ \");\n    for (i = 0; i < m.phash->g_table_size; i++) {\n\tint16_t * gv = (int16_t *) m.phash->data; \n\tprintf(\"%i, \", gv[i]);\n    }\n    printf(\"}\\n\");\n    \n    for (i = 0; s[i] != NULL; i++) {\n\tint32_t v = olio_phash_value(m.phash,\n\t\t\t\t     s[i], strlen(s[i]));\n\tprintf(\" %s -> %li\\n\",\n\t       s[i], v);\n    }\n    \n    olio_phash_free(&m);\n}\n\n#include \"varint.h\"\n\nstatic void test_varint_sub(uint32_t x, uint8_t bytes_expected)\n{\n    uint32_t a;\n    uint8_t storage[5];\n    uint8_t bytes_set, bytes_get;\n    uint8_t i;\n\n    bytes_set = olio_varint_set(x, storage);\n    a = olio_varint_get(storage, &bytes_get);\n\n    if (a != x || bytes_set != bytes_get || bytes_set != bytes_expected) \n    {\n\tprintf(\"x = %lu\\n(%u) 0x\", x, bytes_set);\n\tfor (i = 0; i < bytes_set; i++)\n\t    printf(\"%02x\", storage[i]);\n\tprintf(\"\\na = %lu\\n(%u)\\n\\n\", a, bytes_get);\n    }\n}\n\n\nstatic void test_varint()\n{\n    printf(\"[testing varint...]\\n\"); fflush(stdout);\n\n    test_varint_sub(0, 1);\n    test_varint_sub(1,1);\n    test_varint_sub(127, 1);\n    test_varint_sub(200, 2);\n    test_varint_sub(32000, 3);\n    test_varint_sub(32000000, 3);\n    test_varint_sub(100000000, 4);\n    test_varint_sub(400000000, 5);\n    test_varint_sub(0, 1);\n    test_varint_sub(1, 1);\n}\n\nint main(int argv, char ** argc)\n{\n\ttest_buffer();\n\ttest_array();\n\ttest_string();\n\ttest_graph();\n\ttest_skiplist();\n\ttest_error();\n\ttest_random();\n\ttest_hashes();\n\ttest_varint();\n}\n", "meta": {"hexsha": "69cc9847e81a8be46bd9fcbdfc7b61508169f93e", "size": 7700, "ext": "c", "lang": "C", "max_stars_repo_path": "test.c", "max_stars_repo_name": "jabr/olio", "max_stars_repo_head_hexsha": "e237053d4026e9e78564f1ad354143c8dd6b4b69", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-11-25T05:53:52.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-25T05:53:52.000Z", "max_issues_repo_path": "test.c", "max_issues_repo_name": "jabr/olio", "max_issues_repo_head_hexsha": "e237053d4026e9e78564f1ad354143c8dd6b4b69", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test.c", "max_forks_repo_name": "jabr/olio", "max_forks_repo_head_hexsha": "e237053d4026e9e78564f1ad354143c8dd6b4b69", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.514619883, "max_line_length": 82, "alphanum_fraction": 0.598961039, "num_tokens": 2610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2909808539178129, "lm_q2_score": 0.0209642389830727, "lm_q1q2_score": 0.006100192161031596}}
{"text": "#ifndef _read_h_included_\n#define _read_h_included_\n\n#include <assert.h>\n#include <stdlib.h>\n#include <algorithm>\n#include <cctype>\n#include <fstream>\n#include <functional>\n#include <iostream>\n#include <map>\n#include <numeric>\n#include <set>\n#include <sstream>\n#include <vector>\n#include <sstream>\n#include <string>\n#include <boost/config.hpp>\n#include <boost/foreach.hpp>\n#include <boost/random.hpp>\n#include <boost/shared_ptr.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include <jsc/bioinfo/gene_anno.hpp>\n#include <jsc/util/log.hpp>\n\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n\n#include \"splicing_graph.h\"\n#include \"accessible_read_starts.h\"\n\nusing namespace std;\nusing namespace boost;\nusing namespace boost::numeric;\nusing namespace jsc::bioinfo;\nusing namespace jsc::util;\n\nusing boost::shared_ptr;\n\n// returns the index (in the isoform) of the first matching exon in the isoform\nlong is_connected_exons_compatible_with_isoform(\n\t\tvector<unsigned long> const & exon_indices,\n\t\tvector<unsigned long> const & iso_exon_indices) {\n\tvector<unsigned long>::const_iterator itr, itr2;\n\titr = exon_indices.begin();\n\titr2 = iso_exon_indices.begin();\n\tbool is_compatible = false;\n\tbool found_first_match = false;\n\tlong first_match_idx = 0;\n\twhile (itr != exon_indices.end()) {\n\t\tif (itr2 == iso_exon_indices.end()) {\n\t\t\tis_compatible = false;\n\t\t\tbreak;\n\t\t}\n\t\tif (*itr != *itr2) {\n\t\t\tif (!found_first_match) {\n\t\t\t\titr2++;\n\t\t\t\tfirst_match_idx++;\n\t\t\t} else {\n\t\t\t\tis_compatible = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} else {\n\t\t\tif (!found_first_match) {\n\t\t\t\tfound_first_match = true;\n\t\t\t\tis_compatible = true;\n\t\t\t\titr++;\n\t\t\t\titr2++;\n\t\t\t} else {\n\t\t\t\titr++;\n\t\t\t\titr2++;\n\t\t\t}\n\t\t}\n\t}\n\treturn (is_compatible ? first_match_idx : -1);\n}\n\nclass ReadType {\n\tpublic:\n\t\tstatic const int LONG_READ = 0;\n\t\tstatic const int MEDIUM_READ = 1;\n\t\tstatic const int SHORT_READ = 2;\n\t\tstatic const int SHORT_CONTIG = 3;\n\t\tstatic const int CONTIG = 4;\n\t\tstatic const int LONG_READ_PE = 5;\n\t\tstatic const int MEDIUM_READ_PE = 6;\n\t\tstatic const int SHORT_READ_PE = 7;\n\t\tstatic const string TYPES[];\n};\nconst string ReadType::TYPES[] = {\"LONG_READ\", \"MEDIUM_READ\", \"SHORT_READ\", \"SHORT_CONTIG\", \"CONTIG\", \"LONG_READ_PE\", \"MEDIUM_READ_PE\", \"SHORT_READ_PE\"};\n\nclass Read {\n\tpublic:\n\t\tstring read_type;\n\t\tvector<unsigned long> exon_indices;\n\t\tunsigned long start_at_first_exon;\n\t\tunsigned long end_at_last_exon;\n\n\t\tRead(shared_ptr<AccessibleReadStarts> const & ars\n\t\t\t\t= shared_ptr<AccessibleReadStarts>())\n\t\t\t: ars(ars) {\n\t\t\tread_length = 0;\n\t\t\texpected_read_length = 0;\n\t\t\tread_type = \"General read\";\n\t\t}\n\n\t\tunsigned long get_num_isoforms() const {\n\t\t\treturn ars->get_num_isoforms();\n\t\t}\n\n\t\tunsigned long get_read_length() const {\n\t\t\treturn read_length;\n\t\t}\n\n\t\tshared_ptr<AccessibleReadStarts> get_ARS() const {\n\t\t\treturn ars;\n\t\t}\n\n\t\tvirtual unsigned long get_read_span() const {\n\t\t\treturn read_length;\n\t\t}\n\n\t\tunsigned long get_expected_read_length() const {\n\t\t\treturn expected_read_length;\n\t\t}\n\n\t\tvirtual unsigned long get_expected_read_span() const {\n\t\t\treturn expected_read_length;\n\t\t}\n\n\t\tvirtual bool is_compatible_with_iso(\n\t\t\t\tunsigned long const & iso_idx) const = 0;\n\n\t\tvirtual void build(\n\t\t\t\tinterval_list<long> const & read_il,\n\t\t\t\tSetExonp const & exonps,\n\t\t\t\tinterval_list<long> const & read_il2 = interval_list<long>()) = 0;\n\n\t\t/// Generates a read from an isoform.\n\t\t//\n\t\t/// The start position of the read in the isoform is either\n\t\t/// determined by \\a fixed_read_start or chosen randomly\n\t\t/// according to the actual type of the read.\n\t\t//\n\t\t/// \\param[in] iso_idx\t\t\t\t\t\t\tindex of the isoform from which\n\t\t///\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tthe read will be generated.\n\t\t///\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\texons in the corresponding gene.\n\t\t/// \\param[in] fixed_read_start\t\t\tWhen >= 0, specifies the start\n\t\t///\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tposition (in the isoform) of the\n\t\t///\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tread to be generated.\n\t\t///\t\\returns\tThe actual start position (in the isoform)\n\t\t///\t\t\t\t\t\tof the generated read.\n\t\tvirtual unsigned long generate_read(\n\t\t\t\tunsigned long const & iso_idx,\n\t\t\t\tlong fixed_read_start = -1) = 0;\n\n\t\tvirtual double prob_generated_by_iso(\n\t\t\t\tunsigned long const & iso_idx) const = 0;\n\n\t\tvirtual string to_string() const = 0;\n\n\t\tvirtual ~Read() {}\n\n\tprotected:\n\t\tshared_ptr<AccessibleReadStarts> ars;\n\t\tunsigned long read_length;\n\t\tunsigned long expected_read_length;\n};\n\nostream& operator << (ostream& os, Read const & r) {\n\tos << r.to_string();\n\treturn os;\n};\n\ntypedef shared_ptr<Read> Read_ptr;\n\nclass Read_stats {\n\tpublic:\n\t\tstatic const unsigned long medium_single_expected_read_length = 250;\n\t\tstatic const double medium_cost_per_bp = 7E-5;\n\t\tstatic const unsigned long short_single_expected_read_length = 30;\n\t\tstatic const unsigned long short_paired_expected_insert_size = 300;\n\t\tstatic const double short_cost_per_bp = 7E-6;\n};\n\nclass Read_single : public Read {\n\tpublic:\n\t\tRead_single(shared_ptr<AccessibleReadStarts> ars\n\t\t\t\t= shared_ptr<AccessibleReadStarts>())\n\t\t\t: Read(ars)\t{\n\t\t\trng = NULL;\n\t\t\tread_type = \"General single read\";\n\t\t}\n\n\t\tvirtual bool is_compatible_with_iso(\n\t\t\t\tunsigned long const & iso_idx) const {\n\t\t\treturn (is_connected_exons_compatible_with_isoform(\n\t\t\t\t\t\texon_indices, ars->iso_exon_indices[iso_idx]) >= 0);\n\t\t}\n\n\t\tvirtual void build(\n\t\t\t\tinterval_list<long> const & read_il,\n\t\t\t\tSetExonp const & exonps,\n\t\t\t\tinterval_list<long> const & read_il2 = interval_list<long>()) {\n\t\t\tL_(debug2) << \"Read::build\";\n\t\t\tunsigned long matching_length = 0;\n\t\t\tset<unsigned long> index_set;\n\t\t\texon_indices.clear();\n\t\t\tstart_at_first_exon = end_at_last_exon = 0;\n\t\t\tbool found_start = false;\n\t\t\tunsigned long il_idx = 0;\n\t\t\tSetExonp::const_iterator itr = exonps.begin();\n\t\t\tlong cur_start, cur_end, cur_exon_start;\n\t\t\tcur_exon_start = 0;\n\t\t\tL_(debug2) << \"Read: \" << read_il;\n\t\t\tL_(debug2) << \"Exons: \" << exonps;\n\t\t\twhile (il_idx < read_il.get_num_intervals()) {\n\t\t\t\tcur_start = read_il.get_starts()[il_idx];\n\t\t\t\tcur_end = read_il.get_ends()[il_idx];\n\t\t\t\tL_(debug2) << \"Current interval: [\" << cur_start << \",\"\n\t\t\t\t\t<< cur_end << \")\";\n\t\t\t\t// find all the exons that overlap with/contain the interval\n\t\t\t\twhile (itr != exonps.end() && (*itr)->start < cur_end) {\n\t\t\t\t\tL_(debug2) << \"Current exon: [\" << (*itr)->start << \",\"\n\t\t\t\t\t\t<< (*itr)->end << \")\";\n\t\t\t\t\tcur_exon_start = max(cur_exon_start, (*itr)->start);\n\t\t\t\t\tif (cur_start >= cur_exon_start && cur_start < (*itr)->end) {\n\t\t\t\t\t\tif (!found_start) {\n\t\t\t\t\t\t\tL_(debug2) << \"Found start\";\n\t\t\t\t\t\t\tfound_start = true;\n\t\t\t\t\t\t\tstart_at_first_exon = cur_start - (*itr)->start;\n\t\t\t\t\t\t} else if (cur_start > cur_exon_start) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t} \n\n\t\t\t\t\t\tL_(debug2) << \"Add exon #\" << distance(exonps.begin(), itr);\n\t\t\t\t\t\tindex_set.insert(distance(exonps.begin(), itr));\n\t\t\t\t\t\tcur_exon_start = min((*itr)->end, cur_end);\n\t\t\t\t\t\tmatching_length += cur_exon_start - cur_start;\n\n\t\t\t\t\t\tif (cur_end < (*itr)->end) {\n\t\t\t\t\t\t\tcur_start = cur_end;\n\t\t\t\t\t\t\tend_at_last_exon = cur_end - (*itr)->start;\n\t\t\t\t\t\t\t++il_idx;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t} else if (cur_end == (*itr)->end) {\n\t\t\t\t\t\t\tcur_start = cur_end;\n\t\t\t\t\t\t\tend_at_last_exon = cur_end - (*itr)->start;\n\t\t\t\t\t\t\t++il_idx;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcur_start = (*itr)->end;\n\t\t\t\t\t\t\tend_at_last_exon = (*itr)->end - (*itr)->start;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (cur_exon_start > (*itr)->start\n\t\t\t\t\t\t\t&& cur_exon_start < (*itr)->end) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\titr++;\n\t\t\t\t}\n\t\t\t\tif (cur_start == cur_end) {\n\t\t\t\t\tcontinue;\n\t\t\t\t} else {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tBOOST_FOREACH (unsigned long i, index_set) {\n\t\t\t\texon_indices.push_back(i);\n\t\t\t}\n\t\t\tread_length = matching_length;\n\t\t}\n\n\t\tvirtual unsigned long generate_read(\n\t\t\t\tunsigned long const & iso_idx,\n\t\t\t\tlong fixed_read_start = -1) {\n\t\t\tassert(rng != NULL || fixed_read_start >= 0);\n\t\t\tvector<unsigned long> const & iso_exon_indices =\n\t\t\t\tars->iso_exon_indices[iso_idx];\n\t\t\tvector<unsigned long> const & iso_exon_total_lengths =\n\t\t\t\tars->iso_exon_total_lengths[iso_idx];\n\n\t\t\texon_indices.clear();\n\t\t\tunsigned long read_start;\n\t\t\tif (fixed_read_start < 0) {\t// randomly generate a read start\n\t\t\t\tread_start = (unsigned long)(\n\t\t\t\t\t\tgsl_ran_flat(rng, 0,\n\t\t\t\t\t\t\tars->get_iso_ARS_total_length(iso_idx)));\n\t\t\t\tread_start = ars->ARStart2IsoStart(iso_idx, read_start);\n\t\t\t} else {\n\t\t\t\tread_start = fixed_read_start;\n\t\t\t}\n\n\t\t\tunsigned long read_end = read_start + get_expected_read_length();\n\t\t\tread_length = read_end - read_start;\n\t\t\tL_(debug2) << \"Generating read [\" << read_start\n\t\t\t\t<< \", \" << read_end << \") length=\" << read_length << \"bp\";\n\t\t\tvector<unsigned long>::const_iterator itr =\n\t\t\t\tupper_bound(iso_exon_total_lengths.begin(),\n\t\t\t\t\t\tiso_exon_total_lengths.end(),\n\t\t\t\t\t\tread_start);\n\t\t\tassert(itr != iso_exon_total_lengths.end());\n\t\t\tunsigned long start_exon_idx = distance(\n\t\t\t\t\tiso_exon_total_lengths.begin(), itr);\n\t\t\titr = lower_bound(iso_exon_total_lengths.begin(),\n\t\t\t\t\tiso_exon_total_lengths.end(),\n\t\t\t\t\tread_end);\n\t\t\tassert(itr != iso_exon_total_lengths.end());\n\t\t\tunsigned long end_exon_idx = distance(\n\t\t\t\t\tiso_exon_total_lengths.begin(), itr);\n\t\t\tL_(debug2) << \"Start exon: \"\n\t\t\t\t<< iso_exon_indices[start_exon_idx]\n\t\t\t\t<< \", end exon: \"\n\t\t\t\t<< iso_exon_indices[end_exon_idx];\n\t\t\tfor (unsigned long i = start_exon_idx;\n\t\t\t\t\ti <= end_exon_idx; ++i) {\n\t\t\t\texon_indices.push_back(iso_exon_indices[i]);\n\t\t\t}\n\t\t\tstart_at_first_exon = read_start -\n\t\t\t\t(start_exon_idx == 0 ?\n\t\t\t\t 0 : iso_exon_total_lengths[start_exon_idx - 1]);\n\t\t\tend_at_last_exon = read_end -\n\t\t\t\t(end_exon_idx == 0 ?\n\t\t\t\t 0 : iso_exon_total_lengths[end_exon_idx - 1]);\n\n\t\t\treturn read_start;\n\t\t}\n\n\t\tvirtual double prob_generated_by_iso(\n\t\t\t\tunsigned long const & iso_idx) const {\n\t\t\tdouble num_diff_reads = ars->get_iso_ARS_total_length(iso_idx);\n\t\t\tif (num_diff_reads <= 0) {\n\t\t\t\tL_(warning) << read_type << \": supported read length > isoform length\" << endl;\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tdouble prob = (double)1.0 / num_diff_reads;\n\t\t\treturn prob;\n\t\t}\n\n\t\tvirtual string to_string() const {\n\t\t\tstd::ostringstream os;\n\t\t\tos << \"[\" << read_type << \"] \"\n\t\t\t\t<< \"(Exons) \";\n\t\t\tBOOST_FOREACH(unsigned long const & idx, exon_indices) {\n\t\t\t\tos << idx << \",\";\n\t\t\t}\n\t\t\tos << \" (Start at first exon) \" << start_at_first_exon << \" \";\n\t\t\tos << \"(End at last exon) \" << end_at_last_exon;\n\t\t\treturn os.str();\n\t\t}\n\tprotected:\n\t\tgsl_rng * rng;\n};\n\nclass Read_medium_single : public Read_single {\n\tpublic:\n\t\tRead_medium_single(shared_ptr<AccessibleReadStarts> const & ars\n\t\t\t\t= shared_ptr<AccessibleReadStarts>(),\n\t\t\t\tgsl_rng * r = NULL,\n\t\t\t\tunsigned long expected_length =\n\t\t\t\tRead_stats::medium_single_expected_read_length)\n\t\t\t: Read_single(ars) {\n\t\t\trng = r;\n\t\t\texpected_read_length = expected_length;\n\t\t\tread_type = \"Medium single read\";\n\t\t}\n};\n\nclass Read_short_single : public Read_single {\n\tpublic:\n\t\tRead_short_single(shared_ptr<AccessibleReadStarts> const & ars\n\t\t\t\t= shared_ptr<AccessibleReadStarts>(),\n\t\t\t\tgsl_rng * r = NULL,\n\t\t\t\tunsigned long expected_length =\n\t\t\t\tRead_stats::short_single_expected_read_length)\n\t\t\t: Read_single(ars) {\n\t\t\trng = r;\n\t\t\texpected_read_length = expected_length;\n\t\t\tread_type = \"Short single read\";\n\t\t}\n};\n\nclass Read_paired: public Read {\n\tpublic:\n\t\tRead_single end1;\n\t\tRead_single end2;\n\t\tRead_single span;\n\n\t\tRead_paired(shared_ptr<AccessibleReadStarts> ars\n\t\t\t\t= shared_ptr<AccessibleReadStarts>(),\n\t\t\t\tdouble tolerance = 0)\n\t\t\t: Read(ars), tolerance(tolerance) {\n\t\t\tinsert_size = expected_insert_size = 0;\n\t\t\tread_type = \"General paired-end read\";\n\t\t\tend1 = Read_single(ars);\n\t\t\tend2 = Read_single(ars);\n\t\t\tspan = Read_single(ars);\n\t\t}\n\n\t\tunsigned long get_expected_insert_size() const {\n\t\t\treturn expected_insert_size;\n\t\t}\n\n\t\tvirtual unsigned long get_read_span() const {\n\t\t\treturn read_length + insert_size;\n\t\t}\n\n\t\tvirtual unsigned long get_expected_read_span() const {\n\t\t\treturn (end1.get_expected_read_length()\n\t\t\t\t+ end2.get_expected_read_length()\n\t\t\t\t+ expected_insert_size);\n\t\t}\n\n\t\tvirtual bool is_compatible_with_iso(\n\t\t\t\tunsigned long const & iso_idx) const {\n\t\t\tassert(end1.exon_indices.size() > 0\n\t\t\t\t\t&& end2.exon_indices.size() > 0);\n\t\t\tif (end1.is_compatible_with_iso(iso_idx)\n\t\t\t\t\t&& end2.is_compatible_with_iso(iso_idx)) {\n\t\t\t\tif (expected_insert_size == 0) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tvector<unsigned long> const & iso_exon_indices =\n\t\t\t\t\tars->iso_exon_indices[iso_idx];\n\t\t\t\tvector<unsigned long> const & exon_total_lengths =\n\t\t\t\t\tars->iso_exon_total_lengths[iso_idx];\n\n\t\t\t\tvector<unsigned long>::const_iterator itr;\n\t\t\t\tunsigned long end1_last_exon_idx = end1.exon_indices\n\t\t\t\t\t[end1.exon_indices.size() - 1];\n\t\t\t\titr = lower_bound(iso_exon_indices.begin(),\n\t\t\t\t\t\tiso_exon_indices.end(),\n\t\t\t\t\t\tend1_last_exon_idx);\n\t\t\t\tunsigned long exon_idx = distance(\n\t\t\t\t\t\tiso_exon_indices.begin(), itr);\n\t\t\t\tunsigned long end1_end =\n\t\t\t\t\t(exon_idx > 0 ? exon_total_lengths[exon_idx - 1] : 0)\n\t\t\t\t\t+ end1.end_at_last_exon;\n\t\t\t\tunsigned long end2_first_exon_idx = end2.exon_indices[0];\n\t\t\t\titr = lower_bound(iso_exon_indices.begin(),\n\t\t\t\t\t\tiso_exon_indices.end(),\n\t\t\t\t\t\tend2_first_exon_idx);\n\t\t\t\texon_idx = distance(iso_exon_indices.begin(), itr);\n\t\t\t\tunsigned long end2_start =\n\t\t\t\t\t(exon_idx > 0 ? exon_total_lengths[exon_idx - 1] : 0)\n\t\t\t\t\t+ end2.start_at_first_exon;\n\t\t\t\tdouble gap = end2_start - end1_end;\n\t\t\t\tdouble diff = gap / (double)(expected_insert_size);\n\t\t\t\tif (diff <= (1.0 + tolerance + epsilon)\n\t\t\t\t\t\t&& diff >= (1.0 - tolerance - epsilon)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\tvirtual double prob_generated_by_iso(\n\t\t\t\tunsigned long const & iso_idx) const {\n\t\t\tdouble num_diff_reads = ars->get_iso_ARS_total_length(iso_idx);\n\t\t\tif (num_diff_reads <= 0) {\n\t\t\t\tL_(warning) << read_type << \": supported paired-end read length (including insert) > isoform length\" << endl;\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tdouble prob = (double)1.0 / num_diff_reads;\n\t\t\treturn prob;\n\t\t}\n\n\t\tvirtual string to_string() const {\n\t\t\tstd::ostringstream os;\n\t\t\tos << \"[\" << read_type << \"]\"\n\t\t\t\t<< \" End #1: \" << end1.to_string()\n\t\t\t\t<< \"; End #2: \" << end2.to_string();\n\t\t\treturn os.str();\n\t\t}\n\n\t\tvirtual void build(\n\t\t\t\tinterval_list<long> const & read_il,\n\t\t\t\tSetExonp const & exonps,\n\t\t\t\tinterval_list<long> const & read_il2 = interval_list<long>()) {\n\t\t\tL_(debug2) << \"Read::build\";\n\t\t\tend1.build(read_il, exonps);\n\t\t\tend2.build(read_il2, exonps);\n\t\t\tread_length = end1.get_read_length() + end2.get_read_length();\n\t\t\t/// \\todo compute insert size and construct span, exon_indices, etc.\n\t\t}\n\n\t\tvirtual unsigned long generate_read(\n\t\t\t\tunsigned long const & iso_idx,\n\t\t\t\tlong fixed_read_start = -1) {\n\t\t\tassert(rng != NULL || fixed_read_start >= 0);\n\n\t\t\tunsigned long read_start;\n\t\t\tif (fixed_read_start < 0) {\t// randomly generate a read start\n\t\t\t\tread_start = (unsigned long)(\n\t\t\t\t\t\tgsl_ran_flat(rng, 0,\n\t\t\t\t\t\t\tars->get_iso_ARS_total_length(iso_idx)));\n\t\t\t\tread_start = ars->ARStart2IsoStart(iso_idx, read_start);\n\t\t\t} else {\n\t\t\t\tread_start = fixed_read_start;\n\t\t\t}\n\n\t\t\tunsigned long end1_start =\n\t\t\t\tend1.generate_read(iso_idx, read_start);\n\t\t\tunsigned long end2_start =\n\t\t\t\tend1_start + end1.get_read_length()\n\t\t\t\t+ expected_insert_size;\n\t\t\tend2.generate_read(iso_idx, end2_start);\n\t\t\tread_length = end1.get_read_length() + end2.get_read_length();\n\t\t\t\n\t\t\tspan.generate_read(iso_idx, read_start);\n\t\t\texon_indices = span.exon_indices;\n\t\t\tstart_at_first_exon = span.start_at_first_exon;\n\t\t\tend_at_last_exon = span.end_at_last_exon;\n\n\t\t\treturn end1_start;\n\t\t}\n\n\tprotected:\n\t\tunsigned long insert_size;\n\t\tunsigned long expected_insert_size;\n\t\tdouble tolerance;\n\t\tstatic const double epsilon = 1E-5;\n\t\tgsl_rng * rng;\n};\n\nvoid generate_reads(unsigned long const & num_reads,\n\t\tIsoforms const & iso,\n\t\tshared_ptr<Read> readp,\n\t\tgsl_rng * rng,\n\t\tublas::matrix<double> & m_delta_G,\n\t\tbool known_isoforms_only = false) {\n\tgsl_ran_discrete_t * discrete_g = gsl_ran_discrete_preproc(\n\t\t\tiso.num_known_isoforms, iso.known_iso_probs);\n\n\tfor (unsigned long i = 0; i < num_reads; ++i) {\n\t\tunsigned long iso_idx = gsl_ran_discrete(rng, discrete_g);\n\t\tL_(debug2) << \"Selected known isoform \" << iso_idx;\n\t\tif (!known_isoforms_only) {\n\t\t\tiso_idx = iso.known_iso_indices[iso_idx];\n\t\t}\n\t\treadp->generate_read(iso_idx);\n\t\tL_(debug2) << *readp;\n\t\tif (known_isoforms_only) {\n\t\t\tfor (unsigned long j = 0;\n\t\t\t\t\tj < iso.num_known_isoforms; ++j) {\n\t\t\t\tif (readp->is_compatible_with_iso(j)) {\n\t\t\t\t\tm_delta_G(i,j) = readp->prob_generated_by_iso(j);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tfor (unsigned long j = 0;\n\t\t\t\t\tj < iso.num_possible_isoforms; ++j) {\n\t\t\t\tif (readp->is_compatible_with_iso(j)) {\n\t\t\t\t\tm_delta_G(i,j) = readp->prob_generated_by_iso(j);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tgsl_ran_discrete_free(discrete_g);\n}\n\nclass Read_short_paired: public Read_paired {\n\tpublic:\n\t\tRead_short_paired(shared_ptr<AccessibleReadStarts> ars\n\t\t\t\t= shared_ptr<AccessibleReadStarts>(),\n\t\t\t\tgsl_rng * r = NULL,\n\t\t\t\tunsigned long expected_length =\n\t\t\t\t2 * Read_stats::short_single_expected_read_length,\n\t\t\t\tunsigned long expected_insert =\n\t\t\t\tRead_stats::short_paired_expected_insert_size,\n\t\t\t\tdouble tolerance = 0)\n\t\t\t: Read_paired(ars, tolerance) {\n\t\t\trng = r;\n\t\t\texpected_read_length = expected_length;\n\t\t\tinsert_size = expected_insert_size = expected_insert;\n\t\t\tread_type = \"Short paired-end read\";\n\t\t\tshared_ptr<AccessibleReadStarts> end_ars(\n\t\t\t\t\tnew AccessibleReadStarts(\n\t\t\t\t\t\tars->iso_exon_indices,\n\t\t\t\t\t\tars->iso_exon_total_lengths,\n\t\t\t\t\t\tars->exon_lengths,\n\t\t\t\t\t\texpected_length / 2));\n\t\t\tend1 = Read_short_single(end_ars, r, expected_length / 2);\n\t\t\tend2 = Read_short_single(end_ars, r, expected_length / 2);\n\t\t\tspan = Read_medium_single(ars, r, expected_length + expected_insert);\n\t\t}\n};\n\nvoid compute_iso_probs_EM_step(\n\t\tunsigned long num_possible_isoforms,\n\t\tvector<ublas::matrix<double> > const & m_delta_Gs,\n\t\tvector<double> const & old_theta,\n\t\tvector<double> & new_theta) {\n\tfor (unsigned k = 0; k < num_possible_isoforms; ++k) {\n\t\tdouble sum_zeta = 0;\n\t\tdouble num_total_reads = 0;\n\t\tBOOST_FOREACH (ublas::matrix<double> const & m_delta_G, m_delta_Gs) {\n\t\t\tunsigned long num_reads = m_delta_G.size1();\n\t\t\tnum_total_reads += (double)num_reads;\n\t\t\tfor (unsigned long i = 0; i < num_reads; ++i) {\n\t\t\t\tdouble sum_local_probs = 0;\n\t\t\t\tfor (unsigned k2 = 0; k2 < num_possible_isoforms; ++k2) {\n\t\t\t\t\tsum_local_probs += old_theta[k2] * m_delta_G(i, k2);\n\t\t\t\t}\n\t\t\t\tif (sum_local_probs > 0) {\n\t\t\t\t\tdouble local_prob = old_theta[k] * m_delta_G(i, k);\n\t\t\t\t\tif (local_prob > 0) {\n\t\t\t\t\t\tsum_zeta += local_prob / sum_local_probs;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tnew_theta[k] = sum_zeta / num_total_reads;\n\t}\n}\n\ndouble reads_log_likelihood(\n\t\tunsigned long num_possible_isoforms,\n\t\tvector<ublas::matrix<double> > const & m_delta_Gs,\n\t\tvector<double> const & theta) {\n\tdouble ll = 0;\n\tBOOST_FOREACH (ublas::matrix<double> const & m_delta_G, m_delta_Gs) {\n\t\tunsigned long num_reads = m_delta_G.size1();\n\t\tfor (unsigned long i = 0; i < num_reads; ++i) {\n\t\t\tdouble sum_local_probs = 0;\n\t\t\tfor (unsigned k = 0; k < num_possible_isoforms; ++k) {\n\t\t\t\tsum_local_probs += theta[k] * m_delta_G(i, k);\n\t\t\t}\n\t\t\tll += log(sum_local_probs);\n\t\t}\n\t}\n\treturn ll;\n}\n\nvoid compute_iso_probs_EM(\n\t\tunsigned long num_possible_isoforms,\n\t\tvector<ublas::matrix<double> > const & m_delta_Gs,\n\t\tvector<double> & theta) {\n\ttheta.resize(num_possible_isoforms,\n\t\t\t(double)1.0 / (double)num_possible_isoforms);\n\tdouble ll, old_ll;\n\tvector<double> old_theta;\n\tunsigned long count = 0;\n\tdo {\n\t\told_theta = theta;\n\t\told_ll = reads_log_likelihood(\n\t\t\t\tnum_possible_isoforms, m_delta_Gs, old_theta);\n\t\tcompute_iso_probs_EM_step(num_possible_isoforms,\n\t\t\t\tm_delta_Gs, old_theta, theta);\n\t\tll = reads_log_likelihood(\n\t\t\t\tnum_possible_isoforms, m_delta_Gs, theta);\n\t\tif (++count == 100) {\n\t\t\tL_(debug) << \"log likelihood: \" << old_ll << \" -> \" << ll;\n\t\t\tcount = 0;\n\t\t}\n\t} while (abs(1.0 - old_ll / ll) > 1E-6);\n}\n\nvoid err_known_iso_probs(Isoforms const & iso,\n\t\tvector<double> const & theta, double & abs_err,\n\t\tdouble & sse) {\n\tabs_err = sse = 0;\n\tfor (unsigned long i = 0; i < iso.num_known_isoforms; ++i) {\n\t\tabs_err += abs(iso.known_iso_probs[i]\n\t\t\t\t- theta[iso.known_iso_indices[i]]);\n\t\tsse += (iso.known_iso_probs[i] - theta[iso.known_iso_indices[i]]) *\n\t\t\t(iso.known_iso_probs[i] - theta[iso.known_iso_indices[i]]);\n\t}\n}\n\nvoid err_possible_iso_probs(Isoforms const & iso,\n\t\tvector<double> const & theta, double & abs_err,\n\t\tdouble & sse) {\n\tabs_err = sse = 0;\n\tfor (unsigned long i = 0; i < iso.num_possible_isoforms; ++i) {\n\t\tabs_err += theta[i];\n\t\tsse += theta[i] * theta[i];\n\t}\n\tfor (unsigned long i = 0; i < iso.num_known_isoforms; ++i) {\n\t\tabs_err -= theta[iso.known_iso_indices[i]];\n\t\tabs_err += abs(iso.known_iso_probs[i]\n\t\t\t\t- theta[iso.known_iso_indices[i]]);\n\t\tsse -= theta[iso.known_iso_indices[i]] * theta[iso.known_iso_indices[i]];\n\t\tsse += (iso.known_iso_probs[i] - theta[iso.known_iso_indices[i]]) *\n\t\t\t(iso.known_iso_probs[i] - theta[iso.known_iso_indices[i]]);\n\t}\n}\n\n#endif\n", "meta": {"hexsha": "a33b20e555e31e9ad4465f5bd4ebdbf1963065f7", "size": 20796, "ext": "h", "lang": "C", "max_stars_repo_path": "common/read.h", "max_stars_repo_name": "gersteinlab/LESSeq", "max_stars_repo_head_hexsha": "bfc0a9aae081682a176e26d9804b980999595f16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-06-19T21:14:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-15T03:04:41.000Z", "max_issues_repo_path": "common/read.h", "max_issues_repo_name": "gersteinlab/LESSeq", "max_issues_repo_head_hexsha": "bfc0a9aae081682a176e26d9804b980999595f16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-02-12T21:17:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-20T13:50:38.000Z", "max_forks_repo_path": "common/read.h", "max_forks_repo_name": "gersteinlab/LESSeq", "max_forks_repo_head_hexsha": "bfc0a9aae081682a176e26d9804b980999595f16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0086580087, "max_line_length": 153, "alphanum_fraction": 0.6779188305, "num_tokens": 5866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2689414213699951, "lm_q2_score": 0.0226291981792018, "lm_q1q2_score": 0.006085928722777837}}
{"text": "/* -----------------------------------------------------------------------------\n * Copyright 2021 Jonathan Haigh\n * SPDX-License-Identifier: MIT\n * ---------------------------------------------------------------------------*/\n\n#ifndef SQ_INCLUDE_GUARD_core_Primitive_inl_h_\n#define SQ_INCLUDE_GUARD_core_Primitive_inl_h_\n\n#include \"core/errors.h\"\n#include \"core/narrow.h\"\n#include \"core/typeutil.h\"\n\n#include <gsl/gsl>\n#include <iomanip>\n#include <sstream>\n#include <string_view>\n#include <type_traits>\n\nnamespace sq {\n\ntemplate <PrimitiveAlternative P> struct PrimitiveTypeName {};\n\ntemplate <> struct PrimitiveTypeName<PrimitiveString> {\n  static constexpr std::string_view value = \"PrimitiveString\";\n};\n\ntemplate <> struct PrimitiveTypeName<PrimitiveInt> {\n  static constexpr std::string_view value = \"PrimitiveInt\";\n};\n\ntemplate <> struct PrimitiveTypeName<PrimitiveFloat> {\n  static constexpr std::string_view value = \"PrimitiveFloat\";\n};\n\ntemplate <> struct PrimitiveTypeName<PrimitiveBool> {\n  static constexpr std::string_view value = \"PrimitiveBool\";\n};\n\ntemplate <> struct PrimitiveTypeName<PrimitiveNull> {\n  static constexpr std::string_view value = \"PrimitiveNull\";\n};\n\nconstexpr PrimitiveInt to_primitive_int(auto value, auto &&...format_args) {\n  return narrow<PrimitiveInt>(SQ_FWD(value), SQ_FWD(format_args)...);\n}\n\nconstexpr PrimitiveFloat to_primitive_float(auto value, auto &&...format_args) {\n  return narrow<PrimitiveFloat>(SQ_FWD(value), SQ_FWD(format_args)...);\n}\n\nnamespace detail {\n\nstruct PrimitiveToStrVisitor {\n  SQ_ND std::string operator()(const PrimitiveString &value) {\n    os_ << std::quoted(value);\n    return os_.str();\n  }\n\n  SQ_ND std::string operator()(PrimitiveBool value) {\n    os_ << std::boolalpha << value;\n    return os_.str();\n  }\n\n  SQ_ND std::string operator()(const PrimitiveAlternative auto &value) {\n    os_ << value;\n    return os_.str();\n  }\n\nprivate:\n  std::ostringstream os_;\n};\n\ntemplate <PrimitiveAlternative T> struct ConvertPrimitiveBase {\n  // We can always convert T to T\n  SQ_ND T operator()(const T &value) { return value; }\n\n  // By default, don't allow any other conversions\n  template <PrimitiveAlternative U> SQ_ND T operator()(SQ_MU const U &value) {\n    throw InvalidConversionError{primitive_type_name_v<U>,\n                                 primitive_type_name_v<T>};\n  }\n};\n\ntemplate <PrimitiveAlternative T>\nstruct ConvertPrimitive : ConvertPrimitiveBase<T> {\n  using ConvertPrimitiveBase<T>::operator();\n};\n\ntemplate <>\nstruct ConvertPrimitive<PrimitiveFloat> : ConvertPrimitiveBase<PrimitiveFloat> {\n  using ConvertPrimitiveBase<PrimitiveFloat>::operator();\n\n  // Allow PrimitiveInt -> PrimitiveFloat conversions\n  SQ_ND PrimitiveFloat operator()(const PrimitiveInt &value) {\n    return to_primitive_float(value);\n  }\n};\n\n} // namespace detail\n\nstd::string primitive_to_str(const PrimitiveAlternative auto &value) {\n  return detail::PrimitiveToStrVisitor{}(value);\n}\n\ntemplate <PrimitiveAlternative T> T convert_primitive(const Primitive &value) {\n  return std::visit(detail::ConvertPrimitive<T>{}, value);\n}\n\n} // namespace sq\n\n#endif // SQ_INCLUDE_GUARD_core_Primitive_inl_h_\n", "meta": {"hexsha": "5f42e6c36d7cec466d5935ea2ea71b39ed4c967d", "size": 3153, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/include/core/Primitive.inl.h", "max_stars_repo_name": "jonathanhaigh/sq", "max_stars_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-12T16:21:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-12T16:21:41.000Z", "max_issues_repo_path": "src/core/include/core/Primitive.inl.h", "max_issues_repo_name": "jonathanhaigh/sq", "max_issues_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 44.0, "max_issues_repo_issues_event_min_datetime": "2021-02-08T19:17:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-05T18:51:38.000Z", "max_forks_repo_path": "src/core/include/core/Primitive.inl.h", "max_forks_repo_name": "jonathanhaigh/sq", "max_forks_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1517857143, "max_line_length": 80, "alphanum_fraction": 0.7047256581, "num_tokens": 670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15817436862177234, "lm_q2_score": 0.03846619601410729, "lm_q1q2_score": 0.006084366267812757}}
{"text": "#if !defined(PETIGAPART_H)\n#define PETIGAPART_H\n\n#include <petsc.h>\n\nPETSC_EXTERN PetscErrorCode IGA_Partition(PetscInt,PetscInt,\n                                          PetscInt,const PetscInt[],\n                                          PetscInt[],PetscInt[]);\nPETSC_EXTERN PetscErrorCode IGA_Distribute(PetscInt,\n                                           const PetscInt[],const PetscInt[],\n                                           const PetscInt[],PetscInt[],PetscInt[]);\n\n#endif/*PETIGAPART_H*/\n", "meta": {"hexsha": "9083cb2e3368c5162612e98c8c3651e46c541b0a", "size": 504, "ext": "h", "lang": "C", "max_stars_repo_path": "src/petigapart.h", "max_stars_repo_name": "otherlab/petiga", "max_stars_repo_head_hexsha": "ce8c07de8511000ee6f1cbfd3fb90fda9cb31954", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-08-31T21:20:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T10:40:32.000Z", "max_issues_repo_path": "src/petigapart.h", "max_issues_repo_name": "otherlab/petiga", "max_issues_repo_head_hexsha": "ce8c07de8511000ee6f1cbfd3fb90fda9cb31954", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/petigapart.h", "max_forks_repo_name": "otherlab/petiga", "max_forks_repo_head_hexsha": "ce8c07de8511000ee6f1cbfd3fb90fda9cb31954", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-11-08T12:55:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-14T10:40:40.000Z", "avg_line_length": 36.0, "max_line_length": 83, "alphanum_fraction": 0.5238095238, "num_tokens": 101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.18952107301879198, "lm_q2_score": 0.03210070961065096, "lm_q1q2_score": 0.006083760930075218}}
{"text": "\n#pragma once\n\n#include <gsl/span>\n\n#include \"aas/aas_math.h\"\n\nnamespace aas {\n\n\tstruct AnimPlayerStream;\n\tclass AnimatedModel;\n\tstruct SkelAnim;\n\tstruct SkelAnimEvent;\n\tstruct SkelBoneState;\n\tclass IAnimEventHandler;\n\tclass Skeleton;\n\tstruct AnimEvent;\n\n\tclass AnimPlayer {\n\tpublic:\n\t\tAnimatedModel * ownerAnim;\n\t\tchar field_D;\n\t\tchar field_E;\n\t\tchar field_F;\n\t\tfloat weight; // 1.0 = Fully weighted, otherwise weighted with primary anims\n\t\tfloat fadingSpeed; // Velocity with which weight is being changed\n\t\tint eventHandlingDepth;\n\t\tAnimPlayer * nextRunningAnim;\n\t\tAnimPlayer * prevRunningAnim;\n\t\tconst SkelAnim * animation;\n\t\tint streamCount;\n\t\tAnimPlayerStream * streams[4];\n\t\tfloat streamFps[4]; // \"frames per drive unit\"\n\t\tint8_t streamVariationIndices[4]; // indices into streamVariationIds\n\t\tint8_t streamVariationIds[4];\n\t\tint8_t variationId[4];\n\t\tfloat currentTimeEvents;\n\t\tfloat currentTime;\n\t\tfloat duration;\n\t\tfloat frameRate;\n\t\tfloat distancePerSecond;\n\t\tstd::vector<AnimEvent> events;\n\t\tIAnimEventHandler* eventHandler;\n\tpublic:\n\n\t\tAnimPlayer();\n\t\t~AnimPlayer();\n\n\t\tvoid GetDistPerSec(float* distPerSec);\n\t\tvoid GetRotationPerSec(float* rotationPerSec);\n\t\tvoid AdvanceEvents(float timeChanged, float distanceChanged, float rotationChanged);\n\t\tvoid FadeInOrOut(float timeChanged);\n\t\tvoid method6(gsl::span<SkelBoneState> boneStateOut, float timeChanged, float distanceChanged, float rotationChanged);\n\t\tvoid SetTime(float time);\n\t\tfloat GetCurrentFrame();\n\t\tfloat method9();\n\t\tfloat method10();\n\t\tvoid EnterEventHandling();\n\t\tvoid LeaveEventHandling();\n\t\tint GetEventHandlingDepth();\n\n\t\tvoid Attach(AnimatedModel *owner, int animIdx, IAnimEventHandler *eventHandler);\n\t\tvoid Setup2(float a);\n\n\tprivate:\n\t\tvoid SetEvents(const AnimatedModel *owner, const SkelAnim *anim);\n\n\t};\n\n\tAnimPlayerStream * CreateAnimPlayerStream(Skeleton* skeleton);\n\n}\n", "meta": {"hexsha": "7ffe2196addf9d6b71f7951a4b993e3c86a23f33", "size": 1860, "ext": "h", "lang": "C", "max_stars_repo_path": "Infrastructure/src/aas/aas_anim_player.h", "max_stars_repo_name": "edoipi/TemplePlus", "max_stars_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 69.0, "max_stars_repo_stars_event_min_datetime": "2015-05-05T14:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T06:13:04.000Z", "max_issues_repo_path": "Infrastructure/src/aas/aas_anim_player.h", "max_issues_repo_name": "edoipi/TemplePlus", "max_issues_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 457.0, "max_issues_repo_issues_event_min_datetime": "2015-05-01T22:07:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T02:19:10.000Z", "max_forks_repo_path": "Infrastructure/src/aas/aas_anim_player.h", "max_forks_repo_name": "edoipi/TemplePlus", "max_forks_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2016-02-04T21:19:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T23:14:51.000Z", "avg_line_length": 25.4794520548, "max_line_length": 119, "alphanum_fraction": 0.7639784946, "num_tokens": 463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3998116550426623, "lm_q2_score": 0.015189050953364444, "lm_q1q2_score": 0.006072759600191966}}
{"text": "/* matrix/gsl_matrix_short.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#ifndef __GSL_MATRIX_SHORT_H__\n#define __GSL_MATRIX_SHORT_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_vector_short.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size1;\n  size_t size2;\n  size_t tda;\n  short * data;\n  gsl_block_short * block;\n  int owner;\n} gsl_matrix_short;\n\ntypedef struct\n{\n  gsl_matrix_short matrix;\n} _gsl_matrix_short_view;\n\ntypedef _gsl_matrix_short_view gsl_matrix_short_view;\n\ntypedef struct\n{\n  gsl_matrix_short matrix;\n} _gsl_matrix_short_const_view;\n\ntypedef const _gsl_matrix_short_const_view gsl_matrix_short_const_view;\n\n/* Allocation */\n\ngsl_matrix_short * \ngsl_matrix_short_alloc (const size_t n1, const size_t n2);\n\ngsl_matrix_short * \ngsl_matrix_short_calloc (const size_t n1, const size_t n2);\n\ngsl_matrix_short * \ngsl_matrix_short_alloc_from_block (gsl_block_short * b, \n                                   const size_t offset, \n                                   const size_t n1, \n                                   const size_t n2, \n                                   const size_t d2);\n\ngsl_matrix_short * \ngsl_matrix_short_alloc_from_matrix (gsl_matrix_short * m,\n                                    const size_t k1, \n                                    const size_t k2,\n                                    const size_t n1, \n                                    const size_t n2);\n\ngsl_vector_short * \ngsl_vector_short_alloc_row_from_matrix (gsl_matrix_short * m,\n                                        const size_t i);\n\ngsl_vector_short * \ngsl_vector_short_alloc_col_from_matrix (gsl_matrix_short * m,\n                                        const size_t j);\n\nvoid gsl_matrix_short_free (gsl_matrix_short * m);\n\n/* Views */\n\n_gsl_matrix_short_view \ngsl_matrix_short_submatrix (gsl_matrix_short * m, \n                            const size_t i, const size_t j, \n                            const size_t n1, const size_t n2);\n\n_gsl_vector_short_view \ngsl_matrix_short_row (gsl_matrix_short * m, const size_t i);\n\n_gsl_vector_short_view \ngsl_matrix_short_column (gsl_matrix_short * m, const size_t j);\n\n_gsl_vector_short_view \ngsl_matrix_short_diagonal (gsl_matrix_short * m);\n\n_gsl_vector_short_view \ngsl_matrix_short_subdiagonal (gsl_matrix_short * m, const size_t k);\n\n_gsl_vector_short_view \ngsl_matrix_short_superdiagonal (gsl_matrix_short * m, const size_t k);\n\n_gsl_matrix_short_view\ngsl_matrix_short_view_array (short * base,\n                             const size_t n1, \n                             const size_t n2);\n\n_gsl_matrix_short_view\ngsl_matrix_short_view_array_with_tda (short * base, \n                                      const size_t n1, \n                                      const size_t n2,\n                                      const size_t tda);\n\n\n_gsl_matrix_short_view\ngsl_matrix_short_view_vector (gsl_vector_short * v,\n                              const size_t n1, \n                              const size_t n2);\n\n_gsl_matrix_short_view\ngsl_matrix_short_view_vector_with_tda (gsl_vector_short * v,\n                                       const size_t n1, \n                                       const size_t n2,\n                                       const size_t tda);\n\n\n_gsl_matrix_short_const_view \ngsl_matrix_short_const_submatrix (const gsl_matrix_short * m, \n                                  const size_t i, const size_t j, \n                                  const size_t n1, const size_t n2);\n\n_gsl_vector_short_const_view \ngsl_matrix_short_const_row (const gsl_matrix_short * m, \n                            const size_t i);\n\n_gsl_vector_short_const_view \ngsl_matrix_short_const_column (const gsl_matrix_short * m, \n                               const size_t j);\n\n_gsl_vector_short_const_view\ngsl_matrix_short_const_diagonal (const gsl_matrix_short * m);\n\n_gsl_vector_short_const_view \ngsl_matrix_short_const_subdiagonal (const gsl_matrix_short * m, \n                                    const size_t k);\n\n_gsl_vector_short_const_view \ngsl_matrix_short_const_superdiagonal (const gsl_matrix_short * m, \n                                      const size_t k);\n\n_gsl_matrix_short_const_view\ngsl_matrix_short_const_view_array (const short * base,\n                                   const size_t n1, \n                                   const size_t n2);\n\n_gsl_matrix_short_const_view\ngsl_matrix_short_const_view_array_with_tda (const short * base, \n                                            const size_t n1, \n                                            const size_t n2,\n                                            const size_t tda);\n\n_gsl_matrix_short_const_view\ngsl_matrix_short_const_view_vector (const gsl_vector_short * v,\n                                    const size_t n1, \n                                    const size_t n2);\n\n_gsl_matrix_short_const_view\ngsl_matrix_short_const_view_vector_with_tda (const gsl_vector_short * v,\n                                             const size_t n1, \n                                             const size_t n2,\n                                             const size_t tda);\n\n/* Operations */\n\nshort   gsl_matrix_short_get(const gsl_matrix_short * m, const size_t i, const size_t j);\nvoid    gsl_matrix_short_set(gsl_matrix_short * m, const size_t i, const size_t j, const short x);\n\nshort * gsl_matrix_short_ptr(gsl_matrix_short * m, const size_t i, const size_t j);\nconst short * gsl_matrix_short_const_ptr(const gsl_matrix_short * m, const size_t i, const size_t j);\n\nvoid gsl_matrix_short_set_zero (gsl_matrix_short * m);\nvoid gsl_matrix_short_set_identity (gsl_matrix_short * m);\nvoid gsl_matrix_short_set_all (gsl_matrix_short * m, short x);\n\nint gsl_matrix_short_fread (FILE * stream, gsl_matrix_short * m) ;\nint gsl_matrix_short_fwrite (FILE * stream, const gsl_matrix_short * m) ;\nint gsl_matrix_short_fscanf (FILE * stream, gsl_matrix_short * m);\nint gsl_matrix_short_fprintf (FILE * stream, const gsl_matrix_short * m, const char * format);\n \nint gsl_matrix_short_memcpy(gsl_matrix_short * dest, const gsl_matrix_short * src);\nint gsl_matrix_short_swap(gsl_matrix_short * m1, const gsl_matrix_short * m2);\n\nint gsl_matrix_short_swap_rows(gsl_matrix_short * m, const size_t i, const size_t j);\nint gsl_matrix_short_swap_columns(gsl_matrix_short * m, const size_t i, const size_t j);\nint gsl_matrix_short_swap_rowcol(gsl_matrix_short * m, const size_t i, const size_t j);\nint gsl_matrix_short_transpose (gsl_matrix_short * m);\nint gsl_matrix_short_transpose_memcpy (gsl_matrix_short * dest, const gsl_matrix_short * src);\n\nshort gsl_matrix_short_max (const gsl_matrix_short * m);\nshort gsl_matrix_short_min (const gsl_matrix_short * m);\nvoid gsl_matrix_short_minmax (const gsl_matrix_short * m, short * min_out, short * max_out);\n\nvoid gsl_matrix_short_max_index (const gsl_matrix_short * m, size_t * imax, size_t *jmax);\nvoid gsl_matrix_short_min_index (const gsl_matrix_short * m, size_t * imin, size_t *jmin);\nvoid gsl_matrix_short_minmax_index (const gsl_matrix_short * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);\n\nint gsl_matrix_short_isnull (const gsl_matrix_short * m);\n\nint gsl_matrix_short_add (gsl_matrix_short * a, const gsl_matrix_short * b);\nint gsl_matrix_short_sub (gsl_matrix_short * a, const gsl_matrix_short * b);\nint gsl_matrix_short_mul_elements (gsl_matrix_short * a, const gsl_matrix_short * b);\nint gsl_matrix_short_div_elements (gsl_matrix_short * a, const gsl_matrix_short * b);\nint gsl_matrix_short_scale (gsl_matrix_short * a, const double x);\nint gsl_matrix_short_add_constant (gsl_matrix_short * a, const double x);\n\n/***********************************************************************/\n/* The functions below are obsolete                                    */\n/***********************************************************************/\nint gsl_matrix_short_get_row(gsl_vector_short * v, const gsl_matrix_short * m, const size_t i);\nint gsl_matrix_short_get_col(gsl_vector_short * v, const gsl_matrix_short * m, const size_t j);\nint gsl_matrix_short_set_row(gsl_matrix_short * m, const size_t i, const gsl_vector_short * v);\nint gsl_matrix_short_set_col(gsl_matrix_short * m, const size_t j, const gsl_vector_short * v);\n\nextern int gsl_check_range ;\n\n/* inline functions if you are using GCC */\n\n#ifdef HAVE_INLINE\nextern inline \nshort\ngsl_matrix_short_get(const gsl_matrix_short * m, const size_t i, const size_t j)\n{\n#ifndef GSL_RANGE_CHECK_OFF\n  if (i >= m->size1)\n    {\n      GSL_ERROR_VAL(\"first index out of range\", GSL_EINVAL, 0) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_VAL(\"second index out of range\", GSL_EINVAL, 0) ;\n    }\n#endif\n  return m->data[i * m->tda + j] ;\n} \n\nextern inline \nvoid\ngsl_matrix_short_set(gsl_matrix_short * m, const size_t i, const size_t j, const short x)\n{\n#ifndef GSL_RANGE_CHECK_OFF\n  if (i >= m->size1)\n    {\n      GSL_ERROR_VOID(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_VOID(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  m->data[i * m->tda + j] = x ;\n}\n\nextern inline \nshort *\ngsl_matrix_short_ptr(gsl_matrix_short * m, const size_t i, const size_t j)\n{\n#ifndef GSL_RANGE_CHECK_OFF\n  if (i >= m->size1)\n    {\n      GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  return (short *) (m->data + (i * m->tda + j)) ;\n} \n\nextern inline \nconst short *\ngsl_matrix_short_const_ptr(const gsl_matrix_short * m, const size_t i, const size_t j)\n{\n#ifndef GSL_RANGE_CHECK_OFF\n  if (i >= m->size1)\n    {\n      GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  return (const short *) (m->data + (i * m->tda + j)) ;\n} \n\n#endif\n\n__END_DECLS\n\n#endif /* __GSL_MATRIX_SHORT_H__ */\n", "meta": {"hexsha": "9b6d237495dd045d6977838e7235009f6ae701b2", "size": 10857, "ext": "h", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/matrix/gsl_matrix_short.h", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/matrix/gsl_matrix_short.h", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/matrix/gsl_matrix_short.h", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 34.3575949367, "max_line_length": 124, "alphanum_fraction": 0.6616008105, "num_tokens": 2573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24798742624020276, "lm_q2_score": 0.024423090897336838, "lm_q1q2_score": 0.006056619452461087}}
{"text": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n#pragma once\n\n#include \"Map.h\"\n\n#include \"MapPoint.h\"\n#include \"MappingKeyframe.h\"\n#include \"InitializationData.h\"\n\n#include \"Tracking\\KeyframeBuilder.h\"\n\n#include \"Mapping\\MapPointKeyframeAssociations.h\"\n\n#include \"BoW\\OnlineBow.h\"\n#include \"BoW\\BaseFeatureMatcher.h\"\n\n#include \"BundleAdjustment\\BundleAdjust.h\"\n\n#include \"Data\\Types.h\"\n#include \"Data\\Pose.h\"\n#include \"Data\\Data.h\"\n#include \"Data\\MapState.h\"\n\n#include \"Utils\\historical_queue.h\"\n#include \"Utils\\collection.h\"\n\n#include <arcana\\threading\\blocking_concurrent_queue.h>\n\n#include <gsl\\gsl>\n\n#include <shared_mutex>\n#include <vector>\n#include <set>\n\n\n// forward-declare the friend class method for accessing the root map in unit tests\nnamespace UnitTests\n{\n    class TestHelperFunctions;\n}\n\nnamespace mage\n{\n    class ThreadSafeMap\n    {\n        friend class ::UnitTests::TestHelperFunctions;\n\n    public:\n        ThreadSafeMap(\n            const MageSlamSettings& settings, BaseBow& bagOfWords);\n\n        ~ThreadSafeMap();\n\n        void InitializeMap(const InitializationData& initializationData, thread_memory memory);\n\n        void GetConnectedMapPoints(\n            const collection<Proxy<MapPoint>>& points,\n            thread_memory memory,\n            loop::vector<KeyframeReprojection>& repro) const;\n\n        // returns a sampling of mappoints\n        void GetSampleOfMapPoints(temp::vector<MapPointProxy>& mapPoints, uint32_t max, uint32_t offset = 0) const;\n\n        /*\n        Inserts a new keyframe and returns all the keyframes that\n        are connected to this one by the covisibility graph.\n        */\n        Proxy<Keyframe, proxy::Image> InsertKeyframe(\n            const std::shared_ptr<const KeyframeBuilder>& kb,\n            thread_memory memory);\n\n        /*\n        Inserts a new keyframe and returns all the keyframes that\n        are connected to this one by the covisibility graph.\n        */\n        Proxy<Keyframe, proxy::Image> InsertKeyframe(\n            const std::shared_ptr<const KeyframeBuilder>& keyframe,\n            const gsl::span<MapPointAssociations<MapPointTrackingProxy>::Association>& extraAssociation,\n            thread_memory memory);\n\n        std::unique_ptr<KeyframeProxy> GetKeyFrameProxy(const Id<Keyframe>& kId) const;\n\n        /*\n        Merge information from a set of posited keyframes into the actual keyframes.\n        */\n        void UpdateKeyframesFromProxies(\n            gsl::span<const KeyframeProxy> proxies,\n            const OrbMatcherSettings& mergeSettings,\n            std::unordered_map<Id<MapPoint>, MapPointTrackingProxy>& mapPointMerges,\n            thread_memory memory);\n\n        /*\n        Updates the state of the map points in the KeyframeProxy based on the current\n        information in the map.\n        */\n        void UpdateMapPoints(KeyframeProxy& proxy) const;\n\n        /*\n        Builds a global bundle adjust dataset of everything in the map.\n        NOTE: Fixes the position of fixed and distance-tethered keyframes to preserve some semblance\n        of consistent scale.\n        */\n        void BuildGlobalBundleAdjustData(AdjustableData& data) const;\n\n        /*\n        Retrieves keyframes similar to the image provided.\n        */\n        void FindSimilarKeyframes(const std::shared_ptr<const AnalyzedImage>& image, std::vector<KeyframeProxy>& output) const;\n\n        void FindNonCovisibleSimilarKeyframeClusters(const KeyframeProxy& proxy, thread_memory memory, std::vector<std::vector<KeyframeProxy>>& output) const;\n\n        /*\n        Culls map points based on requirements related to number of keyframes they are visibile in and the results found in tracking\n        Takes a list of points that have failed to appear where predicted during tracking to remove as well\n        */\n        void CullRecentMapPoints(\n            const Id<Keyframe>& ki,\n            const mira::unique_vector<Id<MapPoint>>& recentFailedMapPoints,\n            thread_memory memory);\n\n        /*\n        Return the collection of all the map points\n        */\n        void GetMapPointsAsPositions(std::vector<Position>& positions) const;\n\n        /*\n        Return the number of map points in the map\n        */\n        size_t GetMapPointsCount() const;\n\n        /*\n        Return the number of keyframes in the map\n        */\n        size_t GetKeyframesCount() const;\n\n        /*\n        Return the collection of all the keyframes\n        */\n        void GetKeyframeViewMatrices(std::vector<Matrix>& viewMatrices) const;\n\n        /*\n        Creates the map points passed in and returns the keyframes that\n        were added to the frames connected to Ki through the covis graph\n        */\n        std::vector<MappingKeyframe> CreateMapPoints(\n            const Id<Keyframe>& keyframeId,\n            const gsl::span<const MapPointKeyframeAssociations >& toCreate,\n            thread_memory memory);\n\n        /*\n        Returns all the map points seen by this keyframe and the ones\n        seen by it's neighbours in the covisibility graph. It then returns\n        all the keyframes that see those points and aren't in Ki's covis graph.\n        */\n        unsigned int GetMapPointsAndDistantKeyframes(\n            const Id<Keyframe>& Ki,\n            unsigned int coVisTheta,\n            thread_memory memory,\n            std::vector<MapPointTrackingProxy>& mapPoints,\n            std::vector<Proxy<Keyframe, proxy::Pose, proxy::Intrinsics, proxy::PoseConstraints>>& keyframes,\n            std::vector<MapPointAssociation>& mapPointAssociations,\n            std::vector<Id<Keyframe>>& externallyTetheredKeyframes) const;\n\n        /*\n        Updates all the map point positions and keyframe poses and\n        destroys all the MapPoint outliers (Not sure if we actually destroy them or not).\n        */\n        void AdjustPosesAndMapPoints(\n            const AdjustableData& adjusted,\n            gsl::span<const std::pair<Id<MapPoint>, Id<Keyframe>>> outlierAssociations,\n            thread_memory memory);\n\n        /*\n        Discards the duplicate keyframes that are\n        connected to Ki in the covisibility graph.\n\n        Returns the KeyframeIds that were removed as well as the covisability which lead to the removal decision if argument provided\n        */\n        void CullLocalKeyframes(\n            Id<Keyframe> Ki,\n            thread_memory memory,\n            std::vector<std::pair<const Id<Keyframe>, const std::vector<Id<Keyframe>>>>* cullingDecisions = nullptr);\n\n        /*\n        gets keyframes connected to KId in the covisibility graph (more than the minimum required\n        map points in common to be entered as a link in the covisibility graph)\n        */\n        void GetCovisibilityConnectedKeyframes(\n            const Id<Keyframe>& kId,\n            thread_memory memory,\n            std::vector<MappingKeyframe>& kc) const;\n\n        /*\n        gets the list of recent points the mapping thread is still carefully evaluating. track local map\n        will use this to collect more information on these points for use by the mapping thread, and the\n        age of each of these map points\n        */\n        std::map<Id<MapPoint>, unsigned int> GetRecentlyCreatedMapPoints() const;\n\n        /*\n        * Will attempt to match the set of map points into the set of keyframes if matching criterea are met\n        */\n        void TryConnectMapPoints(gsl::span<const MapPointAssociations<MapPointTrackingProxy>::Association> mapPointAssociations,\n            const Id<Keyframe>& insertedKeyframe,\n            const TrackLocalMapSettings& trackLocalMapSettings,\n            const OrbMatcherSettings& orbMatcherSettings,\n            float searchRadius,\n            thread_memory memory);\n\n        /*\n        Delete the state of the entire map\n        */\n        void Clear(thread_memory memory);\n\n        /*\n        Returns all the information pertinent when saving the map\n        */\n        MapState GetMapData() const;\n\n        float GetMedianTetherDistance() const;\n\n        float GetMapScale() const;\n\n        /*\n        Returns all the keyframes in the map\n        */\n        std::vector<KeyframeProxy> GetAllKeyframes() const;\n\n        /*\n        Destroys this instance of the thread safe map and returns it's\n        internal map for use in another context.\n        */\n        static std::unique_ptr<Map> Release(std::unique_ptr<ThreadSafeMap> tsm);\n\n    private:\n        void UnSafeGetCovisibilityConnectedKeyframes(\n            const Id<Keyframe>& kId,\n            thread_memory memory,\n            std::vector<MappingKeyframe>& kc) const;\n\n        // the int value is the number of Keyframes this map point has existed for\n        std::map<Id<MapPoint>, unsigned int> UnSafeGetRecentlyCreatedMapPoints() const;\n\n        /*\n        Performs all the logic for AdjustPosesAndMapPoints, but does not take its own\n        lock and so can be used by other methods as well.\n        */\n        void UnSafeAdjustPosesAndMapPoints(\n            const AdjustableData& adjusted,\n            gsl::span<const std::pair<Id<MapPoint>, Id<Keyframe>>> outlierAssociations,\n            thread_memory memory);\n\n        // vector to record map point creations for map point culling\n        historical_queue<std::vector<Proxy<MapPoint>>, 3> m_pointHistory;\n\n        const KeyframeSettings& m_keyframeSettings;\n        const MappingSettings& m_mappingSettings;\n        const CovisibilitySettings& m_covisibilitySettings;\n        const BundleAdjustSettings& m_bundleAdjustSettings;\n\n        mutable std::shared_mutex m_mutex;\n\n        std::unique_ptr<Map> m_map;\n\n        BaseBow& m_bow;\n\n        float m_mapScale;\n    };\n}\n", "meta": {"hexsha": "383dff40232a2f5697dfc34ae81bbfd487c3dd0c", "size": 9636, "ext": "h", "lang": "C", "max_stars_repo_path": "Core/MAGESLAM/Source/Map/ThreadSafeMap.h", "max_stars_repo_name": "syntheticmagus/mageslam", "max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z", "max_issues_repo_path": "Core/MAGESLAM/Source/Map/ThreadSafeMap.h", "max_issues_repo_name": "syntheticmagus/mageslam", "max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z", "max_forks_repo_path": "Core/MAGESLAM/Source/Map/ThreadSafeMap.h", "max_forks_repo_name": "syntheticmagus/mageslam", "max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z", "avg_line_length": 35.4264705882, "max_line_length": 158, "alphanum_fraction": 0.6617891241, "num_tokens": 2044, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36296919173767833, "lm_q2_score": 0.016657037629499858, "lm_q1q2_score": 0.006045991485123657}}
{"text": "// The MIT License (MIT)\n//\n// Copyright (c) 2018 Mateusz Pusz\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n// Formatting library for C++ - the core API for char/UTF-8\n//\n// Copyright (c) 2012 - present, Victor Zverovich\n// All rights reserved.\n//\n// For the license information refer to format.h.\n\n#include <gsl/gsl-lite.hpp>\n#include <units/bits/fmt_hacks.h>\n#include <concepts>\n#include <limits>\n#include <string_view>\n\n// most of the below code is based on/copied from libfmt\n\nnamespace units::detail {\n\nstruct auto_id {};\n\nenum class fmt_align { none, left, right, center };\nenum class fmt_sign { none, minus, plus, space };\nenum class arg_id_kind { none, index, name };\n\ntemplate<typename Char>\nstruct fill_t {\nprivate:\n  static constexpr size_t max_size = 4 / sizeof(Char);\n  // At most one codepoint (so one char32_t or four utf-8 char8_t)\n  Char data_[max_size] = {Char{' '}};\n  unsigned char size_ = 1;\n\npublic:\n  constexpr void operator=(std::basic_string_view<Char> s)\n  {\n    auto size = s.size();\n    if (size > max_size) return throw STD_FMT::format_error(\"invalid fill\");\n    for (size_t i = 0; i < size; ++i) data_[i] = s[i];\n    size_ = static_cast<unsigned char>(size);\n  }\n\n  [[nodiscard]] constexpr size_t size() const { return size_; }\n  [[nodiscard]] constexpr const Char* data() const { return data_; }\n\n  [[nodiscard]] constexpr Char& operator[](size_t index) { return data_[index]; }\n  [[nodiscard]] constexpr const Char& operator[](size_t index) const { return data_[index]; }\n};\n\ntemplate<typename T>\ninline constexpr bool is_integer = std::is_integral<T>::value && !std::is_same<T, bool>::value &&\n                                   !std::is_same<T, char>::value && !std::is_same<T, wchar_t>::value;\n\ntemplate<typename Char>\n[[nodiscard]] constexpr bool is_ascii_letter(Char c)\n{\n  return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');\n}\n\n// Converts a character to ASCII. Returns a number > 127 on conversion failure.\ntemplate<std::integral Char>\n[[nodiscard]] constexpr Char to_ascii(Char value)\n{\n  return value;\n}\n\ntemplate<typename Char>\n  requires std::is_enum_v<Char>\n[[nodiscard]] constexpr auto to_ascii(Char value) -> std::underlying_type_t<Char> { return value; }\n\nstruct width_checker {\n  template<typename T>\n  [[nodiscard]] constexpr unsigned long long operator()(T value) const\n  {\n    if constexpr (is_integer<T>) {\n      if constexpr (std::numeric_limits<T>::is_signed) {\n        if (value < 0) throw STD_FMT::format_error(\"negative width\");\n      }\n      return static_cast<unsigned long long>(value);\n    } else {\n      throw STD_FMT::format_error(\"width is not integer\");\n    }\n  }\n};\n\nstruct precision_checker {\n  template<typename T>\n  [[nodiscard]] constexpr unsigned long long operator()(T value) const\n  {\n    if constexpr (is_integer<T>) {\n      if constexpr (std::numeric_limits<T>::is_signed) {\n        if (value < 0) throw STD_FMT::format_error(\"negative precision\");\n      }\n      return static_cast<unsigned long long>(value);\n    } else {\n      throw STD_FMT::format_error(\"precision is not integer\");\n    }\n  }\n};\n\n// Format specifiers for built-in and string types.\ntemplate<typename Char>\nstruct basic_format_specs {\n  int width = 0;\n  int precision = -1;\n  char type = '\\0';\n  fmt_align align : 4 = fmt_align::none;\n  fmt_sign sign : 3 = fmt_sign::none;\n  bool alt : 1 = false;  // Alternate form ('#').\n  bool localized : 1 = false;\n  fill_t<Char> fill;\n};\n\n// Format specifiers with width and precision resolved at formatting rather\n// than parsing time to allow re-using the same parsed specifiers with\n// different sets of arguments (precompilation of format strings).\ntemplate<typename Char>\nstruct dynamic_format_specs : basic_format_specs<Char> {\n  int dynamic_width_index = -1;\n  int dynamic_precision_index = -1;\n};\n\n[[nodiscard]] constexpr int verify_dynamic_arg_index_in_range(size_t idx)\n{\n  if (idx > static_cast<size_t>(std::numeric_limits<int>::max())) {\n    throw STD_FMT::format_error(\"Dynamic width or precision index too large.\");\n  }\n  return static_cast<int>(idx);\n}\n\ntemplate<typename CharT>\n[[nodiscard]] constexpr int on_dynamic_arg(size_t arg_id, STD_FMT::basic_format_parse_context<CharT>& context)\n{\n  context.check_arg_id(FMT_TO_ARG_ID(arg_id));\n  return verify_dynamic_arg_index_in_range(arg_id);\n}\n\ntemplate<typename CharT>\n[[nodiscard]] constexpr int on_dynamic_arg(auto_id, STD_FMT::basic_format_parse_context<CharT>& context)\n{\n  return verify_dynamic_arg_index_in_range(FMT_FROM_ARG_ID(context.next_arg_id()));\n}\n\ntemplate<class Handler, typename FormatContext>\n[[nodiscard]] constexpr int get_dynamic_spec(int index, FormatContext& ctx)\n{\n  const unsigned long long value =\n    STD_FMT::visit_format_arg(Handler{}, ctx.arg(FMT_TO_ARG_ID(static_cast<size_t>(index))));\n  if (value > static_cast<unsigned long long>(std::numeric_limits<int>::max())) {\n    throw STD_FMT::format_error(\"number is too big\");\n  }\n  return static_cast<int>(value);\n}\n\n// Parses the range [begin, end) as an unsigned integer. This function assumes\n// that the range is non-empty and the first character is a digit.\ntemplate<std::input_iterator It, std::sentinel_for<It> S>\n[[nodiscard]] constexpr It parse_nonnegative_int(It begin, S end, size_t& value)\n{\n  gsl_Expects(begin != end && '0' <= *begin && *begin <= '9');\n  constexpr auto max_int = static_cast<unsigned>(std::numeric_limits<int>::max());\n  constexpr auto big_int = max_int / 10u;\n  value = 0;\n\n  do {\n    if (value > big_int) {\n      value = max_int + 1;\n      break;\n    }\n    value = value * 10 + static_cast<unsigned int>(*begin - '0');\n    ++begin;\n  } while (begin != end && '0' <= *begin && *begin <= '9');\n\n  if (value > max_int) throw STD_FMT::format_error(\"Number is too big\");\n\n  return begin;\n}\n\ntemplate<std::input_iterator It, std::sentinel_for<It> S>\n[[nodiscard]] constexpr It parse_nonnegative_int(It begin, S end, int& value)\n{\n  size_t val_unsigned = 0;\n  begin = parse_nonnegative_int(begin, end, val_unsigned);\n  // Never invalid because parse_nonnegative_integer throws an error for values that don't fit in signed integers\n  value = static_cast<int>(val_unsigned);\n  return begin;\n}\n\ntemplate<std::input_iterator It, std::sentinel_for<It> S, typename IDHandler>\n[[nodiscard]] constexpr It do_parse_arg_id(It begin, S end, IDHandler&& handler)\n{\n  gsl_Expects(begin != end);\n  auto c = *begin;\n  if (c >= '0' && c <= '9') {\n    size_t index = 0;\n    if (c != '0')\n      begin = parse_nonnegative_int(begin, end, index);\n    else\n      ++begin;\n    if (begin == end || (*begin != '}' && *begin != ':'))\n      throw STD_FMT::format_error(\"invalid format string\");\n    else\n      handler(index);\n    return begin;\n  }\n  throw STD_FMT::format_error(\"invalid format string\");\n}\n\ntemplate<std::input_iterator It, std::sentinel_for<It> S, typename IDHandler>\n[[nodiscard]] constexpr It parse_arg_id(It begin, S end, IDHandler&& handler)\n{\n  auto c = *begin;\n  if (c != '}' && c != ':') return do_parse_arg_id(begin, end, handler);\n  handler();\n  return begin;\n}\n\ntemplate<std::input_iterator It, std::sentinel_for<It> S, typename Handler>\n[[nodiscard]] constexpr It parse_sign(It begin, S end, Handler&& handler)\n{\n  gsl_Expects(begin != end);\n  switch (to_ascii(*begin)) {\n    case '+':\n      handler.on_sign(fmt_sign::plus);\n      ++begin;\n      break;\n    case '-':\n      handler.on_sign(fmt_sign::minus);\n      ++begin;\n      break;\n    case ' ':\n      handler.on_sign(fmt_sign::space);\n      ++begin;\n      break;\n    default:\n      break;\n  }\n  return begin;\n}\n\ntemplate<std::input_iterator It, std::sentinel_for<It> S, typename Handler>\n[[nodiscard]] constexpr It parse_width(It begin, S end, Handler&& handler)\n{\n  struct width_adapter {\n    Handler& handler;\n    constexpr void operator()() { handler.on_dynamic_width(auto_id{}); }\n    constexpr void operator()(size_t id) { handler.on_dynamic_width(id); }\n  };\n\n  gsl_Expects(begin != end);\n  if ('0' <= *begin && *begin <= '9') {\n    int width = 0;\n    begin = parse_nonnegative_int(begin, end, width);\n    if (width != -1)\n      handler.on_width(width);\n    else\n      throw STD_FMT::format_error(\"number is too big\");\n  } else if (*begin == '{') {\n    ++begin;\n    if (begin != end) begin = parse_arg_id(begin, end, width_adapter{handler});\n    if (begin == end || *begin != '}') throw STD_FMT::format_error(\"invalid format string\");\n    ++begin;\n  }\n  return begin;\n}\n\ntemplate<std::input_iterator It, std::sentinel_for<It> S, typename Handler>\n[[nodiscard]] constexpr It parse_precision(It begin, S end, Handler&& handler)\n{\n  struct precision_adapter {\n    Handler& handler;\n    constexpr void operator()() { handler.on_dynamic_precision(auto_id{}); }\n    constexpr void operator()(size_t id) { handler.on_dynamic_precision(id); }\n  };\n\n  ++begin;\n  auto c = begin != end ? *begin : std::iter_value_t<It>();\n  if ('0' <= c && c <= '9') {\n    auto precision = 0;\n    begin = parse_nonnegative_int(begin, end, precision);\n    if (precision != -1)\n      handler.on_precision(precision);\n    else\n      throw STD_FMT::format_error(\"number is too big\");\n  } else if (c == '{') {\n    ++begin;\n    if (begin != end) begin = parse_arg_id(begin, end, precision_adapter{handler});\n    if (begin == end || *begin++ != '}') throw STD_FMT::format_error(\"invalid format string\");\n  } else {\n    throw STD_FMT::format_error(\"missing precision specifier\");\n  }\n  return begin;\n}\n\ntemplate<std::input_iterator It>\nconstexpr int code_point_length(It begin)\n{\n  if constexpr (sizeof(std::iter_value_t<It>) != 1) return 1;\n  constexpr char lengths[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n                              0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0};\n  int len = lengths[static_cast<unsigned char>(*begin) >> 3];\n\n  // Compute the pointer to the next character early so that the next\n  // iteration can start working on the next character. Neither Clang\n  // nor GCC figure out this reordering on their own.\n  return len + !len;\n}\n\n// Parses fill and alignment.\ntemplate<std::input_iterator It, std::sentinel_for<It> S, typename Handler>\n[[nodiscard]] constexpr It parse_align(It begin, S end, Handler&& handler)\n{\n  gsl_Expects(begin != end);\n  auto align = fmt_align::none;\n  auto p = begin + code_point_length(begin);\n  if (p >= end) p = begin;\n  for (;;) {\n    switch (to_ascii(*p)) {\n      case '<':\n        align = fmt_align::left;\n        break;\n      case '>':\n        align = fmt_align::right;\n        break;\n      case '^':\n        align = fmt_align::center;\n        break;\n      default:\n        break;\n    }\n    if (align != fmt_align::none) {\n      if (p != begin) {\n        auto c = *begin;\n        if (c == '{') throw STD_FMT::format_error(\"invalid fill character '{'\");\n        handler.on_fill(std::basic_string_view<std::iter_value_t<It>>(begin, static_cast<size_t>(p - begin)));\n        begin = p + 1;\n      } else\n        ++begin;\n      handler.on_align(align);\n      break;\n    } else if (p == begin) {\n      break;\n    }\n    p = begin;\n  }\n  return begin;\n}\n\n// Parses standard format specifiers and sends notifications about parsed\n// components to handler.\ntemplate<std::input_iterator It, std::sentinel_for<It> S, typename SpecHandler>\n[[nodiscard]] constexpr It parse_format_specs(It begin, S end, SpecHandler&& handler)\n{\n  if (begin + 1 < end && begin[1] == '}' && is_ascii_letter(*begin) && *begin != 'L') {\n    handler.on_type(*begin++);\n    return begin;\n  }\n\n  if (begin == end) return begin;\n\n  begin = ::units::detail::parse_align(begin, end, handler);\n  if (begin == end) return begin;\n\n  // Parse sign.\n  begin = ::units::detail::parse_sign(begin, end, handler);\n  if (begin == end) return begin;\n\n  if (*begin == '#') {\n    handler.on_hash();\n    if (++begin == end) return begin;\n  }\n\n  // Parse zero flag.\n  if (*begin == '0') {\n    handler.on_zero();\n    if (++begin == end) return begin;\n  }\n\n  begin = ::units::detail::parse_width(begin, end, handler);\n  if (begin == end) return begin;\n\n  // Parse precision.\n  if (*begin == '.') {\n    begin = ::units::detail::parse_precision(begin, end, handler);\n    if (begin == end) return begin;\n  }\n\n  if (*begin == 'L') {\n    handler.on_localized();\n    ++begin;\n  }\n\n  // Parse type.\n  if (begin != end && *begin != '}') handler.on_type(*begin++);\n  return begin;\n}\n\n// A format specifier handler that sets fields in basic_format_specs.\ntemplate<typename Char>\nclass specs_setter {\nprotected:\n  basic_format_specs<Char>& specs_;\npublic:\n  constexpr explicit specs_setter(basic_format_specs<Char>& specs) : specs_(specs) {}\n  constexpr void on_align(fmt_align align) { specs_.align = align; }\n  constexpr void on_fill(std::basic_string_view<Char> fill) { specs_.fill = fill; }\n  constexpr void on_sign(fmt_sign s) { specs_.sign = s; }\n  constexpr void on_hash() { specs_.alt = true; }\n  constexpr void on_localized() { specs_.localized = true; }\n  constexpr void on_zero() { specs_.fill[0] = Char('0'); }\n  constexpr void on_width(int width) { specs_.width = width; }\n  constexpr void on_precision(int precision) { specs_.precision = precision; }\n  constexpr void on_type(Char type) { specs_.type = static_cast<char>(type); }\n};\n\n// Format spec handler that saves references to arguments representing dynamic\n// width and precision to be resolved at formatting time.\ntemplate<typename ParseContext>\nclass dynamic_specs_handler : public specs_setter<typename ParseContext::char_type> {\npublic:\n  using char_type = TYPENAME ParseContext::char_type;\n\n  constexpr dynamic_specs_handler(dynamic_format_specs<char_type>& specs, ParseContext& ctx) :\n      specs_setter<char_type>(specs), specs_(specs), context_(ctx)\n  {}\n\n  template<typename T>\n  constexpr void on_dynamic_width(T t)\n  {\n    specs_.dynamic_width_index = on_dynamic_arg(t, context_);\n  }\n\n  template<typename T>\n  constexpr void on_dynamic_precision(T t)\n  {\n    specs_.dynamic_precision_index = on_dynamic_arg(t, context_);\n  }\nprivate:\n  dynamic_format_specs<char_type>& specs_;\n  ParseContext& context_;\n};\n\n}  // namespace units::detail\n", "meta": {"hexsha": "457c87ff0b6508f361faddc8a96affb8596de0c8", "size": 15047, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core-fmt/include/units/bits/fmt.h", "max_stars_repo_name": "hofbi/units", "max_stars_repo_head_hexsha": "212c9e05f252ffddbf77a8dba125f05d64d0d14a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core-fmt/include/units/bits/fmt.h", "max_issues_repo_name": "hofbi/units", "max_issues_repo_head_hexsha": "212c9e05f252ffddbf77a8dba125f05d64d0d14a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core-fmt/include/units/bits/fmt.h", "max_forks_repo_name": "hofbi/units", "max_forks_repo_head_hexsha": "212c9e05f252ffddbf77a8dba125f05d64d0d14a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4288793103, "max_line_length": 113, "alphanum_fraction": 0.6730909816, "num_tokens": 3833, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16667540468797667, "lm_q2_score": 0.036220052613898816, "lm_q1q2_score": 0.006036991927241392}}
{"text": "/**\n */\n#ifndef _INOUT_APER_H\n\n#define _INOUT_APER_H\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <math.h>\n#include <gsl/gsl_vector.h>\n#include \"aXe_grism.h\"\n#include \"aXe_utils.h\"\n#include \"aXe_errors.h\"\n#include \"spc_cfg.h\"\n#include \"spc_trace_functions.h\"\n\n#define APER_MAXLINE 14\n\nextern int\nnbeams_from_char_array2 (char **apers, int num);\n\nextern gsl_vector_int *\nnbeams_from_char_array (char **apers, int num);\n\nextern int \nobject_list_to_file (object * const *oblist, char *filename,\n                     int leaveout_ignored);\n\nextern int\nget_beam_from_aper_file (char *filename, int aperID, int beamID,beam * b);\n\nextern gsl_vector_int *\naper_file_aperlist (char *filename);\n\nextern int \naper_file_apernum (char *filename);\n\nextern object *\nget_aperture_from_aper_file (char *filename, int aperID);\n\nextern object **\nfile_to_object_list (char filename[], observation * obs);\n\nextern char **\nreturn_next_aperture(FILE *input);\n\nextern object **\nfile_to_object_list_seq (char filename[], observation * obs);\n\nextern int \nfind_object_in_object_list(object **oblist, const int ID);\n\nextern beam\nfind_beam_in_object_list(object **oblist, const int objID,\n                         const int beamID);\n\nextern beam *\nfind_beamptr_in_object_list(object **oblist, const int objID,\n                            const int beamID);\n\nextern void\nrefurbish_object_list(object **oblist, const int new_default,\n                      const int old_value, const int new_value);\n\nextern int\nobject_list_size(object **oblist);\n\nextern int\nget_beamspec_size(object **oblist);\n#endif\n", "meta": {"hexsha": "0dec138306cedb0be5dec3bd65262a25bfe19ef6", "size": 1613, "ext": "h", "lang": "C", "max_stars_repo_path": "cextern/src/inout_aper.h", "max_stars_repo_name": "sosey/pyaxe", "max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cextern/src/inout_aper.h", "max_issues_repo_name": "sosey/pyaxe", "max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cextern/src/inout_aper.h", "max_forks_repo_name": "sosey/pyaxe", "max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.095890411, "max_line_length": 74, "alphanum_fraction": 0.727216367, "num_tokens": 402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31069438321455395, "lm_q2_score": 0.0194193472247875, "lm_q1q2_score": 0.006033482108434613}}
{"text": "#pragma once\n\n#include <gsl\\gsl>\n#include <winrt\\Windows.Foundation.h>\n#include <d3d11.h>\n#include <map>\n#include \"DrawableGameComponent.h\"\n#include \"FullScreenRenderTarget.h\"\n#include \"FullScreenQuad.h\"\n#include \"MatrixHelper.h\"\n\nnamespace Library\n{\n\tclass PixelShader;\n}\n\nnamespace Rendering\n{\n\tclass DiffuseLightingDemo;\n\n\tenum class ColorFilters\n\t{\n\t\tGrayScale = 0,\n\t\tInverse,\n\t\tSepia,\n\t\tGeneric,\n\t\tEnd\n\t};\n\n\tclass ColorFilteringDemo final : public Library::DrawableGameComponent\n\t{\n\tpublic:\n\t\tColorFilteringDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera);\n\t\tColorFilteringDemo(const ColorFilteringDemo&) = delete;\n\t\tColorFilteringDemo(ColorFilteringDemo&&) = default;\n\t\tColorFilteringDemo& operator=(const ColorFilteringDemo&) = default;\t\t\n\t\tColorFilteringDemo& operator=(ColorFilteringDemo&&) = default;\n\t\t~ColorFilteringDemo();\n\n\t\tstd::shared_ptr<DiffuseLightingDemo> DiffuseLighting() const;\n\n\t\tColorFilters ActiveColorFilter() const;\n\t\tvoid SetActiveColorFilter(ColorFilters colorFilter);\n\n\t\tfloat GenericFilterBrightness() const;\n\t\tvoid SetGenericFilterBrightness(float brightness);\n\t\t\n\t\tstatic const std::map<ColorFilters, std::string> ColorFilterNames;\n\n\t\tvirtual void Initialize() override;\n\t\tvirtual void Update(const Library::GameTime& gameTime) override;\n\t\tvirtual void Draw(const Library::GameTime& gameTime) override;\n\n\tprivate:\n\t\tstruct GenericColorFilterPSConstantBuffer\n\t\t{\n\t\t\tDirectX::XMFLOAT4X4 ColorFilter{ Library::MatrixHelper::Identity };\n\t\t};\n\n\t\tstd::shared_ptr<DiffuseLightingDemo> mDiffuseLightingDemo;\t\t\n\t\tLibrary::FullScreenRenderTarget mRenderTarget;\n\t\tLibrary::FullScreenQuad mFullScreenQuad;\n\t\tstd::map<ColorFilters, std::shared_ptr<Library::PixelShader>> mPixelShadersByColorFilter;\n\t\tColorFilters mActiveColorFilter;\t\n\t\twinrt::com_ptr<ID3D11Buffer> mGenericColorFilterPSConstantBuffer;\n\t\tGenericColorFilterPSConstantBuffer mGenericColorFilterPSConstantBufferData;\n\t};\n}", "meta": {"hexsha": "e511c568aeaced7e541836f5d897bc540485fcef", "size": 1932, "ext": "h", "lang": "C", "max_stars_repo_path": "source/7.1_Color_Filtering/ColorFilteringDemo.h", "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/7.1_Color_Filtering/ColorFilteringDemo.h", "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/7.1_Color_Filtering/ColorFilteringDemo.h", "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4117647059, "max_line_length": 91, "alphanum_fraction": 0.7888198758, "num_tokens": 481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32423539898095244, "lm_q2_score": 0.01854656457992723, "lm_q1q2_score": 0.006013452766298706}}
{"text": "#include <config.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_sum.h>\n\ngsl_sum_levin_u_workspace * \ngsl_sum_levin_u_alloc (size_t n)\n{\n  gsl_sum_levin_u_workspace * w;\n\n  if (n == 0)\n    {\n      GSL_ERROR_VAL (\"length n must be positive integer\", GSL_EDOM, 0);\n    }\n\n  w = (gsl_sum_levin_u_workspace *) malloc(sizeof(gsl_sum_levin_u_workspace));\n\n  if (w == NULL)\n    {\n      GSL_ERROR_VAL (\"failed to allocate struct\", GSL_ENOMEM, 0);\n    }\n\n  w->q_num = (double *) malloc (n * sizeof (double));\n\n  if (w->q_num == NULL)\n    {\n      free(w) ; /* error in constructor, prevent memory leak */\n\n      GSL_ERROR_VAL (\"failed to allocate space for q_num\", GSL_ENOMEM, 0);\n    }\n\n  w->q_den = (double *) malloc (n * sizeof (double));\n\n  if (w->q_den == NULL)\n    {\n      free (w->q_num);\n      free (w) ; /* error in constructor, prevent memory leak */\n\n      GSL_ERROR_VAL (\"failed to allocate space for q_den\", GSL_ENOMEM, 0);\n    }\n\n  w->dq_num = (double *) malloc (n * n * sizeof (double));\n\n  if (w->dq_num == NULL)\n    {\n      free (w->q_den);\n      free (w->q_num);\n      free(w) ; /* error in constructor, prevent memory leak */\n\n      GSL_ERROR_VAL (\"failed to allocate space for dq_num\", GSL_ENOMEM, 0);\n    }\n\n  w->dq_den = (double *) malloc (n * n * sizeof (double));\n\n  if (w->dq_den == NULL)\n    {\n      free (w->dq_num);\n      free (w->q_den);\n      free (w->q_num);\n      free (w) ; /* error in constructor, prevent memory leak */\n\n      GSL_ERROR_VAL (\"failed to allocate space for dq_den\", GSL_ENOMEM, 0);\n    }\n\n  w->dsum = (double *) malloc (n * sizeof (double));\n\n  if (w->dsum == NULL)\n    {\n      free (w->dq_den);\n      free (w->dq_num);\n      free (w->q_den);\n      free (w->q_num);\n      free (w) ; /* error in constructor, prevent memory leak */\n\n      GSL_ERROR_VAL (\"failed to allocate space for dsum\", GSL_ENOMEM, 0);\n    }\n\n  w->size = n;\n  w->terms_used = 0;\n  w->sum_plain = 0;\n\n  return w;\n}\n\nvoid\ngsl_sum_levin_u_free (gsl_sum_levin_u_workspace * w)\n{\n  free (w->dsum);\n  free (w->dq_den);\n  free (w->dq_num);\n  free (w->q_den);\n  free (w->q_num);\n  free (w);\n}\n", "meta": {"hexsha": "3f7052b30d2294b6c6c849b04616239aa9e24ca7", "size": 2121, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/sum/work_u.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/sum/work_u.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/sum/work_u.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 22.3263157895, "max_line_length": 78, "alphanum_fraction": 0.5893446488, "num_tokens": 661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30404167496654744, "lm_q2_score": 0.019719129079494028, "lm_q1q2_score": 0.005995437034210917}}
{"text": "#ifndef PRECISION_RECALL_H_G2FJDYVV\n#define PRECISION_RECALL_H_G2FJDYVV\n\n#include <gsl/gsl>\n#include <opencv2/core/base.hpp>\n#include <opencv2/core/types.hpp>\n#include <opencv2/imgproc.hpp>\n#include <optional>\n#include <string_view>\n#include <util/common_structures.h>\n\nnamespace sens_loc::apps {\n\n/// Defines the color and line strength used for backprojection.\nstruct backproject_style {\n    backproject_style() = default;\n    backproject_style(int r, int g, int b, int strength)\n        : color{CV_RGB(r, g, b)}\n        , strength{strength} {\n        Expects(strength > 0);\n        Expects(r >= 0);\n        Expects(g >= 0);\n        Expects(b >= 0);\n        Expects(r < 256);\n        Expects(g < 256);\n        Expects(b < 256);\n    }\n\n    cv::Scalar color    = CV_RGB(0, 0, 0);\n    int        strength = 1;\n};\n\n/// Composition of styles on how the backprojections are plotted.\n/// \\sa backproject_style\nstruct backproject_config {\n    backproject_style true_positive;\n    backproject_style false_negative;\n    backproject_style false_positive;\n};\n\nstruct recognition_analysis_input {\n    std::string_view                depth_image_pattern;\n    std::string_view                pose_file_pattern;\n    std::string_view                intrinsic_file;\n    std::optional<std::string_view> mask_file;\n    cv::NormTypes                   matching_norm;\n    float                           keypoint_distance_threshold;\n\n    /// Unit-Conversion for the ICP of kinect images. No other depth images\n    /// are treated with ICP, so this is dirty set to a constant.\n    const float unit_factor = 0.001F;\n};\n\nstruct recognition_analysis_output_options {\n    std::optional<std::string> backproject_pattern;\n    std::optional<std::string> original_files;\n    std::optional<std::string> stat_file;\n    std::optional<std::string> backprojection_selected_histo;\n    std::optional<std::string> relevant_histo;\n    std::optional<std::string> true_positive_histo;\n    std::optional<std::string> false_positive_histo;\n    std::optional<std::string> true_positive_distance_histo;\n    std::optional<std::string> false_positive_distance_histo;\n};\n\nint analyze_recognition_performance(\n    util::processing_input                     in,\n    const recognition_analysis_input&          required_data,\n    const recognition_analysis_output_options& output_options,\n    const backproject_config&                  backproject_config);\n\n}  // namespace sens_loc::apps\n\n#endif /* end of include guard: PRECISION_RECALL_H_G2FJDYVV */\n", "meta": {"hexsha": "295e8f6734e2bda945214c4d6f3c23c9f953b288", "size": 2502, "ext": "h", "lang": "C", "max_stars_repo_path": "src/apps/feature_performance/recognition_performance.h", "max_stars_repo_name": "JonasToth/depth-conversions", "max_stars_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-09-30T07:09:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T09:14:35.000Z", "max_issues_repo_path": "src/apps/feature_performance/recognition_performance.h", "max_issues_repo_name": "JonasToth/depth-conversions", "max_issues_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/apps/feature_performance/recognition_performance.h", "max_forks_repo_name": "JonasToth/depth-conversions", "max_forks_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.36, "max_line_length": 75, "alphanum_fraction": 0.6826538769, "num_tokens": 579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2538610069692489, "lm_q2_score": 0.023330767195644288, "lm_q1q2_score": 0.005922772053651378}}
{"text": "#pragma once\n\n#include \"datastructures/PointBuffer.h\"\n#include \"io/PointsPersistence.h\"\n#include \"math/AABB.h\"\n#include \"point_source/PointSource.h\"\n#include \"pointcloud/FileStats.h\"\n#include \"pointcloud/PointAttributes.h\"\n#include \"tiling/Sampling.h\"\n#include \"util/Definitions.h\"\n#include \"util/Transformation.h\"\n#include <reflection/StaticReflection.h>\n#include <threading/Semaphore.h>\n#include <threading/TaskSystem.h>\n\n#include <atomic>\n#include <deque>\n#include <gsl/gsl>\n#include <string>\n#include <thread>\n\n#include <taskflow/taskflow.hpp>\n\nstruct ProgressReporter;\nstruct TilingAlgorithmBase;\nstruct ThroughputSampler;\n\n/**\n * Which tiling strategy to use?\n */\nenum class TilingStrategy\n{\n  /**\n   * Use the accurate strategy that samples from the root node. This will be\n   * slower than the 'Fast' strategy, that skips the first couple of levels and\n   * reconstructs them afterwards\n   */\n  Accurate,\n  /**\n   * Use the fast strategy that skips the first couple of levels and starts\n   * tiling deeper in the octree to enable increased parallelism. The skipped\n   * levels are reconstructed and thus contain duplicated data\n   */\n  Fast\n};\n\nstruct FixedThreadCount\n{\n  uint32_t num_threads_for_reading;\n  uint32_t num_threads_for_indexing;\n};\n\nstruct AdaptiveThreadCount\n{\n  uint32_t num_threads;\n};\n\n/**\n * Thread number configuration. Either a fixed number of read and index threads, or\n * a total fixed number of threads that are scheduled adaptively\n */\nusing ThreadConfig = std::variant<FixedThreadCount, AdaptiveThreadCount>;\n\nstruct TilerMetaParameters\n{\n  float spacing_at_root;\n  uint32_t max_depth;\n  size_t max_points_per_node;\n  size_t batch_read_size;\n  size_t internal_cache_size;\n  bool shift_points_to_origin;\n  bool create_journal;\n  TilingStrategy tiling_strategy;\n  std::variant<FixedThreadCount, AdaptiveThreadCount> thread_count;\n};\n\n/**\n * Abstract command for reading points from a file.\n */\nstruct ReadCommand\n{\n  const fs::path* file_path;\n  size_t to_read_count;\n};\n\nstruct Tiler\n{\n  Tiler(DatasetMetadata dataset_metadata,\n        TilerMetaParameters meta_parameters,\n        SamplingStrategy sampling_strategy,\n        ProgressReporter* progress_reporter,\n        MultiReaderPointSource point_source,\n        PointsPersistence& persistence,\n        const PointAttributes& input_attributes,\n        fs::path output_directory);\n  ~Tiler();\n\n  /**\n   * Run the tiler. Returns the total number of points that were processed\n   */\n  size_t run();\n\nprivate:\n  void swap_point_buffers(size_t produced_points_count);\n\n  bool build_execution_graph_for_reading(tf::Taskflow& tf,\n                                         uint32_t num_read_threads,\n                                         ThroughputSampler& throughput_sampler);\n  void execute_read_commands(const std::vector<ReadCommand>& read_commands,\n                             util::Range<PointBuffer::PointIterator> read_destination);\n\n  void build_execution_graph_for_indexing(tf::Taskflow& tf,\n                                          uint32_t num_indexing_threads,\n                                          ThroughputSampler& throughput_sampler);\n\n  void create_read_commands();\n  void adjust_read_thread_count(size_t num_read_threads);\n  uint32_t max_read_parallelism() const;\n\n  void estimate_read_throughput(ThroughputSampler& sampler, size_t num_points_in_last_cycle) const;\n  void estimate_index_throughput(ThroughputSampler& sampler, size_t num_points_in_last_cycle) const;\n\n  DatasetMetadata _dataset_metadata;\n  TilerMetaParameters _meta_parameters;\n  SamplingStrategy _sampling_strategy;\n  ProgressReporter* _progress_reporter;\n  MultiReaderPointSource _point_source;\n  PointsPersistence& _persistence;\n\n  AABB _bounds;\n\n  const PointAttributes& _input_attributes;\n  fs::path _output_directory;\n\n  PointBuffer _points_cache_for_producers, _points_cache_for_consumers;\n  size_t _produced_points_count;\n\n  std::deque<ReadCommand> _remaining_read_commands;\n  std::vector<ReadCommand> _next_read_commands_per_thread;\n\n  std::unique_ptr<TilingAlgorithmBase> _tiling_algorithm;\n\n  Semaphore _producers, _consumers;\n\n  std::chrono::high_resolution_clock::time_point _begin_read_cycle_time;\n  std::chrono::high_resolution_clock::time_point _begin_index_cycle_time;\n};", "meta": {"hexsha": "8ee93ac35a1f53408705117635439af0dfedf144", "size": 4259, "ext": "h", "lang": "C", "max_stars_repo_path": "schwarzwald/core/process/Tiler.h", "max_stars_repo_name": "igd-geo/schwarzwald", "max_stars_repo_head_hexsha": "e3e041f87c93985394444ee056ce8ba7ae62194b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2021-01-06T14:16:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T00:15:17.000Z", "max_issues_repo_path": "schwarzwald/core/process/Tiler.h", "max_issues_repo_name": "igd-geo/schwarzwald", "max_issues_repo_head_hexsha": "e3e041f87c93985394444ee056ce8ba7ae62194b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-25T08:37:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T06:28:06.000Z", "max_forks_repo_path": "schwarzwald/core/process/Tiler.h", "max_forks_repo_name": "igd-geo/schwarzwald", "max_forks_repo_head_hexsha": "e3e041f87c93985394444ee056ce8ba7ae62194b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T13:50:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T11:45:45.000Z", "avg_line_length": 28.9727891156, "max_line_length": 100, "alphanum_fraction": 0.751819676, "num_tokens": 929, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31405054499180746, "lm_q2_score": 0.01883313168021146, "lm_q1q2_score": 0.0059145552680728835}}
{"text": "/* Author:  G. Jungman */\n\n        \n/* Convenience header */\n#ifndef __GSL_SPECFUNC_H__\n#define __GSL_SPECFUNC_H__\n\n#if !defined( GSL_FUN )\n#  if !defined( GSL_DLL )\n#    define GSL_FUN extern\n#  elif defined( BUILD_GSL_DLL )\n#    define GSL_FUN extern __declspec(dllexport)\n#  else\n#    define GSL_FUN extern __declspec(dllimport)\n#  endif\n#endif\n\n#include <gsl/gsl_sf.h>\n\n#endif /* __GSL_SPECFUNC_H__ */\n", "meta": {"hexsha": "f52c4e2f387413b4da691d6fcbf6d4e3bfa3024e", "size": 406, "ext": "h", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_specfunc.h", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-28T08:20:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-28T08:20:20.000Z", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_specfunc.h", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_specfunc.h", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-14T12:45:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-14T12:45:35.000Z", "avg_line_length": 19.3333333333, "max_line_length": 48, "alphanum_fraction": 0.6995073892, "num_tokens": 117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.1895211004851209, "lm_q2_score": 0.031143829073493886, "lm_q1q2_score": 0.005902412759329065}}
{"text": "#ifndef __SAMPLE_H__\n#define __SAMPLE_H__\n\n#include <gsl/gsl_rng.h>\n#include <pthread.h>\n#include <stdint.h>\n\n#include \"parse_mmaps.h\"\n\n#define NUM_USER_LOCKS 2000\n\nstruct sample_thread_info;\nstruct index_update;\nstruct sample_threads;\n\n/* Thread utility functions */\n\nvoid initialize_threads(struct sample_threads* sample_threads, int num_threads,\n\t\t\tconst struct mmap_info* mmap_info);\nvoid destroy_threads(struct sample_threads* sample_threads);\n\n/* Resampling functions */\n\n/* Set all topic and POV assignments to -1, not doing any index\n   updates. Used before initializing topics and POVs.*/\nvoid resample_null(struct sample_threads* sample_threads);\n/* Initialize topic and POV assignments by sampling them uniformly at\n   random and performing index updates. */\nvoid resample_uniform(struct sample_threads* sample_threads);\n\n/* Re-sample topics and POVs. One iteration of Gibbs sampling. */\nvoid resample(struct sample_threads* sample_threads);\n/* Re-sample assignments, but (approximately) in the opposite order as\n   resample(). Used during model selection. */\nvoid resample_reverse(struct sample_threads* sample_threads);\n\n/* Rather than re-sampling randomly, always choose the maximum\n   probability assignment. Useful for finding a high probability\n   assignment of topics and POVs after random sampling. */\nvoid resample_maximize(struct sample_threads* sample_threads);\n/* Restore a set of assignments, updating indexes as necessary */\nvoid resample_restore(struct sample_threads* sample_threads, \n\t\t      const struct revision_assignment* revision_assignments);\n/* Set all topic and POV assignments to -1, subtracting the\n   assignments from indexes. Primarily useful for verifying that\n   indexes were correct. */\nvoid resample_zero(struct sample_threads* sample_threads);\n\n/* Parallel probability computations */\n\n/* Compute the log probability of transitioning to the specified\n   assignments from the current assignments (don't actually transition\n   to them). */\ndouble transition_probability(struct sample_threads* sample_threads,\n\t\t\t      const struct revision_assignment* revision_assignments);\n/* Compute the likelihood of the current model and topic/POV\n   assignments */\ndouble parallel_log_likelihood(struct sample_threads* sample_threads);\n\n/* Other miscellaneous parallel utility routines */\n\n/* Set all of the user topic/POV distributions to alpha. Used during\n   initialization. */\nvoid parallel_initialize_user_topics(struct sample_threads* sample_threads);\n\n/* Structs to hold synchronization and thread information. */\n\nstruct sample_thread_info {\n  /* Each thread gets its own random number generator, initialized\n     with a different seed. */\n  gsl_rng* rand_gen;\n\n  /* A num_topics * num_povs_per_topic array which threads use to\n     sample new topic and POV assignments. */\n  double* sampling_array;\n\n  /* Each thread gets its own copy of mmap_info, allowing us to\n     replace topic_index_mmap with a private copy which is manually\n     synchronized. */\n  struct mmap_info mmap_info;\n\n  // Sample only pages numbered (page# % mod_n) == sample_pages\n  int sample_pages;\n  int mod_n;\n\n  // Information about the current thread.\n  pthread_t thread;\n\n  /* An array of locks to synchronize access and updates to user\n     topic/POV distributions. For a given user's topic and POV\n     distribution, the lock to use is userid % NUM_USER_LOCKS. */\n  pthread_rwlock_t* user_locks;\n\n  /* Memory accounting for the topic_index_mmap copy, if any. One\n     thread updates the original, and so does not have a specially\n     allocated topic index, in which case allocated_topic_dist will be\n     NULL. */\n  char* allocated_topic_dist;\n\n  /* The index of the first position in the topic index update queue\n     that we have not read. */\n  int64_t last_queue_position;\n\n  /* Pointers to the global topic index update queue, and the global\n     position of the first empty slot in the queue. Access to the\n     queue location is synchronized with queue_lock. */\n  struct index_update* index_update_queue;\n  int64_t* queue_location;\n  pthread_mutex_t* queue_lock;\n\n  /* Generally +1 or -1, indicating whether sampling is forward or\n     backward. */\n  int increment;\n\n  /* Helper functions to specify sampling behavior, replacing small or\n     large parts of the sampling routine. */\n  void (*revision_callback) (struct sample_thread_info*, int64_t);\n  void (*index_update_function) (const struct mmap_info* mmap_info, \n\t\t\t\t const struct index_update* patch);\n  void (*sample_function) (const double* sampling_array,\n\t\t\t   double probability_sum,\n\t\t\t   int num_topics, int pov_per_topic,\n\t\t\t   int* chosen_topic, int* chosen_pov,\n\t\t\t   gsl_rng* rand_gen);\n\n  /* When computing transition probabilities, these assignments\n     specify which assignments the transition is to. */\n  const struct revision_assignment* reference_assignments;\n\n  double output;\n};\n\nstruct sample_threads {\n  struct sample_thread_info* thread_info;\n  pthread_mutex_t queue_lock;\n  pthread_rwlock_t user_locks[NUM_USER_LOCKS];\n  int num_threads;\n\n  struct index_update* index_update_queue;\n  // One past the last value in the queue\n  int64_t queue_location;\n};\n\n#endif\n", "meta": {"hexsha": "590b9832bae0aad642f034e816108be8367aa4ae", "size": 5167, "ext": "h", "lang": "C", "max_stars_repo_path": "src/sample.h", "max_stars_repo_name": "allenlavoie/topic-pov", "max_stars_repo_head_hexsha": "c727087d0ac2d440d4e70fbea0c3342c3c734073", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T17:04:56.000Z", "max_stars_repo_stars_event_max_datetime": "2015-01-05T17:04:56.000Z", "max_issues_repo_path": "src/sample.h", "max_issues_repo_name": "allenlavoie/topic-pov", "max_issues_repo_head_hexsha": "c727087d0ac2d440d4e70fbea0c3342c3c734073", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sample.h", "max_forks_repo_name": "allenlavoie/topic-pov", "max_forks_repo_head_hexsha": "c727087d0ac2d440d4e70fbea0c3342c3c734073", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.6344827586, "max_line_length": 79, "alphanum_fraction": 0.7673698471, "num_tokens": 1079, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869689484852374, "lm_q2_score": 0.014063625209518489, "lm_q1q2_score": 0.0058883962055388105}}
{"text": "//\n//  editor.hpp\n//  PretendToWork\n//\n//  Created by tqtifnypmb on 14/12/2017.\n//  Copyright \u00a9 2017 tqtifnypmb. All rights reserved.\n//\n\n#pragma once\n\n#include \"../crdt/Engine.h\"\n#include \"../types.h\"\n\n#include <memory>\n#include <gsl/gsl>\n#include <map>\n\nnamespace brick\n{\n \nclass Rope;\nclass Editor {\npublic:\n    \n    using DeltaList = std::vector<std::tuple<Revision, size_t, size_t>>;     // [(delta, begRow, endRow)]\n    using SyncCb = std::function<void(const Editor::DeltaList& deltaList)>;\n    \n    Editor(size_t viewId, const detail::CodePointList& cplist, SyncCb syncCb);\n    Editor(size_t viewId, SyncCb syncCb);\n    \n    template <class Converter>\n    void insert(gsl::span<const char> bytes, size_t pos);\n    void insert(const detail::CodePointList& cplist, size_t pos);\n    void erase(Range range);\n    void undo();\n    \n    void sync(Editor& editor);\n    \n    std::map<size_t, detail::CodePointList> region(size_t begLine, size_t endLine);\n    \n    void clearRevisions() {\n        engine_.revisions().clear();\n    }\n    \nprivate:\n    Editor::DeltaList convertEngineDelta(const Engine::DeltaList& deltas);\n    \n    void updateLines(size_t pos, const detail::CodePointList& cplist);\n    void updateLines(Range r);\n    \n    std::unique_ptr<Rope> rope_;\n    Engine engine_;\n    std::vector<size_t> linesIndex_;\n    SyncCb sync_cb_;\n};\n    \ntemplate <class Converter>\nvoid Editor::insert(gsl::span<const char> bytes, size_t pos) {\n    insert(Converter::encode(bytes), pos);\n}\n    \n}   // namespace brick\n", "meta": {"hexsha": "f239c1c2f19a1d19dd6bf39dddb1353ff41d9158", "size": 1514, "ext": "h", "lang": "C", "max_stars_repo_path": "src/editor/Editor.h", "max_stars_repo_name": "tqtifnypmb/brick", "max_stars_repo_head_hexsha": "49398f77113c57d4e256e838a5ad6b9a6381de6a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/editor/Editor.h", "max_issues_repo_name": "tqtifnypmb/brick", "max_issues_repo_head_hexsha": "49398f77113c57d4e256e838a5ad6b9a6381de6a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/editor/Editor.h", "max_forks_repo_name": "tqtifnypmb/brick", "max_forks_repo_head_hexsha": "49398f77113c57d4e256e838a5ad6b9a6381de6a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0317460317, "max_line_length": 105, "alphanum_fraction": 0.6657859974, "num_tokens": 405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2254166262422842, "lm_q2_score": 0.02595735437213755, "lm_q1q2_score": 0.005851219248742652}}
{"text": "/*\n   Copyright [2020] [IBM Corporation]\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n       http://www.apache.org/licenses/LICENSE-2.0\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\n#ifndef _MCAS_COMMON_BYTE_SPAN_\n#define _MCAS_COMMON_BYTE_SPAN_\n\n#include <common/pointer_cast.h>\n#include <cstddef>\n#include <gsl/gsl_byte>\n#include <gsl/span>\n#include <sys/uio.h>\n\n#ifndef MCAS_SPAN_USES_GSL\n/* For minimal difference with older code; implement span as iovec (not gsl::span) */\n#define MCAS_SPAN_USES_GSL 0\n#endif\n#ifndef MCAS_BYTE_USES_STD\n/* For compilcation with C++14, use gsl::byte, not C++17 std::byte */\n#define MCAS_BYTE_USES_STD 0\n#endif\n\nnamespace common\n{\n#if MCAS_BYTE_USES_STD\n\tusing byte = std::byte;\n#else\n\tusing byte = gsl::byte; /* can be std::byte in C++17 */\n#endif\n\ttemplate <typename T> using span = gsl::span<T>; /* can be std::span in C++20 */\n\t/* span of a const area. No equivalent in ::iovec, so always use span */\n\tusing const_byte_span = span<const byte>;\n\tinline const_byte_span make_const_byte_span(const void *base, std::size_t len)\n    {\n      return const_byte_span(static_cast<const_byte_span::pointer>(base), len);\n    }\n}\n\nnamespace\n{\n\t/* Accessors: Non-member in order to match ::iovec accessors */\n\t/* Start of area as a void *, for use with %p format and for conversion to an arbitrary type */\n\tinline const void *base(const common::const_byte_span &r) { return r.data(); }\n    /* Length of area in bytes, for use in byte-based address calculations and comparisons */\n\tinline std::size_t size(const common::const_byte_span &r) { return r.size(); }\n\t/* Start of area as byte *, for use in byte-based address calculations and comparisons */\n\tinline const common::byte *data(const common::const_byte_span &r) { return r.data(); }\n\t/* End of area as byte *, for use in byte-based address calculations and comparisons */\n\tinline const common::byte *data_end(const common::const_byte_span &r) { return r.data() + r.size(); }\n\t/* End of are as a void *, for use with %p format */\n\tinline const void *end(const common::const_byte_span &r) { return ::data_end(r); }\n}\n\nnamespace\n{\n\t/* Same accessors as above, for ::iovec */\n\tinline void *base(const ::iovec &r) { return r.iov_base; }\n\tinline std::size_t size(const ::iovec &r) { return r.iov_len; }\n\tinline common::byte *data(const ::iovec &r) { return static_cast<common::byte *>(::base(r)); }\n\tinline common::byte *data_end(const ::iovec &r) { return ::data(r) + ::size(r); }\n\tinline void *end(const ::iovec &r) { return ::data_end(r); }\n}\n\nnamespace common\n{\n\tinline constexpr ::iovec make_iovec(void *base, std::size_t len) { return ::iovec{base, len}; }\n}\n\n#if MCAS_SPAN_USES_GSL\n#include <common/pointer_cast.h>\nnamespace common\n{\n\tusing byte_span = span<byte>;\n}\n\nnamespace\n{\n\t/* Same accessors as above, for non-const byte span */\n\tinline void *base(const common::byte_span &r) { return r.data(); }\n\tinline std::size_t size(const common::byte_span &r) { return r.size(); }\n\tinline common::byte *data(const common::byte_span &r) { return r.data(); }\n\tinline common::byte *data_end(const common::byte_span &r) { return ::data(r) + ::size(r); }\n\tinline void *end(const common::byte_span &r) { return ::data_end(r); }\n}\n\nnamespace common\n{\n\t/* Construct a byte_span in syntax compatible with iovec (function, not constructor) */\n\tinline byte_span make_byte_span(void *base, std::size_t len) { return byte_span(common::pointer_cast<byte_span::value_type>(base), len); }\n}\n#else /* ! MCAS_SPAN_USES_GSL */\nnamespace common\n{\n\tusing byte_span = ::iovec;\n\t/* Construct an iovec in syntax compatible with span (no braces) */\n\tinline byte_span make_byte_span(void *base, std::size_t len) { return byte_span{base, len}; }\n}\n#endif\n\nnamespace common\n{\n\t/* Converion from span of non-const to span of const */\n\tinline const_byte_span make_const_byte_span(const byte_span s) { return const_byte_span(::data(s), ::size(s)); }\n}\n\n#endif\n", "meta": {"hexsha": "6fee0c69438faed6159cf16c4969591b51c4fc9f", "size": 4322, "ext": "h", "lang": "C", "max_stars_repo_path": "src/lib/common/include/common/byte_span.h", "max_stars_repo_name": "moshik1/mcas", "max_stars_repo_head_hexsha": "a6af06bc278993fb3ffe780f230d2396b2287c26", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 60.0, "max_stars_repo_stars_event_min_datetime": "2020-04-28T08:15:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T10:35:15.000Z", "max_issues_repo_path": "src/lib/common/include/common/byte_span.h", "max_issues_repo_name": "moshik1/mcas", "max_issues_repo_head_hexsha": "a6af06bc278993fb3ffe780f230d2396b2287c26", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 66.0, "max_issues_repo_issues_event_min_datetime": "2020-09-03T23:40:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T20:34:52.000Z", "max_forks_repo_path": "src/lib/common/include/common/byte_span.h", "max_forks_repo_name": "moshik1/mcas", "max_forks_repo_head_hexsha": "a6af06bc278993fb3ffe780f230d2396b2287c26", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2019-11-02T06:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T01:56:42.000Z", "avg_line_length": 37.2586206897, "max_line_length": 139, "alphanum_fraction": 0.7147154095, "num_tokens": 1125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15203222625389934, "lm_q2_score": 0.038466193396180445, "lm_q1q2_score": 0.005848101017534354}}
{"text": "/* vector/gsl_vector_long_double.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_VECTOR_LONG_DOUBLE_H__\n#define __GSL_VECTOR_LONG_DOUBLE_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_block_long_double.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size;\n  size_t stride;\n  long double *data;\n  gsl_block_long_double *block;\n  int owner;\n} \ngsl_vector_long_double;\n\ntypedef struct\n{\n  gsl_vector_long_double vector;\n} _gsl_vector_long_double_view;\n\ntypedef _gsl_vector_long_double_view gsl_vector_long_double_view;\n\ntypedef struct\n{\n  gsl_vector_long_double vector;\n} _gsl_vector_long_double_const_view;\n\ntypedef const _gsl_vector_long_double_const_view gsl_vector_long_double_const_view;\n\n\n/* Allocation */\n\nGSL_EXPORT gsl_vector_long_double *gsl_vector_long_double_alloc (const size_t n);\nGSL_EXPORT gsl_vector_long_double *gsl_vector_long_double_calloc (const size_t n);\n\nGSL_EXPORT gsl_vector_long_double *gsl_vector_long_double_alloc_from_block (gsl_block_long_double * b,\n                                                                           const size_t offset,\n                                                                           const size_t n,\n                                                                           const size_t stride);\n\nGSL_EXPORT gsl_vector_long_double *gsl_vector_long_double_alloc_from_vector (gsl_vector_long_double * v,\n                                                                            const size_t offset,\n                                                                            const size_t n,\n                                                                            const size_t stride);\n\nGSL_EXPORT void gsl_vector_long_double_free (gsl_vector_long_double * v);\n\n/* Views */\n\nGSL_EXPORT\n_gsl_vector_long_double_view\ngsl_vector_long_double_view_array (long double *v, size_t n);\n\nGSL_EXPORT\n_gsl_vector_long_double_view\ngsl_vector_long_double_view_array_with_stride (long double *base,\n                                         size_t stride,\n                                         size_t n);\n\nGSL_EXPORT\n_gsl_vector_long_double_const_view\ngsl_vector_long_double_const_view_array (const long double *v, size_t n);\n\nGSL_EXPORT\n_gsl_vector_long_double_const_view\ngsl_vector_long_double_const_view_array_with_stride (const long double *base,\n                                               size_t stride,\n                                               size_t n);\n\nGSL_EXPORT\n_gsl_vector_long_double_view\ngsl_vector_long_double_subvector (gsl_vector_long_double *v,\n                            size_t i,\n                            size_t n);\n\nGSL_EXPORT\n_gsl_vector_long_double_view\ngsl_vector_long_double_subvector_with_stride (gsl_vector_long_double *v,\n                                        size_t i,\n                                        size_t stride,\n                                        size_t n);\n\nGSL_EXPORT\n_gsl_vector_long_double_const_view\ngsl_vector_long_double_const_subvector (const gsl_vector_long_double *v,\n                                  size_t i,\n                                  size_t n);\n\nGSL_EXPORT\n_gsl_vector_long_double_const_view\ngsl_vector_long_double_const_subvector_with_stride (const gsl_vector_long_double *v,\n                                              size_t i,\n                                              size_t stride,\n                                              size_t n);\n\n/* Operations */\n\nGSL_EXPORT long double gsl_vector_long_double_get (const gsl_vector_long_double * v, const size_t i);\nGSL_EXPORT void gsl_vector_long_double_set (gsl_vector_long_double * v, const size_t i, long double x);\n\nGSL_EXPORT long double *gsl_vector_long_double_ptr (gsl_vector_long_double * v, const size_t i);\nGSL_EXPORT const long double *gsl_vector_long_double_const_ptr (const gsl_vector_long_double * v, const size_t i);\n\nGSL_EXPORT void gsl_vector_long_double_set_zero (gsl_vector_long_double * v);\nGSL_EXPORT void gsl_vector_long_double_set_all (gsl_vector_long_double * v, long double x);\nGSL_EXPORT int gsl_vector_long_double_set_basis (gsl_vector_long_double * v, size_t i);\n\nGSL_EXPORT int gsl_vector_long_double_fread (FILE * stream, gsl_vector_long_double * v);\nGSL_EXPORT int gsl_vector_long_double_fwrite (FILE * stream, const gsl_vector_long_double * v);\nGSL_EXPORT int gsl_vector_long_double_fscanf (FILE * stream, gsl_vector_long_double * v);\nGSL_EXPORT int gsl_vector_long_double_fprintf (FILE * stream, const gsl_vector_long_double * v,\n                                               const char *format);\n\nGSL_EXPORT int gsl_vector_long_double_memcpy (gsl_vector_long_double * dest, const gsl_vector_long_double * src);\n\nGSL_EXPORT int gsl_vector_long_double_reverse (gsl_vector_long_double * v);\n\nGSL_EXPORT int gsl_vector_long_double_swap (gsl_vector_long_double * v, gsl_vector_long_double * w);\nGSL_EXPORT int gsl_vector_long_double_swap_elements (gsl_vector_long_double * v, const size_t i, const size_t j);\n\nGSL_EXPORT long double gsl_vector_long_double_max (const gsl_vector_long_double * v);\nGSL_EXPORT long double gsl_vector_long_double_min (const gsl_vector_long_double * v);\nGSL_EXPORT void gsl_vector_long_double_minmax (const gsl_vector_long_double * v, long double * min_out, long double * max_out);\n\nGSL_EXPORT size_t gsl_vector_long_double_max_index (const gsl_vector_long_double * v);\nGSL_EXPORT size_t gsl_vector_long_double_min_index (const gsl_vector_long_double * v);\nGSL_EXPORT void gsl_vector_long_double_minmax_index (const gsl_vector_long_double * v, size_t * imin, size_t * imax);\n\nGSL_EXPORT int gsl_vector_long_double_add (gsl_vector_long_double * a, const gsl_vector_long_double * b);\nGSL_EXPORT int gsl_vector_long_double_sub (gsl_vector_long_double * a, const gsl_vector_long_double * b);\nGSL_EXPORT int gsl_vector_long_double_mul (gsl_vector_long_double * a, const gsl_vector_long_double * b);\nGSL_EXPORT int gsl_vector_long_double_div (gsl_vector_long_double * a, const gsl_vector_long_double * b);\nGSL_EXPORT int gsl_vector_long_double_scale (gsl_vector_long_double * a, const double x);\nGSL_EXPORT int gsl_vector_long_double_add_constant (gsl_vector_long_double * a, const double x);\n\nGSL_EXPORT int gsl_vector_long_double_isnull (const gsl_vector_long_double * v);\n\n#ifdef HAVE_INLINE\n\nextern inline\nlong double\ngsl_vector_long_double_get (const gsl_vector_long_double * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_VAL (\"index out of range\", GSL_EINVAL, 0);\n    }\n#endif\n  return v->data[i * v->stride];\n}\n\nextern inline\nvoid\ngsl_vector_long_double_set (gsl_vector_long_double * v, const size_t i, long double x)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_VOID (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  v->data[i * v->stride] = x;\n}\n\nextern inline\nlong double *\ngsl_vector_long_double_ptr (gsl_vector_long_double * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return (long double *) (v->data + i * v->stride);\n}\n\nextern inline\nconst long double *\ngsl_vector_long_double_const_ptr (const gsl_vector_long_double * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return (const long double *) (v->data + i * v->stride);\n}\n\n\n#endif /* HAVE_INLINE */\n\n__END_DECLS\n\n#endif /* __GSL_VECTOR_LONG_DOUBLE_H__ */\n\n\n", "meta": {"hexsha": "4c506578f482bdcd2a9d07ce4a5a65aa18e21483", "size": 8473, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/gsl/include/gsl/gsl_vector_long_double.h", "max_stars_repo_name": "dynaryu/vaws", "max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/gsl/include/gsl/gsl_vector_long_double.h", "max_issues_repo_name": "dynaryu/vaws", "max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/gsl/include/gsl/gsl_vector_long_double.h", "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0553191489, "max_line_length": 127, "alphanum_fraction": 0.7037649003, "num_tokens": 1904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3140505578320071, "lm_q2_score": 0.018546565766601044, "lm_q1q2_score": 0.005824559324869064}}
{"text": "#include \"constants.h\"\n#include \"artisoptions.h\"\n\n#ifndef TYPES_H\n#define TYPES_H\n\n#include <cstdio>\n#include <cstdlib>\n#include <cmath>\n#include <time.h>\n#ifndef __CUDA_ARCH__\n#include <gsl/gsl_rng.h>\n#endif\n//#include <gsl/gsl_sf_expint.h>\n\n\nstruct time\n{\n  double start; // time at start of this timestep.\n  double width; // Width of timestep.\n  double mid; // Mid time in step - computed logarithmically.\n  double gamma_dep; // cmf gamma ray energy deposition rate\n  double positron_dep; // cmf positron energy deposition rate\n  double electron_dep; // cmf positron energy deposition rate\n  double alpha_dep; // cmf positron energy deposition rate\n  double cmf_lum; // cmf luminosity light curve\n  int pellet_decays; // Number of pellets that decay in this time step.\n};\n\n\n/// Coolinglist\n///============================================================================\nenum coolingtype {\n  COOLINGTYPE_FF         = 880,\n  COOLINGTYPE_FB         = 881,\n  COOLINGTYPE_COLLEXC    = 882,\n  COOLINGTYPE_COLLION    = 883,\n};\n\ntypedef struct cellhistorycoolinglist_t\n{\n  enum coolingtype type;\n  int element;\n  int ion;\n  int level;\n  int upperlevel;\n} cellhistorycoolinglist_t;\n\n/*enum heatingtype {\n  HEATINGTYPE_FF         = 884,\n  HEATINGTYPE_BF         = 885,\n  HEATINGTYPE_COLLDEEXC  = 886,\n  HEATINGTYPE_COLLRECOMB = 887,\n};*/\n\ntypedef struct heatingcoolingrates\n{\n  double cooling_collisional;\n  double cooling_fb;\n  double cooling_ff;\n  double cooling_adiabatic;\n  double heating_collisional;\n  double heating_bf;\n  double heating_ff;\n  double heating_dep;\n  double nt_frac_heating; // = heatingrates.gamma / total_gamma_deposition, = get_nt_frac_heating(modelgridindex) when T_e solver runs\n} heatingcoolingrates_t;\n\n\n/// PHIXSLIST\n\ntypedef struct fullphixslist_t\n{\n  double nu_edge;\n  int element;\n  int ion;\n  int level;\n  int phixstargetindex;\n  int index_in_groundphixslist;\n} fullphixslist_t;\n\ntypedef struct groundphixslist_t\n{\n  double nu_edge;\n  //double photoion_contr;\n  double gamma_contr;\n  //double stimrecomb_contr;\n  //double bfheating_contr;\n  int element;\n  int ion;\n  int level;\n  int phixstargetindex;\n} groundphixslist_t;\n\n\ntypedef struct phixslist_t\n{\n  groundphixslist_t *groundcont;\n  double *kappa_bf_contr;\n#if (DETAILED_BF_ESTIMATORS_ON)\n  double *gamma_contr;\n#endif\n} phixslist_t;\n\nenum packet_type {\n  TYPE_ESCAPE = 32,\n  TYPE_RADIOACTIVE_PELLET = 100,\n  TYPE_GAMMA = 10,\n  TYPE_RPKT = 11,\n  TYPE_KPKT = 12,\n  TYPE_MA = 13,\n  TYPE_NTLEPTON = 20,\n  TYPE_PRE_KPKT = 120,\n  TYPE_GAMMA_KPKT = 121,\n};\n\nenum cell_boundary {\n  NEG_X = 101,\n  POS_X = 102,\n  NEG_Y = 103,\n  POS_Y = 104,\n  NEG_Z = 105,\n  POS_Z = 106,\n  NONE = 107,\n};\n\ntypedef struct mastate_t\n{\n  int element;              /// macro atom of type element (this is an element index)\n  int ion;                  /// in ionstage ion (this is an ion index)\n  int level;                /// and level=level (this is a level index)\n  int activatingline;       /// Linelistindex of the activating line for bb activated MAs, -99 else.\n} mastate_t;\n\n\ntypedef struct packet\n{\n  int where;      /// The grid cell that the packet is in.\n  enum packet_type type;       /// Identifies the type of packet (k-, r-, etc.)\n  enum cell_boundary last_cross; /// To avoid rounding errors on cell crossing.\n  int interactions;/// debug: number of interactions the packet undergone\n  int nscatterings;   /// records number of electron scatterings a r-pkt undergone since it was emitted\n  int last_event;  /// debug: stores information about the packets history\n  double pos[3];  /// Position of the packet (x,y,z).\n  double dir[3];  /// Direction of propagation. (x,y,z). Always a unit vector.\n  double e_cmf;   /// The energy the packet carries in the co-moving frame.\n  double e_rf;    /// The energy the packet carries in the rest frame.\n  double nu_cmf;  /// The frequency in the co-moving frame.\n  double nu_rf;   /// The frequency in the rest frame.\n  int next_trans;  /// This keeps track of the next possible line interaction of a rpkt by storing\n                   /// its linelist index (to overcome numerical problems in propagating the rpkts).\n  int emissiontype;   /// records how the packet was emitted if it is a r-pkt\n  double em_pos[3];   /// Position of the packet (x,y,z).\n  int em_time;\n  double prop_time; // internal clock to track how far in time the packet has been propagated\n  int absorptiontype;     /// records linelistindex of the last absorption\n                          /// negative values give ff-abs (-1), bf-abs (-2), compton scattering of gammas (-3),\n                          /// photoelectric effect of gammas (-4), pair production of gammas (-5)\n                          /// decaying pellets of the 52Fe chain (-6) and pellets which decayed before the\n                          /// onset of the simulation (-7)\n                          /// decay of a positron pellet (-10)\n  int trueemissiontype;  // emission type coming from a kpkt to rpkt (last thermal emission)\n  int trueem_time;\n  double absorptionfreq;  /// records nu_cmf of packet at last absorption\n  double absorptiondir[3]; /// Direction of propagation (x,y,z) when a packet was last absorbed in a line. Always a unit vector.\n  //short timestep;\n  double stokes[3]; //I, Q and U Stokes parameters\n  double pol_dir[3]; //unit vector which defines the coordinate system against which Q and U are measured; should always be perpendicular to dir\n  double tdecay;  /// Time at which pellet decays.\n  enum packet_type escape_type; /// Flag to tell us in which form it escaped from the grid.\n  int escape_time; /// Time at which is passes out of the grid.\n                   /// Pos, dir, where, e_rf, nu_rf should all remain set at the exit point.\n  int scat_count;  /// WHAT'S THAT???\n  int number;     /// A unique number to identify which packet caused potential troubles.\n  bool originated_from_particlenotgamma;    // first-non-pellet packet type was gamma\n  int pellet_decaytype;           // index into decay::decaytypes\n  int pellet_nucindex;           // nuclide index of the decaying species\n  float trueemissionvelocity;\n  mastate_t mastate;\n} PKT;\n\nenum ma_action {\n  /// Radiative deexcitation rate from this level.\n  MA_ACTION_RADDEEXC = 0,\n  /// Collisional deexcitation rate from this level.\n  MA_ACTION_COLDEEXC = 1,\n  /// Radiative recombination from this level.\n  MA_ACTION_RADRECOMB = 2,\n  /// Collisional recombination rate from this level.\n  MA_ACTION_COLRECOMB = 3,\n  /// Rate for internal downward transitions to same ionisation stage.\n  MA_ACTION_INTERNALDOWNSAME = 4,\n  /// Rate for internal upward transitions to same ionisation stage.\n  MA_ACTION_INTERNALDOWNLOWER = 5,\n  /// Rate for internal downward transitions to lower ionisation stage.\n  MA_ACTION_INTERNALUPSAME = 6,\n  /// Rate for internal upward transitions to higher ionisation stage.\n  MA_ACTION_INTERNALUPHIGHER = 7,\n  /// Rate for internal upward transitions to higher ionisation stage due to non-thermal collisions.\n  MA_ACTION_INTERNALUPHIGHERNT = 8,\n  MA_ACTION_COUNT = 9,\n};\n\n\n/// GRID\n///============================================================================\ntypedef struct compositionlist_entry\n{\n  float abundance;         /// Abundance of the element (by mass!).\n  float *groundlevelpop;   /// Pointer to an array of floats which contains the groundlevel populations\n                           /// of all included ionisation stages for the element.\n  float *partfunct;        /// Pointer to an array of floats which contains the partition functions\n                           /// of all included ionisation stages for the element.\n  //float *ltepartfunct;     /// Pointer to an array of floats which contains the LTE partition functions\n  //                         /// of all included ionisation stages for the element.\n} compositionlist_entry;\n\ntypedef struct gridcell\n{\n  double pos_init[3]; /// Initial co-ordinates of inner most corner of cell.\n  // int xyz[3];         /// Integer position of cell in grid.\n  int modelgridindex;\n} CELL;\n\ntypedef struct mgicooling_t\n{\n  double *contrib;\n} mgicooling_t;\n\n\n#define NSYN 1 /* number of frequency points in syn calculation */\n\nenum ray_status {\n  ACTIVE = 1,\n  WAITING = 2,\n  FINISHED = 3,\n};\n\ntypedef struct syn_ray\n{\n  double tstart; /* time at which the ray enters the grid */\n  double rstart[3]; /* vector position at which the ray enters the grid */\n  double pos[3]; /* current position of the ray */\n  double nu_rf[NSYN]; /*rest frame frequencies of rays */\n  double nu_rf_init[NSYN]; /*rest frame frequencies of rays at start - for a test only */\n  double nu_cmf[NSYN]; /*cmf freqencies */\n  double e_rf[NSYN]; /*rest frame energy of rays */\n  double e_cmf[NSYN]; /* cmf energies of rays */\n  int where; /* the grid cell the ray is in */\n  int lindex[NSYN]; /* array of ray positions in the line list */\n  enum cell_boundary last_cross; /* last boundary crossed */\n  enum ray_status status; /*WAITING, then ACTIVE then FINISHED*/\n} RAY;\n\n\n\n/// ATOMIC DATA\n///============================================================================\n\ntypedef struct phixstarget_entry\n{\n  double *spontrecombcoeff;\n  #if (!NO_LUT_PHOTOION)\n    double *corrphotoioncoeff;\n  #endif\n  #if (!NO_LUT_BFHEATING)\n  double *bfheating_coeff;\n  #endif\n  double *bfcooling_coeff;\n\n  double probability;        // fraction of phixs cross section leading to this final level\n  int levelindex;         // index of upper ion level after photoionisation\n} phixstarget_entry;\n\n\ntypedef struct levellist_entry\n{\n  double epsilon;                            /// Excitation energy of this level relative to the neutral ground level.\n  int *uptrans_lineindicies;    /// Allowed upward transitions from this level\n  int *downtrans_lineindicies;  /// Allowed downward transitions from this level\n  int nuptrans;\n  int ndowntrans;\n  double phixs_threshold;                    /// Energy of first point in the photion_xs table\n  phixstarget_entry *phixstargets;  /// pointer to table of target states and probabilities\n  float *photoion_xs;               /// Pointer to a lookup-table providing photoionisation cross-sections for this level.\n  int nphixstargets;                         /// length of phixstargets array:\n  float stat_weight;                           /// Statistical weight of this level.\n\n  int cont_index;                            /// Index of the continuum associated to this level. Negative number.\n#if (!NO_LUT_PHOTOION || !NO_LUT_BFHEATING)\n  int closestgroundlevelcont;\n#endif\n\n  bool metastable;                            ///\n\n//  double photoion_xs_nu_edge;              /// nu of the first grid point in the photoion_xs lookup-table.\n\n//double *spontrecombcoeff_E;\n//double *photoioncoeff_below;\n//double *photoioncoeff_above;\n//double *corrphotoioncoeff_above;\n//double *bfheating_coeff_above;\n//double *stimulated_bfcooling_coeff;\n//double *stimulated_recomb_coeff;\n\n//float *modified_spontrecombcoeff;\n//float *stimrecombcoeff;\n//float *modified_stimrecombcoeff;\n\n///float population;\n///float sahafact;\n///float spontaneousrecomb_ratecoeff;\n///float modifiedspontaneousrecomb_ratecoeff;\n///float corrphotoion_ratecoeff;\n///float modifiedcorrphotoion_ratecoeff;\n\n/// time dependent macroatom event rates\n//double rad_deexc;                          /// Radiative deexcitation rate from this level.\n//double internal_down_same;                 /// Rate for internal downward transitions within the same ionisation stage.\n//double internal_up_same;                   /// Rate for internal upward transitions within the same ionisation stage.\n\n} levellist_entry;\n\ntypedef struct ionlist_entry\n{\n  levellist_entry *levels;                   /// Carries information for each level: 0,1,...,nlevels-1\n  int ionstage;                              /// Which ionisation stage: XI=0, XII=1, XIII=2, ...\n  int nlevels;                               /// Number of levels for this ionisation stage\n  int nlevels_nlte;                          /// number of nlte levels for this ion\n  int first_nlte;                            /// index into nlte_pops array of a grid cell\n  int ionisinglevels;                        /// Number of levels which have a bf-continuum\n  int maxrecombininglevel;                   /// level index of the highest level with a non-zero recombination rate\n  int nlevels_groundterm;\n  int coolingoffset;\n  int ncoolingterms;\n  int uniqueionindex;\n  float *Alpha_sp;\n  double ionpot;                             /// Ionisation threshold to the next ionstage\n  //int nbfcontinua;\n  //ionsphixslist_t *phixslist;\n} ionlist_entry;\n\ntypedef struct elementlist_entry\n{\n  ionlist_entry *ions;              /// Carries information for each ion: 0,1,...,nions-1\n  int nions;                                 /// Number of ions for the current element\n  int anumber;                               /// Atomic number\n//  int uppermost_ion;                       /// Highest ionisation stage which has a decent population for a given cell\n                                             /// Be aware that this must not be used outside of the update_grid routine\n                                             /// and their daughters. Neither it will work with OpenMP threads.\n  float abundance;                           ///\n  float mass;                                /// Atomic mass number in multiple of MH\n} elementlist_entry;\n\ntypedef struct linelist_entry\n{\n  double nu;                                 /// Frequency of the line transition\n  float einstein_A;\n  float osc_strength;\n  float coll_str;\n  int elementindex;                        /// It's a transition of element (not its atomic number,\n                                           /// but the (x-1)th element included in the simulation.\n  int ionindex;                            /// The same for the elements ion\n  int upperlevelindex;                     /// And the participating upper\n  int lowerlevelindex;                     /// and lower levels\n  bool forbidden;\n} linelist_entry;\n\ntypedef struct bflist_t\n{\n  int elementindex;\n  int ionindex;\n  int levelindex;\n  int phixstargetindex;\n} bflist_t;\n\ntypedef struct nne_solution_paras\n{\n  int cellnumber;\n} nne_solution_paras;\n\ntypedef struct gslintegration_paras\n{\n  double nu_edge;\n  double T;\n  float *photoion_xs;\n} gslintegration_paras;\n\ntypedef struct rpkt_cont_opacity_struct\n{\n  double nu; // frequency at which opacity was calculated\n  double total;\n  double es;\n  double ff;\n  double bf;\n  double ffheating;\n  //double bfheating;\n  int modelgridindex;\n  bool recalculate_required; // e.g. when cell or timestep has changed\n} rpkt_cont_opacity_struct;\n\n/// Cell history\n///============================================================================\n// typedef struct coolinglist_contributions\n// {\n//   double contribution;\n// } coolinglist_contributions;\n\ntypedef struct\n{\n  double corrphotoioncoeff;\n#if (SEPARATE_STIMRECOMB)\n  double stimrecombcoeff;\n#endif\n} chphixstargets_struct;\n\n\ntypedef struct chlevels_struct\n{\n  double processrates[MA_ACTION_COUNT];\n  chphixstargets_struct *chphixstargets;\n  double bfheatingcoeff;\n} chlevels_struct;\n\ntypedef struct chions_struct\n{\n  chlevels_struct *chlevels;              /// Pointer to the ions levellist.\n} chions_struct;\n\ntypedef struct chelements_struct\n{\n  chions_struct *chions;                  /// Pointer to the elements ionlist.\n} chelements_struct;\n\ntypedef struct cellhistory_struct\n{\n  double *cooling_contrib;    /// Cooling contributions by the different processes.\n  chelements_struct *chelements;            /// Pointer to a nested list which helds compositional\n                                            /// information for all the elements=0,1,...,nelements-1\n  int cellnumber;                           /// Identifies the cell the data is valid for.\n  int bfheating_mgi;\n} cellhistory_struct;\n\n\n#endif //TYPES_H\n", "meta": {"hexsha": "0bd872176b11b5d49a40cbe7822782a177e75f43", "size": 15835, "ext": "h", "lang": "C", "max_stars_repo_path": "types.h", "max_stars_repo_name": "artis-mcrt/artis", "max_stars_repo_head_hexsha": "eeb4ba06353a34be949d9662ab300a78f852ebdb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-04-12T12:09:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T21:56:21.000Z", "max_issues_repo_path": "types.h", "max_issues_repo_name": "artis-mcrt/artis", "max_issues_repo_head_hexsha": "eeb4ba06353a34be949d9662ab300a78f852ebdb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-11-17T09:37:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-17T15:03:17.000Z", "max_forks_repo_path": "types.h", "max_forks_repo_name": "artis-mcrt/artis", "max_forks_repo_head_hexsha": "eeb4ba06353a34be949d9662ab300a78f852ebdb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5044843049, "max_line_length": 144, "alphanum_fraction": 0.6651720871, "num_tokens": 3786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37754065479083276, "lm_q2_score": 0.01542455474084874, "lm_q1q2_score": 0.005823396496717077}}
{"text": "/* vector/gsl_vector_long_double.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_VECTOR_LONG_DOUBLE_H__\n#define __GSL_VECTOR_LONG_DOUBLE_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_inline.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_block_long_double.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size;\n  size_t stride;\n  long double *data;\n  gsl_block_long_double *block;\n  int owner;\n} \ngsl_vector_long_double;\n\ntypedef struct\n{\n  gsl_vector_long_double vector;\n} _gsl_vector_long_double_view;\n\ntypedef _gsl_vector_long_double_view gsl_vector_long_double_view;\n\ntypedef struct\n{\n  gsl_vector_long_double vector;\n} _gsl_vector_long_double_const_view;\n\ntypedef const _gsl_vector_long_double_const_view gsl_vector_long_double_const_view;\n\n\n/* Allocation */\n\ngsl_vector_long_double *gsl_vector_long_double_alloc (const size_t n);\ngsl_vector_long_double *gsl_vector_long_double_calloc (const size_t n);\n\ngsl_vector_long_double *gsl_vector_long_double_alloc_from_block (gsl_block_long_double * b,\n                                                     const size_t offset, \n                                                     const size_t n, \n                                                     const size_t stride);\n\ngsl_vector_long_double *gsl_vector_long_double_alloc_from_vector (gsl_vector_long_double * v,\n                                                      const size_t offset, \n                                                      const size_t n, \n                                                      const size_t stride);\n\nvoid gsl_vector_long_double_free (gsl_vector_long_double * v);\n\n/* Views */\n\n_gsl_vector_long_double_view \ngsl_vector_long_double_view_array (long double *v, size_t n);\n\n_gsl_vector_long_double_view \ngsl_vector_long_double_view_array_with_stride (long double *base,\n                                         size_t stride,\n                                         size_t n);\n\n_gsl_vector_long_double_const_view \ngsl_vector_long_double_const_view_array (const long double *v, size_t n);\n\n_gsl_vector_long_double_const_view \ngsl_vector_long_double_const_view_array_with_stride (const long double *base,\n                                               size_t stride,\n                                               size_t n);\n\n_gsl_vector_long_double_view \ngsl_vector_long_double_subvector (gsl_vector_long_double *v, \n                            size_t i, \n                            size_t n);\n\n_gsl_vector_long_double_view \ngsl_vector_long_double_subvector_with_stride (gsl_vector_long_double *v, \n                                        size_t i,\n                                        size_t stride,\n                                        size_t n);\n\n_gsl_vector_long_double_const_view \ngsl_vector_long_double_const_subvector (const gsl_vector_long_double *v, \n                                  size_t i, \n                                  size_t n);\n\n_gsl_vector_long_double_const_view \ngsl_vector_long_double_const_subvector_with_stride (const gsl_vector_long_double *v, \n                                              size_t i, \n                                              size_t stride,\n                                              size_t n);\n\n/* Operations */\n\nvoid gsl_vector_long_double_set_zero (gsl_vector_long_double * v);\nvoid gsl_vector_long_double_set_all (gsl_vector_long_double * v, long double x);\nint gsl_vector_long_double_set_basis (gsl_vector_long_double * v, size_t i);\n\nint gsl_vector_long_double_fread (FILE * stream, gsl_vector_long_double * v);\nint gsl_vector_long_double_fwrite (FILE * stream, const gsl_vector_long_double * v);\nint gsl_vector_long_double_fscanf (FILE * stream, gsl_vector_long_double * v);\nint gsl_vector_long_double_fprintf (FILE * stream, const gsl_vector_long_double * v,\n                              const char *format);\n\nint gsl_vector_long_double_memcpy (gsl_vector_long_double * dest, const gsl_vector_long_double * src);\n\nint gsl_vector_long_double_reverse (gsl_vector_long_double * v);\n\nint gsl_vector_long_double_swap (gsl_vector_long_double * v, gsl_vector_long_double * w);\nint gsl_vector_long_double_swap_elements (gsl_vector_long_double * v, const size_t i, const size_t j);\n\nlong double gsl_vector_long_double_max (const gsl_vector_long_double * v);\nlong double gsl_vector_long_double_min (const gsl_vector_long_double * v);\nvoid gsl_vector_long_double_minmax (const gsl_vector_long_double * v, long double * min_out, long double * max_out);\n\nsize_t gsl_vector_long_double_max_index (const gsl_vector_long_double * v);\nsize_t gsl_vector_long_double_min_index (const gsl_vector_long_double * v);\nvoid gsl_vector_long_double_minmax_index (const gsl_vector_long_double * v, size_t * imin, size_t * imax);\n\nint gsl_vector_long_double_add (gsl_vector_long_double * a, const gsl_vector_long_double * b);\nint gsl_vector_long_double_sub (gsl_vector_long_double * a, const gsl_vector_long_double * b);\nint gsl_vector_long_double_mul (gsl_vector_long_double * a, const gsl_vector_long_double * b);\nint gsl_vector_long_double_div (gsl_vector_long_double * a, const gsl_vector_long_double * b);\nint gsl_vector_long_double_scale (gsl_vector_long_double * a, const long double x);\nint gsl_vector_long_double_add_constant (gsl_vector_long_double * a, const long double x);\nint gsl_vector_long_double_axpby (const long double alpha, const gsl_vector_long_double * x, const long double beta, gsl_vector_long_double * y);\nlong double gsl_vector_long_double_sum (const gsl_vector_long_double * a);\n\nint gsl_vector_long_double_equal (const gsl_vector_long_double * u, \n                            const gsl_vector_long_double * v);\n\nint gsl_vector_long_double_isnull (const gsl_vector_long_double * v);\nint gsl_vector_long_double_ispos (const gsl_vector_long_double * v);\nint gsl_vector_long_double_isneg (const gsl_vector_long_double * v);\nint gsl_vector_long_double_isnonneg (const gsl_vector_long_double * v);\n\nINLINE_DECL long double gsl_vector_long_double_get (const gsl_vector_long_double * v, const size_t i);\nINLINE_DECL void gsl_vector_long_double_set (gsl_vector_long_double * v, const size_t i, long double x);\nINLINE_DECL long double * gsl_vector_long_double_ptr (gsl_vector_long_double * v, const size_t i);\nINLINE_DECL const long double * gsl_vector_long_double_const_ptr (const gsl_vector_long_double * v, const size_t i);\n\n#ifdef HAVE_INLINE\n\nINLINE_FUN\nlong double\ngsl_vector_long_double_get (const gsl_vector_long_double * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= v->size))\n    {\n      GSL_ERROR_VAL (\"index out of range\", GSL_EINVAL, 0);\n    }\n#endif\n  return v->data[i * v->stride];\n}\n\nINLINE_FUN\nvoid\ngsl_vector_long_double_set (gsl_vector_long_double * v, const size_t i, long double x)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= v->size))\n    {\n      GSL_ERROR_VOID (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  v->data[i * v->stride] = x;\n}\n\nINLINE_FUN\nlong double *\ngsl_vector_long_double_ptr (gsl_vector_long_double * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= v->size))\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return (long double *) (v->data + i * v->stride);\n}\n\nINLINE_FUN\nconst long double *\ngsl_vector_long_double_const_ptr (const gsl_vector_long_double * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= v->size))\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return (const long double *) (v->data + i * v->stride);\n}\n#endif /* HAVE_INLINE */\n\n__END_DECLS\n\n#endif /* __GSL_VECTOR_LONG_DOUBLE_H__ */\n\n\n", "meta": {"hexsha": "369fcd53bec1aa683db3030bc26248390c5f2077", "size": 8599, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gsl/gsl_vector_long_double.h", "max_stars_repo_name": "shakfu/pd-psl", "max_stars_repo_head_hexsha": "7efdc298dcd249eda11921edc4b52a004150d5ad", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/gsl/gsl_vector_long_double.h", "max_issues_repo_name": "shakfu/pd-psl", "max_issues_repo_head_hexsha": "7efdc298dcd249eda11921edc4b52a004150d5ad", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gsl/gsl_vector_long_double.h", "max_forks_repo_name": "shakfu/pd-psl", "max_forks_repo_head_hexsha": "7efdc298dcd249eda11921edc4b52a004150d5ad", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-10T09:43:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-10T09:43:54.000Z", "avg_line_length": 36.9055793991, "max_line_length": 145, "alphanum_fraction": 0.71287359, "num_tokens": 1949, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2814055953761018, "lm_q2_score": 0.020645929722342256, "lm_q1q2_score": 0.005809880145608879}}
{"text": "// Copyright (C) 2015 Vincent Lejeune\n// For conditions of distribution and use, see copyright notice in License.txt\n#pragma once\n#include <vulkan\\vulkan.h>\n#include <array>\n#include <gsl/gsl>\n\n#define CHECK_VKRESULT(cmd) { VkResult res = (cmd); if (res != VK_SUCCESS) throw; }\n\nnamespace structures\n{\n\tconstexpr VkAttachmentDescription attachment_description(\n\t\tVkFormat format,\n\t\tVkAttachmentLoadOp load_op,\n\t\tVkAttachmentStoreOp store_op,\n\t\tVkImageLayout initial_layout,\n\t\tVkImageLayout final_layout,\n\t\tVkSampleCountFlagBits sample_count = VK_SAMPLE_COUNT_1_BIT,\n\t\tVkAttachmentLoadOp stencil_load_op = VK_ATTACHMENT_LOAD_OP_DONT_CARE,\n\t\tVkAttachmentStoreOp stencil_store_op = VK_ATTACHMENT_STORE_OP_DONT_CARE,\n\t\tVkAttachmentDescriptionFlags flag = 0)\n\t{\n\t\treturn{ flag, format, sample_count, load_op, store_op, stencil_load_op, stencil_store_op, initial_layout, final_layout };\n\t}\n}\n", "meta": {"hexsha": "cdf228cdf80b3c2f13e92956d918603e910f22f5", "size": 886, "ext": "h", "lang": "C", "max_stars_repo_path": "include/VKAPI/vulkan_helpers.h", "max_stars_repo_name": "vlj/YAGF", "max_stars_repo_head_hexsha": "139ddc9c7d3552f383e235715713c30684b7067f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2015-04-16T19:41:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-23T23:30:18.000Z", "max_issues_repo_path": "include/VKAPI/vulkan_helpers.h", "max_issues_repo_name": "vlj/YAGF", "max_issues_repo_head_hexsha": "139ddc9c7d3552f383e235715713c30684b7067f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2015-04-16T19:46:53.000Z", "max_issues_repo_issues_event_max_datetime": "2017-11-16T03:06:58.000Z", "max_forks_repo_path": "include/VKAPI/vulkan_helpers.h", "max_forks_repo_name": "vlj/YAGF", "max_forks_repo_head_hexsha": "139ddc9c7d3552f383e235715713c30684b7067f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-11-18T16:23:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-31T04:40:05.000Z", "avg_line_length": 34.0769230769, "max_line_length": 123, "alphanum_fraction": 0.8036117381, "num_tokens": 218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.17553806499717958, "lm_q2_score": 0.03308598208318718, "lm_q1q2_score": 0.0058078492734140305}}
{"text": "#ifndef __GSL_MATRIX_H__\r\n#define __GSL_MATRIX_H__\r\n\r\n#if !defined( GSL_FUN )\r\n#  if !defined( GSL_DLL )\r\n#    define GSL_FUN extern\r\n#  elif defined( BUILD_GSL_DLL )\r\n#    define GSL_FUN extern __declspec(dllexport)\r\n#  else\r\n#    define GSL_FUN extern __declspec(dllimport)\r\n#  endif\r\n#endif\r\n\r\n#include <gsl/gsl_matrix_complex_long_double.h>\r\n#include <gsl/gsl_matrix_complex_double.h>\r\n#include <gsl/gsl_matrix_complex_float.h>\r\n\r\n#include <gsl/gsl_matrix_long_double.h>\r\n#include <gsl/gsl_matrix_double.h>\r\n#include <gsl/gsl_matrix_float.h>\r\n\r\n#include <gsl/gsl_matrix_ulong.h>\r\n#include <gsl/gsl_matrix_long.h>\r\n\r\n#include <gsl/gsl_matrix_uint.h>\r\n#include <gsl/gsl_matrix_int.h>\r\n\r\n#include <gsl/gsl_matrix_ushort.h>\r\n#include <gsl/gsl_matrix_short.h>\r\n\r\n#include <gsl/gsl_matrix_uchar.h>\r\n#include <gsl/gsl_matrix_char.h>\r\n\r\n\r\n#endif /* __GSL_MATRIX_H__ */\r\n", "meta": {"hexsha": "560f33138316d624eb3d54e51b55167c56a2d8ab", "size": 866, "ext": "h", "lang": "C", "max_stars_repo_path": "deps/include/gsl/gsl_matrix.h", "max_stars_repo_name": "berkus/music-cs", "max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z", "max_issues_repo_path": "deps/include/gsl/gsl_matrix.h", "max_issues_repo_name": "berkus/music-cs", "max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z", "max_forks_repo_path": "deps/include/gsl/gsl_matrix.h", "max_forks_repo_name": "berkus/music-cs", "max_forks_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 24.0555555556, "max_line_length": 49, "alphanum_fraction": 0.7413394919, "num_tokens": 236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22270013882530887, "lm_q2_score": 0.025957355596589876, "lm_q1q2_score": 0.005780706694898474}}
{"text": "#pragma once\n\n#include <gsl/span>\n#include \"simple_math.h\"\n\nconstexpr auto VECTOR_SIZE = sizeof(float) * 4;\n\nclass CBufferBase;\n\nstruct CBufferAlign\n{\n\tsize_t size;\n\texplicit CBufferAlign(size_t size_ = VECTOR_SIZE) : size(size_) {}\n};\n\n__forceinline CBufferAlign cbuff_align(size_t size = VECTOR_SIZE)\n{\n\treturn CBufferAlign(size);\n}\n\nclass ICBuffer\n{\npublic:\n\tvirtual ~ICBuffer() = default;\n\tvirtual void write(CBufferBase& cbuf) const = 0;\n\n\tsize_t cbuffer_size() const;\n\n\ttemplate <typename T>\n\tstatic size_t cbuffer_size()\n\t{\n\t\tT t;\n\t\treturn t.cbuffer_size();\n\t}\n};\n\nclass CBufferBase\n{\nprotected:\n\tsize_t offset_ = 0;\n\tsize_t alignment_ = 0;\n\npublic:\n\tvirtual ~CBufferBase() = default;\n\tbool align(size_t size = VECTOR_SIZE);\n\tvoid add(size_t size);\n\tvoid reset();\n\n\tsize_t offset() const { return offset_; }\n\tsize_t alignment() const { return alignment_; }\n\n\ttemplate <typename T>\n\tCBufferBase& operator<<(const T& data) = delete;\n\n\ttemplate <typename T>\n\tCBufferBase& operator<<(const gsl::span<T>& data) = delete;\n\n\ttemplate <typename T>\n\tCBufferBase& operator<<(const gsl::span<const T>& data) = delete;\n\n\tCBufferBase& operator<<(const CBufferAlign& align_of);\n\n\ttemplate <typename T, size_t size>\n\t__forceinline CBufferBase& operator<<(const std::array<T, size>& array)\n\t{\n\t\treturn *this << gsl::span<const T>(array);\n\t}\n\n\ttemplate <typename T, size_t size>\n\t__forceinline CBufferBase& operator<<(const T(&array)[size])\n\t{\n\t\treturn *this << gsl::span<const T>(array);\n\t}\n\n\ttemplate <typename T>\n\t__forceinline CBufferBase& operator<<(const dirty_t<T>& value)\n\t{\n\t\treturn *this << value.data();\n\t}\n\n\tvirtual void write(const void* data, size_t size)\n\t{\n\t\talign(size);\n\t\tadd(size);\n\t}\n};\n\ntemplate <>\nCBufferBase& CBufferBase::operator<<(const int32_t& data);\ntemplate <>\nCBufferBase& CBufferBase::operator<<(const uint32_t& data);\ntemplate <>\nCBufferBase& CBufferBase::operator<<(const float& data);\ntemplate <>\nCBufferBase& CBufferBase::operator<<(const DirectX::SimpleMath::Matrix& data);\ntemplate <>\nCBufferBase& CBufferBase::operator<<(const DirectX::SimpleMath::Vector2& data);\ntemplate <>\nCBufferBase& CBufferBase::operator<<(const DirectX::SimpleMath::Vector3& data);\ntemplate <>\nCBufferBase& CBufferBase::operator<<(const DirectX::SimpleMath::Vector4& data);\ntemplate <>\nCBufferBase& CBufferBase::operator<<(const gsl::span<float>& data);\ntemplate <>\nCBufferBase& CBufferBase::operator<<(const gsl::span<const float>& data);\n\ntemplate <>\n__forceinline CBufferBase& CBufferBase::operator<<(const DWORD& data)\n{\n\treturn *this << static_cast<uint32_t>(data);\n}\n\ntemplate <>\n__forceinline CBufferBase& CBufferBase::operator<<(const bool& data)\n{\n\treturn *this << (data ? 1 : 0);\n}\n\nclass CBufferWriter : public CBufferBase\n{\n\tuint8_t* ptr = nullptr;\n\npublic:\n\tCBufferWriter(uint8_t* ptr_);\n\nprivate:\n\tvoid write(const void* data, size_t size) override;\n};\n", "meta": {"hexsha": "127cc6a73efb0678f7037d2e1ae0cfe87f48ab00", "size": 2870, "ext": "h", "lang": "C", "max_stars_repo_path": "sadx-d3d11/CBufferWriter.h", "max_stars_repo_name": "SonicFreak94/sadx-d3d11", "max_stars_repo_head_hexsha": "bdfa3fc0d6485d4f9f44a83a43df937ba0b4f68c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-04-27T09:07:57.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-23T19:51:14.000Z", "max_issues_repo_path": "sadx-d3d11/CBufferWriter.h", "max_issues_repo_name": "SonicFreak94/sadx-d3d11", "max_issues_repo_head_hexsha": "bdfa3fc0d6485d4f9f44a83a43df937ba0b4f68c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2018-05-14T22:33:18.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-09T11:58:54.000Z", "max_forks_repo_path": "sadx-d3d11/CBufferWriter.h", "max_forks_repo_name": "michael-fadely/sadx-d3d11", "max_forks_repo_head_hexsha": "bdfa3fc0d6485d4f9f44a83a43df937ba0b4f68c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-02-27T11:20:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-06T19:38:01.000Z", "avg_line_length": 22.2480620155, "max_line_length": 79, "alphanum_fraction": 0.7216027875, "num_tokens": 751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3311197396289915, "lm_q2_score": 0.017442486172716452, "lm_q1q2_score": 0.005775551479992156}}
{"text": "#ifndef DART_META_H\n#define DART_META_H\n\n/*----- System Includes -----*/\n\n#include <memory>\n#include <gsl/gsl>\n#include <type_traits>\n\n/*----- Local Includes -----*/\n\n#include \"shim.h\"\n\n/*----- Type Declarations -----*/\n\nnamespace dart {\n\n  namespace meta {\n\n    template <class...>\n    using void_t = void;\n\n    template <class T>\n    struct identity {\n      using type = T;\n    };\n\n    // Removes one level of \"pointer to const\", \"pointer to volatile\"\n    // \"reference to const\", \"reference to volatile\", etc,\n    // to make working with strings easier.\n    // Like std::decay except it doesn't decay C arrays,\n    // but it otherwise much stronger.\n    template <class T>\n    struct canonical_type {\n      using type = T;\n    };\n    template <class T>\n    struct canonical_type<T const> {\n      using type = T;\n    };\n    template <class T>\n    struct canonical_type<T volatile> {\n      using type = T;\n    };\n    template <class T>\n    struct canonical_type<T const volatile> {\n      using type = T;\n    };\n    template <class T>\n    struct canonical_type<T&> {\n      using type = T&;\n    };\n    template <class T>\n    struct canonical_type<T const&> {\n      using type = T&;\n    };\n    template <class T>\n    struct canonical_type<T volatile&> {\n      using type = T&;\n    };\n    template <class T>\n    struct canonical_type<T const volatile&> {\n      using type = T&;\n    };\n    template <class T>\n    struct canonical_type<T*> {\n      using type = T*;\n    };\n    template <class T>\n    struct canonical_type<T const*> {\n      using type = T*;\n    };\n    template <class T>\n    struct canonical_type<T volatile*> {\n      using type = T*;\n    };\n    template <class T>\n    struct canonical_type<T const volatile*> {\n      using type = T*;\n    };\n    template <class T, size_t len>\n    struct canonical_type<T (&)[len]> {\n      using type = T (&)[len];\n    };\n    template <class T, size_t len>\n    struct canonical_type<T const (&)[len]> {\n      using type = T (&)[len];\n    };\n    template <class T, size_t len>\n    struct canonical_type<T volatile (&)[len]> {\n      using type = T (&)[len];\n    };\n    template <class T, size_t len>\n    struct canonical_type<T const volatile (&)[len]> {\n      using type = T (&)[len];\n    };\n    template <class T, size_t len>\n    struct canonical_type<T (*)[len]> {\n      using type = T (*)[len];\n    };\n    template <class T, size_t len>\n    struct canonical_type<T const (*)[len]> {\n      using type = T (*)[len];\n    };\n    template <class T, size_t len>\n    struct canonical_type<T volatile (*)[len]> {\n      using type = T (*)[len];\n    };\n    template <class T, size_t len>\n    struct canonical_type<T const volatile (*)[len]> {\n      using type = T (*)[len];\n    };\n    template <class T>\n    using canonical_type_t = typename canonical_type<T>::type;\n\n    template <class T>\n    struct is_ptr_to_const : std::false_type {};\n    template <class T>\n    struct is_ptr_to_const<T const*> : std::true_type {};\n\n    // Create type traits to check for each type of comparison.\n    template <class Lhs, class Rhs, class = void>\n    struct are_comparable : std::false_type {};\n    template <class Lhs, class Rhs>\n    struct are_comparable<\n      Lhs,\n      Rhs,\n      void_t<decltype(std::declval<Lhs>() == std::declval<Rhs>())>\n    > : std::true_type {};\n\n    template <class T, class = void>\n    struct is_dereferenceable : std::false_type {};\n    template <class T>\n    struct is_dereferenceable<\n      T,\n      void_t<decltype(*std::declval<T>())>\n    > : std::true_type {};\n\n    template <class...>\n    struct conjunction : std::true_type {};\n    template <class B1>\n    struct conjunction<B1> : B1 {};\n    template <class B1, class... Bn>\n    struct conjunction<B1, Bn...> :\n      std::conditional_t<\n        bool(B1::value),\n        conjunction<Bn...>,\n        B1\n      >\n    {};\n\n    template <class...>\n    struct disjunction : std::false_type {};\n    template <class B1>\n    struct disjunction<B1> : B1 {};\n    template <class B1, class... Bn>\n    struct disjunction<B1, Bn...> :\n      std::conditional_t<\n        bool(B1::value),\n        B1,\n        disjunction<Bn...>\n      >\n    {};\n\n    template <class B>\n    struct negation : std::integral_constant<bool, !bool(B::value)> {};\n\n    template <class T, class... Ts>\n    struct contained : disjunction<std::is_same<T, Ts>...> {};\n    template <class T, class... Ts>\n    struct not_contained : conjunction<negation<std::is_same<T, Ts>>...> {};\n\n    template <class... Types>\n    struct types {\n      template <class T, class =\n        std::enable_if_t<\n          contained<T, Types...>::value\n        >\n      >\n      types(T) {}\n    };\n    template <class... Types>\n    struct not_types {\n      template <class T, class =\n        std::enable_if_t<\n          not_contained<T, Types...>::value\n        >\n      >\n      not_types(T) {}\n    };\n\n    template <class...>\n    struct first_type {\n      using type = void;\n    };\n    template <class T, class... Ts>\n    struct first_type<T, Ts...> {\n      using type = T;\n    };\n    template <class... Ts>\n    using first_type_t = typename first_type<Ts...>::type;\n\n    namespace detail {\n\n      template <class Default, class AlwaysVoid, template <class...> class Op, class... Args>\n      struct detector {\n        using value_t = std::false_type;\n        using type = Default;\n      };\n \n      template <class Default, template <class...> class Op, class... Args>\n      struct detector<Default, void_t<Op<Args...>>, Op, Args...> {\n        // Note that std::void_t is a C++17 feature\n        using value_t = std::true_type;\n        using type = Op<Args...>;\n      };\n \n    }\n \n    struct nonesuch {\n      nonesuch(nonesuch const&) = delete;\n      nonesuch(nonesuch&&) = delete;\n      ~nonesuch() = delete;\n    };\n\n    template <template <class...> class Op, class... Args>\n    using is_detected = typename detail::detector<nonesuch, void, Op, Args...>::value_t;\n    template <template <class...> class Op, class... Args>\n    using detected_t = typename detail::detector<nonesuch, void, Op, Args...>::type;\n    template <class Default, template <class...> class Op, class... Args>\n    using detected_or = detail::detector<Default, void, Op, Args...>;\n\n    template <class T>\n    using strv_t = decltype(std::declval<T>().strv());\n    template <class T>\n    using integer_t = decltype(std::declval<T>().integer());\n    template <class T>\n    using decimal_t = decltype(std::declval<T>().decimal());\n    template <class T>\n    using boolean_t = decltype(std::declval<T>().boolean());\n    template <class T>\n    using get_type_t = decltype(std::declval<T>().get_type());\n\n    template <class T>\n    struct is_dartlike :\n      meta::conjunction<\n        is_detected<strv_t, T>,\n        is_detected<integer_t, T>,\n        is_detected<decimal_t, T>,\n        is_detected<boolean_t, T>,\n        is_detected<get_type_t, T>\n      >\n    {};\n\n    template <class T, template <class> class Template>\n    struct is_specialization_of : std::false_type {};\n    template <class... Args, template <class> class Template>\n    struct is_specialization_of<Template<Args...>, Template> : std::true_type {};\n\n    template <class T, template <template <class> class> class Compound>\n    struct is_higher_specialization_of : std::false_type {};\n    template <template <class> class Inner, template <template <class> class> class Outer>\n    struct is_higher_specialization_of<Outer<Inner>, Outer> : std::true_type {};\n\n    template <class T>\n    struct is_span : std::false_type {};\n#ifdef DART_USING_GSL_LITE\n    template <class T>\n    struct is_span<gsl::span<T>> : std::true_type {};\n#else\n    template <class T, std::size_t extent>\n    struct is_span<gsl::span<T, extent>> : std::true_type {};\n#endif\n\n    template <class T>\n    struct is_std_smart_ptr : std::false_type {};\n    template <class T, class Del>\n    struct is_std_smart_ptr<std::unique_ptr<T, Del>> : std::true_type {};\n    template <class T>\n    struct is_std_smart_ptr<std::shared_ptr<T>> : std::true_type {};\n    template <class T>\n    struct is_std_smart_ptr<std::weak_ptr<T>> : std::true_type {};\n\n    template <size_t pos>\n    struct priority_tag : priority_tag<pos - 1> {};\n    template <>\n    struct priority_tag<0> {};\n\n    namespace detail {\n      template <class T>\n      struct is_builtin_string_impl : std::false_type {};\n      template <>\n      struct is_builtin_string_impl<char*> : std::true_type {};\n      template <>\n      struct is_builtin_string_impl<wchar_t*> : std::true_type {};\n      template <>\n      struct is_builtin_string_impl<char16_t*> : std::true_type {};\n      template <>\n      struct is_builtin_string_impl<char32_t*> : std::true_type {};\n      template <size_t len>\n      struct is_builtin_string_impl<char (&)[len]> : std::true_type {};\n      template <size_t len>\n      struct is_builtin_string_impl<wchar_t (&)[len]> : std::true_type {};\n      template <size_t len>\n      struct is_builtin_string_impl<char16_t (&)[len]> : std::true_type {};\n      template <size_t len>\n      struct is_builtin_string_impl<char32_t (&)[len]> : std::true_type {};\n    }\n\n    template <class T>\n    struct is_builtin_string : detail::is_builtin_string_impl<canonical_type_t<T>> {};\n\n    template <class T>\n    struct is_std_string : std::false_type {};\n    template <class CharT, class Traits, class Allocator>\n    struct is_std_string<std::basic_string<CharT, Traits, Allocator>> : std::true_type {};\n\n    template <class T>\n    struct is_std_string_view : std::false_type {};\n    template <class CharT, class Traits>\n    struct is_std_string_view<shim::basic_string_view<CharT, Traits>> : std::true_type {};\n\n    template <class T>\n    struct is_string :\n      meta::disjunction<\n        is_builtin_string<T>,\n        is_std_string<T>,\n        is_std_string_view<T>\n      >\n    {};\n\n    template <class T>\n    struct spannable_value_type {\n      template <class U>\n      static typename U::value_type detect(priority_tag<1>);\n      template <class U>\n      static typename U::element_type detect(priority_tag<0>);\n      template <class U>\n      static nonesuch detect(...);\n      using type = std::remove_cv_t<decltype(detect<T>(priority_tag<1> {}))>;\n    };\n    template <class T>\n    using spannable_value_type_t = typename spannable_value_type<T>::type;\n  }\n\n}\n\n#undef DART_COMPARE_HELPER\n\n#endif\n", "meta": {"hexsha": "35fc5342d323fc1bccc91ba42652e233b1a8a35f", "size": 10306, "ext": "h", "lang": "C", "max_stars_repo_path": "include/dart/meta.h", "max_stars_repo_name": "Cfretz244/libdart", "max_stars_repo_head_hexsha": "987b01aa1f11455ac6aaf89f8e60825e92e6ec25", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2019-05-09T19:12:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-07T16:31:55.000Z", "max_issues_repo_path": "include/dart/meta.h", "max_issues_repo_name": "Cfretz244/libdart", "max_issues_repo_head_hexsha": "987b01aa1f11455ac6aaf89f8e60825e92e6ec25", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2019-05-09T22:37:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-29T03:25:16.000Z", "max_forks_repo_path": "include/dart/meta.h", "max_forks_repo_name": "Cfretz244/libdart", "max_forks_repo_head_hexsha": "987b01aa1f11455ac6aaf89f8e60825e92e6ec25", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-05-11T08:05:10.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-11T11:05:17.000Z", "avg_line_length": 29.3618233618, "max_line_length": 93, "alphanum_fraction": 0.611003299, "num_tokens": 2592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15002883194322006, "lm_q2_score": 0.038466194222894164, "lm_q1q2_score": 0.005771038188561851}}
{"text": "#include <bindings.cmacros.h>\n#include <gsl/gsl_vector.h>\n\nBC_INLINE2(GSL_COMPLEX_AT,gsl_vector_complex*,size_t,gsl_complex*)\nBC_INLINE2(GSL_COMPLEX_FLOAT_AT,gsl_vector_complex_float*,size_t,gsl_complex_float*)\n/* BC_INLINE2(GSL_COMPLEX_LONG_DOUBLE_AT,gsl_vector_complex_long_double*,size_t,gsl_complex_long_double*) */\n", "meta": {"hexsha": "1bc774e2264c637ccf476d69fd16773178115335", "size": 320, "ext": "c", "lang": "C", "max_stars_repo_path": "bindings-gsl/src/Bindings/Gsl/VectorsAndMatrices/Vectors.c", "max_stars_repo_name": "flip111/bindings-dsl", "max_stars_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2015-04-29T00:31:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T09:29:03.000Z", "max_issues_repo_path": "bindings-gsl/src/Bindings/Gsl/VectorsAndMatrices/Vectors.c", "max_issues_repo_name": "flip111/bindings-dsl", "max_issues_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2015-01-04T06:32:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-07T09:49:12.000Z", "max_forks_repo_path": "bindings-gsl/src/Bindings/Gsl/VectorsAndMatrices/Vectors.c", "max_forks_repo_name": "flip111/bindings-dsl", "max_forks_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2015-01-03T20:43:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-10T19:31:38.000Z", "avg_line_length": 45.7142857143, "max_line_length": 108, "alphanum_fraction": 0.859375, "num_tokens": 81, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.26284183737131667, "lm_q2_score": 0.02194825287519286, "lm_q1q2_score": 0.0057689191128059755}}
{"text": "#pragma once\n\n#include <gsl\\gsl>\n#include <winrt\\Windows.Foundation.h>\n#include <d3d11.h>\n#include \"DrawableGameComponent.h\"\n#include \"MatrixHelper.h\"\n#include \"DirectionalLight.h\"\n\nnamespace Library\n{\n\tclass ProxyModel;\n\tclass AnimationPlayer;\n\tclass Model;\n\tclass AnimationClip;\n}\n\nnamespace Rendering\n{\n\tclass SkinnedModelMaterial;\n\n\tclass AnimationDemo final : public Library::DrawableGameComponent\n\t{\n\tpublic:\n\t\tAnimationDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera);\n\t\tAnimationDemo(const AnimationDemo&) = delete;\n\t\tAnimationDemo(AnimationDemo&&) = default;\n\t\tAnimationDemo& operator=(const AnimationDemo&) = default;\t\t\n\t\tAnimationDemo& operator=(AnimationDemo&&) = default;\n\t\t~AnimationDemo();\n\n\t\tbool ManualAdvanceEnabled() const;\n\t\tvoid SetManualAdvanceEnabled(bool enabled);\n\t\tvoid ToggleManualAdvance();\n\t\t\n\t\tconst std::unique_ptr<Library::AnimationPlayer>& AnimationPlayer() const;\n\t\tvoid TogglePause();\t\t\n\t\tvoid RestartClip();\n\n\t\tvoid IncrementCurrentKeyframe();\n\t\tvoid DecrementCurrentKeyframe();\t\t\n\n\t\tbool InterpolationEnabled() const;\n\t\tvoid SetInterpolationEnabled(bool enabled);\n\t\tvoid ToggleInterpolation();\n\n\t\tfloat AmbientLightIntensity() const;\n\t\tvoid SetAmbientLightIntensity(float intensity);\n\n\t\tfloat DirectionalLightIntensity() const;\n\t\tvoid SetDirectionalLightIntensity(float intensity);\n\n\t\tconst DirectX::XMFLOAT3& LightDirection() const;\n\t\tvoid RotateDirectionalLight(DirectX::XMFLOAT2 amount);\n\n\t\tvirtual void Initialize() override;\n\t\tvirtual void Update(const Library::GameTime& gameTime) override;\n\t\tvirtual void Draw(const Library::GameTime& gameTime) override;\n\n\tprivate:\n\t\tinline static const float RotationRate{ DirectX::XM_PI };\n\n\t\tstd::shared_ptr<SkinnedModelMaterial> mMaterial;\n\t\tDirectX::XMFLOAT4X4 mWorldMatrix{ Library::MatrixHelper::Identity };\n\t\twinrt::com_ptr<ID3D11Buffer> mVertexBuffer;\n\t\twinrt::com_ptr<ID3D11Buffer> mIndexBuffer;\n\t\tstd::uint32_t mIndexCount{ 0 };\n\t\tLibrary::DirectionalLight mDirectionalLight;\n\t\tstd::unique_ptr<Library::ProxyModel> mProxyModel;\n\t\tbool mUpdateMaterial{ true };\n\t\tbool mUpdateMaterialBoneTransforms{ true };\n\t\tstd::unique_ptr<Library::AnimationPlayer> mAnimationPlayer;\n\t\tbool mManualAdvanceEnabled{ false };\n\t\tstd::shared_ptr<Library::Model> mSkinnedModel;\n\t};\n}", "meta": {"hexsha": "5fb3eec222230f1d37c2f63c3157003633960748", "size": 2275, "ext": "h", "lang": "C", "max_stars_repo_path": "source/9.1_Animation/AnimationDemo.h", "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/9.1_Animation/AnimationDemo.h", "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/9.1_Animation/AnimationDemo.h", "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9342105263, "max_line_length": 85, "alphanum_fraction": 0.7758241758, "num_tokens": 548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3557749071749625, "lm_q2_score": 0.016152835473363172, "lm_q1q2_score": 0.0057467735411482245}}
{"text": "#pragma once\n\n#include \"Availability.h\"\n#include \"Library.h\"\n#include \"OctreeTileID.h\"\n#include \"TileAvailabilityFlags.h\"\n\n#include <gsl/span>\n\n#include <cstddef>\n#include <memory>\n#include <vector>\n\nnamespace CesiumGeometry {\n\nclass CESIUMGEOMETRY_API OctreeAvailability final {\npublic:\n  /**\n   * @brief Constructs a new instance.\n   *\n   * @param subtreeLevels The number of levels in each subtree.\n   * @param maximumLevel The index of the maximum level in this tileset.\n   */\n  OctreeAvailability(uint32_t subtreeLevels, uint32_t maximumLevel) noexcept;\n\n  /**\n   * @brief Determines the currently known availability status of the given\n   * tile.\n   *\n   * @param tileID The {@link CesiumGeometry::OctreeTileID} for the tile.\n   *\n   * @return The {@link TileAvailabilityFlags} for this tile encoded into a\n   * uint8_t.\n   */\n  uint8_t computeAvailability(const OctreeTileID& tileID) const noexcept;\n\n  /**\n   * @brief Attempts to add an availability subtree into the existing overall\n   * availability tree.\n   *\n   * @param tileID The {@link CesiumGeometry::OctreeTileID} for the tile.\n   * @param newSubtree The {@link CesiumGeometry::AvailabilitySubtree} to add.\n   *\n   * @return Whether the insertion was successful.\n   */\n  bool addSubtree(\n      const OctreeTileID& tileID,\n      AvailabilitySubtree&& newSubtree) noexcept;\n\n  /**\n   * @brief Determines the currently known availability status of the given\n   * tile.\n   *\n   * Priming with a known parent subtree node avoids the need to traverse the\n   * entire availability tree so far. The node must have a loaded subtree\n   *\n   * @param tileID The tile ID to get the availability for.\n   * @param pNode The subtree node to look for the tileID in. The tileID should\n   * be within this subtree node.\n   *\n   * @return The {@link TileAvailabilityFlags} for this tile encoded into a\n   * uint8_t.\n   */\n  uint8_t computeAvailability(\n      const OctreeTileID& tileID,\n      const AvailabilityNode* pNode) const noexcept;\n\n  /**\n   * @brief Attempts to add a child subtree node onto the given parent node.\n   *\n   * Priming with a known parent subtree node avoids the need to traverse the\n   * entire availability tree so far. If the parent node is nullptr and the\n   * tile ID indicates this is the root tile, the subtree will be attached to\n   * the root.\n   *\n   * @param tileID The root tile's ID of the subtree we are trying to add.\n   * @param pParentNode The parent subtree node. The tileID should fall exactly\n   * at the end of this parent subtree.\n   *\n   * @return The newly created node if the insertion was successful, nullptr\n   * otherwise.\n   */\n  AvailabilityNode*\n  addNode(const OctreeTileID& tileID, AvailabilityNode* pParentNode) noexcept;\n\n  /**\n   * @brief Attempts to add a loaded subtree onto the given node.\n   *\n   * The node must have been created earlier from a call to addNode.\n   *\n   * @param pNode The node on which to add the subtree.\n   * @param newSubtree The new subtree to add.\n   *\n   * @return Whether the insertion was successful.\n   */\n  bool addLoadedSubtree(\n      AvailabilityNode* pNode,\n      AvailabilitySubtree&& newSubtree) noexcept;\n  /**\n   * @brief Find the child node index corresponding to this tile ID and parent\n   * node.\n   *\n   * Attempts to find the child node for the tile with the given ID and parent\n   * node. The parent node is used to speed up the search significantly. Note\n   * that if the given tile ID does not correspond exactly to an immediate\n   * child node of the parent node, nullptr will be returned. If a tileID\n   * outside the given parent node's subtree is given, an incorrect child index\n   * may be returned.\n   *\n   * @param tileID The tile ID of the child node we are looking for.\n   * @param pParentNode The immediate parent to the child node we are looking\n   * for.\n   * @return The child node index if found, std::nullopt otherwise.\n   */\n  std::optional<uint32_t> findChildNodeIndex(\n      const OctreeTileID& tileID,\n      const AvailabilityNode* pParentNode) const;\n\n  /**\n   * @brief Find the child node corresponding to this tile ID and parent node.\n   *\n   * Attempts to find the child node for the tile with the given ID and parent\n   * node. The parent node is used to speed up the search significantly. Note\n   * that if the given tile ID does not correspond exactly to an immediate\n   * child node of the parent node, nullptr will be returned. If a tileID\n   * outside the given parent node's subtree is given, an incorrect child index\n   * may be returned.\n   *\n   * @param tileID The tile ID of the child node we are looking for.\n   * @param pParentNode The immediate parent to the child node we are looking\n   * for.\n   * @return The child node if found, nullptr otherwise.\n   */\n  AvailabilityNode* findChildNode(\n      const OctreeTileID& tileID,\n      AvailabilityNode* pParentNode) const;\n\n  /**\n   * @brief Gets the number of levels in each subtree.\n   */\n  constexpr inline uint32_t getSubtreeLevels() const noexcept {\n    return this->_subtreeLevels;\n  }\n\n  /**\n   * @brief Gets the index of the maximum level in this implicit tileset.\n   */\n  constexpr inline uint32_t getMaximumLevel() const noexcept {\n    return this->_maximumLevel;\n  }\n\n  /**\n   * @brief Gets a pointer to the root subtree node of this implicit tileset.\n   */\n  AvailabilityNode* getRootNode() noexcept { return this->_pRoot.get(); }\n\nprivate:\n  uint32_t _subtreeLevels;\n  uint32_t _maximumLevel;\n  uint32_t _maximumChildrenSubtrees;\n  std::unique_ptr<AvailabilityNode> _pRoot;\n};\n\n} // namespace CesiumGeometry\n", "meta": {"hexsha": "2fd8e9943753ad9bbc1e664e1a5f0d328242b759", "size": 5560, "ext": "h", "lang": "C", "max_stars_repo_path": "CesiumGeometry/include/CesiumGeometry/OctreeAvailability.h", "max_stars_repo_name": "yieryi/cesium-native", "max_stars_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 154.0, "max_stars_repo_stars_event_min_datetime": "2021-03-30T14:08:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T00:01:43.000Z", "max_issues_repo_path": "CesiumGeometry/include/CesiumGeometry/OctreeAvailability.h", "max_issues_repo_name": "yieryi/cesium-native", "max_issues_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 256.0, "max_issues_repo_issues_event_min_datetime": "2021-03-30T18:12:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:44:21.000Z", "max_forks_repo_path": "CesiumGeometry/include/CesiumGeometry/OctreeAvailability.h", "max_forks_repo_name": "yieryi/cesium-native", "max_forks_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 66.0, "max_forks_repo_forks_event_min_datetime": "2021-03-30T15:14:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T13:38:41.000Z", "avg_line_length": 33.696969697, "max_line_length": 79, "alphanum_fraction": 0.7120503597, "num_tokens": 1347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22815650216092534, "lm_q2_score": 0.025178838957499283, "lm_q1q2_score": 0.005744715825016277}}
{"text": "#ifndef EMPHASIS_RINIT_H_INCLUDED\n#define EMPHASIS_RINIT_H_INCLUDED\n\n#include <nlopt.h>\n\n\n#if (defined(_WIN32) || defined(__WIN32__)) && !defined(__LCC__)\n#  define REMP_EXPORT extern \"C\" __declspec(dllexport)\n#else\n#  define REMP_EXPORT extern \"C\"\n#endif\n\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n\n/* some function pointers into nlopt to be filled in by R */\n\n\nREMP_EXPORT nlopt_opt(*remp_create)(nlopt_algorithm, unsigned);\nREMP_EXPORT void(*remp_destroy)(nlopt_opt);\nREMP_EXPORT nlopt_result(*remp_optimize)(nlopt_opt, double *, double *);\nREMP_EXPORT nlopt_result(*remp_set_min_objective)(nlopt_opt, nlopt_func, void *);\nREMP_EXPORT nlopt_result(*remp_set_max_objective)(nlopt_opt, nlopt_func, void *);\nREMP_EXPORT nlopt_result(*remp_set_lower_bounds)(nlopt_opt, const double *);\nREMP_EXPORT nlopt_result(*remp_set_lower_bounds1)(nlopt_opt, double);\nREMP_EXPORT nlopt_result(*remp_set_upper_bounds)(nlopt_opt, const double *);\nREMP_EXPORT nlopt_result(*remp_set_upper_bounds1)(nlopt_opt, double);\nREMP_EXPORT nlopt_result(*remp_set_xtol_rel)(nlopt_opt, double);\nREMP_EXPORT nlopt_result(*remp_set_xtol_abs)(nlopt_opt, double);\n\n\n#ifdef __cplusplus\n}\n#endif\n\n\n#endif\n", "meta": {"hexsha": "3dcf096a1b11a5a2df2e03e9d758823271fb54be", "size": 1170, "ext": "h", "lang": "C", "max_stars_repo_path": "src/rinit.h", "max_stars_repo_name": "franciscorichter/emphasis", "max_stars_repo_head_hexsha": "c23a17ee903ca98c34126739561d97b32f631098", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/rinit.h", "max_issues_repo_name": "franciscorichter/emphasis", "max_issues_repo_head_hexsha": "c23a17ee903ca98c34126739561d97b32f631098", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2018-07-16T13:55:17.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-24T16:53:03.000Z", "max_forks_repo_path": "src/rinit.h", "max_forks_repo_name": "franciscorichter/emphasis", "max_forks_repo_head_hexsha": "c23a17ee903ca98c34126739561d97b32f631098", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-12T13:25:10.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T13:25:10.000Z", "avg_line_length": 28.5365853659, "max_line_length": 81, "alphanum_fraction": 0.7991452991, "num_tokens": 349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2538610069692489, "lm_q2_score": 0.022629197437667663, "lm_q1q2_score": 0.00574467084843226}}
{"text": "/* altProbes.c - Match probes to splicing events and do anaylysis.\n\n   This program origianlly was written to calculate which probe\n   sets were being expressed and matching up the probe sets with\n   the correct splice junctions. Since then it has expanded to fill\n   a number of roles as it is one of the few times where the probe\n   sets, data, and splicing information are all accesible at the\n   same time. Now the program is almost run in an iterative fashion,\n   the first time it generates a number of matrices that are used\n   in R to do calculations. The pvalues and scores that come out\n   of R can then be fed back in to be used as pre-calculated\n   p-vals and scores for outputting new stats.\n\n   Currently altProbes actually:\n   - Matches probe sets to splicing paths.\n   - Calculates average intensities and pvalues for a given path.\n   - Looks for known binding sites of splicing factors.\n   - Lifts splicing factors to current assembly and looks for overlaps\n     with conserved elements.\n   - Compiles and outputs matrices for R.\n   - Outputs a number of cassette exon specific sequence files.\n*/\n\n#include \"common.h\"\n#include \"bed.h\"\n#include \"hash.h\"\n#include \"options.h\"\n#include \"chromKeeper.h\"\n#include \"binRange.h\"\n#include \"obscure.h\"\n#include \"linefile.h\"\n#include \"dystring.h\"\n#include \"altGraphX.h\"\n#include \"splice.h\"\n#include \"hdb.h\"\n#include \"dMatrix.h\"\n#include \"liftOver.h\"\n#include \"dnautil.h\"\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_cdf.h>\n#include <gsl/gsl_statistics_double.h>\n\nstruct altPath\n/* Information about a path and associated bed probes. */\n{\n    struct altPath *next; /* Next in list. */\n    int probeCount;        /* Number of probes on this path. */\n    struct bed **beds;     /* Array of beds that are unique to this path. */\n    int *bedTypes;         /* Are beds exons or splice junction probes. */\n    double **expVals;      /* Expression values. */\n    double **pVals;        /* Probability of expression. */\n    double *avgExpVals;    /* Average value for each exp. */\n    struct path *path;     /* Path that this altPath represents. */\n    double score;               /* Score of being expressed overall. */\n    double exonCorr;            /* Correlation of exon probe set with include junction if appropriate. */\n    double exonSkipCorr;        /* Correlation of exon probe set with skip junction if appropriate. */\n    double probCorr;            /* Correlation of exon probe set prob and include probs. */\n    double probSkipCorr;        /* Correlation of exon probe set prob skip junction if appropriate. */\n    double exonSjPercent;       /* Percentage of includes confirmed by exon probe set. */\n    double sjExonPercent;       /* Percentage of exons confirmed by sj probe set. */\n    int exonAgree;              /* Number of times exon agrees with matched splice junction */\n    int exonDisagree;           /* Number of times exon disagrees with matched splice junction. */\n    int sjAgree;                /* Number of times sj agrees with matched exon */\n    int sjDisagree;             /* Number of times sj disagrees with matched exon. */\n    int sjExp;                  /* Number of times sj expressed. */\n    int exonExp;                /* Number of times exon expressed. */\n    int *motifUpCounts;         /* Number of motifs counted upstream for each motif. */\n    int *motifDownCounts;        /* Number of motifs counted downstream for each motif. */\n    int *motifInsideCounts;        /* Number of motifs counted inside for each motif. */\n};\n\nstruct valuesMat\n/* Matrix of slNames. */\n{\n    struct valuesMat *next; /* Next in list. */\n    struct hash *rowIndex;   /* Hash of row names idexes. */\n    int colCount;            /* Number of columns. */\n    int maxCols;             /* Number of columns we have memory for. */\n    char **colNames; /* Column Names. */\n    int rowCount;            /* Number of rows. */\n    int maxRows;             /* Number of rows we have memory for. */\n    char **rowNames;         /* Names of rows. */\n    char ***vals;            /* Values. */\n};\n\nstruct altEvent\n/* Information about a particular alt-splicing event. Specifically a\n * collection of paths and the associated data. */\n{\n    struct altEvent *next;       /* Next in list. */\n    struct splice *splice;       /* Splice event. */\n    struct altPath *altPathList; /* Matching of paths to probe sets. */\n    int altPathProbeCount;       /* Paths with associated probes. */\n    int geneProbeCount;              /* Number of probes on this gene. */\n    struct bed **geneBeds;           /* Array of beds that are unique to this gene. */\n    double **geneExpVals;            /* Expression values. */\n    double **genePVals;              /* Probability of expression. */\n    double *avgExpVals;          /* Average value for each exp. */\n    double flipScore;            /* Number of times on version - number of times other / sum of both. */\n    double percentUltra;           /* Percentage of bases that overlap very conserved elements. */\n    double pVal;                   /* PVal of being differentially expressed. */\n    boolean isExpressed;         /* Is this altEvent Expressed. */\n    boolean isAltExpressed;      /* Is this altEvent alt-expressed? */\n};\n\nstruct bindSite\n/* Binding sites for a protein. */\n{\n    struct bindSite *next; /* Next in list. */\n    char **motifs;     /* List of valid motifs. */\n    int motifCount;    /* Number of moitfs to look for. */\n    char *rnaBinder;   /* Rna binding protein associated with these sites. */\n};\n\n\nstruct unitTest\n{\n    struct unitTest *next; /* Next in list. */\n    boolean (*test)(struct unitTest *test);     /* Function to call for test. */\n    char *description;     /* Description of tests. */\n    char *errorMsg;        /* Error message returned by test. */\n};\n\n/* Create a funtion pointer. */\ntypedef boolean (*testFunction)(struct unitTest *test);\n\nstruct unitTest *tests = NULL;\n\nstatic struct optionSpec optionSpecs[] =\n/* Our acceptable options to be called with. */\n{\n    {\"help\", OPTION_BOOLEAN},\n    {\"junctionProbes\", OPTION_STRING},\n    {\"spliceFile\", OPTION_STRING},\n    {\"probFile\", OPTION_STRING},\n    {\"intensityFile\", OPTION_STRING},\n    {\"db\", OPTION_STRING},\n    {\"doPathRatios\", OPTION_STRING},\n    {\"brainSpecific\", OPTION_STRING},\n    {\"tissueExpThresh\", OPTION_INT},\n    {\"otherTissExpThresh\", OPTION_INT},\n    {\"useMaxProbeSet\", OPTION_BOOLEAN},\n    {\"browser\", OPTION_STRING},\n    {\"brainSpecificStrict\", OPTION_BOOLEAN},\n    {\"tissueSpecific\", OPTION_STRING},\n    {\"brainTissues\", OPTION_STRING},\n    {\"combinePSets\", OPTION_BOOLEAN},\n    {\"useExonBeds\", OPTION_BOOLEAN},\n    {\"skipMotifControls\", OPTION_BOOLEAN},\n    {\"selectedPValues\", OPTION_STRING},\n    {\"selectedPValFile\", OPTION_STRING},\n    {\"outputProbeMatch\", OPTION_STRING},\n    {\"outputProbePvals\", OPTION_STRING},\n    {\"outputRatioStats\", OPTION_STRING},\n    {\"psToRefGene\", OPTION_STRING},\n    {\"psToKnownGene\", OPTION_STRING},\n    {\"splicePVals\", OPTION_STRING},\n    {\"cassetteBeds\", OPTION_STRING},\n    {\"newDb\", OPTION_STRING},\n    {\"flipScoreSort\", OPTION_BOOLEAN},\n    {\"conservedCassettes\", OPTION_STRING},\n    {\"notHumanCassettes\", OPTION_STRING},\n    {\"pValThresh\", OPTION_FLOAT},\n    {\"controlStats\", OPTION_STRING},\n    {\"sortScore\", OPTION_STRING},\n    {\"plotDir\", OPTION_STRING},\n    {\"minFlip\", OPTION_FLOAT},\n    {\"maxFlip\", OPTION_FLOAT},\n    {\"minIntCons\", OPTION_FLOAT},\n    {\"phastConsScores\", OPTION_STRING},\n    {\"muscleOn\", OPTION_BOOLEAN},\n    {\"presThresh\", OPTION_FLOAT},\n    {\"doTests\", OPTION_BOOLEAN},\n    {NULL, 0}\n};\n\n\nstatic char *optionDescripts[] =\n/* Description of our options for usage summary. */\n{\n    \"Display this message.\",\n    \"Bed format junction probe sets.\",\n    \"Splice format file containing alternative splicing events.\",\n    \"Data matrix with probability of transcription for each probe set.\",\n    \"Data matrix with intensity estimates for each probe set.\",\n    \"Database freeze of splices.\",\n    \"Generate ratios of probe sets of splice events to each other.\",\n    \"Output brain specific isoforms and dna.\",\n    \"How many tissues have to be seen before called expressed [default=1].\",\n    \"How many other tissues have to be seen before called expressed [default=1].\",\n    \"Instead of using best correlated probe set use all probe sets.\",\n    \"Browser to point at when creating web page.\",\n    \"Require each non-brain tissue to be below absThresh.\",\n    \"Output tissue specific counts for various events to this file.\",\n    \"Comma separated list of tissues to consider brain.\",\n    \"Combine the p-values for a path using Fisher's method.\",\n    \"Use exon beds, not just splice junction beds.\",\n    \"Skip looking at the motifs in the controls, can be quite slow.\",\n    \"File containing list of AFFY G###### ids and gene names.\",\n    \"File containing list of AFFY G###### ids and known gene ids.\",\n    \"File to output pvalue vectors for selected genes to.\",\n    \"Output the splicing events and the probes that were used.\",\n    \"Output the probe level pvals for each alternative event.\",\n    \"Output the ratio for altCassette, alt5, alt3, and altMutExclusive to file.\",\n    \"File with mapping from probe set to gene name.\",\n    \"File with pvalues for specific splices of interest.\",\n    \"Prefix for files to output not-expressed, expressed not alt, and alt cassette beds.\",\n    \"Genome to try and lift coordinates to.\",\n    \"Sort brain specific genes by flip score.\",\n    \"Cassettes that are conserved (in new genome).\",\n    \"Cassettes that are not in human (in new genome).\",\n    \"Threshold to filter pvalue at, default .001\",\n    \"Output some stats for control exons to this file.\",\n    \"Score to replace flipScore for sorting, etc.\",\n    \"Directory plots are in.\",\n    \"Minimum Flip Score to output fasta record for.\",\n    \"Maximum Flip Score to output fasta record for.\",\n    \"Minimum intron conservation percent to output fasta records for.\",\n    \"Conservation scores table where first column is skipping probeset.\",\n    \"Do muscle rather than brain, currently only effects some urls.\",\n    \"Threshold to be declared expressed.\",\n    \"Do some unit tests.\"\n};\n\n\nint isBrainTissue[256]; /* Global brain identifier. */\nstruct hash *liftOverHash = NULL; /* Hash holding chains for lifting. */\nstruct hash *bedHash = NULL; /* Access bed probe sets by hash. */\ndouble presThresh = .9;      /* Threshold for being called present. */\nint tissueExpThresh = 1;     /* Number of tissues something must be seen in to\n                                be considered expressed. */\ndouble absThresh = .1;       /* Threshold for being called not present. */\nboolean brainSpecificStrict = FALSE; /* Do we require that all non-brain tissues be below absThresh? */\nchar *browserName = NULL;    /* Name of browser that we are going to html link to. */\nchar *db = NULL;             /* Database version used here. */\nchar *newDb = NULL;             /* Database version lifting to. */\nboolean useMaxProbeSet;      /* Instead of using the best correlated probe set, use any\n                                probe set. */\nboolean useComboProbes = FALSE; /* Combine probe sets on a given path using fisher's method. */\nboolean useExonBedsToo = FALSE; /* Use exon beds too, not just splice junction beds. */\nint intronsConserved = 0;\nint intronsConsCounted = 0;\nstruct slRef *brainSpEvents = NULL; /* List of brain specific events. */\nFILE *constMotifCounts = NULL; /* Counts for each motif in constitutive exons. */\nFILE *probeMappingsOut = NULL;\nFILE *ratioStatOut = NULL;  /* File to output a matrix of ratios of skip/includes. */\nFILE *ratioSkipIntenOut = NULL; /* Intensity file for skip paths. */\nFILE *ratioIncIntenOut = NULL; /* Intensity file for skip paths. */\nFILE *ratioGeneIntenOut = NULL; /* Intensity file for gene probe set. */\nFILE *ratioProbOut = NULL; /* Probability gene is expressed. */\nFILE *incProbOut = NULL;   /* Include maximium probability values. */\nFILE *skipProbOut = NULL;   /* Skip maximum probability values. */\nFILE *incProbCombOut = NULL;   /* Include combined probability values. */\nFILE *skipProbCombOut = NULL;   /* Skip combined probability values. */\n\nFILE *pathProbabilitiesOut = NULL; /* File to print out path probability vectors. */\nFILE *pathExpressionOut = NULL; /* File to print out path probability vectors. */\nFILE *pathProbabilitiesBedOut = NULL; /* File to print out corresponding beds for paths. */\n\ndouble pvalThresh = 2; //.05 / 1263; /* Threshold at which we believe pval is real. */\nstruct hash *notHumanHash = NULL;    /* Hash of exons that are not even aligned to human. */\nstruct hash *conservedHash = NULL;   /* Hash of conserved exon events. */\nstruct hash *splicePValsHash = NULL; /* Hash of pvals of interest. */\nstruct hash *phastConsHash = NULL; /* Hash of conservation scores of interest. */\nstruct hash *sortScoreHash = NULL; /* Hash of scores of interest. */\nstruct hash *outputPValHash = NULL; /* Hash of selected names. */\nstruct hash *psToRefGeneHash = NULL; /* Hash of probe set to affy genes. */\nstruct hash *psToKnownGeneHash = NULL; /* Hash of probe set to known genes. */\n\nint otherTissueExpThres = 1; /* Number of other tissues something must be seen in to\n                                be considered expressed, used */\nstruct bindSite *bindSiteList = NULL; /* List of rna binding sites to look for. */\nstruct bindSite **bindSiteArray = NULL; /* array of rna binding sites to look for. */\nint bindSiteCount = 0;             /* Number of binding sites to loop through. */\nint cassetteExonCount = 0;         /* Number of cassette exons examined. */\nint cassetteExonSkipCount = 0;         /* Number of cassette exons examined. */\nint *cassetteUpMotifs = NULL;      /* Counts of motifs upstream cassette exons. */\nint *cassetteDownMotifs = NULL;    /* Counts of moitfs downstream cassette exons. */\nint *cassetteInsideMotifs = NULL;    /* Counts of moitfs downstream cassette exons. */\nint *cassetteSkipUpMotifs = NULL;      /* Counts of motifs upstream cassette exons for skipping exons. */\nint *cassetteSkipDownMotifs = NULL;    /* Counts of moitfs downstream cassette exon for skipping exons. */\nint *cassetteSkipInsideMotifs = NULL;    /* Counts of moitfs downstream cassette exons for skipping exons. */\nint cassetteSkipInsideBpCount = 0;    /* Counts of base pairs cassette exons for skipping exons. */\nint controlExonCount = 0;         /* Number of control exons examined. */\nint *controlUpMotifs = NULL;      /* Counts of motifs upstream cassette exons. */\nint *controlDownMotifs = NULL;    /* Counts of moitfs downstream cassette exons. */\nint *controlInsideMotifs = NULL;  /* Counts of moitfs inside cassette exons. */\nint controlInsideBpCount = 0;  /* Counts of moitfs inside cassette exons. */\nboolean skipMotifControls = FALSE; /* Skip looking for motifs in controls. */\nFILE *controlValuesOut = NULL;     /* File to output control values to. */\nstruct valuesMat *controlValuesVm = NULL; /* ValuesMat to keep track of various stats. */\nstruct valuesMat *brainSpecificValues = NULL; /* Values to keep track of for values. */\nint brainSpecificEventCount = 0;  /* How many brain specific events are there. */\nint brainSpecificEventCassCount = 0;  /* How many brain specific events are there. */\nint brainSpecificEventMutExCount = 0;  /* How many brain specific events are there. */\nint brainSpecificPathCount = 0;  /* How many brain specific paths are there. */\n\nFILE *brainSpValuesOut = NULL;  /* Value matrix outputted here. */\nFILE *brainSpDnaUpOut = NULL;  /* File for dna around first exon on\n\t\t\t      * brain specific isoforms. */\nFILE *brainSpConsDnaOut = NULL;\nFILE *brainSpConsBedOut = NULL;\nFILE *brainSpDnaUpDownOut = NULL;\nFILE *brainSpDnaDownOut = NULL;\nFILE *brainSpDnaMergedOut = NULL;\nFILE *brainSpBedUpOut = NULL;  /* File for paths (in bed format) that\n\t\t\t      * are brain specific. */\nFILE *brainSpBedDownOut = NULL;\nFILE *brainSpPathBedOut = NULL;\nFILE *brainSpPathEndsBedOut = NULL;\nFILE *brainSpPSetOut = NULL;\nFILE *brainSpPathBedExonUpOut = NULL;\nFILE *brainSpPathBedExonDownOut = NULL;\nFILE *brainSpTableHtmlOut = NULL; /* Html table for visualizing brain specific events. */\nFILE *brainSpFrameHtmlOut = NULL; /* Html frame for visualizing brain specific events. */\n\n\nstatic int *brainSpecificCounts;\nFILE *tissueSpecificOut = NULL;    /* File to output tissue specific results to. */\nboolean tissueSpecificStrict = FALSE; /* Do we require that all other tissues be below absThresh? */\nstatic int **tissueSpecificCounts; /* Array of counts for different tissue specific splice\n\t\t\t\t      types per tissue. */\nint *brainSpecificMotifUpCounts = NULL;\nint *brainSpecificMotifDownCounts = NULL;\nint *brainSpecificMotifInsideCounts = NULL;\nint brainSpecificMotifInsideBpCount = 0;\nFILE *expressedCassetteBedOut = NULL; /* Output beds for casssette exons that are expressed. */\nFILE *altCassetteBedOut = NULL;       /* Output beds for cassettte exons that are alt. expressed. */\nFILE *notExpressedCassetteBedOut = NULL; /* Output beds for cassette exons that don't look expressed. */\n\n/* Keep track of how many of each event are occuring. */\nstatic int alt5PrimeCount = 0;\nstatic int alt3PrimeCount = 0;\nstatic int altCassetteCount = 0;\nstatic int altRetIntCount = 0;\nstatic int altOtherCount = 0;\nstatic int alt3PrimeSoftCount = 0;\nstatic int alt5PrimeSoftCount = 0;\nstatic int altMutExclusiveCount = 0;\nstatic int altControlCount = 0;\n\n/* Keep track of how many of each event with probes */\nstatic int alt5PrimeWProbeCount = 0;\nstatic int alt3PrimeWProbeCount = 0;\nstatic int altCassetteWProbeCount = 0;\nstatic int altRetIntWProbeCount = 0;\nstatic int altOtherWProbeCount = 0;\nstatic int alt3PrimeSoftWProbeCount = 0;\nstatic int alt5PrimeSoftWProbeCount = 0;\nstatic int altMutExclusiveWProbeCount = 0;\nstatic int altControlWProbeCount = 0;\n\n/* Keep track of how many of each event expressed. */\nstatic int alt5PrimeExpCount = 0;\nstatic int alt3PrimeExpCount = 0;\nstatic int altCassetteExpCount = 0;\nstatic int altRetIntExpCount = 0;\nstatic int altOtherExpCount = 0;\nstatic int alt3PrimeSoftExpCount = 0;\nstatic int alt5PrimeSoftExpCount = 0;\nstatic int altMutExclusiveExpCount = 0;\nstatic int altControlExpCount = 0;\n\n/* Keep track of how many of each event alt-expressed */\nstatic int alt5PrimeAltExpCount = 0;\nstatic int alt3PrimeAltExpCount = 0;\nstatic int altCassetteAltExpCount = 0;\nstatic int altRetIntAltExpCount = 0;\nstatic int altOtherAltExpCount = 0;\nstatic int alt3PrimeSoftAltExpCount = 0;\nstatic int alt5PrimeSoftAltExpCount = 0;\nstatic int altMutExclusiveAltExpCount = 0;\nstatic int altControlAltExpCount = 0;\n\nvoid usage()\n/** Print usage and quit. */\n{\nint i=0;\nwarn(\"altProbes - Match probes to splicing paths and analyze.\\n\"\n     \"options are:\");\nfor(i=0; i<ArraySize(optionSpecs) -1; i++)\n    fprintf(stderr, \"  -%s -- %s\\n\", optionSpecs[i].name, optionDescripts[i]);\nerrAbort(\"\\nusage:\\n   \");\n}\n\nstruct splice *ndr2CassTest()\n/* Create a splice for use in testsing. */\n{\nchar *string = cloneString(\"chr14\t43771400\t43772080\tchr14.7822-8.26\t2\t-\t9319\t38\t43765895,43766921,43767127,43767179,43767304,43767340,43767563,43767611,43767860,43767912,43768199,43768244,43768682,43768786,43768944,43769001,43769182,43769269,43769488,43769549,43770672,43770735,43770929,43771050,43771294,43771356,43771400,43771404,43771700,43771742,43772080,43772161,43773937,43774090,43774093,43774180,43774538,43774609,\t0,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,1,3,2,1,3,1,3,1,1,2,2,1,2,\t2\t{\\\"chr14\\\",43771400,43772080,0,2,2,{26,30,},24,31,0,},{\\\"chr14\\\",43771400,43772080,0,4,4,{26,28,29,30,},24,31,42,},\");\nstruct splice *splice = NULL;\nchar *words[100];\nchopByWhite(string, words, sizeof(words));\nsplice = spliceLoad(words);\n}\n\nstruct bed *ndr2BedTest()\n/* Create beds used in testing. */\n{\nchar *inc1 = \"chr14\t43771385\t43771715\tG6912708@J918653_RC@j_at\t0\t-\t43771385\t43771715\t0\t2\t15,15,\t0,315,\";\nchar *skip = \"chr14\t43771385\t43772095\tG6912708@J918654_RC@j_at\t0\t-\t43771385\t43772095\t0\t2\t15,15,\t0,695,\";\nchar *inc2 = \"chr14\t43771727\t43772095\tG6912708@J918655_RC@j_at\t0\t-\t43771727\t43772095\t0\t2\t15,15,\t0,353,\";\nchar *gene = \"chr14\t43765981\t43772151\tG6912708_RC_a_at\t0\t-\t43765981\t43772151\t0\t9\t25,25,25,25,25,25,25,25,43,\t0,149,1602,3222,3262,3516,5000,5392,6127,\";\nstruct bed *bedList = NULL, *bed = NULL;\nchar *words[12];\n\nchopByWhite(cloneString(inc1), words, ArraySize(words));\nbed = bedLoadN(words,12);\nslAddHead(&bedList, bed);\n\nchopByWhite(cloneString(skip), words, ArraySize(words));\nbed = bedLoadN(words,12);\nslAddHead(&bedList, bed);\n\nchopByWhite(cloneString(inc2), words, ArraySize(words));\nbed = bedLoadN(words,12);\nslAddHead(&bedList, bed);\n\nchopByWhite(cloneString(gene), words, ArraySize(words));\nbed = bedLoadN(words,12);\nslAddHead(&bedList, bed);\n\nslReverse(&bedList);\nreturn bedList;\n}\n\nstruct dMatrix *ndr2BedTestMat(boolean probability)\n/* Create a fake matrix of probabilities. If probability is TRUE fill\n in a probability matrix, otherwise fill in an intensity matrix. */\n{\nstruct dMatrix *probs = NULL;\nstatic char *colNames[] = {\"cerebellum\", \"cortex\", \"heart\", \"skeletal\"};\nstatic char *rowNames[] = {\"G6912708@J918653_RC@j_at\", \"G6912708@J918654_RC@j_at\",\n\t\t    \"G6912708@J918655_RC@j_at\", \"G6912708_RC_a_at\"};\ndouble probM[4][4] = {{.8, 1, 0, .5},{0, 0, 0, 1}, {.8, 0, 0, .5}, {1, 0, .5, 1}};\ndouble intenM[4][4] = {{1, 1, 1, 2.5}, {1, 1, 1, 1}, {1, 1, 0, 1.5}, {1, 1, 1, .5}};\ndouble **matrix = NULL;\nint count = 0;\nAllocVar(probs);\nAllocArray(matrix, ArraySize(rowNames));\nprobs->nameIndex = newHash(3);\n\nfor(count = 0; count < ArraySize(colNames); count++)\n    {\n    if(probability)\n        matrix[count] = CloneArray(probM[count], ArraySize(probM[count]));\n    else\n        matrix[count] = CloneArray(intenM[count], ArraySize(intenM[count]));\n    hashAddInt(probs->nameIndex, rowNames[count], count);\n    }\n\nprobs->colNames = colNames;\nprobs->colCount = ArraySize(colNames);\nprobs->rowNames = rowNames;\nprobs->rowCount = ArraySize(rowNames);\nprobs->matrix = matrix;\nreturn probs;\n}\n\nstruct valuesMat *newValuesMat(int numCol, int numRow)\n/* Create a new values matrix. */\n{\nstruct valuesMat *vm = NULL;\nint i = 0;\nAllocVar(vm);\nvm->maxCols = numCol;\nvm->maxRows = numRow;\nAllocArray(vm->colNames, vm->maxCols);\nAllocArray(vm->rowNames, vm->maxRows);\nAllocArray(vm->vals, vm->maxRows);\nfor(i = 0; i < vm->maxRows; i++)\n    AllocArray(vm->vals[i], vm->maxCols);\nvm->rowIndex = newHash(round(logBase2(vm->maxCols) + .5));\nreturn vm;\n}\n\nvoid vmAddVal(struct valuesMat *vm, char *rowName, char *colName, char *val)\n/* Add item val to rowName in correct column. */\n{\nint i = 0;\nint colIx = -1;\nint rowIx = -1;\nassert(vm);\nassert(vm->rowIndex);\nassert(rowName);\nassert(val);\nassert(colName);\nfor( i = 0; i < vm->colCount; i++)\n    if(sameString(vm->colNames[i], colName))\n\t{\n\tcolIx = i;\n\tbreak;\n\t}\n\n/* If column not existent add it. */\nif(colIx == -1)\n    {\n    if(vm->colCount + 1 >= vm->maxCols)\n\t{\n\tExpandArray(vm->colNames, vm->maxCols, vm->maxCols+1);\n\tfor(i = 0; i < vm->rowCount; i++)\n\t    ExpandArray(vm->vals[i], vm->maxCols, vm->maxCols+1);\n\tvm->maxCols++;\n\t}\n    colIx = vm->colCount;\n    vm->colNames[colIx] = cloneString(colName);\n    vm->colCount++;\n    }\n\n/* Get the row for that identifier. */\nrowIx = hashIntValDefault(vm->rowIndex, rowName, -1);\nif(rowIx == -1)\n    {\n    if(vm->rowCount + 1 >= vm->maxRows)\n\t{\n\tExpandArray(vm->rowNames, vm->maxRows, vm->maxRows+1);\n\tExpandArray(vm->vals, vm->maxRows, vm->maxRows+1);\n\tAllocArray(vm->vals[vm->maxRows], vm->maxCols);\n\tvm->maxRows++;\n\t}\n    rowIx = vm->rowCount;\n    vm->rowNames[rowIx] = cloneString(rowName);\n    hashAddInt(vm->rowIndex, rowName, rowIx);\n    vm->rowCount++;\n    }\nvm->vals[rowIx][colIx] = cloneString(val);\n}\n\nvoid vmWriteVals(struct valuesMat *vm, FILE *out)\n/* Writ out the vm. */\n{\nint colIx = 0, rowIx = 0;\nfor(colIx = 0; colIx < vm->colCount - 1; colIx++)\n    fprintf(out, \"%s\\t\", vm->colNames[colIx]);\nfprintf(out, \"%s\\n\", vm->colNames[colIx]);\n\nfor(rowIx = 0; rowIx < vm->rowCount; rowIx++)\n    {\n    fprintf(out, \"%s\\t\", vm->rowNames[rowIx]);\n    for(colIx = 0; colIx < vm->colCount -1; colIx++)\n\tfprintf(out, \"%s\\t\", vm->vals[rowIx][colIx]);\n    fprintf(out, \"%s\\n\", vm->vals[rowIx][colIx]);\n    }\n}\n\nvoid logSpliceType(enum altSpliceType type)\n/* Log the different types of splicing. */\n{\nswitch (type)\n    {\n    case alt5Prime:\n\talt5PrimeCount++;\n\tbreak;\n    case alt3Prime:\n\talt3PrimeCount++;\n\tbreak;\n    case altCassette:\n\taltCassetteCount++;\n\tbreak;\n    case altRetInt:\n\taltRetIntCount++;\n\tbreak;\n    case altOther:\n\taltOtherCount++;\n\tbreak;\n    case alt5PrimeSoft:\n\talt5PrimeSoftCount++;\n\tbreak;\n    case alt3PrimeSoft:\n\talt3PrimeSoftCount++;\n\tbreak;\n    case altMutExclusive:\n\taltMutExclusiveCount++;\n\tbreak;\n    case altControl:\n\taltControlCount++;\n\tbreak;\n    default:\n\terrAbort(\"logSpliceType() - Don't recognize type %d\", type);\n    }\n}\n\n\nvoid logSpliceTypeWProbe(enum altSpliceType type)\n/* Log the different types of splicing. */\n{\nswitch (type)\n    {\n    case alt5Prime:\n\talt5PrimeWProbeCount++;\n\tbreak;\n    case alt3Prime:\n\talt3PrimeWProbeCount++;\n\tbreak;\n    case altCassette:\n\taltCassetteWProbeCount++;\n\tbreak;\n    case altRetInt:\n\taltRetIntWProbeCount++;\n\tbreak;\n    case altOther:\n\taltOtherWProbeCount++;\n\tbreak;\n    case alt5PrimeSoft:\n\talt5PrimeSoftWProbeCount++;\n\tbreak;\n    case alt3PrimeSoft:\n\talt3PrimeSoftWProbeCount++;\n\tbreak;\n    case altMutExclusive:\n\taltMutExclusiveWProbeCount++;\n\tbreak;\n    case altControl:\n\taltControlWProbeCount++;\n\tbreak;\n    default:\n\terrAbort(\"logSpliceType() - Don't recognize type %d\", type);\n    }\n}\n\nvoid logSpliceTypeExp(enum altSpliceType type)\n/* Log the different types of splicing. */\n{\nswitch (type)\n    {\n    case alt5Prime:\n\talt5PrimeExpCount++;\n\tbreak;\n    case alt3Prime:\n\talt3PrimeExpCount++;\n\tbreak;\n    case altCassette:\n\taltCassetteExpCount++;\n\tbreak;\n    case altRetInt:\n\taltRetIntExpCount++;\n\tbreak;\n    case altOther:\n\taltOtherExpCount++;\n\tbreak;\n    case alt5PrimeSoft:\n\talt5PrimeSoftExpCount++;\n\tbreak;\n    case alt3PrimeSoft:\n\talt3PrimeSoftExpCount++;\n\tbreak;\n    case altMutExclusive:\n\taltMutExclusiveExpCount++;\n\tbreak;\n    case altControl:\n\taltControlExpCount++;\n\tbreak;\n    default:\n\terrAbort(\"logSpliceType() - Don't recognize type %d\", type);\n    }\n}\n\nvoid logSpliceTypeAltExp(enum altSpliceType type)\n/* Log the different types of splicing. */\n{\nswitch (type)\n    {\n    case alt5Prime:\n\talt5PrimeAltExpCount++;\n\tbreak;\n    case alt3Prime:\n\talt3PrimeAltExpCount++;\n\tbreak;\n    case altCassette:\n\taltCassetteAltExpCount++;\n\tbreak;\n    case altRetInt:\n\taltRetIntAltExpCount++;\n\tbreak;\n    case altOther:\n\taltOtherAltExpCount++;\n\tbreak;\n    case alt5PrimeSoft:\n\talt5PrimeSoftAltExpCount++;\n\tbreak;\n    case alt3PrimeSoft:\n\talt3PrimeSoftAltExpCount++;\n\tbreak;\n    case altMutExclusive:\n\taltMutExclusiveAltExpCount++;\n\tbreak;\n    case altControl:\n\taltControlAltExpCount++;\n\tbreak;\n    default:\n\terrAbort(\"logSpliceType() - Don't recognize type %d\", type);\n    }\n}\n\nvoid initSplicePVals()\n/* Load up the pvals of interest generated in a separate file. */\n{\nstruct lineFile *lf = NULL;\nchar *fileName = optionVal(\"splicePVals\", NULL);\nchar *words[2];\nstruct slDouble *sd = NULL;\nassert(fileName);\nsplicePValsHash = newHash(10);\nlf = lineFileOpen(fileName, TRUE);\nwhile(lineFileNextRow(lf, words, ArraySize(words)))\n    {\n    char *mark = NULL;\n    hashAdd(splicePValsHash, words[0], slDoubleNew(sqlDouble((words[1]))));\n    }\nlineFileClose(&lf);\n}\n\ndouble pvalForSplice(char *name)\n/* Return a pval as specified in the splicePVal file or 2 if not there. */\n{\nstruct slDouble *d = NULL;\nif(splicePValsHash == NULL)\n    errAbort(\"Need to specify -splicePVal file if using pvalForSplice\");\nassert(name);\nd = hashFindVal(splicePValsHash, name);\nif(d == NULL)\n    return 2.0;\nreturn d->val;\n}\n\nvoid initPhastConsScores()\n/* Load up the conservation scores of interest generated in a separate file. */\n{\nstruct lineFile *lf = NULL;\nchar *fileName = optionVal(\"phastConsScores\", NULL);\nchar *words[2];\nstruct slDouble *sd = NULL;\nassert(fileName);\nphastConsHash = newHash(10);\nlf = lineFileOpen(fileName, TRUE);\nwhile(lineFileNextRow(lf, words, ArraySize(words)))\n    {\n    hashAdd(phastConsHash, words[0], slDoubleNew(sqlDouble((words[1]))));\n    }\nlineFileClose(&lf);\n}\n\ndouble phastConsForSplice(char *name)\n/* Return a phast cons score associated with the splicing event. */\n{\nstruct slDouble *d = NULL;\nif(phastConsHash == NULL)\n    errAbort(\"Need to specify -phastConsScores file if using phastConsForSplice\");\nassert(name);\nd = hashFindVal(phastConsHash, name);\nif(d == NULL)\n    return -1;\nreturn d->val;\n}\n\nvoid initSortScore()\n/* Load up the pvals of interest generated in a separate file. */\n{\nstruct lineFile *lf = NULL;\nchar *fileName = optionVal(\"sortScore\", NULL);\nchar *words[2];\nstruct slDouble *sd = NULL;\nassert(fileName);\nsortScoreHash = newHash(10);\nlf = lineFileOpen(fileName, TRUE);\nwhile(lineFileNextRow(lf, words, ArraySize(words)))\n    {\n    char *mark = NULL;\n    double d = 0;\n    d = sqlDouble(words[1]);\n    sd = slDoubleNew(d);\n    hashAddUnique(sortScoreHash, words[0], sd);\n    }\nlineFileClose(&lf);\n}\n\ndouble sortScoreForSplice(char *name)\n/* Return a pval as specified in the splicePVal file or 2 if not there. */\n{\nstruct slDouble *d = NULL;\nif(sortScoreHash == NULL)\n    errAbort(\"Need to specify -sortScore file if using sortScoreForSplice\");\nassert(name);\nd = hashFindVal(sortScoreHash, name);\nif(d == NULL)\n    return 0;\nreturn d->val;\n}\n\nvoid initPsToRefGene()\n/* Load up a file that converts from affy psName to gene names. */\n{\nstruct lineFile *lf = NULL;\nchar *fileName = optionVal(\"psToRefGene\", NULL);\nchar *words[2];\nassert(fileName);\npsToRefGeneHash = newHash(10);\nlf = lineFileOpen(fileName, TRUE);\nwhile(lineFileNextRow(lf, words, ArraySize(words)))\n    {\n    hashAdd(psToRefGeneHash, words[1], cloneString(words[0]));\n    }\nlineFileClose(&lf);\n}\n\nchar *refSeqForPSet(char *pSet)\n/* Look up the refseq name for a probe set. */\n{\nstatic boolean warned = FALSE;\nchar *gene = NULL;\nif(psToRefGeneHash == NULL)\n    {\n    if(warned != TRUE)\n\twarn(\"Can't convert psName to refSeq name, have to specify psToRefGene flag.\");\n    warned = TRUE;\n    return pSet;\n    }\ngene = hashFindVal(psToRefGeneHash, pSet);\nif(gene == NULL)\n    return pSet;\nreturn gene;\n}\n\nvoid initPsToKnownGene()\n/* Load up a file that converts from affy psName to gene names. */\n{\nstruct lineFile *lf = NULL;\nchar *fileName = optionVal(\"psToKnownGene\", NULL);\nchar *words[2];\nassert(fileName);\npsToKnownGeneHash = newHash(10);\nlf = lineFileOpen(fileName, TRUE);\nwhile(lineFileNextRow(lf, words, ArraySize(words)))\n    {\n    hashAdd(psToKnownGeneHash, words[1], cloneString(words[0]));\n    }\nlineFileClose(&lf);\n}\n\nchar *knownGeneForPSet(char *pSet)\n/* Look up the refseq name for a probe set. */\n{\nstatic boolean warned = FALSE;\nchar *gene = NULL;\nif(psToKnownGeneHash == NULL)\n    {\n    if(warned != TRUE)\n\terrAbort(\"Can't convert psName to known name, have to specify psToKnowngene flag.\");\n    warned = TRUE;\n    return pSet;\n    }\ngene = hashFindVal(psToKnownGeneHash, pSet);\nif(gene == NULL)\n    return pSet;\nreturn gene;\n}\n\n\nvoid initBindSiteList()\n/* Create a little hand curated knowledge about binding sites. */\n{\nstruct bindSite *bsList = NULL, *bs = NULL;\nint i = 0;\n\n/* Nova-1 */\nAllocVar(bs);\nbs->motifCount = 2;\nAllocArray(bs->motifs, bs->motifCount);\n/* Expand TCATY */\nbs->motifs[i++] = cloneString(\"TCATT\");\nbs->motifs[i++] = cloneString(\"TCATC\");\nbs->rnaBinder = cloneString(\"Nova-1\");\nslAddHead(&bsList, bs);\n\n/* Fox-1 */\nAllocVar(bs);\nbs->motifCount = 1;\nAllocArray(bs->motifs, bs->motifCount);\nbs->motifs[0] = cloneString(\"GCATG\");\nbs->rnaBinder = cloneString(\"Fox-1\");\nslAddHead(&bsList, bs);\n\n/* PTB */\nAllocVar(bs);\nbs->motifCount = 1;\nAllocArray(bs->motifs, bs->motifCount);\nbs->motifs[0] = cloneString(\"CTCTCT\");\nbs->rnaBinder = cloneString(\"PTB/nPTB\");\nslAddHead(&bsList, bs);\n\n/* hnRNPs */\nAllocVar(bs);\nbs->motifCount = 1;\nAllocArray(bs->motifs, bs->motifCount);\nbs->motifs[0] = cloneString(\"GGGG\");\nbs->rnaBinder = cloneString(\"hnRNP-H/F\");\nslAddHead(&bsList, bs);\n\n/* /\\* First motif... *\\/ */\n/* i = 0; */\n/* AllocVar(bs); */\n/* bs->motifCount = 16; */\n/* AllocArray(bs->motifs, bs->motifCount); */\n/* /\\* (YNCURY; Y, pyrimidine; R, purine; N, any nucleotide; the branch point adenosine is underlined*\\/ */\n/* bs->motifs[i++] = cloneString(\"TACTAAT\"); */\n/* bs->motifs[i++] = cloneString(\"TGCTAAT\"); */\n/* bs->motifs[i++] = cloneString(\"TTCTAAT\"); */\n/* bs->motifs[i++] = cloneString(\"TCCTAAT\"); */\n\n/* bs->motifs[i++] = cloneString(\"TACTAAC\"); */\n/* bs->motifs[i++] = cloneString(\"TGCTAAC\"); */\n/* bs->motifs[i++] = cloneString(\"TTCTAAC\"); */\n/* bs->motifs[i++] = cloneString(\"TCCTAAC\"); */\n\n/* bs->motifs[i++] = cloneString(\"TATTAAT\"); */\n/* bs->motifs[i++] = cloneString(\"TGTTAAT\"); */\n/* bs->motifs[i++] = cloneString(\"TTTTAAT\"); */\n/* bs->motifs[i++] = cloneString(\"TCTTAAT\"); */\n\n/* bs->motifs[i++] = cloneString(\"TATTAAC\"); */\n/* bs->motifs[i++] = cloneString(\"TGTTAAC\"); */\n/* bs->motifs[i++] = cloneString(\"TTTTAAC\"); */\n/* bs->motifs[i++] = cloneString(\"TCTTAAC\"); */\n/* bs->rnaBinder = cloneString(\"TNCTAAC/T\"); */\n/* slAddHead(&bsList, bs); */\n\ni = 0;\nAllocVar(bs);\nbs->motifCount = 1;\nAllocArray(bs->motifs, bs->motifCount);\nbs->motifs[i++] = cloneString(\"CTAAC\");\nbs->rnaBinder = cloneString(\"CTAAC\");\nslAddHead(&bsList, bs);\n\ni = 0;\nAllocVar(bs);\nbs->motifCount = 2;\nAllocArray(bs->motifs, bs->motifCount);\nbs->motifs[i++] = cloneString(\"TGCTTTC\");\nbs->motifs[i++] = cloneString(\"TGTTTTC\");\nbs->rnaBinder = cloneString(\"TGYTTTC\");\nslAddHead(&bsList, bs);\n\ni = 0;\nAllocVar(bs);\nbs->motifCount = 1;\nAllocArray(bs->motifs, bs->motifCount);\nbs->motifs[i++] = cloneString(\"TAGGG\");\nbs->rnaBinder = cloneString(\"hnRNP-A1\");\nslAddHead(&bsList, bs);\n\ni = 0;\nAllocVar(bs);\nbs->motifCount = 2;\nAllocArray(bs->motifs, bs->motifCount);\nbs->motifs[i++] = cloneString(\"TCCTTT\");\nbs->motifs[i++] = cloneString(\"TGCTTT\");\nbs->rnaBinder = cloneString(\"TG/CCTTT\");\nslAddHead(&bsList, bs);\n\n/* i = 0; */\n/* AllocVar(bs); */\n/* bs->motifCount = 2; */\n/* AllocArray(bs->motifs, bs->motifCount); */\n/* bs->motifs[i++] = cloneString(\"TGCTTTCC\"); */\n/* bs->motifs[i++] = cloneString(\"TGTTTTCC\"); */\n/* bs->rnaBinder = cloneString(\"TGC/TTTTCC\"); */\n/* slAddHead(&bsList, bs); */\n\n/* First discovered motif... */\nAllocVar(bs);\nbs->motifCount = 1;\nAllocArray(bs->motifs, bs->motifCount);\nbs->motifs[0] = cloneString(\"TCCTT\");\nbs->rnaBinder = cloneString(\"TCCTT\");\nslAddHead(&bsList, bs);\n\nslReverse(&bsList);\nbindSiteList = bsList;\nAllocArray(bindSiteArray, slCount(bsList));\nfor(bs = bsList; bs != NULL; bs = bs->next)\n    bindSiteArray[bindSiteCount++] = bs;\n\nAllocArray(cassetteUpMotifs, bindSiteCount);\nAllocArray(cassetteDownMotifs, bindSiteCount);\nAllocArray(cassetteInsideMotifs, bindSiteCount);\nAllocArray(cassetteSkipUpMotifs, bindSiteCount);\nAllocArray(cassetteSkipDownMotifs, bindSiteCount);\nAllocArray(cassetteSkipInsideMotifs, bindSiteCount);\nAllocArray(controlUpMotifs, bindSiteCount);\nAllocArray(controlDownMotifs, bindSiteCount);\nAllocArray(controlInsideMotifs, bindSiteCount);\n}\n\nboolean isJunctionBed(struct bed *bed)\n/* Return TRUE if bed looks like a junction probe. Specifically\n   two blocks, each 15bp. FALSE otherwise. */\n{\nif(bed->blockCount == 2 && bed->blockSizes[0] == 15 && bed->blockSizes[1] == 15)\n    return TRUE;\nreturn FALSE;\n}\n\nboolean validVertex(struct splice *splice, int v1, int v2)\n/* Check to see if a given vertex is the sink or source of the\n   graph and should be ignored. */\n{\nreturn (v1 >= 0 && v1 < splice->vCount && v2 >= 0 && v2 < splice->vCount);\n}\n\nenum ggEdgeType pathEdgeTypeValid(struct splice *s, int v1, int v2)\n{\nassert(validVertex(s, v1,v2));\nreturn pathEdgeType(s->vTypes, v1, v2);\n}\n\nboolean pathContainsIntron(struct splice *splice, struct path *path, char *chrom,\n\t\t\t   int chromStart, int chromEnd, char *strand)\n/* Return TRUE if this path contains an intron (splice junction) that\n   starts at chromStart and ends at chromEnd. */\n{\nint i = 0;\nint *vPos = splice->vPositions;\nint *verts = path->vertices;\nif (differentString(splice->tName, chrom) ||\n   differentString(splice->strand, strand))\n    return FALSE;\n\n/* Check the edges on the path. */\nfor(i = 0; i < path->vCount - 1; i++)\n    {\n    if(validVertex(splice, verts[i], verts[i+1]) &&\n       pathEdgeTypeValid(splice, verts[i], verts[i+1]) == ggSJ)\n\t{\n\tif(chromStart == vPos[verts[i]] && chromEnd == vPos[verts[i+1]])\n\t    return TRUE;\n\t}\n    }\nreturn FALSE;\n}\n\nboolean pathContainsBlock(struct splice *splice, struct path *path, char *chrom,\n\t\t\t  int chromStart, int chromEnd, char *strand,\n\t\t\t  boolean allBases)\n/* Return TRUE if this block is contained in the path, FALSE otherwise.\n   If allBases then every base in chromStart-chromEnd must be covered\n   by path. */\n{\nint i = 0;\nint *vPos = splice->vPositions;\nint *verts = path->vertices;\nif (differentString(splice->tName, chrom) ||\n   differentString(splice->strand, strand))\n    return FALSE;\n\n/* Check the first edge. */\nif(validVertex(splice, path->upV, verts[0]) &&\n   pathEdgeTypeValid(splice, path->upV,verts[0]) == ggExon)\n    {\n    if(chromStart >= vPos[path->upV] && chromEnd <= vPos[verts[0]])\n        return TRUE;\n    else if (!allBases && rangeIntersection(chromStart, chromEnd,\n                                            vPos[path->upV], vPos[verts[0]]) > 0)\n        return TRUE;\n    }\n\n/* Check the last edge. */\nif(validVertex(splice, verts[path->vCount -1], path->downV) &&\n   pathEdgeTypeValid(splice, verts[path->vCount - 1], path->downV) == ggExon)\n    {\n    if (chromStart >= vPos[verts[path->vCount - 1]] &&\n       chromEnd <= vPos[path->downV])\n        return TRUE;\n    else if (!allBases &&\n             rangeIntersection(chromStart, chromEnd,\n                               vPos[verts[path->vCount - 1]], vPos[path->downV])  > 0)\n        return TRUE;\n    }\n\n/* Check the edges on the path. */\nfor(i = 0; i < path->vCount - 1; i++)\n    {\n    if(validVertex(splice, verts[i], verts[i+1]) &&\n       pathEdgeTypeValid(splice, verts[i], verts[i+1]) == ggExon)\n        {\n        if (chromStart >= vPos[verts[i]] && chromEnd <= vPos[verts[i+1]])\n            return TRUE;\n        else if (!allBases && rangeIntersection(chromStart, chromEnd,\n                                                vPos[verts[i]], vPos[verts[i+1]]) > 0)\n            return TRUE;\n        }\n    }\nreturn FALSE;\n}\n\nboolean pathContainsBed(struct splice *splice, struct path *path,\n                        struct bed *bed,  boolean intronsToo)\n/* Return TRUE if this path contains this bed, FALSE otherwise. If\n   allBases, the bed must be completely subsumed by the path. */\n{\nboolean containsBed = TRUE;\nint i = 0;\nassert(bed);\nfor(i = 0; i < bed->blockCount; i++)\n    {\n    int chromStart = bed->chromStart + bed->chromStarts[i];\n    int chromEnd = bed->chromStart + bed->chromStarts[i] + bed->blockSizes[i];\n\n    /* Check the exon. */\n    containsBed &= pathContainsBlock(splice, path, bed->chrom, chromStart,\n\t\t\t\t     chromEnd, bed->strand, TRUE);\n    if(containsBed == FALSE)\n        break;\n\n    /* Check the next intron. */\n    if (intronsToo && i+1 != bed->blockCount)\n        containsBed &= pathContainsIntron(splice, path, bed->chrom, chromEnd,\n                                          bed->chromStarts[i+1]+chromStart, bed->strand);\n    }\nreturn containsBed;\n}\n\nvoid insertBedIntoPath(struct altEvent *altEvent, struct altPath *altPath,\n\t\t       struct bed *bed)\n/* Add the cbed to this path. */\n{\nint pCount = 0;\nassert(altPath);\npCount = altPath->probeCount;\nExpandArray(altPath->beds, pCount, pCount+1);\nExpandArray(altPath->bedTypes, pCount, pCount+1);\naltPath->beds[altPath->probeCount++] = bed;\n}\n\nint findProbeSetsForEvents(struct altEvent *altEvent)\n/* Look for all of the beds that overlap a splice and match\n   them the ones that are uniq to a path. Returns the number\n   of probes that map to this splice. */\n{\nstruct binElement *be = NULL, *beList = NULL;\nstruct altPath *altPath = NULL, *altMatchPath = NULL;\nstruct bed *bed = NULL;\n\nassert(altEvent);\nstruct splice *splice = altEvent->splice;\n/* Load all the beds that span this range. */\nbeList = chromKeeperFind(splice->tName, splice->tStart, splice->tEnd);\nfor(be = beList; be != NULL; be = be->next)\n    {\n    bed = be->val;\n    if(isJunctionBed(bed) || (useExonBedsToo && strchr(bed->name, '@') != NULL))\n\t{\n\taltMatchPath = NULL; /* Indicates that we haven't found a match for this bed. */\n\tfor(altPath = altEvent->altPathList; altPath != NULL; altPath = altPath->next)\n\t    {\n\t    /* If it is a junction pass the intronsToo flag == TRUE, otherwise\n\t       set to false. */\n\t    if((isJunctionBed(bed) && pathContainsBed(splice, altPath->path, bed, TRUE)) ||\n\t       (!isJunctionBed(bed) && pathContainsBed(splice, altPath->path, bed, FALSE)))\n\t\t{\n\t\tif(altMatchPath == NULL)\n\t\t    altMatchPath = altPath; /* So far unique match. */\n\t\telse\n\t\t    { /* Not a unique match. */\n\t\t    altMatchPath = NULL;\n\t\t    break;\n\t\t    }\n\t\t}\n\t    }\n\t}\n    else\n\tcontinue;\n    /* If we've uniquely found a path for a bed insert it. */\n    if(altMatchPath != NULL)\n\tinsertBedIntoPath(altEvent, altMatchPath, bed);\n    }\n\n/* Count up how many paths have probes. */\nfor(altPath = altEvent->altPathList; altPath != NULL; altPath = altPath->next)\n    if(altPath->probeCount > 0)\n        altEvent->altPathProbeCount++;\n}\n\nvoid bedLoadChromKeeper()\n/* Load the beds's in the file into the chromKeeper. */\n{\nchar *db = optionVal(\"db\", NULL);\nchar *bedFile = optionVal(\"junctionProbes\", NULL);\nstruct bed *bed = NULL, *bedList = NULL;\nbedHash = newHash(12);\nif(db == NULL)\n    errAbort(\"Must specify a database when loading beds.\");\nif(bedFile == NULL)\n    errAbort(\"Must specify a file for loading beds.\");\nchromKeeperInit(db);\nbedList = bedLoadAll(bedFile);\nfor(bed = bedList; bed != NULL; bed = bed->next)\n    {\n    chromKeeperAdd(bed->chrom, bed->chromStart, bed->chromEnd, bed);\n    hashAdd(bedHash, bed->name, bed);\n    }\n}\n\nstruct altEvent *altEventsFromSplices(struct splice *spliceList)\n/* Create the altEvents and altPaths from the spliceList. */\n{\nstruct splice *splice = NULL;\nstruct path *path = NULL;\nstruct altEvent *event = NULL, *eventList = NULL;\nstruct altPath *altPath = NULL, *altPathList = NULL;\nfor(splice = spliceList; splice != NULL; splice = splice->next)\n    {\n    AllocVar(event);\n    event->splice = splice;\n    for(path = splice->paths; path != NULL; path = path->next)\n\t{\n\tAllocVar(altPath);\n\taltPath->score = 1;\n\taltPath->path = path;\n\tslAddHead(&event->altPathList, altPath);\n\t}\n    slReverse(&event->altPathList);\n    slAddHead(&eventList, event);\n    }\nslReverse(&eventList);\nreturn eventList;\n}\n\nvoid fillInAltPathData(struct altPath *altPath, struct dMatrix *intenM,\n\t\t     struct dMatrix *probM)\n/* Fill in the data for the probes that map to this\n   altPath. */\n{\nint i = 0;\nint pCount = altPath->probeCount;\n\nif(pCount == 0)\n    return;\n\nAllocArray(altPath->expVals, pCount);\nAllocArray(altPath->pVals, pCount);\nAllocArray(altPath->avgExpVals, pCount);\nfor(i = 0; i < pCount; i++)\n    {\n    int index = hashIntValDefault(intenM->nameIndex, altPath->beds[i]->name, -1);\n    if(index != -1)\n\taltPath->expVals[i] = intenM->matrix[index];\n    index = hashIntValDefault(probM->nameIndex, altPath->beds[i]->name, -1);\n    if(index != -1)\n\taltPath->pVals[i] = probM->matrix[index];\n    }\n}\n\nchar *altGeneNameForPSet(struct bed *bed)\n/* Do some parsing of the bed name and assemble\n   a gene name. */\n{\nstatic char altGeneName[256]; /* static so memory char * can be returned. */\nchar buff[256];\nchar *mark = NULL;\nchar *extra = \"EX\";\n*altGeneName = '\\0';\nsafef(buff, sizeof(buff), \"%s\", bed->name);\nmark = strchr(buff, '@');\nif(mark != NULL)\n    {\n    *mark = '\\0';\n\n    /* If not looking for altSet skip the extra string. */\n    if(stringIn(\"RC\", bed->name))\n\tsafef(altGeneName, sizeof(altGeneName), \"%s%s_RC_a_at\", buff, extra);\n    else\n\tsafef(altGeneName, sizeof(altGeneName), \"%s%s_a_at\", buff, extra);\n    return altGeneName;\n    }\nreturn NULL;\n\n}\n\nchar *geneNameForPSet(struct bed *bed)\n/* Do some parsing of the bed name and assemble\n   a gene name. */\n{\nstatic char geneName[256]; /* static so memory char * can be returned. */\nchar buff[256];\nchar *mark = NULL;\nchar *extra = \"EX\";\n*geneName = '\\0';\nsafef(buff, sizeof(buff), \"%s\", bed->name);\nmark = strchr(buff, '@');\nif(mark != NULL)\n    {\n    *mark = '\\0';\n\n    /* If not looking for altSet skip the extra string. */\n    extra = \"\";\n    if(stringIn(\"RC\", bed->name))\n\tsafef(geneName, sizeof(geneName), \"%s%s_RC_a_at\", buff, extra);\n    else\n\tsafef(geneName, sizeof(geneName), \"%s%s_a_at\", buff, extra);\n    return geneName;\n    }\nreturn NULL;\n\n}\n\nvoid fillInGeneData(struct altEvent *altEvent, struct dMatrix *intenM,\n\t\t     struct dMatrix *probM)\n/* Fill in the gene probe set data for this event. */\n{\nint i = 0;\nstruct altPath *altPath = NULL;\n\nfor(altPath = altEvent->altPathList; altPath != NULL; altPath = altPath->next)\n    {\n    if(altPath->probeCount > 0)\n\t{\n\tint index = -1;\n\tint altIndex = -1;\n\tchar *geneName = NULL, *altGeneName = NULL;\n\tint geneCount = 0;\n\t/* Find the indexes of the possible gene sets. */\n\tgeneName = geneNameForPSet(altPath->beds[0]);\n\tindex = hashIntValDefault(intenM->nameIndex, geneName, -1);\n\taltGeneName = altGeneNameForPSet(altPath->beds[0]);\n\taltIndex = hashIntValDefault(intenM->nameIndex, altGeneName, -1);\n\n\t/* Count how many probes we found. */\n\tif(index != -1)\n\t    geneCount++;\n\tif(altIndex != -1)\n\t    geneCount++;\n\n\tif(geneCount > 0)\n\t    {\n\t    /* Allocate some memory. */\n\t    AllocArray(altEvent->geneBeds, geneCount);\n\t    AllocArray(altEvent->geneExpVals, geneCount);\n\t    AllocArray(altEvent->genePVals, geneCount);\n\t    AllocArray(altEvent->avgExpVals, geneCount);\n\t    altEvent->geneProbeCount = geneCount;\n\n\t    /* If we found the main name look it up. */\n\t    if(index != -1)\n\t\t{\n\t\taltEvent->geneBeds[0] = hashFindVal(bedHash, geneName);\n\t\taltEvent->geneExpVals[0] = intenM->matrix[index];\n\t\tindex =  hashIntValDefault(probM->nameIndex, geneName, -1);\n\t\tif(index != -1)\n\t\t    altEvent->genePVals[0] = probM->matrix[index];\n\t\t}\n\t    /* Try the alternative gene probe set. */\n\t    if(altIndex != -1)\n\t\t{\n\t\tint offSet = geneCount - 1;\n\t\taltEvent->geneBeds[offSet] = hashFindVal(bedHash, altGeneName);\n\t\taltEvent->geneExpVals[offSet] = intenM->matrix[altIndex];\n\t\tindex =  hashIntValDefault(probM->nameIndex, altGeneName, -1);\n\t\tif(index != -1)\n\t\t    altEvent->genePVals[offSet] = probM->matrix[index];\n\t\t}\n\t    }\n\t}\n    }\n}\n\nvoid fillInEventData(struct altEvent *eventList, struct dMatrix *intenM,\n\t\t     struct dMatrix *probM)\n/* Loop through the eventList and fill in the altPaths with\n   data in intenM and probM. */\n{\nstruct altEvent *event = NULL;\nstruct altPath *altPath = NULL;\nfor(event = eventList; event != NULL; event = event->next)\n    {\n    for(altPath = event->altPathList; altPath != NULL; altPath = altPath->next)\n\t{\n\tfillInAltPathData(altPath, intenM, probM);\n\t}\n    fillInGeneData(event, intenM, probM);\n    }\n}\n\ndouble geneExpression(struct altEvent *event, int tissueIx)\n/* Return maximum pval for all the gene sets. */\n{\ndouble maxInten = -1;\nint geneIx = 0;\nfor(geneIx = 0; geneIx < event->geneProbeCount; geneIx++)\n    {\n    if(event->geneExpVals[geneIx] != NULL &&\n       (event->geneExpVals[geneIx][tissueIx] >= maxInten))\n\tmaxInten = event->geneExpVals[geneIx][tissueIx];\n    }\nreturn maxInten;\n}\n\n\ndouble genePVal(struct altEvent *event, int tissueIx)\n/* Return maximum pval for all the gene sets. */\n{\ndouble maxPval = -1;\nint geneIx = 0;\nfor(geneIx = 0; geneIx < event->geneProbeCount; geneIx++)\n    {\n    if(event->genePVals[geneIx] != NULL &&\n       (event->genePVals[geneIx][tissueIx] >= maxPval))\n\tmaxPval = event->genePVals[geneIx][tissueIx];\n    }\nreturn maxPval;\n}\n\n\nboolean geneExpressed(struct altEvent *event, int tissueIx)\n/* Return TRUE if any of the gene probe sets are expressed in\n   this tissue. */\n{\nif(genePVal(event, tissueIx) >= presThresh)\n    return TRUE;\nreturn FALSE;\n}\n\nvoid printVars(double *preLog, double *log)\n{\nprintf(\"Pre-Log %.20f, Log() %.20f\\n\", preLog, log);\n}\n\ndouble pvalAltPathMaxExpressed(struct altPath *altPath, int tissueIx)\n/* Return the maximum pval attained for this path. */\n{\ndouble max = 0;\nint i = 0;\nfor(i = 0; i < altPath->probeCount; i++)\n    {\n    if(altPath->pVals[i] && altPath->pVals[i][tissueIx] >= max)\n\t{\n\tmax = altPath->pVals[i][tissueIx];\n\t}\n    }\nreturn max;\n}\n\ndouble pvalAltPathCombExpressed(struct altPath *altPath, int tissueIx)\n/* Combine pvals that path expressed using fisher's method and return\n   overall prob that expressed. */\n{\ndouble probProduct = 0;\nint probCount = 0;\nint i = 0;\ndouble combination = 0;\ndouble x = 0;\nfor(i = 0; i < altPath->probeCount; i++)\n    {\n    if(altPath->pVals[i])\n\t{\n\t/* Check for log 0, make it just log very small number. */\n\tif(altPath->pVals[i][tissueIx] == 0)\n\t    x = log(.00000001);\n\telse\n\t    x = log(altPath->pVals[i][tissueIx]);\n\tprobProduct += x;\n\tprobCount++;\n        }\n    }\n/* If no probes return 0. */\nif (probCount == 0)\n    return 0;\ncombination = gsl_cdf_chisq_P(-2.0*probProduct,2.0*probCount);\nreturn combination;\n}\n\nboolean altPathProbesCombExpressed(struct altEvent *event, struct altPath *altPath,\n\t\t\t       int probeIx, int tissueIx)\n/* Return TRUE if the path is expressed, FALSE otherwise. */\n{\ndouble combination = 1;\nassert(altPath);\ncombination = pvalAltPathCombExpressed(altPath, tissueIx);\nif(combination <= altPath->score && event->genePVals && geneExpressed(event, tissueIx))\n    altPath->score = combination;\nif(combination <= 1 - presThresh)\n    return TRUE;\nreturn FALSE;\n}\n\nboolean altPathProbesExpressed(struct altEvent *event, struct altPath *altPath,\n\t\t\t       int probeIx, int tissueIx, double *expression)\n/* Return TRUE if the path is expressed, FALSE otherwise. */\n{\nint i = 0;\nint probeCount = 0;\ndouble **expVals = altPath->expVals;\nboolean expressed = FALSE;\nif (useMaxProbeSet)\n    {\n    for(i = 0; i < altPath->probeCount; i++)\n        {\n\tif(altPath->pVals[i] && altPath->pVals[i][tissueIx] >= presThresh)\n\t    {\n\t    expressed = TRUE;\n\t    *expression = max(*expression, expVals[i][tissueIx]);\n            }\n\t}\n    }\nelse if(useComboProbes)\n    {\n    if(altPathProbesCombExpressed(event, altPath, probeIx, tissueIx))\n\texpressed = TRUE;\n    if(expVals[i] != NULL)\n\t{\n\tfor(i = 0; i < altPath->probeCount; i++)\n\t    {\n\t    *expression += expVals[i][tissueIx];\n\t    probeCount++;\n\t    }\n\t}\n    if(probeCount > 0)\n\t*expression = *expression / probeCount;\n    }\nelse\n    {\n    if(altPath->pVals[probeIx] && altPath->pVals[probeIx][tissueIx] >= presThresh)\n\t{\n\texpressed = TRUE;\n\t*expression = altPath->expVals[probeIx][tissueIx];\n\t}\n    }\nreturn expressed;\n}\n\nboolean tissueExpressed(struct altEvent *event, struct altPath *altPath,\n                        int probeIx, int tissueIx, double *expression)\n/* Return TRUE if the probeIx in tissueIx is above minimum\n   pVal, FALSE otherwise. */\n{\nint geneIx = 0;\nif(!altPathProbesExpressed(event, altPath, probeIx, tissueIx, expression))\n    return FALSE;\nif(event->genePVals && geneExpressed(event, tissueIx))\n    return TRUE;\nreturn FALSE;\n}\n\nboolean altPathProbesNotExpressed(struct altEvent *event, struct altPath *altPath,\n\t\t\t       int probeIx, int tissueIx)\n/* Return TRUE if the path is notExpressed, FALSE otherwise. */\n{\nboolean notExpressed = FALSE;\nint i = 0;\nif (useMaxProbeSet)\n    {\n    for(i = 0; i < altPath->probeCount; i++)\n        {\n\tif(altPath->pVals[i] && altPath->pVals[i][tissueIx] <= absThresh)\n\t    notExpressed = TRUE;\n\t}\n    }\nelse\n    {\n    if(altPath->pVals[probeIx] && altPath->pVals[probeIx][tissueIx] <= absThresh)\n\tnotExpressed = TRUE;\n    }\nreturn notExpressed;\n}\n\nboolean tissueNotExpressed(struct altEvent *event, struct altPath *altPath,\n                           int probeIx, int tissueIx)\n/* Return TRUE if the probeIx in tissueIx is above minimum\n   pVal, FALSE otherwise. */\n{\nint geneIx = 0;\nif(!altPathProbesNotExpressed(event, altPath, probeIx, tissueIx))\n    return FALSE;\nreturn TRUE;\n}\n\ndouble covariance(double *X, double *Y, int count)\n/* Compute the covariance for two vectors.\n   cov(X,Y) = E[XY] - E[X]E[Y]\n   page 326 Sheldon Ross \"A First Course in Probability\" 1998\n*/\n{\ndouble cov = gsl_stats_covariance(X, 1, Y, 1, count);\nreturn cov;\n}\n\ndouble correlation(double *X, double *Y, int count)\n/* Compute the correlation between X and Y\n   correlation(X,Y) = cov(X,Y)/ squareRt(var(X)var(Y))\n   page 332 Sheldon Ross \"A First Course in Probability\" 1998\n*/\n{\ndouble varX = gsl_stats_variance(X, 1, count);\ndouble varY = gsl_stats_variance(Y, 1, count);\ndouble covXY = gsl_stats_covariance(X, 1, Y, 1, count);\n\ndouble correlation = covXY / sqrt(varX *varY);\nreturn correlation;\n}\n\nint determineBestProbe(struct altEvent *event, struct altPath *altPath,\n\t\t       struct dMatrix *intenM, struct dMatrix *probM,\n\t\t       int pathIx)\n/* Find the probe with the best correlation to the gene probe sets. */\n{\ndouble corr = 0, bestCorr = -2;\nint bestIx = -1;\nint bedIx = 0, geneIx = 0;\n\n/* Check the easy case. */\nif(altPath->probeCount == 1)\n    return 0;\n\n/* Loop through and find the probe set with the best\n   correlation to the gene sets. */\nfor(bedIx = 0; bedIx < altPath->probeCount; bedIx++)\n    {\n    if(altPath->expVals[bedIx] == NULL)\n\tcontinue;\n    for(geneIx = 0; geneIx < event->geneProbeCount; geneIx++)\n\t{\n\tif(event->geneExpVals[geneIx] == NULL)\n\t    continue;\n\tcorr = correlation(altPath->expVals[bedIx],\n\t\t\t\t  event->geneExpVals[geneIx], intenM->colCount);\n\tif(corr >= bestCorr)\n\t    {\n\t    bestIx = bedIx;\n\t    bestCorr = corr;\n\t    }\n\t}\n    }\nreturn bestIx;\n}\n\nvoid readSelectedList(char *fileName)\n/* Read in a list of gene identifiers that we want to\n   output. */\n{\nstruct lineFile *lf = NULL;\nstruct hash *hash = newHash(12);\nchar *words[2];\nint wordCount = ArraySize(words);\nassert(fileName);\nlf = lineFileOpen(fileName, TRUE);\nwhile (lineFileChopNext(lf, words, wordCount))\n    {\n    hashAdd(hash, words[0], cloneString(words[1]));\n    }\nlineFileClose(&lf);\noutputPValHash = hash;\n}\n\nchar *isSelectedProbeSet(struct altEvent *event, struct altPath *altPath)\n/* Return gene name if this probe set is select for outputing\n   probability vector else return NULL. */\n{\nchar *mark;\nchar buff[256];\nstruct altPath *path = NULL;\nint i = 0;\nfor(i = 0; i < altPath->probeCount; i++)\n    {\n    if(altPath->beds[i] != NULL)\n\t{\n\tchar *mark = strchr(altPath->beds[i]->name, '@');\n\tif(mark != NULL)\n\t    {\n\t    char *geneName = NULL;\n\t    *mark = '\\0';\n\t    if((geneName = hashFindVal(outputPValHash, altPath->beds[i]->name)) != NULL)\n\t\t{\n\t\t*mark = '@';\n\t\treturn geneName;\n\t\t}\n\t    }\n\t}\n    }\nreturn NULL;\n}\n\nchar * nameForType(int type)\n/* Log the different types of splicing. */\n{\nswitch (type)\n    {\n    case alt5Prime:\n\treturn \"alt5Prime\";\n\tbreak;\n    case alt3Prime:\n\treturn \"alt3Prime\";\n\tbreak;\n    case altCassette:\n\treturn \"altCassette\";\n\tbreak;\n    case altRetInt:\n\treturn \"altRetInt\";\n\tbreak;\n    case altOther:\n\treturn \"altOther\";\n\tbreak;\n    case altControl:\n\treturn \"altControl\";\n\tbreak;\n    case altMutExclusive:\n\treturn \"altMutEx\";\n\tbreak;\n    case alt5PrimeSoft:\n\treturn \"altTxStart\";\n\tbreak;\n    case alt3PrimeSoft:\n\treturn \"altTxEnd\";\n\tbreak;\n    case altIdentity:\n\treturn \"altIdentity\";\n\tbreak;\n    default:\n\terrAbort(\"nameForType() - Don't recognize type %d\", type);\n    }\nreturn \"error\";\n}\n\nvoid outputPathProbabilities(struct altEvent* event, struct altPath *altPath,\n\t\t\t     struct dMatrix *intenM, struct dMatrix *probM,\n\t\t\t     int** expressed, int **notExpressed, double **expression,\n\t\t\t     int pathIx)\n/* Print out a thresholded probablilty vector for clustering and visualization\n   in treeview. */\n{\nint i = 0;\nFILE *out = pathProbabilitiesOut;\nFILE *eOut = pathExpressionOut;\nstruct splice *splice = event->splice;\nstruct path *path = altPath->path;\nchar *geneName = NULL;\nassert(out);\nif((geneName = isSelectedProbeSet(event, altPath)) != NULL)\n    {\n    char *psName = \"Error\";\n    assert(altPath->beds[0] != NULL);\n    psName = altPath->beds[0]->name;\n    fprintf(out, \"%s\\t%s.%s.%s.%d\", psName, geneName, nameForType(splice->type), psName, path->bpCount);\n    fprintf(eOut, \"%s\\t%s.%s.%s.%d\", psName, geneName, nameForType(splice->type), psName, path->bpCount);\n    for(i = 0; i < probM->colCount; i++)\n\t{\n\tfprintf(eOut, \"\\t%f\", expression[pathIx][i]);\n\tif(expressed[pathIx][i])\n\t    fprintf(out, \"\\t2\");\n\telse if(notExpressed[pathIx][i])\n\t    fprintf(out, \"\\t-2\");\n\telse\n\t    fprintf(out, \"\\t0\");\n\t}\n    fprintf(out, \"\\n\");\n    fprintf(eOut, \"\\n\");\n    }\n}\n\nboolean altPathExpressed(struct altEvent *event, struct altPath *altPath,\n\t\t\t struct dMatrix *intenM, struct dMatrix *probM,\n\t\t\t int **expressed, int **notExpressed, double **expression,\n\t\t\t int pathIx)\n/* Fill in the expression matrix for this path. */\n{\nint bestProbeIx = 0;\nint tissueIx = 0;\nint total = 0;\n\n/* Quick check to see if there are any\n      probes at all. */\nif(altPath->probeCount == 0)\n    return FALSE;\n\nbestProbeIx = determineBestProbe(event, altPath, intenM, probM, pathIx);\n/* Loop through the tissues to see if they are expressed. */\nif(bestProbeIx == -1)\n    return FALSE;\n\nfor(tissueIx = 0; tissueIx < probM->colCount; tissueIx++)\n    {\n    double e = -1;\n    if(tissueExpressed(event, altPath, bestProbeIx, tissueIx, &e))\n\t{\n\texpressed[pathIx][tissueIx]++;\n\ttotal++;\n\t}\n    else if(tissueNotExpressed(event, altPath, bestProbeIx, tissueIx))\n\t{\n\tnotExpressed[pathIx][tissueIx]++;\n\t}\n    expression[pathIx][tissueIx] = e;\n    }\nreturn total > 0;\n}\n\ndouble expressionAverage(struct altPath *altPath, int tissueIx)\n/* Return the average expression for all probe sets matched\n   to this path in this tissue. */\n{\ndouble pathExp = 0.0;\nint pCount = 0.0;\nint probeIx = 0;\nfor(probeIx = 0; probeIx < altPath->probeCount; probeIx++)\n    {\n    if(altPath->expVals[probeIx])\n\t{\n\tpathExp += altPath->expVals[probeIx][tissueIx];\n\tpCount++;\n\t}\n    }\nif(pCount == 0)\n    return -1;\npathExp = pathExp / pCount;\nreturn pathExp;\n}\n\nchar *nameForSplice(struct splice *splice, struct altPath *namePath)\n/* Return a unique name for this splicing event. Memory is owned by\n this function and will be overwritten each time this function is\n called. */\n{\nstatic char buff[256];\nsafef(buff, sizeof(buff), \"%s:%s:%s:%s:%s:%s:%d:%d\",\n      splice->name, refSeqForPSet(namePath->beds[0]->name), nameForType(splice->type), namePath->beds[0]->name,\n      splice->strand, splice->tName, splice->tStart, splice->tEnd);\nreturn buff;\n}\n\ndouble calculateFlipScore(struct altEvent *event, struct altPath *altPath,\n                          char *name, struct dMatrix *probM,\n                          boolean *isBrain, boolean doAll, int *incBrain, int *skipBrain)\n\n/* Calculate |(#times skip > include) - (#times skip < include)|/totalTissues */\n{\nstruct altPath *skip = NULL, *include = NULL;\nint tissueIx = 0;\nint brainCount = 0;\nint notBrainCount = 0;\nint tissueCount = 0;\n*incBrain = 0;\n*skipBrain = 0;\nassert(event);\nskip = event->altPathList;\ninclude = event->altPathList->next;\nassert(probM);\nassert(probM->colCount > 0);\n\n/* Use the sortScore hash if it is setup. */\nif(sortScoreHash != NULL)\n    {\n    double result = sortScoreForSplice(nameForSplice(event->splice, altPath));\n    if (result > 0)\n        *incBrain = 1;\n    else if(result < 0)\n        *skipBrain = 1;\n    return result;\n    }\n\n/* Else do some calculations. */\nfor(tissueIx = 0; tissueIx < probM->colCount; tissueIx++)\n    {\n    if(geneExpressed(event, tissueIx) || doAll)\n\t{\n\tdouble skipI = expressionAverage(skip, tissueIx);\n\tdouble incI = expressionAverage(include, tissueIx);\n\tif(incI >= skipI && skipI >= 0 && incI >= 0)\n\t    {\n\t    if(isBrain[tissueIx])\n\t\t{\n\t\tbrainCount++;\n\t\t(*incBrain)++;\n\t\t}\n            else\n\t\tnotBrainCount++;\n\t    tissueCount++;\n\t    }\n\telse if(skipI >= 0 && incI >= 0)\n\t    {\n\t    if(isBrain[tissueIx])\n\t\t{\n\t\tbrainCount--;\n\t\t(*skipBrain)++;\n\t\t}\n            else\n\t\tnotBrainCount--;\n\t    tissueCount++;\n\t    }\n\t}\n    }\n/* If no data, then set score to worst val: 0 */\nif(tissueCount == 0)\n    return 0;\nelse\n    {\n    double brainScore = 0;\n    double nonBrainScore = 0;\n    brainScore = (double) brainCount / tissueCount;\n    nonBrainScore = (double) notBrainCount / tissueCount;\n    return fabs(brainScore - nonBrainScore);\n    }\nreturn 0;\n}\n\n\n\nboolean brainSpecific(struct altEvent *event, struct altPath *path, int pathIx,\n                      int **expressed, int **notExpressed,\n\t\t      int pathCount, struct dMatrix *probM)\n/* Output the event if it is alt-expressed and brain\n   specific. */\n{\nint tissueIx = 0;\nint brainTissues = 0;\nint otherTissues = 0;\nint geneBrainTissues = 0;\nint geneOtherTissues = 0;\nint brainIx = 0;\nint incBrain = 0, skipBrain =0;\nstatic int tissueCount = 0;\nstatic char *brainTissuesToChop = NULL;\nstatic char *brainTissuesStrings[256];\nstatic boolean initDone = FALSE;\n\n/* Setup array of what is brain and what isn't. */\nif (!initDone)\n    {\n    brainTissuesToChop = cloneString(optionVal(\"brainTissues\",\"cerebellum,cerebral_hemisphere,cortex,hind_brain,medial_eminence,olfactory_bulb,pinealgland,thalamus\"));\n    if(ArraySize(isBrainTissue) < probM->colCount)\n        errAbort(\"Can only handle up to %d columns, %d is too many\",\n\t\t ArraySize(isBrainTissue), probM->colCount);\n    /* Set everthing to FALSE. */\n    for(tissueIx = 0; tissueIx < probM->colCount; tissueIx++)\n\tisBrainTissue[tissueIx] = FALSE;\n\n    /* Set brain tissue to TRUE. */\n    tissueCount = chopByChar(brainTissuesToChop, ',', brainTissuesStrings, ArraySize(brainTissuesStrings));\n    for(tissueIx = 0; tissueIx < probM->colCount; tissueIx++)\n\tfor(brainIx = 0; brainIx < tissueCount; brainIx++)\n\t    if(stringIn(brainTissuesStrings[brainIx], probM->colNames[tissueIx]))\n\t\tisBrainTissue[tissueIx] = TRUE;\n\n    initDone = TRUE;\n    }\n\n/* If we have pvals specified by the user use them instead. */\nif(splicePValsHash != NULL)\n    {\n    double d = 0;\n    if (path->probeCount > 0)\n\td = pvalForSplice(nameForSplice(event->splice, path));\n    else\n\treturn FALSE;\n\n    if(d <= pvalThresh)\n\treturn TRUE;\n    else\n\treturn FALSE;\n    }\n\n/* Otherwise use the routines here. */\nfor(tissueIx = 0; tissueIx < probM->colCount; tissueIx++)\n    {\n    if(expressed[pathIx] != NULL &&\n       expressed[pathIx][tissueIx])\n\t{\n\tif(isBrainTissue[tissueIx])\n\t    brainTissues++;\n\telse\n\t    otherTissues++;\n\t}\n    else if(brainSpecificStrict &&\n\t    notExpressed[pathIx] != NULL &&\n\t    !notExpressed[pathIx][tissueIx])\n\t{\n\tif(!isBrainTissue[tissueIx])\n\t    otherTissues++;\n\t}\n    if(geneExpressed(event, tissueIx))\n\t{\n\tif(isBrainTissue[tissueIx])\n\t    geneBrainTissues++;\n\telse\n            geneOtherTissues++;\n        }\n    }\n\nif (otherTissues == 0 && rainTissues >= tissueExpThresh && geneOtherTissues >= tissueExpThresh)\n    return TRUE;\nreturn FALSE;\n}\n\nboolean tissueSpecific(struct altEvent *event, int pathIx, int targetTissue,\n                       int **expressed, int **notExpressed,\n                       int pathCount, struct dMatrix *probM)\n/* Output the event if it is alt-expressed and brain\n   specific. */\n{\nint tissueIx = 0;\nint specificTissues = 0;\nint otherTissues = 0;\nint geneSpecificTissues = 0;\nint geneOtherTissues = 0;\n\nfor(tissueIx = 0; tissueIx < probM->colCount; tissueIx++)\n    {\n    if(expressed[pathIx] != NULL &&\n       expressed[pathIx][tissueIx])\n\t{\n\tif(tissueIx == targetTissue)\n\t    specificTissues++;\n\telse\n\t    otherTissues++;\n\t}\n    else if(tissueSpecificStrict &&\n\t    notExpressed[pathIx] != NULL &&\n\t    !notExpressed[pathIx][tissueIx])\n\t{\n\tif(tissueIx != targetTissue)\n\t    otherTissues++;\n\t}\n    if(geneExpressed(event, tissueIx))\n\t{\n\tif(tissueIx == targetTissue)\n\t    geneSpecificTissues++;\n\telse\n            geneOtherTissues++;\n        }\n    }\nif (otherTissues == 0 && specificTissues >= tissueExpThresh && geneOtherTissues >= tissueExpThresh)\n    return TRUE;\nreturn FALSE;\n}\n\nvoid fillInSequences(struct altEvent *event, struct path *path,\n                     struct dnaSeq **upSeq, struct dnaSeq **downSeq, struct dnaSeq **exonSeq,\n                     struct bed **upSeqBed, struct bed **downSeqBed)\n/* Fill in the sequences from the path. 200 from intron, 5bp from\n exon. */\n{\nint firstSplice = -1;\nint secondSplice = -1;\nint i = 0;\nstruct splice *splice = event->splice;\nint *vPos = splice->vPositions;\nunsigned char*vTypes = splice->vTypes;\nint vC = path->vCount;\nint *verts = path->vertices;\nint exonOffset = 0;\nint intronOffset = 100;\n/* Want first exon in order of transcription. */\nif(sameString(splice->strand,\"+\"))\n    {\n    for(i = 0; i < vC -1; i++)\n\tif(validVertex(splice, verts[i], verts[i+1]) &&\n\t   pathEdgeTypeValid(splice, verts[i], verts[i+1]) == ggExon)\n\t    {\n\t    firstSplice = vPos[verts[i]];\n\t    secondSplice = vPos[verts[i+1]];\n\t    break;\n\t    }\n    }\nelse\n    {\n    for(i = vC-1; i > 0; i--)\n\tif(validVertex(splice, verts[i-1], verts[i]) &&\n\t   pathEdgeTypeValid(splice, verts[i-1], verts[i]) == ggExon)\n\t    {\n\t    firstSplice = vPos[verts[i-1]];\n\t    secondSplice = vPos[verts[i]];\n\t    break;\n\t    }\n    }\n\nif(firstSplice < 0 || secondSplice < 0)\n    errAbort(\"Problem with event %s at %s:%d-%d doesn't have an exon\",\n\t     splice->name, splice->tName, splice->tStart, splice->tEnd);\n\nAllocVar(*upSeqBed);\nAllocVar(*downSeqBed);\n/* Construct the beds. */\n(*upSeqBed)->name = cloneString(splice->name);\n(*upSeqBed)->chrom = cloneString(splice->tName);\nsafef((*upSeqBed)->strand, sizeof((*upSeqBed)->strand), \"%s\", splice->strand);\n(*upSeqBed)->chromStart = firstSplice - intronOffset;\n(*upSeqBed)->chromEnd = firstSplice + exonOffset;\n(*upSeqBed)->score = splice->type;\n\n(*downSeqBed)->name = cloneString(splice->name);\n(*downSeqBed)->chrom = cloneString(splice->tName);\nsafef((*downSeqBed)->strand, sizeof((*downSeqBed)->strand), \"%s\", splice->strand);\n(*downSeqBed)->chromStart = secondSplice - exonOffset;\n(*downSeqBed)->chromEnd = secondSplice + intronOffset;\n(*downSeqBed)->score = splice->type;\n\n/* Get the sequences. */\n*upSeq = hSeqForBed((*upSeqBed));\n*downSeq = hSeqForBed((*downSeqBed));\n*exonSeq = hChromSeq(splice->tName , firstSplice, secondSplice);\nif (sameString(splice->strand, \"-\"))\n    reverseComplement((*exonSeq)->dna, (*exonSeq)->size);\n\n/* If on negative strand swap up and down. */\nif(sameString(splice->strand, \"-\"))\n    {\n    struct dnaSeq *tmpSeq = NULL;\n    struct bed *tmpBed = NULL;\n    /* Swap beds. */\n    tmpBed = *upSeqBed;\n    *upSeqBed = *downSeqBed;\n    *downSeqBed = tmpBed;\n    /* Swap sequences. */\n    tmpSeq = *upSeq;\n    *upSeq = *downSeq;\n    *downSeq = tmpSeq;\n    }\n}\n\nvoid makeJunctMdbGenericLink(struct splice *js, struct dyString *buff, char *name)\n{\nint offSet = 100;\nint i = 0;\ndyStringClear(buff);\ndyStringPrintf(buff,\"<a target=\\\"plots\\\" href=\\\"http://mdb1-sugnet.gi.ucsc.edu/cgi-bin/\"\n                    \"mdbSpliceGraph?mdbsg.calledSelf=on&coordString=%s:%c:%s:%d-%d&mdbsg.cs=%d\"\n                    \"&mdbsg.ce=%d&mdbsg.expName=%s&mdbsg.probeSummary=on&mdbsg.toScale=on\\\">\",\n                    \"mm2\", js->strand[0], js->tName, js->tStart, js->tEnd,\n                    js->tStart - offSet, js->tEnd + offSet, \"AffyMouseSplice1-02-2004\");\ndyStringPrintf(buff, \"%s\", name);\ndyStringPrintf(buff, \"</a> \");\n}\n\nstruct bed *phastConForRegion(char *table, char *chrom, int chromStart, int chromEnd)\n/* Load the beds for the region specified in the table specified. */\n{\nstruct sqlConnection *conn = hAllocConn2();\nstruct sqlResult *sr = NULL;\nstruct bed *conBed = NULL, *conBedList = NULL;\nint rowOffset = 0;\nchar **row = NULL;\nsr = hRangeQuery(conn, table, chrom, chromStart, chromEnd,\n\t\t NULL, &rowOffset);\nwhile((row = sqlNextRow(sr)) != NULL)\n    {\n    conBed = bedLoad5(row+rowOffset);\n    slAddHead(&conBedList, conBed);\n    }\nsqlFreeResult(&sr);\nhFreeConn2(&conn);\nslReverse(&conBedList);\nreturn conBedList;\n}\n\nstruct bed *bed12ForRegion(char *table, char *chrom, int chromStart, int chromEnd, char strand)\n/* Load the beds for the region specified in the table specified. */\n{\nstruct sqlConnection *conn = hAllocConn2();\nstruct sqlResult *sr = NULL;\nstruct bed *bed = NULL, *bedList = NULL;\nint rowOffset = 0;\nchar **row = NULL;\nsr = hRangeQuery(conn, table, chrom, chromStart, chromEnd,\n\t\t NULL, &rowOffset);\nwhile((row = sqlNextRow(sr)) != NULL)\n    {\n    bed = bedLoad12(row+rowOffset);\n    if(bed->strand[0] == strand)\n\tslAddHead(&bedList, bed);\n    else\n\tbedFree(&bed);\n    }\nsqlFreeResult(&sr);\nhFreeConn2(&conn);\nslReverse(&bedList);\nreturn bedList;\n}\n\ndouble gcPercentForRegion(char *chrom, int chromStart, int chromEnd, char *db)\n/* Return gcPercent for region. */\n{\nstruct dnaSeq *seq = NULL;\nint hist[4];\ndouble percent = 0;\nif(newDb != NULL && sameString(db, newDb))\n    seq = hChromSeq2(chrom, chromStart, chromEnd);\nelse\n    seq = hChromSeq(chrom, chromStart, chromEnd);\ndnaBaseHistogram(seq->dna, seq->size, hist);\npercent =  (1.0 *hist[G_BASE_VAL]+hist[C_BASE_VAL])/seq->size;\ndnaSeqFree(&seq);\nreturn percent;\n}\n\nvoid findExonNumForRegion(char *chrom, int chromStart, int chromEnd, char strand,\n                          int *exonNum, int *exonCount)\n/* Find out which exon this region overlaps and fill in the exonNum and exonCount. */\n{\nstruct bed *bed = NULL, *bedList = NULL, *goodBed = NULL;\nint blockIx = 0;\nint *starts = NULL, *sizes = NULL;\nint cs = 0, ce = 0;\n*exonNum = -1;\n*exonCount = -1;\nbedList = bed12ForRegion(\"agxBed\", chrom, chromStart, chromEnd, strand);\nfor(bed = bedList; bed != NULL; bed = bed->next)\n    {\n    if(bed->strand[0] != strand)\n\tcontinue;\n    cs = bed->chromStart;\n    ce = bed->chromEnd;\n    starts = bed->chromStarts;\n    sizes = bed->blockSizes;\n    for(blockIx = 0; blockIx < bed->blockCount; blockIx++)\n\t{\n\tint bStart = cs+starts[blockIx];\n\tint bEnd = cs+starts[blockIx]+sizes[blockIx];\n\tif(rangeIntersection(chromStart, chromEnd, bStart, bEnd ) > 0)\n\t    {\n\t    if(goodBed == NULL)\n\t\t{\n                goodBed = bed;\n                *exonNum = blockIx;\n                *exonCount = bed->blockCount;\n                }\n            break;\n            }\n        }\n    }\nif(strand == '-' && *exonNum != -1)\n    {\n    *exonNum = *exonCount - *exonNum;\n    }\nbedFreeList(&bedList);\n}\n\ndouble percentIntronBasesOverlappingConsSide(char *table, char *chrom, int chromStart, int chromEnd, boolean upStream)\n/* Percentage of intron bases that overlap a phastCons element. */\n{\nint intronOffset = 100, overlap = 0;\ndouble percent = 0;\nif(newDb != NULL && hTableExists2(table))\n    {\n    struct bed *upstream = NULL;\n    struct bed *bed = NULL;\n    if(upStream == TRUE)\n\tupstream = phastConForRegion(table, chrom, chromStart-intronOffset, chromStart);\n    else\n\tupstream = phastConForRegion(table, chrom, chromEnd, chromEnd + intronOffset);\n\n    for(bed = upstream; bed != NULL; bed = bed->next)\n\t{\n\tif(upStream == TRUE)\n\t    {\n\t    overlap += positiveRangeIntersection(chromStart-intronOffset, chromStart,\n\t\t\t\t\t\t bed->chromStart, bed->chromEnd);\n\t    }\n        else\n\t    {\n\t    overlap += positiveRangeIntersection(chromEnd, chromEnd+intronOffset,\n\t\t\t\t\t\t bed->chromStart, bed->chromEnd);\n\t    }\n\t}\n    percent = (double)overlap / (intronOffset);\n    bedFreeList(&upstream);\n    }\nreturn percent;\n}\n\ndouble percentIntronBasesOverlappingCons(char *table, char *chrom, int chromStart, int chromEnd)\n/* Percentage of intron bases that overlap a phastCons element. */\n{\nint intronOffset = 100, overlap = 0;\ndouble percent = 0;\nif(newDb != NULL && hTableExists2(table))\n    {\n    struct bed *upstream = phastConForRegion(table, chrom, chromStart-intronOffset, chromStart);\n    struct bed *downstream = phastConForRegion(table, chrom, chromEnd, chromEnd + intronOffset);\n    struct bed *bed = NULL;\n    for(bed = upstream; bed != NULL; bed = bed->next)\n\t{\n\toverlap += positiveRangeIntersection(chromStart-intronOffset, chromStart,\n\t\t\t\t\t     bed->chromStart, bed->chromEnd);\n\t}\n    for(bed = downstream; bed != NULL; bed = bed->next)\n\t{\n\toverlap += positiveRangeIntersection(chromEnd, chromEnd+intronOffset,\n\t\t\t\t\t     bed->chromStart, bed->chromEnd);\n\t}\n    percent = (double)overlap / (2 * intronOffset);\n    bedFreeList(&upstream);\n    bedFreeList(&downstream);\n    }\nreturn percent;\n}\n\nvoid printLinks(struct altEvent *event)\n/* Loop through and print each splicing event to web page. */\n{\nstruct splice *s = NULL;\nstruct path *lastPath = NULL;\nstruct splice *splice = event->splice;\nstruct altPath *altPath = NULL, *namePath = NULL;\nchar *brainDiffDir = optionVal(\"plotDir\",\"brainDiffPlots.9\");\nchar *fileSuffix = optionVal(\"fileSuffix\", \"png\");\nchar *chrom = NULL;\nchar strand;\nint chromStart = 0,  chromEnd = 0;\nint diff = -1;\nchar *useDb = db;\nchar *newDb = optionVal(\"newDb\", NULL);\nboolean overlapsPhasCons = FALSE;\ndouble overlapPercent = 0;\nstruct dyString *buff = NULL;\nchar *skipPSet = NULL;\nint i = 0;\nboolean muscleOn = optionExists(\"muscleOn\");\n/* struct altPath *incPath = NULL, *skipPath = NULL; */\nif(splice->paths == NULL || splice->type == altControl)\n    return;\n\nfor (altPath = event->altPathList; altPath != NULL; altPath = altPath->next)\n    {\n    struct bed *bed = NULL;\n    double score = event->flipScore;\n    char upPos[256];\n    char downPos[256];\n\n    /* If we're dealing with a cassette or other limit to 2 paths\n       use skip/include path model. */\n    if (onlyTwoPaths(event))\n        {\n        namePath = event->altPathList;\n        altPath = event->altPathList->next;\n\tdiff = abs(splice->paths->bpCount - splice->paths->next->bpCount);\n\t}\n    else\n\t{\n\tdiff = altPath->path->bpCount;\n\tnamePath = altPath;\n\t}\n\n    /* Check to make sure that we have probes and that this\n       path is brain specific. */\n    if (namePath->probeCount < 1 || event->geneProbeCount < 1)\n        continue;\n    if(splicePValsHash != NULL)\n        {\n\tdouble d = 0;\n\td = pvalForSplice(nameForSplice(event->splice,namePath));\n\tif(d > pvalThresh)\n\t    continue;\n\tevent->pVal = d;\n\t}\n    if(sortScoreHash != NULL)\n\tscore = sortScoreForSplice(nameForSplice(event->splice, namePath));\n    bed = pathToBed(altPath->path, event->splice, -1, -1, FALSE);\n    chrom = cloneString(bed->chrom);\n    chromStart = bed->chromStart;\n    chromEnd = bed->chromEnd;\n    strand = bed->strand[0];\n\n    if(newDb != NULL)\n\t{\n\tif(liftOverCoords(&chrom, &chromStart, &chromEnd, &strand))\n\t    useDb = newDb;\n\t}\n/* overlapPercent = percentIntronBasesOverlappingCons(chrom, chromStart,chromEnd); */\n    buff = newDyString(256);\n\n/*     if(brainSpPSetOut != NULL)  */\n/*      { */\n/*      skipPath = namePath; */\n/*      skipPSet = skipPath->beds[0]->name; */\n/*      if(onlyTwoPaths(event)) */\n/*          incPath = event->altPathList->next; */\n/*      else */\n/*          incPath = NULL; */\n/*      fprintf(brainSpPSetOut, \"%s\\t\", refSeqForPSet(skipPSet)); */\n/*      fprintf(brainSpPSetOut, \"%s\\t\", skipPSet); */\n/*      if(incPath != NULL) */\n/*          { */\n/*          fprintf(brainSpPSetOut, \"%d\\t\", incPath->probeCount); */\n/*          for(i = 0; i < incPath->probeCount; i++)  */\n/*              { */\n/*              fprintf(brainSpPSetOut, \"%s,\", incPath->beds[i]->name); */\n/*              } */\n/*          } */\n/*      else */\n/*          { */\n/*          fprintf(brainSpPSetOut, \"%d\\t\", event->geneProbeCount); */\n/*          for(i = 0; i < event->geneProbeCount; i++)  */\n/*              { */\n/*              fprintf(brainSpPSetOut, \"%s,\", event->geneBeds[i]->name); */\n/*              } */\n/*          } */\n/*      fprintf(brainSpPSetOut, \"\\t%d\\t\", event->geneProbeCount); */\n/*      for(i = 0; i < event->geneProbeCount; i++)  */\n/*          { */\n/*          fprintf(brainSpPSetOut, \"%s,\", event->geneBeds[i]->name); */\n/*          } */\n/*      fprintf(brainSpPSetOut, \"\\n\"); */\n/*      } */\n\n    fprintf(brainSpTableHtmlOut, \"<tr><td>\");\n    if(overlapsPhasCons)\n        fprintf(brainSpTableHtmlOut, \"<span style='color:red;'> * </span>\");\n    fprintf(brainSpTableHtmlOut, \"<a target=\\\"browser\\\" \"\n\t    \"href=\\\"http://%s/cgi-bin/hgTracks?db=%s&position=%s:%d-%d&hgt.motifs=TCATT%%2CTCATC%%2CGGGGG%%2CCTCTCT%%2CGCATG%%2CTCCTT\\\",>\", browserName,\n\t    useDb, chrom, chromStart-100, chromEnd+100);\n    fprintf(brainSpTableHtmlOut,\"%s </a><font size=-1>%s</font>\\n\",\n\t    refSeqForPSet(event->geneBeds[0]->name), useDb);\n    safef(upPos, sizeof(upPos), \"%s:%d-%d\", chrom, chromStart-95, chromStart+5);\n    safef(downPos, sizeof(downPos), \"%s:%d-%d\", chrom, chromEnd-5, chromEnd+95);\n    fprintf(brainSpTableHtmlOut, \"<a target=\\\"browser\\\" \"\n            \"href=\\\"http://%s/cgi-bin/hgTracks?db=%s&position=%s&complement=%d&hgt.motifs=TCATT%%2CTCATC%%2CGGGGG%%2CCTCTCT%%2CGCATG%%2CTCCTT\\\">[u]</a>\",\n\t    browserName, useDb, strand == '+' ? upPos : downPos,\n\t    strand == '-' ? 1 : 0);\n    fprintf(brainSpTableHtmlOut, \"<a target=\\\"browser\\\" \"\n            \"href=\\\"http://%s/cgi-bin/hgTracks?db=%s&position=%s&complement=%d&hgt.motifs=TCATT%%2CTCATC%%2CGGGGG%%2CCTCTCT%%2CGCATG%%2CTCCTT\\\">[d]</a>\",\n\t    browserName, useDb, strand == '+' ? downPos : upPos,\n\t    strand == '-' ? 1 : 0);\n    fprintf(brainSpTableHtmlOut,\n            \"<a target=\\\"plots\\\" href=\\\"http://%s/cgi-bin/spliceProbeVis?skipPName=%s%s\\\">[p]</a>\",\n            browserName, namePath->beds[0]->name, muscleOn ? \"&muscle=on\" : \"\");\n    fprintf(brainSpTableHtmlOut,\n            \"<a target=\\\"plots\\\" href=\\\"http://%s/cgi-bin/spliceProbeVis?skipPName=%s&pdf=on%s\\\">[pdf]</a>\",\n            browserName, namePath->beds[0]->name, muscleOn ? \"&muscle=on\" : \"\");\n    fprintf(brainSpTableHtmlOut,\n            \"<a target=\\\"plots\\\" href=\\\"./%s/%s:%s:%s:%s:%s:%s:%d:%d.%s\\\">[f]</a>\",\n            brainDiffDir,\n            splice->name, refSeqForPSet(namePath->beds[0]->name),\n            nameForType(splice->type), namePath->beds[0]->name,\n\t    splice->strand, splice->tName, splice->tStart, splice->tEnd, fileSuffix);\n/* makeJunctMdbGenericLink(splice, buff, \"[p]\"); */\n/* fprintf(brainSpTableHtmlOut, \"%s\", buff->string); */\n    fprintf(brainSpTableHtmlOut, \"<font size=-1>(%5.2f, %s, %d, %d)</font>\", event->percentUltra, nameForType(splice->type), diff, diff % 3);\n    fprintf(brainSpTableHtmlOut, \"<font size=-2>\");\n    if (altPath->motifUpCounts != NULL)\n        {\n        fprintf(brainSpTableHtmlOut, \"[\");\n        for (i = 0; i < bindSiteCount; i++)\n            fprintf(brainSpTableHtmlOut, \" %d\", altPath->motifUpCounts[i]);\n        fprintf(brainSpTableHtmlOut, \"] \");\n\n        fprintf(brainSpTableHtmlOut, \"[\");\n        for (i = 0; i < bindSiteCount; i++)\n            fprintf(brainSpTableHtmlOut, \" %d\", altPath->motifInsideCounts[i]);\n        fprintf(brainSpTableHtmlOut, \"] \");\n\n        fprintf(brainSpTableHtmlOut, \"[\");\n        for (i = 0; i < bindSiteCount; i++)\n            fprintf(brainSpTableHtmlOut, \" %d\", altPath->motifDownCounts[i]);\n        fprintf(brainSpTableHtmlOut, \"] \");\n        }\n    fprintf(brainSpTableHtmlOut, \"</font>\\n\");\n    fprintf(brainSpTableHtmlOut, \" </td>\");\n    fprintf(brainSpTableHtmlOut,\"<td>%.4f</td></tr>\\n\", score);\n    dyStringFree(&buff);\n    }\n}\n\ndouble consForIntCoords(char *chrom, int intStart, int intEnd, boolean doLift)\n/* Return the conservation for the intron specified by intStart, intEnd. */\n{\nchar strand = '+';\nchar *startChrom = cloneString(chrom);\nchar *endChrom = cloneString(chrom);\ndouble cons = 0;\nint overlap = 0;\nint chromStart = intStart - 10, chromEnd = intEnd + 10;\nstruct bed *bedList = NULL, *bed = NULL;\nif(doLift && newDb != NULL)\n    {\n    /* Lift over each end seperately so as to ignore changes\n       in assembly in the middle. */\n    liftOverCoords(&startChrom, &chromStart, &intStart, &strand);\n    liftOverCoords(&endChrom, &intEnd, &chromEnd, &strand);\n    }\nif(intStart < intEnd && newDb != NULL)\n    {\n    bedList = phastConForRegion(\"phastConsOrig90\", startChrom, intStart, intEnd);\n    for(bed = bedList; bed != NULL; bed = bed->next)\n\t{\n\toverlap += positiveRangeIntersection(intStart, intEnd,\n\t\t\t\t\t     bed->chromStart, bed->chromEnd);\n\t}\n    cons = (double)overlap / (intEnd - intStart);\n    bedFreeList(&bedList);\n    }\nelse\n    cons = 0;\nreturn cons;\n}\n\nvoid fillInStatsForEvent(struct valuesMat *vm, char *name, char *chrom, int intStart,\n                         int exonStart, int exonEnd, int intEnd, char strand,\n                         enum altSpliceType type)\n/* Fill in stats for the exon specified by intStart->exonStart->exonEnd->intEnd. */\n{\nchar *skipPSet = NULL;\nchar buff[256];\ndouble percentPhastCons = 0;\ndouble upIntCons = 0;\ndouble downIntCons = 0;\ndouble ultraCons = 0;\nint exonCount = -1, exonNum = -1;\ndouble cons = 0;\n\n/* Add event to our list for later sorting, etc. */\nultraCons = cons = percentIntronBasesOverlappingConsSide(\"phastConsOrig90\", chrom, exonStart,exonEnd, TRUE);\n\n/* Percent ultra. */\nsafef(buff, sizeof(buff), \"%.4f\", cons);\nvmAddVal(vm, name, \"intronUltraConsUpStream\", buff);\n\ncons = percentIntronBasesOverlappingConsSide(\"phastConsOrig90\", chrom, exonStart,exonEnd, FALSE);\nultraCons += cons;\n\n/* Percent ultra. */\nsafef(buff, sizeof(buff), \"%.4f\", cons);\nvmAddVal(vm, name, \"intronUltraConsDownStream\", buff);\n\nultraCons = ultraCons / 2;\n\n/* Percent ultra. */\nsafef(buff, sizeof(buff), \"%.4f\", ultraCons);\nvmAddVal(vm, name, \"intronUltraCons\", buff);\n\n/* Percent conserved. */\npercentPhastCons = percentIntronBasesOverlappingCons(\"phastConsElements\", chrom, exonStart, exonEnd);\nsafef(buff, sizeof(buff), \"%.4f\", percentPhastCons);\nvmAddVal(vm, name, \"intronCons\", buff);\n\n/* Name of splicing event. */\nvmAddVal(vm, name, \"type\", nameForType(type));\n\n/* Size in bp of splicing event. */\nsafef(buff, sizeof(buff), \"%d\", exonEnd - exonStart);\nvmAddVal(vm, name, \"bpDiff\", buff);\n\n/* Intron size. */\nsafef(buff, sizeof(buff), \"%d\", intEnd - intStart);\nvmAddVal(vm, name, \"intronSize\", buff);\n\n/* Genome Position. */\nsafef(buff, sizeof(buff), \"%s:%d-%d\", chrom, intStart, intEnd);\nvmAddVal(vm, name, \"mm2.genomePos\", buff);\n\n/* Genome Position. */\nsafef(buff, sizeof(buff), \"%s:%d-%d\", chrom, exonStart, exonEnd);\nvmAddVal(vm, name, \"mm5.exonPos\", buff);\n\n/* Strand. */\nsafef(buff, sizeof(buff), \"%c\", strand);\nvmAddVal(vm, name, \"strand\", buff);\n\n/* GC Percent. */\nsafef(buff, sizeof(buff), \"%.4f\", gcPercentForRegion(chrom, exonStart, exonEnd, newDb));\nvmAddVal(vm, name, \"gcPercent\", buff);\n\n/* Upstream intron conservation. */\nupIntCons = consForIntCoords(chrom, intStart, exonStart, FALSE );\ndownIntCons = consForIntCoords(chrom, exonEnd, intEnd, FALSE);\nif(strand == '-')\n    {\n    double dTmp = upIntCons;\n    upIntCons = downIntCons;\n    downIntCons = dTmp;\n    }\nsafef(buff, sizeof(buff), \"%g\", upIntCons);\nvmAddVal(vm, name, \"upFullIntronCons\", buff);\n\nsafef(buff, sizeof(buff), \"%g\", downIntCons);\nvmAddVal(vm, name, \"downFullIntronCons\", buff);\n\n/* Add some values about expresion. */\nfindExonNumForRegion(chrom, exonStart, exonEnd, strand, &exonNum, &exonCount);\n\nsafef(buff, sizeof(buff), \"%d\", exonNum);\nvmAddVal(vm, name, \"exonNum\", buff);\n\nsafef(buff, sizeof(buff), \"%d\", exonCount);\nvmAddVal(vm, name, \"exonCount\", buff);\n}\n\nvoid writeOutOverlappingUltra(FILE *out, FILE *bedOut, char *chrom,\n                              int chromStart, int chromEnd, char strand)\n/* Write out the sequences for phastCons elements that overlap the region. */\n{\nstruct bed *bedList = NULL, *bed = NULL;\nstruct dnaSeq *seq = NULL;\nchar buff[256];\nbedList = phastConForRegion(\"phastConsOrig90\", chrom, chromStart, chromEnd);\nfor(bed = bedList; bed != NULL; bed = bed->next)\n    {\n    seq = hChromSeq2(bed->chrom, bed->chromStart, bed->chromEnd);\n    if(strand == '-')\n\treverseComplement(seq->dna, seq->size);\n    safef(buff, sizeof(buff), \"%s.%s:%d-%d\", bed->name, chrom, chromStart, chromEnd);\n    safef(bed->strand, sizeof(bed->strand), \"%c\", strand);\n    faWriteNext(out, buff, seq->dna, seq->size);\n    dnaSeqFree(&seq);\n    bedTabOutN(bed, 6, bedOut);\n    }\nbedFreeList(&bedList);\n}\n\n\nvoid outputBrainSpecificEvents(struct altEvent *event, int **expressed, int **notExpressed,\n\t\t\t       int pathCount, struct dMatrix *probM)\n/* Output the event if it is alt-expressed and brain\n   specific. */\n{\nstruct dnaSeq *upSeq = NULL;\nstruct dnaSeq *downSeq = NULL;\nstruct dnaSeq *exonSeq = NULL;\nstruct bed *pathBed = NULL;\nstruct bed *upSeqBed = NULL;\nstruct bed *downSeqBed = NULL;\n\nstruct slRef *brainEvent = NULL;\nboolean lifted = FALSE;\nint i = 0;\nint pathIx = 0;\nstruct altPath *altPath = NULL;\nboolean brainSpecificEvent = FALSE;\nstruct splice *splice = event->splice;\nboolean eventAdded = FALSE;\nfor(altPath = event->altPathList; altPath != NULL; altPath = altPath->next, pathIx++)\n    {\n    char *chrom = NULL;\n    int chromStart = 0;\n    int chromEnd = 0;\n    int intronEnd = 0;\n    int intronStart = 0;\n    int intronDummy = 0;\n    char strand;\n    char *skipPSet = NULL;\n    struct altPath *skipPath = NULL;\n    struct altPath *incPath = NULL;\n    struct altPath *namePath = NULL;\n    char buff[256];\n    double percentPhastCons = 0;\n    double upIntCons = 0;\n    double downIntCons = 0;\n    double cons = 0, ultraCons = 0;\n    double flipScore = 0;\n    double maxProb = 0;\n    int incBrain = 0, skipBrain =0;\n    int exonCount = -1, exonNum = -1;\n    if(onlyTwoPaths(event) && altPath == event->altPathList->next)\n\tnamePath = event->altPathList;\n    else\n\tnamePath = altPath;\n    if(!brainSpecific(event, namePath, pathIx, expressed, notExpressed, pathCount, probM) ||\n       splice->type == altOther)\n\t{\n\tcontinue;\n\t}\n\n    /* check to make sure this path includes some sequence. */\n    pathBed = pathToBed(altPath->path, event->splice, -1, -1, FALSE);\n    if(pathBed == NULL && splice->type != alt5PrimeSoft && splice->type != alt3PrimeSoft)\n        continue;\n\n    if (!eventAdded)\n        {\n        /* Add event to our list for later sorting, etc. */\n        AllocVar(brainEvent);\n\tbrainEvent->val = event;\n\tslAddHead(&brainSpEvents, brainEvent);\n\teventAdded = TRUE;\n\t}\n\n\n    if(sortScoreHash != NULL && namePath->probeCount > 0)\n\tevent->flipScore = sortScoreForSplice(nameForSplice(event->splice, namePath));\n\n    /* Rest of the logging functions are only for cassettes with probes. */\n    if(splice->type != altCassette || event->altPathProbeCount < 2)\n\t{\n\tcontinue;\n\t}\n\n\n\n    /* Print out the cassette connected to the proximal exons. */\n    if(brainSpPathEndsBedOut)\n\t{\n\tstruct bed *longBed = pathToBed(altPath->path, event->splice, -1, -1, TRUE);\n\tassert(longBed);\n\tbedTabOutN(longBed, 12, brainSpPathEndsBedOut);\n\tbedFree(&longBed);\n\t}\n\n    /* Lets do some stat recording. */\n    skipPath = event->altPathList;\n    skipPSet = skipPath->beds[0]->name;\n    incPath = event->altPathList->next;\n\n/*     if(brainSpPSetOut != NULL)  */\n/*      { */\n/*      fprintf(brainSpPSetOut, \"%s\\t\", refSeqForPSet(skipPSet)); */\n/*      fprintf(brainSpPSetOut, \"%s\\t\", skipPSet); */\n/*      fprintf(brainSpPSetOut, \"%d\\t\", incPath->probeCount); */\n/*      for(i = 0; i < incPath->probeCount; i++)  */\n/*          { */\n/*          fprintf(brainSpPSetOut, \"%s,\", incPath->beds[i]->name); */\n/*          } */\n/*      fprintf(brainSpPSetOut, \"\\t%d\\t\", event->geneProbeCount); */\n/*      for(i = 0; i < event->geneProbeCount; i++)  */\n/*          { */\n/*          fprintf(brainSpPSetOut, \"%s,\", event->geneBeds[i]->name); */\n/*          } */\n/*      fprintf(brainSpPSetOut, \"\\n\"); */\n/*      } */\n\n    chrom = cloneString(pathBed->chrom);\n    chromStart = pathBed->chromStart;\n    chromEnd = pathBed->chromEnd;\n    intronStart = splice->tStart;\n    intronEnd = splice->tEnd;\n    strand = pathBed->strand[0];\n\n    if(newDb != NULL)\n\t{\n\tlifted = liftOverCoords(&chrom, &chromStart, &chromEnd, &strand);\n\t}\n    /* Add event to our list for later sorting, etc. */\n    ultraCons = cons = percentIntronBasesOverlappingConsSide(\"phastConsOrig90\", chrom, chromStart,chromEnd, TRUE);\n\n    /* Percent ultra. */\n    safef(buff, sizeof(buff), \"%.4f\", cons);\n    vmAddVal(brainSpecificValues, skipPSet, \"intronUltraConsUpStream\", buff);\n\n    cons = percentIntronBasesOverlappingConsSide(\"phastConsOrig90\", chrom, chromStart,chromEnd, FALSE);\n    ultraCons += cons;\n\n    /* Percent ultra. */\n    safef(buff, sizeof(buff), \"%.4f\", cons);\n    vmAddVal(brainSpecificValues, skipPSet, \"intronUltraConsDownStream\", buff);\n\n    ultraCons = ultraCons / 2;\n    event->percentUltra = ultraCons;\n/*     event->percentUltra = percentIntronBasesOverlappingCons(\"phastConsOrig90\", chrom, chromStart,chromEnd); */\n    if(event->percentUltra >= .20)\n\tintronsConserved++;\n    intronsConsCounted++;\n\n\n    /* Percent ultra. */\n    safef(buff, sizeof(buff), \"%.4f\", event->percentUltra);\n    vmAddVal(brainSpecificValues, skipPSet, \"intronUltraCons\", buff);\n\n    /* If we have phastCons data we want it to end up being printed. */\n    if (phastConsHash != NULL)\n        event->percentUltra = phastConsForSplice(skipPSet);\n\n    /* Percent conserved. */\n    percentPhastCons = percentIntronBasesOverlappingCons(\"phastConsElements\", chrom, chromStart,chromEnd);\n    safef(buff, sizeof(buff), \"%.4f\", percentPhastCons);\n    vmAddVal(brainSpecificValues, skipPSet, \"intronCons\", buff);\n\n    /* Name of splicing event. */\n    vmAddVal(brainSpecificValues, skipPSet, \"type\", nameForType(splice->type));\n\n    /* Size in bp of splicing event. */\n    safef(buff, sizeof(buff), \"%d\", incPath->path->bpCount - skipPath->path->bpCount);\n    vmAddVal(brainSpecificValues, skipPSet, \"bpDiff\", buff);\n\n    /* Modulous 3. */\n    safef(buff, sizeof(buff), \"%d\", (incPath->path->bpCount - skipPath->path->bpCount) % 3);\n    vmAddVal(brainSpecificValues, skipPSet, \"mod3\", buff);\n\n    /* Intron size. */\n    safef(buff, sizeof(buff), \"%d\", splice->tEnd - splice->tStart);\n    vmAddVal(brainSpecificValues, skipPSet, \"intronSize\", buff);\n\n    /* Gene Name. */\n    if(psToRefGeneHash != NULL)\n\tvmAddVal(brainSpecificValues, skipPSet, \"geneName\", refSeqForPSet(skipPSet));\n\n    /* Known Gene. */\n    if(psToKnownGeneHash != NULL)\n\tvmAddVal(brainSpecificValues, skipPSet, \"knownGene\", knownGeneForPSet(skipPSet));\n\n\n    /* Chrom. */\n    safef(buff, sizeof(buff), \"%s\", splice->tName);\n    vmAddVal(brainSpecificValues, skipPSet, \"mm2.chrom\", buff);\n\n    /* ChromStart */\n    safef(buff, sizeof(buff), \"%d\",pathBed->chromStart);\n    vmAddVal(brainSpecificValues, skipPSet, \"mm2.exonChromStart\", buff);\n\n    /* ChromEnd */\n    safef(buff, sizeof(buff), \"%d\",pathBed->chromEnd);\n    vmAddVal(brainSpecificValues, skipPSet, \"mm2.exonChromEnd\", buff);\n\n    /* Strand. */\n    vmAddVal(brainSpecificValues, skipPSet, \"strand\", splice->strand);\n\n\n    /* Genome Position. */\n    safef(buff, sizeof(buff), \"%s:%d-%d\", splice->tName, splice->tStart, splice->tEnd);\n   vmAddVal(brainSpecificValues, skipPSet, \"mm2.genomePos\", buff);\n\n\n    /* Genome Position. */\n    safef(buff, sizeof(buff), \"%s:%d-%d\", chrom, chromStart, chromEnd);\n    vmAddVal(brainSpecificValues, skipPSet, \"mm5.exonPos\", buff);\n\n    /* Pvalue. */\n    if(splicePValsHash != NULL)\n\t{\n\tsafef(buff, sizeof(buff), \"%g\", pvalForSplice(nameForSplice(event->splice, skipPath)));\n\tvmAddVal(brainSpecificValues, skipPSet, \"bsPVal\", buff);\n        event->pVal = atof(buff);\n\t}\n\n    /* GC Percent. */\n    safef(buff, sizeof(buff), \"%.4f\", gcPercentForRegion(pathBed->chrom, pathBed->chromStart, pathBed->chromEnd, db));\n    vmAddVal(brainSpecificValues, skipPSet, \"gcPercent\", buff);\n\n    /* Upstream intron conservation. */\n    upIntCons = consForIntCoords(splice->tName, splice->tStart, pathBed->chromStart, TRUE);\n    downIntCons = consForIntCoords(splice->tName, pathBed->chromEnd, splice->tEnd, TRUE);\n    if(pathBed->strand[0] == '-')\n\t{\n\tdouble dTmp = upIntCons;\n\tupIntCons = downIntCons;\n\tdownIntCons = dTmp;\n\t}\n    safef(buff, sizeof(buff), \"%g\", upIntCons);\n    vmAddVal(brainSpecificValues, skipPSet, \"upFullIntronCons\", buff);\n\n    safef(buff, sizeof(buff), \"%g\", downIntCons);\n    vmAddVal(brainSpecificValues, skipPSet, \"downFullIntronCons\", buff);\n\n    /* Calculate a flip score using all tissues even if they\n       aren't expressed. */\n    event->flipScore = flipScore = calculateFlipScore(event, skipPath, skipPSet, probM, isBrainTissue, TRUE, &incBrain, &skipBrain);\n    safef(buff, sizeof(buff), \"%.4f\", flipScore);\n    vmAddVal(brainSpecificValues, skipPSet, \"flipScoreAllTissues\", buff);\n\n    /* flip. */\n    safef(buff, sizeof(buff), \"%.4f\", event->flipScore);\n    vmAddVal(brainSpecificValues, skipPSet, \"flipScore\", buff);\n\n    /* Calculate times brain includes and brain excludes. */\n    flipScore = calculateFlipScore(event, skipPath, skipPSet, probM, isBrainTissue, FALSE, &incBrain, &skipBrain);\n    safef(buff, sizeof(buff), \"%d\", incBrain);\n    vmAddVal(brainSpecificValues, skipPSet, \"incBrain\", buff);\n    safef(buff, sizeof(buff), \"%d\", skipBrain);\n    vmAddVal(brainSpecificValues, skipPSet, \"skipBrain\", buff);\n\n/* Conserved in human transcriptome? */\n    safef(buff, sizeof(buff), \"%s:%d-%d:%c\", chrom,\n\t  chromStart, chromEnd, strand);\n\n    if(!lifted || conservedHash == NULL)\n\tvmAddVal(brainSpecificValues, skipPSet, \"humanAltToo\", \"UNKNOWN\");\n    else if(hashFindVal(conservedHash, buff) != NULL)\n\tvmAddVal(brainSpecificValues, skipPSet, \"humanAltToo\", \"TRUE\");\n    else\n\tvmAddVal(brainSpecificValues, skipPSet, \"humanAltToo\", \"FALSE\");\n\n\n    /* Add some values about expresion. */\n    if(lifted)\n\tfindExonNumForRegion(chrom, chromStart, chromEnd, strand, &exonNum, &exonCount);\n\n    safef(buff, sizeof(buff), \"%d\", exonNum);\n    vmAddVal(brainSpecificValues, skipPSet, \"exonNum\", buff);\n\n    safef(buff, sizeof(buff), \"%d\", exonCount);\n    vmAddVal(brainSpecificValues, skipPSet, \"exonCount\", buff);\n\n    if(event->altPathProbeCount >= 2)\n\tvmAddVal(brainSpecificValues, skipPSet, \"wProbes\", \"TRUE\");\n    else\n\tvmAddVal(brainSpecificValues, skipPSet, \"wProbes\", \"FALSE\");\n\n    if(event->isExpressed)\n\tvmAddVal(brainSpecificValues, skipPSet, \"expressed\", \"TRUE\");\n    else\n\tvmAddVal(brainSpecificValues, skipPSet, \"expressed\", \"FALSE\");\n\n    if(event->isAltExpressed)\n\tvmAddVal(brainSpecificValues, skipPSet, \"altExpressed\", \"TRUE\");\n    else\n\tvmAddVal(brainSpecificValues, skipPSet, \"altExpressed\", \"FALSE\");\n\n    maxProb = max(skipPath->score, incPath->score);\n    safef(buff, sizeof(buff), \"%.10f\", maxProb);\n    vmAddVal(brainSpecificValues, skipPSet, \"pExpressed\", buff);\n\n    /* Splice event name. */\n    safef(buff, sizeof(buff), \"%s\", event->splice->name);\n    vmAddVal(brainSpecificValues, skipPSet, \"spliceName\", buff);\n\n    /* Count up some motifs. */\n    if(splice->type == altCassette && altPath->path->bpCount > 0)\n\t{\n\tif(event->flipScore >= 0)\n\t    cassetteSkipInsideBpCount += incPath->path->bpCount - skipPath->path->bpCount;\n\telse\n\t    brainSpecificMotifInsideBpCount += incPath->path->bpCount - skipPath->path->bpCount;\n\n\tfor(i = 0; i < bindSiteCount; i++)\n\t    {\n\t    int total = altPath->motifUpCounts[i] + altPath->motifDownCounts[i] + altPath->motifInsideCounts[i];\n\t    char colName[256];\n\t    /* Add the total up. */\n\t    safef(buff, sizeof(buff), \"%d\", total);\n\t    vmAddVal(brainSpecificValues, skipPSet, bindSiteArray[i]->rnaBinder, buff);\n\n\t    /* Add the upstream counts */\n\t    safef(colName, sizeof(colName), \"%s-up\", bindSiteArray[i]->rnaBinder);\n\t    safef(buff, sizeof(buff), \"%d\", altPath->motifUpCounts[i]);\n\t    vmAddVal(brainSpecificValues, skipPSet, colName, buff);\n\n\t    /* Add the downstream counts. */\n\t    safef(colName, sizeof(colName), \"%s-down\", bindSiteArray[i]->rnaBinder);\n\t    safef(buff, sizeof(colName), \"%d\", altPath->motifDownCounts[i]);\n\t    vmAddVal(brainSpecificValues, skipPSet, colName, buff);\n\n\t    if(event->flipScore >=0)\n\t\t{\n\t\tcassetteSkipUpMotifs[i] += event->altPathList->next->motifUpCounts[i];\n\t\tcassetteSkipDownMotifs[i] += event->altPathList->next->motifDownCounts[i];\n\t\tcassetteSkipInsideMotifs[i] += event->altPathList->next->motifInsideCounts[i];\n\n\t\t}\n            else\n\t\t{\n\t\tbrainSpecificMotifUpCounts[i] += altPath->motifUpCounts[i];\n\t\tbrainSpecificMotifDownCounts[i] += altPath->motifDownCounts[i];\n\t\tbrainSpecificMotifInsideCounts[i] += altPath->motifInsideCounts[i];\n\t\t}\n\n\t    }\n\tif(event->flipScore >=0)\n\t    cassetteExonSkipCount++;\n\t}\n    brainSpecificPathCount++;\n    brainSpecificEvent = TRUE;\n    fillInSequences(event, slLastEl(event->splice->paths),\n\t\t    &upSeq, &downSeq, &exonSeq, &upSeqBed, &downSeqBed);\n\n\n    /* Write out the data. */\n    if (event->flipScore >= optionFloat(\"minFlip\", -200000) \n    &&  event->flipScore <= optionFloat(\"maxFlip\", 200000) \n    &&  event->percentUltra >= optionFloat(\"minIntCons\", 0.0))\n        {\n        struct bed *endsBed = NULL;\n\tstruct bed *upExonBed = NULL, *downExonBed = NULL;\n\tstruct dyString *dna = newDyString(2*upSeq->size+5);\n\tchar *tmp = NULL;\n\tdyStringPrintf(dna, \"%sNNN%s\", upSeq->dna, downSeq->dna);\n\tif(lifted)\n\t    {\n            writeOutOverlappingUltra(brainSpConsDnaOut, brainSpConsBedOut,\n\t\t\t\t     chrom, chromStart, chromEnd, strand);\n\t    }\n\tfaWriteNext(brainSpDnaUpOut, upSeq->name, upSeq->dna, upSeq->size);\n\tbedTabOutN(upSeqBed, 6, brainSpBedUpOut);\n\tvmAddVal(brainSpecificValues, skipPSet, \"upSeq\", upSeq->dna);\n\n\tfaWriteNext(brainSpDnaDownOut, downSeq->name, downSeq->dna, downSeq->size);\n\tbedTabOutN(downSeqBed, 6, brainSpBedDownOut);\n\tvmAddVal(brainSpecificValues, skipPSet, \"downSeq\", downSeq->dna);\n\n\tvmAddVal(brainSpecificValues, skipPSet, \"exonSeq\", exonSeq->dna);\n\tfaWriteNext(brainSpDnaMergedOut, upSeqBed->name, dna->string, dna->stringSize);\n\tpathBed->score = 100*event->flipScore;\n\ttmp = pathBed->name;\n        pathBed->name = skipPSet;\n        bedTabOutN(pathBed, 6, brainSpPathBedOut);\n        pathBed->name = tmp;\n\n        /* Find the ends of the intron and make beds for the\n           portions of the upstream and downstream exons that connect\n           to this exon bed. */\n\tendsBed = pathToBed(altPath->path, event->splice, -1, -1, TRUE);\n\tassert(endsBed);\n\tAllocVar(upExonBed);\n\tAllocVar(downExonBed);\n\tupExonBed->strand[0] = downExonBed->strand[0] = endsBed->strand[0];\n\tupExonBed->score = downExonBed->score = pathBed->score;\n\tupExonBed->chrom = cloneString(endsBed->chrom);\n\tdownExonBed->chrom = cloneString(endsBed->chrom);\n\tupExonBed->name = cloneString(endsBed->name);\n\tdownExonBed->name = cloneString(endsBed->name);\n\n\tdownExonBed->chromStart = endsBed->chromEnd;\n        downExonBed->chromEnd = downExonBed->chromStart + 10;\n        upExonBed->chromEnd = endsBed->chromStart;\n        upExonBed->chromStart = upExonBed->chromEnd - 10;\n        if (endsBed->strand[0] == '-')\n            {\n            struct bed *tmp = upExonBed;\n            upExonBed = downExonBed;\n\t    downExonBed = tmp;\n\t    }\n\tbedTabOutN(upExonBed, 6, brainSpPathBedExonUpOut);\n\tbedTabOutN(downExonBed, 6, brainSpPathBedExonDownOut);\n\tbedFree(&upExonBed);\n\tbedFree(&downExonBed);\n\tbedFree(&endsBed);\n\t}\n\n    bedFree(&upSeqBed);\n    bedFree(&downSeqBed);\n    dnaSeqFree(&upSeq);\n    dnaSeqFree(&downSeq);\n    dnaSeqFree(&exonSeq);\n    }\n\nif(brainSpecificEvent == TRUE)\n    {\n    brainSpecificEventCount++;\n\n    switch(splice->type)\n\t{\n\tcase altCassette :\n\t    brainSpecificCounts[altCassette]++;\n\t    break;\n\tcase altMutExclusive :\n\t    brainSpecificCounts[altMutExclusive]++;\n\t    break;\n\tcase alt5Prime :\n\t    brainSpecificCounts[alt5Prime]++;\n\t    break;\n\tcase alt3Prime :\n\t    brainSpecificCounts[alt3Prime]++;\n\t    break;\n\tcase alt3PrimeSoft :\n\t    brainSpecificCounts[alt3PrimeSoft]++;\n\t    break;\n\tcase altOther :\n\t    brainSpecificCounts[altOther]++;\n\t    break;\n\t}\n    }\n}\n\nvoid incrementCountByType(int *array, int type)\n{\nswitch(type)\n    {\n    case altCassette :\n\tarray[altCassette]++;\n\tbreak;\n    case altMutExclusive :\n\tarray[altMutExclusive]++;\n\tbreak;\n    case alt5Prime :\n\tarray[alt5Prime]++;\n\tbreak;\n    case alt3Prime :\n\tarray[alt3Prime]++;\n\tbreak;\n    case alt3PrimeSoft :\n\tarray[alt3PrimeSoft]++;\n\tbreak;\n    case altOther :\n\tarray[altOther]++;\n\tbreak;\n    }\n}\n\nvoid outputTissueSpecificEvents(struct altEvent *event, int **expressed, int **notExpressed,\n\t\t\t       int pathCount, struct dMatrix *probM)\n/* Output the event if it is tissue specific\n   specific. */\n{\nint tissueIx = 0;\nstruct altPath *altPath = NULL;\nstruct splice *splice = event->splice;\nfor(tissueIx = 0; tissueIx < probM->colCount; tissueIx++)\n    {\n    boolean tissueSpecificEvent = FALSE;\n    int pathIx = 0;\n    for(altPath = event->altPathList; altPath != NULL; altPath = altPath->next, pathIx++)\n        {\n        if (altPath->path->bpCount > 0 \n        &&  tissueSpecific(event, pathIx, tissueIx, expressed, notExpressed, pathCount, probM))\n            {\n            incrementCountByType(tissueSpecificCounts[tissueIx], splice->type);\n\t    break;\n\t    }\n\t}\n    }\n}\n\n\nboolean onlyTwoPaths(struct altEvent *event)\n/* Return TRUE if event is altCassette, alt3Prime, alt5Prime,\n * altMutEx. FALSE otherwise. */\n{\nint type = event->splice->type;\nif(type == altCassette || type == alt3Prime || type == alt5Prime || type == altMutExclusive)\n    return TRUE;\nreturn FALSE;\n}\n\n\n\ndouble expressionRatio(struct altEvent *event, struct altPath *skipPath,\n\t\t       struct altPath *incPath, int tissueIx)\n/* Calculate the expression ratio between the two paths.*/\n{\ndouble skipExp = 0.0, incExp = 0.0;\nint probeIx = 0;\ndouble ratio = 0.0;\n/* Calculate average expression for inc and skip paths. */\nskipExp = expressionAverage(skipPath, tissueIx);\nincExp =  expressionAverage(incPath, tissueIx);\nif(skipExp == -1 || incExp == -1)\n    return -1;\n\n/* Caclulate the ratio. */\nif(incExp == 0)\n    incExp = .00001;\nratio = skipExp / incExp;\nreturn ratio;\n}\n\nstruct altPath *altPathStubForGeneSet(struct altEvent *event, int geneIx)\n/* Create a \"fake\" path from data for gene probe set. Return NULL if no\n probeSets for a given event. */\n{\nstruct altPath *ap = NULL;\nif(event->geneProbeCount < 1)\n    return NULL;\nAllocVar(ap);\nap->probeCount = 1;\nap->beds = &event->geneBeds[geneIx];\nap->expVals = &event->geneExpVals[geneIx];\nap->pVals = &event->genePVals[geneIx];\nap->avgExpVals = event->geneExpVals[geneIx];\nreturn ap;\n}\n\n\n\nvoid outputRatioStatsForPaths(struct altEvent *event, struct altPath *incPath,\n\t\t\t      struct altPath *skipPath, struct altPath *namePath,\n\t\t\t      struct dMatrix *probM, struct dMatrix *intenM)\n/* Write the stats for a pair of particular paths. */\n{\nstruct splice *splice = event->splice;\nint tissueIx = 0;\nchar *eventName = nameForSplice(splice, namePath);\nint i = 0;\nchar *skipPSet = NULL;\nassert(ratioStatOut != NULL);\nassert(intenM->colCount = probM->colCount);\n\n/* If there is no data don't output anything. */\nif(skipPath->probeCount == 0 || incPath->probeCount == 0)\n    return;\n\nif(brainSpPSetOut != NULL)\n    {\n    skipPSet = namePath->beds[0]->name;\n    fprintf(brainSpPSetOut, \"%s\\t\", refSeqForPSet(skipPSet));\n    fprintf(brainSpPSetOut, \"%s\\t\", skipPSet);\n    fprintf(brainSpPSetOut, \"%d\\t\", incPath->probeCount);\n    for (i = 0; i < incPath->probeCount; i++)\n        {\n        fprintf(brainSpPSetOut, \"%s,\", incPath->beds[i]->name);\n        }\n    fprintf(brainSpPSetOut, \"\\t%d\\t\", event->geneProbeCount);\n    for (i = 0; i < event->geneProbeCount; i++)\n        {\n        fprintf(brainSpPSetOut, \"%s,\", event->geneBeds[i]->name);\n        }\n    fprintf(brainSpPSetOut, \"\\n\");\n    }\n\nfprintf(ratioStatOut, \"%s\", eventName);\nfprintf(ratioSkipIntenOut, \"%s\", eventName);\nfprintf(ratioIncIntenOut, \"%s\", eventName);\nfprintf(ratioGeneIntenOut, \"%s\", eventName);\nfprintf(ratioProbOut, \"%s\", eventName);\nfprintf(incProbOut, \"%s\", eventName);\nfprintf(skipProbOut, \"%s\", eventName);\nfprintf(incProbCombOut, \"%s\", eventName);\nfprintf(skipProbCombOut, \"%s\", eventName);\n/* Loop through tissues caclulating ratio. */\nfor(tissueIx = 0; tissueIx < probM->colCount; tissueIx++)\n    {\n    double ratio = expressionRatio(event, skipPath, incPath, tissueIx);\n    int bestProbeIx = determineBestProbe(event, incPath, intenM, probM, BIGNUM);\n    fprintf(ratioStatOut, \"\\t%.6f\", ratio);\n    fprintf(ratioSkipIntenOut, \"\\t%.6f\", expressionAverage(skipPath, tissueIx));\n    fprintf(ratioIncIntenOut, \"\\t%.6f\", expressionAverage(incPath, tissueIx));\n    fprintf(ratioGeneIntenOut, \"\\t%.6f\", geneExpression(event, tissueIx));\n    fprintf(ratioProbOut, \"\\t%.6f\", genePVal(event, tissueIx));\n    fprintf(skipProbOut, \"\\t%.6f\", pvalAltPathMaxExpressed(skipPath, tissueIx));\n    fprintf(incProbOut, \"\\t%.6f\", pvalAltPathMaxExpressed(incPath, tissueIx));\n    fprintf(skipProbCombOut, \"\\t%.6f\", 1-pvalAltPathCombExpressed(skipPath, tissueIx));\n/*     fprintf(incProbCombOut, \"\\t%.6f\", incPath->pVals[bestProbeIx][tissueIx]); */\n    fprintf(incProbCombOut, \"\\t%.6f\", 1-pvalAltPathCombExpressed(incPath, tissueIx));\n    }\nfprintf(ratioStatOut, \"\\n\");\nfprintf(ratioSkipIntenOut, \"\\n\");\nfprintf(ratioIncIntenOut, \"\\n\");\nfprintf(ratioGeneIntenOut, \"\\n\");\nfprintf(ratioProbOut, \"\\n\");\nfprintf(incProbOut, \"\\n\");\nfprintf(skipProbOut, \"\\n\");\nfprintf(incProbCombOut, \"\\n\");\nfprintf(skipProbCombOut, \"\\n\");\n\n\n}\n\nvoid outputRatioStats(struct altEvent *event, struct dMatrix *probM,\n                      struct dMatrix *intenM, boolean doVsGeneSets)\n/* Calculate the ratio of skip to include for tissues that are\n   considered expressed. For tissues where event isn't expressed\n   output -1 as all ratios will be positive this makes a good empty\n   data place holder. */\n{\nstruct altPath *skipPath = NULL, *incPath = NULL, *namePath = NULL;\ndouble tmpThresh = presThresh;\n\n/* Few sanity checks. */\nassert(ratioStatOut != NULL);\nassert(intenM->colCount = probM->colCount);\n\n/* Going to include everything that we think might\n   have a chance of being expressed. */\nif (!doVsGeneSets)\n    {\n    assert(slCount(event->altPathList) == 2);\n    skipPath = event->altPathList;\n    incPath = event->altPathList->next;\n    namePath = skipPath;\n    /* If there is no data don't output anything. */\n    if(skipPath->probeCount == 0 || incPath->probeCount == 0)\n\treturn;\n    presThresh = absThresh;\n    outputRatioStatsForPaths(event, incPath, skipPath, namePath, probM, intenM);\n    presThresh = tmpThresh;\n    }\nelse if(event->geneProbeCount > 0)\n    {\n    struct altPath *gene1Path = NULL, *gene2Path = NULL;\n    presThresh = absThresh;\n    gene1Path = altPathStubForGeneSet(event, 0);\n    for (incPath = event->altPathList; incPath != NULL; incPath = incPath->next)\n        {\n        if (incPath->probeCount == 0)\n            continue;\n\tskipPath = gene1Path;\n\tnamePath = incPath;\n\toutputRatioStatsForPaths(event, incPath, skipPath, namePath, probM, intenM);\n\t}\n    freez(&gene1Path);\n    presThresh = tmpThresh;\n    }\n}\n\nvoid doEventAnalysis(struct altEvent *event, struct dMatrix *intenM,\n\t\t     struct dMatrix *probM)\n/* Analyze a given event. */\n{\nint i = 0;\nstruct splice *splice = event->splice;\nint **expressed = NULL;\nint **notExpressed = NULL;\ndouble **expression = NULL;\nstruct altPath *altPath = NULL;\nint pathCount = slCount(event->altPathList);\nint pathExpCount = 0;\nint pathIx = 0;\nint withProbes = 0;\n\n/* Allocate a 2D array for expression. */\nAllocArray(expressed, pathCount);\nAllocArray(notExpressed, pathCount);\nAllocArray(expression, pathCount);\nfor(i = 0; i < pathCount; i++)\n    {\n    AllocArray(expressed[i], probM->colCount);\n    AllocArray(notExpressed[i], probM->colCount);\n    AllocArray(expression[i], intenM->colCount);\n    }\n\n/* Fill in the array. */\nfor(altPath = event->altPathList; altPath != NULL; altPath = altPath->next)\n    {\n    if(altPath->probeCount > 0)\n        withProbes++;\n    if (altPathExpressed(event, altPath, intenM, probM,\n                         expressed, notExpressed, expression, pathIx))\n        pathExpCount++;\n\n    /* Output the probabilities. */\n    if(pathProbabilitiesOut != NULL && event->splice->type != altOther)\n        {\n        outputPathProbabilities(event, altPath, intenM, probM,\n\t\t\t\texpressed, notExpressed, expression, pathIx);\n\t}\n    pathIx++;\n    }\n\n/* Determine our expression, alternate or otherwise. */\nif(pathExpCount >= tissueExpThresh && withProbes > 1)\n    event->isExpressed = TRUE;\nif(pathExpCount >= tissueExpThresh * 2 && withProbes > 1)\n    event->isAltExpressed = TRUE;\n\n/* If we are outputting the beds for cassettes do it now. */\nif(altCassetteBedOut && event->splice->type == altCassette && event->altPathProbeCount >= 2)\n    {\n    struct bed *outBed = pathToBed(event->altPathList->next->path, event->splice, -1, -1, TRUE);\n    if(event->isAltExpressed)\n\tbedTabOutN(outBed, 12, altCassetteBedOut);\n    else if(event->isExpressed)\n\tbedTabOutN(outBed, 12, expressedCassetteBedOut);\n    else\n\tbedTabOutN(outBed, 12, notExpressedCassetteBedOut);\n    bedFree(&outBed);\n    }\n\n/* If we are outputting a ratio statistic do it now. */\nif(onlyTwoPaths(event) && ratioStatOut)\n    {\n    outputRatioStats(event, probM, intenM, FALSE);\n    }\nelse if(( splice->type == altMutExclusive ||\n\t  splice->type == alt3PrimeSoft ||\n\t  splice->type == alt5PrimeSoft) &&\n\tratioStatOut)\n    {\n    outputRatioStats(event, probM, intenM, TRUE);\n    }\n\n/* Get a background count of motifs in the cassettes. */\nif(brainSpBedUpOut != NULL)\n    outputBrainSpecificEvents(event, expressed, notExpressed, pathCount, probM);\n\nif(tissueSpecificOut != NULL && event->isExpressed == TRUE)\n    outputTissueSpecificEvents(event, expressed, notExpressed, pathCount, probM);\n\nif(event->isAltExpressed && event->splice->type == altCassette && event->pVal < pvalThresh)\n    {\n    for(i = 0; i < bindSiteCount; i++)\n\t{\n\tcassetteUpMotifs[i] += event->altPathList->next->motifUpCounts[i];\n\tcassetteDownMotifs[i] += event->altPathList->next->motifDownCounts[i];\n\tcassetteInsideMotifs[i] += event->altPathList->next->motifInsideCounts[i];\n\t}\n    cassetteExonCount++;\n    }\n\n/* Cleanup some memory. */\nfor(i = 0; i < pathCount; i++)\n    {\n    freez(&expressed[i]);\n    freez(&notExpressed[i]);\n    freez(&expression[i]);\n    }\nfreez(&notExpressed);\nfreez(&expressed);\nfreez(&expression);\n}\n\nint stringOccurance(char *needle, char *haystack)\n/* How many times is needle in haystack? */\n{\nint count = 0;\nchar *rest = haystack;\ntouppers(needle);\ntouppers(haystack);\nwhile((rest = stringIn(needle, rest)) != NULL)\n    {\n    count++;\n    rest++;\n    }\nreturn count;\n}\n\nint countMotifs(char *seq, struct bindSite *bs)\n/* Count how many times this binding site appears in this\n   sequence. */\n{\nint i = 0, j = 0;\nint count = 0;\ntouppers(seq);\nfor(i = 0; i < bs->motifCount; i++)\n    {\n    count += stringOccurance(bs->motifs[i],seq);\n    }\nreturn count;\n}\n\nvoid doMotifCassetteAnalysis(struct altEvent *event)\n/* Look to see how many motifs are found around this event. */\n{\nstruct dnaSeq *upStream = NULL, *downStream = NULL, *tmp = NULL, *inside = NULL;\nstruct altPath *altPath = event->altPathList->next;\nstruct path *path = altPath->path;\nint *vPos = event->splice->vPositions;\nint *v = path->vertices;\nint chromStart = vPos[v[1]];\nint chromEnd = vPos[v[2]];\nint motifWin = optionInt(\"motifWin\", 200);\nint i = 0;\nif(event->splice->strand[0] == '-')\n    {\n    upStream = hChromSeq(path->tName, chromEnd, chromEnd+motifWin);\n    reverseComplement(upStream->dna, upStream->size);\n    downStream = hChromSeq(path->tName, chromStart-motifWin, chromStart);\n    reverseComplement(downStream->dna, downStream->size);\n    inside = hChromSeq(path->tName, chromStart, chromEnd);\n    reverseComplement(inside->dna, inside->size);\n    }\nelse\n    {\n    upStream = hChromSeq(path->tName, chromStart-motifWin, chromStart);\n    downStream = hChromSeq(path->tName, chromEnd, chromEnd+motifWin);\n    inside = hChromSeq(path->tName, chromStart, chromEnd);\n    }\nAllocArray(altPath->motifUpCounts, bindSiteCount);\nAllocArray(altPath->motifDownCounts, bindSiteCount);\nAllocArray(altPath->motifInsideCounts, bindSiteCount);\nfor(i = 0; i < bindSiteCount; i++)\n    {\n    altPath->motifUpCounts[i] += countMotifs(upStream->dna, bindSiteArray[i]);\n    altPath->motifDownCounts[i] += countMotifs(downStream->dna, bindSiteArray[i]);\n    altPath->motifInsideCounts[i] += countMotifs(inside->dna, bindSiteArray[i]);\n    }\ndnaSeqFree(&upStream);\ndnaSeqFree(&downStream);\ndnaSeqFree(&inside);\n}\n\nvoid doMotifControlAnalysis(struct altEvent *event)\n/* Look to see how many motifs are found around this event. */\n{\nstruct dnaSeq *upStream = NULL, *downStream = NULL, *tmp = NULL, *inside = NULL;\nstruct altPath *altPath = event->altPathList;\nstruct splice *splice = event->splice;\nstruct path *path = altPath->path;\nstruct bed *bed = NULL;\nint *vPos = event->splice->vPositions;\nint *v = path->vertices;\nint chromStart = 0;\nint chromEnd = 0;\nint motifWin = optionInt(\"motifWin\", 200);\nint i = 0;\nint blockIx;\nbed = pathToBed(path, splice, -1, -1, FALSE);\nif(bed == NULL)\n    return;\n\n/* Only do internal exons. */\nfor(blockIx = 1; blockIx < bed->blockCount - 1; blockIx++)\n    {\n    struct bed *outBed = NULL;\n\n    /* Print out a bed of this exon. */\n    AllocVar(outBed);\n    outBed->chromStart = chromStart = bed->chromStart + bed->chromStarts[blockIx];\n    outBed->chromEnd = chromEnd = chromStart + bed->blockSizes[blockIx];\n    safef(outBed->strand,sizeof(outBed->strand),\"%s\", bed->strand);\n    outBed->score = bed->score;\n    outBed->chrom = cloneString(bed->chrom);\n    outBed->name = cloneString(bed->name);\n    subChar(outBed->name, '-', '\\0');\n    bedTabOutN(outBed, 6, brainSpPathBedOut);\n\n    if(!skipMotifControls)\n\t{\n\tassert(constMotifCounts);\n        fprintf(constMotifCounts, \"%s:%s:%d-%d\",\n\t\toutBed->name, outBed->chrom, outBed->chromStart, outBed->chromEnd);\n\t/* Get the sequences and do motif analysis. */\n\tif(event->splice->strand[0] == '-')\n\t    {\n\t    upStream = hChromSeq(path->tName, chromEnd, chromEnd+motifWin);\n\t    reverseComplement(upStream->dna, upStream->size);\n\t    downStream = hChromSeq(path->tName, chromStart-motifWin, chromStart);\n\t    reverseComplement(downStream->dna, downStream->size);\n\t    inside = hChromSeq(path->tName, chromStart, chromEnd);\n\t    reverseComplement(inside->dna, inside->size);\n\t    }\n\telse\n\t    {\n\t    upStream = hChromSeq(path->tName, chromStart-motifWin, chromStart);\n\t    downStream = hChromSeq(path->tName, chromEnd, chromEnd+motifWin);\n\t    inside = hChromSeq(path->tName, chromStart, chromEnd);\n\t    }\n\ttouppers(upStream->dna);\n\ttouppers(downStream->dna);\n\ttouppers(inside->dna);\n\tcontrolInsideBpCount += inside->size;\n\tif(altPath->motifUpCounts == NULL)\n\t    {\n\t    AllocArray(altPath->motifUpCounts, bindSiteCount);\n\t    AllocArray(altPath->motifDownCounts, bindSiteCount);\n\t    AllocArray(altPath->motifInsideCounts, bindSiteCount);\n\t    }\n\tfor(i = 0; i < bindSiteCount; i++)\n\t    {\n\t    int upStreamCount = countMotifs(upStream->dna, bindSiteArray[i]);\n\t    int downStreamCount = countMotifs(downStream->dna, bindSiteArray[i]);\n\t    int insideCount = countMotifs(inside->dna, bindSiteArray[i]);\n\n\t    /* Report our counts. */\n\t    fprintf(constMotifCounts, \"\\t%d\\t%d\", upStreamCount, downStreamCount);\n\n\t    altPath->motifUpCounts[i] += upStreamCount;\n\t    controlUpMotifs[i] += upStreamCount;\n\t    altPath->motifDownCounts[i] += downStreamCount;\n\t    controlDownMotifs[i] += downStreamCount;\n\t    altPath->motifInsideCounts[i] += insideCount;\n\t    controlInsideMotifs[i] += insideCount;\n\n\t    }\n\tbedFree(&outBed);\n\t/* Finish control line. */\n\tfprintf(constMotifCounts, \"\\n\");\n\tcontrolExonCount++;\n\t}\n    }\ndnaSeqFree(&upStream);\ndnaSeqFree(&downStream);\ndnaSeqFree(&inside);\n}\n\nint flipScoreCmp(const void *va, const void *vb)\n/* Compare to sort based on chrom,chromStart. */\n{\nconst struct slRef *a = *((struct slRef**)va);\nconst struct slRef *b = *((struct slRef **)vb);\nstruct altEvent *aE = a->val;\nstruct altEvent *bE = b->val;\nif(fabs(aE->flipScore) > fabs(bE->flipScore))\n    return -1;\nelse if(fabs(aE->flipScore) < fabs(bE->flipScore))\n    return 1;\nreturn 0;\n}\n\nint percentUltraCmp(const void *va, const void *vb)\n/* Compare to sort based on chrom,chromStart. */\n{\nconst struct slRef *a = *((struct slRef**)va);\nconst struct slRef *b = *((struct slRef **)vb);\nstruct altEvent *aE = a->val;\nstruct altEvent *bE = b->val;\nif(aE->percentUltra < bE->percentUltra)\n    return 1;\nelse if(aE->percentUltra > bE->percentUltra)\n    return -1;\nreturn 0;\n}\n\nboolean isHardExon(unsigned char *vTypes, int v1, int v2)\n/* Return TRUE if this is a hard exon. */\n{\nif(ggExon == pathEdgeType(vTypes, v1, v2) &&\n   (vTypes[v1] == ggHardStart || vTypes[v1] == ggHardEnd) &&\n   (vTypes[v2] == ggHardStart || vTypes[v2] == ggHardEnd))\n    return TRUE;\nreturn FALSE;\n}\n\nvoid doControlStats(struct altEvent *event)\n/* Calculate control stats for control events. */\n{\nstruct splice *splice = event->splice;\nstruct path *path = event->altPathList->path;\nint chromStart = 0, chromEnd = 0;\nchar strand;\nchar *chrom;\nint vertIx = 0;\nint *verts = NULL;\nint vC = path->vCount;\nint *vPos = splice->vPositions;\nunsigned char *vTypes = splice->vTypes;\nstruct dyString *name = newDyString(128);\nfor(vertIx = 0; vertIx < vC - 1; vertIx++)\n    {\n    if(isHardExon(vTypes, vertIx, vertIx+1))\n\t{\n\tchar *startChrom = cloneString(path->tName);\n\tchar *endChrom = cloneString(path->tName);\n\tchar *cassChrom = cloneString(path->tName);\n\tint intStart = vPos[vertIx == 0 ? path->upV : vertIx-1];\n\tint dummy = 0;\n\tint chromStart = vPos[vertIx];\n\tint chromEnd = vPos[vertIx+1];\n\tint intEnd = vPos[vertIx+1 == vC - 1 ? path->downV : vertIx+2];\n\tchar strand = splice->strand[0];\n\tboolean lifted = TRUE;\n\tdyStringClear(name);\n        /* Lift over each end seperately so as to ignore changes\n           in assembly in the middle. */\n\tdummy = intStart-10;\n\tlifted &= liftOverCoords(&startChrom, &dummy, &intStart, &strand);\n\tstrand = splice->strand[0];\n\tdummy = intEnd+10;\n\tlifted &= liftOverCoords(&endChrom, &intEnd, &dummy, &strand);\n\tstrand = splice->strand[0];\n\tlifted &= liftOverCoords(&cassChrom, &chromStart, &chromEnd, &strand);\n\tif(lifted && sameString(endChrom, cassChrom) && sameString (startChrom, cassChrom))\n\t    {\n\t    dyStringPrintf(name, \"%s.%s:%d-%d\", splice->name, startChrom, chromStart, chromEnd);\n\t    fillInStatsForEvent(controlValuesVm, name->string, startChrom,\n\t\t\t\tintStart, chromStart, chromEnd, intEnd, strand,\n\t\t\t\taltControl);\n\t    }\n\t}\n    }\ndyStringFree(&name);\n}\n\nvoid doAnalysis(struct altEvent *eventList, struct dMatrix *intenM,\n\t\tstruct dMatrix *probM)\n/* How many of the alt events are expressed. */\n{\nstruct altEvent *event = NULL;\nint i = 0;\nstruct altPath *altPath = NULL;\nint expressed = 0, altExpressed = 0;\nstruct slRef *ref = NULL;\nint contCount = 0;\nchar *prefix = optionVal(\"brainSpecific\", NULL);\nchar *useDb = newDb;\nfor(event = eventList; event != NULL; event = event->next)\n    {\n    if(event->splice->type == altCassette && bindSiteCount > 0)\n\tdoMotifCassetteAnalysis(event);\n    else if(event->splice->type == altControl && bindSiteCount > 0)\n\tdoMotifControlAnalysis(event);\n\n    if(controlValuesVm != NULL && event->splice->type == altControl)\n\t{\n\tif(++contCount % 100 == 0)\n\t    {\n\t    fputc('*',stderr);\n\t    fflush(stderr);\n\t    contCount = 0;\n\t    }\n\tdoControlStats(event);\n\t}\n    doEventAnalysis(event, intenM, probM);\n\n    if(event->isExpressed)\n\tlogSpliceTypeExp(event->splice->type);\n    if(event->isAltExpressed)\n\tlogSpliceTypeAltExp(event->splice->type);\n    }\nif(brainSpBedUpOut != NULL)\n    {\n    char *chrom = NULL;\n    int chromStart = 0, chromEnd = 0;\n    struct bed *bed = NULL;\n\n    if(optionExists(\"flipScoreSort\"))\n\tslSort(&brainSpEvents, flipScoreCmp);\n    else\n\tslSort(&brainSpEvents, percentUltraCmp);\n    vmWriteVals(brainSpecificValues, brainSpValuesOut);\n    event = brainSpEvents->val;\n    altPath = event->altPathList->next;\n    bed = pathToBed(altPath->path, event->splice, -1, -1, FALSE);\n    chrom = cloneString(bed->chrom);\n    chromStart = bed->chromStart;\n    chromEnd = bed->chromEnd;\n    fprintf(brainSpFrameHtmlOut, \"<html><head><title>%s Specific Events.</title></head>\\n\"\n\t    \"<frameset cols=\\\"30%,70%\\\">\\n\"\n\t    \"   <frame name=\\\"_list\\\" src=\\\"./%s%s\\\">\\n\"\n\t    \"   <frameset rows=\\\"50%,50%\\\">\\n\"\n\t    \"      <frame name=\\\"browser\\\" src=\\\"http://%s/cgi-bin/hgTracks?db=%s&hgt.motifs=GCATG,CTCTCT,GGGG&position=%s:%d-%d\\\">\\n\"\n\t    \"      <frame name=\\\"plots\\\" src=\\\"http://%s/cgi-bin/hgTracks?db=%s&position=%s:%d-%d\\\">\\n\"\n\t    \"   </frameset>\\n\"\n\t    \"</frameset>\\n\"\n            \"</html>\\n\", optionVal(\"brainTissues\",\"Brain\"), prefix, \".table.html\",\n\t    browserName, useDb,\n\t    chrom, chromStart, chromEnd,\n\t    browserName, useDb,\n\t    chrom, chromStart, chromEnd\n\t    );\n    carefulClose(&brainSpFrameHtmlOut);\n    for(ref = brainSpEvents; ref != NULL; ref = ref->next)\n\t{\n\tstruct altEvent *bEvent = ref->val;\n\tprintLinks(bEvent);\n\t}\n    }\n}\n\ndouble calcPercent(double numerator, double denominator)\n/* Calculate a percent checking for zero. */\n{\nif(denominator != 0)\n    return (100.0 * numerator / denominator);\nreturn 0;\n}\n\ndouble cph(double numerator, double denominator)\n/* Calculate a ratio checking for zero. */\n{\nif(denominator != 0)\n    return (numerator / denominator);\nreturn 0;\n}\n\nvoid reportTissueSpecificCounts(char **tissueNames, int tissueCount)\n/* Writ out a matrix of tissues and their counts. */\n{\nint i = 0, j = 0;\n\nassert(tissueSpecificOut);\n\nfprintf(tissueSpecificOut, \"\\taltCassette\\taltMutExclusive\\talt5Prime\\talt3Prime\\taltOther\\n\");\nfor(i = 0; i < tissueCount; i++)\n    {\n    fprintf(tissueSpecificOut, \"%-22s\\t%4d\\t%4d\\t%4d\\t%4d\\t%4d\\n\", tissueNames[i],\n\t    tissueSpecificCounts[i][altCassette], tissueSpecificCounts[i][altMutExclusive],\n\t    tissueSpecificCounts[i][alt5Prime],tissueSpecificCounts[i][alt3Prime],\n\t    tissueSpecificCounts[i][altOther]);\n    }\n}\n\nvoid reportMotifCounts(int *up, int *down, int *in, int total, int bpTotal)\n{\nint *u = up;\nint *d = down;\nint *i = in;\nint t = total;\nint bt = bpTotal;\nstruct bindSite **b = bindSiteArray;\nassert(up);\nassert(down);\nfprintf(stderr, \"+----------+--------------+----------------+----------------+-----------------+----------------+----------------+\\n\");\nfprintf(stderr, \"| Position | %12s | %14s | %14s | %15s | %14s | %14s |\\n\",\n\tb[0]->rnaBinder, b[1]->rnaBinder, b[2]->rnaBinder, b[3]->rnaBinder, b[4]->rnaBinder, b[5]->rnaBinder);\nfprintf(stderr, \"+----------+--------------+----------------+----------------+-----------------+----------------+----------------+\\n\");\n//fprintf(stderr, \"+----------+------------+--------------+--------------+---------------+--------------+--------------+\\n\");\nfprintf(stderr, \"| %-8s | %3d (%4.4f) | %5d (%4.4f) | %5d (%4.4f) | %6d (%4.4f) | %5d (%4.4f) | %5d (%4.4f) |\\n\",\n\t\"UpStream\", u[0], cph(u[0],t), u[1], cph(u[1],t), u[2], cph(u[2],t), u[3], cph(u[3],t), u[4],cph(u[4],t), u[5],cph(u[5],t));\nfprintf(stderr, \"| %-8s | %3d (%4.4f) | %5d (%4.4f) | %5d (%4.4f) | %6d (%4.4f) | %5d (%4.4f) | %5d (%4.4f) |\\n\",\n\t\"DnStream\", d[0], cph(d[0],t), d[1], cph(d[1],t), d[2], cph(d[2],t), d[3], cph(d[3],t), d[4],cph(d[4],t), d[5],cph(d[5],t));\nfprintf(stderr, \"| %-8s | %3d (%1.4f) | %5d (%1.4f) | %5d (%1.4f) | %6d (%1.4f) | %5d (%1.4f) | %5d (%1.4f) |\\n\",\n\t\"Inside  \", i[0], cph(i[0],bt), i[1], cph(i[1],bt), i[2], cph(i[2],bt), i[3], cph(i[3],bt), i[4],cph(i[4],bt), i[5],cph(i[5],bt));\nfprintf(stderr, \"+----------+--------------+----------------+----------------+-----------------+----------------+----------------+\\n\");\n\n}\n\n\nvoid reportBrainSpCounts()\n/* Print brain specific results. */\n{\nif(brainSpDnaUpOut != NULL)\n    {\n    int *bC = brainSpecificCounts;\n    char *tissue = optionVal(\"brainTissues\",\"Brain\");\n    fprintf(stderr, \"%d %s Specific Events. %d %s Specific paths\\n\",\n\t     brainSpecificEventCount, tissue, brainSpecificPathCount, tissue);\n    fprintf(stderr, \"+----------+---------+-------+-------+-------+-------+\\n\");\n    fprintf(stderr, \"| Cassette | MutExcl | Alt3' | Alt5' | TxEnd | Other |\\n\");\n    fprintf(stderr, \"+----------+---------+-------+-------+-------+-------+\\n\");\n    fprintf(stderr, \"| %8d | %7d | %5d | %5d | %5d | %5d |\\n\",\n\t    bC[altCassette], bC[altMutExclusive], bC[alt3Prime], bC[alt5Prime],\n\t    bC[alt3PrimeSoft], bC[altOther]);\n    fprintf(stderr, \"+----------+---------+-------+-------+-------+-------+\\n\");\n    if(bindSiteCount != 0)\n\t{\n\tint *u = brainSpecificMotifUpCounts;\n\tint *d = brainSpecificMotifDownCounts;\n\tint *i = brainSpecificMotifInsideCounts;\n\tint bp = brainSpecificMotifInsideBpCount;\n\tstruct bindSite **b = bindSiteArray;\n\tfprintf(stderr,\"Cassette binding sites in %d include exons:\\n\", bC[altCassette]-cassetteExonSkipCount);\n\treportMotifCounts(u,d,i,bC[altCassette] - cassetteExonSkipCount, bp);\n\tu = cassetteSkipUpMotifs;\n\td = cassetteSkipDownMotifs;\n\ti = cassetteSkipInsideMotifs;\n\tbp = cassetteSkipInsideBpCount;\n\tfprintf(stderr,\"Cassette binding sites in %d skip exons:\\n\", cassetteExonSkipCount);\n\treportMotifCounts(u,d,i,cassetteExonSkipCount, bp);\n\t}\n    }\n}\n\nvoid reportEventCounts()\n/* Print some stats about splices and probe with counts. */\n{\nfprintf(stderr, \"+----------------------+-------+-----------+-----------+------+---------+\\n\");\nfprintf(stderr, \"| Alt Event.           | Count | w/ Probes | Expressed | Alt. | Percent |\\n\");\nfprintf(stderr, \"+----------------------+-------+-----------+-----------+------+---------+\\n\");\nfprintf(stderr, \"| alt 5'               | %5d |      %4d |      %4d |  %3d |  %5.1f%% |\\n\",\n\talt5PrimeCount, alt5PrimeWProbeCount, alt5PrimeExpCount, alt5PrimeAltExpCount,\n\tcalcPercent(alt5PrimeAltExpCount, alt5PrimeExpCount));\nfprintf(stderr, \"| alt 3'               | %5d |      %4d |      %4d |  %3d |  %5.1f%% |\\n\",\n\talt3PrimeCount, alt3PrimeWProbeCount, alt3PrimeExpCount, alt3PrimeAltExpCount,\n\tcalcPercent(alt3PrimeAltExpCount, alt3PrimeExpCount));\nfprintf(stderr, \"| alt Cass             | %5d |      %4d |      %4d |  %3d |  %5.1f%% |\\n\",\n\taltCassetteCount, altCassetteWProbeCount, altCassetteExpCount, altCassetteAltExpCount,\n\tcalcPercent(altCassetteAltExpCount, altCassetteExpCount));\nfprintf(stderr, \"| alt Ret. Int.        | %5d |      %4d |      %4d |  %3d |  %5.1f%% |\\n\",\n\taltRetIntCount, altRetIntWProbeCount, altRetIntExpCount, altRetIntAltExpCount,\n\tcalcPercent(altRetIntAltExpCount, altRetIntExpCount));\nfprintf(stderr, \"| alt Mutual Exclusive | %5d |      %4d |      %4d |  %3d |  %5.1f%% |\\n\",\n\taltMutExclusiveCount, altMutExclusiveWProbeCount, altMutExclusiveExpCount, altMutExclusiveAltExpCount,\n\tcalcPercent(altMutExclusiveAltExpCount, altMutExclusiveExpCount));\nfprintf(stderr, \"| alt Txn Start        | %5d |      %4d |      %4d |  %3d |  %5.1f%% |\\n\",\n\talt5PrimeSoftCount, alt5PrimeSoftWProbeCount, alt5PrimeSoftExpCount, alt5PrimeSoftAltExpCount,\n\tcalcPercent(alt5PrimeSoftAltExpCount, alt5PrimeSoftExpCount));\nfprintf(stderr, \"| alt Txn End          | %5d |      %4d |      %4d |  %3d |  %5.1f%% |\\n\",\n\talt3PrimeSoftCount, alt3PrimeSoftWProbeCount, alt3PrimeSoftExpCount, alt3PrimeSoftAltExpCount,\n\tcalcPercent(alt3PrimeSoftAltExpCount, alt3PrimeSoftExpCount));\nfprintf(stderr, \"| alt Other            | %5d |      %4d |      %4d |  %3d |  %5.1f%% |\\n\",\n\taltOtherCount, altOtherWProbeCount, altOtherExpCount, altOtherAltExpCount,\n\tcalcPercent(altOtherAltExpCount, altOtherExpCount));\nfprintf(stderr, \"| alt Control          | %5d |      %4d |      %4d |  %3d |  %5.1f%% |\\n\",\n\taltControlCount, altControlWProbeCount, altControlExpCount, altControlAltExpCount,\n\tcalcPercent(altControlAltExpCount, altControlExpCount));\nfprintf(stderr, \"+----------------------+-------+-----------+-----------+------+---------+\\n\");\n\n/* if(bindSiteCount != 0) */\n/*     { */\n/*     int *u = cassetteUpMotifs; */\n/*     int *d = cassetteDownMotifs; */\n/*     int *i = cassetteInsideMotifs; */\n/*     struct bindSite **b = bindSiteArray; */\n/*     fprintf(stderr,\"Cassette binding sites in included %d include exons:\\n\", cassetteExonCount); */\n/*     reportMotifCounts(u,d,i,cassetteExonCount); */\n\n/*     } */\n\nif(bindSiteCount != 0)\n    {\n    int *u = controlUpMotifs;\n    int *d = controlDownMotifs;\n    int *i = controlInsideMotifs;\n    struct bindSite **b = bindSiteArray;\n    fprintf(stderr,\"Control binding sites in %d exons:\\n\", controlExonCount);\n    reportMotifCounts(u,d,i,controlExonCount, controlInsideBpCount);\n    }\n}\n\nvoid initLiftOver()\n/* Initialize the liftOver process. */\n{\nchar *from = optionVal(\"db\", NULL);\nchar *to = optionVal(\"newDb\", NULL);\nchar *chainFile = NULL;\n\nassert(from);\nhSetDb2(to);\nif(to == NULL)\n    errAbort(\"Must specify a -newDb to do a lift.\");\nchainFile = liftOverChainFile(from, to);\nif(chainFile == NULL)\n    errAbort(\"Couldn't load a lift chainFile for %s->%s\", from, to);\nliftOverHash = newHash(12);\nreadLiftOverMap(chainFile, liftOverHash);\n}\n\nboolean liftOverCoords(char **chrom, int *chromStart, int *chromEnd, char *strand)\n/* Return TRUE and new values if values passed in can be lifted. */\n{\nchar *newChrom = NULL;\nint newStart = 0, newEnd = 0;\nchar newStrand;\nchar *msg = NULL;\nboolean success = FALSE;\nif(liftOverHash != NULL)\n    msg = liftOverRemapRange(liftOverHash, .95, *chrom, *chromStart, *chromEnd, *strand,\n\t\t\t     1.0, &newChrom, &newStart, &newEnd, &newStrand);\nif(msg == NULL)\n    {\n    freez(chrom);\n    *chrom = newChrom;\n    *chromStart = newStart;\n    *chromEnd = newEnd;\n    *strand = newStrand;\n    success = TRUE;\n    }\nreturn success;\n}\n\nvoid initTissueSpecific(int tissueCount)\n/* Open up the files for tissue specific isoforms and dna. */\n{\nchar *name = optionVal(\"tissueSpecific\", NULL);\nint i = 0;\nAllocArray(tissueSpecificCounts, tissueCount);\nfor(i = 0; i < tissueCount; i++)\n    {\n    AllocArray(tissueSpecificCounts[i], 20);\n    }\ntissueSpecificOut = mustOpen(name, \"w\");\n}\n\nvoid initBrainSpecific()\n/* Open up the files for brain specific isoforms and dna. */\n{\nstruct bindSite *bs = NULL;\nchar *prefix = optionVal(\"brainSpecific\", NULL);\nstruct dyString *file = newDyString(strlen(prefix)+10);\nchar *useDb = newDb;\nbrainSpecificStrict = optionExists(\"brainSpecificStrict\");\nbrainSpecificValues = newValuesMat(400,15);\nAllocArray(brainSpecificCounts, altMutExclusive + 1);\n\nif(bindSiteCount > 0)\n    {\n    AllocArray(brainSpecificMotifUpCounts, bindSiteCount);\n    AllocArray(brainSpecificMotifDownCounts, bindSiteCount);\n    AllocArray(brainSpecificMotifInsideCounts, bindSiteCount);\n    }\n\ndyStringClear(file);\ndyStringPrintf(file, \"%s.path.bed\", prefix);\nbrainSpPathBedOut = mustOpen(file->string, \"w\");\n\ndyStringClear(file);\ndyStringPrintf(file, \"%s.probeSets.tab\", prefix);\nbrainSpPSetOut = mustOpen(file->string, \"w\");\n\ndyStringClear(file);\ndyStringPrintf(file, \"%s.path.ends.bed\", prefix);\nbrainSpPathEndsBedOut = mustOpen(file->string, \"w\");\n\ndyStringClear(file);\ndyStringPrintf(file, \"%s.path.exonUp.bed\", prefix);\nbrainSpPathBedExonUpOut = mustOpen(file->string, \"w\");\n\ndyStringClear(file);\ndyStringPrintf(file, \"%s.path.exonDown.bed\", prefix);\nbrainSpPathBedExonDownOut = mustOpen(file->string, \"w\");\n\ndyStringClear(file);\ndyStringPrintf(file, \"%s.up.fa\", prefix);\nbrainSpDnaUpOut = mustOpen(file->string, \"w\");\n\ndyStringClear(file);\ndyStringPrintf(file, \"%s.merged.fa\", prefix);\nbrainSpDnaMergedOut = mustOpen(file->string, \"w\");\n\ndyStringClear(file);\ndyStringPrintf(file, \"%s.cons.fa\", prefix);\nbrainSpConsDnaOut = mustOpen(file->string, \"w\");\n\ndyStringClear(file);\ndyStringPrintf(file, \"%s.cons.bed\", prefix);\nbrainSpConsBedOut = mustOpen(file->string, \"w\");\n\ndyStringClear(file);\ndyStringPrintf(file, \"%s.down.fa\", prefix);\nbrainSpDnaDownOut = mustOpen(file->string, \"w\");\n\ndyStringClear(file);\ndyStringPrintf(file, \"%s.up.bed\", prefix);\nbrainSpBedUpOut = mustOpen(file->string, \"w\");\n\ndyStringClear(file);\ndyStringPrintf(file, \"%s.down.bed\", prefix);\nbrainSpBedDownOut = mustOpen(file->string, \"w\");\n\ndyStringClear(file);\ndyStringPrintf(file, \"%s.values.tab\", prefix);\nbrainSpValuesOut = mustOpen(file->string, \"w\");\n\ndyStringClear(file);\ndyStringPrintf(file, \"%s.table.html\", prefix);\nbrainSpTableHtmlOut = mustOpen(file->string, \"w\");\nfprintf(brainSpTableHtmlOut, \"<html>\\n<body bgcolor=\\\"#FFF9D2\\\"><b>Alt-Splice List</b>\\n\");\n\nfprintf(brainSpTableHtmlOut, \"<tr><td><b>Motif Order:</b>\");\nfor(bs = bindSiteList; bs != NULL; bs = bs->next)\n    fprintf(brainSpTableHtmlOut, \"%s, \", bs->rnaBinder);\nfprintf(brainSpTableHtmlOut, \"</td></tr>\");\nfprintf(brainSpTableHtmlOut,    \"<table border=1><tr><th>Name</th><th>Sep</th></tr>\\n\");\ndyStringClear(file);\ndyStringPrintf(file, \"%s.frame.html\", prefix);\nbrainSpFrameHtmlOut = mustOpen(file->string, \"w\");\n\n\ndyStringFree(&file);\n}\n\nvoid printCdtHeader(FILE *out, struct dMatrix *dM)\n{\nint i = 0;\nfprintf(out, \"YORF\\tNAME\");\nfor(i = 0; i < dM->colCount; i++)\n    {\n    fprintf(out, \"\\t%s\", dM->colNames[i]);\n    }\nfprintf(out, \"\\n\");\n}\n\nvoid initRatioStats(struct dMatrix *intenM)\n/* Setupt a file to output ratio statistics to. */\n{\nint i = 0;\nchar *outputRatioStats = optionVal(\"outputRatioStats\", NULL);\nstruct dyString *buff = NULL;\nassert(outputRatioStats);\nassert(intenM);\nbuff = newDyString(strlen(outputRatioStats)+30);\nratioStatOut = mustOpen(outputRatioStats, \"w\");\n\ndyStringClear(buff);\ndyStringPrintf(buff, \"%s.skip.intensity\", outputRatioStats);\nratioSkipIntenOut = mustOpen(buff->string, \"w\");\n\ndyStringClear(buff);\ndyStringPrintf(buff, \"%s.inc.intensity\", outputRatioStats);\nratioIncIntenOut = mustOpen(buff->string, \"w\");\n\ndyStringClear(buff);\ndyStringPrintf(buff, \"%s.gene.prob\", outputRatioStats);\nratioProbOut = mustOpen(buff->string, \"w\");\n\ndyStringClear(buff);\ndyStringPrintf(buff, \"%s.gene.intensity\", outputRatioStats);\nratioGeneIntenOut = mustOpen(buff->string, \"w\");\n\ndyStringClear(buff);\ndyStringPrintf(buff, \"%s.inc.prob\", outputRatioStats);\nincProbOut = mustOpen(buff->string, \"w\");\n\ndyStringClear(buff);\ndyStringPrintf(buff, \"%s.skip.prob\", outputRatioStats);\nskipProbOut = mustOpen(buff->string, \"w\");\n\ndyStringClear(buff);\ndyStringPrintf(buff, \"%s.inc.comb.prob\", outputRatioStats);\nincProbCombOut = mustOpen(buff->string, \"w\");\n\ndyStringClear(buff);\ndyStringPrintf(buff, \"%s.skip.comb.prob\", outputRatioStats);\nskipProbCombOut = mustOpen(buff->string, \"w\");\n\nfor(i = 0; i < intenM->colCount - 1; i++)\n    {\n    fprintf(ratioStatOut, \"%s\\t\", intenM->colNames[i]);\n    fprintf(ratioSkipIntenOut, \"%s\\t\", intenM->colNames[i]);\n    fprintf(ratioIncIntenOut, \"%s\\t\", intenM->colNames[i]);\n    fprintf(ratioGeneIntenOut, \"%s\\t\", intenM->colNames[i]);\n    fprintf(ratioProbOut, \"%s\\t\", intenM->colNames[i]);\n    fprintf(skipProbOut, \"%s\\t\", intenM->colNames[i]);\n    fprintf(incProbOut, \"%s\\t\", intenM->colNames[i]);\n    fprintf(skipProbCombOut, \"%s\\t\", intenM->colNames[i]);\n    fprintf(incProbCombOut, \"%s\\t\", intenM->colNames[i]);\n    }\nfprintf(ratioStatOut, \"%s\\n\", intenM->colNames[i]);\nfprintf(ratioSkipIntenOut, \"%s\\n\", intenM->colNames[i]);\nfprintf(ratioIncIntenOut, \"%s\\n\", intenM->colNames[i]);\nfprintf(ratioGeneIntenOut, \"%s\\n\", intenM->colNames[i]);\nfprintf(ratioProbOut, \"%s\\n\", intenM->colNames[i]);\nfprintf(skipProbOut, \"%s\\n\", intenM->colNames[i]);\nfprintf(incProbOut, \"%s\\n\", intenM->colNames[i]);\nfprintf(skipProbCombOut, \"%s\\n\", intenM->colNames[i]);\nfprintf(incProbCombOut, \"%s\\n\", intenM->colNames[i]);\n}\n\nvoid outputProbeMatches(struct altEvent *eventList)\n/* Loop through the event list and output the different probes for\n   each path. Only do events that have two paths. */\n{\nstruct altEvent *event = NULL;\nFILE *out = NULL;\nchar *fileName = optionVal(\"outputProbeMatch\", NULL);\nstruct altPath *altPath = NULL;\nint i = 0;\nassert(fileName);\nout = mustOpen(fileName, \"w\");\nfor(event = eventList; event != NULL; event = event->next)\n    {\n    if(slCount(event->altPathList) != 2 || event->altPathProbeCount != 2)\n\tcontinue;\n    fprintf(out, \"%s\", event->splice->name);\n\n    /* Loop through the alternative isoforms and print comma separated probes for each path. */\n    for(altPath = event->altPathList; altPath != NULL; altPath = altPath->next)\n\t{\n\tfputc('\\t', out);\n\tfor(i = 0; i < altPath->probeCount; i++)\n\t    {\n\t    struct bed *bed = altPath->beds[i];\n\t    fprintf(out, \"%s,\", bed->name);\n\t    }\n\t}\n    fputc('\\n', out);\n    }\ncarefulClose(&out);\n}\n\nvoid outputProbePvals(struct altEvent *eventList, struct dMatrix *probM)\n/* Loop through the events and output the probe probabilities. Only do events\n that have two paths. */\n{\nstruct altEvent *event = NULL;\nstruct altPath *altPath = NULL;\nchar *fileName = optionVal(\"outputProbePvals\", NULL);\nint probeIx = 0;\nint expIx = 0;\nint expCount = 0;\nFILE *out = NULL;\nassert(fileName);\nassert(probM);\nout = mustOpen(fileName, \"w\");\nexpCount = probM->colCount;\n\n/* Output the header of column names. */\nfor(expIx = 0; expIx < expCount-1; expIx++)\n    fprintf(out, \"%s\\t\", probM->colNames[expIx]);\nfprintf(out, \"%s\\n\", probM->colNames[expIx]);\n\nfor(event = eventList; event != NULL; event = event->next)\n    {\n    if(slCount(event->altPathList) != 2 || event->altPathProbeCount != 2)\n\tcontinue;\n    for(altPath = event->altPathList; altPath != NULL; altPath = altPath->next)\n\t{\n\tfor(probeIx = 0; probeIx < altPath->probeCount; probeIx++)\n\t    {\n\t    fprintf(out, \"%s\", altPath->beds[probeIx]->name);\n\t    for(expIx = 0; expIx < expCount; expIx++)\n\t\t{\n\t\tfprintf(out, \"\\t%.5f\", altPath->pVals[probeIx][expIx]);\n\t\t}\n\t    fputc('\\n',out);\n\t    }\n\t}\n    }\ncarefulClose(&out);\n}\n\nvoid altProbes()\n/* Top level function to map probes to paths and analyze. */\n{\nstruct splice *spliceList = NULL;\nstruct altEvent *eventList = NULL, *event = NULL;\nstruct dMatrix *intenM = NULL, *probM = NULL;\nchar *intenIn = optionVal(\"intensityFile\", NULL);\nchar *probIn = optionVal(\"probFile\", NULL);\nchar *splicesIn = optionVal(\"spliceFile\", NULL);\nif(splicesIn == NULL)\n    errAbort(\"Must specify a apliceFile\");\n\nwarn(\"Loading splices from %s\", splicesIn);\nspliceList = spliceLoadAll(splicesIn);\neventList = altEventsFromSplices(spliceList);\nwarn(\"Loading beds.\");\nbedLoadChromKeeper();\ndotForUserInit(max(slCount(eventList)/20, 1));\nfor(event = eventList; event != NULL; event = event->next)\n    {\n    dotForUser();\n    findProbeSetsForEvents(event);\n    logSpliceType(event->splice->type);\n    if(event->altPathProbeCount >= 2)\n\t{\n\tlogSpliceTypeWProbe(event->splice->type);\n\t}\n    }\nwarn(\"\");\nif(optionExists(\"outputProbeMatch\"))\n    outputProbeMatches(eventList);\nwarn(\"Reading Data Matrixes.\");\nif(probIn == NULL || intenIn == NULL)\n    errAbort(\"Must specify intensityFile and probeFile\");\nintenM = dMatrixLoad(intenIn);\nprobM = dMatrixLoad(probIn);\n\n/* If we're doing path probabilities print some headers. */\nif(pathProbabilitiesOut != NULL)\n    {\n    printCdtHeader(pathProbabilitiesOut, probM);\n    printCdtHeader(pathExpressionOut, intenM);\n    }\n\nif(optionExists(\"tissueSpecific\"))\n    initTissueSpecific(probM->colCount);\n\nif(optionExists(\"outputRatioStats\"))\n   initRatioStats(intenM);\n\nwarn(\"Filling in event data.\");\nfillInEventData(eventList, intenM, probM);\nwarn(\"Doing analysis\");\nif(optionExists(\"outputProbePvals\"))\n    outputProbePvals(eventList, probM);\ndoAnalysis(eventList, intenM, probM);\nreportEventCounts();\nreportBrainSpCounts();\nif(intronsConsCounted > 0)\n    warn(\"%d of %d introns are heavily conserved %.2f%%\",\n         intronsConserved, intronsConsCounted, (100.0 * intronsConserved)/intronsConsCounted);\nif(tissueSpecificOut)\n    reportTissueSpecificCounts(probM->colNames, probM->colCount);\nif(brainSpTableHtmlOut)\n    fprintf(brainSpTableHtmlOut, \"</table></body></html>\\n\");\nif(controlValuesVm != NULL)\n    vmWriteVals(controlValuesVm, controlValuesOut);\ncarefulClose(&brainSpTableHtmlOut);\ncarefulClose(&brainSpDnaUpOut);\ncarefulClose(&brainSpDnaDownOut);\ncarefulClose(&brainSpBedUpOut);\ncarefulClose(&brainSpBedDownOut);\ncarefulClose(&brainSpPathBedOut);\n}\n\nboolean unitTestFunct(struct unitTest *test, boolean passed,\n                      struct dyString *error, char *errorMsg)\n/* Wrapper around printing things to the error. */\n{\nassert(error);\nif(!passed)\n    dyStringPrintf(error, \"%s, \", errorMsg);\nreturn passed;\n}\n\n\nboolean testStringOccurance(struct unitTest *test)\n/* Test how many times a motif is counted. */\n{\nint count = 0;\n\nif(stringOccurance(cloneString(\"ggGG\"), cloneString(\"nnnnnggggg\")) != 2)\n    return FALSE;\n\nif(stringOccurance(cloneString(\"ggGG\"), cloneString(\"nnnnngggggnnnn\")) != 2)\n    return FALSE;\n\nif(stringOccurance(cloneString(\"ggGG\"), cloneString(\"gggggnnnn\")) != 2)\n    return FALSE;\n\nif(stringOccurance(cloneString(\"gcATG\"), cloneString(\"GcatGcattg\")) != 1)\n    return FALSE;\n\nreturn TRUE;\n}\n\nboolean testCdfChiSqP(struct unitTest *test)\n/* Test the gsl results for the chisq function. Gold values from R.*/\n{\ndouble result = 0;\nchar buff[256];\n\n/* Run the function for som test values, print to\n   a buffer to get the precision / rounding right. */\nresult = gsl_cdf_chisq_P(-2*log(.9),2);\nsafef(buff, sizeof(buff), \"%.7f\", result);\nif(differentString(buff, \"0.1000000\"))\n    return FALSE;\n\nresult = gsl_cdf_chisq_P(-2*log(.1),2);\nsafef(buff, sizeof(buff), \"%.7f\", result);\nif(differentString(buff, \"0.9000000\"))\n    return FALSE;\n\nresult = gsl_cdf_chisq_P(-2*(log(.1)+log(.9)+log(.5)),6);\nsafef(buff, sizeof(buff), \"%.7f\", result);\nif(differentString(buff, \"0.5990734\"))\n    return FALSE;\n\nresult = gsl_cdf_chisq_P(-2*(log(.8)+log(.8)),4);\nsafef(buff, sizeof(buff), \"%.8f\", result);\nif(differentString(buff, \"0.07437625\"))\n    return FALSE;\nreturn TRUE;\n}\n\nboolean testPathContains(struct unitTest *test)\n/* Test the path contains block functionality. */\n{\nstruct splice *ndr2 = ndr2CassTest();\nstruct path *skipPath = NULL, *incPath = NULL;\nstruct dyString *error = newDyString(128);\nboolean result = TRUE, currentResult = TRUE;\nskipPath = ndr2->paths;\nincPath = ndr2->paths->next;\n\nif(pathContainsIntron(ndr2, skipPath, \"chr14\", 43771385+15, 43772095-15, \"-\") != TRUE)\n    currentResult = FALSE;\nif(pathContainsIntron(ndr2, skipPath, \"chr14\", 43771385+15, 43771715-15, \"-\") != FALSE)\n    currentResult = FALSE;\nif(pathContainsIntron(ndr2, skipPath, \"chr14\", 43771727+15, 43772095-15, \"-\") != FALSE)\n    currentResult = FALSE;\nif(currentResult == FALSE)\n    {\n    dyStringPrintf(error, \"Problem with placing introns on skip path, \");\n    result = FALSE;\n    }\n\ncurrentResult = TRUE;\nif(pathContainsIntron(ndr2, incPath, \"chr14\", 43771385+15, 43772095-15, \"-\") != FALSE)\n    currentResult = FALSE;\nif(pathContainsIntron(ndr2, incPath, \"chr14\", 43771385+15, 43771715-15, \"-\") != TRUE)\n    currentResult = FALSE;\nif(pathContainsIntron(ndr2, incPath, \"chr14\", 43771727+15, 43772095-15, \"-\") != TRUE)\n    currentResult = FALSE;\nif(currentResult == FALSE)\n    {\n    dyStringPrintf(error, \"Problem with placing introns on skip path, \");\n    result = FALSE;\n    }\n\ncurrentResult = TRUE;\nif(pathContainsBlock(ndr2, incPath,  \"chr14\", 43771727, 43771727+15, \"-\", TRUE) != TRUE)\n    currentResult = FALSE;\nif(pathContainsBlock(ndr2, incPath,  \"chr14\", 43771703, 43771735, \"-\", TRUE) != TRUE)\n    currentResult = FALSE;\nif(pathContainsBlock(ndr2, skipPath,  \"chr14\", 43771703, 43771735, \"-\", TRUE) != FALSE)\n    currentResult = FALSE;\nif(currentResult == FALSE)\n    {\n    dyStringPrintf(error, \"Problem placing blocks with all bases, \");\n    result = FALSE;\n    }\n\ncurrentResult = TRUE;\nif(pathContainsBlock(ndr2, incPath,  \"chr14\", 43771727, 43771727+16, \"-\", TRUE) != FALSE)\n    currentResult = FALSE;\nif(pathContainsBlock(ndr2, incPath,  \"chr14\", 43771727, 43771727+16, \"-\", FALSE) != TRUE)\n    currentResult = FALSE;\nif(currentResult == FALSE)\n    {\n    dyStringPrintf(error, \"Problem placing blocks with not all bases, \");\n    result = FALSE;\n    }\n\ntest->errorMsg = cloneString(error->string);\ndyStringFree(&error);\nreturn result;\n}\n\nboolean testPathContainsBed(struct unitTest *test)\n/* Test to see if a path contains the right stuff. */\n{\nstruct splice *ndr2 = ndr2CassTest();\nstruct bed *bedList = ndr2BedTest(), *bed = NULL;\n/* 1 include, 2 skip, 3 include, 4 gene. */\nstruct path *skipPath = NULL, *incPath = NULL;\nboolean result = TRUE;\nstruct dyString *error = newDyString(128);\nskipPath = ndr2->paths;\nincPath = ndr2->paths->next;\n\n/* First include. */\nbed = bedList;\nif(pathContainsBed(ndr2, skipPath, bed, TRUE) != FALSE)\n    {\n    result = FALSE;\n    dyStringPrintf(error, \"Matching include bed to skip, \");\n    }\nif(pathContainsBed(ndr2, incPath, bed, TRUE) != TRUE)\n    {\n    result = FALSE;\n    dyStringPrintf(error, \"Not matching include bed to include, \");\n    }\n\n/* Skip probe set. */\nbed = bed->next;\nif(pathContainsBed(ndr2, skipPath, bed, TRUE) != TRUE)\n    {\n    result = FALSE;\n    dyStringPrintf(error, \"Not matching skip bed to skip, \");\n    }\nif(pathContainsBed(ndr2, incPath, bed, TRUE) != FALSE)\n    {\n    result = FALSE;\n    dyStringPrintf(error, \"Matching skip bed to include, \");\n    }\n\n/* Second include. */\nbed = bed->next;\nif(pathContainsBed(ndr2, skipPath, bed, TRUE) != FALSE)\n    {\n    result = FALSE;\n    dyStringPrintf(error, \"Matching 2nd include bed to skip, \");\n    }\nif(pathContainsBed(ndr2, incPath, bed, TRUE) != TRUE)\n    {\n    result = FALSE;\n    dyStringPrintf(error, \"Not matching 2nd include bed to include, \");\n    }\n\n/* Gene probe set. */\nbed = bed->next;\nif(pathContainsBed(ndr2, skipPath, bed, FALSE) != FALSE)\n    {\n    result = FALSE;\n    dyStringPrintf(error, \"Matching gene set to skip path,  \");\n    }\n\nif(pathContainsBed(ndr2, incPath, bed, FALSE) != FALSE)\n    {\n    result = FALSE;\n    dyStringPrintf(error, \"Matching gene set to include path,  \");\n    }\ntest->errorMsg = cloneString(error->string);\ndyStringFree(&error);\nreturn result;\n}\n\nstruct altEvent *setupNdr2AltEvent()\n/* Setup an ndr2 fake event for testing. */\n{\nstruct splice *splice = ndr2CassTest();\nstruct altEvent *event = NULL;\nstruct path *path = NULL;\nstruct altPath *altPath = NULL;\nstruct dMatrix *probM = ndr2BedTestMat(TRUE);\nstruct dMatrix *intenM = ndr2BedTestMat(FALSE);\ndouble expression = 0;\n\nAllocVar(event);\nevent->splice = splice;\nAllocArray(event->geneExpVals, 1);\nAllocArray(event->genePVals, 1);\nevent->geneProbeCount = 1;\nevent->altPathProbeCount = 2;\nevent->geneExpVals[0] = intenM->matrix[3];\nevent->genePVals[0] = probM->matrix[3];\n\nAllocVar(altPath);\naltPath->path = splice->paths;\naltPath->probeCount = 1;\nAllocArray(altPath->expVals, altPath->probeCount);\naltPath->expVals[0] =  intenM->matrix[1];\nAllocArray(altPath->pVals, altPath->probeCount);\naltPath->pVals[0] = probM->matrix[1];\nslAddHead(&event->altPathList, altPath);\n\nAllocVar(altPath);\naltPath->path = splice->paths->next;\naltPath->probeCount = 2;\nAllocArray(altPath->expVals, altPath->probeCount);\naltPath->expVals[0] = intenM->matrix[0];\naltPath->expVals[1] = intenM->matrix[2];\nAllocArray(altPath->pVals, altPath->probeCount);\naltPath->pVals[0] = probM->matrix[0];\naltPath->pVals[1] = probM->matrix[2];\nslAddHead(&event->altPathList, altPath);\n\nslReverse(&event->altPathList);\nreturn event;\n}\n\nboolean testAltPathProbesExpressed(struct unitTest *test)\n/* Test to see if presense abs software is calling. */\n{\nstruct altEvent *event = setupNdr2AltEvent();\nstruct dyString *error = newDyString(128);\ndouble expression = 0;\nboolean result = TRUE;\nuseMaxProbeSet = TRUE;\nif(altPathProbesExpressed(event, event->altPathList->next, 1, 0, &expression) != FALSE)\n    {\n    result = FALSE;\n    dyStringPrintf(error, \"Max probe set calling false positive, \");\n    }\nif(altPathProbesExpressed(event, event->altPathList, 0, 3, &expression) != TRUE)\n    {\n    result = FALSE;\n    dyStringPrintf(error, \"Max probe set calling positive false, \");\n    }\n\nuseMaxProbeSet = FALSE;\nuseComboProbes = TRUE;\nif(altPathProbesExpressed(event, event->altPathList->next, 1, 0, &expression) != TRUE)\n    {\n    result = FALSE;\n    dyStringPrintf(error, \"Combo probes not combining correctly, \");\n    }\ntest->errorMsg = cloneString(error->string);\ndyStringFree(&error);\nreturn result;\n}\n\nboolean sameDouble(double d1, double d2)\n/* Check to see if these are the same doubles to 6 sig digits. */\n{\nchar buff1[128], buff2[128];\nsafef(buff1, sizeof(buff1), \"%.6f\", d1);\nsafef(buff2, sizeof(buff2), \"%.6f\", d2);\nreturn sameString(buff1, buff2);\n}\n\nboolean testExpressionRatio(struct unitTest *test)\n/* Test to see if the ratios are calculated properly for expresionRatio() */\n{\nstruct altEvent *event = setupNdr2AltEvent();\nstruct dyString *error = newDyString(128);\ndouble expression = 0;\nboolean result = TRUE;\nboolean current = FALSE;\nstruct altPath *skipPath = event->altPathList;\nstruct altPath *incPath = event->altPathList->next;\ndouble tmpThresh = presThresh;\npresThresh = absThresh;\n\ncurrent = sameDouble(expressionRatio(event, skipPath, incPath, 0), 1);\nresult &= unitTestFunct(test, current, error, \"Averaging\");\n\ncurrent = sameDouble(expressionRatio(event, skipPath, incPath, 2), 2);\nresult &= unitTestFunct(test, current, error, \"Low expressed\");\n\ncurrent = sameDouble(expressionRatio(event, skipPath, incPath, 3), .5);\nresult &= unitTestFunct(test, current, error, \"Averaging\");\n\npresThresh = tmpThresh;\nreturn result;\n}\n\nboolean testBrainSpecific(struct unitTest *test)\n/* Test to see if ndr2 is brain specific (which it should be). */\n{\nstruct altEvent *event = setupNdr2AltEvent();\nboolean result = FALSE;\nint **expressed = NULL;\nint **notExpressed = NULL;\ndouble **expression = NULL;\nstruct altPath *altPath = NULL;\nint pathCount = slCount(event->altPathList);\nint pathIx = 0;\nint pathExpCount = 0;\nint i = 0;\nstruct dMatrix *probM = ndr2BedTestMat(TRUE);\nstruct dMatrix *intenM = ndr2BedTestMat(FALSE);\n/* Allocate a 2D array for expression. */\nAllocArray(expressed, pathCount);\nAllocArray(notExpressed, pathCount);\nAllocArray(expression, pathCount);\nfor(i = 0; i < pathCount; i++)\n    {\n    AllocArray(expressed[i], probM->colCount);\n    AllocArray(notExpressed[i], probM->colCount);\n    AllocArray(expression[i], intenM->colCount);\n    }\nfor(altPath = event->altPathList; altPath != NULL; altPath = altPath->next)\n    {\n    if (altPathExpressed(event, altPath, intenM, probM,\n                         expressed, notExpressed, expression, pathIx))\n        pathExpCount++;\n    pathIx++;\n    }\nresult = brainSpecific(event, altPath, 1, expressed, notExpressed, 2, probM);\nif(result != TRUE)\n    test->errorMsg = cloneString(\"Not showing brain expressed.\");\n/* Cleanup some memory. */\nfor(i = 0; i < pathCount; i++)\n    {\n    freez(&expressed[i]);\n    freez(&notExpressed[i]);\n    freez(&expression[i]);\n    }\nfreez(&notExpressed);\nfreez(&expressed);\nfreez(&expression);\nreturn result;\n}\n\nvoid initTests()\n{\nstruct unitTest *test = NULL;\n\n/* Testing stat routines. */\nAllocVar(test);\ntest->test = testCdfChiSqP;\ntest->description = \"GSL ChiSq function\";\nslAddHead(&tests, test);\n\n/* Testing motif matching. */\nAllocVar(test);\ntest->test = testStringOccurance;\ntest->description = \"Motif searching\";\nslAddHead(&tests, test);\n\n/* Testing finding blocks on paths. */\nAllocVar(test);\ntest->test = testPathContains;\ntest->description = \"Match introns and exon blocks to paths\";\nslAddHead(&tests, test);\n\n/* Testing finding blocks on paths. */\nAllocVar(test);\ntest->test = testPathContainsBed;\ntest->description = \"Match beds to paths\";\nslAddHead(&tests, test);\n\n/* Testing finding blocks on paths. */\nAllocVar(test);\ntest->test = testAltPathProbesExpressed;\ntest->description = \"Call paths as expressed or not.\";\nslAddHead(&tests, test);\n\n/* Testing expression ratio generation. */\nAllocVar(test);\ntest->test = testExpressionRatio;\ntest->description = \"Generate expression ratios.\";\nslAddHead(&tests, test);\n\n/* Testing brain specificity. */\nAllocVar(test);\ntest->test = testBrainSpecific;\ntest->description = \"Brain Specific detection.\";\nslAddHead(&tests, test);\n\nslReverse(&tests);\n}\n\nvoid runTests()\n{\nstruct unitTest *test, *testNext, *passed = NULL, *failed = NULL;\nboolean passedAll = TRUE;\nint passCount = 0, *failCount = 0;\nfor(test = tests; test != NULL; test = testNext)\n    {\n    testNext = test->next;\n    if(test->test(test) != FALSE)\n\t{\n\tpassCount++;\n\tslAddHead(&passed, test);\n\t}\n    else\n\t{\n\tslAddHead(&failed, test);\n\tpassedAll = FALSE;\n\tfailCount++;\n\t}\n    }\nif(passedAll)\n    {\n    fprintf(stdout, \"Passed all %d tests.\\n\", passCount);\n    exit(0);\n    }\nelse\n    {\n    fprintf(stdout, \"Failed tests:\\n\");\n    for(test = failed; test != NULL; test = test->next)\n\t{\n\tfprintf(stdout, \"%-40s\\tFAILED\\t%s\\n\", test->description,\n\t\ttest->errorMsg == NULL ? \"\" : test->errorMsg);\n\t}\n    exit(1);\n    }\n}\n\nvoid initCassetteBedsOut()\n{\nstruct dyString *buff = NULL;\nchar *prefix = optionVal(\"cassetteBeds\", NULL);\nassert(prefix);\nbuff = newDyString(strlen(prefix)+20);\n\ndyStringClear(buff);\ndyStringPrintf(buff, \"%s.altExpressed.bed\", prefix);\naltCassetteBedOut = mustOpen(buff->string, \"w\");\n\ndyStringClear(buff);\ndyStringPrintf(buff, \"%s.expressed.bed\", prefix);\nexpressedCassetteBedOut = mustOpen(buff->string, \"w\");\n\ndyStringClear(buff);\ndyStringPrintf(buff, \"%s.notExpressed.bed\", prefix);\nnotExpressedCassetteBedOut = mustOpen(buff->string, \"w\");\n}\n\nvoid initNotHumanCassettes()\n/* Load up cassettes that we think are notHuman. */\n{\nchar *file = optionVal(\"notHumanCassettes\", NULL);\nstruct bed *bed = NULL, *bedList = NULL;\nchar buff[256];\nnotHumanHash = newHash(10);\nassert(file);\nbedList = bedLoadAll(file);\nfor(bed = bedList; bed != NULL; bed = bed->next)\n    {\n    safef(buff, sizeof(buff), \"%s:%d-%d:%s\", bed->chrom, bed->chromStart,bed->chromEnd, bed->strand);\n    hashAdd(notHumanHash, buff, bed);\n    }\n}\n\nvoid initConservedCassettes()\n/* Load up cassettes that we think are conserved. */\n{\nchar *file = optionVal(\"conservedCassettes\", NULL);\nstruct bed *bed = NULL, *bedList = NULL;\nchar buff[256];\nconservedHash = newHash(10);\nassert(file);\nbedList = bedLoadAll(file);\nfor(bed = bedList; bed != NULL; bed = bed->next)\n    {\n    safef(buff, sizeof(buff), \"%s:%d-%d:%s\", bed->chrom, bed->chromStart,bed->chromEnd, bed->strand);\n    hashAdd(conservedHash, buff, bed);\n    }\n}\n\nvoid initConstMotifCounts()\n/* Initialize file for reporting motif counts in constitutive exons. */\n{\nint i = 0;\nconstMotifCounts = mustOpen(\"constitutiveMotifCounts.tab\", \"w\");\n/* Do the first n-1 with tabs. */\nfor(i=0; i<bindSiteCount-1; i++)\n    {\n    fprintf(constMotifCounts, \"%s-up\\t%s-down\\t\",\n\t    bindSiteArray[i]->rnaBinder, bindSiteArray[i]->rnaBinder);\n    }\n/* Last one with newline. */\nfprintf(constMotifCounts, \"%s-up\\t%s-down\\n\",\n\tbindSiteArray[i]->rnaBinder, bindSiteArray[i]->rnaBinder);\n}\n\nvoid setOptions()\n/* Set up some options. */\n{\nchar *selectedPValues = optionVal(\"selectedPValues\", NULL);\nif(optionExists(\"doTests\"))\n    {\n    initTests();\n    runTests();\n    }\npresThresh = optionFloat(\"presThresh\", .9);\npvalThresh = optionFloat(\"pValThresh\", .001);\ntissueExpThresh = optionInt(\"tissueExpThresh\", 1);\notherTissueExpThres = optionInt(\"otherTissueExpThres\", 1);\nuseMaxProbeSet = optionExists(\"useMaxProbeSet\");\ndb = optionVal(\"db\", NULL);\nbrowserName = optionVal(\"browser\", \"hgwdev-sugnet.gi.ucsc.edu\");\nuseComboProbes = optionExists(\"combinePSets\");\nuseExonBedsToo = optionExists(\"useExonBeds\");\nskipMotifControls = optionExists(\"skipMotifControls\");\n\n\nnewDb = optionVal(\"newDb\", NULL);\nif(optionExists(\"newDb\"))\n initLiftOver();\n\nif(optionExists(\"psToRefGene\"))\n    initPsToRefGene();\n\nif(optionExists(\"psToKnownGene\"))\n    initPsToKnownGene();\n\nif(optionExists(\"phastConsScores\"))\n    initPhastConsScores();\n\nif(optionExists(\"splicePVals\"))\n    initSplicePVals();\n\nif(optionExists(\"cassetteBeds\"))\n    initCassetteBedsOut();\n\nif(optionExists(\"conservedCassettes\"))\n   initConservedCassettes();\n\nif(optionExists(\"notHumanCassettes\"))\n   initNotHumanCassettes();\n\nif(optionExists(\"controlStats\"))\n    {\n    controlValuesVm = newValuesMat(1000, 15);\n    controlValuesOut = mustOpen(optionVal(\"controlStats\", NULL), \"w\");\n    }\n\nif(optionExists(\"sortScore\"))\n    {\n    initSortScore();\n    }\n\nif(selectedPValues != NULL)\n    {\n    char *selectedPValFile = optionVal(\"selectedPValFile\", NULL);\n    char buff[2048];\n\n    if(selectedPValFile == NULL)\n\terrAbort(\"Must specify a selectedPValFile when enabling selectedPValues\");\n    readSelectedList(selectedPValues);\n    pathProbabilitiesOut = mustOpen(selectedPValFile, \"w\");\n    safef(buff, sizeof(buff), \"%s.bed\", selectedPValFile);\n    pathProbabilitiesBedOut = mustOpen(buff, \"w\");\n    safef(buff, sizeof(buff), \"%s.intensity\", selectedPValFile);\n    pathExpressionOut = mustOpen(buff, \"w\");\n    }\n\nif(useMaxProbeSet)\n    warn(\"Using max value from all probe sets in a path.\");\n/* Set up the datbase. */\ndb = optionVal(\"db\", NULL);\nif(db != NULL)\n    hSetDb(db);\nelse\n    errAbort(\"Must specify database.\");\ninitBindSiteList();\n\nif (!skipMotifControls)\n    initConstMotifCounts();\nif(optionVal(\"brainSpecific\", NULL) != NULL)\n    initBrainSpecific();\n}\n\nint main(int argc, char *argv[])\n/* Everybody's favorite function... */\n{\nif(argc == 1)\n    usage();\noptionInit(&argc, argv, optionSpecs);\nif(optionExists(\"help\"))\n    usage();\nsetOptions();\naltProbes();\nreturn 0;\n}\n", "meta": {"hexsha": "a29928fbae7a53cc656fa14e8b1b903b9de53f7a", "size": 156009, "ext": "c", "lang": "C", "max_stars_repo_path": "src/hg/altSplice/affySplice/altProbes.c", "max_stars_repo_name": "andypohl/kent", "max_stars_repo_head_hexsha": "af7a004c8f3fa909cd8c2cfc2e5bea60e3421cd1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 171.0, "max_stars_repo_stars_event_min_datetime": "2015-04-22T15:16:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T20:21:53.000Z", "max_issues_repo_path": "src/hg/altSplice/affySplice/altProbes.c", "max_issues_repo_name": "andypohl/kent", "max_issues_repo_head_hexsha": "af7a004c8f3fa909cd8c2cfc2e5bea60e3421cd1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 60.0, "max_issues_repo_issues_event_min_datetime": "2016-10-03T15:15:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T15:21:52.000Z", "max_forks_repo_path": "src/hg/altSplice/affySplice/altProbes.c", "max_forks_repo_name": "andypohl/kent", "max_forks_repo_head_hexsha": "af7a004c8f3fa909cd8c2cfc2e5bea60e3421cd1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 80.0, "max_forks_repo_forks_event_min_datetime": "2015-04-16T10:39:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T16:36:30.000Z", "avg_line_length": 32.3334715026, "max_line_length": 620, "alphanum_fraction": 0.670377991, "num_tokens": 45889, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814648038985, "lm_q2_score": 0.013222823332049272, "lm_q1q2_score": 0.005738460238485909}}
{"text": "#pragma once\n\n#include <halley/utils/utils.h>\n#include <vector>\n#include <gsl/gsl>\n#include \"halley/data_structures/flat_map.h\"\n#include \"halley/maths/vector2.h\"\n#include \"halley/maths/rect.h\"\n#include \"halley/file/path.h\"\n#include <map>\n#include <unordered_map>\n#include <cstdint>\n#include <utility>\n#include <set>\n#include \"halley/data_structures/maybe.h\"\n#include \"halley/maths/colour.h\"\n#include \"halley/maths/vector4.h\"\n\nnamespace Halley\n{\n    class String;\n\n    class SerializerOptions\n    {\n    public:\n        constexpr static int maxVersion = 1;\n\n        int version = 0;\n        bool exhaustiveDictionary = false;\n        std::function< std::optional< size_t >( const String& string ) > stringToIndex;\n        std::function< const String&( size_t index ) > indexToString;\n\n        SerializerOptions() = default;\n        SerializerOptions( int version ) :\n            version( version )\n        { }\n    };\n\n    class SerializerState\n    {\n    };\n\n    class ByteSerializationBase\n    {\n    public:\n        ByteSerializationBase( SerializerOptions options ) :\n            options( std::move( options ) )\n        { }\n\n        SerializerState* setState( SerializerState* state );\n\n        template < typename T >\n        T* getState() const\n        {\n            return static_cast< T* >( state );\n        }\n\n        int getVersion() const { return version; }\n        void setVersion( int v ) { version = v; }\n\n    protected:\n        SerializerOptions options;\n\n    private:\n        SerializerState* state = nullptr;\n        int version = 0;\n    };\n\n    class Serializer : public ByteSerializationBase\n    {\n    public:\n        Serializer( SerializerOptions options );\n        explicit Serializer( gsl::span< gsl::byte > dst, SerializerOptions options );\n\n        template < typename T, typename std::enable_if< std::is_convertible< T, std::function< void( Serializer& ) > >::value, int >::type = 0 >\n        static Bytes toBytes( const T& f, SerializerOptions options = {} )\n        {\n            auto dry = Serializer( options );\n            f( dry );\n            Bytes result( dry.getSize() );\n            auto s = Serializer( gsl::as_writable_bytes( gsl::span< Halley::Byte >( result ) ), options );\n            f( s );\n            return result;\n        }\n\n        template < typename T, typename std::enable_if< !std::is_convertible< T, std::function< void( Serializer& ) > >::value, int >::type = 0 >\n        static Bytes toBytes( const T& value, SerializerOptions options = {} )\n        {\n            return toBytes( [ &value ]( Serializer& s ) { s << value; }, options );\n        }\n\n        size_t getSize() const { return size; }\n\n        Serializer& operator<<( bool val ) { return serializePod( val ); }\n        Serializer& operator<<( int8_t val ) { return serializeInteger( val ); }\n        Serializer& operator<<( uint8_t val ) { return serializeInteger( val ); }\n        Serializer& operator<<( int16_t val ) { return serializeInteger( val ); }\n        Serializer& operator<<( uint16_t val ) { return serializeInteger( val ); }\n        Serializer& operator<<( int32_t val ) { return serializeInteger( val ); }\n        Serializer& operator<<( uint32_t val ) { return serializeInteger( val ); }\n        Serializer& operator<<( int64_t val ) { return serializeInteger( val ); }\n        Serializer& operator<<( uint64_t val ) { return serializeInteger( val ); }\n        Serializer& operator<<( float val ) { return serializePod( val ); }\n        Serializer& operator<<( double val ) { return serializePod( val ); }\n\n        Serializer& operator<<( const std::string& str );\n        Serializer& operator<<( const String& str );\n        Serializer& operator<<( const Path& path );\n        Serializer& operator<<( gsl::span< const gsl::byte > span );\n        Serializer& operator<<( const Bytes& bytes );\n\n        template < typename T >\n        Serializer& operator<<( const std::vector< T >& val )\n        {\n            unsigned int sz = static_cast< unsigned int >( val.size() );\n            *this << sz;\n            for ( unsigned int i = 0; i < sz; i++ )\n            {\n                *this << val[ i ];\n            }\n            return *this;\n        }\n\n        template < typename T, typename U >\n        Serializer& operator<<( const FlatMap< T, U >& val )\n        {\n            *this << static_cast< unsigned int >( val.size() );\n            for ( auto& kv : val )\n            {\n                *this << kv.first << kv.second;\n            }\n            return *this;\n        }\n\n        template < typename T, typename U >\n        Serializer& operator<<( const std::map< T, U >& val )\n        {\n            *this << static_cast< unsigned int >( val.size() );\n            for ( auto& kv : val )\n            {\n                *this << kv.first << kv.second;\n            }\n            return *this;\n        }\n\n        template < typename T, typename U >\n        Serializer& operator<<( const std::unordered_map< T, U >& val )\n        {\n            std::map< T, U > m;\n            for ( auto& kv : val )\n            {\n                m[ kv.first ] = kv.second;\n            }\n            return ( *this << m );\n        }\n\n        template < typename T >\n        Serializer& operator<<( const std::set< T >& val )\n        {\n            unsigned int sz = static_cast< unsigned int >( val.size() );\n            *this << sz;\n            for ( auto& v : val )\n            {\n                *this << v;\n            }\n            return *this;\n        }\n\n        template < typename T >\n        Serializer& operator<<( const Vector2D< T >& val )\n        {\n            return *this << val.x << val.y;\n        }\n\n        template < typename T >\n        Serializer& operator<<( const Vector3D< T >& val )\n        {\n            return *this << val.x << val.y << val.z;\n        }\n\n        template < typename T >\n        Serializer& operator<<( const Vector4D< T >& val )\n        {\n            return *this << val.x << val.y << val.z << val.w;\n        }\n\n        template < typename T >\n        Serializer& operator<<( const Colour4< T >& val )\n        {\n            return *this << val.r << val.g << val.b << val.a;\n        }\n\n        template < typename T >\n        Serializer& operator<<( const Rect2D< T >& val )\n        {\n            return *this << val.getTopLeft() << val.getBottomRight();\n        }\n\n        template < typename T, typename U >\n        Serializer& operator<<( const std::pair< T, U >& p )\n        {\n            return *this << p.first << p.second;\n        }\n\n        template < typename T >\n        Serializer& operator<<( const std::optional< T >& p )\n        {\n            if ( p )\n            {\n                return *this << true << p.value();\n            }\n            else\n            {\n                return *this << false;\n            }\n        }\n\n        template < typename T >\n        Serializer& operator<<( const Range< T >& p )\n        {\n            return *this << p.start << p.end;\n        }\n\n        template < typename T, std::enable_if_t< std::is_enum< T >::value == true, int > = 0 >\n        Serializer& operator<<( const T& val )\n        {\n            using B = typename std::underlying_type< T >::type;\n            return *this << B( val );\n        }\n\n        template < typename T, std::enable_if_t< std::is_enum< T >::value == false, int > = 0 >\n        Serializer& operator<<( const T& val )\n        {\n            val.serialize( *this );\n            return *this;\n        }\n\n        size_t getPosition() const { return size; }\n\n    private:\n        size_t size = 0;\n        gsl::span< gsl::byte > dst;\n        bool dryRun;\n\n        template < typename T >\n        Serializer& serializePod( T val )\n        {\n            if ( !dryRun )\n            {\n                memcpy( dst.data() + size, &val, sizeof( T ) );\n            }\n            size += sizeof( T );\n            return *this;\n        }\n\n        template < typename T >\n        Serializer& serializeInteger( T val )\n        {\n            if ( options.version >= 1 )\n            {\n                // Variable-length\n                if constexpr ( std::is_signed_v< T > )\n                {\n                    serializeVariableInteger( static_cast< uint64_t >( val >= 0 ? val : -( val + 1 ) ), val < 0 );\n                }\n                else\n                {\n                    serializeVariableInteger( val, {} );\n                }\n                return *this;\n            }\n            else\n            {\n                // Fixed length\n                return serializePod( val );\n            }\n        }\n\n        void serializeVariableInteger( uint64_t val, std::optional< bool > sign );\n    };\n\n    class Deserializer : public ByteSerializationBase\n    {\n    public:\n        Deserializer( gsl::span< const gsl::byte > src, SerializerOptions options = {} );\n        Deserializer( const Bytes& src, SerializerOptions options = {} );\n\n        template < typename T >\n        static T fromBytes( const Bytes& src, SerializerOptions options = {} )\n        {\n            T result;\n            Deserializer s( src, std::move( options ) );\n            s >> result;\n            return result;\n        }\n\n        template < typename T >\n        static T fromBytes( gsl::span< const gsl::byte > src, SerializerOptions options = {} )\n        {\n            T result;\n            Deserializer s( src, std::move( options ) );\n            s >> result;\n            return result;\n        }\n\n        template < typename T >\n        static void fromBytes( T& target, const Bytes& src, SerializerOptions options = {} )\n        {\n            Deserializer s( src, std::move( options ) );\n            s >> target;\n        }\n\n        template < typename T >\n        static void fromBytes( T& target, gsl::span< const gsl::byte > src, SerializerOptions options = {} )\n        {\n            Deserializer s( src, std::move( options ) );\n            s >> target;\n        }\n\n        Deserializer& operator>>( bool& val ) { return deserializePod( val ); }\n        Deserializer& operator>>( int8_t& val ) { return deserializeInteger( val ); }\n        Deserializer& operator>>( uint8_t& val ) { return deserializeInteger( val ); }\n        Deserializer& operator>>( int16_t& val ) { return deserializeInteger( val ); }\n        Deserializer& operator>>( uint16_t& val ) { return deserializeInteger( val ); }\n        Deserializer& operator>>( int32_t& val ) { return deserializeInteger( val ); }\n        Deserializer& operator>>( uint32_t& val ) { return deserializeInteger( val ); }\n        Deserializer& operator>>( int64_t& val ) { return deserializeInteger( val ); }\n        Deserializer& operator>>( uint64_t& val ) { return deserializeInteger( val ); }\n        Deserializer& operator>>( float& val ) { return deserializePod( val ); }\n        Deserializer& operator>>( double& val ) { return deserializePod( val ); }\n\n        Deserializer& operator>>( std::string& str );\n        Deserializer& operator>>( String& str );\n        Deserializer& operator>>( Path& p );\n        Deserializer& operator>>( gsl::span< gsl::byte > span );\n        Deserializer& operator>>( Bytes& bytes );\n\n        template < typename T >\n        Deserializer& operator>>( std::vector< T >& val )\n        {\n            unsigned int sz;\n            *this >> sz;\n            ensureSufficientBytesRemaining( sz ); // Expect at least one byte per vector entry\n\n            val.clear();\n            val.reserve( sz );\n            for ( unsigned int i = 0; i < sz; i++ )\n            {\n                val.push_back( T() );\n                *this >> val[ i ];\n            }\n            return *this;\n        }\n\n        template < typename T, typename U >\n        Deserializer& operator>>( FlatMap< T, U >& val )\n        {\n            unsigned int sz;\n            *this >> sz;\n            ensureSufficientBytesRemaining( sz * 2 ); // Expect at least two bytes per map entry\n\n            std::vector< std::pair< T, U > > tmpData( sz );\n            for ( unsigned int i = 0; i < sz; i++ )\n            {\n                *this >> tmpData[ i ].first >> tmpData[ i ].second;\n            }\n            val = FlatMap< T, U >( boost::container::ordered_unique_range_t(), tmpData.begin(), tmpData.end() );\n            return *this;\n        }\n\n        template < typename T, typename U >\n        Deserializer& operator>>( std::map< T, U >& val )\n        {\n            unsigned int sz;\n            *this >> sz;\n            ensureSufficientBytesRemaining( size_t( sz ) * 2 ); // Expect at least two bytes per map entry\n\n            for ( unsigned int i = 0; i < sz; i++ )\n            {\n                T key;\n                U value;\n                *this >> key >> value;\n                val[ key ] = std::move( value );\n            }\n            return *this;\n        }\n\n        template < typename T, typename U >\n        Deserializer& operator>>( std::unordered_map< T, U >& val )\n        {\n            unsigned int sz;\n            *this >> sz;\n            ensureSufficientBytesRemaining( sz * 2 ); // Expect at least two bytes per map entry\n\n            for ( unsigned int i = 0; i < sz; i++ )\n            {\n                T key;\n                U value;\n                *this >> key >> value;\n                val[ key ] = std::move( value );\n            }\n            return *this;\n        }\n\n        template < typename T >\n        Deserializer& operator>>( std::set< T >& val )\n        {\n            unsigned int sz;\n            *this >> sz;\n            ensureSufficientBytesRemaining( sz ); // Expect at least one byte per set entry\n\n            val.clear();\n            for ( unsigned int i = 0; i < sz; i++ )\n            {\n                T v;\n                *this >> v;\n                val.insert( std::move( v ) );\n            }\n            return *this;\n        }\n\n        template < typename T >\n        Deserializer& operator>>( Vector2D< T >& val )\n        {\n            *this >> val.x;\n            *this >> val.y;\n            return *this;\n        }\n\n        template < typename T >\n        Deserializer& operator>>( Vector3D< T >& val )\n        {\n            *this >> val.x;\n            *this >> val.y;\n            *this >> val.z;\n            return *this;\n        }\n\n        template < typename T >\n        Deserializer& operator>>( Vector4D< T >& val )\n        {\n            *this >> val.x;\n            *this >> val.y;\n            *this >> val.z;\n            *this >> val.w;\n            return *this;\n        }\n\n        template < typename T >\n        Deserializer& operator>>( Colour4< T >& val )\n        {\n            *this >> val.r;\n            *this >> val.g;\n            *this >> val.b;\n            *this >> val.a;\n            return *this;\n        }\n\n        template < typename T >\n        Deserializer& operator>>( Rect2D< T >& val )\n        {\n            Vector2D< T > p1, p2;\n            *this >> p1;\n            *this >> p2;\n            val = Rect2D< T >( p1, p2 );\n            return *this;\n        }\n\n        template < typename T, typename U >\n        Deserializer& operator>>( std::pair< T, U >& p )\n        {\n            return *this >> p.first >> p.second;\n        }\n\n        template < typename T >\n        Deserializer& operator>>( Range< T >& p )\n        {\n            return *this >> p.start >> p.end;\n        }\n\n        template < typename T >\n        Deserializer& operator>>( std::optional< T >& p )\n        {\n            bool present;\n            *this >> present;\n            if ( present )\n            {\n                T tmp;\n                *this >> tmp;\n                p = tmp;\n            }\n            else\n            {\n                p = std::optional< T >();\n            }\n            return *this;\n        }\n\n        template < typename T, std::enable_if_t< std::is_enum< T >::value == true, int > = 0 >\n        Deserializer& operator>>( T& val )\n        {\n            typename std::underlying_type< T >::type tmp;\n            *this >> tmp;\n            val = T( tmp );\n            return *this;\n        }\n\n        template < typename T, std::enable_if_t< std::is_enum< T >::value == false, int > = 0 >\n        Deserializer& operator>>( T& val )\n        {\n            val.deserialize( *this );\n            return *this;\n        }\n\n        template < typename T >\n        void peek( T& val )\n        {\n            const auto oldPos = pos;\n            *this >> val;\n            pos = oldPos;\n        }\n\n        size_t getPosition() const { return pos; }\n\n    private:\n        size_t pos = 0;\n        gsl::span< const gsl::byte > src;\n\n        template < typename T >\n        Deserializer& deserializePod( T& val )\n        {\n            ensureSufficientBytesRemaining( sizeof( T ) );\n            memcpy( &val, src.data() + pos, sizeof( T ) );\n            pos += sizeof( T );\n            return *this;\n        }\n\n        template < typename T >\n        Deserializer& deserializeInteger( T& val )\n        {\n            if ( options.version >= 1 )\n            {\n                // Variable-length\n                bool sign;\n                uint64_t temp;\n                deserializeVariableInteger( temp, sign, std::is_signed_v< T > );\n                if ( sign )\n                {\n                    int64_t signedTemp = -int64_t( temp ) - 1;\n                    val = static_cast< T >( signedTemp );\n                }\n                else\n                {\n                    val = static_cast< T >( temp );\n                }\n                return *this;\n            }\n            else\n            {\n                // Fixed length\n                return deserializePod( val );\n            }\n        }\n\n        void deserializeVariableInteger( uint64_t& val, bool& sign, bool isSigned );\n\n        void ensureSufficientBytesRemaining( size_t bytes );\n        size_t getBytesRemaining() const;\n    };\n} // namespace Halley\n", "meta": {"hexsha": "608e674d5d353383cae4a95a82d71e75fd7a1701", "size": 17725, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engine/utils/include/halley/bytes/byte_serializer.h", "max_stars_repo_name": "chidddy/halley", "max_stars_repo_head_hexsha": "f828b74a6bbe7f172a7dba84e72429d3163bd61c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/engine/utils/include/halley/bytes/byte_serializer.h", "max_issues_repo_name": "chidddy/halley", "max_issues_repo_head_hexsha": "f828b74a6bbe7f172a7dba84e72429d3163bd61c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engine/utils/include/halley/bytes/byte_serializer.h", "max_forks_repo_name": "chidddy/halley", "max_forks_repo_head_hexsha": "f828b74a6bbe7f172a7dba84e72429d3163bd61c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0420315236, "max_line_length": 145, "alphanum_fraction": 0.4811283498, "num_tokens": 3936, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24220563966531902, "lm_q2_score": 0.023689470868576642, "lm_q1q2_score": 0.005737723445056546}}
{"text": "#pragma once\n\n#include <imageview/IsPixelFormat.h>\n#include <imageview/internal/ImageViewStorage.h>\n\n#include <gsl/span>\n\nnamespace imageview {\nnamespace detail {\n\ntemplate <class PixelFormat>\nclass PixelRef {\n public:\n  static_assert(IsPixelFormat<PixelFormat>::value, \"Not a PixelFormat.\");\n\n  using color_type = typename PixelFormat::color_type;\n\n  constexpr PixelRef(gsl::span<std::byte, PixelFormat::kBytesPerPixel> pixel_data,\n                     std::reference_wrapper<const PixelFormat> pixel_format);\n\n  constexpr PixelRef(const PixelRef& other) = default;\n  constexpr PixelRef(PixelRef&&) = default;\n  ~PixelRef() = default;\n\n  // Implicit conversion to color_type.\n  // \\return the color of the referenced pixel.\n  constexpr operator color_type() const;\n\n  // Assigns the specified color to the referenced pixel.\n  // \\param color - color to assign.\n  // \\return *this.\n  constexpr PixelRef& operator=(const color_type& color);\n\n  // Assigns the specified color to the referenced pixel.\n  // Note: PixelRef has reference semantics: copy and move assignment operators change the value of the\n  // referenced pixel rather than PixelRef object itself.\n  constexpr PixelRef& operator=(const PixelRef& other);\n  constexpr PixelRef& operator=(PixelRef&& other);\n\n private:\n  // TODO: store PixelFormat by reference if it's not eligible for empty base optimization,\n  // otherwise by value (as an empty base).\n  detail::ImageViewStorage<PixelFormat, true> storage_;\n};\n\ntemplate <class PixelFormat>\nconstexpr PixelRef<PixelFormat>::PixelRef(gsl::span<std::byte, PixelFormat::kBytesPerPixel> pixel_data,\n                                          std::reference_wrapper<const PixelFormat> pixel_format)\n    : storage_(pixel_data.data(), pixel_format.get()) {}\n\ntemplate <class PixelFormat>\nconstexpr PixelRef<PixelFormat>::operator color_type() const {\n  constexpr std::size_t kBytesPerPixel = PixelFormat::kBytesPerPixel;\n  const gsl::span<const std::byte, kBytesPerPixel> pixel_data(storage_.data_, kBytesPerPixel);\n  return storage_.pixelFormat().read(pixel_data);\n}\n\ntemplate <class PixelFormat>\nconstexpr PixelRef<PixelFormat>& PixelRef<PixelFormat>::operator=(const color_type& color) {\n  constexpr std::size_t kBytesPerPixel = PixelFormat::kBytesPerPixel;\n  const gsl::span<std::byte, kBytesPerPixel> pixel_data(storage_.data_, kBytesPerPixel);\n  storage_.pixelFormat().write(color, pixel_data);\n  return *this;\n}\n\ntemplate <class PixelFormat>\nconstexpr PixelRef<PixelFormat>& PixelRef<PixelFormat>::operator=(const PixelRef& other) {\n  // TODO: In theory, we could just memcpy() the binary data. However, if PixelFormat is stateful,\n  // and the state of our PixelFormat differs from the state of @other, then simply copying the binary\n  // data might lead to the wrong result.\n  // Possible workaround: add a constexpr if for the case when PixelFormat is an empty class.\n  return *this = static_cast<color_type>(other);\n}\n\ntemplate <class PixelFormat>\nconstexpr PixelRef<PixelFormat>& PixelRef<PixelFormat>::operator=(PixelRef&& other) {\n  return *this = static_cast<color_type>(other);\n}\n\n}  // namespace detail\n}  // namespace imageview\n", "meta": {"hexsha": "6c6df690933091c37b2ce1af2927f3f7bf403fce", "size": 3151, "ext": "h", "lang": "C", "max_stars_repo_path": "include/imageview/internal/PixelRef.h", "max_stars_repo_name": "alexanderbelous/imageview", "max_stars_repo_head_hexsha": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/imageview/internal/PixelRef.h", "max_issues_repo_name": "alexanderbelous/imageview", "max_issues_repo_head_hexsha": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/imageview/internal/PixelRef.h", "max_forks_repo_name": "alexanderbelous/imageview", "max_forks_repo_head_hexsha": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4268292683, "max_line_length": 103, "alphanum_fraction": 0.7483338623, "num_tokens": 707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1732882144682526, "lm_q2_score": 0.03308597576681318, "lm_q1q2_score": 0.0057334096645709305}}
{"text": "#pragma once\n\n#include <imageview/IsPixelFormat.h>\n#include <imageview/internal/ImageViewIterator.h>\n#include <imageview/internal/ImageViewStorage.h>\n#include <imageview/internal/PixelRef.h>\n\n#include <gsl/assert>\n#include <gsl/span>\n\n#include <cstddef>\n#include <stdexcept>\n\nnamespace imageview {\n\ntemplate <class PixelFormat, bool Mutable = false>\nclass ImageRowView {\n public:\n  static_assert(IsPixelFormat<PixelFormat>::value, \"Not a PixelFormat.\");\n\n  using byte_type = std::conditional_t<Mutable, std::byte, const std::byte>;\n  using value_type = typename PixelFormat::color_type;\n  // TODO: consider using 'const value_type' instead of 'value_type' for immutable views.\n  using reference = std::conditional_t<Mutable, detail::PixelRef<PixelFormat>, value_type>;\n\n  // Constant LegacyInputIterator whose value_type is @value_type. The type satisfies all\n  // requirements of LegacyRandomAccessIterator except the multipass guarantee: for dereferenceable iterators a and b\n  // with a == b, there is no requirement that *a and *b are bound to the same object.\n  using const_iterator = detail::ImageViewIterator<PixelFormat, false>;\n  using iterator = detail::ImageViewIterator<PixelFormat, Mutable>;\n\n  // Constructs an empty view.\n  // This constructor is only available if PixelFormat is default-constructible.\n  template <class Enable = std::enable_if_t<std::is_default_constructible_v<PixelFormat>>>\n  constexpr ImageRowView() noexcept(noexcept(std::is_nothrow_default_constructible_v<PixelFormat>)){};\n\n  // Constructs an empty view.\n  // \\param pixel_format - instance of PixelFormat to use.\n  constexpr explicit ImageRowView(const PixelFormat& pixel_format) noexcept(\n      noexcept(std::is_nothrow_copy_constructible_v<PixelFormat>));\n\n  // Constructs an empty view.\n  // \\param pixel_format - instance of PixelFormat to use.\n  constexpr explicit ImageRowView(PixelFormat&& pixel_format) noexcept(\n      noexcept(std::is_nothrow_move_constructible_v<PixelFormat>));\n\n  // Constructs a flat view into the given bitmap.\n  // This constructor is only available if PixelFormat is default-constructible.\n  // \\param data - bitmap data.\n  // \\param width - the number of pixels in the bitmap.\n  //\n  // Expects(data.size() == width * PixelFormat::kBytesPerPixel)\n  template <class Enable = std::enable_if_t<std::is_default_constructible_v<PixelFormat>>>\n  constexpr ImageRowView(gsl::span<byte_type> data,\n                         std::size_t width) noexcept(noexcept(std::is_nothrow_default_constructible_v<PixelFormat>));\n\n  // Constructs a flat view into the given bitmap.\n  // \\param data - bitmap data.\n  // \\param width - the number of pixels in the bitmap.\n  // \\param pixel_format - instance of PixelFormat to use.\n  //\n  // Expects(data.size() == width * PixelFormat::kBytesPerPixel)\n  constexpr ImageRowView(gsl::span<byte_type> data, std::size_t width, const PixelFormat& pixel_format) noexcept(\n      noexcept(std::is_nothrow_copy_constructible_v<PixelFormat>));\n\n  // Constructs a flat view into the given bitmap.\n  // \\param data - bitmap data.\n  // \\param width - the number of pixels in the bitmap.\n  // \\param pixel_format - instance of PixelFormat to use.\n  //\n  // Expects(data.size() == width * PixelFormat::kBytesPerPixel)\n  constexpr ImageRowView(gsl::span<byte_type> data, std::size_t width, PixelFormat&& pixel_format) noexcept(\n      noexcept(std::is_nothrow_move_constructible_v<PixelFormat>));\n\n  // Construct a read-only view from a mutable view.\n  template <class Enable = std::enable_if_t<!Mutable>>\n  constexpr ImageRowView(ImageRowView<PixelFormat, !Mutable> row_view);\n\n  // Returns the pixel format used by this image.\n  constexpr const PixelFormat& pixelFormat() const noexcept;\n\n  // Returns the bitmap data.\n  constexpr gsl::span<byte_type> data() const noexcept;\n\n  // Returns the total number of pixels in this view.\n  constexpr std::size_t size() const noexcept;\n\n  // Returns true if the view is empty (i.e. has 0 pixels), false otherwise.\n  constexpr bool empty() const noexcept;\n\n  // Returns the size of the referenced bitmap in bytes, i.e.\n  //   size() * PixelFormat::kBytesPerPixel\n  constexpr std::size_t size_bytes() const noexcept;\n\n  // Returns an iterator to the first pixel.\n  constexpr iterator begin() const;\n\n  // Returns a const iterator to the first pixel.\n  constexpr const_iterator cbegin() const;\n\n  // Returns an iterator past the last pixel.\n  constexpr iterator end() const;\n\n  // Returns a const iterator past the last pixel.\n  constexpr const_iterator cend() const;\n\n  // Returns the color of the specified pixel.\n  // \\param index - 0-based index of the pixel. No bounds checking is performed - the behavior is undefined if @index is\n  // outside [0; size()).\n  constexpr reference operator[](std::size_t index) const;\n\n  // Returns the color of the specified pixel.\n  // \\param index - 0-based index of the pixel.\n  // \\throw std::out_of_range if @index is outside [0; size()).\n  constexpr reference at(std::size_t index) const;\n\n private:\n  detail::ImageViewStorage<PixelFormat, Mutable> storage_;\n  std::size_t width_ = 0;\n};\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr ImageRowView<PixelFormat, Mutable>::ImageRowView(const PixelFormat& pixel_format) noexcept(\n    noexcept(std::is_nothrow_copy_constructible_v<PixelFormat>))\n    : storage_(nullptr, pixel_format) {}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr ImageRowView<PixelFormat, Mutable>::ImageRowView(PixelFormat&& pixel_format) noexcept(\n    noexcept(std::is_nothrow_move_constructible_v<PixelFormat>))\n    : storage_(nullptr, std::move(pixel_format)) {}\n\ntemplate <class PixelFormat, bool Mutable>\ntemplate <class Enable>\nconstexpr ImageRowView<PixelFormat, Mutable>::ImageRowView(gsl::span<byte_type> data, std::size_t width) noexcept(\n    noexcept(std::is_nothrow_default_constructible_v<PixelFormat>))\n    : storage_(data.data()), width_(width) {\n  Expects(data.size() == width * PixelFormat::kBytesPerPixel);\n}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr ImageRowView<PixelFormat, Mutable>::ImageRowView(\n    gsl::span<byte_type> data, std::size_t width,\n    const PixelFormat& pixel_format) noexcept(noexcept(std::is_nothrow_copy_constructible_v<PixelFormat>))\n    : storage_(data.data(), pixel_format), width_(width) {\n  Expects(data.size() == width * PixelFormat::kBytesPerPixel);\n}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr ImageRowView<PixelFormat, Mutable>::ImageRowView(\n    gsl::span<byte_type> data, std::size_t width,\n    PixelFormat&& pixel_format) noexcept(noexcept(std::is_nothrow_move_constructible_v<PixelFormat>))\n    : storage_(data.data(), std::move(pixel_format)), width_(width) {\n  Expects(data.size() == width * PixelFormat::kBytesPerPixel);\n}\n\ntemplate <class PixelFormat, bool Mutable>\ntemplate <class Enable>\nconstexpr ImageRowView<PixelFormat, Mutable>::ImageRowView(ImageRowView<PixelFormat, !Mutable> row_view)\n    : ImageRowView(row_view.data(), row_view.size(), row_view.pixelFormat()) {}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr const PixelFormat& ImageRowView<PixelFormat, Mutable>::pixelFormat() const noexcept {\n  return storage_.pixelFormat();\n}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr auto ImageRowView<PixelFormat, Mutable>::data() const noexcept -> gsl::span<byte_type> {\n  return gsl::span<byte_type>(storage_.data(), size_bytes());\n}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr std::size_t ImageRowView<PixelFormat, Mutable>::size() const noexcept {\n  return width_;\n}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr bool ImageRowView<PixelFormat, Mutable>::empty() const noexcept {\n  return width_ == 0;\n}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr std::size_t ImageRowView<PixelFormat, Mutable>::size_bytes() const noexcept {\n  return width_ * PixelFormat::kBytesPerPixel;\n}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr auto ImageRowView<PixelFormat, Mutable>::begin() const -> iterator {\n  return iterator(storage_.data_, storage_.pixelFormat());\n}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr auto ImageRowView<PixelFormat, Mutable>::cbegin() const -> const_iterator {\n  return const_iterator(storage_.data_, storage_.pixelFormat());\n}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr auto ImageRowView<PixelFormat, Mutable>::end() const -> iterator {\n  return iterator(storage_.data_ + width_ * PixelFormat::kBytesPerPixel, storage_.pixelFormat());\n}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr auto ImageRowView<PixelFormat, Mutable>::cend() const -> const_iterator {\n  return const_iterator(storage_.data_ + width_ * PixelFormat::kBytesPerPixel, storage_.pixelFormat());\n}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr auto ImageRowView<PixelFormat, Mutable>::operator[](std::size_t index) const -> reference {\n  const gsl::span<byte_type, PixelFormat::kBytesPerPixel> pixel_data(\n      storage_.data() + index * PixelFormat::kBytesPerPixel, PixelFormat::kBytesPerPixel);\n  if constexpr (Mutable) {\n    return detail::PixelRef<PixelFormat>(pixel_data, pixelFormat());\n  } else {\n    return pixelFormat().read(pixel_data);\n  }\n}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr auto ImageRowView<PixelFormat, Mutable>::at(std::size_t index) const -> reference {\n  if (index >= width_) {\n    throw std::out_of_range(\"ImageRowView::at(): attempting to access an element out of range.\");\n  }\n  return (*this)[index];\n}\n\n}  // namespace imageview\n", "meta": {"hexsha": "9f907f325e53c63937e60e258efca460dc74bfac", "size": 9473, "ext": "h", "lang": "C", "max_stars_repo_path": "include/imageview/ImageRowView.h", "max_stars_repo_name": "alexanderbelous/imageview", "max_stars_repo_head_hexsha": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/imageview/ImageRowView.h", "max_issues_repo_name": "alexanderbelous/imageview", "max_issues_repo_head_hexsha": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/imageview/ImageRowView.h", "max_forks_repo_name": "alexanderbelous/imageview", "max_forks_repo_head_hexsha": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.9159292035, "max_line_length": 120, "alphanum_fraction": 0.753087723, "num_tokens": 2184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1895210821742346, "lm_q2_score": 0.030214586739922344, "lm_q1q2_score": 0.005726301176397362}}
{"text": "#pragma once\n\n#include <d3d11.h>\n#include <DirectXMath.h>\n#include <map>\n#include <gsl\\gsl>\n#include \"DrawableGameComponent.h\"\n#include \"GaussianBlur.h\"\n#include \"FullScreenRenderTarget.h\"\n#include \"FullScreenQuad.h\"\n#include <winrt\\Windows.Foundation.h>\n\nnamespace Library\n{\n\tclass FullScreenQuadMaterial;\n\n\tstruct BloomSettings\n\t{\n\t\tfloat BloomThreshold{ 0.45f };\n\t\tfloat BlurAmount{ 2.0f };\n\t\tfloat BloomIntensity{ 1.25f };\n\t\tfloat BloomSaturation{ 1.0f };\n\t\tfloat SceneIntensity{ 1.0f };\n\t\tfloat SceneSaturation{ 1.0f };\n\t};\n\n\tenum class BloomDrawModes\n\t{\n\t\tNormal = 0,\n\t\tGlowMap,\n\t\tBlurredGlowMap,\n\t\tEnd\n\t};\n\n\tclass Bloom final : public DrawableGameComponent\n\t{\n\t\tRTTI_DECLARATIONS(Bloom, DrawableGameComponent)\n\n\tpublic:\n\t\tBloom(Game& game, const BloomSettings& bloomSettings = DefaultBloomSettings);\n\t\tBloom(const Bloom&) = delete;\n\t\tBloom(Bloom&&) = default;\n\t\tBloom& operator=(const Bloom&) = delete;\n\t\tBloom& operator=(Bloom&&) = default;\n\t\t~Bloom() = default;\n\n\t\tID3D11ShaderResourceView* SceneTexture() const;\n\t\tvoid SetSceneTexture(winrt::com_ptr<ID3D11ShaderResourceView> sceneTexture);\n\n\t\tconst BloomSettings& GetBloomSettings() const;\n\t\tvoid SetBloomSettings(const BloomSettings& bloomSettings);\n\n\t\tBloomDrawModes DrawMode() const;\n\t\tconst std::string& DrawModeString() const;\n\t\tvoid SetDrawMode(BloomDrawModes drawMode);\n\t\t\n\t\tvirtual void Initialize() override;\n\t\tvirtual void Draw(const GameTime& gameTime) override;\n\n\t\tinline static const BloomSettings DefaultBloomSettings{ 0.45f, 2.0f, 1.25f, 1.0f, 1.0f, 1.0f };\n\n\tprivate:\n\t\tstatic const std::map<BloomDrawModes, std::string> DrawModeDisplayNames;\n\n\t\tstruct PixelCBufferPerObject\n\t\t{\n\t\t\tfloat BloomThreshold;\n\t\t\tfloat BloomIntensity;\n\t\t\tfloat BloomSaturation;\n\t\t\tfloat SceneIntensity;\n\t\t\tfloat SceneSaturation;\n\t\t\tDirectX::XMFLOAT3 Padding;\n\n\t\t\tPixelCBufferPerObject(const BloomSettings& bloomSettings) :\n\t\t\t\tBloomThreshold(bloomSettings.BloomThreshold), BloomIntensity(bloomSettings.BloomIntensity),\n\t\t\t\tBloomSaturation(bloomSettings.BloomSaturation), SceneIntensity(bloomSettings.SceneIntensity),\n\t\t\t\tSceneSaturation(bloomSettings.SceneSaturation), Padding()\n\t\t\t{\n\t\t\t}\n\n\t\t\tPixelCBufferPerObject& operator=(const BloomSettings& bloomSettings)\n\t\t\t{\n\t\t\t\tBloomThreshold = bloomSettings.BloomThreshold;\n\t\t\t\tBloomIntensity = bloomSettings.BloomIntensity;\n\t\t\t\tBloomSaturation = bloomSettings.BloomSaturation;\n\t\t\t\tSceneIntensity = bloomSettings.SceneIntensity;\n\t\t\t\tSceneSaturation = bloomSettings.SceneSaturation;\n\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t};\n\n\t\tenum class BloomShaderClass\n\t\t{\n\t\t\tExtract = 0,\n\t\t\tComposite,\n\t\t\tNoBloom\n\t\t};\n\n\t\tvoid DrawNormal(const GameTime& gameTime);\n\t\tvoid DrawGlowMap(const GameTime& gameTime);\n\t\tvoid DrawBlurredGlowMap(const GameTime& gameTime);\n\n\t\tFullScreenQuad mFullScreenQuad;\n\t\tFullScreenRenderTarget mRenderTarget;\n\t\tGaussianBlur mGaussianBlur;\n\t\twinrt::com_ptr<ID3D11ShaderResourceView> mSceneTexture;\n\t\twinrt::com_ptr<ID3D11Buffer> mPixelCBufferPerObject;\n\t\tPixelCBufferPerObject mPixelCBufferPerObjectData;\n\t\tBloomDrawModes mDrawMode{ BloomDrawModes::Normal };\n\t\tstd::map<BloomDrawModes, std::function<void(const GameTime& gameTime)>> mDrawFunctions;\n\t\tstd::map<BloomShaderClass, winrt::com_ptr<ID3D11ClassInstance>> mShaderClassInstances;\n\t\tBloomSettings mBloomSettings;\n\t};\n}", "meta": {"hexsha": "5357e22958712a83524cd67b5ede590ca68c114f", "size": 3275, "ext": "h", "lang": "C", "max_stars_repo_path": "source/Library.Shared/Bloom.h", "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/Library.Shared/Bloom.h", "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/Library.Shared/Bloom.h", "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4782608696, "max_line_length": 97, "alphanum_fraction": 0.7661068702, "num_tokens": 895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2720245510940225, "lm_q2_score": 0.020964242576721838, "lm_q1q2_score": 0.0057027886759589514}}
{"text": "#ifndef PROTO_H_\n#define PROTO_H_\n\n#define _DEFAULT_SOURCE 1\n\n/** PROTO SETTINGS **/\n#define PRECISION 2\n#define MAX_LINE_LENGTH 9046\n#define USE_CBLAS\n#define USE_LAPACK\n/* #define USE_CERES */\n#define USE_STB_IMAGE\n\n#define WARN_UNUSED __attribute__((warn_unused_result))\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <string.h>\n#include <math.h>\n#include <time.h>\n#include <unistd.h>\n#include <dirent.h>\n#include <assert.h>\n#include <sys/time.h>\n\n#include <errno.h>\n#include <netdb.h>\n#include <netinet/in.h>\n#include <arpa/inet.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <sys/poll.h>\n\n#ifdef USE_CBLAS\n#include <cblas.h>\n#endif\n\n#ifdef USE_LAPACK\n#include <lapacke.h>\n#endif\n\n#ifdef USE_CERES\n#include <ceres/c_api.h>\n#endif\n\n/******************************************************************************\n * MACROS\n ******************************************************************************/\n\n/**\n * Mark variable unused.\n * @param[in] expr Variable to mark as unused\n */\n#define UNUSED(expr)                                                           \\\n  do {                                                                         \\\n    (void) (expr);                                                             \\\n  } while (0)\n\n/**\n * Check if condition is satisfied.\n *\n * If the condition is not satisfied a message M will be logged and a goto\n * error is called.\n *\n * @param[in] A Condition to be checked\n * @param[in] M Error message\n * @param[in] ... Varadic arguments for error message\n */\n#define CHECK(A, M, ...)                                                       \\\n  if (!(A)) {                                                                  \\\n    LOG_ERROR(M, ##__VA_ARGS__);                                               \\\n    goto error;                                                                \\\n  }\n\n/******************************************************************************\n * LOGGING\n ******************************************************************************/\n\n/** Terminal ANSI colors */\n#define KRED \"\\x1B[1;31m\"\n#define KGRN \"\\x1B[1;32m\"\n#define KYEL \"\\x1B[1;33m\"\n#define KBLU \"\\x1B[1;34m\"\n#define KMAG \"\\x1B[1;35m\"\n#define KCYN \"\\x1B[1;36m\"\n#define KWHT \"\\x1B[1;37m\"\n#define KNRM \"\\x1B[1;0m\"\n\n/** Macro function that returns the caller's filename */\n#define __FILENAME__                                                           \\\n  (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__)\n\n/**\n * Debug\n * @param[in] M Message\n * @param[in] ... Varadic arguments\n */\n#ifdef NDEBUG\n#define DEBUG(M, ...)\n#else\n#define DEBUG(M, ...) fprintf(stdout, \"[DEBUG] \" M \"\\n\", ##__VA_ARGS__)\n#endif\n\n/**\n * Log info\n * @param[in] M Message\n * @param[in] ... Varadic arguments\n */\n#define LOG_INFO(M, ...)                                                       \\\n  fprintf(stderr,                                                              \\\n          \"[INFO] [%s:%d] \" M \"\\n\",                                            \\\n          __FILENAME__,                                                        \\\n          __LINE__,                                                            \\\n          ##__VA_ARGS__)\n\n/**\n * Log error\n * @param[in] M Message\n * @param[in] ... Varadic arguments\n */\n#define LOG_ERROR(M, ...)                                                      \\\n  fprintf(stderr,                                                              \\\n          KRED \"[ERROR] [%s:%d] \" M KNRM \"\\n\",                                 \\\n          __FILENAME__,                                                        \\\n          __LINE__,                                                            \\\n          ##__VA_ARGS__)\n\n/**\n * Log warn\n * @param[in] M Message\n * @param[in] ... Varadic arguments\n */\n#define LOG_WARN(M, ...)                                                       \\\n  fprintf(stderr,                                                              \\\n          KYEL \"[WARN] [%s:%d] \" M KNRM \"\\n\",                                  \\\n          __FILENAME__,                                                        \\\n          __LINE__,                                                            \\\n          ##__VA_ARGS__)\n\n/**\n * Fatal\n *\n * @param[in] M Message\n * @param[in] ... Varadic arguments\n */\n#define FATAL(M, ...)                                                          \\\n  fprintf(stdout,                                                              \\\n          KRED \"[FATAL] [%s:%d] \" M KNRM \"\\n\",                                 \\\n          __FILENAME__,                                                        \\\n          __LINE__,                                                            \\\n          ##__VA_ARGS__);                                                      \\\n  exit(-1)\n\n/******************************************************************************\n * FILESYSTEM\n ******************************************************************************/\n\nvoid path_file_name(const char *path, char *fname);\nvoid path_file_ext(const char *path, char *fext);\nvoid path_dir_name(const char *path, char *dir_name);\nchar *path_join(const char *x, const char *y);\nchar **list_files(const char *path, int *nb_files);\nvoid list_files_free(char **data, const int n);\nchar *file_read(const char *fp);\nvoid skip_line(FILE *fp);\nint file_exists(const char *fp);\nint file_rows(const char *fp);\nint file_copy(const char *src, const char *dest);\n\n/******************************************************************************\n * DATA\n ******************************************************************************/\n\n#if PRECISION == 1\ntypedef float real_t;\n#elif PRECISION == 2\ntypedef double real_t;\n#else\n#error \"Precision not defined!\"\n#endif\n\nsize_t string_copy(char *dst, const char *src);\nvoid string_cat(char *dst, const char *src);\nchar *string_malloc(const char *s);\nint **load_iarrays(const char *csv_path, int *nb_arrays);\nreal_t **load_darrays(const char *csv_path, int *nb_arrays);\n\nint dsv_rows(const char *fp);\nint dsv_cols(const char *fp, const char delim);\nchar **dsv_fields(const char *fp, const char delim, int *nb_fields);\nreal_t **dsv_data(const char *fp, const char delim, int *nb_rows, int *nb_cols);\nvoid dsv_free(real_t **data, const int nb_rows);\n\nreal_t **csv_data(const char *fp, int *nb_rows, int *nb_cols);\nvoid csv_free(real_t **data, const int nb_rows);\n\n/* real_t *load_matrix(const char *file_path); */\n/* real_t *load_vector(const char *file_path); */\n\n/******************************************************************************\n * TIME\n ******************************************************************************/\n\n/** Timestamp Type */\ntypedef uint64_t timestamp_t;\n\nstruct timespec tic();\nfloat toc(struct timespec *tic);\nfloat mtoc(struct timespec *tic);\ntimestamp_t time_now();\n\nreal_t ts2sec(const timestamp_t ts);\ntimestamp_t sec2ts(const real_t time_s);\n\n/******************************************************************************\n * NETWORK\n ******************************************************************************/\n\n/**\n * TCP server\n */\ntypedef struct tcp_server_t {\n  int port;\n  int sockfd;\n  int conn;\n  void *(*conn_handler)(void *);\n} tcp_server_t;\n\n/**\n * TCP client\n */\ntypedef struct tcp_client_t {\n  char server_ip[1024];\n  int server_port;\n  int sockfd;\n  int (*loop_cb)(struct tcp_client_t *);\n} tcp_client_t;\n\nint ip_port_info(const int sockfd, char *ip, int *port);\n\nint tcp_server_setup(tcp_server_t *server, const int port);\nint tcp_server_loop(tcp_server_t *server);\n\nint tcp_client_setup(tcp_client_t *client,\n                     const char *server_ip,\n                     const int server_port);\nint tcp_client_loop(tcp_client_t *client);\n\n/******************************************************************************\n * MATHS\n ******************************************************************************/\n\n/** Mathematical Pi constant (i.e. 3.1415..) */\n#ifndef M_PI\n#define M_PI (3.14159265358979323846)\n#endif\n\n/** Real number comparison tolerance */\n#ifndef CMP_TOL\n#define CMP_TOL 1e-6\n#endif\n\n/** Min of two numbers, X or Y. */\n#define MIN(x, y) ((x) < (y) ? (x) : (y))\n\n/** Max of two numbers, X or Y. */\n#define MAX(x, y) ((x) > (y) ? (x) : (y))\n\n/** Based on sign of b, return +ve or -ve a. */\n#define SIGN2(a, b) ((b) >= 0.0 ? fabs(a) : -fabs(a))\n\nfloat randf(float a, float b);\nreal_t deg2rad(const real_t d);\nreal_t rad2deg(const real_t r);\nint fltcmp(const real_t x, const real_t y);\nint fltcmp2(const void *x, const void *y);\nreal_t pythag(const real_t a, const real_t b);\nreal_t lerp(const real_t a, const real_t b, const real_t t);\nvoid lerp3(const real_t a[3], const real_t b[3], const real_t t, real_t x[3]);\nreal_t sinc(const real_t x);\nreal_t mean(const real_t *x, const size_t length);\nreal_t median(const real_t *x, const size_t length);\nreal_t var(const real_t *x, const size_t length);\nreal_t stddev(const real_t *x, const size_t length);\n\n/******************************************************************************\n * LINEAR ALGEBRA\n ******************************************************************************/\n\nvoid print_matrix(const char *prefix,\n                  const real_t *A,\n                  const size_t m,\n                  const size_t n);\nvoid print_vector(const char *prefix, const real_t *v, const size_t n);\n\nvoid eye(real_t *A, const size_t m, const size_t n);\nvoid ones(real_t *A, const size_t m, const size_t n);\nvoid zeros(real_t *A, const size_t m, const size_t n);\n\nreal_t *mat_malloc(const size_t m, const size_t n);\nint mat_cmp(const real_t *A, const real_t *B, const size_t m, const size_t n);\nint mat_equals(const real_t *A,\n               const real_t *B,\n               const size_t m,\n               const size_t n,\n               const real_t tol);\nint mat_save(const char *save_path, const real_t *A, const int m, const int n);\nreal_t *mat_load(const char *save_path, int *nb_rows, int *nb_cols);\nvoid mat_set(real_t *A,\n             const size_t stride,\n             const size_t i,\n             const size_t j,\n             const real_t val);\nreal_t\nmat_val(const real_t *A, const size_t stride, const size_t i, const size_t j);\nvoid mat_copy(const real_t *src, const int m, const int n, real_t *dest);\nvoid mat_row_set(real_t *A,\n                 const size_t stride,\n                 const int row_idx,\n                 const real_t *x);\nvoid mat_col_set(real_t *A,\n                 const size_t stride,\n                 const int nb_rows,\n                 const int col_idx,\n                 const real_t *x);\nvoid mat_block_get(const real_t *A,\n                   const size_t stride,\n                   const size_t rs,\n                   const size_t cs,\n                   const size_t re,\n                   const size_t ce,\n                   real_t *block);\nvoid mat_block_set(real_t *A,\n                   const size_t stride,\n                   const size_t rs,\n                   const size_t cs,\n                   const size_t re,\n                   const size_t ce,\n                   const real_t *block);\nvoid mat_diag_get(const real_t *A, const int m, const int n, real_t *d);\nvoid mat_diag_set(real_t *A, const int m, const int n, const real_t *d);\nvoid mat_triu(const real_t *A, const size_t n, real_t *U);\nvoid mat_tril(const real_t *A, const size_t n, real_t *L);\nreal_t mat_trace(const real_t *A, const size_t m, const size_t n);\nvoid mat_transpose(const real_t *A, size_t m, size_t n, real_t *A_t);\nvoid mat_add(const real_t *A, const real_t *B, real_t *C, size_t m, size_t n);\nvoid mat_sub(const real_t *A, const real_t *B, real_t *C, size_t m, size_t n);\nvoid mat_scale(real_t *A, const size_t m, const size_t n, const real_t scale);\n\nreal_t *vec_malloc(const size_t n);\nvoid vec_copy(const real_t *src, const size_t n, real_t *dest);\nint vec_equals(const real_t *x, const real_t *y, const size_t n);\nvoid vec_add(const real_t *x, const real_t *y, real_t *z, size_t n);\nvoid vec_sub(const real_t *x, const real_t *y, real_t *z, size_t n);\nvoid vec_scale(real_t *x, const size_t n, const real_t scale);\nreal_t vec_norm(const real_t *x, const size_t n);\nvoid vec_normalize(real_t *x, const size_t n);\n\nvoid dot(const real_t *A,\n         const size_t A_m,\n         const size_t A_n,\n         const real_t *B,\n         const size_t B_m,\n         const size_t B_n,\n         real_t *C);\nvoid skew(const real_t x[3], real_t A[3 * 3]);\nvoid skew_inv(const real_t A[3 * 3], real_t x[3]);\nvoid fwdsubs(const real_t *L, const real_t *b, real_t *y, const size_t n);\nvoid bwdsubs(const real_t *U, const real_t *y, real_t *x, const size_t n);\nint check_jacobian(const char *jac_name,\n                   const real_t *fdiff,\n                   const real_t *jac,\n                   const size_t m,\n                   const size_t n,\n                   const real_t tol,\n                   const int verbose);\n\n#ifdef USE_CBLAS\nvoid cblas_dot(const real_t *A,\n               const size_t A_m,\n               const size_t A_n,\n               const real_t *B,\n               const size_t B_m,\n               const size_t B_n,\n               real_t *C);\n#endif\n\n/******************************************************************************\n * SVD\n ******************************************************************************/\n\nint svd(real_t *A, const int m, const int n, real_t *w, real_t *V);\n\n#ifdef USE_LAPACK\nvoid lapack_svd(real_t *A, int m, int n, real_t **S, real_t **U, real_t **V_t);\n#endif\n\n/******************************************************************************\n * CHOL\n ******************************************************************************/\n\nvoid chol(const real_t *A, const size_t n, real_t *L);\nvoid chol_solve(const real_t *A, const real_t *b, real_t *x, const size_t n);\n\n#ifdef USE_LAPACK\nvoid lapack_chol_solve(const real_t *A,\n                       const real_t *b,\n                       real_t *x,\n                       const size_t n);\n#endif\n\n/******************************************************************************\n * TRANSFORMS\n ******************************************************************************/\n\nvoid tf(const real_t params[7], real_t T[4 * 4]);\nvoid tf_vector(const real_t T[4 * 4], real_t params[7]);\nvoid tf_decompose(const real_t T[4 * 4], real_t C[3 * 3], real_t r[3]);\nvoid tf_rot_set(real_t T[4 * 4], const real_t C[3 * 3]);\nvoid tf_rot_get(const real_t T[4 * 4], real_t C[3 * 3]);\nvoid tf_quat_set(real_t T[4 * 4], const real_t q[4]);\nvoid tf_quat_get(const real_t T[4 * 4], real_t q[4]);\nvoid tf_euler_set(real_t T[4 * 4], const real_t ypr[3]);\nvoid tf_euler_get(const real_t T[4 * 4], real_t ypr[3]);\nvoid tf_trans_set(real_t T[4 * 4], const real_t r[3]);\nvoid tf_trans_get(const real_t T[4 * 4], real_t r[3]);\nvoid tf_inv(const real_t T[4 * 4], real_t T_inv[4 * 4]);\nvoid tf_point(const real_t T[4 * 4], const real_t p[3], real_t retval[3]);\nvoid tf_hpoint(const real_t T[4 * 4], const real_t p[4], real_t retval[4]);\nvoid tf_perturb_rot(real_t T[4 * 4], const real_t step_size, const int i);\nvoid tf_perturb_trans(real_t T[4 * 4], const real_t step_size, const int i);\nvoid print_pose_vector(const char *prefix, const real_t pose[7]);\nvoid rvec2rot(const real_t *rvec, const real_t eps, real_t *R);\nvoid euler321(const real_t ypr[3], real_t C[3 * 3]);\nvoid euler2quat(const real_t ypr[3], real_t q[4]);\nvoid rot2quat(const real_t C[3 * 3], real_t q[4]);\nvoid rot2euler(const real_t C[3 * 3], real_t ypr[3]);\nvoid quat2euler(const real_t q[4], real_t ypr[3]);\nvoid quat2rot(const real_t q[4], real_t C[3 * 3]);\nreal_t quat_norm(const real_t q[4]);\nvoid quat_normalize(real_t q[4]);\nvoid quat_inv(const real_t q[4], real_t q_inv[4]);\nvoid quat_left(const real_t q[4], real_t left[4 * 4]);\nvoid quat_right(const real_t q[4], real_t right[4 * 4]);\nvoid quat_lmul(const real_t p[4], const real_t q[4], real_t r[4]);\nvoid quat_rmul(const real_t p[4], const real_t q[4], real_t r[4]);\nvoid quat_mul(const real_t p[4], const real_t q[4], real_t r[4]);\nvoid quat_delta(const real_t dalpha[3], real_t dq[4]);\nvoid quat_perturb(real_t q[4], const int i, const real_t h);\n\n/******************************************************************************\n * Lie\n ******************************************************************************/\n\nvoid lie_Exp(const real_t phi[3], real_t C[3 * 3]);\nvoid lie_Log(const real_t C[3 * 3], real_t rvec[3]);\n\n/******************************************************************************\n * CV\n ******************************************************************************/\n\n// IMAGE ///////////////////////////////////////////////////////////////////////\n\ntypedef struct image_t {\n  int width;\n  int height;\n  int channels;\n  uint8_t *data;\n} image_t;\n\nvoid image_setup(image_t *img,\n                 const int width,\n                 const int height,\n                 uint8_t *data);\nimage_t *image_load(const char *file_path);\nvoid image_print_properties(const image_t *img);\nvoid image_free(image_t *img);\n\n// GEOMETRY ////////////////////////////////////////////////////////////////////\n\nvoid linear_triangulation(const real_t P_i[3 * 4],\n                          const real_t P_j[3 * 4],\n                          const real_t z_i[2],\n                          const real_t z_j[2],\n                          real_t p[3]);\n\n// RADTAN //////////////////////////////////////////////////////////////////////\n\nvoid radtan4_distort(const real_t params[4], const real_t p[2], real_t p_d[2]);\nvoid radtan4_point_jacobian(const real_t params[4],\n                            const real_t p[2],\n                            real_t J_point[2 * 2]);\nvoid radtan4_params_jacobian(const real_t params[4],\n                             const real_t p[2],\n                             real_t J_param[2 * 4]);\n\n// EQUI ////////////////////////////////////////////////////////////////////////\n\nvoid equi4_distort(const real_t params[4], const real_t p[2], real_t p_d[2]);\nvoid equi4_point_jacobian(const real_t params[4],\n                          const real_t p[2],\n                          real_t J_point[2 * 2]);\nvoid equi4_params_jacobian(const real_t params[4],\n                           const real_t p[2],\n                           real_t J_param[2 * 4]);\n\n// PINHOLE /////////////////////////////////////////////////////////////////////\n\nreal_t pinhole_focal(const int image_width, const real_t fov);\nvoid pinhole_K(const real_t params[4], real_t K[3 * 3]);\nvoid pinhole_projection_matrix(const real_t params[4],\n                               const real_t T[4 * 4],\n                               real_t P[3 * 4]);\nvoid pinhole_project(const real_t params[4], const real_t p_C[3], real_t z[2]);\nvoid pinhole_point_jacobian(const real_t params[4], real_t J_point[2 * 2]);\nvoid pinhole_params_jacobian(const real_t params[4],\n                             const real_t x[2],\n                             real_t J[2 * 4]);\n\n// PINHOLE-RADTAN4 /////////////////////////////////////////////////////////////\n\nvoid pinhole_radtan4_project(const real_t params[8],\n                             const real_t p_C[3],\n                             real_t x[2]);\nvoid pinhole_radtan4_project_jacobian(const real_t params[8],\n                                      const real_t p_C[3],\n                                      real_t J[2 * 3]);\nvoid pinhole_radtan4_params_jacobian(const real_t params[8],\n                                     const real_t p_C[3],\n                                     real_t J[2 * 8]);\n\n// PINHOLE-EQUI4 ///////////////////////////////////////////////////////////////\n\nvoid pinhole_equi4_project(const real_t params[8],\n                           const real_t p_C[3],\n                           real_t x[2]);\nvoid pinhole_equi4_project_jacobian(const real_t params[8],\n                                    const real_t p_C[3],\n                                    real_t J[2 * 3]);\nvoid pinhole_equi4_params_jacobian(const real_t params[8],\n                                   const real_t p_C[3],\n                                   real_t J[2 * 8]);\n\n/******************************************************************************\n * SENSOR FUSION\n ******************************************************************************/\n\n#define POSE_PARAM 1\n#define SB_PARAM 2\n#define FEATURE_PARAM 3\n#define EXTRINSICS_PARAM 4\n#define CAM_PARAM 5\n\n// POSE ////////////////////////////////////////////////////////////////////////\n\ntypedef struct pose_t {\n  timestamp_t ts;\n  real_t pos[3];\n  real_t quat[4];\n} pose_t;\n\nvoid pose_setup(pose_t *pose, const timestamp_t ts, const real_t *param);\nvoid pose_print(const char *prefix, const pose_t *pose);\n\n// SPEED AND BIASES ////////////////////////////////////////////////////////////\n\ntypedef struct speed_biases_t {\n  timestamp_t ts;\n  real_t data[9];\n} speed_biases_t;\n\nvoid speed_biases_setup(speed_biases_t *sb,\n                        const timestamp_t ts,\n                        const real_t *param);\nvoid speed_biases_print(const speed_biases_t *sb);\n\n// FEATURE /////////////////////////////////////////////////////////////////////\n\n#define MAX_FEATURES 10000\n\ntypedef struct feature_t {\n  real_t data[3];\n} feature_t;\n\nvoid feature_setup(feature_t *p, const real_t *param);\nvoid feature_print(const feature_t *feature);\n\ntypedef struct features_t {\n  feature_t data[MAX_FEATURES];\n  int nb_features;\n  int status[MAX_FEATURES];\n} features_t;\n\nvoid features_setup(features_t *features);\nint features_exists(const features_t *features, const int feature_id);\nfeature_t *features_get(features_t *features, const int feature_id);\nfeature_t *features_add(features_t *features,\n                        const int feature_id,\n                        const real_t *param);\nvoid features_remove(features_t *features, const int feature_id);\n\n// EXTRINSICS //////////////////////////////////////////////////////////////////\n\ntypedef struct extrinsics_t {\n  real_t pos[3];\n  real_t quat[4];\n} extrinsics_t;\n\nvoid extrinsics_setup(extrinsics_t *extrinsics, const real_t *param);\nvoid extrinsics_print(const char *prefix, const extrinsics_t *exts);\n\n// CAMERA PARAMS ///////////////////////////////////////////////////////////////\n\ntypedef struct camera_params_t {\n  int cam_idx;\n  int resolution[2];\n  char proj_model[20];\n  char dist_model[20];\n  real_t data[8];\n} camera_params_t;\n\nvoid camera_params_setup(camera_params_t *camera,\n                         const int cam_idx,\n                         const int cam_res[2],\n                         const char *proj_model,\n                         const char *dist_model,\n                         const real_t *data);\nvoid camera_params_print(const camera_params_t *camera);\n\n// POSE FACTOR /////////////////////////////////////////////////////////////////\n\ntypedef struct pose_factor_t {\n  real_t pos_meas[3];\n  real_t quat_meas[4];\n  pose_t *pose_est;\n  int nb_params;\n\n  real_t covar[6 * 6];\n  real_t sqrt_info[6 * 6];\n} pose_factor_t;\n\nvoid pose_factor_setup(pose_factor_t *factor,\n                       pose_t *pose,\n                       const real_t var[6]);\nint pose_factor_eval(pose_factor_t *factor,\n                     real_t **params,\n                     real_t *residuals,\n                     real_t **jacobians);\nint pose_factor_ceres_eval(void *factor,\n                           double **params,\n                           double *residuals,\n                           double **jacobians);\n\n// BA FACTOR ///////////////////////////////////////////////////////////////////\n\ntypedef struct ba_factor_t {\n  const pose_t *pose;\n  const camera_params_t *camera;\n  const feature_t *feature;\n  int nb_params;\n\n  real_t covar[2 * 2];\n  real_t sqrt_info[2 * 2];\n  real_t z[2];\n} ba_factor_t;\n\nvoid ba_factor_setup(ba_factor_t *factor,\n                     const pose_t *pose,\n                     const feature_t *feature,\n                     const camera_params_t *camera,\n                     const real_t z[2],\n                     const real_t var[2]);\nint ba_factor_eval(ba_factor_t *factor,\n                   real_t **params,\n                   real_t *residuals,\n                   real_t **jacobians);\nint ba_factor_ceres_eval(void *factor,\n                         double **params,\n                         double *residuals,\n                         double **jacobians);\n\n// CAMERA FACTOR ///////////////////////////////////////////////////////////////\n\ntypedef struct cam_factor_t {\n  const pose_t *pose;\n  const extrinsics_t *extrinsics;\n  const camera_params_t *camera;\n  const feature_t *feature;\n  int nb_params;\n\n  real_t covar[2 * 2];\n  real_t sqrt_info[2 * 2];\n  real_t z[2];\n} cam_factor_t;\n\nvoid cam_factor_setup(cam_factor_t *factor,\n                      const pose_t *pose,\n                      const extrinsics_t *extrinsics,\n                      const feature_t *feature,\n                      const camera_params_t *camera,\n                      const real_t z[2],\n                      const real_t var[2]);\nint cam_factor_eval(cam_factor_t *factor,\n                    real_t **params,\n                    real_t *residuals,\n                    real_t **jacobians);\nint cam_factor_ceres_eval(void *factor,\n                          double **params,\n                          double *residuals,\n                          double **jacobians);\n\n// IMU FACTOR //////////////////////////////////////////////////////////////////\n\n#define MAX_IMU_BUF_SIZE 10000\n\ntypedef struct imu_params_t {\n  uint64_t param_id;\n  int imu_idx;\n  real_t rate;\n\n  real_t n_aw;\n  real_t n_gw;\n  real_t n_a;\n  real_t n_g;\n  real_t g;\n} imu_params_t;\n\ntypedef struct imu_buf_t {\n  timestamp_t ts[MAX_IMU_BUF_SIZE];\n  real_t acc[MAX_IMU_BUF_SIZE][3];\n  real_t gyr[MAX_IMU_BUF_SIZE][3];\n  int size;\n} imu_buf_t;\n\ntypedef struct imu_factor_t {\n  imu_params_t *imu_params;\n  imu_buf_t imu_buf;\n  pose_t *pose_i;\n  pose_t *pose_j;\n  speed_biases_t *sb_i;\n  speed_biases_t *sb_j;\n\n  real_t covar[15 * 15];\n  real_t r[15];\n  int r_size;\n\n  real_t J0[2 * 6]; /* Jacobian w.r.t pose i */\n  real_t J1[2 * 9]; /* Jacobian w.r.t speed and biases i */\n  real_t J2[2 * 6]; /* Jacobian w.r.t pose j */\n  real_t J3[2 * 9]; /* Jacobian w.r.t speed and biases j */\n  real_t *jacs[4];\n  int nb_params;\n\n  /* Preintegration variables */\n  real_t Dt;\n  real_t F[15 * 15]; /* State jacobian */\n  real_t P[15 * 15]; /* State covariance */\n  real_t Q[15 * 15]; /* Noise matrix */\n\n  real_t dr[3];     /* Relative position */\n  real_t dv[3];     /* Relative velocity */\n  real_t dC[3 * 3]; /* Relative rotation */\n  real_t ba[3];     /* Accel biase */\n  real_t bg[3];     /* Gyro biase */\n\n} imu_factor_t;\n\nvoid imu_buf_setup(imu_buf_t *imu_buf);\nvoid imu_buf_add(imu_buf_t *imu_buf,\n                 const timestamp_t ts,\n                 const real_t acc[3],\n                 const real_t gyr[3]);\nvoid imu_buf_clear(imu_buf_t *imu_buf);\nvoid imu_buf_copy(const imu_buf_t *from, imu_buf_t *to);\nvoid imu_buf_print(const imu_buf_t *imu_buf);\n\n/* void imu_factor_setup(imu_factor_t *factor, */\n/*                       imu_params_t *imu_params, */\n/*                       imu_buf_t *imu_buf, */\n/*                       pose_t *pose_i, */\n/*                       speed_biases_t *sb_i, */\n/*                       pose_t *pose_j, */\n/*                       speed_biases_t *sb_j); */\nvoid imu_factor_reset(imu_factor_t *factor);\n\n// GRAPH ///////////////////////////////////////////////////////////////////////\n\n#define MAX_NB_FACTORS 1000\n\n#define POSE_FACTOR 1\n#define BA_FACTOR 2\n#define CAM_FACTOR 3\n#define IMU_FACTOR 4\n\ntypedef struct keyframe_t {\n  cam_factor_t *cam_factors;\n  int nb_cam_factors;\n\n  imu_factor_t *imu_factors;\n  int nb_imu_factors;\n\n  pose_t *pose;\n} keyframe_t;\n\ntypedef struct graph_t {\n  void *factors[MAX_NB_FACTORS];\n  int nb_factors;\n  int *factor_types;\n\n  pose_t **poses;\n  int nb_poses;\n\n  const extrinsics_t *extrinsics;\n  int nb_exts;\n\n  camera_params_t **cam_params;\n  int nb_cams;\n\n  feature_t **features;\n  int nb_features;\n\n  real_t *H;\n  real_t *g;\n  real_t *x;\n  int x_size;\n  int r_size;\n} graph_t;\n\nvoid graph_setup(graph_t *graph);\nvoid graph_print(graph_t *graph);\nint graph_add_factor(graph_t *graph, void *factor, int factor_type);\nint graph_eval(graph_t *graph);\nvoid graph_optimize(graph_t *graph);\n\n/******************************************************************************\n * DATASET\n ******************************************************************************/\n\npose_t *load_poses(const char *fp, int *nb_poses);\nint **assoc_pose_data(pose_t *gnd_poses,\n                      size_t nb_gnd_poses,\n                      pose_t *est_poses,\n                      size_t nb_est_poses,\n                      double threshold,\n                      size_t *nb_matches);\n\n/******************************************************************************\n * SIM\n ******************************************************************************/\n\n// SIM FEATURES ////////////////////////////////////////////////////////////////\n\ntypedef struct sim_features_t {\n  real_t **features;\n  int nb_features;\n} sim_features_t;\n\nsim_features_t *load_sim_features(const char *csv_path);\nvoid free_sim_features(sim_features_t *features_data);\n\n// SIM IMU DATA ////////////////////////////////////////////////////////////////\n\ntypedef struct sim_imu_data_t {\n  real_t **data;\n  int nb_measurements;\n} sim_imu_data_t;\n\nsim_imu_data_t *load_sim_imu_data(const char *csv_path);\nvoid free_sim_imu_data(sim_imu_data_t *imu_data);\n\n// SIM CAM DATA ////////////////////////////////////////////////////////////////\n\ntypedef struct sim_cam_frame_t {\n  timestamp_t ts;\n  int *feature_ids;\n  real_t **keypoints;\n  int nb_measurements;\n} sim_cam_frame_t;\n\ntypedef struct sim_cam_data_t {\n  sim_cam_frame_t **frames;\n  int nb_frames;\n\n  timestamp_t *ts;\n  real_t **poses;\n} sim_cam_data_t;\n\nsim_cam_frame_t *load_sim_cam_frame(const char *csv_path);\nvoid print_sim_cam_frame(sim_cam_frame_t *frame_data);\nvoid free_sim_cam_frame(sim_cam_frame_t *frame_data);\n\nsim_cam_data_t *load_sim_cam_data(const char *dir_path);\nvoid free_sim_cam_data(sim_cam_data_t *cam_data);\n\n#endif // _PROTO_H_\n", "meta": {"hexsha": "14c1e0646e48bf1d12cdd9ca84afc9dbc3fcd8b4", "size": 30083, "ext": "h", "lang": "C", "max_stars_repo_path": "proto/lib/proto.h", "max_stars_repo_name": "daoran/proto", "max_stars_repo_head_hexsha": "c0f7bfc3acceac7872dfe9b510e2713f3e5efd90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-08-27T21:37:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-20T12:25:04.000Z", "max_issues_repo_path": "proto/lib/proto.h", "max_issues_repo_name": "daoran/proto", "max_issues_repo_head_hexsha": "c0f7bfc3acceac7872dfe9b510e2713f3e5efd90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-21T01:08:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-21T01:10:10.000Z", "max_forks_repo_path": "proto/lib/proto.h", "max_forks_repo_name": "daoran/proto", "max_forks_repo_head_hexsha": "c0f7bfc3acceac7872dfe9b510e2713f3e5efd90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-03-12T05:10:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-22T03:19:44.000Z", "avg_line_length": 33.5373467113, "max_line_length": 80, "alphanum_fraction": 0.5126150982, "num_tokens": 6780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19436781568545955, "lm_q2_score": 0.029312231811314076, "lm_q1q2_score": 0.0056973544700309586}}
{"text": "#pragma once\n\n#define NOMINMAX\n\n// Windows\n#include <windows.h>\n#include <winrt\\Windows.Foundation.h>\n\n// Standard\n#include <string>\n#include <sstream>\n\n#if defined(DEBUG) || defined(_DEBUG)\n#define _CRTDBG_MAP_ALLOC\n#include <stdlib.h>\n#include <crtdbg.h>\n#endif\n\n// Guidelines Support Library\n#include <gsl\\gsl>\n\n// DirectX\n#include <d3d11_4.h>\n#include <dxgi1_6.h>\n#include <DirectXMath.h>", "meta": {"hexsha": "82bb3894468324193c26646fb9d59bea02a04524", "size": 392, "ext": "h", "lang": "C", "max_stars_repo_path": "source/1.1_Win32_Startup/pch.h", "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/1.1_Win32_Startup/pch.h", "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/1.1_Win32_Startup/pch.h", "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.68, "max_line_length": 37, "alphanum_fraction": 0.7321428571, "num_tokens": 108, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1993079883920791, "lm_q2_score": 0.028436032427331594, "lm_q1q2_score": 0.00566752842094339}}
{"text": "/*\n * Copyright (c) 2020 Microsoft. All rights reserved.\n */\n\n#pragma once\n\n// a place for frequently used types, especially ones relied on for interfaces\n// eg gsl::span<uint8_t> etc\n\n#include \"machine.h\"\n\n#include <vector>\n\n#include <gsl/span>\n#include <gsl/span_ext>\n\n#include <gsl/util>\n\n#include <type_traits> // for make_unsigned\n\ntemplate <typename T>\nT RemoveUnsigned(typename std::make_unsigned<T>::type val) {\n  return gsl::narrow_cast<T>(val);\n}\n\ntemplate <typename T> typename std::make_unsigned<T>::type MakeUnsigned(T val) {\n  return gsl::narrow_cast<typename std::make_unsigned<T>::type>(val);\n}\n\n// encapsulate some memory which may be written, use instead of a ptr, len\nusing MemRef = gsl::span<uint8_t>;\nusing MemRefSizeType = MemRef::size_type;\n\nusing SignedMemRef = gsl::span<char>;\nusing SignedMemRefSizeType = SignedMemRef::size_type;\n\nusing MemVector = std::vector<uint8_t>;\n\n// encapsulate some read only memory\nusing CMemRef = gsl::span<const uint8_t>;\nusing CSignedMemRef = gsl::span<const char>;\n\n// from any old class T make a span covering uint8_ts\n// intended for the Params classes.\ntemplate <class T> MemRef MakeMemRef(T *p) noexcept {\n  void *ptr = p;\n  static_assert(sizeof(*p) != 1);\n  return MemRef(static_cast<uint8_t *>(ptr), sizeof(*p));\n}\n\ntemplate <class T> MemRef MakeMemRef(T *p, size_t len) noexcept {\n  void *ptr = p;\n  return MemRef(static_cast<uint8_t *>(ptr), len);\n}\n\ntemplate <class T> CMemRef MakeCMemRef(const T *p, size_t len) noexcept {\n  const void *ptr = p;\n  return CMemRef(static_cast<const uint8_t *>(ptr), len);\n}\n\ntemplate <class T> CMemRef MakeCMemRef(const T *p) noexcept {\n  const void *ptr = p;\n  return CMemRef(static_cast<const uint8_t *>(ptr), sizeof(*p));\n}\n\ntemplate <class T, size_t TLength>\nCMemRef MakeCMemRef2(const T (&p)[TLength]) noexcept {\n  const void *ptr = p;\n  return CMemRef(static_cast<const uint8_t *>(ptr), TLength);\n}\n\ntemplate <class T> SignedMemRef MakeSignedMemRef(T *p) noexcept {\n  void *ptr = p;\n  static_assert(sizeof(*p) != 1);\n  return SignedMemRef(static_cast<char *>(ptr), sizeof(*p));\n}\n\ntemplate <class T> SignedMemRef MakeSignedMemRef(T *p, size_t len) noexcept {\n  void *ptr = p;\n  return SignedMemRef(static_cast<char *>(ptr), len);\n}\n\ntemplate <class T> CSignedMemRef MakeCSignedMemRef(T *p) noexcept {\n  const void *ptr = p;\n  static_assert(sizeof(*p) != 1);\n  return CSignedMemRef(static_cast<const char *>(ptr), sizeof(*p));\n}\n\ntemplate <class T> CSignedMemRef MakeCSignedMemRef(T *p, size_t len) noexcept {\n  const void *ptr = p;\n  return CSignedMemRef(static_cast<const char *>(ptr), len);\n}\n\n// T will needs top be copyable\ntemplate <class T> T ReHydrate(CMemRef source) noexcept {\n  const void *ptr = source.data();\n  const T *tInPlace = static_cast<const T *>(ptr);\n  T ret = *tInPlace;\n  return ret;\n}\n\n// Work around C4686\nusing _FixedLengthString = std::array<char, 1024>;\nclass FixedLengthString : public _FixedLengthString {\n  using _FixedLengthString::_FixedLengthString;\n};\n\n// helper for HexDump\nvoid HexByte(uint8_t byte, char &c1, char &c2);\n// hex dump a block of memory into another block of memory.\nsize_t HexDump(CMemRef src, SignedMemRef dst);\n\ntemplate <class T, int LEN> struct IsPODEtc {\n  static constexpr bool value =\n      sizeof(T) == LEN && std::is_pod<T>::value && std::is_trivial<T>::value &&\n      std::is_trivially_copyable<T>::value && std::is_standard_layout<T>::value;\n};\n\n/*\n    Compile time protection against objects being different between the\n    host and HW.\n\n    usage - put something like the following outside the class:\n\n    static_assert(OkAsParam<MyClass, 666>::value);\n\n*/\n\ntemplate <class T, int LEN> struct SizeIsOK {\n  static constexpr bool value = sizeof(T) == LEN;\n};\n\ntemplate <class T> struct LayoutIsOK {\n  // These two checks fail for most of our types as they have user provided\n  // default ctors or members with default initialisers.\n  // static_assert(std::is_pod<T>::value);\n  // static_assert(std::is_trivial<T>::value);\n\n  static constexpr bool value =\n\n      // but anything we can serialise by copying must be trivially copyable\n      std::is_trivially_copyable<T>::value &&\n\n      // and must be standard layout, ie if you can't pass it to a C program\n      // what hope is there that you can pass it over the wire to the HW.\n      std::is_standard_layout<T>::value;\n};\n\ntemplate <class T, int LEN> struct OkAsParam {\n  static constexpr bool value = SizeIsOK<T, LEN>::value && LayoutIsOK<T>::value;\n};\n\n// Thinking about labeling classes explicitly. TBC, ignore for now.\n\nclass CannotBeSerialsed {\npublic:\n  constexpr bool canBeSerialised() const { return false; }\n};\n\nclass CanBeSerialsed {\npublic:\n  constexpr bool canBeSerialised() const { return true; }\n};\n", "meta": {"hexsha": "1af6fb13db72e95a4c633a2d54f6ae305222e68d", "size": 4735, "ext": "h", "lang": "C", "max_stars_repo_path": "src/common/common.h", "max_stars_repo_name": "verified-HRoT/Verified-DICE-for-STM32H7", "max_stars_repo_head_hexsha": "703299f9ae5422cfd7161f80c32b5f3ad1bb6af6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/common/common.h", "max_issues_repo_name": "verified-HRoT/Verified-DICE-for-STM32H7", "max_issues_repo_head_hexsha": "703299f9ae5422cfd7161f80c32b5f3ad1bb6af6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/common/common.h", "max_forks_repo_name": "verified-HRoT/Verified-DICE-for-STM32H7", "max_forks_repo_head_hexsha": "703299f9ae5422cfd7161f80c32b5f3ad1bb6af6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8719512195, "max_line_length": 80, "alphanum_fraction": 0.7123548046, "num_tokens": 1268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.13846177634847415, "lm_q2_score": 0.04084571138559326, "lm_q1q2_score": 0.005655569754666338}}
{"text": "/* block/gsl_block_uint.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_BLOCK_UINT_H__\n#define __GSL_BLOCK_UINT_H__\n\n#if !defined( GSL_FUN )\n#  if !defined( GSL_DLL )\n#    define GSL_FUN extern\n#  elif defined( BUILD_GSL_DLL )\n#    define GSL_FUN extern __declspec(dllexport)\n#  else\n#    define GSL_FUN extern __declspec(dllimport)\n#  endif\n#endif\n\n#include <stdlib.h>\n#include <gsl/gsl_errno.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\nstruct gsl_block_uint_struct\n{\n  size_t size;\n  unsigned int *data;\n};\n\ntypedef struct gsl_block_uint_struct gsl_block_uint;\n\nGSL_FUN gsl_block_uint *gsl_block_uint_alloc (const size_t n);\nGSL_FUN gsl_block_uint *gsl_block_uint_calloc (const size_t n);\nGSL_FUN void gsl_block_uint_free (gsl_block_uint * b);\n\nGSL_FUN int gsl_block_uint_fread (FILE * stream, gsl_block_uint * b);\nGSL_FUN int gsl_block_uint_fwrite (FILE * stream, const gsl_block_uint * b);\nGSL_FUN int gsl_block_uint_fscanf (FILE * stream, gsl_block_uint * b);\nGSL_FUN int gsl_block_uint_fprintf (FILE * stream, const gsl_block_uint * b, const char *format);\n\nGSL_FUN int gsl_block_uint_raw_fread (FILE * stream, unsigned int * b, const size_t n, const size_t stride);\nGSL_FUN int gsl_block_uint_raw_fwrite (FILE * stream, const unsigned int * b, const size_t n, const size_t stride);\nGSL_FUN int gsl_block_uint_raw_fscanf (FILE * stream, unsigned int * b, const size_t n, const size_t stride);\nGSL_FUN int gsl_block_uint_raw_fprintf (FILE * stream, const unsigned int * b, const size_t n, const size_t stride, const char *format);\n\nGSL_FUN size_t gsl_block_uint_size (const gsl_block_uint * b);\nGSL_FUN unsigned int * gsl_block_uint_data (const gsl_block_uint * b);\n\n__END_DECLS\n\n#endif /* __GSL_BLOCK_UINT_H__ */\n", "meta": {"hexsha": "f125a9903f00fb7fa5e849805282949f60a286f6", "size": 2675, "ext": "h", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_block_uint.h", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_block_uint.h", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_block_uint.h", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1973684211, "max_line_length": 136, "alphanum_fraction": 0.7652336449, "num_tokens": 707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18713269122913018, "lm_q2_score": 0.030214584447621016, "lm_q1q2_score": 0.005654136502053143}}
{"text": "/* vector/gsl_vector_complex_double.h\r\n * \r\n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\r\n * \r\n * This program is free software; you can redistribute it and/or modify\r\n * it under the terms of the GNU General Public License as published by\r\n * the Free Software Foundation; either version 3 of the License, or (at\r\n * your option) any later version.\r\n * \r\n * This program is distributed in the hope that it will be useful, but\r\n * WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n * General Public License for more details.\r\n * \r\n * You should have received a copy of the GNU General Public License\r\n * along with this program; if not, write to the Free Software\r\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r\n */\r\n\r\n#ifndef __GSL_VECTOR_COMPLEX_DOUBLE_H__\r\n#define __GSL_VECTOR_COMPLEX_DOUBLE_H__\r\n\r\n#if !defined( GSL_FUN )\r\n#  if !defined( GSL_DLL )\r\n#    define GSL_FUN extern\r\n#  elif defined( BUILD_GSL_DLL )\r\n#    define GSL_FUN extern __declspec(dllexport)\r\n#  else\r\n#    define GSL_FUN extern __declspec(dllimport)\r\n#  endif\r\n#endif\r\n\r\n#include <stdlib.h>\r\n#include <gsl/gsl_types.h>\r\n#include <gsl/gsl_errno.h>\r\n#include <gsl/gsl_complex.h>\r\n#include <gsl/gsl_check_range.h>\r\n#include <gsl/gsl_vector_double.h>\r\n#include <gsl/gsl_vector_complex.h>\r\n#include <gsl/gsl_block_complex_double.h>\r\n\r\n#undef __BEGIN_DECLS\r\n#undef __END_DECLS\r\n#ifdef __cplusplus\r\n# define __BEGIN_DECLS extern \"C\" {\r\n# define __END_DECLS }\r\n#else\r\n# define __BEGIN_DECLS /* empty */\r\n# define __END_DECLS /* empty */\r\n#endif\r\n\r\n__BEGIN_DECLS\r\n\r\ntypedef struct \r\n{\r\n  size_t size;\r\n  size_t stride;\r\n  double *data;\r\n  gsl_block_complex *block;\r\n  int owner;\r\n} gsl_vector_complex;\r\n\r\ntypedef struct\r\n{\r\n  gsl_vector_complex vector;\r\n} _gsl_vector_complex_view;\r\n\r\ntypedef _gsl_vector_complex_view gsl_vector_complex_view;\r\n\r\ntypedef struct\r\n{\r\n  gsl_vector_complex vector;\r\n} _gsl_vector_complex_const_view;\r\n\r\ntypedef const _gsl_vector_complex_const_view gsl_vector_complex_const_view;\r\n\r\n/* Allocation */\r\n\r\nGSL_FUN gsl_vector_complex *gsl_vector_complex_alloc (const size_t n);\r\nGSL_FUN gsl_vector_complex *gsl_vector_complex_calloc (const size_t n);\r\n\r\nGSL_FUN gsl_vector_complex *\r\ngsl_vector_complex_alloc_from_block (gsl_block_complex * b, \r\n                                           const size_t offset, \r\n                                           const size_t n, \r\n                                           const size_t stride);\r\n\r\nGSL_FUN gsl_vector_complex *\r\ngsl_vector_complex_alloc_from_vector (gsl_vector_complex * v, \r\n                                             const size_t offset, \r\n                                             const size_t n, \r\n                                             const size_t stride);\r\n\r\nGSL_FUN void gsl_vector_complex_free (gsl_vector_complex * v);\r\n\r\n/* Views */\r\n\r\nGSL_FUN _gsl_vector_complex_view\r\ngsl_vector_complex_view_array (double *base,\r\n                                     size_t n);\r\n\r\nGSL_FUN _gsl_vector_complex_view\r\ngsl_vector_complex_view_array_with_stride (double *base,\r\n                                                 size_t stride,\r\n                                                 size_t n);\r\n\r\nGSL_FUN _gsl_vector_complex_const_view\r\ngsl_vector_complex_const_view_array (const double *base,\r\n                                           size_t n);\r\n\r\nGSL_FUN _gsl_vector_complex_const_view\r\ngsl_vector_complex_const_view_array_with_stride (const double *base,\r\n                                                       size_t stride,\r\n                                                       size_t n);\r\n\r\nGSL_FUN _gsl_vector_complex_view\r\ngsl_vector_complex_subvector (gsl_vector_complex *base,\r\n                                         size_t i, \r\n                                         size_t n);\r\n\r\n\r\nGSL_FUN _gsl_vector_complex_view \r\ngsl_vector_complex_subvector_with_stride (gsl_vector_complex *v, \r\n                                                size_t i, \r\n                                                size_t stride, \r\n                                                size_t n);\r\n\r\nGSL_FUN _gsl_vector_complex_const_view\r\ngsl_vector_complex_const_subvector (const gsl_vector_complex *base,\r\n                                               size_t i, \r\n                                               size_t n);\r\n\r\n\r\nGSL_FUN _gsl_vector_complex_const_view \r\ngsl_vector_complex_const_subvector_with_stride (const gsl_vector_complex *v, \r\n                                                      size_t i, \r\n                                                      size_t stride, \r\n                                                      size_t n);\r\n\r\nGSL_FUN _gsl_vector_view\r\ngsl_vector_complex_real (gsl_vector_complex *v);\r\n\r\nGSL_FUN _gsl_vector_view \r\ngsl_vector_complex_imag (gsl_vector_complex *v);\r\n\r\nGSL_FUN _gsl_vector_const_view\r\ngsl_vector_complex_const_real (const gsl_vector_complex *v);\r\n\r\nGSL_FUN _gsl_vector_const_view \r\ngsl_vector_complex_const_imag (const gsl_vector_complex *v);\r\n\r\n\r\n/* Operations */\r\n\r\nGSL_FUN void gsl_vector_complex_set_zero (gsl_vector_complex * v);\r\nGSL_FUN void gsl_vector_complex_set_all (gsl_vector_complex * v,\r\n                                       gsl_complex z);\r\nGSL_FUN int gsl_vector_complex_set_basis (gsl_vector_complex * v, size_t i);\r\n\r\nGSL_FUN int gsl_vector_complex_fread (FILE * stream,\r\n                                    gsl_vector_complex * v);\r\nGSL_FUN int gsl_vector_complex_fwrite (FILE * stream,\r\n                                     const gsl_vector_complex * v);\r\nGSL_FUN int gsl_vector_complex_fscanf (FILE * stream,\r\n                                     gsl_vector_complex * v);\r\nGSL_FUN int gsl_vector_complex_fprintf (FILE * stream,\r\n                                      const gsl_vector_complex * v,\r\n                                      const char *format);\r\n\r\nGSL_FUN int gsl_vector_complex_memcpy (gsl_vector_complex * dest, const gsl_vector_complex * src);\r\n\r\nGSL_FUN int gsl_vector_complex_reverse (gsl_vector_complex * v);\r\n\r\nGSL_FUN int gsl_vector_complex_swap (gsl_vector_complex * v, gsl_vector_complex * w);\r\nGSL_FUN int gsl_vector_complex_swap_elements (gsl_vector_complex * v, const size_t i, const size_t j);\r\n\r\nGSL_FUN int gsl_vector_complex_isnull (const gsl_vector_complex * v);\r\nGSL_FUN int gsl_vector_complex_ispos (const gsl_vector_complex * v);\r\nGSL_FUN int gsl_vector_complex_isneg (const gsl_vector_complex * v);\r\nGSL_FUN int gsl_vector_complex_isnonneg (const gsl_vector_complex * v);\r\n\r\nGSL_FUN int gsl_vector_complex_add (gsl_vector_complex * a, const gsl_vector_complex * b);\r\nGSL_FUN int gsl_vector_complex_sub (gsl_vector_complex * a, const gsl_vector_complex * b);\r\nGSL_FUN int gsl_vector_complex_mul (gsl_vector_complex * a, const gsl_vector_complex * b);\r\nGSL_FUN int gsl_vector_complex_div (gsl_vector_complex * a, const gsl_vector_complex * b);\r\nGSL_FUN int gsl_vector_complex_scale (gsl_vector_complex * a, const gsl_complex x);\r\nGSL_FUN int gsl_vector_complex_add_constant (gsl_vector_complex * a, const gsl_complex x);\r\n\r\nGSL_FUN INLINE_DECL gsl_complex gsl_vector_complex_get (const gsl_vector_complex * v, const size_t i);\r\nGSL_FUN INLINE_DECL void gsl_vector_complex_set (gsl_vector_complex * v, const size_t i, gsl_complex z);\r\nGSL_FUN INLINE_DECL gsl_complex *gsl_vector_complex_ptr (gsl_vector_complex * v, const size_t i);\r\nGSL_FUN INLINE_DECL const gsl_complex *gsl_vector_complex_const_ptr (const gsl_vector_complex * v, const size_t i);\r\n\r\n#ifdef HAVE_INLINE\r\n\r\nINLINE_FUN\r\ngsl_complex\r\ngsl_vector_complex_get (const gsl_vector_complex * v,\r\n                              const size_t i)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(i >= v->size))\r\n    {\r\n      gsl_complex zero = {{0, 0}};\r\n      GSL_ERROR_VAL (\"index out of range\", GSL_EINVAL, zero);\r\n    }\r\n#endif\r\n  return *GSL_COMPLEX_AT (v, i);\r\n}\r\n\r\nINLINE_FUN\r\nvoid\r\ngsl_vector_complex_set (gsl_vector_complex * v,\r\n                              const size_t i, gsl_complex z)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(i >= v->size))\r\n    {\r\n      GSL_ERROR_VOID (\"index out of range\", GSL_EINVAL);\r\n    }\r\n#endif\r\n  *GSL_COMPLEX_AT (v, i) = z;\r\n}\r\n\r\nINLINE_FUN\r\ngsl_complex *\r\ngsl_vector_complex_ptr (gsl_vector_complex * v,\r\n                              const size_t i)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(i >= v->size))\r\n    {\r\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\r\n    }\r\n#endif\r\n  return GSL_COMPLEX_AT (v, i);\r\n}\r\n\r\nINLINE_FUN\r\nconst gsl_complex *\r\ngsl_vector_complex_const_ptr (const gsl_vector_complex * v,\r\n                                    const size_t i)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(i >= v->size))\r\n    {\r\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\r\n    }\r\n#endif\r\n  return GSL_COMPLEX_AT (v, i);\r\n}\r\n\r\n\r\n#endif /* HAVE_INLINE */\r\n\r\n__END_DECLS\r\n\r\n#endif /* __GSL_VECTOR_COMPLEX_DOUBLE_H__ */\r\n", "meta": {"hexsha": "8d9274b9ae11fa22794849accec0ea1a6b180ac3", "size": 8966, "ext": "h", "lang": "C", "max_stars_repo_path": "deps/include/gsl/gsl_vector_complex_double.h", "max_stars_repo_name": "berkus/music-cs", "max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "deps/include/gsl/gsl_vector_complex_double.h", "max_issues_repo_name": "berkus/music-cs", "max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "deps/include/gsl/gsl_vector_complex_double.h", "max_forks_repo_name": "berkus/music-cs", "max_forks_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6177606178, "max_line_length": 116, "alphanum_fraction": 0.6468882445, "num_tokens": 1950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21733753118592736, "lm_q2_score": 0.025957357386174152, "lm_q1q2_score": 0.0056415079704218865}}
{"text": "/* vector/gsl_vector_long.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_VECTOR_LONG_H__\n#define __GSL_VECTOR_LONG_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_inline.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_block_long.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size;\n  size_t stride;\n  long *data;\n  gsl_block_long *block;\n  int owner;\n} \ngsl_vector_long;\n\ntypedef struct\n{\n  gsl_vector_long vector;\n} _gsl_vector_long_view;\n\ntypedef _gsl_vector_long_view gsl_vector_long_view;\n\ntypedef struct\n{\n  gsl_vector_long vector;\n} _gsl_vector_long_const_view;\n\ntypedef const _gsl_vector_long_const_view gsl_vector_long_const_view;\n\n\n/* Allocation */\n\ngsl_vector_long *gsl_vector_long_alloc (const size_t n);\ngsl_vector_long *gsl_vector_long_calloc (const size_t n);\n\ngsl_vector_long *gsl_vector_long_alloc_from_block (gsl_block_long * b,\n                                                     const size_t offset, \n                                                     const size_t n, \n                                                     const size_t stride);\n\ngsl_vector_long *gsl_vector_long_alloc_from_vector (gsl_vector_long * v,\n                                                      const size_t offset, \n                                                      const size_t n, \n                                                      const size_t stride);\n\nvoid gsl_vector_long_free (gsl_vector_long * v);\n\n/* Views */\n\n_gsl_vector_long_view \ngsl_vector_long_view_array (long *v, size_t n);\n\n_gsl_vector_long_view \ngsl_vector_long_view_array_with_stride (long *base,\n                                         size_t stride,\n                                         size_t n);\n\n_gsl_vector_long_const_view \ngsl_vector_long_const_view_array (const long *v, size_t n);\n\n_gsl_vector_long_const_view \ngsl_vector_long_const_view_array_with_stride (const long *base,\n                                               size_t stride,\n                                               size_t n);\n\n_gsl_vector_long_view \ngsl_vector_long_subvector (gsl_vector_long *v, \n                            size_t i, \n                            size_t n);\n\n_gsl_vector_long_view \ngsl_vector_long_subvector_with_stride (gsl_vector_long *v, \n                                        size_t i,\n                                        size_t stride,\n                                        size_t n);\n\n_gsl_vector_long_const_view \ngsl_vector_long_const_subvector (const gsl_vector_long *v, \n                                  size_t i, \n                                  size_t n);\n\n_gsl_vector_long_const_view \ngsl_vector_long_const_subvector_with_stride (const gsl_vector_long *v, \n                                              size_t i, \n                                              size_t stride,\n                                              size_t n);\n\n/* Operations */\n\nvoid gsl_vector_long_set_zero (gsl_vector_long * v);\nvoid gsl_vector_long_set_all (gsl_vector_long * v, long x);\nint gsl_vector_long_set_basis (gsl_vector_long * v, size_t i);\n\nint gsl_vector_long_fread (FILE * stream, gsl_vector_long * v);\nint gsl_vector_long_fwrite (FILE * stream, const gsl_vector_long * v);\nint gsl_vector_long_fscanf (FILE * stream, gsl_vector_long * v);\nint gsl_vector_long_fprintf (FILE * stream, const gsl_vector_long * v,\n                              const char *format);\n\nint gsl_vector_long_memcpy (gsl_vector_long * dest, const gsl_vector_long * src);\n\nint gsl_vector_long_reverse (gsl_vector_long * v);\n\nint gsl_vector_long_swap (gsl_vector_long * v, gsl_vector_long * w);\nint gsl_vector_long_swap_elements (gsl_vector_long * v, const size_t i, const size_t j);\n\nlong gsl_vector_long_max (const gsl_vector_long * v);\nlong gsl_vector_long_min (const gsl_vector_long * v);\nvoid gsl_vector_long_minmax (const gsl_vector_long * v, long * min_out, long * max_out);\n\nsize_t gsl_vector_long_max_index (const gsl_vector_long * v);\nsize_t gsl_vector_long_min_index (const gsl_vector_long * v);\nvoid gsl_vector_long_minmax_index (const gsl_vector_long * v, size_t * imin, size_t * imax);\n\nint gsl_vector_long_add (gsl_vector_long * a, const gsl_vector_long * b);\nint gsl_vector_long_sub (gsl_vector_long * a, const gsl_vector_long * b);\nint gsl_vector_long_mul (gsl_vector_long * a, const gsl_vector_long * b);\nint gsl_vector_long_div (gsl_vector_long * a, const gsl_vector_long * b);\nint gsl_vector_long_scale (gsl_vector_long * a, const double x);\nint gsl_vector_long_add_constant (gsl_vector_long * a, const double x);\n\nint gsl_vector_long_equal (const gsl_vector_long * u, \n                            const gsl_vector_long * v);\n\nint gsl_vector_long_isnull (const gsl_vector_long * v);\nint gsl_vector_long_ispos (const gsl_vector_long * v);\nint gsl_vector_long_isneg (const gsl_vector_long * v);\nint gsl_vector_long_isnonneg (const gsl_vector_long * v);\n\nINLINE_DECL long gsl_vector_long_get (const gsl_vector_long * v, const size_t i);\nINLINE_DECL void gsl_vector_long_set (gsl_vector_long * v, const size_t i, long x);\nINLINE_DECL long * gsl_vector_long_ptr (gsl_vector_long * v, const size_t i);\nINLINE_DECL const long * gsl_vector_long_const_ptr (const gsl_vector_long * v, const size_t i);\n\n#ifdef HAVE_INLINE\n\nINLINE_FUN\nlong\ngsl_vector_long_get (const gsl_vector_long * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= v->size))\n    {\n      GSL_ERROR_VAL (\"index out of range\", GSL_EINVAL, 0);\n    }\n#endif\n  return v->data[i * v->stride];\n}\n\nINLINE_FUN\nvoid\ngsl_vector_long_set (gsl_vector_long * v, const size_t i, long x)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= v->size))\n    {\n      GSL_ERROR_VOID (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  v->data[i * v->stride] = x;\n}\n\nINLINE_FUN\nlong *\ngsl_vector_long_ptr (gsl_vector_long * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= v->size))\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return (long *) (v->data + i * v->stride);\n}\n\nINLINE_FUN\nconst long *\ngsl_vector_long_const_ptr (const gsl_vector_long * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= v->size))\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return (const long *) (v->data + i * v->stride);\n}\n#endif /* HAVE_INLINE */\n\n__END_DECLS\n\n#endif /* __GSL_VECTOR_LONG_H__ */\n\n\n", "meta": {"hexsha": "aa530989383f21533239137c8a041e7814a13077", "size": 7346, "ext": "h", "lang": "C", "max_stars_repo_path": "gsl-2.6/gsl/gsl_vector_long.h", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gsl-2.6/gsl/gsl_vector_long.h", "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gsl-2.6/gsl/gsl_vector_long.h", "max_forks_repo_name": "ielomariala/Hex-Game", "max_forks_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-30T20:40:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-30T20:40:25.000Z", "avg_line_length": 31.8008658009, "max_line_length": 95, "alphanum_fraction": 0.6717941737, "num_tokens": 1751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23091977351480814, "lm_q2_score": 0.024423090142868222, "lm_q1q2_score": 0.005639774444322873}}
{"text": "/* matrix/gsl_matrix_ushort.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_MATRIX_USHORT_H__\n#define __GSL_MATRIX_USHORT_H__\n\n#if !defined( GSL_FUN )\n#  if !defined( GSL_DLL )\n#    define GSL_FUN extern\n#  elif defined( BUILD_GSL_DLL )\n#    define GSL_FUN extern __declspec(dllexport)\n#  else\n#    define GSL_FUN extern __declspec(dllimport)\n#  endif\n#endif\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_inline.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_vector_ushort.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size1;\n  size_t size2;\n  size_t tda;\n  unsigned short * data;\n  gsl_block_ushort * block;\n  int owner;\n} gsl_matrix_ushort;\n\ntypedef struct\n{\n  gsl_matrix_ushort matrix;\n} _gsl_matrix_ushort_view;\n\ntypedef _gsl_matrix_ushort_view gsl_matrix_ushort_view;\n\ntypedef struct\n{\n  gsl_matrix_ushort matrix;\n} _gsl_matrix_ushort_const_view;\n\ntypedef const _gsl_matrix_ushort_const_view gsl_matrix_ushort_const_view;\n\n/* Allocation */\n\nGSL_FUN gsl_matrix_ushort * \ngsl_matrix_ushort_alloc (const size_t n1, const size_t n2);\n\nGSL_FUN gsl_matrix_ushort * \ngsl_matrix_ushort_calloc (const size_t n1, const size_t n2);\n\nGSL_FUN gsl_matrix_ushort * \ngsl_matrix_ushort_alloc_from_block (gsl_block_ushort * b, \n                                   const size_t offset, \n                                   const size_t n1, \n                                   const size_t n2, \n                                   const size_t d2);\n\nGSL_FUN gsl_matrix_ushort * \ngsl_matrix_ushort_alloc_from_matrix (gsl_matrix_ushort * m,\n                                    const size_t k1, \n                                    const size_t k2,\n                                    const size_t n1, \n                                    const size_t n2);\n\nGSL_FUN gsl_vector_ushort * \ngsl_vector_ushort_alloc_row_from_matrix (gsl_matrix_ushort * m,\n                                        const size_t i);\n\nGSL_FUN gsl_vector_ushort * \ngsl_vector_ushort_alloc_col_from_matrix (gsl_matrix_ushort * m,\n                                        const size_t j);\n\nGSL_FUN void gsl_matrix_ushort_free (gsl_matrix_ushort * m);\n\n/* Views */\n\nGSL_FUN _gsl_matrix_ushort_view \ngsl_matrix_ushort_submatrix (gsl_matrix_ushort * m, \n                            const size_t i, const size_t j, \n                            const size_t n1, const size_t n2);\n\nGSL_FUN _gsl_vector_ushort_view \ngsl_matrix_ushort_row (gsl_matrix_ushort * m, const size_t i);\n\nGSL_FUN _gsl_vector_ushort_view \ngsl_matrix_ushort_column (gsl_matrix_ushort * m, const size_t j);\n\nGSL_FUN _gsl_vector_ushort_view \ngsl_matrix_ushort_diagonal (gsl_matrix_ushort * m);\n\nGSL_FUN _gsl_vector_ushort_view \ngsl_matrix_ushort_subdiagonal (gsl_matrix_ushort * m, const size_t k);\n\nGSL_FUN _gsl_vector_ushort_view \ngsl_matrix_ushort_superdiagonal (gsl_matrix_ushort * m, const size_t k);\n\nGSL_FUN _gsl_vector_ushort_view\ngsl_matrix_ushort_subrow (gsl_matrix_ushort * m, const size_t i,\n                         const size_t offset, const size_t n);\n\nGSL_FUN _gsl_vector_ushort_view\ngsl_matrix_ushort_subcolumn (gsl_matrix_ushort * m, const size_t j,\n                            const size_t offset, const size_t n);\n\nGSL_FUN _gsl_matrix_ushort_view\ngsl_matrix_ushort_view_array (unsigned short * base,\n                             const size_t n1, \n                             const size_t n2);\n\nGSL_FUN _gsl_matrix_ushort_view\ngsl_matrix_ushort_view_array_with_tda (unsigned short * base, \n                                      const size_t n1, \n                                      const size_t n2,\n                                      const size_t tda);\n\n\nGSL_FUN _gsl_matrix_ushort_view\ngsl_matrix_ushort_view_vector (gsl_vector_ushort * v,\n                              const size_t n1, \n                              const size_t n2);\n\nGSL_FUN _gsl_matrix_ushort_view\ngsl_matrix_ushort_view_vector_with_tda (gsl_vector_ushort * v,\n                                       const size_t n1, \n                                       const size_t n2,\n                                       const size_t tda);\n\n\nGSL_FUN _gsl_matrix_ushort_const_view \ngsl_matrix_ushort_const_submatrix (const gsl_matrix_ushort * m, \n                                  const size_t i, const size_t j, \n                                  const size_t n1, const size_t n2);\n\nGSL_FUN _gsl_vector_ushort_const_view \ngsl_matrix_ushort_const_row (const gsl_matrix_ushort * m, \n                            const size_t i);\n\nGSL_FUN _gsl_vector_ushort_const_view \ngsl_matrix_ushort_const_column (const gsl_matrix_ushort * m, \n                               const size_t j);\n\nGSL_FUN _gsl_vector_ushort_const_view\ngsl_matrix_ushort_const_diagonal (const gsl_matrix_ushort * m);\n\nGSL_FUN _gsl_vector_ushort_const_view \ngsl_matrix_ushort_const_subdiagonal (const gsl_matrix_ushort * m, \n                                    const size_t k);\n\nGSL_FUN _gsl_vector_ushort_const_view \ngsl_matrix_ushort_const_superdiagonal (const gsl_matrix_ushort * m, \n                                      const size_t k);\n\nGSL_FUN _gsl_vector_ushort_const_view\ngsl_matrix_ushort_const_subrow (const gsl_matrix_ushort * m, const size_t i,\n                               const size_t offset, const size_t n);\n\nGSL_FUN _gsl_vector_ushort_const_view\ngsl_matrix_ushort_const_subcolumn (const gsl_matrix_ushort * m, const size_t j,\n                                  const size_t offset, const size_t n);\n\nGSL_FUN _gsl_matrix_ushort_const_view\ngsl_matrix_ushort_const_view_array (const unsigned short * base,\n                                   const size_t n1, \n                                   const size_t n2);\n\nGSL_FUN _gsl_matrix_ushort_const_view\ngsl_matrix_ushort_const_view_array_with_tda (const unsigned short * base, \n                                            const size_t n1, \n                                            const size_t n2,\n                                            const size_t tda);\n\nGSL_FUN _gsl_matrix_ushort_const_view\ngsl_matrix_ushort_const_view_vector (const gsl_vector_ushort * v,\n                                    const size_t n1, \n                                    const size_t n2);\n\nGSL_FUN _gsl_matrix_ushort_const_view\ngsl_matrix_ushort_const_view_vector_with_tda (const gsl_vector_ushort * v,\n                                             const size_t n1, \n                                             const size_t n2,\n                                             const size_t tda);\n\n/* Operations */\n\nGSL_FUN void gsl_matrix_ushort_set_zero (gsl_matrix_ushort * m);\nGSL_FUN void gsl_matrix_ushort_set_identity (gsl_matrix_ushort * m);\nGSL_FUN void gsl_matrix_ushort_set_all (gsl_matrix_ushort * m, unsigned short x);\n\nGSL_FUN int gsl_matrix_ushort_fread (FILE * stream, gsl_matrix_ushort * m) ;\nGSL_FUN int gsl_matrix_ushort_fwrite (FILE * stream, const gsl_matrix_ushort * m) ;\nGSL_FUN int gsl_matrix_ushort_fscanf (FILE * stream, gsl_matrix_ushort * m);\nGSL_FUN int gsl_matrix_ushort_fprintf (FILE * stream, const gsl_matrix_ushort * m, const char * format);\n \nGSL_FUN int gsl_matrix_ushort_memcpy(gsl_matrix_ushort * dest, const gsl_matrix_ushort * src);\nGSL_FUN int gsl_matrix_ushort_swap(gsl_matrix_ushort * m1, gsl_matrix_ushort * m2);\n\nGSL_FUN int gsl_matrix_ushort_swap_rows(gsl_matrix_ushort * m, const size_t i, const size_t j);\nGSL_FUN int gsl_matrix_ushort_swap_columns(gsl_matrix_ushort * m, const size_t i, const size_t j);\nGSL_FUN int gsl_matrix_ushort_swap_rowcol(gsl_matrix_ushort * m, const size_t i, const size_t j);\nGSL_FUN int gsl_matrix_ushort_transpose (gsl_matrix_ushort * m);\nGSL_FUN int gsl_matrix_ushort_transpose_memcpy (gsl_matrix_ushort * dest, const gsl_matrix_ushort * src);\n\nGSL_FUN unsigned short gsl_matrix_ushort_max (const gsl_matrix_ushort * m);\nGSL_FUN unsigned short gsl_matrix_ushort_min (const gsl_matrix_ushort * m);\nGSL_FUN void gsl_matrix_ushort_minmax (const gsl_matrix_ushort * m, unsigned short * min_out, unsigned short * max_out);\n\nGSL_FUN void gsl_matrix_ushort_max_index (const gsl_matrix_ushort * m, size_t * imax, size_t *jmax);\nGSL_FUN void gsl_matrix_ushort_min_index (const gsl_matrix_ushort * m, size_t * imin, size_t *jmin);\nGSL_FUN void gsl_matrix_ushort_minmax_index (const gsl_matrix_ushort * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);\n\nGSL_FUN int gsl_matrix_ushort_equal (const gsl_matrix_ushort * a, const gsl_matrix_ushort * b);\n\nGSL_FUN int gsl_matrix_ushort_isnull (const gsl_matrix_ushort * m);\nGSL_FUN int gsl_matrix_ushort_ispos (const gsl_matrix_ushort * m);\nGSL_FUN int gsl_matrix_ushort_isneg (const gsl_matrix_ushort * m);\nGSL_FUN int gsl_matrix_ushort_isnonneg (const gsl_matrix_ushort * m);\n\nGSL_FUN int gsl_matrix_ushort_add (gsl_matrix_ushort * a, const gsl_matrix_ushort * b);\nGSL_FUN int gsl_matrix_ushort_sub (gsl_matrix_ushort * a, const gsl_matrix_ushort * b);\nGSL_FUN int gsl_matrix_ushort_mul_elements (gsl_matrix_ushort * a, const gsl_matrix_ushort * b);\nGSL_FUN int gsl_matrix_ushort_div_elements (gsl_matrix_ushort * a, const gsl_matrix_ushort * b);\nGSL_FUN int gsl_matrix_ushort_scale (gsl_matrix_ushort * a, const double x);\nGSL_FUN int gsl_matrix_ushort_add_constant (gsl_matrix_ushort * a, const double x);\nGSL_FUN int gsl_matrix_ushort_add_diagonal (gsl_matrix_ushort * a, const double x);\n\n/***********************************************************************/\n/* The functions below are obsolete                                    */\n/***********************************************************************/\nGSL_FUN int gsl_matrix_ushort_get_row(gsl_vector_ushort * v, const gsl_matrix_ushort * m, const size_t i);\nGSL_FUN int gsl_matrix_ushort_get_col(gsl_vector_ushort * v, const gsl_matrix_ushort * m, const size_t j);\nGSL_FUN int gsl_matrix_ushort_set_row(gsl_matrix_ushort * m, const size_t i, const gsl_vector_ushort * v);\nGSL_FUN int gsl_matrix_ushort_set_col(gsl_matrix_ushort * m, const size_t j, const gsl_vector_ushort * v);\n/***********************************************************************/\n\n/* inline functions if you are using GCC */\n\nGSL_FUN INLINE_DECL unsigned short   gsl_matrix_ushort_get(const gsl_matrix_ushort * m, const size_t i, const size_t j);\nGSL_FUN INLINE_DECL void    gsl_matrix_ushort_set(gsl_matrix_ushort * m, const size_t i, const size_t j, const unsigned short x);\nGSL_FUN INLINE_DECL unsigned short * gsl_matrix_ushort_ptr(gsl_matrix_ushort * m, const size_t i, const size_t j);\nGSL_FUN INLINE_DECL const unsigned short * gsl_matrix_ushort_const_ptr(const gsl_matrix_ushort * m, const size_t i, const size_t j);\n\n#ifdef HAVE_INLINE\nINLINE_FUN \nunsigned short\ngsl_matrix_ushort_get(const gsl_matrix_ushort * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_VAL(\"first index out of range\", GSL_EINVAL, 0) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_VAL(\"second index out of range\", GSL_EINVAL, 0) ;\n        }\n    }\n#endif\n  return m->data[i * m->tda + j] ;\n} \n\nINLINE_FUN \nvoid\ngsl_matrix_ushort_set(gsl_matrix_ushort * m, const size_t i, const size_t j, const unsigned short x)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_VOID(\"first index out of range\", GSL_EINVAL) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_VOID(\"second index out of range\", GSL_EINVAL) ;\n        }\n    }\n#endif\n  m->data[i * m->tda + j] = x ;\n}\n\nINLINE_FUN \nunsigned short *\ngsl_matrix_ushort_ptr(gsl_matrix_ushort * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n        }\n    }\n#endif\n  return (unsigned short *) (m->data + (i * m->tda + j)) ;\n} \n\nINLINE_FUN \nconst unsigned short *\ngsl_matrix_ushort_const_ptr(const gsl_matrix_ushort * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n        }\n    }\n#endif\n  return (const unsigned short *) (m->data + (i * m->tda + j)) ;\n} \n\n#endif\n\n__END_DECLS\n\n#endif /* __GSL_MATRIX_USHORT_H__ */\n", "meta": {"hexsha": "300e23b46ece49af649092839db4731d9ec32b09", "size": 13469, "ext": "h", "lang": "C", "max_stars_repo_path": "mbsysCopy/win64_include_lib/include/gsl/gsl_matrix_ushort.h", "max_stars_repo_name": "mharding01/augmented-neuromuscular-RT-running", "max_stars_repo_head_hexsha": "7e1ef00d3fdf9cfa9d59fc4f3a6a0e6dd792a834", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mbsysCopy/win64_include_lib/include/gsl/gsl_matrix_ushort.h", "max_issues_repo_name": "mharding01/augmented-neuromuscular-RT-running", "max_issues_repo_head_hexsha": "7e1ef00d3fdf9cfa9d59fc4f3a6a0e6dd792a834", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mbsysCopy/win64_include_lib/include/gsl/gsl_matrix_ushort.h", "max_forks_repo_name": "mharding01/augmented-neuromuscular-RT-running", "max_forks_repo_head_hexsha": "7e1ef00d3fdf9cfa9d59fc4f3a6a0e6dd792a834", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3102493075, "max_line_length": 134, "alphanum_fraction": 0.6728784617, "num_tokens": 3417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23091975234373588, "lm_q2_score": 0.0244230891221166, "lm_q1q2_score": 0.005639773691548155}}
{"text": "#pragma once\n\n#include \"schedule.h\"\n#include <gsl/gsl-lite.hpp>\n#include <range/v3/view/span.hpp>\n#include <vector>\n\nnamespace angonoka {\nstruct Configuration;\n} // namespace angonoka\n\nnamespace angonoka::stun {\nusing ranges::span;\n\n/**\n    Cache-friendly container of views into an array of ints.\n*/\nclass Vector2D {\npublic:\n    /**\n        Default constructor.\n    */\n    Vector2D() noexcept;\n\n    /**\n        Constructor.\n\n        @param data     Array of ints\n        @param spans    Array of spans\n    */\n    Vector2D(\n        std::vector<int16>&& data,\n        std::vector<span<int16>>&& spans) noexcept;\n\n    /**\n        Construct from an array of span sizes.\n\n        @param data     Array of ints\n        @param sizes    Array of span sizes\n    */\n    Vector2D(\n        std::vector<int16>&& data,\n        span<const int16> sizes) noexcept;\n\n    Vector2D(const Vector2D& other);\n    Vector2D& operator=(const Vector2D& other);\n    Vector2D(Vector2D&& other) noexcept;\n    Vector2D& operator=(Vector2D&& other) noexcept;\n    ~Vector2D() noexcept;\n\n    /**\n        Get a span by index.\n\n        @param index Span index\n\n        @return A span of ints.\n    */\n    template <typename T> decltype(auto) operator[](T&& index) const\n    {\n        Expects(!spans.empty());\n        return spans[std::forward<T>(index)];\n    }\n\n    /**\n        Clear the contents of the container.\n    */\n    void clear() noexcept;\n\n    /**\n        Get size of the container.\n\n        @return Size of the container.\n    */\n    [[nodiscard]] std::size_t size() const noexcept;\n\n    /**\n        Check if the container is empty.\n\n        @return True if the container is empty.\n    */\n    [[nodiscard]] bool empty() const noexcept;\n\nprivate:\n    std::vector<int16> data;\n    std::vector<span<int16>> spans;\n};\n\n/**\n    General, read-only information about the schedule.\n\n    @var agent_performance      Agent's speed multipliers\n    @var task_duration          Task durations in seconds\n    @var available_agents       Which agents can perform each task\n    @var dependencies           Task's dependent sub-tasks\n    @var duration_multiplier    Multiply the makespan by this value\n                                to get the duration in seconds\n*/\nstruct ScheduleParams {\n    std::vector<float> agent_performance;\n    std::vector<float> task_duration;\n    Vector2D available_agents;\n    Vector2D dependencies;\n    float duration_multiplier;\n};\n\n/**\n    Construct a valid but naive schedule.\n\n    @param ScheduleParams An instance of ScheduleParams\n\n    @return A valid schedule\n*/\nstd::vector<ScheduleItem>\ninitial_schedule(const ScheduleParams& params);\n\n/**\n    Construct ScheduleParams from Configuration.\n\n    @param config An instance of Configuration\n\n    @return ScheduleParams\n*/\nScheduleParams to_schedule_params(const Configuration& config);\n} // namespace angonoka::stun\n", "meta": {"hexsha": "4acef294b32dd86ca7853ece99c99ae9150a2cb7", "size": 2859, "ext": "h", "lang": "C", "max_stars_repo_path": "src/stun/schedule_params.h", "max_stars_repo_name": "coffee-lord/angonoka", "max_stars_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-10-23T18:05:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T21:53:24.000Z", "max_issues_repo_path": "src/stun/schedule_params.h", "max_issues_repo_name": "coffee-lord/angonoka", "max_issues_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2022-02-12T19:52:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-12T19:55:52.000Z", "max_forks_repo_path": "src/stun/schedule_params.h", "max_forks_repo_name": "coffee-lord/angonoka", "max_forks_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.872, "max_line_length": 68, "alphanum_fraction": 0.6369359916, "num_tokens": 644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25683199138751883, "lm_q2_score": 0.02194825191556434, "lm_q1q2_score": 0.005637013246949315}}
{"text": "#include <bindings.cmacros.h>\n#include <gsl/gsl_sf.h>\n\nBC_INLINE1(GSL_MODE_PREC,gsl_mode_t,unsigned)\n", "meta": {"hexsha": "a6740f437e4b9709c4e200fceb2bae528032593d", "size": 101, "ext": "c", "lang": "C", "max_stars_repo_path": "bindings-gsl/src/Bindings/Gsl/SpecialFunctions.c", "max_stars_repo_name": "flip111/bindings-dsl", "max_stars_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2015-04-29T00:31:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T09:29:03.000Z", "max_issues_repo_path": "bindings-gsl/src/Bindings/Gsl/SpecialFunctions.c", "max_issues_repo_name": "flip111/bindings-dsl", "max_issues_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2015-01-04T06:32:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-07T09:49:12.000Z", "max_forks_repo_path": "bindings-gsl/src/Bindings/Gsl/SpecialFunctions.c", "max_forks_repo_name": "flip111/bindings-dsl", "max_forks_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2015-01-03T20:43:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-10T19:31:38.000Z", "avg_line_length": 20.2, "max_line_length": 45, "alphanum_fraction": 0.801980198, "num_tokens": 30, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22000710997428738, "lm_q2_score": 0.025565212531223618, "lm_q1q2_score": 0.005624528524872944}}
{"text": "/*--------------------------------------------------------------------\n * $Id$\n * \n * This file is part of libRadtran.\n * Copyright (c) 1997-2012 by Arve Kylling, Bernhard Mayer,\n *                            Claudia Emde, Robert Buras\n *\n * ######### Contact info: http://www.libradtran.org #########\n *\n * This program is free software; you can redistribute it and/or \n * modify it under the terms of the GNU General Public License   \n * as published by the Free Software Foundation; either version 2\n * of the License, or (at your option) any later version.        \n * \n * This program is distributed in the hope that it will be useful, \n * but WITHOUT ANY WARRANTY; without even the implied warranty of  \n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the   \n * GNU General Public License for more details.                    \n * \n * You should have received a copy of the GNU General Public License          \n * along with this program; if not, write to the Free Software                \n * Foundation, Inc., 59 Temple Place - Suite 330, \n * Boston, MA 02111-1307, USA.\n *--------------------------------------------------------------------*/\n\n#include <math.h>\n#include <string.h>\n#include <time.h>\n#include <assert.h>\n\n#include \"solve_rte.h\"\n#include \"uvspec.h\"\n#include \"uvspecrandom.h\"\n#include \"ascii.h\"\n#include \"ancillary.h\"\n#include \"numeric.h\"\n#include \"fortran_and_c.h\"\n#include \"cloud.h\"\n#include \"molecular.h\"\n#include \"rodents.h\"\n#include \"twostrebe.h\"\n#include \"twomaxrnd.h\"\n#include \"dynamic_twostream.h\"\n#include \"dynamic_tenstream.h\"\n#if HAVE_TWOMAXRND3C\n#include \"twomaxrnd3C.h\"\n#endif\n#include \"cdisort.h\"\n#include \"c_tzs.h\"\n#include \"sslidar.h\"\n#include \"errors.h\"\n#include \"Corefinder.h\"\n#include \"LinArray.h\"\n#include \"wcloud3d.h\"\n#include \"allocnd.h\"\n#include \"redistribute.h\"\n\n#if HAVE_MYSTIC\n#include \"mystic.h\"\n#endif\n#if HAVE_TIPA\n#include \"tipa.h\"\n#endif\n#if HAVE_SOS\n#include \"sos.h\"\n#endif\n\n#include \"f77-uscore.h\"\n#include \"solver.h\"\n\n#ifndef PI\n#define PI 3.14159265358979323846264338327\n#endif\n\n#if HAVE_LIBGSL\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_diff.h>\n#endif\n\n/* Definitions for numerical recipes functions */\n#define NRANSI\n#define SIGN(a, b) ((b) >= 0.0 ? fabs (a) : -fabs (a))\n\n/* internal structures */\ntypedef struct {\n  char*       deltam;\n  char*       ground_type;\n  char        polscat[15];\n  pol_complex ground_index;\n  double      albedo;\n  double      btemp;\n  double      flux;\n  double*     gas_extinct;\n  double*     height;\n  double      mu;\n  double      sky_temp;\n  double*     temperatures;\n  double      wavelength;\n  int*        outlevels;\n  int         nummu; /* Number of quadrature angles (per hemisphere). */\n} polradtran_input;\n\ntypedef struct {\n  char header[127]; /* A 127- (or less) character header for prints         */\n\n  float accur; /* Convergence criterion for azimuthal series.          */\n\n  float fbeam; /* Intensity of incident parallel beam at top boundary. */\n               /*  [same units as PLKAVG (default W/sq m) if thermal   */\n               /*  sources active, otherwise arbitrary units].         */\n\n  float fisot; /* Intensity of top-boundary isotropic illumination.    */\n               /*  [same units as PLKAVG (default W/sq m) if thermal   */\n               /*  sources active, otherwise arbitrary units].         */\n               /*  Corresponding incident flux is pi (3.14159...)      */\n               /*  times FISOT.                                        */\n\n  float* hl; /* K = 0 to NSTR.  Coefficients in Legendre-            */\n             /* polynomial expansion of bottom bidirectional         */\n             /* reflectivity                                         */\n\n  int planck; /* TRUE,  include thermal emission                      */\n              /* FALSE, ignore thermal emission (saves computer time) */\n\n  float btemp; /* Temperature of bottom boundary (K)                   */\n               /* (bottom emissivity is calculated from ALBEDO or HL,  */\n               /* so it need not be specified).                        */\n               /* Needed only if PLANK is TRUE.                        */\n\n  float ttemp; /* Temperature of top boundary (K)                      */\n               /* Needed only if PLANK is TRUE.                        */\n\n  float temis; /* Emissivity of top boundary.                          */\n               /* Needed only if PLANK is TRUE.                        */\n\n  float* utau;\n  float  umu0;\n\n  int ierror_d[47];\n  int ierror_s[33];\n  int ierror_t[22];\n\n  int prndis[7];\n  int prndis2[5];\n  int prntwo[2];\n\n  int ibcnd; /* 0 : General case.                                    */\n             /* 1 : Return only albedo and transmissivity of the     */\n             /*     entire medium vs. incident beam angle.           */\n\n  int lamber; /* TRUE, isotropically reflecting bottom boundary.      */\n              /* FALSE, bidirectionally reflecting bottom boundary.   */\n\n  int onlyfl; /* TRUE, return fluxes, flux divergences, and mean      */\n              /*       intensities.                                   */\n              /* FALSE, return fluxes, flux divergences, mean         */\n              /*        intensities, azimuthally averaged intensities */\n              /*        (at the user angles) AND intensities.         */\n\n  int quiet;\n  int usrang;\n  int usrtau;\n\n  /* sdisort-specific variables */\n  int nil;\n  int newgeo;\n  int spher;\n\n  /* qdisort-specific variables */\n  int       gsrc;  /* Flag for general source for qdisort */\n  double*** qsrc;  /* The general source, in FORTRAN: REAL*4 qsrc( MXCMU, 0:MXULV, MXCMU )*/\n                   /* At computational angles                                             */\n  double*** qsrcu; /* The general source, in FORTRAN: REAL*4 qsrc( MXUMU, 0:MXULV, MXCMU )*/\n                   /* At user angles                                                      */\n\n  /* PolRadtran-specific variables */\n  polradtran_input pol;\n\n} rte_input;\n\ntypedef struct {\n  float*   dfdt;\n  float*   flup;\n  float*   rfldir;\n  float*   rfldn;\n  float*   uavgso;\n  float*   uavgdn;\n  float*   uavgup;\n  float*   uavg;\n  float*   heat;\n  float*   emis;\n  float*   w_zout;\n  float**  u0u;\n  float*** uu;\n  float*** uum; /* Fourier components of intensities, returned by qdisort */\n  float*   sslidar_nphot;\n  float*   sslidar_nphot_q;\n  float*   sslidar_ratio;\n\n  float***    rfldir3d;\n  float***    rfldn3d;\n  float***    flup3d;\n  float*****  fl3d_is; /* importance sampling */\n  float***    uavgso3d;\n  float***    uavgdn3d;\n  float***    uavgup3d;\n  float***    abs3d;\n  float***    absback3d;\n  float****   radiance3d;\n  float****** radiance3d_is; /*importance sampling*/\n  float****** jacobian;\n\n  /* corresponding variances */\n  float***  rfldir3d_var;\n  float***  rfldn3d_var;\n  float***  flup3d_var;\n  float***  uavgso3d_var;\n  float***  uavgdn3d_var;\n  float***  uavgup3d_var;\n  float***  abs3d_var;\n  float***  absback3d_var;\n  float**** radiance3d_var;\n\n  float* albmed;\n  float* trnmed;\n\n  double**   polradtran_down_flux;\n  double**   polradtran_up_flux;\n  double**** polradtran_down_rad_q; /* _q indicates radiances at quadrature angels. */\n  double**** polradtran_up_rad_q;\n  double**** polradtran_down_rad;\n  double**** polradtran_up_rad;\n  double*    polradtran_mu_values;\n\n  // triangular surface output\n  struct t_triangle_radiation_field* triangle_results;\n} rte_output;\n\ntypedef struct {\n  float* tauw;\n  float* taui;\n\n  float* g1d;\n  float* g2d;\n  float* fd;\n  float* g1i;\n  float* g2i;\n  float* fi;\n\n  float* ssaw;\n  float* ssai;\n} save_optprop;\n\ntypedef struct {\n  double**   dtauc;\n  double*    fbeam;\n  double**** uum;\n  double **  uavgso, **uavgdn, **uavgup;\n  double **  rfldir, **rfldn, **flup;\n  double***  u0u;\n  double**** uu;\n} raman_qsrc_components;\n\n/* prototypes of internal functions */\nstatic int         reverse_profiles (input_struct input, output_struct* output);\nstatic rte_output* calloc_rte_output (input_struct input,\n                                      int          nzout,\n                                      int          Nxcld,\n                                      int          Nycld,\n                                      int          Nzcld,\n                                      int          Ncsample,\n                                      int          Nlambda,\n                                      int          Nxsample,\n                                      int          Nysample,\n                                      int          Nlyr,\n                                      int*         threed,\n                                      int          passback3D,\n                                      const size_t N_triangles);\n\nstatic int reset_rte_output (rte_output** rte,\n                             input_struct input,\n                             int          nzout,\n                             int          Nxcld,\n                             int          Nycld,\n                             int          Nzcld,\n                             int          Nxsample,\n                             int          Nysample,\n                             int          Ncsample,\n                             int          Nlambda,\n                             int          Nlyr,\n                             int*         threed,\n                             int          passback3D,\n                             const size_t N_triangles);\n\nstatic int free_rte_output (rte_output*  result,\n                            input_struct input,\n                            int          nzout,\n                            int          Nxcld,\n                            int          Nycld,\n                            int          Nzcld,\n                            int          Nxsample,\n                            int          Nysample,\n                            int          Ncsample,\n                            int          Nlyr,\n                            int          Nlambda,\n                            int*         threed,\n                            int          passback3D);\n\nstatic int  add_rte_output (rte_output*        rte,\n                            const rte_output*  add,\n                            const double       factor,\n                            const double*      factor_spectral,\n                            const input_struct input,\n                            const int          nzout,\n                            const int          Nxcld,\n                            const int          Nycld,\n                            const int          Nzcld,\n                            const int          Nc,\n                            const int          Nlyr,\n                            const int          Nlambda,\n                            const int*         threed,\n                            const int          passback3D,\n                            const int          islower,\n                            const int          isupper,\n                            const int          jslower,\n                            const int          jsupper,\n                            const int          isstep,\n                            const int          jsstep);\nstatic int  init_rte_input (rte_input* rte, input_struct input, output_struct* output);\nstatic int  setup_and_call_solver (input_struct           input,\n                                   output_struct*         output,\n                                   rte_input*             rte_in,\n                                   rte_output*            rte_out,\n                                   raman_qsrc_components* raman_qsrc_components,\n                                   int                    iv,\n                                   int                    ib,\n                                   int                    ir,\n                                   int*                   threed,\n                                   int                    mc_loaddata);\nstatic int  call_solver (input_struct           input,\n                         output_struct*         output,\n                         int                    rte_solver,\n                         rte_input*             rte_in,\n                         raman_qsrc_components* raman_qsrc_components,\n                         int                    iv,\n                         int                    ib,\n                         int                    ir,\n                         rte_output*            rte_out,\n                         int*                   threed,\n                         int                    mc_loaddata,\n                         int                    verbose);\nstatic void fourier2azimuth (double**** down_rad_rt3,\n                             double**** up_rad_rt3,\n                             double**** down_rad,\n                             double**** up_rad,\n                             int        nzout,\n                             int        aziorder,\n                             int        nstr,\n                             int        numu,\n                             int        nstokes,\n                             int        nphi,\n                             float*     phi);\n\nstatic int calc_spectral_heating (input_struct   input,\n                                  output_struct* output,\n                                  float*         dz,\n                                  double*        rho_mass_zout,\n                                  float*         k_abs,\n                                  float*         k_abs_layer,\n                                  int*           zout_index,\n                                  rte_output*    rte_out,\n                                  float*         heat,\n                                  float*         emis,\n                                  float*         w_zout,\n                                  int            iv);\n\nstatic float*** calloc_abs3d (int Nx, int Ny, int Nz, int* threed);\n\nstatic void free_abs3d (float*** abs3d, int Nx, int Ny, int Nz, int* threed);\n\nstatic float**** calloc_spectral_abs3d (int Nx, int Ny, int Nz, int nlambda, int* threed);\n\ndouble get_unit_factor (input_struct input, output_struct* output, int iv);\n\nstatic int\ngenerate_effective_cloud (input_struct input, output_struct* output, save_optprop* save_cloud, int iv, int iq, int verbose);\n\nstatic int set_raman_source (double***              qsrc,\n                             double***              qsrcu,\n                             int                    maxphi,\n                             int                    nlev,\n                             int                    nzout,\n                             int                    nstr,\n                             int                    n_shifts,\n                             float                  wanted_wl,\n                             double*                wl_shifts,\n                             float                  umu0,\n                             float*                 zd,\n                             float*                 zout,\n                             float                  zenang,\n                             float                  fbeam,\n                             float                  radius,\n                             float*                 dens,\n                             double**               crs_RL,\n                             double**               crs_RG,\n                             float*                 ssalb,\n                             int                    numu,\n                             float*                 umu,\n                             int                    usrang,\n                             int*                   cmuind,\n                             float***               pmom,\n                             raman_qsrc_components* raman_qsrc_components,\n                             int*                   zout_comp_index,\n                             float                  altitude,\n                             int                    last,\n                             int                    verbose);\n\nstatic save_optprop* calloc_save_optprop (int Nlev);\n\nraman_qsrc_components* calloc_raman_qsrc_components (int raman_fast, int nzout, int maxumu, int nphi, int nstr, int nlambda_shift);\n\nstatic void free_raman_qsrc_components (raman_qsrc_components* result, int raman_fast, int nzout, int maxumu, int nphi, int nstr);\n\nvoid F77_FUNC (swde, SWDE) (float* g_scaled,\n                            float* pref,\n                            float* prmuz,\n                            float* tau,\n                            float* ssa_gas,\n                            float* pre1,\n                            float* pre2,\n                            float* ptr1,\n                            float* ptr2);\n\nfloat zbrent_taueff (float mu_eff,\n                     float g_scaled,\n                     float ssa_gas,\n                     float transmission_cloud,\n                     float transmission_layer,\n                     float x1,\n                     float x2,\n                     float tol);\n\nvoid F77_FUNC (qgausn, QGAUSN) (int* n, float* cmu, float* cwt);\nvoid F77_FUNC (lepolys, LEPOLYS) (int* nn, int* mazim, int* mxcmu, int* nstr, float* cmu, float* ylmc);\n\n/*********************************************************************/\n/* Main function. Loop over wavelengths or wavelength bands,         */\n/* correlated-k quadrature points, and independent pixels.           */\n/*********************************************************************/\n\nint solve_rte (input_struct input, output_struct* output) {\n  static int first  = TRUE;\n  int        status = 0, add = 0;\n  int        isp = 0, ipa = 0, is = 0, js = 0, ks = 0, ivs = 0, iv_alis = 0, iv_alis_ref = 0;\n\n  int       iipa = 0, jipa = 0;\n  int       iv = 0, iu = 0, j = 0, lu = 0, ip = 0, iz = 0, ic = 0;\n  int       iq = 0, lc = 0, nr = 0, ir = 0, irs = 0;\n  int       ijac        = 0;\n  int       lower_wl_id = 0, upper_wl_id = 0, lower_iq_id = 0, upper_iq_id = 0, ivr = 0;\n  int       nlambda       = 0;\n  float*    dz            = NULL;\n  double    weight        = 1;\n  double*   rho_mass_zout = NULL;\n  float*    k_abs         = NULL;\n  float*    k_abs_layer   = NULL;\n  float*    k_abs_outband = NULL;\n  int       mc_loaddata   = 1;\n  double    weight2       = 0;\n  double    unit_factor   = 0;\n  double    ffactor = 0.0, rfactor = 0.0, hfactor = 1.0;\n  double**  u0u_raman    = NULL;\n  double*   uavgso_raman = NULL;\n  double*   uavgdn_raman = NULL;\n  double*   uavgup_raman = NULL;\n  double*   rfldir_raman = NULL;\n  double*   rfldn_raman  = NULL;\n  double*   flup_raman   = NULL;\n  double*** uu_raman     = NULL; /* The radiance at user angles for the general source for qdisort */\n                                 /* Only used if raman scattering is on                            */\n\n  /* float heating_rate_emission = 0.0; */\n\n  rte_input*  rte_in      = NULL;\n  rte_output* rte_out     = NULL;\n  rte_output* rte_outband = NULL;\n\n  save_optprop*          save_cloud            = NULL;\n  raman_qsrc_components* raman_qsrc_components = NULL;\n\n  char function_name[] = \"solve_rte\";\n  char file_name[]     = \"solve_rte.c\";\n\n  double* weight_spectral = NULL;\n\n  //FIX 3DAbs not initialized when aerosol setup not done, should be redundant now\n  // output->mc.alis.Nc = 1;\n\n  if (first) {\n    first = FALSE;\n\n    /* this is not the right place to do this! This should be done somewhere else! Please clean up! BCA */\n    if (input.ipa3d) {\n      output->mc.sample.passback3D = 1; /* like for mystic, I set passback3d to 1 */\n\n      /* ipa3d and tipa were configured and tested only with 3D-cloudfiles containing lwc and reff, thus check: */\n      for (isp = 0; isp < input.n_caoth; isp++)\n        if (!(output->caoth3d[isp].cldproperties == 3 || output->caoth3d[isp].cldproperties == 4)) {\n          fprintf (stderr, \"Error: ipa3d/tipa does not work with cldproperties flag different from 3\\n\");\n          return -1;\n        }\n\n      /* finally, we add normalization to the number of pixels to ipaweight, BM 3.7.2020 */\n      /* ipaweight[] either considers cloudcover or normalization for ipa3d              */\n      for (ipa = 0; ipa < output->nipa; ipa++)\n        output->ipaweight[ipa] /= ((double)output->niipa * (double)output->njipa);\n    }\n\n    rte_in = calloc (1, sizeof (rte_input));\n\n    rte_out = calloc_rte_output (input,\n                                 output->atm.nzout,\n                                 output->atm.Nxcld,\n                                 output->atm.Nycld,\n                                 output->atm.Nzcld,\n                                 output->mc.sample.Nx,\n                                 output->mc.sample.Ny,\n                                 output->mc.alis.Nc,\n                                 output->mc.alis.nlambda_abs,\n                                 output->atm.nlev - 1,\n                                 output->atm.threed,\n                                 output->mc.sample.passback3D,\n                                 output->mc.triangular_surface.N_triangles);\n\n    rte_outband = calloc_rte_output (input,\n                                     output->atm.nzout,\n                                     output->atm.Nxcld,\n                                     output->atm.Nycld,\n                                     output->atm.Nzcld,\n                                     output->mc.sample.Nx,\n                                     output->mc.sample.Ny,\n                                     output->mc.alis.Nc,\n                                     output->mc.alis.nlambda_abs,\n                                     output->atm.nlev - 1,\n                                     output->atm.threed,\n                                     output->mc.sample.passback3D,\n                                     output->mc.triangular_surface.N_triangles);\n\n    save_cloud = calloc_save_optprop (output->atm.nlev);\n\n    /* initialize RTE input */\n    status = init_rte_input (rte_in, input, output);\n    if (status != 0) {\n      fprintf (stderr, \"Error %d initializing rte input in %s (%s)\\n\", status, function_name, file_name);\n      return status;\n    }\n\n    /* allocate memory for the output result structures */\n    status = setup_result (input, output, &dz, &rho_mass_zout, &k_abs_layer, &k_abs, &k_abs_outband);\n    if (status != 0) {\n      fprintf (stderr, \"Error %d allocating memory for the model output in %s (%s)\\n\", status, function_name, file_name);\n      return status;\n    }\n\n    if (input.raman) {\n      nr = 2;\n\n      if ((status = ASCII_calloc_double_3D (&uu_raman, output->atm.nzout, input.rte.nphi, input.rte.numu)) != 0)\n        return status;\n      if ((status = ASCII_calloc_double (&u0u_raman, output->atm.nzout, input.rte.numu)) != 0)\n        return status;\n      uavgso_raman = calloc (output->atm.nzout, sizeof (double));\n      uavgdn_raman = calloc (output->atm.nzout, sizeof (double));\n      uavgup_raman = calloc (output->atm.nzout, sizeof (double));\n      rfldir_raman = calloc (output->atm.nzout, sizeof (double));\n      rfldn_raman  = calloc (output->atm.nzout, sizeof (double));\n      flup_raman   = calloc (output->atm.nzout, sizeof (double));\n\n      /* Number of wavelength shifts considered is independent of primary wavelength, */\n      /* hence use output->atm.nq_t[0] below                                          */\n      if (input.raman_fast)\n        nlambda = output->wl.nlambda_r;\n      else\n        nlambda = output->crs.number_of_ramanwavelengths;\n      raman_qsrc_components = calloc_raman_qsrc_components (input.raman_fast,\n                                                            output->atm.nzout,\n                                                            input.rte.maxumu,\n                                                            input.rte.nphi,\n                                                            input.rte.nstr,\n                                                            nlambda);\n    } else {\n      nr = 1;\n    }\n  }\n\n  if (input.raman) {\n    /* For Raman scattering only include wavelengths that the user asked. */\n    /* Internally we have to include more wavelengths to account for      */\n    /* Raman scattered radiation, see loop over quadrature points below.  */\n\n    lower_wl_id = output->wl.raman_start_id;\n    upper_wl_id = output->wl.raman_end_id;\n  } else {\n    lower_wl_id = output->wl.nlambda_rte_lower;\n    upper_wl_id = output->wl.nlambda_rte_upper;\n  }\n\n  /* concentration importance sampling */\n  if (input.rte.mc.concentration_is) {\n    weight_spectral    = calloc (1, sizeof (double));\n    weight_spectral[0] = 1.0;\n  }\n\n  if (input.rte.mc.spectral_is) {\n\n    weight_spectral = calloc (output->mc.alis.nlambda_abs, sizeof (double));\n    /* Take wavelength in center of spectrum if not specified explicitly, FIXCE should also check whether absorption is not too high here */\n    if (input.rte.mc.spectral_is_wvl[0] == 0.) {\n      lower_wl_id                    = (int)(0.5 * ((float)output->wl.nlambda_rte_lower + (float)output->wl.nlambda_rte_upper));\n      output->mc.alis.nlambda_ref    = 1;\n      output->mc.alis.ilambda_ref    = calloc (1, sizeof (int));\n      output->mc.alis.ilambda_ref[0] = lower_wl_id;\n    }\n\n    else if (input.rte.mc.spectral_is_wvl[0] > 0.) {\n      /* Find wavelength index for specified wavelength */\n      lower_wl_id = 0;\n      for (iv_alis = 0; iv_alis < output->mc.alis.nlambda_abs; iv_alis++) {\n        if (output->mc.alis.lambda[iv_alis] > input.rte.mc.spectral_is_wvl[0]) {\n          lower_wl_id                    = iv_alis - 1;\n          output->mc.alis.nlambda_ref    = 1;\n          output->mc.alis.ilambda_ref    = calloc (1, sizeof (int));\n          output->mc.alis.ilambda_ref[0] = lower_wl_id;\n          break;\n        }\n      }\n    } else {\n      /* several calc wvls do not work so far */\n      lower_wl_id                 = (int)(0.5 * ((float)output->wl.nlambda_rte_lower + (float)output->wl.nlambda_rte_upper));\n      output->mc.alis.nlambda_ref = input.rte.mc.spectral_is_nwvl;\n      output->mc.alis.ilambda_ref = calloc (output->mc.alis.nlambda_ref, sizeof (int));\n      for (iv_alis_ref = 0; iv_alis_ref < output->mc.alis.nlambda_ref; iv_alis_ref++) {\n        for (iv_alis = 0; iv_alis < output->mc.alis.nlambda_abs; iv_alis++) {\n          if (output->mc.alis.lambda[iv_alis] > input.rte.mc.spectral_is_wvl[iv_alis_ref]) {\n            output->mc.alis.ilambda_ref[iv_alis_ref] = iv_alis;\n          }\n        }\n      }\n    }\n\n    upper_wl_id = lower_wl_id;\n    if (!input.quiet) {\n      fprintf (stderr, \"... ALIS calculation wavelength: %g nm \\n\", output->mc.alis.lambda[lower_wl_id]);\n      if (output->mc.alis.nlambda_ref > 1)\n        for (iv_alis_ref = 1; iv_alis_ref < output->mc.alis.nlambda_ref; iv_alis_ref++) {\n          fprintf (stderr,\n                   \"... helper ALIS wavelength: %g nm \\n\",\n                   output->mc.alis.lambda[output->mc.alis.ilambda_ref[iv_alis_ref]]);\n        }\n    }\n  }\n\n#if HAVE_TIPA\n  /* ulrike: TIPA DIR. The \"tilted cloud matrix\" is used only for the\n                       calculation of the DIRECT radiation Tilting for\n                       every z-level is done here (outside the loop\n                       over the wavelength)  */\n  if (input.tipa == TIPA_DIR || input.rte.mc.tipa == TIPA_DIR) {\n    for (isp = 0; isp < input.n_caoth; isp++)\n      if (input.caoth[isp].source == CAOTH_FROM_3D) {\n        if (!input.quiet)\n          fprintf (stderr, \" ... performing the tilting for tipa dir (water clouds)\\n\");\n        status = tipa_dirtilt (&(output->caoth3d[isp]),\n                               output->atm,\n                               output->alt,\n                               &(output->caoth[isp].tipa),\n                               input.tipa,\n                               input.atm.sza,\n                               input.atm.phi0,\n                               lower_wl_id,\n                               upper_wl_id,\n                               input.rte.mc.tipa);\n        if (status)\n          return fct_err_out (status, \"tipa_dirtilt\", ERROR_POSITION);\n      }\n  }\n#endif\n\n  /************************/\n  /* loop over wavelength */\n  /************************/\n  int iv_count = 0;\n  for (iv = lower_wl_id; iv <= upper_wl_id; iv++) {\n\n    /***********************************************************/\n    /* iterate over wavelengths, required for raman scattering */\n    /***********************************************************/\n\n    irs = 0;\n    if (input.raman_fast && iv > lower_wl_id)\n      irs = 1; /* AK20110407: All the elastic wavelengths are done for  */\n               /* iv=lower_wl_id and stored. Thus only need to do       */\n               /* the inelastic part for remaining wavelengths.         */\n\n    for (ir = irs; ir < nr; ir++) {\n\n      /* solar zenith angle at this wavelength */\n      rte_in->umu0 = cos (output->atm.sza_r[iv] * PI / 180.0);\n\n      /* calculate 3D caoth properties for this wavelength */\n\n      if (input.rte.solver == SOLVER_MONTECARLO || input.rte.solver == SOLVER_DYNAMIC_TENSTREAM) {\n        int isp_hiddencore = -1, isp_wc3D = -1;\n        for (isp = 0; isp < input.n_caoth; isp++) {\n          if (strcmp (input.caoth[isp].name, \"molecular_3d\") != 0) {\n            status = convert_caoth_mystic (input, input.caoth[isp], output, &(output->caoth[isp]), &(output->caoth3d[isp]), iv);\n            if (status)\n              return fct_err_out (status, \"convert_caoth_mystic\", ERROR_POSITION);\n\n            if (strcmp (input.caoth[isp].name, \"hiddencore_dummy\") == 0)\n              isp_hiddencore = isp;\n\n            if (strcmp (input.caoth[isp].name, \"wc\") == 0)\n              isp_wc3D = isp;\n          }\n        }\n\n        /**\n           Section to find the veiled core. Author: Paul Ockenfu\u00df, Bernhard Mayer\n           Modifies the parameters ext, g1, g2, ssa and ff in the profiles \"wc\" and \"hiddencore_dummy\"\n           Important developer information: Units in caoth3d: ext[...] 1/m; atm.dxcld & atm.dycld in m, atm.zd_common in km!\n           -z-Index=\"0\" means surface in caoth3d.\n           -z-Index=\"0\" means TOA in \"atm\"!\n        */\n        if (input.rte.mc.core_isactive && (iv_count == 0 || output->caoth3d[isp_wc3D].cldproperties == CLD_LWCREFF ||\n                                           output->caoth3d[isp_wc3D].cldproperties == CLD_LWCREFFCF)) {\n          assert (isp_hiddencore >= 0);\n          assert (isp_wc3D >= 0);\n          assert ((output->caoth3d[isp_wc3D]).nthreed > 0);\n          assert ((output->caoth3d[isp_hiddencore]).nthreed > 0);\n          if (!input.quiet)\n            fprintf (stderr, \"Found wc3D; starting to modify core\\n\");\n          int      nx     = (output->caoth3d[isp_wc3D]).Nx;\n          int      ny     = (output->caoth3d[isp_wc3D]).Ny;\n          int      nz     = (output->caoth3d[isp_wc3D]).nlyr;\n          int*     threed = (output->caoth3d[isp_wc3D]).threed;\n          float    dx = output->atm.dxcld, dy = output->atm.dycld;\n          float*** core;\n          float*** distances;\n          if (!(distances = calloc_float_3D (nz, nx, ny, \"distances\")))\n            return -1;\n\n          if (input.rte.mc.core_inputfile) { /*If the user specified the cloud core*/\n            int    core_nx, core_ny, core_nz, core_rows, core_flag = 0, status = 0;\n            double core_dx, core_dy;\n            float* core_dz;\n            status = read_3D_caoth_header (input.rte.mc.core_inputfile,\n                                           &core_nx,\n                                           &core_ny,\n                                           &core_nz,\n                                           &core_flag,\n                                           &core_dx,\n                                           &core_dy,\n                                           &core_dz,\n                                           &core_rows);\n            if (status != 0) {\n              return -1;\n            }\n            if (core_flag != 4) {\n              fprintf (\n                stderr,\n                \"!!Warning: when reading %s, another flag than 4 was found! Is this really a file describing a cloud core?\\n\",\n                input.rte.mc.core_inputfile);\n            }\n            core_dx *= 1000;\n            core_dy *= 1000;\n            if (nx != core_nx || ny != core_ny || dx != core_dx || dy != core_dy) {\n              fprintf (stderr,\n                       \"Error when reading core profile %s: The horizontal grid of the core must be the same as in wc_file 3D!\\n\",\n                       input.rte.mc.core_inputfile);\n              return -1;\n            }\n            float*** column4;\n            int*     core_threed = calloc (core_nz, sizeof (int));\n            if (!(column4 = calloc_float_3D (core_nz, core_nx, core_ny, \"column4\")))\n              return -1;\n            int* indz = calloc (core_rows - 2, sizeof (int));\n            status    = read_3D_caoth_data (input.rte.mc.core_inputfile,\n                                         core_nx,\n                                         core_ny,\n                                         core_nz,\n                                         core_rows,\n                                         &column4,\n                                         NULL,\n                                         NULL,\n                                         NULL,\n                                         NULL,\n                                         indz);\n            if (status != 0) {\n              return -1;\n            }\n            for (size_t i = 0; i < core_rows - 2; i++) {\n              core_threed[indz[i]] = 1;\n            }\n\n            status = redistribute_3D (&column4, nx, ny, core_dz, core_nz, output->atm.zd_common, nz, core_threed, threed, 0);\n            core   = column4;\n\n            free (indz);\n            free (core_threed);\n          } else { /*If the user specified no cloud core, start the corefinder*/\n            if (!(core = calloc_float_3D (nz, nx, ny, \"core\")))\n              return -1;\n            // Initialize array with scattering coefficients from wc3D profile\n            // This profile can contain layers which are not 3D. They are coming from interpolation\n            // to other grids (e.g. ic_file). Therefore, wc scattering is always zero in these layers.\n            arr3d_f* k_scat = calloc3d_float (nx, ny, nz);\n            for (size_t i = 0; i < k_scat->nx; i++) {\n              for (size_t j = 0; j < k_scat->ny; j++) {\n                for (size_t k = 0; k < k_scat->nz; k++) {\n                  if ((output->caoth3d[isp_wc3D]).threed[k])\n                    set3d_f (k_scat,\n                             i,\n                             j,\n                             k,\n                             ((output->caoth3d[isp_wc3D]).ext[k][i][j]) * ((output->caoth3d[isp_wc3D]).ssa[k][i][j]));\n                  else\n                    set3d_f (k_scat, i, j, k, 0.0);\n                }\n              }\n            }\n            //calculate layer distances in atmosphere\n            float* deltaz = malloc (k_scat->nz * sizeof (float));\n            for (size_t i = 0; i < k_scat->nz; i++)\n              deltaz[i] =\n                1000 * (output->atm.zd_common[k_scat->nz - i - 1] - output->atm.zd_common[k_scat->nz - i]);  //convert to meters\n\n            // Calculate starting points for the corefinder: every specified zout-level will create one xy-layer of starting points\n            // Notebook entry 21\n            size_t  total_starts = output->atm.nzout_user * k_scat->nx * k_scat->ny;\n            size_t* xstart       = calloc (total_starts, sizeof (size_t));\n            size_t* ystart       = calloc (total_starts, sizeof (size_t));\n            size_t* zstart       = calloc (total_starts, sizeof (size_t));\n            size_t* z_index      = calloc (output->atm.nzout_user, sizeof (size_t));\n\n            int iz_index = 0;\n            int kc       = 0;\n            for (kc = 0; kc < (output->caoth3d[isp_wc3D]).nlyr; kc++)\n              if (output->mc.sample.sample[kc])\n                z_index[iz_index++] = kc;\n\n            // At TOA, the first layer below TOA is used for starting points\n            if (output->mc.sample.sample[kc])\n              z_index[iz_index++] = kc - 1;\n\n            if (!input.quiet) {\n              fprintf (stderr, \"Corefinder starting points:\\n\");\n              for (size_t i = 0; i < output->atm.nzout_user; i++)\n                fprintf (stderr, \"%d\\n\", (int)z_index[i]);\n            }\n\n            // consistency check\n            if (iz_index != output->atm.nzout_user) {\n              fprintf (stderr, \"Error, number of output levels not matching in corefinder\\n\");\n              return -1;\n            }\n\n            for (size_t k = 0; k < output->atm.nzout_user; k++)\n              for (size_t j = 0; j < k_scat->ny; j++)\n                for (size_t i = 0; i < k_scat->nx; i++) {\n                  xstart[k * k_scat->ny * k_scat->nx + j * k_scat->nx + i] = i;\n                  ystart[k * k_scat->ny * k_scat->nx + j * k_scat->nx + i] = j;\n                  zstart[k * k_scat->ny * k_scat->nx + j * k_scat->nx + i] = z_index[k];\n                }\n\n            //Start to find the core\n            arr3d_i* core_linarray = calloc3d_int (k_scat->nx, k_scat->ny, k_scat->nz);\n            if (!input.quiet)\n              fprintf (stderr, \"...start finding core. Threshold: %.2f\\n\", input.rte.mc.core_threshold);\n            arr3d_f* distances_linarray =\n              get_distances2 (*k_scat, dx, dy, deltaz, xstart, ystart, zstart, total_starts, input.rte.mc.core_threshold);\n            black_white_filter (distances_linarray, input.rte.mc.core_threshold, core_linarray);\n\n            for (size_t i = 0; i < nx; i++) {\n              for (size_t j = 0; j < ny; j++) {\n                for (size_t k = 0; k < nz; k++) {\n                  core[k][i][j]      = (float)get3d_i (core_linarray, i, j, k);\n                  distances[k][i][j] = get3d_f (distances_linarray, i, j, k);\n                }\n              }\n            }\n\n            free (xstart);\n            free (ystart);\n            free (zstart);\n            free (z_index);\n            free (deltaz);\n            free3d_float (k_scat);\n            free3d_int (core_linarray);\n            free3d_float (distances_linarray);\n          } /*END Corefinder*/\n\n          //Optionally: Save the core to the file given by input.rte.mc.core_savefile\n          if (input.rte.mc.core_savefile) {\n            if (!input.quiet)\n              fprintf (stderr, \"...saving core to %s\\n\", input.rte.mc.core_savefile);\n\n            FILE* fp;\n            if ((fp = fopen (input.rte.mc.core_savefile, \"w\")) == NULL) {\n              fprintf (stderr, \"Could not open %s!\\n\", input.rte.mc.core_savefile);\n              return -1;\n            }\n            fprintf (fp, \"%d %d %d 4\\n\", nx, ny, nz);\n            fprintf (fp, \"%g %g\", output->atm.dxcld / 1000.0, output->atm.dycld / 1000.0);\n\n            for (size_t i = 0; i < nz + 1; i++)\n              fprintf (fp, \" %g\", output->atm.zd_common[nz - i]);\n            fprintf (fp, \"\\n#IndexX IndexY IndexZ Core Distance\\n\");\n            for (int i = 0; i < nx; i++) {\n              for (int j = 0; j < ny; j++) {\n                for (int k = 0; k < nz; k++) {\n                  if (threed[k]) {\n                    if (core[k][i][j] == 0.0 && input.rte.mc.core_inputfile == NULL) {\n                      fprintf (fp, \"%d\\t%d\\t%d\\t%.1f\\t%g\\n\", i + 1, j + 1, k + 1, core[k][i][j], distances[k][i][j]);\n                    } else {\n                      fprintf (fp, \"%d\\t%d\\t%d\\t%.1f\\tnan\\n\", i + 1, j + 1, k + 1, core[k][i][j]);\n                    }\n                  }\n                  // else //do also print the non-threed (non-cloud) zeros\n                  // {\n                  //   fprintf(fp, \"%d\\t%d\\t%d\\t%.1f\\n\", i + 1, j + 1, k + 1, 0.0);\n                  // }\n                }\n              }\n            }\n            fclose (fp);\n          }\n          //Start to create a delta-scaled profile for the area inside the core\n          if (!input.quiet)\n            fprintf (stderr, \"...start delta scaling core\\n\");\n\n          int counter   = 0;\n          int counter3d = 0;\n          for (size_t k = 0; k < nz; k++) {\n            if (threed[k]) {\n              counter3d++;\n              for (size_t i = 0; i < nx; i++) {\n                for (size_t j = 0; j < ny; j++) {\n                  if (core[k][i][j] > 0.5) {\n                    counter++;\n                    float g         = (output->caoth3d[isp_wc3D]).g1[k][i][j];\n                    float w0        = (output->caoth3d[isp_wc3D]).ssa[k][i][j];\n                    float ext       = (output->caoth3d[isp_wc3D]).ext[k][i][j];\n                    float f_scaling = input.rte.mc.core_scale;\n                    if (f_scaling < 0.0)\n                      f_scaling = g;\n\n                    (output->caoth3d[isp_wc3D]).ext[k][i][j]       = 0.0;\n                    (output->caoth3d[isp_hiddencore]).ext[k][i][j] = (1 - w0 * f_scaling) * ext;\n                    (output->caoth3d[isp_hiddencore]).ssa[k][i][j] = (1 - f_scaling) * w0 / (1 - w0 * f_scaling);\n                    (output->caoth3d[isp_hiddencore]).g1[k][i][j]  = (g - f_scaling) / (1 - f_scaling);\n                    (output->caoth3d[isp_hiddencore]).g2[k][i][j]  = 0.0;\n                    (output->caoth3d[isp_hiddencore]).ff[k][i][j]  = 0.0;\n                  } else {\n                    (output->caoth3d[isp_hiddencore]).ext[k][i][j] = 0.0;\n                  }\n                }\n              }\n            }\n          }\n\n          if (!input.quiet)\n            fprintf (stderr,\n                     \"scaled %d pixels of %d 3d pixels! (%.2f%%)\\n\",\n                     counter,\n                     counter3d * nx * ny,\n                     100 * counter / ((float)counter3d * nx * ny));\n\n          free_float_3D (core);\n          free_float_3D (distances);\n        } /* End Section to find hidden core */\n      }\n\n      /********************************/\n      /* loop over independent pixels */\n      /********************************/\n      for (ipa = 0; ipa < output->nipa; ipa++) {\n        for (iipa = 0; iipa < output->niipa; iipa++) {\n          for (jipa = 0; jipa < output->njipa; jipa++) {\n\n            if (!input.quiet && (output->niipa > 1 || output->njipa > 1))\n              fprintf (stderr, \" ... ipa loop over iipa=%d, jipa=%d\\n\", iipa, jipa);\n\n            if (input.verbose && output->nipa == 1)\n              fprintf (stderr,\n                       \"\\n\\n*** wavelength: iv = %d, %f nm, albedo = %f \\n\",\n                       iv,\n                       output->wl.lambda_r[iv],\n                       output->alb.albedo_r[iv]);\n\n            if (input.verbose && output->nipa > 1)\n              fprintf (stderr,\n                       \"\\n\\n*** wavelength: iv = %d, %f nm, looking at column %d, albedo = %f\\n\",\n                       iv,\n                       output->wl.lambda_r[iv],\n                       ipa,\n                       output->alb.albedo_r[iv]);\n\n            /* copy pixel number ipa to 1D caoth data, ulrike: allow ipa3d\n\t   (and tipa dir) for caoth */\n            for (isp = 0; isp < input.n_caoth; isp++) {\n              if (input.caoth[isp].ipa || (input.ipa3d && input.caoth[isp].source == CAOTH_FROM_3D)) {\n\n                /* copy everything except the single scattering properties */\n                if (input.caoth[isp].ipa) {\n                  status = cp_caoth_out (&(output->caoth[isp]), output->caoth_ipa[isp][ipa], 0, 0, input.quiet);\n                  if (status)\n                    return fct_err_out (status, \"cp_cld_out\", ERROR_POSITION);\n                }\n\n                if (input.ipa3d) {\n                  if (!input.quiet)\n                    fprintf (stderr, \" ... copying 3d to 1d for %s\\n\", output->caoth[isp].fullname);\n\n                  status = cp_caoth3d_out (&(output->caoth[isp]), output->caoth3d[isp], input.quiet, iipa, jipa);\n                  if (status)\n                    return fct_err_out (status, \"cp_caoth3d_out\", ERROR_POSITION);\n\n                  /* copy cloud fraction, if available */\n                  if (output->caoth3d[isp].cldproperties == CLD_LWCREFFCF) {\n                    if (!input.quiet)\n                      fprintf (stderr, \" ... copying cloud fraction from caoth %d\\n\", isp);\n\n                    /* need to allocate memory for cloud fraction profile? */\n                    if (output->cf.nlev == 0) {\n                      if (!input.quiet)\n                        fprintf (stderr, \" ... allocating memory for cloud fraction profile\\n\");\n\n                      output->cf.nlev = output->atm.nlev - 1;\n                      output->cf.zd   = calloc (output->cf.nlev, sizeof (float));\n                      output->cf.cf   = calloc (output->cf.nlev, sizeof (float));\n\n                      for (lu = 0; lu < output->cf.nlev; lu++)\n                        output->cf.zd[lu] = output->atm.zd[lu];\n                    }\n\n                    status = cp_caoth3d_cf_out (output->cf.cf, output->caoth3d[isp], input.quiet, iipa, jipa);\n                    if (status)\n                      return fct_err_out (status, \"cp_caoth3d_cf_out\", ERROR_POSITION);\n                  }\n                }\n\n#if HAVE_TIPA\n                if (input.tipa == TIPA_DIR) { /* ulrike: calculate tilted dtau for caoth */\n                  status = tipa_calcdtau (input.caoth[isp],\n                                          output->caoth3d[isp],\n                                          iipa,\n                                          jipa,\n                                          iv,\n                                          input,\n                                          output->wl,\n                                          &(output->caoth[isp]),\n                                          &(output->caoth[isp].tipa));\n                  if (status)\n                    return fct_err_out (status, \"tipa_calcdtau\", ERROR_POSITION);\n                }\n#endif\n\n                /* calculate optical properties for the caoth properties\n\t       specified in the input-file (ulrike) */\n                status = caoth_prop_switch (input, input.caoth[isp], output->wl, iv, &(output->caoth[isp]));\n                if (status)\n                  return fct_err_out (status, \"caoth_prop_switch\", ERROR_POSITION);\n\n                /* overwrite these properties with user-defined optical thickness, ssa, etc */\n                status = apply_user_defined_properties_to_caoth (input.caoth[isp],\n                                                                 output->wl.nlambda_r,\n                                                                 output->wl.lambda_r,\n                                                                 output->alt.altitude,\n                                                                 &(output->caoth[isp]));\n                if (status)\n                  return fct_err_out (status, \"apply_user_defined_properties_to_cld\", ERROR_POSITION);\n              } /*ulrike: end of \"if (input.caoth[isp].ipa || input.ipa3d)\"*/\n            }   /* end loop isp */\n\n            if (input.rte.solver == SOLVER_TWOMAXRND && output->cf.nlev == 0) {\n              fprintf (stderr, \"Error, rte_solver twomaxrnd makes only sense with cloud_fraction_file\\n\");\n              fprintf (stderr, \"or cloud fraction defined in 3D cloud file.\\n\");\n              return -1;\n            }\n\n            /* ulrike: for testing */\n            /*\t  if (input.tipa==TIPA_DIR) {\n\t   fprintf(stderr,\"\\nThus, for water clouds we have\\n\");\n\t    for (iz=0; iz<(output->wc.tipa.nztilt); iz++)\n\t      {\n\t\tfprintf(stderr,\"\\nAt level= %e km there are totlev[iz=%d]=%d intersection levels\\n\",output->wc.tipa.level[iz],iz,output->wc.tipa.totlev[iz]);\n\t\tfprintf(stderr,\" tipa->taudircld[iv=%d][iz=%d]=%e\\n\",iv,iz,output->wc.tipa.taudircld[iv][iz]);\n\t      }\n\t   fprintf(stderr,\"\\nThus, for ice clouds we have \\n\");\n\t    for (iz=0; iz<(output->ic.tipa.nztilt); iz++)\n\t      {\n\t\tfprintf(stderr,\"\\nAt level= %e km there are totlev[iz=%d]=%d intersection levels\\n\",output->ic.tipa.level[iz],iz,output->ic.tipa.totlev[iz]);\n\t\tfprintf(stderr,\" tipa->taudircld[iv=%d][iz=%d]=%e\\n\",iv,iz,output->ic.tipa.taudircld[iv][iz]);\n\t      }\n\t  }*/\n            /* *************************************************************** */\n\n            if (input.ipa) {\n              /* copy cloud fraction structure, if needed */\n              switch (input.cloud_overlap) {\n              case CLOUD_OVERLAP_MAX:\n              case CLOUD_OVERLAP_MAXRAND: /* target */ /* source */ /* alloc */\n                if (input.rte.solver != SOLVER_TWOMAXRND && input.rte.solver != SOLVER_TWOMAXRND3C &&\n                    input.rte.solver != SOLVER_DYNAMIC_TWOSTREAM) {\n                  status = copy_cloud_fraction (&(output->cf), output->cfipa[ipa], FALSE); /* in cloud.c */\n                  if (status != 0) {\n                    fprintf (stderr, \"Error %d copying output->cfipa[ipa] to output->cf\\n\", status);\n                    return status;\n                  }\n                }\n                /* For (lc=0;lc<output->cf.nlev;lc++) fprintf (stderr, \" %s ipa=%3d lc=%3d %f \\n\", __func__, ipa, lc, output->cf.cf[lc]); */\n                break;\n              case CLOUD_OVERLAP_RAND:\n              case CLOUD_OVERLAP_OFF:\n                /* nothing to do here */\n                break;\n              default:\n                fprintf (stderr,\n                         \"Error, unknown cloud_overlap assumption %d. (line %d, function %s in %s)\\n\",\n                         input.cloud_overlap,\n                         __LINE__,\n                         __func__,\n                         __FILE__);\n                return -1;\n              }\n            }\n\n            /* IPA molecular absorption and aerosols */\n\n            /* these lines also optimise the iq-loop for corr-k schemes, also if there is no ipa */\n            /* CE: with spectral importance sampling number of calculations always corresponds to maximum number of bands  */\n            if (input.ck_scheme == CK_LOWTRAN && !input.rte.mc.spectral_is)\n              output->atm.nq_r[iv] = output->crs_ck.profile[0][iv].ngauss;\n\n            /* If only one subband is used in the LOWTRAN parameterization, */\n            /* the photon weights of the three subbands are added; this is  */\n            /* necessary because the number of subbands changes with        */\n            /* concentration and is therefore not known beforehand.         */\n            /* The correct use of mc_photons_file for LOWTRAN is then       */\n            /* to always distribute the photons over three subbands;        */\n            /* uvspec decides automatically if only one is needed           */\n\n            if (input.ck_scheme == CK_LOWTRAN) {\n              if (output->atm.nq_r[iv] == 1)\n                for (iq = 1; iq < LOWTRAN_MAXINT; iq++)\n                  output->mc_photons_r[iv][0] += output->mc_photons_r[iv][iq];\n              /* fprintf (stderr, \"mc_photons = %f\\n\", output->mc_photons_r[iv][0]); */\n            }\n\n            /*  if (input.verbose) { */\n            /*    fprintf (stderr, \"*** wavelength: iv = %d, %f nm, albedo = %f\\n\", iv, output->wl.lambda_r[iv], output->alb.albedo_r[iv]); */\n            /*    fprintf (stderr, \"    atm.nmom + 1 = %d phase function moments\\n\", output->atm.nmom+1); */\n            /*    fprintf (stderr, \" --------------------------------------------------------------------------------------------\\n\"); */\n            /*    fprintf (stderr, \"   lu |    z[km] |      aerosol      |    water cloud    |    ice cloud      | tau_molecular \\n\"); */\n            /*    fprintf (stderr, \"      |          |        dtau  nmom |        dtau  nmom |        dtau  nmom |               \\n\"); */\n            /*    fprintf (stderr, \" --------------------------------------------------------------------------------------------\\n\"); */\n            /*    for (lu=0; lu<output->atm.nlyr; lu++) */\n            /*      fprintf (stderr, \"%5d | %8.2f | %11.6f %5d | %11.6f %5d | %11.6f %5d | %11.6f \\n\",  */\n            /* \t  lu, output->atm.zd[lu+1], */\n            /* \t  0.0,0, /\\*output->aer.dtau[iv][lu], output->aer.nmom[iv][lu],*\\/ */\n            /* \t  output->wc.optprop.dtau [iv][lu], output->wc.optprop.nmom[iv][lu], */\n            /* \t  output->ic.optprop.dtau [iv][lu], output->ic.optprop.nmom[iv][lu], */\n            /*          output->atm.optprop.tau_molabs_r[lu][iv][0]); */\n            /*      fprintf (stderr, \" ---------------------------------------------------------------------------\\n\"); */\n            /*  } */\n\n            /* need to load data during first call of mystic() for each band/wavelength */\n            mc_loaddata = 1;\n\n            /* reset band integral */\n            reset_rte_output (&rte_outband,\n                              input,\n                              output->atm.nzout,\n                              output->atm.Nxcld,\n                              output->atm.Nycld,\n                              output->atm.Nzcld,\n                              output->mc.sample.Nx,\n                              output->mc.sample.Ny,\n                              output->mc.alis.Nc,\n                              output->mc.alis.nlambda_abs,\n                              output->atm.nlev - 1,\n                              output->atm.threed,\n                              output->mc.sample.passback3D,\n                              output->mc.triangular_surface.N_triangles);\n\n            if (input.raman) {\n              if (ir == 0) {\n                if (input.raman_fast) {\n                  lower_iq_id          = output->wl.nlambda_rte_lower;\n                  output->atm.nq_r[iv] = output->wl.nlambda_rte_upper;\n                } else {\n                  output->atm.nq_r[iv] = output->crs.number_of_ramanwavelengths;\n                }\n                upper_iq_id = output->atm.nq_r[iv];\n              } else if (ir == 1) {\n                output->atm.nq_r[iv] = 1;\n                lower_iq_id          = 0;\n                upper_iq_id          = output->atm.nq_r[iv];\n              }\n            } else {\n              lower_iq_id = 0;\n              upper_iq_id = output->atm.nq_r[iv];\n            }\n\n            /******************************************/\n            /* loop over quadrature points (subbands) */\n            /******************************************/\n            for (iq = lower_iq_id; iq < upper_iq_id; iq++) {\n\n              if (input.verbose && (input.ck_scheme != CK_CRS))\n                fprintf (stderr,\n                         \"\\n*** wavelength: iv = %d, %f nm, looking at column %d, quadrature point nr %d, albedo = %f\\n\",\n                         iv,\n                         output->wl.lambda_r[iv],\n                         ipa,\n                         iq,\n                         output->alb.albedo_r[iv]);\n\n              if (input.verbose && (input.ck_scheme == CK_RAMAN))\n                fprintf (stderr,\n                         \"\\n*** wavelength: iv = %d, %f nm, looking at column %d, quadrature point nr %d, wvl = %f\\n\",\n                         iv,\n                         output->wl.lambda_r[iv],\n                         ipa,\n                         iq,\n                         output->wl.lambda_r[iq]);\n\n              /* set number of photons for this band */\n              if (input.rte.solver == SOLVER_MONTECARLO && !input.rte.mc.spectral_is)\n                output->mc_photons = (long int)(output->mc_photons_r[iv][iq] * (double)input.rte.mc.photons + 0.5);\n              /* run at least MIN_MCPHOTONS for each band */\n              /* no need to increase for backward direct because backward direct is (nearly) exact */\n              if (output->mc.sample.backward != MCBACKWARD_EDIR && output->mc.sample.backward != MCBACKWARD_FDIR) {\n                if (input.rte.mc.minphotons) { /* set by user */\n                  if (output->mc_photons < (long int)input.rte.mc.minphotons)\n                    output->mc_photons = input.rte.mc.minphotons;\n                } else { /* default */\n                  if (output->mc_photons < MIN_MCPHOTONS)\n                    output->mc_photons = MIN_MCPHOTONS;\n                }\n              } else { /* however, we need at least one photon for direct */\n                if (output->mc_photons < 1)\n                  output->mc_photons = 1;\n              }\n              /* For spectral importance sampling, only one wavelength is */\n              /* calculated, therefore no distribution of photons required.  */\n              if (input.rte.mc.spectral_is)\n                output->mc_photons = input.rte.mc.photons;\n\n              if (input.verbose)\n                fprintf (stderr, \" ... ck weight %9.7f\\n\", output->atm.wght_r[iv][iq]);\n\n              /* if the level number of cloud fraction data is more than 0, than ... */\n              if (input.cloud_overlap != CLOUD_OVERLAP_OFF && input.rte.solver != SOLVER_TWOMAXRND &&\n                  input.rte.solver != SOLVER_TWOMAXRND3C && input.rte.solver != SOLVER_DYNAMIC_TWOSTREAM) {\n\n                /* Save optical properties for wavelength iv. This is necessary because averaged optical properties \n\t       are calulated for each subband and put into output->wc.optprop.... */\n                if (iq == 0) {\n\n                  for (lc = 0; lc < output->atm.nlev - 1; lc++) {\n                    if (input.i_wc != -1) {\n                      /* optical depth */\n                      save_cloud->tauw[lc] = output->caoth[input.i_wc].optprop.dtau[iv][lc];\n                      /* asymmetry parameter */\n                      save_cloud->g1d[lc] = output->caoth[input.i_wc].optprop.g1[iv][lc];\n                      save_cloud->g2d[lc] = output->caoth[input.i_wc].optprop.g2[iv][lc];\n                      save_cloud->fd[lc]  = output->caoth[input.i_wc].optprop.ff[iv][lc];\n                      /* single scattering albedo */\n                      save_cloud->ssaw[lc] = output->caoth[input.i_wc].optprop.ssa[iv][lc];\n                    } else {\n                      save_cloud->tauw[lc] = 0.0;\n                      save_cloud->g1d[lc]  = 0.0;\n                      save_cloud->g2d[lc]  = 0.0;\n                      save_cloud->fd[lc]   = 0.0;\n                      save_cloud->ssaw[lc] = 0.0;\n                    }\n\n                    if (input.i_ic != -1) {\n                      /* optical depth */\n                      save_cloud->taui[lc] = output->caoth[input.i_ic].optprop.dtau[iv][lc];\n                      /* asymmetry parameter */\n                      save_cloud->g1i[lc] = output->caoth[input.i_ic].optprop.g1[iv][lc];\n                      save_cloud->g2i[lc] = output->caoth[input.i_ic].optprop.g2[iv][lc];\n                      save_cloud->fi[lc]  = output->caoth[input.i_ic].optprop.ff[iv][lc];\n                      /* single scattering albedo */\n                      save_cloud->ssai[lc] = output->caoth[input.i_ic].optprop.ssa[iv][lc];\n                    } else {\n                      save_cloud->taui[lc] = 0.0;\n                      save_cloud->g1i[lc]  = 0.0;\n                      save_cloud->g2i[lc]  = 0.0;\n                      save_cloud->fi[lc]   = 0.0;\n                      save_cloud->ssai[lc] = 0.0;\n                    }\n                  }\n                }\n\n                /* calculate effective cloud optical properties for fractional cloud cover */\n                status = generate_effective_cloud (input, output, save_cloud, iv, iq, input.verbose); /* in solve_rte.c */\n                CHKERR (status);\n              }\n\n              /* 3DAbs include caoth3d for 3D molecular atmosphere, right place here ??? */\n              if (input.rte.solver == SOLVER_MONTECARLO && output->molecular3d)\n                optical_properties_molecular3d (input, output, &(output->caoth3d[CAOTH_FIR]), iv, iq);\n\n              /* setup optical properties and call the RTE solver */\n              status = setup_and_call_solver (input,\n                                              output,\n                                              rte_in,\n                                              rte_out,\n                                              raman_qsrc_components,\n                                              iv,\n                                              iq,\n                                              ir,\n                                              output->atm.threed,\n                                              mc_loaddata);\n\n              CHKERR (status);\n\n              /* verbose output */\n              if (input.verbose) {\n                fprintf (stderr,\n                         \"  iv = %d, %f nm, iq = %d, flux_dir[lu=0] = %13.7e, flux_dn[lu=0] = %13.7e, flux_up[lu=0] = %13.7e, \"\n                         \"weight_r = %13.7e \\n\",\n                         iv,\n                         output->wl.lambda_r[iv],\n                         iq,\n                         rte_out->rfldir[0],\n                         rte_out->rfldn[0],\n                         rte_out->flup[0],\n                         output->atm.wght_r[iv][iq]);\n              }\n\n              /* data need to be loaded only once per iv */\n              mc_loaddata = 0;\n\n              if (input.heating != HEAT_NONE)\n                calc_spectral_heating (input,\n                                       output,\n                                       dz,\n                                       rho_mass_zout,\n                                       k_abs,\n                                       k_abs_layer,\n                                       rte_in->pol.outlevels,\n                                       rte_out,\n                                       rte_out->heat,\n                                       rte_out->emis,\n                                       rte_out->w_zout,\n                                       iv);\n\n              /**********************************************************************/\n              /* Store intensities for later use in second round of raman iteration */\n              /**********************************************************************/\n              if (input.raman) {\n                if (ir == 0) {\n                  if (input.raman_fast) {\n                    for (lu = 0; lu < output->atm.nlyr; lu++)\n                      raman_qsrc_components->dtauc[lu][iq] = (double)output->dtauc[lu];\n                    raman_qsrc_components->fbeam[iq] = rte_in->fbeam;\n                    for (lu = 0; lu < output->atm.nzout; lu++) {\n                      raman_qsrc_components->uavgso[lu][iq] = (double)rte_out->uavgso[lu];\n                      raman_qsrc_components->uavgdn[lu][iq] = (double)rte_out->uavgdn[lu];\n                      raman_qsrc_components->uavgup[lu][iq] = (double)rte_out->uavgup[lu];\n                      raman_qsrc_components->rfldir[lu][iq] = (double)rte_out->rfldir[lu];\n                      raman_qsrc_components->rfldn[lu][iq]  = (double)rte_out->rfldn[lu];\n                      raman_qsrc_components->flup[lu][iq]   = (double)rte_out->flup[lu];\n                      for (iu = 0; iu < input.rte.nstr; iu++) {\n                        raman_qsrc_components->u0u[lu][input.rte.cmuind[iu]][iq] = (double)rte_out->u0u[lu][input.rte.cmuind[iu]];\n                        for (j = 0; j < input.rte.nphi; j++) {\n                          raman_qsrc_components->uu[lu][j][input.rte.cmuind[iu]][iq] =\n                            (double)rte_out->uu[j][lu][input.rte.cmuind[iu]];\n                        }\n                      }\n                      for (iu = 0; iu < input.rte.numu - input.rte.nstr; iu++) {\n                        raman_qsrc_components->u0u[lu][input.rte.umuind[iu]][iq] = (double)rte_out->u0u[lu][input.rte.umuind[iu]];\n                        for (j = 0; j < input.rte.nphi; j++) {\n                          raman_qsrc_components->uu[lu][j][input.rte.umuind[iu]][iq] =\n                            (double)rte_out->uu[j][lu][input.rte.umuind[iu]];\n                        }\n                      }\n                    }\n\n                    for (lu = 0; lu < output->atm.nzout; lu++) {\n                      for (j = 0; j < input.rte.nstr; j++) {\n                        for (iu = 0; iu < input.rte.numu; iu++) {\n                          raman_qsrc_components->uum[lu][j][iu][iq] = (double)rte_out->uum[j][lu][iu];\n                        }\n                      }\n                    }\n                  } else {\n                    raman_qsrc_components->fbeam[iq] = (double)rte_in->fbeam;\n                    if (input.verbose)\n                      fprintf (stderr,\n                               \"Storing Raman quantities for iq: %3d out of %3d.\\n\",\n                               iq,\n                               output->crs.number_of_ramanwavelengths - 1);\n                    if (iq == output->crs.number_of_ramanwavelengths - 1) {\n                      /* Only store radiation for the wanted wavelength which should be at the last index */\n                      for (lu = 0; lu < output->atm.nlyr; lu++)\n                        raman_qsrc_components->dtauc[lu][iq] = (double)output->dtauc[lu];\n                      for (lu = 0; lu < output->atm.nzout; lu++) {\n                        uavgso_raman[lu]    = rte_out->uavgso[lu];\n                        uavgdn_raman[lu]    = rte_out->uavgdn[lu];\n                        uavgup_raman[lu]    = rte_out->uavgup[lu];\n                        rfldir_raman[lu]    = rte_out->rfldir[lu];\n                        rfldn_raman[lu]     = rte_out->rfldn[lu];\n                        flup_raman[lu]      = rte_out->flup[lu];\n                        rte_out->rfldir[lu] = 0;\n                        rte_out->rfldn[lu]  = 0;\n                        rte_out->flup[lu]   = 0;\n                        for (iu = 0; iu < input.rte.nstr; iu++) {\n                          u0u_raman[lu][input.rte.cmuind[iu]] = rte_out->u0u[lu][input.rte.cmuind[iu]];\n                          for (j = 0; j < input.rte.nphi; j++) {\n                            uu_raman[lu][j][input.rte.cmuind[iu]] = rte_out->uu[j][lu][input.rte.cmuind[iu]];\n                          }\n                        }\n                        for (iu = 0; iu < input.rte.numu - input.rte.nstr; iu++) {\n                          u0u_raman[lu][input.rte.umuind[iu]] = rte_out->u0u[lu][input.rte.umuind[iu]];\n                          for (j = 0; j < input.rte.nphi; j++) {\n                            uu_raman[lu][j][input.rte.umuind[iu]] = rte_out->uu[j][lu][input.rte.umuind[iu]];\n                          }\n                        }\n                      }\n                    }\n\n                    /* Store source components at all shifted wavelengths. Store uum for all wavelengths, */\n                    /* including the last index which contains the wanted wavelength                      */\n\n                    for (lu = 0; lu < output->atm.nlyr; lu++)\n                      raman_qsrc_components->dtauc[lu][iq] = (double)output->dtauc[lu];\n                    for (lu = 0; lu < output->atm.nzout; lu++) {\n                      for (j = 0; j < input.rte.nstr; j++) {\n                        for (iu = 0; iu < input.rte.numu; iu++) {\n                          raman_qsrc_components->uum[lu][j][iu][iq] = (double)rte_out->uum[j][lu][iu];\n                        }\n                      }\n                    }\n                  }\n                } else if (ir == 1) {\n\n                  add = 1;\n                  if (input.raman_fast) {\n                    ivr = iv + output->wl.nlambda_rte_lower;\n                    for (lu = 0; lu < output->atm.nzout; lu++) {\n                      rte_out->uavgso[lu] += (double)raman_qsrc_components->uavgso[lu][ivr];\n                      rte_out->uavgup[lu] += (double)raman_qsrc_components->uavgup[lu][ivr];\n                      rte_out->uavgdn[lu] += (double)raman_qsrc_components->uavgdn[lu][ivr];\n                      rte_out->rfldir[lu] += (double)raman_qsrc_components->rfldir[lu][ivr];\n                      rte_out->rfldn[lu] += (double)raman_qsrc_components->rfldn[lu][ivr];\n                      rte_out->flup[lu] += (double)raman_qsrc_components->flup[lu][ivr];\n                      for (iu = 0; iu < input.rte.nstr; iu++) {\n                        rte_out->u0u[lu][input.rte.cmuind[iu]] += (double)raman_qsrc_components->u0u[lu][input.rte.cmuind[iu]][ivr];\n                        for (j = 0; j < input.rte.nphi; j++) {\n                          rte_out->uu[j][lu][input.rte.cmuind[iu]] +=\n                            (double)raman_qsrc_components->uu[lu][j][input.rte.cmuind[iu]][ivr];\n                        }\n                      }\n                      for (iu = 0; iu < input.rte.numu - input.rte.nstr; iu++) {\n                        rte_out->u0u[lu][input.rte.umuind[iu]] += (double)raman_qsrc_components->u0u[lu][input.rte.umuind[iu]][ivr];\n                        for (j = 0; j < input.rte.nphi; j++) {\n                          rte_out->uu[j][lu][input.rte.umuind[iu]] +=\n                            (double)raman_qsrc_components->uu[lu][j][input.rte.umuind[iu]][ivr];\n                        }\n                      }\n                    }\n                  } else {\n                    for (lu = 0; lu < output->atm.nzout; lu++) {\n                      if (add) {\n                        rte_out->uavgso[lu] += uavgso_raman[lu];\n                        rte_out->uavgdn[lu] += uavgdn_raman[lu];\n                        rte_out->uavgup[lu] += uavgup_raman[lu];\n                        rte_out->rfldir[lu] += rfldir_raman[lu];\n                        rte_out->rfldn[lu] += rfldn_raman[lu];\n                        rte_out->flup[lu] += flup_raman[lu];\n                        for (iu = 0; iu < input.rte.nstr; iu++) {\n                          rte_out->u0u[lu][input.rte.cmuind[iu]] += u0u_raman[lu][input.rte.cmuind[iu]];\n                          for (j = 0; j < input.rte.nphi; j++) {\n                            rte_out->uu[j][lu][input.rte.cmuind[iu]] += uu_raman[lu][j][input.rte.cmuind[iu]];\n                          }\n                        }\n                        for (iu = 0; iu < input.rte.numu - input.rte.nstr; iu++) {\n                          rte_out->u0u[lu][input.rte.umuind[iu]] += u0u_raman[lu][input.rte.umuind[iu]];\n                          for (j = 0; j < input.rte.nphi; j++) {\n                            rte_out->uu[j][lu][input.rte.umuind[iu]] += uu_raman[lu][j][input.rte.umuind[iu]];\n                          }\n                        }\n                      }\n                    }\n                  }\n                }\n              }\n\n              /* add result for the current quadrature point considering quadrature weight */\n              if (!input.raman || (input.raman && ir == 0 && iq == output->crs.number_of_ramanwavelengths - 1) ||\n                  (input.raman && ir == 1)) {\n\n                if (input.raman) {\n                  if (ir == 0)\n                    weight = 0;\n                  else if (ir == 1)\n                    weight = 1;\n                } else\n                  weight = output->atm.wght_r[iv][iq];\n\n                if (input.rte.mc.spectral_is)\n                  for (iv_alis = 0; iv_alis < output->mc.alis.nlambda_abs; iv_alis++)\n                    weight_spectral[iv_alis] = output->atm.wght_r[iv_alis][iq];\n\n                status = add_rte_output (rte_outband,\n                                         rte_out,\n                                         weight,\n                                         weight_spectral,\n                                         input,\n                                         output->atm.nzout,\n                                         output->atm.Nxcld,\n                                         output->atm.Nycld,\n                                         output->atm.Nzcld,\n                                         output->mc.alis.Nc,\n                                         output->atm.nlev - 1,\n                                         output->mc.alis.nlambda_abs,\n                                         output->atm.threed,\n                                         output->mc.sample.passback3D,\n                                         output->islower,\n                                         output->isupper,\n                                         output->jslower,\n                                         output->jsupper,\n                                         output->isstep,\n                                         output->jsstep);\n                CHKERR (status);\n              }\n\n            } /* for (iq=0; iq<output->atm.nq_r[iv]; iq++) { ...   == 'loop over quadrature points' */\n\n            /************************************************/\n            /* add result for the current independent pixel */\n            /************************************************/\n\n            if (input.rte.solver == SOLVER_POLRADTRAN) {\n              for (lu = 0; lu < output->atm.nzout; lu++) {\n\n                output->rfldir_r[lu][iv] += output->ipaweight[ipa] * rte_outband->rfldir[lu];\n                output->heat_r[lu][iv] += output->ipaweight[ipa] * rte_outband->heat[lu];\n                output->emis_r[lu][iv] += output->ipaweight[ipa] * rte_outband->emis[lu];\n                output->w_zout_r[lu][iv] += output->ipaweight[ipa] * rte_outband->w_zout[lu];\n\n                for (is = 0; is < input.rte.polradtran[POLRADTRAN_NSTOKES]; is++) {\n\n                  output->up_flux_r[lu][is][iv] += output->ipaweight[ipa] * rte_outband->polradtran_up_flux[lu][is];\n\n                  output->down_flux_r[lu][is][iv] += output->ipaweight[ipa] * rte_outband->polradtran_down_flux[lu][is];\n\n                  for (j = 0; j < input.rte.nphi; j++) {\n                    for (iu = 0; iu < input.rte.numu; iu++) {\n                      output->down_rad_r[lu][j][iu][is][iv] +=\n                        output->ipaweight[ipa] * rte_outband->polradtran_down_rad[lu][j][iu][is];\n                      output->up_rad_r[lu][j][iu][is][iv] += output->ipaweight[ipa] * rte_outband->polradtran_up_rad[lu][j][iu][is];\n                    }\n                  }\n                }\n              }\n            } else if (rte_in->ibcnd) {\n              for (iu = 0; iu < input.rte.numu; iu++) {\n                output->albmed_r[iu][iv] += rte_outband->albmed[iu];\n                output->trnmed_r[iu][iv] += rte_outband->trnmed[iu];\n              }\n            } else {\n              for (lu = 0; lu < output->atm.nzout; lu++) {\n                output->rfldir_r[lu][iv] += output->ipaweight[ipa] * rte_outband->rfldir[lu];\n                output->rfldn_r[lu][iv] += output->ipaweight[ipa] * rte_outband->rfldn[lu];\n                output->flup_r[lu][iv] += output->ipaweight[ipa] * rte_outband->flup[lu];\n                output->uavg_r[lu][iv] += output->ipaweight[ipa] * rte_outband->uavg[lu];\n                output->uavgdn_r[lu][iv] += output->ipaweight[ipa] * rte_outband->uavgdn[lu];\n                output->uavgso_r[lu][iv] += output->ipaweight[ipa] * rte_outband->uavgso[lu];\n                output->uavgup_r[lu][iv] += output->ipaweight[ipa] * rte_outband->uavgup[lu];\n                output->heat_r[lu][iv] += output->ipaweight[ipa] * rte_outband->heat[lu];\n                output->emis_r[lu][iv] += output->ipaweight[ipa] * rte_outband->emis[lu];\n                output->w_zout_r[lu][iv] += output->ipaweight[ipa] * rte_outband->w_zout[lu];\n                output->sslidar_nphot_r[lu][iv] += output->ipaweight[ipa] * rte_outband->sslidar_nphot[lu];\n                output->sslidar_nphot_q_r[lu][iv] += output->ipaweight[ipa] * rte_outband->sslidar_nphot_q[lu];\n                output->sslidar_ratio_r[lu][iv] += output->ipaweight[ipa] * rte_outband->sslidar_ratio[lu];\n\n                /* intensities */\n                for (iu = 0; iu < input.rte.numu; iu++) {\n                  output->u0u_r[lu][iu][iv] += output->ipaweight[ipa] * rte_outband->u0u[lu][iu];\n\n                  for (j = 0; j < input.rte.nphi; j++)\n                    output->uu_r[lu][j][iu][iv] += output->ipaweight[ipa] * rte_outband->uu[j][lu][iu];\n                }\n\n                /* 3D fields */ /* ulrike: I added \"&& input.rte.solver == SOLVER_MONTECARLO\" */\n                if (output->mc.sample.passback3D && input.rte.solver == SOLVER_MONTECARLO) {\n                  for (is = output->islower; is <= output->isupper; is += output->isstep) {\n                    for (js = output->jslower; js <= output->jsupper; js += output->jsstep) {\n\n                      output->rfldir3d_r[lu][is][js][iv] += output->ipaweight[ipa] * rte_outband->rfldir3d[lu][is][js];\n\n                      output->rfldn3d_r[lu][is][js][iv] += output->ipaweight[ipa] * rte_outband->rfldn3d[lu][is][js];\n\n                      output->flup3d_r[lu][is][js][iv] += output->ipaweight[ipa] * rte_outband->flup3d[lu][is][js];\n\n                      output->uavgso3d_r[lu][is][js][iv] += output->ipaweight[ipa] * rte_outband->uavgso3d[lu][is][js];\n\n                      output->uavgdn3d_r[lu][is][js][iv] += output->ipaweight[ipa] * rte_outband->uavgdn3d[lu][is][js];\n\n                      output->uavgup3d_r[lu][is][js][iv] += output->ipaweight[ipa] * rte_outband->uavgup3d[lu][is][js];\n\n                      if (output->mc.sample.spectral_is || output->mc.sample.concentration_is)\n                        for (ic = 0; ic < output->mc.alis.Nc; ic++) {\n                          for (ivs = 0; ivs < output->mc.alis.nlambda_abs; ivs++) {\n                            output->fl3d_is_r[lu][is][js][ic][ivs] +=\n                              output->ipaweight[ipa] * rte_outband->fl3d_is[lu][ic][is][js][ivs];\n                          }\n                        }\n\n                      for (ip = 0; ip < input.rte.mc.nstokes; ip++) {\n                        if (output->mc.sample.spectral_is || output->mc.sample.concentration_is) {\n                          for (ivs = 0; ivs < output->mc.alis.nlambda_abs; ivs++) {\n                            for (ic = 0; ic < output->mc.alis.Nc; ic++) {\n                              output->radiance3d_r[lu][is][js][ip][ic][ivs] +=\n                                output->ipaweight[ipa] * rte_outband->radiance3d_is[lu][ic][is][js][ip][ivs];\n                            }\n                          }\n                        } else\n                          output->radiance3d_r[lu][is][js][ip][0][iv] +=\n                            output->ipaweight[ipa] * rte_outband->radiance3d[lu][is][js][ip];\n                      }\n\n                      if (input.rte.mc.jacobian[DIM_1D]) {\n                        for (isp = 0; isp < input.n_caoth + 2; isp++) {\n                          for (ijac = 0; ijac < 2; ijac++) {\n                            /* scattering and absorption */\n                            for (lc = 0; lc < output->atm.nlyr; lc++) {\n                              output->jacobian_r[lu][is][js][isp][ijac][lc][iv] +=\n                                output->ipaweight[ipa] * rte_outband->jacobian[lu][is][js][isp][ijac][lc];\n                            }\n                          }\n                        }\n                      }\n\n                      if (input.rte.mc.backward.absorption)\n                        output->absback3d_r[lu][is][js][iv] += output->ipaweight[ipa] * rte_outband->absback3d[lu][is][js];\n\n                      /* variances */\n                      if (input.rte.mc.std) {\n\n                        /* variance is weighted with square of weight */\n                        weight2 = output->ipaweight[ipa] * output->ipaweight[ipa];\n\n                        output->rfldir3d_var_r[lu][is][js][iv] += weight2 * rte_outband->rfldir3d_var[lu][is][js];\n\n                        output->rfldn3d_var_r[lu][is][js][iv] += weight2 * rte_outband->rfldn3d_var[lu][is][js];\n\n                        output->flup3d_var_r[lu][is][js][iv] += weight2 * rte_outband->flup3d_var[lu][is][js];\n\n                        output->uavgso3d_var_r[lu][is][js][iv] += weight2 * rte_outband->uavgso3d_var[lu][is][js];\n\n                        output->uavgdn3d_var_r[lu][is][js][iv] += weight2 * rte_outband->uavgdn3d_var[lu][is][js];\n\n                        output->uavgup3d_var_r[lu][is][js][iv] += weight2 * rte_outband->uavgup3d_var[lu][is][js];\n\n                        for (ip = 0; ip < input.rte.mc.nstokes; ip++)\n                          output->radiance3d_var_r[lu][is][js][ip][iv] += weight2 * rte_outband->radiance3d_var[lu][is][js][ip];\n\n                        if (input.rte.mc.backward.absorption)\n                          output->absback3d_var_r[lu][is][js][iv] += weight2 * rte_outband->absback3d_var[lu][is][js];\n                      }\n                    }\n                  }\n                } else if (input.ipa3d) {\n                  /*ulrike: 3d-fields (without _r) are not needed*/\n\n                  /* BM 3.7.2020: removed factor ipaweight[]; see comment above */\n                  output->rfldir3d_r[lu][iipa][jipa][iv] += rte_outband->rfldir[lu];\n                  output->rfldn3d_r[lu][iipa][jipa][iv] += rte_outband->rfldn[lu];\n                  output->flup3d_r[lu][iipa][jipa][iv] += rte_outband->flup[lu];\n                  output->uavgso3d_r[lu][iipa][jipa][iv] += rte_outband->uavgso[lu];\n                  output->uavgdn3d_r[lu][iipa][jipa][iv] += rte_outband->uavgdn[lu];\n                  output->uavgup3d_r[lu][iipa][jipa][iv] += rte_outband->uavgup[lu];\n\n                  /* ulrike: missing: emis, w_zout ????????????? */\n                  /*ulrike: 4.5.2010 use absback3d_r to save the ipa_3d-heating rates!*/\n                  if (input.rte.mc.backward.absorption)\n                    output->absback3d_r[lu][iipa][jipa][iv] += output->ipaweight[ipa] * rte_outband->heat[lu];\n\n                } /*ulrike: end of: else if (input.ipa3d)*/\n              }   /*ulrike: end for-loop over lev lu*/\n\n              /* 3D absorption; ulrike added && input.rte.solver == SOLVER_MONTECARLO */\n              if (output->mc.sample.passback3D && input.rte.mc.absorption != MCFORWARD_ABS_NONE &&\n                  input.rte.solver == SOLVER_MONTECARLO)\n                for (ks = 0; ks < output->atm.Nzcld; ks++)\n                  if (output->atm.threed[ks]) /* only for 3D layers, BM07122005 */\n                    for (is = 0; is < output->atm.Nxcld; is++)\n                      for (js = 0; js < output->atm.Nycld; js++) { /* **CK added bracket  */\n                        output->abs3d_r[ks][is][js][iv] += output->ipaweight[ipa] * rte_outband->abs3d[ks][is][js];\n                        if (input.rte.mc.std) /* **CK added for forward mc_std */\n                          output->abs3d_var_r[ks][is][js][iv] += output->ipaweight[ipa] * rte_outband->abs3d_var[ks][is][js];\n                      }\n\n            } /* endof of if(input.rte.solver == SOLVER_POLRADTRAN) elsif {rte_in->ibcnd} else {} */\n\n            if (rte_outband->triangle_results) {  // Add triangle result -> output->result\n              const double factor = output->ipaweight[ipa];\n              status = add_triangular_surface_result (factor, rte_outband->triangle_results, output->triangle_results_r[iv]);\n              CHKERR (status);\n            }\n\n            /* verbose output */\n            if (input.verbose) {\n              fprintf (stderr,\n                       \"  iv = %d, %f nm, sum iq, flux_dir[lu=0] = %13.7e, flux_dn[lu=0] = %13.7e, flux_up[lu=0] = %13.7e \\n\",\n                       iv,\n                       output->wl.lambda_r[iv],\n                       output->rfldir_r[0][iv],\n                       output->rfldn_r[0][iv],\n                       output->flup_r[0][iv]);\n            }\n          } /* for (jipa=0; ipa<output->njipa; jipa++) independent pixel (ulrike) */\n        }   /* for (iipa=0; ipa<output->niipa; iipa++) independent pixel (ulrike) */\n      }     /* for (ipa=0; ipa<output->nipa; ipa++) independent pixel */\n\n      /* change unit of the solar spectrum [e.g. W/(m2 nm)] or terrestral spectrum [e.g. W/(m2 cm-1)]  */\n      /* to output units wanted by the user: 'output per_nm', 'output per_cm', or 'output per_band' */\n      /* but only, when dealing with unit (not transmission or reflectivity).                          */\n      /* Unit conversion must happen before interpolate transmittance, as some unit conversions        */\n      /* use the internal thermal bandwidths or correlated-k bandwidth.                                */\n      /* UH 2006-03                                                                                    */\n\n      if (output->wl.use_reptran)\n        unit_factor = 1; /* conversion is done in internal_to_transmittance_grid() */\n      else\n        unit_factor = get_unit_factor (input, output, iv);\n\n      if (unit_factor <= 0) {\n        fprintf (stderr, \"Error, calculating unit_factor = %f in %s (%s)\\n\", unit_factor, function_name, file_name);\n        return -1;\n      }\n\n      switch (input.source) {\n      case SRC_THERMAL:\n        ffactor = unit_factor;\n        rfactor = unit_factor;\n        break;\n\n      case SRC_SOLAR:\n      case SRC_BLITZ: /* BCA */\n      case SRC_LIDAR: /* BCA */\n        switch (input.processing) {\n        case PROCESS_INT:\n        case PROCESS_SUM:\n        case PROCESS_RGB:\n        case PROCESS_RGBNORM:\n          ffactor = unit_factor;\n          rfactor = unit_factor;\n          break;\n\n        case PROCESS_NONE:\n        case PROCESS_RAMAN:\n          switch (input.calibration) {\n          case OUTCAL_ABSOLUTE:\n            ffactor = unit_factor;\n            rfactor = unit_factor;\n            break;\n\n          case OUTCAL_TRANSMITTANCE:\n            ffactor = 1.0;\n            rfactor = 1.0;\n            break;\n\n          case OUTCAL_REFLECTIVITY:\n            ffactor = 1.0;\n            rfactor = 1.0;\n            break;\n\n          default:\n            fprintf (stderr, \"Error, unknown output calibration %d\\n\", input.calibration);\n            return -1;\n          }\n\n          break;\n\n        default:\n          fprintf (stderr, \"Error, unknown output processing %d\\n\", input.processing);\n          return -1;\n        }\n\n        break;\n\n      default:\n        fprintf (stderr, \"Error, unknown source %d\\n\", input.source);\n        return -1;\n      }\n\n      hfactor = unit_factor;\n\n      /*****************************************************************************************/\n      /* now scale irradiances with ffactor, radiances with rfactor, heating rate with hfactor */\n      /*****************************************************************************************/\n      status = scale_output (input,\n                             &(output->rfldir_r),\n                             &(output->rfldn_r),\n                             &(output->flup_r),\n                             &(output->albmed_r),\n                             &(output->trnmed_r),\n                             &(output->uavgso_r),\n                             &(output->uavgdn_r),\n                             &(output->uavgup_r),\n                             &(output->uavg_r),\n                             &(output->u0u_r),\n                             &(output->uu_r),\n                             &(output->heat_r),\n                             &(output->emis_r),\n                             &(output->w_zout_r),\n                             &(output->down_flux_r),\n                             &(output->up_flux_r),\n                             &(output->down_rad_r),\n                             &(output->up_rad_r),\n                             &(output->rfldir3d_r),\n                             &(output->rfldn3d_r),\n                             &(output->flup3d_r),\n                             &(output->fl3d_is_r),\n                             &(output->uavgso3d_r),\n                             &(output->uavgdn3d_r),\n                             &(output->uavgup3d_r),\n                             &(output->radiance3d_r),\n                             &(output->jacobian_r),\n                             &(output->absback3d_r),\n                             &(output->rfldir3d_var_r),\n                             &(output->rfldn3d_var_r),\n                             &(output->flup3d_var_r),\n                             &(output->uavgso3d_var_r),\n                             &(output->uavgdn3d_var_r),\n                             &(output->uavgup3d_var_r),\n                             &(output->radiance3d_var_r),\n                             &(output->abs3d_var_r),\n                             &(output->absback3d_var_r),\n                             output->atm.nzout,\n                             output->atm.Nxcld,\n                             output->atm.Nycld,\n                             output->atm.Nzcld,\n                             output->mc.alis.Nc,\n                             output->atm.nlev - 1,\n                             output->atm.threed,\n                             output->mc.sample.passback3D,\n                             output->islower,\n                             output->isupper,\n                             output->jslower,\n                             output->jsupper,\n                             output->isstep,\n                             output->jsstep,\n                             &(output->abs3d_r),\n                             output->triangle_results_r,\n                             ffactor,\n                             rfactor,\n                             hfactor,\n                             iv);\n      /* in ancillary.c */ /* **CK added  &(output->abs3d_var_r), for forward mc_std  */\n      CHKERR (status);\n\n      /* free 3D cloud properties */\n      if (input.rte.solver == SOLVER_MONTECARLO)\n        for (isp = 0; isp < input.n_caoth; isp++) {\n          status = free_caoth_mystic (input.caoth[isp].properties, &(output->caoth3d[isp]));\n          CHKERR (status);\n        }\n    } /*   for (ir=0; ir<nr; ir++) */\n    iv_count++;\n\n  } /* for (iv=output->wl.nlambda_rte_lower; iv<=output->wl.nlambda_rte_upper; iv++) */\n\n  /* ulrike: free msorted and zsorted (for tipa dir!!! for tipa\n             dirdiff msorted is freed already),\n             output->(w/i)c.tipa.taudircld, ... */\n  if (input.tipa == TIPA_DIR || input.rte.mc.tipa == TIPA_DIR) {\n    for (isp = 0; isp < input.n_caoth; isp++)\n      if (input.caoth[isp].source == CAOTH_FROM_3D) {\n        /* free m-and z-sorted for caoth */\n        for (iz = 0; iz < (output->caoth[isp].tipa.nztilt); iz++) {\n          for (ks = 0; ks < (output->caoth[isp].tipa.totlev[iz]); ks++)\n            free ((output->caoth[isp].tipa.msorted)[iz][ks]);\n          free ((output->caoth[isp].tipa.msorted)[iz]);\n          free ((output->caoth[isp].tipa.zsorted)[iz]);\n        }\n        free (output->caoth[isp].tipa.msorted);\n        free (output->caoth[isp].tipa.zsorted);\n\n        for (js = 0; js < (upper_wl_id - lower_wl_id + 1); js++) /* free taudircld for wc */\n          free ((output->caoth[isp].tipa.taudircld)[js]);\n        free (output->caoth[isp].tipa.taudircld);\n      }\n  }\n\n  /* free temporary memory */\n\n  status = free_rte_output (rte_out,\n                            input,\n                            output->atm.nzout,\n                            output->atm.Nxcld,\n                            output->atm.Nycld,\n                            output->atm.Nzcld,\n                            output->mc.sample.Nx,\n                            output->mc.sample.Ny,\n                            output->mc.alis.Nc,\n                            output->atm.nlyr - 1,\n                            output->mc.alis.nlambda_abs,\n                            output->atm.threed,\n                            output->mc.sample.passback3D);\n  CHKERR (status);\n\n  status = free_rte_output (rte_outband,\n                            input,\n                            output->atm.nzout,\n                            output->atm.Nxcld,\n                            output->atm.Nycld,\n                            output->atm.Nzcld,\n                            output->mc.sample.Nx,\n                            output->mc.sample.Ny,\n                            output->mc.alis.Nc,\n                            output->atm.nlyr - 1,\n                            output->mc.alis.nlambda_abs,\n                            output->atm.threed,\n                            output->mc.sample.passback3D);\n  CHKERR (status);\n\n  if (input.rte.solver == SOLVER_POLRADTRAN) {\n    free (rte_in->pol.height);\n    free (rte_in->pol.temperatures);\n    free (rte_in->pol.gas_extinct);\n  }\n  free (rte_in->pol.outlevels);\n  free (rte_in->hl);\n  free (rte_in->utau);\n  free (rte_in);\n  if (input.rte.solver == SOLVER_DISORT && input.raman) {\n    if (uu_raman != NULL)\n      ASCII_free_double_3D (uu_raman, output->atm.nzout, input.rte.nphi);\n    ASCII_free_double (u0u_raman, output->atm.nzout);\n    free (uavgso_raman);\n    free (uavgdn_raman);\n    free (uavgup_raman);\n    free (rfldir_raman);\n    free (rfldn_raman);\n    free (flup_raman);\n  }\n\n  if (input.raman) {\n    free_raman_qsrc_components (raman_qsrc_components,\n                                input.raman_fast,\n                                output->atm.nzout,\n                                input.rte.maxumu,\n                                input.rte.nphi,\n                                input.rte.nstr);\n  }\n\n  if (input.heating != HEAT_NONE) {\n    free (dz);\n    free (k_abs_layer);\n    free (k_abs);\n  }\n\n  if (save_cloud != NULL) {\n    free (save_cloud->tauw);\n    free (save_cloud->taui);\n    free (save_cloud->g1d);\n    free (save_cloud->g2d);\n    free (save_cloud->fd);\n    free (save_cloud->g1i);\n    free (save_cloud->g2i);\n    free (save_cloud->fi);\n    free (save_cloud->ssaw);\n    free (save_cloud->ssai);\n    free (save_cloud);\n  }\n\n#if HAVE_LIBGSL\n#ifdef WRITERANDOMSTATUS\n  if (remove (input.filename[FN_RANDOMSTATUS]) != 0)\n    fprintf (stderr, \"Error deleting randomstatusfile\");\n#endif\n#endif\n\n  return 0;\n}\n\n/* small function to get factor for unit conversion */\ndouble get_unit_factor (input_struct input, output_struct* output, int iv) {\n  double unit_factor = 0.0;\n\n  char function_name[] = \"get_unit_factor\";\n  char file_name[]     = \"solve_rte.c\";\n\n  switch (output->spectrum_unit) {\n  case UNIT_PER_NM:\n    switch (input.output_unit) {\n    case UNIT_PER_NM:\n      unit_factor = 1.0;\n      break;\n    case UNIT_PER_CM_1:\n      /* unit_factor = (lambda/k) */ /* (lambda/k) = (lambda**2) / 1.0e+7 */ /* 1.0e+7 == cm -> nm; */\n      unit_factor = (output->wl.lambda_r[iv] * output->wl.lambda_r[iv]) / 1.0e+7;\n      break;\n    case UNIT_PER_BAND:\n      /* unit_factor = delta_lambda */ /* lambda_max = 1.0e+7 / k_lower;  lambda_min = 1.0e+7 / k_upper */\n      unit_factor = 1.0e+7 / output->wl.wvnmlo_r[iv] - 1.0e+7 / output->wl.wvnmhi_r[iv];\n      break;\n    case UNIT_NOT_DEFINED:\n      unit_factor = 1.0;\n      break;\n    default:\n      fprintf (stderr,\n               \"Error: Program bug, unsupported output unit %d in %s (%s). \\n\",\n               input.output_unit,\n               function_name,\n               file_name);\n      return -1;\n    }\n    break;\n  case UNIT_PER_CM_1:\n    switch (input.output_unit) {\n    case UNIT_PER_NM:\n      /* unit_factor = (k/lambda) */ /* (k/lambda)= 1.0e+7 / (lambda**2) */ /* 1.0e+7 == cm -> nm; */\n      /* k wavenumber in 1/cm**-1, lambda in nm */\n      unit_factor = 1.0e+7 / (output->wl.lambda_r[iv] * output->wl.lambda_r[iv]);\n      break;\n    case UNIT_PER_CM_1:\n      unit_factor = 1.0;\n      break;\n    case UNIT_PER_BAND:\n      /* unit_factor = delta_k */\n      unit_factor = output->wl.wvnmhi_r[iv] - output->wl.wvnmlo_r[iv];\n      break;\n    case UNIT_NOT_DEFINED:\n      unit_factor = 1.0;\n      break;\n    default:\n      fprintf (stderr,\n               \"Error: Program bug, unsupported output unit %d in %s (%s). \\n\",\n               input.output_unit,\n               function_name,\n               file_name);\n      return -1;\n    }\n    break;\n  case UNIT_PER_BAND:\n    switch (input.output_unit) {\n    case UNIT_PER_NM:\n      /* unit_factor = 1 / delta_lambda */ /* lambda_max = 1.0e+7 / k_lower;  lambda_min = 1.0e+7 / k_upper */\n      unit_factor = 1.0 / (1.0e7 / output->wl.wvnmlo_r[iv] - 1.0e7 / output->wl.wvnmhi_r[iv]);\n      break;\n    case UNIT_PER_CM_1:\n      /* unit_factor = 1 / delta_k */\n      unit_factor = 1.0 / (output->wl.wvnmhi_r[iv] - output->wl.wvnmlo_r[iv]);\n      break;\n    case UNIT_PER_BAND:\n      unit_factor = 1.0;\n      break;\n    case UNIT_NOT_DEFINED: /* not defined */\n      unit_factor = 1.0;\n      break;\n    default:\n      fprintf (stderr, \"Error, program bug, unsupported output unit %d\\n\", input.output_unit);\n      return -1;\n    }\n    break;\n  case UNIT_NOT_DEFINED:\n    switch (input.output_unit) {\n    case UNIT_PER_NM:\n    case UNIT_PER_CM_1:\n    case UNIT_PER_BAND:\n      fprintf (stderr, \"Error, can not convert undefined solar spectrum to output with units\\n\");\n      fprintf (stderr, \"       please use 'solar_file filename unit' in order to specify the unit of the spectrum\\n\");\n      return -1;\n      break;\n    case UNIT_NOT_DEFINED: /* not defined */\n      unit_factor = 1.0;\n      break;\n    default:\n      fprintf (stderr, \"Error, program bug, unsupported output unit %d\\n\", input.output_unit);\n      return -1;\n    }\n    break;\n  default:\n    fprintf (stderr, \"Error: Program bug, unsupported unit of solar_file %d\\n\", output->spectrum_unit);\n    return -1;\n  }\n\n  return unit_factor;\n}\n\nint setup_result (input_struct   input,\n                  output_struct* output,\n                  float**        p_dz,\n                  double**       p_rho_mass_zout,\n                  float**        p_k_abs_layer,\n                  float**        p_k_abs,\n                  float**        p_k_abs_outband) {\n  int status  = 0;\n  int nlambda = 0;\n  int lc = 0, lu = 0, is = 0, js = 0, ip = 0, ic = 0;\n\n  /* FIX 3DAbs need to be initialized when aerosol is not set up, now redundant ??? */\n  /* output->mc.alis.Nc=1; */\n\n  if ((status = ASCII_calloc_float (&output->flup_r, output->atm.nzout, output->wl.nlambda_r)) != 0)\n    return status;\n\n  if ((status = ASCII_calloc_float (&output->rfldir_r, output->atm.nzout, output->wl.nlambda_r)) != 0)\n    return status;\n\n  if ((status = ASCII_calloc_float (&output->rfldn_r, output->atm.nzout, output->wl.nlambda_r)) != 0)\n    return status;\n\n  if ((status = ASCII_calloc_float (&output->uavg_r, output->atm.nzout, output->wl.nlambda_r)) != 0)\n    return status;\n\n  if ((status = ASCII_calloc_float (&output->uavgdn_r, output->atm.nzout, output->wl.nlambda_r)) != 0)\n    return status;\n\n  if ((status = ASCII_calloc_float (&output->uavgso_r, output->atm.nzout, output->wl.nlambda_r)) != 0)\n    return status;\n\n  if ((status = ASCII_calloc_float (&output->uavgup_r, output->atm.nzout, output->wl.nlambda_r)) != 0)\n    return status;\n\n  if ((status = ASCII_calloc_float (&output->heat_r, output->atm.nzout, output->wl.nlambda_r)) != 0)\n    return status;\n\n  if ((status = ASCII_calloc_float (&output->emis_r, output->atm.nzout, output->wl.nlambda_r)) != 0)\n    return status;\n\n  if ((status = ASCII_calloc_float (&output->w_zout_r, output->atm.nzout, output->wl.nlambda_r)) != 0)\n    return status;\n\n  if ((status = ASCII_calloc_float (&output->sslidar_nphot_r, output->atm.nzout, output->wl.nlambda_r)) != 0)\n    return status;\n\n  if ((status = ASCII_calloc_float (&output->sslidar_nphot_q_r, output->atm.nzout, output->wl.nlambda_r)) != 0)\n    return status;\n\n  if ((status = ASCII_calloc_float (&output->sslidar_ratio_r, output->atm.nzout, output->wl.nlambda_r)) != 0)\n    return status;\n\n  if ((status = ASCII_calloc_float (&output->albmed_r, input.rte.numu, output->wl.nlambda_r)) != 0)\n    return status;\n\n  if ((status = ASCII_calloc_float (&output->trnmed_r, input.rte.numu, output->wl.nlambda_r)) != 0)\n    return status;\n\n  /* variables in order to calculate heating rates (by actinic flux) */\n  if (input.heating != HEAT_NONE) {\n\n    *p_dz = calloc (output->atm.nlyr, sizeof (float)); /* dz in m for all (nlyr) layers */\n    CHKPOINTER (*p_dz);\n\n    /* Initialisation */\n    for (lc = 0; lc < output->atm.nlyr; lc++) {\n      (*p_dz)[lc] = (output->atm.zd[lc] - output->atm.zd[lc + 1]) * 1000.0; /* km -> m */\n    }\n\n    *p_rho_mass_zout = calloc (output->atm.nzout, sizeof (double));\n    CHKPOINTER (*p_rho_mass_zout);\n\n    *p_k_abs_layer = calloc (output->atm.nlyr, sizeof (float));\n    CHKPOINTER (*p_k_abs_layer);\n\n    *p_k_abs = calloc (output->atm.nzout, sizeof (float));\n    CHKPOINTER (*p_k_abs);\n\n    *p_k_abs_outband = calloc (output->atm.nzout, sizeof (float));\n    CHKPOINTER (*p_k_abs_outband);\n  }\n\n  if (input.rte.numu > 0) {\n    status = ASCII_calloc_float_3D (&output->u0u_r, output->atm.nzout, input.rte.numu, output->wl.nlambda_r);\n    CHKERR (status);\n  }\n\n  if (input.rte.numu > 0 && input.rte.nphi > 0) {\n    status = ASCII_calloc_float_4D (&output->uu_r, output->atm.nzout, input.rte.nphi, input.rte.numu, output->wl.nlambda_r);\n    CHKERR (status);\n  }\n\n  if (output->mc.sample.passback3D) {\n\n    if (!input.quiet)\n      fprintf (stderr,\n               \" ... allocating %d x %d x %d x %d = %d pixels (%d bytes) for 3D output\\n\",\n               output->atm.nzout,\n               (output->isupper - output->islower + 1),\n               (output->jsupper - output->jslower + 1),\n               output->wl.nlambda_r,\n               output->atm.nzout * (output->isupper - output->islower + 1) * (output->jsupper - output->jslower + 1) *\n                 output->wl.nlambda_r,\n               output->atm.nzout * (output->isupper - output->islower + 1) * (output->jsupper - output->jslower + 1) *\n                 output->wl.nlambda_r * (int)sizeof (float));\n\n    /* allocate only output pixels which are actually required  */\n    /* (defined by mc_backward islower jslower isupper jsupper) */\n\n    output->rfldir3d_r   = calloc (output->atm.nzout, sizeof (float***));\n    output->rfldn3d_r    = calloc (output->atm.nzout, sizeof (float***));\n    output->flup3d_r     = calloc (output->atm.nzout, sizeof (float***));\n    output->uavgso3d_r   = calloc (output->atm.nzout, sizeof (float***));\n    output->uavgdn3d_r   = calloc (output->atm.nzout, sizeof (float***));\n    output->uavgup3d_r   = calloc (output->atm.nzout, sizeof (float***));\n    output->radiance3d_r = calloc (output->atm.nzout, sizeof (float*****));\n\n    if (input.rte.mc.spectral_is || input.rte.mc.concentration_is)\n      if ((status = ASCII_calloc_float_5D (&output->fl3d_is_r,\n                                           output->atm.nzout,\n                                           output->mc.sample.Nx,\n                                           output->mc.sample.Ny,\n                                           output->mc.alis.Nc,\n                                           output->wl.nlambda_r)) != 0)\n        return status;\n\n    /* So far we allow only 1D output for postprocessing */\n    if (input.rte.mc.jacobian[DIM_1D])\n      if ((status = ASCII_calloc_float_7D (&output->jacobian_r,\n                                           output->atm.nzout,\n                                           1,\n                                           1,\n                                           input.n_caoth + 2,\n                                           2,\n                                           output->atm.nlev - 1,\n                                           output->wl.nlambda_r)) != 0)\n        return status;\n\n    if (input.rte.mc.backward.absorption)\n      output->absback3d_r = calloc (output->atm.nzout, sizeof (float***));\n\n    /* variances */\n    if (input.rte.mc.std) {\n      output->rfldir3d_var_r   = calloc (output->atm.nzout, sizeof (float***));\n      output->rfldn3d_var_r    = calloc (output->atm.nzout, sizeof (float***));\n      output->flup3d_var_r     = calloc (output->atm.nzout, sizeof (float***));\n      output->uavgso3d_var_r   = calloc (output->atm.nzout, sizeof (float***));\n      output->uavgdn3d_var_r   = calloc (output->atm.nzout, sizeof (float***));\n      output->uavgup3d_var_r   = calloc (output->atm.nzout, sizeof (float***));\n      output->radiance3d_var_r = calloc (output->atm.nzout, sizeof (float****));\n\n      if (input.rte.mc.backward.absorption)\n        output->absback3d_var_r = calloc (output->atm.nzout, sizeof (float***));\n    }\n\n    for (lu = 0; lu < output->atm.nzout; lu++) {\n      output->rfldir3d_r[lu]   = calloc (output->mc.sample.Nx, sizeof (float**));\n      output->rfldn3d_r[lu]    = calloc (output->mc.sample.Nx, sizeof (float**));\n      output->flup3d_r[lu]     = calloc (output->mc.sample.Nx, sizeof (float**));\n      output->uavgso3d_r[lu]   = calloc (output->mc.sample.Nx, sizeof (float**));\n      output->uavgdn3d_r[lu]   = calloc (output->mc.sample.Nx, sizeof (float**));\n      output->uavgup3d_r[lu]   = calloc (output->mc.sample.Nx, sizeof (float**));\n      output->radiance3d_r[lu] = calloc (output->mc.sample.Nx, sizeof (float****));\n\n      if (input.rte.mc.backward.absorption)\n        output->absback3d_r[lu] = calloc (output->mc.sample.Nx, sizeof (float**));\n\n      /* variances */\n      if (input.rte.mc.std) {\n        output->rfldir3d_var_r[lu]   = calloc (output->mc.sample.Nx, sizeof (float**));\n        output->rfldn3d_var_r[lu]    = calloc (output->mc.sample.Nx, sizeof (float**));\n        output->flup3d_var_r[lu]     = calloc (output->mc.sample.Nx, sizeof (float**));\n        output->uavgso3d_var_r[lu]   = calloc (output->mc.sample.Nx, sizeof (float**));\n        output->uavgdn3d_var_r[lu]   = calloc (output->mc.sample.Nx, sizeof (float**));\n        output->uavgup3d_var_r[lu]   = calloc (output->mc.sample.Nx, sizeof (float**));\n        output->radiance3d_var_r[lu] = calloc (output->mc.sample.Nx, sizeof (float***));\n\n        if (input.rte.mc.backward.absorption)\n          output->absback3d_var_r[lu] = calloc (output->mc.sample.Nx, sizeof (float**));\n      }\n\n      for (is = output->islower; is <= output->isupper; is += output->isstep) {\n        output->rfldir3d_r[lu][is]   = calloc (output->mc.sample.Ny, sizeof (float*));\n        output->rfldn3d_r[lu][is]    = calloc (output->mc.sample.Ny, sizeof (float*));\n        output->flup3d_r[lu][is]     = calloc (output->mc.sample.Ny, sizeof (float*));\n        output->uavgso3d_r[lu][is]   = calloc (output->mc.sample.Ny, sizeof (float*));\n        output->uavgdn3d_r[lu][is]   = calloc (output->mc.sample.Ny, sizeof (float*));\n        output->uavgup3d_r[lu][is]   = calloc (output->mc.sample.Ny, sizeof (float*));\n        output->radiance3d_r[lu][is] = calloc (output->mc.sample.Ny, sizeof (float***));\n\n        if (input.rte.mc.backward.absorption)\n          output->absback3d_r[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*));\n\n        /* variances */\n        if (input.rte.mc.std) {\n          output->rfldir3d_var_r[lu][is]   = calloc (output->mc.sample.Ny, sizeof (float*));\n          output->rfldn3d_var_r[lu][is]    = calloc (output->mc.sample.Ny, sizeof (float*));\n          output->flup3d_var_r[lu][is]     = calloc (output->mc.sample.Ny, sizeof (float*));\n          output->uavgso3d_var_r[lu][is]   = calloc (output->mc.sample.Ny, sizeof (float*));\n          output->uavgdn3d_var_r[lu][is]   = calloc (output->mc.sample.Ny, sizeof (float*));\n          output->uavgup3d_var_r[lu][is]   = calloc (output->mc.sample.Ny, sizeof (float*));\n          output->radiance3d_var_r[lu][is] = calloc (output->mc.sample.Ny, sizeof (float**));\n\n          if (input.rte.mc.backward.absorption)\n            output->absback3d_var_r[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*));\n        }\n\n        for (js = output->jslower; js <= output->jsupper; js += output->jsstep) {\n          output->rfldir3d_r[lu][is][js]   = calloc (output->wl.nlambda_r, sizeof (float));\n          output->rfldn3d_r[lu][is][js]    = calloc (output->wl.nlambda_r, sizeof (float));\n          output->flup3d_r[lu][is][js]     = calloc (output->wl.nlambda_r, sizeof (float));\n          output->uavgso3d_r[lu][is][js]   = calloc (output->wl.nlambda_r, sizeof (float));\n          output->uavgdn3d_r[lu][is][js]   = calloc (output->wl.nlambda_r, sizeof (float));\n          output->uavgup3d_r[lu][is][js]   = calloc (output->wl.nlambda_r, sizeof (float));\n          output->radiance3d_r[lu][is][js] = calloc (input.rte.mc.nstokes, sizeof (float**));\n\n          for (ip = 0; ip < input.rte.mc.nstokes; ip++) {\n            output->radiance3d_r[lu][is][js][ip] = calloc (output->mc.alis.Nc, sizeof (float*));\n\n            for (ic = 0; ic < output->mc.alis.Nc; ic++)\n              output->radiance3d_r[lu][is][js][ip][ic] = calloc (output->wl.nlambda_r, sizeof (float));\n          }\n\n          if (input.rte.mc.backward.absorption)\n            output->absback3d_r[lu][is][js] = calloc (output->wl.nlambda_r, sizeof (float));\n\n          /* variances */\n          if (input.rte.mc.std) {\n            output->rfldir3d_var_r[lu][is][js]   = calloc (output->wl.nlambda_r, sizeof (float));\n            output->rfldir3d_var_r[lu][is][js]   = calloc (output->wl.nlambda_r, sizeof (float));\n            output->rfldn3d_var_r[lu][is][js]    = calloc (output->wl.nlambda_r, sizeof (float));\n            output->flup3d_var_r[lu][is][js]     = calloc (output->wl.nlambda_r, sizeof (float));\n            output->uavgso3d_var_r[lu][is][js]   = calloc (output->wl.nlambda_r, sizeof (float));\n            output->uavgdn3d_var_r[lu][is][js]   = calloc (output->wl.nlambda_r, sizeof (float));\n            output->uavgup3d_var_r[lu][is][js]   = calloc (output->wl.nlambda_r, sizeof (float));\n            output->radiance3d_var_r[lu][is][js] = calloc (input.rte.mc.nstokes, sizeof (float*));\n\n            for (ip = 0; ip < input.rte.mc.nstokes; ip++)\n              output->radiance3d_var_r[lu][is][js][ip] = calloc (output->wl.nlambda_r, sizeof (float));\n\n            if (input.rte.mc.backward.absorption)\n              output->absback3d_var_r[lu][is][js] = calloc (output->wl.nlambda_r, sizeof (float));\n          }\n        }\n      }\n    }\n\n    /* 3d absorption */\n    if (input.rte.mc.absorption != MCFORWARD_ABS_NONE || input.ipa3d) { /*ulrike: added || input.ipa3d*/ /* **CK added bracket */\n      output->abs3d_r =\n        calloc_spectral_abs3d (output->atm.Nxcld, output->atm.Nycld, output->atm.Nzcld, output->wl.nlambda_r, output->atm.threed);\n      CHKPOINTEROUT (output->abs3d_r, \"Error allocating memory for output->abs3d_r\");\n\n      if (input.rte.mc.std) {\n        output->abs3d_var_r =\n          calloc_spectral_abs3d (output->atm.Nxcld, output->atm.Nycld, output->atm.Nzcld, output->wl.nlambda_r, output->atm.threed);\n        CHKPOINTEROUT (output->abs3d_var_r, \"Error allocating memory for output->abs3d_var_r\");\n      }\n    }\n  }\n\n  /* need to allocate enough memory for both output->wl.nlambda_s */\n  /* and output->wl.nlambda_h, hence using whichever is larger    */\n  nlambda = (output->wl.nlambda_h > output->wl.nlambda_s ? output->wl.nlambda_h : output->wl.nlambda_s);\n\n  if ((status = ASCII_calloc_float (&output->flup, output->atm.nzout, nlambda)) != 0)\n    return status;\n\n  if ((status = ASCII_calloc_float (&output->rfldn, output->atm.nzout, nlambda)) != 0)\n    return status;\n\n  if ((status = ASCII_calloc_float (&output->rfldir, output->atm.nzout, nlambda)) != 0)\n    return status;\n\n  if ((status = ASCII_calloc_float (&output->uavg, output->atm.nzout, nlambda)) != 0)\n    return status;\n\n  if ((status = ASCII_calloc_float (&output->uavgdn, output->atm.nzout, nlambda)) != 0)\n    return status;\n\n  if ((status = ASCII_calloc_float (&output->uavgso, output->atm.nzout, nlambda)) != 0)\n    return status;\n\n  if ((status = ASCII_calloc_float (&output->uavgup, output->atm.nzout, nlambda)) != 0)\n    return status;\n\n  if ((status = ASCII_calloc_float (&output->heat, output->atm.nzout, nlambda)) != 0)\n    return status;\n\n  if ((status = ASCII_calloc_float (&output->emis, output->atm.nzout, nlambda)) != 0)\n    return status;\n\n  if ((status = ASCII_calloc_float (&output->albmed, input.rte.numu, nlambda)) != 0)\n    return status;\n\n  if ((status = ASCII_calloc_float (&output->trnmed, input.rte.numu, nlambda)) != 0)\n    return status;\n\n  if ((status = ASCII_calloc_float (&output->w_zout, output->atm.nzout, nlambda)) != 0)\n    return status;\n\n  if ((status = ASCII_calloc_float_3D (&output->down_flux, output->atm.nzout, input.rte.polradtran[POLRADTRAN_NSTOKES], nlambda)) !=\n      0)\n    return status;\n\n  if ((status = ASCII_calloc_float_3D (&output->down_flux_r,\n                                       output->atm.nzout,\n                                       input.rte.polradtran[POLRADTRAN_NSTOKES],\n                                       output->wl.nlambda_r)) != 0)\n    return status;\n\n  if ((status = ASCII_calloc_float_3D (&output->up_flux, output->atm.nzout, input.rte.polradtran[POLRADTRAN_NSTOKES], nlambda)) !=\n      0)\n    return status;\n\n  if ((status = ASCII_calloc_float_3D (&output->up_flux_r,\n                                       output->atm.nzout,\n                                       input.rte.polradtran[POLRADTRAN_NSTOKES],\n                                       output->wl.nlambda_r)) != 0)\n    return status;\n\n  if (input.rte.nphi > 0) {\n    if ((status = ASCII_calloc_float_5D (&output->down_rad,\n                                         output->atm.nzout,\n                                         input.rte.nphi,\n                                         input.rte.numu,\n                                         input.rte.polradtran[POLRADTRAN_NSTOKES],\n                                         nlambda)) != 0)\n      return status;\n\n    if ((status = ASCII_calloc_float_5D (&output->down_rad_r,\n                                         output->atm.nzout,\n                                         input.rte.nphi,\n                                         input.rte.numu,\n                                         input.rte.polradtran[POLRADTRAN_NSTOKES],\n                                         output->wl.nlambda_r)) != 0)\n      return status;\n\n    if ((status = ASCII_calloc_float_5D (&output->up_rad,\n                                         output->atm.nzout,\n                                         input.rte.nphi,\n                                         input.rte.numu,\n                                         input.rte.polradtran[POLRADTRAN_NSTOKES],\n                                         nlambda)) != 0)\n      return status;\n\n    if ((status = ASCII_calloc_float_5D (&output->up_rad_r,\n                                         output->atm.nzout,\n                                         input.rte.nphi,\n                                         input.rte.numu,\n                                         input.rte.polradtran[POLRADTRAN_NSTOKES],\n                                         output->wl.nlambda_r)) != 0)\n      return status;\n  }\n\n  if (input.rte.numu > 0)\n    if ((status = ASCII_calloc_float_3D (&output->u0u, output->atm.nzout, input.rte.numu, nlambda)) != 0)\n      return status;\n\n  if (input.rte.numu > 0 && input.rte.nphi > 0)\n    if ((status = ASCII_calloc_float_4D (&output->uu, output->atm.nzout, input.rte.nphi, input.rte.numu, nlambda)) != 0)\n      return status;\n\n  if ((status = ASCII_calloc_float (&output->sslidar_nphot, output->atm.nzout, nlambda)) != 0)\n    return status;\n  if ((status = ASCII_calloc_float (&output->sslidar_nphot_q, output->atm.nzout, nlambda)) != 0)\n    return status;\n  if ((status = ASCII_calloc_float (&output->sslidar_ratio, output->atm.nzout, nlambda)) != 0)\n    return status;\n\n  if (output->mc.sample.passback3D) {\n\n    /* allocate only output pixels which are actually required  */\n    /* (defined by mc_backward islower jslower isupper jsupper) */\n\n    output->rfldir3d   = calloc (output->atm.nzout, sizeof (float***));\n    output->rfldn3d    = calloc (output->atm.nzout, sizeof (float***));\n    output->flup3d     = calloc (output->atm.nzout, sizeof (float***));\n    output->uavgso3d   = calloc (output->atm.nzout, sizeof (float***));\n    output->uavgdn3d   = calloc (output->atm.nzout, sizeof (float***));\n    output->uavgup3d   = calloc (output->atm.nzout, sizeof (float***));\n    output->radiance3d = calloc (output->atm.nzout, sizeof (float*****));\n\n    if (input.rte.mc.spectral_is || input.rte.mc.concentration_is) {\n      if ((status = ASCII_calloc_float_5D (&output->fl3d_is,\n                                           output->atm.nzout,\n                                           output->mc.sample.Nx,\n                                           output->mc.sample.Ny,\n                                           output->mc.alis.Nc,\n                                           nlambda)) != 0)\n        return status;\n    }\n\n    if (input.rte.mc.jacobian[DIM_1D])\n      if ((status = ASCII_calloc_float_7D (&output->jacobian,\n                                           output->atm.nzout,\n                                           1,\n                                           1,\n                                           input.n_caoth + 2,\n                                           2,\n                                           output->atm.nlev - 1,\n                                           nlambda)) != 0)\n        return status;\n\n    if (input.rte.mc.backward.absorption)\n      output->absback3d = calloc (output->atm.nzout, sizeof (float***));\n\n    /* variances */\n    if (input.rte.mc.std) {\n      output->rfldir3d_var   = calloc (output->atm.nzout, sizeof (float***));\n      output->rfldn3d_var    = calloc (output->atm.nzout, sizeof (float***));\n      output->flup3d_var     = calloc (output->atm.nzout, sizeof (float***));\n      output->uavgso3d_var   = calloc (output->atm.nzout, sizeof (float***));\n      output->uavgdn3d_var   = calloc (output->atm.nzout, sizeof (float***));\n      output->uavgup3d_var   = calloc (output->atm.nzout, sizeof (float***));\n      output->radiance3d_var = calloc (output->atm.nzout, sizeof (float****));\n\n      if (input.rte.mc.backward.absorption)\n        output->absback3d_var = calloc (output->atm.nzout, sizeof (float***));\n    }\n\n    for (lu = 0; lu < output->atm.nzout; lu++) {\n      output->rfldir3d[lu]   = calloc (output->mc.sample.Nx, sizeof (float**));\n      output->rfldn3d[lu]    = calloc (output->mc.sample.Nx, sizeof (float**));\n      output->flup3d[lu]     = calloc (output->mc.sample.Nx, sizeof (float**));\n      output->uavgso3d[lu]   = calloc (output->mc.sample.Nx, sizeof (float**));\n      output->uavgdn3d[lu]   = calloc (output->mc.sample.Nx, sizeof (float**));\n      output->uavgup3d[lu]   = calloc (output->mc.sample.Nx, sizeof (float**));\n      output->radiance3d[lu] = calloc (output->mc.sample.Nx, sizeof (float****));\n\n      if (input.rte.mc.backward.absorption)\n        output->absback3d[lu] = calloc (output->mc.sample.Nx, sizeof (float**));\n\n      /* variances */\n      if (input.rte.mc.std) {\n        output->rfldir3d_var[lu]   = calloc (output->mc.sample.Nx, sizeof (float**));\n        output->rfldn3d_var[lu]    = calloc (output->mc.sample.Nx, sizeof (float**));\n        output->flup3d_var[lu]     = calloc (output->mc.sample.Nx, sizeof (float**));\n        output->uavgso3d_var[lu]   = calloc (output->mc.sample.Nx, sizeof (float**));\n        output->uavgdn3d_var[lu]   = calloc (output->mc.sample.Nx, sizeof (float**));\n        output->uavgup3d_var[lu]   = calloc (output->mc.sample.Nx, sizeof (float**));\n        output->radiance3d_var[lu] = calloc (output->mc.sample.Nx, sizeof (float***));\n\n        if (input.rte.mc.backward.absorption)\n          output->absback3d_var[lu] = calloc (output->mc.sample.Nx, sizeof (float**));\n      }\n\n      for (is = output->islower; is <= output->isupper; is += output->isstep) {\n        output->rfldir3d[lu][is]   = calloc (output->mc.sample.Ny, sizeof (float*));\n        output->rfldn3d[lu][is]    = calloc (output->mc.sample.Ny, sizeof (float*));\n        output->flup3d[lu][is]     = calloc (output->mc.sample.Ny, sizeof (float*));\n        output->uavgso3d[lu][is]   = calloc (output->mc.sample.Ny, sizeof (float*));\n        output->uavgdn3d[lu][is]   = calloc (output->mc.sample.Ny, sizeof (float*));\n        output->uavgup3d[lu][is]   = calloc (output->mc.sample.Ny, sizeof (float*));\n        output->radiance3d[lu][is] = calloc (output->mc.sample.Ny, sizeof (float***));\n\n        if (input.rte.mc.backward.absorption)\n          output->absback3d[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*));\n\n        /* variances */\n        if (input.rte.mc.std) {\n          output->rfldir3d_var[lu][is]   = calloc (output->mc.sample.Ny, sizeof (float*));\n          output->rfldn3d_var[lu][is]    = calloc (output->mc.sample.Ny, sizeof (float*));\n          output->flup3d_var[lu][is]     = calloc (output->mc.sample.Ny, sizeof (float*));\n          output->uavgso3d_var[lu][is]   = calloc (output->mc.sample.Ny, sizeof (float*));\n          output->uavgdn3d_var[lu][is]   = calloc (output->mc.sample.Ny, sizeof (float*));\n          output->uavgup3d_var[lu][is]   = calloc (output->mc.sample.Ny, sizeof (float*));\n          output->radiance3d_var[lu][is] = calloc (output->mc.sample.Ny, sizeof (float**));\n\n          if (input.rte.mc.backward.absorption)\n            output->absback3d_var[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*));\n        }\n\n        for (js = output->jslower; js <= output->jsupper; js += output->jsstep) {\n          output->rfldir3d[lu][is][js]   = calloc (nlambda, sizeof (float));\n          output->rfldn3d[lu][is][js]    = calloc (nlambda, sizeof (float));\n          output->flup3d[lu][is][js]     = calloc (nlambda, sizeof (float));\n          output->uavgso3d[lu][is][js]   = calloc (nlambda, sizeof (float));\n          output->uavgdn3d[lu][is][js]   = calloc (nlambda, sizeof (float));\n          output->uavgup3d[lu][is][js]   = calloc (nlambda, sizeof (float));\n          output->radiance3d[lu][is][js] = calloc (input.rte.mc.nstokes, sizeof (float**));\n\n          for (ip = 0; ip < input.rte.mc.nstokes; ip++) {\n            output->radiance3d[lu][is][js][ip] = calloc (output->mc.alis.Nc, sizeof (float*));\n\n            for (ic = 0; ic < output->mc.alis.Nc; ic++) {\n              output->radiance3d[lu][is][js][ip][ic] = calloc (nlambda, sizeof (float));\n            }\n          }\n\n          if (input.rte.mc.backward.absorption)\n            output->absback3d[lu][is][js] = calloc (nlambda, sizeof (float));\n\n          /* variances */\n          if (input.rte.mc.std) {\n            output->rfldir3d_var[lu][is][js]   = calloc (nlambda, sizeof (float));\n            output->rfldn3d_var[lu][is][js]    = calloc (nlambda, sizeof (float));\n            output->flup3d_var[lu][is][js]     = calloc (nlambda, sizeof (float));\n            output->uavgso3d_var[lu][is][js]   = calloc (nlambda, sizeof (float));\n            output->uavgdn3d_var[lu][is][js]   = calloc (nlambda, sizeof (float));\n            output->uavgup3d_var[lu][is][js]   = calloc (nlambda, sizeof (float));\n            output->radiance3d_var[lu][is][js] = calloc (input.rte.mc.nstokes, sizeof (float*));\n\n            for (ip = 0; ip < input.rte.mc.nstokes; ip++)\n              output->radiance3d_var[lu][is][js][ip] = calloc (nlambda, sizeof (float));\n\n            if (input.rte.mc.backward.absorption)\n              output->absback3d_var[lu][is][js] = calloc (nlambda, sizeof (float));\n          }\n        }\n      }\n    }\n\n    /* 3D absorption */\n    if (input.rte.mc.absorption != MCFORWARD_ABS_NONE || input.ipa3d) {\n      output->abs3d = calloc_spectral_abs3d (output->atm.Nxcld, output->atm.Nycld, output->atm.Nzcld, nlambda, output->atm.threed);\n      CHKPOINTEROUT (output->abs3d, \"Error allocating memory for output->abs3d\");\n\n      if (input.rte.mc.std) {\n        output->abs3d_var =\n          calloc_spectral_abs3d (output->atm.Nxcld, output->atm.Nycld, output->atm.Nzcld, nlambda, output->atm.threed);\n        CHKPOINTEROUT (output->abs3d_var, \"Error allocating memory for output->abs3d_var\");\n      }\n    }\n  }\n\n  output->sza_h = calloc (output->wl.nlambda_h, sizeof (float));\n  CHKPOINTER (output->sza_h);\n\n  {  // allocate triangle output\n    output->triangle_results_r = NULL;\n    output->triangle_results_t = NULL;\n    output->triangle_results_o = NULL;\n\n    const int ierr = init_spectral_triangular_surface_result_struct (output->wl.nlambda_r,\n                                                                     output->mc.triangular_surface.N_triangles,\n                                                                     &(output->triangle_results_r));\n    CHKERR (ierr);\n  }\n\n  return 0;\n} /*ulrike: end of setup_result*/\n\nstatic int reverse_profiles (input_struct input, output_struct* output) {\n  int    lu = 0, iu = 0;\n  double tmp = 0;\n\n  for (lu = 0; lu < output->atm.nlyr / 2; lu++) {\n\n    /* reverse profile of optical depth dtauc */\n    tmp                                      = output->dtauc[output->atm.nlyr - lu - 1];\n    output->dtauc[output->atm.nlyr - lu - 1] = output->dtauc[lu];\n    output->dtauc[lu]                        = tmp;\n\n    /* reverse profile of single scattering albedo ssalb */\n    tmp                                      = output->ssalb[output->atm.nlyr - lu - 1];\n    output->ssalb[output->atm.nlyr - lu - 1] = output->ssalb[lu];\n    output->ssalb[lu]                        = tmp;\n\n    /* reverse profile of phase function pmom */\n    for (iu = 0; iu <= input.rte.nstr; iu++) {\n      tmp                                            = output->pmom[output->atm.nlyr - lu - 1][0][iu];\n      output->pmom[output->atm.nlyr - lu - 1][0][iu] = output->pmom[lu][0][iu];\n      output->pmom[lu][0][iu]                        = tmp;\n    }\n  }\n  return 0;\n}\n\n/* allocate memory for Raman scattering components needed for calculation of */\n/* source function for second iteration                                      */\nraman_qsrc_components* calloc_raman_qsrc_components (int raman_fast, int nzout, int maxumu, int nphi, int nstr, int nlambda) {\n  raman_qsrc_components* result = calloc (1, sizeof (raman_qsrc_components));\n\n  if (raman_fast) {\n    ASCII_calloc_double (&result->uavgso, nzout, nlambda);\n    ASCII_calloc_double (&result->uavgdn, nzout, nlambda);\n    ASCII_calloc_double (&result->uavgup, nzout, nlambda);\n    ASCII_calloc_double (&result->rfldir, nzout, nlambda);\n    ASCII_calloc_double (&result->rfldn, nzout, nlambda);\n    ASCII_calloc_double (&result->flup, nzout, nlambda);\n    ASCII_calloc_double_3D (&result->u0u, nzout, maxumu, nlambda);\n    ASCII_calloc_double_4D (&result->uu, nzout, maxumu, maxumu, nlambda);\n  }\n  result->fbeam = (double*)calloc (nlambda, sizeof (double));\n  ASCII_calloc_double (&result->dtauc, nzout, nlambda);\n  ASCII_calloc_double_4D (&result->uum, nzout, maxumu, maxumu, nlambda);\n\n  return result;\n}\n\n/* free memory for Raman scattering components needed for calculation of */\n/* source function for second iteration                                      */\nstatic void free_raman_qsrc_components (raman_qsrc_components* result, int raman_fast, int nzout, int maxumu, int nphi, int nstr) {\n  if (raman_fast) {\n    if (result->uavgso != NULL)\n      ASCII_free_double (result->uavgso, nzout);\n    if (result->uavgup != NULL)\n      ASCII_free_double (result->uavgup, nzout);\n    if (result->uavgdn != NULL)\n      ASCII_free_double (result->uavgdn, nzout);\n    if (result->rfldir != NULL)\n      ASCII_free_double (result->rfldir, nzout);\n    if (result->rfldn != NULL)\n      ASCII_free_double (result->rfldn, nzout);\n    if (result->flup != NULL)\n      ASCII_free_double (result->flup, nzout);\n    if (result->u0u != NULL)\n      ASCII_free_double_3D (result->u0u, nzout, maxumu);\n    if (result->uu != NULL)\n      ASCII_free_double_4D (result->uu, nzout, maxumu, maxumu);\n  }\n  if (result->fbeam != NULL)\n    free (result->fbeam);\n  if (result->dtauc != NULL)\n    ASCII_free_double (result->dtauc, nzout);\n  if (result->uum != NULL)\n    ASCII_free_double_4D (result->uum, nzout, maxumu, maxumu);\n\n  free (result);\n}\n\n/* allocate temporary memory optical properties */\nstatic save_optprop* calloc_save_optprop (int Nlev) {\n  save_optprop* result = calloc (1, sizeof (save_optprop));\n\n  result->tauw = (float*)calloc (Nlev, sizeof (float));\n  result->taui = (float*)calloc (Nlev, sizeof (float));\n  result->g1d  = (float*)calloc (Nlev, sizeof (float));\n  result->g2d  = (float*)calloc (Nlev, sizeof (float));\n  result->fd   = (float*)calloc (Nlev, sizeof (float));\n  result->g1i  = (float*)calloc (Nlev, sizeof (float));\n  result->g2i  = (float*)calloc (Nlev, sizeof (float));\n  result->fi   = (float*)calloc (Nlev, sizeof (float));\n  result->ssaw = (float*)calloc (Nlev, sizeof (float));\n  result->ssai = (float*)calloc (Nlev, sizeof (float));\n\n  return result;\n}\n\n/* allocate temporary memory for the RTE solvers */\nstatic rte_output* calloc_rte_output (input_struct input,\n                                      int          nzout,\n                                      int          Nxcld,\n                                      int          Nycld,\n                                      int          Nzcld,\n                                      int          Nxsample,\n                                      int          Nysample,\n                                      int          Ncsample,\n                                      int          Nlambda,\n                                      int          Nlyr,\n                                      int*         threed,\n                                      int          passback3D,\n                                      const size_t N_triangles) {\n  int status = 0;\n\n  rte_output* result = calloc (1, sizeof (rte_output));\n\n  result->albmed          = calloc (input.rte.maxumu, sizeof (float));\n  result->trnmed          = calloc (input.rte.maxumu, sizeof (float));\n  result->dfdt            = calloc (nzout, sizeof (float));\n  result->flup            = calloc (nzout, sizeof (float));\n  result->rfldir          = calloc (nzout, sizeof (float));\n  result->rfldn           = calloc (nzout, sizeof (float));\n  result->uavg            = calloc (nzout, sizeof (float));\n  result->uavgdn          = calloc (nzout, sizeof (float));\n  result->uavgso          = calloc (nzout, sizeof (float));\n  result->uavgup          = calloc (nzout, sizeof (float));\n  result->heat            = calloc (nzout, sizeof (float));\n  result->emis            = calloc (nzout, sizeof (float));\n  result->w_zout          = calloc (nzout, sizeof (float));\n  result->sslidar_nphot   = calloc (nzout, sizeof (float));\n  result->sslidar_nphot_q = calloc (nzout, sizeof (float));\n  result->sslidar_ratio   = calloc (nzout, sizeof (float));\n\n  if (input.rte.maxumu > 0)\n    if ((status = ASCII_calloc_float (&(result->u0u), nzout, input.rte.maxumu)) != 0)\n      return NULL;\n\n  if (input.rte.maxphi > 0 && input.rte.maxumu > 0)\n    if ((status = ASCII_calloc_float_3D (&(result->uu), input.rte.maxphi, nzout, input.rte.maxumu)) != 0)\n      return NULL;\n\n  if (input.rte.solver == SOLVER_DISORT && input.raman)\n    if ((status = ASCII_calloc_float_3D (&(result->uum), input.rte.nstr, nzout, input.rte.maxumu)) != 0)\n      return NULL;\n\n  /* PolRadtran-specific */\n  if (input.rte.solver == SOLVER_POLRADTRAN) {\n    result->polradtran_mu_values = (double*)calloc (input.rte.nstr / 2 + input.rte.numu, sizeof (double));\n\n    if ((status = ASCII_calloc_double (&(result->polradtran_up_flux), nzout, input.rte.polradtran[POLRADTRAN_NSTOKES])) != 0)\n      return NULL;\n\n    if ((status = ASCII_calloc_double (&(result->polradtran_down_flux), nzout, input.rte.polradtran[POLRADTRAN_NSTOKES])) != 0)\n      return NULL;\n\n    if ((status = ASCII_calloc_double_4D (&(result->polradtran_up_rad),\n                                          nzout,\n                                          input.rte.nphi,\n                                          input.rte.nstr / 2 + input.rte.numu,\n                                          input.rte.polradtran[POLRADTRAN_NSTOKES])) != 0)\n      return NULL;\n\n    if ((status = ASCII_calloc_double_4D (&(result->polradtran_down_rad),\n                                          nzout,\n                                          input.rte.nphi,\n                                          input.rte.nstr / 2 + input.rte.numu,\n                                          input.rte.polradtran[POLRADTRAN_NSTOKES])) != 0)\n      return NULL;\n\n    if ((status = ASCII_calloc_double_4D (&(result->polradtran_up_rad_q),\n                                          nzout,\n                                          input.rte.polradtran[POLRADTRAN_AZIORDER] + 1,\n                                          input.rte.nstr / 2 + input.rte.numu,\n                                          input.rte.polradtran[POLRADTRAN_NSTOKES])) != 0)\n      return NULL;\n\n    if ((status = ASCII_calloc_double_4D (&(result->polradtran_down_rad_q),\n                                          nzout,\n                                          input.rte.polradtran[POLRADTRAN_AZIORDER] + 1,\n                                          input.rte.nstr / 2 + input.rte.numu,\n                                          input.rte.polradtran[POLRADTRAN_NSTOKES])) != 0)\n      return NULL;\n  }\n\n  /* 3d fields */\n  if (passback3D) {\n\n    status += ASCII_calloc_float_3D (&(result->rfldir3d), nzout, Nxsample, Nysample);\n    status += ASCII_calloc_float_3D (&(result->rfldn3d), nzout, Nxsample, Nysample);\n    status += ASCII_calloc_float_3D (&(result->flup3d), nzout, Nxsample, Nysample);\n    status += ASCII_calloc_float_3D (&(result->uavgso3d), nzout, Nxsample, Nysample);\n    status += ASCII_calloc_float_3D (&(result->uavgdn3d), nzout, Nxsample, Nysample);\n    status += ASCII_calloc_float_3D (&(result->uavgup3d), nzout, Nxsample, Nysample);\n    status += ASCII_calloc_float_4D (&(result->radiance3d), nzout, Nxsample, Nysample, input.rte.mc.nstokes);\n    status += ASCII_calloc_float_6D (&(result->radiance3d_is), nzout, Ncsample, Nxsample, Nysample, input.rte.mc.nstokes, Nlambda);\n\n    if (input.rte.mc.spectral_is || input.rte.mc.concentration_is)\n      status += ASCII_calloc_float_5D (&(result->fl3d_is), nzout, Ncsample, Nxsample, Nysample, Nlambda);\n\n    if (input.rte.mc.jacobian[DIM_1D]) {\n      /* fprintf(stderr, \"calloc jacobian nzout %d  Nxsample %d Nysample %d input.n_caoth %d abs/sca %d Nzcld %d \\n\", nzout, Nxsample, Nysample, input.n_caoth, 2, Nlyr);  */\n      status += ASCII_calloc_float_6D (&(result->jacobian), nzout, 1, 1, input.n_caoth + 2, 2, Nlyr);\n    }\n\n    if (input.rte.mc.backward.absorption)\n      status += ASCII_calloc_float_3D (&(result->absback3d), nzout, Nxsample, Nysample);\n\n    if (input.rte.mc.absorption != MCFORWARD_ABS_NONE || input.ipa3d) /*ulrike: added || input.ipa3d*/\n      if ((result->abs3d = calloc_abs3d (Nxcld, Nycld, Nzcld, threed)) == NULL)\n        return NULL;\n\n    /* variances */\n    if (input.rte.mc.std) {\n\n      status += ASCII_calloc_float_3D (&(result->rfldir3d_var), nzout, Nxsample, Nysample);\n      status += ASCII_calloc_float_3D (&(result->rfldn3d_var), nzout, Nxsample, Nysample);\n      status += ASCII_calloc_float_3D (&(result->flup3d_var), nzout, Nxsample, Nysample);\n      status += ASCII_calloc_float_3D (&(result->uavgso3d_var), nzout, Nxsample, Nysample);\n      status += ASCII_calloc_float_3D (&(result->uavgdn3d_var), nzout, Nxsample, Nysample);\n      status += ASCII_calloc_float_3D (&(result->uavgup3d_var), nzout, Nxsample, Nysample);\n      status += ASCII_calloc_float_4D (&(result->radiance3d_var), nzout, Nxsample, Nysample, input.rte.mc.nstokes);\n\n      if (input.rte.mc.backward.absorption)\n        status += ASCII_calloc_float_3D (&(result->absback3d_var), nzout, Nxsample, Nysample);\n\n      if (input.rte.mc.absorption != MCFORWARD_ABS_NONE)\n        if ((result->abs3d_var = calloc_abs3d (Nxcld, Nycld, Nzcld, threed)) == NULL)\n          return NULL;\n    }\n  }\n\n  result->triangle_results = NULL;\n  status += init_triangular_surface_result_struct (N_triangles, &(result->triangle_results));\n\n  if (status != 0) {\n    fprintf (stderr, \"Error allocating memory for 3D fields\\n\");\n    return NULL;\n  }\n\n  return result;\n}\n\n/* reset rte_output structure */\nstatic int reset_rte_output (rte_output** rte,\n                             input_struct input,\n                             int          nzout,\n                             int          Nxcld,\n                             int          Nycld,\n                             int          Nzcld,\n                             int          Nxsample,\n                             int          Nysample,\n                             int          Ncsample,\n                             int          Nlambda,\n                             int          Nlyr,\n                             int*         threed,\n                             int          passback3D,\n                             const size_t N_triangles) {\n  const int ierr =\n    free_rte_output (*rte, input, nzout, Nxcld, Nycld, Nzcld, Nxsample, Nysample, Ncsample, Nlyr, Nlambda, threed, passback3D);\n  CHKERR (ierr);\n  *rte = calloc_rte_output (input,\n                            nzout,\n                            Nxcld,\n                            Nycld,\n                            Nzcld,\n                            Nxsample,\n                            Nysample,\n                            Ncsample,\n                            Nlambda,\n                            Nlyr,\n                            threed,\n                            passback3D,\n                            N_triangles);\n\n  return 0; /* if o.k. */\n}\n\nstatic int add_rte_output (rte_output*        rte,\n                           const rte_output*  add,\n                           const double       factor,\n                           const double*      factor_spectral,\n                           const input_struct input,\n                           const int          nzout,\n                           const int          Nxcld,\n                           const int          Nycld,\n                           const int          Nzcld,\n                           const int          Nc,\n                           const int          Nlyr,\n                           const int          Nlambda,\n                           const int*         threed,\n                           const int          passback3D,\n                           const int          islower,\n                           const int          isupper,\n                           const int          jslower,\n                           const int          jsupper,\n                           const int          isstep,\n                           const int          jsstep) {\n  const double factor2 = factor * factor;\n\n  for (int lu = 0; lu < nzout; lu++) {\n    rte->rfldir[lu] += factor * add->rfldir[lu];\n    rte->rfldn[lu] += factor * add->rfldn[lu];\n    rte->flup[lu] += factor * add->flup[lu];\n    rte->uavg[lu] += factor * add->uavg[lu];\n    rte->uavgdn[lu] += factor * add->uavgdn[lu];\n    rte->uavgso[lu] += factor * add->uavgso[lu];\n    rte->uavgup[lu] += factor * add->uavgup[lu];\n    rte->dfdt[lu] += factor * add->dfdt[lu];\n    rte->heat[lu] += factor * add->heat[lu];\n    rte->emis[lu] += factor * add->emis[lu];\n    rte->w_zout[lu] += factor * add->w_zout[lu];\n    rte->sslidar_nphot[lu] += factor * add->sslidar_nphot[lu];\n    rte->sslidar_nphot_q[lu] += factor * add->sslidar_nphot_q[lu];\n    rte->sslidar_ratio[lu] += factor * add->sslidar_ratio[lu];\n\n    for (int iu = 0; iu < input.rte.numu; iu++) {\n      rte->u0u[lu][iu] += factor * add->u0u[lu][iu];\n\n      for (int j = 0; j < input.rte.nphi; j++)\n        rte->uu[j][lu][iu] += factor * add->uu[j][lu][iu];\n    }\n  }\n\n  for (int iu = 0; iu < input.rte.numu; iu++) {\n    rte->albmed[iu] += factor * add->albmed[iu];\n    rte->trnmed[iu] += factor * add->trnmed[iu];\n  }\n\n  /* PolRadtran-specific */\n  if (input.rte.solver == SOLVER_POLRADTRAN) {\n    for (int lu = 0; lu < nzout; lu++) {\n      for (int is = 0; is < input.rte.polradtran[POLRADTRAN_NSTOKES]; is++) {\n\n        rte->polradtran_up_flux[lu][is] += factor * add->polradtran_up_flux[lu][is];\n        rte->polradtran_down_flux[lu][is] += factor * add->polradtran_down_flux[lu][is];\n\n        for (int j = 0; j < input.rte.nphi; j++) {\n          for (int iu = 0; iu < input.rte.nstr / 2 + input.rte.numu; iu++) {\n            rte->polradtran_up_rad[lu][j][iu][is] += factor * add->polradtran_up_rad[lu][j][iu][is];\n            rte->polradtran_down_rad[lu][j][iu][is] += factor * add->polradtran_down_rad[lu][j][iu][is];\n          }\n        }\n      }\n    }\n  }\n\n  if (passback3D) {\n    for (int ks = 0; ks < nzout; ks++) {\n      for (int is = islower; is <= isupper; is += isstep) {\n        for (int js = jslower; js <= jsupper; js += jsstep) {\n          rte->rfldir3d[ks][is][js] += factor * add->rfldir3d[ks][is][js];\n          rte->rfldn3d[ks][is][js] += factor * add->rfldn3d[ks][is][js];\n          rte->flup3d[ks][is][js] += factor * add->flup3d[ks][is][js];\n          rte->uavgso3d[ks][is][js] += factor * add->uavgso3d[ks][is][js];\n          rte->uavgdn3d[ks][is][js] += factor * add->uavgdn3d[ks][is][js];\n          rte->uavgup3d[ks][is][js] += factor * add->uavgup3d[ks][is][js];\n          if (input.rte.mc.concentration_is)\n            for (int ic = 0; ic < Nc; ic++)\n              rte->fl3d_is[ks][ic][is][js][0] += factor * add->fl3d_is[ks][ic][is][js][0];\n\n          else if (input.rte.mc.spectral_is)\n            for (int iv_alis = 0; iv_alis < Nlambda; iv_alis++) {\n              rte->fl3d_is[ks][0][is][js][iv_alis] += factor_spectral[iv_alis] * add->fl3d_is[ks][0][is][js][iv_alis];\n            }\n\n          for (int ip = 0; ip < input.rte.mc.nstokes; ip++) {\n            rte->radiance3d[ks][is][js][ip] += factor * add->radiance3d[ks][is][js][ip];\n\n            /* FIXCE spectral and concentration importance sampling together not */\n            /* yet working correctly */\n            if (input.rte.mc.concentration_is)\n              for (int ic = 0; ic < Nc; ic++) {\n                rte->radiance3d_is[ks][ic][is][js][ip][0] += factor * add->radiance3d_is[ks][ic][is][js][ip][0];\n              }\n\n            if (input.rte.mc.spectral_is) {\n              for (int ic = 0; ic < Nc; ic++) {\n                for (int iv_alis = 0; iv_alis < Nlambda; iv_alis++) {\n                  rte->radiance3d_is[ks][ic][is][js][ip][iv_alis] +=\n                    factor_spectral[iv_alis] * add->radiance3d_is[ks][ic][is][js][ip][iv_alis];\n                }\n              }\n            }\n          }\n\n          if (input.rte.mc.backward.absorption)\n            rte->absback3d[ks][is][js] += factor * add->absback3d[ks][is][js];\n\n          /* variances */\n          if (input.rte.mc.std) {\n\n            rte->rfldir3d_var[ks][is][js] += factor2 * add->rfldir3d_var[ks][is][js];\n            rte->rfldn3d_var[ks][is][js] += factor2 * add->rfldn3d_var[ks][is][js];\n            rte->flup3d_var[ks][is][js] += factor2 * add->flup3d_var[ks][is][js];\n            rte->uavgso3d_var[ks][is][js] += factor2 * add->uavgso3d_var[ks][is][js];\n            rte->uavgdn3d_var[ks][is][js] += factor2 * add->uavgdn3d_var[ks][is][js];\n            rte->uavgup3d_var[ks][is][js] += factor2 * add->uavgup3d_var[ks][is][js];\n\n            for (int ip = 0; ip < input.rte.mc.nstokes; ip++)\n              rte->radiance3d_var[ks][is][js][ip] += factor2 * add->radiance3d_var[ks][is][js][ip];\n\n            if (input.rte.mc.backward.absorption)\n              rte->absback3d_var[ks][is][js] += factor2 * add->absback3d_var[ks][is][js];\n          }\n        }\n      }\n    }\n\n    if (input.rte.mc.absorption != MCFORWARD_ABS_NONE)\n      for (int ks = 0; ks < Nzcld; ks++)\n        if (threed[ks]) /* only for 3D layers, BM07122005 */\n          for (int is = 0; is < Nxcld; is++)\n            for (int js = 0; js < Nycld; js++) { /* **CK added bracket */\n              rte->abs3d[ks][is][js] += factor * add->abs3d[ks][is][js];\n              if (input.rte.mc.std) /* **CK added for forward mc_std */\n                rte->abs3d_var[ks][is][js] += factor2 * add->abs3d_var[ks][is][js];\n            }\n  }\n\n  if (rte->triangle_results) {\n    const int ierr = add_triangular_surface_result (factor, add->triangle_results, rte->triangle_results);\n    CHKERR (ierr);\n  }\n\n  return 0; /* if o.k. */\n}\n\n/* free temporary memory for the RTE solvers */\nstatic int free_rte_output (rte_output*  result,\n                            input_struct input,\n                            int          nzout,\n                            int          Nxcld,\n                            int          Nycld,\n                            int          Nzcld,\n                            int          Nxsample,\n                            int          Nysample,\n                            int          Ncsample,\n                            int          Nlyr,\n                            int          Nlambda,\n                            int*         threed,\n                            int          passback3D) {\n  CHKPOINTEROUT (result, \"rte_output cannot be freed, it is not allocated!\");\n\n  free (result->albmed);\n  result->albmed = NULL;\n  free (result->trnmed);\n  result->trnmed = NULL;\n  free (result->dfdt);\n  result->dfdt = NULL;\n  free (result->flup);\n  result->flup = NULL;\n  free (result->rfldir);\n  result->rfldir = NULL;\n  free (result->rfldn);\n  result->rfldn = NULL;\n  free (result->uavg);\n  result->uavg = NULL;\n  free (result->uavgdn);\n  result->uavgdn = NULL;\n  free (result->uavgso);\n  result->uavgso = NULL;\n  free (result->uavgup);\n  result->uavgup = NULL;\n  free (result->heat);\n  result->heat = NULL;\n  free (result->emis);\n  result->emis = NULL;\n  free (result->w_zout);\n  result->w_zout = NULL;\n  free (result->sslidar_nphot);\n  result->sslidar_nphot = NULL;\n  free (result->sslidar_nphot_q);\n  result->sslidar_nphot_q = NULL;\n  free (result->sslidar_ratio);\n  result->sslidar_ratio = NULL;\n\n  if (result->u0u != NULL) {\n    ASCII_free_float (result->u0u, nzout);\n    result->u0u = NULL;\n  }\n\n  if (result->uu != NULL) {\n    ASCII_free_float_3D (result->uu, input.rte.nphi, nzout);\n    result->uu = NULL;\n  }\n\n  if (result->uum != NULL) {\n    ASCII_free_float_3D (result->uum, input.rte.nstr, nzout);\n    result->uum = NULL;\n  }\n\n  if (input.rte.solver == SOLVER_POLRADTRAN) {\n    free (result->polradtran_mu_values);\n    result->polradtran_mu_values = NULL;\n\n    if (result->polradtran_up_flux != NULL) {\n      ASCII_free_double (result->polradtran_up_flux, nzout);\n      result->polradtran_up_flux = NULL;\n    }\n\n    if (result->polradtran_down_flux != NULL) {\n      ASCII_free_double (result->polradtran_down_flux, nzout);\n      result->polradtran_down_flux = NULL;\n    }\n\n    if (result->polradtran_up_rad != NULL) {\n      ASCII_free_double_4D (result->polradtran_up_rad, nzout, input.rte.nphi, input.rte.nstr / 2 + input.rte.numu);\n      result->polradtran_up_rad = NULL;\n    }\n\n    if (result->polradtran_down_rad != NULL) {\n      ASCII_free_double_4D (result->polradtran_down_rad, nzout, input.rte.nphi, input.rte.nstr / 2 + input.rte.numu);\n      result->polradtran_down_rad = NULL;\n    }\n\n    if (result->polradtran_up_rad_q != NULL) {\n      ASCII_free_double_4D (result->polradtran_up_rad_q,\n                            nzout,\n                            input.rte.polradtran[POLRADTRAN_AZIORDER] + 1,\n                            input.rte.nstr / 2 + input.rte.numu);\n      result->polradtran_up_rad_q = NULL;\n    }\n\n    if (result->polradtran_down_rad_q != NULL) {\n      ASCII_free_double_4D (result->polradtran_down_rad_q,\n                            nzout,\n                            input.rte.polradtran[POLRADTRAN_AZIORDER] + 1,\n                            input.rte.nstr / 2 + input.rte.numu);\n      result->polradtran_down_rad_q = NULL;\n    }\n  }\n\n  /* free 3d fields */\n  if (passback3D) {\n\n    if (result->rfldir3d != NULL) {\n      ASCII_free_float_3D (result->rfldir3d, nzout, Nxsample);\n      result->rfldir3d = NULL;\n    }\n\n    if (result->rfldn3d != NULL) {\n      ASCII_free_float_3D (result->rfldn3d, nzout, Nxsample);\n      result->rfldn3d = NULL;\n    }\n\n    if (result->flup3d != NULL) {\n      ASCII_free_float_3D (result->flup3d, nzout, Nxsample);\n      result->flup3d = NULL;\n    }\n\n    if (result->uavgso3d != NULL) {\n      ASCII_free_float_3D (result->uavgso3d, nzout, Nxsample);\n      result->uavgso3d = NULL;\n    }\n\n    if (result->uavgdn3d != NULL) {\n      ASCII_free_float_3D (result->uavgdn3d, nzout, Nxsample);\n      result->uavgdn3d = NULL;\n    }\n\n    if (result->uavgup3d != NULL) {\n      ASCII_free_float_3D (result->uavgup3d, nzout, Nxsample);\n      result->uavgup3d = NULL;\n    }\n\n    if (result->radiance3d != NULL) {\n      ASCII_free_float_4D (result->radiance3d, nzout, Nxsample, Nysample);\n      result->radiance3d = NULL;\n    }\n\n    if (input.rte.mc.spectral_is || input.rte.mc.concentration_is)\n      if (result->fl3d_is != NULL) {\n        ASCII_free_float_5D (result->fl3d_is, nzout, Ncsample, Nxsample, Nysample);\n        result->fl3d_is = NULL;\n      }\n\n    if (result->radiance3d_is != NULL) {\n      ASCII_free_float_6D (result->radiance3d_is, nzout, Ncsample, Nxsample, Nysample, input.rte.mc.nstokes);\n      result->radiance3d_is = NULL;\n    }\n\n    if (input.rte.mc.jacobian[DIM_1D])\n      if (result->jacobian != NULL) {\n        ASCII_free_float_6D (result->jacobian, nzout, Nxsample, Nysample, input.n_caoth + 2, 2);\n        result->jacobian = NULL;\n      }\n\n    if (input.rte.mc.backward.absorption)\n      if (result->absback3d != NULL) {\n        ASCII_free_float_3D (result->absback3d, nzout, Nxsample);\n        result->absback3d = NULL;\n      }\n\n    if (input.rte.mc.absorption != MCFORWARD_ABS_NONE || input.ipa3d) /*ulrike: added || input.ipa3d*/\n      if (result->abs3d != NULL) {\n        free_abs3d (result->abs3d, Nxcld, Nycld, Nzcld, threed);\n        result->abs3d = NULL;\n      }\n\n    /* variances */\n    if (input.rte.mc.std) {\n\n      if (result->rfldir3d_var != NULL) {\n        ASCII_free_float_3D (result->rfldir3d_var, nzout, Nxsample);\n        result->rfldir3d_var = NULL;\n      }\n      if (result->rfldn3d != NULL) {\n        ASCII_free_float_3D (result->rfldn3d_var, nzout, Nxsample);\n        result->rfldn3d = NULL;\n      }\n      if (result->flup3d != NULL) {\n        ASCII_free_float_3D (result->flup3d_var, nzout, Nxsample);\n        result->flup3d = NULL;\n      }\n      if (result->uavgso3d != NULL) {\n        ASCII_free_float_3D (result->uavgso3d_var, nzout, Nxsample);\n        result->uavgso3d = NULL;\n      }\n      if (result->uavgdn3d != NULL) {\n        ASCII_free_float_3D (result->uavgdn3d_var, nzout, Nxsample);\n        result->uavgdn3d = NULL;\n      }\n      if (result->uavgup3d != NULL) {\n        ASCII_free_float_3D (result->uavgup3d_var, nzout, Nxsample);\n        result->uavgup3d = NULL;\n      }\n      if (result->radiance3d != NULL) {\n        ASCII_free_float_4D (result->radiance3d_var, nzout, Nxsample, Nysample);\n        result->radiance3d = NULL;\n      }\n\n      if (input.rte.mc.backward.absorption)\n        if (result->absback3d != NULL) {\n          ASCII_free_float_3D (result->absback3d_var, nzout, Nxsample);\n          result->absback3d = NULL;\n        }\n\n      if (input.rte.mc.absorption != MCFORWARD_ABS_NONE || input.ipa3d) /*ulrike: added || input.ipa3d*/\n        if (result->abs3d != NULL) {\n          free_abs3d (result->abs3d_var, Nxcld, Nycld, Nzcld, threed);\n          result->abs3d = NULL;\n        }\n    }\n  }\n\n  const int ierr = free_triangular_surface_result_struct (result->triangle_results);\n  CHKERR (ierr);\n\n  free (result);\n  return 0;\n}\n\n/******************************************************/\n/* setup optical properties, do some initializations, */\n/* and call the RTE solver.                           */\n/******************************************************/\n\nstatic int setup_and_call_solver (input_struct           input,\n                                  output_struct*         output,\n                                  rte_input*             rte_in,\n                                  rte_output*            rte_out,\n                                  raman_qsrc_components* raman_qsrc_components,\n                                  int                    iv,\n                                  int                    ib,\n                                  int                    ir,\n                                  int*                   threed,\n                                  int                    mc_loaddata) {\n  int        status = 0, lu = 0, iv1 = 0, iv2 = 0, iv_alis = 0, il = 0, isp = 0;\n  static int first                   = 1;\n  static int verbose                 = 0;\n  int        rte_solver              = NOT_DEFINED_INTEGER;\n  int        skip_optical_properties = FALSE;\n\n  /* change rte solver to NULL solver for                                   */\n  /* solar simulations with sza > 90 degrees done by plane paralell solvers */\n\n  rte_solver = input.rte.solver;\n\n  switch (input.source) {\n  case SRC_THERMAL:\n    /* do not change solver */\n    break;\n  case SRC_SOLAR:\n  case SRC_BLITZ: /* BCA */\n  case SRC_LIDAR: /* BCA */\n    if (output->atm.sza_r[iv] >= 90.0) {\n      switch (input.rte.solver) {\n\n      /* plane parallel solvers */\n      case SOLVER_FDISORT1:\n      case SOLVER_FDISORT2:\n      case SOLVER_RODENTS:\n      case SOLVER_TWOSTREBE:\n      case SOLVER_TWOMAXRND:\n      case SOLVER_TWOMAXRND3C:\n      case SOLVER_DYNAMIC_TWOSTREAM:\n      case SOLVER_DYNAMIC_TENSTREAM:\n      case SOLVER_POLRADTRAN:\n      case SOLVER_SSS:\n      case SOLVER_SSSI:\n      case SOLVER_DISORT:  // aky 24022011, cdisort may produce results for sza>90 if intensity correction\n                           // are turned off. But results are a bit dubious if compared with mystic.\n                           /* change solver to SOLVER_NULL, as output is 0 anyway */\n        /* It is only 0 if pseudospherical is off aky 05022014 */\n        if (!input.rte.pseudospherical) {\n          rte_solver              = SOLVER_NULL;\n          skip_optical_properties = TRUE;\n          if (input.verbose)\n            fprintf (stderr, \" ... solar calculation with SZA>90 and pp solver, switch solver to NULL-solver \\n\");\n        }\n        break;\n\n      /* spherical solvers */\n      case SOLVER_SDISORT:\n      case SOLVER_SPSDISORT:\n      case SOLVER_FTWOSTR:\n      case SOLVER_TWOSTR:\n      case SOLVER_SOS:\n        /* do not change solver as these solvers should be   */\n        /* able to do solar calculations for sza > 90 degree */\n        break;\n\n      /* special solvers */\n      case SOLVER_MONTECARLO: /* user must know it */\n      case SOLVER_TZS:        /* only thermal anyway */\n      case SOLVER_SSLIDAR:\n        /* do nothing */\n        break;\n\n      case SOLVER_NULL:\n        break;\n      default:\n        fprintf (stderr, \"Error, unknown RTE solver %d\\n\", input.rte.solver);\n        break;\n      }\n    }\n    break;\n  default:\n    fprintf (stderr, \"Error, unknown source %d\\n\", input.source);\n    return -1;\n  }\n\n  if (input.raman) {\n    /* Optical properties are calculated just before calling qdisort in solve_rte.c */\n    skip_optical_properties = TRUE;\n    /* For raman_fast optical properties are calculated as usual */\n    if (input.raman_fast && ir == 0)\n      skip_optical_properties = FALSE;\n  }\n\n  verbose = input.verbose;\n\n  if (input.verbose && input.ck_scheme == CK_LOWTRAN)\n    verbose = 0; /* no verbose output for the following call of optical properties */\n\n  /* calculate optical properties from model input */\n  if (input.raman_fast) {\n    iv1 = ib;\n    iv2 = ib;\n  } else {\n    iv1 = iv;\n    iv2 = iv;\n  }\n\n  if (input.rte.mc.spectral_is) {\n    if (ib == 0) {\n      /* fprintf(stderr, \"alloc ALIS struct iv %d\\n\", iv); */\n      output->mc.alis.dt = calloc (output->mc.alis.nlambda_abs, sizeof (double**));\n      output->mc.alis.om = calloc (output->mc.alis.nlambda_abs, sizeof (double**));\n      for (iv_alis = 0; iv_alis < output->mc.alis.nlambda_abs; iv_alis++) {\n        output->mc.alis.dt[iv_alis] = calloc (input.n_caoth + 2, sizeof (double*));\n        output->mc.alis.om[iv_alis] = calloc (input.n_caoth + 2, sizeof (double*));\n      }\n      for (iv_alis = 0; iv_alis < output->mc.alis.nlambda_abs; iv_alis++) {\n        for (isp = 0; isp < input.n_caoth + 2; isp++) {\n          output->mc.alis.dt[iv_alis][isp] = calloc (output->atm.nlev_common - 1, sizeof (double));\n          output->mc.alis.om[iv_alis][isp] = calloc (output->atm.nlev_common - 1, sizeof (double));\n        }\n      }\n    }\n\n    for (iv_alis = 0; iv_alis < output->mc.alis.nlambda_abs; iv_alis++) {\n      status = optical_properties (input, output, 0.0, ir, iv_alis, iv_alis, ib, verbose, skip_optical_properties);\n    }\n\n    /* spatially constant spectral Lambertian albedo */\n    output->mc.alis.albedo = calloc (output->mc.alis.nlambda_abs, sizeof (double));\n    for (iv_alis = 0; iv_alis < output->mc.alis.nlambda_abs; iv_alis++)\n      output->mc.alis.albedo[iv_alis] = output->alb.albedo_r[iv_alis];\n\n    /* 2D spectral Lambertian albedo */\n    if (output->surfaces.n > 0 && output->surfaces.albedo_r != NULL) {\n      output->mc.alis.alb_type = calloc (output->surfaces.n, sizeof (double*));\n\n      for (il = 0; il < output->surfaces.n; il++) {\n        output->mc.alis.alb_type[il] = calloc (output->mc.alis.nlambda_abs, sizeof (double));\n\n        for (iv_alis = 0; iv_alis < output->mc.alis.nlambda_abs; iv_alis++)\n          output->mc.alis.alb_type[il][iv_alis] = output->surfaces.albedo_r[il][iv_alis];\n      }\n    }\n\n    if (output->mc.alis.dt[iv][0][output->atm.nlev_common - 2] * (1.0 - output->mc.alis.om[iv][0][output->atm.nlev_common - 2]) >\n        0.5) {\n      fprintf (stderr, \" ... Warning: Absorption is very high at the calculation wavelength for\\n\");\n      fprintf (stderr, \" ...          spectral importance sampling. In order to improve the result \\n\");\n      fprintf (stderr, \" ...          please select another calculation wavelength using the option\\n\");\n      fprintf (stderr, \" ...          *mc_spectral_is_wvl*. \\n\");\n      fprintf (stderr,\n               \" ...          (Absorption optical depth in lowest layer is %g) \\n\",\n               output->mc.alis.dt[iv][0][output->atm.nlev_common - 2] *\n                 (1.0 - output->mc.alis.om[iv][0][output->atm.nlev_common - 2]));\n    }\n  }\n\n  //TODO: else statement? call optical properties twice -> double allocating etc\n  status = optical_properties (input, output, 0.0, ir, iv1, iv2, ib, verbose, skip_optical_properties); /* in ancillary.c */\n  if (status != 0) {\n    fprintf (stderr,\n             \"Error %d returned by optical_properties (line %d, function %s in %s)\\n\",\n             status,\n             __LINE__,\n             __func__,\n             __FILE__);\n    return status;\n  }\n\n  /* 3DAbs may be here ??? */\n  /* else{ */\n  /*   status = optical_properties_atmosphere3D(input, output, iv, ib, verbose); */\n  /*   if (status!=0) { */\n  /*     fprintf (stderr, \"Error %d returned by optical_properties_atmosphere3D (line %d, function %s in %s)\\n\",  */\n  /* \t       status, __LINE__, __func__, __FILE__); */\n  /*     return status; */\n  /*   } */\n  /* } */\n\n  if (input.ck_scheme == CK_LOWTRAN) {\n\n    /* this is a little inefficient as we need first the scattering optical */\n    /* properties to calculate the absorption coefficients and then         */\n    /* recalculate the optical properties; the reason is that SBDART        */\n    /* requires the total scattering cross section as input, and this       */\n    /* quantity is only available after the call to optical_properties      */\n\n    /* ??? where to get the mixing ratio of N2 from ??? */\n    /* ??? setting this value to -1                 ??? */\n    status = sbdart_profile (output->atm.microphys.temper,\n                             output->atm.microphys.press,\n                             output->atm.zd,\n                             output->atm.microphys.dens[MOL_H2O],\n                             output->atm.microphys.dens[MOL_O3],\n                             -1.0,\n                             output->mixing_ratio[MX_O2],\n                             output->mixing_ratio[MX_CO2],\n                             output->mixing_ratio[MX_CH4],\n                             output->mixing_ratio[MX_N2O],\n                             output->mixing_ratio[MX_NO2],\n                             input.ck_abs[CK_ABS_O4],\n                             input.ck_abs[CK_ABS_N2],\n                             input.ck_abs[CK_ABS_CO],\n                             input.ck_abs[CK_ABS_SO2],\n                             input.ck_abs[CK_ABS_NH3],\n                             input.ck_abs[CK_ABS_NO],\n                             input.ck_abs[CK_ABS_HNO3],\n                             output->dtauc,\n                             output->ssalb,\n                             output->atm.nlev,\n                             output->atm.sza_r[iv],\n                             output->wl.lambda_r[iv],\n                             iv,\n                             output->crs_ck.profile[0],\n                             input.rte.mc.spectral_is);\n\n    if (status != 0) {\n      fprintf (stderr, \"Error %d returned by sbdart_profile (line %d, function %s in %s)\\n\", status, __LINE__, __func__, __FILE__);\n      return status;\n    }\n\n    /* allocate memory for absorption coefficient profile */\n    if (first) {\n      status = ASCII_calloc_float (&output->kabs.kabs, output->atm.nlev, output->wl.nlambda_r);\n      if (status != 0) {\n        fprintf (stderr, \"Error %d allocating memory for output->kabs.kabs\\n\", status);\n        return status;\n      }\n\n      first = 0;\n    }\n\n    /* set absorption coefficient */\n    for (lu = 0; lu < output->atm.nlyr; lu++)\n      output->kabs.kabs[lu][iv] = output->crs_ck.profile[0][iv].crs[0][0][lu][ib];\n\n    if (input.rte.mc.spectral_is) {\n      for (iv_alis = 0; iv_alis < output->mc.alis.nlambda_abs; iv_alis++) {\n        status = optical_properties (input, output, 0.0, ir, iv_alis, iv_alis, ib, verbose, skip_optical_properties);\n      }\n    }\n\n    /* calculate optical properties from model input */\n    status = optical_properties (input, output, 0.0, ir, iv, iv, ib, input.verbose, skip_optical_properties); /* in ancillaries.c */\n\n    if (status != 0) {\n      fprintf (stderr,\n               \"Error %d returned by optical_properties (line %d, function %s in %s)\\n\",\n               status,\n               __LINE__,\n               __func__,\n               __FILE__);\n      return status;\n    }\n  }\n\n  /* translate output altitudes (zout) to optical depths (utau) */\n\n  switch (input.rte.solver) {\n  case SOLVER_FDISORT1:\n  case SOLVER_SDISORT:\n  case SOLVER_FTWOSTR:\n  case SOLVER_SOS:\n  case SOLVER_POLRADTRAN:\n  case SOLVER_FDISORT2:\n  case SOLVER_SPSDISORT:\n  case SOLVER_TZS:\n  case SOLVER_SSS:\n  case SOLVER_SSSI:\n    /* \"very old\" version, recycled */\n    F77_FUNC (setout, SETOUT)\n    (output->dtauc, &(output->atm.nlyr), &(output->atm.nzout), rte_in->utau, output->atm.zd, output->atm.zout_sur);\n\n    break;\n  case SOLVER_TWOSTR:\n  case SOLVER_TWOSTREBE:\n  case SOLVER_TWOMAXRND:\n  case SOLVER_TWOMAXRND3C:\n  case SOLVER_DYNAMIC_TWOSTREAM:\n  case SOLVER_DYNAMIC_TENSTREAM:\n  case SOLVER_RODENTS:\n  case SOLVER_DISORT:\n    /* \"old\" version */\n    /*\n    status = set_out (output->atm.zd, output->dtauc, output->atm.nlyr, \n\t\t      input.atm.zout, output->atm.nzout, rte_in->utau);\n\n    if (status!=0) {\n      fprintf (stderr, \"Error %d returned by set_out()\\n\", status);\n      return status;\n    }\n    */\n\n    status = c_setout (output->dtauc, output->atm.nlyr, output->atm.nzout, rte_in->utau, output->atm.zd, output->atm.zout_sur);\n    if (status) {\n      fprintf (stderr, \"Error returned by c_setout\\n\");\n      return -1;\n    }\n    break;\n  case SOLVER_MONTECARLO:\n  case SOLVER_SSLIDAR:\n  case SOLVER_NULL:\n    break;\n  default:\n    fprintf (stderr,\n             \"Error, unknown rte_solver %d (line %d, function '%s' in '%s')\\n\",\n             input.rte.solver,\n             __LINE__,\n             __func__,\n             __FILE__);\n    return -1;\n  }\n\n  /* reverse profiles, if required */\n  if (input.rte.reverse) {\n    status = reverse_profiles (input, output);\n    if (status != 0) {\n      fprintf (stderr, \"Error %d reversing profiles\\n\", status);\n      return status;\n    }\n  }\n\n  /**** Switch to SOLVER_NULL to run optical_properties tests without solving RTE, Bettina Richter ****/\n  if (input.test_optical_properties) {\n    fprintf (stderr, \" ... switch rte_solver to null_solver\\n\");\n    input.rte.solver = SOLVER_NULL;\n    rte_solver       = SOLVER_NULL;\n  }\n\n  /* call RTE solver */\n  status =\n    call_solver (input, output, rte_solver, rte_in, raman_qsrc_components, iv, ib, ir, rte_out, threed, mc_loaddata, input.verbose);\n  if (status != 0) {\n    fprintf (stderr, \"Error %d calling solver\\n\", status);\n    return status;\n  }\n\n  return 0; /* if o.k. */\n}\n\nstatic int call_solver (input_struct           input,\n                        output_struct*         output,\n                        int                    rte_solver,\n                        rte_input*             rte_in,\n                        raman_qsrc_components* raman_qsrc_comp,\n                        int                    iv,\n                        int                    ib,\n                        int                    ir,\n                        rte_output*            rte_out,\n                        int*                   threed,\n                        int                    mc_loaddata,\n                        int                    verbose) {\n  int                    status = 0;\n  int                    lev = 0, ivi = 0, imu = 0, iv_alis = 0;\n  double                 start = 0, end = 0, last = 0;\n  int                    lu = 0, is = 0;\n  raman_qsrc_components* tmp_raman_qsrc_comp = NULL;\n  double *               tmp_in_int = NULL, *tmp_out_int = NULL, *tmp_wl = NULL;\n\n#if HAVE_SOS\n  int k = 0;\n#endif\n\n  double*** tmp_crs = NULL;\n\n  /* CE: commented since I have introduced the option earth_radius, default value is 6370.0 */\n  /* float radius= 6370.0; */ /* Earth's radius in km */\n\n  /* c_disort and c_twostr double declarations as they expect all input in double */\n  /* and f77 disort and twostr is all float. AK 23.09.2010                        */\n\n  disort_state  ds_in, twostr_ds;\n  disort_output ds_out, twostr_out;\n  double*       c_twostr_gg = NULL;\n  double*       c_zd        = NULL;\n  double        c_r_earth   = (double)input.r_earth;\n  int           lc = 0, j = 0, maz = 0, iq = 0;\n\n  float*  twostr_gg         = NULL;\n  float*  twostr_gg_clr     = NULL;\n  float*  twostr_gg_cldk    = NULL;\n  float*  twostr_gg_cldn    = NULL;\n  float*  twostr_cf         = NULL;\n  float*  twostr_ff         = NULL;\n  float*  sdisort_beta      = NULL;\n  float*  sdisort_sig       = NULL;\n  float** sdisort_denstab   = NULL;\n  float*  tosdisort_denstab = NULL;\n  float * disort_pmom = NULL, *disort2_pmom = NULL, *sss_pmom = NULL, *disort2_phaso = NULL;\n  int     disort2_ntheta_default   = 0;\n  int*    disort2_ntheta           = &disort2_ntheta_default;\n  double* disort2_mup              = NULL;\n  int     intensity_correction     = TRUE;\n  int     old_intensity_correction = FALSE;\n  int     rodents_delta_method     = 0;\n\n  float qwanted_wvl[1];\n  float qfbeam[1];\n  float qalbedo[1];\n  int   iv1 = 0, iv2 = 0;\n  int   skip_optical_properties = FALSE;\n  int   planck_tempoff          = 0;\n\n  char function_name[] = \"call_solver\";\n  char file_name[]     = \"solve_rte.c\";\n\n  double** phase_back = NULL;\n\n#if HAVE_SOS\n  float** pmom_sos = NULL;\n#endif\n\n#if HAVE_POLRADTRAN\n  int iu = 0;\n\n  double* polradtran_down_flux = NULL;\n  double* polradtran_up_flux   = NULL;\n  double* polradtran_down_rad  = NULL;\n  double* polradtran_up_rad    = NULL;\n#endif\n\n  /* temporary Fortran arrays */\n  float *disort_u0u = NULL, *disort_uu = NULL;\n  /* float *tzs_u0u = NULL, *tzs_uu = NULL; */\n  float *sss_u0u = NULL, *sss_uu = NULL;\n\n#if HAVE_MYSTIC\n  int il              = 0;\n  int source          = 0;\n  int thermal_photons = 0;\n\n  double* weight_spectral = NULL;\n\n  /* temporary MC output (for thermal MC calculations, two calls   */\n  /* to mystic() are required, one for the surface and one for the */\n  /* atmospheric contribution                                      */\n  rte_output* tmp_out = NULL;\n\n  /* rpv arrays */\n  float* alb_type  = NULL;\n  float* rpv_rho0  = NULL;\n  float* rpv_k     = NULL;\n  float* rpv_theta = NULL;\n  float* rpv_scale = NULL;\n  float* rpv_sigma = NULL;\n  float* rpv_t1    = NULL;\n  float* rpv_t2    = NULL;\n\n  float* rossli_iso = NULL;\n  float* rossli_vol = NULL;\n  float* rossli_geo = NULL;\n\n  float* hapke_h  = NULL;\n  float* hapke_b0 = NULL;\n  float* hapke_w  = NULL;\n\n  int write_files = 0;\n\n  /* write MYSTIC monochromatic output only if monochromatic, non-ck uvspec calculation */\n  write_files = (output->wl.nlambda_r * output->atm.nq_r[output->wl.nlambda_rte_lower] > 1 ? 0 : 1);\n\n  /* RPB very dirty trick, please dont kill me for this!!! */\n  if (output->mc.sample.LidarLocEst)\n    write_files = 1;\n  /* write files for spectral/concentration importance sampling, but only if not spectrally post-processed */\n  if ((input.rte.mc.spectral_is || input.rte.mc.concentration_is) && input.processing == PROCESS_NONE)\n    write_files = 1;\n#endif\n\n  if (input.rte.mc.backward.writeback == 1)\n    write_files = 1;\n\n  if (verbose)\n    start = clock();\n\n  switch (rte_solver) { /* this is the ONLY use of rte_solver, everywhere else still input.rte.solver is used */\n\n  case SOLVER_MONTECARLO:\n#if HAVE_MYSTIC\n\n    if (ib == 0)\n      if (input.verbose)\n        fprintf (stderr, \" ... start Monte Carlo simulation for lambda = %10.2f nm \\n\", output->wl.lambda_r[iv]);\n\n    /* create rpv arrays */\n    /* BCA: this is not nice, especially case surf.n=0 and il=0, affects mystic.c and albedo.c */\n    if (output->surfaces.n > 0 && output->surfaces.rpv != NULL) {\n\n      rpv_rho0  = calloc (output->surfaces.n, sizeof (float));\n      rpv_k     = calloc (output->surfaces.n, sizeof (float));\n      rpv_theta = calloc (output->surfaces.n, sizeof (float));\n      rpv_scale = calloc (output->surfaces.n, sizeof (float));\n      rpv_sigma = calloc (output->surfaces.n, sizeof (float));\n      rpv_t1    = calloc (output->surfaces.n, sizeof (float));\n      rpv_t2    = calloc (output->surfaces.n, sizeof (float));\n\n      for (il = 0; il < output->surfaces.n; il++) {\n        rpv_rho0[il]  = output->surfaces.rpv[il].rho0_r[iv];\n        rpv_k[il]     = output->surfaces.rpv[il].k_r[iv];\n        rpv_theta[il] = output->surfaces.rpv[il].theta_r[iv];\n        rpv_scale[il] = output->surfaces.rpv[il].scale_r[iv];\n        rpv_sigma[il] = output->surfaces.rpv[il].sigma_r[iv];\n        rpv_t1[il]    = output->surfaces.rpv[il].t1_r[iv];\n        rpv_t2[il]    = output->surfaces.rpv[il].t2_r[iv];\n      }\n    } else {\n      rpv_rho0  = calloc (1, sizeof (float));\n      rpv_k     = calloc (1, sizeof (float));\n      rpv_theta = calloc (1, sizeof (float));\n      rpv_scale = calloc (1, sizeof (float));\n      rpv_sigma = calloc (1, sizeof (float));\n      rpv_t1    = calloc (1, sizeof (float));\n      rpv_t2    = calloc (1, sizeof (float));\n\n      rpv_rho0[0]  = output->rpv.rho0_r[iv];\n      rpv_k[0]     = output->rpv.k_r[iv];\n      rpv_theta[0] = output->rpv.theta_r[iv];\n      rpv_scale[0] = output->rpv.scale_r[iv];\n      rpv_sigma[0] = output->rpv.sigma_r[iv];\n      rpv_t1[0]    = output->rpv.t1_r[iv];\n      rpv_t2[0]    = output->rpv.t2_r[iv];\n    }\n\n    if (output->surfaces.n > 0 && output->surfaces.albedo_r != NULL) {\n      alb_type = calloc (output->surfaces.n, sizeof (float));\n\n      for (il = 0; il < output->surfaces.n; il++)\n        alb_type[il] = output->surfaces.albedo_r[il][iv];\n    } else {\n      alb_type    = calloc (1, sizeof (float));\n      alb_type[0] = output->alb.albedo_r[iv];\n    }\n\n    /* for rossli we don't have a surface type yet, but that */\n    /* would be straightforward to implement                  */\n    if (output->surfaces.n > 0 && output->surfaces.rossli != NULL) {\n\n      rossli_iso = calloc (output->surfaces.n, sizeof (float));\n      rossli_vol = calloc (output->surfaces.n, sizeof (float));\n      rossli_geo = calloc (output->surfaces.n, sizeof (float));\n\n      for (il = 0; il < output->surfaces.n; il++) {\n        rossli_iso[il] = output->surfaces.rossli[il].iso_r[iv];\n        rossli_vol[il] = output->surfaces.rossli[il].vol_r[iv];\n        rossli_geo[il] = output->surfaces.rossli[il].geo_r[iv];\n      }\n    } else {\n      rossli_iso = calloc (1, sizeof (float));\n      rossli_vol = calloc (1, sizeof (float));\n      rossli_geo = calloc (1, sizeof (float));\n\n      rossli_iso[0] = output->rossli.iso_r[iv];\n      rossli_vol[0] = output->rossli.vol_r[iv];\n      rossli_geo[0] = output->rossli.geo_r[iv];\n    }\n\n    /* for hapke we don't have a surface type yet, but that */\n    /* would be straightforward to implement                  */\n    hapke_w  = calloc (1, sizeof (float));\n    hapke_b0 = calloc (1, sizeof (float));\n    hapke_h  = calloc (1, sizeof (float));\n\n    /* also, wavelength dependence is missing, but that */\n    /* would also be straightforward to implement       */\n    hapke_w[0]  = output->hapke.w_r[iv];\n    hapke_b0[0] = output->hapke.b0_r[iv];\n    hapke_h[0]  = output->hapke.h_r[iv];\n\n    if (input.rte.mc.spectral_is)\n      weight_spectral = calloc (output->mc.alis.nlambda_abs, sizeof (double));\n\n    switch (input.source) {\n    case SRC_SOLAR: /* solar source */\n    case SRC_BLITZ: /* blitz source */\n    case SRC_LIDAR: /* lidar source */\n\n      switch (input.source) {\n      case SRC_SOLAR: /* solar source */\n        source = MCSRC_SOLAR;\n        break;\n      case SRC_BLITZ: /* blitz source */\n        source = MCSRC_BLITZ;\n        break;\n      case SRC_LIDAR: /* lidar source */\n        source = MCSRC_LIDAR;\n        break;\n      default:\n        fprintf (stderr, \"Error, source %d should not turn up here!\\n\", input.source);\n        return -1;\n      }\n\n      status = mystic (&output->atm.nlyr,\n                       threed,\n                       input.n_caoth + 2,\n                       output->mc.dt,\n                       output->mc.om,\n                       output->mc.g1,\n                       output->mc.g2,\n                       output->mc.ff,\n                       output->mc.ds,\n                       &(output->mc.alis),\n                       output->mc.refind,\n                       input.r_earth * 1000.0,\n                       input.rte.mc.refractive_index_pv,\n                       &(output->rayleigh_depol[iv]),\n                       output->caoth3d,\n                       output->mc.re,\n                       output->mc.temper,\n                       input.atmosphere3d,\n                       output->mc.z,\n                       output->mc.momaer,\n                       output->mc.nmomaer,\n                       output->mc.nthetaaer,\n                       output->mc.thetaaer,\n                       output->mc.muaer,\n                       output->mc.phaseaer,\n                       output->mc.nphamataer,\n                       &output->alb.albedo_r[iv],\n                       alb_type,\n                       output->atm.sza_r[iv],\n                       output->atm.phi0_r[iv],\n                       input.atm.sza_spher,\n                       input.atm.phi0_spher,\n                       output->mc_photons,\n                       &source,\n                       &(output->wl.wvnmlo_r[iv]),\n                       &(output->wl.wvnmhi_r[iv]),\n                       &(output->wl.lambda_r[iv]),\n                       output->atm.zout_sur,\n                       &(output->atm.nzout),\n                       rpv_rho0,\n                       rpv_k,\n                       rpv_theta,\n                       rpv_scale,\n                       rpv_sigma,\n                       rpv_t1,\n                       rpv_t2,\n                       hapke_h,\n                       hapke_b0,\n                       hapke_w,\n                       rossli_iso,\n                       rossli_vol,\n                       rossli_geo,\n                       input.rossli.hotspot,\n                       &(input.cm.param[BRDF_CAM_U10]),\n                       &(input.cm.param[BRDF_CAM_PCL]),\n                       &(input.cm.param[BRDF_CAM_SAL]),\n                       &(input.cm.param[BRDF_CAM_UPHI]),\n                       &(input.cm.solar_wind),\n                       &(input.bpdf.u10),\n                       &(input.rte.mc.tenstream),\n                       input.rte.mc.tenstream_options,\n                       &(input.rte.mc.nca), /* Carolin Klinger 2019 */\n                       input.rte.mc.nca_options,\n                       &(input.rte.mc.ipa),\n                       &(input.rte.mc.absorption),\n                       &(input.rte.mc.backward.thermal_heating_method),\n                       &mc_loaddata,\n                       &(output->mc.sample),\n                       &(output->mc.elev),\n                       &(output->mc.triangular_surface),\n                       &(output->mc.surftemp),\n                       input.rte.mc.filename[FN_MC_BASENAME],\n                       input.rte.mc.filename[FN_MC_UMU],\n                       input.rte.mc.filename[FN_MC_SUNSHAPE_FILE],\n                       input.rte.mc.filename[FN_MC_ALBEDO],\n                       input.rte.mc.filename[FN_MC_AMBRALS],\n                       input.rte.mc.filename[FN_MC_ROSSLI],\n                       input.rte.mc.filename[FN_MC_ALBEDO_TYPE],\n                       input.rte.mc.filename[FN_MC_RPV2D_TYPE],\n                       input.rte.mc.filename[FN_MC_AMBRALS_TYPE],\n                       output->surfaces.label,\n                       &(output->surfaces.n),\n                       &(input.rte.mc.delta_scaling_mucut), /*TZ ds*/\n                       &(input.rte.mc.truncate),\n                       &(input.rte.mc.reflectalways),\n                       input.quiet,\n                       rte_out->rfldir,\n                       rte_out->rfldn,\n                       rte_out->flup,\n                       rte_out->uavgso,\n                       rte_out->uavgdn,\n                       rte_out->uavgup,\n                       rte_out->rfldir3d,\n                       rte_out->rfldn3d,\n                       rte_out->flup3d,\n                       rte_out->fl3d_is,\n                       rte_out->uavgso3d,\n                       rte_out->uavgdn3d,\n                       rte_out->uavgup3d,\n                       rte_out->radiance3d,\n                       rte_out->absback3d,\n                       rte_out->abs3d,\n                       rte_out->radiance3d_is,\n                       rte_out->jacobian,\n                       rte_out->rfldir3d_var,\n                       rte_out->rfldn3d_var,\n                       rte_out->flup3d_var,\n                       rte_out->uavgso3d_var,\n                       rte_out->uavgdn3d_var,\n                       rte_out->uavgup3d_var,\n                       rte_out->radiance3d_var,\n                       rte_out->absback3d_var,\n                       rte_out->abs3d_var,\n                       rte_out->triangle_results,\n                       output->atm.Nxcld,\n                       output->atm.Nycld,\n                       output->atm.Nzcld,\n                       output->atm.dxcld,\n                       output->atm.dycld,\n                       input.filename[FN_PATH],\n                       input.filename[FN_RANDOMSTATUS],\n                       input.rte.mc.readrandomstatus,\n                       input.write_output_as_netcdf,\n                       write_files,\n                       input.rte.mc.visualize);\n\n      CHKERR (status);\n\n      break;\n\n    case SRC_THERMAL: /* thermal source */\n      /* normal atmospheric + surface emission */\n      switch (input.rte.mc.absorption) {\n      case MCFORWARD_ABS_NONE:\n      case MCFORWARD_ABS_ABSORPTION:\n      case MCFORWARD_ABS_HEATING:\n        if (!input.rte.mc.backward.yes) { /*TZ bt*/\n\n          thermal_photons = 0.5 * output->mc_photons;\n\n          /* thermal emission of the atmosphere */\n          if (ib == 0 && !input.quiet)\n            fprintf (stderr, \" ... thermal emission of the atmosphere\\n\");\n\n        } else {                                      /*TZ bt*/\n          thermal_photons = 1.0 * output->mc_photons; /*TZ bt*/\n          /* CE for spectral importance sampling, we run a MC */\n          /* calculation at only one wavelengths, even if input */\n          /* wavelength is not exactly included in */\n          /* molecular_tau_file   */\n          if (input.rte.mc.spectral_is)\n            thermal_photons = input.rte.mc.photons;\n          /* thermal emission into the atmosphere TZ bt*/\n          if (ib == 0 && !input.quiet)\n            fprintf (stderr, \" ... thermal backward emission into atmosphere\\n\"); /*TZ*/\n        }                                                                         /*TZ bt*/\n\n        if (!input.rte.mc.backward.yes) /*TZ bt*/\n          source = MCSRC_THERMAL_ATMOSPHERE;\n        else                               /*TZ bt*/\n          source = MCSRC_THERMAL_BACKWARD; /*TZ bt*/\n\n        status = mystic (&output->atm.nlyr,\n                         threed,\n                         input.n_caoth + 2,\n                         output->mc.dt,\n                         output->mc.om,\n                         output->mc.g1,\n                         output->mc.g2,\n                         output->mc.ff,\n                         output->mc.ds,\n                         &(output->mc.alis),\n                         output->mc.refind,\n                         input.r_earth * 1000.0,\n                         input.rte.mc.refractive_index_pv,\n                         &(output->rayleigh_depol[iv]),\n                         output->caoth3d,\n                         output->mc.re,\n                         output->mc.temper,\n                         input.atmosphere3d,\n                         output->mc.z,\n                         output->mc.momaer,\n                         output->mc.nmomaer,\n                         output->mc.nthetaaer,\n                         output->mc.thetaaer,\n                         output->mc.muaer,\n                         output->mc.phaseaer,\n                         output->mc.nphamataer,\n                         &output->alb.albedo_r[iv],\n                         alb_type,\n                         output->atm.sza_r[iv],\n                         output->atm.phi0_r[iv],\n                         input.atm.sza_spher,\n                         input.atm.phi0_spher,\n                         thermal_photons,\n                         &source,\n                         &(output->wl.wvnmlo_r[iv]),\n                         &(output->wl.wvnmhi_r[iv]),\n                         &(output->wl.lambda_r[iv]),\n                         output->atm.zout_sur,\n                         &(output->atm.nzout),\n                         rpv_rho0,\n                         rpv_k,\n                         rpv_theta,\n                         rpv_scale,\n                         rpv_sigma,\n                         rpv_t1,\n                         rpv_t2,\n                         hapke_h,\n                         hapke_b0,\n                         hapke_w,\n                         rossli_iso,\n                         rossli_vol,\n                         rossli_geo,\n                         input.rossli.hotspot,\n                         &(input.cm.param[BRDF_CAM_U10]),\n                         &(input.cm.param[BRDF_CAM_PCL]),\n                         &(input.cm.param[BRDF_CAM_SAL]),\n                         &(input.cm.param[BRDF_CAM_UPHI]),\n                         &(input.cm.solar_wind),\n                         &(input.bpdf.u10),\n                         &(input.rte.mc.tenstream),\n                         input.rte.mc.tenstream_options,\n                         &(input.rte.mc.nca), /* Carolin Klinger 2019 */\n                         input.rte.mc.nca_options,\n                         &(input.rte.mc.ipa),\n                         &(input.rte.mc.absorption),\n                         &(input.rte.mc.backward.thermal_heating_method),\n                         &mc_loaddata,\n                         &(output->mc.sample),\n                         &(output->mc.elev),\n                         &(output->mc.triangular_surface),\n                         &(output->mc.surftemp),\n                         input.rte.mc.filename[FN_MC_BASENAME],\n                         input.rte.mc.filename[FN_MC_UMU],\n                         input.rte.mc.filename[FN_MC_SUNSHAPE_FILE],\n                         input.rte.mc.filename[FN_MC_ALBEDO],\n                         input.rte.mc.filename[FN_MC_AMBRALS],\n                         input.rte.mc.filename[FN_MC_ROSSLI],\n                         input.rte.mc.filename[FN_MC_ALBEDO_TYPE],\n                         input.rte.mc.filename[FN_MC_RPV2D_TYPE],\n                         input.rte.mc.filename[FN_MC_AMBRALS_TYPE],\n                         output->surfaces.label,\n                         &(output->surfaces.n),\n                         &(input.rte.mc.delta_scaling_mucut), /*TZ ds*/\n                         &(input.rte.mc.truncate),\n                         &(input.rte.mc.reflectalways),\n                         input.quiet,\n                         rte_out->rfldir,\n                         rte_out->rfldn,\n                         rte_out->flup,\n                         rte_out->uavgso,\n                         rte_out->uavgdn,\n                         rte_out->uavgup,\n                         rte_out->rfldir3d,\n                         rte_out->rfldn3d,\n                         rte_out->flup3d,\n                         rte_out->fl3d_is,\n                         rte_out->uavgso3d,\n                         rte_out->uavgdn3d,\n                         rte_out->uavgup3d,\n                         rte_out->radiance3d,\n                         rte_out->absback3d,\n                         rte_out->abs3d,\n                         rte_out->radiance3d_is,\n                         rte_out->jacobian,\n                         rte_out->rfldir3d_var,\n                         rte_out->rfldn3d_var,\n                         rte_out->flup3d_var,\n                         rte_out->uavgso3d_var,\n                         rte_out->uavgdn3d_var,\n                         rte_out->uavgup3d_var,\n                         rte_out->radiance3d_var,\n                         rte_out->absback3d_var,\n                         rte_out->abs3d_var,\n                         rte_out->triangle_results,\n                         output->atm.Nxcld,\n                         output->atm.Nycld,\n                         output->atm.Nzcld,\n                         output->atm.dxcld,\n                         output->atm.dycld,\n                         input.filename[FN_PATH],\n                         input.filename[FN_RANDOMSTATUS],\n                         input.rte.mc.readrandomstatus,\n                         input.write_output_as_netcdf,\n                         write_files,\n                         input.rte.mc.visualize);\n\n        CHKERR (status);\n\n        /* thermal emission of the surface */\n        if (!input.rte.mc.backward.yes && !input.rte.mc.tenstream &&\n            !input.rte.mc.nca) { /*TZ bt, no separate surface emission needed*/ /* Carolin Klinger 2019 */\n          if (ib == 0 && !input.quiet)\n            fprintf (stderr, \" ... thermal emission of the surface\\n\");\n          /* data have already been loaded during the last MYSTIC call */\n          mc_loaddata = 0;\n\n          tmp_out = calloc_rte_output (input,\n                                       output->atm.nzout,\n                                       output->atm.Nxcld,\n                                       output->atm.Nycld,\n                                       output->atm.Nzcld,\n                                       output->mc.sample.Nx,\n                                       output->mc.sample.Ny,\n                                       output->mc.alis.Nc,\n                                       output->mc.alis.nlambda_abs,\n                                       output->atm.nlyr - 1,\n                                       output->atm.threed,\n                                       output->mc.sample.passback3D,\n                                       output->mc.triangular_surface.N_triangles);\n\n          source = MCSRC_THERMAL_SURFACE;\n\n          status = mystic (&output->atm.nlyr,\n                           threed,\n                           input.n_caoth + 2,\n                           output->mc.dt,\n                           output->mc.om,\n                           output->mc.g1,\n                           output->mc.g2,\n                           output->mc.ff,\n                           output->mc.ds,\n                           &(output->mc.alis),\n                           output->mc.refind,\n                           input.r_earth * 1000.0,\n                           input.rte.mc.refractive_index_pv,\n                           &(output->rayleigh_depol[iv]),\n                           output->caoth3d,\n                           output->mc.re,\n                           output->mc.temper,\n                           input.atmosphere3d,\n                           output->mc.z,\n                           output->mc.momaer,\n                           output->mc.nmomaer,\n                           output->mc.nthetaaer,\n                           output->mc.thetaaer,\n                           output->mc.muaer,\n                           output->mc.phaseaer,\n                           output->mc.nphamataer,\n                           &output->alb.albedo_r[iv],\n                           alb_type,\n                           output->atm.sza_r[iv],\n                           output->atm.phi0_r[iv],\n                           input.atm.sza_spher,\n                           input.atm.phi0_spher,\n                           thermal_photons,\n                           &source,\n                           &(output->wl.wvnmlo_r[iv]),\n                           &(output->wl.wvnmhi_r[iv]),\n                           &(output->wl.lambda_r[iv]),\n                           output->atm.zout_sur,\n                           &(output->atm.nzout),\n                           rpv_rho0,\n                           rpv_k,\n                           rpv_theta,\n                           rpv_scale,\n                           rpv_sigma,\n                           rpv_t1,\n                           rpv_t2,\n                           hapke_h,\n                           hapke_b0,\n                           hapke_w,\n                           rossli_iso,\n                           rossli_vol,\n                           rossli_geo,\n                           input.rossli.hotspot,\n                           &(input.cm.param[BRDF_CAM_U10]),\n                           &(input.cm.param[BRDF_CAM_PCL]),\n                           &(input.cm.param[BRDF_CAM_SAL]),\n                           &(input.cm.param[BRDF_CAM_UPHI]),\n                           &(input.cm.solar_wind),\n                           &(input.bpdf.u10),\n                           &(input.rte.mc.tenstream),\n                           input.rte.mc.tenstream_options,\n                           &(input.rte.mc.nca), /* Carolin Klinger 2019 */\n                           input.rte.mc.nca_options,\n                           &(input.rte.mc.ipa),\n                           &(input.rte.mc.absorption),\n                           &(input.rte.mc.backward.thermal_heating_method),\n                           &mc_loaddata,\n                           &(output->mc.sample),\n                           &(output->mc.elev),\n                           &(output->mc.triangular_surface),\n                           &(output->mc.surftemp),\n                           input.rte.mc.filename[FN_MC_BASENAME],\n                           input.rte.mc.filename[FN_MC_UMU],\n                           input.rte.mc.filename[FN_MC_SUNSHAPE_FILE],\n                           input.rte.mc.filename[FN_MC_ALBEDO],\n                           input.rte.mc.filename[FN_MC_AMBRALS],\n                           input.rte.mc.filename[FN_MC_ROSSLI],\n                           input.rte.mc.filename[FN_MC_ALBEDO_TYPE],\n                           input.rte.mc.filename[FN_MC_RPV2D_TYPE],\n                           input.rte.mc.filename[FN_MC_AMBRALS_TYPE],\n                           output->surfaces.label,\n                           &(output->surfaces.n),\n                           &(input.rte.mc.delta_scaling_mucut), /*TZ ds*/\n                           &(input.rte.mc.truncate),\n                           &(input.rte.mc.reflectalways),\n                           input.quiet,\n                           tmp_out->rfldir,\n                           tmp_out->rfldn,\n                           tmp_out->flup,\n                           tmp_out->uavgso,\n                           tmp_out->uavgdn,\n                           tmp_out->uavgup,\n                           tmp_out->rfldir3d,\n                           tmp_out->rfldn3d,\n                           tmp_out->flup3d,\n                           tmp_out->fl3d_is,\n                           tmp_out->uavgso3d,\n                           tmp_out->uavgdn3d,\n                           tmp_out->uavgup3d,\n                           tmp_out->radiance3d,\n                           rte_out->absback3d,\n                           tmp_out->abs3d,\n                           rte_out->radiance3d_is,\n                           rte_out->jacobian,\n                           tmp_out->rfldir3d_var,\n                           tmp_out->rfldn3d_var,\n                           tmp_out->flup3d_var,\n                           tmp_out->uavgso3d_var,\n                           tmp_out->uavgdn3d_var,\n                           tmp_out->uavgup3d_var,\n                           tmp_out->radiance3d_var,\n                           rte_out->absback3d_var,\n                           tmp_out->abs3d_var,\n                           rte_out->triangle_results,\n                           output->atm.Nxcld,\n                           output->atm.Nycld,\n                           output->atm.Nzcld,\n                           output->atm.dxcld,\n                           output->atm.dycld,\n                           input.filename[FN_PATH],\n                           input.filename[FN_RANDOMSTATUS],\n                           input.rte.mc.readrandomstatus,\n                           input.write_output_as_netcdf,\n                           write_files,\n                           input.rte.mc.visualize);\n\n          CHKERR (status);\n\n          /* add atmosphere and surface contributions to get total (rte_out) */\n          if (input.rte.mc.spectral_is)\n            for (iv_alis = 0; iv_alis < output->mc.alis.nlambda_abs; iv_alis++)\n              weight_spectral[iv_alis] = 1.0;\n\n          status = add_rte_output (rte_out,\n                                   tmp_out,\n                                   1.0,\n                                   weight_spectral,\n                                   input,\n                                   output->atm.nzout,\n                                   output->atm.Nxcld,\n                                   output->atm.Nycld,\n                                   output->atm.Nzcld,\n                                   output->mc.alis.Nc,\n                                   output->atm.nlyr - 1,\n                                   output->mc.alis.nlambda_abs,\n                                   output->atm.threed,\n                                   output->mc.sample.passback3D,\n                                   output->islower,\n                                   output->isupper,\n                                   output->jslower,\n                                   output->jsupper,\n                                   output->isstep,\n                                   output->jsstep);\n          CHKERR (status);\n\n          status = free_rte_output (tmp_out,\n                                    input,\n                                    output->atm.nzout,\n                                    output->atm.Nxcld,\n                                    output->atm.Nycld,\n                                    output->atm.Nzcld,\n                                    output->mc.sample.Nx,\n                                    output->mc.sample.Ny,\n                                    output->mc.alis.Nc,\n                                    output->atm.nlyr - 1,\n                                    output->mc.alis.nlambda_abs,\n                                    output->atm.threed,\n                                    output->mc.sample.passback3D);\n          CHKERR (status);\n        } /*TZ bt, no surface emission needed*/\n\n        break;\n\n      case MCFORWARD_ABS_EMISSION:\n\n        thermal_photons = 0;\n\n        /* 3D emission field */\n        if (!input.quiet)\n          fprintf (stderr, \" ... calculate 3D emission field \\n\");\n\n        source = MCSRC_THERMAL_ATMOSPHERE;\n\n        status = mystic (&output->atm.nlyr,\n                         threed,\n                         input.n_caoth + 2,\n                         output->mc.dt,\n                         output->mc.om,\n                         output->mc.g1,\n                         output->mc.g2,\n                         output->mc.ff,\n                         output->mc.ds,\n                         &(output->mc.alis),\n                         output->mc.refind,\n                         input.r_earth * 1000.0,\n                         input.rte.mc.refractive_index_pv,\n                         &(output->rayleigh_depol[iv]),\n                         output->caoth3d,\n                         output->mc.re,\n                         output->mc.temper,\n                         input.atmosphere3d,\n                         output->mc.z,\n                         output->mc.momaer,\n                         output->mc.nmomaer,\n                         output->mc.nthetaaer,\n                         output->mc.thetaaer,\n                         output->mc.muaer,\n                         output->mc.phaseaer,\n                         output->mc.nphamataer,\n                         &output->alb.albedo_r[iv],\n                         alb_type,\n                         output->atm.sza_r[iv],\n                         output->atm.phi0_r[iv],\n                         input.atm.sza_spher,\n                         input.atm.phi0_spher,\n                         thermal_photons,\n                         &source,\n                         &(output->wl.wvnmlo_r[iv]),\n                         &(output->wl.wvnmhi_r[iv]),\n                         &(output->wl.lambda_r[iv]),\n                         output->atm.zout_sur,\n                         &(output->atm.nzout),\n                         rpv_rho0,\n                         rpv_k,\n                         rpv_theta,\n                         rpv_scale,\n                         rpv_sigma,\n                         rpv_t1,\n                         rpv_t2,\n                         hapke_h,\n                         hapke_b0,\n                         hapke_w,\n                         rossli_iso,\n                         rossli_vol,\n                         rossli_geo,\n                         input.rossli.hotspot,\n                         &(input.cm.param[BRDF_CAM_U10]),\n                         &(input.cm.param[BRDF_CAM_PCL]),\n                         &(input.cm.param[BRDF_CAM_SAL]),\n                         &(input.cm.param[BRDF_CAM_UPHI]),\n                         &(input.cm.solar_wind),\n                         &(input.bpdf.u10),\n                         &(input.rte.mc.tenstream),\n                         input.rte.mc.tenstream_options,\n                         &(input.rte.mc.nca), /* Carolin Klinger 2019 */\n                         input.rte.mc.nca_options,\n                         &(input.rte.mc.ipa),\n                         &(input.rte.mc.absorption),\n                         &(input.rte.mc.backward.thermal_heating_method),\n                         &mc_loaddata,\n                         &(output->mc.sample),\n                         &(output->mc.elev),\n                         &(output->mc.triangular_surface),\n                         &(output->mc.surftemp),\n                         input.rte.mc.filename[FN_MC_BASENAME],\n                         input.rte.mc.filename[FN_MC_UMU],\n                         input.rte.mc.filename[FN_MC_SUNSHAPE_FILE],\n                         input.rte.mc.filename[FN_MC_ALBEDO],\n                         input.rte.mc.filename[FN_MC_AMBRALS],\n                         input.rte.mc.filename[FN_MC_ROSSLI],\n                         input.rte.mc.filename[FN_MC_ALBEDO_TYPE],\n                         input.rte.mc.filename[FN_MC_RPV2D_TYPE],\n                         input.rte.mc.filename[FN_MC_AMBRALS_TYPE],\n                         output->surfaces.label,\n                         &(output->surfaces.n),\n                         &(input.rte.mc.delta_scaling_mucut), /*TZ ds*/\n                         &(input.rte.mc.truncate),\n                         &(input.rte.mc.reflectalways),\n                         input.quiet,\n                         rte_out->rfldir,\n                         rte_out->rfldn,\n                         rte_out->flup,\n                         rte_out->uavgso,\n                         rte_out->uavgdn,\n                         rte_out->uavgup,\n                         rte_out->rfldir3d,\n                         rte_out->rfldn3d,\n                         rte_out->flup3d,\n                         rte_out->fl3d_is,\n                         rte_out->uavgso3d,\n                         rte_out->uavgdn3d,\n                         rte_out->uavgup3d,\n                         rte_out->radiance3d,\n                         rte_out->absback3d,\n                         rte_out->abs3d,\n                         rte_out->radiance3d_is,\n                         rte_out->jacobian,\n                         rte_out->rfldir3d_var,\n                         rte_out->rfldn3d_var,\n                         rte_out->flup3d_var,\n                         rte_out->uavgso3d_var,\n                         rte_out->uavgdn3d_var,\n                         rte_out->uavgup3d_var,\n                         rte_out->radiance3d_var,\n                         rte_out->absback3d_var,\n                         rte_out->abs3d_var,\n                         rte_out->triangle_results,\n                         output->atm.Nxcld,\n                         output->atm.Nycld,\n                         output->atm.Nzcld,\n                         output->atm.dxcld,\n                         output->atm.dycld,\n                         input.filename[FN_PATH],\n                         input.filename[FN_RANDOMSTATUS],\n                         input.rte.mc.readrandomstatus,\n                         input.write_output_as_netcdf,\n                         write_files,\n                         input.rte.mc.visualize);\n\n        CHKERR (status)\n\n        break;\n\n      default:\n        fprintf (stderr, \"Error, unknown absorption type %d\\n\", input.rte.mc.absorption);\n        CHKERR (-1);\n      }\n\n      break;\n\n    default:\n      CHKERROUT (-1, \"unknown source\");\n    }\n\n    /* free RPV arrays */\n    free (rpv_rho0);\n    free (rpv_k);\n    free (rpv_theta);\n    free (rpv_scale);\n    free (rpv_sigma);\n    free (rpv_t1);\n    free (rpv_t2);\n\n    /* free ROSSLI arrays */\n    free (rossli_iso);\n    free (rossli_vol);\n    free (rossli_geo);\n\n    /* free HAPKE arrays */\n    free (hapke_h);\n    free (hapke_b0);\n    free (hapke_w);\n\n    break;\n\n#else\n    fprintf (stderr, \"Error: MYSTIC solver not included in uvspec build.\\n\");\n    fprintf (stderr, \"Error: Please contact bernhard.mayer@lmu.de\\n\");\n    CHKERR (-1);\n#endif\n\n  case SOLVER_FDISORT1:\n  case SOLVER_FDISORT2:\n  case SOLVER_DISORT:\n\n    if (rte_solver != SOLVER_DISORT) {\n      disort_u0u = (float*)calloc (output->atm.nzout * input.rte.maxumu, sizeof (float));\n      disort_uu  = (float*)calloc (output->atm.nzout * input.rte.maxumu * input.rte.maxphi, sizeof (float));\n    }\n\n    /* ??? no need for thermal below 2um;                 ??? */\n    /* ??? need to do that to avoid numerical underflow;  ??? */\n    /* ??? however, this could be done without actually   ??? */\n    /* ??? calling the solver                             ??? */\n    if (rte_in->planck && output->wl.lambda_r[iv] < 2000.0) {\n      rte_in->planck = 0;\n      planck_tempoff = 1;\n    }\n\n    if (input.rte.solver == SOLVER_FDISORT1) {\n\n      if (iv == output->wl.nlambda_rte_lower && ib == 0) {\n        status = F77_FUNC (dcheck, DCHECK) (&output->atm.nlyr,\n                                            &output->atm.nzout,\n                                            &input.rte.nstr,\n                                            &input.rte.numu,\n                                            &input.rte.nphi,\n                                            &input.optimize_fortran,\n                                            &input.optimize_delta);\n        if (status != 0) {\n          fprintf (stderr, \"Error %d returned by dcheck in %s (%s)\\n\", status, function_name, file_name);\n          return status;\n        }\n      }\n\n      disort_pmom = c2fortran_3D_float_ary (output->atm.nlyr, 1, input.rte.nstr + 1, output->pmom);\n\n      if (((input.source == SRC_SOLAR) && (rte_in->umu0 > 0)) || (input.source == SRC_THERMAL)) {\n        /* no need to call disort otherwise as sun below horizon */\n        F77_FUNC (disort, DISORT)\n        (&output->atm.nlyr,\n         output->dtauc,\n         output->ssalb,\n         disort_pmom,\n         output->atm.microphys.temper[0][0],\n         &(output->wl.wvnmlo_r[iv]),\n         &(output->wl.wvnmhi_r[iv]),\n         &(rte_in->usrtau),\n         &output->atm.nzout,\n         rte_in->utau,\n         &input.rte.nstr,\n         &(rte_in->usrang),\n         &input.rte.numu,\n         input.rte.umu,\n         &input.rte.nphi,\n         input.rte.phi,\n         &(rte_in->ibcnd),\n         &(rte_in->fbeam),\n         &(rte_in->umu0),\n         &output->atm.phi0_r[iv],\n         &(rte_in->fisot),\n         &(rte_in->lamber),\n         &output->alb.albedo_r[iv],\n         rte_in->hl,\n         &(rte_in->btemp),\n         &(rte_in->ttemp),\n         &(rte_in->temis),\n         &input.rte.deltam,\n         &(rte_in->planck),\n         &(rte_in->onlyfl),\n         &(rte_in->accur),\n         rte_in->prndis,\n         rte_in->header,\n         &output->atm.nlyr,\n         &output->atm.nzout,\n         &input.rte.maxumu,\n         &input.rte.nstr,\n         &input.rte.maxphi,\n         rte_out->rfldir,\n         rte_out->rfldn,\n         rte_out->flup,\n         rte_out->dfdt,\n         rte_out->uavg,\n         disort_uu,\n         disort_u0u,\n         rte_out->albmed,\n         rte_out->trnmed,\n         rte_out->uavgdn,\n         rte_out->uavgso,\n         rte_out->uavgup,\n         &(input.quiet));\n\n        for (lev = 0; lev < output->atm.nzout; lev++)\n          rte_out->uavg[lev] = rte_out->uavgso[lev] + rte_out->uavgdn[lev] + rte_out->uavgup[lev];\n      }\n    } else if (input.rte.solver == SOLVER_FDISORT2) {\n\n      if (iv == output->wl.nlambda_rte_lower && ib == 0) {\n        status = F77_FUNC (dcheck, DCHECK) (&output->atm.nlyr,\n                                            &output->atm.nzout,\n                                            &input.rte.nstr,\n                                            &input.rte.numu,\n                                            &input.rte.nphi,\n                                            &input.optimize_fortran,\n                                            &input.optimize_delta);\n        if (status != 0) {\n          fprintf (stderr, \"Error %d returned by dcheck in %s (%s)\\n\", status, function_name, file_name);\n          return status;\n        }\n      }\n\n      /* BRDF or Lambertian albedo */\n      if (input.disort2_brdf != BRDF_NONE)\n        rte_in->lamber = 0;\n      else\n        rte_in->lamber = 1;\n\n      disort2_pmom = c2fortran_3D_float_ary (output->atm.nlyr, 1, output->atm.nmom + 1, output->pmom);\n\n      switch (input.rte.disort_icm) {\n      case DISORT_ICM_OFF:\n        intensity_correction = FALSE;\n        break;\n      case DISORT_ICM_MOMENTS:\n        intensity_correction     = TRUE;\n        old_intensity_correction = TRUE;\n        break;\n      case DISORT_ICM_PHASE:\n        intensity_correction     = TRUE;\n        old_intensity_correction = FALSE;\n        disort2_ntheta           = &(output->ntheta[0][0]);\n        disort2_phaso            = c2fortran_3D_float_ary (output->atm.nlyr, 1, output->ntheta[0][0], output->phase);\n        disort2_mup              = c2fortran_3D_double_ary (1, 1, output->ntheta[0][0], output->mu);\n        break;\n      default:\n        fprintf (stderr, \"Error: unknown disort_icm %d\\n\", input.rte.disort_icm);\n        fprintf (stderr, \"       (line %d, function '%s' in '%s')\\n\", __LINE__, __func__, __FILE__);\n        return -1;\n      }\n\n      if (((input.source == SRC_SOLAR) && (rte_in->umu0 > 0)) || (input.source == SRC_THERMAL)) {\n        /* no need to call disort2 otherwise, as sun below horizon */\n        F77_FUNC (disort2, DISORT2)\n        (&output->atm.nlyr,\n         output->dtauc,\n         output->ssalb,\n         &output->atm.nmom,\n         disort2_pmom,\n         disort2_ntheta,\n         disort2_phaso,\n         disort2_mup,\n         output->atm.microphys.temper[0][0],\n         &output->wl.wvnmlo_r[iv],\n         &output->wl.wvnmhi_r[iv],\n         &rte_in->usrtau,\n         &output->atm.nzout,\n         rte_in->utau,\n         &input.rte.nstr,\n         &rte_in->usrang,\n         &input.rte.numu,\n         input.rte.umu,\n         &input.rte.nphi,\n         input.rte.phi,\n         &rte_in->ibcnd,\n         &rte_in->fbeam,\n         &rte_in->umu0,\n         &output->atm.phi0_r[iv],\n         &rte_in->fisot,\n         &rte_in->lamber,\n         &output->alb.albedo_r[iv],\n         &rte_in->btemp,\n         &rte_in->ttemp,\n         &rte_in->temis,\n         &rte_in->planck,\n         &rte_in->onlyfl,\n         &rte_in->accur,\n         rte_in->prndis2,\n         rte_in->header,\n         &output->atm.nlyr,\n         &output->atm.nzout,\n         &input.rte.maxumu,\n         &input.rte.maxphi,\n         &output->atm.nmom,\n         rte_out->rfldir,\n         rte_out->rfldn,\n         rte_out->flup,\n         rte_out->dfdt,\n         rte_out->uavg,\n         disort_uu,\n         disort_u0u,\n         rte_out->albmed,\n         rte_out->trnmed,\n         rte_out->uavgdn,\n         rte_out->uavgso,\n         rte_out->uavgup,\n         &(input.disort2_brdf),\n         &(output->rpv.rho0_r[iv]),\n         &(output->rpv.k_r[iv]),\n         &(output->rpv.theta_r[iv]),\n         &(output->rpv.sigma_r[iv]),\n         &(output->rpv.t1_r[iv]),\n         &(output->rpv.t2_r[iv]),\n         &(output->rpv.scale_r[iv]),\n         &(output->rossli.iso_r[iv]),\n         &(output->rossli.vol_r[iv]),\n         &(output->rossli.geo_r[iv]),\n         &(input.cm.param[BRDF_CAM_U10]),\n         &(input.cm.param[BRDF_CAM_PCL]),\n         &(input.cm.param[BRDF_CAM_SAL]),\n         &intensity_correction,\n         &old_intensity_correction,\n         &(input.quiet));\n        for (lev = 0; lev < output->atm.nzout; lev++)\n          rte_out->uavg[lev] = rte_out->uavgso[lev] + rte_out->uavgdn[lev] + rte_out->uavgup[lev];\n      }\n    } else if (input.rte.solver == SOLVER_DISORT) {\n\n      if (input.flu.source != NOT_DEFINED_INTEGER) {  // We have included fluorescence as radiation source\n        rte_in->fbeam = output->wl.fbeam[iv];         // Need to do calibrated simulation.\n      }\n\n      if (input.raman) {\n\n        rte_in->gsrc              = 0;\n        ds_in.flag.general_source = FALSE; /* No extra source term for zero Raman scattering. */\n\n        if (ir == 0 && input.raman_fast) {\n          rte_in->fbeam = output->wl.fbeam[ib];\n        } else if (ir == 0 && !input.raman_fast) {\n\n          if (ib == 0) {\n            if ((status = ASCII_calloc_double_3D (&tmp_crs, output->atm.nlev, output->crs.number_of_ramanwavelengths, 3)) != 0) {\n              fprintf (stderr, \"Error %d allocating memory for tmp_crs\\n\", status);\n              fprintf (stderr, \"       (line %d, function '%s' in '%s')\\n\", __LINE__, __func__, __FILE__);\n              return status;\n            }\n\n            /* First time for each user wavelength calculate Raman shifted wavelengths and Raman cross section */\n            for (lu = 0; lu < output->atm.nlev; lu++) {\n              ivi    = 0;\n              status = crs_raman_N2 (output->wl.lambda_r[iv],\n                                     input.n_raman_transitions_N2,\n                                     output->atm.microphys.temper[lu][0][0],\n                                     &tmp_crs[lu],\n                                     &ivi,\n                                     verbose);\n              status = crs_raman_O2 (output->wl.lambda_r[iv],\n                                     input.n_raman_transitions_O2,\n                                     output->atm.microphys.temper[lu][0][0],\n                                     &tmp_crs[lu],\n                                     &ivi,\n                                     verbose);\n\n              /* Put the wanted wavelength last in the tmp_crs by doing the following */\n              /* and set correctly after sort                                         */\n              tmp_crs[lu][output->crs.number_of_ramanwavelengths - 1][0] = 999e+9;\n\n              /* sort cross section data in ascending order */\n              status = ASCII_sortarray (tmp_crs[lu], output->crs.number_of_ramanwavelengths, 3, 0, 0);\n\n              for (ivi = 0; ivi < output->crs.number_of_ramanshifts; ivi++) {\n                output->crs.wvl_of_ramanshifts[ivi] = tmp_crs[0][ivi][0];\n                output->crs.crs_raman_RL[lu][ivi]   = tmp_crs[lu][ivi][1];\n                output->crs.crs_raman_RG[lu][ivi]   = tmp_crs[lu][ivi][2];\n              }\n              ivi                                 = output->crs.number_of_ramanwavelengths - 1;\n              output->crs.wvl_of_ramanshifts[ivi] = output->wl.lambda_r[iv];\n              output->crs.crs_raman_RL[lu][ivi]   = 0.0;\n              output->crs.crs_raman_RG[lu][ivi]   = 0.0;\n            }\n            if (tmp_crs != NULL)\n              ASCII_free_double_3D (tmp_crs, output->atm.nlev, output->crs.number_of_ramanwavelengths);\n          }\n\n          /* Interpolate all optical quantities to the Raman shifted wavelength */\n\n          qwanted_wvl[0] = (float)output->crs.wvl_of_ramanshifts[ib];\n          status =\n            arb_wvn (output->wl.nlambda_r, output->wl.lambda_r, output->wl.fbeam, 1, qwanted_wvl, qfbeam, INTERP_METHOD_LINEAR, 0);\n          if (status != 0) {\n            fprintf (stderr, \" Error, interpolation of 'fbeam' for raman option\\n\");\n            fprintf (stderr, \"       (line %d, function '%s' in '%s')\\n\", __LINE__, __func__, __FILE__);\n            return -1;\n          }\n\n          /* FIXME, redistribute photons instead of interpolating spectrum */\n          rte_in->fbeam = qfbeam[0];\n          status        = arb_wvn (output->wl.nlambda_r,\n                            output->wl.lambda_r,\n                            output->alb.albedo_r,\n                            1,\n                            qwanted_wvl,\n                            qalbedo,\n                            INTERP_METHOD_LINEAR,\n                            0);\n          if (status != 0) {\n            fprintf (stderr, \" Error, interpolation of 'albedo_r' for raman option\\n\");\n            fprintf (stderr, \"       (line %d, function '%s' in '%s')\\n\", __LINE__, __func__, __FILE__);\n            return -1;\n          }\n\n          /* Find iv indices closest to ib wavelength above and below */\n          iv1 = closest_above (qwanted_wvl[0], output->wl.lambda_r, output->wl.nlambda_r);\n          iv2 = closest_below (qwanted_wvl[0], output->wl.lambda_r, output->wl.nlambda_r);\n          /* Calculate optical properties for closest wavelength above and below wanted wavelength,*/\n          /* and interpolate optical properties to wanted wavelength.       */\n          status = optical_properties (input,\n                                       output,\n                                       qwanted_wvl[0],\n                                       ir,\n                                       iv1,\n                                       iv2,\n                                       0,\n                                       verbose,\n                                       skip_optical_properties); /* in ancillary.c */\n\n          if (status != 0) {\n            fprintf (stderr,\n                     \"Error %d returned by optical_properties_raman (line %d, function %s in %s)\\n\",\n                     status,\n                     __LINE__,\n                     __func__,\n                     __FILE__);\n            return status;\n          }\n\n          /* We also need utau at the \"new\" interpolated optical depth. */\n          /* \"very old\" version, recycled */\n          /* zd is altitude which defines  dtauc */\n          /* zout is the altitudes at which tau is wanted */\n          F77_FUNC (setout, SETOUT)\n          (output->dtauc, &(output->atm.nlyr), &(output->atm.nzout), rte_in->utau, output->atm.zd, output->atm.zout_sur);\n        }\n\n        else if (ir == 1) {\n\n          rte_in->fbeam             = 0.0;\n          rte_in->gsrc              = 1;\n          ds_in.flag.general_source = TRUE; /* Include extra source term for first order Raman scattering. */\n\n          if ((status = ASCII_calloc_double_3D (&(rte_in->qsrc), input.rte.nstr, output->atm.nzout, input.rte.nstr)) != 0)\n            return status;\n\n          if (rte_in->usrang) {\n            if ((status = ASCII_calloc_double_3D (&(rte_in->qsrcu), input.rte.nstr, output->atm.nzout, input.rte.numu)) != 0)\n              return status;\n          }\n\n          if (input.raman_fast) {\n\n            /* Calculate Raman crs at wanted wavelength. */\n            if ((status = ASCII_calloc_double_3D (&tmp_crs, output->atm.nlev, output->crs.number_of_ramanwavelengths, 3)) != 0) {\n              fprintf (stderr, \"Error %d allocating memory for tmp_crs\\n\", status);\n              fprintf (stderr, \"       (line %d, function '%s' in '%s')\\n\", __LINE__, __func__, __FILE__);\n              return status;\n            }\n\n            /* For each user wavelength calculate Raman shifted wavelengths and Raman cross section */\n            for (lu = 0; lu < output->atm.nlev; lu++) {\n              ivi    = 0;\n              status = crs_raman_N2 (output->wl.lambda_r[iv + output->wl.nlambda_rte_lower],\n                                     input.n_raman_transitions_N2,\n                                     output->atm.microphys.temper[0][0][lu],\n                                     &tmp_crs[lu],\n                                     &ivi,\n                                     verbose);\n              status = crs_raman_O2 (output->wl.lambda_r[iv + output->wl.nlambda_rte_lower],\n                                     input.n_raman_transitions_O2,\n                                     output->atm.microphys.temper[0][0][lu],\n                                     &tmp_crs[lu],\n                                     &ivi,\n                                     verbose);\n\n              /* Put the wanted wavelength last in the tmp_crs by doing the following */\n              /* and set correctly after sort                                         */\n              tmp_crs[lu][output->crs.number_of_ramanwavelengths - 1][0] = 999e+9;\n\n              /* sort cross section data in ascending order */\n              status = ASCII_sortarray (tmp_crs[lu], output->crs.number_of_ramanwavelengths, 3, 0, 0);\n\n              for (ivi = 0; ivi < output->crs.number_of_ramanshifts; ivi++) {\n                output->crs.wvl_of_ramanshifts[ivi] = tmp_crs[0][ivi][0];\n                output->crs.crs_raman_RL[lu][ivi]   = tmp_crs[lu][ivi][1];\n                // Cross sections are reversed in wavelength. This because photons are scattered into the\n                // wavelength of interest, lambda_1, from these wavelengths (lambda_j). If lambda_j >\n                // lambda_1, then the photon gains energy. Thus, the original cross section indices\n                // must be reversed to account for this, and vice versa. AK, 20130513.\n                output->crs.crs_raman_RG[lu][output->crs.number_of_ramanshifts - ivi] = tmp_crs[lu][ivi][2];\n              }\n              ivi                                 = output->crs.number_of_ramanwavelengths - 1;\n              output->crs.wvl_of_ramanshifts[ivi] = output->wl.lambda_r[iv];\n              output->crs.crs_raman_RL[lu][ivi]   = 0.0;\n              output->crs.crs_raman_RG[lu][ivi]   = 0.0;\n            }\n            if (tmp_crs != NULL)\n              ASCII_free_double_3D (tmp_crs, output->atm.nlev, output->crs.number_of_ramanwavelengths);\n\n            /* Interpolate raman_qsrc_comp at wl.lambda_r resolution to raman_wavelength grid */\n\n            tmp_raman_qsrc_comp = calloc_raman_qsrc_components (input.raman_fast,\n                                                                output->atm.nzout,\n                                                                input.rte.maxumu,\n                                                                input.rte.nphi,\n                                                                input.rte.nstr,\n                                                                output->crs.number_of_ramanwavelengths);\n\n            /* Interpolate dtauc */\n            if ((tmp_in_int = (double*)calloc (output->wl.nlambda_r, sizeof (double))) == NULL)\n              return ASCII_NO_MEMORY;\n            if ((tmp_wl = (double*)calloc (output->wl.nlambda_r, sizeof (double))) == NULL)\n              return ASCII_NO_MEMORY;\n            if ((tmp_out_int = (double*)calloc (output->crs.number_of_ramanshifts + 1, sizeof (double))) == NULL)\n              return ASCII_NO_MEMORY;\n            for (ivi = 0; ivi < output->wl.nlambda_r; ivi++)\n              tmp_wl[ivi] = output->wl.lambda_r[ivi];\n            for (lu = 0; lu < output->atm.nzout - 1; lu++) {\n              for (ivi = 0; ivi < output->wl.nlambda_r; ivi++)\n                tmp_in_int[ivi] = raman_qsrc_comp->dtauc[lu][ivi];\n              status = arb_wvn_double (output->wl.nlambda_r,\n                                       tmp_wl,\n                                       tmp_in_int,\n                                       output->crs.number_of_ramanshifts,\n                                       output->crs.wvl_of_ramanshifts,\n                                       tmp_out_int,\n                                       INTERP_METHOD_LINEAR,\n                                       0);\n              for (ivi = 0; ivi < output->crs.number_of_ramanshifts; ivi++)\n                tmp_raman_qsrc_comp->dtauc[lu][ivi] = tmp_out_int[ivi];\n              /* The wavelength we are calculating is stored last in the ary */\n              tmp_raman_qsrc_comp->dtauc[lu][output->crs.number_of_ramanshifts] = raman_qsrc_comp->dtauc[lu][iv];\n            }\n            /* Interpolate fbeam */\n            for (ivi = 0; ivi < output->wl.nlambda_r; ivi++)\n              tmp_in_int[ivi] = raman_qsrc_comp->fbeam[ivi];\n            status = arb_wvn_double (output->wl.nlambda_r,\n                                     tmp_wl,\n                                     tmp_in_int,\n                                     output->crs.number_of_ramanshifts,\n                                     output->crs.wvl_of_ramanshifts,\n                                     tmp_out_int,\n                                     INTERP_METHOD_LINEAR,\n                                     0);\n            for (ivi = 0; ivi < output->crs.number_of_ramanshifts; ivi++)\n              tmp_raman_qsrc_comp->fbeam[ivi] = tmp_out_int[ivi];\n            /* The wavelength we are calculating is stored last in the ary */\n            tmp_raman_qsrc_comp->fbeam[output->crs.number_of_ramanshifts] = raman_qsrc_comp->fbeam[iv];\n            /* Interpolate uum */\n            for (lu = 0; lu < output->atm.nzout; lu++) {\n              for (maz = 0; maz < input.rte.nstr; maz++) {\n                for (iq = 0; iq < input.rte.numu; iq++) {\n                  for (ivi = 0; ivi < output->wl.nlambda_r; ivi++)\n                    tmp_in_int[ivi] = raman_qsrc_comp->uum[lu][maz][iq][ivi];\n                  status = arb_wvn_double (output->wl.nlambda_r,\n                                           tmp_wl,\n                                           tmp_in_int,\n                                           output->crs.number_of_ramanshifts,\n                                           output->crs.wvl_of_ramanshifts,\n                                           tmp_out_int,\n                                           INTERP_METHOD_LINEAR,\n                                           0);\n                  for (ivi = 0; ivi < output->crs.number_of_ramanshifts; ivi++)\n                    tmp_raman_qsrc_comp->uum[lu][maz][iq][ivi] = tmp_out_int[ivi];\n                  /* The wavelength we are calculating is stored last in the ary */\n                  tmp_raman_qsrc_comp->uum[lu][maz][iq][output->crs.number_of_ramanshifts] = raman_qsrc_comp->uum[lu][maz][iq][iv];\n                }\n              }\n            }\n            qwanted_wvl[0] = tmp_wl[iv]; /* Needed later in set_raman_source */\n            free (tmp_in_int);\n            free (tmp_out_int);\n            free (tmp_wl);\n\n            status = optical_properties (input,\n                                         output,\n                                         output->wl.lambda_r[iv],\n                                         ir,\n                                         iv,\n                                         iv,\n                                         0,\n                                         verbose,\n                                         skip_optical_properties); /* in ancillary.c */\n            if (status != 0) {\n              fprintf (stderr,\n                       \"Error %d returned by optical_properties (line %d, function %s in %s)\\n\",\n                       status,\n                       __LINE__,\n                       __func__,\n                       __FILE__);\n              return status;\n            }\n            /* We also need utau. */\n            /* \"very old\" version, recycled */\n            F77_FUNC (setout, SETOUT)\n            (output->dtauc, &(output->atm.nlyr), &(output->atm.nzout), rte_in->utau, output->atm.zd, output->atm.zout_sur);\n\n            /* Set the general inhomogeneous source applicable for Raman scattering   */\n            if (iv == output->wl.raman_end_id)\n              last = 1;\n            status = set_raman_source (rte_in->qsrc,\n                                       rte_in->qsrcu,\n                                       input.rte.maxphi,\n                                       output->atm.nlyr + 1,\n                                       output->atm.nzout,\n                                       input.rte.nstr,\n                                       output->crs.number_of_ramanshifts,\n                                       qwanted_wvl[0],\n                                       output->crs.wvl_of_ramanshifts,\n                                       rte_in->umu0,\n                                       output->atm.zd,\n                                       output->atm.zout_sur,\n                                       output->atm.sza_r[iv],\n                                       output->wl.fbeam[iv],\n                                       input.r_earth,\n                                       output->atm.microphys.dens[MOL_AIR][0][0],\n                                       output->crs.crs_raman_RL,\n                                       output->crs.crs_raman_RG,\n                                       output->ssalb,\n                                       input.rte.numu,\n                                       input.rte.umu,\n                                       rte_in->usrang,\n                                       input.rte.cmuind,\n                                       output->pmom,\n                                       tmp_raman_qsrc_comp,\n                                       output->atm.zout_comp_index,\n                                       output->alt.altitude,\n                                       last,\n                                       verbose);\n\n            free_raman_qsrc_components (tmp_raman_qsrc_comp,\n                                        input.raman_fast,\n                                        output->atm.nzout,\n                                        input.rte.maxumu,\n                                        input.rte.nphi,\n                                        input.rte.nstr);\n\n          } /* END if ( input.raman_fast )  */\n          else {\n\n            /* Find iv indices closest to ib wavelength above and below */\n            qwanted_wvl[0] = (float)output->crs.wvl_of_ramanshifts[output->crs.number_of_ramanwavelengths - 1];\n            iv1            = closest_above (qwanted_wvl[0], output->wl.lambda_r, output->wl.nlambda_r);\n            iv2            = closest_below (qwanted_wvl[0], output->wl.lambda_r, output->wl.nlambda_r);\n            /* Calculate optical properties for closest wavelength above and below wanted wavelength,*/\n            /* and interpolate optical properties to wanted wavelength.       */\n            status = optical_properties (input,\n                                         output,\n                                         qwanted_wvl[0],\n                                         ir,\n                                         iv1,\n                                         iv2,\n                                         0,\n                                         verbose,\n                                         skip_optical_properties); /* in ancillary.c */\n            if (status != 0) {\n              fprintf (stderr,\n                       \"Error %d returned by optical_properties (line %d, function %s in %s)\\n\",\n                       status,\n                       __LINE__,\n                       __func__,\n                       __FILE__);\n              return status;\n            }\n\n            /* We also need utau at the \"new\" interpolated optical depth. */\n            /* \"very old\" version, recycled */\n\n            F77_FUNC (setout, SETOUT)\n            (output->dtauc, &(output->atm.nlyr), &(output->atm.nzout), rte_in->utau, output->atm.zd, output->atm.zout_sur);\n\n            /* Set the general inhomogeneous source applicable for Raman scattering   */\n\n            status = set_raman_source (rte_in->qsrc,\n                                       rte_in->qsrcu,\n                                       input.rte.maxphi,\n                                       output->atm.nlyr + 1,\n                                       output->atm.nzout,\n                                       input.rte.nstr,\n                                       output->crs.number_of_ramanshifts,\n                                       qwanted_wvl[0],\n                                       output->crs.wvl_of_ramanshifts,\n                                       rte_in->umu0,\n                                       output->atm.zd,\n                                       output->atm.zout_sur,\n                                       output->atm.sza_r[iv],\n                                       output->wl.fbeam[iv],\n                                       input.r_earth,\n                                       output->atm.microphys.dens[MOL_AIR][0][0],\n                                       output->crs.crs_raman_RL,\n                                       output->crs.crs_raman_RG,\n                                       output->ssalb,\n                                       input.rte.numu,\n                                       input.rte.umu,\n                                       rte_in->usrang,\n                                       input.rte.cmuind,\n                                       output->pmom,\n                                       raman_qsrc_comp,\n                                       output->atm.zout_comp_index,\n                                       output->alt.altitude,\n                                       last,\n                                       verbose);\n          }\n        } /*  END    if ( input.raman_fast ) {} else    */\n      }   /*  END    if ( input.raman )    */\n\n      /* BRDF or Lambertian albedo */\n      if (input.disort2_brdf != BRDF_NONE)\n        rte_in->lamber = 0;\n      else\n        rte_in->lamber = 1;\n\n      ds_in.nlyr  = output->atm.nlyr;\n      ds_in.ntau  = output->atm.nzout;\n      ds_in.nstr  = input.rte.nstr;\n      ds_in.numu  = input.rte.numu;\n      ds_in.nmom  = output->atm.nmom;\n      ds_in.nphi  = input.rte.nphi;\n      ds_in.accur = rte_in->accur;\n      if (input.rte.disort_icm == DISORT_ICM_PHASE)\n        ds_in.nphase = output->ntheta[0][0];\n\n      /* choose how to do intensity correction */\n      switch (input.rte.disort_icm) {\n      case DISORT_ICM_OFF:\n        ds_in.flag.intensity_correction = FALSE;\n        break;\n      case DISORT_ICM_MOMENTS:\n        ds_in.flag.intensity_correction     = TRUE;\n        ds_in.flag.old_intensity_correction = TRUE;\n        break;\n      case DISORT_ICM_PHASE:\n        ds_in.flag.intensity_correction     = TRUE;\n        ds_in.flag.old_intensity_correction = FALSE;\n        break;\n      default:\n        fprintf (stderr, \"Error: unknown disort_icm %d\\n\", input.rte.disort_icm);\n        fprintf (stderr, \"       (line %d, function '%s' in '%s')\\n\", __LINE__, __func__, __FILE__);\n        return -1;\n      }\n\n      ds_in.flag.quiet  = input.quiet;\n      ds_in.flag.ibcnd  = rte_in->ibcnd;\n      ds_in.flag.planck = rte_in->planck;\n      ds_in.flag.lamber = rte_in->lamber;\n      ds_in.flag.usrtau = rte_in->usrtau;\n      ds_in.flag.usrang = rte_in->usrang;\n      ds_in.flag.onlyfl = rte_in->onlyfl;\n      if (input.raman) {\n        ds_in.flag.output_uum = TRUE;\n        if (ir == 1) {\n          ds_in.flag.general_source = TRUE;\n          ds_in.bc.fluor            = 0.0;  // Only fluorescence source for the zeroth iteration\n                                            // Otherwise source is included twice.\n        } else {\n          ds_in.flag.general_source = FALSE;\n          ds_in.bc.fluor            = (double)output->flu.fluorescence_r[ib];\n        }\n        ds_in.bc.albedo = (double)output->alb.albedo_r[ib];\n      } else {\n        ds_in.flag.output_uum     = FALSE;\n        ds_in.flag.general_source = FALSE;\n        ds_in.bc.albedo           = (double)output->alb.albedo_r[iv];\n        ds_in.bc.fluor            = (double)output->flu.fluorescence_r[iv];\n      }\n      ds_in.flag.spher = rte_in->spher;\n      ds_in.radius     = c_r_earth;\n\n      /* ds_in.flag.spher   = input.rte.pseudospherical; */\n\n      ds_in.bc.btemp       = (double)rte_in->btemp;\n      ds_in.bc.fbeam       = (double)rte_in->fbeam;\n      ds_in.bc.fisot       = (double)rte_in->fisot;\n      ds_in.bc.temis       = (double)rte_in->temis;\n      ds_in.bc.ttemp       = (double)rte_in->ttemp;\n      ds_in.bc.umu0        = (double)rte_in->umu0;\n      ds_in.bc.phi0        = (double)output->atm.phi0_r[iv];\n      ds_in.wvnmlo         = output->wl.wvnmlo_r[iv];\n      ds_in.wvnmhi         = output->wl.wvnmhi_r[iv];\n      ds_in.flag.prnt[0]   = rte_in->prndis2[0];\n      ds_in.flag.prnt[1]   = rte_in->prndis2[1];\n      ds_in.flag.prnt[2]   = rte_in->prndis2[2];\n      ds_in.flag.prnt[3]   = rte_in->prndis2[3];\n      ds_in.flag.prnt[4]   = rte_in->prndis2[4];\n      ds_in.flag.brdf_type = input.disort2_brdf;\n\n      c_disort_state_alloc (&ds_in);\n      c_disort_out_alloc (&ds_in, &ds_out);\n\n      for (lc = 0; lc < output->atm.nlyr; lc++) {\n        ds_in.dtauc[lc] = (double)output->dtauc[lc];\n        ds_in.ssalb[lc] = (double)output->ssalb[lc];\n\n        for (k = 0; k <= output->atm.nmom; k++) {\n          ds_in.pmom[k + lc * (ds_in.nmom_nstr + 1)] = (double)output->pmom[lc][0][k];\n        }\n      }\n      for (lc = 0; lc < output->atm.nzout; lc++) {\n        ds_in.utau[lc] = (double)rte_in->utau[lc];\n      }\n      for (iu = 0; iu < input.rte.numu; iu++) {\n        ds_in.umu[iu] = (double)input.rte.umu[iu];\n      }\n      for (iu = 0; iu < input.rte.nphi; iu++) {\n        ds_in.phi[iu] = (double)input.rte.phi[iu];\n      }\n      for (lu = 0; lu <= output->atm.nlyr; lu++) {\n        if (rte_in->planck)\n          ds_in.temper[lu] = (double)output->atm.microphys.temper[0][0][lu];\n      }\n      if (ds_in.flag.spher) {\n        for (lu = 0; lu <= output->atm.nlyr; lu++) {\n          ds_in.zd[lu] = (double)output->atm.zd[lu];\n        }\n      }\n      if (input.rte.disort_icm == DISORT_ICM_PHASE) {\n        for (imu = 0; imu < ds_in.nphase; imu++)\n          ds_in.mu_phase[imu] = output->mu[0][0][imu];\n        for (imu = 0; imu < ds_in.nphase; imu++)\n          for (lc = 0; lc < ds_in.nlyr; lc++) {\n            ds_in.phase[imu + lc * (ds_in.nphase)] = (double)output->phase[lc][0][imu];\n          }\n      }\n\n      /* albedo stuff */\n      switch (ds_in.flag.brdf_type) {\n      case BRDF_RPV:\n        ds_in.brdf.rpv->rho0  = output->rpv.rho0_r[iv];\n        ds_in.brdf.rpv->k     = output->rpv.k_r[iv];\n        ds_in.brdf.rpv->theta = output->rpv.theta_r[iv];\n        ds_in.brdf.rpv->sigma = output->rpv.sigma_r[iv];\n        ds_in.brdf.rpv->t1    = output->rpv.t1_r[iv];\n        ds_in.brdf.rpv->t2    = output->rpv.t2_r[iv];\n        ds_in.brdf.rpv->scale = output->rpv.scale_r[iv];\n        break;\n      case BRDF_CAM:\n        ds_in.brdf.cam->u10  = input.cm.param[BRDF_CAM_U10];\n        ds_in.brdf.cam->pcl  = input.cm.param[BRDF_CAM_PCL];\n        ds_in.brdf.cam->xsal = input.cm.param[BRDF_CAM_SAL];\n        break;\n      case BRDF_HAPKE:\n        ds_in.brdf.hapke->b0 = output->hapke.b0_r[iv];\n        ds_in.brdf.hapke->h  = output->hapke.h_r[iv];\n        ds_in.brdf.hapke->w  = output->hapke.w_r[iv];\n        break;\n      case BRDF_ROSSLI:\n        ds_in.brdf.rossli->iso     = output->rossli.iso_r[iv];\n        ds_in.brdf.rossli->vol     = output->rossli.vol_r[iv];\n        ds_in.brdf.rossli->geo     = output->rossli.geo_r[iv];\n        ds_in.brdf.rossli->hotspot = input.rossli.hotspot;\n        break;\n      default:\n        break;\n      }\n\n      if (input.raman && ir == 1) {\n        for (maz = 0; maz < ds_in.nstr; maz++) {\n          for (lc = 0; lc < ds_in.nlyr; lc++) {\n            for (iq = 0; iq < ds_in.nstr; iq++) {\n              ds_in.gensrc[iq + (lc + maz * ds_in.nlyr) * ds_in.nstr] = (double)rte_in->qsrc[maz][lc][iq];\n            }\n          }\n        }\n        for (maz = 0; maz < ds_in.nstr; maz++) {\n          for (lc = 0; lc < ds_in.nlyr; lc++) {\n            for (iu = 0; iu < ds_in.numu; iu++) {\n              ds_in.gensrcu[iu + (lc + maz * ds_in.nlyr) * ds_in.numu] = (double)rte_in->qsrcu[maz][lc][iu];\n            }\n          }\n        }\n      }\n\n      if (ir == 1) {\n        if (rte_in->qsrc != NULL)\n          ASCII_free_double_3D (rte_in->qsrc, input.rte.nstr, output->atm.nzout);\n        if (rte_in->qsrcu != NULL)\n          ASCII_free_double_3D (rte_in->qsrcu, input.rte.nstr, output->atm.nzout);\n      }\n\n      if (((input.source == SRC_SOLAR) && (rte_in->umu0 > 0)) /* no need to call plane-parralel cdisort, as sun below horizon */\n          || ((input.source == SRC_SOLAR) && (input.rte.pseudospherical)) /* pseudo-spherical cdisort  */\n          || (input.source == SRC_THERMAL)) {\n        c_disort (&ds_in, &ds_out);\n      }\n\n      if (rte_in->ibcnd) {\n        for (iu = 0; iu < input.rte.numu; iu++) {\n          rte_out->albmed[iu] = (float)ds_out.albmed[iu];\n          rte_out->trnmed[iu] = (float)ds_out.trnmed[iu];\n        }\n      }\n      for (lu = 0; lu < output->atm.nzout; lu++) {\n        rte_out->dfdt[lu]   = (float)ds_out.rad[lu].dfdt;\n        rte_out->rfldir[lu] = (float)ds_out.rad[lu].rfldir;\n        rte_out->rfldn[lu]  = (float)ds_out.rad[lu].rfldn;\n        rte_out->flup[lu]   = (float)ds_out.rad[lu].flup;\n        rte_out->uavg[lu]   = (float)ds_out.rad[lu].uavg;\n        rte_out->uavgdn[lu] = (float)ds_out.rad[lu].uavgdn;\n        rte_out->uavgup[lu] = (float)ds_out.rad[lu].uavgup;\n        rte_out->uavgso[lu] = (float)ds_out.rad[lu].uavgso;\n\n        for (j = 0; j < input.rte.nphi; j++)\n          for (iu = 0; iu < input.rte.numu; iu++)\n            rte_out->uu[j][lu][iu] = ds_out.uu[iu + (lu + j * ds_in.ntau) * ds_in.numu];\n\n        if (input.raman)\n          for (j = 0; j < input.rte.nstr; j++)  // j is the same as mazim in c_disort\n            for (iu = 0; iu < input.rte.numu; iu++)\n              rte_out->uum[j][lu][iu] = ds_out.uum[iu + (lu + j * ds_in.ntau) * ds_in.numu];\n\n        for (iu = 0; iu < input.rte.numu; iu++)\n          rte_out->u0u[lu][iu] = ds_out.u0u[iu + lu * ds_in.numu];\n      }\n      c_disort_out_free (&ds_in, &ds_out);\n      c_disort_state_free (&ds_in);\n    }\n\n    if (planck_tempoff) {\n      rte_in->planck = 1;\n      planck_tempoff = 0;\n    }\n\n    if (rte_solver != SOLVER_DISORT) {\n      /* convert temporary Fortran arrays to permanent result for the fortran solver, not cdisort*/\n      fortran2c_2D_float_ary_noalloc (output->atm.nzout, input.rte.maxumu, disort_u0u, rte_out->u0u);\n\n      fortran2c_3D_float_ary_noalloc (input.rte.maxphi, output->atm.nzout, input.rte.maxumu, disort_uu, rte_out->uu);\n\n      free (disort_pmom);\n      free (disort2_pmom);\n      free (disort2_phaso);\n      free (disort2_mup);\n      free (disort_u0u);\n      free (disort_uu);\n    }\n\n    break;\n\n  case SOLVER_TZS:\n\n    /* tzs_u0u  = (float *) calloc (output->atm.nzout*input.rte.maxumu, sizeof(float)); */\n    /* tzs_uu   = (float *) calloc (output->atm.nzout*input.rte.maxumu*input.rte.maxphi, sizeof(float)); */\n\n    /* ??? no need for thermal below 2um;                 ??? */\n    /* ??? need to do that to avoid numerical underflow;  ??? */\n    /* ??? however, this could be done without actually   ??? */\n    /* ??? calling the solver                             ??? */\n    if (rte_in->planck && output->wl.lambda_r[iv] < 2000.0) {\n      rte_in->planck = 0;\n      planck_tempoff = 1;\n    }\n\n    if (iv == output->wl.nlambda_rte_lower && ib == 0) {\n      status = F77_FUNC (dcheck, DCHECK) (&output->atm.nlyr,\n                                          &output->atm.nzout,\n                                          &input.rte.nstr,\n                                          &input.rte.numu,\n                                          &input.rte.nphi,\n                                          &input.optimize_fortran,\n                                          &input.optimize_delta);\n      if (status != 0) {\n        fprintf (stderr, \"Error %d returned by dcheck in %s (%s)\\n\", status, function_name, file_name);\n        return status;\n      }\n    }\n\n    /* call RTE solver */\n    /* old call to fortran tzs, now replaced by c_tzs which includes also blackbody clouds */\n    /* F77_FUNC  (tzs, TZS) (&output->atm.nlyr, output->dtauc, output->ssalb,  */\n    /* \t\t    output->atm.microphys.temper, &output->wl.wvnmlo_r[iv], */\n    /* \t\t    &output->wl.wvnmhi_r[iv], &rte_in->usrtau, &output->atm.nzout, rte_in->utau, */\n    /* \t\t    &rte_in->usrang, &input.rte.numu, input.rte.umu,  */\n    /* \t\t    &input.rte.nphi, input.rte.phi,  */\n    /* \t\t    &output->alb.albedo_r[iv], &rte_in->btemp, &rte_in->ttemp,  */\n    /* \t\t    &rte_in->temis, &rte_in->planck, */\n    /* \t\t    rte_in->prndis, rte_in->header, &output->atm.nlyr,  */\n    /* \t\t    &output->atm.nzout, &input.rte.maxumu, &input.rte.maxphi,  */\n    /* \t\t    rte_out->rfldir, rte_out->rfldn, rte_out->flup,  */\n    /* \t\t    rte_out->dfdt, rte_out->uavg,  */\n    /* \t\t    tzs_uu, rte_out->albmed, rte_out->trnmed,  */\n    /* \t\t    rte_out->uavgdn, rte_out->uavgso, rte_out->uavgup); */\n    /* call RTE solver */\n    status = c_tzs (output->atm.nlyr,\n                    output->dtauc,\n                    output->atm.nlev_common,\n                    output->atm.zd_common,\n                    output->atm.nzout,\n                    output->atm.zout_sur,\n                    output->ssalb,\n                    output->atm.microphys.temper[0][0],\n                    output->wl.wvnmlo_r[iv],\n                    output->wl.wvnmhi_r[iv],\n                    rte_in->usrtau,\n                    output->atm.nzout,\n                    rte_in->utau,\n                    rte_in->usrang,\n                    input.rte.numu,\n                    input.rte.umu,\n                    input.rte.nphi,\n                    input.rte.phi,\n                    output->alb.albedo_r[iv],\n                    rte_in->btemp,\n                    rte_in->ttemp,\n                    rte_in->temis,\n                    rte_in->planck,\n                    rte_in->prndis,\n                    rte_in->header,\n                    rte_out->rfldir,\n                    rte_out->rfldn,\n                    rte_out->flup,\n                    rte_out->dfdt,\n                    rte_out->uavg,\n                    rte_out->uu,\n                    input.quiet);\n\n    if (planck_tempoff) {\n      rte_in->planck = 1;\n      planck_tempoff = 0;\n    }\n\n    /* convert temporary Fortran arrays to permanent result */\n    /* fortran2c_2D_float_ary_noalloc (output->atm.nzout,  */\n    /* \t\t\t\t    input.rte.maxumu, tzs_u0u, rte_out->u0u); */\n\n    /* fortran2c_3D_float_ary_noalloc (input.rte.maxphi, output->atm.nzout,  */\n    /* \t\t\t\t    input.rte.maxumu, tzs_uu, rte_out->uu); */\n\n    /* free(tzs_u0u); */\n    /* free(tzs_uu); */\n\n    break;\n\n  case SOLVER_SSS:\n\n    sss_u0u = (float*)calloc (output->atm.nzout * input.rte.maxumu, sizeof (float));\n    sss_uu  = (float*)calloc (output->atm.nzout * input.rte.maxumu * input.rte.maxphi, sizeof (float));\n\n    /* ??? no need for thermal below 2um;                 ??? */\n    /* ??? need to do that to avoid numerical underflow;  ??? */\n    /* ??? however, this could be done without actually   ??? */\n    /* ??? calling the solver                             ??? */\n    if (rte_in->planck && output->wl.lambda_r[iv] < 2000.0) {\n      rte_in->planck = 0;\n      planck_tempoff = 1;\n    }\n\n    if (iv == output->wl.nlambda_rte_lower && ib == 0) {\n      status = F77_FUNC (dcheck, DCHECK) (&output->atm.nlyr,\n                                          &output->atm.nzout,\n                                          &input.rte.nstr,\n                                          &input.rte.numu,\n                                          &input.rte.nphi,\n                                          &input.optimize_fortran,\n                                          &input.optimize_delta);\n      if (status != 0) {\n        fprintf (stderr, \"Error %d returned by dcheck in %s (%s)\\n\", status, function_name, file_name);\n        return status;\n      }\n    }\n\n    /* call RTE solver */\n    sss_pmom = c2fortran_3D_float_ary (output->atm.nlyr, 1, output->atm.nmom + 1, output->pmom);\n    F77_FUNC (sss, SSS)\n    (&output->atm.nlyr,\n     output->dtauc,\n     output->ssalb,\n     &output->atm.nmom,\n     sss_pmom,\n     output->atm.microphys.temper[0][0],\n     &output->wl.wvnmlo_r[iv],\n     &output->wl.wvnmhi_r[iv],\n     &rte_in->usrtau,\n     &output->atm.nzout,\n     rte_in->utau,\n     &input.rte.nstr,\n     &rte_in->usrang,\n     &input.rte.numu,\n     input.rte.umu,\n     &input.rte.nphi,\n     input.rte.phi,\n     &rte_in->ibcnd,\n     &rte_in->fbeam,\n     &rte_in->umu0,\n     &output->atm.phi0_r[iv],\n     &rte_in->fisot,\n     &rte_in->lamber,\n     &output->alb.albedo_r[iv],\n     &rte_in->btemp,\n     &rte_in->ttemp,\n     &rte_in->temis,\n     &rte_in->planck,\n     &rte_in->onlyfl,\n     &rte_in->accur,\n     rte_in->prndis2,\n     rte_in->header,\n     &output->atm.nlyr,\n     &output->atm.nzout,\n     &input.rte.maxumu,\n     &input.rte.maxphi,\n     &output->atm.nmom,\n     rte_out->rfldir,\n     rte_out->rfldn,\n     rte_out->flup,\n     rte_out->dfdt,\n     rte_out->uavg,\n     sss_uu,\n     rte_out->albmed,\n     rte_out->trnmed,\n     rte_out->uavgdn,\n     rte_out->uavgso,\n     rte_out->uavgup,\n     &(input.disort2_brdf),\n     &(output->rpv.rho0_r[iv]),\n     &(output->rpv.k_r[iv]),\n     &(output->rpv.theta_r[iv]),\n     &(input.cm.param[BRDF_CAM_U10]),\n     &(input.cm.param[BRDF_CAM_PCL]),\n     &(input.cm.param[BRDF_CAM_SAL]));\n\n    if (planck_tempoff) {\n      rte_in->planck = 1;\n      planck_tempoff = 0;\n    }\n\n    /* convert temporary Fortran arrays to permanent result */\n    fortran2c_2D_float_ary_noalloc (output->atm.nzout, input.rte.maxumu, sss_u0u, rte_out->u0u);\n\n    fortran2c_3D_float_ary_noalloc (input.rte.maxphi, output->atm.nzout, input.rte.maxumu, sss_uu, rte_out->uu);\n\n    free (sss_pmom);\n    free (sss_u0u);\n    free (sss_uu);\n\n    break;\n\n  case SOLVER_SSSI:\n\n#if HAVE_SSSI\n\n    /* get cloud reflectivity from lookup table */\n    status = read_isccp_reflectivity (output->sssi.type,\n                                      output->atm.sza_r[iv],\n                                      output->sssi.tautot,\n                                      input.filename[FN_PATH],\n                                      input.quiet,\n                                      &(output->sssi.ref));\n    if (status != 0) {\n      fprintf (stderr, \"Error %d returned by read_isccp_reflectivity()\\n\", status);\n      return status;\n    }\n\n    if (input.verbose) {\n      fprintf (stderr, \"*** SSSI cloud properties:\\n\");\n      fprintf (stderr, \"    top level:          zd[%d] = %f\\n\", output->sssi.lctop, output->atm.zd[output->sssi.lctop]);\n      switch (output->sssi.type) {\n      case ISCCP_WATER:\n        fprintf (stderr, \"    type:               water\\n\");\n        break;\n      case ISCCP_ICE:\n        fprintf (stderr, \"    type:               ice\\n\");\n        break;\n      default:\n        fprintf (stderr, \"Error, unknown ISCCP cloud type %d\\n\", output->sssi.type);\n        return -1;\n      }\n      fprintf (stderr, \"    optical thickness:  %f\\n\", output->sssi.tautot);\n      fprintf (stderr, \"    reflectivity:       %f\\n\", output->sssi.ref);\n    }\n    fflush (stderr);\n\n    sss_u0u = (float*)calloc (output->atm.nzout * input.rte.maxumu, sizeof (float));\n    sss_uu  = (float*)calloc (output->atm.nzout * input.rte.maxumu * input.rte.maxphi, sizeof (float));\n\n    /* ??? no need for thermal below 2um;                 ??? */\n    /* ??? need to do that to avoid numerical underflow;  ??? */\n    /* ??? however, this could be done without actually   ??? */\n    /* ??? calling the solver                             ??? */\n    if (rte_in->planck && output->wl.lambda_r[iv] < 2000.0) {\n      rte_in->planck = 0;\n      planck_tempoff = 1;\n    }\n\n    if (iv == output->wl.nlambda_rte_lower && ib == 0) {\n      status = F77_FUNC (dcheck, DCHECK) (&output->atm.nlyr,\n                                          &output->atm.nzout,\n                                          &input.rte.nstr,\n                                          &input.rte.numu,\n                                          &input.rte.nphi,\n                                          &input.optimize_fortran,\n                                          &input.optimize_delta);\n      if (status != 0) {\n        fprintf (stderr, \"Error %d returned by dcheck in %s (%s)\\n\", status, function_name, file_name);\n        return status;\n      }\n    }\n\n    /* call RTE solver */\n    sss_pmom = c2fortran_3D_float_ary (output->atm.nlyr, 1, output->atm.nmom + 1, output->pmom);\n    F77_FUNC (sssi, SSSI)\n    (&output->atm.nlyr,\n     output->dtauc,\n     output->ssalb,\n     &output->atm.nmom,\n     sss_pmom,\n     output->atm.microphys.temper[0][0],\n     &output->wl.wvnmlo_r[iv],\n     &output->wl.wvnmhi_r[iv],\n     &rte_in->usrtau,\n     &output->atm.nzout,\n     rte_in->utau,\n     &input.rte.nstr,\n     &rte_in->usrang,\n     &input.rte.numu,\n     input.rte.umu,\n     &input.rte.nphi,\n     input.rte.phi,\n     &rte_in->ibcnd,\n     &rte_in->fbeam,\n     &rte_in->umu0,\n     &output->atm.phi0_r[iv],\n     &rte_in->fisot,\n     &rte_in->lamber,\n     &output->alb.albedo_r[iv],\n     &rte_in->btemp,\n     &rte_in->ttemp,\n     &rte_in->temis,\n     &rte_in->planck,\n     &rte_in->onlyfl,\n     &rte_in->accur,\n     rte_in->prndis2,\n     rte_in->header,\n     &output->atm.nlyr,\n     &output->atm.nzout,\n     &input.rte.maxumu,\n     &input.rte.maxphi,\n     &output->atm.nmom,\n     rte_out->rfldir,\n     rte_out->rfldn,\n     rte_out->flup,\n     rte_out->dfdt,\n     rte_out->uavg,\n     sss_uu,\n     rte_out->albmed,\n     rte_out->trnmed,\n     rte_out->uavgdn,\n     rte_out->uavgso,\n     rte_out->uavgup,\n     &(input.disort2_brdf),\n     &(output->rpv.rho0_r[iv]),\n     &(output->rpv.k_r[iv]),\n     &(output->rpv.theta_r[iv]),\n     &(input.cm.param[BRDF_CAM_U10]),\n     &(input.cm.param[BRDF_CAM_PCL]),\n     &(input.cm.param[BRDF_CAM_SAL]),\n     &(output->sssi.ref),\n     &(output->sssi.lctop));\n\n    if (planck_tempoff) {\n      rte_in->planck = 1;\n      planck_tempoff = 0;\n    }\n\n    /* convert temporary Fortran arrays to permanent result */\n    fortran2c_2D_float_ary_noalloc (output->atm.nzout, input.rte.maxumu, sss_u0u, rte_out->u0u);\n\n    fortran2c_3D_float_ary_noalloc (input.rte.maxphi, output->atm.nzout, input.rte.maxumu, sss_uu, rte_out->uu);\n\n    free (sss_pmom);\n    free (sss_u0u);\n    free (sss_uu);\n#else\n    fprintf (stderr, \"Error, SSSI solver not available!\\n\");\n    return -1;\n#endif\n\n    break;\n\n  case SOLVER_POLRADTRAN:\n#if HAVE_POLRADTRAN\n    rte_in->pol.nummu      = input.rte.nstr / 2 + input.rte.numu;\n    rte_in->pol.albedo     = (double)output->alb.albedo_r[iv];\n    rte_in->pol.btemp      = (double)(rte_in->btemp);\n    rte_in->pol.flux       = (double)(rte_in->fbeam * rte_in->umu0); /* Polradtran wants flux \n                                                                     on horizontal surface */\n    rte_in->pol.mu         = (double)(rte_in->umu0);\n    rte_in->pol.sky_temp   = (double)(rte_in->ttemp);\n    rte_in->pol.wavelength = 0.0; /* Not used for solar source */\n    for (lu = 0; lu < output->atm.nlyr; lu++) {\n      /*\n      rte_in->pol.gas_extinct[lu] = (double)  output->atm.optprop.tau_molabs_r[lu][iv][0]; \n      fprintf(stderr, \"test 1-ssa %g tauc %g molabs %g \\n \", 1.0-output->ssalb[lu],output->atm.optprop.tau_rayleigh_r[lu][iv][0], output->atm.optprop.tau_molabs_r[lu][iv][0] );\n      */\n      /* ????? CE: Something wrong here?? If not set to zero, results for radiances are totally wrong */\n      rte_in->pol.gas_extinct[lu] = 0.0;\n    }\n\n    polradtran_down_flux = (double*)calloc (output->atm.nzout * input.rte.polradtran[POLRADTRAN_NSTOKES], sizeof (double));\n    polradtran_up_flux   = (double*)calloc (output->atm.nzout * input.rte.polradtran[POLRADTRAN_NSTOKES], sizeof (double));\n    polradtran_down_rad  = (double*)calloc (output->atm.nzout * (input.rte.polradtran[POLRADTRAN_AZIORDER] + 1) *\n                                             (input.rte.nstr / 2 + input.rte.numu) * input.rte.polradtran[POLRADTRAN_NSTOKES],\n                                           sizeof (double));\n    polradtran_up_rad    = (double*)calloc (output->atm.nzout * (input.rte.polradtran[POLRADTRAN_AZIORDER] + 1) *\n                                           (input.rte.nstr / 2 + input.rte.numu) * input.rte.polradtran[POLRADTRAN_NSTOKES],\n                                         sizeof (double));\n    for (iu = 0; iu < rte_in->pol.nummu; iu++)\n      rte_out->polradtran_mu_values[iu] = (double)fabs (output->mu_values[iu]);\n    /* Take fabs since radtran will calculate both up_rad and down_rad for the value of mu.  */\n    /* The user wants one of these. That is sorted out in the output section of uvspec_lex.l */\n\n    F77_FUNC (radtran, RADTRAN)\n    (&input.rte.polradtran[POLRADTRAN_NSTOKES],\n     &(rte_in->pol.nummu),\n     &input.rte.polradtran[POLRADTRAN_AZIORDER],\n     &input.rte.pol_max_delta_tau,\n     &input.rte.polradtran[POLRADTRAN_SRC_CODE],\n     input.rte.pol_quad_type,\n     rte_in->pol.deltam,\n     &(rte_in->pol.flux),\n     &(rte_in->pol.mu),\n     &(rte_in->pol.btemp),\n     (rte_in->pol.ground_type),\n     &(rte_in->pol.albedo),\n     &(rte_in->pol.ground_index),\n     &(rte_in->pol.sky_temp),\n     &(rte_in->pol.wavelength),\n     &output->atm.nlyr,\n     (rte_in->pol.height),\n     (rte_in->pol.temperatures),\n     (rte_in->pol.gas_extinct),\n     output->atm.pol_scat_files,\n     &output->atm.nzout,\n     (rte_in->pol.outlevels),\n     rte_out->polradtran_mu_values,\n     polradtran_up_flux,\n     polradtran_down_flux,\n     polradtran_up_rad,\n     polradtran_down_rad);\n\n    fortran2c_2D_double_ary_noalloc (output->atm.nzout,\n                                     input.rte.polradtran[POLRADTRAN_NSTOKES],\n                                     polradtran_up_flux,\n                                     rte_out->polradtran_up_flux);\n\n    fortran2c_2D_double_ary_noalloc (output->atm.nzout,\n                                     input.rte.polradtran[POLRADTRAN_NSTOKES],\n                                     polradtran_down_flux,\n                                     rte_out->polradtran_down_flux);\n\n    if (input.rte.polradtran[POLRADTRAN_AZIORDER] > 0) {\n      fortran2c_4D_double_ary_noalloc (output->atm.nzout,\n                                       input.rte.polradtran[POLRADTRAN_AZIORDER] + 1,\n                                       input.rte.nstr / 2 + input.rte.numu,\n                                       input.rte.polradtran[POLRADTRAN_NSTOKES],\n                                       polradtran_down_rad,\n                                       rte_out->polradtran_down_rad_q);\n\n      fortran2c_4D_double_ary_noalloc (output->atm.nzout,\n                                       input.rte.polradtran[POLRADTRAN_AZIORDER] + 1,\n                                       input.rte.nstr / 2 + input.rte.numu,\n                                       input.rte.polradtran[POLRADTRAN_NSTOKES],\n                                       polradtran_up_rad,\n                                       rte_out->polradtran_up_rad_q);\n\n      fourier2azimuth (rte_out->polradtran_down_rad_q,\n                       rte_out->polradtran_up_rad_q,\n                       rte_out->polradtran_down_rad,\n                       rte_out->polradtran_up_rad,\n                       output->atm.nzout,\n                       input.rte.polradtran[POLRADTRAN_AZIORDER],\n                       input.rte.nstr,\n                       input.rte.numu,\n                       input.rte.polradtran[POLRADTRAN_NSTOKES],\n                       input.rte.nphi,\n                       input.rte.phi);\n    }\n\n    free (polradtran_down_flux);\n    free (polradtran_up_flux);\n\n    free (polradtran_down_rad);\n    free (polradtran_up_rad);\n\n#else\n    fprintf (stderr, \"Error: RTE polradtran solver not included in uvspec build.\\n\");\n    fprintf (stderr, \"Error: Get solver and rebuild uvspec.\\n\");\n    return -1;\n#endif\n    break;\n\n  case SOLVER_SDISORT:\n\n    if (iv == output->wl.nlambda_rte_lower && ib == 0) {\n      status = F77_FUNC (dcheck, DCHECK) (&output->atm.nlyr,\n                                          &output->atm.nzout,\n                                          &input.rte.nstr,\n                                          &input.rte.numu,\n                                          &input.rte.nphi,\n                                          &input.optimize_fortran,\n                                          &input.optimize_delta);\n      if (status != 0) {\n        fprintf (stderr, \"Error %d returned by dcheck in %s (%s)\\n\", status, function_name, file_name);\n        return status;\n      }\n    }\n\n    sdisort_beta = (float*)calloc (output->atm.nlyr + 1, sizeof (float));\n    disort_pmom  = c2fortran_3D_float_ary (output->atm.nlyr, 1, input.rte.nstr + 1, output->pmom);\n    disort_u0u   = (float*)calloc (output->atm.nzout * input.rte.maxumu, sizeof (float));\n    disort_uu    = (float*)calloc (output->atm.nzout * input.rte.maxumu * input.rte.maxphi, sizeof (float));\n    sdisort_sig  = (float*)calloc (output->atm.nlyr + 1, sizeof (float));\n    if ((status = ASCII_calloc_float (&sdisort_denstab, output->atm.microphys.nsza_denstab, output->atm.nlyr + 1)) != 0)\n      return status;\n    if (output->atm.microphys.denstab_id > 0) {\n      for (lu = 0; lu <= output->atm.nlyr; lu++) {\n        sdisort_sig[lu] = output->crs.crs_amf[iv][lu];\n        for (is = 0; is < output->atm.microphys.nsza_denstab; is++)\n          sdisort_denstab[is][lu] = output->atm.microphys.denstab_amf[is][lu];\n      }\n\n      tosdisort_denstab = c2fortran_2D_float_ary (output->atm.microphys.nsza_denstab, output->atm.nlyr + 1, sdisort_denstab);\n      if (sdisort_denstab != NULL)\n        ASCII_free_float (sdisort_denstab, output->atm.microphys.nsza_denstab);\n    }\n\n    /* Definition of refind in (refractive index - 1), function SOLVER_SDISORT takes refractive index */\n    for (lu = 0; lu <= output->atm.nlyr; lu++)\n      output->atm.microphys.refind[iv][lu] += 1.;\n\n    F77_FUNC (sdisort, SDISORT)\n    (&output->atm.nlyr,\n     output->dtauc,\n     output->ssalb,\n     disort_pmom,\n     output->atm.microphys.temper[0][0],\n     &(output->wl.wvnmlo_r[iv]),\n     &(output->wl.wvnmhi_r[iv]),\n     &(rte_in->usrtau),\n     &output->atm.nzout,\n     rte_in->utau,\n     &input.rte.nstr,\n     &(rte_in->usrang),\n     &input.rte.numu,\n     input.rte.umu,\n     &input.rte.nphi,\n     input.rte.phi,\n     &(rte_in->fbeam),\n     sdisort_beta,\n     &(rte_in->nil),\n     &(rte_in->umu0),\n     &output->atm.phi0_r[iv],\n     &(rte_in->newgeo),\n     output->atm.zd,\n     &(rte_in->spher),\n     &input.r_earth,\n     &(rte_in->fisot),\n     &output->alb.albedo_r[iv],\n     &(rte_in->btemp),\n     &(rte_in->ttemp),\n     &(rte_in->temis),\n     &input.rte.deltam,\n     &(rte_in->planck),\n     &(rte_in->onlyfl),\n     &(rte_in->accur),\n     &(rte_in->quiet),\n     rte_in->ierror_s,\n     rte_in->prndis,\n     rte_in->header,\n     &output->atm.nlyr,\n     &output->atm.nzout,\n     &input.rte.maxumu,\n     &input.rte.nstr,\n     &input.rte.maxphi,\n     rte_out->rfldir,\n     rte_out->rfldn,\n     rte_out->flup,\n     rte_out->dfdt,\n     rte_out->uavg,\n     disort_uu,\n     disort_u0u,\n     &input.rte.sdisort[SDISORT_NSCAT],\n     rte_out->uavgdn,\n     rte_out->uavgso,\n     rte_out->uavgup,\n     &input.rte.sdisort[SDISORT_NREFRAC],\n     &input.rte.sdisort[SDISORT_ICHAPMAN],\n     output->atm.microphys.refind[iv],\n     &output->atm.microphys.nsza_denstab,\n     output->atm.microphys.sza_denstab,\n     sdisort_sig,\n     tosdisort_denstab,\n     output->dtauc_md);\n\n    /* convert temporary Fortran arrays to permanent result */\n\n    fortran2c_2D_float_ary_noalloc (output->atm.nzout, input.rte.maxumu, disort_u0u, rte_out->u0u);\n\n    fortran2c_3D_float_ary_noalloc (input.rte.maxphi, output->atm.nzout, input.rte.maxumu, disort_uu, rte_out->uu);\n\n    free (sdisort_beta);\n    free (disort_pmom);\n    free (disort_u0u);\n    free (disort_uu);\n\n    break;\n  case SOLVER_SPSDISORT:\n\n    if (iv == output->wl.nlambda_rte_lower && ib == 0) {\n      status = F77_FUNC (dcheck, DCHECK) (&output->atm.nlyr,\n                                          &output->atm.nzout,\n                                          &input.rte.nstr,\n                                          &input.rte.numu,\n                                          &input.rte.nphi,\n                                          &input.optimize_fortran,\n                                          &input.optimize_delta);\n      if (status != 0) {\n        fprintf (stderr, \"Error %d returned by dcheck in %s (%s)\\n\", status, function_name, file_name);\n        return status;\n      }\n    }\n\n    sdisort_beta = (float*)calloc (output->atm.nlyr + 1, sizeof (float));\n    disort_pmom  = c2fortran_3D_float_ary (output->atm.nlyr, 1, input.rte.nstr + 1, output->pmom);\n    disort_u0u   = (float*)calloc (output->atm.nzout * input.rte.maxumu, sizeof (float));\n    disort_uu    = (float*)calloc (output->atm.nzout * input.rte.maxumu * input.rte.maxphi, sizeof (float));\n\n    F77_FUNC (spsdisort, SPSDISORT)\n    (&output->atm.nlyr,\n     output->dtauc,\n     output->ssalb,\n     disort_pmom,\n     output->atm.microphys.temper[0][0],\n     &(output->wl.wvnmlo_r[iv]),\n     &(output->wl.wvnmhi_r[iv]),\n     &(rte_in->usrtau),\n     &output->atm.nzout,\n     rte_in->utau,\n     &input.rte.nstr,\n     &(rte_in->usrang),\n     &input.rte.numu,\n     input.rte.umu,\n     &input.rte.nphi,\n     input.rte.phi,\n     &(rte_in->fbeam),\n     sdisort_beta,\n     &(rte_in->nil),\n     &(rte_in->umu0),\n     &output->atm.phi0_r[iv],\n     &(rte_in->newgeo),\n     output->atm.zd,\n     &(rte_in->spher),\n     &input.r_earth,\n     &(rte_in->fisot),\n     &output->alb.albedo_r[iv],\n     &(rte_in->btemp),\n     &(rte_in->ttemp),\n     &(rte_in->temis),\n     &input.rte.deltam,\n     &(rte_in->planck),\n     &(rte_in->onlyfl),\n     &(rte_in->accur),\n     &(rte_in->quiet),\n     rte_in->ierror_s,\n     rte_in->prndis,\n     rte_in->header,\n     &output->atm.nlyr,\n     &output->atm.nzout,\n     &input.rte.maxumu,\n     &input.rte.nstr,\n     &input.rte.maxphi,\n     rte_out->rfldir,\n     rte_out->rfldn,\n     rte_out->flup,\n     rte_out->dfdt,\n     rte_out->uavg,\n     disort_uu,\n     disort_u0u,\n     rte_out->uavgdn,\n     rte_out->uavgso,\n     rte_out->uavgup);\n\n    /* convert temporary Fortran arrays to permanent result */\n\n    fortran2c_2D_float_ary_noalloc (output->atm.nzout, input.rte.maxumu, disort_u0u, rte_out->u0u);\n\n    fortran2c_3D_float_ary_noalloc (input.rte.maxphi, output->atm.nzout, input.rte.maxumu, disort_uu, rte_out->uu);\n\n    free (sdisort_beta);\n    free (disort_pmom);\n    free (disort_u0u);\n    free (disort_uu);\n\n    break;\n  case SOLVER_FTWOSTR:\n\n    if (iv == output->wl.nlambda_rte_lower && ib == 0) {\n      status = F77_FUNC (tcheck, TCHECK) (&output->atm.nlyr,\n                                          &output->atm.nzout,\n                                          &input.rte.nstr,\n                                          &input.rte.numu,\n                                          &input.rte.nphi,\n                                          &input.optimize_fortran,\n                                          &input.optimize_delta);\n      if (status != 0)\n        return status;\n    }\n\n    twostr_gg = (float*)calloc (output->atm.nlyr, sizeof (float));\n    for (lu = 0; lu < output->atm.nlyr; lu++)\n      twostr_gg[lu] = output->pmom[lu][0][1];\n\n    /* ??? no need for thermal below 2um;                 ??? */\n    /* ??? need to do that to avoid numerical underflow;  ??? */\n    /* ??? however, this could be done without actually   ??? */\n    /* ??? calling the solver                             ??? */\n    if (rte_in->planck && output->wl.lambda_r[iv] < 2000.0) {\n      rte_in->planck = 0;\n      planck_tempoff = 1;\n    }\n\n    F77_FUNC (twostr, TWOSTR)\n    (&output->alb.albedo_r[iv],\n     &(rte_in->btemp),\n     &input.rte.deltam,\n     output->dtauc,\n     &(rte_in->fbeam),\n     &(rte_in->fisot),\n     twostr_gg,\n     rte_in->header,\n     rte_in->ierror_t,\n     &output->atm.nlyr,\n     &output->atm.nzout,\n     &(rte_in->newgeo),\n     &output->atm.nlyr,\n     &(rte_in->planck),\n     &output->atm.nzout,\n     rte_in->prntwo,\n     &(rte_in->quiet),\n     &input.r_earth,\n     &(rte_in->spher),\n     output->ssalb,\n     &(rte_in->temis),\n     output->atm.microphys.temper[0][0],\n     &(rte_in->ttemp),\n     &(rte_in->umu0),\n     &(rte_in->usrtau),\n     rte_in->utau,\n     &(output->wl.wvnmlo_r[iv]),\n     &(output->wl.wvnmhi_r[iv]),\n     output->atm.zd,\n     rte_out->dfdt,\n     rte_out->flup,\n     rte_out->rfldir,\n     rte_out->rfldn,\n     rte_out->uavg);\n    free (twostr_gg);\n\n    for (lev = 0; lev < output->atm.nzout; lev++) {\n      rte_out->uavgso[lev] = NAN;\n      rte_out->uavgdn[lev] = NAN;\n      rte_out->uavgup[lev] = NAN;\n    }\n\n    if (planck_tempoff) {\n      rte_in->planck = 1;\n      planck_tempoff = 0;\n    }\n\n    break;\n\n  case SOLVER_TWOSTR:\n\n    twostr_ds.nlyr        = output->atm.nlyr;\n    twostr_ds.ntau        = output->atm.nzout;\n    twostr_ds.flag.planck = rte_in->planck;\n    twostr_ds.flag.quiet  = rte_in->quiet;\n    twostr_ds.flag.spher  = rte_in->spher;\n    /* twostr_ds.flag.spher = input.rte.pseudospherical; */\n    twostr_ds.flag.usrtau = rte_in->usrtau;\n    c_twostr_state_alloc (&twostr_ds);\n    c_twostr_out_alloc (&twostr_ds, &twostr_out);\n\n    c_twostr_gg = (double*)calloc (output->atm.nlyr, sizeof (double));\n    for (lu = 0; lu < output->atm.nlyr; lu++) {\n      c_twostr_gg[lu]     = (double)output->pmom[lu][0][1];\n      twostr_ds.dtauc[lu] = (double)output->dtauc[lu];\n      twostr_ds.ssalb[lu] = (double)output->ssalb[lu];\n    }\n    for (lu = 0; lu < output->atm.nzout; lu++) {\n      twostr_ds.utau[lu] = (double)rte_in->utau[lu];\n    }\n    for (lu = 0; lu <= output->atm.nlyr; lu++) {\n      twostr_ds.zd[lu] = (double)output->atm.zd[lu];\n      if (rte_in->planck)\n        twostr_ds.temper[lu] = (double)output->atm.microphys.temper[0][0][lu];\n    }\n    twostr_ds.bc.albedo    = (double)output->alb.albedo_r[iv];\n    twostr_ds.bc.btemp     = (double)rte_in->btemp;\n    twostr_ds.bc.fbeam     = (double)rte_in->fbeam;\n    twostr_ds.bc.fisot     = (double)rte_in->fisot;\n    twostr_ds.bc.temis     = (double)rte_in->temis;\n    twostr_ds.bc.ttemp     = (double)rte_in->ttemp;\n    twostr_ds.bc.umu0      = (double)rte_in->umu0;\n    twostr_ds.flag.prnt[0] = rte_in->prntwo[0];\n    twostr_ds.flag.prnt[1] = rte_in->prntwo[1];\n    twostr_ds.wvnmlo       = output->wl.wvnmlo_r[iv];\n    twostr_ds.wvnmhi       = output->wl.wvnmhi_r[iv];\n\n    /* ??? no need for thermal below 2um;                 ??? */\n    /* ??? need to do that to avoid numerical underflow;  ??? */\n    /* ??? however, this could be done without actually   ??? */\n    /* ??? calling the solver                             ??? */\n    if (rte_in->planck && output->wl.lambda_r[iv] < 2000.0) {\n      rte_in->planck = 0;\n      planck_tempoff = 1;\n    }\n\n    c_twostr (&twostr_ds, &twostr_out, input.rte.deltam, c_twostr_gg, rte_in->ierror_t, c_r_earth);\n\n    for (lu = 0; lu < output->atm.nzout; lu++) {\n      rte_out->dfdt[lu]   = (float)twostr_out.rad[lu].dfdt;\n      rte_out->rfldir[lu] = (float)twostr_out.rad[lu].rfldir;\n      rte_out->rfldn[lu]  = (float)twostr_out.rad[lu].rfldn;\n      rte_out->flup[lu]   = (float)twostr_out.rad[lu].flup;\n      rte_out->uavg[lu]   = (float)twostr_out.rad[lu].uavg;\n    }\n\n    free (c_twostr_gg);\n    free (c_zd);\n    c_twostr_state_free (&twostr_ds);\n    c_twostr_out_free (&twostr_ds, &twostr_out);\n\n    for (lev = 0; lev < output->atm.nzout; lev++) {\n      rte_out->uavgso[lev] = NAN;\n      rte_out->uavgdn[lev] = NAN;\n      rte_out->uavgup[lev] = NAN;\n    }\n\n    if (planck_tempoff) {\n      rte_in->planck = 1;\n      planck_tempoff = 0;\n    }\n\n    break;\n\n  case SOLVER_RODENTS: /* ulrike, Robert Buras' two-stream model */\n\n    if (input.tipa == TIPA_DIR) /* BCA this should be somewhere else */\n      /* for tipa_dir, delta-scaling is not yet implemented!!! */\n      rodents_delta_method = RODENTS_DELTA_METHOD_OFF;\n    else\n      /* test showed that f=g*g is better than f=p2; master thesis to improve this! */\n      rodents_delta_method = RODENTS_DELTA_METHOD_HG;\n\n    twostr_gg = (float*)calloc (output->atm.nlyr, sizeof (float));\n    for (lu = 0; lu < output->atm.nlyr; lu++)\n      twostr_gg[lu] = output->pmom[lu][0][1];\n    twostr_ff = (float*)calloc (output->atm.nlyr, sizeof (float));\n    if (rodents_delta_method ==\n        RODENTS_DELTA_METHOD_ON) /* use second moment for delta-scaling */ /* BCA this should be somewhere else */\n      for (lu = 0; lu < output->atm.nlyr; lu++)\n        twostr_ff[lu] = output->pmom[lu][0][2];\n    else /* f is set to zero, and evtl set to g*g internally */\n      for (lu = 0; lu < output->atm.nlyr; lu++)\n        twostr_ff[lu] = 0.0;\n\n    /* ??? no need for thermal below 2um;                 ??? */\n    /* ??? need to do that to avoid numerical underflow;  ??? */\n    /* ??? however, this could be done without actually   ??? */\n    /* ??? calling the solver                             ??? */\n\n    if (rte_in->planck && output->wl.lambda_r[iv] < 2000.0) {\n      rte_in->planck = 0;\n      planck_tempoff = 1;\n    }\n\n    status = rodents (/* INPUT */\n                      output->atm.nlyr,\n                      output->dtauc,\n                      output->ssalb,\n                      twostr_gg,\n                      twostr_ff,\n                      rodents_delta_method,\n                      output->atm.microphys.temper[0][0],\n                      output->wl.wvnmlo_r[iv],\n                      output->wl.wvnmhi_r[iv],\n                      rte_in->usrtau,\n                      output->atm.nzout,\n                      rte_in->utau,\n                      rte_in->fbeam,\n                      rte_in->umu0,\n                      output->alb.albedo_r[iv],\n                      rte_in->btemp,\n                      rte_in->planck,\n                      /* NECESSARY FOR TIPA DIR */\n                      input.tipa, /* if ==2, then tipa dir */\n                      output->tausol,\n                      /* OUTPUT */\n                      rte_out->rfldn,  /* e_minus */\n                      rte_out->flup,   /* e_plus */\n                      rte_out->rfldir, /* s_direct */\n                      rte_out->uavg);  /* KST ???? */\n\n    if (status != 0) {\n      fprintf (stderr, \"Error %d returned by rodents()\\n\", status);\n      return status;\n    }\n\n    free (twostr_gg);\n    free (twostr_ff);\n\n    for (lev = 0; lev < output->atm.nzout; lev++) {\n      rte_out->uavgso[lev] = NAN;\n      rte_out->uavgdn[lev] = NAN;\n      rte_out->uavgup[lev] = NAN;\n    }\n\n    if (planck_tempoff) {\n      rte_in->planck = 1;\n      planck_tempoff = 0;\n    }\n    break; /* END of rodents */\n\n  case SOLVER_TWOSTREBE: /* ulrike 22.06.2010, Bernhard Mayers twostream*/\n\n    twostr_gg = (float*)calloc (output->atm.nlyr, sizeof (float));\n    for (lu = 0; lu < output->atm.nlyr; lu++)\n      twostr_gg[lu] = output->pmom[lu][0][1];\n\n    /* ??? no need for thermal below 2um;                 ??? */\n    /* ??? need to do that to avoid numerical underflow;  ??? */\n    /* ??? however, this could be done without actually   ??? */\n    /* ??? calling the solver                             ??? */\n    if (rte_in->planck && output->wl.lambda_r[iv] < 2000.0) {\n      rte_in->planck = 0;\n      planck_tempoff = 1;\n    }\n\n    status = twostrebe (output->dtauc,            /* dtau (rodents) = dtau_org (twostrebe) */\n                        output->ssalb,            /* omega_0 */\n                        twostr_gg,                /* g (rodents) = g_org (twostrebe) */\n                        output->atm.nlyr + 1,     /* nlev */\n                        rte_in->fbeam,            /* S_0 */\n                        rte_in->umu0,             /* mu_0 */\n                        output->alb.albedo_r[iv], /* surface albedo */\n                        rte_in->planck,           /* whether to use planck */\n                        input.rte.deltam,         /* delta scaling */\n                        output->atm.nzout,        /* nzout */\n                        output->atm.zd,           /* z-levels */\n                        output->atm.microphys.temper[0][0],\n                        rte_in->btemp, /* surface temperature */\n                        output->wl.wvnmlo_r[iv],\n                        output->wl.wvnmhi_r[iv],\n                        input.atm.zout_sur, /* zout's (in km) */\n                        /* output */\n                        rte_out->rfldn,  /* e_minus */\n                        rte_out->flup,   /* e_plus */\n                        rte_out->rfldir, /* s_direct */\n                        rte_out->uavg);  /* KST ???? */\n\n    if (status != 0) {\n      fprintf (stderr, \"Error %d returned by twostrebe()\\n\", status);\n      return status;\n    }\n\n    free (twostr_gg);\n\n    for (lev = 0; lev < output->atm.nzout; lev++) {\n      rte_out->uavgso[lev] = NAN;\n      rte_out->uavgdn[lev] = NAN;\n      rte_out->uavgup[lev] = NAN;\n    }\n\n    if (planck_tempoff) {\n      rte_in->planck = 1;\n      planck_tempoff = 0;\n    }\n\n    break; /* END twostrebe */\n\n  case SOLVER_TWOMAXRND: /* Bernhard Mayer, 7.7.2016, Nina Crnivec twostream with Maximum Random Overlap */\n\n    twostr_gg     = (float*)calloc (output->atm.nlyr, sizeof (float));\n    twostr_gg_clr = (float*)calloc (output->atm.nlyr, sizeof (float));\n    for (lu = 0; lu < output->atm.nlyr; lu++) {\n      twostr_gg[lu]     = output->pmom[lu][0][1];\n      twostr_gg_clr[lu] = output->pmom01_clr[lu];\n    }\n\n    /* ??? no need for thermal below 2um;                 ??? */\n    /* ??? need to do that to avoid numerical underflow;  ??? */\n    /* ??? however, this could be done without actually   ??? */\n    /* ??? calling the solver                             ??? */\n    if (rte_in->planck && output->wl.lambda_r[iv] < 2000.0) {\n      rte_in->planck = 0;\n      planck_tempoff = 1;\n    }\n\n    twostr_cf = calloc (output->atm.nlyr, sizeof (float));\n\n    if (output->cf.nlev != 0) {\n\n      if (output->atm.nlyr != output->cf.nlev) {\n        fprintf (stderr,\n                 \"Fatal error! Cloud fraction grid different from atmospheric grid. %d levels vs. %d levels\\n\",\n                 output->cf.nlev + 1,\n                 output->atm.nlyr + 1);\n        return -1;\n      } else {\n        for (lu = 0; lu < output->atm.nlyr; lu++)\n          twostr_cf[lu] = output->cf.cf[lu];\n      }\n    }\n\n    status = twomaxrnd (output->dtauc,            /* dtau (rodents) = dtau_org (twostrebe) */\n                        output->ssalb,            /* omega_0 */\n                        twostr_gg,                /* g (rodents) = g_org (twostrebe) */\n                        output->dtauc_clr,        /* dtau (rodents) = dtau_org (twostrebe) */\n                        output->ssalb_clr,        /* omega_0 */\n                        twostr_gg_clr,            /* g (rodents) = g_org (twostrebe) */\n                        twostr_cf,                /* cloud fraction */\n                        output->atm.nlyr + 1,     /* nlev */\n                        rte_in->fbeam,            /* S_0 */\n                        rte_in->umu0,             /* mu_0 */\n                        output->alb.albedo_r[iv], /* surface albedo */\n                        rte_in->planck,           /* whether to use planck */\n                        input.rte.deltam,         /* delta scaling */\n                        output->atm.nzout,        /* nzout */\n                        output->atm.zd,           /* z-levels */\n                        output->atm.microphys.temper[0][0],\n                        rte_in->btemp, /* surface temperature */\n                        output->wl.wvnmlo_r[iv],\n                        output->wl.wvnmhi_r[iv],\n                        input.atm.zout_sur, /* zout's (in km) */\n                        /* output */\n                        rte_out->rfldn,  /* e_minus */\n                        rte_out->flup,   /* e_plus */\n                        rte_out->rfldir, /* s_direct */\n                        rte_out->uavg);  /* KST ???? */\n\n    if (status != 0) {\n      fprintf (stderr, \"Error %d returned by twomaxrnd()\\n\", status);\n      return status;\n    }\n\n    free (twostr_gg);\n    free (twostr_gg_clr);\n    free (twostr_cf);\n\n    for (lev = 0; lev < output->atm.nzout; lev++) {\n      rte_out->uavgso[lev] = NAN;\n      rte_out->uavgdn[lev] = NAN;\n      rte_out->uavgup[lev] = NAN;\n    }\n\n    if (planck_tempoff) {\n      rte_in->planck = 1;\n      planck_tempoff = 0;\n    }\n\n    break; /* END twomaxrnd */\n\n  case SOLVER_DYNAMIC_TWOSTREAM: /* Bernhard Mayer, 23.7.2020, Richard Maier, dynamic twostream */\n\n    twostr_gg     = (float*)calloc (output->atm.nlyr, sizeof (float));\n    twostr_gg_clr = (float*)calloc (output->atm.nlyr, sizeof (float));\n    for (lu = 0; lu < output->atm.nlyr; lu++) {\n      twostr_gg[lu]     = output->pmom[lu][0][1];\n      twostr_gg_clr[lu] = output->pmom01_clr[lu];\n    }\n\n    /* ??? no need for thermal below 2um;                 ??? */\n    /* ??? need to do that to avoid numerical underflow;  ??? */\n    /* ??? however, this could be done without actually   ??? */\n    /* ??? calling the solver                             ??? */\n    if (rte_in->planck && output->wl.lambda_r[iv] < 2000.0) {\n      rte_in->planck = 0;\n      planck_tempoff = 1;\n    }\n\n    twostr_cf = calloc (output->atm.nlyr, sizeof (float));\n\n    if (output->cf.nlev != 0) {\n\n      if (output->atm.nlyr != output->cf.nlev) {\n        fprintf (stderr,\n                 \"Fatal error! Cloud fraction grid different from atmospheric grid. %d levels vs. %d levels\\n\",\n                 output->cf.nlev,\n                 output->atm.nlyr + 1);\n        return -1;\n      } else {\n        for (lu = 0; lu < output->atm.nlyr; lu++)\n          twostr_cf[lu] = output->cf.cf[lu];\n      }\n    }\n\n    status = dynamic_twostream (input.rte.dynamic_iterations, /* number of iterations */\n                                output->dtauc,                /* dtau (rodents) = dtau_org (twostrebe) */\n                                output->ssalb,                /* omega_0 */\n                                twostr_gg,                    /* g (rodents) = g_org (twostrebe) */\n                                output->dtauc_clr,            /* dtau (rodents) = dtau_org (twostrebe) */\n                                output->ssalb_clr,            /* omega_0 */\n                                twostr_gg_clr,                /* g (rodents) = g_org (twostrebe) */\n                                twostr_cf,                    /* cloud fraction */\n                                output->atm.nlyr + 1,         /* nlev */\n                                rte_in->fbeam,                /* S_0 */\n                                rte_in->umu0,                 /* mu_0 */\n                                output->alb.albedo_r[iv],     /* surface albedo */\n                                rte_in->planck,               /* whether to use planck */\n                                input.rte.deltam,             /* delta scaling */\n                                output->atm.nzout,            /* nzout */\n                                output->atm.zd,               /* z-levels */\n                                output->atm.microphys.temper[0][0],\n                                rte_in->btemp, /* surface temperature */\n                                output->wl.wvnmlo_r[iv],\n                                output->wl.wvnmhi_r[iv],\n                                input.atm.zout_sur, /* zout's (in km) */\n                                /* output */\n                                rte_out->rfldn,  /* e_minus */\n                                rte_out->flup,   /* e_plus */\n                                rte_out->rfldir, /* s_direct */\n                                rte_out->uavg);  /* KST ???? */\n\n    if (status != 0) {\n      fprintf (stderr, \"Error %d returned by dynamic_twostream()\\n\", status);\n      return status;\n    }\n\n    free (twostr_gg);\n    free (twostr_gg_clr);\n    free (twostr_cf);\n\n    for (lev = 0; lev < output->atm.nzout; lev++) {\n      rte_out->uavgso[lev] = NAN;\n      rte_out->uavgdn[lev] = NAN;\n      rte_out->uavgup[lev] = NAN;\n    }\n\n    if (planck_tempoff) {\n      rte_in->planck = 1;\n      planck_tempoff = 0;\n    }\n\n    break; /* END dynamic_twostream */\n\n  case SOLVER_DYNAMIC_TENSTREAM: /* Bernhard Mayer, 6.12.2020, Richard Maier, dynamic tenstream */\n\n    twostr_gg_clr = (float*)calloc (output->atm.nlyr, sizeof (float));\n    for (lu = 0; lu < output->atm.nlyr; lu++)\n      twostr_gg_clr[lu] = output->pmom01_clr[lu];\n\n    /* ??? no need for thermal below 2um;                 ??? */\n    /* ??? need to do that to avoid numerical underflow;  ??? */\n    /* ??? however, this could be done without actually   ??? */\n    /* ??? calling the solver                             ??? */\n    if (rte_in->planck && output->wl.lambda_r[iv] < 2000.0) {\n      rte_in->planck = 0;\n      planck_tempoff = 1;\n    }\n\n    status = dynamic_tenstream (input.rte.dynamic_iterations, /* number of iterations */\n                                output->caoth3d,\n                                input.n_caoth + 2,\n                                output->dtauc_clr,        /* dtau (rodents) = dtau_org (twostrebe) */\n                                output->ssalb_clr,        /* omega_0 */\n                                twostr_gg_clr,            /* g (rodents) = g_org (twostrebe) */\n                                output->atm.nlyr + 1,     /* nlev */\n                                rte_in->fbeam,            /* S_0 */\n                                rte_in->umu0,             /* mu_0 */\n                                output->alb.albedo_r[iv], /* surface albedo */\n                                rte_in->planck,           /* whether to use planck */\n                                input.rte.deltam,         /* delta scaling */\n                                output->atm.nzout,        /* nzout */\n                                output->atm.zd,           /* z-levels */\n                                output->atm.microphys.temper[0][0],\n                                rte_in->btemp, /* surface temperature */\n                                output->wl.wvnmlo_r[iv],\n                                output->wl.wvnmhi_r[iv],\n                                input.atm.zout_sur, /* zout's (in km) */\n                                /* output */\n                                rte_out->rfldn,  /* e_minus */\n                                rte_out->flup,   /* e_plus */\n                                rte_out->rfldir, /* s_direct */\n                                rte_out->uavg);  /* KST ???? */\n\n    if (status != 0) {\n      fprintf (stderr, \"Error %d returned by dynamic_tenstream()\\n\", status);\n      return status;\n    }\n\n    free (twostr_gg);\n\n    for (lev = 0; lev < output->atm.nzout; lev++) {\n      rte_out->uavgso[lev] = NAN;\n      rte_out->uavgdn[lev] = NAN;\n      rte_out->uavgup[lev] = NAN;\n    }\n\n    if (planck_tempoff) {\n      rte_in->planck = 1;\n      planck_tempoff = 0;\n    }\n\n    break; /* END dynamic_tenstream */\n\n  case SOLVER_TWOMAXRND3C: /* Bernhard Mayer, 11.4.2018, Nina Crnivec twostream with Maximum Random Overlap and tripleclouds */\n    twostr_gg_cldk = (float*)calloc (output->atm.nlyr, sizeof (float));\n    twostr_gg_cldn = (float*)calloc (output->atm.nlyr, sizeof (float));\n    twostr_gg_clr  = (float*)calloc (output->atm.nlyr, sizeof (float));\n    for (lu = 0; lu < output->atm.nlyr; lu++) {\n      twostr_gg_cldk[lu] = output->pmom01_cldk[lu];\n      twostr_gg_cldn[lu] = output->pmom01_cldn[lu];\n      twostr_gg_clr[lu]  = output->pmom01_clr[lu];\n    }\n\n    /* ??? no need for thermal below 2um;                 ??? */\n    /* ??? need to do that to avoid numerical underflow;  ??? */\n    /* ??? however, this could be done without actually   ??? */\n    /* ??? calling the solver                             ??? */\n    if (rte_in->planck && output->wl.lambda_r[iv] < 2000.0) {\n      rte_in->planck = 0;\n      planck_tempoff = 1;\n    }\n\n    twostr_cf = calloc (output->atm.nlyr, sizeof (float));\n\n    if (output->cf.nlev != 0) {\n\n      if (output->atm.nlyr != output->cf.nlev) {\n        fprintf (stderr,\n                 \"Fatal error! Cloud fraction grid different from atmospheric grid. %d levels vs. %d levels\\n\",\n                 output->cf.nlev,\n                 output->atm.nlyr + 1);\n        return -1;\n      } else {\n        for (lu = 0; lu < output->atm.nlyr; lu++)\n          twostr_cf[lu] = output->cf.cf[lu];\n      }\n    }\n\n#if HAVE_TWOMAXRND3C\n    status = twomaxrnd3C (output->dtauc_cldk, /* dtau (rodents) = dtau_org (twostrebe) */\n                          output->ssalb_cldk, /* omega_0 */\n                          twostr_gg_cldk,     /* g (rodents) = g_org (twostrebe) */\n                          output->dtauc_cldn, /* dtau (rodents) = dtau_org (twostrebe) */\n                          output->ssalb_cldn, /* omega_0 */\n                          twostr_gg_cldn,     /* g (rodents) = g_org (twostrebe) */\n                          output->dtauc_clr,  /* dtau (rodents) = dtau_org (twostrebe) */\n                          output->ssalb_clr,  /* omega_0 */\n                          twostr_gg_clr,      /* g (rodents) = g_org (twostrebe) */\n                          twostr_cf,          /* cloud fraction */\n                          input.rte.twomaxrnd3C_scale_cf,\n                          output->atm.nlyr + 1,     /* nlev */\n                          rte_in->fbeam,            /* S_0 */\n                          rte_in->umu0,             /* mu_0 */\n                          output->alb.albedo_r[iv], /* surface albedo */\n                          rte_in->planck,           /* whether to use planck */\n                          input.rte.deltam,         /* delta scaling */\n                          output->atm.nzout,        /* nzout */\n                          output->atm.zd,           /* z-levels */\n                          output->atm.microphys.temper[0][0],\n                          rte_in->btemp, /* surface temperature */\n                          output->wl.wvnmlo_r[iv],\n                          output->wl.wvnmhi_r[iv],\n                          input.atm.zout_sur, /* zout's (in km) */\n                          /* output */\n                          rte_out->rfldn,  /* e_minus */\n                          rte_out->flup,   /* e_plus */\n                          rte_out->rfldir, /* s_direct */\n                          rte_out->uavg);  /* KST ???? */\n\n    if (status != 0) {\n      fprintf (stderr, \"Error %d returned by twomaxrnd3C()\\n\", status);\n      return status;\n    }\n#else\n    fprintf (stderr, \"Error: twomaxrnd3C solver not included in uvspec build.\\n\");\n    return -1;\n#endif\n\n    free (twostr_gg_cldk);\n    free (twostr_gg_cldn);\n    free (twostr_gg_clr);\n    free (twostr_cf);\n\n    for (lev = 0; lev < output->atm.nzout; lev++) {\n      rte_out->uavgso[lev] = NAN;\n      rte_out->uavgdn[lev] = NAN;\n      rte_out->uavgup[lev] = NAN;\n    }\n\n    if (planck_tempoff) {\n      rte_in->planck = 1;\n      planck_tempoff = 0;\n    }\n\n    break; /* END twomaxrnd3C */\n\n  case SOLVER_SOS:\n#if HAVE_SOS\n    ASCII_calloc_float (&pmom_sos, output->atm.nlyr, output->atm.nmom + 1);\n\n    for (lu = 0; lu < output->atm.nlyr; lu++)\n      for (k = 0; k < output->atm.nmom + 1; k++)\n        pmom_sos[lu][k] = output->pmom[lu][0][k];\n\n    status = sos (output->atm.nlyr,\n                  rte_in->newgeo,\n                  input.rte.nstr,\n                  input.rte.sos_nscat,\n                  output->alb.albedo_r[iv],\n                  input.r_earth,\n                  output->atm.zd,\n                  output->ssalb,\n                  pmom_sos,\n                  output->dtauc,\n                  output->atm.sza_r[iv],\n                  output->atm.nzout,\n                  input.rte.numu,\n                  input.rte.umu,\n                  rte_in->utau,\n                  rte_out->rfldir,\n                  rte_out->rfldn,\n                  rte_out->flup,\n                  rte_out->uavgso,\n                  rte_out->uavgdn,\n                  rte_out->uavgup,\n                  rte_out->u0u);\n\n    if (status != 0) {\n      fprintf (stderr, \"Error %d returned by sos()\\n\", status);\n      return status;\n    }\n    break;\n#else\n    fprintf (stderr, \"Error: sos solver not included in uvspec build.\\n\");\n    fprintf (stderr, \"Error: Please contact arve.kylling@gmail.com\\n\");\n    return -1;\n#endif\n\n  case SOLVER_SSLIDAR:\n\n    /* NOTE! Lidar only uses one umu!!! */\n\n    phase_back = calloc ((size_t)output->atm.nlyr, sizeof (double*));\n\n    for (lu = 0; lu < output->atm.nlyr; lu++)\n      phase_back[lu] = calloc ((size_t)output->nphamat, sizeof (double));\n\n    /* this only works because mu[0] = -1.0 */\n    for (lu = 0; lu < output->atm.nlyr; lu++)\n      for (is = 0; is < output->nphamat; is++)\n        phase_back[lu][is] = output->phase[lu][is][0];\n\n    status = ss_lidar (/* input: atmosphere */\n                       output->atm.nlyr,\n                       output->atm.zd, /* z-levels */\n                       output->alt.altitude,\n                       output->dtauc,            /* optical depth */\n                       output->ssalb,            /* omega_0 */\n                       phase_back,               /* phase function in backward direction */\n                       output->alb.albedo_r[iv], /* albedo (rodents) = Ag (twostrebe) */\n                       /* input: lidar */\n                       output->wl.lambda_r[iv], /* lidar wavelength */\n                       input.sslidar[SSLIDAR_E0],\n                       input.sslidar[SSLIDAR_POSITION],\n                       input.rte.umu[0], /* only first umu is lidar direction */\n                       input.sslidar_nranges,\n                       input.sslidar[SSLIDAR_RANGE],\n                       output->atm.zout_sur, /* ranges (in km) */\n                       input.sslidar[SSLIDAR_EFF],\n                       input.sslidar[SSLIDAR_AREA],\n                       input.sslidar_polarisation,\n                       /* OUTPUT / RESULT */\n                       rte_out->sslidar_nphot,\n                       rte_out->sslidar_nphot_q,\n                       rte_out->sslidar_ratio);\n    if (status != 0) {\n      fprintf (stderr, \"Error %d returned by ss_lidar()\\n\", status);\n      return status;\n    }\n\n    for (lu = 0; lu < output->atm.nlyr; lu++)\n      free (phase_back[lu]);\n    free (phase_back);\n    break;\n  case SOLVER_NULL:\n    /* do nothing */\n    break;\n\n  default:\n    fprintf (stderr, \"Error: RTE solver %d not yet implemented, call_solver (solve_rte.c)\\n\", input.rte.solver);\n    return -1;\n  }\n\n  if (verbose) {\n    end = clock();\n    fprintf (stderr, \"*** last solver call: %f seconds\\n\", ((double)(end - start)) / CLOCKS_PER_SEC);\n  }\n\n  return 0; /* if o.k. */\n}\n\nstatic int init_rte_input (rte_input* rte, input_struct input, output_struct* output) {\n  int i = 0, found = 0;\n  int ip = 0, is = 0, lu = 0;\n  int status = 0;\n\n  strcpy (rte->header, \"\");\n  rte->accur = 1.0e-5;\n\n  switch (input.source) {\n  case SRC_NONE:\n  case SRC_BLITZ:\n  case SRC_LIDAR:\n    rte->planck = 0;\n    rte->fbeam  = 0.0;\n    rte->fisot  = 0.0;\n    break;\n\n  case SRC_SOLAR:\n    rte->planck = 0;\n\n    if (input.rte.fisot > 0) {\n      rte->fbeam = 0.0;\n      rte->fisot = 1.0;\n    } else {\n      rte->fbeam = 1.0;\n      rte->fisot = 0.0;\n    }\n\n    break;\n\n  case SRC_THERMAL:\n    rte->planck = 1;\n    rte->fbeam  = 0.0;\n    rte->fisot  = 0.0;\n\n    rte->btemp = output->surface_temperature;\n    rte->ttemp = output->atm.microphys.temper[0][0][0];\n\n    rte->temis = 0.0;\n\n    break;\n  default:\n    fprintf (stderr, \"Error, unknown source\\n\");\n    return -1;\n  }\n\n  rte->umu0 = 0.0;\n\n  rte->ierror_d[0] = 0;\n  rte->ierror_s[0] = 0;\n  rte->ierror_t[0] = 0;\n\n  for (i = 0; i < 7; i++)\n    rte->prndis[i] = 0;\n\n  for (i = 0; i < 5; i++)\n    rte->prndis2[i] = 0;\n\n  for (i = 0; i < 2; i++)\n    rte->prntwo[i] = 0;\n\n  rte->ibcnd  = input.rte.ibcnd;\n  rte->lamber = 1;\n  rte->newgeo = 1;\n  rte->nil    = 0;\n  rte->onlyfl = 1;\n  rte->quiet  = input.quiet;\n  rte->usrang = 0;\n  rte->usrtau = 1;\n\n  if (input.rte.pseudospherical || input.rte.solver == SOLVER_SDISORT ||\n      input.rte.solver == SOLVER_SPSDISORT) /* these solvers are spherical by default */\n    rte->spher = 1;\n  else\n    rte->spher = 0;\n\n  rte->hl   = (float*)calloc (input.rte.maxumu + 1, sizeof (float));\n  rte->utau = (float*)calloc (output->atm.nzout, sizeof (float));\n\n  if (input.rte.numu > 0) {\n    rte->onlyfl = 0;\n    rte->usrang = 1;\n  }\n\n  /* PolRadtran */\n  rte->pol.deltam      = \"Y\";\n  rte->pol.ground_type = \"L\";\n  strcpy (rte->pol.polscat, \"\");\n  rte->pol.albedo       = 0.0;\n  rte->pol.btemp        = 0.0;\n  rte->pol.flux         = 1.0;\n  rte->pol.gas_extinct  = NULL;\n  rte->pol.height       = NULL;\n  rte->pol.mu           = 1.0;\n  rte->pol.sky_temp     = 0.0;\n  rte->pol.temperatures = NULL;\n  rte->pol.wavelength   = 0.0;\n  rte->pol.outlevels    = NULL;\n  rte->pol.nummu        = 0;\n\n  rte->pol.ground_index.re = 0.0;\n  rte->pol.ground_index.im = 0.0;\n\n  /* get the indices of the zout levels in the z-scale */\n  rte->pol.outlevels = (int*)calloc (output->atm.nzout, sizeof (int));\n  found              = 0;\n  for (i = 0; i < output->atm.nzout; i++)\n    for (lu = 0; lu < output->atm.nlev; lu++) {\n      if (fabs (output->atm.zout_sur[i] - output->atm.zd[lu]) <= 0) {\n        rte->pol.outlevels[found++] = lu + 1;\n        break;\n      }\n    }\n\n  switch (input.rte.solver) {\n  case SOLVER_MONTECARLO:\n    /* set number of photons */\n    output->mc_photons = input.rte.mc.photons;\n    break;\n  case SOLVER_SDISORT:\n  case SOLVER_SPSDISORT:\n  case SOLVER_FDISORT1:\n  case SOLVER_SSS:\n  case SOLVER_SSSI:\n  case SOLVER_TZS:\n    for (ip = 0; ip < input.rte.nprndis; ip++)\n      (rte->prndis)[input.rte.prndis[ip] - 1] = 1;\n    break;\n  case SOLVER_DISORT:\n  case SOLVER_FDISORT2:\n    for (ip = 0; ip < input.rte.nprndis; ip++)\n      (rte->prndis2)[input.rte.prndis[ip] - 1] = 1;\n    break;\n  case SOLVER_POLRADTRAN:\n    /* Need to do a little checking of polradtran specific input stuff here...*/\n    if (found != output->atm.nzout) {\n      fprintf (stderr, \"*** zout does not correspond to atmosphere file levels.\\n\");\n      fprintf (stderr, \"*** zout must do so for the polradtran solver.\\n\");\n      status--;\n    }\n\n    if (input.rte.deltam == 0)\n      rte->pol.deltam = \"N\";\n    else if (input.rte.deltam == 1)\n      rte->pol.deltam = \"Y\";\n\n    if ((output->mu_values = (float*)calloc (input.rte.nstr / 2 + input.rte.numu, sizeof (float))) == NULL)\n      return -1;\n\n    if (strncmp (input.rte.pol_quad_type, \"E\", 1) == 0)\n      for (i = 0; i < input.rte.numu; i++)\n        output->mu_values[input.rte.nstr / 2 + i] = input.rte.umu[i];\n\n    rte->pol.gas_extinct  = (double*)calloc (output->atm.nlyr + 1, sizeof (double));\n    rte->pol.height       = (double*)calloc (output->atm.nlyr + 1, sizeof (double));\n    rte->pol.temperatures = (double*)calloc (output->atm.nlyr + 1, sizeof (double));\n\n    output->atm.pol_scat_files = (char*)calloc (64 * output->atm.nlyr, sizeof (char));\n\n    for (is = 0; is < 64 * output->atm.nlyr; is++)\n      output->atm.pol_scat_files[is] = ' ';\n\n    for (lu = 0; lu < output->atm.nlyr; lu++) {\n      is = lu * 64;\n      if (lu > 998)\n        return err_out (\"nlyr must be < 999, or a sprintf buffer overflow would occur,fix this\", output->atm.nlyr);\n      sprintf (rte->pol.polscat, \".scat_file_%03d\", lu);\n      strcpy (&output->atm.pol_scat_files[is], rte->pol.polscat);\n    }\n\n    for (lu = 0; lu <= output->atm.nlyr; lu++) {\n      rte->pol.height[lu]       = (double)lu; /*  Weird hey???? Well, the story goes as \n\t\t\t\t\t      follows: polradtran wants extinction and\n\t\t\t\t\t      scattering in terms of 1/(layerthickness).\n\t\t\t\t\t      However, we feed it optical depth. Hence,\n\t\t\t\t\t      we need to make delta_height of each layer\n\t\t\t\t\t      equal one. One simple remedy is the one\n\t\t\t\t\t      used. Arve 15.03.2000 */\n      rte->pol.temperatures[lu] = (double)output->atm.microphys.temper[0][0][lu];\n    }\n    break;\n  case SOLVER_TWOSTR:\n  case SOLVER_FTWOSTR:\n    for (ip = 0; ip < input.rte.nprndis; ip++)\n      if (input.rte.prndis[ip] == 1 || input.rte.prndis[ip] == 2)\n        (rte->prntwo)[input.rte.prndis[ip] - 1] = 1;\n    break;\n  case SOLVER_SOS:\n  case SOLVER_NULL:\n  case SOLVER_RODENTS:\n  case SOLVER_TWOSTREBE:\n  case SOLVER_TWOMAXRND:\n  case SOLVER_TWOMAXRND3C:\n  case SOLVER_DYNAMIC_TWOSTREAM:\n  case SOLVER_DYNAMIC_TENSTREAM:\n  case SOLVER_SSLIDAR:\n    break;\n  default:\n    fprintf (stderr, \"Error: RTE solver %d not yet implemented, init_rte_input (solve_rte.c)\\n\", input.rte.solver);\n    return -1;\n    break;\n  }\n\n  return status;\n}\n\nstatic void fourier2azimuth (double**** down_rad_rt3,\n                             double**** up_rad_rt3,\n                             double**** down_rad,\n                             double**** up_rad,\n                             int        nzout,\n                             int        aziorder,\n                             int        nstr,\n                             int        numu,\n                             int        nstokes,\n                             int        nphi,\n                             float*     phi) {\n  /* For each azimuth and polar angle sum the Fourier azimuth series appropriate\n     for the particular Stokes parameter to produce the radiance.\n     Only used for the polradtran solver \n  */\n  int    i = 0, j = 0, je = 0, k = 0, lu = 0, m = 0;\n  double sumd = 0, sumu = 0;\n  float  phir;\n  for (lu = 0; lu < nzout; lu++) {\n    for (k = 0; k < nphi; k++) {\n      phir = PI * phi[k] / 180.0;\n\n      /* Up- and downwelling irradiances at user angles only*/\n      /*      for (j=0;j<nstr/2+numu;j++) {  */\n      for (j = 0; j < numu; j++) {\n        je = j + nstr / 2;\n        for (i = 0; i < nstokes; i++) {\n          sumd = 0.0;\n          sumu = 0.0;\n          for (m = 0; m <= aziorder; m++) {\n            if (i < 2) {\n              sumd += cos (m * phir) * down_rad_rt3[lu][m][je][i];\n              sumu += cos (m * phir) * up_rad_rt3[lu][m][je][i];\n            } else {\n              sumd += sin (m * phir) * down_rad_rt3[lu][m][je][i];\n              sumu += sin (m * phir) * up_rad_rt3[lu][m][je][i];\n            }\n          }\n          down_rad[lu][k][j][i] = sumd;\n          up_rad[lu][k][j][i]   = sumu;\n        }\n      }\n    }\n  }\n}\n\n/***************************************************************/\n/* calc_spectral_heating calculates the divergence of the flux */\n/* either by differences of the flux or                        */\n/* with the help of the actinic flux                           */\n/***************************************************************/\n\nstatic int calc_spectral_heating (input_struct   input,\n                                  output_struct* output,\n                                  float*         dz,\n                                  double*        rho_mass_zout,\n                                  float*         k_abs,\n                                  float*         k_abs_layer,\n                                  int*           zout_index,\n                                  rte_output*    rte_out,\n                                  float*         heat,\n                                  float*         emis,\n                                  float*         w_zout,\n                                  int            iv) {\n\n  int status = 0;\n\n  int lz    = NOT_DEFINED_INTEGER;\n  int lc    = NOT_DEFINED_INTEGER;\n  int nzout = NOT_DEFINED_INTEGER;\n  int nlev  = NOT_DEFINED_INTEGER;\n  int nlyr  = NOT_DEFINED_INTEGER;\n\n  /* float *Fup = NULL; */\n  /* float *Fdn = NULL; */\n  float* F_net = NULL;\n  float  dFdz  = 0;\n  float* c_p   = 0;\n\n  float* dtheta_dz_layer = NULL;\n  float* dtheta_dz       = NULL;\n\n  float* dFdz_array = NULL;\n  int    lz1 = NOT_DEFINED_INTEGER, lz2 = NOT_DEFINED_INTEGER, n_lz = NOT_DEFINED_INTEGER;\n  float  M_AIR           = MOL_MASS_AIR / 1000.0; /* molecular weight of air (kg mol-1) */\n  float  planck_radiance = 0.0;\n\n  float* z_center  = NULL;\n  float* zout_in_m = NULL;\n  int    outside   = 0;\n  int    start     = 0;\n\n  /*   int additional_verbose_output=FALSE; */\n\n  nlev  = output->atm.nlev;\n  nlyr  = nlev - 1;\n  nzout = output->atm.nzout;\n\n  /* center heights of the atmosphere layers in m */\n  if (((z_center) = (float*)calloc (nlyr, sizeof (float))) == NULL) {\n    fprintf (stderr, \"Error allocating memory for 'z_center'\\n\");\n    fprintf (stderr, \"       (line %d, function '%s' in '%s')\\n\", __LINE__, __func__, __FILE__);\n    return -1;\n  }\n  for (lc = 0; lc < nlyr; lc++)\n    z_center[lc] = output->atm.zd[lc] * 1000.0 - dz[lc] / 2; /* 1000 == km -> m */\n\n  /* zout_in_m == levels (layer boundaries) of zout levels in m above surface */\n  if (((zout_in_m) = (float*)calloc (nzout, sizeof (float))) == NULL) {\n    fprintf (stderr, \"Error allocating memory for 'zout_in_m'\\n\");\n    fprintf (stderr, \"       (line %d, function '%s' in '%s')\\n\", __LINE__, __func__, __FILE__);\n    return -1;\n  }\n  for (lz = 0; lz < nzout; lz++) {\n    zout_in_m[lz] = output->atm.zout_sur[lz] * 1000.0; /* 1000 == km -> m */\n    /* if (iv == 0) fprintf(stderr,\"zout in metern %3d = %10.3f\\n\", lz, zout_in_m[lz] ); */\n  }\n\n  if (((dtheta_dz) = (float*)calloc (nzout, sizeof (float))) == NULL) {\n    fprintf (stderr, \"Error allocating memory for 'dtheta_dz'\\n\");\n    fprintf (stderr, \"       (line %d, function '%s' in '%s')\\n\", __LINE__, __func__, __FILE__);\n    return -1;\n  }\n\n  /* calculate normalized (1/incident_flux) spectral heating rate */\n  switch (input.heating) {\n  case HEAT_LAYER_CD:\n  case HEAT_LAYER_FD:\n\n    /*   /\\* additional verbose output *\\/ */\n    /*   if (additional_verbose_output) { */\n    /*     if (((Fup) = (float *) calloc (nzout, sizeof(float))) == NULL) { */\n    /*       fprintf (stderr, \"Error allocating memory for (Fup) in %s (%s)\\n\", function_name, file_name); */\n    /*       return -1; */\n    /*     } */\n\n    /*     if (((Fdn) = (float  *) calloc (nzout, sizeof(float))) == NULL) { */\n    /*       fprintf (stderr, \"Error allocating memory for (Fdn) in %s (%s)\\n\", function_name, file_name); */\n    /*       return -1; */\n    /*     } */\n    /*   } */\n\n    if (((F_net) = (float*)calloc (nzout, sizeof (float))) == NULL) {\n      fprintf (stderr, \"Error allocating memory for 'dF'\\n\");\n      fprintf (stderr, \"       (line %d, function '%s' in '%s')\\n\", __LINE__, __func__, __FILE__);\n      return -1;\n    }\n\n    if (((dFdz_array) = (float*)calloc (nzout, sizeof (float))) == NULL) {\n      fprintf (stderr, \"Error allocating memory for 'dFdz_array'\\n\");\n      fprintf (stderr, \"       (line %d, function '%s' in '%s')\\n\", __LINE__, __func__, __FILE__);\n      return -1;\n    }\n\n    if (((c_p) = (float*)calloc (nzout, sizeof (float))) == NULL) {\n      fprintf (stderr, \"Error allocating memory for 'c_p'\\n\");\n      fprintf (stderr, \"       (line %d, function '%s' in '%s')\\n\", __LINE__, __func__, __FILE__);\n      return -1;\n    }\n\n    switch (input.rte.solver) {\n    case SOLVER_FDISORT1:\n    case SOLVER_SDISORT:\n    case SOLVER_FTWOSTR:\n    case SOLVER_TWOSTR:\n    case SOLVER_RODENTS:\n    case SOLVER_TWOSTREBE:\n    case SOLVER_TWOMAXRND:\n    case SOLVER_TWOMAXRND3C:\n    case SOLVER_DYNAMIC_TWOSTREAM:\n    case SOLVER_DYNAMIC_TENSTREAM:\n    case SOLVER_SOS:\n    case SOLVER_MONTECARLO:\n    case SOLVER_FDISORT2:\n    case SOLVER_DISORT:\n    case SOLVER_SPSDISORT:\n    case SOLVER_TZS:\n    case SOLVER_SSS:\n    case SOLVER_SSSI:\n    case SOLVER_NULL:\n      for (lz = 0; lz < nzout; lz++) {\n        /*       if (additional_verbose_output) { */\n        /*         Fdn[lz] = rte_out->rfldir[lz] + rte_out->rfldn[lz]; */\n        /*         Fup[lz] = rte_out->flup[lz]; */\n        /*       } */\n        F_net[lz] = (rte_out->rfldir[lz] + rte_out->rfldn[lz]) - rte_out->flup[lz];\n      }\n      break;\n    case SOLVER_POLRADTRAN:\n      for (lz = 0; lz < nzout; lz++) {\n        /*       if (additional_verbose_output) { */\n        /*         Fdn[lz] = rte_out->polradtran_down_flux[lz][0]; */\n        /*         Fup[lz] = rte_out->polradtran_up_flux[lz][0]; */\n        /*       } */\n        F_net[lz] = rte_out->polradtran_down_flux[lz][0] - rte_out->polradtran_up_flux[lz][0];\n      }\n      break;\n    default:\n      fprintf (stderr, \"Error: unknown solver id number %d\\n\", input.rte.solver);\n      fprintf (stderr, \"       (line %d, function '%s' in '%s')\\n\", __LINE__, __func__, __FILE__);\n      return -1;\n      break;\n    }\n\n    if (input.heating == HEAT_LAYER_CD)\n      n_lz = nzout;\n    if (input.heating == HEAT_LAYER_FD)\n      n_lz = nzout - 1;\n\n    for (lz = 0; lz < n_lz; lz++) {\n\n      if (input.heating == HEAT_LAYER_CD) {\n        if (lz == 0) {\n          lz1 = lz;\n          lz2 = lz + 1;\n        } else if (lz == output->atm.nzout - 1) {\n          lz1 = lz - 1;\n          lz2 = lz;\n        } else {\n          lz1 = lz - 1;\n          lz2 = lz + 1;\n        }\n\n        if (lz != 0 && lz != output->atm.nzout - 1) {\n          /* centered difference */ /* 1.0e+6: convert from cm-3 to m-3 */\n          rho_mass_zout[lz] = output->atm.microphys.dens_zout[MOL_AIR][lz] * 1.0e+6 * M_AIR / AVOGADRO;\n\n          /* mass weighted mean of specific heating rates */\n          c_p[lz] = output->atm.microphys.c_p[lz];\n        } else {\n          /* boundary, no centered difference possible, (log) average density for forward difference */\n          rho_mass_zout[lz] =\n            log_average (output->atm.microphys.dens_zout[MOL_AIR][lz1], output->atm.microphys.dens_zout[MOL_AIR][lz2]) * 1.0e+6 *\n            M_AIR / AVOGADRO;\n\n          /* mass weighted mean of specific heating rates, assuming exponential change of density and linear change of c_p */\n          c_p[lz] = mass_weighted_average (output->atm.microphys.c_p[lz1],\n                                           output->atm.microphys.c_p[lz2],\n                                           output->atm.microphys.dens_zout[MOL_AIR][lz1],\n                                           output->atm.microphys.dens_zout[MOL_AIR][lz2]);\n        }\n      } else if (input.heating == HEAT_LAYER_FD) {\n        /* forward difference */\n        lz1 = lz;\n        lz2 = lz + 1;\n\n        /* effective density for one layer (logarithmic) */ /* 1.0e+6: convert from cm-3 to m-3 */\n        rho_mass_zout[lz] =\n          log_average (output->atm.microphys.dens_zout[MOL_AIR][lz1], output->atm.microphys.dens_zout[MOL_AIR][lz2]) * 1.0e+6 *\n          M_AIR / AVOGADRO;\n\n        /* mass weighted mean of specific heating rates, assuming exponential change of density and linear change of c_p */\n        c_p[lz] = mass_weighted_average (output->atm.microphys.c_p[lz1],\n                                         output->atm.microphys.c_p[lz2],\n                                         output->atm.microphys.dens_zout[MOL_AIR][lz1],\n                                         output->atm.microphys.dens_zout[MOL_AIR][lz2]);\n      } else {\n        fprintf (stderr, \"Error, unknown processing scheme %d\\n\", input.processing);\n        fprintf (stderr, \"        (line %d, function '%s' in '%s')\\n\", __LINE__, __func__, __FILE__);\n      }\n\n      /* Compute the derivative dF/dz using a two-point formula */\n\n      if (fabs ((F_net[lz1] - F_net[lz2]) / F_net[lz1]) > 1.0E-6 ||\n          fabs ((output->atm.zout_sur[lz1] - output->atm.zout_sur[lz2]) * rho_mass_zout[lz]) > 1.0E-6) {\n        dFdz = (F_net[lz1] - F_net[lz2]) / (output->atm.zout_sur[lz1] - output->atm.zout_sur[lz2]);\n      } else\n        dFdz = NAN;\n\n      dFdz_array[lz] = 0.001 * dFdz; /* 1/1000 = km -> m, for dz */\n\n      /*       if (additional_verbose_output) { */\n      /*        if (lz==0) { */\n      /*          fprintf (stderr, \" ... calling calc_spectral_heating()\\n\"); */\n      /*          if (input.heating == HEAT_LAYER_CD)  fprintf (stderr, \" ... calculate heating_rate with centered differences \\n\"); */\n      /*          if (input.heating == HEAT_LAYER_FD)  fprintf (stderr, \" ... calculate heating_rate with forward differences \\n\"); */\n      /*          fprintf (stderr, \"\\n#--------------------------------------------------------------------------------------------------------------------------------\\n\"); */\n      /*          fprintf (stderr, \"#lvl      z    l1  l2    z(l1)    z(l2)    E(l1)     E(l2)      dE/dz      |dE/E|        Edn       Eup      Edn/dz        Eup/dz   \\n\"); */\n      /*          fprintf (stderr, \"#         km              km       km      W/m2      W/m2      W/(m2 m)                  W/m2      W/m2    W/(m2 km)     W/(m2 km) \\n\"); */\n      /*          fprintf (stderr, \"#----------------------------------------------------------------------------------------------------------------------------------\\n\"); */\n      /*        } */\n\n      /*        fprintf (stderr, \"%3d %9.3f %3d %3d %8.3f %8.3f %9.4f %9.4f %12.5e %10.5e %9.4f %9.4f %12.5e %12.5e\\n\", */\n      /*           lz, output->atm.zout_sur[lz], lz1, lz2, output->atm.zout_sur[lz1],output->atm.zout_sur[lz2], */\n      /*           F_net[lz1],F_net[lz2],dFdz_array[lz],fabs((F_net[lz1]-F_net[lz2])/F_net[lz1]),Fdn[lz],Fup[lz], */\n      /*           (Fdn[lz1]-Fdn[lz2])/(output->atm.zout_sur[lz1]-output->atm.zout_sur[lz2]),(Fup[lz1]-Fup[lz2])/(output->atm.zout_sur[lz1]-output->atm.zout_sur[lz2])); */\n      /*       } */\n\n      heat[lz] = dFdz_array[lz] / (rho_mass_zout[lz] * c_p[lz]);\n\n      /* calculate dtheta_dz from zout-levels */\n      dtheta_dz[lz] = (output->atm.microphys.theta_zout[lz1] - output->atm.microphys.theta_zout[lz2]) /\n                      (1000.0 * (output->atm.zout_sur[lz1] - output->atm.zout_sur[lz2]));\n\n      w_zout[lz] = (output->atm.microphys.theta_zout[lz] / output->atm.microphys.temper_zout[lz]) * 1.0 / dtheta_dz[lz] * heat[lz];\n    }\n\n    /*   if (additional_verbose_output) { */\n    /*     free(Fup); */\n    /*     free(Fdn); */\n    /*   } */\n\n    free (F_net);\n    free (dFdz_array);\n    free (c_p);\n\n    break;\n  case HEAT_LOCAL:\n\n    /* spline interpolation of all level EXEPT LOWEST AND HIGHEST LEVEL */\n    /* they are outside of the range of layer midpoints and must therefor be extrapolated !!!! */\n\n    if (((dtheta_dz_layer) = (float*)calloc (nlyr, sizeof (float))) == NULL) {\n      fprintf (stderr, \"Error allocating memory for 'dtheta_dz_layer'\\n\");\n      fprintf (stderr, \"       (line %d, function '%s' in '%s')\\n\", __LINE__, __func__, __FILE__);\n      return -1;\n    }\n\n    outside = 0;\n    /* k_abs_layer == absorption coefficient representative for one layer (layer midpoint is z_center) */\n    for (lc = 0; lc < nlyr; lc++) {\n      k_abs_layer[lc]     = (1.0 - output->ssalb[lc]) * output->dtauc[lc] / dz[lc];\n      dtheta_dz_layer[lc] = (output->atm.microphys.theta[lc + 1] - output->atm.microphys.theta[lc]) /\n                            ((output->atm.zd[lc + 1] - output->atm.zd[lc]) * 1000.0);\n    }\n\n    /* if uppermost zout level is above the uppermost layer midpoint (e.g. zout TOA),  */\n    /* than extrapolate k_abs from the uppermost 2 layers                              */\n    if (zout_in_m[nzout - 1] > z_center[0]) {\n      outside = 1;\n      /* exponentiell extrapolation, as linear might cause negative values */\n      if (k_abs_layer[1] != 0.0)\n        k_abs[nzout - 1] =\n          k_abs_layer[0] * pow (k_abs_layer[0] / k_abs_layer[1], dz[0] / ((output->atm.zd[0] - output->atm.zd[2]) * 1000.0));\n      else\n        /* if not possible, take value from the last layer, in most cases also 0.0  */\n        k_abs[nzout - 1] = k_abs_layer[0];\n      /* first difference */\n      dtheta_dz[nzout - 1] = dtheta_dz_layer[0]; /* zout is sorted ascending, z_atm descending */\n    }\n\n    /* if lowermost zout level is below the lowest layer midpoint (e.g. zout surface),  */\n    /* than extrapolate k_abs from the lowermost 2 layers                              */\n    if (zout_in_m[0] < z_center[nlyr - 1]) {\n      outside = outside + 1;\n      start   = 1;\n      /* linear extrapolation */\n      k_abs[0] = k_abs_layer[nlyr - 1] - dz[nlyr - 1] * (k_abs_layer[nlyr - 1] - k_abs_layer[nlyr - 2]) /\n                                           ((output->atm.zd[nlyr] - output->atm.zd[nlyr - 2]) * 1000.0); /* 1000 = km -> m */\n      /* canceled 2/2 in (dz/2)/((z[2]-z[0])/2) */\n      /* last difference */\n      dtheta_dz[0] = dtheta_dz_layer[nlyr - 1]; /* zout is sorted ascending, z_atm descending */\n    }\n\n    /* interpolate the rest, attention pointer arithmetic, last argument 1 means descending order of z_center */\n    /* in versions before Jan 2008 also INTERP_METHOD_SPLINE was tested                 */\n    /* but this caused overshootings, if clouds are present.                            */\n    /* thereforwe use linear PLUS additional levels around the zout level, UH Feb 2008 */\n    status = arb_wvn (nlyr, z_center, k_abs_layer, nzout - outside, zout_in_m + start, k_abs + start, INTERP_METHOD_LINEAR, 1);\n    if (status != 0) {\n      fprintf (stderr, \" Error, interpolation of 'k_abs'\\n\");\n      fprintf (stderr, \"       (line %d, function '%s' in '%s')\\n\", __LINE__, __func__, __FILE__);\n      return -1;\n    }\n\n    /* interpolate the rest, attention pointer arithmetic, last argument 1 means descending order of z_center */\n    status =\n      arb_wvn (nlyr, z_center, dtheta_dz_layer, nzout - outside, zout_in_m + start, dtheta_dz + start, INTERP_METHOD_LINEAR, 1);\n    if (status != 0) {\n      fprintf (stderr, \" Error, interpolation of 'dtheta_dz'\\n\");\n      fprintf (stderr, \"       (line %d, function '%s' in '%s')\\n\", __LINE__, __func__, __FILE__);\n      return -1;\n    }\n\n    for (lz = 0; lz < nzout; lz++) {\n\n      /* level (local) property */ /* 1.0e+6: convert from cm-3 to m-3 */\n      rho_mass_zout[lz] = output->atm.microphys.dens_zout[MOL_AIR][lz] * 1.0e+6 * M_AIR / AVOGADRO;\n\n      /* correction of the emission term of the heating rate, when calculated with actinic flux */\n      if (input.source == SRC_THERMAL) {\n        F77_FUNC (cplkavg, CPLKAVG)\n        (&(output->wl.wvnmlo_r[iv]), &(output->wl.wvnmhi_r[iv]), &(output->atm.microphys.temper_zout[lz]), &(planck_radiance));\n      }\n      /* (else (in the solar case) planck_radiance == 0) */\n\n      heat[lz] = k_abs[lz] * 4.0 * PI * (rte_out->uavg[lz] - planck_radiance) / (rho_mass_zout[lz] * output->atm.microphys.c_p[lz]);\n      emis[lz] = k_abs[lz] * 4.0 * PI * (-planck_radiance) / (rho_mass_zout[lz] * output->atm.microphys.c_p[lz]);\n\n      w_zout[lz] = (output->atm.microphys.theta_zout[lz] / output->atm.microphys.temper_zout[lz]) * 1.0 / dtheta_dz[lz] * heat[lz];\n    }\n\n    /* overwrite heating rate in case of dynamic twostream; in that case uavg contains dEnet */\n    if (input.rte.solver == SOLVER_DYNAMIC_TWOSTREAM || input.rte.solver == SOLVER_DYNAMIC_TENSTREAM) {\n\n      if (!input.quiet)\n        fprintf (stderr, \" ... overwriting heating rate by uavg (dynamic_twostream special)\\n\");\n\n      for (lz = 0; lz < nzout - 1; lz++) {\n        /* BM, 18.9.2020: copied from layer_fd above */\n        double rho_mass_tmp =\n          log_average (output->atm.microphys.dens_zout[MOL_AIR][lz], output->atm.microphys.dens_zout[MOL_AIR][lz + 1]) * 1.0e+6 *\n          M_AIR / AVOGADRO;\n\n        /* mass weighted mean of specific heating rates, assuming exponential change of density and linear change of c_p */\n        double c_p_tmp = mass_weighted_average (output->atm.microphys.c_p[lz],\n                                                output->atm.microphys.c_p[lz + 1],\n                                                output->atm.microphys.dens_zout[MOL_AIR][lz],\n                                                output->atm.microphys.dens_zout[MOL_AIR][lz + 1]);\n\n        // factor 1000.0 converts z from km to m\n        heat[lz] =\n          rte_out->uavg[lz] / (rho_mass_tmp * c_p_tmp) / (output->atm.zout_sur[lz + 1] - output->atm.zout_sur[lz]) / 1000.0;\n        emis[lz] = NAN;\n      }\n    }\n\n    break;\n  default:\n    fprintf (stderr, \"Error, unknown processing scheme %d\\n\", input.processing);\n    fprintf (stderr, \"       (line %d, function '%s' in '%s')\\n\", __LINE__, __func__, __FILE__);\n    return -1;\n  }\n\n  free (z_center);\n  free (zout_in_m);\n  free (dtheta_dz);\n\n  return status;\n}\n\nstatic float*** calloc_abs3d (int Nx, int Ny, int Nz, int* threed) {\n  int      lc = 0, lx = 0;\n  float*** tmp;\n\n  tmp = calloc (Nz, sizeof (float**));\n  if (tmp == NULL)\n    return NULL;\n\n  for (lc = 0; lc < Nz; lc++)\n    if (threed[lc]) {\n      tmp[lc] = calloc (Nx, sizeof (float*));\n      if (tmp[lc] == NULL)\n        return NULL;\n\n      for (lx = 0; lx < Nx; lx++) {\n        tmp[lc][lx] = calloc (Ny, sizeof (float));\n        if (tmp[lc][lx] == NULL)\n          return NULL;\n      }\n    }\n\n  return tmp;\n}\n\nstatic void free_abs3d (float*** abs3d, int Nx, int Ny, int Nz, int* threed) {\n  int lc = 0, lx = 0;\n\n  for (lc = 0; lc < Nz; lc++)\n    if (threed[lc]) {\n      for (lx = 0; lx < Nx; lx++)\n        free (abs3d[lc][lx]);\n      free (abs3d[lc]);\n    }\n\n  free (abs3d);\n}\n\nstatic float**** calloc_spectral_abs3d (int Nx, int Ny, int Nz, int nlambda, int* threed) {\n  int       lx = 0, ly = 0, lc = 0;\n  float**** tmp = NULL;\n\n  if ((tmp = (float****)calloc (Nz, sizeof (float***))) == NULL)\n    return NULL;\n\n  for (lc = 0; lc < Nz; lc++) {\n    if (threed[lc]) {\n      if ((tmp[lc] = (float***)calloc (Nx, sizeof (float**))) == NULL)\n        return NULL;\n\n      for (lx = 0; lx < Nx; lx++) {\n        if ((tmp[lc][lx] = (float**)calloc (Ny, sizeof (float*))) == NULL)\n          return NULL;\n\n        for (ly = 0; ly < Ny; ly++)\n          if ((tmp[lc][lx][ly] = (float*)calloc (nlambda, sizeof (float))) == NULL)\n            return NULL;\n      }\n    }\n  }\n\n  return tmp;\n}\n\n/***********************************************************************************/\n/* Function: generate_effective_cloud                                              */\n/*                                                                                 */\n/* Description:                                                                    */\n/*  * Generates an effective cloud assuming random overlap (as in ECHAM)           */\n/*    given cloud profiles and cloud fraction.                                     */\n/*  * save the effective cloud optical property on the wc-structure                */\n/*  * ic-structure is set to 0.0, as wc-structure contrains both now               */\n/*                                                                                 */\n/* Parameters (input/output):                                                      */\n/*   input          uvspec input structure                                         */\n/*   output         uvspec output structure                                        */\n/*   save_cloud     unmodified cloud properties for given wavelength               */\n/*   iv             wavelength index                                               */\n/*   iq             subband index                                                  */\n/*   verbose        flag for verbose output                                        */\n/*                                                                                 */\n/*                                                                                 */\n/* Return value:                                                                   */\n/*     int status         == 0, if everthing is OK                                 */\n/*                        < 0, if there was an error                               */\n/*                                                                                 */\n/* Example:                                                                        */\n/* Files:    solver_rte.c                                                          */\n/* Known bugs: -                                                                   */\n/* Author:                                                                         */\n/*    xxx 200x   C. Emde       Created                                             */\n/*                                                                                 */\n/***********************************************************************************/\n\nstatic int\ngenerate_effective_cloud (input_struct input, output_struct* output, save_optprop* save_cloud, int iv, int iq, int verbose) {\n\n  int    lc = 0, i = 0, isp = 0;\n  float  tauw = 0.0, taui = 0.0, taua = 0.0, taum = 0.0, taur = 0.0, tau_clear = 0.0, tau_cloud = 0.0;\n  float  g1d = 0.0, g2d = 0.0, fd = 0.0, g1i = 0.0, g2i = 0.0, fi = 0.0, gi = 0.0, gw = 0.0;\n  float  ssai = 0.0, ssaw = 0.0;\n  float *ssa = NULL, *tau = NULL, *g = NULL;\n\n  /* Reflectivity of underlying layer, should be zero, because here\n     we calculate just the effective optical thickness of one\n     layer. This optical thickness is used in the RTE solver, where\n     then of course the reflectivity of the neighbour layers is\n     considered. */\n  float pref = 0.0;\n  /* Solar zenith angle */\n  float mu = 0.0;\n  /* Effective solar zenith angle, accounts for the decrease of the\n     direct solar beam and the corresponding increase of the diffuse\n     part of the radiation (in ECHAM). Here always the solar zenith\n     angle is used (see below). */\n  float mu_eff = 0.0;\n  /* Diffusivity factor, 1.66 in ECHAM */\n  float r = 1.66;\n  /* Effective cloudyness */\n  float C_eff = 0.0, product = 1.0;\n  /* Output variables of swde */\n  float pre1 = 0.0, pre2 = 0.0, ptr2 = 0.0;\n  /* Transmission of clear and cloudy parts and of the layer */\n  float transmission_clear = 0.0, transmission_cloud = 0.0, transmission_layer = 0.0;\n  /* Variables for iteratiom */\n  float taueff = 0.0;\n  /* cloud fraction to scale the optical thickness */\n  /* Attention: ECHAM input is already scaled to cloudy part */\n  float cf            = 1.0;\n  int   first_verbose = TRUE;\n\n  /*   if ( input.cloud_overlap == CLOUD_OVERLAP_OFF ) { */\n  /*     fprintf (stderr, \"Error: call of %s, but cloud overlap schema is switched off\\n\", __func__ ); */\n  /*     return -1; */\n  /*   } */\n\n  if (verbose && output->cf.nlev > 0) {\n    fprintf (stderr, \" ... generate effective cloud\\n\");\n  }\n\n  ssa = (float*)calloc (output->atm.nlev - 1, sizeof (float));\n  tau = (float*)calloc (output->atm.nlev - 1, sizeof (float));\n  g   = (float*)calloc (output->atm.nlev - 1, sizeof (float));\n\n  mu = cos (output->atm.sza_r[iv] * PI / 180);\n\n  /* scattering properties */\n  for (lc = 0; lc < output->atm.nlev - 1; lc++) {\n\n    /* Ice and water clouds */\n    tauw = save_cloud->tauw[lc];\n    taui = save_cloud->taui[lc];\n\n    g1d = save_cloud->g1d[lc];\n    g2d = save_cloud->g2d[lc];\n    fd  = save_cloud->fd[lc];\n    gw  = g1d * fd + (1.0 - fd) * g2d;\n\n    g1i = save_cloud->g1i[lc];\n    g2i = save_cloud->g2i[lc];\n    fi  = save_cloud->fi[lc];\n    gi  = g1i * fi + (1.0 - fi) * g2i;\n\n    ssaw = save_cloud->ssaw[lc];\n    ssai = save_cloud->ssai[lc];\n\n    /* molecular absorption */\n    taum = output->atm.optprop.tau_molabs_r[0][0][lc][iv][iq];\n\n    /* aerosol */\n    taua = output->aer.optprop.dtau[iv][lc];\n    //20120816ak stuff below is not in use, commented\n    //    ssaa  = output->aer.optprop.ssa[iv][lc];\n    //    g1a   = output->aer.optprop.g1[iv][lc];\n    //    g2a   = output->aer.optprop.g2[iv][lc];\n    //    fa    = output->aer.optprop.ff[iv][lc];\n    //    ga    = g1a*fa+(1.0-fa)*g2a;\n\n    /*Rayleigh*/\n    switch (input.ck_scheme) {\n    case CK_FU:\n      taur = output->atm.optprop.tau_rayleigh_r[0][0][lc][iv][iq];\n      break;\n\n    case CK_KATO:\n    case CK_KATO2:\n    case CK_KATO2_96:\n    case CK_KATO2ANDWANDJI:\n    case CK_AVHRR_KRATZ:\n    case CK_FILE:\n    case CK_LOWTRAN:\n    case CK_CRS:\n    case CK_REPTRAN:\n    case CK_REPTRAN_CHANNEL:\n    case CK_RAMAN:\n      taur = output->atm.optprop.tau_rayleigh_r[0][0][lc][iv][0];\n      break;\n\n    default:\n      fprintf (stderr, \"Error: unsupported correlated-k scheme %d\\n\", input.ck_scheme);\n      return -1;\n\n      break;\n    }\n\n    /* Calculate mean optical properties of the layer */\n\n    cf = 0.0;\n    for (isp = 0; isp < input.n_caoth; isp++)\n      if (input.caoth[isp].source == CAOTH_FROM_ECHAM || input.caoth[isp].source == CAOTH_FROM_1D)\n        cf = 1.0;\n\n    if (cf == 0.0) { /* else */\n      if (output->cf.cf[lc] != 0.0)\n        cf = output->cf.cf[lc];\n      else\n        cf = 1.0;\n    }\n\n    /* total optical thickness */\n    /* fprintf(stderr, \" scaling tau: tauw = %f, taui = %f, cf = %f\\n\", tauw, taui, cf); */\n    tau_cloud = (tauw + taui) / cf; /* Water and Ice cloud */\n    tau_clear = taum + taua + taur; /* Molecular, Aerosol, and Rayleigh */\n\n    /* Calculate effective Cloudiness */\n\n    /* Total optical thickness */\n    tau[lc] = tau_cloud + tau_clear;\n\n    if ((tauw || taui) != 0.0) {\n      g[lc] = (tauw * ssaw * gw + taui * ssai * gi) / (tauw * ssaw + taui * ssai);\n      /* effective single scattering albedo */\n      ssa[lc] = (tauw * ssaw + taui * ssai) / (tauw + taui);\n    } else {\n      g[lc]   = 1.;\n      ssa[lc] = 1.;\n    }\n\n    if (input.source == SRC_THERMAL)\n      mu_eff = 1. / r;\n    else {\n      /*Calculate effective zenith angle */\n      for (i = lc; i >= 0; i--) {\n        if (mu != 0.0)\n          product *= 1.0 - output->cf.cf[i] * (1.0 - exp (-((1.0 - ssa[i] * g[i] * g[i]) * (tau[lc])) / mu));\n        else\n          product *= 1.0 - output->cf.cf[i];\n      }\n\n      C_eff  = 1.0 - product;\n      mu_eff = mu / (1.0 - C_eff + mu * r * C_eff);\n    }\n\n    /* Call ECHAM radiation routine SWDE. */\n    if ((tauw || taui) != 0.0) {\n\n      /*Initialize inputs for swde.*/\n      pre1               = 0.0;\n      pre2               = 0.0;\n      transmission_cloud = 0.0;\n      transmission_clear = 0.0;\n      ptr2               = 0.0;\n\n      if (verbose) {\n        if (first_verbose) {\n          fprintf (\n            stderr,\n            \"   lc      g        pref    theta_eff   tau        tau_clear      ptr1      ptr2     ssa       cf     taueff\\n\");\n          first_verbose = FALSE;\n        }\n        fprintf (stderr,\n                 \" %4d %9.6f %9.6f %9.3f %12.6e %12.6e %9.6f %9.6f %9.6f %8.5f\",\n                 lc,\n                 g[lc],\n                 pref,\n                 acos (mu_eff) * 180 / PI,\n                 tau[lc],\n                 tau_clear,\n                 transmission_cloud,\n                 ptr2,\n                 ssa[lc],\n                 output->cf.cf[lc]);\n      }\n\n      if (ssa[lc] == 1.0)\n        ssa[lc] = 0.99999;\n\n      /* Perform radiative transfer (twostream) with scaled optical properties\n         to calculate effective optical thickness. */\n      /* Scattering + sbsorption + rayleigh + aerosol*/\n      F77_FUNC (swde, SWDE) (&g[lc], &pref, &mu_eff, &tau[lc], &ssa[lc], &pre1, &pre2, &transmission_cloud, &ptr2);\n\n      ptr2 = 0.0;\n      /* Only absorption, rayleigh, aerosol */\n      F77_FUNC (swde, SWDE) (&g[lc], &pref, &mu_eff, &tau_clear, &ssa[lc], &pre1, &pre2, &transmission_clear, &ptr2);\n\n      /* Transmission of the layer*/\n      transmission_layer = output->cf.cf[lc] * transmission_cloud + (1.0 - output->cf.cf[lc]) * transmission_clear;\n\n      /*    fprintf (stderr,  */\n      /*    \"transmission_cloud %g, transmission_clear %g, transmission_layer %g cloud cover %g \\n\",   */\n      /*         transmission_cloud, transmission_clear, transmission_layer, output->cf.cf[lc+1]);  */\n\n      /* Calculate effective optical thickness */\n      taueff = zbrent_taueff (mu_eff,\n                              g[lc],\n                              ssa[lc],\n                              transmission_cloud,\n                              transmission_layer,\n                              tau_clear,\n                              tau[lc],\n                              0.00001); /* in solve_rte.c, next function */\n\n      /*         fprintf (stderr, \"test %d %g  %g %g %g %g %g %g %g \\n\", lc, */\n      /*                  output->atm.zd[lc]+output->alt.altitude, tau[lc], mu_eff,   */\n      /*                  output->cf.cf[lc], transmission_cloud, transmission_clear,\n                          transmission_layer, taueff); */\n      /*         if (taueff > 0 && taueff < 1e-7) */\n\n      if (verbose)\n        fprintf (stderr, \"  %g\\n\", taueff);\n\n      /* Set the optical properties to be used in rte calculation.*/\n\n      /* wc is now representing both, water and ice clouds */\n      output->caoth[input.i_wc].optprop.dtau[iv][lc] = taueff;\n      output->caoth[input.i_wc].optprop.g1[iv][lc]   = g[lc];\n      output->caoth[input.i_wc].optprop.g2[iv][lc]   = 0.0;\n      output->caoth[input.i_wc].optprop.ff[iv][lc]   = 1.0;\n      output->caoth[input.i_wc].optprop.ssa[iv][lc]  = ssa[lc];\n\n      /* ic is now not needed any more */\n      output->caoth[input.i_ic].optprop.dtau[iv][lc] = 0.0;\n      output->caoth[input.i_ic].optprop.g1[iv][lc]   = 0.0;\n      output->caoth[input.i_ic].optprop.g2[iv][lc]   = 0.0;\n      output->caoth[input.i_ic].optprop.ff[iv][lc]   = 0.0;\n      output->caoth[input.i_ic].optprop.ssa[iv][lc]  = 0.0;\n\n    } else {\n      /* wc is now representing both, water and ice clouds */\n      output->caoth[input.i_wc].optprop.dtau[iv][lc] = 0.0;\n      output->caoth[input.i_wc].optprop.g1[iv][lc]   = 0.0;\n      output->caoth[input.i_wc].optprop.g2[iv][lc]   = 0.0;\n      output->caoth[input.i_wc].optprop.ff[iv][lc]   = 0.0;\n      output->caoth[input.i_wc].optprop.ssa[iv][lc]  = 0.0;\n\n      /* ic is now not needed any more */\n      output->caoth[input.i_ic].optprop.dtau[iv][lc] = 0.0;\n      output->caoth[input.i_ic].optprop.g1[iv][lc]   = 0.0;\n      output->caoth[input.i_ic].optprop.g2[iv][lc]   = 0.0;\n      output->caoth[input.i_ic].optprop.ff[iv][lc]   = 0.0;\n      output->caoth[input.i_ic].optprop.ssa[iv][lc]  = 0.0;\n    }\n  }\n\n  free (ssa);\n  free (tau);\n  free (g);\n  return 0;\n}\n\n/** \n * *zbrent_taueff* returns the effective optical depth of a layer.\n *\n * The function is a slightly modified version of the \"zbrent\" function in the \n * \"Numerical Recipes in C\" (p. 352 ff.) for finding roots of an arbitrary function. \n * The function is here the ECHAM radiative tarnsfer routine swde.f and the root of it \n * is the effective optical thickness.\n * \n * @param mu_eff effective zenith angle\n * @param g asymmetry parameter\n * @param ssa single scattering albedo\n * @param transmission_cloud transmission cloudy part\n * @param transmission_layer total transmission\n * @param x1 clear optical depth\n * @param x2 cloudy optical depth\n * @param tol accuracy\n * \n * @return effective tau\n */\nfloat zbrent_taueff (float mu_eff,\n                     float g,\n                     float ssa,\n                     float transmission_cloud,\n                     float transmission_layer,\n                     float x1,\n                     float x2,\n                     float tol) {\n  int   iter = 0;\n  float a = x1, b = x2, c = x2, d = 0, e = 0, min1 = 0, min2 = 0;\n  float fa = 0, fb = 0;\n  float fc = 0, p = 0, q = 0, r = 0, s = 0, tol1 = 0, xm = 0;\n  int   itmax = 100;\n  float eps   = 3.0e-8;\n  float dummy = 0.0;\n  float pref  = 0.0;\n\n  F77_FUNC (swde, SWDE) (&g, &pref, &mu_eff, &x1, &ssa, &dummy, &dummy, &transmission_cloud, &dummy);\n  fa = transmission_cloud - transmission_layer;\n\n  dummy = 0.0;\n  pref  = 0.0;\n  F77_FUNC (swde, SWDE) (&g, &pref, &mu_eff, &x2, &ssa, &dummy, &dummy, &transmission_cloud, &dummy);\n  fb = transmission_cloud - transmission_layer;\n\n  if ((fa > 0.0 && fb > 0.0) || (fa < 0.0 && fb < 0.0)) {\n    fprintf (stderr, \"Root must be bracketed in zbrent \\n\");\n    fprintf (stderr, \"Please check whether the cloud effective optical thickness has been \\n\");\n    fprintf (stderr, \"calculated correctly. \\n\");\n  }\n  fc = fb;\n  for (iter = 1; iter <= itmax; iter++) {\n    if ((fb > 0.0 && fc > 0.0) || (fb < 0.0 && fc < 0.0)) {\n      c  = a;\n      fc = fa;\n      e = d = b - a;\n    }\n    if (fabs (fc) < fabs (fb)) {\n      a  = b;\n      b  = c;\n      c  = a;\n      fa = fb;\n      fb = fc;\n      fc = fa;\n    }\n    tol1 = 2.0 * eps * fabs (b) + 0.5 * tol;\n    xm   = 0.5 * (c - b);\n    if (fabs (xm) <= tol1 || fb == 0.0)\n      return b;\n    if (fabs (e) >= tol1 && fabs (fa) > fabs (fb)) {\n      s = fb / fa;\n      if (a == c) {\n        p = 2.0 * xm * s;\n        q = 1.0 - s;\n      } else {\n        q = fa / fc;\n        r = fb / fc;\n        p = s * (2.0 * xm * q * (q - r) - (b - a) * (r - 1.0));\n        q = (q - 1.0) * (r - 1.0) * (s - 1.0);\n      }\n      if (p > 0.0)\n        q = -q;\n      p    = fabs (p);\n      min1 = 3.0 * xm * q - fabs (tol1 * q);\n      min2 = fabs (e * q);\n      if (2.0 * p < (min1 < min2 ? min1 : min2)) {\n        e = d;\n        d = p / q;\n      } else {\n        d = xm;\n        e = d;\n      }\n    } else {\n      d = xm;\n      e = d;\n    }\n    a  = b;\n    fa = fb;\n    if (fabs (d) > tol1)\n      b += d;\n    else\n      b += SIGN (tol1, xm);\n\n    dummy = 0.0;\n    pref  = 0.0;\n    F77_FUNC (swde, SWDE) (&g, &dummy, &mu_eff, &b, &ssa, &dummy, &dummy, &transmission_cloud, &dummy);\n    fb = transmission_cloud - transmission_layer;\n  }\n  fprintf (stderr, \"Maximum number of iterations exceeded in zbrent \\n\");\n  return 0.0;\n}\n\nstatic int set_raman_source (double***              qsrc,\n                             double***              qsrcu,\n                             int                    maxphi,\n                             int                    nlev,\n                             int                    nzout,\n                             int                    nstr,\n                             int                    n_shifts,\n                             float                  wanted_wl,\n                             double*                wl_shifts,\n                             float                  umu0,\n                             float*                 zd,\n                             float*                 zout,\n                             float                  zenang,\n                             float                  fbeam,\n                             float                  radius,\n                             float*                 dens,\n                             double**               crs_RL,\n                             double**               crs_RG,\n                             float*                 ssalb,\n                             int                    numu,\n                             float*                 umu,\n                             int                    usrang,\n                             int*                   cmuind,\n                             float***               pmom,\n                             raman_qsrc_components* raman_qsrc_comp,\n                             int*                   zout_comp_index,\n                             float                  altitude,\n                             int                    last,\n                             int                    verbose) {\n\n  /* Equation numbers in this function refer to equations in ESAS-LIGHT */\n  /* report for WP2200.                                                 */\n\n  int status = 0, twonm1, test = 0;\n#if HAVE_SOS\n  int* nfac = NULL;\n#endif\n\n  int static first = 1, nlyr = 0;\n  int            lu = 0, lua = 0, lub = 0, lv = 0, iq = 0, iu = 0, jq = 0, k = 0, l = 0, nn = 0, lc = 0, maz = 0, is = 0;\n  double         sum = 0, sum1 = 0, sum2 = 0, sum3 = 0, sum4 = 0;\n  double static *cmu = NULL, *cwt = NULL, ***ylmc = NULL, ***ylmu = NULL, ***ylm0 = NULL, sgn = 0, *tmpumu = NULL;\n  double *       tmp = NULL, *tmpylmc = NULL, *tmpylmu = NULL, *tmpylm0 = NULL;\n  double static *trs = NULL, **trs_shifted = NULL, *tmp_shifted = NULL, *tmp_dtauc = NULL, *chtau = NULL;\n  double static* tmp_dtauc_shifted = NULL;\n  double static *tmp_dens = NULL, *tmp_dens_org = NULL, **tmp_crs_RG = NULL, **tmp_crs_RL = NULL;\n  double static *tmp_in = NULL, *tmp_out = NULL;\n\n  double static *tmp_cumtau = NULL, *tmp_cumtauint = NULL, **tmp_user_dtauc = NULL, *tmp_zd = NULL, *tmp_zd_org = NULL;\n  int static ntmp_zd = 0;\n\n#if HAVE_SOS\n  double static** fac = NULL;\n#endif\n\n  double g2_R   = 1 / 100.;      /* Legendre expansion coefficients for Raman scattering */\n  double PI_R_b = 0, PI_R_d = 0; /* PIs in Eq. (28)-(29) */\n  double ssalbRL = 0;            /* ssalb for Raman loss, Eq. (40) in Spurr et al 2008 */\n  double ssalbRG = 0;            /* ssalb for Raman gain, Eq. (39) in Spurr et al 2008 */\n  double deltaz = 0, km2cm = 1E+5;\n  ;\n  double delm0       = 1;\n  double crs_RL_tot  = 0;\n  double crs_RG_tot  = 0;\n  double lambda_fact = 0; /* Conversion factor lambdap**2/lambda**2, Eq. A3 Edgington et al. 1999 */\n\n  if (first) {\n\n    nlyr    = nlev - 1;\n    ntmp_zd = nlev;\n\n    /* Need quadrature angles and weights and Legendre polynomials */\n\n    cmu = (double*)calloc (nstr, sizeof (double));\n    cwt = (double*)calloc (nstr, sizeof (double));\n    nn  = nstr / 2;\n\n    c_gaussian_quadrature (nn, cmu, cwt);\n\n    /* Rearrange cmu and cwt such that they are ascending order. qsrc  should */\n    /* have cmu in ascending order, however, internally qdisort does not treat*/\n    /* cmu in ascending order. This feature is inherited from disort.         */\n    for (iq = 0; iq < nn; iq++) {\n      cmu[nn + iq] = cmu[iq];\n      cwt[nn + iq] = cwt[iq];\n    }\n    for (iq = 0; iq < nn; iq++) {\n      cmu[iq] = -cmu[nstr - 1 - iq];\n      cwt[iq] = cwt[nstr - 1 - iq];\n    }\n\n    /* Calculate Legendre polynomials for each m */\n    if ((tmpylmc = (double*)calloc ((size_t) ((nstr + 1) * nstr), sizeof (double))) == NULL)\n      return ASCII_NO_MEMORY;\n    if ((tmpylm0 = (double*)calloc ((size_t) ((nstr + 1) * nstr), sizeof (double))) == NULL)\n      return ASCII_NO_MEMORY;\n    if ((status = ASCII_calloc_double_3D (&ylmc, nstr, nstr, nstr + 1)) != 0)\n      return ASCII_NO_MEMORY;\n    if ((status = ASCII_calloc_double_3D (&ylm0, nstr, nstr, nstr + 1)) != 0)\n      return ASCII_NO_MEMORY;\n    if (usrang) {\n      if ((tmpylmu = (double*)calloc ((size_t) ((nstr + 1) * numu), sizeof (double))) == NULL)\n        return ASCII_NO_MEMORY;\n      if ((status = ASCII_calloc_double_3D (&ylmu, nstr, numu, nstr + 1)) != 0)\n        return ASCII_NO_MEMORY;\n    }\n    for (maz = 0; maz < nstr; maz++) {\n      twonm1 = nstr - 1;\n      nn     = 1;\n      if ((tmp = (double*)calloc ((size_t) (1), sizeof (double))) == NULL)\n        return ASCII_NO_MEMORY;\n      tmp[0] = -umu0;\n      c_legendre_poly (nn, maz, nstr, twonm1, tmp, tmpylm0);\n      free (tmp);\n      fortran2c_2D_double_ary_noalloc (nstr, nstr + 1, tmpylm0, ylm0[maz]);\n\n      nn = nstr / 2;\n      c_legendre_poly (nn, maz, nstr, twonm1, cmu, tmpylmc);\n      fortran2c_2D_double_ary_noalloc (nstr, nstr + 1, tmpylmc, ylmc[maz]);\n\n      /* Evaluate Legendre polynomials with negative -cmu- from those with*/\n      /* positive -cmu-;  Dave Armstrong Eq. (15) */\n      sgn = -1.0;\n      for (l = 0; l < nstr; l++) {\n        sgn = -sgn;\n        for (iq = nn; iq < nstr; iq++) {\n          ylmc[maz][iq][l] = sgn * ylmc[maz][nstr - 1 - iq][l];\n        }\n      }\n\n      if (usrang) {\n        if ((tmpumu = (double*)calloc ((size_t) (numu), sizeof (double))) == NULL) {\n          status = ASCII_NO_MEMORY;\n          fprintf (stderr,\n                   \"Unable to allocate memory for tmpumu, status: %d returned at (line %d, function %s in %s)\\n\",\n                   status,\n                   __LINE__,\n                   __func__,\n                   __FILE__);\n          return status;\n        }\n        for (iu = 0; iu < numu; iu++)\n          tmpumu[iu] = umu[iu];\n        c_legendre_poly (numu, maz, nstr, twonm1, tmpumu, tmpylmu);\n        fortran2c_2D_double_ary_noalloc (numu, nstr + 1, tmpylmu, ylmu[maz]);\n        free (tmpumu);\n      }\n    }\n    free (tmpylmc);\n    free (tmpylm0);\n    if (usrang) {\n      free (tmpylmu);\n    }\n\n    if ((trs = (double*)calloc ((size_t) (ntmp_zd), sizeof (double))) == NULL) {\n      status = ASCII_NO_MEMORY;\n      fprintf (stderr,\n               \"Unable to allocate memory for trs, status: %d returned at (line %d, function %s in %s)\\n\",\n               status,\n               __LINE__,\n               __func__,\n               __FILE__);\n      return status;\n    }\n\n    if ((status = ASCII_calloc_double (&trs_shifted, ntmp_zd, n_shifts)) != 0) {\n      fprintf (stderr,\n               \"Unable to allocate memory for trs_shifted, status: %d returned at (line %d, function %s in %s)\\n\",\n               status,\n               __LINE__,\n               __func__,\n               __FILE__);\n      return status;\n    }\n\n    if ((chtau = (double*)calloc ((size_t) (ntmp_zd), sizeof (double))) == NULL) {\n      status = ASCII_NO_MEMORY;\n      fprintf (stderr,\n               \"Unable to allocate memory for chtau, status: %d returned at (line %d, function %s in %s)\\n\",\n               status,\n               __LINE__,\n               __func__,\n               __FILE__);\n      return status;\n    }\n\n    if ((tmp_dtauc = (double*)calloc ((size_t) (ntmp_zd), sizeof (double))) == NULL) {\n      status = ASCII_NO_MEMORY;\n      fprintf (stderr,\n               \"Unable to allocate memory for tmp_dtauc, status: %d returned at (line %d, function %s in %s)\\n\",\n               status,\n               __LINE__,\n               __func__,\n               __FILE__);\n      return status;\n    }\n\n    if ((tmp_dens = (double*)calloc ((size_t) (ntmp_zd), sizeof (double))) == NULL) {\n      status = ASCII_NO_MEMORY;\n      fprintf (stderr,\n               \"Unable to allocate memory for tmp_dens, status: %d returned at (line %d, function %s in %s)\\n\",\n               status,\n               __LINE__,\n               __func__,\n               __FILE__);\n      return status;\n    }\n\n    if ((tmp_dens_org = (double*)calloc ((size_t) (nlev), sizeof (double))) == NULL) {\n      status = ASCII_NO_MEMORY;\n      fprintf (stderr,\n               \"Unable to allocate memory for tmp_dens_org, status: %d returned at (line %d, function %s in %s)\\n\",\n               status,\n               __LINE__,\n               __func__,\n               __FILE__);\n      return status;\n    }\n\n    if ((tmp_dtauc_shifted = (double*)calloc ((size_t) (ntmp_zd), sizeof (double))) == NULL) {\n      status = ASCII_NO_MEMORY;\n      fprintf (stderr,\n               \"Unable to allocate memory for tmp_dtauc_shifted, status: %d returned at (line %d, function %s in %s)\\n\",\n               status,\n               __LINE__,\n               __func__,\n               __FILE__);\n      return status;\n    }\n\n    if ((tmp_in = (double*)calloc ((size_t) (nzout), sizeof (double))) == NULL) {\n      status = ASCII_NO_MEMORY;\n      fprintf (stderr,\n               \"Unable to allocate memory for tmp_in, status: %d returned at (line %d, function %s in %s)\\n\",\n               status,\n               __LINE__,\n               __func__,\n               __FILE__);\n      return status;\n    }\n\n    if ((tmp_out = (double*)calloc ((size_t) (ntmp_zd), sizeof (double))) == NULL) {\n      status = ASCII_NO_MEMORY;\n      fprintf (stderr,\n               \"Unable to allocate memory for tmp_out, status: %d returned at (line %d, function %s in %s)\\n\",\n               status,\n               __LINE__,\n               __func__,\n               __FILE__);\n      return status;\n    }\n\n    if ((tmp_shifted = (double*)calloc ((size_t) (ntmp_zd), sizeof (double))) == NULL) {\n      status = ASCII_NO_MEMORY;\n      fprintf (stderr,\n               \"Unable to allocate memory for tmp_shifted, status: %d returned at (line %d, function %s in %s)\\n\",\n               status,\n               __LINE__,\n               __func__,\n               __FILE__);\n      return status;\n    }\n\n    if ((status = ASCII_calloc_double (&tmp_crs_RG, ntmp_zd, n_shifts)) != 0) {\n      fprintf (stderr, \"Error %d allocating memory for crs_RG \\n\", status);\n      fprintf (stderr, \"       (line %d, function '%s' in '%s')\\n\", __LINE__, __func__, __FILE__);\n      return status;\n    }\n\n    if ((status = ASCII_calloc_double (&tmp_crs_RL, ntmp_zd, n_shifts)) != 0) {\n      fprintf (stderr, \"Error %d allocating memory for crs_RG \\n\", status);\n      fprintf (stderr, \"       (line %d, function '%s' in '%s')\\n\", __LINE__, __func__, __FILE__);\n      return status;\n    }\n\n    if ((status = ASCII_calloc_double (&tmp_user_dtauc, ntmp_zd, n_shifts + 1)) != 0) {\n      fprintf (stderr,\n               \"Unable to allocate memory for user_dtauc, status: %d returned at (line %d, function %s in %s)\\n\",\n               status,\n               __LINE__,\n               __func__,\n               __FILE__);\n      return status;\n    }\n\n    first = 0;\n\n  } /* if ( first ) */\n\n  /* Find all unique altitudes */\n  ntmp_zd = nlev;\n  if ((tmp_zd = calloc (ntmp_zd, sizeof (double))) == NULL) {\n    fprintf (stderr, \"Error, allocating memory for tmp_zd\\n\");\n    fprintf (stderr, \"      (line %d, function %s in %s)  \\n\", __LINE__, __func__, __FILE__);\n    return -1;\n  }\n  if ((tmp_zd_org = calloc (nlyr + 1, sizeof (double))) == NULL) {\n    fprintf (stderr, \"Error, allocating memory for tmp_zd_org\\n\");\n    fprintf (stderr, \"      (line %d, function %s in %s)  \\n\", __LINE__, __func__, __FILE__);\n    return -1;\n  }\n  for (lc = 0; lc <= nlyr; lc++) {\n    tmp_zd_org[lc]   = (double)zd[lc];\n    tmp_dens_org[lc] = (double)dens[lc];\n  }\n\n  lv = 0;\n  for (lu = 0; lu < nlev - 1; lu++) {\n    if (zd[lu] >= 0.0)\n      tmp_zd[lv++] = (double)zd[lu];\n  }\n\n  if (zd[nlev] < 0.0)\n    tmp_zd[lv] = 0.0;\n  else\n    tmp_zd[lv] = (double)zd[nlev];\n\n    // aky20042012 removed this, made source zero at bottom level if altitude was set different from level.\n    // Probably a leftover from when source varied within layers and forgotten to clean up.....\n    //  if ( altitude != 0) {\n    //aky    ntmp_zd = lv;  /* Number of output levels may be reduced due to altitude option */\n    // }\n\n#if HAVE_SOS\n  /* Calculate geometric correction factor needed for chapman function */\n  if ((nfac = (int*)calloc ((size_t) (ntmp_zd - 1), sizeof (int))) == NULL)\n    return ASCII_NO_MEMORY;\n  if ((status = ASCII_calloc_double (&fac, ntmp_zd - 1, 2 * (ntmp_zd - 1))) != 0)\n    return status;\n\n  /* Share dtauc from zd layering to zout */\n  for (lu = 0; lu < ntmp_zd - 1; lu++)\n    tmp_dtauc[lu] = raman_qsrc_comp->dtauc[lu][n_shifts];\n\n  chtau[0] = 0;\n  for (lc = 1; lc <= ntmp_zd - 1; lc++)\n    chtau[lc] = c_chapman_simpler (lc, 0.5, ntmp_zd, tmp_zd, tmp_dtauc, zenang, radius);\n\n  /* Transmittance of the atmosphere at wanted wavelength */\n  trans_double (ntmp_zd - 1, chtau, trs);\n\n  for (is = 0; is < n_shifts; is++) {\n\n    for (lu = 0; lu < ntmp_zd - 1; lu++) {\n      tmp_dtauc_shifted[lu] = raman_qsrc_comp->dtauc[lu][is];\n    }\n\n    chtau[0] = 0;\n    for (lc = 1; lc <= ntmp_zd - 1; lc++)\n      chtau[lc] = c_chapman_simpler (lc, 0.5, ntmp_zd, tmp_zd, tmp_dtauc_shifted, zenang, radius);\n    trans_double (ntmp_zd - 1, chtau, tmp_shifted);\n    for (lu = 0; lu < ntmp_zd; lu++)\n      trs_shifted[lu][is] = tmp_shifted[lu];\n  }\n\n#else\n  fprintf (stderr, \"Error, need SOS source code for Raman scattering!\\n\");\n  return -1;\n#endif\n\n  /* Interpolate density and Raman cross sections from zd to zout grid */\n  status = arb_wvn_double (nlev, tmp_zd_org, tmp_dens_org, ntmp_zd, tmp_zd, tmp_dens, INTERP_METHOD_LOG, 1);\n\n  for (is = 0; is < n_shifts; is++) {\n    for (lu = 0; lu < nlev; lu++)\n      tmp_in[lu] = crs_RG[lu][is];\n    status = arb_wvn_double (nlev, tmp_zd_org, tmp_in, ntmp_zd, tmp_zd, tmp_out, INTERP_METHOD_LINEAR, 1);\n    for (lu = 0; lu < ntmp_zd; lu++)\n      tmp_crs_RG[lu][is] = tmp_out[lu];\n  }\n  for (is = 0; is < n_shifts; is++) {\n    for (lu = 0; lu < nlev; lu++)\n      tmp_in[lu] = crs_RL[lu][is];\n    status = arb_wvn_double (nlev, tmp_zd_org, tmp_in, ntmp_zd, tmp_zd, tmp_out, INTERP_METHOD_LINEAR, 1);\n    for (lu = 0; lu < ntmp_zd; lu++)\n      tmp_crs_RL[lu][is] = tmp_out[lu];\n  }\n\n  test = 0;\n  if (test) {\n    /*************************************************************/\n    /* To check that all angles etc. are correctly treated test  */\n    /* with the direct beam source. This should give identical   */\n    /* results for the diffuse radiation as the first raman      */\n    /* wavelength loop                                           */\n    /*************************************************************/\n\n    delm0 = 1;\n    fbeam = 1;\n    for (maz = 0; maz < nstr; maz++) {\n      if (maz > 0)\n        delm0 = 0;\n      for (lu = 0; lu < nzout - 1; lu++) {\n        lc = lu;\n        for (iq = 0; iq < nstr; iq++) {\n          sum = 0;\n          for (k = maz; k < nstr; k++) {\n            sum += (2 * k + 1) * ssalb[lc] * pmom[lc][0][k] * ylmc[maz][iq][k] * ylm0[maz][0][k];\n          }\n          qsrc[maz][lu][iq] = sum * (2 - delm0) * fbeam / (4 * M_PI);\n          if (lu == nzout) { /* Set source at bottom level */\n            qsrc[maz][lu + 1][iq] = qsrc[maz][lu][iq] * trs[lu + 1];\n          }\n          qsrc[maz][lu][iq] = qsrc[maz][lu][iq] * trs[lu];\n        }\n        if (usrang) {\n          for (iu = 0; iu < numu; iu++) {\n            sum = 0;\n            for (k = maz; k < nstr; k++) {\n              sum += (2 * k + 1) * ssalb[lc] * pmom[lc][0][k] * ylmu[maz][iu][k] * ylm0[maz][0][k];\n            }\n            qsrcu[maz][lu][iu] = sum * (2 - delm0) * fbeam / (4 * M_PI);\n            if (lu == nzout - 2) { /* Set source at bottom level */\n              qsrcu[maz][lu + 1][iu] = qsrcu[maz][lu][iu] * trs[lu + 1];\n            }\n            qsrcu[maz][lu][iu] = qsrcu[maz][lu][iu] * trs[lu];\n          }\n        }\n      }\n    }\n  } else { /* Raman scattering source */\n\n    if (verbose)\n      fprintf (stderr,\n               \"Raman_src %1s  %2s %2s    %2s     %3s        %4s          %4s          %4s          %4s          %4s  %9s %9s \"\n               \"%9s %9s )\\n\",\n               \"m\",\n               \"lu\",\n               \"iq\",\n               \"zd\",\n               \"cmu\",\n               \"sum1\",\n               \"sum2\",\n               \"sum3\",\n               \"sum4\",\n               \"qsrc\",\n               \"ssalbRL\",\n               \"ssalbRG\",\n               \"PI_R_b\",\n               \"PI_R_d\");\n\n    delm0 = 1;\n\n    /* dtauc is not necessarily at all user altitudes. So first interpolate to all user altitudes.... */\n    if ((tmp_cumtau = (double*)calloc ((size_t) (ntmp_zd), sizeof (double))) == NULL)\n      return ASCII_NO_MEMORY;\n    if ((tmp_cumtauint = (double*)calloc ((size_t) (ntmp_zd), sizeof (double))) == NULL)\n      return ASCII_NO_MEMORY;\n\n    for (is = 0; is <= n_shifts; is++) {\n\n      /* Start by calculating the cumulative optical depth. */\n      lu             = 0;\n      tmp_cumtau[lu] = 0.0;\n      for (lu = 1; lu < ntmp_zd; lu++)\n        tmp_cumtau[lu] = tmp_cumtau[lu - 1] + raman_qsrc_comp->dtauc[lu - 1][is];\n\n      /* Interpolate the cumulative optical depth to all user altitudes. */\n      status = arb_wvn_double (ntmp_zd, tmp_zd, tmp_cumtau, ntmp_zd, tmp_zd, tmp_cumtauint, INTERP_METHOD_LINEAR, 1);\n      /* Finally calculate the optical depth of each layer. */\n      lu                     = 0;\n      tmp_user_dtauc[lu][is] = 0.0;\n      for (lu = 1; lu < ntmp_zd; lu++)\n        tmp_user_dtauc[lu][is] = tmp_cumtauint[lu] - tmp_cumtauint[lu - 1];\n    }\n\n    free (tmp_cumtau);\n    free (tmp_cumtauint);\n\n    for (maz = 0; maz < nstr; maz++) {\n      if (maz > 0)\n        delm0 = 0;\n\n      for (lu = 1; lu < ntmp_zd; lu++) { /* No need to include first level as source is calculated at middle of layer */\n\n        lua = lu - 1;\n        lub = lu;\n\n        deltaz  = (tmp_zd[lua] - tmp_zd[lub]) * km2cm;\n        ssalbRL = 0;\n        //aky\ttmpsum=0.0;\n        for (is = 0; is < n_shifts; is++) {\n          //aky\t  ssalbRL += 0.5 * deltaz * (tmp_dens[lua]*tmp_crs_RL[lua][is] + tmp_dens[lub]*tmp_crs_RL[lub][is]) /\n          ssalbRL += deltaz * dlog_average (tmp_dens[lua] * tmp_crs_RL[lua][is], tmp_dens[lub] * tmp_crs_RL[lub][is]) /\n                     tmp_user_dtauc[lub][n_shifts];\n          //aky\t  tmpsum += dlog_average(tmp_crs_RL[lua][is], tmp_crs_RL[lub][is]);\n        }\n        verbose = 0;\n        if (verbose && maz == 0) {\n          crs_RL_tot = 0;\n          crs_RG_tot = 0;\n          for (is = 0; is < n_shifts; is++) {\n            crs_RL_tot += tmp_crs_RL[lu][is];\n            crs_RG_tot += tmp_crs_RG[lu][is];\n          }\n          fprintf (stderr, \"%3d, zout: %7.2f, crs_RL_tot: %13.6e, crs_RG_tot: %13.6e\\n\", lu, zout[lu], crs_RL_tot, crs_RG_tot);\n        }\n\n        for (iq = 0; iq < nstr; iq++) {\n          sum1 = 0;\n          sum2 = 0;\n          sum3 = 0;\n          sum4 = 0;\n\n          /* Calculate PI_R_b (Eq. 28) for Raman scattering */\n          if (maz == 0)\n            PI_R_b = ylmc[maz][iq][0] * ylm0[maz][0][0] + 5 * g2_R * ylmc[maz][iq][2] * ylm0[maz][0][2];\n          else if (maz == 1)\n            PI_R_b = -5 * g2_R * ylmc[maz][iq][2] * ylm0[maz][0][2];\n          else if (maz == 2)\n            PI_R_b = +5 * g2_R * ylmc[maz][iq][2] * ylm0[maz][0][2];\n          else\n            PI_R_b = 0;\n\n          /* First part of Raman scattering source term, Eq. (31). */\n\n          ssalbRG = 0;\n          for (is = 0; is < n_shifts; is++) {\n            lambda_fact = (wl_shifts[is] * wl_shifts[is]) / (wanted_wl * wanted_wl);\n            sum         = 0;\n            for (jq = 0; jq < nstr; jq++) {\n              /* Calculate  PI_R_d (Eq. 29) for Raman scattering */\n              if (maz == 0)\n                PI_R_d = ylmc[maz][iq][0] * ylmc[maz][jq][0] + 5 * g2_R * ylmc[maz][iq][2] * ylmc[maz][jq][2];\n              else if (maz == 1)\n                PI_R_d = +5 * g2_R * ylmc[maz][iq][2] * ylmc[maz][jq][2];\n              else if (maz == 2)\n                PI_R_d = +5 * g2_R * ylmc[maz][iq][2] * ylmc[maz][jq][2];\n              else\n                PI_R_d = 0;\n\n              sum += cwt[jq] * PI_R_d * raman_qsrc_comp->uum[zout_comp_index[lub]][maz][cmuind[jq]][is];\n            }\n            //aky\t    ssalbRG = 0.5 * deltaz * lambda_fact * (tmp_dens[lua] * tmp_crs_RG[lua][is] +\n            //aky\t\t\t\t      tmp_dens[lub] * tmp_crs_RG[lub][is]) /\n            ssalbRG = deltaz * lambda_fact *\n                      dlog_average (tmp_dens[lua] * tmp_crs_RG[lua][is], tmp_dens[lub] * tmp_crs_RG[lub][is]) /\n                      tmp_user_dtauc[lub][n_shifts];\n\n            sum1 += ssalbRG * sum;\n          }\n          sum1 *= +1. / 2.;\n\n          /* Second part of Raman scattering source term, Eq. (31). */\n\n          for (is = 0; is < n_shifts; is++) {\n            lambda_fact = (wl_shifts[is] * wl_shifts[is]) / (wanted_wl * wanted_wl);\n            //aky\t    ssalbRG = 0.5 * deltaz * (tmp_dens[lua] * tmp_crs_RG[lua][is] + tmp_dens[lub] *\n            //aky\t\t\t\t      tmp_crs_RG[lub][is]) / tmp_user_dtauc[lub][n_shifts];\n            ssalbRG = deltaz * dlog_average (tmp_dens[lua] * tmp_crs_RG[lua][is], tmp_dens[lub] * tmp_crs_RG[lub][is]) /\n                      tmp_user_dtauc[lub][n_shifts];\n\n            sum2 += raman_qsrc_comp->fbeam[is] * ssalbRG * trs_shifted[lub][is] * lambda_fact;\n          }\n          sum2 *= +((2 - delm0) / (4 * M_PI)) * PI_R_b;\n\n          /* Third part of Raman scattering source term, Eq. (31). */\n\n          sum = 0;\n          for (jq = 0; jq < nstr; jq++) {\n            /* Calculate  PI_R_d (Eq. 29) for Raman scattering */\n            if (maz == 0)\n              PI_R_d = ylmc[maz][iq][0] * ylmc[maz][jq][0] + 5 * g2_R * ylmc[maz][iq][2] * ylmc[maz][jq][2];\n            else if (maz == 1)\n              PI_R_d = +5 * g2_R * ylmc[maz][iq][2] * ylmc[maz][jq][2];\n            else if (maz == 2)\n              PI_R_d = +5 * g2_R * ylmc[maz][iq][2] * ylmc[maz][jq][2];\n            else\n              PI_R_d = 0;\n\n            sum += cwt[jq] * PI_R_d * raman_qsrc_comp->uum[zout_comp_index[lub]][maz][cmuind[jq]][n_shifts];\n          }\n\n          sum3 = -(ssalbRL / 2) * sum;\n\n          /* Fourth part of Raman scattering source term, Eq. (31). */\n\n          sum4 = -((ssalbRL * fbeam) / (4 * M_PI)) * (2 - delm0) * PI_R_b * trs[lub];\n\n          qsrc[maz][lu - 1][iq] = sum1 + sum2 + sum3 + sum4; /* lu starts at 1, source index is one less */\n\n          //aky\t  verbose = 0;\n          if (verbose) {\n            if (maz == 0 && iq == 0)\n              fprintf (stderr,\n                       \"Raman_src %2d %2d %2d %7.3f %7.3f %13.6e %13.6e %13.6e %13.6e %13.6e %13.6e %13.6e  %7.3f %7.3f %13.6e\\n\",\n                       maz,\n                       lu,\n                       iq,\n                       zout[lu],\n                       cmu[iq],\n                       sum1,\n                       sum2,\n                       sum3,\n                       sum4,\n                       qsrc[maz][lu - 1][iq],\n                       ssalbRL,\n                       ssalbRG,\n                       PI_R_b,\n                       PI_R_d,\n                       trs[lu]);\n          }\n\n        } /* for (iq=0;iq<nstr;iq++) */\n\n        if (usrang) {\n          /* Also have to calculate the source for all user angles */\n          for (iu = 0; iu < numu; iu++) {\n            sum1 = 0;\n            sum2 = 0;\n            sum3 = 0;\n            sum4 = 0;\n\n            /* Calculate PI_R_b (Eq. 28) for Raman scattering */\n            if (maz == 0)\n              PI_R_b = ylmu[maz][iu][0] * ylm0[maz][0][0] + 5 * g2_R * ylmu[maz][iu][2] * ylm0[maz][0][2];\n            else if (maz == 1)\n              PI_R_b = -5 * g2_R * ylmu[maz][iu][2] * ylm0[maz][0][2];\n            else if (maz == 2)\n              PI_R_b = +5 * g2_R * ylmu[maz][iu][2] * ylm0[maz][0][2];\n            else\n              PI_R_b = 0;\n\n            /* First part of Raman scattering source term, Eq. (31). */\n\n            ssalbRG = 0;\n            for (is = 0; is < n_shifts; is++) {\n              sum = 0;\n              for (jq = 0; jq < nstr; jq++) {\n                /* Calculate  PI_R_d (Eq. 29) for Raman scattering */\n                if (maz == 0)\n                  PI_R_d = ylmu[maz][iu][0] * ylmc[maz][jq][0] + 5 * g2_R * ylmu[maz][iu][2] * ylmc[maz][jq][2];\n                else if (maz == 1)\n                  PI_R_d = +5 * g2_R * ylmu[maz][iu][2] * ylmc[maz][jq][2];\n                else if (maz == 2)\n                  PI_R_d = +5 * g2_R * ylmu[maz][iu][2] * ylmc[maz][jq][2];\n                else\n                  PI_R_d = 0;\n\n                sum += cwt[jq] * PI_R_d * raman_qsrc_comp->uum[zout_comp_index[lub]][maz][cmuind[jq]][is];\n              }\n              //aky\t      ssalbRG = 0.5 * deltaz * (tmp_dens[lua] * tmp_crs_RG[lua][is] + tmp_dens[lub] *\n              //aky\t\t\t\t\ttmp_crs_RG[lub][is])/\n              ssalbRG = deltaz * dlog_average (tmp_dens[lua] * tmp_crs_RG[lua][is], tmp_dens[lub] * tmp_crs_RG[lub][is]) /\n                        tmp_user_dtauc[lub][n_shifts];\n\n              sum1 += ssalbRG * sum;\n            }\n            sum1 *= +1. / 2.;\n\n            /* Second part of Raman scattering source term, Eq. (31). */\n\n            for (is = 0; is < n_shifts; is++) {\n              //aky\t      ssalbRG = 0.5 * deltaz * (tmp_dens[lua] * tmp_crs_RG[lua][is] + tmp_dens[lub] *\n              //aky\t\t\t\t\ttmp_crs_RG[lub][is])/tmp_user_dtauc[lub][n_shifts];\n              ssalbRG = deltaz * dlog_average (tmp_dens[lua] * tmp_crs_RG[lua][is], tmp_dens[lub] * tmp_crs_RG[lub][is]) /\n                        tmp_user_dtauc[lub][n_shifts];\n\n              sum2 += raman_qsrc_comp->fbeam[is] * ssalbRG * trs_shifted[lub][is];\n            }\n            sum2 *= +((2 - delm0) / (4 * M_PI)) * PI_R_b;\n\n            /* Third part of Raman scattering source term, Eq. (31). */\n\n            sum = 0;\n            for (jq = 0; jq < nstr; jq++) {\n              /* Calculate  PI_R_d (Eq. 29) for Raman scattering */\n              if (maz == 0)\n                PI_R_d = ylmu[maz][iu][0] * ylmc[maz][jq][0] + 5 * g2_R * ylmu[maz][iu][2] * ylmc[maz][jq][2];\n              else if (maz == 1)\n                PI_R_d = +5 * g2_R * ylmu[maz][iu][2] * ylmc[maz][jq][2];\n              else if (maz == 2)\n                PI_R_d = +5 * g2_R * ylmu[maz][iu][2] * ylmc[maz][jq][2];\n              else\n                PI_R_d = 0;\n              sum += cwt[jq] * PI_R_d * raman_qsrc_comp->uum[zout_comp_index[lub]][maz][cmuind[jq]][n_shifts];\n            }\n            sum3 = -(ssalbRL / 2) * sum;\n\n            /* Fourth part of Raman scattering source term, Eq. (31). */\n\n            sum4 = -((ssalbRL * fbeam) / (4 * M_PI)) * (2 - delm0) * PI_R_b * trs[lub];\n\n            qsrcu[maz][lu - 1][iu] = sum1 + sum2 + sum3 + sum4; /* lu starts at 1, source index is one less */\n\n            verbose = 0;\n            if (verbose) {\n              if (maz == 0 && iu == 0)\n                fprintf (stderr,\n                         \"Raman_srcu %2d %2d %2d %7.3f %7.3f %13.6e %13.6e %13.6e %13.6e %13.6e  %13.6e %13.6e  %7.3f %7.3f\\n\",\n                         maz,\n                         lu,\n                         iu,\n                         zout[lu],\n                         umu[iu],\n                         sum1,\n                         sum2,\n                         sum3,\n                         sum4,\n                         qsrcu[maz][lu][iu],\n                         ssalbRL,\n                         ssalbRG,\n                         PI_R_b,\n                         PI_R_d);\n            }\n          } /* for (iq=0;iq<nstr;iq++) */\n        }   /* if ( usrang ) {  */\n      }     /* for (lu=0;lu<nzout;lu++) */\n    }\n  }\n\n  free (tmp_zd);\n  free (tmp_zd_org);\n  free (nfac);\n  if (last) {\n    free (cmu);\n    free (cwt);\n  }\n\n  return status;\n}\n\n#undef NRANSI\n", "meta": {"hexsha": "3ac24798c76aad46fd63ecafc6778e81aa3e6581", "size": 362032, "ext": "c", "lang": "C", "max_stars_repo_path": "ubuntu20/projects/libRadtran-2.0.4/src/solve_rte.c", "max_stars_repo_name": "AmberCrafter/docker-compose_libRadtran", "max_stars_repo_head_hexsha": "0182f991db6a13e0cacb3bf9f43809e6850593e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ubuntu20/projects/libRadtran-2.0.4/src/solve_rte.c", "max_issues_repo_name": "AmberCrafter/docker-compose_libRadtran", "max_issues_repo_head_hexsha": "0182f991db6a13e0cacb3bf9f43809e6850593e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ubuntu20/projects/libRadtran-2.0.4/src/solve_rte.c", "max_forks_repo_name": "AmberCrafter/docker-compose_libRadtran", "max_forks_repo_head_hexsha": "0182f991db6a13e0cacb3bf9f43809e6850593e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.1506578181, "max_line_length": 176, "alphanum_fraction": 0.4879458169, "num_tokens": 97920, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41111086923216794, "lm_q2_score": 0.013636834279261852, "lm_q1q2_score": 0.005606250794122364}}
{"text": "// BSD 3-Clause License\n//\n// Copyright (c) 2018, Gregory Meyer\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions\n// are met:\n//\n// * Redistributions of source code must retain the above copyright\n//   notice, this list of conditions and the following disclaimer.\n//\n// * Redistributions in binary form must reproduce the above copyright\n//   notice, this list of conditions and the following disclaimer in\n//   the documentation and/or other materials provided with the\n//   distribution.\n//\n// * Neither the name of the copyright holder nor the names of its\n//   contributors may be used to endorse or promote products derived\n//   from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n// POSSIBILITY OF SUCH DAMAGE.\n\n#ifndef SWEEP_UTIL_TYPES_H\n#define SWEEP_UTIL_TYPES_H\n\n#include <cstdint>\n\n#include <gsl/gsl_util>\n\nnamespace sweep::util {\ninline namespace types {\n\nusing u8 = std::uint8_t;\nusing u16 = std::uint16_t;\nusing u32 = std::uint32_t;\nusing u64 = std::uint64_t;\n\nusing i8 = std::int8_t;\nusing i16 = std::int16_t;\nusing i32 = std::int32_t;\nusing i64 = std::int64_t;\n\nusing usize = std::size_t;\nusing isize = std::ptrdiff_t;\n\nusing f32 = float;\nusing f64 = double;\n\ninline namespace literals {\n\nconstexpr u8 operator\"\"_u8(unsigned long long x) noexcept {\n    return gsl::narrow_cast<u8>(x);\n}\n\nconstexpr u16 operator\"\"_u16(unsigned long long x) noexcept {\n    return gsl::narrow_cast<u16>(x);\n}\n\nconstexpr u32 operator\"\"_u32(unsigned long long x) noexcept {\n    return gsl::narrow_cast<u32>(x);\n}\n\nconstexpr u64 operator\"\"_u64(unsigned long long x) noexcept {\n    return gsl::narrow_cast<u64>(x);\n}\n\nconstexpr i8 operator\"\"_i8(unsigned long long x) noexcept {\n    return gsl::narrow_cast<i8>(x);\n}\n\nconstexpr i16 operator\"\"_i16(unsigned long long x) noexcept {\n    return gsl::narrow_cast<i16>(x);\n}\n\nconstexpr i32 operator\"\"_i32(unsigned long long x) noexcept {\n    return gsl::narrow_cast<i32>(x);\n}\n\nconstexpr i64 operator\"\"_i64(unsigned long long x) noexcept {\n    return gsl::narrow_cast<i64>(x);\n}\n\nconstexpr usize operator\"\"_usize(unsigned long long x) noexcept {\n    return gsl::narrow_cast<usize>(x);\n}\n\nconstexpr isize operator\"\"_isize(unsigned long long x) noexcept {\n    return gsl::narrow_cast<isize>(x);\n}\n\nconstexpr f32 operator\"\"_f32(long double x) noexcept {\n    return gsl::narrow_cast<f32>(x);\n}\n\nconstexpr f64 operator\"\"_f64(long double x) noexcept {\n    return gsl::narrow_cast<f64>(x);\n}\n\n} // inline namespace literals\n} // inline namespace types\n} // namespace sweep::util\n\n#endif\n", "meta": {"hexsha": "2e1d61fcd0c9af09d517a63b33339143eb140d1a", "size": 3404, "ext": "h", "lang": "C", "max_stars_repo_path": "include/sweep/util/types.h", "max_stars_repo_name": "Gregory-Meyer/minesweeper", "max_stars_repo_head_hexsha": "396e9bc23d2fd836618f5f562b9e9fb361ca9f4d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/sweep/util/types.h", "max_issues_repo_name": "Gregory-Meyer/minesweeper", "max_issues_repo_head_hexsha": "396e9bc23d2fd836618f5f562b9e9fb361ca9f4d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/sweep/util/types.h", "max_forks_repo_name": "Gregory-Meyer/minesweeper", "max_forks_repo_head_hexsha": "396e9bc23d2fd836618f5f562b9e9fb361ca9f4d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3448275862, "max_line_length": 71, "alphanum_fraction": 0.7391304348, "num_tokens": 824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.13117323734771857, "lm_q2_score": 0.04272219587060496, "lm_q1q2_score": 0.005604008738950587}}
{"text": "#ifndef __GSL_PERMUTE_VECTOR_H__\n#define __GSL_PERMUTE_VECTOR_H__\n\n#if !defined( GSL_FUN )\n#  if !defined( GSL_DLL )\n#    define GSL_FUN extern\n#  elif defined( BUILD_GSL_DLL )\n#    define GSL_FUN extern __declspec(dllexport)\n#  else\n#    define GSL_FUN extern __declspec(dllimport)\n#  endif\n#endif\n\n#include <gsl/gsl_permute_vector_complex_long_double.h>\n#include <gsl/gsl_permute_vector_complex_double.h>\n#include <gsl/gsl_permute_vector_complex_float.h>\n\n#include <gsl/gsl_permute_vector_long_double.h>\n#include <gsl/gsl_permute_vector_double.h>\n#include <gsl/gsl_permute_vector_float.h>\n\n#include <gsl/gsl_permute_vector_ulong.h>\n#include <gsl/gsl_permute_vector_long.h>\n\n#include <gsl/gsl_permute_vector_uint.h>\n#include <gsl/gsl_permute_vector_int.h>\n\n#include <gsl/gsl_permute_vector_ushort.h>\n#include <gsl/gsl_permute_vector_short.h>\n\n#include <gsl/gsl_permute_vector_uchar.h>\n#include <gsl/gsl_permute_vector_char.h>\n\n#endif /* __GSL_PERMUTE_VECTOR_H__ */\n", "meta": {"hexsha": "71604c9c4f25318fb578c4fa4bd7b66c1a13dacb", "size": 966, "ext": "h", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_permute_vector.h", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-28T08:20:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-28T08:20:20.000Z", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_permute_vector.h", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_permute_vector.h", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-14T12:45:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-14T12:45:35.000Z", "avg_line_length": 27.6, "max_line_length": 55, "alphanum_fraction": 0.8053830228, "num_tokens": 272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18242550602671442, "lm_q2_score": 0.03067580481225527, "lm_q1q2_score": 0.005596049215652389}}
{"text": "/* -*- C -*- */\n/**\n * Author: Pierre Schnizer\t\t\n * Date : January 2003\n */\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_math.h>\n#include <pygsl/general_helpers.h>\n#include <pygsl/utils.h>\n#include <pygsl/profile.h>\n\nPyGSL_API_EXTERN int\nPyGSL_set_error_string_for_callback(PyGSL_error_info * info)\n{\n     PyObject *name_o = NULL;\n     PyObject *callback;\n     const char * message = \"\";\n     const char * error_description = \"\";\n     const char * mmesg;\n     char * name, msg[1024];\n     char *formatstring = \"For the callback %s evaluted  for function %s, an error occured : %s\";\n\n     FUNC_MESS_BEGIN();    \n     callback = info->callback;\n     if(info->message){\n\t  message = info->message;          \n     }\n     if(info->error_description){\n\t  error_description = info->error_description;\n     }\n     \n\n     if (message == NULL){\n\t  mmesg = \"Unknown\";\n     }else{\n\t  mmesg = message;\n     }\n     assert(callback != NULL);\n     name_o = PyObject_GetAttrString(callback, \"__name__\");\n     if (name_o == NULL){\n\t  name_o = PyObject_GetAttrString(callback, \"func_name\");\n     }\n     if (name_o == NULL){\n\t PyErr_SetString(PyExc_AttributeError, \n\t\t\t \"While I was treating an errornous callback object,\"\n\t\t\t \" I found that it had no attribute '__name__'!\");\n\t PyGSL_ERROR(\"Could not get the name of the callback!\", GSL_EBADFUNC);\n\t goto fail;\n     }\n     if(!PyString_Check(name_o)){\n\t  PyErr_SetString(PyExc_TypeError, \n\t\t\t  \" For an errornous callback object,\"  \n\t\t\t  \" the attribute '__name__' was not a Python string!\");\n\t PyGSL_ERROR(\"Nameobject of the callback was not a string!\", GSL_EBADFUNC);\n\t goto fail;\n     }     \n     name = PyString_AsString(name_o);\n\n     /* A non completly standard but safe function. */\n     FUNC_MESS(\"\\tmakeing string\");\n     snprintf(msg, 1024, formatstring, name, mmesg, error_description);     \n     if(DEBUG > 2){\n\t  fprintf(stderr, \"ERROR: \\t%s\", msg);\n     }\n     PyGSL_ERROR(msg, GSL_EBADFUNC);\n\n     FUNC_MESS_END();\n     return GSL_EBADFUNC;\n     /* Py_XDECREF(name_o);  ??? */\n fail:\n     return GSL_EBADFUNC;\n     /* Py_XDECREF(name_o);  ??? */\n}\n\n\nPyGSL_API_EXTERN int \nPyGSL_pyfloat_to_double(PyObject *object, double *result, PyGSL_error_info *info)\n{\n     \n     PyObject *object1;\n     char *msg=\"The object returned to the GSL Function could not be converted to float\";\n\n     FUNC_MESS_BEGIN();\n     object1 = PyNumber_Float(object);\n     if(object1 == NULL){\n\t *result = gsl_nan();\n\t if(info){\n\t      info->error_description = msg;\n\t      return PyGSL_set_error_string_for_callback(info);\n\t }\n\t DEBUG_MESS(2, \"Not from call back treatment, normal error. info = %p\", info);\n\t PyGSL_ERROR(msg, GSL_EBADFUNC);\n     }\n\n     *result   = PyFloat_AsDouble(object1);\n     DEBUG_MESS(3, \"found a double of %f\\n\", *result);\n     Py_DECREF(object1);\n\n     PyGSL_INCREASE_float_transform_counter();\n     FUNC_MESS_END();\n     return GSL_SUCCESS;\n}\n\nPyGSL_API_EXTERN int \nPyGSL_pylong_to_uint(PyObject *object, unsigned int *result, PyGSL_error_info *info)\n{\n     int flag;\n     unsigned long int tmp;\n     flag =PyGSL_pylong_to_ulong(object, &tmp, info);\n     *result = (unsigned int) tmp;\n     return flag;\n}\n\n\nPyGSL_API_EXTERN int \nPyGSL_pylong_to_ulong(PyObject *object, unsigned long *result, PyGSL_error_info *info)\n{\n     \n     PyObject *object1;\n     char *msg=\"The object returned to the GSL Function could not be converted to unsigned long\";\n\n\n     object1 = PyNumber_Long(object);\n     if(object1 == NULL){\n\t *result = 0;\n\t if(info){\n\t      info->error_description = msg;\n\t      return PyGSL_set_error_string_for_callback(info);\n\t }\n\t PyGSL_ERROR(msg, GSL_EINVAL);\n     }\n\n     *result   = PyLong_AsUnsignedLong(object1);\n     if(DEBUG>2){\n\t  fprintf(stderr, \"\\t\\t%s found a double of %ld\\n\", __FUNCTION__, *result);\n     }\n     Py_DECREF(object1);\n\n     PyGSL_INCREASE_float_transform_counter();\n\n     return GSL_SUCCESS;\n}\n\nPyGSL_API_EXTERN int \nPyGSL_pyint_to_int(PyObject *object, int *result, PyGSL_error_info *info)\n{\n     \n     PyObject *object1;\n     char *msg=\"The object returned to the GSL Function could not be converted to int\";\n     long tmp;\n\n     FUNC_MESS_BEGIN();\n     object1 = PyNumber_Int(object);\n     if(object1 == NULL){\n\t *result = INT_MIN;\n\t if(info){\n\t      info->error_description = msg;\n\t      return PyGSL_set_error_string_for_callback(info);\n\t }\n\t DEBUG_MESS(2, \"Not from call back treatment, normal error. info = %p\", info);\n\t PyGSL_ERROR(msg, GSL_EINVAL);\n     }\n\n     tmp = PyInt_AsLong(object1);\n     if(tmp > INT_MAX)\n\t  PyGSL_ERROR(\"Number too big for int\", GSL_EINVAL);\n     else if (tmp < INT_MIN)\n\t  PyGSL_ERROR(\"Number too small for int\", GSL_EINVAL);\n\n     *result = (int) tmp;\n     DEBUG_MESS(3, \"found a int of %d\\n\", *result);\n     Py_DECREF(object1);\n     FUNC_MESS_END();\n     return GSL_SUCCESS;\n}\n\n\n/*\n * Checks following conditions:\n *  For No Arguments: Got Py_None and No Error\n *  For 1  Argument:  Got an Object, No None  and No Error \n *         (Is None a legal return for one object? I think so.) On the other hand its a\n *         callback and Conversions are waiting, so its good not to accept None. \n * For 2  Arguments: Got a tuple of approbriate size\n */\n#define PyGSL_CHECK_PYTHON_RETURN(object, nargs, info)                              \\\n  (                                                                                 \\\n        (  ( (nargs) == 0 ) && ( object ) && ( Py_None == (object) ) && ( !PyErr_Occurred() ) )   \\\n    ||  (  ( (nargs) == 1 ) && ( object ) && ( Py_None != (object) ) && ( !PyErr_Occurred() ) )   \\\n    ||  (  ( (nargs) >  1 ) && ( object ) && ( PyTuple_Check((object)) ) &&                       \\\n                 ( (nargs) == PyTuple_GET_SIZE((object)) ) )                        \\\n )                                                                                  \\\n ?                                                                                  \\\n    GSL_SUCCESS                                                                     \\\n :                                                                                  \\\n   PyGSL_check_python_return((object), (nargs), (info))        \n\nPyGSL_API_EXTERN int\nPyGSL_check_python_return(PyObject *object, int nargs, PyGSL_error_info  *info)\n{\n     int tuple_size, flag=-1;\n     char *msg;\n\n\n     FUNC_MESS_BEGIN();  \n     \n     assert(info);\n\n\n\n\n     if(object == NULL && PyErr_Occurred()){\n\t  /* \n\t   * Error was apparently raised by the function, so lets just add a\n\t   * traceback frame .... \n\t   */\n\t  info->error_description = \"User function raised exception!\";\n\t  PyGSL_add_traceback(NULL, \"Unknown file\", info->message, __LINE__);\n\t  return GSL_EBADFUNC;\n     }\n     if(PyErr_Occurred()){\n\t  info->error_description = \"Function raised an exception.\";\n\t  PyGSL_add_traceback(NULL, \"Unknown file\", info->message, __LINE__);\n\t  return GSL_EBADFUNC;\n\t  /* return PyGSL_set_error_string_for_callback(info); */\n     }\n\n     /* Expected No argumets */\t\n     if(nargs == 0){\n\t  if(object != Py_None){\n\t       info->error_description = \"I expected 0 arguments, but I got an object different from None.\";\n\t       return PyGSL_set_error_string_for_callback(info);\n\t  } else {\n\t       return GSL_SUCCESS;\n\t  }\n     }\n\n     if(nargs == 1){\n\t  if(object == Py_None){\n\t       info->error_description = \"Expected 1 argument, but None was returned. This value is not acceptable for\" \n\t\t    \" the following arithmetic calculations.\";\n\t       return PyGSL_set_error_string_for_callback(info);\n\t  } else {\n\t       return GSL_SUCCESS;\n\t  } \n     }\n\n     if(nargs > 1){\n\t  msg = (char *) malloc(256 * sizeof(char));\n\n\t  if(object == Py_None){\n\t       snprintf(msg, 256, \"I expected %d arguments, but the function returned None!\", nargs);\n\t       info->error_description = msg;\n\t       flag = PyGSL_set_error_string_for_callback(info);\t       \n\n\t  } else if(!PyTuple_Check(object)){\n\t       snprintf(msg, 256, \"Expected %d arguments, but I didn't get a tuple! \"\n\t\t\t\"Did you just return one argument?.\", nargs);\n\t       info->error_description = msg;\n\t       flag = PyGSL_set_error_string_for_callback(info);\t       \n\n\t  } else {\n\t       tuple_size = PyTuple_GET_SIZE(object);\n\t       if(tuple_size != nargs){\n\t\t    snprintf(msg, 256, \"I expected %d arguments, but the function returned %d arguments! \",\n\t\t\t     nargs, tuple_size);\n\t       info->error_description = msg;\n\t       flag = PyGSL_set_error_string_for_callback(info);\n\n\t       } else {\n\t\t    flag = GSL_SUCCESS;\n\t       }\n\t  }\n\t  free(msg);\n     }    \n     FUNC_MESS_END();\n     return flag;\n}\n\nPyGSL_API_EXTERN void\nPyGSL_clear_name(char *name, int size)\n{\n     int j;\n     for(j = 0; j<size; j++){\n\t  if(name[j] == '-')\n\t       name[j] = '_';\n     }\n}\n", "meta": {"hexsha": "3ef94b9faf9bd2f42227dff9b351f0657ec88d94", "size": 8693, "ext": "c", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/src/init/general_helpers.c", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/src/init/general_helpers.c", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/src/init/general_helpers.c", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 30.0795847751, "max_line_length": 113, "alphanum_fraction": 0.5996779018, "num_tokens": 2199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18242552380635632, "lm_q2_score": 0.030675800049112894, "lm_q1q2_score": 0.005596048892138471}}
{"text": "// --------------------------------------------------------------------------\n//                   OpenMS -- Open-Source Mass Spectrometry\n// --------------------------------------------------------------------------\n// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,\n// ETH Zurich, and Freie Universitaet Berlin 2002-2013.\n//\n// This software is released under a three-clause BSD license:\n//  * Redistributions of source code must retain the above copyright\n//    notice, this list of conditions and the following disclaimer.\n//  * Redistributions in binary form must reproduce the above copyright\n//    notice, this list of conditions and the following disclaimer in the\n//    documentation and/or other materials provided with the distribution.\n//  * Neither the name of any author or any participating institution\n//    may be used to endorse or promote products derived from this software\n//    without specific prior written permission.\n// For a full list of authors, refer to the file AUTHORS.\n// --------------------------------------------------------------------------\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING\n// INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// --------------------------------------------------------------------------\n// $Maintainer: Lars Nilse $\n// $Authors: Steffen Sass, Holger Plattfaut, Bastian Blank $\n// --------------------------------------------------------------------------\n\n#ifndef OPENMS_FILTERING_DATAREDUCTION_SILACFILTER_H\n#define OPENMS_FILTERING_DATAREDUCTION_SILACFILTER_H\n\n#include <OpenMS/KERNEL/StandardTypes.h>\n#include <OpenMS/FILTERING/DATAREDUCTION/SILACFiltering.h>\n#include <OpenMS/FILTERING/DATAREDUCTION/SILACPattern.h>\n#include <OpenMS/FILTERING/DATAREDUCTION/IsotopeDistributionCache.h>\n#include <gsl/gsl_interp.h>\n#include <gsl/gsl_spline.h>\n#include <queue>\n#include <list>\n\nnamespace OpenMS\n{\n  /**\n   * @brief Filter to use for SILACFiltering\n   *\n   * A SILACFilter searches for SILAC patterns, which correspond to the defined mass shifts and charge.\n   * Only peaks are taken into account, which were not blacklisted by other filters before e.g. are not part of\n   * a SILAC pair yet.\n   *\n   * @see SILACFiltering\n   */\n  class OPENMS_DLLAPI SILACFilter\n  {\nprivate:\n    friend class SILACFiltering;\n\n    typedef IsotopeDistributionCache::TheoreticalIsotopePattern TheoreticalIsotopePattern;\n\n    /**\n     * @brief mass shift(s) in [Da] to search for\n     */\n    std::vector<DoubleReal> mass_separations_;\n\n    /**\n     * @brief charge of the ions to search for\n     */\n    Int charge_;\n\n    /**\n     * @brief maximal value of which a predicted SILAC feature may deviate from the averagine model\n     */\n    DoubleReal model_deviation_;\n\n    /**\n     * @brief number of peaks per peptide to search for\n     */\n    Size isotopes_per_peptide_;\n\n    /**\n     * @brief minimal intensity of SILAC features\n     */\n    DoubleReal intensity_cutoff_;\n\n    /**\n     * @brief minimal intensity correlation between regions of different peaks\n     */\n    DoubleReal intensity_correlation_;\n\n    /**\n     * @brief flag for missing peaks\n     */\n    bool allow_missing_peaks_;\n\n    /**\n     * Isotope distributions\n     */\n    static IsotopeDistributionCache * isotope_distribution_;\n\n    /**\n     * @brief number of peptides [i.e. number of labelled peptides +1, e.g. for SILAC triplet =3]\n     */\n    Size number_of_peptides_;\n\n    /**\n     * @brief peak positions of SILAC pattern\n     */\n    std::vector<DoubleReal> peak_positions_;\n\n    /**\n     * @brief m/z separation between individual peptides [e.g. {0 Th, 4 Th, 5 Th}]\n     */\n    std::vector<DoubleReal> mz_peptide_separations_;\n\n    /**\n     * @brief m/z shifts relative to mono-isotopic peak of unlabelled peptide\n     */\n    std::vector<DoubleReal> expected_mz_shifts_;\n\n    /**\n     * @brief distance between isotopic peaks of a peptide in [Th]\n     */\n    DoubleReal isotope_distance_;\n\n    /**\n     * @brief holds the recognized features\n     */\n    std::vector<SILACPattern> elements_;\n\n    /**\n     * @brief m/z at which the filter is currently applied to\n     */\n    DoubleReal current_mz_;\n\n    /**\n     * @brief exact m/z shift of isotopic peaks in a SILAC pattern relative to the mono-isotopic peak of the light peptide, peptides (row) x isotope (column)\n     */\n    std::vector<std::vector<DoubleReal> > exact_shifts_;\n\n    /**\n     * @brief m/z positions mz + exact_shifts in a SILAC pattern, where mz is the m/z of the mono-isotopic peak of light peptide\n     */\n    std::vector<std::vector<DoubleReal> > exact_mz_positions_;\n\n    /**\n     * @brief intensities at mz + exact_shifts in a SILAC pattern, where mz is the m/z of the mono-isotopic peak of light peptide\n     */\n    std::vector<std::vector<DoubleReal> > exact_intensities_;\n\n    /**\n     * @brief expected m/z shift of isotopic peaks in a SILAC pattern relative to the mono-isotopic peak of the light peptide, peptides (row) x isotope (column)\n     */\n    std::vector<std::vector<DoubleReal> > expected_shifts_;\n\n    /**\n     * @brief Checks if there exists a SILAC feature at the given position in the raw (interpolated) data, which corresponds to the filter's properties\n     * @param rt RT value of the position\n     * @param mz m/z value of the position\n     */\n    bool isSILACPattern_(const MSSpectrum<Peak1D> &, const SILACFiltering::SpectrumInterpolation &, DoubleReal mz, DoubleReal picked_mz, const SILACFiltering &, MSSpectrum<Peak1D> & debug, SILACPattern & pattern);\n\n    /**\n     * @brief Checks if there exists a SILAC feature at the given position in the picked data\n     */\n    bool isSILACPatternPicked_(const MSSpectrum<Peak1D> &, DoubleReal mz, const SILACFiltering &, MSSpectrum<Peak1D> & debug);\n\n    /**\n     * @brief Extracts mass shifts and intensities from the raw (interpolated) data\n     */\n    bool extractMzShiftsAndIntensities_(const MSSpectrum<Peak1D> &, const SILACFiltering::SpectrumInterpolation &, DoubleReal mz, DoubleReal picked_mz, const SILACFiltering &);\n\n    /**\n     * @brief Extracts mass shifts and intensities from the picked data\n     */\n    bool extractMzShiftsAndIntensitiesPicked_(const MSSpectrum<Peak1D> &, DoubleReal mz, const SILACFiltering &);\n\n    /**\n     * @brief Extracts mass shifts and intensities from the picked data and returns pattern information\n     */\n    bool extractMzShiftsAndIntensitiesPickedToPattern_(const MSSpectrum<Peak1D> &, DoubleReal mz, const SILACFiltering &, SILACPattern & pattern);\n\n    /**\n     * @brief Checks all peaks against intensity cutoff\n     */\n    bool intensityFilter_();\n\n    /**\n     * @brief Checks peak form correlation between peaks of one isotope\n     */\n    bool correlationFilter1_(const SILACFiltering::SpectrumInterpolation &, DoubleReal mz, const SILACFiltering &);\n\n    /**\n     * @brief Checks peak form correlation between peaks of different isotopes\n     */\n    bool correlationFilter2_(const SILACFiltering::SpectrumInterpolation &, DoubleReal mz, const SILACFiltering &);\n\n    /**\n     * @brief Checks peak intensities against the averagine model\n     */\n    bool averageneFilter_(DoubleReal mz);\n\npublic:\n    /**\n     * @brief detailed constructor for SILAC pair filtering\n     * @param mass_separations all mass shifts of the filter\n     * @param charge charge of the ions to search for\n     * @param model_deviation maximum deviation from the averagine model\n     * @param isotopes_per_peptide number of peaks per peptide to search for\n     * @param intensity_cutoff ...\n     * @param intensity_correlation minimal intensity correlation between regions of different peaks\n     * @param allow_missing_peaks flag for missing peaks\n     */\n    SILACFilter(std::vector<DoubleReal> mass_separations, Int charge, DoubleReal model_deviation, Int isotopes_per_peptide,\n                DoubleReal intensity_cutoff, DoubleReal intensity_correlation, bool allow_missing_peaks);\n\n    /**\n     * @brief gets the m/z values of all peaks , which belong the last identified feature\n     */\n    std::vector<DoubleReal> getPeakPositions();\n\n    /**\n     * @brief gets the m/z shifts relative to mono-isotopic peak of unlabelled peptide\n     */\n    const std::vector<DoubleReal> & getExpectedMzShifts();\n\n    /**\n     * @brief returns all identified elements\n     */\n    std::vector<SILACPattern> & getElements();\n\n    /**\n     * @brief returns the charge of the filter\n     */\n    Int getCharge();\n\n    /**\n     * @brief returns the mass shifts of the filter in [Da]\n     */\n    std::vector<DoubleReal> & getMassSeparations();\n  };\n}\n\n#endif /* SILACFILTER_H_ */\n", "meta": {"hexsha": "99c1708041a8ba021aba2483bba0ca9964f1540f", "size": 9289, "ext": "h", "lang": "C", "max_stars_repo_path": "include/OpenMS/FILTERING/DATAREDUCTION/SILACFilter.h", "max_stars_repo_name": "open-ms/all-svn-branches", "max_stars_repo_head_hexsha": "b182ba576e0cbfbe420b8edb0dd1c42bb6c973f3", "max_stars_repo_licenses": ["Zlib", "Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-05-23T03:43:10.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-23T03:43:10.000Z", "max_issues_repo_path": "src/openms/include/OpenMS/FILTERING/DATAREDUCTION/SILACFilter.h", "max_issues_repo_name": "kreinert/OpenMS", "max_issues_repo_head_hexsha": "45455356482ce5ab35e32e445609b291ec78a6d6", "max_issues_repo_licenses": ["Zlib", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/openms/include/OpenMS/FILTERING/DATAREDUCTION/SILACFilter.h", "max_forks_repo_name": "kreinert/OpenMS", "max_forks_repo_head_hexsha": "45455356482ce5ab35e32e445609b291ec78a6d6", "max_forks_repo_licenses": ["Zlib", "Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3052208835, "max_line_length": 213, "alphanum_fraction": 0.6764990849, "num_tokens": 2131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.28776780354463427, "lm_q2_score": 0.0194193463380643, "lm_q1q2_score": 0.0055882626419773}}
{"text": "#pragma once\n\n#include <gsl\\gsl>\n#include <winrt\\Windows.Foundation.h>\n#include <d3d11.h>\n#include <array>\n#include \"DrawableGameComponent.h\"\n#include \"MatrixHelper.h\"\n#include \"PointLight.h\"\n\nnamespace Library\n{\n\tclass PointLight;\n\tclass ProxyModel;\n}\n\nnamespace Rendering\n{\n\tclass MultiplePointLightsMaterial;\n\n\tclass MultiplePointLightsDemo final : public Library::DrawableGameComponent\n\t{\n\tpublic:\n\t\tMultiplePointLightsDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera);\n\t\tMultiplePointLightsDemo(const MultiplePointLightsDemo&) = delete;\n\t\tMultiplePointLightsDemo(MultiplePointLightsDemo&&) = default;\n\t\tMultiplePointLightsDemo& operator=(const MultiplePointLightsDemo&) = default;\t\t\n\t\tMultiplePointLightsDemo& operator=(MultiplePointLightsDemo&&) = default;\n\t\t~MultiplePointLightsDemo();\n\n\t\tbool AnimationEnabled() const;\n\t\tvoid SetAnimationEnabled(bool enabled);\n\t\tvoid ToggleAnimation();\n\n\t\tfloat AmbientLightIntensity() const;\n\t\tvoid SetAmbientLightIntensity(float intensity);\n\n\t\tconst std::array<Library::PointLight, 4>& PointLights() const;\n\t\tvoid SetPointLight(const Library::PointLight& light, size_t index);\n\t\t\t\t\n\t\tconst size_t SelectedLightIndex() const;\n\t\tconst Library::PointLight& SelectedLight() const;\n\t\tvoid UpdateSelectedLight(const Library::PointLight& light);\n\t\tvoid SelectLight(size_t index);\n\n\t\tfloat SpecularPower() const;\n\t\tvoid SetSpecularPower(float power);\n\n\t\tvirtual void Initialize() override;\n\t\tvirtual void Update(const Library::GameTime& gameTime) override;\n\t\tvirtual void Draw(const Library::GameTime& gameTime) override;\n\n\tprivate:\n\t\tinline static const float RotationRate{ DirectX::XM_PI };\n\n\t\tstd::shared_ptr<MultiplePointLightsMaterial> mMaterial;\n\t\tDirectX::XMFLOAT4X4 mWorldMatrix{ Library::MatrixHelper::Identity };\n\t\twinrt::com_ptr<ID3D11Buffer> mVertexBuffer;\n\t\twinrt::com_ptr<ID3D11Buffer> mIndexBuffer;\n\t\tstd::uint32_t mIndexCount{ 0 };\n\t\tstd::array<std::unique_ptr<Library::ProxyModel>, 4> mProxyModels;\n\t\tsize_t mSelectedLightIndex{ 0 };\n\t\tfloat mModelRotationAngle{ 0.0f };\n\t\tbool mAnimationEnabled{ true };\n\t\tbool mUpdateMaterial{ true };\n\t};\n}", "meta": {"hexsha": "523688c4e3aff74c501ac19560eadf3c8c81a4cf", "size": 2119, "ext": "h", "lang": "C", "max_stars_repo_path": "source/4.3_Multiple_Point_Lights/MultiplePointLightsDemo.h", "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/4.3_Multiple_Point_Lights/MultiplePointLightsDemo.h", "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/4.3_Multiple_Point_Lights/MultiplePointLightsDemo.h", "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6268656716, "max_line_length": 95, "alphanum_fraction": 0.7758376593, "num_tokens": 521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.334589441253186, "lm_q2_score": 0.01665703775153725, "lm_q1q2_score": 0.005573268954220074}}
{"text": "//          Copyright Jean Pierre Cimalando 2019.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE.md or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n#pragma once\n#include \"player/instrument.h\"\n#include \"synth/synth.h\"\n#include <fmidi/fmidi.h>\n#include <gsl/gsl>\n#include <memory>\n\nclass Midi_Synth_Instrument : public Midi_Instrument {\npublic:\n    Midi_Synth_Instrument();\n    ~Midi_Synth_Instrument();\n\n    void flush_events() override;\n\n    void open_midi_output(gsl::cstring_span id) override;\n    void close_midi_output() override;\n\n    bool is_synth() const override { return true; }\n\n    void configure_audio(double audio_rate, double audio_latency);\n    void generate_audio(float *output, unsigned nframes);\n\n    void preload(const fmidi_smf_t &smf);\n\nprotected:\n    void handle_send_message(const uint8_t *data, unsigned len, double ts, uint8_t flags) override;\n\nprivate:\n    struct Impl;\n    std::unique_ptr<Impl> impl_;\n};\n", "meta": {"hexsha": "d9da6d43f4074a4cf725595cb72fc681c332347c", "size": 998, "ext": "h", "lang": "C", "max_stars_repo_path": "sources/player/instruments/synth.h", "max_stars_repo_name": "jpcima/smf-dsp", "max_stars_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2020-07-08T15:23:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T23:08:17.000Z", "max_issues_repo_path": "sources/player/instruments/synth.h", "max_issues_repo_name": "jpcima/smf-dsp", "max_issues_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2020-07-05T23:59:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-16T20:44:07.000Z", "max_forks_repo_path": "sources/player/instruments/synth.h", "max_forks_repo_name": "jpcima/smf-dsp", "max_forks_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-07-10T18:48:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-22T08:05:13.000Z", "avg_line_length": 26.972972973, "max_line_length": 99, "alphanum_fraction": 0.7244488978, "num_tokens": 244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2782567937024021, "lm_q2_score": 0.02002344070465909, "lm_q1q2_score": 0.005571658409368605}}
{"text": "#include <string.h>\n\n#include <mpi.h>\n#include <pfft.h>\n#include <gsl/gsl_rng.h>\n\n#include <fastpm/libfastpm.h>\n#include <fastpm/logging.h>\n#include \"pmpfft.h\"\n\n#define HAS(a, b) ((a & b) != 0)\n\nstatic void\npack_any(FastPMStore * p, ptrdiff_t index, int ci, void * packed)\n{\n    size_t elsize = p->_column_info[ci].elsize;\n    memcpy(packed, p->columns[ci] + index * elsize, elsize);\n}\n\nstatic void\nunpack_any(FastPMStore * p, ptrdiff_t index, int ci, void * packed)\n{\n    size_t elsize = p->_column_info[ci].elsize;\n    memcpy(p->columns[ci] + index * elsize, packed, elsize);\n}\n\nvoid\nFastPMReduceOverwriteAny(FastPMStore * p, ptrdiff_t index, int ci, void * packed, void * userdata)\n{\n    size_t elsize = p->_column_info[ci].elsize;\n\n    memcpy(p->columns[ci] + index * elsize, packed, elsize);\n}\n\nvoid\nFastPMReduceAddFloat(FastPMStore * src, ptrdiff_t isrc, FastPMStore * dest, ptrdiff_t idest, int ci, void * userdata)\n{\n    size_t nmemb = dest->_column_info[ci].nmemb ;\n\n    size_t elsize = dest->_column_info[ci].elsize;\n\n    float * pdest = (float*) (dest->columns[ci] + idest * elsize);\n    float * psrc  = (float*) (src ->columns[ci] + isrc * elsize);\n\n    int d;\n    for(d = 0; d < nmemb; d ++) {\n        pdest[d] += psrc[d];\n    }\n}\n\nstatic double\nto_double_f4 (FastPMStore * p, ptrdiff_t index, int ci, int memb)\n{\n    size_t nmemb = p->_column_info[ci].nmemb ;\n    if(memb > nmemb) {\n        fastpm_raise(-1, \"memb %d greater than nmemb %d\", memb, nmemb);\n    }\n    size_t elsize = p->_column_info[ci].elsize;\n\n    float * ptr = (float*) (p->columns[ci] + index * elsize);\n\n    return ptr[memb];\n}\n\nstatic double\nto_double_f8 (FastPMStore * p, ptrdiff_t index, int ci, int memb)\n{\n    size_t nmemb = p->_column_info[ci].nmemb ;\n    if(memb > nmemb) {\n        fastpm_raise(-1, \"memb %d greater than nmemb %d\", memb, nmemb);\n    }\n    size_t elsize = p->_column_info[ci].elsize;\n\n    double * ptr = (double*) (p->columns[ci] + index * elsize);\n\n    return ptr[memb];\n}\n\nstatic void\nfrom_double_f4 (FastPMStore * p, ptrdiff_t index, int ci, int memb, const double value)\n{\n    size_t nmemb = p->_column_info[ci].nmemb ;\n    if(memb > nmemb) {\n        fastpm_raise(-1, \"memb %d greater than nmemb %d\", memb, nmemb);\n    }\n    size_t elsize = p->_column_info[ci].elsize;\n\n    float * ptr = (float*) (p->columns[ci] + index * elsize);\n\n    ptr[memb] = value;\n}\n\nconst char *\nfastpm_species_get_name(enum FastPMSpecies species)\n{\n    switch(species) {\n        case FASTPM_SPECIES_BARYON:\n            return \"0\";\n        case FASTPM_SPECIES_CDM:\n            return \"1\";\n        case FASTPM_SPECIES_NCDM:\n            return \"2\";\n    }\n    return \"UNKNOWN\";\n}\nvoid fastpm_store_get_position(FastPMStore * p, ptrdiff_t index, double pos[3])\n{\n    pos[0] = p->x[index][0];\n    pos[1] = p->x[index][1];\n    pos[2] = p->x[index][2];\n}\n\nvoid fastpm_store_get_lagrangian_position(FastPMStore * p, ptrdiff_t index, double pos[3])\n{\n    pos[0] = p->q[index][0];\n    pos[1] = p->q[index][1];\n    pos[2] = p->q[index][2];\n}\n\ndouble fastpm_store_get_mass(FastPMStore * p, ptrdiff_t index)\n{\n    /* total mass is the sum of the base and the extra */\n    if(p->mass) {\n        return p->meta.M0 + p->mass[index];\n    } else {\n        return p->meta.M0;\n    }\n}\n\nstatic ptrdiff_t\n_alignsize(ptrdiff_t size)\n{\n    /* align sizes */\n    return ((size + 1024) / 1024) * 1024;\n}\n\nvoid\nfastpm_store_init_details(FastPMStore * p,\n                  const char * name,\n                  size_t np_upper,\n                  FastPMColumnTags attributes,\n                  enum FastPMMemoryLocation loc,\n                  const char * file,\n                  const int line)\n{\n    p->mem = _libfastpm_get_gmem();\n\n    /* only set the name if name is not NULL; this is to allow setting the name before calling init.\n     * */\n    if(name) {\n        strcpy(p->name, name);\n    }\n\n    p->attributes = attributes;\n\n    p->np = 0;\n    p->np_upper = np_upper;\n\n    /* clear the column pointers. */\n    memset(p->columns, 0, sizeof(p->columns));\n    memset(p->_column_info, 0, sizeof(p->_column_info));\n\n    /* clear the meta */\n    memset(&p->meta, 0, sizeof(p->meta));\n    int it;\n    p->_base = NULL;\n\n    /* first loop initialize the _column_info struct for corresponding items in the pointer union; \n     * second loop initialize the pointers */\n    #define DEFINE_COLUMN(column, attr_, dtype_, nmemb_) \\\n        { \\\n            int ci = FASTPM_STORE_COLUMN_INDEX(column); \\\n            if(attr_ != (1 << ci)) { fastpm_raise(-1, \"attr and column are out of order for %s\\n\", # column ); } \\\n            strcpy(p->_column_info[ci].dtype, dtype_);  \\\n            strcpy(p->_column_info[ci].name, # column); \\\n            p->_column_info[ci].elsize = sizeof(p->column[0]);  \\\n            p->_column_info[ci].nmemb = nmemb_;  \\\n            p->_column_info[ci].membsize = sizeof(p->column[0]) / nmemb_;  \\\n            p->_column_info[ci].attribute = attr_;  \\\n            p->_column_info[ci].pack = pack_any;  \\\n            p->_column_info[ci].unpack = unpack_any;  \\\n            p->_column_info[ci].from_double = NULL;  \\\n            p->_column_info[ci].to_double = NULL;  \\\n        }\n\n    #define COLUMN_INFO(column) (p->_column_info[FASTPM_STORE_COLUMN_INDEX(column)])\n\n    DEFINE_COLUMN(x, COLUMN_POS, \"f8\", 3);\n    DEFINE_COLUMN(q, COLUMN_Q, \"f4\", 3);\n    DEFINE_COLUMN(v, COLUMN_VEL, \"f4\", 3);\n    DEFINE_COLUMN(acc, COLUMN_ACC, \"f4\", 3);\n    DEFINE_COLUMN(dx1, COLUMN_DX1, \"f4\", 3);\n    DEFINE_COLUMN(dx2, COLUMN_DX2, \"f4\", 3);\n    DEFINE_COLUMN(dv1, COLUMN_DV1, \"f4\", 3);\n    DEFINE_COLUMN(aemit, COLUMN_AEMIT, \"f4\", 1);\n    DEFINE_COLUMN(rho, COLUMN_DENSITY, \"f4\", 1);\n    DEFINE_COLUMN(potential, COLUMN_POTENTIAL, \"f4\", 1);\n    DEFINE_COLUMN(tidal, COLUMN_TIDAL, \"f4\", 6);\n    DEFINE_COLUMN(id, COLUMN_ID, \"i8\", 1);\n    DEFINE_COLUMN(pgdc, COLUMN_PGDC, \"f4\", 3);\n    DEFINE_COLUMN(mask, COLUMN_MASK, \"i1\", 1);\n    DEFINE_COLUMN(minid, COLUMN_MINID, \"i8\", 1);\n    DEFINE_COLUMN(task, COLUMN_TASK, \"i4\", 1);\n    DEFINE_COLUMN(length, COLUMN_LENGTH, \"i4\", 1);\n    DEFINE_COLUMN(rdisp, COLUMN_RDISP, \"f4\", 6);\n    DEFINE_COLUMN(vdisp, COLUMN_VDISP, \"f4\", 6);\n    DEFINE_COLUMN(rvdisp, COLUMN_RVDISP, \"f4\", 9);\n    DEFINE_COLUMN(mass, COLUMN_MASS, \"f4\", 1);\n\n    COLUMN_INFO(x).to_double = to_double_f8;\n    COLUMN_INFO(v).to_double = to_double_f4;\n    COLUMN_INFO(rho).to_double = to_double_f4;\n    COLUMN_INFO(dx1).to_double = to_double_f4;\n    COLUMN_INFO(dx2).to_double = to_double_f4;\n    COLUMN_INFO(dv1).to_double = to_double_f4;\n    COLUMN_INFO(acc).to_double = to_double_f4;\n    COLUMN_INFO(mass).to_double = to_double_f4;\n\n    COLUMN_INFO(rho).from_double = from_double_f4;\n    COLUMN_INFO(acc).from_double = from_double_f4;\n    COLUMN_INFO(pgdc).from_double = from_double_f4;\n    COLUMN_INFO(dx1).from_double = from_double_f4;\n    COLUMN_INFO(dx2).from_double = from_double_f4;\n    COLUMN_INFO(dv1).from_double = from_double_f4;\n    COLUMN_INFO(potential).from_double = from_double_f4;\n    COLUMN_INFO(tidal).from_double = from_double_f4;\n\n    ptrdiff_t size = 0;\n    ptrdiff_t offset = 0;\n    for(it = 0; it < 2; it ++) {\n        int ci;\n        for(ci = 0; ci < 32; ci ++) {\n            if(it == 0) {\n                size += ((attributes & p->_column_info[ci].attribute) != 0) * (_alignsize(p->_column_info[ci].elsize * np_upper)); \\\n            } else { \\\n                if(attributes & p->_column_info[ci].attribute) { \\\n                    p->columns[ci] = (void*) (((char*) p->_base) + offset); \\\n                    offset += _alignsize(p->_column_info[ci].elsize * np_upper); \\\n                } else { \\\n                    p->columns[ci] = NULL; \\\n                } \\\n            }\n\n\n        }\n        if(it == 0) {\n            p->_base = fastpm_memory_alloc_details(p->mem, \"FastPMStore\", size, loc, file, line);\n            /* zero out all memory */\n            memset(p->_base, 0, size);\n        }\n    };\n}\n\nvoid\nfastpm_store_set_name(FastPMStore * p, const char * name)\n{\n    strcpy(p->name, name);\n}\n\nsize_t\nfastpm_store_init_evenly_details(FastPMStore * p,\n    const char * name, size_t np_total, FastPMColumnTags attributes, double alloc_factor, MPI_Comm comm,\n    const char * file,\n    const int line)\n{\n    /* allocate for np_total cross all */\n    /* name means name of species*/\n    int NTask;\n    MPI_Comm_size(comm, &NTask);\n\n    size_t np_upper = (size_t)(1.0 * np_total / NTask * alloc_factor);\n\n    MPI_Bcast(&np_upper, 1, MPI_LONG, 0, comm);\n    fastpm_store_init_details(p, name, np_upper, attributes, FASTPM_MEMORY_HEAP, file, line);\n    return 0;\n}\n\nsize_t\nfastpm_store_get_np_total(FastPMStore * p, MPI_Comm comm)\n{\n    long long np = p->np;\n    MPI_Allreduce(MPI_IN_PLACE, &np, 1, MPI_LONG_LONG, MPI_SUM, comm);\n    return np;\n}\n\nsize_t\nfastpm_store_get_mask_sum(FastPMStore * p, MPI_Comm comm)\n{\n    long long np = 0;\n    ptrdiff_t i;\n    for(i = 0; i < p->np; i ++) {\n        np += p->mask[i] != 0;\n    }\n    MPI_Allreduce(MPI_IN_PLACE, &np, 1, MPI_LONG_LONG, MPI_SUM, comm);\n    return np;\n}\n\nvoid\nfastpm_packing_plan_init(FastPMPackingPlan * plan, FastPMStore * p, FastPMColumnTags attributes)\n{\n    int ci;\n    int i = 0;\n    plan->elsize = 0;\n    plan->attributes = attributes;\n    for (ci = 0; ci < 32; ci ++) {\n        if (!(p->_column_info[ci].attribute & attributes)) continue;\n        plan->_ci[i] = ci;\n        plan->_offsets[ci] = plan->elsize;\n        ptrdiff_t elsize = p->_column_info[ci].elsize;\n        plan->elsize += elsize;\n        plan->_column_info[ci] = p->_column_info[ci];\n        i++;\n    }\n    /* Pad the elsize to 8 bytes. This ensures anything goes to the MPI wire is 8 byte aligned,\n     * and minimizes the chances of hitting an implementation bug. */\n    if (plan->elsize % 8 != 0) {\n        plan->elsize += (8 - plan->elsize % 8);\n    }\n    plan->Ncolumns = i;\n}\n\nvoid\nfastpm_packing_plan_pack(FastPMPackingPlan * plan,\n            FastPMStore * p, ptrdiff_t i, void * packed)\n{\n    int t;\n    memset(packed, 0, plan->elsize);\n    for (t = 0; t < plan->Ncolumns; t ++) {\n        int ci = plan->_ci[t];\n        ptrdiff_t offset = plan->_offsets[ci];\n        plan->_column_info[ci].pack(p, i, ci,\n            ((char*) packed) + offset);\n    }\n}\n\nvoid\nfastpm_packing_plan_unpack(FastPMPackingPlan * plan,\n            FastPMStore * p, ptrdiff_t i, void * packed)\n{\n    int t;\n    for (t = 0; t < plan->Ncolumns; t ++) {\n        int ci = plan->_ci[t];\n        fastpm_packing_plan_unpack_ci(plan, ci, p, i, packed);\n    }\n}\n\n/* unpack a single column from the offset in packed data. */\nvoid\nfastpm_packing_plan_unpack_ci(FastPMPackingPlan * plan, int ci,\n            FastPMStore * p, ptrdiff_t i, void * packed)\n{\n    ptrdiff_t offset = plan->_offsets[ci];\n    plan->_column_info[ci].unpack(p, i, ci,\n        ((char*) packed) + offset);\n}\n\n\nint\nfastpm_store_find_column_id(FastPMStore * p, FastPMColumnTags attribute)\n{\n    int ci;\n    for (ci = 0; ci < 32; ci ++) {\n        if (p->_column_info[ci].attribute == attribute) {\n            return ci;\n        }\n    }\n    fastpm_raise(-1, \"Unknown column %x\", attribute);\n    return -1;\n}\n\nvoid \nfastpm_store_destroy(FastPMStore * p) \n{\n    fastpm_memory_free(p->mem, p->_base);\n}\n\nstatic void permute(void * data, int np, size_t elsize, int * ind) {\n    void * tmp = malloc(elsize * np);\n    if(!tmp) {\n        fastpm_raise(-1, \"No memory for permuting\\n\");\n    }\n    int i;\n    for(i = 0; i < np; i ++) {\n        memcpy(((char*) tmp) + i * elsize, ((char*) data) + ind[i] * elsize, elsize);\n    }\n    memcpy(data, tmp, np * elsize);\n    free(tmp);\n}\n\nvoid fastpm_store_permute(FastPMStore * p, int * ind)\n{\n    int c;\n    for(c = 0; c < 32; c ++) {\n        if(!p->columns[c]) continue;\n        permute(p->columns[c], p->np, p->_column_info[c].elsize, ind);\n    }\n}\n\n\nstatic FastPMStore *  _fastpm_store_sort_store;\nstatic int (*_fastpm_store_sort_cmp_func)(const int i1, const int i2, FastPMStore * p);\n\nint _sort_by_id_cmpfunc(const void * p1, const void * p2)\n{\n    const int * i1 = (const int*) p1;\n    const int * i2 = (const int*) p2;\n\n    return _fastpm_store_sort_cmp_func(*i1, *i2, _fastpm_store_sort_store);\n}\n\nint\nFastPMLocalSortByID(const int i1,\n                    const int i2,\n                    FastPMStore * p)\n{\n    int v1 = (p->id[i1] < p->id[i2]);\n    int v2 = (p->id[i1] > p->id[i2]);\n\n    return v2 - v1;\n}\n\n/* sort a store locally with in the MPI rank. \n *\n * cmp_func is called with three arguments.\n * */\nvoid\nfastpm_store_sort(FastPMStore * p,\n        int (*cmp_func)(const int i1, const int i2, FastPMStore * p))\n{\n    int * arg = fastpm_memory_alloc(p->mem, \"Temp\", sizeof(int) * p->np, FASTPM_MEMORY_HEAP);\n    int i;\n    for(i = 0; i < p->np; i ++) {\n        arg[i] = i;\n    }\n    /* FIXME: copy some version of qsort_r */\n    _fastpm_store_sort_store = p;\n    _fastpm_store_sort_cmp_func = cmp_func;\n    qsort(arg, p->np, sizeof(arg[0]), _sort_by_id_cmpfunc);\n    fastpm_store_permute(p, arg);\n    fastpm_memory_free(p->mem, arg);\n}\n\nvoid \nfastpm_store_wrap(FastPMStore * p, double BoxSize[3])\n{\n    int i;\n    int d;\n    for(i = 0; i < p->np; i ++) {\n        for(d = 0; d < 3; d ++) {\n            double n = abs(p->x[i][d] / BoxSize[d]);\n\n            double x1 = remainder(p->x[i][d], BoxSize[d]);\n\n            while(x1 < 0) x1 += BoxSize[d];\n            while(x1 > BoxSize[d]) x1 -= BoxSize[d];\n            p->x[i][d] = x1;\n\n            if(n > 10000) {\n                double q[3];\n                if(fastpm_store_has_q(p)) {\n                    fastpm_store_get_q_from_id(p, p->id[i], q);\n                }\n                fastpm_raise(-1, \"Particle at %g %g %g (q = %g %g %g) is too far from the bounds. Wrapping failed.\\n\", \n                        p->x[i][0],\n                        p->x[i][1],\n                        p->x[i][2],\n                        q[0], q[1], q[2]\n                );\n            }\n        }\n    } \n}\n\nint\nFastPMTargetPM (FastPMStore * p, ptrdiff_t i, PM * pm)\n{\n    double pos[3];\n    fastpm_store_get_position(p, i, pos);\n    return pm_pos_to_rank(pm, pos);\n}\n\nint\nfastpm_store_decompose(FastPMStore * p,\n    fastpm_store_target_func target_func,\n    void * data, MPI_Comm comm)\n{\n    if(fastpm_store_get_np_total(p, comm) == 0) return 0 ;\n\n    VALGRIND_CHECK_MEM_IS_DEFINED(p->x, sizeof(p->x[0]) * p->np);\n\n    FastPMPackingPlan plan[1];\n\n    fastpm_packing_plan_init(plan, p, p->attributes);\n\n    size_t elsize = plan->elsize;\n\n    size_t Nsend_limit = 1000 * 1024 * 1024 / elsize;     // this large number effectively prevents throttling \n\n    int NTask, ThisTask;\n\n    MPI_Comm_rank(comm, &ThisTask);\n    MPI_Comm_size(comm, &NTask);\n\n    if(p->np > p->np_upper) {\n        fastpm_raise(-1, \"Particle buffer overrun detected np = %td > np_upper %td.\\n\", p->np, p->np_upper);\n    }\n\n    /* do a bincount; offset by -1 because -1 is for self */\n    int * count = calloc(NTask + 1, sizeof(int));\n    int * offsets = calloc(NTask + 1, sizeof(int));\n    int * sendcount = count + 1;\n    int * recvcount = malloc(sizeof(int) * (NTask));\n    int * recvoffset = malloc(sizeof(int) * (NTask));\n    int * sendoffset = malloc(sizeof(int) * (NTask));\n\n    int incomplete = 1;\n    int iter = 0;\n    /* terminate based on incomplete for throttling*/\n    while(1) {\n        incomplete = 0;\n        int * target = fastpm_memory_alloc(p->mem, \"Target\", sizeof(int) * p->np, FASTPM_MEMORY_HEAP);\n\n        size_t Nsend_all = 0;\n        ptrdiff_t i;\n        for(i = 0; i < p->np; i ++) {\n            target[i] = target_func(p, i, data);\n            if(ThisTask == target[i]) {\n                target[i] = -1;\n            } else {\n                Nsend_all++;\n                /* Throttling: never send more than this many particles. */\n                if(Nsend_all >= Nsend_limit) {\n                    incomplete = 1;\n                    target[i] = -1;\n                } else {\n                }\n            }\n        }\n\n        for(i = 0; i < NTask + 1; i ++) {\n            count[i] = 0;\n            offsets[i] = 0;\n        }\n        for(i = 0; i < NTask; i ++) {\n            sendoffset[i] = 0;\n            recvoffset[i] = 0;\n        }\n\n        for(i = 0; i < p->np; i ++) {\n            sendcount[target[i]] ++;\n        }\n        cumsum(offsets, count, NTask + 1);\n\n        int * arg = fastpm_memory_alloc(p->mem, \"PermArg\", sizeof(int) * p->np, FASTPM_MEMORY_HEAP);\n        for(i = 0; i < p->np; i ++) {\n            int offset = offsets[target[i] + 1] ++;\n            arg[offset] = i;\n        }\n\n        fastpm_store_permute(p, arg);\n\n        VALGRIND_CHECK_MEM_IS_DEFINED(p->x, sizeof(p->x[0]) * p->np);\n\n        fastpm_memory_free(p->mem, arg);\n        fastpm_memory_free(p->mem, target);\n\n        MPI_Alltoall(sendcount, 1, MPI_INT, \n                     recvcount, 1, MPI_INT, \n                     comm);\n\n        size_t Nsend = cumsum(sendoffset, sendcount, NTask);\n        size_t Nrecv = cumsum(recvoffset, recvcount, NTask);\n\n        volatile size_t neededsize = p->np + Nrecv - Nsend;\n\n        if(neededsize > p->np_upper) {\n            fastpm_ilog(INFO, \"Need %td particles on rank %d; %td allocated\\n\", neededsize, ThisTask, p->np_upper);\n        }\n\n        if(MPIU_Any(comm, neededsize > p->np_upper)) {\n            goto fail_oom;\n        }\n\n        p->np -= Nsend;\n\n        void * send_buffer = fastpm_memory_alloc(p->mem, \"SendBuf\", elsize * Nsend, FASTPM_MEMORY_HEAP);\n        void * recv_buffer = fastpm_memory_alloc(p->mem, \"RecvBuf\", elsize * Nrecv, FASTPM_MEMORY_HEAP);\n\n        {\n            double nmin, nmax, nmean, nstd;\n\n            MPIU_stats(comm, elsize * Nsend, \"<>-s\", &nmin, &nmax, &nmean, &nstd);\n            fastpm_info(\"Send buffer size : min=%g max=%g mean=%g, std=%g bytes\", nmin, nmax, nmean, nstd);\n            MPIU_stats(comm, elsize * Nrecv, \"<>-s\", &nmin, &nmax, &nmean, &nstd);\n            fastpm_info(\"Recv buffer size : min=%g max=%g mean=%g, std=%g bytes\", nmin, nmax, nmean, nstd);\n        }\n\n        int ipar = 0;\n        int j;\n        for(i = 0; i < NTask; i ++) {\n            for(j = sendoffset[i]; j < sendoffset[i] + sendcount[i]; j ++, ipar++) {\n                fastpm_packing_plan_pack(plan, p, j + p->np, (char*) send_buffer + ipar * elsize);\n            }\n        }\n\n        size_t Nsendsum;\n        size_t Nsendallsum;\n        MPI_Allreduce(&Nsend, &Nsendsum, 1, MPI_LONG, MPI_SUM, comm);\n        MPI_Allreduce(&Nsend_all, &Nsendallsum, 1, MPI_LONG, MPI_SUM, comm);\n        fastpm_info(\"Decomposition iter %d,  exchange of %td particles; need %td\", iter, Nsendsum, Nsendallsum);\n\n        MPI_Datatype PTYPE;\n        MPI_Type_contiguous(elsize, MPI_BYTE, &PTYPE);\n        MPI_Type_commit(&PTYPE);\n\n        MPI_Alltoallv_sparse(\n                send_buffer, sendcount, sendoffset, PTYPE,\n                recv_buffer, recvcount, recvoffset, PTYPE,\n                comm);\n\n        MPI_Type_free(&PTYPE);\n\n        ipar = 0;\n        for(i = 0; i < NTask; i ++) {\n            for(j = recvoffset[i]; j < recvoffset[i] + recvcount[i]; j++, ipar ++) {\n                fastpm_packing_plan_unpack(plan, p, j + p->np, (char*) recv_buffer + ipar * elsize);\n            }\n        }\n\n\n        fastpm_memory_free(p->mem, recv_buffer);\n        fastpm_memory_free(p->mem, send_buffer);\n\n        p->np += Nrecv;\n        iter++;\n        if(MPIU_Any(comm, incomplete)) continue;\n        else break;\n    }\n    free(recvcount);\n    free(recvoffset);\n    free(sendoffset);\n    free(offsets);\n    free(count);\n\n    return 0;\n\n    fail_oom:\n        free(recvcount);\n        free(recvoffset);\n        free(sendoffset);\n        free(offsets);\n        free(count);\n    return -1;\n}\n\nint fastpm_store_has_q(FastPMStore * p)\n{\n    return p->meta._q_size != 0;\n}\n\nvoid\nfastpm_store_get_q_from_id(FastPMStore * p, uint64_t id, double q[3])\n{\n    ptrdiff_t pabs[3];\n\n    int d;\n    id = id % p->meta._q_size;\n    for(d = 0; d < 3; d++) {\n        pabs[d] = id / p->meta._q_strides[d];\n        id -= pabs[d] * p->meta._q_strides[d];\n    }\n\n    for(d = 0; d < 3; d++) {\n        q[d] = pabs[d] * p->meta._q_scale[d];\n        q[d] += p->meta._q_shift[d];\n    }\n}//if all 0 drop\n\nvoid\nfastpm_store_get_iq_from_id(FastPMStore * p, uint64_t id, ptrdiff_t pabs[3])\n{\n    /* integer version of the initial position q\n    i.e. the lattice coordinates of the cells. */\n    int d;\n    for(d = 0; d < 3; d++) {\n        pabs[d] = id / p->meta._q_strides[d];\n        id -= pabs[d] * p->meta._q_strides[d];\n    }\n}\n\nvoid\nfastpm_store_fill(FastPMStore * p, PM * pm, double * shift, ptrdiff_t * Nc)\n{\n    /* fill p with a uniform grid, respecting domain given by pm. use a subsample ratio. \n     * (every subsample grid points) */\n    if(Nc == NULL) {\n        Nc = pm_nmesh(pm);\n    }\n    int d;\n    p->np = 1;\n    for(d = 0; d < 3; d++) {\n        int start = pm->IRegion.start[d] * Nc[d] / pm->Nmesh[d];\n        int end = (pm->IRegion.start[d] + pm->IRegion.size[d]) * Nc[d] / pm->Nmesh[d];\n        p->np *= end - start;\n    }\n    if(p->np > p->np_upper) {\n        fastpm_raise(-1, \"Need %td particles; %td allocated\\n\", p->np, p->np_upper);\n    }\n    ptrdiff_t ptr = 0;\n\n    for(d = 0; d < 3; d ++) {\n        if(shift) \n            p->meta._q_shift[d] = shift[d];\n        else\n            p->meta._q_shift[d] = 0;\n\n        p->meta._q_scale[d] = pm->BoxSize[d] / Nc[d];\n    }\n\n    p->meta._q_size = Nc[0] * Nc[1] * Nc[2];\n    p->meta._q_strides[0] = Nc[1] * Nc[2];\n    p->meta._q_strides[1] = Nc[2];\n    p->meta._q_strides[2] = 1;\n\n    PMXIter iter;\n    for(pm_xiter_init(pm, &iter);\n       !pm_xiter_stop(&iter);\n        pm_xiter_next(&iter)){\n        ptrdiff_t pabs_start[3];\n        ptrdiff_t pabs_end[3];\n        ptrdiff_t ii, jj, kk;\n\n        for(d = 0; d < 3; d ++) {\n            pabs_start[d] = iter.iabs[d] * Nc[d] / pm->Nmesh[d];\n            pabs_end[d] = (iter.iabs[d] + 1) * Nc[d] / pm->Nmesh[d];\n        }\n        for(ii = pabs_start[0]; ii < pabs_end[0]; ii ++)\n        for(jj = pabs_start[1]; jj < pabs_end[1]; jj ++)\n        for(kk = pabs_start[2]; kk < pabs_end[2]; kk ++) {\n            ptrdiff_t pabs[3] = {ii, jj, kk};\n\n            uint64_t id = pabs[2] * p->meta._q_strides[2] +\n                          pabs[1] * p->meta._q_strides[1] +\n                          pabs[0] * p->meta._q_strides[0] ;\n\n            if(p->id) p->id[ptr] = id;\n            if(p->mask) p->mask[ptr] = 0;\n\n            fastpm_store_get_q_from_id(p, id, &p->x[ptr][0]);\n\n            if(p->q) {\n                /* set q if it is allocated. */\n                for(d = 0; d < 3; d ++) {\n                    p->q[ptr][d] = p->x[ptr][d];\n                }\n            }\n            ptr ++;\n        }\n    }\n    if(ptr != p->np) {\n        fastpm_raise(-1, \"This is an internal error, particle number mismatched with grid. %td != %td, allocsize=%td, shape=(%td %td %td)\\n\", \n            ptr, p->np, pm->allocsize,\n            pm->IRegion.size[0],\n            pm->IRegion.size[1],\n            pm->IRegion.size[2]\n            );\n    }\n    p->meta.a_x = p->meta.a_v = 0.;\n}\n\nvoid\nfastpm_store_summary(FastPMStore * p,\n        FastPMColumnTags attribute,\n        MPI_Comm comm,\n        const char * fmt,\n        ...)\n{\n    va_list va;\n    va_start(va, fmt);\n\n    int ci = fastpm_store_find_column_id(p, attribute);\n    size_t nmemb = p->_column_info[ci].nmemb;\n\n    double rmin[nmemb], rmax[nmemb], rsum1[nmemb], rsum2[nmemb];\n\n    if (NULL == p->_column_info[ci].to_double) {\n        fastpm_raise(-1, \"Column %s didnot set to_double virtual function\\n\",\n            p->_column_info[ci].name);\n    }\n    int d;\n    for(d = 0; d < nmemb; d ++) {\n        rmin[d] = 1e20;\n        rmax[d] = -1e20;\n        rsum1[d] = 0;\n        rsum2[d] = 0;\n    }\n    ptrdiff_t i;\n\n#pragma omp parallel\n    {\n        double tmin[nmemb], tmax[nmemb], tsum1[nmemb], tsum2[nmemb];\n        int d;\n        for(d = 0; d < nmemb; d ++) {\n            tmin[d] = 1e20;\n            tmax[d] = -1e20;\n            tsum1[d] = 0;\n            tsum2[d] = 0;\n        }\n        #pragma omp for\n        for(i = 0; i < p->np; i ++) {\n            int d;\n            for(d =0; d < nmemb; d++) {\n                double value = p->_column_info[ci].to_double(p, i, ci, d);\n                tsum1[d] += value;\n                tsum2[d] += value * value;\n                tmin[d] = fmin(tmin[d], value);\n                tmax[d] = fmax(tmax[d], value);\n            } \n        }\n        #pragma omp critical\n        {\n            int d;\n            for(d =0; d < nmemb; d++) {\n                rsum1[d] += tsum1[d];\n                rsum2[d] += tsum2[d];\n                rmin[d] = fmin(rmin[d], tmin[d]);\n                rmax[d] = fmax(rmax[d], tmax[d]);\n            }\n        }\n    }\n    uint64_t Ntot = p->np;\n\n    MPI_Allreduce(MPI_IN_PLACE, rsum1, nmemb, MPI_DOUBLE, MPI_SUM, comm);\n    MPI_Allreduce(MPI_IN_PLACE, rsum2, nmemb, MPI_DOUBLE, MPI_SUM, comm);\n    MPI_Allreduce(MPI_IN_PLACE, rmin, nmemb, MPI_DOUBLE, MPI_MIN, comm);\n    MPI_Allreduce(MPI_IN_PLACE, rmax, nmemb, MPI_DOUBLE, MPI_MAX, comm);\n    MPI_Allreduce(MPI_IN_PLACE, &Ntot,   1, MPI_LONG,  MPI_SUM, comm);\n\n    for(i = 0; i < strlen(fmt); i ++) {\n        void * r = va_arg(va, void *);\n        double * dr = (double * ) r;\n\n        for(d = 0; d < 3; d++) {\n            switch(fmt[i]) {\n                case '-':\n                    dr[d] = rsum1[d] / Ntot;\n                    break;\n                case '<':\n                    dr[d] = rmin[d];\n                    break;\n                case '>':\n                    dr[d] = rmax[d];\n                    break;\n                case 's':\n                    dr[d] = sqrt(rsum2[d] / Ntot - pow(rsum1[d] / Ntot, 2));\n                    break;\n                case 'S':\n                    dr[d] = sqrt(1.0 * Ntot / (Ntot - 1.)) * sqrt(rsum2[d] / Ntot - pow(rsum1[d] / Ntot, 2));\n                    break;\n                case 'v':\n                    dr[d] = (rsum2[d] / Ntot - pow(rsum1[d] / Ntot, 2));\n                    break;\n                case 'V':\n                    dr[d] = (1.0 * Ntot / (Ntot - 1.)) * (rsum2[d] / Ntot - pow(rsum1[d] / Ntot, 2));\n                    break;\n                default:\n                    fastpm_raise(-1, \"Unknown format str. Use '<->sSvV'\\n\");\n            }\n        }\n    }\n    va_end(va);\n}\n\nvoid\nfastpm_store_steal(FastPMStore * p, FastPMStore * po, FastPMColumnTags attributes)\n{\n    int c;\n    for(c = 0; c < 32; c ++) {\n        if (!(p->_column_info[c].attribute & attributes)) continue;\n        po->columns[c] = p->columns[c];\n    }\n\n    po->np = p->np;\n    po->meta = p->meta;\n}\n\nstatic void\n_fastpm_store_copy(FastPMStore * p, ptrdiff_t start, FastPMStore * po, ptrdiff_t offset, size_t ncopy)\n{\n    if(ncopy + start > p->np) {\n        fastpm_raise(-1, \"Copy out of bounds from source FastPMStore: asking for %td but has %td\\n\", ncopy + start, p->np);\n    }\n    if(ncopy + offset > po->np_upper) {\n        fastpm_raise(-1, \"Not enough storage in target FastPMStore: asking for %td but has %td\\n\", ncopy + offset, po->np_upper);\n    }\n\n    int c;\n    for(c = 0; c < 32; c ++) {\n        if(!po->columns[c]) continue;\n        size_t elsize = po->_column_info[c].elsize;\n\n        memcpy(po->columns[c] + offset * elsize,\n                p->columns[c] + start * elsize, elsize * ncopy);\n\n    }\n    po->np = offset + ncopy;\n    po->meta = p->meta;\n}\n\nvoid\nfastpm_store_copy(FastPMStore * p, FastPMStore * po)\n{\n    _fastpm_store_copy(p, 0, po, 0, p->np);\n}\n\nvoid\nfastpm_store_take(FastPMStore * p, ptrdiff_t i, FastPMStore * po, ptrdiff_t j)\n{\n    _fastpm_store_copy(p, i, po, j, 1);\n}\n\n/* extends p by extra. */\nvoid\nfastpm_store_extend(FastPMStore * p, FastPMStore * extra)\n{\n    _fastpm_store_copy(extra, 0, p, p->np, extra->np);\n}\n\nvoid\nfastpm_store_fill_subsample_mask(FastPMStore * p,\n        double fraction,\n        FastPMParticleMaskType * mask,\n        MPI_Comm comm)\n{\n    gsl_rng * random_generator = gsl_rng_alloc(gsl_rng_ranlxd1);\n    int ThisTask;\n    MPI_Comm_rank(comm, &ThisTask);\n\n    /* set uncorrelated seeds */\n    double seed=1231584; //FIXME: set this properly.\n    gsl_rng_set(random_generator, seed);\n    int d;\n\n    for(d = 0; d < ThisTask * 8; d++) {\n        seed = 0x7fffffff * gsl_rng_uniform(random_generator);\n    }\n\n    gsl_rng_set(random_generator, seed);\n\n    memset(mask, 0, p->np * sizeof(mask[0]));\n\n    ptrdiff_t i;\n    for(i=0; i < p->np; i++) {\n        double rand_i = gsl_rng_uniform(random_generator);\n        int flag = fraction > 1 || rand_i <= fraction;\n        mask[i] = flag;\n    }\n\n    gsl_rng_free(random_generator);\n}\n\nvoid\nfastpm_store_fill_subsample_mask_every_dim(FastPMStore * p,\n                                              int every, /* take 1 every 'every' per dimension */\n                                              FastPMParticleMaskType * mask)\n{\n    if(!fastpm_store_has_q(p)) {\n        /* This can be relaxed by using a less strict subsample algorithm, e.g. subsample by a hash of ID. */\n        fastpm_raise(-1, \"Subsample is not supported if the store does not have meta.q.\");\n    }\n    /* UNUSED */\n    memset(mask, 0, p->np * sizeof(mask[0]));\n\n    ptrdiff_t i, d;\n    for(i = 0; i < p->np; i++) {\n        ptrdiff_t pabs[3];   //pabs is the iq index. move out of loop?\n        uint64_t id = p->id[i];\n        fastpm_store_get_iq_from_id(p, id, pabs);\n\n        int flag = 1;\n        for(d = 0; d < 3; d++) {\n            flag *= !(pabs[d] % every);\n        }\n        mask[i] = flag;\n    }\n}\n\n/*\n * Create a subsample, keeping only those with mask == True;\n *\n * if po is NULL, only return number of items.\n * */\nsize_t\nfastpm_store_subsample(FastPMStore * p, FastPMParticleMaskType * mask, FastPMStore * po)\n{\n    ptrdiff_t i;\n    ptrdiff_t j;\n\n    j = 0;\n    for(i = 0; i < p->np; i ++) {\n        if(!mask[i]) continue;\n        /* just counting */\n        if(po == NULL) { j++; continue; }\n        /* avoid memcpy of same address if we are doing subsample inplace */\n        if(p == po && j == i) {j ++; continue; }\n\n        int c;\n        for(c = 0; c < 32; c ++) {\n            if (!po->columns[c]) continue;\n\n            size_t elsize = po->_column_info[c].elsize;\n            memcpy(po->columns[c] + j * elsize, p->columns[c] + i * elsize, elsize);\n        }\n\n        j ++;\n    }\n\n    if(po) {\n        po->np = j;\n        po->meta = p->meta;   ///????\n    }\n    return j;\n}\n\n\n#if 0\nstatic ptrdiff_t\nbinary_search(double foo, double a[], size_t n) {\n    ptrdiff_t left = 0, right = n;\n    ptrdiff_t mid;\n    /* find the right side, because hist would count the number < edge, not <= edge */\n    if(a[left] > foo) {\n        return 0;\n    }\n    if(a[right - 1] <= foo) {\n        return n;\n    }\n    while(right - left > 1) {\n        mid = left + ((right - left - 1) >> 1);\n        double pivot = a[mid];\n        if(pivot > foo) {\n            right = mid + 1;\n            /* a[right - 1] > foo; */\n        } else {\n            left = mid + 1;\n            /* a[left] <= foo; */\n        }\n    }\n    return left;\n}\n#endif\n/* this is cumulative */\nvoid\nfastpm_store_histogram_aemit_sorted(FastPMStore * store,\n        int64_t * hist,\n        double * aedges,\n        size_t nedges,\n        MPI_Comm comm)\n{\n    ptrdiff_t i;\n\n    int64_t * hist1 = malloc(sizeof(hist1[0]) * (nedges + 1));\n\n    memset(hist1, 0, sizeof(hist1[0]) * (nedges + 1));\n\n#pragma omp parallel\n    {\n        /* FIXME: use standard reduction with OpenMP 4.7 */\n\n        int64_t * hist2 = malloc(sizeof(hist2[0]) * (nedges + 1));\n        memset(hist2, 0, sizeof(hist2[0]) * (nedges + 1));\n\n        int iedge = 0;\n\n        /* this works because openmp will send each thread at most 1\n         * chunk with the static scheduling; thus a thread never sees\n         * out of order aemit */\n        #pragma omp for schedule(static)\n        for(i = 0; i < store->np; i ++) {\n            while(iedge < nedges && store->aemit[i] >= aedges[iedge]) iedge ++;\n\n//           int ibin = binary_search(store->aemit[i], aedges, nedges);\n//           if(ibin != iedge) abort();\n\n            hist2[iedge] ++;\n        }\n\n        #pragma omp critical\n        {\n            for(i = 0; i < nedges + 1; i ++) {\n                hist1[i] += hist2[i];\n            }\n        }\n\n        free(hist2);\n    }\n\n    MPI_Allreduce(MPI_IN_PLACE, hist1, nedges + 1, MPI_LONG, MPI_SUM, comm);\n\n    for(i = 0; i < nedges + 1; i ++) {\n        hist[i] += hist1[i];\n    }\n\n    free(hist1);\n}\n", "meta": {"hexsha": "520d999737bc533abdcc8f30c8482e567a050681", "size": 32231, "ext": "c", "lang": "C", "max_stars_repo_path": "fastpm/libfastpm/store.c", "max_stars_repo_name": "sbird/FastPMRunner", "max_stars_repo_head_hexsha": "f38f6e69c603fb699436b645fe7b4eb418ee82c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fastpm/libfastpm/store.c", "max_issues_repo_name": "sbird/FastPMRunner", "max_issues_repo_head_hexsha": "f38f6e69c603fb699436b645fe7b4eb418ee82c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-04-19T23:01:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-24T05:51:04.000Z", "max_forks_repo_path": "fastpm/libfastpm/store.c", "max_forks_repo_name": "sbird/FastPMRunner", "max_forks_repo_head_hexsha": "f38f6e69c603fb699436b645fe7b4eb418ee82c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-14T23:24:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-14T23:24:19.000Z", "avg_line_length": 29.1419529837, "max_line_length": 142, "alphanum_fraction": 0.5471130278, "num_tokens": 9779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2450850131323717, "lm_q2_score": 0.022629198755950593, "lm_q1q2_score": 0.0055460774742772}}
{"text": "/*\n * This file is part of the GROMACS molecular simulation package.\n *\n * Copyright (c) 1991-2000, University of Groningen, The Netherlands.\n * Copyright (c) 2001-2008, The GROMACS development team,\n * check out http://www.gromacs.org for more information.\n * Copyright (c) 2012,2013, by the GROMACS development team, led by\n * David van der Spoel, Berk Hess, Erik Lindahl, and including many\n * others, as listed in the AUTHORS file in the top-level source\n * directory and at http://www.gromacs.org.\n *\n * GROMACS is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public License\n * as published by the Free Software Foundation; either version 2.1\n * of the License, or (at your option) any later version.\n *\n * GROMACS is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with GROMACS; if not, see\n * http://www.gnu.org/licenses, or write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.\n *\n * If you want to redistribute modifications to GROMACS, please\n * consider that scientific software is very special. Version\n * control is crucial - bugs must be traceable. We will be happy to\n * consider code for inclusion in the official distribution, but\n * derived work must not be called official GROMACS. Details are found\n * in the README & COPYING files - if they are missing, get the\n * official version at http://www.gromacs.org.\n *\n * To help us fund GROMACS development, we humbly ask that you cite\n * the research papers on the package. Check out http://www.gromacs.org.\n */\n#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n#include <math.h>\n\n/*#define HAVE_NN_LOOPS*/\n\n#include \"gmx_omp.h\"\n\n#include \"statutil.h\"\n#include \"copyrite.h\"\n#include \"sysstuff.h\"\n#include \"txtdump.h\"\n#include \"futil.h\"\n#include \"tpxio.h\"\n#include \"physics.h\"\n#include \"macros.h\"\n#include \"gmx_fatal.h\"\n#include \"index.h\"\n#include \"smalloc.h\"\n#include \"vec.h\"\n#include \"xvgr.h\"\n#include \"gstat.h\"\n#include \"matio.h\"\n#include \"string2.h\"\n#include \"pbc.h\"\n#include \"correl.h\"\n#include \"gmx_ana.h\"\n#include \"geminate.h\"\n\ntypedef short int t_E;\ntypedef int t_EEst;\n#define max_hx 7\ntypedef int t_hx[max_hx];\n#define NRHXTYPES max_hx\nconst char *hxtypenames[NRHXTYPES] =\n{\"n-n\", \"n-n+1\", \"n-n+2\", \"n-n+3\", \"n-n+4\", \"n-n+5\", \"n-n>6\"};\n#define MAXHH 4\n\n#ifdef GMX_OPENMP\n#define MASTER_THREAD_ONLY(threadNr) ((threadNr) == 0)\n#else\n#define MASTER_THREAD_ONLY(threadNr) ((threadNr) == (threadNr))\n#endif\n\n/* -----------------------------------------*/\n\nenum {\n    gr0,  gr1,    grI,  grNR\n};\nenum {\n    hbNo, hbDist, hbHB, hbNR, hbR2\n};\nenum {\n    noDA, ACC, DON, DA, INGROUP\n};\nenum {\n    NN_NULL, NN_NONE, NN_BINARY, NN_1_over_r3, NN_dipole, NN_NR\n};\n\nstatic const char *grpnames[grNR] = {\"0\", \"1\", \"I\" };\n\nstatic gmx_bool    bDebug = FALSE;\n\n#define HB_NO 0\n#define HB_YES 1<<0\n#define HB_INS 1<<1\n#define HB_YESINS HB_YES|HB_INS\n#define HB_NR (1<<2)\n#define MAXHYDRO 4\n\n#define ISHB(h)   (((h) & 2) == 2)\n#define ISDIST(h) (((h) & 1) == 1)\n#define ISDIST2(h) (((h) & 4) == 4)\n#define ISACC(h)  (((h) & 1) == 1)\n#define ISDON(h)  (((h) & 2) == 2)\n#define ISINGRP(h) (((h) & 4) == 4)\n\ntypedef struct {\n    int      nr;\n    int      maxnr;\n    atom_id *atoms;\n} t_ncell;\n\ntypedef struct {\n    t_ncell d[grNR];\n    t_ncell a[grNR];\n} t_gridcell;\n\ntypedef int     t_icell[grNR];\ntypedef atom_id h_id[MAXHYDRO];\n\ntypedef struct {\n    int      history[MAXHYDRO];\n    /* Has this hbond existed ever? If so as hbDist or hbHB or both.\n     * Result is stored as a bitmap (1 = hbDist) || (2 = hbHB)\n     */\n    /* Bitmask array which tells whether a hbond is present\n     * at a given time. Either of these may be NULL\n     */\n    int            n0;                 /* First frame a HB was found     */\n    int            nframes, maxframes; /* Amount of frames in this hbond */\n    unsigned int **h;\n    unsigned int **g;\n    /* See Xu and Berne, JPCB 105 (2001), p. 11929. We define the\n     * function g(t) = [1-h(t)] H(t) where H(t) is one when the donor-\n     * acceptor distance is less than the user-specified distance (typically\n     * 0.35 nm).\n     */\n} t_hbond;\n\ntypedef struct {\n    int      nra, max_nra;\n    atom_id *acc;             /* Atom numbers of the acceptors     */\n    int     *grp;             /* Group index                       */\n    int     *aptr;            /* Map atom number to acceptor index */\n} t_acceptors;\n\ntypedef struct {\n    int       nrd, max_nrd;\n    int      *don;               /* Atom numbers of the donors         */\n    int      *grp;               /* Group index                        */\n    int      *dptr;              /* Map atom number to donor index     */\n    int      *nhydro;            /* Number of hydrogens for each donor */\n    h_id     *hydro;             /* The atom numbers of the hydrogens  */\n    h_id     *nhbonds;           /* The number of HBs per H at current */\n} t_donors;\n\n/* Tune this to match memory requirements. It should be a signed integer type, e.g. signed char.*/\n#define PSTYPE int\n\ntypedef struct {\n    int     len;   /* The length of frame and p. */\n    int    *frame; /* The frames at which transitio*/\n    PSTYPE *p;\n} t_pShift;\n\ntypedef struct {\n    /* Periodicity history. Used for the reversible geminate recombination. */\n    t_pShift **pHist; /* The periodicity of every hbond in t_hbdata->hbmap:\n                       *   pHist[d][a]. We can safely assume that the same\n                       *   periodic shift holds for all hydrogens of a da-pair.\n                       *\n                       * Nowadays it only stores TRANSITIONS, and not the shift at every frame.\n                       *   That saves a LOT of memory, an hopefully kills a mysterious bug where\n                       *   pHist gets contaminated. */\n\n    PSTYPE nper;      /* The length of p2i */\n    ivec  *p2i;       /* Maps integer to periodic shift for a pair.*/\n    matrix P;         /* Projection matrix to find the box shifts. */\n    int    gemtype;   /* enumerated type */\n} t_gemPeriod;\n\ntypedef struct {\n    int     nframes;\n    int    *Etot; /* Total energy for each frame */\n    t_E ****E;    /* Energy estimate for [d][a][h][frame-n0] */\n} t_hbEmap;\n\ntypedef struct {\n    gmx_bool        bHBmap, bDAnr, bGem;\n    int             wordlen;\n    /* The following arrays are nframes long */\n    int             nframes, max_frames, maxhydro;\n    int            *nhb, *ndist;\n    h_id           *n_bound;\n    real           *time;\n    t_icell        *danr;\n    t_hx           *nhx;\n    /* These structures are initialized from the topology at start up */\n    t_donors        d;\n    t_acceptors     a;\n    /* This holds a matrix with all possible hydrogen bonds */\n    int             nrhb, nrdist;\n    t_hbond      ***hbmap;\n#ifdef HAVE_NN_LOOPS\n    t_hbEmap        hbE;\n#endif\n    /* For parallelization reasons this will have to be a pointer.\n     * Otherwise discrepancies may arise between the periodicity data\n     * seen by different threads. */\n    t_gemPeriod *per;\n} t_hbdata;\n\nstatic void clearPshift(t_pShift *pShift)\n{\n    if (pShift->len > 0)\n    {\n        sfree(pShift->p);\n        sfree(pShift->frame);\n        pShift->len = 0;\n    }\n}\n\nstatic void calcBoxProjection(matrix B, matrix P)\n{\n    const int vp[] = {XX, YY, ZZ};\n    int       i, j;\n    int       m, n;\n    matrix    M, N, U;\n\n    for (i = 0; i < 3; i++)\n    {\n        m = vp[i];\n        for (j = 0; j < 3; j++)\n        {\n            n       = vp[j];\n            U[m][n] = i == j ? 1 : 0;\n        }\n    }\n    m_inv(B, M);\n    for (i = 0; i < 3; i++)\n    {\n        m = vp[i];\n        mvmul(M, U[m], P[m]);\n    }\n    transpose(P, N);\n}\n\nstatic void calcBoxDistance(matrix P, rvec d, ivec ibd)\n{\n    /* returns integer distance in box coordinates.\n     * P is the projection matrix from cartesian coordinates\n     * obtained with calcBoxProjection(). */\n    int  i;\n    rvec bd;\n    mvmul(P, d, bd);\n    /* extend it by 0.5 in all directions since (int) rounds toward 0.*/\n    for (i = 0; i < 3; i++)\n    {\n        bd[i] = bd[i] + (bd[i] < 0 ? -0.5 : 0.5);\n    }\n    ibd[XX] = (int)bd[XX];\n    ibd[YY] = (int)bd[YY];\n    ibd[ZZ] = (int)bd[ZZ];\n}\n\n/* Changed argument 'bMerge' into 'oneHB' below,\n * since -contact should cause maxhydro to be 1,\n * not just -merge.\n * - Erik Marklund May 29, 2006\n */\n\nstatic PSTYPE periodicIndex(ivec r, t_gemPeriod *per, gmx_bool daSwap)\n{\n    /* Try to merge hbonds on the fly. That means that if the\n     * acceptor and donor are mergable, then:\n     * 1) store the hb-info so that acceptor id > donor id,\n     * 2) add the periodic shift in pairs, so that [-x,-y,-z] is\n     *    stored in per.p2i[] whenever acceptor id < donor id.\n     * Note that [0,0,0] should already be the first element of per.p2i\n     * by the time this function is called. */\n\n    /* daSwap is TRUE if the donor and acceptor were swapped.\n     * If so, then the negative vector should be used. */\n    PSTYPE i;\n\n    if (per->p2i == NULL || per->nper == 0)\n    {\n        gmx_fatal(FARGS, \"'per' not initialized properly.\");\n    }\n    for (i = 0; i < per->nper; i++)\n    {\n        if (r[XX] == per->p2i[i][XX] &&\n            r[YY] == per->p2i[i][YY] &&\n            r[ZZ] == per->p2i[i][ZZ])\n        {\n            return i;\n        }\n    }\n    /* Not found apparently. Add it to the list! */\n    /* printf(\"New shift found: %i,%i,%i\\n\",r[XX],r[YY],r[ZZ]); */\n\n#pragma omp critical\n    {\n        if (!per->p2i)\n        {\n            fprintf(stderr, \"p2i not initialized. This shouldn't happen!\\n\");\n            snew(per->p2i, 1);\n        }\n        else\n        {\n            srenew(per->p2i, per->nper+2);\n        }\n        copy_ivec(r, per->p2i[per->nper]);\n        (per->nper)++;\n\n        /* Add the mirror too. It's rather likely that it'll be needed. */\n        per->p2i[per->nper][XX] = -r[XX];\n        per->p2i[per->nper][YY] = -r[YY];\n        per->p2i[per->nper][ZZ] = -r[ZZ];\n        (per->nper)++;\n    } /* omp critical */\n    return per->nper - 1 - (daSwap ? 0 : 1);\n}\n\nstatic t_hbdata *mk_hbdata(gmx_bool bHBmap, gmx_bool bDAnr, gmx_bool oneHB, gmx_bool bGem, int gemmode)\n{\n    t_hbdata *hb;\n\n    snew(hb, 1);\n    hb->wordlen = 8*sizeof(unsigned int);\n    hb->bHBmap  = bHBmap;\n    hb->bDAnr   = bDAnr;\n    hb->bGem    = bGem;\n    if (oneHB)\n    {\n        hb->maxhydro = 1;\n    }\n    else\n    {\n        hb->maxhydro = MAXHYDRO;\n    }\n    snew(hb->per, 1);\n    hb->per->gemtype = bGem ? gemmode : 0;\n\n    return hb;\n}\n\nstatic void mk_hbmap(t_hbdata *hb, gmx_bool bTwo)\n{\n    int  i, j;\n\n    snew(hb->hbmap, hb->d.nrd);\n    for (i = 0; (i < hb->d.nrd); i++)\n    {\n        snew(hb->hbmap[i], hb->a.nra);\n        if (hb->hbmap[i] == NULL)\n        {\n            gmx_fatal(FARGS, \"Could not allocate enough memory for hbmap\");\n        }\n        for (j = 0; (j > hb->a.nra); j++)\n        {\n            hb->hbmap[i][j] = NULL;\n        }\n    }\n}\n\n/* Consider redoing pHist so that is only stores transitions between\n * periodicities and not the periodicity for all frames. This eats heaps of memory. */\nstatic void mk_per(t_hbdata *hb)\n{\n    int i, j;\n    if (hb->bGem)\n    {\n        snew(hb->per->pHist, hb->d.nrd);\n        for (i = 0; i < hb->d.nrd; i++)\n        {\n            snew(hb->per->pHist[i], hb->a.nra);\n            if (hb->per->pHist[i] == NULL)\n            {\n                gmx_fatal(FARGS, \"Could not allocate enough memory for per->pHist\");\n            }\n            for (j = 0; j < hb->a.nra; j++)\n            {\n                clearPshift(&(hb->per->pHist[i][j]));\n            }\n        }\n        /* add the [0,0,0] shift to element 0 of p2i. */\n        snew(hb->per->p2i, 1);\n        clear_ivec(hb->per->p2i[0]);\n        hb->per->nper = 1;\n    }\n}\n\n#ifdef HAVE_NN_LOOPS\nstatic void mk_hbEmap (t_hbdata *hb, int n0)\n{\n    int i, j, k;\n    hb->hbE.E       = NULL;\n    hb->hbE.nframes = 0;\n    snew(hb->hbE.E, hb->d.nrd);\n    for (i = 0; i < hb->d.nrd; i++)\n    {\n        snew(hb->hbE.E[i], hb->a.nra);\n        for (j = 0; j < hb->a.nra; j++)\n        {\n            snew(hb->hbE.E[i][j], MAXHYDRO);\n            for (k = 0; k < MAXHYDRO; k++)\n            {\n                hb->hbE.E[i][j][k] = NULL;\n            }\n        }\n    }\n    hb->hbE.Etot = NULL;\n}\n\nstatic void free_hbEmap (t_hbdata *hb)\n{\n    int i, j, k;\n    for (i = 0; i < hb->d.nrd; i++)\n    {\n        for (j = 0; j < hb->a.nra; j++)\n        {\n            for (k = 0; k < MAXHYDRO; k++)\n            {\n                sfree(hb->hbE.E[i][j][k]);\n            }\n            sfree(hb->hbE.E[i][j]);\n        }\n        sfree(hb->hbE.E[i]);\n    }\n    sfree(hb->hbE.E);\n    sfree(hb->hbE.Etot);\n}\n\nstatic void addFramesNN(t_hbdata *hb, int frame)\n{\n\n#define DELTAFRAMES_HBE 10\n\n    int d, a, h, nframes;\n\n    if (frame >= hb->hbE.nframes)\n    {\n        nframes =  hb->hbE.nframes + DELTAFRAMES_HBE;\n        srenew(hb->hbE.Etot, nframes);\n\n        for (d = 0; d < hb->d.nrd; d++)\n        {\n            for (a = 0; a < hb->a.nra; a++)\n            {\n                for (h = 0; h < hb->d.nhydro[d]; h++)\n                {\n                    srenew(hb->hbE.E[d][a][h], nframes);\n                }\n            }\n        }\n\n        hb->hbE.nframes += DELTAFRAMES_HBE;\n    }\n}\n\nstatic t_E calcHbEnergy(int d, int a, int h, rvec x[], t_EEst EEst,\n                        matrix box, rvec hbox, t_donors *donors)\n{\n    /* d     - donor atom\n     * a     - acceptor atom\n     * h     - hydrogen\n     * alpha - angle between dipoles\n     * x[]   - atomic positions\n     * EEst  - the type of energy estimate (see enum in hbplugin.h)\n     * box   - the box vectors   \\\n     * hbox  - half box lengths  _These two are only needed for the pbc correction\n     */\n\n    t_E  E;\n    rvec dist;\n    rvec dipole[2], xmol[3], xmean[2];\n    int  i;\n    real r, realE;\n\n    if (d == a)\n    {\n        /* Self-interaction */\n        return NONSENSE_E;\n    }\n\n    switch (EEst)\n    {\n        case NN_BINARY:\n            /* This is a simple binary existence function that sets E=1 whenever\n             * the distance between the oxygens is equal too or less than 0.35 nm.\n             */\n            rvec_sub(x[d], x[a], dist);\n            pbc_correct_gem(dist, box, hbox);\n            if (norm(dist) <= 0.35)\n            {\n                E = 1;\n            }\n            else\n            {\n                E = 0;\n            }\n            break;\n\n        case NN_1_over_r3:\n            /* Negative potential energy of a dipole.\n             * E = -cos(alpha) * 1/r^3 */\n\n            copy_rvec(x[d], xmol[0]);                                 /* donor */\n            copy_rvec(x[donors->hydro[donors->dptr[d]][0]], xmol[1]); /* hydrogen */\n            copy_rvec(x[donors->hydro[donors->dptr[d]][1]], xmol[2]); /* hydrogen */\n\n            svmul(15.9994*(1/1.008), xmol[0], xmean[0]);\n            rvec_inc(xmean[0], xmol[1]);\n            rvec_inc(xmean[0], xmol[2]);\n            for (i = 0; i < 3; i++)\n            {\n                xmean[0][i] /= (15.9994 + 1.008 + 1.008)/1.008;\n            }\n\n            /* Assumes that all acceptors are also donors. */\n            copy_rvec(x[a], xmol[0]);                                 /* acceptor */\n            copy_rvec(x[donors->hydro[donors->dptr[a]][0]], xmol[1]); /* hydrogen */\n            copy_rvec(x[donors->hydro[donors->dptr[a]][1]], xmol[2]); /* hydrogen */\n\n\n            svmul(15.9994*(1/1.008), xmol[0], xmean[1]);\n            rvec_inc(xmean[1], xmol[1]);\n            rvec_inc(xmean[1], xmol[2]);\n            for (i = 0; i < 3; i++)\n            {\n                xmean[1][i] /= (15.9994 + 1.008 + 1.008)/1.008;\n            }\n\n            rvec_sub(xmean[0], xmean[1], dist);\n            pbc_correct_gem(dist, box, hbox);\n            r = norm(dist);\n\n            realE = pow(r, -3.0);\n            E     = (t_E)(SCALEFACTOR_E * realE);\n            break;\n\n        case NN_dipole:\n            /* Negative potential energy of a (unpolarizable) dipole.\n             * E = -cos(alpha) * 1/r^3 */\n            clear_rvec(dipole[1]);\n            clear_rvec(dipole[0]);\n\n            copy_rvec(x[d], xmol[0]);                                 /* donor */\n            copy_rvec(x[donors->hydro[donors->dptr[d]][0]], xmol[1]); /* hydrogen */\n            copy_rvec(x[donors->hydro[donors->dptr[d]][1]], xmol[2]); /* hydrogen */\n\n            rvec_inc(dipole[0], xmol[1]);\n            rvec_inc(dipole[0], xmol[2]);\n            for (i = 0; i < 3; i++)\n            {\n                dipole[0][i] *= 0.5;\n            }\n            rvec_dec(dipole[0], xmol[0]);\n\n            svmul(15.9994*(1/1.008), xmol[0], xmean[0]);\n            rvec_inc(xmean[0], xmol[1]);\n            rvec_inc(xmean[0], xmol[2]);\n            for (i = 0; i < 3; i++)\n            {\n                xmean[0][i] /= (15.9994 + 1.008 + 1.008)/1.008;\n            }\n\n            /* Assumes that all acceptors are also donors. */\n            copy_rvec(x[a], xmol[0]);                                 /* acceptor */\n            copy_rvec(x[donors->hydro[donors->dptr[a]][0]], xmol[1]); /* hydrogen */\n            copy_rvec(x[donors->hydro[donors->dptr[a]][2]], xmol[2]); /* hydrogen */\n\n\n            rvec_inc(dipole[1], xmol[1]);\n            rvec_inc(dipole[1], xmol[2]);\n            for (i = 0; i < 3; i++)\n            {\n                dipole[1][i] *= 0.5;\n            }\n            rvec_dec(dipole[1], xmol[0]);\n\n            svmul(15.9994*(1/1.008), xmol[0], xmean[1]);\n            rvec_inc(xmean[1], xmol[1]);\n            rvec_inc(xmean[1], xmol[2]);\n            for (i = 0; i < 3; i++)\n            {\n                xmean[1][i] /= (15.9994 + 1.008 + 1.008)/1.008;\n            }\n\n            rvec_sub(xmean[0], xmean[1], dist);\n            pbc_correct_gem(dist, box, hbox);\n            r = norm(dist);\n\n            double cosalpha = cos_angle(dipole[0], dipole[1]);\n            realE = cosalpha * pow(r, -3.0);\n            E     = (t_E)(SCALEFACTOR_E * realE);\n            break;\n\n        default:\n            printf(\"Can't do that type of energy estimate: %i\\n.\", EEst);\n            E = NONSENSE_E;\n    }\n\n    return E;\n}\n\nstatic void storeHbEnergy(t_hbdata *hb, int d, int a, int h, t_E E, int frame)\n{\n    /* hb - hbond data structure\n       d  - donor\n       a  - acceptor\n       h  - hydrogen\n       E  - estimate of the energy\n       frame - the current frame.\n     */\n\n    /* Store the estimated energy */\n    if (E == NONSENSE_E)\n    {\n        E = 0;\n    }\n\n    hb->hbE.E[d][a][h][frame] = E;\n\n#pragma omp critical\n    {\n        hb->hbE.Etot[frame] += E;\n    }\n}\n#endif /* HAVE_NN_LOOPS */\n\n\n/* Finds -v[] in the periodicity index */\nstatic int findMirror(PSTYPE p, ivec v[], PSTYPE nper)\n{\n    PSTYPE i;\n    ivec   u;\n    for (i = 0; i < nper; i++)\n    {\n        if (v[i][XX] == -(v[p][XX]) &&\n            v[i][YY] == -(v[p][YY]) &&\n            v[i][ZZ] == -(v[p][ZZ]))\n        {\n            return (int)i;\n        }\n    }\n    printf(\"Couldn't find mirror of [%i, %i, %i], index \\n\",\n           v[p][XX],\n           v[p][YY],\n           v[p][ZZ]);\n    return -1;\n}\n\n\nstatic void add_frames(t_hbdata *hb, int nframes)\n{\n    int  i, j, k, l;\n\n    if (nframes >= hb->max_frames)\n    {\n        hb->max_frames += 4096;\n        srenew(hb->time, hb->max_frames);\n        srenew(hb->nhb, hb->max_frames);\n        srenew(hb->ndist, hb->max_frames);\n        srenew(hb->n_bound, hb->max_frames);\n        srenew(hb->nhx, hb->max_frames);\n        if (hb->bDAnr)\n        {\n            srenew(hb->danr, hb->max_frames);\n        }\n    }\n    hb->nframes = nframes;\n}\n\n#define OFFSET(frame) (frame / 32)\n#define MASK(frame)   (1 << (frame % 32))\n\nstatic void _set_hb(unsigned int hbexist[], unsigned int frame, gmx_bool bValue)\n{\n    if (bValue)\n    {\n        hbexist[OFFSET(frame)] |= MASK(frame);\n    }\n    else\n    {\n        hbexist[OFFSET(frame)] &= ~MASK(frame);\n    }\n}\n\nstatic gmx_bool is_hb(unsigned int hbexist[], int frame)\n{\n    return ((hbexist[OFFSET(frame)] & MASK(frame)) != 0) ? 1 : 0;\n}\n\nstatic void set_hb(t_hbdata *hb, int id, int ih, int ia, int frame, int ihb)\n{\n    unsigned int *ghptr = NULL;\n\n    if (ihb == hbHB)\n    {\n        ghptr = hb->hbmap[id][ia]->h[ih];\n    }\n    else if (ihb == hbDist)\n    {\n        ghptr = hb->hbmap[id][ia]->g[ih];\n    }\n    else\n    {\n        gmx_fatal(FARGS, \"Incomprehensible iValue %d in set_hb\", ihb);\n    }\n\n    _set_hb(ghptr, frame-hb->hbmap[id][ia]->n0, TRUE);\n}\n\nstatic void addPshift(t_pShift *pHist, PSTYPE p, int frame)\n{\n    if (pHist->len == 0)\n    {\n        snew(pHist->frame, 1);\n        snew(pHist->p, 1);\n        pHist->len      = 1;\n        pHist->frame[0] = frame;\n        pHist->p[0]     = p;\n        return;\n    }\n    else\n    if (pHist->p[pHist->len-1] != p)\n    {\n        pHist->len++;\n        srenew(pHist->frame, pHist->len);\n        srenew(pHist->p, pHist->len);\n        pHist->frame[pHist->len-1] = frame;\n        pHist->p[pHist->len-1]     = p;\n    }     /* Otherwise, there is no transition. */\n    return;\n}\n\nstatic PSTYPE getPshift(t_pShift pHist, int frame)\n{\n    int f, i;\n\n    if (pHist.len == 0\n        || (pHist.len > 0 && pHist.frame[0] > frame))\n    {\n        return -1;\n    }\n\n    for (i = 0; i < pHist.len; i++)\n    {\n        f = pHist.frame[i];\n        if (f == frame)\n        {\n            return pHist.p[i];\n        }\n        if (f > frame)\n        {\n            return pHist.p[i-1];\n        }\n    }\n\n    /* It seems that frame is after the last periodic transition. Return the last periodicity. */\n    return pHist.p[pHist.len-1];\n}\n\nstatic void add_ff(t_hbdata *hbd, int id, int h, int ia, int frame, int ihb, PSTYPE p)\n{\n    int         i, j, n;\n    t_hbond    *hb       = hbd->hbmap[id][ia];\n    int         maxhydro = min(hbd->maxhydro, hbd->d.nhydro[id]);\n    int         wlen     = hbd->wordlen;\n    int         delta    = 32*wlen;\n    gmx_bool    bGem     = hbd->bGem;\n\n    if (!hb->h[0])\n    {\n        hb->n0        = frame;\n        hb->maxframes = delta;\n        for (i = 0; (i < maxhydro); i++)\n        {\n            snew(hb->h[i], hb->maxframes/wlen);\n            snew(hb->g[i], hb->maxframes/wlen);\n        }\n    }\n    else\n    {\n        hb->nframes = frame-hb->n0;\n        /* We need a while loop here because hbonds may be returning\n         * after a long time.\n         */\n        while (hb->nframes >= hb->maxframes)\n        {\n            n = hb->maxframes + delta;\n            for (i = 0; (i < maxhydro); i++)\n            {\n                srenew(hb->h[i], n/wlen);\n                srenew(hb->g[i], n/wlen);\n                for (j = hb->maxframes/wlen; (j < n/wlen); j++)\n                {\n                    hb->h[i][j] = 0;\n                    hb->g[i][j] = 0;\n                }\n            }\n\n            hb->maxframes = n;\n        }\n    }\n    if (frame >= 0)\n    {\n        set_hb(hbd, id, h, ia, frame, ihb);\n        if (bGem)\n        {\n            if (p >= hbd->per->nper)\n            {\n                gmx_fatal(FARGS, \"invalid shift: p=%u, nper=%u\", p, hbd->per->nper);\n            }\n            else\n            {\n                addPshift(&(hbd->per->pHist[id][ia]), p, frame);\n            }\n\n        }\n    }\n\n}\n\nstatic void inc_nhbonds(t_donors *ddd, int d, int h)\n{\n    int j;\n    int dptr = ddd->dptr[d];\n\n    for (j = 0; (j < ddd->nhydro[dptr]); j++)\n    {\n        if (ddd->hydro[dptr][j] == h)\n        {\n            ddd->nhbonds[dptr][j]++;\n            break;\n        }\n    }\n    if (j == ddd->nhydro[dptr])\n    {\n        gmx_fatal(FARGS, \"No such hydrogen %d on donor %d\\n\", h+1, d+1);\n    }\n}\n\nstatic int _acceptor_index(t_acceptors *a, int grp, atom_id i,\n                           const char *file, int line)\n{\n    int ai = a->aptr[i];\n\n    if (a->grp[ai] != grp)\n    {\n        if (debug && bDebug)\n        {\n            fprintf(debug, \"Acc. group inconsist.. grp[%d] = %d, grp = %d (%s, %d)\\n\",\n                    ai, a->grp[ai], grp, file, line);\n        }\n        return NOTSET;\n    }\n    else\n    {\n        return ai;\n    }\n}\n#define acceptor_index(a, grp, i) _acceptor_index(a, grp, i, __FILE__, __LINE__)\n\nstatic int _donor_index(t_donors *d, int grp, atom_id i, const char *file, int line)\n{\n    int di = d->dptr[i];\n\n    if (di == NOTSET)\n    {\n        return NOTSET;\n    }\n\n    if (d->grp[di] != grp)\n    {\n        if (debug && bDebug)\n        {\n            fprintf(debug, \"Don. group inconsist.. grp[%d] = %d, grp = %d (%s, %d)\\n\",\n                    di, d->grp[di], grp, file, line);\n        }\n        return NOTSET;\n    }\n    else\n    {\n        return di;\n    }\n}\n#define donor_index(d, grp, i) _donor_index(d, grp, i, __FILE__, __LINE__)\n\nstatic gmx_bool isInterchangable(t_hbdata *hb, int d, int a, int grpa, int grpd)\n{\n    /* g_hbond doesn't allow overlapping groups */\n    if (grpa != grpd)\n    {\n        return FALSE;\n    }\n    return\n        donor_index(&hb->d, grpd, a) != NOTSET\n        && acceptor_index(&hb->a, grpa, d) != NOTSET;\n}\n\n\nstatic void add_hbond(t_hbdata *hb, int d, int a, int h, int grpd, int grpa,\n                      int frame, gmx_bool bMerge, int ihb, gmx_bool bContact, PSTYPE p)\n{\n    int      k, id, ia, hh;\n    gmx_bool daSwap = FALSE;\n\n    if ((id = hb->d.dptr[d]) == NOTSET)\n    {\n        gmx_fatal(FARGS, \"No donor atom %d\", d+1);\n    }\n    else if (grpd != hb->d.grp[id])\n    {\n        gmx_fatal(FARGS, \"Inconsistent donor groups, %d iso %d, atom %d\",\n                  grpd, hb->d.grp[id], d+1);\n    }\n    if ((ia = hb->a.aptr[a]) == NOTSET)\n    {\n        gmx_fatal(FARGS, \"No acceptor atom %d\", a+1);\n    }\n    else if (grpa != hb->a.grp[ia])\n    {\n        gmx_fatal(FARGS, \"Inconsistent acceptor groups, %d iso %d, atom %d\",\n                  grpa, hb->a.grp[ia], a+1);\n    }\n\n    if (bMerge)\n    {\n\n        if (isInterchangable(hb, d, a, grpd, grpa) && d > a)\n        /* Then swap identity so that the id of d is lower then that of a.\n         *\n         * This should really be redundant by now, as is_hbond() now ought to return\n         * hbNo in the cases where this conditional is TRUE. */\n        {\n            daSwap = TRUE;\n            k      = d;\n            d      = a;\n            a      = k;\n\n            /* Now repeat donor/acc check. */\n            if ((id = hb->d.dptr[d]) == NOTSET)\n            {\n                gmx_fatal(FARGS, \"No donor atom %d\", d+1);\n            }\n            else if (grpd != hb->d.grp[id])\n            {\n                gmx_fatal(FARGS, \"Inconsistent donor groups, %d iso %d, atom %d\",\n                          grpd, hb->d.grp[id], d+1);\n            }\n            if ((ia = hb->a.aptr[a]) == NOTSET)\n            {\n                gmx_fatal(FARGS, \"No acceptor atom %d\", a+1);\n            }\n            else if (grpa != hb->a.grp[ia])\n            {\n                gmx_fatal(FARGS, \"Inconsistent acceptor groups, %d iso %d, atom %d\",\n                          grpa, hb->a.grp[ia], a+1);\n            }\n        }\n    }\n\n    if (hb->hbmap)\n    {\n        /* Loop over hydrogens to find which hydrogen is in this particular HB */\n        if ((ihb == hbHB) && !bMerge && !bContact)\n        {\n            for (k = 0; (k < hb->d.nhydro[id]); k++)\n            {\n                if (hb->d.hydro[id][k] == h)\n                {\n                    break;\n                }\n            }\n            if (k == hb->d.nhydro[id])\n            {\n                gmx_fatal(FARGS, \"Donor %d does not have hydrogen %d (a = %d)\",\n                          d+1, h+1, a+1);\n            }\n        }\n        else\n        {\n            k = 0;\n        }\n\n        if (hb->bHBmap)\n        {\n\n#pragma omp critical\n            {\n                if (hb->hbmap[id][ia] == NULL)\n                {\n                    snew(hb->hbmap[id][ia], 1);\n                    snew(hb->hbmap[id][ia]->h, hb->maxhydro);\n                    snew(hb->hbmap[id][ia]->g, hb->maxhydro);\n                }\n                add_ff(hb, id, k, ia, frame, ihb, p);\n            }\n        }\n\n        /* Strange construction with frame >=0 is a relic from old code\n         * for selected hbond analysis. It may be necessary again if that\n         * is made to work again.\n         */\n        if (frame >= 0)\n        {\n            hh = hb->hbmap[id][ia]->history[k];\n            if (ihb == hbHB)\n            {\n                hb->nhb[frame]++;\n                if (!(ISHB(hh)))\n                {\n                    hb->hbmap[id][ia]->history[k] = hh | 2;\n                    hb->nrhb++;\n                }\n            }\n            else\n            {\n                if (ihb == hbDist)\n                {\n                    hb->ndist[frame]++;\n                    if (!(ISDIST(hh)))\n                    {\n                        hb->hbmap[id][ia]->history[k] = hh | 1;\n                        hb->nrdist++;\n                    }\n                }\n            }\n        }\n    }\n    else\n    {\n        if (frame >= 0)\n        {\n            if (ihb == hbHB)\n            {\n                hb->nhb[frame]++;\n            }\n            else\n            {\n                if (ihb == hbDist)\n                {\n                    hb->ndist[frame]++;\n                }\n            }\n        }\n    }\n    if (bMerge && daSwap)\n    {\n        h = hb->d.hydro[id][0];\n    }\n    /* Increment number if HBonds per H */\n    if (ihb == hbHB && !bContact)\n    {\n        inc_nhbonds(&(hb->d), d, h);\n    }\n}\n\nstatic char *mkatomname(t_atoms *atoms, int i)\n{\n    static char buf[32];\n    int         rnr;\n\n    rnr = atoms->atom[i].resind;\n    sprintf(buf, \"%4s%d%-4s\",\n            *atoms->resinfo[rnr].name, atoms->resinfo[rnr].nr, *atoms->atomname[i]);\n\n    return buf;\n}\n\nstatic void gen_datable(atom_id *index, int isize, unsigned char *datable, int natoms)\n{\n    /* Generates table of all atoms and sets the ingroup bit for atoms in index[] */\n    int i;\n\n    for (i = 0; i < isize; i++)\n    {\n        if (index[i] >= natoms)\n        {\n            gmx_fatal(FARGS, \"Atom has index %d larger than number of atoms %d.\", index[i], natoms);\n        }\n        datable[index[i]] |= INGROUP;\n    }\n}\n\nstatic void clear_datable_grp(unsigned char *datable, int size)\n{\n    /* Clears group information from the table */\n    int        i;\n    const char mask = !(char)INGROUP;\n    if (size > 0)\n    {\n        for (i = 0; i < size; i++)\n        {\n            datable[i] &= mask;\n        }\n    }\n}\n\nstatic void add_acc(t_acceptors *a, int ia, int grp)\n{\n    if (a->nra >= a->max_nra)\n    {\n        a->max_nra += 16;\n        srenew(a->acc, a->max_nra);\n        srenew(a->grp, a->max_nra);\n    }\n    a->grp[a->nra]   = grp;\n    a->acc[a->nra++] = ia;\n}\n\nstatic void search_acceptors(t_topology *top, int isize,\n                             atom_id *index, t_acceptors *a, int grp,\n                             gmx_bool bNitAcc,\n                             gmx_bool bContact, gmx_bool bDoIt, unsigned char *datable)\n{\n    int i, n;\n\n    if (bDoIt)\n    {\n        for (i = 0; (i < isize); i++)\n        {\n            n = index[i];\n            if ((bContact ||\n                 (((*top->atoms.atomname[n])[0] == 'O') ||\n                  (bNitAcc && ((*top->atoms.atomname[n])[0] == 'N')))) &&\n                ISINGRP(datable[n]))\n            {\n                datable[n] |= ACC; /* set the atom's acceptor flag in datable. */\n                add_acc(a, n, grp);\n            }\n        }\n    }\n    snew(a->aptr, top->atoms.nr);\n    for (i = 0; (i < top->atoms.nr); i++)\n    {\n        a->aptr[i] = NOTSET;\n    }\n    for (i = 0; (i < a->nra); i++)\n    {\n        a->aptr[a->acc[i]] = i;\n    }\n}\n\nstatic void add_h2d(int id, int ih, t_donors *ddd)\n{\n    int i;\n\n    for (i = 0; (i < ddd->nhydro[id]); i++)\n    {\n        if (ddd->hydro[id][i] == ih)\n        {\n            printf(\"Hm. This isn't the first time I found this donor (%d,%d)\\n\",\n                   ddd->don[id], ih);\n            break;\n        }\n    }\n    if (i == ddd->nhydro[id])\n    {\n        if (ddd->nhydro[id] >= MAXHYDRO)\n        {\n            gmx_fatal(FARGS, \"Donor %d has more than %d hydrogens!\",\n                      ddd->don[id], MAXHYDRO);\n        }\n        ddd->hydro[id][i] = ih;\n        ddd->nhydro[id]++;\n    }\n}\n\nstatic void add_dh(t_donors *ddd, int id, int ih, int grp, unsigned char *datable)\n{\n    int i;\n\n    if (ISDON(datable[id]) || !datable)\n    {\n        if (ddd->dptr[id] == NOTSET)   /* New donor */\n        {\n            i             = ddd->nrd;\n            ddd->dptr[id] = i;\n        }\n        else\n        {\n            i = ddd->dptr[id];\n        }\n\n        if (i == ddd->nrd)\n        {\n            if (ddd->nrd >= ddd->max_nrd)\n            {\n                ddd->max_nrd += 128;\n                srenew(ddd->don, ddd->max_nrd);\n                srenew(ddd->nhydro, ddd->max_nrd);\n                srenew(ddd->hydro, ddd->max_nrd);\n                srenew(ddd->nhbonds, ddd->max_nrd);\n                srenew(ddd->grp, ddd->max_nrd);\n            }\n            ddd->don[ddd->nrd]    = id;\n            ddd->nhydro[ddd->nrd] = 0;\n            ddd->grp[ddd->nrd]    = grp;\n            ddd->nrd++;\n        }\n        else\n        {\n            ddd->don[i] = id;\n        }\n        add_h2d(i, ih, ddd);\n    }\n    else\n    if (datable)\n    {\n        printf(\"Warning: Atom %d is not in the d/a-table!\\n\", id);\n    }\n}\n\nstatic void search_donors(t_topology *top, int isize, atom_id *index,\n                          t_donors *ddd, int grp, gmx_bool bContact, gmx_bool bDoIt,\n                          unsigned char *datable)\n{\n    int            i, j, nra, n;\n    t_functype     func_type;\n    t_ilist       *interaction;\n    atom_id        nr1, nr2, nr3;\n    gmx_bool       stop;\n\n    if (!ddd->dptr)\n    {\n        snew(ddd->dptr, top->atoms.nr);\n        for (i = 0; (i < top->atoms.nr); i++)\n        {\n            ddd->dptr[i] = NOTSET;\n        }\n    }\n\n    if (bContact)\n    {\n        if (bDoIt)\n        {\n            for (i = 0; (i < isize); i++)\n            {\n                datable[index[i]] |= DON;\n                add_dh(ddd, index[i], -1, grp, datable);\n            }\n        }\n    }\n    else\n    {\n        for (func_type = 0; (func_type < F_NRE); func_type++)\n        {\n            interaction = &(top->idef.il[func_type]);\n            if (func_type == F_POSRES)\n            {\n                /* The ilist looks strange for posre. Bug in grompp?\n                 * We don't need posre interactions for hbonds anyway.*/\n                continue;\n            }\n            for (i = 0; i < interaction->nr;\n                 i += interaction_function[top->idef.functype[interaction->iatoms[i]]].nratoms+1)\n            {\n                /* next function */\n                if (func_type != top->idef.functype[interaction->iatoms[i]])\n                {\n                    fprintf(stderr, \"Error in func_type %s\",\n                            interaction_function[func_type].longname);\n                    continue;\n                }\n\n                /* check out this functype */\n                if (func_type == F_SETTLE)\n                {\n                    nr1 = interaction->iatoms[i+1];\n                    nr2 = interaction->iatoms[i+2];\n                    nr3 = interaction->iatoms[i+3];\n\n                    if (ISINGRP(datable[nr1]))\n                    {\n                        if (ISINGRP(datable[nr2]))\n                        {\n                            datable[nr1] |= DON;\n                            add_dh(ddd, nr1, nr1+1, grp, datable);\n                        }\n                        if (ISINGRP(datable[nr3]))\n                        {\n                            datable[nr1] |= DON;\n                            add_dh(ddd, nr1, nr1+2, grp, datable);\n                        }\n                    }\n                }\n                else if (IS_CHEMBOND(func_type))\n                {\n                    for (j = 0; j < 2; j++)\n                    {\n                        nr1 = interaction->iatoms[i+1+j];\n                        nr2 = interaction->iatoms[i+2-j];\n                        if ((*top->atoms.atomname[nr1][0] == 'H') &&\n                            ((*top->atoms.atomname[nr2][0] == 'O') ||\n                             (*top->atoms.atomname[nr2][0] == 'N')) &&\n                            ISINGRP(datable[nr1]) && ISINGRP(datable[nr2]))\n                        {\n                            datable[nr2] |= DON;\n                            add_dh(ddd, nr2, nr1, grp, datable);\n                        }\n                    }\n                }\n            }\n        }\n#ifdef SAFEVSITES\n        for (func_type = 0; func_type < F_NRE; func_type++)\n        {\n            interaction = &top->idef.il[func_type];\n            for (i = 0; i < interaction->nr;\n                 i += interaction_function[top->idef.functype[interaction->iatoms[i]]].nratoms+1)\n            {\n                /* next function */\n                if (func_type != top->idef.functype[interaction->iatoms[i]])\n                {\n                    gmx_incons(\"function type in search_donors\");\n                }\n\n                if (interaction_function[func_type].flags & IF_VSITE)\n                {\n                    nr1 = interaction->iatoms[i+1];\n                    if (*top->atoms.atomname[nr1][0]  == 'H')\n                    {\n                        nr2  = nr1-1;\n                        stop = FALSE;\n                        while (!stop && ( *top->atoms.atomname[nr2][0] == 'H'))\n                        {\n                            if (nr2)\n                            {\n                                nr2--;\n                            }\n                            else\n                            {\n                                stop = TRUE;\n                            }\n                        }\n                        if (!stop && ( ( *top->atoms.atomname[nr2][0] == 'O') ||\n                                       ( *top->atoms.atomname[nr2][0] == 'N') ) &&\n                            ISINGRP(datable[nr1]) && ISINGRP(datable[nr2]))\n                        {\n                            datable[nr2] |= DON;\n                            add_dh(ddd, nr2, nr1, grp, datable);\n                        }\n                    }\n                }\n            }\n        }\n#endif\n    }\n}\n\nstatic t_gridcell ***init_grid(gmx_bool bBox, rvec box[], real rcut, ivec ngrid)\n{\n    t_gridcell ***grid;\n    int           i, y, z;\n\n    if (bBox)\n    {\n        for (i = 0; i < DIM; i++)\n        {\n            ngrid[i] = (box[i][i]/(1.2*rcut));\n        }\n    }\n\n    if (!bBox || (ngrid[XX] < 3) || (ngrid[YY] < 3) || (ngrid[ZZ] < 3) )\n    {\n        for (i = 0; i < DIM; i++)\n        {\n            ngrid[i] = 1;\n        }\n    }\n    else\n    {\n        printf(\"\\nWill do grid-seach on %dx%dx%d grid, rcut=%g\\n\",\n               ngrid[XX], ngrid[YY], ngrid[ZZ], rcut);\n    }\n    snew(grid, ngrid[ZZ]);\n    for (z = 0; z < ngrid[ZZ]; z++)\n    {\n        snew((grid)[z], ngrid[YY]);\n        for (y = 0; y < ngrid[YY]; y++)\n        {\n            snew((grid)[z][y], ngrid[XX]);\n        }\n    }\n    return grid;\n}\n\nstatic void reset_nhbonds(t_donors *ddd)\n{\n    int i, j;\n\n    for (i = 0; (i < ddd->nrd); i++)\n    {\n        for (j = 0; (j < MAXHH); j++)\n        {\n            ddd->nhbonds[i][j] = 0;\n        }\n    }\n}\n\nvoid pbc_correct_gem(rvec dx, matrix box, rvec hbox);\n\nstatic void build_grid(t_hbdata *hb, rvec x[], rvec xshell,\n                       gmx_bool bBox, matrix box, rvec hbox,\n                       real rcut, real rshell,\n                       ivec ngrid, t_gridcell ***grid)\n{\n    int         i, m, gr, xi, yi, zi, nr;\n    atom_id    *ad;\n    ivec        grididx;\n    rvec        invdelta, dshell, xtemp = {0, 0, 0};\n    t_ncell    *newgrid;\n    gmx_bool    bDoRshell, bInShell, bAcc;\n    real        rshell2 = 0;\n    int         gx, gy, gz;\n    int         dum = -1;\n\n    bDoRshell = (rshell > 0);\n    rshell2   = sqr(rshell);\n    bInShell  = TRUE;\n\n#define DBB(x) if (debug && bDebug) fprintf(debug, \"build_grid, line %d, %s = %d\\n\", __LINE__,#x, x)\n    DBB(dum);\n    for (m = 0; m < DIM; m++)\n    {\n        hbox[m] = box[m][m]*0.5;\n        if (bBox)\n        {\n            invdelta[m] = ngrid[m]/box[m][m];\n            if (1/invdelta[m] < rcut)\n            {\n                gmx_fatal(FARGS, \"Your computational box has shrunk too much.\\n\"\n                          \"%s can not handle this situation, sorry.\\n\",\n                          ShortProgram());\n            }\n        }\n        else\n        {\n            invdelta[m] = 0;\n        }\n    }\n    grididx[XX] = 0;\n    grididx[YY] = 0;\n    grididx[ZZ] = 0;\n    DBB(dum);\n    /* resetting atom counts */\n    for (gr = 0; (gr < grNR); gr++)\n    {\n        for (zi = 0; zi < ngrid[ZZ]; zi++)\n        {\n            for (yi = 0; yi < ngrid[YY]; yi++)\n            {\n                for (xi = 0; xi < ngrid[XX]; xi++)\n                {\n                    grid[zi][yi][xi].d[gr].nr = 0;\n                    grid[zi][yi][xi].a[gr].nr = 0;\n                }\n            }\n        }\n        DBB(dum);\n\n        /* put atoms in grid cells */\n        for (bAcc = FALSE; (bAcc <= TRUE); bAcc++)\n        {\n            if (bAcc)\n            {\n                nr = hb->a.nra;\n                ad = hb->a.acc;\n            }\n            else\n            {\n                nr = hb->d.nrd;\n                ad = hb->d.don;\n            }\n            DBB(bAcc);\n            for (i = 0; (i < nr); i++)\n            {\n                /* check if we are inside the shell */\n                /* if bDoRshell=FALSE then bInShell=TRUE always */\n                DBB(i);\n                if (bDoRshell)\n                {\n                    bInShell = TRUE;\n                    rvec_sub(x[ad[i]], xshell, dshell);\n                    if (bBox)\n                    {\n                        if (FALSE && !hb->bGem)\n                        {\n                            for (m = DIM-1; m >= 0 && bInShell; m--)\n                            {\n                                if (dshell[m] < -hbox[m])\n                                {\n                                    rvec_inc(dshell, box[m]);\n                                }\n                                else if (dshell[m] >= hbox[m])\n                                {\n                                    dshell[m] -= 2*hbox[m];\n                                }\n                                /* if we're outside the cube, we're outside the sphere also! */\n                                if ( (dshell[m] > rshell) || (-dshell[m] > rshell) )\n                                {\n                                    bInShell = FALSE;\n                                }\n                            }\n                        }\n                        else\n                        {\n                            gmx_bool bDone = FALSE;\n                            while (!bDone)\n                            {\n                                bDone = TRUE;\n                                for (m = DIM-1; m >= 0 && bInShell; m--)\n                                {\n                                    if (dshell[m] < -hbox[m])\n                                    {\n                                        bDone = FALSE;\n                                        rvec_inc(dshell, box[m]);\n                                    }\n                                    if (dshell[m] >= hbox[m])\n                                    {\n                                        bDone      = FALSE;\n                                        dshell[m] -= 2*hbox[m];\n                                    }\n                                }\n                            }\n                            for (m = DIM-1; m >= 0 && bInShell; m--)\n                            {\n                                /* if we're outside the cube, we're outside the sphere also! */\n                                if ( (dshell[m] > rshell) || (-dshell[m] > rshell) )\n                                {\n                                    bInShell = FALSE;\n                                }\n                            }\n                        }\n                    }\n                    /* if we're inside the cube, check if we're inside the sphere */\n                    if (bInShell)\n                    {\n                        bInShell = norm2(dshell) < rshell2;\n                    }\n                }\n                DBB(i);\n                if (bInShell)\n                {\n                    if (bBox)\n                    {\n                        if (hb->bGem)\n                        {\n                            copy_rvec(x[ad[i]], xtemp);\n                        }\n                        pbc_correct_gem(x[ad[i]], box, hbox);\n                    }\n                    for (m = DIM-1; m >= 0; m--)\n                    {\n                        if (TRUE || !hb->bGem)\n                        {\n                            /* put atom in the box */\n                            while (x[ad[i]][m] < 0)\n                            {\n                                rvec_inc(x[ad[i]], box[m]);\n                            }\n                            while (x[ad[i]][m] >= box[m][m])\n                            {\n                                rvec_dec(x[ad[i]], box[m]);\n                            }\n                        }\n                        /* determine grid index of atom */\n                        grididx[m] = x[ad[i]][m]*invdelta[m];\n                        grididx[m] = (grididx[m]+ngrid[m]) % ngrid[m];\n                    }\n                    if (hb->bGem)\n                    {\n                        copy_rvec(xtemp, x[ad[i]]); /* copy back */\n                    }\n                    gx = grididx[XX];\n                    gy = grididx[YY];\n                    gz = grididx[ZZ];\n                    range_check(gx, 0, ngrid[XX]);\n                    range_check(gy, 0, ngrid[YY]);\n                    range_check(gz, 0, ngrid[ZZ]);\n                    DBB(gx);\n                    DBB(gy);\n                    DBB(gz);\n                    /* add atom to grid cell */\n                    if (bAcc)\n                    {\n                        newgrid = &(grid[gz][gy][gx].a[gr]);\n                    }\n                    else\n                    {\n                        newgrid = &(grid[gz][gy][gx].d[gr]);\n                    }\n                    if (newgrid->nr >= newgrid->maxnr)\n                    {\n                        newgrid->maxnr += 10;\n                        DBB(newgrid->maxnr);\n                        srenew(newgrid->atoms, newgrid->maxnr);\n                    }\n                    DBB(newgrid->nr);\n                    newgrid->atoms[newgrid->nr] = ad[i];\n                    newgrid->nr++;\n                }\n            }\n        }\n    }\n}\n\nstatic void count_da_grid(ivec ngrid, t_gridcell ***grid, t_icell danr)\n{\n    int gr, xi, yi, zi;\n\n    for (gr = 0; (gr < grNR); gr++)\n    {\n        danr[gr] = 0;\n        for (zi = 0; zi < ngrid[ZZ]; zi++)\n        {\n            for (yi = 0; yi < ngrid[YY]; yi++)\n            {\n                for (xi = 0; xi < ngrid[XX]; xi++)\n                {\n                    danr[gr] += grid[zi][yi][xi].d[gr].nr;\n                }\n            }\n        }\n    }\n}\n\n/* The grid loop.\n * Without a box, the grid is 1x1x1, so all loops are 1 long.\n * With a rectangular box (bTric==FALSE) all loops are 3 long.\n * With a triclinic box all loops are 3 long, except when a cell is\n * located next to one of the box edges which is not parallel to the\n * x/y-plane, in that case all cells in a line or layer are searched.\n * This could be implemented slightly more efficient, but the code\n * would get much more complicated.\n */\nstatic inline gmx_bool grid_loop_begin(int n, int x, gmx_bool bTric, gmx_bool bEdge)\n{\n    return ((n == 1) ? x : bTric && bEdge ? 0     : (x-1));\n}\nstatic inline gmx_bool grid_loop_end(int n, int x, gmx_bool bTric, gmx_bool bEdge)\n{\n    return ((n == 1) ? x : bTric && bEdge ? (n-1) : (x+1));\n}\nstatic inline int grid_mod(int j, int n)\n{\n    return (j+n) % (n);\n}\n\nstatic void dump_grid(FILE *fp, ivec ngrid, t_gridcell ***grid)\n{\n    int gr, x, y, z, sum[grNR];\n\n    fprintf(fp, \"grid %dx%dx%d\\n\", ngrid[XX], ngrid[YY], ngrid[ZZ]);\n    for (gr = 0; gr < grNR; gr++)\n    {\n        sum[gr] = 0;\n        fprintf(fp, \"GROUP %d (%s)\\n\", gr, grpnames[gr]);\n        for (z = 0; z < ngrid[ZZ]; z += 2)\n        {\n            fprintf(fp, \"Z=%d,%d\\n\", z, z+1);\n            for (y = 0; y < ngrid[YY]; y++)\n            {\n                for (x = 0; x < ngrid[XX]; x++)\n                {\n                    fprintf(fp, \"%3d\", grid[x][y][z].d[gr].nr);\n                    sum[gr] += grid[z][y][x].d[gr].nr;\n                    fprintf(fp, \"%3d\", grid[x][y][z].a[gr].nr);\n                    sum[gr] += grid[z][y][x].a[gr].nr;\n\n                }\n                fprintf(fp, \" | \");\n                if ( (z+1) < ngrid[ZZ])\n                {\n                    for (x = 0; x < ngrid[XX]; x++)\n                    {\n                        fprintf(fp, \"%3d\", grid[z+1][y][x].d[gr].nr);\n                        sum[gr] += grid[z+1][y][x].d[gr].nr;\n                        fprintf(fp, \"%3d\", grid[z+1][y][x].a[gr].nr);\n                        sum[gr] += grid[z+1][y][x].a[gr].nr;\n                    }\n                }\n                fprintf(fp, \"\\n\");\n            }\n        }\n    }\n    fprintf(fp, \"TOTALS:\");\n    for (gr = 0; gr < grNR; gr++)\n    {\n        fprintf(fp, \" %d=%d\", gr, sum[gr]);\n    }\n    fprintf(fp, \"\\n\");\n}\n\n/* New GMX record! 5 * in a row. Congratulations!\n * Sorry, only four left.\n */\nstatic void free_grid(ivec ngrid, t_gridcell ****grid)\n{\n    int           y, z;\n    t_gridcell ***g = *grid;\n\n    for (z = 0; z < ngrid[ZZ]; z++)\n    {\n        for (y = 0; y < ngrid[YY]; y++)\n        {\n            sfree(g[z][y]);\n        }\n        sfree(g[z]);\n    }\n    sfree(g);\n    g = NULL;\n}\n\nvoid pbc_correct_gem(rvec dx, matrix box, rvec hbox)\n{\n    int      m;\n    gmx_bool bDone = FALSE;\n    while (!bDone)\n    {\n        bDone = TRUE;\n        for (m = DIM-1; m >= 0; m--)\n        {\n            if (dx[m] < -hbox[m])\n            {\n                bDone = FALSE;\n                rvec_inc(dx, box[m]);\n            }\n            if (dx[m] >= hbox[m])\n            {\n                bDone = FALSE;\n                rvec_dec(dx, box[m]);\n            }\n        }\n    }\n}\n\n/* Added argument r2cut, changed contact and implemented\n * use of second cut-off.\n * - Erik Marklund, June 29, 2006\n */\nstatic int is_hbond(t_hbdata *hb, int grpd, int grpa, int d, int a,\n                    real rcut, real r2cut, real ccut,\n                    rvec x[], gmx_bool bBox, matrix box, rvec hbox,\n                    real *d_ha, real *ang, gmx_bool bDA, int *hhh,\n                    gmx_bool bContact, gmx_bool bMerge, PSTYPE *p)\n{\n    int      h, hh, id, ja, ihb;\n    rvec     r_da, r_ha, r_dh, r = {0, 0, 0};\n    ivec     ri;\n    real     rc2, r2c2, rda2, rha2, ca;\n    gmx_bool HAinrange = FALSE; /* If !bDA. Needed for returning hbDist in a correct way. */\n    gmx_bool daSwap    = FALSE;\n\n    if (d == a)\n    {\n        return hbNo;\n    }\n\n    if (((id = donor_index(&hb->d, grpd, d)) == NOTSET) ||\n        ((ja = acceptor_index(&hb->a, grpa, a)) == NOTSET))\n    {\n        return hbNo;\n    }\n\n    rc2  = rcut*rcut;\n    r2c2 = r2cut*r2cut;\n\n    rvec_sub(x[d], x[a], r_da);\n    /* Insert projection code here */\n\n    if (bMerge && d > a && isInterchangable(hb, d, a, grpd, grpa))\n    {\n        /* Then this hbond/contact will be found again, or it has already been found. */\n        /*return hbNo;*/\n    }\n    if (bBox)\n    {\n        if (d > a && bMerge && isInterchangable(hb, d, a, grpd, grpa)) /* acceptor is also a donor and vice versa? */\n        {                                                              /* return hbNo; */\n            daSwap = TRUE;                                             /* If so, then their history should be filed with donor and acceptor swapped. */\n        }\n        if (hb->bGem)\n        {\n            copy_rvec(r_da, r); /* Save this for later */\n            pbc_correct_gem(r_da, box, hbox);\n        }\n        else\n        {\n            pbc_correct_gem(r_da, box, hbox);\n        }\n    }\n    rda2 = iprod(r_da, r_da);\n\n    if (bContact)\n    {\n        if (daSwap && grpa == grpd)\n        {\n            return hbNo;\n        }\n        if (rda2 <= rc2)\n        {\n            if (hb->bGem)\n            {\n                calcBoxDistance(hb->per->P, r, ri);\n                *p = periodicIndex(ri, hb->per, daSwap);    /* find (or add) periodicity index. */\n            }\n            return hbHB;\n        }\n        else if (rda2 < r2c2)\n        {\n            return hbDist;\n        }\n        else\n        {\n            return hbNo;\n        }\n    }\n    *hhh = NOTSET;\n\n    if (bDA && (rda2 > rc2))\n    {\n        return hbNo;\n    }\n\n    for (h = 0; (h < hb->d.nhydro[id]); h++)\n    {\n        hh   = hb->d.hydro[id][h];\n        rha2 = rc2+1;\n        if (!bDA)\n        {\n            rvec_sub(x[hh], x[a], r_ha);\n            if (bBox)\n            {\n                pbc_correct_gem(r_ha, box, hbox);\n            }\n            rha2 = iprod(r_ha, r_ha);\n        }\n\n        if (hb->bGem)\n        {\n            calcBoxDistance(hb->per->P, r, ri);\n            *p = periodicIndex(ri, hb->per, daSwap);    /* find periodicity index. */\n        }\n\n        if (bDA || (!bDA && (rha2 <= rc2)))\n        {\n            rvec_sub(x[d], x[hh], r_dh);\n            if (bBox)\n            {\n                pbc_correct_gem(r_dh, box, hbox);\n            }\n\n            if (!bDA)\n            {\n                HAinrange = TRUE;\n            }\n            ca = cos_angle(r_dh, r_da);\n            /* if angle is smaller, cos is larger */\n            if (ca >= ccut)\n            {\n                *hhh  = hh;\n                *d_ha = sqrt(bDA ? rda2 : rha2);\n                *ang  = acos(ca);\n                return hbHB;\n            }\n        }\n    }\n    if (bDA || (!bDA && HAinrange))\n    {\n        return hbDist;\n    }\n    else\n    {\n        return hbNo;\n    }\n}\n\n/* Fixed previously undiscovered bug in the merge\n   code, where the last frame of each hbond disappears.\n   - Erik Marklund, June 1, 2006 */\n/* Added the following arguments:\n *   ptmp[] - temporary periodicity hisory\n *   a1     - identity of first acceptor/donor\n *   a2     - identity of second acceptor/donor\n * - Erik Marklund, FEB 20 2010 */\n\n/* Merging is now done on the fly, so do_merge is most likely obsolete now.\n * Will do some more testing before removing the function entirely.\n * - Erik Marklund, MAY 10 2010 */\nstatic void do_merge(t_hbdata *hb, int ntmp,\n                     unsigned int htmp[], unsigned int gtmp[], PSTYPE ptmp[],\n                     t_hbond *hb0, t_hbond *hb1, int a1, int a2)\n{\n    /* Here we need to make sure we're treating periodicity in\n     * the right way for the geminate recombination kinetics. */\n\n    int       m, mm, n00, n01, nn0, nnframes;\n    PSTYPE    pm;\n    t_pShift *pShift;\n\n    /* Decide where to start from when merging */\n    n00      = hb0->n0;\n    n01      = hb1->n0;\n    nn0      = min(n00, n01);\n    nnframes = max(n00 + hb0->nframes, n01 + hb1->nframes) - nn0;\n    /* Initiate tmp arrays */\n    for (m = 0; (m < ntmp); m++)\n    {\n        htmp[m] = 0;\n        gtmp[m] = 0;\n        ptmp[m] = 0;\n    }\n    /* Fill tmp arrays with values due to first HB */\n    /* Once again '<' had to be replaced with '<='\n       to catch the last frame in which the hbond\n       appears.\n       - Erik Marklund, June 1, 2006 */\n    for (m = 0; (m <= hb0->nframes); m++)\n    {\n        mm       = m+n00-nn0;\n        htmp[mm] = is_hb(hb0->h[0], m);\n        if (hb->bGem)\n        {\n            pm = getPshift(hb->per->pHist[a1][a2], m+hb0->n0);\n            if (pm > hb->per->nper)\n            {\n                gmx_fatal(FARGS, \"Illegal shift!\");\n            }\n            else\n            {\n                ptmp[mm] = pm; /*hb->per->pHist[a1][a2][m];*/\n            }\n        }\n    }\n    /* If we're doing geminate recompbination we usually don't need the distances.\n     * Let's save some memory and time. */\n    if (TRUE || !hb->bGem || hb->per->gemtype == gemAD)\n    {\n        for (m = 0; (m <= hb0->nframes); m++)\n        {\n            mm       = m+n00-nn0;\n            gtmp[mm] = is_hb(hb0->g[0], m);\n        }\n    }\n    /* Next HB */\n    for (m = 0; (m <= hb1->nframes); m++)\n    {\n        mm       = m+n01-nn0;\n        htmp[mm] = htmp[mm] || is_hb(hb1->h[0], m);\n        gtmp[mm] = gtmp[mm] || is_hb(hb1->g[0], m);\n        if (hb->bGem /* && ptmp[mm] != 0 */)\n        {\n\n            /* If this hbond has been seen before with donor and acceptor swapped,\n             * then we need to find the mirrored (*-1) periodicity vector to truely\n             * merge the hbond history. */\n            pm = findMirror(getPshift(hb->per->pHist[a2][a1], m+hb1->n0), hb->per->p2i, hb->per->nper);\n            /* Store index of mirror */\n            if (pm > hb->per->nper)\n            {\n                gmx_fatal(FARGS, \"Illegal shift!\");\n            }\n            ptmp[mm] = pm;\n        }\n    }\n    /* Reallocate target array */\n    if (nnframes > hb0->maxframes)\n    {\n        srenew(hb0->h[0], 4+nnframes/hb->wordlen);\n        srenew(hb0->g[0], 4+nnframes/hb->wordlen);\n    }\n    if (NULL != hb->per->pHist)\n    {\n        clearPshift(&(hb->per->pHist[a1][a2]));\n    }\n\n    /* Copy temp array to target array */\n    for (m = 0; (m <= nnframes); m++)\n    {\n        _set_hb(hb0->h[0], m, htmp[m]);\n        _set_hb(hb0->g[0], m, gtmp[m]);\n        if (hb->bGem)\n        {\n            addPshift(&(hb->per->pHist[a1][a2]), ptmp[m], m+nn0);\n        }\n    }\n\n    /* Set scalar variables */\n    hb0->n0        = nn0;\n    hb0->maxframes = nnframes;\n}\n\n/* Added argument bContact for nicer output.\n * Erik Marklund, June 29, 2006\n */\nstatic void merge_hb(t_hbdata *hb, gmx_bool bTwo, gmx_bool bContact)\n{\n    int           i, inrnew, indnew, j, ii, jj, m, id, ia, grp, ogrp, ntmp;\n    unsigned int *htmp, *gtmp;\n    PSTYPE       *ptmp;\n    t_hbond      *hb0, *hb1;\n\n    inrnew = hb->nrhb;\n    indnew = hb->nrdist;\n\n    /* Check whether donors are also acceptors */\n    printf(\"Merging hbonds with Acceptor and Donor swapped\\n\");\n\n    ntmp = 2*hb->max_frames;\n    snew(gtmp, ntmp);\n    snew(htmp, ntmp);\n    snew(ptmp, ntmp);\n    for (i = 0; (i < hb->d.nrd); i++)\n    {\n        fprintf(stderr, \"\\r%d/%d\", i+1, hb->d.nrd);\n        id = hb->d.don[i];\n        ii = hb->a.aptr[id];\n        for (j = 0; (j < hb->a.nra); j++)\n        {\n            ia = hb->a.acc[j];\n            jj = hb->d.dptr[ia];\n            if ((id != ia) && (ii != NOTSET) && (jj != NOTSET) &&\n                (!bTwo || (bTwo && (hb->d.grp[i] != hb->a.grp[j]))))\n            {\n                hb0 = hb->hbmap[i][j];\n                hb1 = hb->hbmap[jj][ii];\n                if (hb0 && hb1 && ISHB(hb0->history[0]) && ISHB(hb1->history[0]))\n                {\n                    do_merge(hb, ntmp, htmp, gtmp, ptmp, hb0, hb1, i, j);\n                    if (ISHB(hb1->history[0]))\n                    {\n                        inrnew--;\n                    }\n                    else if (ISDIST(hb1->history[0]))\n                    {\n                        indnew--;\n                    }\n                    else\n                    if (bContact)\n                    {\n                        gmx_incons(\"No contact history\");\n                    }\n                    else\n                    {\n                        gmx_incons(\"Neither hydrogen bond nor distance\");\n                    }\n                    sfree(hb1->h[0]);\n                    sfree(hb1->g[0]);\n                    if (hb->bGem)\n                    {\n                        clearPshift(&(hb->per->pHist[jj][ii]));\n                    }\n                    hb1->h[0]       = NULL;\n                    hb1->g[0]       = NULL;\n                    hb1->history[0] = hbNo;\n                }\n            }\n        }\n    }\n    fprintf(stderr, \"\\n\");\n    printf(\"- Reduced number of hbonds from %d to %d\\n\", hb->nrhb, inrnew);\n    printf(\"- Reduced number of distances from %d to %d\\n\", hb->nrdist, indnew);\n    hb->nrhb   = inrnew;\n    hb->nrdist = indnew;\n    sfree(gtmp);\n    sfree(htmp);\n    sfree(ptmp);\n}\n\nstatic void do_nhb_dist(FILE *fp, t_hbdata *hb, real t)\n{\n    int  i, j, k, n_bound[MAXHH], nbtot;\n    h_id nhb;\n\n\n    /* Set array to 0 */\n    for (k = 0; (k < MAXHH); k++)\n    {\n        n_bound[k] = 0;\n    }\n    /* Loop over possible donors */\n    for (i = 0; (i < hb->d.nrd); i++)\n    {\n        for (j = 0; (j < hb->d.nhydro[i]); j++)\n        {\n            n_bound[hb->d.nhbonds[i][j]]++;\n        }\n    }\n    fprintf(fp, \"%12.5e\", t);\n    nbtot = 0;\n    for (k = 0; (k < MAXHH); k++)\n    {\n        fprintf(fp, \"  %8d\", n_bound[k]);\n        nbtot += n_bound[k]*k;\n    }\n    fprintf(fp, \"  %8d\\n\", nbtot);\n}\n\n/* Added argument bContact in do_hblife(...). Also\n * added support for -contact in function body.\n * - Erik Marklund, May 31, 2006 */\n/* Changed the contact code slightly.\n * - Erik Marklund, June 29, 2006\n */\nstatic void do_hblife(const char *fn, t_hbdata *hb, gmx_bool bMerge, gmx_bool bContact,\n                      const output_env_t oenv)\n{\n    FILE          *fp;\n    const char    *leg[] = { \"p(t)\", \"t p(t)\" };\n    int           *histo;\n    int            i, j, j0, k, m, nh, ihb, ohb, nhydro, ndump = 0;\n    int            nframes = hb->nframes;\n    unsigned int **h;\n    real           t, x1, dt;\n    double         sum, integral;\n    t_hbond       *hbh;\n\n    snew(h, hb->maxhydro);\n    snew(histo, nframes+1);\n    /* Total number of hbonds analyzed here */\n    for (i = 0; (i < hb->d.nrd); i++)\n    {\n        for (k = 0; (k < hb->a.nra); k++)\n        {\n            hbh = hb->hbmap[i][k];\n            if (hbh)\n            {\n                if (bMerge)\n                {\n                    if (hbh->h[0])\n                    {\n                        h[0]   = hbh->h[0];\n                        nhydro = 1;\n                    }\n                    else\n                    {\n                        nhydro = 0;\n                    }\n                }\n                else\n                {\n                    nhydro = 0;\n                    for (m = 0; (m < hb->maxhydro); m++)\n                    {\n                        if (hbh->h[m])\n                        {\n                            h[nhydro++] = bContact ? hbh->g[m] : hbh->h[m];\n                        }\n                    }\n                }\n                for (nh = 0; (nh < nhydro); nh++)\n                {\n                    ohb = 0;\n                    j0  = 0;\n\n                    /* Changed '<' into '<=' below, just like I\n                       did in the hbm-output-loop in the main code.\n                       - Erik Marklund, May 31, 2006\n                     */\n                    for (j = 0; (j <= hbh->nframes); j++)\n                    {\n                        ihb      = is_hb(h[nh], j);\n                        if (debug && (ndump < 10))\n                        {\n                            fprintf(debug, \"%5d  %5d\\n\", j, ihb);\n                        }\n                        if (ihb != ohb)\n                        {\n                            if (ihb)\n                            {\n                                j0 = j;\n                            }\n                            else\n                            {\n                                histo[j-j0]++;\n                            }\n                            ohb = ihb;\n                        }\n                    }\n                    ndump++;\n                }\n            }\n        }\n    }\n    fprintf(stderr, \"\\n\");\n    if (bContact)\n    {\n        fp = xvgropen(fn, \"Uninterrupted contact lifetime\", output_env_get_xvgr_tlabel(oenv), \"()\", oenv);\n    }\n    else\n    {\n        fp = xvgropen(fn, \"Uninterrupted hydrogen bond lifetime\", output_env_get_xvgr_tlabel(oenv), \"()\",\n                      oenv);\n    }\n\n    xvgr_legend(fp, asize(leg), leg, oenv);\n    j0 = nframes-1;\n    while ((j0 > 0) && (histo[j0] == 0))\n    {\n        j0--;\n    }\n    sum = 0;\n    for (i = 0; (i <= j0); i++)\n    {\n        sum += histo[i];\n    }\n    dt       = hb->time[1]-hb->time[0];\n    sum      = dt*sum;\n    integral = 0;\n    for (i = 1; (i <= j0); i++)\n    {\n        t  = hb->time[i] - hb->time[0] - 0.5*dt;\n        x1 = t*histo[i]/sum;\n        fprintf(fp, \"%8.3f  %10.3e  %10.3e\\n\", t, histo[i]/sum, x1);\n        integral += x1;\n    }\n    integral *= dt;\n    ffclose(fp);\n    printf(\"%s lifetime = %.2f ps\\n\", bContact ? \"Contact\" : \"HB\", integral);\n    printf(\"Note that the lifetime obtained in this manner is close to useless\\n\");\n    printf(\"Use the -ac option instead and check the Forward lifetime\\n\");\n    please_cite(stdout, \"Spoel2006b\");\n    sfree(h);\n    sfree(histo);\n}\n\n/* Changed argument bMerge into oneHB to handle contacts properly.\n * - Erik Marklund, June 29, 2006\n */\nstatic void dump_ac(t_hbdata *hb, gmx_bool oneHB, int nDump)\n{\n    FILE     *fp;\n    int       i, j, k, m, nd, ihb, idist;\n    int       nframes = hb->nframes;\n    gmx_bool  bPrint;\n    t_hbond  *hbh;\n\n    if (nDump <= 0)\n    {\n        return;\n    }\n    fp = ffopen(\"debug-ac.xvg\", \"w\");\n    for (j = 0; (j < nframes); j++)\n    {\n        fprintf(fp, \"%10.3f\", hb->time[j]);\n        for (i = nd = 0; (i < hb->d.nrd) && (nd < nDump); i++)\n        {\n            for (k = 0; (k < hb->a.nra) && (nd < nDump); k++)\n            {\n                bPrint = FALSE;\n                ihb    = idist = 0;\n                hbh    = hb->hbmap[i][k];\n                if (oneHB)\n                {\n                    if (hbh->h[0])\n                    {\n                        ihb    = is_hb(hbh->h[0], j);\n                        idist  = is_hb(hbh->g[0], j);\n                        bPrint = TRUE;\n                    }\n                }\n                else\n                {\n                    for (m = 0; (m < hb->maxhydro) && !ihb; m++)\n                    {\n                        ihb   = ihb   || ((hbh->h[m]) && is_hb(hbh->h[m], j));\n                        idist = idist || ((hbh->g[m]) && is_hb(hbh->g[m], j));\n                    }\n                    /* This is not correct! */\n                    /* What isn't correct? -Erik M */\n                    bPrint = TRUE;\n                }\n                if (bPrint)\n                {\n                    fprintf(fp, \"  %1d-%1d\", ihb, idist);\n                    nd++;\n                }\n            }\n        }\n        fprintf(fp, \"\\n\");\n    }\n    ffclose(fp);\n}\n\nstatic real calc_dg(real tau, real temp)\n{\n    real kbt;\n\n    kbt = BOLTZ*temp;\n    if (tau <= 0)\n    {\n        return -666;\n    }\n    else\n    {\n        return kbt*log(kbt*tau/PLANCK);\n    }\n}\n\ntypedef struct {\n    int   n0, n1, nparams, ndelta;\n    real  kkk[2];\n    real *t, *ct, *nt, *kt, *sigma_ct, *sigma_nt, *sigma_kt;\n} t_luzar;\n\n#ifdef HAVE_LIBGSL\n#include <gsl/gsl_multimin.h>\n#include <gsl/gsl_sf.h>\n#include <gsl/gsl_version.h>\n\nstatic double my_f(const gsl_vector *v, void *params)\n{\n    t_luzar *tl = (t_luzar *)params;\n    int      i;\n    double   tol = 1e-16, chi2 = 0;\n    double   di;\n    real     k, kp;\n\n    for (i = 0; (i < tl->nparams); i++)\n    {\n        tl->kkk[i] = gsl_vector_get(v, i);\n    }\n    k  = tl->kkk[0];\n    kp = tl->kkk[1];\n\n    for (i = tl->n0; (i < tl->n1); i += tl->ndelta)\n    {\n        di = sqr(k*tl->sigma_ct[i]) + sqr(kp*tl->sigma_nt[i]) + sqr(tl->sigma_kt[i]);\n        /*di = 1;*/\n        if (di > tol)\n        {\n            chi2 += sqr(k*tl->ct[i]-kp*tl->nt[i]-tl->kt[i])/di;\n        }\n\n        else\n        {\n            fprintf(stderr, \"WARNING: sigma_ct = %g, sigma_nt = %g, sigma_kt = %g\\n\"\n                    \"di = %g k = %g kp = %g\\n\", tl->sigma_ct[i],\n                    tl->sigma_nt[i], tl->sigma_kt[i], di, k, kp);\n        }\n    }\n#ifdef DEBUG\n    chi2 = 0.3*sqr(k-0.6)+0.7*sqr(kp-1.3);\n#endif\n    return chi2;\n}\n\nstatic real optimize_luzar_parameters(FILE *fp, t_luzar *tl, int maxiter,\n                                      real tol)\n{\n    real   size, d2;\n    int    iter   = 0;\n    int    status = 0;\n    int    i;\n\n    const gsl_multimin_fminimizer_type *T;\n    gsl_multimin_fminimizer            *s;\n\n    gsl_vector                         *x, *dx;\n    gsl_multimin_function               my_func;\n\n    my_func.f      = &my_f;\n    my_func.n      = tl->nparams;\n    my_func.params = (void *) tl;\n\n    /* Starting point */\n    x = gsl_vector_alloc (my_func.n);\n    for (i = 0; (i < my_func.n); i++)\n    {\n        gsl_vector_set (x, i, tl->kkk[i]);\n    }\n\n    /* Step size, different for each of the parameters */\n    dx = gsl_vector_alloc (my_func.n);\n    for (i = 0; (i < my_func.n); i++)\n    {\n        gsl_vector_set (dx, i, 0.01*tl->kkk[i]);\n    }\n\n    T = gsl_multimin_fminimizer_nmsimplex;\n    s = gsl_multimin_fminimizer_alloc (T, my_func.n);\n\n    gsl_multimin_fminimizer_set (s, &my_func, x, dx);\n    gsl_vector_free (x);\n    gsl_vector_free (dx);\n\n    if (fp)\n    {\n        fprintf(fp, \"%5s %12s %12s %12s %12s\\n\", \"Iter\", \"k\", \"kp\", \"NM Size\", \"Chi2\");\n    }\n\n    do\n    {\n        iter++;\n        status = gsl_multimin_fminimizer_iterate (s);\n\n        if (status != 0)\n        {\n            gmx_fatal(FARGS, \"Something went wrong in the iteration in minimizer %s\",\n                      gsl_multimin_fminimizer_name(s));\n        }\n\n        d2     = gsl_multimin_fminimizer_minimum(s);\n        size   = gsl_multimin_fminimizer_size(s);\n        status = gsl_multimin_test_size(size, tol);\n\n        if (status == GSL_SUCCESS)\n        {\n            if (fp)\n            {\n                fprintf(fp, \"Minimum found using %s at:\\n\",\n                        gsl_multimin_fminimizer_name(s));\n            }\n        }\n\n        if (fp)\n        {\n            fprintf(fp, \"%5d\", iter);\n            for (i = 0; (i < my_func.n); i++)\n            {\n                fprintf(fp, \" %12.4e\", gsl_vector_get (s->x, i));\n            }\n            fprintf (fp, \" %12.4e %12.4e\\n\", size, d2);\n        }\n    }\n    while ((status == GSL_CONTINUE) && (iter < maxiter));\n\n    gsl_multimin_fminimizer_free (s);\n\n    return d2;\n}\n\nstatic real quality_of_fit(real chi2, int N)\n{\n    return gsl_sf_gamma_inc_Q((N-2)/2.0, chi2/2.0);\n}\n\n#else\nstatic real optimize_luzar_parameters(FILE *fp, t_luzar *tl, int maxiter,\n                                      real tol)\n{\n    fprintf(stderr, \"This program needs the GNU scientific library to work.\\n\");\n\n    return -1;\n}\nstatic real quality_of_fit(real chi2, int N)\n{\n    fprintf(stderr, \"This program needs the GNU scientific library to work.\\n\");\n\n    return -1;\n}\n\n#endif\n\nstatic real compute_weighted_rates(int n, real t[], real ct[], real nt[],\n                                   real kt[], real sigma_ct[], real sigma_nt[],\n                                   real sigma_kt[], real *k, real *kp,\n                                   real *sigma_k, real *sigma_kp,\n                                   real fit_start)\n{\n#define NK 10\n    int      i, j;\n    t_luzar  tl;\n    real     kkk = 0, kkp = 0, kk2 = 0, kp2 = 0, chi2;\n\n    *sigma_k  = 0;\n    *sigma_kp = 0;\n\n    for (i = 0; (i < n); i++)\n    {\n        if (t[i] >= fit_start)\n        {\n            break;\n        }\n    }\n    tl.n0       = i;\n    tl.n1       = n;\n    tl.nparams  = 2;\n    tl.ndelta   = 1;\n    tl.t        = t;\n    tl.ct       = ct;\n    tl.nt       = nt;\n    tl.kt       = kt;\n    tl.sigma_ct = sigma_ct;\n    tl.sigma_nt = sigma_nt;\n    tl.sigma_kt = sigma_kt;\n    tl.kkk[0]   = *k;\n    tl.kkk[1]   = *kp;\n\n    chi2      = optimize_luzar_parameters(debug, &tl, 1000, 1e-3);\n    *k        = tl.kkk[0];\n    *kp       = tl.kkk[1] = *kp;\n    tl.ndelta = NK;\n    for (j = 0; (j < NK); j++)\n    {\n        (void) optimize_luzar_parameters(debug, &tl, 1000, 1e-3);\n        kkk += tl.kkk[0];\n        kkp += tl.kkk[1];\n        kk2 += sqr(tl.kkk[0]);\n        kp2 += sqr(tl.kkk[1]);\n        tl.n0++;\n    }\n    *sigma_k  = sqrt(kk2/NK - sqr(kkk/NK));\n    *sigma_kp = sqrt(kp2/NK - sqr(kkp/NK));\n\n    return chi2;\n}\n\nstatic void smooth_tail(int n, real t[], real c[], real sigma_c[], real start,\n                        const output_env_t oenv)\n{\n    FILE *fp;\n    real  e_1, fitparm[4];\n    int   i;\n\n    e_1 = exp(-1);\n    for (i = 0; (i < n); i++)\n    {\n        if (c[i] < e_1)\n        {\n            break;\n        }\n    }\n    if (i < n)\n    {\n        fitparm[0] = t[i];\n    }\n    else\n    {\n        fitparm[0] = 10;\n    }\n    fitparm[1] = 0.95;\n    do_lmfit(n, c, sigma_c, 0, t, start, t[n-1], oenv, bDebugMode(), effnEXP2, fitparm, 0);\n}\n\nvoid analyse_corr(int n, real t[], real ct[], real nt[], real kt[],\n                  real sigma_ct[], real sigma_nt[], real sigma_kt[],\n                  real fit_start, real temp, real smooth_tail_start,\n                  const output_env_t oenv)\n{\n    int        i0, i;\n    real       k = 1, kp = 1, kow = 1;\n    real       Q = 0, chi22, chi2, dg, dgp, tau_hb, dtau, tau_rlx, e_1, dt, sigma_k, sigma_kp, ddg;\n    double     tmp, sn2 = 0, sc2 = 0, sk2 = 0, scn = 0, sck = 0, snk = 0;\n    gmx_bool   bError = (sigma_ct != NULL) && (sigma_nt != NULL) && (sigma_kt != NULL);\n\n    if (smooth_tail_start >= 0)\n    {\n        smooth_tail(n, t, ct, sigma_ct, smooth_tail_start, oenv);\n        smooth_tail(n, t, nt, sigma_nt, smooth_tail_start, oenv);\n        smooth_tail(n, t, kt, sigma_kt, smooth_tail_start, oenv);\n    }\n    for (i0 = 0; (i0 < n-2) && ((t[i0]-t[0]) < fit_start); i0++)\n    {\n        ;\n    }\n    if (i0 < n-2)\n    {\n        for (i = i0; (i < n); i++)\n        {\n            sc2 += sqr(ct[i]);\n            sn2 += sqr(nt[i]);\n            sk2 += sqr(kt[i]);\n            sck += ct[i]*kt[i];\n            snk += nt[i]*kt[i];\n            scn += ct[i]*nt[i];\n        }\n        printf(\"Hydrogen bond thermodynamics at T = %g K\\n\", temp);\n        tmp = (sn2*sc2-sqr(scn));\n        if ((tmp > 0) && (sn2 > 0))\n        {\n            k    = (sn2*sck-scn*snk)/tmp;\n            kp   = (k*scn-snk)/sn2;\n            if (bError)\n            {\n                chi2 = 0;\n                for (i = i0; (i < n); i++)\n                {\n                    chi2 += sqr(k*ct[i]-kp*nt[i]-kt[i]);\n                }\n                chi22 = compute_weighted_rates(n, t, ct, nt, kt, sigma_ct, sigma_nt,\n                                               sigma_kt, &k, &kp,\n                                               &sigma_k, &sigma_kp, fit_start);\n                Q   = quality_of_fit(chi2, 2);\n                ddg = BOLTZ*temp*sigma_k/k;\n                printf(\"Fitting paramaters chi^2 = %10g, Quality of fit = %10g\\n\",\n                       chi2, Q);\n                printf(\"The Rate and Delta G are followed by an error estimate\\n\");\n                printf(\"----------------------------------------------------------\\n\"\n                       \"Type      Rate (1/ps)  Sigma Time (ps)  DG (kJ/mol)  Sigma\\n\");\n                printf(\"Forward    %10.3f %6.2f   %8.3f  %10.3f %6.2f\\n\",\n                       k, sigma_k, 1/k, calc_dg(1/k, temp), ddg);\n                ddg = BOLTZ*temp*sigma_kp/kp;\n                printf(\"Backward   %10.3f %6.2f   %8.3f  %10.3f %6.2f\\n\",\n                       kp, sigma_kp, 1/kp, calc_dg(1/kp, temp), ddg);\n            }\n            else\n            {\n                chi2 = 0;\n                for (i = i0; (i < n); i++)\n                {\n                    chi2 += sqr(k*ct[i]-kp*nt[i]-kt[i]);\n                }\n                printf(\"Fitting parameters chi^2 = %10g\\nQ = %10g\\n\",\n                       chi2, Q);\n                printf(\"--------------------------------------------------\\n\"\n                       \"Type      Rate (1/ps) Time (ps)  DG (kJ/mol)  Chi^2\\n\");\n                printf(\"Forward    %10.3f   %8.3f  %10.3f  %10g\\n\",\n                       k, 1/k, calc_dg(1/k, temp), chi2);\n                printf(\"Backward   %10.3f   %8.3f  %10.3f\\n\",\n                       kp, 1/kp, calc_dg(1/kp, temp));\n            }\n        }\n        if (sc2 > 0)\n        {\n            kow  = 2*sck/sc2;\n            printf(\"One-way    %10.3f   %s%8.3f  %10.3f\\n\",\n                   kow, bError ? \"       \" : \"\", 1/kow, calc_dg(1/kow, temp));\n        }\n        else\n        {\n            printf(\" - Numerical problems computing HB thermodynamics:\\n\"\n                   \"sc2 = %g  sn2 = %g  sk2 = %g sck = %g snk = %g scn = %g\\n\",\n                   sc2, sn2, sk2, sck, snk, scn);\n        }\n        /* Determine integral of the correlation function */\n        tau_hb = evaluate_integral(n, t, ct, NULL, (t[n-1]-t[0])/2, &dtau);\n        printf(\"Integral   %10.3f   %s%8.3f  %10.3f\\n\", 1/tau_hb,\n               bError ? \"       \" : \"\", tau_hb, calc_dg(tau_hb, temp));\n        e_1 = exp(-1);\n        for (i = 0; (i < n-2); i++)\n        {\n            if ((ct[i] > e_1) && (ct[i+1] <= e_1))\n            {\n                break;\n            }\n        }\n        if (i < n-2)\n        {\n            /* Determine tau_relax from linear interpolation */\n            tau_rlx = t[i]-t[0] + (e_1-ct[i])*(t[i+1]-t[i])/(ct[i+1]-ct[i]);\n            printf(\"Relaxation %10.3f   %8.3f  %s%10.3f\\n\", 1/tau_rlx,\n                   tau_rlx, bError ? \"       \" : \"\",\n                   calc_dg(tau_rlx, temp));\n        }\n    }\n    else\n    {\n        printf(\"Correlation functions too short to compute thermodynamics\\n\");\n    }\n}\n\nvoid compute_derivative(int nn, real x[], real y[], real dydx[])\n{\n    int j;\n\n    /* Compute k(t) = dc(t)/dt */\n    for (j = 1; (j < nn-1); j++)\n    {\n        dydx[j] = (y[j+1]-y[j-1])/(x[j+1]-x[j-1]);\n    }\n    /* Extrapolate endpoints */\n    dydx[0]    = 2*dydx[1]   -  dydx[2];\n    dydx[nn-1] = 2*dydx[nn-2] - dydx[nn-3];\n}\n\nstatic void parallel_print(int *data, int nThreads)\n{\n    /* This prints the donors on which each tread is currently working. */\n    int i;\n\n    fprintf(stderr, \"\\r\");\n    for (i = 0; i < nThreads; i++)\n    {\n        fprintf(stderr, \"%-7i\", data[i]);\n    }\n}\n\nstatic void normalizeACF(real *ct, real *gt, int nhb, int len)\n{\n    real ct_fac, gt_fac;\n    int  i;\n\n    /* Xu and Berne use the same normalization constant */\n\n    ct_fac = 1.0/ct[0];\n    gt_fac = (nhb == 0) ? 0 : 1.0/(real)nhb;\n\n    printf(\"Normalization for c(t) = %g for gh(t) = %g\\n\", ct_fac, gt_fac);\n    for (i = 0; i < len; i++)\n    {\n        ct[i] *= ct_fac;\n        if (gt != NULL)\n        {\n            gt[i] *= gt_fac;\n        }\n    }\n}\n\n/* Added argument bContact in do_hbac(...). Also\n * added support for -contact in the actual code.\n * - Erik Marklund, May 31, 2006 */\n/* Changed contact code and added argument R2\n * - Erik Marklund, June 29, 2006\n */\nstatic void do_hbac(const char *fn, t_hbdata *hb,\n                    int nDump, gmx_bool bMerge, gmx_bool bContact, real fit_start,\n                    real temp, gmx_bool R2, real smooth_tail_start, const output_env_t oenv,\n                    t_gemParams *params, const char *gemType, int nThreads,\n                    const int NN, const gmx_bool bBallistic, const gmx_bool bGemFit)\n{\n    FILE          *fp;\n    int            i, j, k, m, n, o, nd, ihb, idist, n2, nn, iter, nSets;\n    const char    *legNN[]   = {\n        \"Ac(t)\",\n        \"Ac'(t)\"\n    };\n    static char  **legGem;\n\n    const char    *legLuzar[] = {\n        \"Ac\\\\sfin sys\\\\v{}\\\\z{}(t)\",\n        \"Ac(t)\",\n        \"Cc\\\\scontact,hb\\\\v{}\\\\z{}(t)\",\n        \"-dAc\\\\sfs\\\\v{}\\\\z{}/dt\"\n    };\n    gmx_bool       bNorm = FALSE, bOMP = FALSE;\n    double         nhb   = 0;\n    int            nhbi  = 0;\n    real          *rhbex = NULL, *ht, *gt, *ght, *dght, *kt;\n    real          *ct, *p_ct, tail, tail2, dtail, ct_fac, ght_fac, *cct;\n    const real     tol     = 1e-3;\n    int            nframes = hb->nframes, nf;\n    unsigned int **h       = NULL, **g = NULL;\n    int            nh, nhbonds, nhydro, ngh;\n    t_hbond       *hbh;\n    PSTYPE         p, *pfound = NULL, np;\n    t_pShift      *pHist;\n    int           *ptimes   = NULL, *poff = NULL, anhb, n0, mMax = INT_MIN;\n    real         **rHbExGem = NULL;\n    gmx_bool       c;\n    int            acType;\n    t_E           *E;\n    double        *ctdouble, *timedouble, *fittedct;\n    double         fittolerance = 0.1;\n    int           *dondata      = NULL, thisThread;\n\n    enum {\n        AC_NONE, AC_NN, AC_GEM, AC_LUZAR\n    };\n\n#ifdef GMX_OPENMP\n    bOMP = TRUE;\n#else\n    bOMP = FALSE;\n#endif\n\n    printf(\"Doing autocorrelation \");\n\n    /* Decide what kind of ACF calculations to do. */\n    if (NN > NN_NONE && NN < NN_NR)\n    {\n#ifdef HAVE_NN_LOOPS\n        acType = AC_NN;\n        printf(\"using the energy estimate.\\n\");\n#else\n        acType = AC_NONE;\n        printf(\"Can't do the NN-loop. Yet.\\n\");\n#endif\n    }\n    else if (hb->bGem)\n    {\n        acType = AC_GEM;\n        printf(\"according to the reversible geminate recombination model by Omer Markowitch.\\n\");\n\n        nSets = 1 + (bBallistic ? 1 : 0) + (bGemFit ? 1 : 0);\n        snew(legGem, nSets);\n        for (i = 0; i < nSets; i++)\n        {\n            snew(legGem[i], 128);\n        }\n        sprintf(legGem[0], \"Ac\\\\s%s\\\\v{}\\\\z{}(t)\", gemType);\n        if (bBallistic)\n        {\n            sprintf(legGem[1], \"Ac'(t)\");\n        }\n        if (bGemFit)\n        {\n            sprintf(legGem[(bBallistic ? 3 : 2)], \"Ac\\\\s%s,fit\\\\v{}\\\\z{}(t)\", gemType);\n        }\n\n    }\n    else\n    {\n        acType = AC_LUZAR;\n        printf(\"according to the theory of Luzar and Chandler.\\n\");\n    }\n    fflush(stdout);\n\n    /* build hbexist matrix in reals for autocorr */\n    /* Allocate memory for computing ACF (rhbex) and aggregating the ACF (ct) */\n    n2 = 1;\n    while (n2 < nframes)\n    {\n        n2 *= 2;\n    }\n\n    nn = nframes/2;\n\n    if (acType != AC_NN || bOMP)\n    {\n        snew(h, hb->maxhydro);\n        snew(g, hb->maxhydro);\n    }\n\n    /* Dump hbonds for debugging */\n    dump_ac(hb, bMerge || bContact, nDump);\n\n    /* Total number of hbonds analyzed here */\n    nhbonds = 0;\n    ngh     = 0;\n    anhb    = 0;\n\n    if (acType != AC_LUZAR && bOMP)\n    {\n        nThreads = min((nThreads <= 0) ? INT_MAX : nThreads, gmx_omp_get_max_threads());\n\n        gmx_omp_set_num_threads(nThreads);\n        snew(dondata, nThreads);\n        for (i = 0; i < nThreads; i++)\n        {\n            dondata[i] = -1;\n        }\n        printf(\"ACF calculations parallelized with OpenMP using %i threads.\\n\"\n               \"Expect close to linear scaling over this donor-loop.\\n\", nThreads);\n        fflush(stdout);\n        fprintf(stderr, \"Donors: [thread no]\\n\");\n        {\n            char tmpstr[7];\n            for (i = 0; i < nThreads; i++)\n            {\n                snprintf(tmpstr, 7, \"[%i]\", i);\n                fprintf(stderr, \"%-7s\", tmpstr);\n            }\n        }\n        fprintf(stderr, \"\\n\");\n    }\n\n\n    /* Build the ACF according to acType */\n    switch (acType)\n    {\n\n        case AC_NN:\n#ifdef HAVE_NN_LOOPS\n            /* Here we're using the estimated energy for the hydrogen bonds. */\n            snew(ct, nn);\n\n#pragma omp parallel \\\n            private(i, j, k, nh, E, rhbex, thisThread) \\\n            default(shared)\n            {\n#pragma omp barrier\n                thisThread = gmx_omp_get_thread_num();\n                rhbex      = NULL;\n\n                snew(rhbex, n2);\n                memset(rhbex, 0, n2*sizeof(real)); /* Trust no-one, not even malloc()! */\n\n#pragma omp barrier\n#pragma omp for schedule (dynamic)\n                for (i = 0; i < hb->d.nrd; i++) /* loop over donors */\n                {\n                    if (bOMP)\n                    {\n#pragma omp critical\n                        {\n                            dondata[thisThread] = i;\n                            parallel_print(dondata, nThreads);\n                        }\n                    }\n                    else\n                    {\n                        fprintf(stderr, \"\\r %i\", i);\n                    }\n\n                    for (j = 0; j < hb->a.nra; j++)              /* loop over acceptors */\n                    {\n                        for (nh = 0; nh < hb->d.nhydro[i]; nh++) /* loop over donors' hydrogens */\n                        {\n                            E = hb->hbE.E[i][j][nh];\n                            if (E != NULL)\n                            {\n                                for (k = 0; k < nframes; k++)\n                                {\n                                    if (E[k] != NONSENSE_E)\n                                    {\n                                        rhbex[k] = (real)E[k];\n                                    }\n                                }\n\n                                low_do_autocorr(NULL, oenv, NULL, nframes, 1, -1, &(rhbex), hb->time[1]-hb->time[0],\n                                                eacNormal, 1, FALSE, bNorm, FALSE, 0, -1, 0, 1);\n#pragma omp critical\n                                {\n                                    for (k = 0; (k < nn); k++)\n                                    {\n                                        ct[k] += rhbex[k];\n                                    }\n                                }\n                            }\n                        } /* k loop */\n                    }     /* j loop */\n                }         /* i loop */\n                sfree(rhbex);\n#pragma omp barrier\n            }\n\n            if (bOMP)\n            {\n                sfree(dondata);\n            }\n            normalizeACF(ct, NULL, 0, nn);\n            snew(ctdouble, nn);\n            snew(timedouble, nn);\n            for (j = 0; j < nn; j++)\n            {\n                timedouble[j] = (double)(hb->time[j]);\n                ctdouble[j]   = (double)(ct[j]);\n            }\n\n            /* Remove ballistic term */\n            /* Ballistic component removal and fitting to the reversible geminate recombination model\n             * will be taken out for the time being. First of all, one can remove the ballistic\n             * component with g_analyze afterwards. Secondly, and more importantly, there are still\n             * problems with the robustness of the fitting to the model. More work is needed.\n             * A third reason is that we're currently using gsl for this and wish to reduce dependence\n             * on external libraries. There are Levenberg-Marquardt and nsimplex solvers that come with\n             * a BSD-licence that can do the job.\n             *\n             * - Erik Marklund, June 18 2010.\n             */\n/*         if (params->ballistic/params->tDelta >= params->nExpFit*2+1) */\n/*             takeAwayBallistic(ctdouble, timedouble, nn, params->ballistic, params->nExpFit, params->bDt); */\n/*         else */\n/*             printf(\"\\nNumber of data points is less than the number of parameters to fit\\n.\" */\n/*                    \"The system is underdetermined, hence no ballistic term can be found.\\n\\n\"); */\n\n            fp = xvgropen(fn, \"Hydrogen Bond Autocorrelation\", output_env_get_xvgr_tlabel(oenv), \"C(t)\");\n            xvgr_legend(fp, asize(legNN), legNN);\n\n            for (j = 0; (j < nn); j++)\n            {\n                fprintf(fp, \"%10g  %10g %10g\\n\",\n                        hb->time[j]-hb->time[0],\n                        ct[j],\n                        ctdouble[j]);\n            }\n            xvgrclose(fp);\n            sfree(ct);\n            sfree(ctdouble);\n            sfree(timedouble);\n#endif             /* HAVE_NN_LOOPS */\n            break; /* case AC_NN */\n\n        case AC_GEM:\n            snew(ct, 2*n2);\n            memset(ct, 0, 2*n2*sizeof(real));\n#ifndef GMX_OPENMP\n            fprintf(stderr, \"Donor:\\n\");\n#define __ACDATA ct\n#else\n#define __ACDATA p_ct\n#endif\n\n#pragma omp parallel \\\n            private(i, k, nh, hbh, pHist, h, g, n0, nf, np, j, m, \\\n            pfound, poff, rHbExGem, p, ihb, mMax, \\\n            thisThread, p_ct) \\\n            default(shared)\n            { /* ##########  THE START OF THE ENORMOUS PARALLELIZED BLOCK!  ########## */\n                h          = NULL;\n                g          = NULL;\n                thisThread = gmx_omp_get_thread_num();\n                snew(h, hb->maxhydro);\n                snew(g, hb->maxhydro);\n                mMax     = INT_MIN;\n                rHbExGem = NULL;\n                poff     = NULL;\n                pfound   = NULL;\n                p_ct     = NULL;\n                snew(p_ct, 2*n2);\n                memset(p_ct, 0, 2*n2*sizeof(real));\n\n                /* I'm using a chunk size of 1, since I expect      \\\n                 * the overhead to be really small compared         \\\n                 * to the actual calculations                       \\ */\n#pragma omp for schedule(dynamic,1) nowait\n                for (i = 0; i < hb->d.nrd; i++)\n                {\n\n                    if (bOMP)\n                    {\n#pragma omp critical\n                        {\n                            dondata[thisThread] = i;\n                            parallel_print(dondata, nThreads);\n                        }\n                    }\n                    else\n                    {\n                        fprintf(stderr, \"\\r %i\", i);\n                    }\n                    for (k = 0; k < hb->a.nra; k++)\n                    {\n                        for (nh = 0; nh < ((bMerge || bContact) ? 1 : hb->d.nhydro[i]); nh++)\n                        {\n                            hbh = hb->hbmap[i][k];\n                            if (hbh)\n                            {\n                                /* Note that if hb->per->gemtype==gemDD, then distances will be stored in\n                                 * hb->hbmap[d][a].h array anyway, because the contact flag will be set.\n                                 * hence, it's only with the gemAD mode that hb->hbmap[d][a].g will be used. */\n                                pHist = &(hb->per->pHist[i][k]);\n                                if (ISHB(hbh->history[nh]) && pHist->len != 0)\n                                {\n\n                                    {\n                                        h[nh] = hbh->h[nh];\n                                        g[nh] = hb->per->gemtype == gemAD ? hbh->g[nh] : NULL;\n                                    }\n                                    n0 = hbh->n0;\n                                    nf = hbh->nframes;\n                                    /* count the number of periodic shifts encountered and store\n                                     * them in separate arrays. */\n                                    np = 0;\n                                    for (j = 0; j < pHist->len; j++)\n                                    {\n                                        p = pHist->p[j];\n                                        for (m = 0; m <= np; m++)\n                                        {\n                                            if (m == np) /* p not recognized in list. Add it and set up new array. */\n                                            {\n                                                np++;\n                                                if (np > hb->per->nper)\n                                                {\n                                                    gmx_fatal(FARGS, \"Too many pshifts. Something's utterly wrong here.\");\n                                                }\n                                                if (m >= mMax) /* Extend the arrays.\n                                                                * Doing it like this, using mMax to keep track of the sizes,\n                                                                * eleviates the need for freeing and re-allocating the arrays\n                                                                * when taking on the next donor-acceptor pair */\n                                                {\n                                                    mMax = m;\n                                                    srenew(pfound, np);   /* The list of found periodic shifts. */\n                                                    srenew(rHbExGem, np); /* The hb existence functions (-aver_hb). */\n                                                    snew(rHbExGem[m], 2*n2);\n                                                    srenew(poff, np);\n                                                }\n\n                                                {\n                                                    if (rHbExGem != NULL && rHbExGem[m] != NULL)\n                                                    {\n                                                        /* This must be done, as this array was most likey\n                                                         * used to store stuff in some previous iteration. */\n                                                        memset(rHbExGem[m], 0, (sizeof(real)) * (2*n2));\n                                                    }\n                                                    else\n                                                    {\n                                                        fprintf(stderr, \"rHbExGem not initialized! m = %i\\n\", m);\n                                                    }\n                                                }\n                                                pfound[m] = p;\n                                                poff[m]   = -1;\n\n                                                break;\n                                            } /* m==np */\n                                            if (p == pfound[m])\n                                            {\n                                                break;\n                                            }\n                                        } /* m: Loop over found shifts */\n                                    }     /* j: Loop over shifts */\n\n                                    /* Now unpack and disentangle the existence funtions. */\n                                    for (j = 0; j < nf; j++)\n                                    {\n                                        /* i:       donor,\n                                         * k:       acceptor\n                                         * nh:      hydrogen\n                                         * j:       time\n                                         * p:       periodic shift\n                                         * pfound:  list of periodic shifts found for this pair.\n                                         * poff:    list of frame offsets; that is, the first\n                                         *          frame a hbond has a particular periodic shift. */\n                                        p = getPshift(*pHist, j+n0);\n                                        if (p != -1)\n                                        {\n                                            for (m = 0; m < np; m++)\n                                            {\n                                                if (pfound[m] == p)\n                                                {\n                                                    break;\n                                                }\n                                                if (m == (np-1))\n                                                {\n                                                    gmx_fatal(FARGS, \"Shift not found, but must be there.\");\n                                                }\n                                            }\n\n                                            ihb = is_hb(h[nh], j) || ((hb->per->gemtype != gemAD || j == 0) ? FALSE : is_hb(g[nh], j));\n                                            if (ihb)\n                                            {\n                                                if (poff[m] == -1)\n                                                {\n                                                    poff[m] = j; /* Here's where the first hbond with shift p is,\n                                                                  * relative to the start of h[0].*/\n                                                }\n                                                if (j < poff[m])\n                                                {\n                                                    gmx_fatal(FARGS, \"j<poff[m]\");\n                                                }\n                                                rHbExGem[m][j-poff[m]] += 1;\n                                            }\n                                        }\n                                    }\n\n                                    /* Now, build ac. */\n                                    for (m = 0; m < np; m++)\n                                    {\n                                        if (rHbExGem[m][0] > 0  && n0+poff[m] < nn /*  && m==0 */)\n                                        {\n                                            low_do_autocorr(NULL, oenv, NULL, nframes, 1, -1, &(rHbExGem[m]), hb->time[1]-hb->time[0],\n                                                            eacNormal, 1, FALSE, bNorm, FALSE, 0, -1, 0, 1);\n                                            for (j = 0; (j < nn); j++)\n                                            {\n                                                __ACDATA[j] += rHbExGem[m][j];\n                                            }\n                                        }\n                                    } /* Building of ac. */\n                                }     /* if (ISHB(...*/\n                            }         /* if (hbh) */\n                        }             /* hydrogen loop */\n                    }                 /* acceptor loop */\n                }                     /* donor loop */\n\n                for (m = 0; m <= mMax; m++)\n                {\n                    sfree(rHbExGem[m]);\n                }\n                sfree(pfound);\n                sfree(poff);\n                sfree(rHbExGem);\n\n                sfree(h);\n                sfree(g);\n\n                if (bOMP)\n                {\n#pragma omp critical\n                    {\n                        for (i = 0; i < nn; i++)\n                        {\n                            ct[i] += p_ct[i];\n                        }\n                    }\n                    sfree(p_ct);\n                }\n\n            } /* ########## THE END OF THE ENORMOUS PARALLELIZED BLOCK ########## */\n            if (bOMP)\n            {\n                sfree(dondata);\n            }\n\n            normalizeACF(ct, NULL, 0, nn);\n\n            fprintf(stderr, \"\\n\\nACF successfully calculated.\\n\");\n\n            /* Use this part to fit to geminate recombination - JCP 129, 84505 (2008) */\n\n            snew(ctdouble, nn);\n            snew(timedouble, nn);\n            snew(fittedct, nn);\n\n            for (j = 0; j < nn; j++)\n            {\n                timedouble[j] = (double)(hb->time[j]);\n                ctdouble[j]   = (double)(ct[j]);\n            }\n\n            /* Remove ballistic term */\n            /* Ballistic component removal and fitting to the reversible geminate recombination model\n             * will be taken out for the time being. First of all, one can remove the ballistic\n             * component with g_analyze afterwards. Secondly, and more importantly, there are still\n             * problems with the robustness of the fitting to the model. More work is needed.\n             * A third reason is that we're currently using gsl for this and wish to reduce dependence\n             * on external libraries. There are Levenberg-Marquardt and nsimplex solvers that come with\n             * a BSD-licence that can do the job.\n             *\n             * - Erik Marklund, June 18 2010.\n             */\n/*         if (bBallistic) { */\n/*             if (params->ballistic/params->tDelta >= params->nExpFit*2+1) */\n/*                 takeAwayBallistic(ctdouble, timedouble, nn, params->ballistic, params->nExpFit, params->bDt); */\n/*             else */\n/*                 printf(\"\\nNumber of data points is less than the number of parameters to fit\\n.\" */\n/*                        \"The system is underdetermined, hence no ballistic term can be found.\\n\\n\"); */\n/*         } */\n/*         if (bGemFit) */\n/*             fitGemRecomb(ctdouble, timedouble, &fittedct, nn, params); */\n\n\n            if (bContact)\n            {\n                fp = xvgropen(fn, \"Contact Autocorrelation\", output_env_get_xvgr_tlabel(oenv), \"C(t)\", oenv);\n            }\n            else\n            {\n                fp = xvgropen(fn, \"Hydrogen Bond Autocorrelation\", output_env_get_xvgr_tlabel(oenv), \"C(t)\", oenv);\n            }\n            xvgr_legend(fp, asize(legGem), (const char**)legGem, oenv);\n\n            for (j = 0; (j < nn); j++)\n            {\n                fprintf(fp, \"%10g  %10g\", hb->time[j]-hb->time[0], ct[j]);\n                if (bBallistic)\n                {\n                    fprintf(fp, \"  %10g\", ctdouble[j]);\n                }\n                if (bGemFit)\n                {\n                    fprintf(fp, \"  %10g\", fittedct[j]);\n                }\n                fprintf(fp, \"\\n\");\n            }\n            xvgrclose(fp);\n\n            sfree(ctdouble);\n            sfree(timedouble);\n            sfree(fittedct);\n            sfree(ct);\n\n            break; /* case AC_GEM */\n\n        case AC_LUZAR:\n            snew(rhbex, 2*n2);\n            snew(ct, 2*n2);\n            snew(gt, 2*n2);\n            snew(ht, 2*n2);\n            snew(ght, 2*n2);\n            snew(dght, 2*n2);\n\n            snew(kt, nn);\n            snew(cct, nn);\n\n            for (i = 0; (i < hb->d.nrd); i++)\n            {\n                for (k = 0; (k < hb->a.nra); k++)\n                {\n                    nhydro = 0;\n                    hbh    = hb->hbmap[i][k];\n\n                    if (hbh)\n                    {\n                        if (bMerge || bContact)\n                        {\n                            if (ISHB(hbh->history[0]))\n                            {\n                                h[0]   = hbh->h[0];\n                                g[0]   = hbh->g[0];\n                                nhydro = 1;\n                            }\n                        }\n                        else\n                        {\n                            for (m = 0; (m < hb->maxhydro); m++)\n                            {\n                                if (bContact ? ISDIST(hbh->history[m]) : ISHB(hbh->history[m]))\n                                {\n                                    g[nhydro] = hbh->g[m];\n                                    h[nhydro] = hbh->h[m];\n                                    nhydro++;\n                                }\n                            }\n                        }\n\n                        nf = hbh->nframes;\n                        for (nh = 0; (nh < nhydro); nh++)\n                        {\n                            int nrint = bContact ? hb->nrdist : hb->nrhb;\n                            if ((((nhbonds+1) % 10) == 0) || (nhbonds+1 == nrint))\n                            {\n                                fprintf(stderr, \"\\rACF %d/%d\", nhbonds+1, nrint);\n                            }\n                            nhbonds++;\n                            for (j = 0; (j < nframes); j++)\n                            {\n                                /* Changed '<' into '<=' below, just like I did in\n                                   the hbm-output-loop in the gmx_hbond() block.\n                                   - Erik Marklund, May 31, 2006 */\n                                if (j <= nf)\n                                {\n                                    ihb   = is_hb(h[nh], j);\n                                    idist = is_hb(g[nh], j);\n                                }\n                                else\n                                {\n                                    ihb = idist = 0;\n                                }\n                                rhbex[j] = ihb;\n                                /* For contacts: if a second cut-off is provided, use it,\n                                 * otherwise use g(t) = 1-h(t) */\n                                if (!R2 && bContact)\n                                {\n                                    gt[j]  = 1-ihb;\n                                }\n                                else\n                                {\n                                    gt[j]  = idist*(1-ihb);\n                                }\n                                ht[j]    = rhbex[j];\n                                nhb     += ihb;\n                            }\n\n\n                            /* The autocorrelation function is normalized after summation only */\n                            low_do_autocorr(NULL, oenv, NULL, nframes, 1, -1, &rhbex, hb->time[1]-hb->time[0],\n                                            eacNormal, 1, FALSE, bNorm, FALSE, 0, -1, 0, 1);\n\n                            /* Cross correlation analysis for thermodynamics */\n                            for (j = nframes; (j < n2); j++)\n                            {\n                                ht[j] = 0;\n                                gt[j] = 0;\n                            }\n\n                            cross_corr(n2, ht, gt, dght);\n\n                            for (j = 0; (j < nn); j++)\n                            {\n                                ct[j]  += rhbex[j];\n                                ght[j] += dght[j];\n                            }\n                        }\n                    }\n                }\n            }\n            fprintf(stderr, \"\\n\");\n            sfree(h);\n            sfree(g);\n            normalizeACF(ct, ght, nhb, nn);\n\n            /* Determine tail value for statistics */\n            tail  = 0;\n            tail2 = 0;\n            for (j = nn/2; (j < nn); j++)\n            {\n                tail  += ct[j];\n                tail2 += ct[j]*ct[j];\n            }\n            tail  /= (nn - nn/2);\n            tail2 /= (nn - nn/2);\n            dtail  = sqrt(tail2-tail*tail);\n\n            /* Check whether the ACF is long enough */\n            if (dtail > tol)\n            {\n                printf(\"\\nWARNING: Correlation function is probably not long enough\\n\"\n                       \"because the standard deviation in the tail of C(t) > %g\\n\"\n                       \"Tail value (average C(t) over second half of acf): %g +/- %g\\n\",\n                       tol, tail, dtail);\n            }\n            for (j = 0; (j < nn); j++)\n            {\n                cct[j] = ct[j];\n                ct[j]  = (cct[j]-tail)/(1-tail);\n            }\n            /* Compute negative derivative k(t) = -dc(t)/dt */\n            compute_derivative(nn, hb->time, ct, kt);\n            for (j = 0; (j < nn); j++)\n            {\n                kt[j] = -kt[j];\n            }\n\n\n            if (bContact)\n            {\n                fp = xvgropen(fn, \"Contact Autocorrelation\", output_env_get_xvgr_tlabel(oenv), \"C(t)\", oenv);\n            }\n            else\n            {\n                fp = xvgropen(fn, \"Hydrogen Bond Autocorrelation\", output_env_get_xvgr_tlabel(oenv), \"C(t)\", oenv);\n            }\n            xvgr_legend(fp, asize(legLuzar), legLuzar, oenv);\n\n\n            for (j = 0; (j < nn); j++)\n            {\n                fprintf(fp, \"%10g  %10g  %10g  %10g  %10g\\n\",\n                        hb->time[j]-hb->time[0], ct[j], cct[j], ght[j], kt[j]);\n            }\n            ffclose(fp);\n\n            analyse_corr(nn, hb->time, ct, ght, kt, NULL, NULL, NULL,\n                         fit_start, temp, smooth_tail_start, oenv);\n\n            do_view(oenv, fn, NULL);\n            sfree(rhbex);\n            sfree(ct);\n            sfree(gt);\n            sfree(ht);\n            sfree(ght);\n            sfree(dght);\n            sfree(cct);\n            sfree(kt);\n            /* sfree(h); */\n/*         sfree(g); */\n\n            break; /* case AC_LUZAR */\n\n        default:\n            gmx_fatal(FARGS, \"Unrecognized type of ACF-calulation. acType = %i.\", acType);\n    } /* switch (acType) */\n}\n\nstatic void init_hbframe(t_hbdata *hb, int nframes, real t)\n{\n    int i, j, m;\n\n    hb->time[nframes]   = t;\n    hb->nhb[nframes]    = 0;\n    hb->ndist[nframes]  = 0;\n    for (i = 0; (i < max_hx); i++)\n    {\n        hb->nhx[nframes][i] = 0;\n    }\n    /* Loop invalidated */\n    if (hb->bHBmap && 0)\n    {\n        for (i = 0; (i < hb->d.nrd); i++)\n        {\n            for (j = 0; (j < hb->a.nra); j++)\n            {\n                for (m = 0; (m < hb->maxhydro); m++)\n                {\n                    if (hb->hbmap[i][j] && hb->hbmap[i][j]->h[m])\n                    {\n                        set_hb(hb, i, m, j, nframes, HB_NO);\n                    }\n                }\n            }\n        }\n    }\n    /*set_hb(hb->hbmap[i][j]->h[m],nframes-hb->hbmap[i][j]->n0,HB_NO);*/\n}\n\nstatic void analyse_donor_props(const char *fn, t_hbdata *hb, int nframes, real t,\n                                const output_env_t oenv)\n{\n    static FILE *fp    = NULL;\n    const char  *leg[] = { \"Nbound\", \"Nfree\" };\n    int          i, j, k, nbound, nb, nhtot;\n\n    if (!fn)\n    {\n        return;\n    }\n    if (!fp)\n    {\n        fp = xvgropen(fn, \"Donor properties\", output_env_get_xvgr_tlabel(oenv), \"Number\", oenv);\n        xvgr_legend(fp, asize(leg), leg, oenv);\n    }\n    nbound = 0;\n    nhtot  = 0;\n    for (i = 0; (i < hb->d.nrd); i++)\n    {\n        for (k = 0; (k < hb->d.nhydro[i]); k++)\n        {\n            nb = 0;\n            nhtot++;\n            for (j = 0; (j < hb->a.nra) && (nb == 0); j++)\n            {\n                if (hb->hbmap[i][j] && hb->hbmap[i][j]->h[k] &&\n                    is_hb(hb->hbmap[i][j]->h[k], nframes))\n                {\n                    nb = 1;\n                }\n            }\n            nbound += nb;\n        }\n    }\n    fprintf(fp, \"%10.3e  %6d  %6d\\n\", t, nbound, nhtot-nbound);\n}\n\nstatic void dump_hbmap(t_hbdata *hb,\n                       int nfile, t_filenm fnm[], gmx_bool bTwo,\n                       gmx_bool bContact, int isize[], int *index[], char *grpnames[],\n                       t_atoms *atoms)\n{\n    FILE    *fp, *fplog;\n    int      ddd, hhh, aaa, i, j, k, m, grp;\n    char     ds[32], hs[32], as[32];\n    gmx_bool first;\n\n    fp = opt2FILE(\"-hbn\", nfile, fnm, \"w\");\n    if (opt2bSet(\"-g\", nfile, fnm))\n    {\n        fplog = ffopen(opt2fn(\"-g\", nfile, fnm), \"w\");\n        fprintf(fplog, \"# %10s  %12s  %12s\\n\", \"Donor\", \"Hydrogen\", \"Acceptor\");\n    }\n    else\n    {\n        fplog = NULL;\n    }\n    for (grp = gr0; grp <= (bTwo ? gr1 : gr0); grp++)\n    {\n        fprintf(fp, \"[ %s ]\", grpnames[grp]);\n        for (i = 0; i < isize[grp]; i++)\n        {\n            fprintf(fp, (i%15) ? \" \" : \"\\n\");\n            fprintf(fp, \" %4u\", index[grp][i]+1);\n        }\n        fprintf(fp, \"\\n\");\n        /*\n           Added -contact support below.\n           - Erik Marklund, May 29, 2006\n         */\n        if (!bContact)\n        {\n            fprintf(fp, \"[ donors_hydrogens_%s ]\\n\", grpnames[grp]);\n            for (i = 0; (i < hb->d.nrd); i++)\n            {\n                if (hb->d.grp[i] == grp)\n                {\n                    for (j = 0; (j < hb->d.nhydro[i]); j++)\n                    {\n                        fprintf(fp, \" %4u %4u\", hb->d.don[i]+1,\n                                hb->d.hydro[i][j]+1);\n                    }\n                    fprintf(fp, \"\\n\");\n                }\n            }\n            first = TRUE;\n            fprintf(fp, \"[ acceptors_%s ]\", grpnames[grp]);\n            for (i = 0; (i < hb->a.nra); i++)\n            {\n                if (hb->a.grp[i] == grp)\n                {\n                    fprintf(fp, (i%15 && !first) ? \" \" : \"\\n\");\n                    fprintf(fp, \" %4u\", hb->a.acc[i]+1);\n                    first = FALSE;\n                }\n            }\n            fprintf(fp, \"\\n\");\n        }\n    }\n    if (bTwo)\n    {\n        fprintf(fp, bContact ? \"[ contacts_%s-%s ]\\n\" :\n                \"[ hbonds_%s-%s ]\\n\", grpnames[0], grpnames[1]);\n    }\n    else\n    {\n        fprintf(fp, bContact ? \"[ contacts_%s ]\" : \"[ hbonds_%s ]\\n\", grpnames[0]);\n    }\n\n    for (i = 0; (i < hb->d.nrd); i++)\n    {\n        ddd = hb->d.don[i];\n        for (k = 0; (k < hb->a.nra); k++)\n        {\n            aaa = hb->a.acc[k];\n            for (m = 0; (m < hb->d.nhydro[i]); m++)\n            {\n                if (hb->hbmap[i][k] && ISHB(hb->hbmap[i][k]->history[m]))\n                {\n                    sprintf(ds, \"%s\", mkatomname(atoms, ddd));\n                    sprintf(as, \"%s\", mkatomname(atoms, aaa));\n                    if (bContact)\n                    {\n                        fprintf(fp, \" %6u %6u\\n\", ddd+1, aaa+1);\n                        if (fplog)\n                        {\n                            fprintf(fplog, \"%12s  %12s\\n\", ds, as);\n                        }\n                    }\n                    else\n                    {\n                        hhh = hb->d.hydro[i][m];\n                        sprintf(hs, \"%s\", mkatomname(atoms, hhh));\n                        fprintf(fp, \" %6u %6u %6u\\n\", ddd+1, hhh+1, aaa+1);\n                        if (fplog)\n                        {\n                            fprintf(fplog, \"%12s  %12s  %12s\\n\", ds, hs, as);\n                        }\n                    }\n                }\n            }\n        }\n    }\n    ffclose(fp);\n    if (fplog)\n    {\n        ffclose(fplog);\n    }\n}\n\n/* sync_hbdata() updates the parallel t_hbdata p_hb using hb as template.\n * It mimics add_frames() and init_frame() to some extent. */\nstatic void sync_hbdata(t_hbdata *hb, t_hbdata *p_hb,\n                        int nframes, real t)\n{\n    int i;\n    if (nframes >= p_hb->max_frames)\n    {\n        p_hb->max_frames += 4096;\n        srenew(p_hb->nhb,   p_hb->max_frames);\n        srenew(p_hb->ndist, p_hb->max_frames);\n        srenew(p_hb->n_bound, p_hb->max_frames);\n        srenew(p_hb->nhx, p_hb->max_frames);\n        if (p_hb->bDAnr)\n        {\n            srenew(p_hb->danr, p_hb->max_frames);\n        }\n        memset(&(p_hb->nhb[nframes]),   0, sizeof(int) * (p_hb->max_frames-nframes));\n        memset(&(p_hb->ndist[nframes]), 0, sizeof(int) * (p_hb->max_frames-nframes));\n        p_hb->nhb[nframes]   = 0;\n        p_hb->ndist[nframes] = 0;\n\n    }\n    p_hb->nframes = nframes;\n/*     for (i=0;) */\n/*     { */\n/*         p_hb->nhx[nframes][i] */\n/*     } */\n    memset(&(p_hb->nhx[nframes]), 0, sizeof(int)*max_hx); /* zero the helix count for this frame */\n\n    /* hb->per will remain constant througout the frame loop,\n     * even though the data its members point to will change,\n     * hence no need for re-syncing. */\n}\n\nint gmx_hbond(int argc, char *argv[])\n{\n    const char        *desc[] = {\n        \"[TT]g_hbond[tt] computes and analyzes hydrogen bonds. Hydrogen bonds are\",\n        \"determined based on cutoffs for the angle Hydrogen - Donor - Acceptor\",\n        \"(zero is extended) and the distance Donor - Acceptor\",\n        \"(or Hydrogen - Acceptor using [TT]-noda[tt]).\",\n        \"OH and NH groups are regarded as donors, O is an acceptor always,\",\n        \"N is an acceptor by default, but this can be switched using\",\n        \"[TT]-nitacc[tt]. Dummy hydrogen atoms are assumed to be connected\",\n        \"to the first preceding non-hydrogen atom.[PAR]\",\n\n        \"You need to specify two groups for analysis, which must be either\",\n        \"identical or non-overlapping. All hydrogen bonds between the two\",\n        \"groups are analyzed.[PAR]\",\n\n        \"If you set [TT]-shell[tt], you will be asked for an additional index group\",\n        \"which should contain exactly one atom. In this case, only hydrogen\",\n        \"bonds between atoms within the shell distance from the one atom are\",\n        \"considered.[PAR]\",\n\n        \"With option -ac, rate constants for hydrogen bonding can be derived with the model of Luzar and Chandler\",\n        \"(Nature 394, 1996; J. Chem. Phys. 113:23, 2000) or that of Markovitz and Agmon (J. Chem. Phys 129, 2008).\",\n        \"If contact kinetics are analyzed by using the -contact option, then\",\n        \"n(t) can be defined as either all pairs that are not within contact distance r at time t\",\n        \"(corresponding to leaving the -r2 option at the default value 0) or all pairs that\",\n        \"are within distance r2 (corresponding to setting a second cut-off value with option -r2).\",\n        \"See mentioned literature for more details and definitions.\"\n        \"[PAR]\",\n\n        /*    \"It is also possible to analyse specific hydrogen bonds with\",\n              \"[TT]-sel[tt]. This index file must contain a group of atom triplets\",\n              \"Donor Hydrogen Acceptor, in the following way:[PAR]\",\n         */\n        \"[TT]\",\n        \"[ selected ][BR]\",\n        \"     20    21    24[BR]\",\n        \"     25    26    29[BR]\",\n        \"      1     3     6[BR]\",\n        \"[tt][BR]\",\n        \"Note that the triplets need not be on separate lines.\",\n        \"Each atom triplet specifies a hydrogen bond to be analyzed,\",\n        \"note also that no check is made for the types of atoms.[PAR]\",\n\n        \"[BB]Output:[bb][BR]\",\n        \"[TT]-num[tt]:  number of hydrogen bonds as a function of time.[BR]\",\n        \"[TT]-ac[tt]:   average over all autocorrelations of the existence\",\n        \"functions (either 0 or 1) of all hydrogen bonds.[BR]\",\n        \"[TT]-dist[tt]: distance distribution of all hydrogen bonds.[BR]\",\n        \"[TT]-ang[tt]:  angle distribution of all hydrogen bonds.[BR]\",\n        \"[TT]-hx[tt]:   the number of n-n+i hydrogen bonds as a function of time\",\n        \"where n and n+i stand for residue numbers and i ranges from 0 to 6.\",\n        \"This includes the n-n+3, n-n+4 and n-n+5 hydrogen bonds associated\",\n        \"with helices in proteins.[BR]\",\n        \"[TT]-hbn[tt]:  all selected groups, donors, hydrogens and acceptors\",\n        \"for selected groups, all hydrogen bonded atoms from all groups and\",\n        \"all solvent atoms involved in insertion.[BR]\",\n        \"[TT]-hbm[tt]:  existence matrix for all hydrogen bonds over all\",\n        \"frames, this also contains information on solvent insertion\",\n        \"into hydrogen bonds. Ordering is identical to that in [TT]-hbn[tt]\",\n        \"index file.[BR]\",\n        \"[TT]-dan[tt]: write out the number of donors and acceptors analyzed for\",\n        \"each timeframe. This is especially useful when using [TT]-shell[tt].[BR]\",\n        \"[TT]-nhbdist[tt]: compute the number of HBonds per hydrogen in order to\",\n        \"compare results to Raman Spectroscopy.\",\n        \"[PAR]\",\n        \"Note: options [TT]-ac[tt], [TT]-life[tt], [TT]-hbn[tt] and [TT]-hbm[tt]\",\n        \"require an amount of memory proportional to the total numbers of donors\",\n        \"times the total number of acceptors in the selected group(s).\"\n    };\n\n    static real        acut     = 30, abin = 1, rcut = 0.35, r2cut = 0, rbin = 0.005, rshell = -1;\n    static real        maxnhb   = 0, fit_start = 1, fit_end = 60, temp = 298.15, smooth_tail_start = -1, D = -1;\n    static gmx_bool    bNitAcc  = TRUE, bDA = TRUE, bMerge = TRUE;\n    static int         nDump    = 0, nFitPoints = 100;\n    static int         nThreads = 0, nBalExp = 4;\n\n    static gmx_bool    bContact     = FALSE, bBallistic = FALSE, bBallisticDt = FALSE, bGemFit = FALSE;\n    static real        logAfterTime = 10, gemBallistic = 0.2; /* ps */\n    static const char *NNtype[]     = {NULL, \"none\", \"binary\", \"oneOverR3\", \"dipole\", NULL};\n\n    /* options */\n    t_pargs     pa [] = {\n        { \"-a\",    FALSE,  etREAL, {&acut},\n          \"Cutoff angle (degrees, Hydrogen - Donor - Acceptor)\" },\n        { \"-r\",    FALSE,  etREAL, {&rcut},\n          \"Cutoff radius (nm, X - Acceptor, see next option)\" },\n        { \"-da\",   FALSE,  etBOOL, {&bDA},\n          \"Use distance Donor-Acceptor (if TRUE) or Hydrogen-Acceptor (FALSE)\" },\n        { \"-r2\",   FALSE,  etREAL, {&r2cut},\n          \"Second cutoff radius. Mainly useful with [TT]-contact[tt] and [TT]-ac[tt]\"},\n        { \"-abin\", FALSE,  etREAL, {&abin},\n          \"Binwidth angle distribution (degrees)\" },\n        { \"-rbin\", FALSE,  etREAL, {&rbin},\n          \"Binwidth distance distribution (nm)\" },\n        { \"-nitacc\", FALSE, etBOOL, {&bNitAcc},\n          \"Regard nitrogen atoms as acceptors\" },\n        { \"-contact\", FALSE, etBOOL, {&bContact},\n          \"Do not look for hydrogen bonds, but merely for contacts within the cut-off distance\" },\n        { \"-shell\", FALSE, etREAL, {&rshell},\n          \"when > 0, only calculate hydrogen bonds within # nm shell around \"\n          \"one particle\" },\n        { \"-fitstart\", FALSE, etREAL, {&fit_start},\n          \"Time (ps) from which to start fitting the correlation functions in order to obtain the forward and backward rate constants for HB breaking and formation. With [TT]-gemfit[tt] we suggest [TT]-fitstart 0[tt]\" },\n        { \"-fitstart\", FALSE, etREAL, {&fit_start},\n          \"Time (ps) to which to stop fitting the correlation functions in order to obtain the forward and backward rate constants for HB breaking and formation (only with [TT]-gemfit[tt])\" },\n        { \"-temp\",  FALSE, etREAL, {&temp},\n          \"Temperature (K) for computing the Gibbs energy corresponding to HB breaking and reforming\" },\n        { \"-smooth\", FALSE, etREAL, {&smooth_tail_start},\n          \"If >= 0, the tail of the ACF will be smoothed by fitting it to an exponential function: y = A exp(-x/[GRK]tau[grk])\" },\n        { \"-dump\",  FALSE, etINT, {&nDump},\n          \"Dump the first N hydrogen bond ACFs in a single [TT].xvg[tt] file for debugging\" },\n        { \"-max_hb\", FALSE, etREAL, {&maxnhb},\n          \"Theoretical maximum number of hydrogen bonds used for normalizing HB autocorrelation function. Can be useful in case the program estimates it wrongly\" },\n        { \"-merge\", FALSE, etBOOL, {&bMerge},\n          \"H-bonds between the same donor and acceptor, but with different hydrogen are treated as a single H-bond. Mainly important for the ACF.\" },\n        { \"-geminate\", FALSE, etENUM, {gemType},\n          \"Use reversible geminate recombination for the kinetics/thermodynamics calclations. See Markovitch et al., J. Chem. Phys 129, 084505 (2008) for details.\"},\n        { \"-diff\", FALSE, etREAL, {&D},\n          \"Dffusion coefficient to use in the reversible geminate recombination kinetic model. If negative, then it will be fitted to the ACF along with ka and kd.\"},\n#ifdef GMX_OPENMP\n        { \"-nthreads\", FALSE, etINT, {&nThreads},\n          \"Number of threads used for the parallel loop over autocorrelations. nThreads <= 0 means maximum number of threads. Requires linking with OpenMP. The number of threads is limited by the number of processors (before OpenMP v.3 ) or environment variable OMP_THREAD_LIMIT (OpenMP v.3)\"},\n#endif\n    };\n    const char *bugs[] = {\n        \"The option [TT]-sel[tt] that used to work on selected hbonds is out of order, and therefore not available for the time being.\"\n    };\n    t_filenm    fnm[] = {\n        { efTRX, \"-f\",   NULL,     ffREAD  },\n        { efTPX, NULL,   NULL,     ffREAD  },\n        { efNDX, NULL,   NULL,     ffOPTRD },\n        /*    { efNDX, \"-sel\", \"select\", ffOPTRD },*/\n        { efXVG, \"-num\", \"hbnum\",  ffWRITE },\n        { efLOG, \"-g\",   \"hbond\",  ffOPTWR },\n        { efXVG, \"-ac\",  \"hbac\",   ffOPTWR },\n        { efXVG, \"-dist\", \"hbdist\", ffOPTWR },\n        { efXVG, \"-ang\", \"hbang\",  ffOPTWR },\n        { efXVG, \"-hx\",  \"hbhelix\", ffOPTWR },\n        { efNDX, \"-hbn\", \"hbond\",  ffOPTWR },\n        { efXPM, \"-hbm\", \"hbmap\",  ffOPTWR },\n        { efXVG, \"-don\", \"donor\",  ffOPTWR },\n        { efXVG, \"-dan\", \"danum\",  ffOPTWR },\n        { efXVG, \"-life\", \"hblife\", ffOPTWR },\n        { efXVG, \"-nhbdist\", \"nhbdist\", ffOPTWR }\n\n    };\n#define NFILE asize(fnm)\n\n    char                  hbmap [HB_NR] = { ' ',    'o',      '-',       '*' };\n    const char           *hbdesc[HB_NR] = { \"None\", \"Present\", \"Inserted\", \"Present & Inserted\" };\n    t_rgb                 hbrgb [HB_NR] = { {1, 1, 1}, {1, 0, 0},   {0, 0, 1},    {1, 0, 1} };\n\n    t_trxstatus          *status;\n    int                   trrStatus = 1;\n    t_topology            top;\n    t_inputrec            ir;\n    t_pargs              *ppa;\n    int                   npargs, natoms, nframes = 0, shatom;\n    int                  *isize;\n    char                **grpnames;\n    atom_id             **index;\n    rvec                 *x, hbox;\n    matrix                box;\n    real                  t, ccut, dist = 0.0, ang = 0.0;\n    double                max_nhb, aver_nhb, aver_dist;\n    int                   h = 0, i = 0, j, k = 0, l, start, end, id, ja, ogrp, nsel;\n    int                   xi, yi, zi, ai;\n    int                   xj, yj, zj, aj, xjj, yjj, zjj;\n    int                   xk, yk, zk, ak, xkk, ykk, zkk;\n    gmx_bool              bSelected, bHBmap, bStop, bTwo, was, bBox, bTric;\n    int                  *adist, *rdist, *aptr, *rprt;\n    int                   grp, nabin, nrbin, bin, resdist, ihb;\n    char                **leg;\n    t_hbdata             *hb, *hbptr;\n    FILE                 *fp, *fpins = NULL, *fpnhb = NULL;\n    t_gridcell         ***grid;\n    t_ncell              *icell, *jcell, *kcell;\n    ivec                  ngrid;\n    unsigned char        *datable;\n    output_env_t          oenv;\n    int                   gemmode, NN;\n    PSTYPE                peri = 0;\n    t_E                   E;\n    int                   ii, jj, hh, actual_nThreads;\n    int                   threadNr = 0;\n    gmx_bool              bGem, bNN, bParallel;\n    t_gemParams          *params = NULL;\n    gmx_bool              bEdge_yjj, bEdge_xjj, bOMP;\n\n    t_hbdata            **p_hb    = NULL;                   /* one per thread, then merge after the frame loop */\n    int                 **p_adist = NULL, **p_rdist = NULL; /* a histogram for each thread. */\n\n#ifdef GMX_OPENMP\n    bOMP = TRUE;\n#else\n    bOMP = FALSE;\n#endif\n\n    CopyRight(stderr, argv[0]);\n\n    npargs = asize(pa);\n    ppa    = add_acf_pargs(&npargs, pa);\n\n    parse_common_args(&argc, argv, PCA_CAN_TIME | PCA_TIME_UNIT | PCA_BE_NICE, NFILE, fnm, npargs,\n                      ppa, asize(desc), desc, asize(bugs), bugs, &oenv);\n\n    /* NN-loop? If so, what estimator to use ?*/\n    NN = 1;\n    /* Outcommented for now DvdS 2010-07-13\n       while (NN < NN_NR && gmx_strcasecmp(NNtype[0], NNtype[NN])!=0)\n        NN++;\n       if (NN == NN_NR)\n        gmx_fatal(FARGS, \"Invalid NN-loop type.\");\n     */\n    bNN = FALSE;\n    for (i = 2; bNN == FALSE && i < NN_NR; i++)\n    {\n        bNN = bNN || NN == i;\n    }\n\n    if (NN > NN_NONE && bMerge)\n    {\n        bMerge = FALSE;\n    }\n\n    /* geminate recombination? If so, which flavor? */\n    gemmode = 1;\n    while (gemmode < gemNR && gmx_strcasecmp(gemType[0], gemType[gemmode]) != 0)\n    {\n        gemmode++;\n    }\n    if (gemmode == gemNR)\n    {\n        gmx_fatal(FARGS, \"Invalid recombination type.\");\n    }\n\n    bGem = FALSE;\n    for (i = 2; bGem == FALSE && i < gemNR; i++)\n    {\n        bGem = bGem || gemmode == i;\n    }\n\n    if (bGem)\n    {\n        printf(\"Geminate recombination: %s\\n\", gemType[gemmode]);\n#ifndef HAVE_LIBGSL\n        printf(\"Note that some aspects of reversible geminate recombination won't work without gsl.\\n\");\n#endif\n        if (bContact)\n        {\n            if (gemmode != gemDD)\n            {\n                printf(\"Turning off -contact option...\\n\");\n                bContact = FALSE;\n            }\n        }\n        else\n        {\n            if (gemmode == gemDD)\n            {\n                printf(\"Turning on -contact option...\\n\");\n                bContact = TRUE;\n            }\n        }\n        if (bMerge)\n        {\n            if (gemmode == gemAA)\n            {\n                printf(\"Turning off -merge option...\\n\");\n                bMerge = FALSE;\n            }\n        }\n        else\n        {\n            if (gemmode != gemAA)\n            {\n                printf(\"Turning on -merge option...\\n\");\n                bMerge = TRUE;\n            }\n        }\n    }\n\n    /* process input */\n    bSelected = FALSE;\n    ccut      = cos(acut*DEG2RAD);\n\n    if (bContact)\n    {\n        if (bSelected)\n        {\n            gmx_fatal(FARGS, \"Can not analyze selected contacts.\");\n        }\n        if (!bDA)\n        {\n            gmx_fatal(FARGS, \"Can not analyze contact between H and A: turn off -noda\");\n        }\n    }\n\n    /* Initiate main data structure! */\n    bHBmap = (opt2bSet(\"-ac\", NFILE, fnm) ||\n              opt2bSet(\"-life\", NFILE, fnm) ||\n              opt2bSet(\"-hbn\", NFILE, fnm) ||\n              opt2bSet(\"-hbm\", NFILE, fnm) ||\n              bGem);\n\n    if (opt2bSet(\"-nhbdist\", NFILE, fnm))\n    {\n        const char *leg[MAXHH+1] = { \"0 HBs\", \"1 HB\", \"2 HBs\", \"3 HBs\", \"Total\" };\n        fpnhb = xvgropen(opt2fn(\"-nhbdist\", NFILE, fnm),\n                         \"Number of donor-H with N HBs\", output_env_get_xvgr_tlabel(oenv), \"N\", oenv);\n        xvgr_legend(fpnhb, asize(leg), leg, oenv);\n    }\n\n    hb = mk_hbdata(bHBmap, opt2bSet(\"-dan\", NFILE, fnm), bMerge || bContact, bGem, gemmode);\n\n    /* get topology */\n    read_tpx_top(ftp2fn(efTPX, NFILE, fnm), &ir, box, &natoms, NULL, NULL, NULL, &top);\n\n    snew(grpnames, grNR);\n    snew(index, grNR);\n    snew(isize, grNR);\n    /* Make Donor-Acceptor table */\n    snew(datable, top.atoms.nr);\n    gen_datable(index[0], isize[0], datable, top.atoms.nr);\n\n    if (bSelected)\n    {\n        /* analyze selected hydrogen bonds */\n        printf(\"Select group with selected atoms:\\n\");\n        get_index(&(top.atoms), opt2fn(\"-sel\", NFILE, fnm),\n                  1, &nsel, index, grpnames);\n        if (nsel % 3)\n        {\n            gmx_fatal(FARGS, \"Number of atoms in group '%s' not a multiple of 3\\n\"\n                      \"and therefore cannot contain triplets of \"\n                      \"Donor-Hydrogen-Acceptor\", grpnames[0]);\n        }\n        bTwo = FALSE;\n\n        for (i = 0; (i < nsel); i += 3)\n        {\n            int dd = index[0][i];\n            int aa = index[0][i+2];\n            /* int */ hh = index[0][i+1];\n            add_dh (&hb->d, dd, hh, i, datable);\n            add_acc(&hb->a, aa, i);\n            /* Should this be here ? */\n            snew(hb->d.dptr, top.atoms.nr);\n            snew(hb->a.aptr, top.atoms.nr);\n            add_hbond(hb, dd, aa, hh, gr0, gr0, 0, bMerge, 0, bContact, peri);\n        }\n        printf(\"Analyzing %d selected hydrogen bonds from '%s'\\n\",\n               isize[0], grpnames[0]);\n    }\n    else\n    {\n        /* analyze all hydrogen bonds: get group(s) */\n        printf(\"Specify 2 groups to analyze:\\n\");\n        get_index(&(top.atoms), ftp2fn_null(efNDX, NFILE, fnm),\n                  2, isize, index, grpnames);\n\n        /* check if we have two identical or two non-overlapping groups */\n        bTwo = isize[0] != isize[1];\n        for (i = 0; (i < isize[0]) && !bTwo; i++)\n        {\n            bTwo = index[0][i] != index[1][i];\n        }\n        if (bTwo)\n        {\n            printf(\"Checking for overlap in atoms between %s and %s\\n\",\n                   grpnames[0], grpnames[1]);\n            for (i = 0; i < isize[1]; i++)\n            {\n                if (ISINGRP(datable[index[1][i]]))\n                {\n                    gmx_fatal(FARGS, \"Partial overlap between groups '%s' and '%s'\",\n                              grpnames[0], grpnames[1]);\n                }\n            }\n            /*\n               printf(\"Checking for overlap in atoms between %s and %s\\n\",\n               grpnames[0],grpnames[1]);\n               for (i=0; i<isize[0]; i++)\n               for (j=0; j<isize[1]; j++)\n               if (index[0][i] == index[1][j])\n               gmx_fatal(FARGS,\"Partial overlap between groups '%s' and '%s'\",\n               grpnames[0],grpnames[1]);\n             */\n        }\n        if (bTwo)\n        {\n            printf(\"Calculating %s \"\n                   \"between %s (%d atoms) and %s (%d atoms)\\n\",\n                   bContact ? \"contacts\" : \"hydrogen bonds\",\n                   grpnames[0], isize[0], grpnames[1], isize[1]);\n        }\n        else\n        {\n            fprintf(stderr, \"Calculating %s in %s (%d atoms)\\n\",\n                    bContact ? \"contacts\" : \"hydrogen bonds\", grpnames[0], isize[0]);\n        }\n    }\n    sfree(datable);\n\n    /* search donors and acceptors in groups */\n    snew(datable, top.atoms.nr);\n    for (i = 0; (i < grNR); i++)\n    {\n        if ( ((i == gr0) && !bSelected ) ||\n             ((i == gr1) && bTwo ))\n        {\n            gen_datable(index[i], isize[i], datable, top.atoms.nr);\n            if (bContact)\n            {\n                search_acceptors(&top, isize[i], index[i], &hb->a, i,\n                                 bNitAcc, TRUE, (bTwo && (i == gr0)) || !bTwo, datable);\n                search_donors   (&top, isize[i], index[i], &hb->d, i,\n                                 TRUE, (bTwo && (i == gr1)) || !bTwo, datable);\n            }\n            else\n            {\n                search_acceptors(&top, isize[i], index[i], &hb->a, i, bNitAcc, FALSE, TRUE, datable);\n                search_donors   (&top, isize[i], index[i], &hb->d, i, FALSE, TRUE, datable);\n            }\n            if (bTwo)\n            {\n                clear_datable_grp(datable, top.atoms.nr);\n            }\n        }\n    }\n    sfree(datable);\n    printf(\"Found %d donors and %d acceptors\\n\", hb->d.nrd, hb->a.nra);\n    /*if (bSelected)\n       snew(donors[gr0D], dons[gr0D].nrd);*/\n\n    if (bHBmap)\n    {\n        printf(\"Making hbmap structure...\");\n        /* Generate hbond data structure */\n        mk_hbmap(hb, bTwo);\n        printf(\"done.\\n\");\n    }\n\n#ifdef HAVE_NN_LOOPS\n    if (bNN)\n    {\n        mk_hbEmap(hb, 0);\n    }\n#endif\n\n    if (bGem)\n    {\n        printf(\"Making per structure...\");\n        /* Generate hbond data structure */\n        mk_per(hb);\n        printf(\"done.\\n\");\n    }\n\n    /* check input */\n    bStop = FALSE;\n    if (hb->d.nrd + hb->a.nra == 0)\n    {\n        printf(\"No Donors or Acceptors found\\n\");\n        bStop = TRUE;\n    }\n    if (!bStop)\n    {\n        if (hb->d.nrd == 0)\n        {\n            printf(\"No Donors found\\n\");\n            bStop = TRUE;\n        }\n        if (hb->a.nra == 0)\n        {\n            printf(\"No Acceptors found\\n\");\n            bStop = TRUE;\n        }\n    }\n    if (bStop)\n    {\n        gmx_fatal(FARGS, \"Nothing to be done\");\n    }\n\n    shatom = 0;\n    if (rshell > 0)\n    {\n        int      shisz;\n        atom_id *shidx;\n        char    *shgrpnm;\n        /* get index group with atom for shell */\n        do\n        {\n            printf(\"Select atom for shell (1 atom):\\n\");\n            get_index(&(top.atoms), ftp2fn_null(efNDX, NFILE, fnm),\n                      1, &shisz, &shidx, &shgrpnm);\n            if (shisz != 1)\n            {\n                printf(\"group contains %d atoms, should be 1 (one)\\n\", shisz);\n            }\n        }\n        while (shisz != 1);\n        shatom = shidx[0];\n        printf(\"Will calculate hydrogen bonds within a shell \"\n               \"of %g nm around atom %i\\n\", rshell, shatom+1);\n    }\n\n    /* Analyze trajectory */\n    natoms = read_first_x(oenv, &status, ftp2fn(efTRX, NFILE, fnm), &t, &x, box);\n    if (natoms > top.atoms.nr)\n    {\n        gmx_fatal(FARGS, \"Topology (%d atoms) does not match trajectory (%d atoms)\",\n                  top.atoms.nr, natoms);\n    }\n\n    bBox  = ir.ePBC != epbcNONE;\n    grid  = init_grid(bBox, box, (rcut > r2cut) ? rcut : r2cut, ngrid);\n    nabin = acut/abin;\n    nrbin = rcut/rbin;\n    snew(adist, nabin+1);\n    snew(rdist, nrbin+1);\n\n    if (bGem && !bBox)\n    {\n        gmx_fatal(FARGS, \"Can't do geminate recombination without periodic box.\");\n    }\n\n    bParallel = FALSE;\n\n#ifndef GMX_OPENMP\n#define __ADIST adist\n#define __RDIST rdist\n#define __HBDATA hb\n#else /* GMX_OPENMP ================================================== \\\n       * Set up the OpenMP stuff,                                       |\n       * like the number of threads and such                            |\n       * Also start the parallel loop.                                  |\n       */\n#define __ADIST p_adist[threadNr]\n#define __RDIST p_rdist[threadNr]\n#define __HBDATA p_hb[threadNr]\n#endif\n    if (bOMP)\n    {\n        bParallel = !bSelected;\n\n        if (bParallel)\n        {\n            actual_nThreads = min((nThreads <= 0) ? INT_MAX : nThreads, gmx_omp_get_max_threads());\n\n            gmx_omp_set_num_threads(actual_nThreads);\n            printf(\"Frame loop parallelized with OpenMP using %i threads.\\n\", actual_nThreads);\n            fflush(stdout);\n        }\n        else\n        {\n            actual_nThreads = 1;\n        }\n\n        snew(p_hb,    actual_nThreads);\n        snew(p_adist, actual_nThreads);\n        snew(p_rdist, actual_nThreads);\n        for (i = 0; i < actual_nThreads; i++)\n        {\n            snew(p_hb[i], 1);\n            snew(p_adist[i], nabin+1);\n            snew(p_rdist[i], nrbin+1);\n\n            p_hb[i]->max_frames = 0;\n            p_hb[i]->nhb        = NULL;\n            p_hb[i]->ndist      = NULL;\n            p_hb[i]->n_bound    = NULL;\n            p_hb[i]->time       = NULL;\n            p_hb[i]->nhx        = NULL;\n\n            p_hb[i]->bHBmap     = hb->bHBmap;\n            p_hb[i]->bDAnr      = hb->bDAnr;\n            p_hb[i]->bGem       = hb->bGem;\n            p_hb[i]->wordlen    = hb->wordlen;\n            p_hb[i]->nframes    = hb->nframes;\n            p_hb[i]->maxhydro   = hb->maxhydro;\n            p_hb[i]->danr       = hb->danr;\n            p_hb[i]->d          = hb->d;\n            p_hb[i]->a          = hb->a;\n            p_hb[i]->hbmap      = hb->hbmap;\n            p_hb[i]->time       = hb->time; /* This may need re-syncing at every frame. */\n            p_hb[i]->per        = hb->per;\n\n#ifdef HAVE_NN_LOOPS\n            p_hb[i]->hbE = hb->hbE;\n#endif\n\n            p_hb[i]->nrhb   = 0;\n            p_hb[i]->nrdist = 0;\n        }\n    }\n\n    /* Make a thread pool here,\n     * instead of forking anew at every frame. */\n\n#pragma omp parallel \\\n    firstprivate(i) \\\n    private(j, h, ii, jj, hh, E, \\\n    xi, yi, zi, xj, yj, zj, threadNr, \\\n    dist, ang, peri, icell, jcell, \\\n    grp, ogrp, ai, aj, xjj, yjj, zjj, \\\n    xk, yk, zk, ihb, id,  resdist, \\\n    xkk, ykk, zkk, kcell, ak, k, bTric, \\\n    bEdge_xjj, bEdge_yjj) \\\n    default(shared)\n    {    /* Start of parallel region */\n        threadNr = gmx_omp_get_thread_num();\n\n        do\n        {\n\n            bTric = bBox && TRICLINIC(box);\n\n            if (bOMP)\n            {\n                sync_hbdata(hb, p_hb[threadNr], nframes, t);\n            }\n#pragma omp single\n            {\n                build_grid(hb, x, x[shatom], bBox, box, hbox, (rcut > r2cut) ? rcut : r2cut,\n                           rshell, ngrid, grid);\n                reset_nhbonds(&(hb->d));\n\n                if (debug && bDebug)\n                {\n                    dump_grid(debug, ngrid, grid);\n                }\n\n                add_frames(hb, nframes);\n                init_hbframe(hb, nframes, output_env_conv_time(oenv, t));\n\n                if (hb->bDAnr)\n                {\n                    count_da_grid(ngrid, grid, hb->danr[nframes]);\n                }\n            } /* omp single */\n\n            if (bOMP)\n            {\n                p_hb[threadNr]->time = hb->time; /* This pointer may have changed. */\n            }\n\n            if (bNN)\n            {\n#ifdef HAVE_NN_LOOPS /* Unlock this feature when testing */\n                /* Loop over all atom pairs and estimate interaction energy */\n\n#pragma omp single\n                {\n                    addFramesNN(hb, nframes);\n                }\n\n#pragma omp barrier\n#pragma omp for schedule(dynamic)\n                for (i = 0; i < hb->d.nrd; i++)\n                {\n                    for (j = 0; j < hb->a.nra; j++)\n                    {\n                        for (h = 0;\n                             h < (bContact ? 1 : hb->d.nhydro[i]);\n                             h++)\n                        {\n                            if (i == hb->d.nrd || j == hb->a.nra)\n                            {\n                                gmx_fatal(FARGS, \"out of bounds\");\n                            }\n\n                            /* Get the real atom ids */\n                            ii = hb->d.don[i];\n                            jj = hb->a.acc[j];\n                            hh = hb->d.hydro[i][h];\n\n                            /* Estimate the energy from the geometry */\n                            E = calcHbEnergy(ii, jj, hh, x, NN, box, hbox, &(hb->d));\n                            /* Store the energy */\n                            storeHbEnergy(hb, i, j, h, E, nframes);\n                        }\n                    }\n                }\n#endif        /* HAVE_NN_LOOPS */\n            } /* if (bNN)*/\n            else\n            {\n                if (bSelected)\n                {\n\n#pragma omp single\n                    {\n                        /* Do not parallelize this just yet. */\n                        /* int ii; */\n                        for (ii = 0; (ii < nsel); ii++)\n                        {\n                            int dd = index[0][i];\n                            int aa = index[0][i+2];\n                            /* int */ hh = index[0][i+1];\n                            ihb          = is_hbond(hb, ii, ii, dd, aa, rcut, r2cut, ccut, x, bBox, box,\n                                                    hbox, &dist, &ang, bDA, &h, bContact, bMerge, &peri);\n\n                            if (ihb)\n                            {\n                                /* add to index if not already there */\n                                /* Add a hbond */\n                                add_hbond(hb, dd, aa, hh, ii, ii, nframes, bMerge, ihb, bContact, peri);\n                            }\n                        }\n                    } /* omp single */\n                }     /* if (bSelected) */\n                else\n                {\n\n#pragma omp single\n                    {\n                        if (bGem)\n                        {\n                            calcBoxProjection(box, hb->per->P);\n                        }\n\n                        /* loop over all gridcells (xi,yi,zi)      */\n                        /* Removed confusing macro, DvdS 27/12/98  */\n\n                    }\n                    /* The outer grid loop will have to do for now. */\n#pragma omp for schedule(dynamic)\n                    for (xi = 0; xi < ngrid[XX]; xi++)\n                    {\n                        for (yi = 0; (yi < ngrid[YY]); yi++)\n                        {\n                            for (zi = 0; (zi < ngrid[ZZ]); zi++)\n                            {\n\n                                /* loop over donor groups gr0 (always) and gr1 (if necessary) */\n                                for (grp = gr0; (grp <= (bTwo ? gr1 : gr0)); grp++)\n                                {\n                                    icell = &(grid[zi][yi][xi].d[grp]);\n\n                                    if (bTwo)\n                                    {\n                                        ogrp = 1-grp;\n                                    }\n                                    else\n                                    {\n                                        ogrp = grp;\n                                    }\n\n                                    /* loop over all hydrogen atoms from group (grp)\n                                     * in this gridcell (icell)\n                                     */\n                                    for (ai = 0; (ai < icell->nr); ai++)\n                                    {\n                                        i  = icell->atoms[ai];\n\n                                        /* loop over all adjacent gridcells (xj,yj,zj) */\n                                        for (zjj = grid_loop_begin(ngrid[ZZ], zi, bTric, FALSE);\n                                             zjj <= grid_loop_end(ngrid[ZZ], zi, bTric, FALSE);\n                                             zjj++)\n                                        {\n                                            zj        = grid_mod(zjj, ngrid[ZZ]);\n                                            bEdge_yjj = (zj == 0) || (zj == ngrid[ZZ] - 1);\n                                            for (yjj = grid_loop_begin(ngrid[YY], yi, bTric, bEdge_yjj);\n                                                 yjj <= grid_loop_end(ngrid[YY], yi, bTric, bEdge_yjj);\n                                                 yjj++)\n                                            {\n                                                yj        = grid_mod(yjj, ngrid[YY]);\n                                                bEdge_xjj =\n                                                    (yj == 0) || (yj == ngrid[YY] - 1) ||\n                                                    (zj == 0) || (zj == ngrid[ZZ] - 1);\n                                                for (xjj = grid_loop_begin(ngrid[XX], xi, bTric, bEdge_xjj);\n                                                     xjj <= grid_loop_end(ngrid[XX], xi, bTric, bEdge_xjj);\n                                                     xjj++)\n                                                {\n                                                    xj    = grid_mod(xjj, ngrid[XX]);\n                                                    jcell = &(grid[zj][yj][xj].a[ogrp]);\n                                                    /* loop over acceptor atoms from other group (ogrp)\n                                                     * in this adjacent gridcell (jcell)\n                                                     */\n                                                    for (aj = 0; (aj < jcell->nr); aj++)\n                                                    {\n                                                        j = jcell->atoms[aj];\n\n                                                        /* check if this once was a h-bond */\n                                                        peri = -1;\n                                                        ihb  = is_hbond(__HBDATA, grp, ogrp, i, j, rcut, r2cut, ccut, x, bBox, box,\n                                                                        hbox, &dist, &ang, bDA, &h, bContact, bMerge, &peri);\n\n                                                        if (ihb)\n                                                        {\n                                                            /* add to index if not already there */\n                                                            /* Add a hbond */\n                                                            add_hbond(__HBDATA, i, j, h, grp, ogrp, nframes, bMerge, ihb, bContact, peri);\n\n                                                            /* make angle and distance distributions */\n                                                            if (ihb == hbHB && !bContact)\n                                                            {\n                                                                if (dist > rcut)\n                                                                {\n                                                                    gmx_fatal(FARGS, \"distance is higher than what is allowed for an hbond: %f\", dist);\n                                                                }\n                                                                ang *= RAD2DEG;\n                                                                __ADIST[(int)( ang/abin)]++;\n                                                                __RDIST[(int)(dist/rbin)]++;\n                                                                if (!bTwo)\n                                                                {\n                                                                    int id, ia;\n                                                                    if ((id = donor_index(&hb->d, grp, i)) == NOTSET)\n                                                                    {\n                                                                        gmx_fatal(FARGS, \"Invalid donor %d\", i);\n                                                                    }\n                                                                    if ((ia = acceptor_index(&hb->a, ogrp, j)) == NOTSET)\n                                                                    {\n                                                                        gmx_fatal(FARGS, \"Invalid acceptor %d\", j);\n                                                                    }\n                                                                    resdist = abs(top.atoms.atom[i].resind-\n                                                                                  top.atoms.atom[j].resind);\n                                                                    if (resdist >= max_hx)\n                                                                    {\n                                                                        resdist = max_hx-1;\n                                                                    }\n                                                                    __HBDATA->nhx[nframes][resdist]++;\n                                                                }\n                                                            }\n\n                                                        }\n                                                    } /* for aj  */\n                                                }     /* for xjj */\n                                            }         /* for yjj */\n                                        }             /* for zjj */\n                                    }                 /* for ai  */\n                                }                     /* for grp */\n                            }                         /* for xi,yi,zi */\n                        }\n                    }\n                } /* if (bSelected) {...} else */\n\n\n                /* Better wait for all threads to finnish using x[] before updating it. */\n                k = nframes;\n#pragma omp barrier\n#pragma omp critical\n                {\n                    /* Sum up histograms and counts from p_hb[] into hb */\n                    if (bOMP)\n                    {\n                        hb->nhb[k]   += p_hb[threadNr]->nhb[k];\n                        hb->ndist[k] += p_hb[threadNr]->ndist[k];\n                        for (j = 0; j < max_hx; j++)\n                        {\n                            hb->nhx[k][j]  += p_hb[threadNr]->nhx[k][j];\n                        }\n                    }\n                }\n\n                /* Here are a handful of single constructs\n                 * to share the workload a bit. The most\n                 * important one is of course the last one,\n                 * where there's a potential bottleneck in form\n                 * of slow I/O.                    */\n#pragma omp barrier\n#pragma omp single\n                {\n                    if (hb != NULL)\n                    {\n                        analyse_donor_props(opt2fn_null(\"-don\", NFILE, fnm), hb, k, t, oenv);\n                    }\n                }\n\n#pragma omp single\n                {\n                    if (fpnhb)\n                    {\n                        do_nhb_dist(fpnhb, hb, t);\n                    }\n                }\n            } /* if (bNN) {...} else  +   */\n\n#pragma omp single\n            {\n                trrStatus = (read_next_x(oenv, status, &t, natoms, x, box));\n                nframes++;\n            }\n\n#pragma omp barrier\n        }\n        while (trrStatus);\n\n        if (bOMP)\n        {\n#pragma omp critical\n            {\n                hb->nrhb   += p_hb[threadNr]->nrhb;\n                hb->nrdist += p_hb[threadNr]->nrdist;\n            }\n            /* Free parallel datastructures */\n            sfree(p_hb[threadNr]->nhb);\n            sfree(p_hb[threadNr]->ndist);\n            sfree(p_hb[threadNr]->nhx);\n\n#pragma omp for\n            for (i = 0; i < nabin; i++)\n            {\n                for (j = 0; j < actual_nThreads; j++)\n                {\n\n                    adist[i] += p_adist[j][i];\n                }\n            }\n#pragma omp for\n            for (i = 0; i <= nrbin; i++)\n            {\n                for (j = 0; j < actual_nThreads; j++)\n                {\n                    rdist[i] += p_rdist[j][i];\n                }\n            }\n\n            sfree(p_adist[threadNr]);\n            sfree(p_rdist[threadNr]);\n        }\n    } /* End of parallel region */\n    if (bOMP)\n    {\n        sfree(p_adist);\n        sfree(p_rdist);\n    }\n\n    if (nframes < 2 && (opt2bSet(\"-ac\", NFILE, fnm) || opt2bSet(\"-life\", NFILE, fnm)))\n    {\n        gmx_fatal(FARGS, \"Cannot calculate autocorrelation of life times with less than two frames\");\n    }\n\n    free_grid(ngrid, &grid);\n\n    close_trj(status);\n    if (fpnhb)\n    {\n        ffclose(fpnhb);\n    }\n\n    /* Compute maximum possible number of different hbonds */\n    if (maxnhb > 0)\n    {\n        max_nhb = maxnhb;\n    }\n    else\n    {\n        max_nhb = 0.5*(hb->d.nrd*hb->a.nra);\n    }\n    /* Added support for -contact below.\n     * - Erik Marklund, May 29-31, 2006 */\n    /* Changed contact code.\n     * - Erik Marklund, June 29, 2006 */\n    if (bHBmap && !bNN)\n    {\n        if (hb->nrhb == 0)\n        {\n            printf(\"No %s found!!\\n\", bContact ? \"contacts\" : \"hydrogen bonds\");\n        }\n        else\n        {\n            printf(\"Found %d different %s in trajectory\\n\"\n                   \"Found %d different atom-pairs within %s distance\\n\",\n                   hb->nrhb, bContact ? \"contacts\" : \"hydrogen bonds\",\n                   hb->nrdist, (r2cut > 0) ? \"second cut-off\" : \"hydrogen bonding\");\n\n            /*Control the pHist.*/\n\n            if (bMerge)\n            {\n                merge_hb(hb, bTwo, bContact);\n            }\n\n            if (opt2bSet(\"-hbn\", NFILE, fnm))\n            {\n                dump_hbmap(hb, NFILE, fnm, bTwo, bContact, isize, index, grpnames, &top.atoms);\n            }\n\n            /* Moved the call to merge_hb() to a line BEFORE dump_hbmap\n             * to make the -hbn and -hmb output match eachother.\n             * - Erik Marklund, May 30, 2006 */\n        }\n    }\n    /* Print out number of hbonds and distances */\n    aver_nhb  = 0;\n    aver_dist = 0;\n    fp        = xvgropen(opt2fn(\"-num\", NFILE, fnm), bContact ? \"Contacts\" :\n                         \"Hydrogen Bonds\", output_env_get_xvgr_tlabel(oenv), \"Number\", oenv);\n    snew(leg, 2);\n    snew(leg[0], STRLEN);\n    snew(leg[1], STRLEN);\n    sprintf(leg[0], \"%s\", bContact ? \"Contacts\" : \"Hydrogen bonds\");\n    sprintf(leg[1], \"Pairs within %g nm\", (r2cut > 0) ? r2cut : rcut);\n    xvgr_legend(fp, 2, (const char**)leg, oenv);\n    sfree(leg[1]);\n    sfree(leg[0]);\n    sfree(leg);\n    for (i = 0; (i < nframes); i++)\n    {\n        fprintf(fp, \"%10g  %10d  %10d\\n\", hb->time[i], hb->nhb[i], hb->ndist[i]);\n        aver_nhb  += hb->nhb[i];\n        aver_dist += hb->ndist[i];\n    }\n    ffclose(fp);\n    aver_nhb  /= nframes;\n    aver_dist /= nframes;\n    /* Print HB distance distribution */\n    if (opt2bSet(\"-dist\", NFILE, fnm))\n    {\n        long sum;\n\n        sum = 0;\n        for (i = 0; i < nrbin; i++)\n        {\n            sum += rdist[i];\n        }\n\n        fp = xvgropen(opt2fn(\"-dist\", NFILE, fnm),\n                      \"Hydrogen Bond Distribution\",\n                      bDA ?\n                      \"Donor - Acceptor Distance (nm)\" :\n                      \"Hydrogen - Acceptor Distance (nm)\", \"\", oenv);\n        for (i = 0; i < nrbin; i++)\n        {\n            fprintf(fp, \"%10g %10g\\n\", (i+0.5)*rbin, rdist[i]/(rbin*(real)sum));\n        }\n        ffclose(fp);\n    }\n\n    /* Print HB angle distribution */\n    if (opt2bSet(\"-ang\", NFILE, fnm))\n    {\n        long sum;\n\n        sum = 0;\n        for (i = 0; i < nabin; i++)\n        {\n            sum += adist[i];\n        }\n\n        fp = xvgropen(opt2fn(\"-ang\", NFILE, fnm),\n                      \"Hydrogen Bond Distribution\",\n                      \"Hydrogen - Donor - Acceptor Angle (\\\\SO\\\\N)\", \"\", oenv);\n        for (i = 0; i < nabin; i++)\n        {\n            fprintf(fp, \"%10g %10g\\n\", (i+0.5)*abin, adist[i]/(abin*(real)sum));\n        }\n        ffclose(fp);\n    }\n\n    /* Print HB in alpha-helix */\n    if (opt2bSet(\"-hx\", NFILE, fnm))\n    {\n        fp = xvgropen(opt2fn(\"-hx\", NFILE, fnm),\n                      \"Hydrogen Bonds\", output_env_get_xvgr_tlabel(oenv), \"Count\", oenv);\n        xvgr_legend(fp, NRHXTYPES, hxtypenames, oenv);\n        for (i = 0; i < nframes; i++)\n        {\n            fprintf(fp, \"%10g\", hb->time[i]);\n            for (j = 0; j < max_hx; j++)\n            {\n                fprintf(fp, \" %6d\", hb->nhx[i][j]);\n            }\n            fprintf(fp, \"\\n\");\n        }\n        ffclose(fp);\n    }\n    if (!bNN)\n    {\n        printf(\"Average number of %s per timeframe %.3f out of %g possible\\n\",\n               bContact ? \"contacts\" : \"hbonds\",\n               bContact ? aver_dist : aver_nhb, max_nhb);\n    }\n\n    /* Do Autocorrelation etc. */\n    if (hb->bHBmap)\n    {\n        /*\n           Added support for -contact in ac and hbm calculations below.\n           - Erik Marklund, May 29, 2006\n         */\n        ivec itmp;\n        rvec rtmp;\n        if (opt2bSet(\"-ac\", NFILE, fnm) || opt2bSet(\"-life\", NFILE, fnm))\n        {\n            please_cite(stdout, \"Spoel2006b\");\n        }\n        if (opt2bSet(\"-ac\", NFILE, fnm))\n        {\n            char *gemstring = NULL;\n\n            if (bGem || bNN)\n            {\n                params = init_gemParams(rcut, D, hb->time, hb->nframes/2, nFitPoints, fit_start, fit_end,\n                                        gemBallistic, nBalExp, bBallisticDt);\n                if (params == NULL)\n                {\n                    gmx_fatal(FARGS, \"Could not initiate t_gemParams params.\");\n                }\n            }\n            gemstring = strdup(gemType[hb->per->gemtype]);\n            do_hbac(opt2fn(\"-ac\", NFILE, fnm), hb, nDump,\n                    bMerge, bContact, fit_start, temp, r2cut > 0, smooth_tail_start, oenv,\n                    params, gemstring, nThreads, NN, bBallistic, bGemFit);\n        }\n        if (opt2bSet(\"-life\", NFILE, fnm))\n        {\n            do_hblife(opt2fn(\"-life\", NFILE, fnm), hb, bMerge, bContact, oenv);\n        }\n        if (opt2bSet(\"-hbm\", NFILE, fnm))\n        {\n            t_matrix mat;\n            int      id, ia, hh, x, y;\n\n            if ((nframes > 0) && (hb->nrhb > 0))\n            {\n                mat.nx = nframes;\n                mat.ny = hb->nrhb;\n\n                snew(mat.matrix, mat.nx);\n                for (x = 0; (x < mat.nx); x++)\n                {\n                    snew(mat.matrix[x], mat.ny);\n                }\n                y = 0;\n                for (id = 0; (id < hb->d.nrd); id++)\n                {\n                    for (ia = 0; (ia < hb->a.nra); ia++)\n                    {\n                        for (hh = 0; (hh < hb->maxhydro); hh++)\n                        {\n                            if (hb->hbmap[id][ia])\n                            {\n                                if (ISHB(hb->hbmap[id][ia]->history[hh]))\n                                {\n                                    /* Changed '<' into '<=' in the for-statement below.\n                                     * It fixed the previously undiscovered bug that caused\n                                     * the last occurance of an hbond/contact to not be\n                                     * set in mat.matrix. Have a look at any old -hbm-output\n                                     * and you will notice that the last column is allways empty.\n                                     * - Erik Marklund May 30, 2006\n                                     */\n                                    for (x = 0; (x <= hb->hbmap[id][ia]->nframes); x++)\n                                    {\n                                        int nn0 = hb->hbmap[id][ia]->n0;\n                                        range_check(y, 0, mat.ny);\n                                        mat.matrix[x+nn0][y] = is_hb(hb->hbmap[id][ia]->h[hh], x);\n                                    }\n                                    y++;\n                                }\n                            }\n                        }\n                    }\n                }\n                mat.axis_x = hb->time;\n                snew(mat.axis_y, mat.ny);\n                for (j = 0; j < mat.ny; j++)\n                {\n                    mat.axis_y[j] = j;\n                }\n                sprintf(mat.title, bContact ? \"Contact Existence Map\" :\n                        \"Hydrogen Bond Existence Map\");\n                sprintf(mat.legend, bContact ? \"Contacts\" : \"Hydrogen Bonds\");\n                sprintf(mat.label_x, \"%s\", output_env_get_xvgr_tlabel(oenv));\n                sprintf(mat.label_y, bContact ? \"Contact Index\" : \"Hydrogen Bond Index\");\n                mat.bDiscrete = TRUE;\n                mat.nmap      = 2;\n                snew(mat.map, mat.nmap);\n                for (i = 0; i < mat.nmap; i++)\n                {\n                    mat.map[i].code.c1 = hbmap[i];\n                    mat.map[i].desc    = hbdesc[i];\n                    mat.map[i].rgb     = hbrgb[i];\n                }\n                fp = opt2FILE(\"-hbm\", NFILE, fnm, \"w\");\n                write_xpm_m(fp, mat);\n                ffclose(fp);\n                for (x = 0; x < mat.nx; x++)\n                {\n                    sfree(mat.matrix[x]);\n                }\n                sfree(mat.axis_y);\n                sfree(mat.matrix);\n                sfree(mat.map);\n            }\n            else\n            {\n                fprintf(stderr, \"No hydrogen bonds/contacts found. No hydrogen bond map will be printed.\\n\");\n            }\n        }\n    }\n\n    if (bGem)\n    {\n        fprintf(stderr, \"There were %i periodic shifts\\n\", hb->per->nper);\n        fprintf(stderr, \"Freeing pHist for all donors...\\n\");\n        for (i = 0; i < hb->d.nrd; i++)\n        {\n            fprintf(stderr, \"\\r%i\", i);\n            if (hb->per->pHist[i] != NULL)\n            {\n                for (j = 0; j < hb->a.nra; j++)\n                {\n                    clearPshift(&(hb->per->pHist[i][j]));\n                }\n                sfree(hb->per->pHist[i]);\n            }\n        }\n        sfree(hb->per->pHist);\n        sfree(hb->per->p2i);\n        sfree(hb->per);\n        fprintf(stderr, \"...done.\\n\");\n    }\n\n#ifdef HAVE_NN_LOOPS\n    if (bNN)\n    {\n        free_hbEmap(hb);\n    }\n#endif\n\n    if (hb->bDAnr)\n    {\n        int    i, j, nleg;\n        char **legnames;\n        char   buf[STRLEN];\n\n#define USE_THIS_GROUP(j) ( (j == gr0) || (bTwo && (j == gr1)) )\n\n        fp = xvgropen(opt2fn(\"-dan\", NFILE, fnm),\n                      \"Donors and Acceptors\", output_env_get_xvgr_tlabel(oenv), \"Count\", oenv);\n        nleg = (bTwo ? 2 : 1)*2;\n        snew(legnames, nleg);\n        i = 0;\n        for (j = 0; j < grNR; j++)\n        {\n            if (USE_THIS_GROUP(j) )\n            {\n                sprintf(buf, \"Donors %s\", grpnames[j]);\n                legnames[i++] = strdup(buf);\n                sprintf(buf, \"Acceptors %s\", grpnames[j]);\n                legnames[i++] = strdup(buf);\n            }\n        }\n        if (i != nleg)\n        {\n            gmx_incons(\"number of legend entries\");\n        }\n        xvgr_legend(fp, nleg, (const char**)legnames, oenv);\n        for (i = 0; i < nframes; i++)\n        {\n            fprintf(fp, \"%10g\", hb->time[i]);\n            for (j = 0; (j < grNR); j++)\n            {\n                if (USE_THIS_GROUP(j) )\n                {\n                    fprintf(fp, \" %6d\", hb->danr[i][j]);\n                }\n            }\n            fprintf(fp, \"\\n\");\n        }\n        ffclose(fp);\n    }\n\n    thanx(stdout);\n\n    return 0;\n}\n", "meta": {"hexsha": "378a03f3866742b7f244094ee66d7a35a92db141", "size": 162958, "ext": "c", "lang": "C", "max_stars_repo_path": "gromacs-4.6.5/src/tools/gmx_hbond.c", "max_stars_repo_name": "farajilab/gifs_release", "max_stars_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-03-04T18:56:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:49:22.000Z", "max_issues_repo_path": "gromacs-4.6.5/src/tools/gmx_hbond.c", "max_issues_repo_name": "farajilab/gifs_release", "max_issues_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gromacs-4.6.5/src/tools/gmx_hbond.c", "max_forks_repo_name": "farajilab/gifs_release", "max_forks_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-08T00:11:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T00:11:00.000Z", "avg_line_length": 33.0744875178, "max_line_length": 294, "alphanum_fraction": 0.4067673879, "num_tokens": 43244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24508501313237172, "lm_q2_score": 0.02262919826159449, "lm_q1q2_score": 0.005546077353117928}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef dirty_08c91b95_68e8_437c_b721_3ad67fdc25ac_h\r\n#define dirty_08c91b95_68e8_437c_b721_3ad67fdc25ac_h\r\n\r\n#include <gslib/std.h>\r\n#include <ariel/type.h>\r\n\r\n__ariel_begin__\r\n\r\nclass dirty_list\r\n{\r\npublic:\r\n    typedef list<rect> rect_list;\r\n    typedef rect_list::iterator iterator;\r\n    typedef rect_list::const_iterator const_iterator;\r\n\r\nprotected:\r\n    int         _width, _height;\r\n    int         _cap;\r\n    bool        _whole;\r\n\r\nprivate:\r\n    rect_list   _rclist;\r\n\r\npublic:\r\n    dirty_list();\r\n    dirty_list(int w, int h);\r\n    int size() const { return (int)_rclist.size(); }\r\n    void clear();\r\n    void set_dimension(int w, int h);\r\n    void add(rect rc);\r\n    void set_whole() { _whole = true;}\r\n    bool is_whole() const { return _whole; }\r\n    bool is_dirty(const rect& rc) const;\r\n    iterator begin() { return _rclist.begin(); }\r\n    const_iterator begin() const { return _rclist.begin(); }\r\n    iterator end() { return _rclist.end(); }\r\n    const_iterator end() const { return _rclist.end(); }\r\n};\r\n\r\n__ariel_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "de21f75df93f1f9c57b4b9e303c155672fafc698", "size": 2313, "ext": "h", "lang": "C", "max_stars_repo_path": "include/ariel/dirty.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/ariel/dirty.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ariel/dirty.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 33.0428571429, "max_line_length": 82, "alphanum_fraction": 0.6995244272, "num_tokens": 556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16667541296674693, "lm_q2_score": 0.03308597779281981, "lm_q1q2_score": 0.0055146190120268605}}
{"text": "\n#pragma once\n\n#include <gsl/gsl>\n\nstruct ScanWordResult;\nstruct GlyphVertex2d;\nstruct TigFont;\nstruct TigTextStyle;\nstruct TigRect;\nstruct TigFontMetrics;\nusing namespace gsl;\n\nnamespace gfx {\n\tclass RenderingDevice;\n\tclass ShapeRenderer2d;\n\tclass TextEngine;\n}\n\nclass FontRenderer {\npublic:\n\texplicit FontRenderer(gfx::RenderingDevice& g);\n\t~FontRenderer();\n\n\tvoid RenderRun(cstring_span<> text,\n\t\tint x,\n\t\tint y,\n\t\tconst TigRect& bounds,\n\t\tTigTextStyle& style,\n\t\tconst TigFont& font);\n\nprivate:\n\n\tvoid RenderGlyphs(const GlyphVertex2d* vertices2d, int textureId, int glyphCount);\n\tstatic void Rotate2d(float& x, float& y,\n\t\tfloat rotCos, float rotSin,\n\t\tfloat centerX, float centerY);\n\n\tstruct Impl;\n\tstd::unique_ptr<Impl> mImpl;\n\n};\n\n/*\nSeparates a block of text given flags into words split up\non lines and renders them.\n*/\nclass TextLayouter {\n\tfriend class FontRenderer;\npublic:\n\tTextLayouter(gfx::RenderingDevice& device, gfx::ShapeRenderer2d& shapeRenderer);\n\t~TextLayouter();\n\n\tvoid LayoutAndDraw(gsl::cstring_span<> text, const TigFont &font, TigRect& extents, TigTextStyle& style);\n\n\tvoid Measure(const TigFont &font, const TigTextStyle &style, TigFontMetrics &metrics);\n\nprivate:\n\tvoid DrawBackgroundOrOutline(const TigRect& rect, const TigTextStyle& style);\n\tstatic int GetGlyphIdx(char ch, const char *text);\n\tScanWordResult ScanWord(const char* text,\n\t\tint firstIdx,\n\t\tint textLength,\n\t\tint tabWidth,\n\t\tbool lastLine,\n\t\tconst TigFont& font,\n\t\tconst TigTextStyle& style,\n\t\tint remainingSpace);\n\tstd::pair<int, int> TextLayouter::MeasureCharRun(cstring_span<> text,\n\t\tconst TigTextStyle& style,\n\t\tconst TigRect& extents,\n\t\tint extentsWidth,\n\t\tconst TigFont& font,\n\t\tint linePadding,\n\t\tbool lastLine);\n\tbool HasMoreText(cstring_span<> text, int tabWidth);\n\n\tvoid LayoutAndDrawVanilla(gsl::cstring_span<> text, \n\t\tconst TigFont &font, \n\t\tTigRect& extents, \n\t\tTigTextStyle& style);\n\n\tvoid MeasureVanilla(const TigFont &font, \n\t\tconst TigTextStyle &style, \n\t\tTigFontMetrics &metrics) const;\n\n\tuint32_t MeasureVanillaLine(const TigFont &font, const TigTextStyle &style, const char *text) const;\n\tuint32_t MeasureVanillaParagraph(const TigFont &font, const TigTextStyle &style, const char *text) const;\n\tuint32_t CountLinesVanilla(uint32_t maxWidth, uint32_t maxLines, const char *text, const TigFont &font, const TigTextStyle &style) const;\n\n\tstatic const char *sEllipsis;\n\tgfx::TextEngine &mTextEngine;\n\tFontRenderer mRenderer;\n\tstd::unique_ptr<class FontsMapping> mMapping;\n\tgfx::ShapeRenderer2d& mShapeRenderer;\n};\n", "meta": {"hexsha": "39b4cb5993f8268e9e67b41347b8875ba850d909", "size": 2527, "ext": "h", "lang": "C", "max_stars_repo_path": "TemplePlus/fonts/fonts.h", "max_stars_repo_name": "edoipi/TemplePlus", "max_stars_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 69.0, "max_stars_repo_stars_event_min_datetime": "2015-05-05T14:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T06:13:04.000Z", "max_issues_repo_path": "TemplePlus/fonts/fonts.h", "max_issues_repo_name": "edoipi/TemplePlus", "max_issues_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 457.0, "max_issues_repo_issues_event_min_datetime": "2015-05-01T22:07:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T02:19:10.000Z", "max_forks_repo_path": "TemplePlus/fonts/fonts.h", "max_forks_repo_name": "edoipi/TemplePlus", "max_forks_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2016-02-04T21:19:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T23:14:51.000Z", "avg_line_length": 26.0515463918, "max_line_length": 138, "alphanum_fraction": 0.7669172932, "num_tokens": 652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2393493581744072, "lm_q2_score": 0.022977367275662783, "lm_q1q2_score": 0.005499618109967515}}
{"text": "#include \"indexes/utils/Utils.h\"\n\n#include <doctest/doctest.h>\n#include <gsl/span>\n\n#include <inttypes.h>\n#include <limits>\n#include <map>\n#include <random>\n#include <string>\n#include <thread>\n#include <vector>\n\nenum class ConcurrentMapTestWorkload {\n  WL_CONTENTED,\n  WL_CONTENTED_SWAP,\n  WL_RANDOM,\n};\n\nenum class LookupType {\n  LT_DEFAULT,\n  LT_CUSTOM,\n};\n\nstd::vector<int64_t> generateUniqueValues(int num_threads, int perthread_count,\n                                          ConcurrentMapTestWorkload workload);\n\ntemplate <typename MapType> void MixedMapTest() {\n  indexes::utils::ThreadRegistry::RegisterThread();\n\n  MapType map;\n\n  int num_operations = 1024 * 1024;\n  int cardinality = num_operations * 0.1;\n\n  constexpr auto INSERT_OP = 1;\n  constexpr auto LOOKUP_OP = 2;\n  constexpr auto DELETE_OP = 3;\n\n  std::random_device r;\n  std::seed_seq seed{r(), r(), r(), r(), r(), r(), r(), r()};\n  std::mt19937 rnd(seed);\n\n  std::uniform_int_distribution<int> key_dist{1, cardinality};\n  std::uniform_int_distribution<int> val_dist;\n  std::uniform_int_distribution<> op_dist{INSERT_OP, DELETE_OP};\n\n  std::map<int, int> key_values;\n\n  for (int i = 0; i < num_operations; i++) {\n    const auto key = key_dist(rnd);\n    const auto op = op_dist(rnd);\n    int val;\n\n    switch (op) {\n    case INSERT_OP: {\n      val = val_dist(rnd);\n\n      if (key_values.count(key)) {\n        REQUIRE(*map.Search(key) == key_values[key]);\n        REQUIRE(*map.Update(key, val) == key_values[key]);\n      } else {\n        REQUIRE(map.Insert(key, val) == true);\n        REQUIRE(*map.Search(key) == val);\n      }\n\n      key_values[key] = val;\n      break;\n    }\n\n    case LOOKUP_OP: {\n      if (key_values.count(key))\n        REQUIRE(*map.Search(key) == key_values[key]);\n      else\n        REQUIRE(map.Search(key).has_value() == false);\n\n      break;\n    }\n\n    case DELETE_OP: {\n      if (key_values.count(key)) {\n        REQUIRE(*map.Search(key) == key_values[key]);\n        REQUIRE(*map.Delete(key) == key_values[key]);\n        key_values.erase(key);\n      } else {\n        REQUIRE(map.Delete(key).has_value() == false);\n      }\n      break;\n    }\n\n    default:\n      continue;\n    }\n  }\n\n  REQUIRE(map.size() == key_values.size());\n\n  for (const auto &kv : key_values) {\n    REQUIRE(*map.Delete(kv.first) == kv.second);\n  }\n\n  REQUIRE(map.size() == 0);\n\n  indexes::utils::ThreadRegistry::UnregisterThread();\n}\n\ntemplate <typename MapType, LookupType LkType, typename LookupOp>\nstatic void lookup_worker(MapType &map, gsl::span<const int64_t> vals,\n                          int64_t min_val, int64_t max_val,\n                          const LookupOp &op) {\n  indexes::utils::ThreadRegistry::RegisterThread();\n\n  if constexpr (LkType == LookupType::LT_DEFAULT) {\n    (void)op;\n    for (auto val : vals) {\n      map.Search(val);\n    }\n  } else {\n    op(map, min_val, max_val, vals.size());\n  }\n  indexes::utils::ThreadRegistry::UnregisterThread();\n}\n\ntemplate <typename MapType>\nstatic void insert_worker(MapType &map, gsl::span<const int64_t> vals) {\n  indexes::utils::ThreadRegistry::RegisterThread();\n\n  for (auto val : vals) {\n    REQUIRE(map.Insert(val, val) == true);\n    REQUIRE(*map.Search(val) == val);\n  }\n\n  indexes::utils::ThreadRegistry::UnregisterThread();\n}\n\nenum class OpType { INSERT, DELETE, DELETE_AND_INSERT };\n\ntemplate <typename MapType>\nstatic void delete_worker(MapType &map, gsl::span<const int64_t> vals,\n                          OpType op) {\n  indexes::utils::ThreadRegistry::RegisterThread();\n\n  for (auto val : vals) {\n    switch (op) {\n    case OpType::DELETE:\n      REQUIRE(*map.Delete(val) == val);\n      REQUIRE(map.Search(val).has_value() == false);\n      break;\n\n    case OpType::DELETE_AND_INSERT:\n      REQUIRE(*map.Delete(val) == val);\n      REQUIRE(map.Insert(val, val) == true);\n      break;\n\n    case OpType::INSERT:\n      break;\n    }\n  }\n\n  indexes::utils::ThreadRegistry::UnregisterThread();\n}\n\ntemplate <typename MapType, LookupType LkType, typename LookupOp>\nvoid ConcurrentMapTest(ConcurrentMapTestWorkload workload, LookupOp &&lop) {\n  MapType map;\n  constexpr int PER_THREAD_OP_COUNT = 256 * 1024;\n  const int NUM_THREADS = std::thread::hardware_concurrency();\n  const std::vector<int64_t> vals =\n      generateUniqueValues(NUM_THREADS, PER_THREAD_OP_COUNT, workload);\n  auto [min_it, max_it] = std::minmax_element(vals.begin(), vals.begin());\n  int64_t min_val = *min_it, max_val = *max_it;\n\n  indexes::utils::ThreadRegistry::RegisterThread();\n\n  auto run_test = [&](OpType op) {\n    std::vector<std::thread> workers;\n    int startval = 0;\n    int quantum = vals.size() / NUM_THREADS;\n\n    for (int i = 0; i < NUM_THREADS; i++) {\n      if (op == OpType::INSERT) {\n        workers.emplace_back(\n            insert_worker<MapType>, std::ref(map),\n            gsl::span<const int64_t>{vals.data() + startval, quantum});\n      } else {\n        workers.emplace_back(\n            delete_worker<MapType>, std::ref(map),\n            gsl::span<const int64_t>{vals.data() + startval, quantum}, op);\n      }\n\n      startval += quantum;\n    }\n\n    workers.emplace_back(lookup_worker<MapType, LkType, LookupOp>,\n                         std::ref(map), gsl::span<const int64_t>{vals}, min_val,\n                         max_val, std::cref(lop));\n\n    for (auto &worker : workers) {\n      worker.join();\n    }\n  };\n\n  // Insert check\n  {\n    run_test(OpType::INSERT);\n\n    REQUIRE(map.size() == vals.size());\n\n    for (auto val : vals) {\n      REQUIRE(*map.Search(val) == val);\n    }\n  }\n\n  // Delete And Insert check\n  {\n    run_test(OpType::DELETE_AND_INSERT);\n\n    for (auto val : vals) {\n      REQUIRE(*map.Search(val) == val);\n    }\n\n    REQUIRE(map.size() == vals.size());\n  }\n\n  // Delete check\n  {\n    run_test(OpType::DELETE);\n\n    REQUIRE(map.size() == 0);\n  }\n\n  indexes::utils::ThreadRegistry::UnregisterThread();\n}\n", "meta": {"hexsha": "de947fb2310eb69ab3a758ebc7b7b771dc1c2969", "size": 5847, "ext": "h", "lang": "C", "max_stars_repo_path": "test/testConcurrentMapUtils.h", "max_stars_repo_name": "harikrishnan94/InMemIndexes", "max_stars_repo_head_hexsha": "e4027ba2151be57a59034d04dba7d0f2a8e75fef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-07-31T04:06:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-27T20:03:10.000Z", "max_issues_repo_path": "test/testConcurrentMapUtils.h", "max_issues_repo_name": "harikrishnan94/bwtree", "max_issues_repo_head_hexsha": "e4027ba2151be57a59034d04dba7d0f2a8e75fef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/testConcurrentMapUtils.h", "max_forks_repo_name": "harikrishnan94/bwtree", "max_forks_repo_head_hexsha": "e4027ba2151be57a59034d04dba7d0f2a8e75fef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9871794872, "max_line_length": 80, "alphanum_fraction": 0.620147084, "num_tokens": 1489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18476749269168688, "lm_q2_score": 0.029760091471954676, "lm_q1q2_score": 0.005498697483548319}}
{"text": "/**\n * \\copyright\n * Copyright (c) 2015, OpenGeoSys Community (http://www.opengeosys.org)\n *            Distributed under a Modified BSD License.\n *              See accompanying file LICENSE.txt or\n *              http://www.opengeosys.org/project/license\n *\n */\n\n/**************************************************************************/\n/* ROCKFLOW - Modul: makros.h\n */\n/* Aufgabe:\n   Diese Datei wird von allen ROCKFLOW-Modulen (*.c - Dateien !!!)\n   importiert. Sie enthaelt globale Preprozessor-Definitionen und\n   importiert weitere, (fast) ueberall benoetigte Header.\n\n */\n/**************************************************************************/\n\n#ifndef makros_INC\n#define makros_INC\n\n/* Global benoetigte Header */\n//#include <stdlib.h>\n/* Speicherverwaltung */\n//#include <string.h>\n#include <string>\n\n/* Zeichenketten */\n//#include <float.h>\n/* Floating-Point */\n\n/* ROCKFLOW-Version */\n// LB: renamed ROCKFLOW_VERSION to OGS_VERSION and moved the #define to\n// Base/Configure.h.in. Please set the version in the top-level CMakeLists.txt!!\n// (see sources/CMakeLists.txt)\n\n/* Definitionen von Makros zur Steuerung der bedingten Compilierung */\n#define SWITCHES\n/* Ausgabe der Schalterstellungen zu Beginn des Programms */\n#ifdef MSVCPP6\n#pragma warning(disable : 4786)\n#endif\n\n/* Laufzeitausgaben */\n#define TESTTIME\n#ifdef TESTTIME\n#define TIMER_ROCKFLOW 0\n#endif\n\n/**********************************************************************/\n/* Speicher */\n\n#ifndef NO_ERROR_CONTROL /* Wird ggf. im Makefile gesetzt */\n#define ERROR_CONTROL\n/* Fehlertests (Feldgrenzen, Existenz o.ae.), die bei sauberen Netzen und\n   einwandfrei funktionierendem Programm nichts bringen und nur Laufzeit\n   kosten */\n#endif\n\n#define MEMORY_MANAGEMENT_NOT_ANSI_COMPLIANT\n/*  Bei einigen Compilern werden\n     malloc(0)\n     realloc(NULL,xxx)\n     realloc(xxx,0)\n     free(NULL)\n    nicht ANSI-gerecht gehandhabt. Mit diesem Schalter wird\n    ANSI-Verhalten gewaehrleistet. */\n\n#define noMEMORY_ALLOCATION_TEST_SUCCESS\n/*  Prueft, ob eine Speicheranforderung erfolgreich absolviert wurde */\n\n#define noMEMORY_TEST_IN_TIME /* fuer Versions-Speichertest */\n/* Erstellt waehrend der Laufzeit eine Bilanz des allockierten\n   und wieder freigegebenen Speichers. Sehr Zeitintensiv !!! */\n\n#define noMEMORY_STR /* fuer Versions-Speichertest */\n/* Gibt Informationen bei Memory-Funktionen zur\n   Aufrufstellenlokalisation. Funktioniert nur zusammen mit\n   MEMORY_TEST_IN_TIME. Sehr Speicherintensiv!!! */\n\n#define noMEMORY_SHOW_USAGE\n/* Gibt bei MEMORY_TEST_IN_TIME Informationen ueber jeden\n   Malloc/Realloc/Free-Vorgang aus. */\n\n#define noMEMORY_REALLOC\n/* Ersetzt Realloc durch Malloc und Free und speichert um */\n\n#ifndef MEMORY_TEST_IN_TIME\n#ifdef MEMORY_SHOW_USAGE\n#undef MEMORY_SHOW_USAGE\n#endif\n#ifndef MEMORY_ALLOCATION_TEST_SUCCESS\n#ifdef MEMORY_STR\n#undef MEMORY_STR\n#endif\n#endif\n#endif\n\n#ifdef MEMORY_STR\n#define Malloc(a) MAlloc(a, __FILE__, __LINE__)\n#define Free(a) FRee(a, __FILE__, __LINE__)\n#define Realloc(a, b) REalloc(a, b, __FILE__, __LINE__)\n/* Ersetzt Malloc, Free und Realloc in allen *.c-Dateien durch den\n   erweiterten Aufruf mit Dateiname und Zeilennummer */\n#endif\n\n/**********************************************************************/\n/* Daten */\n\n#define noENABLE_ADT\n/* Listen, Baeumen, etc sind dann moeglich */\n\n/* Definitionen der Feldgroessen */\n#define ELEM_START_SIZE 200l\n/* Minimale Groesse des Elementverzeichnisses */\n#define ELEM_INC_SIZE 1000l\n/* Bei Erreichen von ELEM_START_SIZE wird das Elementverzeichnis\n   automatisch um ELEM_INC_SIZE vergroessert */\n#define NODE_START_SIZE 200l\n/* Minimale Groesse des Knotenverzeichnisses */\n#define NODE_INC_SIZE 1000l\n/* Bei Erreichen von NODE_START_SIZE wird das Knotenverzeichnis\n   automatisch um NODE_INC_SIZE vergroessert */\n#define EDGE_START_SIZE 0l\n/* Minimale Groesse des Kantenverzeichnisses */\n#define EDGE_INC_SIZE 1000l\n/* Bei Erreichen von EDGE_START_SIZE wird das Kantenverzeichnis\n   automatisch um EDGE_INC_SIZE vergroessert */\n#define PLAIN_START_SIZE 0l\n/* Minimale Groesse des Flaechenverzeichnisses */\n#define PLAIN_INC_SIZE 1000l\n/* Bei Erreichen von PLAIN_START_SIZE wird das Flaechenverzeichnis\n   automatisch um PLAIN_INC_SIZE vergroessert */\n\n/**********************************************************************/\n/* Protokolle */\n\n/* Definitionen der Dateinamen-Erweiterungen */\n#define TEXT_EXTENSION \".rfd\"\n/* Dateinamen-Erweiterung fuer Text-Eingabedatei */\n#define PROTOCOL_EXTENSION \".rfe\"\n/* Dateinamen-Erweiterung fuer Text-Protokolldatei */\n#define RF_INPUT_EXTENSION \".rfi\"\n/* Dateinamen-Erweiterung fuer RF-Input-Dateien */\n#define RF_OUTPUT_EXTENSION \".rfo\"\n/* Dateinamen-Erweiterung fuer RF-Output-Dateien */\n#define RF_MESSAGE_EXTENSION \".msg\"\n/* Dateinamen-Erweiterung fuer RF-Output-Dateien */\n#define RF_SAVE_EXTENSION1 \".sv1\"\n/* Dateinamen-Erweiterung fuer RF-Sicherheitskopien */\n#define RF_SAVE_EXTENSION2 \".sv2\"\n/* Dateinamen-Erweiterung fuer RF-Sicherheitskopien */\n#define MESH_GENERATOR_EXTENSION \".rfm\"\n/* Dateinamen-Erweiterung fuer Text-Eingabedatei (Netzgenerator) */\n#define MESH_GENERATOR_PROTOCOL_EXTENSION \".rfg\"\n/* Dateinamen-Erweiterung fuer Text-Protokolldatei (Netzgenerator) */\n#define INVERSE_EXTENSION \".rfv\" /* ah inv */\n/* Dateinamen-Erweiterung fuer Text-Eingabedatei (Inverses Modellieren) */\n#define INVERSE_PROTOCOL_EXTENSION \".rfp\"\n/* Dateinamen-Erweiterung fuer Text-Eingabedatei (Inverses Modellieren) */\n#define CHEM_REACTION_EXTENSION \".pqc\"\n/* Dateinamen-Erweiterung fuer Text-Eingabedatei (Chemical reaction) */\n#define CHEMAPP_REACTION_EXTENSION \".chm\"\n#define REACTION_EXTENSION_CHEMAPP \".cap\" // DL/SB 11.2008\n#define TEC_FILE_EXTENSION \".tec\"\n#define VTK_FILE_EXTENSION \".vtk\" // GK\n#define CSV_FILE_EXTENSION \".csv\"\n\n#define noTESTFILES\n/* RFD-File Datenbank testen */\n\n#define noEXT_RFD\n/* Eingabeprotokoll ausfuehrlich kommentieren */\n#define EXT_RFD_MIN\n/* Eingabeprotokoll kommentieren, nur gefundene Schluesselworte */\n#ifdef EXT_RFD\n#undef EXT_RFD_MIN\n#endif\n\n/* Format der Double-Ausgabe ueber FilePrintDouble --> txtinout */\n#define FORMAT_DOUBLE\n#define FPD_GESAMT 4\n#define FPD_NACHKOMMA 14\n\n/**********************************************************************/\n/* C1.2 Numerik */\n#define noTESTTAYLOR\n/* nur zu Testzwecken: Taylor-Galerkin-Verfahren nach Donea (1D) */\n\n/**********************************************************************/\n/* C1.4 Loeser */\n#define noNULLE_ERGEBNIS\n/* Nullt den Ergebnisvektor vor Aufruf des Loesers; ansonsten wird er\n   mit den Ergebniswerten des letzten Zeitschritts vorbelegt. */\n#define noSOLVER_SHOW_ERROR\n/* Anzeigen des Iterationsfehlers */\n#define noSOLVER_SHOW_RESULTS\n/* Anzeigen der Iterationswerte */\n#define RELATIVE_EPS\n/* Abbruchkriterium bei CG-Loesern wird nicht als absolute Schranke\n   benutzt, sondern mit der Norm der rechten Seite multipliziert */\n/* Benutzte Normen bei Abbruchkriterien der CG-Loeser mit Speichertechnik:\n     MVekNorm1 : Spaltensummennorm\n     MVekNorm2 : euklidische Norm\n     MVekNormMax : Maximumnorm\n   Diese Normen muessen hier fuer die verschiedenen Loeser eingetragen\n   werden !!!\n */\n#define VEKNORM_BICG MVekNorm2\n/* Norm fuer SpBICG-Loeser */\n#define VEKNORM_BICGSTAB MVekNorm2\n/* Norm fuer SpBICGSTAB-Loeser */\n#define VEKNORM_QMRCGSTAB MVekNorm2\n/* Norm fuer SpQMRCGSTAB-Loeser */\n/*ahb*/\n#define VEKNORM_CG MVekNorm2\n/* Norm fuer SpCG-Loeser */\n#define NORM 2\n/* Norm fuer alle Objekte */\n#if NORM == 0\n#define VEKNORM MVekNormMax\n#elif NORM == 1\n#define VEKNORM MVekNorm1\n#else\n#define VEKNORM MVekNorm2\n#endif\n/*ahe*/\n\n/**********************************************************************/\n/* C1.9 Adaption */\n#define noTEST_ADAPTIV\n/* nur zu Testzwecken */\n#define noREF_STATIC\n/* erlaubt an ungefaehrlichen Stellen statische Variablen in Rekursionen.\n   --> refine.c */\n\n/**********************************************************************/\n/* C1.10 Grafik */\n#define no__RFGRAF\n/* Bindet zur Zeit die Grafik-Funktionen unter X11 */\n\n/**********************************************************************/\n/* PCS / C++ */\n#define PCS_OBJECTS\n#define PCS_NUMBER_MAX 30\n#define DOF_NUMBER_MAX 6 // JT: max # dof's per process\n#define MAX_FLUID_PHASES 2 // JT: max # fluid phases\n#define noPCS_NOD\n//#define GLI // KR\n#define noWINDOWS\n\n/**********************************************************************/\n/* Parallelization */\n#define noPARALLEL\n#define noCHEMAPP // MX\n#define noREACTION_ELEMENT\n#define noSX\n#define noMPI\n#define noOPEN_MP\n/* Definitionen von Konstanten, die bei manchen Compilern benoetigt werden */\n#ifndef NULL\n#define NULL ((void*)0)\n#endif\n#ifndef TRUE\n#define TRUE (0 == 0)\n#endif\n#ifndef FALSE\n#define FALSE (1 == 0)\n#endif\n#ifndef PI\n#define PI 3.14159265358979323846\n#endif\n\n/* Feste Zahlen fuer Genauigkeitspruefungen etc. */\n#define Mdrittel (1.0 / 3.0)\n#define MKleinsteZahl DBL_EPSILON\n#define MFastNull DBL_MIN\n#define MSqrt2Over3 sqrt(2.0 / 3.0)\n\n/* CBLAS oder MKL_CBLAS verwenden? Wenn ja, wo? */\n#define noCBLAS\n#define noMKL_CBLAS\n\n/* Includes fuer CBLAS oder MKL */\n#ifdef MKL_CBLAS\n#include <mkl_cblas.h>\n#define CBLAS\n#else\n#ifdef CBLAS\n#include <cblas.h>\n#endif\n#endif\n\n/* Wo verwenden? */\n#ifdef CBLAS\n#define CBLAS_M2MatVek\n#define CBLAS_MSkalarprodukt\n#define CBLAS_MMultMatMat\n#endif\n\n/* UMF-Pack-Loeser verwenden? */\n#ifdef UMFPACK31\n#define UMFPACK\n#endif\n#ifdef UMFPACK40\n#define UMFPACK\n#endif\n\n// min und max\n#define Max(A, B) ((A) > (B) ? (A) : (B))\n\n/*\n   #ifndef min\n   #define min(A,B) ((A) < (B) ? (A) : (B))\n   #endif\n   #ifndef max\n   #define max(A,B) ((A) > (B) ? (A) : (B))\n   #endif\n */\n#define MAX_ZEILE 2048\n/* max. Laenge einer UCD-Zeile; bei Leseproblemen vergroessern */\n\n// enum DIS_TYPES {CONSTANT,LINEAR};\n\nextern std::string FileName;\nextern std::string FilePath; // WW\n\n#define RESET_4410 // H2_ELE test\n\n//---- MPI Parallel --------------\n#if defined(USE_MPI) || defined(USE_MPI_PARPROC) || defined(USE_MPI_REGSOIL) || defined(USE_MPI_GEMS) \\\n    || defined(USE_MPI_BRNS) || defined(USE_MPI_KRC) || defined(USE_PETSC)\nextern int mysize; // WW\nextern int myrank;\n#endif\n//---- MPI Parallel --------------\n\n#endif\n", "meta": {"hexsha": "8a8131207f86a1be560b909c3686556a06dc51b7", "size": 10171, "ext": "h", "lang": "C", "max_stars_repo_path": "Base/makros.h", "max_stars_repo_name": "yingtaohu/ogs5", "max_stars_repo_head_hexsha": "3ebcbbc209e2306e0721d408a699ecaea52b89d1", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-07-28T01:46:45.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-28T01:46:45.000Z", "max_issues_repo_path": "Base/makros.h", "max_issues_repo_name": "yingtaohu/ogs5", "max_issues_repo_head_hexsha": "3ebcbbc209e2306e0721d408a699ecaea52b89d1", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-08-03T14:13:54.000Z", "max_issues_repo_issues_event_max_datetime": "2016-08-03T14:13:54.000Z", "max_forks_repo_path": "Base/makros.h", "max_forks_repo_name": "yingtaohu/ogs5", "max_forks_repo_head_hexsha": "3ebcbbc209e2306e0721d408a699ecaea52b89d1", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-06-27T15:30:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-15T08:30:31.000Z", "avg_line_length": 29.8269794721, "max_line_length": 103, "alphanum_fraction": 0.6928522269, "num_tokens": 2801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14223190955366666, "lm_q2_score": 0.03846618802254168, "lm_q1q2_score": 0.005471119375696484}}
{"text": "/* matrix/gsl_matrix_uint.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_MATRIX_UINT_H__\n#define __GSL_MATRIX_UINT_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_vector_uint.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size1;\n  size_t size2;\n  size_t tda;\n  unsigned int * data;\n  gsl_block_uint * block;\n  int owner;\n} gsl_matrix_uint;\n\ntypedef struct\n{\n  gsl_matrix_uint matrix;\n} _gsl_matrix_uint_view;\n\ntypedef _gsl_matrix_uint_view gsl_matrix_uint_view;\n\ntypedef struct\n{\n  gsl_matrix_uint matrix;\n} _gsl_matrix_uint_const_view;\n\ntypedef const _gsl_matrix_uint_const_view gsl_matrix_uint_const_view;\n\n/* Allocation */\n\ngsl_matrix_uint * \ngsl_matrix_uint_alloc (const size_t n1, const size_t n2);\n\ngsl_matrix_uint * \ngsl_matrix_uint_calloc (const size_t n1, const size_t n2);\n\ngsl_matrix_uint * \ngsl_matrix_uint_alloc_from_block (gsl_block_uint * b, \n                                   const size_t offset, \n                                   const size_t n1, \n                                   const size_t n2, \n                                   const size_t d2);\n\ngsl_matrix_uint * \ngsl_matrix_uint_alloc_from_matrix (gsl_matrix_uint * m,\n                                    const size_t k1, \n                                    const size_t k2,\n                                    const size_t n1, \n                                    const size_t n2);\n\ngsl_vector_uint * \ngsl_vector_uint_alloc_row_from_matrix (gsl_matrix_uint * m,\n                                        const size_t i);\n\ngsl_vector_uint * \ngsl_vector_uint_alloc_col_from_matrix (gsl_matrix_uint * m,\n                                        const size_t j);\n\nvoid gsl_matrix_uint_free (gsl_matrix_uint * m);\n\n/* Views */\n\n_gsl_matrix_uint_view \ngsl_matrix_uint_submatrix (gsl_matrix_uint * m, \n                            const size_t i, const size_t j, \n                            const size_t n1, const size_t n2);\n\n_gsl_vector_uint_view \ngsl_matrix_uint_row (gsl_matrix_uint * m, const size_t i);\n\n_gsl_vector_uint_view \ngsl_matrix_uint_column (gsl_matrix_uint * m, const size_t j);\n\n_gsl_vector_uint_view \ngsl_matrix_uint_diagonal (gsl_matrix_uint * m);\n\n_gsl_vector_uint_view \ngsl_matrix_uint_subdiagonal (gsl_matrix_uint * m, const size_t k);\n\n_gsl_vector_uint_view \ngsl_matrix_uint_superdiagonal (gsl_matrix_uint * m, const size_t k);\n\n_gsl_matrix_uint_view\ngsl_matrix_uint_view_array (unsigned int * base,\n                             const size_t n1, \n                             const size_t n2);\n\n_gsl_matrix_uint_view\ngsl_matrix_uint_view_array_with_tda (unsigned int * base, \n                                      const size_t n1, \n                                      const size_t n2,\n                                      const size_t tda);\n\n\n_gsl_matrix_uint_view\ngsl_matrix_uint_view_vector (gsl_vector_uint * v,\n                              const size_t n1, \n                              const size_t n2);\n\n_gsl_matrix_uint_view\ngsl_matrix_uint_view_vector_with_tda (gsl_vector_uint * v,\n                                       const size_t n1, \n                                       const size_t n2,\n                                       const size_t tda);\n\n\n_gsl_matrix_uint_const_view \ngsl_matrix_uint_const_submatrix (const gsl_matrix_uint * m, \n                                  const size_t i, const size_t j, \n                                  const size_t n1, const size_t n2);\n\n_gsl_vector_uint_const_view \ngsl_matrix_uint_const_row (const gsl_matrix_uint * m, \n                            const size_t i);\n\n_gsl_vector_uint_const_view \ngsl_matrix_uint_const_column (const gsl_matrix_uint * m, \n                               const size_t j);\n\n_gsl_vector_uint_const_view\ngsl_matrix_uint_const_diagonal (const gsl_matrix_uint * m);\n\n_gsl_vector_uint_const_view \ngsl_matrix_uint_const_subdiagonal (const gsl_matrix_uint * m, \n                                    const size_t k);\n\n_gsl_vector_uint_const_view \ngsl_matrix_uint_const_superdiagonal (const gsl_matrix_uint * m, \n                                      const size_t k);\n\n_gsl_matrix_uint_const_view\ngsl_matrix_uint_const_view_array (const unsigned int * base,\n                                   const size_t n1, \n                                   const size_t n2);\n\n_gsl_matrix_uint_const_view\ngsl_matrix_uint_const_view_array_with_tda (const unsigned int * base, \n                                            const size_t n1, \n                                            const size_t n2,\n                                            const size_t tda);\n\n_gsl_matrix_uint_const_view\ngsl_matrix_uint_const_view_vector (const gsl_vector_uint * v,\n                                    const size_t n1, \n                                    const size_t n2);\n\n_gsl_matrix_uint_const_view\ngsl_matrix_uint_const_view_vector_with_tda (const gsl_vector_uint * v,\n                                             const size_t n1, \n                                             const size_t n2,\n                                             const size_t tda);\n\n/* Operations */\n\nunsigned int   gsl_matrix_uint_get(const gsl_matrix_uint * m, const size_t i, const size_t j);\nvoid    gsl_matrix_uint_set(gsl_matrix_uint * m, const size_t i, const size_t j, const unsigned int x);\n\nunsigned int * gsl_matrix_uint_ptr(gsl_matrix_uint * m, const size_t i, const size_t j);\nconst unsigned int * gsl_matrix_uint_const_ptr(const gsl_matrix_uint * m, const size_t i, const size_t j);\n\nvoid gsl_matrix_uint_set_zero (gsl_matrix_uint * m);\nvoid gsl_matrix_uint_set_identity (gsl_matrix_uint * m);\nvoid gsl_matrix_uint_set_all (gsl_matrix_uint * m, unsigned int x);\n\nint gsl_matrix_uint_fread (FILE * stream, gsl_matrix_uint * m) ;\nint gsl_matrix_uint_fwrite (FILE * stream, const gsl_matrix_uint * m) ;\nint gsl_matrix_uint_fscanf (FILE * stream, gsl_matrix_uint * m);\nint gsl_matrix_uint_fprintf (FILE * stream, const gsl_matrix_uint * m, const char * format);\n \nint gsl_matrix_uint_memcpy(gsl_matrix_uint * dest, const gsl_matrix_uint * src);\nint gsl_matrix_uint_swap(gsl_matrix_uint * m1, gsl_matrix_uint * m2);\n\nint gsl_matrix_uint_swap_rows(gsl_matrix_uint * m, const size_t i, const size_t j);\nint gsl_matrix_uint_swap_columns(gsl_matrix_uint * m, const size_t i, const size_t j);\nint gsl_matrix_uint_swap_rowcol(gsl_matrix_uint * m, const size_t i, const size_t j);\nint gsl_matrix_uint_transpose (gsl_matrix_uint * m);\nint gsl_matrix_uint_transpose_memcpy (gsl_matrix_uint * dest, const gsl_matrix_uint * src);\n\nunsigned int gsl_matrix_uint_max (const gsl_matrix_uint * m);\nunsigned int gsl_matrix_uint_min (const gsl_matrix_uint * m);\nvoid gsl_matrix_uint_minmax (const gsl_matrix_uint * m, unsigned int * min_out, unsigned int * max_out);\n\nvoid gsl_matrix_uint_max_index (const gsl_matrix_uint * m, size_t * imax, size_t *jmax);\nvoid gsl_matrix_uint_min_index (const gsl_matrix_uint * m, size_t * imin, size_t *jmin);\nvoid gsl_matrix_uint_minmax_index (const gsl_matrix_uint * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);\n\nint gsl_matrix_uint_isnull (const gsl_matrix_uint * m);\n\nint gsl_matrix_uint_add (gsl_matrix_uint * a, const gsl_matrix_uint * b);\nint gsl_matrix_uint_sub (gsl_matrix_uint * a, const gsl_matrix_uint * b);\nint gsl_matrix_uint_mul_elements (gsl_matrix_uint * a, const gsl_matrix_uint * b);\nint gsl_matrix_uint_div_elements (gsl_matrix_uint * a, const gsl_matrix_uint * b);\nint gsl_matrix_uint_scale (gsl_matrix_uint * a, const double x);\nint gsl_matrix_uint_add_constant (gsl_matrix_uint * a, const double x);\nint gsl_matrix_uint_add_diagonal (gsl_matrix_uint * a, const double x);\n\n/***********************************************************************/\n/* The functions below are obsolete                                    */\n/***********************************************************************/\nint gsl_matrix_uint_get_row(gsl_vector_uint * v, const gsl_matrix_uint * m, const size_t i);\nint gsl_matrix_uint_get_col(gsl_vector_uint * v, const gsl_matrix_uint * m, const size_t j);\nint gsl_matrix_uint_set_row(gsl_matrix_uint * m, const size_t i, const gsl_vector_uint * v);\nint gsl_matrix_uint_set_col(gsl_matrix_uint * m, const size_t j, const gsl_vector_uint * v);\n\n/* inline functions if you are using GCC */\n\n#ifdef HAVE_INLINE\nextern inline \nunsigned int\ngsl_matrix_uint_get(const gsl_matrix_uint * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_VAL(\"first index out of range\", GSL_EINVAL, 0) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_VAL(\"second index out of range\", GSL_EINVAL, 0) ;\n    }\n#endif\n  return m->data[i * m->tda + j] ;\n} \n\nextern inline \nvoid\ngsl_matrix_uint_set(gsl_matrix_uint * m, const size_t i, const size_t j, const unsigned int x)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_VOID(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_VOID(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  m->data[i * m->tda + j] = x ;\n}\n\nextern inline \nunsigned int *\ngsl_matrix_uint_ptr(gsl_matrix_uint * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  return (unsigned int *) (m->data + (i * m->tda + j)) ;\n} \n\nextern inline \nconst unsigned int *\ngsl_matrix_uint_const_ptr(const gsl_matrix_uint * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  return (const unsigned int *) (m->data + (i * m->tda + j)) ;\n} \n\n#endif\n\n__END_DECLS\n\n#endif /* __GSL_MATRIX_UINT_H__ */\n", "meta": {"hexsha": "a253657227e6e9a9e961681088c0c5d01d550c64", "size": 10904, "ext": "h", "lang": "C", "max_stars_repo_path": "extern/include/gsl/gsl_matrix_uint.h", "max_stars_repo_name": "andrewkern/segSiteHMM", "max_stars_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "extern/include/gsl/gsl_matrix_uint.h", "max_issues_repo_name": "andrewkern/segSiteHMM", "max_issues_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "extern/include/gsl/gsl_matrix_uint.h", "max_forks_repo_name": "andrewkern/segSiteHMM", "max_forks_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3974763407, "max_line_length": 122, "alphanum_fraction": 0.6590242113, "num_tokens": 2626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24508501313237174, "lm_q2_score": 0.02228618789322103, "lm_q1q2_score": 0.005462010652480581}}
{"text": "/*\n  This file is part of p4est.\n  p4est is a C library to manage a collection (a forest) of multiple\n  connected adaptive quadtrees or octrees in parallel.\n\n  Copyright (C) 2010 The University of Texas System\n  Additional copyright (C) 2011 individual authors\n  Written by Carsten Burstedde, Lucas C. Wilcox, and Tobin Isaac\n\n  p4est is free software; you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation; either version 2 of the License, or\n  (at your option) any later version.\n\n  p4est is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with p4est; if not, write to the Free Software Foundation, Inc.,\n  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n*/\n\n#ifndef P4_TO_P8\n#include <p4est_plex.h>\n#include <p4est_extended.h>\n#include <p4est_bits.h>\n#else\n#include <p8est_plex.h>\n#include <p8est_extended.h>\n#include <p8est_bits.h>\n#endif\n\n#ifdef P4EST_WITH_PETSC\n#include <petsc.h>\n#include <petscdmplex.h>\n#include <petscsf.h>\n\nconst char          help[] = \"test creating DMPlex from \" P4EST_STRING \"\\n\";\n\nstatic void\nlocidx_to_PetscInt (sc_array_t * array)\n{\n  sc_array_t         *newarray;\n  size_t              zz, count = array->elem_count;\n  P4EST_ASSERT (array->elem_size == sizeof (p4est_locidx_t));\n\n  if (sizeof (p4est_locidx_t) == sizeof (PetscInt)) {\n    return;\n  }\n\n  newarray = sc_array_new_size (sizeof (PetscInt), array->elem_count);\n  for (zz = 0; zz < count; zz++) {\n    p4est_locidx_t      il = *((p4est_locidx_t *) sc_array_index (array, zz));\n    PetscInt           *ip = (PetscInt *) sc_array_index (newarray, zz);\n\n    *ip = (PetscInt) il;\n  }\n\n  sc_array_reset (array);\n  sc_array_init_size (array, sizeof (PetscInt), count);\n  sc_array_copy (array, newarray);\n  sc_array_destroy (newarray);\n}\n\nstatic void\ncoords_double_to_PetscScalar (sc_array_t * array)\n{\n  sc_array_t         *newarray;\n  size_t              zz, count = array->elem_count;\n  P4EST_ASSERT (array->elem_size == 3 * sizeof (double));\n\n  if (sizeof (double) == sizeof (PetscScalar)) {\n    return;\n  }\n\n  newarray = sc_array_new_size (3 * sizeof (PetscScalar), array->elem_count);\n  for (zz = 0; zz < count; zz++) {\n    double             *id = (double *) sc_array_index (array, zz);\n    PetscScalar        *ip = (PetscScalar *) sc_array_index (newarray, zz);\n\n    ip[0] = (PetscScalar) id[0];\n    ip[1] = (PetscScalar) id[1];\n    ip[2] = (PetscScalar) id[2];\n  }\n\n  sc_array_reset (array);\n  sc_array_init_size (array, 3 * sizeof (PetscScalar), count);\n  sc_array_copy (array, newarray);\n  sc_array_destroy (newarray);\n}\n\nstatic void\nlocidx_pair_to_PetscSFNode (sc_array_t * array)\n{\n  sc_array_t         *newarray;\n  size_t              zz, count = array->elem_count;\n  P4EST_ASSERT (array->elem_size == 2 * sizeof (p4est_locidx_t));\n\n  newarray = sc_array_new_size (sizeof (PetscSFNode), array->elem_count);\n  for (zz = 0; zz < count; zz++) {\n    p4est_locidx_t     *il = (p4est_locidx_t *) sc_array_index (array, zz);\n    PetscSFNode        *ip = (PetscSFNode *) sc_array_index (newarray, zz);\n\n    ip->rank = (PetscInt) il[0];\n    ip->index = (PetscInt) il[1];\n  }\n\n  sc_array_reset (array);\n  sc_array_init_size (array, sizeof (PetscSFNode), count);\n  sc_array_copy (array, newarray);\n  sc_array_destroy (newarray);\n}\n#endif\n\n#ifndef P4_TO_P8\nstatic int          refine_level = 5;\n#else\nstatic int          refine_level = 3;\n#endif\n\nstatic int\nrefine_fn (p4est_t * p4est, p4est_topidx_t which_tree,\n           p4est_quadrant_t * quadrant)\n{\n  int                 cid;\n\n  if (which_tree == 2 || which_tree == 3) {\n    return 0;\n  }\n\n  cid = p4est_quadrant_child_id (quadrant);\n\n  if (cid == P4EST_CHILDREN - 1 ||\n      (quadrant->x >= P4EST_LAST_OFFSET (P4EST_MAXLEVEL - 2) &&\n       quadrant->y >= P4EST_LAST_OFFSET (P4EST_MAXLEVEL - 2)\n#ifdef P4_TO_P8\n       && quadrant->z >= P4EST_LAST_OFFSET (P4EST_MAXLEVEL - 2)\n#endif\n      )) {\n    return 1;\n  }\n  if ((int) quadrant->level >= (refine_level - (int) (which_tree % 3))) {\n    return 0;\n  }\n  if (quadrant->level == 1 && cid == 2) {\n    return 1;\n  }\n  if (quadrant->x == P4EST_QUADRANT_LEN (2) &&\n      quadrant->y == P4EST_LAST_OFFSET (2)) {\n    return 1;\n  }\n  if (quadrant->y >= P4EST_QUADRANT_LEN (2)) {\n    return 0;\n  }\n\n  return 1;\n}\n\nstatic int\nrefine_tree_one_fn (p4est_t * p4est, p4est_topidx_t which_tree,\n                    p4est_quadrant_t * quadrant)\n{\n  return ! !which_tree;\n}\n\nstatic int\ntest_forest (int argc, char **argv, p4est_t * p4est, int overlap)\n{\n  sc_MPI_Comm         mpicomm;\n  int                 mpiret;\n  int                 mpisize, mpirank;\n  sc_array_t         *points_per_dim, *cone_sizes, *cones,\n    *cone_orientations, *coords,\n    *children, *parents, *childids, *leaves, *remotes;\n  p4est_locidx_t      first_local_quad = -1;\n\n  /* initialize MPI */\n  mpicomm = p4est->mpicomm;\n  mpiret = sc_MPI_Comm_size (mpicomm, &mpisize);\n  SC_CHECK_MPI (mpiret);\n  mpiret = sc_MPI_Comm_rank (mpicomm, &mpirank);\n  SC_CHECK_MPI (mpiret);\n\n  points_per_dim = sc_array_new (sizeof (p4est_locidx_t));\n  cone_sizes = sc_array_new (sizeof (p4est_locidx_t));\n  cones = sc_array_new (sizeof (p4est_locidx_t));\n  cone_orientations = sc_array_new (sizeof (p4est_locidx_t));\n  coords = sc_array_new (3 * sizeof (double));\n  children = sc_array_new (sizeof (p4est_locidx_t));\n  parents = sc_array_new (sizeof (p4est_locidx_t));\n  childids = sc_array_new (sizeof (p4est_locidx_t));\n  leaves = sc_array_new (sizeof (p4est_locidx_t));\n  remotes = sc_array_new (2 * sizeof (p4est_locidx_t));\n\n  p4est_get_plex_data (p4est, P4EST_CONNECT_FULL, (mpisize > 1) ? overlap : 0,\n                       &first_local_quad, points_per_dim, cone_sizes, cones,\n                       cone_orientations, coords, children, parents, childids,\n                       leaves, remotes);\n\n#ifdef P4EST_WITH_PETSC\n  {\n    PetscErrorCode      ierr;\n    DM                  plex, refTree;\n    PetscInt            pStart, pEnd;\n    PetscSection        parentSection;\n    PetscSF             pointSF;\n    size_t              zz, count;\n\n    locidx_to_PetscInt (points_per_dim);\n    locidx_to_PetscInt (cone_sizes);\n    locidx_to_PetscInt (cones);\n    locidx_to_PetscInt (cone_orientations);\n    coords_double_to_PetscScalar (coords);\n    locidx_to_PetscInt (children);\n    locidx_to_PetscInt (parents);\n    locidx_to_PetscInt (childids);\n    locidx_to_PetscInt (leaves);\n    locidx_pair_to_PetscSFNode (remotes);\n\n    P4EST_GLOBAL_PRODUCTION (\"Begin PETSc routines\\n\");\n    ierr = PetscInitialize (&argc, &argv, 0, help);\n    CHKERRQ (ierr);\n\n    ierr = DMPlexCreate (mpicomm, &plex);\n    CHKERRQ (ierr);\n    ierr = DMSetDimension (plex, P4EST_DIM);\n    CHKERRQ (ierr);\n    ierr = DMSetCoordinateDim (plex, 3);\n    CHKERRQ (ierr);\n    ierr = DMPlexCreateFromDAG (plex, P4EST_DIM,\n                                (PetscInt *) points_per_dim->array,\n                                (PetscInt *) cone_sizes->array,\n                                (PetscInt *) cones->array,\n                                (PetscInt *) cone_orientations->array,\n                                (PetscScalar *) coords->array);\n    CHKERRQ (ierr);\n    ierr = PetscSFCreate (mpicomm, &pointSF);\n    CHKERRQ (ierr);\n    ierr =\n      DMPlexCreateDefaultReferenceTree (mpicomm, P4EST_DIM, PETSC_FALSE,\n                                        &refTree);\n    CHKERRQ (ierr);\n    ierr = DMPlexSetReferenceTree (plex, refTree);\n    CHKERRQ (ierr);\n    ierr = DMDestroy (&refTree);\n    CHKERRQ (ierr);\n    ierr = PetscSectionCreate (mpicomm, &parentSection);\n    CHKERRQ (ierr);\n    ierr = DMPlexGetChart (plex, &pStart, &pEnd);\n    CHKERRQ (ierr);\n    ierr = PetscSectionSetChart (parentSection, pStart, pEnd);\n    CHKERRQ (ierr);\n    count = children->elem_count;\n    for (zz = 0; zz < count; zz++) {\n      PetscInt            child =\n        *((PetscInt *) sc_array_index (children, zz));\n\n      ierr = PetscSectionSetDof (parentSection, child, 1);\n      CHKERRQ (ierr);\n    }\n    ierr = PetscSectionSetUp (parentSection);\n    CHKERRQ (ierr);\n    ierr =\n      DMPlexSetTree (plex, parentSection, (PetscInt *) parents->array,\n                     (PetscInt *) childids->array);\n    CHKERRQ (ierr);\n    ierr = PetscSectionDestroy (&parentSection);\n    CHKERRQ (ierr);\n    ierr =\n      PetscSFSetGraph (pointSF, pEnd - pStart, (PetscInt) leaves->elem_count,\n                       (PetscInt *) leaves->array, PETSC_COPY_VALUES,\n                       (PetscSFNode *) remotes->array, PETSC_COPY_VALUES);\n    CHKERRQ (ierr);\n    ierr = DMSetPointSF (plex, pointSF);\n    CHKERRQ (ierr);\n    ierr = PetscSFDestroy (&pointSF);\n    CHKERRQ (ierr);\n    ierr = DMViewFromOptions (plex, NULL, \"-dm_view\");\n    CHKERRQ (ierr);\n    /* TODO: test with rigid body modes as in plex ex3 */\n    ierr = DMDestroy (&plex);\n    CHKERRQ (ierr);\n\n    ierr = PetscFinalize ();\n    P4EST_GLOBAL_PRODUCTION (\"End   PETSc routines\\n\");\n  }\n#endif\n\n  sc_array_destroy (points_per_dim);\n  sc_array_destroy (cone_sizes);\n  sc_array_destroy (cones);\n  sc_array_destroy (cone_orientations);\n  sc_array_destroy (coords);\n  sc_array_destroy (children);\n  sc_array_destroy (parents);\n  sc_array_destroy (childids);\n  sc_array_destroy (leaves);\n  sc_array_destroy (remotes);\n\n  return 0;\n}\n\nstatic int\ntest_big (int argc, char **argv)\n{\n  sc_MPI_Comm         mpicomm;\n  int                 mpiret;\n  p4est_t            *p4est;\n  p4est_connectivity_t *conn;\n\n  /* initialize MPI */\n  mpicomm = sc_MPI_COMM_WORLD;\n\n#ifndef P4_TO_P8\n  conn = p4est_connectivity_new_moebius ();\n#else\n  conn = p8est_connectivity_new_rotcubes ();\n#endif\n  p4est = p4est_new_ext (mpicomm, conn, 0, 1, 1, 0, NULL, NULL);\n  p4est_refine (p4est, 1, refine_fn, NULL);\n  p4est_balance (p4est, P4EST_CONNECT_FULL, NULL);\n  p4est_partition (p4est, 0, NULL);\n\n  mpiret = test_forest (argc, argv, p4est, 2);\n  if (mpiret) {\n    return mpiret;\n  }\n\n  p4est_destroy (p4est);\n  p4est_connectivity_destroy (conn);\n\n  return 0;\n}\n\nstatic int\ntest_small (int argc, char **argv)\n{\n  sc_MPI_Comm         mpicomm;\n  int                 mpiret;\n  p4est_t            *p4est;\n  p4est_connectivity_t *conn;\n\n  /* initialize MPI */\n  mpicomm = sc_MPI_COMM_WORLD;\n\n#ifndef P4_TO_P8\n  conn = p4est_connectivity_new_brick (2, 1, 0, 0);\n#else\n  conn = p8est_connectivity_new_brick (2, 1, 1, 0, 0, 0);\n#endif\n  p4est = p4est_new (mpicomm, conn, 0, NULL, NULL);\n  p4est_refine (p4est, 0, refine_tree_one_fn, NULL);\n\n  mpiret = test_forest (argc, argv, p4est, 0);\n  if (mpiret) {\n    return mpiret;\n  }\n\n  p4est_partition (p4est, 0, NULL);\n\n  mpiret = test_forest (argc, argv, p4est, 0);\n  if (mpiret) {\n    return mpiret;\n  }\n\n  p4est_destroy (p4est);\n  p4est_connectivity_destroy (conn);\n\n  return 0;\n}\n\nint\nmain (int argc, char **argv)\n{\n  sc_MPI_Comm         mpicomm;\n  int                 mpiret;\n\n  /* initialize MPI */\n  mpiret = sc_MPI_Init (&argc, &argv);\n  SC_CHECK_MPI (mpiret);\n  mpicomm = sc_MPI_COMM_WORLD;\n\n  sc_init (mpicomm, 1, 1, NULL, SC_LP_DEFAULT);\n  p4est_init (NULL, SC_LP_DEFAULT);\n\n  mpiret = test_small (argc, argv);\n  if (mpiret) {\n    return mpiret;\n  }\n  mpiret = test_big (argc, argv);\n  if (mpiret) {\n    return mpiret;\n  }\n\n  sc_finalize ();\n\n  mpiret = sc_MPI_Finalize ();\n  SC_CHECK_MPI (mpiret);\n\n  return 0;\n}\n", "meta": {"hexsha": "8ae01ba7885464f2756f49e0a758835032516230", "size": 11527, "ext": "c", "lang": "C", "max_stars_repo_path": "sites/workstation/gcc/p4est/test/test_plex2.c", "max_stars_repo_name": "jmark/p4wrap", "max_stars_repo_head_hexsha": "6d237ab8fbe03c8ca985778ac1f65678ecbcccb3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-06-02T12:26:35.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-27T14:29:52.000Z", "max_issues_repo_path": "sites/workstation/gcc/p4est/test/test_plex2.c", "max_issues_repo_name": "jmark/p4wrap", "max_issues_repo_head_hexsha": "6d237ab8fbe03c8ca985778ac1f65678ecbcccb3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sites/workstation/gcc/p4est/test/test_plex2.c", "max_forks_repo_name": "jmark/p4wrap", "max_forks_repo_head_hexsha": "6d237ab8fbe03c8ca985778ac1f65678ecbcccb3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5321782178, "max_line_length": 78, "alphanum_fraction": 0.6460484081, "num_tokens": 3527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20946968133032523, "lm_q2_score": 0.025957355314023947, "lm_q1q2_score": 0.005437278945806621}}
{"text": "/* bst/gsl_bst_avl.h\n * \n * Copyright (C) 2018 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_BST_AVL_H__\n#define __GSL_BST_AVL_H__\n\n#include <gsl/gsl_math.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\n#ifndef GSL_BST_AVL_MAX_HEIGHT\n#define GSL_BST_AVL_MAX_HEIGHT 32\n#endif\n\n/* AVL node */\nstruct gsl_bst_avl_node\n{\n  struct gsl_bst_avl_node *avl_link[2]; /* subtrees */\n  void *avl_data;                       /* pointer to data */\n  signed char avl_balance;              /* balance factor */\n};\n\n/* tree data structure */\ntypedef struct\n{\n  struct gsl_bst_avl_node *avl_root;          /* tree's root */\n  gsl_bst_cmp_function *avl_compare;          /* comparison function */\n  void *avl_param;                            /* extra argument to |avl_compare| */\n  const gsl_bst_allocator *avl_alloc;         /* memory allocator */\n  size_t avl_count;                           /* number of items in tree */\n  unsigned long avl_generation;               /* generation number */\n} gsl_bst_avl_table;\n\n/* AVL traverser structure */\ntypedef struct\n{\n  const gsl_bst_avl_table *avl_table;                         /* tree being traversed */\n  struct gsl_bst_avl_node *avl_node;                          /* current node in tree */\n  struct gsl_bst_avl_node *avl_stack[GSL_BST_AVL_MAX_HEIGHT]; /* all the nodes above |avl_node| */\n  size_t avl_height;                                          /* number of nodes in |avl_parent| */\n  unsigned long avl_generation;                               /* generation number */\n} gsl_bst_avl_traverser;\n\n__END_DECLS\n\n#endif /* __GSL_BST_AVL_H__ */\n", "meta": {"hexsha": "6560777ce27a479a16e81f1842ea1e9d67cf318d", "size": 2461, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gsl/gsl_bst_avl.h", "max_stars_repo_name": "vinej/sml", "max_stars_repo_head_hexsha": "115c007926ca80d51a37cdf887b5252338d8bc8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/gsl/gsl_bst_avl.h", "max_issues_repo_name": "vinej/sml", "max_issues_repo_head_hexsha": "115c007926ca80d51a37cdf887b5252338d8bc8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gsl/gsl_bst_avl.h", "max_forks_repo_name": "vinej/sml", "max_forks_repo_head_hexsha": "115c007926ca80d51a37cdf887b5252338d8bc8d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7123287671, "max_line_length": 99, "alphanum_fraction": 0.6663957741, "num_tokens": 594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1968262036430985, "lm_q2_score": 0.02758528032814983, "lm_q1q2_score": 0.0054295060034203774}}
{"text": "#pragma once\n\n#include \"file_descriptor.h\"\n#include <filesystem>\n#include <gsl/span>\n#include <random>\n\nnamespace dogbox\n{\n    inline void create_random_file(std::filesystem::path const &file, uint64_t const size)\n    {\n        file_descriptor const created = create_file(file).value();\n        file_descriptor const random = open_file_for_reading(\"/dev/urandom\").value();\n        std::array<std::byte, 0x10000> buffer;\n        uint64_t written = 0;\n        while (written < size)\n        {\n            size_t const reading = static_cast<size_t>(std::min<uint64_t>(buffer.size(), (size - written)));\n            ssize_t const read_result = read(random.handle, buffer.data(), reading);\n            if (read_result < 0)\n            {\n                TO_DO();\n            }\n            ssize_t const write_result = write(created.handle, buffer.data(), reading);\n            if (write_result < 0)\n            {\n                TO_DO();\n            }\n            written += reading;\n        }\n    }\n}\n", "meta": {"hexsha": "78d1e465ede97e6cf2d2624a787d4679e36e3c1e", "size": 996, "ext": "h", "lang": "C", "max_stars_repo_path": "common/create_random_file.h", "max_stars_repo_name": "TyRoXx/dogbox", "max_stars_repo_head_hexsha": "af9c7631f6f5a22a73fbd4a497a84ed75183c7d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "common/create_random_file.h", "max_issues_repo_name": "TyRoXx/dogbox", "max_issues_repo_head_hexsha": "af9c7631f6f5a22a73fbd4a497a84ed75183c7d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-09-02T20:36:02.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-02T20:36:02.000Z", "max_forks_repo_path": "common/create_random_file.h", "max_forks_repo_name": "TyRoXx/dogbox", "max_forks_repo_head_hexsha": "af9c7631f6f5a22a73fbd4a497a84ed75183c7d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-08-29T22:01:48.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-29T22:01:48.000Z", "avg_line_length": 30.1818181818, "max_line_length": 108, "alphanum_fraction": 0.5722891566, "num_tokens": 217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22541661583507672, "lm_q2_score": 0.024053554774625185, "lm_q1q2_score": 0.005422070916099661}}
{"text": "#ifndef __mcas_SERVER_TASK_KEY_FIND_H__\n#define __mcas_SERVER_TASK_KEY_FIND_H__\n\n#include <common/logging.h>\n#include <gsl/pointers>\n#include <unistd.h>\n#include <string>\n\n#include \"task.h\"\n\nnamespace mcas\n{\n/**\n * Key search task.  We limit the number of hops we search so as to bound\n * the worst case execution time.\n *\n */\nclass Key_find_task : public Shard_task,\n                      private common::log_source\n{\n  static constexpr unsigned MAX_COMPARES_PER_WORK = 5;\n\n public:\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Weffc++\"  // uninitialized _expr, _out_key, _type\n  Key_find_task(const std::string& expression,\n                const offset_t offset,\n                Connection_handler* handler,\n                gsl::not_null<component::IKVIndex*> index,\n                const unsigned debug_level)\n      : Shard_task(handler),\n        log_source(debug_level),\n        _offset(offset),\n        _index(index)\n  {\n    using namespace component;\n    _index->add_ref();\n\n    CPLOG(1, \"offset=%lu\", offset);\n    CPLOG(1,\"expr: (%s)\", expression.c_str());\n\n    if (expression == \"next:\") {\n      _type = IKVIndex::FIND_TYPE_NEXT;\n      _expr = expression.substr(5);\n    }\n    else if (expression.substr(0, 6) == \"regex:\") {\n      _type = IKVIndex::FIND_TYPE_REGEX;\n      _expr = expression.substr(6);\n    }\n    else if (expression.substr(0, 6) == \"exact:\") {\n      _type = IKVIndex::FIND_TYPE_EXACT;\n      _expr = expression.substr(6);\n    }\n    else if (expression.substr(0, 7) == \"prefix:\") {\n      _type = IKVIndex::FIND_TYPE_PREFIX;\n      _expr = expression.substr(7);\n    }\n    else\n      throw Logic_exception(\"unhandled expression\");\n\n  }\n#pragma GCC diagnostic pop\n\n  Key_find_task(const Key_find_task&) = delete;\n  Key_find_task& operator=(const Key_find_task&) = delete;\n\n  status_t do_work() override\n  {\n    using namespace component;\n\n    status_t hr;\n    try {\n      hr = _index->find(_expr, _offset, _type, _offset, _out_key, MAX_COMPARES_PER_WORK);\n\n      if (hr == E_MAX_REACHED) {\n        _offset++;\n        return component::IKVStore::S_MORE;\n      }\n      else if (hr == S_OK) {\n        CPLOG(2, \"matched: (%s)\", _out_key.c_str());\n        return S_OK;\n      }\n      else {\n        _out_key.clear();\n        return hr;\n      }\n    }\n    catch (...) {\n      return E_FAIL;\n    }\n\n    throw Logic_exception(\"unexpected code path (hr=%d)\", hr);\n  }\n\n  const void* get_result() const override { return _out_key.data(); }\n\n  size_t get_result_length() const override { return _out_key.length(); }\n\n  offset_t matched_position() const override { return _offset; }\n\n private:\n  std::string                             _expr;\n  std::string                             _out_key;\n  component::IKVIndex::find_t             _type;\n  offset_t                                _offset;\n  component::Itf_ref<component::IKVIndex> _index;\n};\n\n}  // namespace mcas\n#endif  // __mcas_SERVER_TASK_KEY_FIND_H__\n", "meta": {"hexsha": "55ef29321f1fdbcc1db6b7da7929452fea8fa368", "size": 2932, "ext": "h", "lang": "C", "max_stars_repo_path": "src/server/mcas/src/task_key_find.h", "max_stars_repo_name": "moshik1/mcas", "max_stars_repo_head_hexsha": "a6af06bc278993fb3ffe780f230d2396b2287c26", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 60.0, "max_stars_repo_stars_event_min_datetime": "2020-04-28T08:15:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T10:35:15.000Z", "max_issues_repo_path": "src/server/mcas/src/task_key_find.h", "max_issues_repo_name": "moshik1/mcas", "max_issues_repo_head_hexsha": "a6af06bc278993fb3ffe780f230d2396b2287c26", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 66.0, "max_issues_repo_issues_event_min_datetime": "2020-09-03T23:40:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T20:34:52.000Z", "max_forks_repo_path": "src/server/mcas/src/task_key_find.h", "max_forks_repo_name": "moshik1/mcas", "max_forks_repo_head_hexsha": "a6af06bc278993fb3ffe780f230d2396b2287c26", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2019-11-02T06:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T01:56:42.000Z", "avg_line_length": 26.4144144144, "max_line_length": 89, "alphanum_fraction": 0.6159618008, "num_tokens": 734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15610490529754448, "lm_q2_score": 0.03461883622466337, "lm_q1q2_score": 0.005404170150362278}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <iniparser.h>\n#include \"parmt_utils.h\"\n#include \"tdsearch_greens.h\"\n#include \"tdsearch_commands.h\"\n#ifdef TDSEARCH_USE_INTEL\n#include <mkl_blas.h>\n#else\n#include <cblas.h>\n#endif\n#include \"tdsearch_struct.h\"\n#include \"tdsearch_hudson.h\"\n#include \"ispl/process.h\"\n#include \"iscl/array/array.h\"\n#include \"iscl/fft/fft.h\"\n#include \"iscl/memory/memory.h\"\n#include \"iscl/os/os.h\"\n\nstatic int getPrimaryArrival(const struct sacHeader_struct hdr,\n                             double *time, char phaseName[8]);\n\n/*!\n * @brief Reads the generic Green's functions pre-processing files from\n *        the ini file.\n *\n * @param[in] iniFile    Name of ini file.\n * @param[in] nobs       Number of observations.\n *\n * @param[in,out] grns   On input contains the number of observations.\n *                       On exit contains the generic Green's functions\n *                       processing commands for the observations.\n *\n * @result 0 indicates success.\n *\n * @author Ben Baker, ISTI\n *\n * @ingroup tdsearch_greens \n *\n * @bug Add an option to read a processing list file.\n *\n */\nint tdsearch_greens_setPreprocessingCommandsFromIniFile(\n    const char *iniFile,\n    const int nobs,  \n    struct tdSearchGreens_struct *grns)\n{\n    dictionary *ini;\n    char **cmds;\n    const char *s;\n    char varname[128];\n    size_t lenos;\n    int ierr, k, ncmds, ncmdsWork;\n    ierr = 0;\n    grns->nobs = nobs;\n    if (grns->nobs < 1){return 0;}\n    if (!os_path_isfile(iniFile))\n    {\n        fprintf(stderr, \"%s: Error ini file %s doesn't exist\\n\",\n                __func__, iniFile);\n        return -1;\n    }\n    ini = iniparser_load(iniFile);\n    ncmds = iniparser_getint(ini, \"tdSearch:greens:nCommands\\0\", 0);\n    grns->cmds = (struct tdSearchDataProcessingCommands_struct *)\n                 calloc((size_t) nobs, //ncmds,\n                        sizeof(struct tdSearchDataProcessingCommands_struct));\n    //if (!luseProcessingList)\n    {\n        if (ncmds > 0)\n        {\n            ncmdsWork = ncmds;\n            ncmds = 0;\n            cmds = (char **) calloc((size_t) ncmdsWork, sizeof(char *));\n            for (k=0; k<ncmdsWork; k++)\n            {\n                memset(varname, 0, 128*sizeof(char));\n                sprintf(varname, \"tdSearch:greens:command_%d\", k+1);\n                s = iniparser_getstring(ini, varname, NULL);\n                if (s == NULL){continue;}\n                lenos = strlen(s);\n                cmds[ncmds] = (char *) calloc(lenos+1, sizeof(char));\n                strcpy(cmds[ncmds], s);\n                //printf(\"%s\\n\", cmds[ncmds]);\n                ncmds = ncmds + 1;\n            }\n            // Attach these to the data processing structure\n            for (k=0; k<grns->nobs; k++)\n            {\n                ierr = tdsearch_greens_attachCommandsToGreens(\n                           k, ncmds, (const char **) cmds, grns);\n            }\n            // Free space\n            for (k=0; k<ncmdsWork; k++)\n            {\n                if (cmds[k] != NULL){free(cmds[k]);}\n            }\n            free(cmds);\n        }\n    }\n    iniparser_freedict(ini);\n    return ierr;\n}\n//============================================================================//\n/*!\n * @brief Attaches the Green's functions processing commands to the Green's\n *        structure.\n * \n * @param[in] iobs      Observation number to attach commands to.\n * @param[in] ncmds     Number of commands.\n * @param[in] cmds      Pre-processing commands for the Green's functions\n *                      corresponding to the iobs'th observation [ncmds].\n *\n * @param[in,out] grns  On input has the Green's functions (depths and t*'s)\n *                      corresponding to the observations.\n *                      On output contains the pre-processing commands\n *                      for Green's functions corresponding to the\n *                      observations.\n *\n * @result 0 indicates success.\n *\n * @ingroup tdsearch_greens\n *\n * @author Ben Baker, ISTI\n *\n */\nint tdsearch_greens_attachCommandsToGreens(const int iobs, const int ncmds,\n                                           const char **cmds,\n                                           struct tdSearchGreens_struct *grns)\n{\n    int i;\n    size_t lenos;\n    // Make sure iobs is in bounds \n    if (iobs < 0 || iobs >= grns->nobs)\n    {    \n        fprintf(stderr, \"%s: Error iobs=%d is out of bounds [0,%d]\\n\",\n                __func__, iobs, grns->nobs);\n        return -1;      \n    }        \n    // Try to handle space allocation if not already done\n    if (grns->cmds == NULL && grns->nobs > 0)\n    {    \n        grns->cmds = (struct tdSearchDataProcessingCommands_struct *)\n                     calloc((size_t) grns->nobs,\n                        sizeof(struct tdSearchDataProcessingCommands_struct));\n    }    \n    if (grns->cmds == NULL)\n    {    \n        fprintf(stderr, \"%s: Error grns->cmds is NULL\\n\", __func__);\n        return -1;\n    }\n    if (ncmds == 0){return 0;}\n    grns->cmds[iobs].ncmds = ncmds;\n    grns->cmds[iobs].cmds = (char **) calloc((size_t) ncmds, sizeof(char *));\n    if (cmds == NULL){printf(\"problem 1\\n\");}\n    for (i=0; i<ncmds; i++)\n    {\n        if (cmds[i] == NULL){printf(\"problem 2\\n\");}\n        lenos = strlen(cmds[i]);\n        grns->cmds[iobs].cmds[i] = (char *) calloc(lenos+1, sizeof(char));\n        strcpy(grns->cmds[iobs].cmds[i], cmds[i]);\n    }\n    return 0;\n}\n//============================================================================//\n/*!\n * @brief Convenience function which returns the index of the Green's\n *        function on the Green's function structure.\n *\n * @param[in] GMT_TERM    Name of the desired Green's function:\n *                        (G11_TERM, G22_TERM, ..., G23_TERM).\n * @param[in] iobs        Desired observation number (C numbering).\n * @param[in] itstar      Desired t* (C numbering).\n * @param[in] idepth      Desired depth (C numbering).\n * @param[in] grns        Contains the number of observations, depths, and t*'s\n *                        on the Green's functions structure.\n *\n * @result Negative indicates failure.  Otherwise, this is the index in \n *         grns.grns corresponding to the desired \n *         (iobs, idepth, itstar, G??_GRNS) coordinate.\n *\n * @ingroup tdsearch_greens\n *\n * @author Ben Baker, ISTI\n *\n */\nint tdsearch_greens_getGreensFunctionIndex(\n    const enum prepmtGreens_enum GMT_TERM,\n    const int iobs, const int itstar, const int idepth,\n    const struct tdSearchGreens_struct grns)\n{\n    int igx, indx;\n    indx =-1;\n    igx = (int) GMT_TERM - 1;\n    if (igx < 0 || igx > 5)\n    {\n        fprintf(stderr, \"%s: Can't classify Green's functions index\\n\",\n                __func__);\n        return indx;\n    }\n    indx = iobs*(6*grns.ntstar*grns.ndepth)\n         + idepth*(6*grns.ntstar)\n         + itstar*6\n         + igx;\n    if (indx >= grns.ngrns)\n    {\n        fprintf(stdout, \"%s: indx out of bounds - segfault is coming\\n\",\n                __func__);\n        return -1;\n    }\n    return indx;\n}\n//============================================================================//\n/*!\n * @brief Convenience function for extracting the: \n *        \\$ \\{ G_{xx}, G_{yy}, G_{zz}, G_{xy}, G_{xz}, G_{yz} \\} \\$\n *        Green's functions indices for the observation, t*, and depth.\n *\n * @param[in] iobs      Observation number.\n * @param[in] itstar    t* index.  This is C numbered.\n * @param[in] idepth    Depth index.  This is C numbered.\n * @param[in] grns      Contains the Green's functions.\n * @param[out] indices  Contains the Green's functions indices defining\n *                      the indices that return the:\n *                       \\$ \\{ G_{xx}, G_{yy}, G_{zz}, \n *                             G_{xy}, G_{xz}, G_{yz} \\} \\$\n *                      for this observation, t*, and depth. \n *\n * @result 0 indicates success.\n *\n * @ingroup tdsearch_greens\n *\n * @author Ben Baker, ISTI\n *\n */\nint tdsearch_greens_getGreensFunctionsIndices(\n    const int iobs, const int itstar, const int idepth,\n    const struct tdSearchGreens_struct grns, int indices[6])\n{\n    int i, ierr;\n    const enum prepmtGreens_enum mtTerm[6] = \n       {G11_GRNS, G22_GRNS, G33_GRNS, G12_GRNS, G13_GRNS, G23_GRNS};\n    ierr = 0;\n    for (i=0; i<6; i++)\n    {\n        indices[i] = tdsearch_greens_getGreensFunctionIndex(mtTerm[i],\n                                                          iobs, itstar, idepth,\n                                                          grns); \n        if (indices[i] < 0){ierr = ierr + 1;}\n    } \n    return ierr;\n}\n//============================================================================//\n/*!\n * @brief Releases memory on the Greens functions structure.\n *\n * @param[out] grns   On exit all memory has been freed and variables set to\n *                    0 or NULL.\n *\n * @result 0 indicates success.\n *\n * @ingroup tdsearch_greens\n *\n * @author Ben Baker, ISTI\n *\n */\nint tdsearch_greens_free(struct tdSearchGreens_struct *grns)\n{\n    int i, k;\n    if (grns->grns != NULL && grns->ngrns > 0)\n    {\n        for (k=0; k<grns->ngrns; k++)\n        {\n            sacio_free(&grns->grns[k]);\n        }\n        free(grns->grns);\n    }\n    if (grns->cmds != NULL)\n    {\n        for (k=0; k<grns->nobs; k++)\n        {\n            if (grns->cmds[k].cmds != NULL)\n            {\n                for (i=0; i<grns->cmds[k].ncmds; i++)\n                {\n                    if (grns->cmds[k].cmds[i] != NULL)\n                    {\n                        free(grns->cmds[k].cmds[i]);\n                        grns->cmds[k].cmds[i] = NULL;\n                    }\n                }\n                free(grns->cmds[k].cmds);\n                grns->cmds[k].cmds = NULL;\n            }\n        }\n        free(grns->cmds);\n        grns->cmds = NULL;\n    }\n    if (grns->cmdsGrns != NULL)\n    {\n        for (k=0; k<grns->ngrns; k++)\n        {\n            if (grns->cmdsGrns[k].cmds != NULL)\n            {\n                for (i=0; i<grns->cmdsGrns[k].ncmds; i++)\n                {\n                    if (grns->cmdsGrns[k].cmds != NULL)\n                    {\n                        free(grns->cmdsGrns[k].cmds[i]);\n                        grns->cmdsGrns[k].cmds[i] = NULL;\n                    }\n                }\n                free(grns->cmdsGrns[k].cmds);\n                grns->cmdsGrns[k].cmds = NULL;\n             }\n        } \n        free(grns->cmdsGrns);\n        grns->cmdsGrns = NULL;\n    }\n    memset(grns, 0, sizeof(struct tdSearchGreens_struct));\n    return 0;\n}\n//============================================================================//\n/*!\n * @brief Converts the fundamental faults Green's functions to Green's\n *        functions that can be used by tdsearch.\n *\n * @param[in] data    tdSearch data structure.\n * @param[in] ffGrns  fundamental fault Green's functions for every t* and\n *                    depth in the grid search for each observation. \n *\n * @param[out] grns   Contains the Green's functions that can be applied to\n *                    a moment tensor to produce a synthetic for every t*\n *                    and depth in the grid search for each observation.\n *\n * @result 0 indicates success.\n *\n * @ingroup tdsearch_greens\n *\n * @author Ben Baker, ISTI\n *\n */\nint tdsearch_greens_ffGreensToGreens(const struct tdSearchData_struct data,\n                                     const struct tdSearchHudson_struct ffGrns,\n                                     struct tdSearchGreens_struct *grns)\n{\n    char knetwk[8], kstnm[8], kcmpnm[8], khole[8], phaseName[8],\n         phaseNameGrns[8];\n    double az, baz, cmpaz, cmpinc, cmpincSEED, dt0, epoch, epochNew,\n           evla, evlo, o, pick, pickTime, pickTimeGrns, stel, stla, stlo;\n    int i, icomp, id, ierr, idx, indx, iobs, it, kndx, l, npts;\n    const char *kcmpnms[6] = {\"GXX\\0\", \"GYY\\0\", \"GZZ\\0\",\n                              \"GXY\\0\", \"GXZ\\0\", \"GYZ\\0\"};\n    const double xmom = 1.0;     // no confusing `relative' magnitudes \n    const double xcps = 1.e-20;  // convert dyne-cm mt to output cm\n    const double cm2m = 1.e-2;   // cm to meters\n    const double dcm2nm = 1.e+7; // magnitudes intended to be specified in\n                                 // Dyne-cm but I work in N-m\n    // Given a M0 in Newton-meters get a seismogram in meters\n    const double xscal = xmom*xcps*cm2m*dcm2nm;\n    const int nTimeVars = 11; \n    const enum sacHeader_enum pickVars[11]\n       = {SAC_FLOAT_A,\n          SAC_FLOAT_T0, SAC_FLOAT_T1, SAC_FLOAT_T2, SAC_FLOAT_T3,\n          SAC_FLOAT_T4, SAC_FLOAT_T5, SAC_FLOAT_T6, SAC_FLOAT_T7,\n          SAC_FLOAT_T8, SAC_FLOAT_T9};\n    //memset(grns, 0, sizeof(struct tdSearchGreens_struct));\n    grns->ntstar = ffGrns.ntstar;\n    grns->ndepth = ffGrns.ndepth;\n    grns->nobs = data.nobs;\n    grns->ngrns = 6*grns->ntstar*grns->ndepth*grns->nobs;\n    if (grns->ngrns < 1)\n    {\n        fprintf(stderr, \"%s: Error grns is empty\\n\", __func__);\n        return -1;\n    }\n    grns->grns = (struct sacData_struct *)\n                 calloc((size_t) grns->ngrns, sizeof(struct sacData_struct));\n    for (iobs=0; iobs<data.nobs; iobs++)\n    {\n        ierr = 0;\n        ierr += sacio_getFloatHeader(SAC_FLOAT_AZ,\n                                     data.obs[iobs].header, &az);\n        ierr += sacio_getFloatHeader(SAC_FLOAT_BAZ,\n                                     data.obs[iobs].header, &baz);\n        ierr += sacio_getFloatHeader(SAC_FLOAT_CMPINC,\n                                     data.obs[iobs].header, &cmpinc);\n        ierr += sacio_getFloatHeader(SAC_FLOAT_CMPAZ,\n                                     data.obs[iobs].header, &cmpaz);\n        ierr += sacio_getFloatHeader(SAC_FLOAT_EVLA,\n                                     data.obs[iobs].header, &evla);\n        ierr += sacio_getFloatHeader(SAC_FLOAT_EVLO,\n                                     data.obs[iobs].header, &evlo);\n        ierr += sacio_getFloatHeader(SAC_FLOAT_STLA,\n                                     data.obs[iobs].header, &stla);\n        ierr += sacio_getFloatHeader(SAC_FLOAT_STLO,\n                                     data.obs[iobs].header, &stlo);\n        ierr += sacio_getFloatHeader(SAC_FLOAT_DELTA,\n                                     data.obs[iobs].header, &dt0);\n        ierr += sacio_getCharacterHeader(SAC_CHAR_KNETWK,\n                                         data.obs[iobs].header, knetwk);\n        ierr += sacio_getCharacterHeader(SAC_CHAR_KSTNM,\n                                         data.obs[iobs].header, kstnm);\n        ierr += sacio_getCharacterHeader(SAC_CHAR_KCMPNM,\n                                         data.obs[iobs].header, kcmpnm);\n        // this one isn't critical\n        sacio_getFloatHeader(SAC_FLOAT_STEL,\n                             data.obs[iobs].header, &stel);\n        if (ierr != 0)\n        {\n            fprintf(stderr, \"%s: Error reading header variables\\n\", __func__);\n            break;\n        }\n        // Station location code is not terribly important\n        sacio_getCharacterHeader(SAC_CHAR_KHOLE, data.obs[iobs].header, khole);\n        cmpincSEED = cmpinc - 90.0; // SAC to SEED convention\n        // Get the primary arrival\n        ierr = sacio_getEpochalStartTime(data.obs[iobs].header, &epoch);\n        if (ierr != 0)\n        {\n            fprintf(stderr, \"%s: Error getting start time\\n\", __func__);\n            break;\n        }\n        ierr += getPrimaryArrival(data.obs[iobs].header, &pickTime, phaseName);\n        if (ierr != 0)\n        {\n            fprintf(stderr, \"%s: Error getting primary pick\\n\", __func__);\n            break;\n        }\n        // Need to figure out the component\n        icomp = 1;\n        if (kcmpnm[2] == 'Z' || kcmpnm[2] == 'z' || kcmpnm[2] == '1')\n        {\n            icomp = 1;\n        }\n        else if (kcmpnm[2] == 'N' || kcmpnm[2] == 'n' || kcmpnm[2] == '2')\n        {\n            icomp = 2;\n        }\n        else if (kcmpnm[2] == 'E' || kcmpnm[2] == 'e' || kcmpnm[2] == '3')\n        {\n            icomp = 3;\n        }\n        else\n        {\n            fprintf(stderr, \"%s: Can't classify component: %s\\n\",\n                    __func__, kcmpnm);\n        }\n        // Process all Green's functions in this block\n        for (id=0; id<ffGrns.ndepth; id++)\n        {\n            for (it=0; it<ffGrns.ntstar; it++)\n            {\n                idx = tdsearch_hudson_observationDepthTstarToIndex(iobs, id, it,\n                                                                   ffGrns);\n                kndx = 10*idx;\n                sacio_getFloatHeader(SAC_FLOAT_O, ffGrns.grns[kndx].header, &o);\n                getPrimaryArrival(ffGrns.grns[kndx].header,\n                                  &pickTimeGrns, phaseNameGrns);\n                if (strcasecmp(phaseNameGrns, phaseName) != 0)\n                {\n                    fprintf(stdout, \"%s: Phase name mismatch %s %s\\n\",\n                            __func__, phaseName, phaseNameGrns);\n                }\n                npts = ffGrns.grns[kndx].npts;\n                indx = tdsearch_greens_getGreensFunctionIndex(G11_GRNS,\n                                                              iobs, it, id,\n                                                              *grns);\n                for (i=0; i<6; i++)\n                {\n                    sacio_copy(ffGrns.grns[kndx], &grns->grns[indx+i]);\n                    if (data.obs[iobs].pz.lhavePZ)\n                    {\n                        sacio_copyPolesAndZeros(data.obs[iobs].pz,\n                                                &grns->grns[indx+i].pz);\n                    }\n                    sacio_setFloatHeader(SAC_FLOAT_AZ, az,\n                                         &grns->grns[indx+i].header);\n                    sacio_setFloatHeader(SAC_FLOAT_BAZ, baz,\n                                         &grns->grns[indx+i].header);\n                    sacio_setFloatHeader(SAC_FLOAT_CMPAZ, cmpaz,\n                                         &grns->grns[indx+i].header);\n                    sacio_setFloatHeader(SAC_FLOAT_CMPINC, cmpinc,\n                                         &grns->grns[indx+i].header);\n                    sacio_setFloatHeader(SAC_FLOAT_EVLA, evla,\n                                         &grns->grns[indx+i].header);\n                    sacio_setFloatHeader(SAC_FLOAT_EVLO, evlo,\n                                         &grns->grns[indx+i].header);\n                    sacio_setFloatHeader(SAC_FLOAT_STLA, stla,\n                                         &grns->grns[indx+i].header);\n                    sacio_setFloatHeader(SAC_FLOAT_STLO, stlo,\n                                         &grns->grns[indx+i].header);\n                    sacio_setFloatHeader(SAC_FLOAT_STEL, stel,\n                                         &grns->grns[indx+i].header); \n                    sacio_setCharacterHeader(SAC_CHAR_KNETWK, knetwk,\n                                             &grns->grns[indx+i].header);\n                    sacio_setCharacterHeader(SAC_CHAR_KSTNM, kstnm,\n                                             &grns->grns[indx+i].header);\n                    sacio_setCharacterHeader(SAC_CHAR_KHOLE, khole,\n                                             &grns->grns[indx+i].header);\n                    sacio_setCharacterHeader(SAC_CHAR_KCMPNM, kcmpnms[i],\n                                             &grns->grns[indx+i].header);\n                    sacio_setCharacterHeader(SAC_CHAR_KEVNM, \"SYNTHETIC\\0\",\n                                             &grns->grns[indx+i].header);\n                    // Set the start time by aligning on the arrival\n                    epochNew = epoch + (pickTime - o) - pickTimeGrns;\n                    sacio_setEpochalStartTime(epochNew,\n                                              &grns->grns[indx+i].header);\n                    // Update the pick times\n                    for (l=0; l<11; l++)\n                    {\n                        ierr = sacio_getFloatHeader(pickVars[l],\n                                                    grns->grns[indx+i].header,\n                                                    &pick);\n                        if (ierr == 0)\n                        {\n                            pick = pick + o;\n                            sacio_setFloatHeader(pickVars[l],\n                                                 pick,\n                                                 &grns->grns[indx+i].header);\n                        }\n                    } \n                }\n                ierr = parmt_utils_ff2mtGreens64f(npts, icomp,\n                                                  az, baz,\n                                                  cmpaz, cmpincSEED,\n                                                  ffGrns.grns[kndx+0].data,\n                                                  ffGrns.grns[kndx+1].data,\n                                                  ffGrns.grns[kndx+2].data,\n                                                  ffGrns.grns[kndx+3].data,\n                                                  ffGrns.grns[kndx+4].data,\n                                                  ffGrns.grns[kndx+5].data,\n                                                  ffGrns.grns[kndx+6].data,\n                                                  ffGrns.grns[kndx+7].data,\n                                                  ffGrns.grns[kndx+8].data,\n                                                  ffGrns.grns[kndx+9].data,\n                                                  grns->grns[indx+0].data,\n                                                  grns->grns[indx+1].data,\n                                                  grns->grns[indx+2].data,\n                                                  grns->grns[indx+3].data,\n                                                  grns->grns[indx+4].data,\n                                                  grns->grns[indx+5].data);\n                if (ierr != 0)\n                {\n                    fprintf(stderr, \"%s: Failed to rotate Greens functions\\n\",\n                            __func__);\n                }\n                // Fix the characteristic magnitude scaling in CPS \n                for (i=0; i<6; i++)\n                {\n                    cblas_dscal(npts, xscal, grns->grns[indx+i].data, 1); \n                }\n            }\n        }\n    }\n    return 0;\n}\n//============================================================================//\n/*!\n * @brief Repicks the Green's functions onset time with an STA/LTA picker.\n *\n * @param[in] sta        Short term average window length (seconds).\n * @param[in] lta        Long term average window length (seconds).\n * @param[in] threshPct  Percentage of max STA/LTA after which an arrival\n *                       is declared.\n * @param[in] iobs       C numbered observation index.\n * @param[in] itstar     C numbered t* index.\n * @param[in] idepth     C numbered depth index.\n *\n * @param[in,out] grns   On input contains the Green's functions.\n *                       On output the first arrival time has been modified\n *                       with an STA/LTA picker.\n *\n * @brief 0 indicates success.\n *\n * @ingroup tdsearch_greens\n *\n * @author Ben Baker, ISTI\n *\n */\nint tdsearch_greens_repickGreensWithSTALTA(\n    const double sta, const double lta, const double threshPct,\n    const int iobs, const int itstar, const int idepth,\n    struct tdSearchGreens_struct *grns)\n{\n    struct stalta_struct stalta;\n    double *charFn, *g, *Gxx, *Gyy, *Gzz, *Gxy, *Gxz, *Gyz,\n           *gxxPad, *gyyPad, *gzzPad, *gxyPad, *gxzPad, *gyzPad,\n           charMax, dt, tpick;\n    int indices[6], ierr, k, npts, nlta, npad, nsta, nwork, prePad;\n    // Check STA/LTA \n    ierr = 0;\n    memset(&stalta, 0, sizeof(struct stalta_struct));\n    if (lta < sta || sta < 0.0)\n    {\n        if (lta < sta){fprintf(stderr,\"%s: Error lta < sta\\n\", __func__);}\n        if (sta < 0.0){fprintf(stderr,\"%s: Error sta is negative\\n\", __func__);}\n        return -1;\n    }\n    ierr = tdsearch_greens_getGreensFunctionsIndices(iobs, itstar, idepth,\n                                                     *grns, indices);\n    if (ierr != 0)\n    {\n        fprintf(stderr, \"%s: Failed to get Greens functions indicies\\n\",\n                 __func__);\n        return -1;\n    }\n    ierr = sacio_getIntegerHeader(SAC_INT_NPTS,\n                                  grns->grns[indices[0]].header, &npts);\n    if (ierr != 0 || npts < 1)\n    {\n        if (ierr != 0)\n        {\n            fprintf(stderr, \"%s: Error getting number of points from header\\n\",\n                    __func__);\n        }\n        else\n        {\n            fprintf(stderr, \"%s: ERror no data points\\n\", __func__);\n        }\n        return -1;\n    }\n    ierr = sacio_getFloatHeader(SAC_FLOAT_DELTA,\n                                grns->grns[indices[0]].header, &dt);\n    if (ierr != 0 || dt <= 0.0)\n    {\n        if (ierr != 0){fprintf(stderr, \"%s: failed to get dt\\n\", __func__);}\n        if (dt <= 0.0){fprintf(stderr, \"%s: invalid sampling period\\n\", __func__);}\n        return -1;\n    }\n    // Define the windows\n    nsta = (int) (sta/dt + 0.5);\n    nlta = (int) (lta/dt + 0.5);\n    prePad = MAX(64, fft_nextpow2(nlta, &ierr));\n    npad = prePad + npts;\n    // Set space\n    gxxPad = memory_calloc64f(npad);\n    gyyPad = memory_calloc64f(npad);\n    gzzPad = memory_calloc64f(npad);\n    gxyPad = memory_calloc64f(npad);\n    gxzPad = memory_calloc64f(npad);\n    gyzPad = memory_calloc64f(npad);\n    charFn = memory_calloc64f(npad);\n    // Reference pointers\n    Gxx = grns->grns[indices[0]].data;\n    Gyy = grns->grns[indices[1]].data;\n    Gzz = grns->grns[indices[2]].data;\n    Gxy = grns->grns[indices[3]].data;\n    Gxz = grns->grns[indices[4]].data;\n    Gyz = grns->grns[indices[5]].data;\n    // Pre-pad signals\n    array_set64f_work(prePad, Gxx[0], gxxPad);\n    array_set64f_work(prePad, Gyy[0], gyyPad);\n    array_set64f_work(prePad, Gzz[0], gzzPad); \n    array_set64f_work(prePad, Gxy[0], gxyPad);\n    array_set64f_work(prePad, Gxz[0], gxzPad);\n    array_set64f_work(prePad, Gyz[0], gyzPad);\n    // Copy rest of array\n    array_copy64f_work(npts, Gxx, &gxxPad[prePad]);\n    array_copy64f_work(npts, Gyy, &gyyPad[prePad]);\n    array_copy64f_work(npts, Gzz, &gzzPad[prePad]);\n    array_copy64f_work(npts, Gxy, &gxyPad[prePad]);\n    array_copy64f_work(npts, Gxz, &gxzPad[prePad]);\n    array_copy64f_work(npts, Gyz, &gyzPad[prePad]);\n    // apply the sta/lta\n    for (k=0; k<6; k++)\n    {\n        g = NULL;\n        if (k == 0)\n        {\n            g = gxxPad;\n        }\n        else if (k == 1)\n        {\n            g = gyyPad;\n        }\n        else if (k == 2)\n        {\n            g = gzzPad;\n        }\n        else if (k == 3)\n        {\n            g = gxyPad;\n        }\n        else if (k == 4)\n        {\n            g = gxzPad;\n        }\n        else if (k == 5)\n        {\n            g = gyzPad;\n        }\n        ierr = stalta_setShortAndLongTermAverage(nsta, nlta, &stalta);\n        if (ierr != 0)\n        {\n            printf(\"%s: Error setting STA/LTA\\n\", __func__);\n            break;\n        }\n        ierr = stalta_setData64f(npad, g, &stalta);\n        if (ierr != 0)\n        {\n            printf(\"%s: Error setting data\\n\", __func__);\n            break;\n        }\n        ierr = stalta_applySTALTA(&stalta);\n        if (ierr != 0)\n        {\n            printf(\"%s: Error applying STA/LTA\\n\", __func__);\n            break;\n        }\n        ierr = stalta_getData64f(stalta, npad, &nwork, g);\n        if (ierr != 0)\n        {\n            printf(\"%s: Error getting result\\n\", __func__);\n            break;\n        }\n        cblas_daxpy(npad, 1.0, g, 1, charFn, 1);\n        stalta_resetInitialConditions(&stalta);\n        stalta_resetFinalConditions(&stalta);\n        g = NULL;\n    }\n    // Compute the pick time\n    charMax = array_max64f(npts, &charFn[prePad], &ierr);\n    tpick =-1.0;\n    for (k=prePad; k<npad; k++)\n    {\n        if (charFn[k] > 0.01*threshPct*charMax)\n        {\n            tpick = (double) (k - prePad)*dt;\n            break;\n        }\n    }\n    if (tpick ==-1.0)\n    {\n        tpick = (double) (array_argmax64f(npad, charFn, &ierr) - prePad)*dt;\n    }\n    // Overwrite the pick; by this point should be on SAC_FLOAT_A\n    //double apick;\n    //sacio_getFloatHeader(SAC_FLOAT_A, grns->grns[indices[0]].header, &apick);\n    for (k=0; k<6; k++)\n    {\n        sacio_setFloatHeader(SAC_FLOAT_A, tpick,\n                             &grns->grns[indices[k]].header);\n    }\n    // Dereference pointers and free space\n    Gxx = NULL;\n    Gyy = NULL;\n    Gzz = NULL;\n    Gxy = NULL;\n    Gxz = NULL;\n    Gyz = NULL;\n    memory_free64f(&gxxPad);\n    memory_free64f(&gyyPad);\n    memory_free64f(&gzzPad);\n    memory_free64f(&gxyPad);\n    memory_free64f(&gxzPad);\n    memory_free64f(&gyzPad);\n    memory_free64f(&charFn);\n    stalta_free(&stalta);\n    return ierr;\n}\n//============================================================================//\n/*!\n * @brief Modifies the Green's functions processing commands.\n *\n * @param[in] iodva     The output units for the hudson96 Green's functions.\n * @param[in] iodva     0 indicates the Green's functions have units\n *                      of displacement.\n * @param[in] iodva     1 indicates the Green's functions have units\n *                      of velocity.\n * @param[in] iodva     2 indicates the Green's functions have units\n *                      of acceleration.\n * @param[in] cut0      The cut time in seconds relative to the pick time\n *                      to begin the window around the arrival.\n * @parma[in] cut1      The cut time in seconds relative to the pick time\n *                      to end the window around the arrival.\n * @param[in] targetDt  Desired sampling period in seconds to which the Green's\n *                      functions should be resampled as to match the data.\n *\n * @param[in,out] grns  On input input contains the genreci Green's functions\n *                      processing commands. \n * @param[in,out] grns  On exit the Green's functions processing have been\n *                      made specific to the input Green's functions.\n *\n * @result 0 indicates success.\n *\n * @ingroup tdsearch_greens\n *\n */\nint tdsearch_greens_modifyProcessingCommands(\n    const int iodva,\n    const double cut0, const double cut1, const double targetDt,\n    struct tdSearchGreens_struct *grns)\n{\n    struct tdSearchModifyCommands_struct options;\n    const char **cmds;\n    char **newCmds;\n    size_t lenos;\n    int i, ierr, iobs, k, kndx1, kndx2, ncmds;\n    ierr = 0;\n    grns->cmdsGrns = (struct tdSearchDataProcessingCommands_struct *)\n                     calloc((size_t) grns->ngrns,\n                        sizeof(struct tdSearchDataProcessingCommands_struct));\n    for (iobs=0; iobs<grns->nobs; iobs++)\n    {\n        newCmds = NULL;\n        ncmds =  grns->cmds[iobs].ncmds;\n        if (ncmds < 1){continue;} // Nothing to do\n        cmds = (const char **) grns->cmds[iobs].cmds;\n        options.cut0 = cut0;\n        options.cut1 = cut1;\n        options.targetDt = targetDt;\n        options.ldeconvolution = false;\n        options.iodva = iodva;\n        kndx1 = iobs*(6*grns->ntstar*grns->ndepth);\n        kndx2 = (iobs+1)*(6*grns->ntstar*grns->ndepth);\n        newCmds = tdsearch_commands_modifyCommands(ncmds, (const char **) cmds,\n                                                   options,\n                                                   grns->grns[kndx1], &ierr);\n        if (ierr != 0)\n        {\n            fprintf(stderr, \"%s: Failed to set processing commands\\n\", __func__);\n            goto ERROR;\n        }\n        // Expand the processing commands \n        for (k=kndx1; k<kndx2; k++)\n        {\n            grns->cmdsGrns[k].ncmds = ncmds;\n            grns->cmdsGrns[k].cmds = (char **)\n                                     calloc((size_t) ncmds, sizeof(char *));\n            for (i=0; i<ncmds; i++)\n            {\n                lenos = strlen(newCmds[i]);\n                grns->cmdsGrns[k].cmds[i] = (char *)\n                                            calloc(lenos+1, sizeof(char));\n                strcpy(grns->cmdsGrns[k].cmds[i], newCmds[i]);\n            }\n        } \n        // Release the memory\n        if (newCmds != NULL)\n        {\n            for (i=0; i<ncmds; i++)\n            {\n                if (newCmds[i] != NULL){free(newCmds[i]);}\n            }\n            free(newCmds);\n        }\n    }\nERROR:;\n    return ierr;\n}\n//============================================================================//\n/*!\n * @brief Processes the Green's functions.\n *\n * @param[in,out] grns    On input contains the Green's functions for all\n *                        observations, depths, and t*'s as well as the\n *                        processing chains.\n *                        On output contains the filtered Green's functions\n *                        for all observations, depths, and t*'s.\n *\n * @result 0 indicates success.\n *\n * @ingroup tdsearch_greens\n *\n * @author Ben Baker, ISTI\n *\n */\nint tdsearch_greens_process(struct tdSearchGreens_struct *grns)\n{\n    double *data;\n    struct serialCommands_struct commands;\n    struct parallelCommands_struct parallelCommands;\n    double dt, dt0, epoch, epoch0, time;\n    int dataPtr[7], i, i0, ierr, iobs, idep, it, kndx, l, npts, npts0, nq,\n        nwork, ny, ns;\n    bool lnewDt, lnewStartTime;\n    const int nsignals = 6;\n    const int nTimeVars = 12;\n    const enum sacHeader_enum timeVars[12]\n       = {SAC_FLOAT_A, SAC_FLOAT_O, \n          SAC_FLOAT_T0, SAC_FLOAT_T1, SAC_FLOAT_T2, SAC_FLOAT_T3,\n          SAC_FLOAT_T4, SAC_FLOAT_T5, SAC_FLOAT_T6, SAC_FLOAT_T7,\n          SAC_FLOAT_T8, SAC_FLOAT_T9};\n    // Loop on the observations\n    for (iobs=0; iobs<grns->nobs; iobs++)\n    {\n        for (idep=0; idep<grns->ndepth; idep++)\n        {\n            for (it=0; it<grns->ntstar; it++)\n            {\n                memset(&parallelCommands, 0,\n                       sizeof(struct parallelCommands_struct)); \n                memset(&commands, 0, sizeof(struct serialCommands_struct));\n                kndx = tdsearch_greens_getGreensFunctionIndex(G11_GRNS,\n                                                              iobs, it, idep,\n                                                              *grns);\n                ierr = process_stringsToSerialCommandsOptions(\n                                      grns->cmdsGrns[kndx].ncmds,\n                                      (const char **) grns->cmdsGrns[kndx].cmds,\n                                      &commands);\n                if (ierr != 0)\n                {\n                    fprintf(stderr, \"%s: Error setting serial command string\\n\", __func__);\n                    goto ERROR;\n                }\n                // Determine some characteristics of the processing\n                sacio_getEpochalStartTime(grns->grns[kndx].header, &epoch0);\n                sacio_getFloatHeader(SAC_FLOAT_DELTA,\n                                     grns->grns[kndx].header, &dt0);\n                lnewDt = false;\n                lnewStartTime = false;\n                epoch = epoch0;\n                dt = dt0;\n                for (i=0; i<commands.ncmds; i++)\n                {\n                     if (commands.commands[i].type == CUT_COMMAND)\n                     {\n                         i0 = commands.commands[i].cut.i0;\n                         epoch = epoch + (double) i0*dt;\n                         lnewStartTime = true;\n                     }\n                     if (commands.commands[i].type == DOWNSAMPLE_COMMAND)\n                     {\n                         nq = commands.commands[i].downsample.nq;\n                         dt = dt*(double) nq;\n                         lnewDt = true;\n                     }\n                     if (commands.commands[i].type == DECIMATE_COMMAND)\n                     {\n                         nq = commands.commands[i].decimate.nqAll;\n                         dt = dt*(double) nq;\n                         lnewDt = true;\n                     }\n                }\n                dataPtr[0] = 0;\n                for (i=0; i<nsignals; i++)\n                {\n                    dataPtr[i+1] = dataPtr[i] + grns->grns[kndx+i].npts;\n                }\n                process_setCommandOnAllParallelCommands(nsignals, commands,\n                                                        &parallelCommands);\n                data = memory_calloc64f(dataPtr[nsignals]);\n                for (i=0; i<nsignals; i++)\n                {\n                    ierr = array_copy64f_work(grns->grns[kndx+i].npts,\n                                              grns->grns[kndx+i].data,\n                                              &data[dataPtr[i]]);\n                    if (ierr != 0)\n                    {\n                         fprintf(stderr, \"%s: Failed to copy data\\n\", __func__);\n                         goto ERROR;\n                    }\n                }\n                ierr = process_setParallelCommandsData64f(nsignals, dataPtr,\n                                                          data,\n                                                          &parallelCommands);\n                if (ierr != 0)\n                {\n                    fprintf(stderr, \"%s: Failed to set data\\n\", __func__);\n                    goto ERROR;\n                }\n                ierr = process_applyParallelCommands(&parallelCommands);\n                if (ierr != 0)\n                {\n                    fprintf(stderr ,\"%s: Failed to process data\\n\", __func__);\n                    goto ERROR;\n                }\n                // Get the data\n                nwork = dataPtr[nsignals];\n                ierr = process_getParallelCommandsData64f(parallelCommands,\n                                                          -1, nsignals,\n                                                          &ny, &ns,\n                                                          dataPtr, data);\n                if (ny > nwork)\n                {\n                    memory_free64f(&data);\n                    data = memory_calloc64f(ny);\n                }\n                nwork = ny;\n                ierr = process_getParallelCommandsData64f(parallelCommands,\n                                                          nwork, nsignals,\n                                                          &ny, &ns,\n                                                          dataPtr, data);\n                for (i=0; i<nsignals; i++)\n                {\n                    sacio_getIntegerHeader(SAC_INT_NPTS,  \n                                           grns->grns[kndx+i].header, &npts0);\n                    npts = dataPtr[i+1] - dataPtr[i];\n                    // Resize event\n                    if (npts != npts0)\n                    {\n                        sacio_freeData(&grns->grns[kndx+i]);\n                        grns->grns[kndx+i].data = sacio_malloc64f(npts);\n                        grns->grns[kndx+i].npts = npts;\n                        sacio_setIntegerHeader(SAC_INT_NPTS, npts,\n                                               &grns->grns[kndx+i].header);\n                        ierr = array_copy64f_work(npts,\n                                                  &data[dataPtr[i]],\n                                                  grns->grns[kndx+i].data);\n                    }\n                    else\n                    {\n                        ierr = array_copy64f_work(npts,\n                                                  &data[dataPtr[i]],\n                                                  grns->grns[kndx+i].data);\n                    }\n                }\n                // Update the times\n                if (lnewStartTime)\n                {\n                    for (i=0; i<nsignals; i++)\n                    {\n                        // Update the picks\n                        for (l=0; l<nTimeVars; l++)\n                        {\n                            ierr = sacio_getFloatHeader(timeVars[l],\n                                              grns->grns[kndx+i].header, &time);\n                            if (ierr == 0)\n                            {\n                                time = time + epoch0; // Turn to real time\n                                time = time - epoch;  // Relative to new time\n                                sacio_setFloatHeader(timeVars[l], time,\n                                                    &grns->grns[kndx+i].header);\n                            }\n                        } // Loop on picks\n                        sacio_setEpochalStartTime(epoch,\n                                                  &grns->grns[kndx+i].header);\n                    } // Loop on signals\n                }\n                // Update the sampling period\n                if (lnewDt)\n                {\n                    for (i=0; i<nsignals; i++)\n                    {\n                        sacio_setFloatHeader(SAC_FLOAT_DELTA, dt,\n                                             &grns->grns[kndx+i].header);\n                    }\n                }\n                process_freeSerialCommands(&commands);\n                process_freeParallelCommands(&parallelCommands);\n                memory_free64f(&data);\n//TODO fix this\ntdsearch_greens_repickGreensWithSTALTA(2.0, 10.0, 80.0, iobs, it, idep, grns);\n            }\n        }\n    }\nERROR:;\n    return 0;\n}\n//============================================================================//\n/*!\n * @brief Writes the Green's functions corresponding to the iobs'th observation\n *        for the given tstar, depth index.\n *\n * @param[in] dirnm    Directory name where the Green's functions should be\n *                     written.  If this is NULL then the Green's functions\n *                     will be written to the current working directory.\n * @param[in] iobs     Observation index in the range [0,nobs-1].\n * @param[in] itstar   The t* index in the range [0,ntstar-1].\n * @param[in] idepth   The depth index in the range [0,ndepth-1].\n * @param[in] grns     The structure containing the Green's functions.\n *\n * @result 0 indicates success.\n *\n * @ingroup tdsearch_greens\n *\n */\nint tdsearch_greens_writeSelectGreensFunctions(\n    const char *dirnm,\n    const int iobs, const int itstar, const int idepth,\n    const struct tdSearchGreens_struct grns) \n{\n    char fileName[PATH_MAX], rootName[PATH_MAX];\n    size_t lenos;\n    int i, ierr, indx;\n    memset(rootName, 0, PATH_MAX*sizeof(char));\n    if (dirnm == NULL)\n    {\n        strcpy(rootName, \"./\\0\");\n    }\n    else\n    {\n        lenos = strlen(dirnm);\n        if (lenos > 0)\n        {\n            strcpy(rootName, dirnm);\n            if (rootName[lenos-1] != '/'){strcat(rootName, \"/\\0\");}\n        }\n        else\n        {\n            strcpy(rootName, \"./\\0\");\n        }\n    }\n    if (!os_path_isdir(rootName))\n    {\n        ierr = os_makedirs(rootName);\n        if (ierr != 0)\n        {\n            fprintf(stderr, \"%s: Failed to make output directory %s\\n\",\n                    __func__, rootName);\n            return -1;\n        }\n    }\n    // Get the indices to write\n    indx =  tdsearch_greens_getGreensFunctionIndex(G11_GRNS,\n                                                   iobs, itstar, idepth,\n                                                   grns);\n    if (indx < 0)\n    {\n        fprintf(stderr, \"%s: Invalid index\\n\", __func__);\n        return -1;\n    }\n    for (i=0; i<6; i++)\n    {\n        memset(fileName, 0, PATH_MAX*sizeof(char));\n        sprintf(fileName, \"%s%s.%s.%s.%s.DEPTH_%d.TSTAR_%d.SAC\",\n                rootName, grns.grns[indx+i].header.knetwk,\n                grns.grns[indx+i].header.kstnm,\n                grns.grns[indx+i].header.kcmpnm,\n                grns.grns[indx+i].header.khole, idepth, itstar);\n        sacio_writeTimeSeriesFile(fileName, grns.grns[indx+i]);\n    }\n    return 0;\n}\n//============================================================================//\nstatic int getPrimaryArrival(const struct sacHeader_struct hdr,\n                             double *time, char phaseName[8])\n{\n    const enum sacHeader_enum timeVars[11]\n       = {SAC_FLOAT_A,\n          SAC_FLOAT_T0, SAC_FLOAT_T1, SAC_FLOAT_T2, SAC_FLOAT_T3,\n          SAC_FLOAT_T4, SAC_FLOAT_T5, SAC_FLOAT_T6, SAC_FLOAT_T7,\n          SAC_FLOAT_T8, SAC_FLOAT_T9};\n    const enum sacHeader_enum timeVarNames[11]\n       = {SAC_CHAR_KA,\n          SAC_CHAR_KT0, SAC_CHAR_KT1, SAC_CHAR_KT2, SAC_CHAR_KT3,\n          SAC_CHAR_KT4, SAC_CHAR_KT5, SAC_CHAR_KT6, SAC_CHAR_KT7,\n          SAC_CHAR_KT8, SAC_CHAR_KT9};\n    int i, ifound1, ifound2; \n    memset(phaseName, 0, 8*sizeof(char));\n    for (i=0; i<11; i++)\n    {\n        ifound1 = sacio_getFloatHeader(timeVars[i], hdr, time);\n        ifound2 = sacio_getCharacterHeader(timeVarNames[i], hdr, phaseName); \n        if (ifound1 == 0 && ifound2 == 0){return 0;}\n    }\n    printf(\"%s: Failed to get primary pick\\n\", __func__);\n    *time =-12345.0;\n    memset(phaseName, 0, 8*sizeof(char));\n    strcpy(phaseName, \"-12345\"); \n    return -1;\n}\n", "meta": {"hexsha": "ae3e33e621a99d46f63828cecef62e86a5679c46", "size": 44824, "ext": "c", "lang": "C", "max_stars_repo_path": "src/greens.c", "max_stars_repo_name": "bakerb845/tdsearch", "max_stars_repo_head_hexsha": "fc65471b097aa6a92fcaf558dfa50622345c4025", "max_stars_repo_licenses": ["Intel"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/greens.c", "max_issues_repo_name": "bakerb845/tdsearch", "max_issues_repo_head_hexsha": "fc65471b097aa6a92fcaf558dfa50622345c4025", "max_issues_repo_licenses": ["Intel"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/greens.c", "max_forks_repo_name": "bakerb845/tdsearch", "max_forks_repo_head_hexsha": "fc65471b097aa6a92fcaf558dfa50622345c4025", "max_forks_repo_licenses": ["Intel"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.8086580087, "max_line_length": 91, "alphanum_fraction": 0.4762627164, "num_tokens": 11023, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1732882016598637, "lm_q2_score": 0.031143832558095677, "lm_q1q2_score": 0.005396858736788313}}
{"text": "/* matrix/gsl_matrix_ushort.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_MATRIX_USHORT_H__\n#define __GSL_MATRIX_USHORT_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_vector_ushort.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size1;\n  size_t size2;\n  size_t tda;\n  unsigned short * data;\n  gsl_block_ushort * block;\n  int owner;\n} gsl_matrix_ushort;\n\ntypedef struct\n{\n  gsl_matrix_ushort matrix;\n} _gsl_matrix_ushort_view;\n\ntypedef _gsl_matrix_ushort_view gsl_matrix_ushort_view;\n\ntypedef struct\n{\n  gsl_matrix_ushort matrix;\n} _gsl_matrix_ushort_const_view;\n\ntypedef const _gsl_matrix_ushort_const_view gsl_matrix_ushort_const_view;\n\n/* Allocation */\n\nGSL_EXPORT\ngsl_matrix_ushort *\ngsl_matrix_ushort_alloc (const size_t n1, const size_t n2);\n\nGSL_EXPORT\ngsl_matrix_ushort *\ngsl_matrix_ushort_calloc (const size_t n1, const size_t n2);\n\nGSL_EXPORT\ngsl_matrix_ushort *\ngsl_matrix_ushort_alloc_from_block (gsl_block_ushort * b,\n                                   const size_t offset,\n                                   const size_t n1,\n                                   const size_t n2,\n                                   const size_t d2);\n\nGSL_EXPORT\ngsl_matrix_ushort *\ngsl_matrix_ushort_alloc_from_matrix (gsl_matrix_ushort * m,\n                                    const size_t k1,\n                                    const size_t k2,\n                                    const size_t n1,\n                                    const size_t n2);\n\nGSL_EXPORT\ngsl_vector_ushort *\ngsl_vector_ushort_alloc_row_from_matrix (gsl_matrix_ushort * m,\n                                        const size_t i);\n\nGSL_EXPORT\ngsl_vector_ushort *\ngsl_vector_ushort_alloc_col_from_matrix (gsl_matrix_ushort * m,\n                                        const size_t j);\n\nGSL_EXPORT void gsl_matrix_ushort_free (gsl_matrix_ushort * m);\n\n/* Views */\n\nGSL_EXPORT\n_gsl_matrix_ushort_view\ngsl_matrix_ushort_submatrix (gsl_matrix_ushort * m,\n                            const size_t i, const size_t j,\n                            const size_t n1, const size_t n2);\n\nGSL_EXPORT\n_gsl_vector_ushort_view\ngsl_matrix_ushort_row (gsl_matrix_ushort * m, const size_t i);\n\nGSL_EXPORT\n_gsl_vector_ushort_view\ngsl_matrix_ushort_column (gsl_matrix_ushort * m, const size_t j);\n\nGSL_EXPORT\n_gsl_vector_ushort_view\ngsl_matrix_ushort_diagonal (gsl_matrix_ushort * m);\n\nGSL_EXPORT\n_gsl_vector_ushort_view\ngsl_matrix_ushort_subdiagonal (gsl_matrix_ushort * m, const size_t k);\n\nGSL_EXPORT\n_gsl_vector_ushort_view\ngsl_matrix_ushort_superdiagonal (gsl_matrix_ushort * m, const size_t k);\n\nGSL_EXPORT\n_gsl_matrix_ushort_view\ngsl_matrix_ushort_view_array (unsigned short * base,\n                             const size_t n1,\n                             const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_ushort_view\ngsl_matrix_ushort_view_array_with_tda (unsigned short * base,\n                                      const size_t n1,\n                                      const size_t n2,\n                                      const size_t tda);\n\n\nGSL_EXPORT\n_gsl_matrix_ushort_view\ngsl_matrix_ushort_view_vector (gsl_vector_ushort * v,\n                              const size_t n1,\n                              const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_ushort_view\ngsl_matrix_ushort_view_vector_with_tda (gsl_vector_ushort * v,\n                                       const size_t n1,\n                                       const size_t n2,\n                                       const size_t tda);\n\n\nGSL_EXPORT\n_gsl_matrix_ushort_const_view\ngsl_matrix_ushort_const_submatrix (const gsl_matrix_ushort * m,\n                                  const size_t i, const size_t j,\n                                  const size_t n1, const size_t n2);\n\nGSL_EXPORT\n_gsl_vector_ushort_const_view\ngsl_matrix_ushort_const_row (const gsl_matrix_ushort * m,\n                            const size_t i);\n\nGSL_EXPORT\n_gsl_vector_ushort_const_view\ngsl_matrix_ushort_const_column (const gsl_matrix_ushort * m,\n                               const size_t j);\n\nGSL_EXPORT\n_gsl_vector_ushort_const_view\ngsl_matrix_ushort_const_diagonal (const gsl_matrix_ushort * m);\n\nGSL_EXPORT\n_gsl_vector_ushort_const_view\ngsl_matrix_ushort_const_subdiagonal (const gsl_matrix_ushort * m,\n                                    const size_t k);\n\nGSL_EXPORT\n_gsl_vector_ushort_const_view\ngsl_matrix_ushort_const_superdiagonal (const gsl_matrix_ushort * m,\n                                      const size_t k);\n\nGSL_EXPORT\n_gsl_matrix_ushort_const_view\ngsl_matrix_ushort_const_view_array (const unsigned short * base,\n                                   const size_t n1,\n                                   const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_ushort_const_view\ngsl_matrix_ushort_const_view_array_with_tda (const unsigned short * base,\n                                            const size_t n1,\n                                            const size_t n2,\n                                            const size_t tda);\n\nGSL_EXPORT\n_gsl_matrix_ushort_const_view\ngsl_matrix_ushort_const_view_vector (const gsl_vector_ushort * v,\n                                    const size_t n1,\n                                    const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_ushort_const_view\ngsl_matrix_ushort_const_view_vector_with_tda (const gsl_vector_ushort * v,\n                                             const size_t n1,\n                                             const size_t n2,\n                                             const size_t tda);\n\n/* Operations */\n\nGSL_EXPORT unsigned short   gsl_matrix_ushort_get(const gsl_matrix_ushort * m, const size_t i, const size_t j);\nGSL_EXPORT void    gsl_matrix_ushort_set(gsl_matrix_ushort * m, const size_t i, const size_t j, const unsigned short x);\n\nGSL_EXPORT unsigned short * gsl_matrix_ushort_ptr(gsl_matrix_ushort * m, const size_t i, const size_t j);\nGSL_EXPORT const unsigned short * gsl_matrix_ushort_const_ptr(const gsl_matrix_ushort * m, const size_t i, const size_t j);\n\nGSL_EXPORT void gsl_matrix_ushort_set_zero (gsl_matrix_ushort * m);\nGSL_EXPORT void gsl_matrix_ushort_set_identity (gsl_matrix_ushort * m);\nGSL_EXPORT void gsl_matrix_ushort_set_all (gsl_matrix_ushort * m, unsigned short x);\n\nGSL_EXPORT int gsl_matrix_ushort_fread (FILE * stream, gsl_matrix_ushort * m) ;\nGSL_EXPORT int gsl_matrix_ushort_fwrite (FILE * stream, const gsl_matrix_ushort * m) ;\nGSL_EXPORT int gsl_matrix_ushort_fscanf (FILE * stream, gsl_matrix_ushort * m);\nGSL_EXPORT int gsl_matrix_ushort_fprintf (FILE * stream, const gsl_matrix_ushort * m, const char * format);\n\nGSL_EXPORT int gsl_matrix_ushort_memcpy(gsl_matrix_ushort * dest, const gsl_matrix_ushort * src);\nGSL_EXPORT int gsl_matrix_ushort_swap(gsl_matrix_ushort * m1, gsl_matrix_ushort * m2);\n\nGSL_EXPORT int gsl_matrix_ushort_swap_rows(gsl_matrix_ushort * m, const size_t i, const size_t j);\nGSL_EXPORT int gsl_matrix_ushort_swap_columns(gsl_matrix_ushort * m, const size_t i, const size_t j);\nGSL_EXPORT int gsl_matrix_ushort_swap_rowcol(gsl_matrix_ushort * m, const size_t i, const size_t j);\nGSL_EXPORT int gsl_matrix_ushort_transpose (gsl_matrix_ushort * m);\nGSL_EXPORT int gsl_matrix_ushort_transpose_memcpy (gsl_matrix_ushort * dest, const gsl_matrix_ushort * src);\n\nGSL_EXPORT unsigned short gsl_matrix_ushort_max (const gsl_matrix_ushort * m);\nGSL_EXPORT unsigned short gsl_matrix_ushort_min (const gsl_matrix_ushort * m);\nGSL_EXPORT void gsl_matrix_ushort_minmax (const gsl_matrix_ushort * m, unsigned short * min_out, unsigned short * max_out);\n\nGSL_EXPORT void gsl_matrix_ushort_max_index (const gsl_matrix_ushort * m, size_t * imax, size_t *jmax);\nGSL_EXPORT void gsl_matrix_ushort_min_index (const gsl_matrix_ushort * m, size_t * imin, size_t *jmin);\nGSL_EXPORT void gsl_matrix_ushort_minmax_index (const gsl_matrix_ushort * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);\n\nGSL_EXPORT int gsl_matrix_ushort_isnull (const gsl_matrix_ushort * m);\n\nGSL_EXPORT int gsl_matrix_ushort_add (gsl_matrix_ushort * a, const gsl_matrix_ushort * b);\nGSL_EXPORT int gsl_matrix_ushort_sub (gsl_matrix_ushort * a, const gsl_matrix_ushort * b);\nGSL_EXPORT int gsl_matrix_ushort_mul_elements (gsl_matrix_ushort * a, const gsl_matrix_ushort * b);\nGSL_EXPORT int gsl_matrix_ushort_div_elements (gsl_matrix_ushort * a, const gsl_matrix_ushort * b);\nGSL_EXPORT int gsl_matrix_ushort_scale (gsl_matrix_ushort * a, const double x);\nGSL_EXPORT int gsl_matrix_ushort_add_constant (gsl_matrix_ushort * a, const double x);\nGSL_EXPORT int gsl_matrix_ushort_add_diagonal (gsl_matrix_ushort * a, const double x);\n\n/***********************************************************************/\n/* The functions below are obsolete                                    */\n/***********************************************************************/\nGSL_EXPORT int gsl_matrix_ushort_get_row(gsl_vector_ushort * v, const gsl_matrix_ushort * m, const size_t i);\nGSL_EXPORT int gsl_matrix_ushort_get_col(gsl_vector_ushort * v, const gsl_matrix_ushort * m, const size_t j);\nGSL_EXPORT int gsl_matrix_ushort_set_row(gsl_matrix_ushort * m, const size_t i, const gsl_vector_ushort * v);\nGSL_EXPORT int gsl_matrix_ushort_set_col(gsl_matrix_ushort * m, const size_t j, const gsl_vector_ushort * v);\n\n/* inline functions if you are using GCC */\n\n#ifdef HAVE_INLINE\nextern inline\nunsigned short\ngsl_matrix_ushort_get(const gsl_matrix_ushort * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_VAL(\"first index out of range\", GSL_EINVAL, 0) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_VAL(\"second index out of range\", GSL_EINVAL, 0) ;\n    }\n#endif\n  return m->data[i * m->tda + j] ;\n}\n\nextern inline\nvoid\ngsl_matrix_ushort_set(gsl_matrix_ushort * m, const size_t i, const size_t j, const unsigned short x)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_VOID(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_VOID(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  m->data[i * m->tda + j] = x ;\n}\n\nextern inline\nunsigned short *\ngsl_matrix_ushort_ptr(gsl_matrix_ushort * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  return (unsigned short *) (m->data + (i * m->tda + j)) ;\n}\n\nextern inline\nconst unsigned short *\ngsl_matrix_ushort_const_ptr(const gsl_matrix_ushort * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  return (const unsigned short *) (m->data + (i * m->tda + j)) ;\n}\n\n#endif\n\n__END_DECLS\n\n#endif /* __GSL_MATRIX_USHORT_H__ */\n", "meta": {"hexsha": "196baed5147fb946d9af5895fbba5895552e75df", "size": 11948, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/gsl/include/gsl/gsl_matrix_ushort.h", "max_stars_repo_name": "dynaryu/vaws", "max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/gsl/include/gsl/gsl_matrix_ushort.h", "max_issues_repo_name": "dynaryu/vaws", "max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/gsl/include/gsl/gsl_matrix_ushort.h", "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.833819242, "max_line_length": 137, "alphanum_fraction": 0.687646468, "num_tokens": 2987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20434189993684584, "lm_q2_score": 0.026355355713931997, "lm_q1q2_score": 0.005385503460096271}}
{"text": "#ifndef TTT_AUDIOCACHE_H\n#define TTT_AUDIOCACHE_H\n\n#include <SDL_mixer.h>\n\n#include <gsl/util>\n\n#include <vector>\n#include <memory>\n#include <string_view>\n\nnamespace ttt\n{\n\t// A class for caching sounds and music.\n\tclass AudioCache final\n\t{\n\tpublic:\n\t\tusing SizeType = gsl::index;\n\n\t\tMix_Music *loadMusic(std::string_view path);\n\t\tMix_Chunk *loadChunk(std::string_view path);\n\n\t\tvoid unloadMusic(SizeType index) noexcept;\n\t\tvoid unloadChunk(SizeType index) noexcept;\n\t\t\n\t\tvoid eraseMusic(SizeType index) noexcept;\n\t\tvoid eraseChunk(SizeType index) noexcept;\n\n\t\tvoid clearMusic() noexcept;\n\t\tvoid clearChunks() noexcept;\n\t\tvoid clear() noexcept;\n\n\t\t[[nodiscard]] Mix_Music *getMusic(SizeType index) const noexcept;\n\t\t[[nodiscard]] Mix_Chunk *getChunk(SizeType index) const noexcept;\n\n\tprivate:\n\t\tstd::vector<std::unique_ptr<Mix_Music, decltype(&Mix_FreeMusic)>> music;\n\t\tstd::vector<std::unique_ptr<Mix_Chunk, decltype(&Mix_FreeChunk)>> chunks;\n\t};\n\n\tinline void AudioCache::unloadMusic(SizeType index) noexcept { gsl::at(music, index).reset(); }\n\tinline void AudioCache::unloadChunk(SizeType index) noexcept { gsl::at(chunks, index).reset(); }\n\n\tinline void AudioCache::eraseMusic(SizeType index) noexcept { music.erase(music.cbegin() + index); }\n\tinline void AudioCache::eraseChunk(SizeType index) noexcept { chunks.erase(chunks.cbegin() + index); }\n\t\n\tinline void AudioCache::clearMusic() noexcept { music.clear(); }\n\tinline void AudioCache::clearChunks() noexcept { chunks.clear(); }\n\n\tinline Mix_Music *AudioCache::getMusic(SizeType index) const noexcept { return gsl::at(music, index).get(); }\n\tinline Mix_Chunk *AudioCache::getChunk(SizeType index) const noexcept { return gsl::at(chunks, index).get(); }\n}\n\n#endif", "meta": {"hexsha": "2e3255a9a94dd85df33f6518254a2292de95ca56", "size": 1720, "ext": "h", "lang": "C", "max_stars_repo_path": "Source/AudioCache.h", "max_stars_repo_name": "itsArtem/TicTacToe", "max_stars_repo_head_hexsha": "8c70a77e4603dd0ff22ec0621b978ec0685ec3cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Source/AudioCache.h", "max_issues_repo_name": "itsArtem/TicTacToe", "max_issues_repo_head_hexsha": "8c70a77e4603dd0ff22ec0621b978ec0685ec3cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/AudioCache.h", "max_forks_repo_name": "itsArtem/TicTacToe", "max_forks_repo_head_hexsha": "8c70a77e4603dd0ff22ec0621b978ec0685ec3cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8518518519, "max_line_length": 111, "alphanum_fraction": 0.7447674419, "num_tokens": 429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20689406837681013, "lm_q2_score": 0.025957358799003922, "lm_q1q2_score": 0.005370423566242511}}
{"text": "#pragma once\n\n#include \"table.h\"\n#include <gsl/span>\n#include <new>\n\ntemplate <typename T>\nT* CreateTypeBuffer(std::size_t rowCount) {\n    return new T[rowCount]();\n}\n\ntemplate <typename T>\nstruct CreateTypeBuffers { };\n\ntemplate <typename... Ts>\nstruct CreateTypeBuffers<std::tuple<Ts...>> {\n    static void** exec(std::size_t rowCount) {\n        return new void* [sizeof...(Ts)]{ CreateTypeBuffer<Ts>(rowCount)... };\n    }\n};\n\ntemplate <typename... Ts>\nTable CreateTable(std::size_t rowCount) {\n    using ColumnList = ColumnListT<Ts...>;\n    return {\n        .columns = ColumnList(),\n        .instanceData = CreateTypeBuffers<typename ColumnList::types>::exec(rowCount),\n        .rowCount = 0,\n        .rowCapacity = rowCount,\n        .cellMetas = ColumnList::metas.data(),\n    };\n}\n\nclass TableFactory {\npublic:\n    Table Alloc(gsl::span<const CellMeta> metas) {\n        const auto rowCapacity = 128;\n        const auto columnCount = metas.size();\n\n        auto columns = static_cast<ColumnId*>(malloc(columnCount * sizeof(ColumnId)));\n        auto instances = new void*[columnCount];\n        auto cellMetas = static_cast<CellMeta*>(malloc(columnCount * sizeof(CellMeta)));\n\n        auto index = 0;\n        for (const auto& meta : metas) {\n            new(columns + index) ColumnId(meta.id);\n            instances[index] = std::calloc(rowCapacity, meta.storageBytes);\n            new(cellMetas + index) CellMeta(meta);\n            ++index;\n        }\n\n        Table ret = {};\n        ret.columns = ColumnList(columns, columnCount);\n        ret.cellMetas = cellMetas;\n        ret.instanceData = instances;\n        ret.rowCapacity = rowCapacity;\n        return ret;\n    }\n\n    void Free(const Table& /*table*/) {\n    }\n};\n", "meta": {"hexsha": "122b49f163a55809a0c4b6093eee6d936d4af435", "size": 1722, "ext": "h", "lang": "C", "max_stars_repo_path": "inc/lime/placeholder.h", "max_stars_repo_name": "zestier/lime", "max_stars_repo_head_hexsha": "c2e500421c443ebe40f04637d0c8340fa52fc495", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "inc/lime/placeholder.h", "max_issues_repo_name": "zestier/lime", "max_issues_repo_head_hexsha": "c2e500421c443ebe40f04637d0c8340fa52fc495", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inc/lime/placeholder.h", "max_forks_repo_name": "zestier/lime", "max_forks_repo_head_hexsha": "c2e500421c443ebe40f04637d0c8340fa52fc495", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3333333333, "max_line_length": 88, "alphanum_fraction": 0.6178861789, "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20689403903542758, "lm_q2_score": 0.02595735776292875, "lm_q1q2_score": 0.00537042259025994}}
{"text": "#pragma once\n\n#include <halley/utils/utils.h>\n#include <vector>\n#include <gsl/gsl>\n#include \"halley/data_structures/flat_map.h\"\n#include \"halley/maths/vector2.h\"\n#include \"halley/maths/rect.h\"\n#include \"halley/file/path.h\"\n#include <map>\n#include <unordered_map>\n#include <cstdint>\n#include <utility>\n#include <set>\n#include \"halley/data_structures/maybe.h\"\n#include \"halley/maths/colour.h\"\n#include \"halley/maths/vector4.h\"\n\nnamespace Halley {\n\tclass String;\n\n\tclass SerializerOptions {\n\tpublic:\n\t\tconstexpr static int maxVersion = 1;\n\t\t\n\t\tint version = 0;\n\t\tbool exhaustiveDictionary = false;\n\t\tstd::function<std::optional<size_t>(const String& string)> stringToIndex;\n\t\tstd::function<const String&(size_t index)> indexToString;\n\n\t\tSerializerOptions() = default;\n\t\tSerializerOptions(int version)\n\t\t\t: version(version)\n\t\t{}\n\t};\n\n\tclass SerializerState {};\n\n\tclass ByteSerializationBase {\n\tpublic:\n\t\tByteSerializationBase(SerializerOptions options)\n\t\t\t: options(std::move(options))\n\t\t{}\n\t\t\n\t\tSerializerState* setState(SerializerState* state);\n\t\t\n\t\ttemplate <typename T>\n\t\tT* getState() const\n\t\t{\n\t\t\treturn static_cast<T*>(state);\n\t\t}\n\n\t\tint getVersion() const { return version; }\n\t\tvoid setVersion(int v) { version = v; }\n\n\tprotected:\n\t\tSerializerOptions options;\n\t\t\n\tprivate:\n\t\tSerializerState* state = nullptr;\n\t\tint version = 0;\n\t};\n\t\t\n\tclass Serializer : public ByteSerializationBase {\n\tpublic:\n\t\tSerializer(SerializerOptions options);\n\t\texplicit Serializer(gsl::span<gsl::byte> dst, SerializerOptions options);\n\n\t\ttemplate <typename T, typename std::enable_if<std::is_convertible<T, std::function<void(Serializer&)>>::value, int>::type = 0>\n\t\tstatic Bytes toBytes(const T& f, SerializerOptions options = {})\n\t\t{\n\t\t\tauto dry = Serializer(options);\n\t\t\tf(dry);\n\t\t\tBytes result(dry.getSize());\n\t\t\tauto s = Serializer(gsl::as_writable_bytes(gsl::span<Halley::Byte>(result)), options);\n\t\t\tf(s);\n\t\t\treturn result;\n\t\t}\n\n\t\ttemplate <typename T, typename std::enable_if<!std::is_convertible<T, std::function<void(Serializer&)>>::value, int>::type = 0>\n\t\tstatic Bytes toBytes(const T& value, SerializerOptions options = {})\n\t\t{\n\t\t\treturn toBytes([&value](Serializer& s) { s << value; }, options);\n\t\t}\n\n\t\tsize_t getSize() const { return size; }\n\n\t\tSerializer& operator<<(bool val) { return serializePod(val); }\n\t\tSerializer& operator<<(int8_t val) { return serializeInteger(val); }\n\t\tSerializer& operator<<(uint8_t val) { return serializeInteger(val); }\n\t\tSerializer& operator<<(int16_t val) { return serializeInteger(val); }\n\t\tSerializer& operator<<(uint16_t val) { return serializeInteger(val); }\n\t\tSerializer& operator<<(int32_t val) { return serializeInteger(val); }\n\t\tSerializer& operator<<(uint32_t val) { return serializeInteger(val); }\n\t\tSerializer& operator<<(int64_t val) { return serializeInteger(val); }\n\t\tSerializer& operator<<(uint64_t val) { return serializeInteger(val); }\n\t\tSerializer& operator<<(float val) { return serializePod(val); }\n\t\tSerializer& operator<<(double val) { return serializePod(val); }\n\n\t\tSerializer& operator<<(const std::string& str);\n\t\tSerializer& operator<<(const String& str);\n\t\tSerializer& operator<<(const StringUTF32& str);\n\t\tSerializer& operator<<(const Path& path);\n\t\tSerializer& operator<<(gsl::span<const gsl::byte> span);\n\t\tSerializer& operator<<(const Bytes& bytes);\n\n\t\ttemplate <typename T>\n\t\tSerializer& operator<<(const std::vector<T>& val)\n\t\t{\n\t\t\tunsigned int sz = static_cast<unsigned int>(val.size());\n\t\t\t*this << sz;\n\t\t\tfor (unsigned int i = 0; i < sz; i++) {\n\t\t\t\t*this << val[i];\n\t\t\t}\n\t\t\treturn *this;\n\t\t}\n\t\t\n\t\ttemplate <typename T>\n\t\tSerializer& operator<<(const std::list<T>& val)\n\t\t{\n\t\t\tunsigned int sz = static_cast<unsigned int>(val.size());\n\t\t\t*this << sz;\n\t\t\tfor (const auto& v: val) {\n\t\t\t\t*this << v;\n\t\t\t}\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate <typename T, typename U>\n\t\tSerializer& operator<<(const FlatMap<T, U>& val)\n\t\t{\n\t\t\t*this << static_cast<unsigned int>(val.size());\n\t\t\tfor (auto& kv : val) {\n\t\t\t\t*this << kv.first << kv.second; \n\t\t\t}\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate <typename K, typename V, typename Cmp, typename Allocator>\n\t\tSerializer& operator<<(const std::map<K, V, Cmp, Allocator>& val)\n\t\t{\n\t\t\t*this << static_cast<unsigned int>(val.size());\n\t\t\tfor (auto& kv : val) {\n\t\t\t\t*this << kv.first << kv.second;\n\t\t\t}\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate <typename T, typename U>\n\t\tSerializer& operator<<(const std::unordered_map<T, U>& val)\n\t\t{\n\t\t\tstd::map<T, U> m;\n\t\t\tfor (auto& kv: val) {\n\t\t\t\tm[kv.first] = kv.second;\n\t\t\t}\n\t\t\treturn (*this << m);\n\t\t}\n\n\t\ttemplate <typename T>\n\t\tSerializer& operator<<(const std::set<T>& val)\n\t\t{\n\t\t\tunsigned int sz = static_cast<unsigned int>(val.size());\n\t\t\t*this << sz;\n\t\t\tfor (auto& v: val) {\n\t\t\t\t*this << v;\n\t\t\t}\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate <typename T>\n\t\tSerializer& operator<<(const Vector2D<T>& val)\n\t\t{\n\t\t\treturn *this << val.x << val.y;\n\t\t}\n\n\t\ttemplate <typename T>\n\t\tSerializer& operator<<(const Vector4D<T>& val)\n\t\t{\n\t\t\treturn *this << val.x << val.y << val.z << val.w;\n\t\t}\n\n\t\ttemplate <typename T>\n\t\tSerializer& operator<<(const Colour4<T>& val)\n\t\t{\n\t\t\treturn *this << val.r << val.g << val.b << val.a;\n\t\t}\n\n\t\ttemplate <typename T>\n\t\tSerializer& operator<<(const Rect2D<T>& val)\n\t\t{\n\t\t\treturn *this << val.getTopLeft() << val.getBottomRight();\n\t\t}\n\n\t\ttemplate <typename T, typename U>\n\t\tSerializer& operator<<(const std::pair<T, U>& p)\n\t\t{\n\t\t\treturn *this << p.first << p.second;\n\t\t}\n\t\t\n\t\ttemplate <typename T>\n\t\tSerializer& operator<<(const std::optional<T>& p)\n\t\t{\n\t\t\tif (p) {\n\t\t\t\treturn *this << true << p.value();\n\t\t\t} else {\n\t\t\t\treturn *this << false;\n\t\t\t}\n\t\t}\n\n\t\ttemplate <typename T>\n\t\tSerializer& operator<<(const Range<T>& p)\n\t\t{\n\t\t\treturn *this << p.start << p.end;\n\t\t}\n\n\t\ttemplate <typename T, std::enable_if_t<std::is_enum<T>::value == true, int> = 0>\n\t\tSerializer& operator<<(const T& val)\n\t\t{\n\t\t\tusing B = typename std::underlying_type<T>::type;\n\t\t\treturn *this << B(val);\n\t\t}\n\n\t\ttemplate <typename T, std::enable_if_t<std::is_enum<T>::value == false, int> = 0>\n\t\tSerializer& operator<<(const T& val)\n\t\t{\n\t\t\tval.serialize(*this);\n\t\t\treturn *this;\n\t\t}\n\n\t\tsize_t getPosition() const { return size; }\n\n\tprivate:\n\t\tsize_t size = 0;\n\t\tgsl::span<gsl::byte> dst;\n\t\tbool dryRun;\n\n\t\ttemplate <typename T>\n\t\tSerializer& serializePod(T val)\n\t\t{\n\t\t\tif (!dryRun) {\n\t\t\t\tmemcpy(dst.data() + size, &val, sizeof(T));\n\t\t\t}\n\t\t\tsize += sizeof(T);\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate <typename T>\n\t\tSerializer& serializeInteger(T val)\n\t\t{\n\t\t\tif (options.version >= 1) {\n\t\t\t\t// Variable-length\n\t\t\t\tif constexpr (std::is_signed_v<T>) {\n\t\t\t\t\tserializeVariableInteger(static_cast<uint64_t>(val >= 0 ? val : -(val + 1)), val < 0);\n\t\t\t\t} else {\n\t\t\t\t\tserializeVariableInteger(val, {});\n\t\t\t\t}\n\t\t\t\treturn *this;\n\t\t\t} else {\n\t\t\t\t// Fixed length\n\t\t\t\treturn serializePod(val);\n\t\t\t}\n\t\t}\n\n\t\tvoid serializeVariableInteger(uint64_t val, std::optional<bool> sign);\n\t};\n\n\tclass Deserializer : public ByteSerializationBase {\n\tpublic:\n\t\tDeserializer(gsl::span<const gsl::byte> src, SerializerOptions options = {});\n\t\tDeserializer(const Bytes& src, SerializerOptions options = {});\n\t\t\n\t\ttemplate <typename T>\n\t\tstatic T fromBytes(const Bytes& src, SerializerOptions options = {})\n\t\t{\n\t\t\tT result;\n\t\t\tDeserializer s(src, std::move(options));\n\t\t\ts >> result;\n\t\t\treturn result;\n\t\t}\n\n\t\ttemplate <typename T>\n\t\tstatic T fromBytes(gsl::span<const gsl::byte> src, SerializerOptions options = {})\n\t\t{\n\t\t\tT result;\n\t\t\tDeserializer s(src, std::move(options));\n\t\t\ts >> result;\n\t\t\treturn result;\n\t\t}\n\n\t\ttemplate <typename T>\n\t\tstatic void fromBytes(T& target, const Bytes& src, SerializerOptions options = {})\n\t\t{\n\t\t\tDeserializer s(src, std::move(options));\n\t\t\ts >> target;\n\t\t}\n\n\t\ttemplate <typename T>\n\t\tstatic void fromBytes(T& target, gsl::span<const gsl::byte> src, SerializerOptions options = {})\n\t\t{\n\t\t\tDeserializer s(src, std::move(options));\n\t\t\ts >> target;\n\t\t}\n\n\t\tDeserializer& operator>>(bool& val) { return deserializePod(val); }\n\t\tDeserializer& operator>>(int8_t& val) { return deserializeInteger(val); }\n\t\tDeserializer& operator>>(uint8_t& val) { return deserializeInteger(val); }\n\t\tDeserializer& operator>>(int16_t& val) { return deserializeInteger(val); }\n\t\tDeserializer& operator>>(uint16_t& val) { return deserializeInteger(val); }\n\t\tDeserializer& operator>>(int32_t& val) { return deserializeInteger(val); }\n\t\tDeserializer& operator>>(uint32_t& val) { return deserializeInteger(val); }\n\t\tDeserializer& operator>>(int64_t& val) { return deserializeInteger(val); }\n\t\tDeserializer& operator>>(uint64_t& val) { return deserializeInteger(val); }\n\t\tDeserializer& operator>>(float& val) { return deserializePod(val); }\n\t\tDeserializer& operator>>(double& val) { return deserializePod(val); }\n\n\t\tDeserializer& operator>>(std::string& str);\n\t\tDeserializer& operator>>(String& str);\n\t\tDeserializer& operator>>(StringUTF32& str);\n\t\tDeserializer& operator>>(Path& p);\n\t\tDeserializer& operator>>(gsl::span<gsl::byte> span);\n\t\tDeserializer& operator>>(Bytes& bytes);\n\n\t\ttemplate <typename T>\n\t\tDeserializer& operator>>(std::vector<T>& val)\n\t\t{\n\t\t\tunsigned int sz;\n\t\t\t*this >> sz;\n\t\t\tensureSufficientBytesRemaining(sz); // Expect at least one byte per vector entry\n\n\t\t\tval.clear();\n\t\t\tval.reserve(sz);\n\t\t\tfor (unsigned int i = 0; i < sz; i++) {\n\t\t\t\tval.push_back(T());\n\t\t\t\t*this >> val[i];\n\t\t\t}\n\t\t\treturn *this;\n\t\t}\n\t\t\n\t\ttemplate <typename T>\n\t\tDeserializer& operator>>(std::list<T>& val)\n\t\t{\n\t\t\tunsigned int sz;\n\t\t\t*this >> sz;\n\t\t\tensureSufficientBytesRemaining(sz); // Expect at least one byte per vector entry\n\n\t\t\tval.clear();\n\t\t\tfor (unsigned int i = 0; i < sz; i++) {\n\t\t\t\tT v;\n\t\t\t\t*this >> v;\n\t\t\t\tval.push_back(std::move(v));\n\t\t\t}\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate <typename T, typename U>\n\t\tDeserializer& operator>>(FlatMap<T, U>& val)\n\t\t{\n\t\t\tunsigned int sz;\n\t\t\t*this >> sz;\n\t\t\tensureSufficientBytesRemaining(sz * 2); // Expect at least two bytes per map entry\n\n\t\t\tstd::vector<std::pair<T, U>> tmpData(sz);\n\t\t\tfor (unsigned int i = 0; i < sz; i++) {\n\t\t\t\t*this >> tmpData[i].first >> tmpData[i].second;\n\t\t\t}\n\t\t\tval = FlatMap<T, U>(boost::container::ordered_unique_range_t(), tmpData.begin(), tmpData.end());\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate <typename K, typename V, typename Cmp, typename Allocator>\n\t\tDeserializer& operator >> (std::map<K, V, Cmp, Allocator>& val)\n\t\t{\n\t\t\tunsigned int sz;\n\t\t\t*this >> sz;\n\t\t\tensureSufficientBytesRemaining(size_t(sz) * 2); // Expect at least two bytes per map entry\n\n\t\t\tfor (unsigned int i = 0; i < sz; i++) {\n\t\t\t\tK key;\n\t\t\t\tV value;\n\t\t\t\t*this >> key >> value;\n\t\t\t\tval[key] = std::move(value);\n\t\t\t}\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate <typename T, typename U>\n\t\tDeserializer& operator >> (std::unordered_map<T, U>& val)\n\t\t{\n\t\t\tunsigned int sz;\n\t\t\t*this >> sz;\n\t\t\tensureSufficientBytesRemaining(sz * 2); // Expect at least two bytes per map entry\n\n\t\t\tfor (unsigned int i = 0; i < sz; i++) {\n\t\t\t\tT key;\n\t\t\t\tU value;\n\t\t\t\t*this >> key >> value;\n\t\t\t\tval[key] = std::move(value);\n\t\t\t}\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate <typename T>\n\t\tDeserializer& operator>>(std::set<T>& val)\n\t\t{\n\t\t\tunsigned int sz;\n\t\t\t*this >> sz;\n\t\t\tensureSufficientBytesRemaining(sz); // Expect at least one byte per set entry\n\n\t\t\tval.clear();\n\t\t\tfor (unsigned int i = 0; i < sz; i++) {\n\t\t\t\tT v;\n\t\t\t\t*this >> v;\n\t\t\t\tval.insert(std::move(v));\n\t\t\t}\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate <typename T>\n\t\tDeserializer& operator>>(Vector2D<T>& val)\n\t\t{\n\t\t\t*this >> val.x;\n\t\t\t*this >> val.y;\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate <typename T>\n\t\tDeserializer& operator>>(Vector4D<T>& val)\n\t\t{\n\t\t\t*this >> val.x;\n\t\t\t*this >> val.y;\n\t\t\t*this >> val.z;\n\t\t\t*this >> val.w;\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate <typename T>\n\t\tDeserializer& operator>>(Colour4<T>& val)\n\t\t{\n\t\t\t*this >> val.r;\n\t\t\t*this >> val.g;\n\t\t\t*this >> val.b;\n\t\t\t*this >> val.a;\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate <typename T>\n\t\tDeserializer& operator>>(Rect2D<T>& val)\n\t\t{\n\t\t\tVector2D<T> p1, p2;\n\t\t\t*this >> p1;\n\t\t\t*this >> p2;\n\t\t\tval = Rect2D<T>(p1, p2);\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate <typename T, typename U>\n\t\tDeserializer& operator>>(std::pair<T, U>& p)\n\t\t{\n\t\t\treturn *this >> p.first >> p.second;\n\t\t}\n\n\t\ttemplate <typename T>\n\t\tDeserializer& operator>>(Range<T>& p)\n\t\t{\n\t\t\treturn *this >> p.start >> p.end;\n\t\t}\n\n\t\ttemplate <typename T>\n\t\tDeserializer& operator>>(std::optional<T>& p)\n\t\t{\n\t\t\tbool present;\n\t\t\t*this >> present;\n\t\t\tif (present) {\n\t\t\t\tT tmp;\n\t\t\t\t*this >> tmp;\n\t\t\t\tp = tmp;\n\t\t\t} else {\n\t\t\t\tp = std::optional<T>();\n\t\t\t}\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate <typename T, std::enable_if_t<std::is_enum<T>::value == true, int> = 0>\n\t\tDeserializer& operator>>(T& val)\n\t\t{\n\t\t\ttypename std::underlying_type<T>::type tmp;\n\t\t\t*this >> tmp;\n\t\t\tval = T(tmp);\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate <typename T, std::enable_if_t<std::is_enum<T>::value == false, int> = 0>\n\t\tDeserializer& operator>>(T& val)\n\t\t{\n\t\t\tval.deserialize(*this);\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate <typename T>\n\t\tvoid peek(T& val)\n\t\t{\n\t\t\tconst auto oldPos = pos;\n\t\t\t*this >> val;\n\t\t\tpos = oldPos;\n\t\t}\n\n\t\tsize_t getPosition() const { return pos; }\n\n\tprivate:\n\t\tsize_t pos = 0;\n\t\tgsl::span<const gsl::byte> src;\n\n\t\ttemplate <typename T>\n\t\tDeserializer& deserializePod(T& val)\n\t\t{\n\t\t\tensureSufficientBytesRemaining(sizeof(T));\n\t\t\tmemcpy(&val, src.data() + pos, sizeof(T));\n\t\t\tpos += sizeof(T);\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate <typename T>\n\t\tDeserializer& deserializeInteger(T& val)\n\t\t{\n\t\t\tif (options.version >= 1) {\n\t\t\t\t// Variable-length\n\t\t\t\tbool sign;\n\t\t\t\tuint64_t temp;\n\t\t\t\tdeserializeVariableInteger(temp, sign, std::is_signed_v<T>);\n\t\t\t\tif (sign) {\n\t\t\t\t\tint64_t signedTemp = -int64_t(temp) - 1;\n\t\t\t\t\tval = static_cast<T>(signedTemp);\n\t\t\t\t} else {\n\t\t\t\t\tval = static_cast<T>(temp);\n\t\t\t\t}\n\t\t\t\treturn *this;\n\t\t\t} else {\n\t\t\t\t// Fixed length\n\t\t\t\treturn deserializePod(val);\n\t\t\t}\n\t\t}\n\n\t\tvoid deserializeVariableInteger(uint64_t& val, bool& sign, bool isSigned);\n\n\t\tvoid ensureSufficientBytesRemaining(size_t bytes);\n\t\tsize_t getBytesRemaining() const;\n\t};\n}\n", "meta": {"hexsha": "aa6169803aaa1e3ce89e9f924e72314871250691", "size": 13836, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engine/utils/include/halley/bytes/byte_serializer.h", "max_stars_repo_name": "JLouhela/halley", "max_stars_repo_head_hexsha": "eb395c8cc5ab6fb4aa1966ce3d7a9c1b8301d587", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3262.0, "max_stars_repo_stars_event_min_datetime": "2016-04-10T15:24:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:47:08.000Z", "max_issues_repo_path": "src/engine/utils/include/halley/bytes/byte_serializer.h", "max_issues_repo_name": "JLouhela/halley", "max_issues_repo_head_hexsha": "eb395c8cc5ab6fb4aa1966ce3d7a9c1b8301d587", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 53.0, "max_issues_repo_issues_event_min_datetime": "2016-10-09T16:25:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-10T13:52:37.000Z", "max_forks_repo_path": "src/engine/utils/include/halley/bytes/byte_serializer.h", "max_forks_repo_name": "JLouhela/halley", "max_forks_repo_head_hexsha": "eb395c8cc5ab6fb4aa1966ce3d7a9c1b8301d587", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 193.0, "max_forks_repo_forks_event_min_datetime": "2017-10-23T06:08:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T12:59:58.000Z", "avg_line_length": 25.2021857923, "max_line_length": 129, "alphanum_fraction": 0.6385516045, "num_tokens": 3975, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22270012850745968, "lm_q2_score": 0.024053552500896167, "lm_q1q2_score": 0.005356729233010504}}
{"text": "/*\n * Subroutines that deal with the aXe configuration file.\n *\n */\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <gsl/gsl_vector.h>\n#include \"aper_conf.h\"\n#include \"disp_conf.h\"\n#include \"aXe_grism.h\"\n#include \"spc_cfg.h\"\n#include \"disp_conf.h\"\n#include \"aXe_utils.h\"\n\n#define MAX(x,y) (((x)>(y))?(x):(y))\n\n/**\n *  Function: get_aperture_descriptor\n *  Read a configuration file and populate an aperture_conf structure\n *  containing a description of the optical set up.\n *  This function populates the geometrical description of all the beams in\n *  all the apertures listed in the configuration file.\n *\n *  Parameters:\n *  @param actinfo  - the header structure with the column names\n *  @param filename - the complete filename to the axe configuration file\n *\n *  Returns:\n *  @return config - the configuration structure created\n */\naperture_conf *\nget_aperture_descriptor (char *filename)\n{\n  char beam[MAXCHAR] = \"\\0\";\n  aperture_conf *config;\n  int i, ix;\n  gsl_vector *v;\n\n  struct CfgStrings AperConfig[] = {\n    {\"INSTRUMENT\", NULL},\n    {\"CAMERA\", NULL},\n    {\"SCIENCE_EXT\", NULL},\n    {\"ERRORS_EXT\", NULL},\n    {\"DQ_EXT\",NULL},\n    {\"DQMASK\",NULL},\n    {\"EXPTIME\",NULL},\n    {\"GAIN\",NULL},\n    {\"OPTKEY1\",NULL},\n    {\"OPTVAL1\",NULL},\n    {\"FFNAME\",NULL},\n    {\"REFX\",NULL},\n    {\"REFY\",NULL},\n    /* aXe1.4:*/\n    {\"DRZRESOLA\",NULL},\n    {\"DRZSCALE\",NULL},\n    {\"DRZLAMB0\",NULL},\n    {\"DRZXINI\",NULL},\n    {\"DRZPFRAC\",NULL},\n    {\"DRZKERNEL\",NULL},\n    /* aXe1.5: */\n    {\"PSFCOEFFS\",NULL},\n    {\"PSFRANGE\",NULL},\n    {\"RDNOISE\",NULL},\n    /* NICMOS HLA */\n    {\"IPIXFUNCTION\",NULL},\n    {\"POBJSIZE\",NULL},\n    {\"SMFACTOR\",NULL},\n\n    {NULL, NULL},\n    {NULL, NULL}                /* array terminator. REQUIRED !!! */\n  };\n\n  struct CfgStrings BeamConfig[] = {\n    {NULL, NULL},\n    {NULL, NULL}\n  };\n\n  AperConfig[25].name = beam;\n  BeamConfig[0].name = beam;\n\n\n  config = malloc (sizeof (aperture_conf));\n  if (config == NULL)\n    {\n      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n                   \"Could not allocate memory for aperture configuration\");\n    }\n\n  CfgRead (filename, AperConfig);\n\n  /* Initialize optional keywords to default values*/\n  sprintf(config->instrument,\"None\");\n  sprintf(config->camera,\"None\");\n  sprintf(config->science_ext,\"None\");\n  sprintf(config->errors_ext,\"None\");\n  sprintf(config->dq_ext,\"None\");\n  sprintf(config->exptimekey,\"None\");\n  sprintf(config->gainkey,\"None\");\n  config->dqmask=0;\n  sprintf(config->optkey1,\"None\");\n  sprintf(config->optval1,\"None\");\n  sprintf(config->FFname,\"None\");\n  sprintf(config->IPIXfunc,\"None\");\n  sprintf(config->drz_kernel,\"square\");\n  config->refx       = 0;\n  config->refy       = 0;\n  config->drz_resol  = 0.0;\n  config->drz_scale  = 0.0;\n  config->drz_lamb0  = 0.0;\n  config->drz_xstart = 15.0;\n  config->drz_pfrac  = 1.0;\n  config->psfcoeffs  = NULL;\n  config->psfrange   = NULL;\n  config->rdnoise    = 0.0;\n  config->pobjsize   = -1.0;\n  config->smfactor   = -1.0;\n\n  for (ix = 0; ix < 26; ix++)\n    {\n\n      /* Name of the instrument */\n      if (!strcmp (AperConfig[ix].name, \"INSTRUMENT\"))\n        {\n          if (AperConfig[ix].data == NULL)\n            aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n                         \"INSTRUMENT tag was not read from %s\\n\",\n                         filename);\n          sprintf (config->instrument, \"%s\", AperConfig[ix].data);\n        }\n\n      /* Name of the camera */\n      if (!strcmp (AperConfig[ix].name, \"CAMERA\"))\n        {\n          if (AperConfig[ix].data == NULL)\n            aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n                         \"camera tag was not read from %s\\n\",\n                         filename);\n          sprintf (config->camera, \"%s\", AperConfig[ix].data);\n        }\n\n      /* Name of the Science data extension */\n      if (!strcmp (AperConfig[ix].name, \"SCIENCE_EXT\"))\n        {\n          if (AperConfig[ix].data != NULL)\n            sprintf (config->science_ext, \"%s\", AperConfig[ix].data);\n        }\n\n      /* Name of the optional Error FITS extension */\n      if (!strcmp (AperConfig[ix].name, \"ERRORS_EXT\"))\n        {\n          if (AperConfig[ix].data != NULL)\n            {\n              sprintf (config->errors_ext, \"%s\", AperConfig[ix].data);\n            }\n        }\n\n      /* Name of the optional Data Quality FITS extension */\n      if (!strcmp (AperConfig[ix].name, \"DQ_EXT\"))\n        {\n          if (AperConfig[ix].data != NULL)\n            {\n              sprintf (config->dq_ext, \"%s\", AperConfig[ix].data);\n            }\n        }\n\n      /* Name of the optional EXPTIME FITS keyword */\n      if (!strcmp (AperConfig[ix].name, \"EXPTIME\"))\n        {\n          if (AperConfig[ix].data != NULL)\n            {\n              sprintf (config->exptimekey, \"%s\", AperConfig[ix].data);\n            }\n        }\n\n      /* Red in the readout noise */\n      if (!strcmp (AperConfig[ix].name, \"RDNOISE\"))\n        {\n          if (AperConfig[ix].data != NULL)\n            {\n              config->rdnoise = atof(AperConfig[ix].data);\n            }\n        }\n\n      /* Name of the optional GAIN FITS keyword */\n      if (!strcmp (AperConfig[ix].name, \"GAIN\"))\n        {\n          if (AperConfig[ix].data != NULL)\n            {\n              sprintf (config->gainkey, \"%s\", AperConfig[ix].data);\n            }\n        }\n\n      /* Gett the Data Quality Mask */\n      if (!strcmp (AperConfig[ix].name, \"DQMASK\"))\n        {\n          if (AperConfig[ix].data != NULL)\n            {\n              config->dqmask = atoi(AperConfig[ix].data);\n            }\n        }\n\n\n      /* Optional OPTional 1st FITS keyword selection */\n      if (!strcmp (AperConfig[ix].name, \"OPTKEY1\"))\n        {\n          if (AperConfig[ix].data != NULL)\n            {\n              sprintf (config->optkey1, \"%s\", AperConfig[ix].data);\n            }\n        }\n\n      /* Optional OPTional 1st FITS keyword value */\n      if (!strcmp (AperConfig[ix].name, \"OPTVAL1\"))\n        {\n          if (AperConfig[ix].data != NULL)\n            {\n              sprintf (config->optval1, \"%s\", AperConfig[ix].data);\n            }\n        }\n\n      /* Optional FFname keyword value */\n      if (!strcmp (AperConfig[ix].name, \"FFNAME\"))\n        {\n          if (AperConfig[ix].data != NULL)\n            {\n              sprintf (config->FFname, \"%s\", AperConfig[ix].data);\n            }\n        }\n\n      /* Optional intra pixel correction keyword value */\n      if (!strcmp (AperConfig[ix].name, \"IPIXFUNCTION\"))\n        {\n          if (AperConfig[ix].data != NULL)\n            {\n              sprintf (config->IPIXfunc, \"%s\", AperConfig[ix].data);\n            }\n        }\n\n      /* Optional REFX keyword value */\n      if (!strcmp (AperConfig[ix].name, \"REFX\"))\n        {\n          if (AperConfig[ix].data != NULL)\n            {\n              config->refx = atoi(AperConfig[ix].data);\n            }\n        }\n\n      /* Optional REFY keyword value */\n      if (!strcmp (AperConfig[ix].name, \"REFY\"))\n        {\n          if (AperConfig[ix].data != NULL)\n            {\n              config->refy = atoi(AperConfig[ix].data);\n            }\n        }\n      if (!strcmp (AperConfig[ix].name, \"DRZRESOLA\"))\n        {\n          if (AperConfig[ix].data != NULL)\n            {\n              config->drz_resol = atof(AperConfig[ix].data);\n            }\n        }\n      if (!strcmp (AperConfig[ix].name, \"DRZSCALE\"))\n        {\n          if (AperConfig[ix].data != NULL)\n            {\n              config->drz_scale = atof(AperConfig[ix].data);\n            }\n        }\n      if (!strcmp (AperConfig[ix].name, \"DRZLAMB0\"))\n        {\n          if (AperConfig[ix].data != NULL)\n            {\n              config->drz_lamb0 = atof(AperConfig[ix].data);\n            }\n        }\n      if (!strcmp (AperConfig[ix].name, \"DRZXINI\"))\n        {\n          if (AperConfig[ix].data != NULL)\n            {\n              config->drz_xstart = atof(AperConfig[ix].data);\n            }\n        }\n      if (!strcmp (AperConfig[ix].name, \"DRZPFRAC\"))\n        {\n          if (AperConfig[ix].data != NULL)\n            {\n              config->drz_pfrac = atof(AperConfig[ix].data);\n            }\n        }\n      if (!strcmp (AperConfig[ix].name, \"DRZKERNEL\"))\n        {\n          if (AperConfig[ix].data != NULL)\n            {\n              sprintf (config->drz_kernel, \"%s\", AperConfig[ix].data);\n            }\n        }\n\n      if (!strcmp (AperConfig[ix].name, \"PSFCOEFFS\"))\n        {\n          if (AperConfig[ix].data != NULL)\n            {\n              //              sprintf (config->drz_kernel, \"%s\", AperConfig[ix].data);\n              v = string_to_gsl_array (AperConfig[ix].data);\n              config->psfcoeffs = v;\n            }\n        }\n\n      if (!strcmp (AperConfig[ix].name, \"PSFRANGE\"))\n        {\n          if (AperConfig[ix].data != NULL)\n            {\n              v = string_to_gsl_array (AperConfig[ix].data);\n              if (v->size != 2)\n                aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n                             \"configuration file: two items for PSFRANGE, lambda_min and lambda_max must be given, not %i\\n\", v->size);\n              config->psfrange = v;\n            }\n        }\n\n      // read in the size of point-like objects\n      if (!strcmp (AperConfig[ix].name, \"POBJSIZE\"))\n        {\n          if (AperConfig[ix].data != NULL)\n            {\n              config->pobjsize = atof(AperConfig[ix].data);\n            }\n        }\n\n      // read in the adjustment for smoothed flux conversion\n      if (!strcmp (AperConfig[ix].name, \"SMFACTOR\"))\n        {\n          if (AperConfig[ix].data != NULL)\n            {\n              config->smfactor = atof(AperConfig[ix].data);\n            }\n        }\n\n\n    }\n\n  // release memory\n  i=0;\n  while(AperConfig[i].name!=NULL)\n    free(AperConfig[i++].data);\n\n  /* Looking for up to MAX_BEAMS beams */\n  config->nbeams = 0;\n  for (i = 0; i < MAX_BEAMS; i++)\n    {\n      sprintf (beam, \"BEAM%c\", BEAM (i));\n      CfgRead (filename, BeamConfig);\n      if (BeamConfig[0].data != NULL)\n        {\n          v = string_to_gsl_array (BeamConfig[0].data);\n          if (v->size != 2)\n            {\n              aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n                           \"tag %s does not have the proper format in file %s.\\n\"\n                           \"Should be of the form %s [integer] [integer]\\n\",\n                           BeamConfig[0].data, filename,beam);\n              //                           beam, filename,beam);\n            }\n          (config->beam[config->nbeams]).offset.dx0 =\n            (int) gsl_vector_get (v, 0);\n          (config->beam[config->nbeams]).offset.dx1 =\n            (int) gsl_vector_get (v, 1);\n\n          // release the memory\n          gsl_vector_free(v);\n\n          (config->beam[config->nbeams]).ID = i;\n\n          // release memory\n          ix=0;\n          while(BeamConfig[ix].name!=NULL)\n            free(BeamConfig[ix++].data);\n          BeamConfig[0].data = NULL;\n\n          (config->beam[config->nbeams]).mmag_extract = get_beam_mmag_extract (filename, i);\n          (config->beam[config->nbeams]).mmag_mark = get_beam_mmag_mark (filename, i);\n\n          sprintf (beam, \"PSF_OFFSET_%c\", BEAM (i));\n          CfgRead (filename, BeamConfig);\n          if (BeamConfig[0].data != NULL)\n            {\n              (config->beam[config->nbeams]).psf_offset = atof(BeamConfig[0].data);\n            }\n          else\n            {\n              (config->beam[config->nbeams]).psf_offset = 0.0;\n            }\n\n          // release memory\n          ix=0;\n          while(BeamConfig[ix].name!=NULL)\n            free(BeamConfig[ix++].data);\n\n          BeamConfig[0].data = NULL;\n\n          config->nbeams = config->nbeams + 1;\n        }\n    }\n\n  if (config->nbeams == 0)\n    {\n      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n                   \"No beam was found in %s. At least one beam must be found.\\n\",\n                   filename);\n    }\n  return config;\n}\n\n/**\n * Function: aperture_conf_fprintf\n * Function to output the content of an aperture_conf structure.\n *\n * Parameters:\n * @param file - a pointer to an output stream or file\n * @param conf - a pointer to an existing aperture_conf structure\n */\nvoid\naperture_conf_fprintf (FILE * file, aperture_conf * conf)\n{\n     int i = 0, id;\n\n     fprintf (file, \"Aperture_conf: INSTRUMENT: %s\\n\", conf->instrument);\n     fprintf (file, \"Aperture_conf: NBEAMS: %d\\n\", conf->nbeams);\n     for (i = 0; i < conf->nbeams; i++)\n       {\n         id = conf->beam[i].ID;\n         fprintf (file, \"Aperture_conf: BEAM%c: %d %d\\n\", BEAM (id),\n                  conf->beam[i].offset.dx0, conf->beam[i].offset.dx1);\n       }\n     fprintf (file, \"FITS SCI extension name: %s, number: %d\\n\",\n              conf->science_ext, conf->science_numext);\n     fprintf (file, \"FITS ERR extension name: %s, number: %d\\n\",\n              conf->errors_ext, conf->errors_numext);\n     fprintf (file, \"FITS DQ extension name: %s, number: %d\\n\",\n              conf->dq_ext, conf->dq_numext);\n     fprintf (file, \"DQ mask: %d\\n\",conf->dqmask);\n     fprintf (file, \"FF filename: %s\\n\",conf->FFname);\n     fprintf (file, \"Refx: %d\\n\",conf->refx);\n     fprintf (file, \"Refy: %d\\n\",conf->refy);\n     fprintf (file, \"DRZRESO: %10.3f\\n\",conf->drz_resol);\n     fprintf (file, \"DRZSCALE: %10.3f\\n\",conf->drz_scale);\n     fprintf (file, \"DRZLAMB0: %10.3f\\n\",conf->drz_lamb0);\n     fprintf (file, \"DRZXINI: %10.3f\\n\",conf->drz_xstart);\n     fprintf (file, \"DRZPFRAC: %10.3f\\n\",conf->drz_pfrac);\n     fprintf (file, \"DRZKERNEL: %s\\n\",conf->drz_kernel);\n\n\n}\n\n/**\n * Function: get_extension_numbers\n * This function assigns HDU numbers to an aperture_conf\n * structues after looking for the location of named\n * extension in a given FITS file. Optional values not\n * found are set to -1.\n *\n * Parameters:\n * @param filename - a pointer to a string containing the name\n *                   of an existing FITS file\n * @param conf     - a pointer to a populated aperture_conf structure\n * @param keyword  - a pointer to a string containing the name of\n *                   an optional keyword to read\n * @param keyval   - a pointer to a string containing the value of\n *                   the optional keyword to look for\n */\nvoid\nget_extension_numbers(char filename[], aperture_conf * conf,\n                      char keyword[],char keyval[])\n{\n  int extver = -1;\n\n  conf->science_numext = get_hdunum_from_hduname(filename,\n                                                 conf->science_ext,keyword\n                                                 ,keyval,extver);\n  if (conf->science_numext > -1)\n    extver = (int)get_float_from_keyword(filename, conf->science_numext, \"EXTVER\");\n\n  if (strcmp(conf->errors_ext,\"None\"))\n  {\n    conf->errors_numext = get_hdunum_from_hduname(filename,\n                                                  conf->errors_ext,keyword,\n                                                  keyval,extver);\n  } else {\n    conf->errors_numext = -1;\n  }\n  if (strcmp(conf->dq_ext,\"None\")) {\n    conf->dq_numext = get_hdunum_from_hduname(filename,conf->dq_ext,\n                                              keyword,keyval,extver);\n  } else {\n    conf->dq_numext = -1;\n  }\n}\n\n/**\n * Function: free_aperture_conf\n * The function releases all memory allocated\n * in a configuration structure.\n *\n * Parameters:\n * @param conf - the configuration structure\n */\nvoid\nfree_aperture_conf(aperture_conf * conf)\n{\n  if (conf->psfcoeffs)\n    gsl_vector_free(conf->psfcoeffs);\n  if (conf->psfrange)\n    gsl_vector_free(conf->psfrange);\n  free(conf);\n  conf = NULL;\n}\n\n\n/**\n * Function: get_psf_offset\n * The function extracts and returns the psf-offset\n * stored in a given configuration structure and\n * a given beam\n *\n * Parameters:\n * @param conf - the configuration structure\n * @param beam - the beam\n *\n * Returns:\n * @return psf_offset - the psf-offset for the beam\n */\ndouble\nget_psf_offset(aperture_conf * conf, const beam actbeam)\n{\n  // initialize the offset\n  double psf_offset=0.0;\n\n  int i=0;\n\n  // go over all beams in the configuration structure\n  for (i = 0; i < conf->nbeams; i++)\n    {\n      // check whether the current beam is the\n      // right one\n      if (conf->beam[i].ID == actbeam.ID)\n        // return the offset\n        return conf->beam[i].psf_offset;\n    }\n\n  // return the default offset\n  return psf_offset;\n}\n\n/**\n * Function: get_psf_offset\n * The function extracts and returns the psf-offset\n * stored in a given configuration structure and\n * a given beam\n *\n * Parameters:\n * @param conf - the configuration structure\n * @param beam - the beam\n *\n * Returns:\n * @return psf_offset - the psf-offset for the beam\n */\ndouble\nget_max_offset(aperture_conf * conf)\n{\n  // initialize the offset\n  double max_offset=0.0;\n\n  int i=0;\n\n  // go over all beams in the configuration structure\n  for (i = 0; i < conf->nbeams; i++)\n    {\n      // check whether the current beam is the\n      // right one\n      max_offset = MAX(conf->beam[i].psf_offset, max_offset);\n    }\n\n  // return the default offset\n  return max_offset;\n}\n\n\n/**\n * Function: extend_config_beams\n * The function extends the size of the beams in a\n * configuration structure.\n *\n * Parameters:\n * @param conf - the configuration structure\n */\nvoid\nextend_config_beams(aperture_conf *conf)\n{\n  int index;\n\n  // go over all beams in the configuration structure\n  for (index=0; index < conf->nbeams; index++)\n    {\n      // lower the left border\n      conf->beam[index].offset.dx0 -= BCK_BEAM_EXT;\n\n      // enhance the right border\n      conf->beam[index].offset.dx1 += BCK_BEAM_EXT;\n    }\n}\n", "meta": {"hexsha": "c5e740373e38f8ca929b02d00bc78ca65aa1d063", "size": 17554, "ext": "c", "lang": "C", "max_stars_repo_path": "cextern/src/aper_conf.c", "max_stars_repo_name": "sosey/pyaxe", "max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cextern/src/aper_conf.c", "max_issues_repo_name": "sosey/pyaxe", "max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cextern/src/aper_conf.c", "max_forks_repo_name": "sosey/pyaxe", "max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6830065359, "max_line_length": 135, "alphanum_fraction": 0.5481941438, "num_tokens": 4710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25091279808829703, "lm_q2_score": 0.021287349659081425, "lm_q1q2_score": 0.005341268466844076}}
{"text": "#ifndef __GSL_SPMATRIX_H__\n#define __GSL_SPMATRIX_H__\n\n#if !defined( GSL_FUN )\n#  if !defined( GSL_DLL )\n#    define GSL_FUN extern\n#  elif defined( BUILD_GSL_DLL )\n#    define GSL_FUN extern __declspec(dllexport)\n#  else\n#    define GSL_FUN extern __declspec(dllimport)\n#  endif\n#endif\n\nenum\n{\n  GSL_SPMATRIX_COO = 0, /* coordinate/triplet representation */\n  GSL_SPMATRIX_CSC = 1, /* compressed sparse column */\n  GSL_SPMATRIX_CSR = 2, /* compressed sparse row */\n  GSL_SPMATRIX_TRIPLET = GSL_SPMATRIX_COO,\n  GSL_SPMATRIX_CCS = GSL_SPMATRIX_CSC,\n  GSL_SPMATRIX_CRS = GSL_SPMATRIX_CSR\n};\n\n/* memory pool for binary tree node allocation */\nstruct gsl_spmatrix_pool_node\n{\n  struct gsl_spmatrix_pool_node * next;\n  void * block_ptr;          /* pointer to memory block, of size n*tree_node_size */\n  unsigned char * free_slot; /* pointer to next available slot */\n};\n\ntypedef struct gsl_spmatrix_pool_node gsl_spmatrix_pool;\n\n#define GSL_SPMATRIX_ISCOO(m)         ((m)->sptype == GSL_SPMATRIX_COO)\n#define GSL_SPMATRIX_ISCSC(m)         ((m)->sptype == GSL_SPMATRIX_CSC)\n#define GSL_SPMATRIX_ISCSR(m)         ((m)->sptype == GSL_SPMATRIX_CSR)\n\n#define GSL_SPMATRIX_ISTRIPLET(m)     GSL_SPMATRIX_ISCOO(m)\n#define GSL_SPMATRIX_ISCCS(m)         GSL_SPMATRIX_ISCSC(m)\n#define GSL_SPMATRIX_ISCRS(m)         GSL_SPMATRIX_ISCSR(m)\n\n#define GSL_SPMATRIX_FLG_GROW         (1 << 0) /* allow size of matrix to grow as elements are added */\n#define GSL_SPMATRIX_FLG_FIXED        (1 << 1) /* sparsity pattern is fixed */\n\n/* compare matrix entries (ia,ja) and (ib,jb) - sort by rows first, then by columns */\n#define GSL_SPMATRIX_COMPARE_ROWCOL(m,ia,ja,ib,jb)   ((ia) < (ib) ? -1 : ((ia) > (ib) ? 1 : ((ja) < (jb) ? -1 : ((ja) > (jb)))))\n\n/* common/utility functions */\n\nGSL_FUN void gsl_spmatrix_cumsum(const size_t n, int * c);\n\n#include <gsl/gsl_spmatrix_complex_long_double.h>\n#include <gsl/gsl_spmatrix_complex_double.h>\n#include <gsl/gsl_spmatrix_complex_float.h>\n\n#include <gsl/gsl_spmatrix_long_double.h>\n#include <gsl/gsl_spmatrix_double.h>\n#include <gsl/gsl_spmatrix_float.h>\n\n#include <gsl/gsl_spmatrix_ulong.h>\n#include <gsl/gsl_spmatrix_long.h>\n\n#include <gsl/gsl_spmatrix_uint.h>\n#include <gsl/gsl_spmatrix_int.h>\n\n#include <gsl/gsl_spmatrix_ushort.h>\n#include <gsl/gsl_spmatrix_short.h>\n\n#include <gsl/gsl_spmatrix_uchar.h>\n#include <gsl/gsl_spmatrix_char.h>\n\n#endif /* __GSL_SPMATRIX_H__ */\n", "meta": {"hexsha": "305561b251ca4f59c22fdccc0b96d89f23385e97", "size": 2392, "ext": "h", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_spmatrix.h", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-28T08:20:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-28T08:20:20.000Z", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_spmatrix.h", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_spmatrix.h", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-14T12:45:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-14T12:45:35.000Z", "avg_line_length": 32.7671232877, "max_line_length": 128, "alphanum_fraction": 0.7286789298, "num_tokens": 735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22541661583507672, "lm_q2_score": 0.023689473754921954, "lm_q1q2_score": 0.005340001004748374}}
{"text": "/**\n * This file is part of the \"libterminal\" project\n *   Copyright (c) 2019-2020 Christian Parpart <christian@parpart.family>\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n#pragma once\n\n#include <terminal/GraphicsAttributes.h>\n#include <terminal/Line.h>\n#include <terminal/primitives.h>\n\n#include <crispy/algorithm.h>\n#include <crispy/assert.h>\n#include <crispy/ring.h>\n\n#include <unicode/convert.h>\n\n#include <range/v3/algorithm/copy.hpp>\n#include <range/v3/iterator/insert_iterators.hpp>\n#include <range/v3/view/iota.hpp>\n\n#include <gsl/span>\n#include <gsl/span_ext>\n\n#include <algorithm>\n#include <array>\n#include <sstream>\n#include <string>\n#include <string_view>\n#include <utility>\n\nnamespace terminal\n{\n\n// {{{ Margin\nstruct Margin\n{\n    struct Horizontal\n    {\n        ColumnOffset from;\n        ColumnOffset\n            to; // TODO: call it begin and end and have end point to to+1 to avoid unnecessary +1's later\n\n        [[nodiscard]] constexpr ColumnCount length() const noexcept\n        {\n            return unbox<ColumnCount>(to - from) + ColumnCount(1);\n        }\n        [[nodiscard]] constexpr bool contains(ColumnOffset _value) const noexcept\n        {\n            return from <= _value && _value <= to;\n        }\n        [[nodiscard]] constexpr bool operator==(Horizontal rhs) const noexcept\n        {\n            return from == rhs.from && to == rhs.to;\n        }\n        [[nodiscard]] constexpr bool operator!=(Horizontal rhs) const noexcept { return !(*this == rhs); }\n    };\n\n    struct Vertical\n    {\n        LineOffset from;\n        // TODO: call it begin and end and have end point to to+1 to avoid unnecessary +1's later\n        LineOffset to;\n\n        [[nodiscard]] constexpr LineCount length() const noexcept\n        {\n            return unbox<LineCount>(to - from) + LineCount(1);\n        }\n        [[nodiscard]] constexpr bool contains(LineOffset _value) const noexcept\n        {\n            return from <= _value && _value <= to;\n        }\n        [[nodiscard]] constexpr bool operator==(Vertical const& rhs) const noexcept\n        {\n            return from == rhs.from && to == rhs.to;\n        }\n        [[nodiscard]] constexpr bool operator!=(Vertical const& rhs) const noexcept\n        {\n            return !(*this == rhs);\n        }\n    };\n\n    Vertical vertical {};     // top-bottom\n    Horizontal horizontal {}; // left-right\n};\n\nconstexpr bool operator==(Margin const& a, PageSize b) noexcept\n{\n    return a.horizontal.from.value == 0 && a.horizontal.to.value + 1 == b.columns.value\n           && a.vertical.from.value == 0 && a.vertical.to.value + 1 == b.lines.value;\n}\n\nconstexpr bool operator!=(Margin const& a, PageSize b) noexcept\n{\n    return !(a == b);\n}\n// }}}\n\ntemplate <typename Cell>\nusing Lines = crispy::ring<Line<Cell>>;\n\n/**\n * Represents a logical grid line, i.e. a sequence lines that were written without\n * an explicit linefeed, triggering an auto-wrap.\n */\ntemplate <typename Cell>\nstruct LogicalLine\n{\n    LineOffset top {};\n    LineOffset bottom {};\n    std::vector<std::reference_wrapper<Line<Cell>>> lines {};\n\n    [[nodiscard]] Line<Cell> joinWithRightTrimmed() const\n    {\n        // TODO: determine final line's column count and pass it to ctor.\n        typename Line<Cell>::Buffer output;\n        auto lineFlags = lines.front().get().flags();\n        for (Line<Cell> const& line: lines)\n            for (Cell const& cell: line.cells())\n                output.emplace_back(cell);\n\n        while (!output.empty() && output.back().empty())\n            output.pop_back();\n\n        return Line<Cell>(output, lineFlags);\n    }\n\n    [[nodiscard]] std::string text() const\n    {\n        std::string output;\n        for (auto const& line: lines)\n            output += line.get().toUtf8();\n        return output;\n    }\n};\n\ntemplate <typename Cell>\nbool operator==(LogicalLine<Cell> const& a, LogicalLine<Cell> const& b) noexcept\n{\n    return a.top == b.top && a.bottom == b.bottom;\n}\n\ntemplate <typename Cell>\nbool operator!=(LogicalLine<Cell> const& a, LogicalLine<Cell> const& b) noexcept\n{\n    return !(a == b);\n}\n\ntemplate <typename Cell>\nstruct LogicalLines\n{\n    LineOffset topMostLine;\n    LineOffset bottomMostLine;\n    std::reference_wrapper<Lines<Cell>> lines;\n\n    struct iterator // {{{\n    {\n        std::reference_wrapper<Lines<Cell>> lines;\n        LineOffset top;\n        LineOffset next; // index to next logical line's beginning\n        LineOffset bottom;\n        LogicalLine<Cell> current;\n\n        iterator(std::reference_wrapper<Lines<Cell>> _lines,\n                 LineOffset _top,\n                 LineOffset _next,\n                 LineOffset _bottom):\n            lines { _lines }, top { _top }, next { _next }, bottom { _bottom }\n        {\n            Require(_top <= next);\n            Require(next <= _bottom + 1);\n            ++*this;\n        }\n\n        LogicalLine<Cell> const& operator*() const noexcept { return current; }\n        LogicalLine<Cell> const* operator->() const noexcept { return &current; }\n\n        iterator& operator++()\n        {\n            if (next == bottom + 1)\n            {\n                current.top = next;\n                current.bottom = next;\n                return *this;\n            }\n\n            Require(!lines.get()[unbox<int>(next)].wrapped());\n\n            current.top = LineOffset::cast_from(next);\n            current.lines.clear();\n            do\n                current.lines.emplace_back(lines.get()[unbox<int>(next++)]);\n            while (next <= bottom && lines.get()[unbox<int>(next)].wrapped());\n\n            current.bottom = LineOffset::cast_from(next - 1);\n\n            return *this;\n        }\n\n        iterator& operator--()\n        {\n            if (next == top - 1)\n            {\n                current.top = top - 1;\n                current.bottom = top - 1;\n                return *this;\n            }\n\n            auto const bottomMost = next - 1;\n            do\n                --next;\n            while (lines.get()[unbox<int>(next)].wrapped());\n            auto const topMost = next;\n\n            current.top = topMost;\n            current.bottom = bottomMost;\n\n            current.lines.clear();\n            for (auto i = topMost; i <= bottomMost; ++i)\n                current.lines.emplace_back(lines.get()[unbox<int>(i)]);\n\n            return *this;\n        }\n\n        iterator& operator++(int)\n        {\n            auto c = *this;\n            ++*this;\n            return c;\n        }\n        iterator& operator--(int)\n        {\n            auto c = *this;\n            --*this;\n            return c;\n        }\n\n        bool operator==(iterator const& other) const noexcept { return current == other.current; }\n        bool operator!=(iterator const& other) const noexcept { return current != other.current; }\n    }; // }}}\n\n    iterator begin() const { return iterator(lines, topMostLine, topMostLine, bottomMostLine); }\n    iterator end() const { return iterator(lines, topMostLine, bottomMostLine + 1, bottomMostLine); }\n};\n\ntemplate <typename Cell>\nstruct ReverseLogicalLines\n{\n    LineOffset topMostLine;\n    LineOffset bottomMostLine;\n    std::reference_wrapper<Lines<Cell>> lines;\n\n    struct iterator // {{{\n    {\n        std::reference_wrapper<Lines<Cell>> lines;\n        LineOffset top;\n        LineOffset next; // index to next logical line's beginning\n        LineOffset bottom;\n        LogicalLine<Cell> current;\n\n        iterator(std::reference_wrapper<Lines<Cell>> _lines,\n                 LineOffset _top,\n                 LineOffset _next,\n                 LineOffset _bottom):\n            lines { _lines }, top { _top }, next { _next }, bottom { _bottom }\n        {\n            Require(_top - 1 <= next);\n            Require(next <= _bottom);\n            ++*this;\n        }\n\n        LogicalLine<Cell> const& operator*() const noexcept { return current; }\n\n        iterator& operator--()\n        {\n            if (next == bottom + 1)\n            {\n                current.top = bottom + 1;\n                current.bottom = bottom + 1;\n                return *this;\n            }\n\n            Require(!lines.get()[unbox<int>(next)].wrapped());\n\n            current.top = LineOffset::cast_from(next);\n            current.lines.clear();\n            do\n                current.lines.emplace_back(lines.get()[unbox<int>(next++)]);\n            while (next <= bottom && lines.get()[unbox<int>(next)].wrapped());\n\n            current.bottom = LineOffset::cast_from(next - 1);\n\n            return *this;\n        }\n\n        iterator& operator++()\n        {\n            if (next == top - 1)\n            {\n                current.top = next;\n                current.bottom = next;\n                return *this;\n            }\n\n            auto const bottomMost = next;\n            while (lines.get()[unbox<int>(next)].wrapped())\n                --next;\n            auto const topMost = next;\n            --next; // jump to next logical line's bottom line above the current logical one\n\n            current.top = topMost;\n            current.bottom = bottomMost;\n\n            current.lines.clear();\n            for (auto i = topMost; i <= bottomMost; ++i)\n                current.lines.emplace_back(lines.get()[unbox<int>(i)]);\n\n            return *this;\n        }\n\n        iterator& operator++(int)\n        {\n            auto c = *this;\n            ++*this;\n            return c;\n        }\n        iterator& operator--(int)\n        {\n            auto c = *this;\n            --*this;\n            return c;\n        }\n\n        bool operator==(iterator const& other) const noexcept { return current == other.current; }\n        bool operator!=(iterator const& other) const noexcept { return current != other.current; }\n    }; // }}}\n\n    iterator begin() const { return iterator(lines, topMostLine, bottomMostLine, bottomMostLine); }\n    iterator end() const { return iterator(lines, topMostLine, topMostLine - 1, bottomMostLine); }\n};\n\n/**\n * Manages the screen grid buffer (main screen + scrollback history).\n *\n * <h3>Future motivations</h3>\n *\n * <ul>\n *   <li>manages text reflow upon resize\n *   <li>manages underlying disk storage for very old scrollback history lines.\n * </ul>\n *\n * <h3>Layout</h3>\n *\n * <pre>\n *      +0========================-3+   <-- scrollback top\n *      |1                        -2|\n *      |2   Scrollback history   -1|\n *      |3                         0|   <-- scrollback bottom\n *      +4-------------------------1+   <-- main page top\n *      |5                         2|\n *      |6   main page area        3|\n *      |7                         4|   <-- main page bottom\n *      +---------------------------+\n *       ^                          ^\n *       1                          pageSize.columns\n * </pre>\n */\ntemplate <typename Cell>\nclass Grid\n{\n    // TODO: Rename all \"History\" to \"Scrollback\"?\n  public:\n    Grid(PageSize _pageSize, bool _reflowOnResize, LineCount _maxHistoryLineCount);\n\n    Grid(): Grid(PageSize { LineCount(25), ColumnCount(80) }, false, LineCount(0)) {}\n\n    void reset();\n\n    // {{{ grid global properties\n    [[nodiscard]] LineCount maxHistoryLineCount() const noexcept { return maxHistoryLineCount_; }\n    void setMaxHistoryLineCount(LineCount _maxHistoryLineCount);\n\n    [[nodiscard]] LineCount totalLineCount() const noexcept { return maxHistoryLineCount_ + pageSize_.lines; }\n\n    [[nodiscard]] LineCount historyLineCount() const noexcept\n    {\n        return std::min(maxHistoryLineCount_, linesUsed_ - pageSize_.lines);\n    }\n\n    [[nodiscard]] bool reflowOnResize() const noexcept { return reflowOnResize_; }\n    void setReflowOnResize(bool _enabled) { reflowOnResize_ = _enabled; }\n\n    [[nodiscard]] PageSize pageSize() const noexcept { return pageSize_; }\n\n    /// Resizes the main page area of the grid and adapts the scrollback area's width accordingly.\n    ///\n    /// @param _pageSize          new size of the main page area\n    /// @param _currentCursorPos  current cursor position\n    /// @param _wrapPending       AutoWrap is on and a wrap is pending\n    ///\n    /// @returns updated cursor position.\n    [[nodiscard]] CellLocation resize(PageSize _pageSize, CellLocation _currentCursorPos, bool _wrapPending);\n    // }}}\n\n    // {{{ Line API\n    /// @returns reference to Line at given relative offset @p _line.\n    Line<Cell>& lineAt(LineOffset _line) noexcept;\n    Line<Cell> const& lineAt(LineOffset _line) const noexcept;\n\n    gsl::span<Cell const> lineBuffer(LineOffset _line) const noexcept { return lineAt(_line).cells(); }\n    gsl::span<Cell const> lineBufferRightTrimmed(LineOffset _line) const noexcept;\n\n    [[nodiscard]] std::string lineText(LineOffset _line) const;\n    [[nodiscard]] std::string lineTextTrimmed(LineOffset _line) const;\n    [[nodiscard]] std::string lineText(Line<Cell> const& _line) const;\n\n    void setLineText(LineOffset _line, std::string_view _text);\n\n    // void resetLine(LineOffset _line, GraphicsAttributes _attribs) noexcept\n    // { lineAt(_line).reset(_attribs); }\n\n    [[nodiscard]] ColumnCount lineLength(LineOffset _line) const noexcept { return lineAt(_line).size(); }\n    [[nodiscard]] bool isLineBlank(LineOffset _line) const noexcept;\n    [[nodiscard]] bool isLineWrapped(LineOffset _line) const noexcept;\n\n    [[nodiscard]] int computeLogicalLineNumberFromBottom(LineCount _n) const noexcept;\n\n    [[nodiscard]] size_t zero_index() const noexcept { return lines_.zero_index(); }\n    // }}}\n\n    /// Gets a reference to the cell relative to screen origin (top left, 0:0).\n    [[nodiscard]] Cell& useCellAt(LineOffset _line, ColumnOffset _column) noexcept;\n    [[nodiscard]] Cell& at(LineOffset _line, ColumnOffset _column) noexcept;\n    [[nodiscard]] Cell const& at(LineOffset _line, ColumnOffset _column) const noexcept;\n\n    // page view API\n    gsl::span<Line<Cell>> pageAtScrollOffset(ScrollOffset _scrollOffset);\n    gsl::span<Line<Cell> const> pageAtScrollOffset(ScrollOffset _scrollOffset) const;\n    gsl::span<Line<Cell>> mainPage();\n    gsl::span<Line<Cell> const> mainPage() const;\n\n    LogicalLines<Cell> logicalLines()\n    {\n        return LogicalLines<Cell> { boxed_cast<LineOffset>(-historyLineCount()),\n                                    boxed_cast<LineOffset>(pageSize_.lines - 1),\n                                    lines_ };\n    }\n\n    ReverseLogicalLines<Cell> logicalLinesReverse()\n    {\n        return ReverseLogicalLines<Cell> { boxed_cast<LineOffset>(-historyLineCount()),\n                                           boxed_cast<LineOffset>(pageSize_.lines - 1),\n                                           lines_ };\n    }\n\n    // {{{ buffer manipulation\n\n    /// Completely deletes all scrollback lines.\n    void clearHistory();\n\n    /// Scrolls up by @p _n lines within the given margin.\n    ///\n    /// @param _n number of lines to scroll up within the given margin.\n    /// @param _defaultAttributes SGR attributes the newly created grid cells will be initialized with.\n    /// @param _margin the margin coordinates to perform the scrolling action into.\n    LineCount scrollUp(LineCount _n, GraphicsAttributes _defaultAttributes, Margin _margin) noexcept;\n\n    /// Scrolls up main page by @p _n lines and re-initializes grid cells with @p _defaultAttributes.\n    LineCount scrollUp(LineCount _n, GraphicsAttributes _defaultAttributes = {}) noexcept;\n\n    /// Scrolls down by @p _n lines within the given margin.\n    ///\n    /// @param _n number of lines to scroll down within the given margin.\n    /// @param _defaultAttributes SGR attributes the newly created grid cells will be initialized with.\n    /// @param _margin the margin coordinates to perform the scrolling action into.\n    void scrollDown(LineCount _n, GraphicsAttributes const& _defaultAttributes, Margin const& _margin);\n\n    // Scrolls the data within the margins to the left filling the new space on the right with empty cells.\n    void scrollLeft(GraphicsAttributes _defaultAttributes, Margin _margin) noexcept;\n    // }}}\n\n    // {{{ Rendering API\n    /// Renders the full screen by passing every grid cell to the callback.\n    template <typename RendererT>\n    void render(RendererT&& _render, ScrollOffset _scrollOffset = {}) const;\n\n    /// Takes text-screenshot of the main page.\n    [[nodiscard]] std::string renderMainPageText() const;\n\n    /// Renders the full grid's text characters.\n    ///\n    /// Empty cells are represented as strings and lines split by LF.\n    [[nodiscard]] std::string renderAllText() const;\n    // }}}\n\n    [[nodiscard]] constexpr LineFlags defaultLineFlags() const noexcept;\n\n    [[nodiscard]] constexpr LineCount linesUsed() const noexcept;\n\n    void verifyState() const;\n\n  private:\n    CellLocation growLines(LineCount _newHeight, CellLocation _cursor);\n    void appendNewLines(LineCount _count, GraphicsAttributes _attr);\n    void clampHistory();\n\n    // {{{ buffer helpers\n    void resizeBuffers(PageSize _newSize)\n    {\n        auto const newTotalLineCount = historyLineCount() + _newSize.lines;\n        lines_.resize(unbox<size_t>(newTotalLineCount));\n        pageSize_ = _newSize;\n    }\n\n    void rezeroBuffers() noexcept { lines_.rezero(); }\n\n    void rotateBuffers(int offset) noexcept { lines_.rotate(offset); }\n\n    void rotateBuffersLeft(LineCount count) noexcept { lines_.rotate_left(unbox<size_t>(count)); }\n\n    void rotateBuffersRight(LineCount count) noexcept { lines_.rotate_right(unbox<size_t>(count)); }\n    // }}}\n\n    // private fields\n    //\n    PageSize pageSize_;\n    bool reflowOnResize_ = false;\n    LineCount maxHistoryLineCount_;\n\n    // Number of lines is at least the sum of maxHistoryLineCount_ + pageSize_.lines,\n    // because shrinking the page height does not necessarily\n    // have to resize the array (as optimization).\n    Lines<Cell> lines_;\n\n    // Number of lines used in the Lines buffer.\n    LineCount linesUsed_;\n};\n\ntemplate <typename Cell>\nstd::ostream& dumpGrid(std::ostream& os, Grid<Cell> const& grid);\n\ntemplate <typename Cell>\nstd::string dumpGrid(Grid<Cell> const& grid);\n\n// {{{ impl\ntemplate <typename Cell>\nconstexpr LineFlags Grid<Cell>::defaultLineFlags() const noexcept\n{\n    return reflowOnResize_ ? LineFlags::Wrappable : LineFlags::None;\n}\n\ntemplate <typename Cell>\nconstexpr LineCount Grid<Cell>::linesUsed() const noexcept\n{\n    return linesUsed_;\n}\n\ntemplate <typename Cell>\nbool Grid<Cell>::isLineWrapped(LineOffset _line) const noexcept\n{\n    return _line >= -boxed_cast<LineOffset>(historyLineCount())\n           && boxed_cast<LineCount>(_line) < pageSize_.lines && lineAt(_line).wrapped();\n}\n\ntemplate <typename Cell>\ntemplate <typename RendererT>\nvoid Grid<Cell>::render(RendererT&& _render, ScrollOffset _scrollOffset) const\n{\n    assert(!_scrollOffset || unbox<LineCount>(_scrollOffset) <= historyLineCount());\n\n    auto y = LineOffset(0);\n    for (int i = -*_scrollOffset, e = i + *pageSize_.lines; i != e; ++i, ++y)\n    {\n        auto x = ColumnOffset(0);\n        Line<Cell> const& line = lines_[i];\n        if (line.isTrivialBuffer())\n            _render.renderTrivialLine(line.trivialBuffer(), y);\n        else\n        {\n            _render.startLine(y);\n            for (Cell const& cell: line.cells())\n                _render.renderCell(cell, y, x++);\n            _render.endLine();\n        }\n    }\n    _render.finish();\n}\n// }}}\n\n} // namespace terminal\n\n// {{{ fmt formatter\nnamespace fmt\n{\n\ntemplate <>\nstruct formatter<terminal::Margin::Horizontal>\n{\n    template <typename ParseContext>\n    constexpr auto parse(ParseContext& ctx)\n    {\n        return ctx.begin();\n    }\n    template <typename FormatContext>\n    auto format(const terminal::Margin::Horizontal range, FormatContext& ctx)\n    {\n        return fmt::format_to(ctx.out(), \"{}..{}\", range.from, range.to);\n    }\n};\n\ntemplate <>\nstruct formatter<terminal::Margin::Vertical>\n{\n    template <typename ParseContext>\n    constexpr auto parse(ParseContext& ctx)\n    {\n        return ctx.begin();\n    }\n    template <typename FormatContext>\n    auto format(const terminal::Margin::Vertical range, FormatContext& ctx)\n    {\n        return fmt::format_to(ctx.out(), \"{}..{}\", range.from, range.to);\n    }\n};\n\n} // namespace fmt\n// }}}\n", "meta": {"hexsha": "4fed5a55a0ec588e181f75fe7ee06edeb4973cfa", "size": 20513, "ext": "h", "lang": "C", "max_stars_repo_path": "src/terminal/Grid.h", "max_stars_repo_name": "christianparpart/libterminal", "max_stars_repo_head_hexsha": "0e6d75a2042437084c9f9880a5c8b5661a02da07", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-08-14T22:29:57.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-19T08:57:15.000Z", "max_issues_repo_path": "src/terminal/Grid.h", "max_issues_repo_name": "christianparpart/libterminal", "max_issues_repo_head_hexsha": "0e6d75a2042437084c9f9880a5c8b5661a02da07", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 69.0, "max_issues_repo_issues_event_min_datetime": "2019-08-17T18:57:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-22T23:25:49.000Z", "max_forks_repo_path": "src/terminal/Grid.h", "max_forks_repo_name": "christianparpart/libterminal", "max_forks_repo_head_hexsha": "0e6d75a2042437084c9f9880a5c8b5661a02da07", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2531446541, "max_line_length": 110, "alphanum_fraction": 0.6102959099, "num_tokens": 4612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19930799790404566, "lm_q2_score": 0.02675928095401614, "lm_q1q2_score": 0.005333338712296818}}
{"text": "// The various memcached commands that we support.\n\n#include \"commands.h\"\n#include \"connections.h\"\n#include \"protocol.h\"\n#include \"server.h\"\n#include \"utils.h\"\n\n#include <gsl/gsl_randist.h>\n\n#include <assert.h>\n#include <stdio.h>\n\n// process a memcached get(s) command. (we don't support CAS).\nvoid process_get_command(conn *c, token_t *tokens, size_t ntokens,\n                                bool return_cas) {\n\tchar *key;\n\tsize_t nkey;\n\tint i = 0;\n\titem *it;\n\ttoken_t *key_token = &tokens[KEY_TOKEN];\n\tchar *suffix;\n\n\tassert(c != NULL);\n\n\t// process the whole command line, (only part of it may be tokenized right now)\n\tdo {\n\t\t// process all tokenized keys at this stage.\n\t\twhile(key_token->length != 0) {\n\t\t\tkey = key_token->value;\n\t\t\tnkey = key_token->length;\n\n\t\t\tif(nkey > KEY_MAX_LENGTH) {\n\t\t\t\tout_string(c, \"CLIENT_ERROR bad command line format\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// lookup key-value.\n\t\t\tit = item_get(key, nkey);\n\t\t\t\n\t\t\t// hit.\n\t\t\tif (it) {\n\t\t\t\tif (i >= c->isize && !conn_expand_items(c)) {\n\t\t\t\t\titem_remove(it);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\t// Construct the response. Each hit adds three elements to the\n\t\t\t\t// outgoing data list:\n\t\t\t\t//   \"VALUE <key> <flags> <data_length>\\r\\n\"\n\t\t\t\t//   \"<data>\\r\\n\"\n\t\t\t\t// The <data> element is stored on the connection item list, not on\n\t\t\t\t// the iov list.\n\t\t\t\tif (!conn_add_iov(c, \"VALUE \", 6) != 0 ||\n\t\t\t\t    !conn_add_iov(c, ITEM_key(it), it->nkey) != 0 ||\n\t\t\t\t    !conn_add_iov(c, ITEM_suffix(it), it->nsuffix + it->nbytes) != 0) {\n\t\t\t\t\titem_remove(it);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (config.verbose > 1) {\n\t\t\t\t\tfprintf(stderr, \">%d sending key %s\\n\", c->sfd, key);\n\t\t\t\t}\n\n\t\t\t\t// add item to remembered list (i.e., we've taken ownership of them\n\t\t\t\t// through refcounting and later must release them once we've\n\t\t\t\t// written out the iov associated with them).\n\t\t\t\titem_update(it);\n\t\t\t\t*(c->ilist + i) = it;\n\t\t\t\ti++;\n\t\t\t}\n\n\t\t\tkey_token++;\n\t\t}\n\n\t\t/*\n\t\t * If the command string hasn't been fully processed, get the next set\n\t\t * of tokens.\n\t\t */\n\t\tif(key_token->value != NULL) {\n\t\t\tntokens = tokenize_command(key_token->value, tokens, MAX_TOKENS);\n\t\t\tkey_token = tokens;\n\t\t}\n\n\t} while(key_token->value != NULL);\n\n\tc->icurr = c->ilist;\n\tc->ileft = i;\n\n\tif (config.verbose > 1) {\n\t\tfprintf(stderr, \">%d END\\n\", c->sfd);\n\t}\n\n\t// If the loop was terminated because of out-of-memory, it is not reliable\n\t// to add END\\r\\n to the buffer, because it might not end in \\r\\n. So we\n\t// send SERVER_ERROR instead.\n\tif (key_token->value != NULL || !conn_add_iov(c, \"END\\r\\n\", 5) != 0) {\n\t\tout_string(c, \"SERVER_ERROR out of memory writing get response\");\n\t} else {\n\t\tif (config.use_dist) {\n\t\t\tdouble r = config.dist_arg1 + gsl_ran_gaussian(config.r, config.dist_arg2);\n\t\t\tif (config.verbose > 0) {\n\t\t\t\tfprintf(stderr, \"delay: %f\\n\", r);\n\t\t\t}\n\t\t\tconn_set_state(c, conn_timeout);\n\t\t\tc->after_timeout = conn_mwrite;\n\t\t\tc->timeout = r;\n\t\t\tc->msgcurr = 0;\n\t\t} else {\n\t\t\tconn_set_state(c, conn_mwrite);\n\t\t}\n\t}\n}\n\n// process a memcached set command.\nvoid process_update_command(conn *c, token_t *tokens,\n                            const size_t ntokens,\n                            int comm, bool handle_cas) {\n\tint vlen;\n\tassert(c != NULL);\n\n\tif (tokens[KEY_TOKEN].length > KEY_MAX_LENGTH ||\n\t    !safe_strtol(tokens[4].value, (int32_t *)&vlen)) {\n\t\tout_string(c, \"CLIENT_ERROR bad command line format\");\n\t\treturn;\n\t}\n\n\tif (vlen < 0) {\n\t\tout_string(c, \"CLIENT_ERROR bad command line format\");\n\t\treturn;\n\t}\n\n\t// setup value to be read\n\tc->sbytes = vlen + 2; // for \\r\\n consumption.\n\tconn_set_state(c, conn_read_value);\n}\n\n", "meta": {"hexsha": "0b9780cbc5efa6ef5052d44cde86cf78303e4715", "size": 3548, "ext": "c", "lang": "C", "max_stars_repo_path": "src/commands.c", "max_stars_repo_name": "dterei/synthetic-memcached", "max_stars_repo_head_hexsha": "2db588dd7f3417a912e8ac1547cd2b51c8fd7915", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/commands.c", "max_issues_repo_name": "dterei/synthetic-memcached", "max_issues_repo_head_hexsha": "2db588dd7f3417a912e8ac1547cd2b51c8fd7915", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/commands.c", "max_forks_repo_name": "dterei/synthetic-memcached", "max_forks_repo_head_hexsha": "2db588dd7f3417a912e8ac1547cd2b51c8fd7915", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7101449275, "max_line_length": 80, "alphanum_fraction": 0.618940248, "num_tokens": 1037, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1540575588075327, "lm_q2_score": 0.03461883585116161, "lm_q1q2_score": 0.00533329333998865}}
{"text": "#include <bindings.cmacros.h>\n#include <gsl/gsl_monte_plain.h>\n#include <gsl/gsl_monte_miser.h>\n#include <gsl/gsl_monte_vegas.h>\n\nBC_INLINE2(GSL_MONTE_FN_EVAL,gsl_monte_function*,double*,double)\n", "meta": {"hexsha": "17f650b95d6f5ca113f0d5e33164357b6396423e", "size": 195, "ext": "c", "lang": "C", "max_stars_repo_path": "bindings-gsl/src/Bindings/Gsl/MonteCarloIntegration.c", "max_stars_repo_name": "flip111/bindings-dsl", "max_stars_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2015-04-29T00:31:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T09:29:03.000Z", "max_issues_repo_path": "bindings-gsl/src/Bindings/Gsl/MonteCarloIntegration.c", "max_issues_repo_name": "flip111/bindings-dsl", "max_issues_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2015-01-04T06:32:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-07T09:49:12.000Z", "max_forks_repo_path": "bindings-gsl/src/Bindings/Gsl/MonteCarloIntegration.c", "max_forks_repo_name": "flip111/bindings-dsl", "max_forks_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2015-01-03T20:43:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-10T19:31:38.000Z", "avg_line_length": 27.8571428571, "max_line_length": 64, "alphanum_fraction": 0.8102564103, "num_tokens": 61, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20181321265898594, "lm_q2_score": 0.026355350743057632, "lm_q1q2_score": 0.005318858004210853}}
{"text": "#ifndef TRANS_UTIL\n#define TRANS_UTIL\n\n\n#define prefetch(x) __builtin_prefetch(x)\n#define prefetch_for_r(x) __builtin_prefetch(x, 0, 3)\n#define prefetch_for_w(x) __builtin_prefetch(x, 1, 3)\n\n\n#include <stdarg.h>\n#include <gsl/gsl_vector.h>\n#include \"../include/type.h\"\n\nint setulb_(integer *, integer *, doublereal *, \n            doublereal *, doublereal *, integer *, doublereal *, doublereal *,\n            doublereal *, doublereal *, doublereal *, integer *, char *, \n            integer *, char *, logical *, integer *, doublereal *, integer *);\n\ndouble cuscumsum(gsl_vector *vec, double (*fun) (double, va_list), int argc, ...);\n\nint parse_title(char* str, char** output);\n\nint str_to_vector(char* str, gsl_vector** vec);\n\nint parse_line(char* str, char** id, size_t* id_n, gsl_vector** inc1,\n               gsl_vector** skp1, gsl_vector** inc2, gsl_vector** skp2,\n               int* inclu_len, int* skip_len);\n\nint parse_file(const char* filename, diff_list_node* list, char** title);\n\ndouble logit(double i);\n\ndouble cumprod(const gsl_vector* vec);\n\ndouble sum_for_multivar(const double i, va_list argv);\n\ndouble sum_for_multivar_der(const double i, va_list argv);\n\ndouble myfunc_marginal_2der(const double x, const double I, const double S,\n                            const double beta, const double var,\n                            const int inclu_len, const int skip_len);\n\ndouble sum_for_marginal(const double i, va_list argv);\n\ndouble sum_for_marginal_der(const double i, va_list argv);\n\nodiff* diff_alloc(gsl_vector* inc1, gsl_vector* inc2,\n                  gsl_vector* skp1, gsl_vector* skp2,\n                  int inclu_len, int skip_len, int flag, char* id);\n\nint diff_append(diff_list_node* header, odiff* data);\n\nvoid mp_threadpool(int nthread, int ntask, void* (*func)(void *), void** datum, void **ret);\n\ndouble l_bfgs_b_wrapper(integer n, integer m, doublereal x[], doublereal l[],\n                        doublereal u[], integer nbd[],\n                        double (*fp) (const double x[], va_list argv),\n                        void (*gp) (const double x[], double res[], va_list argv),\n                        doublereal factr, doublereal pgtol, integer iprint,\n                        int maxfun, int maxiter, int argc, ...);\n\n\n#endif\n", "meta": {"hexsha": "e1560a0fb4f384d8c798f17815f01cf467da6057", "size": 2266, "ext": "h", "lang": "C", "max_stars_repo_path": "rMATS_C/include/util.h", "max_stars_repo_name": "yharlne/rmats-turbo", "max_stars_repo_head_hexsha": "ef04603c71dab9d14863ecac5ac598ef97732c4e", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rMATS_C/include/util.h", "max_issues_repo_name": "yharlne/rmats-turbo", "max_issues_repo_head_hexsha": "ef04603c71dab9d14863ecac5ac598ef97732c4e", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rMATS_C/include/util.h", "max_forks_repo_name": "yharlne/rmats-turbo", "max_forks_repo_head_hexsha": "ef04603c71dab9d14863ecac5ac598ef97732c4e", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.40625, "max_line_length": 92, "alphanum_fraction": 0.6451897617, "num_tokens": 567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.290980853917813, "lm_q2_score": 0.018264282259484392, "lm_q1q2_score": 0.005314556448060731}}
{"text": "/**\n * Created: Wed Aug 31 20:27:45 CST 2016\n * @author: Lie Yan\n * @email: robin.lie.yan@outlook.com\n *\n */\n\n#pragma once\n\n#include <gsl.h>\n\nnamespace formulae {\nnamespace interm {\n\nenum class ItemTag : uint8_t { INoad, IPen, ISpace, IStyle };\n\nstruct Item {\n  virtual ItemTag tag() const = 0;\n  virtual gsl::owner<Item *> clone() const = 0;\n};\n\nclass ItemRef {\npublic:\n  ItemRef(gsl::owner<Item *> itemPtr) : _itemPtr(itemPtr) {}\n  ItemRef(const ItemRef &rhs) { _itemPtr.reset(rhs._itemPtr->clone()); }\n  ItemRef &operator=(const ItemRef &rhs) {\n    _itemPtr.reset(rhs._itemPtr->clone());\n    return *this;\n  }\n  ItemRef(ItemRef &&rhs) = default;\n  ItemRef &operator=(ItemRef &&rhs) = default;\n  virtual ~ItemRef() = default;\n\n  /* -------------------------------------------------------- */\n  ItemTag tag() const { return _itemPtr->tag(); }\n\n  template<typename T>\n  T& as() const { return *dynamic_cast<T*>(_itemPtr.get()); }\n\nprivate:\n  std::unique_ptr<Item> _itemPtr;\n};\n\nusing ilist_t = list_t<ItemRef>;\n\n}\n}\n", "meta": {"hexsha": "3f9441e687ee82181c2b499de3c199b1b0694493", "size": 1016, "ext": "h", "lang": "C", "max_stars_repo_path": "include/interm/types/IL0_Item.h", "max_stars_repo_name": "robin33n/formulae-cxx", "max_stars_repo_head_hexsha": "4b691e515b30508fb5e29c68426bad51d9629e72", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-25T04:00:03.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-25T04:00:03.000Z", "max_issues_repo_path": "include/interm/types/IL0_Item.h", "max_issues_repo_name": "robin33n/formulae-cxx", "max_issues_repo_head_hexsha": "4b691e515b30508fb5e29c68426bad51d9629e72", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-09-25T11:10:39.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-26T11:32:00.000Z", "max_forks_repo_path": "include/interm/types/IL0_Item.h", "max_forks_repo_name": "robin33n/formulae-cxx", "max_forks_repo_head_hexsha": "4b691e515b30508fb5e29c68426bad51d9629e72", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1666666667, "max_line_length": 72, "alphanum_fraction": 0.6161417323, "num_tokens": 293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14223190228178134, "lm_q2_score": 0.037326885737772805, "lm_q1q2_score": 0.005309073964738119}}
{"text": "/* vector/gsl_vector_double.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_VECTOR_DOUBLE_H__\n#define __GSL_VECTOR_DOUBLE_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_block_double.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size;\n  size_t stride;\n  double *data;\n  gsl_block *block;\n  int owner;\n} \ngsl_vector;\n\ntypedef struct\n{\n  gsl_vector vector;\n} _gsl_vector_view;\n\ntypedef _gsl_vector_view gsl_vector_view;\n\ntypedef struct\n{\n  gsl_vector vector;\n} _gsl_vector_const_view;\n\ntypedef const _gsl_vector_const_view gsl_vector_const_view;\n\n\n/* Allocation */\n\nGSL_EXPORT gsl_vector *gsl_vector_alloc (const size_t n);\nGSL_EXPORT gsl_vector *gsl_vector_calloc (const size_t n);\n\nGSL_EXPORT gsl_vector *gsl_vector_alloc_from_block (gsl_block * b,\n                                                     const size_t offset,\n                                                     const size_t n,\n                                                     const size_t stride);\n\nGSL_EXPORT gsl_vector *gsl_vector_alloc_from_vector (gsl_vector * v,\n                                                      const size_t offset,\n                                                      const size_t n,\n                                                      const size_t stride);\n\nGSL_EXPORT void gsl_vector_free (gsl_vector * v);\n\n/* Views */\n\nGSL_EXPORT\n_gsl_vector_view\ngsl_vector_view_array (double *v, size_t n);\n\nGSL_EXPORT\n_gsl_vector_view\ngsl_vector_view_array_with_stride (double *base,\n                                         size_t stride,\n                                         size_t n);\n\nGSL_EXPORT\n_gsl_vector_const_view\ngsl_vector_const_view_array (const double *v, size_t n);\n\nGSL_EXPORT\n_gsl_vector_const_view\ngsl_vector_const_view_array_with_stride (const double *base,\n                                               size_t stride,\n                                               size_t n);\n\nGSL_EXPORT\n_gsl_vector_view\ngsl_vector_subvector (gsl_vector *v,\n                            size_t i,\n                            size_t n);\n\nGSL_EXPORT\n_gsl_vector_view\ngsl_vector_subvector_with_stride (gsl_vector *v,\n                                        size_t i,\n                                        size_t stride,\n                                        size_t n);\n\nGSL_EXPORT\n_gsl_vector_const_view\ngsl_vector_const_subvector (const gsl_vector *v,\n                                  size_t i,\n                                  size_t n);\n\nGSL_EXPORT\n_gsl_vector_const_view\ngsl_vector_const_subvector_with_stride (const gsl_vector *v,\n                                              size_t i,\n                                              size_t stride,\n                                              size_t n);\n\n/* Operations */\n\nGSL_EXPORT double gsl_vector_get (const gsl_vector * v, const size_t i);\nGSL_EXPORT void gsl_vector_set (gsl_vector * v, const size_t i, double x);\n\nGSL_EXPORT double *gsl_vector_ptr (gsl_vector * v, const size_t i);\nGSL_EXPORT const double *gsl_vector_const_ptr (const gsl_vector * v, const size_t i);\n\nGSL_EXPORT void gsl_vector_set_zero (gsl_vector * v);\nGSL_EXPORT void gsl_vector_set_all (gsl_vector * v, double x);\nGSL_EXPORT int gsl_vector_set_basis (gsl_vector * v, size_t i);\n\nGSL_EXPORT int gsl_vector_fread (FILE * stream, gsl_vector * v);\nGSL_EXPORT int gsl_vector_fwrite (FILE * stream, const gsl_vector * v);\nGSL_EXPORT int gsl_vector_fscanf (FILE * stream, gsl_vector * v);\nGSL_EXPORT int gsl_vector_fprintf (FILE * stream, const gsl_vector * v,\n                                   const char *format);\n\nGSL_EXPORT int gsl_vector_memcpy (gsl_vector * dest, const gsl_vector * src);\n\nGSL_EXPORT int gsl_vector_reverse (gsl_vector * v);\n\nGSL_EXPORT int gsl_vector_swap (gsl_vector * v, gsl_vector * w);\nGSL_EXPORT int gsl_vector_swap_elements (gsl_vector * v, const size_t i, const size_t j);\n\nGSL_EXPORT double gsl_vector_max (const gsl_vector * v);\nGSL_EXPORT double gsl_vector_min (const gsl_vector * v);\nGSL_EXPORT void gsl_vector_minmax (const gsl_vector * v, double * min_out, double * max_out);\n\nGSL_EXPORT size_t gsl_vector_max_index (const gsl_vector * v);\nGSL_EXPORT size_t gsl_vector_min_index (const gsl_vector * v);\nGSL_EXPORT void gsl_vector_minmax_index (const gsl_vector * v, size_t * imin, size_t * imax);\n\nGSL_EXPORT int gsl_vector_add (gsl_vector * a, const gsl_vector * b);\nGSL_EXPORT int gsl_vector_sub (gsl_vector * a, const gsl_vector * b);\nGSL_EXPORT int gsl_vector_mul (gsl_vector * a, const gsl_vector * b);\nGSL_EXPORT int gsl_vector_div (gsl_vector * a, const gsl_vector * b);\nGSL_EXPORT int gsl_vector_scale (gsl_vector * a, const double x);\nGSL_EXPORT int gsl_vector_add_constant (gsl_vector * a, const double x);\n\nGSL_EXPORT int gsl_vector_isnull (const gsl_vector * v);\n\n#ifdef HAVE_INLINE\n\nextern inline\ndouble\ngsl_vector_get (const gsl_vector * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_VAL (\"index out of range\", GSL_EINVAL, 0);\n    }\n#endif\n  return v->data[i * v->stride];\n}\n\nextern inline\nvoid\ngsl_vector_set (gsl_vector * v, const size_t i, double x)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_VOID (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  v->data[i * v->stride] = x;\n}\n\nextern inline\ndouble *\ngsl_vector_ptr (gsl_vector * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return (double *) (v->data + i * v->stride);\n}\n\nextern inline\nconst double *\ngsl_vector_const_ptr (const gsl_vector * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return (const double *) (v->data + i * v->stride);\n}\n\n\n#endif /* HAVE_INLINE */\n\n__END_DECLS\n\n#endif /* __GSL_VECTOR_DOUBLE_H__ */\n\n\n", "meta": {"hexsha": "8aa4af445b8f0a9dd01c678809792e686200681a", "size": 6860, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/gsl/include/gsl/gsl_vector_double.h", "max_stars_repo_name": "dynaryu/vaws", "max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/gsl/include/gsl/gsl_vector_double.h", "max_issues_repo_name": "dynaryu/vaws", "max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/gsl/include/gsl/gsl_vector_double.h", "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1914893617, "max_line_length": 93, "alphanum_fraction": 0.6580174927, "num_tokens": 1655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21733753118592733, "lm_q2_score": 0.024423088101365023, "lm_q1q2_score": 0.005308053671887071}}
{"text": "/* vector/gsl_vector_long.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_VECTOR_LONG_H__\n#define __GSL_VECTOR_LONG_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_block_long.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size;\n  size_t stride;\n  long *data;\n  gsl_block_long *block;\n  int owner;\n} \ngsl_vector_long;\n\ntypedef struct\n{\n  gsl_vector_long vector;\n} _gsl_vector_long_view;\n\ntypedef _gsl_vector_long_view gsl_vector_long_view;\n\ntypedef struct\n{\n  gsl_vector_long vector;\n} _gsl_vector_long_const_view;\n\ntypedef const _gsl_vector_long_const_view gsl_vector_long_const_view;\n\n\n/* Allocation */\n\nGSL_EXPORT gsl_vector_long *gsl_vector_long_alloc (const size_t n);\nGSL_EXPORT gsl_vector_long *gsl_vector_long_calloc (const size_t n);\n\nGSL_EXPORT gsl_vector_long *gsl_vector_long_alloc_from_block (gsl_block_long * b,\n                                                                const size_t offset,\n                                                                const size_t n,\n                                                                const size_t stride);\n\nGSL_EXPORT gsl_vector_long *gsl_vector_long_alloc_from_vector (gsl_vector_long * v,\n                                                                 const size_t offset,\n                                                                 const size_t n,\n                                                                 const size_t stride);\n\nGSL_EXPORT void gsl_vector_long_free (gsl_vector_long * v);\n\n/* Views */\n\nGSL_EXPORT\n_gsl_vector_long_view\ngsl_vector_long_view_array (long *v, size_t n);\n\nGSL_EXPORT\n_gsl_vector_long_view\ngsl_vector_long_view_array_with_stride (long *base,\n                                         size_t stride,\n                                         size_t n);\n\nGSL_EXPORT\n_gsl_vector_long_const_view\ngsl_vector_long_const_view_array (const long *v, size_t n);\n\nGSL_EXPORT\n_gsl_vector_long_const_view\ngsl_vector_long_const_view_array_with_stride (const long *base,\n                                               size_t stride,\n                                               size_t n);\n\nGSL_EXPORT\n_gsl_vector_long_view\ngsl_vector_long_subvector (gsl_vector_long *v,\n                            size_t i,\n                            size_t n);\n\nGSL_EXPORT\n_gsl_vector_long_view\ngsl_vector_long_subvector_with_stride (gsl_vector_long *v,\n                                        size_t i,\n                                        size_t stride,\n                                        size_t n);\n\nGSL_EXPORT\n_gsl_vector_long_const_view\ngsl_vector_long_const_subvector (const gsl_vector_long *v,\n                                  size_t i,\n                                  size_t n);\n\nGSL_EXPORT\n_gsl_vector_long_const_view\ngsl_vector_long_const_subvector_with_stride (const gsl_vector_long *v,\n                                              size_t i,\n                                              size_t stride,\n                                              size_t n);\n\n/* Operations */\n\nGSL_EXPORT long gsl_vector_long_get (const gsl_vector_long * v, const size_t i);\nGSL_EXPORT void gsl_vector_long_set (gsl_vector_long * v, const size_t i, long x);\n\nGSL_EXPORT long *gsl_vector_long_ptr (gsl_vector_long * v, const size_t i);\nGSL_EXPORT const long *gsl_vector_long_const_ptr (const gsl_vector_long * v, const size_t i);\n\nGSL_EXPORT void gsl_vector_long_set_zero (gsl_vector_long * v);\nGSL_EXPORT void gsl_vector_long_set_all (gsl_vector_long * v, long x);\nGSL_EXPORT int gsl_vector_long_set_basis (gsl_vector_long * v, size_t i);\n\nGSL_EXPORT int gsl_vector_long_fread (FILE * stream, gsl_vector_long * v);\nGSL_EXPORT int gsl_vector_long_fwrite (FILE * stream, const gsl_vector_long * v);\nGSL_EXPORT int gsl_vector_long_fscanf (FILE * stream, gsl_vector_long * v);\nGSL_EXPORT int gsl_vector_long_fprintf (FILE * stream, const gsl_vector_long * v,\n                                         const char *format);\n\nGSL_EXPORT int gsl_vector_long_memcpy (gsl_vector_long * dest, const gsl_vector_long * src);\n\nGSL_EXPORT int gsl_vector_long_reverse (gsl_vector_long * v);\n\nGSL_EXPORT int gsl_vector_long_swap (gsl_vector_long * v, gsl_vector_long * w);\nGSL_EXPORT int gsl_vector_long_swap_elements (gsl_vector_long * v, const size_t i, const size_t j);\n\nGSL_EXPORT long gsl_vector_long_max (const gsl_vector_long * v);\nGSL_EXPORT long gsl_vector_long_min (const gsl_vector_long * v);\nGSL_EXPORT void gsl_vector_long_minmax (const gsl_vector_long * v, long * min_out, long * max_out);\n\nGSL_EXPORT size_t gsl_vector_long_max_index (const gsl_vector_long * v);\nGSL_EXPORT size_t gsl_vector_long_min_index (const gsl_vector_long * v);\nGSL_EXPORT void gsl_vector_long_minmax_index (const gsl_vector_long * v, size_t * imin, size_t * imax);\n\nGSL_EXPORT int gsl_vector_long_add (gsl_vector_long * a, const gsl_vector_long * b);\nGSL_EXPORT int gsl_vector_long_sub (gsl_vector_long * a, const gsl_vector_long * b);\nGSL_EXPORT int gsl_vector_long_mul (gsl_vector_long * a, const gsl_vector_long * b);\nGSL_EXPORT int gsl_vector_long_div (gsl_vector_long * a, const gsl_vector_long * b);\nGSL_EXPORT int gsl_vector_long_scale (gsl_vector_long * a, const double x);\nGSL_EXPORT int gsl_vector_long_add_constant (gsl_vector_long * a, const double x);\n\nGSL_EXPORT int gsl_vector_long_isnull (const gsl_vector_long * v);\n\n#ifdef HAVE_INLINE\n\nextern inline\nlong\ngsl_vector_long_get (const gsl_vector_long * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_VAL (\"index out of range\", GSL_EINVAL, 0);\n    }\n#endif\n  return v->data[i * v->stride];\n}\n\nextern inline\nvoid\ngsl_vector_long_set (gsl_vector_long * v, const size_t i, long x)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_VOID (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  v->data[i * v->stride] = x;\n}\n\nextern inline\nlong *\ngsl_vector_long_ptr (gsl_vector_long * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return (long *) (v->data + i * v->stride);\n}\n\nextern inline\nconst long *\ngsl_vector_long_const_ptr (const gsl_vector_long * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return (const long *) (v->data + i * v->stride);\n}\n\n\n#endif /* HAVE_INLINE */\n\n__END_DECLS\n\n#endif /* __GSL_VECTOR_LONG_H__ */\n\n\n", "meta": {"hexsha": "cc1ee2d75ff1faa20fc278bcd8e5d513baeaa5c5", "size": 7442, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/gsl/include/gsl/gsl_vector_long.h", "max_stars_repo_name": "dynaryu/vaws", "max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/gsl/include/gsl/gsl_vector_long.h", "max_issues_repo_name": "dynaryu/vaws", "max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/gsl/include/gsl/gsl_vector_long.h", "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6680851064, "max_line_length": 103, "alphanum_fraction": 0.6750873421, "num_tokens": 1767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.256832002764217, "lm_q2_score": 0.020645931680770516, "lm_q1q2_score": 0.005302535982505489}}
{"text": "/* vector/gsl_vector_complex_float.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_VECTOR_COMPLEX_FLOAT_H__\n#define __GSL_VECTOR_COMPLEX_FLOAT_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_complex.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_vector_float.h>\n#include <gsl/gsl_vector_complex.h>\n#include <gsl/gsl_block_complex_float.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size;\n  size_t stride;\n  float *data;\n  gsl_block_complex_float *block;\n  int owner;\n} gsl_vector_complex_float;\n\ntypedef struct\n{\n  gsl_vector_complex_float vector;\n} _gsl_vector_complex_float_view;\n\ntypedef _gsl_vector_complex_float_view gsl_vector_complex_float_view;\n\ntypedef struct\n{\n  gsl_vector_complex_float vector;\n} _gsl_vector_complex_float_const_view;\n\ntypedef const _gsl_vector_complex_float_const_view gsl_vector_complex_float_const_view;\n\n/* Allocation */\n\ngsl_vector_complex_float *gsl_vector_complex_float_alloc (const size_t n);\ngsl_vector_complex_float *gsl_vector_complex_float_calloc (const size_t n);\n\ngsl_vector_complex_float *\ngsl_vector_complex_float_alloc_from_block (gsl_block_complex_float * b, \n                                           const size_t offset, \n                                           const size_t n, \n                                           const size_t stride);\n\ngsl_vector_complex_float *\ngsl_vector_complex_float_alloc_from_vector (gsl_vector_complex_float * v, \n                                             const size_t offset, \n                                             const size_t n, \n                                             const size_t stride);\n\nvoid gsl_vector_complex_float_free (gsl_vector_complex_float * v);\n\n/* Views */\n\n_gsl_vector_complex_float_view\ngsl_vector_complex_float_view_array (float *base,\n                                     size_t n);\n\n_gsl_vector_complex_float_view\ngsl_vector_complex_float_view_array_with_stride (float *base,\n                                                 size_t stride,\n                                                 size_t n);\n\n_gsl_vector_complex_float_const_view\ngsl_vector_complex_float_const_view_array (const float *base,\n                                           size_t n);\n\n_gsl_vector_complex_float_const_view\ngsl_vector_complex_float_const_view_array_with_stride (const float *base,\n                                                       size_t stride,\n                                                       size_t n);\n\n_gsl_vector_complex_float_view\ngsl_vector_complex_float_subvector (gsl_vector_complex_float *base,\n                                         size_t i, \n                                         size_t n);\n\n\n_gsl_vector_complex_float_view \ngsl_vector_complex_float_subvector_with_stride (gsl_vector_complex_float *v, \n                                                size_t i, \n                                                size_t stride, \n                                                size_t n);\n\n_gsl_vector_complex_float_const_view\ngsl_vector_complex_float_const_subvector (const gsl_vector_complex_float *base,\n                                               size_t i, \n                                               size_t n);\n\n\n_gsl_vector_complex_float_const_view \ngsl_vector_complex_float_const_subvector_with_stride (const gsl_vector_complex_float *v, \n                                                      size_t i, \n                                                      size_t stride, \n                                                      size_t n);\n\n_gsl_vector_float_view\ngsl_vector_complex_float_real (gsl_vector_complex_float *v);\n\n_gsl_vector_float_view \ngsl_vector_complex_float_imag (gsl_vector_complex_float *v);\n\n_gsl_vector_float_const_view\ngsl_vector_complex_float_const_real (const gsl_vector_complex_float *v);\n\n_gsl_vector_float_const_view \ngsl_vector_complex_float_const_imag (const gsl_vector_complex_float *v);\n\n\n/* Operations */\n\ngsl_complex_float \ngsl_vector_complex_float_get (const gsl_vector_complex_float * v, const size_t i);\n\nvoid gsl_vector_complex_float_set (gsl_vector_complex_float * v, const size_t i,\n                                   gsl_complex_float z);\n\ngsl_complex_float \n*gsl_vector_complex_float_ptr (gsl_vector_complex_float * v, const size_t i);\n\nconst gsl_complex_float \n*gsl_vector_complex_float_const_ptr (const gsl_vector_complex_float * v, const size_t i);\n\nvoid gsl_vector_complex_float_set_zero (gsl_vector_complex_float * v);\nvoid gsl_vector_complex_float_set_all (gsl_vector_complex_float * v,\n                                       gsl_complex_float z);\nint gsl_vector_complex_float_set_basis (gsl_vector_complex_float * v, size_t i);\n\nint gsl_vector_complex_float_fread (FILE * stream,\n                                    gsl_vector_complex_float * v);\nint gsl_vector_complex_float_fwrite (FILE * stream,\n                                     const gsl_vector_complex_float * v);\nint gsl_vector_complex_float_fscanf (FILE * stream,\n                                     gsl_vector_complex_float * v);\nint gsl_vector_complex_float_fprintf (FILE * stream,\n                                      const gsl_vector_complex_float * v,\n                                      const char *format);\n\nint gsl_vector_complex_float_memcpy (gsl_vector_complex_float * dest, const gsl_vector_complex_float * src);\n\nint gsl_vector_complex_float_reverse (gsl_vector_complex_float * v);\n\nint gsl_vector_complex_float_swap (gsl_vector_complex_float * v, gsl_vector_complex_float * w);\nint gsl_vector_complex_float_swap_elements (gsl_vector_complex_float * v, const size_t i, const size_t j);\n\nint gsl_vector_complex_float_isnull (const gsl_vector_complex_float * v);\nint gsl_vector_complex_float_ispos (const gsl_vector_complex_float * v);\nint gsl_vector_complex_float_isneg (const gsl_vector_complex_float * v);\n\n#ifdef HAVE_INLINE\n\nextern inline\ngsl_complex_float\ngsl_vector_complex_float_get (const gsl_vector_complex_float * v,\n                              const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      gsl_complex_float zero = {{0, 0}};\n      GSL_ERROR_VAL (\"index out of range\", GSL_EINVAL, zero);\n    }\n#endif\n  return *GSL_COMPLEX_FLOAT_AT (v, i);\n}\n\nextern inline\nvoid\ngsl_vector_complex_float_set (gsl_vector_complex_float * v,\n                              const size_t i, gsl_complex_float z)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_VOID (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  *GSL_COMPLEX_FLOAT_AT (v, i) = z;\n}\n\nextern inline\ngsl_complex_float *\ngsl_vector_complex_float_ptr (gsl_vector_complex_float * v,\n                              const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return GSL_COMPLEX_FLOAT_AT (v, i);\n}\n\nextern inline\nconst gsl_complex_float *\ngsl_vector_complex_float_const_ptr (const gsl_vector_complex_float * v,\n                                    const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return GSL_COMPLEX_FLOAT_AT (v, i);\n}\n\n\n#endif /* HAVE_INLINE */\n\n__END_DECLS\n\n#endif /* __GSL_VECTOR_COMPLEX_FLOAT_H__ */\n", "meta": {"hexsha": "0823a23e62e8be74aa5765cc3ea5e9b08864f801", "size": 8191, "ext": "h", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/vector/gsl_vector_complex_float.h", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/vector/gsl_vector_complex_float.h", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/vector/gsl_vector_complex_float.h", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 33.0282258065, "max_line_length": 108, "alphanum_fraction": 0.6664631913, "num_tokens": 1708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2814056194821862, "lm_q2_score": 0.01883313119834847, "lm_q1q2_score": 0.0052997489516605385}}
{"text": "/******************************************************************************\n * Copyright 2018 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************/\n\n#pragma once\n\n#include <cblas.h>\n#include <cuda_runtime_api.h>\n\n#include <boost/shared_ptr.hpp>\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <memory>\n#include <string>\n#include <vector>\n\n#include \"modules/perception/base/blob.h\"\n#include \"modules/perception/base/image.h\"\n\nnamespace apollo {\nnamespace perception {\nnamespace inference {\n\nbool ResizeGPU(const base::Image8U &src,\n               std::shared_ptr<apollo::perception::base::Blob<float>> dst,\n               int stepwidth, int start_axis);\n\nbool ResizeGPU(const apollo::perception::base::Blob<uint8_t> &src_gpu,\n               std::shared_ptr<apollo::perception::base::Blob<float>> dst,\n               int stepwidth, int start_axis, int mean_b, int mean_g,\n               int mean_r, bool channel_axis, float scale);\n\nbool ResizeGPU(const base::Image8U &src,\n               std::shared_ptr<apollo::perception::base::Blob<float>> dst,\n               int stepwidth, int start_axis, float mean_b, float mean_g,\n               float mean_r, bool channel_axis, float scale);\n\n}  // namespace inference\n}  // namespace perception\n}  // namespace apollo\n", "meta": {"hexsha": "43ac5a78d1caf1f690e2c0c8ee24a6a40210c888", "size": 1900, "ext": "h", "lang": "C", "max_stars_repo_path": "modules/perception/inference/utils/resize.h", "max_stars_repo_name": "ghdawn/apollo", "max_stars_repo_head_hexsha": "002eba4a1635d6af7f1ebd2118464bca6f86b106", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-03-15T06:28:38.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-15T06:31:33.000Z", "max_issues_repo_path": "modules/perception/inference/utils/resize.h", "max_issues_repo_name": "thomasgui76/apollo", "max_issues_repo_head_hexsha": "808f1d20a08efea23b718b4e423d6619c9d4b412", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/perception/inference/utils/resize.h", "max_forks_repo_name": "thomasgui76/apollo", "max_forks_repo_head_hexsha": "808f1d20a08efea23b718b4e423d6619c9d4b412", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-02-24T06:20:29.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-24T06:20:29.000Z", "avg_line_length": 35.1851851852, "max_line_length": 79, "alphanum_fraction": 0.6447368421, "num_tokens": 395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24798742624020276, "lm_q2_score": 0.02128735113373678, "lm_q1q2_score": 0.005278995419126847}}
{"text": "#ifndef SOLVER_H\n#define SOLVER_H\n\n#if PY_MAJOR_VERSION >= 3\n#define PY3K\n#endif\n\n// include user-defined headers\n#include \"common.h\"\n#include \"utils.h\"\n\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_interp.h>\n#include <gsl/gsl_spline.h>\n\ntypedef struct _TOV_Tuple {\n    double a;\n    double b;\n    double c;\n} Pair;\n\n#endif", "meta": {"hexsha": "ac7997b4a524bf9fbb7b0685689aa0c25dc3783e", "size": 323, "ext": "h", "lang": "C", "max_stars_repo_path": "src/solver.h", "max_stars_repo_name": "lujiajing1126/tov-solver", "max_stars_repo_head_hexsha": "f3510c4d0628374998e4cb102f9beabc701e02f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-02-22T05:46:28.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-22T05:46:28.000Z", "max_issues_repo_path": "src/solver.h", "max_issues_repo_name": "lujiajing1126/tov-solver", "max_issues_repo_head_hexsha": "f3510c4d0628374998e4cb102f9beabc701e02f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/solver.h", "max_forks_repo_name": "lujiajing1126/tov-solver", "max_forks_repo_head_hexsha": "f3510c4d0628374998e4cb102f9beabc701e02f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.6818181818, "max_line_length": 31, "alphanum_fraction": 0.7089783282, "num_tokens": 93, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19682621306573764, "lm_q2_score": 0.026759285513888915, "lm_q1q2_score": 0.0052669288320436065}}
{"text": "#pragma once\n\n#include <gsl\\gsl>\n#include <d3d11.h>\n#include \"Bone.h\"\n\nnamespace Library\n{\n\tclass Model;\n    class Material;\n    class ModelMaterial;\n\tclass OutputStreamHelper;\n\tclass InputStreamHelper;\n\n\tstruct MeshData final\n\t{\n\t\tstd::shared_ptr<ModelMaterial> Material;\n\t\tstd::string Name;\n\t\tstd::vector<DirectX::XMFLOAT3> Vertices;\n\t\tstd::vector<DirectX::XMFLOAT3> Normals;\n\t\tstd::vector<DirectX::XMFLOAT3> Tangents;\n\t\tstd::vector<DirectX::XMFLOAT3> BiNormals;\n\t\tstd::vector<std::vector<DirectX::XMFLOAT3>> TextureCoordinates;\n\t\tstd::vector<std::vector<DirectX::XMFLOAT4>> VertexColors;\n\t\tstd::uint32_t FaceCount{ 0 };\n\t\tstd::vector<std::uint32_t> Indices;\n\t\tstd::vector<BoneVertexWeights> BoneWeights;\n\t};\n\n    class Mesh final\n    {\n    public:\n\t\tMesh(Library::Model& model, InputStreamHelper& streamHelper);\n\t\tMesh(Library::Model& model, MeshData&& meshData);\n\t\tMesh(const Mesh&) = default;\n\t\tMesh(Mesh&&) = default;\n\t\tMesh& operator=(const Mesh&) = default;\n\t\tMesh& operator=(Mesh&&) = default;\n\t\t~Mesh() = default;\n\n\t\tLibrary::Model& GetModel();\n        std::shared_ptr<ModelMaterial> GetMaterial();\n        const std::string& Name() const;\n\n\t\tconst std::vector<DirectX::XMFLOAT3>& Vertices() const;\n\t\tconst std::vector<DirectX::XMFLOAT3>& Normals() const;\n\t\tconst std::vector<DirectX::XMFLOAT3>& Tangents() const;\n\t\tconst std::vector<DirectX::XMFLOAT3>& BiNormals() const;\n\t\tconst std::vector<std::vector<DirectX::XMFLOAT3>>& TextureCoordinates() const;\n\t\tconst std::vector<std::vector<DirectX::XMFLOAT4>>& VertexColors() const;\n\t\tstd::uint32_t FaceCount() const;\n\t\tconst std::vector<std::uint32_t>& Indices() const;\n\t\tconst std::vector<BoneVertexWeights>& BoneWeights() const;\n\n        void CreateIndexBuffer(ID3D11Device& device, gsl::not_null<ID3D11Buffer**> indexBuffer);\n\t\tvoid Save(OutputStreamHelper& streamHelper) const;\n\n    private:\n\t\tvoid Load(InputStreamHelper& streamHelper);\n\n        gsl::not_null<Library::Model*> mModel;\n\t\tMeshData mData;\n    };\n}", "meta": {"hexsha": "69e0d122af18149c0bfd18809ca0b77486578984", "size": 1973, "ext": "h", "lang": "C", "max_stars_repo_path": "source/Library.Shared/Mesh.h", "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/Library.Shared/Mesh.h", "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/Library.Shared/Mesh.h", "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.828125, "max_line_length": 96, "alphanum_fraction": 0.7116066903, "num_tokens": 556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.27512972382317524, "lm_q2_score": 0.01912403779909107, "lm_q1q2_score": 0.005261591238047891}}
{"text": "#ifndef ABLATE_FLUXDIFFERENCER_H\n#define ABLATE_FLUXDIFFERENCER_H\n#include <petsc.h>\n\ntypedef void (*FluxDifferencerFunction)(PetscReal Mm, PetscReal* sPm, PetscReal* sMm,\n                                            PetscReal Mp, PetscReal* sPp, PetscReal *sMp);\n\n#endif", "meta": {"hexsha": "4971097bea2252efc0afef2149b109ced10cde10", "size": 270, "ext": "h", "lang": "C", "max_stars_repo_path": "ablateCore/flow/fluxDifferencer.h", "max_stars_repo_name": "pakserep/ablate", "max_stars_repo_head_hexsha": "8c8443de8a252b03b3535f7c48b7a50aac1e56e4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ablateCore/flow/fluxDifferencer.h", "max_issues_repo_name": "pakserep/ablate", "max_issues_repo_head_hexsha": "8c8443de8a252b03b3535f7c48b7a50aac1e56e4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ablateCore/flow/fluxDifferencer.h", "max_forks_repo_name": "pakserep/ablate", "max_forks_repo_head_hexsha": "8c8443de8a252b03b3535f7c48b7a50aac1e56e4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.75, "max_line_length": 90, "alphanum_fraction": 0.6740740741, "num_tokens": 79, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1847675286043145, "lm_q2_score": 0.02843603489741593, "lm_q1q2_score": 0.005254055891301583}}
{"text": "#pragma once\n\n#include <memory>\n#include <string>\n#include <vector>\n#include <typeinfo>\n#include <type_traits>\n\n#include <gsl/gsl>\n\n#include <upca/config.h>\n\n#include \"arch/arch.h\"\n\nnamespace upca {\n\ntemplate <typename BACKEND> class resolver {\n  class description {\n\n    std::string name_;\n    unsigned size_;\n    unsigned offset_;\n    decltype(typename BACKEND::resolver_type().resolve({})) data_;\n\n  public:\n    description(std::string name, const unsigned size, const unsigned offset,\n                const typename BACKEND::resolver_type &resolver)\n        : name_(std::move(name)), size_(size), offset_(offset),\n          data_(resolver.resolve(name_)) {}\n    description(const char *name, const unsigned size, const unsigned offset,\n                const typename BACKEND::resolver_type &resolver)\n        : name_(name), size_(size), offset_(offset),\n          data_(resolver.resolve(name_)) {}\n\n    const std::string &name() const { return name_; }\n    unsigned size() const { return size_; }\n    unsigned offset() const { return offset_; }\n    decltype(auto) data() const { return data_; }\n  };\n\n  std::vector<description> counters_;\n  typename BACKEND::resolver_type resolver_;\n\npublic:\n  using value_type = description;\n  using iterator = typename std::vector<description>::iterator;\n  using const_iterator = typename std::vector<description>::const_iterator;\n\n  void add(const char *const name, const unsigned size = 8) {\n    counters_.emplace_back(name, size, counters_.size(), resolver_);\n  }\n\n  void add(std::string name, const unsigned size = 8) {\n    counters_.emplace_back(std::move(name), size, counters_.size(), resolver_);\n  }\n\n  size_t size() const { return counters_.size() + 1; }\n\n  unsigned bytesize() const {\n    unsigned sum = 0;\n    for (const auto &pmc : counters_) {\n      sum += pmc.size();\n    }\n    return sum;\n  }\n\n  const description &\n  at(const typename std::vector<description>::size_type pos) const {\n    return counters_.at(pos);\n  }\n  const_iterator begin() const { return counters_.cbegin(); }\n  const_iterator end() const { return counters_.cend(); }\n  const_iterator cbegin() const { return counters_.cbegin(); }\n  const_iterator cend() const { return counters_.cend(); }\n\n  /* Get PMU backend. Thread has to be pinned to a CPU before this is called */\n  std::unique_ptr<BACKEND> configure(const unsigned additional_counters = 0) const {\n    /* meh. add +1 for the \"out-of-band\" cycles counter :/ */\n    return std::make_unique<BACKEND>(counters_, additional_counters + 1);\n  }\n};\n\n/* sample pmcs */\n} // namespace upca\n", "meta": {"hexsha": "b79f3db422de064eab9435d9fae2c254b6f0f534", "size": 2564, "ext": "h", "lang": "C", "max_stars_repo_path": "include/upca/upca.h", "max_stars_repo_name": "hannesweisbach/ucpa", "max_stars_repo_head_hexsha": "e4062fd98d83f4cc57ee04f554540c09c1ca8ccd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-08-31T13:51:26.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-31T13:51:26.000Z", "max_issues_repo_path": "include/upca/upca.h", "max_issues_repo_name": "hannesweisbach/ucpa", "max_issues_repo_head_hexsha": "e4062fd98d83f4cc57ee04f554540c09c1ca8ccd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/upca/upca.h", "max_forks_repo_name": "hannesweisbach/ucpa", "max_forks_repo_head_hexsha": "e4062fd98d83f4cc57ee04f554540c09c1ca8ccd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1647058824, "max_line_length": 84, "alphanum_fraction": 0.6805772231, "num_tokens": 606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15610489744545739, "lm_q2_score": 0.03358950311062484, "lm_q1q2_score": 0.005243485938327963}}
{"text": "/*\n    COPYRIGHT DISCLAIMER\n\n    Vincent Le Guilloux, Peter Schmidtke and Pierre Tuffery, hereby\n\tdisclaim all copyright interest in the program \u201cfpocket\u201d (which\n\tperforms protein cavity detection) written by Vincent Le Guilloux and Peter\n\tSchmidtke.\n\n    Vincent Le Guilloux  28 November 2008\n    Peter Schmidtke      28 November 2008\n    Pierre Tuffery       28 November 2008\n\n    GNU GPL\n\n    This file is part of the fpocket package.\n\n    fpocket is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    fpocket is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with fpocket.  If not, see <http://www.gnu.org/licenses/>.\n\n**/\n\n\n#ifndef DH_UTILS\n#define DH_UTILS\n\n/* ------------------------------ INCLUDES ---------------------------------- */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <string.h>\n#include <ctype.h>\n#include <limits.h>\n#include <time.h>\n\n#ifdef MD_USE_GSL \t/* GSL */\n\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n\n#endif \t\t\t\t/* /GSL */\n\n#include \"memhandler.h\"\n\n/* ------------------------------- PUBLIC MACROS ---------------------------- */\n\n#define M_MAX_PDB_NAME_LEN 200  /**< maximum pdb filename length*/\n\n#define M_SIGN 1\n#define M_NO_SIGN 0\n\n\n#ifdef MD_USE_GSL\t/* GSL */\n\n#define M_GEN_MTWISTER gsl_rng_mt19937\n#define M_GEN_GFSR4 gsl_rng_gfsr4\n#define M_GEN_TAUS gsl_rng_taus2\n#define M_GEN_RANLXS0 gsl_rng_ranlxs0\n#define M_GEN_RANLXS1 gsl_rng_ranlxs1\n\n#endif\t\t\t\t/* /GSL */\n\n/* ------------------------------ PUBLIC STRUCTURES ------------------------- */\n\ntypedef struct tab_str \n{\n\tchar **t_str ;\n\tint nb_str ;\n\n} tab_str ; \n\n\n/* ------------------------------- PROTOTYPES ------------------------------- */\n\nint str_is_number(const char *str, const int sign) ;\nint str_is_float(const char *str, const int sign) ;\nvoid str_trim(char *str) ;\ntab_str* str_split(const char *str, const int sep) ;\n\ntab_str* f_readl(const char *fpath, int nchar_max) ;\nvoid free_tab_str(tab_str *tstr) ;\nvoid print_tab_str(tab_str* strings) ;\n\nint in_tab(int *tab, int size, int val) ;\nint index_of(int *tab, int size, int val)  ;\n\n\nvoid remove_ext(char *str) ;\nvoid remove_path(char *str) ;\nvoid extract_ext(char *str, char *dest) ;\nvoid extract_path(char *str, char *dest) ;\n\nvoid start_rand_generator(void) ;\nfloat rand_uniform(float min, float max) ;\n\nFILE* fopen_pdb_check_case(char *name, const char *mode)  ;\n\nfloat float_get_min_in_2D_array(float **t,size_t n,int col);\nfloat float_get_max_in_2D_array(float **t,size_t n,int col);\n\n#endif\n", "meta": {"hexsha": "03c1dc4b67047508777d429d9b9b74ea4edcdcb8", "size": 2946, "ext": "h", "lang": "C", "max_stars_repo_path": "fpocket2/headers/utils.h", "max_stars_repo_name": "hjuinj/docker_fpocket", "max_stars_repo_head_hexsha": "29d93d38a9757d0a10d83c0385cd028a6ae39fd4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fpocket2/headers/utils.h", "max_issues_repo_name": "hjuinj/docker_fpocket", "max_issues_repo_head_hexsha": "29d93d38a9757d0a10d83c0385cd028a6ae39fd4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fpocket2/headers/utils.h", "max_forks_repo_name": "hjuinj/docker_fpocket", "max_forks_repo_head_hexsha": "29d93d38a9757d0a10d83c0385cd028a6ae39fd4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3035714286, "max_line_length": 80, "alphanum_fraction": 0.6676849966, "num_tokens": 739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21469141911224196, "lm_q2_score": 0.02442308805698452, "lm_q1q2_score": 0.005243427434057255}}
{"text": "\n#pragma once\n\n#include <gsl/span>\n\n#include \"aas/aas_math.h\"\n\nnamespace aas {\n\n\tclass Skeleton;\n\tstruct SkelAnim;\n\tstruct SkelBoneState;\n\n\tstruct AnimPlayerStreamHeader {\n\t\tint field0;\n\t\tint field1;\n\t\tint field2;\n\t\tint8_t pad[3];\n\t};\n\n\tstruct AnimPlayerStreamBone\n\t{\n\t\tDX::XMFLOAT4 prevScale;\n\t\tDX::XMFLOAT4 scale;\n\t\tDX::XMFLOAT4 prevRotation;\n\t\tDX::XMFLOAT4 rotation;\n\t\tDX::XMFLOAT4 prevTranslation;\n\t\tDX::XMFLOAT4 translation;\n\t\tint16_t scaleFrame;\n\t\tint16_t scaleNextFrame;\n\t\tint16_t rotationFrame;\n\t\tint16_t rotationNextFrame;\n\t\tint16_t translationFrame;\n\t\tint16_t translationNextFrame;\n\t\tint field6C;\n\t};\n\n\tstruct AnimPlayerStream {\n\t\tconst Skeleton* skeleton;\n\t\tconst SkelAnim* animation;\n\t\tint streamIdx;\n\t\tfloat scaleFactor;\n\t\tfloat translationFactor;\n\t\tfloat currentFrame;\n\t\tvoid* keyframePtr;\n\t\tint boneCount;\n\t\tAnimPlayerStreamBone bones[1]; //set according to skafile bone count\n\t\t\n\t\tAnimPlayerStream(AnimPlayerStream&) = delete;\n\t\tAnimPlayerStream(AnimPlayerStream&&) = delete;\n\t\tAnimPlayerStream& operator=(AnimPlayerStream&) = delete;\n\t\tAnimPlayerStream& operator=(AnimPlayerStream&&) = delete;\n\n\n\t\tvoid SetFrame(float frame);\n\t\tvoid Initialize(const SkelAnim *animation, int streamIdx);\n\t\tvoid GetBoneState(gsl::span<SkelBoneState> boneStateOut);\n\t\tfloat GetCurrentFrame() const;\n\t};\n\n}\n", "meta": {"hexsha": "626bf6c15ef29e69167d7b5bf433c00baa2eb60e", "size": 1304, "ext": "h", "lang": "C", "max_stars_repo_path": "Infrastructure/src/aas/aas_anim_player_stream.h", "max_stars_repo_name": "edoipi/TemplePlus", "max_stars_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 69.0, "max_stars_repo_stars_event_min_datetime": "2015-05-05T14:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T06:13:04.000Z", "max_issues_repo_path": "Infrastructure/src/aas/aas_anim_player_stream.h", "max_issues_repo_name": "edoipi/TemplePlus", "max_issues_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 457.0, "max_issues_repo_issues_event_min_datetime": "2015-05-01T22:07:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T02:19:10.000Z", "max_forks_repo_path": "Infrastructure/src/aas/aas_anim_player_stream.h", "max_forks_repo_name": "edoipi/TemplePlus", "max_forks_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2016-02-04T21:19:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T23:14:51.000Z", "avg_line_length": 21.0322580645, "max_line_length": 70, "alphanum_fraction": 0.7515337423, "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.27825680567280014, "lm_q2_score": 0.018833128307170766, "lm_q1q2_score": 0.0052404461235793275}}
{"text": "/*\n * author: Achim Gaedke\n * created: January 2001\n * file: pygsl/src/histogrammodule.c\n * $Id: histogrammodule.c,v 1.3 2008/10/26 17:03:23 schnizer Exp $\n *\n *\n * May 2005\n *    Pierre Schnizer \n *    maintainance: replaced direct python error calls with pygsl calls \n *    added CAST and GET macros to reduce code duplication\n * \n *    Now the warnings are all handled by a separate function.   \n */\n\n#include <pygsl/error_helpers.h>\n#include <pygsl/block_helpers.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_histogram.h>\n#include <gsl/gsl_histogram2d.h>\n\n\nenum hist_error{\n     NOHIST = 0,\n     NOHIST2D,\n     ARGNOHIST,\n     ARGNOHIST2D,\n     HISTP_NULL\n};\nstatic const char * filename = __FILE__;\nstatic PyObject * module = NULL;\n#include \"histogram_doc.ic\"\n\n\nstatic int \nPyGSL_hist_error_helper(const char * function, int line, int myerrno, enum hist_error errtype)\n{\n     char *tmp;\n     switch (errtype){\n     case NOHIST:      tmp = \"Object was not a histogramm\"; break;\n     case NOHIST2D:    tmp = \"Object was not a 2D histogramm\"; break;\n     case ARGNOHIST:   tmp = \"Argument was not a histogramm\"; break;\n     case ARGNOHIST2D: tmp = \"Argument was not a 2D histogramm\"; break;\n     case HISTP_NULL:  tmp = \"Pointer to GSL histogramm(2d) object was NULL!\"; break;\n     default:          tmp = \"Unknown case in function hist_error_helper\"; myerrno = GSL_ESANITY; break;\n     }\n     PyGSL_add_traceback(module, filename, function, line);\n     pygsl_error(tmp, filename, line, myerrno);\n     return myerrno;\n}\n\n/*\n * Check if the recieved object is of approbriate type and that the histogram is defined.\n * Invokes PyGSL_hist_error_helper if it fails.\n * returns GSL_SUCCESS on success\n *\n * ob      ... the object to check\n * type    ... the Python type object\n * errcode ... the errorcode used to describe the failure type for \n *             PyGSL_hist_error_helper\n */\n\n#define _PyGSL_HIST_CHECK_INT(ob, type, errcode) \\\n     ((ob->ob_type == &(type)) ?  GSL_SUCCESS :  \\\n     PyGSL_hist_error_helper(__FUNCTION__, __LINE__, (errcode), GSL_ESANITY))\n\n/*\n * returns the gsl histogram from the object\n */\n#define _PyGSL_HIST_CAST(ob, type) (( ((type *)(ob)) ->h ))\n\n/*\n * Check if it the gsl_histogram is not NULL. Will give a descriptive error\n * message if it fails.\n */\n#define _PyGSL_HIST_CAST_SAVE(ob, type) \\\n      (\\\n          (_PyGSL_HIST_CAST((ob), type)  == NULL ) \\\n        ? \\\n          (PyGSL_hist_error_helper(__FUNCTION__, __LINE__, GSL_EFAULT, HISTP_NULL), NULL) \\\n        : \\\n          ( _PyGSL_HIST_CAST((ob), type) ) \\\n      ) \n\n/*\n * Try to get the gsl_histogram from the python object.\n * Checks for errors ...\n */\n#define _PyGSL_HIST_GET_INT(ob, type, cast, errcode) \\\n      ( \\\n          (  _PyGSL_HIST_CHECK_INT((ob), type, (errcode)) == GSL_SUCCESS ) \\\n        ? \\\n          _PyGSL_HIST_CAST_SAVE((ob), cast) \\\n\t: \\\n          NULL \\\n      )\n#define _PyGSL_HIST_GET(ob, type, errcode) _PyGSL_HIST_GET_INT(ob, type ## Type, type ## Object, errcode) \n\n#define _PyGSL_HIST_CHECK(ob, errcode)   _PyGSL_HIST_CHECK_INT((ob), (histogram_histogramType), (errcode)) \n#define _PyGSL_HIST2D_CHECK(ob, errcode) _PyGSL_HIST_CHECK_INT((ob), (histogram_histogram2dType), (errcode)) \n\n#define PyGSL_HIST_CHECK(ob)       _PyGSL_HIST_CHECK((ob), (NOHIST)) \n#define PyGSL_HIST2D_CHECK(ob)     _PyGSL_HIST2D_CHECK((ob), (NOHIST2D)) \n#define PyGSL_HIST_ARG_CHECK(ob)   _PyGSL_HIST_CHECK((ob), (ARGNOHIST)) \n#define PyGSL_HIST2D_ARG_CHECK(ob) _PyGSL_HIST2D_CHECK((ob), (ARGNOHIST2D)) \n\n#define PyGSL_HIST_CAST(ob)   _PyGSL_HIST_CAST((ob), histogram_histogramObject)\n#define PyGSL_HIST2D_CAST(ob) _PyGSL_HIST_CAST((ob), histogram_histogram2dObject)\n\n\n#define PyGSL_HIST_GET(ob)        _PyGSL_HIST_GET((ob), histogram_histogram,   (NOHIST))\n#define PyGSL_HIST2D_GET(ob)      _PyGSL_HIST_GET((ob), histogram_histogram2d, (NOHIST2D))\n#define _PyGSL_HIST_GET_ARG(ob)   _PyGSL_HIST_GET((ob), histogram_histogram,   (ARGNOHIST))\n#define _PyGSL_HIST2D_GET_ARG(ob) _PyGSL_HIST_GET((ob), histogram_histogram2d, (ARGNOHIST2D))\n\n\n#define PyGSL_HIST_GET_ARG(ob)   ( ((ob) == NULL) ? NULL : _PyGSL_HIST_GET_ARG((ob)) )\n#define PyGSL_HIST2D_GET_ARG(ob) ( ((ob) == NULL) ? NULL : _PyGSL_HIST2D_GET_ARG((ob)) )\n\n/*\n * Helper function for dealing with warning and errors ...\n */\nstatic int\nPyGSL_warn_err(int rcode, int errcode, const char * errdes, const char * file, int line)\n{\n     int warn_result;   \n     if (errcode==rcode) {\n\t  warn_result = PyGSL_warning(errdes, file, line, errcode);\n\t  if (warn_result==-1)\n\t       /* exception is raised by PyErr_Warn */\n\t       return GSL_EFAILED;\n     }\n     else if (PyGSL_ERROR_FLAG(rcode) != GSL_SUCCESS)\n\t  return rcode;\n\n     return GSL_SUCCESS;\n}\n\n#define PyGSL_WARN_ERR(ob, errcode, errdes) \\\n   (\\\n       ((ob) == (GSL_SUCCESS)) \\\n      ? \\\n         GSL_SUCCESS \\\n      : \\\n          ((ob) == (errcode)) \\\n        ? PyGSL_warn_err(ob, errcode, errdes, filename, __LINE__) \\\n        : PyGSL_error_flag((ob)) \\\n    )  \n\nstatic const char edom_message[] =  \"value out of histogram range\";\n#define PyGSL_HIST_EDOM_WARN(ob) PyGSL_WARN_ERR((ob), GSL_EDOM, edom_message)\n\ntypedef int (*hist_op)(void *, const void *);\ntypedef int (*hist_file)(FILE *, void *);\n\n\nstatic PyObject *\nhistogram_histogram_op(PyObject *self, PyObject * arg, hist_op fptr);\nstatic PyObject *\nhistogram_histogram2d_op(PyObject *self, PyObject * arg, hist_op fptr);\nstatic PyObject *\nhistogram_histogram_file(PyObject *self, PyObject * arg, hist_file fptr);\nstatic PyObject *\nhistogram_histogram2d_file(PyObject *self, PyObject * arg, hist_file fptr);\n\n\n/*\n *\n * histogram type\n * for 1d histogram data\n *\n */\n\n\n/* my typedef */\n\nstaticforward PyTypeObject histogram_histogramType;\nstaticforward PyMethodDef histogram_histogram_methods[];\n\ntypedef struct {\n    PyObject_HEAD\n    gsl_histogram* h;\n} histogram_histogramObject;\n\n\n#define _CONCAT2(class, suffix) class ## _ ## suffix\n\n#include \"histogram.ic\"\n\n#define HISTTYPE gsl_histogram\n#define PyGSLHISTTYPE histogram_histogramType\n#define PyGSL_HIST_TYPE_GET(ob) PyGSL_HIST_GET((ob))\n#define PyGSL_HIST_TYPE_CAST(ob) PyGSL_HIST_CAST((ob))\n#define PyGSL_HIST_TYPE_ARG_GET(ob) PyGSL_HIST_GET_ARG((ob))\n#define GSLNAME(suffix)  _CONCAT2(gsl_histogram, suffix)\n#define FUNCNAME(suffix) _CONCAT2(histogram_histogram, suffix)\n#ifdef HISTOGRAM2D\n#undef HISTOGRAM2D\n#endif\n#include \"histogram_pdf_common.ic\"\n#include \"histogram_common.ic\"\n\n#undef HISTTYPE\n#undef PyGSLHISTTYPE\n#undef PyGSL_HIST_TYPE_GET\n#undef PyGSL_HIST_TYPE_CAST\n#undef PyGSL_HIST_TYPE_ARG_GET\n#undef FUNCNAME \n#undef GSLNAME\n\n\n\nstatic\nPyTypeObject histogram_histogramType = {\n\tPyObject_HEAD_INIT(NULL)\n\t0,\n\t\"pygsl.histogram.histogram\",\n\tsizeof(histogram_histogramObject),\n\t0,\n\t(destructor)histogram_histogram_dealloc, /* tp_dealloc */\n\t0,                                      /* tp_print */\n\thistogram_histogram_getattr,            /* tp_getattr */\n\t0,\t\t\t\t\t/* tp_setattr */\n\t0,\t\t\t                /* tp_compare */\n\t0,                  \t\t\t/* tp_repr */\n\t0,\t\t\t\t\t/* tp_as_number */\n\t0,\t                \t\t/* tp_as_sequence */\n\t&histogram_histogram_as_mapping,\t/* tp_as_mapping */\n\t0,\t\t\t\t        /* tp_hash */\n\t0,\t\t\t\t\t/* tp_call */\n\t0,\t\t\t\t\t/* tp_str */\n\t0,\t\t                        /* tp_getattro */\n\t0,\t\t\t\t\t/* tp_setattro */\n\t0,\t\t\t\t\t/* tp_as_buffer */\n\tPy_TPFLAGS_DEFAULT,\t\t        /* tp_flags */\n        0,\t\t\t\t        /* tp_doc */\n\t0, \t\t                        /* tp_traverse */\n\t0,\t\t\t                /* tp_clear */\n\t0,              \t\t\t/* tp_richcompare */\n\t0,\t\t\t\t\t/* tp_weaklistoffset */\n\t0,\t\t\t                /* tp_iter */\n\t0,\t\t\t\t\t/* tp_iternext */\n\t0,\t\t\t\t        /* tp_methods */\n\t0,\t\t\t\t\t/* tp_members */\n\t0,\t\t\t\t\t/* tp_getset */\n\t0,\t\t\t\t\t/* tp_base */\n\t0,\t\t\t\t\t/* tp_dict */\n\t0,\t\t\t\t\t/* tp_descr_get */\n\t0,\t\t\t\t\t/* tp_descr_set */\n\t0,\t\t\t\t\t/* tp_dictoffset */\n\t(initproc)histogram_histogram_init,\t/* tp_init */\n\tNULL,              \t\t\t/* tp_alloc */\n\tNULL,                \t\t\t/* tp_new */\n\tNULL         \t\t\t        /* tp_free */\n};\n\n\n/*\n *\n * here begins the section for the 2d histogram\n *\n */\n\n/* my typedef */\n\nstaticforward PyTypeObject histogram_histogram2dType;\nstaticforward PyMethodDef histogram_histogram2d_methods[];\ntypedef struct {\n    PyObject_HEAD\n    gsl_histogram2d* h;\n} histogram_histogram2dObject;\n\n\nstatic PyObject *\nhistogram_histogram2d_reset(PyObject *);\n\n#include \"histogram2d.ic\"\n#define HISTOGRAM2D 1\n#define HISTTYPE gsl_histogram2d\n#define PyGSLHISTTYPE histogram_histogram2dType\n#define PyGSL_HIST_TYPE_GET(ob) PyGSL_HIST2D_GET((ob))\n#define PyGSL_HIST_TYPE_ARG_GET(ob) PyGSL_HIST2D_GET_ARG((ob))\n#define PyGSL_HIST_TYPE_CAST(ob) PyGSL_HIST2D_CAST((ob))\n#define GSLNAME(suffix)  _CONCAT2(gsl_histogram2d, suffix)\n#define FUNCNAME(suffix) _CONCAT2(histogram_histogram2d, suffix)\n#include \"histogram_pdf_common.ic\"\n#include \"histogram_common.ic\"\n\n\n\nstatic\nPyTypeObject histogram_histogram2dType = {\n\tPyObject_HEAD_INIT(NULL)\n\t0,\n\t\"pygsl.histogram.histogram2d\",\n\tsizeof(histogram_histogram2dObject),\n\t0,\n\t(destructor)histogram_histogram2d_dealloc, /* tp_dealloc */\n\t0,                                      /* tp_print */\n\thistogram_histogram2d_getattr,          /* tp_getattr */\n\t0,\t\t\t\t\t/* tp_setattr */\n\t0,\t\t\t                /* tp_compare */\n\t0,                  \t\t\t/* tp_repr */\n\t0,\t\t\t\t\t/* tp_as_number */\n\t0,\t                \t\t/* tp_as_sequence */\n\t&histogram_histogram2d_as_mapping,      /* tp_as_mapping */\n\t0,\t\t\t\t        /* tp_hash */\n\t0,\t\t\t\t\t/* tp_call */\n\t0,\t\t\t\t\t/* tp_str */\n\t0,\t\t                        /* tp_getattro */\n\t0,\t\t\t\t\t/* tp_setattro */\n\t0,\t\t\t\t\t/* tp_as_buffer */\n\tPy_TPFLAGS_DEFAULT,\t\t        /* tp_flags */\n        0,\t\t\t\t        /* tp_doc */\n\t0, \t\t                        /* tp_traverse */\n\t0,\t\t\t                /* tp_clear */\n\t0,              \t\t\t/* tp_richcompare */\n\t0,\t\t\t\t\t/* tp_weaklistoffset */\n\t0,\t\t\t                /* tp_iter */\n\t0,\t\t\t\t\t/* tp_iternext */\n\t0,\t\t\t\t        /* tp_methods */\n\t0,\t\t\t\t\t/* tp_members */\n\t0,\t\t\t\t\t/* tp_getset */\n\t0,\t\t\t\t\t/* tp_base */\n\t0,\t\t\t\t\t/* tp_dict */\n\t0,\t\t\t\t\t/* tp_descr_get */\n\t0,\t\t\t\t\t/* tp_descr_set */\n\t0,\t\t\t\t\t/* tp_dictoffset */\n\t(initproc)histogram_histogram2d_init,\t/* tp_init */\n\tNULL,            \t\t\t/* tp_alloc */\n\tNULL,\t\t\t                /* tp_new */\n\tNULL\t\t\t                /* tp_free */\n};\n\n#include \"histogram_pdf.ic\"\n/*\n *\n * module specific stuff\n *\n */\n\n\nstatic PyMethodDef histogramMethods[] = {\n  {NULL, NULL, 0, NULL}        /* Sentinel */\n};\n\n\nvoid \nregister_type(PyTypeObject *p, char *name)\n{\n     p->ob_type  = &PyType_Type;\n     p->tp_alloc = PyType_GenericAlloc;\n     p->tp_new   = PyType_GenericNew;\n     p->tp_free  = _PyObject_Del;\n     /* install histogram type */\n     /* important! must increment histogram type reference counter */\n     Py_INCREF((PyObject*)p);\n     PyModule_AddObject(module, name, (PyObject*)p);     \n}\n\nvoid\ninithistogram(void)\n{\n  PyObject* m;\n  m=Py_InitModule(\"histogram\", histogramMethods);\n  if(!m)\n       return;\n\n  module = m;\n  init_pygsl();\n  /* init histogram type */\n  register_type(&histogram_histogramType, \"histogram\");\n  register_type(&histogram_histogram_pdfType, \"histogram_pdf\");\n  register_type(&histogram_histogram2dType, \"histogram2d\");\n  register_type(&histogram_histogram2d_pdfType, \"histogram2d_pdf\");\n}\n", "meta": {"hexsha": "7fc3c05679ec52d902e8228dce0defc666a735d9", "size": 11191, "ext": "c", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/src/histogram/histogrammodule.c", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/src/histogram/histogrammodule.c", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/src/histogram/histogrammodule.c", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 29.6843501326, "max_line_length": 109, "alphanum_fraction": 0.6476633009, "num_tokens": 3196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14223189864583882, "lm_q2_score": 0.03676946805470428, "lm_q1q2_score": 0.0052297912536181075}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n//\n// Copyright (c) 2015 Microsoft Corporation. All rights reserved.\n//\n// This code is licensed under the MIT License (MIT).\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef BITVEC_DECL_H\n#define BITVEC_DECL_H\n\n#include <gsl/gsl_assert> // for Expects\n#include <gsl/gsl_util>   // for narrow_cast, narrow\n\nusing gsl::narrow_cast;\n\n#include <cstddef>  // for ptrdiff_t, size_t, nullptr_t\n#include <iterator> // for reverse_iterator, distance, random_access_...\n#include <memory>\n\n#ifdef _MSC_VER\n#pragma warning(push)\n\n// turn off some warnings that are noisy about our Expects statements\n#pragma warning(disable : 4127) // conditional expression is constant\n#pragma warning(disable : 4702) // unreachable code\n\n// Turn MSVC /analyze rules that generate too much noise. TODO: fix in the tool.\n#pragma warning(                                                               \\\n    disable : 26495) // uninitalized member when constructor calls constructor\n#pragma warning(                                                               \\\n    disable : 26446) // parser bug does not allow attributes on some templates\n\n#endif // _MSC_VER\n\nnamespace gb {\n\n// shared_ptr without atomic overhead\ntemplate <typename T>\nusing shared_ptr_unsynchronized = std::__shared_ptr<T, __gnu_cxx::_S_single>;\n\n// [views.constants], constants\nconst std::ptrdiff_t dynamic_extent = -1;\n\ntemplate <std::ptrdiff_t Extent = dynamic_extent> class bitvec;\n\n// implementation details\nnamespace details {\ntemplate <class Span, bool IsConst> class span_iterator {\n\tusing element_type_ = typename Span::element_type;\n\n  public:\n#ifdef _MSC_VER\n\t// Tell Microsoft standard library that span_iterators are checked.\n\tusing _Unchecked_type = typename Span::pointer;\n#endif\n\n\tusing iterator_category = std::random_access_iterator_tag;\n\tusing value_type = std::remove_cv_t<element_type_>;\n\tusing difference_type = typename Span::index_type;\n\n\tusing pointer = shared_ptr_unsynchronized<\n\t    std::conditional_t<IsConst, const element_type_, element_type_>>;\n\n\tspan_iterator() = default;\n\n\tspan_iterator(const Span *bitvec, typename Span::index_type idx) noexcept\n\t    : span_(bitvec), index_(idx) {}\n\n\tfriend span_iterator<Span, true>;\n\ttemplate <bool B, std::enable_if_t<!B && IsConst> * = nullptr>\n\tspan_iterator(const span_iterator<Span, B> &other) noexcept\n\t    : span_iterator(other.span_, other.index_) {}\n\n\tstd::conditional_t<IsConst, const bitvec<1>, bitvec<1>> operator*() const {\n\t\tExpects(index_ != span_->size());\n\t\treturn std::conditional_t<IsConst, const bitvec<1>, bitvec<1>>(\n\t\t    (*span_)[index_]);\n\t}\n\n\tpointer operator->() const {\n\t\tExpects(index_ != span_->size());\n\t\treturn span_->data() + index_;\n\t}\n\n\tspan_iterator &operator++() {\n\t\tExpects(0 <= index_ && index_ != span_->size());\n\t\t++index_;\n\t\treturn *this;\n\t}\n\n\tspan_iterator &operator--() {\n\t\tExpects(index_ != 0 && index_ <= span_->size());\n\t\t--index_;\n\t\treturn *this;\n\t}\n\n\tpointer operator[](difference_type n) const { return *(*this + n); }\n\n\tfriend bool operator==(span_iterator lhs, span_iterator rhs) noexcept {\n\t\treturn lhs.span_ == rhs.span_ && lhs.index_ == rhs.index_;\n\t}\n\n\tfriend bool operator!=(span_iterator lhs, span_iterator rhs) noexcept {\n\t\treturn !(lhs == rhs);\n\t}\n\n\tfriend bool operator<(span_iterator lhs, span_iterator rhs) noexcept {\n\t\treturn lhs.index_ < rhs.index_;\n\t}\n\n#ifdef _MSC_VER\n\t// MSVC++ iterator debugging support; allows STL algorithms in 15.8+\n\t// to unwrap span_iterator to a pointer type after a range check in STL\n\t// algorithm calls\n\tfriend void _Verify_range(\n\t    span_iterator lhs,\n\t    span_iterator rhs) noexcept {  // test that [lhs, rhs) forms a valid\n\t\t                               // range inside an STL algorithm\n\t\tExpects(lhs.span_ == rhs.span_ // range spans have to match\n\t\t        && lhs.index_ <= rhs.index_); // range must not be transposed\n\t}\n\n\tvoid _Verify_offset(const difference_type n) const\n\t    noexcept { // test that the iterator *this + n is a valid range in an\n\t\t           // STL\n\t\t// algorithm call\n\t\tExpects((index_ + n) >= 0 && (index_ + n) <= span_->size());\n\t}\n\n\tGSL_SUPPRESS(bounds .1)               // NO-FORMAT: attribute\n\tpointer _Unwrapped() const noexcept { // after seeking *this to a high water\n\t\t                                  // mark, or using one of the\n\t\t// _Verify_xxx functions above, unwrap this span_iterator to a raw\n\t\t// pointer\n\t\treturn span_->data() + index_;\n\t}\n\n\t// Tell the STL that span_iterator should not be unwrapped if it can't\n\t// validate in advance, even in release / optimized builds:\n\tstatic const bool _Unwrap_when_unverified = false;\n\tGSL_SUPPRESS(con .3) // NO-FORMAT: attribute // TODO: false positive\n\tvoid _Seek_to(const pointer p) noexcept { // adjust the position of *this to\n\t\t                                      // previously verified location p\n\t\t// after _Unwrapped\n\t\tindex_ = p - span_->data();\n\t}\n#endif\n\n  protected:\n\tconst Span *span_ = nullptr;\n\tstd::ptrdiff_t index_ = 0;\n};\n\n// Used for empty base class optimization\ntemplate <std::ptrdiff_t Ext> class extent_type {\n  public:\n\tusing index_type = std::ptrdiff_t;\n\n\tstatic_assert(Ext >= 0, \"A fixed-size bitvec must be >= 0 in size.\");\n\n\textent_type() noexcept {}\n\n\ttemplate <index_type Other> extent_type(extent_type<Other> ext) {\n\t\tstatic_assert(Other == Ext || Other == dynamic_extent,\n\t\t              \"Mismatch between fixed-size extent and size of \"\n\t\t              \"initializing data.\");\n\t\tExpects(ext.size() == Ext);\n\t}\n\n\textent_type(index_type size) { Expects(size == Ext); }\n\n\tindex_type size() const noexcept { return Ext; }\n};\n\ntemplate <> class extent_type<dynamic_extent> {\n  public:\n\tusing index_type = std::ptrdiff_t;\n\n\ttemplate <index_type Other>\n\texplicit extent_type(extent_type<Other> ext) : size_(ext.size()) {}\n\n\texplicit extent_type(index_type size) : size_(size) { Expects(size >= 0); }\n\n\tindex_type size() const noexcept { return size_; }\n\n  private:\n\tindex_type size_;\n};\n\ntemplate <std::ptrdiff_t Extent, std::ptrdiff_t Offset, std::ptrdiff_t Count>\nstruct calculate_subspan_type {\n\tusing type =\n\t    bitvec<Count != dynamic_extent\n\t             ? Count\n\t             : (Extent != dynamic_extent ? Extent - Offset : Extent)>;\n};\n} // namespace details\n\n} // namespace gb\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif // _MSC_VER\n\n#endif // BITVEC_DECL_H\n", "meta": {"hexsha": "d5add5ca0543d8c2cf125d49cb238b17c868c56d", "size": 6907, "ext": "h", "lang": "C", "max_stars_repo_path": "include/bitvec_decl.h", "max_stars_repo_name": "CapacitorSet/FHE-tools", "max_stars_repo_head_hexsha": "1271f2d65b3390c7156606b266b93c5d23ed398a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-08-28T04:50:57.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-26T22:06:36.000Z", "max_issues_repo_path": "include/bitvec_decl.h", "max_issues_repo_name": "CapacitorSet/Glovebox", "max_issues_repo_head_hexsha": "1271f2d65b3390c7156606b266b93c5d23ed398a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/bitvec_decl.h", "max_forks_repo_name": "CapacitorSet/Glovebox", "max_forks_repo_head_hexsha": "1271f2d65b3390c7156606b266b93c5d23ed398a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1255813953, "max_line_length": 80, "alphanum_fraction": 0.670044882, "num_tokens": 1626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1801066552847503, "lm_q2_score": 0.028870907572972133, "lm_q1q2_score": 0.005199842598003179}}
{"text": "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\n#pragma once\n\n#include \"core/common/logging/logging.h\"\n#include \"core/framework/allocatormgr.h\"\n#include \"core/framework/customregistry.h\"\n#include \"core/framework/execution_frame.h\"\n#include \"core/framework/op_kernel.h\"\n#include \"core/framework/run_options.h\"\n#include \"core/framework/session_state.h\"\n#include \"core/framework/tensor.h\"\n#include \"core/graph/graph_viewer.h\"\n#include \"core/graph/model.h\"\n#include \"core/framework/data_types.h\"\n#include \"test/test_environment.h\"\n#include \"test/framework/TestAllocatorManager.h\"\n#include \"core/framework/TensorSeq.h\"\n#include \"core/framework/session_options.h\"\n\n#include \"gmock/gmock.h\"\n#include \"gtest/gtest.h\"\n#include <gsl/gsl>\n#include \"core/util/math_cpuonly.h\"\n\n// helpers to run a function and check the status, outputting any error if it fails.\n// note: wrapped in do{} while(false) so the _tmp_status variable has limited scope\n#define ASSERT_STATUS_OK(function)                  \\\n  do {                                              \\\n    auto _tmp_status = function;                    \\\n    ASSERT_TRUE(_tmp_status.IsOK()) << _tmp_status; \\\n  } while (false)\n\n#define EXPECT_STATUS_OK(function)                  \\\n  do {                                              \\\n    auto _tmp_status = function;                    \\\n    EXPECT_TRUE(_tmp_status.IsOK()) << _tmp_status; \\\n  } while (false)\n\nnamespace onnxruntime {\nclass InferenceSession;\nstruct SessionOptions;\n\nnamespace test {\ntemplate <typename T>\nstruct SeqTensors {\n  void AddTensor(const std::vector<int64_t>& shape0, const std::vector<T>& data0) {\n    tensors.push_back(Tensor<T>{shape0, data0});\n  }\n\n  template <typename U>\n  struct Tensor {\n    std::vector<int64_t> shape;\n    std::vector<U> data;\n  };\n  std::vector<Tensor<T>> tensors;\n};\n\n// unfortunately std::optional is in C++17 so use a miniversion of it\ntemplate <typename T>\nclass optional {\n public:\n  optional(T v) : has_value_(true), value_(v) {}\n  optional() : has_value_(false) {}\n  bool has_value() const { return has_value_; }\n  const T& value() const {\n    ORT_ENFORCE(has_value_);\n    return value_;\n  }\n\n private:\n  bool has_value_;\n  T value_;\n};\n\n// Function templates to translate C++ types into ONNX_NAMESPACE::TensorProto_DataTypes\ntemplate <typename T>\nconstexpr ONNX_NAMESPACE::TensorProto_DataType TypeToDataType();\n\ntemplate <>\nconstexpr ONNX_NAMESPACE::TensorProto_DataType TypeToDataType<float>() {\n  return ONNX_NAMESPACE::TensorProto_DataType_FLOAT;\n}\n\ntemplate <>\nconstexpr ONNX_NAMESPACE::TensorProto_DataType TypeToDataType<double>() {\n  return ONNX_NAMESPACE::TensorProto_DataType_DOUBLE;\n}\n\ntemplate <>\nconstexpr ONNX_NAMESPACE::TensorProto_DataType TypeToDataType<int32_t>() {\n  return ONNX_NAMESPACE::TensorProto_DataType_INT32;\n}\n\ntemplate <>\nconstexpr ONNX_NAMESPACE::TensorProto_DataType TypeToDataType<int64_t>() {\n  return ONNX_NAMESPACE::TensorProto_DataType_INT64;\n}\n\ntemplate <>\nconstexpr ONNX_NAMESPACE::TensorProto_DataType TypeToDataType<bool>() {\n  return ONNX_NAMESPACE::TensorProto_DataType_BOOL;\n}\n\ntemplate <>\nconstexpr ONNX_NAMESPACE::TensorProto_DataType TypeToDataType<int8_t>() {\n  return ONNX_NAMESPACE::TensorProto_DataType_INT8;\n}\n\ntemplate <>\nconstexpr ONNX_NAMESPACE::TensorProto_DataType TypeToDataType<int16_t>() {\n  return ONNX_NAMESPACE::TensorProto_DataType_INT16;\n}\n\ntemplate <>\nconstexpr ONNX_NAMESPACE::TensorProto_DataType TypeToDataType<uint8_t>() {\n  return ONNX_NAMESPACE::TensorProto_DataType_UINT8;\n}\n\ntemplate <>\nconstexpr ONNX_NAMESPACE::TensorProto_DataType TypeToDataType<uint16_t>() {\n  return ONNX_NAMESPACE::TensorProto_DataType_UINT16;\n}\n\ntemplate <>\nconstexpr ONNX_NAMESPACE::TensorProto_DataType TypeToDataType<uint32_t>() {\n  return ONNX_NAMESPACE::TensorProto_DataType_UINT32;\n}\n\ntemplate <>\nconstexpr ONNX_NAMESPACE::TensorProto_DataType TypeToDataType<uint64_t>() {\n  return ONNX_NAMESPACE::TensorProto_DataType_UINT64;\n}\n\ntemplate <>\nconstexpr ONNX_NAMESPACE::TensorProto_DataType TypeToDataType<std::string>() {\n  return ONNX_NAMESPACE::TensorProto_DataType_STRING;\n}\n\ntemplate <>\nconstexpr ONNX_NAMESPACE::TensorProto_DataType TypeToDataType<MLFloat16>() {\n  return ONNX_NAMESPACE::TensorProto_DataType_FLOAT16;\n}\n\ntemplate <>\nconstexpr ONNX_NAMESPACE::TensorProto_DataType TypeToDataType<BFloat16>() {\n  return ONNX_NAMESPACE::TensorProto_DataType_BFLOAT16;\n}\n\ntemplate <typename T>\nstruct TTypeProto : ONNX_NAMESPACE::TypeProto {\n  TTypeProto(const std::vector<int64_t>* shape = nullptr) {\n    mutable_tensor_type()->set_elem_type(TypeToDataType<T>());\n\n    if (shape) {\n      auto mutable_shape = mutable_tensor_type()->mutable_shape();\n      for (auto i : *shape) {\n        auto* mutable_dim = mutable_shape->add_dim();\n        if (i != -1)\n          mutable_dim->set_dim_value(i);\n        else\n          mutable_dim->set_dim_param(\"symbolic\");\n      }\n    }\n  }\n};\n\n// Variable template for ONNX_NAMESPACE::TensorProto_DataTypes, s_type_proto<float>, etc..\ntemplate <typename T>\nstruct TTensorType {\n  static const TTypeProto<T> s_type_proto;\n};\n\ntemplate <typename T>\nconst TTypeProto<T> TTensorType<T>::s_type_proto;\n\n// TypeProto for map<TKey, TVal>\ntemplate <typename TKey, typename TVal>\nstruct MTypeProto : ONNX_NAMESPACE::TypeProto {\n  MTypeProto() {\n    mutable_map_type()->set_key_type(TypeToDataType<TKey>());\n    mutable_map_type()->mutable_value_type()->mutable_tensor_type()->set_elem_type(TypeToDataType<TVal>());\n    mutable_map_type()->mutable_value_type()->mutable_tensor_type()->mutable_shape()->clear_dim();\n  }\n};\n\ntemplate <typename TKey, typename TVal>\nstruct MMapType {\n  static const MTypeProto<TKey, TVal> s_map_type_proto;\n};\n\ntemplate <typename TKey, typename TVal>\nconst MTypeProto<TKey, TVal> MMapType<TKey, TVal>::s_map_type_proto;\n\n// TypeProto for vector<map<TKey, TVal>>\ntemplate <typename TKey, typename TVal>\nstruct VectorOfMapTypeProto : ONNX_NAMESPACE::TypeProto {\n  VectorOfMapTypeProto() {\n    auto* map_type = mutable_sequence_type()->mutable_elem_type()->mutable_map_type();\n    map_type->set_key_type(TypeToDataType<TKey>());\n    map_type->mutable_value_type()->mutable_tensor_type()->set_elem_type(TypeToDataType<TVal>());\n    map_type->mutable_value_type()->mutable_tensor_type()->mutable_shape()->clear_dim();\n  }\n};\n\ntemplate <typename TKey, typename TVal>\nstruct VectorOfMapType {\n  static const VectorOfMapTypeProto<TKey, TVal> s_vec_map_type_proto;\n};\n\ntemplate <typename TKey, typename TVal>\nconst VectorOfMapTypeProto<TKey, TVal> VectorOfMapType<TKey, TVal>::s_vec_map_type_proto;\n\ntemplate <typename ElemType>\nstruct SequenceTensorTypeProto : ONNX_NAMESPACE::TypeProto {\n  SequenceTensorTypeProto() {\n    MLDataType dt = DataTypeImpl::GetTensorType<ElemType>();\n    const auto* elem_proto = dt->GetTypeProto();\n    mutable_sequence_type()->mutable_elem_type()->CopyFrom(*elem_proto);\n    auto* tensor_type = mutable_sequence_type()->mutable_elem_type()->mutable_tensor_type();\n    tensor_type->set_elem_type(TypeToDataType<ElemType>());\n  }\n};\n\ntemplate <typename ElemType>\nstruct SequenceTensorType {\n  static const SequenceTensorTypeProto<ElemType> s_sequence_tensor_type_proto;\n};\n\ntemplate <typename ElemType>\nconst SequenceTensorTypeProto<ElemType> SequenceTensorType<ElemType>::s_sequence_tensor_type_proto;\n\n// To use OpTester:\n//  1. Create one with the op name\n//  2. Call AddAttribute with any attributes\n//  3. Call AddInput for all the inputs\n//  4. Call AddOutput with all expected outputs\n//  5. Call Run\n// Not all tensor types and output types are added, if a new input type is used, add it to the TypeToDataType list\n// above for new output types, add a new specialization for Check<> See current usage for an example, should be self\n// explanatory\nclass OpTester {\n public:\n  // Default to the first opset that ORT was available (7).\n  // When operators are updated they need to explicitly add tests for the new opset version.\n  // This is due to the kernel matching logic. See KernelRegistry::VerifyKernelDef.\n  // Additionally, -1 is supported and defaults to the latest known opset.\n  //\n  // Defaulting to the latest opset version would result in existing operator implementations for non-CPU EPs to\n  // lose their test coverage until an implementation for the new version is added.\n  //   e.g. there are CPU and GPU implementations for version 1 of an op. both are tested by a single OpTester test.\n  //        opset changes from 1 to 2 and CPU implementation gets added. If 'opset_version' is 2 the kernel matching\n  //        will find and run the CPU v2 implementation, but will not match the GPU v1 implementation.\n  //        OpTester will say it was successful as at least one EP ran, and the GPU implementation of v1 no longer has\n  //        test coverage.\n  explicit OpTester(const char* op, int opset_version = 7, const char* domain = onnxruntime::kOnnxDomain)\n      : op_(op), domain_(domain), opset_version_(opset_version) {\n    if (opset_version_ < 0) {\n      static int latest_onnx_version =\n          ONNX_NAMESPACE::OpSchemaRegistry::DomainToVersionRange().Map().at(ONNX_NAMESPACE::ONNX_DOMAIN).second;\n      opset_version_ = latest_onnx_version;\n    }\n  }\n\n  ~OpTester();\n\n  // Set whether the NodeArg created by AddInput/AddOutput should include shape information\n  // for Tensor types. If not added, shape inferencing should resolve. If added, shape inferencing\n  // should validate. Default is to not add.\n  // Additionally a symbolic dimension will be added if symbolic_dim matches a dimension in the input.\n  OpTester& AddShapeToTensorData(bool add_shape = true, int symbolic_dim = -1) {\n    add_shape_to_tensor_data_ = add_shape;\n    add_symbolic_dim_to_tensor_data_ = symbolic_dim;\n    return *this;\n  }\n\n  // We have an initializer_list and vector version of the Add functions because std::vector is specialized for\n  // bool and we can't get the raw data out. So those cases must use an initializer_list\n  template <typename T>\n  void AddInput(const char* name, const std::vector<int64_t>& dims, const std::initializer_list<T>& values,\n                bool is_initializer = false) {\n    AddData(input_data_, name, dims, values.begin(), values.size(), is_initializer);\n  }\n\n  template <typename T>\n  void AddInput(const char* name, const std::vector<int64_t>& dims, const std::vector<T>& values,\n                bool is_initializer = false) {\n    AddData(input_data_, name, dims, values.data(), values.size(), is_initializer);\n  }\n\n  // Add other registered types, possibly experimental\n  template <typename T>\n  void AddInput(const char* name, const T& val) {\n    auto mltype = DataTypeImpl::GetType<T>();\n    ORT_ENFORCE(mltype != nullptr, \"T must be a registered cpp type\");\n    auto ptr = onnxruntime::make_unique<T>(val);\n    OrtValue value;\n    value.Init(ptr.get(), mltype, mltype->GetDeleteFunc());\n    ptr.release();\n    input_data_.push_back(Data(NodeArg(name, mltype->GetTypeProto()), std::move(value), optional<float>(),\n                               optional<float>()));\n  }\n\n  template <typename T>\n  void AddInput(const char* name, T&& val) {\n    auto mltype = DataTypeImpl::GetType<T>();\n    ORT_ENFORCE(mltype != nullptr, \"T must be a registered cpp type\");\n    auto ptr = onnxruntime::make_unique<T>(std::move(val));\n    OrtValue value;\n    value.Init(ptr.get(), mltype, mltype->GetDeleteFunc());\n    ptr.release();\n    input_data_.push_back(Data(NodeArg(name, mltype->GetTypeProto()), std::move(value), optional<float>(),\n                               optional<float>()));\n  }\n\n  template <typename T>\n  void AddSeqInput(const char* name, const SeqTensors<T>& seq_tensors) {\n    AddSeqData<T>(input_data_, name, seq_tensors);\n  }\n\n  template <typename T>\n  void AddSeqOutput(const char* name, const SeqTensors<T>& seq_tensors) {\n    AddSeqData<T>(output_data_, name, seq_tensors);\n  }\n\n  template <typename TKey, typename TVal>\n  void AddInput(const char* name, const std::map<TKey, TVal>& val) {\n    std::unique_ptr<std::map<TKey, TVal>> ptr = onnxruntime::make_unique<std::map<TKey, TVal>>(val);\n    OrtValue value;\n    value.Init(ptr.release(), DataTypeImpl::GetType<std::map<TKey, TVal>>(),\n               DataTypeImpl::GetType<std::map<TKey, TVal>>()->GetDeleteFunc());\n    input_data_.push_back(Data(NodeArg(name, &MMapType<TKey, TVal>::s_map_type_proto), std::move(value),\n                               optional<float>(), optional<float>()));\n  }\n\n  template <typename T>\n  void AddMissingOptionalInput() {\n    std::string name;  // empty == input doesn't exist\n    input_data_.push_back(Data(NodeArg(name, &TTensorType<T>::s_type_proto), OrtValue(), optional<float>(),\n                               optional<float>()));\n  }\n\n  template <typename T>\n  void AddOutput(const char* name, const std::vector<int64_t>& dims, const std::initializer_list<T>& expected_values,\n                 bool sort_output = false) {\n    AddData(output_data_, name, dims, expected_values.begin(), expected_values.size(), false, sort_output);\n  }\n\n  template <typename T>\n  void AddOutput(const char* name, const std::vector<int64_t>& dims, const std::vector<T>& expected_values,\n                 bool sort_output = false) {\n    AddData(output_data_, name, dims, expected_values.data(), expected_values.size(), false, sort_output);\n  }\n\n  template <typename T>\n  void AddMissingOptionalOutput() {\n    std::string name;  // empty == input doesn't exist\n    output_data_.push_back(Data(NodeArg(name, &TTensorType<T>::s_type_proto), OrtValue(), optional<float>(),\n                                optional<float>()));\n  }\n\n  // Add other registered types, possibly experimental\n  template <typename T>\n  void AddOutput(const char* name, const T& val) {\n    auto mltype = DataTypeImpl::GetType<T>();\n    ORT_ENFORCE(mltype != nullptr, \"T must be a registered cpp type\");\n    auto ptr = onnxruntime::make_unique<T>(val);\n    OrtValue value;\n    value.Init(ptr.get(), mltype, mltype->GetDeleteFunc());\n    ptr.release();\n    output_data_.push_back(Data(NodeArg(name, mltype->GetTypeProto()), std::move(value), optional<float>(),\n                                optional<float>()));\n  }\n\n  template <typename T>\n  void AddOutput(const char* name, T&& val) {\n    auto mltype = DataTypeImpl::GetType<T>();\n    ORT_ENFORCE(mltype != nullptr, \"T must be a registered cpp type\");\n    auto ptr = onnxruntime::make_unique<T>(std::move(val));\n    OrtValue value;\n    value.Init(ptr.get(), mltype, mltype->GetDeleteFunc());\n    ptr.release();\n    output_data_.push_back(Data(NodeArg(name, mltype->GetTypeProto()), std::move(value), optional<float>(),\n                                optional<float>()));\n  }\n\n  // Add non tensor output\n  template <typename TKey, typename TVal>\n  void AddOutput(const char* name, const std::vector<std::map<TKey, TVal>>& val) {\n    auto ptr = onnxruntime::make_unique<std::vector<std::map<TKey, TVal>>>(val);\n    OrtValue ml_value;\n    ml_value.Init(ptr.release(), DataTypeImpl::GetType<std::vector<std::map<TKey, TVal>>>(),\n                  DataTypeImpl::GetType<std::vector<std::map<TKey, TVal>>>()->GetDeleteFunc());\n    output_data_.push_back(Data(NodeArg(name, &VectorOfMapType<TKey, TVal>::s_vec_map_type_proto), std::move(ml_value),\n                                optional<float>(), optional<float>()));\n  }\n\n  void AddCustomOpRegistry(std::shared_ptr<CustomRegistry> registry) {\n    custom_schema_registries_.push_back(registry->GetOpschemaRegistry());\n    custom_session_registries_.push_back(registry);\n  }\n\n  void SetOutputAbsErr(const char* name, float v);\n  void SetOutputRelErr(const char* name, float v);\n\n  // Number of times to call InferenceSession::Run. The same feeds are used each time.\n  // e.g. used to verify the generator ops behave as expected\n  void SetNumRunCalls(int n) {\n    ORT_ENFORCE(n > 0);\n    num_run_calls_ = n;\n  }\n\n  template <typename T>\n  void AddAttribute(std::string name, T value) {\n    // Generate a the proper AddAttribute call for later\n    add_attribute_funcs_.emplace_back([name = std::move(name), value = std::move(value)](onnxruntime::Node& node) {\n      node.AddAttribute(name, value);\n    });\n  }\n\n  enum class ExpectResult { kExpectSuccess,\n                            kExpectFailure };\n\n  void Run(ExpectResult expect_result = ExpectResult::kExpectSuccess, const std::string& expected_failure_string = \"\",\n           const std::unordered_set<std::string>& excluded_provider_types = {},\n           const RunOptions* run_options = nullptr,\n           std::vector<std::unique_ptr<IExecutionProvider>>* execution_providers = nullptr,\n           ExecutionMode execution_mode = ExecutionMode::ORT_SEQUENTIAL);\n\n  void Run(SessionOptions session_options,\n           ExpectResult expect_result = ExpectResult::kExpectSuccess,\n           const std::string& expected_failure_string = \"\",\n           const std::unordered_set<std::string>& excluded_provider_types = {},\n           const RunOptions* run_options = nullptr,\n           std::vector<std::unique_ptr<IExecutionProvider>>* execution_providers = nullptr);\n\n  struct Data {\n    onnxruntime::NodeArg def_;\n    OrtValue data_;\n    optional<float> relative_error_;\n    optional<float> absolute_error_;\n    bool sort_output_;\n    Data(onnxruntime::NodeArg&& def, OrtValue&& data, optional<float>&& rel, optional<float>&& abs,\n         bool sort_output = false)\n        : def_(std::move(def)),\n          data_(std::move(data)),\n          relative_error_(std::move(rel)),\n          absolute_error_(abs),\n          sort_output_(sort_output) {}\n    Data(Data&&) = default;\n    Data& operator=(Data&&) = default;\n  };\n\n protected:\n  virtual void AddNodes(onnxruntime::Graph& graph, std::vector<onnxruntime::NodeArg*>& graph_input_defs,\n                        std::vector<onnxruntime::NodeArg*>& graph_output_defs,\n                        std::vector<std::function<void(onnxruntime::Node& node)>>& add_attribute_funcs);\n\n  void AddInitializers(onnxruntime::Graph& graph);\n\n  void FillFeedsAndOutputNames(std::unordered_map<std::string, OrtValue>& feeds,\n                               std::vector<std::string>& output_names);\n\n  std::unique_ptr<onnxruntime::Model> BuildGraph();\n\n  const char* op_;\n\n#ifndef NDEBUG\n  bool run_called_{};\n#endif\n\n private:\n  template <typename T>\n  void AddData(std::vector<Data>& data, const char* name, const std::vector<int64_t>& dims, const T* values,\n               int64_t values_count, bool is_initializer = false, bool sort_output = false) {\n    try {\n      TensorShape shape{dims};\n      ORT_ENFORCE(shape.Size() == values_count, values_count, \" input values doesn't match tensor size of \",\n                  shape.Size());\n\n      auto allocator = test::AllocatorManager::Instance().GetAllocator(CPU);\n      auto p_tensor = onnxruntime::make_unique<Tensor>(DataTypeImpl::GetType<T>(), shape, allocator);\n\n      auto* data_ptr = p_tensor->template MutableData<T>();\n      for (int64_t i = 0; i < values_count; i++) {\n        data_ptr[i] = values[i];\n      }\n\n      std::vector<int64_t> dims_for_proto{dims};\n      if (add_symbolic_dim_to_tensor_data_ >= 0 &&\n          dims.size() > static_cast<size_t>(add_symbolic_dim_to_tensor_data_)) {\n        dims_for_proto[add_symbolic_dim_to_tensor_data_] = -1;\n      }\n\n      TTypeProto<T> type_proto(add_shape_to_tensor_data_ ? &dims_for_proto : nullptr);\n      OrtValue value;\n      value.Init(p_tensor.release(), DataTypeImpl::GetType<Tensor>(),\n                 DataTypeImpl::GetType<Tensor>()->GetDeleteFunc());\n      data.push_back(Data(NodeArg(name, &type_proto), std::move(value), optional<float>(), optional<float>(), sort_output));\n      if (is_initializer) initializer_index_.push_back(data.size() - 1);\n    } catch (const std::exception& ex) {\n      std::cerr << \"AddData for '\" << name << \"' threw: \" << ex.what();\n      throw;\n    }\n  }\n\n  template <typename T>\n  void AddSeqData(std::vector<Data>& data, const char* name, const SeqTensors<T>& seq_tensors) {\n    auto num_tensors = seq_tensors.tensors.size();\n    std::vector<Tensor> tensors;\n    tensors.resize(num_tensors);\n    auto elem_type = DataTypeImpl::GetType<T>();\n    for (size_t i = 0; i < num_tensors; ++i) {\n      TensorShape shape{seq_tensors.tensors[i].shape};\n      auto values_count = static_cast<int64_t>(seq_tensors.tensors[i].data.size());\n      ORT_ENFORCE(shape.Size() == values_count, values_count,\n                  \" input values doesn't match tensor size of \", shape.Size());\n\n      auto allocator = test::AllocatorManager::Instance().GetAllocator(CPU);\n      auto& tensor = tensors[i];\n\n      tensor = Tensor(elem_type,\n                      shape,\n                      allocator);\n\n      auto* data_ptr = tensor.template MutableData<T>();\n      for (int64_t x = 0; x < values_count; ++x) {\n        data_ptr[x] = seq_tensors.tensors[i].data[x];\n      }\n    }\n\n    OrtValue value;\n    auto mltype = DataTypeImpl::GetType<TensorSeq>();\n    auto ptr = onnxruntime::make_unique<TensorSeq>(elem_type);\n    ptr->SetElements(std::move(tensors));\n    value.Init(ptr.get(), mltype, mltype->GetDeleteFunc());\n    ptr.release();\n    data.push_back(Data(NodeArg(name, &SequenceTensorType<T>::s_sequence_tensor_type_proto), std::move(value),\n                        optional<float>(), optional<float>()));\n  }\n\n  void ExecuteModel(Model& model, InferenceSession& session_object, ExpectResult expect_result,\n                    const std::string& expected_failure_string, const RunOptions* run_options,\n                    std::unordered_map<std::string, OrtValue> feeds, std::vector<std::string> output_names,\n                    const std::string& provider_type);\n\n  const char* domain_;\n  int opset_version_;\n  bool add_shape_to_tensor_data_ = true;\n  int add_symbolic_dim_to_tensor_data_ = -1;\n  int num_run_calls_ = 1;\n  std::vector<Data> input_data_;\n  std::vector<Data> output_data_;\n  std::vector<size_t> initializer_index_;\n  std::vector<std::function<void(onnxruntime::Node& node)>> add_attribute_funcs_;\n\n  IOnnxRuntimeOpSchemaRegistryList custom_schema_registries_;\n  std::vector<std::shared_ptr<CustomRegistry>> custom_session_registries_;\n};\n\ntemplate <typename TException>\nvoid ExpectThrow(OpTester& test, const std::string& error_msg) {\n  try {\n    test.Run();\n    // should throw and not reach this\n    EXPECT_TRUE(false) << \"Expected Run() to throw\";\n  } catch (TException ex) {\n    EXPECT_THAT(ex.what(), testing::HasSubstr(error_msg));\n  }\n}\n\nvoid DebugTrap();\n\nvoid Check(const OpTester::Data& expected_data, const Tensor& output_tensor, const std::string& provider_type);\n\n// Only used for CUDA test since no toher kernel has float 16 support\n#ifdef USE_CUDA\ninline void ConvertFloatToMLFloat16(const float* f_datat, MLFloat16* h_data, int input_size) {\n  auto in_vector = ConstEigenVectorMap<float>(f_datat, input_size);\n  auto output_vector = EigenVectorMap<Eigen::half>(static_cast<Eigen::half*>(static_cast<void*>(h_data)), input_size);\n  output_vector = in_vector.template cast<Eigen::half>();\n}\n#endif\n\ninline void ConvertMLFloat16ToFloat(const MLFloat16* h_data, float* f_data, int input_size) {\n  auto in_vector =\n      ConstEigenVectorMap<Eigen::half>(static_cast<const Eigen::half*>(static_cast<const void*>(h_data)), input_size);\n  auto output_vector = EigenVectorMap<float>(f_data, input_size);\n  output_vector = in_vector.template cast<float>();\n}\n\n}  // namespace test\n}  // namespace onnxruntime\n", "meta": {"hexsha": "36b477b5b13f055027c5968252062c4b672960a2", "size": 23385, "ext": "h", "lang": "C", "max_stars_repo_path": "onnxruntime/test/providers/provider_test_utils.h", "max_stars_repo_name": "MaximKalininMS/onnxruntime", "max_stars_repo_head_hexsha": "1d79926d273d01817ce93f001f36f417ab05f8a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T16:47:43.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T16:47:43.000Z", "max_issues_repo_path": "onnxruntime/test/providers/provider_test_utils.h", "max_issues_repo_name": "MaximKalininMS/onnxruntime", "max_issues_repo_head_hexsha": "1d79926d273d01817ce93f001f36f417ab05f8a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "onnxruntime/test/providers/provider_test_utils.h", "max_forks_repo_name": "MaximKalininMS/onnxruntime", "max_forks_repo_head_hexsha": "1d79926d273d01817ce93f001f36f417ab05f8a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-20T13:49:38.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-20T13:49:38.000Z", "avg_line_length": 39.3025210084, "max_line_length": 124, "alphanum_fraction": 0.7015180671, "num_tokens": 5535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22270014914315833, "lm_q2_score": 0.02333076868115131, "lm_q1q2_score": 0.005195765664916924}}
{"text": "#ifndef TEST_ALL\n#define TEST_ALL\n//#include <cblas.h>\n\n#include \"test_matrix_util.h\"\n#include \"test_spn.h\"\n\n\nint test_all(int result);\n\n#endif\n", "meta": {"hexsha": "79d8595c6f9039f25cb9a04ae775d1d6ab7bd944", "size": 144, "ext": "h", "lang": "C", "max_stars_repo_path": "src/cy_fde/test_all.h", "max_stars_repo_name": "ThayaFluss/cnl", "max_stars_repo_head_hexsha": "485345e730a4cbf5cff6dbdeeb5e1fb7c4283733", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cy_fde/test_all.h", "max_issues_repo_name": "ThayaFluss/cnl", "max_issues_repo_head_hexsha": "485345e730a4cbf5cff6dbdeeb5e1fb7c4283733", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cy_fde/test_all.h", "max_forks_repo_name": "ThayaFluss/cnl", "max_forks_repo_head_hexsha": "485345e730a4cbf5cff6dbdeeb5e1fb7c4283733", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 12.0, "max_line_length": 29, "alphanum_fraction": 0.7361111111, "num_tokens": 37, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22270013882530887, "lm_q2_score": 0.023330769614898633, "lm_q1q2_score": 0.0051957656321392235}}
{"text": "/*\n  Copyright [2017-2020] [IBM Corporation]\n  Licensed under the Apache License, Version 2.0 (the \"License\");\n  you may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n  http://www.apache.org/licenses/LICENSE-2.0\n  Unless required by applicable law or agreed to in writing, software\n  distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions and\n  limitations under the License.\n*/\n#ifndef __BUFFER_MGR_H__\n#define __BUFFER_MGR_H__\n\n#ifdef __cplusplus\n\n#include <common/chksum.h>\n#include <common/delete_copy.h>\n#include <common/logging.h>\n#include <common/moveable_ptr.h>\n#include <common/utils.h> /* MiB, UNLIKELY */\n#include <api/components.h>\n#include <api/fabric_itf.h>\n#include <api/kvstore_itf.h>\n#include <api/registrar_memory_direct.h> /* Opaque_memory_region */\n#include <sys/mman.h>\n\n#include \"mcas_config.h\"\n#include \"memory_registered.h\"\n#include <gsl/pointers> /* not_null */\n#include <cassert>\n#include <cstring>      /* memset */\n#include <memory>       /* unique_ptr */\n\nnamespace\n{\n  inline auto alloc_base(std::size_t len) -> gsl::not_null<void *>\n  {\n    auto b = ::aligned_alloc(MiB(2), len);\n    if (b == nullptr) {\n      throw std::bad_alloc();\n    }\n    ::memset(b, 0, len);\n    return gsl::not_null<void *>(b);\n  }\n}\n\nnamespace mcas\n{\ntemplate <class Memory>\nclass Buffer_manager : private common::log_source {\n\n  static constexpr const char *_cname       = \"Buffer_manager\";\n\npublic:\n  static constexpr size_t DEFAULT_BUFFER_COUNT = NUM_SHARD_BUFFERS;\n  static constexpr size_t BUFFER_LEN           = MiB(2); /* corresponds to huge page see below */\n  using memory_registered_t                    = memory_registered<Memory>;\n\n  using memory_region_t = typename Memory::memory_region_t;\n\n  struct iov_mem_lock\n  {\n  private:\n    common::moveable_ptr<::iovec> _iov;\n  public:\n    iov_mem_lock(::iovec *iov_)\n      : _iov(iov_)\n    {\n      ::madvise(_iov->iov_base, _iov->iov_len, MADV_HUGEPAGE);\n      ::mlock(_iov->iov_base, _iov->iov_len);\n    }\n    iov_mem_lock(iov_mem_lock &&) noexcept = default;\n    ~iov_mem_lock()\n    {\n      if ( _iov )\n      {\n        ::munlock(_iov->iov_base, _iov->iov_len);\n      }\n    }\n  };\n\n  /* Although client tried to hide it with a reinterpret_cast, buffer_base is\n   used as a component::memory_region_t */\n\n  struct buffer_base : public component::Registrar_memory_direct::Opaque_memory_region, private common::log_source\n  {\n  private:\n    static constexpr const char *_cname = \"buffer_base\";\n    void *_base;\n    std::size_t _original_length;\n    memory_registered_t _region;\n    const unsigned magic;\n\n  public:\n    buffer_base(unsigned    debug_level_,\n             Memory * transport_,\n             void *      base_,\n             size_t      length_\n    )\n      : common::log_source(debug_level_)\n      , _base(base_)\n      , _original_length(length_)\n      , _region(memory_registered_t(debug_level_, transport_, base_, length_, 0, 0))\n      , magic(0xC0FFEE)\n    {\n      if ( length_ <= 1 )\n      {\n        throw std::domain_error(\"buffer length too small\");\n      }\n      CPLOG(3, \"%s::%s %p transport %p region %p\", _cname, __func__, common::p_fmt(this),\n            common::p_fmt(transport()), common::p_fmt(region()));\n    }\n\n    void *get_desc() const { return _region.desc(); }\n\n    DELETE_COPY(buffer_base);\n\n  protected:\n    ~buffer_base()\n    {\n      CPLOG(3, \"%s::%s %p transport %p region %p\", _cname, __func__, common::p_fmt(this),\n            common::p_fmt(transport()), common::p_fmt(region()));\n    }\n\n  public:\n    size_t original_length() const { return _original_length; }\n    inline gsl::not_null<void *> base() const { return _base; }\n    auto region() const { return _region.mr(); }\n    Memory * transport() const { return _region.transport(); }\n\n#if 0\n    /* unused */\n    inline bool check_magic() const { return magic == 0xC0FFEE; }\n    unsigned int crc32() const { return common::chksum32(_base, _length); }\n#endif\n  };\n\n  struct free_deleter\n  {\n    void operator()(void *v_) { ::free(v_); }\n  };\n\n  struct buffer_internal\n    : private std::unique_ptr<void, free_deleter>\n    , public buffer_base\n  {\n    ::iovec iov[2];\n    void *desc[2];\n    iov_mem_lock _ml;\n    using completion_t = void (*)(void *, buffer_internal *);\n    completion_t   completion_cb;\n    void *         value_adjunct;\n    inline void set_completion(completion_t completion_) { completion_cb = completion_; }\n    void set_completion(completion_t completion_, void *value_adjunct_)\n    {\n      completion_cb = completion_;\n      value_adjunct = value_adjunct_;\n    }\n    buffer_internal(unsigned debug_level_,\n             Memory *         transport_,\n             size_t              length_\n    )\n      : std::unique_ptr<void, free_deleter>(alloc_base(length_))\n      , buffer_base(debug_level_, transport_, std::unique_ptr<void, free_deleter>::get(), length_)\n      , iov{{this->base(), this->original_length()}, {nullptr, 0}}\n      , desc{this->get_desc(), nullptr}\n      , _ml(&this->iov[0])\n      , completion_cb(nullptr)\n      , value_adjunct(nullptr)\n    {\n    }\n\n    DELETE_COPY(buffer_internal);\n\n    void set_length(size_t s) { iov->iov_len = s; }\n\n    inline void reset_length()\n    {\n      assert(this->original_length() > 1);\n      this->iov[0].iov_len  = this->original_length();\n      value_adjunct = nullptr;\n      completion_cb = nullptr;\n    }\n\n    size_t length() const { return iov[0].iov_len; }\n\n    unsigned int crc32() const { return common::chksum32(iov->iov_base, iov->iov_len); }\n  };\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Weffc++\"  // missing initializers\n  Buffer_manager(unsigned debug_level_,\n                 Memory *transport,\n                 size_t buffer_count = DEFAULT_BUFFER_COUNT)\n    : common::log_source(debug_level_),\n      _buffer_count(buffer_count),\n      _transport(transport)\n  {\n    for (unsigned i = 0; i < _buffer_count; i++) {\n      const auto len  = BUFFER_LEN;\n      _buffers.emplace_back(std::make_unique<buffer_internal>(debug_level_, _transport, len));\n      _free.push_back(_buffers.back().get());\n    }\n    PLOG(\"%s %p allocated %lu buffers\", __func__, common::p_fmt(this), buffer_count);\n  }\n#pragma GCC diagnostic pop\n\n  Buffer_manager(Buffer_manager &&) noexcept = default;\n\n  ~Buffer_manager()\n  {\n  }\n\n  using completion_t = void (*)(void *, buffer_internal *);\n\n  gsl::not_null<buffer_internal *> allocate(completion_t completion_)\n  {\n    if (UNLIKELY(_free.empty())) throw Program_exception(\"Buffer_manager: no shard buffers remaining\");\n    gsl::not_null<buffer_internal *> iob = _free.back();\n    _free.pop_back();\n    CPLOG(3, \"%s::%s %p (%lu free)\", _cname, __func__, common::p_fmt(iob), _free.size());\n    iob->reset_length();\n    iob->set_completion(completion_);\n    return iob;\n  }\n\n  void free(gsl::not_null<buffer_internal *> iob)\n  {\n    CPLOG(3, \"%s::%s %p (%lu free)\", _cname, __func__, common::p_fmt(iob), _free.size());\n    iob->reset_length();\n    iob->set_completion(nullptr);\n    _free.push_back(iob);\n  }\n\nprivate:\n  // static constexpr size_t buffer_len() { return BUFFER_LEN; }\n\n  using pool_t = component::IKVStore::pool_t;\n  using key_t  = std::uint64_t;\n\n  const size_t                           _buffer_count;\n  gsl::not_null<Memory *>             _transport;\n  std::vector<std::unique_ptr<buffer_internal>> _buffers;\n  std::vector<buffer_internal *>        _free;\n};\n}  // namespace mcas\n\n#endif\n#endif\n", "meta": {"hexsha": "cf94880931fc77d04a460d834a36c9f10b2c1e48", "size": 7593, "ext": "h", "lang": "C", "max_stars_repo_path": "src/server/mcas/src/buffer_manager.h", "max_stars_repo_name": "fQuinzan/mcas", "max_stars_repo_head_hexsha": "efaf438eb20cffa18b13f176c74a2b3153f89c07", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 60.0, "max_stars_repo_stars_event_min_datetime": "2020-04-28T08:15:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T10:35:15.000Z", "max_issues_repo_path": "src/server/mcas/src/buffer_manager.h", "max_issues_repo_name": "fQuinzan/mcas", "max_issues_repo_head_hexsha": "efaf438eb20cffa18b13f176c74a2b3153f89c07", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 66.0, "max_issues_repo_issues_event_min_datetime": "2020-09-03T23:40:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T20:34:52.000Z", "max_forks_repo_path": "src/server/mcas/src/buffer_manager.h", "max_forks_repo_name": "fQuinzan/mcas", "max_forks_repo_head_hexsha": "efaf438eb20cffa18b13f176c74a2b3153f89c07", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2019-11-02T06:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T01:56:42.000Z", "avg_line_length": 30.130952381, "max_line_length": 114, "alphanum_fraction": 0.6546819439, "num_tokens": 1916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.13296424019782926, "lm_q2_score": 0.039048294962802745, "lm_q1q2_score": 0.005192026870749791}}
{"text": "#pragma once\n\n#include <gsl.h>\n#include <string>\n#include <cstdarg>\n#include <typeinfo>\n#include <exception>\n\n#include \"HE_Assert.h\"\n#include \"TMP_Helper.h\"\n\n// Utility function that calls the right variadic formatting functions and returns an RAII string\nstd::string CStringFormat(const char* sFormat, va_list args);\nstd::string CStringFormat(const char* sFormat, ...);\n\n// Default to_string functions\nusing std::to_string;\nusing gsl::to_string;\nstd::string to_string(const std::exception& e);\nstd::string to_string(void* p);\n\ninline std::string& to_string(std::string& s) { return s; }\ninline std::string to_string(std::string&& s) { return s; }\ninline const std::string& to_string(const std::string& s) { return s; }\ninline std::string to_string(const char* s) { return{ s }; }\n\n// Built-in type formats specifiers\n// Can be used to format a built-in type to a string with a special format.\n// Use HasFormatSpecifier<T> to test statically (ex: static_assert(...)) if a type supports\n// a format specifier\n// The format specifier is in the same format as printf (http://en.cppreference.com/w/cpp/io/c/fprintf), \n// except that the conversion format specifier (aka the last letter[s]) can be ignored, in which case the\n// default specifier for the type will be used (ex: d for int, u for unsigned, f for float, etc...)\n// On top of that, for long sized types, only the conversion specifier without the argument type can be\n// supplied. For example, for unsigned long, the format could be \" .4o\", which will be converted to\n// \" .4ol\". Supplying \" .4ol\" itself would also work\nstd::string to_string(int val, const std::string& sFormat); // Defaults to %[sFormat]d\nstd::string to_string(unsigned int val, const std::string& sFormat); // Defaults to %[sFormat]u\nstd::string to_string(long val, const std::string& sFormat); // Defaults to %[sFormat]dl\nstd::string to_string(unsigned long val, const std::string& sFormat); // Defaults to %[sFormat]ul\nstd::string to_string(long long val, const std::string& sFormat); // Defaults to %[sFormat]dll\nstd::string to_string(unsigned long long val, const std::string& sFormat); // Defaults to %[sFormat]ull\nstd::string to_string(float val, const std::string& sFormat); // Defaults to %[sFormat]f\nstd::string to_string(double val, const std::string& sFormat); // Defaults to %[sFormat]f\nstd::string to_string(long double val, const std::string& sFormat); // Defaults to %[sFormat]fL\nstd::string to_string(void* val, const std::string& sFormat); // Defaults to %[sFormat]p\n\n\nnamespace HE\n{\n\tnamespace Private\n\t{\n\t\ttemplate<class T>\n\t\tusing try_format = decltype(to_string(std::declval<T>()));\n\n\t\ttemplate<class T>\n\t\tusing has_format = has_op < T, try_format >;\n\t\t\n\t\ttemplate<class T>\n\t\tusing try_format_specifier = decltype(to_string(std::declval<T>(), std::declval<std::string>()));\n\n\t\ttemplate<class T>\n\t\tusing has_format_specifier = has_op<T, try_format_specifier >;\n\n\t\ttemplate< typename Arg >\n\t\tstd::string FormatIthArgN(size_t i, size_t n, Arg&& arg)\n\t\t{\n\t\t\tASSERT_MSG(i == n, \"String format token number was higher than the number of arguments\");\n\t\t\treturn to_string(std::forward<Arg>(arg));\n\t\t}\n\n\t\ttemplate< typename Arg1, typename... Args >\n\t\tstd::string FormatIthArgN(size_t i, size_t n, Arg1&& arg, Args&&... args)\n\t\t{\n\t\t\tif (i == n)\n\t\t\t{\n\t\t\t\treturn to_string(std::forward<Arg1>(arg));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn FormatIthArgN(i, n + 1, std::forward<Args>(args)...);\n\t\t\t}\n\t\t}\n\n\t\ttemplate< typename Arg>\n\t\tauto FormatIthArgFN(size_t i, size_t n, const std::string& format, Arg&& arg)\n\t\t\t-> std::enable_if_t<has_format_specifier<Arg>::value, std::string>\n\t\t{\n\t\t\tASSERT_MSG(i == n, \"String format token number was higher than the number of arguments\");\n\t\t\treturn to_string(std::forward<Arg>(arg), format);\n\t\t}\n\n\t\ttemplate< typename Arg >\n\t\tauto FormatIthArgFN(size_t i, size_t n, const std::string& format, Arg&& arg)\n\t\t\t-> std::enable_if_t<!has_format_specifier<Arg>::value, std::string>\n\t\t{\n\t\t\tASSERT_MSG(false , \"A format specifier was supplied with type \"s + typeid(Arg).name() + \" which that does not support it\");\n\t\t\treturn \"\";\n\t\t}\n\n\t\ttemplate< typename Arg1, typename... Args >\n\t\tstd::string FormatIthArgFN(size_t i, size_t n, const std::string& format, Arg1&& arg, Args&&... args)\n\t\t{\n\t\t\tif (i == n)\n\t\t\t{\n\t\t\t\treturn FormatIthArgFN(i, n, format, std::forward<Arg1>(arg));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn FormatIthArgFN(i, n + 1, format, std::forward<Args>(args)...);\n\t\t\t}\n\t\t}\n\n\t\ttemplate< typename... Args >\n\t\tstd::string FormatIthArg(size_t i, Args&&... args)\n\t\t{\n\t\t\treturn FormatIthArgN(i, 0, std::forward<Args>(args)...);\n\t\t}\n\n\t\ttemplate< typename... Args >\n\t\tstd::string FormatIthArgF(size_t i, const std::string& format, Args&&... args)\n\t\t{\n\t\t\treturn FormatIthArgFN(i, 0, format, std::forward<Args>(args)...);\n\t\t}\n\t}\n\n\t// Can be used in statically evaluated context to test if the type can be formatted\n\t// to a string and formatted with a format specifier\n\ttemplate< class... T >\n\tconstexpr bool HasFormat()\n\t{\n\t\treturn and_<Private::has_format<T>...>::value;\n\t}\n\n\ttemplate< class... T >\n\tconstexpr bool HasFormatSpecifier()\n\t{\n\t\treturn and_<Private::has_format_specifier<T>...>::value;\n\t}\n\n\t// Form: Format(sFormat, args...) -> sFormatted\n\t// Formats the string according to format tokens and arguments\n\t// Format token have the format \"{i}\" or \"{i:xxxx}\", where i is a 0-based argument index to be\n\t// converted to string or the character '_', which means next argument (starting at 0)\n\t// \"xxxx\" is a format string to be passed to the argument \n\t// \n\t// In order to be featured in a format token, an argument must have a \"to_string\" function available\n\t// either in the global namespace or in the same scope as the type of the argument, which\n\t// will be found through ADL\n\t// To have a format specifier, the argument must have a \"to_string\" which takes a string as\n\t// second argument\n\t// You can test for both of these conditions statically with HasFormat<T>() and HasFormatSpecifier<T>()\n\n    // Example: Format(\"{0:dd-mm-yyyy}\", date) -> to_string(date, \"dd-mm-yyyy\")\n\n\t// Pre-condition: The biggest index in the format string must be smaller than\n\t// the number of arguments, and indices can't be negative\n\tinline std::string Format(const std::string& sFormat)\n\t{\n\t\treturn sFormat;\n\t}\n\n\ttemplate< typename... Args>\n\tstd::string Format(const std::string& sFormat, Args&&... args)\n\t{\n\t\tstatic_assert(HasFormat<Args...>(), \"An argument cannot be formatted (HasFormat returns false)\");\n\n\t\tusing namespace HE::Private;\n\n\t\tstd::string sOutput;\n\t\tsize_t nNextArg = 0;\n\t\tfor (size_t i = 0; i < sFormat.size(); ++i)\n\t\t{\n\t\t\t// Find the next format token\n\t\t\tauto const posToken = sFormat.find_first_of('{', i);\n\n\t\t\t// Add to the output all the characters up until the next format token (or the end)\n\t\t\t// and process the format token if necessary\n\t\t\tif (posToken == std::string::npos)\n\t\t\t{\n\t\t\t\tsOutput += sFormat.substr(i);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// The sequence \"\\{\" is not a token start, so we continue as if it was a normal character\n\t\t\telse if (posToken != 0 && sFormat[posToken - 1] == '\\\\')\n\t\t\t{\n\t\t\t\tsOutput += sFormat.substr(i, posToken - i);\n\t\t\t\ti = posToken;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// Otherwise, we have a format token\n\t\t\telse\n\t\t\t{\n\t\t\t\tsOutput += sFormat.substr(i, posToken - i); // Add everything before the token\n\n\t\t\t\tauto const endToken = sFormat.find_first_of('}', posToken);\n\t\t\t\ti = endToken;\n\t\t\t\tASSERT_MSG(endToken != std::string::npos, \"Token error in string format \\\"\" + sFormat + \"\\\"\");\n\n\t\t\t\t// Find the index token inside the whole token\n\t\t\t\tauto const sFormatToken = sFormat.substr(posToken + 1, (endToken - 1) - posToken);\n\t\t\t\tauto const nSpecifierSentinel = sFormatToken.find_first_of(':');\n\t\t\t\tauto const sIndexToken = [sFormatToken, nSpecifierSentinel]() {\n\t\t\t\t\tif (nSpecifierSentinel == std::string::npos)\n\t\t\t\t\t{\n\t\t\t\t\t\treturn sFormatToken;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\treturn sFormatToken.substr(0, nSpecifierSentinel);\n\t\t\t\t\t}\n\t\t\t\t}();\n\t\t\t\t\n\t\t\t\t// Find the index of the current arg for this token\n\t\t\t\tauto const argPos = [sIndexToken, nNextArg]() -> size_t {\n\t\t\t\t\tif (sIndexToken == \"_\")\n\t\t\t\t\t{\n\t\t\t\t\t\treturn nNextArg;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\treturn std::stoi(sIndexToken);\n\t\t\t\t\t}\n\t\t\t\t}();\n\t\t\t\tnNextArg = argPos + 1;\n\t\t\t\t\n\t\t\t\t// Add the formatted argument to the output\n\t\t\t\tif (nSpecifierSentinel == std::string::npos)\n\t\t\t\t{\t\n\t\t\t\t\tsOutput += FormatIthArg(argPos, std::forward<Args>(args)...);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tauto const sSpecifierToken = sFormatToken.substr(nSpecifierSentinel + 1);\n\t\t\t\t\tsOutput += FormatIthArgF(argPos, sSpecifierToken, std::forward<Args>(args)...);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn sOutput;\n\t}\n\t\n\t// Thread-safe logging\n\tvoid Log(const char* psMsg) noexcept;\n\tinline void Log(const std::string& sMsg) noexcept { Log(sMsg.c_str()); }\n\tvoid LogError(const char* psMsg) noexcept;\n\tinline void LogError(const std::string& sMsg) noexcept { LogError(sMsg.c_str()); }\n\t\n\n\ttemplate< typename... Args>\n\tvoid Log(const std::string& sFormat, Args&&... args)\n\t{\n\t\tLog(Format(sFormat, std::forward<Args>(args)...));\n\t}\n\n\ttemplate< typename... Args>\n\tvoid LogError(const std::string& sFormat, Args&&... args)\n\t{\n\t\tLogError(Format(sFormat, std::forward<Args>(args)...));\n\t}\n\n\t// Constexpr-friendly string\n\ttemplate<class Char = char>\n\tclass basic_constexpr_string\n\t{\n\tpublic:\n\t\ttemplate<size_t N>\n\t\tconstexpr basic_constexpr_string(const char(&a)[N]) noexcept :\n\t\t\tm_pStr{ a }, m_nSize{ N - 1 } {}\n\n\t\tconstexpr Char operator[](size_t n) const\n\t\t{\n\t\t\treturn n < m_nSize ? m_pStr[n] : throw std::out_of_range(\"\");\n\t\t}\n\n\t\tconstexpr size_t size() const noexcept { return m_nSize; }\n\n\tprivate:\n\t\tconst Char* const m_pStr;\n\t\tconst size_t m_nSize;\n\t};\n\n\tusing constexpr_string = basic_constexpr_string<char>;\n\tusing constexpr_wstring = basic_constexpr_string<wchar_t>;\n\tusing constexpr_u16string = basic_constexpr_string<char16_t>;\n\tusing constexpr_u32string = basic_constexpr_string<char32_t>;\n}", "meta": {"hexsha": "1c5906bbac21fe14b073e7b9d15ff9d97fd7906f", "size": 9876, "ext": "h", "lang": "C", "max_stars_repo_path": "src/Source/SDK/HE_String.h", "max_stars_repo_name": "KABoissonneault/Hazel_Engine", "max_stars_repo_head_hexsha": "e5ab97f6ccbc2c77bd92dd9dc84f2f64670e586d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Source/SDK/HE_String.h", "max_issues_repo_name": "KABoissonneault/Hazel_Engine", "max_issues_repo_head_hexsha": "e5ab97f6ccbc2c77bd92dd9dc84f2f64670e586d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Source/SDK/HE_String.h", "max_forks_repo_name": "KABoissonneault/Hazel_Engine", "max_forks_repo_head_hexsha": "e5ab97f6ccbc2c77bd92dd9dc84f2f64670e586d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4111498258, "max_line_length": 126, "alphanum_fraction": 0.683981369, "num_tokens": 2714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.17106120013047912, "lm_q2_score": 0.030214584338463815, "lm_q1q2_score": 0.005168543058381199}}
{"text": "#ifndef MKL_TEMPLATE\n#define MKL_TEMPLATE\n\n//#include <cblas.h>\n#include <stddef.h>\n//#include <blas.h>\n#ifdef small\n#undef small\n#endif\n//#include <lapack.h>\n#include <cblas_defvar.h>\n\n#ifdef NEW_MATLAB\n   typedef ptrdiff_t INTT;\n#else\n   typedef int INTT;\n#endif\n\n/// a few static variables for lapack\nstatic char low='l';\nstatic char lower='L';\nstatic char nonUnit='n';\nstatic char upper='u';\nstatic INTT info=0;\nstatic char incr='I';\nstatic char decr='D';\nstatic char all='A';\nstatic char no='N';\nstatic char reduced='S';\nstatic char allV='V';\n\n#ifdef REMOVE_\n#define dnrm2_ dnrm2\n#define snrm2_ snrm2\n#define dcopy_ dcopy\n#define scopy_ scopy\n#define daxpy_ daxpy\n#define saxpy_ saxpy\n#define dscal_ dscal\n#define sscal_ sscal\n#define dasum_ dasum\n#define sasum_ sasum\n#define ddot_ ddot\n#define sdot_ sdot\n#define dgemv_ dgemv\n#define sgemv_ sgemv\n#define dger_ dger\n#define sger_ sger\n#define dtrmv_ dtrmv\n#define strmv_ strmv\n#define dsyr_ dsyr\n#define ssyr_ ssyr\n#define dsymv_ dsymv\n#define ssymv_ ssymv\n#define dgemm_ dgemm\n#define sgemm_ sgemm\n#define dsyrk_ dsyrk\n#define ssyrk_ ssyrk\n#define dtrmm_ dtrmm\n#define strmm_ strmm\n#define dtrtri_ dtrtri\n#define strtri_ strtri\n#define idamax_ idamax\n#define isamax_ isamax\n#define dsytrf_ dsytrf\n#define ssytrf_ ssytrf\n#define dsytri_ dsytri\n#define ssytri_ ssytri\n#define dlasrt_ dlasrt\n#define slasrt_ slasrt\n#define dgesvd_ dgesvd\n#define sgesvd_ sgesvd\n#define dsyev_ dsyev\n#define ssyev_ ssyev\n#endif\n\n/// external functions\n#ifdef HAVE_MKL   // obsolete\nextern \"C\" {\n#endif\n   size_t cblas_idamin( int n,  double* X,  int incX);\n   size_t cblas_isamin( int n,  float* X,  int incX);\n#ifdef HAVE_MKL\n};\n#endif\n\n#ifdef HAVE_MKL\nextern \"C\" {\n   void vdSqr( int n,  double* vecIn, double* vecOut);\n   void vsSqr( int n,  float* vecIn, float* vecOut);\n   void vdSqrt( int n,  double* vecIn, double* vecOut);\n   void vsSqrt( int n,  float* vecIn, float* vecOut);\n   void vdInvSqrt( int n,  double* vecIn, double* vecOut);\n   void vsInvSqrt( int n,  float* vecIn, float* vecOut);\n   void vdSub( int n,  double* vecIn,  double* vecIn2, double* vecOut);\n   void vsSub( int n,  float* vecIn,  float* vecIn2, float* vecOut);\n   void vdDiv( int n,  double* vecIn,  double* vecIn2, double* vecOut);\n   void vsDiv( int n,  float* vecIn,  float* vecIn2, float* vecOut);\n   void vdExp( int n,  double* vecIn, double* vecOut);\n   void vsExp( int n,  float* vecIn, float* vecOut);\n   void vdInv( int n,  double* vecIn, double* vecOut);\n   void vsInv( int n,  float* vecIn, float* vecOut);\n   void vdAdd( int n,  double* vecIn,  double* vecIn2, double* vecOut);\n   void vsAdd( int n,  float* vecIn,  float* vecIn2, float* vecOut);\n   void vdMul( int n,  double* vecIn,  double* vecIn2, double* vecOut);\n   void vsMul( int n,  float* vecIn,  float* vecIn2, float* vecOut);\n   void vdAbs( int n,  double* vecIn, double* vecOut);\n   void vsAbs( int n,  float* vecIn, float* vecOut);\n}\n#endif\n\n\n// INTTerfaces to a few BLAS function, Level 1\n/// INTTerface to cblas_*nrm2\ntemplate <typename T> T cblas_nrm2( INTT n,  T* X,  INTT incX);\n/// INTTerface to cblas_*copy\ntemplate <typename T> void cblas_copy( INTT n,  T* X,  INTT incX, \n      T* Y,  INTT incY);\n/// INTTerface to cblas_*axpy\ntemplate <typename T> void cblas_axpy( INTT n,  T a,  T* X, \n       INTT incX, T* Y,  INTT incY);\n/// INTTerface to cblas_*scal\ntemplate <typename T> void cblas_scal( INTT n,  T a, T* X, \n       INTT incX);\n/// INTTerface to cblas_*asum\ntemplate <typename T> T cblas_asum( INTT n,  T* X,  INTT incX);\n/// INTTerface to cblas_*adot\ntemplate <typename T> T cblas_dot( INTT n,  T* X,  INTT incX, \n       T* Y, INTT incY);\n/// interface to cblas_i*amin\ntemplate <typename T> int cblas_iamin( INTT n,  T* X,  INTT incX);\n/// interface to cblas_i*amax\ntemplate <typename T> int cblas_iamax( INTT n,  T* X,  INTT incX);\n\n// INTTerfaces to a few BLAS function, Level 2\n\n/// INTTerface to cblas_*gemv\ntemplate <typename T> void cblas_gemv( CBLAS_ORDER order,\n       CBLAS_TRANSPOSE TransA,  INTT M, \n       INTT N,  T alpha,  T *A,  INTT lda,  T *X, \n       INTT incX,  T beta,T *Y,   INTT incY);\n/// INTTerface to cblas_*trmv\ntemplate <typename T> void inline cblas_trmv( CBLAS_ORDER order,  CBLAS_UPLO Uplo,\n       CBLAS_TRANSPOSE TransA,  CBLAS_DIAG Diag,  INTT N,\n       T *A,  INTT lda, T *X,  INTT incX);\n/// INTTerface to cblas_*syr\ntemplate <typename T> void inline cblas_syr( CBLAS_ORDER order, \n        CBLAS_UPLO Uplo,  INTT N,  T alpha, \n       T *X,  INTT incX, T *A,  INTT lda);\n\n/// INTTerface to cblas_*symv\ntemplate <typename T> inline void cblas_symv( CBLAS_ORDER order,\n       CBLAS_UPLO Uplo,  INTT N, \n       T alpha,  T *A,  INTT lda,  T *X, \n       INTT incX,  T beta,T *Y,   INTT incY);\n\n\n// INTTerfaces to a few BLAS function, Level 3\n/// INTTerface to cblas_*gemm\ntemplate <typename T> void cblas_gemm( CBLAS_ORDER order, \n       CBLAS_TRANSPOSE TransA,  CBLAS_TRANSPOSE TransB, \n       INTT M,  INTT N,  INTT K,  T alpha, \n       T *A,  INTT lda,  T *B,  INTT ldb,\n       T beta, T *C,  INTT ldc);\n/// INTTerface to cblas_*syrk\ntemplate <typename T> void cblas_syrk( CBLAS_ORDER order, \n       CBLAS_UPLO Uplo,  CBLAS_TRANSPOSE Trans,  INTT N,  INTT K,\n       T alpha,  T *A,  INTT lda,\n       T beta, T*C,  INTT ldc);\n/// INTTerface to cblas_*ger\ntemplate <typename T> void cblas_ger( CBLAS_ORDER order, \n       INTT M,  INTT N,  T alpha,  T *X,  INTT incX,\n       T* Y,  INTT incY, T*A,  INTT lda);\n/// INTTerface to cblas_*trmm\ntemplate <typename T> void cblas_trmm( CBLAS_ORDER order, \n       CBLAS_SIDE Side,  CBLAS_UPLO Uplo, \n       CBLAS_TRANSPOSE TransA,  CBLAS_DIAG Diag,\n       INTT M,  INTT N,  T alpha, \n       T*A,  INTT lda,T *B,  INTT ldb);\n\n// interfaces to a few functions from the intel Vector Mathematical Library\n/// interface to v*Sqr\ntemplate <typename T> void vSqrt( int n,  T* vecIn, T* vecOut);\n/// interface to v*Sqr\ntemplate <typename T> void vInvSqrt( int n,  T* vecIn, T* vecOut);\n/// interface to v*Sqr\ntemplate <typename T> void vSqr( int n,  T* vecIn, T* vecOut);\n/// interface to v*Sub\ntemplate <typename T> void vSub( int n,  T* vecIn,  T* vecIn2, T* vecOut);\n/// interface to v*Div\ntemplate <typename T> void vDiv( int n,  T* vecIn,  T* vecIn2, T* vecOut);\n/// interface to v*Exp\ntemplate <typename T> void vExp( int n,  T* vecIn, T* vecOut);\n/// interface to v*Inv\ntemplate <typename T> void vInv( int n,  T* vecIn, T* vecOut);\n/// interface to v*Add\ntemplate <typename T> void vAdd( int n,  T* vecIn,  T* vecIn2, T* vecOut);\n/// interface to v*Mul\ntemplate <typename T> void vMul( int n,  T* vecIn,  T* vecIn2, T* vecOut);\n/// interface to v*Abs\ntemplate <typename T> void vAbs( int n,  T* vecIn, T* vecOut);\n\n// interfaces to a few LAPACK functions\n/// interface to *trtri\ntemplate <typename T> void trtri(char& uplo, char& diag, \n      INTT n, T * a, INTT lda);\n/// interface to *sytri  // call sytrf\ntemplate <typename T> void sytri(char& uplo, INTT n, T* a, INTT lda);\n//, INTT* ipiv,\n//      T* work);\n/// interaface to *lasrt\ntemplate <typename T> void lasrt(char& id,  INTT n, T *d);\n//template <typename T> void lasrt2(char& id,  INTT& n, T *d, int* key);\ntemplate <typename T> void gesvd( char& jobu, char& jobvt, INTT m, \n      INTT n, T* a, INTT lda, T* s,\n      T* u, INTT ldu, T* vt, INTT ldvt);\ntemplate <typename T> void syev( char& jobz, char& uplo, INTT n,\n         T* a, INTT lda, T* w);\n\n\n/* ******************\n * Implementations\n * *****************/\n\nextern \"C\" {\n   double dnrm2_(INTT *n,double *x,INTT *incX);\n   float snrm2_(INTT *n,float *x,INTT *incX);\n   void dcopy_(INTT *n,double *x,INTT *incX, double *y,INTT *incY);\n   void scopy_(INTT *n,float *x,INTT *incX, float *y,INTT *incY);\n   void daxpy_(INTT *n,double* a, double *x,INTT *incX, double *y,INTT *incY);\n   void saxpy_(INTT *n,float* a, float *x,INTT *incX, float *y,INTT *incY);\n   void dscal_(INTT *n,double* a, double *x,INTT *incX);\n   void sscal_(INTT *n,float* a, float *x,INTT *incX);\n   double dasum_(INTT *n,double *x,INTT *incX);\n   float sasum_(INTT *n,float *x,INTT *incX);\n   double ddot_(INTT *n,double *x,INTT *incX, double *y,INTT *incY);\n   float sdot_(INTT *n,float *x,INTT *incX, float *y,INTT *incY);\n   void dgemv_(char   *trans, INTT *m, INTT *n, double *alpha, double *a,\n         INTT *lda, double *x, INTT *incx, double *beta, double *y,INTT *incy);\n   void sgemv_(char   *trans, INTT *m, INTT *n, float *alpha, float *a,\n         INTT *lda, float *x, INTT *incx, float *beta, float *y,INTT *incy);\n   void dger_(INTT *m, INTT *n, double *alpha, double *x, INTT *incx,\n         double *y, INTT *incy, double *a, INTT *lda);\n   void sger_(INTT *m, INTT *n, float *alpha, float *x, INTT *incx,\n         float *y, INTT *incy, float *a, INTT *lda);\n   void dtrmv_(char *uplo, char *trans, char   *diag, INTT *n, double *a,\n         INTT *lda, double *x, INTT *incx);\n   void strmv_(char *uplo, char *trans, char   *diag, INTT *n, float *a,\n         INTT *lda, float *x, INTT *incx);\n   void dsyr_(char *uplo, INTT *n, double *alpha, double *x, INTT *incx,\n         double *a, INTT *lda);\n   void ssyr_(char *uplo, INTT *n, float *alpha, float *x, INTT *incx,\n         float *a, INTT *lda);\n   void dsymv_(char   *uplo, INTT *n, double *alpha, double *a, INTT *lda,\n         double *x, INTT *incx, double *beta, double *y, INTT *incy);\n   void ssymv_(char   *uplo, INTT *n, float *alpha, float *a, INTT *lda,\n         float *x, INTT *incx, float *beta, float *y, INTT *incy);\n   void dgemm_(char *transa, char *transb, INTT *m, INTT *n, INTT *k,\n         double *alpha, double *a, INTT *lda, double *b, INTT *ldb, double *beta,\n         double *c, INTT *ldc);\n   void sgemm_(char *transa, char *transb, INTT *m, INTT *n, INTT *k,\n         float *alpha, float *a, INTT *lda, float *b, INTT *ldb, float *beta,\n         float *c, INTT *ldc);\n   void dsyrk_(char *uplo, char *trans, INTT *n, INTT *k, double *alpha,\n         double *a, INTT *lda, double *beta, double *c, INTT *ldc);\n   void ssyrk_(char *uplo, char *trans, INTT *n, INTT *k, float *alpha,\n         float *a, INTT *lda, float *beta, float *c, INTT *ldc);\n   void dtrmm_(char *side,char *uplo,char *transa, char *diag, INTT *m,\n         INTT *n, double *alpha, double *a, INTT *lda, double *b, \n         INTT *ldb);\n   void strmm_(char *side,char *uplo,char *transa, char *diag, INTT *m,\n         INTT *n, float *alpha, float *a, INTT *lda, float *b, \n         INTT *ldb);\n   INTT idamax_(INTT *n, double *dx, INTT *incx);\n   INTT isamax_(INTT *n, float *dx, INTT *incx);\n   void dtrtri_(char* uplo, char* diag, INTT* n, double * a, INTT* lda, \n         INTT* info);\n   void strtri_(char* uplo, char* diag, INTT* n, float * a, INTT* lda, \n         INTT* info);\n   void dsytrf_(char* uplo, INTT* n, double* a, INTT* lda, INTT* ipiv,\n         double* work, INTT* lwork, INTT* info);\n   void ssytrf_(char* uplo, INTT* n, float* a, INTT* lda, INTT* ipiv,\n         float* work, INTT* lwork, INTT* info);\n   void dsytri_(char* uplo, INTT* n, double* a, INTT* lda, INTT* ipiv,\n         double* work, INTT* info);\n   void ssytri_(char* uplo, INTT* n, float* a, INTT* lda, INTT* ipiv,\n         float* work, INTT* info);\n   void dlasrt_(char* id,  INTT* n, double *d, INTT* info);\n   void slasrt_(char* id,  INTT* n, float*d, INTT* info);\n   void dgesvd_(char*jobu, char *jobvt, INTT *m, INTT *n, double *a,\n         INTT *lda, double *s, double *u, INTT *ldu, double *vt,\n         INTT *ldvt, double *work, INTT *lwork, INTT *info);\n   void sgesvd_(char*jobu, char *jobvt, INTT *m, INTT *n, float *a,\n         INTT *lda, float *s, float *u, INTT *ldu, float *vt,\n         INTT *ldvt, float *work, INTT *lwork, INTT *info);\n   void dsyev_(char *jobz, char *uplo, INTT *n, double *a, INTT *lda,\n         double *w, double *work, INTT *lwork, INTT *info);\n   void ssyev_(char *jobz, char *uplo, INTT *n, float *a, INTT *lda,\n         float *w, float *work, INTT *lwork, INTT *info);\n}\n\n// Implementations of the INTTerfaces, BLAS Level 1\n/// Implementation of the INTTerface for cblas_dnrm2\ntemplate <> inline double cblas_nrm2<double>( INTT n,  double* X, \n       INTT incX) {\n   //return cblas_dnrm2(n,X,incX);\n   return dnrm2_(&n,X,&incX);\n};\n/// Implementation of the INTTerface for cblas_snrm2\ntemplate <> inline float cblas_nrm2<float>( INTT n,  float* X, \n       INTT incX) {\n   //return cblas_snrm2(n,X,incX);\n   return snrm2_(&n,X,&incX);\n};\n/// Implementation of the INTTerface for cblas_dcopy\ntemplate <> inline void cblas_copy<double>( INTT n,  double* X, \n       INTT incX, double* Y,  INTT incY) {\n   //cblas_dcopy(n,X,incX,Y,incY);\n   dcopy_(&n,X,&incX,Y,&incY);\n};\n/// Implementation of the INTTerface for cblas_scopy\ntemplate <> inline void cblas_copy<float>( INTT n,  float* X,  INTT incX, \n      float* Y,  INTT incY) {\n   //cblas_scopy(n,X,incX,Y,incY);\n   scopy_(&n,X,&incX,Y,&incY);\n};\n/// Implementation of the INTTerface for cblas_scopy\ntemplate <> inline void cblas_copy<int>( INTT n,  int* X,  INTT incX, \n      int* Y,  INTT incY) {\n   for (int i = 0; i<n; ++i)\n      Y[incY*i]=X[incX*i];\n};\n/// Implementation of the INTTerface for cblas_scopy\ntemplate <> inline void cblas_copy<bool>( INTT n,  bool* X,  INTT incX, \n      bool* Y,  INTT incY) {\n   for (int i = 0; i<n; ++i)\n      Y[incY*i]=X[incX*i];\n};\n\n/// Implementation of the INTTerface for cblas_daxpy\ntemplate <> inline void cblas_axpy<double>( INTT n,  double a,  double* X, \n       INTT incX, double* Y,  INTT incY) {\n   //cblas_daxpy(n,a,X,incX,Y,incY);\n   daxpy_(&n,&a,X,&incX,Y,&incY);\n};\n/// Implementation of the INTTerface for cblas_saxpy\ntemplate <> inline void cblas_axpy<float>( INTT n,  float a,  float* X,\n       INTT incX, float* Y,  INTT incY) {\n   //cblas_saxpy(n,a,X,incX,Y,incY);\n   saxpy_(&n,&a,X,&incX,Y,&incY);\n};\n\n/// Implementation of the INTTerface for cblas_saxpy\ntemplate <> inline void cblas_axpy<int>( INTT n,  int a,  int* X,\n       INTT incX, int* Y,  INTT incY) {\n   for (int i = 0; i<n; ++i)\n      Y[i] += a*X[i];\n};\n\n/// Implementation of the INTTerface for cblas_saxpy\ntemplate <> inline void cblas_axpy<bool>( INTT n,  bool a,  bool* X,\n       INTT incX, bool* Y,  INTT incY) {\n   for (int i = 0; i<n; ++i)\n      Y[i] = a*X[i];\n};\n\n\n/// Implementation of the INTTerface for cblas_dscal\ntemplate <> inline void cblas_scal<double>( INTT n,  double a, double* X,\n       INTT incX) {\n   //cblas_dscal(n,a,X,incX);\n   dscal_(&n,&a,X,&incX);\n};\n/// Implementation of the INTTerface for cblas_sscal\ntemplate <> inline void cblas_scal<float>( INTT n,  float a, float* X, \n       INTT incX) {\n   //cblas_sscal(n,a,X,incX);\n   sscal_(&n,&a,X,&incX);\n};\n/// Implementation of the INTTerface for cblas_sscal\ntemplate <> inline void cblas_scal<int>( INTT n,  int a, int* X, \n       INTT incX) {\n   for (int i = 0; i<n; ++i) X[i*incX]*=a;\n};\n/// Implementation of the INTTerface for cblas_sscal\ntemplate <> inline void cblas_scal<bool>( INTT n,  bool a, bool* X, \n       INTT incX) {\n   /// not implemented\n};\n\n/// Implementation of the INTTerface for cblas_dasum\ntemplate <> inline double cblas_asum<double>( INTT n,  double* X,  INTT incX) {\n   //return cblas_dasum(n,X,1);\n   return dasum_(&n,X,&incX);\n};\n/// Implementation of the INTTerface for cblas_sasum\ntemplate <> inline float cblas_asum<float>( INTT n,  float* X,  INTT incX) {\n   //return cblas_sasum(n,X,1);\n   return sasum_(&n,X,&incX);\n};\n/// Implementation of the INTTerface for cblas_ddot\ntemplate <> inline double cblas_dot<double>( INTT n,  double* X,\n       INTT incX,  double* Y, INTT incY) {\n   //return cblas_ddot(n,X,incX,Y,incY);\n   return ddot_(&n,X,&incX,Y,&incY);\n};\n/// Implementation of the INTTerface for cblas_sdot\ntemplate <> inline float cblas_dot<float>( INTT n,  float* X,\n       INTT incX,  float* Y, INTT incY) {\n   //return cblas_sdot(n,X,incX,Y,incY);\n   return sdot_(&n,X,&incX,Y,&incY);\n};\ntemplate <> inline int cblas_dot<int>( INTT n,  int* X,\n       INTT incX,  int* Y, INTT incY) {\n   int total=0;\n   int i,j;\n   j=0;\n   for (i = 0; i<n; ++i) {\n      total+=X[i*incX]*Y[j];\n      //j+=incY;\n      j+=(int)incY;\n   }\n   return total;\n};\n/// Implementation of the INTTerface for cblas_sdot\ntemplate <> inline bool cblas_dot<bool>( INTT n,  bool* X,\n       INTT incX,  bool* Y, INTT incY) {\n   /// not implemented\n   return true;\n};\n\n// Implementations of the INTTerfaces, BLAS Level 2\n///  Implementation of the INTTerface for cblas_dgemv\ntemplate <> inline void cblas_gemv<double>( CBLAS_ORDER order,\n       CBLAS_TRANSPOSE TransA,  INTT M,  INTT N,\n       double alpha,  double *A,  INTT lda,\n       double *X,  INTT incX,  double beta,\n      double *Y,  INTT incY) {\n   //cblas_dgemv(order,TransA,M,N,alpha,A,lda,X,incX,beta,Y,incY);\n   dgemv_(cblas_transpose(TransA),&M,&N,&alpha,A,&lda,X,&incX,&beta,Y,&incY);\n};\n///  Implementation of the INTTerface for cblas_sgemv\ntemplate <> inline void cblas_gemv<float>( CBLAS_ORDER order,\n       CBLAS_TRANSPOSE TransA,  INTT M,  INTT N,\n       float alpha,  float *A,  INTT lda,\n       float *X,  INTT incX,  float beta,\n      float *Y,  INTT incY) {\n   //cblas_sgemv(order,TransA,M,N,alpha,A,lda,X,incX,beta,Y,incY);\n   sgemv_(cblas_transpose(TransA),&M,&N,&alpha,A,&lda,X,&incX,&beta,Y,&incY);\n};\n///  Implementation of the INTTerface for cblas_sgemv\ntemplate <> inline void cblas_gemv<int>( CBLAS_ORDER order,\n       CBLAS_TRANSPOSE TransA,  INTT M,  INTT N,\n       int alpha,  int *A,  INTT lda,\n       int *X,  INTT incX,  int beta,\n      int *Y,  INTT incY) {\n   ///  not implemented\n};\n///  Implementation of the INTTerface for cblas_sgemv\ntemplate <> inline void cblas_gemv<bool>( CBLAS_ORDER order,\n       CBLAS_TRANSPOSE TransA,  INTT M,  INTT N,\n       bool alpha,  bool *A,  INTT lda,\n       bool *X,  INTT incX,  bool beta,\n      bool *Y,  INTT incY) {\n   /// not implemented\n};\n\n///  Implementation of the INTTerface for cblas_dger\ntemplate <> inline void cblas_ger<double>( CBLAS_ORDER order, \n       INTT M,  INTT N,  double alpha,  double *X,  INTT incX,\n       double* Y,  INTT incY, double *A,  INTT lda) {\n   //cblas_dger(order,M,N,alpha,X,incX,Y,incY,A,lda);\n   dger_(&M,&N,&alpha,X,&incX,Y,&incY,A,&lda);\n};\n///  Implementation of the INTTerface for cblas_sger\ntemplate <> inline void cblas_ger<float>( CBLAS_ORDER order, \n       INTT M,  INTT N,  float alpha,  float *X,  INTT incX,\n       float* Y,  INTT incY, float *A,  INTT lda) {\n   //cblas_sger(order,M,N,alpha,X,incX,Y,incY,A,lda);\n   sger_(&M,&N,&alpha,X,&incX,Y,&incY,A,&lda);\n};\n///  Implementation of the INTTerface for cblas_dtrmv\ntemplate <> inline void cblas_trmv<double>( CBLAS_ORDER order,  CBLAS_UPLO Uplo,\n       CBLAS_TRANSPOSE TransA,  CBLAS_DIAG Diag,  INTT N,\n       double *A,  INTT lda, double *X,  INTT incX) {\n   //cblas_dtrmv(order,Uplo,TransA,Diag,N,A,lda,X,incX);\n   dtrmv_(cblas_uplo(Uplo),cblas_transpose(TransA),cblas_diag(Diag),&N,A,&lda,X,&incX);\n};\n///  Implementation of the INTTerface for cblas_strmv\ntemplate <> inline void cblas_trmv<float>( CBLAS_ORDER order,  CBLAS_UPLO Uplo,\n       CBLAS_TRANSPOSE TransA,  CBLAS_DIAG Diag,  INTT N,\n       float *A,  INTT lda, float *X,  INTT incX) {\n   //cblas_strmv(order,Uplo,TransA,Diag,N,A,lda,X,incX);\n   strmv_(cblas_uplo(Uplo),cblas_transpose(TransA),cblas_diag(Diag),&N,A,&lda,X,&incX);\n};\n/// Implementation of cblas_dsyr\ntemplate <> inline void cblas_syr( CBLAS_ORDER order, \n        CBLAS_UPLO Uplo,\n       INTT N,  double alpha,  double*X,\n       INTT incX, double *A,  INTT lda) {\n   //cblas_dsyr(order,Uplo,N,alpha,X,incX,A,lda);\n   dsyr_(cblas_uplo(Uplo),&N,&alpha,X,&incX,A,&lda);\n};\n/// Implementation of cblas_ssyr\ntemplate <> inline void cblas_syr( CBLAS_ORDER order, \n        CBLAS_UPLO Uplo,\n       INTT N,  float alpha,  float*X,\n       INTT incX, float *A,  INTT lda) {\n   //cblas_ssyr(order,Uplo,N,alpha,X,incX,A,lda);\n   ssyr_(cblas_uplo(Uplo),&N,&alpha,X,&incX,A,&lda);\n};\n/// Implementation of cblas_ssymv\ntemplate <> inline void cblas_symv( CBLAS_ORDER order,\n       CBLAS_UPLO Uplo,  INTT N, \n       float alpha,  float *A,  INTT lda,  float *X, \n       INTT incX,  float beta,float *Y,   INTT incY) {\n   //cblas_ssymv(order,Uplo,N,alpha,A,lda,X,incX,beta,Y,incY);\n   ssymv_(cblas_uplo(Uplo),&N,&alpha,A,&lda,X,&incX,&beta,Y,&incY);\n}\n/// Implementation of cblas_dsymv\ntemplate <> inline void cblas_symv( CBLAS_ORDER order,\n       CBLAS_UPLO Uplo,  INTT N, \n       double alpha,  double *A,  INTT lda,  double *X, \n       INTT incX,  double beta,double *Y,   INTT incY) {\n   //cblas_dsymv(order,Uplo,N,alpha,A,lda,X,incX,beta,Y,incY);\n   dsymv_(cblas_uplo(Uplo),&N,&alpha,A,&lda,X,&incX,&beta,Y,&incY);\n}\n\n\n// Implementations of the INTTerfaces, BLAS Level 3\n///  Implementation of the INTTerface for cblas_dgemm\ntemplate <> inline void cblas_gemm<double>( CBLAS_ORDER order, \n       CBLAS_TRANSPOSE TransA,  CBLAS_TRANSPOSE TransB, \n       INTT M,  INTT N,  INTT K,  double alpha, \n       double *A,  INTT lda,  double *B,  INTT ldb,\n       double beta, double *C,  INTT ldc) {\n   //cblas_dgemm(Order,TransA,TransB,M,N,K,alpha,A,lda,B,ldb,beta,C,ldc);\n   dgemm_(cblas_transpose(TransA),cblas_transpose(TransB),&M,&N,&K,&alpha,A,&lda,B,&ldb,&beta,C,&ldc);\n};\n///  Implementation of the INTTerface for cblas_sgemm\ntemplate <> inline void cblas_gemm<float>( CBLAS_ORDER order, \n       CBLAS_TRANSPOSE TransA,  CBLAS_TRANSPOSE TransB, \n       INTT M,  INTT N,  INTT K,  float alpha, \n       float *A,  INTT lda,  float *B,  INTT ldb,\n       float beta, float *C,  INTT ldc) {\n   //cblas_sgemm(Order,TransA,TransB,M,N,K,alpha,A,lda,B,ldb,beta,C,ldc);\n   sgemm_(cblas_transpose(TransA),cblas_transpose(TransB),&M,&N,&K,&alpha,A,&lda,B,&ldb,&beta,C,&ldc);\n};\ntemplate <> inline void cblas_gemm<int>( CBLAS_ORDER order, \n       CBLAS_TRANSPOSE TransA,  CBLAS_TRANSPOSE TransB, \n       INTT M,  INTT N,  INTT K,  int alpha, \n       int *A,  INTT lda,  int *B,  INTT ldb,\n       int beta, int *C,  INTT ldc) {\n   /// not implemented\n};\n///  Implementation of the INTTerface for cblas_sgemm\ntemplate <> inline void cblas_gemm<bool>( CBLAS_ORDER order, \n       CBLAS_TRANSPOSE TransA,  CBLAS_TRANSPOSE TransB, \n       INTT M,  INTT N,  INTT K,  bool alpha, \n       bool *A,  INTT lda,  bool *B,  INTT ldb,\n       bool beta, bool *C,  INTT ldc) {\n   /// not implemented\n};\n\n///  Implementation of the INTTerface for cblas_dsyrk\ntemplate <> inline void cblas_syrk<double>( CBLAS_ORDER order, \n       CBLAS_UPLO Uplo,  CBLAS_TRANSPOSE Trans,  INTT N,  INTT K,\n       double alpha,  double *A,  INTT lda,\n       double beta, double *C,  INTT ldc) {\n   //cblas_dsyrk(Order,Uplo,Trans,N,K,alpha,A,lda,beta,C,ldc);\n   dsyrk_(cblas_uplo(Uplo),cblas_transpose(Trans),&N,&K,&alpha,A,&lda,&beta,C,&ldc);\n};\n///  Implementation of the INTTerface for cblas_ssyrk\ntemplate <> inline void cblas_syrk<float>( CBLAS_ORDER order, \n       CBLAS_UPLO Uplo,  CBLAS_TRANSPOSE Trans,  INTT N,  INTT K,\n       float alpha,  float *A,  INTT lda,\n       float beta, float *C,  INTT ldc) {\n   //cblas_ssyrk(Order,Uplo,Trans,N,K,alpha,A,lda,beta,C,ldc);\n   ssyrk_(cblas_uplo(Uplo),cblas_transpose(Trans),&N,&K,&alpha,A,&lda,&beta,C,&ldc);\n};\n///  Implementation of the INTTerface for cblas_ssyrk\ntemplate <> inline void cblas_syrk<int>( CBLAS_ORDER order, \n       CBLAS_UPLO Uplo,  CBLAS_TRANSPOSE Trans,  INTT N,  INTT K,\n       int alpha,  int *A,  INTT lda,\n       int beta, int *C,  INTT ldc) {\n   /// not implemented\n};\n///  Implementation of the INTTerface for cblas_ssyrk\ntemplate <> inline void cblas_syrk<bool>( CBLAS_ORDER order, \n       CBLAS_UPLO Uplo,  CBLAS_TRANSPOSE Trans,  INTT N,  INTT K,\n       bool alpha,  bool *A,  INTT lda,\n       bool beta, bool *C,  INTT ldc) {\n   /// not implemented\n};\n\n///  Implementation of the INTTerface for cblas_dtrmm\ntemplate <> inline void cblas_trmm<double>( CBLAS_ORDER order, \n       CBLAS_SIDE Side,  CBLAS_UPLO Uplo, \n       CBLAS_TRANSPOSE TransA,  CBLAS_DIAG Diag,\n       INTT M,  INTT N,  double alpha, \n       double *A,  INTT lda,double *B,  INTT ldb) {\n   //cblas_dtrmm(Order,Side,Uplo,TransA,Diag,M,N,alpha,A,lda,B,ldb);\n   dtrmm_(cblas_side(Side),cblas_uplo(Uplo),cblas_transpose(TransA),cblas_diag(Diag),&M,&N,&alpha,A,&lda,B,&ldb);\n};\n///  Implementation of the INTTerface for cblas_strmm\ntemplate <> inline void cblas_trmm<float>( CBLAS_ORDER order, \n       CBLAS_SIDE Side,  CBLAS_UPLO Uplo, \n       CBLAS_TRANSPOSE TransA,  CBLAS_DIAG Diag,\n       INTT M,  INTT N,  float alpha, \n       float *A,  INTT lda,float *B,  INTT ldb) {\n   //cblas_strmm(Order,Side,Uplo,TransA,Diag,M,N,alpha,A,lda,B,ldb);\n   strmm_(cblas_side(Side),cblas_uplo(Uplo),cblas_transpose(TransA),cblas_diag(Diag),&M,&N,&alpha,A,&lda,B,&ldb);\n};\n///  Implementation of the interface for cblas_idamax\ntemplate <> inline int cblas_iamax<double>( INTT n,  double* X,\n       INTT incX) {\n   //return cblas_idamax(n,X,incX);\n   return static_cast<int>(idamax_(&n,X,&incX)-1);\n};\n///  Implementation of the interface for cblas_isamax\ntemplate <> inline int cblas_iamax<float>( INTT n,  float* X, \n       INTT incX) {\n   //return cblas_isamax(n,X,incX);\n   return static_cast<int>(isamax_(&n,X,&incX)-1);\n};\n\n// Implementations of the interfaces, LAPACK\n/// Implemenation of the interface for dtrtri\ntemplate <> inline void trtri<double>(char& uplo, char& diag, \n      INTT n, double * a, INTT lda) {\n   //dtrtri_(&uplo,&diag,&n,a,&lda,&info);\n   dtrtri_(&uplo,&diag,&n,a,&lda,&info);\n};\n/// Implemenation of the interface for strtri\ntemplate <> inline void trtri<float>(char& uplo, char& diag, \n      INTT n, float* a, INTT lda) {\n   //strtri_(&uplo,&diag,&n,a,&lda,&info);\n   strtri_(&uplo,&diag,&n,a,&lda,&info);\n};\n\n/// Implemenation of the interface for dsytri\ntemplate <> inline void sytri<double>(char& uplo, INTT n, double* a, INTT lda) {\n//, INTT* ipiv, double* work) {\n   //dsytri_(&uplo,&n,a,&lda,ipiv,work,&info);\n   INTT lwork=-1;\n   INTT* ipiv= new INTT[n];\n   double* query, *work;\n   query = new double[1];\n   dsytrf_(&uplo,&n,a,&lda,ipiv,query,&lwork,&info);\n   lwork=static_cast<INTT>(*query); \n   delete[](query);\n   work = new double[static_cast<int>(lwork)];\n   dsytrf_(&uplo,&n,a,&lda,ipiv,work,&lwork,&info);\n   delete[](work);\n   work = new double[static_cast<int>(2*n)];\n   dsytri_(&uplo,&n,a,&lda,ipiv,work,&info);\n   delete[](work);\n   delete[](ipiv);\n};\n/// Implemenation of the interface for ssytri\ntemplate <> inline void sytri<float>(char& uplo, INTT n, float* a, INTT lda) {\n   INTT lwork=-1;\n   INTT* ipiv= new INTT[n];\n   float* query, *work;\n   query = new float[1];\n   ssytrf_(&uplo,&n,a,&lda,ipiv,query,&lwork,&info);\n   lwork=static_cast<INTT>(*query); \n   delete[](query);\n   work = new float[static_cast<int>(lwork)];\n   ssytrf_(&uplo,&n,a,&lda,ipiv,work,&lwork,&info);\n   delete[](work);\n   work = new float[static_cast<int>(2*n)];\n   ssytri_(&uplo,&n,a,&lda,ipiv,work,&info);\n   delete[](work);\n   delete[](ipiv);\n};\n/// interaface to *lasrt\ntemplate <> inline void lasrt(char& id, INTT n, double *d) {\n   //dlasrt_(&id,const_cast<int*>(&n),d,&info);\n   dlasrt_(&id,&n,d,&info);\n};\n/// interaface to *lasrt\ntemplate <> inline void lasrt(char& id, INTT n, float *d) {\n   //slasrt_(&id,const_cast<int*>(&n),d,&info);\n   slasrt_(&id,&n,d,&info);\n};\n//template <> inline void lasrt2(char& id, INTT& n, double *d,int* key) {\n//   //dlasrt2_(&id,const_cast<int*>(&n),d,key,&info);\n//   dlasrt2(&id,&n,d,key,&info);\n//};\n///// interaface to *lasrt\n//template <> inline void lasrt2(char& id, INTT& n, float *d, int* key) {\n//   //slasrt2_(&id,const_cast<int*>(&n),d,key,&info);\n//   slasrt2(&id,&n,d,key,&info);\n//};\ntemplate <> void inline gesvd( char& jobu, char& jobvt, INTT m, \n      INTT n, double* a, INTT lda, double* s,\n      double* u, INTT ldu, double* vt, INTT ldvt) {\n   double* query = new double[1];\n   INTT lwork=-1;\n   dgesvd_(&jobu, &jobvt, &m, &n, a, &lda, s, u, &ldu, vt, &ldvt,\n         query, &lwork, &info );\n   lwork=static_cast<INTT>(*query); \n   delete[](query);\n   double* work = new double[static_cast<int>(lwork)];\n   dgesvd_(&jobu, &jobvt, &m, &n, a, &lda, s, u, &ldu, vt, &ldvt,\n         work, &lwork, &info );\n   delete[](work);\n}\ntemplate <> void inline gesvd( char& jobu, char& jobvt, INTT m, \n      INTT n, float* a, INTT lda, float* s,\n      float* u, INTT ldu, float* vt, INTT ldvt) {\n   float* query = new float[1];\n   INTT lwork=-1;\n   sgesvd_(&jobu, &jobvt, &m, &n, a, &lda, s, u, &ldu, vt, &ldvt,\n         query, &lwork, &info );\n   lwork=static_cast<INTT>(*query); \n   delete[](query);\n   float* work = new float[static_cast<int>(lwork)];\n   sgesvd_(&jobu, &jobvt, &m, &n, a, &lda, s, u, &ldu, vt, &ldvt,\n         work, &lwork, &info );\n   delete[](work);\n}\n\ntemplate <> void inline syev( char& jobz, char& uplo, INTT n,\n         float* a, INTT lda, float* w) {\n   float* query = new float[1];\n   INTT lwork=-1;\n   ssyev_(&jobz,&uplo,&n,a,&lda,w,query,&lwork,&info);\n   lwork=static_cast<INTT>(*query); \n   delete[](query);\n   float* work = new float[static_cast<int>(lwork)];\n   ssyev_(&jobz,&uplo,&n,a,&lda,w,work,&lwork,&info);\n   delete[](work);\n};\n\ntemplate <> void inline syev( char& jobz, char& uplo, INTT n,\n         double* a, INTT lda, double* w) {\n   double* query = new double[1];\n   INTT lwork=-1;\n   dsyev_(&jobz,&uplo,&n,a,&lda,w,query,&lwork,&info);\n   lwork=static_cast<INTT>(*query); \n   delete[](query);\n   double* work = new double[static_cast<int>(lwork)];\n   dsyev_(&jobz,&uplo,&n,a,&lda,w,work,&lwork,&info);\n   delete[](work);\n};\n\n\n\n\n/// If the MKL is not present, a slow implementation is used instead.\n#ifdef HAVE_MKL \n/// Implemenation of the interface for vdSqr\ntemplate <> inline void vSqr<double>( int n,  double* vecIn, \n      double* vecOut) {\n   vdSqr(n,vecIn,vecOut);\n};\n/// Implemenation of the interface for vsSqr\ntemplate <> inline void vSqr<float>( int n,  float* vecIn, \n      float* vecOut) {\n   vsSqr(n,vecIn,vecOut);\n};\ntemplate <> inline void vSqrt<double>( int n,  double* vecIn, \n      double* vecOut) {\n   vdSqrt(n,vecIn,vecOut);\n};\n/// Implemenation of the interface for vsSqr\ntemplate <> inline void vSqrt<float>( int n,  float* vecIn, \n      float* vecOut) {\n   vsSqrt(n,vecIn,vecOut);\n};\ntemplate <> inline void vInvSqrt<double>( int n,  double* vecIn, \n      double* vecOut) {\n   vdInvSqrt(n,vecIn,vecOut);\n};\n/// Implemenation of the interface for vsSqr\ntemplate <> inline void vInvSqrt<float>( int n,  float* vecIn, \n      float* vecOut) {\n   vsInvSqrt(n,vecIn,vecOut);\n};\n\n/// Implemenation of the interface for vdSub\ntemplate <> inline void vSub<double>( int n,  double* vecIn, \n       double* vecIn2, double* vecOut) {\n   vdSub(n,vecIn,vecIn2,vecOut);\n};\n/// Implemenation of the interface for vsSub\ntemplate <> inline void vSub<float>( int n,  float* vecIn, \n       float* vecIn2, float* vecOut) {\n   vsSub(n,vecIn,vecIn2,vecOut);\n};\n/// Implemenation of the interface for vdDiv\ntemplate <> inline void vDiv<double>( int n,  double* vecIn, \n       double* vecIn2, double* vecOut) {\n   vdDiv(n,vecIn,vecIn2,vecOut);\n};\n/// Implemenation of the interface for vsDiv\ntemplate <> inline void vDiv<float>( int n,  float* vecIn, \n       float* vecIn2, float* vecOut) {\n   vsDiv(n,vecIn,vecIn2,vecOut);\n};\n/// Implemenation of the interface for vdExp\ntemplate <> inline void vExp<double>( int n,  double* vecIn, \n      double* vecOut) {\n   vdExp(n,vecIn,vecOut);\n};\n/// Implemenation of the interface for vsExp\ntemplate <> inline void vExp<float>( int n,  float* vecIn, \n      float* vecOut) {\n   vsExp(n,vecIn,vecOut);\n};\n/// Implemenation of the interface for vdInv\ntemplate <> inline void vInv<double>( int n,  double* vecIn, \n      double* vecOut) {\n   vdInv(n,vecIn,vecOut);\n};\n/// Implemenation of the interface for vsInv\ntemplate <> inline void vInv<float>( int n,  float* vecIn, \n      float* vecOut) {\n   vsInv(n,vecIn,vecOut);\n};\n/// Implemenation of the interface for vdAdd\ntemplate <> inline void vAdd<double>( int n,  double* vecIn, \n       double* vecIn2, double* vecOut) {\n   vdAdd(n,vecIn,vecIn2,vecOut);\n};\n/// Implemenation of the interface for vsAdd\ntemplate <> inline void vAdd<float>( int n,  float* vecIn, \n       float* vecIn2, float* vecOut) {\n   vsAdd(n,vecIn,vecIn2,vecOut);\n};\n/// Implemenation of the interface for vdMul\ntemplate <> inline void vMul<double>( int n,  double* vecIn, \n       double* vecIn2, double* vecOut) {\n   vdMul(n,vecIn,vecIn2,vecOut);\n};\n/// Implemenation of the interface for vsMul\ntemplate <> inline void vMul<float>( int n,  float* vecIn, \n       float* vecIn2, float* vecOut) {\n   vsMul(n,vecIn,vecIn2,vecOut);\n};\n\n/// interface to vdAbs\ntemplate <> inline void vAbs( int n,  double* vecIn, \n      double* vecOut) {\n   vdAbs(n,vecIn,vecOut);\n};\n/// interface to vdAbs\ntemplate <> inline void vAbs( int n,  float* vecIn, \n      float* vecOut) {\n   vsAbs(n,vecIn,vecOut);\n};\n\n\n/// implemenation of the interface of the non-offical blas, level 1 function \n/// cblas_idamin\ntemplate <> inline int cblas_iamin<double>( int n,  double* x,\n       int incx) {\n   return (int) cblas_idamin(n,x,incx);\n};\n/// implemenation of the interface of the non-offical blas, level 1 function \n/// cblas_isamin\ntemplate <> inline int cblas_iamin<float>( int n,  float* x, \n       int incx) {\n   return (int) cblas_isamin(n,x,incx);\n};\n/// slow alternative implementation of some MKL function\n#else\n/// Slow implementation of vdSqr and vsSqr\ntemplate <typename T> inline void vSqr( int n,  T* vecIn, T* vecOut) {\n   for (int i = 0; i<n; ++i) vecOut[i]=vecIn[i]*vecIn[i];\n};\ntemplate <typename T> inline void vSqrt( int n,  T* vecIn, T* vecOut) {\n   for (int i = 0; i<n; ++i) vecOut[i]=sqr<T>(vecIn[i]);\n};\ntemplate <typename T> inline void vInvSqrt( int n,  T* vecIn, T* vecOut) {\n   for (int i = 0; i<n; ++i) vecOut[i]=T(1.0)/sqr<T>(vecIn[i]);\n};\n\n/// Slow implementation of vdSub and vsSub\ntemplate <typename T> inline void vSub( int n,  T* vecIn1, \n       T* vecIn2, T* vecOut) {\n   for (int i = 0; i<n; ++i) vecOut[i]=vecIn1[i]-vecIn2[i];\n};\n/// Slow implementation of vdInv and vsInv\ntemplate <typename T> inline void vInv( int n,  T* vecIn, T* vecOut) {\n   for (int i = 0; i<n; ++i) vecOut[i]=1.0/vecIn[i];\n};\n/// Slow implementation of vdExp and vsExp\ntemplate <typename T> inline void vExp( int n,  T* vecIn, T* vecOut) {\n   for (int i = 0; i<n; ++i) vecOut[i]=exp(vecIn[i]);\n};\n/// Slow implementation of vdAdd and vsAdd\ntemplate <typename T> inline void vAdd( int n,  T* vecIn1, \n       T* vecIn2, T* vecOut) {\n   for (int i = 0; i<n; ++i) vecOut[i]=vecIn1[i]+vecIn2[i];\n};\n/// Slow implementation of vdMul and vsMul\ntemplate <typename T> inline void vMul( int n,  T* vecIn1, \n       T* vecIn2, T* vecOut) {\n   for (int i = 0; i<n; ++i) vecOut[i]=vecIn1[i]*vecIn2[i];\n};\n/// Slow implementation of vdDiv and vsDiv\ntemplate <typename T> inline void vDiv( int n,  T* vecIn1, \n       T* vecIn2, T* vecOut) {\n   for (int i = 0; i<n; ++i) vecOut[i]=vecIn1[i]/vecIn2[i];\n};\n/// Slow implementation of vAbs\ntemplate <typename T> inline void vAbs( int n,  T* vecIn, \n      T* vecOut) {\n   for (int i = 0; i<n; ++i) vecOut[i]=abs<T>(vecIn[i]);\n};\n\n/// Slow implementation of cblas_idamin and cblas_isamin\ntemplate <typename T> int inline cblas_iamin(INTT n, T* X, INTT incX) {\n   int imin=0;\n   double min=fabs(X[0]);\n   for (int j = 1; j<n; j+=incX) {\n      double cur = fabs(X[j]);\n      if (cur < min) {\n         imin=j;\n         min = cur;\n      }\n   }\n   return imin;\n}\n#endif\n\n#endif \n", "meta": {"hexsha": "e1e6c58f8b5e0c94296bfd104f99cbb2f357e152", "size": 35312, "ext": "h", "lang": "C", "max_stars_repo_path": "util/ISR/spams-matlab/linalg/cblas_alt_template.h", "max_stars_repo_name": "ChrystleMyrnaLobo/person-reid-benchmark", "max_stars_repo_head_hexsha": "d09fa9c57213464f94e37cb3b202dddc6f0b0267", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 202.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T21:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T15:32:17.000Z", "max_issues_repo_path": "util/ISR/spams-matlab/linalg/cblas_alt_template.h", "max_issues_repo_name": "XuJiaMing1997/person-reid-benchmark", "max_issues_repo_head_hexsha": "d09fa9c57213464f94e37cb3b202dddc6f0b0267", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2017-12-18T12:54:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-17T17:33:27.000Z", "max_forks_repo_path": "util/ISR/spams-matlab/linalg/cblas_alt_template.h", "max_forks_repo_name": "XuJiaMing1997/person-reid-benchmark", "max_forks_repo_head_hexsha": "d09fa9c57213464f94e37cb3b202dddc6f0b0267", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 77.0, "max_forks_repo_forks_event_min_datetime": "2017-12-18T01:35:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T08:37:05.000Z", "avg_line_length": 37.9291084855, "max_line_length": 113, "alphanum_fraction": 0.6449932034, "num_tokens": 12637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34864513533394575, "lm_q2_score": 0.014728614741716453, "lm_q1q2_score": 0.0051350598799072816}}
{"text": "#include <gsl/span>\n\nnamespace engine\n{\n\ttemplate <class ElementType, std::ptrdiff_t Extent = gsl::dynamic_extent>\n\tusing span = gsl::span<ElementType, Extent>;\n}\n", "meta": {"hexsha": "704e4e1f60d6f9ecefca1960eeee7ddb3fa60b71", "size": 163, "ext": "h", "lang": "C", "max_stars_repo_path": "Core/span.h", "max_stars_repo_name": "gaspardpetit/INF740-GameEngine", "max_stars_repo_head_hexsha": "075b6563204fb3d1cf7531599f30dd296c2c9239", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Core/span.h", "max_issues_repo_name": "gaspardpetit/INF740-GameEngine", "max_issues_repo_head_hexsha": "075b6563204fb3d1cf7531599f30dd296c2c9239", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Core/span.h", "max_forks_repo_name": "gaspardpetit/INF740-GameEngine", "max_forks_repo_head_hexsha": "075b6563204fb3d1cf7531599f30dd296c2c9239", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-09-25T22:24:16.000Z", "max_forks_repo_forks_event_max_datetime": "2015-09-25T22:24:16.000Z", "avg_line_length": 20.375, "max_line_length": 74, "alphanum_fraction": 0.7423312883, "num_tokens": 40, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.13117323055476696, "lm_q2_score": 0.039048289091790075, "lm_q1q2_score": 0.0051220902278065715}}
{"text": "#pragma once\n\n#include <gsl\\gsl>\n#include <winrt\\Windows.Foundation.h>\n#include <d3d11.h>\n#include <map>\n#include \"DrawableGameComponent.h\"\n#include \"FullScreenRenderTarget.h\"\n#include \"FullScreenQuad.h\"\n\nnamespace Library\n{\n\tclass Texture2D;\n}\n\nnamespace Rendering\n{\n\tenum class DistortionMaps\n\t{\n\t\tGlass,\n\t\tText,\n\t\tNoDistortion,\n\t\tEnd\n\t};\n\n\tclass DiffuseLightingDemo;\n\n\tclass DistortionMappingDemo final : public Library::DrawableGameComponent\n\t{\n\tpublic:\n\t\tDistortionMappingDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera);\n\t\tDistortionMappingDemo(const DistortionMappingDemo&) = delete;\n\t\tDistortionMappingDemo(DistortionMappingDemo&&) = default;\n\t\tDistortionMappingDemo& operator=(const DistortionMappingDemo&) = default;\t\t\n\t\tDistortionMappingDemo& operator=(DistortionMappingDemo&&) = default;\n\t\t~DistortionMappingDemo();\n\n\t\tstd::shared_ptr<DiffuseLightingDemo> DiffuseLighting() const;\n\n\t\tfloat DisplacementScale() const;\n\t\tvoid SetDisplacementScale(float displacementScale);\n\n\t\tDistortionMaps DistortionMap() const;\n\t\tconst std::string& DistortionMapString() const;\n\t\tvoid SetDistortionMap(DistortionMaps distortionMap);\n\n\t\tvirtual void Initialize() override;\n\t\tvirtual void Update(const Library::GameTime& gameTime) override;\n\t\tvirtual void Draw(const Library::GameTime& gameTime) override;\n\n\tprivate:\n\t\tstatic const std::map<DistortionMaps, std::string> DistortionMapNames;\n\n\t\tstruct PixelCBufferPerObject\n\t\t{\n\t\t\tfloat DisplacementScale{ 1.0f };\n\t\t\tDirectX::XMFLOAT3 Padding{ 0.0f, 0.0f, 0.0f };\n\t\t};\n\n\t\tstd::shared_ptr<DiffuseLightingDemo> mDiffuseLightingDemo;\t\t\n\t\tLibrary::FullScreenRenderTarget mRenderTarget;\n\t\tLibrary::FullScreenQuad mFullScreenQuad;\t\t\n\t\twinrt::com_ptr<ID3D11Buffer> mPixelCBufferPerObject;\n\t\tPixelCBufferPerObject mPixelCBufferPerObjectData;\n\t\tstd::map<DistortionMaps, std::shared_ptr<Library::Texture2D>> mDistortionMaps;\n\t\tDistortionMaps mActiveDistortionMap{ DistortionMaps::Glass };\n\t};\n}", "meta": {"hexsha": "bc916c2582f79b524795313a4eb1bd0c13791ae3", "size": 1951, "ext": "h", "lang": "C", "max_stars_repo_path": "source/7.4_Distortion_Mapping/DistortionMappingDemo.h", "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/7.4_Distortion_Mapping/DistortionMappingDemo.h", "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/7.4_Distortion_Mapping/DistortionMappingDemo.h", "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6911764706, "max_line_length": 93, "alphanum_fraction": 0.7816504357, "num_tokens": 521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24798741512455283, "lm_q2_score": 0.02064592979766642, "lm_q1q2_score": 0.005119930763366277}}
{"text": "// Licensed to the Apache Software Foundation (ASF) under one\n// or more contributor license agreements.  See the LICENSE file\n// distributed with this work for additional information\n// regarding copyright ownership.  The ASF licenses this file\n// to you under the Apache License, Version 2.0 (the\n// \"License\"); you may not use this file except in compliance\n// with the License.  You may obtain a copy of the License at\n//\n//   http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing,\n// software distributed under the License is distributed on an\n// \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n// KIND, either express or implied.  See the License for the\n// specific language governing permissions and limitations\n// under the License.\n\n#pragma once\n\n#include <boost/multiprecision/cpp_int.hpp>\n#include <gsl/gsl>\n#include <spdlog/spdlog.h>\n\nusing uint256_t = boost::multiprecision::checked_uint256_t;\nusing byte = std::byte;\n\n#include \"inc/exception.h\"\n#include \"inc/log.h\"\n#include \"inc/string.h\"\n\n#define BETTER_ENUMS_DEFAULT_CONSTRUCTOR(Enum)                                 \\\npublic:                                                                        \\\n  Enum() = default;\n\n#define ENUM BETTER_ENUM\n", "meta": {"hexsha": "45c4de7cf4c835e31080dba51b5bf505963309c3", "size": 1274, "ext": "h", "lang": "C", "max_stars_repo_path": "src/inc/essential.h", "max_stars_repo_name": "bandprotocol/bandprotocol", "max_stars_repo_head_hexsha": "4a5861d14dba6a69af0e7ce9fc142beb9315dcb4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-02-13T17:50:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-21T15:18:14.000Z", "max_issues_repo_path": "src/inc/essential.h", "max_issues_repo_name": "bandprotocol/bandchain-legacy", "max_issues_repo_head_hexsha": "4a5861d14dba6a69af0e7ce9fc142beb9315dcb4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/inc/essential.h", "max_forks_repo_name": "bandprotocol/bandchain-legacy", "max_forks_repo_head_hexsha": "4a5861d14dba6a69af0e7ce9fc142beb9315dcb4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3888888889, "max_line_length": 80, "alphanum_fraction": 0.693877551, "num_tokens": 272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21206880435710534, "lm_q2_score": 0.02405355438109515, "lm_q1q2_score": 0.0051010085181374615}}
{"text": "/*  \n * This file is part of the Visual Computing Library (VCL) release under the\n * license.\n * \n * Copyright (c) 2017 Basil Fierz\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n#pragma once\n\n// VCL configuration\n#include <vcl/config/global.h>\n\n// C++ Standard library\n#include <memory>\n#include <string>\n#include <tuple>\n#include <vector>\n\n// GSL\n#include <gsl/gsl>\n\n// Windows API\n#define WIN32_LEAN_AND_MEAN\n#include <Windows.h>\nextern \"C\" {\n#    include <hidsdi.h>\n}\n\n// VCL\n#include <vcl/hid/device.h>\n\nnamespace Vcl { namespace HID { namespace Windows\n{\n\t//! \\note Structure definition taken from\n\t//! https://zfx.info/viewtopic.php?f=11&t=2977\n\t//! https://www.codeproject.com/Articles/297312/Minimal-Key-Logger-using-RAWINPUT\n\t//! https://www.codeproject.com/Articles/185522/Using-the-Raw-Input-API-to-Process-Joystick-Input\n\tstruct Axis\n\t{\n\t\t//! Usage page as defined in the standard (e.g. \"generic (0001)\")\n\t\tUSAGE usagePage;\n\n\t\t//! Usage of the axis as defined in the standard (e.g. \"slider (0036)\")\n\t\tUSAGE usage;\n\n\t\t//! Index as defined through Hidp_GetData()\n\t\tUSHORT index;\n\t\t\n\t\t//! Minimum value defined by the HID device\n\t\tint32_t                logicalMinimum;\n\t\t\n\t\t//! Maximum value defined by the HID device\n\t\tint32_t                logicalMaximum;\n\n\t\t//! Indicate wheter DirectInput calibration data was applied\n\t\tbool                   isCalibrated;\n\t\t\n\t\t//! Minimum value after calibration\n\t\tint32_t                logicalCalibratedMinimum;\n\t\t\n\t\t//! Maximum value after calibration\n\t\tint32_t                logicalCalibratedMaximum;\n\n\t\t//! Through calibration defined center value of the axis\n\t\tint32_t                logicalCalibratedCenter;\n\n\t\t//! Physical minimum value\n\t\tint32_t physicalMinimum;\n\n\t\t//! Physical maxiumum value\n\t\tint32_t physicalMaximum;\n\n\t\t//! Name as given by the driver\n\t\tstd::wstring name;\n\t};\n\n\tstruct Button\n\t{\n\t\t//! Usage page as defined in the standard (e.g. \"buttons (0009)\")\n\t\tUSAGE usagePage;\n\n\t\t//! Usage of the axis as defined in the standard (e.g. \"secondary (0002)\")\n\t\tUSAGE usage;\n\n\t\t//! Index as defined through Hidp_GetData()\n\t\tUSHORT index;\n\n\t\t//! Name as given by the driver\n\t\tstd::wstring name;\n\t};\n\t\n\t//! Normalize the axix value using the device configuration data\n\tinline float normalizeAxis(ULONG value, const Axis& axis)\n\t{\n\t\tif (static_cast<LONG>(value) < axis.logicalCalibratedCenter)\n\t\t{\n\t\t\tfloat range = static_cast<float>(axis.logicalCalibratedCenter - axis.logicalCalibratedMinimum);\n\t\t\treturn (static_cast<LONG>(value) - axis.logicalCalibratedCenter) / range;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfloat range = static_cast<float>(axis.logicalCalibratedMaximum - axis.logicalCalibratedCenter);\n\t\t\treturn (static_cast<LONG>(value) - axis.logicalCalibratedCenter) / range;\n\t\t}\n\t}\n\n\tclass GenericHID\n\t{\n\tpublic:\n\t\tGenericHID(HANDLE raw_handle);\n\t\t\n\t\t//! Access the raw-input API handle\n\t\t//! \\returns The input device handle\n\t\tHANDLE rawHandle() const { return _rawInputHandle; }\n\n\t\t//! Access the windows internal handle\n\t\t//! \\returns The file handle to the device\n\t\tHANDLE fileHandle() const { return _fileHandle; }\n\n\t\t//! Access the vendor ID\n\t\t//! \\returns The vendor ID\n\t\tDWORD vendorId() const { return _vendorId; }\n\n\t\t//! Access the product ID\n\t\t//! \\returns The product ID\n\t\tDWORD productId() const { return _productId; }\n\n\t\t//! Read the device name from the hardware\n\t\t//! \\returns The vendor defined names (vendor, product)\n\t\tauto readDeviceName() const -> std::pair<std::wstring, std::wstring>;\n\n\t\tconst std::vector<Axis>& axes() const { return _axes; }\n\t\tconst std::vector<Button>& buttons() const { return _buttons; }\n\n\t\tconst std::vector<HIDP_VALUE_CAPS>& axisCaps() const { return _axesCaps; }\n\t\tconst std::vector<HIDP_BUTTON_CAPS>& buttonCaps() const { return _buttonCaps; }\n\n\tprivate:\t\t\n\t\t//! Read the device capabilities\n\t\tauto readDeviceCaps() const -> std::tuple<std::vector<HIDP_BUTTON_CAPS>, std::vector<HIDP_VALUE_CAPS>>;\n\n\t\t//! Map buttons and fetch calibration data\n\t\t//! \\param mapping Direct Input related remapping of buttons\n\t\tvoid readButtonCalibration(gsl::span<struct DirectInputButtonMapping> mapping) const;\n\n\t\t//! Map axes and fetch calibration data\n\t\t//! \\param axes_caps\n\t\tvoid readAxisCalibration(const std::vector<HIDP_VALUE_CAPS>& axes_caps, gsl::span<struct DirectInputAxisMapping> mapping) const;\n\n\t\t//! Convert and store the button caps\n\t\t//! \\param button_caps\n\t\t//! \\param mapping Direct Input related remapping of buttons\n\t\tvoid storeButtons(std::vector<HIDP_BUTTON_CAPS>&& button_caps, gsl::span<struct DirectInputButtonMapping> mapping);\n\n\t\t//! Convert and store the axes caps\n\t\t//! \\param axes_caps\n\t\tvoid storeAxes(std::vector<HIDP_VALUE_CAPS>&& axes_caps, gsl::span<struct DirectInputAxisMapping> mapping);\n\n\tprivate:\n\t\t//! Handle provided by the raw input API\n\t\tHANDLE _rawInputHandle{ nullptr };\n\n\t\t//! Handle from the file API\n\t\tHANDLE _fileHandle{ nullptr };\n\n\t\t//! Vendor ID\n\t\tDWORD _vendorId;\n\n\t\t//! Product ID\n\t\tDWORD _productId;\n\n\t\t//! Buttons associated with the device\n\t\tstd::vector<Button> _buttons;\n\n\t\t//! Axes associated with the device\n\t\tstd::vector<Axis> _axes;\n\n\t\t//! HID button representation\n\t\tstd::vector<HIDP_BUTTON_CAPS> _buttonCaps;\n\n\t\t//! HID axis representation\n\t\tstd::vector<HIDP_VALUE_CAPS> _axesCaps;\n\t};\n\t\n\tclass AbstractHID\n\t{\n\tpublic:\n\t\tAbstractHID(std::unique_ptr<GenericHID> device) : _device{ std::move(device) } {}\n\n\t\tconst GenericHID* device() const { return _device.get(); }\n\n\t\tvirtual bool processInput(HWND window_handle, UINT input_code, PRAWINPUT raw_input) = 0;\n\n\tprivate:\n\t\t//! Actual hardware device implementation\n\t\tstd::unique_ptr<GenericHID> _device;\n\t};\n\n\ttemplate<typename JoystickType>\n\tclass JoystickHID : public AbstractHID, public JoystickType\n\t{\n\tpublic:\n\t\tJoystickHID(std::unique_ptr<GenericHID> device);\n\n\t\tbool processInput(HWND window_handle, UINT input_code, PRAWINPUT raw_input) override;\n\t};\n\n\ttemplate<typename GamepadType>\n\tclass GamepadHID : public AbstractHID, public GamepadType\n\t{\n\tpublic:\n\t\tGamepadHID(std::unique_ptr<GenericHID> device);\n\n\t\tbool processInput(HWND window_handle, UINT input_code, PRAWINPUT raw_input) override;\n\t};\n\t\n\ttemplate<typename ControllerType>\n\tclass MultiAxisControllerHID : public AbstractHID, public ControllerType\n\t{\n\tpublic:\n\t\tMultiAxisControllerHID(std::unique_ptr<GenericHID> device);\n\n\t\tbool processInput(HWND window_handle, UINT input_code, PRAWINPUT raw_input) override;\n\t};\n\n\tclass DeviceManager\n\t{\n\tpublic:\n\t\tDeviceManager();\n\t\n\t\tgsl::span<Device const* const> devices() const;\n\t\t\n\t\t//! Register devices with a specific window\n\t\t//! \\param device_types Types of devices for which input should\n\t\t//!                     be processed.\n\t\t//! \\param window_handle Handle to the window to which devices should be\n\t\t//!                      registered.\n\t\tvoid registerDevices(Flags<DeviceType> device_types, HWND window_handle);\n\t\t\n\t\t//! Polls all the devices instead of processing only a single device\n\t\t//! \\param window_handle Handle of the window calling this method\n\t\t//! \\returns True, if any device was successfully polled.\n\t\t//! \\note This method is implemented according to the documenation\n\t\t//!       on MSDN. However, it seems not possible to call it.\n\t\tbool poll(HWND window_handle, UINT input_code);\n\n\t\t//! Process the input of a specific device\n\t\tbool processInput(HWND window_handle, UINT message, WPARAM wide_param, LPARAM low_param);\n\n\tprivate:\n\t\t//! List of Windows HID\n\t\tstd::vector<std::unique_ptr<AbstractHID>> _devices;\n\n\t\t//! List of device pointers (links to `_devices`)\n\t\tstd::vector<Device*> _deviceLinks;\n\t};\n}}}\n", "meta": {"hexsha": "64aa8d92126a8301f130eba6271f238432826b00", "size": 8580, "ext": "h", "lang": "C", "max_stars_repo_path": "src/vcl/hid/windows/hid.h", "max_stars_repo_name": "bfierz/vcl.hid", "max_stars_repo_head_hexsha": "4193fe488d6759306e297b225e3a3c4da58716b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-26T20:39:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-26T20:39:34.000Z", "max_issues_repo_path": "src/vcl/hid/windows/hid.h", "max_issues_repo_name": "bfierz/vcl.hid", "max_issues_repo_head_hexsha": "4193fe488d6759306e297b225e3a3c4da58716b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/vcl/hid/windows/hid.h", "max_forks_repo_name": "bfierz/vcl.hid", "max_forks_repo_head_hexsha": "4193fe488d6759306e297b225e3a3c4da58716b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2, "max_line_length": 130, "alphanum_fraction": 0.7212121212, "num_tokens": 2165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.13660838651113866, "lm_q2_score": 0.03732688935207538, "lm_q1q2_score": 0.005099166127866819}}
{"text": "#pragma once\n\n#include <vector>\n\n#include <gsl/span>\n\n#include \"Mouse.h\"\n#include \"Joystick.h\"\n#include \"JoystickButton.h\"\n#include \"Keyboard.h\"\n#include \"RawInput.h\"\n#include \"Xbox360Controller.h\"\n\nnamespace qvr\n{\n\nclass JoystickAxisThreshold\n{\npublic:\n\tJoystickAxisThreshold(\n\t\tconst qvr::JoystickAxis axis,\n\t\tconst float threshold,\n\t\tconst bool trueAboveThreshold)\n\t\t: mJoystickAxis(axis)\n\t\t, mThreshold(threshold)\n\t\t, mTrueAboveThreshold(trueAboveThreshold)\n\t{}\n\tJoystickAxisThreshold(\n\t\tconst Xbox360Controller::Axis axis,\n\t\tconst float threshold,\n\t\tconst bool trueAboveThreshold)\n\t\t: JoystickAxisThreshold(\n\t\t\tXbox360Controller::ToJoystickAxis(axis),\n\t\t\tthreshold,\n\t\t\ttrueAboveThreshold)\n\t{\n\t}\n\tbool IsActive(const qvr::Joystick& joystick) const\n\t{\n\t\tconst float v = joystick.GetPosition(mJoystickAxis);\n\t\tif (mTrueAboveThreshold)\n\t\t{\n\t\t\treturn v > mThreshold;\n\t\t}\n\t\treturn v < mThreshold;\n\t}\n\tbool JustActive(const qvr::Joystick& joystick) const\n\t{\n\t\tconst float current  = joystick.GetPosition(mJoystickAxis);\n\t\tconst float previous = joystick.GetPreviousPosition(mJoystickAxis);\n\t\tif (mTrueAboveThreshold)\n\t\t{\n\t\t\treturn current > mThreshold && previous < mThreshold;\n\t\t}\n\t\treturn current < mThreshold && previous > mThreshold;\n\t}\nprivate:\n\tconst qvr::JoystickAxis mJoystickAxis;\n\tconst float mThreshold;\n\tconst bool mTrueAboveThreshold;\n};\n\n}\n\nclass BinaryInput\n{\npublic:\n\tenum class Type\n\t{\n\t\tKeyboardKey,\n\t\tMouseButton,\n\t\tJoystickButton,\n\t\tJoystickAxisThreshold\n\t};\n\n\tBinaryInput(qvr::KeyboardKey key)\n\t\t: mType(Type::KeyboardKey)\n\t\t, mKeyboardKey(key)\n\t{}\n\n\tBinaryInput(qvr::MouseButton mouseButton)\n\t\t: mType(Type::MouseButton)\n\t\t, mMouseButton(mouseButton)\n\t{}\n\n\tBinaryInput(qvr::JoystickButton joystickButton)\n\t\t: mType(Type::JoystickButton)\n\t\t, mJoystickButton(joystickButton)\n\t{}\n\n\tBinaryInput(qvr::JoystickAxisThreshold joystickAxisThreshold)\n\t\t: mType(Type::JoystickAxisThreshold)\n\t\t, mJoystickAxisThreshold(joystickAxisThreshold)\n\t{}\n\n\tbool IsActive(const qvr::RawInputDevices& devices) const\n\t{\n\t\tconst auto joystickIndex = qvr::JoystickIndex(0);\n\t\tconst qvr::Joystick* joystick = devices.GetJoysticks().GetJoystick(joystickIndex);\n\n\t\tswitch (mType)\n\t\t{\n\t\tcase Type::KeyboardKey:\n\t\t\treturn devices.GetKeyboard().IsDown(mKeyboardKey);\n\t\tcase Type::MouseButton:\n\t\t\treturn devices.GetMouse().IsDown(mMouseButton);\n\t\t// TODO: Which joysticks?\n\t\tcase Type::JoystickButton:\n\t\t\tif (joystick) {\n\t\t\t\treturn joystick->IsDown(mJoystickButton);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase Type::JoystickAxisThreshold:\n\t\t\tif (joystick) {\n\t\t\t\treturn mJoystickAxisThreshold.IsActive(*joystick);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\treturn false;\n\t}\n\n\tbool JustActive(const qvr::RawInputDevices& devices) const\n\t{\n\t\tconst auto joystickIndex = qvr::JoystickIndex(0);\n\t\tconst qvr::Joystick* joystick = devices.GetJoysticks().GetJoystick(joystickIndex);\n\n\t\tswitch (mType)\n\t\t{\n\t\tcase Type::KeyboardKey:\n\t\t\treturn devices.GetKeyboard().JustDown(mKeyboardKey);\n\t\tcase Type::MouseButton:\n\t\t\treturn devices.GetMouse().JustDown(mMouseButton);\n\t\t\t// TODO: Which joysticks?\n\t\tcase Type::JoystickButton:\n\t\t\tif (joystick) {\n\t\t\t\treturn joystick->JustDown(mJoystickButton);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase Type::JoystickAxisThreshold:\n\t\t\tif (joystick) {\n\t\t\t\treturn mJoystickAxisThreshold.JustActive(*joystick);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\treturn false;\n\t}\n\nprivate:\n\tconst Type mType;\n\n\tunion\n\t{\n\t\tconst qvr::KeyboardKey mKeyboardKey;\n\t\tconst qvr::MouseButton mMouseButton;\n\t\tconst qvr::JoystickButton mJoystickButton;\n\t\tconst qvr::JoystickAxisThreshold mJoystickAxisThreshold;\n\t};\n};\n\ninline bool AnyActive(const qvr::RawInputDevices& devices, const gsl::span<const BinaryInput> inputs) {\n\tfor (const BinaryInput input : inputs) {\n\t\tif (input.IsActive(devices)) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\ninline bool AnyJustActive(const qvr::RawInputDevices& devices, const gsl::span<const BinaryInput> inputs) {\n\tfor (const BinaryInput input : inputs) {\n\t\tif (input.JustActive(devices)) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}", "meta": {"hexsha": "0b48cdba36166935ae972cae2ec8d7839d9e4611", "size": 3967, "ext": "h", "lang": "C", "max_stars_repo_path": "External/Quiver/Source/Quiver/Quiver/Input/BinaryInput.h", "max_stars_repo_name": "rachelnertia/Quarrel", "max_stars_repo_head_hexsha": "69616179fc71305757549c7fcaccc22707a91ba4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 39.0, "max_stars_repo_stars_event_min_datetime": "2017-10-22T15:47:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-31T22:19:55.000Z", "max_issues_repo_path": "External/Quiver/Source/Quiver/Quiver/Input/BinaryInput.h", "max_issues_repo_name": "rachelnertia/Quarrel", "max_issues_repo_head_hexsha": "69616179fc71305757549c7fcaccc22707a91ba4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2017-10-26T21:21:51.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-13T14:46:17.000Z", "max_forks_repo_path": "Source/Quiver/Quiver/Input/BinaryInput.h", "max_forks_repo_name": "rachelnertia/Quiver", "max_forks_repo_head_hexsha": "c8ef9591117bdfc8d6fa509ae53451e0807f5686", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-10-22T14:47:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-19T10:08:45.000Z", "avg_line_length": 22.2865168539, "max_line_length": 107, "alphanum_fraction": 0.7355684396, "num_tokens": 1072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18476749269168688, "lm_q2_score": 0.02758528412543028, "lm_q1q2_score": 0.005096863783043545}}
{"text": "/*\n#\n# Copyright (c) 2006-2012      University of Houston. All rights reserved.\n# $COPYRIGHT$\n#\n# Additional copyrights may follow\n#\n# $HEADER$\n#\n*/\n\n#ifndef __SL_INTERNAL__\n#define __SL_INTERNAL__\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <sys/types.h>\n//#include <gsl/gsl_fit.h>\n#include <sys/time.h>\n#include <time.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <math.h>\n#include <errno.h>\n//#include <papi.h>\n#ifdef MINGW\n#include <windows.h>\n#include <winsock2.h>\n#include <ws2tcpip.h>\n#else\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netinet/tcp.h>\n#include <arpa/inet.h>\n#include <netdb.h>\n#include <sys/wait.h>\n#include <sys/resource.h>\n#include <pwd.h>\n#include <sys/utsname.h>\n#endif\n\n\n#include \"SL_array.h\"\n\nextern fd_set SL_send_fdset;\nextern fd_set SL_recv_fdset;\n\nextern int SL_this_procid;\nextern int SL_this_procport;\nextern int SL_this_listensock;\nextern int SL_numprocs;\nextern int SL_init_numprocs;\nextern int SL_proxy_numprocs;\n/* Message header send before any message */\nstruct SL_msg_header {\n    int      cmd; /* what type of message is this */\n    int     from; /* id of the src process */\n    int       to; /* id of the dest. process */\n    int      tag; /* tag of the message */\n    int  context; /* context id */\n    int      len; /* Message length in bytes */\n    int       id; /* Id of the last fragment */\n    int loglength;\n    int     temp;\n};\ntypedef struct SL_msg_header SL_msg_header;\n\n\n/* Process structure containing all relevant contact information,\n   communication status etc. */\nstruct SL_proc;\ntypedef int SL_msg_comm_fnct ( struct SL_proc *dproc, int fd );\n\nstruct SL_proc {\n    int                         id;\n    char                 *hostname;\n    int                       port;\n    int                       sock;\n    int                      state;\n    int           connect_attempts; /* number of connect attempts */\n    double    connect_start_tstamp; /* time stamp when we started to accept or connect\n\t\t\t\t       for this proc */\n    double                 timeout; /* max time a process should wait before disconnecting */\n\n    struct SL_msgq_head    *squeue; /* Send queue */\n    struct SL_msgq_head    *rqueue; /* Recv queue */\n    struct SL_msgq_head   *urqueue; /* Unexpected msgs queue */\n    struct SL_msgq_head   *scqueue; /* Send complete queue */\n    struct SL_msgq_head   *rcqueue; /* Recv complete queue */\n    struct SL_qitem   *currecvelem;\n    struct SL_qitem   *cursendelem;\n    SL_msg_comm_fnct     *recvfunc;\n    SL_msg_comm_fnct     *sendfunc;\n    struct SL_msg_perf    *msgperf; /*to keep track of time and msglenth for each communication */\n    struct SL_msg_perf   *insertpt;\n    struct SL_network_perf *netperf;\n};\n\nstruct SL_msg_perf {\n\tstruct SL_msg_perf  *fwd;\n\tstruct SL_msg_perf  *back;\n\tint \t\t   msglen;\n\tdouble\t\t     time;\n\tint \t\t      pos;\n\tint \t\t  msgtype; /*send type(0) or recieve type(1)*/\n\tint \t\t   elemid;\n        struct SL_proc      *proc;\n};\ntypedef struct SL_msg_perf SL_msg_perf;\n\nstruct SL_network_perf {\n\tstruct SL_network_perf\t *fwd;\n\tstruct SL_network_perf\t*back;\n\tdouble \t              latency;\n\tdouble \t\t    bandwidth;\n\tint \t\t\t  pos;\n\n};\ntypedef struct SL_network_perf SL_network_perf;\n\ntypedef struct SL_proc SL_proc;\n\n\n#ifdef MINGW\nstruct iovec {\n\tchar\t*iov_base;\t/* Base address. */\n\tsize_t\t iov_len;\t/* Length. */\n};\n\n#define\tTCP_MAXSEG\t\t0x02\t/* set maximum segment size */\n#define \tF_GETFL\t\t3\t/* get file->f_flags */\n#define \tF_SETFL\t\t4\t/* set file->f_flags */\n#define \tO_NONBLOCK\t \t00004\n#endif\n\n/* A  message queue item containing the operation\n   it decsribes */\nstruct SL_msgq_head;\nstruct SL_qitem {\n    int                       id;\n    int                   iovpos;\n    int                   lenpos;\n    int                    error;\n    struct iovec          iov[2];\n    struct SL_msgq_head *move_to;\n    struct SL_msgq_head    *head;\n    struct SL_qitem        *next;\n    struct SL_qitem        *prev;\n    double             starttime;\n    double               endtime;\n};\ntypedef struct SL_qitem SL_qitem;\n\n/* A message queue */\nstruct SL_msgq_head {\n    int               count;\n    char              *name;\n    struct SL_qitem  *first;\n    struct SL_qitem   *last;\n};\ntypedef struct SL_msgq_head SL_msgq_head;\n\n/* Request object identifying an ongoing communication */\nstruct SL_msg_request {\n    struct SL_proc        *proc;\n    int                    type; /* Send or Recv */\n    int                      id;\n    struct SL_qitem       *elem;\n    struct SL_msgq_head *cqueue; /* completion queue to look for */\n};\ntypedef struct SL_msg_request SL_msg_request;\n\n\nstruct SL_msgq_head     *SL_event_sendq;\nstruct SL_msgq_head     *SL_event_recvq;\nstruct SL_msgq_head     *SL_event_sendcq;\n\n\n/* MACROS */\n/*#ifdef PRINTF\n  #undef PRINTF\n  #define PRINTF(A) printf A \n#else\n  #define PRINTF(A)\n#endif*/\n\n#define FALSE 0\n#define TRUE  1\n\n#define SEND 0\n#define RECV 1\n\n#define SL_RECONN_MAX      20\n#define SL_ACCEPT_MAX_TIME 10 \n#define SL_READ_MAX_TIME   5 \n#define SL_ACCEPT_INFINITE_TIME -1\n#define SL_BIND_PORTSHIFT 200\n#define SL_SLEEP_TIME       1\n#define SL_TCP_BUFFER_SIZE  262142\n#define SL_MAX_EVENT_HANDLE     1\n#define SL_CONSTANT_ID          -32\n#define SL_EVENT_MANAGER        -1\n#define SL_PROXY_SERVER\t\t-2\n#define PERFBUFSIZE\t20\n#define MTU\t\t(1024L*4L)\t\n#define SL_PROC_ID\t-64\n\nint SL_socket ( void );\nint SL_bind_static ( int handle, int port );\nint SL_bind_dynamic (  int handle, int port );\nint SL_socket_close ( int handle );\nint SL_open_socket_conn ( int *handle, const char *as_host, int port );\nint SL_open_socket_bind ( int *handle, int port );\nint SL_open_socket_listen ( int sock );\nint SL_open_socket_listen_nb ( int *handle, int port );\nint SL_open_socket_conn_nb ( int *handle, const char *as_host, int port );\nint SL_socket_read ( int hdl, char *buf, int num, double timeout );\nint SL_socket_write ( int hdl, char *buf, int num, double timeout );\nint SL_socket_write_nb ( int hdl, char *buf, int num, int *numwritten );\n\nint SL_socket_read_nb ( int hdl, char *buf, int num, int* numread );\n\nvoid SL_print_socket_options ( int fd );\nvoid SL_configure_socket ( int sd );\nvoid SL_configure_socket_nb ( int sd );\nint SL_init_internal();\ndouble SL_papi_time();\n\n/* status object t.b.d */\n\n#endif /* __SL_INTERNALL__ */\n\n", "meta": {"hexsha": "674a20c2298a53c6b933b0eb97265cc39b14291b", "size": 6304, "ext": "h", "lang": "C", "max_stars_repo_path": "include/SL_internal.h", "max_stars_repo_name": "edgargabriel/VolpexMPI", "max_stars_repo_head_hexsha": "3289231c0feb6e48fbcff13af8795640d1ce1fb8", "max_stars_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/SL_internal.h", "max_issues_repo_name": "edgargabriel/VolpexMPI", "max_issues_repo_head_hexsha": "3289231c0feb6e48fbcff13af8795640d1ce1fb8", "max_issues_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/SL_internal.h", "max_forks_repo_name": "edgargabriel/VolpexMPI", "max_forks_repo_head_hexsha": "3289231c0feb6e48fbcff13af8795640d1ce1fb8", "max_forks_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9401709402, "max_line_length": 98, "alphanum_fraction": 0.6594225888, "num_tokens": 1610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21469140906295778, "lm_q2_score": 0.023689469834661987, "lm_q1q2_score": 0.005085925658758015}}
{"text": "//\n// Created by ZL on 2019-06-13.\n//\n\n#ifndef ZQCNNDEMO_ZQCNN_MTCNN_NCHWC4_H\n#define ZQCNNDEMO_ZQCNN_MTCNN_NCHWC4_H\n\n#include \"ZQ_CNN_Net_NCHWC.h\"\n#include \"ZQ_CNN_MTCNN_NCHWC.h\"\n#include <vector>\n#include <iostream>\n#include \"opencv2/opencv.hpp\"\n#include \"ZQ_CNN_CompileConfig.h\"\n#include <cblas.h>\n\nclass MTCNNNCHWC {\npublic:\n    MTCNNNCHWC(const std::string &model_path);\n\n    std::vector<ZQ::ZQ_CNN_BBox> detect(const std::string &img_path);\n\n\n    std::vector<ZQ::ZQ_CNN_BBox> detectMat(cv::Mat &image0);\n\nprivate:\n    ZQ::ZQ_CNN_MTCNN_NCHWC *mtcnn;\n    int thread_num = 1;\n};\n\n#endif //ZQCNNDEMO_ZQCNN_MTCNN_NCHWC4_H\n", "meta": {"hexsha": "a06ebf088dc9bbf85755e1c91039a91ab47d53b1", "size": 623, "ext": "h", "lang": "C", "max_stars_repo_path": "app/src/main/cpp/zqcnn_mtcnn_nchwc4.h", "max_stars_repo_name": "zhu260824/ZQCNN_Android", "max_stars_repo_head_hexsha": "337fab2b58f14d118b59072d9469646cdba43d57", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-06-18T14:38:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-14T07:23:08.000Z", "max_issues_repo_path": "app/src/main/cpp/zqcnn_mtcnn_nchwc4.h", "max_issues_repo_name": "zhu260824/ZQCNN_Android", "max_issues_repo_head_hexsha": "337fab2b58f14d118b59072d9469646cdba43d57", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-06-26T09:10:21.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-26T09:10:21.000Z", "max_forks_repo_path": "app/src/main/cpp/zqcnn_mtcnn_nchwc4.h", "max_forks_repo_name": "zhu260824/ZQCNN_Android", "max_forks_repo_head_hexsha": "337fab2b58f14d118b59072d9469646cdba43d57", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-06-27T00:49:48.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-17T02:21:50.000Z", "avg_line_length": 20.0967741935, "max_line_length": 69, "alphanum_fraction": 0.7431781701, "num_tokens": 234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.26588047309981694, "lm_q2_score": 0.0191240373798102, "lm_q1q2_score": 0.00508470810612252}}
{"text": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n#pragma once\n\n#include \"arcana/finally_scope.h\"\n#include \"arcana/functional/inplace_function.h\"\n#include \"arcana/utils/algorithm.h\"\n#include \"sorted_vector.h\"\n\n#include <gsl/gsl>\n#include <iterator>\n#include <map>\n#include <mutex>\n#include <stdint.h>\n\nnamespace mira\n{\n    /*\n        A collection that mimics a coat check. You insert something into it and it gives you a ticket.\n        Once you're done with the ticket, your item gets removed from the collection.\n    */\n    template<typename T, typename MutexT = std::mutex>\n    class ticketed_collection\n    {\n        using seed_t = int64_t;\n\n        struct compare\n        {\n            bool operator()(const std::pair<seed_t, T>& left, const std::pair<seed_t, T>& right) const\n            {\n                return left.first < right.first;\n            }\n\n            bool operator()(const std::pair<seed_t, T>& left, const seed_t& right) const\n            {\n                return left.first < right;\n            }\n        };\n\n        using storage_t = sorted_vector<std::pair<seed_t, T>, compare>;\n\n        struct ticket_functor\n        {\n            ticket_functor(seed_t id, MutexT& mutex, storage_t& items)\n                : m_id{ id }\n                , m_mutex{ mutex }\n                , m_items{ items }\n            {}\n\n            void operator()()\n            {\n                std::lock_guard<MutexT> guard{ m_mutex };\n\n                auto found = m_items.find(\n                    m_id, [](const std::pair<seed_t, T>& left, const seed_t& right) { return left.first == right; });\n\n                assert(found != m_items.end() && \"ticketed item wasn't found in the collection\");\n\n                m_items.erase(found);\n            }\n\n            seed_t m_id;\n            MutexT& m_mutex;\n            storage_t& m_items;\n        };\n\n    public:\n        struct iterator\n        {\n            using iter_t = typename storage_t::const_iterator;\n\n            using difference_type = typename std::iterator_traits<iter_t>::difference_type;\n            using value_type = T;\n            using pointer = const value_type*;\n            using reference = const value_type&;\n            using iterator_category = std::input_iterator_tag;\n\n            explicit iterator(const iter_t& itr)\n                : m_iter{ itr }\n            {}\n\n            bool operator==(const iterator& other) const\n            {\n                return m_iter == other.m_iter;\n            }\n\n            bool operator!=(const iterator& other) const\n            {\n                return !(*this == other);\n            }\n\n            iterator& operator++()\n            {\n                ++m_iter;\n                return *this;\n            }\n\n            iterator operator++(int)\n            {\n                iterator pre{ *this };\n                ++m_iter;\n                return pre;\n            }\n\n            const T* operator->() const\n            {\n                return &m_iter->second;\n            }\n\n            const T& operator*() const\n            {\n                return m_iter->second;\n            }\n\n        private:\n            typename storage_t::const_iterator m_iter;\n        };\n\n        using ticket = gsl::final_action<\n            stdext::inplace_function<void(), sizeof(ticket_functor), alignof(ticket_functor)>>;\n\n        using ticket_scope = finally_scope<ticket>;\n\n        ticketed_collection() = default;\n        ticketed_collection(const ticketed_collection&) = delete;\n        ticketed_collection& operator=(const ticketed_collection&) = delete;\n\n        iterator begin() const\n        {\n            return iterator{ m_items.cbegin() };\n        }\n\n        iterator end() const\n        {\n            return iterator{ m_items.cend() };\n        }\n\n        auto size() const\n        {\n            return m_items.size();\n        }\n\n        auto empty() const\n        {\n            return m_items.empty();\n        }\n\n        //\n        // Inserts an element into the collection and returns a ticket\n        // that will remove the item on its destruction. The mutex passed\n        // in should be already locked when calling this method. That same\n        // mutex will get locked when removing the item from the collection.\n        //\n        template<typename ElementT>\n        ticket insert(ElementT&& element, MutexT& mutex)\n        {\n            seed_t id = m_seed++;\n            m_items.insert(std::pair<seed_t, T>{ id, std::forward<ElementT>(element) });\n\n            return ticket{ ticket_functor(id, mutex, m_items) };\n        }\n\n    private:\n        seed_t m_seed = 0;\n        storage_t m_items;\n    };\n}\n", "meta": {"hexsha": "6c073dce783132295ee2d8a77e1a060068bb0e52", "size": 4644, "ext": "h", "lang": "C", "max_stars_repo_path": "Dependencies/Arcana/Shared/arcana/containers/ticketed_collection.h", "max_stars_repo_name": "syntheticmagus/mageslam", "max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z", "max_issues_repo_path": "Dependencies/Arcana/Shared/arcana/containers/ticketed_collection.h", "max_issues_repo_name": "syntheticmagus/mageslam", "max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z", "max_forks_repo_path": "Dependencies/Arcana/Shared/arcana/containers/ticketed_collection.h", "max_forks_repo_name": "syntheticmagus/mageslam", "max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z", "avg_line_length": 27.4792899408, "max_line_length": 117, "alphanum_fraction": 0.5279931094, "num_tokens": 958, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21733751090819792, "lm_q2_score": 0.02333076651655539, "lm_q1q2_score": 0.005070650722288476}}
{"text": "#ifndef _EM_UTILS_H_\n#define _EM_UTILS_H_ 1\n\n#include <petsc.h>\n\n#include <string>\n\nstd::string string_format(const char*, ...);\nstd::string parse_string(const std::string &s);\n\nclass LogEventHelper {\npublic:\n  LogEventHelper(PetscLogEvent ple) : ple_(ple) { PetscLogEventBegin(ple_, 0, 0, 0, 0); }\n  ~LogEventHelper() { PetscLogEventEnd(ple_, 0, 0, 0, 0); }\n\nprivate:\n  PetscLogEvent ple_;\n};\n\nclass LogStageHelper {\npublic:\n  LogStageHelper(const std::string &name) {\n    PetscLogStage pls;\n    PetscLogStageRegister(name.c_str(), &pls);\n    PetscLogStagePush(pls);\n  }\n  ~LogStageHelper() { PetscLogStagePop(); }\n};\n\n#endif\n", "meta": {"hexsha": "f529949e86bc5aec6d11c424dca07fd9efd227f7", "size": 627, "ext": "h", "lang": "C", "max_stars_repo_path": "src/em_utils.h", "max_stars_repo_name": "emfem/emfem", "max_stars_repo_head_hexsha": "9129e28610d7fcb83a88021528575dfeaadad502", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-03T12:22:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-03T12:22:37.000Z", "max_issues_repo_path": "src/em_utils.h", "max_issues_repo_name": "emfem/emfem", "max_issues_repo_head_hexsha": "9129e28610d7fcb83a88021528575dfeaadad502", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/em_utils.h", "max_forks_repo_name": "emfem/emfem", "max_forks_repo_head_hexsha": "9129e28610d7fcb83a88021528575dfeaadad502", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.2258064516, "max_line_length": 89, "alphanum_fraction": 0.7033492823, "num_tokens": 190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10521053950871515, "lm_q2_score": 0.04813677333562299, "lm_q1q2_score": 0.005064495892849628}}
{"text": "// Implementation of interface described in float_blob.h.\n\n#include <errno.h>\n#include <fcntl.h>\n#include <string.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <unistd.h>\n\n#include <glib.h>\n#include <glib/gstdio.h>\n\n#include <gsl/gsl_math.h>\n\n#include \"float_blob.h\"\n#include \"float_image.h\"\n#include \"utilities.h\"\n\nFloatBlob *\nfloat_blob_new (gssize size_x, gssize size_y, const char *scratch_dir,\n\t\tconst char *name)\n{\n  g_assert (size_x > 0 && size_y > 0);\n  g_assert (g_file_test (scratch_dir, G_FILE_TEST_IS_DIR));\n  g_assert (g_access (scratch_dir, R_OK | W_OK | X_OK) == 0);\n\n  FloatBlob *self = g_new (FloatBlob, 1);\n\n  self->size_x = size_x;\n  self->size_y = size_y;\n\n  self->swapped_bytes = FALSE;\n\n  if ( name != NULL ) {\n    self->file = ensure_slash_terminated (g_string_new (scratch_dir));\n    g_string_append (self->file, name);\n  }\n  else {\n    self->file = make_unique_tmp_file_name (scratch_dir, \"float_blob_tmp_\");\n    g_assert (!g_file_test (self->file->str, G_FILE_TEST_EXISTS));\n  }\n  self->is_file_owner = TRUE;\n\n  self->fd = open (self->file->str, O_RDWR | O_CREAT | O_TRUNC,\n\t\t   S_IRUSR | S_IWUSR);\n  g_assert (self->fd != -1);\n\n  // Out of carefulness we didn't truncate, but we want to make sure\n  // we really got a new file.\n  g_assert (file_size (self->fd) == 0);\n\n  // Seek to last byte of file.\n  off_t last_byte_offset \n    = (off_t) self->size_x * (off_t) self->size_y * sizeof (float) - 1;\n  off_t file_offset = lseek (self->fd, last_byte_offset, SEEK_SET);\n  g_assert (file_offset == last_byte_offset);\n\n  // Write a byte at the end of the file.\n  size_t bytes_to_write = 1;\n  g_assert (sizeof (unsigned char) == 1);\n  unsigned char good_old_zero = 0x0;\n  ssize_t bytes_written = write (self->fd, &good_old_zero, bytes_to_write);\n  g_assert (bytes_written == bytes_to_write);\n\n  // We should now have reserved all the space needed in this file.\n  g_assert (file_size (self->fd) == last_byte_offset + 1);\n\n  self->reference_count = 1;\n\n  return self;\n}\n\nFloatBlob *\nfloat_blob_new_using (gssize size_x, gssize size_y, const char *file,\n\t\t      gboolean swapped_bytes)\n{\n  g_assert (size_x > 0 && size_y > 0);\n  g_assert (g_file_test (file, G_FILE_TEST_IS_REGULAR));\n  g_assert (g_access (file, R_OK | W_OK) == 0);\n\n  FloatBlob *self = g_new (FloatBlob, 1);\n\n  self->fd = open (file, O_RDWR);\n  g_assert (self->fd != -1);\n\n  g_assert (file_size (self->fd) >= (off_t) size_x * size_y * sizeof (float));\n\n  self->size_x = size_x;\n  self->size_y = size_y;\n  \n  self->swapped_bytes = swapped_bytes;\n\n  self->file = g_string_new (file);\n  \n  self->is_file_owner = FALSE;\n\n  self->reference_count = 1;\n\n  return self;\n}\n\nstatic void\nfloat_blob_region_transfer (FloatBlob *self, gssize start_x, gssize start_y,\n\t\t\t    gssize w, gssize h, float *buffer,\n\t\t\t    gboolean is_get_transfer)\n{\n  g_assert (start_x >= 0 && start_x < self->size_x);\n  g_assert (start_y >= 0 && start_y < self->size_y);\n  g_assert (w > 0 && start_x + w <= self->size_x);\n  g_assert (h > 0 && start_y + h <= self->size_y);\n\n  ssize_t (*transfer)(int fd, void *buf, size_t count)\n    = is_get_transfer ? read : ((ssize_t (*)(int, void *, size_t)) write);\n\n  size_t jj;\n  for ( jj = start_y ; jj < start_y + h ; jj++ ) {\n    off_t file_offset \n      = lseek (self->fd,\n\t       sizeof (float) * ((off_t) jj * self->size_x + start_x),\n\t       SEEK_SET);\n    g_assert (file_offset != (off_t) -1);\n    size_t transfer_size = w * sizeof (float);\n    ssize_t transfer_result\n      = transfer (self->fd, buffer + (jj - start_y) * w, transfer_size);\n    if ( transfer_result == -1 ) {\n      g_error (\"I/O error: %s\\n\", strerror (errno));\n    }\n    g_assert (transfer_result == transfer_size);\n  }  \n}\n\nvoid\nfloat_blob_get_region (FloatBlob *self, gssize start_x, gssize start_y,\n\t\t       gssize w, gssize h, float *buffer)\n{\n  float_blob_region_transfer (self, start_x, start_y, w, h, buffer, TRUE);\n\n  if ( self->swapped_bytes ) {\n    swap_array_bytes_32 (buffer, w * h);\n  }\n}\n\nvoid\nfloat_blob_set_region (FloatBlob *self, gssize start_x, gssize start_y,\n\t\t       gssize w, gssize h, float *buffer)\n{\n  if ( self->swapped_bytes ) {\n    swap_array_bytes_32 (buffer, w * h);\n  }\n\n  float_blob_region_transfer (self, start_x, start_y, w, h, buffer, FALSE);\n\n  if ( self->swapped_bytes ) {\n    swap_array_bytes_32 (buffer, w * h);\n  }\n}\n\nGString *\nfloat_blob_steal_file (FloatBlob *self)\n{\n  g_assert (self->is_file_owner == TRUE);\n\n  self->is_file_owner = FALSE;\n\n  return g_string_new (self->file->str);\n\n} \n\nvoid\nfloat_blob_export_as_jpeg (FloatBlob *self, const char *file, double mask)\n{\n  // Self as float image.\n  FloatImage *safi = float_image_new (self->size_x, self->size_y);\n  \n  float *row_buffer = g_new (float, self->size_x);\n\n  // We are about to use swap_32 type function, so we have a quick\n  // attack of paranoia and check sizeof float...\n  g_assert (sizeof (float) == 4);\n\n  // Seek to the beginning of the file.\n  off_t resultant_offset = lseek (self->fd, 0, SEEK_SET);\n  if ( resultant_offset == (off_t) -1 ) {\n    g_error (\"lseek failed: %s\\n\", strerror (errno));\n  }\n  g_assert (resultant_offset == 0);\n\n  size_t ii, jj;\n  for ( jj = 0 ; jj < self->size_y ; jj++ ) {\n\n    // Read one row of data from the file underlying self.\n    ssize_t bytes_to_read = self->size_x * sizeof (float);\n    ssize_t read_count = read (self->fd, row_buffer, bytes_to_read);\n    g_assert (read_count == bytes_to_read);\n\n    // Swap row bytes if necessary.\n    if ( self->swapped_bytes ) {\n      swap_array_bytes_32 (row_buffer, self->size_x);\n    }\n\n    // Write that row to the FloatImage.\n    for ( ii = 0 ; ii < self->size_x ; ii++ ) {\n      float_image_set_pixel (safi, ii, jj, row_buffer[ii]);\n    }\n  }\n\n  g_free (row_buffer);\n\n  float_image_export_as_jpeg (safi, file, GSL_MAX (safi->size_x, safi->size_y),\n\t\t\t      mask);\n\n  float_image_unref (safi);\n}\n\nFloatBlob *\nfloat_blob_ref (FloatBlob *self)\n{\n  g_assert (self->reference_count > 0);\n\n  self->reference_count++;\n\n  return self;\n}\n\nvoid\nfloat_blob_unref (FloatBlob *self)\n{\n  g_assert (self->reference_count > 0);\n  \n  self->reference_count--;\n\n  if ( self->reference_count == 0 ) {\n    int return_code = close (self->fd);\n    g_assert (return_code == 0);\n\n    if ( self->is_file_owner ) {\n      return_code = unlink (self->file->str);\n      if ( return_code != 0 ) {\n\tg_error (\"unlink of float_blob file '%s' in function %s, (file \"\n\t\t __FILE__ \", line %d) failed: %s\", self->file->str, __func__,\n\t\t __LINE__, strerror (errno));\n      }\n      g_assert (return_code == 0);\n    }\n\n    g_string_free (self->file, TRUE);\n\n    g_free (self);\n\n    self = NULL;\n  }\n}\n", "meta": {"hexsha": "97b228bbac84bdad7f7707da57d6db54f554e03a", "size": 6630, "ext": "c", "lang": "C", "max_stars_repo_path": "src/ssv/float_blob.c", "max_stars_repo_name": "glshort/MapReady", "max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z", "max_issues_repo_path": "src/ssv/float_blob.c", "max_issues_repo_name": "glshort/MapReady", "max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ssv/float_blob.c", "max_forks_repo_name": "glshort/MapReady", "max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z", "avg_line_length": 26.2055335968, "max_line_length": 79, "alphanum_fraction": 0.6556561086, "num_tokens": 1973, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.13117322715829127, "lm_q2_score": 0.038466191880538673, "lm_q1q2_score": 0.005045734525460319}}
{"text": "#pragma once\n#include <Manager.h>\n#include <tuple>\n#include <unordered_map>\n#include <unordered_set>\n#include <limits>\n#include <vector>\n#include \"../types/def.h\"\n#include <gsl\\gsl>\n#include \"SFML/Window.hpp\"\n#include <utility>\n#include <../_entity/Entity.h>\n#include <../_entity/EntityManager.h>\n\n#include \"../_component/components/TransformComponent.h\"\n#include \"../_component/components/CollisionComponent.h\"\n\n\nclass ChunkManager : public Manager<ChunkManager> {\npublic:\n    friend class CRSP<ChunkManager>;\n    using ChunkMap = std::unordered_map<Chunk, EntityIdSet, PairIntIntHash>;\n    using EntityMap = std::unordered_map<EntityId, ChunkSet>;\n    using PositionCache = std::unordered_map<EntityId, std::pair<sf::Vector2f, sf::Vector2f>>;\n    using ChunkLengthType = float;\n    using GroupedEntities = std::unordered_map<Chunk, std::set<Entity*>, PairIntIntHash>;\nprivate:\n    ChunkManager();\n    ~ChunkManager();\n\npublic:\n\n    void start_up() override;\n    void shut_down() override;\n\n    std::vector<Chunk> get_relevant_chunks() const;\n\n    ChunkSet get_chunks_of(EntityId id) const;\n\n    ChunkSet calculate_chunks(Entity* entity) const;\n\n    Chunk get_chunk_from_position(float x, float y) const;\n\n    bool share_chunks(EntityId a, EntityId b) const;\n\n    void update_entity_chunks();\n\n    void update_single_entity(Entity* entity);\n\n    void clear();\n\n    /*\n    There are not const because it might require to generate vectors for new chunks without entities\n    */\n    void draw_debug_chunks();\n\n    void draw_debug_chunk_configuration();\n\n    const EntityIdSet& get_entities_of_chunk(Chunk chunk);\n\n    const std::set<Entity*>& get_colliding_entities_of_chunk(Chunk chunk);\n\n\n    /**\n    Returns a vector of vectors with the entities grouped by chunks, that is, in each vector\n    we have all the entities that are in a particular chunk, entities can be repeated in more\n    than one vector.\n    */\n    template<typename... T>\n    GroupedEntities get_grouped_entities_with_components() {\n\n        auto general = GroupedEntities{};\n\n        for (auto & c : m_chunk_map) {\n\n            if (c.second.size() == 0) continue;\n\n            auto& entity_set = c.second;\n\n            auto entities_in_chunk = std::vector<Entity*>{};\n\n            for (auto& e : entity_set) {\n                auto entity = EntityManager::get().get_entity(e);\n\n                if (!entity->is_in_relevant_chunk()) continue;\n\n                auto checks = { entity->has_component<T>()... };\n\n                if (std::all_of(checks.begin(), checks.end(), [](bool i) {return i; })) {\n                    entities_in_chunk.push_back(entity);\n                }\n            }\n\n            general[c.first] = (std::move(entities_in_chunk));\n\n        }\n        return general;\n    }\n\n    /*\n    Specific version of this function for the elements with a collision component\n    that returns an internal member that we calculate on our \"update_entity_chunks\" instead\n    of calculating it on request like we are doing in the function above.\n    */\n    template<>\n    GroupedEntities get_grouped_entities_with_components<TransformComponent, CollisionComponent>() {\n        return m_collision_components_cache;\n    }\n\nprivate:\n\n    /**\n    The length of the side of each square chunk\n    */\n    ChunkLengthType m_chunk_size{ 16 };\n\n    /**\n    Number of chunks outside the visible screen that we still consider relevant\n    */\n    unsigned int m_chunk_threshold{ 1 };\n\n    /**\n    This is used in case an entity enters a chunk exactly in the frame that we have to check\n    something in that new chunk, we register the entity as being in the chunks that it\n    really is plus \"m_safe_threshold\" more in each direction.\n    */\n    unsigned int m_safe_threshold{ 1 };\n\n\n    ChunkMap m_chunk_map{};\n    EntityMap m_entity_map{};\n    PositionCache m_location_cache{};\n\n\n    Chunk m_min_relevant_chunk{};\n    Chunk m_max_relevant_chunk{};\n\n    GroupedEntities m_collision_components_cache{};\n\n    sf::Vector2f camera_previous_center{ std::numeric_limits<float>::infinity(),std::numeric_limits<float>::infinity() };\n    sf::Vector2f camera_previous_size{ std::numeric_limits<float>::infinity(),std::numeric_limits<float>::infinity() };\n    bool m_camera_changed{ true };\n\n};", "meta": {"hexsha": "1914165587b970072bb2d6f88f9740267072f517", "size": 4241, "ext": "h", "lang": "C", "max_stars_repo_path": "NGene/src/physics/ChunkManager.h", "max_stars_repo_name": "osor-io/NGene", "max_stars_repo_head_hexsha": "c28887f233d3485b9e95fa3882a0333e4180c655", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-05-14T14:57:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T04:00:41.000Z", "max_issues_repo_path": "NGene/src/physics/ChunkManager.h", "max_issues_repo_name": "osor-io/NGene", "max_issues_repo_head_hexsha": "c28887f233d3485b9e95fa3882a0333e4180c655", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NGene/src/physics/ChunkManager.h", "max_forks_repo_name": "osor-io/NGene", "max_forks_repo_head_hexsha": "c28887f233d3485b9e95fa3882a0333e4180c655", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-03-07T12:53:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-14T14:57:31.000Z", "avg_line_length": 29.4513888889, "max_line_length": 121, "alphanum_fraction": 0.68309361, "num_tokens": 935, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.28457600421652673, "lm_q2_score": 0.01771230142563056, "lm_q1q2_score": 0.005040495965184634}}
{"text": "/* block/gsl_block_uint.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_BLOCK_UINT_H__\n#define __GSL_BLOCK_UINT_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_errno.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\nstruct gsl_block_uint_struct\n{\n  size_t size;\n  unsigned int *data;\n};\n\ntypedef struct gsl_block_uint_struct gsl_block_uint;\n\ngsl_block_uint *gsl_block_uint_alloc (const size_t n);\ngsl_block_uint *gsl_block_uint_calloc (const size_t n);\nvoid gsl_block_uint_free (gsl_block_uint * b);\n\nint gsl_block_uint_fread (FILE * stream, gsl_block_uint * b);\nint gsl_block_uint_fwrite (FILE * stream, const gsl_block_uint * b);\nint gsl_block_uint_fscanf (FILE * stream, gsl_block_uint * b);\nint gsl_block_uint_fprintf (FILE * stream, const gsl_block_uint * b, const char *format);\n\nint gsl_block_uint_raw_fread (FILE * stream, unsigned int * b, const size_t n, const size_t stride);\nint gsl_block_uint_raw_fwrite (FILE * stream, const unsigned int * b, const size_t n, const size_t stride);\nint gsl_block_uint_raw_fscanf (FILE * stream, unsigned int * b, const size_t n, const size_t stride);\nint gsl_block_uint_raw_fprintf (FILE * stream, const unsigned int * b, const size_t n, const size_t stride, const char *format);\n\nsize_t gsl_block_uint_size (const gsl_block_uint * b);\nunsigned int * gsl_block_uint_data (const gsl_block_uint * b);\n\n__END_DECLS\n\n#endif /* __GSL_BLOCK_UINT_H__ */\n", "meta": {"hexsha": "268cf15783ee2dd2311a9c77a8c7ff7bace2a201", "size": 2338, "ext": "h", "lang": "C", "max_stars_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_block_uint.h", "max_stars_repo_name": "snipekill/FPGen", "max_stars_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-07-06T02:44:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T21:02:18.000Z", "max_issues_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_block_uint.h", "max_issues_repo_name": "snipekill/FPGen", "max_issues_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_block_uint.h", "max_forks_repo_name": "snipekill/FPGen", "max_forks_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-06-27T11:11:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T19:22:30.000Z", "avg_line_length": 35.4242424242, "max_line_length": 128, "alphanum_fraction": 0.7660393499, "num_tokens": 605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19682619422045972, "lm_q2_score": 0.025565214758497216, "lm_q1q2_score": 0.005031903925343736}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n \r\n#ifndef image_a41c29de_bd9b_4bbd_9012_6dc956f524b3_h\r\n#define image_a41c29de_bd9b_4bbd_9012_6dc956f524b3_h\r\n\r\n#include <gslib/type.h>\r\n#include <gslib/string.h>\r\n#include <ariel/dirty.h>\r\n\r\n__ariel_begin__\r\n\r\nclass image\r\n{\r\npublic:\r\n    enum image_format\r\n    {\r\n        fmt_gray,                   /* gray8 */\r\n        fmt_rgba,                   /* rgba8888 */\r\n    };\r\n\r\n    friend class imageio;\r\n\r\npublic:\r\n    image();\r\n    ~image() { destroy(); }\r\n    bool is_valid() const;\r\n    image_format get_format() const { return _format; }\r\n    int get_depth() const { return _depth; }\r\n    bool create(image_format fmt, int w, int h);\r\n    void destroy();\r\n    void init(const color& cr);\r\n    void enable_alpha_channel(bool b) { _is_alpha_channel_valid = b; }\r\n    bool has_alpha() const { return _is_alpha_channel_valid; }\r\n    int get_width() const { return _width; }\r\n    int get_height() const { return _height; }\r\n    int get_bytes_per_line() const { return _bytes_per_line; }\r\n    int get_size() const { return _color_bytes; }\r\n    void set_xdpi(int dpi) { _xdpi = dpi; }\r\n    void set_ydpi(int dpi) { _ydpi = dpi; }\r\n    int get_xdpi() const { return _xdpi; }\r\n    int get_ydpi() const { return _ydpi; }\r\n    byte* get_data(int x, int y) const;\r\n    byte* get_bits() const { return _data; }\r\n    bool load(const string& filepath);\r\n    bool load(const gchar* filepath, int len) { return load(string(filepath, len)); }\r\n    bool save(const string& filepath) const;\r\n    void clear(byte b, const rect* rc = nullptr);\r\n    void clear(const color& cr, const rect* rc = nullptr);\r\n    void copy(const image& img);\r\n    void copy(const image& img, int x, int y, int cx, int cy, int sx, int sy);\r\n\r\nprotected:\r\n    image_format        _format;\r\n    int                 _width;\r\n    int                 _height;\r\n    int                 _depth;\r\n    int                 _color_bytes;\r\n    int                 _bytes_per_line;\r\n    int                 _xdpi;\r\n    int                 _ydpi;\r\n    byte*               _data;\r\n    bool                _is_alpha_channel_valid;\r\n};\r\n\r\n__ariel_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "3b6023e80d8cb955bf252424c052a36573101218", "size": 3370, "ext": "h", "lang": "C", "max_stars_repo_path": "include/ariel/image.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/ariel/image.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ariel/image.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 36.2365591398, "max_line_length": 86, "alphanum_fraction": 0.6451038576, "num_tokens": 816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15817436862177234, "lm_q2_score": 0.03161876772490445, "lm_q1q2_score": 0.005001278621485234}}
{"text": "/* bst/gsl_bst_rb.h\r\n * \r\n * Copyright (C) 2018 Patrick Alken\r\n * \r\n * This program is free software; you can redistribute it and/or modify\r\n * it under the terms of the GNU General Public License as published by\r\n * the Free Software Foundation; either version 3 of the License, or (at\r\n * your option) any later version.\r\n * \r\n * This program is distributed in the hope that it will be useful, but\r\n * WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n * General Public License for more details.\r\n * \r\n * You should have received a copy of the GNU General Public License\r\n * along with this program; if not, write to the Free Software\r\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r\n */\r\n\r\n#ifndef __GSL_BST_RB_H__\r\n#define __GSL_BST_RB_H__\r\n\r\n#if !defined( GSL_FUN )\r\n#  if !defined( GSL_DLL )\r\n#    define GSL_FUN extern\r\n#  elif defined( BUILD_GSL_DLL )\r\n#    define GSL_FUN extern __declspec(dllexport)\r\n#  else\r\n#    define GSL_FUN extern __declspec(dllimport)\r\n#  endif\r\n#endif\r\n\r\n#include <stdlib.h>\r\n#include <gsl/gsl_bst_types.h>\r\n\r\n#undef __BEGIN_DECLS\r\n#undef __END_DECLS\r\n#ifdef __cplusplus\r\n# define __BEGIN_DECLS extern \"C\" {\r\n# define __END_DECLS }\r\n#else\r\n# define __BEGIN_DECLS /* empty */\r\n# define __END_DECLS /* empty */\r\n#endif\r\n\r\n__BEGIN_DECLS\r\n\r\n#ifndef GSL_BST_RB_MAX_HEIGHT\r\n#define GSL_BST_RB_MAX_HEIGHT 48\r\n#endif\r\n\r\n/* red-black node */\r\nstruct gsl_bst_rb_node\r\n{\r\n  struct gsl_bst_rb_node *rb_link[2]; /* subtrees */\r\n  void *rb_data;                      /* pointer to data */\r\n  unsigned char rb_color;             /* color */\r\n};\r\n\r\n/* red-black tree data structure */\r\ntypedef struct\r\n{\r\n  struct gsl_bst_rb_node *rb_root;   /* tree's root */\r\n  gsl_bst_cmp_function *rb_compare;  /* comparison function */\r\n  void *rb_param;                    /* extra argument to |rb_compare| */\r\n  const gsl_bst_allocator *rb_alloc; /* memory allocator */\r\n  size_t rb_count;                   /* number of items in tree */\r\n  unsigned long rb_generation;       /* generation number */\r\n} gsl_bst_rb_table;\r\n\r\n/* red-black traverser structure */\r\ntypedef struct\r\n{\r\n  const gsl_bst_rb_table *rb_table;  /* tree being traversed */\r\n  struct gsl_bst_rb_node *rb_node;   /* current node in tree */\r\n  struct gsl_bst_rb_node *rb_stack[GSL_BST_RB_MAX_HEIGHT];\r\n                                     /* all the nodes above |rb_node| */\r\n  size_t rb_height;                  /* number of nodes in |rb_parent| */\r\n  unsigned long rb_generation;       /* generation number */\r\n} gsl_bst_rb_traverser;\r\n\r\n__END_DECLS\r\n\r\n#endif /* __GSL_BST_RB_H__ */\r\n", "meta": {"hexsha": "370a6c2d8ae47857769b2514fa7463ac2e1add5d", "size": 2678, "ext": "h", "lang": "C", "max_stars_repo_path": "vendor/gsl/gsl/gsl_bst_rb.h", "max_stars_repo_name": "mgreter/astrometrylib", "max_stars_repo_head_hexsha": "ef4d4539a537ab49329b77648aac893d2b4ad318", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z", "max_issues_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_bst_rb.h", "max_issues_repo_name": "zzpwahaha/VimbaCamJILA", "max_issues_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z", "max_forks_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_bst_rb.h", "max_forks_repo_name": "zzpwahaha/VimbaCamJILA", "max_forks_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 31.5058823529, "max_line_length": 82, "alphanum_fraction": 0.6728902166, "num_tokens": 650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16026602430611822, "lm_q2_score": 0.031143832108469622, "lm_q1q2_score": 0.004991298153681658}}
{"text": "#pragma once\n\n#include <gsl/span>\n\n#include <cstddef>\n#include <type_traits>\n\nnamespace imageview {\nnamespace detail {\n\ntemplate <class T, typename Enable = void>\nclass HasColorTypeTypedef : public std::false_type {};\n\ntemplate <class T>\nclass HasColorTypeTypedef<T, std::void_t<typename T::color_type>> : public std::true_type {};\n\ntemplate <class T, typename Enable = void>\nclass HasKBytesPerPixelConstant : public std::false_type {};\n\ntemplate <class T>\nclass HasKBytesPerPixelConstant<T, std::enable_if_t<std::is_integral_v<decltype(T::kBytesPerPixel)> &&\n                                                    std::is_const_v<decltype(T::kBytesPerPixel)>>>\n    : public std::true_type {};\n\ntemplate <class T, class Enable = void>\nclass HasRead : public std::false_type {};\n\ntemplate <class T>\nclass HasRead<T, std::enable_if_t<std::is_same_v<typename T::color_type,\n                                                 decltype(std::declval<const T&>().read(\n                                                     std::declval<gsl::span<const std::byte, T::kBytesPerPixel>>()))>>>\n    : public std::true_type {};\n\ntemplate <class T, class Enable = void>\nclass HasWrite : public std::false_type {};\n\ntemplate <class T>\nclass HasWrite<T, std::enable_if_t<std::is_same_v<void, decltype(std::declval<const T&>().write(\n                                                            std::declval<const typename T::color_type&>(),\n                                                            std::declval<gsl::span<std::byte, T::kBytesPerPixel>>()))>>>\n    : public std::true_type {};\n\n}  // namespace detail\n\ntemplate <class T>\nclass IsPixelFormat : public std::conjunction<\n                          // Has a member typedef 'color_type'.\n                          detail::HasColorTypeTypedef<T>,\n                          // Has an integral static member constant 'kBytesPerPixel'.\n                          detail::HasKBytesPerPixelConstant<T>,\n                          // Has a member function read() with the signature equivalent to\n                          //   color_type read(gsl::span<const std::byte, kBytesPerPixel>) const;\n                          detail::HasRead<T>,\n                          // Has a member function write() with the signature equivalent to\n                          //   void write(const color_type&, gsl::span<std::byte, kBytesPerPixel>) const;\n                          detail::HasWrite<T>> {};\n\n}  // namespace imageview\n", "meta": {"hexsha": "8cc9f9c323cfb3b106ba176aca6f7ca695a51aa6", "size": 2445, "ext": "h", "lang": "C", "max_stars_repo_path": "include/imageview/IsPixelFormat.h", "max_stars_repo_name": "alexanderbelous/imageview", "max_stars_repo_head_hexsha": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/imageview/IsPixelFormat.h", "max_issues_repo_name": "alexanderbelous/imageview", "max_issues_repo_head_hexsha": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/imageview/IsPixelFormat.h", "max_forks_repo_name": "alexanderbelous/imageview", "max_forks_repo_head_hexsha": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.4406779661, "max_line_length": 120, "alphanum_fraction": 0.5721881391, "num_tokens": 497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.17781086947804955, "lm_q2_score": 0.028007522532853213, "lm_q1q2_score": 0.004980041933492695}}
{"text": "#pragma once\n/*\n * (C) Copyright 2020-2021 UCAR\n *\n * This software is licensed under the terms of the Apache Licence Version 2.0\n * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.\n */\n/*! \\defgroup ioda_cxx_types Type System\n * \\brief The data type system\n * \\ingroup ioda_cxx_api\n *\n * @{\n * \\file Type.h\n * \\brief Interfaces for ioda::Type and related classes. Implements the type system.\n */\n#include <array>\n#include <cstring>\n#include <functional>\n#include <gsl/gsl-lite.hpp>\n#include <memory>\n#include <string>\n#include <typeindex>\n#include <typeinfo>\n#include <vector>\n\n#include \"ioda/Types/Type_Provider.h\"\n#include \"ioda/Exception.h\"\n#include \"ioda/defs.h\"\n\nnamespace ioda {\nclass Type;\n\n/// Basic pre-defined types (Python convenience wrappers)\n/// \\see py_ioda.cpp\n/// \\note Names here do not match the python equivalents. The\n///   Python names match numpy's definitions.\nenum class BasicTypes {\n  undefined_,  ///< Internal use only\n  float_,\n  double_,\n  ldouble_,\n  char_,\n  short_,\n  ushort_,\n  int_,\n  uint_,\n  lint_,\n  ulint_,\n  llint_,\n  ullint_,\n  int32_,\n  uint32_,\n  int16_,\n  uint16_,\n  int64_,\n  uint64_,\n  bool_,\n  str_\n};\n\nnamespace detail {\nIODA_DL size_t COMPAT_strncpy_s(char* dest, size_t destSz, const char* src, size_t srcSz);\n\nclass Type_Backend;\n\ntemplate <class Type_Implementation = Type>\nclass Type_Base {\n  friend class ::ioda::Type;\n  std::shared_ptr<Type_Backend> backend_;\n\nprotected:\n  ::ioda::detail::Type_Provider* provider_;\n\n  /// @name General Functions\n  /// @{\n\n  Type_Base(std::shared_ptr<Type_Backend> b, ::ioda::detail::Type_Provider* p)\n      : backend_(b), provider_(p) {}\n\n  /// Get the type provider.\n  inline detail::Type_Provider* getTypeProvider() const { return provider_; }\n\n  /*\n  /// \\brief Convenience function to check a type.\n  /// \\param DataType is the type of the data. I.e. float, int, int32_t, uint16_t, std::string, etc.\n  /// \\returns True if the type matches\n  /// \\returns False (0) if the type does not match\n  /// \\throws if an error occurred.\n  template <class DataType>\n  bool isA() const {\n    Type templateType = Types::GetType_Wrapper<DataType>::GetType(getTypeProvider());\n\n    return isA(templateType);\n  }\n  /// Hand-off to the backend to check equivalence\n  virtual bool isA(Type lhs) const;\n\n  /// Python compatability function\n  inline bool isA(BasicTypes dataType) const { return isA(Type(dataType, getTypeProvider())); }\n  */\npublic:\n  virtual ~Type_Base() {}\n  std::shared_ptr<Type_Backend> getBackend() const { return backend_; }\n  bool isValid() const { return (backend_.use_count() > 0); }\n\n  /// \\brief Get the size of a single element of a type, in bytes.\n  /// \\details This function is paired with the read and write functions to allow you to\n  /// read and write data in a type-agnostic manner.\n  /// This size report is a bit complicated when variable-length strings are encountered.\n  /// In these cases, the size of the string pointer is returned.\n  virtual size_t getSize() const;\n\n  /// @}\n};\n}  // namespace detail\n\n/// \\brief Represents the \"type\" (i.e. integer, string, float) of a piece of data.\n/// \\ingroup ioda_cxx_types\n///\n/// Generally, you do not have to use this class directly. Attributes and Variables have\n/// templated functions that convert your type into the type used internally by ioda.\n/// \\see Types::GetType and Types::GetType_Wrapper for functions that produce these types.\nclass IODA_DL Type : public detail::Type_Base<> {\npublic:\n  Type();\n  Type(std::shared_ptr<detail::Type_Backend> b, std::type_index t);\n  Type(BasicTypes, gsl::not_null<::ioda::detail::Type_Provider*> t);\n\n  virtual ~Type();\n\n  /// @name Type-querying functions\n  /// @{\n\n  /// @deprecated This function is problematic since we cannot query a type properly\n  /// when loading from a file.\n  std::type_index getType() const { return as_type_index_; }\n  inline std::type_index operator()() const { return getType(); }\n  inline std::type_index get() const { return getType(); }\n\n  /// @}\nprivate:\n  std::type_index as_type_index_;\n};\n\nnamespace detail {\n\n/// Backends inherit from this and they provide their own functions.\n/// Lots of std::dynamic_cast, unfortunately.\nclass IODA_DL Type_Backend : public Type_Base<> {\npublic:\n  virtual ~Type_Backend();\n  size_t getSize() const override;\n\nprotected:\n  Type_Backend();\n};\n\n}  // namespace detail\n\n/// \\brief Defines the type system used for manipulating IODA objects.\nnamespace Types {\n\n// using namespace ioda::Handles;\n\n/// \\brief Convenience struct to determine if a type can represent a string.\n/// \\ingroup ioda_cxx_types\n/// \\todo extend to UTF-8 strings, as HDF5 supports these. No support for UTF-16, but conversion\n/// functions may be applied.\n/// \\todo Fix for \"const std::string\".\ntemplate <typename T>\nstruct is_string : public std::integral_constant<\n                     bool, std::is_same<char*, typename std::decay<T>::type>::value\n                             || std::is_same<const char*, typename std::decay<T>::type>::value> {};\n/// \\brief Convenience struct to determine if a type can represent a string.\n/// \\ingroup ioda_cxx_types\ntemplate <>\nstruct is_string<std::string> : std::true_type {};\n\n/// Useful compile-time definitions.\nnamespace constants {\n/// \\note Different than ObsSpace variable-length dimension. This is for a Type.\nconstexpr size_t _Variable_Length = 0;\n// constexpr int _Not_An_Array_type = -3;\n}  // namespace constants\n\n/// \\brief For fundamental, non-string types.\n/// \\ingroup ioda_cxx_types\ntemplate <class DataType, int Array_Type_Dimensionality = 0>\nType GetType(gsl::not_null<const ::ioda::detail::Type_Provider*> t,\n             std::initializer_list<Dimensions_t> Adims                   = {},\n             typename std::enable_if<!is_string<DataType>::value>::type* = 0) {\n  if (Array_Type_Dimensionality <= 0)\n    throw Exception(\n      \"Bad assertion / unsupported fundamental type at the frontend side \"\n      \"of the ioda type system.\", ioda_Here());\n  else\n    return t->makeArrayType(Adims, typeid(DataType[]), typeid(DataType));\n}\n/// \\brief For fundamental string types. These are either constant or variable length arrays.\n/// Separate handling elsewhere.\n/// \\ingroup ioda_cxx_types\ntemplate <class DataType, int String_Type_Length = constants::_Variable_Length>\nType GetType(gsl::not_null<const ::ioda::detail::Type_Provider*> t,\n             std::initializer_list<Dimensions_t>                        = {},\n             typename std::enable_if<is_string<DataType>::value>::type* = 0) {\n  return t->makeStringType(String_Type_Length, typeid(DataType));\n}\n\n// This macro just repeats a long definition\n\n/// @def IODA_ADD_FUNDAMENTAL_TYPE\n/// Macro that defines a \"fundamental type\" that needs to be supported\n/// by the backend. These match C++11.\n/// \\ingroup ioda_cxx_types\n/// \\see https://en.cppreference.com/w/cpp/language/types\n/// \\since C++11: we use bool, short int, unsigned short int,\n///   int, unsigned int, long int, unsigned long int,\n///   long long int, unsigned long long int,\n///   signed char, unsigned char, char,\n///   wchar_t, char16_t, char32_t,\n///   float, double, long double.\n/// \\since C++20: we also add char8_t.\n#define IODA_ADD_FUNDAMENTAL_TYPE(x)                                                               \\\n  template <>                                                                                      \\\n  inline Type GetType<x, 0>(gsl::not_null<const ::ioda::detail::Type_Provider*> t,                 \\\n                            std::initializer_list<Dimensions_t>, void*) {                          \\\n    return t->makeFundamentalType(typeid(x));                                                      \\\n  }\n\nIODA_ADD_FUNDAMENTAL_TYPE(bool);\nIODA_ADD_FUNDAMENTAL_TYPE(short int);\nIODA_ADD_FUNDAMENTAL_TYPE(unsigned short int);\nIODA_ADD_FUNDAMENTAL_TYPE(int);\nIODA_ADD_FUNDAMENTAL_TYPE(unsigned int);\nIODA_ADD_FUNDAMENTAL_TYPE(long int);\nIODA_ADD_FUNDAMENTAL_TYPE(unsigned long int);\nIODA_ADD_FUNDAMENTAL_TYPE(long long int);\nIODA_ADD_FUNDAMENTAL_TYPE(unsigned long long int);\nIODA_ADD_FUNDAMENTAL_TYPE(signed char);\nIODA_ADD_FUNDAMENTAL_TYPE(unsigned char);\nIODA_ADD_FUNDAMENTAL_TYPE(char);\nIODA_ADD_FUNDAMENTAL_TYPE(wchar_t);\nIODA_ADD_FUNDAMENTAL_TYPE(char16_t);\nIODA_ADD_FUNDAMENTAL_TYPE(char32_t);\n// IODA_ADD_FUNDAMENTAL_TYPE(char8_t); // C++20\nIODA_ADD_FUNDAMENTAL_TYPE(float);\nIODA_ADD_FUNDAMENTAL_TYPE(double);\nIODA_ADD_FUNDAMENTAL_TYPE(long double);\n\n#undef IODA_ADD_FUNDAMENTAL_TYPE\n\n/*\n/// Used in an example. Incomplete.\n/// \\todo Pop off std::array as a 1-D object\ntemplate<> inline Type GetType<std::array<int,2>, 0>\n        (gsl::not_null<const ::ioda::detail::Type_Provider*> t,\n        std::initializer_list<Dimensions_t>, void*) {\n        return t->makeArrayType({2}, typeid(std::array<int,2>), typeid(int)); }\n\n*/\n\n/*\ntemplate <class DataType, int Array_Type_Dimensionality = 0>\nType GetType(\n        gsl::not_null<const ::ioda::detail::Type_Provider*> t,\n        std::initializer_list<Dimensions_t> Adims = {},\n        typename std::enable_if<!is_string<DataType>::value>::type* = 0);\ntemplate <class DataType, int String_Type_Length = constants::_Variable_Length>\nType GetType(\n        gsl::not_null<const ::ioda::detail::Type_Provider*> t,\n        typename std::enable_if<is_string<DataType>::value>::type* = 0);\n        */\n\n/// \\brief Wrapper struct to call GetType. Needed because of C++ template rules.\n/// \\ingroup ioda_cxx_types\n/// \\see ioda::Attribute, ioda::Has_Attributes, ioda::Variable, ioda::Has_Variables\ntemplate <class DataType,\n          int Length = 0>  //, typename = std::enable_if_t<!is_string<DataType>::value>>\nstruct GetType_Wrapper {\n  static Type GetType(gsl::not_null<const ::ioda::detail::Type_Provider*> t) {\n    /// \\note Currently breaks array types, but these are not yet used.\n    return ::ioda::Types::GetType<DataType, Length>(t, {Length});\n  }\n};\n/// \\ingroup ioda_cxx_types\ntypedef std::function<Type(gsl::not_null<const ::ioda::detail::Type_Provider*>)>\n  TypeWrapper_function;\n/*\ntemplate <class DataType, int Length = 0, typename = std::enable_if_t<is_string<DataType>::value>>\nstruct GetType_Wrapper {\n        Type GetType(gsl::not_null<const ::ioda::detail::Type_Provider*> t) const {\n                // string split\n                return ::ioda::Types::GetType<DataType, Length>(t);\n        }\n};\n*/\n\n// inline Encapsulated_Handle GetTypeFixedString(Dimensions_t sz);\n}  // namespace Types\n}  // namespace ioda\n\n/// @}\n", "meta": {"hexsha": "0fd39a6df3673a6eab59e208982c3969e84c1931", "size": 10463, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engines/ioda/include/ioda/Types/Type.h", "max_stars_repo_name": "Gibies/ioda", "max_stars_repo_head_hexsha": "5bd372e548eb61d5f7b56a0b3d4cf0ca05e49e75", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-09T16:11:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-09T16:11:50.000Z", "max_issues_repo_path": "src/engines/ioda/include/ioda/Types/Type.h", "max_issues_repo_name": "Gibies/ioda", "max_issues_repo_head_hexsha": "5bd372e548eb61d5f7b56a0b3d4cf0ca05e49e75", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engines/ioda/include/ioda/Types/Type.h", "max_forks_repo_name": "Gibies/ioda", "max_forks_repo_head_hexsha": "5bd372e548eb61d5f7b56a0b3d4cf0ca05e49e75", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-06-09T16:12:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-14T09:19:25.000Z", "avg_line_length": 34.5313531353, "max_line_length": 100, "alphanum_fraction": 0.6891904807, "num_tokens": 2614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07369626970604846, "lm_q2_score": 0.06754668879328725, "lm_q1q2_score": 0.004977938995060618}}
{"text": "#pragma once\n\n#include <nextalign/nextalign.h>\n\n#include <gsl/string_span>\n#include <string>\n\n#include \"../nextalign_private.h\"\n#include \"../utils/to_underlying.h\"\n\nusing NucleotideSequenceSpan = SequenceSpan<Nucleotide>;\n\nNucleotide toNucleotide(char nuc);\n\nchar nucToChar(Nucleotide nuc);\n\ninline std::ostream& operator<<(std::ostream& os, const Nucleotide& nucleotide) {\n  os << std::string{to_underlying(nucleotide)};\n  return os;\n}\n", "meta": {"hexsha": "c52dbaf93398e7fd4dc3a00c1b0fb403ee7748d6", "size": 437, "ext": "h", "lang": "C", "max_stars_repo_path": "packages/nextalign/src/alphabet/nucleotides.h", "max_stars_repo_name": "davidcroll/nextclade", "max_stars_repo_head_hexsha": "f62d906034974c160eabb12ac9bf98a691646ee3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "packages/nextalign/src/alphabet/nucleotides.h", "max_issues_repo_name": "davidcroll/nextclade", "max_issues_repo_head_hexsha": "f62d906034974c160eabb12ac9bf98a691646ee3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "packages/nextalign/src/alphabet/nucleotides.h", "max_forks_repo_name": "davidcroll/nextclade", "max_forks_repo_head_hexsha": "f62d906034974c160eabb12ac9bf98a691646ee3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.8095238095, "max_line_length": 81, "alphanum_fraction": 0.7505720824, "num_tokens": 114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.14804719803168945, "lm_q2_score": 0.03358950407804544, "lm_q1q2_score": 0.0049728319620286334}}
{"text": "#ifndef _PYGSL_SOLVER_INTERN_H_\n#define _PYGSL_SOLVER_INTERN_H_ 1\n\n#define _PyGSL_SOLVER_API_MODULE 1\n#include <pygsl/solver.h>\n#undef _PyGSL_SOLVER_API_MODULE\n\n#include <pygsl/general_helpers.h>\n#include <pygsl/block_helpers.h>\n#include <pygsl/function_helpers.h>\n#include <setjmp.h>\n#include <gsl/gsl_math.h>\n\n/*\n * Collect all element accessor methods which just need a pointer to the struct\n * and return a value.\n */\nstruct _ElementAccessor{\n     int_m_t method;\n     const char * name;\n};\n\n\nstatic PyTypeObject PyGSL_solver_pytype;\n#define PyGSL_solver_check(ob) ((ob)->ob_type == &PyGSL_solver_pytype)\n#define _PyGSL_solver_n_init PyGSL_solver_n_init\n\n\nstatic PyGSL_solver* \n_PyGSL_solver_init(const struct _SolverStatic *mstatic);\n\n\n\nstatic int\nPyGSL_solver_set_called(PyGSL_solver *self);\n\n#define PyGSL_SOLVER_SET_CALLED(ob) \\\n        (((ob)->set_called == 1) ? GSL_SUCCESS: PyGSL_solver_set_called((ob)))\n\nstatic int\nPyGSL_solver_func_set(PyGSL_solver *self, PyObject *args, PyObject *f,\n\t\t       PyObject *df, PyObject *fdf);\n\n\n#if 0\nstatic PyObject *\n_PyGSL_solver_np_init(PyObject *self, PyObject *args, const solver_alloc_struct * alloc);\n\nstatic PyObject *\n_PyGSL_solver_i_vvdd(PyObject * self, PyObject * args, int_f_vvdd_t func);\n\n#endif\n#endif /* _PYGSL_SOLVER_INTERN_H_ */\n", "meta": {"hexsha": "defb339559517946c313395a098ed63f3c30b839", "size": 1293, "ext": "h", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/testing/src/solvers/solver_intern.h", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/testing/src/solvers/solver_intern.h", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/testing/src/solvers/solver_intern.h", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 23.9444444444, "max_line_length": 89, "alphanum_fraction": 0.7718484145, "num_tokens": 365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1968261942204597, "lm_q2_score": 0.025178841060544566, "lm_q1q2_score": 0.00495585546082883}}
{"text": "#pragma once\n\n#include <Babylon/JsRuntime.h>\n#include <napi/env.h>\n#include <gsl/gsl>\n#include <cassert>\n\nnamespace Babylon\n{\n    class NativeDataStream final : public Napi::ObjectWrap<NativeDataStream>\n    {\n        static constexpr auto JS_CLASS_NAME = \"_NativeDataStream\";\n        static constexpr auto JS_ENGINE_CONSTRUCTOR_NAME = \"NativeDataStream\";\n\n        static constexpr auto VALIDATION_ENABLED = false;\n\n        enum class ValidationType : uint32_t\n        {\n            Uint32,\n            Int32,\n            Float32,\n            Uint32Array,\n            Int32Array,\n            Float32Array,\n            NativeData,\n            Boolean,\n        };\n\n        template<ValidationType T, typename ReaderT>\n        static inline void Validate(ReaderT& reader)\n        {\n            if constexpr (VALIDATION_ENABLED)\n            {\n                uint32_t value{reader.template Read<uint32_t>()};\n                if (value != static_cast<uint32_t>(T))\n                {\n                    throw std::runtime_error{\"Data stream validation error: data type mismatch.\"};\n                }\n            }\n        }\n\n    public:\n        class Reader final\n        {\n        public:\n            Reader(const Reader&) = delete;\n            Reader(Reader&&) = delete;\n            Reader operator=(const Reader&) = delete;\n            Reader operator=(const Reader&&) = delete;\n\n            bool CanRead() const\n            {\n                assert(m_position <= static_cast<size_t>(m_buffer.size()));\n                return m_position < static_cast<size_t>(m_buffer.size());\n            }\n\n            uint32_t ReadUint32()\n            {\n                Validate<ValidationType::Uint32>(*this);\n                return Read<uint32_t>();\n            }\n\n            int32_t ReadInt32()\n            {\n                Validate<ValidationType::Int32>(*this);\n                return Read<int32_t>();\n            }\n\n            float ReadFloat32()\n            {\n                Validate<ValidationType::Float32>(*this);\n                return Read<float>();\n            }\n\n            gsl::span<uint32_t> ReadUint32Array()\n            {\n                Validate<ValidationType::Uint32Array>(*this);\n                return ReadArray<uint32_t>();\n            }\n\n            gsl::span<int32_t> ReadInt32Array()\n            {\n                Validate<ValidationType::Int32Array>(*this);\n                return ReadArray<int32_t>();\n            }\n\n            gsl::span<float> ReadFloat32Array()\n            {\n                Validate<ValidationType::Float32Array>(*this);\n                return ReadArray<float>();\n            }\n\n            template<typename T>\n            T ReadNativeData()\n            {\n                Validate<ValidationType::NativeData>(*this);\n                static_assert(sizeof(T) % 4 == 0);\n                auto span = gsl::make_span(reinterpret_cast<uint32_t*>(m_buffer.data() + m_position), sizeof(T) / 4);\n                m_position += sizeof(T) / 4;\n                return *reinterpret_cast<T*>(span.data());\n            }\n\n            template<typename T, class = typename std::enable_if<!std::is_pointer<T>::value>::type>\n            auto ReadPointer()\n            {\n                return ReadNativeData<typename std::conditional<std::is_member_pointer<T>::value, T, T*>::type>();\n            }\n\n        private:\n            gsl::span<uint32_t> m_buffer{};\n            size_t m_position{0};\n            const gsl::final_action<std::function<void()>> m_scopeGuard;\n\n            friend class NativeDataStream;\n\n            template<typename CallableT>\n            Reader(gsl::span<uint32_t> buffer, CallableT&& callable)\n                : m_buffer{buffer}\n                , m_scopeGuard{std::forward<CallableT>(callable)}\n            {\n            }\n\n            template<typename T>\n            T Read()\n            {\n                static_assert(sizeof(T) % 4 == 0);\n                T t{*reinterpret_cast<T*>(m_buffer.data() + m_position)};\n                m_position += sizeof(T) / 4;\n                return t;\n            }\n\n            template<typename T>\n            gsl::span<T> ReadArray()\n            {\n                static_assert(sizeof(T) % 4 == 0);\n\n                // The first 32 bit number is a length\n                uint32_t length = Read<uint32_t>();\n\n                auto span = gsl::make_span<T>(reinterpret_cast<T*>(m_buffer.data() + m_position), length * (sizeof(T) / 4));\n                m_position += length;\n                return span;\n            }\n        };\n\n        static void Initialize(Napi::Env env)\n        {\n            Napi::HandleScope scope{env};\n            if constexpr (VALIDATION_ENABLED)\n            {\n                Napi::Function func = DefineClass(\n                    env,\n                    JS_CLASS_NAME,\n                    {\n                        InstanceMethod(\"writeBuffer\", &NativeDataStream::WriteBuffer),\n\n                        StaticValue(\"VALIDATION_ENABLED\", Napi::Boolean::From(env, VALIDATION_ENABLED)),\n                        StaticValue(\"VALIDATION_UINT_32\", Napi::Number::From(env, static_cast<uint32_t>(ValidationType::Uint32))),\n                        StaticValue(\"VALIDATION_INT_32\", Napi::Number::From(env, static_cast<uint32_t>(ValidationType::Int32))),\n                        StaticValue(\"VALIDATION_FLOAT_32\", Napi::Number::From(env, static_cast<uint32_t>(ValidationType::Float32))),\n                        StaticValue(\"VALIDATION_UINT_32_ARRAY\", Napi::Number::From(env, static_cast<uint32_t>(ValidationType::Uint32Array))),\n                        StaticValue(\"VALIDATION_INT_32_ARRAY\", Napi::Number::From(env, static_cast<uint32_t>(ValidationType::Int32Array))),\n                        StaticValue(\"VALIDATION_FLOAT_32_ARRAY\", Napi::Number::From(env, static_cast<uint32_t>(ValidationType::Float32Array))),\n                        StaticValue(\"VALIDATION_NATIVE_DATA\", Napi::Number::From(env, static_cast<uint32_t>(ValidationType::NativeData))),\n                        StaticValue(\"VALIDATION_BOOLEAN\", Napi::Number::From(env, static_cast<uint32_t>(ValidationType::Boolean))),\n                    });\n                JsRuntime::NativeObject::GetFromJavaScript(env).Set(JS_ENGINE_CONSTRUCTOR_NAME, func);\n            }\n            else\n            {\n                Napi::Function func = DefineClass(\n                    env,\n                    JS_CLASS_NAME,\n                    {\n                        InstanceMethod(\"writeBuffer\", &NativeDataStream::WriteBuffer)\n                    });\n                JsRuntime::NativeObject::GetFromJavaScript(env).Set(JS_ENGINE_CONSTRUCTOR_NAME, func);\n            }\n        }\n\n        NativeDataStream(const Napi::CallbackInfo& info)\n            : Napi::ObjectWrap<NativeDataStream>(info)\n            , m_requestFlushCallback{Napi::Persistent(info[0].As<Napi::Function>())}\n        {\n        }\n\n        void WriteBuffer(const Napi::CallbackInfo& info)\n        {\n            assert(!m_locked); // Cannot write bytes while the stream is locked for reading.\n\n            const auto& buffer = info[0].As<Napi::ArrayBuffer>();\n            const auto& length = info[1].ToNumber().Uint32Value();\n\n            auto span = gsl::make_span(reinterpret_cast<uint32_t*>(buffer.Data()), static_cast<ptrdiff_t>(length));\n            m_buffer.insert(m_buffer.end(), span.begin(), span.end());\n        }\n\n        Reader GetReader()\n        {\n            assert(!m_locked);\n            m_requestFlushCallback.Call({});\n            m_locked = true;\n            return {m_buffer, [this]() {\n                m_buffer.clear();\n                m_locked = false; \n            }};\n        }\n\n    private:\n        std::vector<uint32_t> m_buffer{};\n        Napi::FunctionReference m_requestFlushCallback{};\n        bool m_locked{false};\n    };\n}\n", "meta": {"hexsha": "da8010bed82cf02a62ce28d62733568bb56f8a76", "size": 7772, "ext": "h", "lang": "C", "max_stars_repo_path": "Plugins/NativeEngine/Source/NativeDataStream.h", "max_stars_repo_name": "SergioRZMasson/BabylonNative", "max_stars_repo_head_hexsha": "18ea83ee51e4e5d8b1763cf8d9ef5b48b2f9bb0a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Plugins/NativeEngine/Source/NativeDataStream.h", "max_issues_repo_name": "SergioRZMasson/BabylonNative", "max_issues_repo_head_hexsha": "18ea83ee51e4e5d8b1763cf8d9ef5b48b2f9bb0a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Plugins/NativeEngine/Source/NativeDataStream.h", "max_forks_repo_name": "SergioRZMasson/BabylonNative", "max_forks_repo_head_hexsha": "18ea83ee51e4e5d8b1763cf8d9ef5b48b2f9bb0a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1488372093, "max_line_length": 143, "alphanum_fraction": 0.5281780751, "num_tokens": 1564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2628418489200747, "lm_q2_score": 0.018833128720196126, "lm_q1q2_score": 0.00495013437376611}}
{"text": "#pragma once\n\n#include \"ui_MaterialVisualizationWidget.h\"\n\n#include <mitkDataNode.h>\n#include <vtkDataObject.h>\n\n#include <array>\n#include <gsl.h>\n\nnamespace mitk\n{\nclass DataNode;\nclass TransferFunction;\n}\n\n/*! \\brief   A widget for editing transfer function. */\nclass MaterialVisualizationWidget : public QWidget\n{\n    Q_OBJECT\npublic:\n    MaterialVisualizationWidget(QWidget* parent = nullptr, Qt::WindowFlags f = 0);\n    ~MaterialVisualizationWidget();\n\n    /*!\n     * \\brief   Sets the data node whose transfer function is to be edited.\n     *\n     * \\param   node                The data node.\n     * \\param   dataSet             The vtkDataSet stored in the data node (the access may differ for mitk::Surface and mitk::UnstructuredGrid).\n     * \\param   tfPropertyName      Name of the transfer function property used by the renderer.\n     * \\param   attributeType       Type of the attribute to be shown (vtkDataObject::POINT or vtkDataObject::CELL).\n     * \\param   propertyStorageNode If non-null, the node where to store various transfer functions to be re-used later. If null, the 'node' will be used.\n     */\n    void setDataNode(mitk::DataNode* node, vtkDataSet* dataSet, gsl::cstring_span<> tfPropertyName,\n                     vtkDataObject::AttributeTypes attributeType = vtkDataObject::POINT,\n                     mitk::DataNode* propertyStorageNode = nullptr);\n    /*! \\brief   Resets the data node to null. */\n    void resetDataNode() { setDataNode(nullptr, nullptr, \"\"); }\n\n    /*! \\brief   Gets data node. */\n    mitk::DataNode* getDataNode() const { return _node; }\n\nprivate slots:\n    void _setCurrentArray(const QString& arrayName);\n    void _setCurrentComponent(int comboBoxIndex);\n    void _resetTF();\n    void _setNanColor(QColor c);\n\n    void _setColorSpace(int colorSpace);\n    void _loadTF();\n    void _saveTF();\n\nprivate:\n    void _dataNodeDeleted();\n    std::string _getCurrentTFPropName();\n    void _setupDataComboBoxes();\n    void _setTransferFunction(bool reset = false);\n    static void _setupTFProperties(mitk::TransferFunction* tf, int componentIndex);\n    static void _generateTF(mitk::TransferFunction* tf, const std::array<double, 2>& range);\n    static void _rescaleTF(mitk::TransferFunction* tf, const std::array<double, 2>& range);\n    QColor _getNanColor();\n    void _addNodeObserver();\n    void _removeNodeObserver();\n\n    mitk::DataNode* _node = nullptr;\n    vtkDataSet* _dataSet = nullptr;\n    std::string _tfPropertyName;\n    vtkDataObject::AttributeTypes _attributeType = vtkDataObject::POINT;\n    mitk::DataNode* _propertyStorageNode = nullptr;\n    Ui::MaterialVisualizationWidget _UI;\n    unsigned long _nodeObserverTag = -1;\n};\n", "meta": {"hexsha": "d23b6059482cac12463a847355bb5c57f6b3682d", "size": 2682, "ext": "h", "lang": "C", "max_stars_repo_path": "Plugins/uk.ac.kcl.SolverSetupView/src/internal/MaterialVisualizationWidget.h", "max_stars_repo_name": "carthurs/CRIMSONGUI", "max_stars_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-09-17T18:55:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T02:52:38.000Z", "max_issues_repo_path": "Plugins/uk.ac.kcl.SolverSetupView/src/internal/MaterialVisualizationWidget.h", "max_issues_repo_name": "carthurs/CRIMSONGUI", "max_issues_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Plugins/uk.ac.kcl.SolverSetupView/src/internal/MaterialVisualizationWidget.h", "max_forks_repo_name": "carthurs/CRIMSONGUI", "max_forks_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-05-19T09:02:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-26T17:39:57.000Z", "avg_line_length": 36.7397260274, "max_line_length": 154, "alphanum_fraction": 0.6994780015, "num_tokens": 640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23934933647101647, "lm_q2_score": 0.020645930739218447, "lm_q1q2_score": 0.0049415898232584975}}
{"text": "#ifndef __UTIL_H\n#define __UTIL_H\n\n#include <glib.h>\n#include <gsl/gsl_matrix.h>\n\nstruct _CLArgumentEntry {\n  GString *block;\n  char *label;\n};\n\nstruct _LabeledMatrix {\n  gsl_matrix *mat;\n  char **labels1;\n  char **labels2;\n};\n\ntypedef struct _LabeledMatrix LabeledMatrix ;\ntypedef struct _CLArgumentEntry CLArgumentEntry ;\n\nchar *complearn_make_temp_dir_name(void);\nchar *complearn_make_temp_dir(void);\nint make_directory(const char *name);\nint complearn_make_directory_if_necessary(const char *name);\nGString *complearn_read_whole_file(const char *fname);\nint complearn_count_strings(const char * const * str);\nint complearn_remove_directory_recursively(const char *dirname, int f_err_out);\nGString *complearn_read_whole_file_ptr(FILE *fp);\nGString *complearn_read_whole_file_io(GIOChannel *gio);\nGSList *complearn_read_directory_of_files(const char *dirname);\nGSList *complearn_read_list_of_files(const char *filename);\nGSList *complearn_read_list_of_strings(const char *filename);\ngsl_matrix *complearn_average_matrix(gsl_matrix *a);\ngsl_matrix *complearn_svd_project(gsl_matrix *a);\nCLArgumentEntry *complearn_new_arg(GString *block, const char *label);\nint complearn_get_pid(void);\nchar *complearn_get_hostname();\nchar ** complearn_dupe_strings(const char * const * str);\nchar ** complearn_fix_labels(char **inp);\nchar *complearn_make_temp_file_name(void);\nchar *complearn_chdir(const char *newdir);\nint complearn_write_file(const char *fname, const GString *f);\nvoid complearn_mrbreaker(void);\n\n\n#endif\n", "meta": {"hexsha": "ec0c8ba6de675f7de21fc27b4158e8b72ed64f56", "size": 1510, "ext": "h", "lang": "C", "max_stars_repo_path": "src/complearn/util.h", "max_stars_repo_name": "rudi-cilibrasi/classic-complearn", "max_stars_repo_head_hexsha": "c70ac5ad7bcfe3af80a2a8f087ee6f5904820a66", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-03-14T13:52:31.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-08T11:13:03.000Z", "max_issues_repo_path": "src/complearn/util.h", "max_issues_repo_name": "rudi-cilibrasi/classic-complearn", "max_issues_repo_head_hexsha": "c70ac5ad7bcfe3af80a2a8f087ee6f5904820a66", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2016-05-10T12:56:52.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-15T18:30:04.000Z", "max_forks_repo_path": "src/complearn/util.h", "max_forks_repo_name": "rudi-cilibrasi/classic-complearn", "max_forks_repo_head_hexsha": "c70ac5ad7bcfe3af80a2a8f087ee6f5904820a66", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1276595745, "max_line_length": 79, "alphanum_fraction": 0.8092715232, "num_tokens": 389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2281564916644813, "lm_q2_score": 0.021615332014210595, "lm_q1q2_score": 0.004931678318525235}}
{"text": "#pragma once\n\n#include \"rev/gl/Context.h\"\n#include \"rev/gl/Resource.h\"\n#include \"rev/gl/Uniform.h\"\n\n#include <array>\n#include <gsl/gsl_assert>\n#include <string>\n\nnamespace rev {\n\ntemplate <GLenum shaderType>\nGLuint createShader()\n{\n    return glCreateShader(shaderType);\n}\n\nnamespace detail {\n    template <void (*propertyGetter)(GLuint, GLenum, GLint*),\n        void (*logGetter)(GLuint, GLsizei, GLsizei*, GLchar*)>\n    std::string extractLog(GLuint objectId)\n    {\n        GLint logLength;\n        propertyGetter(objectId, GL_INFO_LOG_LENGTH, &logLength);\n\n        std::string log;\n        log.resize(logLength);\n\n        GLint fetchedLength;\n        logGetter(objectId, logLength, &fetchedLength, log.data());\n\n        log.resize(fetchedLength);\n\n        return log;\n    }\n} // namespace detail\n\ntemplate <GLenum shaderType>\nclass Shader : public Resource<createShader<shaderType>, gl::deleteShader> {\npublic:\n    void setSource(const std::string_view& source)\n    {\n        setSource(std::array<std::string_view, 1>{ source });\n    }\n\n    template <size_t arrayLength>\n    void setSource(const std::array<std::string_view, arrayLength>& source)\n    {\n        std::array<const char*, arrayLength> pointers;\n        std::array<GLint, arrayLength> lengths;\n        for (size_t i = 0; i < arrayLength; i++) {\n            pointers[i] = source[i].data();\n            lengths[i] = static_cast<GLint>(source[i].size());\n            Expects(source[i].size() <= std::numeric_limits<GLint>::max());\n        }\n        glShaderSource(this->getId(), arrayLength, pointers.data(), lengths.data());\n    }\n\n    void compile() { glCompileShader(this->getId()); }\n\n    bool getCompileStatus()\n    {\n        GLint status;\n        glGetShaderiv(this->getId(), GL_COMPILE_STATUS, &status);\n        return (status == GL_TRUE);\n    }\n\n    std::string getCompileLog()\n    {\n        return detail::extractLog<gl::getShaderiv, gl::getShaderInfoLog>(this->getId());\n    }\n};\n\nusing VertexShader = Shader<GL_VERTEX_SHADER>;\nusing FragmentShader = Shader<GL_FRAGMENT_SHADER>;\n\nclass ProgramResource : public Resource<gl::createProgram, gl::deleteProgram> {\npublic:\n    template <GLenum shaderType>\n    void attachShader(const Shader<shaderType>& shader)\n    {\n        glAttachShader(getId(), shader.getId());\n    }\n\n    void link() { glLinkProgram(getId()); }\n\n    bool getLinkStatus()\n    {\n        GLint status;\n        glGetProgramiv(getId(), GL_LINK_STATUS, &status);\n        return (status == GL_TRUE);\n    }\n\n    std::string getLinkLog()\n    {\n        return detail::extractLog<gl::getProgramiv, gl::getProgramInfoLog>(getId());\n    }\n\n    template <typename VertexSourceType, typename FragmentSourceType>\n    void buildWithSource(\n        const VertexSourceType& vertexSource, const FragmentSourceType& fragmentSource)\n    {\n        VertexShader vShader;\n        vShader.setSource(vertexSource);\n        vShader.compile();\n        if (!vShader.getCompileStatus()) {\n            throw vShader.getCompileLog();\n        }\n\n        FragmentShader fShader;\n        fShader.setSource(fragmentSource);\n        fShader.compile();\n        if (!fShader.getCompileStatus()) {\n            throw fShader.getCompileLog();\n        }\n\n        attachShader(vShader);\n        attachShader(fShader);\n        link();\n        if (!getLinkStatus()) {\n            throw getLinkLog();\n        }\n    }\n\n    template <typename VariableType>\n    Uniform<VariableType> getUniform(const char* name)\n    {\n        GLint location = glGetUniformLocation(getId(), name);\n\n        return Uniform<VariableType>(location);\n    }\n};\n\nusing ProgramContext = ResourceContext<ProgramResource, gl::useProgram>;\n\n} // namespace rev\n", "meta": {"hexsha": "c486cfe962e21740e6a8e75576b215e7b7462891", "size": 3672, "ext": "h", "lang": "C", "max_stars_repo_path": "engine/include/rev/gl/ProgramResource.h", "max_stars_repo_name": "eyebrowsoffire/rev", "max_stars_repo_head_hexsha": "d8abdf0a0016e309942932c9af9df1f8a2b02448", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "engine/include/rev/gl/ProgramResource.h", "max_issues_repo_name": "eyebrowsoffire/rev", "max_issues_repo_head_hexsha": "d8abdf0a0016e309942932c9af9df1f8a2b02448", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-01-27T16:52:41.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-27T16:52:41.000Z", "max_forks_repo_path": "engine/include/rev/gl/ProgramResource.h", "max_forks_repo_name": "eyebrowsoffire/rev", "max_forks_repo_head_hexsha": "d8abdf0a0016e309942932c9af9df1f8a2b02448", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6086956522, "max_line_length": 88, "alphanum_fraction": 0.6386165577, "num_tokens": 830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14608725448372273, "lm_q2_score": 0.033589507222162585, "lm_q1q2_score": 0.004906998889546908}}
{"text": "#pragma once\n\n#include <gsl\\gsl>\n#include <winrt\\Windows.Foundation.h>\n#include <d3d11.h>\n#include <map>\n#include \"DrawableGameComponent.h\"\n#include \"FullScreenRenderTarget.h\"\n#include \"Bloom.h\"\n\nnamespace Rendering\n{\n\tclass DiffuseLightingDemo;\n\n\tclass BloomDemo final : public Library::DrawableGameComponent\n\t{\n\tpublic:\n\t\tBloomDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera);\n\t\tBloomDemo(const BloomDemo&) = delete;\n\t\tBloomDemo(BloomDemo&&) = default;\n\t\tBloomDemo& operator=(const BloomDemo&) = default;\t\t\n\t\tBloomDemo& operator=(BloomDemo&&) = default;\n\t\t~BloomDemo();\n\n\t\tstd::shared_ptr<DiffuseLightingDemo> DiffuseLighting() const;\n\n\t\tbool BloomEnabled() const;\n\t\tvoid SetBloomEnabled(bool enabled);\n\t\tvoid ToggleBloom();\n\n\t\tLibrary::BloomDrawModes DrawMode() const;\n\t\tconst std::string& DrawModeString() const;\n\t\tvoid SetDrawMode(Library::BloomDrawModes drawMode);\n\t\t\n\t\tconst Library::BloomSettings& GetBloomSettings() const;\n\t\tvoid SetBloomSettings(Library::BloomSettings& settings);\n\n\t\tvirtual void Initialize() override;\n\t\tvirtual void Update(const Library::GameTime& gameTime) override;\n\t\tvirtual void Draw(const Library::GameTime& gameTime) override;\n\n\tprivate:\n\t\tstd::shared_ptr<DiffuseLightingDemo> mDiffuseLightingDemo;\t\t\n\t\tLibrary::FullScreenRenderTarget mRenderTarget;\n\t\tLibrary::Bloom mBloom;\n\t\tbool mBloomEnabled{ true };\n\t};\n}", "meta": {"hexsha": "bf59c208e0d6d3f4fc01fdfae0719fefc226605f", "size": 1370, "ext": "h", "lang": "C", "max_stars_repo_path": "source/7.3_Bloom/BloomDemo.h", "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/7.3_Bloom/BloomDemo.h", "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/7.3_Bloom/BloomDemo.h", "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5416666667, "max_line_length": 81, "alphanum_fraction": 0.7591240876, "num_tokens": 361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.2942149597859341, "lm_q2_score": 0.016657039826172955, "lm_q1q2_score": 0.004900750302610179}}
{"text": "#ifndef PETSC4PY_COMPAT_H\n#define PETSC4PY_COMPAT_H\n\n#include <petsc.h>\n#include \"compat/mpi.h\"\n#include \"compat/hdf5.h\"\n#include \"compat/tao.h\"\n\n#endif/*PETSC4PY_COMPAT_H*/\n", "meta": {"hexsha": "b55a49da37318045d2910ef4fc0e2879621e9833", "size": 174, "ext": "h", "lang": "C", "max_stars_repo_path": "src/include/compat.h", "max_stars_repo_name": "zonca/petsc4py", "max_stars_repo_head_hexsha": "33408c70b4211b801c24f8c3cdb859f5aaf59367", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/include/compat.h", "max_issues_repo_name": "zonca/petsc4py", "max_issues_repo_head_hexsha": "33408c70b4211b801c24f8c3cdb859f5aaf59367", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/include/compat.h", "max_forks_repo_name": "zonca/petsc4py", "max_forks_repo_head_hexsha": "33408c70b4211b801c24f8c3cdb859f5aaf59367", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.4, "max_line_length": 27, "alphanum_fraction": 0.7643678161, "num_tokens": 54, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.13117323055476696, "lm_q2_score": 0.0373268900213907, "lm_q1q2_score": 0.004896288750668313}}
{"text": "//  This matrix class is a C++ wrapper for the GNU Scientific Library\n//  Copyright (C)  ULP-IPB Strasbourg\n\n//  This program is free software; you can redistribute it and/or modify\n//  it under the terms of the GNU General Public License as published by\n//  the Free Software Foundation; either version 2 of the License, or\n//  (at your option) any later version.\n\n//  This program is distributed in the hope that it will be useful,\n//  but WITHOUT ANY WARRANTY; without even the implied warranty of\n//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n//  GNU General Public License for more details.\n\n//  You should have received a copy of the GNU General Public License\n//  along with this program; if not, write to the Free Software\n//  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\n#ifndef _vector_float_h\n#define _vector_float_h\n\n#ifdef __HP_aCC\n#include <iostream.h>\n#else \n#include <iostream>\n#endif\n\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_vector_float.h>\n#include <gsl/gsl_blas.h>\n#include <gslwrap/vector_double.h>\n\n//#define NDEBUG 0\n\n#include <assert.h>\nnamespace gsl\n{\n\n#ifndef __HP_aCC\n\tusing std::ostream;\n//using std::string;\n//using std::runtime_error;\n#endif\n\nclass vector_float_view;\n\nclass vector_float\n{\nprotected:\n\tgsl_vector_float *gsldata;\n\tvoid free(){if(gsldata) gsl_vector_float_free(gsldata);gsldata=NULL;}\n\tvoid alloc(size_t n) {gsldata=gsl_vector_float_alloc(n);}\n\tvoid calloc(size_t n){gsldata=gsl_vector_float_calloc(n);}\npublic:\n\ttypedef float value_type;\n\tvector_float() : gsldata(NULL) {;}\n\tvector_float( const vector_float &other ):gsldata(NULL) {copy(other);}\n\ttemplate<class oclass>\n\tvector_float( const oclass &other ):gsldata(NULL) {copy(other);}\n\t~vector_float(){free();}\n\tvector_float(const size_t& n,bool clear=true)\n\t{\n\t   this->gsldata = NULL;\n\t\tif(clear){this->calloc(n);}\n\t\telse     {this->alloc(n);}\n\t}\n\tvector_float(const int& n,bool clear=true)\n\t{\n\t   this->gsldata = NULL;\n\t\tif(clear){this->calloc(n);}\n\t\telse     {this->alloc(n);}\n\t}\n\t\n\tvoid resize(size_t n);\n\n\ttemplate <class oclass>\n\t\tvoid copy(const oclass &other)\n\t\t{\n\t\t\tif ( static_cast<const void *>( this ) == static_cast<const void *>( &other ) )\n\t\t\t\treturn;\n\n\t\t\tif (!other.is_set())\n\t\t\t{\n\t\t\t\tgsldata=NULL;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tresize(other.size());\n\t\t\tfor (size_t i=0;i<size();i++)\n\t\t\t{\n\t\t\t\tgsl_vector_float_set(gsldata, i, (float)other[i]);\n\t\t\t}\n\t\t}\n\tvoid copy(const vector_float& other);\n\tbool is_set() const{if (gsldata) return true; else return false;}\n//\tvoid clone(vector_float& other);\n\t\n//\tsize_t size() const {if (!gsldata) {cout << \"vector_float::size vector not initialized\" << endl; exit(-1);}return gsldata->size;}\n\tsize_t size() const {assert (gsldata); return gsldata->size;}\n\n\t/** for interfacing with gsl c */\n/*  \tgsl_vector_float       *gslobj()       {if (!gsldata){cout << \"vector_float::gslobj ERROR, data not initialized!! \" << endl; exit(-1);}return gsldata;} */\n/*  \tconst gsl_vector_float *gslobj() const {if (!gsldata){cout << \"vector_float::gslobj ERROR, data not initialized!! \" << endl; exit(-1);}return gsldata;} */\n\tgsl_vector_float       *gslobj()       {assert(gsldata);return gsldata;}\n\tconst gsl_vector_float *gslobj() const {assert(gsldata);return gsldata;}\n\n\n\tstatic vector_float_view create_vector_view( const gsl_vector_float_view &other );\n\n// ********Accessing vector elements\n\n//  Unlike FORTRAN compilers, C compilers do not usually provide support for range checking of vectors and matrices (2). However, the functions gsl_vector_float_get and gsl_vector_float_set can perform range checking for you and report an error if you attempt to access elements outside the allowed range. \n\n//  The functions for accessing the elements of a vector or matrix are defined in `gsl_vector_float.h' and declared extern inline to eliminate function-call overhead. If necessary you can turn off range checking completely without modifying any source files by recompiling your program with the preprocessor definition GSL_RANGE_CHECK_OFF. Provided your compiler supports inline functions the effect of turning off range checking is to replace calls to gsl_vector_float_get(v,i) by v->data[i*v->stride] and and calls to gsl_vector_float_set(v,i,x) by v->data[i*v->stride]=x. Thus there should be no performance penalty for using the range checking functions when range checking is turned off. \n\n//      This function returns the i-th element of a vector v. If i lies outside the allowed range of 0 to n-1 then the error handler is invoked and 0 is returned. \n\tfloat get(size_t i) const {return gsl_vector_float_get(gsldata,i);}\n\n//      This function sets the value of the i-th element of a vector v to x. If i lies outside the allowed range of 0 to n-1 then the error handler is invoked. \n\tvoid  set(size_t i,float x){gsl_vector_float_set(gsldata,i,x);}\n\n//      These functions return a pointer to the i-th element of a vector v. If i lies outside the allowed range of 0 to n-1 then the error handler is invoked\n\tfloat       &operator[](size_t i)       { return *gsl_vector_float_ptr(gsldata,i);}\n\tconst float &operator[](size_t i) const { return *gsl_vector_float_ptr(gsldata,i);}\n\n\tfloat       &operator()(size_t i)       { return *gsl_vector_float_ptr(gsldata,i);}\n\tconst float &operator()(size_t i) const { return *gsl_vector_float_ptr(gsldata,i);}\n\n\n//  ***** Initializing vector elements\n\n//      This function sets all the elements of the vector v to the value x. \n\tvoid set_all(float x){gsl_vector_float_set_all (gsldata,x);}\n//      This function sets all the elements of the vector v to zero. \n\tvoid set_zero(){gsl_vector_float_set_zero (gsldata);}\n\n//      This function makes a basis vector by setting all the elements of the vector v to zero except for the i-th element which is set to one. \n\tint set_basis (size_t i) {return gsl_vector_float_set_basis (gsldata,i);}\n\n//  **** Reading and writing vectors\n\n//  The library provides functions for reading and writing vectors to a file as binary data or formatted text. \n\n\n//      This function writes the elements of the vector v to the stream stream in binary format. The return value is 0 for success and GSL_EFAILED if there was a problem writing to the file. Since the data is written in the native binary format it may not be portable between different architectures. \n\tint fwrite (FILE * stream) const {return gsl_vector_float_fwrite (stream, gsldata);}\n\n//      This function reads into the vector v from the open stream stream in binary format. The vector v must be preallocated with the correct length since the function uses the size of v to determine how many bytes to read. The return value is 0 for success and GSL_EFAILED if there was a problem reading from the file. The data is assumed to have been written in the native binary format on the same architecture. \n\tint fread (FILE * stream) {return gsl_vector_float_fread (stream, gsldata);}\n\n\tvoid load( const char *filename );\n\t///\n\tvoid save( const char *filename ) const;\n\n//      This function writes the elements of the vector v line-by-line to the stream stream using the format specifier format, which should be one of the %g, %e or %f formats for floating point numbers and %d for integers. The function returns 0 for success and GSL_EFAILED if there was a problem writing to the file. \n\tint fprintf (FILE * stream, const char * format) const {return gsl_vector_float_fprintf (stream, gsldata,format) ;}\n\n//      This function reads formatted data from the stream stream into the vector v. The vector v must be preallocated with the correct length since the function uses the size of v to determine how many numbers to read. The function returns 0 for success and GSL_EFAILED if there was a problem reading from the file. \n\tint fscanf (FILE * stream)  {return gsl_vector_float_fscanf (stream, gsldata); }\n\n\n\n\n//  ******* Vector views\n\n//  In addition to creating vectors from slices of blocks it is also possible to slice vectors and create vector views. For example, a subvector of another vector can be described with a view, or two views can be made which provide access to the even and odd elements of a vector. \n\n//  A vector view is a temporary object, stored on the stack, which can be used to operate on a subset of vector elements. Vector views can be defined for both constant and non-constant vectors, using separate types that preserve constness. A vector view has the type gsl_vector_float_view and a constant vector view has the type gsl_vector_float_const_view. In both cases the elements of the view can be accessed as a gsl_vector_float using the vector component of the view object. A pointer to a vector of type gsl_vector_float * or const gsl_vector_float * can be obtained by taking the address of this component with the & operator. \n\n//      These functions return a vector view of a subvector of another vector v. The start of the new vector is offset by offset elements from the start of the original\n//      vector. The new vector has n elements. Mathematically, the i-th element of the new vector v' is given by, \n\n//      v'(i) = v->data[(offset + i)*v->stride]\n\n//      where the index i runs from 0 to n-1. \n\n//      The data pointer of the returned vector struct is set to null if the combined parameters (offset,n) overrun the end of the original vector. \n\n//      The new vector is only a view of the block underlying the original vector, v. The block containing the elements of v is not owned by the new vector. When the\n//      new vector goes out of scope the original vector v and its block will continue to exist. The original memory can only be deallocated by freeing the original vector.\n//      Of course, the original vector should not be deallocated while the new vector is still in use. \n\n//      The function gsl_vector_float_const_subvector is equivalent to gsl_vector_float_subvector but can be used for vectors which are declared const. \n\tvector_float_view subvector (size_t offset, size_t n);\n\tconst vector_float_view subvector (size_t offset, size_t n) const;\n//\tvector_float_const_view subvector (size_t offset, size_t n) const;\n\n//  \tclass view\n//  \t{\n//  \t\tgsl_vector_float_view *gsldata;\n//  \tpublic:\n//  \t\tview();\n//  \t};\n//  \tview subvector(size_t offset, size_t n)\n//  \t{\n//  \t\treturn view(gsl_vector_float_subvector(gsldata,offset,n);\n//  \t}\n//  \tconst view subvector(size_t offset, size_t n) const\n//  \t{\n//  \t\treturn view(gsl_vector_float_const_subvector(gsldata,offset,n);\n//  \t}\n\n\n\n//  Function: gsl_vector_float gsl_vector_float_subvector_with_stride (gsl_vector_float *v, size_t offset, size_t stride, size_t n) \n//  Function: gsl_vector_float_const_view gsl_vector_float_const_subvector_with_stride (const gsl_vector_float * v, size_t offset, size_t stride, size_t n) \n//      These functions return a vector view of a subvector of another vector v with an additional stride argument. The subvector is formed in the same way as for\n//      gsl_vector_float_subvector but the new vector has n elements with a step-size of stride from one element to the next in the original vector. Mathematically,\n//      the i-th element of the new vector v' is given by, \n\n//      v'(i) = v->data[(offset + i*stride)*v->stride]\n\n//      where the index i runs from 0 to n-1. \n\n//      Note that subvector views give direct access to the underlying elements of the original vector. For example, the following code will zero the even elements of the\n//      vector v of length n, while leaving the odd elements untouched, \n\n//      gsl_vector_float_view v_even = gsl_vector_float_subvector_with_stride (v, 0, 2, n/2);\n//      gsl_vector_float_set_zero (&v_even.vector);\n\n//      A vector view can be passed to any subroutine which takes a vector argument just as a directly allocated vector would be, using &view.vector. For example, the\n//      following code computes the norm of odd elements of v using the BLAS routine DNRM2, \n\n//      gsl_vector_float_view v_odd = gsl_vector_float_subvector_with_stride (v, 1, 2, n/2);\n//      double r = gsl_blas_dnrm2 (&v_odd.vector);\n\n//      The function gsl_vector_float_const_subvector_with_stride is equivalent to gsl_vector_float_subvector_with_stride but can be used for\n//      vectors which are declared const. \n\n//  Function: gsl_vector_float_view gsl_vector_float_complex_real (gsl_vector_float_complex *v) \n//  Function: gsl_vector_float_const_view gsl_vector_float_complex_const_real (const gsl_vector_float_complex *v) \n//      These functions return a vector view of the real parts of the complex vector v. \n\n//      The function gsl_vector_float_complex_const_real is equivalent to gsl_vector_float_complex_real but can be used for vectors which are declared\n//      const. \n\n//  Function: gsl_vector_float_view gsl_vector_float_complex_imag (gsl_vector_float_complex *v) \n//  Function: gsl_vector_float_const_view gsl_vector_float_complex_const_imag (const gsl_vector_float_complex *v) \n//      These functions return a vector view of the imaginary parts of the complex vector v. \n\n//      The function gsl_vector_float_complex_const_imag is equivalent to gsl_vector_float_complex_imag but can be used for vectors which are declared\n//      const. \n\n//  Function: gsl_vector_float_view gsl_vector_float_view_array (double *base, size_t n) \n//  Function: gsl_vector_float_const_view gsl_vector_float_const_view_array (const double *base, size_t n) \n//      These functions return a vector view of an array. The start of the new vector is given by base and has n elements. Mathematically, the i-th element of the new\n//      vector v' is given by, \n\n//      v'(i) = base[i]\n\n//      where the index i runs from 0 to n-1. \n\n//      The array containing the elements of v is not owned by the new vector view. When the view goes out of scope the original array will continue to exist. The\n//      original memory can only be deallocated by freeing the original pointer base. Of course, the original array should not be deallocated while the view is still in use. \n\n//      The function gsl_vector_float_const_view_array is equivalent to gsl_vector_float_view_array but can be used for vectors which are declared const. \n\n//  Function: gsl_vector_float_view gsl_vector_float_view_array_with_stride (double * base, size_t stride, size_t n) \n//  Function: gsl_vector_float_const_view gsl_vector_float_const_view_array_with_stride (const double * base, size_t stride, size_t n) \n//      These functions return a vector view of an array base with an additional stride argument. The subvector is formed in the same way as for\n//      gsl_vector_float_view_array but the new vector has n elements with a step-size of stride from one element to the next in the original array. Mathematically,\n//      the i-th element of the new vector v' is given by, \n\n//      v'(i) = base[i*stride]\n\n//      where the index i runs from 0 to n-1. \n\n//      Note that the view gives direct access to the underlying elements of the original array. A vector view can be passed to any subroutine which takes a vector\n//      argument just as a directly allocated vector would be, using &view.vector. \n\n//      The function gsl_vector_float_const_view_array_with_stride is equivalent to gsl_vector_float_view_array_with_stride but can be used for\n//      arrays which are declared const. \n\n\n//  ************* Copying vectors\n\n//  Common operations on vectors such as addition and multiplication are available in the BLAS part of the library (see section BLAS Support). However, it is useful to have a small number of utility functions which do not require the full BLAS code. The following functions fall into this category. \n\n//      This function copies the elements of the vector src into the vector dest.\n\tvector_float& operator=(const vector_float& other){copy(other);return (*this);}\n\n//  Function: int gsl_vector_float_swap (gsl_vector_float * v, gsl_vector_float * w) \n//      This function exchanges the elements of the vectors v and w by copying. The two vectors must have the same length. \n\n//  ***** Exchanging elements\n\n//  The following function can be used to exchange, or permute, the elements of a vector. \n\n//  Function: int gsl_vector_float_swap_elements (gsl_vector_float * v, size_t i, size_t j) \n//      This function exchanges the i-th and j-th elements of the vector v in-place. \n\tint swap_elements (size_t i, size_t j) {return gsl_vector_float_swap_elements (gsldata, i,j);}\n\n//  Function: int gsl_vector_float_reverse (gsl_vector_float * v) \n//      This function reverses the order of the elements of the vector v. \n\tint reverse () {return  gsl_vector_float_reverse (gsldata) ;}\n\n// ******* Vector operations\n\n//  The following operations are only defined for real vectors. \n\n//      This function adds the elements of vector b to the elements of vector a, a'_i = a_i + b_i. The two vectors must have the same length. \n\tint operator+=(const vector_float &other) {return gsl_vector_float_add (gsldata, other.gsldata);}\n\n//      This function subtracts the elements of vector b from the elements of vector a, a'_i = a_i - b_i. The two vectors must have the same length. \n\tint operator-=(const vector_float &other) {return gsl_vector_float_sub (gsldata, other.gsldata);}\n\n//  Function: int gsl_vector_float_mul (gsl_vector_float * a, const gsl_vector_float * b) \n//      This function multiplies the elements of vector a by the elements of vector b, a'_i = a_i * b_i. The two vectors must have the same length. \n\tint operator*=(const vector_float &other) {return gsl_vector_float_mul (gsldata, other.gsldata);}\n\n//      This function divides the elements of vector a by the elements of vector b, a'_i = a_i / b_i. The two vectors must have the same length. \n\tint operator/=(const vector_float &other) {return gsl_vector_float_div (gsldata, other.gsldata);}\n\n//      This function multiplies the elements of vector a by the constant factor x, a'_i = x a_i. \n\tint operator*=(float x) {return gsl_vector_float_scale (gsldata, x);}\n\n//  Function: int gsl_vector_float_add_constant (gsl_vector_float * a, const double x) \n//      This function adds the constant value x to the elements of the vector a, a'_i = a_i + x. \n\tint operator+=(float x) {return gsl_vector_float_add_constant (gsldata,x);}\n\n//      This function multiplies the elements of vector a by the constant factor x, a'_i = x a_i. \n\tint operator/=(float x) {return gsl_vector_float_scale (gsldata, 1/x);}\n\n// bool operators:\n\tbool operator==(const vector_float& other) const;\n\tbool operator!=(const vector_float& other) const { return (!((*this)==other));}\n\n// stream output:\n//\tfriend ostream& operator<< ( ostream& os, const vector_float& vect );\n\t/** returns sum of all the vector elements. */\n    float sum() const;\n\t// returns sqrt(v.t*v);\n    double norm2() const;\n\n\n// **** Finding maximum and minimum elements of vectors\n\n//      This function returns the maximum value in the vector v. \n    double max() const{return gsl_vector_float_max (gsldata) ;}\n\n//  Function: double gsl_vector_float_min (const gsl_vector_float * v) \n//      This function returns the minimum value in the vector v. \n    double min() const{return gsl_vector_float_min (gsldata) ;}\n\n//  Function: void gsl_vector_float_minmax (const gsl_vector_float * v, double * min_out, double * max_out) \n//      This function returns the minimum and maximum values in the vector v, storing them in min_out and max_out. \n\n//      This function returns the index of the maximum value in the vector v. When there are several equal maximum elements then the lowest index is returned. \n\tsize_t max_index(){return gsl_vector_float_max_index (gsldata);}\n\n//  Function: size_t gsl_vector_float_min_index (const gsl_vector_float * v) \n//      This function returns the index of the minimum value in the vector v. When there are several equal minimum elements then the lowest index is returned. \n\tsize_t min_index(){return gsl_vector_float_min_index (gsldata);}\n\n//  Function: void gsl_vector_float_minmax_index (const gsl_vector_float * v, size_t * imin, size_t * imax) \n//      This function returns the indices of the minimum and maximum values in the vector v, storing them in imin and imax. When there are several equal minimum\n//      or maximum elements then the lowest indices are returned. \n\n//  Vector properties\n\n//  Function: int gsl_vector_float_isnull (const gsl_vector_float * v) \n//      This function returns 1 if all the elements of the vector v are zero, and 0 otherwise. };\n\tbool isnull(){return gsl_vector_float_isnull (gsldata);}\n};\n\n// When you add create a view it will stick to its with the view until you call change_view\n// ex:\n// matrix_float m(5,5);\n// vector_float v(5); \n// // ... \n// m.column(3) = v; //the 3rd column of the matrix m will equal v. \nclass vector_float_view : public vector_float\n{\n public:\n\tvector_float_view(const vector_float&     other) :vector_float(){init(other);}\n\tvector_float_view(const vector_float_view& other):vector_float(){init(other);}\n\tvector_float_view(const gsl_vector_float& gsl_other) : vector_float() {init_with_gsl_vector(gsl_other);}\n\n\tvoid init(const vector_float& other);\n\tvoid init_with_gsl_vector(const gsl_vector_float& gsl_other);\n\tvoid change_view(const vector_float& other){init(other);}\n private:\n};\n\nostream& operator<< ( ostream& os, const vector_float & vect );\n\n\n// vector_type<>::type is a template interface to vector_?\n// it is usefull for in templated situations for getting the correct vector type\n#define tmp_type_is_float\n#ifdef tmp_type_is\ntypedef vector vector_double;\ntemplate<class T> \nstruct vector_type  {typedef vector_double   type;};\n\ntemplate<class T> \nstruct value_type  {typedef double   type;};\n\n#else\ntemplate<> struct vector_type<float> {typedef vector_float type;};\n#endif\n#undef tmp_type_is_float\n\n}\n#endif// _vector_float_h\n", "meta": {"hexsha": "1b3f2ff2181400f742773892a96310553c35fde0", "size": 21755, "ext": "h", "lang": "C", "max_stars_repo_path": "src/gslwrap/vector_float.h", "max_stars_repo_name": "entn-at/GlottDNN", "max_stars_repo_head_hexsha": "b7db669d7f34da92ab34742d75a8ba3c70763a65", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gslwrap/vector_float.h", "max_issues_repo_name": "entn-at/GlottDNN", "max_issues_repo_head_hexsha": "b7db669d7f34da92ab34742d75a8ba3c70763a65", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gslwrap/vector_float.h", "max_forks_repo_name": "entn-at/GlottDNN", "max_forks_repo_head_hexsha": "b7db669d7f34da92ab34742d75a8ba3c70763a65", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.849009901, "max_line_length": 693, "alphanum_fraction": 0.7451620317, "num_tokens": 5144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25091278688527247, "lm_q2_score": 0.0194193472247875, "lm_q1q2_score": 0.004872562531664214}}
{"text": "#pragma once\n\n#include <memory>\n#include <halley/maths/colour.h>\n#include <halley/maths/vector2.h>\n#include \"halley/maths/rect.h\"\n#include \"halley/data_structures/maybe.h\"\n#include <gsl/span>\n#include <map>\n#include \"halley/core/graphics/sprite/sprite.h\"\n#include \"halley/core/graphics/text/font.h\"\n\nnamespace Halley\n{\n\tclass LocalisedString;\n\tclass Painter;\n\tclass Material;\n\n\tusing ColourOverride = std::pair<size_t, std::optional<Colour4f>>;\n\n\tclass TextRenderer\n\t{\n\tpublic:\n\t\tusing SpriteFilter = std::function<void(gsl::span<Sprite>)>;\n\n\t\tTextRenderer();\n\t\texplicit TextRenderer(std::shared_ptr<const Font> font, String text = \"\", float size = 20, Colour colour = Colour(1, 1, 1, 1), float outline = 0, Colour outlineColour = Colour(0, 0, 0, 1));\n\n\t\tTextRenderer& setPosition(Vector2f pos);\n\t\tTextRenderer& setFont(std::shared_ptr<const Font> font);\n\t\tTextRenderer& setText(const String& text);\n\t\tTextRenderer& setText(const StringUTF32& text);\n\t\tTextRenderer& setText(const LocalisedString& text);\n\t\tTextRenderer& setSize(float size);\n\t\tTextRenderer& setColour(Colour colour);\n\t\tTextRenderer& setOutlineColour(Colour colour);\n\t\tTextRenderer& setOutline(float width);\n\t\tTextRenderer& setAlignment(float align);\n\t\tTextRenderer& setOffset(Vector2f align);\n\t\tTextRenderer& setClip(Rect4f clip);\n\t\tTextRenderer& setClip();\n\t\tTextRenderer& setSmoothness(float smoothness);\n\t\tTextRenderer& setPixelOffset(Vector2f offset);\n\t\tTextRenderer& setColourOverride(const std::vector<ColourOverride>& colOverride);\n\t\tTextRenderer& setLineSpacing(float spacing);\n\n\t\tTextRenderer clone() const;\n\n\t\tvoid generateSprites(std::vector<Sprite>& sprites) const;\n\t\tvoid draw(Painter& painter, const std::optional<Rect4f>& extClip = {}) const;\n\n\t\tvoid setSpriteFilter(SpriteFilter f);\n\n\t\tVector2f getExtents() const;\n\t\tVector2f getExtents(const StringUTF32& str) const;\n\t\tVector2f getCharacterPosition(size_t character) const;\n\t\tVector2f getCharacterPosition(size_t character, const StringUTF32& str) const;\n\t\tsize_t getCharacterAt(const Vector2f& position) const;\n\t\tsize_t getCharacterAt(const Vector2f& position, const StringUTF32& str) const;\n\n\t\tStringUTF32 split(const String& str, float width) const;\n\t\tStringUTF32 split(const StringUTF32& str, float width, std::function<bool(int32_t)> filter = {}) const;\n\t\tStringUTF32 split(float width) const;\n\n\t\tVector2f getPosition() const;\n\t\tString getText() const;\n\t\tconst StringUTF32& getTextUTF32() const;\n\t\tColour getColour() const;\n\t\tfloat getOutline() const;\n\t\tColour getOutlineColour() const;\n\t\tfloat getSmoothness() const;\n\t\tstd::optional<Rect4f> getClip() const;\n\t\tfloat getLineHeight() const;\n\t\tfloat getAlignment() const;\n\n\t\tbool empty() const;\n\n\tprivate:\n\t\tstd::shared_ptr<const Font> font;\n\t\tmutable std::map<const Font*, std::shared_ptr<Material>> materials;\n\t\tStringUTF32 text;\n\t\tSpriteFilter spriteFilter;\n\t\t\n\t\tfloat size = 20;\n\t\tfloat outline = 0;\n\t\tfloat align = 0;\n\t\tfloat smoothness = 1.0f;\n\t\tfloat lineSpacing = 0.0f;\n\n\t\tVector2f position;\n\t\tVector2f offset;\n\t\tVector2f pixelOffset;\n\t\tColour colour;\n\t\tColour outlineColour;\n\t\tstd::optional<Rect4f> clip;\n\n\t\tstd::vector<ColourOverride> colourOverrides;\n\n\t\tmutable Vector<Sprite> spritesCache;\n\t\tmutable bool materialDirty = true;\n\t\tmutable bool glyphsDirty = true;\n\t\tmutable bool positionDirty = true;\n\n\t\tstd::shared_ptr<Material> getMaterial(const Font& font) const;\n\t\tvoid updateMaterial(Material& material, const Font& font) const;\n\t\tvoid updateMaterialForFont(const Font& font) const;\n\t\tvoid updateMaterials() const;\n\t\tfloat getScale(const Font& font) const;\n\t};\n\n\tclass ColourStringBuilder {\n\tpublic:\n\t\tvoid append(std::string_view text, std::optional<Colour4f> col = {});\n\n\t\tstd::pair<String, std::vector<ColourOverride>> moveResults();\n\n\tprivate:\n\t\tstd::vector<String> strings;\n\t\tstd::vector<ColourOverride> colours;\n\t\tsize_t len = 0;\n\t};\n}\n", "meta": {"hexsha": "65b1409b0f1c54934b3957d3eead01371a2dce5d", "size": 3843, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engine/core/include/halley/core/graphics/text/text_renderer.h", "max_stars_repo_name": "akien-mga/halley", "max_stars_repo_head_hexsha": "cbc3713017de2e6e4b6d0e4e787b19695c1e6cec", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/engine/core/include/halley/core/graphics/text/text_renderer.h", "max_issues_repo_name": "akien-mga/halley", "max_issues_repo_head_hexsha": "cbc3713017de2e6e4b6d0e4e787b19695c1e6cec", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engine/core/include/halley/core/graphics/text/text_renderer.h", "max_forks_repo_name": "akien-mga/halley", "max_forks_repo_head_hexsha": "cbc3713017de2e6e4b6d0e4e787b19695c1e6cec", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.243902439, "max_line_length": 191, "alphanum_fraction": 0.7486338798, "num_tokens": 1002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18476750166984326, "lm_q2_score": 0.026355355713931997, "lm_q1q2_score": 0.004869613230883243}}
{"text": "#ifndef BATCH_EXTRACTOR_H_IVH3CLLQ\n#define BATCH_EXTRACTOR_H_IVH3CLLQ\n\n#include <gsl/gsl>\n#include <optional>\n#include <sens_loc/util/correctness_util.h>\n#include <string_view>\n\nnamespace sens_loc::apps {\n\n/// \\ingroup feature-plotter-driver\n/// Defines a strongly typed switch for the color to use. Will be mapped\n/// to the actual OpenCV-color using \\c color_to_bgr.\nenum class feature_color {\n    green,\n    blue,\n    red,\n    orange,\n    purple,  ///< Nice purple.\n    all      ///< Draws all keypoints with different colors.\n};\n\n/// Convert a color name to the corresponding \\c feature_color.\n/// The string must match with the enum-value, e.g. \"green\".\n/// \\ingroup feature-plotter-driver\ninline feature_color str_to_color(std::string_view color_string) noexcept {\n\n#define COLOR_SWITCH(COLOR)                                                    \\\n    if (color_string == #COLOR)                                                \\\n        return feature_color::COLOR;\n    COLOR_SWITCH(all)\n    COLOR_SWITCH(green)\n    COLOR_SWITCH(blue)\n    COLOR_SWITCH(red)\n    COLOR_SWITCH(purple)\n    COLOR_SWITCH(orange)\n\n    UNREACHABLE(\"Unexpected color to convert\");  // LCOV_EXCL_LINE\n}\n\n/// Provide a conversion from the \\\u00a2 feature_color to actual OpenCV colors.\n/// \\ingroup feature-plotter-driver\nstruct color_to_bgr {\n    // Color Space in BGR.\n    static cv::Scalar convert(feature_color c) {\n        using cv::Scalar;\n        switch (c) {\n        case feature_color::all: return Scalar::all(-1);\n        case feature_color::green: return Scalar(5, 117, 65);\n        case feature_color::blue: return Scalar(226, 144, 74);\n        case feature_color::red: return Scalar(27, 2, 208);\n        case feature_color::purple: return Scalar(254, 19, 144);\n        case feature_color::orange: return Scalar(35, 166, 245);\n        }\n        UNREACHABLE(\"Invalid enum-value!\");  // LCOV_EXCL_LINE\n    }\n};\n\n/// Helper class that visits a list of images plots keypoints onto them.\n/// \\ingroup feature-plotter-driver\nclass batch_plotter {\n  public:\n    batch_plotter(std::string_view                feature_file_pattern,\n                  std::string_view                output_file_pattern,\n                  feature_color                   color,\n                  std::optional<std::string_view> target_image_file_pattern)\n        : _feature_file_pattern{feature_file_pattern}\n        , _ouput_file_pattern{output_file_pattern}\n        , _color{color}\n        , _target_image_file_pattern{target_image_file_pattern} {\n        Expects(!_feature_file_pattern.empty());\n        Expects(!_ouput_file_pattern.empty());\n        if (_target_image_file_pattern)\n            Expects(!_target_image_file_pattern->empty());\n    }\n\n    /// Process a whole batch of files in the range [start, end].\n    [[nodiscard]] bool process_batch(int start, int end) const noexcept;\n\n  private:\n    /// Process a single feature file. Called in parallel from \\c process_batch.\n    [[nodiscard]] bool process_index(int idx) const noexcept;\n\n    /// The feature-detector creates files with the keypoints. This file-pattern\n    /// needs to be provided in order to plot those keypoints.\n    std::string_view _feature_file_pattern;\n\n    /// File pattern for the output image to be written to.\n    /// These images are 8-bit RGB images!\n    std::string_view _ouput_file_pattern;\n\n    /// Color to draw the keypoints in.\n    feature_color _color;\n\n    /// Even though the feature-files should have a path to the original image,\n    /// the features were detected on, this path might not be the desired target\n    /// for plotting. This is the case for plotting multiple feature keypoints\n    /// or if the path to the file is incorrect.\n    std::optional<std::string_view> _target_image_file_pattern;\n};\n}  // namespace sens_loc::apps\n\n#endif /* end of include guard: BATCH_EXTRACTOR_H_IVH3CLLQ */\n", "meta": {"hexsha": "0a0a75051f911fcc47828501feed835c31ec517f", "size": 3857, "ext": "h", "lang": "C", "max_stars_repo_path": "src/apps/keypoint_plotter/batch_plotter.h", "max_stars_repo_name": "JonasToth/depth-conversions", "max_stars_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-09-30T07:09:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T09:14:35.000Z", "max_issues_repo_path": "src/apps/keypoint_plotter/batch_plotter.h", "max_issues_repo_name": "JonasToth/depth-conversions", "max_issues_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/apps/keypoint_plotter/batch_plotter.h", "max_forks_repo_name": "JonasToth/depth-conversions", "max_forks_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.0865384615, "max_line_length": 80, "alphanum_fraction": 0.6689136635, "num_tokens": 876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10230470515565383, "lm_q2_score": 0.04742587250438209, "lm_q1q2_score": 0.00485188990331044}}
{"text": "#ifndef OPENMC_TALLIES_FILTER_SURFACE_H\n#define OPENMC_TALLIES_FILTER_SURFACE_H\n\n#include <cstdint>\n#include <unordered_map>\n\n#include <gsl/gsl>\n\n#include \"openmc/tallies/filter.h\"\n#include \"openmc/vector.h\"\n\nnamespace openmc {\n\n//==============================================================================\n//! Specifies which surface particles are crossing\n//==============================================================================\n\nclass SurfaceFilter : public Filter {\npublic:\n  //----------------------------------------------------------------------------\n  // Constructors, destructors\n\n  ~SurfaceFilter() = default;\n\n  //----------------------------------------------------------------------------\n  // Methods\n\n  std::string type() const override { return \"surface\"; }\n\n  void from_xml(pugi::xml_node node) override;\n\n  void get_all_bins(const Particle& p, TallyEstimator estimator,\n    FilterMatch& match) const override;\n\n  void to_statepoint(hid_t filter_group) const override;\n\n  std::string text_label(int bin) const override;\n\n  //----------------------------------------------------------------------------\n  // Accessors\n\n  void set_surfaces(gsl::span<int32_t> surfaces);\n\nprivate:\n  //----------------------------------------------------------------------------\n  // Data members\n\n  //! The indices of the surfaces binned by this filter.\n  vector<int32_t> surfaces_;\n\n  //! A map from surface indices to filter bin indices.\n  std::unordered_map<int32_t, int> map_;\n};\n\n} // namespace openmc\n#endif // OPENMC_TALLIES_FILTER_SURFACE_H\n", "meta": {"hexsha": "368fd09d064f65d9e380f207abee41b0b24a018b", "size": 1559, "ext": "h", "lang": "C", "max_stars_repo_path": "include/openmc/tallies/filter_surface.h", "max_stars_repo_name": "stu314159/openmc", "max_stars_repo_head_hexsha": "2efe223404680099f9a77214e743ab78e37cd08c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-09T17:55:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-09T17:55:14.000Z", "max_issues_repo_path": "include/openmc/tallies/filter_surface.h", "max_issues_repo_name": "huak95/openmc", "max_issues_repo_head_hexsha": "922f688978693761f82c4a3764ab05dd96cc8cff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/openmc/tallies/filter_surface.h", "max_forks_repo_name": "huak95/openmc", "max_forks_repo_head_hexsha": "922f688978693761f82c4a3764ab05dd96cc8cff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.350877193, "max_line_length": 80, "alphanum_fraction": 0.5137908916, "num_tokens": 283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12765263195921103, "lm_q2_score": 0.03789242622217325, "lm_q1q2_score": 0.004837067938580639}}
{"text": "#include <stdlib.h>\n#include <gsl/block/gsl_block.h>\n\n\n\n#define BASE_DOUBLE\n#include <gsl/templates_on.h>\n#include <gsl/block/init_source.c>\n#include <gsl/templates_off.h>\n#undef BASE_DOUBLE", "meta": {"hexsha": "ffe5d38c2053dafeaa3e4e5312319676da984314", "size": 190, "ext": "c", "lang": "C", "max_stars_repo_path": "Cartwheel/cartwheel-3d/gsl/block/init.c", "max_stars_repo_name": "MontyThibault/centre-of-mass-awareness", "max_stars_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Cartwheel/cartwheel-3d/gsl/block/init.c", "max_issues_repo_name": "MontyThibault/centre-of-mass-awareness", "max_issues_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cartwheel/cartwheel-3d/gsl/block/init.c", "max_forks_repo_name": "MontyThibault/centre-of-mass-awareness", "max_forks_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.0, "max_line_length": 34, "alphanum_fraction": 0.7684210526, "num_tokens": 47, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22000710997428738, "lm_q2_score": 0.02194825555415603, "lm_q1q2_score": 0.004828772273446969}}
{"text": "/**\n* Copyright 2017 BitTorrent Inc.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n*    http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*/\n#pragma once\n\n#include <okui/config.h>\n\n#include <okui/opengl/Framebuffer.h>\n#include <okui/shaders/ColorShader.h>\n#include <okui/shaders/DistanceFieldShader.h>\n#include <okui/shaders/TextureShader.h>\n#include <okui/Application.h>\n#include <okui/Color.h>\n#include <okui/Point.h>\n#include <okui/Rectangle.h>\n#include <okui/RenderTarget.h>\n#include <okui/Relation.h>\n#include <okui/Responder.h>\n#include <okui/ShaderCache.h>\n#include <okui/TextureHandle.h>\n#include <okui/TouchpadFocus.h>\n#include <okui/WeakTexture.h>\n\n#include <scraps/AbstractTaskScheduler.h>\n#include <scraps/TreeNode.h>\n#include <scraps/utility.h>\n\n#include <stdts/optional.h>\n\n#include <gsl.h>\n\n#include <list>\n#include <typeindex>\n#include <unordered_map>\n\nnamespace okui {\n\nclass Application;\nclass BitmapFont;\nclass Window;\n\n/**\n* View rendering can be cached or buffered to a texture. One reason this may be done is to apply post-rendering\n* effects such as tinting or reflection. When this is done, the contents of the view are clipped to its bounds.\n*/\nclass View : public Responder, private scraps::TreeNode<View> {\npublic:\n    using Relation = okui::Relation;\n\n    View() = default;\n    explicit View(std::string name) : _name{std::move(name)} {}\n    View(const View&) = delete;\n    View(View&&) = delete;\n    View& operator=(const View&) = delete;\n    View& operator=(View&&) = delete;\n\n    /**\n    * It is an error to destroy a focused view. Remove the view first if needed.\n    */\n    virtual ~View();\n\n    std::string name() const       { return _name.empty() ? scraps::Demangle(typeid(*this).name()) : _name; }\n    void setName(std::string name) { _name = std::move(name); }\n\n    void addSubview(View* view);\n    template <typename... Views>\n    void addSubviews(View* view, Views&&... views)  { _addSubviews(view, std::forward<Views>(views)...); }\n    void addHiddenSubview(View* view);\n    void removeSubview(View* view);\n    template <typename... Views>\n    void removeSubviews(View* view, Views&&... views) { _removeSubviews(view, std::forward<Views>(views)...); }\n    void removeSubviews();\n\n    Window* window() const                    { return _window; }\n    Application* application() const;\n\n    const View* superview() const             { return parent(); }\n    View* superview()                         { return parent(); }\n    const std::list<View*>& subviews() const  { return children(); }\n\n    const Rectangle<double>& bounds() const   { return _bounds; }\n    math::Vector<double, 2> size() const      { return _bounds.size(); }\n    Point<double> position() const            { return _bounds.position(); }\n\n    double width() const                      { return _bounds.width; }\n    double height() const                     { return _bounds.height; }\n\n    template <typename... Args>\n    void setBounds(Args&&... args)            { _setBounds(Rectangle<double>(std::forward<Args>(args)...)); }\n\n    void setPosition(double x, double y)      { _setBounds({x, y, _bounds.width, _bounds.height}); }\n    void setPosition(const Point<double>& p)  { setPosition(p.x, p.y); }\n\n    void setSize(double width, double height) { _setBounds({_bounds.x, _bounds.y, width, height}); }\n    void setSize(const math::Vector<double, 2>& s) { setSize(s.x, s.y); }\n\n    Rectangle<double> windowBounds() const;\n\n    /**\n    * Sets bounds as a percent of superview bounds (0-1)\n    */\n    void setBoundsRelative(double x, double y, double width, double height);\n\n    void setInterceptsInteractions(bool intercepts);\n    void setInterceptsInteractions(bool intercepts, bool childrenIntercept);\n    void setChildrenInterceptInteractions(bool childrenIntercept);\n\n    ShaderCache* shaderCache();\n\n    void setIsVisible(bool isVisible = true);\n    bool isVisible() const { return _isVisible; }\n\n    void show() { setIsVisible(); }\n    void hide() { setIsVisible(false); }\n\n    /**\n    * Allows scaling of the view by a particular factor.\n    */\n    void setScale(double scale) { setScale(scale, scale); }\n    void setScale(double scaleX, double scaleY);\n\n    /**\n    * Sets the view's background color.\n    */\n    void setBackgroundColor(const Color& color) { _backgroundColor = color; }\n    const Color& backgroundColor() const        { return _backgroundColor; }\n\n    /**\n    * Sets the view's tint. If this is anything but opaque white, this is a post-rendering effect that\n    * clips the view's contents.\n    */\n    void setTintColor(const Color& color);\n    const Color& tintColor() const        { return _tintColor; }\n\n    /**\n    * Sets the view's opacity. If this is anything but 1, this is a post-rendering effect that\n    * clips the view's contents.\n    *\n    * This effectively sets the alpha component of the view's tint color.\n    */\n    void setOpacity(double opacity)  { setTintColor(_tintColor.withAlphaF(opacity)); }\n    double opacity() const           { return _tintColor.alphaF(); }\n\n    /**\n    * Returns true if the view's ancestors are visible or if the view has no ancestors.\n    */\n    bool ancestorsAreVisible() const;\n\n    /**\n    * Returns true if the view and its ancestors are visible and in an open window.\n    */\n    bool isVisibleInOpenWindow() const;\n\n    /**\n    * Arranges the view so it's behind all of its current siblings.\n    */\n    void sendToBack();\n\n    /**\n    * Arranges the view so it's in front of all of its current siblings.\n    */\n    void bringToFront();\n\n    /**\n    * Override this if the view can become focused.\n    */\n    virtual bool canBecomeDirectFocus() { return false; }\n\n    /**\n    * Makes the view the current focus. If the view has a preferred focus, the preferred focus will\n    * become the focus instead.\n    */\n    void focus();\n\n    /**\n    * Returns the view that would become focused if an attempt to give focus to this view is made.\n    */\n    View* expectedFocus();\n\n    /**\n    * Sets the focus to the next ancestor that can be focused which doesn't result in this view\n    * retaining focus (which would otherwise happen if your ancestor's preferred focus was you)\n    */\n    void focusAncestor();\n\n    /**\n    * If the view or any of its children are focused, unfocuses them.\n    */\n    void unfocus();\n\n    /**\n    * If this view would receive focus and has a preferred focus, the preferred focus will become focus instead.\n    */\n    View* preferredFocus() const       { return _preferredFocus; }\n    void setPreferredFocus(View* view) { _preferredFocus = view; }\n\n    View* nextFocus() const     { return _nextFocus; }\n    View* previousFocus() const { return _previousFocus; }\n\n    /**\n    * If the view receives an unhandled tab key down, focus will change to the given\n    * view (and shift+tab will do the opposite).\n    */\n    void setNextFocus(View* view);\n\n    /**\n    * Returns the next available visible and focusable view if there is one.\n    */\n    View* nextAvailableFocus();\n\n    /**\n    * Returns the previous available visible and focusable view.\n    */\n    View* previousAvailableFocus();\n\n    /**\n    * Returns true if the view or any of its children has focus.\n    */\n    bool isFocus() const;\n\n    TouchpadFocus& touchpadFocus() { return _touchpadFocus; }\n\n    /**\n    * @param rendersToTexture if true, the view is rendered to a texture, making it available via renderTexture\n    */\n    void setRendersToTexture(bool rendersToTexture = true) { _rendersToTexture = rendersToTexture; }\n\n    /**\n    * If the view is set to render to a texture, this can be used to obtain said texture.\n    */\n    std::shared_ptr<TextureInterface> renderTexture() const;\n\n    /**\n    * @param caches if true, the view will render to a texture and the render() method will only be called when\n    *               the cache is invalid\n    */\n    void setCachesRender(bool cachesRender = true) { _cachesRender = cachesRender; }\n\n    /**\n    * Invalidates the view's render cache.\n    */\n    void invalidateRenderCache();\n\n    /**\n    * @param clipsToBounds if true, the view will not render itself or any subviews outside of its bounds\n    */\n    void setClipsToBounds(bool clipsToBounds = true) { _clipsToBounds = clipsToBounds; }\n\n    /**\n    * @return if true, the view will not render itself or any subviews outside of its bounds\n    */\n    bool clipsToBounds() const { return _clipsToBounds; }\n\n    /**\n    * Returns true if the mouse is hovering directly over this view.\n    */\n    bool hasMouse() const;\n\n    shaders::ColorShader* colorShader() { return shader<shaders::ColorShader>(\"color shader\"); }\n    shaders::TextureShader* textureShader() { return shader<shaders::TextureShader>(\"texture shader\"); }\n    shaders::DistanceFieldShader* distanceFieldShader() { return shader<shaders::DistanceFieldShader>(\"distance field shader\"); }\n\n    /**\n    * Begins loading a texture associated with the view. When the texture is loaded, the view's\n    * render cache will be invalidated. If the texture should not be associated with the view,\n    * use Window::loadTexture* instead.\n    */\n    TextureHandle loadTextureResource(const std::string& name);\n    TextureHandle loadTextureFromMemory(std::shared_ptr<const std::string> data);\n    TextureHandle loadTextureFromURL(const std::string& url);\n\n    /**\n    * Get or create a shader cached via the window's shader cache.\n    */\n    template <typename T>\n    T* shader(const char* identifier);\n\n    const AffineTransformation& renderTransformation() const { return _renderTransformation; }\n\n    /**\n    * Converts a point from local coordinates to superview coordinates.\n    */\n    Point<double> localToSuperview(double x, double y) const { return localToAncestor(x, y, superview()); }\n    Point<double> localToSuperview(const Point<double>& p) const { return localToSuperview(p.x, p.y); }\n\n    /**\n    * Converts a point from local coordinates to the coordinates of an ancestor.\n    */\n    Point<double> localToAncestor(double x, double y, const View* ancestor) const;\n    Point<double> localToAncestor(const Point<double>& p, const View* ancestor) const { return localToAncestor(p.x, p.y, ancestor); }\n\n    /**\n    * Converts a point from super coordinates to local coordinates.\n    */\n    Point<double> superviewToLocal(double x, double y) const;\n    Point<double> superviewToLocal(const Point<double>& p) const;\n\n    /**\n    * Converts a point from local coordinates to window coordinates.\n    */\n    Point<double> localToWindow(double x, double y) const;\n    Point<double> localToWindow(const Point<double>& p) const;\n\n    /**\n    * Returns true if this view has the given relation to the given view.\n    *\n    * For example, hasRelation(kDescendant, superview()) should return true.\n    */\n    bool hasRelation(Relation relation, const View* view) const;\n\n    /**\n    * Returns the first view that both views have in their hierarchy, if any.\n    */\n    const View* commonView(const View* other) const { return commonNode(other); }\n\n    using TreeNode::isDescendantOf;\n    using TreeNode::isAncestorOf;\n\n    /**\n    * Posts a message to listeners with the given relation. The view and its potential listeners must have an\n    * associated application for the message to be delivered.\n    *\n    * For example, post(message, Relation::kAncestor) posts the message to listeners that are ancestors of this view.\n    */\n    template <typename T>\n    void post(T& message, Relation relation = Relation::kHierarchy) {\n        _post(std::type_index(typeid(typename std::decay_t<T>)), &message, relation);\n    }\n    template <typename T>\n    void post(T&& message, Relation relation = Relation::kHierarchy) {\n        T m = std::move(message);\n        _post(std::type_index(typeid(typename std::decay_t<T>)), &m, relation);\n    }\n\n    template <typename T>\n    struct ListenerAction : ListenerAction<decltype(&T::operator())> {};\n\n    template <typename C, typename R, typename... Args>\n    struct ListenerAction<R(C::*)(Args...) const> {\n        using ArgumentTuple = std::tuple<Args...>;\n        using ArgumentCount = std::tuple_size<ArgumentTuple>;\n        using MessageType = typename std::decay<typename std::tuple_element<0, ArgumentTuple>::type>::type;\n    };\n\n    /**\n    * Listens for messages from senders with the given relation.\n    *\n    * For example, listen([](const Message& message) {}, Relation::kAncestor) listens for messages from posters that\n    * are ancestors of this view.\n    *\n    * @param action an action that takes a constant reference to the message type to listen for and optionally a View pointer to the sender\n    */\n    template <typename Action>\n    auto listen(Action&& action, Relation relation = Relation::kHierarchy) -> typename std::enable_if<ListenerAction<Action>::ArgumentCount::value == 1, void>::type {\n        using MessageType = typename ListenerAction<Action>::MessageType;\n        _listen(std::type_index(typeid(MessageType)),\n            [action = std::forward<Action>(action)](const void* message, View* sender) {\n                action(*reinterpret_cast<const MessageType*>(message));\n            }, relation\n        );\n    }\n\n    template <typename Action>\n    auto listen(Action&& action, Relation relation = Relation::kHierarchy) -> typename std::enable_if<ListenerAction<Action>::ArgumentCount::value == 2, void>::type {\n        using MessageType = typename ListenerAction<Action>::MessageType;\n        _listen(std::type_index(typeid(MessageType)),\n            [action = std::forward<Action>(action)](const void* message, View* sender) {\n                action(*reinterpret_cast<const MessageType*>(message), sender);\n            }, relation\n        );\n    }\n\n    /**\n    * Makes the given object available via get(). This can be used to store arbitrary state with the view.\n    *\n    * @param relation the object will only be available to views of the given relation\n    */\n    template <typename T>\n    auto set(T&& object, Relation relation = Relation::kHierarchy) {\n        _provisions.emplace_front(std::forward<T>(object), relation);\n        return stdts::any_cast<std::decay_t<T>>(&_provisions.front().object);\n    }\n\n    /**\n    * Finds an object provided via provide. It will return a pointer to the first object it finds of the\n    * specified type. If more than one objects of the given type has been provided, it is undefined\n    * which one will be returned.\n    *\n    * @param relation only objects from views of the given relation will be returned\n    */\n    template <typename T>\n    T* find(Relation relation = Relation::kHierarchy);\n\n    template <typename T>\n    T* get() { return find<T>(Relation::kSelf); }\n\n    template <typename T>\n    T* inherit() { return find<T>(Relation::kAncestor); }\n\n    /**\n    * Asynchronously schedules a function to be invoked using the application's task scheduler.\n    *\n    * If the view is destroyed, the invocation will be canceled.\n    */\n    template <typename... Args>\n    auto async(Args&&... args) -> decltype(std::declval<scraps::AbstractTaskScheduler>().async(std::forward<Args>(args)...)) {\n        return _taskScheduler()->async(_taskScope, std::forward<Args>(args)...);\n    }\n\n    /**\n    * Asynchronously schedules a function to be invoked after a delay using the application's task scheduler.\n    *\n    * If the view is destroyed, the invocation will be canceled.\n    */\n    template <typename... Args>\n    auto asyncAfter(Args&&... args) -> decltype(std::declval<scraps::AbstractTaskScheduler>().asyncAfter(std::forward<Args>(args)...)) {\n        return _taskScheduler()->asyncAfter(_taskScope, std::forward<Args>(args)...);\n    }\n\n    /**\n    * Asynchronously schedules a function to be invoked at a time using the application's task scheduler.\n    *\n    * If the view is destroyed, the invocation will be canceled.\n    */\n    template <typename... Args>\n    auto asyncAt(Args&&... args) -> decltype(std::declval<scraps::AbstractTaskScheduler>().asyncAt(std::forward<Args>(args)...)) {\n        return _taskScheduler()->asyncAt(_taskScope, std::forward<Args>(args)...);\n    }\n\n    /**\n    * The hook provided here will be called before rendering each frame.\n    */\n    void addUpdateHook(const std::string& handle, std::function<void()> hook);\n\n    /**\n    * The hook provided here will no longer be called.\n    */\n    void removeUpdateHook(const std::string& handle);\n\n    /**\n    * Override this to do drawing.\n    */\n    virtual void render() {}\n\n    virtual void render(const RenderTarget* renderTarget, const Rectangle<int>& area) { render(); }\n\n    /**\n    * Override this to implement custom post-render effects. For this method to be called, the view must be\n    * set to render to texture. The default implementation provides the built-in effects such as tint and\n    * opacity. If this is overridden, you will need to provide those effects in your implementation in\n    * order to use them.\n    *\n    * @param texture the view, rendered to a texture with premultiplied alpha\n    */\n    virtual void postRender(std::shared_ptr<TextureInterface> texture, const AffineTransformation& transformation);\n\n    /**\n    * Override this to lay out subviews whenever the view is resized.\n    */\n    virtual void layout() {}\n\n    /**\n    * Override this to do any sort of setup that requires the view to be attached to a window.\n    */\n    virtual void windowChanged() {}\n\n    /**\n    * Override this if you want odd-shaped views to have accurate hit boxes.\n    */\n    virtual bool hitTest(double x, double y);\n    bool hitTest(const Point<double>& p) { return hitTest(p.x, p.y); }\n\n    /**\n    * Return the most descendant visible view which intersects with (x, y)\n    */\n    View* hitTestView(double x, double y);\n    View* hitTestView(const Point<double>& p) { return hitTestView(p.x, p.y); }\n\n    /**\n    * Override these to handle mouse events. Call the base implementation to pass on the event.\n    */\n    virtual void mouseDown(MouseButton button, double x, double y);\n    virtual void mouseUp(MouseButton button, double startX, double startY, double x, double y);\n    virtual void mouseWheel(double xPos, double yPos, int xWheel, int yWheel);\n    virtual void mouseDrag(double startX, double startY, double x, double y);\n    virtual void mouseMovement(double x, double y);\n    virtual void mouseEnter() {}\n    virtual void mouseExit() {}\n\n    /**\n    * Called whenever the view or one of its subviews gains focus.\n    */\n    virtual void focusGained() {}\n\n    /**\n    * Called whenever the view and its subviews lose focus.\n    */\n    virtual void focusLost() {}\n\n    /**\n    * Called whenever the view or any subview gains or loses focus.\n    */\n    virtual void focusChanged() {}\n\n    /**\n    * Called before the view and all of its ancestors become visible in the window.\n    */\n    virtual void willAppear() {}\n\n    /**\n    * Called when the view and all of its ancestors become visible in the window.\n    */\n    virtual void appeared() {}\n\n    /**\n    * Called before the view or one of its ancestors become invisible in the window.\n    */\n    virtual void willDisappear() {}\n\n    /**\n    * Called when the view or one of its ancestors become invisible in the window.\n    */\n    virtual void disappeared() {}\n\n    /**\n    * Renders the view and its subviews.\n    *\n    * @param area the area within the target to render to. the view will fill this area\n    * @param clipBounds the bounds within the target to clip rendering of the view and its children to\n    */\n    void renderAndRenderSubviews(const RenderTarget* target, const Rectangle<int>& area, stdts::optional<Rectangle<int>> clipBounds = stdts::nullopt);\n\n    bool dispatchMouseDown(MouseButton button, double x, double y);\n    bool dispatchMouseUp(MouseButton button, double startX, double startY, double x, double y);\n    bool dispatchMouseMovement(double x, double y);\n    bool dispatchMouseWheel(double xPos, double yPos, int xWheel, int yWheel);\n    void dispatchUpdate(std::chrono::high_resolution_clock::duration elapsed);\n\n    // Responder overrides\n    virtual Responder* nextResponder() override;\n    virtual void keyDown(KeyCode key, KeyModifiers mod, bool repeat) override;\n    virtual void touchUp(size_t finger, Point<double> position, double pressure) override;\n    virtual void touchDown(size_t finger, Point<double> position, double pressure) override;\n    virtual void touchMovement(size_t finger, Point<double> position, Point<double> distance, double pressure) override;\n\nprivate:\n    friend class scraps::TreeNode<View>;\n    friend class Window;\n\n    struct Listener {\n        Listener(std::type_index index, std::function<void(const void*, View*)> action, Relation relation)\n            : index{index}, action{std::move(action)}, relation{relation} {}\n\n        std::type_index index;\n        std::function<void(const void*, View*)> action;\n        Relation relation;\n    };\n\n    struct Provision {\n        Provision(stdts::any object, Relation relation)\n            : object{std::move(object)}, relation{relation} {}\n\n        stdts::any object;\n        Relation relation;\n    };\n\n    void _addSubviews() {}\n    template <typename... Views>\n    void _addSubviews(View* view, Views&&... views);\n\n    void _removeSubviews() {}\n    template <typename... Views>\n    void _removeSubviews(View* view, Views&&... views);\n\n    void _setBounds(const Rectangle<double>& bounds);\n\n    void _invalidateSuperviewRenderCache();\n\n    void _dispatchFutureVisibilityChange(bool visible);\n    void _dispatchVisibilityChange(bool visible);\n    void _dispatchWindowChange(Window* window);\n    void _mouseExit();\n\n    void _updateFocusableRegions(std::vector<std::tuple<View*, Rectangle<double>>>& regions);\n\n    bool _requiresTextureRendering();\n    void _renderAndRenderSubviews(const RenderTarget* target, const Rectangle<int>& area, bool shouldClear = false, stdts::optional<Rectangle<int>> clipBounds = stdts::nullopt);\n\n    void _post(std::type_index index, const void* ptr, Relation relation);\n    void _listen(std::type_index index, std::function<void(const void*, View*)> action, Relation relation);\n\n    template <typename F>\n    void _traverseRelation(Relation relation, F&& function);\n\n    std::vector<View*> _topViewsForRelation(Relation relation);\n\n    scraps::AbstractTaskScheduler* _taskScheduler() const;\n    void _updateTouchFocus(std::chrono::high_resolution_clock::duration elapsed);\n\n    void _checkUpdateSubscription();\n    bool _shouldSubscribeToUpdates();\n\n    std::string _name;\n    bool _isVisible                     = true;\n    bool _rendersToTexture              = false;\n    bool _cachesRender                  = false;\n    bool _hasCachedRender               = false;\n    bool _clipsToBounds                 = true;\n    bool _interceptsInteractions        = true;\n    bool _childrenInterceptInteractions = true;\n\n    Window* _window                     = nullptr;\n    View*   _subviewWithMouse           = nullptr;\n    View*   _nextFocus                  = nullptr;\n    View*   _previousFocus              = nullptr;\n    View*   _preferredFocus             = nullptr;\n\n    Rectangle<double>    _bounds;\n    Point<double>        _scale{1.0, 1.0};\n    Color                _backgroundColor = Color::kTransparentBlack;\n    Color                _tintColor = Color::kWhite;\n    AffineTransformation _renderTransformation;\n\n    std::unique_ptr<opengl::Framebuffer> _renderCache;\n    opengl::Framebuffer::Attachment*     _renderCacheColorAttachment = nullptr;\n    std::shared_ptr<WeakTexture>         _renderCacheTexture = std::make_shared<WeakTexture>();\n\n    std::list<Listener>                               _listeners;\n    std::list<Provision>                              _provisions;\n    TouchpadFocus                                     _touchpadFocus;\n    std::unordered_map<size_t, std::function<void()>> _updateHooks;\n\n    scraps::AbstractTaskScheduler::TaskScope          _taskScope; /* must be the last member */\n};\n\ntemplate <typename... Views>\nvoid View::_addSubviews(View* view, Views&&... views) {\n    addSubview(view);\n    _addSubviews(std::forward<Views>(views)...);\n}\n\ntemplate <typename... Views>\nvoid View::_removeSubviews(View* view, Views&&... views) {\n    removeSubview(view);\n    _removeSubviews(std::forward<Views>(views)...);\n}\n\ntemplate <typename T>\nT* View::shader(const char* identifier) {\n    auto s = shaderCache()->get(std::string(identifier));\n    if (!s) {\n        s = shaderCache()->add(std::make_unique<T>(), std::string(identifier), ShaderCache::Policy::kKeepForever);\n    }\n    auto ret = dynamic_cast<T*>(s->get());\n    ret->setTransformation(renderTransformation());\n    return ret;\n}\n\ntemplate <typename T>\nT* View::find(Relation relation) {\n    T* ret = nullptr;\n    _traverseRelation(relation, [&](View* view, bool* shouldContinue) {\n        for (auto& provision : view->_provisions) {\n            if (!hasRelation(provision.relation, view)) { continue; }\n            if (auto object = stdts::any_cast<T>(&provision.object)) {\n                ret = object;\n                *shouldContinue = false;\n                return 1;\n            }\n            if (auto pointer = stdts::any_cast<T*>(&provision.object)) {\n                ret = *pointer;\n                *shouldContinue = false;\n                return 1;\n            }\n        }\n        return 0;\n    });\n    if (!ret && application() && (relation == Relation::kHierarchy || relation == Relation::kAny || relation == Relation::kAncestor)) {\n        return application()->get<T>();\n    }\n    return ret;\n}\n\ntemplate <typename F>\nvoid View::_traverseRelation(Relation relation, F&& function) {\n    switch (relation) {\n        case Relation::kAny: {\n            bool shouldContinue = true;\n            for (auto& v : _topViewsForRelation(relation)) {\n                v->TreeNode::traverseRelation(TreeNode::Relation::kCommonRoot, function, 0, &shouldContinue);\n            }\n            break;\n        }\n        case Relation::kHierarchy:  TreeNode::traverseRelation(TreeNode::Relation::kCommonRoot, function, 0); break;\n        case Relation::kDescendant: TreeNode::traverseRelation(TreeNode::Relation::kDescendant, function, 0); break;\n        case Relation::kAncestor:   TreeNode::traverseRelation(TreeNode::Relation::kAncestor,   function, 0); break;\n        case Relation::kSibling:    TreeNode::traverseRelation(TreeNode::Relation::kSibling,    function, 0); break;\n        case Relation::kSelf:       TreeNode::traverseRelation(TreeNode::Relation::kSelf,       function, 0); break;\n    }\n}\n\n} // namespace okui\n", "meta": {"hexsha": "1ebaf894681c63737a162eb666ec3bcc37d02dd3", "size": 26920, "ext": "h", "lang": "C", "max_stars_repo_path": "include/okui/View.h", "max_stars_repo_name": "bittorrent/okui", "max_stars_repo_head_hexsha": "e569404b6d121e89451d57e7d321f420e5f86535", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2017-01-20T22:14:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T10:00:31.000Z", "max_issues_repo_path": "include/okui/View.h", "max_issues_repo_name": "bittorrent/okui", "max_issues_repo_head_hexsha": "e569404b6d121e89451d57e7d321f420e5f86535", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-01-25T17:46:17.000Z", "max_issues_repo_issues_event_max_datetime": "2017-01-25T20:30:59.000Z", "max_forks_repo_path": "include/okui/View.h", "max_forks_repo_name": "bittorrent/okui", "max_forks_repo_head_hexsha": "e569404b6d121e89451d57e7d321f420e5f86535", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2017-01-21T07:00:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-26T03:38:20.000Z", "avg_line_length": 37.6503496503, "max_line_length": 177, "alphanum_fraction": 0.6643016345, "num_tokens": 6124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22000709974589316, "lm_q2_score": 0.021948252195455986, "lm_q1q2_score": 0.004828771310013704}}
{"text": "#pragma once\n\n#include <cstdint>\n#include <functional>\n#include <memory>\n#include <sstream>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include <gsl/gsl>\n#include <nonstd/optional.hpp>\n\n#include \"chainerx/array_body.h\"\n#include \"chainerx/array_fwd.h\"\n#include \"chainerx/array_index.h\"\n#include \"chainerx/array_node.h\"\n#include \"chainerx/array_repr.h\"\n#include \"chainerx/axes.h\"\n#include \"chainerx/constant.h\"\n#include \"chainerx/context.h\"\n#include \"chainerx/device.h\"\n#include \"chainerx/dtype.h\"\n#include \"chainerx/enum.h\"\n#include \"chainerx/error.h\"\n#include \"chainerx/graph.h\"\n#include \"chainerx/scalar.h\"\n#include \"chainerx/shape.h\"\n#include \"chainerx/strides.h\"\n\nnamespace chainerx {\nnamespace internal {\n\nBackpropId GetArrayBackpropId(const Array& array, const nonstd::optional<BackpropId>& backprop_id);\n\nArray MakeArray(const Shape& shape, const Strides& strides, Dtype dtype, Device& device, std::shared_ptr<void> data, int64_t offset = 0);\n\ninline const std::shared_ptr<ArrayBody>& GetArrayBody(const Array& array);\n\ninline std::shared_ptr<ArrayBody>&& MoveArrayBody(Array&& array);\n\n}  // namespace internal\n\n// The user interface of multi-dimensional arrays.\n//\n// This wraps an ArrayBody, providing accessors, an interface for graph operations and differentiable operations.\nclass Array {\npublic:\n    Array() = default;\n\n    // TODO(hvy): Consider making this contructor private and prohibit body from being null (assert that given body is not null).\n    explicit Array(std::shared_ptr<internal::ArrayBody> body) : body_{std::move(body)} {\n        if (body_ == nullptr) {\n            throw ChainerxError{\"Cannot create an array from null.\"};\n        }\n    }\n\n    // Copy constructor that copies the pointer to the body instead of the body itself.\n    //\n    // Use MakeView if you want to clone the body.\n    Array(const Array& other) = default;\n    Array(Array&& other) = default;\n\n    // Assign operators just replace the body. They do not copy data between arrays.\n    Array& operator=(const Array&) = default;\n    Array& operator=(Array&& other) = default;\n\n    Array operator-() const;\n\n    Array operator==(const Array& rhs) const;\n    Array operator!=(const Array& rhs) const;\n    Array operator>(const Array& rhs) const;\n    Array operator>=(const Array& rhs) const;\n    Array operator<(const Array& rhs) const;\n    Array operator<=(const Array& rhs) const;\n\n    Array& operator+=(const Array& rhs);\n    Array& operator+=(Scalar rhs);\n    Array& operator-=(const Array& rhs);\n    Array& operator-=(Scalar rhs);\n    Array& operator*=(const Array& rhs);\n    Array& operator*=(Scalar rhs);\n    Array& operator/=(const Array& rhs);\n    Array& operator/=(Scalar rhs);\n\n    const Array& operator+=(const Array& rhs) const;\n    const Array& operator+=(Scalar rhs) const;\n    const Array& operator-=(const Array& rhs) const;\n    const Array& operator-=(Scalar rhs) const;\n    const Array& operator*=(const Array& rhs) const;\n    const Array& operator*=(Scalar rhs) const;\n    const Array& operator/=(const Array& rhs) const;\n    const Array& operator/=(Scalar rhs) const;\n\n    Array operator+(const Array& rhs) const;\n    Array operator+(Scalar rhs) const;\n    Array operator-(const Array& rhs) const;\n    Array operator-(Scalar rhs) const;\n    Array operator*(const Array& rhs) const;\n    Array operator*(Scalar rhs) const;\n    Array operator/(const Array& rhs) const;\n    Array operator/(Scalar rhs) const;\n\n    // Returns a view selected with the indices.\n    Array At(const std::vector<ArrayIndex>& indices) const;\n\n    // Returns a transposed view of the array.\n    Array Transpose(const OptionalAxes& axes = nonstd::nullopt) const;\n\n    // Returns a reshaped array.\n    // TODO(niboshi): Support shape with dimension -1.\n    Array Reshape(const Shape& newshape) const;\n\n    // Returns a squeezed array with unit-length axes removed.\n    //\n    // If no axes are specified, all axes of unit-lengths are removed.\n    // If no axes can be removed, an array with aliased data is returned.\n    Array Squeeze(const OptionalAxes& axis = nonstd::nullopt) const;\n\n    // Broadcasts the array to the specified shape.\n    // Returned array is always a view to this array.\n    Array BroadcastTo(const Shape& shape) const;\n\n    // Returns the indices of the maximum values along the given axis.\n    Array ArgMax(const OptionalAxes& axis = nonstd::nullopt) const;\n\n    // Returns a sum of the array.\n    // If `axis` is set, it will be summed over the specified axes.\n    // Otherwise, it will be summed over all the existing axes.\n    // Note: When implementing chainerx::Sum(), be careful of the semantics of the default value of `keepdims`. See NumPy documentation.\n    Array Sum(const OptionalAxes& axis = nonstd::nullopt, bool keepdims = false) const;\n\n    // Returns the maximum value of the array.\n    // If `axis` is set, the maximum value is chosen along the specified axes.\n    // Otherwise, all the elements are searched at once.\n    Array Max(const OptionalAxes& axis = nonstd::nullopt, bool keepdims = false) const;\n\n    Array Mean(const OptionalAxes& axis = nonstd::nullopt, bool keepdims = false) const;\n\n    Array Var(const OptionalAxes& axis = nonstd::nullopt, bool keepdims = false) const;\n\n    // Returns a dot product of the array with another one.\n    Array Dot(const Array& b) const;\n\n    // Takes elements specified by indices from the array.\n    //\n    // TODO(niboshi): Support Scalar and StackVector as indices.\n    // TODO(niboshi): Support axis=None behavior in NumPy.\n    // TODO(niboshi): Support indices dtype other than int64.\n    Array Take(const Array& indices, int8_t axis) const;\n\n    // Creates a copy.\n    // It will be connected to all the graphs.\n    // It will be always C-contiguous.\n    Array Copy() const;\n\n    // Creates a view.\n    // It creates a new array node and connects graphs.\n    Array MakeView() const;\n\n    // Transfers the array to another device. It will be connected to all the graphs.\n    //\n    // If the destination is the same device, an array with aliased data is returned.\n    // Otherwise, a C-contiguous Array will be created on the target device.\n    // TODO(niboshi): Currently control over whether to make an alias is not supported.\n    Array ToDevice(Device& dst_device) const;\n\n    // Transfer the array to the native device. It will be connected to all the graphs.\n    //\n    // This is a wrapper function which calls Array::ToDevice with the native:0 device.\n    // See also: Array::ToDevice();\n    Array ToNative() const;\n\n    // Creates a copy or a view. It will be disconnected from all the graphs.\n    // If `kind` is `CopyKind::kCopy`, the returned array will be always C-contiguous.\n    Array AsGradStopped(CopyKind kind = CopyKind::kView) const;\n\n    // Creates a copy or a view. It will be disconnected from the specified graphs.\n    // If `kind` is `CopyKind::kCopy`, the returned array will be always C-contiguous.\n    Array AsGradStopped(gsl::span<const BackpropId> backprop_ids, CopyKind kind = CopyKind::kView) const;\n    Array AsGradStopped(std::initializer_list<const BackpropId> backprop_ids, CopyKind kind = CopyKind::kView) const {\n        return AsGradStopped(gsl::span<const BackpropId>{backprop_ids.begin(), backprop_ids.end()}, kind);\n    }\n\n    // Casts to a specified type.\n    // By default, always returns a newly allocated array. If `copy` is false,\n    // and the dtype requirement is satisfied, the input array is returned instead of a copy.\n    Array AsType(Dtype dtype, bool copy = true) const;\n\n    void Fill(Scalar value) const;\n\n    // Returns the gradient of the array.\n    //\n    // ChainerxError is thrown if the array is constant with respect to the computation for the specified backprop ID.\n    // ChainerxError is thrown if the array is not flagged as requiring gradient.\n    // This function ignores no/force-backprop mode.\n    const nonstd::optional<Array>& GetGrad(const nonstd::optional<BackpropId>& backprop_id = nonstd::nullopt) const;\n\n    // Sets the gradient of the array.\n    // This function also flags the array as requiring gradient, so that preceding GetGrad() can return the gradient.\n    //\n    // ChainerxError is thrown if the array is constant with respect to the computation for the specified backprop ID.\n    // This function ignores no/force-backprop mode.\n    void SetGrad(Array grad, const nonstd::optional<BackpropId>& backprop_id = nonstd::nullopt) const;\n\n    // Clears the gradient of the array if set.\n    // This function does not change the state of the array other than that. For example, if the array is flagged as requiring gradient,\n    // that will not change.\n    //\n    // ChainerxError is thrown if the array is constant with respect to the computation for the specified backprop ID.\n    // This function ignores no/force-backprop mode.\n    void ClearGrad(const nonstd::optional<BackpropId>& backprop_id = nonstd::nullopt) const;\n\n    // Returns whether the array needs to backprop.\n    //\n    // If no-backprop mode is set with respect to the specified backprop ID, this function returns false.\n    bool IsBackpropRequired(const nonstd::optional<BackpropId>& backprop_id = nonstd::nullopt) const;\n    bool IsBackpropRequired(AnyGraph any_graph) const;\n\n    // Returns whether the array is flagged to compute the gradient during backprop.\n    //\n    // This function ignores no/force-backprop mode.\n    bool IsGradRequired(const nonstd::optional<BackpropId>& backprop_id = nonstd::nullopt) const;\n\n    // Flags the array to compute the gradient during backprop.\n    // If the array is constant with respect to the computation of the backprop ID, this function makes the array non-constant.\n    //\n    // This function ignores no/force-backprop mode.\n    const Array& RequireGrad(const nonstd::optional<BackpropId>& backprop_id = nonstd::nullopt) const {\n        return RequireGradImpl(*this, backprop_id);\n    }\n\n    Array& RequireGrad(const nonstd::optional<BackpropId>& backprop_id = nonstd::nullopt) { return RequireGradImpl(*this, backprop_id); }\n\n    int64_t GetTotalSize() const { return body_->GetTotalSize(); }\n\n    int64_t GetNBytes() const { return body_->GetNBytes(); }\n\n    int64_t GetItemSize() const { return body_->GetItemSize(); }\n\n    bool IsContiguous() const { return body_->IsContiguous(); }\n\n    std::string ToString() const;\n\n    Context& context() const { return body_->device().context(); }\n\n    Dtype dtype() const { return body_->dtype(); }\n\n    Device& device() const { return body_->device(); }\n\n    int8_t ndim() const { return body_->ndim(); }\n\n    const Shape& shape() const { return body_->shape(); }\n\n    const Strides& strides() const { return body_->strides(); }\n\n    const std::shared_ptr<void>& data() const { return body_->data(); }\n\n    void* raw_data() const { return body_->data().get(); }\n\n    int64_t offset() const { return body_->offset(); }\n\nprivate:\n    friend Array internal::MakeArray(\n            const Shape& shape, const Strides& strides, Dtype dtype, Device& device, std::shared_ptr<void> data, int64_t offset);\n    friend const std::shared_ptr<internal::ArrayBody>& internal::GetArrayBody(const Array& array);\n    friend std::shared_ptr<internal::ArrayBody>&& internal::MoveArrayBody(Array&& array);\n\n    Array(const Shape& shape, const Strides& strides, Dtype dtype, Device& device, std::shared_ptr<void> data, int64_t offset = 0);\n\n    template <typename T>\n    static T& RequireGradImpl(T& array, const nonstd::optional<BackpropId>& backprop_id);\n\n    std::shared_ptr<internal::ArrayBody> body_;\n};\n\nArray operator+(Scalar lhs, const Array& rhs);\nArray operator-(Scalar lhs, const Array& rhs);\nArray operator*(Scalar lhs, const Array& rhs);\n// TODO(hvy): Implement Scalar / Array using e.g. multiplication with reciprocal.\n\nnamespace internal {\n\ninline const std::shared_ptr<ArrayBody>& GetArrayBody(const Array& array) { return array.body_; }\n\ninline std::shared_ptr<ArrayBody>&& MoveArrayBody(Array&& array) { return std::move(array.body_); }\n\nstd::vector<std::shared_ptr<ArrayBody>> MoveArrayBodies(std::vector<Array>&& arrays);\n\nstd::vector<std::shared_ptr<ArrayBody>> MoveArrayBodies(std::vector<nonstd::optional<Array>>&& arrays);\n\n}  // namespace internal\n\nvoid DebugDumpComputationalGraph(\n        std::ostream& os,\n        const Array& array,\n        const nonstd::optional<BackpropId>& backprop_id,\n        int indent = 0,\n        const std::vector<std::pair<ConstArrayRef, std::string>>& array_name_map = {});\n\n}  // namespace chainerx\n", "meta": {"hexsha": "37fa057ac993e1bef2f088a325321927292a07fa", "size": 12475, "ext": "h", "lang": "C", "max_stars_repo_path": "chainerx_cc/chainerx/array.h", "max_stars_repo_name": "hitsgub/chainer", "max_stars_repo_head_hexsha": "20d4d70f5cdacc1f24f243443f5bebc2055c8f8e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-09T07:39:07.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-09T07:39:07.000Z", "max_issues_repo_path": "chainerx_cc/chainerx/array.h", "max_issues_repo_name": "hitsgub/chainer", "max_issues_repo_head_hexsha": "20d4d70f5cdacc1f24f243443f5bebc2055c8f8e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chainerx_cc/chainerx/array.h", "max_forks_repo_name": "hitsgub/chainer", "max_forks_repo_head_hexsha": "20d4d70f5cdacc1f24f243443f5bebc2055c8f8e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.3079470199, "max_line_length": 137, "alphanum_fraction": 0.7063727455, "num_tokens": 3028, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20689404881588813, "lm_q2_score": 0.02333077008177231, "lm_q1q2_score": 0.004826997484210462}}
{"text": "#ifndef TTT_GS_GAMESTATESTACK_H\n#define TTT_GS_GAMESTATESTACK_H\n\n#include \"GameState.h\"\n#include \"../Utilities/Utilities.h\"\n\n#include <gsl/util>\n#include <gsl/assert>\n\n#include <deque>\n#include <memory>\n#include <optional>\n\nnamespace ttt::gs\n{\n\tclass GameStateStack final\n\t{\n\tpublic:\n\t\tusing SizeType = gsl::index;\n\n\t\ttemplate<typename T, typename... Arg>\n\t\tvoid emplace(Arg &&...args) noexcept(std::is_nothrow_constructible_v<T, Arg...>);\n\t\tvoid pop() noexcept;\n\t\tvoid clear() noexcept;\n\n\t\tvoid update();\n\t\tvoid render() const noexcept;\n\n\t\tvoid setBackgroundRender(const std::optional<SizeType> &index) noexcept;\n\t\tvoid setBackgroundUpdate(const std::optional<SizeType> &index) noexcept;\n\n\t\t[[nodiscard]] SizeType getSize() const noexcept;\n\t\t[[nodiscard]] SizeType getMaxSize() const noexcept;\n\n\tprivate:\n\t\tstd::deque<std::unique_ptr<GameState>> gameStates;\n\t\tstd::optional<SizeType> bgUpdateIndex;\n\t\tstd::optional<SizeType> bgRenderIndex;\n\t\t\n\t\tSizeType popIndex{-1};\n\t\tSizeType queuedForPop{0};\n\t};\n\n\ttemplate<typename T, typename... Arg>\n\tvoid GameStateStack::emplace(Arg &&...args) noexcept(std::is_nothrow_constructible_v<T, Arg...>)\n\t{\n\t\tgameStates.emplace_back(std::make_unique<T>(std::forward<Arg>(args)...));\n\t}\n\n\tinline void GameStateStack::setBackgroundUpdate(const std::optional<SizeType> &index) noexcept\n\t{\n\t\tExpects(!index || *index < util::getSize(gameStates));\n\t\tbgUpdateIndex = index;\n\t}\n\n\tinline void GameStateStack::setBackgroundRender(const std::optional<SizeType> &index) noexcept\n\t{\n\t\tExpects(!index || *index < util::getSize(gameStates));\n\t\tbgRenderIndex = index;\n\t}\n\n\tinline GameStateStack::SizeType GameStateStack::getSize() const noexcept { return gameStates.size(); }\n\tinline GameStateStack::SizeType GameStateStack::getMaxSize() const noexcept { return gameStates.max_size(); }\n}\n\n#endif", "meta": {"hexsha": "2430e59f0325d8ec676647e179e0733e78ce4398", "size": 1816, "ext": "h", "lang": "C", "max_stars_repo_path": "Source/GameStates/GameStateStack.h", "max_stars_repo_name": "itsArtem/TicTacToe", "max_stars_repo_head_hexsha": "8c70a77e4603dd0ff22ec0621b978ec0685ec3cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Source/GameStates/GameStateStack.h", "max_issues_repo_name": "itsArtem/TicTacToe", "max_issues_repo_head_hexsha": "8c70a77e4603dd0ff22ec0621b978ec0685ec3cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/GameStates/GameStateStack.h", "max_forks_repo_name": "itsArtem/TicTacToe", "max_forks_repo_head_hexsha": "8c70a77e4603dd0ff22ec0621b978ec0685ec3cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5151515152, "max_line_length": 110, "alphanum_fraction": 0.7362334802, "num_tokens": 450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1311732169688646, "lm_q2_score": 0.036769465811718006, "lm_q1q2_score": 0.004823169116749735}}
{"text": "// SPDX-License-Identifier: MIT\n// The MIT License (MIT)\n//\n// Copyright (c) 2014-2018, Institute for Software & Systems Engineering\n// Copyright (c) 2018-2019, Johannes Leupolz\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n#ifndef PEMC_LMC_LMC_H_\n#define PEMC_LMC_LMC_H_\n\n#include <atomic>\n#include <functional>\n#include <gsl/span>\n#include <string>\n#include <vector>\n\n#include \"pemc/basic/dll_defines.h\"\n#include \"pemc/basic/label.h\"\n#include \"pemc/basic/model_capacity.h\"\n#include \"pemc/basic/probability.h\"\n#include \"pemc/basic/tsc_index.h\"\n#include \"pemc/formula/formula.h\"\n\nnamespace pemc {\n\nstruct LmcStateEntry {\n  TransitionIndex from;\n  int32_t elements;\n};\n\n// Transition = Target + Probability\nstruct LmcTransitionEntry {\n  Probability probability;\n  Label label;\n  StateIndex state;\n\n  LmcTransitionEntry() = default;\n  LmcTransitionEntry(Probability _probability, Label _label, StateIndex _state)\n      : probability(_probability), label(_label), state(_state) {}\n};\n\nclass Lmc {\n private:\n  TransitionIndex maxNumberOfTransitions = 0;\n  std::atomic<TransitionIndex> transitionCount{0};\n  std::vector<LmcTransitionEntry> transitions;\n  TransitionIndex initialTransitionFrom =\n      -1;  // is uninitialized at first, but may be something else than 0\n  int32_t initialTransitionElements = 0;\n\n  StateIndex maxNumberOfStates = 0;\n  StateIndex stateCount = 0;\n  std::vector<LmcStateEntry> states;\n\n  std::vector<std::string> labelIdentifier;\n\n  TransitionIndex getPlaceForNewTransitionEntries(NoOfElements number);\n\n public:\n  Lmc();\n\n  gsl::span<LmcStateEntry> getStates();\n\n  gsl::span<std::string> getLabelIdentifier();\n  void setLabelIdentifier(const std::vector<std::string>& _labelIdentifier);\n  std::function<bool(TransitionIndex)> createLabelBasedFormulaEvaluator(\n      Formula* formula);\n\n  gsl::span<LmcTransitionEntry> getTransitions();\n  gsl::span<LmcTransitionEntry> getInitialTransitions();\n  std::tuple<TransitionIndex, TransitionIndex> getInitialTransitionIndexes();\n  gsl::span<LmcTransitionEntry> getTransitionsOfState(StateIndex state);\n  std::tuple<TransitionIndex, TransitionIndex> getTransitionIndexesOfState(\n      StateIndex state);\n\n  TransitionIndex getPlaceForNewTransitionEntriesOfState(StateIndex stateIndex,\n                                                         NoOfElements number);\n  TransitionIndex getPlaceForNewInitialTransitionEntries(NoOfElements number);\n  void setLmcTransitionEntry(TransitionIndex index,\n                             const LmcTransitionEntry& entry);\n  void createStutteringState(StateIndex stutteringStateIndex);\n\n  void initialize(ModelCapacity& modelCapacity);\n  void finishCreation(StateIndex _stateCount);\n  void validate();\n};\n\n}  // namespace pemc\n\n#endif  // PEMC_LMC_LMC_H_\n", "meta": {"hexsha": "f3af5af517751760124b35f66a03fd7f0e4800d8", "size": 3785, "ext": "h", "lang": "C", "max_stars_repo_path": "pemc/lmc/lmc.h", "max_stars_repo_name": "joleuger/pemc", "max_stars_repo_head_hexsha": "14deb5b97d4219ba3c92d3834ab71332997e9b13", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pemc/lmc/lmc.h", "max_issues_repo_name": "joleuger/pemc", "max_issues_repo_head_hexsha": "14deb5b97d4219ba3c92d3834ab71332997e9b13", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pemc/lmc/lmc.h", "max_forks_repo_name": "joleuger/pemc", "max_forks_repo_head_hexsha": "14deb5b97d4219ba3c92d3834ab71332997e9b13", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0462962963, "max_line_length": 80, "alphanum_fraction": 0.7574636724, "num_tokens": 869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18242554158599963, "lm_q2_score": 0.026355353132900963, "lm_q1q2_score": 0.00480788956895973}}
{"text": "#pragma once\n\n#include \"gl_helpers.h\"\n#include \"GL_Loader.h\"\n#include \"MappedGL.h\"\n#include \"Range.h\"\n\n#include <handy/Guard.h>\n\n#include <gsl/span>\n\n#include <type_traits>\n#include <vector>\n\nnamespace ad\n{\n\nstruct [[nodiscard]] VertexArrayObject : public ResourceGuard<GLuint>\n{\n    /// \\note Deleting a bound VAO reverts the binding to zero\n    VertexArrayObject() :\n        ResourceGuard<GLuint>{reserve(glGenVertexArrays),\n                              [](GLuint aIndex){glDeleteVertexArrays(1, &aIndex);}}\n    {}\n};\n\n/// \\TODO understand when glDisableVertexAttribArray should actually be called\n///       (likely not specially before destruction, but more when rendering other objects\n///        since it is a current(i.e. global) VAO state)\n/// \\Note Well note even that: Activated vertex attribute array are per VAO, so changing VAO\n//        Already correctly handles that.\nstruct [[nodiscard]] VertexBufferObject : public ResourceGuard<GLuint>\n{\n    VertexBufferObject() :\n        ResourceGuard<GLuint>{reserve(glGenBuffers),\n                              [](GLuint aIndex){glDeleteBuffers(1, &aIndex);}}\n    {}\n};\n\n\n/// \\brief A VertexArray with a vector of VertexBuffers\nstruct [[nodiscard]] VertexSpecification\n{\n    VertexSpecification(VertexArrayObject aVertexArray={},\n                        std::vector<VertexBufferObject> aVertexBuffers={}) :\n        mVertexArray{std::move(aVertexArray)},\n        mVertexBuffers{std::move(aVertexBuffers)}\n    {}\n\n    VertexArrayObject mVertexArray;\n    std::vector<VertexBufferObject> mVertexBuffers;\n};\n\n\n/// \\brief Describes the attribute access from the shader (layout id, value type, normalization)\nstruct Attribute\n{\n    enum class Access\n    {\n        Float,\n        Integer,\n    };\n\n    constexpr Attribute(GLuint aValue) :\n        mIndex(aValue)\n    {}\n\n    constexpr Attribute(GLuint aValue, Access aAccess, bool aNormalize=false) :\n        mIndex(aValue),\n        mTypeInShader(aAccess),\n        mNormalize(aNormalize)\n    {}\n\n    GLuint mIndex;\n    Access mTypeInShader{Access::Float};\n    bool mNormalize{false};\n};\n\n/// \\brief The complete description of an attribute expected by OpenGL\nstruct AttributeDescription : public Attribute\n{\n    GLuint mDimension;\n    size_t mOffset;\n    GLenum mDataType;\n};\n\nstd::ostream & operator<<(std::ostream &aOut, const AttributeDescription & aDescription);\n\ntypedef std::initializer_list<AttributeDescription> AttributeDescriptionList;\n\n\ntemplate <class T_vertex>\nVertexBufferObject loadVertexBuffer(const VertexArrayObject & aVertexArray,\n                                    const AttributeDescriptionList & aAttributes,\n                                    const gsl::span<T_vertex> aVertices,\n                                    GLuint aAttributeDivisor = 0)\n{\n    glBindVertexArray(aVertexArray);\n\n    if (aAttributeDivisor)\n    {\n        for(const auto & attribute : aAttributes)\n        {\n            glVertexAttribDivisor(attribute.mIndex, aAttributeDivisor);\n        }\n    }\n\n    return makeLoadedVertexBuffer(aAttributes, aVertices);\n}\n\n\ntemplate <class T_vertex>\nvoid appendToVertexSpecification(VertexSpecification & aSpecification,\n                                 const AttributeDescriptionList & aAttributes,\n                                 const gsl::span<T_vertex> aVertices,\n                                 GLuint aAttributeDivisor = 0)\n{\n    aSpecification.mVertexBuffers.push_back(\n            loadVertexBuffer(aSpecification.mVertexArray,\n                             aAttributes,\n                             std::move(aVertices),\n                             aAttributeDivisor));\n}\n\n/// \\brief Create a VertexBufferObject with provided attributes, load it with data.\n///\n/// This is the lowest level overload, with explicit attribute description and raw data pointer.\n/// Other overloads end-up calling it.\nVertexBufferObject makeLoadedVertexBuffer(AttributeDescriptionList aAttributes,\n                                          GLsizei aStride,\n                                          size_t aSize,\n                                          const GLvoid * aData);\n\ntemplate <class T_vertex>\nVertexBufferObject makeLoadedVertexBuffer(AttributeDescriptionList aAttributes,\n                                          const gsl::span<T_vertex> aVertices)\n{\n    return makeLoadedVertexBuffer(aAttributes,\n                                  sizeof(T_vertex),\n                                  aVertices.size_bytes(),\n                                  aVertices.data());\n}\n\n\n/***\n * Buffer re-specification\n *\n * see: https://www.khronos.org/opengl/wiki/Buffer_Object_Streaming#Buffer_re-specification\n ***/\n\ninline void respecifyBuffer(const VertexBufferObject & aVBO, const GLvoid * aData, GLsizei aSize)\n{\n    glBindBuffer(GL_ARRAY_BUFFER, aVBO);\n\n    // Orphan the previous buffer\n    glBufferData(GL_ARRAY_BUFFER, aSize, NULL, GL_STATIC_DRAW);\n\n    // Copy value to new buffer\n    glBufferSubData(GL_ARRAY_BUFFER, 0, aSize, aData);\n}\n\n\n/// \\brief Respecify the buffer with the same size (allowing potential optimizations)\ninline void respecifyBuffer(const VertexBufferObject & aVBO, const GLvoid * aData)\n{\n    GLint size;\n    glGetBufferParameteriv(GL_ARRAY_BUFFER, GL_BUFFER_SIZE, &size);\n\n    respecifyBuffer(aVBO, aData, size);\n}\n\ntemplate <class T_vertex>\nvoid respecifyBuffer(const VertexBufferObject & aVBO, const gsl::span<T_vertex> aVertices)\n{\n    respecifyBuffer(aVBO,\n                    aVertices.data(),\n                    static_cast<GLsizei>(aVertices.size_bytes()));\n}\n\n} // namespace ad\n", "meta": {"hexsha": "00b90e948a2af69cbc34badd411e8a8447539d6a", "size": 5533, "ext": "h", "lang": "C", "max_stars_repo_path": "src/lib/renderer/renderer/VertexSpecification.h", "max_stars_repo_name": "FranzPoize/graphics", "max_stars_repo_head_hexsha": "b426e5ca8b98dc2bd9c63335daba8aff9244f3fc", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lib/renderer/renderer/VertexSpecification.h", "max_issues_repo_name": "FranzPoize/graphics", "max_issues_repo_head_hexsha": "b426e5ca8b98dc2bd9c63335daba8aff9244f3fc", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lib/renderer/renderer/VertexSpecification.h", "max_forks_repo_name": "FranzPoize/graphics", "max_forks_repo_head_hexsha": "b426e5ca8b98dc2bd9c63335daba8aff9244f3fc", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5690607735, "max_line_length": 97, "alphanum_fraction": 0.6475691307, "num_tokens": 1111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16885695214168314, "lm_q2_score": 0.028436032736092125, "lm_q1q2_score": 0.004801621818817643}}
{"text": "/**\n* Copyright 2016 BitTorrent Inc.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n*    http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*/\n#pragma once\n\n#include <scraps/config.h>\n\n#include <scraps/Temp.h>\n#include <scraps/type-traits.h>\n#include <scraps/utility.h>\n\nSCRAPS_IGNORE_WARNINGS_PUSH\n#include <gsl.h>\nSCRAPS_IGNORE_WARNINGS_POP\n\n#include <array>\n\nnamespace scraps {\n\n/**\n * Convenience functions to create an std::array from a gsl::span\n */\ntemplate <typename T, std::ptrdiff_t ArraySize, template <typename, std::ptrdiff_t...> class Span>\nconstexpr std::array<std::remove_cv_t<T>, ArraySize> ToArray(Span<T, ArraySize> span) {\n    static_assert(ArraySize != gsl::dynamic_range, \"Dynamic range spans are not allowed.\");\n    static_assert(ArraySize > 0, \"ArraySize must be greater than 0\");\n\n    std::array<std::remove_cv_t<T>, ArraySize> ret{};\n    std::copy(span.begin(), span.end(), ret.begin());\n    return ret;\n}\n\ntemplate <typename T, std::ptrdiff_t ArraySize, template <typename, std::ptrdiff_t...> class Span>\nconstexpr std::array<std::remove_cv_t<T>, ArraySize> ToArray(Temp<Span<T, ArraySize>> span) {\n    return ToArray(static_cast<Span<T, ArraySize>>(span));\n}\n\ntemplate <typename T, size_t N>\nconstexpr std::array<std::remove_cv_t<T>, N> ToArray(T (&arr)[N]) {\n    std::array<std::remove_cv_t<T>, N> ret{};\n    std::copy(arr, arr + N, ret.begin());\n    return ret;\n}\n\n/**\n * Convenience type for defining a c-style array using the template parameters\n * of a std::array.\n */\ntemplate <typename ArrayT>\nusing CArray = typename RemoveCVRType<ArrayT>::value_type[std::tuple_size<RemoveCVRType<ArrayT>>::value];\n\n/**\n * Hashing struct suitable for using an std::array as the key in stl\n * associative containers such as unordered_map.\n */\nstruct ArrayHasher {\n    template <typename T, size_t N>\n    size_t operator()(const std::array<T, N>& arr) const {\n        return HashRange(arr.begin(), arr.end());\n    }\n};\n\n} // namespace scraps\n\nnamespace std {\n    template<typename T, size_t N>\n    struct hash<std::array<T, N>> {\n        size_t operator()(const std::array<T, N>& array) const {\n            return scraps::ArrayHasher{}(array);\n        }\n    };\n} // namespace std\n", "meta": {"hexsha": "05fe754da28c4e4291c910bfd3fbf32a4ef3c1c3", "size": 2640, "ext": "h", "lang": "C", "max_stars_repo_path": "include/scraps/array.h", "max_stars_repo_name": "carlbrown/scraps", "max_stars_repo_head_hexsha": "78925a738540415ec04b9cbe23cb319421f44978", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/scraps/array.h", "max_issues_repo_name": "carlbrown/scraps", "max_issues_repo_head_hexsha": "78925a738540415ec04b9cbe23cb319421f44978", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/scraps/array.h", "max_forks_repo_name": "carlbrown/scraps", "max_forks_repo_head_hexsha": "78925a738540415ec04b9cbe23cb319421f44978", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0588235294, "max_line_length": 105, "alphanum_fraction": 0.7026515152, "num_tokens": 658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.136608375965897, "lm_q2_score": 0.03514484955887902, "lm_q1q2_score": 0.004801080821804234}}
{"text": "#ifndef API_H_INCLUDED\n#define API_H_INCLUDED\n\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_complex.h>\n#include <plplot/plplot.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <string.h>\n#include \"stack.h\"\n#include \"utf8.h\"\n#include \"gdate.h\"\n#include <setjmp.h>\n\n#if defined(_MSC_VER) || defined(_WIN32)\n#include <Windows.h>\n#endif\n\n#define RECORD_SEP '~'\n\n\n// Parse errors\n#define KEE_UNQU    0x01 // unmatched quotation marks\n#define KEE_UNLP    0x02 // unmatched left parentheses\n#define KEE_UNRP    0x04 // unmatched right parentheses\n#define KEE_UNOP    0x08 // unknown operators\n#define KEE_FUNC    0x10 // wrong function syntax\n#define KEE_ARG     0x20\n#define KEE_NUM     0x40 // fail to parse a number\n//#define KEE_END     0x80 // fail to parse a number\n\n// Evaluation errors\n#define KEE_UNFUNC  0x40 // undefined function\n#define KEE_UNVAR   0x80 // unassigned variable\n\n// Return type\n#define KEV_REAL 1\n#define KEV_INT  2\n#define KEV_STR  3\n#define KEV_VEC  4\n#define KEV_MAT  5\n#define KEV_COMPLEX 6\n#define KEV_FNC  7\n#define KEV_REC  8\n#define KEV_VEC_INT  9\n#define KEV_DEF  10\n#define KEV_IMAGE 11\n#define KEV_FILE 12\n#define KEV_BUFFER 13\n#define KEV_DATE 14\n#define KEV_PTR   15\n#define KEV_FPOS  16\n\n#define KEV_REAL_S \"REAL\"\n#define KEV_INT_S \"INT\"\n#define KEV_STR_S \"STR\"\n#define KEV_VEC_S  \"VEC\"\n#define KEV_MAT_S  \"MAT\"\n#define KEV_COMPLEX_S \"COMPLEX\"\n#define KEV_CMD_S  \"CMD\"\n#define KEV_FNC_S  \"FNC\"\n#define KEV_REC_S  \"REC\"\n#define KEV_VEC_INT_S  \"VEC_INT\"\n#define KEV_DEF_S  \"DEF\"\n#define KEV_IMAGE_S \"IMAGE\"\n#define KEV_FILE_S \"FILE\"\n#define KEV_BUFFER_S \"BUFFER\"\n#define KEV_DATE_S \"DATE\"\n#define KEV_PTR_S  \"PTR\"\n#define KEV_FPOS_S  \"FPOS\"\n\nextern char * kev_to_str[17];\n\n#define KEO_NULL  0\n#define KEO_POS   1\n#define KEO_NEG   2\n#define KEO_BNOT  3\n#define KEO_LNOT  4\n#define KEO_POW   5\n#define KEO_MUL   6\n#define KEO_DIV   7\n#define KEO_IDIV  8\n#define KEO_MOD   9\n#define KEO_ADD  10\n#define KEO_SUB  11\n#define KEO_LSH  12\n#define KEO_RSH  13\n#define KEO_LT   14\n#define KEO_LE   15\n#define KEO_GT   16\n#define KEO_GE   17\n#define KEO_EQ   18\n#define KEO_NE   19\n#define KEO_BAND 20\n#define KEO_BXOR 21\n#define KEO_BOR  22\n#define KEO_LAND 23\n#define KEO_LOR  24\n#define KEO_LET  25\n#define KEO_NOP  26\n\n#define KEO_MAX  27\n\n#define KET_NULL  0\n#define KET_DEFNAME 1 \n#define KET_CMD   2\n#define KET_VCMD  3\n#define KET_OP    4\n#define KET_FUNC  5\n#define KET_REC   6\n#define KET_XPROP 7\n#define KET_PROP  8\n#define KET_VAL_SEP 10\n#define KET_CONST 11\n#define KET_VAL   12\n#define KET_FILE  13\n#define KET_XNAME 14 //already set when it's VNAME\n#define KET_VNAME 15\n\n#define KEF_NULL  0\n#define KEF_REAL  1\n#define KEF_LET   2\n#define KEF_GET   3\n\n#include \"kdq.h\"\n#include \"khash.h\"\n\nstruct token_s;\nstruct kexpr_s;\nstruct sml_s;\n\ntypedef char* strptr;\ntypedef struct token_s* ke1_p;\ntypedef int(*cmdp)(struct sml_s * sml, int);\ntypedef void(*fncp)(struct sml_s *);\ntypedef int(*vcmdp)(struct sml_s * sml, int);\ntypedef int(__cdecl *dllke_hash_add_t)(struct sml_s *, fncp, char *);\ntypedef struct token_s *(__cdecl *dllke_get_out_t)(struct sml_s *);\n\nKHASH_MAP_INIT_STR(0, cmdp)\nKHASH_MAP_INIT_STR(1, vcmdp)\nKHASH_MAP_INIT_STR(2, int)\nKHASH_MAP_INIT_STR(3, int)\nKHASH_MAP_INIT_STR(5, fncp)\nKHASH_MAP_INIT_STR(6, int)\nKHASH_MAP_INIT_STR(7, int)\n\n#pragma warning( push )\n#pragma warning( disable : 273)\n#pragma warning( disable : 4018)\n#pragma warning( disable : 4334)\n#pragma warning( disable : 4627)\n#pragma warning( disable : 4267)\nKDQ_INIT(int)\n#pragma warning( pop )\n\nstruct sml_s;\ntypedef struct sml_s {\n\tint is_execute;\n\tint topGlobal;\n\tstruct token_s *def_name;      // current def name to put the stack ref\n\tstruct token_s **stack;        // stack for the evaluation of the program\n\tdouble *rstack;                    // stack for the evaluation of the program\n\tstruct token_s *out;           // pointer to the array of out parameter to put into the stack\n\tstruct kexpr_s *kexpr;\n\tstruct token_s ** fields;\t\t// array of all global fields of the program to exectue\n\tstruct token_s ** tokens;     // array of pointers of all program tokens\n\tint top;\n\tint localtop;\t\t\t\t// will be init with gfield_qte;\n\tint inittop;\t\t\t\t// will be init with gfield_qte;\n\tstruct token_s * tokp;\n\tint out_qte;\n\tint tok_idx;\n\tint val;\n\tjmp_buf env_buffer;\n\t// GLOBAL VARIABLE USED BY ALL FUNCTIONS\n\tint field_qte;\t\t\t\t// number of local fields, reset for each def\n\tint gfield_qte;\t\t\t\t// number of global fields  \n\tint mem_count;\t\t\t\t// current count of memory allocation\n\t\t\t\t\t\t\t\t// parser variables\n\tint isNextDefName;\t\t\t// flag to indicate that the next token is the def name\n\tchar currentDefName[100];\t// current name of the current function\n\tint sourceCodeLine;\t\t\t// use to keep the line number to show better error trapping\n\tint isFirstToken;\t\t\t// use to remove separators at the beginning of the program\n\tint isLastTokenNop;\t\t\t// use to manage the command seperator, the rule is to have one separator between each comand\n\tchar lastErrorMessage[256]; // \n\tstruct token_s * recp[100]; // local record fields\n\tstruct token_s * grecp[100];// global record fields\n\tint rec_qte;        // number of local record fields  \n\tint grec_qte;        // number of global record fields  \n\tkhash_t(5) *hfunction;\n\tkhash_t(6) *hname;  // function name = negative stack\n\tkhash_t(7) *gname;  // global name = positif stack\n#if defined(_MSC_VER) || defined(_WIN32)\n\tHMODULE libhandle[64];\n\tint libhandle_qte;      // number of global fields\n#endif\n\tkdq_t(int) *callstack;\n\tkdq_t(int) *hiforcommand;\n\tkdq_t(int) *hinextcommand;\n\tkhash_t(3) *hidefcommand;\n\tkhash_t(0) *hcommand;\n\tkhash_t(1) *hvcommand;\n\tkstack_t *harg;\n\tint g_forstack[20];\n\tint g_fortop;\n\tint lastDef;\n\tdllke_hash_add_t dllke_hash_add;\n\tdllke_get_out_t dllke_get_out;\n} sml_t;\n\nstruct kexpr_s;\ntypedef struct kexpr_s kexpr_t;\ntypedef int * reclistt;\n\nstruct token_s;\ntypedef struct token_s {\n\tint64_t i;\n\tdouble r;\n\tunion {    //                                                                                                 \n\t\tvoid(*builtin)(struct token_s *a, struct token_s *b, struct token_s *out); // execution function\n\t\tdouble(*real_func1)(double);\n\t\tdouble(*real_func2)(double, double);\n\t\tint(*defprop)(sml_t* sml, struct token_s* prop, int top);\n\t\tvoid(*deffunc)(sml_t* sml);\n\t\tint(*defcmd)(sml_t* sml, int itok);\n\t\tint(*defvcmd)(sml_t* sml, int itok);\n\t\tstruct token_s * recp;\n\t} f;\n\tunion {  //     \n\t\tvoid * ptr;\n\t\tstruct token_s * tokp;\n\t\tchar *s;\n\t\tchar* image;\n\t\tchar ** ms;\n\t\tfpos_t * fpos;\n\t\tFILE *file;\n\t\tvoid *buffer;\n\t\tGDate_t * date;\n\t\tgsl_vector_int * vector_int;\n\t\tgsl_vector * vector;\n\t\tgsl_matrix * matrix;\n\t\tgsl_complex tcomplex;\n\t\treclistt reclist;\n\t\tPLGraphicsIn * plgrin;\n\t\tPLPointer * plptr;\n\t\tPLTRANSFORM_callback pltrcb;\n\t\tPLMAPFORM_callback plmpcb;\n\t\tPLDEFINED_callback pldefcb;\n\t\tPLLABEL_FUNC_callback pllblcb;\n\t\tPLFILL_callback plfillcb;\n\t} obj;\n\tchar *name; // variable name or function name                                                                 \n\tint32_t ijmp;\n\tint32_t sourceLine; // fast jmp  \n\tuint16_t ttype;\n\tuint16_t vtype;\n\tint16_t ifield;\n\tint8_t icmd;\n\tint8_t assigned;\n\tint8_t propget;\n\tint8_t propset;\n\tint8_t tofree;\n\tint8_t islocal;\n\tint8_t op;\n\tint8_t n_args;\n\tint8_t realToken;\n\tint8_t isfor;\n} token_t;\n\n\nstruct kexpr_s {\n\tint n;\n\ttoken_t *e;\n};\n\ntoken_t * ke_get_out(sml_t *sml);\nvoid ke_hash_add(sml_t *sml, fncp key, char * name);\nvoid ke_inc_memory(sml_t *sml);\nvoid ke_dec_memory(sml_t *sml);\nvoid * ke_calloc_memory(sml_t *sml, size_t i, size_t x);\nvoid * ke_malloc_memory(sml_t *sml, size_t i);\nvoid ke_free_memory(sml_t *sml, void * m);\nvoid ke_print_one(sml_t *sml, token_t* t);\ngsl_matrix * sml_pop_set_matrix(sml_t * sml);\ngsl_vector * sml_pop_set_vector(sml_t * sml);\ngsl_vector_int * sml_pop_set_vector_int(sml_t * sml);\ngsl_matrix * sml_peek_set_matrix(sml_t * sml, int n);\ngsl_vector * sml_peek_set_vector(sml_t * sml, int n);\ngsl_vector_int * sml_peek_set_vector_int(sml_t * sml, int n);\nvoid * sml_peek_set_ptr(sml_t * sml, int n);\n\n\n#define __GLOBAL \"g_\"\n#define __GLOBAL_SEP \"_\"\n#define __GLOBAL_DSEP \"__\"\n\n#define sml_get_top(sml) sml->top\n#define sml_dec_top(sml) --sml->top\n#define sml_set_top(sml,top) sml->top=top\n#define sml_get_stack(sml) sml->stack\n#define sml_get_tokp(sml) sml->tokp\n#define sml_get_args(sml) sml->tokp->n_args\n#define sml_set_args(sml,a) sml->tokp->n_args = a\n#define sml_get_ttype(sml) sml->tokp->ttype\n#define sml_get_vtype(sml) sml->tokp->vtype\n#define sml_get_ijmp(sml) sml->tokp->ijmp\n#define sml_get_assigned(sml) sml->tokp->assigned\n#define sml_set_assigned(sml,a) sml->tokp->assigned = a\n\n#define sml_pop_token(sml) sml->stack[--sml->top]\n#define sml_pop_int(sml) sml->stack[--sml->top]->i\n#define sml_pop_real(sml) sml->stack[--sml->top]->r\n#define sml_pop_ptr(sml) sml->stack[--sml->top]->obj.ptr\n#define sml_pop_file(sml) sml->stack[--sml->top]->obj.file\n#define sml_pop_fpos(sml) sml->stack[--sml->top]->obj.fpos\n#define sml_pop_str(sml) sml->stack[--sml->top]->obj.s\n#define sml_pop_date(sml) sml->stack[--sml->top]->obj.date\n#define sml_pop_complex(sml) sml->stack[--sml->top]->obj.tcomplex\n#define sml_pop_complex_adr(sml) &sml->stack[--sml->top]->obj.tcomplex\n#define sml_pop_day(sml) sml->stack[--sml->top]->i\n#define sml_pop_month(sml) sml->stack[--sml->top]->i\n#define sml_pop_year(sml) sml->stack[--sml->top]->i\n#define sml_pop_matrix(sml) sml->stack[--sml->top]->obj.matrix\n#define sml_pop_vector(sml) sml->stack[--sml->top]->obj.vector\n#define sml_pop_vector_int(sml) sml->stack[--sml->top]->obj.vector_int\n\n#define sml_peek_token(sml,i) sml->stack[i]\n#define sml_peek_int(sml,ii) sml->stack[ii]->i\n#define sml_peek_real(sml,i) sml->stack[i]->r\n#define sml_peek_ptr(sml,i) sml->stack[i]->obj.ptr\n#define sml_peek_file(sml,i) sml->stack[i]->obj.file\n#define sml_peek_fpos(sml,i) sml->stack[i]->obj.fpos\n#define sml_peek_str(sml,i) sml->stack[i]->obj.s\n#define sml_peek_date(sml,i) sml->stack[i]->obj.date\n#define sml_peek_complex(sml,i) sml->stack[i]->obj.tcomplex\n#define sml_peek_complex_adr(sml,i) &sml->stack[i]->obj.tcomplex\n#define sml_peek_day(sml,i) (GDateDay)sml->stack[i]->i\n#define sml_peek_month(sml,i) (GDateMonth)sml->stack[i]->i\n#define sml_peek_year(sml,i) (GDateYear)sml->stack[i]->i\n#define sml_peek_matrix(sml,i) sml->stack[i]->obj.matrix\n#define sml_peek_vector(sml,i) sml->stack[i]->obj.vector\n#define sml_peek_vector_int(sml,i) sml->stack[i]->obj.vector_int\n\n#define sml_get_complex_adr  &out->obj.tcomplex\n\n#define sml_get_type(t) t->vtype\n#define sml_get_str(t) t->obj.s\n#define sml_get_real(t) t->r\n#define sml_get_int(t) t->i\n#define sml_get_ifield(t) t->ifield\n\n#define sml_set_int(sml,t,ii) { int i = t->ifield; \\\n\tif (i < 0) { \\\n\t\ti += sml->localtop; \\\n\t} \\\n\tt = sml->fields[i]; \\\n\tt->i = ii; }\n\n#define sml_get_ptr(t) t->obj.ptr\n#define sml_get_file(t) t->obj.file\n#define sml_get_buffer(t) t->obj.buffer\n#define sml_get_fpos(t) t->obj.fpos\n\n#define sml_set_fpos(sml,t,fposp) { int i = t->ifield; \\\n\tif (i < 0) { \\\n\t\ti += sml->localtop; \\\n\t} \\\n\tt = sml->fields[i]; \\\n\tt->obj.fpos = fposp; }\n\n\n#define sml_set_ptr_null(sml,t) { int i = t->ifield; \\\n\tif (i < 0) { \\\n\t\ti += sml->localtop; \\\n\t} \\\n\tt = sml->fields[i]; \\\n\tt->obj.ptr = NULL; }\n\n#define sml_get_len(t) t->i\n#define sml_adr_str(t) &t->obj.s\n#define sml_adr_ptr(t) &t->obj\n\n#define sml_get_matrix(t) t->obj.matrix\n#define sml_get_vector(t) t->obj.vector\n#define sml_get_vector_int(t) t->obj.vector_int\n#define sml_get_complex(t) t->obj.complex\n\n#define sml_push_buffer(sml, b, ii) token_t* out; \\\n\tsml->stack[sml->top] = ke_get_out(sml); \\\n\tout = sml->stack[sml->top++]; \\\n\tout->obj.buffer = b; \\\n\tout->i = ii; \\\n\tout->r == (double)ii; \\\n\tout->ttype = KET_VAL; \\\n\tout->vtype = KEV_BUFFER;\n\n#define sml_push_file(sml, file) token_t* out; \\\n\tsml->stack[sml->top] = ke_get_out(sml); \\\n\tout = sml->stack[sml->top++]; \\\n\tout->obj.file = file; \\\n\tout->i = 1; \\\n\tout->r == 1.0; \\\n\tout->ttype = KET_VAL; \\\n\tout->vtype = KEV_FILE;\n\n#define sml_push_new_complex(sml) token_t* out; \\\n\tsml->stack[sml->top] = ke_get_out(sml); \\\n\tout = sml->stack[sml->top++]; \\\n\tout->ttype = KET_VAL; \\\n\tout->vtype = KEV_COMPLEX;\n\n#define sml_push_complex(sml, z) token_t* out; \\\n\tsml->stack[sml->top] = ke_get_out(sml); \\\n\tout = sml->stack[sml->top++]; \\\n\tout->obj.tcomplex = z; \\\n\tout->ttype = KET_VAL; \\\n\tout->vtype = KEV_COMPLEX;\n\n#define sml_push_real(sml, r) token_t* out; \\\n\tsml->stack[sml->top] = ke_get_out(sml); \\\n\tout = sml->stack[sml->top++]; \\\n\tout->r = r; \\\n\tout->i = (int64_t)r; \\\n\tout->ttype = KET_VAL; \\\n\tout->vtype = KEV_REAL;\n\n#define sml_push_date(sml, dt) token_t* out; \\\n\tsml->stack[sml->top] = ke_get_out(sml); \\\n\tout = sml->stack[sml->top++]; \\\n\tout->obj.date = dt; \\\n\tout->ttype = KET_VAL; \\\n\tout->vtype = KEV_DATE;\n\n#define  sml_push_int(sml, ii) token_t* out; \\\n\tsml->stack[sml->top] = ke_get_out(sml); \\\n\tout = sml->stack[sml->top++]; \\\n\tout->i = ii; \\\n\tout->r = (double)ii; \\\n\tout->ttype = KET_VAL; \\\n\tout->vtype = KEV_INT;\n\n#define  sml_push_ptr(sml, ptr) \\\n\ttoken_t* out; \\\n\tsml->stack[sml->top] = ke_get_out(sml); \\\n\tout = sml->stack[sml->top++]; \\\n\tout->obj.ptr = ptr; \\\n\tout->ttype = KET_VAL; \\\n\tout->vtype = KEV_PTR;\n\n#define  sml_push_str(sml, str) \\\n\ttoken_t* out; \\\n\tsml->stack[sml->top] = ke_get_out(sml); \\\n\tout = sml->stack[sml->top++]; \\\n\tout->obj.s = str; \\\n\tout->ttype = KET_VAL; \\\n\tout->vtype = KEV_STR;\n\n#define  sml_push_matrix(sml, m) \\\n\ttoken_t* out; \\\n\tsml->stack[sml->top] = ke_get_out(sml); \\\n\tout = sml->stack[sml->top++]; \\\n\tout->obj.matrix = m; \\\n\tout->ttype = KET_VAL; \\\n\tout->vtype = KEV_MAT;\n\n#define  sml_push_vector(sml, v) \\\n\ttoken_t* out; \\\n\tsml->stack[sml->top] = ke_get_out(sml); \\\n\tout = sml->stack[sml->top++]; \\\n\tout->obj.vector = v; \\\n\tout->ttype = KET_VAL; \\\n\tout->vtype = KEV_VEC;\n\n#define  sml_push_vector_int(sml, v) \\\n\ttoken_t* out; \\\n\tsml->stack[sml->top] = ke_get_out(sml); \\\n\tout = sml->stack[sml->top++]; \\\n\tout->obj.vector_int = v; \\\n\tout->ttype = KET_VAL; \\\n\tout->vtype = KEV_VEC_INT;\n\n#define  sml_push_image(sml, image) \\\n\ttoken_t* out; \\\n\tsml->stack[sml->top] = ke_get_out(sml); \\\n\tout = sml->stack[sml->top++]; \\\n\tout->obj.image = image; \\\n\tout->ttype = KET_VAL; \\\n\tout->vtype = KEV_IMAGE;\n\n#define  sml_push_fpos(sml, fposp) \\\n\ttoken_t* out; \\\n\tsml->stack[sml->top] = ke_get_out(sml); \\\n\tout = sml->stack[sml->top++]; \\\n\tout->obj.fpos = fposp; \\\n\tout->ttype = KET_VAL; \\\n\tout->vtype = KEV_FPOS;\n\n#define sml_out_date out->obj.date\n\n#define sml_free_ptr(sml,ptr) ke_free_memory(sml,ptr); ptr = NULL\n\n#define sml_new_ptr(sml,size) ke_calloc_memory(sml, size,1)\n\n#define sml_mem_inc ke_inc_memory\n\n#define sml_save_str(sml, tokp, tmp) \\\n\tint k = tokp->ifield; \\\n    if (k < 0) \\\n\t\tk += sml->localtop; \\\n\ttokp = sml->fields[k]; \\\n\tif (tokp->vtype == KEV_STR && tokp->obj.s) { \\\n\t\tke_free_memory(sml, tokp->obj.s); \\\n\t} \\\n\ttokp->obj.s = tmp; \\\n\ttokp->i = 0, tokp->r = 0 ; \\\n\ttokp->vtype = KEV_STR;\n\n#endif\n\n#ifdef _DEBUG\n#define sml_assert_args(sml,i,fnc) if (sml->tokp->n_args != i) { \\\n\t\tprintf(\"ASSERT ERROR : Invalid number of parameters, expected <%d> got <%d> at line <%d> for function <%s>\", i, sml->tokp->n_args, sml->tokp->sourceLine,fnc);\t\\\n\t\tlongjmp(sml->env_buffer, 1); \\\n\t} \n#else\n#define sml_assert_args(sml,i,s)\n#endif \n\n#ifdef _DEBUG\n#define sml_assert_args_min(sml,i,fnc) if (sml->tokp->n_args < i) { \\\n\t\tprintf(\"ASSERT ERROR : Invalid number of parameters, expected at least <%d> got <%d> at line <%d> for function <%s>\", i, sml->tokp->n_args, sml->tokp->sourceLine,fnc);\t\\\n\t\tlongjmp(sml->env_buffer, 1); \\\n\t} \n#else\n#define sml_assert_args_min(sml,i,fnc)\n#endif \n\n#ifdef _DEBUG\n#define sml_assert_type(sml,i,t,fnc) \\\n\tif (sml->stack[sml->top - 1 - (sml->tokp->n_args - i)]->vtype != t) { \\\n\t\tprintf(\"ASSERT ERROR : Invalid type for parameter #%d, expected <%s> got <%s> at line <%d> for function <%s>\", i, kev_to_str[t], kev_to_str[sml->stack[sml->top - 1 - (sml->tokp->n_args - i)]->vtype], sml->tokp->sourceLine,fnc); \\\n\t\tlongjmp(sml->env_buffer, 1); \\\n\t}\n#else\n#define sml_assert_type(sml,i,t,s)\n#endif \n\n#ifdef _DEBUG\n#define sml_assert_type_int_or_real(sml,i,fnc) \\\n\tif (sml->stack[sml->top - 1 - (sml->tokp->n_args - i)]->vtype != KEV_INT && sml->stack[sml->top - 1 - (sml->tokp->n_args - i)]->vtype != KEV_REAL) { \\\n\t\tprintf(\"ASSERT ERROR : Invalid type for parameter #%d, expected <INT OR REAL> got <%s> at line <%d> for function <%s>\", i, kev_to_str[sml->stack[sml->top - 1 - (sml->tokp->n_args - i)]->vtype], sml->tokp->sourceLine,fnc); \\\n\t\tlongjmp(sml->env_buffer, 1); \\\n\t}\n#else\n#define sml_assert_type_int_or_real(sml,i,s)\n#endif \n\n#ifdef _DEBUG\n#define sml_assert_str_in(sml,i,search,fnc) \\\n\tif (!strstr(search, sml->stack[sml->top - 1 - (sml->tokp->n_args - i)]->obj.s)) { \\\n\t\tprintf(\"ASSERT ERROR : Invalid parameter value for parameter #%d, at line <%d> for function <%s>\", i, sml->tokp->sourceLine,fnc); \\\n\t\tlongjmp(sml->env_buffer, 1); \\\n\t}\n#else\n#define sml_assert_str_in(sml,i,f,s)\n#endif \n\n#ifdef _DEBUG\n#define sml_assert_str(sml,i,fnc) \\\n\tif (!strlen(sml->stack[sml->top - 1 - (sml->tokp->n_args - i)]->obj.s)) { \\\n\t\tprintf(\"ASSERT ERROR : Invalid parameter value (empty) for parameter #%d, at line <%d> for function <%s>\", i, sml->tokp->sourceLine,fnc); \\\n\t\tlongjmp(sml->env_buffer, 1); \\\n\t}\n#else\n#define sml_assert_str(sml,i,fnc)\n#endif \n\n#ifdef _DEBUG\n#define sml_assert_size(sml,size,i,fnc) \\\n\tif (size <= 0) { \\\n\t\tprintf(\"ASSERT ERROR : Invalid parameter value (<=0) for parameter #%d, at line <%d> for function <%s>\", i, sml->tokp->sourceLine,fnc); \\\n\t\tlongjmp(sml->env_buffer, 1); \\\n\t}\n#else\n#define sml_assert_size(sml,size,i,fnc)\n#endif \n\n#ifdef _DEBUG\n#define sml_assert_gz(sml,size,fnc) \\\n\tif (size < 0) { \\\n\t\tprintf(\"ASSERT ERROR : Invalid parameters (size validation < 0) at line <%d> for function <%s>\", sml->tokp->sourceLine,fnc); \\\n\t\tlongjmp(sml->env_buffer, 1); \\\n\t}\n#else\n#define sml_assert_gz(sml,size,fnc)\n#endif \n\n#ifdef _DEBUG\n#define sml_assert_ptr(sml,p,i,fnc) \\\n\tif (p == NULL) { \\\n\t\tprintf(\"ASSERT ERROR : Invalid parameter value (==NULL) for parameter #%d, at line <%d> for function <%s>\", i, sml->tokp->sourceLine,fnc); \\\n\t\tlongjmp(sml->env_buffer, 1); \\\n\t}\n#else\n#define sml_assert_ptr(sml,p,i,fnc)\n#endif \n\n#ifdef _DEBUG\n#define sml_assert_range(sml,i,v,from,to,fnc) \\\n\tif (v < from || v > to) { \\\n\t\tprintf(\"ASSERT ERROR : Invalid parameter value <%d> expected (%d - %d) for parameter #%d, at line <%d> for function <%s>\", v, from, to, i, sml->tokp->sourceLine,fnc); \\\n\t\tlongjmp(sml->env_buffer, 1); \\\n\t}\n#else\n#define sml_assert_range(sml,i,v,from,to,fnc)\n#endif \n\n\n#define sml_fatal_error(sml,c,fnc) \\\n\t\tprintf(\"ASSERT ERROR : Fatal error <%s> at line <%d> for function <%s>\", c, sml->tokp->sourceLine , fnc); \\\n\t\tlongjmp(sml->env_buffer, 1);\n", "meta": {"hexsha": "713b860a7b2c240e40bae6cefac347cbbdc1b908", "size": 18694, "ext": "h", "lang": "C", "max_stars_repo_path": "api.h", "max_stars_repo_name": "vinej/sml", "max_stars_repo_head_hexsha": "115c007926ca80d51a37cdf887b5252338d8bc8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "api.h", "max_issues_repo_name": "vinej/sml", "max_issues_repo_head_hexsha": "115c007926ca80d51a37cdf887b5252338d8bc8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "api.h", "max_forks_repo_name": "vinej/sml", "max_forks_repo_head_hexsha": "115c007926ca80d51a37cdf887b5252338d8bc8d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9583333333, "max_line_length": 231, "alphanum_fraction": 0.6834813309, "num_tokens": 6401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25091278688527247, "lm_q2_score": 0.019124037729210928, "lm_q1q2_score": 0.004798465603135411}}
{"text": "#pragma once\n\n#include \"arcana/finally_scope.h\"\n#include \"arcana/functional/inplace_function.h\"\n#include \"arcana/sentry.h\"\n#include \"arcana/threading/affinity.h\"\n\n#include <algorithm>\n#include <tuple>\n#include <vector>\n\n#include <gsl/gsl>\n\nnamespace arcana\n{\n    using ticket_seed = int64_t;\n\n    using ticket = gsl::final_action<\n        stdext::inplace_function<void(), sizeof(std::aligned_storage_t<sizeof(ticket_seed) + sizeof(void*)>)>>;\n\n    using ticket_scope = finally_scope<ticket>;\n\n    /*\n        An event routing class used to dispatch events to multiple listeners.\n        Each router class can only handle a certain fixed set of event types defined by EventTs.\n    */\n    template<typename... EventTs>\n    class router\n    {\n    public:\n        static constexpr size_t LISTENER_SIZE = 4 * sizeof(int64_t);\n\n        template<typename EventT>\n        using listener_function = stdext::inplace_function<void(const EventT&), LISTENER_SIZE>;\n\n\n        /*\n            Sends an event synchronously to all listeners.\n        */\n        template<typename EventT>\n        void fire(const EventT& evt)\n        {\n            GSL_CONTRACT_CHECK(\"thread affinity\", m_affinity.check());\n\n            using event = std::decay_t<EventT>;\n\n            auto& listeners = std::get<listener_group<event>>(m_listeners);\n\n            {\n                auto guard = std::get<sentry<event>>(m_sentries).take();\n\n                for (listener<event>& listener : listeners)\n                {\n                    if (listener.valid)\n                    {\n                        listener.callback(evt);\n                    }\n                }\n            }\n\n            // if we're no longer iterating the listeners list in this stack\n            // remove all the unregistered listeners and add the pending ones\n            if (!std::get<sentry<event>>(m_sentries).is_active())\n            {\n                listeners.erase(std::remove_if(listeners.begin(),\n                                               listeners.end(),\n                                               [](const listener<event>& l) { return !l.valid; }),\n                                listeners.end());\n\n                // move the pending listeners to the real list\n                // and clear the pending list\n                auto& pending = std::get<listener_group<event>>(m_pending);\n                std::move(pending.begin(), pending.end(), std::back_inserter(listeners));\n                pending.clear();\n            }\n        }\n\n        /*\n            Adds an event listener.\n        */\n        template<typename EventT, typename T>\n        ticket add_listener(T&& listener)\n        {\n            auto id = internal_add_listener<EventT>(std::forward<T>(listener));\n\n            return ticket{ [id, this] { internal_remove_listener<EventT>(id); } };\n        }\n\n        /*\n            Sets the routers thread affinity. Once this is set the methods\n            on this instance will need to be called by that thread.\n        */\n        void set_affinity(const affinity& aff)\n        {\n            m_affinity = aff;\n        }\n\n    private:\n        /*\n        Adds an event listener.\n        */\n        template<typename EventT, typename T>\n        ticket_seed internal_add_listener(T&& listener)\n        {\n            GSL_CONTRACT_CHECK(\"thread affinity\", m_affinity.check());\n\n            using event = std::decay_t<EventT>;\n\n            // if we're currently firing an event in that group we need to wait until we're done before\n            // adding the listener to the list\n            auto& listeners = std::get<sentry<event>>(m_sentries).is_active()\n                                  ? std::get<listener_group<event>>(m_pending)\n                                  : std::get<listener_group<event>>(m_listeners);\n\n            auto id = m_nextId++;\n            listeners.emplace_back(std::forward<T>(listener), id);\n            return id;\n        }\n\n        /*\n        Removes an event listener by id.\n        */\n        template<typename EventT>\n        void internal_remove_listener(const ticket_seed& id)\n        {\n            GSL_CONTRACT_CHECK(\"thread affinity\", m_affinity.check());\n\n            using event = std::decay_t<EventT>;\n\n            auto& listeners = std::get<listener_group<event>>(m_listeners);\n            auto found = std::find_if(listeners.begin(), listeners.end(), [id](const listener<event>& listener) {\n                return listener.id == id;\n            });\n\n            if (found == listeners.end())\n            {\n                assert(false && \"removing item that isn't there\");\n                return;\n            }\n\n            // don't modify the collection while iterating, just disable the listener\n            if (std::get<sentry<event>>(m_sentries).is_active())\n            {\n                found->valid = false;\n            }\n            else\n            {\n                listeners.erase(found);\n            }\n        }\n\n        template<typename EventT>\n        struct listener\n        {\n            using callback_t = listener_function<EventT>;\n\n            callback_t callback;\n            ticket_seed id;\n            bool valid;\n\n            listener(callback_t&& callback, const ticket_seed& id)\n                : callback{ std::move(callback) }\n                , id{ id }\n                , valid{ true }\n            {}\n\n            listener(const callback_t& callback, const ticket_seed& id)\n                : callback{ callback }\n                , id{ id }\n                , valid{ true }\n            {}\n        };\n\n        template<typename EventT>\n        using listener_group = std::vector<listener<EventT>>;\n\n        std::tuple<listener_group<EventTs>...> m_listeners;\n        std::tuple<sentry<EventTs>...> m_sentries;\n        std::tuple<listener_group<EventTs>...> m_pending;\n\n        affinity m_affinity;\n        ticket_seed m_nextId;\n    };\n}\n", "meta": {"hexsha": "e46a8a3af61089bfe53e08d1079c43ca25c1e292", "size": 5862, "ext": "h", "lang": "C", "max_stars_repo_path": "Source/Shared/arcana/messaging/router.h", "max_stars_repo_name": "andrei-datcu/arcana.cpp", "max_stars_repo_head_hexsha": "3c4757cbee49b3272130bf8b72094c2c62fd36c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 65.0, "max_stars_repo_stars_event_min_datetime": "2019-05-08T01:53:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T15:05:38.000Z", "max_issues_repo_path": "Source/Shared/arcana/messaging/router.h", "max_issues_repo_name": "andrei-datcu/arcana.cpp", "max_issues_repo_head_hexsha": "3c4757cbee49b3272130bf8b72094c2c62fd36c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2019-08-13T03:18:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T20:12:24.000Z", "max_forks_repo_path": "Source/Shared/arcana/messaging/router.h", "max_forks_repo_name": "andrei-datcu/arcana.cpp", "max_forks_repo_head_hexsha": "3c4757cbee49b3272130bf8b72094c2c62fd36c5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2019-05-09T23:07:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-26T14:24:29.000Z", "avg_line_length": 31.6864864865, "max_line_length": 113, "alphanum_fraction": 0.5363357216, "num_tokens": 1163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1993079883920791, "lm_q2_score": 0.024053551976189504, "lm_q1q2_score": 0.004794065058058649}}
{"text": "// Copyright \u00a9 Matt Jones and Contributors. Licensed under the MIT Licence (MIT). See LICENCE.md in the repository root\n// for more information.\n\n#ifndef NOVELRT_UTILITIES_MISC_H\n#define NOVELRT_UTILITIES_MISC_H\n\n#include <filesystem>\n#include <gsl/span>\n#include <type_traits>\n\n#if defined(NDEBUG)\n#define unused(x) (void)(x)\n#else\n#define unused(x) (void)(0)\n#endif\n\nnamespace NovelRT::Utilities\n{\n    class Misc\n    {\n    public:\n        static inline const char* CONSOLE_LOG_GENERIC = \"NovelRT\";\n        static inline const char* CONSOLE_LOG_APP = \"Application\";\n        static inline const char* CONSOLE_LOG_DOTNET = \".NET\";\n        static inline const char* CONSOLE_LOG_GFX = \"GFX\";\n        static inline const char* CONSOLE_LOG_STATS = \"Statistics\";\n        static inline const char* CONSOLE_LOG_AUDIO = \"Audio\";\n        static inline const char* CONSOLE_LOG_INPUT = \"Input\";\n        static inline const char* CONSOLE_LOG_WINDOWING = \"WindowManager\";\n\n        /**\n         * @brief Gets the path to the executable.\n         *\n         * @return The path to the executable.\n         */\n        static std::filesystem::path getExecutablePath();\n\n        /**\n         * @brief Gets the path to the directory that contains the executable. <br/>\n         * For example, `/home/stuff/game/best-game-executable` will return `/home/stuff/game`\n         *\n         * @return The path to the directory that contains the executable.\n         */\n        static std::filesystem::path getExecutableDirPath()\n        {\n            return getExecutablePath().parent_path();\n        }\n\n        [[nodiscard]] static std::vector<const char*> GetStringSpanAsCharPtrVector(\n            const gsl::span<const std::string>& target) noexcept\n        {\n            size_t extensionLength = target.size();\n            std::vector<const char*> targetPtrs{};\n            targetPtrs.reserve(extensionLength);\n\n            for (auto&& extension : target)\n            {\n                targetPtrs.emplace_back(extension.c_str());\n            }\n\n            return targetPtrs;\n        }\n    };\n}\n\ntemplate<class T, class U = std::underlying_type_t<T>> constexpr T operator~(T a)\n{\n    return static_cast<T>(~static_cast<U>(a));\n}\n\ntemplate<class T, class U = std::underlying_type_t<T>> constexpr T operator|(T a, T b)\n{\n    return static_cast<T>((static_cast<U>(a) | static_cast<U>(b)));\n}\n\ntemplate<class T, class U = std::underlying_type_t<T>> constexpr T operator&(T a, T b)\n{\n    return static_cast<T>((static_cast<U>(a) & static_cast<U>(b)));\n}\n\ntemplate<class T, class U = std::underlying_type_t<T>> constexpr T operator^(T a, T b)\n{\n    return static_cast<T>((static_cast<U>(a) ^ static_cast<U>(b)));\n}\n\ntemplate<class T, class U = std::underlying_type_t<T>> constexpr T& operator|=(T& a, T b)\n{\n    return a = static_cast<T>((static_cast<U>(a) | static_cast<U>(b)));\n}\n\ntemplate<class T, class U = std::underlying_type_t<T>> constexpr T& operator&=(T& a, T b)\n{\n    return a = static_cast<T>((static_cast<U>(a) & static_cast<U>(b)));\n}\n\ntemplate<class T, class U = std::underlying_type_t<T>> constexpr T& operator^=(T& a, T b)\n{\n    return a = static_cast<T>((static_cast<U>(a) ^ static_cast<U>(b)));\n}\n\n#endif //! NOVELRT_UTILITIES_MISC_H\n", "meta": {"hexsha": "500ec267e8fd49b79ccfa70c2a5395a9321cde50", "size": 3223, "ext": "h", "lang": "C", "max_stars_repo_path": "include/NovelRT/Utilities/Misc.h", "max_stars_repo_name": "Exadon/NovelRT", "max_stars_repo_head_hexsha": "82000a25fd53157b26a6e6d6c71cbee0ebaa241b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 167.0, "max_stars_repo_stars_event_min_datetime": "2019-02-12T14:12:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T17:14:24.000Z", "max_issues_repo_path": "include/NovelRT/Utilities/Misc.h", "max_issues_repo_name": "BanalityOfSeeking/NovelRT", "max_issues_repo_head_hexsha": "bbbe54f719acdc2fcee4604ee90fb43ff975aee9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 270.0, "max_issues_repo_issues_event_min_datetime": "2019-02-14T20:33:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T02:28:20.000Z", "max_forks_repo_path": "include/NovelRT/Utilities/Misc.h", "max_forks_repo_name": "BanalityOfSeeking/NovelRT", "max_forks_repo_head_hexsha": "bbbe54f719acdc2fcee4604ee90fb43ff975aee9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 56.0, "max_forks_repo_forks_event_min_datetime": "2019-08-22T15:57:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T19:52:18.000Z", "avg_line_length": 31.5980392157, "max_line_length": 119, "alphanum_fraction": 0.6407074155, "num_tokens": 785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.13846178345871912, "lm_q2_score": 0.03461883734516869, "lm_q1q2_score": 0.0047933859600793665}}
{"text": "#ifndef STDAFX_H\n#define STDAFX_H\n/*\n * Libs\n */\n#include <qwt.h>\n#include <qwt_legend.h>\n#include <qwt_plot.h>\n#include <qwt_plot_curve.h>\n#include <qwt_plot_grid.h>\n#include <qwt_plot_marker.h>\n#include <qwt_plot_renderer.h>\n#include <qwt_symbol.h>\n#include <QtConcurrent/QtConcurrent>\n#include <QtCore/QtCore>\n#include <QtWidgets/QtWidgets>\n#include <gsl/gsl>\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n/*\n * STL\n */\n#include <memory>\n#include <vector>\n/*\n * UTILITIES\n */\n#include \"macros.inl\"\n#endif  // !STDAFX_H\n", "meta": {"hexsha": "2cdcbe886e38b70626bf73d25237c256bf16b96a", "size": 587, "ext": "h", "lang": "C", "max_stars_repo_path": "multimedia-project/stdafx.h", "max_stars_repo_name": "philong6297/multimedia-project", "max_stars_repo_head_hexsha": "45b4bedcedde2901729d149484eae9cadb3e32b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "multimedia-project/stdafx.h", "max_issues_repo_name": "philong6297/multimedia-project", "max_issues_repo_head_hexsha": "45b4bedcedde2901729d149484eae9cadb3e32b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "multimedia-project/stdafx.h", "max_forks_repo_name": "philong6297/multimedia-project", "max_forks_repo_head_hexsha": "45b4bedcedde2901729d149484eae9cadb3e32b2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.935483871, "max_line_length": 38, "alphanum_fraction": 0.7291311755, "num_tokens": 170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2146914090629578, "lm_q2_score": 0.022286185985672904, "lm_q1q2_score": 0.004784652671903259}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef pool_81b70dbf_d70f_42d7_8770_678651c585c4_h\r\n#define pool_81b70dbf_d70f_42d7_8770_678651c585c4_h\r\n\r\n#include <assert.h>\r\n#include <memory.h>\r\n#include <stdlib.h>\r\n#include <gslib/type.h>\r\n\r\n__gslib_begin__\r\n\r\ntemplate<class _construct>\r\nclass factory\r\n{\r\npublic:\r\n    typedef _construct mycon;\r\n    typedef factory<mycon> myref;\r\n\r\npublic:\r\n    factory(void* ptr = nullptr) { _generated = (mycon*)ptr; }\r\n    const mycon* get_ptr() const { return _generated; }\r\n    mycon* get_ptr() { return _generated; }\r\n    mycon* emerge()\r\n    {\r\n        if(!_generated)\r\n            _generated = new mycon;\r\n        assert(_generated);\r\n        return _generated;\r\n    }\r\n    void destroy()\r\n    {\r\n        if(!_generated)\r\n            return;\r\n        delete _generated;\r\n        _generated = nullptr;\r\n    }\r\n\r\nprotected:\r\n    mycon*              _generated;\r\n};\r\n\r\nclass vessel\r\n{\r\nprotected:\r\n    void*               _buf;\r\n    int                 _cap;\r\n    int                 _cur;\r\n\r\npublic:\r\n    vessel()\r\n    {\r\n        _buf = nullptr;\r\n        _cap = 0;\r\n        _cur = 0;\r\n    }\r\n    ~vessel()\r\n    {\r\n        destroy();\r\n    }\r\n    void destroy()\r\n    {\r\n        if(_buf) {\r\n            free(_buf);\r\n            _buf = nullptr;\r\n        }\r\n        _cap = _cur = 0;\r\n    }\r\n    int get_cap() const\r\n    {\r\n        return _cap;\r\n    }\r\n    int get_cur() const\r\n    {\r\n        return _cur;\r\n    }\r\n    void* get_ptr() const\r\n    {\r\n        return _buf;\r\n    }\r\n    int get_rest() const\r\n    {\r\n        return _cap - _cur;\r\n    }\r\n    void flex(int size)\r\n    {\r\n        _buf = realloc(_buf, size);\r\n        _cap = size;\r\n    }\r\n    void expand(int size)\r\n    {\r\n        flex(get_cap() + size);\r\n    }\r\n    void fit()\r\n    {\r\n        _buf = realloc(_buf, _cur);\r\n        _cap = _cur;\r\n    }\r\n    void occupy(int size)\r\n    {\r\n        _cur += size;\r\n        assert(_cur <= get_cap());\r\n    }\r\n    void set_cur(int size)\r\n    {\r\n        _cur = size;\r\n        assert(_cur <= get_cap());\r\n    }\r\n    int curaddr(int ofs = 0) const\r\n    {\r\n        return (int)_buf + _cur + ofs;\r\n    }\r\n    void store(const void* buf, int size)\r\n    {\r\n        if(_cur + size > get_cap())\r\n            expand(get_cap() > size ? get_cap() : size);\r\n        assert(get_cap() >= _cur + size);\r\n        memcpy_s((void*)curaddr(), get_rest(), buf, size);\r\n        occupy(size);\r\n    }\r\n    void attach(void* buf, int size)\r\n    {\r\n        flex(0);\r\n        _buf = buf;\r\n        _cap = size;\r\n        _cur = size;\r\n    }\r\n    void attach(vessel* vsl)\r\n    {\r\n        assert(vsl);\r\n        attach(vsl->get_ptr(), vsl->get_cap());\r\n        _cur = vsl->get_cur();\r\n        vsl->detach();\r\n    }\r\n    void detach()\r\n    {\r\n        _buf = nullptr;\r\n        _cap = 0;\r\n        _cur = 0;\r\n    }\r\n    template<class tpl>\r\n    tpl& current(int ofs = 0)\r\n    {\r\n        return *((tpl*)((int)_buf + _cur + ofs));\r\n    }\r\n    template<class tpl>\r\n    tpl& front(int ofs = 0)\r\n    {\r\n        return *((tpl*)((int)_buf + ofs));\r\n    }\r\n};\r\n\r\n__gslib_end__\r\n\r\n#endif", "meta": {"hexsha": "57c7c89a0b66d6b2dfccf70429e33058e0e77174", "size": 4294, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gslib/pool.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/gslib/pool.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gslib/pool.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 23.8555555556, "max_line_length": 82, "alphanum_fraction": 0.5496040987, "num_tokens": 1072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1008786146206548, "lm_q2_score": 0.04742587570200942, "lm_q1q2_score": 0.004784256637990085}}
{"text": "/* histogram/ntuple.h\r\n * \r\n * Copyright (C) 2000 Simone Piccardi\r\n * \r\n * This program is free software; you can redistribute it and/or modify\r\n * it under the terms of the GNU General Public License as published by\r\n * the Free Software Foundation; either version 3 of the License, or (at\r\n * your option) any later version.\r\n * \r\n * This program is distributed in the hope that it will be useful, but\r\n * WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n * General Public License for more details.\r\n * \r\n * You should have received a copy of the GNU General Public License\r\n * along with this program; if not, write to the Free Software\r\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r\n *\r\n */\r\n\r\n/* Jan/2001 Modified by Brian Gough. Minor changes for GSL */\r\n\r\n#ifndef __GSL_NTUPLE_H__\r\n#define __GSL_NTUPLE_H__\r\n\r\n#if !defined( GSL_FUN )\r\n#  if !defined( GSL_DLL )\r\n#    define GSL_FUN extern\r\n#  elif defined( BUILD_GSL_DLL )\r\n#    define GSL_FUN extern __declspec(dllexport)\r\n#  else\r\n#    define GSL_FUN extern __declspec(dllimport)\r\n#  endif\r\n#endif\r\n\r\n#include <stdlib.h>\r\n#include <stdio.h>\r\n#include <gsl/gsl_errno.h>\r\n#include <gsl/gsl_histogram.h>\r\n\r\n#undef __BEGIN_DECLS\r\n#undef __END_DECLS\r\n#ifdef __cplusplus\r\n# define __BEGIN_DECLS extern \"C\" {\r\n# define __END_DECLS }\r\n#else\r\n# define __BEGIN_DECLS /* empty */\r\n# define __END_DECLS /* empty */\r\n#endif\r\n\r\n__BEGIN_DECLS\r\n\r\ntypedef struct {\r\n    FILE * file;\r\n    void * ntuple_data;\r\n    size_t size;\r\n} gsl_ntuple;\r\n\r\ntypedef struct {\r\n  int (* function) (void * ntuple_data, void * params);\r\n  void * params;\r\n} gsl_ntuple_select_fn;\r\n\r\ntypedef struct {\r\n  double (* function) (void * ntuple_data, void * params);\r\n  void * params;\r\n} gsl_ntuple_value_fn;\r\n\r\nGSL_FUN gsl_ntuple * \r\ngsl_ntuple_open (char * filename, void * ntuple_data, size_t size);\r\n\r\nGSL_FUN gsl_ntuple * \r\ngsl_ntuple_create (char * filename, void * ntuple_data, size_t size);\r\n\r\nGSL_FUN int gsl_ntuple_write (gsl_ntuple * ntuple);\r\nGSL_FUN int gsl_ntuple_read (gsl_ntuple * ntuple);\r\n\r\nGSL_FUN int gsl_ntuple_bookdata (gsl_ntuple * ntuple);  /* synonym for write */\r\n\r\nGSL_FUN int gsl_ntuple_project (gsl_histogram * h, gsl_ntuple * ntuple, \r\n                        gsl_ntuple_value_fn *value_func,\r\n                        gsl_ntuple_select_fn *select_func);\r\n\r\nGSL_FUN int gsl_ntuple_close (gsl_ntuple * ntuple);\r\n\r\n__END_DECLS\r\n\r\n#endif /* __GSL_NTUPLE_H__ */\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "8392ca9d0fbc80831f2b7b74e4e6bdb9f7b6e1b0", "size": 2530, "ext": "h", "lang": "C", "max_stars_repo_path": "deps/include/gsl/gsl_ntuple.h", "max_stars_repo_name": "berkus/music-cs", "max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z", "max_issues_repo_path": "deps/include/gsl/gsl_ntuple.h", "max_issues_repo_name": "berkus/music-cs", "max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z", "max_forks_repo_path": "deps/include/gsl/gsl_ntuple.h", "max_forks_repo_name": "berkus/music-cs", "max_forks_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 27.2043010753, "max_line_length": 82, "alphanum_fraction": 0.6972332016, "num_tokens": 646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.17781085205034783, "lm_q2_score": 0.02675928250631317, "lm_q1q2_score": 0.004758090822703512}}
{"text": "/* vector/gsl_vector_int.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_VECTOR_INT_H__\n#define __GSL_VECTOR_INT_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_block_int.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size;\n  size_t stride;\n  int *data;\n  gsl_block_int *block;\n  int owner;\n} \ngsl_vector_int;\n\ntypedef struct\n{\n  gsl_vector_int vector;\n} _gsl_vector_int_view;\n\ntypedef _gsl_vector_int_view gsl_vector_int_view;\n\ntypedef struct\n{\n  gsl_vector_int vector;\n} _gsl_vector_int_const_view;\n\ntypedef const _gsl_vector_int_const_view gsl_vector_int_const_view;\n\n\n/* Allocation */\n\nGSL_EXPORT gsl_vector_int *gsl_vector_int_alloc (const size_t n);\nGSL_EXPORT gsl_vector_int *gsl_vector_int_calloc (const size_t n);\n\nGSL_EXPORT gsl_vector_int *gsl_vector_int_alloc_from_block (gsl_block_int * b,\n                                                                const size_t offset,\n                                                                const size_t n,\n                                                                const size_t stride);\n\nGSL_EXPORT gsl_vector_int *gsl_vector_int_alloc_from_vector (gsl_vector_int * v,\n                                                                 const size_t offset,\n                                                                 const size_t n,\n                                                                 const size_t stride);\n\nGSL_EXPORT void gsl_vector_int_free (gsl_vector_int * v);\n\n/* Views */\n\nGSL_EXPORT\n_gsl_vector_int_view\ngsl_vector_int_view_array (int *v, size_t n);\n\nGSL_EXPORT\n_gsl_vector_int_view\ngsl_vector_int_view_array_with_stride (int *base,\n                                         size_t stride,\n                                         size_t n);\n\nGSL_EXPORT\n_gsl_vector_int_const_view\ngsl_vector_int_const_view_array (const int *v, size_t n);\n\nGSL_EXPORT\n_gsl_vector_int_const_view\ngsl_vector_int_const_view_array_with_stride (const int *base,\n                                               size_t stride,\n                                               size_t n);\n\nGSL_EXPORT\n_gsl_vector_int_view\ngsl_vector_int_subvector (gsl_vector_int *v,\n                            size_t i,\n                            size_t n);\n\nGSL_EXPORT\n_gsl_vector_int_view\ngsl_vector_int_subvector_with_stride (gsl_vector_int *v,\n                                        size_t i,\n                                        size_t stride,\n                                        size_t n);\n\nGSL_EXPORT\n_gsl_vector_int_const_view\ngsl_vector_int_const_subvector (const gsl_vector_int *v,\n                                  size_t i,\n                                  size_t n);\n\nGSL_EXPORT\n_gsl_vector_int_const_view\ngsl_vector_int_const_subvector_with_stride (const gsl_vector_int *v,\n                                              size_t i,\n                                              size_t stride,\n                                              size_t n);\n\n/* Operations */\n\nGSL_EXPORT int gsl_vector_int_get (const gsl_vector_int * v, const size_t i);\nGSL_EXPORT void gsl_vector_int_set (gsl_vector_int * v, const size_t i, int x);\n\nGSL_EXPORT int *gsl_vector_int_ptr (gsl_vector_int * v, const size_t i);\nGSL_EXPORT const int *gsl_vector_int_const_ptr (const gsl_vector_int * v, const size_t i);\n\nGSL_EXPORT void gsl_vector_int_set_zero (gsl_vector_int * v);\nGSL_EXPORT void gsl_vector_int_set_all (gsl_vector_int * v, int x);\nGSL_EXPORT int gsl_vector_int_set_basis (gsl_vector_int * v, size_t i);\n\nGSL_EXPORT int gsl_vector_int_fread (FILE * stream, gsl_vector_int * v);\nGSL_EXPORT int gsl_vector_int_fwrite (FILE * stream, const gsl_vector_int * v);\nGSL_EXPORT int gsl_vector_int_fscanf (FILE * stream, gsl_vector_int * v);\nGSL_EXPORT int gsl_vector_int_fprintf (FILE * stream, const gsl_vector_int * v,\n                                         const char *format);\n\nGSL_EXPORT int gsl_vector_int_memcpy (gsl_vector_int * dest, const gsl_vector_int * src);\n\nGSL_EXPORT int gsl_vector_int_reverse (gsl_vector_int * v);\n\nGSL_EXPORT int gsl_vector_int_swap (gsl_vector_int * v, gsl_vector_int * w);\nGSL_EXPORT int gsl_vector_int_swap_elements (gsl_vector_int * v, const size_t i, const size_t j);\n\nGSL_EXPORT int gsl_vector_int_max (const gsl_vector_int * v);\nGSL_EXPORT int gsl_vector_int_min (const gsl_vector_int * v);\nGSL_EXPORT void gsl_vector_int_minmax (const gsl_vector_int * v, int * min_out, int * max_out);\n\nGSL_EXPORT size_t gsl_vector_int_max_index (const gsl_vector_int * v);\nGSL_EXPORT size_t gsl_vector_int_min_index (const gsl_vector_int * v);\nGSL_EXPORT void gsl_vector_int_minmax_index (const gsl_vector_int * v, size_t * imin, size_t * imax);\n\nGSL_EXPORT int gsl_vector_int_add (gsl_vector_int * a, const gsl_vector_int * b);\nGSL_EXPORT int gsl_vector_int_sub (gsl_vector_int * a, const gsl_vector_int * b);\nGSL_EXPORT int gsl_vector_int_mul (gsl_vector_int * a, const gsl_vector_int * b);\nGSL_EXPORT int gsl_vector_int_div (gsl_vector_int * a, const gsl_vector_int * b);\nGSL_EXPORT int gsl_vector_int_scale (gsl_vector_int * a, const double x);\nGSL_EXPORT int gsl_vector_int_add_constant (gsl_vector_int * a, const double x);\n\nGSL_EXPORT int gsl_vector_int_isnull (const gsl_vector_int * v);\n\n#ifdef HAVE_INLINE\n\nextern inline\nint\ngsl_vector_int_get (const gsl_vector_int * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_VAL (\"index out of range\", GSL_EINVAL, 0);\n    }\n#endif\n  return v->data[i * v->stride];\n}\n\nextern inline\nvoid\ngsl_vector_int_set (gsl_vector_int * v, const size_t i, int x)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_VOID (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  v->data[i * v->stride] = x;\n}\n\nextern inline\nint *\ngsl_vector_int_ptr (gsl_vector_int * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return (int *) (v->data + i * v->stride);\n}\n\nextern inline\nconst int *\ngsl_vector_int_const_ptr (const gsl_vector_int * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return (const int *) (v->data + i * v->stride);\n}\n\n\n#endif /* HAVE_INLINE */\n\n__END_DECLS\n\n#endif /* __GSL_VECTOR_INT_H__ */\n\n\n", "meta": {"hexsha": "1e0f9050075c913fd074ff5fc46f63769c830af5", "size": 7305, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/gsl/include/gsl/gsl_vector_int.h", "max_stars_repo_name": "dynaryu/vaws", "max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/gsl/include/gsl/gsl_vector_int.h", "max_issues_repo_name": "dynaryu/vaws", "max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/gsl/include/gsl/gsl_vector_int.h", "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.085106383, "max_line_length": 101, "alphanum_fraction": 0.6689938398, "num_tokens": 1767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1943678063520299, "lm_q2_score": 0.02442308903335559, "lm_q1q2_score": 0.004747062239753645}}
{"text": "/*\n   Copyright [2020] [IBM Corporation]\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n       http://www.apache.org/licenses/LICENSE-2.0\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\n\n/*\n * Authors:\n *\n */\n\n#ifndef _NUPM_OPENED_SPACE_H_\n#define _NUPM_OPENED_SPACE_H_\n\n#include <common/byte_span.h>\n#include <common/fd_locked.h>\n#include <common/logging.h> /* log_source */\n#include <common/memory_mapped.h>\n#include <common/moveable_ptr.h>\n#include <common/string_view.h>\n#include <common/types.h> /* addr_t */\n#include <gsl/pointers>\n#include <cassert>\n#include <cstddef>\n#include <string>\n#include <vector>\n\nnamespace nupm\n{\nstruct dax_manager;\n\nstruct range_use\n{\nprivate:\n  common::moveable_ptr<dax_manager> _dm;\n  /* Note: arena_fs used multiple ranges */\n  std::vector<common::memory_mapped> _iovm;\n\n  std::vector<common::memory_mapped> address_coverage_check(std::vector<common::memory_mapped> &&iovm);\n  using byte = common::byte;\n  using byte_span = common::byte_span;\npublic:\n#if 0\n  const auto & operator[](std::size_t i) const { return _iovm.at(i).iov(); }\n#else\n  byte_span operator[](std::size_t i) const { const auto &iov = _iovm.at(i).iov(); return common::make_byte_span(::base(iov), ::size(iov)); }\n#endif\n  range_use(dax_manager *dm_, std::vector<common::memory_mapped> &&);\n  range_use(const range_use &) = delete;\n  range_use &operator=(const range_use &) = delete;\n  range_use(range_use &&) noexcept = default;\n  void grow(std::vector<common::memory_mapped> &&);\n  void shrink(std::size_t size);\n  ~range_use();\n  gsl::not_null<dax_manager *> dm() const { return _dm; }\n  ::off_t size() const;\n};\n\nstruct space_opened : private common::log_source\n{\nprivate:\n  using byte_span = common::byte_span;\n  common::fd_locked _fd_locked;\n  /* Note: arena_fs may someday use multiple ranges */\n  range_use _range;\n\n  /* owns the file mapping */\n  std::vector<common::memory_mapped> map_dev(int fd, const addr_t base_addr);\n  std::vector<common::memory_mapped> map_fs(int fd, const std::vector<byte_span> &mapping, ::off_t offset);\npublic:\n  space_opened(const common::log_source &, dax_manager * dm_, common::fd_locked && fd, const addr_t base_addr);\n  space_opened(const common::log_source &, dax_manager * dm_, common::fd_locked && fd, const std::vector<byte_span> &mapping);\n  space_opened(space_opened &&) noexcept = default;\n  void shrink(std::size_t size);\n  void grow(std::vector<byte_span> && iovv);\n  int fd() const { return _fd_locked.fd(); }\n  range_use &range() { return _range; }\n};\n}\n#endif\n", "meta": {"hexsha": "9936d4a8658cda5c3498d483db77514acc2ae76c", "size": 2928, "ext": "h", "lang": "C", "max_stars_repo_path": "src/lib/libnupm/include/nupm/space_opened.h", "max_stars_repo_name": "moshik1/mcas", "max_stars_repo_head_hexsha": "a6af06bc278993fb3ffe780f230d2396b2287c26", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 60.0, "max_stars_repo_stars_event_min_datetime": "2020-04-28T08:15:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T10:35:15.000Z", "max_issues_repo_path": "src/lib/libnupm/include/nupm/space_opened.h", "max_issues_repo_name": "moshik1/mcas", "max_issues_repo_head_hexsha": "a6af06bc278993fb3ffe780f230d2396b2287c26", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 66.0, "max_issues_repo_issues_event_min_datetime": "2020-09-03T23:40:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T20:34:52.000Z", "max_forks_repo_path": "src/lib/libnupm/include/nupm/space_opened.h", "max_forks_repo_name": "moshik1/mcas", "max_forks_repo_head_hexsha": "a6af06bc278993fb3ffe780f230d2396b2287c26", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2019-11-02T06:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T01:56:42.000Z", "avg_line_length": 32.8988764045, "max_line_length": 141, "alphanum_fraction": 0.7219945355, "num_tokens": 760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15203223393803664, "lm_q2_score": 0.031143832445689162, "lm_q1q2_score": 0.004734866420110031}}
{"text": "#pragma once\n\n#include <cstddef>\n#include <gsl/string_span>\n#include <map>\n#include <memory>\n#include <string_view>\n#include <vector>\n\nnamespace multihash {\n\nusing string_span = gsl::span<char>;\n\nclass algorithm {\n public:\n  /** Compute the hash of an input range */\n  template <typename InputIterator>\n  auto digest(InputIterator first, InputIterator last) -> std::string;\n\n  /** Write the hash of an input range into output */\n  template <typename InputIterator, typename OutputIterator>\n  auto digest(InputIterator first, InputIterator last,\n              OutputIterator output) -> OutputIterator;\n\n  virtual ~algorithm() = default;\n\n private:\n  virtual void reset() = 0;\n  virtual std::size_t digest_size() const = 0;\n  virtual std::size_t block_size() const = 0;\n  virtual void update(std::string_view data) = 0;\n  virtual std::size_t digest(string_span output) = 0;\n  std::string digest();\n\n\n};\n\ntemplate <typename InputIterator>\nauto algorithm::digest(InputIterator first, InputIterator last) -> std::string {\n  auto result = std::string{};\n  result.reserve(digest_size());\n  digest(first, last, std::back_inserter(result));\n  return result;\n}\n\ntemplate <typename InputIterator, typename OutputIterator>\nauto algorithm::digest(InputIterator first, InputIterator last,\n                                     OutputIterator output) -> OutputIterator {\n  reset();\n  auto buffer = std::vector<char>{};\n  auto chunk_size = block_size();\n  buffer.reserve(chunk_size);\n  while (first != last) {\n    for (auto i = 0u; first != last && i < chunk_size; ++i, ++first) {\n      buffer.emplace_back(*first);\n    }\n    auto view = std::string_view(buffer.data(), buffer.size());\n    update(view);\n    buffer.clear();\n  }\n  auto result = digest();\n  std::copy(result.begin(), result.end(), output);\n  return output;\n}\n\n}  // namespace multihash", "meta": {"hexsha": "053864beef5da3fb6e4e98cad9eeb73df32078b2", "size": 1833, "ext": "h", "lang": "C", "max_stars_repo_path": "multihash/algorithm.h", "max_stars_repo_name": "lockblox/multihash", "max_stars_repo_head_hexsha": "9f26e84082514a1278c1ba1767fe3d067724b26a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-11-26T11:25:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-31T19:35:12.000Z", "max_issues_repo_path": "multihash/algorithm.h", "max_issues_repo_name": "cpp-ipfs/cpp-multihash", "max_issues_repo_head_hexsha": "9f26e84082514a1278c1ba1767fe3d067724b26a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-12-13T18:04:07.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-14T19:39:21.000Z", "max_forks_repo_path": "multihash/algorithm.h", "max_forks_repo_name": "cpp-ipfs/cpp-multihash", "max_forks_repo_head_hexsha": "9f26e84082514a1278c1ba1767fe3d067724b26a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-05-29T06:15:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-15T08:51:52.000Z", "avg_line_length": 27.7727272727, "max_line_length": 80, "alphanum_fraction": 0.6857610475, "num_tokens": 421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20181323186177208, "lm_q2_score": 0.023330768426492957, "lm_q1q2_score": 0.0047084577779691345}}
{"text": "#include <config.h>\n#include <math.h>\n#include <gsl/gsl_statistics.h>\n\n#define BASE_LONG_DOUBLE\n#include \"templates_on.h\"\n#include \"wskew_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_LONG_DOUBLE\n\n#define BASE_DOUBLE\n#include \"templates_on.h\"\n#include \"wskew_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_DOUBLE\n\n#define BASE_FLOAT\n#include \"templates_on.h\"\n#include \"wskew_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_FLOAT\n\n", "meta": {"hexsha": "9e747c6cdc594d0cbc15597fbcd0e836a2ebcabb", "size": 439, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/statistics/wskew.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/statistics/wskew.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/statistics/wskew.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 19.0869565217, "max_line_length": 31, "alphanum_fraction": 0.7767653759, "num_tokens": 108, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2814056194821861, "lm_q2_score": 0.016657042877108286, "lm_q1q2_score": 0.004687385469573993}}
{"text": "#include <bindings.cmacros.h>\n#include <gsl/gsl_multiset.h>\n\nBC_INLINE2(gsl_multiset_get,gsl_multiset*,size_t,size_t)\n", "meta": {"hexsha": "9ef9e5f443fb55d72ee21813543235cc87086684", "size": 118, "ext": "c", "lang": "C", "max_stars_repo_path": "bindings-gsl/src/Bindings/Gsl/Multisets.c", "max_stars_repo_name": "flip111/bindings-dsl", "max_stars_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2015-04-29T00:31:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T09:29:03.000Z", "max_issues_repo_path": "bindings-gsl/src/Bindings/Gsl/Multisets.c", "max_issues_repo_name": "flip111/bindings-dsl", "max_issues_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2015-01-04T06:32:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-07T09:49:12.000Z", "max_forks_repo_path": "bindings-gsl/src/Bindings/Gsl/Multisets.c", "max_forks_repo_name": "flip111/bindings-dsl", "max_forks_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2015-01-03T20:43:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-10T19:31:38.000Z", "avg_line_length": 23.6, "max_line_length": 56, "alphanum_fraction": 0.813559322, "num_tokens": 35, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1778108694780496, "lm_q2_score": 0.026355352368151074, "lm_q1q2_score": 0.004686268119981316}}
{"text": "#pragma once\n\n#include <halley/maths/vector2.h>\n#include <halley/maths/rect.h>\n#include <memory>\n#include <halley/resources/resource.h>\n#include <halley/text/halleystring.h>\n#include <halley/data_structures/hash_map.h>\n#include <gsl/span>\n#include \"halley/maths/vector4.h\"\n\nnamespace Halley\n{\n\tclass Resources;\n\tclass Serializer;\n\tclass Deserializer;\n\tclass ResourceDataStatic;\n\tclass Texture;\n\tclass ResourceLoader;\n\n\tclass SpriteSheetEntry\n\t{\n\tpublic:\n\t\tVector2f pivot;\n\t\tVector2i origPivot;\n\t\tVector2f size;\n\t\tRect4f coords;\n\t\tVector4s trimBorder;\n\t\tVector4s slices;\n\t\tint duration = 0;\n\t\tbool rotated = false;\n\t\tbool sliced = false;\n\n\t\tvoid serialize(Serializer& s) const;\n\t\tvoid deserialize(Deserializer& s);\n\t};\n\n\tclass SpriteSheetFrameTag\n\t{\n\tpublic:\n\t\tString name;\n\t\tint from = 0;\n\t\tint to = 0;\n\n\t\tvoid serialize(Serializer& s) const;\n\t\tvoid deserialize(Deserializer& s);\n\t};\n\t\n\tclass SpriteSheet : public Resource\n\t{\n\tpublic:\n\t\tconst std::shared_ptr<const Texture>& getTexture() const;\n\t\tconst SpriteSheetEntry& getSprite(const String& name) const;\n\t\tconst SpriteSheetEntry& getSprite(size_t idx) const;\n\n\t\tconst std::vector<SpriteSheetFrameTag>& getFrameTags() const;\n\t\tstd::vector<String> getSpriteNames() const;\n\n\t\tsize_t getSpriteCount() const;\n\t\tsize_t getIndex(const String& name) const;\n\t\tbool hasSprite(const String& name) const;\n\n\t\tvoid loadJson(gsl::span<const gsl::byte> data);\n\n\t\tvoid addSprite(String name, const SpriteSheetEntry& sprite);\n\t\tvoid setTextureName(String name);\n\n\t\tstatic std::unique_ptr<SpriteSheet> loadResource(ResourceLoader& loader);\n\t\tconstexpr static AssetType getAssetType() { return AssetType::SpriteSheet; }\n\t\tvoid reload(Resource&& resource) override;\n\n\t\tvoid serialize(Serializer& s) const;\n\t\tvoid deserialize(Deserializer& s);\n\n\tprivate:\n\t\tResources* resources = nullptr;\n\n\t\tmutable std::shared_ptr<const Texture> texture;\n\t\tstd::vector<SpriteSheetEntry> sprites;\n\t\tHashMap<String, uint32_t> spriteIdx;\n\t\tstd::vector<SpriteSheetFrameTag> frameTags;\n\t\tString textureName;\n\n\t\tvoid loadTexture(Resources& resources) const;\n\t};\n\n\tclass SpriteResource : public Resource\n\t{\n\tpublic:\n\t\tSpriteResource(std::shared_ptr<const SpriteSheet> spriteSheet, size_t idx);\n\n\t\tconst SpriteSheetEntry& getSprite() const;\n\t\tsize_t getIdx() const;\n\t\tstd::shared_ptr<const SpriteSheet> getSpriteSheet() const;\n\n\t\tconstexpr static AssetType getAssetType() { return AssetType::Sprite; }\n\t\tstatic std::unique_ptr<SpriteResource> loadResource(ResourceLoader& loader);\n\t\tvoid reload(Resource&& resource) override;\n\n\tprivate:\n\t\tstd::weak_ptr<const SpriteSheet> spriteSheet;\n\t\tsize_t idx = -1;\n\t};\n}\n", "meta": {"hexsha": "e429f20d36398a085be99c78e3c9570bb958c084", "size": 2619, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engine/core/include/halley/core/graphics/sprite/sprite_sheet.h", "max_stars_repo_name": "sunhay/halley", "max_stars_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T20:23:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T20:23:45.000Z", "max_issues_repo_path": "src/engine/core/include/halley/core/graphics/sprite/sprite_sheet.h", "max_issues_repo_name": "sunhay/halley", "max_issues_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engine/core/include/halley/core/graphics/sprite/sprite_sheet.h", "max_forks_repo_name": "sunhay/halley", "max_forks_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9428571429, "max_line_length": 78, "alphanum_fraction": 0.750668194, "num_tokens": 649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.26284182582255894, "lm_q2_score": 0.017712296046007475, "lm_q1q2_score": 0.004655532232242296}}
{"text": "/*\n * Copyright <2012> <Vincent Le Guilloux,Peter Schmidtke, Pierre Tuffery>\n * Copyright <2013-2018> <Peter Schmidtke, Vincent Le Guilloux>\n\nPermission 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:\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\nTHE 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.\n\n */\n\n\n#ifndef DH_UTILS\n#define DH_UTILS\n\n/* ------------------------------ INCLUDES ---------------------------------- */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <limits.h>\n#include <time.h>\n\n#ifndef _WIN32\n#include <unistd.h>\n#endif\n\n#ifdef MD_USE_GSL \t/* GSL */\n\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n\n#endif \t\t\t\t/* /GSL */\n\n#include \"memhandler.h\"\n\n/* ------------------------------- PUBLIC MACROS ---------------------------- */\n\n#define M_MAX_PDB_NAME_LEN 200  /**< maximum pdb filename length*/\n\n#define M_SIGN 1\n#define M_NO_SIGN 0\n\n\n#ifdef MD_USE_GSL\t/* GSL */\n\n#define M_GEN_MTWISTER gsl_rng_mt19937\n#define M_GEN_GFSR4 gsl_rng_gfsr4\n#define M_GEN_TAUS gsl_rng_taus2\n#define M_GEN_RANLXS0 gsl_rng_ranlxs0\n#define M_GEN_RANLXS1 gsl_rng_ranlxs1\n\n#endif\t\t\t\t/* /GSL */\n\n/* ------------------------------ PUBLIC STRUCTURES ------------------------- */\n\ntypedef struct tab_str \n{\n\tchar **t_str ;\n\tint nb_str ;\n\n} tab_str ; \n\n\n/* ------------------------------- PROTOTYPES ------------------------------- */\n\nint str_is_number(const char *str, const int sign) ;\nint str_is_float(const char *str, const int sign) ;\nvoid str_trim(char *str) ;\ntab_str* str_split(const char *str, const int sep) ;\n\nshort file_exists(const char * filename);\n\n\ntab_str* f_readl(const char *fpath, int nchar_max) ;\nvoid free_tab_str(tab_str *tstr) ;\nvoid print_tab_str(tab_str* strings) ;\n\nint in_tab(int *tab, int size, int val) ;\nint index_of(int *tab, int size, int val)  ;\n\n\nvoid remove_ext(char *str) ;\nvoid remove_path(char *str) ;\nvoid extract_ext(char *str, char *dest) ;\nvoid extract_path(char *str, char *dest) ;\n\nvoid start_rand_generator(void) ;\nfloat rand_uniform(float min, float max) ;\n\nFILE* fopen_pdb_check_case(char *name, const char *mode)  ;\n\nfloat float_get_min_in_2D_array(float **t,size_t n,int col);\nfloat float_get_max_in_2D_array(float **t,size_t n,int col);\n\n#endif\n", "meta": {"hexsha": "af89a317dbd16256627a319653e7aa381882cc0c", "size": 3100, "ext": "h", "lang": "C", "max_stars_repo_path": "headers/utils.h", "max_stars_repo_name": "kencresset/fpocket", "max_stars_repo_head_hexsha": "1ce0f6040e141c8279b50707913593d69d4addf1", "max_stars_repo_licenses": ["Qhull", "MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "headers/utils.h", "max_issues_repo_name": "kencresset/fpocket", "max_issues_repo_head_hexsha": "1ce0f6040e141c8279b50707913593d69d4addf1", "max_issues_repo_licenses": ["Qhull", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "headers/utils.h", "max_forks_repo_name": "kencresset/fpocket", "max_forks_repo_head_hexsha": "1ce0f6040e141c8279b50707913593d69d4addf1", "max_forks_repo_licenses": ["Qhull", "MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-23T09:48:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-23T09:48:16.000Z", "avg_line_length": 31.9587628866, "max_line_length": 460, "alphanum_fraction": 0.6941935484, "num_tokens": 738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21206880435710534, "lm_q2_score": 0.02194825507434171, "lm_q1q2_score": 0.004654540211340417}}
{"text": "#pragma once\n\n#include <variant>\n\n#include <gsl/gsl-lite.hpp>\n\n#include <clrie/instruction_factory.h>\n\nnamespace appmap { namespace cil {\n\nstruct op {\n    ILOrdinalOpcode op;\n};\n\nstruct token_op {\n    ILOrdinalOpcode op;\n    mdToken token;\n};\n\nstruct long_op {\n    ILOrdinalOpcode op;\n    uint64_t value;\n};\n\ntemplate <ILOrdinalOpcode Op>\nstruct token_opcode: token_op {\n    token_opcode(mdToken token): token_op{Op, token} {}\n};\n\nnamespace ops {\n    struct ldarg { int index; };\n    struct ldloc { int index; };\n    struct stloc { int index; };\n\n\n    using ldfld = token_opcode<Cee_Ldfld>;\n    using stfld = token_opcode<Cee_Stfld>;\n    using ldftn = token_opcode<Cee_Ldftn>;\n    using call = token_opcode<Cee_Call>;\n    using calli = token_opcode<Cee_Calli>;\n    using callvirt = token_opcode<Cee_Callvirt>;\n    using newobj = token_opcode<Cee_Newobj>;\n\n    constexpr inline auto ldnull = op{Cee_Ldnull};\n    constexpr inline auto pop = op{Cee_Pop};\n    constexpr inline auto dup = op{Cee_Dup};\n\n    struct ldc: long_op {\n        ldc(uint64_t val): long_op{Cee_Ldc_I8, val} {}\n\n        template <typename Ret, typename... Args>\n        ldc(Ret(*fn)(Args...)): ldc(reinterpret_cast<uint64_t>(fn)) {}\n    };\n}\n\nusing instruction = std::variant<ops::ldarg, ops::ldloc, ops::stloc, op, token_op, long_op>;\n\nclrie::instruction_factory::instruction_sequence compile(const gsl::span<const instruction> code, const clrie::instruction_factory &factory);\nclrie::instruction_factory::instruction_sequence compile(std::initializer_list<const instruction> code, const clrie::instruction_factory &factory);\n\n}}\n", "meta": {"hexsha": "94ccc43186adaa8604409b3192cdc72b3797efc3", "size": 1599, "ext": "h", "lang": "C", "max_stars_repo_path": "source/cil.h", "max_stars_repo_name": "applandinc/appmap-dotnet", "max_stars_repo_head_hexsha": "f62bf237493472a61701c82ddf8d6f3491707307", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-03-11T04:59:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-24T02:04:49.000Z", "max_issues_repo_path": "source/cil.h", "max_issues_repo_name": "applandinc/appmap-dotnet", "max_issues_repo_head_hexsha": "f62bf237493472a61701c82ddf8d6f3491707307", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18.0, "max_issues_repo_issues_event_min_datetime": "2021-03-28T22:32:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-22T16:45:26.000Z", "max_forks_repo_path": "source/cil.h", "max_forks_repo_name": "applandinc/appmap-dotnet", "max_forks_repo_head_hexsha": "f62bf237493472a61701c82ddf8d6f3491707307", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-24T02:05:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-24T02:05:16.000Z", "avg_line_length": 25.7903225806, "max_line_length": 147, "alphanum_fraction": 0.7060662914, "num_tokens": 416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1993079883920791, "lm_q2_score": 0.023330766601441497, "lm_q1q2_score": 0.004650008158978409}}
{"text": "#ifndef __GSL_VECTOR_H__\n#define __GSL_VECTOR_H__\n\n#include <gsl/vector/gsl_vector_double.h>\n\n\n#endif /* __GSL_VECTOR_H__ */\n", "meta": {"hexsha": "2b15303aede2fc801c85668d70ad625b6b1b8e86", "size": 125, "ext": "h", "lang": "C", "max_stars_repo_path": "Cartwheel/cartwheel-3d/gsl/vector/gsl_vector.h", "max_stars_repo_name": "MontyThibault/centre-of-mass-awareness", "max_stars_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Cartwheel/cartwheel-3d/gsl/vector/gsl_vector.h", "max_issues_repo_name": "MontyThibault/centre-of-mass-awareness", "max_issues_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cartwheel/cartwheel-3d/gsl/vector/gsl_vector.h", "max_forks_repo_name": "MontyThibault/centre-of-mass-awareness", "max_forks_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.625, "max_line_length": 41, "alphanum_fraction": 0.792, "num_tokens": 34, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.17106120013047907, "lm_q2_score": 0.02716923005873027, "lm_q1q2_score": 0.004647601100467486}}
{"text": "//\n//  Revision.hpp\n//  PretendToWork\n//\n//  Created by tqtifnypmb on 14/12/2017.\n//  Copyright \u00a9 2017 tqtifnypmb. All rights reserved.\n//\n\n#pragma once\n\n#include \"../rope/Range.h\"\n#include \"../types.h\"\n\n#include <gsl/gsl>\n#include <vector>\n#include <string>\n\nnamespace brick\n{\n    \nclass Rope;\nclass Revision {\npublic:\n    enum class Operation {\n        insert,\n        erase,\n    };\n    \n    Revision(size_t authorId, size_t revId, Operation op, const Range& range);\n    Revision(size_t authorId, size_t revId, Operation op, const Range& range, const detail::CodePointList& text);\n    Revision(const Revision&) = default;\n    Revision() = default;\n    \n    void apply(gsl::not_null<Rope*> rope) const;\n    bool canApply(gsl::not_null<const Rope*> rope) const;\n    \n    size_t authorId() const {\n        return authorId_;\n    }\n    \n    bool prior(const Revision& rev) const {\n        return authorId() <= rev.authorId();\n    }\n    \n    size_t revId() const {\n        return revId_;\n    }\n    \n    const Range& range() const {\n        return range_;\n    }\n    \n    Range& range() {\n        return range_;\n    }\n    \n    int affectLength() const {\n        if (op() == Operation::insert) {\n            return static_cast<int>(cplist().size());\n        } else {\n            return range().length;\n        }\n    }\n    \n    Operation op() const {\n        return op_;\n    }\n    \n    bool valid() const {\n        return !range_.empty() && range_.location >= 0;\n    }\n    \n    void setInvalid() {\n        range_.length = 0;\n    }\n    \n    const detail::CodePointList& cplist() const {\n        return cplist_;\n    }\n    \nprivate:\n    \n    size_t authorId_;\n    \n    // revId_ only identify individual revision\n    // newer revision doesn't have to have greater revId_\n    size_t revId_;\n    detail::CodePointList cplist_;\n    Operation op_;\n    Range range_;\n};\n    \n}   // namespace brick\n", "meta": {"hexsha": "38a7c0f7595f4c23b44de88c29c4eb984ff84ddb", "size": 1882, "ext": "h", "lang": "C", "max_stars_repo_path": "src/crdt/Revision.h", "max_stars_repo_name": "tqtifnypmb/brick", "max_stars_repo_head_hexsha": "49398f77113c57d4e256e838a5ad6b9a6381de6a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/crdt/Revision.h", "max_issues_repo_name": "tqtifnypmb/brick", "max_issues_repo_head_hexsha": "49398f77113c57d4e256e838a5ad6b9a6381de6a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/crdt/Revision.h", "max_forks_repo_name": "tqtifnypmb/brick", "max_forks_repo_head_hexsha": "49398f77113c57d4e256e838a5ad6b9a6381de6a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0212765957, "max_line_length": 113, "alphanum_fraction": 0.5781083953, "num_tokens": 472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18713268216242657, "lm_q2_score": 0.024798159655048765, "lm_q1q2_score": 0.00464054612894135}}
{"text": "#pragma once\n#include <utility>\n#include <algorithm>\n#include <gsl/span>\n#include <array>\n#include <vector>\n#include <memory>\n#include <chrono>\n\nstruct patternbyte\n{\n    uint8_t value;\n    uint8_t mask;\n\n    patternbyte()\n    {\n        this->clear();\n    }\n\n    patternbyte(const uint8_t value, const uint8_t mask)\n    {\n        this->value = value;\n        this->mask = mask;\n    }\n\n    bool opaque() const\n    {\n        return this->mask == 0xffui8;\n    }\n\n    void clear()\n    {\n        this->value = 0ui8;\n        this->mask = 0xffui8;\n    }\n\n    friend inline bool operator==(\n        const patternbyte& left,\n        const uint8_t& right)\n    {\n        return (right & left.mask) == (left.value & left.mask); // value should already be masked\n    }\n\n    friend inline bool operator==(\n        const uint8_t& left,\n        const patternbyte& right)\n    {\n        return (left & right.mask) == (right.value & right.mask);\n    }\n};\n\ninline int hexchtoint(char ch)\n{\n    if (ch >= '0' && ch <= '9')\n        return ch - '0';\n    else if (ch >= 'A' && ch <= 'F')\n        return ch - 'A' + 10;\n    else if (ch >= 'a' && ch <= 'f')\n        return ch - 'a' + 10;\n    return -1;\n}\n\nstatic auto compile_pattern(\n    const char* pattern)\n{\n    auto compiled_pattern = std::make_unique<std::vector< patternbyte>>();\n    patternbyte b;\n\n    char c;\n    auto shift = 0x4UL;\n    while (c = *pattern++) {\n        if (c == '?' || c == '.') {\n            b.mask &= ~(0xf << shift);\n        }\n        else if (auto num = hexchtoint(c); num != -1) {\n            b.value |= (num & 0xf) << shift;\n        }\n        else {\n            continue;\n        }\n\n        if (!shift) {\n            compiled_pattern->push_back(b);\n            b.clear();\n        }\n        shift ^= 0x4UL;\n    }\n    if (!shift) {\n        b.mask &= 0xf;\n        compiled_pattern->push_back(b);\n    }\n    return compiled_pattern;\n}\n\nclass pattern_searcher\n{\n    std::unique_ptr<std::vector< patternbyte>> _cp;\n\npublic:\n    pattern_searcher(const char* pattern)\n    {\n        _cp = compile_pattern(pattern);\n    }\n\n    template <class Iterator>\n    std::pair<Iterator, Iterator> operator()(Iterator first, Iterator last) const\n    {\n        if (first == last)\n            return std::make_pair(last, last);\n        if (_cp->empty())\n            return std::make_pair(first, first);\n\n        auto it = std::search(first, last, std::begin(*_cp), std::end(*_cp));\n\n        if (it == last)\n            return std::make_pair(last, last);\n        return std::make_pair(it, it + std::size(*_cp));\n    }\n};", "meta": {"hexsha": "01ca5b7328d2f87c4605f5f607f4cfe68c14f62d", "size": 2550, "ext": "h", "lang": "C", "max_stars_repo_path": "src/loginhelper/searchers.h", "max_stars_repo_name": "bnsmodpolice/loginhelper", "max_stars_repo_head_hexsha": "7505878b225c7be144ec5e8abf4484133b2cbff9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-12-18T04:53:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-22T20:48:03.000Z", "max_issues_repo_path": "include/searchers.h", "max_issues_repo_name": "bnsmodpolice/loginhelper", "max_issues_repo_head_hexsha": "7505878b225c7be144ec5e8abf4484133b2cbff9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/searchers.h", "max_forks_repo_name": "bnsmodpolice/loginhelper", "max_forks_repo_head_hexsha": "7505878b225c7be144ec5e8abf4484133b2cbff9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-18T18:03:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-18T18:03:36.000Z", "avg_line_length": 21.4285714286, "max_line_length": 97, "alphanum_fraction": 0.5243137255, "num_tokens": 676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23091975234373585, "lm_q2_score": 0.02002344213009975, "lm_q1q2_score": 0.004623808297751761}}
{"text": "#ifndef _HistWidget_H\n#define _HistWidget_H\n\n#include <QWidget>\n#include <gsl/gsl_histogram.h>\n\n#include \"src_config.h\" \n\nclass QwtPlot;\n\nclass _HIST_EXPORT_ HistWidget : public QWidget\n{\npublic:\n    HistWidget (double xmin, double xmax, double ymin, double ymax, QWidget * parent=0, Qt::WindowFlags flags=0);\n    virtual ~HistWidget (void);\n\n    void setHistogram (const gsl_histogram * hist);\n\nprivate:\n    //\n    // Variables\n    //\n    QwtPlot *plot;\n    gsl_histogram * w_hist;\nprivate:\n    Q_OBJECT\n\n};\n\n#endif\n", "meta": {"hexsha": "564083d016bc16e6231b83eccf79bddc9c942f71", "size": 517, "ext": "h", "lang": "C", "max_stars_repo_path": "src/gui/HistWidget.h", "max_stars_repo_name": "YuriyRusinov/Histogram", "max_stars_repo_head_hexsha": "76aff0621acf6d43449cabd5c54c950c77ba7c2c", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gui/HistWidget.h", "max_issues_repo_name": "YuriyRusinov/Histogram", "max_issues_repo_head_hexsha": "76aff0621acf6d43449cabd5c54c950c77ba7c2c", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gui/HistWidget.h", "max_forks_repo_name": "YuriyRusinov/Histogram", "max_forks_repo_head_hexsha": "76aff0621acf6d43449cabd5c54c950c77ba7c2c", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.6774193548, "max_line_length": 113, "alphanum_fraction": 0.6982591876, "num_tokens": 134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.17781087819190095, "lm_q2_score": 0.025957358987381232, "lm_q1q2_score": 0.004615500797088689}}
{"text": "#include <netlib-jni.h>\n#include <cblas.h>\n\n// these CBLAS get* helpers are really irritating because\n// the first thing the cblas_ methods do is to do a reverse\n// lookup for the char and then pass it to the fortran lib!\n\nCBLAS_TRANSPOSE getCblasTrans(const char * fortranChar) {\n\tswitch (fortranChar[0]) {\n\t    case 'N': return CblasNoTrans;\n\t    case 'n': return CblasNoTrans;\n\t\tcase 'T': return CblasTrans;\n\t\tcase 't': return CblasTrans;\n\t\tdefault: return -1;\n\t}\n}\n\nCBLAS_UPLO getCblasUpLo(const char * fortranChar) {\n\tswitch (fortranChar[0]) {\n\t    case 'U': return CblasUpper;\n\t    case 'u': return CblasUpper;\n\t\tcase 'L': return CblasLower;\n\t\tcase 'l': return CblasLower;\n\t\tdefault: return -1;\n\t}\n}\n\nCBLAS_SIDE getCblasSide(const char * fortranChar) {\n\tswitch (fortranChar[0]) {\n\t    case 'L': return CblasLeft;\n\t    case 'l': return CblasLeft;\n\t\tcase 'R': return CblasRight;\n\t\tcase 'r': return CblasRight;\n\t\tdefault: return -1;\n\t}\n}\n\nCBLAS_DIAG getCblasDiag(const char * fortranChar) {\n\tswitch (fortranChar[0]) {\n\t    case 'N': return CblasNonUnit;\n\t    case 'n': return CblasNonUnit;\n\t\tcase 'U': return CblasUnit;\n\t\tcase 'u': return CblasUnit;\n\t\tdefault: return -1;\n\t}\n}\n\ninline void check_memory(JNIEnv * env, void * arg) {\n\tif (arg != NULL) {\n\t\treturn;\n\t}\n\t/*\n\t * WARNING: Memory leak\n\t *\n\t * This doesn't clean up successful allocations prior to throwing this exception.\n\t * However, it's a pretty dire situation to be anyway and the client code is not\n\t * expected to recover.\n\t */\n\t(*env)->ThrowNew(env, (*env)->FindClass(env, \"java/lang/OutOfMemoryError\"),\n\t\t\"Out of memory transferring array to native code in F2J JNI\");\n}\n\ninline int jboolean2int(jboolean b) {\n    switch (b) {\n        case JNI_TRUE: return 1;\n        default: return 0;\n    }\n}\n\ninline jboolean int2jboolean(int i) {\n    switch (i) {\n        case 1: return JNI_TRUE;\n        default: return JNI_FALSE;\n    }\n}\n\n\nint* jbooleanArray2intArray(JNIEnv * env, jboolean * a, jint size) {\n\tint * j = (int*) malloc(size * sizeof(int));\n\tcheck_memory(env, j);\n\t\n\tint i;\n\tfor (i = 0 ; i < size ; i++) {\n\t    j[i] = jboolean2int(a[i]);\n\t}\n\treturn j;\n}\n\nvoid intArray2jbooleanArray(int * a, jboolean * b, jint size) {\n\tint i;\n\tfor (i = 0 ; i < size ; i++) {\n\t    b[i] = int2jboolean(a[i]);\n\t}\n}\n\n", "meta": {"hexsha": "1484635fc3668147aaa66f0ccc9e8177e987846e", "size": 2268, "ext": "c", "lang": "C", "max_stars_repo_path": "netlib/JNI/netlib-jni.c", "max_stars_repo_name": "almson/netlib-java", "max_stars_repo_head_hexsha": "f6973ee73a520529a1d28fa66261fbada27a05a2", "max_stars_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-28T01:29:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-28T01:29:18.000Z", "max_issues_repo_path": "netlib/JNI/netlib-jni.c", "max_issues_repo_name": "almson/netlib-java", "max_issues_repo_head_hexsha": "f6973ee73a520529a1d28fa66261fbada27a05a2", "max_issues_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "netlib/JNI/netlib-jni.c", "max_forks_repo_name": "almson/netlib-java", "max_forks_repo_head_hexsha": "f6973ee73a520529a1d28fa66261fbada27a05a2", "max_forks_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.625, "max_line_length": 82, "alphanum_fraction": 0.6521164021, "num_tokens": 682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2337063569140403, "lm_q2_score": 0.019719130123652447, "lm_q1q2_score": 0.004608486062712722}}
{"text": "/*==================BEGIN ASF DOCUMENTATION==================*/\n/*\nABOUT EDITING THIS DOCUMENTATION:\nIf you wish to edit the documentation for this program, you need to change the\nfollowing defines.\n*/\n\n#define ASF_NAME_STRING \\\n\"asf_export\"\n\n#define ASF_USAGE_STRING \\\n\"   \"ASF_NAME_STRING\" [-format <output_format>] [-byte <sample mapping option>]\\n\"\\\n\"              [-rgb <red> <green> <blue>] [-band <band_id | all>]\\n\"\\\n\"              [-lut <look up table file>] [-truecolor] [-falsecolor]\\n\"\\\n\"              [-log <log_file>] [-quiet] [-license] [-version] [-help]\\n\"\\\n\"              <in_base_name> <out_full_name>\\n\"\n\n#define ASF_DESCRIPTION_STRING \\\n\"   This program ingests ASF internal format data and exports said data to a\\n\"\\\n\"   number of graphics file formats (TIFF/GEOTIFF, JPEG, PGM, PNG, POlSARPRO,\\n\"\\\n\"   HDF5 and netCDF).\\n\"\\\n\"   If the input data was geocoded and the ouput format supports geocoding,\\n\"\\\n\"   that information will be included.  Optionally, you may apply look-up tables,\\n\"\\\n\"   assign color bands (-rgb, -truecolor, -falsecolor).\\n\"\n\n#define ASF_INPUT_STRING \\\n\"   A file set in the ASF internal data format.\\n\"\n\n#define ASF_OUTPUT_STRING \\\n\"   The converted data in the output file, with the requested format.\\n\"\n\n#define ASF_OPTIONS_STRING \\\n\"   -format <format>\\n\"\\\n\"        Format to export to. Must be one of the following:\\n\"\\\n\"            tiff      - Tagged Image File Format, with byte valued pixels\\n\"\\\n\"            geotiff   - GeoTIFF file, with floating point or byte valued pixels\\n\"\\\n\"            jpeg      - Lossy compressed image, with byte valued pixels\\n\"\\\n\"            pgm       - Portable graymap image, with byte valued pixels\\n\"\\\n\"            png       - Portable network graphic, with byte valued pixels\\n\"\\\n\"            polsarpro - Flat binary floating point files in PolSARPro format\\n\"\\\n\"            hdf5      - HDF5 format, with floating point or byte valued pixels\\n\"\\\n\"            netcdf    - netCDF format compliant to the CF conventions\\n\"\\\n\"   NOTE: When exporting to a GeoTIFF format file, all map-projection\\n\"\\\n\"         information is included in GeoKeys as specified in the GeoTIFF\\n\"\\\n\"         standard.  The other graphics file formats do not support the\\n\"\\\n\"         storing of map-projection parameters in the output file.  If you\\n\"\\\n\"         wish to maintain the map-projection and/or georeference (corner\\n\"\\\n\"         point) information in the output, you should choose the GeoTIFF\\n\"\\\n\"         output format.\\n\\n\"\\\n\"   NOTE: When exporting to a GeoTIFF format file, the data format (floating\\n\"\\\n\"         point, byte, 16-bit integer, etc) will be maintained.  Many viewers\\n\"\\\n\"         cannot view non-integer data.  Leaving the data format the same as\\n\"\\\n\"         the original produces the most accurate export, but remapping it to\\n\"\\\n\"         byte range (0-255) with the -byte option will result in the greatest\\n\"\\\n\"         compatibility with viewers and GIS software packages.\\n\\n\"\\\n\"   -byte <sample mapping option>\\n\"\\\n\"        Converts output image to byte using the following options:\\n\"\\\n\"            truncate\\n\"\\\n\"                values less than 0 are mapped to 0, values greater than 255\\n\"\\\n\"                are mapped to 255, and values in between are converted to\\n\"\\\n\"                whole numbers (the fractional part of the values are truncated,\\n\"\\\n\"                not rounded.)\\n\"\\\n\"            minmax\\n\"\\\n\"                determines the minimum and maximum values of the input image\\n\"\\\n\"                and linearly maps those values to the byte range of 0 to 255.\\n\"\\\n\"                The remapping is accomplished using real (floating point)\\n\"\\\n\"                numbers then the result is converted to a whole number by\\n\"\\\n\"                truncating the fractional part.\\n\"\\\n\"            sigma\\n\"\\\n\"                determines the mean and standard deviation of an image and\\n\"\\\n\"                defines a range of +/- two standard deviations (2-sigma)\\n\"\\\n\"                around the mean value, and maps this buffer to the byte range\\n\"\\\n\"                0 to 255 as described for minmax above.  The range limits are\\n\"\\\n\"                adjusted if the either of the 2-sigma range limits lie outside\\n\"\\\n\"                the range of the original values.  As with the other remapping\\n\"\\\n\"                methods, the calculation of values are made with real numbers\\n\"\\\n\"                and the result is converted to a whole number by truncating\\n\"\\\n\"                any fractional part.\\n\"\\\n\"            histogram_equalize\\n\"\\\n\"                develops a look-up table by integrating the (no-adaptation)\\n\"\\\n\"                whole-image histogram and then normalizing the result to the\\n\"\\\n\"                0-255 range.  The result is that areas of low contrast, i.e.\\n\"\\\n\"                flat topography, have a stronger contrast expansion applied\\n\"\\\n\"                while areas of high contrast, i.e. non-flat topography, will\\n\"\\\n\"                receive less contrast expansion.  Histogram equalization\\n\"\\\n\"                is a useful transform for making hard-to-see detail more\\n\"\\\n\"                visible for the the viewer but is likewise a nonlinear\\n\"\\\n\"                transform that results in minor (apparent) topography shifts\\n\"\\\n\"                within the image.  Since shifts occur the most in areas where\\n\"\\\n\"                the contrast is expanded the most, i.e. flat topography, and\\n\"\\\n\"                less in areas of more interesting topography, the pragmatic\\n\"\\\n\"                conclusion is that the nonlinear shifts are quite\\n\"\\\n\"                insignificant for the majority of users ...only important\\n\"\\\n\"                if performing precision geography measurements or overlays.\\n\"\\\n\"   -rgb <red> <green> <blue>\\n\"\\\n\"        Converts output image into a color RGB image.\\n\"\\\n\"        <red>, <green>, and <blue> specify which band (channel)\\n\"\\\n\"        is assigned to color planes red, green, or blue,\\n\"\\\n\"        ex) '-rgb HH VH VV', or '-rgb 3 2 1'.  If the word 'ignore' is\\n\"\\\n\"        provided as one or more bands, then the associated color plane\\n\"\\\n\"        will not be exported, e.g. '-rgb ignore 2 1' will result in an\\n\"\\\n\"        RGB file that has a zero in each RGB pixel's red component, band 2\\n\"\\\n\"        assigned to the green channel, and band 1 assigned to the blue.\\n\"\\\n\"        The result will be an image with only greens and blues in it.\\n\"\\\n\"        Currently implemented for GeoTIFF, TIFF, JPEG and PNG.\\n\"\\\n\"        Cannot be used together with the -band option.\\n\"\\\n\"   -lut <look up table file>\\n\"\\\n\"        Applies a color look up table to the image while exporting.\\n\"\\\n\"        Only allowed for single-band images.  Images must contain byte (8-bit)\\n\"\\\n\"        data (except for data deriving from PolSARpro classifications.) Some\\n\"\\\n\"        look-up table files are in the look_up_tables subdirectory in\\n\"\\\n\"        the asf_tools share directory.  The tool will look in\\n\"\\\n\"        this directory for the specified file if it isn't found\\n\"\\\n\"        in the current directory.\\n\"\\\n\"   -truecolor\\n\"\\\n\"        For 3 or 4 band optical satellite images where the first band is the\\n\"\\\n\"        the blue band, the second green, and the third red.  This option will\\n\"\\\n\"        export the third band as the red element, the second band as the green\\n\"\\\n\"        element, and the first band as the blue element.  Performs a 2-sigma\\n\"\\\n\"        constrast expansion on each individual band during the export (similar\\n\"\\\n\"        to most GIS software packages.)  To export a true-color image WITHOUT\\n\"\\\n\"        the contrast expansion associated with the truecolor option, use the\\n\"\\\n\"        -rgb option instead.  The rgb option will directly assign the\\n\"\\\n\"        available bands, unaltered, to the RGB color channels in the output\\n\"\\\n\"        file, e.g.\\n\\n\"\\\n\"          'asf_export -rgb 03 02 01 <infile> <outfile>'.\\n\\n\"\\\n\"        Only allowed for multi-band images with 3 or more bands.\\n\"\\\n\"        The truecolor option cannot be used together with any of the\\n\"\\\n\"        following options: -rgb, -band, or -falsecolor.\\n\"\\\n\"   -falsecolor\\n\"\\\n\"        For 4 band optical satellite images where the second band is green,\\n\"\\\n\"        the third red, and the fourth is the near-infrared band.  Exports\\n\"\\\n\"        the fourth (IR) band as the red element, the third band as the green\\n\"\\\n\"        element, and the second band as the blue element.  Performs a 2-sigma\\n\"\\\n\"        constrast expansion on the individual bands during the export.  To\\n\"\\\n\"        export a falsecolor image WITHOUT the contrast expansion, use the\\n\"\\\n\"        -rgb flag to directly assign the available bands to the RGB color\\n\"\\\n\"        channels, e.g.\\n\\n\"\\\n\"          'asf_export -rgb 04 03 02 <infile> <outfile>'.\\n\\n\"\\\n\"        Only allowed for multi-band images with 4 bands.\\n\"\\\n\"        Cannot be used together with any of the following: -rgb, -band,\\n\"\\\n\"        or -truecolor.\\n\"\\\n\"   -band <band_id | all>\\n\"\\\n\"        If the data contains multiple data files, one for each band (channel)\\n\"\\\n\"        then export the band identified by 'band_id' (only).  If 'all' is\\n\"\\\n\"        specified rather than a band_id, then export all available bands into\\n\"\\\n\"        individual files, one for each band.  Default is '-band all'.\\n\"\\\n\"        Cannot be chosen together with the -rgb option.\\n\"\\\n\"   -log <logFile>\\n\"\\\n\"        Output will be written to a specified log file.\\n\"\\\n\"   -quiet\\n\"\\\n\"        Supresses all non-essential output.\\n\"\\\n\"   -license\\n\"\\\n\"        Print copyright and license for this software then exit.\\n\"\\\n\"   -version\\n\"\\\n\"        Print version and copyright then exit.\\n\"\\\n\"   -help\\n\"\\\n\"        Print a help page and exit.\\n\"\n\n#define ASF_EXAMPLES_STRING \\\n\"   To export to the default GeoTIFF format from file1.img and file1.meta\\n\"\\\n\"   to file1.tif:\\n\"\\\n\"        example> \"ASF_NAME_STRING\" file1 file1\\n\\n\"\\\n\"   NOTE: When exporting to a GeoTIFF format file, all map-projection\\n\"\\\n\"         information is included in GeoKeys as specified in the GeoTIFF\\n\"\\\n\"         standard.\\n\\n\"\\\n\"   NOTE: When exporting to a GeoTIFF format file, the data format (floating\\n\"\\\n\"         point, byte, 16-bit integer, etc) will be maintained.  Many viewers\\n\"\\\n\"         cannot view non-integer data.  Leaving the data format the same as\\n\"\\\n\"         the original produces the most accurate export, but remapping it to\\n\"\\\n\"         byte range (0-255) with the -byte option will result in the greatest\\n\"\\\n\"         compatibility with viewers and GIS software packages.\\n\"\\\n\"\\n\"\\\n\"   To export to file2.jpg in the jpeg format:\\n\"\\\n\"        example> \"ASF_NAME_STRING\" -format jpeg file1 file2\\n\"\\\n\"\\n\"\n\n#define ASF_LIMITATIONS_STRING \\\n\"   Currently supports ingest of ASF format floating point and byte data (only).\\n\"\\\n\"\\n\"\\\n\"   Floating-point image formats (i.e., geotiff) are not supported in many\\n\"\\\n\"   image viewing programs.\\n\"\n\n#define ASF_SEE_ALSO_STRING \\\n\"   asf_mapready, asf_import\\n\"\n\n/*===================END ASF DOCUMENTATION===================*/\n\n\n#include <ctype.h>\n#include <errno.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n#include <unistd.h>\n#include <limits.h>\n\n#include <cla.h>\n#include <envi.h>\n#include <esri.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_statistics.h>\n\n#include <asf.h>\n#include <asf_endian.h>\n#include <asf_meta.h>\n#include <asf_raster.h>\n#include <asf_export.h>\n#include <asf_contact.h>\n#include <asf_license.h>\n\n// Local prototypes\nint is_numeric(char *str);\n\n// Print minimalistic usage info & exit\nstatic void print_usage(void)\n{\n  asfPrintStatus(\"\\n\"\n      \"Usage:\\n\"\n      ASF_USAGE_STRING\n      \"\\n\");\n  exit(EXIT_FAILURE);\n}\n\n// Print the help info & exit\nstatic void print_help(void)\n{\n  asfPrintStatus(\n      \"\\n\"\n      \"Tool name:\\n   \" ASF_NAME_STRING \"\\n\\n\"\n      \"Usage:\\n\" ASF_USAGE_STRING \"\\n\"\n      \"Description:\\n\" ASF_DESCRIPTION_STRING \"\\n\"\n      \"Input:\\n\" ASF_INPUT_STRING \"\\n\"\n      \"Output:\\n\"ASF_OUTPUT_STRING \"\\n\"\n      \"Options:\\n\" ASF_OPTIONS_STRING \"\\n\"\n      \"Examples:\\n\" ASF_EXAMPLES_STRING \"\\n\"\n      \"Limitations:\\n\" ASF_LIMITATIONS_STRING \"\\n\"\n      \"See also:\\n\" ASF_SEE_ALSO_STRING \"\\n\"\n      \"Contact:\\n\" ASF_CONTACT_STRING \"\\n\"\n      \"Version:\\n   \" SVN_REV \" (part of \" TOOL_SUITE_NAME \" \" MAPREADY_VERSION_STRING \")\\n\\n\");\n  exit(EXIT_FAILURE);\n}\n\nint\ncheckForOption (char *key, int argc, char *argv[])\n{\n  int ii = 0;\n  while ( ii < argc ) {\n    if ( strmatch (key, argv[ii]) )\n      return ii;\n    ++ii;\n  }\n  return FLAG_NOT_SET;\n}\n\nstatic const char *sigma_str(int with_sigma) {\n    return with_sigma ? \"w/sigma\" : \"\";\n}\n\n// Main program body.\nint\nmain (int argc, char *argv[])\n{\n  output_format_t format = 0;\n  meta_parameters *md;\n  char *in_base_name, *output_name;\n  char **band_names=NULL;\n  int rgb=0;\n  int true_color;\n  int false_color;\n  int num_bands_found;\n  int ignored[3] = {0, 0, 0};\n  int num_ignored = 0;\n\n  in_base_name = (char *) MALLOC(sizeof(char)*255);\n  output_name = (char *) MALLOC(sizeof(char)*255);\n\n/**********************BEGIN COMMAND LINE PARSING STUFF**********************/\n  // Command line input goes in it's own structure.\n  command_line_parameters_t command_line;\n  strcpy (command_line.format, \"\");\n  command_line.size = NO_MAXIMUM_OUTPUT_SIZE;\n  strcpy (command_line.in_data_name, \"\");\n  strcpy (command_line.in_meta_name, \"\");\n  strcpy (command_line.output_name, \"\");\n  command_line.verbose = FALSE;\n  command_line.quiet = FALSE;\n  strcpy (command_line.leader_name, \"\");\n  strcpy (command_line.cal_params_file, \"\");\n  strcpy (command_line.cal_comment, \"\");\n  command_line.sample_mapping = 0;\n  strcpy(command_line.red_channel, \"\");\n  strcpy(command_line.green_channel, \"\");\n  strcpy(command_line.blue_channel, \"\");\n  strcpy(command_line.band, \"\");\n  strcpy(command_line.look_up_table_name, \"\");\n\n  int formatFlag, logFlag, quietFlag, byteFlag, rgbFlag, bandFlag, lutFlag;\n  int truecolorFlag, falsecolorFlag;\n  int needed_args = 3;  //command & argument & argument\n  int ii;\n  char sample_mapping_string[25];\n\n  //Check to see which options were specified\n  if (   (checkForOption(\"--help\", argc, argv) != FLAG_NOT_SET)\n      || (checkForOption(\"-h\", argc, argv) != FLAG_NOT_SET)\n      || (checkForOption(\"-help\", argc, argv) != FLAG_NOT_SET) ) {\n      print_help();\n  }\n  get_asf_share_dir_with_argv0(argv[0]);\n  handle_license_and_version_args(argc, argv, ASF_NAME_STRING);\n\n  formatFlag = checkForOption (\"-format\", argc, argv);\n  logFlag = checkForOption (\"-log\", argc, argv);\n  quietFlag = checkForOption (\"-quiet\", argc, argv);\n  byteFlag = checkForOption (\"-byte\", argc, argv);\n  rgbFlag = checkForOption (\"-rgb\", argc, argv);\n  bandFlag = checkForOption (\"-band\", argc, argv);\n  lutFlag = checkForOption (\"-lut\", argc, argv);\n  truecolorFlag = checkForOption(\"-truecolor\", argc, argv);\n  falsecolorFlag = checkForOption(\"-falsecolor\", argc, argv);\n\n  if ( formatFlag != FLAG_NOT_SET ) {\n    needed_args += 2;           // Option & parameter.\n  }\n  if ( quietFlag != FLAG_NOT_SET ) {\n    needed_args += 1;           // Option & parameter.\n  }\n  if ( logFlag != FLAG_NOT_SET ) {\n    needed_args += 2;           // Option & parameter.\n  }\n  if ( byteFlag != FLAG_NOT_SET ) {\n    needed_args += 2;           // Option & parameter.\n  }\n  if ( rgbFlag != FLAG_NOT_SET ) {\n    needed_args += 4;           // Option & 3 parameters.\n  }\n  if ( bandFlag != FLAG_NOT_SET ) {\n    needed_args += 2;           // Option & parameter.\n  }\n  if ( lutFlag != FLAG_NOT_SET ) {\n    needed_args += 2;           // Option & parameter.\n  }\n  if ( truecolorFlag != FLAG_NOT_SET ) {\n    needed_args += 1;           // Option only\n  }\n  if ( falsecolorFlag != FLAG_NOT_SET ) {\n    needed_args += 1;           // Option only\n  }\n\n  if ( argc != needed_args ) {\n    print_usage ();                   // This exits with a failure.\n  }\n\n  // We also need to make sure the last three options are close to\n  // what we expect.\n  if ( argv[argc - 1][0] == '-' || argv[argc - 2][0] == '-' ) {\n    print_usage (); // This exits with a failure.\n  }\n\n  // Make sure any options that have parameters are followed by\n  // parameters (and not other options) Also make sure options'\n  // parameters don't bleed into required arguments.\n  if ( formatFlag != FLAG_NOT_SET ) {\n    if ( argv[formatFlag + 1][0] == '-' || formatFlag >= argc - 3 ) {\n      print_usage ();\n    }\n  }\n  if ( byteFlag != FLAG_NOT_SET ) {\n    if ( argv[byteFlag + 1][0] == '-' || byteFlag >= argc - 3 ) {\n      print_usage ();\n    }\n  }\n  if ( rgbFlag != FLAG_NOT_SET ) {\n    if (( argv[rgbFlag + 1][0] == '-' && argv[rgbFlag + 2][0] == '-' &&\n          argv[rgbFlag + 3][0] == '-' ) || rgbFlag >= argc - 5 ) {\n      print_usage ();\n    }\n  }\n  if ( bandFlag != FLAG_NOT_SET ) {\n    if ( argv[bandFlag + 1][0] == '-' || bandFlag >= argc - 3 ) {\n      print_usage ();\n    }\n  }\n  if ( lutFlag != FLAG_NOT_SET ) {\n    if ( argv[lutFlag + 1][0] == '-' || lutFlag >= argc - 3 ) {\n      print_usage ();\n    }\n  }\n  if ( logFlag != FLAG_NOT_SET ) {\n    if ( argv[logFlag + 1][0] == '-' || logFlag >= argc - 3 ) {\n      print_usage ();\n    }\n  }\n\n  // Make sure there are no flag incompatibilities\n  if ( (rgbFlag != FLAG_NOT_SET           &&\n        (bandFlag != FLAG_NOT_SET         ||\n         truecolorFlag != FLAG_NOT_SET    ||\n         falsecolorFlag != FLAG_NOT_SET))\n     ||\n       (bandFlag != FLAG_NOT_SET         &&\n        (rgbFlag != FLAG_NOT_SET         ||\n         truecolorFlag != FLAG_NOT_SET   ||\n         falsecolorFlag != FLAG_NOT_SET))\n     ||\n       (truecolorFlag != FLAG_NOT_SET    &&\n        (bandFlag != FLAG_NOT_SET        ||\n         rgbFlag != FLAG_NOT_SET         ||\n         falsecolorFlag != FLAG_NOT_SET))\n     ||\n       (falsecolorFlag != FLAG_NOT_SET   &&\n        (bandFlag != FLAG_NOT_SET        ||\n         truecolorFlag != FLAG_NOT_SET   ||\n         rgbFlag != FLAG_NOT_SET))\n     )\n  {\n    asfPrintWarning(\"The following options may only be used one at a time:\\n\"\n        \"    %s\\n    %s\\n    %s\\n    %s\\n    %s\\n    %s\\n\",\n        \"-rgb\", \"-truecolor\", \"-falsecolor\", \"-band\");\n    print_help();\n  }\n  if ( (rgbFlag != FLAG_NOT_SET         ||\n        truecolorFlag != FLAG_NOT_SET   ||\n        falsecolorFlag != FLAG_NOT_SET) &&\n        lutFlag != FLAG_NOT_SET\n     )\n    asfPrintError(\"Look up table option can only be used on single-band \"\n          \"images.\\n\");\n\n  if( logFlag != FLAG_NOT_SET ) {\n    strcpy(logFile, argv[logFlag+1]);\n  }\n  else {\n    sprintf(logFile, \"tmp%i.log\", (int)getpid());\n  }\n  logflag = TRUE; // Since we always log, set the old school logflag to true\n  fLog = FOPEN (logFile, \"a\");\n\n  // Set old school quiet flag (for use in our libraries)\n  quietflag = ( quietFlag != FLAG_NOT_SET ) ? TRUE : FALSE;\n\n  // We're good enough at this point... print the splash screen.\n  asfSplashScreen (argc, argv);\n\n  // Grab the input and output name\n  strcpy (in_base_name, argv[argc - 2]);\n  strcpy (output_name, argv[argc - 1]);\n  strcpy (command_line.output_name, output_name);\n\n  // If user added \".img\", strip it.\n  char *ext = findExt(in_base_name);\n  if (ext && strcmp(ext, \".img\") == 0) *ext = '\\0';\n\n  // Set default output type\n  if( formatFlag != FLAG_NOT_SET ) {\n    strcpy (command_line.format, argv[formatFlag + 1]);\n  }\n  else {\n    // Default behavior: produce a geotiff.\n    strcpy (command_line.format, \"geotiff\");\n  }\n\n  // Compose input metadata name\n  strcpy (command_line.in_meta_name, in_base_name);\n  strcat (command_line.in_meta_name, \".meta\");\n\n  // for some validation, need the metadata\n  md = meta_read (command_line.in_meta_name);\n\n  // Convert the string to upper case.\n  for ( ii = 0 ; ii < strlen (command_line.format) ; ++ii ) {\n    command_line.format[ii] = toupper (command_line.format[ii]);\n  }\n  if (strcmp (command_line.format, \"PGM\") == 0 &&\n      (rgbFlag != FLAG_NOT_SET      ||\n      truecolorFlag != FLAG_NOT_SET ||\n      falsecolorFlag != FLAG_NOT_SET)\n     )\n  {\n    asfPrintWarning(\"Greyscale PGM output is not compatible with color options:\\n\"\n                    \"(RGB, True Color, False Color, color look-up tables, etc\\n)\"\n                    \"...Defaulting to producing separate greyscale PGM files for available band.\\n\");\n    rgbFlag = FLAG_NOT_SET;\n    truecolorFlag = FLAG_NOT_SET;\n    falsecolorFlag = FLAG_NOT_SET;\n  }\n\n  // Set the default byte scaling mechanisms\n  if (md->optical) {\n     // for optical data, default sample mapping is NONE\n      command_line.sample_mapping = NONE;\n  }\n  // for other data, default is based on the output type\n  else if (strcmp (command_line.format, \"TIFF\") == 0 ||\n           strcmp (command_line.format, \"TIF\")  == 0 ||\n           strcmp (command_line.format, \"JPEG\") == 0 ||\n           strcmp (command_line.format, \"JPG\")  == 0 ||\n           strcmp (command_line.format, \"PNG\")  == 0 ||\n           strcmp (command_line.format, \"PGM\")  == 0 ||\n\t   strcmp (command_line.format, \"PNG_ALPHA\") == 0 ||\n\t   strcmp (command_line.format, \"PNG_GE\") == 0)\n  {\n    command_line.sample_mapping = SIGMA;\n  }\n  else if (strcmp (command_line.format, \"GEOTIFF\") == 0) {\n    command_line.sample_mapping = NONE;\n  }\n\n  if ( quietFlag != FLAG_NOT_SET )\n    command_line.quiet = TRUE;\n  else\n    command_line.quiet = FALSE;\n\n  // Set rgb combination\n  if ( rgbFlag != FLAG_NOT_SET ) {\n    int i;\n\n    for (i=0, num_ignored = 0; i<3; i++) {\n      ignored[i] = strncmp(\"IGNORE\", uc(argv[rgbFlag + i + 1]), 6) == 0 ? 1 : 0;\n      num_ignored += ignored[i] ? 1 : 0;\n    }\n    asfRequire(num_ignored < 3,\n               \"Cannot ignore all bands.  Exported image would be blank.\\n\");\n\n    strcpy (command_line.red_channel, ignored[0] ? \"Ignored\" : argv[rgbFlag + 1]);\n    strcpy (command_line.green_channel, ignored[1] ? \"Ignored\" : argv[rgbFlag + 2]);\n    strcpy (command_line.blue_channel, ignored[2] ? \"Ignored\" : argv[rgbFlag + 3]);\n\n    // Check to see if the bands are numeric and in range\n    int r_channel = atoi(command_line.red_channel);\n    int g_channel = atoi(command_line.green_channel);\n    int b_channel = atoi(command_line.blue_channel);\n\n    /////////// Numeric channel case ////////////\n    // Remove trailing non-numeric characters from the channel number\n    // string and pad front end nicely with a zero\n    if (!ignored[0] && is_numeric(command_line.red_channel) &&\n        r_channel >= 1 && r_channel <= MAX_BANDS) {\n      sprintf(command_line.red_channel, \"%02d\", atoi(command_line.red_channel));\n    }\n    if (!ignored[1] && is_numeric(command_line.green_channel) &&\n        g_channel >= 1 && g_channel <= MAX_BANDS) {\n      sprintf(command_line.green_channel, \"%02d\", atoi(command_line.green_channel));\n    }\n    if (!ignored[2] && is_numeric(command_line.blue_channel) &&\n        b_channel >= 1 && b_channel <= MAX_BANDS) {\n      sprintf(command_line.blue_channel, \"%02d\", atoi(command_line.blue_channel));\n    }\n  }\n\n  // Set up the bands for true or false color optical data\n  true_color = false_color = 0;\n  int with_sigma = FALSE;\n  if (truecolorFlag != FLAG_NOT_SET || falsecolorFlag != FLAG_NOT_SET) {\n    int ALOS_optical = (md->optical && strncmp(md->general->sensor, \"ALOS\", 4) == 0) ? 1 : 0;\n    if (md->optical && truecolorFlag != FLAG_NOT_SET) {\n      if (ALOS_optical) {\n        with_sigma = TRUE;\n        strcpy(command_line.red_channel,   \"03\");\n        strcpy(command_line.green_channel, \"02\");\n        strcpy(command_line.blue_channel,  \"01\");\n        true_color = 1;\n        asfPrintStatus(\"Applying True Color contrast expansion to following channels:\");\n      }\n      else {\n        char **bands = extract_band_names(md->general->bands, 3);\n        asfRequire(bands != NULL,\n                   \"-truecolor option specified for non-true color optical image.\\n\");\n\n        asfPrintWarning(\"Attempting to use the -truecolor option with non-ALOS\\n\"\n            \"optical data.\\n\");\n        strcpy(command_line.red_channel, bands[2]);\n        strcpy(command_line.green_channel, bands[1]);\n        strcpy(command_line.blue_channel, bands[0]);\n        int i;\n        for (i=0; i<3; i++) {\n          FREE(bands[i]);\n        }\n        FREE(bands);\n      }\n    }\n    if (md->optical && falsecolorFlag != FLAG_NOT_SET) {\n      if (ALOS_optical) {\n        with_sigma = TRUE;\n        strcpy(command_line.red_channel,   \"04\");\n        strcpy(command_line.green_channel, \"03\");\n        strcpy(command_line.blue_channel,  \"02\");\n        false_color = 1;\n        asfPrintStatus(\"Applying False Color contrast expansion to the following channels:\");\n      }\n      else {\n        char **bands = extract_band_names(md->general->bands, 4);\n        asfRequire(bands != NULL,\n                   \"-falsecolor option specified for an optical image with fewer than 4 bands.\\n\");\n\n        asfPrintWarning(\"Attempting to use the -falsecolor option with non-ALOS\\n\"\n            \"optical data.\\n\");\n        strcpy(command_line.red_channel, bands[3]);\n        strcpy(command_line.green_channel, bands[2]);\n        strcpy(command_line.blue_channel, bands[1]);\n        int i;\n        for (i=0; i<3; i++) {\n          FREE(bands[i]);\n        }\n        FREE(bands);\n      }\n    }\n    if (!ALOS_optical && !md->optical) {\n      asfPrintError(\"-truecolor or -falsecolor option selected with non-optical data\\n\");\n    }\n  }\n\n  if (rgbFlag != FLAG_NOT_SET ||\n     truecolorFlag != FLAG_NOT_SET ||\n     falsecolorFlag != FLAG_NOT_SET)\n  {\n    char red_band[16], green_band[16], blue_band[16];\n\n    asfPrintStatus(\"\\nRed channel  : %s %s\\n\", command_line.red_channel, sigma_str(with_sigma));\n    asfPrintStatus(\"Green channel: %s %s\\n\", command_line.green_channel, sigma_str(with_sigma));\n    asfPrintStatus(\"Blue channel : %s %s\\n\\n\", command_line.blue_channel, sigma_str(with_sigma));\n\n    if (is_numeric(command_line.red_channel) &&\n        is_numeric(command_line.green_channel) &&\n        is_numeric(command_line.blue_channel))\n    {\n      sprintf(red_band, \"%02d\", atoi(command_line.red_channel));\n      sprintf(green_band, \"%02d\", atoi(command_line.green_channel));\n      sprintf(blue_band, \"%02d\", atoi(command_line.blue_channel));\n      band_names = find_bands(in_base_name, rgbFlag,\n                              red_band,\n                              green_band,\n                              blue_band,\n                              &num_bands_found);\n    }\n    else {\n      band_names = find_bands(in_base_name, rgbFlag,\n                              command_line.red_channel,\n                              command_line.green_channel,\n                              command_line.blue_channel,\n                              &num_bands_found);\n    }\n  }\n\n  // Set band\n  if ( bandFlag != FLAG_NOT_SET) {\n    strcpy (command_line.band, argv[bandFlag + 1]);\n    band_names = find_single_band(in_base_name, command_line.band,\n                  &num_bands_found);\n  }\n  else if (rgbFlag == FLAG_NOT_SET &&\n          truecolorFlag == FLAG_NOT_SET &&\n          falsecolorFlag == FLAG_NOT_SET &&\n          bandFlag == FLAG_NOT_SET) {\n    bandFlag=1; // For proper messaging to the user\n    strcpy (command_line.band, \"all\");\n    band_names = find_single_band(in_base_name, command_line.band,\n                                  &num_bands_found);\n  }\n\n  // Read look up table name\n  if ( lutFlag != FLAG_NOT_SET) {\n    strcpy(command_line.look_up_table_name, argv[lutFlag + 1]);\n    rgb = 1;\n  }\n\n  // Set scaling mechanism\n  if ( byteFlag != FLAG_NOT_SET ) {\n    strcpy (sample_mapping_string, argv[byteFlag + 1]);\n    for ( ii = 0; ii < strlen(sample_mapping_string); ii++) {\n      sample_mapping_string[ii] = toupper (sample_mapping_string[ii]);\n    }\n    if ( strcmp (sample_mapping_string, \"TRUNCATE\") == 0 )\n      command_line.sample_mapping = TRUNCATE;\n    else if ( strcmp(sample_mapping_string, \"MINMAX\") == 0 )\n      command_line.sample_mapping = MINMAX;\n    else if ( strcmp(sample_mapping_string, \"SIGMA\") == 0 )\n      command_line.sample_mapping = SIGMA;\n    else if ( strcmp(sample_mapping_string, \"HISTOGRAM_EQUALIZE\") == 0 )\n      command_line.sample_mapping = HISTOGRAM_EQUALIZE;\n    else if ( strcmp(sample_mapping_string, \"NONE\") == 0 ) {\n        asfPrintWarning(\"Sample remapping method (-byte option) is set to NONE\\n\"\n                \"which doesn't make sense.  Defaulting to TRUNCATE...\\n\");\n        command_line.sample_mapping = TRUNCATE;\n    }\n    else\n      asfPrintError(\"Unrecognized byte scaling method '%s'.\\n\",\n                    sample_mapping_string);\n  }\n\n  int is_polsarpro = (md->general->bands && strstr(md->general->bands, \"POLSARPRO\") != NULL) ? 1 : 0;\n  if ( !is_polsarpro               &&\n       lutFlag != FLAG_NOT_SET     &&\n       bandFlag == FLAG_NOT_SET    &&\n       md->general->band_count > 1)\n  {\n    asfPrintError(\"Look up tables can only be applied to single band\"\n          \" images\\n\");\n  }\n\n  if ( !is_polsarpro                       &&\n       lutFlag != FLAG_NOT_SET             &&\n       command_line.sample_mapping == NONE &&\n       md->general->data_type != BYTE      &&\n       md->general->band_count == 1)\n  {\n    asfPrintError(\"Look up tables can only be applied to byte output\"\n          \" images\\n\");\n  }\n\n  // Report what is going to happen\n  if (rgbFlag != FLAG_NOT_SET ||\n     truecolorFlag != FLAG_NOT_SET ||\n     falsecolorFlag != FLAG_NOT_SET)\n  {\n    if (num_bands_found >= 3) {\n      asfPrintStatus(\"Exporting multiband image ...\\n\\n\");\n      rgb = 1;\n    }\n    else {\n      asfPrintError(\"Not all RGB channels found.\\n\");\n    }\n  }\n  else if (bandFlag != FLAG_NOT_SET) {\n    if (strcmp_case(command_line.band, \"ALL\") == 0) {\n      if (multiband(command_line.format, \n\t\t    extract_band_names(md->general->bands, md->general->band_count), \n\t\t    md->general->band_count))\n\tasfPrintStatus(\"Exporting multiband image ...\\n\\n\");\n      else  if (num_bands_found > 1)\n        asfPrintStatus(\"Exporting each band into individual greyscale files ...\\n\\n\");\n    }\n    else if (num_bands_found == 1) {\n      if (lutFlag != FLAG_NOT_SET)\n    asfPrintStatus(\"Exporting band '%s' applying look up table ...\\n\\n\",\n               command_line.band);\n      else\n    asfPrintStatus(\"Exporting band '%s' as greyscale ...\\n\\n\",\n               command_line.band);\n    }\n    else\n      asfPrintError(\"Band could not be found in the image.\\n\");\n  }\n  else if (lutFlag != FLAG_NOT_SET)\n    asfPrintStatus(\"Exporting applying look up table.\\n\\n\");\n  else\n    asfPrintStatus(\"Exporting as greyscale.\\n\\n\");\n\n  //If user added \".img\", strip it.\n  ext = findExt(in_base_name);\n  if (ext && strcmp(ext, \".img\") == 0) *ext = '\\0';\n  meta_free(md);\n\n/***********************END COMMAND LINE PARSING STUFF***********************/\n\n  if ( strcmp (command_line.format, \"ENVI\") == 0 ) {\n    format = ENVI;\n  }\n  else if ( strcmp (command_line.format, \"ESRI\") == 0 ) {\n    format = ESRI;\n  }\n  else if ( strcmp (command_line.format, \"GEOTIFF\") == 0 ||\n            strcmp (command_line.format, \"GEOTIF\") == 0) {\n    format = GEOTIFF;\n  }\n  else if ( strcmp (command_line.format, \"TIFF\") == 0 ||\n            strcmp (command_line.format, \"TIF\") == 0) {\n    format = TIF;\n  }\n  else if ( strcmp (command_line.format, \"JPEG\") == 0 ||\n            strcmp (command_line.format, \"JPG\") == 0) {\n    format = JPEG;\n  }\n  else if ( strcmp (command_line.format, \"PGM\") == 0 ) {\n    format = PGM;\n  }\n  else if ( strcmp (command_line.format, \"PNG\") == 0 ) {\n    format = PNG;\n  }\n  else if ( strcmp (command_line.format, \"PNG_ALPHA\") == 0 ) {\n    format = PNG_ALPHA;\n  }\n  else if ( strcmp (command_line.format, \"PNG_GE\") == 0 ) {\n    format = PNG_GE;\n  }\n  else if ( strcmp (command_line.format, \"KML\") == 0 ) {\n    format = KML;\n  }\n  else if ( strcmp (command_line.format, \"POLSARPRO\") == 0 ) {\n    format = POLSARPRO_HDR;\n  }\n  else if ( strcmp (command_line.format, \"HDF5\") == 0 ) {\n    format = HDF;\n  }\n  else if ( strcmp (command_line.format, \"NETCDF\") == 0 ) {\n    format = NC;\n  }\n  else {\n    asfPrintError(\"Unrecognized output format specified\\n\");\n  }\n\n  /* Complex data generally can't be output into meaningful images, so\n     we refuse to deal with it.  */\n  /*\n  md = meta_read (command_line.in_meta_name);\n  asfRequire (   md->general->data_type == BYTE\n              || md->general->data_type == INTEGER16\n              || md->general->data_type == INTEGER32\n              || md->general->data_type == REAL32\n              || md->general->data_type == REAL64,\n              \"Cannot cope with complex data, exiting...\\n\");\n\n  meta_free (md);\n  */\n\n  // Do that exporting magic!\n  asf_export_bands(format, command_line.sample_mapping, rgb,\n                   true_color, false_color,\n                   command_line.look_up_table_name,\n                   in_base_name, command_line.output_name, band_names,\n                   NULL, NULL);\n\n  // If the user didn't ask for a log file then nuke the one that's been kept\n  // since everything has finished successfully\n  if (logFlag == FLAG_NOT_SET) {\n      fclose (fLog);\n      remove(logFile);\n  }\n\n  for (ii = 0; ii<num_bands_found; ii++) {\n    FREE(band_names[ii]);\n  }\n  FREE(band_names);\n  FREE(in_base_name);\n  FREE(output_name);\n  exit (EXIT_SUCCESS);\n}\n\nint is_numeric(char *str)\n{\n  char *s = str;\n  int numericness = 1;\n\n  while (*s != '\\0') {\n    if (!isdigit(*s)) numericness = 0;\n    s++;\n  }\n\n  return numericness;\n}\n", "meta": {"hexsha": "741e84e43cace25509e3e19cd433309d5192387c", "size": 33300, "ext": "c", "lang": "C", "max_stars_repo_path": "src/asf_export/asf_export.c", "max_stars_repo_name": "glshort/MapReady", "max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z", "max_issues_repo_path": "src/asf_export/asf_export.c", "max_issues_repo_name": "glshort/MapReady", "max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/asf_export/asf_export.c", "max_forks_repo_name": "glshort/MapReady", "max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z", "avg_line_length": 38.9929742389, "max_line_length": 101, "alphanum_fraction": 0.6148048048, "num_tokens": 8551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19682621306573764, "lm_q2_score": 0.023330768681151314, "lm_q1q2_score": 0.004592106847423727}}
{"text": "#include <petsc/private/pcimpl.h>     /*I \"petscpc.h\" I*/\n#include <petsc.h>\n#include <petsc/private/hashmapi.h>\n#include <petscsf.h>\n#include <libssc.h>\n\nPetscLogEvent PC_Patch_CreatePatches, PC_Patch_ComputeOp, PC_Patch_Solve, PC_Patch_Scatter, PC_Patch_Apply, PC_Patch_Prealloc;\n\nstatic PetscBool PCPatchPackageInitialized = PETSC_FALSE;\n\nPETSC_EXTERN PetscErrorCode PCPatchInitializePackage(void)\n{\n    PetscErrorCode ierr;\n    PetscFunctionBegin;\n\n    if (PCPatchPackageInitialized) PetscFunctionReturn(0);\n    PCPatchPackageInitialized = PETSC_TRUE;\n    ierr = PCRegister(\"patch\", PCCreate_PATCH); CHKERRQ(ierr);\n    ierr = PetscLogEventRegister(\"PCPATCHCreate\", PC_CLASSID, &PC_Patch_CreatePatches); CHKERRQ(ierr);\n    ierr = PetscLogEventRegister(\"PCPATCHComputeOp\", PC_CLASSID, &PC_Patch_ComputeOp); CHKERRQ(ierr);\n    ierr = PetscLogEventRegister(\"PCPATCHSolve\", PC_CLASSID, &PC_Patch_Solve); CHKERRQ(ierr);\n    ierr = PetscLogEventRegister(\"PCPATCHApply\", PC_CLASSID, &PC_Patch_Apply); CHKERRQ(ierr);\n    ierr = PetscLogEventRegister(\"PCPATCHScatter\", PC_CLASSID, &PC_Patch_Scatter); CHKERRQ(ierr);\n    ierr = PetscLogEventRegister(\"PCPATCHPrealloc\", PC_CLASSID, &PC_Patch_Prealloc); CHKERRQ(ierr);\n\n    PetscFunctionReturn(0);\n}\n\ntypedef struct {\n    PetscSF          defaultSF;\n    PetscSection    *dofSection;\n    PetscSection     cellCounts;\n    PetscSection     cellNumbering; /* Numbering of cells in DM */\n    PetscSection     gtolCounts;   /* Indices to extract from local to\n                                   * patch vectors */\n    PetscInt         nsubspaces;   /* for mixed problems */\n    PetscInt        *subspaceOffsets; /* offsets for calculating concatenated numbering for mixed spaces */\n    PetscSection     bcCounts;\n    IS               cells;\n    IS               dofs;\n    IS               ghostBcNodes;\n    IS               globalBcNodes;\n    IS               gtol;\n\n    PetscBool        save_operators; /* Save all operators (or create/destroy one at a time?) */\n    PetscBool        partition_of_unity; /* Weight updates by dof multiplicity? */\n    PetscBool        multiplicative; /* Gauss-Seidel or Jacobi? */\n    PetscInt         npatch;     /* Number of patches */\n    PetscInt        *bs;            /* block size (can come from global\n                                    * operators?) */\n    PetscInt        *nodesPerCell;\n    PetscInt         totalDofsPerCell;\n    const PetscInt **cellNodeMap; /* Map from cells to nodes */\n\n    KSP             *ksp;        /* Solvers for each patch */\n    Vec              localX, localY;\n    Vec              dof_weights; /* In how many patches does each dof lie? */\n    Vec             *patchX, *patchY; /* Work vectors for patches */\n    Vec             *patch_dof_weights;\n    Mat             *mat;        /* Operators */\n    MatType          sub_mat_type;\n    PetscErrorCode  (*usercomputeop)(PC, Mat, PetscInt, const PetscInt *, PetscInt, const PetscInt *, void *);\n    void            *usercomputectx;\n\n    PetscErrorCode  (*patchconstructop)(void*, DM, PetscInt, PetscHMapI); /* patch construction */\n    PetscInt         codim; /* dimension or codimension of entities to loop over; */\n    PetscInt         dim;   /* only one of them can be set */\n    PetscInt         exclude_subspace; /* If you don't want any other dofs from a particular subspace you can exclude them with this.\n                                          Used for Vanka in Stokes, for example, to eliminate all pressure dofs not on the vertex\n                                          you're building the patch around */\n    PetscInt         vankadim;   /* In Vanka construction, should we eliminate any entities of a certain dimension? */\n\n    PetscBool        print_patches; /* Should we print out information about patch construction? */\n    PetscBool        symmetrise_sweep; /* Should we sweep forwards->backwards, backwards->forwards? */\n\n    IS              *userIS;\n    IS               iterationSet; /* Index set specifying how we iterate over patches */\n    PetscInt         nuserIS; /* user-specified index sets to specify the patches */\n    PetscBool        user_patches;\n    PetscErrorCode  (*userpatchconstructionop)(PC, PetscInt*, IS**, IS*, void* ctx);\n    void            *userpatchconstructctx;\n} PC_PATCH;\n\nPETSC_EXTERN PetscErrorCode PCPatchSetSaveOperators(PC pc, PetscBool flg)\n{\n    PC_PATCH       *patch = (PC_PATCH *)pc->data;\n    PetscFunctionBegin;\n\n    patch->save_operators = flg;\n    PetscFunctionReturn(0);\n}\n\nPETSC_EXTERN PetscErrorCode PCPatchSetPartitionOfUnity(PC pc, PetscBool flg)\n{\n    PC_PATCH       *patch = (PC_PATCH *)pc->data;\n    PetscFunctionBegin;\n\n    patch->partition_of_unity = flg;\n    PetscFunctionReturn(0);\n}\n\nstatic PetscErrorCode PCPatchCreateDefaultSF_Private(PC pc, PetscInt n, const PetscSF *sf, const PetscInt *bs)\n{\n    PetscErrorCode  ierr;\n    PC_PATCH       *patch = (PC_PATCH *)pc->data;\n    PetscFunctionBegin;\n\n    if (n == 1 && bs[0] == 1) {\n        patch->defaultSF = sf[0];\n        ierr = PetscObjectReference((PetscObject)patch->defaultSF); CHKERRQ(ierr);\n    } else {\n        PetscInt allRoots = 0, allLeaves = 0;\n        PetscInt leafOffset = 0;\n        PetscInt *ilocal = NULL;\n        PetscSFNode *iremote = NULL;\n        PetscInt *remoteOffsets = NULL;\n        PetscInt index = 0;\n        PetscHMapI rankToIndex;\n        PetscInt numRanks = 0;\n        PetscSFNode *remote = NULL;\n        PetscSF rankSF;\n        PetscInt *ranks = NULL;\n        PetscInt *offsets = NULL;\n        MPI_Datatype contig;\n        PetscHMapI ht;\n\n        /* First figure out how many dofs there are in the concatenated numbering.\n         * allRoots: number of owned global dofs;\n         * allLeaves: number of visible dofs (global + ghosted).\n         */\n        for ( PetscInt i = 0; i < n; i++ ) {\n            PetscInt nroots, nleaves;\n            ierr = PetscSFGetGraph(sf[i], &nroots, &nleaves, NULL, NULL); CHKERRQ(ierr);\n            allRoots += nroots * bs[i];\n            allLeaves += nleaves * bs[i];\n        }\n        ierr = PetscMalloc1(allLeaves, &ilocal); CHKERRQ(ierr);\n        ierr = PetscMalloc1(allLeaves, &iremote); CHKERRQ(ierr);\n\n        /* Now build an SF that just contains process connectivity. */\n        PetscHMapICreate(&ht);\n        for (PetscInt i = 0; i < n; i++ ) {\n            PetscInt nranks;\n            const PetscMPIInt *ranks = NULL;\n            ierr = PetscSFSetUp(sf[i]); CHKERRQ(ierr);\n            ierr = PetscSFGetRanks(sf[i], &nranks, &ranks, NULL, NULL, NULL); CHKERRQ(ierr);\n            /* These are all the ranks who communicate with me. */\n            for (PetscInt j = 0; j < nranks; j++) {\n                PetscHMapISet(ht, (PetscInt)ranks[j], 0);\n            }\n        }\n        PetscHMapIGetSize(ht, &numRanks); CHKERRQ(ierr);\n        ierr = PetscMalloc1(numRanks, &remote); CHKERRQ(ierr);\n        ierr = PetscMalloc1(numRanks, &ranks); CHKERRQ(ierr);\n        ierr = PetscHMapIGetKeys(ht, &index, ranks); CHKERRQ(ierr);\n\n        PetscHMapICreate(&rankToIndex);\n        for (PetscInt i = 0; i < numRanks; i++) {\n            remote[i].rank = ranks[i];\n            remote[i].index = 0;\n            PetscHMapISet(rankToIndex, ranks[i], i);\n        }\n        ierr = PetscFree(ranks); CHKERRQ(ierr);\n        PetscHMapIDestroy(&ht);\n        ierr = PetscSFCreate(PetscObjectComm((PetscObject)pc), &rankSF); CHKERRQ(ierr);\n        ierr = PetscSFSetGraph(rankSF, 1, numRanks, NULL, PETSC_OWN_POINTER, remote, PETSC_OWN_POINTER); CHKERRQ(ierr);\n        ierr = PetscSFSetUp(rankSF); CHKERRQ(ierr);\n\n        /* OK, use it to communicate the root offset on the remote\n         * processes for each subspace. */\n        ierr = PetscMalloc1(n, &offsets); CHKERRQ(ierr);\n        ierr = PetscMalloc1(n*numRanks, &remoteOffsets); CHKERRQ(ierr);\n\n        offsets[0] = 0;\n        for (PetscInt i = 1; i < n; i++) {\n            PetscInt nroots;\n            ierr = PetscSFGetGraph(sf[i-1], &nroots, NULL, NULL, NULL); CHKERRQ(ierr);\n            offsets[i] = offsets[i-1] + nroots*bs[i-1];\n        }\n        /* Offsets are the offsets on the current process of the\n         * global dof numbering for the subspaces. */\n        ierr = MPI_Type_contiguous(n, MPIU_INT, &contig); CHKERRQ(ierr);\n        ierr = MPI_Type_commit(&contig); CHKERRQ(ierr);\n\n        ierr = PetscSFBcastBegin(rankSF, contig, offsets, remoteOffsets); CHKERRQ(ierr);\n        ierr = PetscSFBcastEnd(rankSF, contig, offsets, remoteOffsets); CHKERRQ(ierr);\n        ierr = MPI_Type_free(&contig); CHKERRQ(ierr);\n        ierr = PetscFree(offsets); CHKERRQ(ierr);\n        ierr = PetscSFDestroy(&rankSF); CHKERRQ(ierr);\n        /* Now remoteOffsets contains the offsets on the remote\n         * processes who communicate with me.  So now we can\n         * concatenate the list of SFs into a single one. */\n        index = 0;\n        for ( PetscInt i = 0; i < n; i++ ) {\n            PetscInt nroots, nleaves;\n            const PetscInt *local = NULL;\n            const PetscSFNode *remote = NULL;\n            ierr = PetscSFGetGraph(sf[i], &nroots, &nleaves, &local, &remote); CHKERRQ(ierr);\n            for ( PetscInt j = 0; j < nleaves; j++ ) {\n                PetscInt rank = remote[j].rank;\n                PetscInt idx, rootOffset;\n                PetscHMapIGet(rankToIndex, rank, &idx);\n                if (idx == -1) {\n                    SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, \"Didn't find rank, huh?\");\n                }\n                /* Offset on given rank for ith subspace */\n                rootOffset = remoteOffsets[n*idx + i];\n                for ( PetscInt k = 0; k < bs[i]; k++ ) {\n                    ilocal[index] = (local ? local[j] : j)*bs[i] + k + leafOffset;\n                    iremote[index].rank = remote[j].rank;\n                    iremote[index].index = remote[j].index*bs[i] + k + rootOffset;\n                    ++index;\n                }\n            }\n            leafOffset += nleaves * bs[i];\n        }\n        PetscHMapIDestroy(&rankToIndex);\n        ierr = PetscFree(remoteOffsets); CHKERRQ(ierr);\n        ierr = PetscSFCreate(PetscObjectComm((PetscObject)pc), &patch->defaultSF); CHKERRQ(ierr);\n        ierr = PetscSFSetGraph(patch->defaultSF, allRoots, allLeaves, ilocal, PETSC_OWN_POINTER, iremote, PETSC_OWN_POINTER); CHKERRQ(ierr);\n    }\n    PetscFunctionReturn(0);\n}\n\nPETSC_EXTERN PetscErrorCode PCPatchSetCellNumbering(PC pc, PetscSection cellNumbering)\n{\n    PetscErrorCode  ierr;\n    PC_PATCH       *patch = (PC_PATCH *)pc->data;\n    PetscFunctionBegin;\n\n    patch->cellNumbering = cellNumbering;\n    ierr = PetscObjectReference((PetscObject)cellNumbering); CHKERRQ(ierr);\n    PetscFunctionReturn(0);\n}\n\n\nPETSC_EXTERN PetscErrorCode PCPatchSetDiscretisationInfo(PC pc, PetscInt nsubspaces,\n                                                         DM *dms,\n                                                         PetscInt *bs,\n                                                         PetscInt *nodesPerCell,\n                                                         const PetscInt **cellNodeMap,\n                                                         const PetscInt *subspaceOffsets,\n                                                         PetscInt numGhostBcs,\n                                                         const PetscInt *ghostBcNodes,\n                                                         PetscInt numGlobalBcs,\n                                                         const PetscInt *globalBcNodes)\n{\n    PetscErrorCode  ierr;\n    PC_PATCH       *patch = (PC_PATCH *)pc->data;\n    PetscSF        *sfs;\n    PetscFunctionBegin;\n\n    ierr = PetscMalloc1(nsubspaces, &sfs); CHKERRQ(ierr);\n    ierr = PetscMalloc1(nsubspaces, &patch->dofSection); CHKERRQ(ierr);\n    ierr = PetscMalloc1(nsubspaces, &patch->bs); CHKERRQ(ierr);\n    ierr = PetscMalloc1(nsubspaces, &patch->nodesPerCell); CHKERRQ(ierr);\n    ierr = PetscMalloc1(nsubspaces, &patch->cellNodeMap); CHKERRQ(ierr);\n    ierr = PetscMalloc1(nsubspaces+1, &patch->subspaceOffsets); CHKERRQ(ierr);\n\n    patch->nsubspaces = nsubspaces;\n    patch->totalDofsPerCell = 0;\n    for (int i = 0; i < nsubspaces; i++) {\n        ierr = DMGetDefaultSection(dms[i], &patch->dofSection[i]); CHKERRQ(ierr);\n        ierr = PetscObjectReference((PetscObject)patch->dofSection[i]); CHKERRQ(ierr);\n        patch->bs[i] = bs[i];\n        patch->nodesPerCell[i] = nodesPerCell[i];\n        patch->totalDofsPerCell += nodesPerCell[i]*bs[i];\n        patch->cellNodeMap[i] = cellNodeMap[i];\n        patch->subspaceOffsets[i] = subspaceOffsets[i];\n        ierr = DMGetDefaultSF(dms[i], &sfs[i]); CHKERRQ(ierr);\n    }\n    ierr = PCPatchCreateDefaultSF_Private(pc, nsubspaces, sfs, patch->bs); CHKERRQ(ierr);\n    ierr = PetscFree(sfs); CHKERRQ(ierr);\n\n    patch->subspaceOffsets[nsubspaces] = subspaceOffsets[nsubspaces];\n    ierr = ISCreateGeneral(PETSC_COMM_SELF, numGhostBcs, ghostBcNodes, PETSC_COPY_VALUES, &patch->ghostBcNodes); CHKERRQ(ierr);\n    ierr = ISCreateGeneral(PETSC_COMM_SELF, numGlobalBcs, globalBcNodes, PETSC_COPY_VALUES, &patch->globalBcNodes); CHKERRQ(ierr);\n    PetscFunctionReturn(0);\n}\n\nPETSC_EXTERN PetscErrorCode PCPatchSetSubMatType(PC pc, MatType sub_mat_type)\n{\n    PetscErrorCode ierr;\n    PC_PATCH      *patch = (PC_PATCH *)pc->data;\n    PetscFunctionBegin;\n    if (patch->sub_mat_type) {\n        ierr = PetscFree(patch->sub_mat_type); CHKERRQ(ierr);\n    }\n    ierr = PetscStrallocpy(sub_mat_type, (char **)&patch->sub_mat_type); CHKERRQ(ierr);\n    PetscFunctionReturn(0);\n}\n\nPETSC_EXTERN PetscErrorCode PCPatchSetComputeOperator(PC pc, PetscErrorCode (*func)(PC, Mat, PetscInt,\n                                                                                    const PetscInt *,\n                                                                                    PetscInt,\n                                                                                    const PetscInt *,\n                                                                                    void *),\n                                                      void *ctx)\n{\n    PC_PATCH *patch = (PC_PATCH *)pc->data;\n\n    PetscFunctionBegin;\n    /* User op can assume matrix is zeroed */\n    patch->usercomputeop = func;\n    patch->usercomputectx = ctx;\n\n    PetscFunctionReturn(0);\n}\n\nPETSC_EXTERN PetscErrorCode PCPatchSetUserPatchConstructionOperator(PC pc, PetscErrorCode (*func)(PC, PetscInt*, IS**, IS*, void*), void* ctx)\n{\n    PC_PATCH *patch = (PC_PATCH *)pc->data;\n\n    PetscFunctionBegin;\n    patch->userpatchconstructionop = func;\n    patch->userpatchconstructctx = ctx;\n\n    PetscFunctionReturn(0);\n}\n\n/* On entry, ht contains the topological entities whose dofs we are responsible for solving for;\n   on exit, cht contains all the topological entities we need to compute their residuals.\n   In full generality this should incorporate knowledge of the sparsity pattern of the matrix;\n   here we assume a standard FE sparsity pattern.*/\nstatic PetscErrorCode PCPatchCompleteCellPatch(DM dm, PetscHMapI ht, PetscHMapI cht)\n{\n    PetscErrorCode    ierr;\n    PetscHashIter    hi;\n    PetscInt          entity;\n    PetscInt         *star = NULL, *closure = NULL;\n\n    PetscFunctionBegin;\n\n\n    PetscHMapIClear(cht);\n    PetscHashIterBegin(ht, hi);\n    while (!PetscHashIterAtEnd(ht, hi)) {\n        PetscInt       starSize, closureSize;\n\n        PetscHashIterGetKey(ht, hi, entity);\n        PetscHashIterNext(ht, hi);\n\n        /* Loop over all the cells that this entity connects to */\n        ierr = DMPlexGetTransitiveClosure(dm, entity, PETSC_FALSE, &starSize, &star); CHKERRQ(ierr);\n        for ( PetscInt si = 0; si < starSize; si++ ) {\n            PetscInt ownedentity = star[2*si];\n            /* now loop over all entities in the closure of that cell */\n            ierr = DMPlexGetTransitiveClosure(dm, ownedentity, PETSC_TRUE, &closureSize, &closure); CHKERRQ(ierr);\n            for ( PetscInt ci = 0; ci < closureSize; ci++ ) {\n                PetscInt seenentity = closure[2*ci];\n                PetscHMapISet(cht, seenentity, 0);\n            }\n        }\n    }\n    /* Only restore work arrays at very end. */\n    if (closure) {\n        ierr = DMPlexRestoreTransitiveClosure(dm, 0, PETSC_TRUE, NULL, &closure); CHKERRQ(ierr);\n    }\n    if (star) {\n        ierr = DMPlexRestoreTransitiveClosure(dm, 0, PETSC_FALSE, NULL, &star); CHKERRQ(ierr);\n    }\n    PetscFunctionReturn(0);\n}\n\n/* Given a hash table with a set of topological entities (pts), compute the degrees of\n   freedom in global concatenated numbering on those entities.\n   For Vanka smoothing, this needs to do something special: ignore dofs of the\n   constraint subspace on entities that aren't the base entity we're building the patch\n   around. */\nstatic PetscErrorCode PCPatchGetPointDofs(PC_PATCH *patch, PetscHMapI pts, PetscHMapI dofs, PetscInt base, PetscInt exclude_subspace)\n{\n    PetscErrorCode    ierr;\n    PetscInt          ldof, loff;\n    PetscHashIter    hi;\n    PetscInt          p;\n\n    PetscFunctionBegin;\n    PetscHMapIClear(dofs);\n\n    for ( PetscInt k = 0; k < patch->nsubspaces; k++ ) {\n        PetscSection dofSection = patch->dofSection[k];\n        PetscInt bs = patch->bs[k];\n        PetscInt subspaceOffset = patch->subspaceOffsets[k];\n\n        if (k == exclude_subspace) {\n            /* only get this subspace dofs at the base entity, not any others */\n            ierr = PetscSectionGetDof(dofSection, base, &ldof); CHKERRQ(ierr);\n            ierr = PetscSectionGetOffset(dofSection, base, &loff); CHKERRQ(ierr);\n            if (0 == ldof) continue;\n            for ( PetscInt j = loff; j < ldof + loff; j++ ) {\n                for ( PetscInt l = 0; l < bs; l++ ) {\n                    PetscInt dof = bs*j + l + subspaceOffset;\n                    PetscHMapISet(dofs, dof, 0);\n                }\n            }\n            continue; /* skip the other dofs of this subspace */\n        }\n\n        PetscHashIterBegin(pts, hi);\n        while (!PetscHashIterAtEnd(pts, hi)) {\n            PetscHashIterGetKey(pts, hi, p);\n            PetscHashIterNext(pts, hi);\n            ierr = PetscSectionGetDof(dofSection, p, &ldof); CHKERRQ(ierr);\n            ierr = PetscSectionGetOffset(dofSection, p, &loff); CHKERRQ(ierr);\n            if (0 == ldof) continue;\n            for ( PetscInt j = loff; j < ldof + loff; j++ ) {\n                for ( PetscInt l = 0; l < bs; l++ ) {\n                    PetscInt dof = bs*j + l + subspaceOffset;\n                    PetscHMapISet(dofs, dof, 0);\n                }\n            }\n        }\n    }\n\n    PetscFunctionReturn(0);\n}\n\n/* Given two hash tables A and B, compute the keys in B that are not in A, and\n   put them in C */\nstatic PetscErrorCode PCPatchComputeSetDifference(PetscHMapI A, PetscHMapI B, PetscHMapI C)\n{\n    PetscHashIter    hi;\n    PetscInt          key;\n    PetscBool         flg;\n\n    PetscFunctionBegin;\n    PetscHMapIClear(C);\n\n    PetscHashIterBegin(B, hi);\n    while (!PetscHashIterAtEnd(B, hi)) {\n        PetscHashIterGetKey(B, hi, key);\n        PetscHashIterNext(B, hi);\n        PetscHMapIHas(A, key, &flg);\n        if (!flg) {\n            PetscHMapISet(C, key, 0);\n        }\n    }\n\n    PetscFunctionReturn(0);\n}\n\n/*\n * PCPatchCreateCellPatches - create patches.\n *\n * Input Parameters:\n * + dm - The DMPlex object defining the mesh\n *\n * Output Parameters:\n * + cellCounts - Section with counts of cells around each vertex\n * - cells - IS of the cell point indices of cells in each patch\n */\nstatic PetscErrorCode PCPatchCreateCellPatches(PC pc)\n{\n    PetscErrorCode  ierr;\n    PC_PATCH       *patch      = (PC_PATCH *)pc->data;\n    DM              dm;\n    DMLabel         ghost;\n    PetscInt        pStart, pEnd, vStart, vEnd, cStart, cEnd;\n    PetscBool       flg;\n    PetscInt       *cellsArray = NULL;\n    PetscInt        numCells;\n    PetscSection    cellCounts;\n    PetscHMapI      ht;\n    PetscHMapI      cht;\n\n    PetscFunctionBegin;\n\n    /* Used to keep track of the cells in the patch. */\n    PetscHMapICreate(&ht);\n    PetscHMapICreate(&cht);\n\n    ierr = PCGetDM(pc, &dm); CHKERRQ(ierr);\n\n    if (!dm) {\n        SETERRQ(PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_WRONGSTATE, \"DM not yet set on patch PC\\n\");\n    }\n\n    ierr = PetscObjectTypeCompare((PetscObject)dm, DMPLEX, &flg); CHKERRQ(ierr);\n    if (!flg) {\n        SETERRQ(PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_WRONGSTATE, \"DM on patch PC must be DMPlex\\n\");\n    }\n    ierr = DMPlexGetChart(dm, &pStart, &pEnd); CHKERRQ(ierr);\n    ierr = DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd); CHKERRQ(ierr);\n\n    if (patch->user_patches) {\n        /* compute patch->nuserIS, patch->userIS here */\n        ierr = patch->userpatchconstructionop(pc, &patch->nuserIS, &patch->userIS, &patch->iterationSet, patch->userpatchconstructctx); CHKERRQ(ierr);\n        vStart = 0;\n        vEnd = patch->nuserIS;\n    } else if (patch->codim < 0) { /* codim unset */\n        if (patch->dim < 0) { /* dim unset */\n            ierr = DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd); CHKERRQ(ierr);\n        } else { /* dim set */\n            ierr = DMPlexGetDepthStratum(dm, patch->dim, &vStart, &vEnd); CHKERRQ(ierr);\n        }\n    } else { /* codim set */\n        ierr = DMPlexGetHeightStratum(dm, patch->codim, &vStart, &vEnd); CHKERRQ(ierr);\n    }\n\n    /* These labels mark the owned points.  We only create patches\n     * around points that this process owns. */\n    ierr = DMGetLabel(dm, \"pyop2_ghost\", &ghost); CHKERRQ(ierr);\n\n    ierr = DMLabelCreateIndex(ghost, pStart, pEnd); CHKERRQ(ierr);\n\n    ierr = PetscSectionCreate(PETSC_COMM_SELF, &patch->cellCounts); CHKERRQ(ierr);\n    cellCounts = patch->cellCounts;\n    ierr = PetscSectionSetChart(cellCounts, vStart, vEnd); CHKERRQ(ierr);\n\n    /* Count cells in the patch surrounding each entity */\n    for ( PetscInt v = vStart; v < vEnd; v++ ) {\n        PetscHashIter hi;\n        PetscInt chtSize;\n\n        if (!patch->user_patches) {\n            ierr = DMLabelHasPoint(ghost, v, &flg); CHKERRQ(ierr);\n            /* Not an owned entity, don't make a cell patch. */\n            if (flg) {\n                continue;\n            }\n        }\n\n        ierr = patch->patchconstructop((void*)patch, dm, v, ht); CHKERRQ(ierr);\n        ierr = PCPatchCompleteCellPatch(dm, ht, cht);\n\n        PetscHMapIGetSize(cht, &chtSize);\n        if (chtSize == 0) {\n            /* empty patch, continue */\n            continue;\n        }\n\n        PetscHashIterBegin(cht, hi); /* safe because size(cht) > 0 from above */\n        while (!PetscHashIterAtEnd(cht, hi)) {\n            PetscInt entity;\n            PetscHashIterGetKey(cht, hi, entity);\n            if (cStart <= entity && entity < cEnd) {\n                ierr = PetscSectionAddDof(cellCounts, v, 1); CHKERRQ(ierr);\n            }\n            PetscHashIterNext(cht, hi);\n        }\n    }\n    ierr = DMLabelDestroyIndex(ghost); CHKERRQ(ierr);\n\n    ierr = PetscSectionSetUp(cellCounts); CHKERRQ(ierr);\n    ierr = PetscSectionGetStorageSize(cellCounts, &numCells); CHKERRQ(ierr);\n    ierr = PetscMalloc1(numCells, &cellsArray); CHKERRQ(ierr);\n\n    /* Now that we know how much space we need, run through again and\n     * actually remember the cells. */\n    for ( PetscInt v = vStart; v < vEnd; v++ ) {\n        PetscInt ndof, off;\n        PetscHashIter hi;\n\n        ierr = PetscSectionGetDof(cellCounts, v, &ndof); CHKERRQ(ierr);\n        ierr = PetscSectionGetOffset(cellCounts, v, &off); CHKERRQ(ierr);\n        if ( ndof <= 0 ) {\n            continue;\n        }\n        ierr = patch->patchconstructop((void*)patch, dm, v, ht); CHKERRQ(ierr);\n        ierr = PCPatchCompleteCellPatch(dm, ht, cht);\n        ndof = 0;\n        PetscHashIterBegin(cht, hi);\n        while (!PetscHashIterAtEnd(cht, hi)) {\n            PetscInt entity;\n            PetscHashIterGetKey(cht, hi, entity);\n            if (cStart <= entity && entity < cEnd) {\n                cellsArray[ndof + off] = entity;\n                ndof++;\n            }\n            PetscHashIterNext(cht, hi);\n        }\n    }\n\n    ierr = ISCreateGeneral(PETSC_COMM_SELF, numCells, cellsArray, PETSC_OWN_POINTER, &patch->cells); CHKERRQ(ierr);\n    ierr = PetscSectionGetChart(patch->cellCounts, &pStart, &pEnd); CHKERRQ(ierr);\n    patch->npatch = pEnd - pStart;\n    PetscHMapIDestroy(&ht);\n    PetscHMapIDestroy(&cht);\n    PetscFunctionReturn(0);\n}\n\n/*\n * PCPatchCreateCellPatchDiscretisationInfo - Build the dof maps for cell patches\n *\n * Input Parameters:\n * + dm - The DMPlex object defining the mesh\n * . cellCounts - Section with counts of cells around each vertex\n * . cells - IS of the cell point indices of cells in each patch\n * . cellNumbering - Section mapping plex cell points to Firedrake cell indices.\n * . nodesPerCell - number of nodes per cell.\n * - cellNodeMap - map from cells to node indices (nodesPerCell * numCells)\n *\n * Output Parameters:\n * + dofs - IS of local dof numbers of each cell in the patch\n * . gtolCounts - Section with counts of dofs per cell patch\n * - gtol - IS mapping from global dofs to local dofs for each patch. \n */\nstatic PetscErrorCode PCPatchCreateCellPatchDiscretisationInfo(PC pc)\n{\n    PetscErrorCode  ierr;\n    PC_PATCH       *patch           = (PC_PATCH *)pc->data;\n    PetscSection    cellCounts      = patch->cellCounts;\n    PetscSection    gtolCounts;\n    IS              cells           = patch->cells;\n    PetscSection    cellNumbering   = patch->cellNumbering;\n    PetscInt        numCells;\n    PetscInt        numDofs;\n    PetscInt        numGlobalDofs;\n    PetscInt        totalDofsPerCell = patch->totalDofsPerCell;\n    PetscInt        vStart, vEnd;\n    const PetscInt *cellsArray;\n    PetscInt       *newCellsArray   = NULL;\n    PetscInt       *dofsArray       = NULL;\n    PetscInt       *asmArray        = NULL;\n    PetscInt       *globalDofsArray = NULL;\n    PetscInt        globalIndex     = 0;\n    PetscHMapI      ht;\n    PetscHMapI      globalBcs;\n    DM              dm         = NULL;\n    const PetscInt *bcNodes    = NULL;\n    PetscInt        numBcs;\n    PetscHMapI      ownedpts, seenpts, owneddofs, seendofs, artificialbcs;\n    PetscHashIter  hi;\n\n    PetscFunctionBegin;\n\n    ierr = PCGetDM(pc, &dm); CHKERRQ(ierr);\n\n    /* dofcounts section is cellcounts section * dofPerCell */\n    ierr = PetscSectionGetStorageSize(cellCounts, &numCells); CHKERRQ(ierr);\n    numDofs = numCells * totalDofsPerCell;\n    ierr = PetscMalloc1(numDofs, &dofsArray); CHKERRQ(ierr);\n    ierr = PetscMalloc1(numDofs, &asmArray); CHKERRQ(ierr);\n    ierr = PetscMalloc1(numCells, &newCellsArray); CHKERRQ(ierr);\n    ierr = PetscSectionGetChart(cellCounts, &vStart, &vEnd); CHKERRQ(ierr);\n    ierr = PetscSectionCreate(PETSC_COMM_SELF, &patch->gtolCounts); CHKERRQ(ierr);\n    gtolCounts = patch->gtolCounts;\n    ierr = PetscSectionSetChart(gtolCounts, vStart, vEnd); CHKERRQ(ierr);\n\n    /* Outside the patch loop, get the dofs that are globally-enforced Dirichlet\n       conditions */\n    PetscHMapICreate(&globalBcs);\n    ierr = ISGetIndices(patch->ghostBcNodes, &bcNodes); CHKERRQ(ierr);\n    ierr = ISGetSize(patch->ghostBcNodes, &numBcs); CHKERRQ(ierr);\n    for ( PetscInt i = 0; i < numBcs; i++ ) {\n        PetscHMapISet(globalBcs, bcNodes[i], 0); /* these are already in concatenated numbering */\n    }\n    ierr = ISRestoreIndices(patch->ghostBcNodes, &bcNodes); CHKERRQ(ierr);\n\n    /* HMap tables for artificial BC construction */\n    PetscHMapICreate(&ownedpts);\n    PetscHMapICreate(&seenpts);\n    PetscHMapICreate(&owneddofs);\n    PetscHMapICreate(&seendofs);\n    PetscHMapICreate(&artificialbcs);\n\n    ierr = ISGetIndices(cells, &cellsArray); CHKERRQ(ierr);\n    PetscHMapICreate(&ht);\n    for ( PetscInt v = vStart; v < vEnd; v++ ) {\n        PetscInt dof, off;\n        PetscInt localIndex = 0;\n        PetscHMapIClear(ht);\n        ierr = PetscSectionGetDof(cellCounts, v, &dof); CHKERRQ(ierr);\n        ierr = PetscSectionGetOffset(cellCounts, v, &off); CHKERRQ(ierr);\n\n        if ( dof <= 0 ) continue;\n\n        /* Calculate the global numbers of the artificial BC dofs here first */\n        ierr = patch->patchconstructop((void*)patch, dm, v, ownedpts); CHKERRQ(ierr);\n        ierr = PCPatchCompleteCellPatch(dm, ownedpts, seenpts); CHKERRQ(ierr);\n        ierr = PCPatchGetPointDofs(patch, ownedpts, owneddofs, v, patch->exclude_subspace); CHKERRQ(ierr);\n        ierr = PCPatchGetPointDofs(patch, seenpts, seendofs, v, -1); CHKERRQ(ierr);\n        ierr = PCPatchComputeSetDifference(owneddofs, seendofs, artificialbcs); CHKERRQ(ierr);\n        if (patch->print_patches) {\n            PetscHMapI globalbcdofs;\n            PetscHMapICreate(&globalbcdofs);\n\n            MPI_Comm comm = PetscObjectComm((PetscObject)pc);\n            ierr = PetscSynchronizedPrintf(comm, \"Patch %d: owned dofs:\\n\", v); CHKERRQ(ierr);\n            PetscHashIterBegin(owneddofs, hi);\n            while (!PetscHashIterAtEnd(owneddofs, hi)) {\n                PetscInt globalDof;\n\n                PetscHashIterGetKey(owneddofs, hi, globalDof);\n                PetscHashIterNext(owneddofs, hi);\n                ierr = PetscSynchronizedPrintf(comm, \"%d \", globalDof); CHKERRQ(ierr);\n            }\n            ierr = PetscSynchronizedPrintf(comm, \"\\n\"); CHKERRQ(ierr);\n            ierr = PetscSynchronizedPrintf(comm, \"Patch %d: seen dofs:\\n\", v); CHKERRQ(ierr);\n            PetscHashIterBegin(seendofs, hi);\n            while (!PetscHashIterAtEnd(seendofs, hi)) {\n                PetscInt globalDof;\n                PetscBool flg;\n\n                PetscHashIterGetKey(seendofs, hi, globalDof);\n                PetscHashIterNext(seendofs, hi);\n                ierr = PetscSynchronizedPrintf(comm, \"%d \", globalDof); CHKERRQ(ierr);\n\n                PetscHMapIHas(globalBcs, globalDof, &flg);\n                if (flg) {\n                    PetscHMapISet(globalbcdofs, globalDof, 0);\n                }\n            }\n            ierr = PetscSynchronizedPrintf(comm, \"\\n\"); CHKERRQ(ierr);\n            ierr = PetscSynchronizedPrintf(comm, \"Patch %d: global BCs:\\n\", v); CHKERRQ(ierr);\n            PetscHMapIGetSize(globalbcdofs, &numBcs);\n            if (numBcs > 0) {\n                PetscHashIterBegin(globalbcdofs, hi);\n                while (!PetscHashIterAtEnd(globalbcdofs, hi)) {\n                    PetscInt globalDof;\n                    PetscHashIterGetKey(globalbcdofs, hi, globalDof);\n                    PetscHashIterNext(globalbcdofs, hi);\n                    ierr = PetscSynchronizedPrintf(comm, \"%d \", globalDof); CHKERRQ(ierr);\n                }\n            }\n            ierr = PetscSynchronizedPrintf(comm, \"\\n\"); CHKERRQ(ierr);\n            ierr = PetscSynchronizedPrintf(comm, \"Patch %d: artificial BCs:\\n\", v); CHKERRQ(ierr);\n            PetscHMapIGetSize(artificialbcs, &numBcs);\n            if (numBcs > 0) {\n                PetscHashIterBegin(artificialbcs, hi);\n                while (!PetscHashIterAtEnd(artificialbcs, hi)) {\n                    PetscInt globalDof;\n                    PetscHashIterGetKey(artificialbcs, hi, globalDof);\n                    PetscHashIterNext(artificialbcs, hi);\n                    ierr = PetscSynchronizedPrintf(comm, \"%d \", globalDof); CHKERRQ(ierr);\n                }\n            }\n            ierr = PetscSynchronizedPrintf(comm, \"\\n\\n\"); CHKERRQ(ierr);\n            PetscHMapIDestroy(&globalbcdofs);\n        }\n        for ( PetscInt k = 0; k < patch->nsubspaces; k++ ) {\n            PetscInt nodesPerCell = patch->nodesPerCell[k];\n            PetscInt subspaceOffset = patch->subspaceOffsets[k];\n            const PetscInt *cellNodeMap = patch->cellNodeMap[k];\n            PetscInt bs = patch->bs[k];\n\n            for ( PetscInt i = off; i < off + dof; i++ ) {\n                /* Walk over the cells in this patch. */\n                const PetscInt c = cellsArray[i];\n                PetscInt cell;\n                ierr = PetscSectionGetDof(cellNumbering, c, &cell); CHKERRQ(ierr);\n                if ( cell <= 0 ) {\n                    SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE,\n                            \"Cell doesn't appear in cell numbering map\");\n                }\n                ierr = PetscSectionGetOffset(cellNumbering, c, &cell); CHKERRQ(ierr);\n                newCellsArray[i] = cell;\n                for ( PetscInt j = 0; j < nodesPerCell; j++ ) {\n                    /* For each global dof, map it into contiguous local storage. */\n                    const PetscInt globalDof = cellNodeMap[cell*nodesPerCell + j]*bs + subspaceOffset;\n                    /* finally, loop over block size */\n                    for ( PetscInt l = 0; l < bs; l++ ) {\n                        PetscInt localDof, isGlobalBcDof, isArtificialBcDof;\n\n                        /* first, check if this is either a globally enforced or locally enforced BC dof */\n                        PetscHMapIGet(globalBcs, globalDof + l, &isGlobalBcDof);\n                        PetscHMapIGet(artificialbcs, globalDof + l, &isArtificialBcDof);\n\n                        /* if it's either, don't ever give it a local dof number */\n                        if (isGlobalBcDof >= 0 || isArtificialBcDof >= 0) {\n                            dofsArray[globalIndex++] = -1; /* don't use this in assembly in this patch */\n                        } else {\n                            PetscHMapIGet(ht, globalDof + l, &localDof);\n                            if (localDof == -1) {\n                                localDof = localIndex++;\n                                PetscHMapISet(ht, globalDof + l, localDof);\n                            }\n                            if ( globalIndex >= numDofs ) {\n                                SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE,\n                                        \"Found more dofs than expected\");\n                            }\n                            /* And store. */\n                            dofsArray[globalIndex++] = localDof;\n                        }\n                    }\n                }\n            }\n        }\n        PetscHMapIGetSize(ht, &dof);\n        /* How many local dofs in this patch? */\n        ierr = PetscSectionSetDof(gtolCounts, v, dof); CHKERRQ(ierr);\n    }\n    if (globalIndex != numDofs) {\n        SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE,\n                 \"Expected number of dofs (%d) doesn't match found number (%d)\",\n                 numDofs, globalIndex);\n    }\n    ierr = PetscSectionSetUp(gtolCounts); CHKERRQ(ierr);\n    ierr = PetscSectionGetStorageSize(gtolCounts, &numGlobalDofs); CHKERRQ(ierr);\n    ierr = PetscMalloc1(numGlobalDofs, &globalDofsArray); CHKERRQ(ierr);\n\n    /* Now populate the global to local map.  This could be merged\n    * into the above loop if we were willing to deal with reallocs. */\n    PetscInt key = 0;\n    PetscInt asmKey = 0;\n    for ( PetscInt v = vStart; v < vEnd; v++ ) {\n        PetscInt       dof, off;\n        PetscHashIter hi;\n        PetscHMapIClear(ht);\n        ierr = PetscSectionGetDof(cellCounts, v, &dof); CHKERRQ(ierr);\n        ierr = PetscSectionGetOffset(cellCounts, v, &off); CHKERRQ(ierr);\n\n        if ( dof <= 0 ) continue;\n\n        for ( PetscInt k = 0; k < patch->nsubspaces; k++ ) {\n            PetscInt nodesPerCell = patch->nodesPerCell[k];\n            PetscInt subspaceOffset = patch->subspaceOffsets[k];\n            const PetscInt *cellNodeMap = patch->cellNodeMap[k];\n            PetscInt bs = patch->bs[k];\n\n            for ( PetscInt i = off; i < off + dof; i++ ) {\n                /* Reconstruct mapping of global-to-local on this patch. */\n                const PetscInt c = cellsArray[i];\n                PetscInt cell;\n                ierr = PetscSectionGetOffset(cellNumbering, c, &cell); CHKERRQ(ierr);\n                for ( PetscInt j = 0; j < nodesPerCell; j++ ) {\n                    for ( PetscInt l = 0; l < bs; l++ ) {\n                        const PetscInt globalDof = cellNodeMap[cell*nodesPerCell + j]*bs + subspaceOffset + l;\n                        const PetscInt localDof = dofsArray[key++];\n\n                        if (localDof >= 0) PetscHMapISet(ht, globalDof, localDof);\n                    }\n                }\n            }\n            /* Shove it in the output data structure. */\n            PetscInt goff;\n            ierr = PetscSectionGetOffset(gtolCounts, v, &goff); CHKERRQ(ierr);\n            PetscHashIterBegin(ht, hi);\n            while (!PetscHashIterAtEnd(ht, hi)) {\n                PetscInt globalDof, localDof;\n                PetscHashIterGetKey(ht, hi, globalDof);\n                PetscHashIterGetVal(ht, hi, localDof);\n                if (globalDof >= 0) {\n                    globalDofsArray[goff + localDof] = globalDof;\n                }\n                PetscHashIterNext(ht, hi);\n            }\n        }\n\n        /* At this point, we have a hash table ht built that maps globalDof -> localDof.\n           We need to create the dof table laid out cellwise first, then by subspace,\n           as the assembler assembles cell-wise and we need to stuff the different\n           contributions of the different function spaces to the right places. So we loop\n           over cells, then over subspaces. */\n\n        if (patch->nsubspaces > 1) { /* for nsubspaces = 1, data we need is already in dofsArray */\n            for (PetscInt i = off; i < off + dof; i++ ) {\n                const PetscInt c = cellsArray[i];\n                PetscInt cell;\n                ierr = PetscSectionGetOffset(cellNumbering, c, &cell); CHKERRQ(ierr);\n\n                for ( PetscInt k = 0; k < patch->nsubspaces; k++ ) {\n                    PetscInt nodesPerCell = patch->nodesPerCell[k];\n                    PetscInt subspaceOffset = patch->subspaceOffsets[k];\n                    const PetscInt *cellNodeMap = patch->cellNodeMap[k];\n                    PetscInt bs = patch->bs[k];\n                    for ( PetscInt j = 0; j < nodesPerCell; j++ ) {\n                        for ( PetscInt l = 0; l < bs; l++ ) {\n                            const PetscInt globalDof = cellNodeMap[cell*nodesPerCell + j]*bs + subspaceOffset + l;\n                            PetscInt localDof;\n                            PetscHMapIGet(ht, globalDof, &localDof);\n\n                            /* If it's not in the hash table, i.e. is a BC dof,\n                               then the PetscHMapIGet above gives -1, which matches\n                               exactly the convention for PETSc's matrix assembly to\n                               ignore the dof. So we don't need to do anything here */\n                            asmArray[asmKey++] = localDof;\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    if (1 == patch->nsubspaces) { /* replace with memcpy? */\n        for (PetscInt i = 0; i < numDofs; i++) {\n            asmArray[i] = dofsArray[i];\n        }\n    }\n\n\n    PetscHMapIDestroy(&ht);\n    ierr = ISRestoreIndices(cells, &cellsArray);\n    ierr = PetscFree(dofsArray); CHKERRQ(ierr);\n\n    /* Replace cell indices with firedrake-numbered ones. */\n    ierr = ISGeneralSetIndices(cells, numCells, (const PetscInt *)newCellsArray, PETSC_OWN_POINTER); CHKERRQ(ierr);\n    ierr = ISCreateGeneral(PETSC_COMM_SELF, numGlobalDofs, globalDofsArray, PETSC_OWN_POINTER, &patch->gtol); CHKERRQ(ierr);\n    ierr = ISCreateGeneral(PETSC_COMM_SELF, numDofs, asmArray, PETSC_OWN_POINTER, &patch->dofs); CHKERRQ(ierr);\n\n    PetscHMapIDestroy(&artificialbcs);\n    PetscHMapIDestroy(&seendofs);\n    PetscHMapIDestroy(&owneddofs);\n    PetscHMapIDestroy(&seenpts);\n    PetscHMapIDestroy(&ownedpts);\n    PetscHMapIDestroy(&globalBcs);\n\n    ierr = ISDestroy(&patch->ghostBcNodes); CHKERRQ(ierr); /* memory optimisation */\n    PetscFunctionReturn(0);\n}\n\nstatic PetscErrorCode PCReset_PATCH(PC pc)\n{\n    PetscErrorCode  ierr;\n    PC_PATCH       *patch = (PC_PATCH *)pc->data;\n    PetscInt        i;\n\n    PetscFunctionBegin;\n    ierr = PetscSFDestroy(&patch->defaultSF); CHKERRQ(ierr);\n    ierr = PetscSectionDestroy(&patch->cellCounts); CHKERRQ(ierr);\n    ierr = PetscSectionDestroy(&patch->cellNumbering); CHKERRQ(ierr);\n    ierr = PetscSectionDestroy(&patch->gtolCounts); CHKERRQ(ierr);\n    ierr = PetscSectionDestroy(&patch->bcCounts); CHKERRQ(ierr);\n    ierr = ISDestroy(&patch->gtol); CHKERRQ(ierr);\n    ierr = ISDestroy(&patch->cells); CHKERRQ(ierr);\n    ierr = ISDestroy(&patch->dofs); CHKERRQ(ierr);\n    ierr = ISDestroy(&patch->ghostBcNodes); CHKERRQ(ierr);\n    ierr = ISDestroy(&patch->globalBcNodes); CHKERRQ(ierr);\n\n    if (patch->dofSection) {\n        for (i = 0; i < patch->nsubspaces; i++) {\n            ierr = PetscSectionDestroy(&patch->dofSection[i]); CHKERRQ(ierr);\n        }\n    }\n    ierr = PetscFree(patch->dofSection); CHKERRQ(ierr);\n    ierr = PetscFree(patch->bs); CHKERRQ(ierr);\n    ierr = PetscFree(patch->nodesPerCell); CHKERRQ(ierr);\n    ierr = PetscFree(patch->cellNodeMap); CHKERRQ(ierr);\n    ierr = PetscFree(patch->subspaceOffsets); CHKERRQ(ierr);\n\n    if (patch->ksp) {\n        for ( i = 0; i < patch->npatch; i++ ) {\n            ierr = KSPReset(patch->ksp[i]); CHKERRQ(ierr);\n        }\n    }\n\n    ierr = VecDestroy(&patch->localX); CHKERRQ(ierr);\n    ierr = VecDestroy(&patch->localY); CHKERRQ(ierr);\n    if (patch->patchX) {\n        for ( i = 0; i < patch->npatch; i++ ) {\n            ierr = VecDestroy(patch->patchX + i); CHKERRQ(ierr);\n        }\n        ierr = PetscFree(patch->patchX); CHKERRQ(ierr);\n    }\n    if (patch->patchY) {\n        for ( i = 0; i < patch->npatch; i++ ) {\n            ierr = VecDestroy(patch->patchY + i); CHKERRQ(ierr);\n        }\n        ierr = PetscFree(patch->patchY); CHKERRQ(ierr);\n    }\n\n    if (patch->partition_of_unity) {\n        ierr = VecDestroy(&patch->dof_weights); CHKERRQ(ierr);\n    }\n\n    if (patch->patch_dof_weights) {\n        for ( i = 0; i < patch->npatch; i++ ) {\n            ierr = VecDestroy(patch->patch_dof_weights + i); CHKERRQ(ierr);\n        }\n        ierr = PetscFree(patch->patch_dof_weights); CHKERRQ(ierr);\n    }\n    if (patch->mat) {\n        for ( i = 0; i < patch->npatch; i++ ) {\n            ierr = MatDestroy(patch->mat + i); CHKERRQ(ierr);\n        }\n        ierr = PetscFree(patch->mat); CHKERRQ(ierr);\n    }\n    ierr = PetscFree(patch->sub_mat_type); CHKERRQ(ierr);\n\n    patch->bs = 0;\n    patch->cellNodeMap = NULL;\n\n    if (patch->user_patches) {\n        for ( PetscInt i = 0; i < patch->nuserIS; i++ ) {\n            ierr = ISDestroy(&patch->userIS[i]); CHKERRQ(ierr);\n        }\n        PetscFree(patch->userIS);\n        patch->nuserIS = 0;\n    }\n    if (patch->iterationSet) {\n        ierr = ISDestroy(&patch->iterationSet); CHKERRQ(ierr);\n    }\n\n    PetscFunctionReturn(0);\n}\n\nstatic PetscErrorCode PCDestroy_PATCH(PC pc)\n{\n    PetscErrorCode  ierr;\n    PC_PATCH       *patch = (PC_PATCH *)pc->data;\n    PetscInt        i;\n\n    PetscFunctionBegin;\n\n    ierr = PCReset_PATCH(pc); CHKERRQ(ierr);\n    if (patch->ksp) {\n        for ( i = 0; i < patch->npatch; i++ ) {\n            ierr = KSPDestroy(&patch->ksp[i]); CHKERRQ(ierr);\n        }\n        ierr = PetscFree(patch->ksp); CHKERRQ(ierr);\n    }\n    ierr = PetscFree(pc->data); CHKERRQ(ierr);\n    PetscFunctionReturn(0);\n}\n\nstatic PetscErrorCode PCPatchZeroMatrix_Private(Mat mat, const PetscInt ncell,\n                                                const PetscInt ndof,\n                                                const PetscInt *dof)\n{\n    const PetscScalar *values = NULL;\n    PetscInt rows;\n    PetscErrorCode ierr;\n\n    PetscFunctionBegin;\n\n    ierr = PetscCalloc1(ndof*ndof, &values); CHKERRQ(ierr);\n    for (PetscInt c = 0; c < ncell; c++) {\n        const PetscInt *idx = &dof[ndof*c];\n        ierr = MatSetValues(mat, ndof, idx, ndof, idx, values, INSERT_VALUES); CHKERRQ(ierr);\n    }\n    ierr = MatGetLocalSize(mat, &rows, NULL); CHKERRQ(ierr);\n    for (PetscInt i = 0; i < rows; i++) {\n        ierr = MatSetValues(mat, 1, &i, 1, &i, values, INSERT_VALUES); CHKERRQ(ierr);\n    }\n    ierr = MatAssemblyBegin(mat, MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n    ierr = MatAssemblyEnd(mat, MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n    ierr = PetscFree(values); CHKERRQ(ierr);\n    PetscFunctionReturn(0);\n}\n\nstatic PetscErrorCode PCPatchCreateMatrix(PC pc, PetscInt which, Mat *mat)\n{\n    PetscErrorCode  ierr;\n    PC_PATCH       *patch = (PC_PATCH *)pc->data;\n    PetscInt        csize, rsize;\n    Vec             x, y;\n    PetscBool       flg;\n    const char     *prefix = NULL;\n\n    PetscFunctionBegin;\n\n    x = patch->patchX[which];\n    y = patch->patchY[which];\n    ierr = VecGetSize(x, &csize); CHKERRQ(ierr);\n    ierr = VecGetSize(y, &rsize); CHKERRQ(ierr);\n    ierr = MatCreate(PETSC_COMM_SELF, mat); CHKERRQ(ierr);\n    ierr = PCGetOptionsPrefix(pc, &prefix); CHKERRQ(ierr);\n    ierr = MatSetOptionsPrefix(*mat, prefix); CHKERRQ(ierr);\n    ierr = MatAppendOptionsPrefix(*mat, \"sub_\"); CHKERRQ(ierr);\n    if (patch->sub_mat_type) {\n        ierr = MatSetType(*mat, patch->sub_mat_type); CHKERRQ(ierr);\n    }\n    ierr = MatSetSizes(*mat, rsize, csize, rsize, csize); CHKERRQ(ierr);\n    ierr = PetscObjectTypeCompare((PetscObject)*mat, MATDENSE, &flg); CHKERRQ(ierr);\n    if (!flg) {\n        ierr = PetscObjectTypeCompare((PetscObject)*mat, MATSEQDENSE, &flg); CHKERRQ(ierr);\n    }\n\n    if (!flg) {\n        PetscBT         bt;\n        PetscInt       *dnnz       = NULL;\n        const PetscInt *dofsArray = NULL;\n        PetscInt        pStart, pEnd, ncell, offset;\n\n        ierr = ISGetIndices(patch->dofs, &dofsArray); CHKERRQ(ierr);\n        ierr = PetscSectionGetChart(patch->cellCounts, &pStart, &pEnd); CHKERRQ(ierr);\n\n        which += pStart;\n        if (which >= pEnd) {\n            SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, \"Asked for operator index is invalid\\n\"); CHKERRQ(ierr);\n        }\n\n        ierr = PetscSectionGetDof(patch->cellCounts, which, &ncell); CHKERRQ(ierr);\n        ierr = PetscSectionGetOffset(patch->cellCounts, which, &offset); CHKERRQ(ierr);\n\n        ierr = PetscMalloc1(rsize, &dnnz); CHKERRQ(ierr);\n        for (PetscInt i = 0; i < rsize; i++) {\n            dnnz[i] = 0;\n        }\n        ierr = PetscLogEventBegin(PC_Patch_Prealloc, pc, 0, 0, 0); CHKERRQ(ierr);\n\n        /* XXX: This uses N^2 bits to store the sparsity pattern on a\n         * patch.  This is probably OK if the patches are not too big,\n         * but could use quite a bit of memory for planes in 3D.\n         * Should we switch based on the value of rsize to a\n         * hash-table (slower, but more memory efficient) approach? */\n        ierr = PetscBTCreate(rsize*rsize, &bt); CHKERRQ(ierr);\n        for (PetscInt c = 0; c < ncell; c++) {\n            const PetscInt *idx = dofsArray + (offset + c)*patch->totalDofsPerCell;\n            for (PetscInt i = 0; i < patch->totalDofsPerCell; i++) {\n                const PetscInt row = idx[i];\n                if (row < 0) continue;\n                for (PetscInt j = 0; j < patch->totalDofsPerCell; j++) {\n                    const PetscInt col = idx[j];\n                    const PetscInt key = row*rsize + col;\n                    if (col < 0) continue;\n\n                    if (!PetscBTLookupSet(bt, key)) {\n                        ++dnnz[row];\n                    }\n                }\n            }\n        }\n        PetscBTDestroy(&bt);\n        ierr = MatXAIJSetPreallocation(*mat, 1, dnnz, NULL, NULL, NULL); CHKERRQ(ierr);\n\n        ierr = PetscFree(dnnz); CHKERRQ(ierr);\n        ierr = PCPatchZeroMatrix_Private(*mat, ncell, patch->totalDofsPerCell,\n                                         &dofsArray[offset*patch->totalDofsPerCell]); CHKERRQ(ierr);\n        ierr = PetscLogEventEnd(PC_Patch_Prealloc, pc, 0, 0, 0); CHKERRQ(ierr);\n        ierr = ISRestoreIndices(patch->dofs, &dofsArray); CHKERRQ(ierr);\n\n    }\n\n    ierr = MatSetUp(*mat); CHKERRQ(ierr);\n\n    PetscFunctionReturn(0);\n}\n\nstatic PetscErrorCode PCPatchComputeOperator(PC pc, Mat mat, Mat multMat, PetscInt which)\n{\n    PetscErrorCode  ierr;\n    PC_PATCH       *patch = (PC_PATCH *)pc->data;\n    const PetscInt *dofsArray;\n    const PetscInt *cellsArray;\n    PetscInt        ncell, offset, pStart, pEnd;\n\n    PetscFunctionBegin;\n\n    ierr = PetscLogEventBegin(PC_Patch_ComputeOp, pc, 0, 0, 0); CHKERRQ(ierr);\n    if (!patch->usercomputeop) {\n        SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, \"Must call PCPatchSetComputeOperator() to set user callback\\n\");\n    }\n    ierr = ISGetIndices(patch->dofs, &dofsArray); CHKERRQ(ierr);\n    ierr = ISGetIndices(patch->cells, &cellsArray); CHKERRQ(ierr);\n    ierr = PetscSectionGetChart(patch->cellCounts, &pStart, &pEnd); CHKERRQ(ierr);\n\n    which += pStart;\n    if (which >= pEnd) {\n        SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, \"Asked for operator index is invalid\\n\"); CHKERRQ(ierr);\n    }\n\n    ierr = PetscSectionGetDof(patch->cellCounts, which, &ncell); CHKERRQ(ierr);\n    ierr = PetscSectionGetOffset(patch->cellCounts, which, &offset); CHKERRQ(ierr);\n    if ( ncell <= 0 ) {\n        ierr = PetscLogEventEnd(PC_Patch_ComputeOp, pc, 0, 0, 0); CHKERRQ(ierr);\n        PetscFunctionReturn(0);\n    }\n    PetscStackPush(\"PCPatch user callback\");\n    ierr = patch->usercomputeop(pc, mat, ncell, cellsArray + offset, ncell*patch->totalDofsPerCell, dofsArray + offset*patch->totalDofsPerCell, patch->usercomputectx); CHKERRQ(ierr);\n    PetscStackPop;\n    ierr = ISRestoreIndices(patch->dofs, &dofsArray); CHKERRQ(ierr);\n    ierr = ISRestoreIndices(patch->cells, &cellsArray); CHKERRQ(ierr);\n    ierr = PetscLogEventEnd(PC_Patch_ComputeOp, pc, 0, 0, 0); CHKERRQ(ierr);\n    PetscFunctionReturn(0);\n}\n\nstatic PetscErrorCode PCPatch_ScatterLocal_Private(PC pc, PetscInt p,\n                                                   Vec x, Vec y,\n                                                   InsertMode mode,\n                                                   ScatterMode scat)\n{\n    PetscErrorCode ierr;\n    PC_PATCH          *patch   = (PC_PATCH *)pc->data;\n    const PetscScalar *xArray = NULL;\n    PetscScalar *yArray = NULL;\n    const PetscInt *gtolArray = NULL;\n    PetscInt offset, size;\n\n    PetscFunctionBeginHot;\n    ierr = PetscLogEventBegin(PC_Patch_Scatter, pc, 0, 0, 0); CHKERRQ(ierr);\n\n    ierr = VecGetArrayRead(x, &xArray); CHKERRQ(ierr);\n    ierr = VecGetArray(y, &yArray); CHKERRQ(ierr);\n\n    ierr = PetscSectionGetDof(patch->gtolCounts, p, &size); CHKERRQ(ierr);\n    ierr = PetscSectionGetOffset(patch->gtolCounts, p, &offset); CHKERRQ(ierr);\n    ierr = ISGetIndices(patch->gtol, &gtolArray); CHKERRQ(ierr);\n    if (mode == INSERT_VALUES && scat != SCATTER_FORWARD) {\n        SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, \"Can't insert if not scattering forward\\n\");\n    }\n    if (mode == ADD_VALUES && scat != SCATTER_REVERSE) {\n        SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, \"Can't add if not scattering reverse\\n\");\n    }\n    for ( PetscInt lidx = 0; lidx < size; lidx++ ) {\n        const PetscInt gidx = gtolArray[lidx + offset];\n        if (mode == INSERT_VALUES) {\n            yArray[lidx] = xArray[gidx];\n        } else {\n            yArray[gidx] += xArray[lidx];\n        }\n    }\n    ierr = VecRestoreArrayRead(x, &xArray); CHKERRQ(ierr);\n    ierr = VecRestoreArray(y, &yArray); CHKERRQ(ierr);\n    ierr = ISRestoreIndices(patch->gtol, &gtolArray); CHKERRQ(ierr);\n    ierr = PetscLogEventEnd(PC_Patch_Scatter, pc, 0, 0, 0); CHKERRQ(ierr);\n    PetscFunctionReturn(0);\n}\n\n\nstatic PetscErrorCode PCSetUp_PATCH(PC pc)\n{\n    PetscErrorCode  ierr;\n    PC_PATCH       *patch = (PC_PATCH *)pc->data;\n    const char     *prefix;\n    PetscInt       pStart;\n\n    PetscFunctionBegin;\n\n    if (!pc->setupcalled) {\n        PetscInt     pStart, pEnd;\n        PetscInt     localSize;\n        ierr = PetscLogEventBegin(PC_Patch_CreatePatches, pc, 0, 0, 0); CHKERRQ(ierr);\n\n        localSize = patch->subspaceOffsets[patch->nsubspaces];\n        ierr = VecCreateSeq(PETSC_COMM_SELF, localSize, &patch->localX); CHKERRQ(ierr);\n        ierr = VecSetUp(patch->localX); CHKERRQ(ierr);\n        ierr = VecDuplicate(patch->localX, &patch->localY); CHKERRQ(ierr);\n        ierr = PCPatchCreateCellPatches(pc); CHKERRQ(ierr);\n        ierr = PCPatchCreateCellPatchDiscretisationInfo(pc); CHKERRQ(ierr);\n\n        /* OK, now build the work vectors */\n        ierr = PetscSectionGetChart(patch->gtolCounts, &pStart, &pEnd); CHKERRQ(ierr);\n        ierr = PetscMalloc1(patch->npatch, &patch->patchX); CHKERRQ(ierr);\n        ierr = PetscMalloc1(patch->npatch, &patch->patchY); CHKERRQ(ierr);\n\n        for ( PetscInt i = pStart; i < pEnd; i++ ) {\n            PetscInt dof;\n            ierr = PetscSectionGetDof(patch->gtolCounts, i, &dof); CHKERRQ(ierr);\n            ierr = VecCreateSeq(PETSC_COMM_SELF, dof, &patch->patchX[i - pStart]); CHKERRQ(ierr);\n            ierr = VecSetUp(patch->patchX[i - pStart]); CHKERRQ(ierr);\n            ierr = VecCreateSeq(PETSC_COMM_SELF, dof, &patch->patchY[i - pStart]); CHKERRQ(ierr);\n            ierr = VecSetUp(patch->patchY[i - pStart]); CHKERRQ(ierr);\n        }\n        ierr = PetscMalloc1(patch->npatch, &patch->ksp); CHKERRQ(ierr);\n        ierr = PCGetOptionsPrefix(pc, &prefix); CHKERRQ(ierr);\n        for ( PetscInt i = 0; i < patch->npatch; i++ ) {\n            ierr = KSPCreate(PETSC_COMM_SELF, patch->ksp + i); CHKERRQ(ierr);\n            ierr = PetscObjectIncrementTabLevel((PetscObject)patch->ksp[i], (PetscObject)pc, 1); CHKERRQ(ierr);\n            ierr = KSPSetOptionsPrefix(patch->ksp[i], prefix); CHKERRQ(ierr);\n            ierr = KSPAppendOptionsPrefix(patch->ksp[i], \"sub_\"); CHKERRQ(ierr);\n        }\n        if (patch->save_operators) {\n            ierr = PetscMalloc1(patch->npatch, &patch->mat); CHKERRQ(ierr);\n            for ( PetscInt i = 0; i < patch->npatch; i++ ) {\n                ierr = PCPatchCreateMatrix(pc, i, patch->mat + i); CHKERRQ(ierr);\n            }\n        }\n        ierr = PetscLogEventEnd(PC_Patch_CreatePatches, pc, 0, 0, 0); CHKERRQ(ierr);\n    }\n\n    /* If desired, calculate weights for dof multiplicity */\n\n    if (!pc->setupcalled && patch->partition_of_unity) {\n        Mat P;\n        Vec local;\n        const PetscScalar *input = NULL;\n        PetscScalar *output = NULL;\n        ierr = PCGetOperators(pc, NULL, &P); CHKERRQ(ierr);\n        ierr = MatCreateVecs(P, NULL, &patch->dof_weights);\n        ierr = VecDuplicate(patch->localX, &local); CHKERRQ(ierr);\n        ierr = PetscSectionGetChart(patch->gtolCounts, &pStart, NULL); CHKERRQ(ierr);\n        for ( PetscInt i = 0; i < patch->npatch; i++ ) {\n            PetscInt dof;\n            ierr = PetscSectionGetDof(patch->gtolCounts, i + pStart, &dof); CHKERRQ(ierr);\n            if ( dof <= 0 ) continue;\n            ierr = VecSet(patch->patchX[i], 1.0); CHKERRQ(ierr);\n            /* TODO: Do we need different scatters for X and Y? */\n\n            ierr = PCPatch_ScatterLocal_Private(pc, i + pStart,\n                                                patch->patchX[i], local,\n                                                ADD_VALUES, SCATTER_REVERSE); CHKERRQ(ierr);\n        }\n        /* Local to Global */\n        ierr = VecGetArrayRead(local, &input); CHKERRQ(ierr);\n        ierr = VecGetArray(patch->dof_weights, &output); CHKERRQ(ierr);\n        ierr = PetscSFReduceBegin(patch->defaultSF, MPIU_SCALAR, input, output, MPI_SUM); CHKERRQ(ierr);\n        ierr = PetscSFReduceEnd(patch->defaultSF, MPIU_SCALAR, input, output, MPI_SUM); CHKERRQ(ierr);\n        ierr = VecRestoreArray(patch->dof_weights, &output); CHKERRQ(ierr);\n        ierr = VecRestoreArrayRead(local, &input); CHKERRQ(ierr);\n\n        ierr = VecReciprocal(patch->dof_weights); CHKERRQ(ierr);\n        ierr = VecDestroy(&local); CHKERRQ(ierr);\n    }\n\n    if (patch->save_operators) {\n        for ( PetscInt i = 0; i < patch->npatch; i++ ) {\n            ierr = MatZeroEntries(patch->mat[i]); CHKERRQ(ierr);\n            ierr = PCPatchComputeOperator(pc, patch->mat[i], NULL, i); CHKERRQ(ierr);\n            ierr = KSPSetOperators(patch->ksp[i], patch->mat[i], patch->mat[i]); CHKERRQ(ierr);\n        }\n    }\n    if (!pc->setupcalled) {\n        for ( PetscInt i = 0; i < patch->npatch; i++ ) {\n            ierr = KSPSetFromOptions(patch->ksp[i]); CHKERRQ(ierr);\n        }\n    }\n    PetscFunctionReturn(0);\n}\n\nstatic PetscErrorCode PCApply_PATCH(PC pc, Vec x, Vec y)\n{\n    PetscErrorCode     ierr;\n    PC_PATCH          *patch   = (PC_PATCH *)pc->data;\n    const PetscScalar *globalX = NULL;\n    PetscScalar       *localX  = NULL;\n    PetscScalar       *localY  = NULL;\n    PetscScalar       *globalY = NULL;\n    const PetscInt    *bcNodes = NULL;\n    PetscInt           pStart, numBcs, size;\n    PetscInt           nsweep = 1;\n    PetscInt           start[2] = {0, patch->npatch-1};\n    PetscInt           end[2] = {patch->npatch, -1};\n    const PetscInt     inc[2] = {1, -1};\n    const PetscInt    *iterationSet;\n    PetscFunctionBegin;\n\n    ierr = PetscLogEventBegin(PC_Patch_Apply, pc, 0, 0, 0); CHKERRQ(ierr);\n    ierr = PetscOptionsPushGetViewerOff(PETSC_TRUE); CHKERRQ(ierr);\n    /* Scatter from global space into overlapped local spaces */\n    ierr = VecGetArrayRead(x, &globalX); CHKERRQ(ierr);\n    ierr = VecGetArray(patch->localX, &localX); CHKERRQ(ierr);\n    ierr = PetscSFBcastBegin(patch->defaultSF, MPIU_SCALAR, globalX, localX); CHKERRQ(ierr);\n    ierr = PetscSFBcastEnd(patch->defaultSF, MPIU_SCALAR, globalX, localX); CHKERRQ(ierr);\n    ierr = VecRestoreArrayRead(x, &globalX); CHKERRQ(ierr);\n    ierr = VecRestoreArray(patch->localX, &localX); CHKERRQ(ierr);\n\n    if (patch->user_patches) {\n        ierr = ISGetLocalSize(patch->iterationSet, &end[0]); CHKERRQ(ierr);\n        start[1] = end[0] - 1;\n        ierr = ISGetIndices(patch->iterationSet, &iterationSet); CHKERRQ(ierr);\n    }\n\n    ierr = VecSet(patch->localY, 0.0); CHKERRQ(ierr);\n    ierr = PetscSectionGetChart(patch->gtolCounts, &pStart, NULL); CHKERRQ(ierr);\n    if (patch->symmetrise_sweep) {\n        nsweep = 2;\n    } else {\n        nsweep = 1;\n    }\n\n    for (PetscInt sweep = 0; sweep < nsweep; sweep++) {\n        for ( PetscInt j = start[sweep]; j*inc[sweep] < end[sweep]*inc[sweep]; j += inc[sweep] ) {\n            PetscInt start, len, i;\n            Mat multMat = NULL;\n\n            if (patch->user_patches) {\n                i = iterationSet[j];\n            } else {\n                i = j;\n            } \n\n            ierr = PetscSectionGetDof(patch->gtolCounts, i + pStart, &len); CHKERRQ(ierr);\n            ierr = PetscSectionGetOffset(patch->gtolCounts, i + pStart, &start); CHKERRQ(ierr);\n            if ( len <= 0 ) {\n                /* TODO: Squash out these guys in the setup as well. */\n                continue;\n            }\n            ierr = PCPatch_ScatterLocal_Private(pc, i + pStart,\n                                                patch->localX, patch->patchX[i],\n                                                INSERT_VALUES,\n                                                SCATTER_FORWARD); CHKERRQ(ierr);\n            if (!patch->save_operators) {\n                Mat mat;\n                ierr = PCPatchCreateMatrix(pc, i, &mat); CHKERRQ(ierr);\n                /* Populate operator here. */\n                ierr = PCPatchComputeOperator(pc, mat, multMat, i); CHKERRQ(ierr);\n                ierr = KSPSetOperators(patch->ksp[i], mat, mat);\n                /* Drop reference so the KSPSetOperators below will blow it away. */\n                ierr = MatDestroy(&mat); CHKERRQ(ierr);\n            }\n\n            ierr = PetscLogEventBegin(PC_Patch_Solve, pc, 0, 0, 0); CHKERRQ(ierr);\n            ierr = KSPSolve(patch->ksp[i], patch->patchX[i], patch->patchY[i]); CHKERRQ(ierr);\n            ierr = PetscLogEventEnd(PC_Patch_Solve, pc, 0, 0, 0); CHKERRQ(ierr);\n            if (!patch->save_operators) {\n                PC pc;\n                ierr = KSPSetOperators(patch->ksp[i], NULL, NULL); CHKERRQ(ierr);\n                ierr = KSPGetPC(patch->ksp[i], &pc); CHKERRQ(ierr);\n                /* Destroy PC context too, otherwise the factored matrix hangs around. */\n                ierr = PCReset(pc); CHKERRQ(ierr);\n            }\n\n            ierr = PCPatch_ScatterLocal_Private(pc, i + pStart,\n                                                patch->patchY[i], patch->localY,\n                                                ADD_VALUES, SCATTER_REVERSE); CHKERRQ(ierr);\n        }\n    }\n\n    if (patch->user_patches) {\n        ierr = ISRestoreIndices(patch->iterationSet, &iterationSet); CHKERRQ(ierr);\n    }\n\n    /* Now patch->localY contains the solution of the patch solves, so\n     * we need to combine them all. */\n    ierr = VecSet(y, 0.0); CHKERRQ(ierr);\n    ierr = VecGetArray(y, &globalY); CHKERRQ(ierr);\n    ierr = VecGetArrayRead(patch->localY, (const PetscScalar **)&localY); CHKERRQ(ierr);\n    ierr = PetscSFReduceBegin(patch->defaultSF, MPIU_SCALAR, localY, globalY, MPI_SUM); CHKERRQ(ierr);\n    ierr = PetscSFReduceEnd(patch->defaultSF, MPIU_SCALAR, localY, globalY, MPI_SUM); CHKERRQ(ierr);\n    ierr = VecRestoreArrayRead(patch->localY, (const PetscScalar **)&localY); CHKERRQ(ierr);\n\n    /* Now we need to send the global BC values through */\n    ierr = VecGetArrayRead(x, &globalX); CHKERRQ(ierr);\n    ierr = ISGetSize(patch->globalBcNodes, &numBcs); CHKERRQ(ierr);\n    ierr = ISGetIndices(patch->globalBcNodes, &bcNodes); CHKERRQ(ierr);\n    ierr = VecGetLocalSize(x, &size); CHKERRQ(ierr);\n    for ( PetscInt i = 0; i < numBcs; i++ ) {\n        const PetscInt idx = bcNodes[i];\n        if (idx < size) {\n            globalY[idx] = globalX[idx];\n        }\n    }\n\n    ierr = ISRestoreIndices(patch->globalBcNodes, &bcNodes); CHKERRQ(ierr);\n    ierr = VecRestoreArrayRead(x, &globalX); CHKERRQ(ierr);\n    ierr = VecRestoreArray(y, &globalY); CHKERRQ(ierr);\n    if (patch->partition_of_unity) {\n        /* Now apply partition of unity */\n        ierr = VecPointwiseMult(y, y, patch->dof_weights); CHKERRQ(ierr);\n    }\n\n    ierr = PetscOptionsPopGetViewerOff(); CHKERRQ(ierr);\n    ierr = PetscLogEventEnd(PC_Patch_Apply, pc, 0, 0, 0); CHKERRQ(ierr);\n    PetscFunctionReturn(0);\n}\n\nstatic PetscErrorCode PCSetUpOnBlocks_PATCH(PC pc)\n{\n  PC_PATCH           *patch = (PC_PATCH*)pc->data;\n  PetscErrorCode      ierr;\n  PetscInt            i;\n  KSPConvergedReason  reason;\n\n  PetscFunctionBegin;\n  PetscFunctionReturn(0);\n  for (i=0; i<patch->npatch; i++) {\n    ierr = KSPSetUp(patch->ksp[i]); CHKERRQ(ierr);\n    ierr = KSPGetConvergedReason(patch->ksp[i], &reason); CHKERRQ(ierr);\n    if (reason == KSP_DIVERGED_PCSETUP_FAILED) {\n      pc->failedreason = PC_SUBPC_ERROR;\n    }\n  }\n  PetscFunctionReturn(0);\n}\n\nPETSC_EXTERN PetscErrorCode PCPatchConstruct_Star(void *vpatch, DM dm, PetscInt entity, PetscHMapI ht)\n{\n    PetscErrorCode ierr;\n    PetscInt       starSize;\n    PetscInt      *star = NULL;\n\n    PetscFunctionBegin;\n    PetscHMapIClear(ht);\n\n    /* To start with, add the entity we care about */\n    PetscHMapISet(ht, entity, 0);\n\n    /* Loop over all the points that this entity connects to */\n    ierr = DMPlexGetTransitiveClosure(dm, entity, PETSC_FALSE, &starSize, &star); CHKERRQ(ierr);\n    for ( PetscInt si = 0; si < starSize; si++ ) {\n        PetscInt pt = star[2*si];\n        PetscHMapISet(ht, pt, 0);\n    }\n    if (star) {\n        ierr = DMPlexRestoreTransitiveClosure(dm, 0, PETSC_FALSE, NULL, &star); CHKERRQ(ierr);\n    }\n    PetscFunctionReturn(0);\n}\n\nPETSC_EXTERN PetscErrorCode PCPatchConstruct_Vanka(void *vpatch, DM dm, PetscInt entity, PetscHMapI ht)\n{\n    PetscErrorCode ierr;\n    PC_PATCH      *patch = (PC_PATCH*) vpatch;\n    PetscInt       starSize, closureSize;\n    PetscInt      *star = NULL, *closure = NULL;\n    PetscInt       iStart, iEnd;\n    PetscInt       cStart, cEnd;\n    PetscBool      shouldIgnore;\n\n    PetscFunctionBegin;\n    PetscHMapIClear(ht);\n\n    /* To start with, add the entity we care about */\n    PetscHMapISet(ht, entity, 0);\n\n    /* Should we ignore any topological entities of a certain dimension? */\n    if (patch->vankadim >= 0) {\n        shouldIgnore = PETSC_TRUE;\n        ierr = DMPlexGetDepthStratum(dm, patch->vankadim, &iStart, &iEnd); CHKERRQ(ierr);\n    } else {\n        shouldIgnore = PETSC_FALSE;\n    }\n    ierr = DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd); CHKERRQ(ierr);\n\n    /* Loop over all the cells that this entity connects to */\n    ierr = DMPlexGetTransitiveClosure(dm, entity, PETSC_FALSE, &starSize, &star); CHKERRQ(ierr);\n    for ( PetscInt si = 0; si < starSize; si++ ) {\n        PetscInt cell = star[2*si];\n        if ( cell < cStart || cell >= cEnd) continue;\n        /* now loop over all entities in the closure of that cell */\n        ierr = DMPlexGetTransitiveClosure(dm, cell, PETSC_TRUE, &closureSize, &closure); CHKERRQ(ierr);\n        for ( PetscInt ci = 0; ci < closureSize; ci++ ) {\n            PetscInt newentity = closure[2*ci];\n            if (shouldIgnore && iStart <= newentity && newentity < iEnd) {\n                /* We've been told to ignore entities of this type.*/\n                continue;\n            }\n            PetscHMapISet(ht, newentity, 0);\n        }\n    }\n    if (closure) {\n        ierr = DMPlexRestoreTransitiveClosure(dm, 0, PETSC_TRUE, NULL, &closure); CHKERRQ(ierr);\n    }\n    if (star) {\n        ierr = DMPlexRestoreTransitiveClosure(dm, 0, PETSC_FALSE, NULL, &star); CHKERRQ(ierr);\n    }\n    PetscFunctionReturn(0);\n}\n\n/* The user's already set the patches in patch->userIS. Build the hash tables */\nPETSC_EXTERN PetscErrorCode PCPatchConstruct_User(void *vpatch, DM dm, PetscInt entity, PetscHMapI ht)\n{\n    PetscErrorCode  ierr;\n    PC_PATCH       *patch = (PC_PATCH*) vpatch;\n    IS              patchis = patch->userIS[entity];\n    PetscInt        size;\n    PetscInt        pStart, pEnd;\n    const PetscInt *patchdata;\n\n    PetscFunctionBegin;\n    PetscHMapIClear(ht);\n\n    ierr = DMPlexGetChart(dm, &pStart, &pEnd);\n\n    ierr = ISGetLocalSize(patchis, &size); CHKERRQ(ierr);\n    ierr = ISGetIndices(patchis, &patchdata); CHKERRQ(ierr);\n    for ( PetscInt i = 0; i < size; i++ ) {\n        PetscInt ownedentity = patchdata[i];\n        if (ownedentity < pStart || ownedentity >= pEnd) {\n            SETERRQ(PetscObjectComm((PetscObject)dm),PETSC_ERR_USER,\"Entities need to be between the bounds of DMPlexGetChart()\");\n        }\n        PetscHMapISet(ht, patchdata[i], 0);\n    }\n    ierr = ISRestoreIndices(patchis, &patchdata); CHKERRQ(ierr);\n    PetscFunctionReturn(0);\n}\n\nconst char *const PCPatchConstructTypes[]   = {\"star\",\"vanka\",\"user\",\"python\",0};\n\nstatic PetscErrorCode PCSetFromOptions_PATCH(PetscOptionItems *PetscOptionsObject, PC pc)\n{\n    PC_PATCH       *patch = (PC_PATCH *)pc->data;\n    PetscErrorCode  ierr;\n    PetscBool       flg, dimflg, codimflg;\n    char            sub_mat_type[256];\n    PCPatchConstructType patchConstructionType = PC_PATCH_STAR;\n\n    PetscFunctionBegin;\n    ierr = PetscOptionsHead(PetscOptionsObject, \"Vertex-patch Additive Schwarz options\"); CHKERRQ(ierr);\n\n    ierr = PetscOptionsBool(\"-pc_patch_save_operators\", \"Store all patch operators for lifetime of PC?\",\n                            \"PCPatchSetSaveOperators\", patch->save_operators, &patch->save_operators, &flg); CHKERRQ(ierr);\n\n    ierr = PetscOptionsBool(\"-pc_patch_partition_of_unity\", \"Weight contributions by dof multiplicity?\",\n                            \"PCPatchSetPartitionOfUnity\", patch->partition_of_unity, &patch->partition_of_unity, &flg); CHKERRQ(ierr);\n\n    ierr = PetscOptionsBool(\"-pc_patch_multiplicative\", \"Gauss-Seidel instead of Jacobi?\",\n                            \"PCPatchSetMultiplicative\", patch->multiplicative, &patch->multiplicative, &flg); CHKERRQ(ierr);\n    if (patch->multiplicative) {\n      SETERRQ(PetscObjectComm((PetscObject)pc),PETSC_ERR_USER,\"We've removed multiplicative to do BC condensation (for now)\");\n    }\n\n    ierr = PetscOptionsInt(\"-pc_patch_construction_dim\", \"What dimension of entity to construct patches by? (0 = vertices)\", \"PCSetFromOptions_PATCH\", patch->dim, &patch->dim, &dimflg);\n    ierr = PetscOptionsInt(\"-pc_patch_construction_codim\", \"What co-dimension of entity to construct patches by? (0 = cells)\", \"PCSetFromOptions_PATCH\", patch->codim, &patch->codim, &codimflg);\n    if (dimflg && codimflg) {\n        SETERRQ(PetscObjectComm((PetscObject)pc),PETSC_ERR_USER,\"Can only set one of dimension or co-dimension\");\n    }\n    /* XXX: This should be PetscOptionsEnum */\n    ierr = PetscOptionsEList(\"-pc_patch_construction_type\", \"How should the patches be constructed?\", \"PCSetFromOptions_PATCH\", PCPatchConstructTypes, 4, PCPatchConstructTypes[patchConstructionType], (PetscInt *)&patchConstructionType, &flg);\n    if (flg) {\n        switch (patchConstructionType) {\n        case PC_PATCH_STAR:\n            patch->patchconstructop = PCPatchConstruct_Star;\n            break;\n        case PC_PATCH_VANKA:\n            patch->patchconstructop = PCPatchConstruct_Vanka;\n            ierr = PetscOptionsInt(\"-pc_patch_vanka_dim\", \"Topological dimension of entities for Vanka to ignore\", \"PCSetFromOptions_PATCH\", patch->vankadim, &patch->vankadim, &flg);\n            ierr = PetscOptionsInt(\"-pc_patch_vanka_space\", \"What subspace is the constraint space for Vanka?\", \"PCSetFromOptions_PATCH\", patch->exclude_subspace, &patch->exclude_subspace, &flg);\n            if (flg) {\n                SETERRQ(PetscObjectComm((PetscObject)pc),PETSC_ERR_USER, \"-pc_patch_vanka_space has been renamed to -pc_patch_exclude_subspace\");\n            }\n            break;\n        case PC_PATCH_USER:\n        case PC_PATCH_PYTHON:\n            patch->user_patches = PETSC_TRUE;\n            patch->patchconstructop = PCPatchConstruct_User;\n            break;\n        default:\n            SETERRQ(PetscObjectComm((PetscObject)pc),PETSC_ERR_USER,\"Unknown patch construction type\");\n            break;\n        }\n    }\n\n    ierr = PetscOptionsFList(\"-pc_patch_sub_mat_type\", \"Matrix type for patch solves\", \"PCPatchSetSubMatType\",MatList, NULL, sub_mat_type, 256, &flg); CHKERRQ(ierr);\n    if (flg) {\n        ierr = PCPatchSetSubMatType(pc, sub_mat_type); CHKERRQ(ierr);\n    }\n\n    ierr = PetscOptionsBool(\"-pc_patch_print_patches\", \"Print out information during patch construction?\",\n                            \"PCSetFromOptions_PATCH\", patch->print_patches, &patch->print_patches, &flg); CHKERRQ(ierr);\n\n    ierr = PetscOptionsBool(\"-pc_patch_symmetrise_sweep\", \"Go start->end, end->start?\",\n                            \"PCSetFromOptions_PATCH\", patch->symmetrise_sweep, &patch->symmetrise_sweep, &flg); CHKERRQ(ierr);\n\n    ierr = PetscOptionsInt(\"-pc_patch_exclude_subspace\", \"What subspace (if any) to exclude in construction?\", \"PCSetFromOptions_PATCH\", patch->exclude_subspace, &patch->exclude_subspace, &flg);\n\n    ierr = PetscOptionsTail(); CHKERRQ(ierr);\n    PetscFunctionReturn(0);\n}\n\nstatic PetscErrorCode PCView_PATCH(PC pc, PetscViewer viewer)\n{\n    PC_PATCH       *patch = (PC_PATCH *)pc->data;\n    PetscErrorCode  ierr;\n    PetscMPIInt     rank;\n    PetscBool       isascii;\n    PetscViewer     sviewer;\n    PetscFunctionBegin;\n    ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&isascii);CHKERRQ(ierr);\n\n    ierr = MPI_Comm_rank(PetscObjectComm((PetscObject)pc),&rank);CHKERRQ(ierr);\n    if (!isascii) {\n        PetscFunctionReturn(0);\n    }\n    ierr = PetscViewerASCIIPushTab(viewer); CHKERRQ(ierr);\n    ierr = PetscViewerASCIIPrintf(viewer, \"Subspace Correction preconditioner with %d patches\\n\", patch->npatch); CHKERRQ(ierr);\n    if (patch->multiplicative) {\n        ierr = PetscViewerASCIIPrintf(viewer, \"Schwarz type: multiplicative\\n\"); CHKERRQ(ierr);\n    } else {\n        ierr = PetscViewerASCIIPrintf(viewer, \"Schwarz type: additive\\n\"); CHKERRQ(ierr);\n    }\n    if (patch->partition_of_unity) {\n        ierr = PetscViewerASCIIPrintf(viewer, \"Weighting by partition of unity\\n\"); CHKERRQ(ierr);\n    } else {\n        ierr = PetscViewerASCIIPrintf(viewer, \"Not weighting by partition of unity\\n\"); CHKERRQ(ierr);\n    }\n    if (patch->symmetrise_sweep) {\n        ierr = PetscViewerASCIIPrintf(viewer, \"Symmetrising sweep (start->end, then end->start)\\n\"); CHKERRQ(ierr);\n    } else {\n        ierr = PetscViewerASCIIPrintf(viewer, \"Not symmetrising sweep\\n\"); CHKERRQ(ierr);\n    }\n    if (!patch->save_operators) {\n        ierr = PetscViewerASCIIPrintf(viewer, \"Not saving patch operators (rebuilt every PCApply)\\n\"); CHKERRQ(ierr);\n    } else {\n        ierr = PetscViewerASCIIPrintf(viewer, \"Saving patch operators (rebuilt every PCSetUp)\\n\"); CHKERRQ(ierr);\n    }\n    if (patch->patchconstructop == PCPatchConstruct_Star) {\n        ierr = PetscViewerASCIIPrintf(viewer, \"Patch construction operator: star\\n\"); CHKERRQ(ierr);\n    } else if (patch->patchconstructop == PCPatchConstruct_Vanka) {\n        ierr = PetscViewerASCIIPrintf(viewer, \"Patch construction operator: Vanka\\n\"); CHKERRQ(ierr);\n    } else if (patch->patchconstructop == PCPatchConstruct_User) {\n        ierr = PetscViewerASCIIPrintf(viewer, \"Patch construction operator: user-specified\\n\"); CHKERRQ(ierr);\n    } else {\n        ierr = PetscViewerASCIIPrintf(viewer, \"Patch construction operator: unknown\\n\"); CHKERRQ(ierr);\n    }\n    ierr = PetscViewerASCIIPrintf(viewer, \"KSP on patches (all same):\\n\"); CHKERRQ(ierr);\n\n    if (patch->ksp) {\n        ierr = PetscViewerGetSubViewer(viewer, PETSC_COMM_SELF, &sviewer); CHKERRQ(ierr);\n        if (!rank) {\n            ierr = PetscViewerASCIIPushTab(sviewer); CHKERRQ(ierr);\n            ierr = KSPView(patch->ksp[0], sviewer); CHKERRQ(ierr);\n            ierr = PetscViewerASCIIPopTab(sviewer); CHKERRQ(ierr);\n        }\n        ierr = PetscViewerRestoreSubViewer(viewer, PETSC_COMM_SELF, &sviewer); CHKERRQ(ierr);\n    } else {\n        ierr = PetscViewerASCIIPushTab(viewer); CHKERRQ(ierr);\n        ierr = PetscViewerASCIIPrintf(viewer, \"KSP not yet set.\\n\"); CHKERRQ(ierr);\n        ierr = PetscViewerASCIIPopTab(viewer); CHKERRQ(ierr);\n    }\n\n    ierr = PetscViewerASCIIPopTab(viewer); CHKERRQ(ierr);\n    PetscFunctionReturn(0);\n}\n\nPETSC_EXTERN PetscErrorCode PCCreate_PATCH(PC pc)\n{\n    PetscErrorCode ierr;\n    PC_PATCH       *patch;\n\n    PetscFunctionBegin;\n\n    ierr = PetscNewLog(pc, &patch); CHKERRQ(ierr);\n\n    /* Set some defaults */\n    patch->sub_mat_type       = NULL;\n    patch->save_operators     = PETSC_TRUE;\n    patch->partition_of_unity = PETSC_FALSE;\n    patch->multiplicative     = PETSC_FALSE;\n    patch->codim              = -1;\n    patch->dim                = -1;\n    patch->exclude_subspace   = -1;\n    patch->vankadim           = -1;\n    patch->patchconstructop   = PCPatchConstruct_Star;\n    patch->print_patches      = PETSC_FALSE;\n    patch->symmetrise_sweep   = PETSC_FALSE;\n    patch->nuserIS            = 0;\n    patch->userIS             = NULL;\n    patch->iterationSet       = NULL;\n    patch->user_patches       = PETSC_FALSE;\n\n    pc->data                 = (void *)patch;\n    pc->ops->apply           = PCApply_PATCH;\n    pc->ops->applytranspose  = 0; /* PCApplyTranspose_PATCH; */\n    pc->ops->setup           = PCSetUp_PATCH;\n    pc->ops->reset           = PCReset_PATCH;\n    pc->ops->destroy         = PCDestroy_PATCH;\n    pc->ops->setfromoptions  = PCSetFromOptions_PATCH;\n    pc->ops->setuponblocks   = PCSetUpOnBlocks_PATCH;\n    pc->ops->view            = PCView_PATCH;\n    pc->ops->applyrichardson = 0;\n\n    PetscFunctionReturn(0);\n}\n", "meta": {"hexsha": "a2294b421bc2c89b2e3cf3b7df3e1b193aa393f1", "size": 74928, "ext": "c", "lang": "C", "max_stars_repo_path": "ssc/libssc.c", "max_stars_repo_name": "wence-/ssc", "max_stars_repo_head_hexsha": "c56af51286a7dd7f3d98a8087903e3d18ca937cb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ssc/libssc.c", "max_issues_repo_name": "wence-/ssc", "max_issues_repo_head_hexsha": "c56af51286a7dd7f3d98a8087903e3d18ca937cb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-03-05T12:22:54.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-27T10:54:59.000Z", "max_forks_repo_path": "ssc/libssc.c", "max_forks_repo_name": "wence-/ssc", "max_forks_repo_head_hexsha": "c56af51286a7dd7f3d98a8087903e3d18ca937cb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-01-23T15:21:31.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-23T15:21:31.000Z", "avg_line_length": 43.4113557358, "max_line_length": 242, "alphanum_fraction": 0.6019111681, "num_tokens": 19556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2751297238231752, "lm_q2_score": 0.01665704241946795, "lm_q1q2_score": 0.004582847480579131}}
{"text": "/* $Id$   */\n/*--------------------------------------------------------------------*/\n/*;  Copyright (C) 2004-2020                                          */\n/*;  Associated Universities, Inc. Washington DC, USA.                */\n/*;                                                                   */\n/*;  This program is free software; you can redistribute it and/or    */\n/*;  modify it under the terms of the GNU General Public License as   */\n/*;  published by the Free Software Foundation; either version 2 of   */\n/*;  the License, or (at your option) any later version.              */\n/*;                                                                   */\n/*;  This program is distributed in the hope that it will be useful,  */\n/*;  but WITHOUT ANY WARRANTY; without even the implied warranty of   */\n/*;  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the    */\n/*;  GNU General Public License for more details.                     */\n/*;                                                                   */\n/*;  You should have received a copy of the GNU General Public        */\n/*;  License along with this program; if not, write to the Free       */\n/*;  Software Foundation, Inc., 675 Massachusetts Ave, Cambridge,     */\n/*;  MA 02139, USA.                                                   */\n/*;                                                                   */\n/*;Correspondence about this software should be addressed as follows: */\n/*;         Internet email: bcotton@nrao.edu.                         */\n/*;         Postal address: William Cotton                            */\n/*;                         National Radio Astronomy Observatory      */\n/*;                         520 Edgemont Road                         */\n/*;                         Charlottesville, VA 22903-2475 USA        */\n/*--------------------------------------------------------------------*/\n\n#include \"ObitUVDesc.h\"\n#include \"ObitUVUtil.h\"\n#include \"ObitTableSUUtil.h\"\n#include \"ObitTableNXUtil.h\"\n#include \"ObitTablePSUtil.h\"\n#include \"ObitTableFQUtil.h\"\n#include \"ObitTableANUtil.h\"\n#include \"ObitTableFG.h\"\n#include \"ObitPrecess.h\"\n#include \"ObitUVWCalc.h\"\n#include \"ObitUVSortBuffer.h\"\n#if HAVE_GSL==1  /* GSL stuff */\n#include <gsl/gsl_randist.h>\n#endif /* HAVE_GSL */\n/*----------------Obit: Merx mollis mortibus nuper ------------------*/\n/**\n * \\file ObitUVUtil.c\n * ObitUVUtil module function definitions.\n */\n\n/*---------------Private function prototypes----------------*/\n/** Modify output descriptor from effects of frequency averaging */\nstatic ofloat AvgFSetDesc (ObitUVDesc *inDesc, ObitUVDesc *outDesc, \n\t\t\t   olong NumChAvg, olong *ChanSel, gboolean doAvgAll, \n\t\t\t   olong *corChan, olong *corIF, olong *corStok, gboolean *corMask,\n\t\t\t   ObitErr *err);\n\n/** Modify output descriptor from effects of frequency bloating */\nstatic ofloat BloatFSetDesc (ObitUVDesc *inDesc, ObitUVDesc *outDesc, \n\t\t\t     olong nBloat, ObitErr *err);\n\n/** Average visibility in frequency */\nstatic void AvgFAver (ObitUVDesc *inDesc, ObitUVDesc *outDesc, \n\t\t      olong NumChAvg, olong *ChanSel, gboolean doAvgAll, \n\t\t      olong *corChan, olong *corIF, olong *corStok, gboolean *corMask,\n\t\t      ofloat *inBuffer, ofloat *outBuffer, ofloat *work, \n\t\t      ObitErr *err);\n\n/** Smooth visibility in frequency */\nstatic void SmooF (ObitUVDesc *inDesc, ObitUVDesc *outDesc, olong NumChSmo, \n\t\t   olong *corChan, olong *corIF, olong *corStok, gboolean *corMask,\n\t\t   ofloat *inBuffer, ofloat *outBuffer, ofloat *work, \n\t\t   ObitErr *err);\n\n/** Hann visibility in frequency */\nstatic void Hann (ObitUVDesc *inDesc, ObitUVDesc *outDesc, gboolean doDescm,\n\t\t  ofloat *inBuffer, ofloat *outBuffer, ofloat *work, \n\t\t  ObitErr *err);\n\n/** Duplicate channels */\nstatic void Bloat (ObitUVDesc *inDesc, ObitUVDesc *outDesc, olong nBloat,\n\t\t   gboolean unHann, ofloat *inBuffer, ofloat *outBuffer, \n\t\t   ObitErr *err);\n\n/** Copy selected channels */\nstatic void FreqSel (ObitUVDesc *inDesc, ObitUVDesc *outDesc, \n\t\t     olong BChan, olong EChan, olong chinc,\n\t\t     olong BIF, olong EIF,\n\t\t     ofloat *inBuffer, ofloat *outBuffer);\n\n/** Update FQ table for averaging */\nstatic void FQSel (ObitUV *inUV, olong chAvg, olong fqid, ObitErr *err);\n\n/** Low accuracy inverse Sinc function */\nstatic ofloat InvSinc(ofloat arg);\n/*----------------------Public functions---------------------------*/\n\n/**\n * Find maximum baseline length and W in a data set.\n * Imaging parameters are on the inUV info member as arrays for a number \n * of fields.\n * \\param inUV     Input uv data. \n * \\param MaxBL    Output maximum baseline length (sqrt(u*u+v*v))\n * \\param MaxW     Output Max abs(w) in data.\n * \\param err      Error stack, returns if not empty.\n */\nvoid ObitUVUtilUVWExtrema (ObitUV *inUV, ofloat *MaxBL, ofloat *MaxW, ObitErr *err)\n{\n  ObitIOCode retCode=OBIT_IO_SpecErr;\n  olong i;\n  ofloat bl, maxbl, maxw, *u, *v, *w;\n  gchar *routine = \"ObitUVUtilUVWExtrema\";\n \n   /* error checks */\n  g_assert (ObitErrIsA(err));\n  if (err->error) return;\n  g_assert (ObitUVIsA(inUV));\n\n  /* See if values are already in the descriptor */\n  if ((inUV->myDesc->maxBL>0.0) && (inUV->myDesc->maxW>0.0)) {\n    *MaxBL = inUV->myDesc->maxBL;\n    *MaxW  = inUV->myDesc->maxW;\n    return;\n  }\n\n  /* Open uv data if not already open */\n  if (inUV->myStatus==OBIT_Inactive) {\n    retCode = ObitUVOpen (inUV, OBIT_IO_ReadOnly, err);\n    if (err->error) Obit_traceback_msg (err, routine, inUV->name);\n  }\n\n  /* Loop through data */\n  maxbl = maxw = 0.0;\n  while (retCode==OBIT_IO_OK) {\n    /* read buffer full */\n    retCode = ObitUVRead (inUV, NULL, err);\n    if (err->error) Obit_traceback_msg (err, routine, inUV->name);\n    \n    /* initialize data pointers */\n    u   = inUV->buffer+inUV->myDesc->ilocu;\n    v   = inUV->buffer+inUV->myDesc->ilocv;\n    w   = inUV->buffer+inUV->myDesc->ilocw;\n    for (i=0; i<inUV->myDesc->numVisBuff; i++) { /* loop over buffer */\n      \n      /* Get statistics */\n      bl = sqrt ((*u)*(*u) + (*v)*(*v));\n      maxbl = MAX (maxbl, bl);\n      maxw = MAX (fabs(*w), maxw);\n      \n      /* update data pointers */\n      u += inUV->myDesc->lrec;\n      v += inUV->myDesc->lrec;\n      w += inUV->myDesc->lrec;\n    } /* end loop over buffer */\n  } /* end loop over file */\n  \n    /* Close */\n  retCode = ObitUVClose (inUV, err);\n  if (err->error) Obit_traceback_msg (err, routine, inUV->name);\n\n  /* Save values in the descriptor */\n  inUV->myDesc->maxBL = maxbl;\n  inUV->myDesc->maxW  = maxw;\n\n  *MaxBL = maxbl;\n  *MaxW  = maxw;\n  \n} /* end ObitUVUtilUVWExtrema */\n\n/**\n * Make copy of ObitUV with the visibilities zeroed and weights 1.\n * \\param inUV     Input uv data to copy. \n * \\param scratch  True if scratch file desired, will be same type as inUV.\n * \\param outUV    If not scratch, then the previously defined output file\n *                 May be NULL for scratch only\n *                 If it exists and scratch, it will be Unrefed\n * \\param err      Error stack, returns if not empty.\n * \\return the zeroed ObitUV.\n */\nObitUV* ObitUVUtilCopyZero (ObitUV *inUV, gboolean scratch, ObitUV *outUV, \n\t\t\t    ObitErr *err)\n{\n  ObitIOCode iretCode, oretCode;\n  gboolean doCalSelect;\n  gchar *exclude[]={\"AIPS CL\",\"AIPS SN\",\"AIPS FG\",\"AIPS CQ\",\"AIPS WX\",\n\t\t    \"AIPS AT\",\"AIPS CT\",\"AIPS OB\",\"AIPS IM\",\"AIPS MC\",\n\t\t    \"AIPS PC\",\"AIPS NX\",\"AIPS TY\",\"AIPS GC\",\"AIPS HI\",\n\t\t    \"AIPS PL\",\"AIPS NI\",\"AIPS SY\",\"AIPS PT\",\"AIPS OT\",\n\t\t    NULL};\n  gchar *sourceInclude[] = {\"AIPS SU\", NULL};\n  olong i, j, indx;\n  ObitInfoType type;\n  gint32 dim[MAXINFOELEMDIM];\n  ObitIOAccess access;\n  ObitUVDesc *inDesc, *outDesc;\n  gchar *today=NULL;\n  gchar *routine = \"ObitUVUtilCopyZero\";\n \n  /* error checks */\n  g_assert (ObitErrIsA(err));\n  if (err->error) return outUV;\n  g_assert (ObitUVIsA(inUV));\n  if (!scratch && (outUV==NULL)) {\n    Obit_log_error(err, OBIT_Error,\"%s Output MUST be defined for non scratch files\",\n\t\t   routine);\n      return outUV;\n  }\n\n  /* Create scratch? */\n  if (scratch) {\n    if (outUV) outUV = ObitUVUnref(outUV);\n    outUV = newObitUVScratch (inUV, err);\n  } else { /* non scratch output must exist - clone from inUV */\n   outUV->myDesc = ObitUVDescCopy (inUV->myDesc, outUV->myDesc, err);\n    ObitUVClone (inUV, outUV, err);\n  }\n  if (err->error) Obit_traceback_val (err, routine, inUV->name, inUV);\n\n  /* Selection of input? */\n  doCalSelect = FALSE;\n  ObitInfoListGetTest(inUV->info, \"doCalSelect\", &type, (gint32*)dim, &doCalSelect);\n  if (doCalSelect) access = OBIT_IO_ReadCal;\n  else access = OBIT_IO_ReadOnly;\n\n  /* test open to fully instantiate input and see if it's OK */\n  iretCode = ObitUVOpen (inUV, access, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error)) /* add traceback,return */\n    Obit_traceback_val (err, routine, inUV->name, outUV);\n\n  /* copy Descriptor */\n  outUV->myDesc = ObitUVDescCopy(inUV->myDesc, outUV->myDesc, err);\n\n  /* Creation date today */\n  today = ObitToday();\n  strncpy (outUV->myDesc->date, today, UVLEN_VALUE-1);\n  if (today) g_free(today);\n  \n  /* use same data buffer on input and output \n     so don't assign buffer for output */\n  if (outUV->buffer) ObitIOFreeBuffer(outUV->buffer); /* free existing */\n  outUV->buffer = NULL;\n  outUV->bufferSize = -1;\n\n  /* test open output */\n  oretCode = ObitUVOpen (outUV, OBIT_IO_WriteOnly, err);\n  /* If this didn't work try OBIT_IO_ReadWrite */\n  if ((oretCode!=OBIT_IO_OK) || (err->error)) {\n    ObitErrClear(err);\n    oretCode = ObitUVOpen (outUV, OBIT_IO_ReadWrite, err);\n  }\n  /* if it didn't work bail out */\n  if ((oretCode!=OBIT_IO_OK) || (err->error)) {\n    /* unset output buffer (may be multiply deallocated) */\n    outUV->buffer = NULL;\n    outUV->bufferSize = 0;\n    Obit_traceback_val (err, routine, outUV->name, outUV);\n  }\n\n  /* iretCode = ObitUVClose (inUV, err); DEBUG */\n  /* Copy tables before data */\n  iretCode = ObitUVCopyTables (inUV, outUV, exclude, NULL, err);\n  /* If multisource out then copy SU table, multiple sources selected or\n   sources deselected suggest MS out */\n  if ((inUV->mySel->numberSourcesList>1) || (!inUV->mySel->selectSources))\n  iretCode = ObitUVCopyTables (inUV, outUV, NULL, sourceInclude, err);\n  if (err->error) {\n    outUV->buffer = NULL;\n    outUV->bufferSize = 0;\n    Obit_traceback_val (err, routine, inUV->name, outUV);\n  }\n\n  /* reset to beginning of uv data */\n  iretCode = ObitIOSet (inUV->myIO,  inUV->info, err);\n  oretCode = ObitIOSet (outUV->myIO, outUV->info, err);\n  if (err->error) Obit_traceback_val (err, routine,inUV->name, outUV);\n\n  /* Close and reopen input to init calibration which will have been disturbed \n     by the table copy */\n  iretCode = ObitUVClose (inUV, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error)) /* add traceback,return */\n    Obit_traceback_val (err, routine,inUV->name, outUV);\n\n  iretCode = ObitUVOpen (inUV, access, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error)) /* add traceback,return */\n    Obit_traceback_val (err, routine,inUV->name, outUV);\n  outUV->buffer = inUV->buffer;\n\n  /* Get descriptors */\n  inDesc  = inUV->myDesc;\n  outDesc = outUV->myDesc;\n\n  /* we're in business, copy, zero data, set weight to 1 */\n  while ((iretCode==OBIT_IO_OK) && (oretCode==OBIT_IO_OK)) {\n    if (doCalSelect) iretCode = ObitUVReadSelect (inUV, inUV->buffer, err);\n    else iretCode = ObitUVRead (inUV, inUV->buffer, err);\n    if (iretCode!=OBIT_IO_OK) break;\n   /* How many */\n    outDesc->numVisBuff = inDesc->numVisBuff;\n\n    /* Modify data */\n    for (i=0; i<inDesc->numVisBuff; i++) { /* loop over visibilities */\n      indx = i*inDesc->lrec + inDesc->nrparm;\n      for (j=0; j<inDesc->ncorr; j++) { /* loop over correlations */\n\tinUV->buffer[indx]   = 0.0;\n\tinUV->buffer[indx+1] = 0.0;\n\tinUV->buffer[indx+2] = 1.0;\n\tindx += inDesc->inaxes[0];\n      } /* end loop over correlations */\n    } /* end loop over visibilities */\n\n    /* Write */\n    oretCode = ObitUVWrite (outUV, inUV->buffer, err);\n  } /* end loop processing data */\n  \n  /* check for errors */\n  if ((iretCode > OBIT_IO_EOF) || (oretCode > OBIT_IO_EOF) ||\n      (err->error)) /* add traceback,return */\n    Obit_traceback_val (err, routine,inUV->name, outUV);\n  \n  /* unset input buffer (may be multiply deallocated ;'{ ) */\n  outUV->buffer = NULL;\n  outUV->bufferSize = 0;\n  \n  /* close files */\n  iretCode = ObitUVClose (inUV, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error)) \n    Obit_traceback_val (err, routine, inUV->name, outUV);\n  \n  oretCode = ObitUVClose (outUV, err);\n  if ((oretCode!=OBIT_IO_OK) || (err->error))\n    Obit_traceback_val (err, routine, outUV->name, outUV);\n  \n  return outUV;\n} /* end ObitUVUtilCopyZero */\n\n/**\n * Divide the visibilities in one ObitUV by those in another\n * outUV = inUV1 / inUV2\n * \\param inUV1    Input uv data numerator, no calibration/selection\n * \\param inUV2    Input uv data denominator, no calibration/selection\n *                 inUV2 should have the same structure, no. vis etc\n *                 as inUV1.\n * \\param outUV    Previously defined output, may be the same as inUV1\n * \\param err      Error stack, returns if not empty.\n */\nvoid ObitUVUtilVisDivide (ObitUV *inUV1, ObitUV *inUV2, ObitUV *outUV, \n\t\t\t  ObitErr *err)\n{\n  ObitIOCode iretCode, oretCode;\n  gchar *exclude[]={\"AIPS CL\",\"AIPS SN\",\"AIPS FG\",\"AIPS CQ\",\"AIPS WX\",\n\t\t    \"AIPS AT\",\"AIPS CT\",\"AIPS OB\",\"AIPS IM\",\"AIPS MC\",\n\t\t    \"AIPS PC\",\"AIPS NX\",\"AIPS TY\",\"AIPS GC\",\"AIPS HI\",\n\t\t    \"AIPS PL\",\"AIPS NI\",\"AIPS SY\",\"AIPS PT\",\"AIPS OT\",\n\t\t    NULL};\n  gchar *sourceInclude[] = {\"AIPS SU\", NULL};\n  olong i, j, indx, firstVis;\n  ObitInfoType type;\n  gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};\n  olong NPIO;\n  ofloat work[3];\n  gboolean incompatible, same, btemp;\n  ObitUVDesc *in1Desc, *in2Desc, *outDesc;\n  gchar *today=NULL;\n  gchar *routine = \"ObitUVUtilVisDivide\";\n\n  /* error checks */\n  g_assert (ObitErrIsA(err));\n  if (err->error) return;\n  g_assert (ObitUVIsA(inUV1));\n  g_assert (ObitUVIsA(inUV2));\n  g_assert (ObitUVIsA(outUV));\n\n  /* Are input1 and output the same file? */\n  same = ObitUVSame(inUV1, outUV, err);\n  if (err->error) Obit_traceback_msg (err, routine, inUV1->name);\n\n  /* test open to fully instantiate input and see if it's OK */\n  iretCode = ObitUVOpen (inUV1, OBIT_IO_ReadWrite, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error)) /* add traceback,return */\n    Obit_traceback_msg (err, routine,inUV1->name);\n\n  /* copy Descriptor */\n  outUV->myDesc = ObitUVDescCopy(inUV1->myDesc, outUV->myDesc, err);\n\n  /* Creation date today */\n  today = ObitToday();\n  strncpy (outUV->myDesc->date, today, UVLEN_VALUE-1);\n  if (today) g_free(today);\n \n  /* use same data buffer on input and output.\n     If multiple passes are made the input files will be closed\n     which deallocates the buffer, use output buffer.\n     so free input buffer */\n  if (!same) {\n    /* use same data buffer on input 1 and output \n       so don't assign buffer for output */\n    if (outUV->buffer) ObitIOFreeBuffer(outUV->buffer); /* free existing */\n    outUV->buffer = NULL;\n    outUV->bufferSize = -1;\n  }\n\n   /* Copy number of records per IO to second input */\n  ObitInfoListGet (inUV1->info, \"nVisPIO\", &type, dim,  (gpointer)&NPIO, err);\n  ObitInfoListPut (inUV2->info, \"nVisPIO\",  type, dim,  (gpointer)&NPIO, err);\n  if (err->error) Obit_traceback_msg (err, routine, inUV1->name);\n\n  /* Open second input */\n  iretCode = ObitUVOpen (inUV2, OBIT_IO_ReadWrite, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error)) \n    Obit_traceback_msg (err, routine,inUV2->name);\n\n  /* Get input descriptors */\n  in1Desc = inUV1->myDesc;\n  in2Desc = inUV2->myDesc;\n\n  /* Check compatability between inUV1, inUV2 */\n  incompatible = in1Desc->nvis!=in2Desc->nvis;\n  incompatible = incompatible || (in1Desc->ncorr!=in2Desc->ncorr);\n  incompatible = incompatible || (in1Desc->jlocs!=in2Desc->jlocs);\n  incompatible = incompatible || (in1Desc->jlocf!=in2Desc->jlocf);\n  incompatible = incompatible || (in1Desc->jlocif!=in2Desc->jlocif);\n  incompatible = incompatible || (in1Desc->ilocb!=in2Desc->ilocb);\n  if (incompatible) {\n     Obit_log_error(err, OBIT_Error,\"%s inUV1 and inUV2 have incompatible structures\",\n\t\t   routine);\n      return ;\n }\n\n  /* Look at all data */\n  btemp = TRUE;\n  dim[0] = dim[1] = dim[2] = 1;\n  ObitInfoListAlwaysPut(inUV1->info, \"passAll\", OBIT_bool, dim, &btemp);\n  ObitInfoListAlwaysPut(inUV2->info, \"passAll\", OBIT_bool, dim, &btemp);\n\n /* test open output */\n  oretCode = ObitUVOpen (outUV, OBIT_IO_WriteOnly, err);\n  /* If this didn't work try OBIT_IO_ReadWrite */\n  if ((oretCode!=OBIT_IO_OK) || (err->error)) {\n    ObitErrClear(err);\n    oretCode = ObitUVOpen (outUV, OBIT_IO_ReadWrite, err);\n  }\n  /* if it didn't work bail out */\n  if ((oretCode!=OBIT_IO_OK) || (err->error)) {\n    /* unset output buffer (may be multiply deallocated) */\n    outUV->buffer = NULL;\n    outUV->bufferSize = 0;\n    Obit_traceback_msg (err, routine, outUV->name);\n  }\n\n  /* Copy tables before data if in1 and out are not the same */\n  if (!ObitUVSame (inUV1, outUV, err)) {\n    iretCode = ObitUVCopyTables (inUV1, outUV, exclude, NULL, err);\n    /* If multisource out then copy SU table, multiple sources selected or\n       sources deselected suggest MS out */\n    if ((inUV1->mySel->numberSourcesList>1) || (!inUV1->mySel->selectSources))\n      iretCode = ObitUVCopyTables (inUV1, outUV, NULL, sourceInclude, err);\n    if (err->error) {\n      outUV->buffer = NULL;\n      outUV->bufferSize = 0;\n      Obit_traceback_msg (err, routine, inUV1->name);\n    }\n  }\n  if (err->error) Obit_traceback_msg (err, routine, inUV1->name);\n\n  /* reset to beginning of uv data */\n  iretCode = ObitUVIOSet (inUV1, err);\n  oretCode = ObitUVIOSet (outUV, err);\n  if (err->error) Obit_traceback_msg (err, routine,inUV1->name);\n\n  /* Close and reopen input to init calibration which will have been disturbed \n     by the table copy */\n  iretCode = ObitUVClose (inUV1, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error))\n    Obit_traceback_msg (err, routine,inUV1->name);\n  iretCode = ObitUVOpen (inUV1, OBIT_IO_ReadWrite, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error))\n    Obit_traceback_msg (err, routine,inUV1->name);\n  outUV->buffer = inUV1->buffer;\n\n  outDesc = outUV->myDesc;   /* Get output descriptor */\n\n  /* we're in business, divide */\n  while ((iretCode==OBIT_IO_OK) && (oretCode==OBIT_IO_OK)) {\n    /* Read first input */\n    iretCode = ObitUVRead (inUV1, inUV1->buffer, err);\n    if (iretCode!=OBIT_IO_OK) break;\n    /* Read second input */\n    iretCode = ObitUVRead (inUV2, inUV2->buffer, err);\n    if (iretCode!=OBIT_IO_OK) break;\n    /* How many */\n    outDesc->numVisBuff = in1Desc->numVisBuff;\n    firstVis = in1Desc->firstVis;\n\n    /* compatability check */\n    incompatible = in1Desc->numVisBuff!=in2Desc->numVisBuff;\n    if (incompatible) break;\n\n    /* Modify data */\n    for (i=0; i<in1Desc->numVisBuff; i++) { /* loop over visibilities */\n      /* compatability check - check time and baseline or antenna code */\n      indx = i*in1Desc->lrec ;\n      incompatible = \n\tinUV1->buffer[indx+in1Desc->iloct] !=inUV2->buffer[indx+in2Desc->iloct];\n      if (in1Desc->ilocb>=0) {\n\tincompatible = incompatible ||\n\t  inUV1->buffer[indx+in1Desc->ilocb] !=inUV2->buffer[indx+in2Desc->ilocb];\n      }\n      if (in1Desc->iloca1>=0) {\n\tincompatible = incompatible ||\n\t  inUV1->buffer[indx+in1Desc->iloca1]!=inUV2->buffer[indx+in2Desc->iloca1] ||\n\t  inUV1->buffer[indx+in1Desc->iloca2]!=inUV2->buffer[indx+in2Desc->iloca2];\n      }\n      if (incompatible) break;\n\n      indx += in1Desc->nrparm;\n      for (j=0; j<in1Desc->ncorr; j++) { /* loop over correlations */\n\t/* Divide */\n\tObitUVWtCpxDivide ((&inUV1->buffer[indx]), \n\t\t\t   (&inUV2->buffer[indx]), \n\t\t\t   (&inUV1->buffer[indx]), work);\n\tindx += in1Desc->inaxes[0];\n      } /* end loop over correlations */\n      if (incompatible) break;\n    } /* end loop over visibilities */\n    \n    /* Write */\n    oretCode = ObitUVWrite (outUV, inUV1->buffer, err);\n    if (same) {\n      outUV->myDesc->firstVis = firstVis;\n      ((ObitUVDesc*)(outUV->myIO->myDesc))->firstVis = firstVis;\n    }\n  } /* end loop processing data */\n  \n  /* Check for incompatibility */\n  if (incompatible) {\n    Obit_log_error(err, OBIT_Error,\"%s inUV1 and inUV2 have incompatible contents\",\n\t\t   routine);\n    return;\n  }\n    \n  /* check for errors */\n  if ((iretCode > OBIT_IO_EOF) || (oretCode > OBIT_IO_EOF) ||\n      (err->error)) /* add traceback,return */\n    Obit_traceback_msg (err, routine,inUV1->name);\n    \n  /* unset output buffer (may be multiply deallocated ;'{ ) */\n  outUV->buffer = NULL;\n  outUV->bufferSize = 0;\n  \n  /* close files */\n  iretCode = ObitUVClose (inUV1, err);\n  if (err->error) Obit_traceback_msg (err, routine, inUV1->name);\n  \n  iretCode = ObitUVClose (inUV2, err);\n  if (err->error) Obit_traceback_msg (err, routine, inUV2->name);\n  \n  oretCode = ObitUVClose (outUV, err);\n  if (err->error) Obit_traceback_msg (err, routine, outUV->name);\n  /* In case */\n  outUV->buffer     = NULL;\n  outUV->bufferSize = 0;\n \n  /* Reset passAll */\n  btemp = FALSE;\n  dim[0] = dim[1] = dim[2] = 1;\n  ObitInfoListAlwaysPut(inUV1->info, \"passAll\", OBIT_bool, dim, &btemp);\n  ObitInfoListAlwaysPut(inUV2->info, \"passAll\", OBIT_bool, dim, &btemp);\n\n} /* end ObitUVUtilVisDivide */\n\n/**\n * Divide the cross pol visibilities in one ObitUV by I pol (avg parallel pol)\n * \\param inUV     Input uv data, if info member KeepSou TRUE, copy SU table.\n * \\param outUV    Previously defined output, may be the same as inUV\n * \\param err      Error stack, returns if not empty.\n */\nvoid ObitUVUtilXPolDivide (ObitUV *inUV, ObitUV *outUV, ObitErr *err)\n{\n  ObitIOCode iretCode, oretCode;\n  gchar *exclude[]={\"AIPS CL\",\"AIPS SN\",\"AIPS FG\",\"AIPS CQ\",\"AIPS WX\",\n\t\t    \"AIPS AT\",\"AIPS CT\",\"AIPS OB\",\"AIPS IM\",\"AIPS MC\",\n\t\t    \"AIPS PC\",\"AIPS NX\",\"AIPS TY\",\"AIPS GC\",\"AIPS HI\",\n\t\t    \"AIPS PL\",\"AIPS NI\",\"AIPS SY\",\"AIPS PT\",\"AIPS OT\",\n\t\t    NULL};\n  gchar *sourceInclude[] = {\"AIPS SU\", NULL};\n  olong i, indx, jndx, firstVis;\n  olong iif, nif, ichan, nchan, istok, nstok, incs, incf, incif;\n  ObitInfoType type;\n  gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};\n  ofloat work[3], Ivis[3], wt, Ireal, Iimag, Iwt;\n  gboolean KeepSou, same;\n  ObitUVDesc *inDesc, *outDesc;\n  gchar *today=NULL;\n  gchar *routine = \"ObitUVUtilXPolDivide\";\n\n  /* error checks */\n  g_assert (ObitErrIsA(err));\n  if (err->error) return;\n  g_assert (ObitUVIsA(inUV));\n  g_assert (ObitUVIsA(outUV));\n\n  /* Are input1 and output the same file? */\n  same = ObitUVSame(inUV, outUV, err);\n  if (err->error) Obit_traceback_msg (err, routine, inUV->name);\n\n  /* Keep source table? */\n  KeepSou = FALSE;\n  ObitInfoListGetTest(inUV->info, \"KeepSou\", &type, (gint32*)dim, &KeepSou);\n\n  /* test open to fully instantiate input and see if it's OK */\n  iretCode = ObitUVOpen (inUV, OBIT_IO_ReadWrite, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error)) /* add traceback,return */\n    Obit_traceback_msg (err, routine, inUV->name);\n\n  /* Get input descriptor */\n  inDesc = inUV->myDesc;\n\n   /* Set up for parsing data */\n  nchan = inDesc->inaxes[inDesc->jlocf];\n  if (inDesc->jlocif>=0) nif = inDesc->inaxes[inDesc->jlocif];\n  else nif = 1;\n  if (inDesc->jlocs>=0) nstok = inDesc->inaxes[inDesc->jlocs];\n  else nstok = 1;\n  /* get increments */\n  incs  = inDesc->incs;\n  incf  = inDesc->incf;\n  incif = inDesc->incif;\n\n  /* Make sure at least 4 Stokes correlations */\n  Obit_return_if_fail ((nstok>=4), err,\n\t\t       \"%s: MUST have at least 4 Stokes, have  %d\",  \n\t\t       routine, nstok);  \n\n  /* copy Descriptor */\n  outUV->myDesc = ObitUVDescCopy(inUV->myDesc, outUV->myDesc, err);\n\n  /* Creation date today */\n  today = ObitToday();\n  strncpy (outUV->myDesc->date, today, UVLEN_VALUE-1);\n  if (today) g_free(today);\n \n  /* use same data buffer on input and output.\n     If multiple passes are made the input files will be closed\n     which deallocates the buffer, use output buffer.\n     so free input buffer */\n  if (!same) {\n    /* use same data buffer on input 1 and output \n       so don't assign buffer for output */\n    if (outUV->buffer) ObitIOFreeBuffer(outUV->buffer); /* free existing */\n    outUV->buffer = NULL;\n    outUV->bufferSize = -1;\n  }\n\n  /* test open output */\n  oretCode = ObitUVOpen (outUV, OBIT_IO_WriteOnly, err);\n  /* If this didn't work try OBIT_IO_ReadWrite */\n  if ((oretCode!=OBIT_IO_OK) || (err->error)) {\n    ObitErrClear(err);\n    oretCode = ObitUVOpen (outUV, OBIT_IO_ReadWrite, err);\n  }\n  /* if it didn't work bail out */\n  if ((oretCode!=OBIT_IO_OK) || (err->error)) {\n    /* unset output buffer (may be multiply deallocated) */\n    outUV->buffer = NULL;\n    outUV->bufferSize = 0;\n    Obit_traceback_msg (err, routine, outUV->name);\n  }\n\n  /* Copy tables before data if in1 and out are not the same */\n  if (!ObitUVSame (inUV, outUV, err)) {\n    iretCode = ObitUVCopyTables (inUV, outUV, exclude, NULL, err);\n    /* If multisource out then copy SU table, multiple sources selected or\n       sources deselected suggest MS out or KeepSou == TRUE */\n    if ((inUV->mySel->numberSourcesList>1) || (!inUV->mySel->selectSources) ||\n\tKeepSou)\n      iretCode = ObitUVCopyTables (inUV, outUV, NULL, sourceInclude, err);\n    if (err->error) {\n      outUV->buffer = NULL;\n      outUV->bufferSize = 0;\n      Obit_traceback_msg (err, routine, inUV->name);\n    }\n  }\n  if (err->error) Obit_traceback_msg (err, routine, inUV->name);\n\n  /* reset to beginning of uv data */\n  iretCode = ObitUVIOSet (inUV, err);\n  oretCode = ObitUVIOSet (outUV, err);\n  if (err->error) Obit_traceback_msg (err, routine,inUV->name);\n\n  /* Close and reopen input to init calibration which will have been disturbed \n     by the table copy */\n  iretCode = ObitUVClose (inUV, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error))\n    Obit_traceback_msg (err, routine,inUV->name);\n  iretCode = ObitUVOpen (inUV, OBIT_IO_ReadWrite, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error))\n    Obit_traceback_msg (err, routine,inUV->name);\n  outUV->buffer = inUV->buffer;\n\n  outDesc = outUV->myDesc;   /* Get output descriptor */\n\n  /* we're in business, divide */\n  while ((iretCode==OBIT_IO_OK) && (oretCode==OBIT_IO_OK)) {\n    /* Read input */\n    iretCode = ObitUVRead (inUV, inUV->buffer, err);\n    if (iretCode!=OBIT_IO_OK) break;\n    /* How many */\n    outDesc->numVisBuff = inDesc->numVisBuff;\n    firstVis = inDesc->firstVis;\n\n    /* Modify data */\n    for (i=0; i<inDesc->numVisBuff; i++) { /* loop over visibilities */\n      indx = inDesc->nrparm + i*inDesc->lrec;\n      /* loop over IF */\n      for (iif=0; iif<nif; iif++) {\n\t/* Loop over frequency channel */\n\tfor (ichan=0; ichan<nchan; ichan++) { /* loop 60 */\n\t  jndx = indx + iif*incif + ichan*incf;\n\t  /* Get Stokes I - average parallel hands */\n\t  wt = inUV->buffer[jndx+2];\n\t  if (wt>0.0) {\n\t    Ireal = wt*inUV->buffer[jndx];\n\t    Iimag = wt*inUV->buffer[jndx+1];\n\t    Iwt   = wt;\n\t  } else {\n\t    Ireal = Iimag = Iwt = 0.0;\n\t  }\n\t  wt = inUV->buffer[jndx+5];\n\t  if (wt>0.0) {\n\t    Ireal += wt*inUV->buffer[jndx+3];\n\t    Iimag += wt*inUV->buffer[jndx+4];\n\t    Iwt   += wt;\n\t  }\n\t  if (Iwt > 0.0) {\n\t    Ivis[0] = Ireal/Iwt;\n\t    Ivis[1] = Iimag/Iwt;\n\t    Ivis[2] = Iwt;\n\t  } else {\n\t    Ivis[0] = Ivis[1] = Ivis[2] = 0.0;\n\t  }\n\t  /* Loop over cross polarization */\n\t  for (istok=2; istok<nstok; istok++) {\n\t    jndx = indx + iif*incif + ichan*incf + istok*incs;\n\t    /* Divide */\n\t    ObitUVWtCpxDivide ((&inUV->buffer[jndx]), Ivis,\n\t\t\t       (&inUV->buffer[jndx]), work);\n\t  } /* end loop over Stokes */\n\t} /* end loop over channels */\n      } /* end loop over IFs */\n    } /* end loop over visibilities */\n    \n    /* Write */\n    oretCode = ObitUVWrite (outUV, inUV->buffer, err);\n    if (same) {\n      outUV->myDesc->firstVis = firstVis;\n      ((ObitUVDesc*)(outUV->myIO->myDesc))->firstVis = firstVis;\n    }\n  } /* end loop processing data */\n  \n  /* check for errors */\n  if ((iretCode > OBIT_IO_EOF) || (oretCode > OBIT_IO_EOF) ||\n      (err->error)) /* add traceback,return */\n    Obit_traceback_msg (err, routine,inUV->name);\n    \n  /* unset output buffer (may be multiply deallocated ;'{ ) */\n  outUV->buffer = NULL;\n  outUV->bufferSize = 0;\n  \n  /* close files */\n  iretCode = ObitUVClose (inUV, err);\n  if (err->error) Obit_traceback_msg (err, routine, inUV->name);\n  \n  oretCode = ObitUVClose (outUV, err);\n  if (err->error) Obit_traceback_msg (err, routine, outUV->name);\n  /* In case */\n  outUV->buffer     = NULL;\n  outUV->bufferSize = 0;\n \n} /* end ObitUVUtilXPolDivide */\n\n/**\n * Subtract the visibilities in one ObitUV from those in another\n * outUV = inUV1 - inUV2\n * \\param inUV1    First input uv data, no calibration/selection\n * \\param inUV2    Second input uv data, calibration/selection allowed\n *                 inUV2 should have the same structure, no. vis etc\n *                 as inUV1.\n * \\param outUV    Previously defined output, may be the same as inUV1\n * \\param err      Error stack, returns on error\n */\nvoid ObitUVUtilVisSub (ObitUV *inUV1, ObitUV *inUV2, ObitUV *outUV, \n\t\t       ObitErr *err)\n{\n  ObitIOCode iretCode, oretCode;\n  gchar *exclude[]={\"AIPS CL\",\"AIPS SN\",\"AIPS FG\",\"AIPS CQ\",\"AIPS WX\",\n\t\t    \"AIPS AT\",\"AIPS CT\",\"AIPS OB\",\"AIPS IM\",\"AIPS MC\",\n\t\t    \"AIPS PC\",\"AIPS NX\",\"AIPS TY\",\"AIPS GC\",\"AIPS HI\",\n\t\t    \"AIPS PL\",\"AIPS NI\",\"AIPS SY\",\"AIPS PT\",\"AIPS OT\",\n\t\t    NULL};\n  gchar *sourceInclude[] = {\"AIPS SU\", NULL};\n  olong i, j, indx, firstVis;\n  ObitInfoType type;\n  gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};\n  olong NPIO;\n  gboolean incompatible, same, doCalSelect, btemp;\n  ObitUVDesc *in1Desc, *in2Desc, *outDesc;\n  ObitIOAccess access;\n  gchar *today=NULL;\n  gchar *routine = \"ObitUVUtilVisSub\";\n\n  /* error checks */\n  g_assert (ObitErrIsA(err));\n  if (err->error) return;\n  g_assert (ObitUVIsA(inUV1));\n  g_assert (ObitUVIsA(inUV2));\n  g_assert (ObitUVIsA(outUV));\n\n  /* Are input1 and output the same file? */\n  same = ObitUVSame(inUV1, outUV, err);\n  if (err->error) Obit_traceback_msg (err, routine, inUV1->name);\n\n  /* test open to fully instantiate input and see if it's OK */\n  iretCode = ObitUVOpen (inUV1, OBIT_IO_ReadWrite, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error)) /* add traceback,return */\n    Obit_traceback_msg (err, routine,inUV1->name);\n\n  /* copy Descriptor */\n  outUV->myDesc = ObitUVDescCopy(inUV1->myDesc, outUV->myDesc, err);\n\n  /* Creation date today */\n  today = ObitToday();\n  strncpy (outUV->myDesc->date, today, UVLEN_VALUE-1);\n  if (today) g_free(today);\n \n  /* use same data buffer on input and output.\n     If multiple passes are made the input files will be closed\n     which deallocates the buffer, use output buffer.\n     so free input buffer */\n  if (!same) {\n    /* use same data buffer on input 1 and output \n       so don't assign buffer for output */\n    if (outUV->buffer) ObitIOFreeBuffer(outUV->buffer); /* free existing */\n    outUV->buffer = NULL;\n    outUV->bufferSize = -1;\n  }\n\n   /* Copy number of records per IO to second input */\n  ObitInfoListGet (inUV1->info, \"nVisPIO\", &type, dim,  (gpointer)&NPIO, err);\n  ObitInfoListPut (inUV2->info, \"nVisPIO\",  type, dim,  (gpointer)&NPIO, err);\n  if (err->error) Obit_traceback_msg (err, routine, inUV1->name);\n\n  /* Selection of second input? */\n  doCalSelect = FALSE;\n  ObitInfoListGetTest(inUV2->info, \"doCalSelect\", &type, dim, &doCalSelect);\n  if (doCalSelect) access = OBIT_IO_ReadCal;\n  else access = OBIT_IO_ReadOnly;\n\n  /* Open second input */\n  iretCode = ObitUVOpen (inUV2, access, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error)) \n    Obit_traceback_msg (err, routine,inUV2->name);\n\n  /* Get input descriptors */\n  in1Desc = inUV1->myDesc;\n  in2Desc = inUV2->myDesc;\n\n  /* Check compatability between inUV1, inUV2 */\n  incompatible = in1Desc->nvis!=in2Desc->nvis;\n  incompatible = incompatible || (in1Desc->ncorr!=in2Desc->ncorr);\n  incompatible = incompatible || (in1Desc->jlocs!=in2Desc->jlocs);\n  incompatible = incompatible || (in1Desc->jlocf!=in2Desc->jlocf);\n  incompatible = incompatible || (in1Desc->jlocif!=in2Desc->jlocif);\n  incompatible = incompatible || (in1Desc->ilocb!=in2Desc->ilocb);\n  if (incompatible) {\n     Obit_log_error(err, OBIT_Error,\"%s inUV1 and inUV2 have incompatible structures\",\n\t\t   routine);\n      return ;\n  }\n\n  /* Look at all data */\n  btemp = TRUE;\n  dim[0] = dim[1] = dim[2] = 1;\n  ObitInfoListAlwaysPut(inUV1->info, \"passAll\", OBIT_bool, dim, &btemp);\n  ObitInfoListAlwaysPut(inUV2->info, \"passAll\", OBIT_bool, dim, &btemp);\n  \n  /* test open output */\n  oretCode = ObitUVOpen (outUV, OBIT_IO_WriteOnly, err);\n  /* If this didn't work try OBIT_IO_ReadWrite */\n  if ((oretCode!=OBIT_IO_OK) || (err->error)) {\n    ObitErrClear(err);\n    oretCode = ObitUVOpen (outUV, OBIT_IO_ReadWrite, err);\n  }\n  /* if it didn't work bail out */\n  if ((oretCode!=OBIT_IO_OK) || (err->error)) {\n    /* unset output buffer (may be multiply deallocated) */\n    outUV->buffer = NULL;\n    outUV->bufferSize = 0;\n    Obit_traceback_msg (err, routine, outUV->name);\n  }\n\n  /* Copy tables before data if in1 and out are not the same */\n  if (!ObitUVSame (inUV1, outUV, err)) {\n    iretCode = ObitUVCopyTables (inUV1, outUV, exclude, NULL, err);\n    /* If multisource out then copy SU table, multiple sources selected or\n       sources deselected suggest MS out */\n    if ((inUV1->mySel->numberSourcesList>1) || (!inUV1->mySel->selectSources))\n      iretCode = ObitUVCopyTables (inUV1, outUV, NULL, sourceInclude, err);\n    if (err->error) {\n      outUV->buffer = NULL;\n      outUV->bufferSize = 0;\n      Obit_traceback_msg (err, routine, inUV1->name);\n    }\n  }\n  if (err->error) Obit_traceback_msg (err, routine, inUV1->name);\n\n  /* reset to beginning of uv data */\n  iretCode = ObitUVIOSet (inUV1, err);\n  oretCode = ObitUVIOSet (outUV, err);\n  if (err->error) Obit_traceback_msg (err, routine,inUV1->name);\n\n  /* Close and reopen input to init calibration which will have been disturbed \n     by the table copy */\n  iretCode = ObitUVClose (inUV1, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error))\n    Obit_traceback_msg (err, routine,inUV1->name);\n  iretCode = ObitUVOpen (inUV1, OBIT_IO_ReadWrite, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error))\n    Obit_traceback_msg (err, routine,inUV1->name);\n  outUV->buffer = inUV1->buffer;\n\n  outDesc = outUV->myDesc;   /* Get output descriptor */\n\n  /* we're in business, subtract */\n  while ((iretCode==OBIT_IO_OK) && (oretCode==OBIT_IO_OK)) {\n    /* Read first input */\n    iretCode = ObitUVRead (inUV1, inUV1->buffer, err);\n    if (iretCode!=OBIT_IO_OK) break;\n    /* Read second input */\n    if (doCalSelect) iretCode = ObitUVReadSelect (inUV2, inUV2->buffer, err);\n    else iretCode = ObitUVRead (inUV2, inUV2->buffer, err);\n    if (iretCode!=OBIT_IO_OK) break;\n    /* How many */\n    outDesc->numVisBuff = in1Desc->numVisBuff;\n    firstVis = in1Desc->firstVis;\n\n    /* compatability check */\n    incompatible = in1Desc->numVisBuff!=in2Desc->numVisBuff;\n    if (incompatible) break;\n\n    /* Modify data */\n    for (i=0; i<in1Desc->numVisBuff; i++) { /* loop over visibilities */\n      /* compatability check - check time and baseline or antenna code */\n      indx = i*in1Desc->lrec ;\n      incompatible = \n\tinUV1->buffer[indx+in1Desc->iloct] !=inUV2->buffer[indx+in2Desc->iloct];\n      if (in1Desc->ilocb>=0) {\n\tincompatible = incompatible ||\n\t  inUV1->buffer[indx+in1Desc->ilocb] !=inUV2->buffer[indx+in2Desc->ilocb];\n      }\n      if (in1Desc->iloca1>=0) {\n\tincompatible = incompatible ||\n\t  inUV1->buffer[indx+in1Desc->iloca1]!=inUV2->buffer[indx+in2Desc->iloca1] ||\n\t  inUV1->buffer[indx+in1Desc->iloca2]!=inUV2->buffer[indx+in2Desc->iloca2];\n      }\n      if (incompatible) break;\n\n      indx += in1Desc->nrparm;\n      for (j=0; j<in1Desc->ncorr; j++) { /* loop over correlations */\n\t/* subtract */\n\tif ((inUV1->buffer[indx+2]>0.0) && (inUV2->buffer[indx+2]>0.0)) {\n\t  inUV1->buffer[indx]   -= inUV2->buffer[indx];\n\t  inUV1->buffer[indx+1] -= inUV2->buffer[indx+1];\n\t  /* this blanks poln data } else {\n\t    inUV1->buffer[indx]   = 0.0;\n\t    inUV1->buffer[indx+1] = 0.0;\n\t    inUV1->buffer[indx+2] = 0.0;*/\n\t}\n\tindx += in1Desc->inaxes[0];\n      } /* end loop over correlations */\n      if (incompatible) break;\n    } /* end loop over visibilities */\n    \n    /* Write */\n    oretCode = ObitUVWrite (outUV, inUV1->buffer, err);\n    /* suppress vis number update if rewriting the same file */\n    if (same) {\n      outUV->myDesc->firstVis = firstVis;\n      ((ObitUVDesc*)(outUV->myIO->myDesc))->firstVis = firstVis;\n    }\n } /* end loop processing data */\n  \n  /* Check for incompatibility */\n  if (incompatible) {\n    Obit_log_error(err, OBIT_Error,\"%s inUV1 and inUV2 have incompatible contents\",\n\t\t   routine);\n    return;\n  }\n    \n  /* check for errors */\n  if ((iretCode > OBIT_IO_EOF) || (oretCode > OBIT_IO_EOF) ||\n      (err->error)) /* add traceback,return */\n    Obit_traceback_msg (err, routine,inUV1->name);\n    \n  /* unset output buffer (may be multiply deallocated ;'{ ) */\n  outUV->buffer = NULL;\n  outUV->bufferSize = 0;\n  \n  /* Reset passAll */\n  btemp = FALSE;\n  dim[0] = dim[1] = dim[2] = 1;\n  ObitInfoListAlwaysPut(inUV1->info, \"passAll\", OBIT_bool, dim, &btemp);\n  ObitInfoListAlwaysPut(inUV2->info, \"passAll\", OBIT_bool, dim, &btemp);\n  \n  /* close files */\n  iretCode = ObitUVClose (inUV1, err);\n  if (err->error) Obit_traceback_msg (err, routine, inUV1->name);\n  \n  iretCode = ObitUVClose (inUV2, err);\n  if (err->error) Obit_traceback_msg (err, routine, inUV2->name);\n  \n  oretCode = ObitUVClose (outUV, err);\n  if (err->error) Obit_traceback_msg (err, routine, outUV->name);\n  \n} /* end ObitUVUtilVisSub */\n\n/**\n * Subtract the 1st visibility in one ObitUV from those in another\n * outUV = inUV1[*] - inUV2[0]\n * \\param inUV1    First input uv data, no calibration/selection\n * \\param inUV2    Second input uv data, calibration/selection allowed\n *                 inUV2 should have the same structure, only the 1st\n *                 visibility used and subtracted from all in inUV1\n * \\param outUV    Previously defined output, may be the same as inUV1\n * \\param err      Error stack, returns on error\n */\nvoid ObitUVUtilVisSub1 (ObitUV *inUV1, ObitUV *inUV2, ObitUV *outUV, \n\t\t        ObitErr *err)\n{\n  ObitIOCode iretCode, oretCode;\n  gchar *exclude[]={\"AIPS CL\",\"AIPS SN\",\"AIPS FG\",\"AIPS CQ\",\"AIPS WX\",\n\t\t    \"AIPS AT\",\"AIPS CT\",\"AIPS OB\",\"AIPS IM\",\"AIPS MC\",\n\t\t    \"AIPS PC\",\"AIPS NX\",\"AIPS TY\",\"AIPS GC\",\"AIPS HI\",\n\t\t    \"AIPS PL\",\"AIPS NI\",\"AIPS SY\",\"AIPS PT\",\"AIPS OT\",\n\t\t    NULL};\n  gchar *sourceInclude[] = {\"AIPS SU\", NULL};\n  olong i, j, indx, kndx, firstVis;\n  ObitInfoType type;\n  gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};\n  olong NPIO;\n  gboolean incompatible, same, doCalSelect, btemp;\n  ObitUVDesc *in1Desc, *in2Desc, *outDesc;\n  ObitIOAccess access;\n  gchar *today=NULL;\n  gchar *routine = \"ObitUVUtilVisSub1\";\n\n  /* error checks */\n  g_assert (ObitErrIsA(err));\n  if (err->error) return;\n  g_assert (ObitUVIsA(inUV1));\n  g_assert (ObitUVIsA(inUV2));\n  g_assert (ObitUVIsA(outUV));\n\n  /* Are input1 and output the same file? */\n  same = ObitUVSame(inUV1, outUV, err);\n  if (err->error) Obit_traceback_msg (err, routine, inUV1->name);\n\n  /* test open to fully instantiate input and see if it's OK */\n  iretCode = ObitUVOpen (inUV1, OBIT_IO_ReadWrite, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error)) /* add traceback,return */\n    Obit_traceback_msg (err, routine,inUV1->name);\n\n  /* copy Descriptor */\n  outUV->myDesc = ObitUVDescCopy(inUV1->myDesc, outUV->myDesc, err);\n\n  /* Creation date today */\n  today = ObitToday();\n  strncpy (outUV->myDesc->date, today, UVLEN_VALUE-1);\n  if (today) g_free(today);\n \n  /* use same data buffer on input and output.\n     If multiple passes are made the input files will be closed\n     which deallocates the buffer, use output buffer.\n     so free input buffer */\n  if (!same) {\n    /* use same data buffer on input 1 and output \n       so don't assign buffer for output */\n    if (outUV->buffer) ObitIOFreeBuffer(outUV->buffer); /* free existing */\n    outUV->buffer = NULL;\n    outUV->bufferSize = -1;\n  }\n\n   /* Copy number of records per IO to second input */\n  ObitInfoListGet (inUV1->info, \"nVisPIO\", &type, dim,  (gpointer)&NPIO, err);\n  ObitInfoListPut (inUV2->info, \"nVisPIO\",  type, dim,  (gpointer)&NPIO, err);\n  if (err->error) Obit_traceback_msg (err, routine, inUV1->name);\n\n  /* Selection of second input? */\n  doCalSelect = FALSE;\n  ObitInfoListGetTest(inUV2->info, \"doCalSelect\", &type, dim, &doCalSelect);\n  if (doCalSelect) access = OBIT_IO_ReadCal;\n  else access = OBIT_IO_ReadOnly;\n\n  /* Open second input */\n  iretCode = ObitUVOpen (inUV2, access, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error)) \n    Obit_traceback_msg (err, routine,inUV2->name);\n\n  /* Get input descriptors */\n  in1Desc = inUV1->myDesc;\n  in2Desc = inUV2->myDesc;\n\n  /* Check compatability between inUV1, inUV2 */\n  incompatible = (in1Desc->ncorr!=in2Desc->ncorr);\n  incompatible = incompatible || (in1Desc->jlocs!=in2Desc->jlocs);\n  incompatible = incompatible || (in1Desc->jlocf!=in2Desc->jlocf);\n  incompatible = incompatible || (in1Desc->jlocif!=in2Desc->jlocif);\n  incompatible = incompatible || (in1Desc->ilocb!=in2Desc->ilocb);\n  if (incompatible) {\n     Obit_log_error(err, OBIT_Error,\"%s inUV1 and inUV2 have incompatible structures\",\n\t\t   routine);\n      return ;\n  }\n\n  /* Look at all data */\n  btemp = TRUE;\n  dim[0] = dim[1] = dim[2] = 1;\n  ObitInfoListAlwaysPut(inUV1->info, \"passAll\", OBIT_bool, dim, &btemp);\n  ObitInfoListAlwaysPut(inUV2->info, \"passAll\", OBIT_bool, dim, &btemp);\n  \n  /* test open output */\n  oretCode = ObitUVOpen (outUV, OBIT_IO_WriteOnly, err);\n  /* If this didn't work try OBIT_IO_ReadWrite */\n  if ((oretCode!=OBIT_IO_OK) || (err->error)) {\n    ObitErrClear(err);\n    oretCode = ObitUVOpen (outUV, OBIT_IO_ReadWrite, err);\n  }\n  /* if it didn't work bail out */\n  if ((oretCode!=OBIT_IO_OK) || (err->error)) {\n    /* unset output buffer (may be multiply deallocated) */\n    outUV->buffer = NULL;\n    outUV->bufferSize = 0;\n    Obit_traceback_msg (err, routine, outUV->name);\n  }\n\n  /* Copy tables before data if in1 and out are not the same */\n  if (!ObitUVSame (inUV1, outUV, err)) {\n    iretCode = ObitUVCopyTables (inUV1, outUV, exclude, NULL, err);\n    /* If multisource out then copy SU table, multiple sources selected or\n       sources deselected suggest MS out */\n    if ((inUV1->mySel->numberSourcesList>1) || (!inUV1->mySel->selectSources))\n      iretCode = ObitUVCopyTables (inUV1, outUV, NULL, sourceInclude, err);\n    if (err->error) {\n      outUV->buffer = NULL;\n      outUV->bufferSize = 0;\n      Obit_traceback_msg (err, routine, inUV1->name);\n    }\n  }\n  if (err->error) Obit_traceback_msg (err, routine, inUV1->name);\n\n  /* reset to beginning of uv data */\n  iretCode = ObitUVIOSet (inUV1, err);\n  oretCode = ObitUVIOSet (outUV, err);\n  if (err->error) Obit_traceback_msg (err, routine,inUV1->name);\n\n  /* Close and reopen input to init calibration which will have been disturbed \n     by the table copy */\n  iretCode = ObitUVClose (inUV1, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error))\n    Obit_traceback_msg (err, routine,inUV1->name);\n  iretCode = ObitUVOpen (inUV1, OBIT_IO_ReadWrite, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error))\n    Obit_traceback_msg (err, routine,inUV1->name);\n  outUV->buffer = inUV1->buffer;\n\n  outDesc = outUV->myDesc;   /* Get output descriptor */\n\n  /* Read vis from second input */\n  if (doCalSelect) iretCode = ObitUVReadSelect (inUV2, inUV2->buffer, err);\n  else iretCode = ObitUVRead (inUV2, inUV2->buffer, err);\n  if (err->error) Obit_traceback_msg (err, routine,inUV2->name);\n\n  /* we're in business, subtract */\n  while ((iretCode==OBIT_IO_OK) && (oretCode==OBIT_IO_OK)) {\n    /* Read first input */\n    iretCode = ObitUVRead (inUV1, inUV1->buffer, err);\n    if (iretCode!=OBIT_IO_OK) break;\n    /* How many */\n    outDesc->numVisBuff = in1Desc->numVisBuff;\n    firstVis = in1Desc->firstVis;\n\n    /* Modify data */\n    for (i=0; i<in1Desc->numVisBuff; i++) { /* loop over visibilities */\n      indx = i*in1Desc->lrec+ in1Desc->nrparm;\n      kndx = in2Desc->nrparm;\n      for (j=0; j<in1Desc->ncorr; j++) { /* loop over correlations */\n\t/* subtract */\n\tif ((inUV1->buffer[indx+2]>0.0) && (inUV2->buffer[kndx+2]>0.0)) {\n\t  inUV1->buffer[indx]   -= inUV2->buffer[kndx];\n\t  inUV1->buffer[indx+1] -= inUV2->buffer[kndx+1];\n\t  /* this blanks poln data } else {\n\t    inUV1->buffer[indx]   = 0.0;\n\t    inUV1->buffer[indx+1] = 0.0;\n\t    inUV1->buffer[indx+2] = 0.0;*/\n\t}\n\tindx += in1Desc->inaxes[0];\n\tkndx += in2Desc->inaxes[0];\n      } /* end loop over correlations */\n      if (incompatible) break;\n    } /* end loop over visibilities */\n    \n    /* Write */\n    oretCode = ObitUVWrite (outUV, inUV1->buffer, err);\n    /* suppress vis number update if rewriting the same file */\n    if (same) {\n      outUV->myDesc->firstVis = firstVis;\n      ((ObitUVDesc*)(outUV->myIO->myDesc))->firstVis = firstVis;\n    }\n } /* end loop processing data */\n  \n  /* Check for incompatibility */\n  if (incompatible) {\n    Obit_log_error(err, OBIT_Error,\"%s inUV1 and inUV2 have incompatible contents\",\n\t\t   routine);\n    return;\n  }\n    \n  /* check for errors */\n  if ((iretCode > OBIT_IO_EOF) || (oretCode > OBIT_IO_EOF) ||\n      (err->error)) /* add traceback,return */\n    Obit_traceback_msg (err, routine,inUV1->name);\n    \n  /* unset output buffer (may be multiply deallocated ;'{ ) */\n  outUV->buffer = NULL;\n  outUV->bufferSize = 0;\n  \n  /* Reset passAll */\n  btemp = FALSE;\n  dim[0] = dim[1] = dim[2] = 1;\n  ObitInfoListAlwaysPut(inUV1->info, \"passAll\", OBIT_bool, dim, &btemp);\n  ObitInfoListAlwaysPut(inUV2->info, \"passAll\", OBIT_bool, dim, &btemp);\n  \n  /* close files */\n  iretCode = ObitUVClose (inUV1, err);\n  if (err->error) Obit_traceback_msg (err, routine, inUV1->name);\n  \n  iretCode = ObitUVClose (inUV2, err);\n  if (err->error) Obit_traceback_msg (err, routine, inUV2->name);\n  \n  oretCode = ObitUVClose (outUV, err);\n  if (err->error) Obit_traceback_msg (err, routine, outUV->name);\n  \n} /* end ObitUVUtilVisSub1 */\n\n/**\n * Compare the visibilities in one ObitUV with those in another.\n * Return the RMS of the real and imaginary differences \n * divided by the amplitude of inUV2.\n * Only valid visibilities compared, zero amplitudes ignored.\n * \\param inUV1    Input uv data numerator, no calibration/selection\n *  Control parameter on info\n * \\li printRat OBIT_float (1) If given and >0.0 then tell about entries\n *              with a real or imaginary ratio > printRat\n * \\param inUV2    Input uv data denominator, no calibration/selection\n *                 inUV2 should have the same structure, no. vis etc\n *                 as inUV1.\n * \\param err      Error stack, returns if not empty.\n * \\return RMS of the real and imaginary differences /amplitude, \n *        -1 => no data compared or other error.\n */\nofloat ObitUVUtilVisCompare (ObitUV *inUV1, ObitUV *inUV2, ObitErr *err)\n{\n  ObitIOCode iretCode;\n  olong i, j, indx, jndx, vscnt;\n  ollong count, vNo;\n  ObitInfoType type;\n  gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};\n  olong NPIO;\n  ofloat amp, rms = -1.0, rrat, irat, printRat=-1.0;\n  odouble sum;\n  gboolean incompatible;\n  ObitUVDesc *in1Desc, *in2Desc;\n  gchar *routine = \"ObitUVUtilVisCompare\";\n\n  /* error checks */\n  g_assert (ObitErrIsA(err));\n  if (err->error) return rms;\n  g_assert (ObitUVIsA(inUV1));\n  g_assert (ObitUVIsA(inUV2));\n\n  /* Diagnostics? */\n  ObitInfoListGetTest(inUV1->info, \"printRat\", &type, dim, &printRat);\n\n  /* test open to fully instantiate input and see if it's OK */\n  iretCode = ObitUVOpen (inUV1, OBIT_IO_ReadWrite, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error))\n    Obit_traceback_val (err, routine,inUV1->name, rms);\n\n  /* Copy number of records per IO to second input */\n  ObitInfoListGet (inUV1->info, \"nVisPIO\", &type, dim,  (gpointer)&NPIO, err);\n  ObitInfoListPut (inUV2->info, \"nVisPIO\",  type, dim,  (gpointer)&NPIO, err);\n  if (err->error) Obit_traceback_val (err, routine, inUV1->name, rms);\n\n  /* Open second input */\n  iretCode = ObitUVOpen (inUV2, OBIT_IO_ReadWrite, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error)) \n    Obit_traceback_val (err, routine,inUV2->name, rms);\n\n  /* Get input descriptors */\n  in1Desc = inUV1->myDesc;\n  in2Desc = inUV2->myDesc;\n\n  /* Check compatability between inUV1, inUV2 */\n  incompatible = in1Desc->nvis!=in2Desc->nvis;\n  incompatible = incompatible || (in1Desc->ncorr!=in2Desc->ncorr);\n  incompatible = incompatible || (in1Desc->jlocs!=in2Desc->jlocs);\n  incompatible = incompatible || (in1Desc->jlocf!=in2Desc->jlocf);\n  incompatible = incompatible || (in1Desc->jlocif!=in2Desc->jlocif);\n  incompatible = incompatible || (in1Desc->ilocb!=in2Desc->ilocb);\n  if (incompatible) {\n     Obit_log_error(err, OBIT_Error,\"%s inUV1 and inUV2 have incompatible structures\",\n\t\t   routine);\n      return rms;\n }\n\n  /* we're in business, loop comparing */\n  count = 0;\n  vscnt = 0;\n  sum = 0.0;\n  while (iretCode==OBIT_IO_OK) {\n    /* Read first input */\n    iretCode = ObitUVRead (inUV1, inUV1->buffer, err);\n    if (iretCode!=OBIT_IO_OK) break;\n    /* Read second input */\n    iretCode = ObitUVRead (inUV2, inUV2->buffer, err);\n    if (iretCode!=OBIT_IO_OK) break;\n\n    /* compatability check */\n    incompatible = in1Desc->numVisBuff!=in2Desc->numVisBuff;\n    if (incompatible) break;\n\n    /* Compare data */\n    for (i=0; i<in1Desc->numVisBuff; i++) { /* loop over visibilities */\n      vscnt++;\n      /* compatability check - check time and baseline or antenna code */\n      indx = i*in1Desc->lrec ;\n      jndx = i*in2Desc->lrec ;\n      incompatible = \n\tinUV1->buffer[indx+in1Desc->iloct] !=inUV2->buffer[jndx+in2Desc->iloct];\n      if (in1Desc->ilocb>=0) {\n\tincompatible = incompatible ||\n\t  inUV1->buffer[indx+in1Desc->ilocb] !=inUV2->buffer[jndx+in2Desc->ilocb];\n      }\n      if (in1Desc->iloca1>=0) {\n\tincompatible = incompatible ||\n\t  inUV1->buffer[indx+in1Desc->iloca1]!=inUV2->buffer[jndx+in2Desc->iloca1] ||\n\t  inUV1->buffer[indx+in1Desc->iloca2]!=inUV2->buffer[jndx+in2Desc->iloca2];\n      }\n      if (incompatible) {\n\tvNo = indx+in1Desc->firstVis + i;  /* Which visibility */\n\tif (inUV1->buffer[indx+in1Desc->iloct]!=inUV2->buffer[jndx+in2Desc->iloct])\n\t  Obit_log_error(err, OBIT_Error, \"Incompatible Times %f != %f @ vis %ld\", \n\t\t\t inUV1->buffer[indx+in1Desc->iloct], inUV2->buffer[jndx+in2Desc->iloct], vNo);\n\tif ((in1Desc->ilocb>=0) && (inUV1->buffer[indx+in1Desc->ilocb]!=inUV2->buffer[jndx+in2Desc->ilocb]))\n\t  Obit_log_error(err, OBIT_Error, \"Incompatible Baselines %f != %f @ vis %ld\", \n\t\t\t inUV1->buffer[indx+in1Desc->ilocb], inUV2->buffer[jndx+in2Desc->ilocb], vNo);\n\tif ((in1Desc->iloca2>=0) && (inUV1->buffer[indx+in1Desc->iloca1]!=inUV2->buffer[jndx+in2Desc->iloca1]))\n\t  Obit_log_error(err, OBIT_Error, \"Incompatible Antenna 1 %f != %f @ vis %ld\", \n\t\t\t inUV1->buffer[indx+in1Desc->ilocb], inUV2->buffer[jndx+in2Desc->ilocb], vNo);\n\tif ((in1Desc->iloca2>=0) && (inUV1->buffer[indx+in1Desc->iloca2]!=inUV2->buffer[jndx+in2Desc->iloca2]))\n\t  Obit_log_error(err, OBIT_Error, \"Incompatible Antenna 2 %f != %f @ vis %ld\", \n\t\t\t inUV1->buffer[indx+in1Desc->ilocb], inUV2->buffer[jndx+in2Desc->ilocb], vNo);\n\tbreak;\n      }\n\n      indx += in1Desc->nrparm;\n      jndx += in2Desc->nrparm;\n      for (j=0; j<in1Desc->ncorr; j++) { /* loop over correlations */\n\t/* Statistics  */\n\tamp = inUV2->buffer[jndx]*inUV2->buffer[jndx] + \n\t  inUV2->buffer[jndx+1]*inUV2->buffer[jndx+1];\n\tif ((inUV1->buffer[indx+2]>0.0) && (inUV2->buffer[indx+2]>0.0) && (amp>0.0)) {\n\t  amp = sqrt(amp);\n\t  rrat = ((inUV1->buffer[indx] - inUV2->buffer[jndx]) *\n\t\t  (inUV1->buffer[indx] - inUV2->buffer[jndx])) / amp;\n\t  irat = ((inUV1->buffer[indx+1] - inUV2->buffer[jndx+1]) *\n\t\t  (inUV1->buffer[indx+1] - inUV2->buffer[jndx+1])) / amp;\n\t  sum += rrat + irat;\n\t  count += 2;\n\t  /* Diagnostics */\n\t  if ((printRat>0.0) && ((rrat>printRat) ||  (irat>printRat))) {\n\t    Obit_log_error(err, OBIT_InfoWarn, \n\t\t\t   \"High ratio vis %d corr %d ratio %f %f amp %f vis %f %f - %f %f\",\n\t\t\t   vscnt, j+1, rrat, irat, amp, inUV1->buffer[indx], inUV1->buffer[indx+1],\n\t\t\t   inUV2->buffer[jndx], inUV2->buffer[jndx+1]);\n\t  }\n\t}\n\tindx += in1Desc->inaxes[0];\n\tjndx += in2Desc->inaxes[0];\n      } /* end loop over correlations */\n      if (incompatible) break;\n    } /* end loop over visibilities */\n  } /* end loop processing data */\n  \n  /* Check for incompatibility */\n  if (incompatible) {\n    Obit_log_error(err, OBIT_Error,\"%s inUV1 and inUV2 have incompatible contents\",\n\t\t   routine);\n    return rms;\n  }\n    \n  /* check for errors */\n  if ((iretCode > OBIT_IO_EOF) || (err->error))\n    Obit_traceback_val (err, routine,inUV1->name, rms);\n    \n  /* close files */\n  iretCode = ObitUVClose (inUV1, err);\n  if (err->error) Obit_traceback_val (err, routine, inUV1->name, rms);\n  \n  iretCode = ObitUVClose (inUV2, err);\n  if (err->error) Obit_traceback_val (err, routine, inUV2->name, rms);\n\n  /* Get RMS to return */\n  if (count>0) rms = sqrt(sum / count);\n  else rms = -1.0;\n\n  return rms;\n  \n} /* end ObitUVUtilVisCompare */\n\n/**\n * Reads the UV and rewrites its Index (AIPS NX) table\n * \\param inUV    Input UV data. \n * Control parameters are on the info member.\n * \\li \"maxScan\"  OBIT_float (1,1,1) max. scan time, min. [def LARGE]\n * \\li \"maxGap\"   OBIT_float (1,1,1) max. time gap in scan, min. [def LARGE]\n * \\param err      Error stack, returns if not empty.\n */\nvoid ObitUVUtilIndex (ObitUV *inUV, ObitErr *err)\n{ \n  ObitIOCode retCode;\n  ObitTableNX* table;\n  ObitTableNXRow* row=NULL;\n  gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};\n  ObitInfoType type;\n  olong num, i, iRow, ver, startVis=1, curVis, itemp, jtemp;\n  olong suba, lastSubA=0, source, lastSource=0, fqid, lastFQID=0;\n  ofloat maxScan, maxGap, *vis;\n  odouble startTime=0.0, endTime=0.0, lastTime = -1.0e20; \n  gchar *routine = \"ObitUVUtilIndex\";\n\n  /* error checks */\n  g_assert (ObitErrIsA(err));\n  if (err->error) return;\n  g_assert (ObitUVIsA(inUV));\n\n  /* Get maximum scan length */\n  maxScan = 1.0e20;\n  ObitInfoListGetTest(inUV->info, \"maxScan\", &type, dim, &maxScan);\n  maxScan /= 1440.0; /* to days */\n\n  /* Get maximum scan gap */\n  maxGap = 1.0e20;\n  ObitInfoListGetTest(inUV->info, \"maxGap\", &type, dim, &maxGap);\n  maxGap /= 1440.0; /* to days */\n\n  /* Open UV */\n  inUV->bufferSize = MAX (0, inUV->bufferSize); /* Need buffer */\n  retCode = ObitUVOpen (inUV, OBIT_IO_ReadWrite, err);\n  if ((retCode != OBIT_IO_OK) || (err->error>0)) \n    Obit_traceback_msg (err, routine, inUV->name);\n  lastSubA   = -1000; /* initialize subarray number */\n  lastFQID   = -1000; /* initialize FQ Id */\n  lastSource = -1000; /* initialize source number */\n  curVis     = 0;     /* visibility counter */\n\n  /* create Index table object */\n  ver = 1;\n  table = newObitTableNXValue (\"Index table\", (ObitData*)inUV, &ver, \n\t\t\t       OBIT_IO_ReadWrite, err);\n  if (err->error) Obit_traceback_msg (err, routine, inUV->name);\n  \n  /* Clear existing rows */\n  ObitTableClearRows ((ObitTable*)table, err);\n  if (err->error) goto cleanup;\n\n  /* Open Index table */\n  if ((ObitTableNXOpen (table, OBIT_IO_WriteOnly, err)\n       != OBIT_IO_OK) || (err->error)) goto cleanup;\n\n  /* Create Index Row */\n  row = newObitTableNXRow (table);\n\n  /* initialize row */\n  row->SourID   = 0;\n  row->SubA     = 0;\n  row->Time     = 0.0;\n  row->TimeI    = 0.0;\n  row->StartVis = -1;\n  row->EndVis   = -1;\n  row->FreqID   = 0;\n  fqid          = 1;\n  source        = 1;\n\n  /* attach to table buffer */\n  ObitTableNXSetRow (table, row, err);\n  if (err->error)  goto cleanup;\n\n  /* Write at beginning of UVIndex Table */\n  iRow = 0;\n  table->myDesc->nrow = 0; /* ignore any previous entries */\n\n  /* Loop over UV */\n  while (retCode==OBIT_IO_OK) {\n    retCode = ObitUVRead (inUV, inUV->buffer, err);\n    /*if (retCode!=OBIT_IO_OK) fprintf(stderr, \"retcode=%d\\n\", retCode);*/\n    /* EOF is OK */\n    if (retCode==OBIT_IO_EOF) ObitErrClear(err);\n    if (retCode!=OBIT_IO_OK) break;\n    if (err->error) goto cleanup;\n\n    /* How many */\n    num = inUV->myDesc->numVisBuff;\n    \n    /* Visibility pointer */\n    vis = inUV->buffer;\n\n    /* initialize on first visibility */\n    if (curVis<=0) {\n      startVis   = 1;\n      startTime  = vis[inUV->myDesc->iloct];\n      lastTime   = vis[inUV->myDesc->iloct];\n    }\n    \n    /* Loop over buffer */\n    for (i=0; i<num; i++) {\n      curVis++; /* Current UV visibility number */\n\n      /* require some time change for further checks */\n      if (vis[inUV->myDesc->iloct]==lastTime) goto endloop;\n      /* Subarray number */\n      ObitUVDescGetAnts(inUV->myDesc, vis, &itemp, &jtemp, &suba);\n      if (inUV->myDesc->ilocfq>=0) \n\tfqid   = vis[inUV->myDesc->ilocfq] + 0.5;  /* Which FQ Id */\n      if (inUV->myDesc->ilocsu>=0) \n\tsource = vis[inUV->myDesc->ilocsu]  + 0.5; /* Source number */\n       /* Initialize? */\n      if (lastFQID<=0)   lastFQID   = fqid;\n      if (lastSubA<=0)   lastSubA   = suba;\n      if (lastSource<=0) lastSource = source;\n      \n      \n      /* New scan - change of source, fqid, or reach time limit */\n      if (((suba!=lastSubA)     && (lastSubA>0)) || \n\t  ((source!=lastSource) && (lastSource>0)) ||\n\t  ((fqid!=lastFQID)     && (lastFQID>0)) ||\n\t  ((vis[inUV->myDesc->iloct]-lastTime) > maxGap) ||\n\t  ((vis[inUV->myDesc->iloct]-startTime)>maxScan))\n\t{  /* Write index */\n\n\t/* Fill index record */\n\tif (lastSource>0) row->SourID   = lastSource;\n\tif (lastFQID>0)   row->FreqID   = lastFQID;\n\tif (lastSubA>0)   row->SubA     = lastSubA;\n\trow->Time     = 0.5 * (startTime + endTime);\n\trow->TimeI    = (endTime - startTime);\n\trow->StartVis = startVis;\n\trow->EndVis   = curVis-1;\n\t\n\t/* Write Index table */\n\tiRow++;\n\tif ((ObitTableNXWriteRow (table, iRow, row, err)\n\t     != OBIT_IO_OK) || (err->error>0)) goto cleanup;\n\n\t/* Initialize next suba */\n\tlastSubA   = suba;\n\tlastFQID   = fqid;\n\tlastSource = source;\n\tstartVis   = curVis;\n\tstartTime  = vis[inUV->myDesc->iloct];\n\tendTime    = vis[inUV->myDesc->iloct];\n\t\n      } /* end of if new scan */\n\n      endloop: endTime    = vis[inUV->myDesc->iloct];   /* potential end time */\n      lastTime   = vis[inUV->myDesc->iloct];   /* time of last vis */\n      vis += inUV->myDesc->lrec;     /* Update data visibility pointer */\n    } /* end loop over buffer */\n\n  } /* End loop over UV */\n\n  /* Last Scan */\n  if (lastSource>0) row->SourID   = lastSource;\n  if (lastFQID>0)   row->FreqID   = lastFQID;\n  if (lastSubA>0)   row->SubA     = lastSubA;\n  row->Time     = 0.5 * (startTime + endTime);\n  row->TimeI    = (endTime - startTime);\n  row->StartVis = startVis;\n  row->EndVis   = curVis;\n  \n  /* Write Index table */\n  iRow++;\n  if ((ObitTableNXWriteRow (table, iRow, row, err)\n       != OBIT_IO_OK) || (err->error>0)) goto cleanup; \n  \n  /* Close Index table */\n  cleanup: if ((ObitTableNXClose (table, err) \n       != OBIT_IO_OK) || (err->error>0)) \n    Obit_traceback_msg (err, routine, table->name);\n\n  /* Cleanup */\n  row = ObitTableNXRowUnref(row);\n  table = ObitTableNXUnref(table);\n  if (err->error) Obit_traceback_msg (err, routine, inUV->name);\n\n  /* Close UV */\n  retCode = ObitUVClose (inUV, err);\n  if ((retCode != OBIT_IO_OK) || (err->error>0)) \n    Obit_traceback_msg (err, routine, inUV->name);\n} /* end ObitUVUtilIndex */\n\n\n/**\n * Return a SourceList containing selected sources\n * Uses following criteria:\n * \\li initially select all source in SU table\n *     If no SU table, a single entry is returned.\n * \\li Any explicit selection in Sources parameter in UV data selector\n * \\li selection by CalCode\n * \\li selection to exclude any entries marked done in the PS table\n *     if Infolist item 'doPS' is True. \n * \\li if time range given and an NX table exists, only select \n *     sources with data  in this timerange.\n * \\param inUV   UV data with all selection criteria, other controls:\n * \\li \"doPS\" OBIT_bool (1,1,1) If true and PS 1 exists, exclude [def False]\n * \\li \"souCode\" OBIT_string (4,1,1) Source Cal code desired, '    ' => any code selected\n *                                   '*   ' => any non blank code (calibrators only)\n *                                   '-CAL' => blank codes only (no calibrators)\n *                                   def = '    '\n *   any sources marked done in PS table 1.\n * \\param *err   ObitErr error stack.\n * \\return requested ObitSourceList\n */\nObitSourceList* ObitUVUtilWhichSources (ObitUV *inUV, ObitErr *err) \n{\n  olong iver, i, j, count;\n  ObitTableSU *SUTable=NULL;\n  ObitTableNX *NXTable=NULL;\n  ObitTablePS *PSTable=NULL;\n  ObitSourceList *out=NULL, *tsList=NULL;\n  ObitInfoType type;\n  olong theRow;\n  gint32 dim[MAXINFOELEMDIM];\n  gboolean want, allCal, allNCal, doTime, doPS, *good=NULL;\n  gchar souCode[5];\n  gchar *routine = \"ObitUVUtilWhichSources\";\n\n  /* Full Source list */\n  iver = 1;\n  SUTable = newObitTableSUValue (inUV->name, (ObitData*)inUV, &iver, \n\t\t\t\t OBIT_IO_ReadOnly, 0, err);\n  if (err->error) Obit_traceback_val (err, routine, inUV->name, out);\n  if (SUTable) {\n    tsList = ObitTableSUGetList (SUTable, err);\n    if (err->error) Obit_traceback_val (err, routine, inUV->name, out);\n  } else {  /* Use position /name from header */\n    out = ObitSourceListCreate (\"SList\", 1);\n    strncpy (out->SUlist[0]->SourceName, inUV->myDesc->object, MIN(20,UVLEN_VALUE));\n    out->SUlist[0]->equinox = inUV->myDesc->equinox;\n    out->SUlist[0]->RAMean  = inUV->myDesc->crval[inUV->myDesc->jlocr];\n    out->SUlist[0]->DecMean = inUV->myDesc->crval[inUV->myDesc->jlocd];\n    /* Compute apparent position */\n    ObitPrecessUVJPrecessApp (inUV->myDesc, out->SUlist[0]);\n    return out;\n  }\n\n  SUTable = ObitTableSUUnref(SUTable);   /* Done with table */\n\n  /* check selection and calcode */\n  souCode[0] = souCode[1] = souCode[2] = souCode[3] = ' ';souCode[4] = 0;\n  ObitInfoListGetTest(inUV->info, \"souCode\", &type, dim, souCode);\n  doPS = FALSE;\n  ObitInfoListGetTest(inUV->info, \"doPS\",    &type, dim, &doPS);\n  allCal  = !strncmp (souCode, \"-CAL\", 4); /* all calibrators */\n  allNCal = !strncmp (souCode, \"*   \", 4); /* All non calibrators */\n\n  /* Need other tables? */\n  if (doPS) {\n    iver = 1;\n    PSTable = newObitTablePSValue (inUV->name, (ObitData*)inUV, &iver, \n\t\t\t\t   OBIT_IO_ReadOnly, err);\n    if (!PSTable) doPS = FALSE;\n    if (doPS) ObitTablePSOpen (PSTable, OBIT_IO_ReadOnly, err);\n  }\n\n  doTime = TRUE;\n  if (doTime) {\n    iver = 1;\n    NXTable = newObitTableNXValue (inUV->name, (ObitData*)inUV, &iver, \n\t\t\t\t   OBIT_IO_ReadOnly, err);\n    if (!NXTable) doTime = FALSE;\n    if (doTime) ObitTableNXOpen (NXTable, OBIT_IO_ReadOnly, err);\n  }\n\n  /* Keep track of the good ones */\n  good = g_malloc0(tsList->number*sizeof(gboolean));\n  for (i=0; i<tsList->number; i++) good[i] = TRUE;\n  \n  /* Loop over list */\n  for (i=0; i<tsList->number; i++) {\n    /* Explicitly stated */\n    want = ObitUVSelWantSour(inUV->mySel, tsList->SUlist[i]->SourID);\n    \n    if (allCal || allNCal) {\n      /* Calibrator/non calibrator */\n      want = want  &&\n\t((allCal  && !strncmp(tsList->SUlist[i]->CalCode, \"    \", 4)) ||\n\t (allNCal &&  strncmp(tsList->SUlist[i]->CalCode, \"    \", 4)));\n    }\n    \n    /* Timerange */\n    if (doTime) {\n      want = want && \n\tObitTableNXWantSour (NXTable, tsList->SUlist[i]->SourID,\n\t\t\t     inUV->mySel->timeRange, err);\n    }\n    if (err->error) Obit_traceback_val (err, routine, inUV->name, out);\n    \n    /* Already done in PS table? */\n    if (doPS) {\n      want = want && \n\tObitTablePSWantSour (PSTable, tsList->SUlist[i]->SourceName, \n\t\t\t     &theRow, err);\n    }\n    if (err->error) Obit_traceback_val (err, routine, inUV->name, out);\n    \n    /* Want this one? */\n    if (!want) good[i] = FALSE;\n  } /* End loop over list */\n\n  /* Close tables */\n  if (doPS) ObitTablePSClose (PSTable,  err);\n  if (doTime) ObitTableNXClose (NXTable, err);\n  if (NXTable) NXTable = ObitTableNXUnref(NXTable);   /* Done with table */\n   if (PSTable) PSTable = ObitTablePSUnref(PSTable);  /* Done with table */\n  \n  \n  /* create output with only valid entries \n     Count valid */\n  count = 0;\n  for (i=0; i<tsList->number; i++) if (good[i]) count++;\n  out = ObitSourceListCreate (\"Desired source list\", count);\n  \n  /* Copy */\n  j = 0;\n  for (i=0; i<tsList->number; i++) {\n    if (good[i]) {\n      out->SUlist[j] = ObitSourceCopy(tsList->SUlist[i], out->SUlist[j], err);\n      j++;\n    }\n  }\n  \n   tsList =  ObitSourceListUnref (tsList);  /* free old */\n  if (good) g_free(good);\n  return out;\n} /* end ObitUVUtilWhichSources */\n\n/**\n * Hanning smooth the data inObitUV.\n * \\param inUV     Input uv data to average, \n *                 Any request for calibration, editing and selection honored\n * Control parameters are on the info member.\n * \\li \"doDescm\"  OBIT_bool (1,1,1) Descimate data after Hanning [def TRUE]\n *              \n * \\param scratch  True if scratch file desired, will be same type as inUV.\n * \\param outUV    If not scratch, then the previously defined output file\n *                 May be NULL for scratch only\n *                 If it exists and scratch, it will be Unrefed\n * \\param err      Error stack, returns if not empty.\n * \\return the frequency averaged ObitUV.\n */\nObitUV* ObitUVUtilHann (ObitUV *inUV, gboolean scratch, ObitUV *outUV, \n\t\t\tObitErr *err)\n{\n  ObitIOCode iretCode, oretCode;\n  gboolean doCalSelect, doDescm;\n  gchar *exclude[]={\"AIPS CL\", \"AIPS SN\", \"AIPS FG\", \"AIPS CQ\", \"AIPS WX\",\n\t\t    \"AIPS AT\", \"AIPS CT\", \"AIPS OB\", \"AIPS IM\", \"AIPS MC\",\n\t\t    \"AIPS PC\", \"AIPS NX\", \"AIPS TY\", \"AIPS GC\", \"AIPS HI\",\n\t\t    \"AIPS PL\", \"AIPS NI\", \"AIPS BP\", \"AIPS OF\", \"AIPS PS\",\n\t\t    \"AIPS FQ\", \"AIPS SU\", \"AIPS AN\", \"AIPS PD\", \"AIPS OT\",\n\t\t    NULL};\n  gchar *sourceInclude[] = {\"AIPS SU\", NULL};\n  olong NumChAvg, i, j, indx, jndx;\n  ObitInfoType type;\n  gint32 dim[MAXINFOELEMDIM];\n  ObitIOAccess access;\n  ObitUVDesc *inDesc, *outDesc;\n  gchar *today=NULL;\n  ofloat *work=NULL, scale;\n  gchar *routine = \"ObitUVUtilHann\";\n \n  /* error checks */\n  if (err->error) return outUV;\n  g_assert (ObitUVIsA(inUV));\n  if (!scratch && (outUV==NULL)) {\n    Obit_log_error(err, OBIT_Error,\"%s Output MUST be defined for non scratch files\",\n\t\t   routine);\n      return outUV;\n  }\n\n  /* Selection/calibration/editing of input? */\n  doCalSelect = FALSE;\n  ObitInfoListGetTest(inUV->info, \"doCalSelect\", &type, (gint32*)dim, &doCalSelect);\n  if (doCalSelect) access = OBIT_IO_ReadCal;\n  else access = OBIT_IO_ReadOnly;\n\n  /* test open to fully instantiate input and see if it's OK */\n  iretCode = ObitUVOpen (inUV, access, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error)) /* add traceback,return */\n    Obit_traceback_val (err, routine, inUV->name, outUV);\n\n  /* Create scratch? */\n  if (scratch) {\n    if (outUV) outUV = ObitUVUnref(outUV);\n    outUV = newObitUVScratch (inUV, err);\n  } else { /* non scratch output must exist - clone from inUV */\n    outUV->myDesc = ObitUVDescCopy (inUV->myDesc, outUV->myDesc, err);\n    /*ObitUVClone (inUV, outUV, err);*/\n  }\n  if (err->error) Obit_traceback_val (err, routine, inUV->name, inUV);\n\n  /* copy Descriptor */\n  outUV->myDesc = ObitUVDescCopy(inUV->myDesc, outUV->myDesc, err);\n \n  /* Descimate output? */\n  doDescm = TRUE;\n  ObitInfoListGetTest(inUV->info, \"doDescm\", &type, dim, &doDescm);\n\n  /* Effectively averaging 2 channels if doDescm */\n  if (doDescm)  NumChAvg = 2;\n  else          NumChAvg = 1;\n  dim[0] = dim[1] = dim[2] = dim[3] = dim[4] = 1;\n  ObitInfoListAlwaysPut(inUV->info, \"NumChAvg\", OBIT_long, dim, &NumChAvg);\n \n  /* Creation date today */\n  today = ObitToday();\n  strncpy (outUV->myDesc->date, today, UVLEN_VALUE-1);\n  if (today) g_free(today);\n  \n  /* Get descriptors */\n  inDesc  = inUV->myDesc;\n  outDesc = outUV->myDesc;\n\n  /* Create work array for averaging */\n  work = g_malloc(2*inDesc->lrec*sizeof(ofloat));\n\n  /* Modify descriptor for affects of averaging, get u,v,w scaling */\n  ObitUVGetFreq (inUV, err);   /* Make sure frequencies updated */\n  if (err->error) goto cleanup;\n  /* Update output Descriptor */\n  if (doDescm) {/* No descimate - basically moving up one (input) channel */\n    outDesc->crpix[outDesc->jlocf]  = 0.5+inDesc->crpix[inDesc->jlocf]/2.0;\n    outDesc->cdelt[outDesc->jlocf]  = inDesc->cdelt[inDesc->jlocf]*2;\n    outDesc->inaxes[outDesc->jlocf] = inDesc->inaxes[inDesc->jlocf]/2;\n  } else {  /* No descimate */\n    outDesc->crpix[outDesc->jlocf]  = inDesc->crpix[inDesc->jlocf];\n  }\n  scale = 1.0;  /* Haven't really changed the frequency */\n \n  /* If descimating, last channel incomplete - drop */\n  if (doDescm) outDesc->inaxes[outDesc->jlocf]--;\n\n  /* test open output */\n  oretCode = ObitUVOpen (outUV, OBIT_IO_WriteOnly, err);\n  /* If this didn't work try OBIT_IO_ReadWrite */\n  if ((oretCode!=OBIT_IO_OK) || (err->error)) {\n    ObitErrClear(err);\n    oretCode = ObitUVOpen (outUV, OBIT_IO_ReadWrite, err);\n  }\n  /* if it didn't work bail out */\n  if ((oretCode!=OBIT_IO_OK) || (err->error)) goto cleanup;\n\n  /* Copy tables before data */\n  iretCode = ObitUVCopyTables (inUV, outUV, exclude, NULL, err);\n  /* If multisource out then copy SU table, multiple sources selected or\n   sources deselected suggest MS out */\n  if ((inUV->mySel->numberSourcesList>1) || (!inUV->mySel->selectSources))\n  iretCode = ObitUVCopyTables (inUV, outUV, NULL, sourceInclude, err);\n  /* FQ table selection */\n  iretCode = ObitTableFQSelect (inUV, outUV, NULL, 0.0, err);\n  /* Correct FQ table for averaging \n     FQSel (outUV, NumChAvg, 1, err); done in FQSelect(?) */\n  if (err->error) goto cleanup;\n\n  /* reset to beginning of uv data */\n  iretCode = ObitIOSet (inUV->myIO,  inUV->info, err);\n  oretCode = ObitIOSet (outUV->myIO, outUV->info, err);\n  if (err->error) goto cleanup;\n\n  /* Close and reopen input to init calibration which will have been disturbed \n     by the table copy */\n  iretCode = ObitUVClose (inUV, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error)) goto cleanup;\n\n  iretCode = ObitUVOpen (inUV, access, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error)) goto cleanup;\n\n  /* we're in business, average data */\n  while ((iretCode==OBIT_IO_OK) && (oretCode==OBIT_IO_OK)) {\n    if (doCalSelect) iretCode = ObitUVReadSelect (inUV, inUV->buffer, err);\n    else iretCode = ObitUVRead (inUV, inUV->buffer, err);\n    if (iretCode!=OBIT_IO_OK) break;\n    /* How many */\n    outDesc->numVisBuff = inDesc->numVisBuff;\n\n    /* Modify data */\n    for (i=0; i<inDesc->numVisBuff; i++) { /* loop over visibilities */\n      /* Copy random parameters */\n      indx = i*inDesc->lrec;\n      jndx = i*outDesc->lrec;\n      for (j=0; j<inDesc->nrparm; j++) \n\toutUV->buffer[jndx+j] =  inUV->buffer[indx+j];\n\n      /* Scale u,v,w for new reference frequency */\n      outUV->buffer[jndx+outDesc->ilocu] *= scale;\n      outUV->buffer[jndx+outDesc->ilocv] *= scale;\n      outUV->buffer[jndx+outDesc->ilocw] *= scale;\n\n      /* Smooth data */\n      indx += inDesc->nrparm;\n      jndx += outDesc->nrparm;\n      /* Average data */\n      Hann (inUV->myDesc, outUV->myDesc, doDescm, \n\t    &inUV->buffer[indx], &outUV->buffer[jndx], work, err);\n      if (err->error) goto cleanup;\n    } /* end loop over visibilities */\n\n    /* Write */\n    oretCode = ObitUVWrite (outUV, outUV->buffer, err);\n    if (err->error) goto cleanup;\n  } /* end loop processing data */\n  \n  /* check for errors */\n  if ((iretCode > OBIT_IO_EOF) || (oretCode > OBIT_IO_EOF) ||\n      (err->error)) goto cleanup;\n\n  /* Cleanup */\n cleanup:\n  if (work)    g_free(work);    work    = NULL;\n  \n  /* close files */\n  iretCode = ObitUVClose (inUV, err);\n  oretCode = ObitUVClose (outUV, err);\n  if ((iretCode!=OBIT_IO_OK) || (oretCode!=OBIT_IO_OK) || (err->error))\n    Obit_traceback_val (err, routine, outUV->name, outUV);\n  \n  return outUV;\n} /* end ObitUVUtilHann */\n\n/**\n * Duplicate channels in input to output.\n * \\param inUV     Input uv data to average, \n *                 Any request for calibration, editing and selection honored\n * Control parameters are on the info member.\n * \\li \"unHann\"  OBIT_bool (1,1,1) Undo previous Hanning? [def FALSE]\n * \\li \"nBloat\"  OBIT_int  (1,1,1) Number of duplicates of each channel [def 2]\n *              \n * \\param scratch  True if scratch file desired, will be same type as inUV.\n * \\param outUV    If not scratch, then the previously defined output file\n *                 May be NULL for scratch only\n *                 If it exists and scratch, it will be Unrefed\n * \\param err      Error stack, returns if not empty.\n * \\return the frequency averaged ObitUV.\n */\nObitUV* ObitUVUtilBloat (ObitUV *inUV, gboolean scratch, ObitUV *outUV, \n\t\t\tObitErr *err)\n{\n  ObitIOCode iretCode, oretCode;\n  gboolean doCalSelect, unHann;\n  gchar *exclude[]={\"AIPS CL\", \"AIPS SN\", \"AIPS FG\", \"AIPS CQ\", \"AIPS WX\",\n\t\t    \"AIPS AT\", \"AIPS CT\", \"AIPS OB\", \"AIPS IM\", \"AIPS MC\",\n\t\t    \"AIPS PC\", \"AIPS NX\", \"AIPS TY\", \"AIPS GC\", \"AIPS HI\",\n\t\t    \"AIPS PL\", \"AIPS NI\", \"AIPS BP\", \"AIPS OF\", \"AIPS PS\",\n\t\t    \"AIPS FQ\", \"AIPS SU\", \"AIPS AN\", \"AIPS PD\", \"AIPS SY\",\n\t\t    \"AIPS PT\", \"AIPS OT\",\n\t\t    NULL};\n  gchar *sourceInclude[] = {\"AIPS SU\", NULL};\n  olong i, j, indx, jndx;\n  ObitInfoType type;\n  gint32 dim[MAXINFOELEMDIM];\n  ObitIOAccess access;\n  ObitUVDesc *inDesc, *outDesc;\n  gchar *today=NULL;\n  olong nBloat=2;\n  ofloat scale;\n  gchar *routine = \"ObitUVUtilBloat\";\n \n  /* error checks */\n  if (err->error) return outUV;\n  g_assert (ObitUVIsA(inUV));\n  if (!scratch && (outUV==NULL)) {\n    Obit_log_error(err, OBIT_Error,\"%s Output MUST be defined for non scratch files\",\n\t\t   routine);\n      return outUV;\n  }\n\n  /* Selection/calibration/editing of input? */\n  doCalSelect = FALSE;\n  ObitInfoListGetTest(inUV->info, \"doCalSelect\", &type, (gint32*)dim, &doCalSelect);\n  if (doCalSelect) access = OBIT_IO_ReadCal;\n  else access = OBIT_IO_ReadOnly;\n\n  /* test open to fully instantiate input and see if it's OK */\n  iretCode = ObitUVOpen (inUV, access, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error)) /* add traceback,return */\n    Obit_traceback_val (err, routine, inUV->name, outUV);\n\n  /* Create scratch? */\n  if (scratch) {\n    if (outUV) outUV = ObitUVUnref(outUV);\n    outUV = newObitUVScratch (inUV, err);\n  } else { /* non scratch output must exist - clone from inUV */\n    outUV->myDesc = ObitUVDescCopy (inUV->myDesc, outUV->myDesc, err);\n    /*ObitUVClone (inUV, outUV, err);*/\n  }\n  if (err->error) Obit_traceback_val (err, routine, inUV->name, inUV);\n\n  /* copy Descriptor */\n  outUV->myDesc = ObitUVDescCopy(inUV->myDesc, outUV->myDesc, err);\n \n  /* How much bloat output? */\n  nBloat = 2;\n  ObitInfoListGetTest(inUV->info, \"nBloat\", &type, dim, &nBloat);\n  unHann = FALSE;\n  ObitInfoListGetTest(inUV->info, \"unHann\", &type, dim, &unHann);\n  if (unHann) nBloat = 2;\n\n  /* Creation date today */\n  today = ObitToday();\n  strncpy (outUV->myDesc->date, today, UVLEN_VALUE-1);\n  if (today) g_free(today);\n  \n  /* Get descriptors */\n  inDesc  = inUV->myDesc;\n  outDesc = outUV->myDesc;\n\n  /* Modify descriptor for affects of averaging, get u,v,w scaling */\n  ObitUVGetFreq (inUV, err);   /* Make sure frequencies updated */\n  scale = BloatFSetDesc (inDesc, outDesc, nBloat, err);\n  if (err->error) goto cleanup;\n\n  /* test open output */\n  oretCode = ObitUVOpen (outUV, OBIT_IO_WriteOnly, err);\n  /* If this didn't work try OBIT_IO_ReadWrite */\n  if ((oretCode!=OBIT_IO_OK) || (err->error)) {\n    ObitErrClear(err);\n    oretCode = ObitUVOpen (outUV, OBIT_IO_ReadWrite, err);\n  }\n  /* if it didn't work bail out */\n  if ((oretCode!=OBIT_IO_OK) || (err->error)) goto cleanup;\n\n  /* Copy tables before data */\n  iretCode = ObitUVCopyTables (inUV, outUV, exclude, NULL, err);\n  /* If multisource out then copy SU table, multiple sources selected or\n   sources deselected suggest MS out */\n  if ((inUV->mySel->numberSourcesList>1) || (!inUV->mySel->selectSources))\n  iretCode = ObitUVCopyTables (inUV, outUV, NULL, sourceInclude, err);\n  /* FQ table selection */\n  iretCode = ObitTableFQSelect (inUV, outUV, NULL, 0.0, err);\n  /* Correct FQ table for averaging \n     FQSel (outUV, NumChAvg, 1, err); done in FQSelect(?) */\n  if (err->error) goto cleanup;\n\n  /* reset to beginning of uv data */\n  iretCode = ObitIOSet (inUV->myIO,  inUV->info, err);\n  oretCode = ObitIOSet (outUV->myIO, outUV->info, err);\n  if (err->error) goto cleanup;\n\n  /* Close and reopen input to init calibration which will have been disturbed \n     by the table copy */\n  iretCode = ObitUVClose (inUV, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error)) goto cleanup;\n\n  iretCode = ObitUVOpen (inUV, access, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error)) goto cleanup;\n\n  /* we're in business, average data */\n  while ((iretCode==OBIT_IO_OK) && (oretCode==OBIT_IO_OK)) {\n    if (doCalSelect) iretCode = ObitUVReadSelect (inUV, inUV->buffer, err);\n    else iretCode = ObitUVRead (inUV, inUV->buffer, err);\n    if (iretCode!=OBIT_IO_OK) break;\n    /* How many */\n    outDesc->numVisBuff = inDesc->numVisBuff;\n\n    /* Modify data */\n    for (i=0; i<inDesc->numVisBuff; i++) { /* loop over visibilities */\n      /* Copy random parameters */\n      indx = i*inDesc->lrec;\n      jndx = i*outDesc->lrec;\n      for (j=0; j<inDesc->nrparm; j++) \n\toutUV->buffer[jndx+j] =  inUV->buffer[indx+j];\n\n      /* Scale u,v,w for new reference frequency */\n      outUV->buffer[jndx+outDesc->ilocu] *= scale;\n      outUV->buffer[jndx+outDesc->ilocv] *= scale;\n      outUV->buffer[jndx+outDesc->ilocw] *= scale;\n\n      /* Smooth data */\n      indx += inDesc->nrparm;\n      jndx += outDesc->nrparm;\n      /* duplicate channels */\n      Bloat (inUV->myDesc, outUV->myDesc, nBloat, unHann, \n\t    &inUV->buffer[indx], &outUV->buffer[jndx], err);\n      if (err->error) goto cleanup;\n    } /* end loop over visibilities */\n\n    /* Write */\n    oretCode = ObitUVWrite (outUV, outUV->buffer, err);\n    if (err->error) goto cleanup;\n  } /* end loop processing data */\n  \n  /* check for errors */\n  if ((iretCode > OBIT_IO_EOF) || (oretCode > OBIT_IO_EOF) ||\n      (err->error)) goto cleanup;\n\n  /* Cleanup */\n cleanup:\n  /* close files */\n  iretCode = ObitUVClose (inUV, err);\n  oretCode = ObitUVClose (outUV, err);\n  if ((iretCode!=OBIT_IO_OK) || (oretCode!=OBIT_IO_OK) || (err->error))\n    Obit_traceback_val (err, routine, outUV->name, outUV);\n  \n  return outUV;\n} /* end ObitUVUtilBloat */\n\n/**\n * Spectrally average the data inObitUV.\n * \\param inUV     Input uv data to average, \n *                 Any request for calibration, editing and selection honored\n * Control parameters on info element of inUV:\n * \\li \"NumChAvg\" OBIT_long scalar Number of channels to average, [def. = all]\n * \\li \"doAvgAll\" OBIT_bool Scalar, if TRUE then average all channels and \n *                IF. default = FALSE\n * \\li \"ChanSel\"  OBIT_int (4,*) Groups of channels to consider (relative to\n *                channels & IFs selected by BChan, EChan, BIF, EIF)\n *                (start, end, increment, IF) where start and end at the \n *                beginning and ending channel numbers (1-rel) of the group\n *                to be included, increment is the increment between\n *                selected channels and IF is the IF number (1-rel)\n *                default increment is 1, IF=0 means all IF.\n *                The list of groups is terminated by a start <=0\n *                Default is all channels in each IF.\n * \\li \"noScale\" OBIT_bool Scalar, if TRUE then do NOT scale u,v,w for new \n *               frequency. Used for holography data.  def FALSE\n *              \n * \\param scratch  True if scratch file desired, will be same type as inUV.\n * \\param outUV    If not scratch, then the previously defined output file\n *                 May be NULL for scratch only\n *                 If it exists and scratch, it will be Unrefed\n * \\param err      Error stack, returns if not empty.\n * \\return the frequency averaged ObitUV.\n */\nObitUV* ObitUVUtilAvgF (ObitUV *inUV, gboolean scratch, ObitUV *outUV, \n\t\t\tObitErr *err)\n{\n  ObitIOCode iretCode, oretCode;\n  gboolean doCalSelect;\n  gchar *exclude[]={\"AIPS CL\", \"AIPS SN\", \"AIPS FG\", \"AIPS CQ\", \"AIPS WX\",\n\t\t    \"AIPS AT\", \"AIPS CT\", \"AIPS OB\", \"AIPS IM\", \"AIPS MC\",\n\t\t    \"AIPS PC\", \"AIPS NX\", \"AIPS TY\", \"AIPS GC\", \"AIPS HI\",\n\t\t    \"AIPS PL\", \"AIPS NI\", \"AIPS BP\", \"AIPS OF\", \"AIPS PS\",\n\t\t    \"AIPS FQ\", \"AIPS SU\", \"AIPS AN\", \"AIPS PD\", \"AIPS SY\",\n\t\t    \"AIPS PT\", \"AIPS OT\",\n\t\t    NULL};\n  gchar *sourceInclude[] = {\"AIPS SU\", NULL};\n  olong i, j, indx, jndx;\n  olong *corChan=NULL, *corIF=NULL, *corStok=NULL;\n  gboolean *corMask=NULL;\n  ObitInfoType type;\n  gint32 dim[MAXINFOELEMDIM];\n  ObitIOAccess access;\n  ObitUVDesc *inDesc, *outDesc;\n  gchar *today=NULL;\n  ofloat *work=NULL, scale;\n  olong NumChAvg, *ChanSel=NULL;\n  gboolean doAvgAll, noScale;\n  olong defSel[] = {1,-10,1,0, 0,0,0,0};\n  gchar *routine = \"ObitUVUtilAvgF\";\n \n  /* error checks */\n  if (err->error) return outUV;\n  g_assert (ObitUVIsA(inUV));\n  if (!scratch && (outUV==NULL)) {\n    Obit_log_error(err, OBIT_Error,\"%s Output MUST be defined for non scratch files\",\n\t\t   routine);\n      return outUV;\n  }\n\n  /* Get Parameters */\n  NumChAvg = -1;\n  ObitInfoListGetTest(inUV->info, \"NumChAvg\", &type, dim, &NumChAvg);\n  doAvgAll = FALSE;\n  ObitInfoListGetTest(inUV->info, \"doAvgAll\", &type, dim, &doAvgAll);\n  noScale = FALSE;\n  ObitInfoListGetTest(inUV->info, \"noScale\", &type, dim, &noScale);\n  ChanSel = NULL;\n  if (!ObitInfoListGetP(inUV->info, \"ChanSel\", &type, dim, (gpointer)&ChanSel)) {\n    ChanSel = defSel;  /* Use default = channels 1 => n */\n  }\n  /* ChanSel all zero? => default */\n  if ((ChanSel[0]<=0) && (ChanSel[1]<=0) && (ChanSel[2]<=0) && (ChanSel[3]<=0)) {\n    ChanSel = defSel;  /* Use default = channels 1 => n */\n  }\n\n  /* Selection/calibration/editing of input? */\n  doCalSelect = FALSE;\n  ObitInfoListGetTest(inUV->info, \"doCalSelect\", &type, (gint32*)dim, &doCalSelect);\n  if (doCalSelect) access = OBIT_IO_ReadCal;\n  else access = OBIT_IO_ReadOnly;\n\n  /* test open to fully instantiate input and see if it's OK */\n  iretCode = ObitUVOpen (inUV, access, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error)) /* add traceback,return */\n    Obit_traceback_val (err, routine, inUV->name, outUV);\n\n  /* Create scratch? */\n  if (scratch) {\n    if (outUV) outUV = ObitUVUnref(outUV);\n    outUV = newObitUVScratch (inUV, err);\n  } else { /* non scratch output must exist - clone from inUV */\n    outUV->myDesc = ObitUVDescCopy (inUV->myDesc, outUV->myDesc, err);\n    /*ObitUVClone (inUV, outUV, err);*/\n  }\n  if (err->error) Obit_traceback_val (err, routine, inUV->name, inUV);\n\n  /* copy Descriptor */\n  outUV->myDesc = ObitUVDescCopy(inUV->myDesc, outUV->myDesc, err);\n \n  /* Default frequency group selection?  Average all */\n  if (ChanSel == defSel) defSel[1] = inUV->myDesc->inaxes[inUV->myDesc->jlocf];\n\n  /* Default number of channels to average = all */\n  if ((NumChAvg<=0) || doAvgAll) NumChAvg = inUV->myDesc->inaxes[inUV->myDesc->jlocf];\n  NumChAvg = MIN (NumChAvg, inUV->myDesc->inaxes[inUV->myDesc->jlocf]);\n \n  /* Creation date today */\n  today = ObitToday();\n  strncpy (outUV->myDesc->date, today, UVLEN_VALUE-1);\n  if (today) g_free(today);\n  \n  /* Get descriptors */\n  inDesc  = inUV->myDesc;\n  outDesc = outUV->myDesc;\n\n  /* Create work array for averaging */\n  work = g_malloc(2*inDesc->lrec*sizeof(ofloat));\n  /* Work arrays defining data */\n  corChan = g_malloc(inDesc->ncorr*sizeof(olong));\n  corIF   = g_malloc(inDesc->ncorr*sizeof(olong));\n  corStok = g_malloc(inDesc->ncorr*sizeof(olong));\n  corMask = g_malloc(inDesc->ncorr*sizeof(gboolean));\n\n  /* Modify descriptor for affects of averaging, get u,v,w scaling */\n  ObitUVGetFreq (inUV, err);   /* Make sure frequencies updated */\n  scale = AvgFSetDesc (inDesc, outDesc, NumChAvg, ChanSel, doAvgAll, \n\t\t       corChan, corIF, corStok, corMask, err);\n  if (err->error) goto cleanup;\n  /* Scale u,v,w? */\n  if (noScale) scale = 1.0;\n\n  /* test open output */\n  oretCode = ObitUVOpen (outUV, OBIT_IO_WriteOnly, err);\n  /* If this didn't work try OBIT_IO_ReadWrite */\n  if ((oretCode!=OBIT_IO_OK) || (err->error)) {\n    ObitErrClear(err);\n    oretCode = ObitUVOpen (outUV, OBIT_IO_ReadWrite, err);\n  }\n  /* if it didn't work bail out */\n  if ((oretCode!=OBIT_IO_OK) || (err->error)) goto cleanup;\n\n  /* Copy tables before data */\n  iretCode = ObitUVCopyTables (inUV, outUV, exclude, NULL, err);\n  /* If multisource out then copy SU table, multiple sources selected or\n   sources deselected suggest MS out */\n  if ((inUV->mySel->numberSourcesList>1) || (!inUV->mySel->selectSources))\n  iretCode = ObitUVCopyTables (inUV, outUV, NULL, sourceInclude, err);\n  /* FQ table selection */\n  iretCode = ObitTableFQSelect (inUV, outUV, NULL, 0.0, err);\n  /* Correct FQ table for averaging \n     FQSel (outUV, NumChAvg, 1, err); done in FQSelect(?) */\n  if (err->error) goto cleanup;\n\n  /* reset to beginning of uv data */\n  iretCode = ObitIOSet (inUV->myIO,  inUV->info, err);\n  oretCode = ObitIOSet (outUV->myIO, outUV->info, err);\n  if (err->error) goto cleanup;\n\n  /* Close and reopen input to init calibration which will have been disturbed \n     by the table copy */\n  iretCode = ObitUVClose (inUV, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error)) goto cleanup;\n\n  iretCode = ObitUVOpen (inUV, access, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error)) goto cleanup;\n\n  /* we're in business, average data */\n  while ((iretCode==OBIT_IO_OK) && (oretCode==OBIT_IO_OK)) {\n    if (doCalSelect) iretCode = ObitUVReadSelect (inUV, inUV->buffer, err);\n    else iretCode = ObitUVRead (inUV, inUV->buffer, err);\n    if (iretCode!=OBIT_IO_OK) break;\n    /* How many */\n    outDesc->numVisBuff = inDesc->numVisBuff;\n\n    /* Modify data */\n    for (i=0; i<inDesc->numVisBuff; i++) { /* loop over visibilities */\n      /* Copy random parameters */\n      indx = i*inDesc->lrec;\n      jndx = i*outDesc->lrec;\n      for (j=0; j<inDesc->nrparm; j++) \n\toutUV->buffer[jndx+j] =  inUV->buffer[indx+j];\n\n      /* Scale u,v,w for new reference frequency */\n      outUV->buffer[jndx+outDesc->ilocu] *= scale;\n      outUV->buffer[jndx+outDesc->ilocv] *= scale;\n      outUV->buffer[jndx+outDesc->ilocw] *= scale;\n\n      /* Average data */\n      indx += inDesc->nrparm;\n      jndx += outDesc->nrparm;\n      /* Average data */\n      AvgFAver (inUV->myDesc, outUV->myDesc, NumChAvg, ChanSel, doAvgAll, \n\t\tcorChan, corIF, corStok, corMask,\n\t\t&inUV->buffer[indx], &outUV->buffer[jndx], work, err);\n      if (err->error) goto cleanup;\n    } /* end loop over visibilities */\n\n    /* Write */\n    oretCode = ObitUVWrite (outUV, outUV->buffer, err);\n    if (err->error) goto cleanup;\n  } /* end loop processing data */\n  \n  /* check for errors */\n  if ((iretCode > OBIT_IO_EOF) || (oretCode > OBIT_IO_EOF) ||\n      (err->error)) goto cleanup;\n\n  /* Cleanup */\n cleanup:\n  if (work) g_free(work);       work    = NULL;\n  if (corChan) g_free(corChan); corChan = NULL;\n  if (corIF) g_free(corIF);     corIF   = NULL;\n  if (corStok) g_free(corStok); corStok = NULL;\n  if (corMask) g_free(corMask); corMask = NULL;\n  \n  /* close files */\n  iretCode = ObitUVClose (inUV, err);\n  oretCode = ObitUVClose (outUV, err);\n  if ((iretCode!=OBIT_IO_OK) || (oretCode!=OBIT_IO_OK) || (err->error))\n    Obit_traceback_val (err, routine, outUV->name, outUV);\n  \n  return outUV;\n} /* end ObitUVUtilAvgF */\n\n/**\n * Temporally average the data inObitUV.\n * \\param inUV     Input uv data to average, \n *                 Any request for calibration, editing and selection honored\n * Control parameter on info element of inUV:\n * \\li \"timeAvg\"   OBIT_float  (1,1,1) Time interval over which to average \n *                 (min) [def = 1 min.]\n *                 NB: this should be at least 2 integrations.\n *              \n * \\param scratch  True if scratch file desired, will be same type as inUV.\n * \\param outUV    If not scratch, then the previously defined output file\n *                 May be NULL for scratch only\n *                 If it exists and scratch, it will be Unrefed\n * \\param err      Error stack, returns if not empty.\n * \\return the frequency averaged ObitUV.\n */\nObitUV* ObitUVUtilAvgT (ObitUV *inUV, gboolean scratch, ObitUV *outUV, \n\t\t\tObitErr *err)\n{\n  ObitIOCode iretCode, oretCode;\n  gboolean doCalSelect;\n  gchar *exclude[]={\"AIPS CL\", \"AIPS SN\", \"AIPS FG\", \"AIPS CQ\", \"AIPS WX\",\n\t\t    \"AIPS AT\", \"AIPS CT\", \"AIPS OB\", \"AIPS IM\", \"AIPS MC\",\n\t\t    \"AIPS PC\", \"AIPS NX\", \"AIPS TY\", \"AIPS GC\", \"AIPS HI\",\n\t\t    \"AIPS PL\", \"AIPS NI\", \"AIPS BP\", \"AIPS OF\", \"AIPS PS\",\n\t\t    \"AIPS FQ\", \"AIPS SU\", \"AIPS AN\", \"AIPS PD\", \"AIPS SY\",\n\t\t    \"AIPS PT\", \"AIPS OT\",\n\t\t    NULL};\n  gchar *sourceInclude[] = {\"AIPS SU\", NULL};\n  ObitInfoType type;\n  gint32 dim[MAXINFOELEMDIM];\n  olong ncorr, nrparm, numAnt, jtemp;\n  ollong lltmp, i, j, numBL, jndx, indx, blindx, iindx=0, nvis;\n  ollong *blLookup=NULL;\n  ObitIOAccess access;\n  ObitUVDesc *inDesc, *outDesc;\n  ObitUVSortBuffer *outBuffer=NULL;\n  olong suba, lastSourceID, curSourceID, lastSubA;\n  gchar *today=NULL;\n  ofloat timeAvg, curTime, startTime, endTime;\n  ofloat *accVis=NULL, *accRP=NULL, *ttVis=NULL;\n  ofloat *inBuffer;\n  olong ant1, ant2;\n  olong ivis=0, NPIO;\n  gboolean done, gotOne;\n  gchar *routine = \"ObitUVUtilAvgT\";\n \n  /* error checks */\n  if (err->error) return outUV;\n  g_assert (ObitUVIsA(inUV));\n  if (!scratch && (outUV==NULL)) {\n    Obit_log_error(err, OBIT_Error,\"%s Output MUST be defined for non scratch files\",\n\t\t   routine);\n      return outUV;\n  }\n\n  /* Get Parameter - Time interval */\n  timeAvg = 1.0;  /* default 1 min */\n  ObitInfoListGetTest(inUV->info, \"timeAvg\", &type, dim, &timeAvg);\n  if (timeAvg<=(0.01/60.0)) timeAvg = 1.0;\n  timeAvg /= 1440.0;  /* convert to days */\n\n  /* Selection/calibration/editing of input? */\n  doCalSelect = FALSE;\n  ObitInfoListGetTest(inUV->info, \"doCalSelect\", &type, dim, &doCalSelect);\n  if (doCalSelect) access = OBIT_IO_ReadCal;\n  else access = OBIT_IO_ReadOnly;\n\n  /* test open to fully instantiate input and see if it's OK */\n  iretCode = ObitUVOpen (inUV, access, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error)) /* add traceback,return */\n    Obit_traceback_val (err, routine, inUV->name, outUV);\n\n  /* Create scratch? */\n  if (scratch) {\n    if (outUV) outUV = ObitUVUnref(outUV);\n    outUV = newObitUVScratch (inUV, err);\n  } else { /* non scratch output must exist - clone from inUV */\n    ObitUVClone (inUV, outUV, err);\n  }\n  if (err->error) Obit_traceback_val (err, routine, inUV->name, inUV);\n\n  /* copy Descriptor */\n  outUV->myDesc = ObitUVDescCopy(inUV->myDesc, outUV->myDesc, err);\n  inBuffer = inUV->buffer;  /* Local copy of buffer pointer */\n \n  /* Output creation date today */\n  today = ObitToday();\n  strncpy (outUV->myDesc->date, today, UVLEN_VALUE-1);\n  if (today) g_free(today);\n  \n  /* Set number of output vis per read to twice number of baselines */\n  suba    = 1;\n  numAnt  = inUV->myDesc->numAnt[suba-1];/* actually highest antenna number */\n  /* Better be some */\n  Obit_retval_if_fail ((numAnt>1), err, outUV,\n\t\t       \"%s Number of antennas NOT in descriptor\",  \n\t\t       routine);  \n  numBL   = (((ollong)numAnt)*(numAnt+1))/2;  /* Include auto correlations */\n  NPIO = 1;\n  ObitInfoListGetTest(inUV->info, \"nVisPIO\", &type, dim, &NPIO);\n  jtemp = (olong)(2 * numBL);  /* Might cause trouble if numBL VERY large */\n  dim[0] = dim[1] = dim[2] = 1;\n  ObitInfoListAlwaysPut(outUV->info, \"nVisPIO\", OBIT_long, dim, &jtemp);\n\n  /* test open output */\n  oretCode = ObitUVOpen (outUV, OBIT_IO_WriteOnly, err);\n  /* If this didn't work try OBIT_IO_ReadWrite */\n  if ((oretCode!=OBIT_IO_OK) || (err->error)) {\n    ObitErrClear(err);\n    oretCode = ObitUVOpen (outUV, OBIT_IO_ReadWrite, err);\n  }\n  /* if it didn't work bail out */\n  if ((oretCode!=OBIT_IO_OK) || (err->error)) goto cleanup;\n\n  /* Get descriptors */\n  inDesc  = inUV->myDesc;\n  outDesc = outUV->myDesc;\n\n  /* Create work arrays for averaging */\n  ncorr   = inUV->myDesc->ncorr;\n  nrparm  = inUV->myDesc->nrparm;\n  lltmp   = 4*numBL*ncorr*sizeof(ofloat);\n  accVis  = g_malloc0(lltmp);     /* Vis */\n  lltmp   = numBL*(nrparm+1)*sizeof(ofloat);\n  accRP   = g_malloc0(lltmp);  /* Rand. parm */\n  ttVis   = g_malloc0(( inUV->myDesc->lrec+5)*sizeof(ofloat)); /* Temp Vis */\n\n  /* Baseline lookup table */\n  blLookup = g_malloc0 (numAnt* sizeof(ollong));\n  blLookup[0] = 0;\n  /* Include autocorr */\n  for (i=1; i<numAnt; i++) blLookup[i] = blLookup[i-1] + numAnt-i+1; \n\n  /* Create sort buffer */\n  /* Make sort buffer big enough for four copies of each baseline */\n  nvis = 4 * numBL;  \n  nvis = MIN (nvis, inUV->myDesc->nvis);\n  outBuffer = ObitUVSortBufferCreate (\"Buffer\", outUV, nvis, err);\n  if (err->error) goto cleanup;\n\n  /* Copy tables before data */\n  iretCode = ObitUVCopyTables (inUV, outUV, exclude, NULL, err);\n  /* If multisource out then copy SU table, multiple sources selected or\n   sources deselected suggest MS out */\n  if ((inUV->mySel->numberSourcesList>1) || (!inUV->mySel->selectSources))\n  iretCode = ObitUVCopyTables (inUV, outUV, NULL, sourceInclude, err);\n  if (err->error) goto cleanup;\n\n  /* reset to beginning of uv data */\n  iretCode = ObitIOSet (inUV->myIO,  inUV->info, err);\n  oretCode = ObitIOSet (outUV->myIO, outUV->info, err);\n  if (err->error) goto cleanup;\n\n  /* Close and reopen input to init calibration which will have been disturbed \n     by the table copy */\n  iretCode = ObitUVClose (inUV, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error)) goto cleanup;\n\n  iretCode = ObitUVOpen (inUV, access, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error)) goto cleanup;\n\n  /* Initialize things */\n  startTime = -1.0e20;\n  endTime   =  1.0e20;\n  lastSourceID = -1;\n  curSourceID  = 0;\n  outDesc->numVisBuff = 0;\n  inBuffer  = inUV->buffer;   /* Local copy of buffer pointer */\n\n  /* Loop over intervals */\n  done   = FALSE;\n  gotOne = FALSE;\n\n  /* we're in business, average data */\n  while ((iretCode==OBIT_IO_OK) && (oretCode==OBIT_IO_OK)) {\n    if ((!gotOne) || (inUV->myDesc->numVisBuff<=0)) { /* need to read new record? */\n      if (doCalSelect) iretCode = ObitUVReadSelect (inUV, inUV->buffer, err);\n      else iretCode = ObitUVRead (inUV, inUV->buffer, err);\n      if (err->error) goto cleanup;\n    }\n\n    /* Are we there yet??? */\n    done = (inDesc->firstVis >= inDesc->nvis) || (iretCode==OBIT_IO_EOF);\n    if (done && (startTime>0.0)) goto process; /* Final? */\n\n    /* Make sure valid data found */\n    if (inUV->myDesc->numVisBuff<=0) continue;\n\n    /* loop over visibilities */\n    for (ivis=0; ivis<inDesc->numVisBuff; ivis++) { \n      /* Copy random parameters */\n      iindx = ivis*inDesc->lrec;\n\n      gotOne = FALSE;\n      \n      curTime = inBuffer[iindx+inDesc->iloct]; /* Time */\n      if (inDesc->ilocsu>=0) curSourceID = inBuffer[iindx+inDesc->ilocsu];\n      if (startTime < -1000.0) {  /* Set time window etc. if needed */\n\tstartTime = curTime;\n\tendTime   = startTime + timeAvg;\n\tlastSourceID = curSourceID;\n      }\n\n      /* Still in current interval/source? */\n      if ((curTime<endTime) && (curSourceID == lastSourceID) && \n\t  (inDesc->firstVis<=inDesc->nvis) && (iretCode==OBIT_IO_OK)) {\n\t/* accumulate */\n\tObitUVDescGetAnts(inUV->myDesc, &inBuffer[iindx], &ant1, &ant2, &lastSubA);\n\t/* Check antenna number */\n\tObit_retval_if_fail ((ant2<=numAnt), err, outUV, \n\t\t\t     \"%s Antenna 2=%d > max %d\", routine, ant2, numAnt);  \n\t/* Baseline index this assumes a1<=a2 always */\n\tblindx =  blLookup[ant1-1] + ant2-ant1;\n\t\n\t/* Accumulate RP\n\t   (1,*) =  count \n\t   (2...,*) =  Random parameters, sum u, v, w, time, int. */\n\tjndx = blindx*(1+nrparm);\n\taccRP[jndx]++;\n\tfor (i=0; i<nrparm; i++) { \n\t  /* Sum known parameters to average */\n\t  if ((i==inDesc->ilocu) || (i==inDesc->ilocv) || (i==inDesc->ilocw) ||\n\t      (i==inDesc->iloct) || (i==inDesc->ilocit)) {\n\t    accRP[jndx+i+1] += inBuffer[iindx+i];\n\t  } else { /* merely keep the rest */\n\t    accRP[jndx+i+1]  = inBuffer[iindx+i];\n\t  }\n\t} /* end loop over parameters */\n\t/* Accumulate Vis\n\t   (1,*) =  count \n\t   (2,*) =  sum Real\n\t   (3,*) =  sum Imag\n\t   (4,*) =  Sum Wt     */\n\tindx = iindx+inDesc->nrparm; /* offset of start of vis data */\n\tfor (i=0; i<ncorr; i++) {\n\t  if (inBuffer[indx+2] > 0.0) {\n\t    jndx = i*4 + blindx*4*ncorr;\n\t    accVis[jndx]   += 1.0;\n\t    accVis[jndx+1] += inBuffer[indx];\n\t    accVis[jndx+2] += inBuffer[indx+1];\n\t    accVis[jndx+3] += inBuffer[indx+2];\n\t  } \n\t  indx += 3;\n\t} /* end loop over correlations */;\n      } else {  /* process interval */\n\t\n      process:\n\t/* Now may have the next record in the IO Buffer */\n\tif ((iretCode==OBIT_IO_OK) && (ivis<(inDesc->numVisBuff-1))) gotOne = TRUE;\n\t    \n\t/* Loop over baselines writing average */\n\tfor (blindx=0; blindx<numBL; blindx++) {\n\n\t  /* Anything this baseline? */\n\t  jndx = blindx*(1+nrparm);\n\t  if (accRP[jndx]>0.0) {\n\t    /* Average u, v, w, time random parameters */\n\t    indx = 0;\n\t    for (i=0; i<nrparm; i++) { \n\t      /* Average known parameters */\n\t      if ((i==inDesc->ilocu) || (i==inDesc->ilocv) || (i==inDesc->ilocw) ||\n\t\t  (i==inDesc->iloct)) \n\t\taccRP[jndx+i+1] /= accRP[jndx];\n\t      /* Copy to output buffer */\n\t      ttVis[indx++] = accRP[jndx+i+1];\n\t    } /* End random parameter loop */\n\n\t    /* Average vis data */\n\t    for (j=0; j<ncorr; j++) {\n\t      jndx = j*4 + blindx*4*ncorr;\n\t      if (accVis[jndx]>0.0) {\n\t\taccVis[jndx+1] /= accVis[jndx];\n\t\taccVis[jndx+2] /= accVis[jndx];\n\t      }\n\t      /* Copy to output buffer */\n\t      ttVis[indx++] = accVis[jndx+1];\n\t      ttVis[indx++] = accVis[jndx+2];\n\t      ttVis[indx++] = accVis[jndx+3];\n\t    } /* end loop over correlators */\n\n\t    /* Copy to Sort Buffer (Sorts and writes when full) */\n\t    ObitUVSortBufferAddVis(outBuffer, ttVis, endTime, err);\n\t    if (err->error) goto cleanup;\n\t    /* Write output one vis at a time\n\t    outDesc->numVisBuff = 1;\n\t    oretCode = ObitUVWrite (outUV, outBuffer, err);\n\t    if (err->error) goto cleanup; */\n\t  } /* End any data this baseline */\n\t} /* end loop over baselines */\n\t\n\t/* Flush Sort Buffer */\n\tObitUVSortBufferFlush (outBuffer, err);\n\tif (err->error) Obit_traceback_val (err, routine, outUV->name, outUV);\n\n\t/* Are we there yet??? */\n\tdone = (inDesc->firstVis >= inDesc->nvis) || \n\t  (iretCode==OBIT_IO_EOF);\n\tif (done) goto done;\n\n\t/* Reinitialize things */\n\tstartTime = -1.0e20;\n\tendTime   =  1.0e20;\n\tfor (i=0; i<4*ncorr*numBL; i++)    accVis[i] = 0.0;\n\tfor (i=0; i<(nrparm+1)*numBL; i++) accRP[i] = 0.0;\n\n\t/* Now accumulate this visibility */\n\tObitUVDescGetAnts(inUV->myDesc, &inBuffer[iindx], &ant1, &ant2, &lastSubA);\n\t/* Baseline index this assumes a1<=a2 always */\n\t/* Check antenna number */\n\tObit_retval_if_fail ((ant2<=numAnt), err, outUV, \n\t\t\t     \"%s Antenna 2=%d > max %d\", routine, ant2, numAnt);  \n\tblindx =  blLookup[ant1-1] + ant2-ant1;\n\t\n\t/* Accumulate RP\n\t   (1,*) =  count \n\t   (2...,*) =  Random parameters, sum u, v, w, time, int. */\n\tjndx = blindx*(1+nrparm);\n\taccRP[jndx]++;\n\tfor (i=0; i<nrparm; i++) { \n\t  /* Sum known parameters to average */\n\t  if ((i==inDesc->ilocu) || (i==inDesc->ilocv) || (i==inDesc->ilocw) ||\n\t      (i==inDesc->iloct) || (i==inDesc->ilocit)) {\n\t    accRP[jndx+i+1] += inBuffer[iindx+i];\n\t  } else { /* merely keep the rest */\n\t    accRP[jndx+i+1]  = inBuffer[iindx+i];\n\t  }\n\t} /* end loop over parameters */\n\t/* Accumulate Vis\n\t   (1,*) =  count \n\t   (2,*) =  sum Real\n\t   (3,*) =  sum Imag\n\t   (4,*) =  Sum Wt     */\n\tindx = iindx+inDesc->nrparm; /* offset of start of vis data */\n\tfor (i=0; i<ncorr; i++) {\n\t  if (inBuffer[indx+2] > 0.0) {\n\t    jndx = i*4 + blindx*4*ncorr;\n\t    accVis[jndx]   += 1.0;\n\t    accVis[jndx+1] += inBuffer[indx];\n\t    accVis[jndx+2] += inBuffer[indx+1];\n\t    accVis[jndx+3] += inBuffer[indx+2];\n\t  } \n\t  indx += 3;\n\t} /* end loop over correlations */;\n      } /* end process interval */\n      \n    } /* end loop processing buffer of input data */\n  } /* End loop over input file */\n  \n  /* End of processing */\n done:\n  /* check for errors */\n  if ((iretCode > OBIT_IO_EOF) || (oretCode > OBIT_IO_EOF) ||\n      (err->error)) goto cleanup;\n  \n  /* Restore no vis per read in output */\n  dim[0] = dim[1] = dim[2] = 1;\n  ObitInfoListAlwaysPut (outUV->info, \"nVisPIO\", OBIT_long, dim, &NPIO);\n\n  /* Cleanup */\n cleanup:\n  if (accVis)   g_free(accVis);   accVis   = NULL;\n  if (ttVis)    g_free(ttVis);    ttVis    = NULL;\n  if (accRP)    g_free(accRP);    accRP    = NULL;\n  if (blLookup) g_free(blLookup); blLookup = NULL;\n  outBuffer = ObitUVSortBufferUnref(outBuffer);\n\n  /* close files */\n  iretCode = ObitUVClose (inUV, err);\n  oretCode = ObitUVClose (outUV, err);\n  if ((oretCode!=OBIT_IO_OK) || (iretCode!=OBIT_IO_OK) || (err->error))\n    Obit_traceback_val (err, routine, outUV->name, outUV);\n  \n  return outUV;\n} /* end ObitUVUtilAvgT */\n\n/**\n * Average all visibilities in inUV, write single vis to outUV.\n * For single source data single vis, for multisource data, one vis per scan.\n * Data labeled as baseline 1-2\n * \\param inUV     Input uv data to average, \n *                 Any request for calibration, editing and selection honored\n * \\param scratch  True if scratch file desired, will be same type as inUV.\n * \\param outUV    If not scratch, then the previously defined output file\n *                 May be NULL for scratch only\n *                 If it exists and scratch, it will be Unrefed\n * \\param err      Error stack, returns if not empty.\n * \\return the frequency averaged ObitUV.\n */\nObitUV* ObitUVUtilAvg2One (ObitUV *inUV, gboolean scratch, ObitUV *outUV, \n\t\t  \t   ObitErr *err)\n{\n  ObitIOCode iretCode, oretCode;\n  gboolean doCalSelect;\n  gchar *exclude[]={\"AIPS CL\", \"AIPS SN\", \"AIPS FG\", \"AIPS CQ\", \"AIPS WX\",\n\t\t    \"AIPS AT\", \"AIPS CT\", \"AIPS OB\", \"AIPS IM\", \"AIPS MC\",\n\t\t    \"AIPS PC\", \"AIPS NX\", \"AIPS TY\", \"AIPS GC\", \"AIPS HI\",\n\t\t    \"AIPS PL\", \"AIPS NI\", \"AIPS BP\", \"AIPS OF\", \"AIPS PS\",\n\t\t    \"AIPS FQ\", \"AIPS SU\", \"AIPS AN\", \"AIPS PD\", \"AIPS SY\",\n\t\t    \"AIPS PT\", \"AIPS OT\",\n\t\t    NULL};\n  gchar *sourceInclude[] = {\"AIPS SU\", NULL};\n  ObitInfoType type;\n  gint32 dim[MAXINFOELEMDIM];\n  olong ncorr, nrparm, numAnt, jtemp;\n  ollong lltmp, i, j, numBL, jndx, indx, blindx, iindx=0;\n  ObitIOAccess access;\n  ObitUVDesc *inDesc, *outDesc;\n  olong suba, lastSourceID, curSourceID;\n  gchar *today=NULL;\n  ofloat curTime, startTime, endTime;\n  ofloat *accVis=NULL, *accRP=NULL, *ttVis=NULL;\n  ofloat *inBuffer;\n  olong ivis=0, NPIO;\n  gboolean done, gotOne;\n  gchar *routine = \"ObitUVUtilAvgT\";\n \n  /* error checks */\n  if (err->error) return outUV;\n  g_assert (ObitUVIsA(inUV));\n  if (!scratch && (outUV==NULL)) {\n    Obit_log_error(err, OBIT_Error,\"%s Output MUST be defined for non scratch files\",\n\t\t   routine);\n      return outUV;\n  }\n\n  /* Selection/calibration/editing of input? */\n  doCalSelect = FALSE;\n  ObitInfoListGetTest(inUV->info, \"doCalSelect\", &type, dim, &doCalSelect);\n  if (doCalSelect) access = OBIT_IO_ReadCal;\n  else access = OBIT_IO_ReadOnly;\n\n  /* test open to fully instantiate input and see if it's OK */\n  iretCode = ObitUVOpen (inUV, access, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error)) /* add traceback,return */\n    Obit_traceback_val (err, routine, inUV->name, outUV);\n\n  /* Create scratch? */\n  if (scratch) {\n    if (outUV) outUV = ObitUVUnref(outUV);\n    outUV = newObitUVScratch (inUV, err);\n  } else { /* non scratch output must exist - clone from inUV */\n    ObitUVClone (inUV, outUV, err);\n  }\n  if (err->error) Obit_traceback_val (err, routine, inUV->name, inUV);\n\n  /* copy Descriptor */\n  outUV->myDesc = ObitUVDescCopy(inUV->myDesc, outUV->myDesc, err);\n  inBuffer = inUV->buffer;  /* Local copy of buffer pointer */\n \n  /* Output creation date today */\n  today = ObitToday();\n  strncpy (outUV->myDesc->date, today, UVLEN_VALUE-1);\n  if (today) g_free(today);\n  \n  /* Set number of output vis per read to twice number of baselines */\n  suba    = 1;\n  numAnt  = inUV->myDesc->numAnt[suba-1];/* actually highest antenna number */\n  /* Better be some */\n  Obit_retval_if_fail ((numAnt>1), err, outUV,\n\t\t       \"%s Number of antennas NOT in descriptor\",  \n\t\t       routine);  \n  numBL   = 1;  /* Single output visibility */\n  NPIO = 1;\n  ObitInfoListGetTest(inUV->info, \"nVisPIO\", &type, dim, &NPIO);\n  jtemp = (olong)(numBL); \n  dim[0] = dim[1] = dim[2] = 1;\n  ObitInfoListAlwaysPut(outUV->info, \"nVisPIO\", OBIT_long, dim, &jtemp);\n\n  /* test open output */\n  oretCode = ObitUVOpen (outUV, OBIT_IO_WriteOnly, err);\n  /* If this didn't work try OBIT_IO_ReadWrite */\n  if ((oretCode!=OBIT_IO_OK) || (err->error)) {\n    ObitErrClear(err);\n    oretCode = ObitUVOpen (outUV, OBIT_IO_ReadWrite, err);\n  }\n  /* if it didn't work bail out */\n  if ((oretCode!=OBIT_IO_OK) || (err->error)) goto cleanup;\n\n  /* Get descriptors */\n  inDesc  = inUV->myDesc;\n  outDesc = outUV->myDesc;\n\n  /* Create work arrays for averaging */\n  ncorr   = inUV->myDesc->ncorr;\n  nrparm  = inUV->myDesc->nrparm;\n  lltmp   = 4*numBL*ncorr*sizeof(ofloat);\n  accVis  = g_malloc0(lltmp);     /* Vis */\n  lltmp   = numBL*(nrparm+1)*sizeof(ofloat);\n  accRP   = g_malloc0(lltmp);  /* Rand. parm */\n  ttVis   = g_malloc0(( inUV->myDesc->lrec+5)*sizeof(ofloat)); /* Temp Vis */\n\n  /* Copy tables before data */\n  iretCode = ObitUVCopyTables (inUV, outUV, exclude, NULL, err);\n  /* If multisource out then copy SU table, multiple sources selected or\n   sources deselected suggest MS out */\n  if ((inUV->mySel->numberSourcesList>1) || (!inUV->mySel->selectSources))\n  iretCode = ObitUVCopyTables (inUV, outUV, NULL, sourceInclude, err);\n  if (err->error) goto cleanup;\n\n  /* reset to beginning of uv data */\n  iretCode = ObitIOSet (inUV->myIO,  inUV->info, err);\n  oretCode = ObitIOSet (outUV->myIO, outUV->info, err);\n  if (err->error) goto cleanup;\n\n  /* Close and reopen input to init calibration which will have been disturbed \n     by the table copy */\n  iretCode = ObitUVClose (inUV, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error)) goto cleanup;\n\n  iretCode = ObitUVOpen (inUV, access, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error)) goto cleanup;\n\n  /* Initialize things */\n  startTime = -1.0e20;\n  endTime   =  1.0e20;\n  lastSourceID = -1;\n  curSourceID  = 0;\n  outDesc->numVisBuff = 0;\n  inBuffer  = inUV->buffer;   /* Local copy of buffer pointer */\n\n  /* Loop over intervals */\n  done   = FALSE;\n  gotOne = FALSE;\n\n  /* we're in business, average data */\n  while ((iretCode==OBIT_IO_OK) && (oretCode==OBIT_IO_OK)) {\n    if ((!gotOne) || (inUV->myDesc->numVisBuff<=0)) { /* need to read new record? */\n      if (doCalSelect) iretCode = ObitUVReadSelect (inUV, inUV->buffer, err);\n      else iretCode = ObitUVRead (inUV, inUV->buffer, err);\n    }\n\n    /* Are we there yet??? */\n    done = (inDesc->firstVis >= inDesc->nvis) || (iretCode==OBIT_IO_EOF);\n    if (done && (startTime>0.0)) goto process; /* Final? */\n\n    /* Make sure valid data found */\n    if (inUV->myDesc->numVisBuff<=0) continue;\n\n    /* loop over visibilities */\n    for (ivis=0; ivis<inDesc->numVisBuff; ivis++) { \n      /* Copy random parameters */\n      iindx = ivis*inDesc->lrec;\n\n      gotOne = FALSE;\n      \n      curTime = inBuffer[iindx+inDesc->iloct]; /* Time */\n      if (inDesc->ilocsu>=0) curSourceID = inBuffer[iindx+inDesc->ilocsu];\n      if (startTime < -1000.0) {  /* Set time window etc. if needed */\n\tstartTime = curTime;\n\tendTime   = startTime + 1000.0;\n\tlastSourceID = curSourceID;\n      }\n\n      /* Still in current interval/source? */\n      if ((curTime<endTime) && (curSourceID == lastSourceID) && \n\t  (inDesc->firstVis<=inDesc->nvis) && (iretCode==OBIT_IO_OK)) {\n\t/* accumulate all to one vis */\n\tblindx =  0;\n\t\n\t/* Accumulate RP\n\t   (1,*) =  count \n\t   (2...,*) =  Random parameters, sum u, v, w, time, int. */\n\tjndx = blindx*(1+nrparm);\n\taccRP[jndx]++;\n\tfor (i=0; i<nrparm; i++) { \n\t  /* zero u,v,w */\n\t  if ((i==inDesc->ilocu) || (i==inDesc->ilocv) || (i==inDesc->ilocw))\n\t      inBuffer[iindx+i] = 0.0;\n\t  /* Sum known parameters to average */\n\t  if ((i==inDesc->iloct) || (i==inDesc->ilocit)) {\n\t    accRP[jndx+i+1] += inBuffer[iindx+i];\n\t  } else { /* merely keep the rest */\n\t    accRP[jndx+i+1]  = inBuffer[iindx+i];\n\t  }\n\t} /* end loop over parameters */\n\t/* Accumulate Vis\n\t   (1,*) =  count \n\t   (2,*) =  sum Real*wt\n\t   (3,*) =  sum Imag*wt\n\t   (4,*) =  Sum Wt     */\n\tindx = iindx+inDesc->nrparm; /* offset of start of vis data */\n\tfor (i=0; i<ncorr; i++) {\n\t  if (inBuffer[indx+2] > 0.0) {\n\t    jndx = i*4 + blindx*4*ncorr;\n\t    accVis[jndx]   += 1.0;\n\t    accVis[jndx+1] += inBuffer[indx]*inBuffer[indx+2];\n\t    accVis[jndx+2] += inBuffer[indx+1]*inBuffer[indx+2];\n\t    accVis[jndx+3] += inBuffer[indx+2];\n\t  } \n\t  indx += 3;\n\t} /* end loop over correlations */;\n      } else {  /* process interval */\n\t\n      process:\n\t/* Now may have the next record in the IO Buffer */\n\tif ((iretCode==OBIT_IO_OK) && (ivis<(inDesc->numVisBuff-1))) gotOne = TRUE;\n\t    \n\t/* Loop over baselines writing average */\n\tfor (blindx=0; blindx<numBL; blindx++) {\n\n\t  /* Anything this baseline? */\n\t  jndx = blindx*(1+nrparm);\n\t  if (accRP[jndx]>0.0) {\n\t    /* Average u, v, w, time random parameters */\n\t    indx = 0;\n\t    for (i=0; i<nrparm; i++) { \n\t      /* Average known parameters */\n\t      if ((i==inDesc->ilocu) || (i==inDesc->ilocv) || (i==inDesc->ilocw) ||\n\t\t  (i==inDesc->iloct)) \n\t\taccRP[jndx+i+1] /= accRP[jndx];\n\t      /* Copy to output buffer */\n\t      ttVis[indx++] = accRP[jndx+i+1];\n\t    } /* End random parameter loop */\n\t    /* Set baseline to 1-2 */\n\t    ObitUVDescSetAnts(outDesc, ttVis, 1, 2, 1);\n\n\t    /* Average vis data */\n\t    for (j=0; j<ncorr; j++) {\n\t      jndx = j*4 + blindx*4*ncorr;\n\t      if (accVis[jndx]>0.0) {\n\t\taccVis[jndx+1] /= accVis[jndx+3];\n\t\taccVis[jndx+2] /= accVis[jndx+3];\n\t      }\n\t      /* Copy to output buffer */\n\t      ttVis[indx++] = accVis[jndx+1];\n\t      ttVis[indx++] = accVis[jndx+2];\n\t      ttVis[indx++] = accVis[jndx+3];\n\t    } /* end loop over correlators */\n\n\t    /* Write output one vis at a time */\n\t    outDesc->numVisBuff = 1;\n\t    oretCode = ObitUVWrite (outUV, ttVis, err);\n\t    if (err->error) goto cleanup;\n\t  } /* End any data this baseline */\n\t} /* end loop over baselines */\n\t\n\t/* Are we there yet??? */\n\tdone = (inDesc->firstVis >= inDesc->nvis) || \n\t  (iretCode==OBIT_IO_EOF);\n\tif (done) goto done;\n\n\t/* Reinitialize things */\n\tstartTime = -1.0e20;\n\tendTime   =  1.0e20;\n\tfor (i=0; i<4*ncorr*numBL; i++)    accVis[i] = 0.0;\n\tfor (i=0; i<(nrparm+1)*numBL; i++) accRP[i] = 0.0;\n\n\t/* Now accumulate this visibility */\n\tblindx = 0;\n\t\n\t/* Accumulate RP\n\t   (1,*) =  count \n\t   (2...,*) =  Random parameters, sum u, v, w, time, int. */\n\tjndx = blindx*(1+nrparm);\n\taccRP[jndx]++;\n\tfor (i=0; i<nrparm; i++) { \n\t  /* Sum known parameters to average */\n\t  if ((i==inDesc->ilocu) || (i==inDesc->ilocv) || (i==inDesc->ilocw) ||\n\t      (i==inDesc->iloct) || (i==inDesc->ilocit)) {\n\t    accRP[jndx+i+1] += inBuffer[iindx+i];\n\t  } else { /* merely keep the rest */\n\t    accRP[jndx+i+1]  = inBuffer[iindx+i];\n\t  }\n\t} /* end loop over parameters */\n\t/* Accumulate Vis\n\t   (1,*) =  count \n\t   (2,*) =  sum Real\n\t   (3,*) =  sum Imag\n\t   (4,*) =  Sum Wt     */\n\tindx = iindx+inDesc->nrparm; /* offset of start of vis data */\n\tfor (i=0; i<ncorr; i++) {\n\t  if (inBuffer[indx+2] > 0.0) {\n\t    jndx = i*4 + blindx*4*ncorr;\n\t    accVis[jndx]   += 1.0;\n\t    accVis[jndx+1] += inBuffer[indx]*inBuffer[indx+2];\n\t    accVis[jndx+2] += inBuffer[indx+1]*inBuffer[indx+2];\n\t    accVis[jndx+3] += inBuffer[indx+2];\n\t  } \n\t  indx += 3;\n\t} /* end loop over correlations */;\n      } /* end process interval */\n      \n    } /* end loop processing buffer of input data */\n  } /* End loop over input file */\n  \n  /* End of processing */\n done:\n  /* check for errors */\n  if ((iretCode > OBIT_IO_EOF) || (oretCode > OBIT_IO_EOF) ||\n      (err->error)) goto cleanup;\n  \n  /* Restore no vis per read in output */\n  dim[0] = dim[1] = dim[2] = 1;\n  ObitInfoListAlwaysPut (outUV->info, \"nVisPIO\", OBIT_long, dim, &NPIO);\n\n  /* Cleanup */\n cleanup:\n  if (accVis)   g_free(accVis);   accVis   = NULL;\n  if (ttVis)    g_free(ttVis);    ttVis    = NULL;\n  if (accRP)    g_free(accRP);    accRP    = NULL;\n\n  /* close files */\n  iretCode = ObitUVClose (inUV, err);\n  oretCode = ObitUVClose (outUV, err);\n  if ((oretCode!=OBIT_IO_OK) || (iretCode!=OBIT_IO_OK) || (err->error))\n    Obit_traceback_val (err, routine, outUV->name, outUV);\n  \n  return outUV;\n} /* end ObitUVUtilAvg2One */\n\n/**\n * Spectrally smooth the data in ObitUV.\n * \\param inUV     Input uv data to average, \n *                 Any request for calibration, editing and selection honored\n * Control parameters on info element of inUV:\n * \\li \"NumChSmo\" OBIT_long scalar Number of channels to average, [def. = 3]\n * \\param scratch  True if scratch file desired, will be same type as inUV.\n * \\param outUV    If not scratch, then the previously defined output file\n *                 May be NULL for scratch only\n *                 If it exists and scratch, it will be Unrefed\n * \\param err      Error stack, returns if not empty.\n * \\return the frequency averaged ObitUV.\n */\nObitUV* ObitUVUtilSmoF (ObitUV *inUV, gboolean scratch, ObitUV *outUV, \n\t\t\tObitErr *err)\n{\n  ObitIOCode iretCode, oretCode;\n  gboolean doCalSelect;\n  gchar *exclude[]={\"AIPS CL\", \"AIPS SN\", \"AIPS FG\", \"AIPS CQ\", \"AIPS WX\",\n\t\t    \"AIPS AT\", \"AIPS CT\", \"AIPS OB\", \"AIPS IM\", \"AIPS MC\",\n\t\t    \"AIPS PC\", \"AIPS NX\", \"AIPS TY\", \"AIPS GC\", \"AIPS HI\",\n\t\t    \"AIPS PL\", \"AIPS NI\", \"AIPS BP\", \"AIPS OF\", \"AIPS PS\",\n\t\t    \"AIPS FQ\", \"AIPS SU\", \"AIPS AN\", \"AIPS PD\", \"AIPS SY\",\n\t\t    \"AIPS PT\", \"AIPS OT\",\n\t\t    NULL};\n  gchar *sourceInclude[] = {\"AIPS SU\", NULL};\n  olong i, j, indx, jndx;\n  olong *corChan=NULL, *corIF=NULL, *corStok=NULL;\n  gboolean *corMask=NULL;\n  ObitInfoType type;\n  gint32 dim[MAXINFOELEMDIM];\n  ObitIOAccess access;\n  ObitUVDesc *inDesc, *outDesc;\n  gchar *today=NULL;\n  ofloat *work=NULL;\n  olong NumChSmo;\n  gchar *routine = \"ObitUVUtilSmoF\";\n \n  /* error checks */\n  if (err->error) return outUV;\n  g_assert (ObitUVIsA(inUV));\n  if (!scratch && (outUV==NULL)) {\n    Obit_log_error(err, OBIT_Error,\"%s Output MUST be defined for non scratch files\",\n\t\t   routine);\n      return outUV;\n  }\n\n  /* Get Parameters */\n  NumChSmo = 3;\n  ObitInfoListGetTest(inUV->info, \"NumChSmo\", &type, dim, &NumChSmo);\n  /* Make sure odd */\n  Obit_retval_if_fail (((1+2*(NumChSmo/2))==NumChSmo), err, outUV,\n\t\t       \"%s NumChSmo MUST be odd not %d\",  \n\t\t       routine,NumChSmo);  \n\n  /* Selection/calibration/editing of input? */\n  doCalSelect = FALSE;\n  ObitInfoListGetTest(inUV->info, \"doCalSelect\", &type, (gint32*)dim, &doCalSelect);\n  if (doCalSelect) access = OBIT_IO_ReadCal;\n  else access = OBIT_IO_ReadOnly;\n\n  /* test open to fully instantiate input and see if it's OK */\n  iretCode = ObitUVOpen (inUV, access, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error)) /* add traceback,return */\n    Obit_traceback_val (err, routine, inUV->name, outUV);\n\n  /* Create scratch? */\n  if (scratch) {\n    if (outUV) outUV = ObitUVUnref(outUV);\n    outUV = newObitUVScratch (inUV, err);\n  } else { /* non scratch output must exist - clone from inUV */\n    outUV->myDesc = ObitUVDescCopy (inUV->myDesc, outUV->myDesc, err);\n    /*ObitUVClone (inUV, outUV, err);*/\n  }\n  if (err->error) Obit_traceback_val (err, routine, inUV->name, inUV);\n\n  /* copy Descriptor */\n  outUV->myDesc = ObitUVDescCopy(inUV->myDesc, outUV->myDesc, err);\n \n  /* Don't smooth more channels than exist */\n  NumChSmo = MIN (NumChSmo, inUV->myDesc->inaxes[inUV->myDesc->jlocf]);\n \n  /* Creation date today */\n  today = ObitToday();\n  strncpy (outUV->myDesc->date, today, UVLEN_VALUE-1);\n  if (today) g_free(today);\n  \n  /* Get descriptors */\n  inDesc  = inUV->myDesc;\n  outDesc = outUV->myDesc;\n\n  /* Create work array for smoothing */\n  work = g_malloc(2*inDesc->lrec*sizeof(ofloat));\n  /* Work arrays defining data */\n  corChan = g_malloc(inDesc->ncorr*sizeof(olong));\n  corIF   = g_malloc(inDesc->ncorr*sizeof(olong));\n  corStok = g_malloc(inDesc->ncorr*sizeof(olong));\n  corMask = g_malloc(inDesc->ncorr*sizeof(gboolean));\n\n  /* test open output */\n  oretCode = ObitUVOpen (outUV, OBIT_IO_WriteOnly, err);\n  /* If this didn't work try OBIT_IO_ReadWrite */\n  if ((oretCode!=OBIT_IO_OK) || (err->error)) {\n    ObitErrClear(err);\n    oretCode = ObitUVOpen (outUV, OBIT_IO_ReadWrite, err);\n  }\n  /* if it didn't work bail out */\n  if ((oretCode!=OBIT_IO_OK) || (err->error)) goto cleanup;\n\n  /* Copy tables before data */\n  iretCode = ObitUVCopyTables (inUV, outUV, exclude, NULL, err);\n  /* If multisource out then copy SU table, multiple sources selected or\n   sources deselected suggest MS out */\n  if ((inUV->mySel->numberSourcesList>1) || (!inUV->mySel->selectSources))\n  iretCode = ObitUVCopyTables (inUV, outUV, NULL, sourceInclude, err);\n  /* FQ table selection */\n  iretCode = ObitTableFQSelect (inUV, outUV, NULL, 0.0, err);\n  if (err->error) goto cleanup;\n\n  /* reset to beginning of uv data */\n  iretCode = ObitIOSet (inUV->myIO,  inUV->info, err);\n  oretCode = ObitIOSet (outUV->myIO, outUV->info, err);\n  if (err->error) goto cleanup;\n\n  /* Close and reopen input to init calibration which will have been disturbed \n     by the table copy */\n  iretCode = ObitUVClose (inUV, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error)) goto cleanup;\n\n  iretCode = ObitUVOpen (inUV, access, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error)) goto cleanup;\n\n  /* we're in business, average data */\n  while ((iretCode==OBIT_IO_OK) && (oretCode==OBIT_IO_OK)) {\n    if (doCalSelect) iretCode = ObitUVReadSelect (inUV, inUV->buffer, err);\n    else iretCode = ObitUVRead (inUV, inUV->buffer, err);\n    if (iretCode!=OBIT_IO_OK) break;\n    /* How many */\n    outDesc->numVisBuff = inDesc->numVisBuff;\n\n    /* Modify data */\n    for (i=0; i<inDesc->numVisBuff; i++) { /* loop over visibilities */\n      /* Copy random parameters */\n      indx = i*inDesc->lrec;\n      jndx = i*outDesc->lrec;\n      for (j=0; j<inDesc->nrparm; j++) \n\toutUV->buffer[jndx+j] =  inUV->buffer[indx+j];\n\n      /* Average data */\n      indx += inDesc->nrparm;\n      jndx += outDesc->nrparm;\n      /* Average data */\n      SmooF (inDesc, outDesc, NumChSmo, corChan, corIF, corStok, corMask,\n\t     &inUV->buffer[indx], &outUV->buffer[jndx], work, err);\n      if (err->error) goto cleanup;\n    } /* end loop over visibilities */\n\n    /* Write */\n    oretCode = ObitUVWrite (outUV, outUV->buffer, err);\n    if (err->error) goto cleanup;\n  } /* end loop processing data */\n  \n  /* check for errors */\n  if ((iretCode > OBIT_IO_EOF) || (oretCode > OBIT_IO_EOF) ||\n      (err->error)) goto cleanup;\n\n  /* Cleanup */\n cleanup:\n  if (work) g_free(work);       work    = NULL;\n  if (corChan) g_free(corChan); corChan = NULL;\n  if (corIF) g_free(corIF);     corIF   = NULL;\n  if (corStok) g_free(corStok); corStok = NULL;\n  if (corMask) g_free(corMask); corMask = NULL;\n  \n  /* close files */\n  iretCode = ObitUVClose (inUV, err);\n  oretCode = ObitUVClose (outUV, err);\n  if ((iretCode!=OBIT_IO_OK) || (oretCode!=OBIT_IO_OK) || (err->error))\n    Obit_traceback_val (err, routine, outUV->name, outUV);\n  \n  return outUV;\n} /* end ObitUVUtilSmoF */\n\n/**\n * Temporally average in a baseline dependent fashion the data in a ObitUV.\n * Also optionally average in frequency.\n * Time average UV data with averaging times depending\n * on time and baseline.  The averaging time is the greater of\n * maxInt and the time it takes for time smearing to reduce the \n * visibility amplitude by maxFact.\n * \\param inUV     Input uv data to average, \n *                 Any request for calibration, editing and selection honored\n * Control parameters on info element of inUV:\n * \\li \"FOV\"      OBIT_float  (1,1,1) Field of view (radius, deg)\n * \\li \"maxInt\"   OBIT_float  (1,1,1) Maximum integration (min)\n * \\li \"maxFact\"  OBIT_float  (1,1,1) Maximum time smearing factor\n * \\li \"NumChAvg\" OBIT_long scalar Number of channels to average, [def. = all]\n * \\li \"doAvgAll\" OBIT_bool Scalar, if TRUE then average all channels and \n *                IF. default = FALSE\n * \\li \"ChanSel\"  OBIT_int (4,*) Groups of channels to consider (relative to\n *                channels & IFs selected by BChan, EChan, BIF, EIF)\n *                (start, end, increment, IF) where start and end at the \n *                beginning and ending channel numbers (1-rel) of the group\n *                to be included, increment is the increment between\n *                selected channels and IF is the IF number (1-rel)\n *                default increment is 1, IF=0 means all IF.\n *                The list of groups is terminated by a start <=0\n *                Default is all channels in each IF.\n *              \n * \\param scratch  True if scratch file desired, will be same type as inUV.\n * \\param outUV    If not scratch, then the previously defined output file\n *                 May be NULL for scratch only\n *                 If it exists and scratch, it will be Unrefed\n * \\param err      Error stack, returns if not empty.\n * \\return the frequency averaged ObitUV.\n */\nObitUV* ObitUVUtilBlAvgTF (ObitUV *inUV, gboolean scratch, ObitUV *outUV, \n\t\t\t  ObitErr *err)\n{\n  ObitIOCode iretCode, oretCode;\n  gboolean doCalSelect;\n  gchar *exclude[]={\"AIPS CL\", \"AIPS SN\", \"AIPS FG\", \"AIPS CQ\", \"AIPS WX\",\n\t\t    \"AIPS AT\", \"AIPS CT\", \"AIPS OB\", \"AIPS IM\", \"AIPS MC\",\n\t\t    \"AIPS PC\", \"AIPS NX\", \"AIPS TY\", \"AIPS GC\", \"AIPS HI\",\n\t\t    \"AIPS PL\", \"AIPS NI\", \"AIPS BP\", \"AIPS OF\", \"AIPS PS\",\n\t\t    \"AIPS FQ\", \"AIPS SU\", \"AIPS AN\", \"AIPS PD\", \"AIPS SY\",\n\t\t    \"AIPS PT\", \"AIPS OT\", \n\t\t    NULL};\n  gchar *sourceInclude[] = {\"AIPS SU\", NULL};\n  ObitInfoType type;\n  gint32 dim[MAXINFOELEMDIM];\n  olong ncorr, nrparm, numAnt;\n  ollong lltmp, numBL, i, j, jndx, indx, blLo, blHi, nvis, ivis=0, iindx=0;\n  ollong blindx=0, *blLookup=NULL;\n  ObitIOAccess access;\n  ObitUVDesc *inDesc, *outDesc;\n  olong suba, lastSourceID, curSourceID, lastSubA;\n  gchar *today=NULL;\n  ofloat curTime=-1.0e20, startTime;\n  ofloat *accVis=NULL, *accRP=NULL, *lsBlTime=NULL, *stBlTime=NULL, *stBlU=NULL, *stBlV=NULL;\n  ofloat *tVis=NULL, *ttVis=NULL;\n  ofloat *inBuffer;\n  ObitUVSortBuffer *outBuffer=NULL;\n  ofloat FOV, maxTime, maxInt, maxFact, UVDist2, maxUVDist2;\n  olong ant1=1, ant2=2;\n  olong NPIO, itemp, count=0;\n  gboolean done, gotOne, doAllBl, sameInteg;\n  ofloat *work=NULL, scale=1.0;\n  olong NumChAvg, *ChanSel=NULL;\n  gboolean doAvgAll, doAvgFreq;\n  olong defSel[] = {1,1000000000,1,0, 0,0,0,0};\n  olong *corChan=NULL, *corIF=NULL, *corStok=NULL;\n  gboolean *corMask=NULL;\n  gchar *routine = \"ObitUVUtilAvgTF\";\n \n  /* error checks */\n  if (err->error) return outUV;\n  g_assert (ObitUVIsA(inUV));\n  if (!scratch && (outUV==NULL)) {\n    Obit_log_error(err, OBIT_Error,\"%s Output MUST be defined for non scratch files\",\n\t\t   routine);\n      return outUV;\n  }\n\n  /* Give report */  \n  Obit_log_error(err, OBIT_InfoErr, \n\t\t \"Doing baseline dependent time averaging\");\n  ObitErrLog(err); \n\n  /* Get Parameters - radius of field of view */\n  FOV = 20.0/60.0;  /* default 20 amin */\n  ObitInfoListGetTest(inUV->info, \"FOV\", &type, dim, &FOV);\n  /* to radians */\n  FOV = MAX(FOV,1.0e-4) * DG2RAD;\n\n  /* max. integration default 1 min */\n  maxInt = 1.0;  \n  ObitInfoListGetTest(inUV->info, \"maxInt\", &type, dim, &maxInt);\n  if (maxInt<=(1.0e-2/60.0)) maxInt = 1.0;\n  maxInt /= 1440.0;  /* convert to days */\n\n  /* max amplitude loss default 1.01 */\n  maxFact = 1.01;\n  ObitInfoListGetTest(inUV->info, \"maxFact\", &type, dim, &maxFact);\n  if (maxFact<0.99)  maxFact = 1.01;\n  maxFact = MIN(MAX(maxFact,1.0), 10.0);\n\n  /* Maximum UV distance squared to allow */\n  maxUVDist2 = (InvSinc(1.0/maxFact) / FOV);\n  maxUVDist2 = maxUVDist2*maxUVDist2; /* Square */\n\n  /* Get Frequency Parameters */\n  NumChAvg = 0;\n  ObitInfoListGetTest(inUV->info, \"NumChAvg\", &type, dim, &NumChAvg);\n  NumChAvg = MAX(1, NumChAvg);\n  doAvgAll = FALSE;\n  ObitInfoListGetTest(inUV->info, \"doAvgAll\", &type, dim, &doAvgAll);\n  ChanSel = NULL;\n  if (!ObitInfoListGetP(inUV->info, \"ChanSel\", &type, dim, (gpointer)&ChanSel)) {\n    ChanSel = defSel;  /* Use default = channels 1 => n */\n  }\n  /* ChanSel all zero? => default */\n  if ((ChanSel[0]<=0) && (ChanSel[1]<=0) && (ChanSel[2]<=0) && (ChanSel[3]<=0)) {\n    ChanSel = defSel;  /* Use default = channels 1 => n */\n  }\n\n  /* Averaging in frequency? */\n  doAvgFreq = (NumChAvg>1) || doAvgAll;\n\n  /* Selection/calibration/editing of input? */\n  doCalSelect = FALSE;\n  ObitInfoListGetTest(inUV->info, \"doCalSelect\", &type, dim, &doCalSelect);\n  if (doCalSelect) access = OBIT_IO_ReadCal;\n  else             access = OBIT_IO_ReadOnly;\n\n  /* test open to fully instantiate input and see if it's OK */\n  iretCode = ObitUVOpen (inUV, access, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error)) /* add traceback,return */\n    Obit_traceback_val (err, routine, inUV->name, outUV);\n\n  /* Is scratch? */\n  if (scratch) {\n    if (outUV) outUV = ObitUVUnref(outUV);\n    outUV = newObitUVScratch (inUV, err);\n  } else { /* non scratch output must exist - clone from inUV */\n    outUV->myDesc = ObitUVDescCopy (inUV->myDesc, outUV->myDesc, err);\n    ObitUVClone (inUV, outUV, err);\n  }\n  if (err->error) Obit_traceback_val (err, routine, inUV->name, outUV);\n\n  inDesc  = inUV->myDesc;\n  /* Create work array for frequency averaging */\n  if (doAvgFreq) {\n    work = g_malloc(2*inDesc->lrec*sizeof(ofloat));\n    /* Work arrays defining data */\n    corChan = g_malloc(inDesc->ncorr*sizeof(olong));\n    corIF   = g_malloc(inDesc->ncorr*sizeof(olong));\n    corStok = g_malloc(inDesc->ncorr*sizeof(olong));\n    corMask = g_malloc(inDesc->ncorr*sizeof(gboolean));\n\n    /* Modify descriptor for affects of frequency averaging, get u,v,w scaling */\n    ObitUVGetFreq (inUV, err);   /* Make sure frequencies updated */\n    scale = AvgFSetDesc (inUV->myDesc, outUV->myDesc, NumChAvg, ChanSel, doAvgAll, \n\t\t\t corChan, corIF, corStok, corMask, err);\n    if (err->error) goto cleanup;\n    \n  } else { /* Only time averaging */   \n    /* copy Descriptor */\n    outUV->myDesc = ObitUVDescCopy(inUV->myDesc, outUV->myDesc, err);\n  }\n\n  /* Get Parameters - radius of field of view */\n  FOV = 20.0/60.0;  /* default 20 amin */\n  ObitInfoListGetTest(inUV->info, \"FOV\", &type, dim, &FOV);\n  /* to radians */\n  FOV = MAX(FOV,1.0e-4) * DG2RAD;\n\n  /* max. integration default 1 min */\n  maxInt = 1.0;  \n  ObitInfoListGetTest(inUV->info, \"maxInt\", &type, dim, &maxInt);\n  if (maxInt<=(1.0e-2/60.0)) maxInt = 1.0;\n  maxInt /= 1440.0;  /* convert to days */\n\n  /* max amplitude loss default 1.01 */\n  maxFact = 1.01;\n  ObitInfoListGetTest(inUV->info, \"maxFact\", &type, dim, &maxFact);\n  if (maxFact<0.99)  maxFact = 1.01;\n  maxFact = MIN(MAX(maxFact,1.0), 10.0);\n\n  /* Maximum UV distance squared to allow */\n  maxUVDist2 = (InvSinc(1.0/maxFact) / FOV);\n  maxUVDist2 = maxUVDist2*maxUVDist2; /* Square */\n\n  /* Get Frequency Parameters */\n  NumChAvg = 0;\n  ObitInfoListGetTest(inUV->info, \"NumChAvg\", &type, dim, &NumChAvg);\n  NumChAvg = MAX(1, NumChAvg);\n  doAvgAll = FALSE;\n  ObitInfoListGetTest(inUV->info, \"doAvgAll\", &type, dim, &doAvgAll);\n  ChanSel = NULL;\n  if (!ObitInfoListGetP(inUV->info, \"ChanSel\", &type, dim, (gpointer)&ChanSel)) {\n    ChanSel = defSel;  /* Use default = channels 1 => n */\n  }\n  /* ChanSel all zero? => default */\n  if ((ChanSel[0]<=0) && (ChanSel[1]<=0) && (ChanSel[2]<=0) && (ChanSel[3]<=0)) {\n    ChanSel = defSel;  /* Use default = channels 1 => n */\n  }\n\n  /* Averaging in frequency? */\n  doAvgFreq = (NumChAvg>1) || doAvgAll;\n\n  /* Selection/calibration/editing of input? */\n  doCalSelect = FALSE;\n  ObitInfoListGetTest(inUV->info, \"doCalSelect\", &type, dim, &doCalSelect);\n  if (doCalSelect) access = OBIT_IO_ReadCal;\n  else             access = OBIT_IO_ReadOnly;\n\n  /* test open to fully instantiate input and see if it's OK */\n  iretCode = ObitUVOpen (inUV, access, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error)) /* add traceback,return */\n    Obit_traceback_val (err, routine, inUV->name, outUV);\n\n  /* Is scratch? */\n  if (scratch) {\n    if (outUV) outUV = ObitUVUnref(outUV);\n    outUV = newObitUVScratch (inUV, err);\n  } else { /* non scratch output must exist - clone from inUV */\n    outUV->myDesc = ObitUVDescCopy (inUV->myDesc, outUV->myDesc, err);\n    ObitUVClone (inUV, outUV, err);\n  }\n  if (err->error) Obit_traceback_val (err, routine, inUV->name, outUV);\n\n  inDesc  = inUV->myDesc;\n  /* Create work array for frequency averaging */\n  if (doAvgFreq) {\n    work = g_malloc(2*inDesc->lrec*sizeof(ofloat));\n    /* Work arrays defining data */\n    corChan = g_malloc(inDesc->ncorr*sizeof(olong));\n    corIF   = g_malloc(inDesc->ncorr*sizeof(olong));\n    corStok = g_malloc(inDesc->ncorr*sizeof(olong));\n    corMask = g_malloc(inDesc->ncorr*sizeof(gboolean));\n\n    /* Modify descriptor for affects of frequency averaging, get u,v,w scaling */\n    ObitUVGetFreq (inUV, err);   /* Make sure frequencies updated */\n    scale = AvgFSetDesc (inUV->myDesc, outUV->myDesc, NumChAvg, ChanSel, doAvgAll, \n\t\t\t corChan, corIF, corStok, corMask, err);\n    if (err->error) goto cleanup;\n    \n  } else { /* Only time averaging */   \n    /* copy Descriptor */\n    outUV->myDesc = ObitUVDescCopy(inUV->myDesc, outUV->myDesc, err);\n  }\n\n  /* Add integration time if not present */\n  if (outUV->myDesc->ilocit<0) {\n    strncpy (outUV->myDesc->ptype[outUV->myDesc->nrparm], \n\t     \"INTTIM\", UVLEN_KEYWORD-1);\n    outUV->myDesc->ilocit = outUV->myDesc->nrparm;\n    outUV->myDesc->nrparm++;\n  }\n\n  /* Output creation date today */\n  today = ObitToday();\n  strncpy (outUV->myDesc->date, today, UVLEN_VALUE-1);\n  if (today) g_free(today);\n  \n  /* Set number of output vis per write  */\n  NPIO = 1;\n  ObitInfoListGetTest(inUV->info, \"nVisPIO\", &type, dim, &NPIO);\n  itemp = 1000;  /* Internal IO buffer */\n  dim[0] = dim[1] = dim[2] = 1;\n  ObitInfoListAlwaysPut(outUV->info, \"nVisPIO\", OBIT_long, dim, &itemp);\n\n  /* test open output */\n  oretCode = ObitUVOpen (outUV, OBIT_IO_WriteOnly, err);\n  /* If this didn't work try OBIT_IO_ReadWrite */\n  if ((oretCode!=OBIT_IO_OK) || (err->error)) {\n    ObitErrClear(err);\n    oretCode = ObitUVOpen (outUV, OBIT_IO_ReadWrite, err);\n  }\n  /* if it didn't work bail out */\n  if ((oretCode!=OBIT_IO_OK) || (err->error)) goto cleanup;\n\n  /* Create sort buffer - Size depends on OS */\n  if (sizeof(olong*)==4) {  /* 32 bit OS */\n    /* Make sort buffer big  ~ 0.5 Gbyte */\n    nvis = 500000000 / (outUV->myDesc->lrec*sizeof(ofloat));  \n  } else if (sizeof(olong*)==8) {  /* 64 bit OS */\n    /* Make sort buffer big  ~ 4 Gbyte */\n    nvis = 4000000000 / (outUV->myDesc->lrec*sizeof(ofloat));  \n  } else nvis = 2000000000 / (outUV->myDesc->lrec*sizeof(ofloat)); \n  nvis = MIN (nvis, inUV->myDesc->nvis);\n  outBuffer = ObitUVSortBufferCreate (\"Buffer\", outUV, nvis, err);\n  if (err->error) goto cleanup;\n\n  /* Get descriptors */\n  inDesc  = inUV->myDesc;\n  outDesc = outUV->myDesc;\n\n  /* Create work arrays for time averaging */\n  suba    = 1;\n  numAnt  = inDesc->numAnt[suba-1]; /* actually highest antenna number */\n  /* Better be some */\n  Obit_retval_if_fail ((numAnt>1), err, outUV,\n\t\t       \"%s Number of antennas NOT in descriptor\",  \n\t\t       routine);  \n  numBL   = (((ollong)numAnt)*(numAnt+1))/2;  /* Include auto correlations */\n  ncorr   = inDesc->ncorr;\n  nrparm  = inDesc->nrparm;\n  lltmp = 4*numBL*ncorr*sizeof(ofloat);\n  accVis  = g_malloc0(lltmp);                           /* Vis accumulator */\n  tVis    = g_malloc0((inDesc->lrec+5)*sizeof(ofloat)); /* Temp Vis */\n  ttVis   = g_malloc0((inDesc->lrec+5)*sizeof(ofloat)); /* Temp Vis */\n  lltmp   = numBL*(nrparm+1)*sizeof(ofloat);\n  accRP   = g_malloc0(lltmp);   /* Rand. parm */\n  lltmp   = numBL*sizeof(ofloat);\n  stBlTime= g_malloc0(lltmp);   /* Baseline start time */\n  lsBlTime= g_malloc0(lltmp);   /* Baseline last time */\n  stBlU   = g_malloc0(lltmp);   /* Baseline start U */\n  stBlV   = g_malloc0(lltmp);   /* Baseline start V */\n\n  /* Baseline lookup table */\n  blLookup = g_malloc0 (numAnt* sizeof(ollong));\n  blLookup[0] = 0;\n  /* Include autocorr */\n  for (i=1; i<numAnt; i++) blLookup[i] = blLookup[i-1] + numAnt-i+1; \n\n /* Copy tables before data */\n  iretCode = ObitUVCopyTables (inUV, outUV, exclude, NULL, err);\n  /* If multisource out then copy SU table, multiple sources selected or\n   sources deselected suggest MS out */\n  if ((inUV->mySel->numberSourcesList>1) || (!inUV->mySel->selectSources))\n    iretCode = ObitUVCopyTables (inUV, outUV, NULL, sourceInclude, err);\n  if (err->error) goto cleanup;\n\n  /* reset to beginning of uv data */\n  iretCode = ObitIOSet (inUV->myIO,  inUV->info, err);\n  oretCode = ObitIOSet (outUV->myIO, outUV->info, err);\n  if (err->error) goto cleanup;\n\n  /* Close and reopen input to init calibration which will have been disturbed \n     by the table copy */\n  iretCode = ObitUVClose (inUV, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error)) goto cleanup;\n\n  iretCode = ObitUVOpen (inUV, access, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error)) goto cleanup;\n\n  /* Initialize things */\n  startTime    = -1.0e20;\n  lastSourceID = -1;\n  curSourceID  = 0;\n  outDesc->numVisBuff = 0;\n  inBuffer     = inUV->buffer;   /* Local copy of buffer pointer */\n\n  /* Loop over intervals */\n  done   = FALSE;\n  gotOne = FALSE;\n\n  /* we're in business, average data */\n  while ((iretCode==OBIT_IO_OK) && (oretCode==OBIT_IO_OK)) {\n    if ((!gotOne) || (inUV->myDesc->numVisBuff<=0)) { /* need to read new record? */\n      if (doCalSelect) iretCode = ObitUVReadSelect (inUV, inUV->buffer, err);\n      else iretCode = ObitUVRead (inUV, inUV->buffer, err);\n    }\n\n    /* Are we there yet??? */\n    done = (inDesc->firstVis >= inDesc->nvis) || (iretCode==OBIT_IO_EOF);\n    if (done && (startTime>0.0)) {doAllBl=TRUE; goto process;} /* Final? */\n\n    /* Make sure valid data found */\n    if (inUV->myDesc->numVisBuff<=0) continue;\n\n    /* loop over visibilities */\n    for (ivis=0; ivis<inDesc->numVisBuff; ivis++) { \n\n      gotOne = FALSE;\n      \n      /* Which data is this? */\n      iindx = ivis*inDesc->lrec;\n      ObitUVDescGetAnts(inUV->myDesc, &inBuffer[iindx], &ant1, &ant2, &lastSubA);\n      /* Check antenna number */\n      Obit_retval_if_fail ((ant2<=numAnt), err, outUV,\n\t\t\t   \"%s Antenna 2=%d > max %d\", routine, ant2, numAnt);  \n      /* Baseline index this assumes a1<=a2 always */\n      blindx =  blLookup[ant1-1] + ant2-ant1;\n      blindx = MAX (0, MIN (blindx, numBL-1));\n      curTime = inBuffer[iindx+inDesc->iloct]; /* Time */\n      if (inDesc->ilocsu>=0) curSourceID = inBuffer[iindx+inDesc->ilocsu];\n\n      /* Set time window etc. if needed */\n      if (startTime < -1000.0) {  \n\tstartTime    = curTime;\n\tlastSourceID = curSourceID;\n      }\n\n      /* If end of data, new scan, source, etc., finish all accumulations */\n      doAllBl = \n\t(curSourceID != lastSourceID) ||        /* Same source */\n\t(inDesc->firstVis>inDesc->nvis) ||      /* Not end of data */\n\t(iretCode!=OBIT_IO_OK);                 /* Not end of data */\n      lastSourceID = curSourceID;\n      \n      /* Reset baseline start on first accumulation */\n      jndx = blindx*(1+nrparm);\n      if (accRP[jndx]<1.0) { \n\tstBlTime[blindx] = inBuffer[iindx+inDesc->iloct];\n\tstBlU[blindx]    = inBuffer[iindx+inDesc->ilocu];\n\tstBlV[blindx]    = inBuffer[iindx+inDesc->ilocv];\n      }\n\t\n      /* Compute square of UV distance since start of integration */\n      UVDist2 = \n\t(inBuffer[iindx+inDesc->ilocu]-stBlU[blindx])*(inBuffer[iindx+inDesc->ilocu]-stBlU[blindx]) +\n\t(inBuffer[iindx+inDesc->ilocv]-stBlV[blindx])*(inBuffer[iindx+inDesc->ilocv]-stBlV[blindx]);\n\n      /* Still in current baseline integration? */\n      sameInteg = ((!doAllBl) &&                           /* Not end of scan or data */\n\t\t   ((curTime-stBlTime[blindx])<maxInt) &&  /* Max. integration */\n\t\t   (UVDist2<maxUVDist2));                  /* Max. smearing */\n      if (!sameInteg) {  /* Write */\n\t\n      process:\n\t/* Now may have the next record in the IO Buffer */\n\tif ((iretCode==OBIT_IO_OK) && (ivis<(inDesc->numVisBuff-1))) gotOne = TRUE;\n\t/* Finish this or all baselines? */\n\tif (doAllBl) {\n\t  blLo = 0;\n\t  blHi = numBL-1;\n\t} else { /* only this one */\n\t  blLo = blindx;\n\t  blHi = blindx;\n\t}\n\t/* Loop over this or all baselines */\n\tfor (blindx=blLo; blindx<=blHi; blindx++) { \n\t  /* Anything this baseline? */\n\t  jndx = blindx*(1+nrparm);\n\t  if (accRP[jndx]>0.0) {\n\t    /* Average u, v, w, time random parameters */\n\t    indx = 0;\n\t    for (i=0; i<nrparm; i++) { \n\t      /* Average known parameters */\n\t      if ((i==inDesc->ilocu) || (i==inDesc->ilocv) || (i==inDesc->ilocw) ||\n\t\t  (i==inDesc->iloct)) \n\t\taccRP[jndx+i+1] /= accRP[jndx];\n\t      /* Copy to output buffer */\n\t      ttVis[indx++] = accRP[jndx+i+1];\n\t    } /* End random parameter loop */\n\t    \n\t    /* Average vis data in time */\n\t    indx = outDesc->nrparm;\n\t    for (j=0; j<ncorr; j++) {\n\t      jndx = j*4 + blindx*4*ncorr;\n\t      if (accVis[jndx]>0.0) {\n\t\taccVis[jndx+1] /= accVis[jndx];\n\t\taccVis[jndx+2] /= accVis[jndx];\n\t      }\n\t      /* Copy to tempory vis */\n\t      tVis[indx++] = accVis[jndx+1];\n\t      tVis[indx++] = accVis[jndx+2];\n\t      tVis[indx++] = accVis[jndx+3];\n\t      \n\t    } /* end loop over correlators */\n\t    \n\t    if (doAvgFreq) {\n\t      /* Average data in frequency to output buffer */\n\t      AvgFAver (inDesc, outDesc, NumChAvg, ChanSel, doAvgAll, \n\t\t\tcorChan, corIF, corStok, corMask,\n\t\t\t&tVis[outDesc->nrparm], &ttVis[outDesc->nrparm], work, err);\n\t      if (err->error) goto cleanup;\n\n\t      /* Scale u,v,w for new reference frequency */\n\t      ttVis[outDesc->ilocu] *= scale;\n\t      ttVis[outDesc->ilocv] *= scale;\n\t      ttVis[outDesc->ilocw] *= scale;\n\t    } else { /* only time averaging */\n\t      /* Copy to output buffer */\n\t      indx = outDesc->nrparm;\n\t      jndx = outDesc->nrparm;\n\t      for (j=0; j<ncorr; j++) {\n\t\tttVis[indx++] = tVis[jndx++];\n\t\tttVis[indx++] = tVis[jndx++];\n\t\tttVis[indx++] = tVis[jndx++];\n\t      }\n\t    }\n\t    \n\t    /* Set integration time */\n\t    if (inDesc->ilocit>=0)\n\t      ttVis[outDesc->ilocit] = \n\t\tMAX (lsBlTime[blindx]-stBlTime[blindx],ttVis[outDesc->ilocit]);\n\t    else\n\t      ttVis[outDesc->ilocit] = lsBlTime[blindx]-stBlTime[blindx];\n\t    \n\t    /* Copy to Sort Buffer (Sorts and writes when full) */\n\t    count++;\n\t    maxTime = curTime - 0.6*maxInt;\n\t    ObitUVSortBufferAddVis(outBuffer, ttVis, maxTime, err);\n\t    if (err->error) goto cleanup;\n\t    \n\t    /* Reinitialize baseline */\n\t    jndx = blindx*(1+nrparm);\n\t    for (i=0; i<=nrparm; i++) accRP[jndx+i]  = 0.0;\n\t    jndx = blindx*4*ncorr;\n\t    for (i=0; i<4*ncorr; i++) accVis[jndx+i] = 0.0;\n\t    lsBlTime[blindx] = 0.0;\n\t    stBlTime[blindx] = 0.0;\n\t  } /* End any data this baseline */\n\t  \n\t} /* end loop over baseline */\n      }  /* end process interval */\n      \n      /* accumulate */\n      blindx =  blLookup[ant1-1] + ant2-ant1;\n      jndx = blindx*(1+nrparm);\n      if (accRP[jndx]<1.0) { /* starting conditions */\n\tstBlTime[blindx] = inBuffer[iindx+inDesc->iloct];\n\tstBlU[blindx]    = inBuffer[iindx+inDesc->ilocu];\n\tstBlV[blindx]    = inBuffer[iindx+inDesc->ilocv];\n      }\n      lsBlTime[blindx] = inBuffer[iindx+inDesc->iloct]; /* Highest time */\n      /* Accumulate RP\n\t (1,*)    =  count \n\t (2...,*) =  Random parameters, sum u, v, w, time, int. */\n      accRP[jndx]++;\n      for (i=0; i<nrparm; i++) { \n\t/* Sum known parameters to average */\n\tif ((i==inDesc->ilocu) || (i==inDesc->ilocv) || (i==inDesc->ilocw) ||\n\t    (i==inDesc->iloct) || (i==inDesc->ilocit)) {\n\t  accRP[jndx+i+1] += inBuffer[iindx+i];\n\t} else { /* merely keep the rest */\n\t  accRP[jndx+i+1]  = inBuffer[iindx+i];\n\t}\n      } /* end loop over parameters */\n\t/* Accumulate Vis\n\t   (1,*) =  count \n\t   (2,*) =  sum Real\n\t   (3,*) =  sum Imag\n\t   (4,*) =  Sum Wt     */\n      indx = iindx+inDesc->nrparm; /* offset of start of vis data */\n      for (i=0; i<ncorr; i++) {\n\tif (inBuffer[indx+2] > 0.0) {\n\t  jndx = i*4 + blindx*4*ncorr;\n\t  accVis[jndx]   += 1.0;\n\t  accVis[jndx+1] += inBuffer[indx];\n\t  accVis[jndx+2] += inBuffer[indx+1];\n\t  accVis[jndx+3] += inBuffer[indx+2];\n\t} \n\tindx += 3;\n      } /* end loop over correlations */;\n      \n    } /* end loop processing buffer of input data */\n  } /* End loop over input file */\n  \n  /* End of processing */\n\n  /* check for errors */\n  if ((iretCode > OBIT_IO_EOF) || (oretCode > OBIT_IO_EOF) ||\n      (err->error)) goto cleanup;\n  \n  /* Cleanup */\n cleanup:\n  if (accVis)   g_free(accVis);   accVis   = NULL;\n  if (accRP)    g_free(accRP);    accRP    = NULL;\n  if (tVis)     g_free(tVis);     tVis     = NULL;\n  if (ttVis)    g_free(ttVis);    ttVis    = NULL;\n  if (blLookup) g_free(blLookup); blLookup = NULL;\n  if (lsBlTime) g_free(lsBlTime); lsBlTime = NULL;\n  if (stBlTime) g_free(stBlTime); stBlTime = NULL;\n  if (stBlU)    g_free(stBlU);    stBlU    = NULL;\n  if (stBlV)    g_free(stBlV);    stBlV    = NULL;\n  if (work)     g_free(work);     work     = NULL;\n  if (corChan)  g_free(corChan);  corChan  = NULL;\n  if (corIF)    g_free(corIF);    corIF    = NULL;\n  if (corStok)  g_free(corStok);  corStok  = NULL;\n  if (corMask)  g_free(corMask);  corMask  = NULL;\n  \n  /* Flush Sort Buffer */\n  ObitUVSortBufferFlush (outBuffer, err);\n  if (err->error) Obit_traceback_val (err, routine, outUV->name, outUV);\n  outBuffer = ObitUVSortBufferUnref(outBuffer);\n \n  /* close files */\n  iretCode = ObitUVClose (inUV, err);\n  oretCode = ObitUVClose (outUV, err);\n  if ((oretCode!=OBIT_IO_OK) || (iretCode!=OBIT_IO_OK) || (err->error))\n    Obit_traceback_val (err, routine, outUV->name, outUV);\n\n  /* Restore no vis per read in output */\n  dim[0] = dim[1] = dim[2] = 1;\n  ObitInfoListAlwaysPut (outUV->info, \"nVisPIO\", OBIT_long, dim, &NPIO);\n\n  /* Give report */  \n  Obit_log_error(err, OBIT_InfoErr, \n\t\t \"Wrote %d averaged visibilities\",count);\n  ObitErrLog(err); \n\n  return outUV;\n} /* end ObitUVUtilBlAvgTF */\n\n/**\n * Count number of good correlations per time interval\n * \\param inData    Input UV data, data selections, if any, applied\n * \\param timeInt   Size of time interval in days, max. 500 intervals\n *                  If data from a new source is found a new interval \n *                  is started.\n * \\param err       Error stack, returns if not empty.\n * \\return ObitInfoList with entries:\n * \\li \"numTime\" OBIT_int [1] Number of time intervals\n * \\li \"numCorr\" OBIT_int [1] Number of Correlations per vis\n * \\li \"Count\"   OBIT_int [?] Count of good correlations per interval\n * \\li \"Bad\"     OBIT_int [?] Count of bad correlations per interval\n * \\li \"Source\"  OBIT_int [?] Source ID per interval\n * \\li \"LST\"     OBIT_float [?] Average LST (days) per interval\n *               -1000.0 => no data.\n */\nObitInfoList* ObitUVUtilCount (ObitUV *inUV, ofloat timeInt, ObitErr *err)\n{\n  ObitInfoList *outList = NULL;\n  ObitTableAN *ANTable=NULL;\n  ObitIOCode iretCode;\n  gboolean doCalSelect;\n  olong i, ver, ivis;\n  ObitInfoType type;\n  gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};\n  ObitIOAccess access;\n  ObitUVDesc *inDesc;\n  ofloat *inBuffer;\n  olong numTime, ncorr, indx, iindx, lastSourceID, curSourceID;\n  gboolean gotOne, done, isVLA;\n  odouble GSTiat0, DegDay, ArrayX, ArrayY;\n  ofloat dataIat, ArrLong;\n  ofloat startTime, endTime, curTime;\n  ollong visCnt[500], goodCnt[500], badCnt[500], timeCnt[500], timeSou[500];\n  ofloat timeSum[500];\n  odouble dtemp[500];\n  gchar *routine = \"ObitUVUtilCount\";\n\n  /* error checks */\n  if (err->error) return outList;\n  g_assert (ObitUVIsA(inUV));\n\n  /* Initialize sums */\n  numTime = 0;\n  for (i=0; i<500; i++) {\n    visCnt[i] = goodCnt[i] = badCnt[i] = timeCnt[i] = timeSou[i] = 0;\n    timeSum[i] = 0.0;\n  }\n\n  timeInt /= 1440.0;  /* timeInt to days */\n\n  /* Selection of input? */\n  doCalSelect = FALSE;\n  ObitInfoListGetTest(inUV->info, \"doCalSelect\", &type, dim, &doCalSelect);\n  if (doCalSelect) access = OBIT_IO_ReadCal;\n  else access = OBIT_IO_ReadOnly;\n\n  /* Open input */\n  iretCode = ObitUVOpen (inUV, access, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error)) /* add traceback,return */\n    Obit_traceback_val (err, routine, inUV->name, outList);\n  inDesc  = inUV->myDesc;  /* Get descriptor */\n\n  /* Initialize things */\n  startTime = -1.0e20;\n  endTime   =  1.0e20;\n  lastSourceID = -1;\n  curSourceID  = 0;\n  inBuffer = inUV->buffer;\n  ncorr = inDesc->ncorr;\n\n  /* Loop over intervals */\n  done   = FALSE;\n  gotOne = FALSE;\n\n  /* we're in business, average data */\n  while (iretCode==OBIT_IO_OK)  {\n    if ((!gotOne) || (inDesc->numVisBuff<=0)) { /* need to read new record? */\n      if (doCalSelect) iretCode = ObitUVReadSelect (inUV, inUV->buffer, err);\n      else iretCode = ObitUVRead (inUV, inUV->buffer, err);\n      if (iretCode > OBIT_IO_EOF) goto cleanup;\n    }\n\n    /* Are we there yet??? */\n    done = (inDesc->firstVis >= inDesc->nvis) || (iretCode==OBIT_IO_EOF);\n    if (done && (startTime>0.0)) goto process; /* Final? */\n\n    /* Make sure valid data found */\n    if (inUV->myDesc->numVisBuff<=0) continue;\n    iindx = 0;\n\n    /* loop over visibilities in buffer */\n    for (ivis=0; ivis<inDesc->numVisBuff; ivis++) { \n      gotOne = FALSE;\n\n      visCnt[numTime]++;  /* Count vis */\n      curTime = inBuffer[iindx+inDesc->iloct]; /* Time */\n      if (inDesc->ilocsu>=0) curSourceID = inBuffer[iindx+inDesc->ilocsu];\n      if (startTime < -1000.0) {  /* Set time window etc. if needed */\n\tstartTime = curTime;\n\tendTime   = startTime + timeInt;\n\tlastSourceID = curSourceID;\n      }\n\n      /* Still in current interval */\n      if ((curTime<endTime) && (curSourceID == lastSourceID) && \n\t  (inDesc->firstVis<=inDesc->nvis) && (iretCode==OBIT_IO_OK)) {\n\n\t/* sums */\n\ttimeSou[numTime] = curSourceID;\n\ttimeCnt[numTime]++;\n\ttimeSum[numTime] += curTime;\n\tindx = iindx+inDesc->nrparm; /* offset of start of vis data */\n\tfor (i=0; i<ncorr; i++) {\n\t  if (inBuffer[indx+2] > 0.0) goodCnt[numTime]++;\n\t  else badCnt[numTime]++;\n\t  indx += 3;\n\t} /* end loop over correlations */;\n      } else {\n\tnumTime++;  /* new interval */\n\tstartTime = -1.0e20;\n\tendTime   =  1.0e20;\n\t/* Check over run */\n\tObit_retval_if_fail ((numTime<100), err, outList,\n\t\t       \"%s Too many time intervals %d\",  \n\t\t\t     routine, numTime);  \n      }\n      iindx += inDesc->lrec;\n    } /* end loop processing buffer of input data */\n  } /* End loop over input file */\n  \n process:\n  /* Create output */\n  outList  = newObitInfoList();\n\n  /* Get time information */\n  ver = 1;\n  ANTable = newObitTableANValue (inUV->name, (ObitData*)inUV, &ver, \n\t\t\t\t OBIT_IO_ReadOnly, 0, 0, 0, err);\n  GSTiat0 = ANTable->GSTiat0;\n  DegDay  = ANTable->DegDay;\n  ArrayX  = ANTable->ArrayX;\n  ArrayY  = ANTable->ArrayY;\n  if (!strncmp (ANTable->TimeSys, \"IAT\", 3)) {\n    dataIat = 0.0;  /* in IAT */\n  } else {  /* Assume UTC */\n    dataIat = ANTable->dataUtc/86400.0;  /* in days */\n  }\n  isVLA  = !strncmp(ANTable->ArrName, \"VLA     \", 8);\n  ANTable = ObitTableANUnref(ANTable);   /* Done with table */\n  if (err->error) Obit_traceback_val (err, routine, ANTable->name, outList);\n  /* Need longitude */\n  if (isVLA) ArrLong = 1.878283678;\n  else ArrLong = atan2(ArrayY, ArrayX);\n  ArrLong *= RAD2DG;\n\n  /* Average times and convert to LST */\n  numTime++;\n  for (i=0; i<numTime; i++) {\n    if (timeCnt[i]>0) {\n      timeSum[i] /= timeCnt[i];\n      /* To LST in deg */\n      timeSum[i] = ((timeSum[i]-dataIat)*DegDay) + GSTiat0 + ArrLong;\n      timeSum[i] /= 360.0;  /* Back to days */\n    } else timeSum[i] = -1000.0;\n  } /* end loop over time */\n\n  /* save values */\n  ObitInfoListAlwaysPut (outList, \"numTime\", OBIT_long, dim, &numTime);\n  ObitInfoListAlwaysPut (outList, \"numCorr\", OBIT_long, dim, &ncorr);\n  dim[0] = numTime;\n  ObitInfoListAlwaysPut (outList, \"Source\", OBIT_long,     dim, timeSou);\n  ObitInfoListAlwaysPut (outList, \"LST\",    OBIT_float,    dim, timeSum);\n  for (i=0; i<numTime; i++) dtemp[i] = (odouble)goodCnt[i];\n  ObitInfoListAlwaysPut (outList, \"Count\",  OBIT_double,   dim, dtemp);\n  for (i=0; i<numTime; i++) dtemp[i] = (odouble)badCnt[i];\n  ObitInfoListAlwaysPut (outList, \"Bad\",    OBIT_double,   dim, dtemp);\n  for (i=0; i<numTime; i++) dtemp[i] = (odouble)visCnt[i];\n  ObitInfoListAlwaysPut (outList, \"Vis\",    OBIT_double,   dim, dtemp);\n  /* End of processing */\n\n  /* Cleanup */\n cleanup:\n  /* close file */\n  iretCode = ObitUVClose (inUV, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error))\n    Obit_traceback_val (err, routine, inUV->name, outList);\n  \n  return outList;\n} /* end ObitUVUtilCount  */\n\n/**\n * Copy blocks of channels from one UV to a set of output UVs..\n * All selected IFs and polarizations are also copied, there must be\n * an integran number of IFs per output.\n * \\param inUV     Input uv data to average, \n *                 Any request for calibration, editing and selection honored\n * \\param nOut     Number of outout images\n * \\param outUV    Array of previously defined but not yet instantiated \n *                 (never opened) UV data objects to receive 1/nOut \n *                 of the data channels in inUV.\n * \\param err      Error stack, returns if not empty.\n */\nvoid ObitUVUtilSplitCh (ObitUV *inUV, olong nOut, ObitUV **outUV, \n\t\t\tObitErr *err)\n{\n  ObitIOCode iretCode=OBIT_IO_SpecErr, oretCode=OBIT_IO_SpecErr;\n  gboolean doCalSelect;\n  gchar *exclude[]={\"AIPS CL\", \"AIPS SN\", \"AIPS FG\", \"AIPS CQ\", \"AIPS WX\",\n\t\t    \"AIPS AT\", \"AIPS CT\", \"AIPS OB\", \"AIPS IM\", \"AIPS MC\",\n\t\t    \"AIPS PC\", \"AIPS NX\", \"AIPS TY\", \"AIPS GC\", \"AIPS HI\",\n\t\t    \"AIPS PL\", \"AIPS NI\", \"AIPS BP\", \"AIPS OF\", \"AIPS PS\",\n\t\t    \"AIPS FQ\", \"AIPS SU\", \"AIPS AN\", \"AIPS PD\", \"AIPS SY\",\n\t\t    \"AIPS PT\", \"AIPS OT\",\n\t\t    NULL};\n  gchar *sourceInclude[] = {\"AIPS SU\", NULL};\n  olong *BChan=NULL, *numChan=NULL, *BIF=NULL, *numIF=NULL;\n  olong chinc=1, nchan, nif, nchOut, NPIO;\n  olong i, j, indx, jndx, ivis, nIFperOut, oldNumberIF, oldStartIF;\n  ObitInfoType type;\n  gint32 dim[MAXINFOELEMDIM]={1,1,1,1,1};\n  ObitIOAccess access;\n  ObitUVDesc *inDesc, *outDesc;\n  gchar *today=NULL;\n  ofloat *scale = NULL;\n  gchar *routine = \"ObitUVUtilSplitCh\";\n \n  /* error checks */\n  if (err->error) return;\n  g_assert (ObitUVIsA(inUV));\n  for (i=0; i<nOut; i++) {\n    if (!ObitUVIsA(outUV[i])) {\n      Obit_log_error(err, OBIT_Error,\"%s Output %d MUST be defined for non scratch files\",\n\t\t     routine, i);\n      return;\n    }\n  }\n\n  /* Selection/calibration/editing of input? */\n  doCalSelect = FALSE;\n  ObitInfoListGetTest(inUV->info, \"doCalSelect\", &type, dim, &doCalSelect);\n  if (doCalSelect) access = OBIT_IO_ReadCal;\n  else access = OBIT_IO_ReadOnly;\n\n  /* test open to fully instantiate input and see if it's OK */\n  ObitUVFullInstantiate (inUV, TRUE, err);\n  iretCode = ObitUVOpen (inUV, access, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error))\n    Obit_traceback_msg (err, routine, inUV->name);\n\n  /* Get descriptor */\n  inDesc  = inUV->myDesc;\n\n  /* Allocate work arrays */\n  scale   = g_malloc(nOut*sizeof(ofloat));\n  BChan   = g_malloc(nOut*sizeof(olong));\n  numChan = g_malloc(nOut*sizeof(olong));\n  BIF     = g_malloc(nOut*sizeof(olong));\n  numIF   = g_malloc(nOut*sizeof(olong));\n\n  /* Divvy up channels - must be an integral number of IFs per output -\n     or only 1 */\n  nchan = inDesc->inaxes[inDesc->jlocf];\n  if (inDesc->jlocif>=0) nif = inDesc->inaxes[inDesc->jlocif];\n  else                   nif = 1;\n  nIFperOut = (glong) (0.9999 + (nif / (ofloat)nOut));\n  if ((fabs(((ofloat)nIFperOut)-(nif / (ofloat)nOut))>0.001) && (nif>1)) {\n    Obit_log_error(err, OBIT_Error,\"%s Not an equal number of IFs per output\",\n\t\t   routine);\n    return;\n  }\n  if (nOut>(nchan* nIFperOut)) {\n    Obit_log_error(err, OBIT_Error,\"%s Fewer channels, %d than output files %d\",\n\t\t   routine, nchan, nOut);\n    return;\n  }\n  nchOut = (glong) (0.999 + ((nchan*nif) / (ofloat)nOut)); \n  nchOut = MAX (1, nchOut);\n  nchOut = MIN (nchOut, nchan);\n  for (i=0; i<nOut; i++) {\n    BIF[i]     = 1 + i*nIFperOut;\n    numIF[i]   = nIFperOut;\n    BChan[i]   = 1 + i*nchOut - (BIF[i]-1)*nchan;\n    numChan[i] = MIN (nchOut, nchan-BChan[i]+1);\n  }\n\n  /* Set up output UV data */\n  for (i=0; i<nOut; i++) {\n \n    /* copy Descriptor */\n    outUV[i]->myDesc = ObitUVDescCopy(inUV->myDesc, outUV[i]->myDesc, err);\n    \n    /* Creation date today */\n    today = ObitToday();\n    strncpy (outUV[i]->myDesc->date, today, UVLEN_VALUE-1);\n    if (today) g_free(today);\n    \n    /* Get descriptor */\n    outDesc = outUV[i]->myDesc;\n\n    /* Set output frequency info */\n    outDesc->crval[outDesc->jlocf]  = inDesc->crval[outDesc->jlocf] + \n      (BChan[i]-inDesc->crpix[inDesc->jlocf]) * inDesc->cdelt[inDesc->jlocf] +\n      (inDesc->freqIF[BIF[i]-1] - inDesc->freqIF[0]);\n    outDesc->inaxes[outDesc->jlocf] = numChan[i];\n    /*outDesc->crpix[outDesc->jlocf]  = 1.0;*/\n    outDesc->cdelt[outDesc->jlocf]  = inDesc->cdelt[inDesc->jlocf] * chinc;\n    /* UVW scaling parameter */\n    scale[i] = outDesc->crval[outDesc->jlocf]/inDesc->freq;\n    /* IFs */\n    if (outDesc->jlocif>=0) {\n      outDesc->crval[outDesc->jlocif]  = inDesc->crval[outDesc->jlocif] + \n\t(BIF[i]-inDesc->crpix[inDesc->jlocif]) * inDesc->cdelt[inDesc->jlocif];\n      outDesc->inaxes[outDesc->jlocif] = numIF[i];\n      outDesc->crpix[outDesc->jlocif]  = 1.0;\n      outDesc->cdelt[outDesc->jlocif]  = inDesc->cdelt[inDesc->jlocif] * chinc;\n    }\n    /* Alternate frequency/vel */\n    outDesc->altCrpix = inDesc->altCrpix - (BChan[i] + 1.0)/chinc;\n    outDesc->altRef   = inDesc->altRef;\n\n    /* Copy number of records per IO to output */\n    ObitInfoListGet (inUV->info, \"nVisPIO\", &type, dim, (gpointer)&NPIO, err);\n    ObitInfoListAlwaysPut (outUV[i]->info, \"nVisPIO\", type, dim, (gpointer)&NPIO);\n    if (err->error) goto cleanup;\n\n    /* test open output */\n    oretCode = ObitUVOpen (outUV[i], OBIT_IO_WriteOnly, err);\n    /* If this didn't work try OBIT_IO_ReadWrite */\n    if ((oretCode!=OBIT_IO_OK) || (err->error)) {\n      ObitErrClear(err);\n      oretCode = ObitUVOpen (outUV[i], OBIT_IO_ReadWrite, err);\n    }\n    /* if it didn't work bail out */\n    if ((oretCode!=OBIT_IO_OK) || (err->error)) goto cleanup;\n\n    /* Copy tables before data */\n    iretCode = ObitUVCopyTables (inUV, outUV[i], exclude, NULL, err);\n    /* If multisource out then copy SU table, multiple sources selected or\n       sources deselected suggest MS out */\n    if ((inUV->mySel->numberSourcesList>1) || (!inUV->mySel->selectSources))\n      iretCode = ObitUVCopyTables (inUV, outUV[i], NULL, sourceInclude, err);\n    /* Fiddle IF selection */\n    oldNumberIF = inUV->mySel->numberIF;\n    oldStartIF  = inUV->mySel->startIF;\n    inUV->mySel->numberIF = nIFperOut;\n    inUV->mySel->startIF  = BIF[i];\n    ObitTableFQSelect (inUV, outUV[i], NULL, 0.0, err);\n    /* reset IF selection */\n    inUV->mySel->numberIF = oldNumberIF;\n    inUV->mySel->startIF  = oldStartIF;\n    if (err->error) goto cleanup;\n   \n    /* reset to beginning of uv data */\n    iretCode = ObitIOSet (inUV->myIO,  inUV->info, err);\n    oretCode = ObitIOSet (outUV[i]->myIO, outUV[i]->info, err);\n    if (err->error) goto cleanup;\n\n    /* Close and reopen input to init calibration which will have been disturbed \n       by the table copy */\n    iretCode = ObitUVClose (inUV, err);\n    if ((iretCode!=OBIT_IO_OK) || (err->error)) goto cleanup;\n    \n    iretCode = ObitUVOpen (inUV, access, err);\n    if ((iretCode!=OBIT_IO_OK) || (err->error)) goto cleanup;\n    \n  } /* end loop over output files */\n\n  /* we're in business, copy data */\n  while ((iretCode==OBIT_IO_OK) && (oretCode==OBIT_IO_OK)) {\n    if (doCalSelect) iretCode = ObitUVReadSelect (inUV, inUV->buffer, err);\n    else iretCode = ObitUVRead (inUV, inUV->buffer, err);\n    if (iretCode!=OBIT_IO_OK) break;\n\n    /* How many */\n    for (i=0; i<nOut; i++) {\n      outUV[i]->myDesc->numVisBuff = inDesc->numVisBuff;\n    }\n\n    /* Copy data */\n    for (ivis=0; ivis<inDesc->numVisBuff; ivis++) { /* loop over visibilities */\n      /* Copy random parameters */\n      indx = ivis*inDesc->lrec;\n      for (i=0; i<nOut; i++) {\n\tjndx = ivis*outUV[i]->myDesc->lrec;\n\tfor (j=0; j<inDesc->nrparm; j++) \n\t  outUV[i]->buffer[jndx+j] =  inUV->buffer[indx+j];\n \n\t/* Scale u,v,w for new reference frequency */\n\toutUV[i]->buffer[jndx+inDesc->ilocu] *= scale[i];\n\toutUV[i]->buffer[jndx+inDesc->ilocv] *= scale[i];\n\toutUV[i]->buffer[jndx+inDesc->ilocw] *= scale[i];\n     }\n\n      /* Copy visibility */\n      indx += inDesc->nrparm;\n      for (i=0; i<nOut; i++) {\n\tjndx = ivis*outUV[i]->myDesc->lrec + outUV[i]->myDesc->nrparm;\n\tFreqSel (inUV->myDesc, outUV[i]->myDesc, \n\t\t BChan[i], BChan[i]+numChan[i]-1, chinc, BIF[i], BIF[i]+nIFperOut-1,\n\t\t &inUV->buffer[indx], &outUV[i]->buffer[jndx]);\n      }\n    } /* end loop over visibilities */\n\n    /* Write outputs */\n   for (i=0; i<nOut; i++) {\n     oretCode = ObitUVWrite (outUV[i], outUV[i]->buffer, err);\n     if (err->error) goto cleanup;\n   }\n  } /* end loop processing data */\n  \n  /* check for errors */\n  if ((iretCode > OBIT_IO_EOF) || (oretCode > OBIT_IO_EOF) ||\n      (err->error)) goto cleanup;\n\n  /* Cleanup */\n cleanup:\n  if (scale)   g_free(scale);\n  if (BChan)   g_free(BChan);\n  if (numChan) g_free(numChan);\n  if (BIF)     g_free(BIF);\n  if (numIF)   g_free(numIF);\n \n  /* close files */\n  iretCode = ObitUVClose (inUV, err);\n  for (i=0; i<nOut; i++) {\n    oretCode = ObitUVClose (outUV[i], err);\n    if ((iretCode!=OBIT_IO_OK) || (oretCode!=OBIT_IO_OK) || (err->error))\n      Obit_traceback_msg (err, routine, inUV->name);\n  }\n  if (err->error) Obit_traceback_msg (err, routine, inUV->name);\n  \n  return;\n} /* end ObitUVUtilSplitCh */\n\n/**\n * Add Gaussian noise to an UV\n * out = in*scale +  noise (sigma), real, imag, each vis\n * Note: This uses the GSL random number generator, if this is not available\n * then only the scaling is done.\n * \\param inUV  Input UV \n * \\param outUV Output UV, must already be defined but may be inUV\n * \\param scale  scaling factor for data\n * \\param sigma  Standard deviation of Gaussian noise .\n * \\param err    Error stack\n */\nvoid ObitUVUtilNoise(ObitUV *inUV, ObitUV *outUV, ofloat scale, ofloat sigma, \n\t\t     ObitErr *err)\n{\n  ObitIOCode retCode;\n  gboolean doCalSelect, done, same;\n  ObitInfoType type;\n  ObitIOAccess access, oaccess;\n  gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};\n  ofloat val, fblank = ObitMagicF();\n  odouble dsigma = sigma;\n  olong i, j, indx, NPIO, firstVis;\n  ObitUVDesc *inDesc, *outDesc;\n  /* Don't copy Cal and Soln or data or flag tables */\n  gchar *exclude[]={\"AIPS CL\",\"AIPS SN\",\"AIPS FG\",\"AIPS CQ\",\"AIPS WX\",\n\t\t    \"AIPS AT\",\"AIPS CT\",\"AIPS OB\",\"AIPS IM\",\"AIPS MC\",\n\t\t    \"AIPS PC\",\"AIPS NX\",\"AIPS TY\",\"AIPS GC\",\"AIPS HI\",\n\t\t    \"AIPS PL\",\"AIPS NI\",\"AIPS SY\",\"AIPS PT\",\"AIPS OT\",\n\t\t    NULL};\n#if HAVE_GSL==1  /* GSL stuff */\n  gsl_rng *ran=NULL;\n#endif /* HAVE_GSL */\n  gchar *routine = \"ObitUVUtilNoise\";\n\n  /* error checks */\n  g_assert (ObitErrIsA(err));\n  if (err->error) return;\n  g_assert (ObitUVIsA(inUV));\n  g_assert (ObitUVIsA(outUV));\n\n  /* Are input and output the same file? */\n  same = ObitUVSame(inUV, outUV, err);\n  if (err->error) Obit_traceback_msg (err, routine, inUV->name);\n\n  /* Local pointers */\n  inDesc  = inUV->myDesc;\n  outDesc = outUV->myDesc;\n\n  /* Calibration wanted? */ \n  doCalSelect = FALSE;\n  ObitInfoListGetTest(inUV->info, \"doCalSelect\", &type, (gint32*)dim, &doCalSelect);\n  if (doCalSelect) access = OBIT_IO_ReadCal;\n  else access = OBIT_IO_ReadWrite;\n\n /* Open Input Data */\n  retCode = ObitUVOpen (inUV, access, err);\n  if ((retCode != OBIT_IO_OK) || (err->error>0)) \n    Obit_traceback_msg (err, routine, inUV->name);\n\n  /* use same data buffer on input and output.\n     If multiple passes are made the input files will be closed\n     which deallocates the buffer, use output buffer.\n     so free input buffer */\n  if (!same) {\n    /* use same data buffer on input 1 and output \n       so don't assign buffer for output */\n    if (outUV->buffer) ObitIOFreeBuffer(outUV->buffer); /* free existing */\n    outUV->buffer = NULL;\n    outUV->bufferSize = -1;\n  }\n\n   /* Copy number of records per IO to output */\n  ObitInfoListGet (inUV->info, \"nVisPIO\", &type, dim,   (gpointer)&NPIO, err);\n  ObitInfoListPut (outUV->info, \"nVisPIO\",  type, dim,  (gpointer)&NPIO, err);\n  if (err->error) Obit_traceback_msg (err, routine, inUV->name);\n\n  /* Open Output Data */\n  if (same) oaccess = OBIT_IO_ReadWrite;\n  else      oaccess = OBIT_IO_WriteOnly;\n  retCode = ObitUVOpen (outUV, oaccess, err) ;\n  if ((retCode != OBIT_IO_OK) || (err->error>0)) {\n    outUV->buffer = NULL; /* remove pointer to inUV buffer */\n    outUV->bufferSize = 0;\n    Obit_traceback_msg (err, routine, outUV->name);\n  }\n\n  /* Copy tables before data */\n  if (!same) {\n    retCode = ObitUVCopyTables (inUV, outUV, exclude, NULL, err);\n    if (err->error) {/* add traceback,return */\n      outUV->buffer = NULL;\n      outUV->bufferSize = 0;\n      Obit_traceback_msg (err, routine, inUV->name);\n    }\n    \n    /* Close and reopen input to init calibration which will have been disturbed \n       by the table copy */\n    retCode = ObitUVClose (inUV, err);\n    if (err->error) {\n      outUV->buffer = NULL; outUV->bufferSize = 0;\n      Obit_traceback_msg (err, routine, inUV->name);\n    }\n    \n    retCode = ObitUVOpen (inUV, access, err);\n    if ((retCode != OBIT_IO_OK) || (err->error>0)) {\n      outUV->buffer = NULL; outUV->bufferSize = 0;\n      Obit_traceback_msg (err, routine, inUV->name);\n    }\n  } /* end if not same */\n  outUV->buffer = inUV->buffer;\n\n  /* Init random number generator */\n#if HAVE_GSL==1  /* GSL stuff */\n  ran = gsl_rng_alloc(gsl_rng_default);\n#endif /* HAVE_GSL */\n  \n  /* Loop over data */\n  done = (retCode != OBIT_IO_OK);\n  while (!done) {\n    \n    /* read buffer */\n    retCode = ObitUVRead (inUV, NULL, err);\n    if (err->error) {\n      outUV->buffer = NULL; outUV->bufferSize = 0;\n      Obit_traceback_msg (err, routine, inUV->name);\n    }\n    done = (retCode == OBIT_IO_EOF); /* done? */\n    if (done) break;\n\n    /* How many? */\n    outDesc->numVisBuff = inDesc->numVisBuff;\n\n    /* Modify data */\n    for (i=0; i<inDesc->numVisBuff; i++) { /* loop over visibilities */\n      indx = i*inDesc->lrec + inDesc->nrparm;\n      for (j=0; j<inDesc->ncorr; j++) { /* loop over correlations */\n\tif (inUV->buffer[indx]!=fblank) {\n\t  val = inUV->buffer[indx]*scale;\n#if HAVE_GSL==1  /* GSL stuff */\n\t  val += (ofloat)gsl_ran_gaussian (ran, dsigma);\n#endif /* HAVE_GSL */\n\t  inUV->buffer[indx]  = val;\n\t}\n\tif (inUV->buffer[indx+1]!=fblank) {\n\t  val = inUV->buffer[indx+1]*scale;\n#if HAVE_GSL==1  /* GSL stuff */\n\t  val += (ofloat)gsl_ran_gaussian (ran, dsigma);\n#endif /* HAVE_GSL */\n\t  inUV->buffer[indx+1]  = val;\n\t}\n\tindx += inDesc->inaxes[0];\n      } /* end loop over correlations */\n    } /* end loop over visibilities */\n\n    \n    /* Write buffer - if same as input, fiddle first vis value */\n    firstVis = outDesc->firstVis;\n    retCode = ObitUVWrite (outUV, NULL, err);\n    if (same) {\n      outDesc->firstVis = firstVis;\n      ((ObitUVDesc*)(outUV->myIO->myDesc))->firstVis = firstVis;\n    }\n    if (err->error) {\n      outUV->buffer = NULL; outUV->bufferSize = 0;\n      Obit_traceback_msg (err, routine, outUV->name);\n    }\n  } /* end loop over data */\n  \n  /* unset output buffer (may be multiply deallocated ;'{ ) */\n  outUV->buffer = NULL;\n  outUV->bufferSize = 0;\n  \n  /* Free random number generator */\n#if HAVE_GSL==1  /* GSL stuff */\n  gsl_rng_free(ran);\n#endif /* HAVE_GSL */\n  \n  /* Close input */\n  retCode = ObitUVClose (inUV, err);\n  if (err->error) Obit_traceback_msg (err, routine, inUV->name);\n  \n  /* Close output */\n  retCode = ObitUVClose (outUV, err);\n  if (err->error) Obit_traceback_msg (err, routine, outUV->name);\n\n} /* end ObitUVUtilNoise */\n\n/**\n * Adds flagging entry to associated flag table\n * Input values on inUV\n * \\li \"flagVer\"   OBIT_Int (1,1,1) Flagging table version, default = 1\n * \\li \"subA\"      OBIT_Int (1,1,1) Subarray, default = 0\n * \\li \"freqID\"    OBIT_Int (1,1,1) Frequency ID, default = 0\n * \\li \"timeRange\" OBIT_float (2,1,1) Start and stop times to flag (days) def, 0s=all\n * \\li \"Chans\"     OBIT_Int (2,1,1) First and highest channels to flag (1-rel), def, 0=>all\n * \\li \"IFs\"       OBIT_Int (2,1,1) First and highest IF to flag (1-rel), def, 0=>all\n * \\li \"Ants\"      OBIT_Int (2,1,1) first and second antenna  numbers for a baseline, 0=$>$all\n * \\li \"Source\"    OBIT_string (?,1,1) Name of source, def, \"Any\" => all\n * \\li \"Stokes\"    OBIT_string (?,1,1) Stokes to flag, def \" \" = flag all\n *                 \"FFFF\"  where F is '1' to flag corresponding Stokes, '0' not.\n *                 Stokes order 'R', 'L', 'RL' 'LR' or 'X', 'Y', 'XY', 'YX'\n * \\li \"Reason\"    OBIT_string (?,1,1) reason string for flagging (max. 24 char).\n * \\param inUV   Input UV data\n * \\param err     Error stack, returns if not empty.\n * \\return IO return code, OBIT_IO_OK = OK\n */\nObitIOCode ObitUVUtilFlag (ObitUV *inUV, ObitErr *err)\n{\n  ObitIOCode retCode = OBIT_IO_SpecErr;\n  oint iarr[2];\n  olong flagVer, subA, freqID, chans[2], ifs[2], ants[2], SouID;\n  ofloat timerange[2];\n  gchar source[49], stokes[10], reason[49];\n  gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};\n  ObitInfoType type;\n  ObitTableFG    *FlagTable=NULL;\n  ObitTableFGRow *FlagRow=NULL;\n  ObitTableSU    *SourceTable=NULL;\n  gchar *tname, souCode[5];\n  olong ver, iRow, Qual, Number;\n  gboolean xselect;\n  oint numIF;\n  gchar *routine = \"ObitUVUtilFlag\";\n\n  /* error checks */\n  g_assert (ObitErrIsA(err));\n  if (err->error) return retCode;\n  g_assert (ObitUVIsA(inUV));\n\n  /* Get parameters */\n  flagVer = 1;\n  ObitInfoListGetTest(inUV->info, \"flagVer\", &type, dim, &flagVer);\n\n  subA = 0;\n  ObitInfoListGetTest(inUV->info, \"subA\", &type, dim, &subA);\n\n  freqID = 0;\n  ObitInfoListGetTest(inUV->info, \"freqID\", &type, dim, &freqID);\n\n  chans[0] = 1; chans[0] = 0;\n  ObitInfoListGetTest(inUV->info, \"Chans\", &type, dim, chans);\n\n  ifs[0] = 1; ifs[0] = 0;\n  ObitInfoListGetTest(inUV->info, \"IFs\", &type, dim, ifs);\n\n  ants[0] = 1; ants[0] = 0;\n  ObitInfoListGetTest(inUV->info, \"Ants\", &type, dim, ants);\n\n  timerange[0] = -1.0e20;  timerange[1] = 1.0e20;\n  ObitInfoListGetTest(inUV->info, \"timeRange\", &type, dim, timerange);\n  /* default */\n  if ((timerange[0]==0.0) && (timerange[1]==0.0)) {\n    timerange[0] = -1.0e20;\n    timerange[1] =  1.0e20;\n  }\n\n  g_snprintf (source, 48, \"Any\");\n  ObitInfoListGetTest(inUV->info, \"Source\", &type, dim, source);\n  source[dim[0]] = 0;   /* terminate */\n\n  g_snprintf (stokes, 9, \" \");\n  ObitInfoListGetTest(inUV->info, \"Stokes\", &type, dim, stokes);\n  stokes[dim[0]] = 0;   /* terminate */\n\n  g_snprintf (reason, 48, \" \");\n  ObitInfoListGetTest(inUV->info, \"Reason\", &type, dim, reason);\n  reason[dim[0]] = 0;   /* terminate */\n\n  /* Open/close input UV to fully instantiate */\n  retCode = ObitUVOpen (inUV, OBIT_IO_ReadWrite, err);\n  if (err->error) Obit_traceback_val (err, routine, inUV->name, retCode);\n  \n  /* Close */\n  retCode = ObitUVClose (inUV, err);\n  if (err->error) Obit_traceback_val (err, routine, inUV->name, retCode);\n\n  /* Look up Source number if needed */\n  if (strncmp (\"Any\", source, 3)) {\n    /* Instantiate/Create Source Table */\n    retCode = OBIT_IO_ReadErr;\n    tname = g_strconcat (\"SU table for: \",inUV->name, NULL);\n    ver = 1;\n    if (inUV->myDesc->jlocif>=0) numIF = inUV->myDesc->inaxes[inUV->myDesc->jlocif];\n    else numIF = 1;\n    SourceTable = newObitTableSUValue(tname, (ObitData*)inUV, &ver, \n\t\t\t\t      OBIT_IO_ReadWrite, numIF, err);\n    dim[0] = strlen(source);\n    dim[1] = 1;\n    Number = 1;\n    Qual   = -1;\n    sprintf (souCode, \"    \");\n    ObitTableSULookup (SourceTable, dim, source, Qual, souCode, iarr, \n\t\t       &xselect, &Number, err);\n    if (err->error) Obit_traceback_val (err, routine, inUV->name, retCode);\n    SouID = iarr[0];  /* Source ID */\n    SourceTable = ObitTableSUUnref(SourceTable);\n    g_free (tname);\n  } else { /* flag all sources */\n    SouID = 0;\n  }\n\n  /* Instantiate/Create output Flag Table */\n  tname = g_strconcat (\"FG table for: \", inUV->name, NULL);\n  ver = flagVer;\n  FlagTable = newObitTableFGValue(tname, (ObitData*)inUV, &ver, \n\t\t\t\t       OBIT_IO_ReadWrite, err);\n  if (err->error) Obit_traceback_val (err, routine, inUV->name, retCode);\n  g_free (tname);\n\n  /* Open table */\n  retCode = ObitTableFGOpen (FlagTable, OBIT_IO_ReadWrite, err);\n  if (err->error) Obit_traceback_val (err, routine, inUV->name, retCode);\n\n  /* Create Table Row */\n  FlagRow = newObitTableFGRow (FlagTable);\n  \n  /* Attach  row to output buffer */\n  ObitTableFGSetRow (FlagTable, FlagRow, err);\n  if (err->error) Obit_traceback_val (err, routine, inUV->name, retCode);\n\n  /* If there are entries in the table, mark it unsorted */\n  if (FlagTable->myDesc->nrow>0) \n    {FlagTable->myDesc->sort[0]=0; FlagTable->myDesc->sort[1]=0;}\n  \n  /* Fill in Flag row */\n  FlagRow->SourID = SouID;\n  FlagRow->SubA   = subA;\n  FlagRow->freqID = freqID;\n  FlagRow->TimeRange[0] = timerange[0];\n  FlagRow->TimeRange[1] = timerange[1];\n  FlagRow->ants[0]  = ants[0];\n  FlagRow->ants[1]  = ants[1];\n  FlagRow->chans[0] = chans[0];\n  FlagRow->chans[1] = chans[1];\n  FlagRow->ifs[0]   = ifs[0];\n  FlagRow->ifs[1]   = ifs[1];\n  FlagRow->pFlags[0] = 0;\n  strncpy (FlagRow->reason, reason, 24);\n  if (stokes[0]==' ') {\n    FlagRow->pFlags[0] = 15;\n  } else {\n    if (stokes[0]!='0') FlagRow->pFlags[0] += 1;\n    if (stokes[1]!='0') FlagRow->pFlags[0] += 2;\n    if (stokes[2]!='0') FlagRow->pFlags[0] += 4;\n    if (stokes[3]!='0') FlagRow->pFlags[0] += 8;\n  }\n  \n  /* write row */\n  iRow = FlagTable->myDesc->nrow+1;\n  retCode =  ObitTableFGWriteRow (FlagTable, iRow, FlagRow, err);\n  if (err->error) Obit_traceback_val (err, routine, inUV->name, retCode);\n   \n  /* Close Flag table */\n  retCode =  ObitTableFGClose (FlagTable, err);\n  if (err->error) Obit_traceback_val (err, routine, inUV->name, retCode);\n\n  /* Cleanup */\n  FlagTable = ObitTableFGUnref(FlagTable);\n  FlagRow   = ObitTableFGRowUnref(FlagRow);\n\n  return retCode;\n} /* end ObitUVUtilFlag */\n\n/**\n * Make copy of ObitUV with the u,v,w terms calculated\n * \\param inUV     Input uv data to copy. \n * \\param outUV    If not scratch, then the previously defined output file\n *                 May be NULL for scratch only\n *                 If it exists and scratch, it will be Unrefed\n * \\param err      Error stack, returns if not empty.\n */\nvoid ObitUVUtilCalcUVW (ObitUV *inUV, ObitUV *outUV,  ObitErr *err)\n{\n  ObitIOCode iretCode, oretCode;\n  gboolean doCalSelect;\n  gchar *exclude[]={\"AIPS CL\",\"AIPS SN\",\"AIPS FG\",\"AIPS CQ\",\"AIPS WX\",\n\t\t    \"AIPS AT\",\"AIPS CT\",\"AIPS OB\",\"AIPS IM\",\"AIPS MC\",\n\t\t    \"AIPS PC\",\"AIPS NX\",\"AIPS TY\",\"AIPS GC\",\"AIPS HI\",\n\t\t    \"AIPS PL\",\"AIPS NI\",\"AIPS OT\",\n\t\t    NULL};\n  gchar *sourceInclude[] = {\"AIPS SU\", NULL};\n  ObitUVWCalc *uvwCalc=NULL;\n  olong i, indx, SId, subA, ant1, ant2;\n  ofloat uvw[3];\n  ObitInfoType type;\n  gint32 dim[MAXINFOELEMDIM];\n  ObitIOAccess access;\n  ObitUVDesc *inDesc, *outDesc;\n  gchar *today=NULL;\n  gchar *routine = \"ObitUVUtilCopyZero\";\n \n  /* error checks */\n  g_assert (ObitErrIsA(err));\n  if (err->error) return;\n  g_assert (ObitUVIsA(inUV));\n  if (outUV==NULL) {\n    Obit_log_error(err, OBIT_Error,\"%s Output MUST be defined\",\n\t\t   routine);\n      return;\n  }\n\n  /* Selection of input? */\n  doCalSelect = FALSE;\n  ObitInfoListGetTest(inUV->info, \"doCalSelect\", &type, (gint32*)dim, &doCalSelect);\n  if (doCalSelect) access = OBIT_IO_ReadCal;\n  else access = OBIT_IO_ReadOnly;\n\n  /* test open to fully instantiate input and see if it's OK */\n  iretCode = ObitUVOpen (inUV, access, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error)) /* add traceback,return */\n    Obit_traceback_msg (err, routine, inUV->name);\n\n  /* copy Descriptor */\n  outUV->myDesc = ObitUVDescCopy(inUV->myDesc, outUV->myDesc, err);\n\n  /* Creation date today */\n  today = ObitToday();\n  strncpy (outUV->myDesc->date, today, UVLEN_VALUE-1);\n  if (today) g_free(today);\n  \n  /* use same data buffer on input and output \n     so don't assign buffer for output */\n  if (outUV->buffer) ObitIOFreeBuffer(outUV->buffer); /* free existing */\n  outUV->buffer = NULL;\n  outUV->bufferSize = -1;\n\n  /* test open output */\n  oretCode = ObitUVOpen (outUV, OBIT_IO_WriteOnly, err);\n  /* If this didn't work try OBIT_IO_ReadWrite */\n  if ((oretCode!=OBIT_IO_OK) || (err->error)) {\n    ObitErrClear(err);\n    oretCode = ObitUVOpen (outUV, OBIT_IO_ReadWrite, err);\n  }\n  /* if it didn't work bail out */\n  if ((oretCode!=OBIT_IO_OK) || (err->error)) {\n    /* unset output buffer (may be multiply deallocated) */\n    outUV->buffer = NULL;\n    outUV->bufferSize = 0;\n    Obit_traceback_msg (err, routine, outUV->name);\n  }\n\n  /* iretCode = ObitUVClose (inUV, err); DEBUG */\n  /* Copy tables before data */\n  iretCode = ObitUVCopyTables (inUV, outUV, exclude, NULL, err);\n  /* If multisource out then copy SU table, multiple sources selected or\n   sources deselected suggest MS out */\n  if ((inUV->mySel->numberSourcesList>1) || (!inUV->mySel->selectSources))\n  iretCode = ObitUVCopyTables (inUV, outUV, NULL, sourceInclude, err);\n  if (err->error) {\n    outUV->buffer = NULL;\n    outUV->bufferSize = 0;\n    Obit_traceback_msg (err, routine, inUV->name);\n  }\n\n  /* reset to beginning of uv data */\n  iretCode = ObitIOSet (inUV->myIO,  inUV->info, err);\n  oretCode = ObitIOSet (outUV->myIO, outUV->info, err);\n  if (err->error) Obit_traceback_msg (err, routine,inUV->name);\n\n  /* Close and reopen input to init calibration which will have been disturbed \n     by the table copy */\n  iretCode = ObitUVClose (inUV, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error))\n    Obit_traceback_msg (err, routine,inUV->name);\n\n  iretCode = ObitUVOpen (inUV, access, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error)) \n    Obit_traceback_msg (err, routine,inUV->name);\n  outUV->buffer = inUV->buffer;\n\n  /* Get descriptors */\n  inDesc  = inUV->myDesc;\n  outDesc = outUV->myDesc;\n  SId = 0;   /* In case single source */\n\n  uvwCalc = ObitUVWCalcCreate(\"UVWCalc\", outUV, err);\n  if (err->error) Obit_traceback_msg (err, routine, outUV->name);\n\n  /* we're in business, copy, recompute u,v,w */\n  while ((iretCode==OBIT_IO_OK) && (oretCode==OBIT_IO_OK)) {\n    if (doCalSelect) iretCode = ObitUVReadSelect (inUV, inUV->buffer, err);\n    else iretCode = ObitUVRead (inUV, inUV->buffer, err);\n    if (iretCode!=OBIT_IO_OK) break;\n   /* How many */\n    outDesc->numVisBuff = inDesc->numVisBuff;\n\n    /* Modify data */\n    for (i=0; i<inDesc->numVisBuff; i++) { /* loop over visibilities */\n      indx = i*inDesc->lrec;\n      if (inUV->myDesc->ilocsu>=0) \n\tSId = (olong)(inUV->buffer[indx+inUV->myDesc->ilocsu] + 0.5);\n      ObitUVDescGetAnts(inUV->myDesc, &inUV->buffer[indx], &ant1, &ant2, &subA);\n      ObitUVWCalcUVW(uvwCalc, inUV->buffer[indx+inDesc->iloct], SId, \n\t\t     subA, ant1, ant2, uvw, err);\n      inUV->buffer[indx+inDesc->ilocu] = uvw[0];\n      inUV->buffer[indx+inDesc->ilocv] = uvw[1];\n      inUV->buffer[indx+inDesc->ilocw] = uvw[2];\n    } /* end loop over visibilities */\n\n    /* Write */\n    oretCode = ObitUVWrite (outUV, inUV->buffer, err);\n    if (err->error) {\n      uvwCalc = ObitUVWCalcUnref(uvwCalc);\n      Obit_traceback_msg (err, routine,inUV->name);\n    }\n  } /* end loop processing data */\n  \n  /* check for errors */\n  if ((iretCode > OBIT_IO_EOF) || (oretCode > OBIT_IO_EOF) ||\n      (err->error)) /* add traceback,return */\n    Obit_traceback_msg (err, routine,inUV->name);\n  \n  /* unset input buffer (may be multiply deallocated ;'{ ) */\n  outUV->buffer = NULL;\n  outUV->bufferSize = 0;\n  \n  uvwCalc = ObitUVWCalcUnref(uvwCalc);  /* Cleanup */\n\n  /* close files */\n  iretCode = ObitUVClose (inUV, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error)) \n    Obit_traceback_msg (err, routine, inUV->name);\n  \n  oretCode = ObitUVClose (outUV, err);\n  if ((oretCode!=OBIT_IO_OK) || (err->error))\n    Obit_traceback_msg (err, routine, outUV->name);\n  \n  return;\n} /* end ObitUVUtilCalcUVW */\n\n/**\n * Compute low precision  visibility uvw\n * \\param b    Baseline vector\n * \\param dec  Pointing declination (rad)\n * \\param ha   Pointing hour angle (rad)\n * \\param uvw  [out] baseline u,v,w in units of b\n */\nvoid ObitUVUtilUVW(const ofloat b[3], odouble dec, ofloat ha, ofloat uvw[3])\n{\n  odouble cosdec, sindec;\n  ofloat     sinha, cosha, vw;\n\n  cosdec = cos (dec);\n  sindec = sin (dec);\n  cosha = cos (ha);\n  sinha = sin (ha);\n  vw = b[0]*cosha - b[1]*sinha;\n  uvw[0] =  b[0]*sinha + b[1]*cosha;\n  uvw[1] = -vw*sindec + b[2]*cosdec;\n  uvw[2] =  vw*cosdec + b[2]*sindec;\n} /* end  ObitUVUtilUVW */\n\n/**\n * Append the contents of one UV onto the end of another\n * \\param inUV  Input UV \n * \\param outUV Output UV, must already be defined\n * \\param err    Error stack\n */\nvoid ObitUVUtilAppend(ObitUV *inUV, ObitUV *outUV, ObitErr *err)\n{\n  ObitIOCode retCode;\n  gboolean doCalSelect, done;\n  ObitInfoType type;\n  ObitIOAccess access;\n  gboolean incompatible;\n  gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};\n  ObitUVDesc *inDesc, *outDesc;\n  olong inNPIO, outNPIO, NPIO;\n  gchar *routine = \"ObitUVUtilAppend\";\n\n  /* error checks */\n  if (err->error) return;\n  g_assert (ObitUVIsA(inUV));\n  g_assert (ObitUVIsA(outUV));\n\n  /* Get input descriptors */\n  inDesc  = inUV->myDesc;\n  outDesc = outUV->myDesc;\n\n  /* Check compatability between inUV, outUV */\n  incompatible = (inDesc->ncorr!=outDesc->ncorr);\n  incompatible = incompatible || (inDesc->jlocs!=outDesc->jlocs);\n  incompatible = incompatible || (inDesc->jlocf!=outDesc->jlocf);\n  incompatible = incompatible || (inDesc->jlocif!=outDesc->jlocif);\n  incompatible = incompatible || (inDesc->ilocb!=outDesc->ilocb);\n  if (incompatible) {\n     Obit_log_error(err, OBIT_Error,\"%s inUV and outUV have incompatible structures\",\n\t\t   routine);\n      return ;\n }\n  /* Calibration wanted? */ \n  doCalSelect = FALSE;\n  ObitInfoListGetTest(inUV->info, \"doCalSelect\", &type, dim, &doCalSelect);\n  if (doCalSelect) access = OBIT_IO_ReadCal;\n  else access = OBIT_IO_ReadWrite;\n\n  /* Set number of vis per I/O */\n  inNPIO = 1000;\n  ObitInfoListGetTest (inUV->info, \"nVisPIO\", &type, dim, &inNPIO);\n  outNPIO = 1000;\n  ObitInfoListGetTest (outUV->info, \"nVisPIO\", &type, dim, &outNPIO);\n  NPIO = 1000; dim[0] = dim[1] = dim[2] = 1;\n  ObitInfoListAlwaysPut (inUV->info,  \"nVisPIO\", OBIT_long, dim,  &NPIO);\n  ObitInfoListAlwaysPut (outUV->info, \"nVisPIO\", OBIT_long, dim,  &NPIO);\n\n  /* Open Input Data */\n  retCode = ObitUVOpen (inUV, access, err);\n  if ((retCode != OBIT_IO_OK) || (err->error>0)) \n    Obit_traceback_msg (err, routine, inUV->name);\n  \n  /* use same data buffer on input and output \n     so don't assign buffer for output */\n  if (outUV->buffer) ObitIOFreeBuffer(outUV->buffer); /* free existing */\n  outUV->buffer     = inUV->buffer;\n  outUV->bufferSize = inUV->bufferSize;\n\n  /* Open Output Data */\n  retCode = ObitUVOpen (outUV, OBIT_IO_ReadWrite, err) ;\n  if ((retCode != OBIT_IO_OK) || (err->error>0)) {\n    outUV->buffer = NULL; /* remove pointer to inUV buffer */\n    outUV->bufferSize = 0;\n    Obit_traceback_msg (err, routine, outUV->name);\n  }\n  outDesc->firstVis = outDesc->nvis+1; /* Write to end */\n\n  /* Loop over data */\n  done = (retCode != OBIT_IO_OK);\n  while (!done) {\n    \n    /* read buffer */\n    retCode = ObitUVRead (inUV, NULL, err);\n    if (err->error) {\n      outUV->buffer = NULL; outUV->bufferSize = 0;\n      Obit_traceback_msg (err, routine, inUV->name);\n    }\n    done = (retCode == OBIT_IO_EOF); /* done? */\n    if (done) break;\n\n    /* How many? */\n    outDesc->numVisBuff = inDesc->numVisBuff;\n   \n    /* Write buffer */\n    retCode = ObitUVWrite (outUV, NULL, err);\n    if (err->error) {\n      outUV->buffer = NULL; outUV->bufferSize = 0;\n      Obit_traceback_msg (err, routine, outUV->name);\n    }\n  } /* end loop over data */\n  \n  /* unset output buffer (may be multiply deallocated ;'{ ) */\n  outUV->buffer = NULL;\n  outUV->bufferSize = 0;\n  \n  /* Close input */\n  retCode = ObitUVClose (inUV, err);\n  if (err->error) Obit_traceback_msg (err, routine, inUV->name);\n  \n  /* Close output */\n  retCode = ObitUVClose (outUV, err);\n  if (err->error) Obit_traceback_msg (err, routine, outUV->name);\n\n  /* Reset number of vis per I/O */\n  ObitInfoListAlwaysPut (inUV->info,  \"nVisPIO\", OBIT_long, dim,  &inNPIO);\n  ObitInfoListAlwaysPut (outUV->info, \"nVisPIO\", OBIT_long, dim,  &outNPIO);\n\n} /* end ObitUVUtilAppend */\n\n#ifndef VELIGHT\n#define VELIGHT 2.997924562e8\n#endif /* VELIGHT */\n/**\n *  How many channels can I average\n * \\param inUV    Input UV \n * \\param maxFact Maximum allowed bandwith smearing amplitude loss\n * \\param FOV     Radius of desired FOV (deg)\n * \\param err     Error stack\n */\nolong ObitUVUtilNchAvg(ObitUV *inUV, ofloat maxFact, ofloat FOV, ObitErr *err)\n{\n  olong out=1;\n  ObitIOCode iretCode;\n  ObitUVDesc *inDesc;\n  ObitTableAN *ANTable=NULL;\n  ObitAntennaList **AntList=NULL;\n  olong i, j, numSubA, iANver, numIF, numOrb, numPCal;\n  ofloat chBW, maxBL, BL, fact, beta, tau;\n  gchar *routine = \"ObitUVUtilNchAv\";\n\n  /* error checks */\n  if (err->error) return out;\n  g_assert (ObitUVIsA(inUV));\n\n  /* test open to fully instantiate input and see if it's OK */\n  ObitUVFullInstantiate (inUV, TRUE, err);\n  iretCode = ObitUVOpen (inUV, OBIT_IO_ReadCal, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error))\n    Obit_traceback_val (err, routine, inUV->name, out);\n\n  /* Get descriptor */\n  inDesc = inUV->myDesc;\n\n  /* Channel bandwidth */\n  chBW = inDesc->cdelt[inDesc->jlocf];\n\n  /* Antenna List \n     How many AN tables (no. subarrays)?  */\n  numSubA = ObitTableListGetHigh (inUV->tableList, \"AIPS AN\");\n  AntList = g_malloc0(numSubA*sizeof(ObitAntennaList*));\n  maxBL = 0.0;\n\n  /* Loop over AN tables (subarrays) */\n  for (iANver=1; iANver<=numSubA; iANver++) {\n    numOrb   = 0;\n    numPCal  = 0;\n    numIF    = 0;\n\n    ANTable = newObitTableANValue (\"AN table\", (ObitData*)inUV, \n\t\t\t\t   &iANver, OBIT_IO_ReadOnly, numIF, numOrb, numPCal, err);\n    if (ANTable==NULL) Obit_log_error(err, OBIT_Error, \"ERROR with AN table\");\n    AntList[iANver-1] = ObitTableANGetList (ANTable, err);\n    if (err->error) Obit_traceback_val (err, routine, inUV->name, out);\n    \n    /* Cleanup */\n    ANTable = ObitTableANUnref(ANTable);\n\n    /* Find maximum baseline */\n    for (i=0; i<AntList[iANver-1]->number-1; i++) {\n      /* Antenna in array? */\n      if ((fabs(AntList[iANver-1]->ANlist[i]->AntXYZ[0]<1.0)) &&\n\t   (fabs(AntList[iANver-1]->ANlist[i]->AntXYZ[1]<1.0)) &&\n\t  (fabs(AntList[iANver-1]->ANlist[i]->AntXYZ[2]<1.0))) continue;\n      for (j=i+1; j<AntList[iANver-1]->number; j++) {\n\t/* Antenna in array? */\n\tif ((fabs(AntList[iANver-1]->ANlist[j]->AntXYZ[0]<1.0)) &&\n\t    (fabs(AntList[iANver-1]->ANlist[j]->AntXYZ[1]<1.0)) &&\n\t    (fabs(AntList[iANver-1]->ANlist[j]->AntXYZ[2]<1.0))) continue;\n\tBL = \n\t  (AntList[iANver-1]->ANlist[i]->AntXYZ[0]-AntList[iANver-1]->ANlist[j]->AntXYZ[0]) *\n\t  (AntList[iANver-1]->ANlist[i]->AntXYZ[0]-AntList[iANver-1]->ANlist[j]->AntXYZ[0]) + \n\t  (AntList[iANver-1]->ANlist[i]->AntXYZ[1]-AntList[iANver-1]->ANlist[j]->AntXYZ[1]) *\n\t  (AntList[iANver-1]->ANlist[i]->AntXYZ[1]-AntList[iANver-1]->ANlist[j]->AntXYZ[1]) + \n\t  (AntList[iANver-1]->ANlist[i]->AntXYZ[2]-AntList[iANver-1]->ANlist[j]->AntXYZ[2]) *\n\t  (AntList[iANver-1]->ANlist[i]->AntXYZ[2]-AntList[iANver-1]->ANlist[j]->AntXYZ[2]);\n\tmaxBL = MAX (maxBL, BL);\n      }\n    }\n  } /* End loop over subarrays */\n  maxBL = sqrt(maxBL);\n  /* Cleanup */\n  if (AntList) {\n    for (i=0; i<numSubA; i++) {\n      AntList[i] = ObitAntennaListUnref(AntList[i]);\n    }\n    g_free(AntList);\n  }\n\n  /* Close up */\n  iretCode = ObitUVClose (inUV, err);\n  if ((iretCode!=OBIT_IO_OK) || (err->error)) \n    Obit_traceback_val (err, routine, inUV->name, out);\n\n  /* Calculate number of channels to average */\n  tau = sin(FOV*DG2RAD) * maxBL / VELIGHT;  /* Maximum delay across FOV */\n  for (i=2; i<=inDesc->inaxes[inDesc->jlocf]; i++) {\n    beta = i * chBW;\n    fact = (G_PI*beta*tau) / fabs(sin(G_PI*beta*tau));\n    if (fact>maxFact) break;\n    out = i;\n  }\n  \n  return out;\n} /* end ObitUVUtilNchAvg */\n\n/*----------------------Private functions---------------------------*/\n/**\n * Count channels after selection and averaging and modify descriptor.\n * Also determines arrays giving the channel, IF and stokes of each correlator\n * \\param inDesc   Input UV descriptor\n * \\param outDesc  Output UV descriptor to be modified\n * \\param NumChAvg Number of channels to average\n * \\param ChanSel  Groups of channels/IF in input to be averaged together\n *                 (start, end, increment, IF) where start and end at the \n *                 beginning and ending channel numbers (1-rel) of the group\n *                 to be averaged together, increment is the increment between\n *                 selected channels and IF is the IF number (1-rel)\n *                 ChanSel is ignored if NumChAvg is given and > 0.\n *                 default increment is 1, IF=0 means all IF.\n *                 The list of groups is terminated by a start <=0\n * \\param doAvgAll If true all channels and IFs to be averaged together\n * \\param corChan  [out] 0-rel output channel numbers\n *                 Should be externally allocated to at least the number of correlators\n * \\param corIF    [out] 0-rel output IF numbers\n *                 Should be externally allocated to at least the number of correlators\n * \\param corStok  [out] 0-rel output Stokes parameter code.\n *                 Should be externally allocated to at least the number of correlators\n * \\param corMask  [out] Array of masks per correlator for selected channels/IFs\n *                 Should be externally allocated to at least the number of correlators\n * \\param err      Error stack, returns if not empty.\n * \\return scaling factor for U,V,W to new reference frequency\n */\nstatic ofloat AvgFSetDesc (ObitUVDesc *inDesc, ObitUVDesc *outDesc, \n\t\t\t   olong NumChAvg, olong *ChanSel, gboolean doAvgAll, \n\t\t\t   olong *corChan, olong *corIF, olong *corStok, gboolean *corMask,\n\t\t\t   ObitErr *err)\n{\n  ofloat scale = 1.0;\n  olong i, ii, count, count2, NumIFAvg, numChan = 1, numIF = 1;\n  olong ichan, iif, istok, nchan, nif, nstok;\n  olong incs, incf, incif, ioff, lfoff, soff;\n  olong *selTemp;\n  olong *tcorChan=NULL, *tcorIF=NULL;\n  gboolean more, match;\n  odouble oldFreq, sum, sum2;\n\n  /* error checks */\n  if (err->error) return scale;\n  g_assert(ObitUVDescIsA(inDesc));\n  g_assert(ObitUVDescIsA(outDesc));\n\n  /* Set up for parsing data */\n  nchan = inDesc->inaxes[inDesc->jlocf];\n  if (inDesc->jlocif>=0) nif = inDesc->inaxes[inDesc->jlocif];\n  else nif = 1;\n  if (inDesc->jlocs>=0) nstok = inDesc->inaxes[inDesc->jlocs];\n  else nstok = 1;\n\n  numChan = 1 + (nchan-1) / MAX (1, NumChAvg);  /* Number of output channels */\n  /* IF averaging */\n  NumIFAvg   = 1;\n  if (doAvgAll) NumIFAvg   = nif;\n\n  /* Enforce ChanSel Limits */\n  selTemp = ChanSel;\n  more = selTemp[1]>0;\n  while (more) {\n    if (selTemp[0]<1)       selTemp[0] = 1;\n    if (selTemp[1]>nchan)   selTemp[1] = nchan;\n    if (selTemp[2]<1)       selTemp[2] = 1;\n    if (selTemp[3]<0)       selTemp[3] = 0;\n    if (selTemp[3]>nif)     selTemp[3] = nif;\n    selTemp += 4;\n    more = selTemp[1]>0;\n  } /* end loop enforcing limits */\n\n  /* get increments (one word per correlator) */\n  incs  = inDesc->incs  / inDesc->inaxes[0];\n  incf  = inDesc->incf  / inDesc->inaxes[0];\n  incif = inDesc->incif / inDesc->inaxes[0];\n\n  /* temp arrays */\n  tcorChan = g_malloc0(inDesc->ncorr*sizeof(olong));\n  tcorIF   = g_malloc0(inDesc->ncorr*sizeof(olong));\n\n  /* loop over IF */\n  for (iif=0; iif<nif; iif++) {\n    lfoff = iif * incif;\n    ioff  = lfoff;\n    \n    /* Loop over frequency channel */\n    for (ichan=0; ichan<nchan; ichan++) { /* loop 60 */\n      soff = ioff;\n\n      /* Loop over polarization */\n      for (istok=0; istok<nstok; istok++) {\n\tcorChan[soff]  = (ichan/NumChAvg); \n\tcorIF[soff]    = (iif/NumIFAvg); \n\tcorStok[soff]  = istok;\n\tcorMask[soff]  = FALSE;\n\ttcorChan[soff] = (ichan); \n\ttcorIF[soff]   = (iif); \n\n\t/* Is this correlator/IF in ChanSel? */\n\tselTemp = ChanSel;\n\tmore = selTemp[1]>0;\n\twhile (more) {\n\t  /* In IF range? */\n\t  if ((selTemp[3]<=0) || (selTemp[3]==(iif+1))) {\n\t    if ((selTemp[0]<=(ichan+1)) && (selTemp[1]>=(ichan+1))) {\n\t      /* Desired channel? */\n\t      match = (selTemp[2]<=1) || (((ichan-selTemp[0])%(selTemp[2]))==0);\n\t      corMask[soff] = match;\n\t    } /* end channel range */\n\t  } /* end IF range */\n\t  selTemp += 4;\n\t  more = selTemp[1]>0;\n\t}\n\tsoff += incs;\n      } /* end loop over stokes */\n      ioff  += incf;     \n    } /* end loop over channel */\n  } /* end loop over IF */\n\n  /* Averaging all channels/IF? */\n  if (doAvgAll) {\n    outDesc->inaxes[outDesc->jlocf] = nchan;\n    /* Average all frequencies */\n    sum  = 0.0; count  = 0;\n    sum2 = 0.0; count2 = 0;\n    for (i=0; i<inDesc->ncorr; i++) {\n      ii = tcorChan[i] + tcorIF[i]*nchan;\n      sum2 += inDesc->freqArr[ii];\n      count2++;\n      if (corMask[i]) {\n\tsum += inDesc->freqArr[ii];\n\tcount++;\n      }\n    } /* end loop over correlators */\n\n    if (count>0)\n      outDesc->crval[outDesc->jlocf] = sum / (ofloat)count;\n    else if (count2>0)\n      outDesc->crval[outDesc->jlocf] = sum2 / (ofloat)count2;\n    outDesc->inaxes[outDesc->jlocf] = numChan;\n    outDesc->crpix[outDesc->jlocf] = 1.0;\n    outDesc->cdelt[outDesc->jlocf] = \n      inDesc->cdelt[inDesc->jlocf] * inDesc->inaxes[inDesc->jlocf];\n    if (outDesc->jlocif>=0) {\n      outDesc->inaxes[outDesc->jlocif] = numIF;\n      outDesc->crval[outDesc->jlocif] = 1.0;\n      outDesc->crpix[outDesc->jlocif] = 1.0;\n      outDesc->cdelt[outDesc->jlocif] = 1.0;\n    }\n    /* Alternate frequency/vel */\n    outDesc->altCrpix = 1.0;\n    outDesc->altRef   = inDesc->altRef;\n\n    return scale;\n  } /* End doAvgAll */\n\n  /* Averaging channels  - IFs unaffected */\n  numChan = 1 + ((inDesc->inaxes[inDesc->jlocf]-1) / NumChAvg);\n  /* Get frequency of first average */\n  sum  = 0.0; count  = 0;\n  sum2 = 0.0; count2 = 0;\n  ii = -1;\n  for (i=0; i<inDesc->ncorr; i++) {\n    if ((corChan[i]>0) || (corStok[i]>0) || (corIF[i]>0)) continue;  /* want? */\n    ii++;\n    sum2 += inDesc->freqArr[ii];\n    count2++;\n    if (corMask[i]) {\n      sum += inDesc->freqArr[ii];      count++;\n    }\n  } /* end loop over correlators */\n\n  oldFreq = outDesc->crval[outDesc->jlocf]; /* Save old reference freq */\n  outDesc->inaxes[outDesc->jlocf] = numChan;\n  if (count>0)\n    outDesc->crval[outDesc->jlocf]  = sum / (ofloat)count;\n  else if (count2>0)\n    outDesc->crval[outDesc->jlocf]  = sum2 / (ofloat)count2;\n  outDesc->crpix[outDesc->jlocf]  = 1.0;\n  outDesc->cdelt[outDesc->jlocf]  = inDesc->cdelt[inDesc->jlocf] * NumChAvg;\n\n  /* Frequency scaling */\n  scale = outDesc->crval[outDesc->jlocf]/oldFreq;\n\n  /* Alternate frequency/vel */\n  outDesc->altCrpix = 1.0 + (outDesc->altCrpix-1.0)/NumChAvg;\n  outDesc->altRef   = inDesc->altRef;\n\n  /* Cleanup */\n  if (tcorChan) g_free(tcorChan);\n  if (tcorIF) g_free(tcorIF);\n\n  return scale;\n  \n} /* end AvgFSetDesc */\n\n/**\n * Modify descriptor for duplicatiing channels\n * \\param inDesc   Input UV descriptor\n * \\param outDesc  Output UV descriptor to be modified, assumed mostly copied.\n * \\param nBloat   Number of time to duplicate channels \n * \\param err      Error stack, returns if not empty.\n * \\return scaling factor for U,V,W to new reference frequency\n */\nstatic ofloat BloatFSetDesc (ObitUVDesc *inDesc, ObitUVDesc *outDesc, \n\t\t\t     olong nBloat, ObitErr *err)\n{\n  olong nchan;\n  ofloat scale = 1.0;\n\n  /* error checks */\n  if (err->error) return scale;\n  g_assert(ObitUVDescIsA(inDesc));\n  g_assert(ObitUVDescIsA(outDesc));\n\n  /* Modify */\n  nchan = (inDesc->inaxes[inDesc->jlocf]+nBloat-1) * nBloat;\n  outDesc->inaxes[outDesc->jlocf] = nchan;\n  outDesc->cdelt[outDesc->jlocf]  = inDesc->cdelt[inDesc->jlocf] / nBloat;\n  outDesc->crval[outDesc->jlocf]  = inDesc->crval[inDesc->jlocf] - \n    0.5 * outDesc->cdelt[outDesc->jlocf];\n  scale = outDesc->crval[outDesc->jlocf] / inDesc->crval[inDesc->jlocf];\n\n  /* Alternate frequency/vel */\n  outDesc->altCrpix = 1.0 + (outDesc->altCrpix-1.0)*nBloat;\n  outDesc->altRef   = inDesc->altRef;\n\n  return scale;\n  \n} /* end BloatFSetDesc */\n\n/**\n * Average visibility in frequency\n * \\param inDesc    Input UV descriptor\n * \\param outDesc   Output UV descriptor to be modified\n * \\param NumChAvg  Number of channels to average\n * \\param ChanSel   Groups of channels/IF in input to be averaged together\n *                  (start, end, increment, IF) where start and end at the \n *                  beginning and ending channel numbers (1-rel) of the group\n *                  to be averaged together, increment is the increment between\n *                  selected channels and IF is the IF number (1-rel)\n *                  ChanSel is ignored if NumChAvg is given and > 0.\n *                  default increment is 1, IF=0 means all IF.\n *                  The list of groups is terminated by a start <=0\n *                  corMask actually used to select.\n * \\param doAvgAll  If true all channels and IFs to be averaged together\n * \\param corChan  0-rel output channel numbers\n * \\param corIF    0-rel output IF numbers\n * \\param corStok  0-rel output Stokes parameter code.\n * \\param corMask  Array of masks per correlator for selected channels/IFs\n *                 TRUE => select\n * \\param inBuffer  Input buffer (data matrix)\n * \\param outBuffer Output buffer (data matrix)\n * \\param work      Work array twice the size of the output visibility\n * \\param err       Error stack, returns if not empty.\n */\nstatic void AvgFAver (ObitUVDesc *inDesc, ObitUVDesc *outDesc, \n\t\t      olong NumChAvg, olong *ChanSel, gboolean doAvgAll, \n\t\t      olong *corChan, olong *corIF, olong *corStok, gboolean *corMask,\n\t\t      ofloat *inBuffer, ofloat *outBuffer, ofloat *work, \n\t\t      ObitErr *err)\n{\n  olong i, n, indx, jndx, jf, jif, js, nochan, noif;\n  olong nchan, nif, nstok, incs, incf, incif;\n\n  /* error checks */\n  if (err->error) return;\n\n  nchan = inDesc->inaxes[inDesc->jlocf];\n  if (inDesc->jlocif>=0) nif = inDesc->inaxes[inDesc->jlocif];\n  else nif = 1;\n  if (inDesc->jlocs>=0) nstok = inDesc->inaxes[inDesc->jlocs];\n  else nstok = 1;\n  incs  = outDesc->incs;\n  incf  = outDesc->incf;\n  incif = outDesc->incif;\n  nochan = outDesc->inaxes[outDesc->jlocf];\n  if (outDesc->jlocif>=0) noif = outDesc->inaxes[outDesc->jlocif];\n  else noif = 1;\n\n  /* Zero work accumulator */\n  n = 4 * inDesc->ncorr;\n  for (i=0; i<n; i++) work[i] = 0.0;\n\n  /* Accumulate order, channel, IF, poln */\n  indx = 0;\n  for (i=0; i<inDesc->ncorr; i++) {\n    jndx = 4*(corChan[i] + corIF[i]*nchan + corStok[i]*nchan*nif);\n    if ((inBuffer[indx+2]>0.0) && corMask[i]) {\n      work[jndx]   += inBuffer[indx];\n      work[jndx+1] += inBuffer[indx+1];\n      work[jndx+2] += inBuffer[indx+2];\n      work[jndx+3] += 1.0;\n    }\n    indx += inDesc->inaxes[0];\n  } /* end accumulation loop */\n  \n  /* Normalize to output */\n  /* Loop over Stokes */\n  for (js=0; js<nstok; js++) {  /* Stokes loop */\n    for (jif=0; jif<noif; jif++) {  /* IF loop */\n      for (jf=0; jf<nochan; jf++) {  /* Frequency loop */\n\tjndx = 4*(jf + jif*nchan + js*nchan*nif);\n\tindx = js*incs + jif*incif + jf*incf;\n\tif (work[jndx+3]>0.0) {\n\t  outBuffer[indx]   = work[jndx]   / work[jndx+3];\n\t  outBuffer[indx+1] = work[jndx+1] / work[jndx+3];\n\t  outBuffer[indx+2] = work[jndx+2];\n\t} else {\n\t  outBuffer[indx]   = 0.0;\n\t  outBuffer[indx+1] = 0.0;\n\t  outBuffer[indx+2] = 0.0;\n\t}\n      } /* end Frequency loop */\n    } /* end IF loop */\n  } /* end Stokes loop */\n\n} /* end AvgFAver */\n\n/**\n * Frequency boxcar smooth a visibility\n * \\param inDesc   Input UV descriptor\n * \\param outDesc  Output UV descriptor to be modified\n * \\param NumChSMO Number of channels to smooth, should be odd\n * \\param corChan  0-rel output channel numbers\n * \\param corIF    0-rel output IF numbers\n * \\param corStok  0-rel output Stokes parameter code.\n * \\param corMask  Array of masks per correlator for selected channels/IFs\n *                 TRUE => select\n * \\param inBuffer  Input buffer (data matrix)\n * \\param outBuffer Output buffer (data matrix)\n * \\param work      Work array twice the size of the output visibility\n * \\param err       Error stack, returns if not empty.\n */\nstatic void SmooF (ObitUVDesc *inDesc, ObitUVDesc *outDesc, olong NumChSmo,\n\t\t   olong *corChan, olong *corIF, olong *corStok, gboolean *corMask,\n\t\t   ofloat *inBuffer, ofloat *outBuffer, ofloat *work, \n\t\t   ObitErr *err)\n{\n  olong i, j, half, n, indx, jndx, kndx, jf, jif, js, nochan, noif, off;\n  olong nchan, nif, nstok, iincs, iincf, iincif, incs, incf, incif;\n\n  /* error checks */\n  if (err->error) return;\n\n  half   = NumChSmo/2;\n  iincs  = inDesc->incs;\n  iincf  = inDesc->incf;\n  iincif = inDesc->incif;\n  nchan = inDesc->inaxes[inDesc->jlocf];\n  if (inDesc->jlocif>=0) nif = inDesc->inaxes[inDesc->jlocif];\n  else nif = 1;\n  if (inDesc->jlocs>=0) nstok = inDesc->inaxes[inDesc->jlocs];\n  else nstok = 1;\n  incs  = outDesc->incs;\n  incf  = outDesc->incf;\n  incif = outDesc->incif;\n  nochan = outDesc->inaxes[outDesc->jlocf];\n  if (outDesc->jlocif>=0) noif = outDesc->inaxes[outDesc->jlocif];\n  else noif = 1;\n\n  /* Zero work accumulator */\n  n = 4 * inDesc->ncorr;\n  for (i=0; i<n; i++) work[i] = 0.0;\n\n  /* Accumulate order, channel, IF, poln */\n  for (js=0; js<nstok; js++) {  /* Stokes loop */\n    for (jif=0; jif<nif; jif++) {  /* IF loop */\n      for (jf=half; jf<nchan-half+1; jf++) {  /* Frequency loop */\n\tindx = js*iincs + jif*iincif + jf*iincf;\n\tjndx = 4*(jf + jif*nchan + js*nchan*nif);\n\toff = -half*iincf;\n\t/* Sums for smoothing */\n\tfor (j=0; j<NumChSmo; j++) {\n\t  if (inBuffer[indx+off+2]>0.0) {  /* Valid? */\n\t    work[jndx]   += inBuffer[indx+off];\n\t    work[jndx+1] += inBuffer[indx+off+1];\n\t    work[jndx+2] += inBuffer[indx+off+2];\n\t    work[jndx+3] += 1.0;\n\t    off += iincf;\n\t  } /* end data valid */\n\t} /* end smoothing loop */\n      } /* end freq loop */\n      /* Copy end channels */\n      jndx = 4*(half + jif*nchan + js*nchan*nif);\n      for (jf=0; jf<half; jf++) {\n\tkndx = 4*(jf + jif*nchan + js*nchan*nif);\n\twork[kndx]   = work[jndx];\n\twork[kndx+1] = work[jndx+1];\n\twork[kndx+2] = work[jndx+2];\n\twork[kndx+3] = work[jndx+3];\n      }\n      jndx = 4*(nchan-half-1 + jif*nchan + js*nchan*nif);\n      for (jf=half; jf>0; jf--) {\n\tkndx = 4*(nchan-jf + jif*nchan + js*nchan*nif);\n\twork[kndx]   = work[jndx];\n\twork[kndx+1] = work[jndx+1];\n\twork[kndx+2] = work[jndx+2];\n\twork[kndx+3] = work[jndx+3];\n      }\n    } /* end IF loop */\n  } /* end stokes loop */\n\n  /* Normalize to output */\n  /* Loop over Stokes */\n  for (js=0; js<nstok; js++) {  /* Stokes loop */\n    for (jif=0; jif<noif; jif++) {  /* IF loop */\n      for (jf=0; jf<nochan; jf++) {  /* Frequency loop */\n\tjndx = 4*(jf + jif*nchan + js*nchan*nif);\n\tindx = js*incs + jif*incif + jf*incf;\n\t/* Check for zero data */\n\tif ((work[jndx+3]>0.0) && !(( work[jndx]==0.0) && (work[jndx+1]==0.0))) {\n\t  outBuffer[indx]   = work[jndx]   / work[jndx+3];\n\t  outBuffer[indx+1] = work[jndx+1] / work[jndx+3];\n\t  outBuffer[indx+2] = work[jndx+2];\n\t} else {\n\t  outBuffer[indx]   = 0.0;\n\t  outBuffer[indx+1] = 0.0;\n\t  outBuffer[indx+2] = 0.0;\n\t}\n      } /* end Frequency loop */\n    } /* end IF loop */\n  } /* end Stokes loop */\n\n} /* end SmooF */\n\n/**\n * Hanning smooth a visibility\n * \\param inDesc   Input UV descriptor\n * \\param outDesc  Output UV descriptor to be modified\n * \\param doDescm  If TRUE drop every other channel\n * \\param inBuffer  Input buffer (data matrix)\n * \\param outBuffer Output buffer (data matrix)\n * \\param work      Work array twice the size of the output visibility\n * \\param err       Error stack, returns if not empty.\n */\nstatic void Hann (ObitUVDesc *inDesc, ObitUVDesc *outDesc, gboolean doDescm,\n\t\t  ofloat *inBuffer, ofloat *outBuffer, ofloat *work, \n\t\t  ObitErr *err)\n{\n  olong i, n, indx, jndx, jf, jif, js, nochan, noif, off, wincf;\n  olong nchan, nif, nstok, iincs, iincf, iincif, incs, incf, incif;\n\n  /* error checks */\n  if (err->error) return;\n\n  iincs  = inDesc->incs;\n  iincf  = inDesc->incf;\n  iincif = inDesc->incif;\n  nchan = inDesc->inaxes[inDesc->jlocf];\n  if (inDesc->jlocif>=0) nif = inDesc->inaxes[inDesc->jlocif];\n  else nif = 1;\n  if (inDesc->jlocs>=0) nstok = inDesc->inaxes[inDesc->jlocs];\n  else nstok = 1;\n  incs  = outDesc->incs;\n  incf  = outDesc->incf;\n  incif = outDesc->incif;\n  nochan = outDesc->inaxes[outDesc->jlocf];\n  if (outDesc->jlocif>=0) noif = outDesc->inaxes[outDesc->jlocif];\n  else noif = 1;\n\n  /* Zero work accumulator */\n  n = 4 * inDesc->ncorr;\n  for (i=0; i<n; i++) work[i] = 0.0;\n\n  /* Accumulate order, channel, IF, poln */\n  for (js=0; js<nstok; js++) {  /* Stokes loop */\n    for (jif=0; jif<nif; jif++) {  /* IF loop */\n      for (jf=0; jf<nchan; jf++) {  /* Frequency loop */\n\tindx = js*iincs + jif*iincif + jf*iincf;\n\tjndx = 4*(jf + jif*nchan + js*nchan*nif);\n\toff = -iincf;\n\tif ((jf>0) && (inBuffer[indx+off+2]>0.0)) {\n\t  /* Prior channel 0.25 wt */\n\t  work[jndx]   += 0.25*inBuffer[indx+off];\n\t  work[jndx+1] += 0.25*inBuffer[indx+off+1];\n\t  work[jndx+2] += 0.25*inBuffer[indx+off+2];\n\t  work[jndx+3] += 0.25;\n\t}\n\t/* Center channel 0.5 wt */\n\tif (inBuffer[indx+2]>0.0) {\n\t  work[jndx]   += 0.5*inBuffer[indx];\n\t  work[jndx+1] += 0.5*inBuffer[indx+1];\n\t  work[jndx+2] += 0.5*inBuffer[indx+2];\n\t  work[jndx+3] += 0.5;\n\t}\n\t/* Follow channel 0.25 wt */\n\toff = iincf;\n\tif ((jf<(nchan-1)) && (inBuffer[indx+off+2]>0.0)) {\n\t  work[jndx]   += 0.25*inBuffer[indx+off];\n\t  work[jndx+1] += 0.25*inBuffer[indx+off+1];\n\t  work[jndx+2] += 0.25*inBuffer[indx+off+2];\n\t  work[jndx+3] += 0.25;\n\t}\n      } /* end freq loop */\n    } /* end IF loop */\n  } /* end stokes loop */\n\n  /* Descimating output? */\n  if (doDescm) wincf = 2;\n  else         wincf = 1;\n  \n  /* Normalize to output */\n  /* Loop over Stokes */\n  for (js=0; js<nstok; js++) {  /* Stokes loop */\n    for (jif=0; jif<noif; jif++) {  /* IF loop */\n      for (jf=0; jf<nochan; jf++) {  /* Frequency loop */\n\tjndx = 4*(jf*wincf + jif*nchan + js*nchan*nif);\n\tindx = js*incs + jif*incif + jf*incf;\n\t/* Check for zero data */\n\tif ((work[jndx+3]>0.0) && !(( work[jndx]==0.0) && (work[jndx+1]==0.0))) {\n\t  outBuffer[indx]   = work[jndx]   / work[jndx+3];\n\t  outBuffer[indx+1] = work[jndx+1] / work[jndx+3];\n\t  outBuffer[indx+2] = work[jndx+2];\n\t} else {\n\t  outBuffer[indx]   = 0.0;\n\t  outBuffer[indx+1] = 0.0;\n\t  outBuffer[indx+2] = 0.0;\n\t}\n      } /* end Frequency loop */\n    } /* end IF loop */\n  } /* end Stokes loop */\n\n} /* end Hann */\n\n/**\n * Duplicate channels \n * \\param inDesc   Input UV descriptor\n * \\param outDesc  Output UV descriptor to be modified\n * \\param nBloat   Number of duplicates of each input channel\n * \\param unHann   If true, undo prior Hanning\n * \\param inBuffer  Input buffer (data matrix)\n * \\param outBuffer Output buffer (data matrix)\n * \\param err       Error stack, returns if not empty.\n */\nstatic void Bloat (ObitUVDesc *inDesc, ObitUVDesc *outDesc, olong nBloat,\n\t\t   gboolean unHann, ofloat *inBuffer, ofloat *outBuffer, \n\t\t   ObitErr *err)\n{\n  olong j, indx, jndx, jf, jif, js, nochan, noif;\n  olong nchan, nstok, iincs, iincf, iincif, incs, incf, incif;\n  ofloat WtFact;\n\n  /* error checks */\n  if (err->error) return;\n\n  WtFact = 1.0 / nBloat;     /* Weight factor */\n  if (unHann) WtFact = 1.0;  /* Undoing Hanning? */\n  iincs  = inDesc->incs;\n  iincf  = inDesc->incf;\n  iincif = inDesc->incif;\n  nchan = inDesc->inaxes[inDesc->jlocf];\n  if (inDesc->jlocs>=0) nstok = inDesc->inaxes[inDesc->jlocs];\n  else nstok = 1;\n  incs  = outDesc->incs;\n  incf  = outDesc->incf;\n  incif = outDesc->incif;\n  nochan = outDesc->inaxes[outDesc->jlocf];\n  if (outDesc->jlocif>=0) noif = outDesc->inaxes[outDesc->jlocif];\n  else noif = 1;\n\n  /* Duplicate to output */\n  for (js=0; js<nstok; js++) {  /* Stokes loop */\n    for (jif=0; jif<noif; jif++) {  /* IF loop */\n      for (jf=0; jf<nchan; jf++) {  /* Frequency loop */\n\tindx = js*iincs + jif*iincif + jf*iincf;\n\tfor (j=0; j<nBloat; j++) {\n\t  jndx = (jf*nBloat+j)*incf + jif*incif + js*incs;\n\t  /* Check for zero data, final channels */\n\t  if ((inBuffer[indx+2]>0.0) && ((jf*nBloat+j)<nochan)) {\n\t    outBuffer[jndx]   = inBuffer[indx];\n\t    outBuffer[jndx+1] = inBuffer[indx+1];\n\t    outBuffer[jndx+2] = inBuffer[indx+2] * WtFact;\n\t  } else {\n\t    outBuffer[jndx]   = 0.0;\n\t    outBuffer[jndx+1] = 0.0;\n\t    outBuffer[jndx+2] = 0.0;\n\t  }\n\t} /* end duplication */\n      } /* end Frequency loop */\n    } /* end IF loop */\n  } /* end Stokes loop */\n} /* end Bloat */\n\n/**\n * Select visibility in frequency\n * \\param inDesc    Input UV descriptor\n * \\param outDesc   Output UV descriptor\n * \\param BChan     First (1-rel) input channel selected\n * \\param EChan     Highest (1-rel) channel selected\n * \\param chinc     Increment of channels selected\n * \\param BIF       First IF (1-rel) selected\n * \\param EIF       Highest IF selected\n * \\param inBuffer  Input buffer (data matrix)\n * \\param outBuffer Output buffer (data matrix)\n */\nstatic void FreqSel (ObitUVDesc *inDesc, ObitUVDesc *outDesc, \n\t\t     olong BChan, olong EChan, olong chinc,\n\t\t     olong BIF, olong EIF,\n\t\t     ofloat *inBuffer, ofloat *outBuffer)\n{\n  olong indx, jndx, jf, jif, js, ojf, ojif;\n  olong nstok, iincs, iincf, iincif, oincs, oincf, oincif;\n  olong bchan=BChan-1, echan=EChan-1, bif=BIF-1, eif=EIF-1;\n\n  /* Data increments */\n  nstok  = outDesc->inaxes[outDesc->jlocs];\n  iincs  = outDesc->incs;\n  iincf  = outDesc->incf;\n  iincif = outDesc->incif;\n  oincs  = outDesc->incs;\n  oincf  = outDesc->incf;\n  oincif = outDesc->incif;\n\n  /* Copy to output */\n  /* Loop over Stokes */\n  for (js=0; js<nstok; js++) {  /* Stokes loop */\n    for (jif=bif; jif<=eif; jif++) {  /* IF loop */\n      for (jf=bchan; jf<=echan; jf+=chinc) {  /* Frequency loop */\n\tjndx = js*iincs + jif*iincif + jf*iincf;\n\tojf  = jf  - bchan;\n\tojif = jif - bif;\n\tindx = js*oincs + ojif*oincif + ojf*oincf;\n\toutBuffer[indx]   = inBuffer[jndx];\n\toutBuffer[indx+1] = inBuffer[jndx+1];\n\toutBuffer[indx+2] = inBuffer[jndx+2];\n      } /* end Frequency loop */\n    } /* end IF loop */\n  } /* end Stokes loop */\n\n} /* end FreqSel */\n\n/** \n * Update FQ table for averaging \n * \\param inUV   Input UV data\n * \\param chAvg  Number of channels averaged\n * \\param fqid   Desired FQ ID to update\n * \\param err    Error stack, returns if not empty.\n */\nstatic void FQSel (ObitUV *inUV, olong chAvg, olong fqid, ObitErr *err)\n{\n  ObitTableFQ    *inTab=NULL;\n  olong iFQver, highFQver;\n  oint numIF;\n  olong i, nif;\n  odouble *freqOff=NULL;\n  ofloat *chBandw=NULL;\n  oint *sideBand=NULL;\n  gchar *FQType = \"AIPS FQ\";\n  gchar *routine = \"ObitUVUtil:FQSel\";\n\n  /* error checks */\n  if (err->error) return;\n  g_assert (ObitUVIsA(inUV));\n\n  /* How many FQ tables  */\n  highFQver = ObitTableListGetHigh (inUV->tableList, FQType);\n\n  /* Are there any? */\n  if (highFQver <= 0) return;\n\n  /* Should only be one FQ table */\n  iFQver = 1;\n  if (inUV->myDesc->jlocif>=0) \n    nif = inUV->myDesc->inaxes[inUV->myDesc->jlocif];\n  else\n    nif = 1;\n\n  /* Get input table */\n  numIF = 0;\n  inTab = \n    newObitTableFQValue (inUV->name, (ObitData*)inUV, &iFQver, OBIT_IO_ReadOnly, \n\t\t\t numIF, err);\n  if (err->error) Obit_traceback_msg (err, routine, inUV->name);\n  /* Find it? */\n   Obit_return_if_fail(((inTab!=NULL) || (nif<=1)), err,\n\t\t      \"%s: Could not find FQ table for %s %d IFs\", \n\t\t      routine, inUV->name, nif);\n\n   /* Fetch values */\n   ObitTableFQGetInfo (inTab, fqid, &nif, &freqOff, &sideBand, &chBandw, err);\n   if (err->error) Obit_traceback_msg (err, routine, inTab->name);\n\n   /* Update channel widths */\n   for (i=0; i<nif; i++) chBandw[i] *= (ofloat)chAvg;\n\n   /* Save values */\n   ObitTableFQPutInfo (inTab, fqid, nif, freqOff, sideBand, chBandw, err);\n   if (err->error) Obit_traceback_msg (err, routine, inTab->name);\n\n   /* Cleanup */\n   if (freqOff)  g_free(freqOff);\n   if (sideBand) g_free(sideBand);\n   if (chBandw)  g_free(chBandw);\n   inTab = ObitTableFQUnref(inTab);\n  \n } /* end FQSel */\n\n/**\n * Low accuracy inverse Sinc function\n * \\param arg Argument\n * \\return angle in radians\n */\nstatic ofloat InvSinc(ofloat arg)\n{\n  odouble x0, x1, a;\n  olong i, n=1000;\n\n  /* Some iterations of Newton-Raphson starting with the value near 1.0 */\n  x1 = 0.001;\n  for (i=0; i<n; i++) {\n    x0 = x1;\n    a = x0 * G_PI;\n    x1 = x0 - ((sin(a)/a) - arg) / ((a*cos(a) - G_PI*sin(a))/(a*a));\n    if (fabs(x1-x0)<1.0e-6) break;  /* Convergence test */\n  }\n\n  return (ofloat)x1;\n} /* end InvSinc */\n", "meta": {"hexsha": "a83196dce9b2194a26edacfd76374a351d83a128", "size": 207773, "ext": "c", "lang": "C", "max_stars_repo_path": "ObitSystem/Obit/src/ObitUVUtil.c", "max_stars_repo_name": "sarrvesh/Obit", "max_stars_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-01T05:30:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-01T05:30:45.000Z", "max_issues_repo_path": "ObitSystem/Obit/src/ObitUVUtil.c", "max_issues_repo_name": "sarrvesh/Obit", "max_issues_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ObitSystem/Obit/src/ObitUVUtil.c", "max_forks_repo_name": "sarrvesh/Obit", "max_forks_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-22T14:07:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-22T14:07:41.000Z", "avg_line_length": 35.9531060737, "max_line_length": 104, "alphanum_fraction": 0.6277283381, "num_tokens": 69359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19930799790404563, "lm_q2_score": 0.02297737162445238, "lm_q1q2_score": 0.004579573935566832}}
{"text": "#pragma once\n\n#include \"halleystring.h\"\n#include \"halley/data_structures/vector.h\"\n#include <optional>\n#include <gsl/span>\n\nnamespace Halley {\n    class FuzzyTextMatcher {\n    public:\n\t\tclass Score {\n\t\tpublic:\n\t\t\tint curJumps = 0;\n\t\t\tint jumpLength = 0;\n\t\t\tint sections = 0;\n\t\t\tint sectionLens = 0;\n\t\t\tint sectionPos = 0xFFFF;\n\t\t\tVector<std::pair<uint16_t, uint16_t>> matchPositions;\n\n\t\t\tbool operator<(const Score& other) const;\n\n\t\t\tScore advance(int jumpLen, int sectionPos, int newSectionLen) const;\n\t\t\tvoid makeMatchPositions(const Vector<int>& breadcrumbs);\n\t\t};\n    \t\n        class Result {\n        public:\n        \tResult() = default;\n            Result(String str, String id, Score score);\n\n            bool operator<(const Result& other) const;\n\n        \tconst String& getString() const;\n        \tconst String& getId() const;\n        \tgsl::span<const std::pair<uint16_t, uint16_t>> getMatchPositions() const;\n\n        private:\n        \tString str;\n        \tString id;\n        \tVector<std::pair<uint16_t, uint16_t>> matchPositions;\n        \tScore score;\n        };\n\n        FuzzyTextMatcher(bool caseSensitive, std::optional<size_t> resultsLimit);\n    \t\n    \tvoid addStrings(Vector<String> strings);\n    \tvoid addString(String string, String id = \"\");\n    \tvoid clear();\n\n    \tVector<Result> match(const String& query) const;\n\n    private:\n        struct Entry {\n\t        String string;\n            String id;\n        };\n    \t\n    \tVector<Entry> strings;\n    \tbool caseSensitive;\n    \tstd::optional<size_t> resultsLimit;\n\n    \tstd::optional<Result> match(const String& str, const String& id, const StringUTF32& query) const;\n    };\n}\n", "meta": {"hexsha": "cafc2602c2995c6640f80bab2517cbd132a6493f", "size": 1642, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engine/utils/include/halley/text/fuzzy_text_matcher.h", "max_stars_repo_name": "amrezzd/halley", "max_stars_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/engine/utils/include/halley/text/fuzzy_text_matcher.h", "max_issues_repo_name": "amrezzd/halley", "max_issues_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engine/utils/include/halley/text/fuzzy_text_matcher.h", "max_forks_repo_name": "amrezzd/halley", "max_forks_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2615384615, "max_line_length": 102, "alphanum_fraction": 0.6272838002, "num_tokens": 384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18713267309572337, "lm_q2_score": 0.024423090586673288, "lm_q1q2_score": 0.004570358226743171}}
{"text": "#ifndef CollectorMap_h\n#define CollectorMap_h\n/** This is free and unencumbered software released into the public domain.\nThe authors of ISIS do not claim copyright on the contents of this file.\nFor more details about the LICENSE terms and the AUTHORS, you will\nfind files of those names at the top level of this repository. **/\n\n/* SPDX-License-Identifier: CC0-1.0 */\n#include <cctype>\n#include <QString>\n#include <map>\n#include <algorithm>\n#include <functional>\n#include <sstream>\n#include <iomanip>\n#include <exception>\n#include \"IException.h\"\n#include \"IString.h\"\n#include <gsl/gsl_math.h>\n\n\nnamespace Isis {\n\n  /**\n   * @brief Provides a simple comparison between two values\n   *\n   * This simple comparison function object is provided with no special frills\n   * that does pretty much exactly what std::less does.\n   */\n  template <typename K> struct SimpleCompare {\n\n    /**\n     * Returns true if v1 is less than v2\n     *\n     * @param v1 Input constant\n     * @param v2 Input constant\n     *\n     * @return bool Returns true if v1 is less than v2\n     */\n    bool operator()(const K &v1, const K &v2) const {\n      return (v1 < v2);\n    }\n\n  };\n\n  /**\n  * @brief Provides a case insensitive string comparison\n  *\n  * This string comparison functor object compares two strings ignoring case. Use\n  * this policy when your key into the collector map is a string and you want to\n  * ignore case when finding elements in the collection.\n  */\n  template <typename K> struct NoCaseStringCompare {\n\n    /**\n     * Compares v1 and v2 as case insensitive strings, and returns true of v1 is\n     * less than v2 (as those strings).\n     *\n     * @param v1 Input constant\n     * @param v2 Input constant\n     *\n     * @return bool Returns true if v1 is less than v2 in string format\n     */\n    bool operator()(const K &v1, const K &v2) const {\n      return (IString::DownCase(v1) < IString::DownCase(v2));\n    }\n\n  };\n\n  /**\n   * @brief Provides a robust comparison of double/float values\n   *\n   * This functor compares floating point values using a default epsilon of\n   * 1.0e-6. It can be used for doubles or floats, however floats will be promoted\n   * to double for the comparison.\n   */\n  template <typename K> struct RobustFloatCompare {\n\n    /**\n     * Compares v1 and v2 as floating point values.\n     *\n     * @param v1\n     * @param v2\n     *\n     * @return bool\n     */\n    bool operator()(const K &v1, const K &v2) const {\n      return (gsl_fcmp(v1, v2, -1.0E-6) < 0);\n    }\n\n  };\n\n  /**\n   * @brief Supplies a NOOP default for removal of a CollectorMap entry\n   *\n   * This simple declaration is basically a NOOP that implements removal\n   * of a CollectionMap entry.  It is most useful (and the default behavior)\n   * when the storage element of the CollectorMap is anything but a pointer.\n   * Pointers that require deletion should use the PointerRemoval policy unless\n   * the pointers are owned by another \"entity\".\n   */\n  template <typename T> struct NoopRemoval {\n\n    // defines used for cross platform suppression of unused parameter warning. This will prevent\n    // distroy() from causing unused parameter warnings in clang. This is done for the purpose\n    // of porting ISIS to OSX 10.11\n    // #define MON_Internal_UnusedStringify(macro_arg_string_literal) #macro_arg_string_literal\n    // #define MONUnusedParameter(macro_arg_parameter) _Pragma(MON_Internal_UnusedStringify(unused(macro_arg_parameter)))\n\n    protected:\n\n      /**\n       * Destroys the CollectorMap entry\n       *\n       * @param element The CollectorMap to be destroyed\n       */\n      void destroy(T *element) {\n        // arbitrary cast type to suppress unused parameter warnings generated\n        // by clang when building on mac\n        (void)element;\n\n        return;\n      }\n\n  };\n\n  /**\n   * @brief Supplies a policy for deleting pointers that CollectorMap owns\n   *\n   * Defines a method to delete pointers when removed from a CollectorMap.\n   * This is necessary to prevent memory leaks and defer the deletion to\n   * removal from CollectorMap class.\n   */\n  template <typename T> struct PointerRemoval {\n    protected:\n\n      /**\n       * Destroys the CollectorMap pointer's CollectorMap\n       *\n       * @param element The pointer pointing to the CollectorMap to be destroyed\n       */\n      void destroy(T *element) {\n        delete(*element);\n        return;\n      }\n\n  };\n\n  /**\n   * @brief Policy for deleting arrays that CollectorMap owns\n   *\n   * Defines a method to delete arrays when removed from a CollectorMap.\n   * This is necessary to prevent memory leaks and defer the deletion to\n   * removal from CollectorMap class.\n   */\n  template <typename T> struct ArrayRemoval {\n    protected:\n\n      /**\n       * Destroys the array of CollectorMaps\n       *\n       * @param element The array of CollectorMaps to be destroyed\n       */\n      void destroy(T *element) {\n        delete [](*element);\n        return;\n      }\n\n  };\n\n\n  /**\n   * @brief (Default) Policy for copying map elements\n   *\n   * Defines a method to copy simple elements from an existing map to a\n   * destination map.  This policy just makes a direct copy of the element to the\n   * destination.\n   *\n   * This policy assumes the assignment operator handles the proper copying of\n   * each element T in the collection.\n   */\n  template <typename T> struct DefaultCopy {\n    protected:\n\n      /**\n       * Returns a copy of the input\n       *\n       * @param src The map element to be copied\n       *\n       * @return const T& The copy of the input\n       */\n      const T &copy(const T &src) const {\n        return (src);\n      }\n\n  };\n\n\n  /**\n   * @brief Pointer to object policy for copying map elements\n   *\n   * Defines a copy method to properly handle pointers to objects (assumed) when\n   * copying the complete CollectorMap.  This implementation assumes the copy\n   * constructor properly handles the creation of a new element from a different\n   * one.\n   *\n   * This policy assumes the assignment operator handles the proper copying of\n   * each element T* in the collection.\n   *\n   * This employs an intersting technique of redirection.  Because the type T is\n   * actually T*, the templated allocate() method exists to get down to the T\n   * class base level.  Looks strange but it works.\n   */\n  template <typename T> struct PointerCopy {\n    protected:\n      /**\n       * @brief Allocate new object using copy construtor and new pointer\n       *\n       * This copy method takes a pointer to a pointer (T is actually a T*) and\n       * allocates a new object using the copy constructor.\n       *\n       * @param src  Pointer to pointer of new class to allocate\n       *\n       * @return T  Pointer to new object type T\n       */\n      T copy(const T &src)  const {\n        return (allocate(*(src)));\n      }\n\n    private:\n      /**\n       * @brief Allocate new object using copy constructor\n       *\n       * @param obj Source object to create new one from\n       *\n       * @return P* Pointer to newly allocated object\n       */\n      template <typename P>\n      P *allocate(const P &obj) const {\n        return (new P(obj));\n      }\n  };\n\n\n\n  /**\n   *  @brief Collector/container for arbitrary items\n   *\n   *  Used to contain types with iterators of const and non-const conditions.\n   *  This is a multimap that contains arbitrary keys with arbitrary elements.  It\n   *  is intended to be used for pointers and copyable objects.  They should be\n   *  rather efficient in the copy out operation so large objects may not be\n   *  suitable or classes that do not have a good copy operator.  During testing\n   *  it was noted that an object is copied up to four times and destroyed three\n   *  times upon an add() operation.\n   *\n   *  This class is implemented using policies.  The ComparePolicy is used to test\n   *  key elements such as strings and double values.  The NoCaseStringCompare\n   *  policy is provided that expedites case insensitive string key comparisons.\n   *  The RobustFloatCompare implements the comparison of double or float key\n   *  types.  Direct comparisons of floats can be problematic due to round off and\n   *  storage manifestations of these values in conputers.   The default policy,\n   *  SimpleCompare, does a simple parameter to key equality test.\n   *\n   *  The RemovalPolicy is provided when a map value is removed from the list.\n   *  This allows pointers and arrays to be stored in the map as well.  To store\n   *  pointers, use PointerRemoval and for arrays there is the ArrayRemoval\n   *  policy.  The default is the NoopRemoval policy which simply lets the\n   *  destructor handle removals.\n   *\n   *  The CopyPolicy is necessary to properly handle the copying of elements.\n   *  This is especially important for pointers and arrays.  In order to minimize\n   *  difficult passing strategies, map elements are passed by address and the\n   *  return type is the element type.  DefaultCopy simply copies the elements as\n   *  is relying on the element T assigment operator to do the right thing. For\n   *  pointers to objects, the PointerCopy allocates the object using the copy\n   *  constructor.  One could provide a similar operator assuming a clone()\n   *  method existed for the type T element. The ArrayCopy policy is left to the\n   *  user to provide their own as it cannot support arrays of varying length.\n   *  (One should use std::vector instead!) Users can supply their own CopyPolicy\n   *  that need only expose a copy(cont T *src) method.\n   *\n   *  Here are some examples that demonstrate how this policy-based template class\n   *  can be used:\n   *\n   *  @code\n   * // Create a unique string key list that stores double floating point values.\n   * // Use the default removal and copy policies but allow testing for character\n   * // keys without regard to case via the NoCaseStringCompare.\n   *  #include \"CollectorMap.h\"\n   *\n   *  CollectorMap<QString, double, NoCaseStringCompare > dmap;\n   *  cout << \"\\nSize of double map = \" << dmap.size() << endl;\n   *  dmap.add(\"one\", 1.0);\n   *  dmap.add(\"two\", 2.0);\n   *  cout << \"Size of double map = \" << dmap.size() << endl;\n   *\n   *  cout << \"One = \" << dmap.get(\"one\") << endl;\n   *  cout << \"Two = \" << dmap.get(\"Two\") << endl;\n   *\n   *  const double &one = dmap.get(\"one\");\n   *  cout << \"\\nTest Const one = \" << one << endl;\n   *\n   *  dmap.remove(\"one\");\n   *  @endcode\n   *\n   *  Using this class internal to classes is perhaps where it may be applied more\n   *  frequently.  The example below shows how to declare an integer key using\n   *  pointers to classes:\n   *\n   *  @code\n   * #include \"CollectorMap.h\"\n   *\n   *  class ClassTest {\n   *   public:\n   *    ClassTest(int n = 0) : _n(n) {  }\n   *    ~ClassTest() {  }\n   *    int Ident() const { return (_n); }\n   *   private:\n   *    int _n;\n   *  };\n   *\n   *\n   * //  Typedefs are sometimes convenient in these cases\n   *  typedef CollectorMap<int, ClassTest *, SimpleCompare,\n   *                       PointerRemoval, PointerCopy> PointerMap;\n   *\n   *  PointerMap ctest2;\n   *  ctest2.add(4,new ClassTest(4));\n   *  ctest2.add(5,new ClassTest(5));\n   *  ctest2.add(6,new ClassTest(6));\n   *  ctest2.add(7,new ClassTest(7));\n   *\n   *  cout << \"Remove ClassTest 6\\n\";\n   *  ctest2.remove(6);\n   *\n   * //  Creates a copy of ctest2 using the PointerCopy policy\n   *  PointerMap map2(ctest2);\n   *\n   *  cout << \"Find element 7: \"  << map2.find(7)->Ident() << endl;\n   *\n   *  @endcode\n   *\n   *  And, finally, an example of how to use duplicate keys:\n   *\n   *  @code\n   *  #include \"CollectorMap.h\"\n   *\n   *  typedef CollectorMap<int,QString> IntStr;\n   *  IntStr dupstr(IntStr::DuplicateKeys);\n   *  dupstr.add(1,\"One\");\n   *  dupstr.add(1, \"One #2\");\n   *  dupstr.add(1,\"One #3\");\n   *  dupstr.add(2,\"Two\");\n   *  dupstr.add(2,\"Two #2\");\n   *  dupstr.add(3,\"Three\");\n   *\n   *  cout << \"Size of Dup object: \" << dupstr.size() << endl;\n   *  cout << \"Number Ones:   \" << dupstr.count(1) << endl;\n   *  cout << \"Number Twos:   \" << dupstr.count(2) << endl;\n   *  cout << \"Number Threes: \" << dupstr.count(3) << endl;\n   *  cout << \"Number Fours:  \" << dupstr.count(4) << endl;\n   *\n   *  IntStr::CollectorConstIter isIter;\n   *  int j = 0;\n   *  for (isIter = dupstr.begin() ; isIter != dupstr.end() ; ++isIter, j++) {\n   *       cout << \"IntStr[\" << j << \"] = {\" << isIter->first << \", \"\n   *            << isIter->second << \"}, Index: \" << dupstr.index(isIter->first)\n   *            << endl;\n   *       cout << \"Nth Test Ident       = \" << dupstr.getNth(j) << endl;\n   *  }\n   *  @endcode\n   *\n   *  The output of the above example is:\n   *  @code\n   * Size of Dup object: 6\n   * Number Ones:   3\n   * Number Twos:   2\n   * Number Threes: 1\n   * Number Fours:  0\n   * IntStr[0] = {1, One}, Index: 0\n   * Nth Test Ident       = One\n   * IntStr[1] = {1, One #2}, Index: 0\n   * Nth Test Ident       = One #2\n   * IntStr[2] = * {1, One #3}, Index: 0\n   * Nth Test Ident       = One #3\n   * IntStr[3] * = {2, Two}, Index: 3\n   * Nth Test Ident       = Two\n   * IntStr[4] = * {2, Two #2}, Index: 3\n   * Nth Test Ident       = Two #2\n   * IntStr[5] = * {3, Three}, Index: 5\n   * Nth Test Ident = Three\n   *  @endcode\n   *\n   *  @ingroup Utility\n   *\n   *  @author 2006-06-21 Kris Becker\n   *\n   *  @internal\n   *    @history 2006-07-03 Kris Becker Added the ability to stored duplicate keys\n   *             if needed (using a multimap instead of a map).  Initial default\n   *             behavior of unique keys is retained.  See KeyPolicy.\n   *    @history 2006-07-28 Kris Becker Fixed a bug in the NoCaseStringCompare\n   *             implementation.  Prior to this fix, it would not function\n   *             properly at all for case-insenstive keys.\n   *    @history 2006-08-30 Kris Becker Fixed bug in copy constructors that\n   *             attempted to use a virtual method in the object being created\n   *             when it *must* use the method from the one it is being created\n   *             from. (g++ 4.1 on Suse 10.1 didn't like this bug at all!)\n   *    @history 2008-06-18 Christopher Austin Fixed Documentation\n   *    @history 2017-08-30 Summer Stapleton - Updated documentation. References #4807.\n   * \n   */\n  template < typename K, typename T,\n           template <class> class ComparePolicy = SimpleCompare,\n           template <class> class RemovalPolicy = NoopRemoval,\n           template <class> class CopyPolicy = DefaultCopy\n           >\n  class CollectorMap : public RemovalPolicy<T>, public CopyPolicy<T> {\n    public:\n      typedef T                                      CollectorType; //!< Data type\n      /** A multimap attacking a key to a CollectorType and a ComparePolicy<CollectorType>*/\n      typedef std::multimap<K, CollectorType, ComparePolicy<K> > CollectorList;\n      //! CollectorList iterator type declaration\n      typedef typename CollectorList::iterator       CollectorIter;\n      //! CollectorList constant iterator type declaration\n      typedef typename CollectorList::const_iterator CollectorConstIter;\n\n      /**\n       * @brief Enumerated selection of key behaviour\n       *\n       * Using this enumeration during construction allows the user of this class\n       * to specify if the keys used to identify elements are unique or can be\n       * duplicated.\n       */\n      enum KeyPolicy { UniqueKeys,     //!<  Constrain keys to be unique\n                       DuplicateKeys   //!<  Allow duplication of keys\n                     };\n\n      /** Constructor */\n      CollectorMap() : _keyPolicy(UniqueKeys) { }\n\n      /**\n       * @brief Allows the user to choose if keys can be duplicated\n       *\n       * This constructor is provided to the user that wants to explicity define how\n       * the keys, namely insertions are managed.  The default is unique keys in the\n       * noop constructor...this one allows instantiation of either policy.\n       *\n       * @param keyPolicy   Can be UniqueKeys or DuplicateKeys\n       */\n      CollectorMap(const KeyPolicy &keyPolicy) : _keyPolicy(keyPolicy) { }\n\n      /**  Destructor handles removal of the elements within the collection\n       *\n       * This must take into account the removal strategy and apply to any\n       * remaining elements.\n       */\n      virtual ~CollectorMap() {\n        selfDestruct();\n      }\n\n      /**\n       * @brief Copy constructor invokes the copy policy as provided by the users\n       *\n       * This copy constructor will transfer the map of an incoming CollectorMap to\n       * a newly created one.  This process employs the user selectable CopyPolicy.\n       * It invokes the copy() method exposed in the copy policy.\n       *\n       * @param cmap The CollectorMap to be copied\n       */\n      CollectorMap(const CollectorMap &cmap) {\n        _keyPolicy = cmap._keyPolicy;\n        CollectorConstIter cItr;\n        for(cItr = cmap._list.begin() ; cItr != cmap._list.end() ; cItr++) {\n          _list.insert(std::make_pair(cItr->first, cmap.copy(cItr->second)));\n        }\n      }\n\n      /**\n       * @brief Assignment operator for the CollectorMap class object\n       *\n       * This object assignment operator is provided to properly handle the copying\n       * of CollectorMap elements to a new instantiation.  This implements the\n       * CopyPolicy for each element in the @b cmap object to the current one.  This\n       * is a two step operation:  first destroy any elements that exist in the\n       * destination object (using the RemovalPolicy) and then copy all elements\n       * from the @b cmap object to the current one using the copy() method exposed\n       * in the CopyPolicy.\n       *\n       * @param cmap The CollectorMap to be copied\n       * \n       * @returns Pointer to this CollectorMap\n       */\n      CollectorMap &operator=(const CollectorMap &cmap) {\n        if(&cmap != this) {\n          selfDestruct();\n          _keyPolicy = cmap._keyPolicy;\n          CollectorConstIter cItr;\n          for(cItr = cmap._list.begin() ; cItr != cmap._list.end() ; cItr++) {\n            _list.insert(std::make_pair(cItr->first, cmap.copy(cItr->second)));\n          }\n        }\n        return (*this);\n      }\n\n      /**\n       * Returns the size of the collection\n       *\n       * @return int Number of elements in collection\n       */\n      int size() const {\n        return (_list.size());\n      }\n\n      /**\n       * @brief Returns the number of keys found in the list\n       *\n       * For unique keys, this will always be 1.  If duplicate keys are allowed,\n       * this will return the number of keys in the container.\n       *\n       * @param key  Key to return count for\n       *\n       * @return int Number keys in container\n       */\n      int count(const K &key) const {\n        return (_list.count(key));\n      }\n\n      /**\n       * Adds the element to the list.\n       *\n       * If the element exists and the key policy is restricted to uniqueness, it is\n       * replaced after the removal strategy is applied.  If it doesn't exist, it is\n       * inserted into the list.  For duplicate keys, it is simply inserted.\n       *\n       * @param key  Key in the associative map for the value\n       * @param value Value to be associated with the key\n       */\n      void add(const K &key, const T &value) {\n        if(_keyPolicy == UniqueKeys) remove(key);\n        _list.insert(std::make_pair(key, value));\n        return;\n      }\n\n      /**\n       * Checks the existance of a particular key in the list\n       * @param key Key to search for in the list\n       * @return bool True if the key exists, false otherwise\n       */\n      bool exists(const K &key) const {\n        CollectorConstIter cItr = _list.find(key);\n        return (cItr != _list.end());\n      }\n\n      /**\n       * @brief Returns the value associated with the name provided\n       *\n       * If the specifed name and value does not exist in the list, an out_of_range\n       * exception is thrown.  Use @b exists to predetermine of the value is in the\n       * list.\n       *\n       * @param key Key to fetch the value for\n       * @return T Value associated with name\n       * @throws IException if the value is not found\n       */\n      T &get(const K &key) {\n        CollectorIter cItr = _list.find(key);\n        if(cItr == _list.end()) {\n          QString mess = \"Requested value does not exist!\";\n          throw IException(IException::Programmer, mess, _FILEINFO_);\n        }\n        return (cItr->second);\n      }\n\n      /**\n       * @brief Const version returning the value associated with the given name\n       *\n       * @param key Key to fetch the value for\n       * \n       * @returns The value associated with the given name\n       */\n      const T &get(const K &key) const {\n        CollectorConstIter cItr = _list.find(key);\n        if(cItr == _list.end()) {\n          QString mess = \"Requested value does not exist!\";\n          throw IException(IException::Programmer, mess, _FILEINFO_);\n        }\n        return (cItr->second);\n      }\n\n      /**\n       * @brief Returns the index of the first occuring element in the list\n       *\n       * This returns the index such that the getNth() methods would retrieve the\n       * element with key.  For duplicate keys, it is garaunteed to return the first\n       * element.  It will return -1 if the element is not in the list.\n       *\n       * @param key Key to fetch the value for\n       *\n       * @return int Zero-based index of (first) element with key.  If it doesn't\n       *         exist, -1 is returned.\n       */\n      int index(const K &key) const {\n        CollectorConstIter cItr = _list.lower_bound(key);\n        if(cItr == _list.end()) {\n          return (-1);\n        }\n        else {\n          return (std::distance(_list.begin(), cItr));\n        }\n      }\n\n      /**\n       * @brief Returns the nth value in the collection\n       *\n       * If the specifed value does not exist in the list, an out_of_range exception\n       * is thrown.  Use @b size() to predetermine if the range is valid.\n       *\n       * @param nth Return the Nth value in the list\n       *\n       * @return T Value associated with name\n       */\n      T &getNth(int nth) {\n        CollectorIter cItr;\n        int i;\n        for(cItr = _list.begin(), i = 0 ; cItr != _list.end() ; ++cItr, i++) {\n          if(i == nth) break;\n        }\n\n        if(cItr == _list.end()) {\n          std::ostringstream mess;\n          mess << \"Requested index (\" << nth << \") out of range\" << std::endl;\n          throw IException(IException::Programmer, mess.str(), _FILEINFO_);\n        }\n        return (cItr->second);\n      }\n\n      /**\n        * @brief Returns the nth value in the collection\n        *\n        * If the specifed value does not exist in the list, an out_of_range exception\n        * is thrown.  Use @b size() to predetermine if the range is valid.\n        *\n        * @param nth Return the Nth value in the list\n        *\n        * @return T Value associated with name\n        */\n      const T &getNth(int nth) const {\n        CollectorConstIter cItr;\n        int i;\n        for(cItr = _list.begin(), i = 0 ; cItr != _list.end() ; ++cItr, i++) {\n          if(i == nth) break;\n        }\n        if(cItr == _list.end()) {\n          std::ostringstream mess;\n          mess << \"Requested index (\" << nth << \") out of range\" << std::endl;\n          throw IException(IException::Programmer, mess.str(), _FILEINFO_);\n        }\n        return (cItr->second);\n      }\n\n      /**\n        * @brief Returns the nth key in the collection\n        *\n        * If the specifed key does not exist in the list, an out_of_range exception\n        * is thrown.  Use @b size() to predetermine if the range is valid.\n        *\n        * @param nth Return the Nth key in the list\n        *\n        * @return K Key associated with name\n        */\n      const K &key(int nth) const {\n        CollectorConstIter cItr;\n        int i;\n        for(cItr = _list.begin(), i = 0 ; cItr != _list.end() ; ++cItr, i++) {\n          if(i == nth) break;\n        }\n        if(cItr == _list.end()) {\n          std::ostringstream mess;\n          mess << \"Requested key index (\" << nth << \") out of range\" << std::endl;\n          throw IException(IException::Programmer, mess.str(), _FILEINFO_);\n        }\n        return (cItr->first);\n      }\n\n      /**\n       * Removes and entry from the list\n       *\n       * @param key Name of key/value pair to remove from the list\n       *\n       * @return int Number of elements erased\n       */\n      int remove(const K &key) {\n        CollectorIter Itr1 = _list.lower_bound(key);\n        if(Itr1 == _list.end()) return (0);\n\n        CollectorIter Itr2 = _list.upper_bound(key);\n        while(Itr1 != Itr2) {\n          this->destroy(&Itr1->second);\n          ++Itr1;\n        }\n        return (_list.erase(key));\n      }\n\n      /**\n       * Const iterator into list\n       *\n       * @return CollectorConstIter Returns a const iterator to the list\n       */\n      CollectorConstIter begin() const {\n        return _list.begin();\n      }\n\n      /**\n       * Const iterator to end of list\n       *\n       * @return CollectorConstIter  Returns the const end of the list\n       */\n      CollectorConstIter end() const {\n        return _list.end();\n      }\n\n      /**\n       * Returns the start of the list for iterating purposes\n       *\n       * @return CollectorIter Returns an iterator on the collection\n       */\n      CollectorIter begin() {\n        return _list.begin();\n      }\n\n      /**\n       * Returns the end of the list\n       *\n       * @return CollectorIter Returns the end of the list for determining the end\n       *         of the iteration loop\n       */\n      CollectorIter end() {\n        return _list.end();\n      }\n\n    private:\n      KeyPolicy      _keyPolicy;  //!<  Unique or duplicate key constraint\n      CollectorList  _list;       //!< The list\n\n      /**\n       * @brief Thourough destruction of list\n       *\n       * This method iterates through each element in the list applying the\n       * RemovalPolicy to each value in the map.  It then clears the internal list\n       * for subsequent reuse if needed.\n       */\n      void selfDestruct() {\n        CollectorIter itr;\n        for(itr = _list.begin() ; itr != _list.end() ; itr++) {\n          this->destroy(&itr->second);\n        }\n        _list.clear();\n      }\n\n\n  };\n\n};\n#endif\n", "meta": {"hexsha": "50fd0a1dae81a492d261d69c95fc3bf4a7d0414b", "size": 26308, "ext": "h", "lang": "C", "max_stars_repo_path": "isis/src/base/objs/CollectorMap/CollectorMap.h", "max_stars_repo_name": "kdl222/ISIS3", "max_stars_repo_head_hexsha": "aab0e63088046690e6c031881825596c1c2cc380", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 134.0, "max_stars_repo_stars_event_min_datetime": "2018-01-18T00:16:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T03:53:33.000Z", "max_issues_repo_path": "isis/src/base/objs/CollectorMap/CollectorMap.h", "max_issues_repo_name": "kdl222/ISIS3", "max_issues_repo_head_hexsha": "aab0e63088046690e6c031881825596c1c2cc380", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 3825.0, "max_issues_repo_issues_event_min_datetime": "2017-12-11T21:27:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:45:20.000Z", "max_forks_repo_path": "isis/src/base/objs/CollectorMap/CollectorMap.h", "max_forks_repo_name": "jlaura/isis3", "max_forks_repo_head_hexsha": "2c40e08caed09968ea01d5a767a676172ad20080", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 164.0, "max_forks_repo_forks_event_min_datetime": "2017-11-30T21:15:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T10:22:29.000Z", "avg_line_length": 34.2998696219, "max_line_length": 121, "alphanum_fraction": 0.6074958188, "num_tokens": 6566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10970577969958141, "lm_q2_score": 0.041462274636121815, "lm_q1q2_score": 0.0045486511670739214}}
{"text": "/*  Copyright 2017 International Business Machines Corporation\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.  */\n\n#pragma once\n\n#include \"kernelpp/config.h\"\n\n#include <gsl.h>\n#include <memory>\n\n#if defined(kernelpp_WITH_CUDA)\n#   define checkCudaErrors(err)  __checkCudaErrors (err, __FILE__, __LINE__)\n#   define checkCudaLastError()  __checkLastCudaError (__FILE__, __LINE__)\n#endif\n\nnamespace kernelpp\n{\n    /*  Initialize the cuda runtime, and ensure at least\n     *  one device is available.\n     */\n    bool init_cudart();\n\n    /*  `device_ptr<T>` is a smart pointer which owns and manages one\n     *  or more objects of type `T` in contiguous memory on a CUDA device,\n     *  and disposes of these objects when it goes out of scope.\n     */\n    template<typename T> class device_ptr final\n    {\n        struct cuda_deleter;\n        std::unique_ptr<T, cuda_deleter> m_ptr;\n        size_t m_size;\n\n      public:\n        device_ptr();\n        device_ptr(size_t n);\n        device_ptr(device_ptr<T>&& other);\n        device_ptr(gsl::span<T> span);\n\n        gsl::span<T> span();\n        const gsl::span<T> span() const;\n\n        T* get();\n\n        void copy_from(const gsl::span<T> from);\n        void copy_to(gsl::span<T> to) const;\n    };\n}\n\n#if defined(kernelpp_WITH_CUDA) && defined(__CUDACC__)\n#   include \"cuda_util-inl.cuh\"\n#endif\n", "meta": {"hexsha": "2756a4fe34687579943e680f7741310d5a50468c", "size": 1819, "ext": "h", "lang": "C", "max_stars_repo_path": "include/kernelpp/cuda_util.h", "max_stars_repo_name": "rayglover-ibm/kernelpp", "max_stars_repo_head_hexsha": "68644a71be2849cc0ef0b241fc68f195b9def5ce", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-06-23T09:18:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T06:07:39.000Z", "max_issues_repo_path": "include/kernelpp/cuda_util.h", "max_issues_repo_name": "rayglover-ibm/kernelpp", "max_issues_repo_head_hexsha": "68644a71be2849cc0ef0b241fc68f195b9def5ce", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/kernelpp/cuda_util.h", "max_forks_repo_name": "rayglover-ibm/kernelpp", "max_forks_repo_head_hexsha": "68644a71be2849cc0ef0b241fc68f195b9def5ce", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.873015873, "max_line_length": 76, "alphanum_fraction": 0.6910390324, "num_tokens": 440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.13117322376181564, "lm_q2_score": 0.034618842574193974, "lm_q1q2_score": 0.004541065183359816}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef uuid_93a5858f_7040_4f67_9767_808d2a4f7ff9_h\r\n#define uuid_93a5858f_7040_4f67_9767_808d2a4f7ff9_h\r\n\r\n#include <gslib/type.h>\r\n#include <gslib/string.h>\r\n\r\n__gslib_begin__\r\n\r\nstruct uuid_timestamp\r\n{\r\n    byte        tm_sec;\r\n    byte        tm_min;\r\n    byte        tm_hour;\r\n    byte        tm_mday;    /* day of month */\r\n    byte        tm_mon;\r\n    byte        tm_wday;    /* day of week */\r\n    int16       tm_year;\r\n    int16       tm_yday;    /* day of year */\r\n    int32       tm_fraction;\r\n};\r\n\r\nenum uuid_version\r\n{\r\n    uuid_v1,                /* date-time & MAC address */\r\n    uuid_v2,                /* DCE security */\r\n    uuid_v3,                /* MD5 hash & namespace */\r\n    uuid_v4,                /* random */\r\n    uuid_v5,                /* SHA-1 hash & namespace */\r\n    uuid_ver_default = uuid_v4,\r\n    uuid_ver_invalid = uuid_v2,\r\n};\r\n\r\nstruct uuid_raw\r\n{\r\n    uint        data1;\r\n    uint16      data2;\r\n    uint16      data3;\r\n    byte        data4[8];\r\n};\r\n\r\nclass uuid:\r\n    protected uuid_raw\r\n{\r\npublic:\r\n    uuid();\r\n    uuid(uuid_version ver) { generate(ver); }\r\n    uuid(uuid_version ver, const gchar* name, int len) { generate(ver, name, len); }\r\n    uuid(const string& str) { from_string(str.c_str(), str.length()); }\r\n    uuid(const gchar* str, int len) { from_string(str, len); }\r\n    bool operator==(const uuid& that) const;\r\n    bool is_valid() const;\r\n    void generate(uuid_version ver);\r\n    void generate(uuid_version ver, const gchar* name, int len);\r\n    void from_string(const gchar* str, int len);\r\n    const gchar* to_string(string& str) const;\r\n    void get_timestamp(uuid_timestamp& ts) const;\r\n};\r\n\r\n__gslib_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "3b28627581bbfeb128cafb0ee781c52923dfe40f", "size": 2948, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gslib/uuid.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/gslib/uuid.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gslib/uuid.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 33.1235955056, "max_line_length": 85, "alphanum_fraction": 0.6472184532, "num_tokens": 720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11596071519881658, "lm_q2_score": 0.039048289790720114, "lm_q1q2_score": 0.0045280676114225525}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\n * Contact: lymastee@hotmail.com\n *\n * This file is part of the gslib project.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n#ifndef rasm_150d55c1_d63d_40ea_8fd2_9bc280975fe0_h\n#define rasm_150d55c1_d63d_40ea_8fd2_9bc280975fe0_h\n\n#include <gslib\\pool.h>\n#include <gslib\\string.h>\n#include <gslib\\std.h>\n#include <rathen\\config.h>\n\n/*\n * @ 2013.02.26\n * New assemble tool for rathen. This version we gonna solve the problem that last version of rasm could not support labeled jump.\n * In this version, every chuck of assembly code would be a separate and independent node, linked to a whole code segment, and the\n * label would be a particular node in the tree. In this version, we would not need vslen to do the linkage stuff any more.\n * And the short jump would be available.\n * Plus, in this way, we could see the machine code correspond to every single assemble instruction, and yet we've been very close\n * to a disassemble toolkit, but there were still some problems. The rathen didn't use all the x86 machine code. This assemble tool \n * just concerned about a subset of all the x86 machine codes. I didn't intend to provide such a tool to decode all the machine codes\n * into assemble, or rathen source code, either. As the optimize work we might probably did in the future, this decode works would\n * be a hard problem, which was considered unnecessary.\n */\n\n__rathen_begin__\n\nenum reg\n{\n    _regzr = 0,\n    _eax = 1,\n    _ecx = 2,\n    _edx,\n    _ebx,\n    _esp,\n    _ebp,\n    _esi,\n    _edi,\n    /* more to come... */\n};\n\n#ifdef _GS_X86\n\ninline byte get_register_index(reg r)\n{\n    switch(r)\n    {\n    case _eax:      return 0;\n    case _ecx:      return 1;\n    case _edx:      return 2;\n    case _ebx:      return 3;\n    case _esp:      return 4;   /* why \"no index\" */\n    case _ebp:      return 5;\n    case _esi:      return 6;\n    case _edi:      return 7;\n    default:        assert(0);\n    }\n    return -1;\n}\n\ntypedef const gchar*    lab;\n\n#define __rasm_make_type(tname, dname) \\\n    struct tname \\\n    { \\\n        dname       _data; \\\n        \\\n        explicit tname(dname d = (dname)0) { _data = d; } \\\n        bool operator == (const tname& d) const { return _data == d._data; } \\\n        dname inner_data() const { return _data; } \\\n    }\n\n__rasm_make_type(_bias_, int);\n__rasm_make_type(_bias8_, int8);\n__rasm_make_type(_bias16_, int16);\n__rasm_make_type(_mem_, int);\n__rasm_make_type(_reg_, reg);\n\nenum cccc\n{\n    cccc_o = 0,\n    cccc_no,\n    cccc_c,\n    cccc_nc,\n    cccc_e,\n    cccc_ne,\n    cccc_be,\n    cccc_a,\n    cccc_s,\n    cccc_ns,\n    cccc_p,\n    cccc_np,\n    cccc_l,\n    cccc_ge,\n    cccc_le,\n    cccc_g,\n};\n\nstruct __gs_novtable rasm_instr abstract\n{\n    virtual ~rasm_instr() {}\n    virtual const gchar* get_name() const = 0;\n    virtual bool finalize(vessel& vsl) = 0;\n    virtual void to_string(string& str) const = 0;\n    virtual bool compare(const rasm_instr* that) const = 0;\n};\n\ninline const gchar* nameofreg(reg r)\n{\n    switch(r)\n    {\n    case _eax:  return _t(\"eax\");\n    case _ecx:  return _t(\"ecx\");\n    case _edx:  return _t(\"edx\");\n    case _ebx:  return _t(\"ebx\");\n    case _esp:  return _t(\"esp\");\n    case _ebp:  return _t(\"ebp\");\n    case _esi:  return _t(\"esi\");\n    case _edi:  return _t(\"edi\");\n    }\n    return 0;\n}\n\ntemplate<class _in>\nstruct rasm_instr0:\n    public _in\n{\n    virtual void to_string(string& str) const override { print(str, get_name(), _t(\";\")); }\n    virtual bool compare(const rasm_instr* that) const override { return strtool::compare(get_name(), that->get_name()) == 0; }\n    inline void print(string& str, const gchar* p, const gchar* a) const\n    {\n        if(p) { str += p; }\n        if(a) { str += a; }\n    }\n    inline void print(string& str, int n, const gchar* a) const\n    {\n        string s;\n        s.format(_t(\"%08x\"), n);\n        str += s;\n        if(a) { str += a; }\n    }\n    inline void print(string& str, reg n, const gchar* a) const\n    {\n        string s;\n        s.format(_t(\"[%s]\"), nameofreg(n));\n        str += s;\n        if(a) { str += a; }\n    }\n    inline void print(string& str, _bias8_ n, const gchar* a) const\n    {\n        string s;\n        s.format(_t(\"[s8:%02x]\"), (int)n.inner_data());\n        str += s;\n        if(a) { str += a; }\n    }\n    inline void print(string& str, _bias16_ n, const gchar* a) const\n    {\n        string s;\n        s.format(_t(\"[s16:%04x]\"), (int)n.inner_data());\n        str += s;\n        if(a) { str += a; }\n    }\n    inline void print(string& str, _bias_ n, const gchar* a) const\n    {\n        string s;\n        s.format(_t(\"[s:%08x]\"), (int)n.inner_data());\n        str += s;\n        if(a) { str += a; }\n    }\n    inline void print(string& str, _mem_ n, const gchar* a) const\n    {\n        string s;\n        s.format(_t(\"[m:%08x]\"), (int)n.inner_data());\n        str += s;\n        if(a) { str += a; }\n    }\n    inline void print(string& str, _reg_ n, const gchar* a) const\n    {\n        string s;\n        s.format(_t(\"[%s]\"), nameofreg(n.inner_data()));\n        str += s;\n        if(a) { str += a; }\n    }\n};\n\ntemplate<class c1>\nstruct rasm_instr1:\n    public rasm_instr0<rasm_instr>\n{\n    typedef c1  type1;\n    typedef rasm_instr1<c1> myref;\n\n    c1              _data1;\n\n    rasm_instr1(c1 a) { _data1 = a; }\n    virtual void to_string(string& str) const override\n    {\n        print(str, get_name(), _t(\"  \"));\n        print(str, _data1, _t(\";\"));\n    }\n    virtual bool compare(const rasm_instr* that) const override\n    {\n        if(strtool::compare(get_name(), that->get_name()) != 0)\n            return false;\n        const myref* ptr = static_cast<const myref*>(that);\n        return _data1 == ptr->_data1;\n    }\n};\n\nstruct __gs_novtable rasm_link abstract:\n    public rasm_instr\n{\n    virtual bool is_linker() const = 0;\n    virtual const string& get_label() const = 0;\n};\n\nstruct rasm_linker;\n\nstruct rasm_label:\n    public rasm_instr0<rasm_link>\n{\n    typedef rasm_linker linker;\n    typedef gs::vector<linker*> linker_list;\n\n    string          _label;\n    linker_list     _linkers;\n\npublic:\n    rasm_label(lab l) { _label.assign(l); }\n    virtual const gchar* get_name() const override { return _t(\"label\"); }\n    virtual bool finalize(vessel& vsl) override { return true; }\n    virtual void to_string(string& str) const override;\n    virtual bool compare(const rasm_instr* that) const override;\n    virtual bool is_linker() const override { return false; }\n    virtual const string& get_label() const override { return _label; }\n\npublic:\n    int get_linker_ctr() const { return (int)_linkers.size(); }\n    rasm_linker* get_linker(int i) { return _linkers.at(i); }\n    void add_linker(linker* p) { _linkers.push_back(p); }\n};\n\nstruct rasm_linker:\n    public rasm_instr0<rasm_link>\n{\n    typedef lab type1;\n    typedef rasm_linker linker;\n    typedef gs::vector<linker*> linker_list;\n\n    string          _label;\n    int             _linkeeid;\n    linker_list     _affects;\n\npublic:\n    rasm_linker(lab l): _linkeeid(0) { _label.assign(l); }\n    virtual void to_string(string& str) const override;\n    virtual bool compare(const rasm_instr* that) const override;\n    virtual bool is_linker() const override { return true; }\n    virtual const string& get_label() const override { return _label; }\n\npublic:\n    void set_linkee_index(int i) { _linkeeid = i; }\n    int get_linkee_index() const { return _linkeeid; }\n    void add_affects(linker* p) { _affects.push_back(p); }\n};\n\ntemplate<class c1, class c2>\nstruct rasm_instr2:\n    public rasm_instr1<c1>\n{\n    typedef c2  type2;\n    typedef rasm_instr2<c1, c2> myref;\n\n    c2              _data2;\n\n    rasm_instr2(c1 a, c2 b): rasm_instr1(a) { _data2 = b; }\n    virtual void to_string(string& str) const override\n    {\n        print(str, get_name(), _t(\"  \"));\n        print(str, _data1, _t(\",\"));\n        print(str, _data2, _t(\";\"));\n    }\n    virtual bool compare(const rasm_instr* that) const override\n    {\n        if(strtool::compare(get_name(), that->get_name()) != 0)\n            return false;\n        const myref* ptr = static_cast<const myref*>(that);\n        return _data1 == ptr->_data1 && _data2 == ptr->_data2;\n    }\n};\n\ntemplate<class c1, class c2, class c3>\nstruct rasm_instr3:\n    public rasm_instr2<c1, c2>\n{\n    typedef c3  type3;\n    typedef rasm_instr3<c1, c2, c3> myref;\n\n    c3              _data3;\n\n    rasm_instr3(c1 a, c2 b, c3 c): rasm_instr2(a, b) { _data3 = c; }\n    virtual void to_string(string& str) const override\n    {\n        print(str, get_name(), _t(\"  \"));\n        print(str, _data1, _t(\",\"));\n        print(str, _data2, _t(\",\"));\n        print(str, _data3, _t(\";\"));\n    }\n    virtual bool compare(const rasm_instr* that) const override\n    {\n        if(strtool::compare(get_name(), that->get_name()) != 0)\n            return false;\n        const myref* ptr = static_cast<const myref*>(that);\n        return _data1 == ptr->_data1 && _data2 == ptr->_data2 && _data3 == ptr->_data3;\n    }\n};\n\n#define rasm_reginstr(in) \\\n    static rasm_instr* make_##in(); \\\n    void in() { _list.push_back(make_##in()); }\n\n#define rasm_reginstr_i_begin(in, c1) \\\n    static rasm_instr* make_##in(c1); \\\n    void in(c1 a) {\n\n#define rasm_reginstr_i_end(in) \\\n    _list.push_back(make_##in(a)); }\n\n#define rasm_reginstr_i(in, c1) \\\n    rasm_reginstr_i_begin(in, c1) \\\n    rasm_reginstr_i_end(in)\n\n#define rasm_reginstr_ii_begin(in, c1, c2) \\\n    static rasm_instr* make_##in(c1, c2); \\\n    void in(c1 a, c2 b) {\n\n#define rasm_reginstr_ii_end(in) \\\n    _list.push_back(make_##in(a, b)); }\n\n#define rasm_reginstr_ii(in, c1, c2) \\\n    rasm_reginstr_ii_begin(in, c1, c2) \\\n    rasm_reginstr_ii_end(in)\n\n#define rasm_reginstr_iii_begin(in, c1, c2, c3) \\\n    static rasm_instr* make_##in(c1, c2, c3); \\\n    void in(c1 a, c2 b, c3 c) {\n\n#define rasm_reginstr_iii_end(in) \\\n    _list.push_back(make_##in(a, b, c)); }\n\n#define rasm_reginstr_iii(in, c1, c2, c3) \\\n    rasm_reginstr_iii_begin(in, c1, c2, c3) \\\n    rasm_reginstr_iii_end(in)\n\n#define rasm_reginstr_lab(in, c1) \\\n    static rasm_instr* make_##in(c1); \\\n    void in(c1 a) \\\n    { \\\n        rasm_label* ptr = static_cast<rasm_label*>(make_##in(a)); \\\n        assert(ptr && \"alloc failed.\"); \\\n        _list.push_back(ptr); \\\n        verify(_label.insert(std::make_pair(ptr->get_label(), get_last_instruction_index())).second && \"insert failed.\"); \\\n    }\n\n#define rasm_reginstr_lnk(in, c1) \\\n    static rasm_instr* make_##in(c1); \\\n    void in(c1 a) \\\n    { \\\n        rasm_linker* ptr = static_cast<rasm_linker*>(make_##in(a)); \\\n        assert(ptr && \"alloc failed.\"); \\\n        _list.push_back(ptr); \\\n        _link.push_back(ptr); \\\n    }\n\n/*\r\n * Only the 8 - bit offsets need this optimization, but DONOT apply such kind of optimizations to immediate operands,\r\n * that might cause problems like \"mov eax, 1\" become \"mov ah, 1\", which was incorrect\r\n */\n#define rasm_optimize_b8(calling, bparam) \\\n    if((int)bparam.inner_data() > (int)-0x80 && (int)bparam.inner_data() < (int)0x80) \\\n        return calling;\n\n#define rasm_optimize_b16(calling, bparam) \\\n    if((int)bparam.inner_data() > (int)-0x8000 && (int)bparam.inner_data() < (int)0x8000) \\\n        return calling;\n\n/*\r\n * If a instruction was operated on the eax register, it could be optimized like:\r\n */\n#define rasm_optimize_acc(calling, rparam) \\\r\n    if(rparam == _eax) \\\r\n        return calling;\n\n/*\r\n * Optimize for inc or dec\r\n */\r\n#define rasm_optimize_i1(calling, iparam) \\\r\n    if(iparam == 1) \\\r\n        return calling;\r\n\r\n/*\r\n * Optimize for immediate operants less than 1 byte. Instructions like loop need this optimization\r\n */\r\n#define rasm_optimize_i8(calling, iparam) \\\r\n    if((int)iparam > (int)-0x80 && (int)iparam < (int)0x80) \\\r\n        return calling;\n\nclass rasm\n{\npublic:\n    typedef gs::vector<rasm_instr*> instr_list;\n    typedef gs::vector<rasm_link*> link_list;\n    typedef gs::unordered_map<gs::string, int> label_map;       /* label name => index in instruction list */\n\npublic:\n    rasm() {}\n    ~rasm();\n    void print(string& str) const;\n    int finalize(vessel& vsl);\n    int get_last_instruction_index() const;\n    //link get_label(lab l) { return _label.find(l); }\n    //link no_label() { return _label.end(); }\n    //const_link get_label(lab l) const { return _label.find(l); }\n    //const_link no_label() const { return _label.end(); }\n    //iterator get_current() { return _list.end(); }\n    //const_iterator get_current() const { return _list.end(); }\n    //iterator get_head() { return _list.begin(); }\n    //const_iterator get_head() const { return _list.begin(); }\n    //void attach(const_iterator pos, rasm& other);\n    //iterator tick() { return _list.size() ? -- _list.end() : _list.end(); }\n    //void tick(iterator& i) { i = tick(); }\n\nprotected:\n    instr_list      _list;\n    label_map       _label;\n    link_list       _link;\n\npublic:\n    rasm_reginstr_ii(mov, reg, int8);\n    rasm_reginstr_ii(mov, reg, int);\n    rasm_reginstr_ii(mov, reg, reg);\n    rasm_reginstr_ii(mov, reg, _mem_);\n    rasm_reginstr_ii(mov, reg, _bias8_);\n    rasm_reginstr_ii_begin(mov, reg, _bias_)\n        rasm_optimize_b8(mov(a, (_bias8_)b.inner_data()), b)\n        rasm_reginstr_ii_end(mov);\n    rasm_reginstr_ii(mov, _mem_, reg);\n    rasm_reginstr_ii(mov, _bias8_, reg);\n    rasm_reginstr_ii_begin(mov, _bias_, reg)\n        rasm_optimize_b8(mov((_bias8_)a.inner_data(), b), a)\n        rasm_reginstr_ii_end(mov);\n    rasm_reginstr_ii(mov, _mem_, int);\n    rasm_reginstr_ii(mov, _bias8_, int);\n    rasm_reginstr_ii_begin(mov, _bias_, int)\n        rasm_optimize_b8(mov((_bias8_)a.inner_data(), b), a)\n        rasm_reginstr_ii_end(mov);\n    rasm_reginstr_ii(mov, reg, _reg_);\n    rasm_reginstr_ii(mov, _reg_, reg);\n    rasm_reginstr_ii(lea, reg, _bias8_);\n    rasm_reginstr_ii_begin(lea, reg, _bias_)\n        rasm_optimize_b8(lea(a, (_bias8_)b.inner_data()), b)\n        rasm_reginstr_ii_end(lea);\n    rasm_reginstr(nop);\n    rasm_reginstr(hlt);\n    rasm_reginstr_i(call, int);\n    rasm_reginstr_i(call, reg);\n    rasm_reginstr_i(call, _bias_);\n    rasm_reginstr_lnk(call, lab);\n    rasm_reginstr(ret);\n    rasm_reginstr_i(ret, int);\n    rasm_reginstr_i(push, reg);\n    rasm_reginstr_i(push, int8);\n    rasm_reginstr_i(push, int);\n    rasm_reginstr_i(push, _mem_);\n    rasm_reginstr_i(push, _bias8_);\n    rasm_reginstr_i_begin(push, _bias_)\n        rasm_optimize_b8(push((_bias8_)a.inner_data()), a)\n        rasm_reginstr_i_end(push);\n    rasm_reginstr_i(push, _reg_);\n    rasm_reginstr_i(pushw, _bias8_);\n    rasm_reginstr_i_begin(pushw, _bias_)\n        rasm_optimize_b8(pushw((_bias8_)a.inner_data()), a)\n        rasm_reginstr_i_end(pushw);\n    rasm_reginstr(pushad);\n    rasm_reginstr_i(pop, reg);\n    rasm_reginstr_i(pop, _mem_);\n    rasm_reginstr_i(pop, _bias8_);\n    rasm_reginstr_i_begin(pop, _bias_)\n        rasm_optimize_b8(pop((_bias8_)a.inner_data()), a)\n        rasm_reginstr_i_end(pop);\n    rasm_reginstr(popad);\n    rasm_reginstr_lab(label, lab);\n    rasm_reginstr_i(jmp, _mem_);\n    rasm_reginstr_i(jmp, _bias8_);\n    rasm_reginstr_i_begin(jmp, _bias_)\n        rasm_optimize_b8(jmp((_bias8_)a.inner_data()), a)\n        rasm_reginstr_i_end(jmp);\n    rasm_reginstr_i(jmp, reg);\n    rasm_reginstr_i(jmps, _bias8_);         /* jmp bias from ss */\n    rasm_reginstr_i_begin(jmps, _bias_)\n        rasm_optimize_b8(jmps((_bias8_)a.inner_data()), a)\n        rasm_reginstr_i_end(jmps);\n    //rasm_reginstr_i(jmp, lab);\n    rasm_reginstr_lnk(jmp, lab);\n    rasm_reginstr_i(jes, _bias8_);\n    rasm_reginstr_i_begin(jes, _bias_)\n        rasm_optimize_b8(jes((_bias8_)a.inner_data()), a)\n        rasm_reginstr_i_end(jes);\n    rasm_reginstr_i(jnes, _bias8_);\n    rasm_reginstr_i_begin(jnes, _bias_)\n        rasm_optimize_b8(jnes((_bias8_)a.inner_data()), a)\n        rasm_reginstr_i_end(jnes);\n    rasm_reginstr_i(loop, int8);\n    rasm_reginstr_i_begin(loop, int)        /* I'm not sure about this, can the loop instruction operate on a short? */\n        rasm_optimize_i8(loop((int8)a), (a - 2))\n        rasm_reginstr_i_end(loop);\n    rasm_reginstr_lnk(loop, lab);\n    rasm_reginstr(cld);\n    rasm_reginstr(std);\n    rasm_reginstr(movsb);\n    rasm_reginstr(movsw);\n    rasm_reginstr(movs);\n    rasm_reginstr(rep);\n    rasm_reginstr_ii(cmp, _bias_, int);\n    rasm_reginstr_ii(cmp, reg, int8);\n    rasm_reginstr_ii(cmp, reg, int);\n    rasm_reginstr_ii(cmp, reg, _bias8_);\n    rasm_reginstr_ii_begin(cmp, reg, _bias_)\n        rasm_optimize_b8(cmp(a, (_bias8_)b.inner_data()), b)\n        rasm_reginstr_ii_end(cmp);\n    rasm_reginstr_ii(cmp, _reg_, int8);\n    rasm_reginstr_ii(cmp, _reg_, int);\n    rasm_reginstr_ii(cmp, reg, _reg_);\n    rasm_reginstr_i(inc, reg);\n    rasm_reginstr_i(inc, _mem_);\n    rasm_reginstr_i(inc, _bias8_);\n    rasm_reginstr_i_begin(inc, _bias_)\n        rasm_optimize_b8(inc((_bias8_)a.inner_data()), a)\n        rasm_reginstr_i_end(inc);\n    rasm_reginstr_ii(add, reg, reg);\n    rasm_reginstr_ii(add, reg, int8);\n    rasm_reginstr_ii(add, reg, int);\n    rasm_reginstr_i(add, int);\n    rasm_reginstr_ii(add, reg, _mem_);\n    rasm_reginstr_ii(add, reg, _bias8_);\n    rasm_reginstr_ii(add, reg, _bias_);\n    rasm_reginstr_ii(add, _mem_, int8);\n    rasm_reginstr_ii(add, _mem_, int);\n    rasm_reginstr_ii(add, _bias8_, int8);\n    rasm_reginstr_ii(add, _bias_, int8);\n    rasm_reginstr_ii(add, _bias8_, int);\n    rasm_reginstr_ii(add, _bias_, int);\n    rasm_reginstr_ii(add, _mem_, reg);\n    rasm_reginstr_ii(add, _bias8_, reg);\n    rasm_reginstr_ii(add, _bias_, reg);\n    rasm_reginstr_ii(add, reg, _reg_);\n    rasm_reginstr_ii(add, _reg_, reg);\n    rasm_reginstr_i(dec, reg);\n    rasm_reginstr_i(dec, _mem_);\n    rasm_reginstr_i(dec, _bias_);\n    rasm_reginstr_ii(sub, reg, reg);\n    rasm_reginstr_ii(sub, reg, int);\n    rasm_reginstr_i(sub, int);\n    rasm_reginstr_ii(sub, reg, _mem_);\n    rasm_reginstr_ii(sub, reg, _bias_);\n    rasm_reginstr_ii(sub, _mem_, int);\n    rasm_reginstr_ii(sub, _bias_, int);\n    rasm_reginstr_ii(sub, _mem_, reg);\n    rasm_reginstr_ii(sub, _bias_, reg);\n    rasm_reginstr_ii(sub, reg, _reg_);\n    rasm_reginstr_ii(sub, _reg_, reg);\n    rasm_reginstr_iii(imul, reg, reg, int);\n    rasm_reginstr_ii(imul, reg, int);\n    rasm_reginstr_i(imul, reg);\n    rasm_reginstr_ii(imul, reg, _mem_);\n    rasm_reginstr_ii(imul, reg, _bias_);\n    rasm_reginstr_iii(imul, reg, _mem_, int);\n    rasm_reginstr_iii(imul, reg, _bias_, int);\n    rasm_reginstr_ii(imul, reg, reg);\n    rasm_reginstr_i(imul, _mem_);\n    rasm_reginstr_i(imul, _bias_);\n    rasm_reginstr_ii(imul, reg, _reg_);\n    rasm_reginstr_i(idiv, reg);\n    rasm_reginstr_i(idiv, _mem_);\n    rasm_reginstr_i(idiv, _bias_);\n    rasm_reginstr_i(idiv, _reg_);\n    rasm_reginstr(cdq);\n    rasm_reginstr_i(neg, reg);\n    rasm_reginstr_i(not, reg);\n    rasm_reginstr_ii(xor, reg, reg);\n    rasm_reginstr_ii(xor, reg, int);\n    rasm_reginstr_ii(xor, reg, _bias_);\n    rasm_reginstr_ii(xor, reg, _reg_);\n    rasm_reginstr_i(shl, reg);\n    rasm_reginstr_ii(shl, reg, int);\n    rasm_reginstr_i(shr, reg);\n    rasm_reginstr_ii(shr, reg, int);\n    //rasm_reginstr\n    //setcc\n    rasm_reginstr_ii(and, reg, int);\n    rasm_reginstr_ii(and, reg, _bias_);\n    rasm_reginstr_ii(and, reg, _reg_);\n    rasm_reginstr_ii(or , reg, int);\n    rasm_reginstr_ii(or , reg, _bias_);\n    rasm_reginstr_ii(or , reg, _reg_);\n};\n\n#endif\n\n__rathen_end__\n\n#endif", "meta": {"hexsha": "bd1b78e0c9d22fbed36ebc250e13c40af14f5af6", "size": 20376, "ext": "h", "lang": "C", "max_stars_repo_path": "include/rathen/rasm.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/rathen/rasm.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/rathen/rasm.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 32.1895734597, "max_line_length": 133, "alphanum_fraction": 0.6489988221, "num_tokens": 6207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11757212736159102, "lm_q2_score": 0.03846619146718183, "lm_q1q2_score": 0.004522551962294848}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef string_81448b68_30d7_4d64_a67a_cecef7c90139_h\r\n#define string_81448b68_30d7_4d64_a67a_cecef7c90139_h\r\n\r\n#include <string>\r\n#include <assert.h>\r\n#include <gslib/type.h>\r\n\r\n__gslib_begin__\r\n\r\ntemplate<class _element>\r\nclass _std_string:\r\n    public std::basic_string<_element, std::char_traits<_element>, std::allocator<_element> >\r\n{\r\npublic:\r\n    typedef _element protoch;\r\n    typedef std::char_traits<protoch> prototr;\r\n    typedef std::allocator<protoch> protoalloc;\r\n    typedef std::basic_string<protoch, prototr, protoalloc> protoref;\r\n    friend gs_export int _vsprintf(_std_string<char>& str, const char* fmt, va_list ap);\r\n    friend gs_export int _vsprintf(_std_string<wchar>& str, const wchar* fmt, va_list ap);\r\n};\r\n\r\ntemplate<class _element>\r\nstruct _string_tool\r\n{\r\n    typedef _element element;\r\n};\r\n\r\ntemplate<>\r\nstruct _string_tool<char>\r\n{\r\n    static void copy(char* des, size_t size, const char* src) { strcpy_s(des, size, src); }\r\n    static int length(const char* str) { return (int)strlen(str); }\r\n    static int compare(const char* s1, const char* s2) { return (int)strcmp(s1, s2); }\r\n    static int compare_cl(const char* s1, const char* s2) { return (int)_stricmp(s1, s2); }\r\n    static int compare(const char* s1, const char* s2, int cnt) { return (int)strncmp(s1, s2, cnt); }\r\n    static int compare_cl(const char* s1, const char* s2, int cnt) { return (int)_strnicmp(s1, s2, cnt); }\r\n    static int vprintf(char* des, int size, const char* fmt, va_list ap) { return _vsprintf_s_l(des, size, fmt, 0, ap); }\r\n    static int printf(char* des, int size, const char* fmt, ...)\r\n    {\r\n        va_list ptr;\r\n        va_start(ptr, fmt);\r\n        return _vsprintf_s_l(des, size, fmt, 0, ptr);\r\n    }\r\n    static int vsscanf(const char* src, const char* fmt, va_list ap) { return vsscanf_s(src, fmt, ap); }\r\n    static int sscanf(const char* src, const char* fmt, ...)\r\n    {\r\n        va_list ptr;\r\n        va_start(ptr, fmt);\r\n        return vsscanf_s(src, fmt, ptr);\r\n    }\r\n    static int ctlprintf(const char* src, ...)\r\n    {\r\n        va_list ptr;\r\n        va_start(ptr, src);\r\n        return ::vprintf(src, ptr);\r\n    }\r\n    static int to_int(const char* src) { return atoi(src); }\r\n    static int to_int(const char* src, int radix) { return strtol(src, 0, radix); }\r\n    static uint to_uint(const char* src, int radix) { return strtoul(src, 0, radix); }\r\n    static int64 to_int64(const char* src) { return _atoi64(src); }\r\n    static int64 to_int64(const char* src, int radix) { return _strtoi64(src, 0, radix); }\r\n    static uint64 to_uint64(const char* src, int radix) { return _strtoui64(src, 0, radix); }\r\n    static real to_real(const char* src) { return atof(src); }\r\n    static void from_int(int i, char* des, int size, int radix) { _itoa_s(i, des, size, radix); }\r\n    static void from_int64(int64 i, char* des, int size, int radix) { _i64toa_s(i, des, size, radix); }\r\n    static void from_real(char* des, int size, real d) { from_real(des, size, d, size-2); }\r\n    static void from_real(char* des, int size, real d, int precis) { _gcvt_s(des, size, d, precis); }\r\n    static void to_lower(char* str, int size) { _strlwr_s(str, size); }\r\n    static void to_upper(char* str, int size) { _strupr_s(str, size); }\r\n    static const char* find(const char* src, const char* tar) { return strstr(src, tar); }\r\n    static int test(const char* src, const char* cpset) { return (int)strcspn(src, cpset); }\r\n    static const char* _test(const char* src, const char* cpset) { return strpbrk(src, cpset); }\r\n};\r\n\r\ntemplate<>\r\nstruct _string_tool<wchar>\r\n{\r\n    static void copy(wchar* des, size_t size, const wchar* src) { wcscpy_s(des, size, src); }\r\n    static int length(const wchar* str) { return (int)wcslen(str); }\r\n    static int compare(const wchar* s1, const wchar* s2) { return (int)wcscmp(s1, s2); }\r\n    static int compare_cl(const wchar* s1, const wchar* s2) { return (int)_wcsicmp(s1, s2); }\r\n    static int compare(const wchar* s1, const wchar* s2, int cnt) { return (int)wcsncmp(s1, s2, cnt); }\r\n    static int compare_cl(const wchar* s1, const wchar* s2, int cnt) { return (int)_wcsnicmp(s1, s2, cnt); }\r\n    static int vprintf(wchar* des, int size, const wchar* fmt, va_list ap) { return _vswprintf_s_l(des, size, fmt, 0, ap); }\r\n    static int printf(wchar* des, int size, const wchar* fmt, ...)\r\n    {\r\n        va_list ptr;\r\n        va_start(ptr, fmt);\r\n        return _vswprintf_s_l(des, size, fmt, 0, ptr);\r\n    }\r\n    static int vsscanf(const wchar* src, const wchar* fmt, va_list ap) { return vswscanf_s(src, fmt, ap); }\r\n    static int sscanf(const wchar* src, const wchar* fmt, ...)\r\n    {\r\n        va_list ptr;\r\n        va_start(ptr, fmt);\r\n        return vswscanf_s(src, fmt, ptr);\r\n    }\r\n    static int ctlprintf(const wchar* src, ...)\r\n    {\r\n        va_list ptr;\r\n        va_start(ptr, src);\r\n        return ::vwprintf(src, ptr);\r\n    }\r\n    static int to_int(const wchar* src) { return _wtoi(src); }\r\n    static int to_int(const wchar* src, int radix) { return wcstol(src, 0, radix); }\r\n    static uint to_uint(const wchar* src, int radix) { return wcstoul(src, 0, radix); }\r\n    static int64 to_int64(const wchar* src) { return _wtoi64(src); }\r\n    static int64 to_int64(const wchar* src, int radix) { return _wcstoi64(src, 0, radix); }\r\n    static uint64 to_uint64(const wchar* src, int radix) { return _wcstoui64(src, 0, radix); }\r\n    static real to_real(const wchar* src) { return _wtof(src); }\r\n    static void from_int(int i, wchar* des, int size, int radix) { _itow_s(i, des, size, radix); }\r\n    static void from_int64(int64 i, wchar* des, int size, int radix) { _i64tow_s(i, des, size, radix); }\r\n    static void from_real(wchar* des, int size, real d) { from_real(des, size, d, size-2); }\r\n    static void from_real(wchar* des, int size, real d, int precis)\r\n    {\r\n        _gcvt_s((char*)des, size, d, precis);\r\n        int len = (int)strlen((char*)des); /* call it in asm wasn't available in /o2 */\r\n        __asm\r\n        {\r\n            mov  ecx, len;\r\n            mov  esi, des;\r\n            add  esi, ecx;\r\n            mov  edi, esi;\r\n            add  edi, ecx;\r\n            mov  word ptr[edi], 0;\r\n            std;\r\n        rptag:\r\n            movsb;\r\n            mov  byte ptr[edi], 0;\r\n            dec  edi;\r\n            loop rptag;\r\n            cld;\r\n        }\r\n    }\r\n    static void to_lower(wchar* str, int size) { _wcslwr_s(str, size); }\r\n    static void to_upper(wchar* str, int size) { _wcsupr_s(str, size); }\r\n    static const wchar* find(const wchar* src, const wchar* tar) { return wcsstr(src, tar); }\r\n    static int test(const wchar* src, const wchar* cpset) { return (int)wcsspn(src, cpset); }\r\n    static const wchar* _test(const wchar* src, const wchar* cpset) { return wcspbrk(src, cpset); }\r\n};\r\n\r\ngs_export extern const char* get_mbcs_elem(const char* str, uint& c);\r\ngs_export extern const char* get_mbcs_elem(const char* str, uint& c, const char* end);\r\ngs_export extern int convert_to_wide(wchar out[], int size, const char* str, int len = -1);\r\ngs_export extern int convert_to_byte(char out[], int size, const wchar* str, int len = -1);\r\ngs_export extern int convert_utf8_to_wide(wchar out[], int size, const char* str, int len = -1);\r\ngs_export extern int convert_wide_to_utf8(char out[], int size, const wchar* str, int len = -1);\r\n\r\nstruct _string_caseful {};\r\nstruct _string_caseless {};\r\n\r\ntemplate<class _element, \r\n    class _cpcase = _string_caseful>\r\nclass _string:\r\n    public _std_string<_element>\r\n{\r\npublic:\r\n    typedef _element element;\r\n    typedef _std_string<element> inheritref;\r\n    typedef _string_tool<element> _strtool;\r\n    typedef typename inheritref::protoref protoref;\r\n    typedef _string<_element, _cpcase> myref;\r\n\r\n    template<class _cpcase> static int comparefunc(const _string* s, const element* str);\r\n    template<class _cpcase> static  int comparefunc(const _string* s, const element* str, int len);\r\n    template<> static int comparefunc<_string_caseful>(const _string* s, const element* str) { return _strtool::compare(s->c_str(), str); }\r\n    template<> static int comparefunc<_string_caseless>(const _string* s, const element* str) { return _strtool::compare_cl(s->c_str(), str); }\r\n    template<> static int comparefunc<_string_caseful>(const _string* s, const element* str, int len) { return _strtool::compare(s->c_str(), str, len); }\r\n    template<> static int comparefunc<_string_caseless>(const _string* s, const element* str, int len) { return _strtool::compare_cl(s->c_str(), str, len); }\r\n\r\nprotected:\r\n#ifdef _MSC_VER\r\n#if (_MSC_VER >= 1920)\r\n    element* _stl_rawstr() { return const_cast<element*>(c_str()); }\r\n    const element* _stl_rawstr() const { return c_str(); }\r\n#elif (_MSC_VER >= 1914)\r\n    element* _stl_rawstr() { return this->_Get_data()._Myptr(); }\r\n    const element* _stl_rawstr() const { return this->_Get_data()._Myptr(); }\r\n#else\r\n    element* _stl_rawstr() { return this->_Myptr(); }\r\n    const element* _stl_rawstr() const { return this->_Myptr(); }\r\n#endif\r\n#if (_MSC_VER >= 1920)\r\n    int _stl_cap() const { return (int)capacity(); }\r\n    void _stl_fix() { resize(_strtool::length(c_str())); }\r\n#elif (_MSC_VER >= 1914)\r\n    int& _stl_cap() { return (int&)this->_Get_data()._Myres; }\r\n    int& _stl_size() { return (int&)this->_Get_data()._Mysize; }\r\n    void _stl_fix() { this->_stl_size() = _strtool::length(this->c_str()); }\r\n#elif ((_MSC_VER >= 1900) && (_MSC_VER < 1910))\r\n    int& _stl_cap() { return (int&)this->_Myres(); }\r\n    int& _stl_size() { return (int&)this->_Mysize(); }\r\n    void _stl_fix() { this->_Mysize() = (size_t)_strtool::length(this->c_str()); }\r\n#else\r\n    int& _stl_cap() { return (int&)this->_Myres; }\r\n    int& _stl_size() { return (int&)this->_Mysize; }\r\n    void _stl_fix() { this->_Mysize = (size_t)_strtool::length(this->c_str()); }\r\n#endif\r\n#if (_MSC_VER >= 1920)\r\n    void _stl_eos(int pos) { this->resize(pos); }\r\n#else\r\n    void _stl_eos(int pos) { this->_Eos(pos); }\r\n#endif\r\n#endif      /* endif _MSC_VER */\r\n\r\nprivate:\r\n    template<class _element>\r\n    void convert_from(const wchar* str);\r\n    template<class _element>\r\n    void convert_from(const char* str);\r\n    template<>\r\n    void convert_from<wchar>(const wchar* str) { assign(str); }\r\n    template<>\r\n    void convert_from<char>(const wchar* str)\r\n    {\r\n        int len = convert_to_byte(0, 0, str);\r\n        resize(len);\r\n        convert_to_byte(_stl_rawstr(), len, str);\r\n        _stl_fix();\r\n    }\r\n    template<>\r\n    void convert_from<wchar>(const char* str)\r\n    {\r\n        int len = convert_to_wide(0, 0, str);\r\n        resize(len);\r\n        convert_to_wide(_stl_rawstr(), len, str);\r\n        _stl_fix();\r\n    }\r\n    template<>\r\n    void convert_from<char>(const char* str) { assign(str); }\r\n    template<class _element>\r\n    void convert_from(const char* str, int len);\r\n    template<class _element>\r\n    void convert_from(const wchar* str, int len);\r\n    template<>\r\n    void convert_from<wchar>(const wchar* str, int len) { assign(str, len); }\r\n    template<>\r\n    void convert_from<wchar>(const char* str, int len)\r\n    {\r\n        int l = convert_to_wide(0, 0, str, len);\r\n        resize(l + 1);\r\n        convert_to_wide(_stl_rawstr(), l, str, len);\r\n        _stl_eos(l);\r\n    }\r\n    template<>\r\n    void convert_from<char>(const wchar* str, int len)\r\n    {\r\n        int l = convert_to_byte(0, 0, str, len);\r\n        resize(l + 1);\r\n        convert_to_byte(_stl_rawstr(), l, str, len);\r\n        _stl_eos(l);\r\n    }\r\n    template<>\r\n    void convert_from<char>(const char* str, int len) { assign(str, len); }\r\n\r\npublic:\r\n    _string() {}\r\n    _string(const element* str) { if(str) this->assign(str); }\r\n    _string(const element* str, int len) { if(str) this->assign(str, len); }\r\n    _string(element c, int ctr) { this->assign(ctr, c); }\r\n    void destroy() { clear(); }\r\n    int length() const { return (int)this->size(); }\r\n    element& front() { return this->at(0); }\r\n    const element& front() const { return this->at(0); }\r\n    element& back() { return this->at(this->size() - 1); }\r\n    const element& back() const { return this->at(this->size() - 1); }\r\n    element pop_back()\r\n    {\r\n        element e = back();\r\n        resize(this->size() - 1);\r\n        return e;\r\n    }\r\n    int test(const element* cpset) const\r\n    {\r\n        if(this->empty())\r\n            return (int)this->npos;\r\n        int pos = _strtool::test(this->c_str(), cpset);\r\n        if(pos == length())\r\n            return (int)this->npos;\r\n        return pos;\r\n    }\r\n    int test(int off, const element* cpset) const\r\n    {\r\n        if(this->empty() || off >= length())\r\n            return (int)this->npos;\r\n        int pos = _strtool::test(this->c_str() + off, cpset);\r\n        if(pos == length())\r\n            return (int)this->npos;\r\n        return pos;\r\n    }\r\n    const element* _test(const element* cpset) const\r\n    {\r\n        if(this->empty())\r\n            return nullptr;\r\n        return _strtool::_test(this->c_str(), cpset);\r\n    }\r\n    const element* _test(int off, const element* cpset) const\r\n    {\r\n        if(this->empty() || off >= length())\r\n            return nullptr;\r\n        return _strtool::_test(this->c_str() + off, cpset);\r\n    }\r\n    void format(const element* fmt, ...)\r\n    {\r\n        va_list ptr;\r\n        va_start(ptr, fmt);\r\n        _vsprintf(*this, fmt, ptr);\r\n    }\r\n    void formatv(const element* fmt, va_list ptr)\r\n    {\r\n        _vsprintf(*this, fmt, ptr);\r\n    }\r\n    /*\r\n    void format(int size, const element* fmt, ...)\r\n    {\r\n        _stl_grow(size, false);\r\n        va_list ptr;\r\n        va_start(ptr, fmt);\r\n        _stl_size() = _strtool::vprintf(_stl_rawstr(), _stl_cap(), fmt, ptr);\r\n    }\r\n    */\r\n    _string& to_lower()\r\n    {\r\n        if(this->empty())\r\n            return *this;\r\n        _strtool::to_lower(_stl_rawstr(), _stl_cap());\r\n        return *this;\r\n    }\r\n    _string& to_upper()\r\n    {\r\n        if(this->empty())\r\n            return *this;\r\n        _strtool::to_upper(_stl_rawstr(), _stl_cap());\r\n        return *this;\r\n    }\r\n    int to_int() const { return _strtool::to_int(_stl_rawstr()); }\r\n    int to_int(int radix) const { return _strtool::to_int(_stl_rawstr(), radix); }\r\n    int64 to_int64() const { return _strtool::to_int64(_stl_rawstr()); }\r\n    int64 to_int64(int radix) const { return _strtool::to_int64(_stl_rawstr(), radix); }\r\n    real to_real() const { return _strtool::to_real(_stl_rawstr()); }\r\n    _string& from(const char* str)\r\n    {\r\n        convert_from<element>(str);\r\n        return *this;\r\n    }\r\n    _string& from(const wchar* str)\r\n    {\r\n        convert_from<element>(str);\r\n        return *this;\r\n    }\r\n    _string& from(const char* str, int len)\r\n    {\r\n        convert_from<element>(str, len);\r\n        return *this;\r\n    }\r\n    _string& from(const wchar* str, int len)\r\n    {\r\n        convert_from<element>(str, len);\r\n        return *this;\r\n    }\r\n    _string& from_int(int i, int radix = 10)\r\n    {\r\n        resize(12);\r\n        _strtool::from_int(i, _stl_rawstr(), _stl_cap(), radix);\r\n        _stl_fix();\r\n        return *this;\r\n    }\r\n    _string& from_int64(int64 i, int radix = 10)\r\n    {\r\n        resize(24);\r\n        _strtool::from_int64(i, _stl_rawstr(), _stl_cap(), radix);\r\n        _stl_fix();\r\n        return *this;\r\n    }\r\n    _string& from_real(real d, int precis = 22)\r\n    {\r\n        resize(precis + 2);\r\n        _strtool::from_real(_stl_rawstr(), _stl_cap(), d, precis);\r\n        _stl_fix();\r\n        return *this;\r\n    }\r\n    bool starts_with(const element* str, int len) const\r\n    {\r\n        assert(str);\r\n        int s = length();\r\n        if(len > s)\r\n            return false;\r\n        return compare(str, len) == 0;\r\n    }\r\n    bool ends_with(const element* str, int len) const\r\n    {\r\n        assert(str);\r\n        int s = length();\r\n        if(len > s)\r\n            return false;\r\n        return compare(str + s - len, len) == 0;\r\n    }\r\n    bool starts_with(const element* str) const { return starts_with(str, _strtool::length(str)); }\r\n    bool starts_with(const myref& str) const { return starts_with(str.c_str(), str.length()); }\r\n    bool starts_with(const myref& str, int len) const { return starts_with(str.c_str(), len); }\r\n    bool ends_with(const element* str) const { return ends_with(str, _strtool::length(str)); }\r\n    bool ends_with(const myref& str) const { return ends_with(str.c_str(), str.length()); }\r\n    bool ends_with(const myref& str, int len) const { return ends_with(str.c_str(), len); }\r\n    int compare(const element* str) const { return _strtool::compare(_stl_rawstr(), str); }\r\n    int compare(const element* str, int len) const { return _strtool::compare(_stl_rawstr(), str, len); }\r\n    int compare(int off, const element* str, int len) const { return _strtool::compare(_stl_rawstr() + off, str, len); }\r\n    int compare_cl(const element* str) const { return _strtool::compare_cl(_stl_rawstr(), str); }\r\n    int compare_cl(const element* str, int len) const { return _strtool::compare_cl(_stl_rawstr(), str, len); }\r\n    int compare_cl(int off, const element* str, int len) const { return _strtool::compare_cl(_stl_rawstr() + off, str, len); }\r\n    bool greater(const element* str) const { return comparefunc<_cpcase>(this, str) > 0; }\r\n    bool greater(const element* str, int len) const { return comparefunc<_cpcase>(this, str, len) > 0; }\r\n    bool equal(const element* str) const { return comparefunc<_cpcase>(this, str) == 0; }\r\n    bool equal(const element* str, int len) const { return comparefunc<_cpcase>(this, str, len) == 0; }\r\n    bool less(const element* str) const { return comparefunc<_cpcase>(this, str) < 0; }\r\n    bool less(const element* str, int len) const { return comparefunc<_cpcase>(this, str, len) < 0; }\r\n    bool operator < (const element* str) const { return less(str); }\r\n    bool operator < (const _string* str) const { return less(str->c_str(), str->length()); }\r\n    bool operator < (const _string& str) const { return less(str.c_str(), str.length()); }\r\n    bool operator == (const element* str) const { return equal(str); }\r\n    bool operator == (const _string* str) const { return equal(str->c_str(), str->length()); }\r\n    bool operator == (const _string& str) const { return equal(str.c_str(), str.length()); }\r\n    bool operator != (const element* str) const { return !equal(str); }\r\n    bool operator != (const _string* str) const { return !equal(str->c_str(), str->length()); }\r\n    bool operator != (const _string& str) const { return !equal(str.c_str(), str.length()); }\r\n    bool operator > (const element* str) const { return greater(str); }\r\n    bool operator > (const _string* str) const { return greater(str->c_str(), str->length()); }\r\n    bool operator > (const _string& str) const { return greater(str.c_str(), str.length()); }\r\n};\r\n\r\ntypedef _string_tool<gchar> strtool;\r\n\r\n/*\r\n * string compare tool for short const string, notify that the s1 increase:\r\n * string symmetrical check\r\n */\r\ntemplate<class _element>\r\nclass strsymcheck\r\n{\r\npublic:\r\n    typedef _element mchar;\r\n    typedef strsymcheck<mchar> mref;\r\n\r\npublic:\r\n    template<int _len>\r\n    static bool check(const mchar* s1, const mchar* s2) { return *s1 ++ == *s2 ++ && mref::check<_len-1>(s1, s2); }\r\n    template<>\r\n    static bool check<0>(const mchar* s1, const mchar* s2) { return true; }\r\n    template<>\r\n    static bool check<1>(const mchar* s1, const mchar* s2) { return *s1 ++ == *s2 ++; }\r\n    template<int _len>\r\n    static bool check_run(const mchar*& s1, const mchar* s2)\r\n    {\r\n        if(check<_len>(s1, s2)) {\r\n            s1 += _len;\r\n            return true;\r\n        }\r\n        return false;\r\n    }\r\n};\r\n\r\n#ifdef _cstrcmp\r\n#undef _cstrcmp\r\n#endif\r\n#define _cstrcmp(sr, cmp)    strsymcheck<gchar>::check<_cststrlen(cmp)>((sr), (cmp))\r\n\r\n#define _cstrncmp(sr, len, cmp) \\\r\n    ((len >= _cststrlen(cmp)) && strsymcheck<gchar>::check<_cststrlen(cmp)>((sr), (cmp)))\r\n\r\n#ifdef _cstrcmprun\r\n#undef _cstrcmprun\r\n#endif\r\n#define _cstrcmprun(sr, cmp) strsymcheck<gchar>::check_run<_cststrlen(cmp)>((sr), (cmp))\r\n\r\n#define mkstr(str1, str2) (((string(str1) += str2)).c_str())\r\n#define mkstr3(str1, str2, str3) (((string(str1) += str2) += str3).c_str())\r\n#define mkstr4(str1, str2, str3, str4) ((((string(str1) += str2) += str3) += str4).c_str())\r\n\r\ntemplate<int _cmpstr> inline\r\nbool strequ(const char* str) { return *(const int*)str == _cmpstr; }\r\ntemplate<char _cmpch> inline\r\nbool chequ(const char* str) { return *str == _cmpch; }\r\ntemplate<char _c1, char _c2>\r\nstruct chless { static const bool result = _c1 < _c2; };\r\ntemplate<char _c1, char _c2, bool _less = chless<_c1, _c2>::result>\r\nstruct chmin {};\r\ntemplate<char _c1, char _c2>\r\nstruct chmin<_c1, _c2, true> { static const char value = _c1; };\r\ntemplate<char _c1, char _c2>\r\nstruct chmin<_c1, _c2, false> { static const char value = _c2; };\r\ntemplate<char _c1, char _c2, bool _less = chless<_c1, _c2>::result>\r\nstruct chmax {};\r\ntemplate<char _c1, char _c2>\r\nstruct chmax<_c1, _c2, true> { static const char value = _c2; };\r\ntemplate<char _c1, char _c2>\r\nstruct chmax<_c1, _c2, false> { static const char value = _c1; };\r\ntemplate<int _len> inline\r\nchar strhit(const char* str, const char* cmp) { return *str == *cmp++ ? *str : strhit<_len + 1>(str, cmp); }\r\ntemplate<> inline\r\nchar strhit<1>(const char* str, const char* cmp) { return *str == *cmp ? *str : 0; }\r\ntemplate<> inline\r\nchar strhit<0>(const char* str, const char* cmp) { return *str; }\r\ntemplate<char _from, char _to>\r\nchar strhit(const char* str)\r\n{\r\n    return (*str >= chmin<_from, _to>::value && \r\n        *str <= chmax<_from, _to>::value) ?\r\n        *str : 0;\r\n}\r\n\r\n/* used by the tool chain. */\r\ninline int conv_quadstr(const char* str)\r\n{\r\n    int n = 0;\r\n    if(str[0] == 0)\r\n        return n;\r\n    n |= str[0];\r\n    if(str[1] == 0)\r\n        return n;\r\n    n |= ((uint)str[1]) << 8;\r\n    if(str[2] == 0)\r\n        return n;\r\n    n |= ((uint)str[2]) << 16;\r\n    if(str[3] == 0)\r\n        return n;\r\n    n |= ((uint)str[3]) << 24;\r\n    return n;\r\n}\r\ninline char _1of_quadstr(int quadstr) { return (char)(quadstr & 0xff); }\r\ninline char _2of_quadstr(int quadstr) { return (char)((quadstr & 0xff00) >> 8); }\r\ninline char _3of_quadstr(int quadstr) { return (char)((quadstr & 0xff0000) >> 16); }\r\ninline char _4of_quadstr(int quadstr) { return (char)((quadstr & 0xff000000) >> 24); }\r\ninline int len_of_quadstr(int quadstr)\r\n{\r\n    if(!(quadstr & 0xff))\r\n        return 0;\r\n    if(!(quadstr & 0xff00))\r\n        return 1;\r\n    if(!(quadstr & 0xff0000))\r\n        return 2;\r\n    return (quadstr & 0xff000000) ? 4 : 3;\r\n}\r\ninline int utf8_unit_len(const char* str)\r\n{\r\n    if(str[0] == 0)\r\n        return 0;\r\n    if(!(str[0] & 0x80))\r\n        return 1;\r\n    if((str[0] & 0xe0) == 0xc0)\r\n        return 2;\r\n    if((str[0] & 0xf0) == 0xe0)\r\n        return 3;\r\n    if((str[0] & 0xf8) == 0xf0)\r\n        return 4;\r\n    if((str[0] & 0xfc) == 0xf8)\r\n        return 5;\r\n    if((str[0] & 0xfe) == 0xfc)\r\n        return 6;\r\n    return -1;\r\n}\r\ninline bool is_utf8_head(const char* str)\r\n{\r\n    assert(str);\r\n    return (str[0] & 0xc0) != 0x80;\r\n}\r\ninline const char* to_utf8_head(const char* str)\r\n{\r\n    assert(str);\r\n    for( ; str[0] && !is_utf8_head(str); str --);\r\n    return str;\r\n}\r\ninline const char* next_utf8_unit(const char* str)\r\n{\r\n    assert(str);\r\n    if(str[0] == 0)\r\n        return str;\r\n    for(str ++; !is_utf8_head(str); str ++);\r\n    return str;\r\n}\r\ninline const char* prev_utf8_unit(const char* str)\r\n{\r\n    assert(str);\r\n    return to_utf8_head(-- str);\r\n}\r\ninline bool utf8_unit_valid(const char* str)\r\n{\r\n    assert(str);\r\n    return !is_utf8_head(str) ? false :\r\n        next_utf8_unit(str) - str == utf8_unit_len(str);\r\n}\r\ninline int utf8_len(const char* str)\r\n{\r\n    assert(str);\r\n    int len = 0;\r\n    for( ; str[0]; str = next_utf8_unit(str), len ++);\r\n    return len;\r\n}\r\n\r\nclass string:\r\n    public _string<gchar>\r\n{\r\npublic:\r\n    typedef std::basic_string<gchar> stdstr;\r\n    typedef _string<gchar> superref;\r\n    typedef superref::iterator iterator;\r\n    typedef superref::const_iterator const_iterator;\r\n    typedef superref::protoref protoref;\r\n\r\npublic:\r\n    using superref::npos;\r\n    using superref::begin;\r\n    using superref::c_str;\r\n    using superref::capacity;\r\n    using superref::compare;\r\n    using superref::copy;\r\n    using superref::empty;\r\n    using superref::find;\r\n    using superref::find_first_not_of;\r\n    using superref::find_first_of;\r\n    using superref::find_last_not_of;\r\n    using superref::find_last_of;\r\n    using superref::max_size;\r\n    using superref::operator+=;\r\n    using superref::operator=;\r\n    using superref::rbegin;\r\n    using superref::reserve;\r\n    using superref::rfind;\r\n    using superref::substr;\r\n    using superref::test;\r\n    using superref::_test;\r\n    using superref::to_lower;\r\n    using superref::to_upper;\r\n    using superref::to_int;\r\n    using superref::to_int64;\r\n    using superref::to_real;\r\n    using superref::compare_cl;\r\n    using superref::greater;\r\n    using superref::less;\r\n    using superref::equal;\r\n    using superref::operator<;\r\n    using superref::operator>;\r\n    using superref::operator!=;\r\n    using superref::operator==;\r\n    using superref::front;\r\n    using superref::back;\r\n    using superref::assign;\r\n    using superref::append;\r\n    using superref::clear;\r\n    using superref::erase;\r\n    using superref::insert;\r\n    using superref::push_back;\r\n    using superref::replace;\r\n    using superref::resize;\r\n    using superref::swap;\r\n    using superref::at;\r\n    using superref::operator[];\r\n    using superref::format;\r\n    using superref::from_int;\r\n    using superref::from_int64;\r\n    using superref::from_real;\r\n    using superref::length;\r\n    using superref::pop_back;\r\n\r\npublic:\r\n    string() {}\r\n    string(const gchar* str): superref(str) {}\r\n    string(const gchar* str, int len): superref(str, len) {}\r\n    string(gchar ch, int cnt): superref(ch, cnt) {}\r\n    string(protoref& rhs) { assign(rhs.c_str(), (int)rhs.size()); }\r\n    int size() const { return (int)superref::size(); } \r\n    bool operator<(const string& str) const { return less(str.c_str(), str.length()); }\r\n    bool operator>(const string& str) const { return greater(str.c_str(), str.length()); }\r\n    bool operator==(const string& str) const { return equal(str.c_str(), str.length()); }\r\n    bool operator!=(const string& str) const { return !equal(str.c_str(), str.length()); }\r\n};\r\n\r\ninline bool is_mbcs_half(const char* str)\r\n{\r\n    if(!str || !(str[0] & 0x80))\r\n        return false;\r\n    int i = 1;\r\n    for( ; str[i] && (str[i] & 0x80); i ++);\r\n    return i % 2 != 0;\r\n}\r\n\r\ninline const gchar* get_next_char(const gchar* str, uint& c)\r\n{\r\n#ifdef _UNICODE\r\n    if(!str || !str[0]) { c = 0; return 0; }\r\n    c = (uint)str[0];\r\n    return ++ str;\r\n#else\r\n    return get_mbcs_elem(str, c);\r\n#endif\r\n}\r\n\r\ninline const gchar* get_next_char(const gchar* str, uint& c, const gchar* end)\r\n{\r\n#ifdef _UNICODE\r\n    if(!str || str == end) { c = 0; return 0; }\r\n    c = (uint)str[0];\r\n    return ++ str;\r\n#else\r\n    return get_mbcs_elem(str, c, end);\r\n#endif\r\n}\r\n\r\n__gslib_end__\r\n\r\n#endif\r\n\r\n", "meta": {"hexsha": "a01c74c8802f296ec612857acf2f305d90968dde", "size": 28406, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gslib/string.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/gslib/string.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gslib/string.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 38.4384303112, "max_line_length": 158, "alphanum_fraction": 0.6184608885, "num_tokens": 8104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09534947261117098, "lm_q2_score": 0.04742586863357034, "lm_q1q2_score": 0.004522031562337608}}
{"text": "#pragma once\n\n#include \"Library.h\"\n#include \"Tile.h\"\n#include \"TileContentLoadResult.h\"\n#include \"TileContentLoader.h\"\n#include \"TileRefine.h\"\n\n#include <gsl/span>\n#include <spdlog/fwd.h>\n\n#include <cstddef>\n#include <memory>\n#include <vector>\n\nnamespace Cesium3DTilesSelection {\n\nclass Tileset;\n\n/**\n * @brief Creates a {@link TileContentLoadResult} from 3D Tiles external\n * `tileset.json` data.\n */\nclass CESIUM3DTILESSELECTION_API ExternalTilesetContent final\n    : public TileContentLoader {\npublic:\n  /**\n   * @copydoc TileContentLoader::load\n   *\n   * The result will only contain the `childTiles` and the `pNewTileContext`.\n   * Other fields will be empty or have default values.\n   */\n  CesiumAsync::Future<std::unique_ptr<TileContentLoadResult>>\n  load(const TileContentLoadInput& input) override;\n\nprivate:\n  /**\n   * @brief Create the {@link TileContentLoadResult} from the given input data.\n   *\n   * @param pLogger The logger that receives details of loading errors and\n   * warnings.\n   * @param tileRefine The {@link TileRefine}\n   * @param url The source URL\n   * @param data The raw input data\n   * @return The {@link TileContentLoadResult}\n   */\n  static std::unique_ptr<TileContentLoadResult> load(\n      const std::shared_ptr<spdlog::logger>& pLogger,\n      const glm::dmat4& tileTransform,\n      TileRefine tileRefine,\n      const std::string& url,\n      const gsl::span<const std::byte>& data);\n};\n\n} // namespace Cesium3DTilesSelection\n", "meta": {"hexsha": "5325ea3f42d0bd96a74fbabb0ebe0225fb3e77f5", "size": 1460, "ext": "h", "lang": "C", "max_stars_repo_path": "Cesium3DTilesSelection/include/Cesium3DTilesSelection/ExternalTilesetContent.h", "max_stars_repo_name": "yieryi/cesium-native", "max_stars_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 154.0, "max_stars_repo_stars_event_min_datetime": "2021-03-30T14:08:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T00:01:43.000Z", "max_issues_repo_path": "Cesium3DTilesSelection/include/Cesium3DTilesSelection/ExternalTilesetContent.h", "max_issues_repo_name": "yieryi/cesium-native", "max_issues_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 256.0, "max_issues_repo_issues_event_min_datetime": "2021-03-30T18:12:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:44:21.000Z", "max_forks_repo_path": "Cesium3DTilesSelection/include/Cesium3DTilesSelection/ExternalTilesetContent.h", "max_forks_repo_name": "yieryi/cesium-native", "max_forks_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 66.0, "max_forks_repo_forks_event_min_datetime": "2021-03-30T15:14:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T13:38:41.000Z", "avg_line_length": 26.0714285714, "max_line_length": 79, "alphanum_fraction": 0.7178082192, "num_tokens": 375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1540575782272973, "lm_q2_score": 0.0293122339312297, "lm_q1q2_score": 0.0045157717718772574}}
{"text": "#pragma once\n\n#include <gsl\\gsl>\n#include <winrt\\Windows.Foundation.h>\n#include <d3d11.h>\n#include <map>\n#include \"DrawableGameComponent.h\"\n#include \"FullScreenRenderTarget.h\"\n#include \"GaussianBlur.h\"\n\nnamespace Rendering\n{\n\tclass DiffuseLightingDemo;\n\n\tclass GaussianBlurDemo final : public Library::DrawableGameComponent\n\t{\n\tpublic:\n\t\tGaussianBlurDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera);\n\t\tGaussianBlurDemo(const GaussianBlurDemo&) = delete;\n\t\tGaussianBlurDemo(GaussianBlurDemo&&) = default;\n\t\tGaussianBlurDemo& operator=(const GaussianBlurDemo&) = default;\t\t\n\t\tGaussianBlurDemo& operator=(GaussianBlurDemo&&) = default;\n\t\t~GaussianBlurDemo();\n\n\t\tstd::shared_ptr<DiffuseLightingDemo> DiffuseLighting() const;\n\n\t\tfloat BlurAmount() const;\n\t\tvoid SetBlurAmount(float blurAmount);\n\t\t\n\t\tvirtual void Initialize() override;\n\t\tvirtual void Update(const Library::GameTime& gameTime) override;\n\t\tvirtual void Draw(const Library::GameTime& gameTime) override;\n\n\tprivate:\n\t\tstd::shared_ptr<DiffuseLightingDemo> mDiffuseLightingDemo;\t\t\n\t\tLibrary::FullScreenRenderTarget mRenderTarget;\n\t\tLibrary::GaussianBlur mGaussianBlur;\n\t};\n}", "meta": {"hexsha": "2507ae58ef3b6afa001bc1eae7126a07cc8bf860", "size": 1155, "ext": "h", "lang": "C", "max_stars_repo_path": "source/7.2_Gaussian_Blurring/GaussianBlurDemo.h", "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/7.2_Gaussian_Blurring/GaussianBlurDemo.h", "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/7.2_Gaussian_Blurring/GaussianBlurDemo.h", "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6153846154, "max_line_length": 88, "alphanum_fraction": 0.7774891775, "num_tokens": 290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.2751297238231752, "lm_q2_score": 0.016403029781443416, "lm_q1q2_score": 0.004512961053631845}}
{"text": "/* vector/vector.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#include <config.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_vector.h>\n\n/* turn off range checking at runtime if zero */\nint gsl_check_range = 1;\n\n#define BASE_GSL_COMPLEX_LONG\n#include \"templates_on.h\"\n#include \"vector_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_GSL_COMPLEX_LONG\n\n#define BASE_GSL_COMPLEX\n#include \"templates_on.h\"\n#include \"vector_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_GSL_COMPLEX\n\n#define BASE_GSL_COMPLEX_FLOAT\n#include \"templates_on.h\"\n#include \"vector_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_GSL_COMPLEX_FLOAT\n\n#define BASE_LONG_DOUBLE\n#include \"templates_on.h\"\n#include \"vector_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_LONG_DOUBLE\n\n#define BASE_DOUBLE\n#include \"templates_on.h\"\n#include \"vector_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_DOUBLE\n\n#define BASE_FLOAT\n#include \"templates_on.h\"\n#include \"vector_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_FLOAT\n\n#define BASE_ULONG\n#include \"templates_on.h\"\n#include \"vector_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_ULONG\n\n#define BASE_LONG\n#include \"templates_on.h\"\n#include \"vector_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_LONG\n\n#define BASE_UINT\n#include \"templates_on.h\"\n#include \"vector_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_UINT\n\n#define BASE_INT\n#include \"templates_on.h\"\n#include \"vector_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_INT\n\n#define BASE_USHORT\n#include \"templates_on.h\"\n#include \"vector_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_USHORT\n\n#define BASE_SHORT\n#include \"templates_on.h\"\n#include \"vector_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_SHORT\n\n#define BASE_UCHAR\n#include \"templates_on.h\"\n#include \"vector_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_UCHAR\n\n#define BASE_CHAR\n#include \"templates_on.h\"\n#include \"vector_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_CHAR\n", "meta": {"hexsha": "05ffab26b4c4033f3e719165d874f4911503143e", "size": 2685, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/vector/vector.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/vector/vector.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/vector/vector.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 24.4090909091, "max_line_length": 73, "alphanum_fraction": 0.7698324022, "num_tokens": 643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.320821300824607, "lm_q2_score": 0.014063627249862614, "lm_q1q2_score": 0.004511911188613315}}
{"text": "#ifndef __GSL_MATRIX_H__\n#define __GSL_MATRIX_H__\n\n#include <gsl/gsl_matrix_complex_long_double.h>\n#include <gsl/gsl_matrix_complex_double.h>\n#include <gsl/gsl_matrix_complex_float.h>\n\n#include <gsl/gsl_matrix_long_double.h>\n#include <gsl/gsl_matrix_double.h>\n#include <gsl/gsl_matrix_float.h>\n\n#include <gsl/gsl_matrix_ulong.h>\n#include <gsl/gsl_matrix_long.h>\n\n#include <gsl/gsl_matrix_uint.h>\n#include <gsl/gsl_matrix_int.h>\n\n#include <gsl/gsl_matrix_ushort.h>\n#include <gsl/gsl_matrix_short.h>\n\n#include <gsl/gsl_matrix_uchar.h>\n#include <gsl/gsl_matrix_char.h>\n\n\n#endif /* __GSL_MATRIX_H__ */\n", "meta": {"hexsha": "43c41169e56b0c5ec40d823981d9cc3df8ae606b", "size": 598, "ext": "h", "lang": "C", "max_stars_repo_path": "gsl-2.6/gsl/gsl_matrix.h", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gsl-2.6/gsl/gsl_matrix.h", "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gsl-2.6/gsl/gsl_matrix.h", "max_forks_repo_name": "ielomariala/Hex-Game", "max_forks_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-30T20:40:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-30T20:40:25.000Z", "avg_line_length": 23.0, "max_line_length": 47, "alphanum_fraction": 0.7976588629, "num_tokens": 170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23934934732271165, "lm_q2_score": 0.01883313147369875, "lm_q1q2_score": 0.004507697726272615}}
{"text": "#pragma once\n#include <gsl/span.h>\n#include <msgpack.hpp>\n#include <type_traits>\n#include <typeindex>\n#include <unordered_map>\n#include <cstddef> // somehow needed for size_t?\n\nnamespace meta {\nusing packer = msgpack::packer<std::ostream>;\nusing unpacker = msgpack::unpacker;\n\nstruct Attribute {\n  std::type_index typeindex;\n  const void *data;\n};\n\nstruct Field {\n  const char *name;\n  const char *qualName;\n  std::type_index typeindex;\n  std::size_t offset;\n  void *(*getPtr)(void *object);\n  gsl::span<const Attribute> attributes;\n\n  template <typename T> T *getAs(void *object) const {\n    return reinterpret_cast<T *>(getPtr(object));\n  }\n\n  template <typename T> const T *getAttribute() const {\n\t  for (auto&& a : attributes) {\n\t\t  if (a.typeindex == std::type_index{ typeid(T) }) {\n\t\t\t  return static_cast<const T*>(a.data);\n\t\t  }\n\t  }\n\t  return nullptr;\n  }\n};\n\nstruct Enumerator {\n  const char *name;\n  uint64_t value;\n  gsl::span<const Attribute> attributes;\n  \n  template <typename T> const T *getAttribute() const {\n\t  for (auto&& a : attributes) {\n\t\t  if (a.typeindex == std::type_index{ typeid(T) }) {\n\t\t\t  return static_cast<const T*>(a.data);\n\t\t  }\n\t  }\n\t  return nullptr;\n  }\n};\n\nenum class TypeKind { Enum, Struct, Union };\n\nstruct Enum;\nstruct Record;\n\nstruct Type {\n  const char *name;\n  TypeKind kind;\n  gsl::span<const Attribute> attributes;\n  void (*serialize)(packer &, const void *);\n  void (*deserialize)(unpacker &, void *);\n\n  template <typename T> const T *as() const {\n    if (kind == T::t_kind)\n      return static_cast<const T *>(this);\n    return nullptr;\n  }\n};\n\nstruct Record : public Type {\n  static constexpr TypeKind t_kind = TypeKind::Struct;\n  Record(const char *name, gsl::span<const Field> public_fields_,\n           gsl::span<const std::type_index> bases_,\n           gsl::span<const Attribute> attributes_,\n           void (*serialize_)(packer &, const void *),\n           void (*deserialize_)(unpacker &, void *))\n      : Type{name, t_kind, attributes_, serialize_, deserialize_},\n        publicFields{public_fields_}, bases{bases_} {}\n\n  gsl::span<const Field> publicFields;\n  gsl::span<const std::type_index> bases;\n};\n\nstruct Enum : public Type {\n  static constexpr TypeKind t_kind = TypeKind::Enum;\n  Enum(const char *name, gsl::span<const Enumerator> enumerators_,\n         uint64_t (*getValue_)(const void *e),\n         void (*setValue_)(void *, uint64_t),\n         gsl::span<const Attribute> attributes_,\n         void (*serialize_)(packer &, const void *),\n         void (*deserialize_)(unpacker &, void *))\n      : Type{name, t_kind, attributes_, serialize_, deserialize_},\n        enumerators{enumerators_}, getValue{getValue_},\n        setValue{setValue_} {}\n\n  gsl::span<const Enumerator> enumerators;\n\n  int findEnumeratorIndex(const void *obj) const {\n    auto v = getValue(obj);\n    for (int i = 0; i < enumerators.size(); ++i) {\n      if (enumerators[i].value == v)\n        return i;\n    }\n    return -1;\n  }\n\n  const Enumerator *findEnumerator(const void *obj) const {\n    int i = findEnumeratorIndex(obj);\n    if (i < 0)\n      return nullptr;\n    return &enumerators[i];\n  }\n\n  // manipulation functions\n  uint64_t (*getValue)(const void *obj);\n  void (*setValue)(void *obj, uint64_t value);\n};\n\ntemplate <typename T> const Type *typeOf();\nconst Type *typeOf(std::type_index ti);\n\ntemplate <typename T> void serialize(packer& p, const T& data)\n{\n\tserialize(p, typeOf<T>(), &data);\n}\n\ntemplate <typename T> void serialize_dynamic(packer& p, const T& data)\n{\n\t// always use the dynamic type\n\tserialize(p, typeOf(typeid(data)), &data);\n}\n\ninline void serialize(packer& p, const Type* ty, const void* data)\n{\n\tif (!ty) return;\n\tty->serialize(p, data);\n}\n\n// enum value-to-string and string-to-value\ntemplate <typename T, typename = std::enable_if_t<std::is_enum<T>::value>>\nconst char *getEnumeratorName(T constant);\ntemplate <typename T, typename = std::enable_if_t<std::is_enum<T>::value>>\nT getEnumeratorValue(const char *name);\n}\n", "meta": {"hexsha": "3f24416f84cf6b717ea0c456a31bd8f8524ab916", "size": 3992, "ext": "h", "lang": "C", "max_stars_repo_path": "src/Editor/Meta.h", "max_stars_repo_name": "ennis/autograph-pipelines", "max_stars_repo_head_hexsha": "afc66ef60bf99fca26d200bd7739528e1bf3ed8c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-24T12:29:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-24T12:29:42.000Z", "max_issues_repo_path": "src/Editor/Meta.h", "max_issues_repo_name": "ennis/autograph-pipelines", "max_issues_repo_head_hexsha": "afc66ef60bf99fca26d200bd7739528e1bf3ed8c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Editor/Meta.h", "max_forks_repo_name": "ennis/autograph-pipelines", "max_forks_repo_head_hexsha": "afc66ef60bf99fca26d200bd7739528e1bf3ed8c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7919463087, "max_line_length": 74, "alphanum_fraction": 0.6628256513, "num_tokens": 1016, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14414886038616348, "lm_q2_score": 0.03114382783702237, "lm_q1q2_score": 0.004489347290769649}}
{"text": "/* vector/gsl_vector_complex_float.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_VECTOR_COMPLEX_FLOAT_H__\n#define __GSL_VECTOR_COMPLEX_FLOAT_H__\n\n#if !defined( GSL_FUN )\n#  if !defined( GSL_DLL )\n#    define GSL_FUN extern\n#  elif defined( BUILD_GSL_DLL )\n#    define GSL_FUN extern __declspec(dllexport)\n#  else\n#    define GSL_FUN extern __declspec(dllimport)\n#  endif\n#endif\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_complex.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_vector_float.h>\n#include <gsl/gsl_vector_complex.h>\n#include <gsl/gsl_block_complex_float.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size;\n  size_t stride;\n  float *data;\n  gsl_block_complex_float *block;\n  int owner;\n} gsl_vector_complex_float;\n\ntypedef struct\n{\n  gsl_vector_complex_float vector;\n} _gsl_vector_complex_float_view;\n\ntypedef _gsl_vector_complex_float_view gsl_vector_complex_float_view;\n\ntypedef struct\n{\n  gsl_vector_complex_float vector;\n} _gsl_vector_complex_float_const_view;\n\ntypedef const _gsl_vector_complex_float_const_view gsl_vector_complex_float_const_view;\n\n/* Allocation */\n\nGSL_FUN gsl_vector_complex_float *gsl_vector_complex_float_alloc (const size_t n);\nGSL_FUN gsl_vector_complex_float *gsl_vector_complex_float_calloc (const size_t n);\n\nGSL_FUN gsl_vector_complex_float *\ngsl_vector_complex_float_alloc_from_block (gsl_block_complex_float * b, \n                                           const size_t offset, \n                                           const size_t n, \n                                           const size_t stride);\n\nGSL_FUN gsl_vector_complex_float *\ngsl_vector_complex_float_alloc_from_vector (gsl_vector_complex_float * v, \n                                             const size_t offset, \n                                             const size_t n, \n                                             const size_t stride);\n\nGSL_FUN void gsl_vector_complex_float_free (gsl_vector_complex_float * v);\n\n/* Views */\n\nGSL_FUN _gsl_vector_complex_float_view\ngsl_vector_complex_float_view_array (float *base,\n                                     size_t n);\n\nGSL_FUN _gsl_vector_complex_float_view\ngsl_vector_complex_float_view_array_with_stride (float *base,\n                                                 size_t stride,\n                                                 size_t n);\n\nGSL_FUN _gsl_vector_complex_float_const_view\ngsl_vector_complex_float_const_view_array (const float *base,\n                                           size_t n);\n\nGSL_FUN _gsl_vector_complex_float_const_view\ngsl_vector_complex_float_const_view_array_with_stride (const float *base,\n                                                       size_t stride,\n                                                       size_t n);\n\nGSL_FUN _gsl_vector_complex_float_view\ngsl_vector_complex_float_subvector (gsl_vector_complex_float *base,\n                                         size_t i, \n                                         size_t n);\n\n\nGSL_FUN _gsl_vector_complex_float_view \ngsl_vector_complex_float_subvector_with_stride (gsl_vector_complex_float *v, \n                                                size_t i, \n                                                size_t stride, \n                                                size_t n);\n\nGSL_FUN _gsl_vector_complex_float_const_view\ngsl_vector_complex_float_const_subvector (const gsl_vector_complex_float *base,\n                                               size_t i, \n                                               size_t n);\n\n\nGSL_FUN _gsl_vector_complex_float_const_view \ngsl_vector_complex_float_const_subvector_with_stride (const gsl_vector_complex_float *v, \n                                                      size_t i, \n                                                      size_t stride, \n                                                      size_t n);\n\nGSL_FUN _gsl_vector_float_view\ngsl_vector_complex_float_real (gsl_vector_complex_float *v);\n\nGSL_FUN _gsl_vector_float_view \ngsl_vector_complex_float_imag (gsl_vector_complex_float *v);\n\nGSL_FUN _gsl_vector_float_const_view\ngsl_vector_complex_float_const_real (const gsl_vector_complex_float *v);\n\nGSL_FUN _gsl_vector_float_const_view \ngsl_vector_complex_float_const_imag (const gsl_vector_complex_float *v);\n\n\n/* Operations */\n\nGSL_FUN void gsl_vector_complex_float_set_zero (gsl_vector_complex_float * v);\nGSL_FUN void gsl_vector_complex_float_set_all (gsl_vector_complex_float * v,\n                                       gsl_complex_float z);\nGSL_FUN int gsl_vector_complex_float_set_basis (gsl_vector_complex_float * v, size_t i);\n\nGSL_FUN int gsl_vector_complex_float_fread (FILE * stream,\n                                    gsl_vector_complex_float * v);\nGSL_FUN int gsl_vector_complex_float_fwrite (FILE * stream,\n                                     const gsl_vector_complex_float * v);\nGSL_FUN int gsl_vector_complex_float_fscanf (FILE * stream,\n                                     gsl_vector_complex_float * v);\nGSL_FUN int gsl_vector_complex_float_fprintf (FILE * stream,\n                                      const gsl_vector_complex_float * v,\n                                      const char *format);\n\nGSL_FUN int gsl_vector_complex_float_memcpy (gsl_vector_complex_float * dest, const gsl_vector_complex_float * src);\n\nGSL_FUN int gsl_vector_complex_float_reverse (gsl_vector_complex_float * v);\n\nGSL_FUN int gsl_vector_complex_float_swap (gsl_vector_complex_float * v, gsl_vector_complex_float * w);\nGSL_FUN int gsl_vector_complex_float_swap_elements (gsl_vector_complex_float * v, const size_t i, const size_t j);\n\nGSL_FUN int gsl_vector_complex_float_equal (const gsl_vector_complex_float * u, \n                                    const gsl_vector_complex_float * v);\n\nGSL_FUN int gsl_vector_complex_float_isnull (const gsl_vector_complex_float * v);\nGSL_FUN int gsl_vector_complex_float_ispos (const gsl_vector_complex_float * v);\nGSL_FUN int gsl_vector_complex_float_isneg (const gsl_vector_complex_float * v);\nGSL_FUN int gsl_vector_complex_float_isnonneg (const gsl_vector_complex_float * v);\n\nGSL_FUN int gsl_vector_complex_float_add (gsl_vector_complex_float * a, const gsl_vector_complex_float * b);\nGSL_FUN int gsl_vector_complex_float_sub (gsl_vector_complex_float * a, const gsl_vector_complex_float * b);\nGSL_FUN int gsl_vector_complex_float_mul (gsl_vector_complex_float * a, const gsl_vector_complex_float * b);\nGSL_FUN int gsl_vector_complex_float_div (gsl_vector_complex_float * a, const gsl_vector_complex_float * b);\nGSL_FUN int gsl_vector_complex_float_scale (gsl_vector_complex_float * a, const gsl_complex_float x);\nGSL_FUN int gsl_vector_complex_float_add_constant (gsl_vector_complex_float * a, const gsl_complex_float x);\nGSL_FUN int gsl_vector_complex_float_axpby (const gsl_complex_float alpha, const gsl_vector_complex_float * x, const gsl_complex_float beta, gsl_vector_complex_float * y);\n\nGSL_FUN INLINE_DECL gsl_complex_float gsl_vector_complex_float_get (const gsl_vector_complex_float * v, const size_t i);\nGSL_FUN INLINE_DECL void gsl_vector_complex_float_set (gsl_vector_complex_float * v, const size_t i, gsl_complex_float z);\nGSL_FUN INLINE_DECL gsl_complex_float *gsl_vector_complex_float_ptr (gsl_vector_complex_float * v, const size_t i);\nGSL_FUN INLINE_DECL const gsl_complex_float *gsl_vector_complex_float_const_ptr (const gsl_vector_complex_float * v, const size_t i);\n\n#ifdef HAVE_INLINE\n\nINLINE_FUN\ngsl_complex_float\ngsl_vector_complex_float_get (const gsl_vector_complex_float * v,\n                              const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= v->size))\n    {\n      gsl_complex_float zero = {{0, 0}};\n      GSL_ERROR_VAL (\"index out of range\", GSL_EINVAL, zero);\n    }\n#endif\n  return *GSL_COMPLEX_FLOAT_AT (v, i);\n}\n\nINLINE_FUN\nvoid\ngsl_vector_complex_float_set (gsl_vector_complex_float * v,\n                              const size_t i, gsl_complex_float z)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= v->size))\n    {\n      GSL_ERROR_VOID (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  *GSL_COMPLEX_FLOAT_AT (v, i) = z;\n}\n\nINLINE_FUN\ngsl_complex_float *\ngsl_vector_complex_float_ptr (gsl_vector_complex_float * v,\n                              const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= v->size))\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return GSL_COMPLEX_FLOAT_AT (v, i);\n}\n\nINLINE_FUN\nconst gsl_complex_float *\ngsl_vector_complex_float_const_ptr (const gsl_vector_complex_float * v,\n                                    const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= v->size))\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return GSL_COMPLEX_FLOAT_AT (v, i);\n}\n\n\n#endif /* HAVE_INLINE */\n\n__END_DECLS\n\n#endif /* __GSL_VECTOR_COMPLEX_FLOAT_H__ */\n", "meta": {"hexsha": "c48a48c8e52241b27d2f4e61164c1783fda58a72", "size": 9828, "ext": "h", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_vector_complex_float.h", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-28T08:20:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-28T08:20:20.000Z", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_vector_complex_float.h", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_vector_complex_float.h", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-14T12:45:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-14T12:45:35.000Z", "avg_line_length": 37.3688212928, "max_line_length": 171, "alphanum_fraction": 0.6960724461, "num_tokens": 2149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23370636758849894, "lm_q2_score": 0.019124038043671587, "lm_q1q2_score": 0.00446940946481075}}
{"text": "#pragma once\n\n#include <type_traits>\n#include <vector>\n\n#include <gsl-lite/gsl-lite.hpp>\n\nnamespace thrustshift {\n\n/*! \\brief Make multiple spans from a range of objects which contain ranges.\n *\n *  \\param r\n *  \\param get_range This functor must **not** return a copy of any object\n *\n *  ```cpp\n *  struct S {\n *\n *    std::vector<int> v;\n *  };\n *  ...\n *\n *  std::vector<S> ss;\n *  // fill ss\n *\n *  //// WRONG\n *  auto spans_with_invalid_ptrs = make_spans_from_ranges(ss, [](const auto& e) { return e.v; });\n *\n *  //// CORRECT\n *  auto spans = make_spans_from_ranges(ss, [](const auto& e) { return gsl_lite::make_span(e.v); });\n *  ```\n *\n *  The wrong lambda is returning a copy of member vector `v`, which is then deallocated.\n *\n */\ntemplate <class T, class RangeOfRanges, class GetRangeCallback>\nstd::vector<gsl_lite::span<T>> make_spans_from_ranges(\n    RangeOfRanges&& r,\n    GetRangeCallback&& get_range) {\n\tstd::vector<gsl_lite::span<T>> spans(r.size());\n\tfor (size_t i = 0; i < spans.size(); ++i) {\n\t\tspans[i] =\n\t\t    gsl_lite::make_span(get_range(r[i]).data(), get_range(r[i]).size());\n\t}\n\treturn spans;\n}\n\ntemplate <class T, class RangeOfRanges>\nstd::vector<gsl_lite::span<T>> make_spans_from_ranges(RangeOfRanges&& r) {\n\tauto get_range = [](auto& c) { return gsl_lite::make_span(c); };\n\treturn make_spans_from_ranges<T>(std::forward<RangeOfRanges>(r), get_range);\n}\n\ntemplate <class T, class RangeOfPtrs>\nstd::vector<gsl_lite::span<T>> make_spans_from_ptrs(RangeOfPtrs&& r, size_t N) {\n\n\tstd::vector<gsl_lite::span<T>> spans(r.size());\n\tfor (size_t i = 0; i < spans.size(); ++i) {\n\t\tspans[i] = gsl_lite::make_span(r[i].get(), N);\n\t}\n\treturn spans;\n}\n\ntemplate <typename T>\ngsl_lite::span<T> subtract(gsl_lite::span<T>& pool, size_t size_of_new_span) {\n\tgsl_Expects(pool.size() >= size_of_new_span);\n\tauto piece = pool.first(size_of_new_span);\n\tpool = pool.subspan(size_of_new_span);\n\treturn piece;\n}\n\n} // namespace thrustshift\n", "meta": {"hexsha": "5575027af1769917a14da2a250db544e7aa37830", "size": 1946, "ext": "h", "lang": "C", "max_stars_repo_path": "include/thrustshift/span-utility.h", "max_stars_repo_name": "pauleonix/thrustshift", "max_stars_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-16T13:01:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T13:01:46.000Z", "max_issues_repo_path": "include/thrustshift/span-utility.h", "max_issues_repo_name": "pauleonix/thrustshift", "max_issues_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-23T14:12:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-17T11:40:04.000Z", "max_forks_repo_path": "include/thrustshift/span-utility.h", "max_forks_repo_name": "pauleonix/thrustshift", "max_forks_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0277777778, "max_line_length": 100, "alphanum_fraction": 0.6690647482, "num_tokens": 559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.13296422989056966, "lm_q2_score": 0.033589505650103976, "lm_q1q2_score": 0.004466202751171014}}
{"text": "///\n/// @file This file contains OpenMP and BLAS thread count configuration\n/// interface.\n///\n/// @author Mirko Myllykoski (mirkom@cs.umu.se), Ume\u00e5 University\n///\n/// @internal LICENSE\n///\n/// Copyright (c) 2019-2020, Ume\u00e5 Universitet\n///\n/// Redistribution and use in source and binary forms, with or without\n/// modification, are permitted provided that the following conditions are met:\n///\n/// 1. Redistributions of source code must retain the above copyright notice,\n///    this list of conditions and the following disclaimer.\n///\n/// 2. Redistributions in binary form must reproduce the above copyright notice,\n///    this list of conditions and the following disclaimer in the documentation\n///    and/or other materials provided with the distribution.\n///\n/// 3. Neither the name of the copyright holder nor the names of its\n///    contributors may be used to endorse or promote products derived from this\n///    software without specific prior written permission.\n///\n/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n/// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n/// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n/// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n/// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n/// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n/// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n/// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n/// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n/// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n/// POSSIBILITY OF SUCH DAMAGE.\n///\n\n#include <starneig_test_config.h>\n#include <starneig/configuration.h>\n#include \"threads.h\"\n#include \"parse.h\"\n#include \"omp.h\"\n#include <hwloc.h>\n#ifdef MKL_SET_NUM_THREADS_LOCAL_FOUND\n#include <mkl.h>\n#endif\n#if defined(OPENBLAS_SET_NUM_THREADS_FOUND) || \\\ndefined(GOTO_SET_NUM_THREADS_FOUND)\n#include <cblas.h>\n#endif\n\nstatic struct {\n    int worker_threads;\n    int blas_threads;\n    int lapack_threads;\n    int scalapack_threads;\n} status = {\n    .worker_threads = 1,\n    .blas_threads = 1,\n    .lapack_threads = 1,\n    .scalapack_threads = 1\n};\n\nstatic int get_core_count()\n{\n    hwloc_topology_t topology;\n    hwloc_topology_init(&topology);\n    hwloc_topology_load(topology);\n\n    hwloc_cpuset_t res = hwloc_bitmap_alloc();\n\n    hwloc_cpuset_t mask = hwloc_bitmap_alloc();\n    hwloc_get_cpubind(topology, mask, HWLOC_CPUBIND_THREAD);\n\n    int depth_cores = hwloc_get_type_depth(topology, HWLOC_OBJ_CORE);\n    int num_cores = hwloc_get_nbobjs_by_depth(topology, depth_cores);\n\n    int num_hwloc_cpus = 0;\n\n    // iterate over all COREs\n    for (int i = 0; i < num_cores; i++) {\n        hwloc_obj_t core = hwloc_get_obj_by_depth(topology, depth_cores, i);\n\n        // if the CORE has PUs inside it, ...\n        if (core->first_child && core->first_child->type == HWLOC_OBJ_PU) {\n            // iterate over them\n            hwloc_obj_t pu = core->first_child;\n            while (pu) {\n                // if the PU is in the binding mask, ...\n                hwloc_bitmap_and(res, mask, pu->cpuset);\n                if (!hwloc_bitmap_iszero(res)) {\n                    // count the PU as a CORE\n                    num_hwloc_cpus++;\n                    break;\n                }\n                pu = pu->next_sibling;\n            }\n        }\n        else {\n            // if the CORE is in the binding mask, ...\n            hwloc_bitmap_and(res, mask, core->cpuset);\n            if (!hwloc_bitmap_iszero(res)) {\n                // count the CORE\n                num_hwloc_cpus++;\n            }\n        }\n    }\n\n    hwloc_bitmap_free(mask);\n    hwloc_bitmap_free(res);\n    hwloc_topology_destroy(topology);\n\n    return num_hwloc_cpus;\n}\n\nstatic void set_blas_threads(int threads)\n{\n#if defined(MKL_SET_NUM_THREADS_LOCAL_FOUND)\n    mkl_set_num_threads_local(threads);\n#elif defined(OPENBLAS_SET_NUM_THREADS_FOUND)\n    openblas_set_num_threads(threads);\n#elif defined(GOTO_SET_NUM_THREADS_FOUND)\n    goto_set_num_threads(threads);\n#endif\n}\n\nvoid thread_print_usage(int argc, char * const *argv)\n{\n    printf(\n        \"  --test-workers [(num),default] -- Test program StarPU worker count\\n\"\n        \"  --blas-threads [(num),default] -- Test program BLAS thread count\\n\"\n        \"  --lapack-threads [(num),default] -- LAPACK solver thread count\\n\"\n        \"  --scalapack-threads [(num),default] -- ScaLAPACK solver thread \"\n        \"count\\n\"\n    );\n}\n\nvoid thread_print_args(int argc, char * const *argv)\n{\n    print_multiarg(\"--test-workers\", argc, argv, \"default\", NULL);\n    print_multiarg(\"--blas-threads\", argc, argv, \"default\", NULL);\n    print_multiarg(\"--lapack-threads\", argc, argv, \"default\", NULL);\n    print_multiarg(\"--scalapack-threads\", argc, argv, \"default\", NULL);\n}\n\nint thread_check_args(int argc, char * const *argv, int *argr)\n{\n    struct multiarg_t worker_threads =\n        read_multiarg(\"--test-workers\", argc, argv, argr, \"default\", NULL);\n\n    if (worker_threads.type == MULTIARG_INVALID ||\n    (worker_threads.type == MULTIARG_INT && worker_threads.int_value < 1)) {\n        fprintf(stderr, \"Invalid number of StarPU worker threads.\\n\");\n        return 1;\n    }\n\n    struct multiarg_t blas_threads =\n        read_multiarg(\"--blas-threads\", argc, argv, argr, \"default\", NULL);\n\n    if (blas_threads.type == MULTIARG_INVALID ||\n    (blas_threads.type == MULTIARG_INT && blas_threads.int_value < 1)) {\n        fprintf(stderr, \"Invalid number of BLAS threads.\\n\");\n        return 1;\n    }\n\n    struct multiarg_t lapack_threads =\n        read_multiarg(\"--lapack-threads\", argc, argv, argr, \"default\", NULL);\n\n    if (lapack_threads.type == MULTIARG_INVALID ||\n    (lapack_threads.type == MULTIARG_INT && lapack_threads.int_value < 1)) {\n        fprintf(stderr, \"Invalid number of LAPACK threads.\\n\");\n        return 1;\n    }\n\n    struct multiarg_t scalapack_threads =\n        read_multiarg(\"--scalapack-threads\", argc, argv, argr, \"default\", NULL);\n\n    if (scalapack_threads.type == MULTIARG_INVALID ||\n    (scalapack_threads.type == MULTIARG_INT &&\n    scalapack_threads.int_value < 1)) {\n        fprintf(stderr, \"Invalid number of ScaLAPACK threads.\\n\");\n        return 1;\n    }\n\n    return 0;\n}\n\nvoid threads_init(int argc, char * const *argv)\n{\n    struct multiarg_t worker_threads =\n        read_multiarg(\"--test-workers\", argc, argv, NULL, \"default\", NULL);\n    if (worker_threads.type == MULTIARG_INT)\n        status.worker_threads = worker_threads.int_value;\n    else\n        status.worker_threads = get_core_count();\n    printf(\n        \"THREADS: Using %d StarPU worker threads during initialization and \"\n        \"validation.\\n\", status.worker_threads);\n\n    struct multiarg_t blas_threads =\n        read_multiarg(\"--blas-threads\", argc, argv, NULL, \"default\", NULL);\n    if (blas_threads.type == MULTIARG_INT)\n        status.blas_threads = blas_threads.int_value;\n    else\n        status.blas_threads = get_core_count();\n    printf(\n        \"THREADS: Using %d BLAS threads during initialization and \"\n        \"validation.\\n\", status.blas_threads);\n\n    struct multiarg_t lapack_threads =\n        read_multiarg(\"--lapack-threads\", argc, argv, NULL, \"default\", NULL);\n    if (lapack_threads.type == MULTIARG_INT)\n        status.lapack_threads = lapack_threads.int_value;\n    else\n        status.lapack_threads = get_core_count();\n    printf(\n        \"THREADS: Using %d BLAS threads in LAPACK solvers.\\n\",\n        status.lapack_threads);\n\n    struct multiarg_t scalapack_threads =\n        read_multiarg(\"--scalapack-threads\", argc, argv, NULL, \"default\", NULL);\n    if (scalapack_threads.type == MULTIARG_INT)\n        status.scalapack_threads = scalapack_threads.int_value;\n    else\n        status.scalapack_threads = 1;\n    printf(\n        \"THREADS: Using %d BLAS threads in ScaLAPACK solvers.\\n\",\n        status.scalapack_threads);\n\n    threads_set_mode(THREADS_MODE_DEFAULT);\n}\n\nvoid threads_set_mode(thread_mode_t mode)\n{\n    switch (mode) {\n        case THREADS_MODE_BLAS:\n            set_blas_threads(status.blas_threads);\n            break;\n        case THREADS_MODE_LAPACK:\n            set_blas_threads(status.lapack_threads);\n            break;\n        case THREADS_MODE_SCALAPACK:\n            set_blas_threads(status.scalapack_threads);\n            break;\n        default:\n            set_blas_threads(1);\n    }\n}\n\nint threads_get_workers()\n{\n    return status.worker_threads;\n}\n\nstarneig_flag_t threads_get_fast_dm()\n{\n    if (1 < threads_get_workers())\n        return STARNEIG_FAST_DM;\n    return STARNEIG_HINT_DM;\n}\n", "meta": {"hexsha": "5a9b58a8cf2290256d739cd2319a60e2246409b3", "size": 8742, "ext": "c", "lang": "C", "max_stars_repo_path": "test/common/threads.c", "max_stars_repo_name": "NLAFET/StarNEig", "max_stars_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2019-04-28T17:13:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-24T12:30:19.000Z", "max_issues_repo_path": "test/common/threads.c", "max_issues_repo_name": "NLAFET/StarNEig", "max_issues_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/common/threads.c", "max_forks_repo_name": "NLAFET/StarNEig", "max_forks_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-04-30T12:14:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-14T09:41:23.000Z", "avg_line_length": 33.4942528736, "max_line_length": 80, "alphanum_fraction": 0.6687256921, "num_tokens": 2092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.13660837948097748, "lm_q2_score": 0.0325897412425357, "lm_q1q2_score": 0.004452031738847179}}
{"text": "#pragma once\n\n#include <gsl/span>\n\nnamespace miner {\n    \n    template<class T, std::ptrdiff_t Extent = gsl::dynamic_extent>\n    using span = gsl::span<T, Extent>;\n\n    template<std::ptrdiff_t Extent = gsl::dynamic_extent>\n    using ByteSpan = span<uint8_t, Extent>;\n\n    template<std::ptrdiff_t Extent = gsl::dynamic_extent>\n    using cByteSpan = span<const uint8_t, Extent>;\n}", "meta": {"hexsha": "bea4b89e75728338eb68c475579ea41bcaf8842a", "size": 378, "ext": "h", "lang": "C", "max_stars_repo_path": "src/common/Span.h", "max_stars_repo_name": "oldas1/Riner", "max_stars_repo_head_hexsha": "492804079eb223e6d4ffd5f5f44283162eaf421b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/common/Span.h", "max_issues_repo_name": "oldas1/Riner", "max_issues_repo_head_hexsha": "492804079eb223e6d4ffd5f5f44283162eaf421b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/common/Span.h", "max_forks_repo_name": "oldas1/Riner", "max_forks_repo_head_hexsha": "492804079eb223e6d4ffd5f5f44283162eaf421b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2, "max_line_length": 66, "alphanum_fraction": 0.6931216931, "num_tokens": 99, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12421299862599396, "lm_q2_score": 0.03567855190309707, "lm_q1q2_score": 0.004431739918516851}}
{"text": "#ifndef CACHED_IMAGE_H\n#define CACHED_IMAGE_H\n\n#ifndef solaris\n#  include <stdint.h>\n#endif\n#include \"asf_meta.h\"\n#include \"float_image.h\"\n#include <stdio.h>\n#include <sys/types.h>\n\n#include <glib.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_histogram.h>\n\n//---------------------------------------------------------------------------\n// Adding a new supported data type:\n//  cache.c:\n//    data_size()\n//    cached_image_get_pixel()\n//    cached_image_get_rgb()\n//  stats.c:\n//    generate_thumbnail_data()\n//  big_image.c:\n//    update_pixel_info()\n//  read_X.c: (for clients that will handle the data type)\n//    open_X_data()\n//     \ntypedef enum {\n    UNDEFINED = 0,\n    GREYSCALE_FLOAT = 1,\n    GREYSCALE_BYTE = 2,\n    RGB_BYTE = 3,\n    RGB_FLOAT = 4\n} ssv_data_type_t;\n\n// Stats structure -- this one is used by both greyscale and RGB\ntypedef struct {\n    double map_min, map_max;\n    double avg, stddev;\n    double act_min, act_max; // absolute min/max of all values\n    int hist[256];           // histogram\n    double no_data_value;    // value indicating \"no data\"\n    int have_no_data;        // TRUE if \"no_data_value\" is present\n    double no_data_min;\n    double no_data_max;\n    int have_no_data_range;\n    int truncate;\n} ImageStats;\n\n// Stats structure -- this one is used only for RGB images, keeps track\n//                    of stats for each channel\ntypedef struct {\n    double map_min, map_max;\n    double avg, stddev;\n    double act_min, act_max; // absolute min/max of all values\n    double no_data_value;\n    int have_no_data;\n    double no_data_max;\n    double no_data_min;\n    int have_no_data_range;\n    int truncate;\n} ImageStatsRGB;\n\n// NOTE: At the moment, the Pixbuf that contains the displayed data\n// is plain RGB, not RGB-A, so adding support for transparency would\n// also involve changing big_image.c/make_big_image(), and you'd have\n// to add a method to the cache interface that returned the alpha\n// channel in addition to the rgb values.\n\n//---------------------------------------------------------------------------\n// This is the client interface -- the set of function pointers, etc,\n// that encapsulate how the image cache gets data from the file.\n// See: -read.c/read_file() for how the cache is hooked up to the\n//          client depending on what the file type is\n//      -read_template.c for an example of how to add another client\ntypedef int ReadClientFn(int row_start, int n_rows_to_get,\n                         void *dest, void *read_client_info,\n                         meta_parameters *meta, int data_type);\ntypedef int ThumbFn(int thumb_size_x, int thumb_size_y, meta_parameters *meta,\n                    void *read_client_info, void *dest, int data_type);\ntypedef void FreeFn(void *read_client_info);\n\ntypedef struct {\n    ReadClientFn *read_fn;\n    ThumbFn *thumb_fn;\n    FreeFn *free_fn;\n    void *read_client_info;\n    ssv_data_type_t data_type;\n    int require_full_load;\n} ClientInterface;\n\n\n//---------------------------------------------------------------------------\n// Here is the ImageCache stuff.  The global ImageCache that holds the\n// loaded image is \"data_ci\".  This is all private data.\ntypedef struct {\n  int nl, ns;               // Image dimensions.\n  ClientInterface *client;  // pointers to data read implementations\n  int n_tiles;              // Number of tiles in memory\n  int reached_max_tiles;    // Have we loaded as many tiles as we can?\n  int rows_per_tile;        // Number of rows in each tile\n  int entire_image_fits;    // TRUE if we can load the entire image\n  int *rowstarts;           // Row numbers starting each tile\n  unsigned char **cache;    // Cached values (floats, unsigned chars ...)\n  int *access_counts;       // Updated when a tile is accessed\n  int n_access;             // used to find oldest tile\n  ssv_data_type_t data_type;// type of data we have\n  meta_parameters *meta;    // metadata -- don't own this pointer\n  ImageStats *stats;        // not owned by us, not populated by us\n  ImageStatsRGB *stats_r;   // not owned by us, not populated by us\n  ImageStatsRGB *stats_g;   // not owned by us, not populated by us\n  ImageStatsRGB *stats_b;   // not owned by us, not populated by us\n} CachedImage;\n\nCachedImage * cached_image_new_from_file(\n    const char *file, meta_parameters *meta, ClientInterface *client,\n    ImageStats *stats, ImageStatsRGB *stats_r, ImageStatsRGB *stats_g,\n    ImageStatsRGB *stats_b);\n\nfloat cached_image_get_pixel (CachedImage *self, int line, int samp);\nvoid cached_image_get_rgb(CachedImage *self, int line, int samp,\n                          unsigned char *r, unsigned char *g,\n                          unsigned char *b);\nvoid cached_image_get_rgb_float(CachedImage *self, int line, int samp,\n                                float *r, float *g, float *b);\n\nvoid load_thumbnail_data(CachedImage *self, int thumb_size_x, int thumb_size_y,\n                         void *dest);\n\nvoid cached_image_free (CachedImage *self);\n\n#endif\n", "meta": {"hexsha": "cd1a34771e073bdcb0b442e29a64a4af4c444936", "size": 4980, "ext": "h", "lang": "C", "max_stars_repo_path": "src/asf_view/cache.h", "max_stars_repo_name": "glshort/MapReady", "max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z", "max_issues_repo_path": "src/asf_view/cache.h", "max_issues_repo_name": "glshort/MapReady", "max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/asf_view/cache.h", "max_forks_repo_name": "glshort/MapReady", "max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z", "avg_line_length": 37.1641791045, "max_line_length": 79, "alphanum_fraction": 0.6491967871, "num_tokens": 1164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3007455789412415, "lm_q2_score": 0.014728613579421542, "lm_q1q2_score": 0.004429565417944962}}
{"text": "/*\n Copyright (C) 2002 M. Marques, A. Castro, A. Rubio, G. Bertsch\n\n This program is free software; you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2, or (at your option)\n any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n 02110-1301, USA.\n\n $Id$\n*/\n\n#include <config.h>\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <locale.h>\n#include <dirent.h>\n#include <sys/time.h>\n#include <gsl/gsl_rng.h>\n\n#include \"string_f.h\"\n\nunsigned long int random_seed()\n{\n unsigned long int seed;\n FILE *devrandom;\n\n if ((devrandom = fopen(\"/dev/urandom\",\"r\")) == NULL) {\n#ifdef HAVE_GETTIMEOFDAY\n   struct timeval tv;\n   gettimeofday(&tv, 0);\n   seed = tv.tv_sec + tv.tv_usec;\n#else\n   seed = 0;\n#endif\n } else {\n   fread(&seed, sizeof(seed), 1, devrandom);\n   fclose(devrandom);\n }\n\n return seed;\n}\n\nvoid FC_FUNC_(oct_printrecipe, OCT_PRINTRECIPE)\n  (STR_F_TYPE _dir, STR_F_TYPE filename STR_ARG2)\n{\n\n#if HAVE_SCANDIR && HAVE_ALPHASORT\n  char *lang, *tmp, dir[512];\n  struct dirent **namelist;\n  int ii, nn;\n  gsl_rng *rng;\n\n  /* get language */\n  lang = getenv(\"LANG\");\n  if(lang == NULL) lang = \"en\";\n\n  /* convert directory from Fortran to C string */\n  TO_C_STR1(_dir, tmp);\n  strcpy(dir, tmp);\n  free(tmp);\n\n  strcat(dir, \"/recipes\");\n\n  /* check out if lang dir exists */\n  nn = scandir(dir, &namelist, 0, alphasort);\n  if (nn < 0){\n    printf(\"Directory does not exist: %s\", dir);\n    return;\n  }\n\n  for(ii=0; ii<nn; ii++)\n    if(strncmp(lang, namelist[ii]->d_name, 2) == 0){\n      strcat(dir, \"/\");\n      strcat(dir, namelist[ii]->d_name);\n      break;\n    }\n\n  if(ii == nn)\n    strcat(dir, \"/en\"); /* default */\n\n  /* clean up */\n  for(ii=0; ii<nn; ii++)\n    free(namelist[ii]);\n  free(namelist);\n\n  /* now we read the recipes */\n  nn = scandir(dir, &namelist, 0, alphasort);\n\t\n  /* initialize random numbers */\n  gsl_rng_env_setup();\n  rng = gsl_rng_alloc(gsl_rng_default);\n  gsl_rng_set(rng, random_seed());\n  ii = gsl_rng_uniform_int(rng, nn - 2);\n  gsl_rng_free(rng);\n\n  strcat(dir, \"/\");\n  strcat(dir, namelist[ii+2]->d_name); /* skip ./ and ../ */\n\n  /* clean up again */\n  for(ii=0; ii<nn; ii++)\n    free(namelist[ii]);\n  free(namelist);\n\n  TO_F_STR2(dir, filename);\n\n#else\n  printf(\"Sorry, recipes cannot be printed unless scandir and alphasort are available with your C compiler.\\n\");\n#endif\n}\n", "meta": {"hexsha": "0a34c02bc2594929f18330b7c87d1324999fda36", "size": 2824, "ext": "c", "lang": "C", "max_stars_repo_path": "src/basic/recipes.c", "max_stars_repo_name": "neelravi/octopus", "max_stars_repo_head_hexsha": "25cb84cf590276af9ce4617039ba3849e328594c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/basic/recipes.c", "max_issues_repo_name": "neelravi/octopus", "max_issues_repo_head_hexsha": "25cb84cf590276af9ce4617039ba3849e328594c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/basic/recipes.c", "max_forks_repo_name": "neelravi/octopus", "max_forks_repo_head_hexsha": "25cb84cf590276af9ce4617039ba3849e328594c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1475409836, "max_line_length": 112, "alphanum_fraction": 0.664305949, "num_tokens": 791, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25386099567919973, "lm_q2_score": 0.017442487130390594, "lm_q1q2_score": 0.004427967150042583}}
{"text": "/* vector/gsl_vector_uchar.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_VECTOR_UCHAR_H__\n#define __GSL_VECTOR_UCHAR_H__\n\n#if !defined( GSL_FUN )\n#  if !defined( GSL_DLL )\n#    define GSL_FUN extern\n#  elif defined( BUILD_GSL_DLL )\n#    define GSL_FUN extern __declspec(dllexport)\n#  else\n#    define GSL_FUN extern __declspec(dllimport)\n#  endif\n#endif\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_inline.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_block_uchar.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size;\n  size_t stride;\n  unsigned char *data;\n  gsl_block_uchar *block;\n  int owner;\n} \ngsl_vector_uchar;\n\ntypedef struct\n{\n  gsl_vector_uchar vector;\n} _gsl_vector_uchar_view;\n\ntypedef _gsl_vector_uchar_view gsl_vector_uchar_view;\n\ntypedef struct\n{\n  gsl_vector_uchar vector;\n} _gsl_vector_uchar_const_view;\n\ntypedef const _gsl_vector_uchar_const_view gsl_vector_uchar_const_view;\n\n\n/* Allocation */\n\nGSL_FUN gsl_vector_uchar *gsl_vector_uchar_alloc (const size_t n);\nGSL_FUN gsl_vector_uchar *gsl_vector_uchar_calloc (const size_t n);\n\nGSL_FUN gsl_vector_uchar *gsl_vector_uchar_alloc_from_block (gsl_block_uchar * b,\n                                                     const size_t offset, \n                                                     const size_t n, \n                                                     const size_t stride);\n\nGSL_FUN gsl_vector_uchar *gsl_vector_uchar_alloc_from_vector (gsl_vector_uchar * v,\n                                                      const size_t offset, \n                                                      const size_t n, \n                                                      const size_t stride);\n\nGSL_FUN void gsl_vector_uchar_free (gsl_vector_uchar * v);\n\n/* Views */\n\nGSL_FUN _gsl_vector_uchar_view \ngsl_vector_uchar_view_array (unsigned char *v, size_t n);\n\nGSL_FUN _gsl_vector_uchar_view \ngsl_vector_uchar_view_array_with_stride (unsigned char *base,\n                                         size_t stride,\n                                         size_t n);\n\nGSL_FUN _gsl_vector_uchar_const_view \ngsl_vector_uchar_const_view_array (const unsigned char *v, size_t n);\n\nGSL_FUN _gsl_vector_uchar_const_view \ngsl_vector_uchar_const_view_array_with_stride (const unsigned char *base,\n                                               size_t stride,\n                                               size_t n);\n\nGSL_FUN _gsl_vector_uchar_view \ngsl_vector_uchar_subvector (gsl_vector_uchar *v, \n                            size_t i, \n                            size_t n);\n\nGSL_FUN _gsl_vector_uchar_view \ngsl_vector_uchar_subvector_with_stride (gsl_vector_uchar *v, \n                                        size_t i,\n                                        size_t stride,\n                                        size_t n);\n\nGSL_FUN _gsl_vector_uchar_const_view \ngsl_vector_uchar_const_subvector (const gsl_vector_uchar *v, \n                                  size_t i, \n                                  size_t n);\n\nGSL_FUN _gsl_vector_uchar_const_view \ngsl_vector_uchar_const_subvector_with_stride (const gsl_vector_uchar *v, \n                                              size_t i, \n                                              size_t stride,\n                                              size_t n);\n\n/* Operations */\n\nGSL_FUN void gsl_vector_uchar_set_zero (gsl_vector_uchar * v);\nGSL_FUN void gsl_vector_uchar_set_all (gsl_vector_uchar * v, unsigned char x);\nGSL_FUN int gsl_vector_uchar_set_basis (gsl_vector_uchar * v, size_t i);\n\nGSL_FUN int gsl_vector_uchar_fread (FILE * stream, gsl_vector_uchar * v);\nGSL_FUN int gsl_vector_uchar_fwrite (FILE * stream, const gsl_vector_uchar * v);\nGSL_FUN int gsl_vector_uchar_fscanf (FILE * stream, gsl_vector_uchar * v);\nGSL_FUN int gsl_vector_uchar_fprintf (FILE * stream, const gsl_vector_uchar * v,\n                              const char *format);\n\nGSL_FUN int gsl_vector_uchar_memcpy (gsl_vector_uchar * dest, const gsl_vector_uchar * src);\n\nGSL_FUN int gsl_vector_uchar_reverse (gsl_vector_uchar * v);\n\nGSL_FUN int gsl_vector_uchar_swap (gsl_vector_uchar * v, gsl_vector_uchar * w);\nGSL_FUN int gsl_vector_uchar_swap_elements (gsl_vector_uchar * v, const size_t i, const size_t j);\n\nGSL_FUN unsigned char gsl_vector_uchar_max (const gsl_vector_uchar * v);\nGSL_FUN unsigned char gsl_vector_uchar_min (const gsl_vector_uchar * v);\nGSL_FUN void gsl_vector_uchar_minmax (const gsl_vector_uchar * v, unsigned char * min_out, unsigned char * max_out);\n\nGSL_FUN size_t gsl_vector_uchar_max_index (const gsl_vector_uchar * v);\nGSL_FUN size_t gsl_vector_uchar_min_index (const gsl_vector_uchar * v);\nGSL_FUN void gsl_vector_uchar_minmax_index (const gsl_vector_uchar * v, size_t * imin, size_t * imax);\n\nGSL_FUN int gsl_vector_uchar_add (gsl_vector_uchar * a, const gsl_vector_uchar * b);\nGSL_FUN int gsl_vector_uchar_sub (gsl_vector_uchar * a, const gsl_vector_uchar * b);\nGSL_FUN int gsl_vector_uchar_mul (gsl_vector_uchar * a, const gsl_vector_uchar * b);\nGSL_FUN int gsl_vector_uchar_div (gsl_vector_uchar * a, const gsl_vector_uchar * b);\nGSL_FUN int gsl_vector_uchar_scale (gsl_vector_uchar * a, const unsigned char x);\nGSL_FUN int gsl_vector_uchar_add_constant (gsl_vector_uchar * a, const double x);\nGSL_FUN int gsl_vector_uchar_axpby (const unsigned char alpha, const gsl_vector_uchar * x, const unsigned char beta, gsl_vector_uchar * y);\nGSL_FUN unsigned char gsl_vector_uchar_sum (const gsl_vector_uchar * a);\n\nGSL_FUN int gsl_vector_uchar_equal (const gsl_vector_uchar * u, \n                            const gsl_vector_uchar * v);\n\nGSL_FUN int gsl_vector_uchar_isnull (const gsl_vector_uchar * v);\nGSL_FUN int gsl_vector_uchar_ispos (const gsl_vector_uchar * v);\nGSL_FUN int gsl_vector_uchar_isneg (const gsl_vector_uchar * v);\nGSL_FUN int gsl_vector_uchar_isnonneg (const gsl_vector_uchar * v);\n\nGSL_FUN INLINE_DECL unsigned char gsl_vector_uchar_get (const gsl_vector_uchar * v, const size_t i);\nGSL_FUN INLINE_DECL void gsl_vector_uchar_set (gsl_vector_uchar * v, const size_t i, unsigned char x);\nGSL_FUN INLINE_DECL unsigned char * gsl_vector_uchar_ptr (gsl_vector_uchar * v, const size_t i);\nGSL_FUN INLINE_DECL const unsigned char * gsl_vector_uchar_const_ptr (const gsl_vector_uchar * v, const size_t i);\n\n#ifdef HAVE_INLINE\n\nINLINE_FUN\nunsigned char\ngsl_vector_uchar_get (const gsl_vector_uchar * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= v->size))\n    {\n      GSL_ERROR_VAL (\"index out of range\", GSL_EINVAL, 0);\n    }\n#endif\n  return v->data[i * v->stride];\n}\n\nINLINE_FUN\nvoid\ngsl_vector_uchar_set (gsl_vector_uchar * v, const size_t i, unsigned char x)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= v->size))\n    {\n      GSL_ERROR_VOID (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  v->data[i * v->stride] = x;\n}\n\nINLINE_FUN\nunsigned char *\ngsl_vector_uchar_ptr (gsl_vector_uchar * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= v->size))\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return (unsigned char *) (v->data + i * v->stride);\n}\n\nINLINE_FUN\nconst unsigned char *\ngsl_vector_uchar_const_ptr (const gsl_vector_uchar * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(i >= v->size))\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return (const unsigned char *) (v->data + i * v->stride);\n}\n#endif /* HAVE_INLINE */\n\n__END_DECLS\n\n#endif /* __GSL_VECTOR_UCHAR_H__ */\n\n\n", "meta": {"hexsha": "8b29abf33e4733c9c42001f4dd9e0be73a7e62c0", "size": 8465, "ext": "h", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_vector_uchar.h", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-28T08:20:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-28T08:20:20.000Z", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_vector_uchar.h", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_vector_uchar.h", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-14T12:45:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-14T12:45:35.000Z", "avg_line_length": 34.8353909465, "max_line_length": 139, "alphanum_fraction": 0.6948611931, "num_tokens": 2158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1919327818250578, "lm_q2_score": 0.02297737028636319, "lm_q1q2_score": 0.004410110598086112}}
{"text": "#pragma once\n#include <cstddef>\n#include <gsl/gsl.h>\n\nnamespace util{\n\ntemplate<typename T> \nusing span_dyn = gsl::span<T>;\ntemplate<typename T, int64_t M> \nusing span_1d = gsl::span<T,M>;\ntemplate<typename T, int64_t M, int64_t N>\nusing span_2d = gsl::span<T,M,N>;\ntemplate<typename T, int64_t L, int64_t M, int64_t N>\nusing span_3d = gsl::span<T,L,M,N>;\n\n//Not works and param.cpp directly uses gsl.h\ntemplate<typename... Args>\nauto as_span(Args&&... args){\n    return gsl::as_span(std::forward<Args>(args)...);\n}\n\ntemplate<int64_t T> \nusing dim = gsl::dim<T>;\n\ntemplate<std::ptrdiff_t Extent = gsl::dynamic_range>\nusing cstring_span = gsl::basic_string_span<const char, Extent>;\n\n}//namespace util\n\n", "meta": {"hexsha": "8535a886269555224ab6077d4140d224802c32ba", "size": 702, "ext": "h", "lang": "C", "max_stars_repo_path": "rnn++/utils/span.h", "max_stars_repo_name": "uphere-co/nlp-prototype", "max_stars_repo_head_hexsha": "c4623927e5c5c5f9c3e702eb36497ea1d9fd1ff3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rnn++/utils/span.h", "max_issues_repo_name": "uphere-co/nlp-prototype", "max_issues_repo_head_hexsha": "c4623927e5c5c5f9c3e702eb36497ea1d9fd1ff3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rnn++/utils/span.h", "max_forks_repo_name": "uphere-co/nlp-prototype", "max_forks_repo_head_hexsha": "c4623927e5c5c5f9c3e702eb36497ea1d9fd1ff3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4, "max_line_length": 64, "alphanum_fraction": 0.7122507123, "num_tokens": 204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08882029722399612, "lm_q2_score": 0.04958902772449626, "lm_q1q2_score": 0.004404512181538742}}
{"text": "#pragma once\n\n#include \"ShaderCompiler.h\"\n\n#include <gsl/gsl>\n#include <spirv_cross.hpp>\n#include <spirv_parser.hpp>\n#include <unordered_map>\n#include <string>\n\nnamespace Babylon::ShaderCompilerCommon\n{\n    template<typename AppendageT>\n    inline void AppendBytes(std::vector<uint8_t>& bytes, const AppendageT appendage)\n    {\n        auto ptr = reinterpret_cast<const uint8_t*>(&appendage);\n        auto stride = static_cast<std::ptrdiff_t>(sizeof(AppendageT));\n        bytes.insert(bytes.end(), ptr, ptr + stride);\n    }\n\n    template<typename AppendageT = std::string&>\n    inline void AppendBytes(std::vector<uint8_t>& bytes, const std::string& string)\n    {\n        auto ptr = reinterpret_cast<const uint8_t*>(string.data());\n        auto stride = static_cast<std::ptrdiff_t>(string.length());\n        bytes.insert(bytes.end(), ptr, ptr + stride);\n    }\n\n    template<typename ElementT>\n    inline void AppendBytes(std::vector<uint8_t>& bytes, const gsl::span<ElementT>& data)\n    {\n        auto ptr = reinterpret_cast<const uint8_t*>(data.data());\n        auto stride = static_cast<std::ptrdiff_t>(data.size() * sizeof(ElementT));\n        bytes.insert(bytes.end(), ptr, ptr + stride);\n    }\n\n    struct NonSamplerUniformsInfo\n    {\n        struct Uniform\n        {\n            enum class TypeEnum\n            {\n                Vec4,\n                Mat4\n            };\n\n            std::string Name{};\n            uint32_t Offset{};\n            uint16_t RegisterSize{};\n            TypeEnum Type{};\n        };\n\n        uint16_t ByteSize{};\n        std::vector<Uniform> Uniforms{};\n    };\n\n    void AppendUniformBuffer(std::vector<uint8_t>& bytes, const NonSamplerUniformsInfo& uniformBuffer, bool isFragment);\n    void AppendSamplers(std::vector<uint8_t>& bytes, const spirv_cross::Compiler& compiler, const spirv_cross::SmallVector<spirv_cross::Resource>& samplers, std::unordered_map<std::string, uint8_t>& stages);\n    NonSamplerUniformsInfo CollectNonSamplerUniforms(spirv_cross::Parser& parser, const spirv_cross::Compiler& compiler);\n\n    struct ShaderInfo\n    {\n        std::unique_ptr<spirv_cross::Parser> Parser;\n        std::unique_ptr<const spirv_cross::Compiler> Compiler;\n        gsl::span<uint8_t> Bytes;\n        std::unordered_map<std::string, std::string> AttributeRenaming;\n    };\n\n    ShaderCompiler::BgfxShaderInfo CreateBgfxShader(ShaderInfo vertexShaderInfo, ShaderInfo fragmentShaderInfo);\n}\n", "meta": {"hexsha": "1242354a995c9c9f4140e42e5b91aee9d5359a56", "size": 2421, "ext": "h", "lang": "C", "max_stars_repo_path": "Plugins/NativeEngine/Source/ShaderCompilerCommon.h", "max_stars_repo_name": "chiamaka-123/BabylonNative", "max_stars_repo_head_hexsha": "7f1f9fd23bf649c9c8a1260f2b93752145b0c024", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 474.0, "max_stars_repo_stars_event_min_datetime": "2019-05-29T09:41:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:09:35.000Z", "max_issues_repo_path": "Plugins/NativeEngine/Source/ShaderCompilerCommon.h", "max_issues_repo_name": "chiamaka-123/BabylonNative", "max_issues_repo_head_hexsha": "7f1f9fd23bf649c9c8a1260f2b93752145b0c024", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 593.0, "max_issues_repo_issues_event_min_datetime": "2019-05-31T23:56:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:25:09.000Z", "max_forks_repo_path": "Plugins/NativeEngine/Source/ShaderCompilerCommon.h", "max_forks_repo_name": "chiamaka-123/BabylonNative", "max_forks_repo_head_hexsha": "7f1f9fd23bf649c9c8a1260f2b93752145b0c024", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 114.0, "max_forks_repo_forks_event_min_datetime": "2019-06-10T18:07:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T21:13:27.000Z", "avg_line_length": 34.0985915493, "max_line_length": 207, "alphanum_fraction": 0.6621230896, "num_tokens": 557, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22270014914315836, "lm_q2_score": 0.019719129871614203, "lm_q1q2_score": 0.0043914531633817925}}
{"text": "/*\n * This file is part of the GROMACS molecular simulation package.\n *\n * Copyright (c) 1991-2000, University of Groningen, The Netherlands.\n * Copyright (c) 2001-2004, The GROMACS development team,\n * check out http://www.gromacs.org for more information.\n * Copyright (c) 2012,2013, by the GROMACS development team, led by\n * David van der Spoel, Berk Hess, Erik Lindahl, and including many\n * others, as listed in the AUTHORS file in the top-level source\n * directory and at http://www.gromacs.org.\n *\n * GROMACS is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public License\n * as published by the Free Software Foundation; either version 2.1\n * of the License, or (at your option) any later version.\n *\n * GROMACS is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with GROMACS; if not, see\n * http://www.gnu.org/licenses, or write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.\n *\n * If you want to redistribute modifications to GROMACS, please\n * consider that scientific software is very special. Version\n * control is crucial - bugs must be traceable. We will be happy to\n * consider code for inclusion in the official distribution, but\n * derived work must not be called official GROMACS. Details are found\n * in the README & COPYING files - if they are missing, get the\n * official version at http://www.gromacs.org.\n *\n * To help us fund GROMACS development, we humbly ask that you cite\n * the research papers on the package. Check out http://www.gromacs.org.\n */\n#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n#include <math.h>\n#include <string.h>\n#include <stdlib.h>\n#include \"statutil.h\"\n#include \"sysstuff.h\"\n#include \"typedefs.h\"\n#include \"smalloc.h\"\n#include \"macros.h\"\n#include \"gmx_fatal.h\"\n#include \"vec.h\"\n#include \"copyrite.h\"\n#include \"futil.h\"\n#include \"readinp.h\"\n#include \"statutil.h\"\n#include \"txtdump.h\"\n#include \"gstat.h\"\n#include \"xvgr.h\"\n#include \"physics.h\"\n#include \"gmx_ana.h\"\n\nenum {\n    epAuf, epEuf, epAfu, epEfu, epNR\n};\nenum {\n    eqAif, eqEif, eqAfi, eqEfi, eqAui, eqEui, eqAiu, eqEiu, eqNR\n};\nstatic char *eep[epNR] = { \"Af\", \"Ef\", \"Au\", \"Eu\" };\nstatic char *eeq[eqNR] = { \"Aif\", \"Eif\", \"Afi\", \"Efi\", \"Aui\", \"Eui\", \"Aiu\", \"Eiu\" };\n\ntypedef struct {\n    int       nreplica;  /* Number of replicas in the calculation                   */\n    int       nframe;    /* Number of time frames                                   */\n    int       nstate;    /* Number of states the system can be in, e.g. F,I,U       */\n    int       nparams;   /* Is 2, 4 or 8                                            */\n    gmx_bool *bMask;     /* Determine whether this replica is part of the d2 comp.  */\n    gmx_bool  bSum;\n    gmx_bool  bDiscrete; /* Use either discrete folding (0/1) or a continuous       */\n    /* criterion */\n    int       nmask;     /* Number of replicas taken into account                   */\n    real      dt;        /* Timestep between frames                                 */\n    int       j0, j1;    /* Range of frames used in calculating delta               */\n    real    **temp, **data, **data2;\n    int     **state;     /* State index running from 0 (F) to nstate-1 (U)          */\n    real    **beta, **fcalt, **icalt;\n    real     *time, *sumft, *sumit, *sumfct, *sumict;\n    real     *params;\n    real     *d2_replica;\n} t_remd_data;\n\n#ifdef HAVE_LIBGSL\n#include <gsl/gsl_multimin.h>\n\nstatic char *itoa(int i)\n{\n    static char ptr[12];\n\n    sprintf(ptr, \"%d\", i);\n    return ptr;\n}\n\nstatic char *epnm(int nparams, int index)\n{\n    static char buf[32], from[8], to[8];\n    int         nn, ni, ii;\n\n    range_check(index, 0, nparams);\n    if ((nparams == 2) || (nparams == 4))\n    {\n        return eep[index];\n    }\n    else if ((nparams > 4) && (nparams % 4 == 0))\n    {\n        return eeq[index];\n    }\n    else\n    {\n        gmx_fatal(FARGS, \"Don't know how to handle %d parameters\", nparams);\n    }\n\n    return NULL;\n}\n\nstatic gmx_bool bBack(t_remd_data *d)\n{\n    return (d->nparams > 2);\n}\n\nstatic real is_folded(t_remd_data *d, int irep, int jframe)\n{\n    if (d->state[irep][jframe] == 0)\n    {\n        return 1.0;\n    }\n    else\n    {\n        return 0.0;\n    }\n}\n\nstatic real is_unfolded(t_remd_data *d, int irep, int jframe)\n{\n    if (d->state[irep][jframe] == d->nstate-1)\n    {\n        return 1.0;\n    }\n    else\n    {\n        return 0.0;\n    }\n}\n\nstatic real is_intermediate(t_remd_data *d, int irep, int jframe)\n{\n    if ((d->state[irep][jframe] == 1) && (d->nstate > 2))\n    {\n        return 1.0;\n    }\n    else\n    {\n        return 0.0;\n    }\n}\n\nstatic void integrate_dfdt(t_remd_data *d)\n{\n    int    i, j;\n    double beta, ddf, ddi, df, db, fac, sumf, sumi, area;\n\n    d->sumfct[0] = 0;\n    d->sumict[0] = 0;\n    for (i = 0; (i < d->nreplica); i++)\n    {\n        if (d->bMask[i])\n        {\n            if (d->bDiscrete)\n            {\n                ddf = 0.5*d->dt*is_folded(d, i, 0);\n                ddi = 0.5*d->dt*is_intermediate(d, i, 0);\n            }\n            else\n            {\n                ddf = 0.5*d->dt*d->state[i][0];\n                ddi = 0.0;\n            }\n            d->fcalt[i][0] = ddf;\n            d->icalt[i][0] = ddi;\n            d->sumfct[0]  += ddf;\n            d->sumict[0]  += ddi;\n        }\n    }\n    for (j = 1; (j < d->nframe); j++)\n    {\n        if (j == d->nframe-1)\n        {\n            fac = 0.5*d->dt;\n        }\n        else\n        {\n            fac = d->dt;\n        }\n        sumf = sumi = 0;\n        for (i = 0; (i < d->nreplica); i++)\n        {\n            if (d->bMask[i])\n            {\n                beta = d->beta[i][j];\n                if ((d->nstate <= 2) || d->bDiscrete)\n                {\n                    if (d->bDiscrete)\n                    {\n                        df = (d->params[epAuf]*exp(-beta*d->params[epEuf])*\n                              is_unfolded(d, i, j));\n                    }\n                    else\n                    {\n                        area = (d->data2 ? d->data2[i][j] : 1.0);\n                        df   =  area*d->params[epAuf]*exp(-beta*d->params[epEuf]);\n                    }\n                    if (bBack(d))\n                    {\n                        db = 0;\n                        if (d->bDiscrete)\n                        {\n                            db = (d->params[epAfu]*exp(-beta*d->params[epEfu])*\n                                  is_folded(d, i, j));\n                        }\n                        else\n                        {\n                            gmx_fatal(FARGS, \"Back reaction not implemented with continuous\");\n                        }\n                        ddf = fac*(df-db);\n                    }\n                    else\n                    {\n                        ddf = fac*df;\n                    }\n                    d->fcalt[i][j] = d->fcalt[i][j-1] + ddf;\n                    sumf          += ddf;\n                }\n                else\n                {\n                    ddf = fac*((d->params[eqAif]*exp(-beta*d->params[eqEif])*\n                                is_intermediate(d, i, j)) -\n                               (d->params[eqAfi]*exp(-beta*d->params[eqEfi])*\n                                is_folded(d, i, j)));\n                    ddi = fac*((d->params[eqAui]*exp(-beta*d->params[eqEui])*\n                                is_unfolded(d, i, j)) -\n                               (d->params[eqAiu]*exp(-beta*d->params[eqEiu])*\n                                is_intermediate(d, i, j)));\n                    d->fcalt[i][j] = d->fcalt[i][j-1] + ddf;\n                    d->icalt[i][j] = d->icalt[i][j-1] + ddi;\n                    sumf          += ddf;\n                    sumi          += ddi;\n                }\n            }\n        }\n        d->sumfct[j] = d->sumfct[j-1] + sumf;\n        d->sumict[j] = d->sumict[j-1] + sumi;\n    }\n    if (debug)\n    {\n        fprintf(debug, \"@type xy\\n\");\n        for (j = 0; (j < d->nframe); j++)\n        {\n            fprintf(debug, \"%8.3f  %12.5e\\n\", d->time[j], d->sumfct[j]);\n        }\n        fprintf(debug, \"&\\n\");\n    }\n}\n\nstatic void sum_ft(t_remd_data *d)\n{\n    int    i, j;\n    double fac;\n\n    for (j = 0; (j < d->nframe); j++)\n    {\n        d->sumft[j] = 0;\n        d->sumit[j] = 0;\n        if ((j == 0) || (j == d->nframe-1))\n        {\n            fac = d->dt*0.5;\n        }\n        else\n        {\n            fac = d->dt;\n        }\n        for (i = 0; (i < d->nreplica); i++)\n        {\n            if (d->bMask[i])\n            {\n                if (d->bDiscrete)\n                {\n                    d->sumft[j] += fac*is_folded(d, i, j);\n                    d->sumit[j] += fac*is_intermediate(d, i, j);\n                }\n                else\n                {\n                    d->sumft[j] += fac*d->state[i][j];\n                }\n            }\n        }\n    }\n}\n\nstatic double calc_d2(t_remd_data *d)\n{\n    int    i, j;\n    double dd2, d2 = 0, dr2, tmp;\n\n    integrate_dfdt(d);\n\n    if (d->bSum)\n    {\n        for (j = d->j0; (j < d->j1); j++)\n        {\n            if (d->bDiscrete)\n            {\n                d2  += sqr(d->sumft[j]-d->sumfct[j]);\n                if (d->nstate > 2)\n                {\n                    d2 += sqr(d->sumit[j]-d->sumict[j]);\n                }\n            }\n            else\n            {\n                d2  += sqr(d->sumft[j]-d->sumfct[j]);\n            }\n        }\n    }\n    else\n    {\n        for (i = 0; (i < d->nreplica); i++)\n        {\n            dr2 = 0;\n            if (d->bMask[i])\n            {\n                for (j = d->j0; (j < d->j1); j++)\n                {\n                    tmp  = sqr(is_folded(d, i, j)-d->fcalt[i][j]);\n                    d2  += tmp;\n                    dr2 += tmp;\n                    if (d->nstate > 2)\n                    {\n                        tmp  = sqr(is_intermediate(d, i, j)-d->icalt[i][j]);\n                        d2  += tmp;\n                        dr2 += tmp;\n                    }\n                }\n                d->d2_replica[i] = dr2/(d->j1-d->j0);\n            }\n        }\n    }\n    dd2 = (d2/(d->j1-d->j0))/(d->bDiscrete ? d->nmask : 1);\n\n    return dd2;\n}\n\nstatic double my_f(const gsl_vector *v, void *params)\n{\n    t_remd_data *d       = (t_remd_data *) params;\n    double       penalty = 0;\n    int          i;\n\n    for (i = 0; (i < d->nparams); i++)\n    {\n        d->params[i] = gsl_vector_get(v, i);\n        if (d->params[i] < 0)\n        {\n            penalty += 10;\n        }\n    }\n    if (penalty > 0)\n    {\n        return penalty;\n    }\n    else\n    {\n        return calc_d2(d);\n    }\n}\n\nstatic void optimize_remd_parameters(FILE *fp, t_remd_data *d, int maxiter,\n                                     real tol)\n{\n    real   size, d2;\n    int    iter   = 0;\n    int    status = 0;\n    int    i;\n\n    const gsl_multimin_fminimizer_type *T;\n    gsl_multimin_fminimizer            *s;\n\n    gsl_vector                         *x, *dx;\n    gsl_multimin_function               my_func;\n\n    my_func.f      = &my_f;\n    my_func.n      = d->nparams;\n    my_func.params = (void *) d;\n\n    /* Starting point */\n    x = gsl_vector_alloc (my_func.n);\n    for (i = 0; (i < my_func.n); i++)\n    {\n        gsl_vector_set (x, i, d->params[i]);\n    }\n\n    /* Step size, different for each of the parameters */\n    dx = gsl_vector_alloc (my_func.n);\n    for (i = 0; (i < my_func.n); i++)\n    {\n        gsl_vector_set (dx, i, 0.1*d->params[i]);\n    }\n\n    T = gsl_multimin_fminimizer_nmsimplex;\n    s = gsl_multimin_fminimizer_alloc (T, my_func.n);\n\n    gsl_multimin_fminimizer_set (s, &my_func, x, dx);\n    gsl_vector_free (x);\n    gsl_vector_free (dx);\n\n    printf (\"%5s\", \"Iter\");\n    for (i = 0; (i < my_func.n); i++)\n    {\n        printf(\" %12s\", epnm(my_func.n, i));\n    }\n    printf (\" %12s %12s\\n\", \"NM Size\", \"Chi2\");\n\n    do\n    {\n        iter++;\n        status = gsl_multimin_fminimizer_iterate (s);\n\n        if (status != 0)\n        {\n            gmx_fatal(FARGS, \"Something went wrong in the iteration in minimizer %s\",\n                      gsl_multimin_fminimizer_name(s));\n        }\n\n        d2     = gsl_multimin_fminimizer_minimum(s);\n        size   = gsl_multimin_fminimizer_size(s);\n        status = gsl_multimin_test_size(size, tol);\n\n        if (status == GSL_SUCCESS)\n        {\n            printf (\"Minimum found using %s at:\\n\",\n                    gsl_multimin_fminimizer_name(s));\n        }\n\n        printf (\"%5d\", iter);\n        for (i = 0; (i < my_func.n); i++)\n        {\n            printf(\" %12.4e\", gsl_vector_get (s->x, i));\n        }\n        printf (\" %12.4e %12.4e\\n\", size, d2);\n    }\n    while ((status == GSL_CONTINUE) && (iter < maxiter));\n\n    gsl_multimin_fminimizer_free (s);\n}\n\nstatic void preprocess_remd(FILE *fp, t_remd_data *d, real cutoff, real tref,\n                            real ucut, gmx_bool bBack, real Euf, real Efu,\n                            real Ei, real t0, real t1, gmx_bool bSum, gmx_bool bDiscrete,\n                            int nmult)\n{\n    int  i, j, ninter;\n    real dd, tau_f, tau_u;\n\n    ninter = (ucut > cutoff) ? 1 : 0;\n    if (ninter && (ucut <= cutoff))\n    {\n        gmx_fatal(FARGS, \"You have requested an intermediate but the cutoff for intermediates %f is smaller than the normal cutoff(%f)\", ucut, cutoff);\n    }\n\n    if (!bBack)\n    {\n        d->nparams = 2;\n        d->nstate  = 2;\n    }\n    else\n    {\n        d->nparams = 4*(1+ninter);\n        d->nstate  = 2+ninter;\n    }\n    d->bSum      = bSum;\n    d->bDiscrete = bDiscrete;\n    snew(d->beta, d->nreplica);\n    snew(d->state, d->nreplica);\n    snew(d->bMask, d->nreplica);\n    snew(d->d2_replica, d->nreplica);\n    snew(d->sumft, d->nframe);\n    snew(d->sumit, d->nframe);\n    snew(d->sumfct, d->nframe);\n    snew(d->sumict, d->nframe);\n    snew(d->params, d->nparams);\n    snew(d->fcalt, d->nreplica);\n    snew(d->icalt, d->nreplica);\n\n    /* convert_times(d->nframe,d->time); */\n\n    if (t0 < 0)\n    {\n        d->j0 = 0;\n    }\n    else\n    {\n        for (d->j0 = 0; (d->j0 < d->nframe) && (d->time[d->j0] < t0); d->j0++)\n        {\n            ;\n        }\n    }\n    if (t1 < 0)\n    {\n        d->j1 = d->nframe;\n    }\n    else\n    {\n        for (d->j1 = 0; (d->j1 < d->nframe) && (d->time[d->j1] < t1); d->j1++)\n        {\n            ;\n        }\n    }\n    if ((d->j1-d->j0) < d->nparams+2)\n    {\n        gmx_fatal(FARGS, \"Start (%f) or end time (%f) for fitting inconsistent. Reduce t0, increase t1 or supply more data\", t0, t1);\n    }\n    fprintf(fp, \"Will optimize from %g to %g\\n\",\n            d->time[d->j0], d->time[d->j1-1]);\n    d->nmask = d->nreplica;\n    for (i = 0; (i < d->nreplica); i++)\n    {\n        snew(d->beta[i], d->nframe);\n        snew(d->state[i], d->nframe);\n        snew(d->fcalt[i], d->nframe);\n        snew(d->icalt[i], d->nframe);\n        d->bMask[i] = TRUE;\n        for (j = 0; (j < d->nframe); j++)\n        {\n            d->beta[i][j] = 1.0/(BOLTZ*d->temp[i][j]);\n            dd            = d->data[i][j];\n            if (bDiscrete)\n            {\n                if (dd <= cutoff)\n                {\n                    d->state[i][j] = 0;\n                }\n                else if ((ucut > cutoff) && (dd <= ucut))\n                {\n                    d->state[i][j] = 1;\n                }\n                else\n                {\n                    d->state[i][j] = d->nstate-1;\n                }\n            }\n            else\n            {\n                d->state[i][j] = dd*nmult;\n            }\n        }\n    }\n    sum_ft(d);\n\n    /* Assume forward rate constant is half the total time in this\n     * simulation and backward is ten times as long */\n    if (bDiscrete)\n    {\n        tau_f            = d->time[d->nframe-1];\n        tau_u            = 4*tau_f;\n        d->params[epEuf] = Euf;\n        d->params[epAuf] = exp(d->params[epEuf]/(BOLTZ*tref))/tau_f;\n        if (bBack)\n        {\n            d->params[epEfu] = Efu;\n            d->params[epAfu] = exp(d->params[epEfu]/(BOLTZ*tref))/tau_u;\n            if (ninter > 0)\n            {\n                d->params[eqEui] = Ei;\n                d->params[eqAui] = exp(d->params[eqEui]/(BOLTZ*tref))/tau_u;\n                d->params[eqEiu] = Ei;\n                d->params[eqAiu] = exp(d->params[eqEiu]/(BOLTZ*tref))/tau_u;\n            }\n        }\n        else\n        {\n            d->params[epAfu]  = 0;\n            d->params[epEfu]  = 0;\n        }\n    }\n    else\n    {\n        d->params[epEuf] = Euf;\n        if (d->data2)\n        {\n            d->params[epAuf] = 0.1;\n        }\n        else\n        {\n            d->params[epAuf] = 20.0;\n        }\n    }\n}\n\nstatic real tau(real A, real E, real T)\n{\n    return exp(E/(BOLTZ*T))/A;\n}\n\nstatic real folded_fraction(t_remd_data *d, real tref)\n{\n    real tauf, taub;\n\n    tauf = tau(d->params[epAuf], d->params[epEuf], tref);\n    taub = tau(d->params[epAfu], d->params[epEfu], tref);\n\n    return (taub/(tauf+taub));\n}\n\nstatic void print_tau(FILE *gp, t_remd_data *d, real tref)\n{\n    real tauf, taub, ddd, fff, DG, DH, TDS, Tm, Tb, Te, Fb, Fe, Fm;\n    int  i, np = d->nparams;\n\n    ddd = calc_d2(d);\n    fprintf(gp, \"Final value for Chi2 = %12.5e (%d replicas)\\n\", ddd, d->nmask);\n    tauf = tau(d->params[epAuf], d->params[epEuf], tref);\n    fprintf(gp, \"%s = %12.5e %s = %12.5e (kJ/mole)\\n\",\n            epnm(np, epAuf), d->params[epAuf],\n            epnm(np, epEuf), d->params[epEuf]);\n    if (bBack(d))\n    {\n        taub = tau(d->params[epAfu], d->params[epEfu], tref);\n        fprintf(gp, \"%s = %12.5e %s = %12.5e (kJ/mole)\\n\",\n                epnm(np, epAfu), d->params[epAfu],\n                epnm(np, epEfu), d->params[epEfu]);\n        fprintf(gp, \"Equilibrium properties at T = %g\\n\", tref);\n        fprintf(gp, \"tau_f = %8.3f ns, tau_b = %8.3f ns\\n\", tauf/1000, taub/1000);\n        fff = taub/(tauf+taub);\n        DG  = BOLTZ*tref*log(fff/(1-fff));\n        DH  = d->params[epEfu]-d->params[epEuf];\n        TDS = DH-DG;\n        fprintf(gp, \"Folded fraction     F = %8.3f\\n\", fff);\n        fprintf(gp, \"Unfolding energies: DG = %8.3f  DH = %8.3f TDS = %8.3f\\n\",\n                DG, DH, TDS);\n        Tb = 260;\n        Te = 420;\n        Tm = 0;\n        Fm = 0;\n        Fb = folded_fraction(d, Tb);\n        Fe = folded_fraction(d, Te);\n        while ((Te-Tb > 0.001) && (Fm != 0.5))\n        {\n            Tm = 0.5*(Tb+Te);\n            Fm = folded_fraction(d, Tm);\n            if (Fm > 0.5)\n            {\n                Fb = Fm;\n                Tb = Tm;\n            }\n            else if (Fm < 0.5)\n            {\n                Te = Tm;\n                Fe = Fm;\n            }\n        }\n        if ((Fb-0.5)*(Fe-0.5) <= 0)\n        {\n            fprintf(gp, \"Melting temperature Tm = %8.3f K\\n\", Tm);\n        }\n        else\n        {\n            fprintf(gp, \"No melting temperature detected between 260 and 420K\\n\");\n        }\n        if (np > 4)\n        {\n            char *ptr;\n            fprintf(gp, \"Data for intermediates at T = %g\\n\", tref);\n            fprintf(gp, \"%8s  %10s  %10s  %10s\\n\", \"Name\", \"A\", \"E\", \"tau\");\n            for (i = 0; (i < np/2); i++)\n            {\n                tauf = tau(d->params[2*i], d->params[2*i+1], tref);\n                ptr  = epnm(d->nparams, 2*i);\n                fprintf(gp, \"%8s  %10.3e  %10.3e  %10.3e\\n\", ptr+1,\n                        d->params[2*i], d->params[2*i+1], tauf/1000);\n            }\n        }\n    }\n    else\n    {\n        fprintf(gp, \"Equilibrium properties at T = %g\\n\", tref);\n        fprintf(gp, \"tau_f = %8.3f\\n\", tauf);\n    }\n}\n\nstatic void dump_remd_parameters(FILE *gp, t_remd_data *d, const char *fn,\n                                 const char *fn2, const char *rfn,\n                                 const char *efn, const char *mfn, int skip, real tref,\n                                 output_env_t oenv)\n{\n    FILE       *fp, *hp;\n    int         i, j, np = d->nparams;\n    real        rhs, tauf, taub, fff, DG;\n    real       *params;\n    const char *leg[]  = { \"Measured\", \"Fit\", \"Difference\" };\n    const char *mleg[] = { \"Folded fraction\", \"DG (kJ/mole)\"};\n    char      **rleg;\n    real        fac[] = { 0.97, 0.98, 0.99, 1.0, 1.01, 1.02, 1.03 };\n#define NFAC asize(fac)\n    real        d2[NFAC];\n    double      norm;\n\n    integrate_dfdt(d);\n    print_tau(gp, d, tref);\n    norm = (d->bDiscrete ? 1.0/d->nmask : 1.0);\n\n    if (fn)\n    {\n        fp = xvgropen(fn, \"Optimized fit to data\", \"Time (ps)\", \"Fraction Folded\", oenv);\n        xvgr_legend(fp, asize(leg), leg, oenv);\n        for (i = 0; (i < d->nframe); i++)\n        {\n            if ((skip <= 0) || ((i % skip) == 0))\n            {\n                fprintf(fp, \"%12.5e  %12.5e  %12.5e  %12.5e\\n\", d->time[i],\n                        d->sumft[i]*norm, d->sumfct[i]*norm,\n                        (d->sumft[i]-d->sumfct[i])*norm);\n            }\n        }\n        ffclose(fp);\n    }\n    if (!d->bSum && rfn)\n    {\n        snew(rleg, d->nreplica*2);\n        for (i = 0; (i < d->nreplica); i++)\n        {\n            snew(rleg[2*i], 32);\n            snew(rleg[2*i+1], 32);\n            sprintf(rleg[2*i], \"\\\\f{4}F(t) %d\", i);\n            sprintf(rleg[2*i+1], \"\\\\f{12}F \\\\f{4}(t) %d\", i);\n        }\n        fp = xvgropen(rfn, \"Optimized fit to data\", \"Time (ps)\", \"Fraction Folded\", oenv);\n        xvgr_legend(fp, d->nreplica*2, (const char**)rleg, oenv);\n        for (j = 0; (j < d->nframe); j++)\n        {\n            if ((skip <= 0) || ((j % skip) == 0))\n            {\n                fprintf(fp, \"%12.5e\", d->time[j]);\n                for (i = 0; (i < d->nreplica); i++)\n                {\n                    fprintf(fp, \"  %5f  %9.2e\", is_folded(d, i, j), d->fcalt[i][j]);\n                }\n                fprintf(fp, \"\\n\");\n            }\n        }\n        ffclose(fp);\n    }\n\n    if (fn2 && (d->nstate > 2))\n    {\n        fp = xvgropen(fn2, \"Optimized fit to data\", \"Time (ps)\",\n                      \"Fraction Intermediate\", oenv);\n        xvgr_legend(fp, asize(leg), leg, oenv);\n        for (i = 0; (i < d->nframe); i++)\n        {\n            if ((skip <= 0) || ((i % skip) == 0))\n            {\n                fprintf(fp, \"%12.5e  %12.5e  %12.5e  %12.5e\\n\", d->time[i],\n                        d->sumit[i]*norm, d->sumict[i]*norm,\n                        (d->sumit[i]-d->sumict[i])*norm);\n            }\n        }\n        ffclose(fp);\n    }\n    if (mfn)\n    {\n        if (bBack(d))\n        {\n            fp = xvgropen(mfn, \"Melting curve\", \"T (K)\", \"\", oenv);\n            xvgr_legend(fp, asize(mleg), mleg, oenv);\n            for (i = 260; (i <= 420); i++)\n            {\n                tauf = tau(d->params[epAuf], d->params[epEuf], 1.0*i);\n                taub = tau(d->params[epAfu], d->params[epEfu], 1.0*i);\n                fff  = taub/(tauf+taub);\n                DG   = BOLTZ*i*log(fff/(1-fff));\n                fprintf(fp, \"%5d  %8.3f  %8.3f\\n\", i, fff, DG);\n            }\n            ffclose(fp);\n        }\n    }\n\n    if (efn)\n    {\n        snew(params, d->nparams);\n        for (i = 0; (i < d->nparams); i++)\n        {\n            params[i] = d->params[i];\n        }\n\n        hp = xvgropen(efn, \"Chi2 as a function of relative parameter\",\n                      \"Fraction\", \"Chi2\", oenv);\n        for (j = 0; (j < d->nparams); j++)\n        {\n            /* Reset all parameters to optimized values */\n            fprintf(hp, \"@type xy\\n\");\n            for (i = 0; (i < d->nparams); i++)\n            {\n                d->params[i] = params[i];\n            }\n            /* Now modify one of them */\n            for (i = 0; (i < NFAC); i++)\n            {\n                d->params[j] = fac[i]*params[j];\n                d2[i]        = calc_d2(d);\n                fprintf(gp, \"%s = %12g  d2 = %12g\\n\", epnm(np, j), d->params[j], d2[i]);\n                fprintf(hp, \"%12g  %12g\\n\", fac[i], d2[i]);\n            }\n            fprintf(hp, \"&\\n\");\n        }\n        ffclose(hp);\n        for (i = 0; (i < d->nparams); i++)\n        {\n            d->params[i] = params[i];\n        }\n        sfree(params);\n    }\n    if (!d->bSum)\n    {\n        for (i = 0; (i < d->nreplica); i++)\n        {\n            fprintf(gp, \"Chi2[%3d] = %8.2e\\n\", i, d->d2_replica[i]);\n        }\n    }\n}\n#endif /*HAVE_LIBGSL*/\n\nint gmx_kinetics(int argc, char *argv[])\n{\n    const char     *desc[] = {\n        \"[TT]g_kinetics[tt] reads two [TT].xvg[tt] files, each one containing data for N replicas.\",\n        \"The first file contains the temperature of each replica at each timestep,\",\n        \"and the second contains real values that can be interpreted as\",\n        \"an indicator for folding. If the value in the file is larger than\",\n        \"the cutoff it is taken to be unfolded and the other way around.[PAR]\",\n        \"From these data an estimate of the forward and backward rate constants\",\n        \"for folding is made at a reference temperature. In addition,\",\n        \"a theoretical melting curve and free energy as a function of temperature\",\n        \"are printed in an [TT].xvg[tt] file.[PAR]\",\n        \"The user can give a max value to be regarded as intermediate\",\n        \"([TT]-ucut[tt]), which, when given will trigger the use of an intermediate state\",\n        \"in the algorithm to be defined as those structures that have\",\n        \"cutoff < DATA < ucut. Structures with DATA values larger than ucut will\",\n        \"not be regarded as potential folders. In this case 8 parameters are optimized.[PAR]\",\n        \"The average fraction foled is printed in an [TT].xvg[tt] file together with the fit to it.\",\n        \"If an intermediate is used a further file will show the build of the intermediate and the fit to that process.[PAR]\",\n        \"The program can also be used with continuous variables (by setting\",\n        \"[TT]-nodiscrete[tt]). In this case kinetics of other processes can be\",\n        \"studied. This is very much a work in progress and hence the manual\",\n        \"(this information) is lagging behind somewhat.[PAR]\",\n        \"In order to compile this program you need access to the GNU\",\n        \"scientific library.\"\n    };\n    static int      nreplica  = 1;\n    static real     tref      = 298.15;\n    static real     cutoff    = 0.2;\n    static real     ucut      = 0.0;\n    static real     Euf       = 10;\n    static real     Efu       = 30;\n    static real     Ei        = 10;\n    static gmx_bool bHaveT    = TRUE;\n    static real     t0        = -1;\n    static real     t1        = -1;\n    static real     tb        = 0;\n    static real     te        = 0;\n    static real     tol       = 1e-3;\n    static int      maxiter   = 100;\n    static int      skip      = 0;\n    static int      nmult     = 1;\n    static gmx_bool bBack     = TRUE;\n    static gmx_bool bSplit    = TRUE;\n    static gmx_bool bSum      = TRUE;\n    static gmx_bool bDiscrete = TRUE;\n    t_pargs         pa[]      = {\n        { \"-time\",    FALSE, etBOOL, {&bHaveT},\n          \"Expect a time in the input\" },\n        { \"-b\",       FALSE, etREAL, {&tb},\n          \"First time to read from set\" },\n        { \"-e\",       FALSE, etREAL, {&te},\n          \"Last time to read from set\" },\n        { \"-bfit\",    FALSE, etREAL, {&t0},\n          \"Time to start the fit from\" },\n        { \"-efit\",    FALSE, etREAL, {&t1},\n          \"Time to end the fit\" },\n        { \"-T\",       FALSE, etREAL, {&tref},\n          \"Reference temperature for computing rate constants\" },\n        { \"-n\",       FALSE, etINT, {&nreplica},\n          \"Read data for this number of replicas. Only necessary when files are written in xmgrace format using @type and & as delimiters.\" },\n        { \"-cut\",     FALSE, etREAL, {&cutoff},\n          \"Cut-off (max) value for regarding a structure as folded\" },\n        { \"-ucut\",    FALSE, etREAL, {&ucut},\n          \"Cut-off (max) value for regarding a structure as intermediate (if not folded)\" },\n        { \"-euf\",     FALSE, etREAL, {&Euf},\n          \"Initial guess for energy of activation for folding (kJ/mol)\" },\n        { \"-efu\",     FALSE, etREAL, {&Efu},\n          \"Initial guess for energy of activation for unfolding (kJ/mol)\" },\n        { \"-ei\",      FALSE, etREAL, {&Ei},\n          \"Initial guess for energy of activation for intermediates (kJ/mol)\" },\n        { \"-maxiter\", FALSE, etINT, {&maxiter},\n          \"Max number of iterations\" },\n        { \"-back\",    FALSE, etBOOL, {&bBack},\n          \"Take the back reaction into account\" },\n        { \"-tol\",     FALSE, etREAL, {&tol},\n          \"Absolute tolerance for convergence of the Nelder and Mead simplex algorithm\" },\n        { \"-skip\",    FALSE, etINT, {&skip},\n          \"Skip points in the output [TT].xvg[tt] file\" },\n        { \"-split\",   FALSE, etBOOL, {&bSplit},\n          \"Estimate error by splitting the number of replicas in two and refitting\" },\n        { \"-sum\",     FALSE, etBOOL, {&bSum},\n          \"Average folding before computing [GRK]chi[grk]^2\" },\n        { \"-discrete\", FALSE, etBOOL, {&bDiscrete},\n          \"Use a discrete folding criterion (F <-> U) or a continuous one\" },\n        { \"-mult\",    FALSE, etINT, {&nmult},\n          \"Factor to multiply the data with before discretization\" }\n    };\n#define NPA asize(pa)\n\n    FILE        *fp;\n    real         dt_t, dt_d, dt_d2;\n    int          nset_t, nset_d, nset_d2, n_t, n_d, n_d2, i;\n    const char  *tfile, *dfile, *dfile2;\n    t_remd_data  remd;\n    output_env_t oenv;\n\n    t_filenm     fnm[] = {\n        { efXVG, \"-f\",    \"temp\",    ffREAD   },\n        { efXVG, \"-d\",    \"data\",    ffREAD   },\n        { efXVG, \"-d2\",   \"data2\",   ffOPTRD  },\n        { efXVG, \"-o\",    \"ft_all\",  ffWRITE  },\n        { efXVG, \"-o2\",   \"it_all\",  ffOPTWR  },\n        { efXVG, \"-o3\",   \"ft_repl\", ffOPTWR  },\n        { efXVG, \"-ee\",   \"err_est\", ffOPTWR  },\n        { efLOG, \"-g\",    \"remd\",    ffWRITE  },\n        { efXVG, \"-m\",    \"melt\",    ffWRITE  }\n    };\n#define NFILE asize(fnm)\n\n    CopyRight(stderr, argv[0]);\n    parse_common_args(&argc, argv, PCA_CAN_VIEW | PCA_BE_NICE | PCA_TIME_UNIT,\n                      NFILE, fnm, NPA, pa, asize(desc), desc, 0, NULL, &oenv);\n\n#ifdef HAVE_LIBGSL\n    please_cite(stdout, \"Spoel2006d\");\n    if (cutoff < 0)\n    {\n        gmx_fatal(FARGS, \"cutoff should be >= 0 (rather than %f)\", cutoff);\n    }\n\n    tfile   = opt2fn(\"-f\", NFILE, fnm);\n    dfile   = opt2fn(\"-d\", NFILE, fnm);\n    dfile2  = opt2fn_null(\"-d2\", NFILE, fnm);\n\n    fp = ffopen(opt2fn(\"-g\", NFILE, fnm), \"w\");\n\n    remd.temp = read_xvg_time(tfile, bHaveT,\n                              opt2parg_bSet(\"-b\", NPA, pa), tb,\n                              opt2parg_bSet(\"-e\", NPA, pa), te,\n                              nreplica, &nset_t, &n_t, &dt_t, &remd.time);\n    printf(\"Read %d sets of %d points in %s, dt = %g\\n\\n\", nset_t, n_t, tfile, dt_t);\n    sfree(remd.time);\n\n    remd.data = read_xvg_time(dfile, bHaveT,\n                              opt2parg_bSet(\"-b\", NPA, pa), tb,\n                              opt2parg_bSet(\"-e\", NPA, pa), te,\n                              nreplica, &nset_d, &n_d, &dt_d, &remd.time);\n    printf(\"Read %d sets of %d points in %s, dt = %g\\n\\n\", nset_d, n_d, dfile, dt_d);\n\n    if ((nset_t != nset_d) || (n_t != n_d) || (dt_t != dt_d))\n    {\n        gmx_fatal(FARGS, \"Files %s and %s are inconsistent. Check log file\",\n                  tfile, dfile);\n    }\n\n    if (dfile2)\n    {\n        remd.data2 = read_xvg_time(dfile2, bHaveT,\n                                   opt2parg_bSet(\"-b\", NPA, pa), tb,\n                                   opt2parg_bSet(\"-e\", NPA, pa), te,\n                                   nreplica, &nset_d2, &n_d2, &dt_d2, &remd.time);\n        printf(\"Read %d sets of %d points in %s, dt = %g\\n\\n\",\n               nset_d2, n_d2, dfile2, dt_d2);\n        if ((nset_d2 != nset_d) || (n_d != n_d2) || (dt_d != dt_d2))\n        {\n            gmx_fatal(FARGS, \"Files %s and %s are inconsistent. Check log file\",\n                      dfile, dfile2);\n        }\n    }\n    else\n    {\n        remd.data2 = NULL;\n    }\n\n    remd.nreplica  = nset_d;\n    remd.nframe    = n_d;\n    remd.dt        = 1;\n    preprocess_remd(fp, &remd, cutoff, tref, ucut, bBack, Euf, Efu, Ei, t0, t1,\n                    bSum, bDiscrete, nmult);\n\n    optimize_remd_parameters(fp, &remd, maxiter, tol);\n\n    dump_remd_parameters(fp, &remd, opt2fn(\"-o\", NFILE, fnm),\n                         opt2fn_null(\"-o2\", NFILE, fnm),\n                         opt2fn_null(\"-o3\", NFILE, fnm),\n                         opt2fn_null(\"-ee\", NFILE, fnm),\n                         opt2fn(\"-m\", NFILE, fnm), skip, tref, oenv);\n\n    if (bSplit)\n    {\n        printf(\"Splitting set of replicas in two halves\\n\");\n        for (i = 0; (i < remd.nreplica); i++)\n        {\n            remd.bMask[i] = FALSE;\n        }\n        remd.nmask = 0;\n        for (i = 0; (i < remd.nreplica); i += 2)\n        {\n            remd.bMask[i] = TRUE;\n            remd.nmask++;\n        }\n        sum_ft(&remd);\n        optimize_remd_parameters(fp, &remd, maxiter, tol);\n        dump_remd_parameters(fp, &remd, \"test1.xvg\", NULL, NULL, NULL, NULL, skip, tref, oenv);\n\n        for (i = 0; (i < remd.nreplica); i++)\n        {\n            remd.bMask[i] = !remd.bMask[i];\n        }\n        remd.nmask = remd.nreplica - remd.nmask;\n\n        sum_ft(&remd);\n        optimize_remd_parameters(fp, &remd, maxiter, tol);\n        dump_remd_parameters(fp, &remd, \"test2.xvg\", NULL, NULL, NULL, NULL, skip, tref, oenv);\n\n        for (i = 0; (i < remd.nreplica); i++)\n        {\n            remd.bMask[i] = FALSE;\n        }\n        remd.nmask = 0;\n        for (i = 0; (i < remd.nreplica/2); i++)\n        {\n            remd.bMask[i] = TRUE;\n            remd.nmask++;\n        }\n        sum_ft(&remd);\n        optimize_remd_parameters(fp, &remd, maxiter, tol);\n        dump_remd_parameters(fp, &remd, \"test1.xvg\", NULL, NULL, NULL, NULL, skip, tref, oenv);\n\n        for (i = 0; (i < remd.nreplica); i++)\n        {\n            remd.bMask[i] = FALSE;\n        }\n        remd.nmask = 0;\n        for (i = remd.nreplica/2; (i < remd.nreplica); i++)\n        {\n            remd.bMask[i] = TRUE;\n            remd.nmask++;\n        }\n        sum_ft(&remd);\n        optimize_remd_parameters(fp, &remd, maxiter, tol);\n        dump_remd_parameters(fp, &remd, \"test1.xvg\", NULL, NULL, NULL, NULL, skip, tref, oenv);\n    }\n    ffclose(fp);\n\n    view_all(oenv, NFILE, fnm);\n\n    thanx(stderr);\n#else\n    fprintf(stderr, \"This program should be compiled with the GNU scientific library. Please install the library and reinstall GROMACS.\\n\");\n#endif /*HAVE_LIBGSL*/\n\n    return 0;\n}\n", "meta": {"hexsha": "dce1cb7bec0068f6672b7089803cda297135c232", "size": 34615, "ext": "c", "lang": "C", "max_stars_repo_path": "gromacs-4.6.5/src/tools/gmx_kinetics.c", "max_stars_repo_name": "farajilab/gifs_release", "max_stars_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-03-04T18:56:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:49:22.000Z", "max_issues_repo_path": "gromacs-4.6.5/src/tools/gmx_kinetics.c", "max_issues_repo_name": "farajilab/gifs_release", "max_issues_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gromacs-4.6.5/src/tools/gmx_kinetics.c", "max_forks_repo_name": "farajilab/gifs_release", "max_forks_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-08T00:11:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T00:11:00.000Z", "avg_line_length": 31.9621421976, "max_line_length": 151, "alphanum_fraction": 0.4635273725, "num_tokens": 10576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2509127980882971, "lm_q2_score": 0.017442487864607472, "lm_q1q2_score": 0.0043765434357298265}}
{"text": "/*\n * Copyright (C) 2017 Jelmer Ypma. All Rights Reserved.\n * This code is published under the L-GPL.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU Lesser General Public License as published\n * by the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n *\n * File:   nloptrAPI.h\n * Author: Jelmer Ypma\n * Date:   3 October 2017\n *\n * This file provides an API for calling internal NLopt code from C within\n * R packages. The C functions that are registered in init_nloptr.c can be\n * accessed by external R packages.\n *\n * 03/10/2017: Initial version exposing nlopt_version.\n */\n\n#ifndef __NLOPTRAPI_H__\n#define __NLOPTRAPI_H__\n\n#include <R_ext/Rdynload.h>\n#include <R.h>\n#include <Rinternals.h>\n\n#include <nlopt.h>\n\n/*\n * C functions can be exposed using the following template:\n *\n * RET_TYPE FUNCNAME(ARGTYPE_1 ARGNAME 1, ARGTYPE_2 ARGNAME_2)\n * {\n *     static RET_TYPE(*fun)(ARGTYPE_1, ARGTYPE_2) = NULL;\n *     if (fun == NULL) fun = (RET_TYPE(*)(ARGTYPE_1, ARGTYPE_2)) R_GetCCallable(\"nloptr\",\"FUNCNAME\");\n *     return fun(ARGNAME_1, ARGNAME_2);\n * }\n *\n */\n\ninline NLOPT_EXTERN(const char *) nlopt_algorithm_name(nlopt_algorithm a)\n{\n    static const char *(*fun)(nlopt_algorithm) = NULL;\n    if (fun == NULL) fun = (const char *(*)(nlopt_algorithm)) R_GetCCallable(\"nloptr\",\"nlopt_algorithm_name\");\n    return fun(a);\n}\n\ninline NLOPT_EXTERN(void) nlopt_srand(unsigned long seed)\n{\n    static void(*fun)(unsigned long) = NULL;\n    if (fun == NULL) fun = (void(*)(unsigned long)) R_GetCCallable(\"nloptr\",\"nlopt_srand\");\n    return fun(seed);\n}\n\ninline NLOPT_EXTERN(void) nlopt_srand_time(void)\n{\n    static void(*fun)(void) = NULL;\n    if (fun == NULL) fun = (void(*)(void)) R_GetCCallable(\"nloptr\",\"nlopt_srand_time\");\n    return fun();\n}\n\ninline NLOPT_EXTERN(void) nlopt_version(int *major, int *minor, int *bugfix)\n{\n    static void(*fun)(int *, int *, int *) = NULL;\n    if (fun == NULL) fun = (void(*)(int *, int *, int *)) R_GetCCallable(\"nloptr\",\"nlopt_version\");\n    return fun(major, minor, bugfix);\n}\n\ninline NLOPT_EXTERN(nlopt_opt) nlopt_create(nlopt_algorithm algorithm, unsigned n)\n{\n    static nlopt_opt(*fun)(nlopt_algorithm, unsigned) = NULL;\n    if (fun == NULL) fun = (nlopt_opt(*)(nlopt_algorithm, unsigned)) R_GetCCallable(\"nloptr\",\"nlopt_create\");\n    return fun(algorithm, n);\n}\n\ninline NLOPT_EXTERN(void) nlopt_destroy(nlopt_opt opt)\n{\n    static void(*fun)(nlopt_opt) = NULL;\n    if (fun == NULL) fun = (void(*)(nlopt_opt)) R_GetCCallable(\"nloptr\",\"nlopt_destroy\");\n    return fun(opt);\n}\n\ninline NLOPT_EXTERN(nlopt_opt) nlopt_copy(const nlopt_opt opt)\n{\n    static nlopt_opt(*fun)(const nlopt_opt) = NULL;\n    if (fun == NULL) fun = (nlopt_opt(*)(const nlopt_opt)) R_GetCCallable(\"nloptr\",\"nlopt_copy\");\n    return fun(opt);\n}\n\ninline NLOPT_EXTERN(nlopt_result) nlopt_optimize(nlopt_opt opt, double *x, double *opt_f)\n{\n    static nlopt_result(*fun)(nlopt_opt, double *, double *) = NULL;\n    if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, double *, double *)) R_GetCCallable(\"nloptr\",\"nlopt_optimize\");\n    return fun(opt, x, opt_f);\n}\n\ninline NLOPT_EXTERN(nlopt_result) nlopt_set_min_objective(nlopt_opt opt, nlopt_func f, void *f_data)\n{\n    static nlopt_result(*fun)(nlopt_opt, nlopt_func, void *) = NULL;\n    if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, nlopt_func, void *)) R_GetCCallable(\"nloptr\",\"nlopt_set_min_objective\");\n    return fun(opt, f, f_data);\n}\n\ninline NLOPT_EXTERN(nlopt_result) nlopt_set_max_objective(nlopt_opt opt, nlopt_func f, void *f_data)\n{\n    static nlopt_result(*fun)(nlopt_opt, nlopt_func, void *) = NULL;\n    if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, nlopt_func, void *)) R_GetCCallable(\"nloptr\",\"nlopt_set_max_objective\");\n    return fun(opt, f, f_data);\n}\n\ninline NLOPT_EXTERN(nlopt_result) nlopt_set_precond_min_objective(nlopt_opt opt, nlopt_func f, nlopt_precond pre, void *f_data)\n{\n    static nlopt_result(*fun)(nlopt_opt, nlopt_func, nlopt_precond, void *) = NULL;\n    if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, nlopt_func, nlopt_precond, void *)) R_GetCCallable(\"nloptr\",\"nlopt_set_precond_min_objective\");\n    return fun(opt, f, pre, f_data);\n}\n\ninline NLOPT_EXTERN(nlopt_result) nlopt_set_precond_max_objective(nlopt_opt opt, nlopt_func f, nlopt_precond pre, void *f_data)\n{\n    static nlopt_result(*fun)(nlopt_opt, nlopt_func, nlopt_precond, void *) = NULL;\n    if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, nlopt_func, nlopt_precond, void *)) R_GetCCallable(\"nloptr\",\"nlopt_set_precond_max_objective\");\n    return fun(opt, f, pre, f_data);\n}\n\ninline NLOPT_EXTERN(nlopt_algorithm) nlopt_get_algorithm(const nlopt_opt opt)\n{\n    static nlopt_algorithm(*fun)(const nlopt_opt) = NULL;\n    if (fun == NULL) fun = (nlopt_algorithm(*)(const nlopt_opt)) R_GetCCallable(\"nloptr\",\"nlopt_get_algorithm\");\n    return fun(opt);\n}\n\ninline NLOPT_EXTERN(unsigned) nlopt_get_dimension(const nlopt_opt opt)\n{\n    static unsigned(*fun)(const nlopt_opt) = NULL;\n    if (fun == NULL) fun = (unsigned(*)(const nlopt_opt)) R_GetCCallable(\"nloptr\",\"nlopt_get_dimension\");\n    return fun(opt);\n}\n\n/* constraints: */\n\ninline NLOPT_EXTERN(nlopt_result) nlopt_set_lower_bounds(nlopt_opt opt, const double *lb)\n{\n    static nlopt_result(*fun)(nlopt_opt, const double *) = NULL;\n    if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, const double *)) R_GetCCallable(\"nloptr\",\"nlopt_set_lower_bounds\");\n    return fun(opt, lb);\n}\n\ninline NLOPT_EXTERN(nlopt_result) nlopt_set_lower_bounds1(nlopt_opt opt, double lb)\n{\n    static nlopt_result(*fun)(nlopt_opt, double) = NULL;\n    if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, double)) R_GetCCallable(\"nloptr\",\"nlopt_set_lower_bounds1\");\n    return fun(opt, lb);\n}\n\ninline NLOPT_EXTERN(nlopt_result) nlopt_get_lower_bounds(const nlopt_opt opt, double *lb)\n{\n    static nlopt_result(*fun)(const nlopt_opt, double *) = NULL;\n    if (fun == NULL) fun = (nlopt_result(*)(const nlopt_opt, double *)) R_GetCCallable(\"nloptr\",\"nlopt_get_lower_bounds\");\n    return fun(opt, lb);\n}\n\ninline NLOPT_EXTERN(nlopt_result) nlopt_set_upper_bounds(nlopt_opt opt, const double *ub)\n{\n    static nlopt_result(*fun)(nlopt_opt, const double *) = NULL;\n    if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, const double *)) R_GetCCallable(\"nloptr\",\"nlopt_set_upper_bounds\");\n    return fun(opt, ub);\n}\n\ninline NLOPT_EXTERN(nlopt_result) nlopt_set_upper_bounds1(nlopt_opt opt, double ub)\n{\n    static nlopt_result(*fun)(nlopt_opt, double) = NULL;\n    if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, double)) R_GetCCallable(\"nloptr\",\"nlopt_set_upper_bounds1\");\n    return fun(opt, ub);\n}\n\ninline NLOPT_EXTERN(nlopt_result) nlopt_get_upper_bounds(const nlopt_opt opt, double *ub)\n{\n    static nlopt_result(*fun)(const nlopt_opt, double *) = NULL;\n    if (fun == NULL) fun = (nlopt_result(*)(const nlopt_opt, double *)) R_GetCCallable(\"nloptr\",\"nlopt_get_upper_bounds\");\n    return fun(opt, ub);\n}\n\ninline NLOPT_EXTERN(nlopt_result) nlopt_remove_inequality_constraints(nlopt_opt opt)\n{\n    static nlopt_result(*fun)(nlopt_opt) = NULL;\n    if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt)) R_GetCCallable(\"nloptr\",\"nlopt_remove_inequality_constraints\");\n    return fun(opt);\n}\n\ninline NLOPT_EXTERN(nlopt_result) nlopt_add_inequality_constraint(nlopt_opt opt,\n             nlopt_func fc,\n             void *fc_data,\n             double tol)\n{\n    static nlopt_result(*fun)(nlopt_opt, nlopt_func, void *, double) = NULL;\n    if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, nlopt_func, void *, double)) R_GetCCallable(\"nloptr\",\"nlopt_add_inequality_constraint\");\n    return fun(opt, fc, fc_data, tol);\n}\n\ninline NLOPT_EXTERN(nlopt_result) nlopt_add_precond_inequality_constraint(\n        nlopt_opt opt, nlopt_func fc, nlopt_precond pre, void *fc_data,\n        double tol)\n{\n    static nlopt_result(*fun)(nlopt_opt, nlopt_func, nlopt_precond, void *, double) = NULL;\n    if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, nlopt_func, nlopt_precond, void *, double)) R_GetCCallable(\"nloptr\",\"nlopt_add_precond_inequality_constraint\");\n    return fun(opt, fc, pre, fc_data, tol);\n}\n\ninline NLOPT_EXTERN(nlopt_result) nlopt_add_inequality_mconstraint(nlopt_opt opt,\n             unsigned m,\n             nlopt_mfunc fc,\n             void *fc_data,\n             const double *tol)\n{\n    static nlopt_result(*fun)(nlopt_opt, unsigned, nlopt_mfunc, void *, const double *) = NULL;\n    if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, unsigned, nlopt_mfunc, void *, const double *)) R_GetCCallable(\"nloptr\",\"nlopt_add_inequality_mconstraint\");\n    return fun(opt, m, fc, fc_data, tol);\n}\n\ninline NLOPT_EXTERN(nlopt_result) nlopt_remove_equality_constraints(nlopt_opt opt)\n{\n    static nlopt_result(*fun)(nlopt_opt) = NULL;\n    if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt)) R_GetCCallable(\"nloptr\",\"nlopt_remove_equality_constraints\");\n    return fun(opt);\n}\n\ninline NLOPT_EXTERN(nlopt_result) nlopt_add_equality_constraint(nlopt_opt opt,\n             nlopt_func h,\n             void *h_data,\n             double tol)\n{\n    static nlopt_result(*fun)(nlopt_opt, nlopt_func, void *, double) = NULL;\n    if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, nlopt_func, void *, double)) R_GetCCallable(\"nloptr\",\"nlopt_add_equality_constraint\");\n    return fun(opt, h, h_data, tol);\n}\n\ninline NLOPT_EXTERN(nlopt_result) nlopt_add_precond_equality_constraint(\n        nlopt_opt opt, nlopt_func h, nlopt_precond pre, void *h_data,\n        double tol)\n{\n    static nlopt_result(*fun)(nlopt_opt, nlopt_func, nlopt_precond, void *, double) = NULL;\n    if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, nlopt_func, nlopt_precond, void *, double)) R_GetCCallable(\"nloptr\",\"nlopt_add_precond_equality_constraint\");\n    return fun(opt, h, pre, h_data, tol);\n}\n\ninline NLOPT_EXTERN(nlopt_result) nlopt_add_equality_mconstraint(nlopt_opt opt,\n             unsigned m,\n             nlopt_mfunc h,\n             void *h_data,\n             const double *tol)\n{\n    static nlopt_result(*fun)(nlopt_opt, unsigned, nlopt_mfunc, void *, const double *) = NULL;\n    if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, unsigned, nlopt_mfunc, void *, const double *)) R_GetCCallable(\"nloptr\",\"nlopt_add_equality_mconstraint\");\n    return fun(opt, m, h, h_data, tol);\n}\n\n/* stopping criteria: */\n\ninline NLOPT_EXTERN(nlopt_result) nlopt_set_stopval(nlopt_opt opt, double stopval)\n{\n    static nlopt_result(*fun)(nlopt_opt, double) = NULL;\n    if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, double)) R_GetCCallable(\"nloptr\",\"nlopt_set_stopval\");\n    return fun(opt, stopval);\n}\n\ninline NLOPT_EXTERN(double) nlopt_get_stopval(const nlopt_opt opt)\n{\n    static double(*fun)(const nlopt_opt) = NULL;\n    if (fun == NULL) fun = (double(*)(const nlopt_opt)) R_GetCCallable(\"nloptr\",\"nlopt_get_stopval\");\n    return fun(opt);\n}\n\ninline NLOPT_EXTERN(nlopt_result) nlopt_set_ftol_rel(nlopt_opt opt, double tol)\n{\n    static nlopt_result(*fun)(nlopt_opt, double) = NULL;\n    if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, double)) R_GetCCallable(\"nloptr\",\"nlopt_set_ftol_rel\");\n    return fun(opt, tol);\n}\n\ninline NLOPT_EXTERN(double) nlopt_get_ftol_rel(const nlopt_opt opt)\n{\n    static double(*fun)(const nlopt_opt) = NULL;\n    if (fun == NULL) fun = (double(*)(const nlopt_opt)) R_GetCCallable(\"nloptr\",\"nlopt_get_ftol_rel\");\n    return fun(opt);\n}\n\ninline NLOPT_EXTERN(nlopt_result) nlopt_set_ftol_abs(nlopt_opt opt, double tol)\n{\n    static nlopt_result(*fun)(nlopt_opt, double) = NULL;\n    if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, double)) R_GetCCallable(\"nloptr\",\"nlopt_set_ftol_abs\");\n    return fun(opt, tol);\n}\n\ninline NLOPT_EXTERN(double) nlopt_get_ftol_abs(const nlopt_opt opt)\n{\n    static double(*fun)(const nlopt_opt) = NULL;\n    if (fun == NULL) fun = (double(*)(const nlopt_opt)) R_GetCCallable(\"nloptr\",\"nlopt_get_ftol_abs\");\n    return fun(opt);\n}\n\ninline NLOPT_EXTERN(nlopt_result) nlopt_set_xtol_rel(nlopt_opt opt, double tol)\n{\n    static nlopt_result(*fun)(nlopt_opt, double) = NULL;\n    if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, double)) R_GetCCallable(\"nloptr\",\"nlopt_set_xtol_rel\");\n    return fun(opt, tol);\n}\n\ninline NLOPT_EXTERN(double) nlopt_get_xtol_rel(const nlopt_opt opt)\n{\n    static double(*fun)(const nlopt_opt) = NULL;\n    if (fun == NULL) fun = (double(*)(const nlopt_opt)) R_GetCCallable(\"nloptr\",\"nlopt_get_xtol_rel\");\n    return fun(opt);\n}\n\ninline NLOPT_EXTERN(nlopt_result) nlopt_set_xtol_abs1(nlopt_opt opt, double tol)\n{\n    static nlopt_result(*fun)(nlopt_opt, double) = NULL;\n    if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, double)) R_GetCCallable(\"nloptr\",\"nlopt_set_xtol_abs1\");\n    return fun(opt, tol);\n}\n\ninline NLOPT_EXTERN(nlopt_result) nlopt_set_xtol_abs(nlopt_opt opt, const double *tol)\n{\n    static nlopt_result(*fun)(nlopt_opt, const double *) = NULL;\n    if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, const double *)) R_GetCCallable(\"nloptr\",\"nlopt_set_xtol_abs\");\n    return fun(opt, tol);\n}\n\ninline NLOPT_EXTERN(nlopt_result) nlopt_get_xtol_abs(const nlopt_opt opt, double *tol)\n{\n    static nlopt_result(*fun)(nlopt_opt, double *) = NULL;\n    if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, double *)) R_GetCCallable(\"nloptr\",\"nlopt_get_xtol_abs\");\n    return fun(opt, tol);\n}\n\ninline NLOPT_EXTERN(nlopt_result) nlopt_set_maxeval(nlopt_opt opt, int maxeval)\n{\n    static nlopt_result(*fun)(nlopt_opt, int) = NULL;\n    if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, int)) R_GetCCallable(\"nloptr\",\"nlopt_set_maxeval\");\n    return fun(opt, maxeval);\n}\n\ninline NLOPT_EXTERN(int) nlopt_get_maxeval(const nlopt_opt opt)\n{\n    static int(*fun)(const nlopt_opt) = NULL;\n    if (fun == NULL) fun = (int(*)(const nlopt_opt)) R_GetCCallable(\"nloptr\",\"nlopt_get_maxeval\");\n    return fun(opt);\n}\n\ninline NLOPT_EXTERN(nlopt_result) nlopt_set_maxtime(nlopt_opt opt, double maxtime)\n{\n    static nlopt_result(*fun)(nlopt_opt, double) = NULL;\n    if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, double)) R_GetCCallable(\"nloptr\",\"nlopt_set_maxtime\");\n    return fun(opt, maxtime);\n}\n\ninline NLOPT_EXTERN(double) nlopt_get_maxtime(const nlopt_opt opt)\n{\n    static double(*fun)(nlopt_opt) = NULL;\n    if (fun == NULL) fun = (double(*)(nlopt_opt)) R_GetCCallable(\"nloptr\",\"nlopt_get_maxtime\");\n    return fun(opt);\n}\n\ninline NLOPT_EXTERN(nlopt_result) nlopt_force_stop(nlopt_opt opt)\n{\n    static nlopt_result(*fun)(nlopt_opt) = NULL;\n    if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt)) R_GetCCallable(\"nloptr\",\"nlopt_force_stop\");\n    return fun(opt);\n}\n\ninline NLOPT_EXTERN(nlopt_result) nlopt_set_force_stop(nlopt_opt opt, int val)\n{\n    static nlopt_result(*fun)(nlopt_opt, int) = NULL;\n    if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, int)) R_GetCCallable(\"nloptr\",\"nlopt_set_force_stop\");\n    return fun(opt, val);\n}\n\ninline NLOPT_EXTERN(int) nlopt_get_force_stop(const nlopt_opt opt)\n{\n    static int(*fun)(const nlopt_opt) = NULL;\n    if (fun == NULL) fun = (int(*)(const nlopt_opt)) R_GetCCallable(\"nloptr\",\"nlopt_get_force_stop\");\n    return fun(opt);\n}\n\n/* more algorithm-specific parameters */\n\ninline NLOPT_EXTERN(nlopt_result) nlopt_set_local_optimizer(nlopt_opt opt, const nlopt_opt local_opt)\n{\n    static nlopt_result(*fun)(nlopt_opt, const nlopt_opt) = NULL;\n    if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, const nlopt_opt)) R_GetCCallable(\"nloptr\",\"nlopt_set_local_optimizer\");\n    return fun(opt, local_opt);\n}\n\ninline NLOPT_EXTERN(nlopt_result) nlopt_set_population(nlopt_opt opt, unsigned pop)\n{\n    static nlopt_result(*fun)(nlopt_opt, unsigned) = NULL;\n    if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, unsigned)) R_GetCCallable(\"nloptr\",\"nlopt_set_population\");\n    return fun(opt, pop);\n}\n\ninline NLOPT_EXTERN(unsigned) nlopt_get_population(const nlopt_opt opt)\n{\n    static unsigned(*fun)(const nlopt_opt) = NULL;\n    if (fun == NULL) fun = (unsigned(*)(const nlopt_opt)) R_GetCCallable(\"nloptr\",\"nlopt_get_population\");\n    return fun(opt);\n}\n\ninline NLOPT_EXTERN(nlopt_result) nlopt_set_vector_storage(nlopt_opt opt, unsigned dim)\n{\n    static nlopt_result(*fun)(nlopt_opt, unsigned) = NULL;\n    if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, unsigned)) R_GetCCallable(\"nloptr\",\"nlopt_set_vector_storage\");\n    return fun(opt, dim);\n}\n\ninline NLOPT_EXTERN(unsigned) nlopt_get_vector_storage(const nlopt_opt opt)\n{\n    static unsigned(*fun)(const nlopt_opt) = NULL;\n    if (fun == NULL) fun = (unsigned(*)(const nlopt_opt)) R_GetCCallable(\"nloptr\",\"nlopt_get_vector_storage\");\n    return fun(opt);\n}\n\ninline NLOPT_EXTERN(nlopt_result) nlopt_set_default_initial_step(nlopt_opt opt, const double *x)\n{\n    static nlopt_result(*fun)(nlopt_opt, const double *) = NULL;\n    if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, const double *)) R_GetCCallable(\"nloptr\",\"nlopt_set_default_initial_step\");\n    return fun(opt, x);\n}\n\ninline NLOPT_EXTERN(nlopt_result) nlopt_set_initial_step(nlopt_opt opt, const double *dx)\n{\n    static nlopt_result(*fun)(nlopt_opt, const double *) = NULL;\n    if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, const double *)) R_GetCCallable(\"nloptr\",\"nlopt_set_initial_step\");\n    return fun(opt, dx);\n}\n\ninline NLOPT_EXTERN(nlopt_result) nlopt_set_initial_step1(nlopt_opt opt, double dx)\n{\n    static nlopt_result(*fun)(nlopt_opt, double) = NULL;\n    if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, double)) R_GetCCallable(\"nloptr\",\"nlopt_set_initial_step1\");\n    return fun(opt, dx);\n}\n\ninline NLOPT_EXTERN(nlopt_result) nlopt_get_initial_step(const nlopt_opt opt, const double *x, double *dx)\n{\n    static nlopt_result(*fun)(const nlopt_opt, const double *, double *) = NULL;\n    if (fun == NULL) fun = (nlopt_result(*)(const nlopt_opt, const double *, double *)) R_GetCCallable(\"nloptr\",\"nlopt_get_initial_step\");\n    return fun(opt, x, dx);\n}\n\n#endif /* __NLOPTRAPI_H__ */\n", "meta": {"hexsha": "74585eac0b9d3d0c692b879fad58de26eeaa1b12", "size": 18345, "ext": "h", "lang": "C", "max_stars_repo_path": "SilveR/R/library/nloptr/include/nloptrAPI.h", "max_stars_repo_name": "robalexclark/SilveR-Dev", "max_stars_repo_head_hexsha": "263008fdb9dc3fdd22bfc6f71b7c092867631563", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SilveR/R/library/nloptr/include/nloptrAPI.h", "max_issues_repo_name": "robalexclark/SilveR-Dev", "max_issues_repo_head_hexsha": "263008fdb9dc3fdd22bfc6f71b7c092867631563", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SilveR/R/library/nloptr/include/nloptrAPI.h", "max_forks_repo_name": "robalexclark/SilveR-Dev", "max_forks_repo_head_hexsha": "263008fdb9dc3fdd22bfc6f71b7c092867631563", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.8804347826, "max_line_length": 166, "alphanum_fraction": 0.7132733715, "num_tokens": 5707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12421301159407333, "lm_q2_score": 0.03514484501123562, "lm_q1q2_score": 0.00436544704085252}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef treeop_00fc8cde_c6b6_464d_b51d_71eaad31b9ef_h\r\n#define treeop_00fc8cde_c6b6_464d_b51d_71eaad31b9ef_h\r\n\r\n#include <gslib/tree.h>\r\n\r\n__gslib_begin__\r\n\r\n/*\r\n * The original tree was created from top to bottom, to implement the new operation it might be needed\r\n * to create the tree from bottom to top.\r\n * These classes were designed to achieve that.\r\n * Caution:\r\n * You'd better NOT include me in headers.\r\n * You'd better use def_tr$ macros in a function scope.\r\n * with argumented def_tr$ versions, IE. like def_tr$_v1, def_tr$_v2, and so on...\r\n * the tree should NOT be a copy wrapper one.\r\n */\r\n\r\ntemplate<class _tree>\r\nclass treeop_helper\r\n{\r\npublic:\r\n    typedef _tree tree;\r\n    typedef typename _tree::value value;\r\n    typedef typename _tree::wrapper wrapper;\r\n    typedef typename _tree::alloc alloc;\r\n    typedef typename _tree::const_iterator const_iterator;\r\n    typedef typename _tree::iterator iterator;\r\n    typedef typename wrapper::children children;\r\n};\r\n\r\ntemplate<class _tree>\r\nclass treeop_set\r\n{\r\npublic:\r\n    typedef treeop_helper<_tree> helper;\r\n    typedef typename helper::tree tree;\r\n    typedef typename helper::value value;\r\n    typedef typename helper::wrapper wrapper;\r\n    typedef typename helper::alloc alloc;\r\n    typedef typename helper::const_iterator const_iterator;\r\n    typedef typename helper::iterator iterator;\r\n    typedef typename helper::children children;\r\n    typedef children opset;\r\n\r\npublic:\r\n    opset           _opset;\r\n\r\npublic:\r\n    treeop_set() {}\r\n    treeop_set(wrapper* w) { _opset.init(w); }\r\n    treeop_set(treeop_set& rhs) { _opset.swap(rhs.dump()); }\r\n    bool empty() const { return _opset.empty(); }\r\n    bool unary() const { return _opset.size() == 1; }\r\n    opset& dump() { return _opset; }\r\n    treeop_set& operator+ (treeop_set& rhs) { return connect(rhs); }\r\n    void acquire(treeop_set& ops)\r\n    {\r\n        assert(unary());\r\n        wrapper* m = _opset.front();\r\n        assert(m);\r\n        m->acquire_children(ops.dump());\r\n    }\r\n    treeop_set& sub(treeop_set& ops)\r\n    {\r\n        acquire(ops);\r\n        return *this;\r\n    }\r\n    treeop_set& connect(treeop_set& ops)\r\n    {\r\n        _opset.connect(ops.dump());\r\n        return *this;\r\n    }\r\n    wrapper* detach()\r\n    {\r\n        assert(unary());\r\n        wrapper* w = _opset.front();\r\n        _opset.reset();\r\n        return w;\r\n    }\r\n};\r\n\r\ntemplate<class _tree>\r\nclass treeop\r\n{\r\npublic:\r\n    typedef treeop_helper<_tree> helper;\r\n    typedef typename helper::tree tree;\r\n    typedef typename helper::value value;\r\n    typedef typename helper::wrapper wrapper;\r\n    typedef typename helper::alloc alloc;\r\n    typedef typename helper::const_iterator const_iterator;\r\n    typedef typename helper::iterator iterator;\r\n    typedef typename helper::children children;\r\n    typedef treeop_set<_tree> tropset;\r\n    typedef children opset;\r\n\r\npublic:\r\n    treeop(_tree& tr) { _tr = &tr; }\r\n    void create(tropset& ops) { _tr->set_root(ops.detach()); }\r\n\r\nprotected:\r\n    _tree*          _tr;\r\n};\r\n\r\n/*\r\n * Usage:\r\n * For example,\r\n * 1.if we wanted to create a tree in the following structure,\r\n *   { a = 1, b = \"hello\"; }\r\n *        { a = 2, b = \"bingo\"; }\r\n *            { a = 3, b = \"bravo\"; }\r\n *        { a = 6, b = \"amigo\"; }\r\n *   and the node was for: struct node { int a; string b; };\r\n *   We could write it like,\r\n *   typedef tree<node, _treenode_wrapper<node> > mytree;\r\n *   def_tr$(node1, mytree, ([&](){ a = 1, b = \"hello\"; }));\r\n *   def_tr$(node2, mytree, ([&](){ a = 2, b = \"bingo\"; }));\r\n *   def_tr$(node3, mytree, ([&](){ a = 3, b = \"bravo\"; }));\r\n *   def_tr$(node4, mytree, ([&](){ a = 6, b = \"amigo\"; }));\r\n *   tr$(node1).sub(\r\n *      tr$(node2).sub(\r\n *          tr$(node3)\r\n *          )\r\n *      + tr$(node4)\r\n *      );\r\n * 2.if your compiler doesn't support c++0x style of lambda,\r\n *   you may modify the def_tr$ micro a little bit, like assignments;\r\n *   then you could temporally write it like:\r\n *   typedef tree<node, _treenode_wrapper<node> > mytree;\r\n *   def_tr$(node1, mytree, (a = 1, b = \"hello\";));\r\n *   it works, just maybe unsafe.\r\n */\r\n\r\n#define def_tr$(name, treeop, prototype, assignments) \\\r\nstruct tag##name \\\r\n{ \\\r\n    typedef treeop::wrapper wrapper; \\\r\n    typedef treeop::value value; \\\r\n    typedef treeop::alloc alloc; \\\r\n    typedef treeop::tropset tropset; \\\r\n    struct constructor: \\\r\n        public prototype \\\r\n    { \\\r\n        constructor() { (assignments)(); } \\\r\n    }; \\\r\n    tropset create() \\\r\n    { \\\r\n        wrapper* w = alloc::born(); \\\r\n        w->born<constructor>(); \\\r\n        return tropset(w); \\\r\n    } \\\r\n} name;\r\n\r\n#define def_tr$_v1(name, treeop, prototype, arg1, assignments) \\\r\nstruct tag##name \\\r\n{ \\\r\n    typedef treeop::wrapper wrapper; \\\r\n    typedef treeop::value value; \\\r\n    typedef treeop::alloc alloc; \\\r\n    typedef treeop::tropset tropset; \\\r\n    typedef decltype(arg1) type1; \\\r\n    type1& ref_arg1; \\\r\n    tag##name(type1& arg1): ref_arg1(arg1) {} \\\r\n    struct constructor: \\\r\n        public prototype \\\r\n    { \\\r\n        constructor(type1& arg1) { (assignments)(arg1); } \\\r\n    }; \\\r\n    tropset create() \\\r\n    { \\\r\n        wrapper* w = alloc::born(); \\\r\n        w->born<constructor>(ref_arg1); \\\r\n        return tropset(w); \\\r\n    } \\\r\n} name(arg1);\r\n\r\n#define def_tr$_v2(name, treeop, prototype, arg1, arg2, assignments) \\\r\nstruct tag##name \\\r\n{ \\\r\n    typedef treeop::wrapper wrapper; \\\r\n    typedef treeop::value value; \\\r\n    typedef treeop::alloc alloc; \\\r\n    typedef treeop::tropset tropset; \\\r\n    typedef decltype(arg1) type1; \\\r\n    typedef decltype(arg2) type2; \\\r\n    type1& ref_arg1; \\\r\n    type2& ref_arg2; \\\r\n    tag##name(type1& arg1, type2& arg2): ref_arg1(arg1), ref_arg2(arg2) {} \\\r\n    struct constructor: \\\r\n        public prototype \\\r\n    { \\\r\n        constructor(type1& arg1, type2& arg2) { (assignments)(arg1, arg2); } \\\r\n    }; \\\r\n    tropset create() \\\r\n    { \\\r\n        wrapper* w = alloc::born(); \\\r\n        w->born<constructor>(ref_arg1, ref_arg2); \\\r\n        return tropset(w); \\\r\n    } \\\r\n} name(arg1, arg2);\r\n\r\n#define def_tr$_v3(name, treeop, prototype, arg1, arg2, arg3, assignments) \\\r\nstruct tag##name \\\r\n{ \\\r\n    typedef treeop::wrapper wrapper; \\\r\n    typedef treeop::value value; \\\r\n    typedef treeop::alloc alloc; \\\r\n    typedef treeop::tropset tropset; \\\r\n    typedef decltype(arg1) type1; \\\r\n    typedef decltype(arg2) type2; \\\r\n    typedef decltype(arg3) type3; \\\r\n    type1& ref_arg1; \\\r\n    type2& ref_arg2; \\\r\n    type3& ref_arg3; \\\r\n    tag##name(type1& arg1, type2& arg2, type3& arg3): ref_arg1(arg1), ref_arg2(arg2), ref_arg3(arg3) {} \\\r\n    struct constructor: \\\r\n        public prototype \\\r\n    { \\\r\n        constructor(type1& arg1, type2& arg2, type3& arg3) { (assignments)(arg1, arg2, arg3); } \\\r\n    }; \\\r\n    tropset create() \\\r\n    { \\\r\n        wrapper* w = alloc::born(); \\\r\n        w->born<constructor>(ref_arg1, ref_arg2, ref_arg3); \\\r\n        return tropset(w); \\\r\n    } \\\r\n} name(arg1, arg2, arg3);\r\n\r\n#define tr$(name) (name.create())\r\n\r\n__gslib_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "6fb0709b80a56944efd226af8299f1354c5fddb8", "size": 8325, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gslib/treeop.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/gslib/treeop.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gslib/treeop.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 31.7748091603, "max_line_length": 106, "alphanum_fraction": 0.6193393393, "num_tokens": 2213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12592277795604903, "lm_q2_score": 0.03461883746966928, "lm_q1q2_score": 0.004359300183789715}}
{"text": "//        Copyright The Authors 2018.\n//    Distributed under the 3-Clause BSD License.\n//    (See accompanying file LICENSE or copy at\n//   https://opensource.org/licenses/BSD-3-Clause)\n\n#pragma once\n\n#include <cstdint>      // for std::uint8_t etc.\n#include <type_traits>  // for std::underlying_type_t<>\n\n#include <gsl/gsl>  // for gsl::span\n\n#include <p2p/kademlia/buffer.h>\n#include <p2p/kademlia/node.h>\n\nnamespace blocxxi {\nnamespace p2p {\nnamespace kademlia {\n\n/*!\n * @brief Represents a message header block.\n *\n * In its serialized form, every message is composed of a header and a body. The\n * header contains the protocol version, the message body type, the ID (hash\n * 160) of the source node and a random token (hash 160) used to correlate\n * requests and responses.\n *\n * A serialized header uses the following layout:\n * ```\n *      <-----------------><-------...-------><-------...------->\n *            1 byte             20 bytes           20 bytes\n *        4 bits | 4 bits      source id          random token\n *        version  type\n *\n * ```\n */\nstruct Header final {\n  /// Protocol version\n  enum class Version : std::uint8_t {\n    V1 = 1,\n  } version_{Version::V1};\n\n  /// Message body type\n  enum class MessageType : std::uint8_t {\n    PING_REQUEST,\n    PING_RESPONSE,\n    STORE_REQUEST,\n    FIND_NODE_REQUEST,\n    FIND_NODE_RESPONSE,\n    FIND_VALUE_REQUEST,\n    FIND_VALUE_RESPONSE,\n  } type_{MessageType::PING_REQUEST};\n\n  /// ID of the source node (Hash 160)\n  Node::IdType source_id_;\n  /// A random token (Hash 160)\n  blocxxi::crypto::Hash160 random_token_;\n};\n\n/*!\n * @brief Generalized function that can take any scoped enumerator and return\n * a compile time constant of the underlying type.\n *\n * Used specifically for the serialization and deserialization of headers. For\n * more details on the rational see Scott Meyers, Effective Modern C++ Item 10.\n *\n * @tparam TEnum the scoped enum class type.\n * @param [in] e_value any value of the scoped enum class.\n * @return a compile time constant of the underlying type corresponding to\n * e_value.\n */\ntemplate <typename TEnum>\nconstexpr std::underlying_type_t<TEnum> ToUnderlying(TEnum e_value) noexcept {\n  return static_cast<std::underlying_type_t<TEnum>>(e_value);\n}\n\n/*!\n * @brief A template trait class used to carry extra information about the\n * messages types in use.\n *\n * The traits class T<M> lets us record such extra information about a message\n * class M, without requiring any change at all to M. Such extra information is\n * used to generically serialize and deserialize messages.\n *\n * @tparam TMessageBody the type of the message body described by this traits\n * class.\n */\ntemplate <typename TMessageBody>\nstruct MessageTraits;\n\n/*!\n * @brief Serialize the header into the given buffer, which is expected to be\n * able to accomodate the header binary size (41 bytes) or expand as needed.\n *\n * @param [in] header header object to be serialized.\n * @param [out] buffer destination buffer for the header serialized binary form.\n */\nvoid Serialize(Header const &header, Buffer &buffer);\n\n/*!\n * @brief Deserialize the contents of the buffer into a Header object.\n *\n * @param [in] buffer a span over a range of bytes (std::uint8_t) representing\n * the header binary data.\n * @param [out] header the deserialized resulting header object.\n * @return an error code indicating success or failure of the deserialization.\n */\nstd::size_t Deserialize(BufferReader const &buffer, Header &header);\n\n/// FIND_NODE request message body.\nstruct FindNodeRequestBody final {\n  /// The hash 160 id of the node to find.\n  Node::IdType node_id_;\n};\n\n/// Message traits template specialization for the FIND_NODE request message.\ntemplate <>\nstruct MessageTraits<FindNodeRequestBody> {\n  static constexpr Header::MessageType TYPE_ID =\n      Header::MessageType::FIND_NODE_REQUEST;\n};\n\n/*!\n * @brief Serialize a FIND_NODE request body into the given buffer.\n *\n * @param [in] body the request body.\n * @param [out] buffer the destination buffer.\n */\nvoid Serialize(FindNodeRequestBody const &body, Buffer &buffer);\n\n/*!\n * @brief Deserialize a FIND_NODE request body from the given buffer.\n *\n * @param [in] buffer the input buffer.\n * @param [out] body the resulting request body.\n * @return the number of consumed bytes from the input buffer. Subsequent\n * deserialization from the buffer need to start after the consumed bytes.\n */\nstd::size_t Deserialize(BufferReader const &buffer, FindNodeRequestBody &body);\n\n/// FIND_NODE response message body.\nstruct FindNodeResponseBody final {\n  /// The list of nodes in the response.\n  std::vector<Node> peers_;\n};\n\n/// Message traits template specialization for the FIND_NODE response message.\ntemplate <>\nstruct MessageTraits<FindNodeResponseBody> {\n  static constexpr Header::MessageType TYPE_ID =\n      Header::MessageType::FIND_NODE_RESPONSE;\n};\n\n/*!\n * @brief Serialize a FIND_NODE response body into the given buffer.\n *\n * @param [in] body the response body.\n * @param [out] buffer the destination buffer.\n */\nvoid Serialize(FindNodeResponseBody const &body, Buffer &buffer);\n\n/*!\n * @brief Deserialize a FIND_NODE response body from the given buffer.\n *\n * @param [in] buffer the input buffer.\n * @param [out] body the resulting response body.\n * @return the number of consumed bytes from the input buffer. Subsequent\n * deserialization from the buffer need to start after the consumed bytes.\n */\nstd::size_t Deserialize(BufferReader const &buffer, FindNodeResponseBody &body);\n\n/// FIND_VALUE request message body.\nstruct FindValueRequestBody final {\n  /// The hash 160 key of the value to find.\n  blocxxi::crypto::Hash160 value_key_;\n};\n\n/// Message traits template specialization for the FIND_VALUE request message.\ntemplate <>\nstruct MessageTraits<FindValueRequestBody> {\n  static constexpr Header::MessageType TYPE_ID =\n      Header::MessageType::FIND_VALUE_REQUEST;\n};\n\n/*!\n * @brief Serialize a FIND_VALUE request body into the given buffer.\n *\n * @param [in] body the request body.\n * @param [out] buffer the destination buffer.\n */\nvoid Serialize(FindValueRequestBody const &body, Buffer &buffer);\n\n/*!\n * @brief Deserialize a FIND_VALUE request body from the given buffer.\n *\n * @param [in] buffer the input buffer.\n * @param [out] body the resulting request body.\n * @return the number of consumed bytes from the input buffer. Subsequent\n * deserialization from the buffer need to start after the consumed bytes.\n */\nstd::size_t Deserialize(BufferReader const &buffer, FindValueRequestBody &body);\n\n/// FIND_VALUE response message body.\nstruct FindValueResponseBody final {\n  /// The value data  as a vector of bytes.\n  std::vector<std::uint8_t> data_;\n};\n\n/// Message traits template specialization for the FIND_VALUE response message.\ntemplate <>\nstruct MessageTraits<FindValueResponseBody> {\n  static constexpr Header::MessageType TYPE_ID =\n      Header::MessageType::FIND_VALUE_RESPONSE;\n};\n\n/*!\n * @brief Serialize a FIND_VALUE response body into the given buffer.\n *\n * @param [in] body the response body.\n * @param [out] buffer the destination buffer.\n */\nvoid Serialize(FindValueResponseBody const &body, Buffer &buffer);\n\n/*!\n * @brief Deserialize a FIND_VALUE response body from the given buffer.\n *\n * @param [in] buffer the input buffer.\n * @param [out] body the resulting response body.\n * @return the number of consumed bytes from the input buffer. Subsequent\n * deserialization from the buffer need to start after the consumed bytes.\n */\nstd::size_t Deserialize(BufferReader const &buffer,\n                        FindValueResponseBody &body);\n\n/// STORE_VALUE request message body.\nstruct StoreValueRequestBody final {\n  /// The hash 160 of the data key.\n  blocxxi::crypto::Hash160 data_key_;\n  /// The data value as a vector of bytes.\n  std::vector<std::uint8_t> data_value_;\n};\n\n/// Message traits template specialization for the STORE_VALUE request message.\ntemplate <>\nstruct MessageTraits<StoreValueRequestBody> {\n  static constexpr Header::MessageType TYPE_ID =\n      Header::MessageType::STORE_REQUEST;\n};\n\n/*!\n * @brief Serialize a STORE_VALUE request body into the given buffer.\n *\n * @param [in] body the request body.\n * @param [out] buffer the destination buffer.\n */\nvoid Serialize(StoreValueRequestBody const &body, Buffer &buffer);\n\n/*!\n * @brief Deserialize a STORE_VALUE request body from the given buffer.\n *\n * @param [in] buffer the input buffer.\n * @param [out] body the resulting request body.\n * @return the number of consumed bytes from the input buffer. Subsequent\n * deserialization from the buffer need to start after the consumed bytes.\n */\nstd::size_t Deserialize(BufferReader const &buffer,\n                        StoreValueRequestBody &body);\n\n}  // namespace kademlia\n}  // namespace p2p\n}  // namespace blocxxi\n", "meta": {"hexsha": "417dcb82aaf2aab11c2c506ff7b7d72e687a32ec", "size": 8808, "ext": "h", "lang": "C", "max_stars_repo_path": "p2p/include/p2p/kademlia/message.h", "max_stars_repo_name": "canhld94/blocxxi", "max_stars_repo_head_hexsha": "e0e1e629334a7959c3fb9c38567f9cf28e2cf44a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2018-06-17T22:10:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T07:08:26.000Z", "max_issues_repo_path": "p2p/include/p2p/kademlia/message.h", "max_issues_repo_name": "canhld94/blocxxi", "max_issues_repo_head_hexsha": "e0e1e629334a7959c3fb9c38567f9cf28e2cf44a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-06-20T08:39:12.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-03T09:50:56.000Z", "max_forks_repo_path": "p2p/include/p2p/kademlia/message.h", "max_forks_repo_name": "canhld94/blocxxi", "max_forks_repo_head_hexsha": "e0e1e629334a7959c3fb9c38567f9cf28e2cf44a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-07-13T17:55:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-27T19:37:05.000Z", "avg_line_length": 32.3823529412, "max_line_length": 80, "alphanum_fraction": 0.723773842, "num_tokens": 1972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14414884567931802, "lm_q2_score": 0.03021458739486561, "lm_q1q2_score": 0.00435539789564675}}
{"text": "#ifndef SEARCHPATTERNHEXMATCHER_HHHHH\n#define SEARCHPATTERNHEXMATCHER_HHHHH\n\n#include <gsl/string_span>\n#include <vector>\n#include <string>\n#include <algorithm>\n\n#include \"SearchPatternBase.h\"\n\nnamespace MPSig {\n    namespace detail {\n        class SearchPatternHexMatcher final : public SearchPatternBase {\n        private:\n            std::vector<std::pair<char, bool>> m_compiledPattern;\n        public:\n            SearchPatternHexMatcher(gsl::cstring_span<-1> hexPattern);\n            \n            virtual SearchPatternBase::ExecFirstResult<gsl_span_cit_t> ExecFirst(const MPSig::SigScannerMemoryData& data, gsl_span_cit_t begin, gsl_span_cit_t end) const override;\n            virtual SearchPatternBase::ExecFirstResult<gsl_span_crit_t> ExecFirst(const MPSig::SigScannerMemoryData& data, gsl_span_crit_t begin, gsl_span_crit_t end) const override;\n            \n            virtual SearchPatternBase::ExecFirstResult<gsl_span_cit_t> ExecDepend(const MPSig::SigScannerMemoryData& data, gsl_span_cit_t begin, gsl_span_cit_t end) const override;\n            virtual SearchPatternBase::ExecFirstResult<gsl_span_crit_t> ExecDepend(const MPSig::SigScannerMemoryData& data, gsl_span_crit_t begin, gsl_span_crit_t end) const override;\n\n            virtual std::unique_ptr<SearchPatternBase> Clone() const override;\n        };\n\n    }\n}\n\n#endif\n", "meta": {"hexsha": "22ce6c5c65606e8e62c6243854a6b23c55cb8a06", "size": 1340, "ext": "h", "lang": "C", "max_stars_repo_path": "src/search/detail/SearchPatternHexMatcher.h", "max_stars_repo_name": "KevinW1998/MultipassSigScanner", "max_stars_repo_head_hexsha": "13f290ec593ddbeed3c59c7fba642c1704bfd529", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/search/detail/SearchPatternHexMatcher.h", "max_issues_repo_name": "KevinW1998/MultipassSigScanner", "max_issues_repo_head_hexsha": "13f290ec593ddbeed3c59c7fba642c1704bfd529", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/search/detail/SearchPatternHexMatcher.h", "max_forks_repo_name": "KevinW1998/MultipassSigScanner", "max_forks_repo_head_hexsha": "13f290ec593ddbeed3c59c7fba642c1704bfd529", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.875, "max_line_length": 183, "alphanum_fraction": 0.7417910448, "num_tokens": 314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1460872396128689, "lm_q2_score": 0.02976009545188317, "lm_q1q2_score": 0.004347570195181107}}
{"text": "/*\n *  Copyright (C) 2021 FISCO BCOS.\n *  SPDX-License-Identifier: Apache-2.0\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n * @brief scale codec\n * @file Scale.h\n */\n#pragma once\n#include \"Common.h\"\n#include \"ScaleDecoderStream.h\"\n#include \"ScaleEncoderStream.h\"\n#include <boost/system/system_error.hpp>\n#include <boost/throw_exception.hpp>\n#include <gsl/span>\n#include <vector>\n\nnamespace bcos\n{\nnamespace codec\n{\nnamespace scale\n{\n/**\n * @brief convenience function for encoding primitives data to stream\n * @tparam Args primitive types to be encoded\n * @param args data to encode\n * @return encoded data\n */\ntemplate <typename... Args>\nvoid encode(std::shared_ptr<bytes> _encodeData, Args&&... _args)\n{\n    ScaleEncoderStream s;\n    (s << ... << std::forward<Args>(_args));\n    *_encodeData = s.data();\n}\n\ntemplate <typename... Args>\nbytes encode(Args&&... _args)\n{\n    ScaleEncoderStream s;\n    (s << ... << std::forward<Args>(_args));\n    return s.data();\n}\n\n/**\n * @brief convenience function for decoding primitives data from stream\n * @tparam T primitive type that is decoded from provided span\n * @param span of bytes with encoded data\n * @return decoded T\n */\ntemplate <class T>\nvoid decode(T& _decodedObject, gsl::span<byte const> _span)\n{\n    ScaleDecoderStream s(_span);\n    s >> _decodedObject;\n}\n\ntemplate <class T>\nT decode(gsl::span<byte const> _span)\n{\n    T t;\n    decode(t, _span);\n    return t;\n}\n}  // namespace scale\n}  // namespace codec\n}  // namespace bcos\n", "meta": {"hexsha": "7b320e3c7bb3f7e7b592cc393a420b50f24318e0", "size": 2002, "ext": "h", "lang": "C", "max_stars_repo_path": "bcos-framework/libcodec/scale/Scale.h", "max_stars_repo_name": "xueying4402/FISCO-BCOS", "max_stars_repo_head_hexsha": "737e08752e8904c7c24e3737f8f46bf5327ef792", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-06T10:46:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T10:46:12.000Z", "max_issues_repo_path": "bcos-framework/libcodec/scale/Scale.h", "max_issues_repo_name": "xueying4402/FISCO-BCOS", "max_issues_repo_head_hexsha": "737e08752e8904c7c24e3737f8f46bf5327ef792", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 267.0, "max_issues_repo_issues_event_min_datetime": "2021-03-01T02:12:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-17T08:18:34.000Z", "max_forks_repo_path": "bcos-framework/libcodec/scale/Scale.h", "max_forks_repo_name": "xueying4402/FISCO-BCOS", "max_forks_repo_head_hexsha": "737e08752e8904c7c24e3737f8f46bf5327ef792", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2021-02-22T03:47:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-06T06:41:02.000Z", "avg_line_length": 25.3417721519, "max_line_length": 76, "alphanum_fraction": 0.6988011988, "num_tokens": 499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12940272487671914, "lm_q2_score": 0.03358950456175575, "lm_q1q2_score": 0.004346573417550182}}
{"text": "// Copyright \u00a9 Matt Jones and Contributors. Licensed under the MIT Licence (MIT). See LICENCE.md in the repository root\n// for more information.\n\n#ifndef NOVELRT_INPUT_H\n#define NOVELRT_INPUT_H\n\n// Input Dependencies\n#include \"NovelRT/LoggingService.h\"\n#include \"NovelRT/Maths/Maths.h\"\n#include \"NovelRT/Timing/Timestamp.h\"\n#include <gsl/span>\n#include <map>\n#include <string>\n\n/**\n * @Brief The input plugin API.\n */\nnamespace NovelRT::Input\n{\n    enum class KeyState;\n    class IInputDevice;\n    class NovelKey;\n    struct InputAction;\n}\n\n// clang-format off\n// Input Types\n#include \"IInputDevice.h\"\n#include \"KeyState.h\"\n#include \"NovelKey.h\"\n#include \"InputAction.h\"\n// clang-format on\n\n#endif // NOVELRT_INPUT_H\n", "meta": {"hexsha": "c1c0e39b064c31ad047713fcf6015748ddbfb95b", "size": 717, "ext": "h", "lang": "C", "max_stars_repo_path": "include/NovelRT/Input/Input.h", "max_stars_repo_name": "Shidesu/NovelRT", "max_stars_repo_head_hexsha": "53e341a79db9e84b47f80e12e1d7049a6874811d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/NovelRT/Input/Input.h", "max_issues_repo_name": "Shidesu/NovelRT", "max_issues_repo_head_hexsha": "53e341a79db9e84b47f80e12e1d7049a6874811d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/NovelRT/Input/Input.h", "max_forks_repo_name": "Shidesu/NovelRT", "max_forks_repo_head_hexsha": "53e341a79db9e84b47f80e12e1d7049a6874811d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.4857142857, "max_line_length": 119, "alphanum_fraction": 0.7336122734, "num_tokens": 182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.11436851712592713, "lm_q2_score": 0.03789242391337982, "lm_q1q2_score": 0.004333700333280271}}
{"text": "/* vector/gsl_vector_char.h\r\n * \r\n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\r\n * \r\n * This program is free software; you can redistribute it and/or modify\r\n * it under the terms of the GNU General Public License as published by\r\n * the Free Software Foundation; either version 3 of the License, or (at\r\n * your option) any later version.\r\n * \r\n * This program is distributed in the hope that it will be useful, but\r\n * WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n * General Public License for more details.\r\n * \r\n * You should have received a copy of the GNU General Public License\r\n * along with this program; if not, write to the Free Software\r\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r\n */\r\n\r\n#ifndef __GSL_VECTOR_CHAR_H__\r\n#define __GSL_VECTOR_CHAR_H__\r\n\r\n#if !defined( GSL_FUN )\r\n#  if !defined( GSL_DLL )\r\n#    define GSL_FUN extern\r\n#  elif defined( BUILD_GSL_DLL )\r\n#    define GSL_FUN extern __declspec(dllexport)\r\n#  else\r\n#    define GSL_FUN extern __declspec(dllimport)\r\n#  endif\r\n#endif\r\n\r\n#include <stdlib.h>\r\n#include <gsl/gsl_types.h>\r\n#include <gsl/gsl_errno.h>\r\n#include <gsl/gsl_inline.h>\r\n#include <gsl/gsl_check_range.h>\r\n#include <gsl/gsl_block_char.h>\r\n\r\n#undef __BEGIN_DECLS\r\n#undef __END_DECLS\r\n#ifdef __cplusplus\r\n# define __BEGIN_DECLS extern \"C\" {\r\n# define __END_DECLS }\r\n#else\r\n# define __BEGIN_DECLS /* empty */\r\n# define __END_DECLS /* empty */\r\n#endif\r\n\r\n__BEGIN_DECLS\r\n\r\ntypedef struct \r\n{\r\n  size_t size;\r\n  size_t stride;\r\n  char *data;\r\n  gsl_block_char *block;\r\n  int owner;\r\n} \r\ngsl_vector_char;\r\n\r\ntypedef struct\r\n{\r\n  gsl_vector_char vector;\r\n} _gsl_vector_char_view;\r\n\r\ntypedef _gsl_vector_char_view gsl_vector_char_view;\r\n\r\ntypedef struct\r\n{\r\n  gsl_vector_char vector;\r\n} _gsl_vector_char_const_view;\r\n\r\ntypedef const _gsl_vector_char_const_view gsl_vector_char_const_view;\r\n\r\n\r\n/* Allocation */\r\n\r\nGSL_FUN gsl_vector_char *gsl_vector_char_alloc (const size_t n);\r\nGSL_FUN gsl_vector_char *gsl_vector_char_calloc (const size_t n);\r\n\r\nGSL_FUN gsl_vector_char *gsl_vector_char_alloc_from_block (gsl_block_char * b,\r\n                                                     const size_t offset, \r\n                                                     const size_t n, \r\n                                                     const size_t stride);\r\n\r\nGSL_FUN gsl_vector_char *gsl_vector_char_alloc_from_vector (gsl_vector_char * v,\r\n                                                      const size_t offset, \r\n                                                      const size_t n, \r\n                                                      const size_t stride);\r\n\r\nGSL_FUN void gsl_vector_char_free (gsl_vector_char * v);\r\n\r\n/* Views */\r\n\r\nGSL_FUN _gsl_vector_char_view \r\ngsl_vector_char_view_array (char *v, size_t n);\r\n\r\nGSL_FUN _gsl_vector_char_view \r\ngsl_vector_char_view_array_with_stride (char *base,\r\n                                         size_t stride,\r\n                                         size_t n);\r\n\r\nGSL_FUN _gsl_vector_char_const_view \r\ngsl_vector_char_const_view_array (const char *v, size_t n);\r\n\r\nGSL_FUN _gsl_vector_char_const_view \r\ngsl_vector_char_const_view_array_with_stride (const char *base,\r\n                                               size_t stride,\r\n                                               size_t n);\r\n\r\nGSL_FUN _gsl_vector_char_view \r\ngsl_vector_char_subvector (gsl_vector_char *v, \r\n                            size_t i, \r\n                            size_t n);\r\n\r\nGSL_FUN _gsl_vector_char_view \r\ngsl_vector_char_subvector_with_stride (gsl_vector_char *v, \r\n                                        size_t i,\r\n                                        size_t stride,\r\n                                        size_t n);\r\n\r\nGSL_FUN _gsl_vector_char_const_view \r\ngsl_vector_char_const_subvector (const gsl_vector_char *v, \r\n                                  size_t i, \r\n                                  size_t n);\r\n\r\nGSL_FUN _gsl_vector_char_const_view \r\ngsl_vector_char_const_subvector_with_stride (const gsl_vector_char *v, \r\n                                              size_t i, \r\n                                              size_t stride,\r\n                                              size_t n);\r\n\r\n/* Operations */\r\n\r\nGSL_FUN void gsl_vector_char_set_zero (gsl_vector_char * v);\r\nGSL_FUN void gsl_vector_char_set_all (gsl_vector_char * v, char x);\r\nGSL_FUN int gsl_vector_char_set_basis (gsl_vector_char * v, size_t i);\r\n\r\nGSL_FUN int gsl_vector_char_fread (FILE * stream, gsl_vector_char * v);\r\nGSL_FUN int gsl_vector_char_fwrite (FILE * stream, const gsl_vector_char * v);\r\nGSL_FUN int gsl_vector_char_fscanf (FILE * stream, gsl_vector_char * v);\r\nGSL_FUN int gsl_vector_char_fprintf (FILE * stream, const gsl_vector_char * v,\r\n                              const char *format);\r\n\r\nGSL_FUN int gsl_vector_char_memcpy (gsl_vector_char * dest, const gsl_vector_char * src);\r\n\r\nGSL_FUN int gsl_vector_char_reverse (gsl_vector_char * v);\r\n\r\nGSL_FUN int gsl_vector_char_swap (gsl_vector_char * v, gsl_vector_char * w);\r\nGSL_FUN int gsl_vector_char_swap_elements (gsl_vector_char * v, const size_t i, const size_t j);\r\n\r\nGSL_FUN char gsl_vector_char_max (const gsl_vector_char * v);\r\nGSL_FUN char gsl_vector_char_min (const gsl_vector_char * v);\r\nGSL_FUN void gsl_vector_char_minmax (const gsl_vector_char * v, char * min_out, char * max_out);\r\n\r\nGSL_FUN size_t gsl_vector_char_max_index (const gsl_vector_char * v);\r\nGSL_FUN size_t gsl_vector_char_min_index (const gsl_vector_char * v);\r\nGSL_FUN void gsl_vector_char_minmax_index (const gsl_vector_char * v, size_t * imin, size_t * imax);\r\n\r\nGSL_FUN int gsl_vector_char_add (gsl_vector_char * a, const gsl_vector_char * b);\r\nGSL_FUN int gsl_vector_char_sub (gsl_vector_char * a, const gsl_vector_char * b);\r\nGSL_FUN int gsl_vector_char_mul (gsl_vector_char * a, const gsl_vector_char * b);\r\nGSL_FUN int gsl_vector_char_div (gsl_vector_char * a, const gsl_vector_char * b);\r\nGSL_FUN int gsl_vector_char_scale (gsl_vector_char * a, const double x);\r\nGSL_FUN int gsl_vector_char_add_constant (gsl_vector_char * a, const double x);\r\n\r\nGSL_FUN int gsl_vector_char_isnull (const gsl_vector_char * v);\r\nGSL_FUN int gsl_vector_char_ispos (const gsl_vector_char * v);\r\nGSL_FUN int gsl_vector_char_isneg (const gsl_vector_char * v);\r\nGSL_FUN int gsl_vector_char_isnonneg (const gsl_vector_char * v);\r\n\r\nGSL_FUN INLINE_DECL char gsl_vector_char_get (const gsl_vector_char * v, const size_t i);\r\nGSL_FUN INLINE_DECL void gsl_vector_char_set (gsl_vector_char * v, const size_t i, char x);\r\nGSL_FUN INLINE_DECL char * gsl_vector_char_ptr (gsl_vector_char * v, const size_t i);\r\nGSL_FUN INLINE_DECL const char * gsl_vector_char_const_ptr (const gsl_vector_char * v, const size_t i);\r\n\r\n#ifdef HAVE_INLINE\r\n\r\nINLINE_FUN\r\nchar\r\ngsl_vector_char_get (const gsl_vector_char * v, const size_t i)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(i >= v->size))\r\n    {\r\n      GSL_ERROR_VAL (\"index out of range\", GSL_EINVAL, 0);\r\n    }\r\n#endif\r\n  return v->data[i * v->stride];\r\n}\r\n\r\nINLINE_FUN\r\nvoid\r\ngsl_vector_char_set (gsl_vector_char * v, const size_t i, char x)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(i >= v->size))\r\n    {\r\n      GSL_ERROR_VOID (\"index out of range\", GSL_EINVAL);\r\n    }\r\n#endif\r\n  v->data[i * v->stride] = x;\r\n}\r\n\r\nINLINE_FUN\r\nchar *\r\ngsl_vector_char_ptr (gsl_vector_char * v, const size_t i)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(i >= v->size))\r\n    {\r\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\r\n    }\r\n#endif\r\n  return (char *) (v->data + i * v->stride);\r\n}\r\n\r\nINLINE_FUN\r\nconst char *\r\ngsl_vector_char_const_ptr (const gsl_vector_char * v, const size_t i)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(i >= v->size))\r\n    {\r\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\r\n    }\r\n#endif\r\n  return (const char *) (v->data + i * v->stride);\r\n}\r\n#endif /* HAVE_INLINE */\r\n\r\n__END_DECLS\r\n\r\n#endif /* __GSL_VECTOR_CHAR_H__ */\r\n\r\n\r\n", "meta": {"hexsha": "03e386734f03056206cfd0551e6d0eba618056f8", "size": 8056, "ext": "h", "lang": "C", "max_stars_repo_path": "deps/include/gsl/gsl_vector_char.h", "max_stars_repo_name": "berkus/music-cs", "max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "deps/include/gsl/gsl_vector_char.h", "max_issues_repo_name": "berkus/music-cs", "max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "deps/include/gsl/gsl_vector_char.h", "max_forks_repo_name": "berkus/music-cs", "max_forks_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8487394958, "max_line_length": 104, "alphanum_fraction": 0.6631082423, "num_tokens": 1931, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15002882814282253, "lm_q2_score": 0.02887090799076163, "lm_q1q2_score": 0.004331468493273218}}
{"text": "/* -----------------------------------------------------------------------------\n * Copyright 2021 Jonathan Haigh\n * SPDX-License-Identifier: MIT\n * ---------------------------------------------------------------------------*/\n\n#ifndef SQ_INCLUDE_GUARD_results_Filter_h_\n#define SQ_INCLUDE_GUARD_results_Filter_h_\n\n#include \"core/Field.h\"\n#include \"core/typeutil.h\"\n#include \"parser/FilterSpec.h\"\n\n#include <gsl/gsl>\n#include <memory>\n\nnamespace sq::results {\n\nstruct Filter;\nusing FilterPtr = std::unique_ptr<Filter>;\n\nstruct Filter {\n  /**\n   * Create a Filter for the given spec.\n   */\n  SQ_ND static FilterPtr create(const parser::FilterSpec &spec);\n\n  /**\n   * Apply this filter to a Result.\n   */\n  SQ_ND virtual Result operator()(Result &&result) const = 0;\n\n  virtual ~Filter() = default;\n  Filter() = default;\n  Filter(const Filter &) = delete;\n  Filter(Filter &&) = delete;\n  Filter &operator=(const Filter &) = delete;\n  Filter &operator=(Filter &&) = delete;\n};\n\n} // namespace sq::results\n\n#endif // SQ_INCLUDE_GUARD_results_Filter_h_\n", "meta": {"hexsha": "1bc82ce14f43ba0eb99087560c7b0bc8b98af82e", "size": 1048, "ext": "h", "lang": "C", "max_stars_repo_path": "src/results/include/results/Filter.h", "max_stars_repo_name": "jonathanhaigh/sq", "max_stars_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-12T16:21:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-12T16:21:41.000Z", "max_issues_repo_path": "src/results/include/results/Filter.h", "max_issues_repo_name": "jonathanhaigh/sq", "max_issues_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 44.0, "max_issues_repo_issues_event_min_datetime": "2021-02-08T19:17:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-05T18:51:38.000Z", "max_forks_repo_path": "src/results/include/results/Filter.h", "max_forks_repo_name": "jonathanhaigh/sq", "max_forks_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3720930233, "max_line_length": 80, "alphanum_fraction": 0.5982824427, "num_tokens": 225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.136608375965897, "lm_q2_score": 0.03161876361857397, "lm_q1q2_score": 0.0043193879479829795}}
{"text": "#ifndef OPENMC_TALLIES_FILTER_DELAYEDGROUP_H\n#define OPENMC_TALLIES_FILTER_DELAYEDGROUP_H\n\n#include <vector>\n\n#include <gsl/gsl>\n\n#include \"openmc/tallies/filter.h\"\n\nnamespace openmc {\n\n//==============================================================================\n//! Bins outgoing fission neutrons in their delayed groups.\n//!\n//! The get_all_bins functionality is not actually used.  The bins are manually\n//! iterated over in the scoring subroutines.\n//==============================================================================\n\nclass DelayedGroupFilter : public Filter\n{\npublic:\n  //----------------------------------------------------------------------------\n  // Constructors, destructors\n\n  ~DelayedGroupFilter() = default;\n\n  //----------------------------------------------------------------------------\n  // Methods\n\n  std::string type() const override {return \"delayedgroup\";}\n\n  void from_xml(pugi::xml_node node) override;\n\n  void get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match)\n  const override;\n\n  void to_statepoint(hid_t filter_group) const override;\n\n  std::string text_label(int bin) const override;\n\n  //----------------------------------------------------------------------------\n  // Accessors\n\n  const std::vector<int>& groups() const { return groups_; }\n\n  void set_groups(gsl::span<int> groups);\n\nprivate:\n  //----------------------------------------------------------------------------\n  // Data members\n\n  std::vector<int> groups_;\n};\n\n} // namespace openmc\n#endif // OPENMC_TALLIES_FILTER_DELAYEDGROUP_H\n", "meta": {"hexsha": "64bdd3398565cf33a29f23459a0ef5632d2fb709", "size": 1569, "ext": "h", "lang": "C", "max_stars_repo_path": "include/openmc/tallies/filter_delayedgroup.h", "max_stars_repo_name": "Hit-Weixg/openmc", "max_stars_repo_head_hexsha": "c5f66a3af5c1a57087e330f7b870e89a82267e4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-01-10T13:14:35.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-05T10:18:12.000Z", "max_issues_repo_path": "include/openmc/tallies/filter_delayedgroup.h", "max_issues_repo_name": "mehmeturkmen/openmc", "max_issues_repo_head_hexsha": "ffe0f0283a81d32759e4f877909bbb64d5ad0d3d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-03-14T12:18:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-01T15:23:23.000Z", "max_forks_repo_path": "include/openmc/tallies/filter_delayedgroup.h", "max_forks_repo_name": "mehmeturkmen/openmc", "max_forks_repo_head_hexsha": "ffe0f0283a81d32759e4f877909bbb64d5ad0d3d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-07-31T21:03:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-22T20:54:48.000Z", "avg_line_length": 27.5263157895, "max_line_length": 84, "alphanum_fraction": 0.5181644359, "num_tokens": 291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11920292515117027, "lm_q2_score": 0.03622005976626622, "lm_q1q2_score": 0.004317537073289146}}
{"text": "/* spcopy.c\n * \n * Copyright (C) 2014 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <stdlib.h>\n#include <math.h>\n#include <gsl/gsl_spmatrix.h>\n#include <gsl/gsl_errno.h>\n\n#include \"avl.c\"\n\nint\ngsl_spmatrix_memcpy(gsl_spmatrix *dest, const gsl_spmatrix *src)\n{\n  const size_t M = src->size1;\n  const size_t N = src->size2;\n\n  if (M != dest->size1 || N != dest->size2)\n    {\n      GSL_ERROR(\"matrix sizes are different\", GSL_EBADLEN);\n    }\n  else if (dest->sptype != src->sptype)\n    {\n      GSL_ERROR(\"cannot copy matrices of different storage formats\",\n                GSL_EINVAL);\n    }\n  else\n    {\n      int s = GSL_SUCCESS;\n      size_t n;\n\n      if (dest->nzmax < src->nz)\n        {\n          s = gsl_spmatrix_realloc(src->nz, dest);\n          if (s)\n            return s;\n        }\n\n      /* copy indices and data to dest */\n      if (GSL_SPMATRIX_ISTRIPLET(src))\n        {\n          void *ptr;\n\n          for (n = 0; n < src->nz; ++n)\n            {\n              dest->i[n] = src->i[n];\n              dest->p[n] = src->p[n];\n              dest->data[n] = src->data[n];\n\n              /* copy binary tree data */\n              ptr = avl_insert(dest->tree_data->tree, &dest->data[n]);\n              if (ptr != NULL)\n                {\n                  GSL_ERROR(\"detected duplicate entry\", GSL_EINVAL);\n                }\n            }\n        }\n      else if (GSL_SPMATRIX_ISCCS(src))\n        {\n          for (n = 0; n < src->nz; ++n)\n            {\n              dest->i[n] = src->i[n];\n              dest->data[n] = src->data[n];\n            }\n\n          for (n = 0; n < src->size2 + 1; ++n)\n            {\n              dest->p[n] = src->p[n];\n            }\n        }\n      else if (GSL_SPMATRIX_ISCRS(src))\n        {\n          for (n = 0; n < src->nz; ++n)\n            {\n              dest->i[n] = src->i[n];\n              dest->data[n] = src->data[n];\n            }\n\n          for (n = 0; n < src->size1 + 1; ++n)\n            {\n              dest->p[n] = src->p[n];\n            }\n        }\n      else\n        {\n          GSL_ERROR(\"invalid matrix type for src\", GSL_EINVAL);\n        }\n\n      dest->nz = src->nz;\n\n      return s;\n    }\n} /* gsl_spmatrix_memcpy() */\n", "meta": {"hexsha": "b96c21bf6290515fe7c355d047d39d30c5f1e95e", "size": 2900, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.4/spmatrix/spcopy.c", "max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-13T05:01:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-13T05:01:59.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/spmatrix/spcopy.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/spmatrix/spcopy.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3636363636, "max_line_length": 81, "alphanum_fraction": 0.5134482759, "num_tokens": 784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1710612001304791, "lm_q2_score": 0.02517884138057321, "lm_q1q2_score": 0.004307122824455822}}
{"text": "#pragma once\r\n\r\n#include <gsl/gsl>\r\n#include <vector>\r\n#include <sstream>\r\n\r\nnamespace multiformats {\r\n\r\n    //\r\n    // Raw memory byte\r\n    //\r\n    using byte_t = uint8_t;\r\n\r\n    //\r\n    // Raw memory buffer\r\n    //   Represents a contiguous run of byte_t elements, or a const view of it.\r\n    //\r\n    using buffer_t = std::vector<byte_t>;\r\n    using bufferview_t = gsl::span<const byte_t>;\r\n\r\n    //    Appends a buffer or a byte to a buffer\r\n    inline buffer_t& operator += (buffer_t& _Left, bufferview_t _Right) {\r\n        _Left.insert(_Left.end(), _Right.begin(), _Right.end());\r\n        return _Left;\r\n    }\r\n    inline buffer_t& operator += (buffer_t& _Left, byte_t _Value) {\r\n        _Left.push_back(_Value);\r\n        return _Left;\r\n    }\r\n\r\n    //    Concatenates two buffers\r\n    inline buffer_t operator + (bufferview_t _Left, bufferview_t _Right) {\r\n        auto result = buffer_t(_Left.size() + _Right.size());\r\n        std::copy(_Right.begin(), _Right.end(), std::copy(_Left.begin(), _Left.end(), result.begin()));\r\n        return result;\r\n    }\r\n\r\n    //    Buffer comparison\r\n    inline bool operator == (bufferview_t _Left, bufferview_t _Right) {\r\n        return std::equal(_Left.begin(), _Left.end(), _Right.begin(), _Right.end());\r\n    }\r\n\r\n    inline bool operator != (bufferview_t _Left, bufferview_t _Right) { \r\n        return !(_Left == _Right);\r\n    }\r\n\r\n\r\n    //\r\n    // String and constant view of strings\r\n    //\r\n    using string_t = std::string;\r\n    using stringview_t = gsl::cstring_span<>;\r\n\r\n    inline std::vector<stringview_t> split(stringview_t s, char delim) {\r\n        auto elems = std::vector<stringview_t>{};\r\n\r\n        auto begin = s.begin();\r\n        auto end = s.end();\r\n        auto first = begin;\r\n        while (first != end) {\r\n            auto last = std::find(first, end, delim);\r\n            elems.push_back(s.subspan(first - begin, last - first));\r\n            if (last == end) break;\r\n            first = last + 1;\r\n        }\r\n\r\n        return elems;\r\n    }\r\n\r\n    inline string_t operator+(stringview_t _Left, const string_t& _Right) { return (to_string(_Left) + _Right); }\r\n    inline string_t operator+(const string_t& _Left, stringview_t _Right) { return (_Left + to_string(_Right)); }\r\n\r\n    // \r\n    // Conversions\r\n    //   to_* methods create a new container and copy the content\r\n    //   as_* methods return a const view of the container without copy\r\n    //\r\n    inline buffer_t to_buffer(stringview_t s) { return { s.begin(), s.end() }; }\r\n    inline buffer_t to_buffer(const char* s)  { return to_buffer(gsl::ensure_z(s)); }\r\n\r\n    inline bufferview_t as_buffer(stringview_t s) { return { reinterpret_cast<const byte_t*>(s.data()), gsl::narrow<ptrdiff_t>(s.size()) }; }\r\n    inline stringview_t as_string(bufferview_t b) { return { reinterpret_cast<const char*>(b.data()), b.size() }; }\r\n    \r\n    inline string_t to_string(bufferview_t b) { return to_string(as_string(b)); }\r\n}", "meta": {"hexsha": "2c4316de48bb3afac2077d28325c52c5b084465b", "size": 2944, "ext": "h", "lang": "C", "max_stars_repo_path": "include/multiformats/common.h", "max_stars_repo_name": "cedrou/cpp-multiformats", "max_stars_repo_head_hexsha": "5516d857d4429544bd641b7fdde24c6cad9265b7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-07-29T20:33:02.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-29T20:33:02.000Z", "max_issues_repo_path": "include/multiformats/common.h", "max_issues_repo_name": "cedrou/multiformats", "max_issues_repo_head_hexsha": "5516d857d4429544bd641b7fdde24c6cad9265b7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/multiformats/common.h", "max_forks_repo_name": "cedrou/multiformats", "max_forks_repo_head_hexsha": "5516d857d4429544bd641b7fdde24c6cad9265b7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6352941176, "max_line_length": 142, "alphanum_fraction": 0.6063179348, "num_tokens": 727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12252321892633068, "lm_q2_score": 0.03514484741138068, "lm_q1q2_score": 0.004306059833517081}}
{"text": "#pragma once\n\n#include <gsl/gsl>\n#include <codecvt>\n#include <locale>\n#include <string>\n\n#ifdef _MSC_VER\n#include <string_view>\n#else\n// llvm-libc++ included with Android NDK r15c hasn't yet promoted the C++1z library fundamentals\n// technical specification to the final C++17 specification for string_view.\n// Force promote the types we need up into the std namespace.\n#include <experimental/string_view>\nnamespace std\n{\n    using string_view = experimental::string_view;\n    using wstring_view = experimental::wstring_view;\n}\n#endif\n\nnamespace arcana\n{\n    inline std::string utf16_to_utf8(gsl::cwzstring<> input)\n    {\n        std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;\n        return converter.to_bytes(input);\n    }\n\n    inline std::wstring utf8_to_utf16(gsl::czstring<> input)\n    {\n        std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;\n        return converter.from_bytes(input);\n    }\n\n    inline std::string utf16_to_utf8(std::wstring_view input)\n    {\n        std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;\n        return converter.to_bytes(input.data(), input.data() + input.size());\n    }\n\n    inline std::wstring utf8_to_utf16(std::string_view input)\n    {\n        std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;\n        return converter.from_bytes(input.data(), input.data() + input.size());\n    }\n\n    struct string_compare\n    {\n        using is_transparent = std::true_type;\n\n        bool operator()(gsl::cstring_span<> a, gsl::cstring_span<> b) const\n        {\n            return std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end());\n        }\n\n        bool operator()(gsl::czstring_span<> a, gsl::czstring_span<> b) const\n        {\n            return (*this)(a.as_string_span(), b.as_string_span());\n        }\n\n        bool operator()(gsl::czstring<> a, gsl::czstring<> b) const\n        {\n            return strcmp(a, b) < 0;\n        }\n    };\n}\n", "meta": {"hexsha": "1b904e395f912b86fa7dd067bda198ca07208736", "size": 1954, "ext": "h", "lang": "C", "max_stars_repo_path": "Source/Shared/arcana/string.h", "max_stars_repo_name": "andrei-datcu/arcana.cpp", "max_stars_repo_head_hexsha": "3c4757cbee49b3272130bf8b72094c2c62fd36c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 65.0, "max_stars_repo_stars_event_min_datetime": "2019-05-08T01:53:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T15:05:38.000Z", "max_issues_repo_path": "Source/Shared/arcana/string.h", "max_issues_repo_name": "andrei-datcu/arcana.cpp", "max_issues_repo_head_hexsha": "3c4757cbee49b3272130bf8b72094c2c62fd36c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2019-08-13T03:18:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T20:12:24.000Z", "max_forks_repo_path": "Source/Shared/arcana/string.h", "max_forks_repo_name": "andrei-datcu/arcana.cpp", "max_forks_repo_head_hexsha": "3c4757cbee49b3272130bf8b72094c2c62fd36c5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2019-05-09T23:07:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-26T14:24:29.000Z", "avg_line_length": 28.7352941176, "max_line_length": 96, "alphanum_fraction": 0.6566018424, "num_tokens": 473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14414885303274058, "lm_q2_score": 0.029760091364389046, "lm_q1q2_score": 0.004289883036326249}}
{"text": "/** \\file real-compressor.c */\n#ifndef __COMPLEARN_REALCOMPRESSOR_H\n#define __COMPLEARN_REALCOMPRESSOR_H\n\n#define COMPLEARN_REAL_COMPRESSOR_TYPE        (real_compressor_get_type ())\n#define COMPLEARN_TYPE_REAL_COMPRESSOR        (real_compressor_get_type ())\n#define COMPLEARN_REAL_COMPRESSOR(obj)        (G_TYPE_CHECK_INSTANCE_CAST ((obj), COMPLEARN_REAL_COMPRESSOR_TYPE, CompLearnRealCompressor))\n#define IS_COMPLEARN_REAL_COMPRESSOR(obj)        (G_TYPE_CHECK_INSTANCE_TYPE ((obj), COMPLEARN_REAL_COMPRESSOR_TYPE))\n#define COMPLEARN_REAL_COMPRESSOR_GET_INTERFACE(inst) (G_TYPE_INSTANCE_GET_INTERFACE((inst), COMPLEARN_REAL_COMPRESSOR_TYPE, CompLearnRealCompressorIface))\n\n#include <glib.h>\n#include <glib-object.h>\n#include <glib/garray.h>\n#include <gsl/gsl_matrix.h>\n\n#define COMPLEARN_ERROR 1\n#define COMPLEARN_ERROR_NO_COMPRESSOR_SET 100\n\ntypedef struct _CompLearnRealCompressor CompLearnRealCompressor;\ntypedef struct _CompLearnRealCompressorIface CompLearnRealCompressorIface;\n\nstruct _CompLearnRealCompressorIface {\n  GTypeInterface parent;\n\n  GString *(*compress)(CompLearnRealCompressor *self, const GString *input);\n  GString *(*decompress)(CompLearnRealCompressor *self, const GString *input);\n  GString *(*blurb)(CompLearnRealCompressor *self);\n  GString *(*canonical_extension)(CompLearnRealCompressor *self);\n  GString *(*name)(CompLearnRealCompressor *self);\n  GString *(*compressor_version)(CompLearnRealCompressor *self);\n  GString *(*binding_version)(CompLearnRealCompressor *self);\n  gboolean (*is_threadsafe)(CompLearnRealCompressor *self);\n  gboolean (*is_compressible)(CompLearnRealCompressor *self, const GString *input);\n  gboolean (*is_decompressible)(CompLearnRealCompressor *self, const GString *input);\n  gboolean (*is_just_size)(CompLearnRealCompressor *self);\n  gboolean (*is_hash_function)(CompLearnRealCompressor *self);\n  GString *(*hash)(CompLearnRealCompressor *self, const GString *input);\n  gboolean (*is_operational)(CompLearnRealCompressor *self);\n  gboolean (*is_private_property)(CompLearnRealCompressor *self, const char *propname);\n  gdouble (*compressed_size)(CompLearnRealCompressor *self, const GString *input);\n  guint64 (*window_size)(CompLearnRealCompressor *self);\n  CompLearnRealCompressor *(*clone)(CompLearnRealCompressor *self);\n};\n\nGType real_compressor_get_type(void);\n\n/// Compress the string by the compressor\n/// \\param[in] self is a pointer to compressor\n/// \\param[in] input is a pointer to a GString which must be compressed\n/// \\return a pointer to compressed string\nGString *real_compressor_compress(CompLearnRealCompressor *self,const GString *input);\nGString *real_compressor_hash(CompLearnRealCompressor *self,const GString *input);\n/// Decompress the string by the compressor\n/// \\param[in] self is pointer to compressor\n/// \\param[in] input is a pointer to a GString which must be decompressed\n/// \\return a pointer to decompressed string\nGString *real_compressor_decompress(CompLearnRealCompressor *self,const GString *input);\n/// Calculate size of the compressed string\n/// \\param[in] self is a pointer to a compressor\n/// \\param[in] input is a pointer to string which must be compress\n/// \\return size of compressed string in bits\ngdouble real_compressor_compressed_size(CompLearnRealCompressor *self,const GString *input);\n/// Return a short text description of this compressor\n/// \\param[in] self is a pointer to a compressor\nGString *real_compressor_blurb(CompLearnRealCompressor *self);\nGString *real_compressor_name(CompLearnRealCompressor *self);\n/// Display the compressor version\n/// param[in] is a pointer to compressor\n/// \\return a GString holding a 3-part version\nGString *real_compressor_compressor_version(CompLearnRealCompressor *self);\n/// Display the compressor binding version\n/// \\param[in] is a pointer to compressor\n/// \\return a GString holding a 3-part version\nGString *real_compressor_binding_version(CompLearnRealCompressor *self);\n/// This function checks whether the string is compressible by the compressor\n/// \\param[in] self is a pointer to compressor\n/// \\param[in] input is a pointer to GString which is under test\n/// \\return true for every string\ngboolean real_compressor_is_compressible(CompLearnRealCompressor *self, const GString *input);\n/// Check whether the string is decompressible by the compressor\n/// \\param[in] self is a pointer to compressor\n/// \\param[in] input is a pointer to string which is under test\ngboolean real_compressor_is_decompressible(CompLearnRealCompressor *self, const GString *input);\n\n\ngboolean real_compressor_is_private_property(CompLearnRealCompressor *self, const char *input);\nguint64 real_compressor_window_size(CompLearnRealCompressor *self);\ngboolean real_compressor_is_threadsafe(CompLearnRealCompressor *self);\ngboolean real_compressor_is_just_size(CompLearnRealCompressor *self);\ngboolean real_compressor_is_hash_function(CompLearnRealCompressor *self);\nGString *real_compressor_canonical_extension(CompLearnRealCompressor *rc);\ngboolean real_compressor_is_operational(CompLearnRealCompressor *self);\nCompLearnRealCompressor *real_compressor_clone(CompLearnRealCompressor *self);\n\n#define SET_DEFAULT_PROPS(groupname, clt, mobj) \\\n  do { \\\n  GParamSpec **gps, **cur; \\\n  g_assert(mobj != NULL); \\\n    if (complearn_environment_get_nameable(groupname) == NULL) { \\\n      complearn_environment_register_nameable(groupname, G_OBJECT(mobj)); \\\n      break; \\\n    } \\\n  gps =g_object_class_list_properties(G_OBJECT_CLASS(clt(mobj)), NULL); \\\n  for (cur = gps; *cur; cur += 1) { \\\n    GValue v = {0,}; \\\n    g_value_init(&v, (*cur)->value_type); \\\n    g_param_value_set_default(*cur, &v); \\\n    g_object_set_property(G_OBJECT(mobj), (*cur)->name, &v); \\\n    complearn_environment_register_property(G_OBJECT(mobj), (*cur), &v); \\\n  } } while(0)\n\n#define SET_DEFAULT_COMPRESSOR_PROPS(groupname, clt, mobj) \\\n  do { \\\n      SET_DEFAULT_PROPS(groupname, clt, mobj); \\\n    if (complearn_environment_get_nameable(groupname) == NULL) { \\\n      complearn_environment_register_compressor(mobj); \\\n    } \\\n  } while (0);\n\n#endif\n\n#define G_LOG_LEVEL_NOTICE G_LOG_LEVEL_USER_SHIFT\n#define g_notice(...) g_log(G_LOG_DOMAIN, G_LOG_LEVEL_NOTICE, __VA_ARGS__)\n\nvoid real_compressor_interface_init (gpointer g_iface, gpointer iface_data);\n", "meta": {"hexsha": "f2d36ae62bfc1f6c6b6297528178f442284fb8de", "size": 6265, "ext": "c", "lang": "C", "max_stars_repo_path": "doxy/real-compressor.c", "max_stars_repo_name": "rudi-cilibrasi/classic-complearn", "max_stars_repo_head_hexsha": "c70ac5ad7bcfe3af80a2a8f087ee6f5904820a66", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-03-14T13:52:31.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-08T11:13:03.000Z", "max_issues_repo_path": "doxy/real-compressor.c", "max_issues_repo_name": "rudi-cilibrasi/classic-complearn", "max_issues_repo_head_hexsha": "c70ac5ad7bcfe3af80a2a8f087ee6f5904820a66", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2016-05-10T12:56:52.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-15T18:30:04.000Z", "max_forks_repo_path": "doxy/real-compressor.c", "max_forks_repo_name": "rudi-cilibrasi/classic-complearn", "max_forks_repo_head_hexsha": "c70ac5ad7bcfe3af80a2a8f087ee6f5904820a66", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.7222222222, "max_line_length": 155, "alphanum_fraction": 0.7897845172, "num_tokens": 1568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1968262036430985, "lm_q2_score": 0.02161533240812483, "lm_q1q2_score": 0.0042544638183748444}}
{"text": "#pragma once\n\n#include <halley/maths/vector2.h>\n#include <halley/maths/rect.h>\n#include <memory>\n#include <halley/resources/resource.h>\n#include <halley/text/halleystring.h>\n#include <halley/data_structures/hash_map.h>\n#include <gsl/span>\n#include \"halley/maths/vector4.h\"\n\nnamespace Halley\n{\n\tclass Sprite;\n\tclass Resources;\n\tclass Serializer;\n\tclass Deserializer;\n\tclass ResourceDataStatic;\n\tclass Texture;\n\tclass ResourceLoader;\n\tclass Material;\n\tclass SpriteSheet;\n\n\tclass SpriteSheetEntry\n\t{\n\tpublic:\n\t\tVector2f pivot;\n\t\tVector2i origPivot;\n\t\tVector2f size;\n\t\tRect4f coords;\n\t\tVector4s trimBorder;\n\t\tVector4s slices;\n\t\tint duration = 0;\n\t\tbool rotated = false;\n\t\tbool sliced = false;\n\n\t\tvoid serialize(Serializer& s) const;\n\t\tvoid deserialize(Deserializer& s);\n\n#ifdef ENABLE_HOT_RELOAD\n\t\tSpriteSheet* parent = nullptr;\n\t\tuint32_t idx = 0;\n#endif\n\t};\n\n\tclass SpriteSheetFrameTag\n\t{\n\tpublic:\n\t\tString name;\n\t\tint from = 0;\n\t\tint to = 0;\n\n\t\tvoid serialize(Serializer& s) const;\n\t\tvoid deserialize(Deserializer& s);\n\t};\n\n\tclass SpriteHotReloader {\n\tpublic:\n\t\tvirtual ~SpriteHotReloader() = default;\n\n#ifdef ENABLE_HOT_RELOAD\n\t\tvoid addSprite(Sprite* sprite, uint32_t idx) const;\n\t\tvoid removeSprite(Sprite* sprite) const;\n\t\tvoid updateSpriteIndex(Sprite* sprite, uint32_t idx) const;\n\t\tvoid clearSpriteRefs();\n\n\tprotected:\n\t\tclass SpritePointerHasher {\n\t\tpublic:\n\t\t\tstd::size_t operator()(Sprite* ptr) const noexcept;\n\t\t};\n\t\t\n\t\tmutable std::unordered_map<Sprite*, uint32_t, SpritePointerHasher> spriteRefs;\n#endif\n\t};\n\t\n\tclass SpriteSheet final : public Resource, public SpriteHotReloader\n\t{\n\tpublic:\n\t\tSpriteSheet();\n\t\t~SpriteSheet();\n\t\t\n\t\tconst std::shared_ptr<const Texture>& getTexture() const;\n\t\tconst SpriteSheetEntry& getSprite(const String& name) const;\n\t\tconst SpriteSheetEntry& getSprite(size_t idx) const;\n\t\tconst SpriteSheetEntry* tryGetSprite(const String& name) const;\n\t\tconst SpriteSheetEntry& getDummySprite() const;\n\n\t\tconst std::vector<SpriteSheetFrameTag>& getFrameTags() const;\n\t\tstd::vector<String> getSpriteNames() const;\n\t\tconst HashMap<String, uint32_t>& getSpriteNameMap() const;\n\n\t\tsize_t getSpriteCount() const;\n\t\tstd::optional<size_t> getIndex(const String& name) const;\n\t\tbool hasSprite(const String& name) const;\n\n\t\tvoid loadJson(gsl::span<const gsl::byte> data);\n\n\t\tvoid addSprite(String name, const SpriteSheetEntry& sprite);\n\t\tvoid setTextureName(String name);\n\n\t\tstd::shared_ptr<Material> getMaterial(const String& name) const;\n\t\tvoid setDefaultMaterialName(String materialName);\n\t\tconst String& getDefaultMaterialName() const;\n\t\tvoid clearMaterialCache() const;\n\n\t\tstatic std::unique_ptr<SpriteSheet> loadResource(ResourceLoader& loader);\n\t\tconstexpr static AssetType getAssetType() { return AssetType::SpriteSheet; }\n\t\tvoid reload(Resource&& resource) override;\n\n\t\tvoid serialize(Serializer& s) const;\n\t\tvoid deserialize(Deserializer& s);\n\n\tprivate:\n\t\tconstexpr static int version = 1;\n\t\t\n\t\tResources* resources = nullptr;\n\n\t\tstd::vector<SpriteSheetEntry> sprites;\n\t\tSpriteSheetEntry dummySprite;\n\t\tHashMap<String, uint32_t> spriteIdx;\n\t\tstd::vector<SpriteSheetFrameTag> frameTags;\n\n\t\tString textureName;\n\t\tmutable std::shared_ptr<const Texture> texture;\n\n\t\tString defaultMaterialName;\n\t\tmutable HashMap<String, std::weak_ptr<Material>> materials;\n\n\t\tvoid loadTexture(Resources& resources) const;\n\t\tvoid assignIds();\n\t};\n\n\tclass SpriteResource final : public Resource, public SpriteHotReloader\n\t{\n\tpublic:\n\t\tSpriteResource();\n\t\tSpriteResource(const std::shared_ptr<const SpriteSheet>& spriteSheet, size_t idx);\n\t\t~SpriteResource();\n\n\t\tconst SpriteSheetEntry& getSprite() const;\n\t\tsize_t getIdx() const;\n\t\tstd::shared_ptr<const SpriteSheet> getSpriteSheet() const;\n\n\t\tstd::shared_ptr<Material> getMaterial(const String& name) const;\n\t\tconst String& getDefaultMaterialName() const;\n\n\t\tconstexpr static AssetType getAssetType() { return AssetType::Sprite; }\n\t\tstatic std::unique_ptr<SpriteResource> loadResource(ResourceLoader& loader);\n\t\tvoid reload(Resource&& resource) override;\n\n\t\tvoid serialize(Serializer& s) const;\n\t\tvoid deserialize(Deserializer& s);\n\n\tprivate:\n\t\tstd::weak_ptr<const SpriteSheet> spriteSheet;\n\t\tuint64_t idx = -1;\n\t\tResources* resources = nullptr;\n\t};\n}\n", "meta": {"hexsha": "12086994d93a2ae8458ce15407314b2fb4af43b5", "size": 4214, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engine/core/include/halley/core/graphics/sprite/sprite_sheet.h", "max_stars_repo_name": "JLouhela/halley", "max_stars_repo_head_hexsha": "eb395c8cc5ab6fb4aa1966ce3d7a9c1b8301d587", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3262.0, "max_stars_repo_stars_event_min_datetime": "2016-04-10T15:24:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:47:08.000Z", "max_issues_repo_path": "src/engine/core/include/halley/core/graphics/sprite/sprite_sheet.h", "max_issues_repo_name": "JLouhela/halley", "max_issues_repo_head_hexsha": "eb395c8cc5ab6fb4aa1966ce3d7a9c1b8301d587", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 53.0, "max_issues_repo_issues_event_min_datetime": "2016-10-09T16:25:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-10T13:52:37.000Z", "max_forks_repo_path": "src/engine/core/include/halley/core/graphics/sprite/sprite_sheet.h", "max_forks_repo_name": "JLouhela/halley", "max_forks_repo_head_hexsha": "eb395c8cc5ab6fb4aa1966ce3d7a9c1b8301d587", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 193.0, "max_forks_repo_forks_event_min_datetime": "2017-10-23T06:08:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T12:59:58.000Z", "avg_line_length": 26.1739130435, "max_line_length": 84, "alphanum_fraction": 0.7539155197, "num_tokens": 1041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21206880435710532, "lm_q2_score": 0.020023439827464892, "lm_q1q2_score": 0.0042463469433269225}}
{"text": "#pragma once\n\n#include <winrt\\Windows.Foundation.h>\n#include <cstdint>\n#include <d3d11.h>\n#include <DirectXMath.h>\n#include <dxgidebug.h>\n#include <gsl\\gsl>\n#include \"GameException.h\"\n\nnamespace Library\n{\n\tenum class ShaderStages\n\t{\n\t\tIA,\n\t\tVS,\n\t\tHS,\n\t\tDS,\n\t\tGS,\n\t\tSO,\n\t\tRS,\n\t\tPS,\n\t\tOM,\n\n\t\tCS\n\t};\n\n\tconst std::array<ShaderStages, 6> ProgrammableGraphicsShaderStages\n\t{\n\t\tShaderStages::VS,\n\t\tShaderStages::HS,\n\t\tShaderStages::DS,\n\t\tShaderStages::GS,\n\t\tShaderStages::PS,\n\t\tShaderStages::CS,\n\t};\n\n\tinline bool ShaderStageIsProgrammable(ShaderStages shaderStage)\n\t{\n\t\tstatic const std::map<ShaderStages, bool> isProgrammableMap\n\t\t{\n\t\t\t{ShaderStages::IA, false },\n\t\t\t{ ShaderStages::VS, true },\n\t\t\t{ ShaderStages::HS, true },\n\t\t\t{ ShaderStages::DS, true },\n\t\t\t{ ShaderStages::GS, true },\n\t\t\t{ ShaderStages::SO, false },\n\t\t\t{ ShaderStages::RS, false },\n\t\t\t{ ShaderStages::PS, true },\n\t\t\t{ ShaderStages::OM, false },\n\t\t\t{ ShaderStages::CS, true },\n\t\t};\n\n\t\treturn isProgrammableMap.at(shaderStage);\n\t}\n\n\tvoid CreateIndexBuffer(gsl::not_null<ID3D11Device*> device, const gsl::span<const std::uint16_t>& indices, gsl::not_null<ID3D11Buffer**> indexBuffer);\n\tvoid CreateIndexBuffer(gsl::not_null<ID3D11Device*> device, const gsl::span<const std::uint32_t>& indices, gsl::not_null<ID3D11Buffer**> indexBuffer);\n\tvoid CreateConstantBuffer(gsl::not_null<ID3D11Device*> device, std::size_t byteWidth, gsl::not_null<ID3D11Buffer**> constantBuffer);\n\n\tinline float ConvertDipsToPixels(float dips, float dpi)\n\t{\n\t\tstatic const float dipsPerInch = 96.0f;\n\t\treturn floorf(dips * dpi / dipsPerInch + 0.5f); // Round to nearest integer.\n\t}\n\n#if defined(DEBUG) || defined(_DEBUG)\n\t// Check for SDK Layer support.\n\tinline bool SdkLayersAvailable()\n\t{\n\t\tHRESULT hr = D3D11CreateDevice(\n\t\t\tnullptr,\n\t\t\tD3D_DRIVER_TYPE_NULL,       // There is no need to create a real hardware device.\n\t\t\t0,\n\t\t\tD3D11_CREATE_DEVICE_DEBUG,  // Check for the SDK layers.\n\t\t\tnullptr,                    // Any feature level will do.\n\t\t\t0,\n\t\t\tD3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Windows Store apps.\n\t\t\tnullptr,                    // No need to keep the D3D device reference.\n\t\t\tnullptr,                    // No need to know the feature level.\n\t\t\tnullptr                     // No need to keep the D3D device context reference.\n\t\t\t);\n\n\t\treturn SUCCEEDED(hr);\n\t}\n#endif\n\n#if defined(DEBUG) || defined(_DEBUG)\n\tinline void DumpD3DDebug()\n\t{\n\t\twinrt::com_ptr<IDXGIDebug1> debugInterface = nullptr;\n\t\tThrowIfFailed(DXGIGetDebugInterface1(0, IID_PPV_ARGS(debugInterface.put())));\n\t\tThrowIfFailed(debugInterface->ReportLiveObjects(DXGI_DEBUG_ALL, DXGI_DEBUG_RLO_ALL));\n\t}\n#endif\n}", "meta": {"hexsha": "bd13c88fa4f3bc81ac3eeb42ae6bb2a293de1b78", "size": 2661, "ext": "h", "lang": "C", "max_stars_repo_path": "source/Library.Shared/DirectXHelper.h", "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/Library.Shared/DirectXHelper.h", "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/Library.Shared/DirectXHelper.h", "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.71875, "max_line_length": 151, "alphanum_fraction": 0.6907177753, "num_tokens": 802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1993080074160125, "lm_q2_score": 0.02128735322929983, "lm_q1q2_score": 0.004242739955292569}}
{"text": "#ifndef __GSL_SORT_VECTOR_H__\r\n#define __GSL_SORT_VECTOR_H__\r\n\r\n#if !defined( GSL_FUN )\r\n#  if !defined( GSL_DLL )\r\n#    define GSL_FUN extern\r\n#  elif defined( BUILD_GSL_DLL )\r\n#    define GSL_FUN extern __declspec(dllexport)\r\n#  else\r\n#    define GSL_FUN extern __declspec(dllimport)\r\n#  endif\r\n#endif\r\n\r\n#include <gsl/gsl_sort_vector_long_double.h>\r\n#include <gsl/gsl_sort_vector_double.h>\r\n#include <gsl/gsl_sort_vector_float.h>\r\n\r\n#include <gsl/gsl_sort_vector_ulong.h>\r\n#include <gsl/gsl_sort_vector_long.h>\r\n\r\n#include <gsl/gsl_sort_vector_uint.h>\r\n#include <gsl/gsl_sort_vector_int.h>\r\n\r\n#include <gsl/gsl_sort_vector_ushort.h>\r\n#include <gsl/gsl_sort_vector_short.h>\r\n\r\n#include <gsl/gsl_sort_vector_uchar.h>\r\n#include <gsl/gsl_sort_vector_char.h>\r\n\r\n#endif /* __GSL_SORT_VECTOR_H__ */\r\n", "meta": {"hexsha": "47bae77e16fe32b5516624f35bcd2ec8f9ee5984", "size": 796, "ext": "h", "lang": "C", "max_stars_repo_path": "deps/include/gsl/gsl_sort_vector.h", "max_stars_repo_name": "berkus/music-cs", "max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z", "max_issues_repo_path": "deps/include/gsl/gsl_sort_vector.h", "max_issues_repo_name": "berkus/music-cs", "max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z", "max_forks_repo_path": "deps/include/gsl/gsl_sort_vector.h", "max_forks_repo_name": "berkus/music-cs", "max_forks_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 25.6774193548, "max_line_length": 49, "alphanum_fraction": 0.7537688442, "num_tokens": 216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12421301483609336, "lm_q2_score": 0.034100426693928106, "lm_q1q2_score": 0.004235716806850006}}
{"text": "#pragma once\n\n#include <unordered_map>\n#include <vector>\n\n#include <gsl/span>\n#include <json.hpp>\n#include <optional.hpp>\n\n#include \"Quiver/Animation/AnimationData.h\"\n#include \"Quiver/Animation/AnimationId.h\"\n#include \"Quiver/Animation/Rect.h\"\n#include \"Quiver/Animation/TimeUnit.h\"\n\nnamespace qvr\n{\n\n// Tells us about where to find an Animation on disk.\nstruct AnimationSourceInfo {\n\tstd::string name;\n\tstd::string filename;\n};\n\ninline bool operator==(const AnimationSourceInfo& a, const AnimationSourceInfo& b) {\n\treturn a.name == b.name && a.filename == b.filename;\n}\n\nclass AnimationLibrary\n{\npublic:\n\tAnimationId Add(const AnimationData& anim);\n\tAnimationId Add(\n\t\tconst AnimationData& anim, \n\t\tconst AnimationSourceInfo& sourceInfo);\n\n\tbool Remove(const AnimationId anim);\n\n\tbool Contains(const AnimationId anim) const;\n\n\tauto GetCount() const -> int;\n\n\tauto GetAnimation(const AnimationSourceInfo& sourceInfo) \n\t\tconst -> AnimationId;\n\n\tauto GetSourceInfo(const AnimationId anim) \n\t\tconst -> std::experimental::optional<AnimationSourceInfo>;\n\n\tauto GetFrameCount(const AnimationId anim) const -> int;\n\tauto GetViewCount(const AnimationId anim) const -> int;\n\tauto HasAltViews(const AnimationId anim) const -> bool;\n\t\n\tauto GetRect(\n\t\tconst AnimationId anim, \n\t\tconst int frameIndex, \n\t\tconst int viewIndex = 0) \n\t\t\tconst -> Animation::Rect;\n\n\tauto GetRects(\n\t\tconst AnimationId anim,\n\t\tconst int frameIndex)\n\t\t\tconst -> gsl::span<const Animation::Rect>;\n\n\tauto GetTime(\n\t\tconst AnimationId anim,\n\t\tconst int frameIndex) \n\t\t\tconst -> Animation::TimeUnit;\n\n\tauto GetIds() const -> std::vector<AnimationId>;\n\n\tfriend void to_json(nlohmann::json& j, const AnimationLibrary& animations);\n\nprivate:\n\tstruct AnimationInfo {\n\t\tAnimationInfo(\n\t\t\tconst unsigned indexOfFirstRect,\n\t\t\tconst unsigned indexOfFirstTime,\n\t\t\tconst unsigned numRects,\n\t\t\tconst unsigned numRectsPerFrame)\n\t\t\t: mIndexOfFirstRect(indexOfFirstRect)\n\t\t\t, mIndexOfFirstTime(indexOfFirstTime)\n\t\t\t, mNumRects(numRects)\n\t\t\t, mNumRectsPerFrame(numRectsPerFrame)\n\t\t{}\n\n\t\tAnimationInfo(const AnimationInfo& other) = default;\n\n\t\tAnimationInfo() = default;\n\n\t\tunsigned NumFrames() const { return mNumRects / mNumRectsPerFrame; }\n\n\t\tstd::experimental::optional<AnimationSourceInfo> mSourceInfo;\n\t\n\t\tunsigned mIndexOfFirstRect = 0;\n\t\tunsigned mIndexOfFirstTime = 0;\n\t\tunsigned mNumRects = 0;\n\t\tunsigned mNumRectsPerFrame = 0;\n\t};\n\n\tstd::unordered_map<AnimationId, AnimationInfo> infos;\n\t\n\t// Time values for each frame in every animation.\n\tstd::vector<Animation::TimeUnit> allFrameTimes;\n\n\t// Rects for each frame in every animation, including alt view rects.\n\tstd::vector<Animation::Rect> allFrameRects; \n};\n\nvoid to_json(nlohmann::json& j, const AnimationLibrary& animations);\nvoid to_json(nlohmann::json& j, const AnimationSourceInfo& sourceInfo);\n\nvoid from_json(const nlohmann::json& j, AnimationLibrary& animations);\nvoid from_json(const nlohmann::json& j, AnimationSourceInfo& animationSource);\n\n}", "meta": {"hexsha": "6165c47cb49b67a74acc6ffeee3a93ff70677f69", "size": 2961, "ext": "h", "lang": "C", "max_stars_repo_path": "External/Quiver/Source/Quiver/Quiver/Animation/AnimationLibrary.h", "max_stars_repo_name": "rachelnertia/Quarrel", "max_stars_repo_head_hexsha": "69616179fc71305757549c7fcaccc22707a91ba4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 39.0, "max_stars_repo_stars_event_min_datetime": "2017-10-22T15:47:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-31T22:19:55.000Z", "max_issues_repo_path": "External/Quiver/Source/Quiver/Quiver/Animation/AnimationLibrary.h", "max_issues_repo_name": "rachelnertia/Quarrel", "max_issues_repo_head_hexsha": "69616179fc71305757549c7fcaccc22707a91ba4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2017-10-26T21:21:51.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-13T14:46:17.000Z", "max_forks_repo_path": "Source/Quiver/Quiver/Animation/AnimationLibrary.h", "max_forks_repo_name": "rachelnertia/Quiver", "max_forks_repo_head_hexsha": "c8ef9591117bdfc8d6fa509ae53451e0807f5686", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-10-22T14:47:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-19T10:08:45.000Z", "avg_line_length": 25.9736842105, "max_line_length": 84, "alphanum_fraction": 0.7551502871, "num_tokens": 738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22815651265736978, "lm_q2_score": 0.018546564037447796, "lm_q1q2_score": 0.004231519372560677}}
{"text": "#if !defined(fvSupport_h)\n#define fvSupport_h\n\n#include <petsc.h>\n\nPETSC_EXTERN PetscErrorCode DMPlexReconstructGradientsFVM_MulfiField(DM dm, PetscFV fvm,  Vec locX, Vec grad);\nPETSC_EXTERN PetscErrorCode DMPlexGetDataFVM_MulfiField(DM dm, PetscFV fv, Vec *cellgeom, Vec *facegeom, DM *gradDM);\n\n#endif", "meta": {"hexsha": "46af1cef8747172cb543c74b3f02f635bb4d7908", "size": 303, "ext": "h", "lang": "C", "max_stars_repo_path": "ablateCore/flow/fvSupport.h", "max_stars_repo_name": "pakserep/ablate", "max_stars_repo_head_hexsha": "8c8443de8a252b03b3535f7c48b7a50aac1e56e4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ablateCore/flow/fvSupport.h", "max_issues_repo_name": "pakserep/ablate", "max_issues_repo_head_hexsha": "8c8443de8a252b03b3535f7c48b7a50aac1e56e4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ablateCore/flow/fvSupport.h", "max_forks_repo_name": "pakserep/ablate", "max_forks_repo_head_hexsha": "8c8443de8a252b03b3535f7c48b7a50aac1e56e4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6666666667, "max_line_length": 117, "alphanum_fraction": 0.8085808581, "num_tokens": 95, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.2200070895174993, "lm_q2_score": 0.01912403545810631, "lm_q1q2_score": 0.004207423380967426}}
{"text": "#pragma once\n\n#include <halley/maths/vector2.h>\n#include <halley/time/halleytime.h>\n#include <halley/core/graphics/sprite/sprite.h>\n#include <gsl/gsl>\n#include <thread>\n#include <mutex>\n#include <atomic>\n\nnamespace Halley\n{\n\tclass RenderContext;\n\tclass TextureDescriptor;\n\tclass VideoAPI;\n\tclass AudioAPI;\n\tclass StreamingAudioClip;\n\tclass IAudioHandle;\n\tclass TextureRenderTarget;\n\n\tenum class MoviePlayerState\n\t{\n\t\tUninitialised,\n\t\tLoading,\n\t\tPaused,\n\t\tStartingToPlay,\n\t\tPlaying,\n\t\tFinished\n\t};\n\n\tenum class MoviePlayerStreamType\n\t{\n\t\tUnknown,\n\t\tVideo,\n\t\tAudio,\n\t\tOther\n\t};\n\n\tclass MoviePlayerStream\n\t{\n\tpublic:\n\t\tMoviePlayerStreamType type = MoviePlayerStreamType::Unknown;\n\t\tbool playing = true;\n\t\tbool eof = false;\n\t};\n\n\tstruct PendingFrame\n\t{\n\t\tstd::shared_ptr<Texture> texture;\n\t\tTime time;\n\t};\n\n\tstruct MoviePlayerAliveFlag\n\t{\n\t\tbool isAlive = true;\n\t\tmutable std::mutex mutex;\n\t};\n\t\n\tclass MoviePlayer\n\t{\n\tpublic:\n\t\tMoviePlayer(VideoAPI& video, AudioAPI& audio);\n\t\tvirtual ~MoviePlayer();\n\n\t\tvoid play();\n\t\tvoid pause();\n\t\tvoid reset();\n\t\tvoid stop();\n\n\t\tvirtual bool hasError() const;\n\n\t\tvirtual void update(Time t);\n\t\tvoid render(Resources& resources, RenderContext& rc);\n\t\tSprite getSprite(Resources& resources);\n\n\t\tMoviePlayerState getState() const;\n\t\tVector2i getSize() const;\n\n\tprotected:\n\t\tvirtual void requestVideoFrame() = 0;\n\t\tvirtual void requestAudioFrame() = 0;\n\t\tvirtual void onReset();\n\t\tvirtual void onStartPlay();\n\t\tvirtual void waitForVideoInfo();\n\t\tvirtual bool needsYV12Conversion() const;\n\t\tvirtual bool shouldRecycleTextures() const;\n\t\tvirtual void onDoneUsingTexture(std::shared_ptr<Texture> texture);\n\t\tvirtual Rect4i getCropRect() const;\n\t\t\n\t\tvoid setVideoSize(Vector2i size);\n\n\t\tVideoAPI& getVideoAPI() const;\n\t\tAudioAPI& getAudioAPI() const;\n\n\t\tvoid onVideoFrameAvailable(Time time, TextureDescriptor&& descriptor);\n\t\tvoid onVideoFrameAvailable(Time time, std::shared_ptr<Texture> texture);\n\t\tvoid onAudioFrameAvailable(Time time, gsl::span<const short> samples);\n\t\tvoid onAudioFrameAvailable(Time time, gsl::span<const float> samples);\n\n\t\tstd::shared_ptr<MoviePlayerAliveFlag> getAliveFlag() const;\n\n\t\tstd::vector<MoviePlayerStream> streams;\n\t\tstd::list<std::shared_ptr<Texture>> recycleTexture;\n\t\tstd::list<PendingFrame> pendingFrames;\n\t\tint maxVideoFrames;\n\t\tint maxAudioSamples;\n\n\tprivate:\n\t\tVideoAPI& video;\n\t\tAudioAPI& audio;\n\n\t\tMoviePlayerState state = MoviePlayerState::Uninitialised;\n\n\t\tVector2i videoSize;\n\t\tstd::shared_ptr<Texture> currentTexture;\n\t\tstd::shared_ptr<TextureRenderTarget> renderTarget;\n\t\tstd::shared_ptr<Texture> renderTexture;\n\n\t\tstd::shared_ptr<StreamingAudioClip> streamingClip;\n\t\tstd::shared_ptr<IAudioHandle> audioHandle;\n\n\t\tstd::atomic<bool> threadRunning;\n\t\tstd::atomic<bool> threadAborted;\n\t\tstd::thread workerThread;\n\t\tstd::shared_ptr<MoviePlayerAliveFlag> aliveFlag;\n\n\t\tTime time = 0;\n\n\t\tvoid startThread();\n\t\tvoid stopThread();\n\t\tvoid threadEntry();\n\n\t\tvirtual bool useCustomThreads() const;\n\t\tvirtual void stopCustomThreads();\n\n\t\tbool needsMoreVideoFrames() const;\n\t\tbool needsMoreAudioFrames() const;\n\t};\n}\n\n", "meta": {"hexsha": "cff2dbf6798721f85a293f3f1341ce3ea8cecb75", "size": 3083, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engine/core/include/halley/core/graphics/movie/movie_player.h", "max_stars_repo_name": "sunhay/halley", "max_stars_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3262.0, "max_stars_repo_stars_event_min_datetime": "2016-04-10T15:24:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:47:08.000Z", "max_issues_repo_path": "src/engine/core/include/halley/core/graphics/movie/movie_player.h", "max_issues_repo_name": "sunhay/halley", "max_issues_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 53.0, "max_issues_repo_issues_event_min_datetime": "2016-10-09T16:25:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-10T13:52:37.000Z", "max_forks_repo_path": "src/engine/core/include/halley/core/graphics/movie/movie_player.h", "max_forks_repo_name": "sunhay/halley", "max_forks_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 193.0, "max_forks_repo_forks_event_min_datetime": "2017-10-23T06:08:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T12:59:58.000Z", "avg_line_length": 21.865248227, "max_line_length": 74, "alphanum_fraction": 0.7469996756, "num_tokens": 782, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20689406837681013, "lm_q2_score": 0.02033235378788196, "lm_q1q2_score": 0.004206643394851544}}
{"text": "\ufeff#pragma once\n\n#define NOMINMAX\n#include <windows.h>\n\n#include <unknwn.h>\n#include <restrictederrorinfo.h>\n#include <hstring.h>\n#include <MemoryBuffer.h>\n\n// DirectX\n#include <windows.ui.xaml.media.dxinterop.h>\n#include <d3d11.h>\n#include <dxgi.h>\n#include <dxgi1_2.h>\n#include <dxgi1_3.h>\n#include <DirectXMath.h>\n\n// C++/WinRT\n#include \"winrt/Microsoft.UI.Xaml.Automation.Peers.h\"\n#include \"winrt/Microsoft.UI.Xaml.Controls.Primitives.h\"\n#include \"winrt/Microsoft.UI.Xaml.Media.h\"\n#include \"winrt/Microsoft.UI.Xaml.XamlTypeInfo.h\"\n#include \"winrt/Windows.ApplicationModel.h\"\n#include \"winrt/Windows.ApplicationModel.Activation.h\"\n#include \"winrt/Windows.ApplicationModel.Resources.h\"\n#include \"winrt/Windows.Foundation.h\"\n#include \"winrt/Windows.Foundation.Collections.h\"\n#include \"winrt/Windows.Globalization.NumberFormatting.h\"\n#include \"winrt/Windows.Media.h\"\n#include \"winrt/Windows.Media.Audio.h\"\n#include \"winrt/Windows.Media.MediaProperties.h\"\n#include \"winrt/Windows.Media.Render.h\"\n#include \"winrt/Windows.Storage.h\"\n#include \"winrt/Windows.Storage.Pickers.h\"\n#include \"winrt/Windows.Storage.Streams.h\"\n#include \"winrt/Windows.System.Threading.h\"\n#include \"winrt/Windows.UI.Core.h\"\n#include \"winrt/Windows.UI.Xaml.h\"\n#include \"winrt/Windows.UI.Xaml.Controls.h\"\n#include \"winrt/Windows.UI.Xaml.Controls.Primitives.h\"\n#include \"winrt/Windows.UI.Xaml.Data.h\"\n#include \"winrt/Windows.UI.Xaml.Documents.h\"\n#include \"winrt/Windows.UI.Xaml.Interop.h\"\n#include \"winrt/Windows.UI.Xaml.Input.h\"\n#include \"winrt/Windows.UI.Xaml.Markup.h\"\n#include \"winrt/Windows.UI.Xaml.Navigation.h\"\n\n#include <algorithm>\n#include <array>\n#include <chrono>\n#include <cmath>\n#include <cstddef>\n#include <cstdint>\n#include <mutex>\n#include <optional>\n#include <string>\n#include <string_view>\n#include <stdexcept>\n#include <thread>\n#include <sstream>\n\n#include <gsl/gsl>\n", "meta": {"hexsha": "d82c15c5518716692a12877a45c0534490d84cb5", "size": 1852, "ext": "h", "lang": "C", "max_stars_repo_path": "gc8/Gc8/pch.h", "max_stars_repo_name": "greg904/gc8", "max_stars_repo_head_hexsha": "a5171858351c19cf09001fbd22c08723a7a4b126", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gc8/Gc8/pch.h", "max_issues_repo_name": "greg904/gc8", "max_issues_repo_head_hexsha": "a5171858351c19cf09001fbd22c08723a7a4b126", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-04-12T21:20:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-29T08:21:32.000Z", "max_forks_repo_path": "gc8/Gc8/pch.h", "max_forks_repo_name": "greg904/gc8", "max_forks_repo_head_hexsha": "a5171858351c19cf09001fbd22c08723a7a4b126", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9375, "max_line_length": 57, "alphanum_fraction": 0.7688984881, "num_tokens": 464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20689404881588813, "lm_q2_score": 0.020332351153644807, "lm_q1q2_score": 0.0042066424521239685}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n//\n// Copyright (c) 2015 Microsoft Corporation. All rights reserved.\n//\n// This code is licensed under the MIT License (MIT).\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef GSL_SPAN_H\n#define GSL_SPAN_H\n\n#include <gsl/gsl_assert> // for Expects\n#include <gsl/gsl_byte>   // for byte\n#include <gsl/gsl_util>   // for narrow_cast, narrow\n\n#include <algorithm> // for lexicographical_compare\n#include <array>     // for array\n#include <cstddef>   // for ptrdiff_t, size_t, nullptr_t\n#include <iterator>  // for reverse_iterator, distance, random_access_...\n#include <limits>\n#include <stdexcept>\n#include <type_traits> // for enable_if_t, declval, is_convertible, inte...\n#include <utility>\n#include <memory> // for std::addressof\n\n#ifdef _MSC_VER\n#pragma warning(push)\n\n// turn off some warnings that are noisy about our Expects statements\n#pragma warning(disable : 4127) // conditional expression is constant\n#pragma warning(disable : 4702) // unreachable code\n\n// Turn MSVC /analyze rules that generate too much noise. TODO: fix in the tool.\n#pragma warning(disable : 26495) // uninitalized member when constructor calls constructor\n#pragma warning(disable : 26446) // parser bug does not allow attributes on some templates\n\n#if _MSC_VER < 1910\n#pragma push_macro(\"constexpr\")\n#define constexpr /*constexpr*/\n#define GSL_USE_STATIC_CONSTEXPR_WORKAROUND\n\n#endif // _MSC_VER < 1910\n#endif // _MSC_VER\n\n// See if we have enough C++17 power to use a static constexpr data member\n// without needing an out-of-line definition\n#if !(defined(__cplusplus) && (__cplusplus >= 201703L))\n#define GSL_USE_STATIC_CONSTEXPR_WORKAROUND\n#endif // !(defined(__cplusplus) && (__cplusplus >= 201703L))\n\n// GCC 7 does not like the signed unsigned missmatch (size_t ptrdiff_t)\n// While there is a conversion from signed to unsigned, it happens at\n// compiletime, so the compiler wouldn't have to warn indiscriminently, but\n// could check if the source value actually doesn't fit into the target type\n// and only warn in those cases.\n#if __GNUC__ > 6\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wsign-conversion\"\n#endif\n\nnamespace gsl\n{\n\n// [views.constants], constants\nconstexpr const std::ptrdiff_t dynamic_extent = -1;\n\ntemplate <class ElementType, std::ptrdiff_t Extent = dynamic_extent>\nclass span;\n\n// implementation details\nnamespace details\n{\n    template <class T>\n    struct is_span_oracle : std::false_type\n    {\n    };\n\n    template <class ElementType, std::ptrdiff_t Extent>\n    struct is_span_oracle<gsl::span<ElementType, Extent>> : std::true_type\n    {\n    };\n\n    template <class T>\n    struct is_span : public is_span_oracle<std::remove_cv_t<T>>\n    {\n    };\n\n    template <class T>\n    struct is_std_array_oracle : std::false_type\n    {\n    };\n\n    template <class ElementType, std::size_t Extent>\n    struct is_std_array_oracle<std::array<ElementType, Extent>> : std::true_type\n    {\n    };\n\n    template <class T>\n    struct is_std_array : public is_std_array_oracle<std::remove_cv_t<T>>\n    {\n    };\n\n    template <std::ptrdiff_t From, std::ptrdiff_t To>\n    struct is_allowed_extent_conversion\n        : public std::integral_constant<bool, From == To || From == gsl::dynamic_extent ||\n                                                  To == gsl::dynamic_extent>\n    {\n    };\n\n    template <class From, class To>\n    struct is_allowed_element_type_conversion\n        : public std::integral_constant<bool, std::is_convertible<From (*)[], To (*)[]>::value>\n    {\n    };\n\n    template <class Span, bool IsConst>\n    class span_iterator\n    {\n        using element_type_ = typename Span::element_type;\n\n    public:\n#ifdef _MSC_VER\n        // Tell Microsoft standard library that span_iterators are checked.\n        using _Unchecked_type = typename Span::pointer;\n#endif\n\n        using iterator_category = std::random_access_iterator_tag;\n        using value_type = std::remove_cv_t<element_type_>;\n        using difference_type = typename Span::index_type;\n\n        using reference = std::conditional_t<IsConst, const element_type_, element_type_>&;\n        using pointer = std::add_pointer_t<reference>;\n\n        span_iterator() = default;\n\n        constexpr span_iterator(const Span* span, typename Span::index_type idx) noexcept\n            : span_(span), index_(idx)\n        {}\n\n        friend span_iterator<Span, true>;\n        template <bool B, std::enable_if_t<!B && IsConst>* = nullptr>\n        constexpr span_iterator(const span_iterator<Span, B>& other) noexcept\n            : span_iterator(other.span_, other.index_)\n        {}\n\n        GSL_SUPPRESS(bounds.1) // NO-FORMAT: attribute\n        constexpr reference operator*() const\n        {\n            Expects(index_ != span_->size());\n            return *(span_->data() + index_);\n        }\n\n        constexpr pointer operator->() const\n        {\n            Expects(index_ != span_->size());\n            return span_->data() + index_;\n        }\n\n        constexpr span_iterator& operator++()\n        {\n            Expects(0 <= index_ && index_ != span_->size());\n            ++index_;\n            return *this;\n        }\n\n        constexpr span_iterator operator++(int)\n        {\n            auto ret = *this;\n            ++(*this);\n            return ret;\n        }\n\n        constexpr span_iterator& operator--()\n        {\n            Expects(index_ != 0 && index_ <= span_->size());\n            --index_;\n            return *this;\n        }\n\n        constexpr span_iterator operator--(int)\n        {\n            auto ret = *this;\n            --(*this);\n            return ret;\n        }\n\n        constexpr span_iterator operator+(difference_type n) const\n        {\n            auto ret = *this;\n            return ret += n;\n        }\n\n        friend constexpr span_iterator operator+(difference_type n, span_iterator const& rhs)\n        {\n            return rhs + n;\n        }\n\n        constexpr span_iterator& operator+=(difference_type n)\n        {\n            Expects((index_ + n) >= 0 && (index_ + n) <= span_->size());\n            index_ += n;\n            return *this;\n        }\n\n        constexpr span_iterator operator-(difference_type n) const\n        {\n            auto ret = *this;\n            return ret -= n;\n        }\n\n        constexpr span_iterator& operator-=(difference_type n) { return *this += -n; }\n\n        constexpr difference_type operator-(span_iterator rhs) const\n        {\n            Expects(span_ == rhs.span_);\n            return index_ - rhs.index_;\n        }\n\n        constexpr reference operator[](difference_type n) const { return *(*this + n); }\n\n        constexpr friend bool operator==(span_iterator lhs, span_iterator rhs) noexcept\n        {\n            return lhs.span_ == rhs.span_ && lhs.index_ == rhs.index_;\n        }\n\n        constexpr friend bool operator!=(span_iterator lhs, span_iterator rhs) noexcept\n        {\n            return !(lhs == rhs);\n        }\n\n        constexpr friend bool operator<(span_iterator lhs, span_iterator rhs) noexcept\n        {\n            return lhs.index_ < rhs.index_;\n        }\n\n        constexpr friend bool operator<=(span_iterator lhs, span_iterator rhs) noexcept\n        {\n            return !(rhs < lhs);\n        }\n\n        constexpr friend bool operator>(span_iterator lhs, span_iterator rhs) noexcept\n        {\n            return rhs < lhs;\n        }\n\n        constexpr friend bool operator>=(span_iterator lhs, span_iterator rhs) noexcept\n        {\n            return !(rhs > lhs);\n        }\n\n#ifdef _MSC_VER\n        // MSVC++ iterator debugging support; allows STL algorithms in 15.8+\n        // to unwrap span_iterator to a pointer type after a range check in STL\n        // algorithm calls\n        friend constexpr void _Verify_range(span_iterator lhs, span_iterator rhs) noexcept\n        { // test that [lhs, rhs) forms a valid range inside an STL algorithm\n            Expects(lhs.span_ == rhs.span_        // range spans have to match\n                    && lhs.index_ <= rhs.index_); // range must not be transposed\n        }\n\n        constexpr void _Verify_offset(const difference_type n) const noexcept\n        { // test that the iterator *this + n is a valid range in an STL\n            // algorithm call\n            Expects((index_ + n) >= 0 && (index_ + n) <= span_->size());\n        }\n\n        GSL_SUPPRESS(bounds.1) // NO-FORMAT: attribute\n        constexpr pointer _Unwrapped() const noexcept\n        { // after seeking *this to a high water mark, or using one of the\n            // _Verify_xxx functions above, unwrap this span_iterator to a raw\n            // pointer\n            return span_->data() + index_;\n        }\n\n        // Tell the STL that span_iterator should not be unwrapped if it can't\n        // validate in advance, even in release / optimized builds:\n#if defined(GSL_USE_STATIC_CONSTEXPR_WORKAROUND)\n        static constexpr const bool _Unwrap_when_unverified = false;\n#else\n        static constexpr bool _Unwrap_when_unverified = false;\n#endif\n        GSL_SUPPRESS(con.3) // NO-FORMAT: attribute // TODO: false positive\n        constexpr void _Seek_to(const pointer p) noexcept\n        { // adjust the position of *this to previously verified location p\n            // after _Unwrapped\n            index_ = p - span_->data();\n        }\n#endif\n\n    protected:\n        const Span* span_ = nullptr;\n        std::ptrdiff_t index_ = 0;\n    };\n\n    template <std::ptrdiff_t Ext>\n    class extent_type\n    {\n    public:\n        using index_type = std::ptrdiff_t;\n\n        static_assert(Ext >= 0, \"A fixed-size span must be >= 0 in size.\");\n\n        constexpr extent_type() noexcept {}\n\n        template <index_type Other>\n        constexpr extent_type(extent_type<Other> ext)\n        {\n            static_assert(Other == Ext || Other == dynamic_extent,\n                          \"Mismatch between fixed-size extent and size of initializing data.\");\n            Expects(ext.size() == Ext);\n        }\n\n        constexpr extent_type(index_type size) { Expects(size == Ext); }\n\n        constexpr index_type size() const noexcept { return Ext; }\n    };\n\n    template <>\n    class extent_type<dynamic_extent>\n    {\n    public:\n        using index_type = std::ptrdiff_t;\n\n        template <index_type Other>\n        explicit constexpr extent_type(extent_type<Other> ext) : size_(ext.size())\n        {}\n\n        explicit constexpr extent_type(index_type size) : size_(size) { Expects(size >= 0); }\n\n        constexpr index_type size() const noexcept { return size_; }\n\n    private:\n        index_type size_;\n    };\n\n    template <class ElementType, std::ptrdiff_t Extent, std::ptrdiff_t Offset, std::ptrdiff_t Count>\n    struct calculate_subspan_type\n    {\n        using type = span<ElementType, Count != dynamic_extent\n                                           ? Count\n                                           : (Extent != dynamic_extent ? Extent - Offset : Extent)>;\n    };\n} // namespace details\n\n// [span], class template span\ntemplate <class ElementType, std::ptrdiff_t Extent>\nclass span\n{\npublic:\n    // constants and types\n    using element_type = ElementType;\n    using value_type = std::remove_cv_t<ElementType>;\n    using index_type = std::ptrdiff_t;\n    using pointer = element_type*;\n    using reference = element_type&;\n\n    using iterator = details::span_iterator<span<ElementType, Extent>, false>;\n    using const_iterator = details::span_iterator<span<ElementType, Extent>, true>;\n    using reverse_iterator = std::reverse_iterator<iterator>;\n    using const_reverse_iterator = std::reverse_iterator<const_iterator>;\n\n    using size_type = index_type;\n\n#if defined(GSL_USE_STATIC_CONSTEXPR_WORKAROUND)\n    static constexpr const index_type extent{Extent};\n#else\n    static constexpr index_type extent{Extent};\n#endif\n\n    // [span.cons], span constructors, copy, assignment, and destructor\n    template <bool Dependent = false,\n              // \"Dependent\" is needed to make \"std::enable_if_t<Dependent || Extent <= 0>\" SFINAE,\n              // since \"std::enable_if_t<Extent <= 0>\" is ill-formed when Extent is greater than 0.\n              class = std::enable_if_t<(Dependent || Extent <= 0)>>\n    constexpr span() noexcept : storage_(nullptr, details::extent_type<0>())\n    {}\n\n    constexpr span(pointer ptr, index_type count) : storage_(ptr, count) {}\n\n    constexpr span(pointer firstElem, pointer lastElem)\n        : storage_(firstElem, std::distance(firstElem, lastElem))\n    {}\n\n    template <std::size_t N>\n    constexpr span(element_type (&arr)[N]) noexcept\n        : storage_(KnownNotNull{std::addressof(arr[0])}, details::extent_type<N>())\n    {}\n\n    template <std::size_t N, class = std::enable_if_t<(N > 0)>>\n    constexpr span(std::array<std::remove_const_t<element_type>, N>& arr) noexcept\n        : storage_(KnownNotNull{arr.data()}, details::extent_type<N>())\n    {\n    }\n\n    constexpr span(std::array<std::remove_const_t<element_type>, 0>&) noexcept\n        : storage_(static_cast<pointer>(nullptr), details::extent_type<0>())\n    {\n    }\n\n    template <std::size_t N, class = std::enable_if_t<(N > 0)>>\n    constexpr span(const std::array<std::remove_const_t<element_type>, N>& arr) noexcept\n        : storage_(KnownNotNull{arr.data()}, details::extent_type<N>())\n    {\n    }\n\n    constexpr span(const std::array<std::remove_const_t<element_type>, 0>&) noexcept\n        : storage_(static_cast<pointer>(nullptr), details::extent_type<0>())\n    {\n    }\n\n    // NB: the SFINAE here uses .data() as a incomplete/imperfect proxy for the requirement\n    // on Container to be a contiguous sequence container.\n    template <class Container,\n              class = std::enable_if_t<\n                  !details::is_span<Container>::value && !details::is_std_array<Container>::value &&\n                  std::is_convertible<typename Container::pointer, pointer>::value &&\n                  std::is_convertible<typename Container::pointer,\n                                      decltype(std::declval<Container>().data())>::value>>\n    constexpr span(Container& cont) : span(cont.data(), narrow<index_type>(cont.size()))\n    {}\n\n    template <class Container,\n              class = std::enable_if_t<\n                  std::is_const<element_type>::value && !details::is_span<Container>::value &&\n                  std::is_convertible<typename Container::pointer, pointer>::value &&\n                  std::is_convertible<typename Container::pointer,\n                                      decltype(std::declval<Container>().data())>::value>>\n    constexpr span(const Container& cont) : span(cont.data(), narrow<index_type>(cont.size()))\n    {}\n\n    constexpr span(const span& other) noexcept = default;\n\n    template <\n        class OtherElementType, std::ptrdiff_t OtherExtent,\n        class = std::enable_if_t<\n            details::is_allowed_extent_conversion<OtherExtent, Extent>::value &&\n            details::is_allowed_element_type_conversion<OtherElementType, element_type>::value>>\n    constexpr span(const span<OtherElementType, OtherExtent>& other)\n        : storage_(other.data(), details::extent_type<OtherExtent>(other.size()))\n    {}\n\n    ~span() noexcept = default;\n    constexpr span& operator=(const span& other) noexcept = default;\n\n    // [span.sub], span subviews\n    template <std::ptrdiff_t Count>\n    constexpr span<element_type, Count> first() const\n    {\n        Expects(Count >= 0 && Count <= size());\n        return {data(), Count};\n    }\n\n    template <std::ptrdiff_t Count>\n    GSL_SUPPRESS(bounds.1) // NO-FORMAT: attribute\n    constexpr span<element_type, Count> last() const\n    {\n        Expects(Count >= 0 && size() - Count >= 0);\n        return {data() + (size() - Count), Count};\n    }\n\n    template <std::ptrdiff_t Offset, std::ptrdiff_t Count = dynamic_extent>\n    GSL_SUPPRESS(bounds.1) // NO-FORMAT: attribute\n    constexpr auto subspan() const ->\n        typename details::calculate_subspan_type<ElementType, Extent, Offset, Count>::type\n    {\n        Expects((Offset >= 0 && size() - Offset >= 0) &&\n                (Count == dynamic_extent || (Count >= 0 && Offset + Count <= size())));\n\n        return {data() + Offset, Count == dynamic_extent ? size() - Offset : Count};\n    }\n\n    constexpr span<element_type, dynamic_extent> first(index_type count) const\n    {\n        Expects(count >= 0 && count <= size());\n        return {data(), count};\n    }\n\n    constexpr span<element_type, dynamic_extent> last(index_type count) const\n    {\n        return make_subspan(size() - count, dynamic_extent, subspan_selector<Extent>{});\n    }\n\n    constexpr span<element_type, dynamic_extent> subspan(index_type offset,\n                                                         index_type count = dynamic_extent) const\n    {\n        return make_subspan(offset, count, subspan_selector<Extent>{});\n    }\n\n    // [span.obs], span observers\n    constexpr index_type size() const noexcept { return storage_.size(); }\n    constexpr index_type size_bytes() const noexcept\n    {\n        return size() * narrow_cast<index_type>(sizeof(element_type));\n    }\n    constexpr bool empty() const noexcept { return size() == 0; }\n\n    // [span.elem], span element access\n    GSL_SUPPRESS(bounds.1) // NO-FORMAT: attribute\n    constexpr reference operator[](index_type idx) const\n    {\n        Expects(CheckRange(idx, storage_.size()));\n        return data()[idx];\n    }\n\n    constexpr reference at(index_type idx) const { return this->operator[](idx); }\n    constexpr reference operator()(index_type idx) const { return this->operator[](idx); }\n    constexpr pointer data() const noexcept { return storage_.data(); }\n\n    // [span.iter], span iterator support\n    constexpr iterator begin() const noexcept { return {this, 0}; }\n    constexpr iterator end() const noexcept { return {this, size()}; }\n\n    constexpr const_iterator cbegin() const noexcept { return {this, 0}; }\n    constexpr const_iterator cend() const noexcept { return {this, size()}; }\n\n    constexpr reverse_iterator rbegin() const noexcept { return reverse_iterator{end()}; }\n    constexpr reverse_iterator rend() const noexcept { return reverse_iterator{begin()}; }\n\n    constexpr const_reverse_iterator crbegin() const noexcept\n    {\n        return const_reverse_iterator{cend()};\n    }\n    constexpr const_reverse_iterator crend() const noexcept\n    {\n        return const_reverse_iterator{cbegin()};\n    }\n\n#ifdef _MSC_VER\n    // Tell MSVC how to unwrap spans in range-based-for\n    constexpr pointer _Unchecked_begin() const noexcept { return data(); }\n    constexpr pointer _Unchecked_end() const noexcept\n    {\n        GSL_SUPPRESS(bounds.1) // NO-FORMAT: attribute\n        return data() + size();\n    }\n#endif // _MSC_VER\n\nprivate:\n    static bool CheckRange(index_type idx, index_type size)\n    {\n        // Optimization:\n        //\n        // idx >= 0 && idx < size\n        // =>\n        // static_cast<size_t>(idx) < static_cast<size_t>(size)\n        //\n        // because size >=0 by span construction, and negative idx will\n        // wrap around to a value always greater than size when casted.\n\n        // check if we have enough space to wrap around\n        if (sizeof(index_type) <= sizeof(size_t))\n        {\n            return narrow_cast<size_t>(idx) < narrow_cast<size_t>(size);\n        }\n        else\n        {\n            return idx >= 0 && idx < size;\n        }\n    }\n\n    // Needed to remove unnecessary null check in subspans\n    struct KnownNotNull\n    {\n        pointer p;\n    };\n\n    // this implementation detail class lets us take advantage of the\n    // empty base class optimization to pay for only storage of a single\n    // pointer in the case of fixed-size spans\n    template <class ExtentType>\n    class storage_type : public ExtentType\n    {\n    public:\n        // KnownNotNull parameter is needed to remove unnecessary null check\n        // in subspans and constructors from arrays\n        template <class OtherExtentType>\n        constexpr storage_type(KnownNotNull data, OtherExtentType ext)\n            : ExtentType(ext), data_(data.p)\n        {\n            Expects(ExtentType::size() >= 0);\n        }\n\n        template <class OtherExtentType>\n        constexpr storage_type(pointer data, OtherExtentType ext) : ExtentType(ext), data_(data)\n        {\n            Expects(ExtentType::size() >= 0);\n            Expects(data || ExtentType::size() == 0);\n        }\n\n        constexpr pointer data() const noexcept { return data_; }\n\n    private:\n        pointer data_;\n    };\n\n    storage_type<details::extent_type<Extent>> storage_;\n\n    // The rest is needed to remove unnecessary null check\n    // in subspans and constructors from arrays\n    constexpr span(KnownNotNull ptr, index_type count) : storage_(ptr, count) {}\n\n    template <std::ptrdiff_t CallerExtent>\n    class subspan_selector\n    {\n    };\n\n    template <std::ptrdiff_t CallerExtent>\n    span<element_type, dynamic_extent> make_subspan(index_type offset, index_type count,\n                                                    subspan_selector<CallerExtent>) const\n    {\n        const span<element_type, dynamic_extent> tmp(*this);\n        return tmp.subspan(offset, count);\n    }\n\n    GSL_SUPPRESS(bounds.1) // NO-FORMAT: attribute\n    span<element_type, dynamic_extent> make_subspan(index_type offset, index_type count,\n                                                    subspan_selector<dynamic_extent>) const\n    {\n        Expects(offset >= 0 && size() - offset >= 0);\n\n        if (count == dynamic_extent) { return {KnownNotNull{data() + offset}, size() - offset}; }\n\n        Expects(count >= 0 && size() - offset >= count);\n        return {KnownNotNull{data() + offset}, count};\n    }\n};\n\n#if defined(GSL_USE_STATIC_CONSTEXPR_WORKAROUND)\ntemplate <class ElementType, std::ptrdiff_t Extent>\nconstexpr const typename span<ElementType, Extent>::index_type span<ElementType, Extent>::extent;\n#endif\n\n// [span.comparison], span comparison operators\ntemplate <class ElementType, std::ptrdiff_t FirstExtent, std::ptrdiff_t SecondExtent>\nconstexpr bool operator==(span<ElementType, FirstExtent> l, span<ElementType, SecondExtent> r)\n{\n    return std::equal(l.begin(), l.end(), r.begin(), r.end());\n}\n\ntemplate <class ElementType, std::ptrdiff_t Extent>\nconstexpr bool operator!=(span<ElementType, Extent> l, span<ElementType, Extent> r)\n{\n    return !(l == r);\n}\n\ntemplate <class ElementType, std::ptrdiff_t Extent>\nconstexpr bool operator<(span<ElementType, Extent> l, span<ElementType, Extent> r)\n{\n    return std::lexicographical_compare(l.begin(), l.end(), r.begin(), r.end());\n}\n\ntemplate <class ElementType, std::ptrdiff_t Extent>\nconstexpr bool operator<=(span<ElementType, Extent> l, span<ElementType, Extent> r)\n{\n    return !(l > r);\n}\n\ntemplate <class ElementType, std::ptrdiff_t Extent>\nconstexpr bool operator>(span<ElementType, Extent> l, span<ElementType, Extent> r)\n{\n    return r < l;\n}\n\ntemplate <class ElementType, std::ptrdiff_t Extent>\nconstexpr bool operator>=(span<ElementType, Extent> l, span<ElementType, Extent> r)\n{\n    return !(l < r);\n}\n\nnamespace details\n{\n    // if we only supported compilers with good constexpr support then\n    // this pair of classes could collapse down to a constexpr function\n\n    // we should use a narrow_cast<> to go to std::size_t, but older compilers may not see it as\n    // constexpr\n    // and so will fail compilation of the template\n    template <class ElementType, std::ptrdiff_t Extent>\n    struct calculate_byte_size\n        : std::integral_constant<std::ptrdiff_t,\n                                 static_cast<std::ptrdiff_t>(sizeof(ElementType) *\n                                                             static_cast<std::size_t>(Extent))>\n    {\n    };\n\n    template <class ElementType>\n    struct calculate_byte_size<ElementType, dynamic_extent>\n        : std::integral_constant<std::ptrdiff_t, dynamic_extent>\n    {\n    };\n} // namespace details\n\n// [span.objectrep], views of object representation\ntemplate <class ElementType, std::ptrdiff_t Extent>\nspan<const byte, details::calculate_byte_size<ElementType, Extent>::value>\nas_bytes(span<ElementType, Extent> s) noexcept\n{\n    GSL_SUPPRESS(type.1) // NO-FORMAT: attribute\n    return {reinterpret_cast<const byte*>(s.data()), s.size_bytes()};\n}\n\ntemplate <class ElementType, std::ptrdiff_t Extent,\n          class = std::enable_if_t<!std::is_const<ElementType>::value>>\nspan<byte, details::calculate_byte_size<ElementType, Extent>::value>\nas_writeable_bytes(span<ElementType, Extent> s) noexcept\n{\n    GSL_SUPPRESS(type.1) // NO-FORMAT: attribute\n    return {reinterpret_cast<byte*>(s.data()), s.size_bytes()};\n}\n\n//\n// make_span() - Utility functions for creating spans\n//\ntemplate <class ElementType>\nconstexpr span<ElementType> make_span(ElementType* ptr,\n                                      typename span<ElementType>::index_type count)\n{\n    return span<ElementType>(ptr, count);\n}\n\ntemplate <class ElementType>\nconstexpr span<ElementType> make_span(ElementType* firstElem, ElementType* lastElem)\n{\n    return span<ElementType>(firstElem, lastElem);\n}\n\ntemplate <class ElementType, std::size_t N>\nconstexpr span<ElementType, N> make_span(ElementType (&arr)[N]) noexcept\n{\n    return span<ElementType, N>(arr);\n}\n\ntemplate <class Container>\nconstexpr span<typename Container::value_type> make_span(Container& cont)\n{\n    return span<typename Container::value_type>(cont);\n}\n\ntemplate <class Container>\nconstexpr span<const typename Container::value_type> make_span(const Container& cont)\n{\n    return span<const typename Container::value_type>(cont);\n}\n\ntemplate <class Ptr>\nconstexpr span<typename Ptr::element_type> make_span(Ptr& cont, std::ptrdiff_t count)\n{\n    return span<typename Ptr::element_type>(cont, count);\n}\n\ntemplate <class Ptr>\nconstexpr span<typename Ptr::element_type> make_span(Ptr& cont)\n{\n    return span<typename Ptr::element_type>(cont);\n}\n\n// Specialization of gsl::at for span\ntemplate <class ElementType, std::ptrdiff_t Extent>\nconstexpr ElementType& at(span<ElementType, Extent> s, index i)\n{\n    // No bounds checking here because it is done in span::operator[] called below\n    return s[i];\n}\n\n} // namespace gsl\n\n#ifdef _MSC_VER\n#if _MSC_VER < 1910\n#undef constexpr\n#pragma pop_macro(\"constexpr\")\n\n#endif // _MSC_VER < 1910\n\n#pragma warning(pop)\n#endif // _MSC_VER\n\n#if __GNUC__ > 6\n#pragma GCC diagnostic pop\n#endif // __GNUC__ > 6\n\n#endif // GSL_SPAN_H\n", "meta": {"hexsha": "b356ee90ff90ec1ce970341296a7eb6797026029", "size": 26924, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gsl/span.h", "max_stars_repo_name": "Redchards/CVRP", "max_stars_repo_head_hexsha": "f372f2fa06cb374ebdac2f6eee7e6fe297d94103", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-09-01T14:40:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-15T05:01:23.000Z", "max_issues_repo_path": "include/gsl/span.h", "max_issues_repo_name": "Redchards/CVRP", "max_issues_repo_head_hexsha": "f372f2fa06cb374ebdac2f6eee7e6fe297d94103", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gsl/span.h", "max_forks_repo_name": "Redchards/CVRP", "max_forks_repo_head_hexsha": "f372f2fa06cb374ebdac2f6eee7e6fe297d94103", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-02T17:50:23.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-26T08:25:35.000Z", "avg_line_length": 34.0810126582, "max_line_length": 100, "alphanum_fraction": 0.6422151241, "num_tokens": 6022, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16451646699291614, "lm_q2_score": 0.02556521267042821, "lm_q1q2_score": 0.004205898466461384}}
{"text": "#pragma once\n\n#include <gsl.h>\n\n\n#include <QmitkAbstractView.h>\n\n#include \"ui_SolverSetupView.h\"\n#include \"ui_BoundaryConditionTypeSelectionDialog.h\"\n\n#include <HierarchyManager.h>\n\n#include <ImmutableRanges.h>\n\n#include \"SolverStudyUIDsTableModel.h\"\n\nnamespace crimson\n{\nclass ISolverSetupManager;\n}\n\n/*! \\brief   SolverSetupView allows the user to set up the solver and to write the prepared simulation to disk. */\nclass SolverSetupView : public QmitkAbstractView\n{\n    Q_OBJECT\n\npublic:\n    static const std::string VIEW_ID;\n\n    SolverSetupView();\n    ~SolverSetupView();\n\n    void OnSelectionChanged(berry::IWorkbenchPart::Pointer source, const QList<mitk::DataNode::Pointer>& nodes) override;\n    void NodeRemoved(const mitk::DataNode* node) override;\n    void NodeChanged(const mitk::DataNode* node) override;\n\nprivate slots:\n    void writeSolverSetup();\n\tvoid runSimulation();\n    void loadSolution();\n    void showSolution(bool show);\n    void createSolverRoot();\n    void createSolverParameters();\n    void createSolverStudy();\n    void createBoundaryConditionSet();\n    void createBoundaryCondition();\n    void createMaterial();\n    void showMaterial();\n    void exportMaterials();\n    void setMeshNodeForStudy(const mitk::DataNode*);\n    void setSolverParametersNodeForStudy(const mitk::DataNode*);\n\nprivate:\n    void CreateQtPartControl(QWidget* parent) override;\n    void SetFocus() override;\n\n    void _updateUI();\n\n    template <class T, class... Args>\n    void createSolverObject(mitk::DataNode* ownerNode, Args... additionalArgs);\n\nprivate:\n    // Ui and main widget of this view\n    Ui::SolverSetupWidget _UI;\n\n    void _setCurrentRootNode(mitk::DataNode* node);\n    void _setCurrentSolverRootNode(mitk::DataNode* node);\n\n    void _findCurrentSolverSetupManager();\n\n    void _setCurrentBoundaryConditionSetNode(mitk::DataNode* node);\n    void _setCurrentBoundaryConditionNode(mitk::DataNode* node);\n    void _setCurrentMaterialNode(mitk::DataNode* node);\n    void _setCurrentSolverParametersNode(mitk::DataNode* node);\n    void _setCurrentSolverStudyNode(mitk::DataNode* node);\n    void _setupSolverStudyComboBoxes();\n\n    void _selectDataNode(mitk::DataNode* node);\n\n    void _serviceChanged(const us::ServiceEvent event);\n\n    void _solverStudyNodeModified();\n    unsigned long _solverStudyObserverTag = -1;\n\n    void _ensureApplyToAllWalls(mitk::DataNode* node) const;\n    gsl::cstring_span<> _getTypeNameToCreate(crimson::ImmutableValueRange<gsl::cstring_span<>> options);\n\n    mitk::DataNode* _currentSolverRootNode = nullptr;\n    mitk::DataNode* _currentRootNode = nullptr;\n    crimson::HierarchyManager::NodeType _currentRootNodeType;\n    mitk::DataNode* _currentVesselTreeNode = nullptr;\n    mitk::DataNode* _currentBoundaryConditionSetNode = nullptr;\n    mitk::DataNode* _currentBoundaryConditionNode = nullptr;\n    mitk::DataNode* _currentMaterialNode = nullptr;\n    mitk::DataNode* _currentSolverStudyNode = nullptr;\n    mitk::DataNode* _currentSolverParametersNode = nullptr;\n    mitk::DataNode* _currentSolidNode = nullptr;\n    crimson::ISolverSetupManager* _currentSolverSetupManager = nullptr;\n\n    struct RemoveNodeDeleter {\n        void operator()(mitk::DataNode* node);\n    };\n\n    std::unique_ptr<mitk::DataNode, RemoveNodeDeleter> _materialVisNodePtr;\n\n    Ui::boundaryConditionTypeSelectionDialog _typeSelectionDialogUi;\n    QDialog _typeSelectionDialog;\n\n\n    crimson::SolverStudyUIDsTableModel _solverStudyBCSetsModel;\n    crimson::SolverStudyUIDsTableModel _solverStudyMaterialsModel;\n};\n", "meta": {"hexsha": "55caa98b39d4c40df33472d02d0d57c64a1ab343", "size": 3531, "ext": "h", "lang": "C", "max_stars_repo_path": "Plugins/uk.ac.kcl.SolverSetupView/src/internal/SolverSetupView.h", "max_stars_repo_name": "carthurs/CRIMSONGUI", "max_stars_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-09-17T18:55:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T02:52:38.000Z", "max_issues_repo_path": "Plugins/uk.ac.kcl.SolverSetupView/src/internal/SolverSetupView.h", "max_issues_repo_name": "carthurs/CRIMSONGUI", "max_issues_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Plugins/uk.ac.kcl.SolverSetupView/src/internal/SolverSetupView.h", "max_forks_repo_name": "carthurs/CRIMSONGUI", "max_forks_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-05-19T09:02:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-26T17:39:57.000Z", "avg_line_length": 31.2477876106, "max_line_length": 121, "alphanum_fraction": 0.7570093458, "num_tokens": 854, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22270013882530884, "lm_q2_score": 0.01883313198998053, "lm_q1q2_score": 0.004194141108684029}}
{"text": "/**\n*\\file utils.h\n*\\author weckyy702 (weckyy702@gmail.com)\n*\\brief Utility and core Header file\n*\\date 2021-03-25\n*\n*MIT License\n*Copyright (c) [2021] [Weckyy702 (weckyy702@gmail.com | https://github.com/Weckyy702)]\n*Permission is hereby granted, free of charge, to any person obtaining a copy\n*of this software and associated documentation files (the \"Software\"), to deal\n*in the Software without restriction, including without limitation the rights\n*to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n*copies of the Software, and to permit persons to whom the Software is\n*furnished to do so, subject to the following conditions:\n*\n*The above copyright notice and this permission notice shall be included in all\n*copies or substantial portions of the Software.\n*\n*THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n*IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n*FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n*AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n*LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n*OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n*SOFTWARE.\n*\n*/\n#ifndef RAYCHEL_CORE_H\n#define RAYCHEL_CORE_H\n\n#include <cstdint>\n#include <limits>\n#if !((defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L))\n    #error \"C++(17) compilation is required!\"\n#endif\n\n#include <cassert>\n#include <cmath>\n#include <cstddef>\n#include <gsl/gsl>\n#include <type_traits>\n\n//convenience headers\n#include <memory>\n#include <optional>\n#include <utility>\n#include <vector>\n\n#include \"CMakeSettings.h\"\n#include \"Logger.h\"\n#include \"RaychelMath/constants.h\"\n#include \"RaychelMath/equivalent.h\"\n\n#if defined(__clang__) || defined(__GNUC__)\n    #define RAYCHEL_FUNC_NAME __PRETTY_FUNCTION__\n#elif defined(_MSC_VER)\n    #define RAYCHEL_FUNC_NAME __FUNCSIG__\n#else\n    #error \"Unknown compiler detected!\"\n#endif\n\n#ifdef RAYCHEL_DEBUG\n    #define RAYCHEL_LOG(...) Logger::debug(RAYCHEL_FUNC_NAME, \": \", __VA_ARGS__, '\\n');\n#else\n    #define RAYCHEL_LOG(...)\n#endif\n\n//terminate the application with the provided message\n#ifndef RAYCHEL_NO_LOGGER\n    #define RAYCHEL_TERMINATE(...)                                                                                                                   \\\n        Logger::fatal(RAYCHEL_FUNC_NAME, \" at (\", __FILE__, \":\", __LINE__, \"): \", __VA_ARGS__, '\\n');                                                \\\n        std::exit(0x41);\n#else\n    #define RAYCHEL_TERMINATE(...) std::exit(0x41);\n#endif\n\n#if defined(RAYCHEL_DEBUG) || !defined(NDEBUG)\n    #define RAYCHEL_ASSERT(exp)                                                                                                                      \\\n        if (!(exp)) {                                                                                                                                \\\n            RAYCHEL_TERMINATE(\"Assertion '\", GSL_STRINGIFY(exp), \"' failed!\");                                                                       \\\n        }\n#else\n    #define RAYCHEL_ASSERT(exp) Expects(exp)\n#endif\n\n#define RAYCHEL_ASSERT_NOT_REACHED RAYCHEL_TERMINATE(\"Assertion failed! Expected to not execute \", __FILE__, \":\", __LINE__)\n\n//#define RAYCHEL_LOGICALLY_EQUAL //<-- activates logical equivalency for vector-like types\n\n#define RAYCHEL_THROW_EXCEPTION(msg, fatal) throw ::Raychel::exception_context{msg, RAYCHEL_FUNC_NAME, fatal};\n\n#define RAYCHEL_ASSERT_NORMALIZED(vec) RAYCHEL_ASSERT(equivalent(magSq(vec), 1.0f));\n\nnamespace Raychel {\n\n    using gsl::byte, gsl::not_null;\n    using std::size_t;\n\n    template <typename _num>\n    struct vec2Imp;\n    template <typename _num>\n    struct vec3Imp;\n    template <typename _num>\n    struct colorImp;\n    /*TODO: implement\n\ttemplate<typename _num>\n\tclass colorAlphaImp;\n\t*/\n    template <typename _num>\n    class QuaternionImp;\n    template <typename _num>\n    struct TransformImp;\n\n    template <typename _number>\n    constexpr _number sq(_number x)\n    {\n        static_assert(std::is_arithmetic_v<_number>, \"Raychel::sq<T> requires T to be of arithmetic type!\");\n        return x * x;\n    }\n\n    /**\n\t*\\brief Linearly interpolate between two numbers\n\t*\n\t*\\tparam _number Type of number to interpolate. Must be arithmetic\n\t*\\param a first number (x=0.0)\n\t*\\param b second number (x=1.0)\n\t*\\param x value of interpolation\n\t*\\return _number the interpolated number\n\t*/\n    template <typename _number>\n    constexpr _number lerp(_number a, _number b, long double x)\n    {\n        return (x * b) + ((1.0 - x) * a);\n    }\n\n    template <typename _integral>\n    constexpr _integral bit(size_t shift)\n    {\n        static_assert(std::is_integral_v<_integral>, \"Raychel::bit<T> requires T to be of integral type!\");\n        RAYCHEL_ASSERT(shift < (sizeof(_integral) * 8));\n        return static_cast<_integral>(1U << shift);\n    }\n\n    /**\n\t*\\brief Get number of digits in a number\n\t*\n\t*\\param num The number with its digits\n\t*\\return constexpr int \n\t*/\n    constexpr int numDigits(unsigned long long num, unsigned int base = 10U)\n    {\n        int digits = 0;\n\n        do {\n            digits++;\n            num /= base;\n        } while (num != 0);\n\n        return digits;\n    }\n\n} // namespace Raychel\n\n#endif // !RAYCHEL_CORE_H\n", "meta": {"hexsha": "60e3805333892f708cb7b0e8a63be7d5afc45dcf", "size": 5398, "ext": "h", "lang": "C", "max_stars_repo_path": "RaychelEngine/include/Raychel/Core/utils.h", "max_stars_repo_name": "Weckyy702/RaychelCPU", "max_stars_repo_head_hexsha": "a372ac0dfa3339cac19b06b11ec916ae275b67c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-12-07T21:57:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-06T10:39:18.000Z", "max_issues_repo_path": "RaychelEngine/include/Raychel/Core/utils.h", "max_issues_repo_name": "Weckyy702/RaychelCPU", "max_issues_repo_head_hexsha": "a372ac0dfa3339cac19b06b11ec916ae275b67c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RaychelEngine/include/Raychel/Core/utils.h", "max_forks_repo_name": "Weckyy702/RaychelCPU", "max_forks_repo_head_hexsha": "a372ac0dfa3339cac19b06b11ec916ae275b67c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-04-08T12:05:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-06T09:23:32.000Z", "avg_line_length": 32.7151515152, "max_line_length": 150, "alphanum_fraction": 0.6406076325, "num_tokens": 1295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12085323249047067, "lm_q2_score": 0.03461883771867046, "lm_q1q2_score": 0.004183798443364356}}
{"text": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n#pragma once\n\n#include <unordered_map>\n#include <mutex>\n#include <gsl/gsl>\n\n#include <typeindex>\n\n#include \"arcana/containers/ticketed_collection.h\"\n#include \"arcana/string.h\"\n\n#if NDEBUG\n#define FIRE_OBJECT_TRACE(...)\n#else\n#define OBJECT_TRACE_ENABLED\n#define FIRE_OBJECT_TRACE(channelName, instance, evt) \\\n    ::mira::object_trace::fire(channelName, instance, evt)\n#endif\n\nnamespace mira\n{\n    /*\n        Simple static analysis of data for exposing\n    */\n    class object_trace final\n    {\n        using channel_callback = std::function<void(std::intptr_t, const void*)>;\n        using global_callback = std::function<void(const char*, std::intptr_t, const void*)>;\n\n        using channel_ticketed_collection = ticketed_collection<channel_callback, std::recursive_mutex>;\n        using global_ticketed_collection = ticketed_collection<global_callback, std::recursive_mutex>;\n    public:\n        using channel_ticket = channel_ticketed_collection::ticket;\n        using global_ticket = global_ticketed_collection::ticket;\n\n        object_trace() = delete;\n\n        /*\n        Adds a listener to type T on the specified channel.\n\n        The channel is useful to split data into logical streams.\n        */\n        template<typename T>\n        static auto listen(const char* channel, std::function<void(std::intptr_t, T&)> callback)\n        {\n            return add_listener(channel, std::type_index{ typeid(std::decay_t<T>) }, [callback = std::move(callback)](std::intptr_t instance, const void* data)\n            {\n                callback(instance, const_cast<T&>(*reinterpret_cast<const T*>(data)));\n            });\n        }\n\n        /*\n            Adds a listener to type T to all channels.\n        */\n        template<typename T>\n        static auto listen(std::function<void(const char*, std::intptr_t, T&)> callback)\n        {\n            return add_listener(std::type_index{ typeid(std::decay_t<T>) },\n                [callback = std::move(callback)](const char* channel, std::intptr_t instance, const void* data)\n                {\n                    callback(channel, instance, const_cast<T&>(*reinterpret_cast<const T*>(data)));\n                });\n        }\n\n        /*\n            Fires an event in the specified channel.\n        */\n        template<typename T>\n        static void fire(const char* channel, const void* instance, const T& evt)\n        {\n            fire_event(channel, (std::intptr_t)instance, std::type_index{ typeid(std::decay_t<T>) }, &evt);\n        }\n    private:\n        using channels = std::map<std::string, channel_ticketed_collection, string_compare>;\n\n        struct listeners\n        {\n            channels ChannelListeners;\n            global_ticketed_collection GlobalListeners;\n        };\n\n        static channel_ticket add_listener(const char* channel, const std::type_index& type, channel_callback callback);\n        static global_ticket add_listener(const std::type_index& type, global_callback callback);\n\n        static void fire_event(const char* channel, std::intptr_t instance, const std::type_index& type, const void* data);\n\n        static std::recursive_mutex m_mutex;\n        static std::unordered_map<std::type_index, listeners> m_typemap;\n    };\n}\n", "meta": {"hexsha": "d250ec1baab267e9bb541eb9b966255236090925", "size": 3287, "ext": "h", "lang": "C", "max_stars_repo_path": "Dependencies/Arcana/Shared/arcana/analysis/object_trace.h", "max_stars_repo_name": "syntheticmagus/mageslam", "max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z", "max_issues_repo_path": "Dependencies/Arcana/Shared/arcana/analysis/object_trace.h", "max_issues_repo_name": "syntheticmagus/mageslam", "max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z", "max_forks_repo_path": "Dependencies/Arcana/Shared/arcana/analysis/object_trace.h", "max_forks_repo_name": "syntheticmagus/mageslam", "max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z", "avg_line_length": 34.9680851064, "max_line_length": 159, "alphanum_fraction": 0.6473988439, "num_tokens": 681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12085322299118381, "lm_q2_score": 0.03461883746966928, "lm_q1q2_score": 0.004183798084417491}}
{"text": "#pragma once\n\n#include <gsl.h>\n\n#include <mitkCommon.h>\n#include <mitkBaseData.h>\n\n#include <vtkSmartPointer.h>\n#include <vtkDataArray.h>\n\n#include \"SolverSetupServiceExports.h\"\n\nnamespace crimson\n{\n\n/*! \\brief   A class used for storing the simulation results and materials. */\nclass SolverSetupService_EXPORT SolutionData : public mitk::BaseData\n{\npublic:\n    mitkClassMacro(SolutionData, mitk::BaseData);\n    mitkNewMacro1Param(Self, vtkSmartPointer<vtkDataArray>);\n    //     itkCloneMacro(Self);\n    //     mitkCloneMacro(Self);\n\n    /*!\n     * \\brief   Gets the data in form of a vtkDataArray.\n     */\n    vtkDataArray* getArrayData() const;\n\nprotected:\n    SolutionData(vtkSmartPointer<vtkDataArray> data);\n    virtual ~SolutionData() {}\n\n    SolutionData(const Self& other) = delete;\n\nprivate:\n    vtkSmartPointer<vtkDataArray> _data;\n\n    void SetRequestedRegion(const itk::DataObject*) override {}\n    void SetRequestedRegionToLargestPossibleRegion() override {}\n    bool RequestedRegionIsOutsideOfTheBufferedRegion() override { return true; }\n    bool VerifyRequestedRegion() override { return true; }\n};\n}\n", "meta": {"hexsha": "1b0b0e121fc61a5568701f3d7f13c0126c4fc386", "size": 1118, "ext": "h", "lang": "C", "max_stars_repo_path": "Modules/SolverSetupService/include/SolutionData.h", "max_stars_repo_name": "carthurs/CRIMSONGUI", "max_stars_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-09-17T18:55:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T02:52:38.000Z", "max_issues_repo_path": "Modules/SolverSetupService/include/SolutionData.h", "max_issues_repo_name": "carthurs/CRIMSONGUI", "max_issues_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Modules/SolverSetupService/include/SolutionData.h", "max_forks_repo_name": "carthurs/CRIMSONGUI", "max_forks_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-05-19T09:02:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-26T17:39:57.000Z", "avg_line_length": 24.8444444444, "max_line_length": 80, "alphanum_fraction": 0.7271914132, "num_tokens": 267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.17328822300717897, "lm_q2_score": 0.024053554512271823, "lm_q1q2_score": 0.004168197718437895}}
{"text": "#pragma once\n\n#include <bgfx/bgfx.h>\n#include <napi/napi.h>\n#include <gsl/gsl>\n#include <map>\n#include <optional>\n\nnamespace Babylon\n{\n    class VertexBuffer final\n    {\n    public:\n        VertexBuffer(gsl::span<uint8_t> bytes, bool dynamic);\n        ~VertexBuffer();\n\n        void Dispose();\n\n        void Update(Napi::Env env, gsl::span<uint8_t> bytes);\n        bool CreateHandle(const bgfx::VertexLayout& layout);\n        void PromoteToFloats(bgfx::AttribType::Enum attribType, uint32_t numElements, uint32_t byteOffset, uint32_t byteStride);\n        void Set(bgfx::Encoder* encoder, uint8_t stream, uint32_t startVertex, uint32_t numVertices, bgfx::VertexLayoutHandle layoutHandle);\n\n        struct InstanceVertexBufferRecord\n        {\n            VertexBuffer* Buffer{};\n            uint32_t Offset{};\n            uint32_t Stride{};\n            uint32_t ElementSize{};\n        };\n        static void BuildInstanceDataBuffer(bgfx::InstanceDataBuffer& instanceDataBuffer, const std::map<bgfx::Attrib::Enum, InstanceVertexBufferRecord>& vertexBufferInstance);\n    private:\n        std::optional<std::vector<uint8_t>> m_bytes{};\n        bool m_dynamic{};\n\n        union\n        {\n            bgfx::VertexBufferHandle m_handle{bgfx::kInvalidHandle};\n            bgfx::DynamicVertexBufferHandle m_dynamicHandle;\n        };\n\n        bool m_disposed{};\n    };\n}\n", "meta": {"hexsha": "59f97bd75119f382905128a5a823a3305b912168", "size": 1360, "ext": "h", "lang": "C", "max_stars_repo_path": "Modules/@babylonjs/react-native/submodules/BabylonNative/Plugins/NativeEngine/Source/VertexBuffer.h", "max_stars_repo_name": "HarveyLijh/ReactNativeBabylon", "max_stars_repo_head_hexsha": "d9ac79d1e1a00f03f9a4fcf5419e5b118e65e586", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Modules/@babylonjs/react-native/submodules/BabylonNative/Plugins/NativeEngine/Source/VertexBuffer.h", "max_issues_repo_name": "HarveyLijh/ReactNativeBabylon", "max_issues_repo_head_hexsha": "d9ac79d1e1a00f03f9a4fcf5419e5b118e65e586", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Modules/@babylonjs/react-native/submodules/BabylonNative/Plugins/NativeEngine/Source/VertexBuffer.h", "max_forks_repo_name": "HarveyLijh/ReactNativeBabylon", "max_forks_repo_head_hexsha": "d9ac79d1e1a00f03f9a4fcf5419e5b118e65e586", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2222222222, "max_line_length": 176, "alphanum_fraction": 0.6536764706, "num_tokens": 315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1895210821742346, "lm_q2_score": 0.02194825115585846, "lm_q1q2_score": 0.004159656310890191}}
{"text": "/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */\n/*\n *     Copyright 2017 Couchbase, Inc\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n */\n\n#pragma once\n\n#include <gsl_p/span.h>\n\nnamespace phosphor {\n\n/**\n * Pure virtual base class for receiving stats from phosphor internals\n *\n * Methods on this class will be called with the key and value of each stat.\n * Callback implementations MUST NOT re-enter the TraceLog or TraceBuffer\n * upon which it used as locks may be held when the callback is invoked.\n *\n * Example usage:\n *\n *     class MyStatsCallback : public phosphor::StatsCallback {\n *          // Implement callback methods\n *     } callback;\n *\n *     phosphor::TraceLog::getInstance().getStats(callback);\n *\n *     // Stash data as required for application\n *     auto data = callback.getData();\n *\n * Implementations should note that phosphor makes no guarantees about\n * atomicity of the stats with respect to each other.\n */\nclass StatsCallback {\npublic:\n    /**\n     * Utility template method for passing a string literal as the first\n     * argument instead of a string span\n     * @param s String to convert to a span\n     * @param value Value to forward\n     */\n    template <size_t N, typename T>\n    void operator()(const char (&s)[N], T&& value) {\n        this->operator()(gsl_p::make_span(s), std::forward<T>(value));\n    }\n\n    virtual void operator()(gsl_p::cstring_span key,\n                            gsl_p::cstring_span value) = 0;\n    virtual void operator()(gsl_p::cstring_span key, bool value) = 0;\n    virtual void operator()(gsl_p::cstring_span key, size_t value) = 0;\n    virtual void operator()(gsl_p::cstring_span key, ssize_t value) = 0;\n    virtual void operator()(gsl_p::cstring_span key, double value) = 0;\n};\n\n}\n", "meta": {"hexsha": "69da67a324677985d7d9725d9a69bdd3daa53947", "size": 2314, "ext": "h", "lang": "C", "max_stars_repo_path": "include/phosphor/stats_callback.h", "max_stars_repo_name": "Chippiewill/Phosphor", "max_stars_repo_head_hexsha": "ef090fa5b331dd94301cd8562b24c78c0c2030f1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/phosphor/stats_callback.h", "max_issues_repo_name": "Chippiewill/Phosphor", "max_issues_repo_head_hexsha": "ef090fa5b331dd94301cd8562b24c78c0c2030f1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/phosphor/stats_callback.h", "max_forks_repo_name": "Chippiewill/Phosphor", "max_forks_repo_head_hexsha": "ef090fa5b331dd94301cd8562b24c78c0c2030f1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5373134328, "max_line_length": 79, "alphanum_fraction": 0.6789109767, "num_tokens": 549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11124120061463459, "lm_q2_score": 0.03732688868276005, "lm_q1q2_score": 0.004152287912279044}}
{"text": "#pragma once\n\n#include \"options.h\"\n#include \"predict.h\"\n#include \"progress.h\"\n#include <gsl/gsl-lite.hpp>\n\nnamespace angonoka::cli {\nnamespace detail {\n    /**\n        Check if an event is the final one.\n\n        @param evt Event\n\n        @return True if this is the final event.\n    */\n    bool is_final_event(ProgressEvent& evt) noexcept;\n\n    /**\n        Helper constant that checks if a given class is\n        a specialization of std::future.\n    */\n    template <typename T> inline constexpr bool is_future = false;\n    template <typename T>\n    inline constexpr bool is_future<std::future<T>> = true;\n} // namespace detail\n\n/**\n    Prediction events handler.\n\n    Prints various progress messages and results as\n    the prediction algorithm runs.\n\n    @var progress Chosen progress bar implementation\n    @var options CLI options\n*/\nstruct EventHandler {\n    gsl::not_null<Progress*> progress;\n    gsl::not_null<const Options*> options;\n\n    /**\n        Handler events without attributes.\n\n        @param e Event\n    */\n    void operator()(const SimpleProgressEvent& e) const;\n\n    /**\n        Handle schedule optimization events.\n\n        @param e Event\n    */\n    void operator()(const ScheduleOptimizationEvent& e) const;\n\n    /**\n        Handle schedule optimization completion.\n\n        @param e Event\n    */\n    void operator()(const ScheduleOptimizationComplete& e) const;\n};\n\n/**\n    Awaitable result of the prediction.\n*/\ntemplate <typename T>\nconcept Prediction = detail::is_future<T>;\n\n/**\n    Consumes prediction events from the queue.\n\n    @param queue        Prediction events queue\n    @param prediction   Prediction result\n    @param handler      Events handler\n*/\nvoid consume_events(\n    Queue<ProgressEvent>& queue,\n    Prediction auto& prediction,\n    EventHandler handler)\n{\n    Expects(prediction.valid());\n\n    using namespace std::literals::chrono_literals;\n    using boost::variant2::visit;\n    constexpr auto event_timeout = 100ms;\n    ProgressEvent evt;\n    while (!detail::is_final_event(evt)) {\n        if (!queue.try_dequeue(evt)) {\n            prediction.wait_for(event_timeout);\n            continue;\n        }\n        visit(handler, evt);\n    }\n\n    Ensures(prediction.valid());\n}\n} // namespace angonoka::cli\n", "meta": {"hexsha": "4706f630cb8eb3aaaa169d41fbe49021f79bab1e", "size": 2249, "ext": "h", "lang": "C", "max_stars_repo_path": "src/cli/events.h", "max_stars_repo_name": "coffee-lord/angonoka", "max_stars_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-10-23T18:05:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T21:53:24.000Z", "max_issues_repo_path": "src/cli/events.h", "max_issues_repo_name": "coffee-lord/angonoka", "max_issues_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2022-02-12T19:52:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-12T19:55:52.000Z", "max_forks_repo_path": "src/cli/events.h", "max_forks_repo_name": "coffee-lord/angonoka", "max_forks_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9489795918, "max_line_length": 66, "alphanum_fraction": 0.6562916852, "num_tokens": 476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16667539640920673, "lm_q2_score": 0.024798157988393417, "lm_q1q2_score": 0.004133242812933609}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef avl_6c9ab2d0_f8bc_4fb1_bc21_7fc0c6eb4bec_h\r\n#define avl_6c9ab2d0_f8bc_4fb1_bc21_7fc0c6eb4bec_h\r\n\r\n#include <assert.h>\r\n#include <gslib/std.h>\r\n\r\n__gslib_begin__\r\n\r\nstruct _avltree_trait_copy {};\r\nstruct _avltree_trait_detach {};\r\n\r\ntemplate<class _ty>\r\nstruct _avltreenode_cpy_wrapper\r\n{\r\n    typedef _ty value;\r\n    typedef _avltreenode_cpy_wrapper<_ty> myref;\r\n    typedef _avltree_trait_copy tsf_behavior;\r\n\r\n    value               _value;\r\n    myref*              _left;\r\n    myref*              _right;\r\n    myref*              _parent;\r\n    int                 _balance;\r\n\r\n    myref()\r\n    {\r\n        _left = _right = _parent = nullptr;\r\n        _balance = 0;\r\n    }\r\n    value* get_ptr() { return &_value; }\r\n    const value* const_ptr() const { return &_value; }\r\n    value& get_ref() { return _value; }\r\n    const value& const_ref() const { return _value; }\r\n    void born() {}\r\n    void kill() {}\r\n    template<class _ctor>\r\n    void born() {}\r\n    template<class _ctor>\r\n    void kill() {}\r\n    void copy(const myref* a) { get_ref() = a->const_ref(); }\r\n    void attach(myref* a) { assert(0); }\r\n    void swap_data(myref* a) { std::swap(_value, a->_value); }\r\n};\r\n\r\ntemplate<class _ty>\r\nstruct _avltreenode_wrapper\r\n{\r\n    typedef _ty value;\r\n    typedef _avltreenode_wrapper<_ty> myref;\r\n    typedef _avltree_trait_detach tsf_behavior;\r\n\r\n    value*              _value;\r\n    myref*              _left;\r\n    myref*              _right;\r\n    myref*              _parent;\r\n    int                 _balance;\r\n\r\n    myref()\r\n    {\r\n        _left = _right = _parent = nullptr;\r\n        _value = nullptr;\r\n        _balance = 0;\r\n    }\r\n    value* get_ptr() { return _value; }\r\n    const value* const_ptr() const { return _value; }\r\n    value& get_ref() { return *_value; }\r\n    const value& const_ref() const { return *_value; }\r\n    void copy(const myref* a) { get_ref() = a->const_ref(); }\r\n    void born() { !! }\r\n    template<class _ctor>\r\n    void born() { _value = new _ctor; }\r\n    void kill() { if(_value) { delete _value; _value = nullptr; } }\r\n    template<class _ctor>\r\n    void kill() { if(_value) { delete _value; _value = nullptr; } }\r\n    void attach(myref* a)\r\n    {\r\n        assert(a && a->_value);\r\n        kill();\r\n        _value = a->_value;\r\n        a->_value = nullptr;\r\n    }\r\n    void swap_data(myref* a) { gs_swap(_value, a->_value); }\r\n};\r\n\r\ntemplate<class _wrapper>\r\nstruct _avltree_allocator\r\n{\r\n    typedef _wrapper wrapper;\r\n    static wrapper* born() { return new wrapper; }\r\n    static void kill(wrapper* w) { delete w; }\r\n};\r\n\r\ntemplate<class _val>\r\nstruct _avltreenode_val\r\n{\r\n    typedef _val value;\r\n    typedef const _val const_value;\r\n    typedef _avltreenode_val<_val> myref;\r\n\r\n    union\r\n    {\r\n        value*          _vptr;\r\n        const_value*    _cvptr;\r\n    };\r\n\r\n    myref() { _vptr = nullptr; }\r\n    value* get_wrapper() const { return _vptr; }\r\n    operator bool() const { return _vptr != nullptr; }\r\n    bool is_left() const { return (_cvptr && _cvptr->_parent) ? _cvptr->_parent->_left == _cvptr : false; }\r\n    bool is_right() const { return (_cvptr && _cvptr->_parent) ? _cvptr->_parent->_right == _cvptr : false; }\r\n    bool is_root() const { return _cvptr ? (!_cvptr->_parent) : false; }\r\n    bool is_leaf() const { return _cvptr ? (!_cvptr->_left && !_cvptr->_right) : false; }\r\n    int up_depth() const\r\n    {\r\n        int depth = 0;\r\n        for(value* p = _vptr; p; p = p->_parent, depth ++);\r\n        return depth;\r\n    }\r\n    int down_depth() const { return _down_depth(_vptr, 0); }\r\n    bool operator==(const value* v) const { return _vptr == v; }\r\n    bool operator!=(const value* v) const { return _vptr != v; }\r\n    int get_balance() const { return _vptr->_balance; }\r\n    void set_balance(int b) { _vptr->_balance = b; }\r\n    void swap_data(myref& a) { _vptr->swap_data(a._vptr); }\r\n\r\npublic:\r\n    static void connect_left_child(value* p, value* l)\r\n    {\r\n        assert(p);\r\n        p->_left = l;\r\n        if(l)\r\n            l->_parent = p;\r\n    }\r\n    static void connect_right_child(value* p, value* r)\r\n    {\r\n        assert(p);\r\n        p->_right = r;\r\n        if(r)\r\n            r->_parent = p;\r\n    }\r\n    static bool disconnect_parent_child(value* p, value* c)\r\n    {\r\n        assert(p && c && (c->_parent == p));\r\n        if(p->_left == c) {\r\n            p->_left = c->_parent = nullptr;\r\n            return true;\r\n        }\r\n        assert(p->_right == c);\r\n        p->_right = c->_parent = nullptr;\r\n        return false;\r\n    }\r\n\r\nprivate:\r\n    static int _down_depth(value* v, int ctr)\r\n    {\r\n        if(v == nullptr)\r\n            return ctr;\r\n        ctr ++;\r\n        return gs_max(_down_depth(v->_left, ctr), \r\n            _down_depth(v->_right, ctr)\r\n            );\r\n    }\r\n\r\nprotected:\r\n    value* vleft() const { return _vptr ? _vptr->_left : nullptr; }\r\n    value* vright() const { return _vptr ? _vptr->_right : nullptr; }\r\n    value* vparent() const { return _vptr ? _vptr->_parent : nullptr; }\r\n    value* vsibling() const\r\n    {\r\n        if(!_vptr || !_vptr->_parent)\r\n            return nullptr;\r\n        if(is_left())\r\n            return _vptr->_right;\r\n        else if(is_right())\r\n            return _vptr->_left;\r\n        assert(!\"unexpected.\");\r\n        return nullptr;\r\n    }\r\n    value* vroot() const\r\n    {\r\n        if(!_vptr)\r\n            return nullptr;\r\n        value* p = _vptr;\r\n        for( ; p->_parent; p = p->_parent);\r\n        return p;\r\n    }\r\n\r\nprotected:\r\n    template<class _lambda, class _value>\r\n    static void preorder_traversal(_lambda lam, _value* v)\r\n    {\r\n        assert(v);\r\n        lam(v);\r\n        if(v->_left)\r\n            preorder_traversal(lam, v->_left);\r\n        if(v->_right)\r\n            preorder_traversal(lam, v->_right);\r\n    }\r\n    template<class _lambda, class _value>\r\n    static void inorder_traversal(_lambda lam, _value* v)\r\n    {\r\n        assert(v);\r\n        if(v->_left)\r\n            inorder_traversal(lam, v->_left);\r\n        lam(v);\r\n        if(v->_right)\r\n            inorder_traversal(lam, v->_right);\r\n    }\r\n    template<class _lambda, class _value>\r\n    static void postorder_traversal(_lambda lam, _value* v)\r\n    {\r\n        assert(v);\r\n        if(v->_left)\r\n            postorder_traversal(lam, v->_left);\r\n        if(v->_right)\r\n            postorder_traversal(lam, v->-right);\r\n        lam(v);\r\n    }\r\n\r\npublic:\r\n    template<class _lambda>\r\n    void inorder_traversal(_lambda lam) { if(_vptr) inorder_traversal(lam, _vptr); }\r\n    template<class _lambda>\r\n    void inorder_traversal(_lambda lam) const { if(_cvptr) inorder_traversal(lam, _cvptr); }\r\n    template<class _lambda>\r\n    void preorder_traversal(_lambda lam) { if(_vptr) preorder_traversal(lam, _vptr); }\r\n    template<class _lambda>\r\n    void preorder_traversal(_lambda lam) const { if(_cvptr) preorder_traversal(lam, _cvptr); }\r\n    template<class _lambda>\r\n    void postorder_traversal(_lambda lam) { if(_vptr) postorder_traversal(lam, _vptr); }\r\n    template<class _lambda>\r\n    void postorder_traversal(_lambda lam) const { if(_cvptr) postorder_traversal(lam, _cvptr); }\r\n};\r\n\r\ntemplate<class _ty,\r\n    class _wrapper = _avltreenode_cpy_wrapper<_ty> >\r\nclass _avltree_const_iterator:\r\n    public _avltreenode_val<_wrapper>\r\n{\r\npublic:\r\n    typedef _ty value;\r\n    typedef _wrapper wrapper;\r\n    typedef _avltree_const_iterator<_ty, _wrapper> iterator;\r\n\r\npublic:\r\n    iterator(const wrapper* w = nullptr) { _cvptr = w; }\r\n    bool is_valid() const { return _cvptr != nullptr; }\r\n    const value* get_ptr() const { return _cvptr->const_ptr(); }\r\n    const value* operator->() const { return _cvptr->const_ptr(); }\r\n    const value& operator*() const { return _cvptr->const_ref(); }\r\n    iterator left() const { return iterator(vleft()); }\r\n    iterator right() const { return iterator(vright()); }\r\n    iterator parent() const { return iterator(vparent()); }\r\n    iterator sibling() const { return iterator(vsibling()); }\r\n    iterator root() const { return iterator(vroot()); }\r\n    bool operator==(const iterator& that) const { return _cvptr == that._cvptr; }\r\n    bool operator!=(const iterator& that) const { return _cvptr != that._cvptr; }\r\n};\r\n\r\ntemplate<class _ty,\r\n    class _wrapper = _avltreenode_cpy_wrapper<_ty> >\r\nclass _avltree_iterator:\r\n    public _avltree_const_iterator<_ty, _wrapper>\r\n{\r\npublic:\r\n    typedef _ty value;\r\n    typedef _wrapper wrapper;\r\n    typedef _avltree_const_iterator<_ty, _wrapper> const_iterator;\r\n    typedef _avltree_const_iterator<_ty, _wrapper> superref;\r\n    typedef _avltree_iterator<_ty, _wrapper> iterator;\r\n\r\npublic:\r\n    iterator(wrapper* w): superref(w) {}\r\n    value* get_ptr() const { return _vptr->get_ptr(); }\r\n    value* operator->() const { return _vptr->get_ptr(); }\r\n    value& operator*() const { return _vptr->get_ref(); }\r\n    bool operator==(const iterator& that) const { return _vptr == that._vptr; }\r\n    bool operator!=(const iterator& that) const { return _vptr != that._vptr; }\r\n    bool operator==(const const_iterator& that) const { return _vptr == that._vptr; }\r\n    bool operator!=(const const_iterator& that) const { return _vptr != that._vptr; }\r\n    operator const_iterator() { return const_iterator(_cvptr); }\r\n    void to_root() { _vptr = vroot(); }\r\n    void to_left() { _vptr = vleft(); }\r\n    void to_right() { _vptr = vright(); }\r\n    void to_sibling() { _vptr = vsibling(); }\r\n    void to_parent() { _vptr = vparent(); }\r\n    iterator left() const { return iterator(vleft()); }\r\n    iterator right() const { return iterator(vright()); }\r\n    iterator parent() const { return iterator(vparent()); }\r\n    iterator sibling() const { return iterator(vsibling()); }\r\n    iterator root() const { return iterator(vroot()); }\r\n};\r\n\r\ntemplate<class _ty,\r\n    class _wrapper = _avltreenode_cpy_wrapper<_ty>,\r\n    class _alloc = _avltree_allocator<_wrapper> >\r\nclass avltree:\r\n    public _avltreenode_val<_wrapper>\r\n{\r\npublic:\r\n    typedef _ty value;\r\n    typedef _wrapper wrapper;\r\n    typedef _alloc alloc;\r\n    typedef avltree<value, wrapper, alloc> myref;\r\n    typedef _avltree_const_iterator<_ty, _wrapper> const_iterator;\r\n    typedef _avltree_iterator<_ty, _wrapper> iterator;\r\n\r\npublic:\r\n    avltree() { _vptr = nullptr; }\r\n    ~avltree() { clear(); }\r\n    void clear() { destroy(get_root()); }\r\n    void destroy(iterator i)\r\n    {\r\n        if(!i.is_valid())\r\n            return;\r\n        if(iterator p = i.parent())\r\n            disconnect_parent_child(p.get_wrapper(), i.get_wrapper());\r\n        else {\r\n            assert(is_root(i));\r\n            _vptr = nullptr;\r\n        }\r\n        _destroy(i);\r\n    }\r\n    void adopt(wrapper* w)\r\n    {\r\n        assert(!_vptr && \"use attach method.\");\r\n        _vptr = w;\r\n    }\r\n    iterator get_root() const { return iterator(_vptr); }\r\n    const_iterator const_root() const { return const_iterator(_cvptr); }\r\n    bool is_root(iterator i) const { return i.is_valid() ? (_cvptr == i.get_wrapper()) : false; }\r\n    bool is_valid() const { return _cvptr != nullptr; }\r\n    bool is_mine(iterator i) const\r\n    {\r\n        if(!i.is_valid())\r\n            return false;\r\n        i.to_root();\r\n        return i.get_wrapper() == _vptr;\r\n    }\r\n    int depth() const { return _cvptr->down_depth(); }\r\n    void swap(myref& that) { gs_swap(_vptr, that._vptr); }\r\n    iterator find(const value& v) const { return find(get_root(), v); }\r\n    iterator find(iterator i, const value& v) const\r\n    {\r\n        if(!i) {\r\n            if(!is_valid())\r\n                return i;\r\n            i = get_root();\r\n        }\r\n        assert(i);\r\n        if(v == *i)\r\n            return i;\r\n        iterator n = (v < *i) ? i.left() : i.right();\r\n        return n ? find(n, v) : i;\r\n    }\r\n    template<class _ctor = value>\r\n    iterator insert(const value& v)\r\n    {\r\n        iterator i = get_root();\r\n        return !i ? _init<_ctor>(v) : _insert<_ctor>(i, v);\r\n    }\r\n    void erase(iterator i)\r\n    {\r\n        assert(i && is_mine(i));\r\n        if(i.is_leaf()) {\r\n            iterator p = i.parent();\r\n            if(p) {\r\n                disconnect_parent_child(p.get_wrapper(), i.get_wrapper());\r\n                _destroy(i);\r\n                _balance_erase(p);\r\n                return;\r\n            }\r\n            else {\r\n                assert(is_root(i));\r\n                _destroy(i);\r\n                _vptr = nullptr;\r\n                return;\r\n            }\r\n        }\r\n        if(i.left()) {\r\n            if(i.right()) {     /* left & right */\r\n                iterator l = i.left();\r\n                iterator li = l;\r\n                for(; li.right(); li.to_right());\r\n                iterator lil = li.left();\r\n                i.swap_data(li);\r\n                if(lil) {\r\n                    li.swap_data(lil);\r\n                    destroy(lil);\r\n                    _balance_erase(li);\r\n                    return;\r\n                }\r\n                else {\r\n                    iterator q = li.parent();\r\n                    assert(q);\r\n                    destroy(li);\r\n                    _balance_erase(q);\r\n                    return;\r\n                }\r\n            }\r\n            else {      /* only left */\r\n                if(i.parent()) {\r\n                    myref t;\r\n                    iterator j = attach(detach(t, i.left()), i);\r\n                    j.set_balance(i.get_balance());\r\n                    _balance_erase(j);\r\n                    return;\r\n                }\r\n                else {\r\n                    myref t;\r\n                    swap(detach(t, i.left()));\r\n                    return;\r\n                }\r\n            }\r\n        }\r\n        else {\r\n            assert(i.right());      /* only right */\r\n            if(i.parent()) {\r\n                myref t;\r\n                iterator j = attach(detach(t, i.right()), i);\r\n                j.set_balance(i.get_balance());\r\n                _balance_erase(j);\r\n                return;\r\n            }\r\n            else {\r\n                myref t;\r\n                swap(detach(t, i.right()));\r\n                return;\r\n            }\r\n        }\r\n    }\r\n    void erase(const value& v)\r\n    {\r\n        if(iterator i = find(v))\r\n            erase(i);\r\n    }\r\n\r\n    /* The detach and attach methods, provide subtree operations */\r\n    myref& detach(myref& subtree, iterator i)\r\n    {\r\n        assert(i && is_mine(i));\r\n        if(subtree.is_valid())\r\n            subtree.clear();\r\n        detach<myref>(subtree, i);\r\n        return subtree;\r\n    }\r\n    template<class _cont>\r\n    void detach(_cont& cont)\r\n    {\r\n        cont.adopt(_vptr);\r\n        _vptr = nullptr;\r\n    }\r\n    template<class _cont>\r\n    void detach(_cont& cont, iterator i)\r\n    {\r\n        assert(i && is_mine(i));\r\n        if(i == get_root())\r\n            return detach(cont);\r\n        iterator p = i.parent();\r\n        assert(p);\r\n        disconnect_parent_child(p.get_wrapper(), i.get_wrapper());\r\n        cont.adopt(i.get_wrapper());\r\n    }\r\n    iterator attach(myref& subtree, iterator i)\r\n    {\r\n        assert(i && is_mine(i) && i.is_leaf());\r\n        if(i.is_root()) {\r\n            swap(subtree);\r\n            return get_root();\r\n        }\r\n        iterator p = i.parent();\r\n        assert(p);\r\n        bool leftp = disconnect_parent_child(p.get_wrapper(), i.get_wrapper());\r\n        gs_swap(subtree._vptr, i._vptr);\r\n        leftp ? connect_left_child(p.get_wrapper(), i.get_wrapper()) :\r\n            connect_right_child(p.get_wrapper(), i.get_wrapper());\r\n        subtree.clear();\r\n        return i;\r\n    }\r\n\r\npublic:\r\n    template<class _lambda>\r\n    void preorder_for_each(_lambda lam) { preorder_traversal([](wrapper* w) { lam(w->get_ptr()); }); }\r\n    template<class _lambda>\r\n    void preorder_const_for_each(_lambda lam) const { preorder_traversal([](const wrapper* w) { lam(w->const_ptr()); }); }\r\n    template<class _lambda>\r\n    void inorder_for_each(_lambda lam) { inorder_traversal([](wrapper* w) { lam(w->get_ptr()); }); }\r\n    template<class _lambda>\r\n    void inorder_const_for_each(_lambda lam) const { inorder_traversal([](const wrapper* w) { lam(w->const_ptr()); }); }\r\n    template<class _lambda>\r\n    void postorder_for_each(_lambda lam) { postorder_traversal([](wrapper* w) { lam(w->get_ptr()); }); }\r\n    template<class _lambda>\r\n    void postorder_const_for_each(_lambda lam) const { postorder_traversal([](const wrapper* w) { lam(w->const_ptr()); }); }\r\n\r\nprotected:\r\n    void _destroy(iterator i)\r\n    {\r\n        if(!i.is_valid())\r\n            return;\r\n        _destroy(i.left());\r\n        _destroy(i.right());\r\n        wrapper* w = i.get_wrapper();\r\n        w->kill();\r\n        alloc::kill(w);\r\n    }\r\n    template<class _ctor>\r\n    iterator _insert(iterator i, const value& v)\r\n    {\r\n        assert(i);\r\n        if(v == *i)\r\n            return iterator(nullptr);     /* failed */\r\n        if(v < *i) {\r\n            if(i.left())\r\n                return _insert<_ctor>(i.left(), v);\r\n            iterator j = _add_left<_ctor>(i, v);\r\n            _balance_insert(j);\r\n            return j;\r\n        }\r\n        else {\r\n            if(i.right())\r\n                return _insert<_ctor>(i.right(), v);\r\n            iterator j = _add_right<_ctor>(i, v);\r\n            _balance_insert(j);\r\n            return j;\r\n        }\r\n    }\r\n    void _balance_insert(iterator i)\r\n    {\r\n        assert(i);\r\n        iterator p = i.parent();\r\n        if(!p)\r\n            return;\r\n        if(i.is_left()) {\r\n            switch(p.get_balance())\r\n            {\r\n            case -1:\r\n                (i.get_balance() == 1) ?\r\n                    _left_right_rotate(p) :\r\n                    _right_rotate(p);\r\n                break;\r\n            case 0:\r\n                p.set_balance(-1);\r\n                return _balance_insert(p);\r\n            case 1:\r\n                p.set_balance(0);\r\n                break;\r\n            default:\r\n                assert(!\"unexpected.\");\r\n                break;\r\n            }\r\n        }\r\n        else {\r\n            switch(p.get_balance())\r\n            {\r\n            case -1:\r\n                p.set_balance(0);\r\n                break;\r\n            case 0:\r\n                p.set_balance(1);\r\n                return _balance_insert(p);\r\n            case 1:\r\n                (i.get_balance() == -1) ?\r\n                    _right_left_rotate(p) :\r\n                    _left_rotate(p);\r\n                break;\r\n            default:\r\n                assert(!\"unexpected.\");\r\n                break;\r\n            }\r\n        }\r\n    }\r\n    void _balance_erase(iterator i)\r\n    {\r\n        assert(i);\r\n        int b = i.get_balance();\r\n        if(!b) {\r\n            i.set_balance(i.left() ? -1 : 1);\r\n            return;\r\n        }\r\n        if(!i.left()) {\r\n            if(b == -1)\r\n                i.set_balance(0);\r\n            else if(b == 1) {\r\n                iterator r = i.right();\r\n                if(!r)\r\n                    i.set_balance(0);\r\n                else {\r\n                    (r.get_balance() == -1) ?\r\n                        _right_left_rotate(i) :\r\n                        _left_rotate(i);\r\n                    i.to_parent();\r\n                    if(i.get_balance() == -1)\r\n                        return;\r\n                }\r\n            }\r\n            else {\r\n                assert(!\"unexpected.\");\r\n            }\r\n        }\r\n        else if(!i.right()) {\r\n            if(b == 1)\r\n                i.set_balance(0);\r\n            else if(b == -1) {\r\n                iterator l = i.left();\r\n                if(!l)\r\n                    i.set_balance(0);\r\n                else {\r\n                    (l.get_balance() == 1) ?\r\n                        _left_right_rotate(i) :\r\n                        _right_rotate(i);\r\n                    i.to_parent();\r\n                    if(i.get_balance() == 1)\r\n                        return;\r\n                }\r\n            }\r\n            else {\r\n                assert(!\"unexpected.\");\r\n            }\r\n        }\r\n        _balance_erase_(i);\r\n    }\r\n    void _balance_erase_(iterator i)\r\n    {\r\n        assert(i);\r\n        iterator p = i.parent();\r\n        if(!p)\r\n            return;\r\n        if(i.is_left()) {\r\n            switch(p.get_balance())\r\n            {\r\n            case -1:\r\n                p.set_balance(0);\r\n                return _balance_erase_(p);\r\n            case 0:\r\n                p.set_balance(1);\r\n                break;\r\n            case 1:\r\n                (p.right().get_balance() == -1) ?\r\n                    _right_left_rotate(p) :\r\n                    _left_rotate(p);\r\n                if(p.parent().get_balance() != -1)\r\n                    return _balance_erase_(p.parent());\r\n                break;\r\n            default:\r\n                assert(!\"unexpected.\");\r\n                break;\r\n            }\r\n        }\r\n        else {\r\n            switch(p.get_balance())\r\n            {\r\n            case -1:\r\n                (p.left().get_balance() == 1) ?\r\n                    _left_right_rotate(p) :\r\n                    _right_rotate(p);\r\n                if(p.parent().get_balance() != 1)\r\n                    return _balance_erase_(p.parent());\r\n                break;\r\n            case 0:\r\n                p.set_balance(-1);\r\n                break;\r\n            case 1:\r\n                p.set_balance(0);\r\n                return _balance_erase_(p);\r\n            default:\r\n                assert(!\"unexpected.\");\r\n                break;\r\n            }\r\n        }\r\n    }\r\n    iterator _left_rotate(iterator i)\r\n    {\r\n        assert(i && i.right());\r\n        iterator p = i.parent();\r\n        iterator r = i.right();\r\n        iterator rl = r.left();\r\n        if(p) {\r\n            i.is_left() ? connect_left_child(p.get_wrapper(), r.get_wrapper()) :\r\n                connect_right_child(p.get_wrapper(), r.get_wrapper());\r\n        }\r\n        else {\r\n            _vptr = r.get_wrapper();\r\n            _vptr->_parent = nullptr;\r\n        }\r\n        connect_left_child(r.get_wrapper(), i.get_wrapper());\r\n        connect_right_child(i.get_wrapper(), rl.get_wrapper());\r\n        if(r.get_balance() == 0) {\r\n            i.set_balance(1);\r\n            r.set_balance(-1);\r\n        }\r\n        else {\r\n            i.set_balance(0);\r\n            r.set_balance(0);\r\n        }\r\n        return r;\r\n    }\r\n    iterator _right_rotate(iterator i)\r\n    {\r\n        assert(i && i.left());\r\n        iterator p = i.parent();\r\n        iterator l = i.left();\r\n        iterator lr = l.right();\r\n        if(p) {\r\n            i.is_left() ? connect_left_child(p.get_wrapper(), l.get_wrapper()) :\r\n                connect_right_child(p.get_wrapper(), l.get_wrapper());\r\n        }\r\n        else {\r\n            _vptr = l.get_wrapper();\r\n            _vptr->_parent = nullptr;\r\n        }\r\n        connect_right_child(l.get_wrapper(), i.get_wrapper());\r\n        connect_left_child(i.get_wrapper(), lr.get_wrapper());\r\n        if(l.get_balance() == 0) {\r\n            i.set_balance(-1);\r\n            l.set_balance(1);\r\n        }\r\n        else {\r\n            i.set_balance(0);\r\n            l.set_balance(0);\r\n        }\r\n        return l;\r\n    }\r\n    iterator _left_right_rotate(iterator i)\r\n    {\r\n        assert(i && i.left());\r\n        iterator l = i.left();\r\n        iterator lr = l.right();\r\n        assert(lr);\r\n        iterator lrl = lr.left();\r\n        iterator lrr = lr.right();\r\n        iterator p = i.parent();\r\n        if(p) {\r\n            i.is_left() ? connect_left_child(p.get_wrapper(), lr.get_wrapper()) :\r\n                connect_right_child(p.get_wrapper(), lr.get_wrapper());\r\n        }\r\n        else {\r\n            _vptr = lr.get_wrapper();\r\n            _vptr->_parent = nullptr;\r\n        }\r\n        connect_left_child(lr.get_wrapper(), l.get_wrapper());\r\n        connect_right_child(lr.get_wrapper(), i.get_wrapper());\r\n        connect_right_child(l.get_wrapper(), lrl.get_wrapper());\r\n        connect_left_child(i.get_wrapper(), lrr.get_wrapper());\r\n        switch(lr.get_balance())\r\n        {\r\n        case -1:\r\n            i.set_balance(1);\r\n            l.set_balance(0);\r\n            break;\r\n        case 0:\r\n            i.set_balance(0);\r\n            l.set_balance(0);\r\n            break;\r\n        case 1:\r\n            i.set_balance(0);\r\n            l.set_balance(-1);\r\n            break;\r\n        default:\r\n            assert(!\"unexpected.\");\r\n            break;\r\n        }\r\n        lr.set_balance(0);\r\n        return lr;\r\n    }\r\n    iterator _right_left_rotate(iterator i)\r\n    {\r\n        assert(i && i.right());\r\n        iterator r = i.right();\r\n        iterator rl = r.left();\r\n        assert(rl);\r\n        iterator rll = rl.left();\r\n        iterator rlr = rl.right();\r\n        iterator p = i.parent();\r\n        if(p) {\r\n            i.is_left() ? connect_left_child(p.get_wrapper(), rl.get_wrapper()) :\r\n                connect_right_child(p.get_wrapper(), rl.get_wrapper());\r\n        }\r\n        else {\r\n            _vptr = rl.get_wrapper();\r\n            _vptr->_parent = nullptr;\r\n        }\r\n        connect_right_child(rl.get_wrapper(), r.get_wrapper());\r\n        connect_left_child(rl.get_wrapper(), i.get_wrapper());\r\n        connect_right_child(i.get_wrapper(), rll.get_wrapper());\r\n        connect_left_child(r.get_wrapper(), rlr.get_wrapper());\r\n        switch(rl.get_balance())\r\n        {\r\n        case -1:\r\n            i.set_balance(0);\r\n            r.set_balance(1);\r\n            break;\r\n        case 0:\r\n            i.set_balance(0);\r\n            r.set_balance(0);\r\n            break;\r\n        case 1:\r\n            i.set_balance(-1);\r\n            r.set_balance(0);\r\n            break;\r\n        default:\r\n            assert(!\"unexpected.\");\r\n            break;\r\n        }\r\n        rl.set_balance(0);\r\n        return rl;\r\n    }\r\n\r\n    template<class _ctor>\r\n    iterator _init()\r\n    {\r\n        assert(!_vptr);\r\n        _vptr = alloc::born();\r\n        _vptr->born<_ctor>();\r\n        return iterator(_vptr);\r\n    }\r\n    template<class _ctor>\r\n    iterator _init(const value& v)\r\n    {\r\n        assert(!_vptr);\r\n        _vptr = initval<_ctor, wrapper::tsf_behavior>::run(alloc::born(), v);\r\n        assert(_vptr);\r\n        return iterator(_vptr);\r\n    }\r\n    template<class _ctor>\r\n    iterator _add_left(iterator i, const value& v)\r\n    {\r\n        assert(i && !i.left());\r\n        wrapper* n = initval<_ctor, wrapper::tsf_behavior>::run(alloc::born(), v);\r\n        connect_left_child(i.get_wrapper(), n);\r\n        return iterator(n);\r\n    }\r\n    template<class _ctor>\r\n    iterator _add_right(iterator i, const value& v)\r\n    {\r\n        assert(i && !i.right());\r\n        wrapper* n = initval<_ctor, wrapper::tsf_behavior>::run(alloc::born(), v);\r\n        connect_right_child(i.get_wrapper(), n);\r\n        return iterator(n);\r\n    }\r\n    void _modified()\r\n    {\r\n#if defined (DEBUG) || defined (_DEBUG)\r\n        debug_check(get_root());\r\n#endif\r\n    }\r\n\r\nprotected:\r\n    friend struct initval;\r\n    template<class _ctor, class _tsftrait>\r\n    struct initval;\r\n    template<class _ctor>\r\n    struct initval<_ctor, _avltree_trait_copy>\r\n    {\r\n        static wrapper* run(wrapper* w, const value& v)\r\n        {\r\n            assert(w);\r\n            w->get_ref() = v;\r\n            return w;\r\n        }\r\n    };\r\n    template<class _ctor>\r\n    struct initval<_ctor, _avltree_trait_detach>\r\n    {\r\n        static wrapper* run(wrapper* w, const value& v)\r\n        {\r\n            assert(w);\r\n            w->_value = &v;     /* or duplicate? */\r\n            return w;\r\n        }\r\n    };\r\n\r\npublic:\r\n    bool debug_check(iterator i)\r\n    {\r\n        if(!i)\r\n            return true;\r\n        check_root(i);\r\n        check_linkage(i);\r\n        check_order(i);\r\n        check_balance(i);\r\n        iterator l = i.left(), r = i.right();\r\n        if(!(l && debug_check(l)))\r\n            return false;\r\n        if(!(r && debug_check(r)))\r\n            return false;\r\n        return true;\r\n    }\r\n    bool check_root(iterator i)\r\n    {\r\n        assert(i);\r\n        if(is_root(i)) {\r\n            assert(!i.parent() && \"root has no parent.\");\r\n            return true;\r\n        }\r\n        assert(i.parent() && \"non-root must have parent.\");\r\n        return false;\r\n    }\r\n    void check_linkage(iterator i)\r\n    {\r\n        assert(i);\r\n        iterator l = i.left(), r = i.right();\r\n        if(l) { assert(l.parent() == i && \"left link wrong.\"); }\r\n        if(r) { assert(r.parent() == i && \"right link wrong.\"); }\r\n    }\r\n    void check_order(iterator i)\r\n    {\r\n        assert(i);\r\n        iterator l = i.left(), r = i.right();\r\n        if(l) {\r\n            iterator lm = l;\r\n            for(; lm.right(); lm = lm.right());\r\n            assert(*lm < *i && \"left order wrong.\");\r\n        }\r\n        if(r) {\r\n            iterator rm = r;\r\n            for(; rm.left(); rm = rm.left());\r\n            assert(*i < *rm && \"right order wrong.\");\r\n        }\r\n    }\r\n    void check_balance(iterator i)\r\n    {\r\n        assert(i);\r\n        iterator l = i.left(), r = i.right();\r\n        int h1 = 0, h2 = 0;\r\n        if(l) h1 = l.down_depth();\r\n        if(r) h2 = r.down_depth();\r\n        int b = i.get_balance();\r\n        assert(b == h2 - h1 && \"balance wrong.\");\r\n    }\r\n};\r\n\r\n__gslib_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "07a831cc8933e11be84b3b1da84a99bcaa0cd551", "size": 30346, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gslib/avl.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/gslib/avl.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gslib/avl.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 31.5446985447, "max_line_length": 125, "alphanum_fraction": 0.5044486918, "num_tokens": 7006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12085324515618749, "lm_q2_score": 0.03410042890256554, "lm_q1q2_score": 0.0041211474940928946}}
{"text": "////////////////////////////////////////////////////////////\n//\n// Copyright (c) 2018 Jan Filipowicz, Filip Turobos\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n//\n////////////////////////////////////////////////////////////\n\n#ifndef GENETIC_ALGORITHM_LIBRARY_EVALUATED_SPECIMEN_H\n#define GENETIC_ALGORITHM_LIBRARY_EVALUATED_SPECIMEN_H\n\n#include <optional>\n#include <utility>\n#include <tuple>\n#include <type_traits>\n#include <gsl/gsl_assert>\n\ntemplate<class Specimen, class Rating>\nclass evaluated_specimen {\npublic:\n\tusing value_type = Specimen;\n\tusing rating_type = Rating;\n\ttemplate<class... Args, class = std::enable_if_t<!std::is_same_v<std::tuple<std::decay_t<Args>...>, std::tuple<evaluated_specimen>>>>\n\tconstexpr evaluated_specimen(Args&&... args) noexcept(sizeof...(Args) == 0);\n\tconstexpr value_type& value() & noexcept;\n\tconstexpr const value_type& value() const& noexcept;\n\tconstexpr bool has_rating() const noexcept;\n\tconstexpr rating_type rating() const;\n\ttemplate<class Function>\n\tvoid evaluate(Function&& evaluator);\nprivate:\n\tvalue_type specimen;\n\tstd::optional<rating_type> grade;\n};\n\ntemplate<class Specimen, class Rating>\ntemplate<class... Args, class>\nconstexpr evaluated_specimen<Specimen, Rating>::evaluated_specimen(Args&&... args) noexcept(sizeof...(Args) == 0)\n\t: specimen(std::forward<Args>(args)...) {}\n\ntemplate<class Specimen, class Rating>\nconstexpr auto evaluated_specimen<Specimen, Rating>::value() & noexcept -> value_type& {\n\treturn specimen;\n}\n\ntemplate<class Specimen, class Rating>\nconstexpr auto evaluated_specimen<Specimen, Rating>::value() const& noexcept -> const value_type& {\n\treturn specimen;\n}\n\ntemplate<class Specimen, class Rating>\nconstexpr bool evaluated_specimen<Specimen, Rating>::has_rating() const noexcept {\n\treturn grade.has_value();\n}\n\ntemplate<class Specimen, class Rating>\nconstexpr auto evaluated_specimen<Specimen, Rating>::rating() const -> rating_type {\n\treturn grade.value();\n}\n\ntemplate<class Specimen, class Rating>\ntemplate<class Function>\ninline void evaluated_specimen<Specimen, Rating>::evaluate(Function&& evaluator) {\n\tgrade.emplace(evaluator(std::as_const(specimen)));\n\tEnsures(has_rating());\n}\n\n#endif\n", "meta": {"hexsha": "8699e6a0ffded186ca97e3178cbe7c77ba21cb33", "size": 3207, "ext": "h", "lang": "C", "max_stars_repo_path": "Genetic-Algorithm-Library/evaluated_specimen.h", "max_stars_repo_name": "SirEmentaler/Eugenics-Wars", "max_stars_repo_head_hexsha": "8a093d42ca935556e7d6ccaee5a57b8dd0c6b3e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Genetic-Algorithm-Library/evaluated_specimen.h", "max_issues_repo_name": "SirEmentaler/Eugenics-Wars", "max_issues_repo_head_hexsha": "8a093d42ca935556e7d6ccaee5a57b8dd0c6b3e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Genetic-Algorithm-Library/evaluated_specimen.h", "max_forks_repo_name": "SirEmentaler/Eugenics-Wars", "max_forks_repo_head_hexsha": "8a093d42ca935556e7d6ccaee5a57b8dd0c6b3e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.7294117647, "max_line_length": 134, "alphanum_fraction": 0.7383847833, "num_tokens": 682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14033624229926062, "lm_q2_score": 0.029312232341292967, "lm_q1q2_score": 0.004113568540179913}}
{"text": "/* Copyright (c) 2011-2019, NVIDIA CORPORATION. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *  * Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n *  * Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n *  * Neither the name of NVIDIA CORPORATION nor the names of its\n *    contributors may be used to endorse or promote products derived\n *    from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n#pragma once\n\n#include <util.h>\n\n#include <amg.h>\n#include <basic_types.h>\n#include <types.h>\n#include <norm.h>\n#include <logger.h>\n#include <matrix_distribution.h>\n\n#include <iostream>\n#include <iomanip>\n#include <blas.h>\n#include <multiply.h>\n\n#include <amg_level.h>\n#include <amgx_c.h>\n#include <profile.h>\n\n#include <misc.h>\n#include <string>\n#include <cassert>\n#include <csr_multiply.h>\n#include <memory_info.h>\n\n#include <thrust/sort.h>\n#include <thrust/remove.h>\n#include <thrust/unique.h>\n#include <thrust/binary_search.h>\n#include <thrust/iterator/constant_iterator.h>\n\n#define COARSE_CLA_CONSO 0 // used enable / disable coarse level consolidation (used in cycles files)\n\nnamespace amgx\n{\n\n/**********************************************************\n * Glue ( Consolidation)\n *********************************************************/\n#ifdef AMGX_WITH_MPI\n\n//------------------------\n//---------Matrix-------------\n//------------------------\ntemplate<class TConfig>\nvoid compute_glue_info(Matrix<TConfig> &A)\n{\n    // Fill distributed manager fields for consolidation\n    // Example\n    // destination_part = [0 0 0 0 4 4 4 4 8 8 8 8] (input from manager->computeDestinationPartitions)\n    // num_parts_to_consolidate = 4 for partitions 0,4,8 - (0 otherwise)\n    // parts_to_consolidate (rank 0)[0 1 2 3] (rank 4)[4 5 6 7] (rank 8)[8 9 10 11]\n    //coarse_part_to_fine_part = [0 4 8] num_coarse_partitions = 3\n    //fine_part_to_coarse_part = [0 0 0 0 1 1 1 1 2 2 2 2]\n    //ConsolidationArrayOffsets constains the offset of the nnz of each partitions in row pointer fashion : 0, pat1.NNZ, pat1.NNZ+part2.NNZ ... NNZ\n    typedef typename TConfig::template setMemSpace<AMGX_host>::Type TConfig_h;\n    typedef typename TConfig_h::template setVecPrec<AMGX_vecInt>::Type ivec_value_type_h;\n    typedef typename ivec_value_type_h::VecPrec VecInt_t;\n\n    bool is_root_partition = false;\n    int num_parts_to_consolidate = 0;\n    int num_parts = A.manager->getComms()->get_num_partitions();\n    int my_id = A.manager->global_id();\n    Vector<ivec_value_type_h> parts_to_consolidate;\n    Vector<ivec_value_type_h> dest_partitions = A.manager->getDestinationPartitions();\n\n    // compute is_root_partition and num_parts_to_consolidate\n    for (int i = 0; i < num_parts; i++)\n    {\n        if (dest_partitions[i] == my_id)\n        {\n            is_root_partition = true;\n            num_parts_to_consolidate++;\n        }\n    }\n\n    parts_to_consolidate.resize(num_parts_to_consolidate);\n    // parts_to_consolidate\n    int count = 0;\n\n    for (int i = 0; i < num_parts; i++)\n    {\n        if (dest_partitions[i] == my_id)\n        {\n            parts_to_consolidate[count] = i;\n            count++;\n        }\n    }\n\n    A.manager->setIsRootPartition(is_root_partition);\n    A.manager->setNumPartsToConsolidate(num_parts_to_consolidate);\n    A.manager->setPartsToConsolidate(parts_to_consolidate);\n    // We don't really use the following in the latest version of the glue path but they are useful information\n    // coarse_to_fine_part, fine_to_coarse_part\n    Vector<ivec_value_type_h> coarse_to_fine_part, fine_to_coarse_part(num_parts);\n    coarse_to_fine_part = dest_partitions;\n    thrust::sort(coarse_to_fine_part.begin(), coarse_to_fine_part.end());\n    cudaCheckError();\n    coarse_to_fine_part.erase(thrust::unique(coarse_to_fine_part.begin(), coarse_to_fine_part.end()), coarse_to_fine_part.end());\n    cudaCheckError();\n    thrust::lower_bound(coarse_to_fine_part.begin(), coarse_to_fine_part.end(), dest_partitions.begin(), dest_partitions.end(), fine_to_coarse_part.begin());\n    cudaCheckError();\n    A.manager->setCoarseToFine(coarse_to_fine_part);\n    A.manager->setFineToCoarse(fine_to_coarse_part);\n    Vector<ivec_value_type_h> consolidationArrayOffsets;\n    consolidationArrayOffsets.resize(num_parts);\n}\n\ntemplate<class TConfig>\nMPI_Comm compute_glue_matrices_communicator(Matrix<TConfig> &A)\n{\n    // Create temporary communicators for each consilidated matrix\n    int rank;\n    MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n\n    if (A.manager->getDestinationPartitions().size() != 0)\n    {\n        int color = A.manager->getDestinationPartitions()[rank];\n        MPI_Comm new_comm;\n        // Split a communicator into multiple, non-overlapping communicators by color(each destiation partition has its color)\n        // 1. Use MPI_Allgather to get the color and key from each process\n        // 2. Count the number of processes with the same color; create a\n        //    communicator with that many processes.  If this process has\n        //    MPI_UNDEFINED as the color, create a process with a single member.\n        // 3. Use key to order the ranks\n        MPI_Comm_split(MPI_COMM_WORLD, color, rank, &new_comm);\n        return new_comm;\n    }\n    else\n    {\n        FatalError(\"NO DESTINATION PARTIONS\", AMGX_ERR_CORE);\n    }\n}\n\n//function object (functor) for thrust calls (it is a unary operator to add a constant)\ntemplate<typename T>\nclass add_constant_op\n{\n        const T c;\n    public:\n        add_constant_op(T _c) : c(_c) {}\n        __host__ __device__ T operator()(const T &x) const\n        {\n            return x + c;\n        }\n};\n\ntemplate<class TConfig>\nint create_part_offsets(MPI_Comm &mpicm, Matrix<TConfig> &nv_mtx)\n{\n    /* WARNING: Notice that part_offsets_h & part_offsets have type int64_t.\n                Therefore we need to use MPI_INT64_T (or MPI_LONG_LONG) in MPI_Allgather.\n                Also, we need the send & recv buffers to be of the same type, therefore\n                we will create a temporary variable n64 of the correct type below. */\n    //create TConfig64, which is the same as TConfig, but with index type being int64_t\n    typedef typename TConfig::template setVecPrec<AMGX_vecInt64>::Type TConfig64;\n    typedef typename TConfig64::VecPrec t_VecPrec; //t_VecPrec = int64_t\n    int n, offset, mpist;\n    int nranks = 0; //nv_mtx.manager->get_num_partitions();\n\n    if (nv_mtx.manager != NULL)\n    {\n        //some initializations\n        nv_mtx.getOffsetAndSizeForView(OWNED, &offset, &n);\n        MPI_Comm_size(mpicm, &nranks);\n        nv_mtx.manager->part_offsets_h.resize(nranks + 1);\n        //gather the number of rows per partition on the host (on all ranks)\n        t_VecPrec n64 = n;\n        nv_mtx.manager->part_offsets_h[0] = 0; //first element is zero (the # of rows is gathered afterwards)\n\n        if (typeid(t_VecPrec) == typeid(int64_t))\n        {\n            mpist = MPI_Allgather(&n64, 1, MPI_INT64_T, nv_mtx.manager->part_offsets_h.raw() + 1, 1, MPI_INT64_T, mpicm);\n        }\n        else\n        {\n            FatalError(\"MPI_Gatherv of the vector has failed - incorrect vector data type\", AMGX_ERR_CORE);\n        }\n\n        if (mpist != MPI_SUCCESS)\n        {\n            FatalError(\"MPI_Gatherv of the vector has failed - detected incorrect MPI return code\", AMGX_ERR_CORE);\n        }\n\n        //perform a prefix sum\n        thrust::inclusive_scan(nv_mtx.manager->part_offsets_h.begin(), nv_mtx.manager->part_offsets_h.end(), nv_mtx.manager->part_offsets_h.begin());\n        //create the corresponding array on device (this is important)\n        nv_mtx.manager->part_offsets.resize(nranks + 1);\n        thrust::copy(nv_mtx.manager->part_offsets_h.begin(), nv_mtx.manager->part_offsets_h.end(), nv_mtx.manager->part_offsets.begin());\n    }\n\n    return 0;\n}\n\ntemplate<class TConfig>\nint glue_matrices(Matrix<TConfig> &nv_mtx, MPI_Comm &nv_mtx_com, MPI_Comm &temp_com)\n{\n    typedef typename TConfig::IndPrec t_IndPrec;\n    typedef typename TConfig::MatPrec t_MatPrec;\n    int n, nnz, offset, l, k = 0, i;\n    int start, end, shift;\n    int mpist, root = 0;\n    //MPI call parameters\n    t_IndPrec *rc_ptr, *di_ptr;\n    t_IndPrec *hli_ptr, *hgi_ptr, *hgr_ptr, *i_ptr, *r_ptr;\n    t_MatPrec *hlv_ptr, *hgv_ptr, *v_ptr;\n    thrust::host_vector<t_IndPrec> rc;\n    thrust::host_vector<t_IndPrec> di;\n    //unpacked local matrix on the device and host\n    device_vector_alloc<t_IndPrec> Bp;\n    device_vector_alloc<t_IndPrec> Bi;\n    device_vector_alloc<t_MatPrec> Bv;\n    thrust::host_vector<t_IndPrec> hBp;\n    thrust::host_vector<t_IndPrec> hBi;\n    thrust::host_vector<t_MatPrec> hBv;\n    //Consolidated matrices on the host\n    thrust::host_vector<t_IndPrec> hAp;\n    thrust::host_vector<t_IndPrec> hAi;\n    thrust::host_vector<t_MatPrec> hAv;\n    //Consolidated matrices on the device\n    device_vector_alloc<t_IndPrec> Ap;\n    device_vector_alloc<t_IndPrec> Ai;\n    device_vector_alloc<t_MatPrec> Av;\n    //WARNING: this routine currently supports matrix only with block size =1 (it can be generalized in the future, though)\n    //initialize the defaults\n    mpist = MPI_SUCCESS;\n\n    if (nv_mtx.manager != NULL)\n    {\n        //int rank = nv_mtx.manager->global_id();\n        nv_mtx.getOffsetAndSizeForView(OWNED, &offset, &n);\n        nv_mtx.getNnzForView(OWNED, &nnz);\n\n        if (nv_mtx.manager->part_offsets_h.size() == 0 || nv_mtx.manager->part_offsets.size() == 0)   // create part_offsets_h & part_offsets\n        {\n            create_part_offsets(nv_mtx_com, nv_mtx);  // (if needed for aggregation path)\n        }\n\n        Bp.resize(n + 1);\n        Bi.resize(nnz);\n        Bv.resize(nnz);\n        hBp.resize(n + 1);\n        hBi.resize(nnz);\n        hBv.resize(nnz);\n        //--- unpack the matrix ---\n        nv_mtx.manager->unpack_partition(thrust::raw_pointer_cast(Bp.data()),\n                                         thrust::raw_pointer_cast(Bi.data()),\n                                         thrust::raw_pointer_cast(Bv.data()));\n        cudaCheckError();\n        //copy to host (should be able to optimize this out later on)\n        hBp = Bp;\n        hBi = Bi;\n        hBv = Bv;\n        cudaCheckError();\n\n        // --- Glue matrices ---\n\n        // construct global row pointers\n        // compute recvcounts and displacements for MPI_Gatherv\n        if (nv_mtx.manager->isRootPartition())\n        {\n            l = nv_mtx.manager->getNumPartsToConsolidate();      // number of partitions\n            rc.resize(l);\n            di.resize(l);\n\n            //compute recvcounts and displacements for MPI_Gatherv\n            for (i = 0; i < l; i++)\n            {\n                start = nv_mtx.manager->part_offsets_h[nv_mtx.manager->getPartsToConsolidate()[i]];\n                end   = nv_mtx.manager->part_offsets_h[nv_mtx.manager->getPartsToConsolidate()[i] + 1];\n                rc[i] = end - start;\n                di[i] = k + 1;\n                k += rc[i];\n            }\n\n            hAp.resize(k + 1); // extra +1 is needed because row_offsets have one extra element at the end\n        }\n\n        cudaCheckError();\n        //alias raw pointers to thrust vector data (see thrust example unwrap_pointer for details)\n        rc_ptr = thrust::raw_pointer_cast(rc.data());\n        di_ptr = thrust::raw_pointer_cast(di.data());\n        hli_ptr = thrust::raw_pointer_cast(hBp.data());\n        hgr_ptr = thrust::raw_pointer_cast(hAp.data());\n        cudaCheckError();\n\n        //gather (on the host)\n        if (typeid(t_IndPrec) == typeid(int))\n        {\n            mpist = MPI_Gatherv(hli_ptr + 1, n, MPI_INT,  hgr_ptr, rc_ptr, di_ptr, MPI_INT, root, temp_com);\n        }\n        else\n        {\n            FatalError(\"MPI_Gatherv of the vector has failed - incorrect vector data type\", AMGX_ERR_CORE);\n        }\n\n        if (mpist != MPI_SUCCESS)\n        {\n            FatalError(\"MPI_Gatherv of the vector has failed - detected incorrect MPI return code\", AMGX_ERR_CORE);\n        }\n\n        // Adjust row pointers, construct global column indices and values (recvcounts and displacements were computed above)\n        if (nv_mtx.manager->isRootPartition())\n        {\n            //adjust global row pointers and setup the recvcounts & displacements for subsequent MPI calls\n            for (i = 0; i < l; i++)\n            {\n                start = di[i] - 1;\n                end   = di[i] + rc[i] - 1;\n                shift = hAp[start];\n                thrust::transform(hAp.begin() + start + 1, hAp.begin() + end + 1, hAp.begin() + start + 1, add_constant_op<t_IndPrec>(shift));\n                cudaCheckError();\n                di[i] = shift;\n                rc[i] = hAp[end] - hAp[start];\n            }\n\n            //some allocations/resizing\n            hAi.resize(hAp[k]);\n            hAv.resize(hAp[k]);\n        }\n\n        //alias raw pointers to thrust vector data (see thrust example unwrap_pointer for details)\n        rc_ptr = thrust::raw_pointer_cast(rc.data());\n        di_ptr = thrust::raw_pointer_cast(di.data());\n        hli_ptr = thrust::raw_pointer_cast(hBi.data());\n        hgi_ptr = thrust::raw_pointer_cast(hAi.data());\n        hlv_ptr = thrust::raw_pointer_cast(hBv.data());\n        hgv_ptr = thrust::raw_pointer_cast(hAv.data());\n        cudaCheckError();\n\n        //gather (on the host)\n        //columns indices\n        if (typeid(t_IndPrec) == typeid(int))\n        {\n            mpist = MPI_Gatherv(hli_ptr, nnz, MPI_INT,  hgi_ptr, rc_ptr, di_ptr, MPI_INT,  root, temp_com);\n        }\n        else\n        {\n            FatalError(\"MPI_Gatherv of the vector has failed - incorrect vector data type\", AMGX_ERR_CORE);\n        }\n\n        if (mpist != MPI_SUCCESS)\n        {\n            FatalError(\"MPI_Gatherv of the vector has failed - detected incorrect MPI return code\", AMGX_ERR_CORE);\n        }\n\n        //values\n        if      (typeid(t_MatPrec) == typeid(float))\n        {\n            mpist = MPI_Gatherv(hlv_ptr, nnz, MPI_FLOAT,  hgv_ptr, rc_ptr, di_ptr, MPI_FLOAT,  root, temp_com);\n        }\n        else if (typeid(t_MatPrec) == typeid(double))\n        {\n            mpist = MPI_Gatherv(hlv_ptr, nnz, MPI_DOUBLE, hgv_ptr, rc_ptr, di_ptr, MPI_DOUBLE, root, temp_com);\n        }\n        else\n        {\n            FatalError(\"MPI_Gatherv of the vector has failed - incorrect vector data type\", AMGX_ERR_CORE);\n        }\n\n        if (mpist != MPI_SUCCESS)\n        {\n            FatalError(\"MPI_Gatherv of the vector has failed - detected incorrect MPI return code\", AMGX_ERR_CORE);\n        }\n\n        // --- Upload matrices ---\n        if (nv_mtx.manager->isRootPartition())\n        {\n            n = hAp.size() - 1;\n            nnz = hAi.size();\n            Ap.resize(hAp.size());\n            Ai.resize(hAi.size());\n            Av.resize(hAv.size());\n            thrust::copy(hAp.begin(), hAp.end(), Ap.begin());\n            thrust::copy(hAi.begin(), hAi.end(), Ai.begin());\n            thrust::copy(hAv.begin(), hAv.end(), Av.begin());\n            cudaCheckError();\n        }\n        else\n        {\n            n = 0;\n            nnz  = 0;\n            Ap.resize(1); // warning row_ponter size is expected to be n+1.\n            Ap.push_back(0);\n            Ai.resize(0);\n            Av.resize(0);\n            cudaCheckError();\n        }\n\n        r_ptr = thrust::raw_pointer_cast(Ap.data());\n        i_ptr = thrust::raw_pointer_cast(Ai.data());\n        v_ptr = thrust::raw_pointer_cast(Av.data());\n        cudaCheckError();\n        upload_matrix_after_glue(n, nnz, r_ptr, i_ptr, v_ptr, nv_mtx);\n    }\n    else\n    {\n        /* ASSUMPTION: when manager has not been allocated you are running on a single rank */\n    }\n\n    return 0;\n}\n\n\ntemplate<class TConfig>\nint upload_matrix_after_glue(int n, int nnz, int *r_ptr, int *i_ptr, void *v_ptr, Matrix<TConfig> &nv_mtx)\n{\n    // Using a path similar to AMGX_matrix_upload_all_global\n    typedef typename TConfig::IndPrec t_IndPrec;\n    typedef typename TConfig::MatPrec t_MatPrec;\n    typedef typename TConfig::template setMemSpace<AMGX_host>::Type TConfig_h;\n    typedef typename TConfig::template setVecPrec<AMGX_vecInt>::Type ivec_value_type;\n    typedef typename TConfig_h::template setVecPrec<AMGX_vecInt>::Type ivec_value_type_h;\n    typedef typename ivec_value_type_h::VecPrec VecInt_t;\n    typedef Vector<ivec_value_type> IVector;\n    // some parameters\n    int block_dimx, block_dimy, num_ranks, n_global, start, end, val;\n    t_IndPrec *part_vec_ptr;\n    thrust::host_vector<t_IndPrec> pv;\n    // set parameters\n    nv_mtx.setView(ALL); // not sure about this\n    n_global = nv_mtx.manager->part_offsets_h.back();\n    block_dimx = nv_mtx.get_block_dimx();\n    block_dimy = nv_mtx.get_block_dimy();\n    //MPI_Comm* mpi_comm = nv_mtx.getResources()->getMpiComm();\n    //MPI_Comm_size(*mpi_comm, &num_ranks);\n    num_ranks = nv_mtx.manager->getComms()->get_num_partitions();\n    // WARNING We create an artificial partition vectior that matches the new distribution\n    // example n = 8, num_ranks(ie. num partitions) = 4 , DestinationPartitions[0,0,2,2], partvec = [0,0,0,0,2,2,2,2]\n    // This might be an issue for the finest level if input_partvect !=NULL\n    Vector<ivec_value_type_h> dest_partitions = nv_mtx.manager->getDestinationPartitions();\n\n    for (int i = 0; i < num_ranks; i++)\n    {\n        val = dest_partitions[i];\n        start = nv_mtx.manager->part_offsets_h[i];\n        end   = nv_mtx.manager->part_offsets_h[i + 1];\n\n        for (int j = 0; j < end - start; j++)\n        {\n            pv.push_back(val);\n        }\n    }\n\n    part_vec_ptr = thrust::raw_pointer_cast(pv.data());\n    cudaCheckError();\n    // Save some glue info\n    bool is_root_partition = nv_mtx.manager->isRootPartition();\n    int dest_part = nv_mtx.manager->getMyDestinationPartition();\n    int num_parts_to_consolidate = nv_mtx.manager->getNumPartsToConsolidate();\n    Vector<ivec_value_type_h> parts_to_consolidate = nv_mtx.manager->getPartsToConsolidate();\n    std::vector<int> cao;\n\n    for (int i = 0; i < nv_mtx.manager->part_offsets_h.size(); i++)\n    {\n        cao.push_back(nv_mtx.manager->part_offsets_h[i]);\n    }\n\n    // WARNING\n    // renumbering contains the inverse permutation to unreorder an amgx vector\n    // inverse_renumbering contains the permutaion to reorder an amgx vector\n    Vector<ivec_value_type> ir = nv_mtx.manager->inverse_renumbering;\n    Vector<ivec_value_type> r = nv_mtx.manager->renumbering;\n    // We need that to exchange the halo of unglued vectors (in coarse level consolidation)\n    Vector<ivec_value_type_h> nei = nv_mtx.manager->neighbors;  // just neighbors before glue\n    std::vector<std::vector<VecInt_t> > b2lr = nv_mtx.manager->getB2Lrings(); //list of boundary nodes to export to other partitions.\n    Vector<ivec_value_type_h> ho = nv_mtx.manager->halo_offsets;\n    std::vector<IVector > b2lm = nv_mtx.manager->getB2Lmaps();\n    cudaCheckError();\n\n    // Create a fresh distributed manager\n    if (nv_mtx.manager != NULL )\n    {\n        delete nv_mtx.manager;\n    }\n\n    nv_mtx.manager = new DistributedManager<TConfig>(nv_mtx);\n    nv_mtx.set_initialized(0);\n    nv_mtx.delProps(DIAG);\n    // Load distributed matrix\n    MatrixDistribution mdist;\n    mdist.setPartitionVec(part_vec_ptr);\n    nv_mtx.manager->loadDistributedMatrix(n, nnz, block_dimx, block_dimy, r_ptr, i_ptr, (t_MatPrec *) v_ptr, num_ranks, n_global, NULL, mdist);\n    // Create B2L_maps for comm\n    nv_mtx.manager->renumberMatrixOneRing();\n    // WARNING WE SHOULD GET THE NUMBER OF RINGS AND DO THE FOLLOWING ONLY IF THERE ARE 2 RINGS\n    // Exchange 1 ring halo rows (for d2 interp)\n    // if (num_import_rings == 2)\n    nv_mtx.manager->createOneRingHaloRows();\n    nv_mtx.manager->getComms()->set_neighbors(nv_mtx.manager->num_neighbors());\n    nv_mtx.setView(OWNED);\n    nv_mtx.set_initialized(1);\n    cudaCheckError();\n    // restore some glue info to consolidate the vectors in the future\n    nv_mtx.manager->setDestinationPartitions(dest_partitions);\n    nv_mtx.manager->setIsRootPartition(is_root_partition);\n    nv_mtx.manager->setNumPartsToConsolidate(num_parts_to_consolidate);\n    nv_mtx.manager->setPartsToConsolidate(parts_to_consolidate);\n    nv_mtx.manager->setIsGlued(true);\n    nv_mtx.manager->setMyDestinationPartition(dest_part);\n    nv_mtx.manager->setConsolidationArrayOffsets(cao); // partions_offest before consolidation\n    // set fine level data structures, this is used to match the former distribution when we upload / download from the API\n\n    if (nv_mtx.amg_level_index == 0)\n    {\n        // just small copies inside fineLevelUpdate.\n        nv_mtx.manager->fineLevelUpdate();\n    }\n\n    nv_mtx.manager->renumbering_before_glue = r;\n    nv_mtx.manager->inverse_renumbering_before_glue = ir;\n    nv_mtx.manager->neighbors_before_glue = nei;\n    nv_mtx.manager->halo_offsets_before_glue = ho;\n    nv_mtx.manager->B2L_rings_before_glue = b2lr;\n    nv_mtx.manager->B2L_maps_before_glue = b2lm;\n    cudaCheckError();\n    return 0;\n}\n\ntemplate<class TConfig>\nint glue_vector(Matrix<TConfig> &nv_mtx, MPI_Comm &A_comm, Vector<TConfig> &nv_vec, MPI_Comm &temp_com)\n{\n    // glu vecots based on dest_partitions (which contains partitions should be merged together)\n    typedef typename TConfig::IndPrec t_IndPrec;\n    typedef typename TConfig::VecPrec t_VecPrec;\n    int n, l, mpist, start, end, k = 0, root = 0, rank = 0;\n    //MPI call parameters\n    t_IndPrec *rc_ptr, *di_ptr;\n    t_VecPrec *hv_ptr, *hg_ptr, *v_ptr;\n    thrust::host_vector<t_IndPrec> rc;\n    thrust::host_vector<t_IndPrec> di;\n    //unreordered local vector on the host\n    thrust::host_vector<t_VecPrec> hv;\n    //constructed global vector on the host\n    thrust::host_vector<t_VecPrec> hg;\n    //constructed global vector on the device\n    device_vector_alloc<t_VecPrec> v;\n    //WARNING: this routine currently supports vectors only with block size =1 (it can be generalized in the future, though)\n    //initialize the defaults\n    mpist = MPI_SUCCESS;\n\n    if (nv_mtx.manager != NULL)\n    {\n        // some initializations\n        rank = nv_mtx.manager->global_id();\n\n        if (nv_mtx.manager->getComms() != NULL)\n        {\n            nv_mtx.manager->getComms()->get_mpi_comm();\n        }\n\n        n = nv_mtx.manager->getConsolidationArrayOffsets()[rank + 1] - nv_mtx.manager->getConsolidationArrayOffsets()[rank];\n\n        if (nv_mtx.manager->getConsolidationArrayOffsets().size() == 0)\n        {\n            std::cout << \"ERROR part_offsets in glue path\" << std::endl;\n        }\n\n        l = nv_mtx.manager->getNumPartsToConsolidate();      // number of partitions\n        //some allocations/resizing\n        hv.resize(nv_mtx.manager->renumbering_before_glue.size());                         // host copy of nv_vec\n\n        if (nv_mtx.manager->isRootPartition())\n        {\n            // This works with neighbours only\n            hg.resize(nv_mtx.manager->getConsolidationArrayOffsets()[rank + l] - nv_mtx.manager->getConsolidationArrayOffsets()[rank]); // host copy of cvec\n            rc.resize(l);\n            di.resize(l);\n        }\n\n        cudaCheckError();\n        //--- unreorder the vector back (just like you did with the matrix, but only need to undo the interior-boundary reordering, because others do not apply) ---\n        // unreorder and copy the vector\n        // WARNING\n        // renumbering contains the inverse permutation to unreorder an amgx vector\n        // inverse_renumbering contains the permutaion to reorder an amgx vector\n        thrust::copy(thrust::make_permutation_iterator(nv_vec.begin(), nv_mtx.manager->renumbering_before_glue.begin()  ),\n                     thrust::make_permutation_iterator(nv_vec.begin(), nv_mtx.manager->renumbering_before_glue.begin() +  nv_mtx.manager->renumbering_before_glue.size()),\n                     hv.begin());\n        cudaCheckError();\n        hv.resize(n);\n\n        // --- construct global vector (rhs/sol) ---\n        //compute recvcounts and displacements for MPI_Gatherv\n        if (nv_mtx.manager->isRootPartition())\n        {\n            l = nv_mtx.manager->getNumPartsToConsolidate();      // number of partitions\n\n            //compute recvcounts and displacements for MPI_Gatherv\n            for (int i = 0; i < l; i++)\n            {\n                start = nv_mtx.manager->getConsolidationArrayOffsets()[nv_mtx.manager->getPartsToConsolidate()[i]];\n                end   = nv_mtx.manager->getConsolidationArrayOffsets()[nv_mtx.manager->getPartsToConsolidate()[i] + 1];\n                rc[i] = end - start;\n                di[i] = k;\n                k += rc[i];\n            }\n        }\n\n        //alias raw pointers to thrust vector data (see thrust example unwrap_pointer for details)\n        rc_ptr = thrust::raw_pointer_cast(rc.data());\n        di_ptr = thrust::raw_pointer_cast(di.data());\n        hv_ptr = thrust::raw_pointer_cast(hv.data());\n        hg_ptr = thrust::raw_pointer_cast(hg.data());\n        cudaCheckError();\n\n        //gather (on the host)\n        if      (typeid(t_VecPrec) == typeid(float))\n        {\n            mpist = MPI_Gatherv(hv_ptr, n, MPI_FLOAT,  hg_ptr, rc_ptr, di_ptr, MPI_FLOAT,  root, temp_com);\n        }\n        else if (typeid(t_VecPrec) == typeid(double))\n        {\n            mpist = MPI_Gatherv(hv_ptr, n, MPI_DOUBLE, hg_ptr, rc_ptr, di_ptr, MPI_DOUBLE, root, temp_com);\n        }\n        else\n        {\n            FatalError(\"MPI_Gatherv of the vector has failed - incorrect vector data type\", AMGX_ERR_CORE);\n        }\n\n        if (mpist != MPI_SUCCESS)\n        {\n            FatalError(\"MPI_Gatherv of the vector has failed - detected incorrect MPI return code\", AMGX_ERR_CORE);\n        }\n\n        // clean\n        nv_vec.in_transfer = IDLE;\n\n        //nv_vec.dirtybit = 0;\n        if (nv_vec.buffer != NULL)\n        {\n            delete nv_vec.buffer;\n            nv_vec.buffer = NULL;\n            nv_vec.buffer_size = 0;\n        }\n\n        if (nv_vec.linear_buffers_size != 0)\n        {\n            amgx::memory::cudaFreeHost(&(nv_vec.linear_buffers[0]));\n            nv_vec.linear_buffers_size = 0;\n        }\n\n        if (nv_vec.explicit_host_buffer)\n        {\n            amgx::memory::cudaFreeHost(nv_vec.explicit_host_buffer);\n            nv_vec.explicit_host_buffer = NULL;\n            nv_vec.explicit_buffer_size = 0;\n            cudaEventDestroy(nv_vec.mpi_event);\n        }\n\n        // resize\n        if (nv_mtx.manager->isRootPartition())\n        {\n            n = hg.size();\n            v.resize(hg.size());\n            thrust::copy(hg.begin(), hg.end(), v.begin());\n            cudaCheckError();\n        }\n        else\n        {\n            n = 0;\n            v.resize(0);\n            cudaCheckError();\n        }\n\n        // upload\n        v_ptr = thrust::raw_pointer_cast(v.data());\n        cudaCheckError();\n        upload_vector_after_glue(n, v_ptr, nv_vec, nv_mtx);\n    }\n    else\n    {\n        // ASSUMPTION: when manager has not been allocated you are running on a single rank\n    }\n\n    return 0;\n}\n\n\ntemplate<class TConfig>\nint upload_vector_after_glue(int n, void *v_ptr, Vector<TConfig> &nv_vec, Matrix<TConfig> &nv_mtx)\n{\n    typedef typename TConfig::VecPrec t_VecPrec;\n    // vector bind\n    nv_vec.unsetManager();\n    cudaCheckError();\n\n    if (nv_mtx.manager != NULL)\n    {\n        nv_vec.setManager(*(nv_mtx.manager));\n    }\n\n    cudaCheckError();\n\n    if (nv_vec.is_transformed())\n    {\n        nv_vec.unset_transformed();\n    }\n\n    nv_vec.set_block_dimx(1);\n    nv_vec.set_block_dimy(nv_mtx.get_block_dimy());\n    // the dirtybit has to be set to one here in order to have correct results to ensure an exachange halo before the solve\n    // this is particulary important when the number of consolidated partitions is greater than 1 on large matrices such as drivaer9M\n    nv_vec.dirtybit = 1;\n\n    if (nv_mtx.manager != NULL)\n    {\n        nv_vec.getManager()->transformAndUploadVector(nv_vec, (t_VecPrec *)v_ptr, n, nv_vec.get_block_dimy());\n    }\n\n    MPI_Barrier(MPI_COMM_WORLD);\n    return 0;\n}\n\ntemplate<class TConfig>\nint unglue_vector(Matrix<TConfig> &nv_mtx, MPI_Comm &A_comm, Vector<TConfig> &nv_vec, MPI_Comm &temp_com, Vector<TConfig> &nv_vec_unglued)\n{\n    // glue vecots based on dest_partitions (which contains partitions should be merged together)\n    typedef typename TConfig::IndPrec t_IndPrec;\n    typedef typename TConfig::VecPrec t_VecPrec;\n    int n_loc, l, mpist, start, end, k = 0, root = 0, rank = 0;\n    //MPI call parameters\n    t_IndPrec *sc_ptr, *di_ptr;\n    t_VecPrec *hv_ptr, *hg_ptr;\n    thrust::host_vector<t_IndPrec> sc;\n    thrust::host_vector<t_IndPrec> di;\n    //unreordered local vector on the host\n    thrust::host_vector<t_VecPrec> hv;\n    //constructed global vector on the host\n    thrust::host_vector<t_VecPrec> hg;\n    //constructed global vector on the device\n    device_vector_alloc<t_VecPrec> v;\n    //WARNING: this routine currently supports vectors only with block size =1 (it can be generalized in the future, though)\n    //initialize the defaults\n    mpist = MPI_SUCCESS;\n\n    if (nv_mtx.manager != NULL)\n    {\n        // some initializations\n        rank = nv_mtx.manager->global_id();\n\n        if (nv_mtx.manager->getComms() != NULL)\n        {\n            nv_mtx.manager->getComms()->get_mpi_comm();\n        }\n\n        n_loc = nv_mtx.manager->getConsolidationArrayOffsets()[rank + 1] - nv_mtx.manager->getConsolidationArrayOffsets()[rank];\n\n        if (nv_mtx.manager->getConsolidationArrayOffsets().size() == 0)\n        {\n            printf(\"ERROR part_offsets\\n\");\n        }\n\n        l = nv_mtx.manager->getNumPartsToConsolidate();      // number of partitions\n        //some allocations/resizing\n        hv.resize(n_loc);                         // host copy\n\n        if (nv_mtx.manager->isRootPartition())\n        {\n            hg.resize(nv_vec.size()); // host copy of cvec\n        }\n\n        sc.resize(l);\n        di.resize(l);\n        cudaCheckError();\n        // Exchange_halo before unreordering\n        // Do we need that?\n        nv_mtx.manager->exchange_halo(nv_vec, nv_vec.tag);\n\n        // unreorder the vector\n        if (nv_mtx.manager->isRootPartition())\n        {\n            // WARNING\n            // renumbering contains the inverse permutation to unreorder an amgx vector\n            // inverse_renumbering contains the permutaion to reorder an amgx vector\n            thrust::copy(thrust::make_permutation_iterator(nv_vec.begin(), nv_mtx.manager->renumbering.begin()  ),\n                         thrust::make_permutation_iterator(nv_vec.begin(), nv_mtx.manager->renumbering.begin() + nv_mtx.manager->renumbering.size()),\n                         hg.begin());\n            cudaCheckError();\n            hg.resize(nv_mtx.manager->getConsolidationArrayOffsets()[rank + l] - nv_mtx.manager->getConsolidationArrayOffsets()[rank]);\n        }\n\n        // --- construct local vector (sol) ---\n        //compute sendcounts and displacements for MPI_Gatherv\n        for (int i = 0; i < l; i++)\n        {\n            start = nv_mtx.manager->getConsolidationArrayOffsets()[nv_mtx.manager->getPartsToConsolidate()[i]];\n            end   = nv_mtx.manager->getConsolidationArrayOffsets()[nv_mtx.manager->getPartsToConsolidate()[i] + 1];\n            sc[i] = end - start;\n            di[i] = k;\n            k += sc[i];\n        }\n\n        //alias raw pointers to thrust vector data (see thrust example unwrap_pointer for details)\n        sc_ptr = thrust::raw_pointer_cast(sc.data());\n        di_ptr = thrust::raw_pointer_cast(di.data());\n        hv_ptr = thrust::raw_pointer_cast(hv.data());\n        hg_ptr = thrust::raw_pointer_cast(hg.data());\n        cudaCheckError();\n\n        // Scatter (on the host)\n        if      (typeid(t_VecPrec) == typeid(float))\n        {\n            mpist = MPI_Scatterv(hg_ptr, sc_ptr, di_ptr, MPI_FLOAT,  hv_ptr, n_loc, MPI_FLOAT,  root, temp_com);\n        }\n        else if (typeid(t_VecPrec) == typeid(double))\n        {\n            mpist = MPI_Scatterv(hg_ptr, sc_ptr, di_ptr, MPI_DOUBLE, hv_ptr, n_loc, MPI_DOUBLE, root, temp_com);\n        }\n        else\n        {\n            FatalError(\"MPI_Gatherv of the vector has failed - incorrect vector data type\", AMGX_ERR_CORE);\n        }\n\n        if (mpist != MPI_SUCCESS)\n        {\n            FatalError(\"MPI_Gatherv of the vector has failed - detected incorrect MPI return code\", AMGX_ERR_CORE);\n        }\n\n        // --- Manual upload ---\n        // Cleaning\n        nv_vec_unglued.in_transfer = IDLE;\n\n        if (nv_vec_unglued.buffer != NULL)\n        {\n            delete nv_vec_unglued.buffer;\n            nv_vec_unglued.buffer = NULL;\n            nv_vec_unglued.buffer_size = 0;\n        }\n\n        if (nv_vec_unglued.linear_buffers_size != 0)\n        {\n            amgx::memory::cudaFreeHost(&(nv_vec_unglued.linear_buffers[0]));\n            nv_vec_unglued.linear_buffers_size = 0;\n        }\n\n        if (nv_vec_unglued.explicit_host_buffer)\n        {\n            amgx::memory::cudaFreeHost(nv_vec_unglued.explicit_host_buffer);\n            nv_vec_unglued.explicit_host_buffer = NULL;\n            nv_vec_unglued.explicit_buffer_size = 0;\n            cudaEventDestroy(nv_vec_unglued.mpi_event);\n        }\n\n        // We should avoid copies between nv_vec and hv here\n        nv_vec_unglued.resize( nv_mtx.manager->inverse_renumbering_before_glue.size());\n        thrust::fill( nv_vec_unglued.begin(), nv_vec_unglued.end(), 0.0 );\n        thrust::copy(hv.begin(), hv.end(), nv_vec_unglued.begin());\n        hv.resize( nv_mtx.manager->inverse_renumbering_before_glue.size());\n        cudaCheckError();\n        //  Manual reordering\n        //  Upload_vector_after_glue is not going to work because matrix managers has been modified during glued matrices, and don't match the new, glued, topology.\n        thrust::copy(thrust::make_permutation_iterator(nv_vec_unglued.begin(), nv_mtx.manager->inverse_renumbering_before_glue.begin()  ),\n                     thrust::make_permutation_iterator(nv_vec_unglued.begin(), nv_mtx.manager->inverse_renumbering_before_glue.begin() + nv_mtx.manager->inverse_renumbering_before_glue.size()),\n                     hv.begin());\n        cudaCheckError();\n        thrust::fill( nv_vec_unglued.begin(), nv_vec_unglued.end(), 0.0 );\n        thrust::copy(hv.begin(), hv.end(), nv_vec_unglued.begin());\n    }\n    else\n    {\n        // ASSUMPTION: when manager has not been allocated you are running on a single rank\n        printf(\"Glue was called on a single rank\\n\");\n    }\n\n    return 0;\n}\n\n#if 0\n\n// The folowing code is to perform an exhange halo using data that doesn't matches the topology of the matrix stored in its distributed manager\n// We use instead other containers stored in the distributed manager. They are suffixed by \"_before_glue\"\n// This allows to exchange vector halo between unglued vectors from glued matrices\n\ntemplate <class TConfig>\nvoid exchange_halo_after_unglue(const Matrix<TConfig> &A, Vector<TConfig>  &data, int tag, int num_ring = 1)\n{\n    setup_after_unglue(data, A, num_ring);  //set pointers to buffer\n    gather_B2L_after_unglue(A, data, num_ring);             //write values to buffer\n    exchange_halo_after_unglue(data, A, num_ring); //exchange buffers\n    //scatter_L2H(data);            //NULL op\n}\n/*\ntemplate <class TConfig>\nvoid CommsMPIHostBufferStream<T_Config>::setup(DVector &b, const Matrix<TConfig> &m, int num_rings) { do_setup_after_unglue((b, m, num_rings);}\ntemplate <class T_Config>\nvoid CommsMPIHostBufferStream<T_Config>::exchange_halo(DVector &b, const Matrix<TConfig> &m, cudaEvent_t event, int tag, int num_rings) {  do_exchange_halo_after_unglue((b, m, num_rings);}\ntemplate <class T_Config>\nvoid CommsMPIHostBufferStream<T_Config>::setup(FVector &b, const Matrix<TConfig> &m, int tag, int num_rings) { do_setup_after_unglue((b, m, num_rings);}\ntemplate <class T_Config>\nvoid CommsMPIHostBufferStream<T_Config>::exchange_halo(FVector &b, const Matrix<TConfig> &m, cudaEvent_t event, int tag, int num_rings) {  do_exchange_halo_after_unglue((b, m, num_rings);}\n*/\ntemplate <class TConfig>\nvoid setup_after_unglue(Vector<TConfig> &b, const Matrix<TConfig> &m, int num_rings)\n{\n    /*\n    thrust::copy( m.manager->neighbors_before_glue.begin(),  m.manager->neighbors_before_glue.end(), std::ostream_iterator<int64_t>(std::cout, \" \"));\n    thrust::copy( m.manager->halo_offsets_before_glue.begin(),  m.manager->halo_offsets_before_glue.end(), std::ostream_iterator<int64_t>(std::cout, \" \"));\n    for (int i = 0; i < m.manager->B2L_rings_before_glue.size(); ++i)\n    {\n      thrust::copy( m.manager->B2L_rings_before_glue[i].begin(),  m.manager->B2L_rings_before_glue[i].end(), std::ostream_iterator<int64_t>(std::cout, \" \"));\n    }\n\n    for (int i = 0; i < m.manager->B2L_maps_before_glue.size(); ++i)\n    {\n      thrust::copy( m.manager->B2L_maps_before_glue[i].begin(),  m.manager->B2L_maps_before_glue[i].end(), std::ostream_iterator<int64_t>(std::cout, \" \"));\n    }\n    */\n    if (TConfig::memSpace == AMGX_host)\n    {\n        FatalError(\"MPI Comms module no implemented for host\", AMGX_ERR_NOT_IMPLEMENTED);\n    }\n    else\n    {\n#ifdef AMGX_WITH_MPI\n        int bsize = b.get_block_size();\n        int num_cols = b.get_num_cols();\n\n        if (bsize != 1 && num_cols != 1)\n            FatalError(\"Error: vector cannot have block size and subspace size.\",\n                       AMGX_ERR_INTERNAL);\n\n        // set num neighbors = size of B2L_rings_before_glue\n        // need to do this because comms might have more neighbors than our matrix knows about\n        int neighbors = m.manager->B2L_rings_before_glue.size();\n        m.manager->getComms()->set_neighbors(m.manager->B2L_rings_before_glue.size());\n\n        if (b.in_transfer & SENDING)\n        {\n            b.in_transfer = IDLE;\n        }\n\n        typedef typename TConfig::template setVecPrec<(AMGX_VecPrecision)AMGX_GET_MODE_VAL(AMGX_MatPrecision, TConfig::mode)>::Type value_type;\n        b.requests.resize(2 * neighbors); //first part is sends second is receives\n        b.statuses.resize(2 * neighbors);\n\n        for (int i = 0; i < 2 * neighbors; i++)\n        {\n            b.requests[i] = MPI_REQUEST_NULL;\n        }\n\n        int total = 0;\n\n        for (int i = 0; i < neighbors; i++)\n        {\n            total += m.manager->B2L_rings_before_glue[i][num_rings] * bsize * num_cols;\n        }\n\n        b.buffer_size = total;\n\n        if (b.buffer == NULL)\n        {\n            b.buffer = new Vector<TConfig>(total);\n        }\n        else\n        {\n            if (total > b.buffer->size())\n            {\n                b.buffer->resize(total);\n            }\n        }\n\n        if (b.linear_buffers_size < neighbors)\n        {\n            if (b.linear_buffers_size != 0) { amgx::memory::cudaFreeHost(b.linear_buffers); }\n\n            amgx::memory::cudaMallocHost((void **) & (b.linear_buffers), neighbors * sizeof(value_type *));\n            b.linear_buffers_size = neighbors;\n        }\n\n        cudaCheckError();\n        total = 0;\n        bool linear_buffers_changed = false;\n\n        for (int i = 0; i < neighbors; i++)\n        {\n            if (b.linear_buffers[i] != b.buffer->raw() + total)\n            {\n                linear_buffers_changed = true;\n            }\n\n            b.linear_buffers[i] = b.buffer->raw() + total;\n            total += m.manager->B2L_rings_before_glue[i][num_rings] * bsize * num_cols;\n        }\n\n        // Copy to device\n        if (linear_buffers_changed)\n        {\n            b.linear_buffers_ptrs.resize(neighbors);\n            //thrust::copy(b.linear_buffers.begin(),b.linear_buffers.end(),b.linear_buffers_ptrs.begin());\n            cudaMemcpyAsync(thrust::raw_pointer_cast(&b.linear_buffers_ptrs[0]), &(b.linear_buffers[0]), neighbors * sizeof(value_type *), cudaMemcpyHostToDevice);\n            cudaCheckError();\n        }\n\n        int size = 0;\n        size  = total + (m.manager->halo_offsets_before_glue[num_rings * neighbors] - m.manager->halo_offsets_before_glue[0]) * bsize * num_cols;\n\n        if (size > 0)\n        {\n            if (b.explicit_host_buffer == NULL)\n            {\n                b.host_buffer.resize(1);\n                cudaEventCreateWithFlags(&b.mpi_event, cudaEventDisableTiming);\n                cudaCheckError();\n                amgx::memory::cudaMallocHost((void **)&b.explicit_host_buffer, size * sizeof(value_type));\n                cudaCheckError();\n            }\n            else if (size > b.explicit_buffer_size)\n            {\n                amgx::memory::cudaFreeHost(b.explicit_host_buffer);\n                cudaCheckError();\n                amgx::memory::cudaMallocHost((void **)&b.explicit_host_buffer, size * sizeof(value_type));\n                cudaCheckError();\n            }\n\n            cudaCheckError();\n            b.explicit_buffer_size = size;\n        }\n\n#else\n        FatalError(\"MPI Comms module requires compiling with MPI\", AMGX_ERR_NOT_IMPLEMENTED);\n#endif\n    }\n}\ntemplate <class TConfig>\nvoid gather_B2L_after_unglue(const Matrix<TConfig> &m, Vector<TConfig> &b, int num_rings = 1)\n{\n    if (TConfig::memSpace == AMGX_host)\n    {\n        if (m.manager->neighbors_before_glue.size() > 0)\n        {\n            FatalError(\"Distributed solve only supported on devices\", AMGX_ERR_NOT_IMPLEMENTED);\n        }\n    }\n    else\n    {\n        for (int i = 0; i < m.manager->neighbors_before_glue.size(); i++)\n        {\n            int size = m.manager->B2L_rings_before_glue[i][num_rings];\n            int num_blocks = min(4096, (size + 127) / 128);\n\n            if ( size != 0)\n            {\n                if (b.get_num_cols() == 1)\n                {\n                    gatherToBuffer <<< num_blocks, 128>>>(b.raw(), m.manager->B2L_maps_before_glue[i].raw(), b.linear_buffers[i], b.get_block_size(), size);\n                }\n                else\n                {\n                    gatherToBufferMultivector <<< num_blocks, 128>>>(b.raw(), m.manager->B2L_maps_before_glue[i].raw(), b.linear_buffers[i], b.get_num_cols(), b.get_lda(), size);\n                }\n\n                cudaCheckError();\n            }\n        }\n    }\n}\ntemplate <class TConfig>\nvoid exchange_halo_after_unglue(Vector<TConfig> &b, const Matrix<TConfig> &m, int num_rings)\n{\n    if (TConfig::memSpace == AMGX_host)\n    {\n        FatalError(\"Halo exchanges not implemented for host\", AMGX_ERR_NOT_IMPLEMENTED);\n    }\n    else\n    {\n#ifdef AMGX_WITH_MPI\n        typedef typename TConfig::VecPrec VecPrec;\n        cudaCheckError();\n        int bsize = b.get_block_size();\n        int num_cols = b.get_num_cols();\n        int offset = 0;\n        int neighbors = m.manager->B2L_rings_before_glue.size();\n        MPI_Comm mpi_comm = m.manager->getComms()->get_mpi_comm();\n\n        if (b.buffer_size != 0)\n        {\n            cudaMemcpy(&(b.explicit_host_buffer[0]), b.buffer->raw(), b.buffer_size * sizeof(typename TConfig::VecPrec), cudaMemcpyDeviceToHost);\n        }\n\n        for (int i = 0; i < neighbors; i++)\n        {\n            int size = m.manager->B2L_rings_before_glue[i][num_rings] * bsize * num_cols;\n\n            if (size != 0)\n            {\n                MPI_Isend(&(b.explicit_host_buffer[offset]), size * sizeof(typename TConfig::VecPrec), MPI_BYTE, m.manager->neighbors_before_glue[i], m.manager->global_id(), mpi_comm, &b.requests[i]);\n            }\n            else\n            {\n                MPI_Isend(&(b.host_buffer[0]), size * sizeof(typename TConfig::VecPrec), MPI_BYTE, m.manager->neighbors_before_glue[i], m.manager->global_id(), mpi_comm, &b.requests[i]);\n            }\n\n            offset += size;\n        }\n\n        b.in_transfer = RECEIVING | SENDING;\n        offset = 0;\n\n        for (int i = 0; i < neighbors; i++)\n        {\n            // Count total size to receive from one neighbor\n            int size = 0;\n\n            for (int j = 0; j < num_rings; j++)\n            {\n                size += m.manager->halo_offsets_before_glue[j * neighbors + i + 1] * bsize * num_cols - m.manager->halo_offsets_before_glue[j * neighbors + i] * bsize * num_cols;\n            }\n\n            if (size != 0)\n            {\n                MPI_Irecv(&(b.explicit_host_buffer[b.buffer_size + offset]), size * sizeof(typename TConfig::VecPrec), MPI_BYTE, m.manager->neighbors_before_glue[i], m.manager->neighbors_before_glue[i], mpi_comm, &b.requests[neighbors + i]);\n            }\n            else\n            {\n                MPI_Irecv(&(b.host_buffer[0]), size * sizeof(typename TConfig::VecPrec), MPI_BYTE, m.manager->neighbors_before_glue[i], m.manager->neighbors_before_glue[i], mpi_comm, &b.requests[neighbors + i]);\n            }\n\n            offset += size;\n            int required_size = m.manager->halo_offsets_before_glue[0] * bsize * num_cols + offset;\n\n            if (required_size > b.size())\n            {\n                // happen because we have 2 ring\n                // required_size correspond to \"n\" in the FULL view of the unconsolidated matrix.\n                // In exchange halo this is a fatal error since it should never happen.\n                b.resize(required_size);\n            }\n        }\n\n        MPI_Waitall(2 * neighbors, &b.requests[0], /*&b.statuses[0]*/ MPI_STATUSES_IGNORE); //I only wait to receive data, I can start working before all my buffers were sent\n        b.dirtybit = 0;\n        b.in_transfer = IDLE;\n\n        // copy on host ring by ring\n        if (num_rings == 1)\n        {\n            if (num_cols == 1)\n            {\n                if (offset != 0)\n                {\n                    cudaMemcpy(b.raw() + m.manager->halo_offsets_before_glue[0]*bsize, &(b.explicit_host_buffer[b.buffer_size]), offset * sizeof(typename TConfig::VecPrec), cudaMemcpyHostToDevice);\n                }\n            }\n            else\n            {\n                int lda = b.get_lda();\n                VecPrec *rank_start = &(b.explicit_host_buffer[b.buffer_size]);\n\n                for (int i = 0; i < neighbors; ++i)\n                {\n                    int halo_size = m.manager->halo_offsets_before_glue[i + 1] - m.manager->halo_offsets_before_glue[i];\n\n                    for (int s = 0; s < num_cols; ++s)\n                    {\n                        VecPrec *halo_start = b.raw() + lda * s + m.manager->halo_offsets_before_glue[i];\n                        VecPrec *received_halo = rank_start + s * halo_size;\n                        cudaMemcpy(halo_start, received_halo, halo_size * sizeof(VecPrec), cudaMemcpyHostToDevice);\n                    }\n\n                    rank_start += num_cols * halo_size;\n                }\n            }\n        }\n        else\n        {\n            if (num_cols == 1)\n            {\n                offset = 0;\n\n                // Copy into b, one neighbor at a time, one ring at a time\n                for (int i = 0 ; i < neighbors ; i++)\n                {\n                    for (int j = 0; j < num_rings; j++)\n                    {\n                        int size = m.manager->halo_offsets_before_glue[j * neighbors + i + 1] * bsize - m.manager->halo_offsets_before_glue[j * neighbors + i] * bsize;\n\n                        if (size != 0)\n                        {\n                            cudaMemcpy(b.raw() + m.manager->halo_offsets_before_glue[j * neighbors + i]*bsize, &(b.explicit_host_buffer[b.buffer_size + offset]), size * sizeof(typename TConfig::VecPrec), cudaMemcpyHostToDevice);\n                        }\n\n                        offset += size;\n                    }\n                }\n            }\n            else\n            {\n                FatalError(\"num_rings != 1 && num_cols != 1 not supported\\n\", AMGX_ERR_NOT_IMPLEMENTED);\n            }\n        }\n\n#else\n        FatalError(\"MPI Comms module requires compiling with MPI\", AMGX_ERR_NOT_IMPLEMENTED);\n#endif\n    }\n}\n#endif\n// if 0\n#endif\n//MPI\n} // namespace amgx", "meta": {"hexsha": "7d8a47a67148565ba7cf880f8583f2498477c78f", "size": 48759, "ext": "h", "lang": "C", "max_stars_repo_path": "base/include/distributed/glue.h", "max_stars_repo_name": "fizmat/AMGX", "max_stars_repo_head_hexsha": "11af85608ea0f4720e03cbcc920521745f9e40e5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 278.0, "max_stars_repo_stars_event_min_datetime": "2017-10-13T18:28:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T03:54:04.000Z", "max_issues_repo_path": "3rd_party/AMGX/base/include/distributed/glue.h", "max_issues_repo_name": "neams-th-coe/nekRS", "max_issues_repo_head_hexsha": "5d2c8ab3d14b3fb16db35682336a1f96000698bb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 143.0, "max_issues_repo_issues_event_min_datetime": "2017-10-18T10:30:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T21:13:16.000Z", "max_forks_repo_path": "3rd_party/AMGX/base/include/distributed/glue.h", "max_forks_repo_name": "neams-th-coe/nekRS", "max_forks_repo_head_hexsha": "5d2c8ab3d14b3fb16db35682336a1f96000698bb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 112.0, "max_forks_repo_forks_event_min_datetime": "2017-10-16T11:00:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T21:46:46.000Z", "avg_line_length": 39.6737184703, "max_line_length": 241, "alphanum_fraction": 0.6238848213, "num_tokens": 12150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.17553808224967946, "lm_q2_score": 0.02333076808694849, "lm_q1q2_score": 0.00409543828739496}}
{"text": "#pragma once\n\n#include <gsl/span>\n#include <array>\n#include \"halley/core/api/audio_api.h\"\n\nnamespace Halley\n{\n\tclass AudioSource {\n\tpublic:\n\t\tvirtual ~AudioSource() {}\n\n\t\tvirtual uint8_t getNumberOfChannels() const = 0;\n\t\tvirtual size_t getSamplesLeft() const = 0;\n\t\tvirtual bool isReady() const { return true; }\n\t\tvirtual bool getAudioData(size_t numSamples, AudioMultiChannelSamples dst) = 0;\n\t};\n}\n", "meta": {"hexsha": "cc09a0588dcdf29104ebe2acde8d3b0574599edb", "size": 401, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engine/audio/include/halley/audio/audio_source.h", "max_stars_repo_name": "amrezzd/halley", "max_stars_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/engine/audio/include/halley/audio/audio_source.h", "max_issues_repo_name": "amrezzd/halley", "max_issues_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engine/audio/include/halley/audio/audio_source.h", "max_forks_repo_name": "amrezzd/halley", "max_forks_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1052631579, "max_line_length": 81, "alphanum_fraction": 0.7306733167, "num_tokens": 103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.16238002045272698, "lm_q2_score": 0.025178842843561346, "lm_q1q2_score": 0.0040885410159134895}}
{"text": "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\n#pragma once\n#include <iosfwd>\n#include <vector>\n#include <algorithm>\n#include <string>\n#include <cstring>\n#include <gsl/gsl>\n#include \"onnxruntime_config.h\"\n\n#ifndef DISABLE_ABSEIL\n// Need to include abseil inlined_vector.h header directly here\n// as hash tables cause CUDA 10.2 compilers to fail. inlined_vector.h is fine.\n#ifdef _MSC_VER\n#pragma warning(push)\n// C4127: conditional expression is constant\n#pragma warning(disable : 4127)\n// C4324: structure was padded due to alignment specifier\n// Usage of alignas causes some internal padding in places.\n#pragma warning(disable : 4324)\n#endif\n\n#include <absl/container/inlined_vector.h>\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n#endif  // DISABLE_ABSEIL\n\nnamespace onnxruntime {\n#ifdef __GNUC__\n#pragma GCC diagnostic push\n#ifdef HAS_NULL_DEREFERENCE\n#pragma GCC diagnostic ignored \"-Wnull-dereference\"\n#endif\n#endif\n\nconstexpr size_t kTensorShapeSmallBufferElementsSize = 5;\n\n#ifndef DISABLE_ABSEIL\n// Use this type to build a shape and then create TensorShape.\nusing TensorShapeVector = absl::InlinedVector<int64_t, kTensorShapeSmallBufferElementsSize>;\n#else\nclass TensorShapeVector : public std::vector<int64_t> {\n  using Base = std::vector<int64_t>;\n\n public:\n   using Base::Base;\n};\n\n#endif  // DISABLE_ABSEIL\n\ninline TensorShapeVector ToShapeVector(const gsl::span<const int64_t>& span) {\n  TensorShapeVector out;\n  out.reserve(span.size());\n  out.assign(span.begin(), span.end());\n  return out;\n}\n\ninline gsl::span<const int64_t> ToConstSpan(const TensorShapeVector& vec) {\n  return gsl::make_span(vec);\n}\n\nclass TensorShape {\n  // We use negative numbers for unknown symbolic dimension. Each negative\n  // number represents a unique symbolic dimension.\n public:\n  TensorShape() = default;\n\n  TensorShape(const TensorShape& other) : TensorShape(other.GetDims()) {}\n  TensorShape& operator=(const TensorShape& other);\n  TensorShape& operator=(const gsl::span<const int64_t>& dims) {\n    *this = TensorShape(dims);\n    return *this;\n  }\n\n  TensorShape(TensorShape&& other) noexcept { operator=(std::move(other)); }\n  TensorShape& operator=(TensorShape&& other) noexcept;\n\n  TensorShape(gsl::span<const int64_t> dims);\n  TensorShape(const TensorShapeVector& dims) : TensorShape(gsl::make_span(dims)) {}\n  TensorShape(std::initializer_list<int64_t> dims) : TensorShape(gsl::make_span(dims.begin(), dims.end())) {}\n  TensorShape(const int64_t* dimension_sizes, size_t dimension_count) : TensorShape(gsl::span<const int64_t>(dimension_sizes, dimension_count)) {}\n  TensorShape(const std::vector<int64_t>& dims, size_t start, size_t end) : TensorShape(gsl::span<const int64_t>(&dims[start], end - start)) {}\n\n  // Create a TensorShape that points to an existing buffer internally. As no copy is made, 'data' must remain valid for the life of the TensorShape\n  static const TensorShape FromExistingBuffer(const std::vector<int64_t>& data) {\n    return TensorShape(External{}, gsl::span<int64_t>(const_cast<int64_t*>(data.data()), data.size()));\n  }\n\n  /**\n     Return the dimension specified by <idx>.\n  */\n  int64_t operator[](size_t idx) const { return values_[idx]; }\n  int64_t& operator[](size_t idx) { return values_[idx]; }\n\n  bool operator==(const TensorShape& other) const noexcept { return GetDims() == other.GetDims(); }\n  bool operator!=(const TensorShape& other) const noexcept { return !(*this == other); }\n\n  size_t NumDimensions() const noexcept {\n    return values_.size();\n  }\n\n  /**\n     Copy dims into an array with given size\n  */\n  void CopyDims(int64_t* dims, size_t num_dims) const {\n    memcpy(dims, values_.data(), sizeof(int64_t) * std::min(num_dims, NumDimensions()));\n  }\n\n  /**\n     Copy dims from a specific start dim into an array with given size\n     `start_dim` is expected to be in the inclusive range [0, NumDimensions() - 1]\n     and this function does no checks to ensure that\n  */\n  void CopyDims(int64_t* dims, size_t start_dim, size_t num_dims) const {\n    memcpy(dims, values_.data() + start_dim, sizeof(int64_t) * std::min(num_dims, NumDimensions() - start_dim));\n  }\n\n  /**\n     Return underlying vector representation.\n  */\n  gsl::span<const int64_t> GetDims() const { return values_; }\n\n  TensorShapeVector AsShapeVector() const {\n    return ToShapeVector(values_);\n  }\n\n  /**\n   * Return the total number of elements. Returns 1 for an empty (rank 0) TensorShape.\n   *\n   * May return -1\n   */\n  int64_t Size() const;\n\n  /**\n     Return the total number of elements up to the specified dimension.\n     If the dimension interval is empty (dimension == 0), return 1.\n     @param dimension Return size up to this dimension. Value must be between 0 and this->NumDimensions(), inclusive.\n  */\n  int64_t SizeToDimension(size_t dimension) const;\n\n  /**\n     Return the total number of elements from the specified dimension to the end of the tensor shape.\n     If the dimension interval is empty (dimension == this->NumDimensions()), return 1.\n     @param dimension Return size from this dimension to the end. Value must be between 0 and this->NumDimensions(),\n                      inclusive.\n  */\n  int64_t SizeFromDimension(size_t dimension) const;\n\n  /**\n     Return a new TensorShape of the dimensions from dimstart to dimend.\n  */\n  TensorShape Slice(size_t dimstart, size_t dimend) const;\n\n  /**\n     Return a new TensorShape of the dimensions from dimstart to end.\n  */\n  TensorShape Slice(size_t dimstart) const { return Slice(dimstart, values_.size()); }\n\n  /**\n     output dimensions nicely formatted\n  */\n  std::string ToString() const;\n\n  /**\n     Calculate size between start and end.\n     Assumes start and end are between 0 and this->NumDimensions(), inclusive, and that\n     start < end.\n  */\n  int64_t SizeHelper(size_t start, size_t end) const;\n\n  /**\n     empty shape or 1D shape (1) is regarded as scalar tensor\n  */\n  bool IsScalar() const {\n    size_t len = values_.size();\n    return len == 0 || (len == 1 && values_[0] == 1);\n  }\n\n private:\n  struct External {};\n  TensorShape(External, gsl::span<int64_t> buffer) : values_{buffer} {}\n\n  void Allocate(size_t size);\n\n  gsl::span<int64_t> values_;\n  int64_t small_buffer_[kTensorShapeSmallBufferElementsSize];\n  std::unique_ptr<int64_t[]> allocated_buffer_;\n\n  friend struct ProviderHostImpl;  // So that the shared provider interface can access Allocate\n};\n#ifdef __GNUC__\n#pragma GCC diagnostic pop\n#endif\n// operator<< to nicely output to a stream\nstd::ostream& operator<<(std::ostream& out, const TensorShape& shape);\n\n}  // namespace onnxruntime\n", "meta": {"hexsha": "36b8110e3e0283a883b97c4992b872493af16af7", "size": 6617, "ext": "h", "lang": "C", "max_stars_repo_path": "include/onnxruntime/core/framework/tensor_shape.h", "max_stars_repo_name": "mszhanyi/onnxruntime", "max_stars_repo_head_hexsha": "6f85d3e5c81c919022ac4a77e5a051da8518b15d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 669.0, "max_stars_repo_stars_event_min_datetime": "2018-12-03T22:00:31.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-06T19:42:49.000Z", "max_issues_repo_path": "include/onnxruntime/core/framework/tensor_shape.h", "max_issues_repo_name": "mszhanyi/onnxruntime", "max_issues_repo_head_hexsha": "6f85d3e5c81c919022ac4a77e5a051da8518b15d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 440.0, "max_issues_repo_issues_event_min_datetime": "2018-12-03T21:09:56.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-06T20:47:23.000Z", "max_forks_repo_path": "include/onnxruntime/core/framework/tensor_shape.h", "max_forks_repo_name": "mszhanyi/onnxruntime", "max_forks_repo_head_hexsha": "6f85d3e5c81c919022ac4a77e5a051da8518b15d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 140.0, "max_forks_repo_forks_event_min_datetime": "2018-12-03T21:15:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-06T18:02:36.000Z", "avg_line_length": 32.7574257426, "max_line_length": 148, "alphanum_fraction": 0.7193592262, "num_tokens": 1624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1919327864472368, "lm_q2_score": 0.021287349697888144, "lm_q1q2_score": 0.004085740343592416}}
{"text": "\n#pragma once\n\n#include <src/common/Span.h>\n#include <gsl/gsl>\n\n#include <type_traits>\n\nnamespace miner {\n\n    //simple replacement for std::vector<char> in situations where huge\n    //allocations happen, since the standard doesn't define how\n    //much more memory std::vector allocates on reserve or resize.\n\n    //basically an owning gsl::span\n    template<class T = uint8_t>\n    class DynamicBuffer {\n\n        gsl::owner<T*> owner = nullptr;\n        span<T> buffer;\n\n    public:\n\n        DynamicBuffer() = default;\n        // only use alignment if a stronger power of two alignment than the natural alignment of T is needed\n        DynamicBuffer(size_t size, size_t alignment = alignof(T))\n            : owner(reinterpret_cast<T*>(::operator new(size * sizeof(T) + alignment - 1)))\n            , buffer(reinterpret_cast<T*>((uintptr_t(owner) + alignment - 1) & ~uintptr_t(alignment - 1))\n                , ptrdiff_t(size)) {\n            if (!std::is_trivially_constructible<T>::value) {\n                new(buffer.data()) T[size];\n            }\n        }\n\n        ~DynamicBuffer() {\n            if (owner) { //if not moved-from\n                if (!std::is_trivially_destructible<T>::value) {\n                    for (auto &element : buffer) {\n                        element.~T();\n                    }\n                }\n                ::operator delete(owner);\n            }\n        }\n\n        DynamicBuffer(DynamicBuffer &&o) noexcept\n            : owner(o.owner)\n            , buffer(o.buffer) {\n            o.owner = nullptr; //remove ownership\n        }\n\n        DynamicBuffer &operator=(DynamicBuffer &&o) noexcept {\n            owner = o.owner;\n            buffer = o.buffer;\n            o.owner = nullptr; //remove ownership\n            return *this;\n        }\n\n        //copy\n        DynamicBuffer(const DynamicBuffer &) = delete;\n        DynamicBuffer &operator=(const DynamicBuffer &) = delete;\n\n        T *data() {\n            return buffer.data();\n        }\n\n        uint8_t *bytes() {\n            return reinterpret_cast<uint8_t*>(buffer.data());\n        }\n\n        const T *data() const {\n            return buffer.data();\n        }\n\n        const uint8_t *bytes() const {\n            return reinterpret_cast<const uint8_t*>(buffer.data());\n        }\n\n        size_t size_bytes() const {\n            return static_cast<size_t>(buffer.size_bytes());\n        }\n\n        size_t size() const {\n            return static_cast<size_t>(buffer.size());\n        }\n\n        span<const T> getSpan() const {\n            return buffer;\n        }\n\n        span<const uint8_t> getByteSpan() const {\n            return {bytes(), static_cast<ptrdiff_t>(size_bytes())};\n        }\n\n        operator bool() const {\n            return owner != nullptr;\n        }\n\n    };\n\n}\n", "meta": {"hexsha": "d37aff855f57403abfd667bb800dbf6055a6e5a3", "size": 2774, "ext": "h", "lang": "C", "max_stars_repo_path": "src/util/DynamicBuffer.h", "max_stars_repo_name": "oldas1/Riner", "max_stars_repo_head_hexsha": "492804079eb223e6d4ffd5f5f44283162eaf421b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/util/DynamicBuffer.h", "max_issues_repo_name": "oldas1/Riner", "max_issues_repo_head_hexsha": "492804079eb223e6d4ffd5f5f44283162eaf421b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/util/DynamicBuffer.h", "max_forks_repo_name": "oldas1/Riner", "max_forks_repo_head_hexsha": "492804079eb223e6d4ffd5f5f44283162eaf421b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1960784314, "max_line_length": 108, "alphanum_fraction": 0.5320836337, "num_tokens": 588, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11279541224768527, "lm_q2_score": 0.036220052093726696, "lm_q1q2_score": 0.004085455707544539}}
{"text": "//----------------------------------------------------------------------------\r\n//  History:    2018-04-30 Dwayne Robinson - Created\r\n//----------------------------------------------------------------------------\r\n#pragma once\r\n\r\n\r\n#include <iterator>\r\n#include <memory> // For uninitialized_move/copy and std::unique_ptr.\r\n#include <assert.h>\r\n#include <algorithm>\r\n\r\n#if USE_CPP_MODULES\r\n//import std.core;\r\nimport Common.ArrayRef;\r\n#else\r\n#ifdef USE_GSL_SPAN_INSTEAD_OF_ARRAY_REF\r\n#include <gsl/span>\r\n#define array_ref gsl::span\r\n#else\r\n#include \"Common.ArrayRef.h\" // gsl::span may be mostly substituted instead of array_ref, just missing intersects().\r\n#endif\r\n#endif\r\n\r\nMODULE(Common.FastVector);\r\nEXPORT_BEGIN\r\n\r\n\r\n#pragma warning(push)\r\n#pragma warning(disable:4127) // Conditional expression is constant. VS can't tell that certain compound conditionals of template parameters aren't always constant when the tempalate parameter is true.\r\n\r\n#if defined(_ITERATOR_DEBUG_LEVEL) && _ITERATOR_DEBUG_LEVEL > 0\r\n// For std::uninitialized_copy and std::uninitialized_move.\r\n#define FASTVECTOR_MAKE_UNCHECKED stdext::make_unchecked_array_iterator\r\n#else\r\n#define FASTVECTOR_MAKE_UNCHECKED\r\n#endif\r\n\r\n// fast_vector is a dynamic array that can substitute for std::vector, where it:\r\n// (1) avoids heap allocations when the element count fits within the fixed-size capacity.\r\n// (2) avoids unnecessarily initializing elements if ShouldInitializeElements == false.\r\n//     This is useful for large buffers which will just be overwritten soon anyway.\r\n// (3) supports most vector methods except insert/erase/emplace.\r\n//\r\n// Template parameters:\r\n// - DefaultArraySize - passing 0 means it is solely heap allocated. Passing > 0\r\n//   reserves that much element capacity before allocating heap memory.\r\n//\r\n// - ShouldInitializeElements - ensures elements are constructed when resizing, and\r\n//   it must be true for objects with non-trivial constructors, but it can be set\r\n//   false for large buffers to avoid unnecessarily initializing memory which will\r\n//   just be overwritten soon later anyway.\r\n//\r\n// Examples:\r\n//  fast_vector<int, 20> axes        - up to 20 integers before heap allocation.\r\n//  fast_vector<int, 0, false> axes  - always heap allocated but never initialized.\r\n//  fast_vector<int> axes            - basically std::vector.\r\n\r\ntemplate<typename T, size_t DefaultArraySize = 0, bool ShouldInitializeElements = true>\r\nclass fast_vector;\r\n\r\nenum fast_vector_use_memory_buffer_enum\r\n{\r\n    fast_vector_use_memory_buffer // To avoid ambiguous constructor overload resolution.\r\n};\r\n\r\n// The base class is separated out for the customization of passing specific\r\n// memory, and to avoid bloating additional template permutations solely due to\r\n// differing array sizes.\r\ntemplate<typename T, bool ShouldInitializeElements>\r\nclass fast_vector<T, 0, ShouldInitializeElements>\r\n{\r\n    static_assert(ShouldInitializeElements || std::is_trivial<T>::value);\r\n    using self = fast_vector<T, 0, ShouldInitializeElements>;\r\n\r\npublic:\r\n    // Standard container type definitions.\r\n    using value_type = T;\r\n    using pointer = T*;\r\n    using reference = T&;\r\n    using iterator = pointer;\r\n    using const_reference = T const&;\r\n    using const_iterator = T const*;\r\n    using reverse_iterator = std::reverse_iterator<iterator>;\r\n    using const_reverse_iterator = std::reverse_iterator<const_iterator>;\r\n    using size_type = size_t;\r\n    using difference_type = ptrdiff_t;\r\n    using mutable_value_type = typename std::remove_const<T>::type;\r\n    using mutable_iterator = mutable_value_type*;\r\n\r\n    // If true, the data types needs additional alignment like SSE and AVX types.\r\n    constexpr static bool NeedsTypeAlignmentBeyondMaxAlignT = alignof(T) > alignof(std::max_align_t);\r\n    constexpr static size_t MinimumMemoryBlockSize = NeedsTypeAlignmentBeyondMaxAlignT ? sizeof(void*) : 0;\r\n\r\npublic:\r\n    constexpr fast_vector() noexcept\r\n    {\r\n    }\r\n\r\n    fast_vector(size_t initialSize)\r\n    {\r\n        resize(initialSize);\r\n    }\r\n\r\n    fast_vector(array_ref<const T> initialValues)\r\n    {\r\n        assign(initialValues);\r\n    }\r\n\r\n    fast_vector(const fast_vector& otherVector)\r\n    {\r\n        assign(otherVector);\r\n    }\r\n\r\n    fast_vector(fast_vector&& otherVector) // Throws std::bad_alloc if low on memory.\r\n    {\r\n        transfer_from(otherVector);\r\n    }\r\n\r\n    // Construct using explicit fixed size memory buffer.\r\n    // - Used by the derived template specialization which includes a fixed size buffer.\r\n    // - May also be used by the caller to pass an explicit buffer such as a local array,\r\n    //   where the buffer is guaranteed to live for the lifetime of the fast_vector.\r\n    constexpr fast_vector(fast_vector_use_memory_buffer_enum, array_ref<T> initialBackingArray)\r\n    :   data_(initialBackingArray.data()),\r\n        capacity_(initialBackingArray.size())\r\n    {\r\n    }\r\n\r\n    fast_vector(fast_vector_use_memory_buffer_enum, array_ref<T> initialBackingArray, array_ref<const T> initialValues)\r\n    :   data_(initialBackingArray.data()),\r\n        capacity_(initialBackingArray.size())\r\n    {\r\n        assign(initialValues);\r\n    }\r\n\r\n    fast_vector(fast_vector_use_memory_buffer_enum, array_ref<T> initialBackingArray, size_t initialSize)\r\n    :   data_(initialBackingArray.data()),\r\n        capacity_(initialBackingArray.size())\r\n    {\r\n        resize(initialSize);\r\n    }\r\n\r\n    fast_vector(fast_vector_use_memory_buffer_enum, array_ref<T> initialBackingArray, pointer p, size_t elementCount)\r\n    :   data_(initialBackingArray.data()),\r\n        capacity_(initialBackingArray.size())\r\n    {\r\n        assign({p, elementCount});\r\n    }\r\n\r\n    template <typename IteratorType>\r\n    fast_vector(fast_vector_use_memory_buffer_enum, array_ref<T> initialBackingArray, IteratorType begin, IteratorType end)\r\n    :   data_(initialBackingArray.data()),\r\n        capacity_(initialBackingArray.size())\r\n    {\r\n        assign(begin, end);\r\n    }\r\n \r\n    ~fast_vector() noexcept(std::is_nothrow_destructible<T>::value)\r\n    {\r\n        free();\r\n    }\r\n\r\n    // Clear the vector and free all memory. Calling clear() then shrink_to_fit()\r\n    // is a less efficient way to accomplish it too.\r\n    void free()\r\n    {\r\n        clear(); // Destruct objects and zero the size.\r\n\r\n        if (dataIsAllocatedMemory_)\r\n        {\r\n            FreeMemoryBlock(data_);\r\n            data_ = nullptr;\r\n            capacity_ = 0;\r\n        }\r\n    }\r\n\r\n    // Iterators\r\n    iterator begin() const noexcept                 { return data_; }\r\n    iterator end() const noexcept                   { return data_ + size_; }\r\n    const_iterator cbegin() const noexcept          { return begin(); }\r\n    const_iterator cend() const noexcept            { return end(); };\r\n    reverse_iterator rbegin() const noexcept        { return reverse_iterator(begin()); }\r\n    reverse_iterator rend() const noexcept          { return reverse_iterator(end()); }\r\n    const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(begin()); }\r\n    const_reverse_iterator crend() const noexcept   { return const_reverse_iterator(end()); }\r\n\r\n    // Capacity\r\n    size_type size() const noexcept                 { return size_; }\r\n    size_type size_in_bytes() const noexcept        { return size_ * sizeof(T); }\r\n    size_type capacity() const noexcept             { return capacity_; }\r\n    static constexpr size_type max_size() noexcept  { return SIZE_MAX / sizeof(T); }\r\n    bool empty() const noexcept                     { return size_ == 0; }\r\n\r\n    // Element access\r\n    T& operator[](size_t i) const noexcept          { return data_[i]; }\r\n    T& front() const noexcept                       { return data_[0]; }\r\n    T& back() const noexcept                        { return data_[size_ - 1]; }\r\n    T* data() const noexcept                        { return data_; }\r\n    T* data_end() const noexcept                    { return data_ + size_; }\r\n\r\n    array_ref<T> data_span() noexcept               { return {data_, size_}; }\r\n    array_ref<T const> data_span() const noexcept   { return {data_, size_}; }\r\n\r\n    T& at(size_t i)                                 { return checked_read(i); }\r\n    T& at(size_t i) const                           { return checked_read(i); }\r\n\r\n    T& checked_read(size_t i)\r\n    {\r\n        if (i >= size_)\r\n        {\r\n            throw std::out_of_range(\"fast_vector array index out of range.\");\r\n        }\r\n\r\n        return data_[i];\r\n    }\r\n\r\n    const T& checked_read(size_t i) const\r\n    {\r\n        return const_cast<self&>(*this).checked_read(i);\r\n    }\r\n\r\n    fast_vector& operator=(const fast_vector& otherVector)\r\n    {\r\n        assign(otherVector);\r\n        return *this;\r\n    }\r\n\r\n    fast_vector& operator=(fast_vector&& otherVector) // Throws std::bad_alloc if low on memory.\r\n    {\r\n        transfer_from(otherVector);\r\n        return *this;\r\n    }\r\n\r\n    // Clear any existing elements and copy the new elements from span.\r\n    void assign(array_ref<const T> span)\r\n    {\r\n        #ifndef USE_GSL_SPAN_INSTEAD_OF_ARRAY_REF\r\n        assert(!span.intersects(data_span())); // No self intersection.\r\n        #endif\r\n\r\n        clear();\r\n\r\n        size_t newSize = span.size();\r\n        reserve(newSize);\r\n        std::uninitialized_copy(FASTVECTOR_MAKE_UNCHECKED(span.data()), FASTVECTOR_MAKE_UNCHECKED(span.data()) + newSize, /*out*/ FASTVECTOR_MAKE_UNCHECKED(data_));\r\n        size_ = newSize;\r\n    }\r\n\r\n    // Clear any existing elements and copy the new elements from the iterable range.\r\n    template <typename IteratorType>\r\n    void assign(IteratorType begin, IteratorType end)\r\n    {\r\n        clear();\r\n\r\n        size_t newSize = std::distance(begin, end);\r\n        reserve(newSize);\r\n        std::uninitialized_copy(FASTVECTOR_MAKE_UNCHECKED(begin), FASTVECTOR_MAKE_UNCHECKED(end), /*out*/ FASTVECTOR_MAKE_UNCHECKED(data_));\r\n        size_ = newSize;\r\n    }\r\n\r\n    // Tranfer all elements from the other vector to this one.\r\n    // This only offers the weak exception guarantee, that no leaks will happen\r\n    // if type T throws in the middle of a copy.\r\n    void transfer_from(array_ref<const T> span)\r\n    {\r\n        #ifndef USE_GSL_SPAN_INSTEAD_OF_ARRAY_REF\r\n        assert(!span.intersects(data_span())); // No self intersection.\r\n        #endif\r\n\r\n        clear();\r\n\r\n        size_t newSize = span.size();\r\n        reserve(newSize);\r\n        std::uninitialized_move(FASTVECTOR_MAKE_UNCHECKED(span.data()), FASTVECTOR_MAKE_UNCHECKED(span.data()) + newSize, /*out*/ FASTVECTOR_MAKE_UNCHECKED(data_));\r\n        size_ = newSize;\r\n    }\r\n\r\n    // Tranfer all elements from the other vector to this one.\r\n    // This only offers the weak exception guarantee, that no leaks will happen\r\n    // if type T throws in the middle of a copy.\r\n    void transfer_from(fast_vector<T, 0, ShouldInitializeElements>& other)\r\n    {\r\n        if (&other == this)\r\n        {\r\n            return; // Nop for self assignment.\r\n        }\r\n\r\n        if (other.dataIsAllocatedMemory_)\r\n        {\r\n            free();\r\n\r\n            // Take ownership of new data directly.\r\n            data_ = other.data_;\r\n            other.data_ = nullptr;\r\n            size_ = other.size_;\r\n            other.size_ = 0;\r\n            capacity_ = other.capacity_;\r\n            other.capacity_ = 0;\r\n            dataIsAllocatedMemory_ = other.dataIsAllocatedMemory_;\r\n            other.dataIsAllocatedMemory_ = false;\r\n        }\r\n        else\r\n        {\r\n            // Copying from a fixed size buffer; so it's unsafe to simply\r\n            // steal the pointers as that may leave a dangling pointer\r\n            // when the other fast vector disappears.\r\n            transfer_from(make_array_ref(other));\r\n        }\r\n    }\r\n\r\n    void clear() noexcept(std::is_nothrow_destructible<T>::value)\r\n    {\r\n        if (ShouldInitializeElements)\r\n        {\r\n            std::destroy(data_, data_ + size_);\r\n        }\r\n        size_ = 0;\r\n        // But do not free heap memory.\r\n    }\r\n\r\n    void resize(size_t newSize)\r\n    {\r\n        if (newSize > size_)\r\n        {\r\n            if (newSize > capacity_)\r\n            {\r\n                reserve_at_least(newSize);\r\n            }\r\n\r\n            // Grow data to the new size, calling the default constructor on each new item.\r\n            if (ShouldInitializeElements)\r\n            {\r\n                std::uninitialized_value_construct<iterator>(data_ + size_, data_ + newSize);\r\n            }\r\n\r\n            size_ = newSize;\r\n        }\r\n        else if (newSize < size_)\r\n        {\r\n            // Shrink the data to the new size, calling the destructor on each item. Capacity remains intact.\r\n            if (ShouldInitializeElements)\r\n            {\r\n                std::destroy(data_ + newSize, data_ + size_);\r\n            }\r\n\r\n            size_ = newSize;\r\n        }\r\n    }\r\n\r\n    void reserve(size_t newCapacity)\r\n    {\r\n        if (newCapacity <= capacity_)\r\n        {\r\n            return; // Nothing to do.\r\n        }\r\n    \r\n        if (newCapacity > max_size())\r\n        {\r\n            throw std::bad_alloc(); // Too many elements.\r\n        }\r\n\r\n        size_t newByteSize = newCapacity * sizeof(T);\r\n        ReallocateMemory(newByteSize);\r\n\r\n        capacity_ = newCapacity;\r\n    }\r\n\r\n    void reserve_at_least(size_t newCapacity)\r\n    {\r\n        // Grow with 1.5x factor to avoid frequent reallocations.\r\n        newCapacity = std::max((size_ * 3 / 2), newCapacity);\r\n        reserve(newCapacity);\r\n    }\r\n\r\n    void shrink_to_fit()\r\n    {\r\n        if (!dataIsAllocatedMemory_ || capacity_ == size_)\r\n        {\r\n            return; // Nothing to do.\r\n        }\r\n\r\n        size_t newByteSize = size_ * sizeof(T);\r\n        ReallocateMemory(newByteSize);\r\n\r\n        capacity_ = size_;\r\n    }\r\n\r\n\r\n    void push_back(const T& newValue)\r\n    {\r\n        reserve(size_ + 1);// \r\n        new(static_cast<void*>(data_ + size_)) T(newValue);\r\n        ++size_;\r\n    }\r\n\r\n    void push_back(T&& newValue)\r\n    {\r\n        reserve(size_ + 1);\r\n        new(static_cast<void*>(data_ + size_)) T(std::move(newValue));\r\n        ++size_;\r\n    }\r\n\r\n    void append(array_ref<const T> span)\r\n    {\r\n        insert(size_, span);\r\n    }\r\n\r\n    void insert(size_t insertionOffset, array_ref<const T> span)\r\n    {\r\n        insert(insertionOffset, span.begin(), span.end());\r\n    }\r\n\r\n    void insert(size_t insertionOffset, const_iterator begin, const_iterator end)\r\n    {\r\n        assert(insertionOffset <= size_);\r\n\r\n        // Grow array size.\r\n        size_t newSize = std::distance(begin, end) + size_;\r\n        if (newSize < size_)\r\n        {\r\n            throw std::bad_alloc();\r\n        }\r\n        reserve_at_least(newSize);\r\n\r\n        // Add empty elements to the end.\r\n        size_t oldSize = size_;\r\n        if (ShouldInitializeElements)\r\n        {\r\n            std::uninitialized_value_construct<iterator>(data_ + size_, data_ + newSize);\r\n        }\r\n        size_ = newSize;\r\n\r\n        // Shift elements to the end to make more room.\r\n        std::move_backward(data_ + insertionOffset, data_ + oldSize, data_ + newSize);\r\n\r\n        std::copy(begin, end, /*out*/ data_ + insertionOffset);\r\n    }\r\n\r\n    void insert(const_iterator position, array_ref<const T> span)\r\n    {\r\n        insert(position - begin(), span.begin(), span.end());\r\n    }\r\n\r\n    void erase(const_iterator begin, const_iterator end)\r\n    {\r\n        assert(end >= begin);\r\n        assert(begin >= data_);\r\n        assert(end <= data_ + size_);\r\n\r\n        // Shift elements to front.\r\n        size_t oldSize = size_;\r\n        std::copy(iterator(end), data_ + size_, iterator(begin));\r\n        size_ -= std::distance(begin, end);\r\n\r\n        // Destroy elements at the end.\r\n        if (ShouldInitializeElements)\r\n        {\r\n            std::destroy(data_ + size_, data_ + oldSize);\r\n        }\r\n    }\r\n\r\n    void erase(const_iterator position)\r\n    {\r\n        erase(position, position + 1);\r\n    }\r\n\r\n    // Returns underlying malloc()'d memory block.\r\n    // - May be transferred to another fast_vector via attach_memory.\r\n    // - Caller must free() the memory if not transferred.\r\n    // - This is more safely used when T is a POD type, as the caller would also\r\n    //   need to appropriately call any destructors if complex objects.\r\n    // - If the vector is using fixed size memory (no allocations have happened),\r\n    //   the returned span is empty and points to null.\r\n    // - If the vector is using allocated memory, the memory block will be not\r\n    //   empty and non-null, and the vector is then empty.\r\n    // - No object destructors are called.\r\n    // - If NeedsTypeAlignmentBeyondMaxAlignT is true, the data array might start\r\n    //   after the memory block for alignment.\r\n    //\r\n    // fast_vector<int> vector(20);\r\n    // ...\r\n    // auto memory = vector.detach_memory();\r\n    // std::unique_ptr<char, decltype(&std::free)> p(memory.data(), &std::free);\r\n    // ...\r\n    // otherVector.attach_memory(memory);\r\n    // p.release(); // unique_ptr does not own it anymore.\r\n    //\r\n    array_ref<uint8_t> detach_memory() noexcept\r\n    {\r\n        array_ref<uint8_t> data;\r\n\r\n        // Only heap allocated memory can be returned, not the fixed size buffer.\r\n        if (dataIsAllocatedMemory_)\r\n        {\r\n            // Return the raw memory block, from the actual beginning of memory to the true end.\r\n            // The data might start beyond the memory block for alignment purposes.\r\n            uint8_t* bytes = reinterpret_cast<uint8_t*>(data_);\r\n            size_t byteCount = size_ * sizeof(T);\r\n            data = {reinterpret_cast<uint8_t*>(GetMemoryBlock(data_)), bytes + byteCount};\r\n\r\n            data_ = nullptr;\r\n            size_ = 0;\r\n            capacity_ = 0;\r\n        }\r\n\r\n        return data;\r\n    }\r\n\r\n    // Take ownership of the memory, which came from malloc or another fast_vector\r\n    // via detach_memory.\r\n    // - If ShouldInitializeElements == true, then the memory is presumed to contain\r\n    //   valid objects, which will be destructed when the fast_vector dies.\r\n    // - Because the memory is raw, it's possible to reuse a different data type.\r\n    // - The memory must be aligned to alignof(std::max_align_t).\r\n    // - If NeedsTypeAlignmentBeyondMaxAlignT is true, the memory must be at least\r\n    //   sizeof(void*) bytes.\r\n    //\r\n    void attach_memory(array_ref<uint8_t> memory) noexcept(std::is_nothrow_destructible<T>::value)\r\n    {\r\n        #ifndef USE_GSL_SPAN_INSTEAD_OF_ARRAY_REF\r\n        assert(!memory.intersects(data_span())); // No self intersection.\r\n        #endif\r\n\r\n        assert((reinterpret_cast<size_t>(memory.data()) & (alignof(std::max_align_t) - 1)) == 0); // malloc/realloc should return aligned pointers up to max_align_t.\r\n        assert(memory.data() == nullptr || memory.size() >= MinimumMemoryBlockSize);\r\n\r\n        free();\r\n\r\n        T* data = AlignMemoryBlock(memory.data());\r\n\r\n        // Take ownership of new data.\r\n        data_ = data;\r\n        uint8_t* dataEnd = memory.data() + memory.size();\r\n        size_ = (dataEnd - reinterpret_cast<uint8_t*>(data_)) / sizeof(T);\r\n        capacity_ = size_;\r\n        dataIsAllocatedMemory_ = true;\r\n    }\r\n\r\nprotected:\r\n    void ReallocateMemory(size_t newByteSize) // Throws std::bad_alloc if low on memory, or if T's move constructor fails.\r\n    {\r\n        assert(newByteSize >= size_ * sizeof(T)); // Shouldn't have been called otherwise, because it's wrong for size_ to be less than actual memory.\r\n\r\n        // Handle alignment needs when the type is beyond what malloc/realloc guarantee.\r\n        // This needed for SSE and AVX types (which need 16 and 32 bytes). Any other standard\r\n        // type should have sufficient alignment by default.\r\n        newByteSize = InflateMemorySizeForAlignment(newByteSize);\r\n\r\n        // Try to reallocate the memory block directly rather allocate a new block and manually\r\n        // copying. The memory manager can sometimes just extend the existing data block in-place\r\n        // if there is space behind the block. Only trivially moveable types comply though, whereas\r\n        // std::string would not comply due to the small string optimization.\r\n        \r\n        if (std::is_trivially_move_constructible<T>::value && dataIsAllocatedMemory_)\r\n        {\r\n            // Try to just reallocate the existing memory block.\r\n            \r\n            void* memory = realloc(GetMemoryBlock(data_), newByteSize);\r\n            if (memory == nullptr && newByteSize > 0)\r\n            {\r\n                throw std::bad_alloc();\r\n            }\r\n            data_ = AlignMemoryBlock(/*modified*/ memory);\r\n        }\r\n        else\r\n        {\r\n            // Allocate a new memory buffer if one isn't allocated yet,\r\n            // or if the data type is complex enough that it's not trivially\r\n            // moveable (e.g. std::string, which contains pointers that point\r\n            // into the class address itself for the small string optimization).\r\n\r\n            void* memory = std::malloc(newByteSize);\r\n            std::unique_ptr<void, decltype(std::free)*> newDataHolder(memory, &std::free);\r\n\r\n            // Copy an any existing elements from the fixed size buffer.\r\n            T* newData = AlignMemoryBlock(memory);\r\n            std::uninitialized_move(FASTVECTOR_MAKE_UNCHECKED(data_), FASTVECTOR_MAKE_UNCHECKED(data_) + size_, /*out*/ FASTVECTOR_MAKE_UNCHECKED(newData));\r\n\r\n            // Release the existing block, and assign the new one.\r\n            if (dataIsAllocatedMemory_)\r\n            {\r\n                FreeMemoryBlock(data_);\r\n            }\r\n            newDataHolder.release();\r\n            data_ = newData;\r\n            dataIsAllocatedMemory_ = true;\r\n\r\n            // Caller updates capacity_ and size_. This simply reallocates the memory block.\r\n        }\r\n    }\r\n\r\n    // No object destruction, just a direct free.\r\n    static void FreeMemoryBlock(T* data)\r\n    {\r\n        std::free(GetMemoryBlock(data));\r\n    }\r\n\r\n    // Get the actual memory block associated with the data.\r\n    static void* GetMemoryBlock(T* data)\r\n    {\r\n        mutable_value_type* mutableData = const_cast<mutable_value_type*>(data);\r\n\r\n        if (NeedsTypeAlignmentBeyondMaxAlignT && data != nullptr)\r\n        {\r\n            // Read the pointer to the actual block which is set immediately before the data.\r\n            // [ptr to memory block][data ...]\r\n            return reinterpret_cast<void**>(mutableData)[-1];\r\n        }\r\n        else\r\n        {\r\n            return mutableData;\r\n        }\r\n    }\r\n\r\n    // Return aligned data for the given type, storing the raw memory block from malloc.\r\n    // Write the memory block associated with the data, and return the data.\r\n    // The caller has already ensure enough space exists in the block for alignment.\r\n    static T* AlignMemoryBlock(void* memory)\r\n    {\r\n        if (NeedsTypeAlignmentBeyondMaxAlignT && memory != nullptr)\r\n        {\r\n            // Return a pointer to the aligned data, which starts after the pointer to the original\r\n            // memory.\r\n            //\r\n            // [ptr to memory block][data ...]\r\n\r\n            // Return  the pointer to the actual block which is set immediately before the data.\r\n            // [ptr to memory block][data ...]\r\n            constexpr size_t alignmentMask = alignof(T) - 1;\r\n            static_assert((alignof(T) & alignmentMask) == 0, \"Alignment must be a power of 2.\");\r\n            static_assert(NeedsTypeAlignmentBeyondMaxAlignT == false || alignof(T) >= alignof(void*), \"Alignment must be at least the size of a pointer for NeedsTypeAlignmentBeyondMaxAlignT to be true.\");\r\n\r\n            // Align memory. Note calling std::align is awkward given it expects sizes, which are\r\n            // already correct earlier and do not need to be passed to this function.\r\n            size_t memoryAddress = reinterpret_cast<size_t>(memory);\r\n            memoryAddress = (memoryAddress + sizeof(void*) + alignmentMask) & ~alignmentMask;\r\n            mutable_value_type* data = reinterpret_cast<mutable_value_type*>(memoryAddress);\r\n\r\n            // Store the pointer to the original memory block.\r\n            reinterpret_cast<void**>(data)[-1] = memory;\r\n            return data;\r\n        }\r\n        else\r\n        {\r\n            assert((reinterpret_cast<size_t>(memory) & (alignof(std::max_align_t) - 1)) == 0); // malloc/realloc should return aligned pointers up to max_align_t.\r\n            return reinterpret_cast<T*>(memory);\r\n        }\r\n    }\r\n\r\n    static size_t InflateMemorySizeForAlignment(size_t newByteSize)\r\n    {\r\n        if (NeedsTypeAlignmentBeyondMaxAlignT && newByteSize != 0)\r\n        {\r\n            // Need to increase the allocation size to include enough for full type alignment\r\n            // and the size of a single pointer preceding the data.\r\n            size_t alignedByteSize = newByteSize + alignof(T) - alignof(std::max_align_t) + MinimumMemoryBlockSize;\r\n            if (alignedByteSize < newByteSize)\r\n            {\r\n                throw std::bad_alloc(); // Too much memory requested and overflowed.\r\n            }\r\n            newByteSize = alignedByteSize;\r\n        }\r\n        // else malloc/realloc default alignment will suffice.\r\n\r\n        return newByteSize;\r\n    }\r\n\r\nprotected:\r\n    T* data_ = nullptr;     // May point to fixed size array or allocated memory, depending on dataIsAllocatedMemory_.\r\n    size_t size_ = 0;       // Count in elements.\r\n    size_t capacity_ = 0;   // Count in elements.\r\n    bool dataIsAllocatedMemory_ = false;\r\n};\r\n\r\n\r\n// Derived specialization which includes a fixed size buffer.\r\ntemplate <typename T, size_t DefaultArraySize, bool ShouldInitializeElements>\r\nclass fast_vector : public fast_vector<T, 0, ShouldInitializeElements>\r\n{\r\npublic:\r\n    using BaseClass = fast_vector<T, 0, ShouldInitializeElements>;\r\n\r\n    constexpr fast_vector() noexcept\r\n    :   BaseClass(fast_vector_use_memory_buffer, GetFixedSizeArrayData())\r\n    {\r\n    }\r\n\r\n    fast_vector(array_ref<const T> initialValues)\r\n    :   BaseClass(fast_vector_use_memory_buffer, GetFixedSizeArrayData(), initialValues)\r\n    {\r\n    }\r\n\r\n    fast_vector(std::initializer_list<const T> initialValues)\r\n    :   BaseClass(fast_vector_use_memory_buffer, GetFixedSizeArrayData(), make_array_ref(initialValues))\r\n    {\r\n    }\r\n\r\n    fast_vector(const fast_vector& otherVector)\r\n    :   BaseClass(otherVector)\r\n    {\r\n    }\r\n\r\n    fast_vector(typename BaseClass::pointer p, size_t elementCount)\r\n    :   BaseClass(fast_vector_use_memory_buffer, GetFixedSizeArrayData(), p, elementCount)\r\n    {\r\n    }\r\n\r\n    template <typename IteratorType>\r\n    fast_vector(IteratorType begin, IteratorType end)\r\n    :   BaseClass(fast_vector_use_memory_buffer, GetFixedSizeArrayData(), begin, end)\r\n    {\r\n    }\r\n\r\n    fast_vector(size_t initialSize)\r\n    :   BaseClass(fast_vector_use_memory_buffer, GetFixedSizeArrayData(), initialSize)\r\n    {\r\n    }\r\n\r\n    // Move constructor. Will not throw unless type T throws, since the\r\n    // target is guaranteed to have enough space.\r\n    fast_vector(fast_vector&& otherVector) noexcept(std::is_nothrow_move_assignable<T>::value)\r\n    :   BaseClass(std::move(otherVector))\r\n    {\r\n    }\r\n\r\n    // Explicit overload for base class, to avoid the compiler from undesireably\r\n    // choosing the constructor overload which takes a span of initialValues or\r\n    // the copy constructor.\r\n    fast_vector(BaseClass&& otherVector) // Throws std::bad_alloc if low on memory.\r\n    :   BaseClass(std::move(otherVector))\r\n    {\r\n    }\r\n\r\n    // Move assignment. Will not throw unless type T throws, since the\r\n    // target vector is guaranteed to have a large enough fixed-size array.\r\n    fast_vector& operator=(fast_vector&& otherVector) noexcept(std::is_nothrow_move_assignable<T>::value && std::is_nothrow_destructible<T>::value)\r\n    {\r\n        BaseClass::transfer_from(otherVector);\r\n        return *this;\r\n    }\r\n\r\n    fast_vector& operator=(BaseClass&& otherVector) // Throws std::bad_alloc if low on memory.\r\n    {\r\n        BaseClass::transfer_from(otherVector);\r\n        return *this;\r\n    }\r\n\r\n    fast_vector& operator=(const fast_vector& otherVector)\r\n    {\r\n        BaseClass::assign(otherVector);\r\n        return *this;\r\n    }\r\n\r\n    fast_vector& operator=(const BaseClass& otherVector)\r\n    {\r\n        BaseClass::assign(otherVector);\r\n        return *this;\r\n    }\r\n\r\nprivate:\r\n    constexpr array_ref<T> GetFixedSizeArrayData() noexcept\r\n    {\r\n        return array_ref<T>(reinterpret_cast<T*>(std::data(fixedSizedArrayData_)), std::size(fixedSizedArrayData_));\r\n    }\r\n\r\nprivate:\r\n    // Uninitialized data to be used by the base class.\r\n    // It's declared as raw bytes rather than an std::array<T> to avoid any initialization cost\r\n    // up front, only initializing the fields which actually exist when resized later.\r\n    //\r\n    // Note Visual Studio 2017 15.8 requires you to declare _ENABLE_EXTENDED_ALIGNED_STORAGE\r\n    // if your type T is > max_align_t.\r\n    //\r\n    std::aligned_storage_t<sizeof(T), alignof(T)> fixedSizedArrayData_[DefaultArraySize];\r\n};\r\n\r\n#ifdef USE_GSL_SPAN_INSTEAD_OF_ARRAY_REF\r\n#undef array_ref\r\n#endif\r\n\r\n#undef FASTVECTOR_MAKE_UNCHECKED\r\n\r\n#pragma warning(pop)\r\n\r\nEXPORT_END\r\n", "meta": {"hexsha": "375fb87421f4193cfcb2a8d0b1614ca96d3ba1d3", "size": 29217, "ext": "h", "lang": "C", "max_stars_repo_path": "Common.FastVector.h", "max_stars_repo_name": "moyogo/TextLayoutSampler", "max_stars_repo_head_hexsha": "b4acfafde44c4f06a9ed74308a3268c4093817ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Common.FastVector.h", "max_issues_repo_name": "moyogo/TextLayoutSampler", "max_issues_repo_head_hexsha": "b4acfafde44c4f06a9ed74308a3268c4093817ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Common.FastVector.h", "max_forks_repo_name": "moyogo/TextLayoutSampler", "max_forks_repo_head_hexsha": "b4acfafde44c4f06a9ed74308a3268c4093817ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1717557252, "max_line_length": 205, "alphanum_fraction": 0.6247732485, "num_tokens": 6257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14804719803168948, "lm_q2_score": 0.027585279129008742, "lm_q1q2_score": 0.004083923281971788}}
{"text": "/* matrix/gsl_matrix_uchar.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_MATRIX_UCHAR_H__\n#define __GSL_MATRIX_UCHAR_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_vector_uchar.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size1;\n  size_t size2;\n  size_t tda;\n  unsigned char * data;\n  gsl_block_uchar * block;\n  int owner;\n} gsl_matrix_uchar;\n\ntypedef struct\n{\n  gsl_matrix_uchar matrix;\n} _gsl_matrix_uchar_view;\n\ntypedef _gsl_matrix_uchar_view gsl_matrix_uchar_view;\n\ntypedef struct\n{\n  gsl_matrix_uchar matrix;\n} _gsl_matrix_uchar_const_view;\n\ntypedef const _gsl_matrix_uchar_const_view gsl_matrix_uchar_const_view;\n\n/* Allocation */\n\nGSL_EXPORT\ngsl_matrix_uchar *\ngsl_matrix_uchar_alloc (const size_t n1, const size_t n2);\n\nGSL_EXPORT\ngsl_matrix_uchar *\ngsl_matrix_uchar_calloc (const size_t n1, const size_t n2);\n\nGSL_EXPORT\ngsl_matrix_uchar *\ngsl_matrix_uchar_alloc_from_block (gsl_block_uchar * b,\n                                   const size_t offset,\n                                   const size_t n1,\n                                   const size_t n2,\n                                   const size_t d2);\n\nGSL_EXPORT\ngsl_matrix_uchar *\ngsl_matrix_uchar_alloc_from_matrix (gsl_matrix_uchar * m,\n                                    const size_t k1,\n                                    const size_t k2,\n                                    const size_t n1,\n                                    const size_t n2);\n\nGSL_EXPORT\ngsl_vector_uchar *\ngsl_vector_uchar_alloc_row_from_matrix (gsl_matrix_uchar * m,\n                                        const size_t i);\n\nGSL_EXPORT\ngsl_vector_uchar *\ngsl_vector_uchar_alloc_col_from_matrix (gsl_matrix_uchar * m,\n                                        const size_t j);\n\nGSL_EXPORT void gsl_matrix_uchar_free (gsl_matrix_uchar * m);\n\n/* Views */\n\nGSL_EXPORT\n_gsl_matrix_uchar_view\ngsl_matrix_uchar_submatrix (gsl_matrix_uchar * m,\n                            const size_t i, const size_t j,\n                            const size_t n1, const size_t n2);\n\nGSL_EXPORT\n_gsl_vector_uchar_view\ngsl_matrix_uchar_row (gsl_matrix_uchar * m, const size_t i);\n\nGSL_EXPORT\n_gsl_vector_uchar_view\ngsl_matrix_uchar_column (gsl_matrix_uchar * m, const size_t j);\n\nGSL_EXPORT\n_gsl_vector_uchar_view\ngsl_matrix_uchar_diagonal (gsl_matrix_uchar * m);\n\nGSL_EXPORT\n_gsl_vector_uchar_view\ngsl_matrix_uchar_subdiagonal (gsl_matrix_uchar * m, const size_t k);\n\nGSL_EXPORT\n_gsl_vector_uchar_view\ngsl_matrix_uchar_superdiagonal (gsl_matrix_uchar * m, const size_t k);\n\nGSL_EXPORT\n_gsl_matrix_uchar_view\ngsl_matrix_uchar_view_array (unsigned char * base,\n                             const size_t n1,\n                             const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_uchar_view\ngsl_matrix_uchar_view_array_with_tda (unsigned char * base,\n                                      const size_t n1,\n                                      const size_t n2,\n                                      const size_t tda);\n\n\nGSL_EXPORT\n_gsl_matrix_uchar_view\ngsl_matrix_uchar_view_vector (gsl_vector_uchar * v,\n                              const size_t n1,\n                              const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_uchar_view\ngsl_matrix_uchar_view_vector_with_tda (gsl_vector_uchar * v,\n                                       const size_t n1,\n                                       const size_t n2,\n                                       const size_t tda);\n\n\nGSL_EXPORT\n_gsl_matrix_uchar_const_view\ngsl_matrix_uchar_const_submatrix (const gsl_matrix_uchar * m,\n                                  const size_t i, const size_t j,\n                                  const size_t n1, const size_t n2);\n\nGSL_EXPORT\n_gsl_vector_uchar_const_view\ngsl_matrix_uchar_const_row (const gsl_matrix_uchar * m,\n                            const size_t i);\n\nGSL_EXPORT\n_gsl_vector_uchar_const_view\ngsl_matrix_uchar_const_column (const gsl_matrix_uchar * m,\n                               const size_t j);\n\nGSL_EXPORT\n_gsl_vector_uchar_const_view\ngsl_matrix_uchar_const_diagonal (const gsl_matrix_uchar * m);\n\nGSL_EXPORT\n_gsl_vector_uchar_const_view\ngsl_matrix_uchar_const_subdiagonal (const gsl_matrix_uchar * m,\n                                    const size_t k);\n\nGSL_EXPORT\n_gsl_vector_uchar_const_view\ngsl_matrix_uchar_const_superdiagonal (const gsl_matrix_uchar * m,\n                                      const size_t k);\n\nGSL_EXPORT\n_gsl_matrix_uchar_const_view\ngsl_matrix_uchar_const_view_array (const unsigned char * base,\n                                   const size_t n1,\n                                   const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_uchar_const_view\ngsl_matrix_uchar_const_view_array_with_tda (const unsigned char * base,\n                                            const size_t n1,\n                                            const size_t n2,\n                                            const size_t tda);\n\nGSL_EXPORT\n_gsl_matrix_uchar_const_view\ngsl_matrix_uchar_const_view_vector (const gsl_vector_uchar * v,\n                                    const size_t n1,\n                                    const size_t n2);\n\nGSL_EXPORT\n_gsl_matrix_uchar_const_view\ngsl_matrix_uchar_const_view_vector_with_tda (const gsl_vector_uchar * v,\n                                             const size_t n1,\n                                             const size_t n2,\n                                             const size_t tda);\n\n/* Operations */\n\nGSL_EXPORT unsigned char   gsl_matrix_uchar_get(const gsl_matrix_uchar * m, const size_t i, const size_t j);\nGSL_EXPORT void    gsl_matrix_uchar_set(gsl_matrix_uchar * m, const size_t i, const size_t j, const unsigned char x);\n\nGSL_EXPORT unsigned char * gsl_matrix_uchar_ptr(gsl_matrix_uchar * m, const size_t i, const size_t j);\nGSL_EXPORT const unsigned char * gsl_matrix_uchar_const_ptr(const gsl_matrix_uchar * m, const size_t i, const size_t j);\n\nGSL_EXPORT void gsl_matrix_uchar_set_zero (gsl_matrix_uchar * m);\nGSL_EXPORT void gsl_matrix_uchar_set_identity (gsl_matrix_uchar * m);\nGSL_EXPORT void gsl_matrix_uchar_set_all (gsl_matrix_uchar * m, unsigned char x);\n\nGSL_EXPORT int gsl_matrix_uchar_fread (FILE * stream, gsl_matrix_uchar * m) ;\nGSL_EXPORT int gsl_matrix_uchar_fwrite (FILE * stream, const gsl_matrix_uchar * m) ;\nGSL_EXPORT int gsl_matrix_uchar_fscanf (FILE * stream, gsl_matrix_uchar * m);\nGSL_EXPORT int gsl_matrix_uchar_fprintf (FILE * stream, const gsl_matrix_uchar * m, const char * format);\n\nGSL_EXPORT int gsl_matrix_uchar_memcpy(gsl_matrix_uchar * dest, const gsl_matrix_uchar * src);\nGSL_EXPORT int gsl_matrix_uchar_swap(gsl_matrix_uchar * m1, gsl_matrix_uchar * m2);\n\nGSL_EXPORT int gsl_matrix_uchar_swap_rows(gsl_matrix_uchar * m, const size_t i, const size_t j);\nGSL_EXPORT int gsl_matrix_uchar_swap_columns(gsl_matrix_uchar * m, const size_t i, const size_t j);\nGSL_EXPORT int gsl_matrix_uchar_swap_rowcol(gsl_matrix_uchar * m, const size_t i, const size_t j);\nGSL_EXPORT int gsl_matrix_uchar_transpose (gsl_matrix_uchar * m);\nGSL_EXPORT int gsl_matrix_uchar_transpose_memcpy (gsl_matrix_uchar * dest, const gsl_matrix_uchar * src);\n\nGSL_EXPORT unsigned char gsl_matrix_uchar_max (const gsl_matrix_uchar * m);\nGSL_EXPORT unsigned char gsl_matrix_uchar_min (const gsl_matrix_uchar * m);\nGSL_EXPORT void gsl_matrix_uchar_minmax (const gsl_matrix_uchar * m, unsigned char * min_out, unsigned char * max_out);\n\nGSL_EXPORT void gsl_matrix_uchar_max_index (const gsl_matrix_uchar * m, size_t * imax, size_t *jmax);\nGSL_EXPORT void gsl_matrix_uchar_min_index (const gsl_matrix_uchar * m, size_t * imin, size_t *jmin);\nGSL_EXPORT void gsl_matrix_uchar_minmax_index (const gsl_matrix_uchar * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);\n\nGSL_EXPORT int gsl_matrix_uchar_isnull (const gsl_matrix_uchar * m);\n\nGSL_EXPORT int gsl_matrix_uchar_add (gsl_matrix_uchar * a, const gsl_matrix_uchar * b);\nGSL_EXPORT int gsl_matrix_uchar_sub (gsl_matrix_uchar * a, const gsl_matrix_uchar * b);\nGSL_EXPORT int gsl_matrix_uchar_mul_elements (gsl_matrix_uchar * a, const gsl_matrix_uchar * b);\nGSL_EXPORT int gsl_matrix_uchar_div_elements (gsl_matrix_uchar * a, const gsl_matrix_uchar * b);\nGSL_EXPORT int gsl_matrix_uchar_scale (gsl_matrix_uchar * a, const double x);\nGSL_EXPORT int gsl_matrix_uchar_add_constant (gsl_matrix_uchar * a, const double x);\nGSL_EXPORT int gsl_matrix_uchar_add_diagonal (gsl_matrix_uchar * a, const double x);\n\n/***********************************************************************/\n/* The functions below are obsolete                                    */\n/***********************************************************************/\nGSL_EXPORT int gsl_matrix_uchar_get_row(gsl_vector_uchar * v, const gsl_matrix_uchar * m, const size_t i);\nGSL_EXPORT int gsl_matrix_uchar_get_col(gsl_vector_uchar * v, const gsl_matrix_uchar * m, const size_t j);\nGSL_EXPORT int gsl_matrix_uchar_set_row(gsl_matrix_uchar * m, const size_t i, const gsl_vector_uchar * v);\nGSL_EXPORT int gsl_matrix_uchar_set_col(gsl_matrix_uchar * m, const size_t j, const gsl_vector_uchar * v);\n\n/* inline functions if you are using GCC */\n\n#ifdef HAVE_INLINE\nextern inline \nunsigned char\ngsl_matrix_uchar_get(const gsl_matrix_uchar * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_VAL(\"first index out of range\", GSL_EINVAL, 0) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_VAL(\"second index out of range\", GSL_EINVAL, 0) ;\n    }\n#endif\n  return m->data[i * m->tda + j] ;\n} \n\nextern inline \nvoid\ngsl_matrix_uchar_set(gsl_matrix_uchar * m, const size_t i, const size_t j, const unsigned char x)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_VOID(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_VOID(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  m->data[i * m->tda + j] = x ;\n}\n\nextern inline \nunsigned char *\ngsl_matrix_uchar_ptr(gsl_matrix_uchar * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  return (unsigned char *) (m->data + (i * m->tda + j)) ;\n} \n\nextern inline \nconst unsigned char *\ngsl_matrix_uchar_const_ptr(const gsl_matrix_uchar * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  return (const unsigned char *) (m->data + (i * m->tda + j)) ;\n} \n\n#endif\n\n__END_DECLS\n\n#endif /* __GSL_MATRIX_UCHAR_H__ */\n", "meta": {"hexsha": "6a0809c33f8f26399d0f10fb1b2792da1ad2552a", "size": 11755, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/gsl/include/gsl/gsl_matrix_uchar.h", "max_stars_repo_name": "dynaryu/vaws", "max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/gsl/include/gsl/gsl_matrix_uchar.h", "max_issues_repo_name": "dynaryu/vaws", "max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/gsl/include/gsl/gsl_matrix_uchar.h", "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2711370262, "max_line_length": 135, "alphanum_fraction": 0.6819225861, "num_tokens": 2990, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2200070997458932, "lm_q2_score": 0.018546565766601044, "lm_q1q2_score": 0.0040803761445563635}}
{"text": "#pragma once\n\n#define UPCA_ARCH_H\n\n#include <memory>\n#include <vector>\n\n#include <stdint.h>\n\n#include <gsl/gsl>\n\nnamespace upca {\nnamespace arch {\n\nnamespace detail {\ntemplate <typename Reason> struct null_resolver {\n  struct null_type {\n    friend std::ostream &operator<<(std::ostream &os, const null_type &) {\n      return os;\n    }\n  };\n  static null_type resolve(const std::string &) {\n    throw std::runtime_error(Reason::reason);\n  }\n};\n\ntemplate <typename TIMESTAMP, typename REASON> struct basic_pmu {\n  using resolver_type = upca::arch::detail::null_resolver<REASON>;\n  template <typename T> basic_pmu(const T &) {}\n\n  uint64_t timestamp_begin() { return TIMESTAMP::timestamp(); }\n  uint64_t timestamp_end() { return TIMESTAMP::timestamp(); }\n\n  gsl::span<uint64_t>::index_type start(gsl::span<uint64_t>) { return 0; }\n  gsl::span<uint64_t>::index_type stop(gsl::span<uint64_t>) { return 0; }\n};\n\n} // namespace detail\n\ntemplate <typename ARCH> class arch_common_base final {\nprivate:\n  ptrdiff_t offset_ = 0;\n  const ptrdiff_t slice_;\n  ARCH arch_;\n\n  template <typename T> friend class resolver;\n\npublic:\n  using resolver_type = typename ARCH::resolver_type;\n\n  template <typename C>\n  arch_common_base(const C &pmcs, const unsigned external_pmcs = 0)\n      : slice_(gsl::narrow<ptrdiff_t>(pmcs.size() + external_pmcs)),\n        arch_(pmcs) {}\n\n  gsl::span<uint64_t>::index_type start(gsl::span<uint64_t> output) {\n    const auto count = arch_.start(output.subspan(1, slice_ - 1));\n    output[0] = arch_.timestamp_begin();\n    return count + 1;\n  }\n\n  gsl::span<uint64_t>::index_type stop(gsl::span<uint64_t> output) {\n    output[0] = arch_.timestamp_end() - output[0];\n    const auto count = arch_.stop(output.subspan(1, slice_ - 1));\n    return count + 1;\n  }\n};\n\n} // namespace arch\n} // namespace upca\n\n#ifdef __aarch64__\n\n#  include \"aarch64.h\"\n\nusing pmu = upca::arch::arch_common_base<upca::arch::aarch64::pmu>;\n\n#elif defined(__ARM_ARCH_7A__)\n\n#  include \"aarch32.h\"\n\nusing pmu = upca::arch::arch_common_base<upca::arch::aarch32::pmu>;\n\n#elif defined(__sparc)\n\n#  include \"sparc.h\"\n\nusing pmu = upca::arch::arch_common_base<upca::arch::sparc::pmu>;\n\n#elif defined(__x86_64__)\n#  include \"x86_64.h\"\n\n/* MCK can be either:\n * - mck_rawmsr for raw MSR access via rdmsr/wrmsr mcK syscalls\n * - mck_mckmsr for PMU programmed via mcK pmc_* syscalls\n *\n * LINUX can be any of:\n * - linux_perf for using perf\n * - linux_jevents for using jevents\n * - linux_rawmsr for raw MSR access using /dev/cpu/N/msr\n */\n\n#ifdef JEVENTS_FOUND\nusing pmu = upca::arch::arch_common_base<upca::arch::x86_64::x86_linux_mckernel<\n    upca::arch::x86_64::mck_mckmsr, upca::arch::x86_64::linux_rawmsr>>;\n#else\nusing pmu = upca::arch::arch_common_base<upca::arch::x86_64::x86_64_pmu>;\n#endif\n\n#elif defined(__bgq__)\n\n#  include \"bgq.h\"\n\nusing pmu = upca::arch::arch_common_base<upca::arch::bgq::pmu>;\n\n#elif defined(__ppc__) || defined(_ARCH_PPC) || defined(__PPC__)\n\n#  include \"ppc.h\"\n\nusing pmu = upca::arch::arch_common_base<upca::arch::ppc::pmu>;\n\n#else\n\n#error \"Unkown/Unsupported architecture\"\n\n#endif\n\n\n", "meta": {"hexsha": "130ec6179623232a81ca629a80c1c3d3a552537c", "size": 3101, "ext": "h", "lang": "C", "max_stars_repo_path": "include/upca/arch/arch.h", "max_stars_repo_name": "hannesweisbach/ucpa", "max_stars_repo_head_hexsha": "e4062fd98d83f4cc57ee04f554540c09c1ca8ccd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-08-31T13:51:26.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-31T13:51:26.000Z", "max_issues_repo_path": "include/upca/arch/arch.h", "max_issues_repo_name": "hannesweisbach/ucpa", "max_issues_repo_head_hexsha": "e4062fd98d83f4cc57ee04f554540c09c1ca8ccd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/upca/arch/arch.h", "max_forks_repo_name": "hannesweisbach/ucpa", "max_forks_repo_head_hexsha": "e4062fd98d83f4cc57ee04f554540c09c1ca8ccd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0387596899, "max_line_length": 80, "alphanum_fraction": 0.7023540793, "num_tokens": 926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.13296422989056966, "lm_q2_score": 0.03067579927371769, "lm_q1q2_score": 0.004078784026707569}}
{"text": "/* block/gsl_block_long_double.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_BLOCK_LONG_DOUBLE_H__\n#define __GSL_BLOCK_LONG_DOUBLE_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_types.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\nstruct gsl_block_long_double_struct\n{\n  size_t size;\n  long double *data;\n};\n\ntypedef struct gsl_block_long_double_struct gsl_block_long_double;\n\nGSL_EXPORT gsl_block_long_double *gsl_block_long_double_alloc (const size_t n);\nGSL_EXPORT gsl_block_long_double *gsl_block_long_double_calloc (const size_t n);\nGSL_EXPORT void gsl_block_long_double_free (gsl_block_long_double * b);\n\nGSL_EXPORT int gsl_block_long_double_fread (FILE * stream, gsl_block_long_double * b);\nGSL_EXPORT int gsl_block_long_double_fwrite (FILE * stream, const gsl_block_long_double * b);\nGSL_EXPORT int gsl_block_long_double_fscanf (FILE * stream, gsl_block_long_double * b);\nGSL_EXPORT int gsl_block_long_double_fprintf (FILE * stream, const gsl_block_long_double * b, const char *format);\n\nGSL_EXPORT int gsl_block_long_double_raw_fread (FILE * stream, long double * b, const size_t n, const size_t stride);\nGSL_EXPORT int gsl_block_long_double_raw_fwrite (FILE * stream, const long double * b, const size_t n, const size_t stride);\nGSL_EXPORT int gsl_block_long_double_raw_fscanf (FILE * stream, long double * b, const size_t n, const size_t stride);\nGSL_EXPORT int gsl_block_long_double_raw_fprintf (FILE * stream, const long double * b, const size_t n, const size_t stride, const char *format);\n\nGSL_EXPORT size_t gsl_block_long_double_size (const gsl_block_long_double * b);\nGSL_EXPORT long double * gsl_block_long_double_data (const gsl_block_long_double * b);\n\n__END_DECLS\n\n#endif /* __GSL_BLOCK_LONG_DOUBLE_H__ */\n", "meta": {"hexsha": "ab4478bfc15b08b46982cff334904a042421e2c1", "size": 2699, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/gsl/include/gsl/gsl_block_long_double.h", "max_stars_repo_name": "dynaryu/vaws", "max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/gsl/include/gsl/gsl_block_long_double.h", "max_issues_repo_name": "dynaryu/vaws", "max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/gsl/include/gsl/gsl_block_long_double.h", "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.2835820896, "max_line_length": 145, "alphanum_fraction": 0.7906632086, "num_tokens": 676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14223188773801163, "lm_q2_score": 0.028436031706890366, "lm_q1q2_score": 0.00404451046944897}}
{"text": "//\n// Created by bessermt on 6/3/18.\n//\n\n#ifndef SRSGRADE_TIMESTAMP_H\n#define SRSGRADE_TIMESTAMP_H\n\n#include <iostream>\n#include <iomanip>\n#include <chrono>\n#include <gsl.h>\n\nclass Timestamp\n{\nprivate:\n    std::chrono::system_clock::time_point time_point_{};\n\n    void set(const std::string date_string, const std::string time_string);\n\n    friend std::istream& operator>>(std::istream& is, Timestamp& timestamp)\n    {\n        std::string date_string;\n\n\t\tis >> date_string;\n\t\tEnsures(!date_string.empty());\n\n\t\tchar time_cstr[256]{};\n\t\tconstexpr auto max_time_len{ std::extent<decltype(time_cstr)>::value };\n\t\tis >> std::ws;\n\t\tis.getline(time_cstr, max_time_len, ',');\n\t\tconst auto time_len{ strlen(time_cstr) };\n\t\tEnsures(time_len > 0 && time_len < max_time_len);\n    \t\n\t\tconst auto time_string{ std::string(time_cstr) };\n\n        timestamp.set(date_string, time_string);\n\n        return is;\n    }\n\n\tfriend bool operator<(const Timestamp lhs, const Timestamp rhs)\n    {\n\t\treturn lhs.time_point_ < rhs.time_point_;\n    }\n\npublic:\n    auto is_good() const\n    {\n\t\tconst auto is_past{ time_point_ < std::chrono::system_clock::now() };\n\n        return is_past; // TODO: Any better tests?\n    }\n};\n\n\n#endif // SRSGRADE_TIMESTAMP_H\n\n", "meta": {"hexsha": "c641da73ff49ed12b265bcabe0cc2afee4891a7f", "size": 1227, "ext": "h", "lang": "C", "max_stars_repo_path": "SRSGrade/timestamp.h", "max_stars_repo_name": "labermt/SRSGrade", "max_stars_repo_head_hexsha": "2e5f274dbaba950a9ec406b77544be2ca210a8ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SRSGrade/timestamp.h", "max_issues_repo_name": "labermt/SRSGrade", "max_issues_repo_head_hexsha": "2e5f274dbaba950a9ec406b77544be2ca210a8ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SRSGrade/timestamp.h", "max_forks_repo_name": "labermt/SRSGrade", "max_forks_repo_head_hexsha": "2e5f274dbaba950a9ec406b77544be2ca210a8ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1551724138, "max_line_length": 75, "alphanum_fraction": 0.6764466178, "num_tokens": 317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15817433687509233, "lm_q2_score": 0.025565213180845064, "lm_q1q2_score": 0.004043760641950538}}
{"text": "/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */\n/*\n *     Copyright 2017 Couchbase, Inc\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n */\n\n#pragma once\n\n#include \"monotonic.h\"\n\n#include <memcached/dockey.h>\n#include <memcached/types.h>\n#include <nlohmann/json_fwd.hpp>\n#include <platform/sized_buffer.h>\n#include <gsl/gsl>\n\n#include <unordered_map>\n#include <vector>\n\nnamespace Collections {\n\n// The reserved name of the system owned, default collection.\nconst char* const _DefaultCollectionIdentifier = \"_default\";\nstatic cb::const_char_buffer DefaultCollectionIdentifier(\n        _DefaultCollectionIdentifier);\n\nconst char* const _DefaultScopeIdentifier = \"_default\";\nstatic cb::const_char_buffer DefaultScopeIdentifier(_DefaultScopeIdentifier);\n\n// SystemEvent keys or parts which will be made into keys\nconst char* const SystemSeparator = \":\"; // Note this never changes\nconst char* const CollectionEventPrefixWithSeparator = \"_collection:\";\nconst char* const ScopeEventPrefixWithSeparator = \"_scope:\";\n\n// Couchstore private file name for manifest data\nconst char CouchstoreManifest[] = \"_local/collections_manifest\";\n\n// Length of the string excluding the zero terminator (i.e. strlen)\nconst size_t CouchstoreManifestLen = sizeof(CouchstoreManifest) - 1;\n\nusing ManifestUid = WeaklyMonotonic<uint64_t>;\n\n// Map used in summary stats\nusing Summary = std::unordered_map<CollectionID, uint64_t>;\n\nstruct ManifestUidNetworkOrder {\n    ManifestUidNetworkOrder(ManifestUid uid) : uid(htonll(uid)) {\n    }\n    ManifestUid to_host() const {\n        return ntohll(uid);\n    }\n    ManifestUid::value_type uid;\n};\nstatic_assert(sizeof(ManifestUidNetworkOrder) == 8,\n              \"ManifestUidNetworkOrder must have fixed size of 8 bytes as \"\n              \"written to disk.\");\n\n/**\n * Return a ManifestUid from a C-string.\n * A valid ManifestUid is a C-string where each character satisfies\n * std::isxdigit and can be converted to a ManifestUid by std::strtoull.\n *\n * @param uid C-string uid\n * @param len a length for validation purposes\n * @throws std::invalid_argument if uid is invalid\n */\nManifestUid makeUid(const char* uid, size_t len = 16);\n\n/**\n * Return a ManifestUid from a std::string\n * A valid ManifestUid is a std::string where each character satisfies\n * std::isxdigit and can be converted to a ManifestUid by std::strtoull.\n *\n * @param uid std::string\n * @throws std::invalid_argument if uid is invalid\n */\nstatic inline ManifestUid makeUid(const std::string& uid) {\n    return makeUid(uid.c_str());\n}\n\n/**\n * Return a CollectionID from a C-string.\n * A valid CollectionID is a C-string where each character satisfies\n * std::isxdigit and can be converted to a CollectionID by std::strtoul.\n *\n * @param uid C-string uid\n * @throws std::invalid_argument if uid is invalid\n */\nstatic inline CollectionID makeCollectionID(const char* uid) {\n    // CollectionID is 8 characters max and smaller than a ManifestUid\n    return gsl::narrow_cast<CollectionID>(makeUid(uid, 8));\n}\n\n/**\n * Return a CollectionID from a std::string\n * A valid CollectionID is a std::string where each character satisfies\n * std::isxdigit and can be converted to a CollectionID by std::strtoul\n *\n * @param uid std::string\n * @throws std::invalid_argument if uid is invalid\n */\nstatic inline CollectionID makeCollectionID(const std::string& uid) {\n    return makeCollectionID(uid.c_str());\n}\n\n/**\n * Return a ScopeID from a C-string.\n * A valid CollectionID is a std::string where each character satisfies\n * std::isxdigit and can be converted to a CollectionID by std::strtoul\n * @param uid C-string uid\n * @return std::invalid_argument if uid is invalid\n */\nstatic inline ScopeID makeScopeID(const char* uid) {\n    // ScopeId is 8 characters max and smaller than a ManifestUid\n    return gsl::narrow_cast<ScopeID>(makeUid(uid, 8));\n}\n\n/**\n * Return a ScopeID from a std::string\n * A valid ScopeID is a std::string where each character satisfies\n * std::isxdigit and can be converted to a CollectionID by std::strtoul\n * @param uid std::string\n * @return std::invalid_argument if uid is invalid\n */\nstatic inline ScopeID makeScopeID(const std::string& uid) {\n    return makeScopeID(uid.c_str());\n}\n\n/**\n * The metadata of a single collection\n *\n * Default construction yields the default collection\n */\nstruct CollectionMetaData {\n    ScopeID sid{ScopeID::Default}; // The scope that the collection belongs to\n    CollectionID cid{CollectionID::Default}; // The collection's ID\n    std::string name{_DefaultCollectionIdentifier}; // The collection's name\n    cb::ExpiryLimit maxTtl; // The collection's maxTTL\n\n    bool operator==(const CollectionMetaData& other) const {\n        return sid == other.sid && cid == other.cid && name == other.name &&\n               maxTtl == other.maxTtl;\n    }\n};\n\n/**\n * All of the data a system event needs\n */\nstruct CreateEventData {\n    ManifestUid manifestUid; // The Manifest which generated the event\n    CollectionMetaData metaData; // The data of the new collection\n};\n\nstruct DropEventData {\n    ManifestUid manifestUid; // The Manifest which generated the event\n    ScopeID sid; // The scope that the collection belonged to\n    CollectionID cid; // The collection the event belongs to\n};\n\nstruct CreateScopeEventData {\n    ManifestUid manifestUid; // The Manifest which generated the event\n    ScopeID sid; // The scope id\n    std::string name; // The scope name\n};\n\nstruct DropScopeEventData {\n    ManifestUid manifestUid; // The Manifest which generated the event\n    ScopeID sid; // The scope the event belongs to\n};\n\n/**\n * All of the data a DCP create event message will transmit in the value of the\n * message. This is the layout to be used on the wire and is in the correct\n * byte order\n */\nstruct CreateEventDcpData {\n    CreateEventDcpData(const CreateEventData& ev)\n        : manifestUid(ev.manifestUid),\n          sid(ev.metaData.sid),\n          cid(ev.metaData.cid) {\n    }\n    /// The manifest uid stored in network byte order ready for sending\n    ManifestUidNetworkOrder manifestUid;\n    /// The scope id stored in network byte order ready for sending\n    ScopeIDNetworkOrder sid;\n    /// The collection id stored in network byte order ready for sending\n    CollectionIDNetworkOrder cid;\n    // The size is sizeof(manifestUid) + sizeof(cid) + sizeof(sid)\n    // (msvc won't allow that expression)\n    constexpr static size_t size{16};\n};\n\n/**\n * All of the data a DCP create event message will transmit in the value of a\n * DCP system event message (when the collection is created with a TTL). This is\n * the layout to be used on the wire and is in the correct byte order\n */\nstruct CreateWithMaxTtlEventDcpData {\n    CreateWithMaxTtlEventDcpData(const CreateEventData& ev)\n        : manifestUid(ev.manifestUid),\n          sid(ev.metaData.sid),\n          cid(ev.metaData.cid),\n          maxTtl(htonl(gsl::narrow_cast<uint32_t>(\n                  ev.metaData.maxTtl.get().count()))) {\n    }\n    /// The manifest uid stored in network byte order ready for sending\n    ManifestUidNetworkOrder manifestUid;\n    /// The scope id stored in network byte order ready for sending\n    ScopeIDNetworkOrder sid;\n    /// The collection id stored in network byte order ready for sending\n    CollectionIDNetworkOrder cid;\n    /// The collection's maxTTL value (in network byte order)\n    uint32_t maxTtl;\n    // The size is sizeof(manifestUid) + sizeof(cid) + sizeof(sid) +\n    //             sizeof(maxTTL) (msvc won't allow that expression)\n    constexpr static size_t size{20};\n};\n\n/**\n * All of the data a DCP drop event message will transmit in the value of the\n * message. This is the layout to be used on the wire and is in the correct\n * byte order\n */\nstruct DropEventDcpData {\n    DropEventDcpData(const DropEventData& data)\n        : manifestUid(data.manifestUid), sid(data.sid), cid(data.cid) {\n    }\n\n    /// The manifest uid stored in network byte order ready for sending\n    ManifestUidNetworkOrder manifestUid;\n    /// The scope id stored in network byte order ready for sending\n    ScopeIDNetworkOrder sid;\n    /// The collection id stored in network byte order ready for sending\n    CollectionIDNetworkOrder cid;\n    // The size is sizeof(manifestUid) + sizeof(cid) (msvc won't allow that\n    // expression)\n    constexpr static size_t size{16};\n};\n\n/**\n * All of the data a DCP create scope event message will transmit in the value\n * of the message. This is the layout to be used on the wire and is in the\n * correct byte order\n */\nstruct CreateScopeEventDcpData {\n    CreateScopeEventDcpData(const CreateScopeEventData& data)\n        : manifestUid(data.manifestUid), sid(data.sid) {\n    }\n    /// The manifest uid stored in network byte order ready for sending\n    ManifestUidNetworkOrder manifestUid;\n    /// The scope id stored in network byte order ready for sending\n    ScopeIDNetworkOrder sid;\n    constexpr static size_t size{12};\n};\n\n/**\n * All of the data a DCP drop scope event message will transmit in the value of\n * the message. This is the layout to be used on the wire and is in the correct\n * byte order\n */\nstruct DropScopeEventDcpData {\n    DropScopeEventDcpData(const DropScopeEventData& data)\n        : manifestUid(data.manifestUid), sid(data.sid) {\n    }\n\n    /// The manifest uid stored in network byte order ready for sending\n    ManifestUidNetworkOrder manifestUid;\n    /// The collection id stored in network byte order ready for sending\n    ScopeIDNetworkOrder sid;\n    constexpr static size_t size{12};\n};\n\n/**\n * All unknown_collection errors should be accompanied by a error context\n * value which includes the manifest ID which was what the collection lookup\n * failed against.\n * @return json for use in setErrorJsonExtras\n */\nnlohmann::json getUnknownCollectionErrorContext(uint64_t manifestUid);\n\n/**\n * For creation of collection SystemEvents - The SystemEventFactory\n * glues the CollectionID into the event key (so create of x doesn't\n * collide with create of y). This method yields the 'keyExtra' parameter\n *\n * @param collection The value to turn into a string\n * @return the keyExtra parameter to be passed to SystemEventFactory\n */\nstd::string makeCollectionIdIntoString(CollectionID collection);\n\n/**\n * For creation of scope SystemEvents - The SystemEventFactory\n * glues the ScopeID into the event key (so create of x doesn't\n * collide with create of y). This method yields the 'keyExtra' parameter\n *\n * @param sid The ScopeId to turn into a string\n * @return the keyExtra parameter to be passed to SystemEventFactory\n */\nstd::string makeScopeIdIntoString(ScopeID sid);\n\n/**\n * For creation of collection SystemEvents - The SystemEventFactory\n * glues the CollectionID into the event key (so create of x doesn't\n * collide with create of y). This method basically reverses\n * makeCollectionIdIntoString so we can get a CollectionID from a\n * SystemEvent key\n *\n * @param key DocKey from a SystemEvent\n * @param separator the separator between the SystemEvent prefix and the\n *        CollectionID\n * @return the ID which was in the event\n */\nCollectionID getCollectionIDFromKey(\n        const DocKey& key,\n        const char* separator = Collections::SystemSeparator);\n\n/// Same as getCollectionIDFromKey but for events changing scopes\nScopeID getScopeIDFromKey(const DocKey& key,\n                          const char* separator = Collections::SystemSeparator);\n\n/**\n * Callback function for processing against dropped collections in an ephemeral\n * vb, returns true if the key at seqno should be dropped\n */\nusing IsDroppedEphemeralCb = std::function<bool(const DocKey&, int64_t)>;\n\n} // end namespace Collections\n", "meta": {"hexsha": "cfc39b5183b0b6c86252ae23dce7e6fa7168ce5f", "size": 12177, "ext": "h", "lang": "C", "max_stars_repo_path": "engines/ep/src/collections/collections_types.h", "max_stars_repo_name": "hrajput89/kv_engine", "max_stars_repo_head_hexsha": "33fb1ab2c9787f55555e5f7edea38807b3dbc371", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-13T07:33:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-13T07:33:09.000Z", "max_issues_repo_path": "engines/ep/src/collections/collections_types.h", "max_issues_repo_name": "paolococchi/kv_engine", "max_issues_repo_head_hexsha": "40256dca6bf77fb4bcc18e8ef7d9b8f991bf4e45", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "engines/ep/src/collections/collections_types.h", "max_forks_repo_name": "paolococchi/kv_engine", "max_forks_repo_head_hexsha": "40256dca6bf77fb4bcc18e8ef7d9b8f991bf4e45", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-01-15T16:52:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-15T16:52:37.000Z", "avg_line_length": 35.9203539823, "max_line_length": 80, "alphanum_fraction": 0.7263693849, "num_tokens": 2820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21469141911224193, "lm_q2_score": 0.018833128892290028, "lm_q1q2_score": 0.004043311168209511}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n//\n// Copyright (c) 2015 Microsoft Corporation. All rights reserved.\n//\n// This code is licensed under the MIT License (MIT).\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef GSL_GSL_H\n#define GSL_GSL_H\n\n#include <gsl/gsl_algorithm> // copy\n#include <gsl/gsl_assert>    // Ensures/Expects\n#include <gsl/gsl_byte>      // byte\n#include <gsl/gsl_util>      // finally()/narrow()/narrow_cast()...\n#include <gsl/multi_span>    // multi_span, strided_span...\n#include <gsl/pointers>      // owner, not_null\n#include <gsl/span>          // span\n#include <gsl/string_span>   // zstring, string_span, zstring_builder...\n\n#endif // GSL_GSL_H\n", "meta": {"hexsha": "55862ebdd20bd2c9c849f1b808b0df8ec8a1787a", "size": 1241, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gsl/gsl.h", "max_stars_repo_name": "Redchards/CVRP", "max_stars_repo_head_hexsha": "f372f2fa06cb374ebdac2f6eee7e6fe297d94103", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-09-01T14:40:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-15T05:01:23.000Z", "max_issues_repo_path": "include/gsl/gsl.h", "max_issues_repo_name": "Redchards/CVRP", "max_issues_repo_head_hexsha": "f372f2fa06cb374ebdac2f6eee7e6fe297d94103", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gsl/gsl.h", "max_forks_repo_name": "Redchards/CVRP", "max_forks_repo_head_hexsha": "f372f2fa06cb374ebdac2f6eee7e6fe297d94103", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-02T17:50:23.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-26T08:25:35.000Z", "avg_line_length": 41.3666666667, "max_line_length": 80, "alphanum_fraction": 0.6253021757, "num_tokens": 272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.10818896318842186, "lm_q2_score": 0.037326884934594504, "lm_q1q2_score": 0.004038356980127303}}
{"text": "/*  Copyright 2017 International Business Machines Corporation\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.  */\n\n#pragma once\n\n#include \"kernelpp/types.h\"\n#include <gsl.h>\n\nnamespace mwe\n{\n    using kernelpp::maybe;\n    using kernelpp::status;\n\n    /* Operations  --------------------------------------------------------- */\n\n    maybe<int> add(int a, int b);\n\n    status add(const gsl::span<int> a,\n               const gsl::span<int> b,\n                     gsl::span<int> result\n              );\n}", "meta": {"hexsha": "72274bfdd23be1bc5e0d96a883f872ce447f8c13", "size": 980, "ext": "h", "lang": "C", "max_stars_repo_path": "include/mwe.h", "max_stars_repo_name": "rayglover-ibm/cuda-bindings", "max_stars_repo_head_hexsha": "7d9f2f1f2f15cec7ec7b1d5882dc2a2cbfb646cd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2017-04-18T02:56:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-25T10:01:56.000Z", "max_issues_repo_path": "include/mwe.h", "max_issues_repo_name": "rayglover-ibm/cuda-bindings", "max_issues_repo_head_hexsha": "7d9f2f1f2f15cec7ec7b1d5882dc2a2cbfb646cd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/mwe.h", "max_forks_repo_name": "rayglover-ibm/cuda-bindings", "max_forks_repo_head_hexsha": "7d9f2f1f2f15cec7ec7b1d5882dc2a2cbfb646cd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.696969697, "max_line_length": 79, "alphanum_fraction": 0.6591836735, "num_tokens": 205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16238003666671083, "lm_q2_score": 0.024798160240630397, "lm_q1q2_score": 0.0040267261691405345}}
{"text": "/* matrix/gsl_matrix_uchar.h\r\n * \r\n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\r\n * \r\n * This program is free software; you can redistribute it and/or modify\r\n * it under the terms of the GNU General Public License as published by\r\n * the Free Software Foundation; either version 3 of the License, or (at\r\n * your option) any later version.\r\n * \r\n * This program is distributed in the hope that it will be useful, but\r\n * WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n * General Public License for more details.\r\n * \r\n * You should have received a copy of the GNU General Public License\r\n * along with this program; if not, write to the Free Software\r\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r\n */\r\n\r\n#ifndef __GSL_MATRIX_UCHAR_H__\r\n#define __GSL_MATRIX_UCHAR_H__\r\n\r\n#if !defined( GSL_FUN )\r\n#  if !defined( GSL_DLL )\r\n#    define GSL_FUN extern\r\n#  elif defined( BUILD_GSL_DLL )\r\n#    define GSL_FUN extern __declspec(dllexport)\r\n#  else\r\n#    define GSL_FUN extern __declspec(dllimport)\r\n#  endif\r\n#endif\r\n\r\n#include <stdlib.h>\r\n#include <gsl/gsl_types.h>\r\n#include <gsl/gsl_errno.h>\r\n#include <gsl/gsl_inline.h>\r\n#include <gsl/gsl_check_range.h>\r\n#include <gsl/gsl_vector_uchar.h>\r\n\r\n#undef __BEGIN_DECLS\r\n#undef __END_DECLS\r\n#ifdef __cplusplus\r\n# define __BEGIN_DECLS extern \"C\" {\r\n# define __END_DECLS }\r\n#else\r\n# define __BEGIN_DECLS /* empty */\r\n# define __END_DECLS /* empty */\r\n#endif\r\n\r\n__BEGIN_DECLS\r\n\r\ntypedef struct \r\n{\r\n  size_t size1;\r\n  size_t size2;\r\n  size_t tda;\r\n  unsigned char * data;\r\n  gsl_block_uchar * block;\r\n  int owner;\r\n} gsl_matrix_uchar;\r\n\r\ntypedef struct\r\n{\r\n  gsl_matrix_uchar matrix;\r\n} _gsl_matrix_uchar_view;\r\n\r\ntypedef _gsl_matrix_uchar_view gsl_matrix_uchar_view;\r\n\r\ntypedef struct\r\n{\r\n  gsl_matrix_uchar matrix;\r\n} _gsl_matrix_uchar_const_view;\r\n\r\ntypedef const _gsl_matrix_uchar_const_view gsl_matrix_uchar_const_view;\r\n\r\n/* Allocation */\r\n\r\nGSL_FUN gsl_matrix_uchar * \r\ngsl_matrix_uchar_alloc (const size_t n1, const size_t n2);\r\n\r\nGSL_FUN gsl_matrix_uchar * \r\ngsl_matrix_uchar_calloc (const size_t n1, const size_t n2);\r\n\r\nGSL_FUN gsl_matrix_uchar * \r\ngsl_matrix_uchar_alloc_from_block (gsl_block_uchar * b, \r\n                                   const size_t offset, \r\n                                   const size_t n1, \r\n                                   const size_t n2, \r\n                                   const size_t d2);\r\n\r\nGSL_FUN gsl_matrix_uchar * \r\ngsl_matrix_uchar_alloc_from_matrix (gsl_matrix_uchar * m,\r\n                                    const size_t k1, \r\n                                    const size_t k2,\r\n                                    const size_t n1, \r\n                                    const size_t n2);\r\n\r\nGSL_FUN gsl_vector_uchar * \r\ngsl_vector_uchar_alloc_row_from_matrix (gsl_matrix_uchar * m,\r\n                                        const size_t i);\r\n\r\nGSL_FUN gsl_vector_uchar * \r\ngsl_vector_uchar_alloc_col_from_matrix (gsl_matrix_uchar * m,\r\n                                        const size_t j);\r\n\r\nGSL_FUN void gsl_matrix_uchar_free (gsl_matrix_uchar * m);\r\n\r\n/* Views */\r\n\r\nGSL_FUN _gsl_matrix_uchar_view \r\ngsl_matrix_uchar_submatrix (gsl_matrix_uchar * m, \r\n                            const size_t i, const size_t j, \r\n                            const size_t n1, const size_t n2);\r\n\r\nGSL_FUN _gsl_vector_uchar_view \r\ngsl_matrix_uchar_row (gsl_matrix_uchar * m, const size_t i);\r\n\r\nGSL_FUN _gsl_vector_uchar_view \r\ngsl_matrix_uchar_column (gsl_matrix_uchar * m, const size_t j);\r\n\r\nGSL_FUN _gsl_vector_uchar_view \r\ngsl_matrix_uchar_diagonal (gsl_matrix_uchar * m);\r\n\r\nGSL_FUN _gsl_vector_uchar_view \r\ngsl_matrix_uchar_subdiagonal (gsl_matrix_uchar * m, const size_t k);\r\n\r\nGSL_FUN _gsl_vector_uchar_view \r\ngsl_matrix_uchar_superdiagonal (gsl_matrix_uchar * m, const size_t k);\r\n\r\nGSL_FUN _gsl_vector_uchar_view\r\ngsl_matrix_uchar_subrow (gsl_matrix_uchar * m, const size_t i,\r\n                         const size_t offset, const size_t n);\r\n\r\nGSL_FUN _gsl_vector_uchar_view\r\ngsl_matrix_uchar_subcolumn (gsl_matrix_uchar * m, const size_t j,\r\n                            const size_t offset, const size_t n);\r\n\r\nGSL_FUN _gsl_matrix_uchar_view\r\ngsl_matrix_uchar_view_array (unsigned char * base,\r\n                             const size_t n1, \r\n                             const size_t n2);\r\n\r\nGSL_FUN _gsl_matrix_uchar_view\r\ngsl_matrix_uchar_view_array_with_tda (unsigned char * base, \r\n                                      const size_t n1, \r\n                                      const size_t n2,\r\n                                      const size_t tda);\r\n\r\n\r\nGSL_FUN _gsl_matrix_uchar_view\r\ngsl_matrix_uchar_view_vector (gsl_vector_uchar * v,\r\n                              const size_t n1, \r\n                              const size_t n2);\r\n\r\nGSL_FUN _gsl_matrix_uchar_view\r\ngsl_matrix_uchar_view_vector_with_tda (gsl_vector_uchar * v,\r\n                                       const size_t n1, \r\n                                       const size_t n2,\r\n                                       const size_t tda);\r\n\r\n\r\nGSL_FUN _gsl_matrix_uchar_const_view \r\ngsl_matrix_uchar_const_submatrix (const gsl_matrix_uchar * m, \r\n                                  const size_t i, const size_t j, \r\n                                  const size_t n1, const size_t n2);\r\n\r\nGSL_FUN _gsl_vector_uchar_const_view \r\ngsl_matrix_uchar_const_row (const gsl_matrix_uchar * m, \r\n                            const size_t i);\r\n\r\nGSL_FUN _gsl_vector_uchar_const_view \r\ngsl_matrix_uchar_const_column (const gsl_matrix_uchar * m, \r\n                               const size_t j);\r\n\r\nGSL_FUN _gsl_vector_uchar_const_view\r\ngsl_matrix_uchar_const_diagonal (const gsl_matrix_uchar * m);\r\n\r\nGSL_FUN _gsl_vector_uchar_const_view \r\ngsl_matrix_uchar_const_subdiagonal (const gsl_matrix_uchar * m, \r\n                                    const size_t k);\r\n\r\nGSL_FUN _gsl_vector_uchar_const_view \r\ngsl_matrix_uchar_const_superdiagonal (const gsl_matrix_uchar * m, \r\n                                      const size_t k);\r\n\r\nGSL_FUN _gsl_vector_uchar_const_view\r\ngsl_matrix_uchar_const_subrow (const gsl_matrix_uchar * m, const size_t i,\r\n                               const size_t offset, const size_t n);\r\n\r\nGSL_FUN _gsl_vector_uchar_const_view\r\ngsl_matrix_uchar_const_subcolumn (const gsl_matrix_uchar * m, const size_t j,\r\n                                  const size_t offset, const size_t n);\r\n\r\nGSL_FUN _gsl_matrix_uchar_const_view\r\ngsl_matrix_uchar_const_view_array (const unsigned char * base,\r\n                                   const size_t n1, \r\n                                   const size_t n2);\r\n\r\nGSL_FUN _gsl_matrix_uchar_const_view\r\ngsl_matrix_uchar_const_view_array_with_tda (const unsigned char * base, \r\n                                            const size_t n1, \r\n                                            const size_t n2,\r\n                                            const size_t tda);\r\n\r\nGSL_FUN _gsl_matrix_uchar_const_view\r\ngsl_matrix_uchar_const_view_vector (const gsl_vector_uchar * v,\r\n                                    const size_t n1, \r\n                                    const size_t n2);\r\n\r\nGSL_FUN _gsl_matrix_uchar_const_view\r\ngsl_matrix_uchar_const_view_vector_with_tda (const gsl_vector_uchar * v,\r\n                                             const size_t n1, \r\n                                             const size_t n2,\r\n                                             const size_t tda);\r\n\r\n/* Operations */\r\n\r\nGSL_FUN void gsl_matrix_uchar_set_zero (gsl_matrix_uchar * m);\r\nGSL_FUN void gsl_matrix_uchar_set_identity (gsl_matrix_uchar * m);\r\nGSL_FUN void gsl_matrix_uchar_set_all (gsl_matrix_uchar * m, unsigned char x);\r\n\r\nGSL_FUN int gsl_matrix_uchar_fread (FILE * stream, gsl_matrix_uchar * m) ;\r\nGSL_FUN int gsl_matrix_uchar_fwrite (FILE * stream, const gsl_matrix_uchar * m) ;\r\nGSL_FUN int gsl_matrix_uchar_fscanf (FILE * stream, gsl_matrix_uchar * m);\r\nGSL_FUN int gsl_matrix_uchar_fprintf (FILE * stream, const gsl_matrix_uchar * m, const char * format);\r\n \r\nGSL_FUN int gsl_matrix_uchar_memcpy(gsl_matrix_uchar * dest, const gsl_matrix_uchar * src);\r\nGSL_FUN int gsl_matrix_uchar_swap(gsl_matrix_uchar * m1, gsl_matrix_uchar * m2);\r\n\r\nGSL_FUN int gsl_matrix_uchar_swap_rows(gsl_matrix_uchar * m, const size_t i, const size_t j);\r\nGSL_FUN int gsl_matrix_uchar_swap_columns(gsl_matrix_uchar * m, const size_t i, const size_t j);\r\nGSL_FUN int gsl_matrix_uchar_swap_rowcol(gsl_matrix_uchar * m, const size_t i, const size_t j);\r\nGSL_FUN int gsl_matrix_uchar_transpose (gsl_matrix_uchar * m);\r\nGSL_FUN int gsl_matrix_uchar_transpose_memcpy (gsl_matrix_uchar * dest, const gsl_matrix_uchar * src);\r\n\r\nGSL_FUN unsigned char gsl_matrix_uchar_max (const gsl_matrix_uchar * m);\r\nGSL_FUN unsigned char gsl_matrix_uchar_min (const gsl_matrix_uchar * m);\r\nGSL_FUN void gsl_matrix_uchar_minmax (const gsl_matrix_uchar * m, unsigned char * min_out, unsigned char * max_out);\r\n\r\nGSL_FUN void gsl_matrix_uchar_max_index (const gsl_matrix_uchar * m, size_t * imax, size_t *jmax);\r\nGSL_FUN void gsl_matrix_uchar_min_index (const gsl_matrix_uchar * m, size_t * imin, size_t *jmin);\r\nGSL_FUN void gsl_matrix_uchar_minmax_index (const gsl_matrix_uchar * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);\r\n\r\nGSL_FUN int gsl_matrix_uchar_isnull (const gsl_matrix_uchar * m);\r\nGSL_FUN int gsl_matrix_uchar_ispos (const gsl_matrix_uchar * m);\r\nGSL_FUN int gsl_matrix_uchar_isneg (const gsl_matrix_uchar * m);\r\nGSL_FUN int gsl_matrix_uchar_isnonneg (const gsl_matrix_uchar * m);\r\n\r\nGSL_FUN int gsl_matrix_uchar_add (gsl_matrix_uchar * a, const gsl_matrix_uchar * b);\r\nGSL_FUN int gsl_matrix_uchar_sub (gsl_matrix_uchar * a, const gsl_matrix_uchar * b);\r\nGSL_FUN int gsl_matrix_uchar_mul_elements (gsl_matrix_uchar * a, const gsl_matrix_uchar * b);\r\nGSL_FUN int gsl_matrix_uchar_div_elements (gsl_matrix_uchar * a, const gsl_matrix_uchar * b);\r\nGSL_FUN int gsl_matrix_uchar_scale (gsl_matrix_uchar * a, const double x);\r\nGSL_FUN int gsl_matrix_uchar_add_constant (gsl_matrix_uchar * a, const double x);\r\nGSL_FUN int gsl_matrix_uchar_add_diagonal (gsl_matrix_uchar * a, const double x);\r\n\r\n/***********************************************************************/\r\n/* The functions below are obsolete                                    */\r\n/***********************************************************************/\r\nGSL_FUN int gsl_matrix_uchar_get_row(gsl_vector_uchar * v, const gsl_matrix_uchar * m, const size_t i);\r\nGSL_FUN int gsl_matrix_uchar_get_col(gsl_vector_uchar * v, const gsl_matrix_uchar * m, const size_t j);\r\nGSL_FUN int gsl_matrix_uchar_set_row(gsl_matrix_uchar * m, const size_t i, const gsl_vector_uchar * v);\r\nGSL_FUN int gsl_matrix_uchar_set_col(gsl_matrix_uchar * m, const size_t j, const gsl_vector_uchar * v);\r\n/***********************************************************************/\r\n\r\n/* inline functions if you are using GCC */\r\n\r\nGSL_FUN INLINE_DECL unsigned char   gsl_matrix_uchar_get(const gsl_matrix_uchar * m, const size_t i, const size_t j);\r\nGSL_FUN INLINE_DECL void    gsl_matrix_uchar_set(gsl_matrix_uchar * m, const size_t i, const size_t j, const unsigned char x);\r\nGSL_FUN INLINE_DECL unsigned char * gsl_matrix_uchar_ptr(gsl_matrix_uchar * m, const size_t i, const size_t j);\r\nGSL_FUN INLINE_DECL const unsigned char * gsl_matrix_uchar_const_ptr(const gsl_matrix_uchar * m, const size_t i, const size_t j);\r\n\r\n#ifdef HAVE_INLINE\r\nINLINE_FUN \r\nunsigned char\r\ngsl_matrix_uchar_get(const gsl_matrix_uchar * m, const size_t i, const size_t j)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(1)) \r\n    {\r\n      if (i >= m->size1)\r\n        {\r\n          GSL_ERROR_VAL(\"first index out of range\", GSL_EINVAL, 0) ;\r\n        }\r\n      else if (j >= m->size2)\r\n        {\r\n          GSL_ERROR_VAL(\"second index out of range\", GSL_EINVAL, 0) ;\r\n        }\r\n    }\r\n#endif\r\n  return m->data[i * m->tda + j] ;\r\n} \r\n\r\nINLINE_FUN \r\nvoid\r\ngsl_matrix_uchar_set(gsl_matrix_uchar * m, const size_t i, const size_t j, const unsigned char x)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(1)) \r\n    {\r\n      if (i >= m->size1)\r\n        {\r\n          GSL_ERROR_VOID(\"first index out of range\", GSL_EINVAL) ;\r\n        }\r\n      else if (j >= m->size2)\r\n        {\r\n          GSL_ERROR_VOID(\"second index out of range\", GSL_EINVAL) ;\r\n        }\r\n    }\r\n#endif\r\n  m->data[i * m->tda + j] = x ;\r\n}\r\n\r\nINLINE_FUN \r\nunsigned char *\r\ngsl_matrix_uchar_ptr(gsl_matrix_uchar * m, const size_t i, const size_t j)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(1)) \r\n    {\r\n      if (i >= m->size1)\r\n        {\r\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\r\n        }\r\n      else if (j >= m->size2)\r\n        {\r\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\r\n        }\r\n    }\r\n#endif\r\n  return (unsigned char *) (m->data + (i * m->tda + j)) ;\r\n} \r\n\r\nINLINE_FUN \r\nconst unsigned char *\r\ngsl_matrix_uchar_const_ptr(const gsl_matrix_uchar * m, const size_t i, const size_t j)\r\n{\r\n#if GSL_RANGE_CHECK\r\n  if (GSL_RANGE_COND(1)) \r\n    {\r\n      if (i >= m->size1)\r\n        {\r\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\r\n        }\r\n      else if (j >= m->size2)\r\n        {\r\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\r\n        }\r\n    }\r\n#endif\r\n  return (const unsigned char *) (m->data + (i * m->tda + j)) ;\r\n} \r\n\r\n#endif\r\n\r\n__END_DECLS\r\n\r\n#endif /* __GSL_MATRIX_UCHAR_H__ */\r\n", "meta": {"hexsha": "8183f1b13354d74700382f48f58943a3b603cfee", "size": 13512, "ext": "h", "lang": "C", "max_stars_repo_path": "deps/include/gsl/gsl_matrix_uchar.h", "max_stars_repo_name": "berkus/music-cs", "max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "deps/include/gsl/gsl_matrix_uchar.h", "max_issues_repo_name": "berkus/music-cs", "max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "deps/include/gsl/gsl_matrix_uchar.h", "max_forks_repo_name": "berkus/music-cs", "max_forks_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.6378830084, "max_line_length": 133, "alphanum_fraction": 0.6487566607, "num_tokens": 3395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.13117322036534013, "lm_q2_score": 0.03067580259684012, "lm_q1q2_score": 0.004023843813918982}}
{"text": "#pragma once\n\n#include <gsl.h>\n\n#include <boost/graph/graph_traits.hpp>\n#include <boost/range/adaptor/filtered.hpp>\n\n#include \"VesselForestData.h\"\n\nnamespace crimson\n{\nstruct ActiveVesselsFilter {\n    ActiveVesselsFilter() = default;\n    ActiveVesselsFilter(const VesselForestData* owner)\n        : _owner(owner)\n    {\n    }\n\n    bool operator()(const VesselForestData::VesselPathUIDType& uid) const { return _owner->getVesselUsedInBlending(uid); }\n\nprivate:\n    const VesselForestData* _owner = nullptr;\n};\n\nstruct ActiveBooleanOperationsFilter {\n    ActiveBooleanOperationsFilter() = default;\n    ActiveBooleanOperationsFilter(const VesselForestData* owner)\n        : _owner(owner)\n    {\n    }\n\n    bool operator()(const VesselForestData::BooleanOperationInfo& bop) const\n    {\n        return _owner->getVesselUsedInBlending(bop.vessels.first) && _owner->getVesselUsedInBlending(bop.vessels.second);\n    }\n\nprivate:\n    const VesselForestData* _owner;\n};\n\nstruct OutEdgeIteratorFilter {\n    OutEdgeIteratorFilter() = default;\n    OutEdgeIteratorFilter(const VesselForestData::VesselPathUIDType* uid)\n        : _uid(uid)\n    {\n    }\n\n    bool operator()(const VesselForestData::BooleanOperationInfo& bop) const\n    {\n        return bop.vessels.first == *_uid || bop.vessels.second == *_uid;\n    }\n\nprivate:\n    const VesselForestData::VesselPathUIDType* _uid = nullptr;\n};\n\nstruct ExtractOutEdgeFromBooleanOperationInfo {\n    ExtractOutEdgeFromBooleanOperationInfo() = default;\n    ExtractOutEdgeFromBooleanOperationInfo(const VesselForestData::VesselPathUIDType* sourceVertexUID)\n        : _sourceVertexUID(sourceVertexUID)\n    {\n    }\n\n    VesselForestData::VesselPathUIDPair operator()(const VesselForestData::BooleanOperationInfo& bop) const\n    {\n        if (*_sourceVertexUID == bop.vessels.first) {\n            return bop.vessels;\n        }\n        Expects(*_sourceVertexUID == bop.vessels.second);\n        return std::make_pair(bop.vessels.second, bop.vessels.first);\n    }\n\nprivate:\n    const VesselForestData::VesselPathUIDType* _sourceVertexUID;\n};\n\n} // namespace crimson\n\nnamespace boost\n{\ntemplate <>\nstruct graph_traits<crimson::VesselForestData> {\n    /////////////////////////////////\n    // Graph concept\n    /////////////////////////////////\n    using vertex_descriptor = crimson::VesselForestData::VesselPathUIDType;\n    using edge_descriptor = crimson::VesselForestData::VesselPathUIDPair;\n\n    using directed_category = boost::undirected_tag;\n    using edge_parallel_category = boost::disallow_parallel_edge_tag;\n\n    struct traversal_category : boost::vertex_list_graph_tag, boost::incidence_graph_tag {\n    };\n\n    /////////////////////////////////\n    // Incidence graph concept\n    /////////////////////////////////\n    using out_edge_iterator = boost::transform_iterator<\n        crimson::ExtractOutEdgeFromBooleanOperationInfo,\n        boost::filter_iterator<\n            crimson::OutEdgeIteratorFilter,\n            boost::filter_iterator<crimson::ActiveBooleanOperationsFilter,\n                                   crimson::VesselForestData::BooleanOperationContainerType::const_iterator>>>;\n    using degree_size_type = std::size_t;\n\n    // out_edges(v, g)\n    // source(e, g)\n    // target(e, g)\n    // out_degree(v, g)\n\n    /////////////////////////////////\n    // Vertex list graph concept\n    /////////////////////////////////\n    using vertex_iterator = boost::filter_iterator<crimson::ActiveVesselsFilter,\n                                                   crimson::VesselForestData::VesselPathUIDContainerType::const_iterator>;\n    using vertices_size_type = crimson::VesselForestData::VesselPathUIDContainerType::size_type;\n\n    // vertices(g)\n    // num_vertices(g)\n\n    static vertex_descriptor null_vertex() { return {}; }\n};\n} // namespace boost\n\nnamespace crimson\n{\n\ninline boost::graph_traits<crimson::VesselForestData>::vertex_descriptor\nsource(const boost::graph_traits<crimson::VesselForestData>::edge_descriptor& e, const crimson::VesselForestData& g)\n{\n    return e.first;\n}\n\ninline boost::graph_traits<crimson::VesselForestData>::vertex_descriptor\ntarget(const boost::graph_traits<crimson::VesselForestData>::edge_descriptor& e, const crimson::VesselForestData& g)\n{\n    return e.second;\n}\n\ninline std::pair<boost::graph_traits<crimson::VesselForestData>::out_edge_iterator,\n                 boost::graph_traits<crimson::VesselForestData>::out_edge_iterator>\nout_edges(const boost::graph_traits<crimson::VesselForestData>::vertex_descriptor& v, const crimson::VesselForestData& g)\n{\n    auto filtIter1 = boost::make_filter_iterator(crimson::ActiveBooleanOperationsFilter{&g}, g.getBooleanOperations().begin(),\n                                                 g.getBooleanOperations().end());\n    auto endFiltIter1 = boost::make_filter_iterator(crimson::ActiveBooleanOperationsFilter{&g}, g.getBooleanOperations().end(),\n                                                    g.getBooleanOperations().end());\n\n    auto filtIter2 = boost::make_filter_iterator(crimson::OutEdgeIteratorFilter{&v}, filtIter1, endFiltIter1);\n    auto endFiltIter2 = boost::make_filter_iterator(crimson::OutEdgeIteratorFilter{&v}, endFiltIter1, endFiltIter1);\n\n    return {boost::make_transform_iterator(filtIter2, crimson::ExtractOutEdgeFromBooleanOperationInfo{&v}),\n            boost::make_transform_iterator(endFiltIter2, crimson::ExtractOutEdgeFromBooleanOperationInfo{&v})};\n}\n\ninline boost::graph_traits<crimson::VesselForestData>::degree_size_type\nout_degree(const boost::graph_traits<crimson::VesselForestData>::vertex_descriptor& v, const crimson::VesselForestData& g)\n{\n    auto iterPair = out_edges(v, g);\n    return static_cast<boost::graph_traits<crimson::VesselForestData>::degree_size_type>(\n        std::distance(iterPair.first, iterPair.second));\n}\n\ninline std::pair<boost::graph_traits<crimson::VesselForestData>::vertex_iterator,\n                 boost::graph_traits<crimson::VesselForestData>::vertex_iterator>\nvertices(const crimson::VesselForestData& g)\n{\n    auto iter = boost::make_filter_iterator(crimson::ActiveVesselsFilter{&g}, g.getVessels().begin(), g.getVessels().end());\n    auto endIter = boost::make_filter_iterator(crimson::ActiveVesselsFilter{&g}, g.getVessels().end(), g.getVessels().end());\n\n    return {iter, endIter};\n}\n\ninline boost::graph_traits<crimson::VesselForestData>::vertices_size_type num_vertices(const crimson::VesselForestData& g)\n{\n    auto iterPair = vertices(g);\n    return static_cast<boost::graph_traits<crimson::VesselForestData>::vertices_size_type>(\n        std::distance(iterPair.first, iterPair.second));\n}\n\n// static void _test_vertex_list_graph_concept()\n//{\n//    BOOST_CONCEPT_ASSERT((boost::IncidenceGraphConcept<crimson::VesselForestData>));\n//    BOOST_CONCEPT_ASSERT((boost::VertexListGraphConcept<crimson::VesselForestData>));\n//}\n\n} // namespace crimson", "meta": {"hexsha": "219a18a052a50b232a961f9faab9cd3f7fe956e7", "size": 6850, "ext": "h", "lang": "C", "max_stars_repo_path": "Modules/VesselTree/DataManagement/VesselForestDataGraphTraits.h", "max_stars_repo_name": "carthurs/CRIMSONGUI", "max_stars_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-09-17T18:55:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T02:52:38.000Z", "max_issues_repo_path": "Modules/VesselTree/DataManagement/VesselForestDataGraphTraits.h", "max_issues_repo_name": "carthurs/CRIMSONGUI", "max_issues_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Modules/VesselTree/DataManagement/VesselForestDataGraphTraits.h", "max_forks_repo_name": "carthurs/CRIMSONGUI", "max_forks_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-05-19T09:02:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-26T17:39:57.000Z", "avg_line_length": 36.6310160428, "max_line_length": 127, "alphanum_fraction": 0.7027737226, "num_tokens": 1615, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1919327772028789, "lm_q2_score": 0.020964242920794657, "lm_q1q2_score": 0.004023725365743912}}
{"text": "#pragma once\n\n#include <vector>\n#include <string>\n#include <memory>\n#include <functional>\n#include <gsl>\n\nstruct Vec3 { float x,y,z; };\nstruct Vec2 { float x,y; };\n\n#include \"types.h\"\n#include \"automaticId.h\"", "meta": {"hexsha": "4fbcab844c51c1e92720775b42ffd4959cae0e29", "size": 208, "ext": "h", "lang": "C", "max_stars_repo_path": "include/fakemine/base.h", "max_stars_repo_name": "racerxdl/bedhock", "max_stars_repo_head_hexsha": "73659ce98b51eb8ebed297684f62b39fb728e37e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-12-21T17:14:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T21:38:11.000Z", "max_issues_repo_path": "include/fakemine/base.h", "max_issues_repo_name": "racerxdl/bedhock", "max_issues_repo_head_hexsha": "73659ce98b51eb8ebed297684f62b39fb728e37e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/fakemine/base.h", "max_forks_repo_name": "racerxdl/bedhock", "max_forks_repo_head_hexsha": "73659ce98b51eb8ebed297684f62b39fb728e37e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.0, "max_line_length": 29, "alphanum_fraction": 0.6875, "num_tokens": 54, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1645164792819756, "lm_q2_score": 0.024423088855833577, "lm_q1q2_score": 0.004018000591752594}}
{"text": "#include <assert.h>\n#include <stdlib.h>\n#include <ctype.h>\n#include <string.h>\n\n#include <asf.h>\n#include \"asf_tiff.h\"\n\n#include <gsl/gsl_math.h>\n#include <proj_api.h>\n\n#include \"asf_jpeg.h\"\n#include <png.h>\n#include \"envi.h\"\n\n#include \"dateUtil.h\"\n#include <time.h>\n#include \"matrix.h\"\n#include <asf_nan.h>\n#include <asf_endian.h>\n#include <asf_meta.h>\n#include <asf_export.h>\n#include <asf_raster.h>\n#include <float_image.h>\n#include <spheroids.h>\n#include <typlim.h>\n#include <hdf5.h>\n\n#define RES 16\n#define MAX_PTS 256\n\nvoid h5_att_double(hid_t data, hid_t space, char *name, double value)\n{\n  hid_t attr = H5Acreate(data, name, H5T_NATIVE_DOUBLE, space, H5P_DEFAULT, \n\t\t\t H5P_DEFAULT);\n  H5Awrite(attr, H5T_NATIVE_DOUBLE, &value);\n  H5Aclose(attr);\n}\n\nvoid h5_att_float(hid_t data, hid_t space, char *name, float value)\n{\n  hid_t attr = H5Acreate(data, name, H5T_NATIVE_FLOAT, space, H5P_DEFAULT, \n\t\t\t H5P_DEFAULT);\n  H5Awrite(attr, H5T_NATIVE_FLOAT, &value);\n  H5Aclose(attr);\n}\n\nvoid h5_att_int(hid_t data, hid_t space, char *name, int value)\n{\n  hid_t attr = H5Acreate(data, name, H5T_NATIVE_INT, space, H5P_DEFAULT, \n\t\t\t H5P_DEFAULT);\n  H5Awrite(attr, H5T_NATIVE_INT, &value);\n  H5Aclose(attr);\n}\n\nvoid h5_att_float2(hid_t data, hid_t space, char *name, float *value)\n{\n  hid_t attr = H5Acreate(data, name, H5T_NATIVE_FLOAT, space, H5P_DEFAULT, \n\t\t\t H5P_DEFAULT);\n  H5Awrite(attr, H5T_NATIVE_FLOAT, value);\n  H5Aclose(attr);\n}\n\nvoid h5_att_str(hid_t data, hid_t space, char *name, char *value)\n{\n  hid_t str = H5Tcopy(H5T_C_S1);\n  H5Tset_size(str, strlen(value));\n  hid_t attr = H5Acreate(data, name, str, space, H5P_DEFAULT, H5P_DEFAULT);\n  H5Awrite(attr, str, value);\n  H5Aclose(attr);\n}\n\nvoid h5_value_double(hid_t file, char *group, char *name, \n\t\t     double value, char *long_name, char *units)\n{\n  char meta[100];\n  sprintf(meta, \"%s/%s\", group, name);\n  hid_t h5_space = H5Screate(H5S_SCALAR);\n  hid_t h5_data = H5Dcreate(file, meta, H5T_NATIVE_DOUBLE, h5_space,\n\t\t\t    H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);\n  H5Dwrite(h5_data, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, &value);\n  h5_att_str(h5_data, h5_space, \"long_name\", long_name);\n  if (units && strlen(units) > 0) \n    h5_att_str(h5_data, h5_space, \"units\", units);\n  H5Dclose(h5_data);\n  H5Sclose(h5_space);\n}\n\nvoid h5_value_float(hid_t file, char *group, char *name, \n\t\t    float value, char *long_name, char *units)\n{\n  char meta[100];\n  sprintf(meta, \"%s/%s\", group, name);\n  hid_t h5_space = H5Screate(H5S_SCALAR);\n  hid_t h5_data = H5Dcreate(file, meta, H5T_NATIVE_FLOAT, h5_space,\n\t\t\t    H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);\n  H5Dwrite(h5_data, H5T_NATIVE_FLOAT, H5S_ALL, H5S_ALL, H5P_DEFAULT, &value);\n  h5_att_str(h5_data, h5_space, \"long_name\", long_name);\n  if (units && strlen(units) > 0)\n    h5_att_str(h5_data, h5_space, \"units\", units);\n  H5Dclose(h5_data);\n  H5Sclose(h5_space);\n}\n\nvoid h5_value_int(hid_t file, char *group, char *name, \n\t\t  int value, char *long_name, char *units)\n{\n  char meta[100];\n  sprintf(meta, \"%s/%s\", group, name);\n  hid_t h5_space = H5Screate(H5S_SCALAR);\n  hid_t h5_data = H5Dcreate(file, meta, H5T_NATIVE_INT, h5_space,\n\t\t\t    H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);\n  H5Dwrite(h5_data, H5T_NATIVE_INT, H5S_ALL, H5S_ALL, H5P_DEFAULT, &value);\n  h5_att_str(h5_data, h5_space, \"long_name\", long_name);\n  if (units && strlen(units) > 0)\n    h5_att_str(h5_data, h5_space, \"units\", units);\n  H5Dclose(h5_data);\n  H5Sclose(h5_space);\n}\n\nvoid h5_value_str(hid_t file, char *group, char *name, \n\t\t  char *value, char *long_name, char *units)\n{\n  char meta[100];\n  sprintf(meta, \"%s/%s\", group, name);\n  hid_t h5_space = H5Screate(H5S_SCALAR);\n  hid_t h5_str = H5Tcopy(H5T_C_S1);\n  H5Tset_size(h5_str, strlen(value));\n  hid_t h5_data = H5Dcreate(file, meta, h5_str, h5_space,\n\t\t\t H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);\n  H5Dwrite(h5_data, h5_str, H5S_ALL, H5S_ALL, H5P_DEFAULT, value);\n  h5_att_str(h5_data, h5_space, \"long_name\", long_name);\n  if (units && strlen(units) > 0)\n    h5_att_str(h5_data, h5_space, \"units\", units);\n  H5Dclose(h5_data);\n  H5Sclose(h5_space);\n}\n\nh5_t *initialize_h5_file(const char *output_file_name, meta_parameters *md)\n{\n  hid_t h5_file, h5_datagroup, h5_metagroup, h5_data, h5_proj;\n  hid_t h5_array, h5_string, h5_time, h5_lat, h5_lon, h5_xgrid, h5_ygrid;\n  int ii, kk, complex=FALSE, projected=FALSE;\n  char *spatial_ref=NULL, *datum=NULL, *spheroid=NULL;\n  char dataset[50], group[50], band[5], str_attr[50], tmp[50];\n  double lfValue;\n\n  // Convenience variables\n  meta_general *mg = md->general;\n  meta_sar *ms = md->sar;\n  meta_state_vectors *mo = md->state_vectors;\n  meta_projection *mp = md->projection;\n\n  // Check whether data is map projected\n  if (mp && mp->type != SCANSAR_PROJECTION)\n    //asfPrintError(\"Image is map projected. Wrong initialization function!\\n\");\n    projected = TRUE;\n\n  // Initialize the HDF pointer structure\n  h5_t *h5 = (h5_t *) MALLOC(sizeof(h5_t));\n  int band_count = mg->band_count;\n  h5->var_count = band_count;\n  h5->var = (hid_t *) MALLOC(sizeof(hid_t)*h5->var_count);\n\n  // Check for complex data\n  if (mg->image_data_type == COMPLEX_IMAGE)\n    complex = TRUE;\n\n  // Create new HDF5 file\n  h5_file = \n    H5Fcreate(output_file_name, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);\n  h5->file = h5_file;\n\n  // Create data space\n  int samples = mg->sample_count;\n  int lines = mg->line_count;\n  hsize_t dims[2] = { lines, samples };\n  hsize_t cdims[2] = { 100, samples };\n  hsize_t rdims[2] = { 1, 2 };\n  h5_array = H5Screate_simple(2, dims, NULL);\n  h5->space = h5_array;\n  h5_string = H5Screate(H5S_SCALAR);\n  hid_t h5_range = H5Screate(H5S_SIMPLE);\n  H5Sset_extent_simple(h5_range, 2, rdims, NULL); \n  \n  // Create data structure\n  char **band_name = extract_band_names(mg->bands, band_count);\n  hid_t h5_plist = H5Pcreate(H5P_DATASET_CREATE);\n  H5Pset_chunk(h5_plist, 2, cdims);\n  H5Pset_deflate(h5_plist, 6);\n  \n  // Create a data group\n  sprintf(group, \"/data\");\n  h5_datagroup = H5Gcreate(h5_file, group, H5P_DEFAULT, H5P_DEFAULT, \n\t\t\t   H5P_DEFAULT);\n  // Projection information\n  if (projected) { \n    sprintf(group, \"/data/projection\");\n    h5_proj = H5Gcreate(h5_file, group, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);\n\n    if (mp->type == UNIVERSAL_TRANSVERSE_MERCATOR) {\n\n      h5_att_str(h5_proj, h5_string, \"grid_mapping_name\", \n\t\t \"transverse_mercator\");\n      h5_att_double(h5_proj, h5_string, \"scale_factor_at_central_meridian\", \n\t\t    mp->param.utm.scale_factor);\n      h5_att_double(h5_proj, h5_string, \"longitude_of_central_meridian\", \n\t\t    mp->param.utm.lon0);\n      h5_att_double(h5_proj, h5_string, \"latitude_of_projection_origin\",\n\t\t    mp->param.utm.lat0);\n      h5_att_double(h5_proj, h5_string, \"false_easting\", \n\t\t    mp->param.utm.false_easting);\n      h5_att_double(h5_proj, h5_string, \"false_northing\", \n\t\t    mp->param.utm.false_northing);\n      h5_att_str(h5_proj, h5_string, \"projection_x_coordinate\", \"xgrid\");\n      h5_att_str(h5_proj, h5_string, \"projection_y_coordinate\", \"ygrid\");\n      h5_att_str(h5_proj, h5_string, \"units\", \"meters\"); \n      h5_att_double(h5_proj, h5_string, \"grid_boundary_top_projected_y\",\n\t\t    mp->startY);\n      lfValue = mp->startY + mg->line_count * mp->perY;\n      h5_att_double(h5_proj, h5_string, \"grid_boundary_bottom_projected_y\",\n\t\t    lfValue);\n      lfValue = mp->startX + mg->sample_count * mp->perX;\n      h5_att_double(h5_proj, h5_string, \"grid_boundary_right_projected_x\",\n\t\t    lfValue);\n      h5_att_double(h5_proj, h5_string, \"grid_boundary_left_projected_x\",\n\t\t    mp->startX);\n      spatial_ref = (char *) MALLOC(sizeof(char)*1024);\n      datum = (char *) datum_toString(mp->datum);\n      spheroid = (char *) spheroid_toString(mp->spheroid);\n      double flat = mp->re_major/(mp->re_major - mp->re_minor);\n      sprintf(spatial_ref, \"PROJCS[\\\"%s_UTM_Zone_%d%c\\\",GEOGCS[\\\"GCS_%s\\\",DATUM[\\\"D_%s\\\",SPHEROID[\\\"%s\\\",%.1lf,%-16.11g]],PRIMEM[\\\"Greenwich\\\",0],UNIT[\\\"Degree\\\",0.017453292519943295]],PROJECTION[\\\"Transverse_Mercator\\\"],PARAMETER[\\\"False_Easting\\\",%.1lf],PARAMETER[\\\"False_Northing\\\",%.1lf],PARAMETER[\\\"Central_Meridian\\\",%.1lf],PARAMETER[\\\"Scale_Factor\\\",%.4lf],PARAMETER[\\\"Latitude_Of_Origin\\\",%.1lf],UNIT[\\\"Meter\\\",1]]\",\n\t      spheroid, mp->param.utm.zone, mp->hem, spheroid, datum, \n\t      spheroid, mp->re_major, flat, mp->param.utm.false_easting, \n\t      mp->param.utm.false_northing, mp->param.utm.lon0, \n\t      mp->param.utm.scale_factor, mp->param.utm.lat0);\n      h5_att_str(h5_proj, h5_string, \"spatial_ref\", spatial_ref);\n      sprintf(str_attr, \"+proj=utm +zone=%d\", mp->param.utm.zone);\n      if (mg->center_latitude < 0)\n\tstrcat(str_attr, \" +south\");\n      h5_att_str(h5_proj, h5_string, \"proj4text\", str_attr);\n      h5_att_int(h5_proj, h5_string, \"zone\", mp->param.utm.zone);\n      h5_att_double(h5_proj, h5_string, \"semimajor_radius\", mp->re_major);\n      h5_att_double(h5_proj, h5_string, \"semiminor_radius\", mp->re_minor);\n      sprintf(str_attr, \"%.6lf %.6lf 0 %.6lf 0 %.6lf\", mp->startX, mp->perX, \n\t      mp->startY, mp->perY); \n      h5_att_str(h5_proj, h5_string, \"GeoTransform\", str_attr);\n    }\n    else if (mp->type == POLAR_STEREOGRAPHIC) {\n\n      h5_att_str(h5_proj, h5_string, \"grid_mapping_name\", \n\t\t \"polar_stereographic\");\n      h5_att_double(h5_proj, h5_string, \"straight_vertical_longitude_from_pole\",\n\t\t    mp->param.ps.slon);\n      h5_att_double(h5_proj, h5_string, \"latitude_of_projection_origin\", \n\t\t    mp->param.ps.slat);\n      h5_att_double(h5_proj, h5_string, \"scale_factor_at_projection_origin\",\n\t\t    1.0);\n      h5_att_double(h5_proj, h5_string, \"false_easting\", \n\t\t    mp->param.ps.false_easting);\n      h5_att_double(h5_proj, h5_string, \"false_northing\",\n\t\t    mp->param.ps.false_northing);\n      h5_att_str(h5_proj, h5_string, \"projection_x_coordinate\", \"xgrid\");\n      h5_att_str(h5_proj, h5_string, \"projection_y_coordinate\", \"ygrid\");\n      h5_att_str(h5_proj, h5_string, \"units\", \"meters\");\n      h5_att_double(h5_proj, h5_string, \"grid_boundary_top_projected_y\",\n\t\t    mp->startY);\n      lfValue = mp->startY + mg->line_count * mp->perY;\n      h5_att_double(h5_proj, h5_string, \"grid_boundary_bottom_projected_y\",\n\t\t    lfValue);\n      lfValue = mp->startX + mg->sample_count * mp->perX;\n      h5_att_double(h5_proj, h5_string, \"grid_boundary_right_projected_x\",\n\t\t    lfValue);\n      h5_att_double(h5_proj, h5_string, \"grid_boundary_left_projected_x\",\n\t\t    mp->startX);\n      spatial_ref = (char *) MALLOC(sizeof(char)*1024);\n      double flat = mp->re_major/(mp->re_major - mp->re_minor);\n      sprintf(spatial_ref, \"PROJCS[\\\"Stereographic_North_Pole\\\",GEOGCS[\\\"unnamed ellipse\\\",DATUM[\\\"D_unknown\\\",SPHEROID[\\\"Unknown\\\",%.3lf,%-16.11g]],PRIMEM[\\\"Greenwich\\\",0],UNIT[\\\"Degree\\\",0.0002247191011236]],PROJECTION[\\\"Stereographic_North_Pole\\\"],PARAMETER[\\\"standard_parallel_1\\\",%.4lf],PARAMETER[\\\"central_meridian\\\",%.4lf],PARAMETER[\\\"scale_factor\\\",1],PARAMETER[\\\"false_easting\\\",%.1lf],PARAMETER[\\\"false_northing\\\",%.1lf],UNIT[\\\"Meter\\\",1, AUTHORITY[\\\"EPSG\\\",\\\"9122\\\"]],AUTHORITY[\\\"EPSG\\\",\\\"3411\\\"]]\",\n\t      mp->re_major, flat, mp->param.ps.slat, mp->param.ps.slon,\n\t      mp->param.ps.false_easting, mp->param.ps.false_northing);\n      h5_att_str(h5_proj, h5_string, \"spatial_ref\", spatial_ref);\n      if (mp->param.ps.is_north_pole)\n\tsprintf(str_attr, \"+proj=stere +lat_0=90.0000 +lat_ts=%.4lf \"\n\t\t\"+lon_0=%.4lf +k=1 +x_0=%.3lf +y_0=%.3lf +a=%.3lf +b=%.3lf \"\n\t\t\"+units=m +no_defs\", mp->param.ps.slat, mp->param.ps.slon,\n\t\tmp->param.ps.false_easting, mp->param.ps.false_northing,\n\t\tmp->re_major, mp->re_minor);\n      else\n\tsprintf(str_attr, \"+proj=stere +lat_0=-90.0000 +lat_ts=%.4lf \"\n\t\t\"+lon_0=%.4lf +k=1 +x_0=%.3lf +y_0=%.3lf +a=%.3lf +b=%.3lf \"\n\t\t\"+units=m +no_defs\", mp->param.ps.slat, mp->param.ps.slon,\n\t\tmp->param.ps.false_easting, mp->param.ps.false_northing,\n\t\tmp->re_major, mp->re_minor);\n      h5_att_str(h5_proj, h5_string, \"proj4text\", str_attr);\n      h5_att_double(h5_proj, h5_string, \"semimajor_radius\", mp->re_major);\n      h5_att_double(h5_proj, h5_string, \"semiminor_radius\", mp->re_minor);\n      sprintf(str_attr, \"%.6lf %.6lf 0 %.6lf 0 %.6lf\", mp->startX, mp->perX, \n\t      mp->startY, mp->perY); \n      h5_att_str(h5_proj, h5_string, \"GeoTransform\", str_attr);\n    }\n    else if (mp->type == ALBERS_EQUAL_AREA) {\n\n      h5_att_str(h5_proj, h5_string, \"grid_mapping_name\", \n\t\t \"albers_conical_equal_area\");\n      h5_att_double(h5_proj, h5_string, \"standard_parallel_1\",\n\t\t    mp->param.albers.std_parallel1);\n      h5_att_double(h5_proj, h5_string, \"standard_parallel_2\",\n\t\t    mp->param.albers.std_parallel2);\n      h5_att_double(h5_proj, h5_string, \"longitude_of_central_meridian\", \n\t\t    mp->param.albers.center_meridian);\n      h5_att_double(h5_proj, h5_string, \"latitude_of_projection_origin\",\n\t\t    mp->param.albers.orig_latitude);\n      h5_att_double(h5_proj, h5_string, \"false_easting\", \n\t\t    mp->param.albers.false_easting);\n      h5_att_double(h5_proj, h5_string, \"false_northing\",\n\t\t    mp->param.albers.false_northing);\n      h5_att_str(h5_proj, h5_string, \"projection_x_coordinate\", \"xgrid\");\n      h5_att_str(h5_proj, h5_string, \"projection_y_coordinate\", \"ygrid\");\n      h5_att_str(h5_proj, h5_string, \"units\", \"meters\");\n      h5_att_double(h5_proj, h5_string, \"grid_boundary_top_projected_y\",\n\t\t    mp->startY);\n      lfValue = mp->startY + mg->line_count * mp->perY;\n      h5_att_double(h5_proj, h5_string, \"grid_boundary_bottom_projected_y\",\n\t\t    lfValue);\n      lfValue = mp->startX + mg->sample_count * mp->perX;\n      h5_att_double(h5_proj, h5_string, \"grid_boundary_right_projected_x\",\n\t\t    lfValue);\n      h5_att_double(h5_proj, h5_string, \"grid_boundary_left_projected_x\",\n\t\t    mp->startX);\n      spatial_ref = (char *) MALLOC(sizeof(char)*1024);\n      datum = (char *) datum_toString(mp->datum);\n      spheroid = (char *) spheroid_toString(mp->spheroid);\n      double flat = mp->re_major/(mp->re_major - mp->re_minor);\n      sprintf(spatial_ref, \"PROJCS[\\\"Albers_Equal_Area_Conic\\\",GEOGCS[\\\"GCS_%s\\\",DATUM[\\\"D_%s\\\",SPHEROID[\\\"%s\\\",%.3lf,%-16.11g]],PRIMEM[\\\"Greenwich\\\",0],UNIT[\\\"Degree\\\",0.0174532925199432955]],PROJECTION[\\\"Albers\\\"],PARAMETER[\\\"False_Easting\\\",%.3lf],PARAMETER[\\\"False_Northing\\\",%.3lf],PARAMETER[\\\"Central_Meridian\\\",%.4lf],PARAMETER[\\\"Standard_Parallel_1\\\",%.4lf],PARAMETER[\\\"Standard_Parallel_2\\\",%.4lf],PARAMETER[\\\"Latitude_Of_Origin\\\",%.4lf],UNIT[\\\"Meter\\\",1]]\",\n\t      datum, datum, spheroid, mp->re_major, flat, \n\t      mp->param.albers.false_easting, mp->param.albers.false_northing,\n\t      mp->param.albers.center_meridian, mp->param.albers.std_parallel1,\n\t      mp->param.albers.std_parallel2, mp->param.albers.orig_latitude);\n      h5_att_str(h5_proj, h5_string, \"spatial_ref\", spatial_ref);\n      sprintf(str_attr, \"+proj=aea +lat_1=%.4lf +lat_2=%.4lf +lat_0=%.4lf \"\n\t      \"+lon_0=%.4lf +x_0=%.3lf +y_0=%.3lf\", \n\t      mp->param.albers.std_parallel1, mp->param.albers.std_parallel2,\n\t      mp->param.albers.orig_latitude, mp->param.albers.center_meridian,\n\t      mp->param.albers.false_easting, mp->param.albers.false_northing);\n      h5_att_str(h5_proj, h5_string, \"proj4text\", str_attr);\n      h5_att_double(h5_proj, h5_string, \"semimajor_radius\", mp->re_major);\n      h5_att_double(h5_proj, h5_string, \"semiminor_radius\", mp->re_minor);\n      sprintf(str_attr, \"%.6lf %.6lf 0 %.6lf 0 %.6lf\", mp->startX, mp->perX, \n\t      mp->startY, mp->perY); \n      h5_att_str(h5_proj, h5_string, \"GeoTransform\", str_attr);\n    }\n    else if (mp->type == LAMBERT_CONFORMAL_CONIC) {\n\n      h5_att_str(h5_proj, h5_string, \"grid_mapping_name\", \n\t\t \"lambert_conformal_conic\");\n      h5_att_double(h5_proj, h5_string, \"standard_parallel_1\",\n\t\t    mp->param.lamcc.plat1);\n      h5_att_double(h5_proj, h5_string, \"standard_parallel_2\",\n\t\t    mp->param.lamcc.plat2);\n      h5_att_double(h5_proj, h5_string, \"longitude_of_central_meridian\", \n\t\t    mp->param.lamcc.lon0);\n      h5_att_double(h5_proj, h5_string, \"latitude_of_projection_origin\",\n\t\t    mp->param.lamcc.lat0);\n      h5_att_double(h5_proj, h5_string, \"false_easting\", \n\t\t    mp->param.lamcc.false_easting);\n      h5_att_double(h5_proj, h5_string, \"false_northing\",\n\t\t    mp->param.lamcc.false_northing);\n      h5_att_str(h5_proj, h5_string, \"projection_x_coordinate\", \"xgrid\");\n      h5_att_str(h5_proj, h5_string, \"projection_y_coordinate\", \"ygrid\");\n      h5_att_str(h5_proj, h5_string, \"units\", \"meters\");\n      h5_att_double(h5_proj, h5_string, \"grid_boundary_top_projected_y\",\n\t\t    mp->startY);\n      lfValue = mp->startY + mg->line_count * mp->perY;\n      h5_att_double(h5_proj, h5_string, \"grid_boundary_bottom_projected_y\",\n\t\t    lfValue);\n      lfValue = mp->startX + mg->sample_count * mp->perX;\n      h5_att_double(h5_proj, h5_string, \"grid_boundary_right_projected_x\",\n\t\t    lfValue);\n      h5_att_double(h5_proj, h5_string, \"grid_boundary_left_projected_x\",\n\t\t    mp->startX);\n      spatial_ref = (char *) MALLOC(sizeof(char)*1024);\n      datum = (char *) datum_toString(mp->datum);\n      spheroid = (char *) spheroid_toString(mp->spheroid);\n      double flat = mp->re_major/(mp->re_major - mp->re_minor);\n      sprintf(spatial_ref, \"PROJCS[\\\"Lambert_Conformal_Conic\\\",GEOGCS[\\\"GCS_%s\\\",DATUM[\\\"D_%s\\\",SPHEROID[\\\"%s\\\",%.3lf,%-16.11g]],PRIMEM[\\\"Greenwich\\\",0],UNIT[\\\"Degree\\\",0.0174532925199432955]],PROJECTION[\\\"Lambert_Conformal_Conic\\\"],PARAMETER[\\\"False_Easting\\\",%.3lf],PARAMETER[\\\"False_Northing\\\",%.3lf],PARAMETER[\\\"Central_Meridian\\\",%.4lf],PARAMETER[\\\"Standard_Parallel_1\\\",%.4lf],PARAMETER[\\\"Standard_Parallel_2\\\",%.4lf],PARAMETER[\\\"Latitude_Of_Origin\\\",%.4lf],UNIT[\\\"Meter\\\",1]]\",\n\t      datum, datum, spheroid, mp->re_major, flat, \n\t      mp->param.lamcc.false_easting, mp->param.lamcc.false_northing,\n\t      mp->param.lamcc.lon0, mp->param.lamcc.plat1,\n\t      mp->param.lamcc.plat2, mp->param.lamcc.lat0);\n      h5_att_str(h5_proj, h5_string, \"spatial_ref\", spatial_ref);\n      sprintf(str_attr, \"+proj=lcc +lat_1=%.4lf +lat_2=%.4lf +lat_0=%.4lf \"\n\t      \"+lon_0=%.4lf +x_0=%.3lf +y_0=%.3lf\", \n\t      mp->param.lamcc.plat1, mp->param.lamcc.plat2,\n\t      mp->param.lamcc.lat0, mp->param.lamcc.lon0,\n\t      mp->param.lamcc.false_easting, mp->param.lamcc.false_northing);\n      h5_att_str(h5_proj, h5_string, \"proj4text\", str_attr);\n      h5_att_double(h5_proj, h5_string, \"semimajor_radius\", mp->re_major);\n      h5_att_double(h5_proj, h5_string, \"semiminor_radius\", mp->re_minor);\n      sprintf(str_attr, \"%.6lf %.6lf 0 %.6lf 0 %.6lf\", mp->startX, mp->perX, \n\t      mp->startY, mp->perY); \n      h5_att_str(h5_proj, h5_string, \"GeoTransform\", str_attr);\n    }\n    else if (mp->type == LAMBERT_AZIMUTHAL_EQUAL_AREA) {\n\n      h5_att_str(h5_proj, h5_string, \"grid_mapping_name\", \n\t\t \"lambert_azimuthal_equal_area\");\n      h5_att_double(h5_proj, h5_string, \"longitude_of_projection_origin\", \n\t\t    mp->param.lamaz.center_lon);\n      h5_att_double(h5_proj, h5_string, \"latitude_of_projection_origin\",\n\t\t    mp->param.lamaz.center_lat);\n      h5_att_double(h5_proj, h5_string, \"false_easting\", \n\t\t    mp->param.lamaz.false_easting);\n      h5_att_double(h5_proj, h5_string, \"false_northing\",\n\t\t    mp->param.lamaz.false_northing);\n      h5_att_str(h5_proj, h5_string, \"projection_x_coordinate\", \"xgrid\");\n      h5_att_str(h5_proj, h5_string, \"projection_y_coordinate\", \"ygrid\");\n      h5_att_str(h5_proj, h5_string, \"units\", \"meters\");\n      h5_att_double(h5_proj, h5_string, \"grid_boundary_top_projected_y\",\n\t\t    mp->startY);\n      lfValue = mp->startY + mg->line_count * mp->perY;\n      h5_att_double(h5_proj, h5_string, \"grid_boundary_bottom_projected_y\",\n\t\t    lfValue);\n      lfValue = mp->startX + mg->sample_count * mp->perX;\n      h5_att_double(h5_proj, h5_string, \"grid_boundary_right_projected_x\",\n\t\t    lfValue);\n      h5_att_double(h5_proj, h5_string, \"grid_boundary_left_projected_x\",\n\t\t    mp->startX);\n      spatial_ref = (char *) MALLOC(sizeof(char)*1024);\n      datum = (char *) datum_toString(mp->datum);\n      spheroid = (char *) spheroid_toString(mp->spheroid);\n      double flat = mp->re_major/(mp->re_major - mp->re_minor);\n      sprintf(spatial_ref, \"PROJCS[\\\"Lambert_Azimuthal_Equal_Area\\\",GEOGCS[\\\"GCS_%s\\\",DATUM[\\\"D_%s\\\",SPHEROID[\\\"%s\\\",%.3lf,%-16.11g]],PRIMEM[\\\"Greenwich\\\",0],UNIT[\\\"Degree\\\",0.0174532925199432955]],PROJECTION[\\\"Lambert_Conformal_Conic\\\"],PARAMETER[\\\"False_Easting\\\",%.3lf],PARAMETER[\\\"False_Northing\\\",%.3lf],PARAMETER[\\\"Central_Meridian\\\",%.4lf],PARAMETER[\\\"Latitude_Of_Origin\\\",%.4lf],UNIT[\\\"Meter\\\",1]]\",\n\t      datum, datum, spheroid, mp->re_major, flat, \n\t      mp->param.lamaz.false_easting, mp->param.lamaz.false_northing,\n\t      mp->param.lamaz.center_lon, mp->param.lamaz.center_lat);\n      h5_att_str(h5_proj, h5_string, \"spatial_ref\", spatial_ref);\n      sprintf(str_attr, \"+proj=laea +lat_0=%.4lf +lon_0=%.4lf +x_0=%.3lf \"\n\t      \"+y_0=%.3lf\", \n\t      mp->param.lamaz.center_lat, mp->param.lamaz.center_lon,\n\t      mp->param.lamaz.false_easting, mp->param.lamaz.false_northing);\n      h5_att_str(h5_proj, h5_string, \"proj4text\", str_attr);\n      h5_att_double(h5_proj, h5_string, \"semimajor_radius\", mp->re_major);\n      h5_att_double(h5_proj, h5_string, \"semiminor_radius\", mp->re_minor);\n      sprintf(str_attr, \"%.6lf %.6lf 0 %.6lf 0 %.6lf\", mp->startX, mp->perX, \n\t      mp->startY, mp->perY); \n      h5_att_str(h5_proj, h5_string, \"GeoTransform\", str_attr);\n    }\n  }\n\n  for (ii=0; ii<band_count; ii++) {\n\n    // Create data set\n    strncpy(band, band_name[ii], 2);\n    band[2] = '\\0';\n    sprintf(dataset, \"/data/%s_AMPLITUDE_IMAGE\", band);\n    h5_data = H5Dcreate(h5_file, dataset, H5T_NATIVE_FLOAT, h5_array,\n\t\t\tH5P_DEFAULT, h5_plist, H5P_DEFAULT);\n    h5->var[ii] = h5_data;\n\n    // Add attributes (from CF convention)\n    sprintf(str_attr, \"%s\", mg->sensor);\n    if (mg->image_data_type < 9)\n      strcat(str_attr, \" radar backscatter\");\n    if (mg->radiometry >= r_SIGMA_DB && mg->radiometry <= r_GAMMA_DB)\n      strcat(str_attr, \" in dB\");\n    h5_att_str(h5_data, h5_string, \"long_name\", str_attr);\n    h5_att_str(h5_data, h5_string, \"cell_methods\", \"area: backscatter value\");\n    h5_att_str(h5_data, h5_string, \"units\", \"1\");\n    h5_att_str(h5_data, h5_string, \"units_description\",\n\t       \"unitless normalized radar cross-section\");\n    if (mg->radiometry >= r_SIGMA && mg->radiometry <= r_GAMMA)\n      strcat(str_attr, \" stored as powerscale\");\n    else if (mg->radiometry >= r_SIGMA_DB && mg->radiometry <= r_GAMMA_DB)\n      strcat(str_attr, \" stored as dB=10*log10(*)\");\n    h5_att_float(h5_data, h5_string, \"_FillValue\", -999);\n    h5_att_str(h5_data, h5_string, \"coordinates\", \"longitude latitude\");\n    if (projected)\n      h5_att_str(h5_data, h5_string, \"grid_mapping\", \"projection\");\n\n    // Close up\n    H5Dclose(h5_data);\n  }\n\n  // Extra bands - Time\n  asfPrintStatus(\"Storing band 'time' ...\\n\");  \n  float serial_date = seconds_from_str(mg->acquisition_date);\n  sprintf(dataset, \"/data/time\");\n  h5_time = H5Dcreate(h5_file, dataset, H5T_NATIVE_FLOAT, h5_string,\n\t\t      H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);\n  H5Dwrite(h5_time, H5T_NATIVE_FLOAT, H5S_ALL, H5S_ALL, H5P_DEFAULT, \n\t   &serial_date);\n  h5_att_str(h5_time, h5_string, \"units\", \"seconds since 1900-01-01T00:00:00Z\");\n  h5_att_str(h5_time, h5_string, \"references\", \"scene center time\");\n  h5_att_str(h5_time, h5_string, \"standard_name\", \"time\");\n  h5_att_str(h5_time, h5_string, \"axis\", \"T\");\n  h5_att_str(h5_time, h5_string, \"long_name\", \"serial date\");\n  H5Dclose(h5_time);\n  \n  // Extra bands - Longitude\n  int nl = mg->line_count;\n  int ns = mg->sample_count;\n  long pixel_count = mg->line_count * mg->sample_count;\n  double *value = (double *) MALLOC(sizeof(double)*MAX_PTS);\n  double *l = (double *) MALLOC(sizeof(double)*MAX_PTS);\n  double *s = (double *) MALLOC(sizeof(double)*MAX_PTS);\n  double line, sample, lat, lon, first_value;\n  float *lons = (float *) MALLOC(sizeof(float)*pixel_count);\n  asfPrintStatus(\"Generating band 'longitude' ...\\n\");\n  meta_get_latLon(md, 0, 0, 0.0, &lat, &lon);\n  if (lon < 0.0)\n    first_value = lon + 360.0;\n  else\n    first_value = lon;\n  asfPrintStatus(\"Calculating grid for quadratic fit ...\\n\");\n  for (ii=0; ii<RES; ii++) {\n    for (kk=0; kk<RES; kk++) {\n      line = ii * nl / RES;\n      sample = kk * ns / RES;\n      meta_get_latLon(md, line, sample, 0.0, &lat, &lon);\n      l[ii*RES+kk] = line;\n      s[ii*RES+kk] = sample;\n      if (lon < 0.0)\n\tvalue[ii*RES+kk] = lon + 360.0;\n      else\n\tvalue[ii*RES+kk] = lon;\n    }\n    asfLineMeter(ii, nl);\n  }\n  quadratic_2d q = find_quadratic(value, l, s, MAX_PTS);\n  q.A = first_value;\n  for (ii=0; ii<nl; ii++) {\n    for (kk=0; kk<ns; kk++) {\n      lons[ii*ns+kk] = (float)\n\t(q.A + q.B*ii + q.C*kk + q.D*ii*ii + q.E*ii*kk + q.F*kk*kk +\n\t q.G*ii*ii*kk + q.H*ii*kk*kk + q.I*ii*ii*kk*kk + q.J*ii*ii*ii +\n\t q.K*kk*kk*kk) - 360.0;\n      if (lons[ii*ns+kk] < -180.0)\n\tlons[ii*ns+kk] += 360.0;\n    }\n    asfLineMeter(ii, nl);\n  }\n  asfPrintStatus(\"Storing band 'longitude' ...\\n\");\n  sprintf(dataset, \"/data/longitude\");\n  h5_lon = H5Dcreate(h5_file, dataset, H5T_NATIVE_FLOAT, h5_array,\n\t\t     H5P_DEFAULT, h5_plist, H5P_DEFAULT);\n  H5Dwrite(h5_lon, H5T_NATIVE_FLOAT, H5S_ALL, H5S_ALL, H5P_DEFAULT, lons);\n  h5_att_str(h5_lon, h5_string, \"units\", \"degrees_east\");\n  h5_att_str(h5_lon, h5_string, \"long_name\", \"longitude\");\n  h5_att_str(h5_lon, h5_string, \"standard_name\", \"longitude\");\n  float valid_range[2] = { -180.0, 180.0 };\n  h5_att_float2(h5_lon, h5_range, \"valid_range\", valid_range);\n  h5_att_float(h5_lon, h5_string, \"_FillValue\", -999);\n  H5Dclose(h5_lon);\n  FREE(lons);\n\n  // Extra bands - Latitude\n  float *lats = (float *) MALLOC(sizeof(float)*pixel_count);\n  asfPrintStatus(\"Generating band 'latitude' ...\\n\");\n  meta_get_latLon(md, 0, 0, 0.0, &lat, &lon);\n  first_value = lat + 180.0;\n  asfPrintStatus(\"Calculating grid for quadratic fit ...\\n\");\n  for (ii=0; ii<RES; ii++) {\n    for (kk=0; kk<RES; kk++) {\n      line = ii * nl / RES;\n      sample = kk * ns / RES;\n      meta_get_latLon(md, line, sample, 0.0, &lat, &lon);\n      l[ii*RES+kk] = line;\n      s[ii*RES+kk] = sample;\n      value[ii*RES+kk] = lat + 180.0;\n    }\n    asfLineMeter(ii, nl);\n  }\n  q = find_quadratic(value, l, s, MAX_PTS);\n  q.A = first_value;\n  for (ii=0; ii<nl; ii++) {\n    for (kk=0; kk<ns; kk++) {\n      if (mg->orbit_direction == 'A')\n\tlats[(nl-ii-1)*ns+kk] = (float)\n\t  (q.A + q.B*ii + q.C*kk + q.D*ii*ii + q.E*ii*kk + q.F*kk*kk +\n\t   q.G*ii*ii*kk + q.H*ii*kk*kk + q.I*ii*ii*kk*kk + q.J*ii*ii*ii +\n\t   q.K*kk*kk*kk) - 180.0;\n      else\n\tlats[ii*ns+kk] = (float)\n\t  (q.A + q.B*ii + q.C*kk + q.D*ii*ii + q.E*ii*kk + q.F*kk*kk +\n\t   q.G*ii*ii*kk + q.H*ii*kk*kk + q.I*ii*ii*kk*kk + q.J*ii*ii*ii +\n\t   q.K*kk*kk*kk) - 180.0;\n    }\n    asfLineMeter(ii, nl);\n  }\n  asfPrintStatus(\"Storing band 'latitude' ...\\n\");\n  sprintf(dataset, \"/data/latitude\");\n  h5_lat = H5Dcreate(h5_file, dataset, H5T_NATIVE_FLOAT, h5_array,\n\t\t     H5P_DEFAULT, h5_plist, H5P_DEFAULT);\n  H5Dwrite(h5_lat, H5T_NATIVE_FLOAT, H5S_ALL, H5S_ALL, H5P_DEFAULT, lats);\n  h5_att_str(h5_lat, h5_string, \"units\", \"degrees_north\");\n  h5_att_str(h5_lat, h5_string, \"long_name\", \"latitude\");\n  h5_att_str(h5_lat, h5_string, \"standard_name\", \"latitude\");\n  valid_range[0] = -90.0;\n  valid_range[1] = 90.0;\n  h5_att_float2(h5_lat, h5_range, \"valid_range\", valid_range);\n  h5_att_float(h5_lat, h5_string, \"_FillValue\", -999);\n  H5Dclose(h5_lat);\n  FREE(lats);\n\n  if (projected) {\n    // Extra bands - ygrid\n    float *ygrids = (float *) MALLOC(sizeof(float)*pixel_count);\n    for (ii=0; ii<nl; ii++) {\n      for (kk=0; kk<ns; kk++)\n\tygrids[ii*ns+kk] = mp->startY + kk*mp->perY;\n      asfLineMeter(ii, nl);\n    }\n    asfPrintStatus(\"Storing band 'ygrid' ...\\n\");\n    sprintf(dataset, \"/data/ygrid\");\n    h5_ygrid = H5Dcreate(h5_file, dataset, H5T_NATIVE_FLOAT, h5_array,\n\t\t\t H5P_DEFAULT, h5_plist, H5P_DEFAULT);\n    H5Dwrite(h5_ygrid, H5T_NATIVE_FLOAT, H5S_ALL, H5S_ALL, H5P_DEFAULT, ygrids);\n    h5_att_str(h5_ygrid, h5_string, \"units\", \"meters\");\n    h5_att_str(h5_ygrid, h5_string, \"long_name\", \n\t       \"projection_grid_y_coordinates\");\n    h5_att_str(h5_ygrid, h5_string, \"standard_name\", \n\t       \"projection_y_coordinates\");\n    h5_att_str(h5_ygrid, h5_string, \"axis\", \"Y\");\n    H5Dclose(h5_ygrid);\n    FREE(ygrids);\n    \n    // Extra bands - xgrid\n    float *xgrids = (float *) MALLOC(sizeof(float)*pixel_count);\n    for (ii=0; ii<nl; ii++) {\n      for (kk=0; kk<ns; kk++) \n\txgrids[ii*ns+kk] = mp->startX + kk*mp->perX;\n      asfLineMeter(ii, nl);\n    }\n    asfPrintStatus(\"Storing band 'xgrid' ...\\n\");\n    sprintf(dataset, \"/data/xgrid\");\n    h5_xgrid = H5Dcreate(h5_file, dataset, H5T_NATIVE_FLOAT, h5_array,\n\t\t\t H5P_DEFAULT, h5_plist, H5P_DEFAULT);\n    H5Dwrite(h5_xgrid, H5T_NATIVE_FLOAT, H5S_ALL, H5S_ALL, H5P_DEFAULT, xgrids);\n    h5_att_str(h5_xgrid, h5_string, \"units\", \"meters\");\n    h5_att_str(h5_xgrid, h5_string, \"long_name\", \n\t       \"projection_grid_x_coordinates\");\n    h5_att_str(h5_xgrid, h5_string, \"standard_name\", \n\t       \"projection_x_coordinates\");\n    h5_att_str(h5_xgrid, h5_string, \"axis\", \"X\");\n    H5Dclose(h5_xgrid);\n    FREE(xgrids);\n  }\n\n  H5Gclose(h5_datagroup);\n\n  // Adding global attributes\n  hid_t h5_global = H5Gopen(h5_file, \"/\", H5P_DEFAULT);\n  h5_att_str(h5_global, h5_string, \"institution\", \"Alaska Satellite Facility\");\n  sprintf(str_attr, \"%s %s %s image\", mg->sensor, mg->sensor_name, mg->mode);\n  h5_att_str(h5_global, h5_string, \"title\", str_attr); \n  if (mg->image_data_type == AMPLITUDE_IMAGE)\n    strcpy(str_attr, \"SAR backcatter image\");\n  h5_att_str(h5_global, h5_string, \"source\", str_attr);\n  h5_att_str(h5_global, h5_string, \"original_file\", mg->basename);\n  ymd_date ymd;\n  hms_time hms;\n  parse_date(mg->acquisition_date, &ymd, &hms);\n  if (strcmp_case(mg->sensor, \"RSAT-1\") == 0)\n    sprintf(str_attr, \"Copyright Canadian Space Agency, %d\", ymd.year);\n  else if (strncmp_case(mg->sensor, \"ERS\", 3) == 0)\n    sprintf(str_attr, \"Copyright European Space Agency, %d\", ymd.year);\n  else if (strcmp_case(mg->sensor, \"JERS-1\") == 0 ||\n\t   strcmp_case(mg->sensor, \"ALOS\") == 0)\n    sprintf(str_attr, \"Copyright Japan Aerospace Exploration Agency , %d\", \n\t    ymd.year);\n  h5_att_str(h5_global, h5_string, \"comment\", str_attr); \n  h5_att_str(h5_global, h5_string, \"reference\",\n\t     \"Documentation available at: www.asf.alaska.edu\");\n  time_t t;\n  struct tm *timeinfo;\n  time(&t);\n  timeinfo = gmtime(&t);\n  sprintf(str_attr, \"%s\", asctime(timeinfo));\n  chomp(str_attr);\n  strcat(str_attr, \", UTC: H5 File created.\");\n  h5_att_str(h5_global, h5_string, \"history\", str_attr); \n  H5Gclose(h5_global);\n\n  // Metadata\n  sprintf(group, \"/metadata\");\n  h5_metagroup = H5Gcreate(h5_file, group, H5P_DEFAULT, H5P_DEFAULT, \n\t\t\t   H5P_DEFAULT);\n\n  // Metadata - General block\n  h5_value_str(h5_file, group, \"general_name\", mg->basename, \"file_name\", NULL);\n  h5_value_str(h5_file, group, \"general_sensor\", mg->sensor,\n\t       \"imaging satellite\", NULL);\n  h5_value_str(h5_file, group, \"general_sensor_name\", mg->sensor_name, \n\t       \"imaging sensor\", NULL);\n  h5_value_str(h5_file, group, \"general_mode\", mg->mode, \"imaging mode\", NULL);\n  h5_value_str(h5_file, group, \"general_processor\", mg->processor, \n\t       \"name and version of processor\", NULL);\n  h5_value_str(h5_file, group, \"general_data_type\", \n\t       data_type2str(mg->data_type), \"type of samples (e.g. REAL64)\", \n\t       NULL);\n  h5_value_str(h5_file, group, \"general_image_data_type\",\n\t       image_data_type2str(mg->image_data_type),\n\t       \"image data type (e.g. AMPLITUDE_IMAGE)\", NULL);\n  h5_value_str(h5_file, group, \"general_radiometry\",\n\t       radiometry2str(mg->radiometry), \"radiometry (e.g. SIGMA)\", NULL);\n  // FIXME: UDUNITS seconds since ...\n  h5_value_str(h5_file, group, \"general_acquisition_date\", mg->acquisition_date,\n\t       \"acquisition date of image\", NULL);\n  h5_value_int(h5_file, group, \"general_orbit\", mg->orbit,\n\t       \"orbit number of image\", NULL);\n  if (mg->orbit_direction == 'A')\n    strcpy(str_attr, \"Ascending\");\n  else\n    strcpy(str_attr, \"Descending\");\n  h5_value_str(h5_file, group, \"general_orbit_direction\", str_attr,\n\t       \"orbit direction\", NULL);\n  h5_value_int(h5_file, group, \"general_frame\", mg->frame,\n\t       \"frame number of image\", NULL);\n  h5_value_int(h5_file, group, \"general_band_count\", mg->band_count,\n\t       \"number of bands in image\", NULL);\n  h5_value_str(h5_file, group, \"general_bands\", mg->bands,\n\t       \"bands of the sensor\", NULL);\n  h5_value_int(h5_file, group, \"general_line_count\", mg->line_count,\n\t       \"number of lines in image\", NULL);\n  h5_value_int(h5_file, group, \"general_sample_count\", mg->sample_count, \n\t       \"number of samples in image\", NULL);\n  h5_value_int(h5_file, group, \"general_start_line\", mg->start_line,\n\t       \"first line relative to original image\", NULL);\n  h5_value_int(h5_file, group, \"general_start_sample\", mg->start_sample, \n\t       \"first sample relative to original image\", NULL);\n  h5_value_double(h5_file, group, \"general_x_pixel_size\", mg->x_pixel_size, \n\t\t  \"range pixel size\", \"m\");\n  h5_value_double(h5_file, group, \"general_y_pixel_size\", mg->y_pixel_size, \n\t\t  \"azimuth pixel size\", \"m\");\n  h5_value_double(h5_file, group, \"general_center_latitude\", \n\t\t  mg->center_latitude, \"approximate image center latitude\", \n\t\t  \"degrees_north\");\n  h5_value_double(h5_file, group, \"general_center_longitude\",\n\t\t  mg->center_longitude, \"approximate image center longitude\", \n\t\t  \"degrees_east\");\n  h5_value_double(h5_file, group, \"general_re_major\", mg->re_major,\n\t\t  \"major (equator) axis of earth\", \"m\");\n  h5_value_double(h5_file, group, \"general_re_minor\", mg->re_minor,\n\t\t  \"minor (polar) axis of earth\", \"m\");\n  h5_value_double(h5_file, group, \"general_bit_error_rate\", mg->bit_error_rate, \n\t\t  \"fraction of bits which are in error\", NULL);\n  h5_value_int(h5_file, group, \"general_missing_lines\", mg->missing_lines, \n\t       \"number of missing lines in image\", NULL);\n  h5_value_float(h5_file, group, \"general_no_data\", mg->no_data,\n\t\t \"value indicating no data for a pixel\", NULL);\n\n  if (ms) {\n    if (ms->image_type == 'S')\n      strcpy(str_attr, \"slant range\");\n    else if (ms->image_type == 'G')\n      strcpy(str_attr, \"ground range\");\n    else if (ms->image_type == 'P')\n      strcpy(str_attr, \"projected\");\n    else if (ms->image_type == 'R')\n      strcpy(str_attr, \"georeferenced\");\n    h5_value_str(h5_file, group, \"sar_image_type\", str_attr, \"image type\", \n\t\t NULL);\n    if (ms->look_direction == 'R')\n      strcpy(str_attr, \"right\");\n    else if (ms->look_direction == 'L')\n      strcpy(str_attr, \"left\");\n    h5_value_str(h5_file, group, \"sar_look_direction\", str_attr,\n\t\t \"SAR satellite look direction\", NULL);\n    h5_value_int(h5_file, group, \"sar_look_count\", ms->look_count,\n\t\t \"number of looks to take from SLC\", NULL);\n    h5_value_int(h5_file, group, \"sar_multilook\", ms->multilook,\n\t\t \"multilooking flag\", NULL);\n    h5_value_int(h5_file, group, \"sar_deskewed\", ms->deskewed,\n\t\t \"zero doppler deskew flag\", NULL);\n    h5_value_int(h5_file, group, \"sar_original_line_count\",\n\t\t ms->original_line_count, \"number of lines in original image\", \n\t\t NULL);\n    h5_value_int(h5_file, group, \"sar_original_sample_count\",\n\t\t ms->original_sample_count,\n\t\t \"number of samples in original image\", NULL);\n    h5_value_double(h5_file, group, \"sar_line_increment\", \n\t\t    ms->line_increment, \"line increment for sampling\", NULL);\n    h5_value_double(h5_file, group, \"sar_sample_increment\",\n\t\t    ms->sample_increment, \"sample increment for sampling\",\n\t\t    NULL);\n    h5_value_double(h5_file, group, \"sar_range_time_per_pixel\",\n\t\t    ms->range_time_per_pixel, \"time per pixel in range\", \"s\");\n    h5_value_double(h5_file, group, \"sar_azimuth_time_per_pixel\",\n\t\t    ms->azimuth_time_per_pixel, \"time per pixel in azimuth\", \n\t\t    \"s\");\n    h5_value_double(h5_file, group, \"sar_slant_range_first_pixel\",\n\t\t    ms->slant_range_first_pixel, \"slant range to first pixel\", \n\t\t    \"m\");\n    h5_value_double(h5_file, group, \"sar_slant_shift\", ms->slant_shift, \n\t\t    \"error correction factor in slant range\", \"m\");\n    h5_value_double(h5_file, group, \"sar_time_shift\", ms->time_shift, \n\t\t    \"error correction factor in time\", \"s\");\n    h5_value_double(h5_file, group, \"sar_wavelength\", ms->wavelength,\n\t\t    \"SAR carrier wavelength\", \"m\");\n    h5_value_double(h5_file, group, \"sar_pulse_repetition_frequency\", \n\t\t    ms->prf, \"pulse repetition frequency\", \"Hz\");\n    h5_value_double(h5_file, group, \"sar_earth_radius\", ms->earth_radius, \n\t\t    \"earth radius at image center\", \"m\");\n    h5_value_double(h5_file, group, \"sar_satellite_height\", \n\t\t    ms->satellite_height, \n\t\t    \"satellite height from earth's center\", \"m\");\n    h5_value_double(h5_file, group, \"sar_range_doppler_centroid\",\n\t\t    ms->range_doppler_coefficients[0], \"range doppler centroid\",\n\t\t    \"Hz\");\n    // FIXME: UDUNITS unit_description\n    h5_value_double(h5_file, group, \"sar_range_doppler_linear\",\n\t\t    ms->range_doppler_coefficients[1],\n\t\t    \"range doppler per range pixel\", \"Hz/pixel\");\n    // FIXME: UDUNITS unit description\n    h5_value_double(h5_file, group, \"sar_range_doppler_quadratic\",\n\t\t    ms->range_doppler_coefficients[2],\n\t\t    \"range doppler per range pixel square\", \"Hz/pixel^2\");\n    h5_value_double(h5_file, group, \"sar_azimuth_doppler_centroid\",\n\t\t    ms->azimuth_doppler_coefficients[0],\n\t\t    \"azimuth doppler centroid\", \"Hz\");\n    h5_value_double(h5_file, group, \"sar_azimuth_doppler_linear\",\n\t\t    ms->azimuth_doppler_coefficients[1],\n\t\t    \"azimuth doppler per azimuth pixel\", \"Hz/pixel\");\n    h5_value_double(h5_file, group, \"sar_azimuth_doppler_quadratic\",\n\t\t    ms->azimuth_doppler_coefficients[2],\n\t\t    \"azimuth doppler per azimuth pixel square\", \"Hz/pixel^2\");\n  }\n\n  if (mo) {\n    int vector_count = mo->vector_count;\n    h5_value_int(h5_file, group, \"orbit_year\", mo->year,\n\t\t \"year of image start\", NULL);\n    h5_value_int(h5_file, group, \"orbit_day_of_year\", mo->julDay, \n\t\t \"day of year at image start\", NULL);\n    h5_value_double(h5_file, group, \"orbit_second_of_day\", mo->second,\n\t\t    \"second of day at image start\", \"s\");\n    h5_value_int(h5_file, group, \"orbit_vector_count\", vector_count,\n\t\t \"number of state vectors\", NULL);\n    for (ii=0; ii<vector_count; ii++) {\n      sprintf(tmp, \"orbit_vector[%d]_time\", ii+1);\n      h5_value_double(h5_file, group, tmp, mo->vecs[ii].time,\n\t\t      \"time relative to image start\", \"s\");\n      sprintf(tmp, \"orbit_vector[%d]_position_x\", ii+1);\n      h5_value_double(h5_file, group, tmp, mo->vecs[ii].vec.pos.x,\n\t\t      \"x coordinate, earth-fixed\", \"m\");\n      sprintf(tmp, \"orbit_vector[%d]_position_y\", ii+1);\n      h5_value_double(h5_file, group, tmp, mo->vecs[ii].vec.pos.y,\n\t\t      \"y coordinate, earth-fixed\", \"m\");\n      sprintf(tmp, \"orbit_vector[%d]_position_z\", ii+1);\n      h5_value_double(h5_file, group, tmp, mo->vecs[ii].vec.pos.z,\n\t\t      \"z coordinate, earth-fixed\", \"m\");\n      sprintf(tmp, \"orbit_vector[%d]_velocity_x\", ii+1);\n      h5_value_double(h5_file, group, tmp, mo->vecs[ii].vec.vel.x,\n\t\t      \"x velocity, earth-fixed\", \"m/s\");\n      sprintf(tmp, \"orbit_vector[%d]_velocity_y\", ii+1);\n      h5_value_double(h5_file, group, tmp, mo->vecs[ii].vec.vel.y,\n\t\t      \"y velocity, earth-fixed\", \"m/s\");\n      sprintf(tmp, \"orbit_vector[%d]_velocity_z\", ii+1);\n      h5_value_double(h5_file, group, tmp, mo->vecs[ii].vec.vel.z,\n\t\t      \"z velocity, earth-fixed\", \"m/s\");\n    }\n  }\n  H5Gclose(h5_metagroup);\n  H5Sclose(h5_string);\n  H5Sclose(h5_array);\n\n  // Write ASF metadata to XML file\n  char *output_file = \n    (char *) MALLOC(sizeof(char)*(strlen(output_file_name)+5));\n  sprintf(output_file, \"%s.xml\", output_file_name);\n  meta_write_xml(md, output_file);\n  FREE(output_file);\n\n  return h5;\n}\n\nvoid finalize_h5_file(h5_t *hdf)\n{\n  H5Fclose(hdf->file);\n  \n  // Clean up\n  FREE(hdf->var);\n  FREE(hdf);\n}\n", "meta": {"hexsha": "7bce4dec757af3fe5a0f5630630c5f6c82f65c04", "size": 39780, "ext": "c", "lang": "C", "max_stars_repo_path": "src/libasf_export/export_hdf.c", "max_stars_repo_name": "glshort/MapReady", "max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z", "max_issues_repo_path": "src/libasf_export/export_hdf.c", "max_issues_repo_name": "glshort/MapReady", "max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libasf_export/export_hdf.c", "max_forks_repo_name": "glshort/MapReady", "max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z", "avg_line_length": 44.9491525424, "max_line_length": 510, "alphanum_fraction": 0.6793866264, "num_tokens": 13041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1968262036430985, "lm_q2_score": 0.020332352897435558, "lm_q1q2_score": 0.004001939831933995}}
{"text": "/*\n *   Copyright (c) 2007, Michael Lehn\n *\n *   All rights reserved.\n *\n *   Redistribution and use in source and binary forms, with or without\n *   modification, are permitted provided that the following conditions\n *   are met:\n *\n *   1) Redistributions of source code must retain the above copyright\n *      notice, this list of conditions and the following disclaimer.\n *   2) Redistributions in binary form must reproduce the above copyright\n *      notice, this list of conditions and the following disclaimer in\n *      the documentation and/or other materials provided with the\n *      distribution.\n *   3) Neither the name of the FLENS development group nor the names of\n *      its contributors may be used to endorse or promote products derived\n *      from this software without specific prior written permission.\n *\n *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n *   \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef FLENS_FLENS_H\n#define FLENS_FLENS_H 1\n\n#define ADDRESS(x) reinterpret_cast<const void *>(&x)\n\n#ifndef ASSERT\n#define ASSERT(x) assert(x)\n#endif //ASSERT\n\n#include <array.h>\n#include <bandstorage.h>\n#include <blas.h>\n#include <blas_flens.h>\n#include <cg.h>\n#include <complex_helper.h>\n#include <crs.h>\n#include <densevector.h>\n#include <evalclosure.h>\n#include <fullstorage.h>\n#include <generalmatrix.h>\n#include <generic_blas.h>\n#include <refcounter.h>\n#include <lapack.h>\n#include <lapack_flens.h>\n#include <listinitializer.h>\n#include <matvec.h>\n#include <matvecclosures.h>\n#include <matvecio.h>\n#include <matvecoperations.h>\n#include <multigrid.h>\n#include <packedstorage.h>\n#include <range.h>\n#include <snapshot.h>\n#include <storage.h>\n#include <sparsematrix.h>\n#include <sparse_blas.h>\n#include <sparse_blas_flens.h>\n#include <symmetricmatrix.h>\n#include <traits.h>\n#include <triangularmatrix.h>\n#include <underscore.h>\n#include <uplo.h>\n\n#endif // FLENS_FLENS_H\n", "meta": {"hexsha": "5a47a6c4655bb9fcb11624e840778c567ce07f02", "size": 2623, "ext": "h", "lang": "C", "max_stars_repo_path": "src/flens/flens.h", "max_stars_repo_name": "wmotte/toolkid", "max_stars_repo_head_hexsha": "2a8f82e1492c9efccde9a4935ce3019df1c68cde", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/flens/flens.h", "max_issues_repo_name": "wmotte/toolkid", "max_issues_repo_head_hexsha": "2a8f82e1492c9efccde9a4935ce3019df1c68cde", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/flens/flens.h", "max_forks_repo_name": "wmotte/toolkid", "max_forks_repo_head_hexsha": "2a8f82e1492c9efccde9a4935ce3019df1c68cde", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0649350649, "max_line_length": 75, "alphanum_fraction": 0.7426610751, "num_tokens": 610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1422318804661272, "lm_q2_score": 0.02800752253285321, "lm_q1q2_score": 0.003983562597045142}}
{"text": "#ifndef S3D_CV_IMAGE_OPERATION_INPUT_OUTPUT_ADAPTER_H\n#define S3D_CV_IMAGE_OPERATION_INPUT_OUTPUT_ADAPTER_H\n\n#include <s3d/multiview/stan_results.h>\n\n#include <opencv2/core/mat.hpp>\n\n#include <gsl/gsl>\n\nnamespace s3d {\nnamespace image_operation {\n\nclass ImageOperations;\n\nclass InputOutputAdapter {\npublic:\n  InputOutputAdapter(gsl::not_null<ImageOperations*> imageOperations);\n\n  void setInputImages(const cv::Mat& leftImage, const cv::Mat& rightImage);\n  std::tuple<cv::Mat&, cv::Mat&> getOutputImages();\n  bool applyAllOperations();\n  void copyInputToOutputs();\n  bool canApplyOperations();\n\n  StanResults results;\n\nprivate:\n  cv::Mat inputLeftImage{};\n  cv::Mat inputRightImage{};\n  cv::Mat outputLeftImage{};\n  cv::Mat outputRightImage{};\n\n  ImageOperations* operations_{};\n};\n\n} // namespace s3d\n} // namespace image_operation\n\n#endif // S3D_CV_IMAGE_OPERATION_INPUT_OUTPUT_ADAPTER_H\n", "meta": {"hexsha": "b597922c81546126c2e48227e6ae92ada3c75358", "size": 890, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/cv/include/s3d/cv/image_operation/input_output_adapter.h", "max_stars_repo_name": "hugbed/OpenS3D", "max_stars_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-16T16:38:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-20T03:23:15.000Z", "max_issues_repo_path": "src/core/cv/include/s3d/cv/image_operation/input_output_adapter.h", "max_issues_repo_name": "hugbed/OpenS3D", "max_issues_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 40.0, "max_issues_repo_issues_event_min_datetime": "2017-04-12T17:24:44.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-21T18:41:23.000Z", "max_forks_repo_path": "src/core/cv/include/s3d/cv/image_operation/input_output_adapter.h", "max_forks_repo_name": "hugbed/OpenS3D", "max_forks_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-07-13T21:51:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-18T16:22:03.000Z", "avg_line_length": 22.25, "max_line_length": 75, "alphanum_fraction": 0.7730337079, "num_tokens": 221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12940272487671914, "lm_q2_score": 0.03067580060296662, "lm_q1q2_score": 0.003969532185798785}}
{"text": "#pragma once\r\n#include <mylibs/container.hpp> // pl::Vector\r\n#include <initializer_list> // std::initializer_list\r\n#include \"FoodImpl.h\" // fa::FoodWithAmount\r\n#include \"NoteImpl.h\" // fa::NoteImpl\r\n#include \"PlanEntry.h\" // fa::PlanEntryDynamicDelegator\r\n#include \"Date.h\" // fa::Date\r\n#include \"GlobalHeader.h\" // fa::OStream\r\n#include <utility> // std::forward\r\n#include <mylibs/utility.hpp> // pl::forEachArgument\r\n#include <gsl.h> // gsl::not_null\r\n\r\nnamespace fa {\r\n    namespace daily_plan_detail {\r\n        template <class Type>\r\n        using Container = pl::Vector<Type>;\r\n    } // END of namespace daily_plan_detail\r\n\r\n    class DailyPlanImpl final {\r\n    public:\r\n        using this_type = DailyPlanImpl;\r\n        using DailyPlanFood = FoodWithAmount;\r\n        using DailyPlanNote = NoteImpl;\r\n        using Interface = PlanEntryInterface;\r\n        using FoodUniqueOwner = pl::PolymorphicUniqueOwner<Interface, PlanEntryDynamicDelegator>;\r\n        using NoteUniqueOwner = pl::PolymorphicUniqueOwner<Interface, PlanEntryDynamicDelegator>;\r\n        using FoodCont = daily_plan_detail::Container<FoodUniqueOwner>;\r\n        using NoteCont = daily_plan_detail::Container<NoteUniqueOwner>;\r\n\r\n        //! put FoodWithAmounts and NoteImpls in here.\r\n        template <class ...Args>\r\n        explicit DailyPlanImpl(Args &&...args) : date_{ Date::today() } {\r\n            pl::forEachArgument([this](auto &&e) {\r\n                                    initCont(std::forward<decltype(e)>(e));\r\n                                }, std::forward<Args>(args)...);\r\n        }\r\n\r\n        Date getDate() const;\r\n        void setDate(Date const &);\r\n        void setDate(Date &&);\r\n        NutrientTable getAllNutrients() const;\r\n        NutrientTable getMacroNutrients() const;\r\n        NutrientTable getMicroNutrients() const;\r\n        double getMacroPercentage() const;\r\n        double getMicroPercentage() const;\r\n        double getKcalPercentage() const;\r\n        double getOverallPercentage() const;\r\n        void addEntry(FoodWithAmount const &);\r\n        void addEntry(FoodWithAmount &&);\r\n        void addEntry(NoteImpl const &);\r\n        void addEntry(NoteImpl &&);\r\n\r\n        pl::View<FoodCont const> getFoods() const;\r\n        pl::View<FoodCont> getFoods();\r\n        pl::View<NoteCont const> getNotes() const;\r\n        pl::View<NoteCont> getNotes();\r\n        daily_plan_detail::Container<gsl::not_null<Interface const *>> getEntries() const;\r\n        daily_plan_detail::Container<gsl::not_null<Interface *>> getEntries();\r\n        daily_plan_detail::Container<gsl::not_null<DailyPlanFood *>> getFoodsDownCasted();\r\n        daily_plan_detail::Container<gsl::not_null<DailyPlanFood const *>> getFoodsDownCasted() const;\r\n        daily_plan_detail::Container<gsl::not_null<DailyPlanNote *>> getNotesDownCasted();\r\n        daily_plan_detail::Container<gsl::not_null<DailyPlanNote const *>> getNotesDownCasted() const;\r\n\r\n        friend OStream &operator<<(OStream &, this_type const &);\r\n\r\n    private:\r\n        void initCont(DailyPlanFood const &dpf);\r\n\r\n        void initCont(DailyPlanFood &&dpf);\r\n\r\n        void initCont(DailyPlanNote const &note);\r\n\r\n        void initCont(DailyPlanNote &&note);\r\n\r\n        NutrientTable getNutrients(FoodCont::const_iterator b,\r\n                                   FoodCont::const_iterator e,\r\n                                   NutrientTable accu) const;\r\n\r\n        FoodCont foodCont_;\r\n        NoteCont noteCont_;\r\n        Date date_;\r\n    }; // END of class DailyPlanImpl\r\n} // END of namespace fa\r\n", "meta": {"hexsha": "0aa8c4ef17c2037beccc95b902e40bcf7723bdcd", "size": 3538, "ext": "h", "lang": "C", "max_stars_repo_path": "Source/DailyPlanImpl.h", "max_stars_repo_name": "CppPhil/SE2P_FoodAssistant", "max_stars_repo_head_hexsha": "0ed9964fc0470f4ad9e7164af3da7be85c0caf68", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Source/DailyPlanImpl.h", "max_issues_repo_name": "CppPhil/SE2P_FoodAssistant", "max_issues_repo_head_hexsha": "0ed9964fc0470f4ad9e7164af3da7be85c0caf68", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/DailyPlanImpl.h", "max_forks_repo_name": "CppPhil/SE2P_FoodAssistant", "max_forks_repo_head_hexsha": "0ed9964fc0470f4ad9e7164af3da7be85c0caf68", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.119047619, "max_line_length": 103, "alphanum_fraction": 0.6365178067, "num_tokens": 803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1460872396128689, "lm_q2_score": 0.02716922868024295, "lm_q1q2_score": 0.003969077620307481}}
{"text": "#pragma once\n\n#include \"Library.h\"\n\n#include <gsl/span>\n\n#include <cstdint>\n#include <memory>\n#include <optional>\n#include <utility>\n#include <variant>\n#include <vector>\n\nnamespace CesiumGeometry {\n\nnamespace AvailabilityUtilities {\nuint8_t countOnesInByte(uint8_t _byte);\nuint32_t countOnesInBuffer(gsl::span<const std::byte> buffer);\n} // namespace AvailabilityUtilities\n\nstruct CESIUMGEOMETRY_API ConstantAvailability {\n  bool constant;\n};\n\nstruct CESIUMGEOMETRY_API SubtreeBufferView {\n  uint32_t byteOffset;\n  uint32_t byteLength;\n  uint8_t buffer;\n};\n\ntypedef std::variant<ConstantAvailability, SubtreeBufferView> AvailabilityView;\n\nstruct CESIUMGEOMETRY_API AvailabilitySubtree {\n  AvailabilityView tileAvailability;\n  AvailabilityView contentAvailability;\n  AvailabilityView subtreeAvailability;\n  std::vector<std::vector<std::byte>> buffers;\n};\n\n/**\n * @brief Availability nodes wrap subtree objects and link them together to\n * form a downwardly traversable availability tree.\n */\nstruct CESIUMGEOMETRY_API AvailabilityNode {\n  /**\n   * @brief The subtree data for this node.\n   *\n   * If a node exists but its subtree does not exist, it indicates that the\n   * subtree is known to be available and is actively in the process of loading.\n   */\n  std::optional<AvailabilitySubtree> subtree;\n\n  /**\n   * @brief The child nodes for this subtree node.\n   */\n  std::vector<std::unique_ptr<AvailabilityNode>> childNodes;\n\n  /**\n   * @brief Creates an empty instance;\n   */\n  AvailabilityNode() noexcept;\n\n  /**\n   * @brief Sets the loaded subtree for this availability node.\n   *\n   * @param subtree_ The loaded subtree to set for this node.\n   * @param maxChildrenSubtrees The maximum number of children this subtree\n   * could possible have if all of them happen to be available.\n   */\n  void setLoadedSubtree(\n      AvailabilitySubtree&& subtree_,\n      uint32_t maxChildrenSubtrees) noexcept;\n};\n\nstruct CESIUMGEOMETRY_API AvailabilityTree {\n  std::unique_ptr<AvailabilityNode> pRoot;\n};\n\nclass CESIUMGEOMETRY_API AvailabilityAccessor {\npublic:\n  AvailabilityAccessor(\n      const AvailabilityView& view,\n      const AvailabilitySubtree& subtree) noexcept;\n\n  bool isBufferView() const noexcept {\n    return pBufferView != nullptr && bufferAccessor;\n  }\n\n  bool isConstant() const noexcept { return pConstant != nullptr; }\n\n  /**\n   * @brief Unsafe if isConstant is false.\n   */\n  bool getConstant() const { return pConstant->constant; }\n\n  /**\n   * @brief Unsafe is isBufferView is false.\n   */\n  const gsl::span<const std::byte>& getBufferAccessor() const {\n    return *bufferAccessor;\n  }\n\n  /**\n   * @brief Unsafe if isBufferView is false.\n   */\n  const std::byte& operator[](size_t i) const {\n    return bufferAccessor.value()[i];\n  }\n\n  /**\n   * @brief Unsafe if isBufferView is false;\n   */\n  size_t size() const { return pBufferView->byteLength; }\n\nprivate:\n  const SubtreeBufferView* pBufferView;\n  const ConstantAvailability* pConstant;\n  std::optional<gsl::span<const std::byte>> bufferAccessor;\n};\n} // namespace CesiumGeometry\n", "meta": {"hexsha": "6c50591f99da15f876e886cf559141f9a60e1a2f", "size": 3048, "ext": "h", "lang": "C", "max_stars_repo_path": "CesiumGeometry/include/CesiumGeometry/Availability.h", "max_stars_repo_name": "yieryi/cesium-native", "max_stars_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 154.0, "max_stars_repo_stars_event_min_datetime": "2021-03-30T14:08:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T00:01:43.000Z", "max_issues_repo_path": "CesiumGeometry/include/CesiumGeometry/Availability.h", "max_issues_repo_name": "yieryi/cesium-native", "max_issues_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 256.0, "max_issues_repo_issues_event_min_datetime": "2021-03-30T18:12:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:44:21.000Z", "max_forks_repo_path": "CesiumGeometry/include/CesiumGeometry/Availability.h", "max_forks_repo_name": "yieryi/cesium-native", "max_forks_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 66.0, "max_forks_repo_forks_event_min_datetime": "2021-03-30T15:14:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T13:38:41.000Z", "avg_line_length": 25.1900826446, "max_line_length": 80, "alphanum_fraction": 0.7303149606, "num_tokens": 708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16238003666671083, "lm_q2_score": 0.024423091119239376, "lm_q1q2_score": 0.003965822431456509}}
{"text": "/*\n Copyright (C) 2002 M. Marques, A. Castro, A. Rubio, G. Bertsch\n\n This program is free software; you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2, or (at your option)\n any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n 02110-1301, USA.\n\n*/\n\n#ifndef _SYMBOLS_H\n#define _SYMBOLS_H\n\n#include <gsl/gsl_complex.h>\n#include \"liboct_parser.h\"\n\ntypedef enum{\n  S_CMPLX, S_STR, S_BLOCK, S_FNCT\n} symrec_type;\n\n/* Data type for links in the chain of symbols. */\ntypedef struct symrec{\n  char *name;                  /* name of symbol */\n  symrec_type type;            /* type of symbol: complex, string, block, or function */\n  int def;                     /* has this symbol been defined */\n  int used;                    /* this symbol has been used before */\n\n  int nargs;                   /* if type==S_FNCT contains the number of arguments of the function */\n\n  union {\n    gsl_complex c;             /* value of a S_CMPLX */\n    char *str;                 /* value of a S_STR */\n    sym_block *block;          /* to store blocks */\n    gsl_complex (*fnctptr)();  /* value of a S_FNCT */\n  } value;\n\n  struct symrec *next;         /* link field */\n} symrec;\n\n/* The symbol table: a chain of struct symrec. */\nextern symrec *sym_table;\nextern char *reserved_symbols[];\n\nsymrec *putsym (const char *sym_name, symrec_type sym_type);\nsymrec *getsym (const char *sym_name);\nint      rmsym (const char *sym_name);\n\nvoid sym_notdef(symrec *sym);\nvoid sym_redef(symrec *sym);\nvoid sym_wrong_arg(symrec *sym);\nvoid sym_init_table(void);\nvoid sym_end_table(void);\nvoid sym_output_table(int only_unused, int mpiv_node);\nvoid str_tolower(char *in);\nvoid sym_mark_table_used();\nvoid sym_print(FILE *f, const symrec *ptr);\n\n#endif\n", "meta": {"hexsha": "26ba3cf7b81311208d36a75d0f26dfcb1e03b950", "size": 2223, "ext": "h", "lang": "C", "max_stars_repo_path": "liboct_parser/symbols.h", "max_stars_repo_name": "shunsuke-sato/octopus", "max_stars_repo_head_hexsha": "dcf68a185cdb13708395546b1557ca46aed969f6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-11-17T09:03:11.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-17T06:31:08.000Z", "max_issues_repo_path": "liboct_parser/symbols.h", "max_issues_repo_name": "shunsuke-sato/octopus", "max_issues_repo_head_hexsha": "dcf68a185cdb13708395546b1557ca46aed969f6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-08-11T19:14:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-11T19:14:06.000Z", "max_forks_repo_path": "liboct_parser/symbols.h", "max_forks_repo_name": "shunsuke-sato/octopus", "max_forks_repo_head_hexsha": "dcf68a185cdb13708395546b1557ca46aed969f6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-11-22T20:30:46.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-29T23:24:51.000Z", "avg_line_length": 32.2173913043, "max_line_length": 101, "alphanum_fraction": 0.6842105263, "num_tokens": 551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2068940488158881, "lm_q2_score": 0.01912403587738714, "lm_q1q2_score": 0.0039566492123729305}}
{"text": "/*\n Copyright (C) 2002 M. Marques, A. Castro, A. Rubio, G. Bertsch\n\n This program is free software; you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2, or (at your option)\n any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n 02110-1301, USA.\n\n $Id$\n*/\n\n#ifndef _LIB_OCT_H\n#define _LIB_OCT_H\n\n#include <gsl/gsl_complex.h>\n\nint         parse_init   (char *file_out, int *mpiv_node);\nint         parse_input  (char *file_in);\nvoid        parse_end    (void);\n\nint         parse_isdef  (char *name);\nint         parse_int    (char *name, int def);\ndouble      parse_double (char *name, double def);\ngsl_complex parse_complex(char *name, gsl_complex def);\nchar       *parse_string (char *name, char *def);\n\n/* Now comes stuff for the blocks */\ntypedef struct sym_block_line{\n  int n;\n  char **fields;\n} sym_block_line;\n\ntypedef struct sym_block{\n  int n;\n  sym_block_line *lines;\n} sym_block;\n\nint parse_block        (char *name, sym_block **blk);\nint parse_block_end    (sym_block **blk);\nint parse_block_n      (sym_block *blk);\nint parse_block_cols   (sym_block *blk, int l);\nint parse_block_int    (sym_block *blk, int l, int col, int *r);\nint parse_block_double (sym_block *blk, int l, int col, double *r);\nint parse_block_complex(sym_block *blk, int l, int col, gsl_complex *r);\nint parse_block_string (sym_block *blk, int l, int col, char **r);\n\n/* from parse_exp.c */\nenum pr_type {PR_NONE,PR_CMPLX, PR_STR};\ntypedef struct parse_result{\n  union {\n    gsl_complex c;\n    char *s;\n  } value;\n  enum pr_type type;\n} parse_result;\n\nvoid parse_result_free(parse_result *t);\n\nint parse_exp(char *exp, parse_result *t);\n\nvoid parse_putsym_int(char *s, int i);\nvoid parse_putsym_double(char *s, double d);\nvoid parse_putsym_complex(char *s, gsl_complex c);\n\n#endif\n", "meta": {"hexsha": "caedf842cb2bd14e3a55b845a4e85cc0add74ce4", "size": 2265, "ext": "h", "lang": "C", "max_stars_repo_path": "liboct_parser/liboct_parser.h", "max_stars_repo_name": "neelravi/octopus", "max_stars_repo_head_hexsha": "25cb84cf590276af9ce4617039ba3849e328594c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "liboct_parser/liboct_parser.h", "max_issues_repo_name": "neelravi/octopus", "max_issues_repo_head_hexsha": "25cb84cf590276af9ce4617039ba3849e328594c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "liboct_parser/liboct_parser.h", "max_forks_repo_name": "neelravi/octopus", "max_forks_repo_head_hexsha": "25cb84cf590276af9ce4617039ba3849e328594c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8026315789, "max_line_length": 72, "alphanum_fraction": 0.719205298, "num_tokens": 590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2365162472088944, "lm_q2_score": 0.016657039673626202, "lm_q1q2_score": 0.003939660513215737}}
{"text": "\n#pragma once\n\n#include <sstream>\n#include <gsl/string_span>\n\n/*\n\tString tokenizer that works like the ToEE vanilla one.\n*/\nclass Tokenizer {\npublic:\n\n\texplicit Tokenizer(const std::string &input) : mIn(input) {\n\t}\n\t\n\tbool NextToken();\n\n\tbool IsQuotedString() const {\n\t\treturn mTokenType == TokenType::QuotedString;\n\t}\n\n\tbool IsNumber() const {\n\t\treturn mTokenType == TokenType::Number;\n\t}\n\n\tbool IsIdentifier() const {\n\t\treturn mTokenType == TokenType::Identifier;\n\t}\n\n\tbool IsIdentifier(const char *identifier) const;\n\n\tconst std::string &GetTokenText() const {\n\t\treturn mTokenText;\n\t}\n\n\tconst bool& GetEnableEscapes() const {\n\t\treturn mEnableEscapes;\n\t}\n\n\tvoid SetEnableEscapes(bool enableEscapes) {\n\t\tmEnableEscapes = enableEscapes;\n\t}\n\n\tint GetTokenInt() const {\n\t\treturn mTokenInt;\n\t}\n\n\tfloat GetTokenFloat() const {\n\t\treturn (float) mTokenFloat;\n\t}\n\nprivate:\n\tenum class TokenType {\n\t\tNumber,\n\t\tQuotedString,\n\t\tIdentifier,\n\t\tUnknown\n\t};\n\n\tstd::istringstream mIn;\n\tstd::string mTokenText;\n\tTokenType mTokenType = TokenType::Unknown;\n\tdouble mTokenFloat = 0;\n\tint mTokenInt = 0;\n\n\tstd::string mLine; // Buffer for current line\n\tsize_t mLinePos; // Current position within mLine\n\tint mLineNo = 0;\n\tbool mEnableEscapes = true;\n\n\tbool GetLine();\n\tbool LineHasMoreChars() const;\n\n\tbool ReadNumber();\n\tbool ReadQuotedString();\n\tbool ReadIdentifier();\n\n\t// Character based reading on the input source\n\tchar PeekChar();\n\tvoid SkipChar();\n\tchar TakeChar();\n\tvoid UngetChar();\n\n\t// Seeks past any control or space characters at current line pos\n\tvoid SkipSpaceAndControl();\n\t// Skips past comment at current line pos to end of line\n\tvoid SkipComment();\n};\n\n\n", "meta": {"hexsha": "f86d7ed5fe45785f1ef9a51ea01dae7344a1e284", "size": 1654, "ext": "h", "lang": "C", "max_stars_repo_path": "Infrastructure/include/infrastructure/tokenizer.h", "max_stars_repo_name": "edoipi/TemplePlus", "max_stars_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 69.0, "max_stars_repo_stars_event_min_datetime": "2015-05-05T14:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T06:13:04.000Z", "max_issues_repo_path": "Infrastructure/include/infrastructure/tokenizer.h", "max_issues_repo_name": "edoipi/TemplePlus", "max_issues_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 457.0, "max_issues_repo_issues_event_min_datetime": "2015-05-01T22:07:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T02:19:10.000Z", "max_forks_repo_path": "Infrastructure/include/infrastructure/tokenizer.h", "max_forks_repo_name": "edoipi/TemplePlus", "max_forks_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2016-02-04T21:19:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T23:14:51.000Z", "avg_line_length": 18.1758241758, "max_line_length": 66, "alphanum_fraction": 0.7188633615, "num_tokens": 415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14033626387172932, "lm_q2_score": 0.028007522938509034, "lm_q1q2_score": 0.003930471129492115}}
{"text": "#ifndef COMUTILS_H\r\n#define    COMUTILS_H\r\n\r\n#include \"HypCommands.h\" // RECORD_LENGTH\r\n\r\n#include <gsl/gsl-lite.hpp> // gsl::span\r\n\r\n#include <array>\r\n#include <functional>\r\n#include <memory>\r\n#include <stdint.h>\r\n#include <string>\r\n#include <vector>\r\n\r\n#include <QObject>\r\n#include <QString>\r\nQT_USE_NAMESPACE\r\n\r\nclass SerialPort;\r\n\r\n#define val const auto\r\n\r\n//------------------------------------------------------------------------------\r\nclass DeviceLink : public QObject\r\n{\r\n    Q_OBJECT\r\n\r\n    DeviceLink()                              = delete;\r\n    DeviceLink            (const DeviceLink&) = delete;\r\n    DeviceLink& operator =(const DeviceLink&) = delete;\r\n\r\npublic:\r\n    //enum class DeviceType {\r\n    //    UNKNOWN = 0,\r\n    //    LDU, RDU, MDU,\r\n    //    NUM_TYPES // the last\r\n    //};\r\n\r\n    typedef std::function<void(const QString&)>            MsgToDisplayCbk;\r\n    typedef std::function<void(const gsl::span<uint8_t>&)> PacketRecvdCbk;\r\n    typedef std::function<void()>                          SeriesEndCbk;\r\n    typedef std::function<void(bool)>                      FinishedCbk;\r\n\r\n    DeviceLink(MsgToDisplayCbk msgCbk, PacketRecvdCbk packetCbk, \r\n               SeriesEndCbk seriesEndCbk, FinishedCbk finishCbk);\r\n\r\n    void DownloadRecorded(); // returns packets via PacketRecvdCbk\r\n    void ClearRecordings();\r\n    void UploadToDevice(const std::vector<uint8_t>& data);\r\n\r\n    Hyperion::DeviceType GetDeviceType() const { return m_deviceType;  }\r\n    int GetFirmwareVersionX100() const { return m_firmwareVersionX100; }\r\n\r\nprivate:\r\n    void DownloadThreadFn();\r\n    void ClearThreadFn();\r\n    void UploadThreadFn();\r\n\r\n    std::unique_ptr<SerialPort> EstablishConnection(size_t& port_idx, uint8_t& handshakeReply);\r\n\r\n    void SendMessage  (const QString& msg) const { if (m_messageCbk)     m_messageCbk(msg); }\r\n    void ReceivePacket(const gsl::span<uint8_t>& p)const { if (m_packetRecvdCbk) m_packetRecvdCbk(p); }\r\n    void SendFinished (bool ok)            const { if (m_finishCbk)      m_finishCbk(ok); }\r\n\r\n    typedef std::vector<uint8_t> dataVec_t;\r\n\r\n    template<size_t N> static bool ChecksumOk(const std::array<uint8_t, N>& data) {\r\n        size_t sum = 0;\r\n        for (size_t i=0;  i+1 < N;  sum += data[i++]);\r\n        return ((sum & 0xFF) == data[N - 1]);\r\n    }\r\n\r\n//data:\r\n    MsgToDisplayCbk m_messageCbk;\r\n    PacketRecvdCbk  m_packetRecvdCbk; \r\n    SeriesEndCbk    m_seriesEndCbk;\r\n    FinishedCbk     m_finishCbk;\r\n\r\n    std::vector<QString> m_portNames;\r\n\r\n    Hyperion::DeviceType m_deviceType = Hyperion::UNKNOWN_DEVICE;\r\n    int m_firmwareVersionX100 = 0; // unknown\r\n\r\n//statics const:\r\n    static const std::array<uint8_t,2> HANDSHAKE;            // \"DZ\"\r\n    static const std::array<uint8_t,2> START_DOWNLOAD;       // \"DK\"\r\n    static const std::array<uint8_t,1> CONTINUE_DOWNLOAD;    // 0x01\r\n    static const std::array<uint8_t,2> CLEAR_VALUES;         // \"DE\" - not sure what it does...\r\n    static const std::array<uint8_t,2> CLEAR_MEMORY;         // \"DB\" \r\n    static const std::array<uint8_t,2> GET_FW_VERSION; // \"DV\" \r\n\r\n    static const std::array<uint8_t,5> HANDSHAKE_REPLY;\r\n};\r\n//------------------------------------------------------------------------------\r\n\r\n#endif // COMUTILS_H\r\n", "meta": {"hexsha": "586e83225298149d5207160f3a757e5a8fa688fe", "size": 3257, "ext": "h", "lang": "C", "max_stars_repo_path": "src/ComUtils.h", "max_stars_repo_name": "bsergeev/HyperionEmeter2", "max_stars_repo_head_hexsha": "105124530364cdf9f625a03046b5edba140c9114", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-01T08:01:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-01T08:01:08.000Z", "max_issues_repo_path": "src/ComUtils.h", "max_issues_repo_name": "bsergeev/HyperionEmeter2", "max_issues_repo_head_hexsha": "105124530364cdf9f625a03046b5edba140c9114", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ComUtils.h", "max_forks_repo_name": "bsergeev/HyperionEmeter2", "max_forks_repo_head_hexsha": "105124530364cdf9f625a03046b5edba140c9114", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5773195876, "max_line_length": 104, "alphanum_fraction": 0.6027018729, "num_tokens": 825, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11124119766818044, "lm_q2_score": 0.03514484880093841, "lm_q1q2_score": 0.003909555072483504}}
{"text": "/* vector/gsl_vector_uint.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_VECTOR_UINT_H__\n#define __GSL_VECTOR_UINT_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_block_uint.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size;\n  size_t stride;\n  unsigned int *data;\n  gsl_block_uint *block;\n  int owner;\n} \ngsl_vector_uint;\n\ntypedef struct\n{\n  gsl_vector_uint vector;\n} _gsl_vector_uint_view;\n\ntypedef _gsl_vector_uint_view gsl_vector_uint_view;\n\ntypedef struct\n{\n  gsl_vector_uint vector;\n} _gsl_vector_uint_const_view;\n\ntypedef const _gsl_vector_uint_const_view gsl_vector_uint_const_view;\n\n\n/* Allocation */\n\nGSL_EXPORT gsl_vector_uint *gsl_vector_uint_alloc (const size_t n);\nGSL_EXPORT gsl_vector_uint *gsl_vector_uint_calloc (const size_t n);\n\nGSL_EXPORT gsl_vector_uint *gsl_vector_uint_alloc_from_block (gsl_block_uint * b,\n                                                                const size_t offset,\n                                                                const size_t n,\n                                                                const size_t stride);\n\nGSL_EXPORT gsl_vector_uint *gsl_vector_uint_alloc_from_vector (gsl_vector_uint * v,\n                                                                 const size_t offset,\n                                                                 const size_t n,\n                                                                 const size_t stride);\n\nGSL_EXPORT void gsl_vector_uint_free (gsl_vector_uint * v);\n\n/* Views */\n\nGSL_EXPORT\n_gsl_vector_uint_view\ngsl_vector_uint_view_array (unsigned int *v, size_t n);\n\nGSL_EXPORT\n_gsl_vector_uint_view\ngsl_vector_uint_view_array_with_stride (unsigned int *base,\n                                         size_t stride,\n                                         size_t n);\n\nGSL_EXPORT\n_gsl_vector_uint_const_view\ngsl_vector_uint_const_view_array (const unsigned int *v, size_t n);\n\nGSL_EXPORT\n_gsl_vector_uint_const_view\ngsl_vector_uint_const_view_array_with_stride (const unsigned int *base,\n                                               size_t stride,\n                                               size_t n);\n\nGSL_EXPORT\n_gsl_vector_uint_view\ngsl_vector_uint_subvector (gsl_vector_uint *v,\n                            size_t i,\n                            size_t n);\n\nGSL_EXPORT\n_gsl_vector_uint_view\ngsl_vector_uint_subvector_with_stride (gsl_vector_uint *v,\n                                        size_t i,\n                                        size_t stride,\n                                        size_t n);\n\nGSL_EXPORT\n_gsl_vector_uint_const_view\ngsl_vector_uint_const_subvector (const gsl_vector_uint *v,\n                                  size_t i,\n                                  size_t n);\n\nGSL_EXPORT\n_gsl_vector_uint_const_view\ngsl_vector_uint_const_subvector_with_stride (const gsl_vector_uint *v,\n                                              size_t i,\n                                              size_t stride,\n                                              size_t n);\n\n/* Operations */\n\nGSL_EXPORT unsigned int gsl_vector_uint_get (const gsl_vector_uint * v, const size_t i);\nGSL_EXPORT void gsl_vector_uint_set (gsl_vector_uint * v, const size_t i, unsigned int x);\n\nGSL_EXPORT unsigned int *gsl_vector_uint_ptr (gsl_vector_uint * v, const size_t i);\nGSL_EXPORT const unsigned int *gsl_vector_uint_const_ptr (const gsl_vector_uint * v, const size_t i);\n\nGSL_EXPORT void gsl_vector_uint_set_zero (gsl_vector_uint * v);\nGSL_EXPORT void gsl_vector_uint_set_all (gsl_vector_uint * v, unsigned int x);\nGSL_EXPORT int gsl_vector_uint_set_basis (gsl_vector_uint * v, size_t i);\n\nGSL_EXPORT int gsl_vector_uint_fread (FILE * stream, gsl_vector_uint * v);\nGSL_EXPORT int gsl_vector_uint_fwrite (FILE * stream, const gsl_vector_uint * v);\nGSL_EXPORT int gsl_vector_uint_fscanf (FILE * stream, gsl_vector_uint * v);\nGSL_EXPORT int gsl_vector_uint_fprintf (FILE * stream, const gsl_vector_uint * v,\n                                         const char *format);\n\nGSL_EXPORT int gsl_vector_uint_memcpy (gsl_vector_uint * dest, const gsl_vector_uint * src);\n\nGSL_EXPORT int gsl_vector_uint_reverse (gsl_vector_uint * v);\n\nGSL_EXPORT int gsl_vector_uint_swap (gsl_vector_uint * v, gsl_vector_uint * w);\nGSL_EXPORT int gsl_vector_uint_swap_elements (gsl_vector_uint * v, const size_t i, const size_t j);\n\nGSL_EXPORT unsigned int gsl_vector_uint_max (const gsl_vector_uint * v);\nGSL_EXPORT unsigned int gsl_vector_uint_min (const gsl_vector_uint * v);\nGSL_EXPORT void gsl_vector_uint_minmax (const gsl_vector_uint * v, unsigned int * min_out, unsigned int * max_out);\n\nGSL_EXPORT size_t gsl_vector_uint_max_index (const gsl_vector_uint * v);\nGSL_EXPORT size_t gsl_vector_uint_min_index (const gsl_vector_uint * v);\nGSL_EXPORT void gsl_vector_uint_minmax_index (const gsl_vector_uint * v, size_t * imin, size_t * imax);\n\nGSL_EXPORT int gsl_vector_uint_add (gsl_vector_uint * a, const gsl_vector_uint * b);\nGSL_EXPORT int gsl_vector_uint_sub (gsl_vector_uint * a, const gsl_vector_uint * b);\nGSL_EXPORT int gsl_vector_uint_mul (gsl_vector_uint * a, const gsl_vector_uint * b);\nGSL_EXPORT int gsl_vector_uint_div (gsl_vector_uint * a, const gsl_vector_uint * b);\nGSL_EXPORT int gsl_vector_uint_scale (gsl_vector_uint * a, const double x);\nGSL_EXPORT int gsl_vector_uint_add_constant (gsl_vector_uint * a, const double x);\n\nGSL_EXPORT int gsl_vector_uint_isnull (const gsl_vector_uint * v);\n\n#ifdef HAVE_INLINE\n\nextern inline\nunsigned int\ngsl_vector_uint_get (const gsl_vector_uint * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_VAL (\"index out of range\", GSL_EINVAL, 0);\n    }\n#endif\n  return v->data[i * v->stride];\n}\n\nextern inline\nvoid\ngsl_vector_uint_set (gsl_vector_uint * v, const size_t i, unsigned int x)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_VOID (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  v->data[i * v->stride] = x;\n}\n\nextern inline\nunsigned int *\ngsl_vector_uint_ptr (gsl_vector_uint * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return (unsigned int *) (v->data + i * v->stride);\n}\n\nextern inline\nconst unsigned int *\ngsl_vector_uint_const_ptr (const gsl_vector_uint * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return (const unsigned int *) (v->data + i * v->stride);\n}\n\n\n#endif /* HAVE_INLINE */\n\n__END_DECLS\n\n#endif /* __GSL_VECTOR_UINT_H__ */\n\n\n", "meta": {"hexsha": "cd4e7d3d3927b21388972379df85786c6742e806", "size": 7602, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/gsl/include/gsl/gsl_vector_uint.h", "max_stars_repo_name": "dynaryu/vaws", "max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/gsl/include/gsl/gsl_vector_uint.h", "max_issues_repo_name": "dynaryu/vaws", "max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/gsl/include/gsl/gsl_vector_uint.h", "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3489361702, "max_line_length": 115, "alphanum_fraction": 0.6792949224, "num_tokens": 1787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20434189024594807, "lm_q2_score": 0.01912403654124848, "lm_q1q2_score": 0.003907841775971297}}
{"text": "static char help[] = \"Broker for DYNHELICS\\n\";\n\n#include <stdio.h>\n#include <unistd.h>\n#include <helics.h>\n#include <petsc.h>\n\nint main(int argc,char **argv)\n{\n  helics_broker broker;\n  const char*   helicsversion;\n  int            isconnected;\n  char           initstring[PETSC_MAX_PATH_LEN];\n  PetscInt       nfederates=0;\n  PetscErrorCode ierr;\n\n  PetscInitialize(&argc,&argv,\"petscopt\",help);\n\n  helicsversion = helicsGetVersion();\n\n  printf(\"BROKER: Helics version = %s\\n\",helicsversion);\n  printf(\"%s\",help);\n\n  ierr = PetscOptionsGetInt(NULL,NULL,\"-nfeds\",&nfederates,NULL);CHKERRQ(ierr);\n  if(!nfederates) {\n    SETERRQ(PETSC_COMM_SELF,0,\"Number of federates need to be given with option -nfeds\");\n  }\n  ierr = PetscSNPrintf(initstring,PETSC_MAX_PATH_LEN-1,\"%d\",nfederates);\n  ierr = PetscStrcat(initstring,\" --name=mainbroker\");\n\n\n  /* Create broker */\n  broker = helicsCreateBroker(\"zmq\",\"\",initstring);\n\n  isconnected = helicsBrokerIsConnected(broker);\n\n  if(isconnected) {\n    printf(\"BROKER: Created and connected\\n\");\n  }\n\n  while(helicsBrokerIsConnected(broker)) {\n    usleep(1000); /* Sleep for 1 millisecond */\n  }\n  printf(\"BROKER: disconnected\\n\");\n  helicsBrokerFree(broker);\n  helicsCloseLibrary();\n\n  printf(\"Helics library closed\\n\");\n  PetscFinalize();\n  return 0;\n}\n\n", "meta": {"hexsha": "d6940b2bc7d1eed59dc92a46f6b8ce3674692668", "size": 1292, "ext": "c", "lang": "C", "max_stars_repo_path": "ANL-TD-Iterative-Pflow/helics-broker.c", "max_stars_repo_name": "GMLC-TDC/Use-Cases", "max_stars_repo_head_hexsha": "14d687fe04af731c1ee466e05acfd5813095660a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-04T07:27:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-04T07:27:34.000Z", "max_issues_repo_path": "ANL-TD-Iterative-Pflow/helics-broker.c", "max_issues_repo_name": "GMLC-TDC/Use-Cases", "max_issues_repo_head_hexsha": "14d687fe04af731c1ee466e05acfd5813095660a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ANL-TD-Iterative-Pflow/helics-broker.c", "max_forks_repo_name": "GMLC-TDC/Use-Cases", "max_forks_repo_head_hexsha": "14d687fe04af731c1ee466e05acfd5813095660a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-01T21:49:40.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-23T19:30:36.000Z", "avg_line_length": 24.3773584906, "max_line_length": 89, "alphanum_fraction": 0.6911764706, "num_tokens": 361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.13296424019782926, "lm_q2_score": 0.02931223138733097, "lm_q1q2_score": 0.0038974785749194252}}
{"text": "#ifndef __GSL_VECTOR_H__\r\n#define __GSL_VECTOR_H__\r\n\r\n#if !defined( GSL_FUN )\r\n#  if !defined( GSL_DLL )\r\n#    define GSL_FUN extern\r\n#  elif defined( BUILD_GSL_DLL )\r\n#    define GSL_FUN extern __declspec(dllexport)\r\n#  else\r\n#    define GSL_FUN extern __declspec(dllimport)\r\n#  endif\r\n#endif\r\n\r\n#include <gsl/gsl_vector_complex_long_double.h>\r\n#include <gsl/gsl_vector_complex_double.h>\r\n#include <gsl/gsl_vector_complex_float.h>\r\n\r\n#include <gsl/gsl_vector_long_double.h>\r\n#include <gsl/gsl_vector_double.h>\r\n#include <gsl/gsl_vector_float.h>\r\n\r\n#include <gsl/gsl_vector_ulong.h>\r\n#include <gsl/gsl_vector_long.h>\r\n\r\n#include <gsl/gsl_vector_uint.h>\r\n#include <gsl/gsl_vector_int.h>\r\n\r\n#include <gsl/gsl_vector_ushort.h>\r\n#include <gsl/gsl_vector_short.h>\r\n\r\n#include <gsl/gsl_vector_uchar.h>\r\n#include <gsl/gsl_vector_char.h>\r\n\r\n\r\n#endif /* __GSL_VECTOR_H__ */\r\n", "meta": {"hexsha": "a6a361469e15439b283ff1c79d32114eb963f8db", "size": 866, "ext": "h", "lang": "C", "max_stars_repo_path": "deps/include/gsl/gsl_vector.h", "max_stars_repo_name": "berkus/music-cs", "max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z", "max_issues_repo_path": "deps/include/gsl/gsl_vector.h", "max_issues_repo_name": "berkus/music-cs", "max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z", "max_forks_repo_path": "deps/include/gsl/gsl_vector.h", "max_forks_repo_name": "berkus/music-cs", "max_forks_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 24.0555555556, "max_line_length": 49, "alphanum_fraction": 0.7413394919, "num_tokens": 236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14223190228178134, "lm_q2_score": 0.027169233209558687, "lm_q1q2_score": 0.0038643317229328797}}
{"text": "#pragma once\n\n#include <array>\n\n#include <gsl/span>\n\n#include \"Joystick.h\"\n#include \"JoystickAxis.h\"\n#include \"JoystickButton.h\"\n#include \"JoystickProvider.h\"\n\nnamespace qvr\n{\n\nclass SfmlJoystick : public Joystick\n{\npublic:\n\tstruct ButtonState {\n\t\tbool isDown = false;\n\t\tbool wasDown = false;\n\t};\n\n\tstruct AxisState {\n\t\tfloat position = 0.0f;\n\t\tfloat previousPosition = 0.0f;\n\t};\n\nprivate:\n\tconst int m_Index;\n\t\n\tint m_ButtonCount;\n\tint m_AxisCount;\n\n\tbool m_IsConnected  = false;\n\tbool m_WasConnected = false;\n\n\t// Copied from sf::Joystick\n\tenum\n\t{\n\t\tButtonCount = 32, ///< Maximum number of supported buttons\n\t\tAxisCount = 8     ///< Maximum number of supported axes\n\t};\n\n\tstd::array<ButtonState, ButtonCount> m_Buttons;\n\tstd::array<AxisState,   AxisCount>   m_Axes;\n\n\tbool JustConnected() const {\n\t\treturn m_IsConnected && !m_WasConnected;\n\t}\n\tbool JustDisconnected() const {\n\t\treturn m_WasConnected && !m_IsConnected;\n\t}\n\n\tvoid UpdateButtons();\n\tvoid UpdateAxes();\n\npublic:\n\tSfmlJoystick(const int index) : m_Index(index) {}\n\n\tvoid Update();\n\n\tbool IsConnected() const {\n\t\treturn m_IsConnected;\n\t}\n\n\tbool IsDown(const JoystickButton button) const override {\n\t\treturn m_Buttons[button.GetValue()].isDown;\n\t}\n\tbool JustDown(const JoystickButton button) const override {\n\t\treturn m_Buttons[button.GetValue()].isDown && !m_Buttons[button.GetValue()].wasDown;\n\t}\n\tbool JustUp(const JoystickButton button) const override {\n\t\treturn m_Buttons[button.GetValue()].wasDown && !m_Buttons[button.GetValue()].isDown;\n\t}\n\t\n\tfloat GetPosition(const JoystickAxis axis) const override {\n\t\treturn m_Axes[(int)axis].position;\n\t}\n\tfloat GetPreviousPosition(const JoystickAxis axis) const override {\n\t\treturn m_Axes[(int)axis].previousPosition;\n\t}\n\n\tconst gsl::span<const ButtonState> GetButtons() const {\n\t\treturn gsl::make_span(m_Buttons.data(), m_ButtonCount);\n\t}\n\n\tconst gsl::span<const AxisState> GetAxes() const {\n\t\treturn gsl::make_span(m_Axes);\n\t}\n\n\tint GetButtonCount() const {\n\t\treturn m_ButtonCount;\n\t}\n\n\tint GetAxisCount() const {\n\t\treturn m_AxisCount;\n\t}\n};\n\nclass SfmlJoystickSet : public JoystickProvider\n{\npublic:\n\t// Worst constructor ever.\n\tSfmlJoystickSet()\n\t\t: m_Joysticks({ 0, 1, 2, 3, 4, 5, 6, 7 })\n\t{}\n\n\tvoid Update();\n\n\tconst Joystick* GetJoystick(const JoystickIndex index) const override {\n\t\tif (m_Joysticks[index.Get()].IsConnected()) {\n\t\t\treturn &m_Joysticks[index.Get()];\n\t\t}\n\t\treturn nullptr;\n\t}\n\n\tstatic const int Count = 8; // The maximum number of supported joysticks.\n\nprivate:\n\tstd::array<SfmlJoystick, Count> m_Joysticks;\n};\n\nvoid LogSfmlJoystickInfo(const int index);\n\n}\n", "meta": {"hexsha": "8bff486bd8a8337db4b99bfc3b18099bf3d17a9c", "size": 2591, "ext": "h", "lang": "C", "max_stars_repo_path": "External/Quiver/Source/Quiver/Quiver/Input/SfmlJoystick.h", "max_stars_repo_name": "rachelnertia/Quarrel", "max_stars_repo_head_hexsha": "69616179fc71305757549c7fcaccc22707a91ba4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 39.0, "max_stars_repo_stars_event_min_datetime": "2017-10-22T15:47:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-31T22:19:55.000Z", "max_issues_repo_path": "External/Quiver/Source/Quiver/Quiver/Input/SfmlJoystick.h", "max_issues_repo_name": "rachelnertia/Quarrel", "max_issues_repo_head_hexsha": "69616179fc71305757549c7fcaccc22707a91ba4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2017-10-26T21:21:51.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-13T14:46:17.000Z", "max_forks_repo_path": "Source/Quiver/Quiver/Input/SfmlJoystick.h", "max_forks_repo_name": "rachelnertia/Quiver", "max_forks_repo_head_hexsha": "c8ef9591117bdfc8d6fa509ae53451e0807f5686", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-10-22T14:47:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-19T10:08:45.000Z", "avg_line_length": 20.5634920635, "max_line_length": 86, "alphanum_fraction": 0.7197993053, "num_tokens": 708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21733752104706247, "lm_q2_score": 0.017712302268222273, "lm_q1q2_score": 0.0038495478670116908}}
{"text": "/**\n * @file coroutine/linux.h\n * @author github.com/luncliff (luncliff@gmail.com)\n * @copyright CC BY 4.0\n */\n#ifndef COROUTINE_SYSTEM_WRAPPER_H\n#define COROUTINE_SYSTEM_WRAPPER_H\n#if !(defined(__linux__))\n#error \"expect Linux platform for this file\"\n#endif\n#include <sys/epoll.h> // for Linux epoll\n\n#include <coroutine/return.h>\n#include <gsl/gsl>\n\n/**\n * @defgroup Linux\n */\n\nnamespace coro {\n\n/**\n * @brief RAII wrapping for epoll file descriptor\n * @ingroup Linux\n */\nclass epoll_owner final {\n    int64_t epfd;\n\n  public:\n    /**\n     * @brief create a fd with `epoll`. Throw if the function fails.\n     * @see kqeueue\n     * @throw system_error\n     */\n    epoll_owner() noexcept(false);\n    /**\n     * @brief close the current epoll file descriptor\n     */\n    ~epoll_owner() noexcept;\n    epoll_owner(const epoll_owner&) = delete;\n    epoll_owner(epoll_owner&&) = delete;\n    epoll_owner& operator=(const epoll_owner&) = delete;\n    epoll_owner& operator=(epoll_owner&&) = delete;\n\n  public:\n    /**\n     * @brief bind the fd to epoll\n     * @param fd\n     * @param req \n     * @see epoll_ctl\n     * @throw system_error\n     */\n    void try_add(uint64_t fd, epoll_event& req) noexcept(false);\n\n    /**\n     * @brief unbind the fd to epoll\n     * @param fd \n     * @see epoll_ctl\n     */\n    void remove(uint64_t fd);\n\n    /**\n     * @brief fetch all events for the given kqeueue descriptor\n     * @param wait_ms millisecond to wait\n     * @param list \n     * @return ptrdiff_t \n     * @see epoll_wait\n     * @throw system_error\n     * \n     * Timeout is not an error for this function\n     */\n    ptrdiff_t wait(uint32_t wait_ms,\n                   gsl::span<epoll_event> list) noexcept(false);\n\n  public:\n    /**\n     * @brief return temporary awaitable object for given event\n     * @param req input for `change` operation \n     * @see change\n     * \n     * There is no guarantee of reusage of returned awaiter object\n     * When it is awaited, and `req.udata` is null(0),\n     * the value is set to `coroutine_handle<void>`\n     * \n     * ```cpp\n     * auto edge_in_async(epoll_owner& ep, int64_t fd) -> frame_t {\n     *     epoll_event req{};\n     *     req.events = EPOLLET | EPOLLIN | EPOLLONESHOT;\n     *     req.data.ptr = nullptr;\n     *     co_await ep.submit(fd, req);\n     * }\n     * ```\n     */\n    [[nodiscard]] auto submit(int64_t fd, epoll_event& req) noexcept {\n        class awaiter final : public suspend_always {\n            epoll_owner& ep;\n            int64_t fd;\n            epoll_event& req;\n\n          public:\n            constexpr awaiter(epoll_owner& _ep, int64_t _fd, epoll_event& _req)\n                : ep{_ep}, fd{_fd}, req{_req} {\n            }\n\n          public:\n            void await_suspend(coroutine_handle<void> coro) noexcept(false) {\n                if (req.data.ptr == nullptr)\n                    req.data.ptr = coro.address();\n                return ep.try_add(fd, req);\n            }\n        };\n        return awaiter{*this, fd, req};\n    }\n};\n\n/**\n * @brief RAII + stateful `eventfd`\n * @see https://github.com/grpc/grpc/blob/master/src/core/lib/iomgr/is_epollexclusive_available.cc\n * @ingroup Linux\n * \n * If the object is signaled(`set`), \n * the bound `epoll_owner` will yield suspended coroutine through `epoll_event`'s user data.\n * \n * Its object can be `co_await`ed multiple times\n */\nclass event final {\n    uint64_t state;\n\n  public:\n    event() noexcept(false);\n    ~event() noexcept;\n    event(const event&) = delete;\n    event(event&&) = delete;\n    event& operator=(const event&) = delete;\n    event& operator=(event&&) = delete;\n\n    uint64_t fd() const noexcept;\n    bool is_set() const noexcept;\n    void set() noexcept(false);\n    void reset() noexcept(false);\n};\n\n/**\n * @brief Bind the given `event`(`eventfd`) to `epoll_owner`(Epoll)\n * \n * @param ep  epoll_owner\n * @param efd event\n * @see event\n * @return awaitable struct for the binding\n * @ingroup Linux\n */\nauto wait_in(epoll_owner& ep, event& efd) {\n    class awaiter : epoll_event {\n        epoll_owner& ep;\n        event& efd;\n\n      public:\n        /**\n         * @brief Prepares one-time registration\n         */\n        awaiter(epoll_owner& _ep, event& _efd) noexcept\n            : epoll_event{}, ep{_ep}, efd{_efd} {\n            this->events = EPOLLET | EPOLLIN | EPOLLONESHOT;\n        }\n\n        bool await_ready() const noexcept {\n            return efd.is_set();\n        }\n        /**\n         * @brief Wait for `write` to given `eventfd`\n         */\n        void await_suspend(coroutine_handle<void> coro) noexcept(false) {\n            this->data.ptr = coro.address();\n            return ep.try_add(efd.fd(), *this);\n        }\n        /**\n         * @brief Reset the given event object when resumed\n         */\n        void await_resume() noexcept {\n            return efd.reset();\n        }\n    };\n    return awaiter{ep, efd};\n}\n\n} // namespace coro\n\n#endif // COROUTINE_SYSTEM_WRAPPER_H\n", "meta": {"hexsha": "b6b45fe249e33da7d1117ca53ffb13db9a5b1af4", "size": 4933, "ext": "h", "lang": "C", "max_stars_repo_path": "interface/coroutine/linux.h", "max_stars_repo_name": "lanza/coroutine", "max_stars_repo_head_hexsha": "c90caab988f96997f5bc1bd6f1958b80524fa14a", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 368.0, "max_stars_repo_stars_event_min_datetime": "2018-11-22T22:57:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T04:04:54.000Z", "max_issues_repo_path": "interface/coroutine/linux.h", "max_issues_repo_name": "lanza/coroutine", "max_issues_repo_head_hexsha": "c90caab988f96997f5bc1bd6f1958b80524fa14a", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 35.0, "max_issues_repo_issues_event_min_datetime": "2018-11-09T04:38:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-27T01:10:02.000Z", "max_forks_repo_path": "interface/coroutine/linux.h", "max_forks_repo_name": "lanza/coroutine", "max_forks_repo_head_hexsha": "c90caab988f96997f5bc1bd6f1958b80524fa14a", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 29.0, "max_forks_repo_forks_event_min_datetime": "2018-12-26T14:03:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T17:36:55.000Z", "avg_line_length": 26.1005291005, "max_line_length": 98, "alphanum_fraction": 0.5911210217, "num_tokens": 1265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09009300373428242, "lm_q2_score": 0.04272220166002823, "lm_q1q2_score": 0.00384897147369369}}
{"text": "#pragma once\n\n#include \"Core/Pointers.h\"\n#include \"Graphics/GraphicsResource.h\"\n#include \"Graphics/TextureInfo.h\"\n\n#include <glad/gl.h>\n#include <gsl/span>\n\n#include <vector>\n\nclass Texture;\nstruct Viewport;\n\nnamespace Fb\n{\n   enum class DepthStencilType\n   {\n      None,\n      Depth24Stencil8,\n      Depth32FStencil8\n   };\n\n   enum class Target\n   {\n      Framebuffer = GL_FRAMEBUFFER,\n      ReadFramebuffer = GL_READ_FRAMEBUFFER,\n      DrawFramebuffer = GL_DRAW_FRAMEBUFFER\n   };\n\n   enum class CubeFace\n   {\n      Front,\n      Back,\n      Top,\n      Bottom,\n      Left,\n      Right\n   };\n\n   struct Specification\n   {\n      GLsizei width = 0;\n      GLsizei height = 0;\n\n      GLsizei samples = 0;\n      bool cubeMap = false;\n\n      DepthStencilType depthStencilType = DepthStencilType::Depth24Stencil8;\n\n      gsl::span<const Tex::InternalFormat> colorAttachmentFormats;\n\n      bool operator==(const Specification& other) const;\n   };\n\n   struct Attachments\n   {\n      SPtr<Texture> depthStencilAttachment;\n      std::vector<SPtr<Texture>> colorAttachments;\n   };\n\n   Attachments generateAttachments(const Specification& specification);\n}\n\nnamespace std\n{\n   template<>\n   struct hash<Fb::Specification>\n   {\n      size_t operator()(const Fb::Specification& specification) const;\n   };\n}\n\nclass Framebuffer : public GraphicsResource\n{\npublic:\n   Framebuffer();\n   Framebuffer(const Framebuffer& other) = delete;\n   Framebuffer(Framebuffer&& other);\n   ~Framebuffer();\n   Framebuffer& operator=(const Framebuffer& other) = delete;\n   Framebuffer& operator=(Framebuffer&& other);\n\nprivate:\n   void move(Framebuffer&& other);\n   void release();\n\npublic:\n   using SpecificationType = Fb::Specification;\n   static SPtr<Framebuffer> create(const Fb::Specification& specification);\n   static const char* labelSuffix();\n\n   static void blit(Framebuffer& source, Framebuffer& destination, GLenum readBuffer, GLenum drawBuffer, GLbitfield mask, GLenum filter);\n   static void bindDefault(Fb::Target target = Fb::Target::Framebuffer);\n\n   void bind(Fb::Target target = Fb::Target::Framebuffer);\n   bool isBound(Fb::Target target = Fb::Target::Framebuffer) const;\n\n   const Fb::Attachments& getAttachments() const\n   {\n      return attachments;\n   }\n\n   const SPtr<Texture>& getDepthStencilAttachment() const;\n   SPtr<Texture> getColorAttachment(int index) const;\n\n   void setAttachments(Fb::Attachments newAttachments);\n\n   bool getViewport(Viewport& viewport) const;\n\n   bool isCubeMap() const;\n   void setActiveFace(Fb::CubeFace face);\n\nprivate:\n   const SPtr<Texture>* getFirstValidAttachment() const;\n\n   Fb::Attachments attachments;\n};\n", "meta": {"hexsha": "fb48ddaf9a3810252df957a26429542158156e72", "size": 2633, "ext": "h", "lang": "C", "max_stars_repo_path": "Source/Graphics/Framebuffer.h", "max_stars_repo_name": "aaronmjacobs/Swap", "max_stars_repo_head_hexsha": "955f36bc95b6829bf1a1a89b430df7816c065ac0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Source/Graphics/Framebuffer.h", "max_issues_repo_name": "aaronmjacobs/Swap", "max_issues_repo_head_hexsha": "955f36bc95b6829bf1a1a89b430df7816c065ac0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/Graphics/Framebuffer.h", "max_forks_repo_name": "aaronmjacobs/Swap", "max_forks_repo_head_hexsha": "955f36bc95b6829bf1a1a89b430df7816c065ac0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.1260504202, "max_line_length": 137, "alphanum_fraction": 0.6984428409, "num_tokens": 603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16238002855971875, "lm_q2_score": 0.02368947259176783, "lm_q1q2_score": 0.0038466972360159347}}
{"text": "#ifndef SIGSCANNERMEMORYDATA_HHHHH\n#define SIGSCANNERMEMORYDATA_HHHHH\n\n#include <vector>\n#include <gsl/span>\n#include <string>\n\nnamespace MPSig {\n    class SigScannerMemoryData {\n        gsl::span<const char> m_refData;\n    public:\n        explicit SigScannerMemoryData(gsl::span<const char> data);\n\n        bool IsInRange(std::intptr_t addr) const;\n        char* Deref(std::intptr_t addrWithOffset) const;\n        std::pair<char*, bool> DerefTry(std::intptr_t addrWithOffset) const;\n\n        gsl::span<const char> Get() const;\n        std::intptr_t GetOffset() const;\n    };\n}\n\n\n\n#endif\n", "meta": {"hexsha": "ef846bc9b7561a6bd6b8adae976cca330e98b1be", "size": 588, "ext": "h", "lang": "C", "max_stars_repo_path": "src/SigScannerMemoryData.h", "max_stars_repo_name": "KevinW1998/MultipassSigScanner", "max_stars_repo_head_hexsha": "13f290ec593ddbeed3c59c7fba642c1704bfd529", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SigScannerMemoryData.h", "max_issues_repo_name": "KevinW1998/MultipassSigScanner", "max_issues_repo_head_hexsha": "13f290ec593ddbeed3c59c7fba642c1704bfd529", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SigScannerMemoryData.h", "max_forks_repo_name": "KevinW1998/MultipassSigScanner", "max_forks_repo_head_hexsha": "13f290ec593ddbeed3c59c7fba642c1704bfd529", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.6153846154, "max_line_length": 76, "alphanum_fraction": 0.6819727891, "num_tokens": 148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.09138210801622944, "lm_q2_score": 0.04208772626352764, "lm_q1q2_score": 0.0038460651475711797}}
{"text": "/*\n *  Copyright (C) 2021 FISCO BCOS.\n *  SPDX-License-Identifier: Apache-2.0\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n * @brief interface for TransactionReceipt\n * @file TransactionReceipt.h\n */\n#pragma once\n\n#include \"ProtocolTypeDef.h\"\n#include <bcos-crypto/interfaces/crypto/CryptoSuite.h>\n#include <bcos-utilities/FixedBytes.h>\n#include <gsl/span>\n\nnamespace bcos\n{\nnamespace protocol\n{\nclass LogEntry;\nclass TransactionReceipt\n{\npublic:\n    using Ptr = std::shared_ptr<TransactionReceipt>;\n    using ConstPtr = std::shared_ptr<const TransactionReceipt>;\n    explicit TransactionReceipt(bcos::crypto::CryptoSuite::Ptr _cryptoSuite)\n      : m_cryptoSuite(_cryptoSuite)\n    {}\n\n    virtual ~TransactionReceipt() {}\n\n    virtual void decode(bytesConstRef _receiptData) = 0;\n    virtual void encode(bytes& _encodedData) const = 0;\n    virtual bytesConstRef encode(bool _onlyHashFieldData = false) const = 0;\n\n    virtual bcos::crypto::HashType hash() const\n    {\n        auto hashFields = encode(true);\n        return m_cryptoSuite->hash(hashFields);\n    }\n\n    virtual int32_t version() const = 0;\n    virtual u256 gasUsed() const = 0;  // TODO: remove from hash\n    virtual std::string_view contractAddress() const = 0;\n    virtual int32_t status() const = 0;\n    virtual bytesConstRef output() const = 0;\n    virtual gsl::span<const LogEntry> logEntries() const = 0;\n    virtual bcos::crypto::CryptoSuite::Ptr cryptoSuite() { return m_cryptoSuite; }\n    virtual BlockNumber blockNumber() const = 0;\n\n    // additional information on transaction execution, no need to be involved in the hash\n    // calculation\n    virtual std::string const& message() const = 0;\n    virtual void setMessage(std::string const& _message) = 0;\n    virtual void setMessage(std::string&& _message) = 0;\n\nprotected:\n    bcos::crypto::CryptoSuite::Ptr m_cryptoSuite;\n};\nusing Receipts = std::vector<TransactionReceipt::Ptr>;\nusing ReceiptsPtr = std::shared_ptr<Receipts>;\nusing ReceiptsConstPtr = std::shared_ptr<const Receipts>;\n}  // namespace protocol\n}  // namespace bcos\n", "meta": {"hexsha": "0dff070058180172ac6f8f79ade67d8db3d2c2e2", "size": 2579, "ext": "h", "lang": "C", "max_stars_repo_path": "bcos-framework/interfaces/protocol/TransactionReceipt.h", "max_stars_repo_name": "contropist/FISCO-BCOS", "max_stars_repo_head_hexsha": "1605c371448b410674559bb1c9e98bab722f036b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bcos-framework/interfaces/protocol/TransactionReceipt.h", "max_issues_repo_name": "contropist/FISCO-BCOS", "max_issues_repo_head_hexsha": "1605c371448b410674559bb1c9e98bab722f036b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bcos-framework/interfaces/protocol/TransactionReceipt.h", "max_forks_repo_name": "contropist/FISCO-BCOS", "max_forks_repo_head_hexsha": "1605c371448b410674559bb1c9e98bab722f036b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3866666667, "max_line_length": 90, "alphanum_fraction": 0.7223730128, "num_tokens": 629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.17781086512112404, "lm_q2_score": 0.021615334220130417, "lm_q1q2_score": 0.0038434412775636266}}
{"text": "#ifndef buildin_40bf10d0_ba81_4f06_accf_8020d3698607_h\r\n#define buildin_40bf10d0_ba81_4f06_accf_8020d3698607_h\r\n\r\n#include <gslib\\type.h>\r\n#include <gslib\\string.h>\r\n#include <rathen\\config.h>\r\n\r\n__rathen_begin__\r\n\r\n#define max_opr 4\r\n\r\nstruct oprnode\r\n{\r\n    int     prior;\r\n    gchar   opr[max_opr];\r\n    bool    unary;\r\n};\r\n\r\nstruct oprinfo\r\n{\r\n    string      opr;\r\n    bool        unary;\r\n\r\n    oprinfo(const gchar* o, bool u): opr(o), unary(u) {}\r\n    oprinfo(const string& s, bool u): opr(s), unary(u) {}\r\n};\r\n\r\nstruct unary_oprinfo:\r\n    public oprinfo\r\n{\r\n    unary_oprinfo(const gchar* o): oprinfo(o, true) {}\r\n    unary_oprinfo(const string& s): oprinfo(s, true) {}\r\n};\r\n\r\nstruct binary_oprinfo:\r\n    public oprinfo\r\n{\r\n    binary_oprinfo(const gchar* o): oprinfo(o, false) {}\r\n    binary_oprinfo(const string& s): oprinfo(s, false) {}\r\n};\r\n\r\nclass opr_manager\r\n{\r\npublic:\r\n    /*\r\n     * the operators:\r\n       ( )\r\n       ++ --\r\n       - ! ~\r\n       += -= *= /= %=\r\n       * / %\r\n       + -\r\n       << >>\r\n       < > <= >= == !=\r\n       & | ^ && ||\r\n       =\r\n     */\r\n    static const oprnode opr_list[];\r\n\r\nprivate:\r\n    opr_manager() {}\r\n\r\npublic:\r\n    static opr_manager* get_singleton_ptr()\r\n    {\r\n        static opr_manager inst;\r\n        return &inst;\r\n    }\r\n    const oprnode* get_unary_operator(const gchar* src) const;\r\n    const oprnode* get_binary_operator(const gchar* src) const;\r\n    const oprnode* get_unary_operator(const string& src) const { return get_unary_operator(src.c_str()); }\r\n    const oprnode* get_binary_operator(const string& src) const { return get_binary_operator(src.c_str()); }\r\n    const oprnode* get_operator(const oprinfo& info) const\r\n    {\r\n        return info.unary ? get_unary_operator(info.opr) :\r\n            get_binary_operator(info.opr);\r\n    }\r\n\r\n    /*\r\n     * Currently, only priority '1' was unary.\r\n     * pass the 'opr' to this function, in case of any proper changes in the future.\r\n     */\r\n    bool is_unary(int prior, const gchar* opr) const { return prior == 1; }\r\n    bool is_unary(int prior, const string& opr) const { return prior == 1; }\r\n};\r\n\r\n#define _opr_manager    opr_manager::get_singleton_ptr()\r\n\r\n#define max_key 8\r\n\r\nstruct key_node\r\n{\r\n    int     pattern;\r\n    gchar   key[max_key];\r\n};\r\n\r\nclass key_manager\r\n{\r\npublic:\r\n    static const key_node key_list[];\r\n    enum\r\n    {\r\n        /*\r\n         * Respectively like:\r\n         * stop;\r\n         * exit(...);\r\n         * else {...}\r\n         * if(...) {...}\r\n         */\r\n        pat_err     = 0x00,\r\n        pat_raw     = 0x01,\r\n        pat_arg     = 0x02,\r\n        pat_seg     = 0x04,\r\n        pat_com     = 0x08,\r\n    };\r\n\r\nprivate:\r\n    key_manager() {}\r\n\r\npublic:\r\n    static key_manager* get_singleton_ptr()\r\n    {\r\n        static key_manager inst;\r\n        return &inst;\r\n    }\r\n    const key_node* get_key(const gchar* src) const;\r\n    const key_node* get_key(const string& src) const { return get_key(src.c_str()); }\r\n    int get_key_pattern(const gchar* src) const;\r\n    int get_key_pattern(const string& src) const { return get_key_pattern(src.c_str()); }\r\n};\r\n\r\n#define _key_manager    key_manager::get_singleton_ptr()\r\n\r\n__rathen_end__\r\n\r\n#endif", "meta": {"hexsha": "c930316f919f4b28efd023aa53cc441a47d69755", "size": 3195, "ext": "h", "lang": "C", "max_stars_repo_path": "include/rathen/buildin.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/rathen/buildin.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/rathen/buildin.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 23.4926470588, "max_line_length": 109, "alphanum_fraction": 0.579029734, "num_tokens": 835, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19193276795852135, "lm_q2_score": 0.02002344216664951, "lm_q1q2_score": 0.0038431546791024124}}
{"text": "#include \"asf.h\"\n#include \"asf_meta.h\"\n#include \"dateUtil.h\"\n\n#include <assert.h>\n\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_multiroots.h>\n\n\nstatic FILE *fopen_workreport_ext(const char *fileName, report_level_t level)\n{\n  char *path = getPath(fileName);\n  char *basename = get_basename(fileName);\n  char *txtFile = MALLOC(sizeof(char) * (strlen(path)+strlen(fileName)+20));\n  \n  char *p;\n  if (strncmp_case(basename, \"LED-\", 4)==0)\n    p = basename + 4;\n  else\n    p = basename;\n\n  if (strlen(path) > 0)\n    sprintf(txtFile, \"%s/%s\", path, p);\n  else\n    strcpy(txtFile, p);\n\n  char *workreport_filename = appendExt(txtFile, \".txt\");\n\n  // first attempt: basename.txt\n  FILE *fp;\n  if (!fileExists(workreport_filename)) {\n    // second attempt: path/'workreport'\n    FREE(workreport_filename);\n    workreport_filename = MALLOC(sizeof(char) * (strlen(path) + 20));\n\n    if (strlen(path) > 0)\n      sprintf(workreport_filename, \"%s/workreport\", path);\n    else\n      strcpy(workreport_filename, \"workreport\");\n\n    if (!fileExists(workreport_filename)) {\n\n      // third attempt: path/'summary.txt'\n      if (strlen(path) > 0)\n        sprintf(workreport_filename, \"%s/summary.txt\", path);\n      else\n        strcpy(workreport_filename, \"summary.txt\");\n\n      if (!fileExists(workreport_filename)) {\n        // failed!\n        fp = NULL;\n      }\n      else {\n        // success with 'summary.txt'\n        asfReport(level, \"workreport file found as: summary.txt\\n\");\n        fp = FOPEN(workreport_filename, \"r\");\n      }\n    }\n    else {\n      // success with 'workreport'\n      asfReport(level, \"workreport file found as: workreport\\n\");\n      fp = FOPEN(workreport_filename, \"r\");\n    }\n  }\n  else {\n    // success with 'basename.txt'\n    char *basename = get_basename(workreport_filename);\n    asfReport(level, \"workreport file found as: %s\\n\", basename);\n    fp = FOPEN(workreport_filename, \"r\");\n    FREE(basename);\n  }\n\n  FREE(workreport_filename);\n  FREE(txtFile);\n  FREE(path);\n  FREE(basename);\n\n  return fp;\n}\n\nFILE *fopen_workreport(const char *fileName)\n{\n  return fopen_workreport_ext(fileName, REPORT_LEVEL_STATUS);\n}\n\n// Get the delta image time for ALOS data out of the summary file\nint get_alos_delta_time (const char *fileName, double *delta)\n{\n  struct dataset_sum_rec dssr;\n  hms_time dssr_time, summary_time, start_time, end_time;\n  ymd_date dssr_date, summary_date, start_date, end_date;\n  char line[512], dateStr[30], *str;\n\n  get_dssr(fileName, &dssr);\n  date_dssr2date(dssr.inp_sctim, &dssr_date, &dssr_time);\n\n  FILE *fp = fopen_workreport(fileName);\n  if (!fp) {\n    // no workreport file...\n    *delta = 0;\n    return FALSE;\n  }\n\n  while (fgets(line, 512, fp)) {\n    if (strstr(line, \"Img_SceneCenterDateTime\")) {\n      str = strchr(line, '\"');\n      sprintf(dateStr, \"%s\", str+1);\n      dateStr[strlen(dateStr)-2] = '\\0';\n      date_alos2date(dateStr, &summary_date, &summary_time);\n      // bumped up the tolerance to 2 seconds... can't see how this would\n      // introduce any false positives, and definitely reduces false negatives\n      if (date_difference(&dssr_date, &dssr_time,\n          &summary_date, &summary_time) > 2.0)\n      {\n        asfPrintWarning(\"Summary file does not correspond to leader file.\\n\"\n                        \"DSSR: %s\\nSummary: %s\\n\",\n                        dssr.inp_sctim, dateStr);\n        *delta = 0;\n        FCLOSE(fp);\n        return FALSE;\n      }\n    }\n    else if (strstr(line, \"Img_SceneStartDateTime\")) {\n      str = strchr(line, '\"');\n      sprintf(dateStr, \"%s\", str+1);\n      dateStr[strlen(dateStr)-2] = '\\0';\n      date_alos2date(dateStr, &start_date, &start_time);\n    }\n    else if (strstr(line, \"Img_SceneEndDateTime\")) {\n      str = strchr(line, '\"');\n      sprintf(dateStr, \"%s\", str+1);\n      dateStr[strlen(dateStr)-2] = '\\0';\n      date_alos2date(dateStr, &end_date, &end_time);\n    }\n  }\n\n  *delta = date_difference(&start_date, &start_time, &end_date, &end_time);\n  FCLOSE(fp);\n  return TRUE;\n}\n\n// Get the SAR processor version from the workreport\nint get_alos_processor_version (const char *fileName, double *version)\n{\n  char line[512], versionStr[10], *str;\n\n  FILE *fp = fopen_workreport_ext(fileName, REPORT_LEVEL_NONE);\n  if (!fp) {\n    // no workreport file...\n    *version = 0.0;\n    return FALSE;\n  }\n\n  while (fgets(line, 512, fp)) {\n    if (strstr(line, \"Ver_PSR_CorPrcSigmaSAR\")) {\n      str = strchr(line, '\"');\n      sprintf(versionStr, \"%s\", str+1);\n      versionStr[strlen(versionStr)-2] = '\\0';\n      *version = atof(versionStr);\n    }\n  }\n\n  FCLOSE(fp);\n  return TRUE;\n}\n\n\n// ------------------------------------------------------------------------\n// helper code for refine_slc_geolocation_from_workreport()\n\nstruct refine_shift_params {\n    meta_parameters *meta;\n    double center_lat, center_lon;\n    double ul_lat, ul_lon;\n    double ur_lat, ur_lon;\n    double ll_lat, ll_lon;\n    double lr_lat, lr_lon;\n};\n\nstatic double lldist(double lat1, double lat2, double lon1, double lon2)\n{\n    double dlat = lat1 - lat2;\n    double dlon;\n\n    // some kludgery to handle crossing the meridian\n    // get lat1,lon1 to be on the same side as lat2,lon2\n    if (fabs(lon1-lon2) > 300) {\n        if (lon2 < 0 && lon1 > 0) lon1 -= 360;\n        if (lon2 > 0 && lon1 < 0) lon1 += 360;\n    }\n    \n    dlon = lon1 - lon2;\n    \n    // Scale longitude difference to take into accound the fact\n    // that longitude lines are a lot closer at the pole.\n    dlon *= cos (lat2 * PI / 180.0);\n\n    return dlat * dlat + dlon * dlon;\n}\n\nstatic double err_at_pixel(struct refine_shift_params *p, double off_t,\n                           double off_x, double line, double samp,\n                           double real_lat, double real_lon)\n{\n    const double huge_err = 999999.9;\n\n    meta_parameters *meta = p->meta;\n    double lat, lon;\n    int bad=0;\n\n    bad = meta_get_latLon(meta, line, samp, 0.0, &lat, &lon);\n    if (bad) return huge_err;\n\n    return lldist(lat, real_lat, lon, real_lon);\n}\n\nstatic int\ngetObjective(const gsl_vector *x, void *params, gsl_vector *f)\n{\n    double dt = gsl_vector_get(x,0);\n    double ds = gsl_vector_get(x,1);\n\n    if (!meta_is_valid_double(ds) || !meta_is_valid_double(dt)) {\n        // This does happen sometimes, when we've already found the root\n\treturn GSL_FAILURE;\n    }\n\n    struct refine_shift_params *p = (struct refine_shift_params *)params;\n    meta_parameters *meta = p->meta;\n\n    int nl = meta->general->line_count;\n    int ns = meta->general->sample_count;\n\n    double saved_timeOffset = meta->sar->time_shift;\n    double saved_slant = meta->sar->slant_shift;\n    meta->sar->time_shift += dt;\n    meta->sar->slant_shift += ds;\n\n    double err = 0.0;\n\n    // add up the errors for the 5 known points\n    err += err_at_pixel(p, dt, ds, nl/2, ns/2, p->center_lat, p->center_lon); \n\n    if (meta->general->orbit_direction=='A') {\n      err += err_at_pixel(p, dt, ds, 0,    0,    p->ll_lat, p->ll_lon);\n      err += err_at_pixel(p, dt, ds, nl-1, 0,    p->ul_lat, p->ul_lon);\n      err += err_at_pixel(p, dt, ds, 0,    ns-1, p->lr_lat, p->lr_lon);\n      err += err_at_pixel(p, dt, ds, nl-1, ns-1, p->ur_lat, p->ur_lon);\n    }\n    else {\n      err += err_at_pixel(p, dt, ds, 0,    0,    p->ul_lat, p->ur_lon);\n      err += err_at_pixel(p, dt, ds, nl-1, 0,    p->ll_lat, p->lr_lon);\n      err += err_at_pixel(p, dt, ds, 0,    ns-1, p->ur_lat, p->ul_lon);\n      err += err_at_pixel(p, dt, ds, nl-1, ns-1, p->lr_lat, p->ll_lon);\n    }\n    \n    meta->sar->time_shift = saved_timeOffset;\n    meta->sar->slant_shift = saved_slant;\n\n    gsl_vector_set(f,0,err);\n    gsl_vector_set(f,1,err);\n    return GSL_SUCCESS;\n}\n\nstatic void coarse_search(double t_extent_min, double t_extent_max,\n                          double s_extent_min, double s_extent_max,\n                          double *t_min, double *s_min,\n                          struct refine_shift_params *params)\n{\n    double the_min = 9999999;\n    double min_t=99, min_s=99;\n    int i,j,k=6;\n    double t_extent = t_extent_max - t_extent_min;\n    double s_extent = s_extent_max - s_extent_min;\n    gsl_vector *v = gsl_vector_alloc(2);\n    gsl_vector *u = gsl_vector_alloc(2);\n    //printf(\"           \");\n    //for (j = 0; j <= k; ++j) {\n    //    double s = s_extent_min + ((double)j)/k*s_extent;\n    //    printf(\"%9.3f \", s);\n    //}\n    //printf(\"\\n           \");\n    //for (j = 0; j <= k; ++j)\n    //    printf(\"--------- \");\n    //printf(\"\\n\");\n    for (i = 0; i <= k; ++i) {\n        double t = t_extent_min + ((double)i)/k*t_extent;\n        //printf(\"%9.3f | \", t);\n\n        for (j = 0; j <= k; ++j) {\n            double s = s_extent_min + ((double)j)/k*s_extent;\n\n            gsl_vector_set(v, 0, t);\n            gsl_vector_set(v, 1, s);\n            getObjective(v,(void*)params, u);\n            double n = gsl_vector_get(u,0);\n            //printf(\"%9.3f \", n);\n            if (n<the_min) { \n                the_min=n;\n                min_t=gsl_vector_get(v,0);\n                min_s=gsl_vector_get(v,1);\n            }\n        }\n        //printf(\"\\n\");\n    }\n\n    *t_min = min_t;\n    *s_min = min_s;\n\n    gsl_vector_free(v);\n    gsl_vector_free(u);\n}\n\n/* this one can be used to do a time-only search (no slant adjustment)\nstatic void coarse_search_t(double t_extent_min, double t_extent_max,\n                            double *t_min, struct refine_shift_params *params)\n{\n    double the_min = 9999999;\n    double min_t=99;\n    int i,k=10;\n    double t_extent = t_extent_max - t_extent_min;\n    gsl_vector *v = gsl_vector_alloc(2);\n    gsl_vector *u = gsl_vector_alloc(2);\n    for (i = 0; i <= k; ++i) {\n        double t = t_extent_min + ((double)i)/k*t_extent;\n\n        gsl_vector_set(v, 0, t);\n        gsl_vector_set(v, 1, 0);\n        getObjective(v,(void*)params, u);\n        double n = gsl_vector_get(u,0);\n        if (n<the_min) { \n            the_min=n;\n            min_t=gsl_vector_get(v,0);\n        }\n    }\n\n    *t_min = min_t;\n\n    gsl_vector_free(v);\n    gsl_vector_free(u);\n}\n*/\n\nstatic void generate_start(struct refine_shift_params *params,\n                           double *start_t, double *start_s)\n{\n    int i;\n\n    double extent_t_min = -20;\n    double extent_t_max = 20;\n\n    double extent_s_min = -5000;\n    double extent_s_max = 5000;\n\n    double t_range = extent_t_max - extent_t_min;\n    double s_range = extent_s_max - extent_s_min;\n\n    for (i = 0; i < 12; ++i)\n    {\n        coarse_search(extent_t_min, extent_t_max, extent_s_min, extent_s_max,\n                      start_t, start_s, params);\n        //coarse_search_t(extent_t_min, extent_t_max, start_t, params);\n\n        t_range /= 3;\n        s_range /= 3;\n\n        extent_t_min = *start_t - t_range/2;\n        extent_t_max = *start_t + t_range/2;\n\n        extent_s_min = *start_s - s_range/2;\n        extent_s_max = *start_s + s_range/2;\n\n        //printf(\"refining search to region: (%9.3f,%9.3f)\\n\"\n        //       \"                           (%9.3f,%9.3f)\\n\",\n        //       extent_t_min, extent_t_max,\n        //       extent_s_min, extent_s_max);\n    }\n}\n\n/* small debug func\nstatic void print_state(int iter, gsl_multiroot_fsolver *s)\n{\n    printf(\"iter = %3d   x = (%.3f %.3f)   f(x) = %.8f\\n\", iter,\n           gsl_vector_get(s->x, 0), gsl_vector_get(s->x, 1),\n           gsl_vector_get(s->f, 0));\n}\n*/\n\n// This won't change the passed-in metadata -- afterwards, if you want\n// to apply the found corrections, do this:\n//   meta->sar->slant_shift += slant_shift_adjustment;\n//   meta->sar->time_shift += time_shift_adjustment;\n// usually you will only want to do this if the function returns TRUE\n// (on success), though if it returns FALSE (failed) these two parameters\n// will be 0\nint refine_slc_geolocation_from_workreport(const char *metaName,\n                                           const char *basename,\n                                           meta_parameters *meta,\n                                           double *time_shift_adjustment,\n                                           double *slant_shift_adjustment)\n{\n  char *fileName = MALLOC(sizeof(char)*(10+strlen(basename)+strlen(metaName)));\n  char *dirname = get_dirname(metaName);\n  if (strlen(dirname)>0)\n    sprintf(fileName, \"%s%s\", dirname, basename);\n  else\n    strcpy(fileName, basename);\n  FILE *fp = fopen_workreport(fileName);\n  FREE(dirname);\n  if (!fp) {\n    // failed to open workreport file\n    asfPrintWarning(\n\"Attempted to refine the geolocation with the workreport file.  However,\\n\"\n\"this file could not be found.  To get the most accurate geolocations with\\n\"\n\"Palsar SLC data, include the workreport file in the same directory as the\\n\"\n\"data file.  First <basename>.txt is checked, then 'workreport'.\\n\\n\"\n\"Proceeding... however, extremely poor geolocations may result.\\n\");\n    *slant_shift_adjustment = 0.0;\n    *time_shift_adjustment = 0.0;\n    FREE(fileName);\n    return FALSE;\n  }\n\n  // Read the workreport file, find the 4 corners and scene center\n  // lat and long info.  We also check to make sure this is the right\n  // workreport file...\n\n  struct dataset_sum_rec dssr;\n  hms_time dssr_time, summary_time;\n  ymd_date dssr_date, summary_date;\n  char line[512], tmp[512], *p;\n  get_dssr(metaName, &dssr);\n  date_dssr2date(dssr.inp_sctim, &dssr_date, &dssr_time);\n\n  double center_lat=-999, center_lon=-999;\n  double ul_lat=-999, ul_lon=-999;\n  double ur_lat=-999, ur_lon=-999;\n  double ll_lat=-999, ll_lon=-999;\n  double lr_lat=-999, lr_lon=-999;\n\n  while (fgets(line, 512, fp)) {\n    if (strstr(line, \"Img_SceneCenterDateTime\")) {\n      p = strchr(line, '\"');\n      sprintf(tmp, \"%s\", p+1);\n      tmp[strlen(tmp)-2] = '\\0';\n      date_alos2date(tmp, &summary_date, &summary_time);\n      if (date_difference(&dssr_date, &dssr_time,\n          &summary_date, &summary_time) > 10.0)\n      {\n        asfPrintWarning(\n\"Summary file does not correspond to leader file.\\n\"\n\"  DSSR: %s\\n  Summary: %s\\n\"\n\"This is most likely because you have a mismatched workreport file.  Since\\n\"\n\"by default these files are all named 'workreport' this file may have been\\n\"\n\"overwritten with another scene's workreport file.  You may wish to rename\\n\"\n\"your workreport files using the <basename>.txt convention, for example:\\n\"\n\"  %s.txt\\n\"\n\"Proceeding... however, extremely poor geolocations may result.\\n\",\n                        dssr.inp_sctim, tmp, fileName);\n        *slant_shift_adjustment = 0;\n        *time_shift_adjustment = 0;\n        FCLOSE(fp);\n        FREE(fileName);\n        return 0;\n      }\n    }\n    else if (strstr(line, \"ImageSceneCenterLatitude\")) {\n      p = strchr(line, '\"');\n      if (p) center_lat = atof(p+1);\n    }\n    else if (strstr(line, \"ImageSceneCenterLongitude\")) {\n      p = strchr(line, '\"');\n      if (p) center_lon = atof(p+1);\n    }\n    else if (strstr(line, \"ImageSceneLeftTopLatitude\")) {\n      p = strchr(line, '\"');\n      if (p) ul_lat = atof(p+1);\n    }\n    else if (strstr(line, \"ImageSceneLeftTopLongitude\")) {\n      p = strchr(line, '\"');\n      if (p) ul_lon = atof(p+1);\n    }\n    else if (strstr(line, \"ImageSceneRightTopLatitude\")) {\n      p = strchr(line, '\"');\n      if (p) ur_lat = atof(p+1);\n    }\n    else if (strstr(line, \"ImageSceneRightTopLongitude\")) {\n      p = strchr(line, '\"');\n      if (p) ur_lon = atof(p+1);\n    }\n    else if (strstr(line, \"ImageSceneLeftBottomLatitude\")) {\n      p = strchr(line, '\"');\n      if (p) ll_lat = atof(p+1);\n    }\n    else if (strstr(line, \"ImageSceneLeftBottomLongitude\")) {\n      p = strchr(line, '\"');\n      if (p) ll_lon = atof(p+1);\n    }\n    else if (strstr(line, \"ImageSceneRightBottomLatitude\")) {\n      p = strchr(line, '\"');\n      if (p) lr_lat = atof(p+1);\n    }\n    else if (strstr(line, \"ImageSceneRightBottomLongitude\")) {\n      p = strchr(line, '\"');\n      if (p) lr_lon = atof(p+1);\n    }\n  }\n\n  FREE(fileName);\n  fclose(fp);\n\n  // Did we get all that we needed?\n  int ok = TRUE;\n  if (center_lat == -999) {\n    asfPrintStatus(\"Missing: ImageSceneCenterLatitude\\n\");\n    ok = FALSE;\n  }\n  if (center_lon == -999) {\n    asfPrintStatus(\"Missing: ImageSceneCenterLongitude\\n\");\n    ok = FALSE;\n  }\n  if (ul_lat == -999) {\n    asfPrintStatus(\"Missing: ImageSceneTopLeftLatitude\\n\");\n    ok = FALSE;\n  }\n  if (ul_lon == -999) {\n    asfPrintStatus(\"Missing: ImageSceneTopLeftLongitude\\n\");\n    ok = FALSE;\n  }\n  if (ur_lat == -999) {\n    asfPrintStatus(\"Missing: ImageSceneTopRightLatitude\\n\");\n    ok = FALSE;\n  }\n  if (ur_lon == -999) {\n    asfPrintStatus(\"Missing: ImageSceneTopRightLongitude\\n\");\n    ok = FALSE;\n  }\n  if (ll_lat == -999) {\n    asfPrintStatus(\"Missing: ImageSceneBottomLeftLatitude\\n\");\n    ok = FALSE;\n  }\n  if (ll_lon == -999) {\n    asfPrintStatus(\"Missing: ImageSceneBottomLeftLongitude\\n\");\n    ok = FALSE;\n  }\n  if (lr_lat == -999) {\n    asfPrintStatus(\"Missing: ImageSceneBottomRightLatitude\\n\");\n    ok = FALSE;\n  }\n  if (lr_lon == -999) {\n    asfPrintStatus(\"Missing: ImageSceneBottomRightLongitude\\n\");\n    ok = FALSE;\n  }\n  if (!ok) {\n    asfPrintWarning(\"Not all necessary information is available in the \"\n                    \"workreport file.\\nProceeding... however, extremely \"\n                    \"poor geolocations may result.\\n\");    \n    *slant_shift_adjustment = 0.0;\n    *time_shift_adjustment = 0.0;\n    return FALSE;\n  }\n\n  // all required info is present-- search for min slant and time shifts\n\n  struct refine_shift_params params;\n  params.meta = meta;\n  params.center_lat = center_lat;\n  params.center_lon = center_lon;\n  params.ul_lat = ul_lat;\n  params.ul_lon = ul_lon;\n  params.ur_lat = ur_lat;\n  params.ur_lon = ur_lon;\n  params.ll_lat = ll_lat;\n  params.ll_lon = ll_lon;\n  params.lr_lat = lr_lat;\n  params.lr_lon = lr_lon;\n\n  //int status;\n  //int iter = 0, max_iter = 1000;\n  //const gsl_multiroot_fsolver_type *T;\n  //gsl_multiroot_fsolver *s;\n  //gsl_error_handler_t *prev;\n  //const size_t n = 2;\n\n  //gsl_multiroot_function F = {&getObjective, n, &params};\n  //gsl_vector *x = gsl_vector_alloc(n);\n\n  double start_t, start_s;\n  generate_start(&params, &start_t, &start_s);\n  //printf(\"Starting point at (%f, %f)\\n\", start_t, start_s);\n\n/*\n  gsl_vector_set (x, 0, start_t);\n  gsl_vector_set (x, 1, start_s);\n\n  T = gsl_multiroot_fsolver_hybrid;\n  s = gsl_multiroot_fsolver_alloc(T, n);\n  gsl_multiroot_fsolver_set(s, &F, x);\n\n  prev = gsl_set_error_handler_off();\n\n  do {\n    ++iter;\n    status = gsl_multiroot_fsolver_iterate(s);\n\n    //print_state(iter, s);\n\n    // abort if stuck\n    if (status) break;\n\n    status = gsl_multiroot_test_residual (s->f, 1e-8);\n  } while (status == GSL_CONTINUE && iter < max_iter);\n\n  *time_shift_adjustment = gsl_vector_get(s->x, 0);\n  *slant_shift_adjustment = gsl_vector_get(s->x, 1);\n\n  gsl_vector *retrofit = gsl_vector_alloc(n);\n  gsl_vector_set(retrofit, 0, *time_shift_adjustment);\n  gsl_vector_set(retrofit, 1, *slant_shift_adjustment);\n  gsl_vector *output = gsl_vector_alloc(n);\n  getObjective(retrofit, (void*)&params, output);\n  double val= gsl_vector_get(output,0);\n  printf(\"GSL Result: %f at (%f,%f)\\n\",\n         val, *time_shift_adjustment, *slant_shift_adjustment);\n  gsl_vector_free(retrofit);\n  gsl_vector_free(output);\n  \n  gsl_multiroot_fsolver_free(s);\n  gsl_vector_free(x);\n  gsl_set_error_handler(prev);\n*/\n  *time_shift_adjustment = start_t;\n  *slant_shift_adjustment = start_s;\n\n  // the rest of this is a bunch of debug code\n/*\n  int nl = meta->general->line_count;\n  int ns = meta->general->sample_count;\n  double lat,lon;\n\n  if (meta->general->orbit_direction=='A') {\n\n    printf(\"BEFORE-->\\n\");\n    meta_get_latLon(meta, nl/2, ns/2, 0, &lat, &lon);\n    printf(\"  CN: mgll: %f,%f - wr:%f,%f - err:%f\\n\",\n           lat,lon,center_lat,center_lon,\n           lldist(lat,center_lat,lon,center_lon));\n    meta_get_latLon(meta, nl-1, 0, 0, &lat, &lon);\n    printf(\"  UL: mgll: %f,%f - wr:%f,%f - err:%f\\n\",\n           lat,lon,ul_lat,ul_lon,lldist(lat,ul_lat,lon,ul_lon));\n    meta_get_latLon(meta, nl-1, ns-1, 0, &lat, &lon);\n    printf(\"  UR: mgll: %f,%f - wr:%f,%f - err:%f\\n\",\n           lat,lon,ur_lat,ur_lon,lldist(lat,ur_lat,lon,ur_lon));\n    meta_get_latLon(meta, 0, 0, 0, &lat, &lon);\n    printf(\"  LL: mgll: %f,%f - wr:%f,%f - err:%f\\n\",\n           lat,lon,ll_lat,ll_lon,lldist(lat,ll_lat,lon,ll_lon));\n    meta_get_latLon(meta, 0, ns-1, 0, &lat, &lon);\n    printf(\"  LR: mgll: %f,%f - wr:%f,%f - err:%f\\n\",\n           lat,lon,lr_lat,lr_lon,lldist(lat,lr_lat,lon,lr_lon));\n    \n    double saved_timeOffset = meta->sar->time_shift;\n    double saved_slant = meta->sar->slant_shift;\n    meta->sar->time_shift += *time_shift_adjustment;\n    meta->sar->slant_shift += *slant_shift_adjustment;\n    \n    printf(\"AFTER-->\\n\");\n    meta_get_latLon(meta, nl/2, ns/2, 0, &lat, &lon);\n    printf(\"  CN: mgll: %f,%f - wr:%f,%f - err:%f\\n\",\n           lat,lon,center_lat,center_lon,\n           lldist(lat,center_lat,lon,center_lon));\n    meta_get_latLon(meta, nl-1, 0, 0, &lat, &lon);\n    printf(\"  UL: mgll: %f,%f - wr:%f,%f - err:%f\\n\",\n           lat,lon,ul_lat,ul_lon,lldist(lat,ul_lat,lon,ul_lon));\n    meta_get_latLon(meta, nl-1, ns-1, 0, &lat, &lon);\n    printf(\"  UR: mgll: %f,%f - wr:%f,%f - err:%f\\n\",\n           lat,lon,ur_lat,ur_lon,lldist(lat,ur_lat,lon,ur_lon));\n    meta_get_latLon(meta, 0, 0, 0, &lat, &lon);\n    printf(\"  LL: mgll: %f,%f - wr:%f,%f - err:%f\\n\",\n           lat,lon,ll_lat,ll_lon,lldist(lat,ll_lat,lon,ll_lon));\n    meta_get_latLon(meta, 0, ns-1, 0, &lat, &lon);\n    printf(\"  LR: mgll: %f,%f - wr:%f,%f - err:%f\\n\",\n           lat,lon,lr_lat,lr_lon,lldist(lat,lr_lat,lon,lr_lon));\n\n    meta->sar->time_shift = saved_timeOffset;\n    meta->sar->slant_shift = saved_slant;\n  }\n  else {\n    printf(\"BEFORE-->\\n\");\n    meta_get_latLon(meta, nl/2, ns/2, 0, &lat, &lon);\n    printf(\"  CN: mgll: %f,%f - wr:%f,%f - err:%f\\n\",\n           lat,lon,center_lat,center_lon,\n           lldist(lat,center_lat,lon,center_lon));\n    meta_get_latLon(meta, 0, ns-1, 0, &lat, &lon);\n    printf(\"  UL: mgll: %f,%f - wr:%f,%f - err:%f\\n\",\n           lat,lon,ul_lat,ul_lon,lldist(lat,ul_lat,lon,ul_lon));\n    meta_get_latLon(meta, 0, 0, 0, &lat, &lon);\n    printf(\"  UR: mgll: %f,%f - wr:%f,%f - err:%f\\n\",\n           lat,lon,ur_lat,ur_lon,lldist(lat,ur_lat,lon,ur_lon));\n    meta_get_latLon(meta, nl-1, ns-1, 0, &lat, &lon);\n    printf(\"  LL: mgll: %f,%f - wr:%f,%f - err:%f\\n\",\n           lat,lon,ll_lat,ll_lon,lldist(lat,ll_lat,lon,ll_lon));\n    meta_get_latLon(meta, nl-1, 0, 0, &lat, &lon);\n    printf(\"  LR: mgll: %f,%f - wr:%f,%f - err:%f\\n\",\n           lat,lon,lr_lat,lr_lon,lldist(lat,lr_lat,lon,lr_lon));\n    \n    double saved_timeOffset = meta->sar->time_shift;\n    double saved_slant = meta->sar->slant_shift;\n    meta->sar->time_shift += *time_shift_adjustment;\n    meta->sar->slant_shift += *slant_shift_adjustment;\n    \n    printf(\"AFTER-->\\n\");\n    meta_get_latLon(meta, nl/2, ns/2, 0, &lat, &lon);\n    printf(\"  CN: mgll: %f,%f - wr:%f,%f - err:%f\\n\",\n           lat,lon,center_lat,center_lon,\n           lldist(lat,center_lat,lon,center_lon));\n    meta_get_latLon(meta, 0, ns-1, 0, &lat, &lon);\n    printf(\"  UL: mgll: %f,%f - wr:%f,%f - err:%f\\n\",\n           lat,lon,ul_lat,ul_lon,lldist(lat,ul_lat,lon,ul_lon));\n    meta_get_latLon(meta, 0, 0, 0, &lat, &lon);\n    printf(\"  UR: mgll: %f,%f - wr:%f,%f - err:%f\\n\",\n           lat,lon,ur_lat,ur_lon,lldist(lat,ur_lat,lon,ur_lon));\n    meta_get_latLon(meta, nl-1, ns-1, 0, &lat, &lon);\n    printf(\"  LL: mgll: %f,%f - wr:%f,%f - err:%f\\n\",\n           lat,lon,ll_lat,ll_lon,lldist(lat,ll_lat,lon,ll_lon));\n    meta_get_latLon(meta, nl-1, 0, 0, &lat, &lon);\n    printf(\"  LR: mgll: %f,%f - wr:%f,%f - err:%f\\n\",\n           lat,lon,lr_lat,lr_lon,lldist(lat,lr_lat,lon,lr_lon));\n\n    meta->sar->time_shift = saved_timeOffset;\n    meta->sar->slant_shift = saved_slant;\n  }\n*/\n  return TRUE;\n}\n", "meta": {"hexsha": "4e4f27b6de496cc66fe8d938636a3c7c013d67a5", "size": 23798, "ext": "c", "lang": "C", "max_stars_repo_path": "src/asf_meta/workreport.c", "max_stars_repo_name": "glshort/MapReady", "max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z", "max_issues_repo_path": "src/asf_meta/workreport.c", "max_issues_repo_name": "glshort/MapReady", "max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/asf_meta/workreport.c", "max_forks_repo_name": "glshort/MapReady", "max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z", "avg_line_length": 32.2466124661, "max_line_length": 79, "alphanum_fraction": 0.6072779225, "num_tokens": 7200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16451647108926923, "lm_q2_score": 0.02333076863870825, "lm_q1q2_score": 0.003838295724240475}}
{"text": "#pragma once\n\n#include <imageview/ContinuousImageView.h>\n#include <imageview/internal/ImageViewStorage.h>\n#include <imageview/internal/PixelRef.h>\n\n#include <gsl/span>\n\n#include <cstddef>\n\nnamespace imageview {\n\ntemplate <class PixelFormat, bool Mutable = false>\nclass ImageView {\n public:\n  static_assert(IsPixelFormat<PixelFormat>::value, \"Not a PixelFormat.\");\n\n  using byte_type = std::conditional_t<Mutable, std::byte, const std::byte>;\n  using value_type = typename PixelFormat::color_type;\n  // TODO: consider using 'const value_type' instead of 'value_type' for immutable views.\n  using reference = std::conditional_t<Mutable, detail::PixelRef<PixelFormat>, value_type>;\n\n  // Construct an empty view.\n  template <class Enable = std::enable_if_t<std::is_default_constructible_v<PixelFormat>>>\n  constexpr ImageView() noexcept(noexcept(std::is_nothrow_default_constructible_v<PixelFormat>)) {}\n\n  // Construct a view into an image.\n  // \\param height - height of the image.\n  // \\param width - width of the image.\n  // \\param stride -\n  // \\param data - bitmap data.\n  constexpr ImageView(unsigned int height, unsigned int width, unsigned int stride, gsl::span<byte_type> data);\n\n  // Construct a view into an image.\n  // \\param height - height of the image.\n  // \\param width - width of the image.\n  // \\param stride -\n  // \\param data - bitmap data.\n  // \\param pixel_format - PixelFormat instance to use.\n  constexpr ImageView(unsigned int height, unsigned int width, unsigned int stride, gsl::span<byte_type> data,\n                      const PixelFormat& pixel_format);\n  constexpr ImageView(unsigned int height, unsigned int width, unsigned int stride, gsl::span<byte_type> data,\n                      PixelFormat&& pixel_format);\n\n  // Construct a read-only view from a mutable view.\n  template <class Enable = std::enable_if_t<!Mutable>>\n  constexpr ImageView(ImageView<PixelFormat, !Mutable> other);\n\n  constexpr ImageView(ContinuousImageView<PixelFormat, Mutable> image);\n  // Construct a read-only view from a mutable contiguous view.\n  template <class Enable = std::enable_if_t<!Mutable>>\n  constexpr ImageView(ContinuousImageView<PixelFormat, !Mutable> image);\n\n  // Return the height of the image\n  constexpr unsigned int height() const noexcept;\n\n  constexpr unsigned int width() const noexcept;\n\n  constexpr unsigned int stride() const noexcept;\n\n  constexpr unsigned int area() const noexcept;\n\n  // Returns true if the image has zero area, false otherwise.\n  constexpr bool empty() const noexcept;\n\n  // Returns the pixel format used by this image.\n  constexpr const PixelFormat& pixelFormat() const noexcept;\n\n  constexpr gsl::span<byte_type> data() const noexcept;\n\n  constexpr reference operator()(unsigned int y, unsigned int x) const;\n\n  constexpr ImageRowView<PixelFormat, Mutable> row(unsigned int y) const;\n\n private:\n  detail::ImageViewStorage<PixelFormat, Mutable> storage_;\n  unsigned int height_ = 0;\n  unsigned int width_ = 0;\n  unsigned int stride_ = 0;\n};\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr ImageView<PixelFormat, Mutable>::ImageView(unsigned int height, unsigned int width, unsigned int stride,\n                                                     gsl::span<byte_type> data)\n    : storage_(data.data()), height_(height), width_(width), stride_(stride) {\n  Expects(width <= stride);\n  const std::size_t expected_size = (height == 0) ? 0 : ((height - 1) * stride + width) * PixelFormat::kBytesPerPixel;\n  Expects(data.size() == expected_size);\n}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr ImageView<PixelFormat, Mutable>::ImageView(unsigned int height, unsigned int width, unsigned int stride,\n                                                     gsl::span<byte_type> data, const PixelFormat& pixel_format)\n    : storage_(data.data(), pixel_format), height_(height), width_(width), stride_(stride) {\n  Expects(width <= stride);\n  const std::size_t expected_size = (height == 0) ? 0 : ((height - 1) * stride + width) * PixelFormat::kBytesPerPixel;\n  Expects(data.size() == expected_size);\n}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr ImageView<PixelFormat, Mutable>::ImageView(unsigned int height, unsigned int width, unsigned int stride,\n                                                     gsl::span<byte_type> data, PixelFormat&& pixel_format)\n    : storage_(data.data(), std::move(pixel_format)), height_(height), width_(width), stride_(stride) {\n  Expects(width <= stride);\n  const std::size_t expected_size = (height == 0) ? 0 : ((height - 1) * stride + width) * PixelFormat::kBytesPerPixel;\n  Expects(data.size() == expected_size);\n}\n\ntemplate <class PixelFormat, bool Mutable>\ntemplate <class Enable>\nconstexpr ImageView<PixelFormat, Mutable>::ImageView(ImageView<PixelFormat, !Mutable> other)\n    : ImageView(other.height(), other.width(), other.stride(), other.data(), other.pixelFormat()) {}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr ImageView<PixelFormat, Mutable>::ImageView(ContinuousImageView<PixelFormat, Mutable> image)\n    : ImageView(image.height(), image.width(), image.width(), image.data()) {}\n\ntemplate <class PixelFormat, bool Mutable>\ntemplate <class Enable>\nconstexpr ImageView<PixelFormat, Mutable>::ImageView(ContinuousImageView<PixelFormat, !Mutable> image)\n    : ImageView(ContinuousImageView<PixelFormat, Mutable>(image)) {}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr unsigned int ImageView<PixelFormat, Mutable>::height() const noexcept {\n  return height_;\n}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr unsigned int ImageView<PixelFormat, Mutable>::width() const noexcept {\n  return width_;\n}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr unsigned int ImageView<PixelFormat, Mutable>::stride() const noexcept {\n  return stride_;\n}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr unsigned int ImageView<PixelFormat, Mutable>::area() const noexcept {\n  return height_ * width_;\n}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr bool ImageView<PixelFormat, Mutable>::empty() const noexcept {\n  return height_ == 0 || width_ == 0;\n}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr const PixelFormat& ImageView<PixelFormat, Mutable>::pixelFormat() const noexcept {\n  return storage_.pixelFormat();\n}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr auto ImageView<PixelFormat, Mutable>::data() const noexcept -> gsl::span<byte_type> {\n  const std::size_t data_size = (height_ == 0) ? 0 : ((height_ - 1) * stride_ + width_) * PixelFormat::kBytesPerPixel;\n  return gsl::span<byte_type>(storage_.data(), data_size);\n}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr auto ImageView<PixelFormat, Mutable>::operator()(unsigned int y, unsigned int x) const -> reference {\n  Expects(y < height_);\n  Expects(x < width_);\n  const gsl::span<byte_type, PixelFormat::kBytesPerPixel> pixel_data(\n      storage_.data() + (y * stride_ + x) * PixelFormat::kBytesPerPixel, PixelFormat::kBytesPerPixel);\n  if constexpr (Mutable) {\n    return detail::PixelRef<PixelFormat>(pixel_data, pixelFormat());\n  } else {\n    return pixelFormat().read(pixel_data);\n  }\n}\n\ntemplate <class PixelFormat, bool Mutable>\nconstexpr ImageRowView<PixelFormat, Mutable> ImageView<PixelFormat, Mutable>::row(unsigned int y) const {\n  Expects(y < height_);\n  const gsl::span<byte_type> row_data(storage_.data() + y * stride_ * PixelFormat::kBytesPerPixel,\n                                      width_ * PixelFormat::kBytesPerPixel);\n  return ImageRowView<PixelFormat>(row_data, width_, pixelFormat());\n}\n\n}  // namespace imageview\n", "meta": {"hexsha": "2312b4906a30b4d9542528677611f642d8f48fbc", "size": 7565, "ext": "h", "lang": "C", "max_stars_repo_path": "include/imageview/ImageView.h", "max_stars_repo_name": "alexanderbelous/imageview", "max_stars_repo_head_hexsha": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/imageview/ImageView.h", "max_issues_repo_name": "alexanderbelous/imageview", "max_issues_repo_head_hexsha": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/imageview/ImageView.h", "max_forks_repo_name": "alexanderbelous/imageview", "max_forks_repo_head_hexsha": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.7955801105, "max_line_length": 118, "alphanum_fraction": 0.722538004, "num_tokens": 1671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15002881674163046, "lm_q2_score": 0.02556521536171718, "lm_q1q2_score": 0.0038355190104633827}}
{"text": "// Copyright \u00a9 Matt Jones and Contributors. Licensed under the MIT Licence (MIT). See LICENCE.md in the repository root\n// for more information.\n\n#ifndef NOVELRT_EXPERIMENTAL_GRAPHICS_H\n#define NOVELRT_EXPERIMENTAL_GRAPHICS_H\n\n// Graphics dependencies\n#include \"../../Graphics/RGBAColour.h\"\n#include \"../../Maths/Maths.h\"\n#include \"../../Utilities/Event.h\"\n#include \"../../Utilities/Misc.h\"\n#include \"../EngineConfig.h\"\n#include \"../Threading/Threading.h\"\n#include <chrono>\n#include <cstdint>\n#include <filesystem>\n#include <gsl/span>\n#include <list>\n#include <memory>\n#include <mutex>\n#include <optional>\n#include <string>\n#include <typeindex>\n#include <utility>\n#include <vector>\n\n/**\n * @brief The experimental Graphics plugin API. Comes with built-in support for the ECS.\n */\nnamespace NovelRT::Experimental::Graphics\n{\n    enum class ShaderProgramKind : uint32_t;\n    class GraphicsDeviceObject;\n    enum class GraphicsResourceAccess : uint32_t;\n    enum class GraphicsSurfaceKind : uint32_t;\n    class IGraphicsSurface;\n    class GraphicsAdapter;\n    class GraphicsDevice;\n    class GraphicsResource;\n    class GraphicsBuffer;\n    class GraphicsTexture;\n    class ShaderProgram;\n    class GraphicsPipeline;\n    class GraphicsPipelineSignature;\n    class GraphicsPipelineInput;\n    class GraphicsPipelineResource;\n    class GraphicsPipelineInputElement;\n    enum class GraphicsPipelineInputElementKind : uint32_t;\n    enum class GraphicsPipelineResourceKind : uint32_t;\n    enum class ShaderProgramVisibility : uint32_t;\n    class GraphicsContext;\n    class GraphicsFence;\n    class GraphicsPrimitive;\n    class GraphicsProvider;\n    class GraphicsMemoryAllocator;\n    struct GraphicsMemoryAllocatorSettings;\n    enum class GraphicsTextureKind : uint32_t;\n    class IGraphicsAdapterSelector;\n    enum class GraphicsMemoryRegionAllocationFlags : uint32_t;\n    class GraphicsMemoryBlockCollection;\n    class GraphicsMemoryBlock;\n    enum class GraphicsMemoryRegionAllocationFlags : uint32_t;\n    class GraphicsMemoryBudget;\n    enum class GraphicsBufferKind : uint32_t;\n    enum class TexelFormat : uint32_t;\n    class GraphicsSurfaceContext;\n}\n\n// Graphics types\n// clang-format off\n\n#include \"ShaderProgramKind.h\"\n#include \"EcsDefaultRenderingComponentTypes.h\"\n#include \"EcsDefaultRenderingSystem.h\"\n#include \"GraphicsAdapter.h\"\n#include \"GraphicsDeviceObject.h\"\n#include \"GraphicsContext.h\"\n#include \"GraphicsFence.h\"\n#include \"GraphicsMemoryAllocatorSettings.h\"\n#include \"GraphicsMemoryRegion.h\"\n#include \"IGraphicsMemoryRegionCollection.h\"\n#include \"GraphicsMemoryRegionAllocationFlags.h\"\n#include \"TexelFormat.h\"\n#include \"GraphicsMemoryAllocator.h\"\n#include \"GraphicsMemoryBlockCollection.h\"\n#include \"GraphicsMemoryBudget.h\"\n#include \"GraphicsMemoryBlock.h\"\n#include \"GraphicsResourceAccess.h\"\n#include \"GraphicsSurfaceKind.h\"\n#include \"GraphicsTextureKind.h\"\n#include \"IGraphicsSurface.h\"\n#include \"GraphicsSurfaceContext.h\"\n#include \"GraphicsDevice.h\"\n#include \"GraphicsResource.h\"\n#include \"GraphicsBufferKind.h\"\n#include \"GraphicsBuffer.h\"\n#include \"GraphicsTexture.h\"\n#include \"IGraphicsAdapterSelector.h\"\n#include \"ShaderProgram.h\"\n#include \"GraphicsPipeline.h\"\n#include \"GraphicsPipelineSignature.h\"\n#include \"GraphicsPrimitive.h\"\n#include \"GraphicsProvider.h\"\n#include \"GraphicsPipelineInput.h\"\n#include \"GraphicsPipelineInputElement.h\"\n#include \"GraphicsPipelineInputElementKind.h\"\n#include \"GraphicsPipelineResource.h\"\n#include \"GraphicsPipelineResourceKind.h\"\n#include \"ShaderProgramVisibility.h\"\n\n// clang-format on\n\n#endif // !NOVELRT_EXPERIMENTAL_GRAPHICS_H\n", "meta": {"hexsha": "1727869d4a1930926ed0fb66369e492925481c2f", "size": 3583, "ext": "h", "lang": "C", "max_stars_repo_path": "include/NovelRT/Experimental/Graphics/Graphics.h", "max_stars_repo_name": "Exadon/NovelRT", "max_stars_repo_head_hexsha": "82000a25fd53157b26a6e6d6c71cbee0ebaa241b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 167.0, "max_stars_repo_stars_event_min_datetime": "2019-02-12T14:12:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T17:14:24.000Z", "max_issues_repo_path": "include/NovelRT/Experimental/Graphics/Graphics.h", "max_issues_repo_name": "BanalityOfSeeking/NovelRT", "max_issues_repo_head_hexsha": "bbbe54f719acdc2fcee4604ee90fb43ff975aee9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 270.0, "max_issues_repo_issues_event_min_datetime": "2019-02-14T20:33:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T02:28:20.000Z", "max_forks_repo_path": "include/NovelRT/Experimental/Graphics/Graphics.h", "max_forks_repo_name": "BanalityOfSeeking/NovelRT", "max_forks_repo_head_hexsha": "bbbe54f719acdc2fcee4604ee90fb43ff975aee9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 56.0, "max_forks_repo_forks_event_min_datetime": "2019-08-22T15:57:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T19:52:18.000Z", "avg_line_length": 31.4298245614, "max_line_length": 119, "alphanum_fraction": 0.7870499581, "num_tokens": 748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.180106646483037, "lm_q2_score": 0.021287350978509898, "lm_q1q2_score": 0.003833993397246814}}
{"text": "#ifndef LIC_CALL_STACK_FRAME\n#define LIC_CALL_STACK_FRAME\n\n#include <stack>\n#include <gsl/gsl>\n\n#include \"format/Opcodes.h\"\n#include \"loader/MethodDefinition.h\"\n#include \"EvaluationStack.h\"\n\nnamespace lic\n{\n\nclass CallStackFrame\n{\npublic:\n    CallStackFrame(MethodDefinition& method, gsl::span<TypedValue> args, Opcode* returnAddress);\n    CallStackFrame(MethodDefinition& method, TypedValue& thisRef, gsl::span<TypedValue> args, Opcode* returnAddress);\n\n    MethodDefinition& Method();\n    TypedValue& Arg(size_t index);\n    TypedValue& Local(size_t index);\n    EvaluationStack& Stack();\n    Opcode* ReturnAddress() const;\n\nprivate:\n    MethodDefinition& method;\n    std::vector<TypedValue> args;\n    std::vector<TypedValue> locals;\n    EvaluationStack stack;\n    Opcode* returnAddress;\n};\n\n}\n\n#endif // !LIC_CALL_STACK_FRAME\n\n", "meta": {"hexsha": "ce37797f5cc4133019c329905c678708ce50beaa", "size": 828, "ext": "h", "lang": "C", "max_stars_repo_path": "src/interpreter/CallStackFrame.h", "max_stars_repo_name": "roberthusak/lic", "max_stars_repo_head_hexsha": "5ad4a7014673bb60b748390856e0c7cb11eaca09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-05-18T11:44:16.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-18T11:44:16.000Z", "max_issues_repo_path": "src/interpreter/CallStackFrame.h", "max_issues_repo_name": "roberthusak/lic", "max_issues_repo_head_hexsha": "5ad4a7014673bb60b748390856e0c7cb11eaca09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/interpreter/CallStackFrame.h", "max_forks_repo_name": "roberthusak/lic", "max_forks_repo_head_hexsha": "5ad4a7014673bb60b748390856e0c7cb11eaca09", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.7894736842, "max_line_length": 117, "alphanum_fraction": 0.7415458937, "num_tokens": 196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.10521054792560194, "lm_q2_score": 0.03622005417441523, "lm_q1q2_score": 0.003810731745585212}}
{"text": "#pragma once\n\n#include <gsl/span>\n\n#include <memory>\n\n#include <qbuffer.h>\n#include <qthread.h>\n\n#if QT_VERSION >= 0x060000\n    #include <QtMultimedia/QAudioSink>\n#else\n    #include <QtMultimedia/QAudioOutput>\n#endif\nnamespace contour\n{\nclass Audio: public QObject\n{\n    Q_OBJECT\n\n  public:\n    Audio();\n    ~Audio() override;\n  signals:\n    void play(int volume, int duration, std::vector<int> const& notes);\n  private slots:\n    void handleStateChanged(QAudio::State state);\n    void handlePlayback(int volume, int duration, std::vector<int> const& notes);\n\n  private:\n    void fillBuffer(int volume, int duration, gsl::span<const int> notes);\n    std::vector<std::int16_t> createMusicalNote(double volume, int duration, int note_) noexcept;\n\n    QByteArray byteArray_;\n    QBuffer audioBuffer_;\n    QThread soundThread_;\n#if QT_VERSION >= 0x060000\n    std::unique_ptr<QAudioSink> audio;\n#else\n    std::unique_ptr<QAudioOutput> audio;\n#endif\n};\n} // namespace contour\n", "meta": {"hexsha": "d2055f663374c1b55ef02729b85a64b925e8c60a", "size": 970, "ext": "h", "lang": "C", "max_stars_repo_path": "src/contour/Audio.h", "max_stars_repo_name": "christianparpart/libterminal", "max_stars_repo_head_hexsha": "0e6d75a2042437084c9f9880a5c8b5661a02da07", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-08-14T22:29:57.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-19T08:57:15.000Z", "max_issues_repo_path": "src/contour/Audio.h", "max_issues_repo_name": "christianparpart/libterminal", "max_issues_repo_head_hexsha": "0e6d75a2042437084c9f9880a5c8b5661a02da07", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 69.0, "max_issues_repo_issues_event_min_datetime": "2019-08-17T18:57:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-22T23:25:49.000Z", "max_forks_repo_path": "src/contour/Audio.h", "max_forks_repo_name": "christianparpart/libterminal", "max_forks_repo_head_hexsha": "0e6d75a2042437084c9f9880a5c8b5661a02da07", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0454545455, "max_line_length": 97, "alphanum_fraction": 0.712371134, "num_tokens": 246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21733751090819795, "lm_q2_score": 0.017442484097755995, "lm_q1q2_score": 0.0037909060778621127}}
{"text": "#pragma once\n#include <gsl/gsl>\n#include <map>\n#include <optional>\n\n\n#include \"aseprite_file.h\"\n#include \"halley/text/halleystring.h\"\n#include \"halley/maths/vector4.h\"\n\nnamespace Halley\n{\n\tclass Path;\n\tclass Image;\n\tstruct ImageData;\n\n\tclass AsepriteReader\n\t{\n\tpublic:\n\t\tstatic std::map<String, Vector<ImageData>> importAseprite(const String& spriteName, const Path& filename, gsl::span<const gsl::byte> fileData, bool trim, int padding, bool groupSeparated, bool sequenceSeparated);\n\t\tstatic void addImageData(int tagFrameNumber, int origFrameNumber, Vector<ImageData>& frameData, std::unique_ptr<Image> frameImage,\n\t\t                  const AsepriteFile& aseFile, const String& baseName, const String& sequence, const String& direction,\n\t\t\t\t\t\t  int duration, bool trim, int padding, bool hasFrameNumber, std::optional<String> group, bool firstImage,\n\t\t                  const String& spriteName, const Path& filename);\n\t};\n}\n", "meta": {"hexsha": "f4e7af06271d5f58ee6ae9aa3158cd60ae832db7", "size": 927, "ext": "h", "lang": "C", "max_stars_repo_path": "src/tools/tools/src/sprites/aseprite_reader.h", "max_stars_repo_name": "amrezzd/halley", "max_stars_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tools/tools/src/sprites/aseprite_reader.h", "max_issues_repo_name": "amrezzd/halley", "max_issues_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tools/tools/src/sprites/aseprite_reader.h", "max_forks_repo_name": "amrezzd/halley", "max_forks_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3333333333, "max_line_length": 214, "alphanum_fraction": 0.7335490831, "num_tokens": 222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.20946968133032529, "lm_q2_score": 0.01798621239664392, "lm_q1q2_score": 0.0037675661790645483}}
{"text": "/*\n *  Copyright (C) 2021 FISCO BCOS.\n *  SPDX-License-Identifier: Apache-2.0\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n * @brief scale decoder\n * @file ScaleDecoderStream.cpp\n */\n#pragma once\n#include \"../../libutilities/Common.h\"\n#include \"../../libutilities/DataConvertUtility.h\"\n#include \"../../libutilities/FixedBytes.h\"\n#include \"Common.h\"\n#include \"FixedWidthIntegerCodec.h\"\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/optional.hpp>\n#include <boost/variant.hpp>\n#include <array>\n#include <gsl/span>\n\nnamespace bcos\n{\nnamespace codec\n{\nnamespace scale\n{\nclass ScaleDecoderStream\n{\npublic:\n    // special tag to differentiate decoding streams from others\n    static constexpr auto is_decoder_stream = true;\n    explicit ScaleDecoderStream(gsl::span<byte const> span);\n\n    /**\n     * @brief scale-decodes pair of values\n     * @tparam F first value type\n     * @tparam S second value type\n     * @param p pair of values to decode\n     * @return reference to stream\n     */\n    template <class F, class S>\n    ScaleDecoderStream& operator>>(std::pair<F, S>& p)\n    {\n        static_assert(!std::is_reference_v<F> && !std::is_reference_v<S>);\n        return *this >> const_cast<std::remove_const_t<F>&>(p.first)  // NOLINT\n               >> const_cast<std::remove_const_t<S>&>(p.second);      // NOLINT\n    }\n\n    /**\n     * @brief scale-decoding of tuple\n     * @tparam T enumeration of tuples types\n     * @param v reference to tuple\n     * @return reference to stream\n     */\n    template <class... T>\n    ScaleDecoderStream& operator>>(std::tuple<T...>& v)\n    {\n        if constexpr (sizeof...(T) > 0)\n        {\n            decodeElementOfTuple<0>(v);\n        }\n        return *this;\n    }\n\n    /**\n     * @brief scale-decoding of variant\n     * @tparam T enumeration of various types\n     * @param v reference to variant\n     * @return reference to stream\n     */\n    template <class... Ts>\n    ScaleDecoderStream& operator>>(boost::variant<Ts...>& v)\n    {\n        // first byte means type index\n        uint8_t type_index = 0u;\n        *this >> type_index;  // decode type index\n\n        // ensure that index is in [0, types_count)\n        if (type_index >= sizeof...(Ts))\n        {\n            BOOST_THROW_EXCEPTION(\n                ScaleDecodeException() << errinfo_comment(\"exception for WRONG_TYPE_INDEX\"));\n        }\n\n        tryDecodeAsOneOfVariant<0>(v, type_index);\n        return *this;\n    }\n\n    /**\n     * @brief scale-decodes shared_ptr value\n     * @tparam T value type\n     * @param v value to decode\n     * @return reference to stream\n     */\n    template <class T>\n    ScaleDecoderStream& operator>>(std::shared_ptr<T>& v)\n    {\n        using mutableT = std::remove_const_t<T>;\n\n        static_assert(std::is_default_constructible_v<mutableT>);\n\n        v = std::make_shared<mutableT>();\n        return *this >> const_cast<mutableT&>(*v);  // NOLINT\n    }\n\n    /**\n     * @brief scale-decodes unique_ptr value\n     * @tparam T value type\n     * @param v value to decode\n     * @return reference to stream\n     */\n    template <class T>\n    ScaleDecoderStream& operator>>(std::unique_ptr<T>& v)\n    {\n        using mutableT = std::remove_const_t<T>;\n\n        static_assert(std::is_default_constructible_v<mutableT>);\n\n        v = std::make_unique<mutableT>();\n        return *this >> const_cast<mutableT&>(*v);  // NOLINT\n    }\n\n    /**\n     * @brief scale-encodes any integral type including bool\n     * @tparam T integral type\n     * @param v value of integral type\n     * @return reference to stream\n     */\n    template <typename T, typename I = std::decay_t<T>,\n        typename = std::enable_if_t<std::is_integral<I>::value>>\n    ScaleDecoderStream& operator>>(T& v)\n    {\n        // check bool\n        if constexpr (std::is_same<I, bool>::value)\n        {\n            v = decodeBool();\n            return *this;\n        }\n        // check byte\n        if constexpr (sizeof(T) == 1u)\n        {\n            v = nextByte();\n            return *this;\n        }\n        // decode any other integer\n        v = decodeInteger<I>(*this);\n        return *this;\n    }\n\n    /**\n     * @brief scale-decodes any optional value\n     * @tparam T type of optional value\n     * @param v optional value reference\n     * @return reference to stream\n     */\n    template <class T>\n    ScaleDecoderStream& operator>>(boost::optional<T>& v)\n    {\n        using mutableT = std::remove_const_t<T>;\n\n        static_assert(std::is_default_constructible_v<mutableT>);\n\n        // optional bool is special case of optional values\n        // it is encoded as one byte instead of two\n        // as described in specification\n        if constexpr (std::is_same<mutableT, bool>::value)\n        {\n            v = decodeOptionalBool();\n            return *this;\n        }\n        // detect if optional has value\n        bool has_value = false;\n        *this >> has_value;\n        if (!has_value)\n        {\n            v.reset();\n            return *this;\n        }\n        // decode value\n        v.emplace();\n        return *this >> const_cast<mutableT&>(*v);  // NOLINT\n    }\n\n    ScaleDecoderStream& operator>>(u256& v);\n    /**\n     * @brief scale-decodes compact integer value\n     * @param v compact integer reference\n     * @return\n     */\n    ScaleDecoderStream& operator>>(CompactInteger& v);\n    ScaleDecoderStream& operator>>(s256& v)\n    {\n        u256 unsignedValue;\n        *this >> unsignedValue;\n        v = u2s(unsignedValue);\n        return *this;\n    }\n\n    template <unsigned N>\n    ScaleDecoderStream& operator>>(FixedBytes<N>& fixedData)\n    {\n        bytes decodedData;\n        *this >> decodedData;\n        if (decodedData.size() < FixedBytes<N>::size)\n        {\n            BOOST_THROW_EXCEPTION(ScaleDecodeException() << errinfo_comment(\n                                      \"exception for invalid FixedBytes, expected size:\" +\n                                      std::to_string(FixedBytes<N>::size) +\n                                      \", decoded data size:\" + std::to_string(decodedData.size())));\n        }\n        fixedData = FixedBytes<N>(decodedData.data(), FixedBytes<N>::ConstructorType::FromPointer);\n        return *this;\n    }\n    /**\n     * @brief decodes vector of items\n     * @tparam T item type\n     * @param v reference to vector\n     * @return reference to stream\n     */\n    template <class T>\n    ScaleDecoderStream& operator>>(std::vector<T>& v)\n    {\n        using mutableT = std::remove_const_t<T>;\n        using size_type = typename std::list<T>::size_type;\n\n        static_assert(std::is_default_constructible_v<mutableT>);\n\n        CompactInteger size{0u};\n        *this >> size;\n\n        auto item_count = size.convert_to<size_type>();\n        std::vector<mutableT> vec;\n        try\n        {\n            vec.resize(item_count);\n        }\n        catch (const std::bad_alloc&)\n        {\n            BOOST_THROW_EXCEPTION(\n                ScaleDecodeException()\n                << errinfo_comment(\"exception for TOO_MANY_ITEMS: \" + std::to_string(item_count)));\n        }\n        if constexpr (sizeof(T) == 1u)\n        {\n            vec.assign(m_currentIterator, m_currentIterator + item_count);\n            m_currentIterator += item_count;\n            m_currentIndex += item_count;\n        }\n        else\n        {\n            for (size_type i = 0u; i < item_count; ++i)\n            {\n                *this >> vec[i];\n            }\n        }\n        v = std::move(vec);\n        return *this;\n    }\n\n    /**\n     * @brief decodes map of pairs\n     * @tparam T item type\n     * @tparam F item type\n     * @param m reference to map\n     * @return reference to stream\n     */\n    template <class T, class F>\n    ScaleDecoderStream& operator>>(std::map<T, F>& m)\n    {\n        using mutableT = std::remove_const_t<T>;\n        static_assert(std::is_default_constructible_v<mutableT>);\n        using mutableF = std::remove_const_t<F>;\n        static_assert(std::is_default_constructible_v<mutableF>);\n\n        using size_type = typename std::map<T, F>::size_type;\n\n        CompactInteger size{0u};\n        *this >> size;\n\n        auto item_count = size.convert_to<size_type>();\n        std::map<mutableT, mutableF> map;\n        for (size_type i = 0u; i < item_count; ++i)\n        {\n            std::pair<mutableT, mutableF> p;\n            *this >> p;\n            map.emplace(std::move(p));\n        }\n        m = std::move(map);\n        return *this;\n    }\n\n    /**\n     * @brief decodes collection of items\n     * @tparam T item type\n     * @param v reference to collection\n     * @return reference to stream\n     */\n    template <class T>\n    ScaleDecoderStream& operator>>(std::list<T>& v)\n    {\n        using mutableT = std::remove_const_t<T>;\n        using size_type = typename std::list<T>::size_type;\n\n        static_assert(std::is_default_constructible_v<mutableT>);\n\n        CompactInteger size{0u};\n        *this >> size;\n\n        auto item_count = size.convert_to<size_type>();\n\n        std::list<T> lst;\n        try\n        {\n            lst.reserve(item_count);\n        }\n        catch (const std::bad_alloc&)\n        {\n            BOOST_THROW_EXCEPTION(ScaleDecodeException() << errinfo_comment(\n                                      \"exception for TOO_MANY_ITEMS\" + std::to_string(item_count)));\n        }\n\n        for (size_type i = 0u; i < item_count; ++i)\n        {\n            lst.emplace_back();\n            *this >> lst.back();\n        }\n        v = std::move(lst);\n        return *this;\n    }\n\n    /**\n     * @brief decodes array of items\n     * @tparam T item type\n     * @tparam size of the array\n     * @param a reference to the array\n     * @return reference to stream\n     */\n    template <class T, size_t size>\n    ScaleDecoderStream& operator>>(std::array<T, size>& a)\n    {\n        using mutableT = std::remove_const_t<T>;\n        for (size_t i = 0u; i < size; ++i)\n        {\n            *this >> const_cast<mutableT&>(a[i]);  // NOLINT\n        }\n        return *this;\n    }\n\n    /**\n     * @brief decodes string from stream\n     * @param v value to decode\n     * @return reference to stream\n     */\n    ScaleDecoderStream& operator>>(std::string& v);\n\n    /**\n     * @brief hasMore Checks whether n more bytes are available\n     * @param n Number of bytes to check\n     * @return True if n more bytes are available and false otherwise\n     */\n    bool hasMore(uint64_t n) const;\n\n    /**\n     * @brief takes one byte from stream and\n     * advances current byte iterator by one\n     * @return current byte\n     */\n    uint8_t nextByte()\n    {\n        if (!hasMore(1))\n        {\n            BOOST_THROW_EXCEPTION(ScaleDecodeException()\n                                  << errinfo_comment(\"nextByte exception for NOT_ENOUGH_DATA\"));\n        }\n        ++m_currentIndex;\n        return *m_currentIterator++;\n    }\n    using SizeType = gsl::span<const byte>::size_type;\n\n    gsl::span<byte const> span() const { return m_span; }\n    SizeType currentIndex() const { return m_currentIndex; }\n\nprivate:\n    bool decodeBool();\n    /**\n     * @brief special case of optional values as described in specification\n     * @return boost::optional<bool> value\n     */\n    boost::optional<bool> decodeOptionalBool();\n\n    template <size_t I, class... Ts>\n    void decodeElementOfTuple(std::tuple<Ts...>& v)\n    {\n        using T = std::remove_const_t<std::tuple_element_t<I, std::tuple<Ts...>>>;\n        *this >> const_cast<T&>(std::get<I>(v));  // NOLINT\n        if constexpr (sizeof...(Ts) > I + 1)\n        {\n            decodeElementOfTuple<I + 1>(v);\n        }\n    }\n\n    template <size_t I, class... Ts>\n    void tryDecodeAsOneOfVariant(boost::variant<Ts...>& v, size_t i)\n    {\n        using T = std::remove_const_t<std::tuple_element_t<I, std::tuple<Ts...>>>;\n        static_assert(std::is_default_constructible_v<T>);\n        if (I == i)\n        {\n            T val;\n            *this >> val;\n            v = std::forward<T>(val);\n            return;\n        }\n        if constexpr (sizeof...(Ts) > I + 1)\n        {\n            tryDecodeAsOneOfVariant<I + 1>(v, i);\n        }\n    }\n\nprivate:\n    gsl::span<byte const> m_span;\n    gsl::span<byte const>::const_iterator m_currentIterator;\n    SizeType m_currentIndex;\n};\n}  // namespace scale\n}  // namespace codec\n}  // namespace bcos", "meta": {"hexsha": "9cc31c52b27a1096d9b588c9e3596ab4b5840f3d", "size": 12796, "ext": "h", "lang": "C", "max_stars_repo_path": "bcos-framework/libcodec/scale/ScaleDecoderStream.h", "max_stars_repo_name": "xueying4402/FISCO-BCOS", "max_stars_repo_head_hexsha": "737e08752e8904c7c24e3737f8f46bf5327ef792", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bcos-framework/libcodec/scale/ScaleDecoderStream.h", "max_issues_repo_name": "xueying4402/FISCO-BCOS", "max_issues_repo_head_hexsha": "737e08752e8904c7c24e3737f8f46bf5327ef792", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 267.0, "max_issues_repo_issues_event_min_datetime": "2021-03-01T02:12:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-17T08:18:34.000Z", "max_forks_repo_path": "bcos-framework/libcodec/scale/ScaleDecoderStream.h", "max_forks_repo_name": "xueying4402/FISCO-BCOS", "max_forks_repo_head_hexsha": "737e08752e8904c7c24e3737f8f46bf5327ef792", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2021-02-22T03:47:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-06T06:41:02.000Z", "avg_line_length": 29.2814645309, "max_line_length": 100, "alphanum_fraction": 0.5750234448, "num_tokens": 3085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1561048856673274, "lm_q2_score": 0.024053550795599545, "lm_q1q2_score": 0.0037548767968403184}}
{"text": "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\n#pragma once\n\n#include <gsl/span>\n\n#include \"core/common/common.h\"\n#include \"core/optimizer/graph_transformer.h\"\n\nnamespace onnxruntime {\n\nstruct FreeDimensionOverride;\n\n/**\n@Class FreeDimensionOverrideTransformer\n\nTransformer that overrides free dimensions in the graph with the specific value\nthat matches the denotation for that dimension.\n*/\nclass FreeDimensionOverrideTransformer : public GraphTransformer {\n public:\n  explicit FreeDimensionOverrideTransformer(gsl::span<const FreeDimensionOverride> overrides_to_apply);\n\n private:\n  Status ApplyImpl(Graph& graph, bool& modified, int graph_level) const override;\n\n  std::map<std::string, int64_t> dimension_override_by_denotation_;\n};\n\n}  // namespace onnxruntime\n", "meta": {"hexsha": "d92ac47a08455c5f01f65a7a755a18285e2f0c68", "size": 817, "ext": "h", "lang": "C", "max_stars_repo_path": "onnxruntime/core/optimizer/free_dim_override_transformer.h", "max_stars_repo_name": "mohammad1ta/onnxruntime", "max_stars_repo_head_hexsha": "9ed85987e3cc4c76cdbbec0f1aa84be7660adb43", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "onnxruntime/core/optimizer/free_dim_override_transformer.h", "max_issues_repo_name": "mohammad1ta/onnxruntime", "max_issues_repo_head_hexsha": "9ed85987e3cc4c76cdbbec0f1aa84be7660adb43", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "onnxruntime/core/optimizer/free_dim_override_transformer.h", "max_forks_repo_name": "mohammad1ta/onnxruntime", "max_forks_repo_head_hexsha": "9ed85987e3cc4c76cdbbec0f1aa84be7660adb43", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.53125, "max_line_length": 103, "alphanum_fraction": 0.7992656059, "num_tokens": 165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1460872619191501, "lm_q2_score": 0.02556521345925426, "lm_q1q2_score": 0.0037347520346410587}}
{"text": "\n#pragma once\n\n#include <gsl/gsl>\n\n#include \"exception.h\"\n#include <fmt/format.h>\n#include \"mathutil.h\"\n#include \"stringutil.h\"\n#include \"version.h\"\n#include \"stopwatch.h\"\n#include \"logging.h\"\n", "meta": {"hexsha": "6a6f32d3d6bf38f882acda17e29846606acdabbb", "size": 193, "ext": "h", "lang": "C", "max_stars_repo_path": "Infrastructure/include/infrastructure/infrastructure.h", "max_stars_repo_name": "edoipi/TemplePlus", "max_stars_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 69.0, "max_stars_repo_stars_event_min_datetime": "2015-05-05T14:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T06:13:04.000Z", "max_issues_repo_path": "Infrastructure/include/infrastructure/infrastructure.h", "max_issues_repo_name": "edoipi/TemplePlus", "max_issues_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 457.0, "max_issues_repo_issues_event_min_datetime": "2015-05-01T22:07:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T02:19:10.000Z", "max_forks_repo_path": "Infrastructure/include/infrastructure/infrastructure.h", "max_forks_repo_name": "edoipi/TemplePlus", "max_forks_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2016-02-04T21:19:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T23:14:51.000Z", "avg_line_length": 14.8461538462, "max_line_length": 23, "alphanum_fraction": 0.7150259067, "num_tokens": 50, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.1480471829959148, "lm_q2_score": 0.025178843940802505, "lm_q1q2_score": 0.003727656916529569}}
{"text": "#ifndef OPENMC_TALLIES_FILTER_CELL_H\n#define OPENMC_TALLIES_FILTER_CELL_H\n\n#include <cstdint>\n#include <unordered_map>\n\n#include <gsl/gsl>\n\n#include \"openmc/tallies/filter.h\"\n#include \"openmc/vector.h\"\n\nnamespace openmc {\n\n//==============================================================================\n//! Specifies which geometric cells tally events reside in.\n//==============================================================================\n\nclass CellFilter : public Filter\n{\npublic:\n  //----------------------------------------------------------------------------\n  // Constructors, destructors\n\n  ~CellFilter() = default;\n\n  //----------------------------------------------------------------------------\n  // Methods\n\n  std::string type() const override {return \"cell\";}\n\n  void from_xml(pugi::xml_node node) override;\n\n  void get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match)\n  const override;\n\n  void to_statepoint(hid_t filter_group) const override;\n\n  std::string text_label(int bin) const override;\n\n  //----------------------------------------------------------------------------\n  // Accessors\n\n  const vector<int32_t>& cells() const { return cells_; }\n\n  void set_cells(gsl::span<int32_t> cells);\n\nprotected:\n  //----------------------------------------------------------------------------\n  // Data members\n\n  //! The indices of the cells binned by this filter.\n  vector<int32_t> cells_;\n\n  //! A map from cell indices to filter bin indices.\n  std::unordered_map<int32_t, int> map_;\n};\n\n} // namespace openmc\n#endif // OPENMC_TALLIES_FILTER_CELL_H\n", "meta": {"hexsha": "e4180148f45473b0cbc3e6c6aaa3d37f2c85b2e8", "size": 1592, "ext": "h", "lang": "C", "max_stars_repo_path": "include/openmc/tallies/filter_cell.h", "max_stars_repo_name": "cjwyett/openmc", "max_stars_repo_head_hexsha": "a9e85f4d5b59d133c17caccf4704a032184841d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-30T13:08:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-30T13:08:45.000Z", "max_issues_repo_path": "include/openmc/tallies/filter_cell.h", "max_issues_repo_name": "cjwyett/openmc", "max_issues_repo_head_hexsha": "a9e85f4d5b59d133c17caccf4704a032184841d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-05-22T07:57:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-21T17:34:35.000Z", "max_forks_repo_path": "include/openmc/tallies/filter_cell.h", "max_forks_repo_name": "cjwyett/openmc", "max_forks_repo_head_hexsha": "a9e85f4d5b59d133c17caccf4704a032184841d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5333333333, "max_line_length": 84, "alphanum_fraction": 0.5125628141, "num_tokens": 300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11920292202211755, "lm_q2_score": 0.031143831771250078, "lm_q1q2_score": 0.00371243575009827}}
{"text": "/*\nMPCOTool:\nThe Multi-Purposes Calibration and Optimization Tool. A software to perform\ncalibrations or optimizations of empirical parameters.\n\nAUTHORS: Javier Burguete and Borja Latorre.\n\nCopyright 2012-2019, AUTHORS.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n    1. Redistributions of source code must retain the above copyright notice,\n        this list of conditions and the following disclaimer.\n\n    2. Redistributions in binary form must reproduce the above copyright notice,\n        this list of conditions and the following disclaimer in the\n        documentation and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY AUTHORS ``AS IS'' AND ANY EXPRESS OR IMPLIED\nWARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT\nSHALL AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\nBUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING\nIN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY\nOF SUCH DAMAGE.\n*/\n\n/**\n * \\file interface.c\n * \\brief Source file to define the graphical interface functions.\n * \\authors Javier Burguete and Borja Latorre.\n * \\copyright Copyright 2012-2019, all rights reserved.\n */\n#define _GNU_SOURCE\n#include \"config.h\"\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <gsl/gsl_rng.h>\n#include <libxml/parser.h>\n#include <libintl.h>\n#include <glib.h>\n#include <glib/gstdio.h>\n#include <json-glib/json-glib.h>\n#ifdef G_OS_WIN32\n#include <windows.h>\n#endif\n#if HAVE_MPI\n#include <mpi.h>\n#endif\n#include <gio/gio.h>\n#include <gtk/gtk.h>\n#include \"genetic/genetic.h\"\n#include \"utils.h\"\n#include \"experiment.h\"\n#include \"variable.h\"\n#include \"input.h\"\n#include \"optimize.h\"\n#include \"interface.h\"\n\n#define DEBUG_INTERFACE 0       ///< Macro to debug interface functions.\n\n/**\n * \\def INPUT_FILE\n * \\brief Macro to define the initial input file.\n */\n#ifdef G_OS_WIN32\n#define INPUT_FILE \"test-ga-win.xml\"\n#else\n#define INPUT_FILE \"test-ga.xml\"\n#endif\n\nWindow window[1];\n///< Window struct to define the main interface window.\n\nstatic const char *logo[] = {\n  \"32 32 3 1\",\n  \"     c None\",\n  \".    c #0000FF\",\n  \"+    c #FF0000\",\n  \"                                \",\n  \"                                \",\n  \"                                \",\n  \"     .      .      .      .     \",\n  \"     .      .      .      .     \",\n  \"     .      .      .      .     \",\n  \"     .      .      .      .     \",\n  \"     .      .     +++     .     \",\n  \"     .      .    +++++    .     \",\n  \"     .      .    +++++    .     \",\n  \"     .      .    +++++    .     \",\n  \"    +++     .     +++    +++    \",\n  \"   +++++    .      .    +++++   \",\n  \"   +++++    .      .    +++++   \",\n  \"   +++++    .      .    +++++   \",\n  \"    +++     .      .     +++    \",\n  \"     .      .      .      .     \",\n  \"     .     +++     .      .     \",\n  \"     .    +++++    .      .     \",\n  \"     .    +++++    .      .     \",\n  \"     .    +++++    .      .     \",\n  \"     .     +++     .      .     \",\n  \"     .      .      .      .     \",\n  \"     .      .      .      .     \",\n  \"     .      .      .      .     \",\n  \"     .      .      .      .     \",\n  \"     .      .      .      .     \",\n  \"     .      .      .      .     \",\n  \"     .      .      .      .     \",\n  \"                                \",\n  \"                                \",\n  \"                                \"\n};                              ///< Logo pixmap.\n\n/*\nconst char * logo[] = {\n\"32 32 3 1\",\n\"     c #FFFFFFFFFFFF\",\n\".    c #00000000FFFF\",\n\"X    c #FFFF00000000\",\n\"                                \",\n\"                                \",\n\"                                \",\n\"     .      .      .      .     \",\n\"     .      .      .      .     \",\n\"     .      .      .      .     \",\n\"     .      .      .      .     \",\n\"     .      .     XXX     .     \",\n\"     .      .    XXXXX    .     \",\n\"     .      .    XXXXX    .     \",\n\"     .      .    XXXXX    .     \",\n\"    XXX     .     XXX    XXX    \",\n\"   XXXXX    .      .    XXXXX   \",\n\"   XXXXX    .      .    XXXXX   \",\n\"   XXXXX    .      .    XXXXX   \",\n\"    XXX     .      .     XXX    \",\n\"     .      .      .      .     \",\n\"     .     XXX     .      .     \",\n\"     .    XXXXX    .      .     \",\n\"     .    XXXXX    .      .     \",\n\"     .    XXXXX    .      .     \",\n\"     .     XXX     .      .     \",\n\"     .      .      .      .     \",\n\"     .      .      .      .     \",\n\"     .      .      .      .     \",\n\"     .      .      .      .     \",\n\"     .      .      .      .     \",\n\"     .      .      .      .     \",\n\"     .      .      .      .     \",\n\"                                \",\n\"                                \",\n\"                                \"};\n*/\n\nstatic Options options[1];\n///< Options struct to define the options dialog.\nstatic Running running[1];\n///< Running struct to define the running dialog.\n\n/**\n * Function to save the hill climbing method data in a XML node.\n */\nstatic void\ninput_save_climbing_xml (xmlNode * node)        ///< XML node.\n{\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"input_save_climbing_xml: start\\n\");\n#endif\n  if (input->nsteps)\n    {\n      xml_node_set_uint (node, (const xmlChar *) LABEL_NSTEPS, input->nsteps);\n      if (input->relaxation != DEFAULT_RELAXATION)\n        xml_node_set_float (node, (const xmlChar *) LABEL_RELAXATION,\n                            input->relaxation);\n      switch (input->climbing)\n        {\n        case CLIMBING_METHOD_COORDINATES:\n          xmlSetProp (node, (const xmlChar *) LABEL_CLIMBING,\n                      (const xmlChar *) LABEL_COORDINATES);\n          break;\n        default:\n          xmlSetProp (node, (const xmlChar *) LABEL_CLIMBING,\n                      (const xmlChar *) LABEL_RANDOM);\n          xml_node_set_uint (node, (const xmlChar *) LABEL_NESTIMATES,\n                             input->nestimates);\n        }\n    }\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"input_save_climbing_xml: end\\n\");\n#endif\n}\n\n/**\n * Function to save the hill climbing method data in a JSON node.\n */\nstatic void\ninput_save_climbing_json (JsonNode * node)      ///< JSON node.\n{\n  JsonObject *object;\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"input_save_climbing_json: start\\n\");\n#endif\n  object = json_node_get_object (node);\n  if (input->nsteps)\n    {\n      json_object_set_uint (object, LABEL_NSTEPS, input->nsteps);\n      if (input->relaxation != DEFAULT_RELAXATION)\n        json_object_set_float (object, LABEL_RELAXATION, input->relaxation);\n      switch (input->climbing)\n        {\n        case CLIMBING_METHOD_COORDINATES:\n          json_object_set_string_member (object, LABEL_CLIMBING,\n                                         LABEL_COORDINATES);\n          break;\n        default:\n          json_object_set_string_member (object, LABEL_CLIMBING, LABEL_RANDOM);\n          json_object_set_uint (object, LABEL_NESTIMATES, input->nestimates);\n        }\n    }\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"input_save_climbing_json: end\\n\");\n#endif\n}\n\n/**\n * Function to save the input file in XML format.\n */\nstatic inline void\ninput_save_xml (xmlDoc * doc)   ///< xmlDoc struct.\n{\n  unsigned int i, j;\n  char *buffer;\n  xmlNode *node, *child;\n  GFile *file, *file2;\n\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"input_save_xml: start\\n\");\n#endif\n\n  // Setting root XML node\n  node = xmlNewDocNode (doc, 0, (const xmlChar *) LABEL_OPTIMIZE, 0);\n  xmlDocSetRootElement (doc, node);\n\n  // Adding properties to the root XML node\n  if (xmlStrcmp\n      ((const xmlChar *) input->result, (const xmlChar *) result_name))\n    xmlSetProp (node, (const xmlChar *) LABEL_RESULT_FILE,\n                (xmlChar *) input->result);\n  if (xmlStrcmp\n      ((const xmlChar *) input->variables, (const xmlChar *) variables_name))\n    xmlSetProp (node, (const xmlChar *) LABEL_VARIABLES_FILE,\n                (xmlChar *) input->variables);\n  file = g_file_new_for_path (input->directory);\n  file2 = g_file_new_for_path (input->simulator);\n  buffer = g_file_get_relative_path (file, file2);\n  g_object_unref (file2);\n  xmlSetProp (node, (const xmlChar *) LABEL_SIMULATOR, (xmlChar *) buffer);\n  g_free (buffer);\n  if (input->evaluator)\n    {\n      file2 = g_file_new_for_path (input->evaluator);\n      buffer = g_file_get_relative_path (file, file2);\n      g_object_unref (file2);\n      if (xmlStrlen ((xmlChar *) buffer))\n        xmlSetProp (node, (const xmlChar *) LABEL_EVALUATOR,\n                    (xmlChar *) buffer);\n      g_free (buffer);\n    }\n  if (input->seed != DEFAULT_RANDOM_SEED)\n    xml_node_set_uint (node, (const xmlChar *) LABEL_SEED, input->seed);\n\n  // Setting the algorithm\n  buffer = (char *) g_slice_alloc (64);\n  switch (input->algorithm)\n    {\n    case ALGORITHM_MONTE_CARLO:\n      xmlSetProp (node, (const xmlChar *) LABEL_ALGORITHM,\n                  (const xmlChar *) LABEL_MONTE_CARLO);\n      snprintf (buffer, 64, \"%u\", input->nsimulations);\n      xmlSetProp (node, (const xmlChar *) LABEL_NSIMULATIONS,\n                  (xmlChar *) buffer);\n      snprintf (buffer, 64, \"%u\", input->niterations);\n      xmlSetProp (node, (const xmlChar *) LABEL_NITERATIONS,\n                  (xmlChar *) buffer);\n      snprintf (buffer, 64, \"%.3lg\", input->tolerance);\n      xmlSetProp (node, (const xmlChar *) LABEL_TOLERANCE, (xmlChar *) buffer);\n      snprintf (buffer, 64, \"%u\", input->nbest);\n      xmlSetProp (node, (const xmlChar *) LABEL_NBEST, (xmlChar *) buffer);\n      input_save_climbing_xml (node);\n      break;\n    case ALGORITHM_SWEEP:\n      xmlSetProp (node, (const xmlChar *) LABEL_ALGORITHM,\n                  (const xmlChar *) LABEL_SWEEP);\n      snprintf (buffer, 64, \"%u\", input->niterations);\n      xmlSetProp (node, (const xmlChar *) LABEL_NITERATIONS,\n                  (xmlChar *) buffer);\n      snprintf (buffer, 64, \"%.3lg\", input->tolerance);\n      xmlSetProp (node, (const xmlChar *) LABEL_TOLERANCE, (xmlChar *) buffer);\n      snprintf (buffer, 64, \"%u\", input->nbest);\n      xmlSetProp (node, (const xmlChar *) LABEL_NBEST, (xmlChar *) buffer);\n      input_save_climbing_xml (node);\n      break;\n    case ALGORITHM_ORTHOGONAL:\n      xmlSetProp (node, (const xmlChar *) LABEL_ALGORITHM,\n                  (const xmlChar *) LABEL_ORTHOGONAL);\n      snprintf (buffer, 64, \"%u\", input->niterations);\n      xmlSetProp (node, (const xmlChar *) LABEL_NITERATIONS,\n                  (xmlChar *) buffer);\n      snprintf (buffer, 64, \"%.3lg\", input->tolerance);\n      xmlSetProp (node, (const xmlChar *) LABEL_TOLERANCE, (xmlChar *) buffer);\n      snprintf (buffer, 64, \"%u\", input->nbest);\n      xmlSetProp (node, (const xmlChar *) LABEL_NBEST, (xmlChar *) buffer);\n      input_save_climbing_xml (node);\n      break;\n    default:\n      xmlSetProp (node, (const xmlChar *) LABEL_ALGORITHM,\n                  (const xmlChar *) LABEL_GENETIC);\n      snprintf (buffer, 64, \"%u\", input->nsimulations);\n      xmlSetProp (node, (const xmlChar *) LABEL_NPOPULATION,\n                  (xmlChar *) buffer);\n      snprintf (buffer, 64, \"%u\", input->niterations);\n      xmlSetProp (node, (const xmlChar *) LABEL_NGENERATIONS,\n                  (xmlChar *) buffer);\n      snprintf (buffer, 64, \"%.3lg\", input->mutation_ratio);\n      xmlSetProp (node, (const xmlChar *) LABEL_MUTATION, (xmlChar *) buffer);\n      snprintf (buffer, 64, \"%.3lg\", input->reproduction_ratio);\n      xmlSetProp (node, (const xmlChar *) LABEL_REPRODUCTION,\n                  (xmlChar *) buffer);\n      snprintf (buffer, 64, \"%.3lg\", input->adaptation_ratio);\n      xmlSetProp (node, (const xmlChar *) LABEL_ADAPTATION, (xmlChar *) buffer);\n      break;\n    }\n  g_slice_free1 (64, buffer);\n  if (input->threshold != 0.)\n    xml_node_set_float (node, (const xmlChar *) LABEL_THRESHOLD,\n                        input->threshold);\n\n  // Setting the experimental data\n  for (i = 0; i < input->nexperiments; ++i)\n    {\n      child = xmlNewChild (node, 0, (const xmlChar *) LABEL_EXPERIMENT, 0);\n      xmlSetProp (child, (const xmlChar *) LABEL_NAME,\n                  (xmlChar *) input->experiment[i].name);\n      if (input->experiment[i].weight != 1.)\n        xml_node_set_float (child, (const xmlChar *) LABEL_WEIGHT,\n                            input->experiment[i].weight);\n      for (j = 0; j < input->experiment->ninputs; ++j)\n        xmlSetProp (child, (const xmlChar *) stencil[j],\n                    (xmlChar *) input->experiment[i].stencil[j]);\n    }\n\n  // Setting the variables data\n  for (i = 0; i < input->nvariables; ++i)\n    {\n      child = xmlNewChild (node, 0, (const xmlChar *) LABEL_VARIABLE, 0);\n      xmlSetProp (child, (const xmlChar *) LABEL_NAME,\n                  (xmlChar *) input->variable[i].name);\n      xml_node_set_float (child, (const xmlChar *) LABEL_MINIMUM,\n                          input->variable[i].rangemin);\n      if (input->variable[i].rangeminabs != -G_MAXDOUBLE)\n        xml_node_set_float (child, (const xmlChar *) LABEL_ABSOLUTE_MINIMUM,\n                            input->variable[i].rangeminabs);\n      xml_node_set_float (child, (const xmlChar *) LABEL_MAXIMUM,\n                          input->variable[i].rangemax);\n      if (input->variable[i].rangemaxabs != G_MAXDOUBLE)\n        xml_node_set_float (child, (const xmlChar *) LABEL_ABSOLUTE_MAXIMUM,\n                            input->variable[i].rangemaxabs);\n      if (input->variable[i].precision != DEFAULT_PRECISION)\n        xml_node_set_uint (child, (const xmlChar *) LABEL_PRECISION,\n                           input->variable[i].precision);\n      if (input->algorithm == ALGORITHM_SWEEP\n          || input->algorithm == ALGORITHM_ORTHOGONAL)\n        xml_node_set_uint (child, (const xmlChar *) LABEL_NSWEEPS,\n                           input->variable[i].nsweeps);\n      else if (input->algorithm == ALGORITHM_GENETIC)\n        xml_node_set_uint (child, (const xmlChar *) LABEL_NBITS,\n                           input->variable[i].nbits);\n      if (input->nsteps)\n        xml_node_set_float (child, (const xmlChar *) LABEL_STEP,\n                            input->variable[i].step);\n    }\n\n  // Saving the error norm\n  switch (input->norm)\n    {\n    case ERROR_NORM_MAXIMUM:\n      xmlSetProp (node, (const xmlChar *) LABEL_NORM,\n                  (const xmlChar *) LABEL_MAXIMUM);\n      break;\n    case ERROR_NORM_P:\n      xmlSetProp (node, (const xmlChar *) LABEL_NORM,\n                  (const xmlChar *) LABEL_P);\n      xml_node_set_float (node, (const xmlChar *) LABEL_P, input->p);\n      break;\n    case ERROR_NORM_TAXICAB:\n      xmlSetProp (node, (const xmlChar *) LABEL_NORM,\n                  (const xmlChar *) LABEL_TAXICAB);\n    }\n\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"input_save: end\\n\");\n#endif\n}\n\n/**\n * Function to save the input file in JSON format.\n */\nstatic inline void\ninput_save_json (JsonGenerator * generator)     ///< JsonGenerator struct.\n{\n  unsigned int i, j;\n  char *buffer;\n  JsonNode *node, *child;\n  JsonObject *object;\n  JsonArray *array;\n  GFile *file, *file2;\n\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"input_save_json: start\\n\");\n#endif\n\n  // Setting root JSON node\n  node = json_node_new (JSON_NODE_OBJECT);\n  object = json_node_get_object (node);\n  json_generator_set_root (generator, node);\n\n  // Adding properties to the root JSON node\n  if (strcmp (input->result, result_name))\n    json_object_set_string_member (object, LABEL_RESULT_FILE, input->result);\n  if (strcmp (input->variables, variables_name))\n    json_object_set_string_member (object, LABEL_VARIABLES_FILE,\n                                   input->variables);\n  file = g_file_new_for_path (input->directory);\n  file2 = g_file_new_for_path (input->simulator);\n  buffer = g_file_get_relative_path (file, file2);\n  g_object_unref (file2);\n  json_object_set_string_member (object, LABEL_SIMULATOR, buffer);\n  g_free (buffer);\n  if (input->evaluator)\n    {\n      file2 = g_file_new_for_path (input->evaluator);\n      buffer = g_file_get_relative_path (file, file2);\n      g_object_unref (file2);\n      if (strlen (buffer))\n        json_object_set_string_member (object, LABEL_EVALUATOR, buffer);\n      g_free (buffer);\n    }\n  if (input->seed != DEFAULT_RANDOM_SEED)\n    json_object_set_uint (object, LABEL_SEED, input->seed);\n\n  // Setting the algorithm\n  buffer = (char *) g_slice_alloc (64);\n  switch (input->algorithm)\n    {\n    case ALGORITHM_MONTE_CARLO:\n      json_object_set_string_member (object, LABEL_ALGORITHM,\n                                     LABEL_MONTE_CARLO);\n      snprintf (buffer, 64, \"%u\", input->nsimulations);\n      json_object_set_string_member (object, LABEL_NSIMULATIONS, buffer);\n      snprintf (buffer, 64, \"%u\", input->niterations);\n      json_object_set_string_member (object, LABEL_NITERATIONS, buffer);\n      snprintf (buffer, 64, \"%.3lg\", input->tolerance);\n      json_object_set_string_member (object, LABEL_TOLERANCE, buffer);\n      snprintf (buffer, 64, \"%u\", input->nbest);\n      json_object_set_string_member (object, LABEL_NBEST, buffer);\n      input_save_climbing_json (node);\n      break;\n    case ALGORITHM_SWEEP:\n      json_object_set_string_member (object, LABEL_ALGORITHM, LABEL_SWEEP);\n      snprintf (buffer, 64, \"%u\", input->niterations);\n      json_object_set_string_member (object, LABEL_NITERATIONS, buffer);\n      snprintf (buffer, 64, \"%.3lg\", input->tolerance);\n      json_object_set_string_member (object, LABEL_TOLERANCE, buffer);\n      snprintf (buffer, 64, \"%u\", input->nbest);\n      json_object_set_string_member (object, LABEL_NBEST, buffer);\n      input_save_climbing_json (node);\n      break;\n    case ALGORITHM_ORTHOGONAL:\n      json_object_set_string_member (object, LABEL_ALGORITHM, LABEL_ORTHOGONAL);\n      snprintf (buffer, 64, \"%u\", input->niterations);\n      json_object_set_string_member (object, LABEL_NITERATIONS, buffer);\n      snprintf (buffer, 64, \"%.3lg\", input->tolerance);\n      json_object_set_string_member (object, LABEL_TOLERANCE, buffer);\n      snprintf (buffer, 64, \"%u\", input->nbest);\n      json_object_set_string_member (object, LABEL_NBEST, buffer);\n      input_save_climbing_json (node);\n      break;\n    default:\n      json_object_set_string_member (object, LABEL_ALGORITHM, LABEL_GENETIC);\n      snprintf (buffer, 64, \"%u\", input->nsimulations);\n      json_object_set_string_member (object, LABEL_NPOPULATION, buffer);\n      snprintf (buffer, 64, \"%u\", input->niterations);\n      json_object_set_string_member (object, LABEL_NGENERATIONS, buffer);\n      snprintf (buffer, 64, \"%.3lg\", input->mutation_ratio);\n      json_object_set_string_member (object, LABEL_MUTATION, buffer);\n      snprintf (buffer, 64, \"%.3lg\", input->reproduction_ratio);\n      json_object_set_string_member (object, LABEL_REPRODUCTION, buffer);\n      snprintf (buffer, 64, \"%.3lg\", input->adaptation_ratio);\n      json_object_set_string_member (object, LABEL_ADAPTATION, buffer);\n      break;\n    }\n  g_slice_free1 (64, buffer);\n  if (input->threshold != 0.)\n    json_object_set_float (object, LABEL_THRESHOLD, input->threshold);\n\n  // Setting the experimental data\n  array = json_array_new ();\n  for (i = 0; i < input->nexperiments; ++i)\n    {\n      child = json_node_new (JSON_NODE_OBJECT);\n      object = json_node_get_object (child);\n      json_object_set_string_member (object, LABEL_NAME,\n                                     input->experiment[i].name);\n      if (input->experiment[i].weight != 1.)\n        json_object_set_float (object, LABEL_WEIGHT,\n                               input->experiment[i].weight);\n      for (j = 0; j < input->experiment->ninputs; ++j)\n        json_object_set_string_member (object, stencil[j],\n                                       input->experiment[i].stencil[j]);\n      json_array_add_element (array, child);\n    }\n  json_object_set_array_member (object, LABEL_EXPERIMENTS, array);\n\n  // Setting the variables data\n  array = json_array_new ();\n  for (i = 0; i < input->nvariables; ++i)\n    {\n      child = json_node_new (JSON_NODE_OBJECT);\n      object = json_node_get_object (child);\n      json_object_set_string_member (object, LABEL_NAME,\n                                     input->variable[i].name);\n      json_object_set_float (object, LABEL_MINIMUM,\n                             input->variable[i].rangemin);\n      if (input->variable[i].rangeminabs != -G_MAXDOUBLE)\n        json_object_set_float (object, LABEL_ABSOLUTE_MINIMUM,\n                               input->variable[i].rangeminabs);\n      json_object_set_float (object, LABEL_MAXIMUM,\n                             input->variable[i].rangemax);\n      if (input->variable[i].rangemaxabs != G_MAXDOUBLE)\n        json_object_set_float (object, LABEL_ABSOLUTE_MAXIMUM,\n                               input->variable[i].rangemaxabs);\n      if (input->variable[i].precision != DEFAULT_PRECISION)\n        json_object_set_uint (object, LABEL_PRECISION,\n                              input->variable[i].precision);\n      if (input->algorithm == ALGORITHM_SWEEP\n          || input->algorithm == ALGORITHM_ORTHOGONAL)\n        json_object_set_uint (object, LABEL_NSWEEPS,\n                              input->variable[i].nsweeps);\n      else if (input->algorithm == ALGORITHM_GENETIC)\n        json_object_set_uint (object, LABEL_NBITS, input->variable[i].nbits);\n      if (input->nsteps)\n        json_object_set_float (object, LABEL_STEP, input->variable[i].step);\n      json_array_add_element (array, child);\n    }\n  json_object_set_array_member (object, LABEL_VARIABLES, array);\n\n  // Saving the error norm\n  switch (input->norm)\n    {\n    case ERROR_NORM_MAXIMUM:\n      json_object_set_string_member (object, LABEL_NORM, LABEL_MAXIMUM);\n      break;\n    case ERROR_NORM_P:\n      json_object_set_string_member (object, LABEL_NORM, LABEL_P);\n      json_object_set_float (object, LABEL_P, input->p);\n      break;\n    case ERROR_NORM_TAXICAB:\n      json_object_set_string_member (object, LABEL_NORM, LABEL_TAXICAB);\n    }\n\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"input_save_json: end\\n\");\n#endif\n}\n\n/**\n * Function to save the input file.\n */\nstatic inline void\ninput_save (char *filename)     ///< Input file name.\n{\n  xmlDoc *doc;\n  JsonGenerator *generator;\n\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"input_save: start\\n\");\n#endif\n\n  // Getting the input file directory\n  input->name = g_path_get_basename (filename);\n  input->directory = g_path_get_dirname (filename);\n\n  if (input->type == INPUT_TYPE_XML)\n    {\n      // Opening the input file\n      doc = xmlNewDoc ((const xmlChar *) \"1.0\");\n      input_save_xml (doc);\n\n      // Saving the XML file\n      xmlSaveFormatFile (filename, doc, 1);\n\n      // Freeing memory\n      xmlFreeDoc (doc);\n    }\n  else\n    {\n      // Opening the input file\n      generator = json_generator_new ();\n      json_generator_set_pretty (generator, TRUE);\n      input_save_json (generator);\n\n      // Saving the JSON file\n      json_generator_to_file (generator, filename, NULL);\n\n      // Freeing memory\n      g_object_unref (generator);\n    }\n\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"input_save: end\\n\");\n#endif\n}\n\n/**\n * Function to open the options dialog.\n */\nstatic void\noptions_new ()\n{\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"options_new: start\\n\");\n#endif\n  options->label_seed = (GtkLabel *)\n    gtk_label_new (_(\"Pseudo-random numbers generator seed\"));\n  options->spin_seed = (GtkSpinButton *)\n    gtk_spin_button_new_with_range (0., (gdouble) G_MAXULONG, 1.);\n  gtk_widget_set_tooltip_text\n    (GTK_WIDGET (options->spin_seed),\n     _(\"Seed to init the pseudo-random numbers generator\"));\n  gtk_spin_button_set_value (options->spin_seed, (gdouble) input->seed);\n  options->label_threads = (GtkLabel *)\n    gtk_label_new (_(\"Threads number for the stochastic algorithm\"));\n  options->spin_threads\n    = (GtkSpinButton *) gtk_spin_button_new_with_range (1., 64., 1.);\n  gtk_widget_set_tooltip_text\n    (GTK_WIDGET (options->spin_threads),\n     _(\"Number of threads to perform the calibration/optimization for \"\n       \"the stochastic algorithm\"));\n  gtk_spin_button_set_value (options->spin_threads, (gdouble) nthreads);\n  options->label_climbing = (GtkLabel *)\n    gtk_label_new (_(\"Threads number for the hill climbing method\"));\n  options->spin_climbing =\n    (GtkSpinButton *) gtk_spin_button_new_with_range (1., 64., 1.);\n  gtk_widget_set_tooltip_text\n    (GTK_WIDGET (options->spin_climbing),\n     _(\"Number of threads to perform the calibration/optimization for the \"\n       \"hill climbing method\"));\n  gtk_spin_button_set_value (options->spin_climbing,\n                             (gdouble) nthreads_climbing);\n  options->grid = (GtkGrid *) gtk_grid_new ();\n  gtk_grid_attach (options->grid, GTK_WIDGET (options->label_seed), 0, 0, 1, 1);\n  gtk_grid_attach (options->grid, GTK_WIDGET (options->spin_seed), 1, 0, 1, 1);\n  gtk_grid_attach (options->grid, GTK_WIDGET (options->label_threads),\n                   0, 1, 1, 1);\n  gtk_grid_attach (options->grid, GTK_WIDGET (options->spin_threads),\n                   1, 1, 1, 1);\n  gtk_grid_attach (options->grid, GTK_WIDGET (options->label_climbing), 0, 2, 1,\n                   1);\n  gtk_grid_attach (options->grid, GTK_WIDGET (options->spin_climbing), 1, 2, 1,\n                   1);\n  gtk_widget_show_all (GTK_WIDGET (options->grid));\n  options->dialog = (GtkDialog *)\n    gtk_dialog_new_with_buttons (_(\"Options\"),\n                                 window->window,\n                                 GTK_DIALOG_MODAL,\n                                 _(\"_OK\"), GTK_RESPONSE_OK,\n                                 _(\"_Cancel\"), GTK_RESPONSE_CANCEL, NULL);\n  gtk_container_add\n    (GTK_CONTAINER (gtk_dialog_get_content_area (options->dialog)),\n     GTK_WIDGET (options->grid));\n  if (gtk_dialog_run (options->dialog) == GTK_RESPONSE_OK)\n    {\n      input->seed\n        = (unsigned long int) gtk_spin_button_get_value (options->spin_seed);\n      nthreads = gtk_spin_button_get_value_as_int (options->spin_threads);\n      nthreads_climbing\n        = gtk_spin_button_get_value_as_int (options->spin_climbing);\n    }\n  gtk_widget_destroy (GTK_WIDGET (options->dialog));\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"options_new: end\\n\");\n#endif\n}\n\n/**\n * Function to open the running dialog.\n */\nstatic inline void\nrunning_new ()\n{\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"running_new: start\\n\");\n#endif\n  running->label = (GtkLabel *) gtk_label_new (_(\"Calculating ...\"));\n  running->spinner = (GtkSpinner *) gtk_spinner_new ();\n  running->grid = (GtkGrid *) gtk_grid_new ();\n  gtk_grid_attach (running->grid, GTK_WIDGET (running->label), 0, 0, 1, 1);\n  gtk_grid_attach (running->grid, GTK_WIDGET (running->spinner), 0, 1, 1, 1);\n  running->dialog = (GtkDialog *)\n    gtk_dialog_new_with_buttons (_(\"Calculating\"),\n                                 window->window, GTK_DIALOG_MODAL, NULL, NULL);\n  gtk_container_add (GTK_CONTAINER\n                     (gtk_dialog_get_content_area (running->dialog)),\n                     GTK_WIDGET (running->grid));\n  gtk_spinner_start (running->spinner);\n  gtk_widget_show_all (GTK_WIDGET (running->dialog));\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"running_new: end\\n\");\n#endif\n}\n\n/**\n * Function to get the stochastic algorithm number.\n *\n * \\return Stochastic algorithm number.\n */\nstatic unsigned int\nwindow_get_algorithm ()\n{\n  unsigned int i;\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_get_algorithm: start\\n\");\n#endif\n  i = gtk_array_get_active (window->button_algorithm, NALGORITHMS);\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_get_algorithm: %u\\n\", i);\n  fprintf (stderr, \"window_get_algorithm: end\\n\");\n#endif\n  return i;\n}\n\n/**\n * Function to get the hill climbing method number.\n *\n * \\return Hill climbing method number.\n */\nstatic unsigned int\nwindow_get_climbing ()\n{\n  unsigned int i;\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_get_climbing: start\\n\");\n#endif\n  i = gtk_array_get_active (window->button_climbing, NCLIMBINGS);\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_get_climbing: %u\\n\", i);\n  fprintf (stderr, \"window_get_climbing: end\\n\");\n#endif\n  return i;\n}\n\n/**\n * Function to get the norm method number.\n *\n * \\return Norm method number.\n */\nstatic unsigned int\nwindow_get_norm ()\n{\n  unsigned int i;\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_get_norm: start\\n\");\n#endif\n  i = gtk_array_get_active (window->button_norm, NNORMS);\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_get_norm: %u\\n\", i);\n  fprintf (stderr, \"window_get_norm: end\\n\");\n#endif\n  return i;\n}\n\n/**\n * Function to save the hill climbing method data in the input file.\n */\nstatic void\nwindow_save_climbing ()\n{\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_save_climbing: start\\n\");\n#endif\n  if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (window->check_climbing)))\n    {\n      input->nsteps = gtk_spin_button_get_value_as_int (window->spin_steps);\n      input->relaxation = gtk_spin_button_get_value (window->spin_relaxation);\n      switch (window_get_climbing ())\n        {\n        case CLIMBING_METHOD_COORDINATES:\n          input->climbing = CLIMBING_METHOD_COORDINATES;\n          break;\n        default:\n          input->climbing = CLIMBING_METHOD_RANDOM;\n          input->nestimates\n            = gtk_spin_button_get_value_as_int (window->spin_estimates);\n        }\n    }\n  else\n    input->nsteps = 0;\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_save_climbing: end\\n\");\n#endif\n}\n\n/**\n * Function to save the input file.\n *\n * \\return 1 on OK, 0 on Cancel.\n */\nstatic int\nwindow_save ()\n{\n  GtkFileChooserDialog *dlg;\n  GtkFileFilter *filter1, *filter2;\n  char *buffer;\n\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_save: start\\n\");\n#endif\n\n  // Opening the saving dialog\n  dlg = (GtkFileChooserDialog *)\n    gtk_file_chooser_dialog_new (_(\"Save file\"),\n                                 window->window,\n                                 GTK_FILE_CHOOSER_ACTION_SAVE,\n                                 _(\"_Cancel\"), GTK_RESPONSE_CANCEL,\n                                 _(\"_OK\"), GTK_RESPONSE_OK, NULL);\n  gtk_file_chooser_set_do_overwrite_confirmation (GTK_FILE_CHOOSER (dlg), TRUE);\n  buffer = g_build_filename (input->directory, input->name, NULL);\n  gtk_file_chooser_set_filename (GTK_FILE_CHOOSER (dlg), buffer);\n  g_free (buffer);\n\n  // Adding XML filter\n  filter1 = (GtkFileFilter *) gtk_file_filter_new ();\n  gtk_file_filter_set_name (filter1, \"XML\");\n  gtk_file_filter_add_pattern (filter1, \"*.xml\");\n  gtk_file_filter_add_pattern (filter1, \"*.XML\");\n  gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (dlg), filter1);\n\n  // Adding JSON filter\n  filter2 = (GtkFileFilter *) gtk_file_filter_new ();\n  gtk_file_filter_set_name (filter2, \"JSON\");\n  gtk_file_filter_add_pattern (filter2, \"*.json\");\n  gtk_file_filter_add_pattern (filter2, \"*.JSON\");\n  gtk_file_filter_add_pattern (filter2, \"*.js\");\n  gtk_file_filter_add_pattern (filter2, \"*.JS\");\n  gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (dlg), filter2);\n\n  if (input->type == INPUT_TYPE_XML)\n    gtk_file_chooser_set_filter (GTK_FILE_CHOOSER (dlg), filter1);\n  else\n    gtk_file_chooser_set_filter (GTK_FILE_CHOOSER (dlg), filter2);\n\n  // If OK response then saving\n  if (gtk_dialog_run (GTK_DIALOG (dlg)) == GTK_RESPONSE_OK)\n    {\n      // Setting input file type\n      filter1 = gtk_file_chooser_get_filter (GTK_FILE_CHOOSER (dlg));\n      buffer = (char *) gtk_file_filter_get_name (filter1);\n      if (!strcmp (buffer, \"XML\"))\n        input->type = INPUT_TYPE_XML;\n      else\n        input->type = INPUT_TYPE_JSON;\n\n      // Adding properties to the root XML node\n      input->simulator = gtk_file_chooser_get_filename\n        (GTK_FILE_CHOOSER (window->button_simulator));\n      if (gtk_toggle_button_get_active\n          (GTK_TOGGLE_BUTTON (window->check_evaluator)))\n        input->evaluator = gtk_file_chooser_get_filename\n          (GTK_FILE_CHOOSER (window->button_evaluator));\n      else\n        input->evaluator = NULL;\n      if (input->type == INPUT_TYPE_XML)\n        {\n          input->result\n            = (char *) xmlStrdup ((const xmlChar *)\n                                  gtk_entry_get_text (window->entry_result));\n          input->variables\n            = (char *) xmlStrdup ((const xmlChar *)\n                                  gtk_entry_get_text (window->entry_variables));\n        }\n      else\n        {\n          input->result = g_strdup (gtk_entry_get_text (window->entry_result));\n          input->variables =\n            g_strdup (gtk_entry_get_text (window->entry_variables));\n        }\n\n      // Setting the algorithm\n      switch (window_get_algorithm ())\n        {\n        case ALGORITHM_MONTE_CARLO:\n          input->algorithm = ALGORITHM_MONTE_CARLO;\n          input->nsimulations\n            = gtk_spin_button_get_value_as_int (window->spin_simulations);\n          input->niterations\n            = gtk_spin_button_get_value_as_int (window->spin_iterations);\n          input->tolerance = gtk_spin_button_get_value (window->spin_tolerance);\n          input->nbest = gtk_spin_button_get_value_as_int (window->spin_bests);\n          window_save_climbing ();\n          break;\n        case ALGORITHM_SWEEP:\n          input->algorithm = ALGORITHM_SWEEP;\n          input->niterations\n            = gtk_spin_button_get_value_as_int (window->spin_iterations);\n          input->tolerance = gtk_spin_button_get_value (window->spin_tolerance);\n          input->nbest = gtk_spin_button_get_value_as_int (window->spin_bests);\n          window_save_climbing ();\n          break;\n        case ALGORITHM_ORTHOGONAL:\n          input->algorithm = ALGORITHM_ORTHOGONAL;\n          input->niterations\n            = gtk_spin_button_get_value_as_int (window->spin_iterations);\n          input->tolerance = gtk_spin_button_get_value (window->spin_tolerance);\n          input->nbest = gtk_spin_button_get_value_as_int (window->spin_bests);\n          window_save_climbing ();\n          break;\n        default:\n          input->algorithm = ALGORITHM_GENETIC;\n          input->nsimulations\n            = gtk_spin_button_get_value_as_int (window->spin_population);\n          input->niterations\n            = gtk_spin_button_get_value_as_int (window->spin_generations);\n          input->mutation_ratio\n            = gtk_spin_button_get_value (window->spin_mutation);\n          input->reproduction_ratio\n            = gtk_spin_button_get_value (window->spin_reproduction);\n          input->adaptation_ratio\n            = gtk_spin_button_get_value (window->spin_adaptation);\n          break;\n        }\n      input->norm = window_get_norm ();\n      input->p = gtk_spin_button_get_value (window->spin_p);\n      input->threshold = gtk_spin_button_get_value (window->spin_threshold);\n\n      // Saving the XML file\n      buffer = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dlg));\n      input_save (buffer);\n\n      // Closing and freeing memory\n      g_free (buffer);\n      gtk_widget_destroy (GTK_WIDGET (dlg));\n#if DEBUG_INTERFACE\n      fprintf (stderr, \"window_save: end\\n\");\n#endif\n      return 1;\n    }\n\n  // Closing and freeing memory\n  gtk_widget_destroy (GTK_WIDGET (dlg));\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_save: end\\n\");\n#endif\n  return 0;\n}\n\n/**\n * Function to run a optimization.\n */\nstatic void\nwindow_run ()\n{\n  unsigned int i;\n  char *msg, *msg2, buffer[64], buffer2[64];\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_run: start\\n\");\n#endif\n  if (!window_save ())\n    {\n#if DEBUG_INTERFACE\n      fprintf (stderr, \"window_run: end\\n\");\n#endif\n      return;\n    }\n  running_new ();\n  while (gtk_events_pending ())\n    gtk_main_iteration ();\n  optimize_open ();\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_run: closing running dialog\\n\");\n#endif\n  gtk_spinner_stop (running->spinner);\n  gtk_widget_destroy (GTK_WIDGET (running->dialog));\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_run: displaying results\\n\");\n#endif\n  snprintf (buffer, 64, \"error = %.15le\\n\", optimize->error_old[0]);\n  msg2 = g_strdup (buffer);\n  for (i = 0; i < optimize->nvariables; ++i, msg2 = msg)\n    {\n      snprintf (buffer, 64, \"%s = %s\\n\",\n                input->variable[i].name, format[input->variable[i].precision]);\n      snprintf (buffer2, 64, buffer, optimize->value_old[i]);\n      msg = g_strconcat (msg2, buffer2, NULL);\n      g_free (msg2);\n    }\n  snprintf (buffer, 64, \"%s = %.6lg s\", _(\"Calculation time\"),\n            optimize->calculation_time);\n  msg = g_strconcat (msg2, buffer, NULL);\n  g_free (msg2);\n  show_message (_(\"Best result\"), msg, INFO_TYPE);\n  g_free (msg);\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_run: freeing memory\\n\");\n#endif\n  optimize_free ();\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_run: end\\n\");\n#endif\n}\n\n/**\n * Function to show a help dialog.\n */\nstatic void\nwindow_help ()\n{\n  char *buffer, *buffer2;\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_help: start\\n\");\n#endif\n  buffer2 = g_build_filename (window->application_directory, \"..\", \"manuals\",\n                              _(\"user-manual.pdf\"), NULL);\n  buffer = g_filename_to_uri (buffer2, NULL, NULL);\n  g_free (buffer2);\n#if GTK_MINOR_VERSION >= 22\n  gtk_show_uri_on_window (window->window, buffer, GDK_CURRENT_TIME, NULL);\n#else\n  gtk_show_uri (NULL, buffer, GDK_CURRENT_TIME, NULL);\n#endif\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_help: uri=%s\\n\", buffer);\n#endif\n  g_free (buffer);\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_help: end\\n\");\n#endif\n}\n\n/**\n * Function to show an about dialog.\n */\nstatic void\nwindow_about ()\n{\n  static const gchar *authors[] = {\n    \"Javier Burguete Tolosa <jburguete@eead.csic.es>\",\n    \"Borja Latorre Garc\u00e9s <borja.latorre@csic.es>\",\n    NULL\n  };\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_about: start\\n\");\n#endif\n  gtk_show_about_dialog\n    (window->window,\n     \"program_name\", \"MPCOTool\",\n     \"comments\",\n     _(\"The Multi-Purposes Calibration and Optimization Tool.\\n\"\n       \"A software to perform calibrations or optimizations of empirical \"\n       \"parameters\"),\n     \"authors\", authors,\n     \"translator-credits\",\n     \"Javier Burguete Tolosa <jburguete@eead.csic.es> \"\n     \"(english, french and spanish)\\n\"\n     \"U\u011fur \u00c7ayo\u011flu (german)\",\n     \"version\", \"4.0.1\",\n     \"copyright\", \"Copyright 2012-2019 Javier Burguete Tolosa\",\n     \"logo\", window->logo,\n     \"website\", \"https://github.com/jburguete/mpcotool\",\n     \"license-type\", GTK_LICENSE_BSD, NULL);\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_about: end\\n\");\n#endif\n}\n\n/**\n * Function to update hill climbing method widgets view in the main window.\n */\nstatic void\nwindow_update_climbing ()\n{\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_update_climbing: start\\n\");\n#endif\n  gtk_widget_show (GTK_WIDGET (window->check_climbing));\n  if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (window->check_climbing)))\n    {\n      gtk_widget_show (GTK_WIDGET (window->grid_climbing));\n      gtk_widget_show (GTK_WIDGET (window->label_step));\n      gtk_widget_show (GTK_WIDGET (window->spin_step));\n    }\n  switch (window_get_climbing ())\n    {\n    case CLIMBING_METHOD_COORDINATES:\n      gtk_widget_hide (GTK_WIDGET (window->label_estimates));\n      gtk_widget_hide (GTK_WIDGET (window->spin_estimates));\n      break;\n    default:\n      gtk_widget_show (GTK_WIDGET (window->label_estimates));\n      gtk_widget_show (GTK_WIDGET (window->spin_estimates));\n    }\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_update_climbing: end\\n\");\n#endif\n}\n\n/**\n * Function to update the main window view.\n */\nstatic void\nwindow_update ()\n{\n  unsigned int i;\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_update: start\\n\");\n#endif\n  gtk_widget_set_sensitive\n    (GTK_WIDGET (window->button_evaluator),\n     gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON\n                                   (window->check_evaluator)));\n  gtk_widget_hide (GTK_WIDGET (window->label_simulations));\n  gtk_widget_hide (GTK_WIDGET (window->spin_simulations));\n  gtk_widget_hide (GTK_WIDGET (window->label_iterations));\n  gtk_widget_hide (GTK_WIDGET (window->spin_iterations));\n  gtk_widget_hide (GTK_WIDGET (window->label_tolerance));\n  gtk_widget_hide (GTK_WIDGET (window->spin_tolerance));\n  gtk_widget_hide (GTK_WIDGET (window->label_bests));\n  gtk_widget_hide (GTK_WIDGET (window->spin_bests));\n  gtk_widget_hide (GTK_WIDGET (window->label_population));\n  gtk_widget_hide (GTK_WIDGET (window->spin_population));\n  gtk_widget_hide (GTK_WIDGET (window->label_generations));\n  gtk_widget_hide (GTK_WIDGET (window->spin_generations));\n  gtk_widget_hide (GTK_WIDGET (window->label_mutation));\n  gtk_widget_hide (GTK_WIDGET (window->spin_mutation));\n  gtk_widget_hide (GTK_WIDGET (window->label_reproduction));\n  gtk_widget_hide (GTK_WIDGET (window->spin_reproduction));\n  gtk_widget_hide (GTK_WIDGET (window->label_adaptation));\n  gtk_widget_hide (GTK_WIDGET (window->spin_adaptation));\n  gtk_widget_hide (GTK_WIDGET (window->label_sweeps));\n  gtk_widget_hide (GTK_WIDGET (window->spin_sweeps));\n  gtk_widget_hide (GTK_WIDGET (window->label_bits));\n  gtk_widget_hide (GTK_WIDGET (window->spin_bits));\n  gtk_widget_hide (GTK_WIDGET (window->check_climbing));\n  gtk_widget_hide (GTK_WIDGET (window->grid_climbing));\n  gtk_widget_hide (GTK_WIDGET (window->label_step));\n  gtk_widget_hide (GTK_WIDGET (window->spin_step));\n  gtk_widget_hide (GTK_WIDGET (window->label_p));\n  gtk_widget_hide (GTK_WIDGET (window->spin_p));\n  i = gtk_spin_button_get_value_as_int (window->spin_iterations);\n  switch (window_get_algorithm ())\n    {\n    case ALGORITHM_MONTE_CARLO:\n      gtk_widget_show (GTK_WIDGET (window->label_simulations));\n      gtk_widget_show (GTK_WIDGET (window->spin_simulations));\n      gtk_widget_show (GTK_WIDGET (window->label_iterations));\n      gtk_widget_show (GTK_WIDGET (window->spin_iterations));\n      if (i > 1)\n        {\n          gtk_widget_show (GTK_WIDGET (window->label_tolerance));\n          gtk_widget_show (GTK_WIDGET (window->spin_tolerance));\n          gtk_widget_show (GTK_WIDGET (window->label_bests));\n          gtk_widget_show (GTK_WIDGET (window->spin_bests));\n        }\n      window_update_climbing ();\n      break;\n    case ALGORITHM_SWEEP:\n    case ALGORITHM_ORTHOGONAL:\n      gtk_widget_show (GTK_WIDGET (window->label_iterations));\n      gtk_widget_show (GTK_WIDGET (window->spin_iterations));\n      if (i > 1)\n        {\n          gtk_widget_show (GTK_WIDGET (window->label_tolerance));\n          gtk_widget_show (GTK_WIDGET (window->spin_tolerance));\n          gtk_widget_show (GTK_WIDGET (window->label_bests));\n          gtk_widget_show (GTK_WIDGET (window->spin_bests));\n        }\n      gtk_widget_show (GTK_WIDGET (window->label_sweeps));\n      gtk_widget_show (GTK_WIDGET (window->spin_sweeps));\n      gtk_widget_show (GTK_WIDGET (window->check_climbing));\n      window_update_climbing ();\n      break;\n    default:\n      gtk_widget_show (GTK_WIDGET (window->label_population));\n      gtk_widget_show (GTK_WIDGET (window->spin_population));\n      gtk_widget_show (GTK_WIDGET (window->label_generations));\n      gtk_widget_show (GTK_WIDGET (window->spin_generations));\n      gtk_widget_show (GTK_WIDGET (window->label_mutation));\n      gtk_widget_show (GTK_WIDGET (window->spin_mutation));\n      gtk_widget_show (GTK_WIDGET (window->label_reproduction));\n      gtk_widget_show (GTK_WIDGET (window->spin_reproduction));\n      gtk_widget_show (GTK_WIDGET (window->label_adaptation));\n      gtk_widget_show (GTK_WIDGET (window->spin_adaptation));\n      gtk_widget_show (GTK_WIDGET (window->label_bits));\n      gtk_widget_show (GTK_WIDGET (window->spin_bits));\n    }\n  gtk_widget_set_sensitive\n    (GTK_WIDGET (window->button_remove_experiment), input->nexperiments > 1);\n  gtk_widget_set_sensitive\n    (GTK_WIDGET (window->button_remove_variable), input->nvariables > 1);\n  for (i = 0; i < input->experiment->ninputs; ++i)\n    {\n      gtk_widget_show (GTK_WIDGET (window->check_template[i]));\n      gtk_widget_show (GTK_WIDGET (window->button_template[i]));\n      gtk_widget_set_sensitive (GTK_WIDGET (window->check_template[i]), 0);\n      gtk_widget_set_sensitive (GTK_WIDGET (window->button_template[i]), 1);\n      g_signal_handler_block\n        (window->check_template[i], window->id_template[i]);\n      g_signal_handler_block (window->button_template[i], window->id_input[i]);\n      gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON\n                                    (window->check_template[i]), 1);\n      g_signal_handler_unblock (window->button_template[i],\n                                window->id_input[i]);\n      g_signal_handler_unblock (window->check_template[i],\n                                window->id_template[i]);\n    }\n  if (i > 0)\n    {\n      gtk_widget_set_sensitive (GTK_WIDGET (window->check_template[i - 1]), 1);\n      gtk_widget_set_sensitive (GTK_WIDGET (window->button_template[i - 1]),\n                                gtk_toggle_button_get_active\n                                GTK_TOGGLE_BUTTON (window->check_template\n                                                   [i - 1]));\n    }\n  if (i < MAX_NINPUTS)\n    {\n      gtk_widget_show (GTK_WIDGET (window->check_template[i]));\n      gtk_widget_show (GTK_WIDGET (window->button_template[i]));\n      gtk_widget_set_sensitive (GTK_WIDGET (window->check_template[i]), 1);\n      gtk_widget_set_sensitive\n        (GTK_WIDGET (window->button_template[i]),\n         gtk_toggle_button_get_active\n         GTK_TOGGLE_BUTTON (window->check_template[i]));\n      g_signal_handler_block\n        (window->check_template[i], window->id_template[i]);\n      g_signal_handler_block (window->button_template[i], window->id_input[i]);\n      gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON\n                                    (window->check_template[i]), 0);\n      g_signal_handler_unblock (window->button_template[i],\n                                window->id_input[i]);\n      g_signal_handler_unblock (window->check_template[i],\n                                window->id_template[i]);\n    }\n  while (++i < MAX_NINPUTS)\n    {\n      gtk_widget_hide (GTK_WIDGET (window->check_template[i]));\n      gtk_widget_hide (GTK_WIDGET (window->button_template[i]));\n    }\n  gtk_widget_set_sensitive\n    (GTK_WIDGET (window->spin_minabs),\n     gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (window->check_minabs)));\n  gtk_widget_set_sensitive\n    (GTK_WIDGET (window->spin_maxabs),\n     gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (window->check_maxabs)));\n  if (window_get_norm () == ERROR_NORM_P)\n    {\n      gtk_widget_show (GTK_WIDGET (window->label_p));\n      gtk_widget_show (GTK_WIDGET (window->spin_p));\n    }\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_update: end\\n\");\n#endif\n}\n\n/**\n * Function to avoid memory errors changing the algorithm.\n */\nstatic void\nwindow_set_algorithm ()\n{\n  int i;\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_set_algorithm: start\\n\");\n#endif\n  i = window_get_algorithm ();\n  switch (i)\n    {\n    case ALGORITHM_SWEEP:\n    case ALGORITHM_ORTHOGONAL:\n      i = gtk_combo_box_get_active (GTK_COMBO_BOX (window->combo_variable));\n      if (i < 0)\n        i = 0;\n      gtk_spin_button_set_value (window->spin_sweeps,\n                                 (gdouble) input->variable[i].nsweeps);\n      break;\n    case ALGORITHM_GENETIC:\n      i = gtk_combo_box_get_active (GTK_COMBO_BOX (window->combo_variable));\n      if (i < 0)\n        i = 0;\n      gtk_spin_button_set_value (window->spin_bits,\n                                 (gdouble) input->variable[i].nbits);\n    }\n  window_update ();\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_set_algorithm: end\\n\");\n#endif\n}\n\n/**\n * Function to set the experiment data in the main window.\n */\nstatic void\nwindow_set_experiment ()\n{\n  unsigned int i, j;\n  char *buffer1, *buffer2;\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_set_experiment: start\\n\");\n#endif\n  i = gtk_combo_box_get_active (GTK_COMBO_BOX (window->combo_experiment));\n  gtk_spin_button_set_value (window->spin_weight, input->experiment[i].weight);\n  buffer1 = gtk_combo_box_text_get_active_text (window->combo_experiment);\n  buffer2 = g_build_filename (input->directory, buffer1, NULL);\n  g_free (buffer1);\n  g_signal_handler_block\n    (window->button_experiment, window->id_experiment_name);\n  gtk_file_chooser_set_filename\n    (GTK_FILE_CHOOSER (window->button_experiment), buffer2);\n  g_signal_handler_unblock\n    (window->button_experiment, window->id_experiment_name);\n  g_free (buffer2);\n  for (j = 0; j < input->experiment->ninputs; ++j)\n    {\n      g_signal_handler_block (window->button_template[j], window->id_input[j]);\n      buffer2 =\n        g_build_filename (input->directory, input->experiment[i].stencil[j],\n                          NULL);\n      gtk_file_chooser_set_filename (GTK_FILE_CHOOSER\n                                     (window->button_template[j]), buffer2);\n      g_free (buffer2);\n      g_signal_handler_unblock\n        (window->button_template[j], window->id_input[j]);\n    }\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_set_experiment: end\\n\");\n#endif\n}\n\n/**\n * Function to remove an experiment in the main window.\n */\nstatic void\nwindow_remove_experiment ()\n{\n  unsigned int i, j;\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_remove_experiment: start\\n\");\n#endif\n  i = gtk_combo_box_get_active (GTK_COMBO_BOX (window->combo_experiment));\n  g_signal_handler_block (window->combo_experiment, window->id_experiment);\n  gtk_combo_box_text_remove (window->combo_experiment, i);\n  g_signal_handler_unblock (window->combo_experiment, window->id_experiment);\n  experiment_free (input->experiment + i, input->type);\n  --input->nexperiments;\n  for (j = i; j < input->nexperiments; ++j)\n    memcpy (input->experiment + j, input->experiment + j + 1,\n            sizeof (Experiment));\n  j = input->nexperiments - 1;\n  if (i > j)\n    i = j;\n  for (j = 0; j < input->experiment->ninputs; ++j)\n    g_signal_handler_block (window->button_template[j], window->id_input[j]);\n  g_signal_handler_block\n    (window->button_experiment, window->id_experiment_name);\n  gtk_combo_box_set_active (GTK_COMBO_BOX (window->combo_experiment), i);\n  g_signal_handler_unblock\n    (window->button_experiment, window->id_experiment_name);\n  for (j = 0; j < input->experiment->ninputs; ++j)\n    g_signal_handler_unblock (window->button_template[j], window->id_input[j]);\n  window_update ();\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_remove_experiment: end\\n\");\n#endif\n}\n\n/**\n * Function to add an experiment in the main window.\n */\nstatic void\nwindow_add_experiment ()\n{\n  unsigned int i, j;\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_add_experiment: start\\n\");\n#endif\n  i = gtk_combo_box_get_active (GTK_COMBO_BOX (window->combo_experiment));\n  g_signal_handler_block (window->combo_experiment, window->id_experiment);\n  gtk_combo_box_text_insert_text\n    (window->combo_experiment, i, input->experiment[i].name);\n  g_signal_handler_unblock (window->combo_experiment, window->id_experiment);\n  input->experiment = (Experiment *) g_realloc\n    (input->experiment, (input->nexperiments + 1) * sizeof (Experiment));\n  for (j = input->nexperiments - 1; j > i; --j)\n    memcpy (input->experiment + j + 1, input->experiment + j,\n            sizeof (Experiment));\n  input->experiment[j + 1].weight = input->experiment[j].weight;\n  input->experiment[j + 1].ninputs = input->experiment[j].ninputs;\n  if (input->type == INPUT_TYPE_XML)\n    {\n      input->experiment[j + 1].name\n        = (char *) xmlStrdup ((xmlChar *) input->experiment[j].name);\n      for (j = 0; j < input->experiment->ninputs; ++j)\n        input->experiment[i + 1].stencil[j]\n          = (char *) xmlStrdup ((xmlChar *) input->experiment[i].stencil[j]);\n    }\n  else\n    {\n      input->experiment[j + 1].name = g_strdup (input->experiment[j].name);\n      for (j = 0; j < input->experiment->ninputs; ++j)\n        input->experiment[i + 1].stencil[j]\n          = g_strdup (input->experiment[i].stencil[j]);\n    }\n  ++input->nexperiments;\n  for (j = 0; j < input->experiment->ninputs; ++j)\n    g_signal_handler_block (window->button_template[j], window->id_input[j]);\n  g_signal_handler_block\n    (window->button_experiment, window->id_experiment_name);\n  gtk_combo_box_set_active (GTK_COMBO_BOX (window->combo_experiment), i + 1);\n  g_signal_handler_unblock\n    (window->button_experiment, window->id_experiment_name);\n  for (j = 0; j < input->experiment->ninputs; ++j)\n    g_signal_handler_unblock (window->button_template[j], window->id_input[j]);\n  window_update ();\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_add_experiment: end\\n\");\n#endif\n}\n\n/**\n * Function to set the experiment name in the main window.\n */\nstatic void\nwindow_name_experiment ()\n{\n  unsigned int i;\n  char *buffer;\n  GFile *file1, *file2;\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_name_experiment: start\\n\");\n#endif\n  i = gtk_combo_box_get_active (GTK_COMBO_BOX (window->combo_experiment));\n  file1\n    = gtk_file_chooser_get_file (GTK_FILE_CHOOSER (window->button_experiment));\n  file2 = g_file_new_for_path (input->directory);\n  buffer = g_file_get_relative_path (file2, file1);\n  g_signal_handler_block (window->combo_experiment, window->id_experiment);\n  gtk_combo_box_text_remove (window->combo_experiment, i);\n  gtk_combo_box_text_insert_text (window->combo_experiment, i, buffer);\n  gtk_combo_box_set_active (GTK_COMBO_BOX (window->combo_experiment), i);\n  g_signal_handler_unblock (window->combo_experiment, window->id_experiment);\n  g_free (buffer);\n  g_object_unref (file2);\n  g_object_unref (file1);\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_name_experiment: end\\n\");\n#endif\n}\n\n/**\n * Function to update the experiment weight in the main window.\n */\nstatic void\nwindow_weight_experiment ()\n{\n  unsigned int i;\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_weight_experiment: start\\n\");\n#endif\n  i = gtk_combo_box_get_active (GTK_COMBO_BOX (window->combo_experiment));\n  input->experiment[i].weight = gtk_spin_button_get_value (window->spin_weight);\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_weight_experiment: end\\n\");\n#endif\n}\n\n/**\n * Function to update the experiment input templates number in the main window.\n */\nstatic void\nwindow_inputs_experiment ()\n{\n  unsigned int j;\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_inputs_experiment: start\\n\");\n#endif\n  j = input->experiment->ninputs - 1;\n  if (j\n      && !gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON\n                                        (window->check_template[j])))\n    --input->experiment->ninputs;\n  if (input->experiment->ninputs < MAX_NINPUTS\n      && gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON\n                                       (window->check_template[j])))\n    ++input->experiment->ninputs;\n  window_update ();\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_inputs_experiment: end\\n\");\n#endif\n}\n\n/**\n * Function to update the experiment i-th input template in the main window.\n */\nstatic void\nwindow_template_experiment (void *data)\n                            ///< Callback data (i-th input template).\n{\n  unsigned int i, j;\n  char *buffer;\n  GFile *file1, *file2;\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_template_experiment: start\\n\");\n#endif\n  i = (size_t) data;\n  j = gtk_combo_box_get_active (GTK_COMBO_BOX (window->combo_experiment));\n  file1\n    = gtk_file_chooser_get_file (GTK_FILE_CHOOSER (window->button_template[i]));\n  file2 = g_file_new_for_path (input->directory);\n  buffer = g_file_get_relative_path (file2, file1);\n  if (input->type == INPUT_TYPE_XML)\n    input->experiment[j].stencil[i] = (char *) xmlStrdup ((xmlChar *) buffer);\n  else\n    input->experiment[j].stencil[i] = g_strdup (buffer);\n  g_free (buffer);\n  g_object_unref (file2);\n  g_object_unref (file1);\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_template_experiment: end\\n\");\n#endif\n}\n\n/**\n * Function to set the variable data in the main window.\n */\nstatic void\nwindow_set_variable ()\n{\n  unsigned int i;\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_set_variable: start\\n\");\n#endif\n  i = gtk_combo_box_get_active (GTK_COMBO_BOX (window->combo_variable));\n  g_signal_handler_block (window->entry_variable, window->id_variable_label);\n  gtk_entry_set_text (window->entry_variable, input->variable[i].name);\n  g_signal_handler_unblock (window->entry_variable, window->id_variable_label);\n  gtk_spin_button_set_value (window->spin_min, input->variable[i].rangemin);\n  gtk_spin_button_set_value (window->spin_max, input->variable[i].rangemax);\n  if (input->variable[i].rangeminabs != -G_MAXDOUBLE)\n    {\n      gtk_spin_button_set_value (window->spin_minabs,\n                                 input->variable[i].rangeminabs);\n      gtk_toggle_button_set_active\n        (GTK_TOGGLE_BUTTON (window->check_minabs), 1);\n    }\n  else\n    {\n      gtk_spin_button_set_value (window->spin_minabs, -G_MAXDOUBLE);\n      gtk_toggle_button_set_active\n        (GTK_TOGGLE_BUTTON (window->check_minabs), 0);\n    }\n  if (input->variable[i].rangemaxabs != G_MAXDOUBLE)\n    {\n      gtk_spin_button_set_value (window->spin_maxabs,\n                                 input->variable[i].rangemaxabs);\n      gtk_toggle_button_set_active\n        (GTK_TOGGLE_BUTTON (window->check_maxabs), 1);\n    }\n  else\n    {\n      gtk_spin_button_set_value (window->spin_maxabs, G_MAXDOUBLE);\n      gtk_toggle_button_set_active\n        (GTK_TOGGLE_BUTTON (window->check_maxabs), 0);\n    }\n  gtk_spin_button_set_value (window->spin_precision,\n                             input->variable[i].precision);\n  gtk_spin_button_set_value (window->spin_steps, (gdouble) input->nsteps);\n  if (input->nsteps)\n    gtk_spin_button_set_value (window->spin_step, input->variable[i].step);\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_set_variable: precision[%u]=%u\\n\", i,\n           input->variable[i].precision);\n#endif\n  switch (window_get_algorithm ())\n    {\n    case ALGORITHM_SWEEP:\n    case ALGORITHM_ORTHOGONAL:\n      gtk_spin_button_set_value (window->spin_sweeps,\n                                 (gdouble) input->variable[i].nsweeps);\n#if DEBUG_INTERFACE\n      fprintf (stderr, \"window_set_variable: nsweeps[%u]=%u\\n\", i,\n               input->variable[i].nsweeps);\n#endif\n      break;\n    case ALGORITHM_GENETIC:\n      gtk_spin_button_set_value (window->spin_bits,\n                                 (gdouble) input->variable[i].nbits);\n#if DEBUG_INTERFACE\n      fprintf (stderr, \"window_set_variable: nbits[%u]=%u\\n\", i,\n               input->variable[i].nbits);\n#endif\n      break;\n    }\n  window_update ();\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_set_variable: end\\n\");\n#endif\n}\n\n/**\n * Function to remove a variable in the main window.\n */\nstatic void\nwindow_remove_variable ()\n{\n  unsigned int i, j;\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_remove_variable: start\\n\");\n#endif\n  i = gtk_combo_box_get_active (GTK_COMBO_BOX (window->combo_variable));\n  g_signal_handler_block (window->combo_variable, window->id_variable);\n  gtk_combo_box_text_remove (window->combo_variable, i);\n  g_signal_handler_unblock (window->combo_variable, window->id_variable);\n  xmlFree (input->variable[i].name);\n  --input->nvariables;\n  for (j = i; j < input->nvariables; ++j)\n    memcpy (input->variable + j, input->variable + j + 1, sizeof (Variable));\n  j = input->nvariables - 1;\n  if (i > j)\n    i = j;\n  g_signal_handler_block (window->entry_variable, window->id_variable_label);\n  gtk_combo_box_set_active (GTK_COMBO_BOX (window->combo_variable), i);\n  g_signal_handler_unblock (window->entry_variable, window->id_variable_label);\n  window_update ();\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_remove_variable: end\\n\");\n#endif\n}\n\n/**\n * Function to add a variable in the main window.\n */\nstatic void\nwindow_add_variable ()\n{\n  unsigned int i, j;\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_add_variable: start\\n\");\n#endif\n  i = gtk_combo_box_get_active (GTK_COMBO_BOX (window->combo_variable));\n  g_signal_handler_block (window->combo_variable, window->id_variable);\n  gtk_combo_box_text_insert_text (window->combo_variable, i,\n                                  input->variable[i].name);\n  g_signal_handler_unblock (window->combo_variable, window->id_variable);\n  input->variable = (Variable *) g_realloc\n    (input->variable, (input->nvariables + 1) * sizeof (Variable));\n  for (j = input->nvariables - 1; j > i; --j)\n    memcpy (input->variable + j + 1, input->variable + j, sizeof (Variable));\n  memcpy (input->variable + j + 1, input->variable + j, sizeof (Variable));\n  if (input->type == INPUT_TYPE_XML)\n    input->variable[j + 1].name\n      = (char *) xmlStrdup ((xmlChar *) input->variable[j].name);\n  else\n    input->variable[j + 1].name = g_strdup (input->variable[j].name);\n  ++input->nvariables;\n  g_signal_handler_block (window->entry_variable, window->id_variable_label);\n  gtk_combo_box_set_active (GTK_COMBO_BOX (window->combo_variable), i + 1);\n  g_signal_handler_unblock (window->entry_variable, window->id_variable_label);\n  window_update ();\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_add_variable: end\\n\");\n#endif\n}\n\n/**\n * Function to set the variable label in the main window.\n */\nstatic void\nwindow_label_variable ()\n{\n  unsigned int i;\n  const char *buffer;\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_label_variable: start\\n\");\n#endif\n  i = gtk_combo_box_get_active (GTK_COMBO_BOX (window->combo_variable));\n  buffer = gtk_entry_get_text (window->entry_variable);\n  g_signal_handler_block (window->combo_variable, window->id_variable);\n  gtk_combo_box_text_remove (window->combo_variable, i);\n  gtk_combo_box_text_insert_text (window->combo_variable, i, buffer);\n  gtk_combo_box_set_active (GTK_COMBO_BOX (window->combo_variable), i);\n  g_signal_handler_unblock (window->combo_variable, window->id_variable);\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_label_variable: end\\n\");\n#endif\n}\n\n/**\n * Function to update the variable precision in the main window.\n */\nstatic void\nwindow_precision_variable ()\n{\n  unsigned int i;\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_precision_variable: start\\n\");\n#endif\n  i = gtk_combo_box_get_active (GTK_COMBO_BOX (window->combo_variable));\n  input->variable[i].precision\n    = (unsigned int) gtk_spin_button_get_value_as_int (window->spin_precision);\n  gtk_spin_button_set_digits (window->spin_min, input->variable[i].precision);\n  gtk_spin_button_set_digits (window->spin_max, input->variable[i].precision);\n  gtk_spin_button_set_digits (window->spin_minabs,\n                              input->variable[i].precision);\n  gtk_spin_button_set_digits (window->spin_maxabs,\n                              input->variable[i].precision);\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_precision_variable: end\\n\");\n#endif\n}\n\n/**\n * Function to update the variable rangemin in the main window.\n */\nstatic void\nwindow_rangemin_variable ()\n{\n  unsigned int i;\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_rangemin_variable: start\\n\");\n#endif\n  i = gtk_combo_box_get_active (GTK_COMBO_BOX (window->combo_variable));\n  input->variable[i].rangemin = gtk_spin_button_get_value (window->spin_min);\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_rangemin_variable: end\\n\");\n#endif\n}\n\n/**\n * Function to update the variable rangemax in the main window.\n */\nstatic void\nwindow_rangemax_variable ()\n{\n  unsigned int i;\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_rangemax_variable: start\\n\");\n#endif\n  i = gtk_combo_box_get_active (GTK_COMBO_BOX (window->combo_variable));\n  input->variable[i].rangemax = gtk_spin_button_get_value (window->spin_max);\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_rangemax_variable: end\\n\");\n#endif\n}\n\n/**\n * Function to update the variable rangeminabs in the main window.\n */\nstatic void\nwindow_rangeminabs_variable ()\n{\n  unsigned int i;\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_rangeminabs_variable: start\\n\");\n#endif\n  i = gtk_combo_box_get_active (GTK_COMBO_BOX (window->combo_variable));\n  input->variable[i].rangeminabs\n    = gtk_spin_button_get_value (window->spin_minabs);\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_rangeminabs_variable: end\\n\");\n#endif\n}\n\n/**\n * Function to update the variable rangemaxabs in the main window.\n */\nstatic void\nwindow_rangemaxabs_variable ()\n{\n  unsigned int i;\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_rangemaxabs_variable: start\\n\");\n#endif\n  i = gtk_combo_box_get_active (GTK_COMBO_BOX (window->combo_variable));\n  input->variable[i].rangemaxabs\n    = gtk_spin_button_get_value (window->spin_maxabs);\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_rangemaxabs_variable: end\\n\");\n#endif\n}\n\n/**\n * Function to update the variable step in the main window.\n */\nstatic void\nwindow_step_variable ()\n{\n  unsigned int i;\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_step_variable: start\\n\");\n#endif\n  i = gtk_combo_box_get_active (GTK_COMBO_BOX (window->combo_variable));\n  input->variable[i].step = gtk_spin_button_get_value (window->spin_step);\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_step_variable: end\\n\");\n#endif\n}\n\n/**\n * Function to update the variable data in the main window.\n */\nstatic void\nwindow_update_variable ()\n{\n  int i;\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_update_variable: start\\n\");\n#endif\n  i = gtk_combo_box_get_active (GTK_COMBO_BOX (window->combo_variable));\n  if (i < 0)\n    i = 0;\n  switch (window_get_algorithm ())\n    {\n    case ALGORITHM_SWEEP:\n    case ALGORITHM_ORTHOGONAL:\n      input->variable[i].nsweeps\n        = gtk_spin_button_get_value_as_int (window->spin_sweeps);\n#if DEBUG_INTERFACE\n      fprintf (stderr, \"window_update_variable: nsweeps[%d]=%u\\n\", i,\n               input->variable[i].nsweeps);\n#endif\n      break;\n    case ALGORITHM_GENETIC:\n      input->variable[i].nbits\n        = gtk_spin_button_get_value_as_int (window->spin_bits);\n#if DEBUG_INTERFACE\n      fprintf (stderr, \"window_update_variable: nbits[%d]=%u\\n\", i,\n               input->variable[i].nbits);\n#endif\n    }\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_update_variable: end\\n\");\n#endif\n}\n\n/**\n * Function to read the input data of a file.\n *\n * \\return 1 on succes, 0 on error.\n */\nstatic int\nwindow_read (char *filename)    ///< File name.\n{\n  unsigned int i;\n  char *buffer;\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_read: start\\n\");\n#endif\n\n  // Reading new input file\n  input_free ();\n  input->result = input->variables = NULL;\n  if (!input_open (filename))\n    {\n#if DEBUG_INTERFACE\n      fprintf (stderr, \"window_read: end\\n\");\n#endif\n      return 0;\n    }\n\n  // Setting GTK+ widgets data\n  gtk_entry_set_text (window->entry_result, input->result);\n  gtk_entry_set_text (window->entry_variables, input->variables);\n  buffer = g_build_filename (input->directory, input->simulator, NULL);\n  gtk_file_chooser_set_filename (GTK_FILE_CHOOSER\n                                 (window->button_simulator), buffer);\n  g_free (buffer);\n  gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (window->check_evaluator),\n                                (size_t) input->evaluator);\n  if (input->evaluator)\n    {\n      buffer = g_build_filename (input->directory, input->evaluator, NULL);\n      gtk_file_chooser_set_filename (GTK_FILE_CHOOSER\n                                     (window->button_evaluator), buffer);\n      g_free (buffer);\n    }\n  gtk_toggle_button_set_active\n    (GTK_TOGGLE_BUTTON (window->button_algorithm[input->algorithm]), TRUE);\n  switch (input->algorithm)\n    {\n    case ALGORITHM_MONTE_CARLO:\n      gtk_spin_button_set_value (window->spin_simulations,\n                                 (gdouble) input->nsimulations);\n      // fallthrough\n    case ALGORITHM_SWEEP:\n    case ALGORITHM_ORTHOGONAL:\n      gtk_spin_button_set_value (window->spin_iterations,\n                                 (gdouble) input->niterations);\n      gtk_spin_button_set_value (window->spin_bests, (gdouble) input->nbest);\n      gtk_spin_button_set_value (window->spin_tolerance, input->tolerance);\n      gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON\n                                    (window->check_climbing), input->nsteps);\n      if (input->nsteps)\n        {\n          gtk_toggle_button_set_active\n            (GTK_TOGGLE_BUTTON (window->button_climbing[input->climbing]),\n             TRUE);\n          gtk_spin_button_set_value (window->spin_steps,\n                                     (gdouble) input->nsteps);\n          gtk_spin_button_set_value (window->spin_relaxation,\n                                     (gdouble) input->relaxation);\n          switch (input->climbing)\n            {\n            case CLIMBING_METHOD_RANDOM:\n              gtk_spin_button_set_value (window->spin_estimates,\n                                         (gdouble) input->nestimates);\n            }\n        }\n      break;\n    default:\n      gtk_spin_button_set_value (window->spin_population,\n                                 (gdouble) input->nsimulations);\n      gtk_spin_button_set_value (window->spin_generations,\n                                 (gdouble) input->niterations);\n      gtk_spin_button_set_value (window->spin_mutation, input->mutation_ratio);\n      gtk_spin_button_set_value (window->spin_reproduction,\n                                 input->reproduction_ratio);\n      gtk_spin_button_set_value (window->spin_adaptation,\n                                 input->adaptation_ratio);\n    }\n  gtk_toggle_button_set_active\n    (GTK_TOGGLE_BUTTON (window->button_norm[input->norm]), TRUE);\n  gtk_spin_button_set_value (window->spin_p, input->p);\n  gtk_spin_button_set_value (window->spin_threshold, input->threshold);\n  g_signal_handler_block (window->combo_experiment, window->id_experiment);\n  g_signal_handler_block (window->button_experiment,\n                          window->id_experiment_name);\n  gtk_combo_box_text_remove_all (window->combo_experiment);\n  for (i = 0; i < input->nexperiments; ++i)\n    gtk_combo_box_text_append_text (window->combo_experiment,\n                                    input->experiment[i].name);\n  g_signal_handler_unblock\n    (window->button_experiment, window->id_experiment_name);\n  g_signal_handler_unblock (window->combo_experiment, window->id_experiment);\n  gtk_combo_box_set_active (GTK_COMBO_BOX (window->combo_experiment), 0);\n  g_signal_handler_block (window->combo_variable, window->id_variable);\n  g_signal_handler_block (window->entry_variable, window->id_variable_label);\n  gtk_combo_box_text_remove_all (window->combo_variable);\n  for (i = 0; i < input->nvariables; ++i)\n    gtk_combo_box_text_append_text (window->combo_variable,\n                                    input->variable[i].name);\n  g_signal_handler_unblock (window->entry_variable, window->id_variable_label);\n  g_signal_handler_unblock (window->combo_variable, window->id_variable);\n  gtk_combo_box_set_active (GTK_COMBO_BOX (window->combo_variable), 0);\n  window_set_variable ();\n  window_update ();\n\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_read: end\\n\");\n#endif\n  return 1;\n}\n\n/**\n * Function to open the input data.\n */\nstatic void\nwindow_open ()\n{\n  GtkFileChooserDialog *dlg;\n  GtkFileFilter *filter;\n  char *buffer, *directory, *name;\n\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_open: start\\n\");\n#endif\n\n  // Saving a backup of the current input file\n  directory = g_strdup (input->directory);\n  name = g_strdup (input->name);\n\n  // Opening dialog\n  dlg = (GtkFileChooserDialog *)\n    gtk_file_chooser_dialog_new (_(\"Open input file\"),\n                                 window->window,\n                                 GTK_FILE_CHOOSER_ACTION_OPEN,\n                                 _(\"_Cancel\"), GTK_RESPONSE_CANCEL,\n                                 _(\"_OK\"), GTK_RESPONSE_OK, NULL);\n\n  // Adding XML filter\n  filter = (GtkFileFilter *) gtk_file_filter_new ();\n  gtk_file_filter_set_name (filter, \"XML\");\n  gtk_file_filter_add_pattern (filter, \"*.xml\");\n  gtk_file_filter_add_pattern (filter, \"*.XML\");\n  gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (dlg), filter);\n\n  // Adding JSON filter\n  filter = (GtkFileFilter *) gtk_file_filter_new ();\n  gtk_file_filter_set_name (filter, \"JSON\");\n  gtk_file_filter_add_pattern (filter, \"*.json\");\n  gtk_file_filter_add_pattern (filter, \"*.JSON\");\n  gtk_file_filter_add_pattern (filter, \"*.js\");\n  gtk_file_filter_add_pattern (filter, \"*.JS\");\n  gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (dlg), filter);\n\n  // If OK saving\n  while (gtk_dialog_run (GTK_DIALOG (dlg)) == GTK_RESPONSE_OK)\n    {\n\n      // Traying to open the input file\n      buffer = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dlg));\n      if (!window_read (buffer))\n        {\n#if DEBUG_INTERFACE\n          fprintf (stderr, \"window_open: error reading input file\\n\");\n#endif\n          g_free (buffer);\n\n          // Reading backup file on error\n          buffer = g_build_filename (directory, name, NULL);\n          input->result = input->variables = NULL;\n          if (!input_open (buffer))\n            {\n\n              // Closing on backup file reading error\n#if DEBUG_INTERFACE\n              fprintf (stderr, \"window_read: error reading backup file\\n\");\n#endif\n              g_free (buffer);\n              break;\n            }\n          g_free (buffer);\n        }\n      else\n        {\n          g_free (buffer);\n          break;\n        }\n    }\n\n  // Freeing and closing\n  g_free (name);\n  g_free (directory);\n  gtk_widget_destroy (GTK_WIDGET (dlg));\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_open: end\\n\");\n#endif\n}\n\n/**\n * Function to open the main window.\n */\nvoid\nwindow_new (GtkApplication * application)       ///< GtkApplication struct.\n{\n  unsigned int i;\n  char *buffer, *buffer2, buffer3[64];\n  char *label_algorithm[NALGORITHMS] = {\n    \"_Monte-Carlo\", _(\"_Sweep\"), _(\"_Genetic\"), _(\"_Orthogonal\")\n  };\n  char *tip_algorithm[NALGORITHMS] = {\n    _(\"Monte-Carlo brute force algorithm\"),\n    _(\"Sweep brute force algorithm\"),\n    _(\"Genetic algorithm\"),\n    _(\"Orthogonal sampling brute force algorithm\"),\n  };\n  char *label_climbing[NCLIMBINGS] = {\n    _(\"_Coordinates climbing\"), _(\"_Random climbing\")\n  };\n  char *tip_climbing[NCLIMBINGS] = {\n    _(\"Coordinates climbing estimate method\"),\n    _(\"Random climbing estimate method\")\n  };\n  char *label_norm[NNORMS] = { \"L2\", \"L\u221e\", \"Lp\", \"L1\" };\n  char *tip_norm[NNORMS] = {\n    _(\"Euclidean error norm (L2)\"),\n    _(\"Maximum error norm (L\u221e)\"),\n    _(\"P error norm (Lp)\"),\n    _(\"Taxicab error norm (L1)\")\n  };\n\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_new: start\\n\");\n#endif\n\n  // Creating the window\n  window->window = main_window\n    = (GtkWindow *) gtk_application_window_new (application);\n\n  // Finish when closing the window\n  g_signal_connect_swapped (window->window, \"delete-event\",\n                            G_CALLBACK (g_application_quit),\n                            G_APPLICATION (application));\n\n  // Setting the window title\n  gtk_window_set_title (window->window, \"MPCOTool\");\n\n  // Creating the open button\n  window->button_open = (GtkToolButton *) gtk_tool_button_new\n    (gtk_image_new_from_icon_name (\"document-open\",\n                                   GTK_ICON_SIZE_LARGE_TOOLBAR), _(\"Open\"));\n  g_signal_connect (window->button_open, \"clicked\", window_open, NULL);\n\n  // Creating the save button\n  window->button_save = (GtkToolButton *) gtk_tool_button_new\n    (gtk_image_new_from_icon_name (\"document-save\",\n                                   GTK_ICON_SIZE_LARGE_TOOLBAR), _(\"Save\"));\n  g_signal_connect (window->button_save, \"clicked\", (GCallback) window_save,\n                    NULL);\n\n  // Creating the run button\n  window->button_run = (GtkToolButton *) gtk_tool_button_new\n    (gtk_image_new_from_icon_name (\"system-run\",\n                                   GTK_ICON_SIZE_LARGE_TOOLBAR), _(\"Run\"));\n  g_signal_connect (window->button_run, \"clicked\", window_run, NULL);\n\n  // Creating the options button\n  window->button_options = (GtkToolButton *) gtk_tool_button_new\n    (gtk_image_new_from_icon_name (\"preferences-system\",\n                                   GTK_ICON_SIZE_LARGE_TOOLBAR), _(\"Options\"));\n  g_signal_connect (window->button_options, \"clicked\", options_new, NULL);\n\n  // Creating the help button\n  window->button_help = (GtkToolButton *) gtk_tool_button_new\n    (gtk_image_new_from_icon_name (\"help-browser\",\n                                   GTK_ICON_SIZE_LARGE_TOOLBAR), _(\"Help\"));\n  g_signal_connect (window->button_help, \"clicked\", window_help, NULL);\n\n  // Creating the about button\n  window->button_about = (GtkToolButton *) gtk_tool_button_new\n    (gtk_image_new_from_icon_name (\"help-about\",\n                                   GTK_ICON_SIZE_LARGE_TOOLBAR), _(\"About\"));\n  g_signal_connect (window->button_about, \"clicked\", window_about, NULL);\n\n  // Creating the exit button\n  window->button_exit = (GtkToolButton *) gtk_tool_button_new\n    (gtk_image_new_from_icon_name (\"application-exit\",\n                                   GTK_ICON_SIZE_LARGE_TOOLBAR), _(\"Exit\"));\n  g_signal_connect_swapped (window->button_exit, \"clicked\",\n                            G_CALLBACK (g_application_quit),\n                            G_APPLICATION (application));\n\n  // Creating the buttons bar\n  window->bar_buttons = (GtkToolbar *) gtk_toolbar_new ();\n  gtk_toolbar_insert\n    (window->bar_buttons, GTK_TOOL_ITEM (window->button_open), 0);\n  gtk_toolbar_insert\n    (window->bar_buttons, GTK_TOOL_ITEM (window->button_save), 1);\n  gtk_toolbar_insert\n    (window->bar_buttons, GTK_TOOL_ITEM (window->button_run), 2);\n  gtk_toolbar_insert\n    (window->bar_buttons, GTK_TOOL_ITEM (window->button_options), 3);\n  gtk_toolbar_insert\n    (window->bar_buttons, GTK_TOOL_ITEM (window->button_help), 4);\n  gtk_toolbar_insert\n    (window->bar_buttons, GTK_TOOL_ITEM (window->button_about), 5);\n  gtk_toolbar_insert\n    (window->bar_buttons, GTK_TOOL_ITEM (window->button_exit), 6);\n  gtk_toolbar_set_style (window->bar_buttons, GTK_TOOLBAR_BOTH);\n\n  // Creating the simulator program label and entry\n  window->label_simulator = (GtkLabel *) gtk_label_new (_(\"Simulator program\"));\n  window->button_simulator = (GtkFileChooserButton *)\n    gtk_file_chooser_button_new (_(\"Simulator program\"),\n                                 GTK_FILE_CHOOSER_ACTION_OPEN);\n  gtk_widget_set_tooltip_text (GTK_WIDGET (window->button_simulator),\n                               _(\"Simulator program executable file\"));\n  gtk_widget_set_hexpand (GTK_WIDGET (window->button_simulator), TRUE);\n\n  // Creating the evaluator program label and entry\n  window->check_evaluator = (GtkCheckButton *)\n    gtk_check_button_new_with_mnemonic (_(\"_Evaluator program\"));\n  g_signal_connect (window->check_evaluator, \"toggled\", window_update, NULL);\n  window->button_evaluator = (GtkFileChooserButton *)\n    gtk_file_chooser_button_new (_(\"Evaluator program\"),\n                                 GTK_FILE_CHOOSER_ACTION_OPEN);\n  gtk_widget_set_tooltip_text\n    (GTK_WIDGET (window->button_evaluator),\n     _(\"Optional evaluator program executable file\"));\n\n  // Creating the results files labels and entries\n  window->label_result = (GtkLabel *) gtk_label_new (_(\"Result file\"));\n  window->entry_result = (GtkEntry *) gtk_entry_new ();\n  gtk_widget_set_tooltip_text\n    (GTK_WIDGET (window->entry_result), _(\"Best results file\"));\n  window->label_variables = (GtkLabel *) gtk_label_new (_(\"Variables file\"));\n  window->entry_variables = (GtkEntry *) gtk_entry_new ();\n  gtk_widget_set_tooltip_text\n    (GTK_WIDGET (window->entry_variables), _(\"All simulated results file\"));\n\n  // Creating the files grid and attaching widgets\n  window->grid_files = (GtkGrid *) gtk_grid_new ();\n  gtk_grid_attach (window->grid_files, GTK_WIDGET (window->label_simulator),\n                   0, 0, 1, 1);\n  gtk_grid_attach (window->grid_files, GTK_WIDGET (window->button_simulator),\n                   1, 0, 1, 1);\n  gtk_grid_attach (window->grid_files, GTK_WIDGET (window->check_evaluator),\n                   0, 1, 1, 1);\n  gtk_grid_attach (window->grid_files, GTK_WIDGET (window->button_evaluator),\n                   1, 1, 1, 1);\n  gtk_grid_attach (window->grid_files, GTK_WIDGET (window->label_result),\n                   0, 2, 1, 1);\n  gtk_grid_attach (window->grid_files, GTK_WIDGET (window->entry_result),\n                   1, 2, 1, 1);\n  gtk_grid_attach (window->grid_files, GTK_WIDGET (window->label_variables),\n                   0, 3, 1, 1);\n  gtk_grid_attach (window->grid_files, GTK_WIDGET (window->entry_variables),\n                   1, 3, 1, 1);\n\n  // Creating the algorithm properties\n  window->label_simulations = (GtkLabel *) gtk_label_new\n    (_(\"Simulations number\"));\n  window->spin_simulations\n    = (GtkSpinButton *) gtk_spin_button_new_with_range (1., 1.e12, 1.);\n  gtk_widget_set_tooltip_text\n    (GTK_WIDGET (window->spin_simulations),\n     _(\"Number of simulations to perform for each iteration\"));\n  gtk_widget_set_hexpand (GTK_WIDGET (window->spin_simulations), TRUE);\n  window->label_iterations = (GtkLabel *)\n    gtk_label_new (_(\"Iterations number\"));\n  window->spin_iterations\n    = (GtkSpinButton *) gtk_spin_button_new_with_range (1., 1.e6, 1.);\n  gtk_widget_set_tooltip_text\n    (GTK_WIDGET (window->spin_iterations), _(\"Number of iterations\"));\n  g_signal_connect\n    (window->spin_iterations, \"value-changed\", window_update, NULL);\n  gtk_widget_set_hexpand (GTK_WIDGET (window->spin_iterations), TRUE);\n  window->label_tolerance = (GtkLabel *) gtk_label_new (_(\"Tolerance\"));\n  window->spin_tolerance =\n    (GtkSpinButton *) gtk_spin_button_new_with_range (0., 1., 0.001);\n  gtk_widget_set_tooltip_text\n    (GTK_WIDGET (window->spin_tolerance),\n     _(\"Tolerance to set the variable interval on the next iteration\"));\n  window->label_bests = (GtkLabel *) gtk_label_new (_(\"Bests number\"));\n  window->spin_bests\n    = (GtkSpinButton *) gtk_spin_button_new_with_range (1., 1.e6, 1.);\n  gtk_widget_set_tooltip_text\n    (GTK_WIDGET (window->spin_bests),\n     _(\"Number of best simulations used to set the variable interval \"\n       \"on the next iteration\"));\n  window->label_population\n    = (GtkLabel *) gtk_label_new (_(\"Population number\"));\n  window->spin_population\n    = (GtkSpinButton *) gtk_spin_button_new_with_range (1., 1.e12, 1.);\n  gtk_widget_set_tooltip_text\n    (GTK_WIDGET (window->spin_population),\n     _(\"Number of population for the genetic algorithm\"));\n  gtk_widget_set_hexpand (GTK_WIDGET (window->spin_population), TRUE);\n  window->label_generations\n    = (GtkLabel *) gtk_label_new (_(\"Generations number\"));\n  window->spin_generations\n    = (GtkSpinButton *) gtk_spin_button_new_with_range (1., 1.e6, 1.);\n  gtk_widget_set_tooltip_text\n    (GTK_WIDGET (window->spin_generations),\n     _(\"Number of generations for the genetic algorithm\"));\n  window->label_mutation = (GtkLabel *) gtk_label_new (_(\"Mutation ratio\"));\n  window->spin_mutation\n    = (GtkSpinButton *) gtk_spin_button_new_with_range (0., 1., 0.001);\n  gtk_widget_set_tooltip_text\n    (GTK_WIDGET (window->spin_mutation),\n     _(\"Ratio of mutation for the genetic algorithm\"));\n  window->label_reproduction\n    = (GtkLabel *) gtk_label_new (_(\"Reproduction ratio\"));\n  window->spin_reproduction\n    = (GtkSpinButton *) gtk_spin_button_new_with_range (0., 1., 0.001);\n  gtk_widget_set_tooltip_text\n    (GTK_WIDGET (window->spin_reproduction),\n     _(\"Ratio of reproduction for the genetic algorithm\"));\n  window->label_adaptation = (GtkLabel *) gtk_label_new (_(\"Adaptation ratio\"));\n  window->spin_adaptation\n    = (GtkSpinButton *) gtk_spin_button_new_with_range (0., 1., 0.001);\n  gtk_widget_set_tooltip_text\n    (GTK_WIDGET (window->spin_adaptation),\n     _(\"Ratio of adaptation for the genetic algorithm\"));\n  window->label_threshold = (GtkLabel *) gtk_label_new (_(\"Threshold\"));\n  window->spin_threshold = (GtkSpinButton *)\n    gtk_spin_button_new_with_range (-G_MAXDOUBLE, G_MAXDOUBLE,\n                                    precision[DEFAULT_PRECISION]);\n  gtk_widget_set_tooltip_text\n    (GTK_WIDGET (window->spin_threshold),\n     _(\"Threshold in the objective function to finish the simulations\"));\n  window->scrolled_threshold =\n    (GtkScrolledWindow *) gtk_scrolled_window_new (NULL, NULL);\n  gtk_container_add (GTK_CONTAINER (window->scrolled_threshold),\n                     GTK_WIDGET (window->spin_threshold));\n//  gtk_widget_set_hexpand (GTK_WIDGET (window->scrolled_threshold), TRUE);\n//  gtk_widget_set_halign (GTK_WIDGET (window->scrolled_threshold),\n//                               GTK_ALIGN_FILL);\n\n  // Creating the hill climbing method properties\n  window->check_climbing = (GtkCheckButton *)\n    gtk_check_button_new_with_mnemonic (_(\"_Hill climbing method\"));\n  g_signal_connect (window->check_climbing, \"clicked\", window_update, NULL);\n  window->grid_climbing = (GtkGrid *) gtk_grid_new ();\n  window->button_climbing[0] = (GtkRadioButton *)\n    gtk_radio_button_new_with_mnemonic (NULL, label_climbing[0]);\n  gtk_grid_attach (window->grid_climbing,\n                   GTK_WIDGET (window->button_climbing[0]), 0, 0, 1, 1);\n  g_signal_connect (window->button_climbing[0], \"clicked\", window_update, NULL);\n  for (i = 0; ++i < NCLIMBINGS;)\n    {\n      window->button_climbing[i] = (GtkRadioButton *)\n        gtk_radio_button_new_with_mnemonic\n        (gtk_radio_button_get_group (window->button_climbing[0]),\n         label_climbing[i]);\n      gtk_widget_set_tooltip_text (GTK_WIDGET (window->button_climbing[i]),\n                                   tip_climbing[i]);\n      gtk_grid_attach (window->grid_climbing,\n                       GTK_WIDGET (window->button_climbing[i]), 0, i, 1, 1);\n      g_signal_connect (window->button_climbing[i], \"clicked\", window_update,\n                        NULL);\n    }\n  window->label_steps = (GtkLabel *) gtk_label_new (_(\"Steps number\"));\n  window->spin_steps = (GtkSpinButton *)\n    gtk_spin_button_new_with_range (1., 1.e12, 1.);\n  gtk_widget_set_hexpand (GTK_WIDGET (window->spin_steps), TRUE);\n  window->label_estimates\n    = (GtkLabel *) gtk_label_new (_(\"Climbing estimates number\"));\n  window->spin_estimates = (GtkSpinButton *)\n    gtk_spin_button_new_with_range (1., 1.e3, 1.);\n  window->label_relaxation\n    = (GtkLabel *) gtk_label_new (_(\"Relaxation parameter\"));\n  window->spin_relaxation = (GtkSpinButton *)\n    gtk_spin_button_new_with_range (0., 2., 0.001);\n  gtk_grid_attach (window->grid_climbing, GTK_WIDGET (window->label_steps),\n                   0, NCLIMBINGS, 1, 1);\n  gtk_grid_attach (window->grid_climbing, GTK_WIDGET (window->spin_steps),\n                   1, NCLIMBINGS, 1, 1);\n  gtk_grid_attach (window->grid_climbing, GTK_WIDGET (window->label_estimates),\n                   0, NCLIMBINGS + 1, 1, 1);\n  gtk_grid_attach (window->grid_climbing, GTK_WIDGET (window->spin_estimates),\n                   1, NCLIMBINGS + 1, 1, 1);\n  gtk_grid_attach (window->grid_climbing, GTK_WIDGET (window->label_relaxation),\n                   0, NCLIMBINGS + 2, 1, 1);\n  gtk_grid_attach (window->grid_climbing, GTK_WIDGET (window->spin_relaxation),\n                   1, NCLIMBINGS + 2, 1, 1);\n\n  // Creating the array of algorithms\n  window->grid_algorithm = (GtkGrid *) gtk_grid_new ();\n  window->button_algorithm[0] = (GtkRadioButton *)\n    gtk_radio_button_new_with_mnemonic (NULL, label_algorithm[0]);\n  gtk_widget_set_tooltip_text (GTK_WIDGET (window->button_algorithm[0]),\n                               tip_algorithm[0]);\n  gtk_grid_attach (window->grid_algorithm,\n                   GTK_WIDGET (window->button_algorithm[0]), 0, 0, 1, 1);\n  g_signal_connect (window->button_algorithm[0], \"clicked\",\n                    window_set_algorithm, NULL);\n  for (i = 0; ++i < NALGORITHMS;)\n    {\n      window->button_algorithm[i] = (GtkRadioButton *)\n        gtk_radio_button_new_with_mnemonic\n        (gtk_radio_button_get_group (window->button_algorithm[0]),\n         label_algorithm[i]);\n      gtk_widget_set_tooltip_text (GTK_WIDGET (window->button_algorithm[i]),\n                                   tip_algorithm[i]);\n      gtk_grid_attach (window->grid_algorithm,\n                       GTK_WIDGET (window->button_algorithm[i]), 0, i, 1, 1);\n      g_signal_connect (window->button_algorithm[i], \"clicked\",\n                        window_set_algorithm, NULL);\n    }\n  gtk_grid_attach (window->grid_algorithm,\n                   GTK_WIDGET (window->label_simulations),\n                   0, NALGORITHMS, 1, 1);\n  gtk_grid_attach (window->grid_algorithm,\n                   GTK_WIDGET (window->spin_simulations), 1, NALGORITHMS, 1, 1);\n  gtk_grid_attach (window->grid_algorithm,\n                   GTK_WIDGET (window->label_iterations),\n                   0, NALGORITHMS + 1, 1, 1);\n  gtk_grid_attach (window->grid_algorithm, GTK_WIDGET (window->spin_iterations),\n                   1, NALGORITHMS + 1, 1, 1);\n  gtk_grid_attach (window->grid_algorithm, GTK_WIDGET (window->label_tolerance),\n                   0, NALGORITHMS + 2, 1, 1);\n  gtk_grid_attach (window->grid_algorithm, GTK_WIDGET (window->spin_tolerance),\n                   1, NALGORITHMS + 2, 1, 1);\n  gtk_grid_attach (window->grid_algorithm, GTK_WIDGET (window->label_bests),\n                   0, NALGORITHMS + 3, 1, 1);\n  gtk_grid_attach (window->grid_algorithm, GTK_WIDGET (window->spin_bests),\n                   1, NALGORITHMS + 3, 1, 1);\n  gtk_grid_attach (window->grid_algorithm,\n                   GTK_WIDGET (window->label_population),\n                   0, NALGORITHMS + 4, 1, 1);\n  gtk_grid_attach (window->grid_algorithm, GTK_WIDGET (window->spin_population),\n                   1, NALGORITHMS + 4, 1, 1);\n  gtk_grid_attach (window->grid_algorithm,\n                   GTK_WIDGET (window->label_generations),\n                   0, NALGORITHMS + 5, 1, 1);\n  gtk_grid_attach (window->grid_algorithm,\n                   GTK_WIDGET (window->spin_generations),\n                   1, NALGORITHMS + 5, 1, 1);\n  gtk_grid_attach (window->grid_algorithm, GTK_WIDGET (window->label_mutation),\n                   0, NALGORITHMS + 6, 1, 1);\n  gtk_grid_attach (window->grid_algorithm, GTK_WIDGET (window->spin_mutation),\n                   1, NALGORITHMS + 6, 1, 1);\n  gtk_grid_attach (window->grid_algorithm,\n                   GTK_WIDGET (window->label_reproduction),\n                   0, NALGORITHMS + 7, 1, 1);\n  gtk_grid_attach (window->grid_algorithm,\n                   GTK_WIDGET (window->spin_reproduction),\n                   1, NALGORITHMS + 7, 1, 1);\n  gtk_grid_attach (window->grid_algorithm,\n                   GTK_WIDGET (window->label_adaptation),\n                   0, NALGORITHMS + 8, 1, 1);\n  gtk_grid_attach (window->grid_algorithm, GTK_WIDGET (window->spin_adaptation),\n                   1, NALGORITHMS + 8, 1, 1);\n  gtk_grid_attach (window->grid_algorithm, GTK_WIDGET (window->check_climbing),\n                   0, NALGORITHMS + 9, 2, 1);\n  gtk_grid_attach (window->grid_algorithm, GTK_WIDGET (window->grid_climbing),\n                   0, NALGORITHMS + 10, 2, 1);\n  gtk_grid_attach (window->grid_algorithm, GTK_WIDGET (window->label_threshold),\n                   0, NALGORITHMS + 11, 1, 1);\n  gtk_grid_attach (window->grid_algorithm,\n                   GTK_WIDGET (window->scrolled_threshold),\n                   1, NALGORITHMS + 11, 1, 1);\n  window->frame_algorithm = (GtkFrame *) gtk_frame_new (_(\"Algorithm\"));\n  gtk_container_add (GTK_CONTAINER (window->frame_algorithm),\n                     GTK_WIDGET (window->grid_algorithm));\n\n  // Creating the variable widgets\n  window->combo_variable = (GtkComboBoxText *) gtk_combo_box_text_new ();\n  gtk_widget_set_tooltip_text\n    (GTK_WIDGET (window->combo_variable), _(\"Variables selector\"));\n  window->id_variable = g_signal_connect\n    (window->combo_variable, \"changed\", window_set_variable, NULL);\n  window->button_add_variable = (GtkButton *)\n    gtk_button_new_from_icon_name (\"list-add\", GTK_ICON_SIZE_BUTTON);\n  g_signal_connect (window->button_add_variable, \"clicked\", window_add_variable,\n                    NULL);\n  gtk_widget_set_tooltip_text (GTK_WIDGET (window->button_add_variable),\n                               _(\"Add variable\"));\n  window->button_remove_variable = (GtkButton *)\n    gtk_button_new_from_icon_name (\"list-remove\", GTK_ICON_SIZE_BUTTON);\n  g_signal_connect (window->button_remove_variable, \"clicked\",\n                    window_remove_variable, NULL);\n  gtk_widget_set_tooltip_text (GTK_WIDGET (window->button_remove_variable),\n                               _(\"Remove variable\"));\n  window->label_variable = (GtkLabel *) gtk_label_new (_(\"Name\"));\n  window->entry_variable = (GtkEntry *) gtk_entry_new ();\n  gtk_widget_set_tooltip_text\n    (GTK_WIDGET (window->entry_variable), _(\"Variable name\"));\n  gtk_widget_set_hexpand (GTK_WIDGET (window->entry_variable), TRUE);\n  window->id_variable_label = g_signal_connect\n    (window->entry_variable, \"changed\", window_label_variable, NULL);\n  window->label_min = (GtkLabel *) gtk_label_new (_(\"Minimum\"));\n  window->spin_min = (GtkSpinButton *) gtk_spin_button_new_with_range\n    (-G_MAXDOUBLE, G_MAXDOUBLE, precision[DEFAULT_PRECISION]);\n  gtk_widget_set_tooltip_text\n    (GTK_WIDGET (window->spin_min), _(\"Minimum initial value of the variable\"));\n  window->scrolled_min\n    = (GtkScrolledWindow *) gtk_scrolled_window_new (NULL, NULL);\n  gtk_container_add (GTK_CONTAINER (window->scrolled_min),\n                     GTK_WIDGET (window->spin_min));\n  g_signal_connect (window->spin_min, \"value-changed\",\n                    window_rangemin_variable, NULL);\n  window->label_max = (GtkLabel *) gtk_label_new (_(\"Maximum\"));\n  window->spin_max = (GtkSpinButton *) gtk_spin_button_new_with_range\n    (-G_MAXDOUBLE, G_MAXDOUBLE, precision[DEFAULT_PRECISION]);\n  gtk_widget_set_tooltip_text\n    (GTK_WIDGET (window->spin_max), _(\"Maximum initial value of the variable\"));\n  window->scrolled_max\n    = (GtkScrolledWindow *) gtk_scrolled_window_new (NULL, NULL);\n  gtk_container_add (GTK_CONTAINER (window->scrolled_max),\n                     GTK_WIDGET (window->spin_max));\n  g_signal_connect (window->spin_max, \"value-changed\",\n                    window_rangemax_variable, NULL);\n  window->check_minabs = (GtkCheckButton *)\n    gtk_check_button_new_with_mnemonic (_(\"_Absolute minimum\"));\n  g_signal_connect (window->check_minabs, \"toggled\", window_update, NULL);\n  window->spin_minabs = (GtkSpinButton *) gtk_spin_button_new_with_range\n    (-G_MAXDOUBLE, G_MAXDOUBLE, precision[DEFAULT_PRECISION]);\n  gtk_widget_set_tooltip_text\n    (GTK_WIDGET (window->spin_minabs),\n     _(\"Minimum allowed value of the variable\"));\n  window->scrolled_minabs\n    = (GtkScrolledWindow *) gtk_scrolled_window_new (NULL, NULL);\n  gtk_container_add (GTK_CONTAINER (window->scrolled_minabs),\n                     GTK_WIDGET (window->spin_minabs));\n  g_signal_connect (window->spin_minabs, \"value-changed\",\n                    window_rangeminabs_variable, NULL);\n  window->check_maxabs = (GtkCheckButton *)\n    gtk_check_button_new_with_mnemonic (_(\"_Absolute maximum\"));\n  g_signal_connect (window->check_maxabs, \"toggled\", window_update, NULL);\n  window->spin_maxabs = (GtkSpinButton *) gtk_spin_button_new_with_range\n    (-G_MAXDOUBLE, G_MAXDOUBLE, precision[DEFAULT_PRECISION]);\n  gtk_widget_set_tooltip_text\n    (GTK_WIDGET (window->spin_maxabs),\n     _(\"Maximum allowed value of the variable\"));\n  window->scrolled_maxabs\n    = (GtkScrolledWindow *) gtk_scrolled_window_new (NULL, NULL);\n  gtk_container_add (GTK_CONTAINER (window->scrolled_maxabs),\n                     GTK_WIDGET (window->spin_maxabs));\n  g_signal_connect (window->spin_maxabs, \"value-changed\",\n                    window_rangemaxabs_variable, NULL);\n  window->label_precision = (GtkLabel *) gtk_label_new (_(\"Precision digits\"));\n  window->spin_precision = (GtkSpinButton *)\n    gtk_spin_button_new_with_range (0., (gdouble) DEFAULT_PRECISION, 1.);\n  gtk_widget_set_tooltip_text\n    (GTK_WIDGET (window->spin_precision),\n     _(\"Number of precision floating point digits\\n\"\n       \"0 is for integer numbers\"));\n  g_signal_connect (window->spin_precision, \"value-changed\",\n                    window_precision_variable, NULL);\n  window->label_sweeps = (GtkLabel *) gtk_label_new (_(\"Sweeps number\"));\n  window->spin_sweeps =\n    (GtkSpinButton *) gtk_spin_button_new_with_range (1., 1.e12, 1.);\n  gtk_widget_set_tooltip_text (GTK_WIDGET (window->spin_sweeps),\n                               _(\"Number of steps sweeping the variable\"));\n  g_signal_connect (window->spin_sweeps, \"value-changed\",\n                    window_update_variable, NULL);\n  window->label_bits = (GtkLabel *) gtk_label_new (_(\"Bits number\"));\n  window->spin_bits\n    = (GtkSpinButton *) gtk_spin_button_new_with_range (1., 64., 1.);\n  gtk_widget_set_tooltip_text\n    (GTK_WIDGET (window->spin_bits),\n     _(\"Number of bits to encode the variable\"));\n  g_signal_connect\n    (window->spin_bits, \"value-changed\", window_update_variable, NULL);\n  window->label_step = (GtkLabel *) gtk_label_new (_(\"Step size\"));\n  window->spin_step = (GtkSpinButton *) gtk_spin_button_new_with_range\n    (-G_MAXDOUBLE, G_MAXDOUBLE, precision[DEFAULT_PRECISION]);\n  gtk_widget_set_tooltip_text\n    (GTK_WIDGET (window->spin_step),\n     _(\"Initial step size for the hill climbing method\"));\n  window->scrolled_step\n    = (GtkScrolledWindow *) gtk_scrolled_window_new (NULL, NULL);\n  gtk_container_add (GTK_CONTAINER (window->scrolled_step),\n                     GTK_WIDGET (window->spin_step));\n  g_signal_connect\n    (window->spin_step, \"value-changed\", window_step_variable, NULL);\n  window->grid_variable = (GtkGrid *) gtk_grid_new ();\n  gtk_grid_attach (window->grid_variable,\n                   GTK_WIDGET (window->combo_variable), 0, 0, 2, 1);\n  gtk_grid_attach (window->grid_variable,\n                   GTK_WIDGET (window->button_add_variable), 2, 0, 1, 1);\n  gtk_grid_attach (window->grid_variable,\n                   GTK_WIDGET (window->button_remove_variable), 3, 0, 1, 1);\n  gtk_grid_attach (window->grid_variable,\n                   GTK_WIDGET (window->label_variable), 0, 1, 1, 1);\n  gtk_grid_attach (window->grid_variable,\n                   GTK_WIDGET (window->entry_variable), 1, 1, 3, 1);\n  gtk_grid_attach (window->grid_variable,\n                   GTK_WIDGET (window->label_min), 0, 2, 1, 1);\n  gtk_grid_attach (window->grid_variable,\n                   GTK_WIDGET (window->scrolled_min), 1, 2, 3, 1);\n  gtk_grid_attach (window->grid_variable,\n                   GTK_WIDGET (window->label_max), 0, 3, 1, 1);\n  gtk_grid_attach (window->grid_variable,\n                   GTK_WIDGET (window->scrolled_max), 1, 3, 3, 1);\n  gtk_grid_attach (window->grid_variable,\n                   GTK_WIDGET (window->check_minabs), 0, 4, 1, 1);\n  gtk_grid_attach (window->grid_variable,\n                   GTK_WIDGET (window->scrolled_minabs), 1, 4, 3, 1);\n  gtk_grid_attach (window->grid_variable,\n                   GTK_WIDGET (window->check_maxabs), 0, 5, 1, 1);\n  gtk_grid_attach (window->grid_variable,\n                   GTK_WIDGET (window->scrolled_maxabs), 1, 5, 3, 1);\n  gtk_grid_attach (window->grid_variable,\n                   GTK_WIDGET (window->label_precision), 0, 6, 1, 1);\n  gtk_grid_attach (window->grid_variable,\n                   GTK_WIDGET (window->spin_precision), 1, 6, 3, 1);\n  gtk_grid_attach (window->grid_variable,\n                   GTK_WIDGET (window->label_sweeps), 0, 7, 1, 1);\n  gtk_grid_attach (window->grid_variable,\n                   GTK_WIDGET (window->spin_sweeps), 1, 7, 3, 1);\n  gtk_grid_attach (window->grid_variable,\n                   GTK_WIDGET (window->label_bits), 0, 8, 1, 1);\n  gtk_grid_attach (window->grid_variable,\n                   GTK_WIDGET (window->spin_bits), 1, 8, 3, 1);\n  gtk_grid_attach (window->grid_variable,\n                   GTK_WIDGET (window->label_step), 0, 9, 1, 1);\n  gtk_grid_attach (window->grid_variable,\n                   GTK_WIDGET (window->scrolled_step), 1, 9, 3, 1);\n  window->frame_variable = (GtkFrame *) gtk_frame_new (_(\"Variable\"));\n  gtk_container_add (GTK_CONTAINER (window->frame_variable),\n                     GTK_WIDGET (window->grid_variable));\n\n  // Creating the experiment widgets\n  window->combo_experiment = (GtkComboBoxText *) gtk_combo_box_text_new ();\n  gtk_widget_set_tooltip_text (GTK_WIDGET (window->combo_experiment),\n                               _(\"Experiment selector\"));\n  window->id_experiment = g_signal_connect\n    (window->combo_experiment, \"changed\", window_set_experiment, NULL);\n  window->button_add_experiment = (GtkButton *)\n    gtk_button_new_from_icon_name (\"list-add\", GTK_ICON_SIZE_BUTTON);\n  g_signal_connect\n    (window->button_add_experiment, \"clicked\", window_add_experiment, NULL);\n  gtk_widget_set_tooltip_text (GTK_WIDGET (window->button_add_experiment),\n                               _(\"Add experiment\"));\n  window->button_remove_experiment = (GtkButton *)\n    gtk_button_new_from_icon_name (\"list-remove\", GTK_ICON_SIZE_BUTTON);\n  g_signal_connect (window->button_remove_experiment, \"clicked\",\n                    window_remove_experiment, NULL);\n  gtk_widget_set_tooltip_text (GTK_WIDGET (window->button_remove_experiment),\n                               _(\"Remove experiment\"));\n  window->label_experiment\n    = (GtkLabel *) gtk_label_new (_(\"Experimental data file\"));\n  window->button_experiment = (GtkFileChooserButton *)\n    gtk_file_chooser_button_new (_(\"Experimental data file\"),\n                                 GTK_FILE_CHOOSER_ACTION_OPEN);\n  gtk_widget_set_tooltip_text (GTK_WIDGET (window->button_experiment),\n                               _(\"Experimental data file\"));\n  window->id_experiment_name\n    = g_signal_connect (window->button_experiment, \"selection-changed\",\n                        window_name_experiment, NULL);\n  gtk_widget_set_hexpand (GTK_WIDGET (window->button_experiment), TRUE);\n  window->label_weight = (GtkLabel *) gtk_label_new (_(\"Weight\"));\n  window->spin_weight\n    = (GtkSpinButton *) gtk_spin_button_new_with_range (0., 1., 0.001);\n  gtk_widget_set_tooltip_text\n    (GTK_WIDGET (window->spin_weight),\n     _(\"Weight factor to build the objective function\"));\n  g_signal_connect\n    (window->spin_weight, \"value-changed\", window_weight_experiment, NULL);\n  window->grid_experiment = (GtkGrid *) gtk_grid_new ();\n  gtk_grid_attach (window->grid_experiment,\n                   GTK_WIDGET (window->combo_experiment), 0, 0, 2, 1);\n  gtk_grid_attach (window->grid_experiment,\n                   GTK_WIDGET (window->button_add_experiment), 2, 0, 1, 1);\n  gtk_grid_attach (window->grid_experiment,\n                   GTK_WIDGET (window->button_remove_experiment), 3, 0, 1, 1);\n  gtk_grid_attach (window->grid_experiment,\n                   GTK_WIDGET (window->label_experiment), 0, 1, 1, 1);\n  gtk_grid_attach (window->grid_experiment,\n                   GTK_WIDGET (window->button_experiment), 1, 1, 3, 1);\n  gtk_grid_attach (window->grid_experiment,\n                   GTK_WIDGET (window->label_weight), 0, 2, 1, 1);\n  gtk_grid_attach (window->grid_experiment,\n                   GTK_WIDGET (window->spin_weight), 1, 2, 3, 1);\n  for (i = 0; i < MAX_NINPUTS; ++i)\n    {\n      snprintf (buffer3, 64, \"%s %u\", _(\"Input template\"), i + 1);\n      window->check_template[i] = (GtkCheckButton *)\n        gtk_check_button_new_with_label (buffer3);\n      window->id_template[i]\n        = g_signal_connect (window->check_template[i], \"toggled\",\n                            window_inputs_experiment, NULL);\n      gtk_grid_attach (window->grid_experiment,\n                       GTK_WIDGET (window->check_template[i]), 0, 3 + i, 1, 1);\n      window->button_template[i] = (GtkFileChooserButton *)\n        gtk_file_chooser_button_new (_(\"Input template\"),\n                                     GTK_FILE_CHOOSER_ACTION_OPEN);\n      gtk_widget_set_tooltip_text (GTK_WIDGET (window->button_template[i]),\n                                   _(\"Experimental input template file\"));\n      window->id_input[i] =\n        g_signal_connect_swapped (window->button_template[i],\n                                  \"selection-changed\",\n                                  (GCallback) window_template_experiment,\n                                  (void *) (size_t) i);\n      gtk_grid_attach (window->grid_experiment,\n                       GTK_WIDGET (window->button_template[i]), 1, 3 + i, 3, 1);\n    }\n  window->frame_experiment = (GtkFrame *) gtk_frame_new (_(\"Experiment\"));\n  gtk_container_add (GTK_CONTAINER (window->frame_experiment),\n                     GTK_WIDGET (window->grid_experiment));\n\n  // Creating the error norm widgets\n  window->frame_norm = (GtkFrame *) gtk_frame_new (_(\"Error norm\"));\n  window->grid_norm = (GtkGrid *) gtk_grid_new ();\n  gtk_container_add (GTK_CONTAINER (window->frame_norm),\n                     GTK_WIDGET (window->grid_norm));\n  window->button_norm[0] = (GtkRadioButton *)\n    gtk_radio_button_new_with_mnemonic (NULL, label_norm[0]);\n  gtk_widget_set_tooltip_text (GTK_WIDGET (window->button_norm[0]),\n                               tip_norm[0]);\n  gtk_grid_attach (window->grid_norm,\n                   GTK_WIDGET (window->button_norm[0]), 0, 0, 1, 1);\n  g_signal_connect (window->button_norm[0], \"clicked\", window_update, NULL);\n  for (i = 0; ++i < NNORMS;)\n    {\n      window->button_norm[i] = (GtkRadioButton *)\n        gtk_radio_button_new_with_mnemonic\n        (gtk_radio_button_get_group (window->button_norm[0]), label_norm[i]);\n      gtk_widget_set_tooltip_text (GTK_WIDGET (window->button_norm[i]),\n                                   tip_norm[i]);\n      gtk_grid_attach (window->grid_norm,\n                       GTK_WIDGET (window->button_norm[i]), 0, i, 1, 1);\n      g_signal_connect (window->button_norm[i], \"clicked\", window_update, NULL);\n    }\n  window->label_p = (GtkLabel *) gtk_label_new (_(\"P parameter\"));\n  gtk_grid_attach (window->grid_norm, GTK_WIDGET (window->label_p), 1, 1, 1, 1);\n  window->spin_p = (GtkSpinButton *)\n    gtk_spin_button_new_with_range (-G_MAXDOUBLE, G_MAXDOUBLE, 0.01);\n  gtk_widget_set_tooltip_text (GTK_WIDGET (window->spin_p),\n                               _(\"P parameter for the P error norm\"));\n  window->scrolled_p =\n    (GtkScrolledWindow *) gtk_scrolled_window_new (NULL, NULL);\n  gtk_container_add (GTK_CONTAINER (window->scrolled_p),\n                     GTK_WIDGET (window->spin_p));\n  gtk_widget_set_hexpand (GTK_WIDGET (window->scrolled_p), TRUE);\n  gtk_widget_set_halign (GTK_WIDGET (window->scrolled_p), GTK_ALIGN_FILL);\n  gtk_grid_attach (window->grid_norm, GTK_WIDGET (window->scrolled_p),\n                   1, 2, 1, 2);\n\n  // Creating the grid and attaching the widgets to the grid\n  window->grid = (GtkGrid *) gtk_grid_new ();\n  gtk_grid_attach (window->grid, GTK_WIDGET (window->bar_buttons), 0, 0, 3, 1);\n  gtk_grid_attach (window->grid, GTK_WIDGET (window->grid_files), 0, 1, 1, 1);\n  gtk_grid_attach (window->grid,\n                   GTK_WIDGET (window->frame_algorithm), 0, 2, 1, 1);\n  gtk_grid_attach (window->grid,\n                   GTK_WIDGET (window->frame_variable), 1, 2, 1, 1);\n  gtk_grid_attach (window->grid,\n                   GTK_WIDGET (window->frame_experiment), 2, 2, 1, 1);\n  gtk_grid_attach (window->grid, GTK_WIDGET (window->frame_norm), 1, 1, 2, 1);\n  gtk_container_add (GTK_CONTAINER (window->window), GTK_WIDGET (window->grid));\n\n  // Setting the window logo\n  window->logo = gdk_pixbuf_new_from_xpm_data (logo);\n  gtk_window_set_icon (window->window, window->logo);\n\n  // Showing the window\n  gtk_widget_show_all (GTK_WIDGET (window->window));\n\n  // In GTK+ 3.16 and 3.18 the default scrolled size is wrong\n#if GTK_MINOR_VERSION >= 16\n  gtk_widget_set_size_request (GTK_WIDGET (window->scrolled_min), -1, 40);\n  gtk_widget_set_size_request (GTK_WIDGET (window->scrolled_max), -1, 40);\n  gtk_widget_set_size_request (GTK_WIDGET (window->scrolled_minabs), -1, 40);\n  gtk_widget_set_size_request (GTK_WIDGET (window->scrolled_maxabs), -1, 40);\n  gtk_widget_set_size_request (GTK_WIDGET (window->scrolled_step), -1, 40);\n  gtk_widget_set_size_request (GTK_WIDGET (window->scrolled_p), -1, 40);\n  gtk_widget_set_size_request (GTK_WIDGET (window->scrolled_threshold), -1, 40);\n#endif\n\n  // Reading initial example\n  input_new ();\n  buffer2 = g_get_current_dir ();\n  buffer = g_build_filename (buffer2, \"..\", \"tests\", \"test1\", INPUT_FILE, NULL);\n  g_free (buffer2);\n  window_read (buffer);\n  g_free (buffer);\n\n#if DEBUG_INTERFACE\n  fprintf (stderr, \"window_new: start\\n\");\n#endif\n}\n", "meta": {"hexsha": "95aba2601cddfdd31c0fb7e8d65d8aeebfa8f8f2", "size": 108235, "ext": "c", "lang": "C", "max_stars_repo_path": "4.0.5/interface.c", "max_stars_repo_name": "jburguete/mpcotool", "max_stars_repo_head_hexsha": "e8a6a9713d4ef73b0aa8a0a552d91117ebd22610", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-17T14:59:29.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-17T14:59:29.000Z", "max_issues_repo_path": "4.0.5/interface.c", "max_issues_repo_name": "jburguete/mpcotool", "max_issues_repo_head_hexsha": "e8a6a9713d4ef73b0aa8a0a552d91117ebd22610", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-03-08T17:02:14.000Z", "max_issues_repo_issues_event_max_datetime": "2016-03-08T17:02:14.000Z", "max_forks_repo_path": "4.0.5/interface.c", "max_forks_repo_name": "jburguete/mpcotool", "max_forks_repo_head_hexsha": "e8a6a9713d4ef73b0aa8a0a552d91117ebd22610", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.3868267831, "max_line_length": 80, "alphanum_fraction": 0.6590936388, "num_tokens": 26679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15610488174128417, "lm_q2_score": 0.023689471514773325, "lm_q1q2_score": 0.00369804214932721}}
{"text": "/*==================BEGIN ASF AUTO-GENERATED DOCUMENTATION==================*/\n/*\nABOUT EDITING THIS DOCUMENTATION:\nIf you wish to edit the documentation for this program, you need to\nchange the following defines. For the short ones (like\nASF_NAME_STRING) this is no big deal. However, for some of the longer\nones, such as ASF_COPYRIGHT_STRING, it can be a daunting task to get\nall the newlines in correctly, etc. In order to help you with this\ntask, there is a tool, edit_man_header. The tool *only* works with\nthis portion of the code, so fear not. It will scan in defines of the\nformat #define ASF_<something>_STRING between the two auto-generated\ndocumentation markers, format them for a text editor, run that editor,\nallow you to edit the text in a clean manner, and then automatically\ngenerate these defines, formatted appropriately. The only warning is\nthat any text between those two markers and not part of one of those\ndefines will not be preserved, and that all of this auto-generated\ncode will be at the top of the source file. Save yourself the time and\ntrouble, and use edit_man_header. :)\n*/\n\n#define ASF_NAME_STRING \\\n\"asf_geocode\"\n\n#define ASF_USAGE_STRING \\\n\"   \"ASF_NAME_STRING\" -p <projection name> <<projection parameters>>\\n\"\\\n\"             [-force] [-resample-method <method>] [-height <height>]\\n\"\\\n\"             [-datum <datum>] [-pixel-size <pixel size>] [-band <band_id | all>]\\n\"\\\n\"             [-log <file>] [-write-proj-file <file>] [-read-proj-file <file>]\\n\"\\\n\"             [-save-mapping] [-background <value>] [-quiet] [-license]\\n\"\\\n\"             [-version] [-help]\\n\"\\\n\"             <in_base_name> <out_base_name>\\n\"\\\n\"\\n\"\\\n\"   Use the -help option for more projection parameter controls.\\n\"\n\n#define ASF_DESCRIPTION_STRING \\\n\"     This program takes a map projected or an unprojected (ground\\n\"\\\n\"     range) image in the ASF internal format and geocodes it,\\n\"\\\n\"     i.e. swizzles it around into one of the standard projections used\\n\"\\\n\"     for maps (universal transverse mercator, polar stereo, etc).  The\\n\"\\\n\"     output is a new image in ASF internal format.\\n\"\n\n#define ASF_INPUT_STRING \\\n\"     Most of the \\\"options\\\" are actually required.  The specification\\n\"\\\n\"     of a certain projection type implies that all the parameters\\n\"\\\n\"     required to fully specify a projection of that type be included.\\n\"\\\n\"\\n\"\\\n\"     This must be an ASF internal format image base name.\\n\"\n\n#define ASF_OUTPUT_STRING \\\n\"     The base name of the geocoded image to produce.\\n\"\n\n#define ASF_OPTIONS_STRING \\\n\"%s\"\\\n\"\\n\"\\\n\"     -save-mapping\\n\"\\\n\"          Creates two additional files during geocoding.  One will contain\\n\"\\\n\"          the line number from which the pixel was obtained from the\\n\"\\\n\"          original file, the other the sample numbers.  Together, these\\n\"\\\n\"          define the mapping of pixels performed by the geocoding.\\n\"\\\n\"\\n\"\\\n\"     -log <log file>\\n\"\\\n\"          Output will be written to a specified log file.\\n\"\\\n\"\\n\"\\\n\"     -quiet\\n\"\\\n\"          Supresses all non-essential output.\\n\"\\\n\"\\n\"\\\n\"     -license\\n\"\\\n\"          Print copyright and license for this software then exit.\\n\"\\\n\"\\n\"\\\n\"     -version\\n\"\\\n\"          Print version and copyright then exit.\\n\"\\\n\"\\n\"\\\n\"     -help\\n\"\\\n\"          Print a help page and exit.\\n\"\n\n#define ASF_EXAMPLES_STRING \\\n\"     To map project an image with centerpoint at -147 degrees\\n\"\\\n\"     longitude and average height 466 meters into universal transverse\\n\"\\\n\"     mercator projection, with one pixel 50 meters on a side:\\n\"\\\n\"\\n\"\\\n\"     \"ASF_NAME_STRING\" -p utm --central-meridian -147.0 --height 466\\n\"\\\n\"                 input_image output_image\\n\"\\\n\"\\n\"\\\n\"     To geocode one band within an image file, you specify the selected band\\n\"\\\n\"     with the -band option, and the selected band MUST be one of which appears\\n\"\\\n\"     in the list of available bands as noted in the 'bands' item found in the\\n\"\\\n\"     'general' (first) block in the metadata file.  For example, if 'bands'\\n\"\\\n\"     contains \\\"01,02,03,04\\\", then you could specify a band_id, e.g. \\\"-band 02\\\"\\n\"\\\n\"     etc on the command line.  The same applies to band lists, such\\n\"\\\n\"     as \\\"HH,HV,VH,VV\\\" or just \\\"03\\\" etc.\\n\"\\\n\"\\n\"\\\n\"     \"ASF_NAME_STRING\" -p utm -band HV file outfile_HV\\n\"\n\n#define ASF_LIMITATIONS_STRING \\\n\"     May fail badly if bad projection parameters are supplied for the\\n\"\\\n\"     area in the image.\\n\"\n\n#define ASF_SEE_ALSO_STRING \\\n\"     asf_import, asf_export\\n\"\n\n/*===================END ASF AUTO-GENERATED DOCUMENTATION===================*/\n#include <asf_contact.h>\n#include <asf_license.h>\n\n// Standard libraries.\n#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n// Libraries from packages outside ASF.\n#include <glib.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_spline.h>\n#include <gsl/gsl_statistics_double.h>\n\n// Libraries developed at ASF.\n#include <asf.h>\n#include <asf_nan.h>\n#include <asf_meta.h>\n#include <asf_raster.h>\n#include \"float_image.h\"\n#include <libasf_proj.h>\n#include <spheroids.h>\n#include <asf_contact.h>\n\n// Headers used by this program.\n#include \"asf_geocode.h\"\n\n// Print minimalistic usage info & exit\nstatic void print_usage(void)\n{\n  asfPrintStatus(\"\\n\"\n      \"Usage:\\n\"\n      ASF_USAGE_STRING\n      \"\\n\");\n  exit(EXIT_FAILURE);\n}\n\n// Print the help info & exit\nstatic void print_help(void)\n{\n  asfPrintStatus(\n      \"\\n\"\n      \"Tool name:\\n   \" ASF_NAME_STRING \"\\n\\n\"\n      \"Usage:\\n\" ASF_USAGE_STRING \"\\n\"\n      \"Description:\\n\" ASF_DESCRIPTION_STRING \"\\n\"\n      \"Input:\\n\" ASF_INPUT_STRING \"\\n\"\n      \"Output:\\n\"ASF_OUTPUT_STRING \"\\n\"\n      \"Options:\\n\" ASF_OPTIONS_STRING \"\\n\"\n      \"Examples:\\n\" ASF_EXAMPLES_STRING \"\\n\"\n      \"Limitations:\\n\" ASF_LIMITATIONS_STRING \"\\n\"\n      \"See also:\\n\" ASF_SEE_ALSO_STRING \"\\n\"\n      \"Contact:\\n\" ASF_CONTACT_STRING \"\\n\"\n      \"Version:\\n   \" SVN_REV \" (part of \" TOOL_SUITE_NAME \" \" MAPREADY_VERSION_STRING \")\\n\\n\",\n        geocode_projection_options_help());\n  exit(EXIT_FAILURE);\n}\n\n// Main routine.\nint\nmain (int argc, char **argv)\n{\n  int force_flag = FALSE;\n  int debug_dump = FALSE;\n  char band_id[256]=\"\";\n  char *in_base_name, *out_base_name;\n\n  in_base_name = (char *) MALLOC(sizeof(char)*255);\n  out_base_name = (char *) MALLOC(sizeof(char)*255);\n\n  // Get the projection parameters from the command line.\n  projection_type_t projection_type;\n  // Terrain height to assume.  Defaults to 0 (no height correction)\n  double average_height = 0.0;\n  // Pixel size to use for output image, in projection coordinate\n  // units.  This variable corresponds to a \"private\"\n  // (i.e. undocumented, so users don't fiddle with it) option.\n  // NOTE: Setting the pixel size to a negative number results in the\n  // code to pick a pixel size from the metadata\n  double pixel_size = -1;\n  // Datum to use in the target projection\n  datum_type_t datum;\n  spheroid_type_t spheroid;\n  // Method to use to resample images.\n  resample_method_t resample_method;\n  // Value to put in the region outside the image\n  double background_val = 0.0;\n  // Should we save the mapping files?\n  int save_map_flag;\n\n  if (detect_flag_options(argc, argv, \"-help\", \"--help\", \"-h\", NULL)) {\n    print_help();\n  }\n\n  // Detect & Process logging arguments\n  if ((logflag = detect_string_options(argc, argv, logFile,\n                      \"-log\", \"--log\", NULL))) {\n      fLog = fopen (logFile, \"a\");\n      if ( fLog == NULL ) {\n    // Couldn't open the log file, so just don't do logging.\n    logflag = FALSE;\n      }\n  }\n  quietflag = detect_flag_options(argc, argv, \"-quiet\", \"--quiet\", NULL);\n  save_map_flag = extract_flag_options(&argc, &argv, \"-save-mapping\", \"--save_mapping\", NULL);\n\n  handle_license_and_version_args(argc, argv, ASF_NAME_STRING);\n\n  asfSplashScreen(argc, argv);\n\n  project_parameters_t *pp\n    = get_geocode_options (&argc, &argv, &projection_type, &average_height,\n\t\t\t   &pixel_size, &datum, &spheroid, &resample_method,\n\t\t\t   &force_flag, band_id);\n\n  if (!pp && projection_type != LAT_LONG_PSEUDO_PROJECTION) {\n      print_usage();\n  }\n\n  // The argument at which the filenames start\n  int arg_num = 1;\n\n  if (detect_flag_options(argc, argv, \"-debug\", NULL)) {\n    debug_dump=TRUE;\n    ++arg_num;\n  }\n\n  if (!extract_double_options(&argc, &argv, &background_val, \"--background\",\n\t\t\t      \"-background\", NULL)) {\n    strcpy(in_base_name, argv[arg_num]);\n    meta_parameters *meta = meta_read(in_base_name);\n    background_val = meta->general->no_data;\n    asfPrintStatus(\"Extracted no data value (%f) out of the metadata.\\n\",\n\t\t   meta->general->no_data);\n    meta_free(meta);\n  }\n  if (ISNAN(background_val)) background_val = DEFAULT_NO_DATA_VALUE;\n\n  // Get non-option command line arguments.\n  if ( argc != 3 && !debug_dump ) {\n    int ii;\n    int bad_arg = FALSE;\n\n    for (ii = 0; ii < argc; ++ii) {\n      if (argv[ii][0] == '-') {\n    bad_arg = TRUE;\n    asfPrintStatus(\"Unrecognized argument: %s\\n\", argv[ii]);\n      }\n    }\n\n    if (!bad_arg)\n      fprintf (stderr, \"Wrong number of arguments\\n\");\n\n    print_usage ();\n  }\n\n  strcpy (in_base_name, argv[arg_num]);\n  strcpy (out_base_name, argv[arg_num + 1]);\n\n  // Strip .img and also check to make sure input and output\n  // base names are not the same\n  char *ext = findExt(in_base_name);\n  if (ext && strncmp(ext, \".img\", 4) == 0) *ext = '\\0';\n  ext = findExt(out_base_name);\n  if (ext && strncmp(ext, \".img\", 4) == 0) *ext = '\\0';\n  char msg[512];\n  sprintf(msg,\"Input and output basenames cannot be the same:\\n\"\n      \"    Input base name : %s\\n\"\n          \"    Output base name: %s\\n\",\n      in_base_name, out_base_name);\n  if (strcmp(in_base_name, out_base_name) == 0)\n    asfPrintError(msg);\n\n  // Call library function that does the actual work\n  asf_geocode(pp, projection_type, force_flag, resample_method, average_height,\n          datum, pixel_size, band_id, in_base_name, out_base_name,\n              (float)background_val, save_map_flag);\n\n  // Close Log, if needed\n  if (logflag)\n    FCLOSE (fLog);\n\n  exit (EXIT_SUCCESS);\n}\n", "meta": {"hexsha": "8c26ce6ff5373d076bc55bb78d0780de25761154", "size": 10035, "ext": "c", "lang": "C", "max_stars_repo_path": "src/asf_geocode/asf_geocode.c", "max_stars_repo_name": "glshort/MapReady", "max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z", "max_issues_repo_path": "src/asf_geocode/asf_geocode.c", "max_issues_repo_name": "glshort/MapReady", "max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/asf_geocode/asf_geocode.c", "max_forks_repo_name": "glshort/MapReady", "max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z", "avg_line_length": 34.9651567944, "max_line_length": 95, "alphanum_fraction": 0.6639760837, "num_tokens": 2636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18713267309572332, "lm_q2_score": 0.019719128719439417, "lm_q1q2_score": 0.0036900932683873455}}
{"text": "#ifndef __GSL_VERSION_H__\r\n#define __GSL_VERSION_H__\r\n\r\n#if !defined( GSL_FUN )\r\n#  if !defined( GSL_DLL )\r\n#    define GSL_FUN extern\r\n#  elif defined( BUILD_GSL_DLL )\r\n#    define GSL_FUN extern __declspec(dllexport)\r\n#  else\r\n#    define GSL_FUN extern __declspec(dllimport)\r\n#  endif\r\n#endif\r\n\r\n#include <gsl/gsl_types.h>\r\n\r\n#undef __BEGIN_DECLS\r\n#undef __END_DECLS\r\n#ifdef __cplusplus\r\n# define __BEGIN_DECLS extern \"C\" {\r\n# define __END_DECLS }\r\n#else\r\n# define __BEGIN_DECLS /* empty */\r\n# define __END_DECLS /* empty */\r\n#endif\r\n__BEGIN_DECLS\r\n\r\n\r\n#define GSL_VERSION \"2.4\"\r\n#define GSL_MAJOR_VERSION 2\r\n#define GSL_MINOR_VERSION 4\r\n\r\nGSL_VAR const char * gsl_version;\r\n\r\n__END_DECLS\r\n\r\n#endif /* __GSL_VERSION_H__ */\r\n", "meta": {"hexsha": "56f1556fc918e37a2c05d0786f7ab5643447084b", "size": 727, "ext": "h", "lang": "C", "max_stars_repo_path": "vendor/gsl/gsl/gsl_version.h", "max_stars_repo_name": "mgreter/astrometrylib", "max_stars_repo_head_hexsha": "ef4d4539a537ab49329b77648aac893d2b4ad318", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z", "max_issues_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_version.h", "max_issues_repo_name": "zzpwahaha/VimbaCamJILA", "max_issues_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z", "max_forks_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_version.h", "max_forks_repo_name": "zzpwahaha/VimbaCamJILA", "max_forks_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 19.6486486486, "max_line_length": 49, "alphanum_fraction": 0.7138927098, "num_tokens": 187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08756383476086142, "lm_q2_score": 0.04208772611333754, "lm_q1q2_score": 0.0036853626948486805}}
{"text": "/* matrix/gsl_matrix_uchar.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_MATRIX_UCHAR_H__\n#define __GSL_MATRIX_UCHAR_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_vector_uchar.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size1;\n  size_t size2;\n  size_t tda;\n  unsigned char * data;\n  gsl_block_uchar * block;\n  int owner;\n} gsl_matrix_uchar;\n\ntypedef struct\n{\n  gsl_matrix_uchar matrix;\n} _gsl_matrix_uchar_view;\n\ntypedef _gsl_matrix_uchar_view gsl_matrix_uchar_view;\n\ntypedef struct\n{\n  gsl_matrix_uchar matrix;\n} _gsl_matrix_uchar_const_view;\n\ntypedef const _gsl_matrix_uchar_const_view gsl_matrix_uchar_const_view;\n\n/* Allocation */\n\ngsl_matrix_uchar * \ngsl_matrix_uchar_alloc (const size_t n1, const size_t n2);\n\ngsl_matrix_uchar * \ngsl_matrix_uchar_calloc (const size_t n1, const size_t n2);\n\ngsl_matrix_uchar * \ngsl_matrix_uchar_alloc_from_block (gsl_block_uchar * b, \n                                   const size_t offset, \n                                   const size_t n1, \n                                   const size_t n2, \n                                   const size_t d2);\n\ngsl_matrix_uchar * \ngsl_matrix_uchar_alloc_from_matrix (gsl_matrix_uchar * m,\n                                    const size_t k1, \n                                    const size_t k2,\n                                    const size_t n1, \n                                    const size_t n2);\n\ngsl_vector_uchar * \ngsl_vector_uchar_alloc_row_from_matrix (gsl_matrix_uchar * m,\n                                        const size_t i);\n\ngsl_vector_uchar * \ngsl_vector_uchar_alloc_col_from_matrix (gsl_matrix_uchar * m,\n                                        const size_t j);\n\nvoid gsl_matrix_uchar_free (gsl_matrix_uchar * m);\n\n/* Views */\n\n_gsl_matrix_uchar_view \ngsl_matrix_uchar_submatrix (gsl_matrix_uchar * m, \n                            const size_t i, const size_t j, \n                            const size_t n1, const size_t n2);\n\n_gsl_vector_uchar_view \ngsl_matrix_uchar_row (gsl_matrix_uchar * m, const size_t i);\n\n_gsl_vector_uchar_view \ngsl_matrix_uchar_column (gsl_matrix_uchar * m, const size_t j);\n\n_gsl_vector_uchar_view \ngsl_matrix_uchar_diagonal (gsl_matrix_uchar * m);\n\n_gsl_vector_uchar_view \ngsl_matrix_uchar_subdiagonal (gsl_matrix_uchar * m, const size_t k);\n\n_gsl_vector_uchar_view \ngsl_matrix_uchar_superdiagonal (gsl_matrix_uchar * m, const size_t k);\n\n_gsl_matrix_uchar_view\ngsl_matrix_uchar_view_array (unsigned char * base,\n                             const size_t n1, \n                             const size_t n2);\n\n_gsl_matrix_uchar_view\ngsl_matrix_uchar_view_array_with_tda (unsigned char * base, \n                                      const size_t n1, \n                                      const size_t n2,\n                                      const size_t tda);\n\n\n_gsl_matrix_uchar_view\ngsl_matrix_uchar_view_vector (gsl_vector_uchar * v,\n                              const size_t n1, \n                              const size_t n2);\n\n_gsl_matrix_uchar_view\ngsl_matrix_uchar_view_vector_with_tda (gsl_vector_uchar * v,\n                                       const size_t n1, \n                                       const size_t n2,\n                                       const size_t tda);\n\n\n_gsl_matrix_uchar_const_view \ngsl_matrix_uchar_const_submatrix (const gsl_matrix_uchar * m, \n                                  const size_t i, const size_t j, \n                                  const size_t n1, const size_t n2);\n\n_gsl_vector_uchar_const_view \ngsl_matrix_uchar_const_row (const gsl_matrix_uchar * m, \n                            const size_t i);\n\n_gsl_vector_uchar_const_view \ngsl_matrix_uchar_const_column (const gsl_matrix_uchar * m, \n                               const size_t j);\n\n_gsl_vector_uchar_const_view\ngsl_matrix_uchar_const_diagonal (const gsl_matrix_uchar * m);\n\n_gsl_vector_uchar_const_view \ngsl_matrix_uchar_const_subdiagonal (const gsl_matrix_uchar * m, \n                                    const size_t k);\n\n_gsl_vector_uchar_const_view \ngsl_matrix_uchar_const_superdiagonal (const gsl_matrix_uchar * m, \n                                      const size_t k);\n\n_gsl_matrix_uchar_const_view\ngsl_matrix_uchar_const_view_array (const unsigned char * base,\n                                   const size_t n1, \n                                   const size_t n2);\n\n_gsl_matrix_uchar_const_view\ngsl_matrix_uchar_const_view_array_with_tda (const unsigned char * base, \n                                            const size_t n1, \n                                            const size_t n2,\n                                            const size_t tda);\n\n_gsl_matrix_uchar_const_view\ngsl_matrix_uchar_const_view_vector (const gsl_vector_uchar * v,\n                                    const size_t n1, \n                                    const size_t n2);\n\n_gsl_matrix_uchar_const_view\ngsl_matrix_uchar_const_view_vector_with_tda (const gsl_vector_uchar * v,\n                                             const size_t n1, \n                                             const size_t n2,\n                                             const size_t tda);\n\n/* Operations */\n\nunsigned char   gsl_matrix_uchar_get(const gsl_matrix_uchar * m, const size_t i, const size_t j);\nvoid    gsl_matrix_uchar_set(gsl_matrix_uchar * m, const size_t i, const size_t j, const unsigned char x);\n\nunsigned char * gsl_matrix_uchar_ptr(gsl_matrix_uchar * m, const size_t i, const size_t j);\nconst unsigned char * gsl_matrix_uchar_const_ptr(const gsl_matrix_uchar * m, const size_t i, const size_t j);\n\nvoid gsl_matrix_uchar_set_zero (gsl_matrix_uchar * m);\nvoid gsl_matrix_uchar_set_identity (gsl_matrix_uchar * m);\nvoid gsl_matrix_uchar_set_all (gsl_matrix_uchar * m, unsigned char x);\n\nint gsl_matrix_uchar_fread (FILE * stream, gsl_matrix_uchar * m) ;\nint gsl_matrix_uchar_fwrite (FILE * stream, const gsl_matrix_uchar * m) ;\nint gsl_matrix_uchar_fscanf (FILE * stream, gsl_matrix_uchar * m);\nint gsl_matrix_uchar_fprintf (FILE * stream, const gsl_matrix_uchar * m, const char * format);\n \nint gsl_matrix_uchar_memcpy(gsl_matrix_uchar * dest, const gsl_matrix_uchar * src);\nint gsl_matrix_uchar_swap(gsl_matrix_uchar * m1, gsl_matrix_uchar * m2);\n\nint gsl_matrix_uchar_swap_rows(gsl_matrix_uchar * m, const size_t i, const size_t j);\nint gsl_matrix_uchar_swap_columns(gsl_matrix_uchar * m, const size_t i, const size_t j);\nint gsl_matrix_uchar_swap_rowcol(gsl_matrix_uchar * m, const size_t i, const size_t j);\nint gsl_matrix_uchar_transpose (gsl_matrix_uchar * m);\nint gsl_matrix_uchar_transpose_memcpy (gsl_matrix_uchar * dest, const gsl_matrix_uchar * src);\n\nunsigned char gsl_matrix_uchar_max (const gsl_matrix_uchar * m);\nunsigned char gsl_matrix_uchar_min (const gsl_matrix_uchar * m);\nvoid gsl_matrix_uchar_minmax (const gsl_matrix_uchar * m, unsigned char * min_out, unsigned char * max_out);\n\nvoid gsl_matrix_uchar_max_index (const gsl_matrix_uchar * m, size_t * imax, size_t *jmax);\nvoid gsl_matrix_uchar_min_index (const gsl_matrix_uchar * m, size_t * imin, size_t *jmin);\nvoid gsl_matrix_uchar_minmax_index (const gsl_matrix_uchar * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);\n\nint gsl_matrix_uchar_isnull (const gsl_matrix_uchar * m);\nint gsl_matrix_uchar_ispos (const gsl_matrix_uchar * m);\nint gsl_matrix_uchar_isneg (const gsl_matrix_uchar * m);\n\nint gsl_matrix_uchar_add (gsl_matrix_uchar * a, const gsl_matrix_uchar * b);\nint gsl_matrix_uchar_sub (gsl_matrix_uchar * a, const gsl_matrix_uchar * b);\nint gsl_matrix_uchar_mul_elements (gsl_matrix_uchar * a, const gsl_matrix_uchar * b);\nint gsl_matrix_uchar_div_elements (gsl_matrix_uchar * a, const gsl_matrix_uchar * b);\nint gsl_matrix_uchar_scale (gsl_matrix_uchar * a, const double x);\nint gsl_matrix_uchar_add_constant (gsl_matrix_uchar * a, const double x);\nint gsl_matrix_uchar_add_diagonal (gsl_matrix_uchar * a, const double x);\n\n/***********************************************************************/\n/* The functions below are obsolete                                    */\n/***********************************************************************/\nint gsl_matrix_uchar_get_row(gsl_vector_uchar * v, const gsl_matrix_uchar * m, const size_t i);\nint gsl_matrix_uchar_get_col(gsl_vector_uchar * v, const gsl_matrix_uchar * m, const size_t j);\nint gsl_matrix_uchar_set_row(gsl_matrix_uchar * m, const size_t i, const gsl_vector_uchar * v);\nint gsl_matrix_uchar_set_col(gsl_matrix_uchar * m, const size_t j, const gsl_vector_uchar * v);\n\n/* inline functions if you are using GCC */\n\n#ifdef HAVE_INLINE\nextern inline \nunsigned char\ngsl_matrix_uchar_get(const gsl_matrix_uchar * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_VAL(\"first index out of range\", GSL_EINVAL, 0) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_VAL(\"second index out of range\", GSL_EINVAL, 0) ;\n    }\n#endif\n  return m->data[i * m->tda + j] ;\n} \n\nextern inline \nvoid\ngsl_matrix_uchar_set(gsl_matrix_uchar * m, const size_t i, const size_t j, const unsigned char x)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_VOID(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_VOID(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  m->data[i * m->tda + j] = x ;\n}\n\nextern inline \nunsigned char *\ngsl_matrix_uchar_ptr(gsl_matrix_uchar * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  return (unsigned char *) (m->data + (i * m->tda + j)) ;\n} \n\nextern inline \nconst unsigned char *\ngsl_matrix_uchar_const_ptr(const gsl_matrix_uchar * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (i >= m->size1)\n    {\n      GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  return (const unsigned char *) (m->data + (i * m->tda + j)) ;\n} \n\n#endif\n\n__END_DECLS\n\n#endif /* __GSL_MATRIX_UCHAR_H__ */\n", "meta": {"hexsha": "c85c01223be8487ee57067cf4ee4ee05bb1c4201", "size": 11218, "ext": "h", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/matrix/gsl_matrix_uchar.h", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/matrix/gsl_matrix_uchar.h", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/matrix/gsl_matrix_uchar.h", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 35.1661442006, "max_line_length": 124, "alphanum_fraction": 0.6667855233, "num_tokens": 2838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16238004072020704, "lm_q2_score": 0.022629200939356865, "lm_q1q2_score": 0.003674530569998515}}
{"text": "#pragma once\n\n#include \"type_traits.h\"\n\n#include <gsl/gsl>\n\n#include <system_error>\n#include <variant>\n\nnamespace arcana\n{\n    template<typename Type>\n    struct is_expected;\n\n    template<typename T, typename E>\n    class basic_expected;\n\n    namespace internal\n    {\n        template<typename T>\n        struct expected_error_traits;\n\n        template<>\n        struct expected_error_traits<std::error_code>\n        {\n            template<typename ErrorT>\n            using is_convertible = std::bool_constant<\n                std::is_error_code_enum<std::decay_t<ErrorT>>::value ||\n                std::is_error_condition_enum<std::decay_t<ErrorT>>::value\n            >;\n\n            template<typename ErrorT>\n            using enable_conversion = std::enable_if<\n                is_convertible<ErrorT>::value\n            >;\n\n            template<typename ErrorT>\n            static std::error_code convert(ErrorT errorEnum)\n            {\n                using std::make_error_code;\n\n                return make_error_code(errorEnum);\n            }\n        };\n\n        template<>\n        struct expected_error_traits<std::exception_ptr>\n        {\n            template<typename ErrorT>\n            using enable_conversion = std::enable_if<\n                std::is_same<std::error_code, ErrorT>::value || // support conversion from error_codes\n                expected_error_traits<std::error_code>::template is_convertible<ErrorT>::value // and also enumerations that are error codes\n            >;\n\n            static std::exception_ptr convert(std::error_code code)\n            {\n                return std::make_exception_ptr(std::system_error(code));\n            }\n\n            template<typename ErrorT, typename = typename expected_error_traits<std::error_code>::template enable_conversion<ErrorT>::type>\n            static std::exception_ptr convert(ErrorT errorEnum)\n            {\n                return convert(\n                    expected_error_traits<std::error_code>::convert(errorEnum));\n            }\n        };\n    }\n\n    class bad_expected_access : public std::exception\n    {\n    public:\n        const char* what() const override\n        {\n            return \"tried accessing value()/error() of an expected when it wasn't set\";\n        }\n    };\n\n    template<typename E>\n    class unexpected\n    {\n    public:\n        unexpected() = delete;\n\n        constexpr explicit unexpected(const E& e)\n            : m_e{ e }\n        {}\n\n        constexpr explicit unexpected(E&& e)\n            : m_e{ std::move(e) }\n        {}\n\n        constexpr const E& value() const &\n        {\n            return m_e;\n        }\n\n        constexpr E& value() &\n        {\n            return m_e;\n        }\n\n        constexpr E&& value() &&\n        {\n            return std::move(m_e);\n        }\n    private:\n        E m_e;\n    };\n\n    template<typename T>\n    inline auto make_unexpected(T&& error)\n    {\n        return unexpected<std::decay_t<T>>{std::forward<T>(error)};\n    }\n\n    template<typename T, typename E>\n    class basic_expected\n    {\n        using traits = internal::expected_error_traits<E>;\n\n        template<typename E2,\n            typename = typename traits::template enable_conversion<E2>::type>\n        std::variant<E, T> convert_variant(const basic_expected<T, E2>& exp)\n        {\n            if (exp.has_error())\n                return { traits::convert(exp.error()) };\n            else\n                return { exp.value() };\n        }\n    public:\n        using value_type = T;\n        using error_type = E;\n\n        basic_expected(const value_type& value)\n            : m_data{ value }\n        {}\n\n        basic_expected(value_type&& value)\n            : m_data{ std::move(value) }\n        {}\n        \n        template<typename ErrorT,\n            typename = typename traits::template enable_conversion<ErrorT>::type>\n        basic_expected(const unexpected<ErrorT>& errorEnum)\n            : m_data{ traits::convert(errorEnum.value()) }\n        {}\n\n        basic_expected(const unexpected<error_type>& ec)\n            : m_data{ ec.value() }\n        {\n            GSL_CONTRACT_CHECK(\"you should never build an basic_expected<T,E> with a non-error\", static_cast<bool>(error()));\n        }\n\n        basic_expected(unexpected<error_type>&& ec)\n            : m_data{ std::move(ec).value() }\n        {\n            GSL_CONTRACT_CHECK(\"you should never build an basic_expected<T,E> with a non-error\", static_cast<bool>(error()));\n        }\n\n        template<typename ErrorT,\n            typename = typename traits::template enable_conversion<ErrorT>::type>\n        basic_expected(const basic_expected<value_type, ErrorT>& other)\n            : m_data{ convert_variant(other) }\n        {}\n\n        template<typename ErrorT,\n            typename = typename traits::template enable_conversion<ErrorT>::type>\n        basic_expected& operator=(const basic_expected<value_type, ErrorT>& other)\n        {\n            m_data = convert_variant(other);\n        }\n\n        //\n        // Returns the expected value or throws bad_expected_access if it is in an error state.\n        //\n        const value_type& value() const\n        {\n            return const_cast<basic_expected*>(this)->value();\n        }\n\n        value_type& value()\n        {\n            auto val = std::get_if<value_type>(&m_data);\n            if (val == nullptr)\n            {\n                throw bad_expected_access();\n            }\n            return *val;\n        }\n\n        //\n        // Returns the value contained or the default passed in if the expected is in an error state.\n        //\n        template<typename U>\n        value_type value_or(U&& def) const\n        {\n            if (!has_value())\n            {\n                return std::forward<U>(def);\n            }\n\n            return value();\n        }\n\n        //\n        // Returns the error or throws bad_expected_access if it is not in an error state.\n        //\n        const error_type& error() const\n        {\n            auto err = std::get_if<error_type>(&m_data);\n            if (err == nullptr)\n            {\n                throw bad_expected_access();\n            }\n            return *err;\n        }\n\n        //\n        // Returns whether or not the expected contains a value.\n        //\n        bool has_value() const noexcept\n        {\n            return std::holds_alternative<value_type>(m_data);\n        }\n\n        //\n        // Returns whether or not the expected is in an error state.\n        //\n        bool has_error() const noexcept\n        {\n            return std::holds_alternative<error_type>(m_data);\n        }\n\n        //\n        // Converts to true if the value is valid.\n        //\n        explicit operator bool() const noexcept\n        {\n            return has_value();\n        }\n\n        //\n        // Shorthand access operators\n        //\n        const value_type& operator*() const\n        {\n            return value();\n        }\n\n        value_type& operator*()\n        {\n            return value();\n        }\n\n        //\n        // Shorthand access operators\n        //\n        const value_type* operator->() const\n        {\n            return &value();\n        }\n\n        value_type* operator->()\n        {\n            return &value();\n        }\n\n    private:\n        std::variant<error_type, value_type> m_data;\n    };\n\n    template<typename E>\n    class basic_expected<void, E>\n    {\n    public:\n        using value_type = void;\n        using error_type = E;\n\n        using traits = internal::expected_error_traits<error_type>;\n\n        template<typename ErrorT,\n            typename = typename traits::template enable_conversion<ErrorT>::type>\n        basic_expected(const unexpected<ErrorT>& errorEnum)\n            : m_error{ traits::convert(errorEnum.value()) }\n        {}\n\n        basic_expected(const unexpected<error_type>& ec)\n            : m_error{ ec.value() }\n        {\n            GSL_CONTRACT_CHECK(\"you should never build an basic_expected<T,E> with a non-error\", static_cast<bool>(error()));\n        }\n\n        basic_expected(unexpected<error_type>&& ec)\n            : m_error{ std::move(ec).value() }\n        {\n            GSL_CONTRACT_CHECK(\"you should never build an basic_expected<T,E> with a non-error\", static_cast<bool>(error()));\n        }\n\n        template<typename ErrorT,\n            typename = typename traits::template enable_conversion<ErrorT>::type>\n        basic_expected(const basic_expected<value_type, ErrorT>& other)\n            : m_error{ other.has_error() ? traits::convert(other.error()) : nullptr }\n        {}\n\n        template<typename ErrorT,\n            typename = typename traits::template enable_conversion<ErrorT>::type>\n        basic_expected& operator=(const basic_expected<value_type, ErrorT>& other)\n        {\n            m_error = other.has_error() ? traits::convert(other.error()) : nullptr;\n        }\n\n        //\n        // Returns the error, throws bad_expected_access if it is not in an error state\n        //\n        const error_type& error() const\n        {\n            if (!has_error())\n            {\n                throw bad_expected_access();\n            }\n            return m_error;\n        }\n\n        //\n        // Returns whether or not the expected is in an error state.\n        //\n        bool has_error() const noexcept\n        {\n            return static_cast<bool>(m_error);\n        }\n\n        //\n        // Converts to true if the value is valid.\n        //\n        explicit operator bool() const noexcept\n        {\n            return !has_error();\n        }\n\n        //\n        // Creates an expected<void> that doesn't have an error\n        //\n        static basic_expected make_valid()\n        {\n            return basic_expected{};\n        }\n\n    private:\n        basic_expected() = default;\n\n        error_type m_error;\n    };\n\n    template<typename Type>\n    struct is_expected : public std::false_type\n    {};\n\n    template<typename Type, typename Error>\n    struct is_expected<basic_expected<Type, Error>> : public std::true_type\n    {};\n\n    template<typename ResultT, typename ErrorT>\n    struct as_expected\n    {\n        using type = basic_expected<ResultT, ErrorT>;\n        using value_type = typename type::value_type;\n        using error_type = typename type::error_type;\n    };\n\n    template<typename ResultT, typename ErrorT, typename DesiredErrorT>\n    struct as_expected<basic_expected<ResultT, ErrorT>, DesiredErrorT>\n    {\n        static_assert(std::is_same<ErrorT, DesiredErrorT>::value, \"the error type of the expected and the desired error type don't match\");\n\n        using type = basic_expected<ResultT, ErrorT>;\n        using value_type = typename type::value_type;\n        using error_type = typename type::error_type;\n    };\n\n    template<typename ResultT, typename ErrorT>\n    using expected = basic_expected<ResultT, ErrorT>;\n\n    template<typename ErrorT>\n    struct error_priority;\n\n    template<>\n    struct error_priority<std::error_code> : std::integral_constant<int, 0>\n    {\n        using type = std::error_code;\n    };\n\n    template<>\n    struct error_priority<std::exception_ptr> : std::integral_constant<int, 1>\n    {\n        using type = std::exception_ptr;\n    };\n\n    template<typename Left, typename Right>\n    struct largest_error\n    {\n        using type = typename typename largest_integral_constant<error_priority<Left>, error_priority<Right>>::type::type;\n    };\n\n    namespace internal\n    {\n        template<typename Expected, typename OrType, bool IsExpected>\n        struct expected_error_or_impl\n        {\n            using type = OrType;\n        };\n\n        template<typename Expected, typename OrType>\n        struct expected_error_or_impl<Expected, OrType, true>\n        {\n            using type = typename Expected::error_type;\n        };\n    }\n\n    template<typename Expected, typename OrType>\n    struct expected_error_or : public internal::expected_error_or_impl<Expected, OrType, is_expected<Expected>::value>\n    {};\n}\n", "meta": {"hexsha": "c94ad68b3208a76b6d584a1261afea75040c69b1", "size": 11930, "ext": "h", "lang": "C", "max_stars_repo_path": "Source/Shared/arcana/expected.h", "max_stars_repo_name": "ryantrem/arcana.cpp", "max_stars_repo_head_hexsha": "1df97dab612caf0d25f9f00bda6d7ca2f27b7e6d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-25T10:03:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T10:25:56.000Z", "max_issues_repo_path": "Source/Shared/arcana/expected.h", "max_issues_repo_name": "ryantrem/arcana.cpp", "max_issues_repo_head_hexsha": "1df97dab612caf0d25f9f00bda6d7ca2f27b7e6d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/Shared/arcana/expected.h", "max_forks_repo_name": "ryantrem/arcana.cpp", "max_forks_repo_head_hexsha": "1df97dab612caf0d25f9f00bda6d7ca2f27b7e6d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2033096927, "max_line_length": 140, "alphanum_fraction": 0.5670578374, "num_tokens": 2422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.180106646483037, "lm_q2_score": 0.020332354752532266, "lm_q1q2_score": 0.0036619922295820263}}
{"text": "/*\n * VGMTrans (c) 2002-2019\n * Licensed under the zlib license,\n * refer to the included LICENSE.txt file\n */\n\n#pragma once\n\n#include <string>\n#include <sstream>\n#include <cassert>\n#include <cmath>\n#include <cstring>\n#include <iomanip>\n#include <climits>\n#include <algorithm>\n#include <vector>\n#include <gsl-lite.hpp>\n\n#include \"helper.h\"\n\n#define VERSION \"1.0.3\"\n\n/* Type aliases to save some typing */\nusing size_t = std::size_t;\n\nusing s8 = std::int8_t;\nusing s16 = std::int16_t;\nusing s32 = std::int32_t;\nusing s64 = std::int64_t;\nusing sptr = std::intptr_t;\n\nusing u8 = std::uint8_t;\nusing u16 = std::uint16_t;\nusing u32 = std::uint32_t;\nusing u64 = std::uint64_t;\nusing uptr = std::uintptr_t;\n\nstd::string removeExtFromPath(const std::string &s);\n\nstd::string StringToUpper(std::string myString);\nstd::string StringToLower(std::string myString);\n\nuint32_t StringToHex(const std::string &str);\n\nstd::string ConvertToSafeFileName(const std::string &str);\n\ninline int CountBytesOfVal(uint8_t *buf, uint32_t numBytes, uint8_t val) {\n    int count = 0;\n    for (uint32_t i = 0; i < numBytes; i++)\n        if (buf[i] == val)\n            count++;\n    return count;\n}\n\nstruct SizeOffsetPair {\n    uint32_t size;\n    uint32_t offset;\n\n    SizeOffsetPair() : size(0), offset(0) {}\n\n    SizeOffsetPair(uint32_t offset_, uint32_t size_) : size(size_), offset(offset_) {}\n};\n\nchar *GetFileWithBase(const char *f, const char *newfile);\n\nstd::vector<char> zdecompress(gsl::span<const char> data);\nstd::vector<char> zdecompress(std::vector<char> &data);\n", "meta": {"hexsha": "051df407ac6c24a278726803bd92e8a2f2eb2c12", "size": 1545, "ext": "h", "lang": "C", "max_stars_repo_path": "src/main/util/common.h", "max_stars_repo_name": "sykhro/vgmtrans-qt", "max_stars_repo_head_hexsha": "6d0780bdaaac29ffe118b9be2e2ad87401b426fe", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2018-01-04T17:42:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-26T02:52:22.000Z", "max_issues_repo_path": "src/main/util/common.h", "max_issues_repo_name": "sykhro/vgmtrans-qt", "max_issues_repo_head_hexsha": "6d0780bdaaac29ffe118b9be2e2ad87401b426fe", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2017-10-19T16:47:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-10T15:26:24.000Z", "max_forks_repo_path": "src/main/util/common.h", "max_forks_repo_name": "sykhro/vgmtrans-qt", "max_forks_repo_head_hexsha": "6d0780bdaaac29ffe118b9be2e2ad87401b426fe", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-10-19T16:40:12.000Z", "max_forks_repo_forks_event_max_datetime": "2017-10-19T16:40:12.000Z", "avg_line_length": 22.3913043478, "max_line_length": 86, "alphanum_fraction": 0.6951456311, "num_tokens": 442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16667540468797667, "lm_q2_score": 0.021948256153923946, "lm_q1q2_score": 0.003658234476650648}}
{"text": "/* vector/gsl_vector_uchar.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#ifndef __GSL_VECTOR_UCHAR_H__\n#define __GSL_VECTOR_UCHAR_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_block_uchar.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size;\n  size_t stride;\n  unsigned char *data;\n  gsl_block_uchar *block;\n  int owner;\n} \ngsl_vector_uchar;\n\ntypedef struct\n{\n  gsl_vector_uchar vector;\n} _gsl_vector_uchar_view;\n\ntypedef _gsl_vector_uchar_view gsl_vector_uchar_view;\n\ntypedef struct\n{\n  gsl_vector_uchar vector;\n} _gsl_vector_uchar_const_view;\n\ntypedef const _gsl_vector_uchar_const_view gsl_vector_uchar_const_view;\n\n\n/* Allocation */\n\ngsl_vector_uchar *gsl_vector_uchar_alloc (const size_t n);\ngsl_vector_uchar *gsl_vector_uchar_calloc (const size_t n);\n\ngsl_vector_uchar *gsl_vector_uchar_alloc_from_block (gsl_block_uchar * b,\n                                                     const size_t offset, \n                                                     const size_t n, \n                                                     const size_t stride);\n\ngsl_vector_uchar *gsl_vector_uchar_alloc_from_vector (gsl_vector_uchar * v,\n                                                      const size_t offset, \n                                                      const size_t n, \n                                                      const size_t stride);\n\nvoid gsl_vector_uchar_free (gsl_vector_uchar * v);\n\n/* Views */\n\n_gsl_vector_uchar_view \ngsl_vector_uchar_view_array (unsigned char *v, size_t n);\n\n_gsl_vector_uchar_view \ngsl_vector_uchar_view_array_with_stride (unsigned char *base,\n                                         size_t stride,\n                                         size_t n);\n\n_gsl_vector_uchar_const_view \ngsl_vector_uchar_const_view_array (const unsigned char *v, size_t n);\n\n_gsl_vector_uchar_const_view \ngsl_vector_uchar_const_view_array_with_stride (const unsigned char *base,\n                                               size_t stride,\n                                               size_t n);\n\n_gsl_vector_uchar_view \ngsl_vector_uchar_subvector (gsl_vector_uchar *v, \n                            size_t i, \n                            size_t n);\n\n_gsl_vector_uchar_view \ngsl_vector_uchar_subvector_with_stride (gsl_vector_uchar *v, \n                                        size_t i,\n                                        size_t stride,\n                                        size_t n);\n\n_gsl_vector_uchar_const_view \ngsl_vector_uchar_const_subvector (const gsl_vector_uchar *v, \n                                  size_t i, \n                                  size_t n);\n\n_gsl_vector_uchar_const_view \ngsl_vector_uchar_const_subvector_with_stride (const gsl_vector_uchar *v, \n                                              size_t i, \n                                              size_t stride,\n                                              size_t n);\n\n/* Operations */\n\nunsigned char gsl_vector_uchar_get (const gsl_vector_uchar * v, const size_t i);\nvoid gsl_vector_uchar_set (gsl_vector_uchar * v, const size_t i, unsigned char x);\n\nunsigned char *gsl_vector_uchar_ptr (gsl_vector_uchar * v, const size_t i);\nconst unsigned char *gsl_vector_uchar_const_ptr (const gsl_vector_uchar * v, const size_t i);\n\nvoid gsl_vector_uchar_set_zero (gsl_vector_uchar * v);\nvoid gsl_vector_uchar_set_all (gsl_vector_uchar * v, unsigned char x);\nint gsl_vector_uchar_set_basis (gsl_vector_uchar * v, size_t i);\n\nint gsl_vector_uchar_fread (FILE * stream, gsl_vector_uchar * v);\nint gsl_vector_uchar_fwrite (FILE * stream, const gsl_vector_uchar * v);\nint gsl_vector_uchar_fscanf (FILE * stream, gsl_vector_uchar * v);\nint gsl_vector_uchar_fprintf (FILE * stream, const gsl_vector_uchar * v,\n                              const char *format);\n\nint gsl_vector_uchar_memcpy (gsl_vector_uchar * dest, const gsl_vector_uchar * src);\n\nint gsl_vector_uchar_reverse (gsl_vector_uchar * v);\n\nint gsl_vector_uchar_swap (gsl_vector_uchar * v, gsl_vector_uchar * w);\nint gsl_vector_uchar_swap_elements (gsl_vector_uchar * v, const size_t i, const size_t j);\n\nunsigned char gsl_vector_uchar_max (const gsl_vector_uchar * v);\nunsigned char gsl_vector_uchar_min (const gsl_vector_uchar * v);\nvoid gsl_vector_uchar_minmax (const gsl_vector_uchar * v, unsigned char * min_out, unsigned char * max_out);\n\nsize_t gsl_vector_uchar_max_index (const gsl_vector_uchar * v);\nsize_t gsl_vector_uchar_min_index (const gsl_vector_uchar * v);\nvoid gsl_vector_uchar_minmax_index (const gsl_vector_uchar * v, size_t * imin, size_t * imax);\n\nint gsl_vector_uchar_add (gsl_vector_uchar * a, const gsl_vector_uchar * b);\nint gsl_vector_uchar_sub (gsl_vector_uchar * a, const gsl_vector_uchar * b);\nint gsl_vector_uchar_mul (gsl_vector_uchar * a, const gsl_vector_uchar * b);\nint gsl_vector_uchar_div (gsl_vector_uchar * a, const gsl_vector_uchar * b);\nint gsl_vector_uchar_scale (gsl_vector_uchar * a, const double x);\nint gsl_vector_uchar_add_constant (gsl_vector_uchar * a, const double x);\n\nint gsl_vector_uchar_isnull (const gsl_vector_uchar * v);\n\n#ifdef HAVE_INLINE\n\nextern inline\nunsigned char\ngsl_vector_uchar_get (const gsl_vector_uchar * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_VAL (\"index out of range\", GSL_EINVAL, 0);\n    }\n#endif\n  return v->data[i * v->stride];\n}\n\nextern inline\nvoid\ngsl_vector_uchar_set (gsl_vector_uchar * v, const size_t i, unsigned char x)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_VOID (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  v->data[i * v->stride] = x;\n}\n\nextern inline\nunsigned char *\ngsl_vector_uchar_ptr (gsl_vector_uchar * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return (unsigned char *) (v->data + i * v->stride);\n}\n\nextern inline\nconst unsigned char *\ngsl_vector_uchar_const_ptr (const gsl_vector_uchar * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return (const unsigned char *) (v->data + i * v->stride);\n}\n\n\n#endif /* HAVE_INLINE */\n\n__END_DECLS\n\n#endif /* __GSL_VECTOR_UCHAR_H__ */\n\n\n", "meta": {"hexsha": "b778ad65c7b60ae0e4dee0f48686bcac713d4ab9", "size": 7209, "ext": "h", "lang": "C", "max_stars_repo_path": "gsl_subset/gsl/gsl_vector_uchar.h", "max_stars_repo_name": "pvnuffel/test_repos", "max_stars_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2015-04-29T05:13:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T02:07:41.000Z", "max_issues_repo_path": "gsl_subset/gsl/gsl_vector_uchar.h", "max_issues_repo_name": "pvnuffel/test_repos", "max_issues_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-11-07T05:42:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-20T16:32:02.000Z", "max_forks_repo_path": "gsl_subset/gsl/gsl_vector_uchar.h", "max_forks_repo_name": "pvnuffel/test_repos", "max_forks_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-04-29T20:31:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-10T03:09:53.000Z", "avg_line_length": 31.7577092511, "max_line_length": 108, "alphanum_fraction": 0.6760993203, "num_tokens": 1782, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16667540882736176, "lm_q2_score": 0.021948253474960704, "lm_q1q2_score": 0.003658234120985639}}
{"text": "#ifndef TTT_UTIL_FONTCACHE_H\n#define TTT_UTIL_FONTCACHE_H\n\n#include <SDL_ttf.h>\n\n#include <gsl/pointers>\n#include <gsl/util>\n\n#include <vector>\n#include <memory>\n#include <string_view>\n\nnamespace ttt::gfx\n{\n\t// A class for caching fonts for reuse.\n\tclass FontCache final\n\t{\n\tpublic:\n\t\tusing SizeType = gsl::index;\n\n\t\tTTF_Font  *load(std::string_view path, int size, int index = 0);\n\t\tvoid unload(SizeType index) noexcept;\n\t\tvoid erase(SizeType index) noexcept;\n\t\tvoid clear() noexcept;\n\n\t\t[[nodiscard]] TTF_Font *at(SizeType index) const noexcept;\n\t\t[[nodiscard]] TTF_Font *operator [](SizeType index) const noexcept;\n\t\t\n\t\t[[nodiscard]] SizeType getSize() const noexcept;\n\t\t[[nodiscard]] SizeType getMaxSize() const noexcept;\n\n\tprivate:\n\t\tstd::vector<std::unique_ptr<TTF_Font, decltype(&TTF_CloseFont)>> fonts;\n\t};\n\n\tinline void FontCache::unload(SizeType index) noexcept { gsl::at(fonts, index).reset(); }\n\tinline void FontCache::erase(SizeType index) noexcept { fonts.erase(fonts.cbegin() + index); }\n\tinline void FontCache::clear() noexcept { fonts.clear(); }\n\n\tinline TTF_Font *FontCache::at(SizeType index) const noexcept { return gsl::at(fonts, index).get(); }\n\tinline TTF_Font *FontCache::operator [](SizeType index) const noexcept { return gsl::at(fonts, index).get(); }\n\n\tinline FontCache::SizeType FontCache::getSize() const noexcept { return fonts.size(); }\n\tinline FontCache::SizeType FontCache::getMaxSize() const noexcept { return fonts.max_size(); }\n}\n\n#endif", "meta": {"hexsha": "2d407c2decc03885d9d282c22736550b3c32cd81", "size": 1474, "ext": "h", "lang": "C", "max_stars_repo_path": "Source/Graphics/FontCache.h", "max_stars_repo_name": "itsArtem/TicTacToe", "max_stars_repo_head_hexsha": "8c70a77e4603dd0ff22ec0621b978ec0685ec3cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Source/Graphics/FontCache.h", "max_issues_repo_name": "itsArtem/TicTacToe", "max_issues_repo_head_hexsha": "8c70a77e4603dd0ff22ec0621b978ec0685ec3cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/Graphics/FontCache.h", "max_forks_repo_name": "itsArtem/TicTacToe", "max_forks_repo_head_hexsha": "8c70a77e4603dd0ff22ec0621b978ec0685ec3cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3617021277, "max_line_length": 111, "alphanum_fraction": 0.7286295794, "num_tokens": 380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11920292202211756, "lm_q2_score": 0.030675802375298614, "lm_q1q2_score": 0.0036566452785086094}}
{"text": "// SPDX-License-Identifier: MIT\n// The MIT License (MIT)\n//\n// Copyright (c) 2014-2018, Institute for Software & Systems Engineering\n// Copyright (c) 2018-2019, Johannes Leupolz\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n#ifndef PEMC_EXECUTABLE_MODEL_ABSTRACT_MODEL_H_\n#define PEMC_EXECUTABLE_MODEL_ABSTRACT_MODEL_H_\n\n#include <vector>\n#include <gsl/span>\n#include <gsl/gsl_byte>\n#include <cstdint>\n#include <atomic>\n#include <stack>\n#include <limits>\n#include <functional>\n\n#include \"pemc/basic/tsc_index.h\"\n#include \"pemc/basic/label.h\"\n#include \"pemc/basic/model_capacity.h\"\n#include \"pemc/basic/probability.h\"\n#include \"pemc/basic/raw_memory.h\"\n#include \"pemc/formula/formula.h\"\n#include \"pemc/generic_traverser/i_transitions_calculator.h\"\n#include \"pemc/generic_traverser/i_pre_state_storage_modifier.h\"\n#include \"pemc/generic_traverser/i_post_state_storage_modifier.h\"\n#include \"pemc/executable_model/i_choice_resolver.h\"\n\nnamespace pemc {\n\n  class AbstractModel {\n  protected:\n      IChoiceResolver* choiceResolver = nullptr;\n      std::vector<std::function<bool()>> formulaEvaluators;\n  public:\n      AbstractModel() {}\n      virtual ~AbstractModel() {}\n\n      //AbstractModel(const AbstractModel&) = delete;\n\n      void setChoiceResolver(IChoiceResolver* _choiceResolver);\n\n      virtual void serialize(gsl::span<gsl::byte> position) {}\n\n      virtual void deserialize(gsl::span<gsl::byte> position) {}\n\n      virtual void setFormulasForLabel(const std::vector<std::shared_ptr<Formula>>& _formulas) {}\n\n      Label calculateLabel();\n\n      size_t choose(const gsl::span<Probability>& choices);\n\n      size_t choose(size_t numberOfChoices);\n\n      virtual void resetToInitialState() {}\n\n      virtual void step() {}\n\n      virtual int32_t getStateVectorSize() {return 0;}\n  };\n\n}\n\n#endif  // PEMC_EXECUTABLE_MODEL_ABSTRACT_MODEL_H_\n", "meta": {"hexsha": "3a17b85947facbea18d2929ae018a2529e74feb0", "size": 2873, "ext": "h", "lang": "C", "max_stars_repo_path": "pemc/executable_model/abstract_model.h", "max_stars_repo_name": "joleuger/pemc", "max_stars_repo_head_hexsha": "14deb5b97d4219ba3c92d3834ab71332997e9b13", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pemc/executable_model/abstract_model.h", "max_issues_repo_name": "joleuger/pemc", "max_issues_repo_head_hexsha": "14deb5b97d4219ba3c92d3834ab71332997e9b13", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pemc/executable_model/abstract_model.h", "max_forks_repo_name": "joleuger/pemc", "max_forks_repo_head_hexsha": "14deb5b97d4219ba3c92d3834ab71332997e9b13", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2023809524, "max_line_length": 97, "alphanum_fraction": 0.7507831535, "num_tokens": 665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.196826208354418, "lm_q2_score": 0.018546562749059203, "lm_q1q2_score": 0.0036504496239046142}}
{"text": "/* matrix/gsl_matrix_ushort.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#ifndef __GSL_MATRIX_USHORT_H__\n#define __GSL_MATRIX_USHORT_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_vector_ushort.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size1;\n  size_t size2;\n  size_t tda;\n  unsigned short * data;\n  gsl_block_ushort * block;\n  int owner;\n} gsl_matrix_ushort;\n\ntypedef struct\n{\n  gsl_matrix_ushort matrix;\n} _gsl_matrix_ushort_view;\n\ntypedef _gsl_matrix_ushort_view gsl_matrix_ushort_view;\n\ntypedef struct\n{\n  gsl_matrix_ushort matrix;\n} _gsl_matrix_ushort_const_view;\n\ntypedef const _gsl_matrix_ushort_const_view gsl_matrix_ushort_const_view;\n\n/* Allocation */\n\ngsl_matrix_ushort * \ngsl_matrix_ushort_alloc (const size_t n1, const size_t n2);\n\ngsl_matrix_ushort * \ngsl_matrix_ushort_calloc (const size_t n1, const size_t n2);\n\ngsl_matrix_ushort * \ngsl_matrix_ushort_alloc_from_block (gsl_block_ushort * b, \n                                   const size_t offset, \n                                   const size_t n1, \n                                   const size_t n2, \n                                   const size_t d2);\n\ngsl_matrix_ushort * \ngsl_matrix_ushort_alloc_from_matrix (gsl_matrix_ushort * m,\n                                    const size_t k1, \n                                    const size_t k2,\n                                    const size_t n1, \n                                    const size_t n2);\n\ngsl_vector_ushort * \ngsl_vector_ushort_alloc_row_from_matrix (gsl_matrix_ushort * m,\n                                        const size_t i);\n\ngsl_vector_ushort * \ngsl_vector_ushort_alloc_col_from_matrix (gsl_matrix_ushort * m,\n                                        const size_t j);\n\nvoid gsl_matrix_ushort_free (gsl_matrix_ushort * m);\n\n/* Views */\n\n_gsl_matrix_ushort_view \ngsl_matrix_ushort_submatrix (gsl_matrix_ushort * m, \n                            const size_t i, const size_t j, \n                            const size_t n1, const size_t n2);\n\n_gsl_vector_ushort_view \ngsl_matrix_ushort_row (gsl_matrix_ushort * m, const size_t i);\n\n_gsl_vector_ushort_view \ngsl_matrix_ushort_column (gsl_matrix_ushort * m, const size_t j);\n\n_gsl_vector_ushort_view \ngsl_matrix_ushort_diagonal (gsl_matrix_ushort * m);\n\n_gsl_vector_ushort_view \ngsl_matrix_ushort_subdiagonal (gsl_matrix_ushort * m, const size_t k);\n\n_gsl_vector_ushort_view \ngsl_matrix_ushort_superdiagonal (gsl_matrix_ushort * m, const size_t k);\n\n_gsl_matrix_ushort_view\ngsl_matrix_ushort_view_array (unsigned short * base,\n                             const size_t n1, \n                             const size_t n2);\n\n_gsl_matrix_ushort_view\ngsl_matrix_ushort_view_array_with_tda (unsigned short * base, \n                                      const size_t n1, \n                                      const size_t n2,\n                                      const size_t tda);\n\n\n_gsl_matrix_ushort_view\ngsl_matrix_ushort_view_vector (gsl_vector_ushort * v,\n                              const size_t n1, \n                              const size_t n2);\n\n_gsl_matrix_ushort_view\ngsl_matrix_ushort_view_vector_with_tda (gsl_vector_ushort * v,\n                                       const size_t n1, \n                                       const size_t n2,\n                                       const size_t tda);\n\n\n_gsl_matrix_ushort_const_view \ngsl_matrix_ushort_const_submatrix (const gsl_matrix_ushort * m, \n                                  const size_t i, const size_t j, \n                                  const size_t n1, const size_t n2);\n\n_gsl_vector_ushort_const_view \ngsl_matrix_ushort_const_row (const gsl_matrix_ushort * m, \n                            const size_t i);\n\n_gsl_vector_ushort_const_view \ngsl_matrix_ushort_const_column (const gsl_matrix_ushort * m, \n                               const size_t j);\n\n_gsl_vector_ushort_const_view\ngsl_matrix_ushort_const_diagonal (const gsl_matrix_ushort * m);\n\n_gsl_vector_ushort_const_view \ngsl_matrix_ushort_const_subdiagonal (const gsl_matrix_ushort * m, \n                                    const size_t k);\n\n_gsl_vector_ushort_const_view \ngsl_matrix_ushort_const_superdiagonal (const gsl_matrix_ushort * m, \n                                      const size_t k);\n\n_gsl_matrix_ushort_const_view\ngsl_matrix_ushort_const_view_array (const unsigned short * base,\n                                   const size_t n1, \n                                   const size_t n2);\n\n_gsl_matrix_ushort_const_view\ngsl_matrix_ushort_const_view_array_with_tda (const unsigned short * base, \n                                            const size_t n1, \n                                            const size_t n2,\n                                            const size_t tda);\n\n_gsl_matrix_ushort_const_view\ngsl_matrix_ushort_const_view_vector (const gsl_vector_ushort * v,\n                                    const size_t n1, \n                                    const size_t n2);\n\n_gsl_matrix_ushort_const_view\ngsl_matrix_ushort_const_view_vector_with_tda (const gsl_vector_ushort * v,\n                                             const size_t n1, \n                                             const size_t n2,\n                                             const size_t tda);\n\n/* Operations */\n\nunsigned short   gsl_matrix_ushort_get(const gsl_matrix_ushort * m, const size_t i, const size_t j);\nvoid    gsl_matrix_ushort_set(gsl_matrix_ushort * m, const size_t i, const size_t j, const unsigned short x);\n\nunsigned short * gsl_matrix_ushort_ptr(gsl_matrix_ushort * m, const size_t i, const size_t j);\nconst unsigned short * gsl_matrix_ushort_const_ptr(const gsl_matrix_ushort * m, const size_t i, const size_t j);\n\nvoid gsl_matrix_ushort_set_zero (gsl_matrix_ushort * m);\nvoid gsl_matrix_ushort_set_identity (gsl_matrix_ushort * m);\nvoid gsl_matrix_ushort_set_all (gsl_matrix_ushort * m, unsigned short x);\n\nint gsl_matrix_ushort_fread (FILE * stream, gsl_matrix_ushort * m) ;\nint gsl_matrix_ushort_fwrite (FILE * stream, const gsl_matrix_ushort * m) ;\nint gsl_matrix_ushort_fscanf (FILE * stream, gsl_matrix_ushort * m);\nint gsl_matrix_ushort_fprintf (FILE * stream, const gsl_matrix_ushort * m, const char * format);\n \nint gsl_matrix_ushort_memcpy(gsl_matrix_ushort * dest, const gsl_matrix_ushort * src);\nint gsl_matrix_ushort_swap(gsl_matrix_ushort * m1, const gsl_matrix_ushort * m2);\n\nint gsl_matrix_ushort_swap_rows(gsl_matrix_ushort * m, const size_t i, const size_t j);\nint gsl_matrix_ushort_swap_columns(gsl_matrix_ushort * m, const size_t i, const size_t j);\nint gsl_matrix_ushort_swap_rowcol(gsl_matrix_ushort * m, const size_t i, const size_t j);\nint gsl_matrix_ushort_transpose (gsl_matrix_ushort * m);\nint gsl_matrix_ushort_transpose_memcpy (gsl_matrix_ushort * dest, const gsl_matrix_ushort * src);\n\nunsigned short gsl_matrix_ushort_max (const gsl_matrix_ushort * m);\nunsigned short gsl_matrix_ushort_min (const gsl_matrix_ushort * m);\nvoid gsl_matrix_ushort_minmax (const gsl_matrix_ushort * m, unsigned short * min_out, unsigned short * max_out);\n\nvoid gsl_matrix_ushort_max_index (const gsl_matrix_ushort * m, size_t * imax, size_t *jmax);\nvoid gsl_matrix_ushort_min_index (const gsl_matrix_ushort * m, size_t * imin, size_t *jmin);\nvoid gsl_matrix_ushort_minmax_index (const gsl_matrix_ushort * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);\n\nint gsl_matrix_ushort_isnull (const gsl_matrix_ushort * m);\n\nint gsl_matrix_ushort_add (gsl_matrix_ushort * a, const gsl_matrix_ushort * b);\nint gsl_matrix_ushort_sub (gsl_matrix_ushort * a, const gsl_matrix_ushort * b);\nint gsl_matrix_ushort_mul_elements (gsl_matrix_ushort * a, const gsl_matrix_ushort * b);\nint gsl_matrix_ushort_div_elements (gsl_matrix_ushort * a, const gsl_matrix_ushort * b);\nint gsl_matrix_ushort_scale (gsl_matrix_ushort * a, const double x);\nint gsl_matrix_ushort_add_constant (gsl_matrix_ushort * a, const double x);\n\n/***********************************************************************/\n/* The functions below are obsolete                                    */\n/***********************************************************************/\nint gsl_matrix_ushort_get_row(gsl_vector_ushort * v, const gsl_matrix_ushort * m, const size_t i);\nint gsl_matrix_ushort_get_col(gsl_vector_ushort * v, const gsl_matrix_ushort * m, const size_t j);\nint gsl_matrix_ushort_set_row(gsl_matrix_ushort * m, const size_t i, const gsl_vector_ushort * v);\nint gsl_matrix_ushort_set_col(gsl_matrix_ushort * m, const size_t j, const gsl_vector_ushort * v);\n\nextern int gsl_check_range ;\n\n/* inline functions if you are using GCC */\n\n#ifdef HAVE_INLINE\nextern inline \nunsigned short\ngsl_matrix_ushort_get(const gsl_matrix_ushort * m, const size_t i, const size_t j)\n{\n#ifndef GSL_RANGE_CHECK_OFF\n  if (i >= m->size1)\n    {\n      GSL_ERROR_VAL(\"first index out of range\", GSL_EINVAL, 0) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_VAL(\"second index out of range\", GSL_EINVAL, 0) ;\n    }\n#endif\n  return m->data[i * m->tda + j] ;\n} \n\nextern inline \nvoid\ngsl_matrix_ushort_set(gsl_matrix_ushort * m, const size_t i, const size_t j, const unsigned short x)\n{\n#ifndef GSL_RANGE_CHECK_OFF\n  if (i >= m->size1)\n    {\n      GSL_ERROR_VOID(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_VOID(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  m->data[i * m->tda + j] = x ;\n}\n\nextern inline \nunsigned short *\ngsl_matrix_ushort_ptr(gsl_matrix_ushort * m, const size_t i, const size_t j)\n{\n#ifndef GSL_RANGE_CHECK_OFF\n  if (i >= m->size1)\n    {\n      GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  return (unsigned short *) (m->data + (i * m->tda + j)) ;\n} \n\nextern inline \nconst unsigned short *\ngsl_matrix_ushort_const_ptr(const gsl_matrix_ushort * m, const size_t i, const size_t j)\n{\n#ifndef GSL_RANGE_CHECK_OFF\n  if (i >= m->size1)\n    {\n      GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n    }\n  else if (j >= m->size2)\n    {\n      GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n    }\n#endif\n  return (const unsigned short *) (m->data + (i * m->tda + j)) ;\n} \n\n#endif\n\n__END_DECLS\n\n#endif /* __GSL_MATRIX_USHORT_H__ */\n", "meta": {"hexsha": "c5baa9812af5019d4edb36919cff05365623d93a", "size": 11215, "ext": "h", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/matrix/gsl_matrix_ushort.h", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/matrix/gsl_matrix_ushort.h", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/matrix/gsl_matrix_ushort.h", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 35.4905063291, "max_line_length": 126, "alphanum_fraction": 0.6706197058, "num_tokens": 2771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.17106119167858438, "lm_q2_score": 0.021287351754644333, "lm_q1q2_score": 0.003641439758830664}}
{"text": "#pragma once\n\n#include <functional>\n#include <gsl/gsl_util>\n#include <vector>\n\nstruct Executor;\nnamespace detail {\nExecutor*& get_current_executor_holder();\n}\n\nstruct Executor {\n  using WorkQueue = std::vector<std::function<void()>>;\n\n  void add_work(std::function<void()> fn) {\n    work_.emplace_back(std::move(fn));\n  }\n\n  void execute() {\n    const auto cleanup                    = gsl::finally([&] { //\n      detail::get_current_executor_holder() = nullptr;\n    });\n    detail::get_current_executor_holder() = this;\n\n    while (not work_.empty()) {\n      auto pending_work = WorkQueue{};\n      swap(pending_work, work_);\n      for (auto&& fn : pending_work) {\n        fn();\n      }\n    }\n  }\n\n  WorkQueue work_;\n};\n\ninline Executor& get_current_executor() {\n  return *detail::get_current_executor_holder();\n}\n", "meta": {"hexsha": "6e17f689b9b78d312ec3dd41a7e7bc0fcf9bbeda", "size": 814, "ext": "h", "lang": "C", "max_stars_repo_path": "mixed/src/executor.h", "max_stars_repo_name": "adrianimboden/cppusergroup-adynchronous-programming", "max_stars_repo_head_hexsha": "d6fad3ff980be2e7c13ed9e3e05b62e984c9caa4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mixed/src/executor.h", "max_issues_repo_name": "adrianimboden/cppusergroup-adynchronous-programming", "max_issues_repo_head_hexsha": "d6fad3ff980be2e7c13ed9e3e05b62e984c9caa4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mixed/src/executor.h", "max_forks_repo_name": "adrianimboden/cppusergroup-adynchronous-programming", "max_forks_repo_head_hexsha": "d6fad3ff980be2e7c13ed9e3e05b62e984c9caa4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.35, "max_line_length": 65, "alphanum_fraction": 0.6351351351, "num_tokens": 187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10669059394565121, "lm_q2_score": 0.03410042264475985, "lm_q1q2_score": 0.0036381943457671623}}
{"text": "#pragma once\n\n#define QT_IS_BROKEN\n#define QAPPLICATION_CLASS QApplication // for SingleApplication\n\n// Windows\n#include <Windows.h>\n#include <SetupAPI.h>\n\n#include <winioctl.h>\n#include <BluetoothAPIs.h>\n#include <Bthioctl.h>\n\n#include <Dbt.h>\n#include <Hidsdi.h>\n#include <shellapi.h>\n#include <Xinput.h>\n\n// STL\n#include <array>\n#include <chrono>\n#include <cmath>\n#include <cstdint>\n#include <deque>\n#include <functional>\n#include <iomanip>\n#include <list>\n#include <map>\n#include <memory>\n#include <mutex>\n#include <optional>\n#include <sstream>\n#include <string>\n#include <thread>\n#include <unordered_map>\n\n// Qt\n#include <QDialog>\n#include <QtWidgets/QApplication>\n#include <QtWidgets/QMainWindow>\n#include <QtWidgets>\n\n#include <singleapplication.h>\n\n// GSL\n#include <gsl/span>\n\n// better-enums\n#include <enum.h>\n\n// fmt\n#include <fmt/format.h>\n\n// libhid\n#include <hid_handle.h>\n#include <hid_instance.h>\n#include <hid_util.h>\n\n// ViGEm\n#include <ViGEm/Client.h>\n#include <ViGEm/Common.h>\n#include <ViGEm/km/BusShared.h>\n\n#include \"MapCache.h\"\n#include \"average.h\"\n#include \"AxisOptions.h\"\n#include \"Bluetooth.h\"\n#include \"busenum.h\"\n#include \"ConnectionType.h\"\n#include \"DeviceIdleOptions.h\"\n#include \"DeviceProfile.h\"\n#include \"DeviceProfileCache.h\"\n#include \"DevicePropertiesDialog.h\"\n#include \"DeviceSettings.h\"\n#include \"DeviceSettingsCommon.h\"\n#include \"Ds4AutoLightColor.h\"\n#include \"Ds4Color.h\"\n#include \"Ds4Device.h\"\n#include \"Ds4DeviceManager.h\"\n#include \"Ds4Input.h\"\n#include \"Ds4InputData.h\"\n#include \"Ds4ItemModel.h\"\n#include \"Ds4LightOptions.h\"\n#include \"Ds4Output.h\"\n#include \"Ds4TouchRegion.h\"\n#include \"enums.h\"\n#include \"Event.h\"\n#include \"gmath.h\"\n#include \"InputMap.h\"\n#include \"InputSimulator.h\"\n#include \"JsonData.h\"\n#include \"KeyboardSimulator.h\"\n#include \"Latency.h\"\n#include \"lock.h\"\n#include \"Logger.h\"\n#include \"MainWindow.h\"\n#include \"MouseSimulator.h\"\n#include \"pathutil.h\"\n#include \"Pressable.h\"\n#include \"ProfileEditorDialog.h\"\n#include \"program.h\"\n#include \"Settings.h\"\n#include \"Stopwatch.h\"\n#include \"stringutil.h\"\n#include \"Trackball.h\"\n#include \"Vector2.h\"\n#include \"Vector3.h\"\n#include \"XInputGamepad.h\"\n", "meta": {"hexsha": "437e5c40f8c9b214f6b8d457e150e27c03e61fba", "size": 2148, "ext": "h", "lang": "C", "max_stars_repo_path": "ds4wizard-cpp/pch.h", "max_stars_repo_name": "SonicFreak94/ds4wizard", "max_stars_repo_head_hexsha": "4d2ddc15b7db7cc5618c8676c91cf81614921c3c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T19:23:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-13T08:35:31.000Z", "max_issues_repo_path": "ds4wizard-cpp/pch.h", "max_issues_repo_name": "SonicFreak94/ds4wizard", "max_issues_repo_head_hexsha": "4d2ddc15b7db7cc5618c8676c91cf81614921c3c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-01-29T20:34:26.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-30T04:00:38.000Z", "max_forks_repo_path": "ds4wizard-cpp/pch.h", "max_forks_repo_name": "SonicFreak94/ds4wizard", "max_forks_repo_head_hexsha": "4d2ddc15b7db7cc5618c8676c91cf81614921c3c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.7064220183, "max_line_length": 64, "alphanum_fraction": 0.7430167598, "num_tokens": 552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2782567937024021, "lm_q2_score": 0.013020492076658327, "lm_q1q2_score": 0.003623040377678477}}
{"text": "#ifndef VEC_WRAPPER_H\n#define VEC_WRAPPER_H\n\n\n#include <atomic>\n\n#include <gsl/gsl_vector.h>\n\n\nclass Vector {\npublic:\n    Vector(); // null\n\n    Vector(gsl_vector *wrap);\n    Vector(const size_t length);\n    Vector(const Vector& copy);\n    virtual ~Vector();\n\n    gsl_vector *get() const;\n    void set(gsl_vector *newVector);\n    void reset(gsl_vector *newVector);\n\n    void reset(const size_t length);\n\n\n    explicit operator bool() const;\n\n    Vector &operator =(const Vector& copy);\n    void operator *=(const Vector& other);\n    double operator [](const size_t i) const;\n    double& operator [](const size_t i);\n\n\n    void coords();\n    void uncoords();\n    void basis(size_t i);\n\nprivate:\n    gsl_vector *m_vec;\n\n    std::atomic<unsigned int> m_delCount;\n};\n\n\n#endif // VEC_WRAPPER_H\n", "meta": {"hexsha": "e410c41ce21b7556d5575b8acf38566273c03075", "size": 789, "ext": "h", "lang": "C", "max_stars_repo_path": "inc/vector.h", "max_stars_repo_name": "ichi-rika/glottal-inverse", "max_stars_repo_head_hexsha": "c922ed540278e3c8eec528c2cf66b89e6d310575", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-01-24T17:01:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-26T16:22:08.000Z", "max_issues_repo_path": "inc/vector.h", "max_issues_repo_name": "ichi-rika/glottal-inverse", "max_issues_repo_head_hexsha": "c922ed540278e3c8eec528c2cf66b89e6d310575", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inc/vector.h", "max_forks_repo_name": "ichi-rika/glottal-inverse", "max_forks_repo_head_hexsha": "c922ed540278e3c8eec528c2cf66b89e6d310575", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-04-27T00:23:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-27T14:41:25.000Z", "avg_line_length": 17.152173913, "max_line_length": 45, "alphanum_fraction": 0.6603295311, "num_tokens": 191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11920292828022305, "lm_q2_score": 0.030214587831494465, "lm_q1q2_score": 0.0036016673462941347}}
{"text": "#pragma once\n\n#include <cassert>\n#include <exception>\n#include <functional>\n#include <set>\n#include <map>\n\n#include <nod/nod.hpp>\n\n#include <gsl-lite/gsl-lite.hpp>\n\n#include \"mutils/time/profiler.h\"\n\n#include \"threadpool/threadpool.h\"\n\n#include \"nodegraph/model/node.h\"\n#include \"nodegraph/model/pin.h\"\n\nnamespace NodeGraph\n{\n\n// A collection of nodes that can be computed\nclass Graph\n{\npublic:\n    Graph();\n    virtual ~Graph();\n    virtual void Clear();\n\n    // Use this method to create nodes and add them to the m_graph\n    template <typename T, typename... Args>\n    T* CreateNode(Args&&... args)\n    {\n        PreModify();\n\n        auto pNode = new T(*this, std::forward<Args>(args)...);\n        nodes.insert(pNode);\n        m_displayNodes.insert(pNode);\n        m_mapIdToNode[pNode->GetId()] = pNode;\n\n        PostModify();\n        return pNode;\n    }\n\n    void DestroyNode(Node* pNode);\n\n    bool IsType(Node& node, ctti::type_id_t type) const;\n\n    template <class T>\n    std::set<T*> Find(ctti::type_id_t type) const\n    {\n        std::set<T*> found;\n        for (auto& pNode : nodes)\n        {\n            if (IsType(*pNode, type))\n            {\n                found.insert(static_cast<T*>(pNode));\n            }\n        }\n        return found;\n    }\n\n    template <class T>\n    std::set<T*> Find(const std::vector<ctti::type_id_t>& nodeTypes) const\n    {\n        std::set<T*> found;\n        for (auto& t : nodeTypes)\n        {\n            auto f = Find<T>(t);\n            found.insert(f.begin(), f.end());\n        }\n        return found;\n    }\n\n    void Visit(Node& node, PinDir dir, ParameterType type, std::function<bool(Node&)> fn);\n\n    // Get the list of pins that could be on the UI\n    virtual std::vector<Pin*> GetControlSurface() const;\n\n    virtual void Compute(const std::set<Node*>& nodes, int64_t numTicks);\n\n    const std::set<Node*>& GetNodes() const\n    {\n        return nodes;\n    }\n\n    const std::set<Node*>& GetDisplayNodes() const\n    {\n        return m_displayNodes;\n    }\n    void SetDisplayNodes(const std::set<Node*>& nodes)\n    {\n        m_displayNodes = nodes;\n    }\n\n    const std::set<Node*>& GetOutputNodes() const\n    {\n        return m_outputNodes;\n    }\n    void SetOutputNodes(const std::set<Node*>& nodes)\n    {\n        m_outputNodes = nodes;\n    }\n\n    void PreModify()\n    {\n        if (m_modifyTracker == 0)\n        {\n            sigBeginModify(this);\n        }\n\n        m_modifyTracker++;\n    }\n\n    void PostModify()\n    {\n        assert(m_modifyTracker > 0);\n        m_modifyTracker--;\n        if (m_modifyTracker == 0)\n        {\n            sigEndModify(this);\n        }\n    }\n\n    void SetName(const std::string& name);\n    std::string Name() const;\n\n    // Called to notify that this graph is about to be destroyed\n    void NotifyDestroy(Graph* pGraph);\n\n    const std::map<uint64_t, Node*>& GetNodesById() const\n    {\n        return m_mapIdToNode;\n    }\n\n    // Signals\n    nod::signal<void(Graph*)> sigBeginModify;\n    nod::signal<void(Graph*)> sigEndModify;\n    nod::signal<void(Graph*)> sigDestroy;\n\nprotected:\n    uint32_t m_modifyTracker = 0;\n\n    std::map<uint64_t, Node*> m_mapIdToNode;\n\n    std::set<Node*> nodes;\n    std::set<Node*> m_displayNodes;\n    std::set<Node*> m_outputNodes;\n\n    uint64_t currentGeneration = 1;\n    std::string m_strName;\n}; // Graph\n\n} // namespace NodeGraph\n", "meta": {"hexsha": "65e79936f304de72e8874bb19ce33918fbf72ef6", "size": 3353, "ext": "h", "lang": "C", "max_stars_repo_path": "include/nodegraph/model/graph.h", "max_stars_repo_name": "Rezonality/nodegraph", "max_stars_repo_head_hexsha": "2eb4994c5bbf73cc9d41199fc8a309de6d1b46c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-09-17T20:59:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-24T02:43:12.000Z", "max_issues_repo_path": "include/nodegraph/model/graph.h", "max_issues_repo_name": "cmaughan/nodegraph", "max_issues_repo_head_hexsha": "207686ac742c9e5792f4f00d5c5d594ff0a4d0df", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/nodegraph/model/graph.h", "max_forks_repo_name": "cmaughan/nodegraph", "max_forks_repo_head_hexsha": "207686ac742c9e5792f4f00d5c5d594ff0a4d0df", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-12-08T18:43:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-24T09:03:19.000Z", "avg_line_length": 21.4935897436, "max_line_length": 90, "alphanum_fraction": 0.5848493886, "num_tokens": 845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18242552380635632, "lm_q2_score": 0.019719127675281077, "lm_q1q2_score": 0.0035972721951675678}}
{"text": "#pragma once\n#include <cassert>\n#include <cstdio>\n#include <cstdlib>\n#include <cfloat>\n\n#include <algorithm>\n#include <vector>\n#include <memory>\n#include <stdexcept>\n#include <map>\n\n#include <hip/hip_runtime.h>\n#include <hiprand_kernel.h> \n#include <gsl/gsl_assert.h>\n#include <nonstd/byte.hpp>\n#include <nonstd/expected.hpp>\n#include <nonstd/optional.hpp>\n#include <nonstd/span.hpp>\n#include <nonstd/ring_span.hpp>\n#include <nonstd/string_view.hpp>\n#include <nonstd/variant.hpp>\n#include <nonstd/value_ptr.hpp>\n\n#include \"kernel_config.h\"\n#include \"logger.h\"\n#include \"math.h\"\n\nusing nonstd::variant;\nusing nonstd::value_ptr;\nusing nonstd::make_value;\nusing nonstd::ring_span;\nusing nonstd::expected;\nusing nonstd::make_unexpected;\nusing nonstd::optional;\nusing nonstd::nullopt;\nusing nonstd::make_optional;\nusing nonstd::byte;\nusing nonstd::to_integer;\nusing nonstd::to_byte;\nusing nonstd::to_string;\nusing nonstd::string_view;\nusing nonstd::span;\nusing nonstd::make_span;\nusing bytearray = std::vector<byte>;\n\n#define HIP_ASSERT(x) (Ensures((x)==hipSuccess))\n\nstruct hip_free_deleter {\n    void operator()(void *p) const noexcept { hipFree(p); }\n};\n\ntemplate<typename T>\nusing host_unique_ptr = std::unique_ptr<T, hip_free_deleter>;\n\ntemplate<class T> struct _host_unique_if {\n    typedef void _single_object;\n};\n\ntemplate<class T> struct _host_unique_if<T[]> {\n    typedef host_unique_ptr<T[]> _unknown_bound;\n};\n\ntemplate<class T, std::size_t N> struct _host_unique_if<T[N]> {\n    typedef void _known_bound;\n};\n\ntemplate<class T, class... Args>\ntypename _host_unique_if<T>::_single_object\nhip_alloc_managed_unique(Args&&... args) = delete;\n\ntemplate<class T>\ntypename _host_unique_if<T>::_unknown_bound\nhip_alloc_managed_unique(std::size_t n) {\n    typedef typename std::remove_extent<T>::type U;\n    T *tmp;\n    HIP_ASSERT(hipMallocManaged(&tmp, n * sizeof(U)));\n    return host_unique_ptr<T>(reinterpret_cast<U*>(tmp));\n}\n\ntemplate<class T, class... Args>\ntypename _host_unique_if<T>::_known_bound\nhip_alloc_managed_unique(Args&&...) = delete;", "meta": {"hexsha": "3e55968407980c42c47ed31f58b2a1498b17bb14", "size": 2050, "ext": "h", "lang": "C", "max_stars_repo_path": "src/common.h", "max_stars_repo_name": "sargarass/Raytracer", "max_stars_repo_head_hexsha": "6b903970caa6eb56c642383c323a9bddf7b25629", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/common.h", "max_issues_repo_name": "sargarass/Raytracer", "max_issues_repo_head_hexsha": "6b903970caa6eb56c642383c323a9bddf7b25629", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/common.h", "max_forks_repo_name": "sargarass/Raytracer", "max_forks_repo_head_hexsha": "6b903970caa6eb56c642383c323a9bddf7b25629", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6987951807, "max_line_length": 63, "alphanum_fraction": 0.7502439024, "num_tokens": 524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.13846179767920994, "lm_q2_score": 0.025957355219835308, "lm_q1q2_score": 0.0035941020667362203}}
{"text": "// Copyright 2021 atframework\n// Created by owent on 2020-08-18\n\n#pragma once\n\n#include <gsl/select-gsl.h>\n\n#include <config/atframe_utils_build_feature.h>\n#include <config/compiler_features.h>\n\n#include <design_pattern/nomovable.h>\n#include <design_pattern/noncopyable.h>\n\n#include <random/random_generator.h>\n\n#include \"atframe/atapp_conf.h\"\n\nnamespace atapp {\nstruct LIBATAPP_MACRO_API_HEAD_ONLY etcd_discovery_action_t {\n  enum type {\n    EN_NAT_UNKNOWN = 0,\n    EN_NAT_PUT,\n    EN_NAT_DELETE,\n  };\n};\n\nclass etcd_discovery_node {\n public:\n  using on_destroy_fn_t = std::function<void(etcd_discovery_node &)>;\n  using ptr_t = std::shared_ptr<etcd_discovery_node>;\n\n  UTIL_DESIGN_PATTERN_NOCOPYABLE(etcd_discovery_node)\n  UTIL_DESIGN_PATTERN_NOMOVABLE(etcd_discovery_node)\n\n public:\n  LIBATAPP_MACRO_API etcd_discovery_node();\n  LIBATAPP_MACRO_API ~etcd_discovery_node();\n\n  UTIL_FORCEINLINE const atapp::protocol::atapp_discovery &get_discovery_info() const { return node_info_; }\n  LIBATAPP_MACRO_API void copy_from(const atapp::protocol::atapp_discovery &input);\n\n  UTIL_FORCEINLINE const std::pair<uint64_t, uint64_t> &get_name_hash() const { return name_hash_; }\n\n  UTIL_FORCEINLINE void set_private_data_ptr(void *input) { private_data_ptr_ = input; }\n  UTIL_FORCEINLINE void *get_private_data_ptr() const { return private_data_ptr_; }\n  UTIL_FORCEINLINE void set_private_data_u64(uint64_t input) { private_data_u64_ = input; }\n  UTIL_FORCEINLINE uint64_t get_private_data_u64() const { return private_data_u64_; }\n  UTIL_FORCEINLINE void set_private_data_i64(int64_t input) { private_data_i64_ = input; }\n  UTIL_FORCEINLINE int64_t get_private_data_i64() const { return private_data_i64_; }\n  UTIL_FORCEINLINE void set_private_data_uptr(uintptr_t input) { private_data_uptr_ = input; }\n  UTIL_FORCEINLINE uintptr_t get_private_data_uptr() const { return private_data_uptr_; }\n  UTIL_FORCEINLINE void set_private_data_iptr(intptr_t input) { private_data_iptr_ = input; }\n  UTIL_FORCEINLINE intptr_t get_private_data_iptr() const { return private_data_iptr_; }\n\n  LIBATAPP_MACRO_API void set_on_destroy(on_destroy_fn_t fn);\n  LIBATAPP_MACRO_API const on_destroy_fn_t &get_on_destroy() const;\n  LIBATAPP_MACRO_API void reset_on_destroy();\n\n  LIBATAPP_MACRO_API const atapp::protocol::atapp_gateway &next_ingress_gateway() const;\n  LIBATAPP_MACRO_API int32_t get_ingress_size() const;\n\n private:\n  atapp::protocol::atapp_discovery node_info_;\n  std::pair<uint64_t, uint64_t> name_hash_;\n  union {\n    void *private_data_ptr_;\n    uint64_t private_data_u64_;\n    int64_t private_data_i64_;\n    uintptr_t private_data_uptr_;\n    intptr_t private_data_iptr_;\n  };\n  on_destroy_fn_t on_destroy_fn_;\n  mutable int32_t ingress_index_;\n  mutable atapp::protocol::atapp_gateway ingress_for_listen_;\n};\n\nclass etcd_discovery_set {\n public:\n  using node_by_name_t = std::unordered_map<std::string, etcd_discovery_node::ptr_t>;\n  using node_by_id_t = std::unordered_map<uint64_t, etcd_discovery_node::ptr_t>;\n  using ptr_t = std::shared_ptr<etcd_discovery_set>;\n\n  struct node_hash_t {\n    enum { HASH_POINT_PER_INS = 80 };\n\n    etcd_discovery_node::ptr_t node;\n    std::pair<uint64_t, uint64_t> hash_code;\n  };\n\n  UTIL_DESIGN_PATTERN_NOCOPYABLE(etcd_discovery_set)\n  UTIL_DESIGN_PATTERN_NOMOVABLE(etcd_discovery_set)\n public:\n  LIBATAPP_MACRO_API etcd_discovery_set();\n  LIBATAPP_MACRO_API ~etcd_discovery_set();\n\n  LIBATAPP_MACRO_API bool empty() const;\n\n  LIBATAPP_MACRO_API etcd_discovery_node::ptr_t get_node_by_id(uint64_t id) const;\n  LIBATAPP_MACRO_API etcd_discovery_node::ptr_t get_node_by_name(gsl::string_view name) const;\n\n  LIBATAPP_MACRO_API etcd_discovery_node::ptr_t get_node_by_consistent_hash(const void *buf, size_t bufsz) const;\n  LIBATAPP_MACRO_API etcd_discovery_node::ptr_t get_node_by_consistent_hash(uint64_t key) const;\n  LIBATAPP_MACRO_API etcd_discovery_node::ptr_t get_node_by_consistent_hash(int64_t key) const;\n  LIBATAPP_MACRO_API etcd_discovery_node::ptr_t get_node_by_consistent_hash(gsl::string_view key) const;\n\n  LIBATAPP_MACRO_API etcd_discovery_node::ptr_t get_node_by_random() const;\n  LIBATAPP_MACRO_API etcd_discovery_node::ptr_t get_node_by_round_robin() const;\n\n  LIBATAPP_MACRO_API const std::vector<etcd_discovery_node::ptr_t> &get_sorted_nodes() const;\n  LIBATAPP_MACRO_API std::vector<etcd_discovery_node::ptr_t>::const_iterator lower_bound_sorted_nodes(\n      uint64_t id, gsl::string_view name) const;\n  LIBATAPP_MACRO_API std::vector<etcd_discovery_node::ptr_t>::const_iterator upper_bound_sorted_nodes(\n      uint64_t id, gsl::string_view name) const;\n\n  LIBATAPP_MACRO_API void add_node(const etcd_discovery_node::ptr_t &node);\n  LIBATAPP_MACRO_API void remove_node(const etcd_discovery_node::ptr_t &node);\n  LIBATAPP_MACRO_API void remove_node(uint64_t id);\n  LIBATAPP_MACRO_API void remove_node(gsl::string_view name);\n\n private:\n  void rebuild_cache() const;\n  void clear_cache() const;\n\n private:\n  node_by_name_t node_by_name_;\n  node_by_id_t node_by_id_;\n\n  mutable std::vector<node_hash_t> hashing_cache_;\n  mutable std::vector<etcd_discovery_node::ptr_t> round_robin_cache_;\n  mutable util::random::xoshiro256_starstar random_generator_;\n  mutable size_t round_robin_index_;\n};\n}  // namespace atapp\n", "meta": {"hexsha": "9b581491ce8dd2b20693a3291f4790b75a46697a", "size": 5257, "ext": "h", "lang": "C", "max_stars_repo_path": "include/atframe/etcdcli/etcd_discovery.h", "max_stars_repo_name": "atframework/libatapp", "max_stars_repo_head_hexsha": "54aae9e0972eb94c33a7c109bdd099ff3a89ee80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2018-06-23T04:38:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T01:22:54.000Z", "max_issues_repo_path": "include/atframe/etcdcli/etcd_discovery.h", "max_issues_repo_name": "atframework/libatapp", "max_issues_repo_head_hexsha": "54aae9e0972eb94c33a7c109bdd099ff3a89ee80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/atframe/etcdcli/etcd_discovery.h", "max_forks_repo_name": "atframework/libatapp", "max_forks_repo_head_hexsha": "54aae9e0972eb94c33a7c109bdd099ff3a89ee80", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-08-04T06:14:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-19T10:06:06.000Z", "avg_line_length": 39.2313432836, "max_line_length": 113, "alphanum_fraction": 0.8069241012, "num_tokens": 1406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19930799790404563, "lm_q2_score": 0.01798621335072534, "lm_q1q2_score": 0.0035847961728080833}}
{"text": "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\n#pragma once\n#include <iosfwd>\n#include <vector>\n#include <algorithm>\n#include <string>\n#include <cstring>\n#include <gsl/gsl>\n#include \"onnxruntime_config.h\"\n\nnamespace onnxruntime {\n#ifdef __GNUC__\n#pragma GCC diagnostic push\n#ifdef HAS_NULL_DEREFERENCE\n#pragma GCC diagnostic ignored \"-Wnull-dereference\"\n#endif\n#endif\nclass TensorShape {\n  // We use negative numbers for unknown symbolic dimension. Each negative\n  // number represents a unique symbolic dimension.\n public:\n  TensorShape() = default;\n\n  TensorShape(const TensorShape& other) : TensorShape(other.GetDims()) {}\n  TensorShape& operator=(const TensorShape& other);\n\n  TensorShape(TensorShape&& other) { operator=(std::move(other)); }\n  TensorShape& operator=(TensorShape&& other);\n\n  TensorShape(gsl::span<const int64_t> dims);\n  TensorShape(const std::vector<int64_t>& dims) : TensorShape(gsl::make_span(dims)) {}\n  TensorShape(const std::initializer_list<int64_t>& dims) : TensorShape(gsl::make_span(dims)) {}\n  TensorShape(const int64_t* dimension_sizes, size_t dimension_count) : TensorShape(gsl::span<const int64_t>(dimension_sizes, dimension_count)) {}\n  TensorShape(const std::vector<int64_t>& dims, size_t start, size_t end) : TensorShape(gsl::span<const int64_t>(&dims[start], end - start)) {}\n\n  // Create a TensorShape that points to an existing buffer internally. As no copy is made, 'data' must remain valid for the life of the TensorShape\n  static const TensorShape FromExistingBuffer(const std::vector<int64_t>& data) {\n    return TensorShape(External{}, gsl::span<int64_t>(const_cast<int64_t*>(data.data()), data.size()));\n  }\n\n  /**\n     Return the dimension specified by <idx>.\n  */\n  int64_t operator[](size_t idx) const { return values_[idx]; }\n  int64_t& operator[](size_t idx) { return values_[idx]; }\n\n  bool operator==(const TensorShape& other) const noexcept { return GetDims() == other.GetDims(); }\n  bool operator!=(const TensorShape& other) const noexcept { return GetDims() != other.GetDims(); }\n\n  size_t NumDimensions() const noexcept {\n    return values_.size();\n  }\n\n  /**\n     Copy dims into an array with given size\n  */\n  void CopyDims(int64_t* dims, size_t num_dims) const {\n    memcpy(dims, values_.begin(), sizeof(int64_t) * std::min(num_dims, NumDimensions()));\n  }\n\n  /**\n     Copy dims from a specific start dim into an array with given size\n     `start_dim` is expected to be in the inclusive range [0, NumDimensions() - 1]\n     and this function does no checks to ensure that\n  */\n  void CopyDims(int64_t* dims, size_t start_dim, size_t num_dims) const {\n    memcpy(dims, values_.begin() + start_dim, sizeof(int64_t) * std::min(num_dims, NumDimensions() - start_dim));\n  }\n\n  /**\n     Return underlying vector representation.\n  */\n  gsl::span<const int64_t> GetDims() const { return values_; }\n  std::vector<int64_t> GetDimsAsVector() const { return std::vector<int64_t>(values_.begin(), values_.end()); }\n\n  /**\n   * Return the total number of elements. Returns 1 for an empty (rank 0) TensorShape.\n   *\n   * May return -1\n   */\n  int64_t Size() const;\n\n  /**\n     Return the total number of elements up to the specified dimension.\n     If the dimension interval is empty (dimension == 0), return 1.\n     @param dimension Return size up to this dimension. Value must be between 0 and this->NumDimensions(), inclusive.\n  */\n  int64_t SizeToDimension(size_t dimension) const;\n\n  /**\n     Return the total number of elements from the specified dimension to the end of the tensor shape.\n     If the dimension interval is empty (dimension == this->NumDimensions()), return 1.\n     @param dimension Return size from this dimension to the end. Value must be between 0 and this->NumDimensions(),\n                      inclusive.\n  */\n  int64_t SizeFromDimension(size_t dimension) const;\n\n  /**\n     Return a new TensorShape of the dimensions from dimstart to dimend.\n  */\n  TensorShape Slice(size_t dimstart, size_t dimend) const;\n\n  /**\n     Return a new TensorShape of the dimensions from dimstart to end.\n  */\n  TensorShape Slice(size_t dimstart) const { return Slice(dimstart, values_.size()); }\n\n  /**\n     output dimensions nicely formatted\n  */\n  std::string ToString() const;\n\n  /**\n     Calculate size between start and end.\n     Assumes start and end are between 0 and this->NumDimensions(), inclusive, and that\n     start < end.\n  */\n  int64_t SizeHelper(size_t start, size_t end) const;\n\n  /**\n     empty shape or 1D shape (1) is regarded as scalar tensor\n  */\n  bool IsScalar() const {\n    size_t len = values_.size();\n    return len == 0 || (len == 1 && values_[0] == 1);\n  }\n\n private:\n\n  struct External {};\n  TensorShape(External, gsl::span<int64_t> buffer) : values_{buffer} {}\n\n  void Allocate(size_t size);\n\n  gsl::span<int64_t> values_;\n  int64_t small_buffer_[5];\n  std::unique_ptr<int64_t[]> allocated_buffer_;\n\n  friend struct ProviderHostImpl; // So that the shared provider interface can access Allocate\n};\n#ifdef __GNUC__\n#pragma GCC diagnostic pop\n#endif\n// operator<< to nicely output to a stream\nstd::ostream& operator<<(std::ostream& out, const TensorShape& shape);\n\n}  // namespace onnxruntime\n", "meta": {"hexsha": "365cbe26c58e312445f7d5b339ae3f49a89d9f6c", "size": 5226, "ext": "h", "lang": "C", "max_stars_repo_path": "include/onnxruntime/core/framework/tensor_shape.h", "max_stars_repo_name": "TingGong1/onnxruntime", "max_stars_repo_head_hexsha": "435010ab6873974803591fa22262ed8b3e36e44d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-14T12:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T12:52:29.000Z", "max_issues_repo_path": "include/onnxruntime/core/framework/tensor_shape.h", "max_issues_repo_name": "TingGong1/onnxruntime", "max_issues_repo_head_hexsha": "435010ab6873974803591fa22262ed8b3e36e44d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2021-08-16T04:01:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T11:41:45.000Z", "max_forks_repo_path": "include/onnxruntime/core/framework/tensor_shape.h", "max_forks_repo_name": "jthelin/onnxruntime", "max_forks_repo_head_hexsha": "21eb747a0fcad6559c4e601697e2f4fa06e2fb27", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.84, "max_line_length": 148, "alphanum_fraction": 0.7072330654, "num_tokens": 1286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19930799790404566, "lm_q2_score": 0.017986209698896728, "lm_q1q2_score": 0.003584795444969435}}
{"text": "// This file is part of playd.\n// playd is licensed under the MIT licence: see LICENSE.txt.\n\n/**\n * @file\n * Declaration of the Basic_audio, Null_audio and Audio classes.\n * @see audio/audio.cpp\n */\n\n#ifndef PLAYD_AUDIO_H\n#define PLAYD_AUDIO_H\n\n#include <chrono>\n#include <cstdint>\n#include <memory>\n#include <string>\n#include <utility>\n#include <vector>\n\n#undef max\n#include <gsl/gsl>\n\n#include \"../response.h\"\n#include \"sink.h\"\n#include \"source.h\"\n\nnamespace Playd::Audio\n{\n/**\n * An audio item.\n *\n * Audio abstractly represents an audio item that can be played, stopped,\n * and queried for its position and path (or equivalent).\n *\n * Audio is a virtual interface implemented concretely by PipeAudio, and\n * also by mock implementations for testing purposes.\n *\n * @see PipeAudio\n */\nclass Audio\n{\npublic:\n\t/// Enumeration of possible states for Audio.\n\tusing State = Sink::State;\n\n\t/// Virtual, empty destructor for Audio.\n\tvirtual ~Audio() = default;\n\n\t//\n\t// Control interface\n\t//\n\n\t/**\n\t * Performs an update cycle on this Audio.\n\t *\n\t * Depending on the Audio implementation, this may do actions such as\n\t * performing a decoding round, checking for end-of-file, transferring\n\t * frames, and so on.\n\t *\n\t * @return The state of the Audio after updating.\n\t * @see State\n\t */\n\tvirtual State Update() = 0;\n\n\t/**\n\t * Sets whether this Audio should be playing or not.\n\t * @param playing True for playing; false for stopped.\n\t * @exception NoAudioError if the current state is NONE.\n\t */\n\tvirtual void SetPlaying(bool playing) = 0;\n\n\t/**\n\t * Attempts to seek to the given position.\n\t * @param position The position to seek to, in microseconds.\n\t * @exception NoAudioError if the current state is NONE.\n\t * @see Position\n\t */\n\tvirtual void SetPosition(std::chrono::microseconds position) = 0;\n\n\t//\n\t// Property access\n\t//\n\n\t/**\n\t * This Audio's current file.\n\t * @return The filename of this current file.\n\t * @exception NoAudioError if the current state is NONE.\n\t */\n\tvirtual std::string_view File() const = 0;\n\n\t/**\n\t * The state of this Audio.\n\t * @return this Audio's current state.\n\t */\n\tvirtual State CurrentState() const = 0;\n\n\t/**\n\t * This Audio's current position.\n\t *\n\t * As this may be executing whilst the playing callback is running,\n\t * do not expect it to be highly accurate.\n\t *\n\t * @return The current position, in microseconds.\n\t * @exception NoAudioError if the current state is NONE.\n\t * @see Seek\n\t */\n\tvirtual std::chrono::microseconds Position() const = 0;\n\n\t/**\n\t * This Audio's length.\n\t *\n\t * @return The length, in microseconds.\n\t * @exception NoAudioError if the current state is NONE.\n\t * @see Seek\n\t */\n\tvirtual std::chrono::microseconds Length() const = 0;\n};\n\n/**\n * A dummy Audio implementation representing a lack of file.\n *\n * NoAudio throws exceptions if any attempt is made to change, start, or stop\n * the audio, and returns Audio::State::NONE during any attempt to Update.\n * If asked to emit the audio file, NoAudio does nothing.\n *\n * @see Audio\n */\nclass NullAudio : public Audio\n{\npublic:\n\tAudio::State Update() override;\n\n\tAudio::State CurrentState() const override;\n\n\t// The following all raise an exception:\n\n\tvoid SetPlaying(bool playing) override;\n\n\tvoid SetPosition(std::chrono::microseconds position) override;\n\n\tstd::chrono::microseconds Position() const override;\n\n\tstd::chrono::microseconds Length() const override;\n\n\tstd::string_view File() const override;\n};\n\n/**\n * A concrete implementation of Audio as a 'pipe'.\n *\n * Basic_audio is comprised of a 'source', which decodes frames from a\n * file, and a 'sink', which plays out the decoded frames.  Updating\n * consists of shifting frames from the source to the sink.\n *\n * @see Audio\n * @see Sink\n * @see Source\n */\nclass BasicAudio : public Audio\n{\npublic:\n\t/**\n\t * Constructs audio from a source and a sink.\n\t * @param src The source of decoded audio frames.\n\t * @param sink The target of decoded audio frames.\n\t * @see AudioSystem::Load\n\t */\n\tBasicAudio(std::unique_ptr<Source> src, std::unique_ptr<Sink> sink);\n\n\tAudio::State Update() override;\n\n\tstd::string_view File() const override;\n\n\tvoid SetPlaying(bool playing) override;\n\n\tAudio::State CurrentState() const override;\n\n\tvoid SetPosition(std::chrono::microseconds position) override;\n\n\tstd::chrono::microseconds Position() const override;\n\n\tstd::chrono::microseconds Length() const override;\n\nprivate:\n\t/// The source of audio data.\n\tstd::unique_ptr<Source> src;\n\n\t/// The sink to which audio data is sent.\n\tstd::unique_ptr<Sink> sink;\n\n\t/// The current decoded frame.\n\tSource::DecodeVector frame;\n\n\t/// A span representing the unclaimed part of the decoded frame.\n\tgsl::span<const std::byte> frame_span;\n\n\t/// Clears the current frame and its iterator.\n\tvoid ClearFrame();\n\n\t/**\n\t * Decodes a new frame, if the current frame is empty.\n\t * @return True if more frames are available to decode; false\n\t *   otherwise.\n\t */\n\tbool DecodeIfFrameEmpty();\n\n\t/**\n\t * Returns whether the current frame has been finished.\n\t * If this is true, then either the frame is empty, or all of the\n\t * samples in the frame have been fed to the ringbuffer.\n\t * @return True if the frame is finished; false otherwise.\n\t */\n\tbool FrameFinished() const;\n\n\t/// Transfers as much of the current frame as possible to the sink.\n\tvoid TransferFrame();\n};\n\n} // namespace Playd::Audio\n\n#endif // PLAYD_AUDIO_H\n", "meta": {"hexsha": "30aeed3abd26b6ed16fe9cf88559e001f68ebc60", "size": 5351, "ext": "h", "lang": "C", "max_stars_repo_path": "src/audio/audio.h", "max_stars_repo_name": "UniversityRadioYork/ury-playd", "max_stars_repo_head_hexsha": "dc072e4934acb21b9dddb225818732bd27671ae0", "max_stars_repo_licenses": ["BSL-1.0", "MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-02-11T20:33:45.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-19T20:01:51.000Z", "max_issues_repo_path": "src/audio/audio.h", "max_issues_repo_name": "UniversityRadioYork/ury-playd", "max_issues_repo_head_hexsha": "dc072e4934acb21b9dddb225818732bd27671ae0", "max_issues_repo_licenses": ["BSL-1.0", "MIT"], "max_issues_count": 56.0, "max_issues_repo_issues_event_min_datetime": "2015-01-01T19:22:34.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-28T13:48:14.000Z", "max_forks_repo_path": "src/audio/audio.h", "max_forks_repo_name": "UniversityRadioYork/ury-playd", "max_forks_repo_head_hexsha": "dc072e4934acb21b9dddb225818732bd27671ae0", "max_forks_repo_licenses": ["BSL-1.0", "MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-09-04T23:04:46.000Z", "max_forks_repo_forks_event_max_datetime": "2017-02-23T12:41:21.000Z", "avg_line_length": 24.1036036036, "max_line_length": 77, "alphanum_fraction": 0.7041674453, "num_tokens": 1293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10669058258408719, "lm_q2_score": 0.03358950214320426, "lm_q1q2_score": 0.0035836835523679078}}
{"text": "#ifndef TTT_UTIL_TEXTURECACHE_H\n#define TTT_UTIL_TEXTURECACHE_H\n\n#include <SDL_render.h>\n\n#include <gsl/pointers>\n#include <gsl/util>\n\n#include <vector>\n#include <memory>\n#include <string_view>\n\nnamespace ttt::gfx\n{\n\t// A class for caching textures for reuse.\n\tclass TextureCache final\n\t{\n\tpublic:\n\t\tusing SizeType = gsl::index;\n\n\t\tSDL_Texture *load(std::string_view path, gsl::not_null<SDL_Renderer *> renderer);\n\t\tvoid unload(SizeType index) noexcept;\n\t\tvoid erase(SizeType index) noexcept;\n\t\tvoid clear() noexcept;\n\n\t\t[[nodiscard]] SDL_Texture *at(SizeType index) const noexcept;\n\t\t[[nodiscard]] SDL_Texture *operator [](SizeType index) const noexcept;\n\t\t\n\t\t[[nodiscard]] SizeType getSize() const noexcept;\n\t\t[[nodiscard]] SizeType getMaxSize() const noexcept;\n\n\tprivate:\n\t\tstd::vector<std::unique_ptr<SDL_Texture, decltype(&SDL_DestroyTexture)>> textures;\n\t};\n\n\tinline void TextureCache::unload(SizeType index) noexcept { gsl::at(textures, index).reset(); }\n\tinline void TextureCache::erase(SizeType index) noexcept { textures.erase(textures.cbegin() + index); }\n\tinline void TextureCache::clear() noexcept { textures.clear(); }\n\n\tinline SDL_Texture *TextureCache::at(SizeType index) const noexcept { return gsl::at(textures, index).get(); }\n\tinline SDL_Texture *TextureCache::operator [](SizeType index) const noexcept { return gsl::at(textures, index).get(); }\n\n\tinline TextureCache::SizeType TextureCache::getSize() const noexcept { return textures.size(); }\n\tinline TextureCache::SizeType TextureCache::getMaxSize() const noexcept { return textures.max_size(); }\n}\n\n#endif", "meta": {"hexsha": "4a7919c1cf518d9a7b4d1c72bf3aa7bbfff4f101", "size": 1580, "ext": "h", "lang": "C", "max_stars_repo_path": "Source/Graphics/TextureCache.h", "max_stars_repo_name": "itsArtem/TicTacToe", "max_stars_repo_head_hexsha": "8c70a77e4603dd0ff22ec0621b978ec0685ec3cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Source/Graphics/TextureCache.h", "max_issues_repo_name": "itsArtem/TicTacToe", "max_issues_repo_head_hexsha": "8c70a77e4603dd0ff22ec0621b978ec0685ec3cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/Graphics/TextureCache.h", "max_forks_repo_name": "itsArtem/TicTacToe", "max_forks_repo_head_hexsha": "8c70a77e4603dd0ff22ec0621b978ec0685ec3cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6170212766, "max_line_length": 120, "alphanum_fraction": 0.7474683544, "num_tokens": 369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10970577387797076, "lm_q2_score": 0.03258974711501865, "lm_q1q2_score": 0.0035752834277404857}}
{"text": "#define PyGSL_NUMERIC\n#define PyGSL_NUMARRAY\n#include \"numeric_numarray.h\"\n#include <gsl/gsl_errno.h>\n#include <pygsl/general_helpers.h>\n\nstatic int\ncp_numeric_ptrs(void)\n{\n     return GSL_SUCCESS;\n}\n\nstatic int\ncp_numarray_ptrs(void)\n{\n     return GSL_SUCCESS;\n}\n\n\nvoid\ninitnumx(void)\n{\n     init_pygsl();\n     cp_numeric_ptrs();\n     cp_numarray_ptrs();\n}\n", "meta": {"hexsha": "5ff99b5d3ea61a7da568496478e32d7836d25872", "size": 358, "ext": "c", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/testing/src/numeric_numarray.c", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/testing/src/numeric_numarray.c", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/testing/src/numeric_numarray.c", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 13.2592592593, "max_line_length": 34, "alphanum_fraction": 0.7234636872, "num_tokens": 95, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.1755380649971796, "lm_q2_score": 0.02033235460412452, "lm_q1q2_score": 0.003569102184044514}}
{"text": "/* Sound display/edit/etc\n *\n * originally intended as a re-implementation of my much-missed dpysnd -- the Foonly/SAIL/E/Mus10/Grnlib sound editor from ca 1983.\n */\n\n#include \"snd.h\"\n\nsnd_state *ss = NULL;\n\nstatic bool ignore_mus_error(int type, char *msg)\n{\n  XEN result = XEN_FALSE;\n\n  if (XEN_HOOKED(ss->mus_error_hook))\n    result = run_or_hook(ss->mus_error_hook, \n\t\t\t XEN_LIST_2(C_TO_XEN_INT(type), \n\t\t\t\t    C_TO_XEN_STRING(msg)),\n\t\t\t S_mus_error_hook);\n  return(XEN_NOT_FALSE_P(result));\n}\n\n#if HAVE_SETJMP_H\n  void top_level_catch(int ignore);\n#endif\n\n\nvoid mus_error_to_snd(int type, char *msg)\n{\n  if (!ss)\n    {\n      fprintf(stderr, \"%s\", msg);\n      return;\n    }\n\n  if (!(ignore_mus_error(type, msg)))\n    {\n#if HAVE_EXTENSION_LANGUAGE\n      if (msg == NULL)\n\tXEN_ERROR(XEN_ERROR_TYPE(\"mus-error\"),\n\t\t  XEN_LIST_1(C_TO_XEN_STRING((char *)mus_error_type_to_string(type))));\n      else XEN_ERROR(XEN_ERROR_TYPE(\"mus-error\"),\n\t\t     XEN_LIST_1(C_TO_XEN_STRING(msg)));\n#endif\n      snd_error(\"%s: %s\", mus_error_type_to_string(type), msg);\n#if HAVE_SETJMP_H\n      ss->jump_ok = true;\n      top_level_catch(1); /* sigh -- try to keep going */\n#endif\n    }\n}\n\n\nstatic void mus_print_to_snd(char *msg)\n{\n  if (!ss)\n    {\n      fprintf(stderr, \"%s\", msg);\n      return;\n    }\n  if (!(ignore_mus_error(MUS_NO_ERROR, msg)))\n    if (msg)\n      {\n\tint i, len;\n\tlistener_append(\";\");\n\tlen = strlen(msg);\n\n\tfor (i = 1; i < len - 1; i++)\n\t  if ((msg[i] == '\\n') && (msg[i + 1] == ' '))\n\t    msg[i + 1] = ';';\n\n\tif (msg[0] == '\\n')\n\t  listener_append((char *)(msg + 1));\n\telse listener_append(msg);\n\n\tif (msg[strlen(msg) - 1] != '\\n')\n\t  listener_append(\"\\n\");\n      }\n}\n\n\nstatic void initialize_load_path(void)\n{\n  /* look for SND_PATH env var, add dirs to %load-path or load_path */\n  char *path;\n  path = getenv(\"SND_PATH\");\n  if (path)\n    {\n      /* colon-separated list of directory names, pushed on load-path in reverse order (hopefully = search order) */\n      int i, len, dirs = 1, curdir = 0, start = 0;\n      char **dirnames;\n\n      len = strlen(path);\n      for (i = 0; i < len; i++)\n\tif (path[i] == ':')\n\t  dirs++;\n\n      dirnames = (char **)calloc(dirs, sizeof(char *));\n      for (i = 0; i < len; i++)\n\t{\n\t  if ((path[i] == ':') ||\n\t      (i == len - 1))\n\t    {\n\t      if (i > start)\n\t\t{\n\t\t  int j, lim;\n\t\t  char *tmp;\n\n\t\t  if (i == (len - 1))\n\t\t    lim = i + 1;\n\t\t  else lim = i;\n\n\t\t  tmp = (char *)calloc(lim - start + 1, sizeof(char));\n\t\t  for (j = start; j < lim; j++)\n\t\t    tmp[j - start] = path[j];\n\n\t\t  dirnames[curdir++] = mus_expand_filename(tmp);\n\t\t  start = i + 1;\n\t\t  free(tmp);\n\t\t}\n\t    }\n\t}\n\n      for (i = curdir - 1; i >= 0; i--)\n\t{\n\t  XEN_ADD_TO_LOAD_PATH(dirnames[i]);\n\t  free(dirnames[i]);\n\t}\n      free(dirnames);\n    }\n}\n\n\nvoid snd_set_global_defaults(bool need_cleanup)\n{\n  if (need_cleanup)\n    {\n      if (ss->HTML_Program) {free(ss->HTML_Program); ss->HTML_Program = NULL;}\n      if (ss->HTML_Dir) {free(ss->HTML_Dir); ss->HTML_Dir = NULL;}\n      if (ss->Temp_Dir) {free(ss->Temp_Dir); ss->Temp_Dir = NULL;}\n      if (ss->Save_Dir) {free(ss->Save_Dir); ss->Save_Dir = NULL;}\n      if (ss->Ladspa_Dir) {free(ss->Ladspa_Dir); ss->Ladspa_Dir = NULL;}\n      if (ss->Save_State_File) {free(ss->Save_State_File); ss->Save_State_File = NULL;}\n      if (ss->Eps_File) {free(ss->Eps_File); ss->Eps_File = NULL;}\n      if (ss->Listener_Prompt) {free(ss->Listener_Prompt); ss->Listener_Prompt = NULL;}\n      if (ss->Open_File_Dialog_Directory) {free(ss->Open_File_Dialog_Directory); ss->Open_File_Dialog_Directory = NULL;}\n      \n      /* not sure about the next two... */\n      if ((cursor_style(ss) == CURSOR_PROC) && (XEN_PROCEDURE_P(ss->cursor_proc)))\n\tsnd_unprotect_at(ss->cursor_proc_loc);\n      if ((zoom_focus_style(ss) == ZOOM_FOCUS_PROC) && (XEN_PROCEDURE_P(ss->zoom_focus_proc)))\n\tsnd_unprotect_at(ss->zoom_focus_proc_loc);\n    }\n\n  ss->Transform_Size =              DEFAULT_TRANSFORM_SIZE;\n  ss->Fft_Window =                  DEFAULT_FFT_WINDOW;\n  ss->Fft_Window_Alpha =            DEFAULT_FFT_WINDOW_ALPHA;\n  ss->Fft_Window_Beta =             DEFAULT_FFT_WINDOW_BETA;\n  ss->Transform_Graph_Type =        DEFAULT_TRANSFORM_GRAPH_TYPE;\n  ss->Sinc_Width =                  DEFAULT_SINC_WIDTH;\n  ss->Zero_Pad =                    DEFAULT_ZERO_PAD;\n  ss->Wavelet_Type =                DEFAULT_WAVELET_TYPE;\n  ss->Transform_Type =              DEFAULT_TRANSFORM_TYPE;\n  ss->Transform_Normalization =     DEFAULT_TRANSFORM_NORMALIZATION;\n  ss->Show_Transform_Peaks =        DEFAULT_SHOW_TRANSFORM_PEAKS;\n  ss->Show_Sonogram_Cursor =        DEFAULT_SHOW_SONOGRAM_CURSOR;\n  ss->Fft_Log_Magnitude =           DEFAULT_FFT_LOG_MAGNITUDE;\n  ss->Fft_Log_Frequency =           DEFAULT_FFT_LOG_FREQUENCY;\n  ss->Fft_With_Phases =             DEFAULT_FFT_WITH_PHASES;\n  ss->Max_Transform_Peaks =         DEFAULT_MAX_TRANSFORM_PEAKS;\n  ss->Log_Freq_Start =              DEFAULT_LOG_FREQ_START;\n  ss->Min_dB =                      DEFAULT_MIN_DB;\n  ss->lin_dB =                      pow(10.0, DEFAULT_MIN_DB * 0.05);\n  ss->Show_Selection_Transform =    DEFAULT_SHOW_SELECTION_TRANSFORM;\n  ss->Default_Output_Chans =        DEFAULT_OUTPUT_CHANS;\n  ss->Default_Output_Srate =        DEFAULT_OUTPUT_SRATE;\n  ss->Default_Output_Header_Type =  DEFAULT_OUTPUT_HEADER_TYPE;\n  ss->Default_Output_Data_Format =  DEFAULT_OUTPUT_DATA_FORMAT;\n  ss->Audio_Input_Device =          DEFAULT_AUDIO_INPUT_DEVICE;\n  ss->Audio_Output_Device =         DEFAULT_AUDIO_OUTPUT_DEVICE;\n  ss->Dac_Size =                    DEFAULT_DAC_SIZE;\n  ss->Dac_Combines_Channels =       DEFAULT_DAC_COMBINES_CHANNELS;\n  ss->Auto_Resize =                 DEFAULT_AUTO_RESIZE; \n  ss->Auto_Update =                 DEFAULT_AUTO_UPDATE; \n  ss->Auto_Update_Interval =        DEFAULT_AUTO_UPDATE_INTERVAL;\n  ss->Ask_Before_Overwrite =        DEFAULT_ASK_BEFORE_OVERWRITE;\n  ss->With_Toolbar =                DEFAULT_WITH_TOOLBAR;\n  ss->With_Tooltips =               DEFAULT_WITH_TOOLTIPS;\n  ss->Remember_Sound_State =        DEFAULT_REMEMBER_SOUND_STATE;\n  ss->Ask_About_Unsaved_Edits =     DEFAULT_ASK_ABOUT_UNSAVED_EDITS;\n  ss->Save_As_Dialog_Src =          DEFAULT_SAVE_AS_DIALOG_SRC;\n  ss->Save_As_Dialog_Auto_Comment = DEFAULT_SAVE_AS_DIALOG_AUTO_COMMENT;\n  ss->Show_Full_Duration =          DEFAULT_SHOW_FULL_DURATION;\n  ss->Show_Full_Range =             DEFAULT_SHOW_FULL_RANGE;\n  ss->Initial_Beg =                 DEFAULT_INITIAL_BEG;\n  ss->Initial_Dur =                 DEFAULT_INITIAL_DUR;\n  ss->With_Background_Processes =   DEFAULT_WITH_BACKGROUND_PROCESSES;\n  ss->With_File_Monitor =           DEFAULT_WITH_FILE_MONITOR;\n  ss->Selection_Creates_Region =    DEFAULT_SELECTION_CREATES_REGION;\n  ss->Channel_Style =               DEFAULT_CHANNEL_STYLE;\n  ss->Sound_Style =                 DEFAULT_SOUND_STYLE;\n  ss->Graphs_Horizontal =           DEFAULT_GRAPHS_HORIZONTAL;\n  ss->Graph_Style =                 DEFAULT_GRAPH_STYLE;\n  ss->Region_Graph_Style =          DEFAULT_GRAPH_STYLE;\n  ss->Time_Graph_Type =             DEFAULT_TIME_GRAPH_TYPE;\n  ss->X_Axis_Style =                DEFAULT_X_AXIS_STYLE;\n  ss->Beats_Per_Minute =            DEFAULT_BEATS_PER_MINUTE;\n  ss->Beats_Per_Measure =           DEFAULT_BEATS_PER_MEASURE;\n  ss->With_Relative_Panes =         DEFAULT_WITH_RELATIVE_PANES;\n  ss->With_GL =                     DEFAULT_WITH_GL;\n  ss->Dot_Size =                    DEFAULT_DOT_SIZE;\n  ss->Grid_Density =                DEFAULT_GRID_DENSITY;\n  ss->Zoom_Focus_Style =            DEFAULT_ZOOM_FOCUS_STYLE;\n  ss->zoom_focus_proc =             XEN_UNDEFINED;\n  ss->zoom_focus_proc_loc =         NOT_A_GC_LOC;\n  ss->Max_Regions =                 DEFAULT_MAX_REGIONS;\n  ss->Show_Y_Zero =                 DEFAULT_SHOW_Y_ZERO;\n  ss->Show_Grid =                   DEFAULT_SHOW_GRID;\n  ss->Show_Axes =                   DEFAULT_SHOW_AXES;\n  ss->Show_Indices =                DEFAULT_SHOW_INDICES;\n  ss->Show_Backtrace =              DEFAULT_SHOW_BACKTRACE;\n  ss->With_Inset_Graph =            DEFAULT_WITH_INSET_GRAPH;\n  ss->With_Interrupts =             DEFAULT_WITH_INTERRUPTS;\n  ss->With_Menu_Icons =             DEFAULT_WITH_MENU_ICONS;\n  ss->With_Smpte_Label =            DEFAULT_WITH_SMPTE_LABEL;\n  ss->With_Pointer_Focus =          DEFAULT_WITH_POINTER_FOCUS;\n  ss->Play_Arrow_Size =             DEFAULT_PLAY_ARROW_SIZE;\n  ss->Sync_Style =                  DEFAULT_SYNC_STYLE;\n  ss->Listener_Prompt =             mus_strdup(DEFAULT_LISTENER_PROMPT);\n  ss->listener_prompt_length =      mus_strlen(ss->Listener_Prompt);\n  ss->Minibuffer_History_Length =   DEFAULT_MINIBUFFER_HISTORY_LENGTH;\n  ss->Clipping =                    DEFAULT_CLIPPING;\n  ss->Optimization =                DEFAULT_OPTIMIZATION;\n  ss->Print_Length =                DEFAULT_PRINT_LENGTH;\n  ss->View_Files_Sort =             DEFAULT_VIEW_FILES_SORT;\n  ss->Just_Sounds =                 DEFAULT_JUST_SOUNDS;\n  ss->Open_File_Dialog_Directory =  NULL;\n  ss->HTML_Dir =                    mus_strdup(DEFAULT_HTML_DIR);\n  ss->HTML_Program =                mus_strdup(DEFAULT_HTML_PROGRAM);\n  ss->Cursor_Size =                 DEFAULT_CURSOR_SIZE;\n  ss->Cursor_Style =                DEFAULT_CURSOR_STYLE;\n  ss->Tracking_Cursor_Style =       DEFAULT_TRACKING_CURSOR_STYLE;\n  ss->With_Tracking_Cursor =        DEFAULT_WITH_TRACKING_CURSOR;\n  ss->cursor_proc =                 XEN_UNDEFINED;\n  ss->cursor_proc_loc =             NOT_A_GC_LOC;\n  ss->Verbose_Cursor =              DEFAULT_VERBOSE_CURSOR;\n  ss->Cursor_Update_Interval =      DEFAULT_CURSOR_UPDATE_INTERVAL;\n  ss->Cursor_Location_Offset =      DEFAULT_CURSOR_LOCATION_OFFSET;\n  ss->Show_Mix_Waveforms =          DEFAULT_SHOW_MIX_WAVEFORMS;\n  ss->Mix_Waveform_Height =         DEFAULT_MIX_WAVEFORM_HEIGHT;\n  ss->Mix_Tag_Width =               DEFAULT_MIX_TAG_WIDTH;\n  ss->Mix_Tag_Height =              DEFAULT_MIX_TAG_HEIGHT;\n  ss->With_Mix_Tags =               DEFAULT_WITH_MIX_TAGS;\n  ss->Mark_Tag_Width =              DEFAULT_MARK_TAG_WIDTH;\n  ss->Mark_Tag_Height =             DEFAULT_MARK_TAG_HEIGHT;\n  ss->Show_Marks =                  DEFAULT_SHOW_MARKS;\n  ss->Color_Map =                   DEFAULT_COLOR_MAP;\n  ss->Color_Map_Size =              DEFAULT_COLOR_MAP_SIZE;\n  ss->Color_Cutoff =                DEFAULT_COLOR_CUTOFF;\n  ss->Color_Scale =                 DEFAULT_COLOR_SCALE;\n  ss->Color_Inverted =              DEFAULT_COLOR_INVERTED;\n  ss->Color_Map =                   DEFAULT_COLOR_MAP;\n  ss->Wavo_Hop =                    DEFAULT_WAVO_HOP;\n  ss->Wavo_Trace =                  DEFAULT_WAVO_TRACE;\n  ss->Spectro_Hop =                 DEFAULT_SPECTRO_HOP;\n  ss->Spectro_X_Scale =             DEFAULT_SPECTRO_X_SCALE;\n  ss->Spectro_Y_Scale =             DEFAULT_SPECTRO_Y_SCALE;\n  ss->Spectro_Z_Scale =             DEFAULT_SPECTRO_Z_SCALE;\n  ss->Spectro_Z_Angle =             DEFAULT_SPECTRO_Z_ANGLE;\n  ss->Spectro_X_Angle =             DEFAULT_SPECTRO_X_ANGLE;\n  ss->Spectro_Y_Angle =             DEFAULT_SPECTRO_Y_ANGLE;\n  ss->Spectrum_End =                DEFAULT_SPECTRUM_END;\n  ss->Spectrum_Start =              DEFAULT_SPECTRUM_START;\n  ss->Enved_Base =                  DEFAULT_ENVED_BASE;\n  ss->Enved_Power =                 DEFAULT_ENVED_POWER;\n  ss->Enved_Wave_p =                DEFAULT_ENVED_WAVE_P;\n  ss->Enved_Style =                 DEFAULT_ENVED_STYLE;\n  ss->Enved_Target =                DEFAULT_ENVED_TARGET;\n  ss->Enved_Filter_Order =          DEFAULT_ENVED_FILTER_ORDER;\n  ss->Eps_Bottom_Margin =           DEFAULT_EPS_BOTTOM_MARGIN;\n  ss->Eps_Left_Margin =             DEFAULT_EPS_LEFT_MARGIN;\n  ss->Eps_Size =                    DEFAULT_EPS_SIZE;\n  ss->Expand_Control_Min =          DEFAULT_EXPAND_CONTROL_MIN;\n  ss->Expand_Control_Max =          DEFAULT_EXPAND_CONTROL_MAX;\n  ss->Amp_Control_Min =             DEFAULT_AMP_CONTROL_MIN;\n  ss->Amp_Control_Max =             DEFAULT_AMP_CONTROL_MAX;\n  ss->Speed_Control_Min =           DEFAULT_SPEED_CONTROL_MIN;\n  ss->Speed_Control_Max =           DEFAULT_SPEED_CONTROL_MAX;\n  ss->Contrast_Control_Min =        DEFAULT_CONTRAST_CONTROL_MIN;\n  ss->Contrast_Control_Max =        DEFAULT_CONTRAST_CONTROL_MAX;\n  ss->Contrast_Control_Amp =        DEFAULT_CONTRAST_CONTROL_AMP;\n  ss->Expand_Control_Length =       DEFAULT_EXPAND_CONTROL_LENGTH;\n  ss->Expand_Control_Ramp =         DEFAULT_EXPAND_CONTROL_RAMP;\n  ss->Expand_Control_Hop =          DEFAULT_EXPAND_CONTROL_HOP;\n  ss->Expand_Control_Jitter =       DEFAULT_EXPAND_CONTROL_JITTER;\n  ss->Reverb_Control_Feedback =     DEFAULT_REVERB_CONTROL_FEEDBACK;\n  ss->Reverb_Control_Lowpass =      DEFAULT_REVERB_CONTROL_LOWPASS;\n  ss->Reverb_Control_Scale_Min =    DEFAULT_REVERB_CONTROL_SCALE_MIN;\n  ss->Reverb_Control_Scale_Max =    DEFAULT_REVERB_CONTROL_SCALE_MAX;\n  ss->Reverb_Control_Decay =        DEFAULT_REVERB_CONTROL_DECAY;\n  ss->Speed_Control_Tones =         DEFAULT_SPEED_CONTROL_TONES;\n  ss->Speed_Control_Style =         DEFAULT_SPEED_CONTROL_STYLE;\n  ss->Reverb_Control_Length_Min =   DEFAULT_REVERB_CONTROL_LENGTH_MIN;\n  ss->Reverb_Control_Length_Max =   DEFAULT_REVERB_CONTROL_LENGTH_MAX;\n  ss->Filter_Control_Order =        DEFAULT_FILTER_CONTROL_ORDER;\n  ss->Filter_Control_In_Db =        DEFAULT_FILTER_CONTROL_IN_DB;\n  ss->Filter_Control_In_Hz =        DEFAULT_FILTER_CONTROL_IN_HZ;\n  ss->Show_Controls =               DEFAULT_SHOW_CONTROLS;\n\n  if (MUS_DEFAULT_TEMP_DIR != (char *)NULL) \n    ss->Temp_Dir = mus_strdup(MUS_DEFAULT_TEMP_DIR); \n  else ss->Temp_Dir = NULL;\n  \n  if (MUS_DEFAULT_SAVE_DIR != (char *)NULL) \n    ss->Save_Dir = mus_strdup(MUS_DEFAULT_SAVE_DIR); \n  else ss->Save_Dir = NULL;\n\n  if (DEFAULT_LADSPA_DIR != (char *)NULL) \n    ss->Ladspa_Dir = mus_strdup(DEFAULT_LADSPA_DIR); \n  else ss->Ladspa_Dir = NULL;\n\n  if (DEFAULT_SAVE_STATE_FILE != (char *)NULL) \n    ss->Save_State_File = mus_strdup(DEFAULT_SAVE_STATE_FILE); \n  else ss->Save_State_File = NULL;\n\n  if (DEFAULT_PEAK_ENV_DIR != (char *)NULL) \n    ss->Peak_Env_Dir = mus_strdup(DEFAULT_PEAK_ENV_DIR); \n  else ss->Peak_Env_Dir = NULL;\n  \n  if (DEFAULT_EPS_FILE != (char *)NULL) \n    ss->Eps_File = mus_strdup(DEFAULT_EPS_FILE);\n  else ss->Eps_File = NULL;\n}\n\n\n#if HAVE_SETJMP_H && HAVE_SCHEME\nstatic void jump_to_top_level(void)\n{\n  top_level_catch(1);\n}\n#endif\n\n\n#if HAVE_GSL\n#include <gsl/gsl_ieee_utils.h>\n#include <gsl/gsl_errno.h>\n\n/* default gsl error handler apparently aborts main program! */\n\nstatic void snd_gsl_error(const char *reason, const char *file, int line, int gsl_errno)\n{\n  XEN_ERROR(XEN_ERROR_TYPE(\"gsl-error\"),\n\t    XEN_LIST_6(C_TO_XEN_STRING(\"GSL: ~A, ~A in ~A line ~A, gsl err: ~A\"),\n\t\t       C_TO_XEN_STRING(gsl_strerror(gsl_errno)),\n\t\t       C_TO_XEN_STRING(reason),\n\t\t       C_TO_XEN_STRING(file),\n\t\t       C_TO_XEN_INT(line),\n\t\t       C_TO_XEN_INT(gsl_errno)));\n}\n#endif\n\n\n#if SND_AS_WIDGET\n  snd_state *snd_main(int argc, char **argv)\n#else\n  int main(int argc, char **argv)\n#endif\n{\n  int i;\n\n#if HAVE_GSL\n  /* if HAVE_GSL and the environment variable GSL_IEEE_MODE exists, use it */\n  /* GSL_IEEE_MODE=double-precision,mask-underflow,mask-denormalized */\n  if (getenv(\"GSL_IEEE_MODE\") != NULL) \n    gsl_ieee_env_setup();\n  gsl_set_error_handler(snd_gsl_error);\n#endif\n\n  ss = (snd_state *)calloc(1, sizeof(snd_state)); /* not calloc! */\n  ss->fam_ok = false;\n  ss->startup_errors = NULL;\n\n#if HAVE_GTK_3\n  g_type_init();\n#endif\n\n  mus_sound_initialize(); /* has to precede version check (mus_audio_moniker needs to be setup in Alsa/Oss) */\n  xen_initialize();\n\n#if HAVE_SCHEME && HAVE_SETJMP_H\n  s7_set_error_exiter(s7, jump_to_top_level);\n#endif\n\n  for (i = 1; i < argc; i++)\n    {\n      if (strcmp(argv[i], \"--version\") == 0)\n\t{\n\t  fprintf(stdout, \"%s\", version_info());\n\t  snd_exit(0);\n\t}\n      else\n\t{\n\t  if (strcmp(argv[i], \"--help\") == 0)\n\t    {\n\t      fprintf(stdout, \"%s\", \"Snd is a sound editor; see http://ccrma.stanford.edu/software/snd/.\\n\");\n\t      fprintf(stdout, \"%s\", version_info());\n\t      snd_exit(0);\n\t    }\n\t}\n    }\n\n  initialize_format_lists();\n  snd_set_global_defaults(false);\n\n#if MUS_DEBUGGING\n  ss->Trap_Segfault = false;\n#else\n  ss->Trap_Segfault = DEFAULT_TRAP_SEGFAULT;\n#endif\n  ss->jump_ok = false;\n  allocate_regions(max_regions(ss));\n  ss->init_window_x = DEFAULT_INIT_WINDOW_X; \n  ss->init_window_y = DEFAULT_INIT_WINDOW_Y; \n  ss->init_window_width = DEFAULT_INIT_WINDOW_WIDTH; \n  ss->init_window_height = DEFAULT_INIT_WINDOW_HEIGHT;\n  ss->click_time = 100;\n  init_sound_file_extensions();\n\n  ss->max_sounds = 4;                 /* expands to accommodate any number of files */\n  ss->sound_sync_max = 0;\n  ss->stopped_explicitly = false;     /* C-g sets this flag so that we can interrupt various loops */\n  ss->checking_explicitly = false;\n  ss->selection_play_stop = false;\n  ss->reloading_updated_file = 0;\n  ss->selected_sound = NO_SELECTION;\n  ss->sounds = (snd_info **)calloc(ss->max_sounds, sizeof(snd_info *));\n  ss->print_choice = PRINT_SND;\n  ss->graph_hook_active = false;\n  ss->lisp_graph_hook_active = false;\n  ss->exiting = false;\n  ss->deferred_regions = 0;\n  ss->fam_connection = NULL;\n  ss->snd_error_data = NULL;\n  ss->snd_error_handler = NULL;\n  ss->snd_warning_data = NULL;\n  ss->snd_warning_handler = NULL;\n  ss->xen_error_data = NULL;\n  ss->xen_error_handler = NULL;\n  ss->update_sound_channel_style = NOT_A_CHANNEL_STYLE;\n\n#if HAVE_GL && WITH_GL2PS\n  ss->gl_printing = false;\n#endif\n  g_xen_initialize();\n  ss->search_proc = XEN_UNDEFINED;\n  ss->search_expr = NULL;\n  ss->search_tree = NULL;\n  mus_error_set_handler(mus_error_to_snd);\n  mus_print_set_handler(mus_print_to_snd);\n\n  initialize_load_path(); /* merge SND_PATH entries into the load-path */\n\n#ifdef SND_AS_WIDGET\n  return(ss); \n#else\n  snd_doit(argc, argv);\n  return(0);\n#endif\n}\n\n\nvoid g_init_base(void)\n{\n  #define H_mus_error_hook S_mus_error_hook \" (error-type error-message):  called upon mus_error. \\\nIf it returns \" PROC_TRUE \", Snd ignores the error (it assumes you've handled it via the hook).\"\n\n  ss->mus_error_hook = XEN_DEFINE_HOOK(S_mus_error_hook, 2, H_mus_error_hook);       /* arg = error-type error-message */\n}\n", "meta": {"hexsha": "dbe01904529818e1f4a4d0ecf114e7bd4e01aa2f", "size": 18036, "ext": "c", "lang": "C", "max_stars_repo_path": "sources/snd.c", "max_stars_repo_name": "OS2World/MM-SOUND-Snd", "max_stars_repo_head_hexsha": "b633660e5945a6a6b095cd9aa3178deab56b354f", "max_stars_repo_licenses": ["Ruby"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-08-27T17:57:08.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-27T17:57:08.000Z", "max_issues_repo_path": "sources/snd.c", "max_issues_repo_name": "OS2World/MM-SOUND-Snd", "max_issues_repo_head_hexsha": "b633660e5945a6a6b095cd9aa3178deab56b354f", "max_issues_repo_licenses": ["Ruby"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sources/snd.c", "max_forks_repo_name": "OS2World/MM-SOUND-Snd", "max_forks_repo_head_hexsha": "b633660e5945a6a6b095cd9aa3178deab56b354f", "max_forks_repo_licenses": ["Ruby"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.7322175732, "max_line_length": 131, "alphanum_fraction": 0.6603459747, "num_tokens": 4829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1666754212455175, "lm_q2_score": 0.021287352259131725, "lm_q1q2_score": 0.0035480784049924993}}
{"text": "/* Author: G. Jungman\n */\n#include <config.h>\n#include <stdlib.h>\n#include <string.h>\n#include <gsl/gsl_errno.h>\n\n/* Compile all the inline functions */\n\n#define COMPILE_INLINE_STATIC\n#include \"build.h\"\n#include <gsl/gsl_qrng.h>\n\n", "meta": {"hexsha": "5b9c8b560b964cd4588d28763bc962d37f92c35f", "size": 230, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/qrng/inline.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/qrng/inline.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/qrng/inline.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 16.4285714286, "max_line_length": 38, "alphanum_fraction": 0.7086956522, "num_tokens": 61, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.13660838299605801, "lm_q2_score": 0.025957358799003922, "lm_q1q2_score": 0.003545992812380424}}
{"text": "/* block/gsl_block_int.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_BLOCK_INT_H__\n#define __GSL_BLOCK_INT_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_errno.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\nstruct gsl_block_int_struct\n{\n  size_t size;\n  int *data;\n};\n\ntypedef struct gsl_block_int_struct gsl_block_int;\n\ngsl_block_int *gsl_block_int_alloc (const size_t n);\ngsl_block_int *gsl_block_int_calloc (const size_t n);\nvoid gsl_block_int_free (gsl_block_int * b);\n\nint gsl_block_int_fread (FILE * stream, gsl_block_int * b);\nint gsl_block_int_fwrite (FILE * stream, const gsl_block_int * b);\nint gsl_block_int_fscanf (FILE * stream, gsl_block_int * b);\nint gsl_block_int_fprintf (FILE * stream, const gsl_block_int * b, const char *format);\n\nint gsl_block_int_raw_fread (FILE * stream, int * b, const size_t n, const size_t stride);\nint gsl_block_int_raw_fwrite (FILE * stream, const int * b, const size_t n, const size_t stride);\nint gsl_block_int_raw_fscanf (FILE * stream, int * b, const size_t n, const size_t stride);\nint gsl_block_int_raw_fprintf (FILE * stream, const int * b, const size_t n, const size_t stride, const char *format);\n\nsize_t gsl_block_int_size (const gsl_block_int * b);\nint * gsl_block_int_data (const gsl_block_int * b);\n\n__END_DECLS\n\n#endif /* __GSL_BLOCK_INT_H__ */\n", "meta": {"hexsha": "8004f765fb8d6665ab1dd49b905c4e1d66d6f7a4", "size": 2255, "ext": "h", "lang": "C", "max_stars_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_block_int.h", "max_stars_repo_name": "snipekill/FPGen", "max_stars_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-07-06T02:44:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T21:02:18.000Z", "max_issues_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_block_int.h", "max_issues_repo_name": "snipekill/FPGen", "max_issues_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_block_int.h", "max_forks_repo_name": "snipekill/FPGen", "max_forks_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-06-27T11:11:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T19:22:30.000Z", "avg_line_length": 34.1666666667, "max_line_length": 118, "alphanum_fraction": 0.7600886918, "num_tokens": 599, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.13846178345871915, "lm_q2_score": 0.02556521633614946, "lm_q1q2_score": 0.003539805448411236}}
{"text": "/*\n   Copyright [2019,2021] [IBM Corporation]\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n       http://www.apache.org/licenses/LICENSE-2.0\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\n#ifndef __CCPM_CRASH_CONSISTENT_ALLOCATOR_H__\n#define __CCPM_CRASH_CONSISTENT_ALLOCATOR_H__\n\n#include <ccpm/interfaces.h>\n#include <common/exceptions.h>\n#include <gsl/pointers>\n#include <iosfwd>\n#include <memory>\n#include <string>\n#include <vector>\n\nnamespace ccpm\n{\n\n\tstruct area_top;\n\n\tstruct cca\n\t\t: public IHeap_expandable\n\t{\n\t\tusing byte_span = common::byte_span;\n\t\tusing persist_type = gsl::not_null<persister *>;\n\n\t\t/*\n\t\t * An objection arose to requiring multiple arguments for the cca constructor.\n\t\t * This struct allows construction from a single argument in all cases.\n\t\t * cca.h may not be the best place for this, as cca does not itsenf use the struct.\n\t\t */\n\t\tstruct ctor_args\n\t\t{\n\t\t\tpersist_type persister;\n\t\t\tregion_span regions;\n\t\t\tbool force_init;\n\t\t\townership_callback_type callee_owns;\n\t\t};\n\n\tprivate:\n\t\tusing top_vec_t = std::vector<std::unique_ptr<area_top>>;\n\t\ttop_vec_t _top;\n\t\ttop_vec_t::difference_type _last_top_allocate;\n\t\ttop_vec_t::difference_type _last_top_free;\n\t\tpersist_type _persist;\n\n\t\tvoid init(\n\t\t\tregion_span regions\n\t\t\t, ownership_callback_type resolver\n\t\t\t, bool force_init\n\t\t);\n\tpublic:\n\t\texplicit cca(persist_type persist, region_span regions, ownership_callback_type resolver);\n\n\t\texplicit cca(persist_type persist, region_span regions);\n\n\t\texplicit cca(persist_type persist);\n\n\t\t~cca();\n\n\t\tcca(const cca &) = delete;\n\t\tconst cca& operator=(const cca &) = delete;\n\n\t\tbool reconstitute(\n\t\t\tregion_span regions\n\t\t\t, ownership_callback_type resolver\n\t\t\t, bool force_init\n\t\t) override;\n\n\t\tstatus_t allocate(\n\t\t\tvoid * & ptr_\n\t\t\t, std::size_t bytes_\n\t\t\t, std::size_t alignment_\n\t\t) override;\n\n    void * allocate(std::size_t bytes_, std::size_t alignment_ = 1) {\n      void * ptr = nullptr;\n      if(allocate(ptr, bytes_, alignment_) != 0)\n        throw General_exception(\"ccpm::cca::allocate failed\");\n      return ptr;\n    }\n\n    void * allocate_root(std::size_t bytes_, std::size_t alignment_ = 8) {\n      void * ptr = nullptr;\n      if(allocate(ptr, bytes_, alignment_) != 0)\n        throw General_exception(\"ccpm::cca::allocate failed\");\n      set_root(common::make_byte_span(ptr, bytes_));\n      return ptr;\n    }\n\n\t\tstatus_t free(\n\t\t\tvoid * & ptr_\n\t\t\t, std::size_t bytes_\n\t\t) override;\n\n\t\tvoid add_regions(\n\t\t\tregion_span\n\t\t) override;\n\n\t\tbool includes(\n\t\t\tconst void *addr\n\t\t) const override;\n\n\t\tstatus_t remaining(\n\t\t\tstd::size_t & out_size_\n\t\t) const override;\n\n\t\tregion_vector_t get_regions() const override;\n\n    void set_root(\n      byte_span\n    );\n\n    byte_span get_root() const;\n\n\t\tvoid print(std::ostream &, const std::string &title = \"cca\") const;\n\t};\n}\n\n#endif\n", "meta": {"hexsha": "a73222f3532a8ea1f9b323680fbca60b2f6f6594", "size": 3220, "ext": "h", "lang": "C", "max_stars_repo_path": "src/lib/libccpm/include/ccpm/cca.h", "max_stars_repo_name": "omriarad/mcas", "max_stars_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 60.0, "max_stars_repo_stars_event_min_datetime": "2020-04-28T08:15:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T10:35:15.000Z", "max_issues_repo_path": "src/lib/libccpm/include/ccpm/cca.h", "max_issues_repo_name": "omriarad/mcas", "max_issues_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 66.0, "max_issues_repo_issues_event_min_datetime": "2020-09-03T23:40:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T20:34:52.000Z", "max_forks_repo_path": "src/lib/libccpm/include/ccpm/cca.h", "max_forks_repo_name": "omriarad/mcas", "max_forks_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2019-11-02T06:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T01:56:42.000Z", "avg_line_length": 24.7692307692, "max_line_length": 92, "alphanum_fraction": 0.7086956522, "num_tokens": 833, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14223190228178134, "lm_q2_score": 0.02479816001540669, "lm_q1q2_score": 0.0035270894720793016}}
{"text": "/*\n * VGMTrans (c) 2002-2019\n * Licensed under the zlib license,\n * refer to the included LICENSE.txt file\n */\n#pragma once\n\n#include <cstdint>\n#include <vector>\n#include <map>\n#include <string>\n#include <cassert>\n#include <climits>\n#include <gsl-lite.hpp>\n\nclass RawFile;\n\nconstexpr auto PSF_TAG_SIG = \"[TAG]\";\nconstexpr auto PSF_TAG_SIG_LEN = 5;\nconstexpr auto PSF_STRIP_BUF_SIZE = 4096;\n\nclass PSFFile2 {\n   public:\n    PSFFile2(const RawFile &file);\n    ~PSFFile2() = default;\n\n    uint8_t version() const noexcept { return m_version; }\n    const std::map<std::string, std::string> &tags() const noexcept { return m_tags; }\n    const std::vector<char> &exe() const noexcept { return m_exe_data; }\n    const std::vector<char> &reservedSection() const noexcept { return m_reserved_data; }\n\n    template <typename T>\n    T getExe(size_t ind) const {\n        assert(ind + sizeof(T) < m_exe_data.size());\n\n        T value = 0;\n        for (size_t i = 0; i < sizeof(T); i++) {\n            value |= (m_exe_data[ind + i] << (i * CHAR_BIT));\n        }\n\n        return value;\n    }\n\n    template <typename T>\n    T getRes(size_t ind) const {\n        assert(ind + sizeof(T) < m_reserved_data.size());\n\n        T value = 0;\n        for (size_t i = 0; i < sizeof(T); i++) {\n            value |= (m_reserved_data[ind + i] << (i * CHAR_BIT));\n        }\n\n        return value;\n    }\n\n   private:\n    uint8_t m_version;\n    uint32_t m_exe_CRC;\n    std::vector<char> m_exe_data;\n    std::vector<char> m_reserved_data;\n    std::map<std::string, std::string> m_tags;\n\n    void parseTags(gsl::span<const char> data);\n};\n", "meta": {"hexsha": "1b8487530b417367b6be71ed111179991461f04e", "size": 1603, "ext": "h", "lang": "C", "max_stars_repo_path": "src/main/components/PSFFile2.h", "max_stars_repo_name": "sykhro/vgmtrans-qt", "max_stars_repo_head_hexsha": "6d0780bdaaac29ffe118b9be2e2ad87401b426fe", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2018-01-04T17:42:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-26T02:52:22.000Z", "max_issues_repo_path": "src/main/components/PSFFile2.h", "max_issues_repo_name": "sykhro/vgmtrans-qt", "max_issues_repo_head_hexsha": "6d0780bdaaac29ffe118b9be2e2ad87401b426fe", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2017-10-19T16:47:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-10T15:26:24.000Z", "max_forks_repo_path": "src/main/components/PSFFile2.h", "max_forks_repo_name": "sykhro/vgmtrans-qt", "max_forks_repo_head_hexsha": "6d0780bdaaac29ffe118b9be2e2ad87401b426fe", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-10-19T16:40:12.000Z", "max_forks_repo_forks_event_max_datetime": "2017-10-19T16:40:12.000Z", "avg_line_length": 24.6615384615, "max_line_length": 89, "alphanum_fraction": 0.6182158453, "num_tokens": 439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.17328821446825263, "lm_q2_score": 0.02033235252641624, "lm_q1q2_score": 0.003523357065241735}}
{"text": "/*\nCopyright (c) 2015, Patrick Weltevrede\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <gsl/gsl_sort_float.h>\n#include <gsl/gsl_statistics_float.h>\n#include <gsl/gsl_integration.h>\n#include \"psrsalsa.h\"\nint filterPApoints(datafile_definition *datafile, verbose_definition verbose)\n{\n  int dPa_polnr;\n  long i, j, nrpoints;\n  float *olddata;\n  if(datafile->poltype != POLTYPE_ILVPAdPA && datafile->poltype != POLTYPE_PAdPA && datafile->poltype != POLTYPE_ILVPAdPATEldEl) {\n    printerror(verbose.debug, \"ERROR filterPApoints: Data doesn't appear to have poltype ILVPAdPA, PAdPA or ILVPAdPATEldEl.\");\n    return 0;\n  }\n  if(datafile->poltype == POLTYPE_ILVPAdPA && datafile->NrPols != 5) {\n    printerror(verbose.debug, \"ERROR filterPApoints: 5 polarization channels were expected, but there are only %ld.\", datafile->NrPols);\n    return 0;\n  }else if(datafile->poltype == POLTYPE_ILVPAdPATEldEl && datafile->NrPols != 8) {\n    printerror(verbose.debug, \"ERROR filterPApoints: 8 polarization channels were expected, but there are only %ld.\", datafile->NrPols);\n    return 0;\n  }else if(datafile->poltype == POLTYPE_PAdPA && datafile->NrPols != 2) {\n    printerror(verbose.debug, \"ERROR filterPApoints: 2 polarization channels were expected, but there are only %ld.\", datafile->NrPols);\n    return 0;\n  }\n  if(datafile->NrSubints > 1 || datafile->NrFreqChan > 1) {\n    printerror(verbose.debug, \"ERROR filterPApoints: Can only do this opperation if there is one subint and one frequency channel.\");\n    return 0;\n  }\n  if(datafile->tsampMode != TSAMPMODE_LONGITUDELIST) {\n    printerror(verbose.debug, \"ERROR filterPApoints: Expected pulse longitudes to be defined.\");\n    return 0;\n  }\n  if(datafile->poltype == POLTYPE_ILVPAdPA || datafile->poltype == POLTYPE_ILVPAdPATEldEl) {\n    dPa_polnr = 4;\n  }else if(datafile->poltype == POLTYPE_PAdPA) {\n    dPa_polnr = 1;\n  }\n  nrpoints = 0;\n  for(i = 0; i < datafile->NrBins; i++) {\n    if(datafile->data[i+dPa_polnr*datafile->NrBins] > 0) {\n      nrpoints++;\n    }\n  }\n  if(verbose.verbose)\n    printf(\"Keeping %ld significant PA points\\n\", nrpoints);\n  olddata = datafile->data;\n  datafile->data = (float *)malloc(nrpoints*datafile->NrPols*sizeof(float));\n  if(datafile->data == NULL) {\n    printerror(verbose.debug, \"ERROR filterPApoints: Memory allocation error.\");\n    return 0;\n  }\n  j = 0;\n  for(i = 0; i < datafile->NrBins; i++) {\n    if(olddata[i+dPa_polnr*datafile->NrBins] > 0) {\n      if(datafile->poltype == POLTYPE_ILVPAdPA) {\n datafile->data[j+0*nrpoints] = olddata[i+0*datafile->NrBins];\n datafile->data[j+1*nrpoints] = olddata[i+1*datafile->NrBins];\n datafile->data[j+2*nrpoints] = olddata[i+2*datafile->NrBins];\n datafile->data[j+3*nrpoints] = olddata[i+3*datafile->NrBins];\n datafile->data[j+4*nrpoints] = olddata[i+4*datafile->NrBins];\n      }else if(datafile->poltype == POLTYPE_ILVPAdPATEldEl) {\n datafile->data[j+0*nrpoints] = olddata[i+0*datafile->NrBins];\n datafile->data[j+1*nrpoints] = olddata[i+1*datafile->NrBins];\n datafile->data[j+2*nrpoints] = olddata[i+2*datafile->NrBins];\n datafile->data[j+3*nrpoints] = olddata[i+3*datafile->NrBins];\n datafile->data[j+4*nrpoints] = olddata[i+4*datafile->NrBins];\n datafile->data[j+5*nrpoints] = olddata[i+5*datafile->NrBins];\n datafile->data[j+6*nrpoints] = olddata[i+6*datafile->NrBins];\n datafile->data[j+7*nrpoints] = olddata[i+7*datafile->NrBins];\n      }else {\n datafile->data[j+0*nrpoints] = olddata[i+0*datafile->NrBins];\n datafile->data[j+1*nrpoints] = olddata[i+1*datafile->NrBins];\n      }\n      datafile->tsamp_list[j] = datafile->tsamp_list[i];\n      j++;\n    }\n  }\n  free(olddata);\n  datafile->NrBins = nrpoints;\n  return datafile->NrBins;\n}\nint make_paswing_fromIQUV(datafile_definition *datafile, int extended, pulselongitude_regions_definition onpulse, int normalize, int correctLbias, float correctQV, float correctV, int nolongitudes, float loffset, float paoffset, datafile_definition *rms_file, float rebin_factor, verbose_definition verbose)\n{\n  int indent, rms_file_specified;\n  long i, j, NrOffpulseBins, pulsenr, freqnr, output_nr_pols;\n  float ymax, baseline_intensity, RMSQ, RMSU, *Loffpulse, *Poffpulse, medianL, medianP, *newdata, *newdata_rms;\n  rms_file_specified = 1;\n  if(rms_file == NULL) {\n    rms_file = datafile;\n    rms_file_specified = 0;\n  }\n  if(verbose.verbose) {\n    for(indent = 0; indent < verbose.indent; indent++) printf(\" \");\n    printf(\"Constructing PA and degree of linear polarization\");\n    if(extended)\n      printf(\", total polarization and ellipticity\");\n    if(rms_file_specified)\n      printf(\" (using a seperate file to determine the off-pulse rms)\");\n    printf(\"\\n\");\n    for(indent = 0; indent < verbose.indent; indent++) printf(\" \");\n    printf(\"  Reference frequency for PA is \");\n    if(datafile->isDeFarad) {\n      if((datafile->freq_ref > -1.1 && datafile->freq_ref < -0.9) || (datafile->freq_ref > 0.99e10 && datafile->freq_ref < 1.01e10))\n printf(\"infinity\\n\");\n      else if(datafile->freq_ref < 0)\n printf(\"unknown\\n\");\n      else\n printf(\"%f MHz\\n\", datafile->freq_ref);\n    }else {\n      if(datafile->NrFreqChan == 1)\n printf(\"%lf MHz\\n\", get_centre_frequency(*datafile, verbose));\n      else\n printf(\"observing frequencies of individual frequency channels\\n\");\n    }\n    for(indent = 0; indent < verbose.indent; indent++) printf(\" \");\n    printf(\"  \");\n    switch(correctLbias) {\n    case -1: printf(\"No L de-bias applied\"); break;\n    case 0: printf(\"De-bias L using median noise subtraction\"); break;\n    case 1: printf(\"De-bias L using Wardle & Kronberg correction\"); break;\n    default: printerror(verbose.debug, \"ERROR make_paswing_fromIQUV: Undefined L de-bias method specified.\"); return 0;\n    }\n    if(correctQV != 1 || correctV != 1)\n      printf(\", Q correction factor %f, V correction factor %f\", 1.0/correctQV, 1.0/(correctQV*correctV));\n    if(normalize)\n      printf(\", output is normalised\");\n    if(loffset != 0)\n      printf(\", pulse longitude shifted by %f deg\\n\", loffset);\n    if(paoffset != 0)\n      printf(\", PA shifted by %f deg\\n\", paoffset);\n    printf(\"\\n\");\n    if(extended) {\n      printwarning(verbose.debug, \"WARNING make_paswing_fromIQUV: Total polarization is computed, and the median off-pulse value is subtracted (probably not a very good idea).\");\n    }\n  }\n  if(datafile->NrPols != 4 || rms_file->NrPols != 4) {\n    fflush(stdout);\n    printerror(verbose.debug, \"ERROR make_paswing_fromIQUV: Expected 4 input polarizations.\");\n    return 0;\n  }\n  if(datafile->poltype != POLTYPE_STOKES) {\n    if(datafile->poltype == POLTYPE_UNKNOWN) {\n      printwarning(verbose.debug, \"WARNING make_paswing_fromIQUV: Polarization state unknown, it is assumed the data are Stokes parameters.\");\n    }else {\n      printerror(verbose.debug, \"ERROR make_paswing_fromIQUV: Convert data into Stokes parameters first.\");\n      return 0;\n    }\n  }\n  if(rms_file_specified) {\n    if(rms_file->poltype != POLTYPE_STOKES) {\n      if(rms_file->poltype == POLTYPE_UNKNOWN) {\n printwarning(verbose.debug, \"WARNING make_paswing_fromIQUV: Polarization state of the data to be used to determine the off-pulse rms is unknown, it is assumed the data are Stokes parameters.\");\n      }else {\n printerror(verbose.debug, \"ERROR make_paswing_fromIQUV: Convert data to be used to determine the off-pulse rms into Stokes parameters first.\");\n return 0;\n      }\n    }\n  }\n  if(datafile->tsampMode != TSAMPMODE_FIXEDTSAMP) {\n    fflush(stdout);\n    printerror(verbose.debug, \"ERROR make_paswing_fromIQUV: Expects input to have a regular sampling.\");\n    return 0;\n  }\n  if(correctQV == 0) {\n    fflush(stdout);\n    printerror(verbose.debug, \"ERROR make_paswing_fromIQUV: correctQV is set to zero, you probably want this to be 1.\");\n    return 0;\n  }\n  if(correctV == 0) {\n    fflush(stdout);\n    printerror(verbose.debug, \"ERROR make_paswing_fromIQUV: correctV is set to zero, you probably want this to be 1.\");\n    return 0;\n  }\n  if(datafile->isDebase == 0) {\n    fflush(stdout);\n    printerror(verbose.debug, \"ERROR make_paswing_fromIQUV: Please remove baseline first, i.e. use pmod -debase.\");\n    return 0;\n  }else if(datafile->isDebase != 1) {\n    fflush(stdout);\n    printwarning(verbose.debug, \"WARNING make_paswing_fromIQUV: Unknown baseline state. It is assumed the baseline has already removed from the data.\");\n  }\n  if(rms_file_specified) {\n    if(rms_file->isDebase == 0) {\n      fflush(stdout);\n      printerror(verbose.debug, \"ERROR make_paswing_fromIQUV: Please remove baseline first, i.e. use pmod -debase.\");\n      return 0;\n    }else if(rms_file->isDebase != 1) {\n      fflush(stdout);\n      printwarning(verbose.debug, \"WARNING make_paswing_fromIQUV: Unknown baseline state. It is assumed the baseline has already removed from the data.\");\n    }\n  }\n  if(rms_file_specified) {\n    if(datafile->NrSubints != rms_file->NrSubints) {\n      printerror(verbose.debug, \"ERROR make_paswing_fromIQUV: Number of subintegrations is different in the data to be used to determine the off-pulse rms.\");\n return 0;\n    }\n    if(datafile->NrFreqChan != rms_file->NrFreqChan) {\n      printerror(verbose.debug, \"ERROR make_paswing_fromIQUV: Number of frequency channels is different in the data to be used to determine the off-pulse rms (%ld != %ld).\", rms_file->NrFreqChan, datafile->NrFreqChan);\n return 0;\n    }\n    if(correctLbias == 0) {\n      printerror(verbose.debug, \"ERROR make_paswing_fromIQUV: Subtracting the median of L is not supported when a separate file is used for the offpulse statistics.\");\n      return 0;\n    }\n    if(extended) {\n      printerror(verbose.debug, \"ERROR make_paswing_fromIQUV: Subtracting the median of P is not supported when a separate file is used for the offpulse statistics.\");\n      return 0;\n    }\n  }\n  if(datafile->offpulse_rms != NULL) {\n    free(datafile->offpulse_rms);\n  }\n  Loffpulse = (float *)malloc((rms_file->NrBins)*sizeof(float));\n  Poffpulse = (float *)malloc((rms_file->NrBins)*sizeof(float));\n  if(extended) {\n    output_nr_pols = 8;\n  }else {\n    output_nr_pols = 5;\n  }\n  newdata = (float *)malloc(datafile->NrBins*datafile->NrSubints*datafile->NrFreqChan*output_nr_pols*sizeof(float));\n  if(rms_file_specified) {\n    newdata_rms = (float *)malloc(rms_file->NrBins*rms_file->NrSubints*rms_file->NrFreqChan*output_nr_pols*sizeof(float));\n  }else {\n    newdata_rms = newdata;\n  }\n  datafile->offpulse_rms = (float *)malloc(datafile->NrSubints*datafile->NrFreqChan*output_nr_pols*sizeof(float));\n  if(Loffpulse == NULL || Poffpulse == NULL || newdata == NULL || datafile->offpulse_rms == NULL || newdata_rms == NULL) {\n    fflush(stdout);\n    printerror(verbose.debug, \"ERROR make_paswing_fromIQUV: Memory allocation error.\");\n    return 0;\n  }\n  if(nolongitudes == 0) {\n    datafile->tsamp_list = (double *)malloc(datafile->NrBins*sizeof(double));\n    if(datafile->tsamp_list == NULL) {\n      fflush(stdout);\n      printerror(verbose.debug, \"ERROR make_paswing_fromIQUV: Memory allocation error.\");\n      return 0;\n    }\n    for(j = 0; j < (datafile->NrBins); j++) {\n      datafile->tsamp_list[j] = get_pulse_longitude(*datafile, 0, j, verbose);\n      datafile->tsamp_list[j] += loffset;\n    }\n  }\n  if(normalize && (datafile->NrSubints > 1 || datafile->NrFreqChan > 1)) {\n    fflush(stdout);\n    printwarning(verbose.debug, \"WARNING make_paswing_fromIQUV: Normalization will cause all subintegrations/frequency channels to be normalised individually. This may not be desired.\");\n  }\n  long sindex_I, sindex_Q, sindex_U, sindex_V, sindex_I_rms, sindex_Q_rms, sindex_U_rms, sindex_V_rms, newindex_I, newindex_L, newindex_V, newindex_Pa, newindex_dPa, newindex_T, newindex_Ell, newindex_dEll, newindex_L_rms, newindex_T_rms;\n  for(pulsenr = 0; pulsenr < datafile->NrSubints; pulsenr++) {\n    for(freqnr = 0; freqnr < datafile->NrFreqChan; freqnr++) {\n      sindex_I = datafile->NrBins*(0+datafile->NrPols*(freqnr+pulsenr*datafile->NrFreqChan));\n      sindex_Q = datafile->NrBins*(1+datafile->NrPols*(freqnr+pulsenr*datafile->NrFreqChan));\n      sindex_U = datafile->NrBins*(2+datafile->NrPols*(freqnr+pulsenr*datafile->NrFreqChan));\n      sindex_V = datafile->NrBins*(3+datafile->NrPols*(freqnr+pulsenr*datafile->NrFreqChan));\n      newindex_I = datafile->NrBins*(0+output_nr_pols*(freqnr+datafile->NrFreqChan*pulsenr));\n      newindex_L = datafile->NrBins*(1+output_nr_pols*(freqnr+datafile->NrFreqChan*pulsenr));\n      newindex_V = datafile->NrBins*(2+output_nr_pols*(freqnr+datafile->NrFreqChan*pulsenr));\n      newindex_Pa = datafile->NrBins*(3+output_nr_pols*(freqnr+datafile->NrFreqChan*pulsenr));\n      newindex_dPa = datafile->NrBins*(4+output_nr_pols*(freqnr+datafile->NrFreqChan*pulsenr));\n      if(extended) {\n newindex_T = datafile->NrBins*(5+output_nr_pols*(freqnr+datafile->NrFreqChan*pulsenr));\n newindex_Ell = datafile->NrBins*(6+output_nr_pols*(freqnr+datafile->NrFreqChan*pulsenr));\n newindex_dEll = datafile->NrBins*(7+output_nr_pols*(freqnr+datafile->NrFreqChan*pulsenr));\n      }\n      if(rms_file_specified) {\n sindex_I_rms = rms_file->NrBins*(0+rms_file->NrPols*(freqnr+pulsenr*rms_file->NrFreqChan));\n sindex_Q_rms = rms_file->NrBins*(1+rms_file->NrPols*(freqnr+pulsenr*rms_file->NrFreqChan));\n sindex_U_rms = rms_file->NrBins*(2+rms_file->NrPols*(freqnr+pulsenr*rms_file->NrFreqChan));\n sindex_V_rms = rms_file->NrBins*(3+rms_file->NrPols*(freqnr+pulsenr*rms_file->NrFreqChan));\n newindex_L_rms = rms_file->NrBins*(1+output_nr_pols*(freqnr+rms_file->NrFreqChan*pulsenr));\n if(extended) {\n   newindex_T_rms = rms_file->NrBins*(5+output_nr_pols*(freqnr+rms_file->NrFreqChan*pulsenr));\n }\n      }else {\n sindex_I_rms = sindex_I;\n sindex_Q_rms = sindex_Q;\n sindex_U_rms = sindex_U;\n sindex_V_rms = sindex_V;\n newindex_L_rms = newindex_L;\n if(extended) {\n   newindex_T_rms = newindex_T;\n }\n      }\n      if(normalize == 0) {\n ymax = 1;\n      }else {\n ymax = datafile->data[sindex_I];\n for(j = 1; j < (datafile->NrBins); j++) {\n   if(datafile->data[sindex_I+j] > ymax)\n     ymax = datafile->data[sindex_I+j];\n }\n      }\n      if(ymax == 0)\n ymax = 1;\n      for(j = 0; j < (datafile->NrBins); j++) {\n datafile->data[sindex_I + j] /= ymax;\n datafile->data[sindex_Q + j] /= correctQV*ymax;\n datafile->data[sindex_U + j] /= ymax;\n datafile->data[sindex_V + j] /= correctV*correctQV*ymax;\n newdata[j+newindex_L] = sqrt((datafile->data[sindex_Q+j])*(datafile->data[sindex_Q+j])+(datafile->data[sindex_U+j])*(datafile->data[sindex_U+j]));\n if(extended) {\n   newdata[j+newindex_T] = sqrt(newdata[j+newindex_L]*newdata[j+newindex_L]+datafile->data[sindex_V+j]*datafile->data[sindex_V+j]);\n }\n      }\n      if(rms_file_specified) {\n for(j = 0; j < (rms_file->NrBins); j++) {\n   rms_file->data[sindex_I_rms + j] /= ymax;\n   rms_file->data[sindex_Q_rms + j] /= correctQV*ymax;\n   rms_file->data[sindex_U_rms + j] /= ymax;\n   rms_file->data[sindex_V_rms + j] /= correctV*correctQV*ymax;\n   newdata_rms[j+newindex_L_rms] = sqrt((rms_file->data[sindex_Q_rms+j])*(rms_file->data[sindex_Q_rms+j])+(rms_file->data[sindex_U_rms+j])*(rms_file->data[sindex_U_rms+j]));\n   if(extended) {\n     newdata_rms[j+newindex_T_rms] = sqrt(newdata[j+newindex_L_rms]*newdata[j+newindex_L_rms]+rms_file->data[sindex_V_rms+j]*rms_file->data[sindex_V_rms+j]);\n   }\n }\n      }\n      datafile->offpulse_rms[0+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] = 0;\n      datafile->offpulse_rms[1+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] = 0;\n      datafile->offpulse_rms[2+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] = 0;\n      datafile->offpulse_rms[3+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] = -1;\n      datafile->offpulse_rms[4+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] = -1;\n      if(extended) {\n datafile->offpulse_rms[5+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] = 0;\n datafile->offpulse_rms[6+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] = -1;\n datafile->offpulse_rms[7+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] = -1;\n      }\n      baseline_intensity = 0;\n      RMSQ = 0;\n      RMSU = 0;\n      NrOffpulseBins = 0;\n      for(i = 0; i < (rms_file->NrBins); i++) {\n Loffpulse[i] = 0;\n if(checkRegions(i, &onpulse, 0, verbose) == 0) {\n   NrOffpulseBins++;\n   baseline_intensity += rms_file->data[sindex_I_rms+i];\n   RMSQ += (rms_file->data[sindex_Q_rms+i])*(rms_file->data[sindex_Q_rms+i]);\n   RMSU += (rms_file->data[sindex_U_rms+i])*(rms_file->data[sindex_U_rms+i]);\n   datafile->offpulse_rms[0+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] += (rms_file->data[sindex_I_rms+i])*(rms_file->data[sindex_I_rms+i]);\n   datafile->offpulse_rms[1+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] += (newdata_rms[i+newindex_L_rms])*(newdata_rms[i+newindex_L_rms]);\n   datafile->offpulse_rms[2+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] += (rms_file->data[sindex_V_rms+i])*(rms_file->data[sindex_V_rms+i]);\n   if(extended) {\n     datafile->offpulse_rms[5+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] += (newdata_rms[i+newindex_L_rms])*(newdata_rms[i+newindex_L_rms]) + (rms_file->data[sindex_V_rms+i])*(rms_file->data[sindex_V_rms+i]);\n   }\n   Loffpulse[NrOffpulseBins-1] = newdata_rms[i+newindex_L_rms];\n   if(extended)\n     Poffpulse[NrOffpulseBins-1] = newdata_rms[i+newindex_T_rms];\n }\n      }\n      baseline_intensity /= (float)NrOffpulseBins;\n      RMSQ = sqrt(RMSQ/(float)NrOffpulseBins);\n      RMSU = sqrt(RMSU/(float)NrOffpulseBins);\n      datafile->offpulse_rms[0+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] = sqrt(datafile->offpulse_rms[0+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)]/(float)NrOffpulseBins);\n      datafile->offpulse_rms[1+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] = sqrt(datafile->offpulse_rms[1+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)]/(float)NrOffpulseBins);\n      datafile->offpulse_rms[2+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] = sqrt(datafile->offpulse_rms[2+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)]/(float)NrOffpulseBins);\n      if(extended) {\n datafile->offpulse_rms[5+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] = sqrt(datafile->offpulse_rms[5+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)]/(float)NrOffpulseBins);\n      }\n      if(rms_file_specified) {\n float scale = 1.0/sqrt(rebin_factor);\n RMSQ *= scale;\n RMSU *= scale;\n datafile->offpulse_rms[0+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] *= scale;\n datafile->offpulse_rms[1+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] *= scale;\n datafile->offpulse_rms[2+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] *= scale;\n if(extended) {\n   datafile->offpulse_rms[5+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] *= scale;\n }\n      }\n      if(verbose.verbose) {\n if((freqnr == 0 && pulsenr == 0) || verbose.debug) {\n   for(indent = 0; indent < verbose.indent; indent++) printf(\" \");\n   fprintf(stdout, \"  PA conversion output for subint %ld frequency channel %ld:\\n\", pulsenr, freqnr);\n   for(indent = 0; indent < verbose.indent; indent++) printf(\" \");\n   fprintf(stdout, \"    Average baseline Stokes I: %f\\n\", baseline_intensity);\n   for(indent = 0; indent < verbose.indent; indent++) printf(\" \");\n   fprintf(stdout, \"    RMS I:                  %f\\n\", datafile->offpulse_rms[0+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)]);\n   for(indent = 0; indent < verbose.indent; indent++) printf(\" \");\n   fprintf(stdout, \"    RMS Q:                  %f\\n\", RMSQ);\n   for(indent = 0; indent < verbose.indent; indent++) printf(\" \");\n   fprintf(stdout, \"    RMS U:                  %f\\n\", RMSU);\n   for(indent = 0; indent < verbose.indent; indent++) printf(\" \");\n   fprintf(stdout, \"    RMS V:                  %f\\n\", datafile->offpulse_rms[2+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)]);\n   for(indent = 0; indent < verbose.indent; indent++) printf(\" \");\n   fprintf(stdout, \"    RMS L (before de-bias): %f\\n\", datafile->offpulse_rms[1+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)]);\n   if(extended) {\n     for(indent = 0; indent < verbose.indent; indent++) printf(\" \");\n     fprintf(stdout, \"    RMS sqrt(Q^2+U^2+V^2):  %f\\n\", datafile->offpulse_rms[5+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)]);\n   }\n }\n      }\n      gsl_sort_float (Loffpulse, 1, NrOffpulseBins);\n      medianL = gsl_stats_float_median_from_sorted_data(Loffpulse, 1, NrOffpulseBins);\n      fflush(stdout);\n      if((verbose.verbose && freqnr == 0 && pulsenr == 0) || verbose.debug) {\n for(indent = 0; indent < verbose.indent; indent++) printf(\" \");\n fprintf(stdout, \"    Median L: %f\\n\", medianL);\n      }\n      if(extended) {\n gsl_sort_float (Poffpulse, 1, NrOffpulseBins);\n medianP = gsl_stats_float_median_from_sorted_data(Poffpulse, 1, NrOffpulseBins);\n fflush(stdout);\n if((verbose.verbose && freqnr == 0 && pulsenr == 0) || verbose.debug) {\n   for(indent = 0; indent < verbose.indent; indent++) printf(\" \");\n   fprintf(stdout, \"    Median sqrt(Q^2+U^2+V^2): %f\\n\", medianP);\n }\n      }\n      for(j = 0; j < (datafile->NrBins); j++) {\n if(correctLbias == 1) {\n   float junk = (0.5*(RMSQ+RMSU)/newdata[j+newindex_L]);\n   if(junk < 1)\n     newdata[j+newindex_L] *= sqrt(1.0-junk*junk);\n   else\n     newdata[j+newindex_L] = 0.0;\n }else if(correctLbias == 0) {\n   newdata[j+newindex_L] -= medianL;\n }\n if(extended)\n   newdata[j+newindex_T] -= medianP;\n      }\n      for(i = 0; i < (datafile->NrBins); i++) {\n newdata[i+newindex_Pa] = 90.0*atan2(datafile->data[sindex_U+i],datafile->data[sindex_Q+i])/M_PI;\n if(paoffset) {\n   newdata[i+newindex_Pa] += paoffset;\n   newdata[i+newindex_Pa] = derotate_180_small_double(newdata[i+newindex_Pa]);\n }\n if(datafile->data[i+sindex_Q] != 0 || datafile->data[i+sindex_U] != 0) {\n   newdata[i+newindex_dPa] = sqrt((datafile->data[sindex_Q+i]*RMSU)*(datafile->data[sindex_Q+i]*RMSU) + (datafile->data[sindex_U+i]*RMSQ)*(datafile->data[sindex_U+i]*RMSQ));\n   newdata[i+newindex_dPa] /= 2.0*(datafile->data[i+sindex_Q]*datafile->data[i+sindex_Q] + datafile->data[i+sindex_U]*datafile->data[i+sindex_U]);\n   newdata[i+newindex_dPa] *= 180.0/M_PI;\n }else {\n   newdata[i+newindex_dPa] = 0;\n }\n if(extended) {\n   newdata[i+newindex_Ell] = 0;\n     newdata[i+newindex_dEll] = 0;\n }\n      }\n      for(j = 0; j < (datafile->NrBins); j++) {\n newdata[j+newindex_I] = datafile->data[j+sindex_I];\n newdata[j+newindex_V] = datafile->data[j+sindex_V];\n      }\n    }\n  }\n  free(datafile->data);\n  datafile->data = newdata;\n  if(rms_file_specified) {\n    free(newdata_rms);\n  }\n  if(nolongitudes == 0) {\n    datafile->tsampMode = TSAMPMODE_LONGITUDELIST;\n  }\n  datafile->NrPols = output_nr_pols;\n  if(extended) {\n    datafile->poltype = POLTYPE_ILVPAdPATEldEl;\n  }else {\n    datafile->poltype = POLTYPE_ILVPAdPA;\n  }\n  free(Loffpulse);\n  free(Poffpulse);\n  return 1;\n}\nint writePPOLHeader(datafile_definition datafile, int argc, char **argv, verbose_definition verbose)\n{\n  char *txt;\n  txt = malloc(10000);\n  if(txt == NULL) {\n    fflush(stdout);\n    printerror(verbose.debug, \"ERROR writePPOLHeader: Memory allocation error.\");\n    return 0;\n  }\n  constructCommandLineString(txt, 10000, argc, argv, verbose);\n  fprintf(datafile.fptr_hdr, \"#ppol file: %s\\n\", txt);\n  free(txt);\n  return 1;\n}\nint readPPOLHeader(datafile_definition *datafile, int extended, verbose_definition verbose)\n{\n  float dummy_float;\n  int ret, maxlinelength, nrwords;\n  char *txt, *ret_ptr, *word_ptr;\n  maxlinelength = 2000;\n  txt = malloc(maxlinelength);\n  if(txt == NULL) {\n    fflush(stdout);\n    printerror(verbose.debug, \"ERROR readPPOLHeader: Memory allocation error.\");\n    return 0;\n  }\n  datafile->isFolded = 1;\n  datafile->foldMode = FOLDMODE_FIXEDPERIOD;\n  datafile->fixedPeriod = 0;\n  datafile->tsampMode = TSAMPMODE_LONGITUDELIST;\n  datafile->fixedtsamp = 0;\n  datafile->tsubMode = TSUBMODE_FIXEDTSUB;\n  if(datafile->tsub_list != NULL)\n    free(datafile->tsub_list);\n  datafile->tsub_list = (double *)malloc(sizeof(double));\n  if(datafile->tsub_list == NULL) {\n    fflush(stdout);\n    printerror(verbose.debug, \"ERROR readPPOLHeader: Memory allocation error\");\n    return 0;\n  }\n  datafile->tsub_list[0] = 0;\n  datafile->NrSubints = 1;\n  datafile->NrFreqChan = 1;\n  datafile->datastart = 0;\n  rewind(datafile->fptr);\n  ret = fread(txt, 1, 3, datafile->fptr);\n  txt[3] = 0;\n  if(ret != 3) {\n    fflush(stdout);\n    printerror(verbose.debug, \"ERROR readPPOLHeader: cannot read from file.\");\n    free(txt);\n    return 0;\n  }\n  if(strcmp(txt, \"#pp\") != 0\n) {\n    fflush(stdout);\n    printwarning(verbose.debug, \"WARNING readPPOLHeader: File does not appear to be in PPOL or PPOLSHORT format. I will try to load file, but this will probably fail. Did you run ppol first?\");\n  }\n  skipallhashedlines(datafile);\n  datafile->NrBins = 0;\n  dummy_float = 0;\n  do {\n    ret_ptr = fgets(txt, maxlinelength, datafile->fptr);\n    if(ret_ptr != NULL) {\n      if(txt[0] != '#') {\n if(extended) {\n   word_ptr = pickWordFromString(txt, 2, &nrwords, 1, ' ', verbose);\n   if(nrwords != 10 && nrwords != 14) {\n     fflush(stdout);\n     printerror(verbose.debug, \"ERROR readPPOLHeader: Line should have 10 or 14 words, got %d\", nrwords);\n     if(nrwords == 3)\n       printerror(verbose.debug, \"                             Maybe file is in format %s?\", returnFileFormat_str(PPOL_SHORT_format));\n     printerror(verbose.debug, \"                             Line: '%s'.\", txt);\n     free(txt);\n     return 0;\n   }\n   if(nrwords == 10) {\n     datafile->poltype = POLTYPE_ILVPAdPA;\n     datafile->NrPols = 5;\n   }else {\n     datafile->poltype = POLTYPE_ILVPAdPATEldEl;\n     datafile->NrPols = 8;\n   }\n }else {\n   word_ptr = pickWordFromString(txt, 1, &nrwords, 1, ' ', verbose);\n   if(nrwords != 3) {\n     fflush(stdout);\n     printerror(verbose.debug, \"ERROR readPPOLHeader: Line should have 3 words, got %d\", nrwords);\n     if(nrwords == 10)\n       printerror(verbose.debug, \"                             Maybe file is in format %s?\", returnFileFormat_str(PPOL_format));\n     printerror(verbose.debug, \"                             Line: '%s'.\", txt);\n     free(txt);\n     return 0;\n   }\n }\n ret = sscanf(word_ptr, \"%f\", &dummy_float);\n if(ret != 1) {\n   fflush(stdout);\n   printerror(verbose.debug, \"ERROR readPPOLHeader: Cannot interpret as a float: '%s'.\", txt);\n   free(txt);\n   return 0;\n }\n if(dummy_float >= 360) {\n   fflush(stdout);\n   printwarning(verbose.debug, \"WARNING: IGNORING POINTS AT PULSE LONGITUDES > 360 deg.\");\n }else {\n   (datafile->NrBins)++;\n }\n      }\n    }\n  }while(ret_ptr != NULL && dummy_float < 360);\n  if(extended == 0) {\n    datafile->poltype = POLTYPE_PAdPA;\n    datafile->NrPols = 2;\n  }\n  fflush(stdout);\n  if(verbose.verbose) fprintf(stdout, \"Going to load %ld points from %s\\n\", datafile->NrBins, datafile->filename);\n  if(datafile->NrBins == 0) {\n    fflush(stdout);\n    printerror(verbose.debug, \"ERROR readPPOLHeader: No data in %s\", datafile->filename);\n    free(txt);\n    return 0;\n  }\n  fseek(datafile->fptr, datafile->datastart, SEEK_SET);\n  free(txt);\n  if(datafile->offpulse_rms != NULL) {\n    free(datafile->offpulse_rms);\n    datafile->offpulse_rms = NULL;\n  }\n  if(extended) {\n    datafile->offpulse_rms = (float *)malloc(datafile->NrSubints*datafile->NrFreqChan*datafile->NrPols*sizeof(float));\n    if(datafile->offpulse_rms == NULL) {\n      fflush(stdout);\n      printerror(verbose.debug, \"ERROR readPPOLHeader: Memory allocation error\");\n      return 0;\n    }\n  }\n  datafile->tsamp_list = (double *)malloc(datafile->NrBins*sizeof(double));\n  if(datafile->tsamp_list == NULL) {\n    fflush(stdout);\n    printerror(verbose.debug, \"ERROR readPPOLHeader: Memory allocation error\");\n    return 0;\n  }\n  return 1;\n}\nint readPPOLfile(datafile_definition *datafile, float *data, int extended, float add_longitude_shift, verbose_definition verbose)\n{\n  int maxlinelength;\n  long i, k, dummy_long;\n  char *txt, *ret_ptr;\n  if(datafile->NrBins == 0) {\n    fflush(stdout);\n    printerror(verbose.debug, \"ERROR readPPOLfile: No data in %s\", datafile->filename);\n    return 0;\n  }\n  maxlinelength = 2000;\n  txt = malloc(maxlinelength);\n  if(txt == NULL) {\n    fflush(stdout);\n    printerror(verbose.debug, \"ERROR readPPOLfile: Memory allocation error.\");\n    return 0;\n  }\n  fseek(datafile->fptr, datafile->datastart, SEEK_SET);\n  k = 0;\n  if(extended) {\n    datafile->offpulse_rms[3] = -1;\n    datafile->offpulse_rms[4] = -1;\n    if(datafile->NrPols == 8) {\n      datafile->offpulse_rms[6] = -1;\n      datafile->offpulse_rms[7] = -1;\n    }\n  }\n  for(i = 0; i < datafile->NrBins; i++) {\n    ret_ptr = fgets(txt, maxlinelength, datafile->fptr);\n    if(ret_ptr == NULL) {\n      fflush(stdout);\n      printerror(verbose.debug, \"ERROR readPPOLfile: Cannot read next line, should not happen after successfully reading in header\");\n      free(txt);\n      return 0;\n    }\n    if(txt[0] != '#') {\n      if(extended == 0) {\n sscanf(txt, \"%lf %f %f\", &(datafile->tsamp_list[k]), &(data[k]), &(data[k+datafile->NrBins]));\n      }else {\n if(datafile->NrPols == 8) {\n   sscanf(txt, \"%ld %lf %f %f %f %f %f %f %f %f %f %f %f %f\", &dummy_long, &(datafile->tsamp_list[k]), &(data[k]), &(datafile->offpulse_rms[0]), &(data[k+datafile->NrBins]), &(datafile->offpulse_rms[1]), &(data[k+2*datafile->NrBins]), &(datafile->offpulse_rms[2]), &(data[k+3*datafile->NrBins]), &(data[k+4*datafile->NrBins]), &(data[k+5*datafile->NrBins]), &(datafile->offpulse_rms[5]), &(data[k+6*datafile->NrBins]), &(data[k+7*datafile->NrBins]));\n }else {\n   sscanf(txt, \"%ld %lf %f %f %f %f %f %f %f %f\", &dummy_long, &(datafile->tsamp_list[k]), &(data[k]), &(datafile->offpulse_rms[0]), &(data[k+datafile->NrBins]), &(datafile->offpulse_rms[1]), &(data[k+2*datafile->NrBins]), &(datafile->offpulse_rms[2]), &(data[k+3*datafile->NrBins]), &(data[k+4*datafile->NrBins]));\n }\n      }\n      datafile->tsamp_list[k] += add_longitude_shift;\n      if(datafile->tsamp_list[k] >= 0 && datafile->tsamp_list[k] < 360) {\n   k++;\n      }else {\n fflush(stdout);\n printwarning(verbose.debug, \"WARNING readPPOLfile: IGNORING POINTS AT PULSE LONGITUDES > 360 deg.\");\n      }\n    }\n  }\n  if(k != datafile->NrBins) {\n    fflush(stdout);\n    printerror(verbose.debug, \"WARNING readPPOLfile: The nr of bins read in is different as determined from header. Something is wrong.\");\n    return 0;\n  }\n  fflush(stdout);\n  if(verbose.verbose) fprintf(stdout, \"readPPOLfile: Accepted %ld points\\n\", datafile->NrBins);\n     free(txt);\n  return 1;\n}\nint writePPOLfile(datafile_definition datafile, float *data, int extended, int onlysignificantPA, int twoprofiles, float PAoffset, verbose_definition verbose)\n{\n  long j;\n  if(datafile.poltype != POLTYPE_ILVPAdPA && datafile.poltype != POLTYPE_PAdPA && datafile.poltype != POLTYPE_ILVPAdPATEldEl) {\n    printerror(verbose.debug, \"ERROR writePPOLfile: Data doesn't appear to have poltype ILVPAdPA, PAdPA or ILVPAdPATEldEl (it is %d).\", datafile.poltype);\n    return 0;\n  }\n  if(datafile.poltype == POLTYPE_ILVPAdPA && datafile.NrPols != 5) {\n    printerror(verbose.debug, \"ERROR writePPOLfile: 5 polarization channels were expected, but there are %ld.\", datafile.NrPols);\n    return 0;\n  }else if(datafile.poltype == POLTYPE_PAdPA && datafile.NrPols != 2) {\n    printerror(verbose.debug, \"ERROR writePPOLfile: 2 polarization channels were expected, but there are %ld.\", datafile.NrPols);\n    return 0;\n  }else if(datafile.poltype == POLTYPE_ILVPAdPATEldEl && datafile.NrPols != 8) {\n    printerror(verbose.debug, \"ERROR writePPOLfile: 8 polarization channels were expected, but there are %ld.\", datafile.NrPols);\n    return 0;\n  }\n  if(datafile.NrSubints > 1 || datafile.NrFreqChan > 1) {\n    printerror(verbose.debug, \"ERROR writePPOLfile: Can only do this opperation if there is one subint and one frequency channel.\");\n    return 0;\n  }\n  if(datafile.tsampMode != TSAMPMODE_LONGITUDELIST) {\n    printerror(verbose.debug, \"ERROR writePPOLfile: Expected pulse longitudes to be defined.\");\n    return 0;\n  }\n  int pa_offset, dpa_offset;\n  if(datafile.poltype == POLTYPE_ILVPAdPA || datafile.poltype == POLTYPE_ILVPAdPATEldEl) {\n    pa_offset = 3;\n    dpa_offset = 4;\n  }else if(datafile.poltype == POLTYPE_PAdPA) {\n    pa_offset = 0;\n    dpa_offset = 1;\n  }\n  for(j = 0; j < datafile.NrBins; j++) {\n    if(data[j+dpa_offset*datafile.NrBins] > 0 || onlysignificantPA == 0) {\n      if(extended) {\n fprintf(datafile.fptr, \"%ld %e %e %e %e %e %e %e %e %e\", j, datafile.tsamp_list[j], data[j], datafile.offpulse_rms[0], data[j+datafile.NrBins], datafile.offpulse_rms[1], data[j+2*datafile.NrBins], datafile.offpulse_rms[2], data[j+pa_offset*datafile.NrBins]+PAoffset, data[j+dpa_offset*datafile.NrBins]);\n if(datafile.poltype == POLTYPE_ILVPAdPATEldEl)\n   fprintf(datafile.fptr, \" %e %e %e %e\", data[j+5*datafile.NrBins], datafile.offpulse_rms[5], data[j+6*datafile.NrBins], data[j+7*datafile.NrBins]);\n fprintf(datafile.fptr, \"\\n\");\n      }else {\n fprintf(datafile.fptr, \"%e %e %e\\n\", datafile.tsamp_list[j], data[j+pa_offset*datafile.NrBins]+PAoffset, data[j+dpa_offset*datafile.NrBins]);\n      }\n    }\n  }\n  if(twoprofiles) {\n    for(j = 0; j < datafile.NrBins; j++) {\n      if(data[j+dpa_offset*datafile.NrBins] > 0 || onlysignificantPA == 0) {\n if(extended) {\n   fprintf(datafile.fptr, \"%ld %e %e %e %e %e %e %e %e %e\", j, datafile.tsamp_list[j]+360, data[j], datafile.offpulse_rms[0], data[j+datafile.NrBins], datafile.offpulse_rms[1], data[j+2*datafile.NrBins], datafile.offpulse_rms[2], data[j+pa_offset*datafile.NrBins]+PAoffset, data[j+dpa_offset*datafile.NrBins]);\n   if(datafile.poltype == POLTYPE_ILVPAdPATEldEl)\n     fprintf(datafile.fptr, \" %e %e %e %e\", data[j+5*datafile.NrBins], datafile.offpulse_rms[5], data[j+6*datafile.NrBins], data[j+7*datafile.NrBins]);\n   fprintf(datafile.fptr, \"\\n\");\n }else {\n   fprintf(datafile.fptr, \"%e %e %e\\n\", datafile.tsamp_list[j]+360, data[j]+PAoffset, data[j+dpa_offset*datafile.NrBins]);\n }\n      }\n    }\n  }\n  return 1;\n}\n", "meta": {"hexsha": "393ea22da10936e432e4a1ea070145001b3c3e34", "size": 35337, "ext": "c", "lang": "C", "max_stars_repo_path": "src/lib/psrio_paswing.c", "max_stars_repo_name": "David-McKenna/psrsalsa", "max_stars_repo_head_hexsha": "e5074b552d1c404123dee058d5cee79ea230b5a9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lib/psrio_paswing.c", "max_issues_repo_name": "David-McKenna/psrsalsa", "max_issues_repo_head_hexsha": "e5074b552d1c404123dee058d5cee79ea230b5a9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lib/psrio_paswing.c", "max_forks_repo_name": "David-McKenna/psrsalsa", "max_forks_repo_head_hexsha": "e5074b552d1c404123dee058d5cee79ea230b5a9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.1789052069, "max_line_length": 755, "alphanum_fraction": 0.6861646433, "num_tokens": 10960, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18952110048512089, "lm_q2_score": 0.018546566478605368, "lm_q1q2_score": 0.0035149656892457426}}
{"text": "/*\n *  Copyright (C) 2021 FISCO BCOS.\n *  SPDX-License-Identifier: Apache-2.0\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n * @file LogEntry.h\n * @author: yujiechen\n * @date: 2021-03-18\n */\n#pragma once\n#include \"../interfaces/crypto/CryptoSuite.h\"\n#include \"../libutilities/Common.h\"\n#include \"../libutilities/FixedBytes.h\"\n#include <gsl/span>\n\nnamespace bcos\n{\nnamespace protocol\n{\nclass LogEntry\n{\npublic:\n    using Ptr = std::shared_ptr<LogEntry>;\n    LogEntry() = default;\n    LogEntry(bytes const& _address, h256s _topics, bytes _data)\n      : m_address(_address), m_topics(std::move(_topics)), m_data(std::move(_data))\n    {}\n\n    ~LogEntry() {}\n\n    std::string_view address() const\n    {\n        return std::string_view((char*)m_address.data(), m_address.size());\n    }\n    gsl::span<const h256> topics() const { return gsl::span(m_topics.data(), m_topics.size()); }\n    bytesConstRef data() const { return ref(m_data); }\n    // Define the scale decode method, which cannot be modified at will\n    template <class Stream, typename = std::enable_if_t<Stream::is_decoder_stream>>\n    friend Stream& operator>>(Stream& _stream, LogEntry& _logEntry)\n    {\n        return _stream >> _logEntry.m_address >> _logEntry.m_topics >> _logEntry.m_data;\n    }\n\n    // Define the scale encode method, which cannot be modified at will\n    template <class Stream, typename = std::enable_if_t<Stream::is_encoder_stream>>\n    friend Stream& operator<<(Stream& _stream, LogEntry const& _logEntry)\n    {\n        return _stream << _logEntry.m_address << _logEntry.m_topics << _logEntry.m_data;\n    }\n\nprivate:\n    bcos::bytes m_address;\n    bcos::h256s m_topics;\n    bytes m_data;\n};\n\nusing LogEntries = std::vector<LogEntry>;\nusing LogEntriesPtr = std::shared_ptr<std::vector<LogEntry>>;\n}  // namespace protocol\n}  // namespace bcos", "meta": {"hexsha": "3da9d9469ac78449a1afc2be106b40097b3bc39e", "size": 2341, "ext": "h", "lang": "C", "max_stars_repo_path": "bcos-framework/libprotocol/LogEntry.h", "max_stars_repo_name": "xueying4402/FISCO-BCOS", "max_stars_repo_head_hexsha": "737e08752e8904c7c24e3737f8f46bf5327ef792", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bcos-framework/libprotocol/LogEntry.h", "max_issues_repo_name": "xueying4402/FISCO-BCOS", "max_issues_repo_head_hexsha": "737e08752e8904c7c24e3737f8f46bf5327ef792", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 267.0, "max_issues_repo_issues_event_min_datetime": "2021-03-01T02:12:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-17T08:18:34.000Z", "max_forks_repo_path": "bcos-framework/libprotocol/LogEntry.h", "max_forks_repo_name": "xueying4402/FISCO-BCOS", "max_forks_repo_head_hexsha": "737e08752e8904c7c24e3737f8f46bf5327ef792", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2021-02-22T03:47:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-06T06:41:02.000Z", "avg_line_length": 33.4428571429, "max_line_length": 96, "alphanum_fraction": 0.697992311, "num_tokens": 598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16667542124551754, "lm_q2_score": 0.020964240129981934, "lm_q1q2_score": 0.003494223554756922}}
{"text": "/*\n   Copyright [2019-2021] [IBM Corporation]\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n       http://www.apache.org/licenses/LICENSE-2.0\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\n#ifndef __CCPM_INTERFACES_H__\n#define __CCPM_INTERFACES_H__\n\n#include <common/byte_span.h>\n#include <common/types.h>\n#include <gsl/pointers>\n#include <cstddef>\n#include <functional>\n#include <vector>\n\nnamespace ccpm\n{\n\tstruct persister\n\t{\n\t\tusing byte_span = common::byte_span;\n\t\tvirtual void persist(byte_span span) = 0;\n\tprotected:\n\t\t~persister() {}\n\t};\n\n/*\n * Ownership callback can resolve the ambiguity about area\n *        ownership which occurs during phase (b) of allocate() and free()\n *        Intended to be used by IHeap::reconstitute when a crash during\n *        an IHeap::allocate or IHeap::free call has left area ownership\n *        in doubt.\n *\n * In order to support ownership resolution, it is expected that a caller to\n * allocate or free will\n *   (1) store and persist the initial value of ptr\n *   (2) call allocate or free\n *\n * It is expected that IHeap::allocate() will\n *   (1) determine an appropriate new value for ptr\n *   (2) persist a note indicating that the allocation status of the new value\n *       of ptr is indeterminate.\n *   (3) store and persist the new value of ptr\n *   (4) persist an invalidation of the note written in step 2.\n *\n * It is expected that IHeap::free() will\n *   (1) persist a note indicating that the allocation status of the value\n *       of ptr is indeterminate.\n *   (2) store and persist nullptr as the new value of ptr\n *   (3) return the area located by the original value of ptr to free status\n *   (4) persist an invalidation of the note written in step 1.\n */\n\nusing ownership_callback_type = std::function<bool(const void * ptr)>;\nusing ownership_callback_t = ownership_callback_type;\n\ninline bool accept_all(const void *) { return true; }\n/*\n * Allocators can expand to more than one coarse-grained region of\n * memory.\n */\nstruct region_vector_t : public std::vector<common::byte_span>\n{\n\tusing base = std::vector<common::byte_span>;\n  explicit region_vector_t(void * ptr_, std::size_t size_)\n    : region_vector_t(common::make_byte_span(static_cast<common::byte *>(ptr_), size_))\n  {}\n  explicit region_vector_t(const value_type &v) {\n    push_back(v);\n  }\n  region_vector_t() {\n  }\n\tconst base &cbase() const { return *this; }\n};\n\nusing region_span = gsl::span<common::byte_span>;\n\nenum class Type_id : int64_t\n  {\n    None        = 0,\n    Fixed_array = 0xF0,\n  };\n\n/**\n * Heap allocator (variable sized allocations)\n */\nclass IHeap\n{\npublic:\n  virtual ~IHeap() {}\n\n  /* Reconstitute/initialize slab from existing memory\n   *\n   * @param regions Pointer/length regions of contiguous memory\n   * @param resolver Access to an object which can resolve the ambiguity\n   *        over area ownership which occurs during a phase of allocate()\n   *        and free() calls. If the callee of the ownership_callback_t\n   *        function might own the area located by the arument, the callee\n   *        must return true. If the callee does not own the area, it should\n   *        return false.\n   * @param force_init If true, force re-setting to empty\n   *\n   *\n   * @return : True if memory was reset to empty\n   **/\n  virtual bool reconstitute(const region_span regions,\n                            ownership_callback_t resolver = [] (const void *) -> bool { return true; },\n                            const bool force_init = false) = 0;\n\n  /* Allocate memory\n   *\n   * @param ptr in/out: nullptr -> pointer to newly allocated memory\n   *                    On a successful allocation the allocator will\n   *                    first write and then persist ptr. Allocation\n   *                    has three phases:\n   *                    (a) ptr is not yet written; the allocator unambiguously\n   *                        owns the free \"area\" the address of which it will\n   *                        later write into ptr.\n   *                    (b) allocator has written ptr, but has not yet persisted\n   *                        ptr. Caller must be able to tell the allocator (see\n   *                        reconstitute) whether caller has accepted ownership\n   *                        of the allocated area. Acceptance is implicit.\n   *                        Visibility of a non-null value in ptr, which happens\n   *                        upon write in the non-crash case and upon persist in\n   *                        the crash+reconstitute case, consititutes acceptance.\n   *                    (c) allocator has persisted the ptr. Caller will know upon\n   *                        successful return (normal case) or discovery of a\n   *                        non-null value (crash+reconstitute case) that it owns\n   *                        the area.\n   *\n   *                    The pointer shall be altered iff the function returns S_OK.\n   *\n   * @param size Size of memory to allocate in bytes\n   * @param alignment Alignment for memory\n   *\n   * @return : S_OK, E_INVAL, E_BAD_PARAM, E_EMPTY\n   **/\n  virtual status_t allocate(void * & ptr,\n                            std::size_t bytes,\n                            std::size_t alignment) = 0;\n\n  /* Free previously allocated memory.\n   * @param ptr in/out: Pointer to memory to free, which must have been previously\n   *                    allocated with the same size and alignment.\n   *                    On a successful free the allocator will first nullify ptr\n   *                    and then persist ptr. Free has has three phases, similar\n   *                    to allocation:\n   *                    (a) ptr is not yet written; the caller unambiguously\n   *                        owns the \"area\".\n   *                    (b) allocator has nullified ptr, but has not yet persisted\n   *                        ptr. Caller must be able to tell the allocator (see\n   *                        reconstitute) whether caller has relinquished ownership\n   *                        of the allocated area. Relinquishment is implicit.\n   *                        Visibility of a null value in ptr, which happens upon\n   *                        write in the non-crash case and upon persist in the\n   *                        crash+reconstitute case, consititutes relinquishment.\n   *                    (c) allocator has persisted the (null-valued) ptr. Caller\n   *                        will know upon successful return (normal case) or\n   *                        discovery of null value (crash+reconstitute case) that\n   *                        the allocator now owns the area.\n   *\n   *                    The pointer shall be altered iff the function returns S_OK.\n   *\n   * @param size Size of memory to free in bytes\n   *\n   * @return : S_OK, E_INVAL\n   **/\n  virtual status_t free(void * & ptr,\n                        std::size_t bytes = 0) = 0;\n\n  /* Return remaining space in bytes\n   * @param out_size Size remaining in bytes\n   *\n   * @return S_OK or E_NOT_IMPL\n   **/\n  virtual status_t remaining(std::size_t& out_size) const = 0;\n\n  /* Return a vector of all regions\n   *\n   * @return vector containing the initial regions and all subsequently added\n   * regions, if the implementation keeps track of regions. Otherwise, an\n   * empty region_vector_t.\n   **/\n  virtual region_vector_t get_regions() const = 0;\n};\n\n/**\n * Heap allocator (variable sized allocations)\n */\nclass IHeap_expandable : public IHeap\n{\npublic:\n  /* Add an additional regions to the heap\n   * @param regions Pointer/length regions of contiguous memory\n   **/\n  virtual void add_regions(const region_span regions) = 0;\n\n  /** Test whether an address is in any heap region\n   * @param addr the address to test\n   *\n   * @erturn true iff the address is in some heap region\n   */\n  virtual bool includes(const void *ptr) const = 0;\n};\n\nclass ILog\n{\npublic:\n  virtual ~ILog() = default;\n\n  /*\n   * Record old value of a region to the log.\n   */\n  virtual void add(void *begin, std::size_t size) = 0;\n  /*\n   * Record an allocation to the log.\n   */\n  virtual void allocated(void *&p, std::size_t size) = 0;\n  /*\n   * Record a free to the log.\n   */\n  virtual void freed(void *&p, std::size_t size) = 0;\n\n  /*\n   * commit all previous add/allocated/freed commands\n   */\n  virtual void commit() = 0;\n  /*\n   * Restore all data areas added after initialization (or the most recent clear)\n   * to the values present at their last add command.\n   */\n  virtual void rollback() = 0;\n\n};\n}\n#endif //  __CCPM_INTERFACES_H__\n", "meta": {"hexsha": "370371288bc7f1de5552622ed5b3685f8d1222b3", "size": 8939, "ext": "h", "lang": "C", "max_stars_repo_path": "src/lib/libccpm/include/ccpm/interfaces.h", "max_stars_repo_name": "omriarad/mcas", "max_stars_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 60.0, "max_stars_repo_stars_event_min_datetime": "2020-04-28T08:15:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T10:35:15.000Z", "max_issues_repo_path": "src/lib/libccpm/include/ccpm/interfaces.h", "max_issues_repo_name": "omriarad/mcas", "max_issues_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 66.0, "max_issues_repo_issues_event_min_datetime": "2020-09-03T23:40:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T20:34:52.000Z", "max_forks_repo_path": "src/lib/libccpm/include/ccpm/interfaces.h", "max_forks_repo_name": "omriarad/mcas", "max_forks_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2019-11-02T06:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T01:56:42.000Z", "avg_line_length": 36.6352459016, "max_line_length": 103, "alphanum_fraction": 0.6270276317, "num_tokens": 2069, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1384617799035966, "lm_q2_score": 0.025178839231809528, "lm_q1q2_score": 0.003486306895942854}}
{"text": "#ifndef SPC_FITSCARDS_H\n#define SPC_FITSCARDS_H\n\n#include <stdlib.h>\n\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_vector.h>\n\n#include \"aXe_grism.h\"\n#include \"fitsio.h\"\n#include \"disp_conf.h\"\n#include \"aper_conf.h\"\n\ntypedef struct\n{\n  int n;          /* Number of cards in the **cards array */\n  char **cards;   /* A pointer to an array of strings     */\n} FITScards;\n\nextern FITScards *\nallocate_FITScards(int n);\n\nextern void\nfree_FITScards(FITScards *cards);\n\nextern FITScards *\nget_WCS_FITScards(const double rval1, const double delta1, const double rval2);\n\nextern FITScards *\nbeam_to_FITScards(object *ob, int beamnum);\n\nextern FITScards *\nstpmin_to_FITScards(d_point stp_min);\n\nextern FITScards *\ndrzinfo_to_FITScards(object *ob, int beamnum, d_point outref,\n\t\t     aperture_conf *conf, gsl_matrix *drizzcoeffs,\n\t\t     int trlength, double relx, double rely,\n\t\t     double objwidth, d_point refwave_pos,\n\t\t     float sky_cps, double drizzle_width,\n\t\t     double cdcorr, double spcorr);\n\nextern FITScards *\nnicbck_info_to_FITScards(const double skypix_frac, const double scale_factor,\n\t\t\t const double offset);\n\nextern FITScards *\ndispstruct_to_FITScards(dispstruct *disp);\n\nextern void\nupdate_contam_model(fitsfile *fptr, char model_name[]);\n\nextern int\ncheck_quantitative_contamination(fitsfile *fptr);\n\nextern void\ntransport_cont_modname(char grism_file_path[], char PET_file_path[]);\n\n#endif\n", "meta": {"hexsha": "984c34eb082f0e49253d10991e044004fd761e07", "size": 1403, "ext": "h", "lang": "C", "max_stars_repo_path": "cextern/src/spc_FITScards.h", "max_stars_repo_name": "sosey/pyaxe", "max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cextern/src/spc_FITScards.h", "max_issues_repo_name": "sosey/pyaxe", "max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cextern/src/spc_FITScards.h", "max_forks_repo_name": "sosey/pyaxe", "max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3833333333, "max_line_length": 79, "alphanum_fraction": 0.7569493942, "num_tokens": 387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.19682621306573764, "lm_q2_score": 0.01771229497656452, "lm_q1q2_score": 0.0034862439449404826}}
{"text": "/* $Header$ */\n\n/* ncks -- netCDF Kitchen Sink */\n\n/* Purpose: Extract (subsets of) variables from a netCDF file \n   Print them to screen, copy them to another file, or regrid them\n   Since 2015 ncks has also been the back-end to the ncremap regridder,\n   meaning that ncks implements the regridder API and functionality, \n   though all of that is a segregable component of ncks.\n   The regridder is really just an API and that ncks implements */\n\n/* Copyright (C) 1995--present Charlie Zender\n   This file is part of NCO, the netCDF Operators. NCO is free software.\n   You may redistribute and/or modify NCO under the terms of the \n   3-Clause BSD License.\n   You are permitted to link NCO with the HDF, netCDF, OPeNDAP, and UDUnits\n   libraries and to distribute the resulting executables under the terms \n   of the BSD, but in addition obeying the extra stipulations of the \n   HDF, netCDF, OPeNDAP, and UDUnits licenses.\n\n   This program is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  \n   See the 3-Clause BSD License for more details.\n   \n   The original author of this software, Charlie Zender, seeks to improve\n   it with your suggestions, contributions, bug-reports, and patches.\n   Please contact the NCO project at http://nco.sf.net or write to\n   Charlie Zender\n   Department of Earth System Science\n   University of California, Irvine\n   Irvine, CA 92697-3100 */\n\n/* URL: https://github.com/nco/nco/tree/master/src/nco/ncks.c\n\n   Usage:\n   ncks ~/nco/data/in.nc \n   ncks -v one ~/nco/data/in.nc\n   ncks ~/nco/data/in.nc ~/foo.nc\n   ncks -O -4 ~/nco/data/in.nc ~/foo.nc\n   ncks -v one ~/nco/data/in.nc ~/foo.nc\n   ncks -p /ZENDER/tmp -l /data/zender/tmp h0001.nc ~/foo.nc\n   ncks -s \"%+16.10f\\n\" -H -C -v three_dmn_var ~/nco/data/in.nc\n   ncks -H -v fl_nm,fl_nm_arr ~/nco/data/in.nc\n   ncks -H -C -u -d wvl,'0.4 micron','0.7 micron' -v wvl ~/nco/data/in.nc\n   ncks -H -d fl_dim,1 -d char_dim,6,12 -v fl_nm,fl_nm_arr ~/nco/data/in.nc\n   ncks -H -m -v char_var_nul,char_var_space,char_var_multinul ~/nco/data/in.nc\n   ncks -H -C -v three_dmn_rec_var -d time,,,2 ~/nco/data/in.nc\n   ncks -H -C -v lon -d lon,3,1 ~/nco/data/in.nc \n   ncks -M -p http://thredds-test.ucar.edu/thredds/dodsC/testdods in.nc\n   ncks -O -v one -p http://thredds-testa.ucar.edu/thredds/dodsC/testdods in.nc ~/foo.nc\n   ncks -O -G foo ~/nco/data/in.nc ~/foo.nc\n   ncks -O -G :-5 -v v7 ~/nco/data/in_grp.nc ~/foo.nc\n   ncks -O -G level3name:-5 -v v7 ~/nco/data/in_grp.nc ~/foo.nc\n   ncks -O -v time ~/in_grp.nc ~/foo.nc\n   ncks -O --sysconf ~/in_grp.nc ~/foo.nc\n   ncks -C --xml_spr_chr=', ' -v two_dmn_rec_var_sng ~/nco/data/in.nc\n   ncks --cdl -v one_dmn_rec_var ~/nco/data/in.nc\n   ncks --jsn -C -v one_dmn_rec_var ~/nco/data/in.nc\n   ncks --jsn -C -m -v one_dmn_rec_var ~/nco/data/in_grp.nc\n   ncks -O -4 --ppc ppc_dbl=1 --ppc ppc_flt,ppc_big=4 ~/nco/data/in.nc ~/foo.nc\n   ncks -O --ppc ppc_dbl=1 --ppc '/g1/ppc.?',/g1/g1g1/ppc_dbl=4 ~/nco/data/in_grp.nc ~/foo.nc\n   ncks -O -m -M -v Snow_Cover_Monthly_CMG ${DATA}/hdf/MOD10CM.A2007001.005.2007108111758.hdf */\n\n#ifdef HAVE_CONFIG_H\n# include <config.h> /* Autotools tokens */\n#endif /* !HAVE_CONFIG_H */\n\n/* Standard C headers */\n#include <assert.h> /* assert() */\n#include <stdio.h> /* stderr, FILE, NULL, etc. */\n#include <stdlib.h> /* atof, atoi, malloc, getopt */\n#include <string.h> /* strcmp() */\n#include <sys/stat.h> /* stat() */\n#include <time.h> /* machine time */\n#ifndef _MSC_VER\n# include <unistd.h> /* POSIX stuff */\n#endif\n#ifndef HAVE_GETOPT_LONG\n# include \"nco_getopt.h\"\n#else /* HAVE_GETOPT_LONG */ \n# ifdef HAVE_GETOPT_H\n#  include <getopt.h>\n# endif /* !HAVE_GETOPT_H */ \n#endif /* HAVE_GETOPT_LONG */\n\n#ifdef I18N\n# include <langinfo.h> /* nl_langinfo() */\n# include <libintl.h> /* Internationalization i18n */\n# include <locale.h> /* Locale setlocale() */\n# define _(sng) gettext (sng)\n# define gettext_noop(sng) (sng)\n# define N_(sng) gettext_noop(sng)\n#endif /* I18N */\n/* Supply stub gettext() function in case i18n failed */\n#ifndef _LIBINTL_H\n# define gettext(foo) foo\n#endif /* _LIBINTL_H */\n\n/* 3rd party vendors */\n#include <netcdf.h> /* netCDF definitions and C library */\n#ifdef ENABLE_MPI\n# include <mpi.h> /* MPI definitions */\n# include <netcdf_par.h> /* Parallel netCDF definitions */\n# include \"nco_mpi.h\" /* MPI utilities */\n#endif /* !ENABLE_MPI */\n\n#ifdef ENABLE_GSL\n  #include <gsl/gsl_errno.h>\n#endif\n\n/* Personal headers */\n/* #define MAIN_PROGRAM_FILE MUST precede #include libnco.h */\n#define MAIN_PROGRAM_FILE\n#include \"libnco.h\" /* netCDF Operator (NCO) library */\n#include \"nco.h\"\n\nint \nmain(int argc,char **argv)\n{\n  char **fl_lst_abb=NULL; /* Option a */\n  char **fl_lst_in;\n  char **gaa_arg=NULL; /* [sng] Global attribute arguments */\n  char **grp_lst_in=NULL;\n  char **rgr_arg=NULL; /* [sng] Regridding arguments */\n  char **trr_arg=NULL; /* [sng] Terraref arguments */\n  char **var_lst_in=NULL;\n  char **xtn_lst_in=NULL; /* [sng] Extensive variables */\n  char *aux_arg[NC_MAX_DIMS];\n  char *cmd_ln;\n  char *cnk_arg[NC_MAX_DIMS];\n  char *cnk_map_sng=NULL_CEWI; /* [sng] Chunking map */\n  char *cnk_plc_sng=NULL_CEWI; /* [sng] Chunking policy */\n  char *dlm_sng=NULL;\n  char *fl_bnr=NULL; /* [sng] Unformatted binary output file */\n  char *fl_in=NULL;\n  char *fl_in_dpl=NULL; /* [sng] Duplicate of fl_in */\n  char *fl_in_stub=NULL; /* [sng] Filename component of fl_in */\n  char *fl_out=NULL; /* Option o */\n  char *fl_out_tmp=NULL_CEWI;\n  char *fl_prn=NULL; /* [sng] Formatted text output file */\n  char *fl_pth=NULL; /* Option p */\n  char *fl_pth_lcl=NULL; /* Option l */\n  char *flt_sng=NULL; /* [sng] Filter string */\n  char *fmt_val=NULL; /* [sng] Format string for variable values */\n  char *lmt_arg[NC_MAX_DIMS];\n  char *opt_crr=NULL; /* [sng] String representation of current long-option name */\n  char *optarg_lcl=NULL; /* [sng] Local copy of system optarg */\n  char *ppc_arg[NC_MAX_VARS]; /* [sng] PPC arguments */\n  char *rec_dmn_nm=NULL; /* [sng] Record dimension name */\n  char *rec_dmn_nm_fix=NULL; /* [sng] Record dimension name (Original input name without _fix prefix) */\n  char *rgr_in=NULL; /* [sng] File containing fields to be regridded */\n  char *rgr_grd_src=NULL; /* [sng] File containing input grid */\n  char *rgr_grd_dst=NULL; /* [sng] File containing destination grid */\n  char *rgr_hrz=NULL; /* [sng] File containing horizontal coordinate grid */\n  char *rgr_map=NULL; /* [sng] File containing mapping weights from source to destination grid */\n  char *rgr_out=NULL; /* [sng] File containing regridded fields */\n  char *rgr_var=NULL; /* [sng] Variable for special regridding treatment */\n  char *rgr_vrt=NULL; /* [sng] File containing vertical coordinate grid */\n  char *smr_fl_sz_sng=NULL; /* [sng] String describing estimated file size */\n  char *smr_sng=NULL; /* [sng] File summary string */\n  char *smr_xtn_sng=NULL; /* [sng] File extended summary string */\n  char *sng_cnv_rcd=NULL_CEWI; /* [sng] strtol()/strtoul() return code */\n  char *spr_chr=NULL; /* [sng] Separator for XML character types */\n  char *spr_nmr=NULL; /* [sng] Separator for XML numeric types */\n  char *trr_in=NULL; /* [sng] File containing raw Terraref imagery */\n  char *trr_wxy=NULL; /* [sng] Terraref dimension sizes */\n\n  char trv_pth[]=\"/\"; /* [sng] Root path of traversal tree */\n\n  const char * const CVS_Id=\"$Id$\"; \n  const char * const CVS_Revision=\"$Revision$\";\n  const char * const opt_sht_lst=\"34567aABb:CcD:d:FG:g:HhL:l:MmOo:Pp:qQrRs:t:uVv:X:xz-:\";\n\n  cnk_sct cnk; /* [sct] Chunking structure */\n\n#if defined(__cplusplus) || defined(PGI_CC)\n  ddra_info_sct ddra_info;\n  ddra_info.flg_ddra=False;\n#else /* !__cplusplus */\n  ddra_info_sct ddra_info={.flg_ddra=False};\n#endif /* !__cplusplus */\n\n  double wgt_vld_thr=NC_MIN_DOUBLE; /* [frc] Weight threshold for valid destination value */\n\n  extern char *optarg;\n  extern int optind;\n\n  FILE *fp_bnr=NULL; /* [fl] Unformatted binary output file handle */\n  FILE *fp_prn=NULL; /* [fl] Formatted text output file handle */\n\n  gpe_sct *gpe=NULL; /* [sng] Group Path Editing (GPE) structure */\n\n  int *in_id_arr; /* [id] netCDF file IDs used by OpenMP code */\n\n  int JSN_ATT_FMT=0; /* [enm] JSON format for netCDF attributes: 0 (no object, only data), 1 (data only for string, char, int, and floating-point types, otherwise object), 2 (always object) */\n  int JSN_VAR_FMT=2; /* [flg] JSON format for netCDF variables: 0 (no type except for user-defined types), 1 (type for non-default types), 2 (always type) */\n  nco_bool JSN_DATA_BRK=True; /* [flg] JSON format for netCDF variables: 0 (no brackets), 1 (bracket inner dimensions of multi-dimensional data) */\n\n  int abb_arg_nbr=0;\n  int att_glb_nbr;\n  int att_grp_nbr;\n  int att_var_nbr;\n  int aux_nbr=0; /* [nbr] Number of auxiliary coordinate hyperslabs specified */\n  int cnk_map=nco_cnk_map_nil; /* [enm] Chunking map */\n  int cnk_nbr=0; /* [nbr] Number of chunk sizes */\n  int cnk_plc=nco_cnk_plc_nil; /* [enm] Chunking policy */\n  int dfl_lvl=NCO_DFL_LVL_UNDEFINED; /* [enm] Deflate level */\n  int dmn_nbr_fl;\n  int dmn_rec_fl;\n  int dt_fmt=fmt_dt_nil;\n  int fl_in_fmt=NCO_FORMAT_UNDEFINED; /* [enm] Input file format */\n  int fl_nbr=0;\n  int fl_out_fmt=NCO_FORMAT_UNDEFINED; /* [enm] Output file format */\n  int fll_md_old; /* [enm] Old fill mode */\n  int gaa_nbr=0; /* [nbr] Number of global attributes to add */\n  int grp_dpt_fl; /* [nbr] Maximum group depth (root = 0) */\n  int grp_lst_in_nbr=0; /* [nbr] Number of groups explicitly specified by user */\n  int grp_nbr_fl;\n  int idx;\n  int in_id;  \n  int lmt_nbr=0; /* Option d. NB: lmt_nbr gets incremented */\n  int log_lvl=0; /* [enm] netCDF library debugging verbosity [0..5] */\n  int md_open; /* [enm] Mode flag for nc_open() call */\n  int opt;\n  int ppc_nbr=0; /* [nbr] Number of PPC arguments */\n  int rgr_nbr=0; /* [nbr] Number of regridding arguments */\n  int trr_nbr=0; /* [nbr] Number of TERRAREF arguments */\n  int rcd=NC_NOERR; /* [rcd] Return code */\n  int srt_mth=0; /* [enm] Sort method [0=ascending, 1=descending] */\n  int thr_idx; /* [idx] Index of current thread */\n  int thr_nbr=int_CEWI; /* [nbr] Thread number Option t */\n  int var_lst_in_nbr=0;\n  int var_nbr_fl;\n  int var_udt_fl;\n  int xtn_nbr=0; /* [nbr] Number of extensive variables */\n  int xtr_nbr=0; /* [nbr] xtr_nbr will not otherwise be set for -c with no -v */\n\n  md5_sct *md5=NULL; /* [sct] MD5 configuration */\n \n  nco_bool ALPHABETIZE_OUTPUT=True; /* Option a */\n  nco_bool CHK_MAP=False; /* [flg] Check map-file quality */\n  nco_bool CHK_NAN=False; /* [flg] Check for NaNs */\n  nco_bool CPY_GRP_METADATA; /* [flg] Copy group metadata (attributes) */\n  nco_bool EXCLUDE_INPUT_LIST=False; /* Option x */\n  nco_bool EXTRACT_ALL_COORDINATES=False; /* Option c */\n  nco_bool EXTRACT_ASSOCIATED_COORDINATES=True; /* Option C */\n  nco_bool EXTRACT_CLL_MSR=True; /* [flg] Extract cell_measures variables */\n  nco_bool EXTRACT_FRM_TRM=True; /* [flg] Extract formula_terms variables */\n  nco_bool FL_RTR_RMT_LCN;\n  nco_bool FL_LST_IN_FROM_STDIN=False; /* [flg] fl_lst_in comes from stdin */\n  nco_bool FORCE_APPEND=False; /* Option A */\n  nco_bool FORCE_NOCLOBBER=False; /* Option no-clobber */\n  nco_bool FORCE_OVERWRITE=False; /* Option O */\n  nco_bool FORTRAN_IDX_CNV=False; /* Option F */\n  nco_bool GRP_VAR_UNN=False; /* [flg] Select union of specified groups and variables */\n  nco_bool GRP_XTR_VAR_XCL=False; /* [flg] Extract matching groups, exclude matching variables */\n  nco_bool HAVE_LIMITS=False; /* [flg] Are there user limits? (-d) */\n  nco_bool HISTORY_APPEND=True; /* Option h */\n  nco_bool HPSS_TRY=False; /* [flg] Search HPSS for unfound files */\n  nco_bool LST_RNK_GE2=False; /* [flg] Print extraction list of rank >= 2 variables */\n  nco_bool LST_XTR=False; /* [flg] Print extraction list */\n  nco_bool MSA_USR_RDR=False; /* [flg] Multi-Slab Algorithm returns hyperslabs in user-specified order */\n  nco_bool PRN_CDL=False; /* [flg] Print CDL */\n  nco_bool PRN_HDN=False; /* [flg] Print hidden attributes */\n  nco_bool PRN_UDT=False; /* [flg] Print non-atomic variables */\n  nco_bool PRN_SRM=False; /* [flg] Print ncStream */\n  nco_bool PRN_JSN=False; /* [flg] Print JSON */\n  nco_bool PRN_TRD=False; /* [flg] Print traditional */\n  nco_bool PRN_XML=False; /* [flg] Print XML (NcML) */\n  nco_bool PRN_XML_LOCATION=True; /* [flg] Print XML location tag */\n  nco_bool PRN_DMN_IDX_CRD_VAL=True; /* [flg] Print leading dimension/coordinate indices/values Option Q */\n  nco_bool PRN_DMN_UNITS=True; /* [flg] Print dimensional units Option u */\n  nco_bool PRN_DMN_VAR_NM=True; /* [flg] Print dimension/variable names */\n  nco_bool PRN_DMN_UNITS_TGL=False; /* [flg] Toggle print dimensional units Option u */\n  nco_bool PRN_GLB_METADATA=False; /* [flg] Print global metadata */\n  nco_bool PRN_GLB_METADATA_TGL=False; /* [flg] Toggle print global metadata Option M */\n  nco_bool PRN_MSS_VAL_BLANK=True; /* [flg] Print missing values as blanks */\n  nco_bool PRN_QUENCH=False; /* [flg] Quench (turn-off) all printing to screen */\n  nco_bool PRN_VAR_DATA=False; /* [flg] Print variable data */\n  nco_bool PRN_VAR_DATA_TGL=False; /* [flg] Toggle print variable data Option H */\n  nco_bool PRN_VAR_METADATA=False; /* [flg] Print variable metadata */\n  nco_bool PRN_VAR_METADATA_TGL=False; /* [flg] Toggle print variable metadata Option m */\n  nco_bool PRN_CLN_LGB=False; /* [flg] Print UDUnits-formatted calendar dates/times human-legibly */\n  nco_bool PRN_VRB=False; /* [flg] Print data and metadata by default */\n  nco_bool RETAIN_ALL_DIMS=False; /* [flg] Retain all dimensions */\n  nco_bool RAM_CREATE=False; /* [flg] Create file in RAM */\n  nco_bool RAM_OPEN=False; /* [flg] Open (netCDF3-only) file(s) in RAM */\n  nco_bool SHARE_CREATE=False; /* [flg] Create (netCDF3-only) file(s) with unbuffered I/O */\n  nco_bool SHARE_OPEN=False; /* [flg] Open (netCDF3-only) file(s) with unbuffered I/O */\n  nco_bool RM_RMT_FL_PST_PRC=True; /* Option R */\n  nco_bool WRT_TMP_FL=True; /* [flg] Write output to temporary file */\n  nco_bool flg_area_wgt=False; /* [flg] Area-weight map-file statistics */\n  nco_bool flg_dmm_in=False; /* [flg] Make dummy input file */\n  nco_bool flg_frac_b_nrm=False; /* [flg] Normalize map-file weights when frac_b >> 1 */\n  nco_bool flg_mmr_cln=True; /* [flg] Clean memory prior to exit */\n  nco_bool flg_rgr=False; /* [flg] Regrid */\n  nco_bool flg_s1d=False; /* [flg] Unpack sparse-1D CLM/ELM variables */\n  nco_bool flg_trr=False; /* [flg] Terraref */\n\n  nco_dmn_dne_t *flg_dne=NULL; /* [lst] Flag to check if input dimension -d \"does not exist\" */\n\n  size_t bfr_sz_hnt=NC_SIZEHINT_DEFAULT; /* [B] Buffer size hint */\n  size_t cnk_csh_byt=NCO_CNK_CSH_BYT_DFL; /* [B] Chunk cache size */\n  size_t cnk_min_byt=NCO_CNK_SZ_MIN_BYT_DFL; /* [B] Minimize size of variable to chunk */\n  size_t cnk_sz_byt=0UL; /* [B] Chunk size in bytes */\n  size_t cnk_sz_scl=0UL; /* [nbr] Chunk size scalar */\n  size_t hdr_pad=0UL; /* [B] Pad at end of header section */\n\n  trv_tbl_sct *trv_tbl=NULL; /* [lst] Traversal table */\n\n#ifdef ENABLE_MPI\n  /* Declare all MPI-specific variables here */\n  MPI_Comm mpi_cmm=MPI_COMM_WORLD; /* [prc] Communicator */\n  int prc_rnk; /* [idx] Process rank */\n  int prc_nbr=0; /* [nbr] Number of MPI processes */\n#endif /* !ENABLE_MPI */\n  \n  static struct option opt_lng[]={ /* Structure ordered by short option key if possible */\n    /* Long options with no argument, no short option counterpart */\n    {\"area_wgt\",no_argument,0,0}, /* [flg] Area-weight map-file statistics */\n    {\"bld\",no_argument,0,0}, /* [sng] Build-engine */\n    {\"build_engine\",no_argument,0,0}, /* [sng] Build-engine */\n    {\"calendar\",no_argument,0,0}, /* [flg] Print UDUnits-formatted calendar dates/times human-legibly */\n    {\"cln_lgb\",no_argument,0,0}, /* [flg] Print UDUnits-formatted calendar dates/times human-legibly */\n    {\"prn_cln_lgb\",no_argument,0,0}, /* [flg] Print UDUnits-formatted calendar dates/times human-legibly */\n    {\"prn_lgb\",no_argument,0,0}, /* [flg] Print UDUnits-formatted calendar dates/times human-legibly */\n    {\"timestamp\",no_argument,0,0}, /* [flg] Print UDUnits-formatted calendar dates/times human-legibly */\n    {\"cdl\",no_argument,0,0}, /* [flg] Print CDL */\n    {\"cll_msr\",no_argument,0,0}, /* [flg] Extract cell_measures variables */\n    {\"cell_measures\",no_argument,0,0}, /* [flg] Extract cell_measures variables */\n    {\"no_cll_msr\",no_argument,0,0}, /* [flg] Do not extract cell_measures variables */\n    {\"no_cell_measures\",no_argument,0,0}, /* [flg] Do not extract cell_measures variables */\n    {\"frm_trm\",no_argument,0,0}, /* [flg] Extract formula_terms variables */\n    {\"formula_terms\",no_argument,0,0}, /* [flg] Extract formula_terms variables */\n    {\"no_frm_trm\",no_argument,0,0}, /* [flg] Do not extract formula_terms variables */\n    {\"no_formula_terms\",no_argument,0,0}, /* [flg] Do not extract formula_terms variables */\n    {\"chk_map\",no_argument,0,0}, /* [flg] Check map-file quality */\n    {\"check_map\",no_argument,0,0}, /* [flg] Check map-file quality */\n    {\"chk_nan\",no_argument,0,0}, /* [flg] Check file for NaNs */\n    {\"check_nan\",no_argument,0,0}, /* [flg] Check file for NaNs */\n    {\"nan\",no_argument,0,0}, /* [flg] Check file for NaNs */\n    {\"NaN\",no_argument,0,0}, /* [flg] Check file for NaNs */\n    {\"clean\",no_argument,0,0}, /* [flg] Clean memory prior to exit */\n    {\"mmr_cln\",no_argument,0,0}, /* [flg] Clean memory prior to exit */\n    {\"drt\",no_argument,0,0}, /* [flg] Allow dirty memory on exit */\n    {\"dirty\",no_argument,0,0}, /* [flg] Allow dirty memory on exit */\n    {\"mmr_drt\",no_argument,0,0}, /* [flg] Allow dirty memory on exit */\n    {\"cmp\",no_argument,0,0},\n    {\"compiler\",no_argument,0,0},\n    {\"copyright\",no_argument,0,0},\n    {\"cpy\",no_argument,0,0},\n    {\"dmm_in_mk\",no_argument,0,0}, /* [flg] Make dummy input file */\n    {\"fl_dmm\",no_argument,0,0}, /* [flg] Make dummy input file */\n    {\"license\",no_argument,0,0},\n    {\"hdf4\",no_argument,0,0}, /* [flg] Treat file as HDF4 */\n    {\"hdn\",no_argument,0,0}, /* [flg] Print hidden attributes */\n    {\"hidden\",no_argument,0,0}, /* [flg] Print hidden attributes */\n    {\"help\",no_argument,0,0},\n    {\"hlp\",no_argument,0,0},\n    {\"hpss_try\",no_argument,0,0}, /* [flg] Search HPSS for unfound files */\n    {\"id\",no_argument,0,0}, /* [flg] Print normally hidden information, like file, group, and variable IDs */\n    {\"lbr\",no_argument,0,0},\n    {\"library\",no_argument,0,0},\n    {\"lst_rnk_ge2\",no_argument,0,0}, /* [flg] Print extraction list of rank >= 2 variables */\n    {\"lst_xtr\",no_argument,0,0}, /* [flg] Print extraction list */\n    {\"frac_b_nrm\",no_argument,0,0}, /* [flg] Normalize map-file weights when frac_b >> 1 */\n    {\"md5_dgs\",no_argument,0,0}, /* [flg] Perform MD5 digests */\n    {\"md5_digest\",no_argument,0,0}, /* [flg] Perform MD5 digests */\n    {\"md5_wrt_att\",no_argument,0,0}, /* [flg] Write MD5 digests as attributes */\n    {\"md5_write_attribute\",no_argument,0,0}, /* [flg] Write MD5 digests as attributes */\n    {\"mpi_implementation\",no_argument,0,0},\n    {\"msa_usr_rdr\",no_argument,0,0}, /* [flg] Multi-Slab Algorithm returns hyperslabs in user-specified order */\n    {\"msa_user_order\",no_argument,0,0}, /* [flg] Multi-Slab Algorithm returns hyperslabs in user-specified order */\n    {\"no_abc\",no_argument,0,0},\n    {\"no-abc\",no_argument,0,0},\n    {\"no_alphabetize\",no_argument,0,0},\n    {\"no-alphabetize\",no_argument,0,0},\n    {\"no_blank\",no_argument,0,0}, /* [flg] Print numeric missing values */\n    {\"no-blank\",no_argument,0,0}, /* [flg] Print numeric missing values */\n    {\"noblank\",no_argument,0,0}, /* [flg] Print numeric missing values */\n    {\"no_clb\",no_argument,0,0},\n    {\"noclobber\",no_argument,0,0},\n    {\"no-clobber\",no_argument,0,0},\n    {\"no_clobber\",no_argument,0,0},\n    {\"no_dmn_var_nm\",no_argument,0,0}, /* [flg] Omit variable and dimension names and indices but print all values */\n    {\"no_nm_prn\",no_argument,0,0}, /* [flg] Omit variable and dimension names and indices but print all values */\n    {\"ntm\",no_argument,0,0}, /* [flg] Print non-atomic variables */\n    {\"nonatomic\",no_argument,0,0}, /* [flg] Print non-atomic variables */\n    {\"udt\",no_argument,0,0}, /* [flg] Print non-atomic variables */\n    {\"user_defined_types\",no_argument,0,0}, /* [flg] Print non-atomic variables */\n    {\"rad\",no_argument,0,0}, /* [flg] Retain all dimensions */\n    {\"retain_all_dimensions\",no_argument,0,0}, /* [flg] Retain all dimensions */\n    {\"orphan_dimensions\",no_argument,0,0}, /* [flg] Retain all dimensions */\n    {\"rph_dmn\",no_argument,0,0}, /* [flg] Retain all dimensions */\n    {\"ram_all\",no_argument,0,0}, /* [flg] Open and create (netCDF3) file(s) in RAM */\n    {\"create_ram\",no_argument,0,0}, /* [flg] Create file in RAM */\n    {\"open_ram\",no_argument,0,0}, /* [flg] Open (netCDF3) file(s) in RAM */\n    {\"diskless_all\",no_argument,0,0}, /* [flg] Open and create (netCDF3) file(s) in RAM */\n    {\"share_all\",no_argument,0,0}, /* [flg] Open and create (netCDF3) file(s) with unbuffered I/O */\n    {\"create_share\",no_argument,0,0}, /* [flg] Create (netCDF3) file(s) with unbuffered I/O */\n    {\"open_share\",no_argument,0,0}, /* [flg] Open (netCDF3) file(s) with unbuffered I/O */\n    {\"unbuffered_io\",no_argument,0,0}, /* [flg] Open and create (netCDF3) file(s) with unbuffered I/O */\n    {\"uio\",no_argument,0,0}, /* [flg] Open and create (netCDF3) file(s) with unbuffered I/O */\n    {\"secret\",no_argument,0,0},\n    {\"shh\",no_argument,0,0},\n    {\"srm\",no_argument,0,0}, /* [flg] Print ncStream */\n    {\"s1d\",no_argument,0,0}, /* [flg] Unpack sparse-1D CLM/ELM variables */\n    {\"sparse\",no_argument,0,0}, /* [flg] Unpack sparse-1D CLM/ELM variables */\n    {\"unpack_sparse\",no_argument,0,0}, /* [flg] Unpack sparse-1D CLM/ELM variables */\n    {\"sysconf\",no_argument,0,0}, /* [flg] Perform sysconf() test */\n    {\"wrt_tmp_fl\",no_argument,0,0}, /* [flg] Write output to temporary file */\n    {\"write_tmp_fl\",no_argument,0,0}, /* [flg] Write output to temporary file */\n    {\"no_tmp_fl\",no_argument,0,0}, /* [flg] Do not write output to temporary file */\n    {\"intersection\",no_argument,0,0}, /* [flg] Select intersection of specified groups and variables */\n    {\"nsx\",no_argument,0,0}, /* [flg] Select intersection of specified groups and variables */\n    {\"union\",no_argument,0,0}, /* [flg] Select union of specified groups and variables */\n    {\"unn\",no_argument,0,0}, /* [flg] Select union of specified groups and variables */\n    {\"grp_xtr_var_xcl\",no_argument,0,0}, /* [flg] Extract matching groups, exclude matching variables */\n    {\"version\",no_argument,0,0},\n    {\"vrs\",no_argument,0,0},\n    {\"jsn\",no_argument,0,0}, /* [flg] Print JSON */\n    {\"json\",no_argument,0,0}, /* [flg] Print JSON */\n    {\"trd\",no_argument,0,0}, /* [flg] Print traditional */\n    {\"traditional\",no_argument,0,0}, /* [flg] Print traditional */\n    {\"w10\",no_argument,0,0}, /* [flg] Print JSON */\n    {\"w10n\",no_argument,0,0}, /* [flg] Print JSON */\n    {\"xml\",no_argument,0,0}, /* [flg] Print XML (NcML) */\n    {\"ncml\",no_argument,0,0}, /* [flg] Print XML (NcML) */\n    {\"xml_no_location\",no_argument,0,0}, /* [flg] Omit XML location tag */\n    {\"ncml_no_location\",no_argument,0,0}, /* [flg] Omit XML location tag */\n    /* Long options with argument, no short option counterpart */\n    {\"baa\",required_argument,0,0}, /* [enm] Bit-Adjustment Algorithm */\n    {\"bit_alg\",required_argument,0,0}, /* [enm] Bit-Adjustment Algorithm */\n    {\"bfr_sz_hnt\",required_argument,0,0}, /* [B] Buffer size hint */\n    {\"buffer_size_hint\",required_argument,0,0}, /* [B] Buffer size hint */\n    {\"bsa\",required_argument,0,0}, /* [enm] Binary byte-swap algorithm */\n    {\"byte_swap\",required_argument,0,0}, /* [enm] Binary byte-swap algorithm */\n    {\"cnk_byt\",required_argument,0,0}, /* [B] Chunk size in bytes */\n    {\"chunk_byte\",required_argument,0,0}, /* [B] Chunk size in bytes */\n    {\"cnk_csh\",required_argument,0,0}, /* [B] Chunk cache size in bytes */\n    {\"chunk_cache\",required_argument,0,0}, /* [B] Chunk cache size in bytes */\n    {\"cnk_dmn\",required_argument,0,0}, /* [nbr] Chunk size */\n    {\"chunk_dimension\",required_argument,0,0}, /* [nbr] Chunk size */\n    {\"cnk_map\",required_argument,0,0}, /* [nbr] Chunking map */\n    {\"chunk_map\",required_argument,0,0}, /* [nbr] Chunking map */\n    {\"cnk_min\",required_argument,0,0}, /* [B] Minimize size of variable to chunk */\n    {\"chunk_min\",required_argument,0,0}, /* [B] Minimize size of variable to chunk */\n    {\"cnk_plc\",required_argument,0,0}, /* [nbr] Chunking policy */\n    {\"chunk_policy\",required_argument,0,0}, /* [nbr] Chunking policy */\n    {\"cnk_scl\",required_argument,0,0}, /* [nbr] Chunk size scalar */\n    {\"chunk_scalar\",required_argument,0,0}, /* [nbr] Chunk size scalar */\n    {\"dt_fmt\",required_argument,0,0}, /* [enm] Date format for CDL output with --cal */\n    {\"date_format\",required_argument,0,0}, /* [enm] Date format for CDL output with --cal */\n    {\"fl_fmt\",required_argument,0,0},\n    {\"file_format\",required_argument,0,0},\n    {\"fix_rec_dmn\",required_argument,0,0}, /* [sng] Fix record dimension */\n    {\"no_rec_dmn\",required_argument,0,0}, /* [sng] Fix record dimension */\n    {\"fl_prn\",required_argument,0,0}, /* [sng] Formatted text output file */\n    {\"file_print\",required_argument,0,0}, /* [sng] Formatted text output file */\n    {\"prn_fl\",required_argument,0,0}, /* [sng] Formatted text output file */\n    {\"print_file\",required_argument,0,0}, /* [sng] Formatted text output file */\n    {\"ccr\",required_argument,0,0}, /* [sng] CCR codec name */\n    {\"cdc\",required_argument,0,0}, /* [sng] CCR codec name */\n    {\"codec\",required_argument,0,0}, /* [sng] CCR codec name */\n    {\"flt\",required_argument,0,0}, /* [sng] Filter string */\n    {\"filter\",required_argument,0,0}, /* [sng] Filter string */\n    {\"fmt_val\",required_argument,0,0}, /* [sng] Format string for variable values */\n    {\"val_fmt\",required_argument,0,0}, /* [sng] Format string for variable values */\n    {\"value_format\",required_argument,0,0}, /* [sng] Format string for variable values */\n    {\"gaa\",required_argument,0,0}, /* [sng] Global attribute add */\n    {\"glb_att_add\",required_argument,0,0}, /* [sng] Global attribute add */\n    {\"hdr_pad\",required_argument,0,0},\n    {\"header_pad\",required_argument,0,0},\n    {\"jsn_fmt\",required_argument,0,0}, /* [enm] JSON format */\n    {\"jsn_format\",required_argument,0,0}, /* [enm] JSON format */\n    {\"json_fmt\",required_argument,0,0}, /* [enm] JSON format */\n    {\"json_format\",required_argument,0,0}, /* [enm] JSON format */\n    {\"log_lvl\",required_argument,0,0}, /* [enm] netCDF library debugging verbosity [0..5] */\n    {\"log_level\",required_argument,0,0}, /* [enm] netCDF library debugging verbosity [0..5] */\n    {\"mk_rec_dmn\",required_argument,0,0}, /* [sng] Name of record dimension in output */\n    {\"mk_rec_dim\",required_argument,0,0}, /* [sng] Name of record dimension in output */\n    {\"mta_dlm\",required_argument,0,0}, /* [sng] Multi-argument delimiter */\n    {\"dlm_mta\",required_argument,0,0}, /* [sng] Multi-argument delimiter */\n    {\"ppc\",required_argument,0,0}, /* [nbr] Precision-preserving compression, i.e., number of total or decimal significant digits */\n    {\"precision_preserving_compression\",required_argument,0,0}, /* [nbr] Precision-preserving compression, i.e., number of total or decimal significant digits */\n    {\"quantize\",required_argument,0,0}, /* [nbr] Precision-preserving compression, i.e., number of total or decimal significant digits */\n    {\"rgr\",required_argument,0,0}, /* [sng] Regridding */\n    {\"regridding\",required_argument,0,0}, /* [sng] Regridding */\n    {\"rgr_in\",required_argument,0,0}, /* [sng] File containing fields to be regridded */\n    {\"rgr_grd_src\",required_argument,0,0}, /* [sng] File containing input grid */\n    {\"grd_src\",required_argument,0,0}, /* [sng] File containing input grid */\n    {\"src_grd\",required_argument,0,0}, /* [sng] File containing input grid */\n    {\"rgr_grd_dst\",required_argument,0,0}, /* [sng] File containing destination grid */\n    {\"dst_grd\",required_argument,0,0}, /* [sng] File containing destination grid */\n    {\"grd_dst\",required_argument,0,0}, /* [sng] File containing destination grid */\n    {\"rgr_map\",required_argument,0,0}, /* [sng] File containing mapping weights from source to destination grid */\n    {\"map_file\",required_argument,0,0}, /* [sng] File containing mapping weights from source to destination grid */\n    {\"map_fl\",required_argument,0,0}, /* [sng] File containing mapping weights from source to destination grid */\n    {\"rgr_hrz\",required_argument,0,0}, /* [sng] File containing horizontal coordinate grid */\n    {\"hrz_fl\",required_argument,0,0}, /* [sng] File containing horizontal coordinate grid */\n    {\"hrz_crd\",required_argument,0,0}, /* [sng] File containing horizontal coordinate grid */\n    {\"rgr_rnr\",required_argument,0,0}, /* [flg] Renormalize destination values by valid area */\n    {\"rgr_var\",required_argument,0,0}, /* I [sng] Variable for special regridding treatment */\n    {\"rgr_vrt\",required_argument,0,0}, /* [sng] File containing vertical coordinate grid */\n    {\"vrt_fl\",required_argument,0,0}, /* [sng] File containing vertical coordinate grid */\n    {\"vrt_crd\",required_argument,0,0}, /* [sng] File containing vertical coordinate grid */\n    {\"rnr_thr\",required_argument,0,0}, /* [flg] Renormalize destination values by valid area */\n    {\"renormalize\",required_argument,0,0}, /* [flg] Renormalize destination values by valid area */\n    {\"renormalization_threshold\",required_argument,0,0}, /* [flg] Renormalize destination values by valid area */\n    {\"trr\",required_argument,0,0}, /* [sng] Terraref */\n    {\"terraref\",required_argument,0,0}, /* [sng] Terraref */\n    {\"trr_in\",required_argument,0,0}, /* [sng] File containing raw Terraref imagery */\n    {\"trr_wxy\",required_argument,0,0}, /* [sng] Terraref dimension sizes */\n    {\"tst_udunits\",required_argument,0,0},\n    {\"xml_spr_chr\",required_argument,0,0}, /* [flg] Separator for XML character types */\n    {\"xml_spr_nmr\",required_argument,0,0}, /* [flg] Separator for XML numeric types */\n    {\"xtn_var_lst\",required_argument,0,0}, /* [sng] Extensive variables */\n    {\"extensive\",required_argument,0,0}, /* [sng] Extensive variables */\n    /* Long options with short counterparts */\n    {\"3\",no_argument,0,'3'},\n    {\"4\",no_argument,0,'4'},\n    {\"netcdf4\",no_argument,0,'4'},\n    {\"5\",no_argument,0,'5'},\n    {\"64bit_data\",no_argument,0,'5'},\n    {\"cdf5\",no_argument,0,'5'},\n    {\"pnetcdf\",no_argument,0,'5'},\n    {\"64bit_offset\",no_argument,0,'6'},\n    {\"7\",no_argument,0,'7'},\n    {\"abc\",no_argument,0,'a'},\n    {\"alphabetize\",no_argument,0,'a'},\n    {\"append\",no_argument,0,'A'},\n    {\"apn\",no_argument,0,'A'},\n    {\"bnr\",required_argument,0,'b'},\n    {\"binary\",required_argument,0,'b'},\n    {\"binary-file\",required_argument,0,'b'},\n    {\"fl_bnr\",required_argument,0,'b'},\n    {\"coords\",no_argument,0,'c'},\n    {\"crd\",no_argument,0,'c'},\n    {\"xtr_ass_var\",no_argument,0,'c'},\n    {\"xcl_ass_var\",no_argument,0,'C'},\n    {\"no_coords\",no_argument,0,'C'},\n    {\"no_crd\",no_argument,0,'C'},\n    {\"data\",required_argument,0,'H'},\n    {\"dbg_lvl\",required_argument,0,'D'},\n    {\"debug\",required_argument,0,'D'},\n    {\"nco_dbg_lvl\",required_argument,0,'D'},\n    {\"dimension\",required_argument,0,'d'},\n    {\"dmn\",required_argument,0,'d'},\n    {\"fortran\",no_argument,0,'F'},\n    {\"ftn\",no_argument,0,'F'},\n    {\"gpe\",required_argument,0,'G'}, /* [sng] Group Path Edit (GPE) */\n    {\"grp\",required_argument,0,'g'},\n    {\"group\",required_argument,0,'g'},\n    {\"history\",no_argument,0,'h'},\n    {\"hst\",no_argument,0,'h'},\n    {\"hieronymus\",no_argument,0,'H'}, /* fxm: need better mnemonic for -H */\n    {\"dfl_lvl\",required_argument,0,'L'}, /* [enm] Deflate level */\n    {\"deflate\",required_argument,0,'L'}, /* [enm] Deflate level */\n    {\"lcl\",required_argument,0,'l'},\n    {\"local\",required_argument,0,'l'},\n    {\"metadata\",no_argument,0,'m'},\n    {\"mtd_lcl\",no_argument,0,'m'},\n    {\"metadata_local\",no_argument,0,'m'},\n    {\"Metadata\",no_argument,0,'M'},\n    {\"Mtd\",no_argument,0,'M'},\n    {\"mtd_glb\",no_argument,0,'M'},\n    {\"metadata_global\",no_argument,0,'M'},\n    {\"overwrite\",no_argument,0,'O'},\n    {\"ovr\",no_argument,0,'O'},\n    {\"output\",required_argument,0,'o'},\n    {\"fl_out\",required_argument,0,'o'},\n    {\"print\",required_argument,0,'P'},\n    {\"prn\",required_argument,0,'P'},\n    {\"path\",required_argument,0,'p'},\n    {\"quench\",no_argument,0,'q'},\n    {\"quiet\",no_argument,0,'Q'},\n    {\"retain\",no_argument,0,'R'},\n    {\"rtn\",no_argument,0,'R'},\n    {\"revision\",no_argument,0,'r'},\n    {\"spinlock\",no_argument,0,'S'}, /* [flg] Suspend with signal handler to facilitate debugging */\n    {\"sng_fmt\",required_argument,0,'s'},\n    {\"string\",required_argument,0,'s'},\n    {\"thr_nbr\",required_argument,0,'t'},\n    {\"threads\",required_argument,0,'t'},\n    {\"omp_num_threads\",required_argument,0,'t'},\n    {\"units\",no_argument,0,'u'},\n    {\"val_var\",no_argument,0,'V'}, /* [flg] Print variable values only */\n    {\"variable\",required_argument,0,'v'},\n    {\"auxiliary\",required_argument,0,'X'},\n    {\"exclude\",no_argument,0,'x'},\n    {\"xcl\",no_argument,0,'x'},\n    {\"lbr_rcd\",no_argument,0,0},\n    {0,0,0,0}\n  }; /* end opt_lng */\n  int opt_idx=0; /* Index of current long option into opt_lng array */\n  \n#ifdef _LIBINTL_H\n  setlocale(LC_ALL,\"\"); /* LC_ALL sets all localization tokens to same value */\n  bindtextdomain(\"nco\",\"/home/zender/share/locale\"); /* ${LOCALEDIR} is e.g., /usr/share/locale */\n  /* MO files should be in ${LOCALEDIR}/es/LC_MESSAGES */\n  textdomain(\"nco\"); /* PACKAGE is name of program or library */\n#endif /* not _LIBINTL_H */\n  \n  /* Start timer and save command line */ \n  ddra_info.tmr_flg=nco_tmr_srt;\n  rcd+=nco_ddra((char *)NULL,(char *)NULL,&ddra_info);\n  ddra_info.tmr_flg=nco_tmr_mtd;\n  cmd_ln=nco_cmd_ln_sng(argc,argv);\n  \n  /* Get program name and set program enum (e.g., nco_prg_id=ncra) */\n  nco_prg_nm=nco_prg_prs(argv[0],&nco_prg_id);\n  \n  /* MPI I/O: Either Parallel netCDF (PnetCDF) or HDF5-based\n     export NETCDF_ROOT=/usr/local/parallel;export NETCDF_INC=/usr/local/parallel/include;export NETCDF_LIB=/usr/local/parallel/lib;export NETCDF4_ROOT=/usr/local/parallel;\n     cd ~/nco/bld;make MPI=Y;cd -\n     LD_LIBRARY_PATH=/usr/local/parallel/lib\\:${LD_LIBRARY_PATH}\n     ldd `which ncks`\n     ncks -O -5 ~/nco/data/in.nc ~/foo.nc # PnetCDF \n     mpiexec -n 1 ncks -O -4 ~/nco/data/in.nc ~/foo.nc # HDF5\n     od -An -c -N4 ~/foo.nc */\n#ifdef ENABLE_MPI\n  /* MPI Initialization */\n  if(False) (void)fprintf(stdout,gettext(\"%s: WARNING Compiled with MPI\\n\"),nco_prg_nm);\n  MPI_Init(&argc,&argv);\n  MPI_Comm_size(mpi_cmm,&prc_nbr);\n  MPI_Comm_rank(mpi_cmm,&prc_rnk);\n#endif /* !ENABLE_MPI */\n\n  /* Parse command line arguments */\n  while(1){\n    /* getopt_long_only() allows one dash to prefix long options */\n    opt=getopt_long(argc,argv,opt_sht_lst,opt_lng,&opt_idx);\n    /* NB: access to opt_crr is only valid when long_opt is detected */\n    if(opt == EOF) break; /* Parse positional arguments once getopt_long() returns EOF */\n    opt_crr=(char *)strdup(opt_lng[opt_idx].name);\n\n    /* Process long options without short option counterparts */\n    if(opt == 0){\n      if(!strcmp(opt_crr,\"baa\") || !strcmp(opt_crr,\"bit_alg\")){\n\tnco_baa_cnv=(unsigned short int)strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10);\n\tif(*sng_cnv_rcd) nco_sng_cnv_err(optarg,\"strtoul\",sng_cnv_rcd);\n      } /* endif baa */\n      if(!strcmp(opt_crr,\"bfr_sz_hnt\") || !strcmp(opt_crr,\"buffer_size_hint\")){\n        bfr_sz_hnt=strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10);\n        if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,\"strtoul\",sng_cnv_rcd);\n      } /* endif bfr_sz */\n      if(!strcmp(opt_crr,\"bsa\") || !strcmp(opt_crr,\"byte_swap\")){\n\tnco_bnr_cnv=(unsigned short int)strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10);\n\tif(*sng_cnv_rcd) nco_sng_cnv_err(optarg,\"strtoul\",sng_cnv_rcd);\n      } /* endif bnr */\n      if(!strcmp(opt_crr,\"bld\") || !strcmp(opt_crr,\"build_engine\")){\n\tconst char bld_ngn[]=TKN2SNG(NCO_BUILDENGINE); // [sng] Build-engine\n        (void)fprintf(stdout,\"%s\\n\",bld_ngn);\n        nco_exit(EXIT_SUCCESS);\n      } /* endif \"bld\" */\n      if(!strcmp(opt_crr,\"dt_fmt\") || !strcmp(opt_crr,\"date_format\")){\n        dt_fmt=strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10);\n      } /* !dt_fmt */\n      if(!strcmp(opt_crr,\"calendar\") || !strcmp(opt_crr,\"cln_lgb\") || !strcmp(opt_crr,\"prn_cln_lgb\") || !strcmp(opt_crr,\"prn_lgb\") || !strcmp(opt_crr,\"timestamp\")) PRN_CLN_LGB=True; /* [flg] Print UDUnits-formatted calendar dates/times human-legibly */\n      if(!strcmp(opt_crr,\"chk_map\") || !strcmp(opt_crr,\"check_map\")) CHK_MAP=True; /* [flg] Check map-file quality */\n      if(!strcmp(opt_crr,\"chk_nan\") || !strcmp(opt_crr,\"check_nan\") || !strcmp(opt_crr,\"nan\") || !strcmp(opt_crr,\"NaN\")) CHK_NAN=True; /* [flg] Check for NaNs */\n      if(!strcmp(opt_crr,\"cnk_byt\") || !strcmp(opt_crr,\"chunk_byte\")){\n        cnk_sz_byt=strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10);\n        if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,\"strtoul\",sng_cnv_rcd);\n      } /* endif cnk_byt */\n      if(!strcmp(opt_crr,\"cnk_csh\") || !strcmp(opt_crr,\"chunk_cache\")){\n        cnk_csh_byt=strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10);\n        if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,\"strtoul\",sng_cnv_rcd);\n      } /* endif cnk_csh */\n      if(!strcmp(opt_crr,\"cnk_min\") || !strcmp(opt_crr,\"chunk_min\")){\n        cnk_min_byt=strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10);\n        if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,\"strtoul\",sng_cnv_rcd);\n      } /* endif cnk_min */\n      if(!strcmp(opt_crr,\"cnk_dmn\") || !strcmp(opt_crr,\"chunk_dimension\")){\n        /* Copy limit argument for later processing */\n        cnk_arg[cnk_nbr]=(char *)strdup(optarg);\n        cnk_nbr++;\n      } /* endif cnk_dmn */\n      if(!strcmp(opt_crr,\"cnk_scl\") || !strcmp(opt_crr,\"chunk_scalar\")){\n        cnk_sz_scl=strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10);\n        if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,\"strtoul\",sng_cnv_rcd);\n      } /* endif cnk_scl */\n      if(!strcmp(opt_crr,\"cnk_map\") || !strcmp(opt_crr,\"chunk_map\")){\n        /* Chunking map */\n        cnk_map_sng=(char *)strdup(optarg);\n        cnk_map=nco_cnk_map_get(cnk_map_sng);\n      } /* endif cnk_map */\n      if(!strcmp(opt_crr,\"cnk_plc\") || !strcmp(opt_crr,\"chunk_policy\")){\n        /* Chunking policy */\n        cnk_plc_sng=(char *)strdup(optarg);\n        cnk_plc=nco_cnk_plc_get(cnk_plc_sng);\n      } /* endif cnk_plc */\n      if(!strcmp(opt_crr,\"cll_msr\") || !strcmp(opt_crr,\"cell_measures\")) EXTRACT_CLL_MSR=True; /* [flg] Extract cell_measures variables */\n      if(!strcmp(opt_crr,\"no_cll_msr\") || !strcmp(opt_crr,\"no_cell_measures\")) EXTRACT_CLL_MSR=False; /* [flg] Do not extract cell_measures variables */\n      if(!strcmp(opt_crr,\"frm_trm\") || !strcmp(opt_crr,\"formula_terms\")) EXTRACT_FRM_TRM=True; /* [flg] Extract formula_terms variables */\n      if(!strcmp(opt_crr,\"no_frm_trm\") || !strcmp(opt_crr,\"no_formula_terms\")) EXTRACT_FRM_TRM=False; /* [flg] Do not extract formula_terms variables */\n      if(!strcmp(opt_crr,\"cmp\") || !strcmp(opt_crr,\"compiler\")){\n        (void)fprintf(stdout,\"%s\\n\",nco_cmp_get());\n        nco_exit(EXIT_SUCCESS);\n      } /* endif \"cmp\" */\n      if(!strcmp(opt_crr,\"cpy\") || !strcmp(opt_crr,\"copyright\") || !strcmp(opt_crr,\"license\")){\n\t(void)nco_cpy_prn();\n        nco_exit(EXIT_SUCCESS);\n      } /* endif \"copyright\" */\n      if(!strcmp(opt_crr,\"cdl\")) PRN_CDL=True; /* [flg] Print CDL */\n      if(!strcmp(opt_crr,\"trd\") || !strcmp(opt_crr,\"traditional\")) PRN_TRD=True; /* [flg] Print traditional */\n      if(!strcmp(opt_crr,\"mmr_cln\") || !strcmp(opt_crr,\"clean\")) flg_mmr_cln=True; /* [flg] Clean memory prior to exit */\n      if(!strcmp(opt_crr,\"drt\") || !strcmp(opt_crr,\"mmr_drt\") || !strcmp(opt_crr,\"dirty\")) flg_mmr_cln=False; /* [flg] Clean memory prior to exit */\n      if(!strcmp(opt_crr,\"dmm_in_mk\") || !strcmp(opt_crr,\"fl_dmm\")) flg_dmm_in=True; /* [flg] Make dummy input file */\n      if(!strcmp(opt_crr,\"fix_rec_dmn\") || !strcmp(opt_crr,\"no_rec_dmn\")){\n        const char fix_pfx[]=\"fix_\"; /* [sng] Prefix string to fix dimension */\n        rec_dmn_nm=(char *)nco_malloc((strlen(fix_pfx)+strlen(optarg)+1L)*sizeof(char));\n        rec_dmn_nm=strcpy(rec_dmn_nm,fix_pfx);\n        rec_dmn_nm=strcat(rec_dmn_nm,optarg);\n        rec_dmn_nm_fix=strdup(optarg);\n      } /* !fix_rec_dmn */\n      if(!strcmp(opt_crr,\"fl_fmt\") || !strcmp(opt_crr,\"file_format\")) rcd=nco_create_mode_prs(optarg,&fl_out_fmt);\n      if(!strcmp(opt_crr,\"fl_prn\") || !strcmp(opt_crr,\"file_print\") || !strcmp(opt_crr,\"prn_fl\") || !strcmp(opt_crr,\"print_file\")) fl_prn=(char *)strdup(optarg);\n      if(!strcmp(opt_crr,\"flt\") || !strcmp(opt_crr,\"filter\")){\n\tflt_sng=(char *)strdup(optarg);\n\t/* [fnc] Parse filter string and exit */\n\tif(flt_sng) nco_flt_prs(flt_sng);\n      } /* !flt */\n      if(!strcmp(opt_crr,\"ccr\") || !strcmp(opt_crr,\"cdc\") || !strcmp(opt_crr,\"codec\")){\n\tnco_flt_glb=nco_flt_sng2enm(optarg);\n\t(void)fprintf(stdout,\"%s: INFO %s reports user-specified filter string translates to CCR string \\\"%s\\\"<.\\n\",nco_prg_nm,nco_prg_nm,nco_flt_enm2sng((nco_flt_typ_enm)nco_flt_glb_get()));\n\tnco_exit(EXIT_SUCCESS);\n      } /* !ccr */\n      if(!strcmp(opt_crr,\"fmt_val\") || !strcmp(opt_crr,\"val_fmt\") || !strcmp(opt_crr,\"value_format\")) fmt_val=(char *)strdup(optarg);\n      if(!strcmp(opt_crr,\"gaa\") || !strcmp(opt_crr,\"glb_att_add\")){\n        gaa_arg=(char **)nco_realloc(gaa_arg,(gaa_nbr+1)*sizeof(char *));\n        gaa_arg[gaa_nbr++]=(char *)strdup(optarg);\n      } /* !gaa */\n      if(!strcmp(opt_crr,\"hdf4\")) nco_fmt_xtn=nco_fmt_xtn_hdf4; /* [enm] Treat file as HDF4 */\n      if(!strcmp(opt_crr,\"hdn\") || !strcmp(opt_crr,\"hidden\")) PRN_HDN=True; /* [flg] Print hidden attributes */\n      if(!strcmp(opt_crr,\"hdr_pad\") || !strcmp(opt_crr,\"header_pad\")){\n        hdr_pad=strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10);\n        if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,\"strtoul\",sng_cnv_rcd);\n      } /* endif \"hdr_pad\" */\n      if(!strcmp(opt_crr,\"help\") || !strcmp(opt_crr,\"hlp\")){\n\t(void)nco_usg_prn();\n\tnco_exit(EXIT_SUCCESS);\n      } /* endif \"help\" */\n      if(!strcmp(opt_crr,\"hpss_try\")) HPSS_TRY=True; /* [flg] Search HPSS for unfound files */\n      if(!strcmp(opt_crr,\"lbr\") || !strcmp(opt_crr,\"library\")){\n        (void)nco_lbr_vrs_prn();\n        nco_exit(EXIT_SUCCESS);\n      } /* endif \"lbr\" */\n      if(!strcmp(opt_crr,\"lbr_rcd\")) nco_exit_lbr_rcd();\n      if(!strcmp(opt_crr,\"log_lvl\") || !strcmp(opt_crr,\"log_level\")){\n\tlog_lvl=(int)strtol(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10);\n\tif(*sng_cnv_rcd) nco_sng_cnv_err(optarg,\"strtol\",sng_cnv_rcd);\n\tnc_set_log_level(log_lvl);\n      } /* !log_lvl */\n      if(!strcmp(opt_crr,\"lst_rnk_ge2\") || !strcmp(opt_crr,\"rank_ge2\"))\tLST_RNK_GE2=True; /* [flg] Print extraction list of rank >= 2 variables */\n      if(!strcmp(opt_crr,\"lst_xtr\") || !strcmp(opt_crr,\"xtr_lst\")) LST_XTR=True; /* [flg] Print extraction list */\n      if(!strcmp(opt_crr,\"mk_rec_dmn\") || !strcmp(opt_crr,\"mk_rec_dim\")){\n\tif(strchr(optarg,',')){\n\t  (void)fprintf(stdout,\"%s: ERROR record dimension name %s contains a comma and appears to be a list\\n\",nco_prg_nm_get(),optarg);\n\t  (void)fprintf(stdout,\"%s: HINT --mk_rec_dmn currently accepts only one dimension name as an argument (relaxing this limit is TODO nco1129, let us know if this is important to you). To change multiple dimensions into record dimensions, run ncks multiple times and change one dimension each time. Be sure the output file format is netCDF4.\\n\",nco_prg_nm_get());\n\t  nco_exit(EXIT_FAILURE);\n\t} /* endif */\n\trec_dmn_nm=strdup(optarg);\n      } /* !mk_rec_dmn */\n      if(!strcmp(opt_crr,\"mpi_implementation\")){\n        (void)fprintf(stdout,\"%s\\n\",nco_mpi_get());\n        nco_exit(EXIT_SUCCESS);\n      } /* endif \"mpi\" */\n      if(!strcmp(opt_crr,\"md5_dgs\") || !strcmp(opt_crr,\"md5_digest\")){\n        if(!md5) md5=nco_md5_ini();\n\tmd5->dgs=True;\n        if(nco_dbg_lvl >= nco_dbg_std) (void)fprintf(stderr,\"%s: INFO Will perform MD5 digests of input and output hyperslabs\\n\",nco_prg_nm_get());\n      } /* endif \"md5_dgs\" */\n      if(!strcmp(opt_crr,\"md5_wrt_att\") || !strcmp(opt_crr,\"md5_write_attribute\")){\n        if(!md5) md5=nco_md5_ini();\n\tmd5->wrt=md5->dgs=True;\n        if(nco_dbg_lvl >= nco_dbg_fl) (void)fprintf(stderr,\"%s: INFO Will write MD5 digests as attributes\\n\",nco_prg_nm_get());\n      } /* endif \"md5_wrt_att\" */\n      if(!strcmp(opt_crr,\"msa_usr_rdr\") || !strcmp(opt_crr,\"msa_user_order\")) MSA_USR_RDR=True; /* [flg] Multi-Slab Algorithm returns hyperslabs in user-specified order */\n      if(!strcmp(opt_crr,\"mta_dlm\") || !strcmp(opt_crr,\"dlm_mta\")) nco_mta_dlm_set(optarg);\n      if(!strcmp(opt_crr,\"no_abc\") || !strcmp(opt_crr,\"no-abc\") || !strcmp(opt_crr,\"no_alphabetize\") || !strcmp(opt_crr,\"no-alphabetize\")) ALPHABETIZE_OUTPUT=False;\n      if(!strcmp(opt_crr,\"no_blank\") || !strcmp(opt_crr,\"no-blank\") || !strcmp(opt_crr,\"noblank\")) PRN_MSS_VAL_BLANK=!PRN_MSS_VAL_BLANK;\n      if(!strcmp(opt_crr,\"no_clb\") || !strcmp(opt_crr,\"no-clobber\") || !strcmp(opt_crr,\"no_clobber\") || !strcmp(opt_crr,\"noclobber\")) FORCE_NOCLOBBER=!FORCE_NOCLOBBER;\n      if(!strcmp(opt_crr,\"no_nm_prn\") || !strcmp(opt_crr,\"no_dmn_var_nm\")) PRN_DMN_VAR_NM=False; /* endif \"no_nm_prn\" */\n      if(!strcmp(opt_crr,\"ntm\") || !strcmp(opt_crr,\"nonatomic\") || !strcmp(opt_crr,\"udt\") || !strcmp(opt_crr,\"user_defined_types\")) PRN_UDT=True; /* [flg] Print non-atomic variables */\n      if(!strcmp(opt_crr,\"ppc\") || !strcmp(opt_crr,\"precision_preserving_compression\") || !strcmp(opt_crr,\"quantize\")) ppc_arg[ppc_nbr++]=(char *)strdup(optarg);\n      if(!strcmp(opt_crr,\"rad\") || !strcmp(opt_crr,\"retain_all_dimensions\") || !strcmp(opt_crr,\"orphan_dimensions\") || !strcmp(opt_crr,\"rph_dmn\")) RETAIN_ALL_DIMS=True;\n      if(!strcmp(opt_crr,\"ram_all\") || !strcmp(opt_crr,\"create_ram\") || !strcmp(opt_crr,\"diskless_all\")) RAM_CREATE=True; /* [flg] Create (netCDF3) file(s) in RAM */\n      if(!strcmp(opt_crr,\"ram_all\") || !strcmp(opt_crr,\"open_ram\") || !strcmp(opt_crr,\"diskless_all\")) RAM_OPEN=True; /* [flg] Open (netCDF3) file(s) in RAM */\n      if(!strcmp(opt_crr,\"share_all\") || !strcmp(opt_crr,\"unbuffered_io\") || !strcmp(opt_crr,\"uio\") || !strcmp(opt_crr,\"create_share\")) SHARE_CREATE=True; /* [flg] Create (netCDF3) file(s) with unbuffered I/O */\n      if(!strcmp(opt_crr,\"share_all\") || !strcmp(opt_crr,\"unbuffered_io\") || !strcmp(opt_crr,\"uio\") || !strcmp(opt_crr,\"open_share\")) SHARE_OPEN=True; /* [flg] Open (netCDF3) file(s) with unbuffered I/O */\n      if(!strcmp(opt_crr,\"area_wgt\") || !strcmp(opt_crr,\"area_weight\")){\n\tflg_area_wgt=True;\n\tCHK_MAP=True;\n      } /* !area_wgt */\n      if(!strcmp(opt_crr,\"frac_b_nrm\")){\n\tflg_frac_b_nrm=True;\n\tCHK_MAP=True;\n      } /* !frac_b_nrm */\n      if(!strcmp(opt_crr,\"rgr\") || !strcmp(opt_crr,\"regridding\")){\n        flg_rgr=True;\n        rgr_arg=(char **)nco_realloc(rgr_arg,(rgr_nbr+1)*sizeof(char *));\n        rgr_arg[rgr_nbr++]=(char *)strdup(optarg);\n      } /* endif \"rgr\" */\n      if(!strcmp(opt_crr,\"rgr_in\")) rgr_in=(char *)strdup(optarg);\n      if(!strcmp(opt_crr,\"rgr_grd_src\") || !strcmp(opt_crr,\"grd_src\") || !strcmp(opt_crr,\"src_grd\")) rgr_grd_src=(char *)strdup(optarg);\n      if(!strcmp(opt_crr,\"rgr_grd_dst\") || !strcmp(opt_crr,\"grd_dst\") || !strcmp(opt_crr,\"dst_grd\")) rgr_grd_dst=(char *)strdup(optarg);\n      if(!strcmp(opt_crr,\"rgr_map\") || !strcmp(opt_crr,\"map_file\") || !strcmp(opt_crr,\"map_fl\")){\n        flg_rgr=True;\n\trgr_map=(char *)strdup(optarg);\n      } /* endif rgr_map */\n      if(!strcmp(opt_crr,\"hrz_fl\") || !strcmp(opt_crr,\"hrz_crd\") || !strcmp(opt_crr,\"rgr_hrz\")){\n\tflg_s1d=flg_rgr=True;\n\trgr_hrz=(char *)strdup(optarg);\n      } /* !vrt_fl */\n      if(!strcmp(opt_crr,\"vrt_fl\") || !strcmp(opt_crr,\"vrt_crd\") || !strcmp(opt_crr,\"rgr_vrt\")){\n        flg_rgr=True;\n\trgr_vrt=(char *)strdup(optarg);\n      } /* !vrt_fl */\n      if(!strcmp(opt_crr,\"rnr_thr\") || !strcmp(opt_crr,\"rgr_rnr\") || !strcmp(opt_crr,\"renormalize\") || !strcmp(opt_crr,\"renormalization_threshold\")){\n        wgt_vld_thr=strtod(optarg,&sng_cnv_rcd);\n        if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,\"strtod\",sng_cnv_rcd);\n      } /* endif rgr_rnr */\n      if(!strcmp(opt_crr,\"rgr_var\")){\n        flg_rgr=True;\n\trgr_var=(char *)strdup(optarg);\n      } /* !rgr_var */\n      if(!strcmp(opt_crr,\"secret\") || !strcmp(opt_crr,\"scr\") || !strcmp(opt_crr,\"shh\")){\n        (void)fprintf(stdout,\"Hidden/unsupported NCO options:\\nBit-Adjustment Alg.\\t--baa, --bit_alg\\nBuild-engine\\t\\t--bld, --build_engine\\nByte-swap algorithm\\t--bsa, --byte_swap\\nCompiler used\\t\\t--cmp, --compiler\\nCopyright\\t\\t--cpy, --copyright, --license\\nHidden functions\\t--scr, --shh, --secret\\nLibrary used\\t\\t--lbr, --library\\nLog level\\t\\t--log_lvl, --log_level\\nList rank >= 2 vars\\t--lst_rnk_ge2\\nList extracted vars\\t--lst_xtr\\nMemory clean\\t\\t--mmr_cln, --cln, --clean\\nMemory dirty\\t\\t--mmr_drt, --drt, --dirty\\nMPI implementation\\t--mpi_implementation\\nNo-clobber files\\t--no_clb, --no-clobber\\nPseudonym\\t\\t--pseudonym, -Y (ncra only)\\nSpinlock\\t\\t--spinlock\\nStreams\\t\\t\\t--srm\\nSysconf\\t\\t\\t--sysconf\\nTest UDUnits\\t\\t--tst_udunits,'units_in','units_out','cln_sng'? \\nVersion\\t\\t\\t--vrs, --version\\n\\n\");\n        nco_exit(EXIT_SUCCESS);\n      } /* endif \"shh\" */\n      if(!strcmp(opt_crr,\"srm\")) PRN_SRM=True; /* [flg] Print ncStream */\n      if(!strcmp(opt_crr,\"s1d\") || !strcmp(opt_crr,\"sparse\") || !strcmp(opt_crr,\"unpack_sparse\")) flg_s1d=flg_rgr=True; /* [flg] Unpack sparse-1D CLM/ELM variables */\n      if(!strcmp(opt_crr,\"sysconf\")){\n\tlong maxrss; /* [B] Maximum resident set size */\n\tmaxrss=nco_mmr_usg_prn((int)0);\n\tmaxrss+=0; /* CEWI */\n        nco_exit(EXIT_SUCCESS);\n      } /* endif \"sysconf\" */\n      if(!strcmp(opt_crr,\"trr\") || !strcmp(opt_crr,\"terraref\")){\n        flg_trr=True;\n        trr_arg=(char **)nco_realloc(trr_arg,(trr_nbr+1)*sizeof(char *));\n        trr_arg[trr_nbr++]=(char *)strdup(optarg);\n      } /* endif \"trr\" */\n      if(!strcmp(opt_crr,\"trr_in\")){trr_in=(char *)strdup(optarg);flg_trr=True;}\n      if(!strcmp(opt_crr,\"trr_wxy\")){trr_wxy=(char *)strdup(optarg);flg_trr=True;}\n      if(!strcmp(opt_crr,\"tst_udunits\")){ \n\t/* Use this feature with, e.g.,\n\t   ncks --tst_udunits='5 meters',centimeters ~/nco/data/in.nc\n\t   ncks --tst_udunits='0 days since 1918-11-11','days since 1939-09-09',standard ~/nco/data/in.nc\n\t   ncks --tst_udunits='0 days since 1918-11-11','days since 1939-09-09',360_day ~/nco/data/in.nc\n\t   ncks --tst_udunits='0 days since 1918-11-11','days since 1939-09-09',365_day ~/nco/data/in.nc\n\t   ncks --tst_udunits='0 days since 1918-11-11','days since 1939-09-09',366_day ~/nco/data/in.nc */\n        char *cp;\n        char **args;\n        double crr_val;\n#ifndef ENABLE_UDUNITS\n        (void)fprintf(stdout,\"%s: Build NCO with UDUnits support to use this option\\n\",nco_prg_nm_get());\n        nco_exit(EXIT_FAILURE);\n#endif /* !ENABLE_UDUNITS */\n        cp=strdup(optarg); \n        args=nco_lst_prs_1D(cp,\",\",&lmt_nbr);         \n        nco_cln_clc_dbl_org(args[0],args[1],(lmt_nbr > 2 ? nco_cln_get_cln_typ(args[2]) : cln_nil),&crr_val);        \n        (void)fprintf(stdout,\"Value+Units in=%s, units out=%s, time-difference (for dates) or value-conversion (for non-dates) = %f\\n\",args[0],args[1],crr_val);\n        if(cp) cp=(char *)nco_free(cp);\n        nco_exit(EXIT_SUCCESS);\n      } /* endif \"tst_udunits\" */\n      if(!strcmp(opt_crr,\"unn\") || !strcmp(opt_crr,\"union\")) GRP_VAR_UNN=True;\n      if(!strcmp(opt_crr,\"nsx\") || !strcmp(opt_crr,\"intersection\")) GRP_VAR_UNN=False;\n      if(!strcmp(opt_crr,\"grp_xtr_var_xcl\")){\n\tEXCLUDE_INPUT_LIST=True;\n\tGRP_XTR_VAR_XCL=True;\n      } /* endif \"grp_xtr_var_xcl\" */\n      if(!strcmp(opt_crr,\"vrs\") || !strcmp(opt_crr,\"version\")){\n        (void)nco_vrs_prn(CVS_Id,CVS_Revision);\n        nco_exit(EXIT_SUCCESS);\n      } /* endif \"vrs\" */\n      if(!strcmp(opt_crr,\"jsn_fmt\") || !strcmp(opt_crr,\"json_format\") || !strcmp(opt_crr,\"json_fmt\") || !strcmp(opt_crr,\"jsn_format\")){\n\tPRN_JSN=True;\n\tJSN_ATT_FMT=(int)strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10);\n\tif(*sng_cnv_rcd) nco_sng_cnv_err(optarg,\"strtoul\",sng_cnv_rcd);\n\tif(JSN_ATT_FMT >= 4) JSN_DATA_BRK=False; /* [flg] Print JSON with bracket data */\n\tJSN_ATT_FMT%=4; /* 20161221: Valid values are 0,1,2 */\n\tif(JSN_ATT_FMT == 3) JSN_ATT_FMT=2;\n\tJSN_VAR_FMT=JSN_ATT_FMT;\n      } /* !jsn_att_fmt */\n      if(!strcmp(opt_crr,\"jsn\") || !strcmp(opt_crr,\"json\") || !strcmp(opt_crr,\"w10\") || !strcmp(opt_crr,\"w10n\")) PRN_JSN=True; /* [flg] Print JSON */\n      if(!strcmp(opt_crr,\"wrt_tmp_fl\") || !strcmp(opt_crr,\"write_tmp_fl\")) WRT_TMP_FL=True;\n      if(!strcmp(opt_crr,\"no_tmp_fl\")) WRT_TMP_FL=False;\n      if(!strcmp(opt_crr,\"xml\") || !strcmp(opt_crr,\"ncml\")) PRN_XML=True; /* [flg] Print XML (NcML) */\n      if(!strcmp(opt_crr,\"xml_no_location\") || !strcmp(opt_crr,\"ncml_no_location\")){PRN_XML_LOCATION=False;PRN_XML=True;} /* [flg] Print XML location tag */\n      if(!strcmp(opt_crr,\"xml_spr_chr\")){spr_chr=(char *)strdup(optarg);PRN_XML=True;} /* [flg] Separator for XML character types */\n      if(!strcmp(opt_crr,\"xml_spr_nmr\")){spr_nmr=(char *)strdup(optarg);PRN_XML=True;} /* [flg] Separator for XML numeric types */\n      if(!strcmp(opt_crr,\"xtn_var_lst\") || !strcmp(opt_crr,\"extensive\")){\n\t/* Extensive variables */\n\toptarg_lcl=(char *)strdup(optarg);\n\t(void)nco_rx_comma2hash(optarg_lcl);\n\txtn_lst_in=nco_lst_prs_2D(optarg_lcl,\",\",&xtn_nbr);\n\toptarg_lcl=(char *)nco_free(optarg_lcl);\n      } /* !xtn */\n    } /* opt != 0 */\n    /* Process short options */\n    switch(opt){\n    case 0: /* Long options have already been processed, return */\n      break;\n    case '3': /* Request netCDF3 output storage format */\n      fl_out_fmt=NC_FORMAT_CLASSIC;\n      break;\n    case '4': /* Request netCDF4 output storage format */\n      fl_out_fmt=NC_FORMAT_NETCDF4; \n      break;\n    case '5': /* Request netCDF3 64-bit offset+data storage (i.e., pnetCDF) format */\n      fl_out_fmt=NC_FORMAT_CDF5;\n      break;\n    case '6': /* Request netCDF3 64-bit offset output storage format */\n      fl_out_fmt=NC_FORMAT_64BIT_OFFSET;\n      break;\n    case '7': /* Request netCDF4-classic output storage format */\n      fl_out_fmt=NC_FORMAT_NETCDF4_CLASSIC;\n      break;\n    case 'A': /* Toggle FORCE_APPEND */\n      FORCE_APPEND=!FORCE_APPEND;\n      break;\n    case 'a': /* Do not alphabetize output */\n      ALPHABETIZE_OUTPUT=False;\n      (void)fprintf(stderr,\"%s: WARNING the ncks '-a', '--abc', and '--alphabetize' switches are misleadingly named because they turn-off the default alphabetization. These switches are deprecated as of NCO 4.7.1 and will soon be deleted. Instead, please use the new long options --no_abc, --no-abc, --no_alphabetize, or --no-alphabetize, all of which turn-off the default alphabetization.\\n\",nco_prg_nm_get());\n      break;\n    case 'b': /* Set file for binary output */\n      fl_bnr=(char *)strdup(optarg);\n      break;\n    case 'C': /* Extract all coordinates associated with extracted variables? */\n      EXTRACT_ASSOCIATED_COORDINATES=!EXTRACT_ASSOCIATED_COORDINATES;\n      break;\n    case 'c': /* Add all coordinates to extraction list? */\n      EXTRACT_ALL_COORDINATES=True;\n      break;\n    case 'D': /* Debugging level. Default is 0. */\n      nco_dbg_lvl=(unsigned short int)strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10);\n      if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,\"strtoul\",sng_cnv_rcd);\n      break;\n    case 'd': /* Copy limit argument for later processing */\n      lmt_arg[lmt_nbr]=(char *)strdup(optarg);\n      lmt_nbr++;\n      HAVE_LIMITS=True;\n      break;\n    case 'F': /* Toggle index convention. Default is 0-based arrays (C-style). */\n      FORTRAN_IDX_CNV=!FORTRAN_IDX_CNV;\n      break;\n    case 'G': /* Apply Group Path Editing (GPE) to output group */\n      gpe=nco_gpe_prs_arg(optarg);\n      /*      fl_out_fmt=NC_FORMAT_NETCDF4; */\n      break;\n    case 'g': /* Copy group argument for later processing */\n      /* Replace commas with hashes when within braces (convert back later) */\n      optarg_lcl=(char *)strdup(optarg);\n      (void)nco_rx_comma2hash(optarg_lcl);\n      grp_lst_in=nco_lst_prs_2D(optarg_lcl,\",\",&grp_lst_in_nbr);\n      optarg_lcl=(char *)nco_free(optarg_lcl);\n      break;\n    case 'H': /* Toggle printing data to screen */\n      PRN_VAR_DATA_TGL=True;\n      break;\n    case 'h': /* Toggle appending to history global attribute */\n      HISTORY_APPEND=!HISTORY_APPEND;\n      break;\n    case 'L': /* [enm] Deflate level. Default is 0. */\n      dfl_lvl=(int)strtol(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10);\n      if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,\"strtol\",sng_cnv_rcd);\n      break;\n    case 'l': /* Local path prefix for files retrieved from remote file system */\n      fl_pth_lcl=(char *)strdup(optarg);\n      break;\n    case 'm': /* Toggle printing variable metadata to screen */\n      PRN_VAR_METADATA_TGL=True;\n      break;\n    case 'M': /* Toggle printing global metadata to screen */\n      PRN_GLB_METADATA_TGL=True;\n      break;\n    case 'O': /* Toggle FORCE_OVERWRITE */\n      FORCE_OVERWRITE=!FORCE_OVERWRITE;\n      break;\n    case 'o': /* Name of output file */\n      fl_out=(char *)strdup(optarg);\n      break;\n    case 'P': /* Print data to screen, maximal verbosity */\n      PRN_VRB=True;\n      EXTRACT_ASSOCIATED_COORDINATES=!EXTRACT_ASSOCIATED_COORDINATES;\n      break;\n    case 'p': /* Common file path */\n      fl_pth=(char *)strdup(optarg);\n      break;\n    case 'q': /* [flg] Quench (turn-off) all printing to screen */\n      PRN_QUENCH=True; /* [flg] Quench (turn-off) all printing to screen */\n      break;\n    case 'Q': /* Turn off printing of dimension indices and coordinate values */\n      PRN_DMN_IDX_CRD_VAL=!PRN_DMN_IDX_CRD_VAL;\n      break;\n    case 'R': /* Toggle removal of remotely-retrieved-files. Default is True. */\n      RM_RMT_FL_PST_PRC=!RM_RMT_FL_PST_PRC;\n      break;\n    case 'r': /* Print CVS program information and copyright notice */\n      (void)nco_vrs_prn(CVS_Id,CVS_Revision);\n      (void)nco_lbr_vrs_prn();\n      (void)nco_cpy_prn();\n      (void)nco_cnf_prn();\n      nco_exit(EXIT_SUCCESS);\n      break;\n#ifdef ENABLE_MPI\n    case 'S': /* Suspend with signal handler to facilitate debugging */\n      if(signal(SIGUSR1,nco_cnt_run) == SIG_ERR) (void)fprintf(stdout,\"%s: ERROR Could not install suspend handler.\\n\",nco_prg_nm);\n      while(!nco_spn_lck_brk) usleep(nco_spn_lck_us); /* Spinlock. fxm: should probably insert a sched_yield */\n      break;\n#endif /* !ENABLE_MPI */\n    case 's': /* User-specified delimiter string for traditional printed output */\n      PRN_TRD=True; /* [flg] Print traditional */\n      dlm_sng=(char *)strdup(optarg);\n      break;\n    case 't': /* Thread number */\n      thr_nbr=(int)strtol(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10);\n      if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,\"strtol\",sng_cnv_rcd);\n      break;\n    case 'u': /* Toggle printing dimensional units */\n      PRN_DMN_UNITS_TGL=True;\n      break;\n    case 'V': /* Print variable values only (same as -Q --no_nm_prn) */\n      PRN_DMN_IDX_CRD_VAL=False;\n      PRN_DMN_VAR_NM=False;\n      break;\n    case 'v': /* Variables to extract/exclude */\n      /* Replace commas with hashes when within braces (convert back later) */\n      optarg_lcl=(char *)strdup(optarg);\n      (void)nco_rx_comma2hash(optarg_lcl);\n      var_lst_in=nco_lst_prs_2D(optarg_lcl,\",\",&var_lst_in_nbr);\n      optarg_lcl=(char *)nco_free(optarg_lcl);\n      xtr_nbr=var_lst_in_nbr;\n      break;\n    case 'X': /* Copy auxiliary coordinate argument for later processing */\n      aux_arg[aux_nbr]=(char *)strdup(optarg);\n      aux_nbr++;\n      MSA_USR_RDR=True; /* [flg] Multi-Slab Algorithm returns hyperslabs in user-specified order */\n      HAVE_LIMITS=True;\n      break;\n    case 'x': /* Exclude rather than extract groups and variables specified with -v */\n      EXCLUDE_INPUT_LIST=True;\n      break;\n    case 'z': /* Print absolute path of all input variables then exit */\n      trv_tbl_prn(trv_tbl);\n      goto close_and_free; \n      break;\n     case '?': /* Question mark means unrecognized option, print proper usage then EXIT_FAILURE */\n      (void)fprintf(stdout,\"%s: ERROR in command-line syntax/options. Missing or unrecognized option. Please reformulate command accordingly.\\n\",nco_prg_nm_get());\n      (void)nco_usg_prn();\n      nco_exit(EXIT_FAILURE);\n      break;\n    case '-': /* Long options are not allowed */\n      (void)fprintf(stderr,\"%s: ERROR Long options are not available in this build. Use single letter options instead.\\n\",nco_prg_nm_get());\n      nco_exit(EXIT_FAILURE);\n      break;\n    default: /* Print proper usage */\n      (void)fprintf(stdout,\"%s ERROR in command-line syntax/options. Please reformulate command accordingly.\\n\",nco_prg_nm_get());\n      (void)nco_usg_prn();\n      nco_exit(EXIT_FAILURE);\n      break;\n    } /* end switch */\n    if(opt_crr) opt_crr=(char *)nco_free(opt_crr);\n  } /* end while loop */\n\n  /* 20170107: Unlike all other operators, ncks may benefit from setting chunk cache when input file (not output file) is netCDF4 because there is anecdotal evidence that ncdump netCDF4 print speed may be improved by cache adjustments. We cannot verify whether input, output, or both file formats are netCDF4 because nco_set_chunk_cache() must be called before opening file(s). Setting this for netCDF3 library is harmless and calls a no-op stub function */\n  /* Set/report global chunk cache */\n  rcd+=nco_cnk_csh_ini(cnk_csh_byt);\n\n#ifdef _LANGINFO_H\n/* Internationalization i18n\n   Linux Journal 200211 p. 57--59 http://www.linuxjournal.com/article/6176 \n   Fedora: http://fedoraproject.org/wiki/How_to_do_I18N_through_gettext\n   cd ~/nco/bld;make I18N=Y\n   cd ~/nco/bld;xgettext --default-domain=nco --join-existing -o ../po/nco.pot ../src/nco/ncks.c ../src/nco/ncra.c\n   for LL in fr es; do\n     mkdir -p ~/share/locale/${LL}/LC_MESSAGES\n     msgfmt ~/nco/po/${LL}/nco.po -o ~/nco/po/${LL}/nco.mo\n     /bin/cp ~/nco/po/${LL}/nco.mo ~/share/locale/${LL}/LC_MESSAGES\n#     sudo /bin/cp ~/nco/po/${LL}/nco.mo /usr/share/locale/${LL}/LC_MESSAGES  \n   done\n   export LOCALEDIR=${HOME}/share/locale\n   LC_ALL=en ncks -D 1 -O ~/nco/data/in.nc ~/foo.nc\n   LANG=en_GB.utf8 LANGUAGE=en_GB:en:fr_FR:fr LC_ALL=en_GB.utf8 ncks -D 1 -O ~/nco/data/in.nc ~/foo.nc\n   LANG=es ncks -D 1 -O ~/nco/data/in.nc ~/foo.nc\n   LANG=fr_FR.utf8 LANGUAGE=fr_FR:fr:en_GB:en LC_ALL=fr_FR.utf8 ncks -D 1 -O ~/nco/data/in.nc ~/foo.nc */\n  if(nco_dbg_lvl >= nco_dbg_std) (void)fprintf(stdout,gettext(\"%s: I18N Current charset = %s\\n\"),nco_prg_nm,nl_langinfo(CODESET));\n  if(nco_dbg_lvl >= nco_dbg_std) (void)fprintf(stdout,gettext(\"%s: I18N This text may appear in a foreign language\\n\"),nco_prg_nm);\n#endif /* !_LANGINFO_H */\n\n  #if defined(ENABLE_GSL)\n    gsl_set_error_handler_off();\n  #endif /* !ENABLE_GSL */\n\n  /* Initialize traversal table */\n  (void)trv_tbl_init(&trv_tbl);\n \n  /* Process positional arguments and fill-in filenames */\n  fl_lst_in=nco_fl_lst_mk(argv,argc,optind,&fl_nbr,&fl_out,&FL_LST_IN_FROM_STDIN,FORCE_OVERWRITE);\n  \n  /* Initialize thread information */\n  if(flg_rgr) thr_nbr=nco_openmp_ini(thr_nbr); else thr_nbr=nco_openmp_ini((int)1);\n  in_id_arr=(int *)nco_malloc(thr_nbr*sizeof(int));\n  trv_tbl->thr_nbr=thr_nbr;\n  trv_tbl->in_id_arr=in_id_arr;\n\n  /* Parse filename */\n  fl_in=nco_fl_nm_prs(fl_in,0,&fl_nbr,fl_lst_in,abb_arg_nbr,fl_lst_abb,fl_pth);\n  /* Make dummy input file (this step must precede nco_fl_mk_lcl()) */\n  if(flg_dmm_in) nco_fl_dmm_mk(fl_in);\n  /* Make sure file is on local system and is readable or die trying */\n  fl_in=nco_fl_mk_lcl(fl_in,fl_pth_lcl,HPSS_TRY,&FL_RTR_RMT_LCN);\n  fl_in_dpl=strdup(fl_in);\n#ifdef WIN32\n  const char sls_chr='\\\\';   /* [chr] Slash character */\n#else /* !WIN32 */\n  const char sls_chr='/';   /* [chr] Slash character */\n#endif /* !WIN32 */\n  fl_in_stub=strrchr(fl_in_dpl,sls_chr);\n  if(fl_in_stub) fl_in_stub++; else fl_in_stub=fl_in_dpl;\n  /* Open file using appropriate buffer size hints and verbosity */\n  if(RAM_OPEN) md_open=NC_NOWRITE|NC_DISKLESS; else md_open=NC_NOWRITE;\n  if(SHARE_OPEN) md_open=md_open|NC_SHARE;\n  for(thr_idx=0;thr_idx<thr_nbr;thr_idx++) rcd+=nco_fl_open(fl_in,md_open,&bfr_sz_hnt,in_id_arr+thr_idx);\n  in_id=in_id_arr[0];\n  \n  /* Construct GTT (Group Traversal Table), check -v and -g input names and create extraction list */\n  (void)nco_bld_trv_tbl(in_id,trv_pth,lmt_nbr,lmt_arg,aux_nbr,aux_arg,MSA_USR_RDR,FORTRAN_IDX_CNV,grp_lst_in,grp_lst_in_nbr,var_lst_in,xtr_nbr,EXTRACT_ALL_COORDINATES,GRP_VAR_UNN,GRP_XTR_VAR_XCL,EXCLUDE_INPUT_LIST,EXTRACT_ASSOCIATED_COORDINATES,EXTRACT_CLL_MSR,EXTRACT_FRM_TRM,nco_pck_plc_nil,&flg_dne,trv_tbl);\n\n  if(ALPHABETIZE_OUTPUT) trv_tbl_srt(srt_mth,trv_tbl);\n\n  /* [fnc] Print extraction list and exit */\n  if(LST_XTR) nco_xtr_lst(trv_tbl);\n\n  /* [fnc] Print extraction list of N>=D variables and exit */\n  if(LST_RNK_GE2) nco_xtr_ND_lst(trv_tbl);\n\n  /* Were all user-specified dimensions found? */ \n  (void)nco_chk_dmn(lmt_nbr,flg_dne);    \n\n  /* Get number of variables, dimensions, and global attributes in file */\n  (void)trv_tbl_inq(&att_glb_nbr,&att_grp_nbr,&att_var_nbr,&dmn_nbr_fl,&dmn_rec_fl,&grp_dpt_fl,&grp_nbr_fl,&var_udt_fl,&var_nbr_fl,trv_tbl);\n\n  /* Make output and input files consanguinous */\n  (void)nco_inq_format(in_id,&fl_in_fmt);\n  if(fl_out_fmt == NCO_FORMAT_UNDEFINED) fl_out_fmt=fl_in_fmt;\n  if(fl_out_fmt == NC_FORMAT_NETCDF4 || fl_out_fmt == NC_FORMAT_NETCDF4_CLASSIC) (void)omp_set_num_threads((int)0);\n\n#ifdef ENABLE_MPI\n  if(prc_rnk == rnk_mgr) (void)fprintf(stdout,\"%s: MPI process rank %d reports %d process%s\\n\",nco_prg_nm,prc_rnk,prc_nbr,(prc_nbr == 1) ? \"\" : \"es\");\n  /* Roll call */\n  (void)fprintf(stdout,\"%s: MPI process rank %d reports %d process%s\\n\",nco_prg_nm,prc_rnk,prc_nbr,(prc_nbr == 1) ? \"\" : \"es\");\n#endif /* !ENABLE_MPI */\n\n  /* We now have final list of variables to extract. Phew. */\n\n  if(fl_out){\n    /* Copy everything (all data and metadata) to output file by default */\n    if(PRN_VAR_DATA_TGL) PRN_VAR_DATA=False; else PRN_VAR_DATA=True;\n    if(PRN_VAR_METADATA_TGL) PRN_VAR_METADATA=False; else PRN_VAR_METADATA=True;\n    if(PRN_GLB_METADATA_TGL) PRN_GLB_METADATA=False; else PRN_GLB_METADATA=True;\n    if(FORCE_APPEND){\n      /* When appending, do not copy global metadata by default */\n      if(var_lst_in) PRN_GLB_METADATA=False; else PRN_GLB_METADATA=True;\n      if(PRN_GLB_METADATA_TGL) PRN_GLB_METADATA=!PRN_GLB_METADATA;\n    } /* !FORCE_APPEND */\n  }else{ /* !fl_out */\n    /* Only input file is specified, so print it */\n    if(PRN_VRB || (!PRN_VAR_DATA_TGL && !PRN_VAR_METADATA_TGL && !PRN_GLB_METADATA_TGL)){\n      /* Verbose printing simply means assume user wants deluxe frills by default */\n      if(PRN_DMN_UNITS_TGL) PRN_DMN_UNITS=False; else PRN_DMN_UNITS=True;\n      if(PRN_VAR_DATA_TGL) PRN_VAR_DATA=False; else PRN_VAR_DATA=True;\n      if(PRN_VAR_METADATA_TGL) PRN_VAR_METADATA=False; else PRN_VAR_METADATA=True;\n      /* Assume user wants global metadata unless variable extraction is invoked */\n      if(var_lst_in == NULL) PRN_GLB_METADATA=True;\n      if(PRN_GLB_METADATA_TGL) PRN_GLB_METADATA=!PRN_GLB_METADATA;\n    }else{ /* end if PRN_VRB */\n      /* Default is to print data and metadata to screen if output file is not specified */\n      if(PRN_DMN_UNITS_TGL) PRN_DMN_UNITS=True; else PRN_DMN_UNITS=False;\n      if(PRN_VAR_DATA_TGL) PRN_VAR_DATA=True; else PRN_VAR_DATA=False;\n      if(PRN_VAR_METADATA_TGL) PRN_VAR_METADATA=True; else PRN_VAR_METADATA=False;\n      if(PRN_GLB_METADATA_TGL) PRN_GLB_METADATA=True; else PRN_GLB_METADATA=False;\n    } /* !PRN_VRB */  \n    /* PRN_QUENCH turns off all printing to screen */\n    if(PRN_QUENCH) PRN_VAR_DATA=PRN_VAR_METADATA=PRN_GLB_METADATA=False;\n  } /* !fl_out */  \n\n  if(fl_bnr && !fl_out){\n    /* Native binary files depend on writing netCDF file to enter generic I/O logic */\n    (void)fprintf(stdout,\"%s: ERROR Native binary files cannot be written unless netCDF output filename also specified.\\nHINT: Repeat command with dummy netCDF file specified for output file (e.g., -o foo.nc)\\n\",nco_prg_nm_get());\n    nco_exit(EXIT_FAILURE);\n  } /* endif fl_bnr */\n    \n  if(flg_rgr && !fl_out){\n    (void)fprintf(stdout,\"%s: ERROR Regridding requested but no output file specified\\nHINT: Specify output file with \\\"-o fl_out\\\" or as last argument\\n\",nco_prg_nm_get());\n    nco_exit(EXIT_FAILURE);\n  } /* !flg_rgr */\n    \n  if(gpe){\n    if(nco_dbg_lvl >= nco_dbg_fl) (void)fprintf(stderr,\"%s: INFO Group Path Edit (GPE) feature enabled\\n\",nco_prg_nm_get());\n    if(fl_out && fl_out_fmt != NC_FORMAT_NETCDF4 && nco_dbg_lvl >= nco_dbg_std) (void)fprintf(stderr,\"%s: WARNING Group Path Edit (GPE) requires netCDF4 output format in most cases (except flattening) but user explicitly requested output format = %s. This command will fail if the output file requires netCDF4 features like groups, non-atomic types, or multiple record dimensions. However, it _will_ autoconvert netCDF4 atomic types (e.g., NC_STRING, NC_UBYTE...) to netCDF3 atomic types (e.g., NC_CHAR, NC_SHORT...).\\n\",nco_prg_nm_get(),nco_fmt_sng(fl_out_fmt));\n  } /* !gpe */\n\n  /* Terraref */\n  if(flg_trr){\n    char *trr_out;\n    trr_sct *trr_nfo;\n    trr_out=(char *)strdup(fl_out);\n    trr_nfo=nco_trr_ini(cmd_ln,dfl_lvl,trr_arg,trr_nbr,trr_in,trr_out,trr_wxy);\n    (void)nco_trr_read(trr_nfo);\n    /* Free Terraref structure */\n    trr_nfo=nco_trr_free(trr_nfo);\n    if(trr_wxy) trr_wxy=(char *)nco_free(trr_wxy);\n    nco_exit_gracefully();\n    return EXIT_SUCCESS;\n  } /* !Terraref */\n  \n  if(fl_out){\n    /* Output file was specified so PRN_ tokens refer to (meta)data copying */\n    int out_id;\n    \n    /* Make output and input files consanguinous */\n    if(fl_out_fmt == NCO_FORMAT_UNDEFINED) fl_out_fmt=fl_in_fmt;\n\n    /* Regridding */\n    if(flg_rgr){\n      rgr_sct *rgr_nfo;\n      /* Initialize regridding structure */\n      rgr_in=(char *)strdup(fl_in);\n      rgr_out=(char *)strdup(fl_out);\n      rgr_nfo=nco_rgr_ini(cmd_ln,in_id,rgr_arg,rgr_nbr,rgr_in,rgr_out,rgr_grd_src,rgr_grd_dst,rgr_hrz,rgr_map,rgr_var,rgr_vrt,wgt_vld_thr,xtn_lst_in,xtn_nbr);\n      rgr_nfo->fl_out_fmt=fl_out_fmt;\n      rgr_nfo->dfl_lvl=dfl_lvl;\n      rgr_nfo->hdr_pad=hdr_pad;\n      rgr_nfo->flg_area_out=EXTRACT_CLL_MSR; /* [flg] Add area to output */\n      rgr_nfo->flg_s1d=flg_s1d; /* [flg] Unpack sparse-1D CLM/ELM variables */\n      rgr_nfo->flg_uio=SHARE_CREATE;\n      rgr_nfo->fl_out_tmp=nco_fl_out_open(rgr_nfo->fl_out,&FORCE_APPEND,FORCE_OVERWRITE,fl_out_fmt,&bfr_sz_hnt,RAM_CREATE,RAM_OPEN,SHARE_CREATE,SHARE_OPEN,WRT_TMP_FL,&out_id);\n\n      /* Copy Global Metadata */\n      rgr_nfo->out_id=out_id;\n      rgr_nfo->thr_nbr=thr_nbr;\n      nco_bool PCK_ATT_CPY=True; /* [flg] Copy attributes \"scale_factor\", \"add_offset\" */\n      (void)nco_att_cpy(in_id,out_id,NC_GLOBAL,NC_GLOBAL,PCK_ATT_CPY);\n      /* Catenate time-stamped command line to \"history\" global attribute */\n      if(HISTORY_APPEND) (void)nco_hst_att_cat(out_id,cmd_ln);\n      if(gaa_nbr > 0) (void)nco_glb_att_add(out_id,gaa_arg,gaa_nbr);\n      if(HISTORY_APPEND) (void)nco_vrs_att_cat(out_id);\n      if(thr_nbr > 1 && HISTORY_APPEND) (void)nco_thr_att_cat(out_id,thr_nbr);\n      char att_sng_ttl[]=\"title\"; /* [sng] NUG-documented title string */\n      char *att_ttl_val=NULL;\n      att_ttl_val=nco_char_att_get(in_id,NC_GLOBAL,att_sng_ttl);\n      //(void)fprintf(stdout,\"%s: DEBUG input title attribute is: %s\\n\",nco_prg_nm_get(),att_ttl_val);\n      if(!att_ttl_val || (att_ttl_val && (!strcmp(att_ttl_val,\"UNSET\")))){\n\t/* Panoply prints the value of global attribute \"title\", if any, in its file selector menu\n\t   Otherwise it prints \"UNSET\", which is ... unsettling\n\t   NUG and CF endorse \"title\" as a global attribute that succinctly describes file contents\n\t   Construct a useful value when none exists in input\n\t   20210609: \"Regridded version of \"+fl_in_stub */\n\tatt_ttl_val=(char *)nco_realloc(att_ttl_val,(strlen(fl_in_stub)+21L+1L)*sizeof(char));\n\tatt_ttl_val=strcpy(att_ttl_val,\"Regridded version of \");\n\tatt_ttl_val=strcat(att_ttl_val,fl_in_stub);\n\trcd=nco_char_att_put(out_id,NULL,att_sng_ttl,att_ttl_val);\n\t//(void)fprintf(stdout,\"%s: DEBUG output title attribute is: %s\\n\",nco_prg_nm_get(),att_ttl_val);\n\tif(att_ttl_val) att_ttl_val=(char *)nco_free(att_ttl_val);\n      } /* !att_ttl_val */\n      \n      /* Generate grids/maps or regrid horizontally/vertically */\n      rcd=nco_rgr_ctl(rgr_nfo,trv_tbl);\n      /* Change from NCO_NOERR to NC_NOERR */\n      rcd=NC_NOERR;\n\n      /* Close output file and move it from temporary to permanent location */\n      (void)nco_fl_out_cls(rgr_nfo->fl_out,rgr_nfo->fl_out_tmp,out_id);\n\n      /* Free regridding structure */\n      rgr_nfo=nco_rgr_free(rgr_nfo);\n    } /* endif !flg_rgr */\n\n    if(!flg_rgr){\n      \n      /* Initialize, decode, and set PPC information */\n      if(ppc_nbr > 0) nco_ppc_ini(in_id,&dfl_lvl,fl_out_fmt,ppc_arg,ppc_nbr,trv_tbl);\n      \n      /* Verify output file format supports requested actions */\n      (void)nco_fl_fmt_vet(fl_out_fmt,cnk_nbr,dfl_lvl);\n      \n      /* Open output file */\n      fl_out_tmp=nco_fl_out_open(fl_out,&FORCE_APPEND,FORCE_OVERWRITE,fl_out_fmt,&bfr_sz_hnt,RAM_CREATE,RAM_OPEN,SHARE_CREATE,SHARE_OPEN,WRT_TMP_FL,&out_id);\n    \n      /* Initialize chunking from user-specified inputs */\n      if(fl_out_fmt == NC_FORMAT_NETCDF4 || fl_out_fmt == NC_FORMAT_NETCDF4_CLASSIC) rcd+=nco_cnk_ini(in_id,fl_out,cnk_arg,cnk_nbr,cnk_map,cnk_plc,cnk_csh_byt,cnk_min_byt,cnk_sz_byt,cnk_sz_scl,&cnk);\n\n      /* Define extracted groups, variables, and attributes in output file */\n      CPY_GRP_METADATA=PRN_GLB_METADATA;\n      (void)nco_xtr_dfn(in_id,out_id,&cnk,dfl_lvl,gpe,md5,CPY_GRP_METADATA,PRN_VAR_METADATA,RETAIN_ALL_DIMS,nco_pck_plc_nil,rec_dmn_nm,trv_tbl);\n\n      /* Catenate time-stamped command line to \"history\" global attribute */\n      if(HISTORY_APPEND) (void)nco_hst_att_cat(out_id,cmd_ln);\n      if(HISTORY_APPEND && FORCE_APPEND) (void)nco_prv_att_cat(fl_in,in_id,out_id);\n      if(gaa_nbr > 0) (void)nco_glb_att_add(out_id,gaa_arg,gaa_nbr);\n      if(HISTORY_APPEND) (void)nco_vrs_att_cat(out_id);\n#ifdef ENABLE_MPI\n      if(prc_rnk == rnk_mgr)\n\tif(prc_nbr > 0 && HISTORY_APPEND) (void)nco_mpi_att_cat(out_id,prc_nbr);\n#endif /* !ENABLE_MPI */\n      \n      /* Turn-off default filling behavior to enhance efficiency */\n      nco_set_fill(out_id,NC_NOFILL,&fll_md_old);\n      \n      /* Take output file out of define mode */\n      if(hdr_pad == 0UL){\n\t(void)nco_enddef(out_id);\n      }else{\n\t(void)nco__enddef(out_id,hdr_pad);\n\tif(nco_dbg_lvl >= nco_dbg_scl) (void)fprintf(stderr,\"%s: INFO Padding header with %lu extra bytes\\n\",nco_prg_nm_get(),(unsigned long)hdr_pad);\n      } /* hdr_pad */\n\n      /* [fnc] Open unformatted binary data file for writing */\n      if(fl_bnr) fp_bnr=nco_bnr_open(fl_bnr,\"w\");\n      \n      /* Timestamp end of metadata setup and disk layout */\n      rcd+=nco_ddra((char *)NULL,(char *)NULL,&ddra_info);\n      ddra_info.tmr_flg=nco_tmr_rgl;\n      /* Write extracted data to output file */\n      if(PRN_VAR_DATA) (void)nco_xtr_wrt(in_id,out_id,gpe,fp_bnr,md5,HAVE_LIMITS,trv_tbl);\n      \n      /* [fnc] Close unformatted binary data file */\n      if(fp_bnr) (void)nco_bnr_close(fp_bnr,fl_bnr);\n      \n      if(nco_dbg_lvl_get() == 14){\n\t(void)nco_wrt_trv_tbl(in_id,trv_tbl,True);\n\t(void)nco_wrt_trv_tbl(out_id,trv_tbl,True);\n      } /* endif dbg */\n\n      /* Close output file and move it from temporary to permanent location */\n      (void)nco_fl_out_cls(fl_out,fl_out_tmp,out_id);\n    \n    } /* flg_rgr */\n    \n  }else{ /* !fl_out */\n\n    nco_bool ALPHA_BY_FULL_GROUP=False; /* [flg] Print alphabetically by full group */\n    nco_bool ALPHA_BY_STUB_GROUP=True; /* [flg] Print alphabetically by stub group */\n    char *sfx_ptr;\n\n    /* Update all GTT dimensions with hyperslabbed size */\n    (void)nco_dmn_trv_msa_tbl(in_id,rec_dmn_nm,trv_tbl);   \n\n    /* No output file was specified so PRN_ tokens refer to screen printing */\n    prn_fmt_sct prn_flg;\n    /* Printing defaults to stdout */\n    prn_flg.fp_out=stdout;\n    PRN_CDL=PRN_CDL || !(PRN_TRD || PRN_XML || PRN_JSN); // 20170817\n    prn_flg.cdl=PRN_CDL;\n    prn_flg.trd=PRN_TRD;\n    prn_flg.jsn=PRN_JSN;\n    prn_flg.srm=PRN_SRM;\n    prn_flg.xml=PRN_XML;\n    if((prn_flg.cdl || prn_flg.xml) && nco_dbg_lvl >= nco_dbg_std) prn_flg.nfo_xtr=True; else prn_flg.nfo_xtr=False;\n    prn_flg.new_fmt=(PRN_CDL || PRN_JSN || PRN_SRM || PRN_XML);\n    prn_flg.hdn=PRN_HDN;\n    prn_flg.udt=PRN_UDT;\n    prn_flg.rad=RETAIN_ALL_DIMS;\n    /* CDL must print filename stub (filename without path or suffix) */\n    if(prn_flg.cdl || prn_flg.xml){\n      sfx_ptr=strrchr(fl_in_stub,'.');\n      if(sfx_ptr) *sfx_ptr='\\0';\n      prn_flg.fl_stb=fl_in_stub;\n    } /* endif CDL */\n    /* JSON and XML need filename (unless location will be omitted) */\n    if(prn_flg.xml || prn_flg.jsn) prn_flg.fl_in=fl_in;\n    prn_flg.spr_nmr=spr_nmr;\n    prn_flg.spr_chr=spr_chr;\n    prn_flg.xml_lcn=PRN_XML_LOCATION;\n    prn_flg.gpe=gpe;\n    prn_flg.md5=md5;\n    prn_flg.ndn=0; /* Initialize for prn_flg->trd */\n    prn_flg.spc_per_lvl=2;\n    prn_flg.sxn_fst=2;\n    prn_flg.var_fst=2;\n    prn_flg.tab=4;\n    prn_flg.nbr_zro=0;  \n    if(nco_dbg_lvl >= nco_dbg_scl) prn_flg.fll_pth=True; else prn_flg.fll_pth=False;\n    if(prn_flg.xml) prn_flg.nwl_pst_val=False; else prn_flg.nwl_pst_val=True;\n    prn_flg.dlm_sng=dlm_sng;\n    if(PRN_CLN_LGB && dt_fmt == fmt_dt_nil) dt_fmt=fmt_dt_sht;\n    prn_flg.cdl_fmt_dt=dt_fmt;\n    prn_flg.fl_out_fmt=fl_out_fmt;\n    prn_flg.fmt_val=fmt_val;\n    prn_flg.ALPHA_BY_FULL_GROUP=ALPHA_BY_FULL_GROUP;\n    prn_flg.ALPHA_BY_STUB_GROUP=ALPHA_BY_STUB_GROUP;\n    prn_flg.FORTRAN_IDX_CNV=FORTRAN_IDX_CNV;\n    prn_flg.PRN_DMN_IDX_CRD_VAL=PRN_DMN_IDX_CRD_VAL;\n    prn_flg.PRN_DMN_UNITS=PRN_DMN_UNITS;\n    prn_flg.PRN_DMN_VAR_NM=PRN_DMN_VAR_NM;\n    prn_flg.PRN_GLB_METADATA=PRN_GLB_METADATA;\n    prn_flg.PRN_MSS_VAL_BLANK=PRN_MSS_VAL_BLANK;\n    prn_flg.PRN_VAR_DATA=PRN_VAR_DATA;\n    prn_flg.PRN_VAR_METADATA=PRN_VAR_METADATA;\n    prn_flg.PRN_CLN_LGB=PRN_CLN_LGB;\n\n    /* Derived formats */\n    if(prn_flg.cdl){\n      prn_flg.PRN_DMN_UNITS=True;\n      prn_flg.PRN_DMN_VAR_NM=True;\n      prn_flg.PRN_MSS_VAL_BLANK=True;\n    } /* endif */\n\n    if(prn_flg.jsn){\n      /* In JSON numeric notation, a terminal decimal place, like 0. and 20., is invalid---correct is 0.0, 20.0 */\n      prn_flg.nbr_zro=1;\n      /* JSON numerical arrays have no notion of missing values */\n      prn_flg.PRN_MSS_VAL_BLANK=False;\n      prn_flg.jsn_data_brk=JSN_DATA_BRK;\n      prn_flg.jsn_var_fmt=JSN_VAR_FMT;\n    }else { /* endif JSON */\n      prn_flg.jsn_att_fmt=0;\n      prn_flg.jsn_data_brk=False;\n      prn_flg.jsn_var_fmt=2;\n    } /* !JSON */\n      \n    if(prn_flg.xml) prn_flg.PRN_MSS_VAL_BLANK=False;\n\n    /* File summary */\n    if(PRN_GLB_METADATA){\n      prn_flg.smr_sng=smr_sng=(char *)nco_malloc((strlen(fl_in)+300L*sizeof(char))); /* [sng] File summary string */\n      smr_xtn_sng=(char *)nco_malloc(300L*sizeof(char)); /* [sng] File extended summary string */\n      if(nco_dbg_lvl > nco_dbg_std) (void)sprintf(smr_xtn_sng,\" (representation of extended/underlying filetype %s)\",nco_fmt_xtn_sng(nco_fmt_xtn_get())); else smr_xtn_sng[0]='\\0';\n      (void)sprintf(smr_sng,\"Summary of %s: filetype = %s%s, %i groups (max. depth = %i), %i dimensions (%i fixed, %i record), %i variables (%i atomic, %i user-defined types), %i attributes (%i global, %i group, %i variable)\",fl_in,nco_fmt_sng(fl_in_fmt),smr_xtn_sng,grp_nbr_fl,grp_dpt_fl,trv_tbl->nbr_dmn,trv_tbl->nbr_dmn-dmn_rec_fl,dmn_rec_fl,var_nbr_fl,var_nbr_fl-var_udt_fl,var_udt_fl,att_glb_nbr+att_grp_nbr+att_var_nbr,att_glb_nbr,att_grp_nbr,att_var_nbr);\n\n      if(nco_dbg_lvl > nco_dbg_std){\n\tprn_flg.smr_fl_sz_sng=smr_fl_sz_sng=(char *)nco_malloc(300L*sizeof(char)); /* [sng] String describing estimated file size */\n \t(void)nco_fl_sz_est(smr_fl_sz_sng,trv_tbl);\n      } /* !dbg */\n    } /* endif summary */\n\n    if(fl_prn){\n      if((fp_prn=fopen(fl_prn,\"w\")) == NULL){\n\t(void)fprintf(stderr,\"%s: ERROR unable to open formatted output file %s\\n\",nco_prg_nm_get(),fl_prn);\n\tnco_exit(EXIT_FAILURE);\n      } /* !fp_prn */\n      prn_flg.fp_out=fp_prn;\n    } /* !fl_prn */\n\n    if(!prn_flg.new_fmt){\n      /* Traditional printing order/format always used prior to 201307 */\n      if(PRN_GLB_METADATA){\n        int dmn_ids_rec[NC_MAX_DIMS]; /* [ID] Record dimension IDs array */\n        int nbr_rec_lcl; /* [nbr] Number of record dimensions visible in root */\n        /* Get unlimited dimension information from input file/group */\n        rcd=nco_inq_unlimdims(in_id,&nbr_rec_lcl,dmn_ids_rec);\n        if(nbr_rec_lcl > 0){\n          char dmn_nm[NC_MAX_NAME]; \n          long rec_dmn_sz;\n          for(int rec_idx=0;rec_idx<nbr_rec_lcl;rec_idx++){\n            (void)nco_inq_dim(in_id,dmn_ids_rec[rec_idx],dmn_nm,&rec_dmn_sz);\n            (void)fprintf(prn_flg.fp_out,\"Root record dimension %d: name = %s, size = %li\\n\",rec_idx,dmn_nm,rec_dmn_sz);\n          } /* end loop over rec_idx */\n          (void)fprintf(stdout,\"\\n\");\n        } /* NCO_REC_DMN_UNDEFINED */\n        /* Print group attributes recursively */\n        (void)nco_prn_att_trv(in_id,&prn_flg,trv_tbl);\n      } /* !PRN_GLB_METADATA */\n\n      if(PRN_VAR_METADATA) (void)nco_prn_xtr_mtd(in_id,&prn_flg,trv_tbl);\n      if(PRN_VAR_DATA) (void)nco_prn_xtr_val(in_id,&prn_flg,trv_tbl);\n      \n    }else{ \n\n      if(CHK_MAP){\n\t/* Check map-file quality */\n\tnco_map_chk(fl_in,flg_area_wgt,flg_frac_b_nrm);\n        goto close_and_free;\n      } /* !CHK_MAP */\n\n      if(CHK_NAN){\n\t/* Check floating-point fields for NaNs */\n        nco_chk_nan(in_id,trv_tbl);\n        goto close_and_free;\n      } /* !CHK_NAN */\n\n      /* New file dump format(s) developed 201307 for CDL, JSN, SRM, TRD, XML */\n      if(PRN_SRM){\n\t/* Stream printing is pre-alpha. Great project for volunteers! */\n        nco_srm_hdr();\n        goto close_and_free;\n      } /* !PRN_SRM */\n\n      if(ALPHA_BY_FULL_GROUP || ALPHA_BY_STUB_GROUP){\n\t/* Print CDL, JSN, TRD, and XML formats */\n        if(prn_flg.jsn) rcd+=nco_prn_jsn(in_id,trv_pth,&prn_flg,trv_tbl);\n        else if(prn_flg.xml) rcd+=nco_prn_xml(in_id,trv_pth,&prn_flg,trv_tbl);\n        else if(prn_flg.cdl || prn_flg.trd) rcd+=nco_prn_cdl_trd(in_id,trv_pth,&prn_flg,trv_tbl); \n      }else{\n\t/* Place-holder for other options for organization/alphabetization */\n\tif(PRN_VAR_METADATA) (void)nco_prn_xtr_mtd(in_id,&prn_flg,trv_tbl);\n\tif(PRN_VAR_DATA) (void)nco_prn_xtr_val(in_id,&prn_flg,trv_tbl);\n      } /* end if */\n    } /* endif new format */\n\n    if(fl_prn){\n      rcd=fclose(fp_prn);\n      if(rcd != 0){\n\t(void)fprintf(stderr,\"%s: ERROR unable to close formatted output file %s\\n\",nco_prg_nm_get(),fl_prn);\n\tnco_exit(EXIT_FAILURE);\n      } /* !fp_prn */\n    } /* !fl_prn */\n\n  } /* !fl_out */\n\n  /* goto close_and_free */\nclose_and_free: \n\n  /* Close input netCDF files */\n  for(thr_idx=0;thr_idx<thr_nbr;thr_idx++) nco_close(in_id_arr[thr_idx]);\n\n  /* Remove local copy of file */\n  if(FL_RTR_RMT_LCN && RM_RMT_FL_PST_PRC) (void)nco_fl_rm(fl_in);\n  \n  /* Clean memory unless dirty memory allowed */\n  if(flg_mmr_cln){\n    /* ncks-specific memory */\n    if(fl_bnr) fl_bnr=(char *)nco_free(fl_bnr);\n    if(fl_in_dpl) fl_in_dpl=(char *)nco_free(fl_in_dpl);\n    if(fl_prn) fl_prn=(char *)nco_free(fl_prn);\n    if(flt_sng) flt_sng=(char *)nco_free(flt_sng);\n    if(rec_dmn_nm) rec_dmn_nm=(char *)nco_free(rec_dmn_nm); \n    /* NCO-generic clean-up */\n    /* Free individual strings/arrays */\n    if(cmd_ln) cmd_ln=(char *)nco_free(cmd_ln);\n    if(cnk_map_sng) cnk_map_sng=(char *)nco_free(cnk_map_sng);\n    if(cnk_plc_sng) cnk_plc_sng=(char *)nco_free(cnk_plc_sng);\n    if(fl_in) fl_in=(char *)nco_free(fl_in);\n    if(fl_out) fl_out=(char *)nco_free(fl_out);\n    if(fl_out_tmp) fl_out_tmp=(char *)nco_free(fl_out_tmp);\n    if(fl_pth) fl_pth=(char *)nco_free(fl_pth);\n    if(fl_pth_lcl) fl_pth_lcl=(char *)nco_free(fl_pth_lcl);\n    if(in_id_arr) in_id_arr=(int *)nco_free(in_id_arr);\n    if(spr_nmr) spr_nmr=(char *)nco_free(spr_nmr);\n    if(spr_chr) spr_chr=(char *)nco_free(spr_chr);\n    /* Free lists of strings */\n    if(fl_lst_in && fl_lst_abb == NULL) fl_lst_in=nco_sng_lst_free(fl_lst_in,fl_nbr); \n    if(fl_lst_in && fl_lst_abb) fl_lst_in=nco_sng_lst_free(fl_lst_in,1);\n    if(fl_lst_abb) fl_lst_abb=nco_sng_lst_free(fl_lst_abb,abb_arg_nbr);\n    if(gaa_nbr > 0) gaa_arg=nco_sng_lst_free(gaa_arg,gaa_nbr);\n    if(grp_lst_in_nbr > 0) grp_lst_in=nco_sng_lst_free(grp_lst_in,grp_lst_in_nbr);\n    if(var_lst_in_nbr > 0) var_lst_in=nco_sng_lst_free(var_lst_in,var_lst_in_nbr);\n    /* Free limits */\n    for(idx=0;idx<aux_nbr;idx++) aux_arg[idx]=(char *)nco_free(aux_arg[idx]);\n    for(idx=0;idx<lmt_nbr;idx++) lmt_arg[idx]=(char *)nco_free(lmt_arg[idx]);\n    for(idx=0;idx<ppc_nbr;idx++) ppc_arg[idx]=(char *)nco_free(ppc_arg[idx]);\n    /* Free chunking information */\n    for(idx=0;idx<cnk_nbr;idx++) cnk_arg[idx]=(char *)nco_free(cnk_arg[idx]);\n    if(cnk_nbr > 0 && (fl_out_fmt == NC_FORMAT_NETCDF4 || fl_out_fmt == NC_FORMAT_NETCDF4_CLASSIC)) cnk.cnk_dmn=(cnk_dmn_sct **)nco_cnk_lst_free(cnk.cnk_dmn,cnk_nbr);\n    trv_tbl_free(trv_tbl);\n    for(idx=0;idx<lmt_nbr;idx++) flg_dne[idx].dim_nm=(char *)nco_free(flg_dne[idx].dim_nm);\n    if(flg_dne) flg_dne=(nco_dmn_dne_t *)nco_free(flg_dne);\n    if(gpe) gpe=(gpe_sct *)nco_gpe_free(gpe);\n    if(md5) md5=(md5_sct *)nco_md5_free(md5);\n    if(rec_dmn_nm_fix) rec_dmn_nm_fix=(char *)nco_free(rec_dmn_nm_fix);\n    if(smr_sng) smr_sng=(char *)nco_free(smr_sng);\n    if(smr_fl_sz_sng) smr_fl_sz_sng=(char *)nco_free(smr_fl_sz_sng);\n    if(smr_xtn_sng) smr_xtn_sng=(char *)nco_free(smr_xtn_sng);\n  } /* !flg_mmr_cln */\n  \n#ifdef ENABLE_MPI\n  MPI_Finalize();\n#endif /* !ENABLE_MPI */\n  \n  /* End timer */ \n  ddra_info.tmr_flg=nco_tmr_end; /* [enm] Timer flag */\n  rcd+=nco_ddra((char *)NULL,(char *)NULL,&ddra_info);\n  if(rcd != NC_NOERR) nco_err_exit(rcd,\"main\");\n\n  nco_exit_gracefully();\n  return EXIT_SUCCESS;\n} /* end main() */\n", "meta": {"hexsha": "c5f079a93d1f0cda45c47a12e4a470cfd393881b", "size": 85987, "ext": "c", "lang": "C", "max_stars_repo_path": "src/nco/ncks.c", "max_stars_repo_name": "rkouznetsov/nco", "max_stars_repo_head_hexsha": "e77123be96876ed8e63f71e9721ff00e42693c9b", "max_stars_repo_licenses": ["BSD-3-Clause-Clear", "BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-20T08:05:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-20T08:05:14.000Z", "max_issues_repo_path": "src/nco/ncks.c", "max_issues_repo_name": "merjatoelle/nco", "max_issues_repo_head_hexsha": "bec69956bcf5a8ea8cb2b2116badc6bf95e1c625", "max_issues_repo_licenses": ["BSD-3-Clause-Clear", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/nco/ncks.c", "max_forks_repo_name": "merjatoelle/nco", "max_forks_repo_head_hexsha": "bec69956bcf5a8ea8cb2b2116badc6bf95e1c625", "max_forks_repo_licenses": ["BSD-3-Clause-Clear", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 54.3533501896, "max_line_length": 825, "alphanum_fraction": 0.6789398397, "num_tokens": 26993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08035747322699914, "lm_q2_score": 0.04336580154570671, "lm_q1q2_score": 0.003484766236676485}}
{"text": "#pragma once\n\n#ifndef UPCA_ARCH_H\n#error \"Don't include this file directly. Use #include <upca/upca.h>.\"\n#endif\n\n#include <iostream>\n#include <memory>\n#include <sstream>\n#include <string>\n\n#include <gsl/gsl>\n\n#include <fcntl.h>\n#include <stdio.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n\n#ifdef JEVENTS_FOUND\n\n#include <inttypes.h>\n#include <unistd.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n#include <jevents.h>\n#include <rdpmc.h>\n#ifdef __cplusplus\n}\n#endif\n\n#include <linux/perf_event.h>\n#include <sys/ioctl.h>\n\n#endif\n\nnamespace upca {\n\nstd::ostream &operator<<(std::ostream &os, const struct perf_event_attr &c);\n\nnamespace arch {\nnamespace x86_64 {\n\nclass x86_64_base_pmu {\npublic:\n  uint64_t timestamp_begin() {\n    unsigned high, low;\n    __asm__ volatile(\"CPUID\\n\\t\"\n                     \"RDTSC\\n\\t\"\n                     \"mov %%edx, %0\\n\\t\"\n                     \"mov %%eax, %1\\n\\t\"\n                     : \"=r\"(high), \"=r\"(low)::\"%rax\", \"%rbx\", \"%rcx\", \"%rdx\");\n\n    return static_cast<uint64_t>(high) << 32 | low;\n  }\n\n  uint64_t timestamp_end() {\n    unsigned high, low;\n    __asm__ volatile(\"RDTSCP\\n\\t\"\n                     \"mov %%edx,%0\\n\\t\"\n                     \"mov %%eax,%1\\n\\t\"\n                     \"CPUID\\n\\t\"\n                     : \"=r\"(high), \"=r\"(low)::\"%rax\", \"%rbx\", \"%rcx\", \"%rdx\");\n    return static_cast<uint64_t>(high) << 32 | low;\n  }\n};\n\n#ifdef JEVENTS_FOUND\n\n#ifndef __APPLE__\n\n/*\n * SYSCALL_HANDLED(601, pmc_init) int counter, int type, int mode\n * SYSCALL_HANDLED(602, pmc_start)\n * SYSCALL_HANDLED(603, pmc_stop)\n * SYSCALL_HANDLED(604, pmc_reset)\n *\n * Yes, the interface is that fucked up. counter is either int or unsigned long,\n * depending on the syscall \u2026\n */\n\nstatic inline long mck_pmc_init(int counter, int type, unsigned mode) {\n  return syscall(601, counter, type, mode);\n}\n\nstatic inline long mck_pmc_start(unsigned long counter) {\n  return syscall(602, counter);\n}\nstatic inline long mck_pmc_stop(unsigned long counter) { return syscall(603, counter); }\nstatic inline long mck_pmc_reset(int counter) { return syscall(604, counter); }\n\nstatic inline int mck_is_mckernel() { return syscall(732) == 0; }\n\n#else\n\nstatic inline int mck_is_mckernel() { return 0; }\n\n#endif\n\nclass resolver {\npublic:\n  resolver();\n\n  struct perf_event_attr resolve(const std::string &name) const;\n};\n\nclass fd {\n  int fd_;\n\npublic:\n  explicit fd(int fd) : fd_(fd) {}\n  fd(std::nullptr_t = nullptr) : fd_(-1) {}\n  ~fd() {\n    if (fd_ != -1) {\n      close(fd_);\n    }\n  }\n  fd(fd &&l) {\n    fd_ = l.fd_;\n    l.fd_ = -1;\n  }\n  explicit operator bool() { return fd_ != -1; }\n  explicit operator int() { return fd_; }\n  friend bool operator==(const fd &l, const fd &r) { return l.fd_ == r.fd_; }\n  friend bool operator!=(const fd &l, const fd &r) { return !(l == r); }\n};\n\nstatic inline std::unique_ptr<fd> make_perf_fd(struct perf_event_attr &attr) {\n  const int fd = perf_event_open(&attr, 0, -1, -1, 0);\n\n  if (fd < 0) {\n    std::ostringstream os;\n    os << \"perf_event_open() failed: \" << errno << strerror(errno) << std::endl;\n    throw std::runtime_error(os.str());\n  }\n  return std::make_unique<class fd>(fd);\n}\n\nstatic uint64_t rdpmc(const uint32_t counter) {\n  uint32_t low, high;\n  __asm__ volatile(\"rdpmc\" : \"=a\"(low), \"=d\"(high) : \"c\"(counter));\n  return static_cast<uint64_t>(high) << 32 | low;\n}\n\nenum msrs {\n  IA32_PMC_BASE = 0x0c1,\n  IA32_PERFEVTSEL_BASE = 0x186,\n  IA32_FIXED_CTR_CTRL = 0x38d,\n  IA32_PERF_GLOBAL_STATUS = 0x38e,\n  IA32_PERF_GLOBAL_CTRL = 0x38f,\n  IA32_PERF_GLOBAL_OVF_CTRL = 0x390,\n  IA32_PERF_CAPABILITIES = 0x345,\n  IA32_DEBUGCTL = 0x1d9,\n};\n\nstatic inline void cpuid(const int code, uint32_t *a, uint32_t *b, uint32_t *c,\n                         uint32_t *d) {\n  asm volatile(\"cpuid\" : \"=a\"(*a), \"=b\"(*b), \"=c\"(*c), \"=d\"(*d) : \"a\"(code));\n}\n\n#define MASK(v, high, low) ((v >> low) & ((1 << (high - low + 1)) - 1))\n\ntemplate <typename POLICY> static void pmu_info(const POLICY &msr) {\n  uint32_t eax, ebx, ecx, edx;\n\n  cpuid(0x1, &eax, &ebx, &ecx, &edx);\n\n  std::cout << std::hex;\n\n  std::cout << \"EAX: \" << eax << std::endl;\n  std::cout << \"EBX: \" << ebx << std::endl;\n  std::cout << \"ECX: \" << ecx << std::endl;\n  std::cout << \"EDX: \" << edx << std::endl;\n\n  if (ecx & (1 << 15)) {\n    const uint64_t caps = msr.rdmsr(IA32_PERF_CAPABILITIES);\n    const int vmm_freeze = MASK(caps, 12, 12);\n    std::cout << \"Caps: \" << caps << std::endl;\n    std::cout << \"VMM Freeze: \" << std::boolalpha\n              << static_cast<bool>(vmm_freeze) << std::noboolalpha << std::endl;\n    if (vmm_freeze) {\n      const uint64_t debugctl = msr.rdmsr(IA32_DEBUGCTL);\n      msr.wrmsr(IA32_DEBUGCTL, debugctl & ~(1 << 14));\n    }\n  }\n\n  cpuid(0xa, &eax, &ebx, &ecx, &edx);\n\n  const unsigned version = MASK(eax, 7, 0);\n  const unsigned counters = MASK(eax, 15, 8);\n  const unsigned width = MASK(eax, 23, 16);\n\n  const unsigned ffpc = MASK(edx, 4, 0);\n  const unsigned ff_width = MASK(edx, 12, 5);\n\n  std::cout << \"EAX: \" << eax << std::endl;\n  std::cout << \"EBX: \" << ebx << std::endl;\n  std::cout << \"ECX: \" << ecx << std::endl;\n  std::cout << \"EDX: \" << edx << std::endl;\n\n  std::cout << std::dec;\n\n  std::cout << \"PMC version \" << version << std::endl;\n  std::cout << \"PMC counters: \" << counters << std::endl;\n  std::cout << \"PMC width: \" << width << std::endl;\n\n  std::cout << \"FFPCs: \" << ffpc << \", width: \" << ff_width << std::endl;\n}\n\nstruct x86_pmc_base {\n  virtual ~x86_pmc_base();\n  virtual gsl::span<uint64_t>::index_type start(gsl::span<uint64_t>) = 0;\n  virtual gsl::span<uint64_t>::index_type stop(gsl::span<uint64_t>) = 0;\n};\n\nstruct mck_mck_policy {\n  static long init(const int active, const uint64_t config) {\n    return mck_pmc_init(active, gsl::narrow<int>(config), 0x4);\n  }\n\n  /* writes MSR_IA32_PMC0 + i to 0 */\n  static void reset(const int i) { mck_pmc_reset(i); }\n  /* sets and clears bits in MSR_PERF_GLOBAL_CTRL */\n  static void start(const unsigned long mask) {\n    const auto err = mck_pmc_start(mask);\n    if (err) {\n      std::cerr << \"Error starting PMCs\" << std::endl;\n    }\n  }\n  static void stop(const unsigned long mask) {\n    const auto err = mck_pmc_stop(mask);\n    if (err) {\n      std::cerr << \"Error stopping PMCs\" << std::endl;\n    }\n  }\n  static uint64_t read(const unsigned i) { return rdpmc(i); }\n};\n\nclass msr_mck {\npublic:\n  msr_mck() {}\n  uint64_t rdmsr(const uint32_t reg) const {\n    return static_cast<unsigned long>(syscall(850, reg));\n  }\n  auto wrmsr(const uint32_t reg, const uint64_t val) const {\n    /* always returns 0 */\n    return syscall(851, reg, val);\n  }\n};\n\nclass msr_linux {\n  std::unique_ptr<fd> fd_;\n\n  static unsigned cpu() {\n    int cpu = sched_getcpu();\n    if (cpu < 0) {\n      using namespace std::string_literals;\n      throw std::runtime_error(\"Error getting CPU number: \"s + strerror(errno) +\n                               \" (\" + std::to_string(errno) + \")\\n\");\n    }\n    /* TODO: check thread affinity mask\n     * - has a single CPU\n     * - this single CPU is this CPU\n     */\n    return static_cast<unsigned>(cpu);\n  }\n\npublic:\n  msr_linux()\n      : fd_(std::make_unique<fd>(open(\n            (\"/dev/cpu/\" + std::to_string(cpu()) + \"/msr\").c_str(), O_RDWR))) {}\n\n  uint64_t rdmsr(const uint32_t reg) const {\n    uint64_t v;\n    const ssize_t ret = pread(static_cast<int>(*fd_), &v, sizeof(v), reg);\n    if (ret != sizeof(v)) {\n      std::cerr << \"Reading MSR \" << std::hex << reg << std::dec << \" failed.\"\n                << std::endl;\n    }\n    return v;\n  }\n\n  auto wrmsr(const uint32_t reg, const uint64_t val) const {\n    const ssize_t ret = pwrite(static_cast<int>(*fd_), &val, sizeof(val), reg);\n    if (ret != sizeof(val)) {\n      std::cerr << \"Writing MSR \" << std::hex << reg << std::dec << \" failed.\"\n                << std::endl;\n    }\n    return ret;\n  }\n};\n\ntemplate <typename MSR> class rawmsr_policy : MSR {\n  uint64_t global_ctrl_;\n\npublic:\n  rawmsr_policy() : global_ctrl_(this->rdmsr(IA32_PERF_GLOBAL_CTRL)) {\n    // pmu_info(static_cast<MSR&>(*this));\n  }\n  ~rawmsr_policy() { this->wrmsr(IA32_PERF_GLOBAL_CTRL, global_ctrl_); }\n  int init(const int i, const uint64_t config) {\n    const uint64_t v = (1 << 22) | (1 << 16) | config;\n    this->wrmsr(IA32_PERFEVTSEL_BASE + static_cast<uint32_t>(i), v);\n    return 0;\n  }\n\n  void reset(const int i) {\n    this->wrmsr(IA32_PMC_BASE + static_cast<uint32_t>(i), 0);\n  }\n  void start(const unsigned long mask) {\n    this->wrmsr(IA32_PERF_GLOBAL_OVF_CTRL, 0);\n    this->wrmsr(IA32_PERF_GLOBAL_CTRL, mask);\n  }\n  void stop(const unsigned long /* mask */) {\n    this->wrmsr(IA32_PERF_GLOBAL_CTRL, 0);\n    const uint64_t ovf = this->rdmsr(IA32_PERF_GLOBAL_STATUS);\n    if (ovf) {\n      std::cout << \"Overflow: \" << std::hex << ovf << std::dec << std::endl;\n      this->wrmsr(IA32_PERF_GLOBAL_OVF_CTRL, 0);\n    }\n  }\n  /* Should be equivalent to rdpmc instruction */\n  uint64_t read(const unsigned i) { return this->rdmsr(IA32_PMC_BASE + i); }\n};\n\ntemplate <typename ACCESS> class msr_pmc final : ACCESS, public x86_pmc_base {\n  unsigned long active_mask_ = 0;\n  int active = 0;\n\npublic:\n  using resolver_type = resolver;\n\n  template <typename T> msr_pmc(const T &pmcs) {\n    for (const auto &pmc : pmcs) {\n      const auto err = ACCESS::init(active, pmc.data().config);\n      if (err) {\n        std::cerr << \"Error configuring PMU \" << pmc.name() << \" with \"\n                  << std::hex << pmc.data().config << std::dec << std::endl;\n        continue;\n      }\n      ++active;\n    }\n\n    active_mask_ = static_cast<unsigned long>((1 << active) - 1);\n  }\n\n  gsl::span<uint64_t>::index_type start(gsl::span<uint64_t>) override {\n    for (int i = 0; i < active; ++i) {\n      ACCESS::reset(i);\n    }\n    ACCESS::start(active_mask_);\n\n    return active;\n  }\n\n  gsl::span<uint64_t>::index_type stop(gsl::span<uint64_t> buf) override {\n    ACCESS::stop(active_mask_);\n    for (int i = 0; i < active; ++i) {\n      buf[i] = ACCESS::read(static_cast<uint32_t>(i));\n    }\n    return active;\n  }\n};\n\nusing mck_rawmsr = msr_pmc<rawmsr_policy<msr_mck>>;\nusing mck_mckmsr = msr_pmc<mck_mck_policy>;\nusing linux_rawmsr = msr_pmc<rawmsr_policy<msr_linux>>;\n\nclass linux_jevents final : public x86_pmc_base {\n  struct rdpmc_t {\n    struct rdpmc_ctx ctx;\n    int close = 0;\n\n    rdpmc_t(struct perf_event_attr attr) {\n      const int err = rdpmc_open_attr(&attr, &ctx, nullptr);\n      if (err) {\n        throw std::runtime_error(std::to_string(errno) + ' ' + strerror(errno));\n      }\n\n      close = 1;\n    }\n    ~rdpmc_t() {\n      if (close) {\n        rdpmc_close(&ctx);\n      }\n    }\n    rdpmc_t(const rdpmc_t &) = delete;\n    rdpmc_t(rdpmc_t &&rhs) {\n      this->ctx = rhs.ctx;\n      this->close = rhs.close;\n      rhs.close = 0;\n    }\n\n    uint64_t read() { return rdpmc_read(&ctx); }\n  };\n\n  std::vector<rdpmc_t> rdpmc_ctxs;\n\npublic:\n  using resolver_type = resolver;\n\n  template <typename T> linux_jevents(const T &pmcs) {\n    for (const auto &pmc : pmcs) {\n      rdpmc_ctxs.emplace_back(pmc.data());\n    }\n  }\n\n  gsl::span<uint64_t>::index_type start(gsl::span<uint64_t> buf) override {\n    int idx = 0;\n    for (auto &&pmc : rdpmc_ctxs) {\n      buf[idx] = pmc.read();\n      ++idx;\n    }\n    return idx;\n  }\n\n  gsl::span<uint64_t>::index_type stop(gsl::span<uint64_t> buf) override {\n    int idx = 0;\n    for (auto &&pmc : rdpmc_ctxs) {\n      buf[idx] = pmc.read() - buf[idx];\n      ++idx;\n    }\n    return idx;\n  }\n};\n\nclass linux_perf final : public x86_pmc_base {\n  std::vector<std::unique_ptr<fd>> perf_fds;\n\npublic:\n  using resolver_type = resolver;\n\n  template <typename T> linux_perf(const T &pmcs) {\n    for (const auto &pmc : pmcs) {\n      struct perf_event_attr pe;\n      memset(&pe, 0, sizeof(pe));\n      const auto &attr = pmc.data();\n      pe.config = attr.config;\n      pe.config1 = attr.config1;\n      pe.config2 = attr.config2;\n      pe.type = attr.type;\n      pe.size = attr.size;\n      // attr.disabled = 1;\n      pe.exclude_kernel = 1;\n      pe.exclude_hv = 1;\n      try {\n        perf_fds.push_back(make_perf_fd(pe));\n      } catch (const std::exception &e) {\n        std::cerr << pmc.name() << \": \" << e.what() << std::endl;\n      }\n    }\n  }\n\n  gsl::span<uint64_t>::index_type start(gsl::span<uint64_t>) override {\n    for (const auto &perf_fd : perf_fds) {\n      if (ioctl(static_cast<int>(*perf_fd), PERF_EVENT_IOC_RESET, 0)) {\n        std::cerr << \"Error in ioctl\\n\";\n      }\n    }\n\n    return static_cast<gsl::span<uint64_t>::index_type>(perf_fds.size());\n  }\n\n  gsl::span<uint64_t>::index_type stop(gsl::span<uint64_t> buf) override {\n    uint64_t v;\n    int idx = 0;\n    for (const auto &perf_fd : perf_fds) {\n      const auto ret = read(static_cast<int>(*perf_fd), &v, sizeof(v));\n      if (ret < 0) {\n        std::cerr << \"perf: Error reading performance counter: \" << errno\n                  << \": \" << strerror(errno) << std::endl;\n      } else if (ret != sizeof(v)) {\n        std::cerr << \"perf: Error reading \" << sizeof(v) << \" bytes.\"\n                  << std::endl;\n      }\n      buf[idx] = v;\n      ++idx;\n    }\n    return idx;\n  }\n};\n\ntemplate <typename MCK, typename LINUX>\nclass x86_linux_mckernel : public x86_64_base_pmu {\n  std::unique_ptr<x86_pmc_base> backend_;\n\npublic:\n  using resolver_type = resolver;\n\n  template <typename T>\n  x86_linux_mckernel(const T &pmcs)\n      : backend_(mck_is_mckernel() ? static_cast<std::unique_ptr<x86_pmc_base>>(\n                                         std::make_unique<MCK>(pmcs))\n                                   : static_cast<std::unique_ptr<x86_pmc_base>>(\n                                         std::make_unique<LINUX>(pmcs))) {}\n\n  auto start(gsl::span<uint64_t> o) { return backend_->start(o); }\n  auto stop(gsl::span<uint64_t> o) { return backend_->stop(o); }\n};\n\n#else\n\nstruct Reason {\n  static constexpr const char reason[] =\n      \"PMC support not compiled in; libjevents missing\";\n};\n\nclass x86_64_pmu : public x86_64_base_pmu {\npublic:\n  using resolver_type = upca::arch::detail::null_resolver<Reason>;\n  template <typename T> x86_64_pmu(const T &) {}\n\n  gsl::span<uint64_t>::index_type start(gsl::span<uint64_t>) { return 0; }\n  gsl::span<uint64_t>::index_type stop(gsl::span<uint64_t>) { return 0; }\n};\n\n#endif /* JEVENTS_FOUND */\n\n} // namespace x86_64\n} // namespace arch\n} // namespace upca\n\n", "meta": {"hexsha": "b2327a1121c075998f385161d92a7db90058ca7c", "size": 14266, "ext": "h", "lang": "C", "max_stars_repo_path": "include/upca/arch/x86_64.h", "max_stars_repo_name": "hannesweisbach/ucpa", "max_stars_repo_head_hexsha": "e4062fd98d83f4cc57ee04f554540c09c1ca8ccd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-08-31T13:51:26.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-31T13:51:26.000Z", "max_issues_repo_path": "include/upca/arch/x86_64.h", "max_issues_repo_name": "hannesweisbach/ucpa", "max_issues_repo_head_hexsha": "e4062fd98d83f4cc57ee04f554540c09c1ca8ccd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/upca/arch/x86_64.h", "max_forks_repo_name": "hannesweisbach/ucpa", "max_forks_repo_head_hexsha": "e4062fd98d83f4cc57ee04f554540c09c1ca8ccd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2251908397, "max_line_length": 88, "alphanum_fraction": 0.6044441329, "num_tokens": 4351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12252321892633067, "lm_q2_score": 0.02843603623537837, "lm_q1q2_score": 0.0034840746930643357}}
{"text": "#pragma once\n#include <gsl/span>\n#include \"halley/data_structures/vector.h\"\n#include \"component_schema.h\"\n#include \"custom_type_schema.h\"\n#include \"halley/data_structures/hash_map.h\"\n#include \"halley/text/halleystring.h\"\n#include \"message_schema.h\"\n#include \"system_message_schema.h\"\n#include \"system_schema.h\"\n\nnamespace YAML\n{\n\tclass Node;\n}\n\nnamespace Halley {\n\tstruct CodegenSourceInfo {\n\t\tString filename;\n\t\tgsl::span<const gsl::byte> data;\n\t\tbool generate = false;\n\t};\n\n\tclass Codegen;\n\t\n    class ECSData {\n    public:\n\t\tvoid loadSources(Vector<CodegenSourceInfo> files);\n\n\t\tconst HashMap<String, ComponentSchema>& getComponents() const;\n\t\tconst HashMap<String, SystemSchema>& getSystems() const;\n\t\tconst HashMap<String, MessageSchema>& getMessages() const;\n\t\tconst HashMap<String, SystemMessageSchema>& getSystemMessages() const;\n\t\tconst HashMap<String, CustomTypeSchema>& getCustomTypes() const;\n\n    \tvoid clear();\n\t\tint getRevision() const;\n\n\tprivate:\n    \tvoid addSource(CodegenSourceInfo sourceInfo);\n\t\tvoid addComponent(YAML::Node rootNode, bool generate);\n\t\tvoid addSystem(YAML::Node rootNode, bool generate);\n\t\tvoid addMessage(YAML::Node rootNode, bool generate);\n    \tvoid addSystemMessage(YAML::Node rootNode, bool generate);\n\t\tvoid addType(YAML::Node rootNode);\n\t\tString getInclude(String typeName) const;\n\n    \tvoid validate();\n\t\tvoid process();\n\n    \tHashMap<String, ComponentSchema> components;\n\t\tHashMap<String, SystemSchema> systems;\n\t\tHashMap<String, MessageSchema> messages;\n    \tHashMap<String, SystemMessageSchema> systemMessages;\n\t\tHashMap<String, CustomTypeSchema> types;\n\t\tint revision = 0;\n    };\n}\n", "meta": {"hexsha": "e53befdc4674af2306603ab78c8450f6e645c3ed", "size": 1631, "ext": "h", "lang": "C", "max_stars_repo_path": "src/tools/tools/include/halley/tools/ecs/ecs_data.h", "max_stars_repo_name": "amrezzd/halley", "max_stars_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tools/tools/include/halley/tools/ecs/ecs_data.h", "max_issues_repo_name": "amrezzd/halley", "max_issues_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tools/tools/include/halley/tools/ecs/ecs_data.h", "max_forks_repo_name": "amrezzd/halley", "max_forks_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6440677966, "max_line_length": 72, "alphanum_fraction": 0.7486204782, "num_tokens": 371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1441488530327406, "lm_q2_score": 0.024053552894426174, "lm_q1q2_score": 0.003467292061093891}}
{"text": "#pragma once\n\n#include <string_view>\n#include <gsl/span>\n#include <spirv_cross.hpp>\n\nnamespace glslang\n{\n    class TShader;\n}\n\nnamespace Babylon\n{\n    class ShaderCompiler\n    {\n    public:\n        ShaderCompiler();\n        ~ShaderCompiler();\n\n        struct ShaderInfo\n        {\n            std::unique_ptr<const spirv_cross::Compiler> Compiler;\n            gsl::span<uint8_t> Bytes;\n        };\n\n        void Compile(std::string_view vertexSource, std::string_view fragmentSource, std::function<void(ShaderInfo, ShaderInfo)> onCompiled);\n\n    protected:\n        // Invert dFdy operands similar to bgfx_shader.sh\n        // https://github.com/bkaradzic/bgfx/blob/7be225bf490bb1cd231cfb4abf7e617bf35b59cb/src/bgfx_shader.sh#L44-L45\n        // https://github.com/bkaradzic/bgfx/blob/7be225bf490bb1cd231cfb4abf7e617bf35b59cb/src/bgfx_shader.sh#L62-L65\n        static void InvertYDerivativeOperands(glslang::TShader& shader);\n    };\n}\n", "meta": {"hexsha": "9cf0d126cffce4d3585e87caa8798d562c579624", "size": 931, "ext": "h", "lang": "C", "max_stars_repo_path": "Library/Source/ShaderCompiler.h", "max_stars_repo_name": "zloop1982/BabylonNative", "max_stars_repo_head_hexsha": "dc15fbde9eb8df3f72d4d14aa8f896341005aea2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Library/Source/ShaderCompiler.h", "max_issues_repo_name": "zloop1982/BabylonNative", "max_issues_repo_head_hexsha": "dc15fbde9eb8df3f72d4d14aa8f896341005aea2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Library/Source/ShaderCompiler.h", "max_forks_repo_name": "zloop1982/BabylonNative", "max_forks_repo_head_hexsha": "dc15fbde9eb8df3f72d4d14aa8f896341005aea2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6, "max_line_length": 141, "alphanum_fraction": 0.6874328679, "num_tokens": 256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19193277720287888, "lm_q2_score": 0.01798621292303366, "lm_q1q2_score": 0.0034521437976801606}}
{"text": "//\n//  Engine.hpp\n//  PretendToWork\n//\n//  Created by tqtifnypmb on 14/12/2017.\n//  Copyright \u00a9 2017 tqtifnypmb. All rights reserved.\n//\n\n#pragma once\n\n#include \"../rope/Rope.h\"\n#include \"../types.h\"\n#include \"Revision.h\"\n\n#include <gsl/gsl>\n#include <vector>\n#include <map>\n\nnamespace brick\n{\n   \nclass Engine {\npublic:\n    using DeltaList = std::vector<Revision>;\n    \n    Engine(size_t authorId, gsl::not_null<Rope*> rope);\n    \n    template <class Converter>\n    void insert(gsl::span<const char> bytes, size_t pos);\n    void insert(const detail::CodePointList& cplist, size_t pos);\n    \n    void erase(const Range& range);\n    \n    std::pair<DeltaList, DeltaList> sync(Engine& other);\n    \n    void fastForward(const std::vector<Revision>& revs);\n    \n    const std::vector<Revision>& revisions() const {\n        return revisions_;\n    }\n    \n    std::vector<Revision>& revisions() {\n        return revisions_;\n    }\n    \n    size_t authorId() const {\n        return authorId_;\n    }\n    \n    size_t nextRevId() {\n        return revId_++;\n    }\n    \nprivate:\n    Revision delta(const Revision& history, Revision& rev);\n    std::vector<Revision> delta(Revision& rev);\n    \n    void appendRevision(Revision rev);\n    bool appendRevision(Revision rev, bool pendingRev, std::vector<Revision>* deltas);\n    std::pair<DeltaList, DeltaList> sync(Engine& other, bool symetric);\n    \n    gsl::not_null<Rope*> rope_;\n    std::vector<Revision> revisions_;\n    std::vector<Revision> pendingRevs_;\n    std::map<size_t, std::pair<size_t, size_t>> sync_state_;\n    \n    size_t authorId_;\n    size_t revId_;\n};\n    \ntemplate <class Converter>\nvoid Engine::insert(gsl::span<const char> bytes, size_t pos) {\n    return insert(Converter::encode(bytes), pos);\n}\n    \n}   // namespace brick\n", "meta": {"hexsha": "1dae3cb7a6fc570a07749a7d3a14ced553c64897", "size": 1775, "ext": "h", "lang": "C", "max_stars_repo_path": "src/crdt/Engine.h", "max_stars_repo_name": "tqtifnypmb/brick", "max_stars_repo_head_hexsha": "49398f77113c57d4e256e838a5ad6b9a6381de6a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/crdt/Engine.h", "max_issues_repo_name": "tqtifnypmb/brick", "max_issues_repo_head_hexsha": "49398f77113c57d4e256e838a5ad6b9a6381de6a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/crdt/Engine.h", "max_forks_repo_name": "tqtifnypmb/brick", "max_forks_repo_head_hexsha": "49398f77113c57d4e256e838a5ad6b9a6381de6a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0519480519, "max_line_length": 86, "alphanum_fraction": 0.6461971831, "num_tokens": 462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19930799790404563, "lm_q2_score": 0.017176708855095604, "lm_q1q2_score": 0.0034234554524897967}}
{"text": "/* matrix/gsl_matrix_uchar.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_MATRIX_UCHAR_H__\n#define __GSL_MATRIX_UCHAR_H__\n\n#if !defined( GSL_FUN )\n#  if !defined( GSL_DLL )\n#    define GSL_FUN extern\n#  elif defined( BUILD_GSL_DLL )\n#    define GSL_FUN extern __declspec(dllexport)\n#  else\n#    define GSL_FUN extern __declspec(dllimport)\n#  endif\n#endif\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_inline.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_vector_uchar.h>\n#include <gsl/gsl_blas_types.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size1;\n  size_t size2;\n  size_t tda;\n  unsigned char * data;\n  gsl_block_uchar * block;\n  int owner;\n} gsl_matrix_uchar;\n\ntypedef struct\n{\n  gsl_matrix_uchar matrix;\n} _gsl_matrix_uchar_view;\n\ntypedef _gsl_matrix_uchar_view gsl_matrix_uchar_view;\n\ntypedef struct\n{\n  gsl_matrix_uchar matrix;\n} _gsl_matrix_uchar_const_view;\n\ntypedef const _gsl_matrix_uchar_const_view gsl_matrix_uchar_const_view;\n\n/* Allocation */\n\nGSL_FUN gsl_matrix_uchar * \ngsl_matrix_uchar_alloc (const size_t n1, const size_t n2);\n\nGSL_FUN gsl_matrix_uchar * \ngsl_matrix_uchar_calloc (const size_t n1, const size_t n2);\n\nGSL_FUN gsl_matrix_uchar * \ngsl_matrix_uchar_alloc_from_block (gsl_block_uchar * b, \n                                   const size_t offset, \n                                   const size_t n1, \n                                   const size_t n2, \n                                   const size_t d2);\n\nGSL_FUN gsl_matrix_uchar * \ngsl_matrix_uchar_alloc_from_matrix (gsl_matrix_uchar * m,\n                                    const size_t k1, \n                                    const size_t k2,\n                                    const size_t n1, \n                                    const size_t n2);\n\nGSL_FUN gsl_vector_uchar * \ngsl_vector_uchar_alloc_row_from_matrix (gsl_matrix_uchar * m,\n                                        const size_t i);\n\nGSL_FUN gsl_vector_uchar * \ngsl_vector_uchar_alloc_col_from_matrix (gsl_matrix_uchar * m,\n                                        const size_t j);\n\nGSL_FUN void gsl_matrix_uchar_free (gsl_matrix_uchar * m);\n\n/* Views */\n\nGSL_FUN _gsl_matrix_uchar_view \ngsl_matrix_uchar_submatrix (gsl_matrix_uchar * m, \n                            const size_t i, const size_t j, \n                            const size_t n1, const size_t n2);\n\nGSL_FUN _gsl_vector_uchar_view \ngsl_matrix_uchar_row (gsl_matrix_uchar * m, const size_t i);\n\nGSL_FUN _gsl_vector_uchar_view \ngsl_matrix_uchar_column (gsl_matrix_uchar * m, const size_t j);\n\nGSL_FUN _gsl_vector_uchar_view \ngsl_matrix_uchar_diagonal (gsl_matrix_uchar * m);\n\nGSL_FUN _gsl_vector_uchar_view \ngsl_matrix_uchar_subdiagonal (gsl_matrix_uchar * m, const size_t k);\n\nGSL_FUN _gsl_vector_uchar_view \ngsl_matrix_uchar_superdiagonal (gsl_matrix_uchar * m, const size_t k);\n\nGSL_FUN _gsl_vector_uchar_view\ngsl_matrix_uchar_subrow (gsl_matrix_uchar * m, const size_t i,\n                         const size_t offset, const size_t n);\n\nGSL_FUN _gsl_vector_uchar_view\ngsl_matrix_uchar_subcolumn (gsl_matrix_uchar * m, const size_t j,\n                            const size_t offset, const size_t n);\n\nGSL_FUN _gsl_matrix_uchar_view\ngsl_matrix_uchar_view_array (unsigned char * base,\n                             const size_t n1, \n                             const size_t n2);\n\nGSL_FUN _gsl_matrix_uchar_view\ngsl_matrix_uchar_view_array_with_tda (unsigned char * base, \n                                      const size_t n1, \n                                      const size_t n2,\n                                      const size_t tda);\n\n\nGSL_FUN _gsl_matrix_uchar_view\ngsl_matrix_uchar_view_vector (gsl_vector_uchar * v,\n                              const size_t n1, \n                              const size_t n2);\n\nGSL_FUN _gsl_matrix_uchar_view\ngsl_matrix_uchar_view_vector_with_tda (gsl_vector_uchar * v,\n                                       const size_t n1, \n                                       const size_t n2,\n                                       const size_t tda);\n\n\nGSL_FUN _gsl_matrix_uchar_const_view \ngsl_matrix_uchar_const_submatrix (const gsl_matrix_uchar * m, \n                                  const size_t i, const size_t j, \n                                  const size_t n1, const size_t n2);\n\nGSL_FUN _gsl_vector_uchar_const_view \ngsl_matrix_uchar_const_row (const gsl_matrix_uchar * m, \n                            const size_t i);\n\nGSL_FUN _gsl_vector_uchar_const_view \ngsl_matrix_uchar_const_column (const gsl_matrix_uchar * m, \n                               const size_t j);\n\nGSL_FUN _gsl_vector_uchar_const_view\ngsl_matrix_uchar_const_diagonal (const gsl_matrix_uchar * m);\n\nGSL_FUN _gsl_vector_uchar_const_view \ngsl_matrix_uchar_const_subdiagonal (const gsl_matrix_uchar * m, \n                                    const size_t k);\n\nGSL_FUN _gsl_vector_uchar_const_view \ngsl_matrix_uchar_const_superdiagonal (const gsl_matrix_uchar * m, \n                                      const size_t k);\n\nGSL_FUN _gsl_vector_uchar_const_view\ngsl_matrix_uchar_const_subrow (const gsl_matrix_uchar * m, const size_t i,\n                               const size_t offset, const size_t n);\n\nGSL_FUN _gsl_vector_uchar_const_view\ngsl_matrix_uchar_const_subcolumn (const gsl_matrix_uchar * m, const size_t j,\n                                  const size_t offset, const size_t n);\n\nGSL_FUN _gsl_matrix_uchar_const_view\ngsl_matrix_uchar_const_view_array (const unsigned char * base,\n                                   const size_t n1, \n                                   const size_t n2);\n\nGSL_FUN _gsl_matrix_uchar_const_view\ngsl_matrix_uchar_const_view_array_with_tda (const unsigned char * base, \n                                            const size_t n1, \n                                            const size_t n2,\n                                            const size_t tda);\n\nGSL_FUN _gsl_matrix_uchar_const_view\ngsl_matrix_uchar_const_view_vector (const gsl_vector_uchar * v,\n                                    const size_t n1, \n                                    const size_t n2);\n\nGSL_FUN _gsl_matrix_uchar_const_view\ngsl_matrix_uchar_const_view_vector_with_tda (const gsl_vector_uchar * v,\n                                             const size_t n1, \n                                             const size_t n2,\n                                             const size_t tda);\n\n/* Operations */\n\nGSL_FUN void gsl_matrix_uchar_set_zero (gsl_matrix_uchar * m);\nGSL_FUN void gsl_matrix_uchar_set_identity (gsl_matrix_uchar * m);\nGSL_FUN void gsl_matrix_uchar_set_all (gsl_matrix_uchar * m, unsigned char x);\n\nGSL_FUN int gsl_matrix_uchar_fread (FILE * stream, gsl_matrix_uchar * m) ;\nGSL_FUN int gsl_matrix_uchar_fwrite (FILE * stream, const gsl_matrix_uchar * m) ;\nGSL_FUN int gsl_matrix_uchar_fscanf (FILE * stream, gsl_matrix_uchar * m);\nGSL_FUN int gsl_matrix_uchar_fprintf (FILE * stream, const gsl_matrix_uchar * m, const char * format);\n \nGSL_FUN int gsl_matrix_uchar_memcpy(gsl_matrix_uchar * dest, const gsl_matrix_uchar * src);\nGSL_FUN int gsl_matrix_uchar_swap(gsl_matrix_uchar * m1, gsl_matrix_uchar * m2);\nGSL_FUN int gsl_matrix_uchar_tricpy(CBLAS_UPLO_t Uplo, CBLAS_DIAG_t Diag, gsl_matrix_uchar * dest, const gsl_matrix_uchar * src);\n\nGSL_FUN int gsl_matrix_uchar_swap_rows(gsl_matrix_uchar * m, const size_t i, const size_t j);\nGSL_FUN int gsl_matrix_uchar_swap_columns(gsl_matrix_uchar * m, const size_t i, const size_t j);\nGSL_FUN int gsl_matrix_uchar_swap_rowcol(gsl_matrix_uchar * m, const size_t i, const size_t j);\nGSL_FUN int gsl_matrix_uchar_transpose (gsl_matrix_uchar * m);\nGSL_FUN int gsl_matrix_uchar_transpose_memcpy (gsl_matrix_uchar * dest, const gsl_matrix_uchar * src);\nGSL_FUN int gsl_matrix_uchar_transpose_tricpy (CBLAS_UPLO_t Uplo_src, CBLAS_DIAG_t Diag, gsl_matrix_uchar * dest, const gsl_matrix_uchar * src);\n\nGSL_FUN unsigned char gsl_matrix_uchar_max (const gsl_matrix_uchar * m);\nGSL_FUN unsigned char gsl_matrix_uchar_min (const gsl_matrix_uchar * m);\nGSL_FUN void gsl_matrix_uchar_minmax (const gsl_matrix_uchar * m, unsigned char * min_out, unsigned char * max_out);\n\nGSL_FUN void gsl_matrix_uchar_max_index (const gsl_matrix_uchar * m, size_t * imax, size_t *jmax);\nGSL_FUN void gsl_matrix_uchar_min_index (const gsl_matrix_uchar * m, size_t * imin, size_t *jmin);\nGSL_FUN void gsl_matrix_uchar_minmax_index (const gsl_matrix_uchar * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);\n\nGSL_FUN int gsl_matrix_uchar_equal (const gsl_matrix_uchar * a, const gsl_matrix_uchar * b);\n\nGSL_FUN int gsl_matrix_uchar_isnull (const gsl_matrix_uchar * m);\nGSL_FUN int gsl_matrix_uchar_ispos (const gsl_matrix_uchar * m);\nGSL_FUN int gsl_matrix_uchar_isneg (const gsl_matrix_uchar * m);\nGSL_FUN int gsl_matrix_uchar_isnonneg (const gsl_matrix_uchar * m);\n\nGSL_FUN unsigned char gsl_matrix_uchar_norm1 (const gsl_matrix_uchar * m);\n\nGSL_FUN int gsl_matrix_uchar_add (gsl_matrix_uchar * a, const gsl_matrix_uchar * b);\nGSL_FUN int gsl_matrix_uchar_sub (gsl_matrix_uchar * a, const gsl_matrix_uchar * b);\nGSL_FUN int gsl_matrix_uchar_mul_elements (gsl_matrix_uchar * a, const gsl_matrix_uchar * b);\nGSL_FUN int gsl_matrix_uchar_div_elements (gsl_matrix_uchar * a, const gsl_matrix_uchar * b);\nGSL_FUN int gsl_matrix_uchar_scale (gsl_matrix_uchar * a, const double x);\nGSL_FUN int gsl_matrix_uchar_scale_rows (gsl_matrix_uchar * a, const gsl_vector_uchar * x);\nGSL_FUN int gsl_matrix_uchar_scale_columns (gsl_matrix_uchar * a, const gsl_vector_uchar * x);\nGSL_FUN int gsl_matrix_uchar_add_constant (gsl_matrix_uchar * a, const double x);\nGSL_FUN int gsl_matrix_uchar_add_diagonal (gsl_matrix_uchar * a, const double x);\n\n/***********************************************************************/\n/* The functions below are obsolete                                    */\n/***********************************************************************/\nGSL_FUN int gsl_matrix_uchar_get_row(gsl_vector_uchar * v, const gsl_matrix_uchar * m, const size_t i);\nGSL_FUN int gsl_matrix_uchar_get_col(gsl_vector_uchar * v, const gsl_matrix_uchar * m, const size_t j);\nGSL_FUN int gsl_matrix_uchar_set_row(gsl_matrix_uchar * m, const size_t i, const gsl_vector_uchar * v);\nGSL_FUN int gsl_matrix_uchar_set_col(gsl_matrix_uchar * m, const size_t j, const gsl_vector_uchar * v);\n/***********************************************************************/\n\n/* inline functions if you are using GCC */\n\nGSL_FUN INLINE_DECL unsigned char   gsl_matrix_uchar_get(const gsl_matrix_uchar * m, const size_t i, const size_t j);\nGSL_FUN INLINE_DECL void    gsl_matrix_uchar_set(gsl_matrix_uchar * m, const size_t i, const size_t j, const unsigned char x);\nGSL_FUN INLINE_DECL unsigned char * gsl_matrix_uchar_ptr(gsl_matrix_uchar * m, const size_t i, const size_t j);\nGSL_FUN INLINE_DECL const unsigned char * gsl_matrix_uchar_const_ptr(const gsl_matrix_uchar * m, const size_t i, const size_t j);\n\n#ifdef HAVE_INLINE\nINLINE_FUN \nunsigned char\ngsl_matrix_uchar_get(const gsl_matrix_uchar * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_VAL(\"first index out of range\", GSL_EINVAL, 0) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_VAL(\"second index out of range\", GSL_EINVAL, 0) ;\n        }\n    }\n#endif\n  return m->data[i * m->tda + j] ;\n} \n\nINLINE_FUN \nvoid\ngsl_matrix_uchar_set(gsl_matrix_uchar * m, const size_t i, const size_t j, const unsigned char x)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_VOID(\"first index out of range\", GSL_EINVAL) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_VOID(\"second index out of range\", GSL_EINVAL) ;\n        }\n    }\n#endif\n  m->data[i * m->tda + j] = x ;\n}\n\nINLINE_FUN \nunsigned char *\ngsl_matrix_uchar_ptr(gsl_matrix_uchar * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n        }\n    }\n#endif\n  return (unsigned char *) (m->data + (i * m->tda + j)) ;\n} \n\nINLINE_FUN \nconst unsigned char *\ngsl_matrix_uchar_const_ptr(const gsl_matrix_uchar * m, const size_t i, const size_t j)\n{\n#if GSL_RANGE_CHECK\n  if (GSL_RANGE_COND(1)) \n    {\n      if (i >= m->size1)\n        {\n          GSL_ERROR_NULL(\"first index out of range\", GSL_EINVAL) ;\n        }\n      else if (j >= m->size2)\n        {\n          GSL_ERROR_NULL(\"second index out of range\", GSL_EINVAL) ;\n        }\n    }\n#endif\n  return (const unsigned char *) (m->data + (i * m->tda + j)) ;\n} \n\n#endif\n\n__END_DECLS\n\n#endif /* __GSL_MATRIX_UCHAR_H__ */\n", "meta": {"hexsha": "f04b31f19fedaccd68095c30fc84caf4847dbf6e", "size": 13818, "ext": "h", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_matrix_uchar.h", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_matrix_uchar.h", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_matrix_uchar.h", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5489130435, "max_line_length": 144, "alphanum_fraction": 0.6742654509, "num_tokens": 3592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1645164506075047, "lm_q2_score": 0.02064593107817719, "lm_q1q2_score": 0.003396595300468884}}
{"text": "#pragma once\n\n#include <gsl/span>\n\nnamespace CesiumUtility {\n/**\n * @brief This function converts between span types. This function\n * has the same rules with C++ reintepret_cast\n * https://en.cppreference.com/w/cpp/language/reinterpret_cast. So please use it\n * carefully\n */\ntemplate <typename To, typename From>\ngsl::span<To> reintepretCastSpan(const gsl::span<From>& from) noexcept {\n  return gsl::span<To>(\n      reinterpret_cast<To*>(from.data()),\n      from.size() * sizeof(From) / sizeof(To));\n}\n} // namespace CesiumUtility\n", "meta": {"hexsha": "84fddffb03ba72e236a0aef4ffec7fb324f54c43", "size": 533, "ext": "h", "lang": "C", "max_stars_repo_path": "CesiumUtility/include/CesiumUtility/SpanHelper.h", "max_stars_repo_name": "yieryi/cesium-native", "max_stars_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 154.0, "max_stars_repo_stars_event_min_datetime": "2021-03-30T14:08:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T00:01:43.000Z", "max_issues_repo_path": "CesiumUtility/include/CesiumUtility/SpanHelper.h", "max_issues_repo_name": "yieryi/cesium-native", "max_issues_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 256.0, "max_issues_repo_issues_event_min_datetime": "2021-03-30T18:12:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:44:21.000Z", "max_forks_repo_path": "CesiumUtility/include/CesiumUtility/SpanHelper.h", "max_forks_repo_name": "yieryi/cesium-native", "max_forks_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 66.0, "max_forks_repo_forks_event_min_datetime": "2021-03-30T15:14:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T13:38:41.000Z", "avg_line_length": 28.0526315789, "max_line_length": 80, "alphanum_fraction": 0.712945591, "num_tokens": 134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.10521054231434403, "lm_q2_score": 0.03210070764297384, "lm_q1q2_score": 0.003377332859791486}}
{"text": "#ifndef IOSLICEMUT_H\n#define IOSLICEMUT_H\n\n#include <WinSock2.h>\n\n#include <variant>\n#include <gsl/span>\n\nnamespace laio {\n\n    template<typename T>\n    using Result = std::variant<T, std::exception>;\n\n    namespace net {\n\n        class IoSpanMut {\n            WSABUF _raw_wsa_buffer;\n        public:\n            explicit constexpr IoSpanMut(const WSABUF& wsaBuffer) noexcept\n                : _raw_wsa_buffer{wsaBuffer} {}\n\n            explicit constexpr IoSpanMut(WSABUF&& wsaBuffer) noexcept\n                : _raw_wsa_buffer{std::move(wsaBuffer)} {}  // NOLINT(hicpp-move-const-arg,performance-move-const-arg)\n\n            static inline IoSpanMut create(unsigned char buf[]) noexcept {\n                static_assert(sizeof(*buf) <= (std::numeric_limits<ULONG>::max)());\n\n                // Seriously? Casting an unsigned char to a signed char?\n                // Well behaved for all 128 ASCII characters - Blows up for any value lesser than 0 or greater than 127\n                return IoSpanMut{std::move(WSABUF{  // NOLINT(hicpp-move-const-arg,performance-move-const-arg)\n                    sizeof(*buf),\n                    reinterpret_cast<CHAR*>(buf),\n                })};\n            }\n\n            inline Result<std::monostate> advance(std::size_t n) noexcept {\n                if (static_cast<std::size_t>(sizeof(_raw_wsa_buffer.len)) < n) {\n                    return std::out_of_range(\"Advancing out of range\");\n                }\n                _raw_wsa_buffer.len -= static_cast<ULONG>(n);\n                _raw_wsa_buffer.buf += n;\n                return std::monostate{};\n            }\n\n            inline gsl::span<const unsigned char> as_span() noexcept {\n                return gsl::span<const unsigned char>{\n                    reinterpret_cast<const unsigned char*>(_raw_wsa_buffer.buf),\n                    static_cast<int>(_raw_wsa_buffer.len)\n                };\n            }\n\n            inline gsl::span<unsigned char> as_mut_span() noexcept {\n                return gsl::span<unsigned char>{\n                    reinterpret_cast<unsigned char*>(_raw_wsa_buffer.buf),\n                    static_cast<int>(_raw_wsa_buffer.len)\n                };\n            }\n        };\n\n    } // namespace net\n\n} // namespace laio\n\n#endif // IOSLICEMUT_H\n", "meta": {"hexsha": "ff99dfb9124ee395f0c372512204a21598aac0db", "size": 2269, "ext": "h", "lang": "C", "max_stars_repo_path": "src/laio_net/utils/IoSpanMut.h", "max_stars_repo_name": "mjptree/laio", "max_stars_repo_head_hexsha": "b94040757213b77639c7ea368b2efa83ca71b164", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/laio_net/utils/IoSpanMut.h", "max_issues_repo_name": "mjptree/laio", "max_issues_repo_head_hexsha": "b94040757213b77639c7ea368b2efa83ca71b164", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/laio_net/utils/IoSpanMut.h", "max_forks_repo_name": "mjptree/laio", "max_forks_repo_head_hexsha": "b94040757213b77639c7ea368b2efa83ca71b164", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9076923077, "max_line_length": 119, "alphanum_fraction": 0.5650066108, "num_tokens": 503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11124121240045179, "lm_q2_score": 0.030214583574363407, "lm_q1q2_score": 0.0033611069089869616}}
{"text": "#pragma once\n#include \"common/to_do.h\"\n#include \"open_file.h\"\n#include \"trees/regular_file.h\"\n#include <gsl/span>\n\nnamespace dogbox::tree\n{\n    enum class read_caching\n    {\n        none,\n        one_piece\n    };\n\n    inline std::ostream &operator<<(std::ostream &out, read_caching const printed)\n    {\n        switch (printed)\n        {\n        case read_caching::none:\n            return out << \"none\";\n        case read_caching::one_piece:\n            return out << \"one_piece\";\n        }\n        TO_DO();\n    }\n\n    constexpr dogbox::tree::read_caching all_read_caching_modes[] = {\n        dogbox::tree::read_caching::none, dogbox::tree::read_caching::one_piece};\n\n    size_t read_file(open_file &file, sqlite3 &database, regular_file::length_type const offset,\n                     gsl::span<std::byte> const into, read_caching const caching);\n}\n", "meta": {"hexsha": "89f71973dee558301335799644e97a143bc371f2", "size": 851, "ext": "h", "lang": "C", "max_stars_repo_path": "trees/read_file.h", "max_stars_repo_name": "TyRoXx/dogbox", "max_stars_repo_head_hexsha": "af9c7631f6f5a22a73fbd4a497a84ed75183c7d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "trees/read_file.h", "max_issues_repo_name": "TyRoXx/dogbox", "max_issues_repo_head_hexsha": "af9c7631f6f5a22a73fbd4a497a84ed75183c7d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-09-02T20:36:02.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-02T20:36:02.000Z", "max_forks_repo_path": "trees/read_file.h", "max_forks_repo_name": "TyRoXx/dogbox", "max_forks_repo_head_hexsha": "af9c7631f6f5a22a73fbd4a497a84ed75183c7d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-08-29T22:01:48.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-29T22:01:48.000Z", "avg_line_length": 25.7878787879, "max_line_length": 96, "alphanum_fraction": 0.6192714454, "num_tokens": 207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1311732373477186, "lm_q2_score": 0.025565215732929476, "lm_q1q2_score": 0.003353472111181188}}
{"text": "#pragma once\n\n#include \"text_parser.h\"\n#include \"width_cache.h\"\n\n#include <string>\n#include <vector>\n\n#include <gsl/span>\n\nnamespace terminal_editor {\n\nenum class GraphemeKind {\n    NORMAL,      ///< Normal, displayable characters.\n    INVALID,     ///< Invalid characters for given encoding.\n    REPLACEMENT, ///< Replacement representation of valid (possibly control) characters (such as 4 spaces for tabs, or [NUL] for 0x00).\n};\n\n/// Each grapheme represents one logical 'image' on the screen.\n/// It can consist of many actual characters (either because we have combining characters, or because we replaced bytes with some special string, like \"[CR]\").\n/// It is produced from one or more bytes in the underlying byte data.\n/// It can have a width of 0 or more (either because actual characters take two columns, or because replacement string is longer, like \"[x66]\" or \"[TAB]\").\nstruct Grapheme {\n    GraphemeKind kind;    ///< Kind of grapheme: normal grapheme, invalid bytes or replacement.\n    std::string rendered; ///< Valid UTF-8 string to display on the screen.\n    std::string info;     ///< Valid UTF-8 string. Can contain arbitrary informational text about the grapheme. Will contain error description in case of invalid graphemes.\n    int width;            ///< Width (in terminal cells) of the 'rendered' string, once it will be displayed on the terminal.\n    gsl::span<const char> consumedInput; ///< Span of input data that was rendered into this grapheme.\n};\n\n/// Converts given span of CodePoinInfos into a Grapheme, by concatenating their representations.\n/// @param codePoinInfos    A span of CodePoinInfos.\n///                         @note If codePoinInfos is empty a NORMAL, but zero width grapheme is returned.\nGrapheme renderGrapheme(gsl::span<const CodePointInfo> codePointInfos);\n\n/// CodePointWidthCache used by renderLine().\n/// @todo This should not be a gloabl variable.\nextern CodePointWidthCache textRendererWidthCache;\n\n/// Renders data into Graphemes.\n/// Each byte of invalid CodePointInfos are rendered as separate graphemes.\n/// Valid CodePointInfos are grouped into maximal chunks where only first CodePointInfo can have non-zero wcwidth() (after processing replacements). One grapheme is created for\n/// each such group.\n/// @note Some resulting graphemes can have zero-width.\n/// @note Result can be empty.\n/// @note Width of characters is computed using global CodePointWidthCache.\n/// @param data     Input string to render. It is assumed to be in UTF-8, but can contain invalid characters (which will be rendered as special Graphemes).\n///                 @note Any control characters (including new line characters) will be rendered as a replacement string (i.e. [LF]).\nstd::vector<Grapheme> renderLine(gsl::span<CodePointInfo> codePointInfos);\n\n/// Returns concatenation of rendered property of all graphemes.\n/// @param graphemes    Span of graphemes to concatenate.\n/// @param useBrackets  If true all invalid and replacement sequences will be enclosed with brackets.\nstd::string renderGraphemes(gsl::span<const Grapheme> graphemes, bool useBrackets);\n\n/// Returns width of given text after rendering on screen.\n/// @note This functions takes into consideration replacement strings, and thus differs from wcswidth().\n/// @note This function is very slow, as it needs to convert text to graphemes first.\n/// @param text     UTF-8 string, can be invalid.\nint getRenderedWidth(gsl::span<const char> text);\n\n/// Returns width of given line of graphemes after rendering on screen.\n/// @param graphemes    A span of graphemes.\nint getRenderedWidth(gsl::span<const Grapheme> graphemes);\n\n} // namespace terminal_editor\n", "meta": {"hexsha": "35256836e9d3e9aa645f6b44fe428d03ec637321", "size": 3663, "ext": "h", "lang": "C", "max_stars_repo_path": "editorlib/text_renderer.h", "max_stars_repo_name": "Zbyl/terminal-editor", "max_stars_repo_head_hexsha": "375ac936f09543bab9c01fcb5a2dc8de9af83a58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "editorlib/text_renderer.h", "max_issues_repo_name": "Zbyl/terminal-editor", "max_issues_repo_head_hexsha": "375ac936f09543bab9c01fcb5a2dc8de9af83a58", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "editorlib/text_renderer.h", "max_forks_repo_name": "Zbyl/terminal-editor", "max_forks_repo_head_hexsha": "375ac936f09543bab9c01fcb5a2dc8de9af83a58", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-12-21T00:37:06.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-21T00:37:06.000Z", "avg_line_length": 54.671641791, "max_line_length": 176, "alphanum_fraction": 0.7414687415, "num_tokens": 807, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.162380052880696, "lm_q2_score": 0.020645931605446352, "lm_q1q2_score": 0.003352487465863612}}
{"text": "#ifndef TTT_UTIL_UTILITIES_H\n#define TTT_UTIL_UTILITIES_H\n\n#include <SDL_keyboard.h>\n\n#include <gsl/util>\n\nnamespace ttt::util\n{\n\t// Used to avoid having to cast std::size_t to gsl::index.\n\ttemplate<typename Container>\n\t[[nodiscard]] inline gsl::index getSize(const Container &container) noexcept\n\t{\n\t\treturn gsl::narrow_cast<gsl::index>(container.size());\n\t}\n}\n\n#endif", "meta": {"hexsha": "619440b130fe821d0f76796de6a6bf314893a3ca", "size": 369, "ext": "h", "lang": "C", "max_stars_repo_path": "Source/Utilities/Utilities.h", "max_stars_repo_name": "itsArtem/TicTacToe", "max_stars_repo_head_hexsha": "8c70a77e4603dd0ff22ec0621b978ec0685ec3cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Source/Utilities/Utilities.h", "max_issues_repo_name": "itsArtem/TicTacToe", "max_issues_repo_head_hexsha": "8c70a77e4603dd0ff22ec0621b978ec0685ec3cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/Utilities/Utilities.h", "max_forks_repo_name": "itsArtem/TicTacToe", "max_forks_repo_head_hexsha": "8c70a77e4603dd0ff22ec0621b978ec0685ec3cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.5, "max_line_length": 77, "alphanum_fraction": 0.7479674797, "num_tokens": 93, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06954174257744826, "lm_q2_score": 0.048136771628708996, "lm_q1q2_score": 0.003347514981113096}}
{"text": "/* Copyright (c) 2020 Felix Kutzner (github.com/fkutzner)\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n\n Except as contained in this notice, the name(s) of the above copyright holders\n shall not be used in advertising or otherwise to promote the sale, use or\n other dealings in this Software without prior written authorization.\n\n*/\n\n#pragma once\n\n#include <libincmonk/verifier/Clause.h>\n\n#include <cassert>\n#include <cstdint>\n#include <functional>\n#include <gsl/span>\n#include <iterator>\n#include <limits>\n#include <optional>\n#include <ostream>\n\n\n//\n// Implementation of inline function declared in Clause.h\n//\n\nnamespace incmonk::verifier {\n\nconstexpr Var::Var(uint32_t id) : m_rawValue(id) {}\n\nconstexpr Var::Var() : m_rawValue{0} {}\n\nconstexpr auto Var::getRawValue() const -> uint32_t\n{\n  return m_rawValue;\n}\n\nconstexpr auto Var::operator==(Var rhs) const -> bool\n{\n  return m_rawValue == rhs.m_rawValue;\n}\n\nconstexpr auto Var::operator!=(Var rhs) const -> bool\n{\n  return m_rawValue != rhs.m_rawValue;\n}\n\nconstexpr auto Var::operator<(Var rhs) const -> bool\n{\n  return m_rawValue < rhs.m_rawValue;\n}\n\nconstexpr auto Var::operator<=(Var rhs) const -> bool\n{\n  return m_rawValue <= rhs.m_rawValue;\n}\n\nconstexpr auto Var::operator>(Var rhs) const -> bool\n{\n  return m_rawValue > rhs.m_rawValue;\n}\n\nconstexpr auto Var::operator>=(Var rhs) const -> bool\n{\n  return m_rawValue >= rhs.m_rawValue;\n}\n\ninline auto operator\"\"_Var(unsigned long long cnfValue) -> Var\n{\n  return Var{static_cast<uint32_t>(cnfValue)};\n}\n\nconstexpr auto Key<Var>::get(Var const& item) -> std::size_t\n{\n  return item.getRawValue();\n}\n\nconstexpr Lit::Lit(Var v, bool positive) : m_rawValue{(v.getRawValue() << 1) + (positive ? 1 : 0)}\n{\n}\n\nconstexpr Lit::Lit() : m_rawValue{0} {}\n\nconstexpr auto Lit::getRawValue() const -> uint32_t\n{\n  return m_rawValue;\n}\n\nconstexpr auto Lit::getVar() const -> Var\n{\n  return Var{m_rawValue >> 1};\n}\n\nconstexpr auto Lit::isPositive() const -> bool\n{\n  return (m_rawValue & 1) == 1;\n}\n\nconstexpr auto Lit::operator-() const -> Lit\n{\n  return Lit{getVar(), !isPositive()};\n}\n\nconstexpr auto Lit::operator==(Lit rhs) const -> bool\n{\n  return m_rawValue == rhs.m_rawValue;\n}\n\nconstexpr auto Lit::operator!=(Lit rhs) const -> bool\n{\n  return m_rawValue != rhs.m_rawValue;\n}\n\nconstexpr auto Lit::operator<(Lit rhs) const -> bool\n{\n  return m_rawValue < rhs.m_rawValue;\n}\n\nconstexpr auto Lit::operator<=(Lit rhs) const -> bool\n{\n  return m_rawValue <= rhs.m_rawValue;\n}\n\nconstexpr auto Lit::operator>(Lit rhs) const -> bool\n{\n  return m_rawValue > rhs.m_rawValue;\n}\n\nconstexpr auto Lit::operator>=(Lit rhs) const -> bool\n{\n  return m_rawValue >= rhs.m_rawValue;\n}\n\ninline auto operator\"\"_Lit(unsigned long long cnfValue) -> Lit\n{\n  Var var{static_cast<uint32_t>(cnfValue)};\n  return Lit{var, cnfValue > 0};\n}\n\nconstexpr auto Key<Lit>::get(Lit const& item) -> std::size_t\n{\n  return item.getRawValue();\n}\n\ninline auto Clause::operator[](size_type idx) noexcept -> Lit&\n{\n  return *((&m_firstLit) + idx);\n}\n\ninline auto Clause::operator[](size_type idx) const noexcept -> Lit const&\n{\n  return *((&m_firstLit) + idx);\n}\n\ninline auto Clause::getLiterals() noexcept -> gsl::span<Lit>\n{\n  return gsl::span<Lit>{&m_firstLit, (&m_firstLit) + m_size};\n}\n\ninline auto Clause::getLiterals() const noexcept -> gsl::span<Lit const>\n{\n  return gsl::span<Lit const>{&m_firstLit, (&m_firstLit) + m_size};\n}\n\ninline auto Clause::size() const noexcept -> size_type\n{\n  return m_size;\n}\n\ninline auto Clause::empty() const noexcept -> bool\n{\n  return m_size == 0;\n}\n\ninline void Clause::setState(ClauseVerificationState state) noexcept\n{\n  uint8_t rawState = static_cast<uint8_t>(state);\n  m_flags = (m_flags & 0xFFFFFFFC) | rawState;\n}\n\ninline auto Clause::getState() const noexcept -> ClauseVerificationState\n{\n  return static_cast<ClauseVerificationState>(m_flags & 3);\n}\n\ninline auto Clause::getAddIdx() const noexcept -> ProofSequenceIdx\n{\n  return m_pointOfAdd;\n}\n\ninline Clause::Clause(size_type size,\n                      ClauseVerificationState initialState,\n                      ProofSequenceIdx addIdx) noexcept\n  : m_size{size}, m_pointOfAdd{addIdx}, m_firstLit{Var{0}, false}\n{\n  setState(initialState);\n}\n\ninline auto ClauseCollection::Ref::operator==(Ref rhs) const noexcept -> bool\n{\n  return m_offset == rhs.m_offset;\n}\n\ninline auto ClauseCollection::Ref::operator!=(Ref rhs) const noexcept -> bool\n{\n  return !(*this == rhs);\n}\n\ninline ClauseCollection::RefIterator::RefIterator(char const* m_allocatorMemory,\n                                                  std::size_t highWaterMark) noexcept\n  : m_clausePtr{m_allocatorMemory}, m_distanceToEnd{highWaterMark}, m_currentRef{}\n{\n  if (m_distanceToEnd == 0) {\n    m_clausePtr = nullptr;\n  }\n  // Otherwise, the iterator is valid and currentRef is 0, referring to the first clause\n}\n\ninline ClauseCollection::RefIterator::RefIterator() noexcept\n  : m_clausePtr{nullptr}, m_distanceToEnd{0}, m_currentRef{}\n{\n}\n\ninline auto ClauseCollection::RefIterator::operator*() const noexcept -> Ref const&\n{\n  assert(m_clausePtr != nullptr && \"Dereferencing a non-dereferencaable RefIterator\");\n  return m_currentRef;\n}\n\ninline auto ClauseCollection::RefIterator::operator->() const noexcept -> Ref const*\n{\n  assert(m_clausePtr != nullptr && \"Dereferencing a non-dereferencaable RefIterator\");\n  return &m_currentRef;\n}\n\ninline auto ClauseCollection::RefIterator::operator++(int) noexcept -> RefIterator\n{\n  RefIterator old = *this;\n  ++(*this);\n  return old;\n}\n\ninline auto ClauseCollection::RefIterator::operator==(RefIterator const& rhs) const noexcept -> bool\n{\n  return (this == &rhs) || (m_clausePtr == nullptr && rhs.m_clausePtr == nullptr) ||\n         (m_clausePtr == rhs.m_clausePtr && m_distanceToEnd == rhs.m_distanceToEnd &&\n          m_currentRef == rhs.m_currentRef);\n}\n\ninline auto ClauseCollection::RefIterator::operator!=(RefIterator const& rhs) const noexcept -> bool\n{\n  return !(*this == rhs);\n}\n\n}\n\nnamespace std {\ntemplate <>\nstruct hash<incmonk::verifier::Lit> {\n  auto operator()(incmonk::verifier::Lit lit) const noexcept -> std::size_t\n  {\n    return std::hash<uint32_t>{}(lit.getRawValue());\n  }\n};\n\ntemplate <>\nstruct hash<incmonk::verifier::Var> {\n  auto operator()(incmonk::verifier::Var var) const noexcept -> std::size_t\n  {\n    return std::hash<uint32_t>{}(var.getRawValue());\n  }\n};\n\ntemplate <>\nstruct hash<incmonk::verifier::ClauseCollection::Ref> {\n  auto operator()(incmonk::verifier::ClauseCollection::Ref ref) const noexcept -> std::size_t\n  {\n    return std::hash<std::size_t>{}(ref.m_offset);\n  }\n};\n}\n", "meta": {"hexsha": "8959ea394a7cb03afc8ec164cf9fd8bf6d4a2029", "size": 7582, "ext": "h", "lang": "C", "max_stars_repo_path": "lib/libincmonk/verifier/ClauseImpl.h", "max_stars_repo_name": "fkutzner/IncrementalMonkey", "max_stars_repo_head_hexsha": "fc87d8b408cd57a69f0c1bf3579ccbdfd60d7c13", "max_stars_repo_licenses": ["X11", "MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-12T17:58:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-12T17:58:09.000Z", "max_issues_repo_path": "lib/libincmonk/verifier/ClauseImpl.h", "max_issues_repo_name": "fkutzner/IncrementalMonkey", "max_issues_repo_head_hexsha": "fc87d8b408cd57a69f0c1bf3579ccbdfd60d7c13", "max_issues_repo_licenses": ["X11", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/libincmonk/verifier/ClauseImpl.h", "max_forks_repo_name": "fkutzner/IncrementalMonkey", "max_forks_repo_head_hexsha": "fc87d8b408cd57a69f0c1bf3579ccbdfd60d7c13", "max_forks_repo_licenses": ["X11", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2733333333, "max_line_length": 100, "alphanum_fraction": 0.712872593, "num_tokens": 1917, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1347759174229568, "lm_q2_score": 0.02479815866406449, "lm_q1q2_score": 0.003342194584349337}}
{"text": "/*\n   Copyright [2021] [IBM Corporation]\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n       http://www.apache.org/licenses/LICENSE-2.0\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\n#ifndef _MCAS_COMMON_BYTE_\n#define _MCAS_COMMON_BYTE_\n\n#include <cstddef>\n#include <gsl/gsl_byte>\n\n#ifndef MCAS_BYTE_USES_STD\n/* For compilation with C++14 use gsl::byte, not C++17 std::byte */\n#define MCAS_BYTE_USES_STD 0\n#endif\n\nnamespace common\n{\n#if MCAS_BYTE_USES_STD\n\tusing byte = std::byte;\n#else\n\tusing byte = gsl::byte; /* can be std::byte in C++17 */\n#endif\n}\n\n#endif\n", "meta": {"hexsha": "579212965336c483dc5decd6c94343bff8e59313", "size": 972, "ext": "h", "lang": "C", "max_stars_repo_path": "src/lib/common/include/common/byte.h", "max_stars_repo_name": "IBM/artemis", "max_stars_repo_head_hexsha": "f655d6e952577de11b52e2f4ab6f48c73ce5dba1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lib/common/include/common/byte.h", "max_issues_repo_name": "IBM/artemis", "max_issues_repo_head_hexsha": "f655d6e952577de11b52e2f4ab6f48c73ce5dba1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lib/common/include/common/byte.h", "max_forks_repo_name": "IBM/artemis", "max_forks_repo_head_hexsha": "f655d6e952577de11b52e2f4ab6f48c73ce5dba1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7714285714, "max_line_length": 75, "alphanum_fraction": 0.7397119342, "num_tokens": 239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1347759139476672, "lm_q2_score": 0.024798158033438156, "lm_q1q2_score": 0.0033421944131753127}}
{"text": "// SPDX-License-Identifier: MIT\n// The MIT License (MIT)\n//\n// Copyright (c) 2014-2018, Institute for Software & Systems Engineering\n// Copyright (c) 2018-2019, Johannes Leupolz\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n#ifndef PEMC_EXECUTABLE_MODEL_MODEL_EXECUTOR_H_\n#define PEMC_EXECUTABLE_MODEL_MODEL_EXECUTOR_H_\n\n#include <vector>\n#include <gsl/span>\n#include <cstdint>\n#include <atomic>\n#include <stack>\n#include <limits>\n#include <functional>\n\n#include \"pemc/basic/tsc_index.h\"\n#include \"pemc/basic/configuration.h\"\n#include \"pemc/basic/label.h\"\n#include \"pemc/basic/model_capacity.h\"\n#include \"pemc/basic/raw_memory.h\"\n#include \"pemc/formula/formula.h\"\n#include \"pemc/generic_traverser/i_transitions_calculator.h\"\n#include \"pemc/generic_traverser/i_pre_state_storage_modifier.h\"\n#include \"pemc/generic_traverser/i_post_state_storage_modifier.h\"\n#include \"pemc/executable_model/temporary_state_storage.h\"\n#include \"pemc/executable_model/i_choice_resolver.h\"\n#include \"pemc/executable_model/abstract_model.h\"\n\nnamespace pemc {\n\n  class ModelExecutor : public ITransitionsCalculator {\n  protected:\n      std::unique_ptr<IChoiceResolver> choiceResolver;\n      std::unique_ptr<AbstractModel> model;\n\n      // Create a storage for different state vectors and a vector of transitions\n      // that can be reused for different calculations. This should prevent garbage.\n      TemporaryStateStorage temporaryStateStorage;\n      std::vector<TraversalTransition> transitions;\n\n      int32_t preStateStorageModifierStateVectorSize = 0;\n\n      void addTransition();\n  public:\n      ModelExecutor(const Configuration& conf);\n\n      void setModel(std::unique_ptr<AbstractModel> _model);\n\n      void setChoiceResolver(std::unique_ptr<IChoiceResolver> _choiceResolver);\n\n      virtual int32_t getStateVectorSize();\n\n      virtual void setPreStateStorageModifierStateVectorSize(int32_t _preStateStorageModifierStateVectorSize);\n\n      virtual gsl::span<TraversalTransition> calculateInitialTransitions();\n\n      virtual gsl::span<TraversalTransition> calculateTransitionsOfState(gsl::span<gsl::byte> state);\n\n      virtual void* getCustomPayloadOfLastCalculation();\n\n  };\n\n}\n\n#endif  // PEMC_EXECUTABLE_MODEL_MODEL_EXECUTOR_H_\n", "meta": {"hexsha": "42001a2df8dee5ceb56d1bfe521ea36a46a100fe", "size": 3250, "ext": "h", "lang": "C", "max_stars_repo_path": "pemc/executable_model/model_executor.h", "max_stars_repo_name": "joleuger/pemc", "max_stars_repo_head_hexsha": "14deb5b97d4219ba3c92d3834ab71332997e9b13", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pemc/executable_model/model_executor.h", "max_issues_repo_name": "joleuger/pemc", "max_issues_repo_head_hexsha": "14deb5b97d4219ba3c92d3834ab71332997e9b13", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pemc/executable_model/model_executor.h", "max_forks_repo_name": "joleuger/pemc", "max_forks_repo_head_hexsha": "14deb5b97d4219ba3c92d3834ab71332997e9b13", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.7906976744, "max_line_length": 110, "alphanum_fraction": 0.7766153846, "num_tokens": 730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.13846179767920996, "lm_q2_score": 0.024053554687174065, "lm_q1q2_score": 0.003330498422561308}}
{"text": "/*\t$Id$ */\n/*\n * Copyright (c) 2014, 2015 Kristaps Dzonsons <kristaps@kcons.eu>\n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n */\n#include <assert.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <string.h>\n\n#ifdef MAC_INTEGRATION\n#include <gtkosxapplication.h>\n#endif\n#include <gtk/gtk.h>\n#include <gdk/gdk.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_multifit.h>\n#include <gsl/gsl_histogram.h>\n#include <kplot.h>\n\n#include \"extern.h\"\n\nstatic\tconst char *const inputs[INPUT__MAX] = {\n\t\"uniform\",\n\t\"variable\",\n\t\"mapped\",\n};\n\nstatic\tconst char *const views[VIEW__MAX] = {\n\t\"times-cdf\", /* VIEW_TIMEESCDF */\n\t\"times-pdf\", /* VIEW_TIMEESPDF */\n\t\"raw-mean-stddev\", /* VIEW_DEV */\n\t\"extinct-incumbent\", /* VIEW_EXTI */\n\t\"extinct-incumbent-min-cdf\", /* VIEW_EXTIMINCDF */\n\t\"extinct-incumbent-min-pdf\", /* VIEW_EXTIMINPDF */\n\t\"extinct-incumbent-min-mean\", /* VIEW_EXTIMINS */\n\t\"extinct-mutant\", /* VIEW_EXTM */\n\t\"extinct-mutant-max-cdf\", /* VIEW_EXTMMAXCDF */\n\t\"extinct-mutant-max-pdf\", /* VIEW_EXTMMAXPDF */\n\t\"extinct-mutant-max-mean\", /* VIEW_EXTMMAXS */\n\t\"island-mean\", /* VIEW_ISLANDMEAN */\n\t\"islander-mean\", /* VIEW_ISLANDERMEAN */\n\t\"raw-mean\", /* VIEW_MEAN */\n\t\"raw-mean-min-cdf\", /* VIEW_MEANMINCDF */\n\t\"raw-mean-min-pdf\", /* VIEW_MEANMINPDF */\n\t\"raw-mean-min-history\", /* VIEW_MEANMINQ */\n\t\"raw-mean-min-mean\", /* VIEW_MEANMINS */\n\t\"fitted-mean\", /* VIEW_POLY */\n\t\"fitted-mean-min-cdf\", /* VIEW_POLYMINCDF */\n\t\"fitted-mean-min-pdf\", /* VIEW_POLYMINPDF */\n\t\"fitted-mean-min-history\", /* VIEW_POLYMINQ */\n\t\"fitted-mean-min-mean\", /* VIEW_POLYMINS */\n\t\"extinct-mutant-smooth\", /* VIEW_SEXTM */\n\t\"extinct-incunmbent-smooth\", /* VIEW_SEXTI */\n\t\"raw-mean-smooth\", /* VIEW_SMEAN */\n};\n\nstatic void\nhwin_init(struct hwin *c, GtkBuilder *b)\n{\n\tGObject\t\t*w;\n\tgchar\t\t buf[1024];\n\tgchar\t\t*bufp;\n\tGTimeVal\t gt;\n\tsize_t\t\t nprocs;\n\n\tc->maptop[MAPTOP_RECORD] = win_init_toggle(b, \"radiobutton10\");\n\tc->maptop[MAPTOP_RAND] = win_init_toggle(b, \"radiobutton11\");\n\tc->maptop[MAPTOP_TORUS] = win_init_toggle(b, \"radiobutton13\");\n\tc->rangeminlambda = win_init_label(b, \"label55\");\n\tc->rangemaxlambda = win_init_label(b, \"label52\");\n\tc->rangemeanlambda = win_init_label(b, \"label58\");\n\tc->rangeerrorbox = win_init_box(b, \"box39\");\n\tc->rangeerror = win_init_label(b, \"label74\");\n\tc->rangemin = win_init_label(b, \"label43\");\n\tc->rangemax = win_init_label(b, \"label41\");\n\tc->rangemean = win_init_label(b, \"label45\");\n\tc->rangestatus = win_init_label(b, \"label47\");\n\tc->rangefunc = win_init_label(b, \"label50\");\n\tc->rangeparms = win_init_label(b, \"label72\");\n\tc->buttonrange = win_init_button(b, \"button4\");\n\tc->mapindices[MAPINDEX_STRIPED] = win_init_toggle(b, \"radiobutton15\");\n\tc->mapindices[MAPINDEX_FIXED] = win_init_toggle(b, \"radiobutton16\");\n\tc->mapindexfix = win_init_adjustment(b, \"adjustment11\");\n\tc->namefill[NAMEFILL_DATE] = win_init_toggle(b, \"radiobutton3\");\n\tc->namefill[NAMEFILL_M] = win_init_toggle(b, \"radiobutton4\");\n\tc->namefill[NAMEFILL_T] = win_init_toggle(b, \"radiobutton7\");\n\tc->namefill[NAMEFILL_MUTANTS] = win_init_toggle(b, \"radiobutton8\");\n\tc->namefill[NAMEFILL_NONE] = win_init_toggle(b, \"radiobutton9\");\n\tc->mapbox = win_init_box(b, \"box31\");\n\tc->config = win_init_window(b, \"window1\");\n\tc->rangefind = win_init_window(b, \"window2\");\n\tc->status = win_init_status(b, \"statusbar1\");\n\tc->menu = win_init_menubar(b, \"menubar1\");\n\tc->mutants[MUTANTS_DISCRETE] = win_init_radio(b, \"radiobutton1\");\n\tc->mutants[MUTANTS_GAUSSIAN] = win_init_radio(b, \"radiobutton2\");\n\tc->weighted = win_init_toggle(b, \"checkbutton1\");\n\tc->menuquit = win_init_menuitem(b, \"menuitem5\");\n\tc->input = win_init_label(b, \"label19\");\n\tc->mutantsigma = win_init_entry(b, \"entry17\");\n\tc->name = win_init_entry(b, \"entry16\");\n\tc->stop = win_init_entry(b, \"entry9\");\n\tc->xmin = win_init_entry(b, \"entry8\");\n\tc->xmax = win_init_entry(b, \"entry10\");\n\tc->ymin = win_init_entry(b, \"entry18\");\n\tc->ymax = win_init_entry(b, \"entry19\");\n\tc->inputs = win_init_notebook(b, \"notebook1\");\n\tc->error = win_init_label(b, \"label8\");\n\tc->func = win_init_entry(b, \"entry2\");\n\tc->smoothing = win_init_adjustment(b, \"adjustment10\");\n\tc->nthreads = win_init_adjustment(b, \"adjustment3\");\n\tc->fitpoly = win_init_adjustment(b, \"adjustment4\");\n\tc->pop = win_init_adjustment(b, \"adjustment1\");\n\tc->totalpop = win_init_label(b, \"label68\");\n\tc->islands = win_init_adjustment(b, \"adjustment2\");\n\tc->ideathmean = win_init_adjustment(b, \"adjustment12\");\n\tc->ideathcoef = win_init_entry(b, \"entry3\");\n\tc->resprocs = win_init_label(b, \"label3\");\n\tc->onprocs = win_init_label(b, \"label36\");\n\tc->alpha = win_init_entry(b, \"entry13\");\n\tc->delta = win_init_entry(b, \"entry14\");\n\tc->migrate[INPUT_UNIFORM] = win_init_entry(b, \"entry1\");\n\tc->migrate[INPUT_VARIABLE] = win_init_entry(b, \"entry20\");\n\tc->migrate[INPUT_MAPPED] = win_init_entry(b, \"entry4\");\n\tc->incumbents = win_init_entry(b, \"entry15\");\n\tc->mapfile = win_init_filechoose(b, \"filechooserbutton1\");\n\tc->mapmigrants[MAPMIGRANT_UNIFORM] = win_init_toggle(b, \"radiobutton5\");\n\tc->mapmigrants[MAPMIGRANT_DISTANCE] = win_init_toggle(b, \"radiobutton6\");\n\tc->mapmigrants[MAPMIGRANT_NEAREST] = win_init_toggle(b, \"radiobutton12\");\n\tc->mapmigrants[MAPMIGRANT_TWONEAREST] = win_init_toggle(b, \"radiobutton14\");\n\tc->maprandislands = win_init_adjustment(b, \"adjustment6\");\n\tc->maprandislanders = win_init_adjustment(b, \"adjustment7\");\n\tc->maptorusislands = win_init_adjustment(b, \"adjustment8\");\n\tc->maptorusislanders = win_init_adjustment(b, \"adjustment9\");\n\n\tgtk_widget_show_all(GTK_WIDGET(c->config));\n\n\t/* Hide our error message. */\n\tgtk_widget_hide(GTK_WIDGET(c->error));\n\n\t/* Set the initially-selected notebooks. */\n\tgtk_label_set_text(c->input, inputs\n\t\t[gtk_notebook_get_current_page(c->inputs)]);\n\n\t/* XXX: builder doesn't do this. */\n\tw = gtk_builder_get_object(b, \"comboboxtext1\");\n\tgtk_combo_box_set_active(GTK_COMBO_BOX(w), 0);\n\n#if GLIB_CHECK_VERSION(2, 36, 0)\n\tnprocs = g_get_num_processors();\n#else\n\tnprocs = sysconf(_SC_NPROCESSORS_ONLN);\n#endif\n\n\t/* Maximum number of processors. */\n\tgtk_adjustment_set_upper(c->nthreads, nprocs);\n\tw = gtk_builder_get_object(b, \"label12\");\n\t(void)g_snprintf(buf, sizeof(buf), \"%zu\", nprocs);\n\tgtk_label_set_text(GTK_LABEL(w), buf);\n\n\t/* Compute initial total population. */\n\t(void)g_snprintf(buf, sizeof(buf),\n\t\t\"%g\", gtk_adjustment_get_value(c->pop) *\n\t\tgtk_adjustment_get_value(c->islands));\n\tgtk_label_set_text(c->totalpop, buf);\n\n\tg_get_current_time(&gt);\n\tbufp = g_time_val_to_iso8601(&gt);\n\tgtk_entry_set_text(c->name, bufp);\n\tg_free(bufp);\n\n\t/* Hide the rangefinder when we start up. */\n\tgtk_widget_set_visible(GTK_WIDGET(c->rangefind), FALSE);\n\n#ifdef MAC_INTEGRATION\n\tgtk_widget_hide(GTK_WIDGET(c->menu));\n\tgtk_widget_hide(GTK_WIDGET(c->menuquit));\n\tgtkosx_application_set_menu_bar\n\t\t(gtkosx_application_get(), \n\t\t GTK_MENU_SHELL(c->menu));\n\tgtkosx_application_sync_menubar\n\t\t(gtkosx_application_get());\n#endif\n}\n\n/*\n * Free a given simulation, possibly waiting for the simulation threads\n * to exit. \n * The simulation is presumed to have been set as terminating before\n * running this.\n * Yes, we can wait if the simulation takes a long time between updates.\n */\nstatic void\nsim_free(gpointer arg)\n{\n\tstruct sim\t*p = arg;\n\tsize_t\t\t i;\n\n\tif (NULL == p)\n\t\treturn;\n\n\tg_debug(\"%p: Freeing simulation\", p);\n\n\t/*\n\t * Join all of our running threads.\n\t * They were stopped in the sim_stop function, which was called\n\t * before this one.\n\t */\n\tfor (i = 0; i < p->nprocs; i++) \n\t\tif (NULL != p->threads[i].thread) {\n\t\t\tg_debug(\"%p: Freeing joining thread \"\n\t\t\t\t\"(simulation %p)\", \n\t\t\t\tp->threads[i].thread, p);\n\t\t\tg_thread_join(p->threads[i].thread);\n\t\t}\n\tp->nprocs = 0;\n\n\tsimbuf_free(p->bufs.means);\n\tsimbuf_free(p->bufs.stddevs);\n\tsimbuf_free(p->bufs.imeans);\n\tsimbuf_free(p->bufs.times);\n\tsimbuf_free(p->bufs.istddevs);\n\tsimbuf_free(p->bufs.islandmeans);\n\tsimbuf_free(p->bufs.islandstddevs);\n\tsimbuf_free(p->bufs.mextinct);\n\tsimbuf_free(p->bufs.iextinct);\n\tkdata_destroy(p->bufs.fractions);\n\tkdata_destroy(p->bufs.ifractions);\n\tkdata_destroy(p->bufs.mutants);\n\tkdata_destroy(p->bufs.incumbents);\n\tkdata_destroy(p->bufs.islands);\n\tkdata_destroy(p->bufs.meanmins);\n\tkdata_destroy(p->bufs.mextinctmaxs);\n\tkdata_destroy(p->bufs.iextinctmins);\n\tkdata_destroy(p->bufs.fitpoly);\n\tkdata_destroy(p->bufs.fitpolybuf);\n\tkdata_destroy(p->bufs.fitpolymins);\n\tkdata_destroy(p->bufs.meanminqbuf);\n\tkdata_destroy(p->bufs.fitminqbuf);\n\n\thnode_free(p->exp);\n\tg_mutex_clear(&p->hot.mux);\n\tg_cond_clear(&p->hot.cond);\n\tg_free(p->name);\n\tg_free(p->func);\n\tif (NULL != p->ms)\n\t\tfor (i = 0; i < p->islands; i++)\n\t\t\tg_free(p->ms[i]);\n\tg_free(p->ms);\n\tg_free(p->pops);\n\tkml_free(p->kml);\n\tif (p->fitpoly) {\n\t\tg_free(p->work.coeffs);\n\t\tgsl_matrix_free(p->work.X);\n\t\tgsl_vector_free(p->work.y);\n\t\tgsl_vector_free(p->work.w);\n\t\tgsl_vector_free(p->work.c);\n\t\tgsl_matrix_free(p->work.cov);\n\t\tgsl_multifit_linear_free(p->work.work);\n\t\tp->fitpoly = 0;\n\t}\n\tg_free(p->threads);\n\tg_free(p);\n\tg_debug(\"%p: Simulation freed\", p);\n}\n\n/*\n * Set a given simulation to stop running.\n * This must be invoked before sim_free() or simulation threads will\n * still be running.\n */\nvoid\nsim_stop(gpointer arg, gpointer unused)\n{\n\tstruct sim\t*p = arg;\n\tint\t\t pause;\n\n\tif (p->terminate)\n\t\treturn;\n\tg_debug(\"%p: Simulation stopping\", p);\n\tp->terminate = 1;\n\tg_mutex_lock(&p->hot.mux);\n\tif (0 != (pause = p->hot.pause)) {\n\t\tp->hot.pause = 0;\n\t\tg_cond_broadcast(&p->hot.cond);\n\t}\n\tg_mutex_unlock(&p->hot.mux);\n\tif (pause)\n\t\tg_debug(\"%p: Simulation unpausing to stop\", p);\n}\n\n/*\n * Free up all memory.\n * This can be reentrant (due to gtk-osx's funny handling of\n * termination), so be careful to nullify things so that if recalled it\n * doesn't puke.\n */\nstatic void\nbmigrate_free(struct bmigrate *p)\n{\n\n\tg_debug(\"%p: Freeing main\", p);\n\tg_list_foreach(p->sims, sim_stop, NULL);\n\tg_list_free_full(p->sims, sim_free);\n\tp->sims = NULL;\n\thnode_free(p->range.exp);\n\tp->range.exp = NULL;\n\tif (NULL != p->status_elapsed)\n\t\tg_timer_destroy(p->status_elapsed);\n\tp->status_elapsed = NULL;\n\tp->clrsz = 0;\n\tfree(p->clrs);\n\tp->clrs = NULL;\n}\n\n/*\n * Pause or unpause (unset pause and broadcast to condition) a given\n * simulation depending on its current pause status.\n */\nstatic void\non_sim_pause(struct sim *sim, int dopause)\n{\n\tint\t\t pause = -1;\n\n\tg_mutex_lock(&sim->hot.mux);\n\tif (0 == dopause && sim->hot.pause) {\n\t\tsim->hot.pause = pause = 0;\n\t\tg_cond_broadcast(&sim->hot.cond);\n\t} else if (dopause && 0 == sim->hot.pause)\n\t\tsim->hot.pause = pause = 1;\n\tg_mutex_unlock(&sim->hot.mux);\n\n\tif (0 == pause && 0 == dopause)\n\t\tg_debug(\"Unpausing simulation %p\", sim);\n\telse if (pause && dopause)\n\t\tg_debug(\"Pausing simulation %p\", sim);\n}\n\nstatic void\ncqueue_fill(size_t pos, struct kpair *kp, void *arg)\n{\n\tstruct cqueue\t*q = arg;\n\n\tkp->x = -(double)(CQUEUESZ - pos);\n\tkp->y = q->vals[(q->pos + pos + 1) % CQUEUESZ];\n}\n\nstatic void\ncqueue_push(struct cqueue *q, double val)\n{\n\n\tq->vals[q->pos] = val;\n\tif (val > q->vals[q->maxpos])\n\t\tq->maxpos = q->pos;\n\tq->pos = (q->pos + 1) % CQUEUESZ;\n}\n\n\n/*\n * This copies data from the threads into local (\"cold\") storage.\n * It does so by checking whether the threads have copied out of \"hot\"\n * storage (locking their mutex in the process) and, if so, indicates\n * that we're about to read it (and thus to do so again), then after\n * reading, reset that the data is stale.\n */\nstatic gboolean\non_sim_copyout(gpointer dat)\n{\n\tstruct bmigrate\t*b = dat;\n\tGList\t\t*list, *w, *sims;\n\tssize_t\t\t pos;\n\tstruct kpair\t kp;\n\tstruct sim\t*sim;\n\tstruct curwin\t*cur;\n\tint\t\t copy, rc;\n\n\tfor (list = b->sims; NULL != list; list = g_list_next(list)) {\n\t\tsim = list->data;\n\t\tif (0 == sim->nprocs)\n\t\t\tcontinue;\n\t\t/*\n\t\t * Instruct the simulation to copy out its data into warm\n\t\t * storage.\n\t\t * If it hasn't already done so, then don't copy into\n\t\t * cold storage, as nothing has changed.\n\t\t */\n\t\tg_mutex_lock(&sim->hot.mux);\n\t\tcopy = 0 == sim->hot.copyout;\n\t\tg_mutex_unlock(&sim->hot.mux);\n\n\t\tif ( ! copy)\n\t\t\tcontinue;\n\n\t\t/* \n\t\t * Don't copy stale data.\n\t\t * Trigger the simulation to copy-out when it gets a\n\t\t * chance.\n\t\t */\n\t\tif (sim->cold.truns == sim->warm.truns) {\n\t\t\tassert(sim->cold.tgens == sim->warm.tgens);\n\t\t\tg_mutex_lock(&sim->hot.mux);\n\t\t\tg_assert(0 == sim->hot.copyout);\n\t\t\tsim->hot.copyout = 1;\n\t\t\tg_mutex_unlock(&sim->hot.mux);\n\t\t\tcontinue;\n\t\t}\n\n\t\t/*\n\t\t * Since we're updating this particular simulation, make\n\t\t * sure that all windows tied to this simulation are\n\t\t * also going to be redrawn when the redrawer is called.\n\t\t */\n\t\tfor (w = b->windows ; w != NULL; w = w->next) {\n\t\t\tcur = w->data;\n\t\t\tsims = cur->sims;\n\t\t\tg_assert(NULL != sims);\n\t\t\tfor ( ; NULL != sims; sims = sims->next)\n\t\t\t\tif (sim == sims->data) {\n\t\t\t\t\tcur->redraw = 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t}\n\n\t\t/* Most strutures we simply copy over. */\n\t\tsimbuf_copy_cold(sim->bufs.times);\n\t\tsimbuf_copy_cold(sim->bufs.imeans);\n\t\tsimbuf_copy_cold(sim->bufs.istddevs);\n\t\tsimbuf_copy_cold(sim->bufs.islandmeans);\n\t\tsimbuf_copy_cold(sim->bufs.islandstddevs);\n\t\tsimbuf_copy_cold(sim->bufs.means);\n\t\tsimbuf_copy_cold(sim->bufs.stddevs);\n\t\tsimbuf_copy_cold(sim->bufs.mextinct);\n\t\tsimbuf_copy_cold(sim->bufs.iextinct);\n\t\trc = kdata_buffer_copy\n\t\t\t(sim->bufs.fitpolybuf, \n\t\t\t sim->bufs.fitpoly);\n\t\tg_assert(0 != rc);\n\n\t\tsim->cold.truns = sim->warm.truns;\n\t\tsim->cold.tgens = sim->warm.tgens;\n\n\t\tpos = kdata_ymin(sim->bufs.means->cold, &kp);\n\t\tg_assert(pos >= 0);\n\t\tkdata_array_add(sim->bufs.meanmins, pos, 1.0);\n\t\tcqueue_push(&sim->bufs.meanminq, kp.x);\n\t\tkdata_array_fill(sim->bufs.meanminqbuf, \n\t\t\t&sim->bufs.meanminq, cqueue_fill);\n\n\t\tkdata_array_add(sim->bufs.mextinctmaxs, \n\t\t\tkdata_ymax(sim->bufs.mextinct->cold, NULL), 1.0);\n\n\t\tkdata_array_add(sim->bufs.iextinctmins, \n\t\t\tkdata_ymin(sim->bufs.iextinct->cold, NULL), 1.0);\n\n\t\tpos = kdata_ymin(sim->bufs.fitpolybuf, &kp);\n\t\tg_assert(pos >= 0);\n\t\tkdata_array_add(sim->bufs.fitpolymins, pos, 1.0);\n\t\tcqueue_push(&sim->bufs.fitminq, kp.x);\n\t\tkdata_array_fill(sim->bufs.fitminqbuf, \n\t\t\t&sim->bufs.fitminq, cqueue_fill);\n\n\t\t/* Copy-out when convenient. */\n\t\tg_mutex_lock(&sim->hot.mux);\n\t\tg_assert(0 == sim->hot.copyout);\n\t\tsim->hot.copyout = 1;\n\t\tg_mutex_unlock(&sim->hot.mux);\n\t}\n\n\treturn(TRUE);\n}\n\nstatic gboolean\non_sim_autosave(gpointer dat)\n{\n\tstruct bmigrate\t*b = dat;\n\tstruct curwin\t*cur;\n\tGList\t\t*l;\n\tGtkWidget\t*dialog;\n\tenum view\t sv, view;\n\tgchar\t\t*file;\n\tint\t\t rc;\n\n\tfor (l = b->windows; l != NULL; l = l->next) {\n\t\tcur = l->data;\n\t\tif (NULL == cur->autosave)\n\t\t\tcontinue;\n\t\tsv = cur->view;\n\t\tfor (view = 0; view < VIEW__MAX; view++) {\n\t\t\tfile = g_strdup_printf\n\t\t\t\t(\"%s\" G_DIR_SEPARATOR_S \"%s.pdf\",\n\t\t\t\t cur->autosave, views[view]);\n\t\t\tcur->view = view;\n\t\t\trc = save(file, cur);\n\t\t\tg_free(file);\n\t\t\tif (0 == rc)\n\t\t\t\tbreak;\n\t\t}\n\t\tcur->view = sv;\n\t\tif (view != VIEW__MAX)\n\t\t\tbreak;\n\t\tfile = g_strdup_printf(\"%s\" \n\t\t\tG_DIR_SEPARATOR_S \"README.txt\", \n\t\t\tcur->autosave);\n\t\trc = saveconfig(file, cur);\n\t\tg_free(file);\n\t\tif (0 == rc)\n\t\t\tbreak;\n\t}\n\tif (NULL == l)\n\t\treturn(TRUE);\n\n\tdialog = gtk_message_dialog_new\n\t\t(GTK_WINDOW(cur->wins.window),\n\t\t GTK_DIALOG_DESTROY_WITH_PARENT, \n\t\t GTK_MESSAGE_ERROR, \n\t\t GTK_BUTTONS_CLOSE, \n\t\t \"Error auto-saving: %s\", \n\t\t strerror(errno));\n\tgtk_dialog_run(GTK_DIALOG(dialog));\n\tgtk_widget_destroy(dialog);\n\tg_free(cur->autosave);\n\tcur->autosave = NULL;\n\tgtk_widget_hide(GTK_WIDGET\n\t\t(cur->wins.menuunautoexport));\n\tgtk_widget_show(GTK_WIDGET\n\t\t(cur->wins.menuautoexport));\n\treturn(TRUE);\n}\n\nstatic void\non_win_redraw(struct curwin *cur)\n{\n\tGList\t\t*l;\n\tstruct sim\t*sim;\n\tsize_t\t\t i;\n\tint\t\t rc;\n\n\tfor (i = 0, l = cur->sims; NULL != l; l = g_list_next(l), i++) {\n\t\tsim = l->data;\n\t\trc = kdata_vector_set(cur->winmean, i, i, \n\t\t\tkdata_pmfmean(sim->bufs.meanmins));\n\t\tg_assert(0 != rc);\n\t\trc = kdata_vector_set(cur->winstddev, i, i, \n\t\t\tkdata_pmfstddev(sim->bufs.meanmins));\n\t\tg_assert(0 != rc);\n\t\trc = kdata_vector_set(cur->winfitmean, i, i, \n\t\t\tkdata_pmfmean(sim->bufs.fitpolymins));\n\t\tg_assert(0 != rc);\n\t\trc = kdata_vector_set(cur->winfitstddev, i, i, \n\t\t\tkdata_pmfstddev(sim->bufs.fitpolymins));\n\t\tg_assert(0 != rc);\n\t\trc = kdata_vector_set(cur->winmextinctmean, i, i, \n\t\t\tkdata_pmfmean(sim->bufs.mextinctmaxs));\n\t\tg_assert(0 != rc);\n\t\trc = kdata_vector_set(cur->winmextinctstddev, i, i, \n\t\t\tkdata_pmfstddev(sim->bufs.mextinctmaxs));\n\t\tg_assert(0 != rc);\n\t\trc = kdata_vector_set(cur->winiextinctmean, i, i, \n\t\t\tkdata_pmfmean(sim->bufs.iextinctmins));\n\t\tg_assert(0 != rc);\n\t\trc = kdata_vector_set(cur->winiextinctstddev, i, i, \n\t\t\tkdata_pmfstddev(sim->bufs.iextinctmins));\n\t\tg_assert(0 != rc);\n\t}\n\n\tgtk_widget_queue_draw(GTK_WIDGET(cur->wins.window));\n}\n\n/*\n * Run this fairly often to see if we need to join any worker threads.\n * Worker threads are joined when they have zero references are in the\n * terminating state.\n */\nstatic gboolean\non_sim_timer(gpointer dat)\n{\n\tstruct bmigrate\t*b = dat;\n\tstruct sim\t*sim;\n\tgchar\t\t buf[1024];\n\tGList\t\t*list;\n\tuint64_t\t runs;\n\tsize_t\t\t i, onprocs, resprocs;\n\tdouble\t\t elapsed;\n\n\tonprocs = resprocs = runs = 0;\n\tfor (list = b->sims; NULL != list; list = g_list_next(list)) {\n\t\tsim = (struct sim *)list->data;\n\t\truns += sim->cold.tgens;\n\t\t/*\n\t\t * If \"terminate\" is set, then the thread is (or already\n\t\t * did finish) exiting, so wait for it.\n\t\t * If we wait, it should take only a very small while.\n\t\t */\n\t\tif (sim->terminate && sim->nprocs > 0) {\n\t\t\tfor (i = 0; i < sim->nprocs; i++)  {\n\t\t\t\tif (NULL == sim->threads[i].thread)\n\t\t\t\t\tcontinue;\n\t\t\t\tg_debug(\"%p: Timeout handler joining \"\n\t\t\t\t\t\"thread (simulation %p)\", \n\t\t\t\t\tsim->threads[i].thread, sim);\n\t\t\t\tg_thread_join(sim->threads[i].thread);\n\t\t\t\tsim->threads[i].thread = NULL;\n\t\t\t}\n\t\t\tsim->nprocs = 0;\n\t\t\tassert(0 == sim->refs); \n\t\t} else if ( ! sim->terminate && ! sim->hot.pause) {\n\t\t\tonprocs += sim->nprocs;\n\t\t\tresprocs += sim->nprocs;\n\t\t} else if ( ! sim->terminate)\n\t\t\tresprocs += sim->nprocs;\n\t}\n\n\t/* \n\t * Remind us of how many threads we're running. \n\t * FIXME: this shows the number of allocated threads, not\n\t * necessarily the number of running threads.\n\t */\n\t(void)g_snprintf(buf, sizeof(buf), \"%zu\", resprocs);\n\tgtk_label_set_text(b->wins.resprocs, buf);\n\n\t(void)g_snprintf(buf, sizeof(buf), \"%zu\", onprocs);\n\tgtk_label_set_text(b->wins.onprocs, buf);\n\t\n\t/* \n\t * Tell us how many generations have transpired (if no time has\n\t * elapsed, then make sure we don't divide by zero).\n\t * Then update the status bar.\n\t * This will in turn redraw that window portion.\n\t */\n\telapsed = g_timer_elapsed(b->status_elapsed, NULL);\n\tif (0.0 == elapsed)\n\t\telapsed = DBL_MIN;\n\t(void)g_snprintf(buf, sizeof(buf), \n\t\t\"Running %.0f generations/second.\", \n\t\t(runs - b->lastmatches) / elapsed);\n\tgtk_statusbar_pop(b->wins.status, 0);\n\tgtk_statusbar_push(b->wins.status, 0, buf);\n\tg_timer_start(b->status_elapsed);\n\tb->lastmatches = runs;\n\n\t/* \n\t * Conditionally update our windows.\n\t * We do this by iterating through all simulation windows and\n\t * seeing if they have the \"update\" flag set to true.\n\t */\n\tfor (list = b->windows; list != NULL; list = list->next)\n\t\tif (((struct curwin *)list->data)->redraw)\n\t\t\ton_win_redraw(list->data);\n\n\treturn(TRUE);\n}\n\n\ngboolean\nonfocussim(GtkWidget *w, GdkEvent *event, gpointer dat)\n{\n#ifdef MAC_INTEGRATION\n\tstruct curwin\t  *c = dat;\n\n\tgtkosx_application_set_menu_bar\n\t\t(gtkosx_application_get(), \n\t\t GTK_MENU_SHELL(c->wins.menu));\n\tgtkosx_application_sync_menubar\n\t\t(gtkosx_application_get());\n#endif\n\treturn(TRUE);\n}\n\ngboolean\nonfocusmain(GtkWidget *w, GdkEvent *event, gpointer dat)\n{\n#ifdef MAC_INTEGRATION\n\tstruct bmigrate\t  *b = dat;\n\n\tgtkosx_application_set_menu_bar\n\t\t(gtkosx_application_get(),\n\t\t GTK_MENU_SHELL(b->wins.menu));\n\tgtkosx_application_sync_menubar\n\t\t(gtkosx_application_get());\n#endif\n\treturn(TRUE);\n}\n\ngboolean\nondraw(GtkWidget *w, cairo_t *cr, gpointer dat)\n{\n\n\tdraw(w, cr, dat);\n\treturn(TRUE);\n}\n\nvoid\nonunautoexport(GtkMenuItem *menuitem, gpointer dat)\n{\n\tstruct curwin\t*cur = dat;\n\n\tg_assert(NULL != cur->autosave);\n\tg_debug(\"Disabling auto-exporting: %s\", cur->autosave);\n\tg_free(cur->autosave);\n\tcur->autosave = NULL;\n\tgtk_widget_show(GTK_WIDGET(cur->wins.menuautoexport));\n\tgtk_widget_hide(GTK_WIDGET(cur->wins.menuunautoexport));\n}\n\nvoid\nonautoexport(GtkMenuItem *menuitem, gpointer dat)\n{\n\tGtkWidget\t*dialog;\n\tgint\t\t res;\n\tstruct curwin\t*cur = dat;\n\tGtkFileChooser\t*chooser;\n\n\tg_assert(NULL == cur->autosave);\n\tdialog = gtk_file_chooser_dialog_new\n\t\t(\"Create Data Folder\", cur->wins.window,\n\t\t GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER,\n\t\t \"_Cancel\", GTK_RESPONSE_CANCEL,\n\t\t \"_Create\", GTK_RESPONSE_ACCEPT, NULL);\n\tchooser = GTK_FILE_CHOOSER(dialog);\n\tgtk_file_chooser_set_current_name(chooser, \"bmigrate\");\n\tres = gtk_dialog_run(GTK_DIALOG(dialog));\n\tif (res != GTK_RESPONSE_ACCEPT) {\n\t\tgtk_widget_destroy(dialog);\n\t\treturn;\n\t}\n\tcur->autosave = gtk_file_chooser_get_filename(chooser);\n\tgtk_widget_destroy(dialog);\n\tgtk_widget_hide(GTK_WIDGET(cur->wins.menuautoexport));\n\tgtk_widget_show(GTK_WIDGET(cur->wins.menuunautoexport));\n\tg_debug(\"Auto-exporting: %s\", cur->autosave);\n\tg_mkdir_with_parents(cur->autosave, 0755);\n}\n\n/*\n * Toggle a different view of the current window.\n */\nvoid\nonviewtoggle(GtkMenuItem *menuitem, gpointer dat)\n{\n\tstruct curwin\t*cur = dat;\n\n\t/*\n\t * First, set the \"view\" indicator to be the current view as\n\t * found in the drop-down menu.\n\t */\n\tfor (cur->view = 0; cur->view < VIEW__MAX; cur->view++) \n\t\tif (gtk_check_menu_item_get_active\n\t\t\t(cur->wins.views[cur->view]))\n\t\t\tbreak;\n\t/*\n\t * Next, set the window name to be the label associated with the\n\t * respective menu check item.\n\t */\n\tg_assert(cur->view < VIEW__MAX);\n\tgtk_window_set_title(GTK_WINDOW(cur->wins.window),\n\t\tgtk_menu_item_get_label\n\t\t(GTK_MENU_ITEM(cur->wins.views[cur->view])));\n\n\t/* Redraw the window. */\n\tgtk_widget_queue_draw(GTK_WIDGET(cur->wins.window));\n}\n\n/*\n * Pause all simulations connect to a view.\n */\nvoid\nonpause(GtkMenuItem *menuitem, gpointer dat)\n{\n\tGList\t\t*l;\n\tstruct curwin\t*cur = dat;\n\n\tfor (l = cur->sims; NULL != l; l = l->next)\n\t\ton_sim_pause(l->data, 1);\n}\n\n/*\n * Unpause all simulations connect to a view.\n */\nvoid\nonunpause(GtkMenuItem *menuitem, gpointer dat)\n{\n\tstruct curwin\t*cur = dat;\n\tGList\t\t*l;\n\n\tfor (l = cur->sims ; NULL != l; l = l->next)\n\t\ton_sim_pause(l->data, 0);\n}\n\ngboolean\nonrangedelete(GtkWidget *widget, GdkEvent *event, gpointer dat)\n{\n\tstruct bmigrate\t*b = dat;\n\n\tgtk_widget_set_visible\n\t\t(GTK_WIDGET(b->wins.rangefind), FALSE);\n\n\tif (b->rangeid > 0) {\n\t\tg_debug(\"Disabling rangefinder (user request)\");\n\t\tg_source_remove(b->rangeid);\n\t\tb->rangeid = 0;\n\t} else \n\t\tg_debug(\"Rangefinder already disabled (user request)\");\n\n\treturn(TRUE);\n}\n\nvoid\nonrangeclose(GtkButton *button, gpointer dat)\n{\n\tstruct bmigrate\t*b = dat;\n\n\tgtk_widget_set_visible\n\t\t(GTK_WIDGET(b->wins.rangefind), FALSE);\n\n\tif (b->rangeid > 0) {\n\t\tg_debug(\"Disabling rangefinder (user request)\");\n\t\tg_source_remove(b->rangeid);\n\t\tb->rangeid = 0;\n\t} else \n\t\tg_debug(\"Rangefinder already disabled (user request)\");\n}\n\n/*\n * One of the preset continuum functions for our continuum game\n * possibility.\n */\nvoid\nonpreset(GtkComboBox *widget, gpointer dat)\n{\n\tstruct bmigrate\t*b = dat;\n\n\tswitch (gtk_combo_box_get_active(widget)) {\n\tcase (1):\n\t\t/* Tullock */\n\t\tgtk_entry_set_text(b->wins.func, \n\t\t\t\"x * (1 / X) - x\");\n\t\tbreak;\n\tcase (2):\n\t\t/* Cournot */\n\t\tgtk_entry_set_text(b->wins.func, \"(1 - X) * x\");\n\t\tbreak;\n\tcase (3):\n\t\t/* Exponential Public Goods */\n\t\tgtk_entry_set_text(b->wins.func, \n\t\t\t\"(1 - exp(-X)) - x\");\n\t\tbreak;\n\tcase (4):\n\t\t/* Quadratic Public Goods */\n\t\tgtk_entry_set_text(b->wins.func, \n\t\t\t\"sqrt(1 / n * X) - 0.5 * x^2\");\n\t\tbreak;\n\tdefault:\n\t\tgtk_entry_set_text(b->wins.func, \"\");\n\t\tbreak;\n\t}\n}\n\nstatic void\non_totalpop(struct bmigrate *b, gint pnum)\n{\n\tGList\t\t*l, *cl, *sv;\n\tgchar\t \t buf[32];\n\tdouble\t\t v = 0.0;\n\tenum maptop\t maptop;\n\tstruct kml\t*kml;\n\tstruct kmlplace\t*kmlp;\n\tgchar\t\t*file;\n\n\tswitch (pnum) {\n\tcase (INPUT_UNIFORM):\n\t\tgtk_label_set_text(b->wins.input, \"uniform\");\n\t\tv = gtk_adjustment_get_value(b->wins.pop) *\n\t\t\tgtk_adjustment_get_value(b->wins.islands);\n\t\tbreak;\n\tcase (INPUT_VARIABLE):\n\t\tgtk_label_set_text(b->wins.input, \"variable\");\n\t\tl = sv = gtk_container_get_children\n\t\t\t(GTK_CONTAINER(b->wins.mapbox));\n\t\tfor (; NULL != l; l = g_list_next(l)) {\n\t\t\tcl = gtk_container_get_children\n\t\t\t\t(GTK_CONTAINER(l->data));\n\t\t\tv += gtk_spin_button_get_value_as_int\n\t\t\t\t(GTK_SPIN_BUTTON(g_list_next(cl)->data));\n\t\t\tg_list_free(cl);\n\t\t}\n\t\tg_list_free(sv);\n\t\tbreak;\n\tcase (INPUT_MAPPED):\n\t\tfor (maptop = 0; maptop < MAPTOP__MAX; maptop++)\n\t\t\tif (gtk_toggle_button_get_active\n\t\t\t\t (b->wins.maptop[maptop]))\n\t\t\t\tbreak;\n\t\tswitch (maptop) {\n\t\tcase (MAPTOP_RECORD):\n\t\t\tgtk_label_set_text(b->wins.input, \n\t\t\t\t\"KML islands\");\n\t\t\tfile = gtk_file_chooser_get_filename\n\t\t\t\t(b->wins.mapfile);\n\t\t\tif (NULL == file)\n\t\t\t\tbreak;\n\t\t\tkml = kml_parse(file, NULL);\n\t\t\tif (NULL == kml)\n\t\t\t\tbreak;\n\t\t\tl = kml->kmls;\n\t\t\tfor ( ; NULL != l; l = g_list_next(l)) {\n\t\t\t\tkmlp = l->data;\n\t\t\t\tv += kmlp->pop;\n\t\t\t}\n\t\t\tkml_free(kml);\n\t\t\tbreak;\n\t\tcase (MAPTOP_RAND):\n\t\t\tgtk_label_set_text(b->wins.input, \n\t\t\t\t\"random islands\");\n\t\t\tv = gtk_adjustment_get_value\n\t\t\t\t(b->wins.maprandislands) *\n\t\t\t\tgtk_adjustment_get_value\n\t\t\t\t(b->wins.maprandislanders);\n\t\t\tbreak;\n\t\tcase (MAPTOP_TORUS):\n\t\t\tgtk_label_set_text(b->wins.input, \n\t\t\t\t\"toroidal islands\");\n\t\t\tv = gtk_adjustment_get_value\n\t\t\t\t(b->wins.maptorusislands) *\n\t\t\t\tgtk_adjustment_get_value\n\t\t\t\t(b->wins.maptorusislanders);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tabort();\n\t\t}\n\t\tbreak;\n\tdefault:\n\t\tabort();\n\t}\n\n\tg_snprintf(buf, sizeof(buf), \"%g\", v);\n\tgtk_label_set_text(b->wins.totalpop, buf);\n}\n\nvoid\non_change_input(GtkNotebook *notebook, \n\tGtkWidget *page, gint pnum, gpointer dat)\n{\n\n\ton_totalpop(dat, pnum);\n}\n\nvoid\non_change_mapfile(GtkFileChooserButton *widget, gpointer dat)\n{\n\tstruct bmigrate\t*b = dat;\n\n\ton_totalpop(b, gtk_notebook_get_current_page(b->wins.inputs));\n}\n\nvoid\non_change_maptype(GtkToggleButton *togglebutton, gpointer dat)\n{\n\tstruct bmigrate\t*b = dat;\n\n\ton_totalpop(b, gtk_notebook_get_current_page(b->wins.inputs));\n}\n\nvoid\non_change_totalpop(GtkSpinButton *spinbutton, gpointer dat)\n{\n\tstruct bmigrate\t*b = dat;\n\n\ton_totalpop(b, gtk_notebook_get_current_page(b->wins.inputs));\n}\n\nvoid\nonsaveall(GtkMenuItem *menuitem, gpointer dat)\n{\n\tstruct curwin\t*cur = dat;\n\tGtkWidget\t*dialog;\n\tgint\t\t res;\n\tGtkFileChooser\t*chooser;\n\tchar \t\t*dir, *file;\n\tenum view\t view, sv;\n\tint\t\t rc;\n\n\tdialog = gtk_file_chooser_dialog_new\n\t\t(\"Create View Data Folder\", cur->wins.window,\n\t\t GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER,\n\t\t \"_Cancel\", GTK_RESPONSE_CANCEL,\n\t\t \"_Create\", GTK_RESPONSE_ACCEPT, NULL);\n\n\tchooser = GTK_FILE_CHOOSER(dialog);\n\tgtk_file_chooser_set_current_name(chooser, \"bmigrate\");\n\tres = gtk_dialog_run(GTK_DIALOG(dialog));\n\tif (res != GTK_RESPONSE_ACCEPT) {\n\t\tgtk_widget_destroy(dialog);\n\t\treturn;\n\t}\n\tdir = gtk_file_chooser_get_filename(chooser);\n\tgtk_widget_destroy(dialog);\n\tg_assert(NULL != dir);\n\tg_assert('\\0' != *dir);\n\n\tsv = cur->view;\n\tfor (view = 0; view < VIEW__MAX; view++) {\n\t\tfile = g_strdup_printf\n\t\t\t(\"%s\" G_DIR_SEPARATOR_S \"%s.pdf\",\n\t\t\t dir, views[view]);\n\t\tcur->view = view;\n\t\trc = save(file, cur);\n\t\tg_free(file);\n\t\tif (0 == rc)\n\t\t\tbreak;\n\t}\n\tcur->view = sv;\n\tif (view == VIEW__MAX) {\n\t\tfile = g_strdup_printf(\"%s\" \n\t\t\tG_DIR_SEPARATOR_S \"README.txt\", dir);\n\t\tif (0 == (rc = saveconfig(file, cur)))\n\t\t\tview = 0;\n\t\tg_free(file);\n\t}\n\tg_free(dir);\n\tif (view == VIEW__MAX)\n\t\treturn;\n\tdialog = gtk_message_dialog_new\n\t\t(GTK_WINDOW(cur->wins.window),\n\t\t GTK_DIALOG_DESTROY_WITH_PARENT, \n\t\t GTK_MESSAGE_ERROR, \n\t\t GTK_BUTTONS_CLOSE, \n\t\t \"Error saving: %s\", \n\t\t strerror(errno));\n\tgtk_dialog_run(GTK_DIALOG(dialog));\n\tgtk_widget_destroy(dialog);\n}\n\nvoid\nonsave(GtkMenuItem *menuitem, gpointer dat)\n{\n\tstruct curwin\t*cur = dat;\n\tGtkWidget\t*dialog;\n\tgint\t\t res;\n\tGtkFileChooser\t*chooser;\n\tint\t\t rc;\n\tchar \t\t*file;\n\n\tdialog = gtk_file_chooser_dialog_new\n\t\t(\"Save View Data\", cur->wins.window,\n\t\t GTK_FILE_CHOOSER_ACTION_SAVE,\n\t\t \"_Cancel\", GTK_RESPONSE_CANCEL,\n\t\t \"_Save\", GTK_RESPONSE_ACCEPT, NULL);\n\tchooser = GTK_FILE_CHOOSER(dialog);\n\tgtk_file_chooser_set_do_overwrite_confirmation(chooser, TRUE);\n\tgtk_file_chooser_set_current_name(chooser, \"bmigrate.pdf\");\n\tres = gtk_dialog_run(GTK_DIALOG(dialog));\n\tif (res != GTK_RESPONSE_ACCEPT) {\n\t\tgtk_widget_destroy(dialog);\n\t\treturn;\n\t}\n\tfile = gtk_file_chooser_get_filename(chooser);\n\tgtk_widget_destroy(dialog);\n\tg_assert(NULL != file);\n\tg_assert('\\0' != *file);\n\trc = save(file, cur);\n\tg_free(file);\n\tif (0 != rc)\n\t\treturn;\n\tdialog = gtk_message_dialog_new\n\t\t(GTK_WINDOW(cur->wins.window),\n\t\t GTK_DIALOG_DESTROY_WITH_PARENT, \n\t\t GTK_MESSAGE_ERROR, \n\t\t GTK_BUTTONS_CLOSE, \n\t\t \"Error saving: %s\", \n\t\t strerror(errno));\n\tgtk_dialog_run(GTK_DIALOG(dialog));\n\tgtk_widget_destroy(dialog);\n}\n\n#ifdef MAC_INTEGRATION\ngboolean\nonterminate(GtkosxApplication *action, gpointer dat)\n{\n\n\tbmigrate_free(dat);\n\tgtk_main_quit();\n\treturn(FALSE);\n}\n#endif\n\n/*\n * Run when we quit from a simulation window.\n */\nvoid\nonclose(GtkMenuItem *menuitem, gpointer dat)\n{\n\tstruct curwin\t*cur = dat;\n\n\tg_debug(\"Simulation window closing\");\n\tgtk_widget_destroy(GTK_WIDGET(cur->wins.window));\n}\n\n/*\n * Run when we quit from a simulation window.\n */\nvoid\nonquitsim(GtkMenuItem *menuitem, gpointer dat)\n{\n\tstruct curwin\t*cur = dat;\n\n\tbmigrate_free(cur->b);\n\tgtk_main_quit();\n}\n\n/*\n * Run when we quit from a simulation window.\n */\nvoid\nonquitmain(GtkMenuItem *menuitem, gpointer dat)\n{\n\n\tbmigrate_free(dat);\n\tgtk_main_quit();\n}\n\n/*\n * Run when we destroy the config screen.\n */\nvoid \nondestroy(GtkWidget *object, gpointer dat)\n{\n\t\n\tbmigrate_free(dat);\n\tgtk_main_quit();\n}\n\n/*\n * Run when we press \"Quit\" on the config screen.\n */\nvoid\non_deactivate(GtkButton *button, gpointer dat)\n{\n\n\tbmigrate_free(dat);\n\tgtk_main_quit();\n}\n\n/*\n * Add an island configuration.\n * For the time being, we only allow the population size of the island\n * to be specified.\n * (Inter-island migration probabilities may not yet be assigned.)\n */\nstatic void\nmapbox_add(struct bmigrate *b, size_t sz)\n{\n\tGtkWidget\t*box, *label, *btn;\n\tGtkAdjustment\t*adj;\n\tgchar\t\t buf[64];\n\n\tbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 5);\n\n\tg_snprintf(buf, sizeof(buf), \"Population %zu:\", sz);\n\tlabel = gtk_label_new(buf);\n\tgtk_misc_set_alignment(GTK_MISC(label), 1.0, 0.5);\n\tgtk_label_set_width_chars(GTK_LABEL(label), 20);\n\tgtk_container_add(GTK_CONTAINER(box), label);\n\n\tadj = gtk_adjustment_new(2.0, 2.0, 1000.0, 1.0, 10.0, 0.0);\n\tbtn = gtk_spin_button_new(adj, 1.0, 0);\n\tg_signal_connect(btn, \"value-changed\", \n\t\tG_CALLBACK(on_change_totalpop), b);\n\tgtk_spin_button_set_numeric(GTK_SPIN_BUTTON(btn), TRUE);\n\tgtk_spin_button_set_snap_to_ticks(GTK_SPIN_BUTTON(btn), TRUE);\n\tgtk_container_add(GTK_CONTAINER(box), btn);\n\tgtk_container_add(GTK_CONTAINER(b->wins.mapbox), box);\n\tgtk_widget_show_all(box);\n}\n\n/*\n * Remove the last island configuration.\n */\nstatic void\nmapbox_rem(struct bmigrate *b)\n{\n\tGList\t\t*list, *last;\n\n\tlist = gtk_container_get_children(GTK_CONTAINER(b->wins.mapbox));\n\tlast = g_list_last(list);\n\tgtk_widget_destroy(GTK_WIDGET(last->data));\n\tg_list_free(list);\n}\n\n/*\n * We've requested more or fewer islands for the mapped scenario.\n */\nvoid\nonislandspin(GtkSpinButton *spinbutton, gpointer dat)\n{\n\tstruct bmigrate\t*b = dat;\n\tguint\t\t oldsz, newsz;\n\tGList\t\t*list;\n\n\tlist = gtk_container_get_children(GTK_CONTAINER(b->wins.mapbox));\n\toldsz = g_list_length(list);\n\tg_list_free(list);\n\tnewsz = (guint)gtk_spin_button_get_value(spinbutton);\n\n\tif (newsz > oldsz) {\n\t\twhile (oldsz++ < newsz)\n\t\t\tmapbox_add(b, oldsz);\n\t} else if (oldsz > newsz) {\n\t\twhile (oldsz-- > newsz)\n\t\t\tmapbox_rem(b);\n\t}\n\n\ton_totalpop(b, gtk_notebook_get_current_page(b->wins.inputs));\n}\n\nint \nmain(int argc, char *argv[])\n{\n\tGtkBuilder\t*builder;\n\tstruct bmigrate\t b;\n\tint\t\t rc;\n\n\tmemset(&b, 0, sizeof(struct bmigrate));\n\tgtk_init(&argc, &argv);\n\n\trc = kplotcfg_default_palette(&b.clrs, &b.clrsz);\n\tg_assert(0 != rc);\n\n\t/*\n\t * Sanity-check to make sure that the hnode expression evaluator\n\t * is working properly.\n\t * You'll need to actually look at the debugging output to see\n\t * if that's the case, of course.\n\t */\n\thnode_test();\n\n\tbuilder = builder_get(\"bmigrate.glade\");\n\tif (NULL == builder) \n\t\treturn(EXIT_FAILURE);\n\n\thwin_init(&b.wins, builder);\n\tgtk_builder_connect_signals(builder, &b);\n\tg_object_unref(G_OBJECT(builder));\n\n\t/*\n\t * Have two running timers: once per second, forcing a refresh of\n\t * the window system; then another at four times per second\n\t * updating our cold statistics.\n\t */\n\tb.status_elapsed = g_timer_new();\n\tg_timeout_add_seconds(1, (GSourceFunc)on_sim_timer, &b);\n\tg_timeout_add_seconds(60, (GSourceFunc)on_sim_autosave, &b);\n\tg_timeout_add(250, (GSourceFunc)on_sim_copyout, &b);\n\tgtk_statusbar_push(b.wins.status, 0, \"No simulations.\");\n\n#ifdef MAC_INTEGRATION\n\tg_signal_connect(gtkosx_application_get(), \n\t\t\"NSApplicationWillTerminate\",\n\t\tG_CALLBACK(onterminate), &b);\n\tgtkosx_application_ready(gtkosx_application_get());\n#endif\n\n\tgtk_main();\n\tbmigrate_free(&b);\n\treturn(EXIT_SUCCESS);\n}\n", "meta": {"hexsha": "20eb7bdc4e586242aeb7c933b5aa2df4be643f62", "size": 33550, "ext": "c", "lang": "C", "max_stars_repo_path": "bmigrate.c", "max_stars_repo_name": "kristapsdz/bmigrate", "max_stars_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-03-03T17:13:19.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-03T17:13:19.000Z", "max_issues_repo_path": "bmigrate.c", "max_issues_repo_name": "kristapsdz/bmigrate", "max_issues_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bmigrate.c", "max_forks_repo_name": "kristapsdz/bmigrate", "max_forks_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.272513704, "max_line_length": 77, "alphanum_fraction": 0.6940387481, "num_tokens": 10046, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18476750166984326, "lm_q2_score": 0.017986214074511276, "lm_q1q2_score": 0.0033232678390464204}}
{"text": "#pragma once\n\n#include <memory>\n#include <string>\n\n#include <gsl/gsl>\n#include <nonstd/optional.hpp>\n\n#include \"chainerx/backend.h\"\n#include \"chainerx/context.h\"\n#include \"chainerx/device.h\"\n#include \"chainerx/kernel_registry.h\"\n\nnamespace chainerx {\nnamespace cuda {\n\nclass CudaDevice;\nclass CudaBackend;\n\nnamespace cuda_internal {\n\n// Creates a device instance.\n// This function is meant to be used from the backend class. Never use it for other purpose.\n// This is defined in cuda_internal namespace in order to make it a friend of CudaDevice\n// class.\ngsl::owner<CudaDevice*> CreateDevice(CudaBackend& backend, int index);\n\n}  // namespace cuda_internal\n\nclass CudaBackend : public Backend {\npublic:\n    static constexpr const char* kDefaultName = \"cuda\";\n    static constexpr const size_t kCudnnDefaultMaxWorkspaceSize = 8 * 1024 * 1024;\n    static constexpr const char* kCudnnMaxWorkspaceSizeEnvVarName = \"CHAINERX_CUDNN_MAX_WORKSPACE_SIZE\";\n\n    using Backend::Backend;\n\n    std::string GetName() const override;\n\n    int GetDeviceCount() const override;\n\n    bool SupportsTransfer(Device& src_device, Device& dst_device) override;\n\n    // TODO(hvy): Move to CudaDevice.\n    // Sets maximum cuDNN workspace size.\n    // This value is shared across threads.\n    void SetCudnnMaxWorkspaceSize(size_t max_workspace_size);\n\n    // TODO(hvy): Move to CudaDevice.\n    // Gets maximum cuDNN workspace size.\n    size_t GetCudnnMaxWorkspaceSize();\n\n    static KernelRegistry& GetGlobalKernelRegistry() {\n        static gsl::owner<KernelRegistry*> global_kernel_registry = new KernelRegistry{};\n        return *global_kernel_registry;\n    }\n\nprotected:\n    KernelRegistry& GetParentKernelRegistry() override { return GetGlobalKernelRegistry(); }\n\nprivate:\n    std::unique_ptr<Device> CreateDevice(int index) override;\n\n    // TODO(hvy): Move to CudaDevice.\n    nonstd::optional<size_t> cudnn_max_workspace_size_{};\n\n    std::mutex mutex_;\n};\n\n}  // namespace cuda\n}  // namespace chainerx\n", "meta": {"hexsha": "9e5742c596568078fc4e75aeb7a6448392823981", "size": 1986, "ext": "h", "lang": "C", "max_stars_repo_path": "chainerx_cc/chainerx/cuda/cuda_backend.h", "max_stars_repo_name": "tkerola/chainer", "max_stars_repo_head_hexsha": "572f6eef2c3f1470911ac08332c2b5c3440edf44", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-26T10:27:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-26T10:27:25.000Z", "max_issues_repo_path": "chainerx_cc/chainerx/cuda/cuda_backend.h", "max_issues_repo_name": "tkerola/chainer", "max_issues_repo_head_hexsha": "572f6eef2c3f1470911ac08332c2b5c3440edf44", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chainerx_cc/chainerx/cuda/cuda_backend.h", "max_forks_repo_name": "tkerola/chainer", "max_forks_repo_head_hexsha": "572f6eef2c3f1470911ac08332c2b5c3440edf44", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-07-16T00:24:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-26T10:27:27.000Z", "avg_line_length": 27.5833333333, "max_line_length": 104, "alphanum_fraction": 0.7406847936, "num_tokens": 475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11596071214366649, "lm_q2_score": 0.02843603602953799, "lm_q1q2_score": 0.003297462988528184}}
{"text": "///\n/// @file\n///\n/// @brief This file contains functions and macros that are used in the sanity\n/// checks.\n///\n/// @author Mirko Myllykoski (mirkom@cs.umu.se), Ume\u00e5 University\n///\n/// @internal LICENSE\n///\n/// Copyright (c) 2019-2020, Ume\u00e5 Universitet\n///\n/// Redistribution and use in source and binary forms, with or without\n/// modification, are permitted provided that the following conditions are met:\n///\n/// 1. Redistributions of source code must retain the above copyright notice,\n///    this list of conditions and the following disclaimer.\n///\n/// 2. Redistributions in binary form must reproduce the above copyright notice,\n///    this list of conditions and the following disclaimer in the documentation\n///    and/or other materials provided with the distribution.\n///\n/// 3. Neither the name of the copyright holder nor the names of its\n///    contributors may be used to endorse or promote products derived from this\n///    software without specific prior written permission.\n///\n/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n/// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n/// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n/// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n/// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n/// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n/// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n/// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n/// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n/// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n/// POSSIBILITY OF SUCH DAMAGE.\n///\n\n#ifndef STARNEIG_COMMON_SANITY\n#define STARNEIG_COMMON_SANITY\n\n#include <starneig_config.h>\n#include <starneig/configuration.h>\n\n#ifdef STARNEIG_ENABLE_SANITY_CHECKS\n\n#include \"math.h\"\n#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n#include <cblas.h>\n\n///\n/// @brief Reports a sanity check error. Aborts the program.\n///\n/// @param[in] message\n///         Message.\n///\n#define STARNEIG_SANITY_REPORT(message) { \\\n    fprintf(stderr, \"[starneig][sanity] %s:%d: %s\\n\", \\\n        __FILE__, __LINE__, message); \\\n    abort(); \\\n}\n\n///\n/// @brief Reports a sanity check error. Aborts the program.\n///\n/// @param[in] message\n///         printf formatted message.\n///\n/// @param[in] ...\n///         Additional printf compatible arguments.\n///\n#define STARNEIG_SANITY_REPORT_ARGS(message, ...) { \\\n    fprintf(stderr, \"[starneig][sanity] %s:%d: %s\\n\", \\\n        __FILE__, __LINE__, message, __VA_ARGS__); \\\n    abort(); \\\n}\n\n///\n/// @brief Checks a conditional statement and reports a sanity check error if\n/// the condition is not satisfied. Aborts the program.\n///\n/// @param[in] cond\n///         The conditional statement.\n///\n/// @param[in] message\n///         Message.\n///\n#define STARNEIG_SANITY_CHECK(cond, message) { \\\n    if (!(cond)) { \\\n        fprintf(stderr, \"[starneig][sanity] %s:%d: %s\\n\", \\\n            __FILE__, __LINE__, message); \\\n        abort(); \\\n    } \\\n}\n\n///\n/// @brief Checks a conditional statement and reports a sanity check error if\n/// the condition is not satisfied. Aborts the program.\n///\n/// @param[in] cond\n///         The conditional statement.\n///\n/// @param[in] message\n///         printf formatted message.\n///\n/// @param[in] ...\n///         Additional printf compatible arguments.\n///\n#define STARNEIG_SANITY_CHECK_ARGS(cond, message, ...) { \\\n    if (!(cond)) { \\\n        fprintf(stderr, \"[starneig][sanity] %s:%d: %s\\n\", \\\n            __FILE__, __LINE__, message, __VA_ARGS__); \\\n        abort(); \\\n    } \\\n}\n\nstatic inline void starneig_sanity_check_inf(\n    int rbegin, int rend, int cbegin, int cend, int ldA, double const *A,\n    char const *mat, char const *file, int line)\n{\n    if (A == NULL)\n        return;\n\n    for (int i = cbegin; i < cend; i++) {\n        for (int j = rbegin; j < rend; j++) {\n            if (isinf(A[i*ldA+j])) {\n                fprintf(stderr,\n                    \"[starneig][sanity] %s:%d: Matrix %s has an infinite \"\n                    \"element.\\n\", file, line, mat);\n                abort();\n            }\n            if (isnan(A[i*ldA+j])) {\n                fprintf(stderr,\n                    \"[starneig][sanity] %s:%d: Matrix %s has a NaN element.\\n\",\n                    file, line, mat);\n                abort();\n            }\n        }\n    }\n}\n\n#define STARNEIG_SANITY_CHECK_INF(rbegin, rend, cbegin, cend, ldA, A, mat) \\\n    starneig_sanity_check_inf(rbegin, rend, cbegin, cend, ldA, A, mat, \\\n        __FILE__, __LINE__)\n\nstatic inline void starneig_sanity_check_multiplicities(\n    int n, double *real, double *imag, char const *file, int line)\n{\n    for (int i = 0; i < n; i++) {\n        double lambda_re = real[i];\n        double lambda_im = imag[i];\n\n        if (lambda_im == 0.0) { // real eigenvalue\n            for (int j = i+1; j < n; j++) {\n                if (real[j] == lambda_re && imag[j] == 0.0) {\n                    fprintf(stderr,\n                        \"[starneig][sanity] %s:%d: Multiple eigenvalues at \"\n                        \"S(%d,%d) and S(%d,%d).\\n\", file, line, i, i, j, j);\n                    abort();\n                }\n            }\n        }\n        else { // complex eigenvalue\n            for (int j = i+1; j < n; j++) {\n                if (real[j] == lambda_re && imag[j] == lambda_im) {\n                    fprintf(stderr,\n                        \"[starneig][sanity] %s:%d: Multiple eigenvalues at \"\n                        \"S(%d:%d,%d:%d) and S(%d:%d,%d:%d).\\n\",\n                        file, line, i, i+1, i, i+1, j, j+1, j, j+1);\n                    abort();\n                }\n            }\n        }\n    }\n}\n\n///\n/// @brief A sanity check that checks for multiple eigenvalues.\n///\n/// @param[in] n\n///         The length of the vectors real and imag.\n///\n/// @param[in] real\n///         A vector that contains the real parts of the eigenvalues.\n///\n/// @param[in] imag\n///         A vector that contains the imaginary parts of the eigenvalues.\n///\n#define STARNEIG_SANITY_CHECK_MULTIPLICITIES(n, real, imag) \\\n    starneig_sanity_check_multiplicities(n, real, imag, __FILE__, __LINE__)\n\nstatic inline void starneig_sanity_check_orthogonality(\n    int n, int ldQ, double const *Q, char const *mat, char const *file,\n    int line)\n{\n    if (Q == NULL)\n        return;\n\n    starneig_sanity_check_inf(0, n, 0, n, ldQ, Q, mat, file, line);\n\n    size_t ldT;\n    double *T = starneig_alloc_matrix(n, n, sizeof(double), &ldT);\n\n    cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans, n, n, n, 1.0,\n        Q, ldQ, Q, ldQ, 0.0, T, ldT);\n\n    double dot = 0.0;\n    for (int i = 0; i < n; i++)\n        for (int j = 0; j < n; j++)\n            dot += squ(T[i*ldT+j] - (i == j ? 1.0 : 0.0));\n\n    double norm = ((long long)1<<52) * sqrt(dot)/sqrt(n);\n\n    if (10000 < norm || isnan(norm)) {\n        fprintf(stderr,\n            \"[starneig][sanity] %s:%d: Matrix %s is not orthogonal.\\n\",\n            file, line, mat);\n        fprintf(stderr,\n            \"[starneig][sanity] %s:%d: |%s %s^T - I| / |I| = %.0f u.\\n\",\n            file, line, mat, mat, norm);\n        abort();\n    }\n\n    starneig_free_matrix(T);\n}\n\n///\n/// @brief A sanity check that makes sure a matrix Q is orthogonal.\n///\n/// @param[in] n\n///         The order of the matrix Q.\n///\n/// @param[in] ldQ\n///         The leading dimension of the matrix Q.\n///\n/// @param[in] Q\n///         The matrix Q.\n///\n/// @param[in] mat\n///         A string that identifies the matrix Q.\n///\n#define STARNEIG_SANITY_CHECK_ORTHOGONALITY(n, ldQ, Q, mat) \\\n    starneig_sanity_check_orthogonality(n, ldQ, Q, mat, __FILE__, __LINE__)\n\nstruct starneig_sanity_check_args {\n    double *A; size_t ldA;\n    double *B; size_t ldB;\n};\n\nstatic inline struct starneig_sanity_check_args *\nstarneig_sanity_check_residuals_begin(\n    int n, int ldQ, int ldZ, int ldA, int ldB, double const *Q, double const *Z,\n    double const *A, double const *B, char const *file, int line)\n{\n    starneig_sanity_check_inf(0, n, 0, n, ldA, A, \"A\", file, line);\n    starneig_sanity_check_inf(0, n, 0, n, ldB, B, \"B\", file, line);\n    starneig_sanity_check_orthogonality(n, ldQ, Q, \"Q\", file, line);\n    starneig_sanity_check_orthogonality(n, ldZ, Z, \"Z\", file, line);\n\n    if (Z == NULL) {\n        Z = Q; ldZ = ldQ;\n    }\n\n    struct starneig_sanity_check_args *ret =\n        malloc(sizeof(struct starneig_sanity_check_args));\n\n    size_t ldT;\n    double *T = starneig_alloc_matrix(n, n, sizeof(double), &ldT);\n\n    ret->A = starneig_alloc_matrix(n, n, sizeof(double), &ret->ldA);\n    cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, n, n, n, 1.0,\n        Q, ldQ, A, ldA, 0.0, T, ldT);\n    cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans, n, n, n, 1.0,\n        T, ldT, Z, ldZ, 0.0, ret->A, ret->ldA);\n\n    ret->B = NULL; ret->ldB = 0;\n    if (B != NULL) {\n        ret->B = starneig_alloc_matrix(n, n, sizeof(double), &ret->ldB);\n        cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, n, n, n, 1.0,\n            Q, ldQ, B, ldB, 0.0, T, ldT);\n        cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans, n, n, n, 1.0,\n            T, ldT, Z, ldZ, 0.0, ret->B, ret->ldB);\n    }\n\n    starneig_free_matrix(T);\n\n    starneig_sanity_check_inf(0, n, 0, n, ret->ldA, ret->A, \"A\", file, line);\n    starneig_sanity_check_inf(0, n, 0, n, ret->ldB, ret->B, \"B\", file, line);\n\n    return ret;\n}\n\n///\n/// @brief The first part of a sanity check that makes sure a matrix pencil\n/// Q (A,B) X^T and an updated matrix pencil ~Q (~A,~B) ~X^T are equivalent.\n///\n/// @param[in] name\n///         An unique identifier.\n///\n/// @param[in] n\n///         The order of the matrices A, B, Q and Z.\n///\n/// @param[in] ldQ\n///         The leading dimension of the matrix Q.\n///\n/// @param[in] ldZ\n///         The leading dimension of the matrix Z.\n///\n/// @param[in] ldA\n///         The leading dimension of the matrix A.\n///\n/// @param[in] ldB\n///         The leading dimension of the matrix B.\n///\n/// @param[in] Q\n///         The matrix Q.\n///\n/// @param[in] Z\n///         The matrix Z.\n///\n/// @param[in] A\n///         The matrix A.\n///\n/// @param[in] B\n///         The matrix B.\n///\n#define STARNEIG_SANITY_CHECK_RESIDUALS_BEGIN( \\\n    name, n, ldQ, ldZ, ldA, ldB, Q, Z, A, B) \\\n    struct starneig_sanity_check_args *name = \\\n    starneig_sanity_check_residuals_begin( \\\n        n, ldQ, ldZ, ldA, ldB, Q, Z, A, B, __FILE__, __LINE__)\n\nstatic inline void starneig_sanity_check_residuals_end(\n    int n, int ldQ, int ldZ, int ldA, int ldB, double const *Q, double const *Z,\n    double const *A, double const *B,\n    struct starneig_sanity_check_args const *args, char const *file, int line)\n{\n    struct starneig_sanity_check_args *ret =\n        starneig_sanity_check_residuals_begin(\n            n, ldQ, ldZ, ldA, ldB, Q, Z, A, B, file, line);\n\n    int failure = 0;\n\n    {\n        double dot = 0.0;\n        for(int i = 0; i < n; ++i )\n            for(int j = 0; j < n; ++j )\n                dot += squ(ret->A[ret->ldA*i+j] - args->A[args->ldA*i+j]);\n\n        double a_dot = 0.0;\n        for(int i = 0; i < n; ++i )\n            for(int j = 0; j < n; ++j )\n                a_dot += squ(args->A[args->ldA*i+j]);\n\n        double norm = ((long long)1<<52) * sqrt(dot)/sqrt(a_dot);\n\n        if (10000 < norm || isnan(norm)) {\n            fprintf(stderr,\n                \"[starneig][sanity] %s:%d: Residual check failed for the \"\n                \"matrix A.\\n\", file, line);\n            fprintf(stderr,\n                \"[starneig][sanity] %s:%d: The norm was %.0f u.\\n\",\n                file, line, norm);\n            failure++;\n        }\n    }\n\n    if (B != NULL) {\n        double dot = 0.0;\n        for(int i = 0; i < n; ++i )\n            for(int j = 0; j < n; ++j )\n                dot += squ(ret->B[ret->ldB*i+j] - args->B[args->ldB*i+j]);\n\n        double a_dot = 0.0;\n        for(int i = 0; i < n; ++i )\n            for(int j = 0; j < n; ++j )\n                a_dot += squ(args->B[args->ldB*i+j]);\n\n        double norm = ((long long)1<<52) * sqrt(dot)/sqrt(a_dot);\n\n        if (10000 < norm || isnan(norm)) {\n            fprintf(stderr,\n                \"[starneig][sanity] %s:%d: Residual check failed for the \"\n                \"matrix B.\\n\", file, line);\n            fprintf(stderr,\n                \"[starneig][sanity] %s:%d: The norm was %.0f u.\\n\",\n                file, line, norm);\n            failure++;\n        }\n    }\n\n    if (failure)\n        abort();\n\n    starneig_free_matrix(ret->A);\n    starneig_free_matrix(ret->B);\n    free(ret);\n}\n\n///\n/// @brief The second part of a sanity check that makes sure a matrix pencil\n/// Q (A,B) X^T and an updated matrix pencil ~Q (~A,~B) ~X^T are equivalent.\n///\n/// @param[in] name\n///         An unique identifier.\n///\n/// @param[in] n\n///         The order of the matrices A, B, Q and Z.\n///\n/// @param[in] ldQ\n///         The leading dimension of the matrix Q.\n///\n/// @param[in] ldZ\n///         The leading dimension of the matrix Z.\n///\n/// @param[in] ldA\n///         The leading dimension of the matrix A.\n///\n/// @param[in] ldB\n///         The leading dimension of the matrix B.\n///\n/// @param[in] Q\n///         The matrix Q.\n///\n/// @param[in] Z\n///         The matrix Z.\n///\n/// @param[in] A\n///         The matrix A.\n///\n/// @param[in] B\n///         The matrix B.\n///\n#define STARNEIG_SANITY_CHECK_RESIDUALS_END( \\\n    name, n, ldQ, ldZ, ldA, ldB, Q, Z, A, B) \\\n    starneig_sanity_check_residuals_end( \\\n        n, ldQ, ldZ, ldA, ldB, Q, Z, A, B, name, __FILE__, __LINE__); \\\n    if (name != NULL) { \\\n        starneig_free_matrix(name->A); \\\n        starneig_free_matrix(name->B); \\\n        free(name); \\\n        name = NULL; \\\n    }\n\n///\n/// @brief Skips the second part of a sanity check that makes sure a matrix\n/// pencil Q (A,B) X^T and an updated matrix pencil ~Q (~A,~B) ~X^T are\n/// equivalent.\n///\n/// @param[in] name\n///         An unique identifier.\n///\n#define STARNEIG_SANITY_CHECK_RESIDUALS_SKIP(name) \\\n    if (name != NULL) { \\\n        starneig_free_matrix(name->A); \\\n        starneig_free_matrix(name->B); \\\n        free(name); \\\n        name = NULL; \\\n    }\n\nstatic inline void starneig_sanity_check_bulges(\n    int begin, int shifts, int n, int ldA, int ldB,\n    double const *A, double const *B, char const *file, int line)\n{\n    starneig_sanity_check_inf(\n        0, n, begin, begin+3*(shifts/2)+1, ldA, A, \"A\", file, line);\n    starneig_sanity_check_inf(\n        0, n, begin, begin+3*(shifts/2)+1, ldB, B, \"B\", file, line);\n\n    if (n < begin+3*(shifts/2)+1) {\n        fprintf(stderr,\n            \"[starneig][sanity] %s:%d: Matrix A has an invalid bulge.\\n\",\n            file, line);\n        abort();\n    }\n\n    double const *_A = A+begin*ldA+begin;\n    double const *_B = B != NULL ? B+begin*ldB+begin : NULL;\n    int _n = n - begin;\n    for (int i = 0; i < shifts/2; i++) {\n        for (int j = 3*i+4; j < _n; j++) {\n            if (_A[3*i*ldA+j] != 0.0 || _A[(3*i+1)*ldA+j] != 0.0 ||\n            _A[(3*i+2)*ldA+j] != 0.0) {\n                fprintf(stderr,\n                    \"[starneig][sanity] %s:%d: Matrix A has an invalid \"\n                    \"bulge.\\n\", file, line);\n                abort();\n            }\n        }\n        for (int j = 3*i+3; _B != NULL && j < _n; j++) {\n            if (_B[3*i*ldB+j] != 0.0 || _B[(3*i+1)*ldB+j] != 0.0 ||\n            _B[(3*i+2)*ldB+j] != 0.0) {\n                fprintf(stderr,\n                    \"[starneig][sanity] %s:%d: Matrix B has invalid bulge .\\n\",\n                    file, line);\n                abort();\n            }\n        }\n        if (_B != NULL &&\n        (_B[3*i*ldB+3*i+1] != 0.0 || _B[3*i*ldB+3*i+2] != 0.0)) {\n            fprintf(stderr,\n                \"[starneig][sanity] %s:%d: Matrix B has invalid bulge.\\n\",\n                file, line);\n            abort();\n        }\n    }\n}\n\n///\n/// @brief A sanity check that makes sure that matrix pencil (A,B) contains the\n/// correct number of bulges.\n///\n/// @param[in] begin\n///         The column that should contain the first bulge.\n///\n/// @param[in] shifts\n///         The number of shifts (shifts/2 bulges).\n///\n/// @param[in] n\n///         The order of the matrices A and B.\n///\n/// @param[in] ldA\n///         The leading dimension of the matrix A.\n///\n/// @param[in] ldB\n///         The leading dimension of the matrix B.\n///\n/// @param[in] A\n///         The matrix A.\n///\n/// @param[in] B\n///         The matrix B.\n///\n#define STARNEIG_SANITY_CHECK_BULGES(begin, shifts, n, ldA, ldB, A, B) \\\n    starneig_sanity_check_bulges( \\\n        begin, shifts, n, ldA, ldB, A, B, __FILE__, __LINE__)\n\nstatic inline void starneig_sanity_check_schur(\n    int begin, int end, int n, int ldA, int ldB,\n    double const *A, double const *B, char const *file, int line)\n{\n    starneig_sanity_check_inf(0, n, begin, end, ldA, A, \"A\", file, line);\n    starneig_sanity_check_inf(0, n, begin, end, ldB, B, \"B\", file, line);\n\n    const double safmin = dlamch(\"S\");\n\n    int two_by_two = 0;\n    for (int i = begin; i < end; i++) {\n        if (i+1 < end && A[i*ldA+i+1] != 0.0) {\n            if (two_by_two) {\n                fprintf(stderr,\n                    \"[starneig][sanity] %s:%d: Matrix A is not in Schur \"\n                    \"form.\\n\", file, line);\n                abort();\n            }\n\n            if (B != NULL) {\n                if (B[(i+1)*ldB+i] != 0.0 || B[i*ldB+i+1] != 0.0) {\n                    fprintf(stderr,\n                        \"[starneig][sanity] %s:%d: Matrix pencil (A,B) \"\n                        \"contains a non-normalized 2-by-2 block.\\n\",\n                        file, line);\n                    abort();\n                }\n\n                if (B[i*ldB+i] == 0.0 || B[(i+1)*ldB+i+1] == 0.0) {\n                    fprintf(stderr,\n                        \"[starneig][sanity] %s:%d: Matrix B is singular.\",\n                        file, line);\n                    abort();\n                }\n\n                double s1, s2, wr1, wr2, wi;\n\n                extern void dlag2_(double const *, int const *, double const *,\n                    int const *, double const *, double *, double *,\n                    double *, double *, double *);\n\n                dlag2_(&A[i*ldA+i], &ldA, &B[i*ldB+i], &ldB, &safmin,\n                    &s1, &s2, &wr1, &wr2, &wi);\n\n                if (wi == 0.0) {\n                    fprintf(stderr,\n                        \"[starneig][sanity] %s:%d: Matrix pencil (A,B) \"\n                        \"contains a fake 2-by-2 block.\\n\", file, line);\n                    abort();\n                }\n            }\n            else {\n                if (A[i*ldA+i] != A[(i+1)*ldA+i+1]) {\n                    fprintf(stderr,\n                        \"[starneig][sanity] %s:%d: Matrix A contains a \"\n                        \"non-normalized 2-by-2 block.\\n\",\n                        file, line);\n                    abort();\n                }\n\n                double a[] = {\n                    A[i*ldA+i], A[i*ldA+i+1], A[(i+1)*ldA+i], A[(i+1)*ldA+i+1]\n                };\n\n                double rt1r, rt1i, rt2r, rt2i, cs, ss;\n\n                extern void dlanv2_(\n                    double *, double *, double *, double *, double *,\n                    double *, double *, double *, double *, double *);\n\n                dlanv2_(&a[0], &a[2], &a[1], &a[3],\n                    &rt1r, &rt1i, &rt2r, &rt2i, &cs, &ss);\n\n                if (rt1i == 0.0 || rt2i == 0.0) {\n                    fprintf(stderr,\n                        \"[starneig][sanity] %s:%d: Matrix A contains a fake \"\n                        \"2-by-2 block.\\n\", file, line);\n                    abort();\n                }\n            }\n\n            two_by_two = 1;\n        }\n        else {\n            two_by_two = 0;\n        }\n\n        for (int j = i+2; j < n; j++) {\n            if (A[i*ldA+j] != 0.0) {\n                fprintf(stderr,\n                    \"[starneig][sanity] %s:%d: Matrix A is not in Schur \"\n                    \"form.\\n\", file, line);\n                abort();\n            }\n        }\n    }\n\n    if (B != NULL) {\n        for (int i = begin; i < end; i++) {\n            for (int j = i+2; j < n; j++) {\n                if (B[i*ldB+j] != 0.0) {\n                    fprintf(stderr,\n                        \"[starneig][sanity] %s:%d: Matrix B is not in upper \"\n                        \"Hessenberg form.\\n\", file, line);\n                    abort();\n                }\n            }\n        }\n    }\n}\n\n///\n/// @brief A sanity check that makes sure that matrix pencil (A,B) is in Schur\n/// form.\n///\n/// @param[in] begin\n///         The first column to check.\n///\n/// @param[in] end\n///         The last column to check + 1;\n///\n/// @param[in] n\n///         The order of the matrices A and B.\n///\n/// @param[in] ldA\n///         The leading dimension of the matrix A.\n///\n/// @param[in] ldB\n///         The leading dimension of the matrix B.\n///\n/// @param[in] A\n///         The matrix A.\n///\n/// @param[in] B\n///         The matrix B.\n///\n#define STARNEIG_SANITY_CHECK_SCHUR(begin, end, n, ldA, ldB, A, B) \\\n    starneig_sanity_check_schur( \\\n        begin, end, n, ldA, ldB, A, B, __FILE__, __LINE__)\n\nstatic inline void starneig_sanity_check_hessenberg(\n    int begin, int end, int n, int ldA, int ldB,\n    double const *A, double const *B, char const *file, int line)\n{\n    starneig_sanity_check_inf(0, n, begin, end, ldA, A, \"A\", file, line);\n    starneig_sanity_check_inf(0, n, begin, end, ldB, B, \"B\", file, line);\n\n    for (int i = begin; i < end; i++) {\n        for (int j = i+2; j < n; j++) {\n            if (A[i*ldA+j] != 0.0) {\n                fprintf(stderr,\n                    \"[starneig][sanity] %s:%d: Matrix A is not in upper \"\n                    \"Hessenberg form.\\n\", file, line);\n                abort();\n            }\n        }\n    }\n    for (int i = begin; B != NULL && i < end; i++) {\n        for (int j = i+1; j < n; j++) {\n            if (B[i*ldB+j] != 0.0) {\n                fprintf(stderr,\n                    \"[starneig][sanity] %s:%d: Matrix B is not in upper \"\n                    \"triangular form.\\n\", file, line);\n                abort();\n            }\n        }\n    }\n}\n\n///\n/// @brief A sanity check that makes sure that matrix pencil (A,B) is in\n/// Hessenberg-triangular form.\n///\n/// @param[in] begin\n///         The first column to check.\n///\n/// @param[in] end\n///         The last column to check + 1;\n///\n/// @param[in] n\n///         The order of the matrices A and B.\n///\n/// @param[in] ldA\n///         The leading dimension of the matrix A.\n///\n/// @param[in] ldB\n///         The leading dimension of the matrix B.\n///\n/// @param[in] A\n///         The matrix A.\n///\n/// @param[in] B\n///         The matrix B.\n///\n#define STARNEIG_SANITY_CHECK_HESSENBERG(begin, end, n, ldA, ldB, A, B) \\\n    starneig_sanity_check_hessenberg( \\\n        begin, end, n, ldA, ldB, A, B, __FILE__, __LINE__)\n\n#else\n\n#define STARNEIG_SANITY_REPORT(message) {}\n#define STARNEIG_SANITY_REPORT_ARGS(message, ...) {}\n#define STARNEIG_SANITY_CHECK(cond, message) {}\n#define STARNEIG_SANITY_CHECK_ARGS(cond, message, ...) {}\n#define STARNEIG_SANITY_CHECK_INF(rbegin, rend, cbegin, cend, ldA, A, mat) {}\n#define STARNEIG_SANITY_CHECK_MULTIPLICITIES(n, real, imag) {}\n#define STARNEIG_SANITY_CHECK_ORTHOGONALITY(n, ldQ, Q, mat) {}\n#define STARNEIG_SANITY_CHECK_RESIDUALS_BEGIN( \\\n    name, n, ldQ, ldZ, ldA, ldB, Q, Z, A, B) {}\n#define STARNEIG_SANITY_CHECK_RESIDUALS_END( \\\n    name, n, ldQ, ldZ, ldA, ldB, Q, Z, A, B) {}\n#define STARNEIG_SANITY_CHECK_RESIDUALS_SKIP(name) {}\n#define STARNEIG_SANITY_CHECK_BULGES(begin, shifts, n, ldA, ldB, A, B) {}\n#define STARNEIG_SANITY_CHECK_SCHUR(begin, end, n, ldA, ldB, A, B) {}\n#define STARNEIG_SANITY_CHECK_HESSENBERG(begin, end, n, ldA, ldB, A, B) {}\n\n#endif // STARNEIG_ENABLE_SANITY_CHECKS\n\n#endif // STARNEIG_COMMON_SANITY\n", "meta": {"hexsha": "92d9aa30d0011880227fb0953c091cc6e00f9774", "size": 23912, "ext": "h", "lang": "C", "max_stars_repo_path": "src/common/sanity.h", "max_stars_repo_name": "NLAFET/StarNEig", "max_stars_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2019-04-28T17:13:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-24T12:30:19.000Z", "max_issues_repo_path": "src/common/sanity.h", "max_issues_repo_name": "NLAFET/StarNEig", "max_issues_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/common/sanity.h", "max_forks_repo_name": "NLAFET/StarNEig", "max_forks_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-04-30T12:14:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-14T09:41:23.000Z", "avg_line_length": 31.4631578947, "max_line_length": 80, "alphanum_fraction": 0.5288976246, "num_tokens": 7020, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09947022189081604, "lm_q2_score": 0.03308597719693549, "lm_q1q2_score": 0.003291069493253653}}
{"text": "#ifndef libceed_solids_examples_cl_options_h\n#define libceed_solids_examples_cl_options_h\n\n#include <petsc.h>\n#include \"../include/structs.h\"\n\n// Process general command line options\nPetscErrorCode ProcessCommandLineOptions(MPI_Comm comm, AppCtx app_ctx);\n\n#endif // libceed_solids_examples_cl_options_h\n", "meta": {"hexsha": "c4b3844a1b13b2eec5fdbca1591a43cd9d01594e", "size": 304, "ext": "h", "lang": "C", "max_stars_repo_path": "examples/solids/include/cl-options.h", "max_stars_repo_name": "wence-/libCEED", "max_stars_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/solids/include/cl-options.h", "max_issues_repo_name": "wence-/libCEED", "max_issues_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/solids/include/cl-options.h", "max_forks_repo_name": "wence-/libCEED", "max_forks_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6363636364, "max_line_length": 72, "alphanum_fraction": 0.8421052632, "num_tokens": 67, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.07921032410902436, "lm_q2_score": 0.04146227182308095, "lm_q1q2_score": 0.0032842399894027104}}
{"text": "#pragma once\n\n#include <emerald/util/foundation.h>\n\n#define gsl_FEATURE_MAKE_SPAN_TO_STD 20\n#include <gsl/gsl-lite.hpp>\n\n#include <array>\n\nnamespace emerald::shallow_weaver {\n\nusing namespace emerald::util;\n\ntemplate <typename T>\nusing span = gsl::span<T>;\n\nenum class Time_integration { FIRST_ORDER, RUNGE_KUTTA_2, RUNGE_KUTTA_4 };\n\nusing int2 = std::array<int, 2>;\nusing int4 = std::array<int, 4>;\nusing float2 = std::array<float, 2>;\nusing float4 = std::array<float, 4>;\n\n}  // namespace emerald::shallow_weaver", "meta": {"hexsha": "fe9174369d129d812106e2d58f1a7aff29a82641", "size": 514, "ext": "h", "lang": "C", "max_stars_repo_path": "emerald/shallow_weaver/foundation.h", "max_stars_repo_name": "blackencino/emerald", "max_stars_repo_head_hexsha": "3c4823dbdeff7c63007ff359d262608227f5433f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-08-16T17:56:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-25T21:55:39.000Z", "max_issues_repo_path": "emerald/shallow_weaver/foundation.h", "max_issues_repo_name": "blackencino/emerald", "max_issues_repo_head_hexsha": "3c4823dbdeff7c63007ff359d262608227f5433f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "emerald/shallow_weaver/foundation.h", "max_forks_repo_name": "blackencino/emerald", "max_forks_repo_head_hexsha": "3c4823dbdeff7c63007ff359d262608227f5433f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.4166666667, "max_line_length": 74, "alphanum_fraction": 0.7392996109, "num_tokens": 148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.12085324515618749, "lm_q2_score": 0.02716922858177957, "lm_q1q2_score": 0.0032834894424983024}}
{"text": "/*****************************************************************\\\n           __\n          / /\n\t\t / /                     __  __\n\t\t/ /______    _______    / / / / ________   __       __\n\t   / ______  \\  /_____  \\  / / / / / _____  | / /      / /\n\t  / /      | / _______| / / / / / / /____/ / / /      / /\n\t / /      / / / _____  / / / / / / _______/ / /      / /\n\t/ /      / / / /____/ / / / / / / |______  / |______/ /\n   /_/      /_/ |________/ / / / /  \\_______/  \\_______  /\n                          /_/ /_/                     / /\n\t\t\t                                         / /\n\t\t       High Level Game Framework            /_/\n\n  ---------------------------------------------------------------\n\n  Copyright (c) 2007-2011 - Rodrigo Braz Monteiro.\n  This file is subject to the terms of halley_license.txt.\n\n\\*****************************************************************/\n\n#pragma once\n\n#include <memory>\n#include \"halley/data_structures/vector.h\"\n#include <gsl/gsl>\n\n#include \"halley/core/api/audio_api.h\"\n\nstruct OggVorbis_File;\n\n#if defined(_MSC_VER) || defined(__clang__)\nusing OggOffsetType = int64_t;\n#else\nusing OggOffsetType = long int;\n#endif\n\nnamespace Halley {\n\tclass ResourceData;\n\tclass ResourceDataReader;\n\n\tclass VorbisData {\n\tpublic:\n\t\tVorbisData(std::shared_ptr<ResourceData> resource, bool open);\n\t\t~VorbisData();\n\n\t\tsize_t read(gsl::span<Vector<float>> dst);\n\t\tsize_t read(AudioMultiChannelSamples dst, size_t nChannels);\n\n\t\tsize_t getNumSamples() const; // Per channel\n\t\tint getSampleRate() const;\n\t\tint getNumChannels() const;\n\n\t\tvoid close();\n\t\tvoid reset();\n\t\tvoid seek(double t);\n\t\tvoid seek(size_t sample);\n\t\tsize_t tell() const;\n\n\t\tsize_t getSizeBytes() const;\n\n\tprivate:\n\t\tvoid open();\n\t\tstatic size_t vorbisRead(void* ptr, size_t size, size_t nmemb, void* datasource);\n\t\tstatic int vorbisSeek(void *datasource, OggOffsetType offset, int whence);\n\t\tstatic int vorbisClose(void *datasource);\n\t\tstatic long vorbisTell(void *datasource);\n\n\t\tstd::shared_ptr<ResourceData> resource;\n\t\tstd::shared_ptr<ResourceDataReader> stream;\n\t\tOggVorbis_File* file;\n\t\t\n\t\tbool streaming;\n\t\tlong long pos;\n\t};\n}\n", "meta": {"hexsha": "3a69756808d6fb623ee8ef7133f2c0b820a392a7", "size": 2130, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engine/audio/include/halley/audio/vorbis_dec.h", "max_stars_repo_name": "amrezzd/halley", "max_stars_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/engine/audio/include/halley/audio/vorbis_dec.h", "max_issues_repo_name": "amrezzd/halley", "max_issues_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engine/audio/include/halley/audio/vorbis_dec.h", "max_forks_repo_name": "amrezzd/halley", "max_forks_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6623376623, "max_line_length": 83, "alphanum_fraction": 0.534741784, "num_tokens": 544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15817436068510188, "lm_q2_score": 0.020645933074267656, "lm_q1q2_score": 0.0032656572647696866}}
{"text": "\n#pragma once\n\n#include <gsl/gsl_assert>\n#include <src/util/Logging.h>\n\n#ifndef NDEBUG\n    //#define MI_EXPECTS(x) Expects(x)\n    //#define MI_ENSURES(x) Ensures(x)\n\n#define MI_EXPECTS(x) \\\n  do { \\\n    if (!(x)) { \\\n        LOG(ERROR) << \"assertion failed: \" << #x; \\\n        std::terminate(); \\\n    } \\\n  } while (0)\n\n#define MI_ENSURES(x) \\\n  do { \\\n    if (!(x)) { \\\n        LOG(ERROR) << \"assertion failed: \" << #x; \\\n        std::terminate(); \\\n    } \\\n  } while (0)\n#else\n    #define MI_EXPECTS(x)\n    #define MI_ENSURES(x)\n#endif", "meta": {"hexsha": "066712388bd696d0760e9a9a20f0d6733d23551f", "size": 537, "ext": "h", "lang": "C", "max_stars_repo_path": "src/common/Assert.h", "max_stars_repo_name": "oldas1/Riner", "max_stars_repo_head_hexsha": "492804079eb223e6d4ffd5f5f44283162eaf421b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/common/Assert.h", "max_issues_repo_name": "oldas1/Riner", "max_issues_repo_head_hexsha": "492804079eb223e6d4ffd5f5f44283162eaf421b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/common/Assert.h", "max_forks_repo_name": "oldas1/Riner", "max_forks_repo_head_hexsha": "492804079eb223e6d4ffd5f5f44283162eaf421b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.5172413793, "max_line_length": 51, "alphanum_fraction": 0.530726257, "num_tokens": 167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06097517574577167, "lm_q2_score": 0.05340332942318685, "lm_q1q2_score": 0.0032562773969881578}}
{"text": "#pragma once\n\n#if SEAL_COMPILER == SEAL_COMPILER_MSVC\n\n// Require Visual Studio 2015 or newer and C++14 support\n#if (_MSC_VER < 1900) || (_MSVC_LANG < 201402L)\n#error \"Microsoft Visual Studio 2015 (14.0) or newer required; C++14 support required\"\n#endif\n\n// Can work with Visual Studio 2015 (C++14) with some limitations\n#if _MSVC_LANG == 1900\n#undef SEAL_USE_SHARED_MUTEX_FOR_RW_LOCK\n#endif\n\n// Deal with Debug mode in Visual Studio\n#ifdef _DEBUG\n#define SEAL_DEBUG\n#endif\n\n// Cannot use std::shared_mutex when compiling with /clr\n#ifdef _M_CEE\n#undef SEAL_USE_SHARED_MUTEX_FOR_RW_LOCK\n#endif\n\n// Try to check presence of additional headers using __has_include\n#ifdef __has_include\n\n// Check for MSGSL\n#if __has_include(<gsl/gsl>)\n#include <gsl/gsl>\n#define SEAL_USE_MSGSL\n#else\n#undef SEAL_USE_MSGSL\n#endif //__has_include(<gsl/gsl>)\n\n#endif\n\n// X64\n#ifdef _M_X64\n\n// Use compiler intrinsics for better performance\n#define SEAL_USE_INTRIN\n\n#ifdef SEAL_USE_INTRIN\n#include <intrin.h>\n\n#pragma intrinsic(_addcarry_u64)\n#define SEAL_ADD_CARRY_UINT64(operand1, operand2, carry, result) _addcarry_u64(     \\\n    carry,                                                                          \\\n    static_cast<unsigned long long>(operand1),                                      \\\n    static_cast<unsigned long long>(operand2),                                      \\\n    reinterpret_cast<unsigned long long*>(result))\n\n#pragma intrinsic(_subborrow_u64)\n#define SEAL_SUB_BORROW_UINT64(operand1, operand2, borrow, result) _subborrow_u64(  \\\n    borrow,                                                                         \\\n    static_cast<unsigned long long>(operand1),                                      \\\n    static_cast<unsigned long long>(operand2),                                      \\\n    reinterpret_cast<unsigned long long*>(result))\n\n#pragma intrinsic(_BitScanReverse64)\n#define SEAL_MSB_INDEX_UINT64(result, value) _BitScanReverse64(result, value)\n\n#pragma intrinsic(_umul128)\n#define SEAL_MULTIPLY_UINT64(operand1, operand2, result128) {                       \\\n    result128[0] = _umul128(                                                        \\\n        static_cast<unsigned long long>(operand1),                                  \\\n        static_cast<unsigned long long>(operand2),                                  \\\n        reinterpret_cast<unsigned long long*>(result128 + 1));                      \\\n}\n#define SEAL_MULTIPLY_UINT64_HW64(operand1, operand2, hw64) {                       \\\n    _umul128(                                                                       \\\n        static_cast<unsigned long long>(operand1),                                  \\\n        static_cast<unsigned long long>(operand2),                                  \\\n        reinterpret_cast<unsigned long long*>(hw64));                               \\\n}\n\n#endif\n#else \n#undef SEAL_USE_INTRIN\n\n#endif //_M_X64\n\n#endif", "meta": {"hexsha": "20e06aeec9e6ba4491d1bbe975badcbea59c0499", "size": 2915, "ext": "h", "lang": "C", "max_stars_repo_path": "SEAL/seal2/msvc.h", "max_stars_repo_name": "MarbleHE/SEAL4Pyfhel", "max_stars_repo_head_hexsha": "dca915e0964f6ae1b891876e64101f09c1ecfe08", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-19T17:09:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-27T06:25:36.000Z", "max_issues_repo_path": "SEAL/seal2/msvc.h", "max_issues_repo_name": "MarbleHE/SEAL4Pyfhel", "max_issues_repo_head_hexsha": "dca915e0964f6ae1b891876e64101f09c1ecfe08", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SEAL/seal2/msvc.h", "max_forks_repo_name": "MarbleHE/SEAL4Pyfhel", "max_forks_repo_head_hexsha": "dca915e0964f6ae1b891876e64101f09c1ecfe08", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-05-29T10:15:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-26T02:31:56.000Z", "avg_line_length": 34.7023809524, "max_line_length": 86, "alphanum_fraction": 0.5804459691, "num_tokens": 601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1755380649971796, "lm_q2_score": 0.018546566376890464, "lm_q1q2_score": 0.0032556283741411044}}
{"text": "#pragma once\n\n#include <GLES2/gl2.h>\n#include <GLES2/gl2ext.h>\n#include <GLES3/gl3.h>\n#include <GLES3/gl3ext.h>\n#include <GLES3/gl3platform.h>\n#include <EGL/egl.h>\n#include <EGL/eglext.h>\n#include <gsl/gsl>\n\nnamespace android::OpenGLHelpers\n{\n    constexpr GLint GetTextureUnit(GLenum texture)\n    {\n        return texture - GL_TEXTURE0;\n    }\n\n    GLuint CreateShaderProgram(const char* vertShaderSource, const char* fragShaderSource);\n\n    namespace GLTransactions\n    {\n        inline auto SetCapability(GLenum capability, bool isEnabled)\n        {\n            const auto setCapability{ [capability](bool isEnabled)\n            {\n                if (isEnabled)\n                {\n                    glEnable(capability);\n                }\n                else\n                {\n                    glDisable(capability);\n                }\n            }};\n\n            const auto wasEnabled{ glIsEnabled(capability) };\n            setCapability(isEnabled);\n            return gsl::finally([wasEnabled, setCapability]() { setCapability(wasEnabled); });\n        }\n\n        inline auto BindFrameBuffer(GLuint frameBufferId)\n        {\n            GLint previousFrameBufferId;\n            glGetIntegerv(GL_FRAMEBUFFER_BINDING, &previousFrameBufferId);\n            glBindFramebuffer(GL_FRAMEBUFFER, frameBufferId);\n            return gsl::finally([previousFrameBufferId]() { glBindFramebuffer(GL_FRAMEBUFFER, static_cast<GLuint>(previousFrameBufferId)); });\n        }\n\n        inline auto DepthMask(GLboolean depthMask)\n        {\n            GLboolean previousDepthMask;\n            glGetBooleanv(GL_DEPTH_WRITEMASK, &previousDepthMask);\n            glDepthMask(depthMask);\n            return gsl::finally([previousDepthMask]() { glDepthMask(previousDepthMask); });\n        }\n\n        inline auto BindSampler(GLenum unit, GLuint id)\n        {\n            glActiveTexture(unit);\n            GLint previousId;\n            glGetIntegerv(GL_SAMPLER_BINDING, &previousId);\n            glBindSampler(unit - GL_TEXTURE0, id);\n            return gsl::finally([unit, id{ previousId }]() { glActiveTexture(unit); glBindSampler(unit - GL_TEXTURE0, id); });\n        }\n\n        inline auto MakeCurrent(EGLDisplay display, EGLSurface drawSurface, EGLSurface readSurface, EGLContext context)\n        {\n            EGLDisplay previousDisplay{ eglGetDisplay(EGL_DEFAULT_DISPLAY) };\n            EGLSurface previousDrawSurface{ eglGetCurrentSurface(EGL_DRAW) };\n            EGLSurface previousReadSurface{ eglGetCurrentSurface(EGL_READ) };\n            EGLContext previousContext{ eglGetCurrentContext() };\n            eglMakeCurrent(display, drawSurface, readSurface, context);\n            return gsl::finally([previousDisplay, previousDrawSurface, previousReadSurface, previousContext]() { eglMakeCurrent(previousDisplay, previousDrawSurface, previousReadSurface, previousContext); });\n        }\n    }\n}", "meta": {"hexsha": "743801ce16965de5afd2d3fc1b74ebb83a5d6c48", "size": 2881, "ext": "h", "lang": "C", "max_stars_repo_path": "Dependencies/AndroidExtensions/Include/AndroidExtensions/OpenGLHelpers.h", "max_stars_repo_name": "chiamaka-123/BabylonNative", "max_stars_repo_head_hexsha": "7f1f9fd23bf649c9c8a1260f2b93752145b0c024", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-23T17:39:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-23T17:39:12.000Z", "max_issues_repo_path": "Dependencies/AndroidExtensions/Include/AndroidExtensions/OpenGLHelpers.h", "max_issues_repo_name": "chiamaka-123/BabylonNative", "max_issues_repo_head_hexsha": "7f1f9fd23bf649c9c8a1260f2b93752145b0c024", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Dependencies/AndroidExtensions/Include/AndroidExtensions/OpenGLHelpers.h", "max_forks_repo_name": "chiamaka-123/BabylonNative", "max_forks_repo_head_hexsha": "7f1f9fd23bf649c9c8a1260f2b93752145b0c024", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4155844156, "max_line_length": 208, "alphanum_fraction": 0.636931621, "num_tokens": 597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1311732373477186, "lm_q2_score": 0.024798157402811837, "lm_q1q2_score": 0.003252854586785122}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef json_58ea0e36_7aaa_49a1_b466_3bbbb2483c5b_h\r\n#define json_58ea0e36_7aaa_49a1_b466_3bbbb2483c5b_h\r\n\r\n#include <gslib/std.h>\r\n\r\n__gslib_begin__\r\n\r\nenum json_tag\r\n{\r\n    jst_array,\r\n    jst_table,\r\n    jst_pair,\r\n    jst_value,\r\n};\r\n\r\nclass json_node_value;\r\n\r\nclass __gs_novtable json_node abstract\r\n{\r\npublic:\r\n    virtual ~json_node() {}\r\n    virtual json_tag get_tag() const = 0;\r\n    virtual const string& get_name() const = 0;\r\n    virtual json_node* duplicate() const = 0;   /* delete */\r\n};\r\n\r\nstruct json_node_hash\r\n#if defined(_MSC_VER) && (_MSC_VER < 1914)\r\n    : public std::unary_function<json_node*, size_t>\r\n#endif\r\n{\r\npublic:\r\n    size_t operator()(const json_node* p) const\r\n    {\r\n        assert(p);\r\n        return string_hash(p->get_name());\r\n    }\r\n};\r\n\r\nstruct json_node_equalto\r\n#if defined(_MSC_VER) && (_MSC_VER < 1914)\r\n    : public std::binary_function<json_node*, json_node*, bool>\r\n#endif\r\n{\r\npublic:\r\n    bool operator()(const json_node* p1, const json_node* p2) const\r\n    {\r\n        assert(p1 && p2);\r\n        return p1->get_name() == p2->get_name();\r\n    }\r\n};\r\n\r\ntypedef unordered_set<json_node*, json_node_hash, json_node_equalto> json_node_map;\r\ntypedef vector<json_node*> json_node_list;\r\n\r\nclass json_node_array:\r\n    public json_node\r\n{\r\npublic:\r\n    virtual ~json_node_array();\r\n    virtual json_tag get_tag() const override { return jst_array; }\r\n    virtual const string& get_name() const override { return _name; }\r\n    virtual json_node* duplicate() const override;\r\n\r\nprotected:\r\n    string              _name;\r\n    json_node_list      _array;\r\n\r\npublic:\r\n    void set_name(const gchar* str) { _name.assign(str); }\r\n    void set_name(const gchar* str, int len) { _name.assign(str, len); }\r\n    void set_name(const string& str) { _name = str; }\r\n    bool is_empty() const { return _array.empty(); }\r\n    int get_childs() const { return (int)_array.size(); }\r\n    json_node* at(int i) const { return _array.at(i); }\r\n    int parse(const gchar* src, int len);\r\n    json_node_list& get_container() { return _array; }\r\n};\r\n\r\nclass json_node_table:\r\n    public json_node\r\n{\r\npublic:\r\n    virtual ~json_node_table();\r\n    virtual json_tag get_tag() const override { return jst_table; }\r\n    virtual const string& get_name() const override { return _name; }\r\n    virtual json_node* duplicate() const override;\r\n\r\nprotected:\r\n    string              _name;\r\n    json_node_map       _table;\r\n\r\npublic:\r\n    void set_name(const gchar* str) { _name.assign(str); }\r\n    void set_name(const gchar* str, int len) { _name.assign(str, len); }\r\n    void set_name(const string& str) { _name = str; }\r\n    bool is_empty() const { return _table.empty(); }\r\n    int get_childs() const { return (int)_table.size(); }\r\n    json_node* find(const string& name) const;\r\n    int parse(const gchar* src, int len);\r\n    json_node_map& get_container() { return _table; }\r\n};\r\n\r\nclass json_node_value:\r\n    public json_node\r\n{\r\npublic:\r\n    virtual json_tag get_tag() const override { return jst_value; }\r\n    virtual const string& get_name() const override { return _strval; }\r\n    virtual json_node* duplicate() const override;\r\n\r\nprotected:\r\n    string              _strval;\r\n\r\npublic:\r\n    void set_value_string(const gchar* str) { _strval.assign(str); }\r\n    void set_value_string(const gchar* str, int len) { _strval.assign(str, len); }\r\n    void set_value_string(const string& str) { _strval = str; }\r\n    int parse(const gchar* src, int len);\r\n};\r\n\r\nclass json_node_pair:\r\n    public json_node\r\n{\r\npublic:\r\n    virtual json_tag get_tag() const override { return jst_pair; }\r\n    virtual const string& get_name() const override { return _name; }\r\n    virtual json_node* duplicate() const override;\r\n\r\nprotected:\r\n    string              _name;\r\n    json_node_value     _value;\r\n\r\npublic:\r\n    void set_name(const gchar* str) { _name.assign(str); }\r\n    void set_name(const gchar* str, int len) { _name.assign(str, len); }\r\n    void set_name(const string& str) { _name = str; }\r\n    void set_value(const gchar* str) { _value.set_value_string(str); }\r\n    void set_value(const gchar* str, int len) { _value.set_value_string(str, len); }\r\n    void set_value(const string& str) { _value.set_value_string(str); }\r\n    const json_node_value& get_value() const { return _value; }\r\n    const string& get_value_string() const { return _value.get_name(); }\r\n    int parse(const gchar* src, int len);\r\n};\r\n\r\nclass json_key:\r\n    public json_node_pair\r\n{\r\npublic:\r\n    json_key(const string& name) { _name = name; }\r\n    json_key(const gchar* str) { _name.assign(str); }\r\n    json_key(const gchar* str, int len) { _name.assign(str, len); }\r\n};\r\n\r\nclass json_parser\r\n{\r\npublic:\r\n    json_parser() { _root = nullptr; }\r\n    ~json_parser() { destroy(); }\r\n    bool parse(const gchar* src, int len);\r\n    bool parse(const gchar* filename);\r\n    void destroy();\r\n    json_node* get_root() const { return _root; }\r\n\r\nprotected:\r\n    json_node*          _root;\r\n};\r\n\r\n__gslib_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "a4445799968219ae1a57324b6ef9b680618e4112", "size": 6263, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gslib/json.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/gslib/json.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gslib/json.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 31.472361809, "max_line_length": 85, "alphanum_fraction": 0.6709244771, "num_tokens": 1541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06656918711865298, "lm_q2_score": 0.0488577786221749, "lm_q1q2_score": 0.003252422607301284}}
{"text": "//        Copyright The Authors 2018.\n//    Distributed under the 3-Clause BSD License.\n//    (See accompanying file LICENSE or copy at\n//   https://opensource.org/licenses/BSD-3-Clause)\n\n#pragma once\n\n#include <cstdint>  // for std::uint8_t\n#include <gsl/gsl>  // for gsl::span<std::uint8_t>\n#include <vector>   // for std::vector<std::uint8_t>\n\nnamespace blocxxi {\nnamespace p2p {\nnamespace kademlia {\n\n/// Represents an output buffer to which headers and message bodies can be\n/// serialized. Whatever type is used, it needs to be able to expand as needed.\nusing Buffer = std::vector<std::uint8_t>;\n\n/// Represents a read-only view over the input buffer used to deserialize\n/// headers and message bodies.\nusing BufferReader = gsl::span<std::uint8_t>;\n\n}  // namespace kademlia\n}  // namespace p2p\n}  // namespace blocxxi\n", "meta": {"hexsha": "217e4f6cf6dcb02882a1a3d0eaf9802f5852d858", "size": 825, "ext": "h", "lang": "C", "max_stars_repo_path": "p2p/include/p2p/kademlia/buffer.h", "max_stars_repo_name": "canhld94/blocxxi", "max_stars_repo_head_hexsha": "e0e1e629334a7959c3fb9c38567f9cf28e2cf44a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2018-06-17T22:10:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T07:08:26.000Z", "max_issues_repo_path": "p2p/include/p2p/kademlia/buffer.h", "max_issues_repo_name": "canhld94/blocxxi", "max_issues_repo_head_hexsha": "e0e1e629334a7959c3fb9c38567f9cf28e2cf44a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-06-20T08:39:12.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-03T09:50:56.000Z", "max_forks_repo_path": "p2p/include/p2p/kademlia/buffer.h", "max_forks_repo_name": "canhld94/blocxxi", "max_forks_repo_head_hexsha": "e0e1e629334a7959c3fb9c38567f9cf28e2cf44a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-07-13T17:55:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-27T19:37:05.000Z", "avg_line_length": 30.5555555556, "max_line_length": 79, "alphanum_fraction": 0.7115151515, "num_tokens": 211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11757213354550883, "lm_q2_score": 0.02758528272643216, "lm_q1q2_score": 0.0032432605446026997}}
{"text": "#ifndef PyGSL_RNG_H\n#define PyGSL_RNG_H 1\n\n#include <pygsl/intern.h>\n#include <gsl/gsl_rng.h>\ntypedef struct {\n  PyObject_HEAD\n  gsl_rng * rng;\n} PyGSL_rng;\n\n\n\n/* \n * Get a gsl_rng object from a PyGSL rng wrapper.\n */\nPyGSL_API_EXTERN gsl_rng *\nPyGSL_gsl_rng_from_pyobject(PyObject * object);\n#ifndef _PyGSL_API_MODULE\n#define PyGSL_gsl_rng_from_pyobject \\\n(*(gsl_rng *  (*) (PyObject *)) PyGSL_API[PyGSL_gsl_rng_from_pyobject_NUM])\n#endif /* _PyGSL_API_MODULE */\n\n#define PyGSL_RNG_Check(op) \\\n   ((op)->ob_type == (PyTypeObject *)PyGSL_API[PyGSL_RNG_ObjectType_NUM])\n\n#define import_pygsl_rng() \\\n{ \\\n   PyObject *pygsl = NULL, *c_api = NULL, *md = NULL; \\\n   if ( \\\n      (pygsl = PyImport_ImportModule(\"pygsl.rng\"))         != NULL && \\\n      (md = PyModule_GetDict(pygsl))                       != NULL && \\\n      (c_api = PyDict_GetItemString(md, \"_PYGSL_RNG_API\")) != NULL && \\\n      (PyCObject_Check(c_api))                                        \\\n     ) { \\\n\t PyGSL_API = (void **)PyCObject_AsVoidPtr(c_api); \\\n   } else { \\\n        PyGSL_API = NULL; \\\n   } \\\n   /* fprintf(stderr, \"PyGSL_API points to %p\\n\", (void *) PyGSL_API); */ \\\n}\n#endif  /* PyGSL_RNG_H */\n\n\n\n\n\n", "meta": {"hexsha": "d2b2f62c815cf54982eb71a55d8c2cb2b4ea901d", "size": 1179, "ext": "h", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/Include/pygsl/rng.h", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/Include/pygsl/rng.h", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/Include/pygsl/rng.h", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 25.085106383, "max_line_length": 75, "alphanum_fraction": 0.6183206107, "num_tokens": 371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1225232189263307, "lm_q2_score": 0.026355354949182036, "lm_q1q2_score": 0.003229142924319784}}
{"text": "#pragma once\n#include <gsl/gsl>\n#include <typeindex>\n#include \"halley/utils/utils.h\"\n#include \"halley/data_structures/maybe.h\"\n#include \"halley/bytes/byte_serializer.h\"\n#include <cstdint>\n\nnamespace Halley\n{\n\tclass IMessageStream;\n\tclass MessageQueue;\n\tclass MessageQueueUDP;\n\tclass MessageQueueTCP;\n\t\n\tclass NetworkMessage\n\t{\n\tpublic:\n\t\tvirtual ~NetworkMessage() = default;\n\n\t\tsize_t getSerializedSize() const\n\t\t{\n\t\t\tif (!serialized) {\n\t\t\t\tserialized = Serializer::toBytes(*this, getSerializerOptions());\n\t\t\t}\n\t\t\treturn serialized->size();\n\t\t}\n\n\t\tvoid serializeTo(gsl::span<gsl::byte> dst) const\n\t\t{\n\t\t\tif (!serialized) {\n\t\t\t\tserialized = Serializer::toBytes(*this, getSerializerOptions());\n\t\t\t}\n\t\t\tmemcpy(dst.data(), serialized->data(), serialized->size());\n\t\t}\n\n\t\tBytes getBytes() const\n\t\t{\n\t\t\tif (!serialized) {\n\t\t\t\tserialized = Serializer::toBytes(*this, getSerializerOptions());\n\t\t\t}\n\t\t\treturn *serialized;\n\t\t}\n\n\t\tvirtual void serialize(Serializer& s) const = 0;\n\t\tvirtual void deserialize(Deserializer& s) = 0;\n\n\t\tvoid setSeq(uint16_t seq) { this->seq = seq; }\n\t\tuint16_t getSeq() const { return seq; }\n\t\tvoid setChannel(uint8_t channel) { this->channel = channel; }\n\t\tuint8_t getChannel() const { return channel; }\n\n\t\tstatic SerializerOptions getSerializerOptions()\n\t\t{\n\t\t\treturn SerializerOptions(SerializerOptions::maxVersion);\n\t\t}\n\n\tprivate:\n\t\tuint16_t seq = 0;\n\t\tuint8_t channel = -1;\n\n\t\tmutable std::optional<Bytes> serialized;\n\t};\n\n\tclass NetworkMessageFactoryBase\n\t{\n\tpublic:\n\t\tvirtual ~NetworkMessageFactoryBase() {}\n\n\t\tvirtual std::unique_ptr<NetworkMessage> create(gsl::span<const gsl::byte> src) const = 0;\n\t\tvirtual std::type_index getTypeIndex() const = 0;\n\t};\n\n\ttemplate <typename T>\n\tclass NetworkMessageFactory : public NetworkMessageFactoryBase\n\t{\n\tpublic:\n\t\tstd::unique_ptr<NetworkMessage> create(gsl::span<const gsl::byte> src) const override\n\t\t{\n\t\t\tauto result = std::make_unique<T>();\n\t\t\tauto s = Deserializer(src, T::getSerializerOptions());\n\t\t\tresult->deserialize(s);\n\t\t\treturn result;\n\t\t}\n\n\t\tstd::type_index getTypeIndex() const override\n\t\t{\n\t\t\treturn std::type_index(typeid(T));\n\t\t}\n\t};\n\n\tclass NetworkMessageFactories\n\t{\n\tpublic:\n\t\ttemplate <typename T>\n\t\tvoid addFactory()\n\t\t{\n\t\t\taddFactory(std::make_unique<NetworkMessageFactory<T>>());\n\t\t}\n\n\t\tuint16_t getMessageType(NetworkMessage& msg) const;\n\t\tstd::unique_ptr<NetworkMessage> deserializeMessage(gsl::span<const gsl::byte> data, uint16_t msgType, uint16_t seq);\n\n\tprivate:\n\t\tstd::map<std::type_index, uint16_t> typeToMsgIndex;\n\t\tVector<std::unique_ptr<NetworkMessageFactoryBase>> factories;\n\n\t\tvoid addFactory(std::unique_ptr<NetworkMessageFactoryBase> factory);\n\t};\n}\n", "meta": {"hexsha": "113979e5303dee89e46186bad41b1b54dbb805db", "size": 2658, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engine/net/include/halley/net/connection/network_message.h", "max_stars_repo_name": "amrezzd/halley", "max_stars_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/engine/net/include/halley/net/connection/network_message.h", "max_issues_repo_name": "amrezzd/halley", "max_issues_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engine/net/include/halley/net/connection/network_message.h", "max_forks_repo_name": "amrezzd/halley", "max_forks_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9459459459, "max_line_length": 118, "alphanum_fraction": 0.7155756208, "num_tokens": 698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12252319970181706, "lm_q2_score": 0.026355353180697833, "lm_q1q2_score": 0.00322914220097056}}
{"text": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n#pragma once\n\n#include \"arcana/utils/serialization/base_stream.h\"\n#include \"arcana/utils/serialization/serializable.h\"\n#include \"arcana/analysis/determinator.h\"\n#include \"Proxies/Proxy.h\"\n#include \"arcana/analysis/binary_iterator.h\"\n#include \"Mapping/MapPointKeyframeAssociations.h\"\n#include \"BundleAdjustment/BundleAdjust.h\"\n#include \"Proxies/KeyframeFields.h\"\n\n#include \"Tracking/PoseEstimator.h\"\n#include \"Utils/cv.h\"\n\n#include <type_traits>\n#include <memory>\n#include <gsl/gsl>\n\nnamespace mage\n{\n    class MapPoint;\n    class Keyframe;\n\n    template<typename IterT>\n    inline void binary_iterate(const Id<MapPoint>& id, mira::binary_iterator<IterT>& iterator)\n    {\n        iterator.iterate(reinterpret_cast<const IdT&>(id));\n    }\n\n    template<typename IterT>\n    inline void binary_iterate(const Id<Keyframe>& id, mira::binary_iterator<IterT>& iterator)\n    {\n        iterator.iterate(reinterpret_cast<const IdT&>(id));\n    }\n\n    /*\n    Serialize only the proxy properties that support serialization\n    */\n    template<typename IterT, typename T, typename ...Props>\n    inline void binary_iterate(const Proxy<T, Props...>& proxy, mira::binary_iterator<IterT>& iterator)\n    {\n        iterator.iterate(static_cast<const proxy::Id<T>&>(proxy));\n\n        int unused[] = {\n            0, // in case it's just a Proxy<MapPoint>, we can't declare an empty c-style array\n            (iterator.iterate(static_cast<const Props&>(proxy)) , 0)...\n        };\n        (void)unused;\n    };\n\n    template<typename IterT>\n    inline void binary_iterate(const KeyframeReprojection& data, mira::binary_iterator<IterT>& itr)\n    {\n        itr.iterate(reinterpret_cast<const IdT&>(data.KeyframeId));\n        itr.iterate(data.Pose);\n        for (auto& point : data.Points)\n        {\n            itr.iterate(point.As<Proxy<MapPoint, proxy::Position, proxy::UpdateStatistics, proxy::ViewingData>>());\n            itr.iterate(*point.GetRepresentativeDescriptor());\n        }\n    }\n\n    template<typename IterT>\n    inline void binary_iterate(const MapPointAssociation& data, mira::binary_iterator<IterT>& itr)\n    {\n        itr.iterate(&data, sizeof(MapPointAssociation));\n    }\n\n    template<typename IterT>\n    inline void binary_iterate(const HistoricalFrame& data, mira::binary_iterator<IterT>& itr)\n    {\n        itr.iterate(data.UpdatedPose);\n        itr.iterate(data.Keyframe);\n    }\n\n\n    template<typename IterT>\n    inline void binary_iterate(const AdjustableData& data, mira::binary_iterator<IterT>& itr)\n    {\n        itr.iterate(data.Keyframes);\n        itr.iterate(data.ExternallyTetheredKeyframes);\n        itr.iterate(data.MapPointAssociations);\n        itr.iterate(data.MapPoints);\n    }\n\n    template<typename IterT>\n    inline void binary_iterate(const typename MapPointAssociations<MapPointTrackingProxy>::Association& assoc, mira::binary_iterator<IterT>& itr)\n    {\n        itr.iterate_all(assoc.MapPoint, assoc.Index);\n    }\n\n    template<typename IterT>\n    inline void binary_iterate(const MapPointKeyframeAssociations& data, mira::binary_iterator<IterT>& itr)\n    {\n        itr.iterate(data.MapPoint);\n        itr.iterate(data.Keyframes);\n    }\n\n    template<typename IterT>\n    inline void binary_iterate(const KeyframeAssociation& data, mira::binary_iterator<IterT>& itr)\n    {\n        itr.iterate_all(data.KeyframeId, data.KeypointDescriptorIndex);\n    }\n\n    template<typename IterT>\n    inline void binary_iterate(const FrameId& data, mira::binary_iterator<IterT>& itr)\n    {\n        itr.iterate(data.CorrelationId);\n        itr.iterate(data.Camera);\n    }\n\n    template<typename IterT>\n    inline void binary_iterate(const AnalyzedImage& data, mira::binary_iterator<IterT>& itr)\n    {\n        itr.iterate(data.GetFrameId());\n        itr.iterate(data.GetTimeStamp().time_since_epoch());\n        itr.iterate(data.GetImageData());\n        itr.iterate(data.GetDistortedCalibration());\n        itr.iterate(data.GetUndistortedCalibration());\n        itr.iterate(data.GetKeyPoints());\n    }\n\n    template<typename IterT, typename T>\n    inline void binary_iterate(const Tether<T>& data, mira::binary_iterator<IterT>& itr)\n    {\n        itr.iterate(data.Type());\n        itr.iterate(data.Weight());\n        itr.iterate(data.OriginId());\n\n        if (data.Type() == TetherType::DISTANCE)\n        {\n            itr.iterate(data.Distance());\n        }\n\n        if(data.Type() == TetherType::SIX_DOF || data.Type() == TetherType::EXTRINSIC)\n        {\n            itr.iterate(data.Position());\n        }\n\n        if (data.Type() == TetherType::THREE_DOF || data.Type() == TetherType::SIX_DOF || data.Type() == TetherType::EXTRINSIC)\n        {\n            itr.iterate(data.Rotation());\n        }\n    }\n\n    namespace proxy\n    {\n        // no-ops that we don't check for determinism\n        inline void binary_iterate(const Image&, mira::binary_iterator<mira::determinator::iterator_callback>&) {}\n        inline void binary_iterate(const Associations<MapPointTrackingProxy>&, mira::binary_iterator<mira::determinator::iterator_callback>&) {}\n\n        inline void binary_iterate(const UnAssociatedMask& data, mira::binary_iterator<mira::determinator::iterator_callback>& itr)\n        {\n            itr.iterate(data.GetUnassociatedKeypointCount());\n            itr.iterate(data.GetUnassociatedKeypointMask());\n        }\n\n        template<typename IterT>\n        inline void binary_iterate(const PoseConstraints& data, mira::binary_iterator<IterT>& itr)\n        {\n            itr.iterate(data.IsImmortal());\n            itr.iterate(data.IsFixed());\n            itr.iterate(data.GetTethers());\n        }\n\n        template<typename IterT>\n        inline void binary_iterate(const Descriptor& data, mira::binary_iterator<IterT>& itr)\n        {\n            // proxy::Descriptor is just a pointer to the descriptor\n            itr.iterate(data.GetRepresentativeDescriptor()->Data(), mage::ORBDescriptor::DESCRIPTOR_SIZE_BYTES);\n        }\n\n        template<typename IterT>\n        inline void binary_iterate(const Associations<mage::MapPointTrackingProxy>& data, mira::binary_iterator<IterT>& itr)\n        {\n            // not the real size as we don't account for the bimap overhead\n            std::vector<mage::MapPointAssociations<mage::MapPointTrackingProxy>::Association> assocs;\n            data.GetAssociations(assocs);\n            itr.iterate(assocs);\n        }\n    }\n}\n\nnamespace cv\n{\n    template<typename IterT>\n    inline void binary_iterate(const cv::KeyPoint& data, mira::binary_iterator<IterT>& itr)\n    {\n        itr.iterate(&data, sizeof(data));\n    }\n\n    template<typename IterT>\n    inline void binary_iterate(const cv::Vec3f& data, mira::binary_iterator<IterT>& itr)\n    {\n        itr.iterate(&data, sizeof(data));\n    }\n}\n\n\nnamespace Eigen\n{\n    template<typename IterT, typename T>\n    inline void binary_iterate(const Quaternion<T>& data, mira::binary_iterator<IterT>& itr)\n    {\n        itr.iterate(data.coeffs().data(), data.coeffs().size()*sizeof(T));\n    }\n}\n", "meta": {"hexsha": "50b4e1ccb984455858a0860faf33b7c5fb941c4e", "size": 7059, "ext": "h", "lang": "C", "max_stars_repo_path": "Core/MAGESLAM/Source/Analysis/binary_iterators.h", "max_stars_repo_name": "syntheticmagus/mageslam", "max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z", "max_issues_repo_path": "Core/MAGESLAM/Source/Analysis/binary_iterators.h", "max_issues_repo_name": "syntheticmagus/mageslam", "max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z", "max_forks_repo_path": "Core/MAGESLAM/Source/Analysis/binary_iterators.h", "max_forks_repo_name": "syntheticmagus/mageslam", "max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z", "avg_line_length": 33.4549763033, "max_line_length": 145, "alphanum_fraction": 0.6646833829, "num_tokens": 1653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21206880435710534, "lm_q2_score": 0.015189050814054013, "lm_q1q2_score": 0.003221123845455752}}
{"text": "/*\nCopyright (c) 2003-2008 Rudi Cilibrasi, Rulers of the RHouse\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n1. Redistributions of source code must retain the above copyright\n   notice, this list of conditions and the following disclaimer.\n2. Redistributions in binary form must reproduce the above copyright\n   notice, this list of conditions and the following disclaimer in the\n   documentation and/or other materials provided with the distribution.\n3. Neither the name of the University nor the names of its contributors\n   may be used to endorse or promote products derived from this software\n   without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE RULERS AND CONTRIBUTORS ``AS IS'' AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED.  IN NO EVENT SHALL THE RULERS OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\nOR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\nHOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\nLIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\nOUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGE.\n*/\n#include <stdio.h>\n#include <string.h>\n#if OPENMP_ENABLED\n#include <omp.h>\n#endif\n#include <assert.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <stdlib.h>\n#include <glib.h>\n#include <glib/gstdio.h>\n//#include <gsl/gsl_cblas.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_linalg.h>\n#include <libintl.h>\n#include <unistd.h>\n\n#include \"complearn/util.h\"\n\n#define _(O) gettext(O)\n\nvoid complearn_mrbreaker(void)\n{\n  printf(\"break!\\n\");\n}\n\nint complearn_make_directory_if_necessary(const char *name)\n{\n  return g_mkdir_with_parents(name, 0700);\n}\n\nchar *complearn_get_hostname()\n{\n  static char *answer;\n  if (answer == NULL) {\n    static char buf[1024];\n#ifdef __MINGW32__\n\tstrcpy(buf, \"localhost\");\n#else\n    gethostname(buf, sizeof(buf));\n#endif\n    buf[sizeof(buf)-1] = '\\0';\n    answer = buf;\n  }\n  return g_strdup(answer);\n}\n\nint complearn_get_pid(void)\n{\n  return getpid();\n}\n\nGSList *complearn_read_directory_of_files(const char *dirname)\n{\n  GError *err = NULL;\n  GSList *result = NULL;\n  GDir *d = g_dir_open(dirname, 0, &err);\n  if (err)\n    g_error(_(\"Cannot open directory %s\"), dirname);\n  const char *n;\n  while ( (n = g_dir_read_name(d)) ) {\n    char *cur = g_build_filename(dirname, n, NULL);\n    if (g_file_test(cur, G_FILE_TEST_IS_REGULAR)) {\n      result = g_slist_append(result, complearn_new_arg(complearn_read_whole_file(cur),cur));\n    }\n    g_free(cur);\n  }\n  g_dir_close(d);\n  return result;\n}\n\nstatic GSList *complearn_read_list_of_files_or_strings(const char *filename, int isfiles)\n{\n  GIOChannel *in;\n  GError *err = NULL;\n  GSList *result = NULL;\n  in = g_io_channel_new_file(filename, \"r\", &err);\n  if (err)\n    g_error(_(\"Cannot open file %s\"), filename);\n  for (;;) {\n    GIOStatus s;\n    gsize tpos;\n    err = NULL;\n    GString *block = g_string_new(\"\");\n    s = g_io_channel_read_line_string(in, block, &tpos, &err);\n    if (s == G_IO_STATUS_EOF)\n      break;\n    if (err != NULL)\n      g_error(_(\"Cannot read line from file %s: %s\"), filename, err->message);\n    g_string_truncate(block, tpos);\n    GString *tokeep;\n    tokeep = (isfiles != 0) ? complearn_read_whole_file(block->str) : g_string_new_len(block->str, block->len);\n    result = g_slist_append(result, complearn_new_arg(tokeep, block->str));\n  }\n  g_io_channel_close(in);\n  return result;\n}\n\nGSList *complearn_read_list_of_files(const char *filename)\n{\n  return complearn_read_list_of_files_or_strings(filename, 1);\n}\n\nGSList *complearn_read_list_of_strings(const char *filename)\n{\n  return complearn_read_list_of_files_or_strings(filename, 0);\n}\n\nGString *complearn_read_whole_file_ptr(FILE *fp)\n{\n  GString *result = g_string_new(\"\");\n  char buf[512];\n  int rl;\n  while ( (rl = fread(buf, 1, 512, fp)) == 512)\n    g_string_append_len(result, buf, rl);\n  if (rl > 0)\n    g_string_append_len(result, buf, rl);\n  return result;\n}\n\nchar *complearn_chdir(const char *newdir)\n{\n  char *retval = g_get_current_dir();\n  int rv;\n  rv = g_chdir(newdir);\n  if (rv != 0) {\n    g_error(_(\"Cannot change directory to %s\"), newdir);\n  }\n  return retval;\n}\n\nint complearn_remove_directory_recursively(const char *dirname, int f_err_out)\n{\n  GError *err = NULL;\n  int result = 0;\n  GDir *d = g_dir_open(dirname, 0, &err);\n  if ( (err) ) {\n    if (f_err_out)\n      g_error(_(\"Cannot open directory %s. Error: %s\"), dirname, err->message);\n    else\n      return 1;\n  }\n  const char *n;\n  while ( (n = g_dir_read_name(d)) ) {\n    char *cur = g_build_filename(dirname, n, NULL);\n    if (g_file_test(cur, G_FILE_TEST_IS_REGULAR))\n      g_unlink(cur);\n    g_free(cur);\n  }\n  g_dir_close(d);\n  result = g_rmdir(dirname);\n  return result;\n}\n\nint complearn_write_file(const char *fname, const GString *f)\n{\n  g_assert(fname != NULL && strlen(fname) > 0);\n  FILE *fp = fopen(fname, \"wb\");\n  if (fp == NULL) {\n    g_error(_(\"Cannot open file %s for writing.\"), fname);\n  }\n  fwrite(f->str, 1, f->len, fp);\n  fclose(fp);\n  return 0;\n}\n\nGString *complearn_read_whole_file(const char *fname)\n{\n  FILE *fp = fopen(fname, \"rb\");\n  if (fp == NULL)\n    g_error(_(\"Cannot open file %s for reading\"), fname);\n  fseek(fp, 0, SEEK_END);\n  int sz = ftell(fp);\n  fseek(fp, 0, SEEK_SET);\n  char *b = calloc(sz, 1);\n  GString *result;\n  fread(b, 1, sz, fp);\n  fclose(fp);\n  result = g_string_new_len(b, sz);\n  g_free(b);\n  return result;\n}\n\nchar *complearn_make_temp_dir(void)\n{\n  char *result = complearn_make_temp_dir_name();\n#ifdef __MINGW32__\n  mkdir(result);\n#else\n  mkdir(result, 0700);\n#endif\n  return result;\n}\n\n/* different each time */\nchar *complearn_make_temp_file_name(void)\n{\n  char *tnam, *result;\n  static int i = 0;\n  char pidbuf[32];\n  sprintf(pidbuf, \"%d-%d\", ++i, getpid());\n  tnam = getenv(\"TMPDIR\");\n  if (tnam == NULL)\n    tnam = \"/tmp\";\n  result = g_strconcat(tnam, \"/clfile\", pidbuf, NULL);\n  return result;\n}\n\nchar *complearn_make_temp_dir_name(void)\n{\n  int tid = 0;\n#if OPENMP_ENABLED\n    if (!g_thread_supported ()) g_thread_init (NULL);\n    tid = omp_get_thread_num();\n#endif\n\n  char *result = NULL, *tnam;\n  int incr = 0;\n  char pidbuf[64];\n  for (;;) {\n    sprintf(pidbuf, \"%dx%dx%d\", getpid(),incr,tid);\n    tnam = getenv(\"TMPDIR\");\n    if (tnam == NULL)\n      tnam = \"/tmp\";\n    result = tnam;\n    result = g_strconcat(tnam, \"/complearn-\", pidbuf, NULL);\n    if (!g_file_test(result, G_FILE_TEST_EXISTS) && !g_file_test(result, G_FILE_TEST_IS_DIR))\n      break;\n    incr += 1;\n  }\n  return result;\n}\n\nchar ** complearn_dupe_strings(const char * const * str)\n{\n  int size = complearn_count_strings(str);\n  char **result;\n  int i;\n  result = calloc(size+1, sizeof(gpointer));\n  for (i = 0; i < size; i += 1)\n    result[i] = g_strdup(str[i]);\n  return result;\n}\n\nint complearn_count_strings(const char * const * str)\n{\n  int acc = 0;\n  const char * const *cur = str;\n  while (cur && *cur) {\n    acc += 1;\n    cur += 1;\n  }\n  return acc;\n}\n\nCLArgumentEntry *complearn_new_arg(GString *block, const char *label) {\n  CLArgumentEntry *cl = calloc(1, sizeof(*cl));\n  cl->block = block;\n  cl->label = g_strdup(label);\n  return cl;\n}\n\n/* This function makes the off-diagonal elements symmetric by averaging.  */\ngsl_matrix *complearn_average_matrix(gsl_matrix *a)\n{\n  int i,j;\n  gsl_matrix *res;\n  res = gsl_matrix_alloc(a->size1, a->size2);\n\n  for (i = 0;i<a->size1;i+=1)\n    for (j = 0; j <a->size2; j+=1) {\n      double v;\n      if (i == j)\n        gsl_matrix_set(res,i,j,gsl_matrix_get(a,i,j));\n      if (i <= j)\n        continue;\n      v = (gsl_matrix_get(a,i,j) + gsl_matrix_get(a,j,i))/2.0;\n      gsl_matrix_set(res,i,j,v);\n      gsl_matrix_set(res,j,i,v);\n    }\n  return res;\n}\n\ngsl_matrix *complearn_svd_project(gsl_matrix *a)\n{\n  int retval;\n  gsl_matrix *res;\n  gsl_matrix *u, *v;\n  gsl_vector *s;\n  u = gsl_matrix_alloc(a->size1, a->size2);\n  gsl_matrix_memcpy(u, a);\n  v = gsl_matrix_alloc(a->size2, a->size2);\n  s = gsl_vector_alloc(a->size1);\n  retval = gsl_linalg_SV_decomp_jacobi(u, v, s);\n//  g_assert(retval == GSL_OK);\n  res = gsl_matrix_alloc(a->size1, a->size2);\n  gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, a, u, 0.0, res);\n  return res;\n}\n\nstatic gboolean is_last_common_char(char **inp, int which)\n{\n  int i;\n  if (strlen(inp[0]) <= which)\n    return FALSE;\n  for (i = 1; inp[i]; i += 1)\n    if (strlen(inp[i]) <= which || inp[i][strlen(inp[i])-which-1] != inp[0][strlen(inp[0])-which-1])\n      return FALSE;\n  return TRUE;\n}\n\nstatic gboolean is_common_char(char **inp, int which)\n{\n  int i;\n  if (strlen(inp[0]) <= which)\n    return FALSE;\n  for (i = 1; inp[i]; i += 1)\n    if (strlen(inp[i]) <= which || inp[i][which] != inp[0][which])\n      return FALSE;\n  return TRUE;\n}\n\nstatic char **chop_strings(char **inp, int prefixc, int suffixc)\n{\n  int sc = complearn_count_strings((const char * const *) inp);\n  char **result = calloc(sc+1,sizeof(gpointer));\n  int i;\n  for (i = 0; i < sc; i += 1) {\n    char *p = inp[i]+prefixc;\n    char *res;\n    res = g_strdup(p);\n    if (suffixc && strlen(p) > suffixc)\n      res[strlen(res)-suffixc] = '\\0';\n    result[i] = res;\n  }\n  return result;\n}\n\nchar ** complearn_fix_labels(char **inp)\n{\n  int prefixc = 0, suffixc = 0;\n  if (inp[1] != NULL) {\n    while (is_common_char(inp, prefixc))\n      prefixc += 1;\n    while ( is_last_common_char(inp, suffixc))\n      suffixc += 1;\n  }\n  return chop_strings(inp, prefixc, suffixc);\n}\n", "meta": {"hexsha": "9936cd1cbfda3d8dee8a3e00b6a6511d2da4697c", "size": 9792, "ext": "c", "lang": "C", "max_stars_repo_path": "src/util.c", "max_stars_repo_name": "rudi-cilibrasi/classic-complearn", "max_stars_repo_head_hexsha": "c70ac5ad7bcfe3af80a2a8f087ee6f5904820a66", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-03-14T13:52:31.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-08T11:13:03.000Z", "max_issues_repo_path": "src/util.c", "max_issues_repo_name": "rudi-cilibrasi/classic-complearn", "max_issues_repo_head_hexsha": "c70ac5ad7bcfe3af80a2a8f087ee6f5904820a66", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2016-05-10T12:56:52.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-15T18:30:04.000Z", "max_forks_repo_path": "src/util.c", "max_forks_repo_name": "rudi-cilibrasi/classic-complearn", "max_forks_repo_head_hexsha": "c70ac5ad7bcfe3af80a2a8f087ee6f5904820a66", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9047619048, "max_line_length": 111, "alphanum_fraction": 0.6691176471, "num_tokens": 2877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1294027315916391, "lm_q2_score": 0.024798161141525246, "lm_q1q2_score": 0.0032089497901630058}}
{"text": "/**\n* VGMTrans (c) - 2002-2021\n* Licensed under the zlib license\n* See the included LICENSE for more information\n*/\n\n#pragma once\n\n#include <vector>\n#include <fluidsynth.h>\n#include <gsl-lite.hpp>\n\nclass MusicPlayer {\npublic:\n  MusicPlayer();\n  ~MusicPlayer();\n\n  /**\n   * Toggles the status of the player\n   * @returns true if the player is playing\n   */\n  bool toggle();\n  /**\n   * Stops the player (unloads resources)\n   */\n  void stop();\n  /**\n   * Moves the player position\n   * @param position relative to song start\n   */\n  void seek(int position);\n\n  /**\n   * Loads SF2 and MIDI data into the player; resources are copied\n   * @param soundfont_data\n   * @param midi_data\n   * @return true if data was loaded correctly\n   */\n  bool loadDataAndPlay(gsl::span<char> soundfont_data, gsl::span<char> midi_data);\n\n  /**\n   * Checks whether the player is playing\n   * @return true if playing\n   */\n  [[nodiscard]] bool playing() const;\n  /**\n   * The number of MIDI ticks elapsed since the player was started\n   * @return number of ticks relative to song start\n   */\n  [[nodiscard]] int elapsedTicks() const;\n  /**\n   * The total number of MIDI ticks in the song\n   * @return total ticks in the song\n   */\n  [[nodiscard]] int totalTicks() const;\n\n  /**\n   * Gets all the audio driver the player supports\n   * @return the driver list\n   */\n  [[nodiscard]] std::vector<const char *> getAvailableDrivers() const;\n  /**\n   * Changes the current audio driver and restarts playing\n   * @param driver_name\n   * @return true if the driver changed\n   */\n  bool setAudioDriver(const char* driver_name);\n\nprivate:\n  fluid_settings_t *m_settings = nullptr;\n  fluid_synth_t *m_synth = nullptr;\n  fluid_audio_driver_t *m_active_driver = nullptr;\n  fluid_player_t *m_active_player = nullptr;\n\n  void makeSettings();\n  void makeSynth();\n  void makePlayer();\n};\n", "meta": {"hexsha": "280506245c0624c429d9cc85bf806c4279b72249", "size": 1846, "ext": "h", "lang": "C", "max_stars_repo_path": "src/common/MusicPlayer.h", "max_stars_repo_name": "Oipo/vgmtrans", "max_stars_repo_head_hexsha": "b48cb0e54f3a319c53de17fc76224d1a711e35ea", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-12-08T18:04:47.000Z", "max_stars_repo_stars_event_max_datetime": "2015-12-08T18:04:47.000Z", "max_issues_repo_path": "src/common/MusicPlayer.h", "max_issues_repo_name": "RGBA-CRT/vgmtrans", "max_issues_repo_head_hexsha": "c5f424b9bfbc509a5a7dd675d4502ae2fb3e8c41", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/common/MusicPlayer.h", "max_forks_repo_name": "RGBA-CRT/vgmtrans", "max_forks_repo_head_hexsha": "c5f424b9bfbc509a5a7dd675d4502ae2fb3e8c41", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3670886076, "max_line_length": 82, "alphanum_fraction": 0.676056338, "num_tokens": 465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14804719803168945, "lm_q2_score": 0.021615331462730675, "lm_q1q2_score": 0.003200089257583496}}
{"text": "/*\n *  Copyright (C) 2021 FISCO BCOS.\n *  SPDX-License-Identifier: Apache-2.0\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n * @brief scale encoder\n * @file ScaleEncoderStream.cpp\n */\n#pragma once\n#include \"FixedWidthIntegerCodec.h\"\n#include \"libutilities/FixedBytes.h\"\n#include <boost/optional.hpp>\n#include <boost/variant.hpp>\n#include <deque>\n#include <gsl/span>\nnamespace bcos\n{\nnamespace codec\n{\nnamespace scale\n{\nclass ScaleEncoderStream\n{\npublic:\n    // special tag to differentiate encoding streams from others\n    static constexpr auto is_encoder_stream = true;\n\n    // get the encoded data\n    bytes data() const;\n\n    /**\n     * @brief scale-encodes pair of values\n     * @tparam F first value type\n     * @tparam S second value type\n     * @param p pair of values to encode\n     * @return reference to stream\n     */\n    template <class F, class S>\n    ScaleEncoderStream& operator<<(const std::pair<F, S>& p)\n    {\n        return *this << p.first << p.second;\n    }\n\n    /**\n     * @brief scale-encodes tuple\n     * @tparam T enumeration of types\n     * @param v tuple\n     * @return reference to stream\n     */\n    template <class... Ts>\n    ScaleEncoderStream& operator<<(const std::tuple<Ts...>& v)\n    {\n        if constexpr (sizeof...(Ts) > 0)\n        {\n            encodeElementOfTuple<0>(v);\n        }\n        return *this;\n    }\n\n    /**\n     * @brief scale-encodes variant value\n     * @tparam T type list\n     * @param v value to encode\n     * @return reference to stream\n     */\n    template <class... T>\n    ScaleEncoderStream& operator<<(const boost::variant<T...>& v)\n    {\n        tryEncodeAsOneOfVariant<0>(v);\n        return *this;\n    }\n\n    /**\n     * @brief scale-encodes sharead_ptr value\n     * @tparam T type list\n     * @param v value to encode\n     * @return reference to stream\n     */\n    template <class T>\n    ScaleEncoderStream& operator<<(const std::shared_ptr<T>& v)\n    {\n        if (v == nullptr)\n        {\n            BOOST_THROW_EXCEPTION(ScaleEncodeException()\n                                  << errinfo_comment(\"encode exception for DEREF_NULLPOINTER\"));\n        }\n        return *this << *v;\n    }\n\n    /**\n     * @brief scale-encodes unique_ptr value\n     * @tparam T type list\n     * @param v value to encode\n     * @return reference to stream\n     */\n    template <class T>\n    ScaleEncoderStream& operator<<(const std::unique_ptr<T>& v)\n    {\n        if (v == nullptr)\n        {\n            BOOST_THROW_EXCEPTION(ScaleEncodeException()\n                                  << errinfo_comment(\"encode exception for DEREF_NULLPOINTER\"));\n        }\n        return *this << *v;\n    }\n\n    template <unsigned N>\n    ScaleEncoderStream& operator<<(const FixedBytes<N>& fixedData)\n    {\n        return encodeCollection((size_t)FixedBytes<N>::size, fixedData.begin(), fixedData.end());\n    }\n\n    /**\n     * @brief scale-encodes collection of same time items\n     * @tparam T type of item\n     * @param c collection to encode\n     * @return reference to stream\n     */\n    template <class T>\n    ScaleEncoderStream& operator<<(const std::vector<T>& c)\n    {\n        return encodeCollection(c.size(), c.begin(), c.end());\n    }\n\n    /**\n     * @brief scale-encodes collection of same time items\n     * @tparam T type of item\n     * @param c collection to encode\n     * @return reference to stream\n     */\n    template <class T>\n    ScaleEncoderStream& operator<<(const std::list<T>& c)\n    {\n        return encodeCollection(c.size(), c.begin(), c.end());\n    }\n\n    /**\n     * @brief scale-encodes optional value\n     * @tparam T value type\n     * @param v value to encode\n     * @return reference to stream\n     */\n    template <class T>\n    ScaleEncoderStream& operator<<(const boost::optional<T>& v)\n    {\n        // optional bool is a special case of optional values\n        // it should be encoded using one byte instead of two\n        // as described in specification\n        if constexpr (std::is_same<T, bool>::value)\n        {\n            return encodeOptionalBool(v);\n        }\n        if (!v.has_value())\n        {\n            return putByte(0u);\n        }\n        return putByte(1u) << *v;\n    }\n\n    /**\n     * @brief appends sequence of bytes\n     * @param v bytes sequence\n     * @return reference to stream\n     */\n    template <class T>\n    ScaleEncoderStream& operator<<(const gsl::span<T>& v)\n    {\n        return encodeCollection(v.size(), v.begin(), v.end());\n    }\n\n    /**\n     * @brief scale-encodes array of items\n     * @tparam T item type\n     * @tparam size of the array\n     * @param a reference to the array\n     * @return reference to stream\n     */\n    template <typename T, size_t size>\n    ScaleEncoderStream& operator<<(const std::array<T, size>& a)\n    {\n        for (const auto& e : a)\n        {\n            *this << e;\n        }\n        return *this;\n    }\n\n    /**\n     * @brief scale-encodes std::reference_wrapper of a type\n     * @tparam T underlying type\n     * @param v value to encode\n     * @return reference to stream;\n     */\n    template <class T>\n    ScaleEncoderStream& operator<<(const std::reference_wrapper<T>& v)\n    {\n        return *this << static_cast<const T&>(v);\n    }\n\n    /**\n     * @brief scale-encodes a string view\n     * @param sv string_view item\n     * @return reference to stream\n     */\n    ScaleEncoderStream& operator<<(std::string_view sv)\n    {\n        return encodeCollection(sv.size(), sv.begin(), sv.end());\n    }\n\n    /**\n     * @brief scale-encodes any integral type including bool\n     * @tparam T integral type\n     * @param v value of integral type\n     * @return reference to stream\n     */\n    template <typename T, typename I = std::decay_t<T>,\n        typename = std::enable_if_t<std::is_integral<I>::value>>\n    ScaleEncoderStream& operator<<(T&& v)\n    {\n        // encode bool\n        if constexpr (std::is_same<I, bool>::value)\n        {\n            uint8_t byte = (v ? 1u : 0u);\n            return putByte(byte);\n        }\n        // put byte\n        if constexpr (sizeof(T) == 1u)\n        {\n            // to avoid infinite recursion\n            return putByte(static_cast<uint8_t>(v));\n        }\n        // encode any other integer\n        encodeInteger<I>(v, *this);\n        return *this;\n    }\n\n    /**\n     * @brief scale-encodes CompactInteger value as compact integer\n     * @param v value to encode\n     * @return reference to stream\n     */\n    ScaleEncoderStream& operator<<(const CompactInteger& v);\n\nprotected:\n    template <size_t I, class... Ts>\n    void encodeElementOfTuple(const std::tuple<Ts...>& v)\n    {\n        *this << std::get<I>(v);\n        if constexpr (sizeof...(Ts) > I + 1)\n        {\n            encodeElementOfTuple<I + 1>(v);\n        }\n    }\n\n    template <uint8_t I, class... Ts>\n    void tryEncodeAsOneOfVariant(const boost::variant<Ts...>& v)\n    {\n        using T = std::tuple_element_t<I, std::tuple<Ts...>>;\n        if (v.type() == typeid(T))\n        {\n            *this << I << boost::get<T>(v);\n            return;\n        }\n        if constexpr (sizeof...(Ts) > I + 1)\n        {\n            tryEncodeAsOneOfVariant<I + 1>(v);\n        }\n    }\n\n    /**\n     * @brief scale-encodes any collection\n     * @tparam It iterator over collection of bytes\n     * @param size size of the collection\n     * @param begin iterator pointing to the begin of collection\n     * @param end iterator pointing to the end of collection\n     * @return reference to stream\n     */\n    template <class It>\n    ScaleEncoderStream& encodeCollection(const CompactInteger& size, It&& begin, It&& end)\n    {\n        *this << size;\n        for (auto&& it = begin; it != end; ++it)\n        {\n            *this << *it;\n        }\n        return *this;\n    }\n    /**\n     * @brief puts a byte to buffer\n     * @param v byte value\n     * @return reference to stream\n     */\n    ScaleEncoderStream& putByte(uint8_t v)\n    {\n        m_stream.emplace_back(v);\n        return *this;\n    }\n\nprivate:\n    ScaleEncoderStream& encodeOptionalBool(const boost::optional<bool>& v);\n    // std::deque<uint8_t> m_stream;\n    std::deque<uint8_t> m_stream;\n};\n}  // namespace scale\n}  // namespace codec\n}  // namespace bcos", "meta": {"hexsha": "cd92194f6a60b40e39eaa6a0ca5742eea6cc18c6", "size": 8668, "ext": "h", "lang": "C", "max_stars_repo_path": "libcodec/scale/ScaleEncoderStream.h", "max_stars_repo_name": "ywy2090/bcos-framework", "max_stars_repo_head_hexsha": "2e71899b37b86d66d29d21e34427505c4e5cf47c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libcodec/scale/ScaleEncoderStream.h", "max_issues_repo_name": "ywy2090/bcos-framework", "max_issues_repo_head_hexsha": "2e71899b37b86d66d29d21e34427505c4e5cf47c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libcodec/scale/ScaleEncoderStream.h", "max_forks_repo_name": "ywy2090/bcos-framework", "max_forks_repo_head_hexsha": "2e71899b37b86d66d29d21e34427505c4e5cf47c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4303797468, "max_line_length": 97, "alphanum_fraction": 0.5831795108, "num_tokens": 2143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09807932610676663, "lm_q2_score": 0.032589746880119314, "lm_q1q2_score": 0.0031963804119922025}}
{"text": "#pragma once\n#include \"nkg_point.h\"\n#include \"nkg_rect.h\"\n#include \"utility/types.h\"\n#include <stb_image.h>\n#include <gsl/gsl>\n#include <memory>\n#include <vector>\n#include <stdlib.h>\n\nnamespace cws80 {\n\nclass im_image {\npublic:\n    im_image();\n    ~im_image();\n\n    void load(const char *filename, uint desired_channels);\n    void load_from_memory(const u8 *buffer, uint length, uint desired_channels);\n    void load_from_memory(gsl::span<const u8> memory, uint desired_channels)\n    {\n        load_from_memory(memory.data(), memory.size(), desired_channels);\n    }\n\n    const u8 *pixel(uint x, uint y) const;\n    u8 alpha(uint x, uint y) const;\n\n    bool is_transparent_column(uint x) const;\n    bool is_transparent_row(uint y) const;\n\n    im_image cut(const im_recti &r) const;\n    std::vector<im_image> hsplit() const;\n    std::vector<im_image> vsplit() const;\n\n    im_recti rect() const;\n    im_recti crop_alpha_border() const;\n\n    const u8 *data() const { return data_.get(); }\n    uint width() const { return w_; }\n    uint height() const { return h_; }\n    uint channels() const { return c_; }\n\n    im_image(im_image &&other) = default;\n    im_image &operator=(im_image &&other) = default;\n\nprivate:\n    uint w_{}, h_{}, n_{}, c_{};\n    std::unique_ptr<u8[], void (*)(void *)> data_{nullptr, &stbi_image_free};\n\npublic:\n    class exception : public std::runtime_error {\n    public:\n        using std::runtime_error::runtime_error;\n    };\n};\n\n}  // namespace cws80\n", "meta": {"hexsha": "9b3310e3c5ea72a930f96127abbd9d63b3565759", "size": 1472, "ext": "h", "lang": "C", "max_stars_repo_path": "sources/ui/detail/nki_image.h", "max_stars_repo_name": "jpcima/cws80", "max_stars_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-05-20T19:27:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-03T04:21:53.000Z", "max_issues_repo_path": "sources/ui/detail/nki_image.h", "max_issues_repo_name": "jpcima/cws80", "max_issues_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-05-21T12:56:22.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-23T21:33:33.000Z", "max_forks_repo_path": "sources/ui/detail/nki_image.h", "max_forks_repo_name": "jpcima/cws80", "max_forks_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3793103448, "max_line_length": 80, "alphanum_fraction": 0.6657608696, "num_tokens": 386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16451647108926923, "lm_q2_score": 0.019419348288855397, "lm_q1q2_score": 0.003194802651335929}}
{"text": "//        Copyright The Authors 2018.\n//    Distributed under the 3-Clause BSD License.\n//    (See accompanying file LICENSE or copy at\n//   https://opensource.org/licenses/BSD-3-Clause)\n\n#pragma once\n\n#include <cstdint>   // for uint8_t\n#include <gsl/gsl>  // for gsl::span\n#include <string>    // for std::string\n\nnamespace blocxxi {\nnamespace codec {\nnamespace hex {\n\nstd::string Encode(gsl::span<const uint8_t> src, bool reverse = false,\n                   bool lower_case = false);\n\nvoid Decode(gsl::span<const char> src, gsl::span<uint8_t> dest,\n            bool reverse = false);\n\n}  // namespace hex\n}  // namespace codec\n}  // namespace blocxxi\n", "meta": {"hexsha": "5d53872b0f1059b315917894b50c58ff3ec860c4", "size": 654, "ext": "h", "lang": "C", "max_stars_repo_path": "codec/include/codec/base16.h", "max_stars_repo_name": "canhld94/blocxxi", "max_stars_repo_head_hexsha": "e0e1e629334a7959c3fb9c38567f9cf28e2cf44a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2018-06-17T22:10:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T07:08:26.000Z", "max_issues_repo_path": "codec/include/codec/base16.h", "max_issues_repo_name": "canhld94/blocxxi", "max_issues_repo_head_hexsha": "e0e1e629334a7959c3fb9c38567f9cf28e2cf44a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-06-20T08:39:12.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-03T09:50:56.000Z", "max_forks_repo_path": "codec/include/codec/base16.h", "max_forks_repo_name": "canhld94/blocxxi", "max_forks_repo_head_hexsha": "e0e1e629334a7959c3fb9c38567f9cf28e2cf44a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-07-13T17:55:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-27T19:37:05.000Z", "avg_line_length": 26.16, "max_line_length": 70, "alphanum_fraction": 0.6574923547, "num_tokens": 167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12252321892633068, "lm_q2_score": 0.02595735898738123, "lm_q1q2_score": 0.0031803791779602677}}
{"text": "#ifndef ARRUS_CORE_DEVICES_US4R_US4ROUTPUTBUFFER_H\n#define ARRUS_CORE_DEVICES_US4R_US4ROUTPUTBUFFER_H\n\n#include <mutex>\n#include <condition_variable>\n#include <gsl/span>\n#include <chrono>\n#include <iostream>\n\n#include \"arrus/core/api/common/types.h\"\n#include \"arrus/core/api/common/exceptions.h\"\n#include \"arrus/common/asserts.h\"\n#include \"arrus/common/format.h\"\n#include \"arrus/core/common/logging.h\"\n#include \"arrus/core/api/framework/DataBuffer.h\"\n\n\nnamespace arrus::devices {\n\nusing ::arrus::framework::Buffer;\nusing ::arrus::framework::BufferElement;\n\nclass Us4ROutputBuffer;\n\n/**\n * Buffer element owns the data arrrays, which then are returned to user.\n */\nclass Us4ROutputBufferElement : public BufferElement {\npublic:\n    using AccumulatorType = uint16;\n\n    using SharedHandle = std::shared_ptr<Us4ROutputBufferElement>;\n\n    Us4ROutputBufferElement(int16 *address, size_t size,\n                            const framework::NdArray::Shape &elementShape,\n                            const framework::NdArray::DataType elementDataType,\n                            AccumulatorType filledAccumulator,\n                            size_t position)\n        : data(address, elementShape, elementDataType,\n               DeviceId(DeviceType::Us4R, 0)), size(size),\n          filledAccumulator(filledAccumulator),\n          position(position)\n          {}\n\n    void release() override {\n        std::unique_lock<std::mutex> guard(mutex);\n        this->accumulator = 0;\n        releaseFunction();\n    }\n\n    int16 *getAddress() {\n        validateState();\n        return data.get<int16>();\n    }\n\n    framework::NdArray &getData() override {\n        validateState();\n        return data;\n    }\n\n    size_t getSize() override {\n        return size;\n    }\n\n    size_t getPosition() override {\n        return position;\n    }\n\n    void registerReleaseFunction(std::function<void()> &func) {\n        releaseFunction = func;\n    }\n\n    [[nodiscard]] bool isElementReady() {\n        std::unique_lock<std::mutex> guard(mutex);\n        return accumulator == filledAccumulator;\n    }\n\n    void signal(Ordinal n) {\n        std::unique_lock<std::mutex> guard(mutex);\n        AccumulatorType us4oemPattern = 1ul << n;\n        if((accumulator & us4oemPattern) != 0) {\n            throw IllegalStateException(\"Detected data overflow, buffer is in invalid state.\");\n        }\n        accumulator |= us4oemPattern;\n    }\n\n    void resetState() {\n        accumulator = 0;\n    }\n\n    void markAsInvalid() {\n        this->isInvalid = true;\n    }\n\n    void validateState() {\n        if(this->isInvalid) {\n            throw ::arrus::IllegalStateException(\n                \"The buffer is in invalid state \"\n                \"(probably some data transfer overflow happened).\");\n        }\n    }\n\nprivate:\n    std::mutex mutex;\n    framework::NdArray data;\n    size_t size;\n    AccumulatorType accumulator;\n    /** A pattern of the filled accumulator, which indicates that the\n     * whole element is ready. */\n    AccumulatorType filledAccumulator;\n    std::function<void()> releaseFunction;\n    bool isInvalid{false};\n    size_t position;\n};\n\n/**\n * Us4R system's output circular FIFO buffer.\n *\n * The buffer has the following relationships:\n * - buffer contains **elements**\n * - the **element** is filled by many us4oems (with given ordinal)\n *\n * A single element is the output of a single data transfer (the result of running a complete sequence once).\n *\n * The state of each buffer element is determined by the field accumulators:\n * - accumulators[element] == 0 means that the buffer element was processed and is ready for new data from the producer.\n * - accumulators[element] > 0 && accumulators[element] != filledAccumulator means that the buffer element is partially\n *   confirmed by some of us4oems\n * - accumulators[element] == filledAccumulator means that the buffer element is ready to be processed by a consumer.\n *\n * The assumption is here that each element of the buffer has the same size (and the same us4oem offsets).\n */\nclass Us4ROutputBuffer : public framework::DataBuffer {\npublic:\n    static constexpr size_t DATA_ALIGNMENT = 4096;\n    using DataType = int16;\n\n    /**\n     * Buffer's constructor.\n     *\n     * @param us4oemOutputSizes number of bytes to allocate for each of the\n     *  us4oem output. That is, the i-th value describes how many bytes will\n     *  be written by i-th us4oem to generate a single buffer element.\n     */\n    Us4ROutputBuffer(const std::vector<size_t> &us4oemOutputSizes,\n                     const framework::NdArray::Shape &elementShape,\n                     const framework::NdArray::DataType elementDataType,\n                     const unsigned nElements)\n        : elementSize(0) {\n        ARRUS_REQUIRES_TRUE(us4oemOutputSizes.size() <= 16,\n                            \"Currently Us4R data buffer supports up to 16 us4oem modules.\");\n\n        size_t nus4oems = us4oemOutputSizes.size();\n        Us4ROutputBufferElement::AccumulatorType filledAccumulator((1ul << nus4oems) - 1);\n        // Calculate us4oem write offsets for each buffer element.\n        size_t us4oemOffset = 0;\n        Ordinal us4oemOrdinal = 0;\n        for(auto s : us4oemOutputSizes) {\n            us4oemOffsets.emplace_back(us4oemOffset);\n            us4oemOffset += s;\n            if(s == 0) {\n                // We should not expect any response from modules, which do not acquire any data.\n                filledAccumulator &= ~(1ul << us4oemOrdinal);\n            }\n            ++us4oemOrdinal;\n        }\n        elementSize = us4oemOffset;\n        // Allocate buffer with an appropriate size.\n        dataBuffer = reinterpret_cast<DataType *>(operator new[](elementSize * nElements,\n                                                                 std::align_val_t(DATA_ALIGNMENT)));\n        getDefaultLogger()->log(LogSeverity::DEBUG,\n                                ::arrus::format(\n                                    \"Allocated {} ({}, {}) bytes of memory, address: {}\",\n                                    elementSize * nElements, elementSize, nElements, (size_t) dataBuffer));\n\n        for(unsigned i = 0; i < nElements; ++i) {\n            auto elementAddress = reinterpret_cast<DataType *>(reinterpret_cast<int8 *>(dataBuffer) + i * elementSize);\n            elements.push_back(std::make_shared<Us4ROutputBufferElement>(elementAddress, elementSize,\n                                                                         elementShape, elementDataType,\n                                                                         filledAccumulator,\n                                                                         i));\n        }\n        this->initialize();\n    }\n\n    ~Us4ROutputBuffer() override {\n        ::operator delete(dataBuffer, std::align_val_t(DATA_ALIGNMENT));\n        getDefaultLogger()->log(LogSeverity::DEBUG, \"Released the output buffer.\");\n    }\n\n    void registerOnNewDataCallback(framework::OnNewDataCallback &callback) override {\n        this->onNewDataCallback = callback;\n    }\n\n    [[nodiscard]] const framework::OnNewDataCallback &getOnNewDataCallback() const {\n        return this->onNewDataCallback;\n    }\n\n    void registerOnOverflowCallback(framework::OnOverflowCallback &callback) override {\n        this->onOverflowCallback = callback;\n    }\n\n    void registerShutdownCallback(framework::OnShutdownCallback &callback) override {\n        this->onShutdownCallback = callback;\n    }\n\n    [[nodiscard]] size_t getNumberOfElements() const override {\n        return elements.size();\n    }\n\n    BufferElement::SharedHandle getElement(size_t i) override {\n        return std::static_pointer_cast<BufferElement>(elements[i]);\n    }\n\n    uint8 *getAddress(uint16 elementNumber, Ordinal us4oem) {\n        return reinterpret_cast<uint8 *>(this->elements[elementNumber]->getAddress()) + us4oemOffsets[us4oem];\n    }\n\n    /**\n     * Returns a total size of the buffer, the number of bytes.\n     */\n    [[nodiscard]] size_t getElementSize() const override {\n        return elementSize;\n    }\n\n    /**\n     * Signals the readiness of new data acquired by the n-th Us4OEM module.\n     *\n     * This function should be called by us4oem interrupt callbacks.\n     *\n     * @param n us4oem ordinal number\n     *\n     *  @return true if the buffer signal was successful, false otherwise (e.g. the queue was shut down).\n     */\n    bool signal(Ordinal n, uint16 elementNr) {\n        std::unique_lock<std::mutex> guard(mutex);\n        if(this->state != State::RUNNING) {\n            getDefaultLogger()->log(LogSeverity::DEBUG, \"Signal queue shutdown.\");\n            return false;\n        }\n        this->validateState();\n        auto &element = this->elements[elementNr];\n        try {\n            element->signal(n);\n        } catch(const IllegalArgumentException &e) {\n            this->markAsInvalid();\n            throw e;\n        }\n        if(element->isElementReady()) {\n            guard.unlock();\n            onNewDataCallback(elements[elementNr]);\n        } else {\n            guard.unlock();\n        }\n        return true;\n    }\n\n    void markAsInvalid() {\n        std::unique_lock<std::mutex> guard(mutex);\n        if(this->state != State::INVALID) {\n            this->state = State::INVALID;\n            for(auto &element: elements) {\n                element->markAsInvalid();\n            }\n            this->onOverflowCallback();\n        }\n    }\n\n    void shutdown() {\n        std::unique_lock<std::mutex> guard(mutex);\n        this->onShutdownCallback();\n        this->state = State::SHUTDOWN;\n        guard.unlock();\n    }\n\n    void resetState() {\n        this->state = State::INVALID;\n        this->initialize();\n        this->state = State::RUNNING;\n    }\n\n    void initialize() {\n        for(auto &element: elements) {\n            element->resetState();\n        }\n    }\n\n    void registerReleaseFunction(size_t element, std::function<void()> &releaseFunction) {\n        this->elements[element]->registerReleaseFunction(releaseFunction);\n    }\n\n\nprivate:\n    std::mutex mutex;\n    /** A size of a single element IN number of BYTES. */\n    size_t elementSize;\n    /**  Total size in the number of elements. */\n    int16 *dataBuffer;\n    /** Host buffer elements */\n    std::vector<Us4ROutputBufferElement::SharedHandle> elements;\n    /** Relative addresses where us4oem modules will write. IN NUMBER OF BYTES. */\n    std::vector<size_t> us4oemOffsets;\n    // Callback that should be called once new data arrive.\n    framework::OnNewDataCallback onNewDataCallback;\n    framework::OnOverflowCallback onOverflowCallback{[]() {}};\n    framework::OnShutdownCallback onShutdownCallback{[]() {}};\n\n    // State management\n    enum class State {\n        RUNNING, SHUTDOWN, INVALID\n    };\n    State state{State::RUNNING};\n\n    /**\n     * Throws IllegalStateException when the buffer is in invalid state.\n     *\n     * @return true if the queue execution should continue, false otherwise.\n     */\n    void validateState() {\n        if(this->state == State::INVALID) {\n            throw ::arrus::IllegalStateException(\n                \"The buffer is in invalid state \"\n                \"(probably some data transfer overflow happened).\");\n        } else if(this->state == State::SHUTDOWN) {\n            throw ::arrus::IllegalStateException(\n                \"The data buffer has been turned off.\");\n        }\n    }\n};\n\n}\n\n#endif //ARRUS_CORE_DEVICES_US4R_US4ROUTPUTBUFFER_H\n", "meta": {"hexsha": "c47dcc8bd904a9aa961e805b9e006957c9a8f109", "size": 11406, "ext": "h", "lang": "C", "max_stars_repo_path": "arrus/core/devices/us4r/Us4ROutputBuffer.h", "max_stars_repo_name": "us4useu/arrus", "max_stars_repo_head_hexsha": "10487b09f556e327ddb1bec28fbaccf3b8b08064", "max_stars_repo_licenses": ["BSL-1.0", "MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2021-02-04T19:56:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T09:41:51.000Z", "max_issues_repo_path": "arrus/core/devices/us4r/Us4ROutputBuffer.h", "max_issues_repo_name": "us4useu/arrus", "max_issues_repo_head_hexsha": "10487b09f556e327ddb1bec28fbaccf3b8b08064", "max_issues_repo_licenses": ["BSL-1.0", "MIT"], "max_issues_count": 60.0, "max_issues_repo_issues_event_min_datetime": "2020-11-06T04:59:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T17:39:06.000Z", "max_forks_repo_path": "arrus/core/devices/us4r/Us4ROutputBuffer.h", "max_forks_repo_name": "us4useu/arrus", "max_forks_repo_head_hexsha": "10487b09f556e327ddb1bec28fbaccf3b8b08064", "max_forks_repo_licenses": ["BSL-1.0", "MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-07-22T16:13:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T08:53:31.000Z", "avg_line_length": 34.1497005988, "max_line_length": 120, "alphanum_fraction": 0.6156408908, "num_tokens": 2501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10669059962643357, "lm_q2_score": 0.029760091256823416, "lm_q1q2_score": 0.0031751219811278733}}
{"text": "/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*\n**                                                                                  **\n** This file forms part of the Underworld geophysics modelling application.         **\n**                                                                                  **\n** For full license and copyright information, please refer to the LICENSE.md file  **\n** located at the project root, or contact the authors.                             **\n**                                                                                  **\n**~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/\n#include <mpi.h>\n#include <StGermain/libStGermain/src/StGermain.h>\n#include <petsc.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst Type StGermain_Type = \"StGermain\";\n\n#include \"StGermain_Tools.h\"\n\nStgData* StgInit( int argc, char* argv[] ) {\n   StgData* data = (StgData*) malloc(sizeof(StgData));\n   *data = (StgData){.comm = NULL, .rank=-1, .nProcs=-1, .dictionary=NULL, .argcCpy=0, .argvCpy=NULL };\n\n   //lets copy all this data for safety\n   data->argcCpy = argc;\n   data->argvCpy = (char**) malloc((argc+1)*sizeof(char*));\n   int ii;\n   for(ii = 0; ii<argc; ii++){\n      data->argvCpy[ii] = (char*)malloc(strlen(argv[ii])+1);\n      strcpy(data->argvCpy[ii],argv[ii]);\n   }\n   data->argvCpy[argc] = NULL;  //add sentinel\n\n   int is_inited;\n   MPI_Initialized( &is_inited );\n   if(!is_inited)\n      MPI_Init( &argc, &argv );\n   MPI_Comm_dup( MPI_COMM_WORLD, &data->comm );\n   MPI_Comm_size( data->comm, &data->nProcs );\n   MPI_Comm_rank( data->comm, &data->rank );\n   StGermain_Init( &(data->argcCpy), &(data->argvCpy) );\n   \n   return data;\n}\n\nint StgFinalise(StgData* data){\n   /* Close off everything */\n//   StGermain_Finalise();   // avoid this finalise, as py interpreter has its own ideas about when it will destroy objects.\n   PetscFinalize();\n//   MPI_Finalize();\n\n   /* free up these guys created earlier */\n   int ii;\n   for(ii = 0; ii<data->argcCpy; ii++)\n   \t  free(data->argvCpy[ii]);\n   free(data->argvCpy);\n   free(data);\n   return 0; /* success */\n}\n\n\nvoid StgAbort(StgData* data){\n     MPI_Abort( data->comm, EXIT_FAILURE );\n}\n\n\n", "meta": {"hexsha": "9934c14e62e570307acb8ec110a765d276ee86b4", "size": 2267, "ext": "c", "lang": "C", "max_stars_repo_path": "underworld/libUnderworld/libUnderworldPy/StGermain_Tools.c", "max_stars_repo_name": "rbeucher/underworld2", "max_stars_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "underworld/libUnderworld/libUnderworldPy/StGermain_Tools.c", "max_issues_repo_name": "rbeucher/underworld2", "max_issues_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "underworld/libUnderworld/libUnderworldPy/StGermain_Tools.c", "max_forks_repo_name": "rbeucher/underworld2", "max_forks_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8358208955, "max_line_length": 124, "alphanum_fraction": 0.5183061315, "num_tokens": 721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10970576805636038, "lm_q2_score": 0.028436031809810542, "lm_q1q2_score": 0.003119596710170361}}
{"text": "#pragma once\n\n#include <memory>\n#include <memory_resource>\n\n#include <gsl-lite/gsl-lite.hpp>\n\n#include <sysmakeshift/memory.hpp>\n\nnamespace thrustshift {\n\nnamespace detail {\n\n//! Allocate without initialization\ntemplate <typename T, typename A, typename SizeC>\nT* allocate_array(A& alloc, SizeC sizeC) {\n\treturn std::allocator_traits<A>::allocate(alloc, std::size_t(sizeC));\n}\n\ntemplate <typename ArrayT, typename A>\nstd::enable_if_t<\n    sysmakeshift::detail::extent_only<ArrayT>::value == 0,\n    std::unique_ptr<ArrayT, sysmakeshift::allocator_deleter<ArrayT, A>>>\nallocate_unique(A alloc, std::size_t size) {\n\tusing T = std::remove_cv_t<sysmakeshift::detail::remove_extent_only_t<ArrayT>>;\n\tstatic_assert(\n\t    std::is_same<typename std::allocator_traits<A>::value_type, T>::value,\n\t    \"allocator has mismatching value_type\");\n\n\tT* ptr = detail::allocate_array<T>(alloc, size);\n\treturn {ptr, {std::move(alloc), size}};\n}\n\n} // namespace detail\n\n/*! \\brief Container which provides memory with a custom allocator.\n *\n *  Useful in combination with memory which is not accessible on the\n *  host. E.g. you can use a device memory allocator with this class\n *  to obtain device memory and pass it as a span to a GPU kernel.\n */\ntemplate <typename T, class Allocator>\nclass not_a_vector {\n\n   public:\n\tnot_a_vector(std::size_t size, Allocator& alloc)\n\t    : ptr_(detail::allocate_unique<T[]>(alloc, size)), size_(size) {\n\t}\n\n\tgsl_lite::span<T> to_span() const {\n\t\treturn gsl_lite::make_span(ptr_.get(), size_);\n\t}\n\n   private:\n\tstd::unique_ptr<T[], sysmakeshift::allocator_deleter<T[], Allocator>> ptr_;\n\tstd::size_t size_;\n};\n\ntemplate <typename T, class Resource>\nauto make_not_a_vector(std::size_t size, Resource& memory_resource) {\n\tstd::pmr::polymorphic_allocator<T> alloc(&memory_resource);\n\treturn not_a_vector<T, decltype(alloc)>(size, alloc);\n}\n\n/*! \\brief Make not_a_vector object and the span on the corresponding buffer.\n *\n *  This function makes it easier to construct the owning container and the view\n *  in one line of code with structured bindings.\n *\n *  ```cpp\n *\n *  auto [nav, span] = make_not_a_vector_and_span<T>(N, resource);\n *  ```\n */\ntemplate <typename T, class Resource>\nauto make_not_a_vector_and_span(std::size_t size, Resource& memory_resource) {\n\tstd::pmr::polymorphic_allocator<T> alloc(&memory_resource);\n\tauto nav = not_a_vector<T, decltype(alloc)>(size, alloc);\n\tauto s = nav.to_span();\n\treturn std::make_tuple(std::move(nav), s);\n}\n\n} // namespace thrustshift\n", "meta": {"hexsha": "e8fc09b5a7366bb87c7c55a3404029272f521fa9", "size": 2499, "ext": "h", "lang": "C", "max_stars_repo_path": "include/thrustshift/not-a-vector.h", "max_stars_repo_name": "pauleonix/thrustshift", "max_stars_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-16T13:01:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T13:01:46.000Z", "max_issues_repo_path": "include/thrustshift/not-a-vector.h", "max_issues_repo_name": "pauleonix/thrustshift", "max_issues_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-23T14:12:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-17T11:40:04.000Z", "max_forks_repo_path": "include/thrustshift/not-a-vector.h", "max_forks_repo_name": "pauleonix/thrustshift", "max_forks_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.75, "max_line_length": 80, "alphanum_fraction": 0.7266906763, "num_tokens": 628, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09670580110615865, "lm_q2_score": 0.03210070822170239, "lm_q1q2_score": 0.003104324704654783}}
{"text": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n#pragma once\n\n#include \"iterators.h\"\n#include \"macros.h\"\n#include \"type_traits.h\"\n#include \"string.h\"\n#include \"path.h\"\n\n#include <cereal/cereal.hpp>\n\n#include <algorithm>\n#include <assert.h>\n#include <cmath>\n#include <gsl/gsl>\n#include <iterator>\n#include <map>\n#include <sstream>\n#include <string>\n#include <vector>\n\nnamespace mira\n{\n    struct property_bag;\n\n    struct property_interface\n    {\n        property_interface(const char* type, const char* name)\n            : m_type{ type }\n            , m_name{ name }\n        {}\n\n        virtual ~property_interface()\n        {}\n\n        const char* name() const\n        {\n            return m_name;\n        }\n\n        const char* type() const\n        {\n            return m_type;\n        }\n\n    private:\n        const char* const m_type;\n        const char* const m_name;\n    };\n\n    struct simple_property : public property_interface\n    {\n        virtual void from_string(const std::string& str) = 0;\n        virtual void from_stream(std::istream& str) = 0;\n\n        virtual void from_other(const property_interface& other) = 0;\n\n        virtual std::type_index serializable_type() const = 0;\n\n        virtual std::string to_string() const = 0;\n\n        simple_property(const char* type, const char* name)\n            : property_interface(type, name)\n        {}\n    };\n\n    template<typename SerializableType>\n    struct serializable_property : public simple_property\n    {\n        serializable_property(const char* type, const char* name)\n            : simple_property(type, name)\n        {}\n\n        virtual ~serializable_property() {}\n\n        std::type_index serializable_type() const override\n        {\n            return { typeid(SerializableType) };\n        }\n\n        // serialization functions\n        template<class Archive>\n        SerializableType save_minimal(Archive const&) const\n        {\n            return get_serializable();\n        }\n\n        template<class Archive>\n        void load_minimal(Archive const&, SerializableType const& val)\n        {\n            set_serializable(val);\n        }\n\n    protected:\n        virtual SerializableType get_serializable() const = 0;\n        virtual void set_serializable(const SerializableType& value) = 0;\n    };\n\n    template<typename T> struct property;\n\n    struct property_bag : public property_interface\n    {\n        bool set(const std::string& name, const std::string& value)\n        {\n            auto itr = m_properties.find(name.c_str());\n            if (itr == m_properties.end())\n                return false;\n\n            itr->second->from_string(value);\n\n            return true;\n        }\n\n        void from_other(const property_bag& other)\n        {\n            assert(strcmp(name(), other.name()) == 0);\n            assert(other.m_properties.size() == m_properties.size());\n            assert(other.m_groups.size() == m_groups.size());\n\n            for (auto prop : m_properties)\n            {\n                prop.second->from_other(*other.m_properties.at(prop.first));\n            }\n\n            for (size_t i = 0; i < m_groups.size(); ++i)\n            {\n                assert(strcmp(m_groups[i]->name(), other.m_groups[i]->name()) == 0);\n                m_groups[i]->from_other(*other.m_groups[i]);\n            }\n        }\n\n        std::string get(const std::string& name) const\n        {\n            return m_properties.find(name.c_str())->second->to_string();\n        }\n\n        std::vector<simple_property*> properties()\n        {\n            std::vector<simple_property*> props;\n            std::transform(m_properties.begin(), m_properties.end(), std::back_inserter(props), [](const auto& entry) {\n                return entry.second;\n            });\n            return props;\n        }\n\n        std::vector<const simple_property*> properties() const\n        {\n            std::vector<const simple_property*> props;\n            std::transform(m_properties.begin(), m_properties.end(), std::back_inserter(props), [](const auto& entry) {\n                return entry.second;\n            });\n            return props;\n        }\n\n        gsl::span<property_bag*> groups()\n        {\n            return m_groups;\n        }\n\n        gsl::span<const property_bag*> groups() const\n        {\n            return { const_cast<property_bag const**>(m_groups.data()), (gsl::span<const property_bag*>::size_type)m_groups.size() };\n        }\n\n        // serialization function\n        template<typename ArchiveT>\n        void serialize(ArchiveT& ar)\n        {\n            using arch_func = void(ArchiveT & ar, property_interface * prop);\n\n            static std::unordered_map<std::type_index, arch_func*> converters{\n                { typeid(bool), &archive_prop<ArchiveT, serializable_property<bool>> },\n                { typeid(int), &archive_prop<ArchiveT, serializable_property<int>> },\n                { typeid(unsigned int), &archive_prop<ArchiveT, serializable_property<unsigned int>> },\n                { typeid(uint32_t), &archive_prop<ArchiveT, serializable_property<uint32_t>> },\n                { typeid(uint64_t), &archive_prop<ArchiveT, serializable_property<uint64_t>> },\n                { typeid(size_t), &archive_prop<ArchiveT, serializable_property<size_t>> },\n                { typeid(float), &archive_prop<ArchiveT, serializable_property<float>> },\n                { typeid(std::string), &archive_prop<ArchiveT, serializable_property<std::string>> },\n                { typeid(double), &archive_prop<ArchiveT, serializable_property<double>> },\n            };\n\n            for (auto prop : m_properties)\n            {\n                auto found = converters.find(prop.second->serializable_type());\n                if (found == converters.end())\n                    throw std::invalid_argument(\"unable to convert type, conversion function not found\");\n\n                found->second(ar, prop.second);\n            }\n\n            for (auto group : m_groups)\n            {\n                ar(cereal::make_nvp(group->name(), *group));\n            }\n        }\n\n    protected:\n        property_bag(const char* name)\n            : property_bag{ name, nullptr }\n        {}\n\n        property_bag(const char* name, property_bag* owner)\n            : property_interface{ \"bag\", name }\n        {\n            if (owner != nullptr)\n            {\n                owner->add(this);\n            }\n        }\n\n        property_bag(const property_bag& other) = delete;\n        property_bag& operator=(const property_bag& other) = delete;\n\n    private:\n        template<typename ArchiveT, typename T>\n        static void archive_prop(ArchiveT& ar, property_interface* prop)\n        {\n            ar(cereal::make_nvp(prop->name(), *static_cast<T*>(prop)));\n        }\n\n        template<typename T>\n        friend struct property;\n\n        void add(simple_property* prop)\n        {\n            m_properties.insert({ prop->name(), prop });\n        }\n\n        void add(property_bag* prop)\n        {\n            m_groups.push_back(prop);\n        }\n\n        std::map<const char*, simple_property*, string_compare> m_properties;\n\n        std::vector<property_bag*> m_groups;\n    };\n\n    template<typename T, bool isEnum = std::is_enum<T>::value>\n    struct property_serialization_traits;\n\n    template<typename T>\n    struct property_serialization_traits<T, true>\n    {\n        using serialization_type = std::underlying_type_t<T>;\n\n        static serialization_type to_serializable(const T& value)\n        {\n            return static_cast<serialization_type>(value);\n        }\n\n        static T from_serializable(const serialization_type& value)\n        {\n            return static_cast<T>(value);\n        }\n\n        static void from_stream(std::istream& stream, T& value)\n        {\n            serialization_type underlyingValue{};\n\n            stream >> underlyingValue;\n\n            assert(!stream.fail() && \"Property bag failed to convert string to value\");\n\n            value = static_cast<T>(underlyingValue);\n        }\n\n        static void to_stream(std::ostream& stream, const T& value)\n        {\n            auto underlying = static_cast<serialization_type>(value);\n\n            std::stringstream ss;\n            stream.precision(std::numeric_limits<serialization_type>::max_digits10);\n            stream << underlying;\n\n            assert(!stream.fail() && \"Property bag failed to convert value to string\");\n        }\n    };\n\n    template<typename T>\n    struct property_serialization_traits<T, false>\n    {\n        using serialization_type = T;\n\n        static serialization_type to_serializable(const T& value)\n        {\n            return value;\n        }\n\n        static T from_serializable(const serialization_type& value)\n        {\n            return value;\n        }\n\n        static void from_stream(std::istream& stream, T& value)\n        {\n            if (std::is_same<T, bool>())\n            {\n                stream >> std::boolalpha >> value;\n            }\n            else\n            {\n                stream >> value;\n            }\n\n            assert((is_string<T>() || !stream.fail()) && \"Property bag failed to convert string to value\");\n        }\n\n        static void to_stream(std::ostream& stream, const T& value)\n        {\n            if (std::is_same<T, bool>())\n            {\n                stream << std::boolalpha << value;\n            }\n            else\n            {\n                stream.precision(std::numeric_limits<T>::max_digits10);\n                stream << value;\n            }\n            assert(!stream.fail() && \"Property bag failed to convert value to string\");\n        }\n    };\n\n    template<>\n    struct property_serialization_traits<path, false>\n    {\n        using serialization_type = std::string;\n\n        static serialization_type to_serializable(const path& value)\n        {\n            return value.string();\n        }\n\n        static path from_serializable(const serialization_type& value)\n        {\n            return { value };\n        }\n\n        static void from_stream(std::istream& stream, path& value)\n        {\n            stream >> value;\n        }\n\n        static void to_stream(std::ostream& stream, const path& value)\n        {\n            stream << value;\n        }\n    };\n\n    template<typename T>\n    struct property : public serializable_property<typename property_serialization_traits<T>::serialization_type>\n    {\n        using traits = property_serialization_traits<T>;\n\n        using type = std::decay_t<T>;\n\n        property(property_bag* lookup, const char* name, const char* type, const T& defaultValue)\n            : serializable_property<typename traits::serialization_type>{ type, name }\n            , value{ defaultValue }\n        {\n            lookup->add(this);\n        }\n\n        property& operator=(const property& other)\n        {\n            value = other.value;\n            return *this;\n        }\n\n        virtual void from_string(const std::string& str) override\n        {\n            std::stringstream ss{ str };\n            from_stream(ss);\n        }\n\n        virtual void from_stream(std::istream& stream) override\n        {\n            traits::from_stream(stream, value);\n        }\n\n        virtual void from_other(const property_interface& other) override\n        {\n            assert(dynamic_cast<const property<T>*>(&other) && \"invalid type\");\n            value = static_cast<const property<T>&>(other).value;\n        }\n\n        virtual std::string to_string() const override\n        {\n            std::stringstream ss;\n            traits::to_stream(ss, value);\n            return ss.str();\n        }\n\n        operator T() const\n        {\n            return value;\n        }\n\n        property& operator=(const T& val)\n        {\n            value = val;\n            return *this;\n        }\n\n        T value;\n\n    protected:\n        typename traits::serialization_type get_serializable() const override\n        {\n            return traits::to_serializable(value);\n        }\n\n        void set_serializable(const typename traits::serialization_type& val) override\n        {\n            value = traits::from_serializable(val);\n        }\n    };\n\n    template<typename T>\n    std::ostream& operator<<(std::ostream& os, const property<T>& prop)\n    {\n        return os << prop.value;\n    }\n}\n\n#define PROPERTY(TYPE, NAME, DEFAULT) ::mira::property<TYPE> NAME{ this, #NAME, #TYPE, DEFAULT };\n\n#define WEIRDLY_NAMED_PROPERTY(TYPE, STRNAME, DEFAULT)                                                                 \\\n    ::mira::property<TYPE> CONCATENATE_MACRO(setting_, __COUNTER__){ this, STRNAME, #TYPE, DEFAULT };\n\n#define BAG_PROPERTY(TYPE) TYPE TYPE{ this };\n\n#define NAMED_BAG_PROPERTY(TYPE, NAME) TYPE NAME{ this, #NAME };\n\n#define PROPERTYBAG(NAME, ...)                                                                                         \\\n    struct NAME : public ::mira::property_bag                                                                          \\\n    {                                                                                                                  \\\n        NAME(const NAME& other)                                                                                        \\\n            : NAME{ other.name() }                                                                                     \\\n        {                                                                                                              \\\n            from_other(other);                                                                                         \\\n        }                                                                                                              \\\n        NAME& operator=(const NAME& other)                                                                             \\\n        {                                                                                                              \\\n            from_other(other);                                                                                         \\\n            return *this;                                                                                              \\\n        }                                                                                                              \\\n        NAME()                                                                                                         \\\n            : ::mira::property_bag{ #NAME }                                                                            \\\n        {}                                                                                                             \\\n        NAME(::mira::property_bag* owner)                                                                              \\\n            : ::mira::property_bag{ #NAME, owner }                                                                     \\\n        {}                                                                                                             \\\n        NAME(const char* name)                                                                                         \\\n            : ::mira::property_bag{ name }                                                                             \\\n        {}                                                                                                             \\\n        NAME(::mira::property_bag* owner, const char* name)                                                            \\\n            : ::mira::property_bag{ name, owner }                                                                      \\\n        {}                                                                                                             \\\n        __VA_ARGS__                                                                                                    \\\n    }\n", "meta": {"hexsha": "dcd138fe3faa67501296e090fb08203bb6913d66", "size": 15866, "ext": "h", "lang": "C", "max_stars_repo_path": "Dependencies/Arcana/Shared/arcana/propertybag.h", "max_stars_repo_name": "syntheticmagus/mageslam", "max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z", "max_issues_repo_path": "Dependencies/Arcana/Shared/arcana/propertybag.h", "max_issues_repo_name": "syntheticmagus/mageslam", "max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z", "max_forks_repo_path": "Dependencies/Arcana/Shared/arcana/propertybag.h", "max_forks_repo_name": "syntheticmagus/mageslam", "max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z", "avg_line_length": 34.1204301075, "max_line_length": 133, "alphanum_fraction": 0.4726459095, "num_tokens": 2800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.17781087819190095, "lm_q2_score": 0.017442482022795774, "lm_q1q2_score": 0.0031014630463197614}}
{"text": "/*\n   Copyright [2017-2021] [IBM Corporation]\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n       http://www.apache.org/licenses/LICENSE-2.0\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\n#ifndef MCAS_HSTORE_HEAP_MC_EPHEMERAL_H\n#define MCAS_HSTORE_HEAP_MC_EPHEMERAL_H\n\n#include \"heap_mm_ephemeral.h\"\n\n#include \"hstore_config.h\"\n#include \"histogram_log2.h\"\n#include \"hop_hash_log.h\"\n#include <mm_plugin_itf.h>\n#include \"persistent.h\"\n\n#include <ccpm/cca.h> /* ctor_args */\n#include <ccpm/interfaces.h> /* ownership_callback, (IHeap_expandable, region_vector_t) */\n#include <common/byte_span.h>\n#include <common/string_view.h>\n#include <nupm/region_descriptor.h>\n#include <gsl/span>\n\n#include <algorithm> /* min, swap */\n#include <cstddef> /* size_t */\n#include <functional> /* function */\n#include <memory> /* unique_ptr */\n#include <vector>\n\nnamespace impl\n{\n\tstruct allocation_state_pin;\n\tstruct allocation_state_emplace;\n\tstruct allocation_state_extend;\n}\n\nstruct heap_mc_ephemeral\n  : public heap_mm_ephemeral\n{\nprivate:\n\tusing byte_span = common::byte_span;\n\tusing string_view = common::string_view;\n\tstd::unique_ptr<\n\t\tccpm::IHeap_expandable\n\t> _heap;\n\timpl::allocation_state_emplace *_ase;\n\timpl::allocation_state_pin *_aspd;\n\timpl::allocation_state_pin *_aspk;\n\timpl::allocation_state_extend *_asx;\n\n\tstatic constexpr unsigned log_min_alignment = 3U; /* log (sizeof(void *)) */\n\tstatic_assert(sizeof(void *) == 1U << log_min_alignment, \"log_min_alignment does not match sizeof(void *)\");\n\t/* Rca_LB seems not to allocate at or above about 2GiB. Limit reporting to 16 GiB. */\n\tstatic constexpr unsigned hist_report_upper_bound = 34U;\n\texplicit heap_mc_ephemeral(\n\t\tunsigned debug_level_\n\t\t, bool restore_not_clear\n\t\t, impl::allocation_state_emplace *ase\n\t\t, impl::allocation_state_pin *aspd\n\t\t, impl::allocation_state_pin *aspk\n\t\t, impl::allocation_state_extend *asx\n\t\t, std::unique_ptr<ccpm::IHeap_expandable> p\n\t\t, string_view id\n\t\t, string_view backing_file\n\t\t, const std::vector<byte_span> rv_full\n\t\t, const byte_span pool0_heap\n\t);\n\npublic:\n\tfriend struct heap_mc;\n\tfriend struct heap_mm;\n\n\tusing common::log_source::debug_level;\n\n\t/* heap_mm version */\n\texplicit heap_mc_ephemeral(\n\t\tunsigned debug_level\n\t\t, bool restore_not_clear\n\t\t, MM_plugin_wrapper &&pw\n\t\t, impl::allocation_state_emplace *ase\n\t\t, impl::allocation_state_pin *aspd\n\t\t, impl::allocation_state_pin *aspk\n\t\t, impl::allocation_state_extend *asx\n\t\t, string_view id\n\t\t, string_view backing_file\n\t\t, const std::vector<byte_span> rv_full\n\t\t, byte_span pool0_heap_\n\t);\n\n\tstd::size_t allocated() const override; // { return _allocated; }\n\tstd::size_t capacity() const override; // { return _capacity; }\n\tvoid allocate(persistent_t<void *> &p, std::size_t sz, std::size_t alignment) override;\n\tstd::size_t free(persistent_t<void *> &p_, std::size_t sz_) override;\n\tvoid free_tracked(const void *p, std::size_t sz) override;\n\theap_mc_ephemeral(const heap_mc_ephemeral &) = delete;\n\theap_mc_ephemeral& operator=(const heap_mc_ephemeral &) = delete;\n\tvoid add_managed_region_to_heap(byte_span r_heap) override;\n\tvoid reconstitute_managed_region_to_heap(byte_span r_heap, ccpm::ownership_callback_t f) override;\n\tbool is_crash_consistent() const override;\n\tbool can_reconstitute() const override;\n};\n\n#endif\n", "meta": {"hexsha": "8be4a9b6fbd1a53068f4c8b1b889a967e94d0c34", "size": 3687, "ext": "h", "lang": "C", "max_stars_repo_path": "src/components/store/hstore/src/heap_mc_ephemeral.h", "max_stars_repo_name": "omriarad/mcas", "max_stars_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 60.0, "max_stars_repo_stars_event_min_datetime": "2020-04-28T08:15:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T10:35:15.000Z", "max_issues_repo_path": "src/components/store/hstore/src/heap_mc_ephemeral.h", "max_issues_repo_name": "omriarad/mcas", "max_issues_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 66.0, "max_issues_repo_issues_event_min_datetime": "2020-09-03T23:40:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T20:34:52.000Z", "max_forks_repo_path": "src/components/store/hstore/src/heap_mc_ephemeral.h", "max_forks_repo_name": "omriarad/mcas", "max_forks_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2019-11-02T06:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T01:56:42.000Z", "avg_line_length": 32.9196428571, "max_line_length": 109, "alphanum_fraction": 0.7615947925, "num_tokens": 961, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.13660840408654296, "lm_q2_score": 0.02262919739647132, "lm_q1q2_score": 0.0030913385420913}}
{"text": "#pragma once\n\n#include <cstdint>\n#include <functional>\n#include <memory>\n#include <string>\n#include <tuple>\n#include <utility>\n#include <vector>\n\n#include <gsl/gsl>\n#include <nonstd/optional.hpp>\n\n#include \"chainerx/array_body.h\"\n#include \"chainerx/array_fwd.h\"\n#include \"chainerx/device.h\"\n#include \"chainerx/dtype.h\"\n#include \"chainerx/graph.h\"\n#include \"chainerx/macro.h\"\n#include \"chainerx/shape.h\"\n\nnamespace chainerx {\n\nclass BackwardContext;\nclass Device;\n\nusing BackwardFunction = std::function<void(BackwardContext&)>;\n\nnamespace internal {\n\nclass ArrayNode;\nclass OpNode;\n\nstruct ArrayProps {\n    explicit ArrayProps(const Array& array);\n    explicit ArrayProps(const ArrayNode& array_node);\n    explicit ArrayProps(const ArrayBody& array_body);\n\n    Shape shape;\n    Dtype dtype;\n    Device& device;\n};\n\nclass OpNodeBackwardEntry {\npublic:\n    OpNodeBackwardEntry(OpNode& op_node, std::vector<size_t> input_array_node_indices, BackwardFunction backward_func);\n\n    OpNode& op_node() const { return op_node_; }\n\n    size_t input_array_node_count() const { return input_array_node_indices_.size(); }\n\n    const std::vector<size_t>& input_array_node_indices() const { return input_array_node_indices_; }\n\n    const BackwardFunction& backward_func() const { return backward_func_; }\n\nprivate:\n    friend class OpNode;\n\n    OpNode& op_node_;\n\n    // The index mapping from local (this backward function) to global (op node).\n    // Can be unset if the input array does not require grad.\n    std::vector<size_t> input_array_node_indices_;\n\n    BackwardFunction backward_func_;\n};\n\n// Creates an output array node at the specified index and adds edges between the output array node and the op node.\n// Undefined behavior if the output array node already exists.\n// This function is used by BackwardContext::GetRetainedOutput().\nstd::shared_ptr<ArrayNode> FabricateOutputArrayNode(std::shared_ptr<OpNode> op_node, size_t output_array_node_index);\n\nclass OpNode {\npublic:\n    // Creates a new op node that has output array nodes corresponding to the given outputs.\n    static std::shared_ptr<OpNode> CreateWithOutputArrayNodes(\n            std::string name, BackpropId backprop_id, size_t input_count, const std::vector<ConstArrayRef>& outputs);\n\n    OpNode(const OpNode&) = delete;\n    OpNode(OpNode&&) = delete;\n    OpNode& operator=(const OpNode&) = delete;\n    OpNode& operator=(OpNode&&) = delete;\n\n    OpNodeBackwardEntry& RegisterBackwardFunction(\n            std::vector<std::tuple<size_t, std::shared_ptr<ArrayNode>>> input_array_nodes, BackwardFunction backward_func);\n\n    // Adds links to input array nodes of other graphs.\n    // The size of the vector must be equal to the number of inputs.\n    void AddEdgesToInputArrayNodesOfOuterGraph(\n            const BackpropId& outer_backprop_id, std::vector<std::shared_ptr<ArrayNode>> outer_graphs_input_array_nodes);\n\n    // Adds links to output array nodes of other graphs.\n    // The size of the vector must be equal to the number of outputs.\n    void AddEdgesToOutputArrayNodesOfOuterGraph(\n            const BackpropId& outer_backprop_id, std::vector<std::shared_ptr<ArrayNode>> outer_graphs_output_array_nodes);\n\n    void Unchain() {\n        backward_entries_.clear();\n        std::fill(input_array_nodes_.begin(), input_array_nodes_.end(), std::shared_ptr<ArrayNode>{});\n        AssertConsistency();\n    }\n\n    bool HasInputArrayNode(size_t input_index) const { return input_array_nodes_[input_index] != nullptr; }\n\n    std::string name() const { return name_; }\n\n    std::vector<std::shared_ptr<ArrayNode>>& input_array_nodes();\n\n    const std::vector<std::shared_ptr<ArrayNode>>& input_array_nodes() const;\n\n    gsl::span<OpNodeBackwardEntry> backward_entries() { return backward_entries_; }\n\n    gsl::span<const OpNodeBackwardEntry> backward_entries() const { return backward_entries_; }\n\n    size_t input_array_node_count() const { return input_array_nodes_.size(); }\n\n    size_t output_array_node_count() const { return output_array_props_.size(); }\n\n    int64_t rank() const { return rank_; }\n\n    BackpropId backprop_id() const { return backprop_id_; }\n\n    const ArrayProps& GetOutputArrayProps(size_t i) const {\n        CHAINERX_ASSERT(i < output_array_props_.size());\n        return output_array_props_[i];\n    }\n\n    // Returns the list of output array nodes on \"this\" graph.\n    const std::vector<nonstd::optional<std::weak_ptr<ArrayNode>>>& output_array_nodes() const { return output_array_nodes_; }\n\n    // Returns the list of output array nodes on \"this\" graph.\n    std::vector<nonstd::optional<std::weak_ptr<ArrayNode>>>& output_array_nodes() { return output_array_nodes_; }\n\n    // Returns the input array nodes of all graphs.\n    const std::vector<std::tuple<BackpropId, std::vector<std::shared_ptr<ArrayNode>>>>& outer_graphs_input_array_nodes() const {\n        return outer_graphs_input_array_nodes_;\n    }\n\n    // Returns the output array nodes of all graphs.\n    const std::vector<std::tuple<BackpropId, std::vector<std::shared_ptr<ArrayNode>>>>& outer_graphs_output_array_nodes() const {\n        return outer_graphs_output_array_nodes_;\n    }\n\nprivate:\n    OpNode(std::string name, BackpropId backprop_id, size_t input_array_node_count);\n\n    void AssertConsistency() const;\n\n    std::string name_;\n\n    // Backprop ID.\n    // Backprop ID is also held in the first entry of output_array_nodes_, but the reference to it may be invalidated, whereas this member\n    // is stable during the lifetime of this OpNode instance.\n    BackpropId backprop_id_;\n\n    int64_t rank_{0};\n\n    // List of input array nodes.\n    std::vector<std::shared_ptr<ArrayNode>> input_array_nodes_;\n\n    // List of output array nodes of this graph.\n    std::vector<nonstd::optional<std::weak_ptr<ArrayNode>>> output_array_nodes_;\n\n    // List of input/output array nodes of outer graphs.\n    // Outer graphs refer to graphs with lower ordinals.\n    // Each entry is a pair of backprop ID and list of input/output array nodes.\n    std::vector<std::tuple<BackpropId, std::vector<std::shared_ptr<ArrayNode>>>> outer_graphs_input_array_nodes_;\n    std::vector<std::tuple<BackpropId, std::vector<std::shared_ptr<ArrayNode>>>> outer_graphs_output_array_nodes_;\n\n    // Array props of output array nodes. This is used for creating dummy gradients.\n    std::vector<ArrayProps> output_array_props_;\n\n    std::vector<OpNodeBackwardEntry> backward_entries_;\n};\n\n}  // namespace internal\n}  // namespace chainerx\n", "meta": {"hexsha": "d2668613609bbd5553084346eb4cf5a25752b1dc", "size": 6463, "ext": "h", "lang": "C", "max_stars_repo_path": "chainerx_cc/chainerx/op_node.h", "max_stars_repo_name": "yuhonghong66/chainer", "max_stars_repo_head_hexsha": "15d475f54fc39587abd7264808c5e4b33782df9e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-02-14T09:18:32.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-14T09:18:32.000Z", "max_issues_repo_path": "chainerx_cc/chainerx/op_node.h", "max_issues_repo_name": "nolfwin/chainer", "max_issues_repo_head_hexsha": "8d776fcc1e848cb9d3800a6aab356eb91ae9d088", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-05-14T15:45:01.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-15T07:12:49.000Z", "max_forks_repo_path": "chainerx_cc/chainerx/op_node.h", "max_forks_repo_name": "nolfwin/chainer", "max_forks_repo_head_hexsha": "8d776fcc1e848cb9d3800a6aab356eb91ae9d088", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-05-28T22:43:34.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-28T22:43:34.000Z", "avg_line_length": 36.308988764, "max_line_length": 138, "alphanum_fraction": 0.7361906235, "num_tokens": 1510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.17106119167858438, "lm_q2_score": 0.017986211278065767, "lm_q1q2_score": 0.0030767427350087244}}
{"text": "/* block/gsl_block_uint.h\r\n * \r\n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\r\n * \r\n * This program is free software; you can redistribute it and/or modify\r\n * it under the terms of the GNU General Public License as published by\r\n * the Free Software Foundation; either version 3 of the License, or (at\r\n * your option) any later version.\r\n * \r\n * This program is distributed in the hope that it will be useful, but\r\n * WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n * General Public License for more details.\r\n * \r\n * You should have received a copy of the GNU General Public License\r\n * along with this program; if not, write to the Free Software\r\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r\n */\r\n\r\n#ifndef __GSL_BLOCK_UINT_H__\r\n#define __GSL_BLOCK_UINT_H__\r\n\r\n#if !defined( GSL_FUN )\r\n#  if !defined( GSL_DLL )\r\n#    define GSL_FUN extern\r\n#  elif defined( BUILD_GSL_DLL )\r\n#    define GSL_FUN extern __declspec(dllexport)\r\n#  else\r\n#    define GSL_FUN extern __declspec(dllimport)\r\n#  endif\r\n#endif\r\n\r\n#include <stdlib.h>\r\n#include <gsl/gsl_errno.h>\r\n\r\n#undef __BEGIN_DECLS\r\n#undef __END_DECLS\r\n#ifdef __cplusplus\r\n# define __BEGIN_DECLS extern \"C\" {\r\n# define __END_DECLS }\r\n#else\r\n# define __BEGIN_DECLS /* empty */\r\n# define __END_DECLS /* empty */\r\n#endif\r\n\r\n__BEGIN_DECLS\r\n\r\nstruct gsl_block_uint_struct\r\n{\r\n  size_t size;\r\n  unsigned int *data;\r\n};\r\n\r\ntypedef struct gsl_block_uint_struct gsl_block_uint;\r\n\r\nGSL_FUN gsl_block_uint *gsl_block_uint_alloc (const size_t n);\r\nGSL_FUN gsl_block_uint *gsl_block_uint_calloc (const size_t n);\r\nGSL_FUN void gsl_block_uint_free (gsl_block_uint * b);\r\n\r\nGSL_FUN int gsl_block_uint_fread (FILE * stream, gsl_block_uint * b);\r\nGSL_FUN int gsl_block_uint_fwrite (FILE * stream, const gsl_block_uint * b);\r\nGSL_FUN int gsl_block_uint_fscanf (FILE * stream, gsl_block_uint * b);\r\nGSL_FUN int gsl_block_uint_fprintf (FILE * stream, const gsl_block_uint * b, const char *format);\r\n\r\nGSL_FUN int gsl_block_uint_raw_fread (FILE * stream, unsigned int * b, const size_t n, const size_t stride);\r\nGSL_FUN int gsl_block_uint_raw_fwrite (FILE * stream, const unsigned int * b, const size_t n, const size_t stride);\r\nGSL_FUN int gsl_block_uint_raw_fscanf (FILE * stream, unsigned int * b, const size_t n, const size_t stride);\r\nGSL_FUN int gsl_block_uint_raw_fprintf (FILE * stream, const unsigned int * b, const size_t n, const size_t stride, const char *format);\r\n\r\nGSL_FUN size_t gsl_block_uint_size (const gsl_block_uint * b);\r\nGSL_FUN unsigned int * gsl_block_uint_data (const gsl_block_uint * b);\r\n\r\n__END_DECLS\r\n\r\n#endif /* __GSL_BLOCK_UINT_H__ */\r\n", "meta": {"hexsha": "4d1cec7eb619890bf5e098bf3eb136157e96ef4c", "size": 2750, "ext": "h", "lang": "C", "max_stars_repo_path": "deps/include/gsl/gsl_block_uint.h", "max_stars_repo_name": "berkus/music-cs", "max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z", "max_issues_repo_path": "deps/include/gsl/gsl_block_uint.h", "max_issues_repo_name": "berkus/music-cs", "max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z", "max_forks_repo_path": "deps/include/gsl/gsl_block_uint.h", "max_forks_repo_name": "berkus/music-cs", "max_forks_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 36.1842105263, "max_line_length": 137, "alphanum_fraction": 0.7443636364, "num_tokens": 708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11124121829336078, "lm_q2_score": 0.027585282326718426, "lm_q1q2_score": 0.0030686204129904715}}
{"text": "#pragma once\n\n#define NOMINMAX\n\n#ifndef _WIN32\n#include <wsl/winadapter.h>\n#include \"directml_guids.h\"\n#endif\n\n#include <unordered_map>\n#include <vector>\n#include <iostream>\n#include <filesystem>\n#include <variant>\n#include <fstream>\n#include <deque>\n#include <optional>\n#include <set>\n#include <string_view>\n#include <wrl/client.h>\n#include <wil/result.h>\n#include <gsl/gsl>\n#include <DirectML.h>\n#include \"DirectMLX.h\"\n#include <rapidjson/document.h>\n#include <rapidjson/istreamwrapper.h>\n#include <fmt/format.h>\n#include <half.hpp>\n\ntemplate<class... Ts> struct overload : Ts... { using Ts::operator()...; };\ntemplate<class... Ts> overload(Ts...) -> overload<Ts...>;", "meta": {"hexsha": "b1424734a67c7a8dd78ec5339e3ff9ac893b8136", "size": 669, "ext": "h", "lang": "C", "max_stars_repo_path": "DxDispatch/src/model/pch.h", "max_stars_repo_name": "miaobin/DirectML", "max_stars_repo_head_hexsha": "d4657006a60a7b7d9baf17638c42aee27258c836", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2019-05-07T14:41:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-14T07:36:27.000Z", "max_issues_repo_path": "DxDispatch/src/model/pch.h", "max_issues_repo_name": "miaobin/DirectML", "max_issues_repo_head_hexsha": "d4657006a60a7b7d9baf17638c42aee27258c836", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2019-05-10T09:12:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-09T01:51:06.000Z", "max_forks_repo_path": "DxDispatch/src/model/pch.h", "max_forks_repo_name": "miaobin/DirectML", "max_forks_repo_head_hexsha": "d4657006a60a7b7d9baf17638c42aee27258c836", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2019-05-13T12:56:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-12T15:57:58.000Z", "avg_line_length": 21.5806451613, "max_line_length": 75, "alphanum_fraction": 0.7174887892, "num_tokens": 167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09947020854296808, "lm_q2_score": 0.030675801046049608, "lm_q1q2_score": 0.003051328327273153}}
{"text": "#pragma once\n\n#include <nextalign/nextalign.h>\n\n#include <gsl/string_span>\n#include <string>\n\n#include \"../nextalign_private.h\"\n#include \"../utils/to_underlying.h\"\n\nusing AminoacidSequenceSpan = SequenceSpan<Aminoacid>;\n\nAminoacid charToAa(char aa);\n\nchar aaToChar(Aminoacid aa);\n\ninline std::ostream& operator<<(std::ostream& os, const Aminoacid& aminoacid) {\n  os << std::string{to_underlying(aminoacid)};\n  return os;\n}\n", "meta": {"hexsha": "50e6079acc129efb0d1c5e36ac5ef7a4feec5fac", "size": 423, "ext": "h", "lang": "C", "max_stars_repo_path": "packages/nextalign/src/alphabet/aminoacids.h", "max_stars_repo_name": "davidcroll/nextclade", "max_stars_repo_head_hexsha": "f62d906034974c160eabb12ac9bf98a691646ee3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "packages/nextalign/src/alphabet/aminoacids.h", "max_issues_repo_name": "davidcroll/nextclade", "max_issues_repo_head_hexsha": "f62d906034974c160eabb12ac9bf98a691646ee3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "packages/nextalign/src/alphabet/aminoacids.h", "max_forks_repo_name": "davidcroll/nextclade", "max_forks_repo_head_hexsha": "f62d906034974c160eabb12ac9bf98a691646ee3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.1428571429, "max_line_length": 79, "alphanum_fraction": 0.7423167849, "num_tokens": 111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.11920292202211756, "lm_q2_score": 0.025565213923269593, "lm_q1q2_score": 0.0030474482017742595}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n/* inet_aton -> per utilizzarla in gcc: __USE_MISC */\n#define __USE_MISC\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <arpa/inet.h>\n#include <pthread.h>\n#include \"buffer.h\"\n#include \"list.h\"\n#include \"router.h\"\n#include <gsl/gsl_matrix.h>\n\n#define DIM_BUFFER 1000\n#define POISON_ID -1\n\nstruct msg_t {\n    int msg_id;\n    int msg_time;\n    float msg_x;\n    float msg_z;\n};\n\nstruct routing_table_t {\n    int dimension;\n    list list_table;\n};\n\nstruct router_t {\n    int router_id;\n    struct routing_table_t routing_table;\n    pthread_mutex_t router_mutex;\n};\n\nstruct parametri_accepter_t {\n    int accepter_agents_number;\n    char *accepter_address;\n    int accepter_port;\n    list accepter_lista_buffer;\n    int accepter_in_out;\n};\n\nstruct parametri_dispatcher_t {\n    buffer dispatcher_buffer_in;\n    list dispatcher_lista_buffer_out;\n};\n\nstruct parametri_receiver_t {\n    int receiver_id;\n    int receiver_socket;\n    buffer receiver_buffer;\n};\n\nstruct parametri_sender_t {\n    int sender_id;\n    int sender_socket;\n    buffer sender_buffer;\n};\n\ntypedef struct msg_t *msg;\n\ntypedef struct parametri_accepter_t *parametri_accepter;\ntypedef struct parametri_dispatcher_t *parametri_dispatcher;\ntypedef struct parametri_receiver_t *parametri_receiver;\ntypedef struct parametri_sender_t *parametri_sender;\n\nstatic pthread_mutex_t router_class_mutex;\nstatic int routerObjectsNumber = 0;\n\nstatic int numero_receiver_vivi = 0;\nstatic int numero_dispatcher_vivi = 0;\nstatic int numero_sender_vivi = 0;\n\nstatic void initClassRouter() {\n    pthread_mutex_init(&(router_class_mutex), NULL);\n}\n\nstatic void cleanClassRouter() {\n    pthread_mutex_destroy(&(router_class_mutex));\n\n}\n\nrouter allocRouter() {\n\n    router router_M_;\n\n    if (routerObjectsNumber == 0) initClassRouter();\n\n    routerObjectsNumber++;\n\n    router_M_ = (router) malloc(sizeof (struct router_t));\n\n    pthread_mutex_init(&(router_M_->router_mutex), NULL);\n\n    return router_M_;\n\n}\n\nvoid freeRouter(router _F_router) {\n\n    pthread_mutex_destroy(&(_F_router->router_mutex));\n\n    free(_F_router);\n\n    _F_router = NULL;\n\n    routerObjectsNumber--;\n\n    if (routerObjectsNumber == 0) cleanClassRouter();\n}\n\nstatic int listenFrom(char * _ip_address_local, int _ip_port_local) {\n\n    int socket_M_;\n\n    struct sockaddr_in sockaddr_in_local_;\n\n    memset(&sockaddr_in_local_, 0, sizeof (sockaddr_in_local_));\n    sockaddr_in_local_.sin_family = AF_INET;\n    sockaddr_in_local_.sin_port = htons(_ip_port_local);\n    inet_aton(_ip_address_local, &(sockaddr_in_local_.sin_addr));\n\n    if ((socket_M_ = socket(AF_INET, SOCK_STREAM, 0)) == -1) {\n        perror(\"listenFrom: socket() Error\\n\");\n        exit(1);\n    }\n\n    if (bind(socket_M_, (struct sockaddr *) & sockaddr_in_local_, sizeof (struct sockaddr_in)) == -1) {\n        perror(\"listenFrom: bind() Error\\n\");\n        exit(1);\n    }\n\n    if (listen(socket_M_, 1) == -1) {\n        perror(\"listenFrom: listen() Error\\n\");\n        exit(1);\n    }\n\n    return socket_M_;\n\n}\n\nstatic void sendMsg(int _socket, msg _msg) {\n\n    if (send(_socket, _msg, sizeof (struct msg_t), 0) == -1) {\n        perror(\"sendMsg: send() Error\\n\");\n        exit(1);\n    };\n    /*\n        int net_id;\n        int net_x;\n        int net_z;\n\n        net_id = htonl(_msg->msg_id);\n        if (send(_socket, &net_id, sizeof (net_id), 0) == -1) {\n            perror(\"sendMsg: send() Error\\n\");\n            exit(1);\n        };\n\n        net_x = htonl(_msg->msg_x);\n        if (send(_socket, &net_x, sizeof (net_x), 0) == -1) {\n            perror(\"sendMsg: send() Error\\n\");\n            exit(1);\n        };\n\n        net_z = htonl(_msg->msg_z);\n        if (send(_socket, &net_z, sizeof (net_z), 0) == -1) {\n            perror(\"sendMsg: send() Error\\n\");\n            exit(1);\n        };\n     */\n}\n\nstatic msg recvMsg(int _socket) {\n\n    msg _M_msg = (struct msg_t *) malloc(sizeof (struct msg_t));\n\n    if (recv(_socket, _M_msg, sizeof (struct msg_t), 0) == -1) {\n        perror(\"recvMsg: recv() Error\\n\");\n        exit(1);\n    }\n    /*\n        int net_id;\n        int net_x;\n        int net_z;\n\n        msg _M_msg = (struct msg_t *) malloc(sizeof (struct msg_t));\n\n        if (recv(_socket, &net_id, sizeof (net_id), 0) == -1) {\n            perror(\"recvMsg: recv() Error\\n\");\n            exit(1);\n        }\n        _M_msg->msg_id = ntohl(net_id);\n\n        if (recv(_socket, &net_x, sizeof (net_x), 0) == -1) {\n            perror(\"recvMsg: recv() Error\\n\");\n            exit(1);\n        }\n        _M_msg->msg_x = ntohl(net_x);\n\n        if (recv(_socket, &net_z, sizeof (net_z), 0) == -1) {\n            perror(\"recvMsg: recv() Error\\n\");\n            exit(1);\n        }\n        _M_msg->msg_z = ntohl(net_z);\n     */\n    return _M_msg;\n}\n\nstatic parametri_receiver allocParamReceiver(int _receiver_socket, buffer _receiver_buffer) {\n\n    parametri_receiver _M_parametri_receiver = (parametri_receiver) malloc(sizeof (struct parametri_receiver_t));\n\n    _M_parametri_receiver->receiver_socket = _receiver_socket;\n    _M_parametri_receiver->receiver_buffer = _receiver_buffer;\n\n    return _M_parametri_receiver;\n}\n\n/*\n * Quando il Receiver riceve dall'agent un messaggio con id = POISON_ID allora:\n * - lo inoltra nel buffer\n * - chiude la connessione con l'agent\n * - fa il fflush del file di log e lo chiude\n * - decrementa numero_receiver_vivi\n * - termina\n */\n\nstatic void *runReceiver(void *_parametri_receiver) {\n\n    parametri_receiver _parametri = (parametri_receiver) _parametri_receiver;\n\n    int _receiver_socket = _parametri->receiver_socket;\n    buffer _receiver_buffer = _parametri->receiver_buffer;\n\n    msg _msg;\n    int _receiver_id;\n\n    FILE *receiver_log;\n\n    char receiver_log_file_name[FILENAME_MAX];\n\n    /*\n     * Riceve il messaggio di presentazione dall'agent\n     * - imposta l'id del receiver\n     * - imposta l'id del _receiver_buffer\n     * - reinvia all'agent il messaggio ricevuto\n     */\n\n    _msg = recvMsg(_receiver_socket);\n    _receiver_id = _msg->msg_id;\n    setBufferID(_receiver_buffer, _receiver_id);\n\n    /* \n     * Apre il file di log\n     */\n\n    sprintf(receiver_log_file_name, \"receiver_%d.log\", _receiver_id);\n\n    receiver_log = fopen(receiver_log_file_name, \"w\");\n\n    if (receiver_log == NULL) {\n        perror(\"Errore apertura file: \\\"receiver.log\\\"\\n\");\n        exit(1);\n    };\n\n    setbuf(receiver_log, NULL);\n\n    fprintf(receiver_log, \"R%d: Open log\\n\", _receiver_id);\n\n    /*sleep(1);*/\n\n    fprintf(receiver_log, \"R%d: Parametri invocazione:\\n\", _receiver_id);\n\n    fprintf(receiver_log, \"R%d: Wait: rcv\\n\", _receiver_id);\n\n    fprintf(receiver_log, \"R%d: > (%d,%d,%f,%f)\\n\", _receiver_id, _msg->msg_id, _msg->msg_time, _msg->msg_x, _msg->msg_z);\n\n    fprintf(receiver_log, \"R%d: Wait: rcv\\n\", _receiver_id);\n\n    /* \n     * Riceve un messaggio e lo pone nel buffer finch\u00e8 non riceve il POISON_ID\n     */\n\n    _msg = recvMsg(_receiver_socket);\n\n    fprintf(receiver_log, \"R%d: > (%d,%d,%f,%f)\\n\", _receiver_id, _msg->msg_id, _msg->msg_time, _msg->msg_x, _msg->msg_z);\n\n    fprintf(receiver_log, \"R%d: Loop:\\n\", _receiver_id);\n\n    fprintf(receiver_log, \"R%d: > while(msg != POISON_ID)\\n\", _receiver_id);\n\n    fprintf(receiver_log, \"R%d: --- Loop Start ---\\n\", _receiver_id);\n\n    while (_msg->msg_id != POISON_ID) {\n\n        putInBuffer_blocking(_receiver_buffer, _msg);\n\n        fprintf(receiver_log, \"R%d: >>> putInBuffer(%d,%d,%f,%f)\\n\", _receiver_id, _msg->msg_id, _msg->msg_time, _msg->msg_x, _msg->msg_z);\n\n        fprintf(receiver_log, \"R%d: >>> Wait: rcv\\n\", _receiver_id);\n\n        _msg = recvMsg(_receiver_socket);\n    };\n\n    fprintf(receiver_log, \"R%d: ---- Loop End ----\\n\", _receiver_id);\n\n    fprintf(receiver_log, \"R%d: Signal:\\n\", _receiver_id);\n\n    putInBuffer_blocking(_receiver_buffer, _msg);\n\n    fprintf(receiver_log, \"R%d: > putInBuffer(%d,%d,%f,%f) \\n\", _receiver_id, _msg->msg_id, _msg->msg_time, _msg->msg_x, _msg->msg_z);\n\n    fprintf(receiver_log, \"R%d: Socket:\\n\", _receiver_id);\n\n    /* \n     * Chiude la connessione con l'agent\n     */\n\n    send(_receiver_socket, \"\", 1, 0);\n\n    close(_receiver_socket);\n\n    fprintf(receiver_log, \"R%d: > close receiver socket\\n\", _receiver_id);\n\n    fprintf(receiver_log, \"R%d: Memoria\\n\", _receiver_id);\n\n    free(_parametri_receiver);\n\n    fprintf(receiver_log, \"R%d: > parametri\\n\", _receiver_id);\n\n    /*\n     * fflush e chiusura del logfile\n     */\n\n    fprintf(receiver_log, \"R%d: Close log\\n\", _receiver_id);\n\n    fflush(receiver_log);\n\n    fclose(receiver_log);\n\n    /* Decrementa numero_receiver_vivi e termina*/\n\n    numero_receiver_vivi--;\n\n    return NULL;\n}\n\nstatic parametri_sender allocParamSender(int _sender_socket, buffer _sender_buffer) {\n\n    parametri_sender _M_parametri_sender = (parametri_sender) malloc(sizeof (struct parametri_sender_t));\n\n    _M_parametri_sender->sender_socket = _sender_socket;\n    _M_parametri_sender->sender_buffer = _sender_buffer;\n\n    return _M_parametri_sender;\n}\n\n/*\n * Quando il Sender prende dal buffer un messaggio con id = POISON_ID\n * vuol dire che quello \u00e8 l'ultimo messaggio e il buffer non ne contiene altri:\n * - attende che i dispatcher siano morti\n * - elimina il sender buffer associato\n * - chiude la connessione con l'agent\n * - fa il fflush del file di log e lo chiude\n * - decrementa numero_sender_buffer\n * - termina\n */\n\nstatic void *runSender(void *_parametri_sender) {\n\n    parametri_sender _parametri = (parametri_sender) _parametri_sender;\n\n    int _sender_socket = _parametri->sender_socket;\n    buffer _sender_buffer = _parametri->sender_buffer;\n\n    int _sender_id;\n\n    msg _msg;\n\n    FILE *sender_log;\n\n    char sender_log_file_name[FILENAME_MAX];\n\n    /*\n     * Riceve il messaggio di presentazione dall'agent:\n     * - imposta l'id del sender\n     * - imposta l'id del _sender_buffer\n     * - reinvia all'agent il messaggio ricevuto\n     */\n\n    _msg = recvMsg(_sender_socket);\n    _sender_id = _msg->msg_id;\n    setBufferID(_sender_buffer, _sender_id);\n\n    /* \n     * Apre il file di log\n     */\n\n    sprintf(sender_log_file_name, \"sender_%d.log\", _sender_id);\n\n    sender_log = fopen(sender_log_file_name, \"w\");\n\n    if (sender_log == NULL) {\n        perror(\"Errore apertura file: \\\"sender.log\\\"\\n\");\n        exit(1);\n    };\n\n    setbuf(sender_log, NULL);\n\n    fprintf(sender_log, \"S%d: Open log\\n\", _sender_id);\n\n    /*sleep(1);*/\n\n    fprintf(sender_log, \"S%d: Parametri di invocazione:\\n\", _sender_id);\n\n    fprintf(sender_log, \"S%d: Wait: rcv\\n\", _sender_id);\n\n    fprintf(sender_log, \"S%d: > (%d,%d,%f,%f)\\n\", _sender_id, _msg->msg_id, _msg->msg_time, _msg->msg_x, _msg->msg_z);\n\n    fprintf(sender_log, \"S%d: Wait: getFromBuffer\\n\", _sender_id);\n\n    /* \n     * Riceve un messaggio e lo pone nel buffer finch\u00e8 non riceve il POISON_ID\n     */\n\n    _msg = getFromBuffer_blocking(_sender_buffer);\n\n    fprintf(sender_log, \"S%d: > (%d,%d,%f,%f)\\n\", _sender_id, _msg->msg_id, _msg->msg_time, _msg->msg_x, _msg->msg_z);\n\n    fprintf(sender_log, \"S%d: Loop:\\n\", _sender_id);\n\n    fprintf(sender_log, \"S%d: > while(msg != POISON_ID)\\n\", _sender_id);\n\n    fprintf(sender_log, \"S%d: --- Loop Start ---\\n\", _sender_id);\n\n    while (_msg->msg_id != POISON_ID) {\n\n        sendMsg(_sender_socket, _msg);\n\n        fprintf(sender_log, \"S%d: >>> snd (%d,%d,%f,%f)\\n\", _sender_id, _msg->msg_id, _msg->msg_time, _msg->msg_x, _msg->msg_z);\n\n        fprintf(sender_log, \"S%d: >>> Wait: getFromBuffer\\n\", _sender_id);\n\n        _msg = getFromBuffer_blocking(_sender_buffer);\n    };\n\n    fprintf(sender_log, \"S%d: ---- Loop End ----\\n\", _sender_id);\n\n    fprintf(sender_log, \"S%d: Wait:\\n\", _sender_id);\n\n    /* \n     * Attende che tutti i dispatcher siano morti\n     */\n\n    fprintf(sender_log, \"S%d: > while(dispatcher > 0)\\n\", _sender_id);\n\n    while (numero_dispatcher_vivi > 0);\n\n    fprintf(sender_log, \"S%d: Socket:\\n\", _sender_id);\n\n    /*\n     * Chiude la connessione con l'agent\n     */\n\n    send(_sender_socket, \"\", 1, 0);\n\n    close(_sender_socket);\n\n    fprintf(sender_log, \"S%d: > close sender socket\\n\", _sender_id);\n\n    fprintf(sender_log, \"S%d: Memoria:\\n\", _sender_id);\n\n    /* \n     * Elimina il receiver buffer associato\n     */\n\n    freeBuffer(_sender_buffer);\n\n    fprintf(sender_log, \"S%d: > free(sender_buffer)\\n\", _sender_id);\n\n    free(_parametri_sender);\n\n    fprintf(sender_log, \"S%d: > parametri\\n\", _sender_id);\n\n    /*\n     * fflush e chiusura del logfile\n     */\n\n    fprintf(sender_log, \"S%d: Close log\\n\", _sender_id);\n\n    fflush(sender_log);\n\n    fclose(sender_log);\n\n    /* Decrementa numero_sender_vivi e termina*/\n\n    numero_sender_vivi--;\n\n    return NULL;\n}\n\nstatic parametri_accepter allocParamAccepter(int _accepter_agents_number, char *_accepter_address, int _accepter_port, list _accepter_lista_buffer, int _accepter_in_out) {\n\n    parametri_accepter _M_parametri_accepter = (parametri_accepter) malloc(sizeof (struct parametri_accepter_t));\n\n    _M_parametri_accepter->accepter_agents_number = _accepter_agents_number;\n    _M_parametri_accepter->accepter_address = _accepter_address;\n    _M_parametri_accepter->accepter_port = _accepter_port;\n    _M_parametri_accepter->accepter_lista_buffer = _accepter_lista_buffer;\n    _M_parametri_accepter->accepter_in_out = _accepter_in_out;\n\n    return _M_parametri_accepter;\n\n}\n\n/*\n * Quando l'accepter riceve _accepter_agents_number connessioni in input e in output\n * vuol dire che tutti gli agents si sono collegati:\n * - chiude le due porte in listening\n * - fa il fflush del file di log e lo chiude\n * - termina\n */\n\nstatic void *runAccepter(void *_parametri_accepter) {\n\n    parametri_accepter _parametri = (parametri_accepter) _parametri_accepter;\n\n    int _accepter_agents_number;\n    char *_accepter_address;\n    int _accepter_port;\n    list _accepter_lista_buffer;\n    int _accepter_in_out;\n\n    int listening_socket;\n    int communication_socket;\n\n    FILE *accepter_log;\n\n    char *accepter_log_file_name;\n    char *in_out;\n    char *accepter_error;\n\n    /* Apre il file di log */\n\n    _accepter_in_out = _parametri->accepter_in_out;\n\n    if (_accepter_in_out == 0) {\n        accepter_log_file_name = \"accepter_in.log\";\n        accepter_error = \"Errore apertura file: \\\"accepter_in.log\\\"\\n\";\n        in_out = \"AI\";\n    } else {\n        accepter_log_file_name = \"accepter_out.log\";\n        accepter_error = \"Errore apertura file: \\\"accepter_out.log\\\"\\n\";\n        in_out = \"AO\";\n    };\n\n    accepter_log = fopen(accepter_log_file_name, \"w\");\n\n    if (accepter_log == NULL) {\n        perror(accepter_error);\n        exit(1);\n    };\n\n    setbuf(accepter_log, NULL);\n\n    fprintf(accepter_log, \"%s: Open log\\n\", in_out);\n\n    fprintf(accepter_log, \"%s: Parametri di invocazione:\\n\", in_out);\n\n    _accepter_agents_number = _parametri->accepter_agents_number;\n\n    fprintf(accepter_log, \"%s: > %d\\n\", in_out, _accepter_agents_number);\n\n    _accepter_address = _parametri->accepter_address;\n\n    fprintf(accepter_log, \"%s: > %s\\n\", in_out, _accepter_address);\n\n    _accepter_port = _parametri->accepter_port;\n\n    fprintf(accepter_log, \"%s: > %d\\n\", in_out, _accepter_port);\n\n    _accepter_lista_buffer = _parametri->accepter_lista_buffer;\n\n    fprintf(accepter_log, \"%s: > %d\\n\", in_out, _accepter_in_out);\n\n    fprintf(accepter_log, \"%s: Socket:\\n\", in_out);\n\n    fprintf(accepter_log, \"%s: > listenFrom(%s,%d)\\n\", in_out, _accepter_address, _accepter_port);\n\n    listening_socket = listenFrom(_accepter_address, _accepter_port);\n\n    if (_accepter_in_out == 0) {\n\n        fprintf(accepter_log, \"%s: Loop:\\n\", in_out);\n\n        fprintf(accepter_log, \"%s: > while(receiver < agents)\\n\", in_out);\n\n        fprintf(accepter_log, \"%s: ---------- Loop Start ----------\\n\", in_out);\n\n        while (numero_receiver_vivi < _accepter_agents_number) {\n\n            buffer _M_buffer = allocBuffer(DIM_BUFFER);\n\n            pthread_t receiver_;\n\n            if ((communication_socket = accept(listening_socket, NULL, NULL)) == -1) {\n                perror(\"Accepter accept() Error\\n\");\n                exit(1);\n            }\n\n            fprintf(accepter_log, \"%s: >>> accept connection\\n\", in_out);\n\n            addElementToList(_accepter_lista_buffer, _M_buffer);\n\n            numero_receiver_vivi++;\n\n            pthread_create(&receiver_, NULL, &runReceiver, allocParamReceiver(communication_socket, _M_buffer));\n        }\n        fprintf(accepter_log, \"%s: ----------- Loop End -----------\\n\", in_out);\n\n\n    } else {\n\n        fprintf(accepter_log, \"%s: Loop:\\n\", in_out);\n\n        fprintf(accepter_log, \"%s: > while(sender < agents)\\n\", in_out);\n\n        fprintf(accepter_log, \"%s: --------- Loop Start ---------\\n\", in_out);\n\n        while (numero_sender_vivi < _accepter_agents_number) {\n\n            buffer _M_buffer = allocBuffer(DIM_BUFFER);\n\n            pthread_t sender_;\n\n            if ((communication_socket = accept(listening_socket, NULL, NULL)) == -1) {\n                perror(\"Accepter accept() Error\\n\");\n                exit(1);\n            }\n\n            fprintf(accepter_log, \"%s: >>> accept connection\\n\", in_out);\n\n            addElementToList(_accepter_lista_buffer, _M_buffer);\n\n            numero_sender_vivi++;\n\n            pthread_create(&sender_, NULL, &runSender, allocParamSender(communication_socket, _M_buffer));\n        }\n\n        fprintf(accepter_log, \"%s: ---------- Loop End ----------\\n\", in_out);\n\n    }\n\n    fprintf(accepter_log, \"%s: Socket:\\n\", in_out);\n\n    /* \n     * Chiude le due porte in listening\n     */\n\n    close(listening_socket);\n\n    fprintf(accepter_log, \"%s: > close listen socket\\n\", in_out);\n\n    fprintf(accepter_log, \"%s: Memoria:\\n\", in_out);\n\n    free(_parametri_accepter);\n\n    fprintf(accepter_log, \"%s: > parametri\\n\", in_out);\n\n    /*\n     * fflush e chiusura del logfile\n     */\n\n    fprintf(accepter_log, \"%s: Close log\\n\", in_out);\n\n    fflush(accepter_log);\n\n    fclose(accepter_log);\n\n    return NULL;\n\n}\n\nstatic parametri_dispatcher allocParamDispatcher(buffer _dispatcher_buffer_in, list _dispatcher_lista_buffer_out) {\n\n    parametri_dispatcher _M_parametri_dispatcher = (parametri_dispatcher) malloc(sizeof (struct parametri_dispatcher_t));\n\n    _M_parametri_dispatcher->dispatcher_buffer_in = _dispatcher_buffer_in;\n    _M_parametri_dispatcher->dispatcher_lista_buffer_out = _dispatcher_lista_buffer_out;\n\n    return _M_parametri_dispatcher;\n\n}\n\n/*\n * Quando il dispatcher riceve il POISON_ID allora:\n * - lo inoltra nel sender buffer associato e solo in quello\n * - attende che tutti i receiver siano morti\n * - elimina il receiver buffer associato\n * - fa il fflush del file di log e lo chiude\n * - decrementa numero_dispatcher_vivi\n * - termina\n */\n\nstatic void *runDispatcher(void *_parametri_dispatcher) {\n\n    parametri_dispatcher _parametri = (parametri_dispatcher) _parametri_dispatcher;\n\n    buffer _dispatcher_buffer_in = _parametri->dispatcher_buffer_in;\n    list _dispatcher_lista_buffer_out;\n\n    int _dispatcher_id;\n    int _sender_buffer_id;\n\n    list_iterator it_out;\n    buffer _sender_buffer;\n\n    msg _msg;\n\n    gsl_matrix *_dispatcher_adjacency_matrix;\n\n    FILE *dispatcher_adjacency_matrix_file;\n\n    FILE *dispatcher_log;\n\n    char dispatcher_log_file_name[FILENAME_MAX];\n\n    _dispatcher_adjacency_matrix = gsl_matrix_alloc(6, 6);\n    dispatcher_adjacency_matrix_file = fopen(\"adjacency_matrix.txt\", \"r\");\n    gsl_matrix_fscanf(dispatcher_adjacency_matrix_file, _dispatcher_adjacency_matrix);\n    fclose(dispatcher_adjacency_matrix_file);\n\n    /*\n    gsl_matrix_fprintf(stdout, adjacency_matrix, \"%f\");\n    printf(\"valore 0,0 = %f\\n\",gsl_matrix_get(adjacency_matrix,0,0));\n    printf(\"valore 1,0 = %f\\n\",gsl_matrix_get(adjacency_matrix,1,0));\n    printf(\"valore 0,1 = %f\\n\",gsl_matrix_get(adjacency_matrix,0,1));\n    printf(\"valore 1,1 = %f\\n\",gsl_matrix_get(adjacency_matrix,1,1));\n     */\n\n    /* Apre il file di log impostando il suo id a quello del buffer associato */\n\n    _dispatcher_id = getBufferID(_dispatcher_buffer_in);\n\n    sprintf(dispatcher_log_file_name, \"dispatcher_%d.log\", _dispatcher_id);\n\n    dispatcher_log = fopen(dispatcher_log_file_name, \"w\");\n\n    if (dispatcher_log == NULL) {\n        perror(\"Errore apertura file: \\\"dispatcher.log\\\"\\n\");\n        exit(1);\n    };\n\n    setbuf(dispatcher_log, NULL);\n\n    fprintf(dispatcher_log, \"D%d: Open log\\n\", _dispatcher_id);\n\n    /*sleep(1);*/\n\n    fprintf(dispatcher_log, \"D%d: Parametri di invocazione:\\n\", _dispatcher_id);\n\n    _dispatcher_lista_buffer_out = _parametri->dispatcher_lista_buffer_out;\n\n    fprintf(dispatcher_log, \"D%d: Wait:\\n\", _dispatcher_id);\n\n    fprintf(dispatcher_log, \"D%d: > getFromBuffer(receiver_buffer)\\n\", _dispatcher_id);\n\n    /*\n     * Riceve un messaggio e lo pone in tutti i sender buffer finch\u00e8 non riceve il POISON_ID\n     */\n\n    _msg = getFromBuffer_blocking(_dispatcher_buffer_in);\n\n    fprintf(dispatcher_log, \"D%d: ----------- Loop Start -----------\\n\", _dispatcher_id);\n\n    while (_msg->msg_id != POISON_ID) {\n\n        it_out = allocListIterator(_dispatcher_lista_buffer_out);\n\n        while (hasNextList(it_out) == 1) {\n\n            int i;\n\n            _sender_buffer = nextElementFromList(it_out);\n\n            _sender_buffer_id = getBufferID(_sender_buffer);\n\n            i = gsl_matrix_get(_dispatcher_adjacency_matrix, _sender_buffer_id - 1, _dispatcher_id - 1);\n\n            /* i = 1;*/\n\n            /* fprintf(dispatcher_log, \"sender %d receiver %d matrix_get %d\\n\", _sender_buffer_id, _dispatcher_id, i); */\n\n            if (i == 1) {\n\n                putInBuffer_blocking(_sender_buffer, _msg);\n\n                fprintf(dispatcher_log, \"D%d: > (%d,%d,%f,%f) > %d\\n\", _dispatcher_id, _msg->msg_id, _msg->msg_time, _msg->msg_x, _msg->msg_z, _sender_buffer_id);\n            }\n        }\n\n        freeListIterator(it_out);\n\n        fprintf(dispatcher_log, \"D%d: ----------------------------------\\n\", _dispatcher_id);\n\n        _msg = getFromBuffer_blocking(_dispatcher_buffer_in);\n    }\n\n    fprintf(dispatcher_log, \"D%d: ------------ Loop End ------------\\n\", _dispatcher_id);\n\n    /* \n     * Inoltra nel sender buffer associato e solo in quello il POISON_ID\n     */\n\n    it_out = allocListIterator(_dispatcher_lista_buffer_out);\n\n    _sender_buffer = nextElementFromList(it_out);\n\n    _sender_buffer_id = getBufferID(_sender_buffer);\n\n    while (_sender_buffer_id != _dispatcher_id) {\n\n        _sender_buffer = nextElementFromList(it_out);\n\n        _sender_buffer_id = getBufferID(_sender_buffer);\n    }\n\n    putInBuffer_blocking(_sender_buffer, _msg);\n\n    fprintf(dispatcher_log, \"D%d: Signal:\\n\", _dispatcher_id);\n\n    fprintf(dispatcher_log, \"D%d: > snd (%d,%d,%f,%f) > %d\\n\", _dispatcher_id, _msg->msg_id, _msg->msg_time, _msg->msg_x, _msg->msg_z, _sender_buffer_id);\n\n    fprintf(dispatcher_log, \"D%d: Wait:\\n\", _dispatcher_id);\n\n    fprintf(dispatcher_log, \"D%d: > numero_receiver_vivi > 0\\n\", _dispatcher_id);\n\n\n    /* \n     * Attende che tutti i receiver siano morti\n     */\n\n    while (numero_receiver_vivi > 0);\n\n    fprintf(dispatcher_log, \"D%d: Memoria:\\n\", _dispatcher_id);\n\n    /* \n     * free delle variabili usate\n     */\n\n    freeBuffer(_dispatcher_buffer_in);\n\n    fprintf(dispatcher_log, \"D%d: > free(receiver_buffer)\\n\", _dispatcher_id);\n\n    free(_parametri_dispatcher);\n\n    fprintf(dispatcher_log, \"D%d: > parametri\\n\", _dispatcher_id);\n\n    /* \n     * Fa il fflush del file di log e lo chiude\n     */\n\n    fprintf(dispatcher_log, \"D%d: Close log\\n\", _dispatcher_id);\n\n    fflush(dispatcher_log);\n\n    fclose(dispatcher_log);\n\n    /* \n     * Decrementa numero_dispatcher_vivi e termina\n     */\n\n    numero_dispatcher_vivi--;\n\n    return NULL;\n\n}\n\nparametri_router allocParamRouter(char *_router_ip_to_listen, int _port_client_to_router, int _port_router_to_client) {\n\n    parametri_router _M_parametri_router = (struct parametri_router_t *) malloc(sizeof (struct parametri_router_t));\n\n    _M_parametri_router->router_ip_to_listen = _router_ip_to_listen;\n    _M_parametri_router->port_router_to_client = _port_router_to_client;\n    _M_parametri_router->port_client_to_router = _port_client_to_router;\n\n    return _M_parametri_router;\n}\n\nvoid *runRouter(void *_parametri_router) {\n\n    parametri_router _parametri = (parametri_router) _parametri_router;\n\n    char *_router_ip_to_listen;\n    int _port_client_to_router;\n    int _port_router_to_client;\n\n    int _router_agents_number;\n\n    list lista_buffer_in_M_;\n    list_iterator it_in;\n    buffer _buffer_in;\n\n    list lista_buffer_out_M_;\n\n    pthread_t dispatcher_T_;\n    pthread_t accepter_in_T_;\n    pthread_t accepter_out_T_;\n\n    FILE *router_log;\n\n    /* \n     * Apre il file di log\n     */\n\n    router_log = fopen(\"router.log\", \"w\");\n\n    if (router_log == NULL) {\n        perror(\"Errore apertura file: \\\"router.log\\\"\\n\");\n        exit(1);\n    };\n\n    setbuf(router_log, NULL);\n\n    fprintf(router_log, \": Open log\\n\");\n\n    fprintf(router_log, \": Parametri di invocazione:\\n\");\n\n    _router_ip_to_listen = _parametri->router_ip_to_listen;\n\n    fprintf(router_log, \": > _router_ip_to_listen = %s\\n\", _router_ip_to_listen);\n\n    _port_client_to_router = _parametri->port_client_to_router;\n\n    fprintf(router_log, \": > _port_client_to_router = %d\\n\", _port_client_to_router);\n\n    _port_router_to_client = _parametri->port_router_to_client;\n\n    fprintf(router_log, \": > _port_router_to_client = %d\\n\", _port_router_to_client);\n\n    fprintf(router_log, \": Memoria:\\n\");\n\n    _router_agents_number = 6;\n\n    fprintf(router_log, \": > _router_agents_number = %d\\n\", _router_agents_number);\n\n    lista_buffer_in_M_ = allocList();\n\n    fprintf(router_log, \": > alloc(lista_buffer_in)\\n\");\n\n    lista_buffer_out_M_ = allocList();\n\n    fprintf(router_log, \": > alloc(lista_buffer_out)\\n\");\n\n    /* \n     * Fa partire i due accepter (threads)\n     */\n\n    pthread_create(&accepter_in_T_, NULL, &runAccepter, allocParamAccepter(_router_agents_number, _router_ip_to_listen, _port_client_to_router, lista_buffer_in_M_, 0));\n\n    fprintf(router_log, \": Thread -< Accepter():\\n\");\n\n    fprintf(router_log, \": > _accepter_agents_number = %d\\n\", _router_agents_number);\n\n    fprintf(router_log, \": > _accepter_address = %s\\n\", _router_ip_to_listen);\n\n    fprintf(router_log, \": > _accepter_port = %d\\n\", _port_client_to_router);\n\n    fprintf(router_log, \": > _accepter_in_out = %d\\n\", 0);\n\n    pthread_create(&accepter_out_T_, NULL, &runAccepter, allocParamAccepter(_router_agents_number, _router_ip_to_listen, _port_router_to_client, lista_buffer_out_M_, 1));\n\n    fprintf(router_log, \": Thread -< Accepter():\\n\");\n\n    fprintf(router_log, \": > _accepter_agents_number = %d\\n\", _router_agents_number);\n\n    fprintf(router_log, \": > _accepter_address = %s\\n\", _router_ip_to_listen);\n\n    fprintf(router_log, \": > _accepter_port = %d\\n\", _port_router_to_client);\n\n    fprintf(router_log, \": > _accepter_in_out = %d\\n\", 1);\n\n    /* \n     * Attende che i due accepter abbiano terminato il loro compito\n     */\n\n    fprintf(router_log, \": Wait:\\n\");\n\n    fprintf(router_log, \": > pthread_join(accepter_out)\\n\");\n\n    pthread_join(accepter_out_T_, NULL);\n\n    fprintf(router_log, \": > pthread_join(accepter_in)\\n\");\n\n    pthread_join(accepter_in_T_, NULL);\n\n    fprintf(router_log, \": Loop:\\n\");\n\n    fprintf(router_log, \": > while hasNext(lista_buffer_in)\\n\");\n\n    /* \n     * Associa ad ogni receiver buffer un dispatcher\n     */\n\n    it_in = allocListIterator(lista_buffer_in_M_);\n\n    fprintf(router_log, \": ----------- Loop Start -----------\\n\");\n\n    while (hasNextList(it_in) == 1) {\n\n        _buffer_in = nextElementFromList(it_in);\n\n        numero_dispatcher_vivi++;\n\n        pthread_create(&dispatcher_T_, NULL, &runDispatcher, allocParamDispatcher(_buffer_in, lista_buffer_out_M_));\n\n        fprintf(router_log, \": >>> create dispatcher thread\\n\");\n    }\n\n    freeListIterator(it_in);\n\n    fprintf(router_log, \": ------------ Loop End ------------\\n\");\n\n    /* Attende che tutti i sender thread creati siano morti, infatti loro sono gli ultimi a morire */\n\n    fprintf(router_log, \": Wait:\\n\");\n\n    fprintf(router_log, \": > numero_sender_vivi > 0\\n\");\n\n    while (numero_sender_vivi > 0);\n\n    fprintf(router_log, \": Memoria:\\n\");\n\n    /*\n     * free delle variabili usate\n     */\n\n    freeList(lista_buffer_in_M_);\n    lista_buffer_in_M_ = NULL;\n\n    fprintf(router_log, \": > free(lista_buffer_in)\\n\");\n\n    freeList(lista_buffer_out_M_);\n    lista_buffer_out_M_ = NULL;\n\n    fprintf(router_log, \": > free(lista_buffer_out)\\n\");\n\n    free(_parametri_router);\n\n    fprintf(router_log, \": > parametri\\n\");\n\n    /*\n     * fflush e chiusura del logfile\n     */\n\n    fprintf(router_log, \": Close log\\n\");\n\n    fflush(router_log);\n\n    fclose(router_log);\n\n    return NULL;\n}\n\n", "meta": {"hexsha": "beee8a9feccabd910636c1c17bc75e1966d68c2e", "size": 28724, "ext": "c", "lang": "C", "max_stars_repo_path": "router.c", "max_stars_repo_name": "vittorioc/VirtualAgent", "max_stars_repo_head_hexsha": "0455a86a79ef2c5a817b9a1ec26d9025703d22ab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-01-29T01:05:11.000Z", "max_stars_repo_stars_event_max_datetime": "2017-01-29T01:05:11.000Z", "max_issues_repo_path": "router.c", "max_issues_repo_name": "vittorioc/VirtualAgent", "max_issues_repo_head_hexsha": "0455a86a79ef2c5a817b9a1ec26d9025703d22ab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "router.c", "max_forks_repo_name": "vittorioc/VirtualAgent", "max_forks_repo_head_hexsha": "0455a86a79ef2c5a817b9a1ec26d9025703d22ab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8951310861, "max_line_length": 171, "alphanum_fraction": 0.6648795432, "num_tokens": 7591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18010668168989225, "lm_q2_score": 0.016914914629562842, "lm_q1q2_score": 0.0030464891449983765}}
{"text": "#include \"solver_intern.h\"\n#include <pygsl/general_helpers.h>\n#include <pygsl/block_helpers.h>\n#if 0\n#include <pygsl/function_helpers.h>\n#endif\n#include <setjmp.h>\n#include <gsl/gsl_math.h>\n#include <pygsl/error_helpers.h>\n#include <strings.h>\n#include \"solver_doc.ic\"\n\n\nPyObject * module = NULL;\nconst char *filename = __FILE__;\n\n\nstatic int\nPyGSL_solver_set_called(PyGSL_solver *self)\n{\n     FUNC_MESS_BEGIN();\n     if(self->set_called == 1)\n\t  return GSL_SUCCESS;\n     DEBUG_MESS(2, \"self->set_called was %d\", self->set_called);\n     pygsl_error(\"The set() method must be called before using the other methods!\",\n\t       filename, __LINE__, GSL_EINVAL);\n     FUNC_MESS_END();\n     return GSL_EINVAL;\n}\n\nstatic PyObject* \nPyGSL_solver_restart(PyGSL_solver *self, PyObject *args) \n{\n     FUNC_MESS_BEGIN();\n     if (PyGSL_SOLVER_SET_CALLED(self) != GSL_SUCCESS)\n\t  return NULL;\n\n     if(self->mstatic->cmethods.restart == NULL)\n\t  PyGSL_ERROR_NULL(\"Can not restart a solver of this type!\", GSL_ESANITY);\n     self->mstatic->cmethods.restart(self->solver);\n     Py_INCREF(Py_None);\n     FUNC_MESS_END();\n     return Py_None;\n}\n\nstatic PyObject* \nPyGSL_solver_name(PyGSL_solver *self, PyObject *args) \n{\n     PyObject * tmp;\n     const char * ctmp;\n     FUNC_MESS_BEGIN();\n     if(self->mstatic->cmethods.name == NULL)\n\t  PyGSL_ERROR_NULL(\"Can not restart a solver of this type!\", GSL_ESANITY);\n     ctmp = self->mstatic->cmethods.name(self->solver);\n     tmp =  PyString_FromString(ctmp);\n     FUNC_MESS_END();\n     return tmp;\n}\n\nstatic PyObject* \nPyGSL_solver_iterate(PyGSL_solver *self, PyObject *args) \n{\n     int tmp;\n     FUNC_MESS_BEGIN();\n     if (PyGSL_SOLVER_SET_CALLED(self) != GSL_SUCCESS)\n\t  return NULL;\n\n     if(self->mstatic->cmethods.iterate == NULL)\n\t  PyGSL_ERROR_NULL(\"Can not restart a solver of this type!\", GSL_ESANITY);\n\n     assert(self->mstatic->cmethods.iterate);\n     assert(self->solver);\n     tmp = (self->mstatic->cmethods.iterate(self->solver));\n     if(PyGSL_ERROR_FLAG(tmp) != GSL_SUCCESS)\n\t  return NULL;\n\n     return PyInt_FromLong((long) tmp);\n}\n\n\nstatic void\nPyGSL_solver_dealloc(PyGSL_solver * self)\n{\n     /* struct pygsl_array_cache * cache_ptr; \n     int i, count;\n     PyObject * ob;\n     PyArrayObject *tmp;\n     */\n     FUNC_MESS_BEGIN();\n     assert(self);\n     assert(self->mstatic);\n\n     if(self->mstatic->cmethods.free == NULL){\n\t  DEBUG_MESS(3, \"Could not free solver @ %p. No free method specified!\", self->solver);\n     }else{\n\t  DEBUG_MESS(3, \"Freeing a solver of type %s\", self->mstatic->type_name);\n\t  if(self->solver != NULL){\n\t       self->mstatic->cmethods.free(self->solver);\n\t       self->solver = NULL;\n\t  }\n     }\n\n     Py_XDECREF(self->args);     \n     self->args = NULL;\n     if(self->c_sys){\n\t  DEBUG_MESS(3, \"Freeing c_sys @ %p\", self->c_sys);\n\t  free(self->c_sys);\n\t  self->c_sys = NULL;\n     }\n\n     /*\n      * remove the cached arrays\n      */\n     if(self->cache == NULL){\n\t  DEBUG_MESS(2, \"No cache was used cache = %p\", self->cache);\n     }else{\n#if 0\n\t  cache_ptr = self->cache;\n\t  for(i = 0; i< PyGSL_SOLVER_N_ARRAYS; ++i){\n\t       tmp =  cache_ptr[i].ref;\n\t       ob = (PyObject *) tmp;\n\t       if(ob == NULL){\n\t\t    break;\n\t       }\n\t       count =  ob->ob_refcnt;\n\t       if(count == 0){\n\t\t    DEBUG_MESS(3, \"object[%d] @ %p has a zero reference count!\"\n\t\t\t       \" array should be deposed already and ptr set to zero!\", i, ob);\n\t       }else if(count == 1){\n\t\t    /* no one referencing the array; good */\t\t    \n\t\t    DEBUG_MESS(3, \"Dereferencing  object[%d] @ %p\", i, ob);\n\t\t    Py_DECREF(ob);\n\t\t    cache_ptr[i].ref = NULL;\n\t       }else if(count < 0){\n\t\t    DEBUG_MESS(2, \"I found an array (object) at %p which had \"\n\t\t\t       \"a count [%d] smaller than zero\", ob, count);\n\t\t    \n\t       }else{\n\t\t    /* count > 1 */\n\t\t    fprintf(stderr, \"In %s at %d array %d had %d refcouts.\\n\"\n\t\t\t    \"This means you reference an array which was\\n\"\n\t\t\t    \"passed to you while evaluating your callback.\\n\" \n\t\t\t    \"This produces a memory leak!\\n\", \n\t\t\t    __FILE__, __LINE__, i, count);\t\t    \n\t       \n\t       }\n\t  } /* handeled cached objects */\n\t  fprintf(stderr, \"Freed %d cached objects\\n\", i);\n\t  /* free the cache */\n\t  free(self->cache);\n\t  self->cache = NULL;\n#endif \n\n     } /* freeing cached objects */\n     PyObject_Del(self);\n     self = NULL;\n     FUNC_MESS_END();\n\n}\n\nstatic PyObject *\nPyGSL_solver_type(PyGSL_solver * self, PyObject *unused)\n{\n     assert(self->mstatic->type_name);\n     return PyString_FromString(self->mstatic->type_name);\n}\n\nstatic PyMethodDef solver_methods[] = {\n     {\"name\",    (PyCFunction) PyGSL_solver_name,    METH_NOARGS, NULL},\n     {\"restart\", (PyCFunction) PyGSL_solver_restart, METH_NOARGS, NULL},\n     {\"iterate\", (PyCFunction) PyGSL_solver_iterate, METH_NOARGS, NULL},\n     {\"type\",    (PyCFunction) PyGSL_solver_type,    METH_NOARGS, NULL},\n     {NULL, NULL, 0, NULL}\n};\nstatic PyObject *\nPyGSL_solver_getattr(PyGSL_solver * self, char * name)\n{\n     PyObject *tmp = NULL;\n     FUNC_MESS_BEGIN();\n     if(self->mstatic->pymethods)\n\t  tmp = Py_FindMethod(self->mstatic->pymethods, (PyObject *) self, name);\n     if(tmp == NULL){\n\t  PyErr_Clear();\n\t  tmp = Py_FindMethod(solver_methods, (PyObject *) self, name);\n     }\n     FUNC_MESS_END();\n     return tmp;\n}\n\nstatic PyTypeObject PyGSL_solver_pytype = {\n  PyObject_HEAD_INIT(NULL)\t /* fix up the type slot in initcrng */\n  0,\t\t\t\t /* ob_size */\n  \"PyGSL_solver\",\t\t /* tp_name */\n  sizeof(PyGSL_solver),\t /* tp_basicsize */\n  0,\t\t\t\t /* tp_itemsize */\n\n  /* standard methods */\n  (destructor)  PyGSL_solver_dealloc, /* tp_dealloc  ref-count==0  */\n  (printfunc)   0,\t\t /* tp_print    \"print x\"     */\n  (getattrfunc) PyGSL_solver_getattr,/* tp_getattr  \"x.attr\"      */\n  (setattrfunc) 0,\t\t /* tp_setattr  \"x.attr=v\"    */\n  (cmpfunc)     0,\t\t   /* tp_compare  \"x > y\"       */\n  (reprfunc)    0,                 /* tp_repr     `x`, print x  */\n\n  /* type categories */\n  0,\t\t\t\t/* tp_as_number   +,-,*,/,%,&,>>,pow...*/\n  0,\t\t\t\t/* tp_as_sequence +,[i],[i:j],len, ...*/\n  0,\t\t\t\t/* tp_as_mapping  [key], len, ...*/\n\n  /* more methods */\n  (hashfunc)     0,\t\t/* tp_hash    \"dict[x]\" */\n  (ternaryfunc)  0,      /* tp_call    \"x()\"     */\n  (reprfunc)     0,             /* tp_str     \"str(x)\"  */\n  (getattrofunc) 0,\t\t/* tp_getattro */\n  (setattrofunc) 0,\t\t/* tp_setattro */\n  0,\t\t\t\t/* tp_as_buffer */\n  0L,\t\t\t\t/* tp_flags */\n  (char *) PyGSL_solver_type_doc\t\t/* tp_doc */\n};\n\nPyGSL_solver* \n_PyGSL_solver_init(const struct _SolverStatic *mstatic) \n{\n     PyGSL_solver *solver_o=NULL;\n     int line = -1;\n     int i;\n\n     FUNC_MESS_BEGIN();     \n     if(mstatic->n_cbs > PyGSL_SOLVER_NCBS_MAX){\n\t  line = __LINE__ - 1;\n\t  pygsl_error(\"More callbacks requested than possible!\", __FILE__,\n\t\t    line, GSL_ESANITY);\n\t  goto fail;\n     }\n     solver_o =  (PyGSL_solver *) PyObject_NEW(PyGSL_solver, &PyGSL_solver_pytype);\n     if(solver_o == NULL){\n\t  line = __LINE__ -1;\n\t  goto fail;\n     }\n     \n     solver_o->args = NULL;     \n     solver_o->cache = NULL;\n     solver_o->mstatic = NULL;\n     solver_o->mstatic = mstatic;\n     solver_o->solver = NULL;\n     solver_o->c_sys = NULL;\n     solver_o->set_called = 0;\n     solver_o->isset = 0;\n\n     for(i = 0; i < PyGSL_SOLVER_NCBS_MAX; ++i){\n\t  solver_o->cbs[i] = NULL;\n     }\n\n     for(i = 0; i < PyGSL_SOLVER_PB_ND_MAX; ++i){\n\t  solver_o->problem_dimensions[i] = -1;\n     }\n\n     DEBUG_MESS(3, \"refcount = %d\", solver_o->ob_refcnt);\n     FUNC_MESS_END();\n     return solver_o;\n fail:\n     FUNC_MESS(\"Fail\");\n     PyGSL_add_traceback(module, __FILE__, __FUNCTION__, line);\n     return NULL;\n}\n\n\nstatic PyObject *\nPyGSL_solver_dn_init(PyObject *self, PyObject *args, const solver_alloc_struct * alloc, int nd)\n{\n     PyGSL_solver *solver_o=NULL;\n     int n1=1, n2=1;\n     int line = -1;\n     int flag=0;\n\n     FUNC_MESS_BEGIN();\n     assert(alloc);\n     solver_o =  _PyGSL_solver_init(alloc->mstatic);\n     if(solver_o == NULL){\n\t  line = __LINE__ - 2;\n\t  goto fail;\n     }\n     switch(nd){\n     case 0: flag = 1; break;\n     case 1: flag = PyArg_ParseTuple(args,\"i\", &n1); break;\n     case 2: flag = PyArg_ParseTuple(args,\"ii\", &n1, &n2); break;\n     case 3:\n\t  /* odeiv */\n\t  flag = 1; break;\n     default:\n\t  line = __LINE__;\n\t  pygsl_error(\"Only 1 or two for number of problem_dimensions implemented!\",\n\t\t    __FILE__, line, GSL_ESANITY);\n\t  goto fail;\n     }\n     if (0==flag){\n\t  /* Successful parsing of the arguments ?*/\n\t  line = __LINE__ - 1;\n\t  goto fail;\n     }\n     if (n1<=0) {\n\t  PyErr_SetString(PyExc_RuntimeError, \"dimension 1 must be >0\");\n\t  line = __LINE__ - 2;\n\t  goto fail;\n     }\n     if (n2<=0) {\n\t  PyErr_SetString(PyExc_RuntimeError, \"dimension 2 must be >0\");\n\t  line = __LINE__ - 2;\n\t  goto fail;\n     }\n     {\n\t  void *tmp = alloc->alloc;\n\t  switch(nd){\n\t  case 0:\n\t       solver_o->solver =  ((void_a_t)(tmp))(alloc->type);\n\t       break;\n\t  case 1: \n\t       solver_o->solver =  (void *) ((void_an_t) tmp)(alloc->type, n1); \n\t       break;\n\t  case 2: \n\t       DEBUG_MESS(3, \"Allocating solver with N=%d, p=%d\", n1, n2);\n\t       solver_o->solver =  (void *) ((void_anp_t) tmp)(alloc->type, n1, n2); \n\t       break;\n\t  case 3:\n\t       /* odeiv handles that itself */\n\t       break;\n\t  default:\n\t       pygsl_error(\"Only 0,1 or 2 for number of problem_dimensions implemented!\",\n\t\t\t __FILE__, __LINE__, GSL_ESANITY);\n\t       goto fail;\n\t  }\n     }\n\n     switch(nd){\n     case 1:\n     case 2:\n\t  if(solver_o->solver == NULL){\n\t       line = __LINE__ - 1;\n\t       goto fail;\n\t  }\n\t  break;\t  \n     default:\n\t  ;\n     }\n     switch(nd){\n     case 1:\n\t  solver_o->problem_dimensions[0] = n1;\n\t  break;\n     case 2:\n\t  solver_o->problem_dimensions[0] = n2;\n\t  solver_o->problem_dimensions[1] = n1;\n\t  break;\n     default:\n\t  ;\n     }\n\n     solver_o->cache = (struct pygsl_array_cache *) calloc(PyGSL_SOLVER_N_ARRAYS, sizeof(struct pygsl_array_cache));\n     if(solver_o->cache == NULL){\n\t  PyErr_NoMemory();\n\t  line = __LINE__ - 1;\n\t  goto fail;\n     }\n\n     FUNC_MESS_END();\n     return (PyObject *) solver_o;\n fail:\n     FUNC_MESS(\"Fail\");\n     DEBUG_MESS(3, \"line was %d\", line);\n     PyGSL_add_traceback(module, __FILE__, __FUNCTION__, line);\n     Py_XDECREF(solver_o);\n     return NULL;\n}\n\n#if 0\nstatic PyObject *\n_PyGSL_solver_np_init(PyObject *self, PyObject *args, const solver_alloc_struct * alloc)\n{\n    FUNC_MESS_BEGIN();     \n    return PyGSL_solver_dn_init(self, args, alloc, 2);\n    FUNC_MESS_END();\n}\n\nstatic PyObject *\nPyGSL_solver_n_init(PyObject *self, PyObject *args, const solver_alloc_struct * alloc)\n{\n     FUNC_MESS_BEGIN();\n     return PyGSL_solver_dn_init(self, args, alloc, 1);\n     FUNC_MESS_END();\n}\n\nstatic PyObject *\n_PyGSL_solver_1_init(PyObject *self, PyObject *args, const solver_alloc_struct * alloc)\n{\n     FUNC_MESS_BEGIN();\n     return PyGSL_solver_dn_init(self, args, alloc, 0);\n     FUNC_MESS_END();\n}\n\n#endif\nstatic double\nPyGSL_gsl_function(double x, void * params)\n{\n     PyGSL_solver *s;\n     double result = GSL_NAN;\n     int flag = GSL_EFAILED;\n\n     FUNC_MESS_BEGIN();\n     assert(params);\n     assert(PyGSL_solver_check((PyObject *) params));\n     s = (PyGSL_solver *) params;\n\n     flag = PyGSL_function_wrap_helper(x, &result, NULL, s->cbs[0], s->args, __FUNCTION__);\n     if(flag == GSL_SUCCESS){\n\t  FUNC_MESS_END();\n\t  return result;\n     }\n     FUNC_MESS(\"Fail\");\n     if(s->isset)\n\t  longjmp(s->buffer, flag);\n     DEBUG_MESS(2, \"Found an error of %d but could not jump!\", flag);\n     return GSL_NAN;\n}\n\nstatic double\nPyGSL_gsl_function_df(double x, void * params)\n{\n     PyGSL_solver *s;\n     double result = GSL_NAN;\n     int flag = GSL_EFAILED;\n\n     FUNC_MESS_BEGIN();\n     assert(params);\n     assert(PyGSL_solver_check((PyObject *) params));\n     s = (PyGSL_solver *) params;\n\n     flag = PyGSL_function_wrap_helper(x, &result, NULL, s->cbs[1], s->args, __FUNCTION__);\n     if(flag == GSL_SUCCESS){\n\t  FUNC_MESS_END();\n\t  return result;\n     }\n     FUNC_MESS(\"Fail\");\n     if(s->isset)\n\t  longjmp(s->buffer, flag);\n     DEBUG_MESS(2, \"Found an error of %d but could not jump!\", flag);\n     return GSL_NAN;\n}\n\nstatic void\nPyGSL_gsl_function_fdf(double x, void * params,  double *f, double *df)\n{\n     PyGSL_solver *s;\n     int flag = GSL_EFAILED;\n\n     FUNC_MESS_BEGIN();\n     assert(params);\n     assert(PyGSL_solver_check((PyObject *) params));\n     s = (PyGSL_solver *) params;\n\n     assert(s->cbs[2]);\n     assert(PyCallable_Check(s->cbs[2]));\n     flag = PyGSL_function_wrap_helper(x, f, df, s->cbs[2], s->args, __FUNCTION__);\n     if(flag == GSL_SUCCESS){\n\t  FUNC_MESS_END();\n\t  return;\n     }\n     FUNC_MESS(\"Fail\");\n     if(s->isset)\n\t  longjmp(s->buffer, flag);\n     DEBUG_MESS(2, \"Found an error of %d but could not jump!\", flag);\n     *f = GSL_NAN;\n     *df = GSL_NAN;\n}\n\nstatic PyObject* \nPyGSL_solver_set_f(PyGSL_solver *self, PyObject *pyargs, PyObject *kw, \n\t\t    void *fptr, int isfdf) \n{\n\n     PyObject *f = NULL, *df = NULL, *fdf = NULL, *args = Py_None;\n     int  flag=GSL_EFAILED;\n     void *c_sys = NULL;\n     gsl_function * f_sys = NULL;\n     gsl_function_fdf * fdf_sys = NULL;\n     double x0, lower=0, upper=0;\n\n     static const char *f_kwlist[]   = {\"f\", \"x0\", \"upper\", \"lower\", \"args\", NULL};\n     static const char *fdf_kwlist[] = {\"f\", \"df\", \"fdf\", \"x0\", \"args\", NULL};\n\n     FUNC_MESS_BEGIN();\n     assert(PyGSL_solver_check(self));     \n     if (self->solver == NULL) {\n\t  pygsl_error(\"Got a NULL Pointer of min.f\",  filename, __LINE__ - 3, GSL_EFAULT);\n\t  return NULL;\n     }\n\n     assert(pyargs);\n     /* arguments PyFunction, Parameters, start Vector, step Vector */\n\n     if(isfdf == 0){\n\t  if (0==PyArg_ParseTupleAndKeywords(pyargs,kw,\"OdddO\", (char **)f_kwlist, &f,\n\t\t\t\t\t     &x0,&lower,&upper,&args))\n\t       return NULL;\n     }else{\n\t  if (0==PyArg_ParseTupleAndKeywords(pyargs,kw,\"OOOdO\", (char **)fdf_kwlist, &f,&df,&fdf,\n\t\t\t\t\t     &x0,&args))\n\t       return NULL;\t  \n     }\n\n     if(!PyCallable_Check(f)){\n\t  pygsl_error(\"First argument must be callable\",  filename, __LINE__ - 3, GSL_EBADFUNC);\n\t  return NULL;\t  \n     }\n     if(isfdf == 1){\n\t  if(!PyCallable_Check(df)){\n\t       pygsl_error(\"Second argument must be callable\",  filename, __LINE__ - 3, GSL_EBADFUNC);\n\t       return NULL;\t  \n\t  }\n\t  if(!PyCallable_Check(fdf)){\n\t       pygsl_error(\"Third argument must be callable\",  filename, __LINE__ - 3, GSL_EBADFUNC);\n\t       return NULL;\t  \n\t  }\n     }\n     if (self->c_sys != NULL) {\n\t  /* free the previous function and args */\n\t  c_sys = self->c_sys;\n     } else {\n\t  /* allocate function space */\n\t  if(isfdf == 0)\n\t       c_sys=calloc(1, sizeof(gsl_function));\n\t  else\n\t       c_sys=calloc(1, sizeof(gsl_function_fdf));\n\t  if (c_sys == NULL) {\n\t       pygsl_error(\"Could not allocate the object for the minimizer function\", \n\t\t\t filename, __LINE__ - 3, GSL_ENOMEM);\n\t       goto fail;\n\t  }\n     }\n     DEBUG_MESS(3, \"Everything allocated args = %p\", args);\n     /* add new function  and parameters */\n\n     if(PyGSL_solver_func_set(self, args, f, df, fdf) != GSL_SUCCESS)\n\t  goto fail;\n     \n     /* initialize the function struct */\n     if(isfdf == 0){\n\t  f_sys = c_sys;\n\t  f_sys->function=PyGSL_gsl_function;\n\t  f_sys->params=(void*)self;\n     }else{\n\t  fdf_sys = c_sys;\n\t  fdf_sys->f=PyGSL_gsl_function;\n\t  fdf_sys->df=PyGSL_gsl_function_df;\n\t  fdf_sys->fdf=PyGSL_gsl_function_fdf;\n\t  fdf_sys->params=(void*)self;\t  \n     }\n     DEBUG_MESS(3, \"Setting jmp buffer isset = % d\", self->isset);\n     if((flag = setjmp(self->buffer)) == 0){\n\t  self->isset = 1;\n\t  if(isfdf == 0){\n\t       DEBUG_MESS(3, \"Calling f isfdf = %d\", isfdf);\n\t       flag = ((set_m_ddd_t) fptr)(self->solver, c_sys, x0, lower, upper);\n\t  }else{\n\t       DEBUG_MESS(3, \"Calling fdf isfdf = %d\", isfdf);\n\t       flag = ((set_m_d_t) fptr)(self->solver, c_sys, x0);\n\t  }\n\t  if(PyGSL_ERROR_FLAG(flag) != GSL_SUCCESS){\n\t       goto fail;\n\t  }\n     } else {\n\t  goto fail;\n     }\n     DEBUG_MESS(4, \"Set evaluated. flag = %d\", flag);\n     self->c_sys = c_sys;\n     self->set_called = 1;\n\n     self->isset = 0;\n     Py_INCREF(Py_None);\n     FUNC_MESS_END();\n     return Py_None;\n\n     \n fail:\n     FUNC_MESS(\"Fail\");\n     PyGSL_ERROR_FLAG(flag);\n     self->isset = 0;\n     return NULL;\n     \n}\n\n/*\n * Set the solver\n */\nPyGSL_API_EXTERN PyObject *\nPyGSL_solver_n_set(PyGSL_solver *self, PyObject *pyargs, PyObject *kw, \n\t\t    const struct pygsl_solver_n_set * info)\n{\n     int n, flag=GSL_EFAILED;\n     PyGSL_array_index_t stride;\n\n     PyObject *args=Py_None, *f=NULL, *df=NULL, *fdf=NULL, *x;\n     PyArrayObject * xa = NULL;\n     gsl_vector_view gsl_x;\n     void *c_sys;\n     int line = -1;\n     static const char *f_kwlist[]   = {\"f\", \"x0\", \"args\", NULL};\n     static const char *fdf_kwlist[] = {\"f\", \"df\", \"fdf\", \"x0\", \"args\", NULL};\n\n     FUNC_MESS_BEGIN();\n     assert(PyGSL_solver_check(self));     \n     if (self->solver == NULL) {\n\t  pygsl_error(\"solver ==  NULL at solver_n_set\", filename, __LINE__ - 3, GSL_EFAULT);\n\t  return NULL;\n     }\t  \n\n     /* arguments PyFunction, Parameters, start Vector, step Vector */\n     if(info->is_fdf == 0){\n\t  if (0==PyArg_ParseTupleAndKeywords(pyargs, kw, \"OO|O\", (char **)f_kwlist, \n\t\t\t\t\t     &f, &x, &args))\n\t       return NULL;\n     } else {\n\t  if (0==PyArg_ParseTupleAndKeywords(pyargs, kw, \"OOOO|O\", (char **)fdf_kwlist, \n\t\t\t\t\t     &f, &df, &fdf, &x, &args))\n\t       return NULL;\n     }\n\n     n=self->problem_dimensions[0];\n     DEBUG_MESS(3, \"len(x) should be %d\", n);\n     xa  = PyGSL_vector_check(x, n, PyGSL_DARRAY_INPUT(2), &stride, NULL);\n     if (xa == NULL){\n\t  line = __LINE__ - 2;\n\t  goto fail;\n     }\n     gsl_x = gsl_vector_view_array_with_stride((double *)(xa->data), stride,\n\t\t\t\t\t       xa->dimensions[0]);\n\n\n     if (self->c_sys != NULL) {\n\t  c_sys = self->c_sys;\n     } else {\n\t  c_sys=info->c_sys;\n     }\n\n     if(PyGSL_solver_func_set(self, args, f, df, fdf) != GSL_SUCCESS){\n\t  line = __LINE__ - 1;\n\t  goto fail;\n     }\n     if((flag = setjmp(self->buffer)) == 0){\n\t  self->isset = 1;\t  \n\t  flag = info->set(self->solver, c_sys, &gsl_x.vector);\n\t  if((PyGSL_ERROR_FLAG(flag)) != GSL_SUCCESS){\n\t  line = __LINE__ - 2;\n\t       goto fail;\n\t  }\n     }else{\n\t  line = __LINE__ - 9;\n\t  goto fail;\n     }\n     self->c_sys = c_sys;\n     self->isset = 0;\n     Py_DECREF(xa);\n     self->set_called = 1;\n\n     Py_INCREF(Py_None);\n     FUNC_MESS_END();\n     return Py_None;\n\n fail:\n     PyGSL_add_traceback(module, __FILE__, __FUNCTION__, line);\n     self->isset = 0;\n     self->set_called = 0;\n     Py_XDECREF(xa);\n     return NULL;\n     \n}\n\nstatic PyObject* \nPyGSL_solver_ret_size_t(PyGSL_solver *self, PyObject *args, \n\t\t\tsize_t_m_t func)\n{\n     size_t result;\n     FUNC_MESS_BEGIN();\n     assert(PyGSL_solver_check(self));     \n     result=func(self->solver);\n     FUNC_MESS_END();\n     return (PyObject *) PyLong_FromLong((long)result);\n} \n\nstatic PyObject* \nPyGSL_solver_ret_int(PyGSL_solver *self, PyObject *args, \n\t\t\tint_m_t func)\n{\n     int result;\n     FUNC_MESS_BEGIN();\n     assert(PyGSL_solver_check(self));     \n     result=func(self->solver);\n     FUNC_MESS_END();\n     return (PyObject *) PyLong_FromLong((long)result);\n} \n\nstatic PyObject* \nPyGSL_solver_ret_double(PyGSL_solver *self, PyObject *args, \n\t\t\tdouble_m_t func)\n{\n     double result;\n     FUNC_MESS_BEGIN();\n     assert(PyGSL_solver_check(self));     \n     result=func(self->solver);\n     FUNC_MESS_END();\n     return (PyObject *) PyFloat_FromDouble(result);\n} \n\nstatic PyObject* \nPyGSL_solver_ret_vec(PyGSL_solver *self, PyObject *args, \n\t\t     ret_vec func)\n{\n     gsl_vector *result;\n     FUNC_MESS_BEGIN();\n     assert(PyGSL_solver_check(self));     \n     result=func(self->solver);\n     if(result == NULL)\n\t  PyGSL_ERROR_NULL(\"Could not retrive vector ...\", GSL_ESANITY);\n     FUNC_MESS_END();\n     return (PyObject *) PyGSL_copy_gslvector_to_pyarray(result);\n} \n\n/*\n * evaluates a C function taking an vector and a double as input and returning a status.\n */\nstatic PyObject*\nPyGSL_solver_vd_i(PyObject * self, PyObject *args, int_f_vd_t func)\n{\n     PyObject *g=NULL;\n     PyArrayObject *ga=NULL;\n     gsl_vector_view gradient;\n\n     double epsabs;\n     int flag = GSL_EFAILED;\n     PyGSL_array_index_t stride_recalc=-1;\n\n     FUNC_MESS_BEGIN();\n     if (0==PyArg_ParseTuple(args,\"Od\", &g, &epsabs))\n\t  return NULL;     \n\n     ga  = PyGSL_vector_check(g, -1, PyGSL_DARRAY_INPUT(1), &stride_recalc, NULL);\n     if (ga == NULL){\n\t  PyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__ - 1);\n\t  return NULL;\n     }\n     gradient = gsl_vector_view_array_with_stride((double *)(ga->data), stride_recalc,\n\t\t\t\t\t\t  ga->dimensions[0]);\n     flag = func(&gradient.vector, epsabs);\n     FUNC_MESS_END();\n     return PyGSL_ERROR_FLAG_TO_PYINT(flag);\n     \n}\n\nstatic PyObject *\nPyGSL_solver_vvdd_i(PyObject * self, PyObject * args, int_f_vvdd_t func)\n{\n     int flag;\n     int line = -1;\n     double epsabs, epsrel;\n     PyObject *dx_o, *x_o;\n     PyArrayObject *dx_a = NULL, *x_a = NULL;\n     gsl_vector_view x, dx;\n     PyGSL_array_index_t dimension, stride;\n\n     FUNC_MESS_BEGIN();\n     if(!PyArg_ParseTuple(args, \"OOdd\", &dx_o, &x_o, &epsabs, &epsrel))\n\t  return NULL;\n\n     dx_a = PyGSL_vector_check(dx_o, -1, PyGSL_DARRAY_INPUT(1), &stride, NULL);\n     if(dx_a == NULL){\n\t  line = __LINE__ - 4;\n\t  goto fail;\n     }\n     dx = gsl_vector_view_array_with_stride((double *)(dx_a->data), stride, dx_a->dimensions[0]);\n\n     dimension = dx_a->dimensions[0];\n     x_a = PyGSL_vector_check(x_o, dimension, PyGSL_DARRAY_CINPUT(2), &stride,  NULL);\n     if(x_a == NULL){\n\t  line = __LINE__ - 4;\n\t  goto fail;\n     }\n     x = gsl_vector_view_array_with_stride((double *)(x_a->data), stride, x_a->dimensions[0]);\n     flag = func(&(dx.vector), &(x.vector), epsabs, epsrel);\n     Py_DECREF(x_a);\n     Py_DECREF(dx_a);\n     FUNC_MESS_END();\n     return PyGSL_ERROR_FLAG_TO_PYINT(flag);\n\n fail:\n     PyGSL_add_traceback(module, __FILE__, __FUNCTION__, line);\n     Py_XDECREF(dx_a);\n     Py_XDECREF(x_a);\n     return NULL;\n}\n\nPyGSL_API_EXTERN int\nPyGSL_Callable_Check(PyObject *f, const char * myname)\n{\n     FUNC_MESS_BEGIN();\n     if(!PyCallable_Check(f)){\n\t  char str[256];\n\t  snprintf(str, 254, \"Callback named %s is not callable!\", myname);\n\t  PyGSL_ERROR(str, GSL_EINVAL);\n     }\n     FUNC_MESS_END();\n     return GSL_SUCCESS;\n}\n\nPyGSL_API_EXTERN int\nPyGSL_solver_func_set(PyGSL_solver *self, PyObject *args, PyObject *f,\n\t\t       PyObject *df, PyObject *fdf)\n{\n     int flag = GSL_EFAILED;\n     if(df){\n\t  if(!fdf)\n\t       PyGSL_ERROR(\"If df is given, fdf must be given as well!\", GSL_ESANITY);\n\t  Py_XDECREF(self->cbs[1]);\n\t  Py_XDECREF(self->cbs[2]);\n\t  self->cbs[1] = NULL;\t  \n\t  self->cbs[2] = NULL;\n     }\n     Py_XDECREF(self->args);\n     Py_XDECREF(self->cbs[0]);\n     self->args = NULL;     \n     self->cbs[0] = NULL;\n\n     \n     DEBUG_MESS(3, \"args = %p\", (void *) args);\n     self->args=args; Py_XINCREF(args);\n     assert(f);\n     if((flag = PyGSL_CALLABLE_CHECK(f, \"f\")) != GSL_SUCCESS)\n\t  return flag;\n     self->cbs[0] = f; Py_INCREF(f);\n     if(df){\n\t  assert(fdf);\n\t  if((flag = PyGSL_CALLABLE_CHECK(df, \"df\")) != GSL_SUCCESS)\n\t       return flag;\n\t  if((flag = PyGSL_CALLABLE_CHECK(fdf, \"fdf\")) != GSL_SUCCESS)\n\t       return flag;\n\t  self->cbs[1]=df;   Py_INCREF(df);\n\t  self->cbs[2]=fdf;  Py_INCREF(fdf);\n     }\n     return GSL_SUCCESS;     \n}\n\n\nstatic PyObject *\nPyGSL_solver_GetSet(PyObject *self, PyObject *args, void * address, enum PyGSL_GETSET_typemode mode)\n{\n     PyObject *ret=NULL, *input=NULL;\n     unsigned long ultmp;\n     int flag;\n\n     if (!PyArg_ParseTuple(args, \"|O\", &input))\t  \n\t  return NULL;\n\n     if(input){\n\t  switch(mode){\n\t  case PyGSL_MODE_DOUBLE:\n\t       flag = PyGSL_PYFLOAT_TO_DOUBLE(input, (double *) address, NULL);\n\t       break;\n\t  case PyGSL_MODE_INT:\n\t       flag = PyGSL_PYINT_TO_INT(input, (int *) address, NULL);\n\t       break;\n\t  case PyGSL_MODE_SIZE_T:\n\t       flag = PyGSL_PYLONG_TO_ULONG(input, &ultmp, NULL);\n\t       *((size_t *) address) = ultmp;\n\t       break;\n\t  default:\n\t       PyGSL_ERROR_NULL(\"Unknown mode\",GSL_ESANITY);\n\t  }\n\t  if(PyGSL_ERROR_FLAG(flag) != GSL_SUCCESS)\n\t       return NULL;\n\n\t  Py_INCREF(Py_None);\n\t  ret = Py_None;\n\t  return ret;     \n     }\n\n     switch(mode){\n     case PyGSL_MODE_DOUBLE:\n\t  ret = PyFloat_FromDouble(*((double *) address));\n\t  break;\n     case PyGSL_MODE_INT:\n\t  ret = PyInt_FromLong(((long) *((int *) address)));\n\t  break;\n     case PyGSL_MODE_SIZE_T:\n\t  ret = PyLong_FromUnsignedLong(((unsigned long) *((size_t *) address)));\n\t  break;\n     default:\n\t  PyGSL_ERROR_NULL(\"Unknown mode\",GSL_ESANITY);\n     }\n     return ret;\n}\n\n#ifdef ONEFILE\n\n#include \"chars.c\"\n#include \"function_helpers2.c\"\n/* \n\n#include \"function_helpers.c\"\n#include \"integrate.c\"\n#include \"odeiv.c\"\n#include \"roots.c\"\n#include \"minimize.c\"\n#include \"multifit_nlin.c\"\n#include \"multimin.c\" \n#include \"multiroot.c\"\n*/\n#endif /* ONEFILE */\n\nstatic PyMethodDef solverMethods[] = {\n     {NULL, NULL, 0, NULL}\n};\n\nvoid\ninit_api(void)\n{\n     FUNC_MESS_BEGIN();    \n     PyGSL_API[PyGSL_solver_type_NUM            ] = (void *) &PyGSL_solver_pytype     ;\n     PyGSL_API[PyGSL_solver_ret_int_NUM         ] = (void *) &PyGSL_solver_ret_int    ;\n     PyGSL_API[PyGSL_solver_ret_double_NUM      ] = (void *) &PyGSL_solver_ret_double ;\n     PyGSL_API[PyGSL_solver_ret_size_t_NUM      ] = (void *) &PyGSL_solver_ret_size_t ;\n     PyGSL_API[PyGSL_solver_ret_vec_NUM         ] = (void *) &PyGSL_solver_ret_vec    ;\n     PyGSL_API[PyGSL_solver_dn_init_NUM         ] = (void *) &PyGSL_solver_dn_init    ;\n     PyGSL_API[PyGSL_solver_vd_i_NUM            ] = (void *) &PyGSL_solver_vd_i       ;\n     PyGSL_API[PyGSL_solver_vvdd_i_NUM          ] = (void *) &PyGSL_solver_vvdd_i     ;\n     PyGSL_API[PyGSL_Callable_Check_NUM         ] = (void *) &PyGSL_Callable_Check    ;\n     PyGSL_API[PyGSL_solver_func_set_NUM        ] = (void *) &PyGSL_solver_func_set   ;\n     PyGSL_API[PyGSL_function_wrap_OnOn_On_NUM  ] = (void *) &PyGSL_function_wrap_OnOn_On;\n     PyGSL_API[PyGSL_function_wrap_On_O_NUM     ] = (void *) &PyGSL_function_wrap_On_O;\n     PyGSL_API[PyGSL_function_wrap_Op_On_NUM    ] = (void *) &PyGSL_function_wrap_Op_On;\n     PyGSL_API[PyGSL_function_wrap_Op_Opn_NUM   ] = (void *) &PyGSL_function_wrap_Op_Opn;\n     PyGSL_API[PyGSL_function_wrap_Op_On_Opn_NUM] = (void *) &PyGSL_function_wrap_Op_On_Opn;\n     PyGSL_API[PyGSL_solver_n_set_NUM           ] = (void *) &PyGSL_solver_n_set      ;\n     PyGSL_API[PyGSL_solver_set_f_NUM           ] = (void *) &PyGSL_solver_set_f      ;\n     PyGSL_API[PyGSL_solver_getset_NUM          ] = (void *) &PyGSL_solver_GetSet     ;\n     FUNC_MESS_END();\n}\n\nvoid\ninitsolver(void)\n{\n  PyObject* m, *dict, *item;\n\n  FUNC_MESS_BEGIN();\n  m=Py_InitModule(\"solver\", solverMethods);\n  init_pygsl();\n\n\n  /* init multimin type */\n  PyGSL_solver_pytype.ob_type  = &PyType_Type;\n\n  init_api();\n\n\n  module = m;\n\n  Py_INCREF((PyObject*)&PyGSL_solver_pytype);\n\n  dict = PyModule_GetDict(m);\n  if(!dict)\n       goto fail;\n  \n  if (!(item = PyString_FromString((char*)PyGSL_solver_module_doc))){\n       PyErr_SetString(PyExc_ImportError, \n\t\t       \"I could not generate module doc string!\");\n       goto fail;\n  }\n  if (PyDict_SetItemString(dict, \"__doc__\", item) != 0){\n       PyErr_SetString(PyExc_ImportError, \n\t\t       \"I could not init doc string!\");\n       goto fail;\n  }\n  FUNC_MESS_END();\n\n fail:\n  FUNC_MESS(\"FAIL\");\n  return;\n\n}\n", "meta": {"hexsha": "d7ba52dcf4909ce8fa2433ad8431d021c2b2a30f", "size": 27367, "ext": "c", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/testing/src/solvers/solvermodule.c", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/testing/src/solvers/solvermodule.c", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/testing/src/solvers/solvermodule.c", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 27.7555780933, "max_line_length": 116, "alphanum_fraction": 0.6192860014, "num_tokens": 8172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10521053670308636, "lm_q2_score": 0.028870907364077388, "lm_q1q2_score": 0.0030375236588796703}}
{"text": "#ifndef __GSL_BLOCK_H__\r\n#define __GSL_BLOCK_H__\r\n\r\n#if !defined( GSL_FUN )\r\n#  if !defined( GSL_DLL )\r\n#    define GSL_FUN extern\r\n#  elif defined( BUILD_GSL_DLL )\r\n#    define GSL_FUN extern __declspec(dllexport)\r\n#  else\r\n#    define GSL_FUN extern __declspec(dllimport)\r\n#  endif\r\n#endif\r\n\r\n#include <gsl/gsl_block_complex_long_double.h>\r\n#include <gsl/gsl_block_complex_double.h>\r\n#include <gsl/gsl_block_complex_float.h>\r\n\r\n#include <gsl/gsl_block_long_double.h>\r\n#include <gsl/gsl_block_double.h>\r\n#include <gsl/gsl_block_float.h>\r\n\r\n#include <gsl/gsl_block_ulong.h>\r\n#include <gsl/gsl_block_long.h>\r\n\r\n#include <gsl/gsl_block_uint.h>\r\n#include <gsl/gsl_block_int.h>\r\n\r\n#include <gsl/gsl_block_ushort.h>\r\n#include <gsl/gsl_block_short.h>\r\n\r\n#include <gsl/gsl_block_uchar.h>\r\n#include <gsl/gsl_block_char.h>\r\n\r\n#endif /* __GSL_BLOCK_H__ */\r\n", "meta": {"hexsha": "cb9752d48510e051148e5bc93c79de4d98b51361", "size": 847, "ext": "h", "lang": "C", "max_stars_repo_path": "deps/include/gsl/gsl_block.h", "max_stars_repo_name": "berkus/music-cs", "max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z", "max_issues_repo_path": "deps/include/gsl/gsl_block.h", "max_issues_repo_name": "berkus/music-cs", "max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z", "max_forks_repo_path": "deps/include/gsl/gsl_block.h", "max_forks_repo_name": "berkus/music-cs", "max_forks_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 24.2, "max_line_length": 49, "alphanum_fraction": 0.7378984652, "num_tokens": 236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12940274502147983, "lm_q2_score": 0.023330766346783167, "lm_q1q2_score": 0.0030190652087285046}}
{"text": "#ifndef OPENMC_TALLIES_FILTER_MATERIAL_H\n#define OPENMC_TALLIES_FILTER_MATERIAL_H\n\n#include <cstdint>\n#include <unordered_map>\n\n#include <gsl/gsl>\n\n#include \"openmc/tallies/filter.h\"\n#include \"openmc/vector.h\"\n\nnamespace openmc {\n\n//==============================================================================\n//! Specifies which material tally events reside in.\n//==============================================================================\n\nclass MaterialFilter : public Filter\n{\npublic:\n  //----------------------------------------------------------------------------\n  // Constructors, destructors\n\n  ~MaterialFilter() = default;\n\n  //----------------------------------------------------------------------------\n  // Methods\n\n  std::string type() const override {return \"material\";}\n\n  void from_xml(pugi::xml_node node) override;\n\n  void get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match)\n  const override;\n\n  void to_statepoint(hid_t filter_group) const override;\n\n  std::string text_label(int bin) const override;\n\n  //----------------------------------------------------------------------------\n  // Accessors\n\n  vector<int32_t>& materials() { return materials_; }\n\n  const vector<int32_t>& materials() const { return materials_; }\n\n  void set_materials(gsl::span<const int32_t> materials);\n\nprivate:\n  //----------------------------------------------------------------------------\n  // Data members\n\n  //! The indices of the materials binned by this filter.\n  vector<int32_t> materials_;\n\n  //! A map from material indices to filter bin indices.\n  std::unordered_map<int32_t, int> map_;\n};\n\n} // namespace openmc\n#endif // OPENMC_TALLIES_FILTER_MATERIAL_H\n", "meta": {"hexsha": "65bfce04eb455a97454475ad957db5ec11551a04", "size": 1696, "ext": "h", "lang": "C", "max_stars_repo_path": "include/openmc/tallies/filter_material.h", "max_stars_repo_name": "cjwyett/openmc", "max_stars_repo_head_hexsha": "a9e85f4d5b59d133c17caccf4704a032184841d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-02-07T20:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-07T20:23:33.000Z", "max_issues_repo_path": "include/openmc/tallies/filter_material.h", "max_issues_repo_name": "cjwyett/openmc", "max_issues_repo_head_hexsha": "a9e85f4d5b59d133c17caccf4704a032184841d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-05-22T07:57:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-21T17:34:35.000Z", "max_forks_repo_path": "include/openmc/tallies/filter_material.h", "max_forks_repo_name": "cjwyett/openmc", "max_forks_repo_head_hexsha": "a9e85f4d5b59d133c17caccf4704a032184841d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3548387097, "max_line_length": 84, "alphanum_fraction": 0.5324292453, "num_tokens": 314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11279540031810144, "lm_q2_score": 0.026759280274886218, "lm_q1q2_score": 0.0030183237308300664}}
{"text": "/* vector/gsl_vector_uchar.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_VECTOR_UCHAR_H__\n#define __GSL_VECTOR_UCHAR_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_check_range.h>\n#include <gsl/gsl_block_uchar.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n  size_t size;\n  size_t stride;\n  unsigned char *data;\n  gsl_block_uchar *block;\n  int owner;\n} \ngsl_vector_uchar;\n\ntypedef struct\n{\n  gsl_vector_uchar vector;\n} _gsl_vector_uchar_view;\n\ntypedef _gsl_vector_uchar_view gsl_vector_uchar_view;\n\ntypedef struct\n{\n  gsl_vector_uchar vector;\n} _gsl_vector_uchar_const_view;\n\ntypedef const _gsl_vector_uchar_const_view gsl_vector_uchar_const_view;\n\n\n/* Allocation */\n\nGSL_EXPORT gsl_vector_uchar *gsl_vector_uchar_alloc (const size_t n);\nGSL_EXPORT gsl_vector_uchar *gsl_vector_uchar_calloc (const size_t n);\n\nGSL_EXPORT gsl_vector_uchar *gsl_vector_uchar_alloc_from_block (gsl_block_uchar * b,\n                                                                const size_t offset,\n                                                                const size_t n,\n                                                                const size_t stride);\n\nGSL_EXPORT gsl_vector_uchar *gsl_vector_uchar_alloc_from_vector (gsl_vector_uchar * v,\n                                                                 const size_t offset,\n                                                                 const size_t n,\n                                                                 const size_t stride);\n\nGSL_EXPORT void gsl_vector_uchar_free (gsl_vector_uchar * v);\n\n/* Views */\n\nGSL_EXPORT\n_gsl_vector_uchar_view\ngsl_vector_uchar_view_array (unsigned char *v, size_t n);\n\nGSL_EXPORT\n_gsl_vector_uchar_view\ngsl_vector_uchar_view_array_with_stride (unsigned char *base,\n                                         size_t stride,\n                                         size_t n);\n\nGSL_EXPORT\n_gsl_vector_uchar_const_view\ngsl_vector_uchar_const_view_array (const unsigned char *v, size_t n);\n\nGSL_EXPORT\n_gsl_vector_uchar_const_view\ngsl_vector_uchar_const_view_array_with_stride (const unsigned char *base,\n                                               size_t stride,\n                                               size_t n);\n\nGSL_EXPORT\n_gsl_vector_uchar_view\ngsl_vector_uchar_subvector (gsl_vector_uchar *v,\n                            size_t i,\n                            size_t n);\n\nGSL_EXPORT\n_gsl_vector_uchar_view\ngsl_vector_uchar_subvector_with_stride (gsl_vector_uchar *v,\n                                        size_t i,\n                                        size_t stride,\n                                        size_t n);\n\nGSL_EXPORT\n_gsl_vector_uchar_const_view\ngsl_vector_uchar_const_subvector (const gsl_vector_uchar *v,\n                                  size_t i,\n                                  size_t n);\n\nGSL_EXPORT\n_gsl_vector_uchar_const_view\ngsl_vector_uchar_const_subvector_with_stride (const gsl_vector_uchar *v,\n                                              size_t i,\n                                              size_t stride,\n                                              size_t n);\n\n/* Operations */\n\nGSL_EXPORT unsigned char gsl_vector_uchar_get (const gsl_vector_uchar * v, const size_t i);\nGSL_EXPORT void gsl_vector_uchar_set (gsl_vector_uchar * v, const size_t i, unsigned char x);\n\nGSL_EXPORT unsigned char *gsl_vector_uchar_ptr (gsl_vector_uchar * v, const size_t i);\nGSL_EXPORT const unsigned char *gsl_vector_uchar_const_ptr (const gsl_vector_uchar * v, const size_t i);\n\nGSL_EXPORT void gsl_vector_uchar_set_zero (gsl_vector_uchar * v);\nGSL_EXPORT void gsl_vector_uchar_set_all (gsl_vector_uchar * v, unsigned char x);\nGSL_EXPORT int gsl_vector_uchar_set_basis (gsl_vector_uchar * v, size_t i);\n\nGSL_EXPORT int gsl_vector_uchar_fread (FILE * stream, gsl_vector_uchar * v);\nGSL_EXPORT int gsl_vector_uchar_fwrite (FILE * stream, const gsl_vector_uchar * v);\nGSL_EXPORT int gsl_vector_uchar_fscanf (FILE * stream, gsl_vector_uchar * v);\nGSL_EXPORT int gsl_vector_uchar_fprintf (FILE * stream, const gsl_vector_uchar * v,\n                                         const char *format);\n\nGSL_EXPORT int gsl_vector_uchar_memcpy (gsl_vector_uchar * dest, const gsl_vector_uchar * src);\n\nGSL_EXPORT int gsl_vector_uchar_reverse (gsl_vector_uchar * v);\n\nGSL_EXPORT int gsl_vector_uchar_swap (gsl_vector_uchar * v, gsl_vector_uchar * w);\nGSL_EXPORT int gsl_vector_uchar_swap_elements (gsl_vector_uchar * v, const size_t i, const size_t j);\n\nGSL_EXPORT unsigned char gsl_vector_uchar_max (const gsl_vector_uchar * v);\nGSL_EXPORT unsigned char gsl_vector_uchar_min (const gsl_vector_uchar * v);\nGSL_EXPORT void gsl_vector_uchar_minmax (const gsl_vector_uchar * v, unsigned char * min_out, unsigned char * max_out);\n\nGSL_EXPORT size_t gsl_vector_uchar_max_index (const gsl_vector_uchar * v);\nGSL_EXPORT size_t gsl_vector_uchar_min_index (const gsl_vector_uchar * v);\nGSL_EXPORT void gsl_vector_uchar_minmax_index (const gsl_vector_uchar * v, size_t * imin, size_t * imax);\n\nGSL_EXPORT int gsl_vector_uchar_add (gsl_vector_uchar * a, const gsl_vector_uchar * b);\nGSL_EXPORT int gsl_vector_uchar_sub (gsl_vector_uchar * a, const gsl_vector_uchar * b);\nGSL_EXPORT int gsl_vector_uchar_mul (gsl_vector_uchar * a, const gsl_vector_uchar * b);\nGSL_EXPORT int gsl_vector_uchar_div (gsl_vector_uchar * a, const gsl_vector_uchar * b);\nGSL_EXPORT int gsl_vector_uchar_scale (gsl_vector_uchar * a, const double x);\nGSL_EXPORT int gsl_vector_uchar_add_constant (gsl_vector_uchar * a, const double x);\n\nGSL_EXPORT int gsl_vector_uchar_isnull (const gsl_vector_uchar * v);\n\n#ifdef HAVE_INLINE\n\nextern inline\nunsigned char\ngsl_vector_uchar_get (const gsl_vector_uchar * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_VAL (\"index out of range\", GSL_EINVAL, 0);\n    }\n#endif\n  return v->data[i * v->stride];\n}\n\nextern inline\nvoid\ngsl_vector_uchar_set (gsl_vector_uchar * v, const size_t i, unsigned char x)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_VOID (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  v->data[i * v->stride] = x;\n}\n\nextern inline\nunsigned char *\ngsl_vector_uchar_ptr (gsl_vector_uchar * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return (unsigned char *) (v->data + i * v->stride);\n}\n\nextern inline\nconst unsigned char *\ngsl_vector_uchar_const_ptr (const gsl_vector_uchar * v, const size_t i)\n{\n#if GSL_RANGE_CHECK\n  if (i >= v->size)\n    {\n      GSL_ERROR_NULL (\"index out of range\", GSL_EINVAL);\n    }\n#endif\n  return (const unsigned char *) (v->data + i * v->stride);\n}\n\n\n#endif /* HAVE_INLINE */\n\n__END_DECLS\n\n#endif /* __GSL_VECTOR_UCHAR_H__ */\n\n\n", "meta": {"hexsha": "632455af130599fb4a98e3696bac0fefbb4a2d44", "size": 7739, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/gsl/include/gsl/gsl_vector_uchar.h", "max_stars_repo_name": "dynaryu/vaws", "max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/gsl/include/gsl/gsl_vector_uchar.h", "max_issues_repo_name": "dynaryu/vaws", "max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/gsl/include/gsl/gsl_vector_uchar.h", "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9319148936, "max_line_length": 119, "alphanum_fraction": 0.6849722186, "num_tokens": 1904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16451646289656316, "lm_q2_score": 0.018264280489362485, "lm_q1q2_score": 0.0030047748234606256}}
{"text": "/**\n * @license    BSD 3-Clause\n * @copyright  Pawel Okas\n * @version    $Id$\n * @brief\n *\n * @authors    Pawel Okas\n * created on: 30-03-2019\n *\n * @copyright Copyright (c) 2019, Pawel Okas\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n *\n *     1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n *     2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the\n *        documentation and/or other materials provided with the distribution.\n *     3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this\n *        software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER\n * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,\n * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef _AT24MAC_H_\n#define _AT24MAC_H_\n\n#include <charconv>\n#include <gsl/span>\n#include <optional>\n#include <string_view>\n#include \"I2CDevice/I2CDevice.h\"\n#include \"microhal.h\"\n\n/**\n * \\addtogroup Devices\n * @{\n * @class AT24MAC\n * @}\n */\nclass AT24MAC {\n public:\n    using I2C = microhal::I2C;\n    enum class Error {\n        AcknowledgeFailure = static_cast<int>(I2C::Error::AcknowledgeFailure),\n        ArbitrationLost = static_cast<int>(I2C::Error::ArbitrationLost),\n        Bus = static_cast<int>(I2C::Error::Bus),\n        None = static_cast<int>(I2C::Error::None),\n        Overrun = static_cast<int>(I2C::Error::Overrun),\n        Timeout = static_cast<int>(I2C::Error::Timeout),\n        Unknown = static_cast<int>(I2C::Error::Unknown),\n        DataOverflow,\n        Addres\n    };\n\n    struct SerialNumber {\n        uint8_t serial[128 / 8];\n\n        bool operator!=(SerialNumber b) { return std::equal(std::begin(serial), std::begin(serial) + sizeof(serial), std::begin(b.serial)); }\n        std::string toString() const {\n            std::string str;\n            str.reserve(18);\n            for (uint_fast8_t i = 0; i < sizeof(serial); i++) {\n                std::array<char, 2> buff;\n                auto [p, ec] = std::to_chars(buff.data(), buff.data() + buff.size(), serial[i], 16);\n                str.append(std::string_view(buff.data(), p - str.data()));\n                if (i + 1 != sizeof(serial)) {\n                    str.append(\":\");\n                }\n            }\n            return str;\n        }\n    };\n\n    static constexpr const size_t pageSize = 16;\n    static constexpr const size_t memorySizeInBytes = 256;\n\n private:\n    using Endianness = microhal::Endianness;\n    using Access = microhal::Access;\n    using span = gsl::span<uint8_t>;  // Todo change to std::span when it will be available in gcc\n\n    // create alias to microhal::Address, we just want to type less\n    template <typename T, T i>\n    using Address = microhal::Address<T, i>;\n\n    struct Register {\n        static constexpr auto SerialNumberReg =\n            microhal::makeRegister<SerialNumber, Access::ReadOnly, Endianness::Little>(Address<uint8_t, 0b1000'0000>{});\n        static constexpr auto EUIAddress = microhal::makeRegister<uint64_t, Access::ReadOnly, Endianness::Big>(Address<uint8_t, 0b1001'1000>{});\n    };\n\n    static constexpr uint8_t getMACi2cAddrFromMemoryI2cAddr(uint8_t memoryAddress) { return (memoryAddress & 0x0F) | 0xB0; }\n\n public:\n    AT24MAC(I2C &i2c, uint8_t address) : memory(i2c, address), mac(i2c, getMACi2cAddrFromMemoryI2cAddr(address)) {}\n\n    static std::string_view toString(Error error);\n\n    Error readEUI(uint64_t &eui) { return static_cast<Error>(mac.readRegister(Register::EUIAddress, eui)); }\n    Error readSerialNumber(SerialNumber &serial) { return static_cast<Error>(mac.readRegister(Register::SerialNumberReg, serial)); }\n\n    // Memory access functions\n    Error readByte(uint8_t address, uint8_t &data) { return static_cast<Error>(memory.read(address, data)); }\n    Error read(uint8_t address, span data) { return static_cast<Error>(memory.read(address, data)); }\n\n    Error writeByte(uint8_t address, uint8_t data) { return static_cast<Error>(memory.write(address, data)); }\n    Error writePage(uint8_t pageAddress, span data) {\n        if (data.size_bytes() > 16) return Error::DataOverflow;\n        if ((pageAddress % 16) != 0) return Error::Addres;\n        return static_cast<Error>(memory.write(pageAddress, data));\n    }\n    Error write(uint8_t address, span data) {\n        if (data.size_bytes() > memorySizeInBytes) return Error::DataOverflow;\n\n        uint_fast8_t bytesInFirstPage = pageSize - (address % pageSize);\n        span firstPage(data.data(), bytesInFirstPage);\n        writePage(address, firstPage);\n\n        address += bytesInFirstPage;\n        uint_fast8_t bytesToWrite = (data.size_bytes() - bytesInFirstPage);\n        uint8_t *dataPtr = data.data() + bytesInFirstPage;\n        while (bytesToWrite / pageSize) {\n            span page(dataPtr, pageSize);\n            writePage(address, page);\n            address += pageSize;\n            dataPtr += pageSize;\n            bytesToWrite -= pageSize;\n        }\n\n        uint_fast8_t lastPageSize = bytesToWrite % pageSize;\n        if (lastPageSize) {\n            span page(dataPtr, lastPageSize);\n            writePage(address, page);\n        }\n        return Error::None;\n    }\n\n    void writeWait() { std::this_thread::sleep_for(std::chrono::milliseconds{5}); }\n\n private:\n    microhal::I2CDevice memory;\n    microhal::I2CDevice mac;\n};\n\n#endif /* _AT24MAC_H_ */\n", "meta": {"hexsha": "0ceeeaac071404bfc8510dc5f19319464124766f", "size": 6291, "ext": "h", "lang": "C", "max_stars_repo_path": "drivers/Atmel/AT24MAC/driver/at24mac.h", "max_stars_repo_name": "microHAL/microhal-drivers", "max_stars_repo_head_hexsha": "09925a9696e4794f9ca0b2e9b5e61908ac99b84b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "drivers/Atmel/AT24MAC/driver/at24mac.h", "max_issues_repo_name": "microHAL/microhal-drivers", "max_issues_repo_head_hexsha": "09925a9696e4794f9ca0b2e9b5e61908ac99b84b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "drivers/Atmel/AT24MAC/driver/at24mac.h", "max_forks_repo_name": "microHAL/microhal-drivers", "max_forks_repo_head_hexsha": "09925a9696e4794f9ca0b2e9b5e61908ac99b84b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.6622516556, "max_line_length": 148, "alphanum_fraction": 0.6719122556, "num_tokens": 1531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10374862409521529, "lm_q2_score": 0.028870909035235398, "lm_q1q2_score": 0.002995317088783792}}
{"text": "#ifndef VKST_WSI_WINDOW_H\n#define VKST_WSI_WINDOW_H\n\n#include <turf/c/core.h>\n#include <gsl.h>\n#include <wsi/input.h>\n#include <functional>\n\nnamespace wsi {\n\nenum class window_options : uint8_t {\n  none = 0,\n  decorated = (1 << 1),\n  sizeable = (1 << 2),\n  fullscreen_windowed = (1 << 3),\n}; // enum class window_options\n\nnamespace impl {\n\ntemplate <class D>\nclass window {\npublic:\n  void retitle(gsl::czstring title) noexcept {\n    static_cast<D*>(this)->do_retitle(title);\n  }\n  std::string title() const noexcept {\n    return static_cast<D const*>(this)->do_title();\n  }\n\n  rect2d const& topleft_size() const noexcept { return _topleft_size; }\n\n  extent2d const& size() const noexcept { return _topleft_size.extent; }\n  void resize(extent2d const& size) noexcept {\n    static_cast<D*>(this)->do_resize(size);\n  }\n\n  offset2d const& position() const noexcept { return _topleft_size.offset; }\n  void reposition(offset2d const& position) noexcept {\n    static_cast<D*>(this)->do_reposition(position);\n  }\n\n  void show() noexcept { static_cast<D*>(this)->do_show(); }\n  void hide() noexcept { static_cast<D*>(this)->do_hide(); }\n\n  void close() noexcept { static_cast<D*>(this)->do_close(); }\n  bool closed() const noexcept { return _closed; }\n\n  keyset const& keys() const noexcept { return _keys; }\n  buttonset const& buttons() const noexcept { return _buttons; }\n  int scroll() const noexcept { return _scroll; }\n\n  offset2d cursor_pos() const noexcept {\n    return static_cast<D const*>(this)->do_cursor_pos();\n  }\n\n  void poll_events() noexcept { static_cast<D*>(this)->do_poll_events(); }\n\n  using resize_delegate = std::function<void(D*, extent2d const&)>;\n  void on_resize(resize_delegate delegate) noexcept {\n    _on_resize = std::move(delegate);\n  }\n\n  using reposition_delegate = std::function<void(D*, offset2d const&)>;\n  void on_reposition(reposition_delegate delegate) noexcept {\n    _on_reposition = std::move(delegate);\n  }\n\n  using close_delegate = std::function<void(D*)>;\n  void on_close(close_delegate delegate) noexcept {\n    _on_close = std::move(delegate);\n  }\n\n  constexpr window() noexcept {}\n  constexpr window(rect2d topleft_size) noexcept\n  : _topleft_size{std::move(topleft_size)} {}\n\nprotected:\n  rect2d _topleft_size{};\n  bool _closed{false};\n  keyset _keys{};\n  buttonset _buttons{};\n  int _scroll{0};\n\n  resize_delegate _on_resize{[](auto, auto) {}};\n  reposition_delegate _on_reposition{[](auto, auto) {}};\n  close_delegate _on_close{[](D*) {}};\n}; // class window\n\n} // namespace impl\n\ninline constexpr auto operator|(window_options a, window_options b) noexcept {\n  using U = std::underlying_type_t<window_options>;\n  return static_cast<window_options>(static_cast<U>(a) | static_cast<U>(b));\n}\n\ninline constexpr auto operator&(window_options a, window_options b) noexcept {\n  using U = std::underlying_type_t<window_options>;\n  return static_cast<window_options>(static_cast<U>(a) & static_cast<U>(b));\n}\n\n} // namespace wsi\n\n// clang-format off\n#if TURF_TARGET_WIN32\n#  include <wsi/window_win32.h>\n#elif TURF_KERNEL_LINUX\n#  include <wsi/window_xlib.h>\n#else\n#  error \"Unsupported platform\"\n#endif\n// clang-format on\n\n#endif // VKST_WSI_WINDOW_H\n", "meta": {"hexsha": "9599355eba0a0e9b2c85bff901239340cdd9c0df", "size": 3185, "ext": "h", "lang": "C", "max_stars_repo_path": "src/wsi/window.h", "max_stars_repo_name": "wesleygriffin/vkst", "max_stars_repo_head_hexsha": "5f1210ef8aeecdd2bbc3904b0cc4dd09892f239c", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/wsi/window.h", "max_issues_repo_name": "wesleygriffin/vkst", "max_issues_repo_head_hexsha": "5f1210ef8aeecdd2bbc3904b0cc4dd09892f239c", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/wsi/window.h", "max_forks_repo_name": "wesleygriffin/vkst", "max_forks_repo_head_hexsha": "5f1210ef8aeecdd2bbc3904b0cc4dd09892f239c", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9385964912, "max_line_length": 78, "alphanum_fraction": 0.7102040816, "num_tokens": 832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10374862132405094, "lm_q2_score": 0.028870904543998467, "lm_q1q2_score": 0.0029953165428181186}}
{"text": "#pragma once\n\n#include <nextalign/nextalign.h>\n\n#include <gsl/string_span>\n\ntemplate<typename Letter>\nusing SequenceSpan = gsl::basic_string_span<Letter, gsl::dynamic_extent>;\n\n\ntemplate<typename Letter>\nstruct InsertionInternal {\n  int begin;\n  int end;\n  Sequence<Letter> seq;\n};\n\nstruct PeptideInternal {\n  std::string name;\n  AminoacidSequence seq;\n  std::vector<InsertionInternal<Aminoacid>> insertions;\n};\n", "meta": {"hexsha": "73d6a177de6e530315d37ee5527e6c48cbb082d2", "size": 412, "ext": "h", "lang": "C", "max_stars_repo_path": "packages/nextalign/src/nextalign_private.h", "max_stars_repo_name": "davidcroll/nextclade", "max_stars_repo_head_hexsha": "f62d906034974c160eabb12ac9bf98a691646ee3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "packages/nextalign/src/nextalign_private.h", "max_issues_repo_name": "davidcroll/nextclade", "max_issues_repo_head_hexsha": "f62d906034974c160eabb12ac9bf98a691646ee3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "packages/nextalign/src/nextalign_private.h", "max_forks_repo_name": "davidcroll/nextclade", "max_forks_repo_head_hexsha": "f62d906034974c160eabb12ac9bf98a691646ee3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.9130434783, "max_line_length": 73, "alphanum_fraction": 0.7621359223, "num_tokens": 100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14223190228178134, "lm_q2_score": 0.020964242003267144, "lm_q1q2_score": 0.0029817840200203082}}
{"text": "#ifndef rpsr_f7f329f9_ae61_4fcf_b0c9_8a96216ed0e0_h\r\n#define rpsr_f7f329f9_ae61_4fcf_b0c9_8a96216ed0e0_h\r\n\r\n#include <rathen\\config.h>\r\n\r\n/*\r\n * This version of API wrappers were used by the flex & bison due to the cpp generator was still unstable.\r\n * Any kind of cpp style announcement should not appear in the header file.\r\n */\r\n\r\n#ifndef __cplusplus\r\n#ifdef _UNICODE\r\ntypedef wchar_t rchar;\r\n#else\r\ntypedef char rchar;\r\n#endif\r\n#else\r\n#include <gslib\\string.h>\r\ntypedef gs::gchar rchar;\r\n#endif\r\n\r\n#ifndef __cplusplus\r\ntypedef void rpswrap;\r\ntypedef void rpsobj;\r\ntypedef void rpsparser;\r\n#else\r\n#include <rathen\\parser.h>\r\ntypedef gs::rathen::parser::wrapper rpswrap;\r\ntypedef gs::rathen::ps_obj rpsobj;\r\ntypedef gs::rathen::parser rpsparser;\r\n#endif\r\n\r\n/* file: parser.h, line: 14 */\r\nenum rpobj_tag\r\n{\r\n    rpt_root,\r\n    rpt_block,\r\n    rpt_value,\r\n    rpt_expression,\r\n    rpt_operator,\r\n    rpt_function,\r\n    rpt_calling,\r\n    rpt_if_statement,\r\n    rpt_loop_statement,\r\n    rpt_go_statement,\r\n    rpt_stop_statement,\r\n    rpt_exit_statement,\r\n    rpt_variable,\r\n    rpt_constant,\r\n};\r\n\r\nenum rpv_tag\r\n{\r\n    rvt_string,\r\n    rvt_integer,\r\n    rvt_float,\r\n};\r\n\r\nenum rps_encoding\r\n{\r\n    rpe_ascii,\r\n    rpe_utf8,\r\n    rpe_utf16,\r\n    // ...\r\n};\r\n\r\ntypedef struct \r\n{\r\n    rps_encoding    encoding;\r\n    const char*     file;\r\n    char*           source;\r\n    char*           current;\r\n    int             length;\r\n    int             line;\r\n    int             position;\r\n}\r\nrgcontext;\r\n\r\ntypedef struct\r\n{\r\n    rps_encoding    encoding;\r\n    const rchar*    file;\r\n    char*           source;\r\n    char*           current;\r\n    int             length;\r\n    int             line;\r\n    int             position;\r\n    const rchar*    keyword;\r\n    rpsparser*      parser;\r\n    rpswrap*        wrapper;\r\n}\r\nrpscontext;\r\n\r\n#ifdef __cplusplus\r\nextern \"C\" {\r\n#endif\r\n\r\nextern void rathen_yy_setup(rgcontext* context, const char* file, rps_encoding encoding = rpe_utf8);\r\nextern void rathen_yy_ssetup(rgcontext* context, const char* file, char* source, int length, rps_encoding encoding = rpe_utf8);\r\nextern void rathen_yy_release(rgcontext* context);\r\nextern rpscontext* rathen_yy_select(rpscontext* context);\r\nextern void rathen_yy_parse(rpsparser* ps, const char* file);\r\nextern void rathen_yy_sparse(rpsparser* ps, const char* file, char* source, int length);\r\nextern int rathen_yy_read(char* buff, int* bytes, int cap);\r\n\r\nextern bool rathen_is_type(const rchar* str, int len = -1);\r\nextern bool rathen_is_keyword(const rchar* str, int len = -1);\r\nextern rpsparser* rathen_create_parser(const rchar* name);\r\nextern void rathen_destroy_parser(rpsparser* rps);\r\nextern rpswrap* rathen_get_root(rpsparser* rps);\r\nextern rpswrap* rathen_create_value(rpscontext* context, const rchar* name, const rchar* tyname, bool ref);\r\nextern rpswrap* rathen_create_function(rpscontext* context, const rchar* name, const rchar* retyname, bool retref);\r\nextern rpswrap* rathen_create_constant(rpscontext* context, const rchar* name, rpv_tag tag, const rchar* vstr);\r\n//extern rpswrap* rathen_create();\r\n\r\n#ifdef __cplusplus\r\n};\r\n#endif\r\n\r\n#endif\r\n", "meta": {"hexsha": "2550ca62721d3a7cccfa45ec1463e46cea7c078d", "size": 3139, "ext": "h", "lang": "C", "max_stars_repo_path": "include/rathen/rpsr.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/rathen/rpsr.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/rathen/rpsr.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 25.9421487603, "max_line_length": 128, "alphanum_fraction": 0.6807900605, "num_tokens": 861, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11279540031810142, "lm_q2_score": 0.0263553541844321, "lm_q1q2_score": 0.0029727627257583682}}
{"text": "//\n//  View.hpp\n//  PretendToWork\n//\n//  Created by tqtifnypmb on 14/12/2017.\n//  Copyright \u00a9 2017 tqtifnypmb. All rights reserved.\n//\n\n#pragma once\n\n#include \"../rope/Range.h\"\n#include \"../types.h\"\n#include \"../editor/Editor.h\"\n\n#include <memory>\n#include <utility>\n#include <gsl/gsl>\n#include <map>\n#include <string>\n\nnamespace brick\n{\n    \nclass View {\npublic:\n    \n    using UpdateCb = std::function<void(View* view, const Editor::DeltaList&)>;\n    \n    View(size_t viewId, UpdateCb cb);\n    View(size_t viewId, View* parent, UpdateCb cb);\n    View(size_t viewId, const std::string& filePath, UpdateCb cb);\n    \n    ~View();\n    \n    void scroll(size_t begRow, size_t endRow);\n    \n    template<class Converter>\n    void insert(gsl::span<const char> bytes);\n    void insert(const detail::CodePointList& cplist);\n    \n    void erase();\n    void undo();\n    void select(Range sel);\n    Range selection() const {\n        return sel_;\n    }\n    \n    void save();\n    void save(const std::string& filePath);\n    \n    template <class Converter>\n    std::map<size_t, std::string> region() {\n        return region<Converter>(visibleRange_.first, visibleRange_.second);\n    }\n    \n    template <class Converter>\n    std::map<size_t, std::string> region(size_t begRow, size_t endRow);\n    \n    size_t viewId() const {\n        return viewId_;\n    }\n    \n    size_t viewSize() const {\n        return viewSize_;\n    }\n    \n    bool hasChildren() const {\n        return !children_.empty();\n    }\n    \n    void removeChild(const View* child) {\n        auto found = std::find_if(children_.begin(), children_.end(), [child](const auto& v) { return v->viewId_ == child->viewId_; });\n        if (found != children_.end()) {\n            children_.erase(found);\n        }\n    }\n    \n    const std::vector<View*>& children() const {\n        return children_;\n    }\n    \n    const std::string filePath() const {\n        return filePath_;\n    }\n    \n    bool hasParent() const {\n        return parent() != nullptr;\n    }\n    \n    const View* parent() const {\n        return parent_;\n    }\n    \nprivate:\n    void editor_sync_cb(const Editor::DeltaList& deltaList);\n    void update(std::vector<View*>& src);\n    \n    std::map<size_t, detail::CodePointList> regionImpl(size_t begRow, size_t endRow);\n    std::map<size_t, detail::CodePointList> regionImpl() {\n        return regionImpl(visibleRange_.first, visibleRange_.second);\n    }\n    \n    UpdateCb update_cb_;\n    \n    std::pair<size_t, size_t> visibleRange_;\n    size_t viewId_;\n    size_t viewSize_;\n    View* parent_;\n    Range sel_;\n    std::vector<View*> children_;\n    std::unique_ptr<Editor> editor_;\n    std::string filePath_;\n};\n        \ntemplate<class Converter>\nvoid View::insert(gsl::span<const char> bytes) {\n    insert(Converter::encode(bytes));\n}\n    \ntemplate <class Converter>\nstd::map<size_t, std::string> View::region(size_t begRow, size_t endRow) {\n    auto lines = regionImpl(begRow, endRow);\n    std::map<size_t, std::string> ret;\n    for (const auto& line : lines) {\n        ret[line.first] = Converter::decode(line.second);\n    }\n    return ret;\n}\n    \n}\n", "meta": {"hexsha": "5dfea6789c3fa04d762c849a10e91e2be62844cc", "size": 3111, "ext": "h", "lang": "C", "max_stars_repo_path": "src/view/View.h", "max_stars_repo_name": "tqtifnypmb/brick", "max_stars_repo_head_hexsha": "49398f77113c57d4e256e838a5ad6b9a6381de6a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/view/View.h", "max_issues_repo_name": "tqtifnypmb/brick", "max_issues_repo_head_hexsha": "49398f77113c57d4e256e838a5ad6b9a6381de6a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/view/View.h", "max_forks_repo_name": "tqtifnypmb/brick", "max_forks_repo_head_hexsha": "49398f77113c57d4e256e838a5ad6b9a6381de6a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7480916031, "max_line_length": 135, "alphanum_fraction": 0.6171648987, "num_tokens": 788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1480471980316895, "lm_q2_score": 0.020023440521910296, "lm_q1q2_score": 0.0029644142642230096}}
{"text": "#ifndef __TEST_UTILS_H__\n#define __TEST_UTILS_H__\n\n#define THEN_WHEN(x)\n#define THEN_CHECK(x)\n\n#include <initializer_list>\n#include <memory>\n#include <string>\n#include <vector>\n\n#include <gsl/gsl>\n#include <gsl/string_span>\n\n#include \"base-utils/yaml.h\"\n#include \"config/path.h\"\n#include \"config/pattern.h\"\n#include \"plugins/pluginUtils.h\"\n\n#include \"executorStub.h\"\n\nnamespace execHelper {\nnamespace config {\nclass SettingsNode;\n} // namespace config\n\nnamespace test {\nnamespace baseUtils {\nclass ConfigFileWriter;\n} // namespace baseUtils\n} // namespace test\n} // namespace execHelper\n\nnamespace std {\ntemplate <typename T>\nstd::ostream& operator<<(std::ostream& os, const std::vector<T>& stream) {\n    for(const auto& element : stream) {\n        os << element << \", \";\n    }\n    return os;\n}\n\ntemplate <typename T, typename U>\nstd::ostream& operator<<(std::ostream& os, const std::pair<T, U>& stream) {\n    os << stream.first << \": \" << stream.second;\n    return os;\n}\n} // namespace std\n\nnamespace execHelper {\nnamespace test {\nnamespace utils {\nusing Patterns = std::vector<config::Pattern>;\n\nusing Arguments = std::vector<std::string>;\nstruct MainVariables {\n    int argc;\n    std::unique_ptr<char*[]> argv;\n\n    explicit MainVariables(const Arguments& arguments);\n};\n\ntemplate <typename T> void appendVectors(T& appendTo, const T& appendFrom) {\n    appendTo.insert(std::end(appendTo), std::begin(appendFrom),\n                    std::end(appendFrom));\n}\n\nbaseUtils::YamlWriter toYaml(const config::SettingsNode& settings,\n                             const config::Patterns& patterns) noexcept;\nvoid writeSettingsFile(\n    gsl::not_null<baseUtils::ConfigFileWriter*> configFileWriter,\n    const config::SettingsNode& settings,\n    const config::Patterns& patterns) noexcept;\nstd::string convertToConfig(const Patterns& patterns) noexcept;\nstd::string\nconvertToConfig(const config::SettingsNode& rootSettings,\n                const std::string& prepend = std::string()) noexcept;\nstd::string\nconvertToConfig(const config::SettingsNode& settings, const Patterns& patterns,\n                const std::string& prepend = std::string()) noexcept;\n\nstd::string convertToConfig(std::string key, std::string value,\n                            const std::string& prepend = std::string());\nstd::string convertToConfig(const std::string& key,\n                            const std::initializer_list<std::string>& values,\n                            const std::string& prepend = std::string());\nstd::string convertToConfig(const std::string& key,\n                            const std::vector<std::string>& values,\n                            const std::string& prepend = std::string());\n\nstd::string\nconvertToConfig(const std::initializer_list<std::string>& keys,\n                const std::string& value,\n                const std::string& prepend = std::string()) noexcept;\nstd::string\nconvertToConfig(const std::initializer_list<std::string>& keys,\n                const std::initializer_list<std::string>& values,\n                const std::string& prepend = std::string()) noexcept;\nstd::string\nconvertToConfig(const std::initializer_list<std::string>& keys,\n                const std::vector<std::string>& values,\n                const std::string& prepend = std::string()) noexcept;\nstd::string\nconvertToConfig(const std::vector<std::string>& keys,\n                const std::initializer_list<std::string>& values,\n                const std::string& prepend = std::string()) noexcept;\nstd::string\nconvertToConfig(const std::vector<std::string>& keys,\n                const std::vector<std::string>& values,\n                const std::string& prepend = std::string()) noexcept;\nstd::string basename(const std::string& file);\n\nconfig::PatternCombinations createPatternCombination(\n    const std::initializer_list<config::PatternKey>& keys,\n    const std::initializer_list<config::PatternValue>& values) noexcept;\n\nconfig::PatternCombinations\ncreatePatternCombination(const config::PatternKeys& keys,\n                         const config::PatternValues& values) noexcept;\nplugins::PatternPermutator\nmakePatternPermutator(const config::Patterns& patterns) noexcept;\ncore::test::ExecutorStub::TaskQueue\ngetExpectedTasks(const core::Task& task,\n                 const config::Patterns patterns) noexcept;\ncore::test::ExecutorStub::TaskQueue\ngetExpectedTasks(const core::test::ExecutorStub::TaskQueue& tasks,\n                 const config::Patterns patterns) noexcept;\n\nstd::string toString(const config::SettingsNode& settings,\n                     unsigned int nbOfTabs = 0) noexcept;\n\nstd::string inheritWorkingDirKey() noexcept;\nPatterns getPredefinedPatterns() noexcept;\n} // namespace utils\n} // namespace test\n} // namespace execHelper\n\n#endif /* __TEST_UTILS_H__ */\n", "meta": {"hexsha": "ef5f96a411e4563b2b675c0e2541a9416b0922e8", "size": 4770, "ext": "h", "lang": "C", "max_stars_repo_path": "test/utils/include/utils/utils.h", "max_stars_repo_name": "exec-helper/source", "max_stars_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-28T13:24:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-28T13:24:30.000Z", "max_issues_repo_path": "test/utils/include/utils/utils.h", "max_issues_repo_name": "exec-helper/source", "max_issues_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/utils/include/utils/utils.h", "max_forks_repo_name": "exec-helper/source", "max_forks_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-07-03T11:11:19.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-03T11:11:19.000Z", "avg_line_length": 34.3165467626, "max_line_length": 79, "alphanum_fraction": 0.6790356394, "num_tokens": 1032, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09807932874307332, "lm_q2_score": 0.03021458433846381, "lm_q1q2_score": 0.002963426150167507}}
{"text": "/* interpolation/accel.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Author:  G. Jungman\n */\n#include <config.h>\n#include <stdlib.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_interp.h>\n\ngsl_interp_accel *\ngsl_interp_accel_alloc (void)\n{\n  gsl_interp_accel *a = (gsl_interp_accel *) malloc (sizeof (gsl_interp_accel));\n  if (a == 0)\n    {\n      GSL_ERROR_NULL(\"could not allocate space for gsl_interp_accel\", GSL_ENOMEM);\n    }\n\n  a->cache = 0;\n  a->hit_count = 0;\n  a->miss_count = 0;\n\n  return a;\n}\n\nint\ngsl_interp_accel_reset (gsl_interp_accel * a)\n{\n  a->cache = 0;\n  a->hit_count = 0;\n  a->miss_count = 0;\n\n  return GSL_SUCCESS;\n}\n\nvoid\ngsl_interp_accel_free (gsl_interp_accel * a)\n{\n  RETURN_IF_NULL (a);\n  free (a);\n}\n", "meta": {"hexsha": "00063fd8c9c56882827ac1ebf2c65a5ea9b877db", "size": 1480, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/interpolation/accel.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/interpolation/accel.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/interpolation/accel.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 25.0847457627, "max_line_length": 82, "alphanum_fraction": 0.7074324324, "num_tokens": 415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15203223393803664, "lm_q2_score": 0.019419347366663217, "lm_q1q2_score": 0.002952366761772538}}
{"text": "#pragma once\n\n#include <memory>\n#include \"halley/text/halleystring.h\"\n#include \"halley/core/graphics/texture.h\"\n#include <gsl/gsl>\n\nnamespace Halley\n{\n\tenum class ShaderType;\n\tclass MaterialDataBlock;\n\tclass Material;\n\tenum class ShaderParameterType;\n\tclass Painter;\n\tclass MaterialDefinition;\n\tclass MaterialParameter;\n\tclass MaterialTextureParameter;\n\tclass VideoAPI;\n\n\tclass MaterialConstantBuffer\n\t{\n\tpublic:\n\t\tvirtual ~MaterialConstantBuffer() {}\n\n\t\tvirtual void update(const MaterialDataBlock& dataBlock) = 0;\n\t};\n\n\tenum class MaterialDataBlockType\n\t{\n\t\t// Shared blocks are not stored locally in the material (e.g. the HalleyBlock, stored by the engine)\n\t\tSharedLocal,    // Shared, this keeps the canonical copy\n\t\tSharedExternal, // Shared, only a reference\n\t\tLocal           // Local data\n\t};\n\n\tclass MaterialDataBlock\n\t{\n\t\tfriend class Material;\n\n\tpublic:\n\t\tMaterialDataBlock();\n\t\tMaterialDataBlock(MaterialDataBlockType type, size_t size, int bindPoint, const String& name, const MaterialDefinition& def);\n\t\tMaterialDataBlock(const MaterialDataBlock& other);\n\t\tMaterialDataBlock(MaterialDataBlock&& other) noexcept;\n\n\t\tMaterialConstantBuffer& getConstantBuffer() const;\n\t\tint getAddress(int pass, ShaderType stage) const;\n\t\tint getBindPoint() const;\n\t\tgsl::span<const gsl::byte> getData() const;\n\t\tMaterialDataBlockType getType() const;\n\n\tprivate:\n\t\tstd::unique_ptr<MaterialConstantBuffer> constantBuffer;\n\t\tBytes data;\n\t\tVector<int> addresses;\n\t\tMaterialDataBlockType dataBlockType;\n\t\tint bindPoint = 0;\n\t\tbool dirty = true;\n\n\t\tbool setUniform(size_t offset, ShaderParameterType type, const void* data);\n\t\tvoid upload(VideoAPI* api);\n\t};\n\t\n\tclass Material\n\t{\n\t\tfriend class MaterialParameter;\n\n\tpublic:\n\t\tMaterial(const Material& other);\n\t\texplicit Material(std::shared_ptr<const MaterialDefinition> materialDefinition, bool forceLocalBlocks = false); // forceLocalBlocks is for engine use only\n\n\t\tvoid bind(int pass, Painter& painter);\n\t\tvoid uploadData(Painter& painter);\n\t\tstatic void resetBindCache();\n\n\t\tbool operator==(const Material& material) const;\n\t\tbool operator!=(const Material& material) const;\n\n\t\tconst MaterialDefinition& getDefinition() const { return *materialDefinition; }\n\n\t\tstd::shared_ptr<Material> clone() const;\n\t\t\n\t\tconst std::shared_ptr<const Texture>& getTexture(int textureUnit) const;\n\t\tconst Vector<MaterialTextureParameter>& getTextureUniforms() const;\n\t\tconst std::vector<std::shared_ptr<const Texture>>& getTextures() const;\n\n\t\tconst Vector<MaterialParameter>& getUniforms() const;\n\t\tconst Vector<MaterialDataBlock>& getDataBlocks() const;\n\n\t\tvoid setPassEnabled(int pass, bool enabled);\n\t\tbool isPassEnabled(int pass) const;\n\n\t\tMaterial& set(const String& name, const std::shared_ptr<const Texture>& texture);\n\t\tMaterial& set(const String& name, const std::shared_ptr<Texture>& texture);\n\n\t\tbool hasParameter(const String& name) const;\n\n\t\ttemplate <typename T>\n\t\tMaterial& set(const String& name, const T& value)\n\t\t{\n\t\t\tgetParameter(name) = value;\n\t\t\treturn *this;\n\t\t}\n\n\t\tuint64_t getHash() const;\n\n\tprivate:\n\t\tstd::shared_ptr<const MaterialDefinition> materialDefinition;\n\t\t\n\t\tVector<MaterialParameter> uniforms;\n\t\tVector<MaterialTextureParameter> textureUniforms;\n\t\tVector<MaterialDataBlock> dataBlocks;\n\t\tstd::vector<std::shared_ptr<const Texture>> textures;\n\n\t\tstd::vector<char> passEnabled;\n\n\t\tmutable uint64_t hashValue = 0;\n\t\tmutable bool needToUpdateHash = true;\n\t\tbool needToUploadData = true;\n\n\t\tvoid initUniforms(bool forceLocalBlocks);\n\t\tMaterialParameter& getParameter(const String& name);\n\n\t\tvoid setUniform(int blockNumber, size_t offset, ShaderParameterType type, const void* data);\n\t\tuint64_t computeHash() const;\n\n\t\tconst std::shared_ptr<const Texture>& getFallbackTexture() const;\n\t};\n}\n", "meta": {"hexsha": "65801cc3f62382e63f716241b802fa07629840c4", "size": 3752, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engine/core/include/halley/core/graphics/material/material.h", "max_stars_repo_name": "Bearwaves/halley", "max_stars_repo_head_hexsha": "dcd5ad2631eadd40ec952355577ac0d894d530d4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/engine/core/include/halley/core/graphics/material/material.h", "max_issues_repo_name": "Bearwaves/halley", "max_issues_repo_head_hexsha": "dcd5ad2631eadd40ec952355577ac0d894d530d4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engine/core/include/halley/core/graphics/material/material.h", "max_forks_repo_name": "Bearwaves/halley", "max_forks_repo_head_hexsha": "dcd5ad2631eadd40ec952355577ac0d894d530d4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8615384615, "max_line_length": 156, "alphanum_fraction": 0.7595948827, "num_tokens": 888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16667540468797665, "lm_q2_score": 0.01771230239785177, "lm_q1q2_score": 0.002952205170117763}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef style_ac50d5be_0f99_48dc_908f_ab8a309b2a27_h\r\n#define style_ac50d5be_0f99_48dc_908f_ab8a309b2a27_h\r\n\r\n#include <gslib/string.h>\r\n#include <gslib/std.h>\r\n#include <ariel/type.h>\r\n#include <ariel/painter.h>\r\n\r\n__ariel_begin__\r\n\r\nenum style_sheet_type\r\n{\r\n    sst_unknown     = -1,\r\n    sst_color       = 0,\r\n    sst_integer,\r\n    sst_boolean,\r\n    sst_float,\r\n    sst_string,\r\n    sst_capacity,\r\n};\r\n\r\nextern const string& get_style_sheet_type_name(style_sheet_type sst);\r\ntypedef std::pair<style_sheet_type, string> style_sheet_def;\r\ntypedef unordered_map<string, int> style_sheet_info_map;\r\n\r\nstruct accel_key;\r\n\r\nclass __gs_novtable style_sheet abstract\r\n{\r\npublic:\r\n    static const int npos = -1;\r\n\r\npublic:\r\n    style_sheet(const style_sheet_def* ssp, int len);\r\n    virtual ~style_sheet() {}\r\n    virtual bool get_value(const string& name, string& value) = 0;\r\n    virtual void set_value(const string& name, const string& value) = 0;\r\n    virtual int get_content_size() const { return _ss_length; }\r\n    virtual style_sheet_type get_content_type(int index) const;\r\n    virtual const string& get_content_name(int index) const;\r\n    virtual void flush_style() = 0;\r\n\r\nprotected:\r\n    const style_sheet_def*  _ss_pairs;\r\n    int                     _ss_length;\r\n    style_sheet_info_map    _ss_info;\r\n\r\npublic:\r\n    void initialize_style_sheet(const style_sheet_def* ssp, int len);\r\n    int get_style_sheet_index(const string& name) const;\r\n\r\nprotected:\r\n    static bool from_color(string& str, const color& cr);\r\n    static bool to_color(color& cr, const string& str);\r\n    static bool from_integer(string& str, int i);\r\n    static bool to_integer(int& i, const string& str);\r\n    static bool from_boolean(string& str, bool b);\r\n    static bool to_boolean(bool& b, const string& str);\r\n    static bool from_float(string& str, float f);\r\n    static bool to_float(float& f, const string& str);\r\n    static bool from_accel_key(string& str, const accel_key& k);\r\n    static bool to_accel_key(accel_key& k, const string& str);\r\n    static void setup_brush_by_color(painter_brush& brush, const color& cr);\r\n    static void setup_pen_by_color(painter_pen& pen, const color& cr);\r\n    static void setup_font(font& ft, const string& name, int size);\r\n};\r\n\r\n__ariel_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "020997dbdc30042ada61929e47f83a256ac7da32", "size": 3548, "ext": "h", "lang": "C", "max_stars_repo_path": "include/ariel/style.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/ariel/style.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ariel/style.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 36.2040816327, "max_line_length": 82, "alphanum_fraction": 0.7201240135, "num_tokens": 854, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08269734493579813, "lm_q2_score": 0.035678553825659445, "lm_q1q2_score": 0.002950521672530999}}
{"text": "#pragma once\n\n#include <cstring>\n#include <string>\n#include <sstream>\n#include <iomanip>\n#include <array>\n#include <string_view>\n#include <iterator>\n#include <random>\n#include <memory>\n#include <functional>\n#include <type_traits>\n#include <assert.h>\n#include <gsl/span>\n\n#ifdef _WIN32\n#include <objbase.h>\n#elif defined(__linux__) || defined(__unix__)\n#include <uuid/uuid.h>\n#elif defined(__APPLE__)\n#include <CoreFoundation/CFUUID.h>\n#endif\n\nnamespace uuids\n{\n   namespace detail\n   {\n      template <typename TChar>\n      constexpr inline unsigned char hex2char(TChar const ch)\n      {\n         if (ch >= static_cast<TChar>('0') && ch <= static_cast<TChar>('9'))\n            return static_cast<unsigned char>(ch - static_cast<TChar>('0'));\n         if (ch >= static_cast<TChar>('a') && ch <= static_cast<TChar>('f'))\n            return static_cast<unsigned char>(10 + ch - static_cast<TChar>('a'));\n         if (ch >= static_cast<TChar>('A') && ch <= static_cast<TChar>('F'))\n            return static_cast<unsigned char>(10 + ch - static_cast<TChar>('A'));\n         return 0;\n      }\n\n      template <typename TChar>\n      constexpr inline bool is_hex(TChar const ch)\n      {\n         return\n            (ch >= static_cast<TChar>('0') && ch <= static_cast<TChar>('9')) ||\n            (ch >= static_cast<TChar>('a') && ch <= static_cast<TChar>('f')) ||\n            (ch >= static_cast<TChar>('A') && ch <= static_cast<TChar>('F'));\n      }\n\n      template <typename TChar>\n      constexpr inline unsigned char hexpair2char(TChar const a, TChar const b)\n      {\n         return static_cast<unsigned char>((hex2char(a) << 4) | hex2char(b));\n      }\n\n      class sha1\n      {\n      public:\n         using digest32_t = uint32_t[5];\n         using digest8_t = uint8_t[20];\n\n         static constexpr unsigned int block_bytes = 64;\n\n         inline static uint32_t left_rotate(uint32_t value, size_t const count) \n         {\n            return (value << count) ^ (value >> (32 - count));\n         }\n\n         sha1() { reset(); }\n\n         void reset() \n         {\n            m_digest[0] = 0x67452301;\n            m_digest[1] = 0xEFCDAB89;\n            m_digest[2] = 0x98BADCFE;\n            m_digest[3] = 0x10325476;\n            m_digest[4] = 0xC3D2E1F0;\n            m_blockByteIndex = 0;\n            m_byteCount = 0;\n         }\n\n         void process_byte(uint8_t octet) \n         {\n            this->m_block[this->m_blockByteIndex++] = octet;\n            ++this->m_byteCount;\n            if (m_blockByteIndex == block_bytes)\n            {\n               this->m_blockByteIndex = 0;\n               process_block();\n            }\n         }\n\n         void process_block(void const * const start, void const * const end) \n         {\n            const uint8_t* begin = static_cast<const uint8_t*>(start);\n            const uint8_t* finish = static_cast<const uint8_t*>(end);\n            while (begin != finish) \n            {\n               process_byte(*begin);\n               begin++;\n            }\n         }\n\n         void process_bytes(void const * const data, size_t const len)\n         {\n            const uint8_t* block = static_cast<const uint8_t*>(data);\n            process_block(block, block + len);\n         }\n\n         uint32_t const * get_digest(digest32_t digest) \n         {\n            size_t const bitCount = this->m_byteCount * 8;\n            process_byte(0x80);\n            if (this->m_blockByteIndex > 56) {\n               while (m_blockByteIndex != 0) {\n                  process_byte(0);\n               }\n               while (m_blockByteIndex < 56) {\n                  process_byte(0);\n               }\n            }\n            else {\n               while (m_blockByteIndex < 56) {\n                  process_byte(0);\n               }\n            }\n            process_byte(0);\n            process_byte(0);\n            process_byte(0);\n            process_byte(0);\n            process_byte(static_cast<unsigned char>((bitCount >> 24) & 0xFF));\n            process_byte(static_cast<unsigned char>((bitCount >> 16) & 0xFF));\n            process_byte(static_cast<unsigned char>((bitCount >> 8) & 0xFF));\n            process_byte(static_cast<unsigned char>((bitCount) & 0xFF));\n\n            memcpy(digest, m_digest, 5 * sizeof(uint32_t));\n            return digest;\n         }\n\n         uint8_t const * get_digest_bytes(digest8_t digest) \n         {\n            digest32_t d32;\n            get_digest(d32);\n            size_t di = 0;\n            digest[di++] = (uint8_t)((d32[0] >> 24) & 0xFF);\n            digest[di++] = (uint8_t)((d32[0] >> 16) & 0xFF);\n            digest[di++] = (uint8_t)((d32[0] >> 8) & 0xFF);\n            digest[di++] = (uint8_t)((d32[0]) & 0xFF);\n\n            digest[di++] = (uint8_t)((d32[1] >> 24) & 0xFF);\n            digest[di++] = (uint8_t)((d32[1] >> 16) & 0xFF);\n            digest[di++] = (uint8_t)((d32[1] >> 8) & 0xFF);\n            digest[di++] = (uint8_t)((d32[1]) & 0xFF);\n\n            digest[di++] = (uint8_t)((d32[2] >> 24) & 0xFF);\n            digest[di++] = (uint8_t)((d32[2] >> 16) & 0xFF);\n            digest[di++] = (uint8_t)((d32[2] >> 8) & 0xFF);\n            digest[di++] = (uint8_t)((d32[2]) & 0xFF);\n\n            digest[di++] = (uint8_t)((d32[3] >> 24) & 0xFF);\n            digest[di++] = (uint8_t)((d32[3] >> 16) & 0xFF);\n            digest[di++] = (uint8_t)((d32[3] >> 8) & 0xFF);\n            digest[di++] = ((d32[3]) & 0xFF);\n\n            digest[di++] = (uint8_t)((d32[4] >> 24) & 0xFF);\n            digest[di++] = (uint8_t)((d32[4] >> 16) & 0xFF);\n            digest[di++] = (uint8_t)((d32[4] >> 8) & 0xFF);\n            digest[di++] = (uint8_t)((d32[4]) & 0xFF);\n\n            return digest;\n         }\n\n      private:\n         void process_block() \n         {\n            uint32_t w[80];\n            for (size_t i = 0; i < 16; i++) {\n               w[i] = (m_block[i * 4 + 0] << 24);\n               w[i] |= (m_block[i * 4 + 1] << 16);\n               w[i] |= (m_block[i * 4 + 2] << 8);\n               w[i] |= (m_block[i * 4 + 3]);\n            }\n            for (size_t i = 16; i < 80; i++) {\n               w[i] = left_rotate((w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]), 1);\n            }\n\n            uint32_t a = m_digest[0];\n            uint32_t b = m_digest[1];\n            uint32_t c = m_digest[2];\n            uint32_t d = m_digest[3];\n            uint32_t e = m_digest[4];\n\n            for (std::size_t i = 0; i < 80; ++i) \n            {\n               uint32_t f = 0;\n               uint32_t k = 0;\n\n               if (i < 20) {\n                  f = (b & c) | (~b & d);\n                  k = 0x5A827999;\n               }\n               else if (i < 40) {\n                  f = b ^ c ^ d;\n                  k = 0x6ED9EBA1;\n               }\n               else if (i < 60) {\n                  f = (b & c) | (b & d) | (c & d);\n                  k = 0x8F1BBCDC;\n               }\n               else {\n                  f = b ^ c ^ d;\n                  k = 0xCA62C1D6;\n               }\n               uint32_t temp = left_rotate(a, 5) + f + e + k + w[i];\n               e = d;\n               d = c;\n               c = left_rotate(b, 30);\n               b = a;\n               a = temp;\n            }\n\n            m_digest[0] += a;\n            m_digest[1] += b;\n            m_digest[2] += c;\n            m_digest[3] += d;\n            m_digest[4] += e;\n         }\n\n      private:\n         digest32_t m_digest;\n         uint8_t m_block[64];\n         size_t m_blockByteIndex;\n         size_t m_byteCount;\n      };\n   }\n\n   // UUID format https://tools.ietf.org/html/rfc4122\n   // Field\t                     NDR Data Type\t   Octet #\tNote\n   // --------------------------------------------------------------------------------------------------------------------------\n   // time_low\t                  unsigned long\t   0 - 3\t   The low field of the timestamp.\n   // time_mid\t                  unsigned short\t   4 - 5\t   The middle field of the timestamp.\n   // time_hi_and_version\t      unsigned short\t   6 - 7\t   The high field of the timestamp multiplexed with the version number.\n   // clock_seq_hi_and_reserved\tunsigned small\t   8\t      The high field of the clock sequence multiplexed with the variant.\n   // clock_seq_low\t            unsigned small\t   9\t      The low field of the clock sequence.\n   // node\t                     character\t      10 - 15\tThe spatially unique node identifier.\n   // --------------------------------------------------------------------------------------------------------------------------\n   // 0                   1                   2                   3\n   //  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n   // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n   // |                          time_low                             |\n   // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n   // |       time_mid                |         time_hi_and_version   |\n   // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n   // |clk_seq_hi_res |  clk_seq_low  |         node (0-1)            |\n   // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n   // |                         node (2-5)                            |\n   // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\n   // indicated by a bit pattern in octet 8, marked with N in xxxxxxxx-xxxx-xxxx-Nxxx-xxxxxxxxxxxx\n   enum class uuid_variant\n   {\n      // NCS backward compatibility (with the obsolete Apollo Network Computing System 1.5 UUID format)\n      // N bit pattern: 0xxx\n      // > the first 6 octets of the UUID are a 48-bit timestamp (the number of 4 microsecond units of time since 1 Jan 1980 UTC);\n      // > the next 2 octets are reserved;\n      // > the next octet is the \"address family\"; \n      // > the final 7 octets are a 56-bit host ID in the form specified by the address family\n      ncs,\n      \n      // RFC 4122/DCE 1.1 \n      // N bit pattern: 10xx\n      // > big-endian byte order\n      rfc,\n      \n      // Microsoft Corporation backward compatibility\n      // N bit pattern: 110x\n      // > little endian byte order\n      // > formely used in the Component Object Model (COM) library      \n      microsoft,\n      \n      // reserved for possible future definition\n      // N bit pattern: 111x      \n      reserved\n   };\n\n   struct uuid_error : public std::runtime_error\n   {\n      explicit uuid_error(std::string_view message)\n         : std::runtime_error(message.data())\n      {\n      }\n\n      explicit uuid_error(char const * message)\n         : std::runtime_error(message)\n      {\n      }\n   };\n\n   // indicated by a bit pattern in octet 6, marked with M in xxxxxxxx-xxxx-Mxxx-xxxx-xxxxxxxxxxxx\n   enum class uuid_version\n   {\n      none = 0, // only possible for nil or invalid uuids\n      time_based = 1,  // The time-based version specified in RFC 4122\n      dce_security = 2,  // DCE Security version, with embedded POSIX UIDs.\n      name_based_md5 = 3,  // The name-based version specified in RFS 4122 with MD5 hashing\n      random_number_based = 4,  // The randomly or pseudo-randomly generated version specified in RFS 4122\n      name_based_sha1 = 5   // The name-based version specified in RFS 4122 with SHA1 hashing\n   };\n\n   struct uuid\n   {\n      struct uuid_const_iterator\n      {\n         using self_type         = uuid_const_iterator;\n         using value_type        = uint8_t;\n         using reference         = uint8_t const &;\n         using pointer           = uint8_t const *;\n         using iterator_category = std::random_access_iterator_tag;\n         using difference_type   = ptrdiff_t;\n\n      protected:\n         pointer ptr = nullptr;\n         size_t  index = 0;\n\n         bool compatible(self_type const & other) const noexcept\n         {\n            return ptr == other.ptr;\n         }\n\n      public:\n         constexpr explicit uuid_const_iterator(pointer ptr, size_t const index) :\n            ptr(ptr), index(index)\n         {\n         }\n\n         uuid_const_iterator(uuid_const_iterator const & o) = default;\n         uuid_const_iterator& operator=(uuid_const_iterator const & o) = default;\n         ~uuid_const_iterator() = default;\n\n         self_type & operator++ ()\n         {\n            if (index >= 16)\n               throw std::out_of_range(\"Iterator cannot be incremented past the end of the data.\");\n            ++index;\n            return *this;\n         }\n\n         self_type operator++ (int)\n         {\n            self_type tmp = *this;\n            ++*this;\n            return tmp;\n         }\n\n         bool operator== (self_type const & other) const\n         {\n            assert(compatible(other));\n            return index == other.index;\n         }\n\n         bool operator!= (self_type const & other) const\n         {\n            return !(*this == other);\n         }\n\n         reference operator* () const\n         {\n            if (ptr == nullptr)\n               throw std::bad_function_call();\n            return *(ptr + index);\n         }\n\n         reference operator-> () const\n         {\n            if (ptr == nullptr)\n               throw std::bad_function_call();\n            return *(ptr + index);\n         }\n\n         uuid_const_iterator() = default;\n\n         self_type & operator--()\n         {\n            if (index <= 0)\n               throw std::out_of_range(\"Iterator cannot be decremented past the beginning of the data.\");\n            --index;\n            return *this;\n         }\n\n         self_type operator--(int)\n         {\n            self_type tmp = *this;\n            --*this;\n            return tmp;\n         }\n\n         self_type operator+(difference_type offset) const\n         {\n            self_type tmp = *this;\n            return tmp += offset;\n         }\n\n         self_type operator-(difference_type offset) const\n         {\n            self_type tmp = *this;\n            return tmp -= offset;\n         }\n\n         difference_type operator-(self_type const & other) const\n         {\n            assert(compatible(other));\n            return (index - other.index);\n         }\n\n         bool operator<(self_type const & other) const\n         {\n            assert(compatible(other));\n            return index < other.index;\n         }\n\n         bool operator>(self_type const & other) const\n         {\n            return other < *this;\n         }\n\n         bool operator<=(self_type const & other) const\n         {\n            return !(other < *this);\n         }\n\n         bool operator>=(self_type const & other) const\n         {\n            return !(*this < other);\n         }\n\n         self_type & operator+=(difference_type const offset)\n         {\n            if (static_cast<difference_type>(index) + offset < 0 ||\n               static_cast<difference_type>(index) + offset > 16)\n               throw std::out_of_range(\"Iterator cannot be incremented outside data bounds.\");\n\n            index += offset;\n            return *this;\n         }\n\n         self_type & operator-=(difference_type const offset)\n         {\n            return *this += -offset;\n         }\n\n         value_type const & operator[](difference_type const offset) const\n         {\n            return (*(*this + offset));\n         }\n      };\n\n      using value_type = uint8_t;\n\n   public:\n      constexpr uuid() noexcept : data({}) {};\n\n      explicit uuid(gsl::span<value_type, 16> bytes)\n      {\n         std::copy(std::cbegin(bytes), std::cend(bytes), std::begin(data));\n      }\n      \n      template<typename ForwardIterator>\n      explicit uuid(ForwardIterator first, ForwardIterator last)\n      {\n         if (std::distance(first, last) == 16)\n            std::copy(first, last, std::begin(data));\n      }\n      \n      constexpr uuid_variant variant() const noexcept\n      {\n         if ((data[8] & 0x80) == 0x00)\n            return uuid_variant::ncs;\n         else if ((data[8] & 0xC0) == 0x80)\n            return uuid_variant::rfc;\n         else if ((data[8] & 0xE0) == 0xC0)\n            return uuid_variant::microsoft;\n         else\n            return uuid_variant::reserved;\n      }\n\n      constexpr uuid_version version() const noexcept\n      {\n         if ((data[6] & 0xF0) == 0x10)\n            return uuid_version::time_based;\n         else if ((data[6] & 0xF0) == 0x20)\n            return uuid_version::dce_security;\n         else if ((data[6] & 0xF0) == 0x30)\n            return uuid_version::name_based_md5;\n         else if ((data[6] & 0xF0) == 0x40)\n            return uuid_version::random_number_based;\n         else if ((data[6] & 0xF0) == 0x50)\n            return uuid_version::name_based_sha1;\n         else\n            return uuid_version::none;\n      }\n\n      constexpr std::size_t size() const noexcept { return 16; }\n\n      constexpr bool is_nil() const noexcept\n      {\n         for (size_t i = 0; i < data.size(); ++i) if (data[i] != 0) return false;\n         return true;\n      }\n\n      void swap(uuid & other) noexcept\n      {\n         data.swap(other.data);\n      }\n\n      constexpr uuid_const_iterator begin() const noexcept { return uuid_const_iterator(&data[0], 0); }\n      constexpr uuid_const_iterator end() const noexcept { return uuid_const_iterator(&data[0], 16); }\n\n      inline gsl::span<std::byte const, 16> as_bytes() const\n      {\n         return gsl::span<std::byte const, 16>(reinterpret_cast<std::byte const*>(data.data()), 16);\n      }\n\n      template <typename TChar>\n      static uuid from_string(TChar const * const str, size_t const size)\n      {\n         TChar digit = 0;\n         bool firstDigit = true;\n         int hasBraces = 0;\n         size_t index = 0;\n         std::array<uint8_t, 16> data{ { 0 } };\n\n         if (str == nullptr || size == 0)\n            throw uuid_error{ \"Wrong uuid format\" };\n\n         if (str[0] == static_cast<TChar>('{'))\n            hasBraces = 1;\n         if (hasBraces && str[size - 1] != static_cast<TChar>('}'))\n            throw uuid_error{ \"Wrong uuid format\" };\n\n         for (size_t i = hasBraces; i < size - hasBraces; ++i)\n         {\n            if (str[i] == static_cast<TChar>('-')) continue;\n\n            if (index >= 16 || !detail::is_hex(str[i]))\n            {\n               throw uuid_error{ \"Wrong uuid format\" };\n            }\n\n            if (firstDigit)\n            {\n               digit = str[i];\n               firstDigit = false;\n            }\n            else\n            {\n               data[index++] = detail::hexpair2char(digit, str[i]);\n               firstDigit = true;\n            }\n         }\n\n         if (index < 16)\n         {\n            throw uuid_error{ \"Wrong uuid format\" };\n         }\n\n         return uuid{ std::cbegin(data), std::cend(data) };\n      }\n\n      static uuid from_string(std::string_view str)\n      {\n         return from_string(str.data(), str.size());\n      }\n\n      static uuid from_string(std::wstring_view str)\n      {\n         return from_string(str.data(), str.size());\n      }\n\n   private:\n      std::array<value_type, 16> data{ { 0 } };\n\n      friend bool operator==(uuid const & lhs, uuid const & rhs) noexcept;\n      friend bool operator<(uuid const & lhs, uuid const & rhs) noexcept;\n\n      template <class Elem, class Traits>\n      friend std::basic_ostream<Elem, Traits> & operator<<(std::basic_ostream<Elem, Traits> &s, uuid const & id);  \n   };\n\n   inline bool operator== (uuid const& lhs, uuid const& rhs) noexcept\n   {\n      return lhs.data == rhs.data;\n   }\n\n   inline bool operator!= (uuid const& lhs, uuid const& rhs) noexcept\n   {\n      return !(lhs == rhs);\n   }\n\n   inline bool operator< (uuid const& lhs, uuid const& rhs) noexcept\n   {\n      return lhs.data < rhs.data;\n   }\n\n   template <class Elem, class Traits>\n   std::basic_ostream<Elem, Traits> & operator<<(std::basic_ostream<Elem, Traits> &s, uuid const & id)\n   {\n      return s << std::hex << std::setfill(static_cast<Elem>('0'))\n         << std::setw(2) << (int)id.data[0]\n         << std::setw(2) << (int)id.data[1]\n         << std::setw(2) << (int)id.data[2]\n         << std::setw(2) << (int)id.data[3]\n         << '-'\n         << std::setw(2) << (int)id.data[4]\n         << std::setw(2) << (int)id.data[5]\n         << '-'\n         << std::setw(2) << (int)id.data[6]\n         << std::setw(2) << (int)id.data[7]\n         << '-'\n         << std::setw(2) << (int)id.data[8]\n         << std::setw(2) << (int)id.data[9]\n         << '-'\n         << std::setw(2) << (int)id.data[10]\n         << std::setw(2) << (int)id.data[11]\n         << std::setw(2) << (int)id.data[12]\n         << std::setw(2) << (int)id.data[13]\n         << std::setw(2) << (int)id.data[14]\n         << std::setw(2) << (int)id.data[15];\n   }\n\n   inline std::string to_string(uuid const & id)\n   {\n      std::stringstream sstr;\n      sstr << id;\n      return sstr.str();\n   }\n\n   inline std::wstring to_wstring(uuid const & id)\n   {\n      std::wstringstream sstr;\n      sstr << id;\n      return sstr.str();\n   }\n\n   inline void swap(uuids::uuid & lhs, uuids::uuid & rhs)\n   {\n      lhs.swap(rhs);\n   }\n\n   class uuid_system_generator\n   {\n   public:\n      using result_type = uuid;\n\n      uuid operator()()\n      {\n#ifdef _WIN32\n\n         GUID newId;\n         ::CoCreateGuid(&newId);\n\n         std::array<uint8_t, 16> bytes =\n         { {\n               (unsigned char)((newId.Data1 >> 24) & 0xFF),\n               (unsigned char)((newId.Data1 >> 16) & 0xFF),\n               (unsigned char)((newId.Data1 >> 8) & 0xFF),\n               (unsigned char)((newId.Data1) & 0xFF),\n\n               (unsigned char)((newId.Data2 >> 8) & 0xFF),\n               (unsigned char)((newId.Data2) & 0xFF),\n\n               (unsigned char)((newId.Data3 >> 8) & 0xFF),\n               (unsigned char)((newId.Data3) & 0xFF),\n\n               newId.Data4[0],\n               newId.Data4[1],\n               newId.Data4[2],\n               newId.Data4[3],\n               newId.Data4[4],\n               newId.Data4[5],\n               newId.Data4[6],\n               newId.Data4[7]\n            } };\n\n         return uuid{ std::begin(bytes), std::end(bytes) };\n\n#elif defined(__linux__) || defined(__unix__)\n\n         uuid_t id;\n         uuid_generate(id);\n\n         std::array<uint8_t, 16> bytes =\n         { {\n               id[0],\n               id[1],\n               id[2],\n               id[3],\n               id[4],\n               id[5],\n               id[6],\n               id[7],\n               id[8],\n               id[9],\n               id[10],\n               id[11],\n               id[12],\n               id[13],\n               id[14],\n               id[15]\n            } };\n\n         return uuid{ std::begin(bytes), std::end(bytes) };\n\n#elif defined(__APPLE__)\n         auto newId = CFUUIDCreate(NULL);\n         auto bytes = CFUUIDGetUUIDBytes(newId);\n         CFRelease(newId);\n\n         std::array<uint8_t, 16> arrbytes =\n         { {\n               bytes.byte0,\n               bytes.byte1,\n               bytes.byte2,\n               bytes.byte3,\n               bytes.byte4,\n               bytes.byte5,\n               bytes.byte6,\n               bytes.byte7,\n               bytes.byte8,\n               bytes.byte9,\n               bytes.byte10,\n               bytes.byte11,\n               bytes.byte12,\n               bytes.byte13,\n               bytes.byte14,\n               bytes.byte15\n            } };\n         return uuid{ std::begin(arrbytes), std::end(arrbytes) };\n#elif\n         return uuid{};\n#endif\n      }\n   };\n\n   template <typename UniformRandomNumberGenerator>\n   class basic_uuid_random_generator \n   {\n   public:\n      using result_type = uuid;\n\n      basic_uuid_random_generator()\n         :generator(new UniformRandomNumberGenerator)\n      {\n         std::random_device rd;\n         generator->seed(rd());\n      }\n\n      explicit basic_uuid_random_generator(UniformRandomNumberGenerator& gen) :\n         generator(&gen, [](auto) {}) {}\n      explicit basic_uuid_random_generator(UniformRandomNumberGenerator* gen) :\n         generator(gen, [](auto) {}) {}\n\n      uuid operator()()\n      {\n         uint8_t bytes[16];\n         for (int i = 0; i < 16; i += 4)\n            *reinterpret_cast<uint32_t*>(bytes + i) = distribution(*generator);\n\n         // variant must be 10xxxxxx\n         bytes[8] &= 0xBF;\n         bytes[8] |= 0x80;\n\n         // version must be 0100xxxx\n         bytes[6] &= 0x4F;\n         bytes[6] |= 0x40;\n\n         return uuid{std::begin(bytes), std::end(bytes)};\n      }\n\n   private:\n      std::uniform_int_distribution<uint32_t>  distribution;\n      std::shared_ptr<UniformRandomNumberGenerator> generator;\n   };\n\n   using uuid_random_generator = basic_uuid_random_generator<std::mt19937>;\n   \n   class uuid_name_generator\n   {\n   public:\n      using result_type = uuid;\n\n      explicit uuid_name_generator(uuid const& namespace_uuid) noexcept\n         : nsuuid(namespace_uuid)\n      {}\n\n      uuid operator()(std::string_view name)\n      {\n         reset();\n         process_characters(name.data(), name.size());\n         return make_uuid();\n      }\n\n      uuid operator()(std::wstring_view name)\n      {\n         reset();\n         process_characters(name.data(), name.size());\n         return make_uuid();\n      }\n\n   private:\n      void reset() \n      {\n         hasher.reset();\n         uint8_t bytes[16];\n         std::copy(std::begin(nsuuid), std::end(nsuuid), bytes);\n         hasher.process_bytes(bytes, 16);\n      }\n      \n      template <typename char_type,\n                typename = std::enable_if_t<std::is_integral<char_type>::value>>\n      void process_characters(char_type const * const characters, size_t const count)\n      {\n         for (size_t i = 0; i < count; i++) \n         {\n            uint32_t c = characters[i];\n            hasher.process_byte(static_cast<unsigned char>((c >> 0) & 0xFF));\n            hasher.process_byte(static_cast<unsigned char>((c >> 8) & 0xFF));\n            hasher.process_byte(static_cast<unsigned char>((c >> 16) & 0xFF));\n            hasher.process_byte(static_cast<unsigned char>((c >> 24) & 0xFF));\n         }\n      }\n\n      void process_characters(const char * const characters, size_t const count)\n      {\n         hasher.process_bytes(characters, count);\n      }\n\n      uuid make_uuid()\n      {\n         detail::sha1::digest8_t digest;\n         hasher.get_digest_bytes(digest);\n\n         // variant must be 0b10xxxxxx\n         digest[8] &= 0xBF;\n         digest[8] |= 0x80;\n\n         // version must be 0b0101xxxx\n         digest[6] &= 0x5F;\n         digest[6] |= 0x50;\n\n         return uuid{ digest, digest + 16 };\n      }\n\n   private:\n      uuid nsuuid;\n      detail::sha1 hasher;\n   }; \n}\n\nnamespace std\n{\n   template <>\n   struct hash<uuids::uuid>\n   {\n      using argument_type = uuids::uuid;\n      using result_type   = std::size_t;\n\n      result_type operator()(argument_type const &uuid) const\n      {\n         std::hash<std::string> hasher;\n         return static_cast<result_type>(hasher(uuids::to_string(uuid)));\n      }\n   };\n}\n", "meta": {"hexsha": "23c82c09c067e2bf151a90c7540ac38a9c1641e3", "size": 26855, "ext": "h", "lang": "C", "max_stars_repo_path": "third_party/uuid.h", "max_stars_repo_name": "cogment/cogment-orchestrator", "max_stars_repo_head_hexsha": "c3089d2827938d450d2d2b1391ff57aee82eddd3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-02-20T01:32:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T15:05:27.000Z", "max_issues_repo_path": "third_party/uuid.h", "max_issues_repo_name": "cogment/cogment-orchestrator", "max_issues_repo_head_hexsha": "c3089d2827938d450d2d2b1391ff57aee82eddd3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/uuid.h", "max_forks_repo_name": "cogment/cogment-orchestrator", "max_forks_repo_head_hexsha": "c3089d2827938d450d2d2b1391ff57aee82eddd3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-02-20T02:42:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T23:47:21.000Z", "avg_line_length": 30.7265446224, "max_line_length": 130, "alphanum_fraction": 0.4908955502, "num_tokens": 6735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1824255326961778, "lm_q2_score": 0.01615283180283831, "lm_q1q2_score": 0.0029466889461845407}}
{"text": "/*  \n * This file is part of the Visual Computing Library (VCL) release under the\n * license.\n * \n * Copyright (c) 2017 Basil Fierz\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n#pragma once\n\n// VCL configuration\n#include <vcl/config/global.h>\n\n// C++ Standard library\n#include <memory>\n#include <vector>\n\n// GSL\n#include <gsl/gsl>\n\n// VCL\n#include <vcl/hid/windows/hid.h>\n#include <vcl/hid/spacenavigator.h>\n\nnamespace Vcl { namespace HID { namespace Windows\n{\n\t//! Implementation of a 3Dconnexion space mouse\n\tclass SpaceNavigatorHID : public AbstractHID, public SpaceNavigator\n\t{\n\tprivate:\n\t\tstruct InputData \n\t\t{\n\t\t\t//! Current time to live for telling\n\t\t\t//! if the device was unplugged while sending data\n\t\t\tint timeToLive;\n\n\t\t\t//! Indicate if the data is dirty\n\t\t\tbool isDirty;\n\n\t\t\t//! Axis data\n\t\t\tstd::array<float,6> axes;\n\n\t\t\t//! Check if the data is zero\n\t\t\tbool isZero()\n\t\t\t{\n\t\t\t\treturn (0 == axes[0] && 0 == axes[1] && 0 == axes[2] &&\n\t\t\t\t\t\t0 == axes[3] && 0 == axes[4] && 0 == axes[5]    );\n\t\t\t}\n\n\t\t\t//! Maximum time to live\n\t\t\tstatic const int MaxTimeToLive = 5;\n\t\t};\n\n\tpublic:\n\t\tSpaceNavigatorHID(std::unique_ptr<GenericHID> dev, bool poll_3d_mouse = false);\n\t\t\n\t\t//! Reset device when activating the program\n\t\tvoid onActivateApp(BOOL active, DWORD dwThreadID);\n\n\t\t//! Handle device input\n\t\tbool processInput(HWND window_handle, UINT input_code, PRAWINPUT raw_input) override;\n\t\t\n\tprivate:\n\t\t\n\t\t/*!\n\t\t * \\brief Does all the preprocessing of the rawinput device data before\n\t\t *        finally calling the move3D method.\n\t\t *\n\t\t * If polling is enabled (_poll3DMouse == true) this method is called\n\t\t * from the windows timer message handler\n\t\t * If polling is not enabled (_poll3DMouse == false) this method is\n\t\t * called directly from the WM_INPUT handler\n\t\t */\n\t\tvoid on3DMouseInput();\n\t\t\n\t\t/*!\n\t\t * \\brief onSpaceMouseMove is invoked when new 3d mouse data is\n\t\t *        available.\n\t\t * \n\t\t * \\param motion_data Contains the displacement data, using a\n\t\t *                    right-handed coordinate system with z down.\n\t\t *                    See 'Programing for the 3dmouse' document\n\t\t *                    available at www.3dconnexion.com.\n\t\t *                    Entries 0, 1, 2 is the incremental pan zoom\n\t\t *                    displacement vector (x,y,z).\n\t\t *                    Entries 3, 4, 5 is the incremental rotation vector\n\t\t *                    (NOT Euler angles).\n\t\t */\n\t\tvoid onSpaceMouseMove(std::array<float, 6> motion_data);\n\t\t\n\t\t/*!\n\t\t * \\brief onSpaceMouseKeyDown processes the 3d mouse key presses\n\t\t * \n\t\t * \\param virtual_key 3d mouse key code \n\t\t */\n\t\tvoid onSpaceMouseKeyDown(UINT virtual_key);\n\t\t\n\t\t/*!\n\t\t * \\brief onSpaceMouseKeyUp processes the 3d mouse key releases\n\t\t * \n\t\t * \\param virtual_key 3d mouse key code \n\t\t */\n\t\tvoid onSpaceMouseKeyUp(UINT virtual_key);\n\n\tprivate:\n\t\t//! Process a raw input message\n\t\tbool translateRawInputData(UINT input_code, PRAWINPUT raw_input);\n\n\t\t//! Axis input data\n\t\tInputData _deviceData;\n\n\t\t//! Button input data\n\t\tuint32_t _keystate{ 0 };\n\t\t\n\t\t//! Last time the data was updated.\n\t\t//! Use to calculate distance traveled since last event\n\t\tDWORD _last3DMouseInputTime{ 0 };\n\n\tprivate: // Polling support methods\n\n\t\t//! Start the timer\n\t\tvoid startTimer(HWND hwnd);\n\n\t\t//! Timer callback\n\t\tvoid onTimer(UINT_PTR event_id);\n\n\t\t//! Kill the currently running timer\n\t\tvoid killPollingTimer();\n\t\t\n\tprivate: // Polling support\n\t\t//! 3D mouse is in polling mode\n\t\tbool _poll3DMouse{ false };\n\t\t\n\t\t//! Polling period. Default is 50 Hz)\n\t\tUINT _pollingPeriod3DMouse{ 20 };\n\n\t\t//! 3DMouse data polling timer\n\t\t//! Only used if _poll3DMouse == true\n\t\tUINT_PTR _timer3DMouse{ 0 };\n\t};\n}}}\n", "meta": {"hexsha": "897dea644f05f6c34e8b6edcfac59913ac39d8f8", "size": 4708, "ext": "h", "lang": "C", "max_stars_repo_path": "src/vcl/hid/windows/spacenavigator.h", "max_stars_repo_name": "bfierz/vcl.hid", "max_stars_repo_head_hexsha": "4193fe488d6759306e297b225e3a3c4da58716b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-26T20:39:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-26T20:39:34.000Z", "max_issues_repo_path": "src/vcl/hid/windows/spacenavigator.h", "max_issues_repo_name": "bfierz/vcl.hid", "max_issues_repo_head_hexsha": "4193fe488d6759306e297b225e3a3c4da58716b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/vcl/hid/windows/spacenavigator.h", "max_forks_repo_name": "bfierz/vcl.hid", "max_forks_repo_head_hexsha": "4193fe488d6759306e297b225e3a3c4da58716b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7974683544, "max_line_length": 87, "alphanum_fraction": 0.6796941376, "num_tokens": 1216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10669060530721626, "lm_q2_score": 0.027585280428078257, "lm_q1q2_score": 0.002943090266440975}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\n * Contact: lymastee@hotmail.com\n *\n * This file is part of the gslib project.\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n#pragma once\n\n#ifndef rose_fbed1fbf_2ba3_46bc_97da_b1df11752358_h\n#define rose_fbed1fbf_2ba3_46bc_97da_b1df11752358_h\n\n#include <gslib/utility.h>\n#include <ariel/config.h>\n#include <ariel/rendersys.h>\n#include <ariel/painter.h>\n#include <ariel/batch.h>\n#include <ariel/texbatch.h>\n\n__ariel_begin__\n\nclass rose;\n\n/* this block was used for synchronize with the constant buffer */\nstruct rose_configs\n{\n    vec4                screen;\n    float               mapscreen[3][4];\n    /* more.. */\n};\n\nstruct rose_bind_info_cr\n{\n    vec4                color;      /* RGBA */\n};\n\nstruct rose_bind_info_tex\n{\n    texture2d*          img;\n    vec2                tex;\n};\n\nstruct vertex_info_cr\n{\n    vec2                pos;\n    vec4                cr;\n};\n\nstruct vertex_info_klm_cr\n{\n    vec2                pos;\n    vec3                klm;\n    vec4                cr;\n};\n\nstruct vertex_info_coef_cr\n{\n    vec2                pos;\n    vec4                coef;       /* float3 coef & float tune */\n    vec4                cr;\n};\n\nstruct vertex_info_klm_tex\n{\n    vec2                pos;\n    vec3                klm;\n    vec2                tex;\n};\n\nstruct vertex_info_coef_tex\n{\n    vec2                pos;\n    vec4                coef;\n    vec2                tex;\n};\n\nclass rose_batch;\ntypedef list<rose_bind_info_cr> rose_bind_list_cr;\ntypedef list<rose_bind_info_tex> rose_bind_list_tex;\ntypedef vector<rose_batch*> rose_batch_list;\ntypedef vector<vertex_info_cr> vertex_stream_cr;\ntypedef vector<vertex_info_klm_cr> vertex_stream_klm_cr;\ntypedef vector<vertex_info_coef_cr> vertex_stream_cf_cr;\ntypedef vector<vertex_info_klm_tex> vertex_stream_klm_tex;\ntypedef vector<vertex_info_coef_tex> vertex_stream_cf_tex;\ntypedef vector<int> index_stream;\ntypedef bat_type rose_batch_tag;\n\nclass __gs_novtable rose_batch abstract\n{\npublic:\n    typedef rendersys::vertex_buffer vertex_buffer;\n    typedef rendersys::index_buffer index_buffer;\n\npublic:\n    rose_batch(int index);\n    virtual ~rose_batch();\n    virtual rose_batch_tag get_tag() const = 0;\n    virtual void create(bat_batch* bat) = 0;\n    virtual int buffering(rendersys* rsys) = 0;\n    virtual void draw(rendersys* rsys) = 0;\n    virtual void tracing() const = 0;\n\nprotected:\n    int                 _bat_index;\n    vertex_shader*      _vertex_shader;\n    pixel_shader*       _pixel_shader;\n    vertex_format*      _vertex_format;\n    vertex_buffer*      _vertex_buffer;\n\npublic:\n    int get_batch_index() const { return _bat_index; }\n    void set_vertex_shader(vertex_shader* p) { _vertex_shader = p; }\n    void set_pixel_shader(pixel_shader* p) { _pixel_shader = p; }\n    void set_vertex_format(vertex_format* p) { _vertex_format = p; }\n    void setup_vs_and_ps(rendersys* rsys);\n    void setup_vf_and_topology(rendersys* rsys, uint topo);\n\nprotected:\n    template<class stream_type>\n    int template_buffering(stream_type& stm, rendersys* rsys);\n};\n\nclass rose_fill_batch_cr:\n    public rose_batch\n{\npublic:\n    rose_fill_batch_cr(int index): rose_batch(index) {}\n    rose_batch_tag get_tag() const override { return bf_cr; }\n    void create(bat_batch* bat) override;\n    int buffering(rendersys* rsys) override;\n    void draw(rendersys* rsys) override;\n    void tracing() const override;\n\nprotected:\n    vertex_stream_cr    _vertices;\n\nprivate:\n    void create_from_fill(bat_fill_batch* bat);\n    void create_from_stroke(bat_stroke_batch* bat);\n};\n\nclass rose_fill_batch_klm_cr:\n    public rose_batch\n{\npublic:\n    rose_fill_batch_klm_cr(int index) : rose_batch(index) {}\n    rose_batch_tag get_tag() const override { return bf_klm_cr; }\n    void create(bat_batch* bat) override;\n    int buffering(rendersys* rsys) override;\n    void draw(rendersys* rsys) override;\n    void tracing() const override;\n\nprotected:\n    vertex_stream_klm_cr _vertices;\n};\n\nclass rose_fill_batch_klm_tex:\n    public rose_batch\n{\n    friend class rose_stroke_batch_assoc_with_klm_tex;\n\npublic:\n    rose_fill_batch_klm_tex(int index, render_sampler_state* ss);\n    ~rose_fill_batch_klm_tex() { destroy(); }\n    rose_batch_tag get_tag() const override { return bf_klm_tex; }\n    void create(bat_batch* bat) override;\n    int buffering(rendersys* rsys) override;\n    void draw(rendersys* rsys) override;\n    void tracing() const override;\n    void destroy();\n\nprotected:\n    vertex_stream_klm_tex _vertices;\n    tex_batcher         _texbatch;\n    render_sampler_state* _sstate;\n    shader_resource_view* _srv;\n    render_texture2d*   _tex;\n\nprivate:\n    void create_from_fill(bat_fill_batch* bat);\n    void create_from_stroke(bat_stroke_batch* bat);\n};\n\nclass rose_stroke_batch_coef_cr:\n    public rose_batch\n{\npublic:\n    rose_stroke_batch_coef_cr(int index) : rose_batch(index) {}\n    rose_batch_tag get_tag() const override { return bs_coef_cr; }\n    void create(bat_batch* bat) override;\n    int buffering(rendersys* rsys) override;\n    void draw(rendersys* rsys) override;\n    void tracing() const override;\n\nprotected:\n    vertex_stream_cf_cr _vertices;\n};\n\nclass rose_stroke_batch_coef_tex:\n    public rose_batch\n{\npublic:\n    rose_stroke_batch_coef_tex(int index, render_sampler_state* ss);\n    ~rose_stroke_batch_coef_tex() { destroy(); }\n    rose_batch_tag get_tag() const override { return bs_coef_tex; }\n    void create(bat_batch* bat) override;\n    int buffering(rendersys* rsys) override;\n    void draw(rendersys* rsys) override;\n    void tracing() const override;\n    void destroy();\n\nprotected:\n    vertex_stream_cf_tex _vertices;\n    tex_batcher         _texbatch;\n    render_sampler_state* _sstate;\n    shader_resource_view* _srv;\n    render_texture2d*   _tex;\n\nprotected:\n    void create_vertices(bat_batch* bat);\n    void create_vertices(bat_lines& lines, const tex_batcher& bat);\n};\n\nclass rose_stroke_batch_assoc_with_klm_tex:\n    public rose_stroke_batch_coef_tex\n{\npublic:\n    rose_stroke_batch_assoc_with_klm_tex(int index, rose_fill_batch_klm_tex* assoc);\n    ~rose_stroke_batch_assoc_with_klm_tex();\n    void create(bat_batch* bat) override;\n    int buffering(rendersys* rsys) override;\n\nprotected:\n    rose_fill_batch_klm_tex* _assoc;\n\nprotected:\n    void create_vertices(bat_batch* bat);\n};\n\nclass rose_bindings\n{\npublic:\n    rose_bind_list_cr& get_cr_bindings() { return _cr_bindings; }\n    rose_bind_list_tex& get_tex_bindings() { return _tex_bindings; }\n    void clear_binding_cache();\n\nprotected:\n    rose_bind_list_cr   _cr_bindings;\n    rose_bind_list_tex  _tex_bindings;\n};\n\nclass graphics_obj_entity:\n    public loop_blinn_processor\n{\npublic:\n    graphics_obj_entity(float w, float h) : loop_blinn_processor(w, h) {}\n    void proceed_fill(const painter_path& path) { __super::proceed(path); }\n    void proceed_stroke(const painter_path& path);\n\nprotected:\n    int create_from_path(const painter_path& path, int start);\n\n    struct path_seg\n    {\n        lb_line*        first;\n        lb_line*        last;\n        path_seg() { first = last = nullptr; }\n    };\n    void add_line_seg(path_seg& seg, const painter_path::line_to_node* node);\n    void add_quad_seg(path_seg& seg, const painter_node* node1, const painter_path::quad_to_node* node2);\n    void add_cubic_seg(path_seg& seg, const painter_node* node1, const painter_path::cubic_to_node* node2);\n};\n\nclass graphics_obj:\n    public std::shared_ptr<graphics_obj_entity>\n{\npublic:\n    graphics_obj(float w, float h);\n};\n\nextern void rose_paint_non_picture_brush(graphics_obj& gfx, rose_bindings& bindings, const painter_brush& brush);\nextern void rose_paint_solid_brush(graphics_obj& gfx, rose_bind_list_cr& bind_cache, const painter_brush& brush);\nextern void rose_paint_picture_brush(graphics_obj& gfx, const rectf& bound, rose_bind_list_tex& bind_cache, const painter_brush& brush);\nextern void rose_paint_pen(graphics_obj& gfx, const painter_path& path, rose_bindings& bindings, const painter_pen& pen);\nextern void rose_paint_solid_pen(graphics_obj& gfx, rose_bind_list_cr& bind_cache, const painter_pen& pen);\nextern void rose_paint_picture_pen(graphics_obj& gfx, const rectf& bound, rose_bind_list_tex& bind_cache, const painter_pen& pen);\n/* more to come. */\n\nclass rose:\n    public painter\n{\npublic:\n    typedef render_constant_buffer constant_buffer;\n    typedef render_sampler_state sampler_state;\n    typedef list<graphics_obj> graphics_obj_cache;\n\npublic:\n    rose();\n    virtual ~rose();\n    virtual void resize(int w, int h) override {}\n    virtual void draw_path(const painter_path& path) override;\n    virtual void on_draw_begin() override;\n    virtual void on_draw_end() override;\n\npublic:\n    void setup(rendersys* rsys);\n    rendersys* get_rendersys() const { return _rsys; }\n    void fill_non_picture_graphics_obj(graphics_obj& gfx, uint brush_tag);\n    bat_batch* fill_picture_graphics_obj(graphics_obj& gfx);\n    void stroke_graphics_obj(graphics_obj& gfx, uint pen_tag);\n\nprotected:\n    template<class _addline>\n    void meta_stroke_graphics_obj(graphics_obj& gfx, _addline fn_add);\n\nprotected:\n    rendersys*          _rsys;\n    rose_configs        _cfgs;\n    batch_processor     _bp;\n    rose_batch_list     _batches;\n    rose_bindings       _bindings;\n    graphics_obj_cache  _gocache;\n    float               _nextz;\n\nprotected:\n    void setup_configs();\n    void prepare_fill(const painter_path& path, const painter_brush& brush);\n    void prepare_picture_fill(const painter_path& path, const painter_brush& brush);\n    void prepare_stroke(const painter_path& path, const painter_pen& pen);\n    rose_batch* create_fill_batch_cr(int index);\n    rose_batch* create_fill_batch_klm_cr(int index);\n    rose_batch* create_fill_batch_klm_tex(int index);\n    rose_batch* create_stroke_batch_cr(int index);\n    rose_batch* create_stroke_batch_tex(int index);\n    rose_batch* create_stroke_batch_assoc(int index, rose_fill_batch_klm_tex* assoc);\n    void clear_batches();\n    void prepare_batches();\n    void draw_batches();\n\n#if use_rendersys_d3d_11\nprotected:\n    void initialize();\n    void destroy_miscs();\n    sampler_state* acquire_default_sampler_state();\n\nprotected:\n    vertex_shader*      _vsf_cr;\n    vertex_shader*      _vsf_klm_cr;\n    vertex_shader*      _vsf_klm_tex;\n    pixel_shader*       _psf_cr;\n    pixel_shader*       _psf_klm_cr;\n    pixel_shader*       _psf_klm_tex;\n    vertex_format*      _vf_cr;\n    vertex_format*      _vf_klm_cr;\n    vertex_format*      _vf_klm_tex;\n    vertex_shader*      _vss_coef_cr;\n    vertex_shader*      _vss_coef_tex;\n    pixel_shader*       _pss_coef_cr;\n    pixel_shader*       _pss_coef_tex;\n    vertex_format*      _vf_coef_cr;\n    vertex_format*      _vf_coef_tex;\n    sampler_state*      _sampler_state;\n    constant_buffer*    _cb_configs;\n    uint                _cb_config_slot;\n#endif\n};\n\n__ariel_end__\n\n#endif\n", "meta": {"hexsha": "f345a188a1be66b410e88d483aaa0bd74382897a", "size": 11944, "ext": "h", "lang": "C", "max_stars_repo_path": "include/ariel/rose.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/ariel/rose.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ariel/rose.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 30.6256410256, "max_line_length": 136, "alphanum_fraction": 0.718687207, "num_tokens": 2945, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12592276811536138, "lm_q2_score": 0.023330766261897062, "lm_q1q2_score": 0.0029378746699505603}}
{"text": "///\n/// @file\n///\n/// @author Mirko Myllykoski (mirkom@cs.umu.se), Ume\u00e5 University\n/// @author Lars Karlsson (larsk@cs.umu.se), Ume\u00e5 University\n///\n/// @internal LICENSE\n///\n/// Copyright (c) 2019-2020, Ume\u00e5 Universitet\n///\n/// Redistribution and use in source and binary forms, with or without\n/// modification, are permitted provided that the following conditions are met:\n///\n/// 1. Redistributions of source code must retain the above copyright notice,\n///    this list of conditions and the following disclaimer.\n///\n/// 2. Redistributions in binary form must reproduce the above copyright notice,\n///    this list of conditions and the following disclaimer in the documentation\n///    and/or other materials provided with the distribution.\n///\n/// 3. Neither the name of the copyright holder nor the names of its\n///    contributors may be used to endorse or promote products derived from this\n///    software without specific prior written permission.\n///\n/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n/// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n/// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n/// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n/// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n/// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n/// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n/// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n/// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n/// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n/// POSSIBILITY OF SUCH DAMAGE.\n///\n\n#include <starneig_config.h>\n#include <starneig/configuration.h>\n#include \"node_internal.h\"\n#ifdef STARNEIG_ENABLE_MPI\n#include \"../mpi/node_internal.h\"\n#include \"../mpi/distr_matrix_internal.h\"\n#endif\n#include \"common.h\"\n#include \"scratch.h\"\n#include <starneig/node.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <hwloc.h>\n#include <starpu.h>\n#ifdef MKL_SET_NUM_THREADS_LOCAL_FOUND\n#include <mkl.h>\n#endif\n#if defined(OPENBLAS_SET_NUM_THREADS_FOUND) || \\\ndefined(GOTO_SET_NUM_THREADS_FOUND)\n#include <cblas.h>\n#endif\n\nstatic struct {\n    /// initialization flag\n    bool is_init;\n    // initialization flags\n    starneig_flag_t flags;\n    /// library mode\n    enum starneig_mode mode;\n    /// blas mode\n    enum starneig_blas_mode blas_mode;\n    // original blas thread count\n    int blas_threads_original;\n    // StarPU worker bind mask\n    unsigned starpu_workers_bindid[STARPU_NMAXWORKERS];\n    // total number of available cpu cores\n    int avail_cores;\n    // total number of available gpus\n    int avail_gpus;\n    // number of used cpu cores\n    int used_cores;\n    // total number of used gpus\n    int used_gpus;\n} state = {\n    .is_init = false,\n    .flags = STARNEIG_DEFAULT,\n    .mode = STARNEIG_MODE_OFF,\n    .blas_mode = STARNEIG_BLAS_MODE_ORIGINAL,\n    .blas_threads_original = -1,\n    .avail_cores = 0,\n    .avail_gpus = 0,\n    .used_cores = 0,\n    .used_gpus = 0\n};\n\n///\n/// @brief Sets the number of BLAS threads.\n///\n/// @param[in] threads\n///         Number of BLAS threads.\n///\n/// @return Previous BLAS thread count (can be 0).\n///\nstatic int set_blas_threads(int threads)\n{\n    starneig_verbose(\"Setting BLAS thread count to %d.\", threads);\n#ifdef MKL_SET_NUM_THREADS_LOCAL_FOUND\n    return mkl_set_num_threads_local(threads);\n#elif defined(OPENBLAS_SET_NUM_THREADS_FOUND)\n    int old = openblas_get_num_threads();\n    openblas_set_num_threads(threads);\n    return old;\n#elif defined(GOTO_SET_NUM_THREADS_FOUND)\n    goto_set_num_threads(threads);\n    return 1;\n#else\n    return 1;\n#endif\n}\n\n///\n/// @brief Sets the BLAS mode.\n///\n/// @param[in] mode\n///         BLAS mode.\n///\nstatic void set_blas_mode(enum starneig_blas_mode mode)\n{\n    int old = -1;\n    switch (mode) {\n        case STARNEIG_BLAS_MODE_PARALLEL:\n            starneig_verbose(\"Switching to parallel BLAS.\");\n            old = set_blas_threads(state.used_cores);\n            break;\n        case STARNEIG_BLAS_MODE_SEQUENTIAL:\n            starneig_verbose(\"Switching to sequential BLAS.\");\n            old = set_blas_threads(1);\n            break;\n        default:\n            starneig_verbose(\"Restoring BLAS mode.\");\n            if (0 <= state.blas_threads_original)\n                set_blas_threads(state.blas_threads_original);\n            state.blas_threads_original = -1;\n    }\n    if (state.blas_mode == STARNEIG_BLAS_MODE_ORIGINAL && 0 <= old)\n        state.blas_threads_original = old;\n    state.blas_mode = mode;\n}\n\n#ifdef MKL_SET_NUM_THREADS_LOCAL_FOUND\n\n///\n/// @brief Sets the per thread BLAS thread count to 1.\n///\n/// @param[in] arg\n///         An unused argument.\n///\nstatic void set_worker_blas_mode(void *arg)\n{\n    mkl_set_num_threads_local(1);\n}\n\n#endif\n\n///\n/// @brief Reconfigures the node.\n///\n/// @param[in] cores\n///         Number of CPU cores to use.\n///\n/// @param[in] gpus\n///         Number of GPUs to use.\n///\n/// @param[in] mode\n///         Library mode.\n///\n/// @param[in] blas_mode\n///         BLAS mode.\n///\n#define CONFIGURE(cores, gpus, mode, blas_mode) \\\n    node_configure(cores, gpus, mode, blas_mode, __func__)\n\n///\n/// @brief Reconfigures the node.\n///\n/// @param[in] cores\n///         Number of CPU cores to use.\n///\n/// @param[in] gpus\n///         Number of GPUs to use.\n///\n/// @param[in] mode\n///         Library mode.\n///\n/// @param[in] blas_mode\n///         BLAS mode\n///\n/// @param[in] func\n///         Name of the calling function.\n///\nstatic void node_configure(\n    int cores, int gpus, enum starneig_mode mode,\n    enum starneig_blas_mode blas_mode, char const *func)\n{\n#ifndef STARNEIG_ENABLE_MPI\n    if (mode == STARNEIG_MODE_DM)\n        starneig_fatal_error(\"StarPU was compiled without MPI support.\");\n#endif\n\n    if (cores == state.used_cores && gpus == state.used_gpus &&\n    mode == state.mode && blas_mode == state.blas_mode)\n        return;\n\n    starneig_verbose(\"Reconfiguring the library.\");\n\n    if (cores == state.used_cores && gpus == state.used_gpus &&\n    mode == state.mode) {\n        set_blas_mode(blas_mode);\n        return;\n    }\n\n    //\n    // shutdown StarPU\n    //\n\n    if (state.mode != STARNEIG_MODE_OFF) {\n        starneig_node_resume_starpu();\n#ifdef STARNEIG_ENABLE_CUDA\n        if (0 < state.used_gpus) {\n            starneig_verbose(\"Shutting down cuBLAS.\");\n            starpu_cublas_shutdown();\n        }\n#endif\n\n        starneig_verbose(\"Shutting down StarPU.\");\n\n        starneig_scratch_unregister();\n#ifdef STARNEIG_ENABLE_MPI\n        starneig_mpi_cache_clear();\n    if (state.mode == STARNEIG_MODE_DM &&\n    state.flags & STARNEIG_AWAKE_MPI_WORKER)\n        starneig_mpi_stop_persistent_starpumpi();\n#endif\n\n        starpu_task_wait_for_all();\n        starpu_shutdown();\n    }\n\n    //\n    // set the number of CPU cores\n    //\n\n    if (cores == 0)\n        starneig_fatal_error(\"At least one CPU core must be selected.\");\n\n    if (cores < 0) {\n        state.used_cores = state.avail_cores;\n    }\n    else {\n        state.used_cores = MIN(cores, state.avail_cores);\n        if (state.avail_cores < cores)\n            starneig_warning(\n                \"Failed to acquire the desired number of CPU cores. \"\n                \"Acquired %d.\", state.used_cores);\n    }\n\n    //\n    // set the number of GPUs\n    //\n\n    if (gpus < 0) {\n        state.used_gpus = state.avail_gpus;\n    }\n    else {\n#ifdef STARNEIG_ENABLE_CUDA\n        state.used_gpus = MIN(gpus, state.avail_gpus);\n\n        if (state.avail_gpus < gpus)\n            starneig_warning(\n                \"Failed to acquire the desired number of CUDA devices. \"\n                \"Acquired %d.\", state.used_gpus);\n#else\n        if (0 < gpus)\n            starneig_warning(\"StarPU was compiled without CUDA support.\");\n#endif\n    }\n\n    //\n    // set BLAS threads\n    //\n\n    set_blas_mode(blas_mode);\n\n    //\n    // set mode\n    //\n\n    state.mode = mode;\n    if (state.mode == STARNEIG_MODE_OFF)\n        return;\n\n    //\n    // create StarPU configuration\n    //\n\n    starneig_verbose(\"Configuring StarPU.\");\n\n    struct starpu_conf conf;\n    starpu_conf_init(&conf);\n\n    int cpu_workers = state.used_cores;\n    if (0 < state.used_gpus)\n        cpu_workers -= state.used_gpus;\n    if (state.mode == STARNEIG_MODE_DM)\n        cpu_workers--;\n\n    conf.ncpus = MAX(1, cpu_workers);\n    conf.ncuda = state.used_gpus;\n    conf.nopencl = 0;\n\n//#if 1 < STARPU_MAJOR_VERSION || 2 < STARPU_MINOR_VERSION\n    if (getenv(\"STARPU_WORKERS_CPUID\") == NULL)\n        conf.use_explicit_workers_bindid = 1;\n//#endif\n    memcpy(conf.workers_bindid, state.starpu_workers_bindid,\n        sizeof(state.starpu_workers_bindid));\n\n#ifdef STARNEIG_ENABLE_CUDA\n    if (0 < state.used_gpus)\n        conf.sched_policy_name = \"dmdas\";\n    else\n#endif\n        conf.sched_policy_name = \"prio\";\n\n    //\n    // setup FXT\n    //\n\n    if (state.flags & STARNEIG_FXT_DISABLE) {\n        starneig_verbose(\"Disabling FXT traces.\");\n        starpu_fxt_autostart_profiling(0);\n    }\n    else {\n        char const *starpu_fxt_trace = getenv(\"STARPU_FXT_TRACE\");\n        if (starpu_fxt_trace == NULL || atoi(starpu_fxt_trace) != 0) {\n            starneig_verbose(\"Keeping FXT traces enabled.\");\n            starpu_fxt_autostart_profiling(1);\n        }\n    }\n\n    //\n    // initialize StarPU\n    //\n\n    starneig_verbose(\"Starting StarPU.\");\n\n    unsigned seed = rand();\n    int ret = starpu_init(&conf);\n    srand(seed);\n\n    if (ret != 0)\n        starneig_fatal_error(\"Failed to initialize StarPU.\");\n\n    starpu_profiling_status_set(STARPU_PROFILING_ENABLE);\n    starpu_malloc_set_align(64);\n\n    //\n    // initialize persistent StarPU-MPI\n    //\n\n#ifdef STARNEIG_ENABLE_MPI\n    if (state.mode == STARNEIG_MODE_DM &&\n    state.flags & STARNEIG_AWAKE_MPI_WORKER)\n        starneig_mpi_start_persistent_starpumpi();\n#endif\n\n    //\n    // cuBLAS\n    //\n\n    if (0 < state.used_gpus) {\n        starneig_verbose(\"Initializing cuBLAS.\");\n        starpu_cublas_init();\n    }\n\n    //\n    // configure workers\n    //\n\n#ifdef MKL_SET_NUM_THREADS_LOCAL_FOUND\n    starneig_verbose(\n        \"MKL detected. Setting StarPU worker BLAS thread count to 1.\");\n    starpu_execute_on_each_worker(\n        &set_worker_blas_mode, NULL, STARPU_CPU | STARPU_CUDA);\n#endif\n\n    starneig_node_pause_starpu();\n}\n\nvoid starneig_node_pause_starpu()\n{\n    if (state.flags & STARNEIG_AWAKE_WORKERS)\n        return;\n\n    starneig_verbose(\"Pausing StarPU workers.\");\n    starpu_pause();\n}\n\nvoid starneig_node_resume_starpu()\n{\n    if (state.flags & STARNEIG_AWAKE_WORKERS)\n        return;\n\n    starneig_verbose(\"Waking up StarPU workers.\");\n    starpu_resume();\n}\n\nvoid starneig_node_pause_awake_starpu()\n{\n    if (!(state.flags & STARNEIG_AWAKE_WORKERS))\n        return;\n\n    starneig_verbose(\"Pausing \\\"awake\\\" StarPU workers.\");\n    starpu_pause();\n}\n\nvoid starneig_node_resume_awake_starpu()\n{\n    if (!(state.flags & STARNEIG_AWAKE_WORKERS))\n        return;\n\n    starneig_verbose(\"Waking up \\\"awake\\\" StarPU workers.\");\n    starpu_resume();\n}\n\n__attribute__ ((visibility (\"default\")))\nvoid starneig_node_init(int cores, int gpus, starneig_flag_t flags)\n{\n    starneig_set_message_mode(\n        !(flags & STARNEIG_NO_MESSAGES), !(flags & STARNEIG_NO_VERBOSE));\n\n    starneig_verbose(\"Initializing node.\");\n\n    if (state.is_init)\n        starneig_fatal_error(\"The node is already initialized.\");\n\n    state.flags = flags;\n\n    //\n    // set up CUDA\n    //\n\n    state.avail_gpus = 0;\n    state.used_gpus = 0;\n\n#ifdef STARNEIG_ENABLE_CUDA\n    // query the number of available CUDA devices\n\tif (cudaGetDeviceCount(&state.avail_gpus) != cudaSuccess) {\n        starneig_warning(\"Failed to acquire CUDA device count.\");\n        state.avail_gpus = 0;\n    }\n#endif\n\n    // query STARPU_NCUDA environment\n    char *starpu_ncuda = getenv(\"STARPU_NCUDA\");\n    int num_starpu_gpus = (starpu_ncuda ? atoi(starpu_ncuda) : -1);\n\n    if (num_starpu_gpus != -1) {\n        if (state.avail_gpus < num_starpu_gpus)\n        starneig_warning(\n            \"A conflict between STARPU_NCUDA and cudaGetDeviceCount().\");\n        state.avail_gpus = MIN(state.avail_gpus, num_starpu_gpus);\n    }\n\n    //\n    // set up CPU cores\n    //\n\n    state.avail_cores = 0;\n    state.used_cores = 0;\n\n    // query the SLURM environment\n    char *slurm = getenv(\"SLURM_CPUS_PER_TASK\");\n    const int num_slurm_cpus = (slurm ? atoi(slurm) : -1);\n\n    // query STARPU_NCPUS environment\n    char *starpu_ncpus = getenv(\"STARPU_NCPUS\");\n    int num_starpu_cpus = -1;\n    if (starpu_ncpus) {\n        if (0 < state.avail_gpus)\n            num_starpu_cpus = atoi(starpu_ncpus) + 1;\n        else\n            num_starpu_cpus = atoi(starpu_ncpus);\n    }\n\n    // query hardware topology and CPU core binding mask\n\n    hwloc_topology_t topology;\n    hwloc_topology_init(&topology);\n    hwloc_topology_load(topology);\n\n    hwloc_cpuset_t res = hwloc_bitmap_alloc();\n\n    hwloc_cpuset_t mask = hwloc_bitmap_alloc();\n    hwloc_get_cpubind(topology, mask, HWLOC_CPUBIND_THREAD);\n\n    int depth_cores = hwloc_get_type_depth(topology, HWLOC_OBJ_CORE);\n    int num_cores = hwloc_get_nbobjs_by_depth(topology, depth_cores);\n\n    int num_hwloc_cpus = 0;\n\n    // iterate over all COREs\n    for (int i = 0; i < num_cores && num_hwloc_cpus < STARPU_NMAXWORKERS; i++) {\n        hwloc_obj_t core = hwloc_get_obj_by_depth(topology, depth_cores, i);\n\n        // if the CORE has PUs inside it, ...\n        if (core->first_child && core->first_child->type == HWLOC_OBJ_PU) {\n            // iterate over them\n            hwloc_obj_t pu = core->first_child;\n            while (pu) {\n                // if the PU is in the binding mask, ...\n                hwloc_bitmap_and(res, mask, pu->cpuset);\n                if (!hwloc_bitmap_iszero(res)) {\n                    // add it to the worker list\n                    state.starpu_workers_bindid[num_hwloc_cpus++] =\n                        pu->logical_index;\n                    break;\n                }\n                pu = pu->next_sibling;\n            }\n        }\n        else {\n            // if the CORE is in the binding mask, ...\n            hwloc_bitmap_and(res, mask, core->cpuset);\n            if (!hwloc_bitmap_iszero(res)) {\n                // add it to the worker list\n                state.starpu_workers_bindid[num_hwloc_cpus++] =\n                    core->logical_index;\n            }\n        }\n    }\n\n    hwloc_bitmap_free(mask);\n    hwloc_bitmap_free(res);\n    hwloc_topology_destroy(topology);\n\n    starneig_verbose_begin(\"Attached CPU cores\");\n    for (int i = 0; i < num_hwloc_cpus; i++)\n        starneig_verbose_cont(\" %d\", state.starpu_workers_bindid[i]);\n    starneig_verbose_cont(\".\\n\");\n\n    // set avail_cores\n\n    state.avail_cores = num_hwloc_cpus;\n    if (0 < num_starpu_cpus) {\n        if (num_hwloc_cpus < num_starpu_cpus)\n            starneig_warning(\n                \"A conflict between STARPU_NCPUS/STARPU_NCUDA and hwloc core \"\n                \"binding mask.\");\n        state.avail_cores = MIN(state.avail_cores, num_starpu_cpus);\n        if (0 < num_slurm_cpus) {\n            if (num_slurm_cpus < num_starpu_cpus)\n                starneig_warning(\n                    \"A conflict between STARPU_NCPUS/STARPU_NCUDA and \"\n                    \"SLURM_CPUS_PER_TASK.\");\n            state.avail_cores = MIN(state.avail_cores, num_slurm_cpus);\n        }\n    }\n    if (0 < num_slurm_cpus) {\n        if (num_hwloc_cpus < num_slurm_cpus)\n            starneig_warning(\n                \"A conflict between SLURM_CPUS_PER_TASK and hwloc core \"\n                \"binding mask.\");\n        state.avail_cores = MIN(state.avail_cores, num_slurm_cpus);\n    }\n\n    if (state.avail_cores <= 0)\n        starneig_fatal_error(\"Something unexpected happened.\");\n\n    state.is_init   = true;\n\n    if (state.flags & STARNEIG_HINT_DM)\n        CONFIGURE(cores, gpus, STARNEIG_MODE_DM, STARNEIG_BLAS_MODE_SEQUENTIAL);\n    else\n        CONFIGURE(cores, gpus, STARNEIG_MODE_SM, STARNEIG_BLAS_MODE_SEQUENTIAL);\n}\n\n__attribute__ ((visibility (\"default\")))\nint starneig_node_initialized()\n{\n    return state.is_init;\n}\n\n__attribute__ ((visibility (\"default\")))\nvoid starneig_node_finalize(void)\n{\n    CHECK_INIT();\n\n    starneig_verbose(\"De-initializing node.\");\n\n    CONFIGURE(-1, -1, STARNEIG_MODE_OFF, STARNEIG_BLAS_MODE_ORIGINAL);\n\n    starneig_set_message_mode(0, 0);\n\n    state.avail_cores = 0;\n    state.avail_gpus = 0;\n\n    state.is_init = false;\n}\n\n__attribute__ ((visibility (\"default\")))\nint starneig_node_get_cores(void)\n{\n    CHECK_INIT();\n    return state.used_cores;\n}\n\n__attribute__ ((visibility (\"default\")))\nvoid starneig_node_set_cores(int cores)\n{\n    CHECK_INIT();\n    CONFIGURE(cores, starneig_node_get_gpus(), state.mode, state.blas_mode);\n}\n\n__attribute__ ((visibility (\"default\")))\nint starneig_node_get_gpus(void)\n{\n    CHECK_INIT();\n    return state.used_gpus;\n}\n\n__attribute__ ((visibility (\"default\")))\nvoid starneig_node_set_gpus(int gpus)\n{\n    CHECK_INIT();\n    CONFIGURE(starneig_node_get_cores(), gpus, state.mode, state.blas_mode);\n}\n\n__attribute__ ((visibility (\"default\")))\nvoid starneig_node_set_mode(enum starneig_mode mode)\n{\n    CHECK_INIT();\n    CONFIGURE(starneig_node_get_cores(), starneig_node_get_gpus(),\n        mode, state.blas_mode);\n}\n\nvoid starneig_node_set_blas_mode(enum starneig_blas_mode blas_mode)\n{\n    CHECK_INIT();\n    CONFIGURE(starneig_node_get_cores(), starneig_node_get_gpus(),\n        state.mode, blas_mode);\n}\n", "meta": {"hexsha": "68f61733a7a549282ce9d54fc13897f21269c69c", "size": 17596, "ext": "c", "lang": "C", "max_stars_repo_path": "src/common/node.c", "max_stars_repo_name": "NLAFET/StarNEig", "max_stars_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2019-04-28T17:13:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-24T12:30:19.000Z", "max_issues_repo_path": "src/common/node.c", "max_issues_repo_name": "NLAFET/StarNEig", "max_issues_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/common/node.c", "max_forks_repo_name": "NLAFET/StarNEig", "max_forks_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-04-30T12:14:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-14T09:41:23.000Z", "avg_line_length": 27.0291858679, "max_line_length": 80, "alphanum_fraction": 0.6506592407, "num_tokens": 4486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11596072436426733, "lm_q2_score": 0.025178839688993277, "lm_q1q2_score": 0.002919756488987424}}
{"text": "/******************************************************************************\n *\n * INTEL CONFIDENTIAL\n *\n * Copyright 2015 Intel Corporation All Rights Reserved.\n *\n * The source code contained or described herein and all documents related\n * to the source code (Material) are owned by Intel Corporation or its\n * suppliers or licensors. Title to the Material remains with\n * Intel Corporation or its suppliers and licensors. The Material contains\n * trade secrets and proprietary and confidential information of Intel or\n * its suppliers and licensors. The Material is protected by worldwide\n * copyright and trade secret laws and treaty provisions. No part of the\n * Material may be used, copied, reproduced, modified, published, uploaded,\n * posted, transmitted, distributed, or disclosed in any way without Intel's\n * prior express written permission.\n *\n * No license under any patent, copyright, trade secret or other intellectual\n * property right is granted to or conferred upon you by disclosure or\n * delivery of the Materials, either expressly, by implication, inducement,\n * estoppel or otherwise. Any license under such intellectual property rights\n * must be express and approved by Intel in writing.\n *\n *\n *   Workfile:   FwUpdateDebug.c\n *\n *   Abstract:   macros to wrap dbglog for simple FwUpdate debugging\n *\n ******************************************************************************/\n\n#ifndef __FW_UPDATE_DEBUG_H__\n#define __FW_UPDATE_DEBUG_H__\n\n#include <gsl/span>\n#include <iostream>\n\ntypedef enum\n{\n    PRINT_NONE = 0,\n    PRINT_CRITICAL = 1,\n    PRINT_ERROR,\n    PRINT_WARNING,\n    PRINT_INFO,\n    PRINT_DEBUG,\n    PRINT_DEBUG2,\n    PRINT_ALL,\n} dbg_level;\n\n#define FWCRITICAL(MSG) PRINT(PRINT_CRITICAL, MSG)\n#define FWERROR(MSG) PRINT(PRINT_ERROR, MSG)\n#define FWWARN(MSG) PRINT(PRINT_WARNING, MSG)\n#define FWINFO(MSG) PRINT(PRINT_INFO, MSG)\n#define FWDEBUG(MSG) PRINT(PRINT_DEBUG, MSG)\n#define FWDEBUG2(MSG) PRINT(PRINT_DEBUG2, MSG)\n\n#define FWDUMP(D, L) DUMP(PRINT_DEBUG, D, L)\n\n#define FW_UPDATE_DEBUG 1\n\n#ifdef FW_UPDATE_DEBUG\n\nextern dbg_level fw_update_get_dbg_level(void);\nextern void fw_update_set_dbg_level(dbg_level l);\n\n#define PRINT(LEVEL, MSG)                                                      \\\n    do                                                                         \\\n    {                                                                          \\\n        if ((LEVEL) <= fw_update_get_dbg_level())                              \\\n        {                                                                      \\\n            std::stringstream ss;                                              \\\n            ss << '<' << LEVEL << '>' << __FUNCTION__ << \":\" << __LINE__       \\\n               << \": \" << MSG;                                                 \\\n            std::cerr << ss.str() << std::endl;                                \\\n        }                                                                      \\\n    } while (0)\n\nvoid _dump(dbg_level lvl, const char* fn, int lineno, const char* bname,\n           const gsl::span<const uint8_t>& buf);\n\nvoid _dump(dbg_level lvl, const char* fn, int lineno, const char* bname,\n           const void* buf, size_t len);\n\n#define DUMP(LEVEL, BUF, ...)                                                  \\\n    do                                                                         \\\n    {                                                                          \\\n        if ((LEVEL) <= fw_update_get_dbg_level())                              \\\n        {                                                                      \\\n            _dump(LEVEL, __FUNCTION__, __LINE__, #BUF, BUF, ##__VA_ARGS__);    \\\n        }                                                                      \\\n    } while (0)\n\n#else /* !FW_UPDATE_DEBUG */\n\n#define PRINT(...)\n#define DUMP(...)\n\n#endif /* FW_UPDATE_DEBUG */\n\n#endif /* __FW_UPDATE_DEBUG_H__ */\n", "meta": {"hexsha": "2344b10ebe062eefe4e03ca8d63e45ccef75c530", "size": 3947, "ext": "h", "lang": "C", "max_stars_repo_path": "debug.h", "max_stars_repo_name": "Intel-BMC/mtd-util", "max_stars_repo_head_hexsha": "708072b62a3cecb520eeaacac88b4f2c2e101fe4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "debug.h", "max_issues_repo_name": "Intel-BMC/mtd-util", "max_issues_repo_head_hexsha": "708072b62a3cecb520eeaacac88b4f2c2e101fe4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "debug.h", "max_forks_repo_name": "Intel-BMC/mtd-util", "max_forks_repo_head_hexsha": "708072b62a3cecb520eeaacac88b4f2c2e101fe4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-02-17T06:51:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-19T15:17:54.000Z", "avg_line_length": 39.47, "max_line_length": 80, "alphanum_fraction": 0.5082341018, "num_tokens": 723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07477003466112468, "lm_q2_score": 0.039048291468152245, "lm_q1q2_score": 0.0029196421065314426}}
{"text": "#pragma once\n#include \"iparamlist.h\"\n#include \"optioninfo.h\"\n#include \"configaccess.h\"\n#include \"format.h\"\n#include \"streamreader.h\"\n#include <sfun/string_utils.h>\n#include <cmdlime/errors.h>\n#include <cmdlime/customnames.h>\n#include <gsl/gsl>\n#include <vector>\n#include <sstream>\n#include <functional>\n#include <memory>\n\nnamespace cmdlime::detail{\nnamespace str = sfun::string_utils;\n\ntemplate <typename T>\nclass ParamList : public IParamList{\npublic:\n    ParamList(std::string name,\n              std::string shortName,\n              std::string type,\n              std::function<std::vector<T>&()> paramListGetter)\n        : info_(std::move(name), std::move(shortName), std::move(type))\n        , paramListGetter_(std::move(paramListGetter))\n    {\n    }\n\n    void setDefaultValue(const std::vector<T>& value)\n    {\n        hasValue_ = true;\n        defaultValue_ = value;\n    }\n\n    OptionInfo& info() override\n    {\n        return info_;\n    }\n\n    const OptionInfo& info() const override\n    {\n        return info_;\n    }\n\nprivate:\n    bool read(const std::string& data) override\n    {\n        if (!isDefaultValueOverwritten_){\n            paramListGetter_().clear();\n            isDefaultValueOverwritten_ = true;\n        }\n\n        const auto dataParts = str::split(data, \",\");\n        for (const auto& part : dataParts){\n            auto stream = std::stringstream{part};            \n            paramListGetter_().emplace_back();\n            if (!readFromStream(stream, paramListGetter_().back()))\n                return false;\n        }\n        hasValue_ = true;\n        return true;\n    }\n\n    bool hasValue() const override\n    {\n        return hasValue_;\n    }\n\n    bool isOptional() const override\n    {\n        return defaultValue_.has_value();\n    }\n\n    std::string defaultValue() const override\n    {\n        if (!defaultValue_.has_value())\n            return {};\n        auto stream = std::stringstream{};\n        stream << \"{\";\n        auto firstVal = true;\n        for (auto& val : defaultValue_.value()){\n            if (firstVal)\n                stream << val;\n            else\n                stream << \", \" << val;\n            firstVal = false;\n        }\n        stream << \"}\";\n        return stream.str();\n    }\n\nprivate:\n    OptionInfo info_;\n    std::function<std::vector<T>&()> paramListGetter_;\n    bool hasValue_ = false;\n    std::optional<std::vector<T>> defaultValue_;\n    bool isDefaultValueOverwritten_ = false;\n};\n\ntemplate <>\ninline bool ParamList<std::string>::read(const std::string& data)\n{\n    const auto dataParts = str::split(data, \",\");\n    for (const auto& part : dataParts){\n        paramListGetter_().push_back(part);\n    }\n    hasValue_ = true;\n    return true;\n}\n\ntemplate<typename T, typename TConfig>\nclass ParamListCreator{\n    using NameProvider = typename Format<ConfigAccess<TConfig>::format()>::nameProvider;\n\npublic:\n    ParamListCreator(TConfig& cfg,\n                   const std::string& varName,\n                   const std::string& type,\n                   std::function<std::vector<T>&()> paramListGetter)\n        : cfg_(cfg)\n    {\n        Expects(!varName.empty());\n        Expects(!type.empty());\n        paramList_ = std::make_unique<ParamList<T>>(NameProvider::name(varName),\n                                                    NameProvider::shortName(varName),\n                                                    NameProvider::valueName(type),\n                                                    std::move(paramListGetter));\n    }\n\n    ParamListCreator<T, TConfig>& operator<<(const std::string& info)\n    {\n        paramList_->info().addDescription(info);\n        return *this;\n    }\n\n    ParamListCreator<T, TConfig>& operator<<(const Name& customName)\n    {\n        paramList_->info().resetName(customName.value());\n        return *this;\n    }\n\n    ParamListCreator<T, TConfig>& operator<<(const ShortName& customName)\n    {\n        static_assert(Format<ConfigAccess<TConfig>::format()>::shortNamesEnabled,\n                      \"Current command line format doesn't support short names\");\n        paramList_->info().resetShortName(customName.value());\n        return *this;\n    }\n\n    ParamListCreator<T, TConfig>& operator<<(const WithoutShortName&)\n    {\n        static_assert(Format<ConfigAccess<TConfig>::format()>::shortNamesEnabled,\n                      \"Current command line format doesn't support short names\");\n        paramList_->info().resetShortName({});\n        return *this;\n    }\n\n    ParamListCreator<T, TConfig>& operator<<(const ValueName& valueName)\n    {\n        paramList_->info().resetValueName(valueName.value());\n        return *this;\n    }\n\n    ParamListCreator<T, TConfig>& operator()(std::vector<T> defaultValue = {})\n    {\n        defaultValue_ = std::move(defaultValue);\n        paramList_->setDefaultValue(defaultValue_);\n        return *this;\n    }\n\n    operator std::vector<T>()\n    {\n        ConfigAccess<TConfig>{cfg_}.addParamList(std::move(paramList_));\n        return defaultValue_;\n    }\n\nprivate:\n    std::unique_ptr<ParamList<T>> paramList_;\n    std::vector<T> defaultValue_;\n    TConfig& cfg_;\n};\n\ntemplate <typename T, typename TConfig>\nParamListCreator<T, TConfig> makeParamListCreator(TConfig& cfg,\n                                                  const std::string& varName,\n                                                  const std::string& type,\n                                                  std::function<std::vector<T>&()> paramListGetter)\n{\n    return ParamListCreator<T, TConfig>{cfg, varName, type, std::move(paramListGetter)};\n}\n\n}\n", "meta": {"hexsha": "5dfe515bd3006a285e5a9faac7f66c7cc2155be3", "size": 5564, "ext": "h", "lang": "C", "max_stars_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/paramlist.h", "max_stars_repo_name": "GerHobbelt/hypertextcpp", "max_stars_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_stars_repo_licenses": ["MS-PL"], "max_stars_count": 77.0, "max_stars_repo_stars_event_min_datetime": "2021-05-20T18:05:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T21:37:54.000Z", "max_issues_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/paramlist.h", "max_issues_repo_name": "GerHobbelt/hypertextcpp", "max_issues_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_issues_repo_licenses": ["MS-PL"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2021-05-20T22:04:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-21T08:13:28.000Z", "max_forks_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/paramlist.h", "max_forks_repo_name": "GerHobbelt/hypertextcpp", "max_forks_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_forks_repo_licenses": ["MS-PL"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-22T00:36:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-22T00:36:08.000Z", "avg_line_length": 28.5333333333, "max_line_length": 99, "alphanum_fraction": 0.5785406183, "num_tokens": 1202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12085323882332893, "lm_q2_score": 0.02405355105795286, "lm_q1q2_score": 0.0029069495505559136}}
{"text": "/*\t$Id$ */\n/*\n * Copyright (c) 2015 Kristaps Dzonsons <kristaps@kcons.eu>\n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n */\n#include <assert.h>\n#include <math.h>\n#include <stdint.h>\n#include <stdlib.h>\n\n#include <gtk/gtk.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_multifit.h>\n#include <gsl/gsl_histogram.h>\n#include <kplot.h>\n\n#include \"extern.h\"\n\nstruct simbuf *\nsimbuf_alloc_warm(struct kdata *hot, size_t bufsz)\n{\n\tstruct simbuf\t*buf;\n\n\tg_assert(NULL != hot);\n\tbuf = g_malloc0(sizeof(struct simbuf));\n\tbuf->cold = kdata_buffer_alloc(bufsz);\n\tg_assert(NULL != buf->cold);\n\treturn(buf);\n}\n\nstruct simbuf *\nsimbuf_alloc(struct kdata *hot, size_t bufsz)\n{\n\tstruct simbuf\t*buf;\n\n\tg_assert(NULL != hot);\n\tbuf = g_malloc0(sizeof(struct simbuf));\n\tbuf->hot = hot;\n\tbuf->hotlsb = kdata_buffer_alloc(bufsz);\n\tg_assert(NULL != buf->hotlsb);\n\tbuf->warm = kdata_buffer_alloc(bufsz);\n\tg_assert(NULL != buf->warm);\n\tbuf->cold = kdata_buffer_alloc(bufsz);\n\tg_assert(NULL != buf->cold);\n\treturn(buf);\n}\n\nvoid\nsimbuf_free(struct simbuf *buf)\n{\n\n\tkdata_destroy(buf->hot);\n\tkdata_destroy(buf->hotlsb);\n\tkdata_destroy(buf->warm);\n\tkdata_destroy(buf->cold);\n\tfree(buf);\n}\n\nvoid\nsimbuf_copy_hotlsb(struct simbuf *buf)\n{\n\tint\trc;\n\n\trc = kdata_buffer_copy(buf->hotlsb, buf->hot);\n\tg_assert(0 != rc);\n}\n\nvoid\nsimbuf_copy_warm(struct simbuf *buf)\n{\n\tint\trc;\n\n\trc = kdata_buffer_copy(buf->warm, buf->hotlsb);\n\tg_assert(0 != rc);\n}\n\nvoid\nsimbuf_copy_cold(struct simbuf *buf)\n{\n\tint\trc;\n\n\trc = kdata_buffer_copy(buf->cold, buf->warm);\n\tg_assert(0 != rc);\n}\n", "meta": {"hexsha": "932818158c8ca7dd01bbcaafbc2c8707a884b0b1", "size": 2216, "ext": "c", "lang": "C", "max_stars_repo_path": "buf.c", "max_stars_repo_name": "kristapsdz/bmigrate", "max_stars_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-03-03T17:13:19.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-03T17:13:19.000Z", "max_issues_repo_path": "buf.c", "max_issues_repo_name": "kristapsdz/bmigrate", "max_issues_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "buf.c", "max_forks_repo_name": "kristapsdz/bmigrate", "max_forks_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0833333333, "max_line_length": 75, "alphanum_fraction": 0.7211191336, "num_tokens": 596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16885695214168314, "lm_q2_score": 0.01717671203099644, "lm_q1q2_score": 0.0029004072413694386}}
{"text": "\n#if !defined(RANDOM_H_INCLUDED)\n#define RANDOM_H_INCLUDED\n\n#include <gsl/gsl>\n#include <iosfwd>\n\nclass Random\n{\npublic:\n\tstatic int usage(::std::ostream& strm, const ::std::string& progName,\n\t\tconst char* pMsg);\n\n\tRandom(::gsl::span<const char*const> args);\n\tint run() const;\n\n\tRandom(const Random&) = delete;\n\tRandom& operator=(const Random&) = delete;\n\tRandom(Random&&) = delete;\n\tRandom& operator=(Random&&) = delete;\n\nprivate:\n\tstatic long getRandomInteger(long low, long high);\n\n\tlong\tm_lowerBound;\n\tlong\tm_upperBound;\n\tlong\tm_count;\n};\n\n#endif // RANDOM_H_INCLUDED\n", "meta": {"hexsha": "33f1d8db227de44f8fe1131a3ea44de10156081a", "size": 572, "ext": "h", "lang": "C", "max_stars_repo_path": "Random.h", "max_stars_repo_name": "IanEmmons/CmdLineUtil", "max_stars_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Random.h", "max_issues_repo_name": "IanEmmons/CmdLineUtil", "max_issues_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Random.h", "max_forks_repo_name": "IanEmmons/CmdLineUtil", "max_forks_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.4516129032, "max_line_length": 70, "alphanum_fraction": 0.7132867133, "num_tokens": 144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.12421301483609336, "lm_q2_score": 0.023330767407859568, "lm_q1q2_score": 0.002897984958169904}}
{"text": "#pragma once\n\n#include <gsl\\gsl>\n#include <winrt\\base.h>\n#include <d3d11.h>\n#include \"DrawableGameComponent.h\"\n#include \"PointSpriteMaterial.h\"\n\nnamespace Rendering\n{\n\tclass PointSpriteDemo final : public Library::DrawableGameComponent\n\t{\n\tpublic:\n\t\tPointSpriteDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera);\n\t\tPointSpriteDemo(const PointSpriteDemo&) = delete;\n\t\tPointSpriteDemo(PointSpriteDemo&&) = default;\n\t\tPointSpriteDemo& operator=(const PointSpriteDemo&) = default;\t\t\n\t\tPointSpriteDemo& operator=(PointSpriteDemo&&) = default;\n\t\t~PointSpriteDemo();\n\n\t\tvirtual void Initialize() override;\n\t\tvirtual void Draw(const Library::GameTime& gameTime) override;\n\n\tprivate:\n\t\tvoid InitializeRandomPoints();\n\n\t\tPointSpriteMaterial mMaterial;\n\t\twinrt::com_ptr<ID3D11Buffer> mVertexBuffer;\n\t\tstd::size_t mVertexCount{ 0 };\n\t\tbool mUpdateMaterial{ true };\n\t};\n}", "meta": {"hexsha": "0723238b1e9eb441f5038d8443042c04c6c86c27", "size": 881, "ext": "h", "lang": "C", "max_stars_repo_path": "source/10.1_Point_Sprites/PointSpriteDemo.h", "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/10.1_Point_Sprites/PointSpriteDemo.h", "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/10.1_Point_Sprites/PointSpriteDemo.h", "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.53125, "max_line_length": 87, "alphanum_fraction": 0.7604994325, "num_tokens": 220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.18476751064799998, "lm_q2_score": 0.015663647074695697, "lm_q1q2_score": 0.002894133077660351}}
{"text": "#include <pygsl/error_helpers.h>\n#include <pygsl/utils.h>\n#include <gsl/gsl_errno.h>\n#include <compile.h>\n#include <frameobject.h>\n\n\nenum handleflag {\n     HANDLE_ERROR = 0,\n     HANDLE_WARNING\n};\n\nstatic int\nPyGSL_internal_error_handler(const char *reason, /* name of function*/\n\t\t\t     const char *file, /*from CPP*/\n\t\t\t     int line,   /*from CPP*/\n\t\t\t     int gsl_error,\n\t\t\t     enum handleflag flag);\n\nstatic int  \nPyGSL_error_flag(long flag)\n{\n     FUNC_MESS_BEGIN();\n     if(PyGSL_DEBUG_LEVEL() > 2){\n\t  fprintf(stderr,\"I got an Error %ld\\n\", flag);\n     }\n     if(PyErr_Occurred()){\n\t     DEBUG_MESS(3, \"Already a python error registered for flag %ld\", flag);\n\t     return GSL_FAILURE;\n     }\n     if(flag>0){\n\t  /* \n\t   * How can I end here without an Python error? \n\t   *\n\t   * 25. October 2008\n\t   * Well, very simply when the GSL_ERROR_HANDLER is set to off. \n\t   *\n\t   * All GSL modules are\n\t   * supposed to call GSL_ERROR which should call the default error\n\t   * handler.\n\t   *\n\t   * 25. October 2008\n\t   * No not when the handler is set to off, which is necessary in \n\t   * a threaded python. That's why it was a bad idea to call the\n\t   * gsl_error_handler here!\n\t   */\n\t  /*\n\t   * gsl_error(\"Unknown Reason. It was not set by GSL.\",  __FILE__, \n\t   *\t    __LINE__, flag);\n\t  */\n\t  PyGSL_internal_error_handler(\"Unknown Reason. It was not set by GSL\",  __FILE__, \n\t\t\t\t       __LINE__, flag, HANDLE_ERROR);\n\t  /* \n\t   * So lets keep the flag to return ... who knows what it will be used for...\n\t   * return GSL_FAILURE;\n\t   */\n\t  return flag;\n     }\n     FUNC_MESS_END();\n     return GSL_SUCCESS;\n}\n\nstatic PyObject * \nPyGSL_error_flag_to_pyint(long flag)\n{\n     PyObject * result = NULL;\n     FUNC_MESS_BEGIN();\n     if(GSL_FAILURE == PyGSL_error_flag(flag)){\n\t  return NULL;\n     }\n     result = PyInt_FromLong((long) flag);\n     FUNC_MESS_END();\n\n     return result;\n}\n\nstatic void \nPyGSL_add_traceback(PyObject *module, const char *filename, const char *funcname, int lineno)\n{\n     PyObject *py_srcfile = NULL, *py_funcname = NULL, *py_globals = NULL,\n\t  *empty_tuple = NULL,  *empty_string = NULL;\n     PyCodeObject *py_code = NULL;\n     PyFrameObject *py_frame = NULL;\n     \n     FUNC_MESS_BEGIN();\n\n     if(filename == NULL)\n\t  filename = \"file ???\";\n     py_srcfile = PyString_FromString(filename);\n     if (py_srcfile == NULL) \n\t  goto fail;\n\n     if(funcname == NULL)\n\t  funcname = \"function ???\";\n\n     py_funcname = PyString_FromString(funcname);\n     if (py_funcname == NULL) \n\t  goto fail;\n\n     /* Use the module if provided */\n     if(module == NULL){\n\t  py_globals = PyDict_New();\n     } else {\n\t  py_globals = PyModule_GetDict(module);\n     } \n     if (py_globals == NULL) \n\t  goto fail;\n\n     empty_tuple = PyTuple_New(0);\n     if (empty_tuple == NULL) \n\t  goto fail;\n\n     empty_string = PyString_FromString(\"\");\n     if (empty_string == NULL) \n\t  goto fail;\n\n     py_code = PyCode_New(\n\t  0,            /*int argcount,*/\n\t  0,            /*int nlocals,*/\n\t  0,            /*int stacksize,*/\n\t  0,            /*int flags,*/\n\t  empty_string, /*PyObject *code,*/\n\t  empty_tuple,  /*PyObject *consts,*/\n\t  empty_tuple,  /*PyObject *names,*/\n\t  empty_tuple,  /*PyObject *varnames,*/\n\t  empty_tuple,  /*PyObject *freevars,*/\n\t  empty_tuple,  /*PyObject *cellvars,*/\n\t  py_srcfile,   /*PyObject *filename,*/\n\t  py_funcname,  /*PyObject *name,*/\n\t  lineno,       /*int firstlineno,*/\n\t  empty_string  /*PyObject *lnotab*/\n\t  );\n     if (py_code == NULL) \n\t  goto fail;\n\n     py_frame = PyFrame_New(\n\t  PyThreadState_Get(), /*PyThreadState *tstate,*/\n\t  py_code,             /*PyCodeObject *code,*/\n\t  py_globals,          /*PyObject *globals,*/\n\t  0                    /*PyObject *locals*/\n\t  );\n\n     if (py_frame == NULL) \n\t  goto fail;\n     py_frame->f_lineno = lineno;\n     PyTraceBack_Here(py_frame);\n\n     FUNC_MESS_END();\n     return;\n\n fail:\n     FUNC_MESS(\"Handling failure\");\n     Py_XDECREF(py_srcfile);\n     Py_XDECREF(py_funcname);\n     Py_XDECREF(empty_tuple);\n     Py_XDECREF(empty_string);\n     Py_XDECREF(py_code);\n     Py_XDECREF(py_frame);\n}\n\n\n#define PyGSL_ERRNO_MAX 32\nstatic PyObject * errno_accel[PyGSL_ERRNO_MAX];\nstatic PyObject * error_dict = NULL;\nstatic PyObject * warning_dict = NULL;\nstatic PyObject * unknown_error = NULL;\n\nstatic void\nPyGSL_print_accel_object(void)\n{\n     int i;\n     FUNC_MESS_BEGIN();\n     for(i = 0; i<PyGSL_ERRNO_MAX; ++i){\n\t  DEBUG_MESS(4, \"errno_accel[%d] = %p\", i, (void*)(errno_accel[i]));\n     }\n     FUNC_MESS_END();\n}\n\nstatic int\nPyGSL_register_accel_err_object(PyObject * err_ob, long test_errno)\n{\n     PyObject *tmp;\n\n     FUNC_MESS_BEGIN();\n     assert(err_ob);\n     tmp = errno_accel[test_errno];\n     if(tmp != NULL){\n\t  PyErr_Format(PyExc_ValueError, \n\t\t       \"In errno_accel: errno %ld already occupied with object %p!\\n\",\n\t\t       test_errno, (void *) tmp);\n\t  return -2;\n     }\n     Py_INCREF(err_ob);\n     errno_accel[test_errno] = err_ob;\n     FUNC_MESS_END();\n     return 0;\n}\n\n/* register an error object to the Python dictionary */\nstatic int\n_PyGSL_register_err_object(PyObject *dict, PyObject * err_ob, PyObject *the_errno)\n{\n     PyObject *test;\n\n     FUNC_MESS_BEGIN();\n     assert(error_dict);\n     test = PyDict_GetItem(dict, the_errno);\n     if(test != NULL){\n\t  PyErr_Format(PyExc_ValueError, \n\t\t       \"In dict %p: key %p already occupied with object %p!\\n\",\n\t\t       dict, the_errno, (void *) test);\n\t  return -2;\n     }\n     Py_INCREF(err_ob);\n     PyDict_SetItem(dict, the_errno, err_ob);\n     FUNC_MESS_END();\n     return 0;\n}\n\n/* register an error object */\nstatic int\n_PyGSL_register_error(PyObject *dict, int errno_max, PyObject * err_ob)\n{\n     PyObject *tmp, *name;\n     long test_errno;\n     int flag; \n     char * c_name;\n\n     FUNC_MESS_BEGIN();\n     assert(err_ob);\n     tmp = PyObject_GetAttrString(err_ob, \"errno\");\n     if(tmp == NULL){\n\t  name = PyObject_GetAttrString(err_ob, \"__name__\");\n\n\t  if(name == NULL) \n\t       c_name = \"unknown name\";\n\t  else if (!PyString_Check(name))\n\t       c_name = \"name not str object!\";\t       \n\t  else\t       \n\t       c_name = PyString_AsString (name);\n\n\t  fprintf(stderr, \"failed to get errno from err_ob '%s' @ %p\\n\",\n\t\t  c_name, (void *) err_ob);\n\t  PyErr_Format(PyExc_AttributeError,\n\t\t       \"err_ob '%s' @ %p missed attribue 'errno!'\\n\", c_name,\n\t\t       err_ob);\n\t  return -1;\n     }\n     \n     if(!PyInt_CheckExact(tmp)){\n\t  fprintf(stderr, \"errno %p from err_ob %p was not an exact int!\\n\", \n\t\t  (void *) tmp, (void *) err_ob);\n\t  PyErr_Format(PyExc_TypeError, \"errno %p from err_ob %p was not an exact int!\\n\",\n\t\t       (void *) tmp, (void *) err_ob);\n\t  return -1;\n     }\n\n     test_errno = PyInt_AsLong(tmp);\n     if((dict == error_dict) && (test_errno < PyGSL_ERRNO_MAX)){\n\t  flag = PyGSL_register_accel_err_object(err_ob, test_errno);\n     }else{\n\t  flag = _PyGSL_register_err_object(dict, err_ob, tmp);\n     }\t       \n     if(flag != 0)\n\t  fprintf(stderr, \"Failed to register err_ob %p with errno %ld.\\n\" \n\t\t  \"\\tAlready registered?\\n\", err_ob, test_errno);\n     FUNC_MESS_END();\n     return flag;\n}\n\nstatic PyObject*\nPyGSL_register_error_objs(PyObject *self, PyObject *args, PyObject *dict, int errno_max)\n{\n     int flag, i, len;\n     PyObject *tmp;\n\n     FUNC_MESS_BEGIN();     \n     if(!PySequence_Check(args))\n\t  return NULL;\n\n     len = PySequence_Size(args);\n     DEBUG_MESS(5, \"Recieved %d error objects\", len);\n     for(i = 0; i < len; ++i){\n\t  tmp = PySequence_GetItem(args, i);\n\t  flag = _PyGSL_register_error(dict, errno_max, tmp);\n\t  if(flag != 0){\n\t       fprintf(stderr, \"Failed to register error object %d\\n\", i);\n\t       return NULL;\n\t  }\n     }\n     PyGSL_print_accel_object();\n     \n     Py_INCREF(Py_None);\n     FUNC_MESS_END();\n     return Py_None;\n}\n\nstatic PyObject*\nPyGSL_register_warnings(PyObject *self, PyObject *args)\n{\n     PyObject *tmp;\n     FUNC_MESS_BEGIN();\n     tmp = PyGSL_register_error_objs(self, args, warning_dict, 0);    \n     FUNC_MESS_END();\n     return tmp;\n}\n\nstatic PyObject*\nPyGSL_register_exceptions(PyObject *self, PyObject *args)\n{\n     PyObject *tmp;\n     FUNC_MESS_BEGIN();\n     tmp = PyGSL_register_error_objs(self, args, error_dict, PyGSL_ERRNO_MAX);\n     FUNC_MESS_END();\n     return tmp;\n}\n\n\nstatic PyObject *\nPyGSL_get_error_object(int the_errno, PyObject ** accel, int accel_max, PyObject *dict)\n{\n     PyObject *tmp;\n\n     FUNC_MESS_BEGIN();\n     assert(the_errno >= 0);\n     if (the_errno < accel_max){\n\t  DEBUG_MESS(4, \"Trying to get an error object from accel array at %p\",\n\t\t     (void*) accel);\n\t  tmp = accel[the_errno];\n     }else{\n\t  DEBUG_MESS(4, \"Trying to get an error object from dictonary at %p\",\n\t\t     (void*) dict);\n\t  tmp =  PyDict_GetItem(dict, PyInt_FromLong(the_errno));\n     }\n     if(tmp == NULL){\n\t  DEBUG_MESS(3, \"Could not find an error object for errno %d\", the_errno);\n\t  PyGSL_print_accel_object();\n\t  return unknown_error;\n     }\n     FUNC_MESS_END();\n     return tmp;\n}\n\nstatic int \nPyGSL_init_errno(void)\n{\n     int i;\n     FUNC_MESS_BEGIN();\n\n     for(i = 0; i< PyGSL_ERRNO_MAX; ++i){\n\t  DEBUG_MESS(3, \"setting errno_accel[%d] to NULL; was %p\", \n\t\t     i, (void*) (errno_accel[i]));\n\t  errno_accel[i] = NULL;\n     }\n     error_dict = PyDict_New();\n     if (error_dict == NULL)\n\t  return -1;\n\n     warning_dict = PyDict_New();\n     if (warning_dict == NULL)\n\t  return -1;\n\n     unknown_error = PyExc_ValueError;\n     FUNC_MESS_END();\n     return 0;\n}\n\n\n\n/*\n * Warnings return a flag, so one can see if the warning raises an exception\n *  or not.\n */\nstatic int\nPyGSL_internal_error_handler(const char *reason, /* name of function*/\n\t\t\t     const char *file, /*from CPP*/\n\t\t\t     int line,   /*from CPP*/\n\t\t\t     int gsl_error,\n\t\t\t     enum handleflag flag)\t\t\t     \n{\n  const char* error_explanation;\n  char error_text[255];\n  PyObject* gsl_error_object;\n\n  FUNC_MESS_BEGIN();\n  /*\n   * GSL_ENOMEM is special. I am out of memory. No fancy tricks here.\n   */\n  if (GSL_ENOMEM == gsl_error){\n       PyErr_NoMemory();\n       return -1;\n  }\n\n  /*\n   * some functions call error handler more than once before returning \n   *  report only the first (most specific) error \n   */\n  if (line < 0) line = 0;\n  /* test, if exception is already set */\n  DEBUG_MESS(5, \"Checking if python error occured, gsl error %d, line %d\", gsl_error, line);\n  if (PyErr_Occurred()) {\n       if(PyGSL_DEBUG_LEVEL() > 0)\n\t    fprintf(stderr, \"Another error occured: %s\\n\",error_text);\n       FUNC_MESS(\"Already set python error found\");\n       return -1;    \n  }\n  \n  /*\n   * Find the approbriate error\n   */\n  error_explanation = gsl_strerror(gsl_error);\n  if (reason==NULL){\n       reason = \"no reason given!\";\n  }\n\n  if (error_explanation==NULL){\n      snprintf(error_text,sizeof(error_text),\n\t       \"unknown error %d: %s\",\n\t       gsl_error, reason);\n  }else{\n      snprintf(error_text,sizeof(error_text),\n\t       \"%s: %s\",\n\t       error_explanation,reason);\n  }\n\n\n  switch(flag){\n  case HANDLE_ERROR:   \n       assert(gsl_error > 0);\n       gsl_error_object = PyGSL_get_error_object(gsl_error, errno_accel, PyGSL_ERRNO_MAX, error_dict);\n       Py_INCREF(gsl_error_object);  \n       PyErr_SetObject(gsl_error_object, PyString_FromString(error_text)); \n       FUNC_MESS(\"Set Python error object\");\n       return -1;\n       break;\n  case HANDLE_WARNING:\n       assert(gsl_error > 0);\n       gsl_error_object = PyGSL_get_error_object(gsl_error, NULL, 0, warning_dict);\n       Py_INCREF(gsl_error_object);  \n       FUNC_MESS(\"Returning python warning\");\n       return PyErr_Warn(gsl_error_object, error_text); \n       break;\n  default:\n       fprintf(stderr, \"Unknown handle %d\\n\", flag);\n  }\n  FUNC_MESS(\"Should not end here!\");\n  return -1;\n}\n/*\n * sets the right exception, but does not return to python!\n */\nstatic void \nPyGSL_module_error_handler(const char *reason, /* name of function*/\n\t\t\t   const char *file, /*from CPP*/\n\t\t\t   int line,   /*from CPP*/\n\t\t\t   int gsl_error) /* real \"reason\" */\n{\n     FUNC_MESS_BEGIN();\n     PyGSL_internal_error_handler(reason, file, line,  gsl_error, HANDLE_ERROR);\n     FUNC_MESS_END();\n}\n\nstatic int\nPyGSL_warning(const char *reason, /* name of function*/\n\t      const char *file, /*from CPP*/\n\t      int line,   /*from CPP*/\n\t      int gsl_error) /* real \"reason\" */\n{\n     int tmp;\n     FUNC_MESS_BEGIN();\n     tmp =  PyGSL_internal_error_handler(reason, file, line,  gsl_error, HANDLE_WARNING);\n     FUNC_MESS_END();\n     return tmp;\n}\n", "meta": {"hexsha": "973f3902bf6318b86e3ee4e05382314c188fc8b0", "size": 12431, "ext": "c", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/src/init/error_helpers.c", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/src/init/error_helpers.c", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/src/init/error_helpers.c", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 26.1705263158, "max_line_length": 102, "alphanum_fraction": 0.6277049312, "num_tokens": 3337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1276526286405008, "lm_q2_score": 0.022629199250306712, "lm_q1q2_score": 0.002888676768331302}}
{"text": "#include <petsc.h>\n#if PETSC_VERSION_LE(3,3,0)\n\nPETSC_EXTERN PetscErrorCode PetscOptionsGetViewer(MPI_Comm,const char[],const char[],PetscViewer*,PetscViewerFormat*,PetscBool*);\n\n#undef __FUNCT__\n#define __FUNCT__ \"PetscEListFind\"\nstatic PetscErrorCode PetscEListFind(PetscInt n,const char *const *list,const char *str,PetscInt *value,PetscBool *found)\n{\n  PetscInt  i;\n  PetscBool matched;\n  PetscErrorCode ierr;\n  PetscFunctionBegin;\n  if (found) *found = PETSC_FALSE;\n  for (i=0; i<n; i++) {\n    ierr = PetscStrcasecmp(str,list[i],&matched);CHKERRQ(ierr);\n    if (matched || !str[0]) {\n      if (found) *found = PETSC_TRUE;\n      *value = i;\n      break;\n    }\n  }\n  PetscFunctionReturn(0);\n}\n\n#undef __FUNCT__\n#define __FUNCT__ \"PetscEnumFind\"\nstatic PetscErrorCode PetscEnumFind(const char *const *enumlist,const char *str,PetscEnum *value,PetscBool *found)\n{\n  PetscInt       n,evalue;\n  PetscBool      efound;\n  PetscErrorCode ierr;\n  PetscFunctionBegin;\n  for (n = 0; enumlist[n]; n++) {\n    if (n > 50) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,\"List argument appears to be wrong or have more than 50 entries\");\n  }\n  if (n < 3) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,\"List argument must have at least two entries: typename and type prefix\");\n  n -= 3;                       /* drop enum name, prefix, and null termination */\n  ierr = PetscEListFind(n,enumlist,str,&evalue,&efound);CHKERRQ(ierr);\n  if (efound) *value = (PetscEnum)evalue;\n  if (found)  *found = efound;\n  PetscFunctionReturn(0);\n}\n\n#undef __FUNCT__\n#define __FUNCT__ \"PetscOptionsGetViewer\"\nPetscErrorCode PetscOptionsGetViewer(MPI_Comm comm,const char pre[],const char name[],PetscViewer *viewer,PetscViewerFormat *format,PetscBool *set)\n{\n  char           value[2*PETSC_MAX_PATH_LEN];\n  PetscBool      flag;\n  PetscErrorCode ierr;\n  PetscFunctionBegin;\n  PetscValidCharPointer(name,3);\n  if (format) *format = PETSC_VIEWER_DEFAULT;\n  if (set) *set = PETSC_FALSE;\n  ierr = PetscOptionsGetString(pre,name,value,sizeof(value),&flag);CHKERRQ(ierr);\n  if (flag) {\n    if (set) *set = PETSC_TRUE;\n    if (!value[0]) {\n      ierr = PetscViewerASCIIGetStdout(comm,viewer);CHKERRQ(ierr);\n      ierr = PetscObjectReference((PetscObject)*viewer);CHKERRQ(ierr);\n    } else {\n      char       *loc0_vtype,*loc1_fname,*loc2_fmt = NULL,*loc3_fmode = NULL;\n      PetscInt   cnt;\n      const char *const PetscFileModes[] = {\"READ\",\"WRITE\",\"APPEND\",\"UPDATE\",\"APPEND_UPDATE\",\"PetscFileMode\",\"PETSC_FILE_\",0};\n      const char *const viewers[] = {PETSCVIEWERASCII,PETSCVIEWERBINARY,PETSCVIEWERDRAW,PETSCVIEWERSOCKET,PETSCVIEWERMATLAB,PETSCVIEWERAMS,PETSCVIEWERVTK,0};\n      ierr = PetscStrallocpy(value,&loc0_vtype);CHKERRQ(ierr);\n      ierr = PetscStrchr(loc0_vtype,':',&loc1_fname);CHKERRQ(ierr);\n      if (loc1_fname) {\n        *loc1_fname++ = 0;\n        ierr = PetscStrchr(loc1_fname,':',&loc2_fmt);CHKERRQ(ierr);\n      }\n      if (loc2_fmt) {\n        *loc2_fmt++ = 0;\n        ierr = PetscStrchr(loc2_fmt,':',&loc3_fmode);CHKERRQ(ierr);\n      }\n      if (loc3_fmode) *loc3_fmode++ = 0;\n      ierr = PetscStrendswithwhich(*loc0_vtype ? loc0_vtype : \"ascii\",viewers,&cnt);CHKERRQ(ierr);\n      if (cnt > (PetscInt)sizeof(viewers)-1) SETERRQ1(comm,PETSC_ERR_ARG_OUTOFRANGE,\"Unknown viewer type: %s\",loc0_vtype);\n      if (!loc1_fname) {\n        switch (cnt) {\n        case 0:\n          ierr = PetscViewerASCIIGetStdout(comm,viewer);CHKERRQ(ierr);\n          break;\n        case 1:\n          if (!(*viewer = PETSC_VIEWER_BINARY_(comm))) CHKERRQ(PETSC_ERR_PLIB);\n          break;\n        case 2:\n          if (!(*viewer = PETSC_VIEWER_DRAW_(comm))) CHKERRQ(PETSC_ERR_PLIB);\n          break;\n#if defined(PETSC_USE_SOCKET_VIEWER)\n        case 3:\n          if (!(*viewer = PETSC_VIEWER_SOCKET_(comm))) CHKERRQ(PETSC_ERR_PLIB);\n          break;\n#endif\n#if defined(PETSC_HAVE_MATLAB_ENGINE)\n        case 4:\n          if (!(*viewer = PETSC_VIEWER_MATLAB_(comm))) CHKERRQ(PETSC_ERR_PLIB);\n          break;\n#endif\n#if defined(PETSC_HAVE_AMS)\n        case 5:\n          if (!(*viewer = PETSC_VIEWER_AMS_(comm))) CHKERRQ(PETSC_ERR_PLIB);\n          break;\n#endif\n        default: SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,\"Unsupported viewer %s\",loc0_vtype);\n        }\n        ierr = PetscObjectReference((PetscObject)*viewer);CHKERRQ(ierr);\n      } else {\n        if (loc2_fmt && !*loc1_fname && (cnt == 0)) { /* ASCII format without file name */\n          ierr = PetscViewerASCIIGetStdout(comm,viewer);CHKERRQ(ierr);\n          ierr = PetscObjectReference((PetscObject)*viewer);CHKERRQ(ierr);\n        } else {\n          PetscFileMode fmode;\n          ierr = PetscViewerCreate(comm,viewer);CHKERRQ(ierr);\n          ierr = PetscViewerSetType(*viewer,*loc0_vtype ? loc0_vtype : \"ascii\");CHKERRQ(ierr);\n#if defined(PETSC_HAVE_AMS)\n          ierr = PetscViewerAMSSetCommName(*viewer,loc1_fname);CHKERRQ(ierr);\n#endif\n          fmode = FILE_MODE_WRITE;\n          if (loc3_fmode && *loc3_fmode) { /* Has non-empty file mode (\"write\" or \"append\") */\n            ierr = PetscEnumFind(PetscFileModes,loc3_fmode,(PetscEnum*)&fmode,&flag);CHKERRQ(ierr);\n            if (!flag) SETERRQ1(comm,PETSC_ERR_ARG_UNKNOWN_TYPE,\"Unknown file mode: %s\",loc3_fmode);\n          }\n          ierr = PetscViewerFileSetMode(*viewer,flag?fmode:FILE_MODE_WRITE);CHKERRQ(ierr);\n          ierr = PetscViewerFileSetName(*viewer,loc1_fname);CHKERRQ(ierr);\n        }\n      }\n      if (loc2_fmt && *loc2_fmt) {\n        ierr = PetscEnumFind(PetscViewerFormats,loc2_fmt,(PetscEnum*)format,&flag);CHKERRQ(ierr);\n        if (!flag) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,\"Unknown viewer format %s\",loc2_fmt);CHKERRQ(ierr);\n        if (((int)*format) >= 5) *format = (PetscViewerFormat)(((int)*format)-2); /**/\n      }\n      ierr = PetscViewerSetUp(*viewer);CHKERRQ(ierr);\n      ierr = PetscFree(loc0_vtype);CHKERRQ(ierr);\n    }\n  }\n  PetscFunctionReturn(0);\n}\n\n#endif\n", "meta": {"hexsha": "1bdc512c56fa7fd50d65922fd33029935cd0cbdb", "size": 5875, "ext": "c", "lang": "C", "max_stars_repo_path": "src/petscvwopt.c", "max_stars_repo_name": "otherlab/petiga", "max_stars_repo_head_hexsha": "ce8c07de8511000ee6f1cbfd3fb90fda9cb31954", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-08-31T21:20:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T10:40:32.000Z", "max_issues_repo_path": "src/petscvwopt.c", "max_issues_repo_name": "otherlab/petiga", "max_issues_repo_head_hexsha": "ce8c07de8511000ee6f1cbfd3fb90fda9cb31954", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/petscvwopt.c", "max_forks_repo_name": "otherlab/petiga", "max_forks_repo_head_hexsha": "ce8c07de8511000ee6f1cbfd3fb90fda9cb31954", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-11-08T12:55:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-14T10:40:40.000Z", "avg_line_length": 41.3732394366, "max_line_length": 157, "alphanum_fraction": 0.666212766, "num_tokens": 1679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11436853221906972, "lm_q2_score": 0.025178841517728343, "lm_q1q2_score": 0.002879667147359164}}
{"text": "/* -----------------------------------------------------------------------------\n * Copyright 2021 Jonathan Haigh\n * SPDX-License-Identifier: MIT\n * ---------------------------------------------------------------------------*/\n\n#ifndef SQ_INCLUDE_GUARD_core_typeutil_h_\n#define SQ_INCLUDE_GUARD_core_typeutil_h_\n\n#include <concepts>\n#include <cstddef>\n#include <gsl/gsl>\n#include <range/v3/range/concepts.hpp>\n#include <stdexcept>\n#include <string>\n#include <system_error>\n#include <type_traits>\n#include <variant>\n\n// The following macros can't be replaced with constexpr functions or constants\n// so tell clang-tidy not to complain\n\n// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)\n#define SQ_FWD(x) static_cast<decltype(x) &&>(x)\n\n// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)\n#define SQ_ND [[nodiscard]]\n\n// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)\n#define SQ_MU [[maybe_unused]]\n\nnamespace sq {\n\n/**\n * Concept for types that can be dumped to a std::ostream.\n */\ntemplate <typename T> concept Printable = requires(T x, std::ostream &os) {\n  os << x;\n};\n\n///@{\n/**\n * Get whether the type T is a specialization of std::variant.\n */\ntemplate <typename T> struct IsVariant : std::false_type {};\n\ntemplate <typename... Types>\nstruct IsVariant<std::variant<Types...>> : std::true_type {};\n\ntemplate <typename T> inline constexpr bool is_variant_v = IsVariant<T>::value;\n///@}\n\n///@{\n/**\n * Get whether the type T is one of the alternative types of the variant V.\n */\ntemplate <typename T, typename V>\nrequires is_variant_v<V> struct IsAlternative : std::false_type {};\n\ntemplate <typename T, typename... Types>\nstruct IsAlternative<T, std::variant<Types...>>\n    : std::disjunction<std::is_same<T, Types>...> {};\n\ntemplate <typename T, typename V>\ninline constexpr bool is_alternative_v = IsAlternative<T, V>::value;\n///@}\n\n/**\n * Concept for types that are alternatives of the variant V.\n */\ntemplate <typename T, typename V> concept Alternative = is_alternative_v<T, V>;\n\n///@{\n/**\n * Get whether T can be converted to one of the variant V's alternatives.\n */\ntemplate <typename T, typename V>\nrequires is_variant_v<V> struct IsConvertibleToAlternative : std::false_type {};\n\ntemplate <typename T, typename... Types>\nstruct IsConvertibleToAlternative<T, std::variant<Types...>>\n    : std::disjunction<std::is_convertible<T, Types>...> {};\n\ntemplate <typename T, typename V>\ninline constexpr bool is_convertible_to_alternative_v =\n    IsConvertibleToAlternative<T, V>::value;\n///@}\n\n/**\n * Concept for types that are convertible to one of the variant V's\n * alternatives.\n */\ntemplate <typename T, typename V>\nconcept ConvertibleToAlternative = is_convertible_to_alternative_v<T, V>;\n\n///@{\n/**\n * A range whose distance can be obtained without invalidating the range.\n *\n * This is different to std::sized_range because it doesn't require:\n * - that size(rng) is available;\n * - that distance(rng) is a constant time operation.\n *\n * Essentially, it just rules out std::input_ranges without a known size.\n */\ntemplate <typename T>\nconcept SlowSizedRange =\n    ranges::cpp20::forward_range<T> || ranges::cpp20::sized_range<T>;\n\n/**\n * Get the name of the \"base type\" of the given expression.\n *\n * The \"base type\" is the type with no references or cv qualification.\n */\nSQ_ND std::string base_type_name(const auto &thing);\n\n/**\n * Create a std::error code from a platform dependent error code.\n */\nSQ_ND inline std::error_code make_error_code(int code) {\n  return std::make_error_code(static_cast<std::errc>(code));\n}\n\n} // namespace sq\n\nnamespace ranges {\n\n// Tell the ranges library that gsl::spans with dynamic extent are views. Note\n// that the view concept requires a default constructor so sized gsl::spans are\n// *not* views...\ntemplate <typename T>\ninline constexpr bool enable_view<gsl::span<T, gsl::dynamic_extent>> = true;\n\n// ... unless the size is zero.\ntemplate <typename T> inline constexpr bool enable_view<gsl::span<T, 0>> = true;\n\n} // namespace ranges\n\n#include \"core/typeutil.inl.h\"\n\n#endif // SQ_INCLUDE_GUARD_core_typeutil_h_\n", "meta": {"hexsha": "b6d542b8d16ce8f735dfa69c50a1b4794cd61c78", "size": 4057, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/include/core/typeutil.h", "max_stars_repo_name": "jonathanhaigh/sq", "max_stars_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-12T16:21:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-12T16:21:41.000Z", "max_issues_repo_path": "src/core/include/core/typeutil.h", "max_issues_repo_name": "jonathanhaigh/sq", "max_issues_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 44.0, "max_issues_repo_issues_event_min_datetime": "2021-02-08T19:17:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-05T18:51:38.000Z", "max_forks_repo_path": "src/core/include/core/typeutil.h", "max_forks_repo_name": "jonathanhaigh/sq", "max_forks_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7730496454, "max_line_length": 80, "alphanum_fraction": 0.698792211, "num_tokens": 951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07921032628268802, "lm_q2_score": 0.03622005612506082, "lm_q1q2_score": 0.0028690024636433406}}
{"text": "/* -----------------------------------------------------------------------------\n * Copyright 2021 Jonathan Haigh\n * SPDX-License-Identifier: MIT\n * ---------------------------------------------------------------------------*/\n\n#ifndef SQ_INCLUDE_GUARD_core_errors_h_\n#define SQ_INCLUDE_GUARD_core_errors_h_\n\n#include \"core/Primitive.fwd.h\"\n#include \"core/Token.fwd.h\"\n#include \"core/typeutil.h\"\n\n#include <cstddef>\n#include <filesystem>\n#include <fmt/format.h>\n#include <fmt/ostream.h>\n#include <gsl/gsl>\n#include <stdexcept>\n#include <string_view>\n#include <system_error>\n\nnamespace sq {\n\n/**\n * Base class for errors thrown by the SQ code.\n */\nclass Exception : public std::runtime_error {\npublic:\n  using std::runtime_error::runtime_error;\n};\n\n/**\n * Indicates that a required parameter of a field is missing.\n */\nclass ArgumentMissingError : public Exception {\npublic:\n  /**\n   * @param arg_name the name of the missing argument.\n   * @param arg_type the type of the missing argument.\n   */\n  ArgumentMissingError(std::string_view arg_name, std::string_view arg_type);\n};\n\n/**\n * Indicates that a given parameter is of incorrect type.\n */\nclass ArgumentTypeError : public Exception {\npublic:\n  /**\n   * @param received the value of the given parameter.\n   * @param type_expected the name of the type expected for the parameter.\n   */\n  ArgumentTypeError(const Primitive &received, std::string_view type_expected);\n};\n\n/**\n * Indicates a programming error in SQ.\n *\n * InternalError should never actually be thrown - they are used in places that\n * the programmer believes are dead code, but where the C++ language still\n * requires e.g. a return statement.\n */\nclass InternalError : public Exception {\npublic:\n  using Exception::Exception;\n};\n\nclass InvalidConversionError : public Exception {\npublic:\n  using Exception::Exception;\n  InvalidConversionError(std::string_view from, std::string_view to);\n};\n\n/**\n * Indicates attempted access of a non-existent field.\n */\nclass InvalidFieldError : public Exception {\npublic:\n  /**\n   * @param sq_type the SQ type of the parent of the missing field.\n   * @param field the name of the field that was requested.\n   *\n   * E.g. if the query is \"a.b\" and \"b\" is not a field of \"a\" then sq_type\n   * should be the type of \"a\" and field should be \"b\".\n   */\n  InvalidFieldError(std::string_view sq_type, std::string_view field);\n};\n\n/**\n * Indicates incorrect grammar in a query.\n */\nclass ParseError : public Exception {\npublic:\n  using Exception::Exception;\n\n  /**\n   * Create a ParseError for when an unexpected token is found.\n   *\n   * @param token the unexpected token.\n   * @param expecting the set of tokens that would have been valid in place\n   * of the unexpected token.\n   */\n  ParseError(const Token &token, const TokenKindSet &expecting);\n};\n\n/**\n * Indicates a failure to interpret part of the input query as a token.\n */\nclass LexError : public ParseError {\npublic:\n  /**\n   * @param pos position in the input query (in characters) at which the lex\n   *      error occured.\n   * @param query the full input query.\n   */\n  LexError(gsl::index pos, std::string_view query);\n};\n\n/**\n * Indicates that an array operation has been requested on a non-array type.\n */\nclass NotAScalarError : public Exception {\npublic:\n  using Exception::Exception;\n};\n\n/**\n * Indicates that an array operation has been requested on a non-array type.\n */\nclass NotAnArrayError : public Exception {\npublic:\n  using Exception::Exception;\n};\n/**\n * Indicates that a requested feature has not been implemented.\n */\nclass NotImplementedError : public Exception {\npublic:\n  using Exception::Exception;\n};\n\n/**\n * Indicates that a request to access an element outside of an allowed range.\n */\nclass OutOfRangeError : public Exception {\npublic:\n  using Exception::Exception;\n  /**\n   * @param token the token in the query where the access was requested.\n   * @param message details about the requested access.\n   */\n  OutOfRangeError(const Token &token, std::string_view message);\n};\n\n/**\n * Indicates that a pullup type field access has been requested for a field\n * access with siblings.\n */\nclass PullupWithSiblingsError : public Exception {\n  using Exception::Exception;\n};\n\n/**\n * Indicates an error was received from a system library.\n */\nclass SystemError : public Exception {\npublic:\n  using Exception::Exception;\n\n  /**\n   * Create a SystemError object.\n   *\n   * @param operation the operation that failed.\n   * @param code the system error code associated with the error.\n   */\n  SystemError(std::string_view operation, std::error_code code);\n\n  /**\n   * Get the system error code associated with this error.\n   */\n  SQ_ND std::error_code code() const;\n\nprivate:\n  std::error_code code_;\n};\n\n/**\n * Indicates that the udev library returned an error.\n */\nclass UdevError : public SystemError {\n  using SystemError::SystemError;\n};\n\n/**\n * Indicates that a filesystem error occurred.\n */\nclass FilesystemError : public SystemError {\npublic:\n  using SystemError::SystemError;\n\n  /**\n   * Create a FilesystemError object.\n   *\n   * @param operation the operation that failed.\n   * @param path the path for which the operation failed.\n   * @param code the system error code associated with the error.\n   */\n  FilesystemError(std::string_view operation, const std::filesystem::path &path,\n                  std::error_code code);\n};\n\nclass NarrowingError : public OutOfRangeError {\npublic:\n  using OutOfRangeError::OutOfRangeError;\n\n  NarrowingError(auto &&target, auto &&value, auto &&kind_of_value_format,\n                 auto &&...format_args);\n\n  NarrowingError(auto &&target, auto &&value);\n};\n\n} // namespace sq\n\n#include \"core/errors.inl.h\"\n\n#endif // SQ_INCLUDE_GUARD_core_errors_h_\n", "meta": {"hexsha": "17f055743db57ed4b537f8a8ca201f724b4ad7f4", "size": 5726, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/include/core/errors.h", "max_stars_repo_name": "jonathanhaigh/sq", "max_stars_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-12T16:21:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-12T16:21:41.000Z", "max_issues_repo_path": "src/core/include/core/errors.h", "max_issues_repo_name": "jonathanhaigh/sq", "max_issues_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 44.0, "max_issues_repo_issues_event_min_datetime": "2021-02-08T19:17:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-05T18:51:38.000Z", "max_forks_repo_path": "src/core/include/core/errors.h", "max_forks_repo_name": "jonathanhaigh/sq", "max_forks_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2246696035, "max_line_length": 80, "alphanum_fraction": 0.6935033182, "num_tokens": 1254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10230470515565383, "lm_q2_score": 0.02800752253285321, "lm_q1q2_score": 0.0028653013348638786}}
{"text": "/**\r\n * @file coroutine/net.h\r\n * @brief Async I/O operation support with system socket functions\r\n * @author github.com/luncliff (luncliff@gmail.com)\r\n * @copyright CC BY 4.0\r\n */\r\n#pragma once\r\n#ifndef COROUTINE_NET_IO_H\r\n#define COROUTINE_NET_IO_H\r\n#include <gsl/gsl>\r\n\r\n#include <coroutine/return.h>\r\n\r\n/**\r\n * @defgroup Network\r\n * Helper types to apply `co_await` for socket operations + Name resolution utilities\r\n */\r\n\r\n#if __has_include(<WinSock2.h>) // use winsock\r\n#include <WS2tcpip.h>\r\n#include <WinSock2.h>\r\n#include <ws2def.h>\r\n\r\n/** @brief indicates current import: using Windows Socket API? */\r\n/** @brief indicates current import: using <netinet/*.h>? */\r\nstatic constexpr bool is_winsock = true;\r\nstatic constexpr bool is_netinet = false;\r\n\r\nusing io_control_block = OVERLAPPED;\r\n\r\n#elif __has_include(<netinet/in.h>) // use netinet\r\n#include <fcntl.h>\r\n#include <netdb.h>\r\n#include <netinet/in.h>\r\n#include <netinet/tcp.h>\r\n#include <sys/socket.h>\r\n#include <unistd.h>\r\n\r\nstatic constexpr bool is_winsock = false;\r\nstatic constexpr bool is_netinet = true;\r\n\r\n/**\r\n * @brief Follow the definition of Windows `OVERLAPPED`\r\n * @see https://docs.microsoft.com/en-us/windows/win32/sync/synchronization-and-overlapped-input-and-output\r\n * @see https://docs.microsoft.com/en-us/windows/win32/api/minwinbase/ns-minwinbase-overlapped\r\n * @ingroup Network\r\n */\r\nstruct io_control_block {\r\n    uint64_t internal;      // uint32_t errc, int32_t flag\r\n    uint64_t internal_high; // int64_t len, socklen_t addrlen\r\n    union {\r\n        struct {\r\n            int32_t offset;\r\n            int32_t offset_high;\r\n        };\r\n        void* ptr; // sockaddr* addr;\r\n    };\r\n    int64_t handle; // int64_t sd;\r\n};\r\n\r\n#endif // winsock || netinet\r\n\r\nnamespace coro {\r\n\r\n/**\r\n * @brief This is simply a view to storage. Be aware that it doesn't have ownership\r\n * @ingroup Network\r\n */\r\nusing io_buffer_t = gsl::span<std::byte>;\r\nstatic_assert(sizeof(io_buffer_t) <= sizeof(void*) * 2);\r\n\r\n/**\r\n * @brief A struct to describe \"1 I/O request\" to system API.\r\n * @ingroup Network\r\n * When I/O request is submitted, an I/O task becomes 1 coroutine handle\r\n */\r\nclass io_work_t : public io_control_block {\r\n  public:\r\n    coroutine_handle<void> task{};\r\n    io_buffer_t buffer{};\r\n\r\n  protected:\r\n    /**\r\n     * @see await_ready\r\n     * @return true  The given socket can be use for non-blocking operations\r\n     * @return false For Windows, the return is always `false`\r\n     */\r\n    bool ready() const noexcept;\r\n\r\n  public:\r\n    /**\r\n     * @brief Multiple retrieving won't be a matter\r\n     * @return uint32_t error code from the system\r\n     */\r\n    uint32_t error() const noexcept;\r\n};\r\nstatic_assert(sizeof(io_work_t) <= 56);\r\n\r\n/**\r\n * @brief Awaitable type to perform `sendto` I/O request\r\n * @see sendto\r\n * @see WSASendTo\r\n * @ingroup Network\r\n */\r\nclass io_send_to final : public io_work_t {\r\n  private:\r\n    /**\r\n     * @brief makes an I/O request with given context(`coroutine_handle<void>`)\r\n     * @throw std::system_error\r\n     */\r\n    void suspend(coroutine_handle<void> t) noexcept(false);\r\n    /**\r\n     * @brief Fetch I/O result/error\r\n     * @return int64_t return of `sendto`\r\n     * \r\n     * This function must be used through `co_await`.\r\n     * Multiple invoke of this will lead to malfunction.\r\n     */\r\n    int64_t resume() noexcept;\r\n\r\n  public:\r\n    bool await_ready() const noexcept {\r\n        return this->ready();\r\n    }\r\n    /**\r\n     * @throw std::system_error\r\n     */\r\n    void await_suspend(coroutine_handle<void> t) noexcept(false) {\r\n        return this->suspend(t);\r\n    }\r\n    int64_t await_resume() noexcept {\r\n        return this->resume();\r\n    }\r\n};\r\nstatic_assert(sizeof(io_send_to) == sizeof(io_work_t));\r\n\r\n/**\r\n * @brief Awaitable type to perform `recvfrom` I/O request\r\n * @see recvfrom\r\n * @see WSARecvFrom\r\n * @ingroup Network\r\n */\r\nclass io_recv_from final : public io_work_t {\r\n  private:\r\n    /**\r\n     * @brief makes an I/O request with given context(`coroutine_handle<void>`)\r\n     * @throw std::system_error\r\n     */\r\n    void suspend(coroutine_handle<void> t) noexcept(false);\r\n    /**\r\n     * @brief Fetch I/O result/error\r\n     * @return int64_t return of `recvfrom`\r\n     * \r\n     * This function must be used through `co_await`.\r\n     * Multiple invoke of this will lead to malfunction.\r\n     */\r\n    int64_t resume() noexcept;\r\n\r\n  public:\r\n    bool await_ready() const noexcept {\r\n        return this->ready();\r\n    }\r\n    /**\r\n     * @throw std::system_error\r\n     */\r\n    void await_suspend(coroutine_handle<void> t) noexcept(false) {\r\n        return this->suspend(t);\r\n    }\r\n    int64_t await_resume() noexcept {\r\n        return this->resume();\r\n    }\r\n};\r\nstatic_assert(sizeof(io_recv_from) == sizeof(io_work_t));\r\n\r\n/**\r\n * @brief Awaitable type to perform `send` I/O request\r\n * @see send\r\n * @see WSASend\r\n * @ingroup Network\r\n */\r\nclass io_send final : public io_work_t {\r\n  private:\r\n    /**\r\n     * @brief makes an I/O request with given context(`coroutine_handle<void>`)\r\n     * @throw std::system_error\r\n     */\r\n    void suspend(coroutine_handle<void> t) noexcept(false);\r\n    /**\r\n     * @brief Fetch I/O result/error\r\n     * @return int64_t return of `send`\r\n     * \r\n     * This function must be used through `co_await`.\r\n     * Multiple invoke of this will lead to malfunction.\r\n     */\r\n    int64_t resume() noexcept;\r\n\r\n  public:\r\n    bool await_ready() const noexcept {\r\n        return this->ready();\r\n    }\r\n    void await_suspend(coroutine_handle<void> t) noexcept(false) {\r\n        return this->suspend(t);\r\n    }\r\n    int64_t await_resume() noexcept {\r\n        return this->resume();\r\n    }\r\n};\r\nstatic_assert(sizeof(io_send) == sizeof(io_work_t));\r\n\r\n/**\r\n * @brief Awaitable type to perform `recv` I/O request\r\n * @see recv\r\n * @see WSARecv\r\n * @ingroup Network\r\n */\r\nclass io_recv final : public io_work_t {\r\n  private:\r\n    /**\r\n     * @brief makes an I/O request with given context(`coroutine_handle<void>`)\r\n     * @throw std::system_error\r\n     */\r\n    void suspend(coroutine_handle<void> t) noexcept(false);\r\n\r\n    /**\r\n     * @brief Fetch I/O result/error\r\n     * @return int64_t return of `recv`\r\n     * \r\n     * This function must be used through `co_await`.\r\n     * Multiple invoke of this will lead to malfunction.\r\n     */\r\n    int64_t resume() noexcept;\r\n\r\n  public:\r\n    bool await_ready() const noexcept {\r\n        return this->ready();\r\n    }\r\n    void await_suspend(coroutine_handle<void> t) noexcept(false) {\r\n        return this->suspend(t);\r\n    }\r\n    int64_t await_resume() noexcept {\r\n        return this->resume();\r\n    }\r\n};\r\nstatic_assert(sizeof(io_recv) == sizeof(io_work_t));\r\n\r\n/**\r\n * @brief Constructs `io_send_to` awaitable with the given parameters\r\n * @param sd \r\n * @param remote \r\n * @param buf \r\n * @param work \r\n * @return io_send_to& \r\n * \r\n * @ingroup Network\r\n */\r\nauto send_to(uint64_t sd, const sockaddr_in& remote, io_buffer_t buf,\r\n             io_work_t& work) noexcept(false) -> io_send_to&;\r\n\r\n/**\r\n * @brief Constructs `io_send_to` awaitable with the given parameters\r\n * @param sd \r\n * @param remote \r\n * @param buf \r\n * @param work \r\n * @return io_send_to& \r\n * \r\n * @ingroup Network\r\n */\r\nauto send_to(uint64_t sd, const sockaddr_in6& remote, io_buffer_t buf,\r\n             io_work_t& work) noexcept(false) -> io_send_to&;\r\n\r\n/**\r\n * @brief Constructs `io_recv_from` awaitable with the given parameters\r\n * @param sd \r\n * @param remote \r\n * @param buf \r\n * @param work \r\n * @return io_recv_from& \r\n * \r\n * @ingroup Network\r\n */\r\nauto recv_from(uint64_t sd, sockaddr_in& remote, io_buffer_t buf,\r\n               io_work_t& work) noexcept(false) -> io_recv_from&;\r\n\r\n/**\r\n * @brief Constructs `io_recv_from` awaitable with the given parameters\r\n * @param sd \r\n * @param remote \r\n * @param buf \r\n * @param work \r\n * @return io_recv_from& \r\n * \r\n * @ingroup Network\r\n */\r\nauto recv_from(uint64_t sd, sockaddr_in6& remote, io_buffer_t buf,\r\n               io_work_t& work) noexcept(false) -> io_recv_from&;\r\n\r\n/**\r\n * @brief Constructs `io_send` awaitable with the given parameters\r\n * @param sd \r\n * @param buf \r\n * @param flag \r\n * @param work \r\n * @return io_send&\r\n *  \r\n * @ingroup Network\r\n */\r\nauto send_stream(uint64_t sd, io_buffer_t buf, uint32_t flag,\r\n                 io_work_t& work) noexcept(false) -> io_send&;\r\n\r\n/**\r\n * @brief Constructs `io_recv` awaitable with the given parameters\r\n * @param sd \r\n * @param buf \r\n * @param flag \r\n * @param work \r\n * @return io_recv& \r\n * \r\n * @ingroup Network\r\n */\r\nauto recv_stream(uint64_t sd, io_buffer_t buf, uint32_t flag,\r\n                 io_work_t& work) noexcept(false) -> io_recv&;\r\n\r\n/**\r\n * @brief Poll internal I/O works and invoke user callback\r\n * @param nano timeout in nanoseconds \r\n * @throw std::system_error\r\n * \r\n * @ingroup Network\r\n */\r\nvoid poll_net_tasks(uint64_t nano) noexcept(false);\r\n\r\n/**\r\n * @brief Thin wrapper of `getaddrinfo` for IPv4\r\n * \r\n * @param hint \r\n * @param host \r\n * @param serv \r\n * @param output\r\n * @return uint32_t Error code from the `getaddrinfo` that can be the argument of `gai_strerror`\r\n * @see getaddrinfo\r\n * @see gai_strerror\r\n * \r\n * @ingroup Network\r\n */\r\nuint32_t get_address(const addrinfo& hint, //\r\n                     gsl::czstring host, gsl::czstring serv,\r\n                     gsl::span<sockaddr_in> output) noexcept;\r\n\r\n/**\r\n * @brief Thin wrapper of `getaddrinfo` for IPv6\r\n * \r\n * @param hint \r\n * @param host \r\n * @param serv \r\n * @param output\r\n * @return uint32_t Error code from the `getaddrinfo` that can be the argument of `gai_strerror`\r\n * @see getaddrinfo\r\n * @see gai_strerror\r\n * \r\n * @ingroup Network\r\n */\r\nuint32_t get_address(const addrinfo& hint, //\r\n                     gsl::czstring host, gsl::czstring serv,\r\n                     gsl::span<sockaddr_in6> output) noexcept;\r\n\r\n/**\r\n * @brief Thin wrapper of `getnameinfo`\r\n * \r\n * @param addr \r\n * @param name \r\n * @param serv can be `nullptr`\r\n * @param flags \r\n * @return uint32_t EAI_AGAIN ...\r\n * @see getnameinfo\r\n * \r\n * @ingroup Network\r\n */\r\nuint32_t get_name(const sockaddr_in& addr, //\r\n                  gsl::basic_zstring<char, NI_MAXHOST> name, gsl::basic_zstring<char, NI_MAXSERV> serv,\r\n                  int32_t flags = NI_NUMERICHOST | NI_NUMERICSERV) noexcept;\r\n\r\n/**\r\n * @brief Thin wrapper of `getnameinfo`\r\n * @param addr \r\n * @param name \r\n * @param serv can be `nullptr`\r\n * @param flags \r\n * @return uint32_t EAI_AGAIN ...\r\n * @see getnameinfo\r\n * \r\n * @ingroup Network\r\n */\r\nuint32_t get_name(const sockaddr_in6& addr, //\r\n                  gsl::basic_zstring<char, NI_MAXHOST> name, gsl::basic_zstring<char, NI_MAXSERV> serv,\r\n                  int32_t flags = NI_NUMERICHOST | NI_NUMERICSERV) noexcept;\r\n\r\n} // namespace coro\r\n\r\n#endif // COROUTINE_NET_IO_H\r\n", "meta": {"hexsha": "3c44827d01ad5fd5091201b0ec77f43543479b09", "size": 10815, "ext": "h", "lang": "C", "max_stars_repo_path": "interface/coroutine/net.h", "max_stars_repo_name": "dmitrykobets-msft/coroutine", "max_stars_repo_head_hexsha": "114a4342b9ceaa149e3014f7b9346025d0722c19", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "interface/coroutine/net.h", "max_issues_repo_name": "dmitrykobets-msft/coroutine", "max_issues_repo_head_hexsha": "114a4342b9ceaa149e3014f7b9346025d0722c19", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "interface/coroutine/net.h", "max_forks_repo_name": "dmitrykobets-msft/coroutine", "max_forks_repo_head_hexsha": "114a4342b9ceaa149e3014f7b9346025d0722c19", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.970074813, "max_line_length": 108, "alphanum_fraction": 0.630420712, "num_tokens": 2690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.05033063544642758, "lm_q2_score": 0.056652424511612155, "lm_q1q2_score": 0.0028513525252502094}}
{"text": "/* Copyright (c) 2020 Felix Kutzner (github.com/fkutzner)\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n\n Except as contained in this notice, the name(s) of the above copyright holders\n shall not be used in advertising or otherwise to promote the sale, use or\n other dealings in this Software without prior written authorization.\n\n*/\n\n#pragma once\n\n#include <libincmonk/verifier/Traits.h>\n\n#include <cstdint>\n#include <gsl/span>\n#include <iterator>\n#include <limits>\n#include <memory>\n#include <optional>\n#include <ostream>\n#include <unordered_map>\n#include <vector>\n\nnamespace incmonk::verifier {\n\nclass Var {\npublic:\n  constexpr explicit Var(uint32_t id);\n  constexpr Var();\n\n  constexpr auto getRawValue() const -> uint32_t;\n\n  constexpr auto operator==(Var rhs) const -> bool;\n  constexpr auto operator!=(Var rhs) const -> bool;\n  constexpr auto operator<(Var rhs) const -> bool;\n  constexpr auto operator<=(Var rhs) const -> bool;\n  constexpr auto operator>(Var rhs) const -> bool;\n  constexpr auto operator>=(Var rhs) const -> bool;\n\nprivate:\n  uint32_t m_rawValue;\n};\n\ntemplate <>\nstruct Key<Var> {\n  constexpr static auto get(Var const& item) -> std::size_t;\n};\n\nauto operator\"\"_Var(unsigned long long cnfValue) -> Var;\nauto operator<<(std::ostream& stream, Var var) -> std::ostream&;\n\n\nclass Lit {\npublic:\n  constexpr explicit Lit(Var v, bool positive);\n  constexpr Lit();\n\n  constexpr auto getRawValue() const -> uint32_t;\n  constexpr auto getVar() const -> Var;\n  constexpr auto isPositive() const -> bool;\n  constexpr auto operator-() const -> Lit;\n\n  constexpr auto operator==(Lit rhs) const -> bool;\n  constexpr auto operator!=(Lit rhs) const -> bool;\n  constexpr auto operator<(Lit rhs) const -> bool;\n  constexpr auto operator<=(Lit rhs) const -> bool;\n  constexpr auto operator>(Lit rhs) const -> bool;\n  constexpr auto operator>=(Lit rhs) const -> bool;\n\nprivate:\n  uint32_t m_rawValue;\n};\n\nauto operator\"\"_Lit(unsigned long long cnfValue) -> Lit;\nauto operator<<(std::ostream& stream, Lit lit) -> std::ostream&;\n\ntemplate <>\nstruct Key<Lit> {\n  constexpr static auto get(Lit const& item) -> std::size_t;\n};\n\nauto maxLit(Var var) noexcept -> Lit;\n\n\nenum class ClauseVerificationState : uint8_t {\n  /// The clause is part of the problem instance, no verification required\n  Irredundant = 0,\n\n  /// The clause is a lemma and has not yet been determined to be relevant for the proof\n  Passive = 1,\n\n  /// The clause is a lemma and has been determinined relevant for the proof. RAT property\n  /// verification is pending\n  VerificationPending = 2,\n\n  /// The clause is a lemma and its RAT property has been verified.\n  Verified = 3\n};\n\nusing ProofSequenceIdx = uint32_t;\n\nclass Clause final {\npublic:\n  using size_type = uint32_t;\n  using iterator = Lit*;             // TODO: write proper iterator\n  using const_iterator = Lit const*; // TODO: write proper const_iterator\n\n  auto operator[](size_type idx) noexcept -> Lit&;\n  auto operator[](size_type idx) const noexcept -> Lit const&;\n\n  auto getLiterals() noexcept -> gsl::span<Lit>;\n  auto getLiterals() const noexcept -> gsl::span<Lit const>;\n\n  auto size() const noexcept -> size_type;\n  auto empty() const noexcept -> bool;\n\n  void setState(ClauseVerificationState state) noexcept;\n  auto getState() const noexcept -> ClauseVerificationState;\n\n  auto getAddIdx() const noexcept -> ProofSequenceIdx;\n\nprivate:\n  friend class ClauseCollection;\n  Clause(size_type size, ClauseVerificationState initialState, ProofSequenceIdx addIdx) noexcept;\n\n  size_type m_size;\n  uint32_t m_flags;\n  ProofSequenceIdx m_pointOfAdd;\n  Lit m_firstLit;\n};\n\nauto operator<<(std::ostream& stream, Clause const& clause) -> std::ostream&;\n\nclass ClauseFinder;\nclass ClauseOccurrences;\n\nclass ClauseCollection final {\npublic:\n  ClauseCollection();\n  ~ClauseCollection();\n\n  class Ref {\n  public:\n    auto operator==(Ref rhs) const noexcept -> bool;\n    auto operator!=(Ref rhs) const noexcept -> bool;\n\n  private:\n    std::size_t m_offset = 0;\n    friend class ClauseCollection;\n    friend class RefIterator;\n    friend struct std::hash<Ref>;\n  };\n\n  class RefIterator {\n  public:\n    using value_type = Ref;\n    using reference = Ref&;\n    using pointer = Ref*;\n    using difference_type = intptr_t;\n    using iterator_category = std::input_iterator_tag;\n\n    RefIterator(char const* m_allocatorMemory, std::size_t highWaterMark) noexcept;\n    RefIterator() noexcept;\n\n    auto operator*() const noexcept -> Ref const&;\n    auto operator->() const noexcept -> Ref const*;\n    auto operator++(int) noexcept -> RefIterator;\n    auto operator++() noexcept -> RefIterator&;\n\n    auto operator==(RefIterator const& rhs) const noexcept -> bool;\n    auto operator!=(RefIterator const& rhs) const noexcept -> bool;\n\n    RefIterator(RefIterator const& rhs) noexcept = default;\n    RefIterator(RefIterator&& rhs) noexcept = default;\n    auto operator=(RefIterator const& rhs) noexcept -> RefIterator& = default;\n    auto operator=(RefIterator&& rhs) noexcept -> RefIterator& = default;\n\n  private:\n    char const* m_clausePtr;\n    std::size_t m_distanceToEnd;\n    Ref m_currentRef;\n  };\n\n  using LitSpan = gsl::span<Lit const>;\n  using OccRng = gsl::span<Ref const>;\n\n\n  auto add(LitSpan lits, ClauseVerificationState initialState, ProofSequenceIdx addIdx) -> Ref;\n  auto resolve(Ref cref) noexcept -> Clause&;\n  auto resolve(Ref cref) const noexcept -> Clause const&;\n  auto find(LitSpan lits) const noexcept -> std::optional<Ref>;\n  auto getOccurrences(Lit lit) const noexcept -> OccRng;\n\n  auto begin() const noexcept -> RefIterator;\n  auto end() const noexcept -> RefIterator;\n\n  auto getMaxVar() const noexcept -> Var;\n\n\n  ClauseCollection(ClauseCollection&&) noexcept;\n  auto operator=(ClauseCollection &&) -> ClauseCollection&;\n\n  ClauseCollection(ClauseCollection const&) = delete;\n  auto operator=(ClauseCollection const&) -> ClauseCollection& = delete;\n\nprivate:\n  void resize(std::size_t newSize);\n  auto isValidRef(Ref cref) const noexcept -> bool;\n\n  char* m_memory = nullptr;\n  std::size_t m_currentSize = 0;\n  std::size_t m_highWaterMark = 0;\n\n  Var m_maxVar = 0_Var;\n\n  std::vector<Ref> m_deletedClauses;\n  mutable std::unique_ptr<ClauseFinder> m_clauseFinder;\n  mutable std::unique_ptr<ClauseOccurrences> m_clauseOccurrences;\n};\n\nusing CRef = ClauseCollection::Ref;\nusing OptCRef = std::optional<CRef>;\n}\n\n#include \"ClauseImpl.h\"\n", "meta": {"hexsha": "600be576742e1351c1c5055856fbfb9e060af7d9", "size": 7377, "ext": "h", "lang": "C", "max_stars_repo_path": "lib/libincmonk/verifier/Clause.h", "max_stars_repo_name": "fkutzner/IncrementalMonkey", "max_stars_repo_head_hexsha": "fc87d8b408cd57a69f0c1bf3579ccbdfd60d7c13", "max_stars_repo_licenses": ["X11", "MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-12T17:58:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-12T17:58:09.000Z", "max_issues_repo_path": "lib/libincmonk/verifier/Clause.h", "max_issues_repo_name": "fkutzner/IncrementalMonkey", "max_issues_repo_head_hexsha": "fc87d8b408cd57a69f0c1bf3579ccbdfd60d7c13", "max_issues_repo_licenses": ["X11", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/libincmonk/verifier/Clause.h", "max_forks_repo_name": "fkutzner/IncrementalMonkey", "max_forks_repo_head_hexsha": "fc87d8b408cd57a69f0c1bf3579ccbdfd60d7c13", "max_forks_repo_licenses": ["X11", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3580246914, "max_line_length": 97, "alphanum_fraction": 0.7283448556, "num_tokens": 1735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11436853523769842, "lm_q2_score": 0.02479815884424345, "lm_q1q2_score": 0.0028361291036078998}}
{"text": "#pragma once\n#include \"../utils/utils.h\"\n#include <gsl/gsl>\n#include <limits>\n\nnamespace Halley {\n\tclass Compression {\n\tpublic:\n\t\tstatic Bytes compress(const Bytes& bytes);\n\t\tstatic Bytes compress(gsl::span<const gsl::byte> bytes);\n\t\tstatic Bytes decompress(const Bytes& bytes, size_t maxSize = std::numeric_limits<size_t>::max());\n\t\tstatic Bytes decompress(gsl::span<const gsl::byte> bytes, size_t maxSize = std::numeric_limits<size_t>::max());\n\t\tstatic std::shared_ptr<const char> decompressToSharedPtr(gsl::span<const gsl::byte> bytes, size_t& outSize, size_t maxSize = std::numeric_limits<size_t>::max());\n\n\t\tstatic Bytes compressRaw(gsl::span<const gsl::byte> bytes, bool insertLength);\n\t\tstatic Bytes decompressRaw(gsl::span<const gsl::byte> bytes, size_t maxSize, size_t expectedSize = 0);\n\t};\n}\n", "meta": {"hexsha": "857746ce187d8149897da8797e549106894c0bca", "size": 803, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engine/utils/include/halley/bytes/compression.h", "max_stars_repo_name": "sunhay/halley", "max_stars_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3262.0, "max_stars_repo_stars_event_min_datetime": "2016-04-10T15:24:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:47:08.000Z", "max_issues_repo_path": "src/engine/utils/include/halley/bytes/compression.h", "max_issues_repo_name": "sunhay/halley", "max_issues_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 53.0, "max_issues_repo_issues_event_min_datetime": "2016-10-09T16:25:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-10T13:52:37.000Z", "max_forks_repo_path": "src/engine/utils/include/halley/bytes/compression.h", "max_forks_repo_name": "sunhay/halley", "max_forks_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 193.0, "max_forks_repo_forks_event_min_datetime": "2017-10-23T06:08:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T12:59:58.000Z", "avg_line_length": 42.2631578947, "max_line_length": 163, "alphanum_fraction": 0.7397260274, "num_tokens": 200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11596071214366646, "lm_q2_score": 0.02442308876707257, "lm_q1q2_score": 0.002832118766177716}}
{"text": "#pragma once\n\n#include \"../common.h\"\n#include \"../concepts.h\"\n#include <boost/container/flat_set.hpp>\n#include <boost/outcome/result.hpp>\n#include <boost/outcome/try.hpp>\n#include <fmt/format.h>\n#include <gsl/gsl-lite.hpp>\n#include <string>\n#include <string_view>\n#include <yaml-cpp/yaml.h>\n\nnamespace angonoka::validation {\nusing boost::container::flat_set;\nnamespace bo = boost::outcome_v2;\nusing result = bo::result<void, std::string>;\nusing namespace fmt::literals;\n\ntemplate <typename T>\nconcept Check\n    = std::is_invocable_v<T, const YAML::Node&, gsl::czstring>;\ntemplate <typename T>\nconcept Attribute = std::is_convertible_v<\n    decltype(std::declval<T>().name),\n    std::string_view> && Check<T>;\ntemplate <typename T>\nconcept AttrOrStr = String<T> || Attribute<T>;\n\n/**\n    YAML scalar.\n\n    Example:\n\n    hello: \"world\"\n           ^\n           | Scalar\n\n    scalar()\n\n    Means that the value has to be a scalar and\n    not a map or a sequence, etc.\n\n    @return Check function\n*/\nconstexpr Check auto scalar()\n{\n    return\n        [](const YAML::Node& node, std::string_view scope) -> result {\n            if (!node || node.IsNull())\n                return R\"(\"{}\" can't be empty.)\"_format(scope);\n            if (!node.IsScalar())\n                return R\"(\"{}\" has invalid type.)\"_format(scope);\n            return bo::success();\n        };\n}\n\nnamespace detail {\n    /**\n        Helper class for required and optional YAML fields.\n\n        @var name   Parameter's name\n        @var check  Function to apply to the field\n    */\n    template <Check T> struct functor {\n        gsl::czstring name;\n        T check;\n\n        constexpr functor(gsl::czstring name, T check)\n            : name{name}\n            , check{check}\n        {\n        }\n        explicit constexpr functor(gsl::czstring name)\n            : functor{name, scalar()}\n        {\n        }\n    };\n\n    /**\n        Join YAML path parts.\n\n        @param a Root path\n        @param b New path\n\n        @return Concatenation of parts separated by a \".\".\n    */\n    template <String T1, String T2> std::string join(T1&& a, T2&& b)\n    {\n        if (std::empty(a)) return std::forward<T2>(b);\n        return \"{}.{}\"_format(\n            std::forward<T1>(a),\n            std::forward<T2>(b));\n    }\n} // namespace detail\n\n/**\n    Requred YAML field.\n\n    Example:\n\n    required(\"hello\")\n\n    Means that the field \"hello\" is required and\n    it has to be a scalar value.\n\n    @var name   Parameter's name\n    @var check  Function to apply to the field\n*/\ntemplate <Check T> struct required : detail::functor<T> {\n    using detail::functor<T>::functor;\n    result\n    operator()(const YAML::Node& node, std::string_view scope) const\n    {\n        if (const auto n = node[this->name])\n            return this->check(n, detail::join(scope, this->name));\n        return R\"(\"{}\" is missing a \"{}\" attribute.)\"_format(\n            scope,\n            this->name);\n    }\n};\n\ntemplate <Check T> required(gsl::czstring, T) -> required<T>;\nrequired(gsl::czstring)->required<decltype(scalar())>;\n\nnamespace detail {\n    /**\n        Extract the map attribute's name.\n\n        If an attribute is a string literal, pass the argument as is.\n\n        @param attr Either an attribute or a string literal\n\n        @return Attribute name\n    */\n    constexpr auto attr_name(gsl::czstring attr) { return attr; }\n    constexpr auto attr_name(Attribute auto&& attr)\n    {\n        return attr.name;\n    }\n\n    /**\n        Extract or construct an attribute check function.\n\n        If an attrubte is a string literal, construct\n        the required attrubte with the string literal as it's\n        name.\n\n        @param attr Either an attribute or a string literal\n\n        @return Check function\n    */\n    constexpr auto attr_check(gsl::czstring attr)\n    {\n        return required(attr);\n    }\n    constexpr auto attr_check(Attribute auto&& attr) { return attr; }\n} // namespace detail\n\n/**\n    Optional YAML field.\n\n    Example:\n\n    optional(\"hello\")\n\n    Means that the field \"hello\" is optional and if\n    present, it has to be a scalar value.\n\n    @var name  Parameter's name\n    @var check Function to apply to the field\n*/\ntemplate <Check T> struct optional : detail::functor<T> {\n    using detail::functor<T>::functor;\n\n    result\n    operator()(const YAML::Node& node, std::string_view scope) const\n    {\n        if (const auto n = node[this->name])\n            return this->check(n, detail::join(scope, this->name));\n        return bo::success();\n    }\n};\n\ntemplate <Check T> optional(gsl::czstring, T) -> optional<T>;\noptional(gsl::czstring)->optional<decltype(scalar())>;\n\n/**\n    YAML array.\n\n    Validates each value of the array with the provided function.\n\n    Example:\n\n    sequence(scalar())\n\n    Means that the value has to be a sequence (array) of\n    scalar values.\n\n    @param check Function to apply to each item\n\n    @return Check function\n*/\nconstexpr Check auto sequence(Check auto check)\n{\n    return [=](const YAML::Node& node,\n               std::string_view scope) -> result {\n        if (!node || !node.IsSequence()) {\n            return R\"(\"{}\" is expected to be a sequence.)\"_format(\n                scope);\n        }\n        for (gsl::index i{0}; i < std::size(node); ++i) {\n            BOOST_OUTCOME_TRY(\n                check(node[i], \"{}[{}]\"_format(scope, i)));\n        }\n        return bo::success();\n    };\n}\n\nconstexpr Check auto sequence() { return sequence(scalar()); }\n\n/**\n    YAML map.\n\n    Matches specified parameters exactly, no extra fields permitted.\n\n    Example:\n\n    attributes(\"first\", optional(\"second\"))\n\n    Means that the value has to be a map with a required field\n    \"first\", which has to be a scalar and an optional field \"second\"\n    which also has to be a scalar.\n\n    @param attrs Sequence of optional or required parameters\n\n    @return Check function\n*/\nconstexpr Check auto attributes(AttrOrStr auto... attrs)\n{\n    return [=](const YAML::Node& node,\n               std::string_view scope = {}) -> result {\n        if (!node || node.IsScalar() || node.IsSequence())\n            return R\"(\"{}\" is expected to be a map.)\"_format(scope);\n        flat_set<std::string_view> unique_fields;\n        for (auto&& n : node) {\n            const auto& attr_name = n.first.Scalar();\n            if (attr_name.empty())\n                return R\"(Empty attribute in \"{}\".)\"_format(scope);\n            if (!unique_fields.emplace(attr_name).second) {\n                return R\"(Duplicate attribute \"{}\" in \"{}\".)\"_format(\n                    attr_name,\n                    scope);\n            }\n            if (!((attr_name == detail::attr_name(attrs)) || ...)) {\n                return R\"(Unexpected attribute \"{}\" in \"{}\".)\"_format(\n                    attr_name,\n                    scope);\n            }\n        }\n        result r = bo::success();\n        ((r = detail::attr_check(attrs)(node, scope)) && ...);\n        return r;\n    };\n}\n\n/**\n    YAML map.\n\n    Validates each value of the map with the provided function.\n    Used when the number of map fields may vary.\n\n    Example:\n\n    foo:\n      bar1: 1\n      bar2: 2\n      bar3: 3\n\n    values(scalar())\n\n    @param check Function to apply to each value\n\n    @return Check function\n*/\nconstexpr Check auto values(Check auto check)\n{\n    return [=](const YAML::Node& node,\n               std::string_view scope) -> result {\n        if (!node || !node.IsMap())\n            return R\"(\"{}\" is expected to be a map.)\"_format(scope);\n        for (auto&& n : node) {\n            BOOST_OUTCOME_TRY(check(\n                n.second,\n                detail::join(scope, n.first.Scalar())));\n        }\n        return bo::success();\n    };\n}\n\n/**\n    Match at least one of the validators.\n\n    Example:\n\n    required(\"example\", any_of(scalar(), attributes(\"foo\", \"bar\")))\n\n    Means the value has to either be a singular scalar value or\n    a map with 2 fields \"foo\" and \"bar.\n\n    example: \"hello\"\n\n    or\n\n    example:\n      foo: 1\n      bar: 2\n\n    @param check Functions to match\n\n    @return Check function\n*/\nconstexpr Check auto any_of(Check auto... checks)\n{\n    return [=](const YAML::Node& node,\n               std::string_view scope) -> result {\n        result r = bo::success();\n        ((r = checks(node, scope)) || ...);\n        return r;\n    };\n}\n} // namespace angonoka::validation\n", "meta": {"hexsha": "daa03ca1e06c2460e53326e3657a93ad5d029a3d", "size": 8344, "ext": "h", "lang": "C", "max_stars_repo_path": "src/config/validation.h", "max_stars_repo_name": "coffee-lord/angonoka", "max_stars_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-10-23T18:05:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T21:53:24.000Z", "max_issues_repo_path": "src/config/validation.h", "max_issues_repo_name": "coffee-lord/angonoka", "max_issues_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2022-02-12T19:52:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-12T19:55:52.000Z", "max_forks_repo_path": "src/config/validation.h", "max_forks_repo_name": "coffee-lord/angonoka", "max_forks_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0570570571, "max_line_length": 70, "alphanum_fraction": 0.5800575264, "num_tokens": 1963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12085322299118383, "lm_q2_score": 0.023330770039329245, "lm_q1q2_score": 0.002819598754119088}}
{"text": "/*\n * edges.h -- \u00e9lek effekt\u00edv t\u00e1rol\u00e1sa: lista az id-k szerint rendezve,\n * \tebben gyorsan lehet keresni + binary heap az id\u0151pontok szerint, \u00edgy\n * \ta legr\u00e9gebbit gyorsan ki lehet v\u00e1lasztani\n * \n * Copyright 2013 Kondor D\u00e1niel <dani@thinkpad-r9r>\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n * \n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n * MA 02110-1301, USA.\n * \n * \n */\n\n\n#ifndef EDGES_H\n#define EDGES_H\n\n#ifndef _GNU_SOURCE\n#define _GNU_SOURCE\n#endif\n\n#include \"idlist.h\"\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <ctype.h>\n#include <sys/mman.h>\n//~ #include <gsl/gsl_rng.h>\n#include <limits.h>\n//~ #include \"mt19937.h\"\n\n \n//v\u00e1ltoz\u00e1s: hashmap haszn\u00e1lata helyett el\u0151re beolvassuk az \u00f6sszes lehets\u00e9ges \u00e9lt, sorbarendezve (felt\u00e9tel:\n//\ta bemeneti f\u00e1jlban sorbarendezve kell legyenek, minden \u00e9l csak egyszer -- ezt egyszer\u0171bb az SQL Serverrel\n//\tmegcsin\u00e1ltatni), ebben tudunk m\u00e1r gyorsan keresni\n\ntypedef struct edgehelper_t {\n\tconst idlist* il;\n\tuint64_t* index;\n\tuint64_t* outdeg;\n} edgehelper;\n\n\n//heap strukt\u00fara az \u00e9lek t\u00e1rol\u00e1s\u00e1hoz (\u00f6sszes \u00e9l, id\u0151 szerint rendezve)\ntypedef struct edge_t { //egy \u00e9l, heap ezekb\u0151l, timestamp szerint rendezve\n\tuint32_t p1; //els\u0151 pont -> itt az \"igazi\" ID-ket t\u00e1roljuk (a h\u00e1l\u00f3zatbeli azonos\u00edt\u00f3kat, ezeknek nem kell szekvenci\u00e1lisnak lenni)\n\tuint32_t p2; //m\u00e1sodik pont (p1->p2 \u00e9l)\n\tunsigned int offset; //heap-beli offset (heap[i].offset == i mindig) -- vagy: tranzakci\u00f3 ID-k\n\tunsigned int timestamp; //legutols\u00f3 aktivit\u00e1s\n} edge; //m\u00e9ret -- 16 b\u00e1jt\n\ntypedef struct edges_t {\n\tedge* e; //\u00e9lek t\u00e1rol\u00e1sa itt, id-k szerint rendezve\n\tuint64_t nedges;\n\tuint64_t edges_size;\n\tuint64_t edges_grow;\n\tedgehelper* h;\n} edges;\n\n\n/*\n * egy t\u00f6mb (unsigned int-ekb\u0151l), amiben az edge-ekre mutat\u00f3 pointerek vannak, ezek binary heap-ben:\n * \tunsigned int* heap;\n * \tedges[heap[i]].timestamp < edges[heap[2*i+1 / 2*i+2]].timestamp\n * \u00e9s edges[heap[i]].offset == i\n * \n */\n\n//hash fv. (k\u00e9t 32-bites id-b\u0151l egy 64-bites sz\u00e1m, ezeket tal\u00e1n gyorsabb \u00f6sszehasonl\u00edtani\nstatic inline uint64_t edgehash(const edge* e, const unsigned int i) {\n\t\tuint64_t r = e[i].p1;\n\t\tr = r << 32;\n\t\tuint64_t r2 = e[i].p2;\n\t\treturn r | r2;\n}\n\n//k\u00e9t \u00e9l \u00f6sszehasonl\u00edt\u00e1sa, eredm\u00e9ny: -1, ha eh2-nek e[i] el\u0151tt kell lenni, 1 ha ut\u00e1na, 0, ha megegyeznek\nstatic inline int cmpedge(const edge* e, uint64_t i, uint64_t eh2) {\n\tuint64_t eh1 = edgehash(e,i);\n\tif(eh1 < eh2) return 1;\n\tif(eh1 > eh2) return -1;\n\treturn 0;\n}\n\nstatic inline int cmpedge2(const edge* e, uint64_t i, uint64_t j) {\n\tuint64_t eh2 = edgehash(e,j);\n\treturn cmpedge(e,i,eh2);\n}\n\n//\u00e9leket t\u00e1rol\u00f3 strukt\u00fara lefoglal\u00e1sa / n\u00f6veszt\u00e9se:\n//\tha e == 0, akkor \u00faj strukt\u00fara lefoglal\u00e1sa\n//\tha e != 0, akkor n\u00f6veszt\u00e9s (mremap())\n//eredm\u00e9ny: 0, ha hiba t\u00f6rt\u00e9nt (nem siker\u00fclt mem\u00f3ri\u00e1t lefoglalni)\n//ha a bemeneti e nem volt 0, akkor azt nem szabad\u00edtottuk fel\n//edges* pointer, ha rendben volt (ha e != 0, akkor e-t adjuk vissza)\nedges* edges_grow(edges* e);\n\n//\u00e9lek felszabad\u00edt\u00e1sa\nvoid edges_free(edges* e);\n\n//\u00e9lek beolvas\u00e1sa egy f\u00e1jlb\u00f3l -- a f\u00e1jlban m\u00e1r megfelel\u0151en rendezve kell lenni\u00fck\nedges* edges_read(FILE* f);\n\n//\u00e9lek beolvas\u00e1sa egy f\u00e1jlb\u00f3l -- a f\u00e1jlban m\u00e1r megfelel\u0151en rendezve kell lenni\u00fck\nedges* edges_read2(FILE* f); //+ timestamp-ok is meg vannak adva\n\n//beolvas\u00e1s \u00e1ltal\u00e1nosan:\n//flags \u00e9rt\u00e9kei:\n#define EFLAGS_T1 1 //id\u0151pontokat is beolvasunk \u00e9s id\u0151 szerint rendezz\u00fck az eredm\u00e9nyt (ha nincs megadva, akkor csak\n\t//\u00e9leket olvasunk be \u00e9s minden \u00e9lb\u0151l csak egyet tartunk meg)\n#define EFLAGS_SELF 2 //megenged\u00fcnk \u00f6nmag\u00e1ba mutat\u00f3 \u00e9leket (p1->p1)\n#define EFLAGS_TXID 4 //tranzakci\u00f3 ID-ket is beolvasunk (legutols\u00f3 oszlop, az offset t\u00f6mbbe t\u00e1roljuk el)\n#define EFLAGS_ERROR_OVERFLOW 8 // overflow hib\u00e1t jelent (k\u00fcl\u00f6nben csak kihagyjuk)\nedges* edges_read0(FILE* f, int flags);\n\n//\u00e9lek \u00e1tm\u00e1sol\u00e1sa egy \u00faj t\u00f6mbbe, ha r == 1, akkor ford\u00edtva (p2->p1, p1->p2)\nedges* edges_copy(edges* e1, int r);\n\n//r\u00e9szhalmaz \u00e1tm\u00e1sol\u00e1sa\nedges* edges_copy2(edges* e1, uint64_t start, uint64_t end, int r);\n\n//\u00e9l megkeres\u00e9se, eredm\u00e9ny: a t\u00f6mb\u00f6n (e->e) bel\u00fcli sorsz\u00e1m, ha megtal\u00e1ltuk, e->nedges, ha nem tal\u00e1ltuk\nuint64_t edges_find(edges* e, uint32_t p1, uint32_t p2);\n\n//olyan \u00e9l keres\u00e9se, ahol az els\u0151 ID megegyezik a megadottal\nuint64_t edges_findfirst(edges* e, uint32_t p1);\n\n//\u00e9lek sorbarendez\u00e9se az ID-k szerint\nvoid edges_sort1(edges* e);\n\n\n//v\u00e9letlen cser\u00e9k\n//a->b, c->d helyett a->d, c->b\n//N darab csere\n/*\nvoid edges_rand1(edges* e, uint64_t N, gsl_rng* r);\n\n//v\u00e9letlen cser\u00e9k, a sikertelen pr\u00f3b\u00e1lkoz\u00e1sok is belesz\u00e1m\u00edtanak a cser\u00e9k sz\u00e1m\u00e1ba\n//a->b, c->d helyett a->d, c->b\nvoid edges_rand2(edges* e, uint64_t N, gsl_rng* r);\n*/\n\n// create a \"helper\" for faster edge lookups: store the starting index for each addr, making it unnecessary to perform binary\n//\tsearch for the whole set, and also return result in O(1) time for addresses with outdeg == 1\nint edges_createhelper(edges* e, const idlist* il);\n\n\n//ID-k gener\u00e1l\u00e1sa N db \u00e9l alapj\u00e1n\nidlist* ids_gen(const edge* e, unsigned int N);\n\n//N db \u00e9lben az ID-k kicser\u00e9l\u00e9se a sorsz\u00e1mukra\nint ids_replace(const idlist* il, edge* e, uint64_t N);\n\n\n#endif\n\n\n\n", "meta": {"hexsha": "7fddbf401acb057baafdd71d909fbe95469cada7", "size": 5675, "ext": "h", "lang": "C", "max_stars_repo_path": "patestgen/edges.h", "max_stars_repo_name": "dkondor/patest_new", "max_stars_repo_head_hexsha": "ebdb1bae08d32274b16d29fcd07451a7451c8b5b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "patestgen/edges.h", "max_issues_repo_name": "dkondor/patest_new", "max_issues_repo_head_hexsha": "ebdb1bae08d32274b16d29fcd07451a7451c8b5b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "patestgen/edges.h", "max_forks_repo_name": "dkondor/patest_new", "max_forks_repo_head_hexsha": "ebdb1bae08d32274b16d29fcd07451a7451c8b5b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1871345029, "max_line_length": 129, "alphanum_fraction": 0.7319823789, "num_tokens": 1987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16667541296674696, "lm_q2_score": 0.016914913731329796, "lm_q1q2_score": 0.002819300231466292}}
{"text": "/* ieee-utils/fp-unknown.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#include <config.h>\n#include <gsl/gsl_ieee_utils.h>\n#include <gsl/gsl_errno.h>\n\nint\ngsl_ieee_set_mode (int precision, int rounding, int exception_mask)\n{\n  GSL_ERROR (\n\"the IEEE interface for this platform is unsupported or could not be \"\n\"determined at configure time\\n\", GSL_EUNSUP) ;\n}\n", "meta": {"hexsha": "6e4ac96aa75ba5df7a63fe7ee56ef38260b77d7a", "size": 1086, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/ieee-utils/fp-unknown.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/ieee-utils/fp-unknown.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/ieee-utils/fp-unknown.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 35.0322580645, "max_line_length": 72, "alphanum_fraction": 0.741252302, "num_tokens": 277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1943678110187447, "lm_q2_score": 0.014503579345280283, "lm_q1q2_score": 0.002819028969278807}}
{"text": "#ifndef RENDERING_ENTITY_STEREO_VIEWERCENTRICENTITY_H\n#define RENDERING_ENTITY_STEREO_VIEWERCENTRICENTITY_H\n\n#include \"stereoimageentity.h\"\n\n#include <gsl/gsl>\n\nclass QPaintEvent;\nclass QPainter;\n\nnamespace s3d {\nstruct ViewerContext;\n}  // namespace s3d\n\nclass ViewerCentricEntity : public StereoImageEntity {\n public:\n  ViewerCentricEntity();\n\n  void init() override;\n  void setHorizontalShift(float shift) override;\n  void setAspectRatio(float ratio) override;\n  void setTextureLeft(QOpenGLTexture* texture) override;\n  void setTextureRight(QOpenGLTexture* texture) override;\n  void setViewerContext(gsl::not_null<s3d::ViewerContext*> viewerContext);\n  void setDepthRangeMeters(float min, float max);\n  void setDisplayZoom(float displayZoom);\n\n  void draw(QPaintDevice* paintDevice) override;\n\n  QPoint worldToWidget(QPointF pos, int deviceWidth, int deviceHeight);\n  float worldYToWidgetX(float y, int deviceWidth, int deviceHeight);\n  float worldZToWidgetY(float z, int deviceHeight);\n  float getPixelToWorldRatio(float deviceHeight);\n\n private:\n  void drawScreen(QPainter* painter);\n  void drawViewer(QPainter* painter);\n\n private:\n  s3d::ViewerContext* m_viewerContext{};\n  float m_displayZoom{1.0f};\n\n  float m_minZ{-1.0f};\n  float m_maxZ{3.0f};\n};\n\n#endif  // RENDERING_ENTITY_STEREO_VIEWERCENTRICENTITY_H\n", "meta": {"hexsha": "98283f4490dfd22f6e5397807bdd23de440d29a4", "size": 1315, "ext": "h", "lang": "C", "max_stars_repo_path": "src/apps/S3DAnalyzer/rendering/entity/stereo/viewercentricentity.h", "max_stars_repo_name": "hugbed/OpenS3D", "max_stars_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-16T16:38:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-20T03:23:15.000Z", "max_issues_repo_path": "src/apps/S3DAnalyzer/rendering/entity/stereo/viewercentricentity.h", "max_issues_repo_name": "hugbed/OpenS3D", "max_issues_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 40.0, "max_issues_repo_issues_event_min_datetime": "2017-04-12T17:24:44.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-21T18:41:23.000Z", "max_forks_repo_path": "src/apps/S3DAnalyzer/rendering/entity/stereo/viewercentricentity.h", "max_forks_repo_name": "hugbed/OpenS3D", "max_forks_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-07-13T21:51:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-18T16:22:03.000Z", "avg_line_length": 27.3958333333, "max_line_length": 74, "alphanum_fraction": 0.791634981, "num_tokens": 335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14223190955366666, "lm_q2_score": 0.01971913005164152, "lm_q1q2_score": 0.0028046895219820665}}
{"text": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n#pragma once\n\n#include \"arcana/type_traits.h\"\n#include \"arcana/either.h\"\n#include \"arcana/iterators.h\"\n\n#include <memory>\n#include <gsl/gsl>\n#include <utility>\n\n#include <cereal/cereal.hpp>\n#include <cereal/archives/json.hpp>\n\n\nnamespace mira\n{\n    //\n    // Generic object used to iterate an object hierarchy in order to\n    // iterate all its members in the goal of introspecting objects as they\n    // flow through a system.\n    //\n    // CallableT is anything that can get invoked to introspect an object hierarchy.\n    // It supports cereal serialization out of the box in order to help writing out\n    // object hierarchies to file, so one thing to be aware of is that when iterating\n    // if you need to handle T's and cereal::NameValuePair<T>'s.\n    //\n    // The introspection contract isn't as strict as the serialization contract.\n    // If a type is already serializable using cereal, it should already support\n    // being introspected.\n    //\n    // If the type can't be serialized for any reason it can still be introspected.\n    // All a type needs in order to be introspected is a free function with the following\n    // signature:\n    //\n    // template<typename ArchiveT>\n    // void introspect_object(introspector<ArchiveT>& archive, const Foo& object)\n    // {\n    //      archive(\n    //              cereal::make_nvp(\"Param1\", object.param1),\n    //              object.param2 // if the name doesn't matter, but it usually helps.\n    //      );\n    // }\n    //\n\n    namespace internal\n    {\n        // helper struct to support nested introspectable types\n        // that create objects in the serializer.\n        struct nested_serialize_object\n        {\n            std::function<void()> callback;\n\n            template<typename ArchiveT>\n            void save(ArchiveT&) const\n            {\n                callback();\n            }\n        };\n\n        // helper struct to support nested introspectable objects\n        // that don't create objects but act as additional data to the parent.\n        struct nested_serialize_inline\n        {\n            std::function<void()> callback;\n\n            template<typename ArchiveT>\n            void save(ArchiveT&) const\n            {\n                callback();\n            }\n        };\n\n        inline void prologue(cereal::JSONOutputArchive&, const nested_serialize_inline&)\n        {}\n\n        inline void epilogue(cereal::JSONOutputArchive&, const nested_serialize_inline&)\n        {}\n    }\n\n    template<typename CallableT>\n    class introspector\n    {\n        template<typename L>\n        struct has_internal_introspection_function_test\n        {\n            template<typename T,\n                typename = decltype(introspect_object_internal(instance_of<introspector<CallableT>>(), instance_of<T>()))>\n                static std::true_type test(T* = nullptr);\n\n            static std::false_type test(...);\n        };\n\n        template<typename T>\n        using has_internal_introspection_function = decltype(has_internal_introspection_function_test<CallableT>::test(&instance_of<T>()));\n\n        template<typename L>\n        struct has_custom_introspection_function_test\n        {\n            template<typename T,\n                typename = decltype(introspect_object(instance_of<introspector<CallableT>>(), instance_of<T>()))>\n            static std::true_type test(T* = nullptr);\n\n            static std::false_type test(...);\n        };\n\n        template<typename T>\n        using has_custom_introspection_function = decltype(has_custom_introspection_function_test<CallableT>::test(&instance_of<T>()));\n    public:\n        template<typename ItrT>\n        explicit introspector(ItrT&& i)\n            : m_callable{ std::forward<ItrT>(i) }\n        {}\n\n        using internally_introspected = std::integral_constant<size_t, 0>;\n        using externally_introspected = std::integral_constant<size_t, 1>;\n        using default_introspected = std::integral_constant<size_t, 2>;\n\n        template<typename T>\n        using introspection_type =\n            find_first_index<has_internal_introspection_function<T>, has_custom_introspection_function<T>>;\n\n        template<typename T>\n        static constexpr bool should_introspect()\n        {\n            return introspection_type<T>::value < default_introspected::value;\n        }\n\n        template<typename ...ArgTs>\n        void operator()(ArgTs&& ...args)\n        {\n            mira::static_foreach([this](auto&& arg)\n            {\n                introspect(std::forward<decltype(arg)>(arg));\n            }, std::forward<ArgTs>(args)...);\n        }\n\n        template<typename T>\n        void introspect(const T& value)\n        {\n            introspect_dispatch(value, introspection_type<T>{});\n        }\n\n        CallableT& callable()\n        {\n            return m_callable;\n        }\n\n        const CallableT& callable() const\n        {\n            return m_callable;\n        }\n\n    private:\n        template<typename T>\n        void introspect_dispatch(const T& value, internally_introspected)\n        {\n            introspect_object_internal(*this, value);\n        }\n\n        template<typename T>\n        void introspect_dispatch(const T& value, externally_introspected)\n        {\n            internal::nested_serialize_object nested{ [&]\n            {\n                introspect_object(*this, value);\n            } };\n            m_callable(nested);\n        }\n\n        template<typename T>\n        void introspect_dispatch(const T& value, default_introspected)\n        {\n            m_callable(value);\n        }\n\n        CallableT m_callable;\n    };\n\n    template<typename CallableT, typename T>\n    void introspect_object_internal(introspector<CallableT>& ar, const cereal::NameValuePair<T>& named)\n    {\n        internal::nested_serialize_inline nested{ [&]\n        {\n            ar.introspect(named.value);\n        } };\n        ar.callable()(cereal::make_nvp(named.name, nested));\n    }\n\n    template<typename CallableT, typename T>\n    void introspect_object_internal(introspector<CallableT>& ar, const T* object)\n    {\n        if (!object)\n        {\n            ar.callable()(cereal::make_nvp(\"pointer\", nullptr));\n        }\n        else\n        {\n            internal::nested_serialize_inline nested{ [&]\n            {\n                ar.introspect(*object);\n            } };\n            ar.callable()(cereal::make_nvp(\"pointer\", nested));\n        }\n    }\n\n    template<typename CallableT, typename T>\n    void introspect_object(introspector<CallableT>& ar, const std::shared_ptr<T>& ptr)\n    {\n        ar.introspect(ptr.get());\n    }\n\n    template<typename CallableT, typename T, typename D>\n    void introspect_object(introspector<CallableT>& ar, const std::unique_ptr<T, D>& ptr)\n    {\n        ar.introspect(ptr.get());\n    }\n\n    template<typename CallableT, typename T, std::ptrdiff_t Extent>\n    void introspect_object(introspector<CallableT>& ar, gsl::span<T, Extent> elements)\n    {\n        ar.callable()(cereal::SizeTag<cereal::size_type>(elements.size()));\n\n        for (auto& el : elements)\n        {\n            ar.introspect(el);\n        }\n    }\n\n    template<typename CallableT, typename T, typename AllocT>\n    void introspect_object(introspector<CallableT>& ar, const std::vector<T, AllocT>& elements)\n    {\n        introspect_object(ar, gsl::make_span(elements));\n    }\n\n    template<typename CallableT, typename A, typename B>\n    void introspect_object(introspector<CallableT>& ar, const std::pair<A, B>& elements)\n    {\n        ar(\n            cereal::make_nvp(\"First\", elements.first),\n            cereal::make_nvp(\"Second\", elements.second)\n        );\n    }\n}\n", "meta": {"hexsha": "525e4827c54eb835a95f9d9a42e52d66dd208fc4", "size": 7694, "ext": "h", "lang": "C", "max_stars_repo_path": "Dependencies/Arcana/Shared/arcana/analysis/introspector.h", "max_stars_repo_name": "syntheticmagus/mageslam", "max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z", "max_issues_repo_path": "Dependencies/Arcana/Shared/arcana/analysis/introspector.h", "max_issues_repo_name": "syntheticmagus/mageslam", "max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z", "max_forks_repo_path": "Dependencies/Arcana/Shared/arcana/analysis/introspector.h", "max_forks_repo_name": "syntheticmagus/mageslam", "max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z", "avg_line_length": 31.1497975709, "max_line_length": 139, "alphanum_fraction": 0.6094359241, "num_tokens": 1638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1127954092652892, "lm_q2_score": 0.02479816235773334, "lm_q1q2_score": 0.0027971188721676215}}
{"text": "// The MIT License (MIT)\n//\n// Copyright (c) 2018 Mateusz Pusz\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#pragma once\n\n// IWYU pragma: begin_exports\n#include <units/bits/external/fixed_string.h>\n#include <compare>\n#include <cstdint>\n#include <cstddef>\n// IWYU pragma: end_exports\n\n#include <gsl/gsl-lite.hpp>\n\nnamespace units {\n\nnamespace detail {\n\nconstexpr void validate_ascii_char([[maybe_unused]] char c) noexcept { gsl_Expects((c & 0x80) == 0); }\n\ntemplate<std::size_t N>\nconstexpr void validate_ascii_string([[maybe_unused]] const char (&s)[N + 1]) noexcept\n{\n#ifndef NDEBUG\n  if constexpr (N != 0)\n    for (size_t i = 0; i < N; ++i)\n      validate_ascii_char(s[i]);\n#endif\n}\n\n}  // namespace detail\n\n\n/**\n * @brief A symbol text representation\n * \n * This class template is responsible for definition and handling of a symbol text\n * representation. In the libary it is used to define symbols of units and prefixes.\n * Each symbol can have two versions: Unicode and ASCI-only.\n * \n * @tparam StandardCharT Character type to be used for a Unicode representation\n * @tparam N The size of a Unicode symbol\n * @tparam M The size of the ASCII-only symbol\n */\ntemplate<typename StandardCharT, std::size_t N, std::size_t M>\nstruct basic_symbol_text {\n  basic_fixed_string<StandardCharT, N> standard_;\n  basic_fixed_string<char, M> ascii_;\n\n  constexpr basic_symbol_text(char std) noexcept: standard_(std), ascii_(std) { detail::validate_ascii_char(std); }\n  constexpr basic_symbol_text(StandardCharT std, char a) noexcept: standard_(std), ascii_(a) { detail::validate_ascii_char(a); }\n  constexpr basic_symbol_text(const char (&std)[N + 1]) noexcept: standard_(std), ascii_(std) { detail::validate_ascii_string<N>(std); }\n  constexpr basic_symbol_text(const basic_fixed_string<char, N>& std) noexcept: standard_(std), ascii_(std) { detail::validate_ascii_string<N>(std.data_); }\n  constexpr basic_symbol_text(const StandardCharT (&std)[N + 1], const char (&a)[M + 1]) noexcept: standard_(std), ascii_(a) { detail::validate_ascii_string<M>(a); }\n  constexpr basic_symbol_text(const basic_fixed_string<StandardCharT, N>& std, const basic_fixed_string<char, M>& a) noexcept: standard_(std), ascii_(a) { detail::validate_ascii_string<M>(a.data_); }\n\n  [[nodiscard]] constexpr auto& standard() { return standard_; }\n  [[nodiscard]] constexpr const auto& standard() const { return standard_; }\n  [[nodiscard]] constexpr auto& ascii() { return ascii_; }\n  [[nodiscard]] constexpr const auto& ascii() const { return ascii_; }\n\n  template<std::size_t N2, std::size_t M2>\n  [[nodiscard]] constexpr friend basic_symbol_text<StandardCharT, N + N2, M + M2> operator+(\n      const basic_symbol_text& lhs, const basic_symbol_text<StandardCharT, N2, M2>& rhs) noexcept\n  {\n    return basic_symbol_text<StandardCharT, N + N2, M + M2>(\n        lhs.standard() + rhs.standard(), lhs.ascii() + rhs.ascii());\n  }\n\n  template<std::size_t N2>\n  [[nodiscard]] constexpr friend basic_symbol_text<StandardCharT, N + N2, M + N2> operator+(\n      const basic_symbol_text& lhs, const basic_fixed_string<StandardCharT, N2>& rhs) noexcept\n  {\n    return lhs + basic_symbol_text<StandardCharT, N2, N2>(rhs);\n  }\n  \n  template<std::size_t N2>\n  [[nodiscard]] constexpr friend basic_symbol_text<StandardCharT, N + N2, M + N2> operator+(\n      const basic_fixed_string<StandardCharT, N2>& lhs, const basic_symbol_text& rhs) noexcept\n  {\n    return basic_symbol_text<StandardCharT, N2, N2>(lhs) + rhs;\n  }\n\n  template<std::size_t N2>\n  [[nodiscard]] constexpr friend basic_symbol_text<StandardCharT, N + N2 - 1, M + N2 - 1> operator+(\n      const basic_symbol_text& lhs, const StandardCharT (&rhs)[N2]) noexcept\n  {\n    return lhs + basic_symbol_text<StandardCharT, N2 - 1, N2 - 1>(rhs);\n  }\n  \n  template<std::size_t N2>\n  [[nodiscard]] constexpr friend basic_symbol_text<StandardCharT, N + N2 - 1, M + N2 - 1> operator+(\n      const StandardCharT (&lhs)[N2], const basic_symbol_text& rhs) noexcept\n  {\n    return basic_symbol_text<StandardCharT, N2 - 1, N2 - 1>(lhs) + rhs;\n  }\n\n  [[nodiscard]] constexpr friend basic_symbol_text<StandardCharT, N + 1, M + 1> operator+(\n      const basic_symbol_text& lhs, StandardCharT rhs) noexcept\n  {\n    return lhs + basic_symbol_text<StandardCharT, 1, 1>(rhs);\n  }\n  \n  [[nodiscard]] constexpr friend basic_symbol_text<StandardCharT, N + 1, M + 1> operator+(\n      StandardCharT lhs, const basic_symbol_text& rhs) noexcept\n  {\n    return basic_symbol_text<StandardCharT, 1, 1>(lhs) + rhs;\n  }\n\n  template<typename StandardCharT2, std::size_t N2, std::size_t M2>\n  [[nodiscard]] friend constexpr auto operator<=>(const basic_symbol_text& lhs,\n                                                  const basic_symbol_text<StandardCharT2, N2, M2>& rhs) noexcept\n  {\n    if (const auto cmp = lhs.standard() <=> rhs.standard(); cmp != 0) return cmp;\n    return lhs.ascii() <=> rhs.ascii();\n  }\n\n  template<typename StandardCharT2, std::size_t N2, std::size_t M2>\n  [[nodiscard]] friend constexpr bool operator==(const basic_symbol_text& lhs,\n                                                 const basic_symbol_text<StandardCharT2, N2, M2>& rhs) noexcept\n  {\n    return lhs.standard() == rhs.standard() && lhs.ascii() == rhs.ascii();\n  }\n};\n\nbasic_symbol_text(char) -> basic_symbol_text<char, 1, 1>;\n\ntemplate<typename StandardCharT>\nbasic_symbol_text(StandardCharT, char) -> basic_symbol_text<StandardCharT, 1, 1>;\n\ntemplate<std::size_t N>\nbasic_symbol_text(const char (&)[N]) -> basic_symbol_text<char, N - 1, N - 1>;\n\ntemplate<std::size_t N>\nbasic_symbol_text(const basic_fixed_string<char, N>&) -> basic_symbol_text<char, N, N>;\n\ntemplate<typename StandardCharT, std::size_t N, std::size_t M>\nbasic_symbol_text(const StandardCharT (&)[N], const char (&)[M]) -> basic_symbol_text<StandardCharT, N - 1, M - 1>;\n\ntemplate<typename StandardCharT, std::size_t N, std::size_t M>\nbasic_symbol_text(const basic_fixed_string<StandardCharT, N>&,\n                  const basic_fixed_string<char, M>&) -> basic_symbol_text<StandardCharT, N, M>;\n\n}  // namespace units\n", "meta": {"hexsha": "3f3466c1fd7da8d1012350c02ab9361466c5810d", "size": 7088, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/include/units/symbol_text.h", "max_stars_repo_name": "bebuch/units", "max_stars_repo_head_hexsha": "bd801c1f6e07fc38ba52398df9171709ee68125d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 571.0, "max_stars_repo_stars_event_min_datetime": "2018-10-17T14:57:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:53:22.000Z", "max_issues_repo_path": "src/core/include/units/symbol_text.h", "max_issues_repo_name": "bebuch/units", "max_issues_repo_head_hexsha": "bd801c1f6e07fc38ba52398df9171709ee68125d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 283.0, "max_issues_repo_issues_event_min_datetime": "2018-11-01T05:31:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T20:25:11.000Z", "max_forks_repo_path": "src/core/include/units/symbol_text.h", "max_forks_repo_name": "bebuch/units", "max_forks_repo_head_hexsha": "bd801c1f6e07fc38ba52398df9171709ee68125d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 70.0, "max_forks_repo_forks_event_min_datetime": "2019-06-14T01:04:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T01:57:29.000Z", "avg_line_length": 43.2195121951, "max_line_length": 199, "alphanum_fraction": 0.7131772009, "num_tokens": 1846, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09670579329612156, "lm_q2_score": 0.028870903917314297, "lm_q1q2_score": 0.0027919836664999824}}
{"text": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n#pragma once\n\n#include \"arcana/type_traits.h\"\n#include \"arcana/utils/serialization/base_stream.h\"\n#include \"arcana/utils/serialization/serializable.h\"\n\n#include <gsl/gsl>\n#include <memory>\n#include <type_traits>\n\nnamespace mira\n{\n    template<typename LambdaT>\n    class binary_iterator\n    {\n        template<typename T>\n        using is_serializable = std::is_base_of<serializable<std::remove_cv_t<T>>, T>;\n\n        template<typename L>\n        struct check_custom_iterator\n        {\n            template<typename T,\n                     typename = decltype(binary_iterate(instance_of<const T>(),\n                                                        instance_of<binary_iterator<LambdaT>>()))>\n            static std::true_type test(T* = nullptr);\n            static std::false_type test(...);\n        };\n\n        template<typename T>\n        using has_custom_iterator = decltype(check_custom_iterator<LambdaT>::test(&instance_of<T>()));\n\n        template<typename T>\n        using is_valid_pod =\n            std::integral_constant<bool,\n                                   !has_custom_iterator<T>::value && std::is_pod<std::decay_t<T>>::value &&\n                                       !std::is_pointer<std::decay_t<T>>::value>;\n\n    public:\n        template<typename... ArgTs>\n        void iterate_all(ArgTs&&... args)\n        {\n            int unused[] = { (iterate(std::forward<ArgTs>(args)), 0)... };\n            (void)unused;\n        }\n\n        template<typename T>\n        std::enable_if_t<has_custom_iterator<std::decay_t<T>>::value> iterate(const T& value)\n        {\n            static_assert(!is_valid_pod<T>::value, \"we've got some overlap\");\n            binary_iterate(value, *this);\n        }\n\n        template<typename T>\n        std::enable_if_t<is_valid_pod<std::decay_t<T>>::value> iterate(const T& ptr)\n        {\n            static_assert(!has_custom_iterator<T>::value, \"we've got some overlap\");\n            stream{ *this }.write(ptr);\n        }\n\n        void iterate(const void* data, size_t size)\n        {\n            m_iter(data, size);\n        }\n\n        template<typename ItrT>\n        void iterate(ItrT beg, ItrT end)\n        {\n            while (beg != end)\n            {\n                iterate(*beg);\n                beg++;\n            }\n        }\n\n        template<typename A, typename B>\n        void iterate(const std::pair<A, B>& pair)\n        {\n            iterate(pair.first);\n            iterate(pair.second);\n        }\n\n        template<typename T>\n        void iterate(const std::shared_ptr<T>& ptr)\n        {\n            iterate(ptr.get());\n        }\n\n        template<typename T, ptrdiff_t E = -1>\n        void iterate(const gsl::span<T, E>& span)\n        {\n            iterate(span.begin(), span.end());\n        }\n\n        template<typename T, typename D>\n        void iterate(const std::unique_ptr<T, D>& ptr)\n        {\n            iterate(ptr.get());\n        }\n\n        template<typename T>\n        void iterate(const T* ptr)\n        {\n            if (!ptr)\n                iterate((intptr_t)0);\n            else\n                iterate(*ptr);\n        }\n\n        template<typename T>\n        void iterate(const serializable<T>& ptr)\n        {\n            stream s{ *this };\n            ptr.serialize(s);\n        }\n\n        template<typename ItrT>\n        explicit binary_iterator(ItrT&& i)\n            : m_iter{ std::forward<ItrT>(i) }\n        {}\n\n        LambdaT& iterator()\n        {\n            return m_iter;\n        }\n\n        const LambdaT& iterator() const\n        {\n            return m_iter;\n        }\n\n    private:\n        struct stream : public base_stream\n        {\n            template<typename T>\n            void write(const T& obj)\n            {\n                m_itr.iterate(&obj, sizeof(T));\n            }\n\n            template<typename T>\n            void write(const T* obj, size_t N)\n            {\n                m_itr.iterate(obj, N * sizeof(T));\n            }\n\n            stream(binary_iterator<LambdaT>& itr)\n                : m_itr{ itr }\n            {}\n\n        private:\n            binary_iterator<LambdaT>& m_itr;\n        };\n\n        LambdaT m_iter;\n    };\n\n    template<typename LambdaT>\n    binary_iterator<std::decay_t<LambdaT>> make_binary_iterator(LambdaT&& lambda)\n    {\n        return binary_iterator<std::decay_t<LambdaT>>{ std::forward<LambdaT>(lambda) };\n    }\n}\n\nnamespace std\n{\n    template<typename Iter>\n    void binary_iterate(const std::string& str, mira::binary_iterator<Iter>& iter)\n    {\n        iter.iterate(str.data(), str.size());\n    }\n\n    template<typename T, typename Iter>\n    void binary_iterate(const std::vector<T>& vec, mira::binary_iterator<Iter>& iter)\n    {\n        iter.iterate(vec.size());\n        iter.iterate(vec.begin(), vec.end());\n    }\n\n    template<typename IterT, typename FirstT, typename SecondT>\n    void binary_iterate(const std::pair<FirstT, SecondT>& data, mira::binary_iterator<IterT>& itr)\n    {\n        itr.iterate_all(data.first, data.second);\n    }\n\n    template<typename Iter, typename T>\n    void binary_iterate(const std::shared_ptr<T>& ptr, mira::binary_iterator<Iter>& iter)\n    {\n        iter.iterate(ptr.get());\n    }\n\n    template<typename Iter, typename T>\n    void binary_iterate(const std::unique_ptr<T>& ptr, mira::binary_iterator<Iter>& iter)\n    {\n        iter.iterate(ptr.get());\n    }\n}\n\nnamespace gsl\n{\n    template<typename Iter, typename T, ptrdiff_t E = -1>\n    void binary_iterate(const gsl::span<T, E>& span, mira::binary_iterator<Iter>& iter)\n    {\n        iter.iterate(span.begin(), span.end());\n    }\n}\n", "meta": {"hexsha": "8f8b1d129cb15b6cc04258ee8f87db0ca343899a", "size": 5635, "ext": "h", "lang": "C", "max_stars_repo_path": "Dependencies/Arcana/Shared/arcana/analysis/binary_iterator.h", "max_stars_repo_name": "syntheticmagus/mageslam", "max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z", "max_issues_repo_path": "Dependencies/Arcana/Shared/arcana/analysis/binary_iterator.h", "max_issues_repo_name": "syntheticmagus/mageslam", "max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z", "max_forks_repo_path": "Dependencies/Arcana/Shared/arcana/analysis/binary_iterator.h", "max_forks_repo_name": "syntheticmagus/mageslam", "max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z", "avg_line_length": 26.961722488, "max_line_length": 107, "alphanum_fraction": 0.5417923691, "num_tokens": 1230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16451647108926923, "lm_q2_score": 0.016914912306546435, "lm_q1q2_score": 0.002782781681457471}}
{"text": "/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */\n/*\n *     Copyright 2017 Couchbase, Inc\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n */\n\n#pragma once\n\n#include \"monotonic.h\"\n\n#include <memcached/dockey.h>\n#include <platform/sized_buffer.h>\n#include <gsl/gsl>\n#include <unordered_map>\n#include <vector>\n\nnamespace Collections {\n\n// The reserved name of the system owned, default collection.\nconst char* const _DefaultCollectionIdentifier = \"_default\";\nstatic cb::const_char_buffer DefaultCollectionIdentifier(\n        _DefaultCollectionIdentifier);\n\nconst char* const _DefaultScopeIdentifier = \"_default\";\nstatic cb::const_char_buffer DefaultScopeIdentifier(_DefaultScopeIdentifier);\n\n// SystemEvent keys or parts which will be made into keys\nconst char* const SystemSeparator = \":\"; // Note this never changes\nconst char* const SystemEventPrefix = \"_collections\";\nconst char* const SystemEventPrefixWithSeparator = \"_collections:\";\nconst char* const DeleteKey = \"_collections_delete:\";\n\n// Couchstore private file name for manifest data\nconst char CouchstoreManifest[] = \"_local/collections_manifest\";\n\n// Length of the string excluding the zero terminator (i.e. strlen)\nconst size_t CouchstoreManifestLen = sizeof(CouchstoreManifest) - 1;\n\nusing ManifestUid = WeaklyMonotonic<uint64_t>;\n\n// Map used in summary stats\nusing Summary = std::unordered_map<CollectionID, uint64_t>;\n\nstruct ManifestUidNetworkOrder {\n    ManifestUidNetworkOrder(ManifestUid uid) : uid(htonll(uid)) {\n    }\n    ManifestUid to_host() const {\n        return ntohll(uid);\n    }\n    ManifestUid uid;\n};\n\n/**\n * Return a ManifestUid from a C-string.\n * A valid ManifestUid is a C-string where each character satisfies\n * std::isxdigit and can be converted to a ManifestUid by std::strtoull.\n *\n * @param uid C-string uid\n * @param len a length for validation purposes\n * @throws std::invalid_argument if uid is invalid\n */\nManifestUid makeUid(const char* uid, size_t len = 16);\n\n/**\n * Return a ManifestUid from a std::string\n * A valid ManifestUid is a std::string where each character satisfies\n * std::isxdigit and can be converted to a ManifestUid by std::strtoull.\n *\n * @param uid std::string\n * @throws std::invalid_argument if uid is invalid\n */\nstatic inline ManifestUid makeUid(const std::string& uid) {\n    return makeUid(uid.c_str());\n}\n\n/**\n * Return a CollectionID from a C-string.\n * A valid CollectionID is a C-string where each character satisfies\n * std::isxdigit and can be converted to a CollectionID by std::strtoul.\n *\n * @param uid C-string uid\n * @throws std::invalid_argument if uid is invalid\n */\nstatic inline CollectionID makeCollectionID(const char* uid) {\n    // CollectionID is 8 characters max and smaller than a ManifestUid\n    return gsl::narrow_cast<CollectionID>(makeUid(uid, 8));\n}\n\n/**\n * Return a CollectionID from a std::string\n * A valid CollectionID is a std::string where each character satisfies\n * std::isxdigit and can be converted to a CollectionID by std::strtoul\n *\n * @param uid std::string\n * @throws std::invalid_argument if uid is invalid\n */\nstatic inline CollectionID makeCollectionID(const std::string& uid) {\n    return makeCollectionID(uid.c_str());\n}\n\n/**\n * Return a ScopeID from a C-string.\n * A valid CollectionID is a std::string where each character satisfies\n * std::isxdigit and can be converted to a CollectionID by std::strtoul\n * @param uid C-string uid\n * @return std::invalid_argument if uid is invalid\n */\nstatic inline ScopeID makeScopeID(const char* uid) {\n    // ScopeId is 8 characters max and smaller than a ManifestUid\n    return gsl::narrow_cast<ScopeID>(makeUid(uid, 8));\n}\n\n/**\n * Return a ScopeID from a std::string\n * A valid ScopeID is a std::string where each character satisfies\n * std::isxdigit and can be converted to a CollectionID by std::strtoul\n * @param uid std::string\n * @return std::invalid_argument if uid is invalid\n */\nstatic inline ScopeID makeScopeID(const std::string& uid) {\n    return makeScopeID(uid.c_str());\n}\n\n/**\n * All of the data a system event needs\n */\nstruct SystemEventData {\n    ManifestUid manifestUid; // The Manifest which created the event\n    ScopeID sid; // The scope that the collection belongs to\n    CollectionID cid; // The collection the event belongs to\n};\n\n/**\n * All of the data a DCP system event message will transmit in the value of the\n * message. This is the layout to be used on the wire and is in the correct\n * byte order\n */\nstruct SystemEventDcpData {\n    SystemEventDcpData(const SystemEventData& data)\n        : manifestUid(data.manifestUid), sid(data.sid), cid(data.cid) {\n    }\n    /// The manifest uid stored in network byte order ready for sending\n    ManifestUidNetworkOrder manifestUid;\n    /// The scope id stored in network byte order ready for sending\n    ScopeIDNetworkOrder sid;\n    /// The collection id stored in network byte order ready for sending\n    CollectionIDNetworkOrder cid;\n    // The size is sizeof(manifestUid) + sizeof(cid) + sizeof(sid) (msvc won't\n    // allow that expression)\n    constexpr static size_t size{16};\n};\n\nnamespace VB {\n/**\n * The PersistedManifest which stores a copy of the VB::Manifest, the actual\n * format of the data is defined by VB::Manifest\n */\nusing PersistedManifest = std::vector<uint8_t>;\n\n} // namespace VB\n} // end namespace Collections\n\nstd::ostream& operator<<(std::ostream& os,\n                         const Collections::VB::PersistedManifest& data);\n", "meta": {"hexsha": "2a6d40d89a4cc161e7cc97d5d8048898f392b7cf", "size": 5991, "ext": "h", "lang": "C", "max_stars_repo_path": "engines/ep/src/collections/collections_types.h", "max_stars_repo_name": "t3rm1n4l/kv_engine", "max_stars_repo_head_hexsha": "24d4546220f3181678d7eadedc68b4ea088d3538", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "engines/ep/src/collections/collections_types.h", "max_issues_repo_name": "t3rm1n4l/kv_engine", "max_issues_repo_head_hexsha": "24d4546220f3181678d7eadedc68b4ea088d3538", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "engines/ep/src/collections/collections_types.h", "max_forks_repo_name": "t3rm1n4l/kv_engine", "max_forks_repo_head_hexsha": "24d4546220f3181678d7eadedc68b4ea088d3538", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0397727273, "max_line_length": 79, "alphanum_fraction": 0.7299282257, "num_tokens": 1413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16451644651115202, "lm_q2_score": 0.01691491208973158, "lm_q1q2_score": 0.002782781230051164}}
{"text": "#pragma once\n\n#include <chrono>\n#include <unordered_map>\n#include <vector>\n\n#include <gsl/span>\n#include <json.hpp>\n\n#include \"Quiver/Animation/AnimationId.h\"\n#include \"Quiver/Animation/AnimationLibrary.h\"\n#include \"Quiver/Animation/AnimatorId.h\"\n#include \"Quiver/Animation/Rect.h\"\n#include \"Quiver/Graphics/ViewBuffer.h\"\n\nnamespace qvr {\n\nstruct AnimatorTarget {\n\tViewBuffer views;\n\n\tAnimatorTarget() = default;\n\n\tAnimatorTarget(const AnimatorTarget&) = delete;\n\tAnimatorTarget(const AnimatorTarget&&) = delete;\n\n\tAnimatorTarget& operator=(AnimatorTarget&) = delete;\n\tAnimatorTarget& operator=(AnimatorTarget&&) = delete;\n};\n\nclass AnimatorRepeatSetting\n{\npublic:\n\texplicit AnimatorRepeatSetting(const int repeatCount) : m_RepeatCount(repeatCount) {}\n\n\tAnimatorRepeatSetting() = default;\n\n\tint GetRepeatCount() const { return m_RepeatCount; }\n\n\tstatic const AnimatorRepeatSetting Forever;\n\tstatic const AnimatorRepeatSetting Never;\n\tstatic const AnimatorRepeatSetting Once;\n\tstatic const AnimatorRepeatSetting Twice;\n\nprivate:\n\tint m_RepeatCount = Forever.GetRepeatCount();\n};\n\nstruct AnimatorStartSetting\n{\n\tAnimatorStartSetting(AnimationId animationId)\n\t\t: m_AnimationId(animationId)\n\t{}\n\n\tAnimatorStartSetting(\n\t\tAnimationId animationId,\n\t\tAnimatorRepeatSetting repeatSetting)\n\t\t: m_AnimationId(animationId)\n\t\t, m_RepeatSetting(repeatSetting)\n\t{}\n\n\tAnimationId m_AnimationId;\n\tAnimatorRepeatSetting m_RepeatSetting;\n};\n\ninline bool operator==(const AnimatorRepeatSetting& a, const AnimatorRepeatSetting& b) {\n\treturn a.GetRepeatCount() == b.GetRepeatCount();\n}\n\ninline bool operator!=(const AnimatorRepeatSetting& a, const AnimatorRepeatSetting& b) {\n\treturn a.GetRepeatCount() != b.GetRepeatCount();\n}\n\nstruct AnimationLibraryEditorData;\n\nclass AnimationData;\n\nclass AnimatorCollection {\npublic:\n\tauto GetAnimations() const -> const AnimationLibrary& {\n\t\treturn animations;\n\t}\n\n\tAnimationId AddAnimation(const AnimationData& anim);\n\tAnimationId AddAnimation(\n\t\tconst AnimationData& anim, \n\t\tconst AnimationSourceInfo& animSourceInfo);\n\n\tbool RemoveAnimation(const AnimationId id);\n\n\tint GetReferenceCount(const AnimationId animation) const { \n\t\tif (animationReferenceCounts.count(animation) == 0) {\n\t\t\treturn 0;\n\t\t}\n\n\t\treturn animationReferenceCounts.at(animation); \n\t}\n\n\tAnimatorId Add(\n\t\tAnimatorTarget& target, \n\t\tconst AnimatorStartSetting& startSetting);\n\n\tbool Remove(const AnimatorId id);\n\n\tbool Exists(const AnimatorId id) const {\n\t\treturn animators.states.count(id) != 0;\n\t}\n\n\tint GetCount() const { \n\t\treturn animators.states.size(); \n\t}\n\n\tvoid AnimatorGui(const AnimatorId id);\n\n\tbool SetAnimation(\n\t\tconst AnimatorId animatorId,\n\t\tconst AnimatorStartSetting& animation,\n\t\tconst bool clearQueue = true);\n\n\tbool SetTarget(\n\t\tconst AnimatorId id,\n\t\tAnimatorTarget& newTarget);\n\n\tbool SetFrame(\n\t\tconst AnimatorId id, \n\t\tconst int index);\n\n\tbool QueueAnimation(\n\t\tconst AnimatorId animatorId,\n\t\tconst AnimatorStartSetting& pendingAnimation);\n\n\tbool ClearAnimationQueue(const AnimatorId id);\n\n\tunsigned GetFrame(const AnimatorId animatorId) const;\n\n\tAnimationId GetAnimation(const AnimatorId animatorId) const;\n\n\tvoid Animate(const Animation::TimeUnit ms);\n\nprivate:\n\tstruct AnimatorState {\n\t\tAnimatorState(\n\t\t\tconst AnimationId animation,\n\t\t\tconst int frameIndex,\n\t\t\tconst int index,\n\t\t\tAnimatorTarget& target,\n\t\t\tconst AnimatorRepeatSetting& repeat)\n\t\t\t: index(index)\n\t\t\t, currentFrame(frameIndex)\n\t\t\t, currentAnimation(animation)\n\t\t\t, target(&target)\n\t\t\t, repeatSetting(repeat)\n\t\t\t, repeatCount(0)\n\t\t{}\n\n\t\tAnimatorState() = default;\n\n\t\tint index;\n\t\tint currentFrame;\n\t\tint repeatCount;\n\t\tAnimationId currentAnimation;\n\t\tAnimatorRepeatSetting repeatSetting;\n\t\tAnimatorTarget* target;\n\t\tstd::vector<AnimatorStartSetting> queuedAnimations;\n\t};\n\n\tstruct AnimatorState_Hot {\n\t\tAnimatorState_Hot(\n\t\t\tconst AnimatorId animatorId,\n\t\t\tconst Animation::TimeUnit timeLeft)\n\t\t\t: animatorId(animatorId)\n\t\t\t, timeLeftInFrame(timeLeft)\n\t\t{}\n\n\t\tAnimation::TimeUnit timeLeftInFrame;\n\t\tAnimatorId animatorId;\n\t};\n\n\tstruct Animators {\n\t\tstd::vector<AnimatorState_Hot> hotStates;\n\t\tstd::unordered_map<AnimatorId, AnimatorState> states;\n\t\tAnimatorId GetNextAnimatorId();\n\tprivate:\n\t\tAnimatorId lastId = AnimatorId::Invalid;\n\t} animators;\n\n\tAnimationLibrary animations;\n\n\tstd::unordered_map<AnimationId, unsigned> animationReferenceCounts;\n\n\t// friends:\n\n\tfriend void GuiControls(\n\t\tAnimatorCollection& animators, \n\t\tAnimationLibraryEditorData& editorData);\n\n\tfriend void to_json(nlohmann::json& j, const AnimatorCollection& animators);\n\tfriend void from_json(const nlohmann::json& j, AnimatorCollection& animators);\n};\n\nvoid GuiControls(AnimatorCollection& animators, AnimationLibraryEditorData& editorData);\n\nvoid to_json(nlohmann::json& j, const AnimatorCollection& animators);\nvoid from_json(const nlohmann::json& j, AnimatorCollection& animators);\n\n}", "meta": {"hexsha": "608b23a0a25297fe58363e3abfbc9625e41a9cb3", "size": 4848, "ext": "h", "lang": "C", "max_stars_repo_path": "External/Quiver/Source/Quiver/Quiver/Animation/Animators.h", "max_stars_repo_name": "rachelnertia/Quarrel", "max_stars_repo_head_hexsha": "69616179fc71305757549c7fcaccc22707a91ba4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 39.0, "max_stars_repo_stars_event_min_datetime": "2017-10-22T15:47:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-31T22:19:55.000Z", "max_issues_repo_path": "External/Quiver/Source/Quiver/Quiver/Animation/Animators.h", "max_issues_repo_name": "rachelnertia/Quarrel", "max_issues_repo_head_hexsha": "69616179fc71305757549c7fcaccc22707a91ba4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2017-10-26T21:21:51.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-13T14:46:17.000Z", "max_forks_repo_path": "Source/Quiver/Quiver/Animation/Animators.h", "max_forks_repo_name": "rachelnertia/Quiver", "max_forks_repo_head_hexsha": "c8ef9591117bdfc8d6fa509ae53451e0807f5686", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-10-22T14:47:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-19T10:08:45.000Z", "avg_line_length": 23.6487804878, "max_line_length": 88, "alphanum_fraction": 0.7735148515, "num_tokens": 1128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22000709974589316, "lm_q2_score": 0.012624946332762574, "lm_q1q2_score": 0.002777577827118644}}
{"text": "/*\n   Copyright [2020] [IBM Corporation]\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n       http://www.apache.org/licenses/LICENSE-2.0\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\n#ifndef _MCAS_NUPM_ARENA_\n#define _MCAS_NUPM_ARENA_\n\n#include <nupm/region_descriptor.h>\n#include <common/logging.h>\n#include <common/string_view.h>\n#include <gsl/pointers> /* not_null */\n#include <sys/uio.h> /* ::iovec */\n\n#include <cstddef>\n#include <vector>\n\nnamespace nupm\n{\n\tstruct registry_memory_mapped;\n\tstruct space_registered;\n}\n\nstruct arena\n  : private common::log_source\n{\n  using region_descriptor = nupm::region_descriptor;\n  using registry_memory_mapped = nupm::registry_memory_mapped;\n  using space_registered = nupm::space_registered;\n  using string_view = common::string_view;\n\n  arena(const common::log_source &ls) : common::log_source(ls) {}\n  virtual ~arena() {}\n  virtual void debug_dump() const = 0;\n  virtual region_descriptor region_get(const string_view &id) = 0;\n  virtual region_descriptor region_create(const string_view &id, gsl::not_null<registry_memory_mapped *> mh, std::size_t size) = 0;\n  virtual void region_resize(gsl::not_null<space_registered *> mh, std::size_t size) = 0;\n  /* It is unknown whether region_erase may be used on an open region.\n   * arena_fs assumes that it may, just as ::unlink can be used against\n   * an open file.\n   */\n  virtual void region_erase(const string_view &id, gsl::not_null<registry_memory_mapped *> mh) = 0;\n  virtual std::size_t get_max_available() = 0;\n  virtual bool is_file_backed() const = 0;\nprotected:\n  using common::log_source::debug_level;\n};\n\n#endif\n", "meta": {"hexsha": "d6fe918b5219d968a2fac91bbd94c9025f955f78", "size": 2028, "ext": "h", "lang": "C", "max_stars_repo_path": "src/lib/libnupm/src/arena.h", "max_stars_repo_name": "moshik1/mcas", "max_stars_repo_head_hexsha": "a6af06bc278993fb3ffe780f230d2396b2287c26", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lib/libnupm/src/arena.h", "max_issues_repo_name": "moshik1/mcas", "max_issues_repo_head_hexsha": "a6af06bc278993fb3ffe780f230d2396b2287c26", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lib/libnupm/src/arena.h", "max_forks_repo_name": "moshik1/mcas", "max_forks_repo_head_hexsha": "a6af06bc278993fb3ffe780f230d2396b2287c26", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9655172414, "max_line_length": 131, "alphanum_fraction": 0.7470414201, "num_tokens": 502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10521053109182896, "lm_q2_score": 0.026355354662400805, "lm_q1q2_score": 0.002772860861144699}}
{"text": "// Petsc initialization\n#pragma once\n\n#include <hollow/petsc/config.h>\n#include <geode/utility/debug.h>\n#include <vector>\n#include <string>\n// Work around configuration issue in old PETSc versions\n#define PETSC_RESTRICT PETSC_CXX_RESTRICT\n#include <petsc.h>\nnamespace hollow {\n\nusing std::string;\nusing std::vector;\n\n// Initialize petsc, and automatically finalize on application exit\nHOLLOW_EXPORT void petsc_initialize(const string& help, const vector<string>& args);\n\n// Check if petsc is initialized\nHOLLOW_EXPORT bool petsc_initialized();\n\n// Ensure that petsc is initialized.  Can be called multiple times, but no help or args support.\nHOLLOW_EXPORT void petsc_reinitialize();\n\n// Explicitly finalize petsc.  This happens automatically at program exit if petsc_initialize\n// is called, but sometime it is useful to do it sooner.\nHOLLOW_EXPORT void petsc_finalize();\n\n// Reset petsc options to the given list.  Any petsc objects already allocated will not change.\nHOLLOW_EXPORT void petsc_set_options(const vector<string>& args);\n\n// Add new petsc options without removing old options.  Like argv[0], the first option is ignored.\nHOLLOW_EXPORT void petsc_add_options(const vector<string>& args);\n\n}\n", "meta": {"hexsha": "7984d8097eb19036cd60a40dbbbd308aeca378d2", "size": 1204, "ext": "h", "lang": "C", "max_stars_repo_path": "hollow/petsc/init.h", "max_stars_repo_name": "otherlab/hollow", "max_stars_repo_head_hexsha": "9f8209464969dfd449c791c93978292998d5c4e7", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2016-05-09T17:49:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-18T22:22:05.000Z", "max_issues_repo_path": "hollow/petsc/init.h", "max_issues_repo_name": "otherlab/hollow", "max_issues_repo_head_hexsha": "9f8209464969dfd449c791c93978292998d5c4e7", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hollow/petsc/init.h", "max_forks_repo_name": "otherlab/hollow", "max_forks_repo_head_hexsha": "9f8209464969dfd449c791c93978292998d5c4e7", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-20T06:16:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-20T06:16:51.000Z", "avg_line_length": 33.4444444444, "max_line_length": 98, "alphanum_fraction": 0.7873754153, "num_tokens": 266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10669059394565118, "lm_q2_score": 0.025957356350099027, "lm_q1q2_score": 0.0027694057662509854}}
{"text": "// The various memcached commands that we support.\n\n#include \"commands.h\"\n#include \"connections.h\"\n#include \"locking.h\"\n#include \"protocol.h\"\n#include \"server.h\"\n#include \"threads.h\"\n#include \"utils.h\"\n\n#include <assert.h>\n#include <gsl/gsl_randist.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nstatic const char* default_key = \"skeleton\";\n\n/* // process a memcached get(s) command. (we don't support CAS). This function */\n/* // performs the request parsing and setup of backend RPC's. */\n/* void process_get_command(conn *c, token_t *tokens, size_t ntokens, */\n/*                                 bool return_cas) { */\n/* \tchar *key; */\n/* \tsize_t nkey; */\n/* \tint i = 0; */\n/* \titem *it; */\n/* \ttoken_t *key_token = &tokens[KEY_TOKEN]; */\n/* \tchar *suffix; */\n/* \tworker_thread_t *t = c->thread; */\n/* \tmemcached_t *mc; */\n/*  */\n/* \tassert(c != NULL); */\n/*  */\n/* \tkey  = key_token->value; */\n/* \tnkey = key_token->length; */\n/*  */\n/* \tif (config.use_dist) { */\n/* \t\tlong size = config.dist_arg1 + gsl_ran_gaussian(config.r, config.dist_arg2); */\n/* \t\tif (config.verbose > 1) { */\n/* \t\t\tfprintf(stderr, \"allocated blob: %ld\\n\", size); */\n/* \t\t} */\n/* \t\tc->mem_blob = malloc(sizeof(char) * size); */\n/* \t} */\n/*  */\n/* \tif(nkey > KEY_MAX_LENGTH) { */\n/* \t\terror_response(c, \"CLIENT_ERROR bad command line format\"); */\n/* \t\treturn; */\n/* \t} */\n/*  */\n/* \t// lookup key-value. */\n/* \tit = item_get(key, nkey); */\n/*  */\n/* \t// hit. */\n/* \tif (it) { */\n/* \t\tif (i >= c->isize && !conn_expand_items(c)) { */\n/* \t\t\titem_remove(it); */\n/* \t\t\terror_response(c, \"SERVER_ERROR out of memory writing get response\"); */\n/* \t\t\treturn; */\n/* \t\t} */\n/* \t\t// add item to remembered list (i.e., we've taken ownership of them */\n/* \t\t// through refcounting and later must release them once we've */\n/* \t\t// written out the iov associated with them). */\n/* \t\titem_update(it); */\n/* \t\t*(c->ilist + i) = it; */\n/* \t\ti++; */\n/* \t} */\n/*  */\n/* \t// make sure it's a single get */\n/* \tkey_token++; */\n/* \tif (key_token->length != 0 || key_token->value != NULL) { */\n/* \t\terror_response(c, \"SERVER_ERROR only support single `get`\"); */\n/* \t\treturn; */\n/* \t} */\n/*  */\n/* \t// update our rememberd reference set. */\n/* \tc->icurr = c->ilist; */\n/* \tc->ileft = i; */\n/*  */\n/* \t// setup RPC calls. */\n/* \tfor (i = 0; i < t->memcache_used; i++) { */\n/* \t\tmc = t->memcache[i]; */\n/* \t\tif (!conn_add_msghdr(mc) != 0) { */\n/* \t\t\terror_response(mc, \"SERVER_ERROR out of memory preparing response\"); */\n/* \t\t\treturn; */\n/* \t\t} */\n/* \t\tmemcache_get(mc, c, default_key); */\n/* \t} */\n/* \tconn_set_state(c, conn_rpc_wait); */\n/* } */\n\n// complete the response to a get request.\nvoid finish_get_command(conn *c) {\n\titem *it;\n\tint i;\n\n\t// setup all items for writing out.\n\tfor (i = 0; i < c->ileft; i++) {\n\t\tit = *(c->ilist + i);\n\t\tif (it) {\n\t\t\t// Construct the response. Each hit adds three elements to the\n\t\t\t// outgoing data list:\n\t\t\t//   \"VALUE <key> <flags> <data_length>\\r\\n\"\n\t\t\t//   \"<data>\\r\\n\"\n\t\t\t// The <data> element is stored on the connection item list, not on\n\t\t\t// the iov list.\n\t\t\tif (!conn_add_iov(c, \"VALUE \", 6) ||\n\t\t\t\t !conn_add_iov(c, ITEM_key(it), it->nkey) ||\n\t\t\t\t !conn_add_iov(c, ITEM_suffix(it), it->nsuffix + it->nbytes)) {\n\t\t\t\titem_remove(it);\n\t\t\t\terror_response(c, \"SERVER_ERROR out of memory writing get response\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (config.verbose > 1) {\n\t\t\t\tfprintf(stderr, \">%d sending key %s\\n\", c->sfd, ITEM_key(it));\n\t\t\t}\n\t\t} else {\n\t\t\tfprintf(stderr, \"ERROR corrupted ilist!\\n\");\n\t\t\texit(1);\n\t\t}\n\t}\n\n\tif (config.verbose > 1) {\n\t\tfprintf(stderr, \">%d END\\n\", c->sfd);\n\t}\n\n\tif (!conn_add_iov(c, \"END\\r\\n\", 5) != 0) {\n\t\terror_response(c, \"SERVER_ERROR out of memory writing get response\");\n\t} else {\n\t\tconn_set_state(c, conn_mwrite);\n\t}\n}\n\n// process a memcached get(s) command. (we don't support CAS).\nvoid process_get_command(conn *c, token_t *tokens, size_t ntokens,\n                                bool return_cas) {\n\tchar *key;\n\tsize_t nkey;\n\tint i = 0;\n\titem *it;\n\ttoken_t *key_token = &tokens[KEY_TOKEN];\n\tchar *suffix;\n\n\tassert(c != NULL);\n\n\tif (config.alloc && c->mem_blob == NULL) {\n\t\tlong size = config.alloc_mean + gsl_ran_gaussian(c->thread->r, config.alloc_stddev);\n\t\tsize = size <= 0 ? 10 : size;\n\t\tif (config.verbose > 0) {\n\t\t\tfprintf(stderr, \"allocated blob: %ld\\n\", size);\n\t\t}\n\n\t\tc->mem_blob = malloc(sizeof(char) * size);\n\t\tc->mem_free_delay = 0;\n\n\t\tif (config.rtt_delay) {\n\t\t\tdouble r = config.rtt_mean + gsl_ran_gaussian(c->thread->r, config.rtt_stddev);\n\t\t\tif (r >= config.rtt_cutoff) {\n\t\t\t\tint wait = r / 100;\n\t\t\t\tif (config.verbose > 0) {\n\t\t\t\t\tfprintf(stderr, \"delay: %d\\n\", wait);\n\t\t\t\t}\n\t\t\t\tc->mem_free_delay = wait;\n\t\t\t\tconn_set_state(c, conn_mwrite);\n\t\t\t}\n\t\t}\n\t}\n\n\t// process the whole command line, (only part of it may be tokenized right now)\n\tdo {\n\t\t// process all tokenized keys at this stage.\n\t\twhile(key_token->length != 0) {\n\t\t\tkey = key_token->value;\n\t\t\tnkey = key_token->length;\n\n\t\t\tif(nkey > KEY_MAX_LENGTH) {\n\t\t\t\terror_response(c, \"CLIENT_ERROR bad command line format\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// lookup key-value.\n\t\t\tit = item_get(key, nkey);\n\t\t\t\n\t\t\t// hit.\n\t\t\tif (it) {\n\t\t\t\tif (i >= c->isize && !conn_expand_items(c)) {\n\t\t\t\t\titem_remove(it);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\t// Construct the response. Each hit adds three elements to the\n\t\t\t\t// outgoing data list:\n\t\t\t\t//   \"VALUE <key> <flags> <data_length>\\r\\n\"\n\t\t\t\t//   \"<data>\\r\\n\"\n\t\t\t\t// The <data> element is stored on the connection item list, not on\n\t\t\t\t// the iov list.\n\t\t\t\tif (!conn_add_iov(c, \"VALUE \", 6) != 0 ||\n\t\t\t\t    !conn_add_iov(c, ITEM_key(it), it->nkey) != 0 ||\n\t\t\t\t    !conn_add_iov(c, ITEM_suffix(it), it->nsuffix + it->nbytes) != 0) {\n\t\t\t\t\titem_remove(it);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (config.verbose > 1) {\n\t\t\t\t\tfprintf(stderr, \">%d sending key %s\\n\", c->sfd, key);\n\t\t\t\t}\n\n\t\t\t\t// add item to remembered list (i.e., we've taken ownership of them\n\t\t\t\t// through refcounting and later must release them once we've\n\t\t\t\t// written out the iov associated with them).\n\t\t\t\titem_update(it);\n\t\t\t\t*(c->ilist + i) = it;\n\t\t\t\ti++;\n\t\t\t}\n\n\t\t\tkey_token++;\n\t\t}\n\n\t\t/*\n\t\t * If the command string hasn't been fully processed, get the next set\n\t\t * of tokens.\n\t\t */\n\t\tif(key_token->value != NULL) {\n\t\t\tntokens = tokenize_command(key_token->value, tokens, MAX_TOKENS);\n\t\t\tkey_token = tokens;\n\t\t}\n\n\t} while(key_token->value != NULL);\n\n\tc->icurr = c->ilist;\n\tc->ileft = i;\n\n\tif (config.verbose > 1) {\n\t\tfprintf(stderr, \">%d END\\n\", c->sfd);\n\t}\n\n\t// If the loop was terminated because of out-of-memory, it is not reliable\n\t// to add END\\r\\n to the buffer, because it might not end in \\r\\n. So we\n\t// send SERVER_ERROR instead.\n\tif (key_token->value != NULL || !conn_add_iov(c, \"END\\r\\n\", 5) != 0) {\n\t\terror_response(c, \"SERVER_ERROR out of memory writing get response\");\n\t} else {\n\t\tconn_set_state(c, conn_mwrite);\n\t}\n}\n\n// process a memcached set command.\nvoid process_update_command(conn *c, token_t *tokens,\n                            const size_t ntokens,\n                            int comm, bool handle_cas) {\n\tint vlen;\n\tassert(c != NULL);\n\n\tif (tokens[KEY_TOKEN].length > KEY_MAX_LENGTH ||\n\t    !safe_strtol(tokens[4].value, (int32_t *)&vlen)) {\n\t\terror_response(c, \"CLIENT_ERROR bad command line format\");\n\t\treturn;\n\t}\n\n\tif (vlen < 0) {\n\t\terror_response(c, \"CLIENT_ERROR bad command line format\");\n\t\treturn;\n\t}\n\n\t// setup value to be read\n\tc->sbytes = vlen + 2; // for \\r\\n consumption.\n\tconn_set_state(c, conn_read_value);\n}\n\n// process a memcached stat command.\nvoid process_stat_command(conn *c, token_t *tokens, const size_t ntokens) {\n\tmutex_lock(&c->stats->lock);\n\n\t// just for debugging right now\n\tfprintf(stderr, \"STAT client_id %d\\n\", c->stats->client_id);\n\tfprintf(stderr, \"STAT total_connections %d\\n\", c->stats->total_connections);\n\tfprintf(stderr, \"STAT live_connections %d\\n\", c->stats->live_connections);\n\tfprintf(stderr, \"STAT requests %d\\n\", c->stats->requests);\n\n\tmutex_unlock(&c->stats->lock);\n\tconn_set_state(c, conn_new_cmd);\n}\n\n", "meta": {"hexsha": "dd7a3091797bec9f9a0eadb1e5c7521bc6983f65", "size": 7938, "ext": "c", "lang": "C", "max_stars_repo_path": "src/commands.c", "max_stars_repo_name": "dterei/synthetic-client", "max_stars_repo_head_hexsha": "cf998af17337df7b9f50e1aac80855b150841059", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/commands.c", "max_issues_repo_name": "dterei/synthetic-client", "max_issues_repo_head_hexsha": "cf998af17337df7b9f50e1aac80855b150841059", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/commands.c", "max_forks_repo_name": "dterei/synthetic-client", "max_forks_repo_head_hexsha": "cf998af17337df7b9f50e1aac80855b150841059", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0494699647, "max_line_length": 86, "alphanum_fraction": 0.6000251953, "num_tokens": 2385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09670579850281286, "lm_q2_score": 0.02843603602953799, "lm_q1q2_score": 0.0027499295704912275}}
{"text": "#ifndef LIC_OPCODES\n#define LIC_OPCODES\n\n#include <gsl/gsl>\n\nnamespace lic\n{\n\nconstexpr uint8_t MethodHeaderFormatMask = 0x3;\n\nenum class HeaderFormat : uint8_t\n{\n    Tiny = 0x2,\n    Fat = 0x3\n};\n\nenum class Opcode : uint8_t\n{\n    Nop = 0x00,\n    Break = 0x01,\n    Ldarg_0 = 0x02,\n    Ldarg_1 = 0x03,\n    Ldarg_2 = 0x04,\n    Ldarg_3 = 0x05,\n    Ldloc_0 = 0x06,\n    Ldloc_1 = 0x07,\n    Ldloc_2 = 0x08,\n    Ldloc_3 = 0x09,\n    Stloc_0 = 0x0a,\n    Stloc_1 = 0x0b,\n    Stloc_2 = 0x0c,\n    Stloc_3 = 0x0d,\n    Ldarg_S = 0x0e,\n    Ldarga_S = 0x0f,\n    Starg_S = 0x10,\n    Ldloc_S = 0x11,\n    Ldloca_S = 0x12,\n    Stloc_S = 0x13,\n    Ldnull = 0x14,\n    Ldc_I4_M1 = 0x15,\n    Ldc_I4_0 = 0x16,\n    Ldc_I4_1 = 0x17,\n    Ldc_I4_2 = 0x18,\n    Ldc_I4_3 = 0x19,\n    Ldc_I4_4 = 0x1a,\n    Ldc_I4_5 = 0x1b,\n    Ldc_I4_6 = 0x1c,\n    Ldc_I4_7 = 0x1d,\n    Ldc_I4_8 = 0x1e,\n    Ldc_I4_S = 0x1f,\n    Ldc_I4 = 0x20,\n    Ldc_I8 = 0x21,\n    Ldc_R4 = 0x22,\n    Ldc_R8 = 0x23,\n    Dup = 0x25,\n    Pop = 0x26,\n    Jmp = 0x27,\n    Call = 0x28,\n    Calli = 0x29,\n    Ret = 0x2a,\n    Br_S = 0x2b,\n    Brfalse_S = 0x2c,\n    Brtrue_S = 0x2d,\n    Beq_S = 0x2e,\n    Bge_S = 0x2f,\n    Bgt_S = 0x30,\n    Ble_S = 0x31,\n    Blt_S = 0x32,\n    Bne_Un_S = 0x33,\n    Bge_Un_S = 0x34,\n    Bgt_Un_S = 0x35,\n    Ble_Un_S = 0x36,\n    Blt_Un_S = 0x37,\n    Br = 0x38,\n    Brfalse = 0x39,\n    Brtrue = 0x3a,\n    Beq = 0x3b,\n    Bge = 0x3c,\n    Bgt = 0x3d,\n    Ble = 0x3e,\n    Blt = 0x3f,\n    Bne_Un = 0x40,\n    Bge_Un = 0x41,\n    Bgt_Un = 0x42,\n    Ble_Un = 0x43,\n    Blt_Un = 0x44,\n    Switch = 0x45,\n    Ldind_I1 = 0x46,\n    Ldind_U1 = 0x47,\n    Ldind_I2 = 0x48,\n    Ldind_U2 = 0x49,\n    Ldind_I4 = 0x4a,\n    Ldind_U4 = 0x4b,\n    Ldind_I8 = 0x4c,\n    Ldind_I = 0x4d,\n    Ldind_R4 = 0x4e,\n    Ldind_R8 = 0x4f,\n    Ldind_Ref = 0x50,\n    Stind_Ref = 0x51,\n    Stind_I1 = 0x52,\n    Stind_I2 = 0x53,\n    Stind_I4 = 0x54,\n    Stind_I8 = 0x55,\n    Stind_R4 = 0x56,\n    Stind_R8 = 0x57,\n    Add = 0x58,\n    Sub = 0x59,\n    Mul = 0x5a,\n    Div = 0x5b,\n    Div_Un = 0x5c,\n    Rem = 0x5d,\n    Rem_Un = 0x5e,\n    And = 0x5f,\n    Or = 0x60,\n    Xor = 0x61,\n    Shl = 0x62,\n    Shr = 0x63,\n    Shr_Un = 0x64,\n    Neg = 0x65,\n    Not = 0x66,\n    Conv_I1 = 0x67,\n    Conv_I2 = 0x68,\n    Conv_I4 = 0x69,\n    Conv_I8 = 0x6a,\n    Conv_R4 = 0x6b,\n    Conv_R8 = 0x6c,\n    Conv_U4 = 0x6d,\n    Conv_U8 = 0x6e,\n    Callvirt = 0x6f,\n    Cpobj = 0x70,\n    Ldobj = 0x71,\n    Ldstr = 0x72,\n    Newobj = 0x73,\n    Castclass = 0x74,\n    Isinst = 0x75,\n    Conv_R_Un = 0x76,\n    Unbox = 0x79,\n    Throw = 0x7a,\n    Ldfld = 0x7b,\n    Ldflda = 0x7c,\n    Stfld = 0x7d,\n    Ldsfld = 0x7e,\n    Ldsflda = 0x7f,\n    Stsfld = 0x80,\n    Stobj = 0x81,\n    Conv_Ovf_I1_Un = 0x82,\n    Conv_Ovf_I2_Un = 0x83,\n    Conv_Ovf_I4_Un = 0x84,\n    Conv_Ovf_I8_Un = 0x85,\n    Conv_Ovf_U1_Un = 0x86,\n    Conv_Ovf_U2_Un = 0x87,\n    Conv_Ovf_U4_Un = 0x88,\n    Conv_Ovf_U8_Un = 0x89,\n    Conv_Ovf_I_Un = 0x8a,\n    Conv_Ovf_U_Un = 0x8b,\n    Box = 0x8c,\n    Newarr = 0x8d,\n    Ldlen = 0x8e,\n    Ldelema = 0x8f,\n    Ldelem_I1 = 0x90,\n    Ldelem_U1 = 0x91,\n    Ldelem_I2 = 0x92,\n    Ldelem_U2 = 0x93,\n    Ldelem_I4 = 0x94,\n    Ldelem_U4 = 0x95,\n    Ldelem_I8 = 0x96,\n    Ldelem_I = 0x97,\n    Ldelem_R4 = 0x98,\n    Ldelem_R8 = 0x99,\n    Ldelem_Ref = 0x9a,\n    Stelem_I = 0x9b,\n    Stelem_I1 = 0x9c,\n    Stelem_I2 = 0x9d,\n    Stelem_I4 = 0x9e,\n    Stelem_I8 = 0x9f,\n    Stelem_R4 = 0xa0,\n    Stelem_R8 = 0xa1,\n    Stelem_Ref = 0xa2,\n    Conv_Ovf_I1 = 0xb3,\n    Conv_Ovf_U1 = 0xb4,\n    Conv_Ovf_I2 = 0xb5,\n    Conv_Ovf_U2 = 0xb6,\n    Conv_Ovf_I4 = 0xb7,\n    Conv_Ovf_U4 = 0xb8,\n    Conv_Ovf_I8 = 0xb9,\n    Conv_Ovf_U8 = 0xba,\n    Refanyval = 0xc2,\n    Ckfinite = 0xc3,\n    Mkrefany = 0xc6,\n    Ldtoken = 0xd0,\n    Conv_U2 = 0xd1,\n    Conv_U1 = 0xd2,\n    Conv_I = 0xd3,\n    Conv_Ovf_I = 0xd4,\n    Conv_Ovf_U = 0xd5,\n    Add_Ovf = 0xd6,\n    Add_Ovf_Un = 0xd7,\n    Mul_Ovf = 0xd8,\n    Mul_Ovf_Un = 0xd9,\n    Sub_Ovf = 0xda,\n    Sub_Ovf_Un = 0xdb,\n    Endfinally = 0xdc,\n    Leave = 0xdd,\n    Leave_S = 0xde,\n    Stind_I = 0xdf,\n    Conv_U = 0xe0,\n\n    LongOpcodePrefix = 0xfe\n};\n\nenum class LongOpcodeSuffix: uint8_t\n{\n    Arglist = 0x00,\n    Ceq = 0x01,\n    Cgt = 0x02,\n    Cgt_Un = 0x03,\n    Clt = 0x04,\n    Clt_Un = 0x05,\n    Ldftn = 0x06,\n    Ldvirtftn = 0x07,\n    Ldarg = 0x09,\n    Ldarga = 0x0a,\n    Starg = 0x0b,\n    Ldloc = 0x0c,\n    Ldloca = 0x0d,\n    Stloc = 0x0e,\n    Localloc = 0x0f,\n    Endfilter = 0x11,\n    Unaligned_ = 0x12,\n    Volatile_ = 0x13,\n    Tail_ = 0x14,\n    Initobj = 0x15,\n    Cpblk = 0x17,\n    Initblk = 0x18,\n    Rethrow = 0x1a,\n    Sizeof = 0x1c,\n    Refanytype = 0x1d,\n\n    InvalidOpcode = 0xff\n};\n\nconst char* OpcodeName(Opcode first, LongOpcodeSuffix second = LongOpcodeSuffix::InvalidOpcode);\n\n}\n\n#endif // !LIC_OPCODES\n", "meta": {"hexsha": "272795aedd9cbc449ca0cc315341190a9196ea34", "size": 4740, "ext": "h", "lang": "C", "max_stars_repo_path": "src/format/Opcodes.h", "max_stars_repo_name": "roberthusak/lic", "max_stars_repo_head_hexsha": "5ad4a7014673bb60b748390856e0c7cb11eaca09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-05-18T11:44:16.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-18T11:44:16.000Z", "max_issues_repo_path": "src/format/Opcodes.h", "max_issues_repo_name": "roberthusak/lic", "max_issues_repo_head_hexsha": "5ad4a7014673bb60b748390856e0c7cb11eaca09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/format/Opcodes.h", "max_forks_repo_name": "roberthusak/lic", "max_forks_repo_head_hexsha": "5ad4a7014673bb60b748390856e0c7cb11eaca09", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.1902834008, "max_line_length": 96, "alphanum_fraction": 0.5694092827, "num_tokens": 2410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.13296424706933602, "lm_q2_score": 0.020645930701556365, "lm_q1q2_score": 0.0027451706307781306}}
{"text": "/*\t$Id$ */\n/*\n * Copyright (c) 2014, 2015 Kristaps Dzonsons <kristaps@kcons.eu>\n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n */\n#include <assert.h>\n#include <inttypes.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include <cairo.h>\n#include <gtk/gtk.h>\n#include <gsl/gsl_multifit.h>\n#include <kplot.h>\n\n#include \"extern.h\"\n\nvoid\ndraw(GtkWidget *w, cairo_t *cr, struct curwin *cur)\n{\n\tdouble\t\t x, y;\n\n\tcur->redraw = 0;\n\n\t/* White-out the view. */\n\tx = gtk_widget_get_allocated_width(w);\n\ty = gtk_widget_get_allocated_height(w);\n\tcairo_set_source_rgb(cr, 1.0, 1.0, 1.0); \n\tcairo_rectangle(cr, 0.0, 0.0, x, y);\n\tcairo_fill(cr);\n\n\n\t/* Draw our plot. */\n\tkplot_draw(cur->views[cur->view], x, y, cr);\n}\n", "meta": {"hexsha": "20075b334d5bbfab9a7d489326e41f37e650418a", "size": 1400, "ext": "c", "lang": "C", "max_stars_repo_path": "draw.c", "max_stars_repo_name": "kristapsdz/bmigrate", "max_stars_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-03-03T17:13:19.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-03T17:13:19.000Z", "max_issues_repo_path": "draw.c", "max_issues_repo_name": "kristapsdz/bmigrate", "max_issues_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "draw.c", "max_forks_repo_name": "kristapsdz/bmigrate", "max_forks_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1666666667, "max_line_length": 75, "alphanum_fraction": 0.7207142857, "num_tokens": 374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.17781086947804958, "lm_q2_score": 0.015424554967147282, "lm_q1q2_score": 0.0027426535300204267}}
{"text": "#pragma once\n#include \"halley/plugin/iasset_importer.h\"\n#include <gsl/gsl>\n\nnamespace Halley\n{\n\tclass AudioImporter : public IAssetImporter\n\t{\n\tpublic:\n\t\tImportAssetType getType() const override { return ImportAssetType::Audio; }\n\n\t\tvoid import(const ImportingAsset& asset, IAssetCollector& collector) override;\n\n\tprivate:\n\t\tBytes encodeVorbis(int channels, int sampleRate, gsl::span<const std::vector<float>> src);\n\t\tstatic std::vector<float> resampleChannel(int from, int to, gsl::span<const float> src);\n\t};\n}\n", "meta": {"hexsha": "c6037aca89b6dbd8aa64971c785058d675d8dc9f", "size": 513, "ext": "h", "lang": "C", "max_stars_repo_path": "src/tools/tools/src/assets/importers/audio_importer.h", "max_stars_repo_name": "sunhay/halley", "max_stars_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T20:23:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T20:23:45.000Z", "max_issues_repo_path": "src/tools/tools/src/assets/importers/audio_importer.h", "max_issues_repo_name": "sunhay/halley", "max_issues_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tools/tools/src/assets/importers/audio_importer.h", "max_forks_repo_name": "sunhay/halley", "max_forks_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0, "max_line_length": 92, "alphanum_fraction": 0.7563352827, "num_tokens": 129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.1645164792819756, "lm_q2_score": 0.016657038453252237, "lm_q1q2_score": 0.0027403573215935427}}
{"text": "#pragma once\n#include <gsl/gsl>\n#include <typeindex>\n#include \"halley/utils/utils.h\"\n#include \"halley/data_structures/maybe.h\"\n#include \"halley/file/byte_serializer.h\"\n\nnamespace Halley\n{\n\tclass IMessageStream;\n\tclass MessageQueue;\n\tclass MessageQueueUDP;\n\tclass MessageQueueTCP;\n\n\tclass NetworkMessage\n\t{\n\t\tfriend class MessageQueue;\n\t\tfriend class MessageQueueUDP;\n\t\tfriend class MessageQueueTCP;\n\n\tpublic:\n\t\tvirtual ~NetworkMessage() = default;\n\n\t\tsize_t getSerializedSize() const\n\t\t{\n\t\t\tif (!serialized) {\n\t\t\t\tserialized = Serializer::toBytes(*this);\n\t\t\t}\n\t\t\treturn serialized.get().size();\n\t\t}\n\n\t\tvoid serializeTo(gsl::span<gsl::byte> dst) const\n\t\t{\n\t\t\tif (!serialized) {\n\t\t\t\tserialized = Serializer::toBytes(*this);\n\t\t\t}\n\t\t\tmemcpy(dst.data(), serialized.get().data(), serialized.get().size());\n\t\t}\n\n\t\tvirtual void serialize(Serializer& s) const = 0;\n\n\tprivate:\n\t\tunsigned short seq = 0;\n\t\tchar channel = -1;\n\n\t\tmutable Maybe<Bytes> serialized;\n\t};\n\n\tclass NetworkMessageFactoryBase\n\t{\n\tpublic:\n\t\tvirtual ~NetworkMessageFactoryBase() {}\n\n\t\tvirtual std::unique_ptr<NetworkMessage> create(gsl::span<const gsl::byte> src) const = 0;\n\t\tvirtual std::type_index getTypeIndex() const = 0;\n\t};\n\n\ttemplate <typename T>\n\tclass NetworkMessageFactory : public NetworkMessageFactoryBase\n\t{\n\tpublic:\n\t\tstd::unique_ptr<NetworkMessage> create(gsl::span<const gsl::byte> src) const override\n\t\t{\n\t\t\treturn std::make_unique<T>(src);\n\t\t}\n\n\t\tstd::type_index getTypeIndex() const override\n\t\t{\n\t\t\treturn std::type_index(typeid(T));\n\t\t}\n\t};\n}\n", "meta": {"hexsha": "9aa10fcde0463d06f8c45b1ee09185e219160c17", "size": 1524, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engine/net/include/halley/net/connection/network_message.h", "max_stars_repo_name": "Healthire/halley", "max_stars_repo_head_hexsha": "aa58e1abe22cda9e80637922721c03574779cd81", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/engine/net/include/halley/net/connection/network_message.h", "max_issues_repo_name": "Healthire/halley", "max_issues_repo_head_hexsha": "aa58e1abe22cda9e80637922721c03574779cd81", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engine/net/include/halley/net/connection/network_message.h", "max_forks_repo_name": "Healthire/halley", "max_forks_repo_head_hexsha": "aa58e1abe22cda9e80637922721c03574779cd81", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.8767123288, "max_line_length": 91, "alphanum_fraction": 0.7086614173, "num_tokens": 398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.13477591047237772, "lm_q2_score": 0.02033235419600324, "lm_q1q2_score": 0.002740311548813206}}
{"text": "#pragma once\n\n#include <renderer/Shading.h>\n#include <renderer/VertexSpecification.h>\n#include <gsl/span>\n\n#include <cassert>\n\nnamespace ad {\nnamespace graphics {\n\nstruct GenericDrawer\n{\n    VertexArrayObject mVertexArray;\n    Program mProgram;\n\n    std::size_t mVertexCount{0};\n    std::size_t mInstanceCount{1};\n\n    template <class T_vertex>\n    VertexBufferObject addVertexBuffer(\n        const std::initializer_list<AttributeDescription> & aAttributes,\n        gsl::span<T_vertex> aVertices)\n    {\n        if (mVertexCount)\n        {\n            assert(static_cast<std::size_t>(aVertices.size()) == mVertexCount);\n        }\n        else\n        {\n            mVertexCount = aVertices.size();\n        }\n\n        return loadVertexBuffer(mVertexArray,\n                                aAttributes,\n                                sizeof(T_vertex),\n                                sizeof(T_vertex)*aVertices.size(),\n                                aVertices.data());\n    }\n\n    void render() const\n    {\n        glBindVertexArray(mVertexArray);\n        glUseProgram(mProgram);\n\n        glDrawArraysInstanced(GL_TRIANGLE_STRIP,\n                              0,\n                              mVertexCount,\n                              mInstanceCount);\n    }\n};\n\n} // namespace graphics\n} // namespace ad\n", "meta": {"hexsha": "997337dfc002e2c161fbfe54d833bee0b3c87869", "size": 1303, "ext": "h", "lang": "C", "max_stars_repo_path": "src/app/prototypes/chader/GenericDrawer.h", "max_stars_repo_name": "Adnn/Graphics", "max_stars_repo_head_hexsha": "335d54bdbb5d8d6042c9adfb9e47ccb14f612cf8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/app/prototypes/chader/GenericDrawer.h", "max_issues_repo_name": "Adnn/Graphics", "max_issues_repo_head_hexsha": "335d54bdbb5d8d6042c9adfb9e47ccb14f612cf8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2021-08-03T11:34:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T13:35:29.000Z", "max_forks_repo_path": "src/app/prototypes/chader/GenericDrawer.h", "max_forks_repo_name": "ShredEagle/graphics", "max_forks_repo_head_hexsha": "6dcc18e4fe21ecd833799bf7338305bbc3600041", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-18T10:56:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-18T10:56:05.000Z", "avg_line_length": 23.6909090909, "max_line_length": 79, "alphanum_fraction": 0.5495011512, "num_tokens": 247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11920292202211753, "lm_q2_score": 0.022977367568369753, "lm_q1q2_score": 0.002738969354525912}}
{"text": "/**\n * This file is part of the \"libterminal\" project\n *   Copyright (c) 2019-2020 Christian Parpart <christian@parpart.family>\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n#pragma once\n\n#include <terminal/GraphicsAttributes.h>\n#include <terminal/primitives.h>\n\n#include <crispy/Comparison.h>\n#include <crispy/assert.h>\n\n#include <gsl/span>\n#include <gsl/span_ext>\n\n#include <iterator>\n#include <sstream>\n#include <string>\n#include <vector>\n\nnamespace terminal\n{\n\nenum class LineFlags : uint8_t\n{\n    None = 0x0000,\n    Wrappable = 0x0001,\n    Wrapped = 0x0002,\n    Marked = 0x0004,\n    // TODO: DoubleWidth  = 0x0010,\n    // TODO: DoubleHeight = 0x0020,\n};\n\ntemplate <typename, bool>\nstruct OptionalProperty;\ntemplate <typename T>\nstruct OptionalProperty<T, false>\n{\n};\ntemplate <typename T>\nstruct OptionalProperty<T, true>\n{\n    T value;\n};\n\nstruct SimpleLineBuffer\n{\n    GraphicsAttributes attributes;\n    std::string text;  // TODO: Try std::string_view later to avoid scattered copies.\n    ColumnCount width; // page display width\n};\n\ntemplate <typename Cell>\nusing InflatedLineBuffer = std::vector<Cell>;\n\ntemplate <typename Cell>\nInflatedLineBuffer<Cell> inflate(SimpleLineBuffer const& input);\n\ntemplate <typename Cell>\nusing LineStorage = std::variant<SimpleLineBuffer, InflatedLineBuffer<Cell>>;\n\n/**\n * Line<Cell> API.\n *\n * TODO: Use custom allocator for ensuring cache locality of Cells to sibling lines.\n * TODO: Make the line optimization work.\n */\ntemplate <typename Cell, bool Optimize = false>\nclass Line\n{\n  public:\n    Line() = default;\n    Line(Line const&) = default;\n    Line(Line&&) noexcept = default;\n    Line& operator=(Line const&) = default;\n    Line& operator=(Line&&) noexcept = default;\n\n    using InflatedBuffer = InflatedLineBuffer<Cell>;\n    using Storage = LineStorage<Cell>;\n    using value_type = Cell;\n    using iterator = typename InflatedBuffer::iterator;\n    using reverse_iterator = typename InflatedBuffer::reverse_iterator;\n    using const_iterator = typename InflatedBuffer::const_iterator;\n\n    Line(ColumnCount _width, LineFlags _flags, Cell _template = {}):\n        buffer_(_width.as<size_t>(), _template /*, _allocator*/), flags_ { static_cast<unsigned>(_flags) }\n    {\n    }\n\n    Line(ColumnCount _width, InflatedBuffer _buffer, LineFlags _flags):\n        buffer_ { std::move(_buffer) }, flags_ { static_cast<unsigned>(_flags) }\n    {\n        buffer_.resize(unbox<size_t>(_width));\n    }\n\n    Line(InflatedBuffer _buffer, LineFlags _flags):\n        buffer_ { std::move(_buffer) }, flags_ { static_cast<unsigned>(_flags) }\n    {\n    }\n\n    constexpr static inline bool ColumnOptimized = Optimize;\n\n    // This is experimental (aka. buggy) and going to be replaced with another optimization idea soon.\n    //#define LINE_AVOID_CELL_RESET 1\n\n    void reset(LineFlags _flags,\n               GraphicsAttributes _attributes) noexcept // TODO: optimize by having no need to O(n) iterate\n                                                        // through all buffer cells.\n    {\n        flags_ = static_cast<unsigned>(_flags);\n\n        // if constexpr (ColumnOptimized)\n        // {\n        //     #if !defined(LINE_AVOID_CELL_RESET)\n        //     if (buffer_.back().backgroundColor() != _attributes.backgroundColor)\n        //         // TODO: also styles and UL color\n        //         markUsedFirst(ColumnCount::cast_from(buffer_.size()));\n        //\n        //     for (auto i = 0; i < *columnsUsed(); ++i)\n        //         buffer_[i].reset(_attributes);\n        //     #endif\n        //     markUsedFirst(ColumnCount(0));\n        // }\n        // else\n        {\n            for (Cell& cell: buffer_)\n                cell.reset(_attributes);\n        }\n    }\n\n    void markUsedFirst(ColumnCount /*_n*/) noexcept\n    {\n        // if constexpr (ColumnOptimized)\n        //     usedColumns_.value = _n;\n    }\n\n    void reset(LineFlags _flags,\n               GraphicsAttributes const& _attributes,\n               char32_t _codepoint,\n               uint8_t _width) noexcept\n    {\n        flags_ = static_cast<unsigned>(_flags);\n        markUsedFirst(size());\n        for (Cell& cell: buffer_)\n        {\n            cell.reset();\n            cell.write(_attributes, _codepoint, _width);\n        }\n    }\n\n    /**\n     * Fills this line with the given content.\n     *\n     * @p _start offset into this line of the first charater\n     * @p _sgr graphics rendition for the line starting at @c _start until the end\n     * @p _ascii the US-ASCII characters to fill with\n     */\n    void fill(ColumnOffset _start, GraphicsAttributes const& _sgr, std::string_view _ascii)\n    {\n        auto& buffer = editable();\n\n        assert(unbox<size_t>(_start) + _ascii.size() <= buffer.size());\n\n        auto constexpr ASCII_Width = 1;\n        auto const* s = _ascii.data();\n\n        Cell* i = &buffer_[unbox<size_t>(_start)];\n        Cell* e = i + _ascii.size();\n        while (i != e)\n            (i++)->write(_sgr, static_cast<char32_t>(*s++), ASCII_Width);\n\n        // if constexpr (ColumnOptimized)\n        // {\n        //     #if !defined(LINE_AVOID_CELL_RESET)\n        //     auto const e2 = buffer.data() + unbox<long>(columnsUsed());\n        //     while (i != e2)\n        //         (i++)->reset();\n        //     #endif\n        //     usedColumns_.value = boxed_cast<ColumnCount>(_start) + ColumnCount::cast_from(_ascii.size());\n        // }\n        // else\n        {\n            auto const e2 = buffer.data() + buffer.size();\n            while (i != e2)\n                (i++)->reset();\n        }\n    }\n\n    ColumnCount size() const noexcept { return ColumnCount::cast_from(buffer_.size()); }\n\n    ColumnCount columnsUsed() const noexcept\n    {\n        // if constexpr (ColumnOptimized)\n        //     return usedColumns_.value;\n        // else\n        return size();\n    }\n\n    void resize(ColumnCount _count);\n\n    gsl::span<Cell const> trim_blank_right() const noexcept;\n\n    gsl::span<Cell const> cells() const noexcept { return buffer_; }\n\n    gsl::span<Cell> useRange(ColumnOffset _start, ColumnCount _count) noexcept\n    {\n        markUsedFirst(std::max(columnsUsed(), boxed_cast<ColumnCount>(_start) + _count));\n#if defined(__FreeBSD__)\n        auto const bufferSpan = gsl::span(buffer_);\n        return bufferSpan.subspan(unbox<size_t>(_start), unbox<size_t>(_count));\n#else\n        // NOTE: On FreeBSD the line below does not compile.\n        return gsl::span(buffer_).subspan(unbox<size_t>(_start), unbox<size_t>(_count));\n#endif\n    }\n\n    iterator begin() noexcept { return buffer_.begin(); }\n    iterator end() noexcept { return std::next(std::begin(buffer_), unbox<int>(columnsUsed())); }\n\n    const_iterator begin() const noexcept { return buffer_.begin(); }\n    const_iterator end() const noexcept { return std::next(buffer_.begin(), unbox<int>(columnsUsed())); }\n\n    reverse_iterator rbegin() noexcept { return buffer_.rbegin(); }\n    reverse_iterator rend() noexcept { return buffer_.rend(); }\n\n    Cell& front() noexcept { return buffer_.front(); }\n    Cell const& front() const noexcept { return buffer_.front(); }\n\n    Cell& back() noexcept { return *std::next(buffer_.begin(), unbox<int>(columnsUsed() - 1)); }\n    Cell const& back() const noexcept { return *std::next(buffer_.begin(), unbox<int>(columnsUsed() - 1)); }\n\n    Cell& useCellAt(ColumnOffset _column) noexcept\n    {\n        Require(ColumnOffset(0) <= _column);\n        Require(_column <= ColumnOffset::cast_from(buffer_.size())); // Allow off-by-one for sentinel.\n        return editable()[unbox<size_t>(_column)];\n    }\n\n    Cell const& at(ColumnOffset _column) const noexcept\n    {\n        Require(ColumnOffset(0) <= _column);\n        Require(_column <= ColumnOffset::cast_from(buffer_.size())); // Allow off-by-one for sentinel.\n        return buffer_[unbox<size_t>(_column)];\n    }\n\n    LineFlags flags() const noexcept { return static_cast<LineFlags>(flags_); }\n\n    bool marked() const noexcept { return isFlagEnabled(LineFlags::Marked); }\n    void setMarked(bool _enable) { setFlag(LineFlags::Marked, _enable); }\n\n    bool wrapped() const noexcept { return isFlagEnabled(LineFlags::Wrapped); }\n    void setWrapped(bool _enable) { setFlag(LineFlags::Wrapped, _enable); }\n\n    bool wrappable() const noexcept { return isFlagEnabled(LineFlags::Wrappable); }\n    void setWrappable(bool _enable) { setFlag(LineFlags::Wrappable, _enable); }\n\n    LineFlags wrappableFlag() const noexcept { return wrappable() ? LineFlags::Wrappable : LineFlags::None; }\n    LineFlags wrappedFlag() const noexcept { return marked() ? LineFlags::Wrapped : LineFlags::None; }\n    LineFlags markedFlag() const noexcept { return marked() ? LineFlags::Marked : LineFlags::None; }\n\n    LineFlags inheritableFlags() const noexcept\n    {\n        auto constexpr Inheritables = unsigned(LineFlags::Wrappable) | unsigned(LineFlags::Marked);\n        return static_cast<LineFlags>(flags_ & Inheritables);\n    }\n\n    void setFlag(LineFlags _flag, bool _enable) noexcept\n    {\n        if (_enable)\n            flags_ |= static_cast<unsigned>(_flag);\n        else\n            flags_ &= ~static_cast<unsigned>(_flag);\n    }\n\n    bool isFlagEnabled(LineFlags _flag) const noexcept\n    {\n        return (flags_ & static_cast<unsigned>(_flag)) != 0;\n    }\n\n    InflatedBuffer reflow(ColumnCount _newColumnCount);\n    std::string toUtf8() const;\n    std::string toUtf8Trimmed() const;\n\n    // Returns a reference to this mutable grid-line buffer.\n    //\n    // If this line has been stored in an optimized state, then\n    // the line will be first unpacked into a vector of grid cells.\n    InflatedBuffer& editable();\n\n  private:\n    InflatedBuffer buffer_;\n    Storage storage_;\n    unsigned flags_ = 0;\n    // OptionalProperty<ColumnCount, ColumnOptimized> usedColumns_;\n};\n\nconstexpr LineFlags operator|(LineFlags a, LineFlags b) noexcept\n{\n    return LineFlags(unsigned(a) | unsigned(b));\n}\n\nconstexpr LineFlags operator~(LineFlags a) noexcept\n{\n    return LineFlags(~unsigned(a));\n}\n\nconstexpr LineFlags operator&(LineFlags a, LineFlags b) noexcept\n{\n    return LineFlags(unsigned(a) & unsigned(b));\n}\n\ntemplate <typename Cell, bool Optimize>\ninline typename Line<Cell, Optimize>::InflatedBuffer& Line<Cell, Optimize>::editable()\n{\n    // TODO: when we impement the line text buffer optimization,\n    // then this is the place where we want to *promote* a possibly\n    // optimized text buffer to a full grid line buffer.\n#if 0\n    if (std::holds_alternative<SimpleLineBuffer>(storage_))\n        storage_ = inflate<Cell>(std::get<SimpleLineBuffer>(storage_));\n\n    return std::get<InflatedBuffer>(storage_);\n#else\n    return buffer_;\n#endif\n}\n\n} // namespace terminal\n\nnamespace fmt // {{{\n{\ntemplate <>\nstruct formatter<terminal::LineFlags>\n{\n    template <typename ParseContext>\n    auto parse(ParseContext& ctx)\n    {\n        return ctx.begin();\n    }\n    template <typename FormatContext>\n    auto format(const terminal::LineFlags _flags, FormatContext& ctx) const\n    {\n        static const std::array<std::pair<terminal::LineFlags, std::string_view>, 3> nameMap = {\n            std::pair { terminal::LineFlags::Wrappable, std::string_view(\"Wrappable\") },\n            std::pair { terminal::LineFlags::Wrapped, std::string_view(\"Wrapped\") },\n            std::pair { terminal::LineFlags::Marked, std::string_view(\"Marked\") },\n        };\n        std::string s;\n        for (auto const& mapping: nameMap)\n        {\n            if ((mapping.first & _flags) != terminal::LineFlags::None)\n            {\n                if (!s.empty())\n                    s += \",\";\n                s += mapping.second;\n            }\n        }\n        return format_to(ctx.out(), s);\n    }\n};\n} // namespace fmt\n", "meta": {"hexsha": "500ac343ec67d82c40987990553549c8c38de395", "size": 12104, "ext": "h", "lang": "C", "max_stars_repo_path": "src/terminal/Line.h", "max_stars_repo_name": "sebastianrakel/contour", "max_stars_repo_head_hexsha": "f0004230be75bb99fc899851a216f41d1dca2a81", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/terminal/Line.h", "max_issues_repo_name": "sebastianrakel/contour", "max_issues_repo_head_hexsha": "f0004230be75bb99fc899851a216f41d1dca2a81", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/terminal/Line.h", "max_forks_repo_name": "sebastianrakel/contour", "max_forks_repo_head_hexsha": "f0004230be75bb99fc899851a216f41d1dca2a81", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6253369272, "max_line_length": 109, "alphanum_fraction": 0.6426801058, "num_tokens": 2877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1023047024186547, "lm_q2_score": 0.026759280468923334, "lm_q1q2_score": 0.0027376002253105204}}
{"text": "#pragma once\n\n#include <nextalign/nextalign.h>\n\n#include <gsl/string_span>\n#include <string>\n#include <vector>\n\n\ntemplate<typename Letter>\nusing SequenceSpan = gsl::basic_string_span<Letter, gsl::dynamic_extent>;\n\nusing NucleotideSequenceSpan = SequenceSpan<Nucleotide>;\n\nusing AminoacidSequenceSpan = SequenceSpan<Aminoacid>;\n\n\nNucleotide toNucleotide(char nuc);\n\nNucleotide stringToNuc(const std::string& nuc);\n\nchar nucToChar(Nucleotide nuc);\n\nstd::string nucToString(Nucleotide nuc);\n\n\nAminoacid charToAa(char aa);\n\nAminoacid stringToAa(const std::string& aa);\n\nchar aaToChar(Aminoacid aa);\n\nstd::string aaToString(Aminoacid aa);\n\ntemplate<typename Letter>\nstruct LetterTag {};\n\ntemplate<typename Letter>\ninline Letter stringToLetter(const std::string& str, LetterTag<Letter>);\n\ntemplate<>\ninline Nucleotide stringToLetter<Nucleotide>(const std::string& str, LetterTag<Nucleotide>) {\n  return stringToNuc(str);\n}\n\ntemplate<>\ninline Aminoacid stringToLetter<Aminoacid>(const std::string& str, LetterTag<Aminoacid>) {\n  return stringToAa(str);\n}\n\ntemplate<typename Letter>\ninline std::string letterToString(Letter letter);\n\ntemplate<>\ninline std::string letterToString(Nucleotide letter) {\n  return nucToString(letter);\n}\n\ntemplate<>\ninline std::string letterToString(Aminoacid letter) {\n  return aaToString(letter);\n}\n\nstd::vector<Insertion> toInsertionsExternal(const std::vector<InsertionInternal<Nucleotide>>& insertions);\n\nstd::vector<Peptide> toPeptidesExternal(const std::vector<PeptideInternal>& peptides);\n\nstd::vector<RefPeptide> toRefPeptidesExternal(const std::vector<RefPeptideInternal>& peptides);\n\n\ninline std::ostream& operator<<(std::ostream& os, const Nucleotide& nuc) {\n  os << \"'\" << nucToString(nuc) << \"'\";\n  return os;\n}\n\ninline std::ostream& operator<<(std::ostream& os, const NucleotideSequence& seq) {\n  os << \"\\\"\";\n  for (const auto& nuc : seq) {\n    os << nucToString(nuc);\n  }\n  os << \"\\\"\";\n  return os;\n}\n\ninline std::ostream& operator<<(std::ostream& os, const Aminoacid& aa) {\n  os << \"'\" << aaToString(aa) << \"'\";\n  return os;\n}\n\ninline std::ostream& operator<<(std::ostream& os, const AminoacidSequence& seq) {\n  os << \"\\\"\";\n  for (const auto& aa : seq) {\n    os << aaToString(aa);\n  }\n  os << \"\\\"\";\n  return os;\n}\n\ninline std::ostream& operator<<(std::ostream& os, const Range& f) {\n  os << \"{ \" << f.begin << \", \" << f.end << \" }\";\n  return os;\n}\n\ninline std::ostream& operator<<(std::ostream& os, const FrameShiftContext& f) {\n  os << \"{ \"                        //\n     << \"codon: \" << f.codon << \", \"//\n     << \"}\"                         //\n    ;\n  return os;\n}\n\n\ninline std::ostream& operator<<(std::ostream& os, const FrameShiftResult& f) {\n  os << \"{ \"                                      //\n     << \"geneName: \\\"\" << f.geneName << \"\\\", \"    //\n     << \"nucRel: \" << f.nucRel << \", \"            //\n     << \"nucAbs: \" << f.nucAbs << \", \"            //\n     << \"codon: \" << f.codon << \", \"              //\n     << \"gapsLeading: \" << f.gapsLeading << \", \"  //\n     << \"gapsTrailing: \" << f.gapsTrailing << \", \"//\n     << \"}\"                                       //\n    ;\n  return os;\n}\n", "meta": {"hexsha": "a98fd1945577e1c8fff6b06620dc83a08da70d7f", "size": 3130, "ext": "h", "lang": "C", "max_stars_repo_path": "packages/nextalign/include/nextalign/private/nextalign_private.h", "max_stars_repo_name": "neherlab/nextclade", "max_stars_repo_head_hexsha": "8a76752eb9dbed0ee44592e708f3b146e8df2410", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "packages/nextalign/include/nextalign/private/nextalign_private.h", "max_issues_repo_name": "neherlab/nextclade", "max_issues_repo_head_hexsha": "8a76752eb9dbed0ee44592e708f3b146e8df2410", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "packages/nextalign/include/nextalign/private/nextalign_private.h", "max_forks_repo_name": "neherlab/nextclade", "max_forks_repo_head_hexsha": "8a76752eb9dbed0ee44592e708f3b146e8df2410", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.04, "max_line_length": 106, "alphanum_fraction": 0.6239616613, "num_tokens": 838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15405756269148543, "lm_q2_score": 0.017712296985821028, "lm_q1q2_score": 0.0027287133033033315}}
{"text": "#pragma once\n\n#include \"NativeDataStream.h\"\n#include \"PerFrameValue.h\"\n#include \"ShaderCompiler.h\"\n#include \"VertexArray.h\"\n\n#include <Babylon/JsRuntime.h>\n#include <Babylon/JsRuntimeScheduler.h>\n\n#include <GraphicsImpl.h>\n#include <BgfxCallback.h>\n#include <FrameBuffer.h>\n\n#include <napi/napi.h>\n\n#include <bgfx/bgfx.h>\n#include <bgfx/platform.h>\n#include <bimg/bimg.h>\n#include <bx/allocator.h>\n\n#include <gsl/gsl>\n\n#include <arcana/threading/cancellation.h>\n#include <unordered_map>\n\nnamespace Babylon\n{\n    struct UniformInfo final\n    {\n        UniformInfo(uint8_t stage, bgfx::UniformHandle handle) :\n            Stage{stage},\n            Handle{handle}\n        {\n        }\n\n        uint8_t Stage{};\n        bgfx::UniformHandle Handle{bgfx::kInvalidHandle};\n    };\n\n    struct ProgramData final\n    {\n        ProgramData() = default;\n        ProgramData(ProgramData&& other) = delete;\n        ProgramData(const ProgramData&) = delete;\n        ProgramData& operator=(ProgramData&& other) = delete;\n        ProgramData& operator=(const ProgramData& other) = delete;\n\n        ~ProgramData()\n        {\n            Dispose();\n        }\n\n        void Dispose()\n        {\n            if (!Disposed && bgfx::isValid(Handle))\n            {\n                bgfx::destroy(Handle);\n            }\n            Disposed = true;\n        }\n\n        std::unordered_map<std::string, uint32_t> VertexAttributeLocations{};\n        std::unordered_map<std::string, UniformInfo> UniformInfos{};\n\n        bgfx::ProgramHandle Handle{bgfx::kInvalidHandle};\n        bool Disposed{false};\n\n        struct UniformValue\n        {\n            std::vector<float> Data{};\n            uint16_t ElementLength{};\n        };\n\n        std::unordered_map<uint16_t, UniformValue> Uniforms{};\n\n        void SetUniform(bgfx::UniformHandle handle, gsl::span<const float> data, size_t elementLength = 1)\n        {\n            UniformValue& value = Uniforms[handle.idx];\n            value.Data.assign(data.begin(), data.end());\n            value.ElementLength = static_cast<uint16_t>(elementLength);\n        }\n    };\n\n    class NativeEngine final : public Napi::ObjectWrap<NativeEngine>\n    {\n        static constexpr auto JS_CLASS_NAME = \"_NativeEngine\";\n        static constexpr auto JS_CONSTRUCTOR_NAME = \"Engine\";\n\n    public:\n        NativeEngine(const Napi::CallbackInfo& info);\n        NativeEngine(const Napi::CallbackInfo& info, JsRuntime& runtime);\n        ~NativeEngine();\n\n        static void Initialize(Napi::Env env);\n\n    private:\n        void Dispose();\n\n        void Dispose(const Napi::CallbackInfo& info);\n        void RequestAnimationFrame(const Napi::CallbackInfo& info);\n        Napi::Value CreateVertexArray(const Napi::CallbackInfo& info);\n        void DeleteVertexArray(NativeDataStream::Reader& data);\n        void BindVertexArray(NativeDataStream::Reader& data);\n        Napi::Value CreateIndexBuffer(const Napi::CallbackInfo& info);\n        void DeleteIndexBuffer(NativeDataStream::Reader& data);\n        void RecordIndexBuffer(const Napi::CallbackInfo& info);\n        void UpdateDynamicIndexBuffer(const Napi::CallbackInfo& info);\n        Napi::Value CreateVertexBuffer(const Napi::CallbackInfo& info);\n        void DeleteVertexBuffer(NativeDataStream::Reader& data);\n        void RecordVertexBuffer(const Napi::CallbackInfo& info);\n        void UpdateDynamicVertexBuffer(const Napi::CallbackInfo& info);\n        Napi::Value CreateProgram(const Napi::CallbackInfo& info);\n        Napi::Value GetUniforms(const Napi::CallbackInfo& info);\n        Napi::Value GetAttributes(const Napi::CallbackInfo& info);\n        void SetProgram(NativeDataStream::Reader& data);\n        void DeleteProgram(NativeDataStream::Reader& data);\n        void SetState(NativeDataStream::Reader& data);\n        void SetZOffset(NativeDataStream::Reader& data);\n        void SetZOffsetUnits(NativeDataStream::Reader& data);\n        void SetDepthTest(NativeDataStream::Reader& data);\n        void SetDepthWrite(NativeDataStream::Reader& data);\n        void SetColorWrite(NativeDataStream::Reader& data);\n        void SetBlendMode(NativeDataStream::Reader& data);\n        void SetMatrix(NativeDataStream::Reader& data);\n        void SetInt(NativeDataStream::Reader& data);\n        void SetIntArray(NativeDataStream::Reader& data);\n        void SetIntArray2(NativeDataStream::Reader& data);\n        void SetIntArray3(NativeDataStream::Reader& data);\n        void SetIntArray4(NativeDataStream::Reader& data);\n        void SetFloatArray(NativeDataStream::Reader& data);\n        void SetFloatArray2(NativeDataStream::Reader& data);\n        void SetFloatArray3(NativeDataStream::Reader& data);\n        void SetFloatArray4(NativeDataStream::Reader& data);\n        void SetMatrices(NativeDataStream::Reader& data);\n        void SetMatrix3x3(NativeDataStream::Reader& data);\n        void SetMatrix2x2(NativeDataStream::Reader& data);\n        void SetFloat(NativeDataStream::Reader& data);\n        void SetFloat2(NativeDataStream::Reader& data);\n        void SetFloat3(NativeDataStream::Reader& data);\n        void SetFloat4(NativeDataStream::Reader& data);\n        Napi::Value CreateTexture(const Napi::CallbackInfo& info);\n        void LoadTexture(const Napi::CallbackInfo& info);\n        void CopyTexture(const Napi::CallbackInfo& info);\n        void LoadRawTexture(const Napi::CallbackInfo& info);\n        void LoadCubeTexture(const Napi::CallbackInfo& info);\n        void LoadCubeTextureWithMips(const Napi::CallbackInfo& info);\n        Napi::Value GetTextureWidth(const Napi::CallbackInfo& info);\n        Napi::Value GetTextureHeight(const Napi::CallbackInfo& info);\n        void SetTextureSampling(NativeDataStream::Reader& data);\n        void SetTextureWrapMode(NativeDataStream::Reader& data);\n        void SetTextureAnisotropicLevel(NativeDataStream::Reader& data);\n        void SetTexture(NativeDataStream::Reader& data);\n        void DeleteTexture(const Napi::CallbackInfo& info);\n        Napi::Value CreateFrameBuffer(const Napi::CallbackInfo& info);\n        void DeleteFrameBuffer(NativeDataStream::Reader& data);\n        void BindFrameBuffer(NativeDataStream::Reader& data);\n        void UnbindFrameBuffer(NativeDataStream::Reader& data);\n        void DrawIndexed(NativeDataStream::Reader& data);\n        void Draw(NativeDataStream::Reader& data);\n        void Clear(NativeDataStream::Reader& data);\n        Napi::Value GetRenderWidth(const Napi::CallbackInfo& info);\n        Napi::Value GetRenderHeight(const Napi::CallbackInfo& info);\n        void SetViewPort(const Napi::CallbackInfo& info);\n        Napi::Value GetHardwareScalingLevel(const Napi::CallbackInfo& info);\n        void SetHardwareScalingLevel(const Napi::CallbackInfo& info);\n        Napi::Value CreateImageBitmap(const Napi::CallbackInfo& info);\n        Napi::Value ResizeImageBitmap(const Napi::CallbackInfo& info);\n        void GetFrameBufferData(const Napi::CallbackInfo& info);\n        void SetStencil(NativeDataStream::Reader& data);\n        void SetCommandDataStream(const Napi::CallbackInfo& info);\n        void SubmitCommands(const Napi::CallbackInfo& info);\n        void DrawInternal(bgfx::Encoder* encoder, uint32_t fillMode);\n\n        std::string ProcessShaderCoordinates(const std::string& vertexSource);\n\n        GraphicsImpl::UpdateToken& GetUpdateToken();\n        FrameBuffer& GetBoundFrameBuffer(bgfx::Encoder& encoder);\n\n        std::shared_ptr<arcana::cancellation_source> m_cancellationSource{};\n\n        ShaderCompiler m_shaderCompiler{};\n\n        ProgramData* m_currentProgram{nullptr};\n\n        JsRuntime& m_runtime;\n        GraphicsImpl& m_graphicsImpl;\n\n        JsRuntimeScheduler m_runtimeScheduler;\n\n        std::optional<GraphicsImpl::UpdateToken> m_updateToken{};\n\n        void ScheduleRequestAnimationFrameCallbacks();\n        bool m_requestAnimationFrameCallbacksScheduled{};\n\n        bx::DefaultAllocator m_allocator{};\n        uint64_t m_engineState{BGFX_STATE_DEFAULT};\n        uint32_t m_stencilState{BGFX_STENCIL_TEST_ALWAYS | BGFX_STENCIL_FUNC_REF(0) | BGFX_STENCIL_FUNC_RMASK(0xFF) | BGFX_STENCIL_OP_FAIL_S_KEEP | BGFX_STENCIL_OP_FAIL_Z_KEEP | BGFX_STENCIL_OP_PASS_Z_REPLACE};\n\n        template<int size, typename arrayType>\n        void SetTypeArrayN(const UniformInfo& uniformInfo, const uint32_t elementLength, const arrayType& array);\n\n        template<int size>\n        void SetIntArrayN(NativeDataStream::Reader& data);\n\n        template<int size>\n        void SetFloatArrayN(NativeDataStream::Reader& data);\n\n        template<int size>\n        void SetFloatN(NativeDataStream::Reader& data);\n\n        template<int size>\n        void SetMatrixN(NativeDataStream::Reader& data);\n\n        // Scratch vector used for data alignment.\n        std::vector<float> m_scratch{};\n\n        std::vector<Napi::FunctionReference> m_requestAnimationFrameCallbacks{};\n\n        VertexArray* m_boundVertexArray{};\n        FrameBuffer m_defaultFrameBuffer;\n        FrameBuffer* m_boundFrameBuffer{};\n        PerFrameValue<bool> m_boundFrameBufferNeedsRebinding;\n\n        // TODO: This should be changed to a non-owning ref once multi-update is available.\n        NativeDataStream* m_commandStream{};\n    };\n}\n", "meta": {"hexsha": "3141cfdf5f2b0dd47f733493c7ef1c168237d80e", "size": 9166, "ext": "h", "lang": "C", "max_stars_repo_path": "Plugins/NativeEngine/Source/NativeEngine.h", "max_stars_repo_name": "olidum/Babylon", "max_stars_repo_head_hexsha": "1ee73a8e80b2a71d40e7bee8a4012b066a55b814", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 474.0, "max_stars_repo_stars_event_min_datetime": "2019-05-29T09:41:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:09:35.000Z", "max_issues_repo_path": "Plugins/NativeEngine/Source/NativeEngine.h", "max_issues_repo_name": "olidum/Babylon", "max_issues_repo_head_hexsha": "1ee73a8e80b2a71d40e7bee8a4012b066a55b814", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 593.0, "max_issues_repo_issues_event_min_datetime": "2019-05-31T23:56:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:25:09.000Z", "max_forks_repo_path": "Plugins/NativeEngine/Source/NativeEngine.h", "max_forks_repo_name": "olidum/Babylon", "max_forks_repo_head_hexsha": "1ee73a8e80b2a71d40e7bee8a4012b066a55b814", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 114.0, "max_forks_repo_forks_event_min_datetime": "2019-06-10T18:07:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T21:13:27.000Z", "avg_line_length": 40.0262008734, "max_line_length": 210, "alphanum_fraction": 0.6872136155, "num_tokens": 2025, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15817436862177234, "lm_q2_score": 0.0171767107417693, "lm_q1q2_score": 0.002716915376578174}}
{"text": "#pragma once\n\n#include <algorithm>\n#include <gsl/gsl_assert>\n#include \"family_type.h\"\n#include \"family_mask.h\"\n#include \"entity_id.h\"\n#include \"halley/data_structures/nullable_reference.h\"\n#include \"halley/support/exception.h\"\n#include \"halley/support/debug.h\"\n#include \"halley/utils/utils.h\"\n\nnamespace Halley {\n\tclass Entity;\n\tclass FamilyBindingBase;\n\n\tclass Family {\n\t\tfriend class World;\n\n\tpublic:\n\t\texplicit Family(FamilyMaskType inclusionMask, FamilyMaskType optionalMask);\n\t\tvirtual ~Family() {}\n\n\t\tsize_t count() const\n\t\t{\n\t\t\treturn elemCount;\n\t\t}\n\n\t\tvoid* getElement(size_t n) const\n\t\t{\n\t\t\treturn static_cast<char*>(elems) + (n * elemSize);\n\t\t}\n\n\t\tvoid addOnEntitiesAdded(FamilyBindingBase* bind);\n\t\tvoid removeOnEntityAdded(FamilyBindingBase* bind);\n\t\tvoid addOnEntitiesRemoved(FamilyBindingBase* bind);\n\t\tvoid removeOnEntityRemoved(FamilyBindingBase* bind);\n\t\tvoid addOnEntitiesReloaded(FamilyBindingBase* bind);\n\t\tvoid removeOnEntitiesReloaded(FamilyBindingBase* bind);\n\n\t\tvoid notifyAdd(void* entities, size_t count);\n\t\tvoid notifyRemove(void* entities, size_t count);\n\t\tvoid notifyReload(void* entities, size_t count);\n\n\tprotected:\n\t\tvirtual void addEntity(Entity& entity) = 0;\n\t\tvirtual void refreshEntity(Entity& entity) = 0;\n\t\tvoid removeEntity(Entity& entity);\n\t\tvoid reloadEntity(Entity& entity);\n\t\tvirtual void updateEntities() = 0;\n\t\tvirtual void clearEntities() = 0;\n\t\t\n\t\tvoid* elems = nullptr;\n\t\tsize_t elemCount = 0;\n\t\tsize_t elemSize = 0;\n\t\tVector<EntityId> toRemove;\n\t\tVector<EntityId> toReload;\n\n\t\tVector<FamilyBindingBase*> addEntityCallbacks;\n\t\tVector<FamilyBindingBase*> removeEntityCallbacks;\n\t\tVector<FamilyBindingBase*> modifiedEntityCallbacks;\n\n\tprivate:\n\t\tFamilyMaskType inclusionMask;\n\t\tFamilyMaskType optionalMask;\n\t};\n\n\tclass FamilyBase {\n\tprotected:\n\t\tNullableReferenceAnchor anchor;\n\n\tpublic:\n\t\tEntityId entityId;\n\t};\n\n\ttemplate <typename T>\n\tclass FamilyBaseOf : public FamilyBase {\n\tpublic:\n\t\tNullableReferenceOf<T> getReference()\n\t\t{\n\t\t\treturn anchor.getReferenceOf<T>();\n\t\t}\n\n\t\tNullableReferenceOf<const T> getReference() const\n\t\t{\n\t\t\treturn anchor.getReferenceOf<const T>();\n\t\t}\n\t};\n\t\n\t// Apple's Clang 3.5 does not seem to have constexpr std::max...\n\tconstexpr size_t maxSize(size_t a, size_t b)\n\t{\n\t\treturn a > b ? a : b;\n\t}\n\n\ttemplate <typename T>\n\tclass FamilyImpl : public Family\n\t{\n\t\tconstexpr static size_t storageSize = sizeof(T) - alignUp(sizeof(FamilyBase), alignof(void*));\n\t\tstatic_assert(std::is_base_of<FamilyBase, T>::value, \"Family type does not derive from FamilyBase\");\n\n\t\t// I don't know why this needs to be aligned up to 8 on Win32. :|\n\t\tstatic_assert(alignUp(T::Type::getNumComponents() * sizeof(void*), size_t(8)) == storageSize, \"Family type has unexpected storage size\");\n\n\t\tstruct StorageType : public FamilyBase\n\t\t{\n\t\t\talignas(alignof(void*)) std::array<char, storageSize> data;\n\t\t};\n\n\tpublic:\n\t\texplicit FamilyImpl(MaskStorage& storage)\n\t\t\t: Family(T::Type::inclusionMask(storage), T::Type::optionalMask(storage))\n\t\t{\n\t\t}\n\t\t\t\t\n\tprotected:\n\t\tvoid addEntity(Entity& entity) override\n\t\t{\n\t\t\tauto& e = entities.emplace_back();\n\t\t\te.entityId = entity.getEntityId();\n\t\t\tT::Type::loadComponents(entity, &e.data[0]);\n\n\t\t\tdirty = true;\n\t\t}\n\t\t\n\t\tvoid refreshEntity(Entity& entity) override\n\t\t{\n\t\t\tfor (auto& e: entities) {\n\t\t\t\tif (e.entityId == entity.getEntityId()) {\n\t\t\t\t\tT::Type::loadComponents(entity, &e.data[0]);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tvoid updateEntities() override\n\t\t{\n\t\t\tif (dirty) {\n\t\t\t\t// Notify additions\n\t\t\t\tHALLEY_DEBUG_TRACE();\n\t\t\t\tsize_t prevSize = elemCount;\n\t\t\t\tsize_t curSize = entities.size();\n\t\t\t\tupdateElems();\n\t\t\t\tExpects(curSize >= prevSize);\n\t\t\t\tif (curSize > prevSize) {\n\t\t\t\t\tnotifyAdd(entities.data() + prevSize, curSize - prevSize);\n\t\t\t\t}\n\n\t\t\t\tdirty = false;\n\t\t\t}\n\n\t\t\tif (!toReload.empty()) {\n\t\t\t\t// Notify reloads\n\t\t\t\tHALLEY_DEBUG_TRACE();\n\t\t\t\tstd::vector<StorageType*> reloadedEntities;\n\t\t\t\tfor (auto& entity : entities) {\n\t\t\t\t\tif (std::find(toReload.begin(), toReload.end(), entity.entityId) != toReload.end()) {\n\t\t\t\t\t\treloadedEntities.push_back(&entity);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tnotifyReload(reloadedEntities.data(), reloadedEntities.size());\n\t\t\t\ttoReload.clear();\n\t\t\t}\n\n\t\t\t// Remove\n\t\t\tremoveDeadEntities();\n\t\t}\n\n\t\tvoid clearEntities() override\n\t\t{\n\t\t\tnotifyRemove(entities.data(), entities.size());\n\t\t\tentities.clear();\n\t\t\tupdateElems();\n\t\t}\n\n\tprivate:\n\t\tVector<StorageType> entities;\n\t\tbool dirty = false;\n\n\t\tvoid updateElems()\n\t\t{\n\t\t\telems = entities.empty() ? nullptr : entities.data();\n\t\t\telemCount = entities.size();\n\t\t\telemSize = sizeof(StorageType);\n\t\t}\n\n\t\tvoid removeDeadEntities()\n\t\t{\n\t\t\t// Performance-critical code\n\t\t\t// Benchmarks suggest that using a Vector is faster than std::set and std::unordered_set\n\t\t\tif (!toRemove.empty()) {\n\t\t\t\tHALLEY_DEBUG_TRACE();\n\t\t\t\tsize_t removeCount = toRemove.size();\n\t\t\t\tExpects(removeCount > 0);\n\t\t\t\tExpects(removeCount <= entities.size());\n\t\t\t\tstd::sort(toRemove.begin(), toRemove.end());\n\n\t\t\t\tfor (size_t i = 1; i < toRemove.size(); ++i) {\n\t\t\t\t\tExpects(toRemove[i - 1] != toRemove[i]);\n\t\t\t\t}\n\n\t\t\t\t// Move all entities to be removed to the back of the vector\n\t\t\t\t{\n\t\t\t\t\tint n = int(entities.size());\n\t\t\t\t\t// Note: it's important to scan it forward. Scanning backwards would improve performance for short-lived entities,\n\t\t\t\t\t// but it causes an issue where an entity is removed and added to the same family in one frame.\n\t\t\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\t\t\tEntityId id = entities[i].entityId;\n\t\t\t\t\t\tauto iter = std::lower_bound(toRemove.begin(), toRemove.end(), id);\n\t\t\t\t\t\tif (iter != toRemove.end() && id == *iter) {\n\t\t\t\t\t\t\ttoRemove.erase(iter);\n\t\t\t\t\t\t\tif (i != n - 1) {\n\t\t\t\t\t\t\t\tstd::swap(entities[i], entities[n - 1]);\n\t\t\t\t\t\t\t\ti--;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tn--;\n\t\t\t\t\t\t\tif (toRemove.empty()) {\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tEnsures(size_t(n) + removeCount == entities.size());\n\t\t\t\t}\n\n\t\t\t\tExpects(toRemove.empty());\n\n\t\t\t\t// Notify removal\n\t\t\t\tsize_t newSize = entities.size() - removeCount;\n\t\t\t\tEnsures(newSize < entities.size());\n\t\t\t\tnotifyRemove(entities.data() + newSize, removeCount);\n\n\t\t\t\t// Remove them\n\t\t\t\tentities.resize(newSize);\n\t\t\t\tupdateElems();\n\t\t\t}\n\t\t\tEnsures(toRemove.empty());\n\t\t}\n\t};\n}\n", "meta": {"hexsha": "e70910c382fd97a753e9950ddec92d246bdac823", "size": 6160, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engine/entity/include/halley/entity/family.h", "max_stars_repo_name": "code-disaster/halley", "max_stars_repo_head_hexsha": "5c85c889b76c69c6bdef6f4801c6aba282b7af80", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3262.0, "max_stars_repo_stars_event_min_datetime": "2016-04-10T15:24:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:47:08.000Z", "max_issues_repo_path": "src/engine/entity/include/halley/entity/family.h", "max_issues_repo_name": "code-disaster/halley", "max_issues_repo_head_hexsha": "5c85c889b76c69c6bdef6f4801c6aba282b7af80", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 53.0, "max_issues_repo_issues_event_min_datetime": "2016-10-09T16:25:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-10T13:52:37.000Z", "max_forks_repo_path": "src/engine/entity/include/halley/entity/family.h", "max_forks_repo_name": "code-disaster/halley", "max_forks_repo_head_hexsha": "5c85c889b76c69c6bdef6f4801c6aba282b7af80", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 193.0, "max_forks_repo_forks_event_min_datetime": "2017-10-23T06:08:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T12:59:58.000Z", "avg_line_length": 25.6666666667, "max_line_length": 139, "alphanum_fraction": 0.6720779221, "num_tokens": 1632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14608723589515568, "lm_q2_score": 0.01854656424087758, "lm_q1q2_score": 0.002709416305301742}}
{"text": "#pragma once\n\n#include \"halley/net/connection/iconnection.h\"\n#include \"halley/net/connection/network_packet.h\"\n\n#ifdef _MSC_VER\n#pragma warning(disable: 4834)\n#endif\n#define BOOST_SYSTEM_NO_DEPRECATED\n#define BOOST_ERROR_CODE_HEADER_ONLY\n#include <boost/asio.hpp>\n\n#include <deque>\n#include <array>\n#include <string>\n#include <gsl/gsl>\n\nnamespace Halley\n{\n\tclass NetworkService;\n\tusing UDPEndpoint = boost::asio::ip::udp::endpoint;\n\tusing UDPSocket = boost::asio::ip::udp::socket;\n\n\tclass AsioUDPConnection : public IConnection\n\t{\n\tpublic:\n\t\tAsioUDPConnection(UDPSocket& socket, UDPEndpoint remote);\n\n\t\tvoid close() override;\n\t\tConnectionStatus getStatus() const override { return status; }\n\t\tvoid send(OutboundNetworkPacket&& packet) override;\n\t\tbool receive(InboundNetworkPacket& packet) override;\n\t\t\n\t\tbool matchesEndpoint(const UDPEndpoint& remoteEndpoint) const;\n\t\tvoid onReceive(gsl::span<const gsl::byte> data);\n\t\tvoid setError(const std::string& cs);\n\t\t\n\t\tvoid open(short connectionId);\n\t\tvoid onOpen(short connectionId);\n\t\tvoid terminateConnection();\n\t\tshort getConnectionId() const { return connectionId; }\n\n\tprivate:\n\t\tUDPSocket& socket;\n\t\tUDPEndpoint remote;\n\t\tConnectionStatus status;\n\t\tshort connectionId;\n\n\t\tstd::deque<OutboundNetworkPacket> pendingSend;\n\t\tstd::deque<InboundNetworkPacket> pendingReceive;\n\t\tstd::array<gsl::byte, 2048> sendBuffer;\n\t\tstd::string error;\n\n\t\tvoid sendNext();\n\t};\n}\n", "meta": {"hexsha": "ae9f510babd73f060e6f9874e86f0e298b1cdec9", "size": 1410, "ext": "h", "lang": "C", "max_stars_repo_path": "src/plugins/asio/src/asio_udp_connection.h", "max_stars_repo_name": "sunhay/halley", "max_stars_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3262.0, "max_stars_repo_stars_event_min_datetime": "2016-04-10T15:24:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:47:08.000Z", "max_issues_repo_path": "src/plugins/asio/src/asio_udp_connection.h", "max_issues_repo_name": "sunhay/halley", "max_issues_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 53.0, "max_issues_repo_issues_event_min_datetime": "2016-10-09T16:25:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-10T13:52:37.000Z", "max_forks_repo_path": "src/plugins/asio/src/asio_udp_connection.h", "max_forks_repo_name": "sunhay/halley", "max_forks_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 193.0, "max_forks_repo_forks_event_min_datetime": "2017-10-23T06:08:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T12:59:58.000Z", "avg_line_length": 24.7368421053, "max_line_length": 64, "alphanum_fraction": 0.7602836879, "num_tokens": 348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.13660837596589698, "lm_q2_score": 0.019719127495253782, "lm_q1q2_score": 0.002693797982591085}}
{"text": "#pragma once\n\n#include <vector>\n\n#include <gsl/gsl>\n#include <atlcomcli.h>\n\nusing gsl::span;\n\nnamespace gfx {\n\n\t/*\n\t\tDefines the file formats supported by the imaging functions.\n\t*/\n\tenum class ImageFileFormat {\n\t\tBMP,\n\t\tJPEG,\n\t\tTGA,\n\t\tFNTART,\n\t\tIMG,\n\t\tUnknown\n\t};\n\n\tstruct ImageFileInfo {\n\t\tImageFileFormat format = ImageFileFormat::Unknown;\n\t\tint width = 0;\n\t\tint height = 0;\n\t\tbool hasAlpha = false;\n\t};\n\n\t/*\n\t\tTries to detect the image format of the given data by\n\t\tinspecting the header only.\n\t*/\n\tImageFileInfo DetectImageFormat(span<uint8_t> data);\n\n\tbool DetectTga(span<uint8_t> data, ImageFileInfo &info);\n\n\tstd::unique_ptr<uint8_t[]> DecodeTga(span<uint8_t> data);\n\n\t/*\n\t\tSpecifies the pixel format of the uncompressed data\n\t\twhen encoding or decoding a JPEG image.\n\t*/\n\tenum class JpegPixelFormat {\n\t\tRGB,\n\t\tBGR,\n\t\tRGBX,\n\t\tBGRX,\n\t\tXBGR,\n\t\tXRGB\n\t};\n\n\t/*\n\t\tEncodes a JPEG image in memory and returns the compressed data.\n\t\tpitch is the size in pixels of a line of the uncompressed data.\n\t\tquality is an integer between 1 and 100.\n\t*/\n\tstd::vector<uint8_t> EncodeJpeg(const uint8_t* imageData,\n\t                                JpegPixelFormat imageDataFormat,\n\t                                int width,\n\t                                int height,\n\t                                int quality,\n\t                                int pitch);\n\n\tstruct DecodedImage {\n\t\tstd::unique_ptr<uint8_t[]> data;\n\t\tImageFileInfo info;\n\t};\n\n\tDecodedImage DecodeFontArt(const span<uint8_t> data);\n\n\tDecodedImage DecodeImage(const span<uint8_t> data);\n\n\tDecodedImage DecodeCombinedImage(const std::string &filename, span<uint8_t> data);\n\n\tHCURSOR LoadImageToCursor(const span<uint8_t> data, uint32_t hotspotX, uint32_t hotspotY);\n\n}\n", "meta": {"hexsha": "2c0f0f7a4f56242302f9ec102ce0001ba096c400", "size": 1724, "ext": "h", "lang": "C", "max_stars_repo_path": "Infrastructure/include/infrastructure/images.h", "max_stars_repo_name": "edoipi/TemplePlus", "max_stars_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 69.0, "max_stars_repo_stars_event_min_datetime": "2015-05-05T14:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T06:13:04.000Z", "max_issues_repo_path": "Infrastructure/include/infrastructure/images.h", "max_issues_repo_name": "edoipi/TemplePlus", "max_issues_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 457.0, "max_issues_repo_issues_event_min_datetime": "2015-05-01T22:07:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T02:19:10.000Z", "max_forks_repo_path": "Infrastructure/include/infrastructure/images.h", "max_forks_repo_name": "edoipi/TemplePlus", "max_forks_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2016-02-04T21:19:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T23:14:51.000Z", "avg_line_length": 21.55, "max_line_length": 91, "alphanum_fraction": 0.6583526682, "num_tokens": 443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16885695214168314, "lm_q2_score": 0.015906388387952466, "lm_q1q2_score": 0.002685904262771514}}
{"text": "// ---------------------------------------------------------------------------\r\n//\r\n//  Author  : github.com/luncliff (luncliff@gmail.com)\r\n//  License : CC BY 4.0\r\n//\r\n//  Note\r\n//      Async I/O operation support for socket\r\n//\r\n// ---------------------------------------------------------------------------\r\n#pragma once\r\n// clang-format off\r\n#ifdef USE_STATIC_LINK_MACRO // ignore macro declaration in static build\r\n#   define _INTERFACE_\r\n#   define _HIDDEN_\r\n#else \r\n#   if defined(_MSC_VER) // MSVC\r\n#       define _HIDDEN_\r\n#       ifdef _WINDLL\r\n#           define _INTERFACE_ __declspec(dllexport)\r\n#       else\r\n#           define _INTERFACE_ __declspec(dllimport)\r\n#       endif\r\n#   elif defined(__GNUC__) || defined(__clang__)\r\n#       define _INTERFACE_ __attribute__((visibility(\"default\")))\r\n#       define _HIDDEN_ __attribute__((visibility(\"hidden\")))\r\n#   else\r\n#       error \"unexpected compiler\"\r\n#   endif // compiler check\r\n#endif\r\n// clang-format on\r\n\r\n#ifndef COROUTINE_NET_IO_H\r\n#define COROUTINE_NET_IO_H\r\n#include <coroutine/yield.hpp>\r\n\r\n#include <chrono>\r\n#include <gsl/gsl>\r\n\r\n#if defined(_MSC_VER)\r\n#include <WS2tcpip.h>\r\n#include <WinSock2.h>\r\n#include <ws2def.h>\r\n#pragma comment(lib, \"Ws2_32.lib\")\r\n\r\nusing io_control_block = OVERLAPPED;\r\n\r\nstatic constexpr bool is_winsock = true;\r\nstatic constexpr bool is_netinet = false;\r\n#else\r\n#include <fcntl.h>\r\n#include <netdb.h>\r\n#include <netinet/in.h>\r\n#include <sys/socket.h>\r\n#include <unistd.h>\r\n\r\n// - Note\r\n// follow the definition of Windows `OVERLAPPED`\r\nstruct io_control_block\r\n{\r\n    uint64_t internal; // uint32_t errc; int32_t flag;\r\n    uint64_t internal_high;\r\n    union {\r\n        struct\r\n        {\r\n            int32_t offset; // socklen_t addrlen;\r\n            int32_t offset_high;\r\n        };\r\n        void* ptr;\r\n    };\r\n    int64_t handle; // int64_t sd;\r\n};\r\n\r\nstatic constexpr bool is_winsock = false;\r\nstatic constexpr bool is_netinet = true;\r\n#endif\r\n\r\n// - Note\r\n//      Even though this class violates C++ Core Guidelines,\r\n//      it will be used for simplicity\r\nunion endpoint_t final {\r\n    sockaddr_storage storage{};\r\n    sockaddr addr;\r\n    sockaddr_in in4;\r\n    sockaddr_in6 in6;\r\n};\r\n\r\nusing io_task_t = std::experimental::coroutine_handle<void>;\r\nusing buffer_view_t = gsl::span<gsl::byte>;\r\n\r\nstruct io_work_t : public io_control_block\r\n{\r\n    io_task_t task{};\r\n    buffer_view_t buffer{};\r\n    endpoint_t* ep{};\r\n\r\n  public:\r\n    _INTERFACE_ bool ready() const noexcept;\r\n    _INTERFACE_ uint32_t error() const noexcept;\r\n};\r\nstatic_assert(sizeof(buffer_view_t) <= sizeof(void*) * 2);\r\nstatic_assert(sizeof(io_work_t) <= 64);\r\n\r\nclass io_send_to final : public io_work_t\r\n{\r\n  public:\r\n    _INTERFACE_ void suspend(io_task_t rh) noexcept(false);\r\n    _INTERFACE_ int64_t resume() noexcept;\r\n\r\n  public:\r\n    auto await_ready() const noexcept\r\n    {\r\n        return this->ready();\r\n    }\r\n    void await_suspend(io_task_t rh) noexcept(false)\r\n    {\r\n        return this->suspend(rh);\r\n    }\r\n    auto await_resume() noexcept\r\n    {\r\n        return this->resume();\r\n    }\r\n};\r\nstatic_assert(sizeof(io_send_to) == sizeof(io_work_t));\r\n\r\n[[nodiscard]] _INTERFACE_ auto\r\n    send_to(uint64_t sd, const sockaddr_in& remote, //\r\n            buffer_view_t buffer, io_work_t& work) noexcept(false)\r\n        -> io_send_to&;\r\n\r\n[[nodiscard]] _INTERFACE_ //\r\n    auto\r\n    send_to(uint64_t sd, const sockaddr_in6& remote, //\r\n            buffer_view_t buffer, io_work_t& work) noexcept(false)\r\n        -> io_send_to&;\r\n\r\nclass io_recv_from final : public io_work_t\r\n{\r\n  public:\r\n    _INTERFACE_ void suspend(io_task_t rh) noexcept(false);\r\n    _INTERFACE_ int64_t resume() noexcept;\r\n\r\n  public:\r\n    auto await_ready() const noexcept\r\n    {\r\n        return this->ready();\r\n    }\r\n    void await_suspend(io_task_t rh) noexcept(false)\r\n    {\r\n        return this->suspend(rh);\r\n    }\r\n    auto await_resume() noexcept\r\n    {\r\n        return this->resume();\r\n    }\r\n};\r\nstatic_assert(sizeof(io_recv_from) == sizeof(io_work_t));\r\n\r\n[[nodiscard]] _INTERFACE_ //\r\n    auto\r\n    recv_from(uint64_t sd, sockaddr_in6& remote, //\r\n              buffer_view_t buffer, io_work_t& work) noexcept(false)\r\n        -> io_recv_from&;\r\n\r\n[[nodiscard]] _INTERFACE_ //\r\n    auto\r\n    recv_from(uint64_t sd, sockaddr_in& remote, //\r\n              buffer_view_t buffer, io_work_t& work) noexcept(false)\r\n        -> io_recv_from&;\r\n\r\nclass io_send final : public io_work_t\r\n{\r\n  public:\r\n    _INTERFACE_ void suspend(io_task_t rh) noexcept(false);\r\n    _INTERFACE_ int64_t resume() noexcept;\r\n\r\n  public:\r\n    auto await_ready() const noexcept\r\n    {\r\n        return this->ready();\r\n    }\r\n    void await_suspend(io_task_t rh) noexcept(false)\r\n    {\r\n        return this->suspend(rh);\r\n    }\r\n    auto await_resume() noexcept\r\n    {\r\n        return this->resume();\r\n    }\r\n};\r\nstatic_assert(sizeof(io_send) == sizeof(io_work_t));\r\n\r\n[[nodiscard]] _INTERFACE_ //\r\n    auto\r\n    send_stream(uint64_t sd, buffer_view_t buffer, uint32_t flag,\r\n                io_work_t& work) noexcept(false) -> io_send&;\r\n\r\nclass io_recv final : public io_work_t\r\n{\r\n  public:\r\n    _INTERFACE_ void suspend(io_task_t rh) noexcept(false);\r\n    _INTERFACE_ int64_t resume() noexcept;\r\n\r\n  public:\r\n    auto await_ready() const noexcept\r\n    {\r\n        return this->ready();\r\n    }\r\n    void await_suspend(io_task_t rh) noexcept(false)\r\n    {\r\n        return this->suspend(rh);\r\n    }\r\n    auto await_resume() noexcept\r\n    {\r\n        return this->resume();\r\n    }\r\n};\r\nstatic_assert(sizeof(io_recv) == sizeof(io_work_t));\r\n\r\n[[nodiscard]] _INTERFACE_ //\r\n    auto\r\n    recv_stream(uint64_t sd, buffer_view_t buffer, uint32_t flag,\r\n                io_work_t& work) noexcept(false) -> io_recv&;\r\n\r\n// - Note\r\n//      This function is only non-windows platform.\r\n//      Over windows api, it always yields nothing.\r\n//\r\n//      User must continue looping without break so that there is no leak of\r\n//      event. Also, the library doesn't guarantee all coroutines(i/o tasks)\r\n//      will be fetched at once. Therefore it is strongly recommended for user\r\n//      to have a method to detect that coroutines are returned.\r\n_INTERFACE_\r\nauto wait_io_tasks(std::chrono::nanoseconds timeout) noexcept(false)\r\n    -> coro::enumerable<io_task_t>;\r\n\r\n_INTERFACE_\r\nauto host_name() noexcept -> gsl::czstring<NI_MAXHOST>;\r\n\r\n_INTERFACE_\r\nstd::errc peer_name(uint64_t sd, sockaddr_in6& ep) noexcept;\r\n\r\n_INTERFACE_\r\nstd::errc sock_name(uint64_t sd, sockaddr_in6& ep) noexcept;\r\n\r\n_INTERFACE_\r\nauto resolve(const addrinfo& hint, //\r\n             gsl::czstring<NI_MAXHOST> name,\r\n             gsl::czstring<NI_MAXSERV> serv) noexcept\r\n    -> coro::enumerable<sockaddr_in6>;\r\n\r\n_INTERFACE_\r\nstd::errc nameof(const sockaddr_in& ep, //\r\n                 gsl::zstring<NI_MAXHOST> name) noexcept;\r\n\r\n_INTERFACE_\r\nstd::errc nameof(const sockaddr_in6& ep, //\r\n                 gsl::zstring<NI_MAXHOST> name) noexcept;\r\n\r\n_INTERFACE_\r\nstd::errc nameof(const sockaddr_in6& ep, //\r\n                 gsl::zstring<NI_MAXHOST> name,\r\n                 gsl::zstring<NI_MAXSERV> serv) noexcept;\r\n\r\n#endif // COROUTINE_NET_IO_H", "meta": {"hexsha": "788434b39025d0e98bed6d89809e40e4d8a87268", "size": 7161, "ext": "h", "lang": "C", "max_stars_repo_path": "interface/coroutine/net.h", "max_stars_repo_name": "eddeighton/coroutine", "max_stars_repo_head_hexsha": "5082bc1ff710dcd17b3b4fb1b8cdfc1b3a1828a4", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "interface/coroutine/net.h", "max_issues_repo_name": "eddeighton/coroutine", "max_issues_repo_head_hexsha": "5082bc1ff710dcd17b3b4fb1b8cdfc1b3a1828a4", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "interface/coroutine/net.h", "max_forks_repo_name": "eddeighton/coroutine", "max_forks_repo_head_hexsha": "5082bc1ff710dcd17b3b4fb1b8cdfc1b3a1828a4", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-16T09:09:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-16T09:09:16.000Z", "avg_line_length": 27.125, "max_line_length": 79, "alphanum_fraction": 0.6298003072, "num_tokens": 1697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.061875982263751246, "lm_q2_score": 0.04336580355478455, "lm_q1q2_score": 0.0026833016916091696}}
{"text": "/* $Id$      */\n/*--------------------------------------------------------------------*/\n/*;  Copyright (C) 2012-2018                                          */\n/*;  Associated Universities, Inc. Washington DC, USA.                */\n/*;                                                                   */\n/*;  This program is free software; you can redistribute it and/or    */\n/*;  modify it under the terms of the GNU General Public License as   */\n/*;  published by the Free Software Foundation; either version 2 of   */\n/*;  the License, or (at your option) any later version.              */\n/*;                                                                   */\n/*;  This program is distributed in the hope that it will be useful,  */\n/*;  but WITHOUT ANY WARRANTY; without even the implied warranty of   */\n/*;  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the    */\n/*;  GNU General Public License for more details.                     */\n/*;                                                                   */\n/*;  You should have received a copy of the GNU General Public        */\n/*;  License along with this program; if not, write to the Free       */\n/*;  Software Foundation, Inc., 675 Massachusetts Ave, Cambridge,     */\n/*;  MA 02139, USA.                                                   */\n/*;                                                                   */\n/*;Correspondence about this software should be addressed as follows: */\n/*;         Internet email: bcotton@nrao.edu.                         */\n/*;         Postal address: William Cotton                            */\n/*;                         National Radio Astronomy Observatory      */\n/*;                         520 Edgemont Road                         */\n/*;                         Charlottesville, VA 22903-2475 USA        */\n/*--------------------------------------------------------------------*/\n\n#include \"ObitPolnCalFit.h\"\n#include \"ObitSpectrumFit.h\"\n#include \"ObitThread.h\"\n#include \"ObitTableAN.h\"\n#include \"ObitTableANUtil.h\"\n#include \"ObitTableSU.h\"\n#include \"ObitTableSUUtil.h\"\n#include \"ObitPrecess.h\"\n#ifdef HAVE_GSL\n#include <gsl/gsl_blas.h>\n#endif /* HAVE_GSL */ \n#ifndef VELIGHT\n#define VELIGHT 2.997924562e8\n#endif\n/*----------------Obit: Merx mollis mortibus nuper ------------------*/\n/**\n * \\file ObitPolnCalFit.c\n * ObitPolnCalFit class function definitions.\n * This class is derived from the Obit base class.\n */\n\n/** name of the class defined in this file */\nstatic gchar *myClassName = \"ObitPolnCalFit\";\n\n/** Function to obtain parent ClassInfo */\nstatic ObitGetClassFP ObitParentGetClass = ObitGetClass;\n\n/**\n * ClassInfo structure ObitPolnCalFitClassInfo.\n * This structure is used by class objects to access class functions.\n */\nstatic ObitPolnCalFitClassInfo myClassInfo = {FALSE};\n\n/*--------------- File Global Variables  ----------------*/\n\n\n/*---------------Private function prototypes----------------*/\n/** Private: Initialize newly instantiated object. */\nvoid  ObitPolnCalFitInit  (gpointer in);\n\n/** Private: Deallocate members. */\nvoid  ObitPolnCalFitClear (gpointer in);\n\n/** Private: Set Class function pointers. */\nstatic void ObitPolnCalFitClassInfoDefFn (gpointer inClass);\n\n/** Private: Write output image */\nstatic void WriteOutput (ObitPolnCalFit* in, ObitUV *outUV, \n\t\t\t gboolean isOK, ObitErr *err);\n\n/** Private: Read data to thread arguments, init soln */\nstatic void  ReadData(ObitPolnCalFit *in, ObitUV *inUV, olong *iChan, \n\t\t      olong EChan, olong *iIF, olong EIF, \n\t\t      gboolean first,  ObitErr *err);\n\n/* Private: Initialize new Source poln.(CP) table */\nstatic void InitSourceTab(ObitPolnCalFit *in, ObitErr *err);\n\n/* Private: Initialize new Instrumental poln.(PD) table */\nstatic void InitInstrumentalTab(ObitPolnCalFit *in, ObitErr *err);\n\n/* Private: Initialize new Bandpass.(BP) table */\nstatic void InitBandpassTab(ObitPolnCalFit *in, ObitErr *err);\n\n/* Private: Update Source poln.(CP) table */\nstatic void UpdateSourceTab(ObitPolnCalFit *in, ObitErr *err);\n\n/* Private:  Update Instrumental poln.(PD) table */\nstatic void UpdateInstrumentalTab(ObitPolnCalFit *in, gboolean isOK, ObitErr *err);\n\n/* Private: Update Bandpass.(BP) table */\nstatic void UpdateBandpassTab(ObitPolnCalFit *in, gboolean isOK, ObitErr *err);\n\n/** Private: Fit spectra in SU list */\nstatic void FitSpectra (ObitPolnCalFit *in, ObitErr *err);\n\n/** Private: Fit data */\nstatic gboolean doFitFast(ObitPolnCalFit *in, ObitErr *err);\nstatic void doFitGSL (ObitPolnCalFit *in, ObitErr *err);\n\n/** Private: Get Chi Sq & derivatives of current model */\nstatic odouble GetChi2 (olong nThreads, ObitPolnCalFit *in, \n\t\t\tPolnParmType paramType, olong paramNumber,\n\t\t\tofloat *ParRMS, ofloat *XRMS, \n\t\t\todouble *dChi2, odouble *d2Chi2,\n\t\t\tObitErr *err);\n\n/** Private: Determine RMS residuals of current model on selected data */\nstatic void GetRMSes (olong nThreads, ObitPolnCalFit *in, olong antNumber, \n\t\t      ofloat *ParRMS, ofloat *XRMS, ObitErr *err);\n\n/** Private: Fit R/L Phase difference */\nofloat FitRLPhase (ObitPolnCalFit *in, ObitErr *err);\n\n/** Private: Make Threaded args */\nstatic void MakePolnFitFuncArgs (ObitPolnCalFit *in, ObitErr *err);\n\n/** Private: Delete Threaded args */\nstatic void KillPolnFitFuncArgs (ObitPolnCalFit *in);\n\n/** Private: Threaded Chi**2 R/L evaluator */\nstatic gpointer ThreadPolnFitRLChi2 (gpointer arg);\n\n/** Private: Threaded Chi**2 X/Y evaluator */\nstatic gpointer ThreadPolnFitXYChi2 (gpointer arg);\n\n/** Private: Check for crazy antenna solutions */\nstatic gboolean CheckCrazy(ObitPolnCalFit *in, ObitErr *err);\n\n/** Private: Check for one crazy antenna, flag */\nstatic gboolean CheckCrazyOne(ObitPolnCalFit *in, ObitErr *err);\n\n/** Private: Reset solutions */\nstatic void ResetAllSoln(ObitPolnCalFit *in);\n\n/** Private: Reset blanked solutions */\nstatic void resetSoln(ObitPolnCalFit *in);\n\n/** Private: Constrain Linear feed fits */\nstatic ofloat ConstrLinFeed (ObitPolnCalFit *in);\n\n#ifdef HAVE_GSL\n/** Private: Circular feed Solver function evaluation */\nstatic int PolnFitFuncOERL (const gsl_vector *x, void *params, \n\t\t\t    gsl_vector *f);\n\n/** Private: Circular feed Solver Jacobian evaluation */\nstatic int PolnFitJacOERL (const gsl_vector *x, void *params, \n\t\t\t   gsl_matrix *J);\n\n/** Private: Circular feed Solver function + Jacobian evaluation */\nstatic int PolnFitFuncJacOERL (const gsl_vector *x, void *params, \n\t\t\t       gsl_vector *f, gsl_matrix *J);\n\n/** Private: Linear feed Solver function evaluation */\nstatic int PolnFitFuncOEXY (const gsl_vector *x, void *params, \n\t\t\t    gsl_vector *f);\n\n/** Private: Linear feed Solver Jacobian evaluation */\nstatic int PolnFitJacOEXY (const gsl_vector *x, void *params, \n\t\t\t   gsl_matrix *J);\n\n/** Private: Linear feed Solver function + Jacobian evaluation */\nstatic int PolnFitFuncJacOEXY (const gsl_vector *x, void *params, \n\t\t\t       gsl_vector *f, gsl_matrix *J);\n\n#endif /* HAVE_GSL */ \n\n/*----------------------Public functions---------------------------*/\n/**\n * Constructor.\n * Initializes class if needed on first call.\n * \\param name An optional name for the object.\n * \\return the new object.\n */\nObitPolnCalFit* newObitPolnCalFit (gchar* name)\n{\n  ObitPolnCalFit* out;\n\n  /* Class initialization if needed */\n  if (!myClassInfo.initialized) ObitPolnCalFitClassInit();\n\n  /* allocate/init structure */\n  out = g_malloc0(sizeof(ObitPolnCalFit));\n\n  /* initialize values */\n  if (name!=NULL) out->name = g_strdup(name);\n  else out->name = g_strdup(\"Noname\");\n\n  /* set ClassInfo */\n  out->ClassInfo = (gpointer)&myClassInfo;\n\n  /* initialize other stuff */\n  ObitPolnCalFitInit((gpointer)out);\n\n return out;\n} /* end newObitPolnCalFit */\n\n/**\n * Returns ClassInfo pointer for the class.\n * \\return pointer to the class structure.\n */\ngconstpointer ObitPolnCalFitGetClass (void)\n{\n  /* Class initialization if needed */\n  if (!myClassInfo.initialized) ObitPolnCalFitClassInit();\n\n  return (gconstpointer)&myClassInfo;\n} /* end ObitPolnCalFitGetClass */\n\n/**\n * Make a deep copy of an ObitPolnCalFit.\n * NOT YET IMPLEMENTED\n * \\param in  The object to copy\n * \\param out An existing object pointer for output or NULL if none exists.\n * \\param err Obit error stack object.\n * \\return pointer to the new object.\n */\nObitPolnCalFit* ObitPolnCalFitCopy  (ObitPolnCalFit *in, ObitPolnCalFit *out, ObitErr *err)\n{\n  const ObitClassInfo *ParentClass;\n  gboolean oldExist;\n  gchar *outName;\n\n  /* error checks */\n  if (err->error) return out;\n  g_assert (ObitIsA(in, &myClassInfo));\n  if (out) g_assert (ObitIsA(out, &myClassInfo));\n\n  /* Create if it doesn't exist */\n  oldExist = out!=NULL;\n  if (!oldExist) {\n    /* derive object name */\n    outName = g_strconcat (\"Copy: \",in->name,NULL);\n    out = newObitPolnCalFit(outName);\n    g_free(outName);\n  }\n\n  /* deep copy any base class members */\n  ParentClass = myClassInfo.ParentClass;\n  g_assert ((ParentClass!=NULL) && (ParentClass->ObitCopy!=NULL));\n  ParentClass->ObitCopy (in, out, err);\n\n  /*  copy this class */\n\n  /* Arrays */\n    \n  /* reference this class members */\n  return out;\n} /* end ObitPolnCalFitCopy */\n\n/**\n * Make a copy of a object but do not copy the actual data\n * This is useful to create an PolnCalFit similar to the input one.\n * NOT YET IMPLEMENTED\n * \\param in  The object to copy\n * \\param out An existing object pointer for output, must be defined.\n * \\param err Obit error stack object.\n */\nvoid ObitPolnCalFitClone  (ObitPolnCalFit *in, ObitPolnCalFit *out, ObitErr *err)\n{\n  const ObitClassInfo *ParentClass;\n\n  /* error checks */\n  g_assert (ObitErrIsA(err));\n  if (err->error) return;\n  g_assert (ObitIsA(in, &myClassInfo));\n  g_assert (ObitIsA(out, &myClassInfo));\n\n  /* deep copy any base class members */\n  ParentClass = myClassInfo.ParentClass;\n  g_assert ((ParentClass!=NULL) && (ParentClass->ObitCopy!=NULL));\n  ParentClass->ObitCopy (in, out, err);\n\n  /*  copy this class */\n  \n  /* Arrays */\n\n  /* reference this class members */\n} /* end ObitPolnCalFitClone */\n\n/**\n * Creates an ObitPolnCalFit \n * \\param name   An optional name for the object.\n * \\return the new object.\n */\nObitPolnCalFit* ObitPolnCalFitCreate (gchar* name)\n{\n  ObitPolnCalFit* out;\n\n  /* Create basic structure */\n  out = newObitPolnCalFit (name);\n\n  return out;\n} /* end ObitPolnCalFitCreate */\n\n/**\n * Calculate circular feed model using a thread argument\n * \\param args   argument\n * \\param Rarray output array\n * \\param idata  0-rel data number\n */\nstatic void calcmodelRL (ObitPolnCalFit *args, ofloat Rarray[8], olong idata)\n{\n  odouble    *antParm   = args->antParm;\n  odouble    *souParm   = args->souParm;\n  ofloat     *data      = args->inData;\n  dcomplex   *RS        = args->RS;\n  dcomplex   *RD        = args->RD;\n  dcomplex   *LS        = args->LS;\n  dcomplex   *LD        = args->LD;\n  dcomplex   *RSc       = args->RSc;\n  dcomplex   *RDc       = args->RDc;\n  dcomplex   *LSc       = args->LSc;\n  dcomplex   *LDc       = args->LDc;\n\n  odouble ipol=0.0, qpol=0.0, upol=0.0, vpol=0.0;\n  ofloat  PD;\n  olong i, ia1, ia2, isou;\n\n  dcomplex PRref, PLref, PPRL, PPLR, PA1, PA2, PA1c, PA2c, ct1, ct2;\n  dcomplex S[4], VRR, VRL, VLR, VLL, MC1, MC2, MC3, MC4;\n  ofloat root2, chi1, chi2;\n\n  /* R-L phase difference  at reference antenna */\n  PD = args->PD;\n\n  COMPLEX_SET (MC1, 0.0, 0.0);  /* Other stuff */\n  COMPLEX_SET (MC2, 0.0, 0.0);\n  COMPLEX_SET (MC3, 0.0, 0.0);\n  COMPLEX_SET (MC4, 0.0, 0.0);\n  chi1  = data[idata*10+0];   /* parallactic angle ant 1 */\n  chi2  = data[idata*10+1];   /* parallactic angle ant 2 */\n  COMPLEX_EXP (PA1, 2*chi1);\n  COMPLEX_EXP (PA2, 2*chi2);\n  COMPLEX_CONJUGATE (PA1c, PA1);\n  COMPLEX_CONJUGATE (PA2c, PA2);\n  \n  isou  = MAX (0, args->souNo[idata]);    /* Source number */\n  \n  /* Source parameters */\n  ipol = souParm[isou*4+0];\n  qpol = souParm[isou*4+1];\n  upol = souParm[isou*4+2];\n  vpol = souParm[isou*4+3];\n  /* Complex Stokes array */\n  COMPLEX_SET (S[0], ipol+vpol, 0.0);\n  COMPLEX_SET (S[1], qpol,  upol);\n  COMPLEX_SET (S[2], qpol, -upol);\n  COMPLEX_SET (S[3], ipol-vpol, 0.0);\n  \n  /* Injest model factorize into antenna components - \n     data in order Orientation R/X, Elipticity R/X, Orientation L/Y, Elipticity L/Y*/\n  root2 = 1.0 / sqrt(2.0);\n  /* Elipticity, Orientation terms */\n  for (i=0; i<args->nant; i++) {\n    COMPLEX_SET(RS[i], root2*(cos(antParm[i*4+1]) + sin(antParm[i*4+1])), 0);\n    COMPLEX_SET(ct1,   root2*(cos(antParm[i*4+1]) - sin(antParm[i*4+1])), 0);\n    COMPLEX_EXP(ct2, 2*antParm[i*4+0]);\n    COMPLEX_MUL2 (RD[i], ct1, ct2);\n    COMPLEX_SET (ct1, root2*(cos(antParm[i*4+3]) + sin(antParm[i*4+3])), 0);\n    COMPLEX_EXP (ct2, -2*antParm[i*4+2]);\n    COMPLEX_MUL2 (LS[i], ct1, ct2);\n    COMPLEX_SET (LD[i], root2*(cos(antParm[i*4+3]) - sin(antParm[i*4+3])), 0);\n    COMPLEX_CONJUGATE (RSc[i], RS[i]);\n    COMPLEX_CONJUGATE (RDc[i], RD[i]);\n    COMPLEX_CONJUGATE (LSc[i], LS[i]);\n    COMPLEX_CONJUGATE (LDc[i], LD[i]);\n  }\n\n  /* Reference antenna phase terms */\n  if (args->refAnt>0) {\n    COMPLEX_EXP (PRref,  antParm[(args->refAnt-1)*4+0]);\n    COMPLEX_EXP (PLref, -antParm[(args->refAnt-1)*4+2]+PD);\n  } else {\n    COMPLEX_SET(PRref, 1.0, 0.0);\n    COMPLEX_EXP (PLref, PD);\n  }\n  COMPLEX_CONJUGATE (ct1, PLref);\n  COMPLEX_MUL2 (PPRL, PRref, ct1);\n  COMPLEX_CONJUGATE (ct1, PRref);\n  COMPLEX_MUL2 (PPLR, PLref, ct1);\n  \n  ia1    = args->antNo[idata*2+0];\n  ia2    = args->antNo[idata*2+1]; \n  \n  /* VRR = S[0] * RS[ia1] * RSc[ia2] +        \n           S[1] * RS[ia1] * RDc[ia2] * PA2c + \n\t   S[2] * RD[ia1] * RSc[ia2] * PA1  + \n\t   S[3] * RD[ia1] * RDc[ia2] * PA1  * PA2c; */\n  COMPLEX_MUL2 (MC1, RS[ia1], RSc[ia2]);\n  COMPLEX_MUL2 (VRR, S[0], MC1);\n  COMPLEX_MUL3 (MC2, RS[ia1], RDc[ia2],  PA2c);\n  COMPLEX_MUL2 (ct1, S[1], MC2);\n  COMPLEX_ADD2 (VRR, VRR,  ct1);\n  COMPLEX_MUL3 (MC3, RD[ia1], RSc[ia2], PA1);\n  COMPLEX_MUL2 (ct1, S[2], MC3);\n  COMPLEX_ADD2 (VRR, VRR,  ct1);\n  COMPLEX_MUL4 (MC4, RD[ia1], RDc[ia2], PA1, PA2c);\n  COMPLEX_MUL2 (ct1, S[3], MC4);\n  COMPLEX_ADD2 (VRR, VRR,  ct1);\n  Rarray[0] = VRR.real;\n  Rarray[1] = VRR.imag;\n\n  /* VLL = S[0] * LS[ia1] * LSc[ia2] * PA1c * PA2 +\t\n           S[1] * LS[ia1] * LDc[ia2] * PA1c +\n\t   S[2] * LD[ia1] * LSc[ia2] * PA2  +\n\t   S[3] * LD[ia1] * LDc[ia2]; */\n  COMPLEX_MUL4 (MC1, LS[ia1], LSc[ia2], PA1c, PA2);\n  COMPLEX_MUL2 (VLL, S[0], MC1);\n  COMPLEX_MUL3 (MC2, LS[ia1], LDc[ia2], PA1c);\n  COMPLEX_MUL2 (ct1, S[1], MC2);\n  COMPLEX_ADD2 (VLL, VLL,  ct1);\n  COMPLEX_MUL3 (MC3, LD[ia1], LSc[ia2], PA2);\n  COMPLEX_MUL2 (ct1, S[2], MC3);\n  COMPLEX_ADD2 (VLL, VLL,  ct1);\n  COMPLEX_MUL2 (MC4, LD[ia1], LDc[ia2]);\n  COMPLEX_MUL2 (ct1, S[3], MC4);\n  COMPLEX_ADD2 (VLL, VLL,  ct1);\n  Rarray[6] = VLL.real;\n  Rarray[7] = VLL.imag;\n\n  /* \t    RL */\n  /* VRL = PPRL * S[0] * RS[ia1] * LSc[ia2] * PA2 +\n           PPRL * S[1] * RS[ia1] * LDc[ia2] + \n\t   PPRL * S[2] * RD[ia1] * LSc[ia2] * PA1 * PA2 +\n\t   PPRL * S[3] * RD[ia1] * LDc[ia2] * PA1; */\n  COMPLEX_MUL4 (MC1, PPRL, RS[ia1], LSc[ia2], PA2);\n  COMPLEX_MUL2 (VRL, S[0], MC1);\n  COMPLEX_MUL3 (MC2, PPRL, RS[ia1], LDc[ia2]);\n  COMPLEX_MUL2 (ct1, S[1], MC2);\n  COMPLEX_ADD2 (VRL, VRL,  ct1);\n  COMPLEX_MUL5 (MC3, PPRL, RD[ia1], LSc[ia2],  PA1,  PA2);\n  COMPLEX_MUL2 (ct1, S[2], MC3);\n  COMPLEX_ADD2 (VRL, VRL,  ct1);\n  COMPLEX_MUL4 (MC4, PPRL, RD[ia1], LDc[ia2],  PA1);\n  COMPLEX_MUL2 (ct1, S[3], MC4);\n  COMPLEX_ADD2 (VRL, VRL,  ct1);\n  Rarray[2] = VRL.real;\n  Rarray[3] = VRL.imag;\n\n  /*        LR */\n  /* VLR = PPLR * S[0] * LS[ia1] * RSc[ia2] * PA1c +\n           PPLR * S[1] * LS[ia1] * RDc[ia2] * PA1c * PA2c +\n\t   PPLR * S[2] * LD[ia1] * RSc[ia2] +\n\t   PPLR * S[3] * LD[ia1] * RDc[ia2] * PA2c */\n  COMPLEX_MUL4 (MC1, PPLR, LS[ia1], RSc[ia2], PA1c);\n  COMPLEX_MUL2 (VLR, S[0], MC1);\n  COMPLEX_MUL5 (MC2, PPLR, LS[ia1], RDc[ia2], PA1c,  PA2c);\n  COMPLEX_MUL2 (ct1, S[1], MC2);\n  COMPLEX_ADD2 (VLR, VLR,  ct1);\n  COMPLEX_MUL3 (MC3, PPLR, LD[ia1], RSc[ia2]);\n  COMPLEX_MUL2 (ct1, S[2], MC3);\n  COMPLEX_ADD2 (VLR, VLR,  ct1);\n  COMPLEX_MUL4 (MC4, PPLR, LD[ia1], RDc[ia2],  PA2c);\n  COMPLEX_MUL2 (ct1, S[3], MC4);\n  COMPLEX_ADD2 (VLR, VLR, ct1);\n  Rarray[4] = VLR.real;\n  Rarray[5] = VLR.imag;\n} /* end calcmodelRL */\n\n/**\n * Calculate linear feed model using a thread argument\n * R Perley version\n * \\param args   argument\n * \\param Rarray output array\n * \\param idata  0-rel data number\n */\nstatic void calcmodelXY (ObitPolnCalFit *args, ofloat Rarray[8], olong idata)\n{\n  odouble    *antParm   = args->antParm;\n  odouble    *antGain   = args->antGain;\n  odouble    *souParm   = args->souParm;\n  ofloat     *data      = args->inData;\n  dcomplex   *CX        = args->RS;\n  dcomplex   *SX        = args->RD;\n  dcomplex   *CY        = args->LS;\n  dcomplex   *SY        = args->LD;\n  dcomplex   *CXc       = args->RSc;\n  dcomplex   *SXc       = args->RDc;\n  dcomplex   *CYc       = args->LSc;\n  dcomplex   *SYc       = args->LDc;\n\n  odouble ipol=0.0, qpol=0.0, upol=0.0, vpol=0.0;\n  olong i, ia1, ia2, isou;\n\n  dcomplex SPA, DPA, SPAc, DPAc, ct1, ct2, ct3;\n  dcomplex S[4], S0[4], VXX, VXY, VYX, VYY, MC1, MC2, MC3, MC4;\n  dcomplex SM1, SM2, SM3, SM4, ggPD;\n  ofloat chi1, chi2, PD;\n\n  /* Init working variables */\n  COMPLEX_SET (MC1, 0.0, 0.0);  /* Muller matrix */\n  COMPLEX_SET (MC2, 0.0, 0.0);\n  COMPLEX_SET (MC3, 0.0, 0.0);\n  COMPLEX_SET (MC4, 0.0, 0.0);\n  chi1  = data[idata*10+0];   /* parallactic angle ant 1 */\n  chi2  = data[idata*10+1];   /* parallactic angle ant 2 */\n  COMPLEX_EXP (SPA,(chi1+chi2));\n  COMPLEX_EXP (DPA,chi1-chi2);\n  COMPLEX_CONJUGATE (SPAc, SPA);\n  COMPLEX_CONJUGATE (DPAc, DPA);\n  \n  isou  = MAX (0, args->souNo[idata]);    /* Source number */\n  \n   /* X-Y phase difference  at reference antenna */\n  PD = args->PD;\n\n /* Source parameters */\n  ipol = souParm[isou*4+0];\n  qpol = souParm[isou*4+1];\n  upol = souParm[isou*4+2];\n  vpol = souParm[isou*4+3];\n  /* Complex Stokes array  */\n  COMPLEX_SET (S0[0], ipol+vpol, 0.0);\n  COMPLEX_SET (S0[1], qpol,  upol);\n  COMPLEX_SET (S0[2], qpol, -upol);\n  COMPLEX_SET (S0[3], ipol-vpol, 0.0);\n\n  /* Rotate Stokes by parallactic angle */\n  COMPLEX_MUL2(S[0], DPAc, S0[0]);\n  COMPLEX_MUL2(S[1], SPAc, S0[1]);\n  COMPLEX_MUL2(S[2], SPA,  S0[2]);\n  COMPLEX_MUL2(S[3], DPA,  S0[3]);\n\n   /* Injest model factorize into antenna components - \n     data in order 0: Orientation X, 1: Elipticity X, 2: Orientation Y, 3: Elipticity Y */\n  /* Elipticity, Orientation terms */\n  for (i=0; i<args->nant; i++) {\n    COMPLEX_EXP (ct1, -antParm[i*4+0]);\n    COMPLEX_SET (ct2, cos(G_PI*0.25+antParm[i*4+1]), 0.0);\n    COMPLEX_MUL2 (CX[i], ct2, ct1);\n    COMPLEX_EXP (ct1, antParm[i*4+0]);\n    COMPLEX_SET (ct2, sin(G_PI*0.25+antParm[i*4+1]), 0.0);\n    COMPLEX_MUL2 (SX[i], ct2, ct1);\n    COMPLEX_EXP (ct1, antParm[i*4+2]);\n    COMPLEX_SET (ct2, cos(G_PI*0.25-antParm[i*4+3]), 0.0);\n    COMPLEX_MUL2 (CY[i], ct2, ct1);\n    COMPLEX_EXP (ct1, -antParm[i*4+2]);\n    COMPLEX_SET (ct2, sin(G_PI*0.25-antParm[i*4+3]), 0.0);\n    COMPLEX_MUL2 (SY[i], ct2, ct1);\n    COMPLEX_CONJUGATE (CXc[i], CX[i]);\n    COMPLEX_CONJUGATE (SXc[i], SX[i]);\n    COMPLEX_CONJUGATE (CYc[i], CY[i]);\n    COMPLEX_CONJUGATE (SYc[i], SY[i]);\n  }\n\n  ia1    = args->antNo[idata*2+0];\n  ia2    = args->antNo[idata*2+1]; \n  \n  /* VXX = {S[0] * CX[ia1] * CXc[ia2]c  +\n            S[1] * CX[ia1] * SXc[ia2]c  +\n\t    S[2] * SX[ia1] * CXc[ia2]   + \n\t    S[3] * SX[ia1] * SXc[ia2]} * g1X * g2X ;\n  */\n  COMPLEX_MUL2 (MC1, CX[ia1], CXc[ia2]);\n  COMPLEX_MUL2 (MC2, CX[ia1], SXc[ia2]);\n  COMPLEX_MUL2 (MC3, SX[ia1], CXc[ia2]);\n  COMPLEX_MUL2 (MC4, SX[ia1], SXc[ia2]);\n  COMPLEX_MUL2 (VXX, S[0], MC1);\n  COMPLEX_MUL2 (ct1, S[1], MC2);\n  COMPLEX_ADD2 (VXX, VXX,  ct1);\n  COMPLEX_MUL2 (ct1, S[2], MC3);\n  COMPLEX_ADD2 (VXX, VXX,  ct1);\n  COMPLEX_MUL2 (ct1, S[3], MC4);\n  COMPLEX_ADD2 (ct3, VXX,  ct1);\n  COMPLEX_SET (ct1,  antGain[ia1*2+0]*antGain[ia2*2+0], 0);\n  COMPLEX_MUL2 (VXX, ct3, ct1);\n  Rarray[0] = VXX.real;\n  Rarray[1] = VXX.imag;\n\n  /* VYY = {S[0] * SY[ia1] * SYc[ia2] +       \n            S[1] * SY[ia1] * CYc[ia2] +\n\t    S[2] * CY[ia1] * SYc[ia2]  + \n\t    S[3] * CY[ia1] * CYc[ia2]} * g1Y * g2Y ;\n  */\n  COMPLEX_MUL2 (MC1, SY[ia1], SYc[ia2]);\n  COMPLEX_MUL2 (MC2, SY[ia1], CYc[ia2]);\n  COMPLEX_MUL2 (MC3, CY[ia1], SYc[ia2]);\n  COMPLEX_MUL2 (MC4, CY[ia1], CYc[ia2]);\n  COMPLEX_MUL2 (VYY, S[0], MC1);\n  COMPLEX_MUL2 (ct1, S[1], MC2);\n  COMPLEX_ADD2 (VYY, VYY,  ct1);\n  COMPLEX_MUL2 (ct1, S[2], MC3);\n  COMPLEX_ADD2 (VYY, VYY,  ct1);\n  COMPLEX_MUL2 (ct1, S[3], MC4);\n  COMPLEX_ADD2 (ct3, VYY,  ct1);\n  COMPLEX_SET (ct1,  antGain[ia1*2+1]*antGain[ia2*2+1], 0);\n  COMPLEX_MUL2 (VYY, ct3, ct1);\n  Rarray[6] = VYY.real;\n  Rarray[7] = VYY.imag;\n\n  /* VXY = {S[0] * CX[ia1] * SYc[ia2] +       \n            S[1] * CX[ia1] * CYc[ia2] +\n\t    S[2] * SX[ia1] * SYc[ia2] + \n\t    S[3] * SX[ia1] * CYc[ia2]}} * g1X * g2Y * exp(i PD);\n  */\n  COMPLEX_MUL2 (MC1, CX[ia1], SYc[ia2]);\n  COMPLEX_MUL2 (MC2, CX[ia1], CYc[ia2]);\n  COMPLEX_MUL2 (MC3, SX[ia1], SYc[ia2]);\n  COMPLEX_MUL2 (MC4, SX[ia1], CYc[ia2]);\n  COMPLEX_MUL2 (SM1, S[0], MC1);\n  COMPLEX_MUL2 (SM2, S[1], MC2);\n  COMPLEX_MUL2 (SM3, S[2], MC3);\n  COMPLEX_MUL2 (SM4, S[3], MC4);\n  COMPLEX_ADD4 (ct3, SM1, SM2, SM3, SM4);\n  COMPLEX_SET (ct1, antGain[ia1*2+0]*antGain[ia2*2+1], 0);\n  COMPLEX_EXP (ct2, PD);\n  COMPLEX_MUL2 (ggPD, ct1, ct2);\n  COMPLEX_MUL2 (VXY, ct3, ggPD);\n  Rarray[2] = VXY.real;\n  Rarray[3] = VXY.imag;\n\n  /* VYX = {S[0] * SY[ia1] * CXc[ia2] +       \n            S[1] * SY[ia1] * SXc[ia2] +\n\t    S[2] * CY[ia1] * CXc[ia2] + \n\t    S[3] * CY[ia1] * SXc[ia2]} * g1Y * g2X * exp(-i PD);\n  */\n  COMPLEX_MUL2 (MC1, SY[ia1], CXc[ia2]);\n  COMPLEX_MUL2 (MC2, SY[ia1], SXc[ia2]);\n  COMPLEX_MUL2 (MC3, CY[ia1], CXc[ia2]);\n  COMPLEX_MUL2 (MC4, CY[ia1], SXc[ia2]);\n  COMPLEX_MUL2 (SM1, S[0], MC1);\n  COMPLEX_MUL2 (SM2, S[1], MC2);\n  COMPLEX_MUL2 (SM3, S[2], MC3);\n  COMPLEX_MUL2 (SM4, S[3], MC4);\n  COMPLEX_ADD4 (ct3, SM1, SM2, SM3, SM4);\n  COMPLEX_SET (ct1,  antGain[ia1*2+1]*antGain[ia2*2+0], 0);\n  COMPLEX_EXP (ct2, -PD);\n  COMPLEX_MUL2 (ggPD, ct1, ct2);\n  COMPLEX_MUL2 (VYX, ct3, ggPD);\n  Rarray[4] = VYX.real;\n  Rarray[5] = VYX.imag;\n} /* end calcmodelXY */\n\n/**\n * Fit selected parameters to a UV data.\n * \\param in       Spectral fitting object\n *                 Potential parameters on in->info:\n * \\li nCal       OBIT_int scalar Number of calibrator sources [1]\n * \\li solnType   OBIT_string [4] Solution type:'FULD'\n * \\li Sources    OBIT_string [16,*] Calibrator sources \n * \\li Qual       OBIT_long scalar Source qualifier -1=>any\n * \\li souCode    OBIT_string [4] Calibrator code '    '=>any\n * \\li doFitI     OBIT_boolean [*] If True fit Stokes I poln, per cal [F]\n * \\li doFitPol   OBIT_boolean [*] If True fit source linear poln, per cal  [T]\n * \\li doFitV     OBIT_boolean [*] If True fit Stokes V poln, per cal  [F]\n * \\li doFitRL    OBIT_boolean  If True fit R-L phase difference  [F]\n * \\li XYPhase    OBIT_float scalar cross hand phase difference  (deg) [def 0.0]\n * \\li RLPhase    OBIT_float scalar R-L phase difference @ ref Freq per calibrator\n *                <= -999 => fit value [-1000.] in deg.\n * \\li RM         OBIT_float scalar Rotation measure (rad/m^2) to be used with RLPhase\n * \\li PPol       OBIT_float scalar Fractional linear polarization per calibrator\n * \\li dPPol      OBIT_float scalar freq derivative of PPol (GHz) per calibrator\n * \\li ChWid      OBIT_long scalar Number of channels in poln soln  [1]\n * \\li ChInc      OBIT_long scalar  Spacing of poln soln  [1]\n * \\li CPSoln     OBIT_long scalar Source (CP) table to write, 0=> create new  [0]\n * \\li PDSoln     OBIT_long scalar Instrumental (PD) table to write, 0=> create new  [0]\n * \\li BPSoln     OBIT_long scalar Bandpass (BP) table to write, 0=> create new  [0]\n * \\li doBlank    OBIT_boolean scalar If True blanked failed solns, else default values [T]\n * \\li doBand     OBIT_long scalar If >0 then BP table BPVer was applied to input  [0]\n * \\li BPVer      OBIT_long scalar Input BP table  [0]\n * \\li refAnt     OBIT_long scalar Reference antenna  [0-> none, def 1]\n * \\li BIF        OBIT_long scalar First IF (1-rel) selected in outUV  [1]\n * \\li BChan      OBIT_long scalar First channel (1-rel) selected in outUV  [1]\n * \\param inUV  Averaged/calibrated/divided UV data to be fitted\n *              Should be averaged to the solInt time.\n *              MUST be a multisource file\n * \\param outUV UV data with fitted results in tables\n * \\param err      Obit error stack object.\n */\nvoid ObitPolnCalFitFit (ObitPolnCalFit* in, ObitUV *inUV, \n\t\t\tObitUV *outUV, ObitErr *err)\n{\n  olong nCal=1;\n  ObitIOCode retCode;\n  gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1}, sdim[MAXINFOELEMDIM];\n  ObitInfoType type;\n  ObitTableAN    *ANTable = NULL;\n  ObitTableSU    *SUTable = NULL;\n  olong i, j, k, iant, isou, numAnt, BChan, EChan, iChan, EIF, iIF;\n  olong first, highANver, iANver, ver, numIF, Qual, suba=1, nvis;\n  olong highSUver, size, oldNparam, oldNdata, iarr[5]={0,0,0,0,0};\n  ofloat *farr;\n  olong number, maxSUId=-1;\n  gboolean done, xselect=TRUE, *barr, isOK;\n  gchar solnType[5], *Sources, souCode[5];\n  ofloat  endChi2, ParRMS, XRMS;\n#ifdef HAVE_GSL\n  const gsl_multifit_fdfsolver_type *T=NULL;\n#endif /* HAVE_GSL */ \n  /* Diagnostics */\n  ofloat ftemp, RArray[8];\n  odouble RRr, RRi, LLr, LLi, RLr, RLi, LRr, LRi;\n  olong ia1, ia2, refAnt;\n  gchar *routine = \"ObitPolnCalFitFit\";\n\n  /* error checks */\n  if (err->error) return;\n  g_assert (ObitIsA(in, &myClassInfo));\n  g_assert(ObitUVIsA(inUV));\n  g_assert(ObitUVIsA(outUV));\n\n  /* How many calibrators? */\n  ObitInfoListGetTest(in->info, \"nCal\", &type, dim, &nCal);\n\n  /* Allocate calibrator arrays */\n  in->RLPhaseIn= g_malloc0(nCal*sizeof(ofloat));\n  in->RLPhase  = g_malloc0(nCal*sizeof(ofloat));\n  in->RM       = g_malloc0(nCal*sizeof(ofloat));\n  in->PPol     = g_malloc0(nCal*sizeof(ofloat));\n  in->dPPol    = g_malloc0(nCal*sizeof(ofloat));\n  in->doFitI   = g_malloc0(nCal*sizeof(olong));\n  in->doFitV   = g_malloc0(nCal*sizeof(olong));\n  in->doFitPol = g_malloc0(nCal*sizeof(olong));\n  in->IFlux0   = g_malloc0(nCal*sizeof(ofloat));\n  in->IFlux1   = g_malloc0(nCal*sizeof(ofloat));\n  in->IFlux2   = g_malloc0(nCal*sizeof(ofloat));\n\n  /* Control parameters - arrays may be defined larger than nCal */\n  if (ObitInfoListGetP(in->info, \"RLPhase\", &type, dim, (gpointer)&farr))\n    for (i=0; i<nCal; i++) in->RLPhaseIn[i] = farr[i] * DG2RAD;\n  else\n    for (i=0; i<nCal; i++) in->RLPhaseIn[i] =- 1000.0;\n  if (ObitInfoListGetP(in->info, \"RM\", &type, dim, (gpointer)&farr))\n    for (i=0; i<nCal; i++) in->RM[i] = farr[i];\n  else\n    for (i=0; i<nCal; i++)  in->RM[i] = 0.0;\n  if (ObitInfoListGetP(in->info, \"PPol\", &type, dim, (gpointer)&farr))\n    for (i=0; i<nCal; i++) in->PPol[i] = farr[i];\n  else\n    for (i=0; i<nCal; i++)  in->PPol[i] = 0.0;\n  if (ObitInfoListGetP(in->info, \"dPPol\", &type, dim, (gpointer)&farr))\n    for (i=0; i<nCal; i++) in->dPPol[i] = farr[i]*1.0e-9;  /* delta freq  to GHz */\n  else\n    for (i=0; i<nCal; i++)  in->dPPol[i] = 0.0;\n  if (ObitInfoListGetP(in->info, \"doFitI\", &type, dim, (gpointer)&barr))\n    for (i=0; i<nCal; i++) in->doFitI[i] = barr[i];\n  else\n    for (i=0; i<nCal; i++) in->doFitI[i] = FALSE;\n  if (ObitInfoListGetP(in->info, \"doFitV\", &type, dim, (gpointer)&barr))\n    for (i=0; i<nCal; i++) in->doFitV[i] = barr[i];\n  else\n    for (i=0; i<nCal; i++) in->doFitV[i] = FALSE;\n  if (ObitInfoListGetP(in->info, \"doFitPol\", &type, dim, (gpointer)&barr))\n    for (i=0; i<nCal; i++) in->doFitPol[i] = barr[i];\n  else\n    for (i=0; i<nCal; i++) in->doFitPol[i] = TRUE;\n  ObitInfoListGetTest(in->info, \"doFitRL\",  &type, dim, &in->doFitRL);\n  ObitInfoListGetTest(in->info, \"doBlank\",  &type, dim, &in->doBlank);\n  ObitInfoListGetTest(in->info, \"doFitGain\",&type, dim, &in->doFitGain);\n  ObitInfoListGetTest(in->info, \"doFitOri\", &type, dim, &in->doFitOri);\n  ObitInfoListGetTest(in->info, \"ChWid\",    &type, dim, &in->ChWid);\n  ObitInfoListGetTest(in->info, \"ChInc\",    &type, dim, &in->ChInc);\n  ObitInfoListGetTest(in->info, \"CPSoln\",   &type, dim, &in->CPSoln);\n  ObitInfoListGetTest(in->info, \"PDSoln\",   &type, dim, &in->PDSoln);\n  ObitInfoListGetTest(in->info, \"BPSoln\",   &type, dim, &in->BPSoln);\n  ObitInfoListGetTest(in->info, \"doBand\",   &type, dim, &in->doBand);\n  ObitInfoListGetTest(in->info, \"BPVer\",    &type, dim, &in->BPVer);\n  ObitInfoListGetTest(in->info, \"BIF\",      &type, dim, &in->BIF);\n  in->BIF = MAX (1, in->BIF);\n  ObitInfoListGetTest(in->info, \"BChan\",    &type, dim, &in->BChan);\n  in->BChan = MAX (1, in->BChan);\n  ObitInfoListGetTest(in->info, \"refAnt\",   &type, dim, &in->refAnt);\n  ObitInfoListGetTest(in->info, \"prtLv\",    &type, dim, &in->prtLv);\n  ObitInfoListGetTest(in->info, \"Qual\",     &type, dim, &Qual);\n  ObitInfoListGetTest(in->info, \"souCode\",  &type, dim, souCode);\n  strcpy (solnType, \"LM  \");\n  ObitInfoListGetTest(in->info, \"solnType\", &type, dim, solnType);\n  strncpy (in->solnType, solnType, 4);\n  ObitInfoListGetP(in->info, \"Sources\", &type, sdim, (gpointer)&Sources);\n  ftemp = 0.0;\n  ObitInfoListGetTest(in->info, \"XPhase\",   &type, dim, &ftemp);\n  in->PD = ftemp * DG2RAD;   /* Phase difference in radians */\n\n  /* Open input data to get info */\n  retCode = ObitUVOpen (inUV, OBIT_IO_ReadOnly, err);\n  /* if it didn't work bail out */\n  if ((retCode!=OBIT_IO_OK) || (err->error)) \n    Obit_traceback_msg (err, routine, inUV->name);\n\n  /* Save in/output descriptor */\n  in->inDesc  = ObitUVDescRef(inUV->myDesc);\n  in->outDesc = ObitUVDescRef(outUV->myDesc);\n\n  /* Is this circular (linear) feed data? */\n  in->isCircFeed = \n    (in->outDesc->crval[in->outDesc->jlocs]<0.0) && \n    (in->outDesc->crval[in->outDesc->jlocs]>-1.5);\n\n  /* Gain fitting only for linear feeeds */\n  if (in->isCircFeed) in->doFitGain = FALSE;\n  /* Orientation fitting required for circular Feeds */\n  if (in->isCircFeed) in->doFitGain = TRUE;\n\n  /* Number of antennas */\n  numAnt  = inUV->myDesc->numAnt[suba-1];/* actually highest antenna number */\n  in->nant = numAnt;\n  in->nsou = nCal;\n\n  /* How many AN tables (subarrays) */\n  highANver = ObitTableListGetHigh (inUV->tableList, \"AIPS AN\");\n  \n  /* Antenna lists */\n  in->AntLists = g_malloc0(highANver*sizeof(ObitAntennaList*));\n  in->numSubA  = highANver;\n /* Read Info from AN tables  */\n  for (i=0; i<highANver; i++) {\n    iANver = i+1;\n    /* Get table */\n    ANTable = newObitTableANValue (inUV->name, (ObitData*)inUV, &iANver, \n\t\t\t\t   OBIT_IO_ReadOnly, 0, 0, 0, err);\n    if (err->error) Obit_traceback_msg (err, routine, inUV->name);\n    \n    in->AntLists[i] = ObitTableANGetList (ANTable, err);\n    if (err->error) Obit_traceback_msg (err, routine, inUV->name);\n\n    /* release table object */\n    ANTable = ObitTableANUnref(ANTable);\n  } /* End loop over subarrays */\n\n  /* Allocate source lookup table */\n  in->souIDs = g_malloc0(in->nsou*sizeof(olong));\n\n  /* Convert SU table into Source List if there is an SU table */\n  highSUver = ObitTableListGetHigh (outUV->tableList, \"AIPS SU\");\n  if (highSUver>0) {\n    ver   = 1;\n    numIF = 0;\n    SUTable = newObitTableSUValue (outUV->name, (ObitData*)outUV, &ver, numIF, \n\t\t\t\t   OBIT_IO_ReadOnly, err);\n    if (SUTable) in->SouList = ObitTableSUGetList (SUTable, err);\n    /* Look up source IDs - one at a time to get correct order */\n    number = 1; sdim[1] = 1;\n    for (i=0; i<in->nsou; i++) {\n      j = sdim[0]*i;\n      ObitTableSULookup (SUTable, sdim, &Sources[j], Qual, souCode, iarr, \n\t\t\t &xselect, &number, err);\n      if (err->error) Obit_traceback_msg (err, routine, inUV->name);\n      in->souIDs[i] = MAX (1, iarr[0]);\n    } /* End loop over calibrators */\n    /* Get maximum source id */\n    for (i=0; i<in->nsou; i++) maxSUId = MAX(maxSUId, in->souIDs[i]);\n    maxSUId = MAX (1, maxSUId);\n    /* Inverse lookup table */\n    in->isouIDs = g_malloc0(maxSUId*sizeof(olong));\n    for (j=0; j<maxSUId; j++)  in->isouIDs[j] = -1000;\n    for (i=0; i<in->nsou; i++) in->isouIDs[in->souIDs[i]-1] = i;\n\n    /* Fit spectra to IPol in table */\n    FitSpectra (in, err);\n    if (err->error) Obit_traceback_msg (err, routine, inUV->name);\n    SUTable = ObitTableSUUnref(SUTable);\n    \n  } else {  /* Create a single source object */\n    in->oneSource = newObitSource(\"Single\");\n    strncpy (in->oneSource->SourceName, inUV->myDesc->object, MIN(20,UVLEN_VALUE));\n    in->oneSource->equinox = inUV->myDesc->equinox;\n    in->oneSource->RAMean  = inUV->myDesc->crval[inUV->myDesc->jlocr];\n    SUTable = ObitTableSUUnref(SUTable);\n    in->oneSource->DecMean = inUV->myDesc->crval[inUV->myDesc->jlocd];\n    /* Compute apparent position */\n    ObitPrecessUVJPrecessApp (inUV->myDesc, in->oneSource);\n    in->souIDs[0] = 1;  /* Source ID */\n    /* Inverse lookup table */\n    in->isouIDs = g_malloc0(1*sizeof(olong));\n    in->isouIDs[0] = 0;\n  }\n\n  /* Allocate Fitting flag/order arrays */\n  in->gotAnt = g_malloc0(in->nant*sizeof(gboolean*));\n  in->antFit = g_malloc0(in->nant*sizeof(gboolean*));\n  for (i=0; i<in->nant; i++) in->antFit[i] = g_malloc0(4*sizeof(gboolean));\n  in->souFit = g_malloc0(in->nsou*sizeof(gboolean*));\n  for (i=0; i<in->nsou; i++) in->souFit[i] = g_malloc0(4*sizeof(gboolean));\n\n  in->antPNumb = g_malloc0(in->nant*sizeof(gboolean*));\n  for (i=0; i<in->nant; i++) in->antPNumb[i] = g_malloc0(4*sizeof(gboolean));\n  in->souPNumb = g_malloc0(in->nsou*sizeof(gboolean*));\n  for (i=0; i<in->nsou; i++) in->souPNumb[i] = g_malloc0(4*sizeof(gboolean));\n  oldNparam = 0;\n  oldNdata  = 0;\n\n  /* Parameter/error arrays */\n  in->antParm     = g_malloc0(in->nant*4*sizeof(odouble));\n  in->antErr      = g_malloc0(in->nant*4*sizeof(odouble));\n  in->souParm     = g_malloc0(in->nsou*4*sizeof(odouble));\n  in->souErr      = g_malloc0(in->nsou*4*sizeof(odouble));\n  in->lastSouParm = g_malloc0(in->nsou*4*sizeof(odouble));\n  in->souFlux     = g_malloc0(in->nsou*4*sizeof(ofloat));\n\n  /* Antenna gains for linear feeds? */\n  if (!in->isCircFeed ) {\n    in->antGain     = g_malloc0((in->nant+2)*2*sizeof(odouble));\n    for (i=0; i<in->nant*2; i++) in->antGain[i] = 1.0;\n    in->antGainErr  = g_malloc0(in->nant*2*sizeof(odouble));\n    in->antGainFit  = g_malloc0(in->nant*sizeof(gboolean*));\n    for (i=0; i<in->nant; i++) {\n      in->antGainFit[i] = g_malloc0(2*sizeof(gboolean));\n      in->antGainFit[i][0] = FALSE; /* Don't fit  Xpol gain */\n      /* in->antGainFit[i][0] = in->doFitGain;  DEBUG */\n      in->antGainFit[i][1] = in->doFitGain;\n    }\n    in->antGainPNumb = g_malloc0(in->nant*sizeof(gboolean*));\n    for (i=0; i<in->nant; i++) \n      in->antGainPNumb[i] = g_malloc0(2*sizeof(gboolean));\n\n  } /* End create feed gain arrays */\n\n  /* Fill Fitting flag arrays */\n  /* Order of antenna parameters:\n     0,1 ori, elip (r/x),\n     2,3 ori, elip  (l/y),\n   */\n  for (i=0; i<in->nant; i++) {\n    /* Initialize FALSE */\n    in->gotAnt[i] = FALSE;\n\n    /* Antenna terms */\n    for (j=0; j<4; j++) in->antFit[i][j] = TRUE;\n    /* Don't fit reference antenna terms,\n     Fix ori 1 if circ. feeds, elip 1&2 if linear feeds*/\n    if (in->isCircFeed) { /* Circular */\n      if  ((i+1)==in->refAnt) in->antFit[i][0] = FALSE;\n    } else  { /* Linear */\n      if  ((i+1)==in->refAnt) in->antFit[i][1] = FALSE;\n    }\n    /* doFitOri=False-> fix orientations */\n    if (!in->doFitOri) {\n      in->antFit[i][0] = FALSE;\n      in->antFit[i][2] = FALSE;\n    }\n } /* end filling antenna fitting flags */\n\n  /* Order of source parameters:\n     0, Stokes I,\n     1, Stokes Q,\n     2, Stokes U\n     3, Stokes V\n   */\n  for (i=0; i<in->nsou; i++) {\n    if (in->doFitI[i])    in->souFit[i][0] = TRUE;\n    else                  in->souFit[i][0] = FALSE;\n    if (in->doFitPol[i]) {in->souFit[i][1] = TRUE;  in->souFit[i][2] = TRUE;}\n    else                 {in->souFit[i][1] = FALSE; in->souFit[i][2] = FALSE;}\n    if (in->doFitV[i])    in->souFit[i][3] = TRUE;\n    else                  in->souFit[i][3] = FALSE;\n    in->souParm[i*4+0] = in->souFlux[i];  /* average of input data */\n    in->souParm[i*4+1] = in->souParm[i*4+2] = in->souParm[i*4+3] = 0.0;\n    /* Last valid source parameters, I<-1000 =>none */\n    in->lastSouParm[i*4+0] = -1000.0;\n    in->lastSouParm[i*4+1] = in->lastSouParm[i*4+2] = in->lastSouParm[i*4+3] = 0.0;\n  } /* end filling source fitting flags */\n\n  /* Get numbers of channels/IFs */\n  BChan   = 1;\n  EChan   = in->inDesc->inaxes[in->inDesc->jlocf];\n  iChan   = 1 + in->ChInc/2;\n  if (in->inDesc->jlocif>=0) EIF = in->inDesc->inaxes[in->inDesc->jlocif];\n  else                      EIF = 1;\n  iIF     = 1;\n  done    = FALSE;\n\n  /* Data tables */\n  size = in->inDesc->nvis;\n  in->inData = g_malloc0(10*size*sizeof(ofloat));\n  in->inWt   = g_malloc0(4*size*sizeof(ofloat));\n  in->antNo  = g_malloc0(2*size*sizeof(olong));\n  in->souNo  = g_malloc0(size*sizeof(olong));\n\n  /* Initialize threads*/\n  MakePolnFitFuncArgs (in, err); \n\n  /* Loop over data in blocks of Channels */\n  while (!done) {\n\n    /* Read data, init solutions */\n    first = (iIF!=in->IFno) || (iChan==BChan);   /* First of an IF */\n    ReadData (in, inUV, &iChan, EChan, &iIF, EIF, first, err);\n    if (err->error) Obit_traceback_msg (err, routine, inUV->name);\n\n    /* average flux densities of input data */\n    for (i=0; i<in->nsou; i++) {\n      if (in->souFit[i][0]) in->souParm[i*4+0] = in->souFlux[i];\n    } /* End initializing source flux densities */\n\n    if (in->prtLv>=2) {\n      Obit_log_error(err, OBIT_InfoErr, \"Process IF %d Channel %d no chan %d\",\n\t\t     in->IFno+in->BIF-1, in->Chan+in->BChan-1, in->ChWid);\n      ObitErrLog(err); \n   }\n\n    /* Set order and count number of parameters being fitted */\n    in->nparam = 0;\n    /* get model parameters - first antenna */\n    for (iant=0; iant<in->nant; iant++) {\n      if (in->gotAnt[iant]) {\n\t/* Loop over parameters */\n\tfor (k=0; k<4; k++) {\n\t  /* Fitting? */\n\t  if (in->antFit[iant][k]) {\n\t    in->antPNumb[iant][k] = in->nparam++;\n\t  } else in->antPNumb[iant][k] = -999;\n\t} /* end loop over parameters */\n      } /* end if gotAnt */\n    } /* end loop over antennas */\n\n    /* Antenna gains if needed */\n    if (!in->isCircFeed && in->doFitGain) {\n      for (iant=0; iant<in->nant; iant++) {\n\tif (in->gotAnt[iant]) {\n\t  /* Loop over parameters */\n\t  for (k=0; k<2; k++) {\n\t    /* Fitting? */\n\t    if (in->antGainFit[iant][k]) {\n\t      in->antGainPNumb[iant][k] = in->nparam++;\n\t    } else in->antGainPNumb[iant][k] = -999;\n\t  } /* end loop over parameters */\n\t} /* end if gotAnt */\n      } /* end loop over antennas */\n    } /* End if antenna gains */\n   \n    /* now source */\n    for (isou=0; isou<in->nsou; isou++) {\n      /* Loop over parameters */\n      for (k=0; k<4; k++) {\n\t/* Fitting? */\n\tif (in->souFit[isou][k]) {\n\t  in->souPNumb[isou][k] = in->nparam++;\n\t} else in->souPNumb[isou][k] = -999;\n      } /* end loop over parameters */\n    } /* end loop over sources */\n\n    /* Phase difference parameter number if being fitted */\n    if (in->doFitRL) in->PDPNumb = in->nparam++;\n    \n    /* Init solver stuff first pass */\n    nvis       = inUV->myDesc->nvis;\n    in->ndata  = nvis*4*2;   /* 4 complex visibililties */\n#ifdef HAVE_GSL\n    if ((in->solnType[0]=='L') && (in->solnType[1]=='M')) { \n      /* Need to rebuild? */\n      if ((in->solver!=NULL) || (oldNparam!=in->nparam) || (oldNdata!=in->ndata))  {\n\tif( in->solver)    gsl_multifit_fdfsolver_free (in->solver); in->solver = NULL;\n\tif (in->funcStruc) g_free(in->funcStruc);                    in->funcStruc = NULL;\n\tif (in->work)      gsl_vector_free(in->work);                in->work = NULL;\n\tif (in->covar)     gsl_matrix_free(in->covar);               in->covar = NULL;\n      }\n      if (in->solver==NULL) {\n\toldNparam = in->nparam;\n\toldNdata  = in->ndata;\n\tT = gsl_multifit_fdfsolver_lmder;\n\tin->solver    = gsl_multifit_fdfsolver_alloc(T, in->ndata, in->nparam);\n\tin->funcStruc = g_malloc0(sizeof(gsl_multifit_function_fdf));\n\tin->work      = gsl_vector_alloc(in->nparam);\n\tin->covar     = gsl_matrix_alloc(in->nparam, in->nparam);\n\t/* Function by feed type  */\n\tif (in->isCircFeed) {\n\t  /* Circular feeds */\n\t  in->funcStruc->f   = &PolnFitFuncOERL;\n\t  in->funcStruc->df  = &PolnFitJacOERL;\n\t  in->funcStruc->fdf = &PolnFitFuncJacOERL;\n\t} else {\n\t  /* Linear feeds  */\n\t  in->funcStruc->f   = &PolnFitFuncOEXY;\n\t  in->funcStruc->df  = &PolnFitJacOEXY;\n\t  in->funcStruc->fdf = &PolnFitFuncJacOEXY;\n\t}\n      }\n    } /* If using LM */\n#endif /* HAVE_GSL */ \n\n    /* Do actual fitting  */\n\n    /* Make sure solutions are not blanked from last fit */\n    resetSoln(in);\n\n    /* zero reference antenna ellipticity for lin. feeds */\n    if ((!in->isCircFeed) &&(in->refAnt>0)) {\n      refAnt = in->refAnt;\n      in->antParm[(refAnt-1)*4+1] = 0.0;\n    }\n\n    /* Do fit - fast method to get better soln, then possibly GSL */\n    isOK = doFitFast (in, err);\n    /* refit with no reference antenna for lin. feeds \n     This doesn't actually do much except better elip. for ref ant */\n    if ((!in->isCircFeed) &&(in->refAnt>0)) {\n      refAnt = in->refAnt-1;\n      in->antFit[refAnt][1] = TRUE;\n      isOK = doFitFast (in, err);\n      in->antFit[refAnt][1] = FALSE;\n      in->refAnt = refAnt+1;\n    }\n    /* end refit linear */\n    /* If only one screwy antenna chunk it and try again */\n    if (CheckCrazyOne(in, err)) isOK = doFitFast (in, err);\n    if (isOK) {\n      if (!strncmp(in->solnType, \"LM  \", 4)) doFitGSL (in, err);\n      \n      endChi2 = GetChi2 (in->nThread, in, polnParmUnspec, 0, \n\t\t\t &ParRMS, &XRMS, NULL, NULL, err);  /* Final value */\n      if (err->prtLv>=2) {\n\tObit_log_error(err, OBIT_InfoErr, \n\t\t       \"Final Chi2=%g Par RMS %g X RMS %g \", endChi2, ParRMS, XRMS);\n\tif (err->error) Obit_traceback_msg (err, routine, inUV->name);\n      }\n      \n    } /* End fit OK */\n    \n    /* Done? */\n    done = iIF > EIF;\n    /* Diagnostics */\n    if (isOK && (err->prtLv>=4)) {\n      /* BL 1-2 sou 1 */\n      refAnt = in->refAnt-1;\n      fprintf (stderr, \"Source 0 IF %d Chan %d\\n\", in->IFno, in->Chan);\n      /* Header by feed type  */\n      if (in->isCircFeed) {\n\t/* Circular feeds */\n\tfprintf (stderr, \" bl     PA          RRr (o,c)         RRi                LLr                LLi                RLr                RLi                LRr                LRi \\n\");\n      } else  {\n\t/* Linear feeds  */\n\tfprintf (stderr, \" bl     PA          XXr (o,c)         XXi                YYr                YYi                XYr                XYi                YXr                YXi \\n\");\n      }\n      for (i=0; i<in->nvis; i++) {\n\tisou   = MAX(0, in->souNo[i]);    /* Source number */\n\tia1    = in->antNo[i*2+0];\n\tia2    = in->antNo[i*2+1]; \n\t/* Diagnostics */\n\tif ((isou==0) && (ia1==1) && (ia2==2)) {  /* first source 2-3 */\n\t  /* Function by feed type  */\n\t  if (in->isCircFeed ) {\n\t    /* Circular feeds */\n\t    calcmodelRL (in, RArray, i);\n\t  } else {\n\t    /* Linear feeds  */\n\t    calcmodelXY (in, RArray, i);\n\t  }\n\t  RRr = RArray[0]; RRi = RArray[1]; \n\t  LLr = RArray[6]; LLi = RArray[7]; \n\t  RLr = RArray[2]; RLi = RArray[3]; \n\t  LRr = RArray[4]; LRi = RArray[5]; \n\t  fprintf (stderr, \"%2d-%2d %8.5f %8.5f %8.5f  %8.5f %8.5f  %8.5f %8.5f  %8.5f %8.5f  %8.5f %8.5f  %8.5f %8.5f  %8.5f %8.5f  %8.5f %8.5f \\n\",\n\t\t   ia1+1,ia2+1,in->inData[i*10+0],\n\t\t   in->inData[i*10+2],  RRr, in->inData[i*10+3], RRi, in->inData[i*10+4], LLr, in->inData[i*10+5], LLi,\n\t\t   in->inData[i*10+6],  RLr, in->inData[i*10+7], RLi, in->inData[i*10+8], LRr, in->inData[i*10+9], LRi);\n\t}\n      }\n    } /* End debug diagnostics */\n    \n    /* Write output to Tables  if some valid XPol data */\n    isOK = isOK && (XRMS>0.0);\n    WriteOutput(in, outUV, isOK, err);\n    if (err->error) Obit_traceback_msg (err, routine, inUV->name);\n\n  } /* end loop over blocks of channels */\n  \n} /* end ObitPolnCalFitFit */\n\n/**\n * Initialize global ClassInfo Structure.\n */\nvoid ObitPolnCalFitClassInit (void)\n{\n  if (myClassInfo.initialized) return;  /* only once */\n  \n  /* Set name and parent for this class */\n  myClassInfo.ClassName   = g_strdup(myClassName);\n  myClassInfo.ParentClass = ObitParentGetClass();\n\n  /* Set function pointers */\n  ObitPolnCalFitClassInfoDefFn ((gpointer)&myClassInfo);\n \n  myClassInfo.initialized = TRUE; /* Now initialized */\n \n} /* end ObitPolnCalFitClassInit */\n\n/**\n * Initialize global ClassInfo Function pointers.\n */\nstatic void ObitPolnCalFitClassInfoDefFn (gpointer inClass)\n{\n  ObitPolnCalFitClassInfo *theClass = (ObitPolnCalFitClassInfo*)inClass;\n  ObitClassInfo *ParentClass = (ObitClassInfo*)myClassInfo.ParentClass;\n\n  if (theClass->initialized) return;  /* only once */\n\n  /* Check type of inClass */\n  g_assert (ObitInfoIsA(inClass, (ObitClassInfo*)&myClassInfo));\n\n  /* Initialize (recursively) parent class first */\n  if ((ParentClass!=NULL) && \n      (ParentClass->ObitClassInfoDefFn!=NULL))\n    ParentClass->ObitClassInfoDefFn(theClass);\n\n  /* function pointers defined or overloaded this class */\n  theClass->ObitClassInit = (ObitClassInitFP)ObitPolnCalFitClassInit;\n  theClass->newObit       = (newObitFP)newObitPolnCalFit;\n  theClass->ObitClassInfoDefFn = (ObitClassInfoDefFnFP)ObitPolnCalFitClassInfoDefFn;\n  theClass->ObitGetClass  = (ObitGetClassFP)ObitPolnCalFitGetClass;\n  theClass->ObitCopy      = (ObitCopyFP)ObitPolnCalFitCopy;\n  theClass->ObitClone     = NULL;\n  theClass->ObitClear     = (ObitClearFP)ObitPolnCalFitClear;\n  theClass->ObitInit      = (ObitInitFP)ObitPolnCalFitInit;\n  theClass->ObitPolnCalFitCreate = (ObitPolnCalFitCreateFP)ObitPolnCalFitCreate;\n  theClass->ObitPolnCalFitFit    = (ObitPolnCalFitFitFP)ObitPolnCalFitFit;\n} /* end ObitPolnCalFitClassDefFn */\n\n/*---------------Private functions--------------------------*/\n\n/**\n * Creates empty member objects, initialize reference count.\n * Parent classes portions are (recursively) initialized first\n * \\param inn Pointer to the object to initialize.\n */\nvoid ObitPolnCalFitInit  (gpointer inn)\n{\n  ObitClassInfo *ParentClass;\nObitPolnCalFit *in = inn;\n\n  /* error checks */\n  g_assert (in != NULL);\n\n  /* recursively initialize parent class members */\n  ParentClass = (ObitClassInfo*)(myClassInfo.ParentClass);\n  if ((ParentClass!=NULL) && ( ParentClass->ObitInit!=NULL)) \n    ParentClass->ObitInit (inn);\n\n  /* set members in this class */\n  in->thread     = newObitThread();\n  in->info       = newObitInfoList(); \n  in->inData     = NULL;\n  in->inWt       = NULL;\n  in->nant       = 0;\n  in->antNo      = NULL;\n  in->antParm    = NULL;\n  in->antErr     = NULL;\n  in->gotAnt     = NULL;\n  in->antFit     = NULL;\n  in->antGain    = NULL;\n  in->antGainErr = NULL;\n  in->antGain    = NULL;\n  in->antGainFit = NULL;\n  in->AntLists   = NULL;\n  in->nsou       = 0;\n  in->souNo      = NULL;\n  in->souParm    = NULL;\n  in->souFlux    = NULL;\n  in->souErr     = NULL;\n  in->lastSouParm= NULL;\n  in->souFit     = NULL;\n  in->antPNumb   = NULL;\n  in->SouList    = NULL;\n  in->souIDs     = NULL;\n  in->isouIDs    = NULL;\n  in->inDesc     = NULL;\n  in->outDesc    = NULL;\n  in->RLPhaseIn  = NULL;\n  in->RLPhase    = NULL;\n  in->RM         = NULL;\n  in->PPol       = NULL;\n  in->dPPol      = NULL;\n  in->doFitI     = NULL;\n  in->doFitV     = NULL;\n  in->doFitPol   = NULL;\n  in->IFlux0     = NULL;\n  in->IFlux1     = NULL;\n  in->IFlux2     = NULL;\n  in->CPTable    = NULL;\n  in->PDTable    = NULL;\n  in->BPTable    = NULL;\n  in->doFitRL    = FALSE;\n  in->doBlank    = TRUE;\n  in->doFitGain  = TRUE;\n  in->doFitOri   = TRUE;\n  in->BIF        = 1;\n  in->BChan      = 1;\n  in->ChWid      = 1;\n  in->ChInc      = 1;\n  in->CPSoln     = 0;\n  in->PDSoln     = 0;\n  in->BPSoln     = 0;\n  in->doBand     = 0;\n  in->BPVer      = 0;\n  in->doError    = TRUE;\n  in->isCircFeed = TRUE;\n  in->maxAnt   = 100;\n  in->isInitialized = FALSE;\n} /* end ObitPolnCalFitInit */\n\n/**\n * Deallocates member objects.\n * Does (recursive) deallocation of parent class members.\n * \\param  inn Pointer to the object to deallocate.\n *           Actually it should be an ObitPolnCalFit* cast to an Obit*.\n */\nvoid ObitPolnCalFitClear (gpointer inn)\n{\n  ObitClassInfo *ParentClass;\n  ObitPolnCalFit *in = inn;\n  olong i;\n\n  /* error checks */\n  g_assert (ObitIsA(in, &myClassInfo));\n\n  /* delete this class members */\n  if (in->antFit) {\n    for (i=0; i<in->nant; i++) if (in->antFit[i]) g_free(in->antFit[i]);\n    g_free(in->antFit);\n  }\n  if (in->antGainFit) {\n    for (i=0; i<in->nant; i++) if (in->antGainFit[i]) g_free(in->antGainFit[i]);\n    g_free(in->antGainFit);\n  }\n  if (in->souFit) {\n    for (i=0; i<in->nsou; i++) if (in->souFit[i]) g_free(in->souFit[i]);\n    g_free(in->souFit);\n  }\n  if (in->antPNumb) {\n    for (i=0; i<in->nant; i++) if (in->antPNumb[i]) g_free(in->antPNumb[i]);\n    g_free(in->antPNumb);\n  }\n  if (in->antGainPNumb) {\n    for (i=0; i<in->nant; i++) if (in->antGainPNumb[i]) g_free(in->antGainPNumb[i]);\n    g_free(in->antGainPNumb);\n  }\n  if (in->souPNumb) {\n    for (i=0; i<in->nsou; i++) if (in->souPNumb[i]) g_free(in->souPNumb[i]);\n    g_free(in->souPNumb);\n  }\n  if (in->AntLists) {\n    for (i=0; i<in->numSubA; i++) if (in->AntLists[i]) ObitAntennaListUnref(in->AntLists[i]);\n    g_free(in->AntLists);\n  }\n  if (in->inWt)     g_free(in->inWt);\n  if (in->inData)   g_free(in->inData);\n  if (in->antNo)    g_free(in->antNo);\n  if (in->antParm)  g_free(in->antParm);\n  if (in->gotAnt)   g_free(in->gotAnt);\n  if (in->antErr)   g_free(in->antErr);\n  if (in->antGain)  g_free(in->antGain);\n  if (in->antGainErr) g_free(in->antGainErr);\n  if (in->souNo)    g_free(in->souNo);\n  if (in->souParm)  g_free(in->souParm);\n  if (in->souFlux)  g_free(in->souFlux);\n  if (in->souErr)   g_free(in->souErr);\n  if (in->lastSouParm) g_free(in->lastSouParm);\n  if (in->souIDs)   g_free(in->souIDs);\n  if (in->isouIDs)  g_free(in->isouIDs);\n  if (in->RLPhaseIn)g_free(in->RLPhaseIn);\n  if (in->RLPhase)  g_free(in->RLPhase);\n  if (in->RM)       g_free(in->RM);\n  if (in->PPol)     g_free(in->PPol);\n  if (in->dPPol)    g_free(in->dPPol);\n  if (in->doFitI)   g_free(in->doFitI);\n  if (in->doFitV)   g_free(in->doFitV);\n  if (in->doFitPol) g_free(in->doFitPol);\n  if (in->IFlux0)   g_free(in->IFlux0);\n  if (in->IFlux1)   g_free(in->IFlux1);\n  if (in->IFlux2)   g_free(in->IFlux2);\n  if (in->thArgs) KillPolnFitFuncArgs (in);\n  in->inDesc    = ObitUVDescUnref(in->inDesc);\n  in->outDesc   = ObitUVDescUnref(in->outDesc);\n  in->thread    = ObitThreadUnref(in->thread);\n  in->info      = ObitInfoListUnref(in->info);\n  in->SouList   = ObitSourceListUnref(in->SouList);\n  in->oneSource = ObitSourceUnref(in->oneSource);\n  in->CPTable   = ObitTableUnref(in->CPTable);\n  in->PDTable   = ObitTableUnref(in->PDTable);\n  in->BPTable   = ObitTableUnref(in->BPTable);\n#ifdef HAVE_GSL\n    if( in->solver)    gsl_multifit_fdfsolver_free (in->solver);\n    if (in->funcStruc) g_free(in->funcStruc);\n    if (in->work)      gsl_vector_free(in->work);\n    if (in->covar)     gsl_matrix_free(in->covar);\n#endif /* HAVE_GSL */ \n\n  /* unlink parent class members */\n  ParentClass = (ObitClassInfo*)(myClassInfo.ParentClass);\n  /* delete parent class members */\n  if ((ParentClass!=NULL) && ( ParentClass->ObitClear!=NULL)) \n    ParentClass->ObitClear (inn);\n  \n} /* end ObitPolnCalFitClear */\n\n/**\n * Write contents on in to tables on outUV\n * Tables initialized on call with first thread for chan=IF=1\n * (including BChan, BIF)\n * \\param in       Fitting object\n * \\param outUV    UV date with results in tables\n * \\param isOK     Something worth writing\n * \\param err      Obit error stack object.\n */\nstatic void WriteOutput (ObitPolnCalFit* in, ObitUV *outUV, \n\t\t\t gboolean isOK, ObitErr *err)\n{\n  oint numPol, numIF, numChan;\n  ObitIOCode retCode;\n  ObitTableBP *oldBPTab=NULL;\n  gboolean sameBP=FALSE, crazy;\n  ObitIOAccess access;\n  ObitUVDesc *IODesc;\n  gchar *routine = \"ObitPolnCalFit:WriteOutput\";\n\n  /* error checks */\n  if (err->error) return;\n\n\n  /* Need to initialize? */\n  if (!in->isInitialized) {\n     /* First channel and IF \n\tif (((in->Chan+in->BChan-1-in->ChInc/2)==1) && \n\t((in->IFno+in->BIF-1)==1)) {*/\n    in->isInitialized = TRUE;  /* This will initialize it */\n    /* Open output */\n    retCode = ObitUVOpen (outUV, OBIT_IO_ReadWrite, err);\n    /* if it didn't work bail out */\n    if ((retCode!=OBIT_IO_OK) || (err->error)) \n      Obit_traceback_msg (err, routine, outUV->name);\n\n    /* How many of things? Use underlying sizes */\n    IODesc = (ObitUVDesc*)outUV->myIO->myDesc;\n    numPol  = MIN (2,IODesc->inaxes[IODesc->jlocs]);\n    if (IODesc->jlocif>=0) numIF = IODesc->inaxes[IODesc->jlocif];\n    else                  numIF = 1;\n    numChan = IODesc->inaxes[IODesc->jlocf];\n\n   /* Source table */\n    in->CPTable = newObitTableCPValue (\"Source\", (ObitData*)outUV, &in->CPSoln, \n\t\t\t\t       OBIT_IO_WriteOnly, numIF, numChan, err);\n    InitSourceTab(in, err);\n\n    /* Instrumental poln table */\n    in->PDTable = newObitTablePDValue (\"Instrum\", (ObitData*)outUV, &in->PDSoln, \n\t\t\t\t       OBIT_IO_WriteOnly, numPol, numIF, numChan, \n\t\t\t\t       err);\n    InitInstrumentalTab(in, err);\n\n    /* BP table used if fitting R/L X/Y phase difference or X/Y gain*/\n    if (in->doFitRL || in->doFitGain) {\n      /* Bandpass table - copy and update if doBand>0 */\n      if (in->doBand>0) {\n\toldBPTab = newObitTableBPValue (\"Temp BP\", (ObitData*)outUV, &in->BPVer, \n\t\t\t\t\tOBIT_IO_ReadOnly, numPol, numIF, numChan, \n\t\t\t\t\terr);\n\t/* Check that you're not about to clobber the input */\n\tsameBP = in->BPVer==in->BPSoln;\n\tif (sameBP) access = OBIT_IO_ReadWrite;\n\taccess = OBIT_IO_WriteOnly;\n\t/* Warn if overwriting */\n\tif (sameBP) {\n\t  Obit_log_error(err, OBIT_InfoWarn, \"Modifying input BP Table\");\n\t  ObitErrLog(err); \n\t}\n      } else { /* No prior bandpass cal */\n\tif (in->BPSoln<=0) access = OBIT_IO_WriteOnly;\n\telse access = OBIT_IO_ReadWrite;\n      }\n      \n      /* Create or open output */\n      in->BPTable = newObitTableBPValue (\"Bandpass\", (ObitData*)outUV, &in->BPSoln, \n\t\t\t\t\t access , numPol, numIF, numChan, \n\t\t\t\t\t err);\n      /* Copy old to new */\n      if ((in->doBand>0) && !sameBP) {\n\tin->BPTable = ObitTableBPCopy (oldBPTab, in->BPTable, err);\n\toldBPTab = ObitTableBPUnref(oldBPTab);\n      } else {\n\tInitBandpassTab(in, err);\n      }\n    } /* end setup BP table */\n\n    /* Close output */\n    retCode = ObitUVClose (outUV, err);\n    /* if it didn't work bail out */\n    if ((retCode!=OBIT_IO_OK) || (err->error)) \n      Obit_traceback_msg (err, routine, outUV->name);\n    /* end init */\n  } else { /* Make sure output tables defined */\n    /* How many of things? */\n    numPol  = MIN (2,in->outDesc->inaxes[in->outDesc->jlocs]);\n    if (in->outDesc->jlocif>=0) numIF = in->outDesc->inaxes[in->outDesc->jlocif];\n    else                       numIF = 1;\n    numChan = in->outDesc->inaxes[in->outDesc->jlocf];\n\n    if (!in->CPTable) \n      in->CPTable = newObitTableCPValue (\"Source\", (ObitData*)outUV, &in->CPSoln, \n\t\t\t\t\t OBIT_IO_ReadWrite, numIF, numChan, err);\n    if (!in->PDTable) \n      in->PDTable = newObitTablePDValue (\"Instrum\", (ObitData*)outUV, &in->PDSoln, \n\t\t\t\t\t OBIT_IO_ReadWrite, numPol, numIF, numChan, \n\t\t\t\t\t err);\n    if ((!in->BPTable) && (in->doFitRL))\n      in->BPTable = newObitTableBPValue (\"Bandpass\", (ObitData*)outUV, &in->BPSoln, \n\t\t\t\t\t OBIT_IO_ReadWrite, numPol, numIF, numChan, \n\t\t\t\t\t err);\n  }\n\n   /* Check for crazy antenna solutions and reset defaults */\n  crazy = CheckCrazy(in, err);\n  if (crazy) isOK = FALSE;\n\n  /* Update Tables */\n  if (isOK) UpdateSourceTab(in, err);\n  UpdateInstrumentalTab(in, isOK, err);\n  if (in->doFitRL || in->doFitGain) UpdateBandpassTab(in, isOK, err);\n  if (err->error)  Obit_traceback_msg (err, routine, outUV->name);\n\n} /* end WriteOutput */\n\n/**\n * Read data and load arrays.\n * Averages ChWid channels centered on each channel.\n * Require all 4 correlations to be valid in each channel\n * \\param in    Fitting object\n * \\param inUV  Averaged/calibrated/divided UV data to be fitted\n * \\param iChan Current first channel (1-rel) in thread group, \n *              updated to value for next call on exit;\n * \\param EChan Highest channel\n * \\param iIF   Current IF number (1-rel) , updated to value for next call\n * \\param EIF   Highest IF\n * \\param init  If True, solutions also initialized\n * \\param err   Obit error stack object.\n * \\return number of threads with data loaded.\n */\nstatic void ReadData (ObitPolnCalFit *in, ObitUV *inUV, olong *iChan, \n\t\t      olong EChan, olong *iIF, olong EIF, \n\t\t      gboolean init,  ObitErr *err)\n{\n  ObitIOCode retCode = OBIT_IO_OK;\n  ObitSource *curSource=NULL;\n  olong ivis, ant1, ant2, isou, jsou, lastSou=-999, jvis, istok, suba;\n  olong nChan, bch, ech, cnt, i, j, indx, indx1, indx2, indx3, indx4, *cntFlux=NULL;\n  olong ChInc=in->ChInc, jChan, jIF;\n  ofloat *buffer, curPA1=0.0, curPA2=0.0, curTime=0.0, lastTime=-1.0e20;\n  ofloat sumRe, sumIm, sumWt, PPol, *sumFlux=NULL; \n  odouble lambdaRef, lambda, ll, sum;\n  gboolean OK, allBad;\n  gchar *routine = \"ObitPolnCalFit:ReadData\";\n  /* DEBUG */\n#ifdef DEBUG\n  olong dbgCnt1, dbgCnt2;\n  ofloat dbgSum1, dbgSum2, dbgISum1, dbgISum2;\n#endif\n  /* end DEBUG */\n\n  /* Previous error? */\n  if (err->error) return;\n\n  lambdaRef = VELIGHT/in->inDesc->freq;  /* Wavelength at reference freq */\n\n  /* Sums for flux density */\n  sumFlux = g_malloc0(in->nsou*sizeof(ofloat));\n  cntFlux = g_malloc0(in->nsou*sizeof(olong));\n  for (i=0; i<in->nsou; i++) {sumFlux[i] = 0.0; cntFlux[i] = 0;}\n\n  /* initial center channel/IF */\n  jChan = *iChan;\n  jIF   = *iIF;\n  nChan = in->inDesc->inaxes[in->inDesc->jlocf];\n\n  /* Set channel/IF in thread */\n  ChInc = MAX (1,ChInc);\n  in->Chan  = (*iChan);\n  in->IFno = *iIF;\n  (*iChan) += ChInc;   /* Next channel */\n  if (((*iChan)>EChan) && ((*iIF)<EIF)) {  /* Done with IF? */\n    (*iChan) = 1 + ChInc/2;\n    (*iIF)++;\n  }\n  \n  /* Keep track of antennas with data */\n  for (i=0; i<in->nant; i++) in->gotAnt[i] = FALSE;\n\n  /* Frequency */\n  indx = (jIF-1)*nChan + (jChan-1);\n  in->freq = in->inDesc->freqArr[indx];\n  /* Set RL phases of calibrators */\n  lambda = VELIGHT/in->freq;\n  /* Loop over calibrators */\n  for (i=0; i<in->nsou; i++) {\n    /* Set R-L phase if given */\n    if (in->RLPhaseIn[i]>-900.0) {\n      in->RLPhase[i] = \tin->RLPhaseIn[i] + \n\t2.0 * (lambda*lambda - lambdaRef*lambdaRef) * in->RM[i];\n    } else in->RLPhase[i] = 0.0;\n  }\n\n  /* Beginnning and end channel */\n  bch = in->Chan - in->ChWid/2;\n  ech = in->Chan + in->ChWid/2;\n  /* Force to range */\n  bch = MAX (1, bch);\n  ech = MIN (nChan, ech);\n  /* Convert to 0-rel */\n  bch--;\n  ech--;\n\n  /* Open input */\n  retCode = ObitUVOpen (inUV, OBIT_IO_ReadOnly, err);\n  if (err->error) goto cleanup;\n\n /* loop loading data */\n  jvis = 0;\n  while (retCode == OBIT_IO_OK) {\n    \n    /* read buffer */\n    retCode = ObitUVRead (inUV, NULL, err);\n    if (retCode == OBIT_IO_EOF) break; /* done? */\n    if (err->error) goto cleanup;\n    \n    /* Loop over buffer */\n    buffer = inUV->buffer;\n    for (ivis=0; ivis<inUV->myDesc->numVisBuff; ivis++) {\n      \n      /* Check array bounds */\n      if (jvis>=in->inDesc->nvis) {\n\tObit_log_error(err, OBIT_Error, \"%s: Exceeded vis buffer size\", routine);\n\tgoto cleanup;\n      }\n\n      /* Check that all Stokes correlations in each channel are present,\n\t if only partial, flag the rest */\n      allBad = TRUE;\n      for (i=bch; i<=ech; i++) {\n\tindx = inUV->myDesc->nrparm + i*inUV->myDesc->incf\n\t  + (jIF-1)*inUV->myDesc->incif + 2;\n\tindx1 = indx + 0*inUV->myDesc->incs;\n\tindx2 = indx + 1*inUV->myDesc->incs;\n\tindx3 = indx + 2*inUV->myDesc->incs;\n\tindx4 = indx + 3*inUV->myDesc->incs;\n\tOK = (buffer[indx1]>0.0) && (buffer[indx2]>0.0) && \n\t  (buffer[indx3]>0.0) && (buffer[indx4]>0.0);\n\tif (!OK) {  /* Kill 'em all */\n\t  buffer[indx1] = buffer[indx2] = buffer[indx3] = buffer[indx4] = 0.0;\n\t} else allBad = FALSE;  /* Some OK */\n      } /* end checking data loop */\n      \n      /* if all data flagged skip to end */\n      if (allBad) goto endloop;\n\n      /* Get info - source ID */\n      if (inUV->myDesc->ilocsu>=0) isou = buffer[inUV->myDesc->ilocsu]+0.5;\n      else isou = in->souIDs[0];\n      jsou = in->isouIDs[isou-1];  /* Calibrator number */\n      /* Antennas */\n      ObitUVDescGetAnts(inUV->myDesc, buffer, &ant1, &ant2, &suba);\n\n      /* Source change? */\n      if (isou!=lastSou) {\n\tlastSou = isou;\n\tif (in->SouList) curSource = in->SouList->SUlist[isou-1];\n\telse curSource = in->oneSource;\n      }\n      \n      /* Get parallactic angle when time changes */\n      curTime = buffer[inUV->myDesc->iloct];\n      if (curTime>lastTime) {\n\tcurPA1 = ObitAntennaListParAng (in->AntLists[suba-1], ant1, curTime, curSource);\n\tcurPA2 = ObitAntennaListParAng (in->AntLists[suba-1], ant2, curTime, curSource);\n\tlastTime = curTime;\n      }\n\n      /* Save info */\n      in->souNo[jvis]     = jsou;  /* relative to list, not data ID */\n      in->antNo[jvis*2+0] = ant1-1;\n      in->antNo[jvis*2+1] = ant2-1;\n      /* Parallactic angle */\n      in->inData[jvis*10]    = curPA1;\n      in->inData[jvis*10+1]  = curPA2;\n      /* getAnt flags */\n      in->gotAnt[ant1-1] = TRUE;\n      in->gotAnt[ant2-1] = TRUE;\n      \n      /* Loop over Stokes */\n      for (istok=0; istok<4; istok++) {\n\t\n\t/* Average vis */\n\tsumRe = sumIm = sumWt = 0; cnt = 0;\n\tfor (i=bch; i<=ech; i++) {\n\t  /* Where in buffer? */\n\t  indx = inUV->myDesc->nrparm + i*inUV->myDesc->incf\n\t    + (jIF-1)*inUV->myDesc->incif + istok*inUV->myDesc->incs;\n\t  if (buffer[indx+2]>0) {\n\t    cnt++;\n\t    sumRe += buffer[indx];\n\t    sumIm += buffer[indx+1];\n\t    sumWt += buffer[indx+2];\n\t  }\n\t} /* end average loop */\n\t  /* Average */\n\tif ((cnt>0) && (sumWt>0.0)) {\n\t  sumRe /= cnt;\n\t  sumIm /= cnt;\n\t} else {  /* invalid */\n\t  sumRe = 0.0;\n\t  sumIm = 0.0;\n\t  sumWt = 0.0;\n\t}\n\t/* Weight */\n\tin->inWt[jvis*4+istok] = sumWt;\n\t  /* Data */\n\tin->inData[jvis*10+(istok+1)*2]   = sumRe;\n\tin->inData[jvis*10+(istok+1)*2+1] = sumIm;\n\t/* Sums for Stokes */\n\tif (istok<=1) {cntFlux[jsou]++; sumFlux[jsou]+=sumRe; }\n    } /* end Stokes loop */\n      \n\n      /* Diagnostic - sample data */\n      if ((err->prtLv>=5) && (ant1==2) && (ant2==4)) {\n\tfprintf (stderr,\"vis %d bl %d %d sou %d time %f PA %f Data %8.5f %8.5f  %8.5f %8.5f  %8.5f %8.5f  %8.5f %8.5f\\n\",\n\t\t jvis, ant1, ant2, isou, curTime, curPA1,\n\t\t in->inData[jvis*10+2],in->inData[jvis*10+3],\n\t\t in->inData[jvis*10+4],in->inData[jvis*10+5],\n\t\t in->inData[jvis*10+6],in->inData[jvis*10+7],\n\t\t in->inData[jvis*10+8],in->inData[jvis*10+9]);\n      }\n      \n      jvis++;  /* Data array visibility index */\n    endloop:  /* to here if data bad */\n      buffer += inUV->myDesc->lrec;\n    } /* end loop over vis */\n  } /* end loop reading data */\n\n\n  in->nvis = jvis;  /* How many good data? */\n  /* Initialize solutions if init */\n  if (init) {\n    /* first zero everything \n       for (i=0; i<in->nsou; i++) {\n       for (j=0; j<4; j++) in->souParm[i*4+j] = 0.0;\n       }*/\n    for (i=0; i<in->nant; i++) {\n      for (j=0; j<4; j++) in->antParm[i*4+j] = 0.0;\n      if (in->isCircFeed) {\n\t/* Circular feeds ori_r, elip_r, ori_l, elip_l */\n\tin->antParm[i*4+0] = 0.0;\n\tin->antParm[i*4+1] = G_PI/4.0;\n\tin->antParm[i*4+2] =  0.0;\n\tin->antParm[i*4+3] =  -G_PI/4.0;\n      } else  {\n \t/* Linear feeds, if the antenna angles on sky are given in the AntennaList[0] use then, \n           otherwise assume Feeds are X, Y\n\t   ori_x, elip_x, ori_y, elip_y,  \n\t*/\n\tin->antGain[i*2] = in->antGain[i*2+1] = 1.0;  /* Gain */\n\tin->antParm[i*4+1] = 0.0;                     /* ellipticity */\n\tin->antParm[i*4+3] = 0.0;\n\tif (fabs (in->AntLists[0]->ANlist[i]->FeedAPA-in->AntLists[0]->ANlist[i]->FeedBPA)<1.0) {\n\t  /* Assume X, Y */\n\t  in->antParm[i*4+0] = 0.0;\n\t  in->antParm[i*4+2] = +G_PI/2.0;\n\t} else {  /* Use what's in the AN table as initial convert to radians */\n\t  in->antParm[i*4+0] = in->AntLists[0]->ANlist[i]->FeedAPA*DG2RAD;\n\t  in->antParm[i*4+2] = in->AntLists[0]->ANlist[i]->FeedBPA*DG2RAD;\n\t} /* end if antenna angle given */\n      }\n    }\n  } /* end init */\n\n  /* Some parameters always need updating */\n  /* in->PD = 0.0;  R-L (X/Y) phase difference */\n  for (i=0; i<in->nsou; i++) {\n    \n    /* Stokes I - evaluate spectrum in ln(nu/nu_ref) */\n    ll = log(in->freq/in->inDesc->freq);\n    sum = in->IFlux1[i]*ll + in->IFlux2[i]*ll*ll;\n    in->souParm[i*4] = exp(sum) * in->IFlux0[i];\n    /* Fixed linear poln fn? */\n    if (in->PPol[i]>0.0) {\n      PPol = in->PPol[i] + in->dPPol[i]*(in->freq-in->inDesc->freq);\n      in->souParm[i*4+1] = PPol * in->souParm[i*4] * cos(in->RLPhase[i]);\n      in->souParm[i*4+2] = PPol * in->souParm[i*4] * sin(in->RLPhase[i]);\n    }\n    /* Add 1% linear poln if fitting on init \n       if (init && in->souFit[i][1]) {\n       in->souParm[i*4+1] = 0.01*in->souParm[i*4];\n       }*/\n   \n  } /* end loop over source */\n  \n  /* Cleanup */\n cleanup:\n  /* Close data */\n  ObitUVClose (inUV, err);\n  if (err->error) Obit_traceback_msg (err, routine, inUV->name);\n\n  /* Set iChan, *iIF for next */\n  if ((*iChan)>nChan) {  /* Done with IF? */\n    (*iChan) = 1;\n    (*iIF)++;\n  }\n\n  /* Average Ipol flux densities */\n  for (i=0; i<in->nsou; i++) {\n    if (cntFlux[i]>0) in->souFlux[i] = sumFlux[i]/cntFlux[i];\n    else              in->souFlux[i] = 0.0;\n  }\n  if (cntFlux) g_free(cntFlux); cntFlux = NULL;\n  if (sumFlux) g_free(sumFlux); sumFlux = NULL;\n\n  return; \n} /* end ReadData */\n\n/**\n * Initialize new Source poln.(CP) table\n * All zero entries\n * \\param in    Fitting object\n * \\param err   Obit error stack object.\n */\nstatic void InitSourceTab(ObitPolnCalFit* in, ObitErr *err) \n{\n  olong i, irow, nif, nchan, isou;\n  ObitTableCPRow *row=NULL;\n  gchar *routine = \"ObitPolnCalFit:InitSourceTab\";\n  \n  /* Clear any existing rows */\n  ObitTableClearRows ((ObitTable*)in->CPTable, err);\n\n  /* Open  */\n  ObitTableCPOpen (in->CPTable, OBIT_IO_ReadWrite, err);\n  if (err->error) Obit_traceback_msg (err, routine, in->name);\n\n  /* define row */\n  row = newObitTableCPRow(in->CPTable);\n  ObitTableCPSetRow (in->CPTable, row, err);\n  if (err->error) Obit_traceback_msg (err, routine, in->name);\n \n  /* Set header values */\n  in->CPTable->FreqID = 0;\n\n  if (in->outDesc->jlocif>=0) nif = in->outDesc->inaxes[in->outDesc->jlocif];\n  else                       nif = 1;\n  nchan = in->outDesc->inaxes[in->outDesc->jlocf];\n\n /* Initialize Row */\n  row->SourID = 0;\n  for (i=0; i<nif*nchan; i++) row->IPol[i] = 0.0;\n  for (i=0; i<nif*nchan; i++) row->QPol[i] = 0.0;\n  for (i=0; i<nif*nchan; i++) row->UPol[i] = 0.0;\n  for (i=0; i<nif*nchan; i++) row->VPol[i] = 0.0;\n\n  /* Loop over sources writing */\n  for (isou=0; isou<in->nsou; isou++) {\n    row->SourID = in->souIDs[isou];\n    irow = -1;\n    ObitTableCPWriteRow (in->CPTable, irow, row, err);\n    if (err->error) Obit_traceback_msg (err, routine, in->name);\n  } /* End loop onver source writing */\n\n  /* Close */\n  ObitTableCPClose (in->CPTable, err);\n  if (err->error) Obit_traceback_msg (err, routine, in->name);\n\n  row = ObitTableCPRowUnref(row);  /* Cleanup */\n\n} /* end InitSourceTab */\n\n/**\n * Initialize new Instrumental poln.(PD) table\n * All zero entries\n * \\param in    Fitting object\n * \\param err   Obit error stack object.\n */\nstatic void InitInstrumentalTab(ObitPolnCalFit* in, ObitErr *err) \n{\n  olong i, irow, iant, npol, nif, nchan;\n  ObitTablePDRow *row=NULL;\n  gchar *routine = \"ObitPolnCalFit:InitInstrumentalTab\";\n  \n  /* Clear any existing rows */\n  ObitTableClearRows ((ObitTable*)in->PDTable, err);\n\n  /* Open Write only */\n  ObitTablePDOpen (in->PDTable, OBIT_IO_ReadWrite, err);\n  if (err->error) Obit_traceback_msg (err, routine, in->name);\n\n  /* define row */\n  row = newObitTablePDRow(in->PDTable);\n  ObitTablePDSetRow (in->PDTable, row, err);\n  if (err->error) Obit_traceback_msg (err, routine, in->name);\n \n  /* Set header values */\n  in->PDTable->numAnt = in->nant;\n  /* Mark soln type */\n  strncpy (in->PDTable->polType, \"ORI-ELP\", MAXKEYCHARTABLEPD);\n\n  if (in->outDesc->jlocif>=0) nif = in->outDesc->inaxes[in->outDesc->jlocif];\n  else                        nif = 1;\n  nchan = in->outDesc->inaxes[in->outDesc->jlocf];\n  npol  = MIN (2,in->outDesc->inaxes[in->outDesc->jlocs]);\n\n /* Initialize Row */\n  /*  row->SourID  = 0;*/\n  row->antNo   = 0;\n  row->SubA    = 0;\n  row->FreqID  = 0;\n  row->RefAnt  = in->refAnt;\n  for (i=0; i<nif*nchan; i++) row->RLPhase[i] = 0.0;\n  /* Circular feed default */\n  if (in->isCircFeed) {\n    for (i=0; i<nif*nchan; i++) row->Real1[i] = G_PI/4.0;\n    for (i=0; i<nif*nchan; i++) row->Imag1[i] = 0.0;\n    if (npol>1) {\n      for (i=0; i<nif*nchan; i++) row->Real2[i] = -G_PI/4.0;\n      for (i=0; i<nif*nchan; i++) row->Imag2[i] = 0.0;\n    }\n  } else {\n    /* Linear feeds  ori_x, elip_x, ori_y, elip_y,  */\n    for (i=0; i<nif*nchan; i++) row->Real1[i] = 0.0;\n    for (i=0; i<nif*nchan; i++) row->Imag1[i] = G_PI/4.0;\n    if (npol>1) {\n      for (i=0; i<nif*nchan; i++) row->Real2[i] = 0.0;\n      for (i=0; i<nif*nchan; i++) row->Imag2[i] = 0.0;\n    }\n  } \n\n  /* Loop over antennas writing */\n  for (iant=0; iant<in->nant; iant++) {\n    row->antNo = iant+1;\n    irow = -1;\n    ObitTablePDWriteRow (in->PDTable, irow, row, err);\n    if (err->error) Obit_traceback_msg (err, routine, in->name);\n  } /* End loop over source writing */\n\n  /* Close */\n  ObitTablePDClose (in->PDTable, err);\n  if (err->error) Obit_traceback_msg (err, routine, in->name);\n\n  row = ObitTablePDRowUnref(row);  /* Cleanup */\n\n} /* end InitInstrumentalTab */\n\n/**\n * Initialize new Bandpass.(BP) table \n * All zero entries\n * \\param in    Fitting object\n * \\param err   Obit error stack object.\n */\nstatic void InitBandpassTab(ObitPolnCalFit* in, ObitErr *err) \n{\n  olong i, irow, iant, npol, nif, nchan, nant;\n  ObitUVDesc *desc;\n  ObitTableBPRow *row=NULL;\n  gchar *routine = \"ObitPolnCalFit:InitBandpassTab\";\n  \n  /* Initialize */\n  nant  = in->nant;\n  if (in->outDesc->jlocif>=0) nif = in->outDesc->inaxes[in->outDesc->jlocif];\n  else                       nif = 1;\n  nchan = in->outDesc->inaxes[in->outDesc->jlocf];\n  npol  = MIN (2,in->outDesc->inaxes[in->outDesc->jlocs]);\n\n  /* Clear any existing rows */\n  ObitTableClearRows ((ObitTable*)in->BPTable, err);\n\n  /* Open  */\n  ObitTableBPOpen (in->BPTable, OBIT_IO_ReadWrite, err);\n  if (err->error) Obit_traceback_msg (err, routine, in->name);\n\n  /* define row */\n  row = newObitTableBPRow(in->BPTable);\n  ObitTableBPSetRow (in->BPTable, row, err);\n  if (err->error) Obit_traceback_msg (err, routine, in->name);\n \n  /* Set header values */\n  in->BPTable->numAnt = nant;\n\n  /* Initialize Row */\n  desc = (ObitUVDesc*)in->outDesc;\n  row->BW           = desc->cdelt[desc->jlocf];\n  row->ChanShift[0] = 0.0;\n  row->ChanShift[1] = 0.0;\n  row->RefAnt1      = in->refAnt;\n  row->RefAnt2      = in->refAnt;\n  row->SubA         = 0;\n  row->FreqID       = 0;\n  row->TimeI        = 24.0;\n  row->SourID       = 0;\n  for (i=0; i<nif; i++) row->ChanShift[i] = 0.0;\n  for (i=0; i<nif; i++) row->Weight1[i]   = 1.0;\n  if (npol>1) for (i=0; i<nif; i++) row->Weight2[i] = 1.0;\n  for (i=0; i<nchan*nif; i++) { \n    row->Real1[i]   = 1.0;\n    row->Imag1[i]   = 0.0;\n    if (npol>1) {\n      row->Real2[i]   = 1.0;\n      row->Imag2[i]   = 0.0;\n    }\n  }\n  /* Loop over antennas writing */\n  for (iant=0; iant<in->nant; iant++) {\n    row->antNo = iant+1;\n    irow = -1;\n    ObitTableBPWriteRow (in->BPTable, irow, row, err);\n    if (err->error) Obit_traceback_msg (err, routine, in->name);\n  } /* End loop onver source writing */\n\n  /* Close */\n  ObitTableBPClose (in->BPTable, err);\n  if (err->error) Obit_traceback_msg (err, routine, in->name);\n\n  row = ObitTableBPRowUnref(row);  /* Cleanup */\n\n\n} /* end InitBandpassTab */\n\n/**\n * Update Source poln.(CP) table\n * Results obtained from in\n * \\param in    Fitting object\n * \\param err   Obit error stack object.\n */\nstatic void UpdateSourceTab(ObitPolnCalFit* in, ObitErr *err) \n{\n  olong irow, nchan, indx, ich, iif, isou, jsou;\n  olong chanOff=in->BChan-1, ifOff=in->BIF-1, chans[2];\n  ObitTableCPRow *row=NULL;\n  gchar *routine = \"ObitPolnCalFit:UpdateSourceTab\";\n  \n  /* Open */\n  ObitTableCPOpen (in->CPTable, OBIT_IO_ReadWrite, err);\n  if (err->error) Obit_traceback_msg (err, routine, in->name);\n  \n  /* define row */\n  row = newObitTableCPRow(in->CPTable);\n  ObitTableCPSetRow (in->CPTable, row, err);\n  if (err->error) Obit_traceback_msg (err, routine, in->name);\n \n  nchan = in->outDesc->inaxes[in->outDesc->jlocf];\n\n  /* 0-rel Channels covered in ChInc */\n  chans[0] = in->Chan-1+chanOff - in->ChInc/2;\n  chans[0] = MAX (0, chans[0]);\n  chans[1] = in->Chan-1+chanOff + in->ChInc/2;\n  chans[1] = MIN (nchan-1, chans[1]);\n  \n  /* Loop over row updating */\n  for (irow=1; irow<=in->CPTable->myDesc->nrow; irow++) {\n    /* Read previous */\n    ObitTableCPReadRow (in->CPTable, irow, row, err);\n    if (err->error) Obit_traceback_msg (err, routine, in->name);\n\n    isou = row->SourID - 1;\n    jsou = in->isouIDs[isou];  /* Calibrator number */\n\n    /* Loop over chans */\n    for (ich=chans[0]; ich<=chans[1]; ich++) {\n      iif = in->IFno-1+ifOff;    /* 0 rel IF */\n      indx = iif*nchan + ich;\n      row->IPol[indx] = in->souParm[jsou*4+0];\n      row->QPol[indx] = in->souParm[jsou*4+1];\n      row->UPol[indx] = in->souParm[jsou*4+2];\n      row->VPol[indx] = in->souParm[jsou*4+3];\n    } /* end loop over channels */\n\n    /* Rewrite */\n    ObitTableCPWriteRow (in->CPTable, irow, row, err);\n    if (err->error) Obit_traceback_msg (err, routine, in->name);\n  } /* End loop onver source writing */\n\n  /* Close */\n  ObitTableCPClose (in->CPTable, err);\n  if (err->error) Obit_traceback_msg (err, routine, in->name);\n\n  row = ObitTableCPRowUnref(row);  /* Cleanup */\n\n} /* end UpdateSourceTab */\n\n/**\n * Update Instrumental poln.(PD) table\n * if in->doBlank, blank failed solutions, else noop\n * \\param in    Fitting object\n * \\param isOK  was fitting successful?\n * \\param err   Obit error stack object.\n */\nstatic void UpdateInstrumentalTab(ObitPolnCalFit* in, gboolean isOK, \n\t\t\t\t  ObitErr *err) \n{\n  olong irow, npol, nchan, indx, ich, iif, iant;\n  ofloat fblank = ObitMagicF();\n  olong chanOff=in->BChan-1, ifOff=in->BIF-1, chans[2];\n  ObitTablePDRow *row=NULL;\n  gchar *routine = \"ObitPolnCalFit:UpdateInstrumentalTab\";\n  \n  /* If doBlank FALSE and this one failed, simple return */\n  if (!isOK && (in->doBlank==FALSE)) return;\n  \n  /* Open */\n  ObitTablePDOpen (in->PDTable, OBIT_IO_ReadWrite, err);\n  if (err->error) Obit_traceback_msg (err, routine, in->name);\n\n  /* define row */\n  row = newObitTablePDRow(in->PDTable);\n  ObitTablePDSetRow (in->PDTable, row, err);\n  if (err->error) Obit_traceback_msg (err, routine, in->name);\n \n  nchan = in->outDesc->inaxes[in->outDesc->jlocf];\n  npol  = MIN (2,in->outDesc->inaxes[in->outDesc->jlocs]);\n\n  /* 0-rel Channels covered in ChInc */\n  chans[0] = in->Chan-1+chanOff - in->ChInc/2;\n  chans[0] = MAX (0, chans[0]);\n  chans[1] = in->Chan-1+chanOff + in->ChInc/2;\n  chans[1] = MIN (nchan-1, chans[1]);\n  /* Fill orphans at end */\n  if ((nchan-chans[1]-1)>in->ChInc) chans[1] = nchan-1;\n  \n  /* Loop over row updating */\n  for (irow=1; irow<=in->PDTable->myDesc->nrow; irow++) {\n    /* Read previous */\n    ObitTablePDReadRow (in->PDTable, irow, row, err);\n    if (err->error) Obit_traceback_msg (err, routine, in->name);\n\n    iant = row->antNo - 1;\n\n    /* Update */\n    /* Loop over chans */\n    for (ich=chans[0]; ich<=chans[1]; ich++) {\n      iif = in->IFno-1+ifOff;  /* 0 rel IF */\n      indx = iif*nchan + ich;\n      \n         /* OK solution? */\n      if (isOK && in->gotAnt[iant]) {\n\t/* row->RLPhase[indx] = in->PD*RAD2DG;  R-L phase difference */\n\trow->Real1[indx]   = in->antParm[iant*4+1];\n\trow->Imag1[indx]   = in->antParm[iant*4+0];\n\tif (npol>1) {\n\t  row->Real2[indx] = in->antParm[iant*4+3];\n\t  row->Imag2[indx] = in->antParm[iant*4+2];\n\t}\n      } else { /* failed solution */\n\trow->RLPhase[indx] = fblank;\n\trow->Real1[indx]   = fblank;\n\trow->Imag1[indx]   = fblank;\n\tif (npol>1) {\n\t  row->Real2[indx] = fblank;\n\t  row->Imag2[indx] = fblank;\n\t}\n      }\n    } /* end loop over channels */\n    /* Rewrite */\n    ObitTablePDWriteRow (in->PDTable, irow, row, err);\n    if (err->error) Obit_traceback_msg (err, routine, in->name);\n  } /* End loop over antenna writing */\n\n  /* Close */\n  ObitTablePDClose (in->PDTable, err);\n  if (err->error) Obit_traceback_msg (err, routine, in->name);\n\n  row = ObitTablePDRowUnref(row);  /* Cleanup */\n\n} /* end UpdateInstrumentalTab */\n\n/**\n * Update Bandpass (BP) table\n * if in->doBlank, blank failed solutions, else noop\n * \\param in    Fitting object\n * \\param isOK  was fitting successful?\n * \\param err   Obit error stack object.\n */\nstatic void UpdateBandpassTab(ObitPolnCalFit* in, gboolean isOK, ObitErr *err) \n{\n  olong irow, npol, nchan, indx, ich, iif, iant;\n  ofloat amp1, amp2, pre, pim, fblank = ObitMagicF();\n  ObitTableBPRow *row=NULL;\n  olong chanOff=in->BChan-1, ifOff=in->BIF-1, chans[2];\n  gchar *routine = \"ObitPolnCalFit:UpdateBandpassTab\";\n  \n  /* If doBlank FALSE and this one failed, simple return */\n  if (!isOK && (in->doBlank==FALSE)) return;\n  \n  /* Open */\n  ObitTableBPOpen (in->BPTable, OBIT_IO_ReadWrite, err);\n  if (err->error) Obit_traceback_msg (err, routine, in->name);\n\n  /* define row */\n  row = newObitTableBPRow(in->BPTable);\n  ObitTableBPSetRow (in->BPTable, row, err);\n  if (err->error) Obit_traceback_msg (err, routine, in->name);\n \n  nchan = in->outDesc->inaxes[in->outDesc->jlocf];\n  npol  = MIN (2,in->outDesc->inaxes[in->outDesc->jlocs]);\n\n  /* 0-rel Channels covered in ChInc */\n  chans[0] = in->Chan-1+chanOff - in->ChInc/2;\n  chans[0] = MAX (0, chans[0]);\n  chans[1] = in->Chan-1+chanOff + in->ChInc/2;\n  chans[1] = MIN (nchan-1, chans[1]);\n  /* Fill orphans at end */\n  if ((nchan-chans[1]-1)>in->ChInc) chans[1] = nchan-1;\n\n  /* Phase difference */\n  pre = cos(in->PD); pim = sin(-in->PD);\n\n  /* Loop over row updating */\n  for (irow=1; irow<=in->BPTable->myDesc->nrow; irow++) {\n    /* Read previous */\n    ObitTableBPReadRow (in->BPTable, irow, row, err);\n    if (err->error) Obit_traceback_msg (err, routine, in->name);\n\n    iant = row->antNo - 1;\n    /* Amplitudes of gains */\n    if (in->doFitGain && in->antGain) {  /* Inverse? */\n      /*{amp1 = 1.0/in->antGain[iant*2];amp2 = 1.0/in->antGain[iant*2+1];}*/\n      {amp1 = in->antGain[iant*2];amp2 = in->antGain[iant*2+1];}\n      /* Divide the correction between pol1 and pol 2 \n      amp1 = 1.0/sqrt(in->antGain[iant*2+1]);\n      amp2 =     sqrt(in->antGain[iant*2+1]);*/\n    } else {amp1 = 1.0; amp2 = 1.0;}\n\n    /* Update */\n    /* Loop over chans */\n    for (ich=chans[0]; ich<=chans[1]; ich++) {\n      iif = in->IFno-1+ifOff;  /* 0 rel IF */\n      indx = iif*nchan + ich;\n      \n      if (isOK && in->gotAnt[iant]) {\n\trow->Real1[indx] = amp1;\n\trow->Imag1[indx] = 0.0;\n\tif (npol>1) {\n\t  row->Real2[indx] = amp2*pre;\n\t  row->Imag2[indx] = pim;\n\t}\n      } else { /* failed solution */\n\trow->Real1[indx] = fblank;\n\trow->Imag1[indx] = fblank;\n\tif (npol>1) {\n\t  row->Real2[indx] = fblank;\n\t  row->Imag2[indx] = fblank;\n\t}\n      }\n      } /* end loop over channels */\n    /* Rewrite */\n    ObitTableBPWriteRow (in->BPTable, irow, row, err);\n    if (err->error) Obit_traceback_msg (err, routine, in->name);\n  } /* End loop onver source writing */\n\n  /* Close */\n  ObitTableBPClose (in->BPTable, err);\n  if (err->error) Obit_traceback_msg (err, routine, in->name);\n\n  row = ObitTableBPRowUnref(row);  /* Cleanup */\n\n} /* end UpdateBandpassTab */\n\n/**\n * Fit spectra to calibrator IPol flux densities in Source list\n * \\param in       Fitting object\n * \\param err      Obit error stack object.\n */\nstatic void FitSpectra (ObitPolnCalFit *in, ObitErr *err)\n  {\n    ofloat *parms=NULL, *sigma=NULL;\n    olong i, isou, jsou, nterm=3, nfreq;\n    gchar *routine=\"ObitPolnCalFit:FitSpectra\";\n\n    if (err->error) return;  /* Error exists? */\n\n    /* Dummy error array */\n    if (in->inDesc->jlocif>=0) nfreq = in->inDesc->inaxes[in->inDesc->jlocif];\n    else                       nfreq = 1;\n    sigma = g_malloc(nfreq*sizeof(ofloat));\n    for (i=0; i<nfreq; i++) sigma[i] = 0.01;\n    nterm = MIN (3, nfreq);\n\n    /* Loop over calibrators */\n    for (isou=0; isou<in->nsou; isou++) {\n      jsou = MAX (1, in->souIDs[isou]);  /* Source ID in data */\n      parms = ObitSpectrumFitSingle (nfreq, nterm, in->inDesc->freq, \n\t\t\t\t     in->inDesc->freqIF, \n\t\t\t\t     in->SouList->SUlist[jsou-1]->IFlux, sigma, \n\t\t\t\t     FALSE, err);\n      if (err->error) Obit_traceback_msg (err, routine, in->name);\n      in->IFlux0[isou] = parms[0];\n      in->IFlux1[isou] = parms[1];\n      in->IFlux2[isou] = parms[2];\n      g_free(parms);\n    }\n\n    if (sigma) g_free(sigma);\n } /* end FitSpectra */\n\n/**\n * Determine Fit Poln parameters\n * Uses GSL nonlinear solver\n * \\param in    Fitting object\n * \\param err   Obit error stack object.\n */\nstatic void doFitGSL (ObitPolnCalFit *in, ObitErr *err)\n{\n  /*odouble difParam, difChi2=0.0, endChi2=0.0;*/\n  ofloat fpol, fpa;\n  olong isou=0, iant, i, k=0, iter;\n  olong nparam, ndata, nvalid, nvis, j;\n  odouble sumwt, chi2Test=0.0; \n  double epsabs=1.0e-5, epsrel=1.0e-4;  /* Stopping criteria */\n  olong maxIter=10;                     /* Stopping criteria */\n  int status;\n  ofloat chi2, initChi2, ParRMS, XRMS;\n  gchar *routine=\"ObitPolnCalFit:doFitGSL\";\n\n#ifdef HAVE_GSL\n  gsl_multifit_fdfsolver *solver = in->solver;\n  gsl_matrix *covar              = in->covar;\n  gsl_vector *work               = in->work;\n  gsl_matrix *J;\n\n  if (err->error) return;  /* Error exists? */\n  \n  /* Set initial parameters */\n  /* first antenna */\n  for (iant=0; iant<in->nant; iant++) {\n    /* Loop over parameters */\n    for (k=0; k<4; k++) {\n      /* Fitting? */\n      if ((in->antFit[iant][k]) && (in->gotAnt[iant])) {\n\tj = in->antPNumb[iant][k];\n\tgsl_vector_set(work, j, in->antParm[iant*4+k]);\n      }\n    } /* end loop over parameters */\n  } /* end loop over antennas */\n\n    /* Antenna gains if needed */\n  if (!in->isCircFeed && in->doFitGain) {\n    for (iant=0; iant<in->nant; iant++) {\n      if (in->gotAnt[iant]) {\n\t/* Loop over parameters */\n\tfor (k=0; k<2; k++) {\n\t  /* Fitting? */\n\t  if (in->antGainFit[iant][k]) {\n\t    j = in->antGainPNumb[iant][k];\n\t    gsl_vector_set(work, j, in->antGain[iant*2+k]);\n\t  } \n\t} /* end loop over parameters */\n      } /* end if gotAnt */\n    } /* end loop over antennas */\n  } /* End if antenna gains */\n  \n  /* now source */\n  for (isou=0; isou<in->nsou; isou++) {\n    /* Loop over parameters */\n    for (k=0; k<4; k++) {\n      /* Fitting? */\n      if (in->souFit[isou][k]) {\n\tj = in->souPNumb[isou][k];\n\tgsl_vector_set(work, j, in->souParm[isou*4+k]);\n      }\n    } /* end loop over parameters */\n  } /* end loop over sources */\n\n  /* Phase difference  if being fitted */\n  if (in->doFitRL) {\n    j = in->PDPNumb;\n    gsl_vector_set(work, j, in->PD);\n  }\n\n  /* Set up fitting */\n  nparam                = in->nparam;\n  ndata                 = in->ndata;\n  nvis                  = in->nvis;\n  in->funcStruc->n      = ndata;\n  in->funcStruc->p      = nparam;\n  in->funcStruc->params = in;\n  iter = 0;\n\n  /* init solver */\n  gsl_multifit_fdfsolver_set (solver, in->funcStruc, work);\n\n  /* initial Chi2 */\n  if (err->prtLv>=3) {\n    initChi2 = GetChi2 (in->nThread, in, polnParmUnspec, 0, \n\t\t\t&ParRMS, &XRMS, NULL, NULL, err);\n    Obit_log_error(err, OBIT_InfoErr, \n\t\t   \"Initial LM Chi2=%g Par RMS %g X RMS %g \", \n\t\t   initChi2, ParRMS, XRMS);\n    if (err->error) Obit_traceback_msg (err, routine, \"diagnostic\");\n  } /* end initial Chi2 */\n\n  /* iteration loop */\n  do {\n    iter++;\n    status = gsl_multifit_fdfsolver_iterate(solver);\n\n    /* current  Chi2 */\n    if (err->prtLv>=3) {\n      chi2 = GetChi2 (in->nThread, in, polnParmUnspec, 0, \n\t\t      &ParRMS, &XRMS, NULL, NULL, err);\n    Obit_log_error(err, OBIT_InfoErr, \n\t\t   \"current LM Chi2=%g Par RMS %g X RMS %g\", \n\t\t   chi2, ParRMS, XRMS);\n    if (err->error) Obit_traceback_msg (err, routine, \"diagnostic\");\n  } /* end Chi2 */\n\n    /* Diagnostics */\n    if (err->prtLv>=5) {\n      sumwt = (ofloat)gsl_blas_dnrm2(solver->f);\n      /*Obit_log_error(err, OBIT_InfoErr,\"iter %d status %d ant 1 %g %g %g %g sumwt %f\", \n\titer, status, in->antParm[0], in->antParm[1], in->antParm[2], in->antParm[3], sumwt); */\n      Obit_log_error(err, OBIT_InfoErr,\"iter %d status %d grad norm %f\", \n\t\t     iter, status, sumwt);\n      ObitErrLog(err); \n    }     /* end  Diagnostics */\n\n    /* Minimum of two iterations */\n    if (iter<2) status = GSL_CONTINUE;\n\n    /* Convergence test */    \n    if (iter>1)\n      status = gsl_multifit_test_delta (solver->dx, solver->x, \n\t\t\t\t\tepsabs, epsrel);\n  } while ((status==GSL_CONTINUE) && (iter<maxIter));\n  \n /* If it didn't work - bail */\n  if ((status!=GSL_SUCCESS) && (status!=GSL_CONTINUE)) {\n    fprintf (stderr, \"Failed, status = %s\\n\", gsl_strerror(status));\n    goto done;\n  }\n\n  /* Get fitting results - fixed parameters will still be in the arrays */\n  /* first antennas */\n  for (iant=0; iant<in->nant; iant++) {\n    /* Loop over parameters */\n    for (k=0; k<4; k++) {\n      /* Fitting? */\n      if ((in->antFit[iant][k])  && (in->gotAnt[iant])) {\n\tj = in->antPNumb[iant][k];\n\tin->antParm[iant*4+k] = gsl_vector_get(solver->x, j);\n\t/* if ((k==0) || (k==2))  undo wraps */\n\tin->antParm[iant*4+k] = fmod(in->antParm[iant*4+k], 2*G_PI);\n\tif (in->antParm[iant*4+k]>G_PI) in->antParm[iant*4+k] -= 2*G_PI;\n      }\n    } /* end loop over parameters */\n  } /* end loop over antennas */\n\n  /* Antenna gains if needed */\n  if (!in->isCircFeed && in->doFitGain) {\n    for (iant=0; iant<in->nant; iant++) {\n      if (in->gotAnt[iant]) {\n\t/* Loop over parameters */\n\tfor (k=0; k<2; k++) {\n\t  /* Fitting? */\n\t  if (in->antGainFit[iant][k]) {\n\t    j = in->antGainPNumb[iant][k];\n\t    in->antGain[iant*2+k] = gsl_vector_get(solver->x, j);\n\t  }\n\t} /* end loop over parameters */\n      } /* end if gotAnt */\n    } /* end loop over antennas */\n  } /* End if antenna gains */\n  \n  /* now source */\n  for (isou=0; isou<in->nsou; isou++) {\n    /* Loop over parameters */\n    for (k=0; k<4; k++) {\n      /* Fitting? */\n      if (in->souFit[isou][k]) {\n\tj = in->souPNumb[isou][k];\n\tin->souParm[isou*4+k] = gsl_vector_get(solver->x, j);\n      }\n    } /* end loop over parameters */\n  } /* end loop over sources */\n\n  if (in->doFitRL) {\n    j = in->PDPNumb;\n    in->PD = gsl_vector_get(solver->x, j);\n  }\n  /* Errors */\n  if (in->doError) {\n    /* Get covariance matrix - extract diagonal terms */\n    J = gsl_matrix_alloc(in->ndata, in->nparam);\n#ifdef HAVE_GSL_MULTIFIT_FDFSOLVER_JAC\n    gsl_multifit_fdfsolver_jac(solver, J);\n#else\n    gsl_matrix_memcpy(J, solver->J);\n#endif\n    gsl_multifit_covar (J, 0.0, covar);\n    gsl_matrix_free(J);\n    for (iant=0; iant<in->nant; iant++) {\n      /* Loop over antenna parameters */\n      for (k=0; k<4; k++) {\n\t/* Fitting? */\n\tif ((in->antFit[iant][k])  && (in->gotAnt[iant])) {\n\t  j = in->antPNumb[iant][k];\n\t  in->antErr[iant*4+k] =  sqrt(gsl_matrix_get(covar, j, j));\n\t} else in->antErr[iant*4+k] =  -1.0;\n      } /* end loop over parameters */\n    } /* end loop over antennas */\n    \n    /* Antenna gains if needed */\n    if (!in->isCircFeed && in->doFitGain) {\n      for (iant=0; iant<in->nant; iant++) {\n\tif (in->gotAnt[iant]) {\n\t  /* Loop over parameters */\n\t  for (k=0; k<2; k++) {\n\t    /* Fitting? */\n\t    if (in->antGainFit[iant][k]) {\n\t      j = in->antGainPNumb[iant][k];\n\t      in->antGainErr[iant*2+k] =  sqrt(gsl_matrix_get(covar, j, j));\n\t    } else in->antGainErr[iant*2+k] =  -1.0;\n\t  } /* end loop over parameters */\n\t} /* end if gotAnt */\n      } /* end loop over antennas */\n    } /* End if antenna gains */\n\n    /* now source */\n    for (isou=0; isou<in->nsou; isou++) {\n      /* Loop over parameters */\n      for (k=0; k<4; k++) {\n\t/* Fitting? */\n\tif (in->souFit[isou][k]) {\n\t  j = in->souPNumb[isou][k];\n\t  in->souErr[isou*4+k] =  sqrt(gsl_matrix_get(covar, j, j));\n\t} else in->souErr[isou*4+k] = -1.0;\n      } /* end loop over parameters */\n    } /* end loop over sources */\n\n    /* Now phase difference */\n    if (in->doFitRL) {\n      j = in->PDPNumb;\n      in->PDerr = sqrt(gsl_matrix_get(covar, j, j));\n    }\n\n    /* Count valid data */\n    nvalid = 0;\n    for (i=0; i<nvis*4; i++) if (in->inWt[i]>0.0) nvalid++;\n    \n    /* normalized Chi squares */\n    if (nvalid>nparam) {\n      sumwt = (ofloat)gsl_blas_dnrm2(solver->f);\n      chi2Test = (sumwt*sumwt)/(nvalid-nparam);\n    } else chi2Test = -1.0;\n    \n    in->ChiSq = chi2Test;\n  } /* end do error */\n\n    /* Diagnostics */\n done:\n  if (err->prtLv>=2) {\n    Obit_log_error(err, OBIT_InfoErr, \"%d iter LM fit\", iter);\n    for (isou=0; isou<in->nsou; isou++) {\n      fpol = sqrt (in->souParm[isou*4+1]*in->souParm[isou*4+1] + in->souParm[isou*4+2]*in->souParm[isou*4+2]) /\n\tin->souParm[isou*4+0];\n      fpa = 57.296*atan2(in->souParm[isou*4+2], in->souParm[isou*4+1]);\n      Obit_log_error(err, OBIT_InfoErr, \n\t\t     \"sou %3d %8.4f (%8.4f) %8.4f (%8.4f) %8.4f (%8.4f) %8.4f (%8.4f)\", \n\t\t     isou+1, in->souParm[isou*4+0], in->souErr[isou*4+0], \n\t\t     in->souParm[isou*4+1], in->souErr[isou*4+1],\n\t\t     in->souParm[isou*4+2], in->souErr[isou*4+2], \n\t\t     in->souParm[isou*4+3], in->souErr[isou*4+3]);\n      Obit_log_error(err, OBIT_InfoErr, \n\t\t     \"        (fpol %6.4f %s %6.2f\", fpol, \"@\", fpa);\n    }\n    \n    for (iant=0; iant<in->nant; iant++) {\n      if (in->gotAnt[iant]) {\n\tObit_log_error(err, OBIT_InfoErr, \n\t\t       \"ant %3d %8.2f (%8.2f) %8.2f (%8.2f) %8.2f (%8.2f) %8.2f (%8.2f)\", \n\t\t       iant+1, in->antParm[iant*4+0]*57.296, MAX(-1.0, in->antErr[iant*4+0]*57.296), \n\t\t       in->antParm[iant*4+1]*57.296, MAX(-1.0, in->antErr[iant*4+1]*57.296), \n\t\t       in->antParm[iant*4+2]*57.296, MAX(-1.0, in->antErr[iant*4+2]*57.296), \n\t\t       in->antParm[iant*4+3]*57.296, MAX(-1.0, in->antErr[iant*4+3]*57.296));\n      }\n    }\n    /* Phase differrence */\n    if (in->doFitRL) {\n      Obit_log_error(err, OBIT_InfoErr, \n\t\t     \"Phase difference %8.2f (%8.2f)\",in->PD*57.296,in->PDerr*57.296);\n    }\n\n    /* Antenna gain if fitted */\n    if (!in->isCircFeed && in->doFitGain) {\n      for (iant=0; iant<in->nant; iant++) {\n\tif (in->gotAnt[iant]) {\n\t  Obit_log_error(err, OBIT_InfoErr, \n\t\t\t \"ant %3d gain X %6.3f (%6.3f) Y %6.3f (%6.3f)\", \n\t\t\t iant+1, in->antGain[iant*2+0], in->antGainErr[iant*2+0],\n\t\t\t in->antGain[iant*2+1], in->antGainErr[iant*2+1]);\n\t}\n      }\n    } /* end antenna gain */\n  } /* end diagnostics */\n  ObitErrLog(err); \n\n#endif /* HAVE_GSL */ \n return;\n } /* end doFitGSL */\n\n/**\n * Determine Fit Poln parameters\n * Solution uses a relaxation method from Fred Schwab:  \n * Pn+1 = Pn + atan2 (dChi2/dP), (d2Chi2/dP2))  \n * for each parameter P where n or n+1 indicates a given iteration,   \n * dChi2/dP is the first partial derivative of Chi squared wrt P,  \n * d2Chi2/d2P is the second partial derivative of Chi squared wrt P,  \n * Chi2 = Sum (w (model-obs)**2)\n * \\param in    Fitting object\n * \\param err   Obit error stack object.\n * \\return TRUE if worked, else FALSE.\n */\nstatic gboolean doFitFast (ObitPolnCalFit *in, ObitErr *err)\n{\n  odouble begChi2, endChi2=0.0, iChi2, tChi2, deriv=0.0, deriv2=1.0;\n  odouble difParam, difChi2=0.0, hiChi2=0.0, dChi2, d2Chi2;\n  ofloat tParam, sParam, delta, sdelta = 0.02;\n  ofloat ParRMS, XRMS, fpol, fpa, PPol;\n  olong isou=0, iant, i, k=0, iter, maxIter;\n  olong pas=0, ptype=0, pnumb=-1;\n  gchar *routine=\"ObitPolnCalFit:doFitFast\";\n\n  if (err->error) return TRUE;  /* Error exists? */\n  iter = 0; maxIter = 300;\n  while (iter<maxIter) { \n    in->selSou = -1;\n    in->selAnt = -1;\n    begChi2 = GetChi2 (in->nThread, in,  polnParmUnspec, 0,\n\t\t       &ParRMS, &XRMS, NULL, NULL, err);  /* Initial value */\n    if (iter==0) in->initChiSq = begChi2;  /* Save initial */\n    /* Test for valid data */\n    if (begChi2<=0.0) {\n      Obit_log_error(err, OBIT_InfoErr, \"No valid data\");\n      ObitErrLog(err); \n      return FALSE;\n   }\n    hiChi2 = MAX (hiChi2, begChi2);\n    difParam = 0.0; ptype = -1; pnumb = -1; \n    if ((iter==0) &&(err->prtLv>=2)) {\n      /*hiChi2 = begChi2;  WHAT???*/\n      Obit_log_error(err, OBIT_InfoErr, \"Initial Chi2=%g Parallel RMS %g Cross RMS %g\", \n\t\t     begChi2, ParRMS, XRMS);\n   }\n\n    /* Fit phase difference? */\n    if (in->doFitRL) {\n      iChi2 = GetChi2 (in->nThread, in, polnParmPD, 0,\n\t\t       &ParRMS, &XRMS, &dChi2, &d2Chi2, err);     /* Initial value */\n      sParam = in->PD;\n      deriv  = dChi2;\n      deriv2 = d2Chi2;\n      if (fabs(deriv2)>(fabs(deriv)*1.0e-4)) {      /* Bother with this one?*/\n\tdelta = -0.5*atan2(deriv, deriv2);\n\t/* Don't go wild */\n\tif (delta>0.) delta = MIN (delta,  20*sdelta);\n\tif (delta<0.) delta = MAX (delta, -20*sdelta);\n\t/* Loop decreasing delta until fit improves */\n\tfor (i=0; i<10; i++) {\n\t  in->PD = sParam + delta;\n\t  tChi2 = GetChi2 (in->nThread, in, polnParmUnspec, 0, \n\t\t\t   &ParRMS, &XRMS, NULL, NULL, err);\n\t  if (tChi2<iChi2) {\n\t    /* Got new value? */\n\t    sParam += delta;\n\t    if (fabs(difParam)<fabs(delta)) {\n\t      ptype = 0; pnumb = 0; pas = 0;\n\t      difParam = delta;\n\t    }\n\t    break;\n\t  }\n\t  delta *= -0.7;  /* Test signs */\n\t  if (fabs(delta)<1.0e-6) break;\n\t} /* end loop decreasing */\n      } \n      in->PD = sParam;   /* Set parameter to new or old value */\n    } /* end  Fit phase difference */\n\n    /* Loop over sources */\n    for (isou=0; isou<in->nsou; isou++) {\n      in->selSou = isou;\n      /* Loop over parameters ipol, qpol, upol, vpol*/\n      for (k=0; k<4; k++) {\n\t/* Fitting? */\n\tif (in->souFit[isou][k]) {\n\t  iChi2 = GetChi2 (in->nThread, in, polnParmSou, k,\n\t     &ParRMS, &XRMS, &dChi2, &d2Chi2, err); /* Initial value */\n\t  sParam = in->souParm[isou*4+k];\n\t  deriv  = dChi2;\n\t  deriv2 = d2Chi2;\n\t  if (fabs(deriv2)>(fabs(deriv)*1.0e-4))      /* Bother with this one?*/\n\t    delta = -0.5*atan2(deriv, deriv2);\n\t  else {in->souParm[isou*4+k] = sParam; continue;}\n\t  if (k<3) delta *= 5;  /* Speed up I,Q, U, slow down V*/\n\t  else {\n\t    delta *= 0.03;\n\t    /* Set bound of 1% of I */\n\t    if (in->souParm[isou*4+k]> 0.01*in->souParm[isou*4]) delta = -delta;\n\t    if (in->souParm[isou*4+k]<-0.01*in->souParm[isou*4]) delta = -delta;\n\t  }\n\t  if (delta>0.) delta = MIN (delta, 20*sdelta);\n\t  if (delta<0.) delta = MAX (delta, -20*sdelta);\n\t  /* Loop decreasing delta until fit improves */\n\t  for (i=0; i<10; i++) {\n\t    in->souParm[isou*4+k] = sParam + delta;\n\t    tChi2 = GetChi2 (in->nThread, in, polnParmUnspec, k, \n\t\t\t     &ParRMS, &XRMS, NULL, NULL, err);\n\t    if (tChi2<iChi2) {\n\t      /* Got new value */\n\t      sParam += delta;\n\t      if (fabs(difParam)<fabs(delta)) {\n\t\tptype = 1; pnumb = k; pas = isou;\n\t\tdifParam = delta;\n\t      }\n\t      break;\n\t    }\n\t    delta *= -0.7;   /* Test signs */\n\t    if (fabs(delta)<1.0e-6) break;\n\t  } /* end loop decreasing */\n\t  in->souParm[isou*4+k] = sParam;   /* Set parameter to new or old value */\n\t} /* end if fitting parameter */ \n\telse if (k==1) { /* Fixed Q poln? */\n\t  if (in->PPol[isou]>0.0) {\n\t    PPol = in->PPol[isou] + in->dPPol[isou]*(in->freq-in->inDesc->freq);\n\t    in->souParm[isou*4+k] = \n\t      PPol * in->souParm[isou*4] * cos(in->RLPhase[isou]);}\n\t} /* end Fixed Q poln */\n\telse if (k==2) { /* Fixed U poln? */\n\t  if (in->PPol[isou]>0.0) {\n\t    PPol = in->PPol[isou] + in->dPPol[isou]*(in->freq-in->inDesc->freq);\n\t    in->souParm[isou*4+k] = \n\t      PPol * in->souParm[isou*4] * sin(in->RLPhase[isou]);}\n\t} /* end Fixed U poln */\n\tif (err->error) Obit_traceback_val (err, routine, in->name, FALSE);\n      } /* end loop over parameters */\n    } /* end loop over sources */\n    in->selSou = -1;\n    \n    /* Antenna gain if fitted */\n    if (!in->isCircFeed && in->doFitGain) {\n      for (iant=0; iant<in->nant; iant++) {\n\tif (!in->gotAnt[iant]) continue;  /* Have data? */\n\tin->selAnt = iant;\n\t/* Loop over parameters, gain_X, Gain_Y */\n\tfor (k=0; k<2; k++) {\n\t  /* Fitting? */\n\t  if (in->antGainFit[iant][k]) {\n\t    iChi2 = GetChi2 (in->nThread, in, polnParmGain, k,\n\t\t\t     &ParRMS, &XRMS, &dChi2, &d2Chi2, err);  /* Initial value */\n\t    if (iChi2<=0.0) continue;\n\t    sParam = in->antGain[iant*2+k];\n\t    deriv  = dChi2;\n\t    deriv2 = d2Chi2;\n\t    if ((fabs(deriv2)>(fabs(deriv)*1.0e-4)) && (fabs(deriv)>(fabs(deriv2)*1.0e-3)))  /* Bother with this one?*/\n\t      delta = -0.5*atan2(deriv, deriv2);\n\t    else {in->antGain[iant*2+k] = sParam; continue;}\n\t    /* Loop decreasing delta until fit improves */\n\t    for (i=0; i<10; i++) {\n\t      tParam = sParam + delta;\n\t      in->antGain[iant*2+k] = tParam;\n\t      tChi2 = GetChi2 (in->nThread, in, polnParmUnspec, k, \n\t\t\t       &ParRMS, &XRMS, NULL, NULL, err);\n\t      if (tChi2<iChi2) {\n\t\t/* Got new value */\n\t\tsParam += delta;\n\t\tif (fabs(difParam)<fabs(delta)) {\n\t\t  ptype = 2; pnumb = k; pas = iant;\n\t\t  difParam = delta;\n\t\t}\n\t\tbreak;\n\t      }\n\t      delta *= -0.7;  /* Test signs */\n\t      if (fabs(delta)<1.0e-6) break;\n\t    } /* end loop decreasing */\n\t    in->antGain[iant*2+k] = sParam;   /* Set parameter to new or old value */\n\t  } else if (k==0) {  /* Not fitting gain_X, use 1.gain_Y */\n\t    in->antGain[iant*2] = 1.0/in->antGain[iant*2+1];\n\t  } /* end if fitting parameter */ \n\t  if (err->error) Obit_traceback_val (err, routine, in->name, FALSE);\n\t} /* end loop over parameters */\n      } /* end loop over antennas */\n    } /* end antenna gain */\n\n    /* Don't change antenna non-gain parameters the first 3 loops */\n    if (iter<3) {iter++; continue;}\n\n    /* Loop over antennas */\n    for (iant=0; iant<in->nant; iant++) {\n      if (!in->gotAnt[iant]) continue;  /* Have data? */\n      in->selAnt = iant;\n      /* Loop over parameters \n\t 0,1 ori, elip (r/x),\n\t 2,3 ori, elip  (l/y),\n      */\n      for (k=0; k<4; k++) {\n\t/* Fitting? */\n\tif (in->antFit[iant][k]) {\n\t  iChi2 = GetChi2 (in->nThread, in, polnParmAnt, k,\n\t\t\t   &ParRMS, &XRMS, &dChi2, &d2Chi2, err);  /* Initial value */\n\t  if (iChi2<=0.0) continue;\n\t  sParam = in->antParm[iant*4+k];\n\t  deriv  = dChi2;\n\t  deriv2 = d2Chi2;\n\t  if ((fabs(deriv2)>(fabs(deriv)*1.0e-4)) && (fabs(deriv)>(fabs(deriv2)*1.0e-3)))  /* Bother with this one?*/\n\t    delta = -0.5*atan2(deriv, deriv2);\n\t  else {in->antParm[iant*4+k] = sParam; continue;}\n\t  if ((k==0) || (k==2)) {  /* Orientation */\n\t    delta *= 5;  /*  Speed up orientation */\n\t    /* But don't go crazy */\n\t    if (delta>0.1)  delta = +0.1;\n\t    if (delta<-0.1) delta = -0.1;\n\t  }\n\t  /* Loop decreasing delta until fit improves */\n\t  for (i=0; i<10; i++) {\n\t    tParam = sParam + delta;\n\t    in->antParm[iant*4+k] = tParam;\n\t    /* Restrict elipticities to [-pi/4, +pi/4] */\n\t    if ((k==1) && (tParam>+0.25*G_PI)) tParam = +0.5*G_PI - tParam;\n\t    if ((k==3) && (tParam<-0.25*G_PI)) tParam = -0.5*G_PI - tParam;\n\t    tChi2 = GetChi2 (in->nThread, in, polnParmUnspec, k, \n\t\t\t     &ParRMS, &XRMS, NULL, NULL, err);\n\t    if (tChi2<iChi2) {\n\t      /* Got new value */\n\t      sParam = tParam;\n\t      sParam = fmod (sParam, 2*G_PI);\n\t      if (sParam> G_PI) sParam -= 2*G_PI;\n\t      if (sParam<-G_PI) sParam += 2*G_PI;\n\t      if (fabs(difParam)<fabs(delta)) {\n\t\tptype = 2; pnumb = k; pas = iant;\n\t\tdifParam = delta;\n\t      }\n\t      break;\n\t    }\n\t    delta *= -0.7;  /* Test signs */\n\t    if (fabs(delta)<1.0e-6) break;\n\t  } /* end loop decreasing */\n\t  if ((k==0) || (k==2)) {  /* Orientation */\n\t    /* Make sure in range +/- 2 pi\n\t    if (sParam>2*G_PI)  sParam -= 2*G_PI;\n\t    if (sParam,-2*G_PI) sParam += 2*G_PI; */\n\t  }\n\t  in->antParm[iant*4+k] = sParam;   /* Set parameter to new or old value */\n\t} /* end if fitting parameter */ \n\tif (err->error) Obit_traceback_val (err, routine, in->name, FALSE);\n      } /* end loop over parameters */\n    } /* end loop over antennas */\n    in->selAnt = -1;\n    \n    in->selSou = -1;\n    in->selAnt = -1;\n    endChi2 = GetChi2 (in->nThread, in, polnParmUnspec, 0, \n\t\t       &ParRMS, &XRMS, NULL, NULL, err);  /* Final value */\n    /* Save (final) values */\n    in->ChiSq = endChi2;\n    in->ParRMS = ParRMS;\n    in->XRMS   = XRMS;\n\n    /*Constrain ellipticities for Lin. Feeds if refAnt<0 */\n    if ((!in->isCircFeed) &&(in->refAnt<0)) {\n      tParam = ConstrLinFeed(in);\n      if (err->prtLv>=5) {  /* Diagnostics */\n\tObit_log_error(err, OBIT_InfoErr, \"iter %d Remove average Ellip =  %g\", \n\t\t       iter+1, tParam);\n\tObitErrLog(err); \n      }\n    } /* end constrain feeds */\n\n    /* Convergence test */\n    difChi2 = fabs(begChi2 - endChi2);\n\n    if ((fabs(difParam)<1.0e-7) || \n      ((fabs(difParam)<5.0e-4)&&(difChi2<=1.0e-6*hiChi2))) break; \n\n    /* Diagnostics */\n    if (err->prtLv>=5) {\n      Obit_log_error(err, OBIT_InfoErr, \n\t\t     \"%d iter Chi2=%g Param %g type %d numb %d sou/ant %d dChi2 %g\", \n\t\t     iter+1, endChi2, difParam, ptype, pnumb, pas, difChi2);\n      ObitErrLog(err); \n   }\n    \n    iter++;\n  } /* end iteration loop */\n  /* Diagnostics */\n  if (err->prtLv>=2) {\n    Obit_log_error(err, OBIT_InfoErr, \n\t\t   \"%d iter relaxation Chi2=%g Par RMS %g X RMS %g \", \n\t\t   iter+1, endChi2, ParRMS, XRMS);\n    /* Don't give fit is using GSL */\n    \n    if (strncmp(in->solnType, \"LM  \", 4) || (err->prtLv>=5)) {\n      Obit_log_error(err, OBIT_InfoErr, \"Phase difference %8.2f\",  in->PD*57.296);\n      for (isou=0; isou<in->nsou; isou++) {\n\tfpol = sqrt (in->souParm[isou*4+1]*in->souParm[isou*4+1] + in->souParm[isou*4+2]*in->souParm[isou*4+2]) /\n\t  in->souParm[isou*4+0];\n\tfpa = 57.296*atan2(in->souParm[isou*4+2], in->souParm[isou*4+1]);\n\tObit_log_error(err, OBIT_InfoErr, \n\t\t       \"sou %3d %8.4f %8.4f %8.4f %8.4f (fpol %6.4f %s %6.2f)\", \n\t\t       isou+1, in->souParm[isou*4+0], in->souParm[isou*4+1], \n\t\t       in->souParm[isou*4+2], in->souParm[isou*4+3], fpol, \"@\", fpa);\n      }\n      if (in->isCircFeed) Obit_log_error(err, OBIT_InfoErr, \n\t\t\t\t\t \"ant    Ori_R    Elp_R    Ori_L    Elp_L    Par RMS    X RMS\");\n      else                Obit_log_error(err, OBIT_InfoErr, \n\t\t\t\t\t \"ant    Ori_X    Elp_X    Ori_Y    Elp_Y    Par RMS    X RMS\");\n    for (iant=0; iant<in->nant; iant++)\n\tif (in->gotAnt[iant]) {\n\t  /* Get RMSes */\n\t  GetRMSes (in->nThread, in, iant, &ParRMS, &XRMS, err);\n\t  Obit_log_error(err, OBIT_InfoErr, \n\t\t\t \"%3d %8.2f %8.2f %8.2f %8.2f  %10.7f %10.7f\", \n\t\t\t iant+1, in->antParm[iant*4+0]*57.296, in->antParm[iant*4+1]*57.296, \n\t\t\t in->antParm[iant*4+2]*57.296, in->antParm[iant*4+3]*57.296, ParRMS, XRMS);\n\t}\n      /* Antenna gain if fitted */\n      if (!in->isCircFeed && in->doFitGain) {\n\tfor (iant=0; iant<in->nant; iant++) {\n\t  if (in->gotAnt[iant]) {\n\t    Obit_log_error(err, OBIT_InfoErr, \n\t\t\t   \"ant %3d gain X %6.3f Y %6.3f \", \n\t\t\t   iant+1, in->antGain[iant*2+0], in->antGain[iant*2+1]);\n\t  }\n\t}\n      } /* end antenna gain */\n    } /* end if not LM */\n  } /* end diagnostics */\n  ObitErrLog(err); \n  return TRUE;\n } /* end doFitFast */\n\n/**\n * Determine Chi Sq and RMS residuals of current model on selected data\n * Also optionally computes the first and second derivative wrt a given \n * parameter which is specified by paramType, paramNumber\n * \\param nThreads Number of threads to use\n * \\param in           Fitting object\n * \\param paramType    Parameter type\n * \\li polnParmUnspec  Unspecified = don't compute derivatives\n * \\li polnParmSou     Source parameter\n * \\li polnParmAnt     Antenna parameter\n * \\li polnParmGain    Antenna gains\n * \\li polnParmPD      Phase difference\n * \\param paramNumber  Parameter number,\n *                     Sou: 0=Ipol, 1=Qpol, 2=Upol, 3=VPol\n *                     Gain 0=X, 1=Y\n *                     Ant: 0= Ori R/X, 1=Elp R/X, 2= Ori L/Y, 1=Elp L/Y,       \n * \\param ParRMS       [out] Parallel hand RMS\n * \\param XRMS         [out] Cross hand RMS\n * \\param dChi2        [out] First derivative of Chi2 wrt parameter\n *                     May be NULL if not needed\n * \\param d2Chi2       [out] Second derivative of Chi2 wrt parameter\n *                     May be NULL if not needed\n * \\param err          Obit error stack object.\n * \\return             Chi^2\n */\nstatic odouble GetChi2 (olong nThreads, ObitPolnCalFit *in, \n\t\t\tPolnParmType paramType, olong paramNumber,\n\t\t\tofloat *ParRMS, ofloat *XRMS, \n\t\t\todouble *dChi2, odouble *d2Chi2,\n\t\t\tObitErr *err)\n{\n  odouble Chi2 = -1.0;\n  ObitThreadFunc func=NULL;\n  odouble sumParResid, sumXResid, sumWt, ldChi2, ld2Chi2;\n  olong iTh, nPobs, nXobs, nVisPerThread;\n  gboolean OK;\n  gchar *routine=\"ObitPolnCalFit:GetChi2\";\n\n  if (err->error) return Chi2;  /* Error exists? */\n  if (dChi2!=NULL)  *dChi2  = 0.0;\n  if (d2Chi2!=NULL) *d2Chi2 = 1.0;\n\n  /* Feed polarization type? */\n  if (in->isCircFeed) {\n    /* Circular feeds */\n    func = (ObitThreadFunc)ThreadPolnFitRLChi2;\n  } else {\n    /* Linear feeds  */\n    func = (ObitThreadFunc)ThreadPolnFitXYChi2;\n  }\n\n  /* Init threads */\n  nVisPerThread = in->nvis / in->nThread;\n  for (iTh=0; iTh<nThreads; iTh++) {\n    in->thArgs[iTh]->selSou = in->selSou;\n    in->thArgs[iTh]->selAnt = in->selAnt;\n    in->thArgs[iTh]->inData = in->inData;\n    in->thArgs[iTh]->inWt   = in->inWt;\n    in->thArgs[iTh]->antNo  = in->antNo;\n    in->thArgs[iTh]->souNo  = in->souNo;\n    in->thArgs[iTh]->PD     = in->PD;\n    in->thArgs[iTh]->curFreq= in->freq;\n    in->thArgs[iTh]->nvis   = in->nvis;\n    in->thArgs[iTh]->paramType   = paramType;\n    in->thArgs[iTh]->paramNumber = paramNumber;\n    in->thArgs[iTh]->lo          = iTh*nVisPerThread;     /* Zero rel first */\n    in->thArgs[iTh]->hi          = (iTh+1)*nVisPerThread; /* Zero rel last */\n  }\n  /* Make sure do all data */\n  iTh = in->nThread-1;\n  in->thArgs[iTh]->hi = MAX (in->thArgs[iTh]->hi, in->nvis);\n\n  OK = ObitThreadIterator (in->thread, nThreads, func, (gpointer)in->thArgs);\n  if (!OK) {\n    Obit_log_error(err, OBIT_Error,\"%s: Problem in threading\", routine);\n    return Chi2;\n  }\n\n  /* Sum over threads */\n  Chi2 = sumParResid = sumXResid = sumWt = ldChi2 = ld2Chi2 = 0.0;\n  nPobs = nXobs = 0;\n  for (iTh=0; iTh<nThreads; iTh++) {\n    Chi2        += in->thArgs[iTh]->ChiSq;\n    sumParResid += in->thArgs[iTh]->sumParResid;\n    sumXResid   += in->thArgs[iTh]->sumXResid;\n    sumWt       += in->thArgs[iTh]->sumWt;\n    nPobs       += in->thArgs[iTh]->nPobs;\n    nXobs       += in->thArgs[iTh]->nXobs;\n    if (paramType!=polnParmUnspec) {\n      ldChi2  += in->thArgs[iTh]->sumDeriv;\n      ld2Chi2 += in->thArgs[iTh]->sumDeriv2;\n    }\n  }\n  if (sumWt>0.0) Chi2 /= sumWt;\n\n  /* output RMSes */\n  *ParRMS = sqrt (sumParResid / nPobs);\n  *XRMS   = sqrt (sumXResid / nXobs);\n  if ((paramType!=polnParmUnspec) && (dChi2!=NULL) && (sumWt>0.0))  \n    *dChi2  = ldChi2 / sumWt;\n  if ((paramType!=polnParmUnspec) && (d2Chi2!=NULL) && (sumWt>0.0))  \n    *d2Chi2 = ld2Chi2 / sumWt;\n\n  return Chi2;\n } /* end GetChi2 */\n/**\n * Determine  RMS residuals of current model on selected data\n * \\param nThreads Number of threads to use\n * \\param in           Fitting object\n * \\parma antNumber    0-rel antenna number\n * \\param ParRMS       [out] Parallel hand RMS\n * \\param XRMS         [out] Cross hand RMS\n * \\param err          Obit error stack object.\n */\nstatic void GetRMSes (olong nThreads, ObitPolnCalFit *in, olong antNumber, \n\t\t      ofloat *ParRMS, ofloat *XRMS, \n\t\t      ObitErr *err)\n{\n  ObitThreadFunc func=NULL;\n  odouble sumParResid, sumXResid;\n  olong iTh, nPobs, nXobs, nVisPerThread;\n  gboolean OK;\n  gchar *routine=\"ObitPolnCalFit:GetRMSes\";\n\n  *ParRMS = 0.0;\n  *XRMS   = 0.0;\n if (err->error) return;  /* Error exists? */\n\n  /* Feed polarization type? */\n  if (in->isCircFeed) {\n    /* Circular feeds */\n    func = (ObitThreadFunc)ThreadPolnFitRLChi2;\n  } else {\n    /* Linear feeds  */\n    func = (ObitThreadFunc)ThreadPolnFitXYChi2;\n  }\n\n  /* Init threads */\n  nVisPerThread = in->nvis / in->nThread;\n  for (iTh=0; iTh<nThreads; iTh++) {\n    in->thArgs[iTh]->selSou = -1;\n    in->thArgs[iTh]->selAnt = antNumber;\n    in->thArgs[iTh]->inData = in->inData;\n    in->thArgs[iTh]->inWt   = in->inWt;\n    in->thArgs[iTh]->antNo  = in->antNo;\n    in->thArgs[iTh]->souNo  = in->souNo;\n    in->thArgs[iTh]->PD     = in->PD;\n    in->thArgs[iTh]->curFreq= in->freq;\n    in->thArgs[iTh]->nvis   = in->nvis;\n    in->thArgs[iTh]->paramType   = polnParmAnt;\n    in->thArgs[iTh]->paramNumber = 0;                     /* Ori R/X */\n    in->thArgs[iTh]->lo          = iTh*nVisPerThread;     /* Zero rel first */\n    in->thArgs[iTh]->hi          = (iTh+1)*nVisPerThread; /* Zero rel last */\n  }\n  /* Make sure do all data */\n  iTh = in->nThread-1;\n  in->thArgs[iTh]->hi = MAX (in->thArgs[iTh]->hi, in->nvis);\n\n  OK = ObitThreadIterator (in->thread, nThreads, func, (gpointer)in->thArgs);\n  if (!OK) {\n    Obit_log_error(err, OBIT_Error,\"%s: Problem in threading\", routine);\n    return;\n  }\n\n  /* Sum over threads */\n  sumParResid = sumXResid = 0.0;\n  nPobs = nXobs = 0;\n  for (iTh=0; iTh<nThreads; iTh++) {\n    sumParResid += in->thArgs[iTh]->sumParResid;\n    sumXResid   += in->thArgs[iTh]->sumXResid;\n    nPobs       += in->thArgs[iTh]->nPobs;\n    nXobs       += in->thArgs[iTh]->nXobs;\n  }\n\n  /* Now do orthogonal poln */\n  for (iTh=0; iTh<nThreads; iTh++)  in->thArgs[iTh]->paramNumber = 2;   /* Ori L/Y */\n OK = ObitThreadIterator (in->thread, nThreads, func, (gpointer)in->thArgs);\n  if (!OK) {\n    Obit_log_error(err, OBIT_Error,\"%s: Problem in threading\", routine);\n    return;\n  }\n\n  /* Sum over threads */\n  for (iTh=0; iTh<nThreads; iTh++) {\n    sumParResid += in->thArgs[iTh]->sumParResid;\n    sumXResid   += in->thArgs[iTh]->sumXResid;\n    nPobs       += in->thArgs[iTh]->nPobs;\n    nXobs       += in->thArgs[iTh]->nXobs;\n  }\n \n  /* output RMSes */\n  *ParRMS = sqrt (sumParResid / MAX(1, nPobs));\n  *XRMS   = sqrt (sumXResid / MAX(1, nXobs));\n } /* end GetRMSes */\n\n\n/**\n * Determine average R-L phase difference\n * \\param in           Fitting object\n * \\param err          Obit error stack object.\n * \\return             Chi^2\n */\nofloat FitRLPhase (ObitPolnCalFit *in, ObitErr *err)\n{\n  ofloat PD = 0.0;\n  ofloat *RLr=NULL, *RLi=NULL, *LRr=NULL, *LRi=NULL, *RLwt=NULL, *LRwt=NULL;\n  ofloat *data, *wt, iipol, Re1, Re2, Im1, Im2, PPol1, PPol2, Pang1, Pang2;\n  odouble sumr, sumi, sumw;\n  olong i, isou, idata;\n  gboolean OK;\n  /*gchar *routine=\"ObitPolnCalFit:FitRLPhase\";*/\n\n  if (err->error) return PD;  /* Error exists? */\n\n  /* Alias work arrays */\n  RLr = (ofloat*)in->SR;\n  RLi = (ofloat*)in->DR;\n  LRr = (ofloat*)in->SL;\n  LRi = (ofloat*)in->DL;\n  RLwt = (ofloat*)in->RS;\n  LRwt = (ofloat*)in->RS;\n\n  /* Init sums */\n  OK = FALSE;\n  for (i=0; i<in->nsou; i++) {\n    RLr[i] = RLi[i] = LRr[i] = LRi[i] = RLwt[i] = LRwt[i] = 0.0;\n    /* Check for suitable calibrators */\n    OK = OK || (!in->souFit[i][1] && !in->souFit[i][2] && \n\t\t(in->PPol[i]>0.0001));\n  }\n\n  /* Any suitable calibrators? */\n  if (!OK) return PD;\n  wt   = in->inWt;\n  data = in->inData;\n\n  /* Loop over data */\n  for (idata=0; idata<in->nvis; idata++) {\n    isou  = MAX (0, in->souNo[idata]);    /* Source number */\n    /* This one usable? */\n    if (in->souFit[isou][1] || in->souFit[isou][2] || \n\t(in->PPol[isou]<=0.0001)) continue;\n    /* Normalize data py 1/ipol */\n    iipol = 1.0 / in->souParm[isou*4];\n    if (wt[idata*4+2]>0.0) {\n      RLr[isou]  += data[idata*10+6] * iipol * wt[idata*4+2];\n      RLi[isou]  += data[idata*10+7] * iipol * wt[idata*4+2];\n      RLwt[isou] += wt[idata*4+2];\n    }\n    if (wt[idata*4+3]>0.0) {\n      LRr[isou] += data[idata*10+8] * iipol * wt[idata*4+3];\n      LRi[isou] += data[idata*10+9] * iipol * wt[idata*4+3];\n      LRwt[isou] += wt[idata*4+3];\n    }\n  } /* end loop over data */\n\n  /* Loop over sources differences phase with model - \n     weight average by polarized flux,\n     average as real and imaginary parts */\n  sumr = sumi = sumw = 0.0;\n  /* Signs here need to be checked */\n  for (isou=0; isou<in->nsou; isou++) {\n    if (in->souFit[isou][1] || in->souFit[isou][2] || \n\t(in->PPol[isou]<=0.0001)) continue;\n    /* Get weighted average RL and LR per source */\n    if (RLwt[isou]>0.0) {\n      Re1   = RLr[isou] / RLwt[isou];\n      Im1   = RLi[isou] / RLwt[isou];\n      PPol1 = in->souParm[isou*4] * sqrt (Re1*Re1 + Im1*Im1);\n    } else {Re1 = 1.0; Im1=0.0; PPol1 = 0.0;}\n    Pang1 = atan2 (Im1, Re1);\n    sumr += PPol1 * cos (Pang1 - in->RLPhase[isou]);\n    sumi += PPol1 * sin (Pang1 - in->RLPhase[isou]);\n    sumw += PPol1;\n    if (LRwt[isou]>0.0) {\n      Re2   = LRr[isou] / LRwt[isou];\n      Im2   = LRi[isou] / LRwt[isou];\n      PPol2 = in->souParm[isou*4] * sqrt (Re2*Re2 + Im2*Im2);\n    } else {Re2 = 1.0; Im2=0.0; PPol2 = 0.0;}\n    Pang2 = atan2 (Im2, Re2);\n    sumr += PPol2 * cos (Pang2 + in->RLPhase[isou]);\n    sumi -= PPol2 * sin (Pang2 + in->RLPhase[isou]);\n    sumw += PPol2;\n    }\n\n  if ((sumr!=0.0) || (sumi!=0.0))\n    PD = atan2 (sumi, sumr); /* Weighted phase difference */\n\n  return PD;\n} /* end FitRLPhase */\n\n/**\n * Circular polarization version.\n * Threaded Chi**2 evaluator for polarization fitting\n * Evaluates sum [(model-observed) / sigma] and derivatives\n * Parallel hands count 0.3 of cross in sums\n * If selAnt or selSou are set, then only data involving that \n * source or antenna (or ref ant) is included.\n * \\param arg   PolnFitArg pointer with elements:\n * \\li lo       First 0-rel datum in Data/Wt arrays\n * \\li hi       Last 0-rel datum  in Data/Wt arrays\n * \\li selAnt   selected antenna, -1-> all\n * \\li selSou   selected source,  -1> all\n * \\li paramType       Parameter type\n * \\li polnParmUnspec  Unspecified = don't compute derivatives\n * \\li polnParmAnt     Antenna parameter\n * \\li polnParmSou     Source parameter\n * \\li polnParmPD      Phase difference\n * \\li paramNumber  Parameter number,\n *                     Sou: 0=Ipol, 1=Qpol, 2=Upol, 3=VPol\n                       Ant: 0= Ori R/X, 1=Elp R/X, 2= Ori L/Y, 1=Elp L/Y,       \n * \\li ChiSq        [out] computed Chi2\n * \\li nPobs        [out] Number of valid parallel measurements\n * \\li nXobs        [out] Number of valid cross pol measurements\n * \\li ParRMS       [out] Parallel hand RMS\n * \\li sumParResid  [out] Cross hand RMS\n * \\li sumXResid    [out] First derivative of Chi2 wrt parameter\n * \\li d2Chi2       [out] Second derivative of Chi2 wrt parameter\n * \\li ithread  thread number, <0 -> no threading\n * \\return NULL\n */\nstatic gpointer ThreadPolnFitRLChi2 (gpointer arg)\n{\n  PolnFitArg *args = (PolnFitArg*)arg;\n  odouble    *antParm   = args->antParm;\n  gboolean   **antFit   = args->antFit;\n  odouble    *souParm   = args->souParm;\n  gboolean   **souFit   = args->souFit;\n  ofloat     *data      = args->inData;\n  ofloat     *wt        = args->inWt;\n  odouble    *SR        = args->SR;\n  odouble    *DR        = args->DR;\n  odouble    *SL        = args->SL;\n  odouble    *DL        = args->DL;\n  dcomplex   *PR        = args->PR;\n  dcomplex   *PRc       = args->PRc;\n  dcomplex   *PL        = args->PL;\n  dcomplex   *PLc       = args->PLc;\n  dcomplex   *RS        = args->RS;\n  dcomplex   *RD        = args->RD;\n  dcomplex   *LS        = args->LS;\n  dcomplex   *LD        = args->LD;\n  dcomplex   *RSc       = args->RSc;\n  dcomplex   *RDc       = args->RDc;\n  dcomplex   *LSc       = args->LSc;\n  dcomplex   *LDc       = args->LDc;\n  PolnParmType paramType = args->paramType;\n  olong paramNumber      = args->paramNumber;\n  olong selSou           = args->selSou;\n  olong selAnt           = args->selAnt;\n\n  odouble ipol=0.0, qpol=0.0, upol=0.0, vpol=0.0;\n  odouble residR=0.0, residI=0.0, isigma=0.0;\n  odouble sumParResid, sumXResid;\n  ofloat PD, chi1, chi2, PPol;\n  olong nPobs, nXobs, ia1, ia2, isou, idata, isouLast=-999;\n  gboolean isAnt1, isAnt2;\n  size_t i;\n  odouble sum=0.0, sumwt=0.0, sumd, sumd2;\n\n  dcomplex PRref, PLref, PPRL, PPLR, PA1, PA2, PA1c, PA2c;\n  dcomplex ct1, ct2, ct3, ct4, ct5, ct6, dt1, dt2;\n  dcomplex S[4], VRR, VRL, VLR, VLL, MC1, MC2, MC3, MC4, DFDP, DFDP2;\n  ofloat root2;\n\n  COMPLEX_SET (S[0], 0.0, 0.0);  /* Initialize poln vector */\n  COMPLEX_SET (S[1], 0.0, 0.0);\n  COMPLEX_SET (S[2], 0.0, 0.0);\n  COMPLEX_SET (S[3], 0.0, 0.0);\n  COMPLEX_SET (MC1, 0.0, 0.0);  /* Other stuff */\n  COMPLEX_SET (MC2, 0.0, 0.0);\n  COMPLEX_SET (MC3, 0.0, 0.0);\n  COMPLEX_SET (MC4, 0.0, 0.0);\n  COMPLEX_SET (VRR, 0.0, 0.0);\n  COMPLEX_SET (VLL, 0.0, 0.0);\n  COMPLEX_SET (VLR, 0.0, 0.0);\n  COMPLEX_SET (VRL, 0.0, 0.0);\n  COMPLEX_SET (DFDP,  0.0, 0.0);\n  COMPLEX_SET (DFDP2, 0.0, 0.0);\n  COMPLEX_SET (dt1, 0.0, 0.0);\n  COMPLEX_SET (dt2, 0.0, 0.0);\n  /* Init others */\n  isouLast=-999;\n  sum = sumwt = 0.0;\n  ipol = qpol = upol = vpol = 0.0;\n  residR = residI = isigma = 0.0;\n\n  /* RMS sums and counts */\n  sumParResid = sumXResid = 0.0;\n  sumd = sumd2 = 0.0;\n  nPobs = nXobs = 0;\n  /* R-L phase difference  at reference antenna */\n  PD = args->PD;\n\n  /* Injest model, factorize into antenna components - \n     data in order Orientation R/X, Elipticity R/X, Orientation L/Y, Elipticity L/Y */\n  root2 = 1.0 / sqrt(2.0);\n  /* Elipticity, Orientation terms */\n  for (i=0; i<args->nant; i++) {\n    SR[i] = cos(antParm[i*4+1]) + sin(antParm[i*4+1]);\n    DR[i] = cos(antParm[i*4+1]) - sin(antParm[i*4+1]);\n    SL[i] = cos(antParm[i*4+3]) + sin(antParm[i*4+3]);\n    DL[i] = cos(antParm[i*4+3]) - sin(antParm[i*4+3]);\n    COMPLEX_SET  (RS[i], root2*SR[i], 0.);\n    COMPLEX_SET  (ct1,   root2*DR[i], 0.);\n    COMPLEX_EXP  (PR[i], 2*antParm[i*4+0]);\n    COMPLEX_CONJUGATE (PRc[i], PR[i]);\n    COMPLEX_MUL2 (RD[i], ct1, PR[i]);\n    COMPLEX_SET  (ct1, root2*SL[i], 0.);\n    COMPLEX_EXP  (PL[i], -2*antParm[i*4+2]);\n    COMPLEX_CONJUGATE (PLc[i], PL[i]);\n    COMPLEX_MUL2 (LS[i], ct1, PL[i]);\n    COMPLEX_SET  (LD[i], root2*DL[i], 0.);\n    COMPLEX_CONJUGATE (RSc[i], RS[i]);\n    COMPLEX_CONJUGATE (RDc[i], RD[i]);\n    COMPLEX_CONJUGATE (LSc[i], LS[i]);\n    COMPLEX_CONJUGATE (LDc[i], LD[i]);\n  }\n\n  /* Reference antenna phase terms */\n  if (args->refAnt>0) {\n    COMPLEX_EXP (PRref,  antParm[(args->refAnt-1)*4+0]);\n    COMPLEX_EXP (PLref, -antParm[(args->refAnt-1)*4+2]+PD);\n  } else {\n    COMPLEX_SET (PRref, 1.0, 0.0);\n    COMPLEX_EXP (PLref, PD);\n  }\n  COMPLEX_CONJUGATE (ct1, PLref);\n  COMPLEX_MUL2(PPRL, PRref, ct1);\n  COMPLEX_CONJUGATE (ct1, PRref);\n  COMPLEX_MUL2(PPLR, PLref, ct1);\n\n  /* Loop over data */\n  i = 0;\n  for (idata=args->lo; idata<args->hi; idata++) {\n    isou  = MAX (0, args->souNo[idata]);    /* Source number */\n    /* Selected source? */\n    if ((selSou>=0) && (selSou!=isou)) continue;\n\n    /* Antenna parameters (0 ref) */\n    ia1    = args->antNo[idata*2+0];\n    ia2    = args->antNo[idata*2+1]; \n    /* Selected source? */\n    if ((selAnt>=0) && \n\t((selAnt!=ia1) && (ia1!=args->refAnt)) && \n\t (selAnt!=ia2) && (ia2!=args->refAnt)) continue;\n    /* Which antenna is the selected one in the baseline? */\n    if (selAnt==ia1) {isAnt1 = TRUE; isAnt2 = FALSE;}\n    else if (selAnt==ia2) {isAnt2 = TRUE; isAnt1 = FALSE;}\n    else {isAnt1 = FALSE; isAnt2 = FALSE;}  /* Only refant */\n    \n    /* Parallactic angle terms */\n    chi1  = data[idata*10+0];   /* parallactic angle ant 1 */\n    chi2  = data[idata*10+1];   /* parallactic angle ant 2 */\n    COMPLEX_EXP (PA1,2*chi1);\n    COMPLEX_EXP (PA2,2*chi2);\n    COMPLEX_CONJUGATE (PA1c, PA1);\n    COMPLEX_CONJUGATE (PA2c, PA2);\n\n    /* New source? get parameters */\n    if (isou!=isouLast) {\n      isouLast = isou;\n      /* Source parameters */\n      ipol = souParm[isou*4+0];      /* Fitting or fixed? */\n      if (args->souFit[isou][1]) \n\tqpol = souParm[isou*4+1];\n      else {\n\tPPol = args->PPol[isou] + args->dPPol[isou]*(args->curFreq-args->refFreq);\n\tqpol = PPol*ipol*cos(args->RLPhase[isou]);}\n      if (args->souFit[isou][2]) \n\tupol = souParm[isou*4+2];\n      else {\n\tPPol = args->PPol[isou]+ args->dPPol[isou]*(args->curFreq-args->refFreq);\n\tupol = PPol*ipol*sin(args->RLPhase[isou]);}\n      vpol = souParm[isou*4+3];\n      /* Complex Stokes array */\n      COMPLEX_SET (S[0], ipol+vpol, 0.0);\n      COMPLEX_SET (S[1], qpol,  upol);\n      COMPLEX_SET (S[2], qpol, -upol);\n      COMPLEX_SET (S[3], ipol-vpol, 0.0);\n    }\n\n  /* Calculate residals - Note different order for LL */\n  /*      RR */\n  if (wt[idata*4]>0.0) {\n    isigma = 0.3*wt[idata*4]; /* downweight parallel */\n    \n    /* VRR = S[0] * RS[ia1] * RSc[ia2] +        \n             S[1] * RS[ia1] * RDc[ia2] * PA2c + \n\t     S[2] * RD[ia1] * RSc[ia2] * PA1  + \n\t     S[3] * RD[ia1] * RDc[ia2] * PA1  * PA2c; */\n    COMPLEX_MUL2 (MC1, RS[ia1], RSc[ia2]);\n    COMPLEX_MUL2 (VRR, S[0], MC1);\n    COMPLEX_MUL3 (MC2, RS[ia1], RDc[ia2],  PA2c);\n    COMPLEX_MUL2 (ct1, S[1], MC2);\n    COMPLEX_ADD2 (VRR, VRR,  ct1);\n    COMPLEX_MUL3 (MC3, RD[ia1], RSc[ia2], PA1);\n    COMPLEX_MUL2 (ct1, S[2], MC3);\n    COMPLEX_ADD2 (VRR, VRR,  ct1);\n    COMPLEX_MUL4 (MC4, RD[ia1], RDc[ia2], PA1, PA2c);\n    COMPLEX_MUL2 (ct1, S[3], MC4);\n    COMPLEX_ADD2 (VRR, VRR,  ct1);\n    residR = VRR.real - data[idata*10+2];\n    sum += isigma * residR * residR; sumwt += isigma;\n    residI = VRR.imag - data[idata*10+3];\n    sum += isigma * residI * residI; sumwt += isigma;\n    nPobs++;\n    sumParResid += residR * residR + residI * residI;\n    /* Derivatives */\n    if (paramType==polnParmAnt) {         /* Antenna parameters */\n      /* Default partials */\n      COMPLEX_SET (DFDP,  0.0, 0.0);\n      COMPLEX_SET (DFDP2, 0.0, 0.0);\n      switch (paramNumber) {   /* Switch over parameter */\n      case 0:     /* RR wrt Or */\n\tif (isAnt1) {\n\t  if (antFit[ia1][paramNumber]) {\n\t    /* (0, 2 i) * (S[2]*MC3 + S[3]*MC4) */\n\t    COMPLEX_MUL2(ct1, S[2], MC3);\n\t    COMPLEX_MUL2(ct2, S[3], MC4);\n\t    COMPLEX_ADD2(ct3, ct1, ct2);\n\t    COMPLEX_SET (ct1, 0.0, 2.0);\n\t    COMPLEX_MUL2(DFDP,  ct1, ct3);\n\t    COMPLEX_MUL2(DFDP2, ct1, DFDP);\n\t  }\n\t} else if (isAnt2) {\n\t  if (antFit[ia2][paramNumber]) {\n\t    /* (0,-2 i) * (S[1]*MC2 + S[3]*MC4) */\n\t    COMPLEX_MUL2(ct1, S[1], MC2);\n\t    COMPLEX_MUL2(ct2, S[3], MC4);\n\t    COMPLEX_ADD2(ct3, ct1, ct2);\n\t    COMPLEX_SET (ct1, 0.0, -2.0);\n\t    COMPLEX_MUL2(DFDP,  ct1, ct3);\n\t    COMPLEX_MUL2(DFDP2, ct1, DFDP);\n\t  }\n\t} \n\tbreak;\n      case 1:     /* RR wrt Er */\n\tif (isAnt1) {\n\t  if (antFit[ia1][paramNumber]) {\n\t    /* part = r2 * DR[ia1] * (S[0] * RSc[ia2] + S[1] * RDc[ia2] * PA2c) -\n\t              r2 * SR[ia1] * PR[ia1] * (S[2] * RSc[ia2] * PA1 + \n\t\t                                S[3] * RDc[ia2] * PA1  * PA2c) */\n\t    COMPLEX_MUL2(ct1, S[0], RSc[ia2]);\n\t    COMPLEX_MUL3(ct2, S[1], RDc[ia2], PA2c);\n\t    COMPLEX_ADD2(dt1, ct1, ct2);\n\t    COMPLEX_SET (ct4, root2*DR[ia1], 0.0);\n\t    COMPLEX_MUL2(ct5, ct4, dt1);\n\t    COMPLEX_MUL3(ct1, S[2], RSc[ia2], PA1);\n\t    COMPLEX_MUL4(ct2, S[3], RDc[ia2], PA1, PA2c);\n\t    COMPLEX_ADD2(dt2, ct1, ct2);\n\t    COMPLEX_SET (ct4, root2*SR[ia1], 0.0);\n\t    COMPLEX_MUL3(ct6, ct4, PR[ia1], dt2);\n\t    COMPLEX_SUB (DFDP, ct5, ct6);\n\t    /* part2 = -r2 * SR[ia1] * (S[0] * RSc[ia2] + S[1] * RDc[ia2] * PA2c) -\n\t                r2 * DR[ia1] * PR[ia1] * (S[2] * RSc[ia2] * PA1 + \n                                                  S[3] * RDc[ia2] * PA1  * PA2c) */\n\t    COMPLEX_SET (ct4, -root2*SR[ia1], 0.0);\n\t    COMPLEX_MUL2(ct5, ct4, dt1);\n\t    COMPLEX_SET (ct4, root2*DR[ia1], 0.0);\n\t    COMPLEX_MUL3(ct6, ct4, PR[ia1], dt2);\n\t    COMPLEX_SUB (DFDP2, ct5, ct6);\n\t  }\n\t} else if (isAnt2) {\n\t  if (antFit[ia2][paramNumber]) {\n\t    /* part = r2 * DR[ia2] * (S[0] * RS[ia1] + S[2] * RD[ia1] * PA1) -\n\t              r2 * SR[ia2] * PRc[ia2] * PA2c  * (S[1] * RS[ia1] * PA2c w+ \n                                                 S[3] * RD[ia1] * PA1) */\n\t    COMPLEX_MUL2(ct1, S[0], RS[ia1]);\n\t    COMPLEX_MUL3(ct2, S[2], RD[ia1], PA1);\n\t    COMPLEX_ADD2(dt2, ct1, ct2);\n\t    COMPLEX_SET (ct4, root2*DR[ia2], 0.0);\n\t    COMPLEX_MUL2(ct5, ct4, dt1);\n\t    COMPLEX_MUL2(ct1, S[1], RS[ia1]);\n\t    COMPLEX_MUL3(ct2, S[3], RD[ia1], PA1);\n\t    COMPLEX_ADD2(dt2, ct1, ct2);\n\t    COMPLEX_SET (ct4, root2*SR[ia2], 0.0);\n\t    COMPLEX_MUL4(ct6, ct4, PRc[ia2], PA2c, dt2);\n\t    COMPLEX_SUB (DFDP, ct5, ct6);\n\t    /* part2 = -r2 * SR[ia2] * (S[0] * RS[ia1] + S[2] * RD[ia1] * PA1) -\n\t                r2 * DR[ia2] * PRc[ia2] * PA2c * (S[1] * RS[ia1] + \n                                                          S[3] * RD[ia1] * PA1) */\n\t    COMPLEX_SET (ct4, -root2*SR[ia2], 0.0);\n\t    COMPLEX_MUL2(ct5, ct4, dt1);\n\t    COMPLEX_SET (ct4, root2*DR[ia2], 0.0);\n\t    COMPLEX_MUL4(ct6, ct4, PRc[ia2], PA2c, dt2);\n\t    COMPLEX_SUB (DFDP2, ct5, ct6);\n\t  }\n\t}\n\tbreak;\n      case 2:     /* RR wrt Ol - nope */\n\tbreak;\n      case 3:     /* RR wrt El - nope */\n\tbreak;\n      default:\n\tbreak;\n      }; /* end antenna parameter switch */\n      /* end antenna param */\n    } else if (paramType==polnParmSou) {   /* Source parameters */\n      /* Default partials  */\n      COMPLEX_SET (DFDP,  0.0, 0.0);\n      COMPLEX_SET (DFDP2, 0.0, 0.0);\n      switch (paramNumber) {   /* Switch over parameter */\n      case 0:     /* RR wrt I */\n\tif (souFit[isou][paramNumber]) {\n\t  /* part = MC1 + MC4 */\n\t  COMPLEX_ADD2(DFDP, MC1, MC4);\n\t}\n\tbreak;\n      case 1:     /* RR wrt QPol */\n\tif (souFit[isou][paramNumber]) {\n\t  /* part = MC2 + MC3 */\n\t  COMPLEX_ADD2(DFDP, MC2, MC3);\n\t}\n\tbreak;\n      case 2:     /* RR wrt UPol */\n\tif (souFit[isou][paramNumber]) {\n\t  /* part = i (MC2 - MC3) */\n\t  COMPLEX_SUB (ct3, MC2, MC3);\n\t  COMPLEX_SET(ct4, 0.0, 1.0);\n\t  COMPLEX_MUL2(DFDP, ct4, ct3);\n\t}\n\tbreak;\n      case 3:     /* RR wrt Vpol */\n\tif (souFit[isou][paramNumber]) {\n\t  /* part = MC1 - MC4 */\n\t  COMPLEX_SUB (DFDP, MC1, MC4);\n\t}\n\tbreak;  \n      default:\n\tbreak;\n      }; /* end source parameter switch */\n      /* end source param */\n    } else if (paramType==polnParmPD) {   /* R-L Phase difference */\n      /* No dependence on RR */\n      COMPLEX_SET (DFDP,  0.0, 0.0);\n      COMPLEX_SET (DFDP2, 0.0, 0.0);      \n    } /* end R-L phase difference */\n    /* Accumulate partials */\n    if (paramType!=polnParmUnspec) {\n      sumd  += 2.0 * isigma * (residR*DFDP.real + residI*DFDP.imag);\n      sumd2 += 2.0 * isigma * (DFDP.real*DFDP.real + DFDP.imag*DFDP.imag +\n\t\t\t       residR*DFDP2.real + residI*DFDP2.imag);\n    } /* end set partials */\n  } /* end valid data */\n  \n    /*      LL */\n  if (wt[idata*4+1]>0.0) {\n    isigma = 0.3*wt[idata*4+1];  /* downweight parallel */\n    /* VLL = S[0] * LS[ia1] * LSc[ia2] * PA1c * PA2 +\t\n             S[1] * LS[ia1] * LDc[ia2] * PA1c +\n\t     S[2] * LD[ia1] * LSc[ia2] * PA2  +\n\t     S[3] * LD[ia1] * LDc[ia2]; */\n    COMPLEX_MUL4 (MC1, LS[ia1], LSc[ia2], PA1c, PA2);\n    COMPLEX_MUL2 (VLL, S[0], MC1);\n    COMPLEX_MUL3 (MC2, LS[ia1], LDc[ia2], PA1c);\n    COMPLEX_MUL2 (ct1, S[1], MC2);\n    COMPLEX_ADD2 (VLL, VLL,  ct1);\n    COMPLEX_MUL3 (MC3, LD[ia1], LSc[ia2], PA2);\n    COMPLEX_MUL2 (ct1, S[2], MC3);\n    COMPLEX_ADD2 (VLL, VLL,  ct1);\n    COMPLEX_MUL2 (MC4, LD[ia1], LDc[ia2]);\n    COMPLEX_MUL2 (ct1, S[3], MC4);\n    COMPLEX_ADD2 (VLL, VLL,  ct1);\n    residR = VLL.real - data[idata*10+4];\n    sum += isigma * residR * residR; sumwt += isigma; \n    residI = VLL.imag - data[idata*10+5];\n    sum += isigma * residI * residI; sumwt += isigma; \n    nPobs++;\n    sumParResid += residR * residR + residI * residI;\n    /* Derivatives */\n    if (paramType==polnParmAnt) {         /* Antenna parameters */\n      /* Default partials */\n      COMPLEX_SET (DFDP,  0.0, 0.0);\n      COMPLEX_SET (DFDP2, 0.0, 0.0);\n      switch (paramNumber) {   /* Switch over parameter */\n      case 0:     /* LL wrt Or - nope */\n\tbreak;\n      case 1:     /* LL wrt Er - nope*/\n\tbreak;\n      case 2:     /* LL wrt Ol */\n\tif (isAnt1) {\n\t  if (antFit[ia1][paramNumber]) {\n\t    /* (0,-2 i) * (S[0]*MC1 + S[1]*MC2) */\n\t    COMPLEX_MUL2(ct1, S[0], MC1);\n\t    COMPLEX_MUL2(ct2, S[1], MC2);\n\t    COMPLEX_ADD2(ct3, ct1, ct2);\n\t    COMPLEX_SET (ct1, 0.0, -2.0);\n\t    COMPLEX_MUL2(DFDP,  ct1, ct3);\n\t    COMPLEX_MUL2(DFDP2, ct1, DFDP);\n\t  }\n\t} else if (isAnt2) {\n\t  if (antFit[ia2][paramNumber]) {\n\t    /* (0, 2 i) * (S[0]*MC1 + S[2]*MC3) */\n\t    COMPLEX_MUL2(ct1, S[0], MC1);\n\t    COMPLEX_MUL2(ct2, S[2], MC3);\n\t    COMPLEX_ADD2(ct3, ct1, ct2);\n\t    COMPLEX_SET (ct1, 0.0, 2.0);\n\t    COMPLEX_MUL2(DFDP,  ct1, ct3);\n\t    COMPLEX_MUL2(DFDP2, ct1, DFDP);\n\t  }\n\t}\n\tbreak;\n      case 3:     /* LL wrt El */\n\tif (isAnt1) {\n\t  if (antFit[ia1][paramNumber]) {\n\t    /* part = r2 * DL[ia1] * PL[ia1] * PA1c * (S[0] * LSc[ia2] * PA2 + \n\t                                               S[1] * LDc[ia2) -\n\t              r2 * SL[ia1] * (S[2] * LSc[ia2] * PA2  + S[3] * LDc[ia2]) */\n\t    COMPLEX_MUL3(ct1, S[0], LSc[ia2], PA2);\n\t    COMPLEX_MUL2(ct2, S[1], LDc[ia2]);\n\t    COMPLEX_ADD2(dt1, ct1, ct2);\n\t    COMPLEX_SET (ct4, root2*DL[ia1], 0.0);\n\t    COMPLEX_MUL4(ct5, ct4, PL[ia1], PA1c, dt1);\n\t    COMPLEX_MUL3(ct1, S[2], LSc[ia2], PA2);\n\t    COMPLEX_MUL2(ct2, S[3], LDc[ia2]);\n\t    COMPLEX_ADD2(dt2, ct1, ct2);\n\t    COMPLEX_SET (ct4, root2*SL[ia1], 0.0);\n\t    COMPLEX_MUL2(ct6, ct4, dt2);\n\t    COMPLEX_SUB (DFDP, ct5, ct6);\n\t    /* part2 = -r2 * SL[ia1] * PL[ia1] * PA1c * (S[0] * LSc[ia2] * PA2 + \n                                                         S[1] * LDc[ia2]) -\n\t                r2 * DL[ia1] * (S[2] * LSc[ia2] * PA2  + S[3] * LDc[ia2]) */\n\t    COMPLEX_SET (ct4, -root2*SL[ia1], 0.0);\n\t    COMPLEX_MUL4(ct5, ct4, PL[ia1], PA1c, dt1);\n\t    COMPLEX_SET (ct4, root2*DL[ia1], 0.0);\n\t    COMPLEX_MUL2(ct6, ct4, dt2);\n\t    COMPLEX_SUB (DFDP2, ct5, ct6);\n\t  }\n\t} else if (isAnt2) {\n\t  if (antFit[ia2][paramNumber]) {\n\t    /* part = r2 * DL[ia2] * PLc[ia2] * PA2 * (S[0] * LS[ia1] * PA1c  + \n\t                                               S[2] * LD[ia1]) -\n\t              r2 * SL[ia2] * (S[1] * LS[ia1] * PA1c + S[3] * LD[ia1]) */\n\t    COMPLEX_MUL3(ct1, S[0], LS[ia1], PA1c);\n\t    COMPLEX_MUL2(ct2, S[2], LD[ia1]);\n\t    COMPLEX_ADD2(dt1, ct1, ct2);\n\t    COMPLEX_SET (ct4, root2*DL[ia2], 0.0);\n\t    COMPLEX_MUL4(ct5, ct4, PLc[ia2], PA2, dt1);\n\t    COMPLEX_MUL3(ct1, S[1], LS[ia1], PA1c);\n\t    COMPLEX_MUL2(ct2, S[3], LD[ia1]);\n\t    COMPLEX_ADD2(dt2, ct1, ct2);\n\t    COMPLEX_SET (ct4, root2*SL[ia2], 0.0);\n\t    COMPLEX_MUL2(ct6, ct4, dt2);\n\t    COMPLEX_SUB (DFDP, ct5, ct6);\n\t    /* part2 = -r2 * SL[ia2] * PLc[ia2] * PA2 * (S[0] * LS[ia1] * PA1c  + \n\t                                                 S[2] * LD[ia1) -\n\t                r2 * DL[ia2] * (S[1] * LS[ia1] * PA1c + S[3] * LD[ia1]) */\n\t    COMPLEX_SET (ct4, -root2*SL[ia2], 0.0);\n\t    COMPLEX_MUL4(ct5, ct4, PLc[ia2], PA2, dt1);\n\t    COMPLEX_SET (ct4, root2*DL[ia2], 0.0);\n\t    COMPLEX_MUL2(ct6, ct4, dt2);\n\t    COMPLEX_SUB (DFDP2, ct5, ct6);\n\t  }\n\t}\n\tbreak;\n      default:\n\tbreak;\n      }; /* end antenna parameter switch */\n      /* end antenna param */\n    } else if (paramType==polnParmSou) {   /* Source parameters */\n      /* Default partials  */\n      COMPLEX_SET (DFDP,  0.0, 0.0);\n      COMPLEX_SET (DFDP2, 0.0, 0.0);\n      switch (paramNumber) {   /* Switch over parameter */\n      case 0:     /* LL wrt I */\n\tif (souFit[isou][paramNumber]) {\n\t  /* part = MC1 + MC4 */\n\t  COMPLEX_ADD2(DFDP, MC1, MC4);\n\t}\n\tbreak;\n      case 1:     /* LL wrt QPol */\n\tif (souFit[isou][paramNumber]) {\n\t  /* part = MC2 + MC3 */\n\t  COMPLEX_ADD2(DFDP, MC2, MC3);\n\t}\n\tbreak;\n      case 2:     /* LL wrt UPol */\n\tif (souFit[isou][paramNumber]) {\n\t  /* part = i (MC2 - MC3) */\n\t  COMPLEX_SUB (ct3, MC2, MC3);\n\t  COMPLEX_SET(ct4, 0.0, 1.0);\n\t  COMPLEX_MUL2(DFDP, ct4, ct3);\n\t}\n\tbreak;\n      case 3:     /* LL wrt Vpol */\n\tif (souFit[isou][paramNumber]) {\n\t  /* part = MC1 - MC4 */\n\t  COMPLEX_SUB (DFDP, MC1, MC4);\n\t}\n\tbreak;  \n      default:\n\tbreak;\n      }; /* end source parameter switch */\n      /* end source param */\n    } else if (paramType==polnParmPD) {   /* R-L Phase difference */\n      /* No dependence on LL */\n      COMPLEX_SET (DFDP,  0.0, 0.0);\n      COMPLEX_SET (DFDP2, 0.0, 0.0);      \n    } /* end R-L phase difference */\n    /* Accumulate partials */\n    if (paramType!=polnParmUnspec) {\n      sumd  += 2.0 * isigma * (residR*DFDP.real + residI*DFDP.imag);\n      sumd2 += 2.0 * isigma * (DFDP.real*DFDP.real + DFDP.imag*DFDP.imag +\n\t\t\t       residR*DFDP2.real + residI*DFDP2.imag);\n    } /* end set partials */\n  } /* end valid data */\n  \n    /* \t    RL */\n  if (wt[idata*4+2]>0.0) {\n    isigma = wt[idata*4+2];\n    /* VRL = PPRL * S[0] * RS[ia1] * LSc[ia2] * PA2 +\n             PPRL * S[1] * RS[ia1] * LDc[ia2] + \n\t     PPRL * S[2] * RD[ia1] * LSc[ia2] * PA1 * PA2 +\n\t     PPRL * S[3] * RD[ia1] * LDc[ia2] * PA1; */\n    COMPLEX_MUL4 (MC1, PPRL, RS[ia1], LSc[ia2], PA2);\n    COMPLEX_MUL2 (VRL, S[0], MC1);\n    COMPLEX_MUL3 (MC2, PPRL, RS[ia1], LDc[ia2]);\n    COMPLEX_MUL2 (ct1, S[1], MC2);\n    COMPLEX_ADD2 (VRL, VRL,  ct1);\n    COMPLEX_MUL5 (MC3, PPRL, RD[ia1], LSc[ia2],  PA1,  PA2);\n    COMPLEX_MUL2 (ct1, S[2], MC3);\n    COMPLEX_ADD2 (VRL, VRL,  ct1);\n    COMPLEX_MUL4 (MC4, PPRL, RD[ia1], LDc[ia2],  PA1);\n    COMPLEX_MUL2 (ct1, S[3], MC4);\n    COMPLEX_ADD2 (VRL, VRL,  ct1);\n    residR = VRL.real - data[idata*10+6];\n    sum += isigma * residR * residR; sumwt += isigma;\n    residI = VRL.imag - data[idata*10+7];\n    sum += isigma * residI * residI; sumwt += isigma;\n    nXobs++;\n    sumXResid += residR * residR + residI * residI;\n    /* Derivatives */\n    if (paramType==polnParmAnt) {         /* Antenna parameters */\n      /* Default partials  */\n      COMPLEX_SET (DFDP,  0.0, 0.0);\n      COMPLEX_SET (DFDP2, 0.0, 0.0);\n      switch (paramNumber) {   /* Switch over parameter */\n      case 0:     /* RL wrt Or */\n\tif (isAnt1) {\n\t  if (antFit[ia1][paramNumber]) {\n\t    /* (0, 2 i) * (S[2]*MC3 + S[3]*MC4) */\n\t    COMPLEX_MUL2(ct1, S[2], MC3);\n\t    COMPLEX_MUL2(ct2, S[3], MC4);\n\t    COMPLEX_ADD2(ct3, ct1, ct2);\n\t    COMPLEX_SET (ct1, 0.0,  2.0);\n\t    COMPLEX_MUL2(DFDP, ct1, ct3);\n\t    COMPLEX_MUL2(DFDP2, ct1, DFDP);\n\t  }\n\t} \n\t/* If ia1==refant) */\n\tif (ia1==args->refAnt) {\n\t  COMPLEX_SET (ct1, 0.0,  1.0);\n\t  COMPLEX_MUL2(ct2, ct1, VRL);\n\t  COMPLEX_ADD2(DFDP, DFDP, ct2);\n\t  COMPLEX_MUL2(ct2, ct1, DFDP);\n\t  COMPLEX_ADD2(DFDP2, DFDP2, ct2);\n\t}\n\tbreak;\n      case 1:     /* RL wrt Er */\n\tif (isAnt1) {\n\t  if (antFit[ia1][paramNumber]) {\n\t    /* part = r2 * DR[ia1] * PPRL * (S[0] * LSc[ia2] * PA2 +S[1] * LDc[ia2]) -\n\t              r2 * SR[ia1] * PR[ia1] * PPRL * PA1 * (S[2] * LSc[ia2] * PA2 +\n\t                                                     S[3] * LDc[ia2]) */\n\t    COMPLEX_MUL3(ct1, S[0], LSc[ia2], PA2);\n\t    COMPLEX_MUL2(ct2, S[1], LDc[ia2]);\n\t    COMPLEX_ADD2(dt1, ct1, ct2);\n\t    COMPLEX_SET (ct4, root2*DR[ia1], 0.0);\n\t    COMPLEX_MUL3(ct5, ct4, PPRL, dt1);\n\t    COMPLEX_MUL3(ct1, S[2], LSc[ia2], PA2);\n\t    COMPLEX_MUL2(ct2, S[3], LDc[ia2]);\n\t    COMPLEX_ADD2(dt2, ct1, ct2);\n\t    COMPLEX_SET (ct4, root2*SR[ia1], 0.0);\n\t    COMPLEX_MUL5(ct6, ct4, PR[ia1], PPRL, PA1, dt2);\n\t    COMPLEX_SUB (DFDP, ct5, ct6);\n\t    /* part2 = -r2 * SR[ia1] * PPRL * (S[0] * LSc[ia2] * PA2 + S[1] * LDc[ia2]) -\n\t                r2 * DR[ia1] * PR[ia1] * PPRL * PA1 * (S[2] * LSc[ia2] * PA2 + \n\t                                                       S[3] * LDc[ia2] ) */\n\t    COMPLEX_SET (ct4, -root2*SR[ia1], 0.0);\n\t    COMPLEX_MUL3(ct5, ct4, PPRL, dt1);\n\t    COMPLEX_SET (ct4, root2*DR[ia1], 0.0);\n\t    COMPLEX_MUL5(ct6, ct4, PR[ia1], PPRL, PA1, dt2);\n\t    COMPLEX_SUB (DFDP2, ct5, ct6);\n\t  }\n\t}\n\tbreak;\n      case 2:     /* RL wrt Ol */\n\tif (isAnt2) {\n\t  if (antFit[ia2][paramNumber]) {\n\t    /* (0, 2 i) * (S[0]*MC1 + S[2]*MC3) */\n\t    COMPLEX_MUL2(ct1, S[0], MC1);\n\t    COMPLEX_MUL2(ct2, S[2], MC3);\n\t    COMPLEX_ADD2(ct3, ct1, ct2);\n\t    COMPLEX_SET (ct1, 0.0,  2.0);\n\t    COMPLEX_MUL2(DFDP, ct1, ct3);\n\t    COMPLEX_MUL2(DFDP2, ct1, DFDP);\n\t  }\n\t} \n\t/* If ia2==refant) */\n\tif (ia2==args->refAnt) {\n\t  COMPLEX_SET (ct1, 0.0, 1.0);\n\t  COMPLEX_MUL2(ct2, ct1, VRL);\n\t  COMPLEX_ADD2(DFDP, DFDP, ct2);\n\t  COMPLEX_MUL2(ct2, ct1, DFDP);\n\t  COMPLEX_ADD2(DFDP2, DFDP2, ct2);\n\t}\n\tbreak;\n      case 3:     /* RL wrt El */\n\tif (isAnt2) {\n\t  if (antFit[ia2][paramNumber]) {\n\t    /* part = r2 * DL[ia2] * PLc[ia2] * PPRL * PA2 * (S[0] * RS[ia1] + \n\t                                                      S[2] * RD[ia1] * PA1) -\n\t              r2 * SL[ia2] * PPRL * (S[1] * RS[ia1] + S[3] * RD[ia1] * PA1) */\n\t    COMPLEX_MUL2(ct1, S[0], RS[ia1]);\n\t    COMPLEX_MUL3(ct2, S[2], RD[ia1], PA1);\n\t    COMPLEX_ADD2(dt1, ct1, ct2);\n\t    COMPLEX_SET (ct4, root2*DL[ia2], 0.0);\n\t    COMPLEX_MUL5(ct5, ct4, PLc[ia2], PPRL, PA2, dt1);\n\t    COMPLEX_MUL2(ct1, S[1], RS[ia1]);\n\t    COMPLEX_MUL3(ct2, S[3], RD[ia1], PA1);\n\t    COMPLEX_ADD2(dt2, ct1, ct2);\n\t    COMPLEX_SET (ct4, root2*SL[ia2], 0.0);\n\t    COMPLEX_MUL3(ct6, ct4, PPRL, dt2);\n\t    COMPLEX_SUB (DFDP, ct5, ct6);\n\t    /* part2 = -r2 * SL[ia2] * PLc[ia2] * PPRL * PA2 * (S[0] * RS[ia1] + \n\t                                                        S[2] * RD[ia1] * PA1) -\n\t                r2 * DL[ia2] * PPRL * S[1] * RS[ia1] + S[3] * RD[ia1] * PA1) */\n\t    COMPLEX_SET (ct4, -root2*SL[ia2], 0.0);\n\t    COMPLEX_MUL5(ct5, ct4, PLc[ia2], PPRL, PA2, dt1);\n\t    COMPLEX_SET (ct4, root2*DL[ia2], 0.0);\n\t    COMPLEX_MUL3(ct6, ct4, PPRL, dt2);\n\t    COMPLEX_SUB (DFDP2, ct5, ct6);\n\t  }\n\t}\n\tbreak;\n      default:\n\tbreak;\n      }; /* end antenna parameter switch */\n      /* end antenna param */\n    } else if (paramType==polnParmSou) {   /* Source parameters */\n      /* Default partials  */\n      COMPLEX_SET (DFDP,  0.0, 0.0);\n      COMPLEX_SET (DFDP2, 0.0, 0.0);\n      switch (paramNumber) {   /* Switch over parameter */\n      case 0:     /* RL wrt I */\n\tif (souFit[isou][paramNumber]) {\n\t  /* part = MC1 + MC4 */\n\t  COMPLEX_ADD2(DFDP, MC1, MC4);\n\t}\n\tbreak;\n      case 1:     /* RL wrt QPol */\n\tif (souFit[isou][paramNumber]) {\n\t  /* part = MC2 + MC3 */\n\t  COMPLEX_ADD2(DFDP, MC2, MC3);\n\t}\n\tbreak;\n      case 2:     /* RL wrt UPol */\n\tif (souFit[isou][paramNumber]) {\n\t  /* part = i (MC2 - MC3) */\n\t  COMPLEX_SUB (ct3, MC2, MC3);\n\t  COMPLEX_SET(ct4, 0.0, 1.0);\n\t  COMPLEX_MUL2(DFDP, ct4, ct3);\n\t}\n\tbreak;\n      case 3:     /* RL wrt Vpol */\n\tif (souFit[isou][paramNumber]) {\n\t  /* part = MC1 - MC4 */\n\t  COMPLEX_SUB (DFDP, MC1, MC4);\n\t}\n\tbreak;  \n      default:\n\tbreak;\n      }; /* end source parameter switch */\n      /* end source param */\n    } else if (paramType==polnParmPD) {   /* R-L Phase difference */\n      COMPLEX_SET (ct1, 0.0,  -1.0);\n      COMPLEX_MUL2(DFDP, ct1, VRL);\n      COMPLEX_MUL2(DFDP2, ct1, DFDP);\n    } /* end R-L phase difference */\n    /* Accumulate partials */\n    if (paramType!=polnParmUnspec) {\n      sumd  += 2.0 * isigma * (residR*DFDP.real + residI*DFDP.imag);\n      sumd2 += 2.0 * isigma * (DFDP.real*DFDP.real + DFDP.imag*DFDP.imag +\n\t\t\t       residR*DFDP2.real + residI*DFDP2.imag);\n   } /* end set partials */\n  } /* end valid data */\n  \n    /*        LR */\n  if (wt[idata*4+3]>0.0) {\n    isigma = wt[idata*4+3];\n    /* VLR = PPLR * S[0] * LS[ia1] * RSc[ia2] * PA1c +\n             PPLR * S[1] * LS[ia1] * RDc[ia2] * PA1c * PA2c +\n\t     PPLR * S[2] * LD[ia1] * RSc[ia2] +\n\t     PPLR * S[3] * LD[ia1] * RDc[ia2] * PA2c */\n    COMPLEX_MUL4 (MC1, PPLR, LS[ia1], RSc[ia2], PA1c);\n    COMPLEX_MUL2 (VLR, S[0], MC1);\n    COMPLEX_MUL5 (MC2, PPLR, LS[ia1], RDc[ia2], PA1c,  PA2c);\n    COMPLEX_MUL2 (ct1, S[1], MC2);\n    COMPLEX_ADD2 (VLR, VLR,  ct1);\n    COMPLEX_MUL3 (MC3, PPLR, LD[ia1], RSc[ia2]);\n    COMPLEX_MUL2 (ct1, S[2], MC3);\n    COMPLEX_ADD2 (VLR, VLR,  ct1);\n    COMPLEX_MUL4 (MC4, PPLR, LD[ia1], RDc[ia2],  PA2c);\n    COMPLEX_MUL2 (ct1, S[3], MC4);\n    COMPLEX_ADD2 (VLR, VLR, ct1);\n    residR = VLR.real - data[idata*10+8];\n    sum += isigma * residR * residR; sumwt += isigma;\n    residI = VLR.imag - data[idata*10+9];\n    sum += isigma * residI * residI; sumwt += isigma;\n    nXobs++;\n    sumXResid += residR * residR + residI * residI;\n    /* Derivatives */\n    if (paramType==polnParmAnt) {         /* Antenna parameters */\n      /* Default partials if only refant on baseline */\n      COMPLEX_SET (DFDP,  0.0, 0.0);\n      COMPLEX_SET (DFDP2, 0.0, 0.0);\n      switch (paramNumber) {   /* Switch over parameter */\n      case 0:     /* LR wrt Or */\n\tif (isAnt2) {\n\t  if (antFit[ia2][paramNumber]) {\n\t    /* (0,-2 i) * (S[1]*MC2 + S[3]*MC4) */\n\t    COMPLEX_MUL2(ct1, S[1], MC2);\n\t    COMPLEX_MUL2(ct2, S[3], MC4);\n\t    COMPLEX_ADD2(ct3, ct1, ct2);\n\t    COMPLEX_SET (ct1, 0.0, -2.0);\n\t    COMPLEX_MUL2(DFDP, ct1, ct3);\n\t    COMPLEX_MUL2(DFDP2, ct1, DFDP);\n\t  }\n\t} \n\t/* If ia2==refant */\n\tif (ia2==args->refAnt) {\n\t  COMPLEX_SET (ct1, 0.0, -1.0);\n\t  COMPLEX_MUL2(ct2, ct1, VLR);\n\t  COMPLEX_ADD2(DFDP, DFDP, ct2);\n\t  COMPLEX_MUL2(ct2, ct1, DFDP);\n\t  COMPLEX_ADD2(DFDP2, DFDP2, ct2);\n\t}\n\tbreak;\n      case 1:     /* LR wrt Er */\n\tif (isAnt2) {\n\t  if (antFit[ia2][paramNumber]) {\n\t    /* part = r2 * DR[ia2] * (PPLR * S[0] * LS[ia1] * PA1c + PPLR * S[2] * LD[ia1]) -\n\t              r2 * SR[ia2] * PRc[ia2] * (PPLR * S[1] * LS[ia1] * PA1c * PA2c + \n\t                                         PPLR * S[3] * LD[ia1] * PA2c) */\n\t    COMPLEX_MUL3(ct1, S[0], LS[ia1], PA1c);\n\t    COMPLEX_MUL2(ct2, S[2], LD[ia1]);\n\t    COMPLEX_ADD2(dt1, ct1, ct2);\n\t    COMPLEX_SET (ct4, root2*DR[ia2], 0.0);\n\t    COMPLEX_MUL3(ct5, ct4, PPLR, dt1);\n\t    COMPLEX_MUL3(ct1, S[1], LS[ia1], PA1c);\n\t    COMPLEX_MUL2(ct2, S[3], LD[ia1]);\n\t    COMPLEX_ADD2(dt2, ct1, ct2);\n\t    COMPLEX_SET (ct4, root2*SR[ia2], 0.0);\n\t    COMPLEX_MUL5(ct6, ct4, PRc[ia2], PPLR, PA2c, dt2);\n\t    COMPLEX_SUB (DFDP, ct5, ct6);\n\t    /* part2 = -r2 * SR[ia2] * (PPLR * S[0] * LS[ia1] * PA1c + PPLR * S[2] * LD[ia1]) -\n\t                r2 * DR[ia2] * PRc[ia2] * (PPLR * S[1] * LS[ia1] * PA1c * PA2c + \n\t                                           PPLR * S[3] * LD[ia1] * PA2c) */\n\t    COMPLEX_SET (ct4, -root2*SR[ia2], 0.0);\n\t    COMPLEX_MUL3(ct5, ct4, PPLR, dt1);\n\t    COMPLEX_SET (ct4, root2*DR[ia2], 0.0);\n\t    COMPLEX_MUL5(ct6, ct4, PRc[ia2], PPLR, PA2c, dt2);\n\t    COMPLEX_SUB (DFDP2, ct5, ct6);\n\t  }\n\t}\n\tbreak;\n      case 2:     /* LR wrt Ol */\n\tif (isAnt1) {\n\t  if (antFit[ia1][paramNumber]) {\n\t    /* (0,-2 i) * (S[0]*MC1 + S[1]*MC2) */\n\t    COMPLEX_MUL2(ct1, S[0], MC1);\n\t    COMPLEX_MUL2(ct2, S[1], MC2);\n\t    COMPLEX_ADD2(ct3, ct1, ct2);\n\t    COMPLEX_SET (ct1, 0.0, -2.0);\n\t    COMPLEX_MUL2(DFDP, ct1, ct3);\n\t    COMPLEX_MUL2(DFDP2, ct1, DFDP);\n\t  }\n\t  /* If ia1==refant) */\n\t} else  if (ia1==args->refAnt) {\n\t  COMPLEX_SET (ct1, 0.0, -1.0);\n\t  COMPLEX_MUL2(ct2, ct1, VLR);\n\t  COMPLEX_ADD2(DFDP, DFDP, ct2);\n\t  COMPLEX_MUL2(ct2, ct1, DFDP);\n\t  COMPLEX_ADD2(DFDP2, DFDP2, ct2);\n\t}\n\tbreak;\n      case 3:     /* LR wrt El */\n\tif (isAnt1) {\n\t  if (antFit[ia1][paramNumber]) {\n\t    /* part = r2 * DL[ia1] * PL[ia1] * PPLR * PA1c * (S[0] * RSc[ia2 + \n\t                                                      S[1] * RDc[ia2] * PA2c) -\n\t              r2 * SL[ia1] * PPLR * (S[2] * RSc[ia2] + S[3] * RDc[ia2] * PA2c) */\n\t    COMPLEX_MUL2(ct1, S[0], RSc[ia2]);\n\t    COMPLEX_MUL3(ct2, S[1], RDc[ia2], PA1c);\n\t    COMPLEX_ADD2(dt1, ct1, ct2);\n\t    COMPLEX_SET (ct4, root2*DL[ia1], 0.0);\n\t    COMPLEX_MUL5(ct5, ct4, PL[ia1], PPLR, PA1c, dt1);\n\t    COMPLEX_MUL2(ct1, S[2], RSc[ia2]);\n\t    COMPLEX_MUL3(ct2, S[3], RDc[ia2], PA2c);\n\t    COMPLEX_ADD2(dt2, ct1, ct2);\n\t    COMPLEX_SET (ct4, root2*SL[ia1], 0.0);\n\t    COMPLEX_MUL3(ct6, ct4, PPLR, dt2);\n\t    COMPLEX_SUB (DFDP, ct5, ct6);\n\t    /* part2 = -r2 * SL[ia1] * PL[ia1] * PPLR * PA1c * (S[0] * RSc[ia2]  + \n\t                                                        S[1] * RDc[ia2] * PA2c) -\n\t                r2 * DL[ia1] * PPLR * (S[2] * RSc[ia2] + S[3] * RDc[ia2] * PA2c) */\n\t    COMPLEX_SET (ct4, -root2*SL[ia1], 0.0);\n\t    COMPLEX_MUL5(ct5, ct4, PL[ia1], PPLR, PA1c, dt1);\n\t    COMPLEX_SET (ct4, root2*DL[ia1], 0.0);\n\t    COMPLEX_MUL3(ct6, ct4, PPLR, dt2);\n\t    COMPLEX_SUB (DFDP2, ct5, ct6);\n\t  }\n\t}\n\tbreak;\n      default:\n\tbreak;\n      }; /* end antenna parameter switch */\n      /* end antenna param */\n    } else if (paramType==polnParmSou) {   /* Source parameters */\n      /* Default partials  */\n      COMPLEX_SET (DFDP,  0.0, 0.0);\n      COMPLEX_SET (DFDP2, 0.0, 0.0);\n      switch (paramNumber) {   /* Switch over parameter */\n      case 0:     /* LR wrt I */\n\tif (souFit[isou][paramNumber]) {\n\t  /* part = MC1 + MC4 */\n\t  COMPLEX_ADD2(DFDP, MC1, MC4);\n\t}\n\tbreak;\n      case 1:     /* LR wrt QPol */\n\tif (souFit[isou][paramNumber]) {\n\t  /* part = MC2 + MC3 */\n\t  COMPLEX_ADD2(DFDP, MC2, MC3);\n\t}\n\tbreak;\n      case 2:     /* LR wrt UPol */\n\tif (souFit[isou][paramNumber]) {\n\t  /* part = i (MC2 - MC3) */\n\t  COMPLEX_SUB (ct3, MC2, MC3);\n\t  COMPLEX_SET(ct4, 0.0, 1.0);\n\t  COMPLEX_MUL2(DFDP, ct4, ct3);\n\t}\n\tbreak;\n      case 3:     /* LR wrt Vpol */\n\tif (souFit[isou][paramNumber]) {\n\t  /* part = MC1 - MC4 */\n\t  COMPLEX_SUB (DFDP, MC1, MC4);\n\t}\n\tbreak;  \n      default:\n\tbreak;\n      }; /* end source parameter switch */\n      /* end source param */\n    } else if (paramType==polnParmPD) {   /* R-L Phase difference */\n      /* No dependence on MORE HERE */\n      COMPLEX_SET (ct1, 0.0, 1.0);\n      COMPLEX_MUL2(DFDP, ct1, VRL);\n      COMPLEX_MUL2(DFDP2, ct1, DFDP);\n    } /* end R-L phase difference */\n    /* Accumulate partials */\n    if (paramType!=polnParmUnspec) {\n      sumd  += 2.0*isigma * (residR*DFDP.real + residI*DFDP.imag);\n      sumd2 += 2.0*isigma * (DFDP.real*DFDP.real + DFDP.imag*DFDP.imag +\n\t\t\t      residR*DFDP2.real + residI*DFDP2.imag);\n      } /* end set partials */\n    }  /* end valid data */\n  } /* End loop over visibilities */\n  \n  if (sumwt<=0.0) sumwt = 1.0;  /* Trap no data */\n  args->ChiSq       = sum;   /* Save results  */\n  args->sumParResid = sumParResid;\n  args->sumXResid   = sumXResid;\n  args->sumWt       = sumwt;\n  args->nPobs       = nPobs;\n  args->nXobs       = nXobs;\n  if (paramType!=polnParmUnspec) args->sumDeriv  = sumd;\n  if (paramType!=polnParmUnspec) args->sumDeriv2 = sumd2;\n\n /* Indicate completion if threaded */\n  if (args->ithread>=0)\n    ObitThreadPoolDone (args->thread, (gpointer)&args->ithread);\n\n  return NULL;\n\n} /*  end ThreadPolnFitRLChi2 */\n\n/**\n * Linear polarization version.\n * Threaded Chi**2 evaluator for polarization fitting\n * Evaluates sum [(model-observed) / sigma] and derivatives\n * Parallel hands count 0.3 of cross in sums\n * If selAnt or selSou are set, then only data involving that \n * source or antenna (or ref ant) is included.\n * \\param arg   PolnFitArg pointer with elements:\n * \\li lo       First 0-rel datum in Data/Wt arrays\n * \\li hi       Last 0-rel datum  in Data/Wt arrays\n * \\li selAnt   selected antenna, -1-> all\n * \\li selSou   selected source,  -1-> all\n * \\li paramType       Parameter type\n * \\li polnParmUnspec  Unspecified = don't compute derivatives\n * \\li polnParmAnt     Antenna parameter\n * \\li polnParmGain    Antenna gains\n * \\li polnParmSou     Source parameter\n * \\li polnParmPD      Phase difference\n * \\li paramNumber  Parameter number,\n *                     Sou: 0=Ipol, 1=Qpol, 2=Upol, 3=VPol\n                       Ant: 0= Ori R/X, 1=Elp R/X, 2= Ori L/Y, 1=Elp L/Y,       \n * \\li ChiSq        [out] computed Chi2\n * \\li nPobs        [out] Number of valid parallel measurements\n * \\li nXobs        [out] Number of valid cross pol measurements\n * \\li ParRMS       [out] Parallel hand RMS\n * \\li sumParResid  [out] Cross hand RMS\n * \\li sumXResid    [out] First derivative of Chi2 wrt parameter\n * \\li d2Chi2       [out] Second derivative of Chi2 wrt parameter\n * \\li ithread  thread number, <0 -> no threading\n * \\return NULL\n */\nstatic gpointer ThreadPolnFitXYChi2 (gpointer arg)\n{\n  PolnFitArg *args = (PolnFitArg*)arg;\n  odouble    *antParm   = args->antParm;\n  gboolean   **antFit   = args->antFit;\n  odouble    *antGain   = args->antGain;\n  gboolean   **antGainFit= args->antGainFit;\n  odouble    *souParm   = args->souParm;\n  gboolean   **souFit   = args->souFit;\n  ofloat     *data      = args->inData;\n  ofloat     *wt        = args->inWt;\n  dcomplex   *CX        = args->RS;\n  dcomplex   *SX        = args->RD;\n  dcomplex   *CY        = args->LS;\n  dcomplex   *SY        = args->LD;\n  dcomplex   *CXc       = args->RSc;\n  dcomplex   *SXc       = args->RDc;\n  dcomplex   *CYc       = args->LSc;\n  dcomplex   *SYc       = args->LDc;\n  PolnParmType paramType = args->paramType;\n  olong paramNumber      = args->paramNumber;\n  olong selSou           = args->selSou;\n  olong selAnt           = args->selAnt;\n\n  odouble ipol=0.0, qpol=0.0, upol=0.0, vpol=0.0;\n  odouble residR=0.0, residI=0.0, isigma=0.0;\n  odouble sumParResid, sumXResid;\n  ofloat PD, chi1, chi2, PPol;\n  olong nPobs, nXobs, ia1, ia2, isou, idata, isouLast=-999;\n  gboolean isAnt1=FALSE, isAnt2=FALSE;\n  size_t i;\n  odouble sum=0.0, sumwt=0.0, sumd, sumd2;\n\n  dcomplex  SPA, DPA, SPAc, DPAc, ggPD;\n  dcomplex ct1, ct2, ct3, ct4, ct5, Jm, Jp;\n  dcomplex S0[4], S[4], VXX, VXY, VYX, VYY, MC1, MC2, MC3, MC4, DFDP, DFDP2;\n  dcomplex SM1, SM2, SM3, SM4;\n\n  /* DEBUG */\n#ifdef DEBUG\n  olong dbgCnt1, dbgCnt2;\n  ofloat dbgSum1, dbgSum2, dbgISum1, dbgISum2;\n#endif\n\n  COMPLEX_SET (S[0], 0.0, 0.0);  /* Initialize poln vector */\n  COMPLEX_SET (S[1], 0.0, 0.0);\n  COMPLEX_SET (S[2], 0.0, 0.0);\n  COMPLEX_SET (S[3], 0.0, 0.0);\n  COMPLEX_SET (S0[0], 0.0, 0.0);\n  COMPLEX_SET (S0[1], 0.0, 0.0);\n  COMPLEX_SET (S0[2], 0.0, 0.0);\n  COMPLEX_SET (S0[3], 0.0, 0.0);\n  COMPLEX_SET (MC1, 0.0, 0.0);  /* Other stuff */\n  COMPLEX_SET (MC2, 0.0, 0.0);\n  COMPLEX_SET (MC3, 0.0, 0.0);\n  COMPLEX_SET (MC4, 0.0, 0.0);\n  COMPLEX_SET (VXX, 0.0, 0.0);\n  COMPLEX_SET (VYY, 0.0, 0.0);\n  COMPLEX_SET (VYX, 0.0, 0.0);\n  COMPLEX_SET (VXY, 0.0, 0.0);\n  COMPLEX_SET (DFDP,  0.0, 0.0);\n  COMPLEX_SET (DFDP2, 0.0, 0.0);\n  COMPLEX_SET (Jm,  0.0,-1.0);\n  COMPLEX_SET (Jp,  0.0, 1.0);\n  /* Init others */\n  isouLast=-999;\n  sum = sumwt = 0.0;\n  ipol = qpol = upol = vpol = 0.0;\n  residR = residI = isigma = 0.0;\n  isAnt1 = isAnt2 = TRUE;\n\n  /* RMS sums and counts */\n  sumParResid = sumXResid = 0.0;\n  sumd = sumd2 = 0.0;\n  nPobs = nXobs = 0;\n  /* X-Y phase difference  at reference antenna */\n  PD = args->PD;\n\n  /* Injest model, factorize into antenna components - \n     data in order Orientation R/X, Elipticity R/X, Orientation L/Y, Elipticity L/Y */\n  /* Elipticity, Orientation terms */\n  for (i=0; i<args->nant; i++) {\n    COMPLEX_EXP (ct1, -antParm[i*4+0]);\n    COMPLEX_SET (ct2, cos(G_PI*0.25+antParm[i*4+1]), 0.0);\n    COMPLEX_MUL2 (CX[i], ct2, ct1);\n    COMPLEX_EXP (ct1, antParm[i*4+0]);\n    COMPLEX_SET (ct2, sin(G_PI*0.25+antParm[i*4+1]), 0.0);\n    COMPLEX_MUL2 (SX[i], ct2, ct1);\n    COMPLEX_EXP (ct1, antParm[i*4+2]);\n    COMPLEX_SET (ct2, cos(G_PI*0.25-antParm[i*4+3]), 0.0);\n    COMPLEX_MUL2 (CY[i], ct2, ct1);\n    COMPLEX_EXP (ct1, -antParm[i*4+2]);\n    COMPLEX_SET (ct2, sin(G_PI*0.25-antParm[i*4+3]), 0.0);\n    COMPLEX_MUL2 (SY[i], ct2, ct1);\n\n    COMPLEX_CONJUGATE (CXc[i], CX[i]);\n    COMPLEX_CONJUGATE (SXc[i], SX[i]);\n    COMPLEX_CONJUGATE (CYc[i], CY[i]);\n    COMPLEX_CONJUGATE (SYc[i], SY[i]);\n\n    /* Default X gain = 1.0/Y gain\n    if (!antGainFit[i][0]) antGain[i*2+0] = 1.0 / antGain[i*2+1]; */\n  }\n\n  /* Loop over data */\n  i = 0;\n  for (idata=args->lo; idata<args->hi; idata++) {\n     isou  = MAX (0, args->souNo[idata]);    /* Source number */\n    /* Selected source? */\n    if ((selSou>=0) && (selSou!=isou)) continue;\n\n    /* Antenna parameters (0 ref) */\n    ia1    = args->antNo[idata*2+0];\n    ia2    = args->antNo[idata*2+1]; \n    /* Selected source? */\n    if ((selAnt>=0) && (selAnt!=ia1) && (selAnt!=ia2)) continue;\n    /* Which antenna is the selected one in the baseline? */\n    if (selAnt==ia1) {isAnt1 = TRUE; isAnt2 = FALSE;}\n    else if (selAnt==ia2) {isAnt2 = TRUE; isAnt1 = FALSE;}\n    \n    /* Parallactic angle terms */\n    chi1  = data[idata*10+0];   /* parallactic angle ant 1 */\n    chi2  = data[idata*10+1];   /* parallactic angle ant 2 */\n    COMPLEX_EXP (SPA,(chi1+chi2));\n    COMPLEX_EXP (DPA,chi1-chi2);\n    COMPLEX_CONJUGATE (SPAc, SPA);\n    COMPLEX_CONJUGATE (DPAc, DPA);\n\n    /* New source? get parameters */\n    if (isou!=isouLast) {\n      isouLast = isou;\n      /* Source parameters */\n      ipol = souParm[isou*4+0];\n      /* Fitting or fixed? */\n      if (args->souFit[isou][1]) \n\tqpol = souParm[isou*4+1];\n      else {\n\tPPol = args->PPol[isou] + args->dPPol[isou]*(args->curFreq-args->refFreq);\n\tqpol = PPol*ipol*cos(args->RLPhase[isou]);}\n      if (args->souFit[isou][2]) \n\tupol = souParm[isou*4+2];\n      else {\n\tPPol = args->PPol[isou] + args->dPPol[isou]*(args->curFreq-args->refFreq);\n\tupol = PPol*ipol*sin(args->RLPhase[isou]);}\n      vpol = souParm[isou*4+3];\n      /* Complex Stokes array */\n      COMPLEX_SET (S0[0], ipol+vpol, 0.0);\n      COMPLEX_SET (S0[1], qpol,  upol);\n      COMPLEX_SET (S0[2], qpol, -upol);\n      COMPLEX_SET (S0[3], ipol-vpol, 0.0);\n    }\n\n    /* Rotate Stokes by parallactic angle */\n    COMPLEX_MUL2(S[0], DPAc, S0[0]);\n    COMPLEX_MUL2(S[1], SPAc, S0[1]);\n    COMPLEX_MUL2(S[2], SPA,  S0[2]);\n    COMPLEX_MUL2(S[3], DPA,  S0[3]);\n    \n    /* Calculate residals -  XX */\n  if (wt[idata*4]>0.0) {\n    isigma = wt[idata*4];\n    \n    /* VXX = {S[0] * CX[ia1] * CXc[ia2]  +\n              S[1] * CX[ia1] * SXc[ia2]  +\n\t      S[2] * SX[ia1] * CXc[ia2]  + \n\t      S[3] * SX[ia1] * SXc[ia2]} * g1X * g2X ;\n    */\n    COMPLEX_MUL2 (MC1, CX[ia1], CXc[ia2]);\n    COMPLEX_MUL2 (MC2, CX[ia1], SXc[ia2]);\n    COMPLEX_MUL2 (MC3, SX[ia1], CXc[ia2]);\n    COMPLEX_MUL2 (MC4, SX[ia1], SXc[ia2]);\n    COMPLEX_MUL2 (SM1, S[0], MC1);\n    COMPLEX_MUL2 (SM2, S[1], MC2);\n    COMPLEX_MUL2 (SM3, S[2], MC3);\n    COMPLEX_MUL2 (SM4, S[3], MC4);\n    COMPLEX_ADD4 (ct5, SM1, SM2, SM3, SM4);\n    COMPLEX_SET (ggPD,  antGain[ia1*2+0]*antGain[ia2*2+0], 0);\n    COMPLEX_MUL2 (VXX, ct5, ggPD);\n    residR = VXX.real - data[idata*10+2];\n    sum += isigma * residR * residR; sumwt += isigma;\n    residI = VXX.imag - data[idata*10+3];\n    sum += isigma * residI * residI; sumwt += isigma;\n    nPobs++;\n    sumParResid += residR * residR + residI * residI;\n    /* Derivatives */\n    /* Default partials */\n    COMPLEX_SET (DFDP,  0.0, 0.0);\n    COMPLEX_SET (DFDP2, 0.0, 0.0);\n    if (paramType==polnParmAnt) {         /* Antenna parameters */\n      switch (paramNumber) {   /* Switch over parameter */\n      case 0:     /* XX wrt Ox */\n\tif (isAnt1) {\n\t  if (antFit[ia1][paramNumber]) {\n\t    /* {(0, -1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + \n\t        (0,  1) * S[2] * MC3 + (0,  1) * S[3] * MC4}  * gX[ia1] * gX[ia2]  */\n\t    COMPLEX_ADD2 (ct1, SM1, SM2);\n\t    COMPLEX_MUL2 (ct2, Jm, ct1);\n\t    COMPLEX_ADD2 (ct1, SM3, SM4);\n\t    COMPLEX_MUL2 (ct3, Jp, ct1);\n\t    COMPLEX_ADD2 (ct2, ct2, ct3);\n\t    COMPLEX_MUL2 (DFDP, ct2, ggPD);\n\t    /* -VXX */\n\t    COMPLEX_NEGATE(DFDP2, VXX);\n\t  }\n\t} else if (isAnt2) {\n\t  if (antFit[ia2][paramNumber]) {\n\t    /* {(0,  1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + \n\t        (0,  1) * S[2] * MC3 + (0, -1) * S[3] * MC4}  * gX[ia1] * gX[ia2]   */\n\t    COMPLEX_ADD2 (ct1, SM1, SM3);\n\t    COMPLEX_MUL2 (ct2, Jp, ct1);\n\t    COMPLEX_ADD2 (ct1, SM2, SM4);\n\t    COMPLEX_MUL2 (ct3, Jm, ct1);\n\t    COMPLEX_ADD2 (ct2, ct2, ct3);\n\t    COMPLEX_MUL2 (DFDP, ct2, ggPD);\n\t    /*  -VXX  */\n\t    COMPLEX_NEGATE(DFDP2, VXX);\n\t  }\n\t} \n\tbreak;\n      case 1:     /* XX wrt Ex */\n\tif (isAnt1) {\n\t  if (antFit[ia1][paramNumber]) {\n\t    /* part = {-S[0] * CXc[ia2] * SXc[ia1] -\n\t                S[1] * SXc[ia2] * SXc[ia1] +\n\t\t        S[2] * CXc[ia2] * CXc[ia1] +\t       \n\t\t        S[3] * SXc[ia2] * CXc[ia1]}  * gX[ia1] * gX[ia2]  */\n\t    COMPLEX_MUL3(ct5, S[0], CXc[ia2], SXc[ia1]);\n\t    COMPLEX_NEGATE(ct1, ct5);\n\t    COMPLEX_MUL3(ct5, S[1], SXc[ia2], SXc[ia1]);\n\t    COMPLEX_NEGATE(ct2, ct5);\n\t    COMPLEX_MUL3(ct3, S[2], CXc[ia2], SXc[ia1]);\n\t    COMPLEX_MUL3(ct4, S[3], SXc[ia2], CXc[ia1]);\n\t    COMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4);\n\t    COMPLEX_MUL2(DFDP, ct5, ggPD);\n\t    /* part2 = -VXX */\n\t    COMPLEX_NEGATE(DFDP2, VXX);\n\t  }\n\t} else if (isAnt2) {\n\t  if (antFit[ia2][paramNumber]) {\n\t    /* part = {-S[0] * CX[ia1] * SX[ia2] +\n                        S[1] * CX[ia1] * CX[ia2] -\n\t\t        S[2] * SX[ia1] * SX[ia2] +\n\t\t        S[3] * SX[ia1] * CX[ia2]} * gX[ia1] * gX[ia2]  */\n\t    COMPLEX_MUL3(ct5, S[0], CX[ia1], SX[ia2]);\n\t    COMPLEX_NEGATE(ct1, ct5);\n\t    COMPLEX_MUL3(ct2, S[1], CX[ia1], CX[ia2]);\n\t    COMPLEX_MUL3(ct5, S[2], SX[ia1], SX[ia2]);\n\t    COMPLEX_NEGATE(ct3, ct5);\n\t    COMPLEX_MUL3(ct4, S[3], SX[ia1], CX[ia2]);\n\t    COMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4);\n\t    COMPLEX_MUL2(DFDP, ct5, ggPD);\n\t    /* part2 = -VXX */\n\t    COMPLEX_NEGATE(DFDP2, VXX);\n\t  }\n\t}\n\tbreak;\n      case 2:     /* XX wrt Oy - nope */\n\tbreak;\n      case 3:     /* XX wrt Ey - nope */\n\tbreak;\n      default:\n\tbreak;\n\t}; /* end antenna parameter switch */\n\t/* end antenna param */\n      } else if (paramType==polnParmSou) {   /* Source parameters */\n      switch (paramNumber) {   /* Switch over parameter */\n      case 0:     /* XX wrt I */\n\tif (souFit[isou][paramNumber]) {\n\t  /* part =   (MC1*DPAc + MC4*DPA) * gX[ia1] * gX[ia2] */\n\t  COMPLEX_MUL2(ct2, MC1, DPAc);\n\t  COMPLEX_MUL2(ct3, MC4, DPA);\n\t  COMPLEX_ADD2(ct1, ct2, ct3);\n\t  COMPLEX_MUL2(DFDP, ct1, ggPD);\n\t}\n\tbreak;\n      case 1:     /* XX wrt QPol */\n\tif (souFit[isou][paramNumber]) {\n\t  /* part = (MC2*SPAc + MC3*SPA) * gX[ia1] * gX[ia2] */\n\t  COMPLEX_MUL2(ct2, MC2, SPAc);\n\t  COMPLEX_MUL2(ct3, MC3, SPA);\n\t  COMPLEX_ADD2(ct1, ct2, ct3);\n\t  COMPLEX_MUL2(DFDP, ct1, ggPD);\n\t}\n\tbreak;\n      case 2:     /* XX wrt UPol */\n\tif (souFit[isou][paramNumber]) {\n\t  /* (j MC2*SPAc - j MC3*SPA) * gX[ia1] * gX[ia2] */\n\t  COMPLEX_MUL3(ct2, Jp, MC2, SPAc);\n\t  COMPLEX_MUL3(ct3, Jp, MC3, SPA);\n\t  COMPLEX_SUB(ct1, ct2, ct3);\n\t  COMPLEX_MUL2(DFDP, ct1, ggPD);\n\t}\n\tbreak;\n      case 3:     /* XX wrt Vpol */\n\tif (souFit[isou][paramNumber]) {\n\t  /* (MC1*DPAc - MC4*DPA) * gX[ia1] * gX[ia2] */\n\t  COMPLEX_MUL2(ct2, MC1, DPAc);\n\t  COMPLEX_MUL2(ct3, MC4, DPA);\n\t  COMPLEX_SUB(ct1, ct2, ct3);\n\t  COMPLEX_MUL2(DFDP, ct1, ggPD);\n\t}\n\tbreak;  \n      default:\n\tbreak;\n      }; /* end source parameter switch */\n      /* end source param */\n\n    } else if (paramType==polnParmGain) {   /* Antenna Gains */\n      switch (paramNumber) {   /* Switch over parameter */\n      case 0:     /* XX wrt gX */\n\tif (isAnt1 && (antGainFit[ia1][paramNumber])) {\n\t  /* part = (S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) * gX[ia2] */\n\t  COMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4);\n\t  COMPLEX_SET (ct2, antGain[ia2*2+0], 0);\n\t  COMPLEX_MUL2 (DFDP, ct1, ct2);\n\t  /* part2 = 0 */\n\t} else if (isAnt2 && (antGainFit[ia2][paramNumber])) {\n\t  /* part = (S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) * gX[ia1] */\n\t  COMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4);\n\t  COMPLEX_SET (ct2, antGain[ia1*2+0], 0);\n\t  COMPLEX_MUL2 (DFDP, ct1, ct2);\n\t  /* part2 = 0 */\n\t}\n\tbreak;\n      case 1:     /* XX wrt gY - nope */\n\tbreak;\n       default:\n\tbreak;\n      }  /* end gain switch */\n    } else if (paramType==polnParmPD) {   /* X-Y phase difference */\n    } /* end parameter types */\n    /* Accumulate partials */\n    if (paramType!=polnParmUnspec) {\n      sumd  += 2.0 * isigma * (residR*DFDP.real + residI*DFDP.imag); \n      sumd2 += 2.0 * isigma * (DFDP.real*DFDP.real + DFDP.imag*DFDP.imag +\n\t\t\t       residR*DFDP2.real + residI*DFDP2.imag);\n    } /* end set partials */\n  } /* end valid data */\n  \n  /*      YY */\n  if (wt[idata*4+1]>0.0) {\n    isigma = wt[idata*4+1];\n    /* VYY = {S[0] * SY[ia1] * SYc[ia2] +       \n              S[1] * SY[ia1] * CYc[ia2] +\n\t      S[2] * CY[ia1] * SYc[ia2] + \n\t      S[3] * CY[ia1] * CYc[ia2]} * g1Y * g2Y ;\n    */\n    COMPLEX_MUL2 (MC1, SY[ia1], SYc[ia2]);\n    COMPLEX_MUL2 (MC2, SY[ia1], CYc[ia2]);\n    COMPLEX_MUL2 (MC3, CY[ia1], SYc[ia2]);\n    COMPLEX_MUL2 (MC4, CY[ia1], CYc[ia2]);\n    COMPLEX_MUL2 (SM1, S[0], MC1);\n    COMPLEX_MUL2 (SM2, S[1], MC2);\n    COMPLEX_MUL2 (SM3, S[2], MC3);\n    COMPLEX_MUL2 (SM4, S[3], MC4);\n    COMPLEX_ADD4 (ct5, SM1, SM2, SM3, SM4);\n    COMPLEX_SET (ggPD,  antGain[ia1*2+1]*antGain[ia2*2+1], 0); \n    COMPLEX_MUL2 (VYY, ct5, ggPD);\n    residR = VYY.real - data[idata*10+4];\n    sum += isigma * residR * residR; sumwt += isigma; \n    residI = VYY.imag - data[idata*10+5];\n    sum += isigma * residI * residI; sumwt += isigma; \n    nPobs++;\n    sumParResid += residR * residR + residI * residI;\n    /* Derivatives */\n    /* Default partials  */\n    COMPLEX_SET (DFDP,  0.0, 0.0);\n    COMPLEX_SET (DFDP2, 0.0, 0.0);\n    if (paramType==polnParmAnt) {         /* Antenna parameters */\n      /* Default partials */\n      COMPLEX_SET (DFDP,  0.0, 0.0);\n      COMPLEX_SET (DFDP2, 0.0, 0.0);\n      switch (paramNumber) {   /* Switch over parameter */\n      case 0:     /* YY wrt Ox - nope */\n\tbreak;\n      case 1:     /* YY wrt Ex - nope*/\n\tbreak;\n      case 2:     /* YY wrt Oy */\n\tif (isAnt1) {\n\t  if (antFit[ia1][paramNumber]) {\n\t    /* part = {(0, -1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + \n\t               (0,  1) * S[2] * MC3 + (0,  1) * S[3] * MC4} * gY[ia1] * gY[ia2] */\n\t    COMPLEX_ADD2 (ct1, SM1, SM2);\n\t    COMPLEX_MUL2 (ct2, Jm, ct1);\n\t    COMPLEX_ADD2 (ct1, SM3, SM4);\n\t    COMPLEX_MUL2 (ct3, Jp, ct1);\n\t    COMPLEX_ADD2 (ct2, ct2, ct3);\n\t    COMPLEX_MUL2 (DFDP, ct2, ggPD);\n\t    /* part2 = -VYY */\n\t    COMPLEX_NEGATE(DFDP2, VYY);\n\t  }\n\t} else if (isAnt2) {\n\t  if (antFit[ia2][paramNumber]) {\n\t    /* part = {(0,  1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + \n                       (0,  1) * S[2] * MC3 + (0, -1) * S[3] * MC4} * gY[ia1] * gY[ia2]  */\n\t    COMPLEX_ADD2 (ct1, SM1, SM3);\n\t    COMPLEX_MUL2 (ct2, Jp, ct1);\n\t    COMPLEX_ADD2 (ct1, SM2, SM4);\n\t    COMPLEX_MUL2 (ct3, Jm, ct1);\n\t    COMPLEX_ADD2 (ct2, ct2, ct3);\n\t    COMPLEX_MUL2 (DFDP,  ct2, ggPD);\n\t    /* part2 = -VYY */\n\t    COMPLEX_NEGATE(DFDP2, VYY);\n\t  }\n\t}\n\tbreak;\n      case 3:     /* YY wrt Ey */\n\tif (isAnt1) {\n\t  if (antFit[ia1][paramNumber]) {\n\t    /* part = {-S[0] * SYc[ia2] * CYc[ia1] -\n                        S[1] * CYc[ia2] * CYc[ia1] +\n\t\t        S[2] * SYc[ia2] * SYc[ia1] +\t       \n\t\t        S[3] * CYc[ia2] * SYc[ia1]}  * gX[ia1] * gX[ia2]  */\n\t    COMPLEX_MUL3(ct5, S[0], SYc[ia2], CYc[ia1]);\n\t    COMPLEX_NEGATE(ct1, ct5);\n\t    COMPLEX_MUL3(ct5, S[1], CYc[ia2], CYc[ia1]);\n\t    COMPLEX_NEGATE(ct2, ct5);\n\t    COMPLEX_MUL3(ct3, S[2], SYc[ia2], SYc[ia1]);\n\t    COMPLEX_MUL3(ct4, S[3], CYc[ia2], SYc[ia1]);\n\t    COMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4);\n\t    COMPLEX_MUL2(DFDP, ct5, ggPD);\n\t    /* part2 = -VYY */\n\t    COMPLEX_NEGATE(DFDP2, VYY);\n\t  }\n\t} else if (isAnt2) {\n\t  if (antFit[ia2][paramNumber]) {\n\t    /* part = {-S[0] * SY[ia1] * CY[ia2] + \n                        S[1] * SY[ia1] * SY[ia2] -\n\t\t        S[2] * CY[ia1] * CY[ia2]  + \n\t\t        S[3] * CY[ia1] * SY[ia2]} * gY[ia1] * gY[ia2] */\n\t    COMPLEX_MUL3(ct5, S[0], SY[ia1], CY[ia2]);\n\t    COMPLEX_NEGATE(ct1, ct5);\n\t    COMPLEX_MUL3(ct2, S[1], SY[ia1], SY[ia2]);\n\t    COMPLEX_MUL3(ct5, S[2], CY[ia1], CY[ia2]);\n\t    COMPLEX_NEGATE(ct3, ct5);\n\t    COMPLEX_MUL3(ct4, S[3], CY[ia1], SY[ia2]);\n\t    COMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4);\n\t    COMPLEX_MUL2(DFDP, ct5, ggPD);\n\t    /* part2 = -VYY */\n\t    COMPLEX_NEGATE(DFDP2, VYY);\n\t  }\n\t}\n\tbreak;\n      default:\n\tbreak;\n      }; /* end antenna parameter switch */\n      /* end antenna param */\n    } else if (paramType==polnParmSou) {   /* Source parameters */\n      switch (paramNumber) {   /* Switch over parameter */\n      case 0:     /* YY wrt IPol */\n\tif (souFit[isou][paramNumber]) {\n\t  /* part =   (MC1*DPAc + MC4*DPA) * gX[ia1] * gX[ia2] */\n\t  COMPLEX_MUL2(ct2, MC1, DPAc);\n\t  COMPLEX_MUL2(ct3, MC4, DPA);\n\t  COMPLEX_ADD2(ct1, ct2, ct3);\n\t  COMPLEX_MUL2(DFDP, ct1, ggPD);\n\t}\n\tbreak;\n      case 1:     /* YY wrt QPol */\n\tif (souFit[isou][paramNumber]) {\n\t  /* part = (MC2*SPAc + MC3*SPA) * gX[ia1] * gX[ia2] */\n\t  COMPLEX_MUL2(ct2, MC2, SPAc);\n\t  COMPLEX_MUL2(ct3, MC3, SPA);\n\t  COMPLEX_ADD2(ct1, ct2, ct3);\n\t  COMPLEX_MUL2(DFDP, ct1, ggPD);\n\t}\n\tbreak;\n      case 2:     /* YY wrt UPol */\n\tif (souFit[isou][paramNumber]) {\n\t  /* (j MC2*SPAc - j MC3*SPA) * gX[ia1] * gX[ia2] */\n\t  COMPLEX_MUL3(ct2, Jp, MC2, SPAc);\n\t  COMPLEX_MUL3(ct3, Jp, MC3, SPA);\n\t  COMPLEX_SUB(ct1, ct2, ct3);\n\t  COMPLEX_MUL2(DFDP, ct1, ggPD);\n\t}\n\tbreak;\n      case 3:     /* YY wrt Vpol */\n\tif (souFit[isou][paramNumber]) {\n\t  /* (MC1*DPAc - MC4*DPA) * gX[ia1] * gX[ia2] */\n\t  COMPLEX_MUL2(ct2, MC1, DPAc);\n\t  COMPLEX_MUL2(ct3, MC4, DPA);\n\t  COMPLEX_SUB(ct1, ct2, ct3);\n\t  COMPLEX_MUL2(DFDP, ct1, ggPD);\n\t}\n\tbreak;  \n      default:\n\tbreak;\n      }; /* end source parameter switch */\n      /* end source param */\n    } else if (paramType==polnParmGain) {   /* Antenna Gains */\n     switch (paramNumber) {   /* Switch over parameter */\n      case 0:     /* YY wrt gX - nope */\n\tbreak;\n      case 1:     /* YY wrt gY */\n\tif (isAnt1 && (antGainFit[ia1][paramNumber])) {\n\t  /* part = (S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) * gY[ia2] */\n\t  COMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4);\n\t  COMPLEX_SET (ct2, antGain[ia2*2+1], 0);\n\t  COMPLEX_MUL2 (DFDP, ct1, ct2);\n\t  /* part2 = 0 */\n\t} else \tif (isAnt2 && (antGainFit[ia2][paramNumber])) {\n\t  /* part = (S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) * gY[ia1] */\n\t  COMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4);\n\t  COMPLEX_SET (ct2, antGain[ia1*2+1], 0);\n\t  COMPLEX_MUL2 (DFDP, ct1, ct2);\n\t  /* part2 = 0 */\n\t}\n\tbreak;\n       default:\n\tbreak;\n      } /* end gain switch */\n    } else if (paramType==polnParmPD) {   /* X-Y phase difference */\n      /* Nope */\n    } /* end parameter types */\n\n    /* Accumulate partials */\n    if (paramType!=polnParmUnspec) {\n      sumd  += 2.0 * isigma * (residR*DFDP.real + residI*DFDP.imag); \n      sumd2 += 2.0 * isigma * (DFDP.real*DFDP.real + DFDP.imag*DFDP.imag +\n\t\t\t       residR*DFDP2.real + residI*DFDP2.imag);\n    } /* end set partials */\n  } /* end valid data */\n  \n    /* \t    XY */\n  if (wt[idata*4+2]>0.0) {\n    /* Increase X hand weight */\n    isigma = 3.0 * wt[idata*4+2];\n    /* VXY = {S[0] * CX[ia1] * SYc[ia2] +       \n              S[1] * CX[ia1] * CYc[ia2] +\n\t      S[2] * SX[ia1] * SYc[ia2]  + \n\t      S[3] * SX[ia1] * CYc[ia2]}} * g1X * g2Y * exp(j PD);\n    */\n    COMPLEX_MUL2 (MC1, CX[ia1], SYc[ia2]);\n    COMPLEX_MUL2 (MC2, CX[ia1], CYc[ia2]);\n    COMPLEX_MUL2 (MC3, SX[ia1], SYc[ia2]);\n    COMPLEX_MUL2 (MC4, SX[ia1], CYc[ia2]);\n    COMPLEX_MUL2 (SM1, S[0], MC1);\n    COMPLEX_MUL2 (SM2, S[1], MC2);\n    COMPLEX_MUL2 (SM3, S[2], MC3);\n    COMPLEX_MUL2 (SM4, S[3], MC4);\n    COMPLEX_ADD4 (ct5, SM1, SM2, SM3, SM4);\n    COMPLEX_SET (ct1,  antGain[ia1*2+0]*antGain[ia2*2+1], 0);\n    COMPLEX_EXP (ct2, PD);\n    COMPLEX_MUL2 (ggPD, ct1, ct2);\n    COMPLEX_MUL2 (VXY, ct5, ggPD);\n    residR = VXY.real - data[idata*10+6];\n    sum += isigma * residR * residR; sumwt += isigma;\n    residI = VXY.imag - data[idata*10+7];\n    sum += isigma * residI * residI; sumwt += isigma;\n    nXobs++;\n    sumXResid += residR * residR + residI * residI;\n    /* Derivatives */\n    /* Default partials  */\n    COMPLEX_SET (DFDP,  0.0, 0.0);\n    COMPLEX_SET (DFDP2, 0.0, 0.0);\n     if (paramType==polnParmAnt) {         /* Antenna parameters */\n     switch (paramNumber) {   /* Switch over parameter */\n      case 0:     /* XY wrt Ox */\n\tif (isAnt1) {\n\t  if (antFit[ia1][paramNumber]) {\n\t    /* part = {(0, -1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + \n\t               (0,  1) * S[2] * MC3 + (0,  1) * S[3] * MC4} *\n\t\t                        gX[ia1] * gY[ia2] * exp(j PD) */\n\t    COMPLEX_ADD2 (ct1, SM1, SM2);\n\t    COMPLEX_MUL2 (ct2, Jm, ct1);\n\t    COMPLEX_ADD2 (ct1, SM3, SM4);\n\t    COMPLEX_MUL2 (ct3, Jp, ct1);\n\t    COMPLEX_ADD2 (ct2, ct2, ct3);\n\t    COMPLEX_MUL2 (DFDP, ct2, ggPD);\n\t    /* part2 = -VXY */\n\t    COMPLEX_NEGATE(DFDP2, VXY);\n\t  }\n\t} \n\tbreak;\n      case 1:     /* XY wrt Ex */\n\tif (isAnt1) {\n\t  if (antFit[ia1][paramNumber]) {\n\t    /* part =  {-S[0] * SYc[ia2] * SXc[ia1]  - \n                         S[1] * CYc[ia2] * SXc[ia1]  +\n\t\t         S[2] * SYc[ia2] * CXc[ia1]  + \n\t\t         S[3] * CYc[ia2] * CXc[ia1]  } * \n\t\t\t\t         gX[ia1] * gY[ia2] * exp(j PD) */\n\t    COMPLEX_MUL3(ct5, S[0], SYc[ia2], SXc[ia1]);\n\t    COMPLEX_NEGATE(ct1, ct5);\n\t    COMPLEX_MUL3(ct5, S[1], CYc[ia2], SXc[ia1]);\n\t    COMPLEX_NEGATE(ct2, ct5);\n\t    COMPLEX_MUL3(ct3, S[2], SYc[ia2], CXc[ia1]);\n\t    COMPLEX_MUL3(ct4, S[3], CYc[ia2], CXc[ia1]);\n\t    COMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4);\n\t    COMPLEX_MUL2(DFDP, ct5, ggPD);\n\t    /*   part2 = -VXY  */\n\t    COMPLEX_NEGATE(DFDP2, VXY);\n\t  }\n\t}\n\tbreak;\n      case 2:     /* XY wrt Oy */\n\tif (isAnt2) {\n\t  if (antFit[ia2][paramNumber]) {\n\t    /* part = {(0,  1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + \n\t               (0,  1) * S[2] * MC3 + (0, -1) * S[3] * MC4} * \n                             gX[ia1] * gY[ia2] * exp(j PD) */\n\t    COMPLEX_ADD2 (ct1, SM1, SM3);\n\t    COMPLEX_MUL2 (ct2, Jp, ct1);\n\t    COMPLEX_ADD2 (ct1, SM2, SM4);\n\t    COMPLEX_MUL2 (ct3, Jm, ct1);\n\t    COMPLEX_ADD2 (ct5, ct2, ct3);\n\t    COMPLEX_MUL2 (DFDP,  ct5, ggPD);\n\t    /* part2 = -VXY */\n\t    COMPLEX_NEGATE(DFDP2, VXY);\n\t  }\n\t} \n\tbreak;\n      case 3:     /* XY wrt Ey */\n\tif (isAnt2) {\n\t  if (antFit[ia2][paramNumber]) {\n\t    /* part = {-S[0] * CX[ia1] * CY[ia2] +       \n\t                S[1] * CX[ia1] * SY[ia2] -\n\t\t      \tS[2] * SX[ia1] * CY[ia2] + \n\t\t      \tS[3] * SX[ia1] * SY[ia2]} * \n\t\t\t   \t       gX[ia1] * gY[ia2] * exp(j PD) */\n\t    COMPLEX_MUL3(ct5, S[0], CX[ia1], CY[ia2]);\n\t    COMPLEX_NEGATE(ct1, ct5);\n\t    COMPLEX_MUL3(ct5, S[1], CX[ia1], SY[ia2]);\n\t    COMPLEX_NEGATE(ct2, ct5);\n\t    COMPLEX_MUL3(ct3, S[2], SX[ia1], CY[ia2]);\n\t    COMPLEX_MUL3(ct4, S[3], SX[ia1], SY[ia2]);\n\t    COMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4);\n\t    COMPLEX_MUL2(DFDP, ct5, ggPD);\n\t    /* part2 = -VXY */\n\t    COMPLEX_NEGATE(DFDP2, VXY);\n\t  }\n\t}\n\tbreak;\n      default:\n\tbreak;\n      }; /* end antenna parameter switch */\n      /* end antenna param */\n    } else if (paramType==polnParmSou) {   /* Source parameters */\n      switch (paramNumber) {   /* Switch over parameter */\n      case 0:     /* XY wrt I */\n\tif (souFit[isou][paramNumber]) {\n\t  /* part =   (MC1*DPAc + MC4*DPA) * gX[ia1] * gX[ia2] * exp(j PD) */\n\t  COMPLEX_MUL2(ct2, MC1, DPAc);\n\t  COMPLEX_MUL2(ct3, MC4, DPA);\n\t  COMPLEX_ADD2(ct1, ct2, ct3);\n\t  COMPLEX_MUL2(DFDP, ct1, ggPD);\n\t}\n\tbreak;\n      case 1:     /* XY wrt QPol */\n\tif (souFit[isou][paramNumber]) {\n\t  /* part = (MC2*SPAc + MC3*SPA) * gX[ia1] * gX[ia2] * exp(j PD) */\n\t  COMPLEX_MUL2(ct2, MC2, SPAc);\n\t  COMPLEX_MUL2(ct3, MC3, SPA);\n\t  COMPLEX_ADD2(ct1, ct2, ct3);\n\t  COMPLEX_MUL2(DFDP, ct1, ggPD);\n\t}\n\tbreak;\n      case 2:     /* XY wrt UPol */\n\tif (souFit[isou][paramNumber]) {\n\t  /* (j MC2*SPAc - j MC3*SPA) * gX[ia1] * gX[ia2] * exp(j PD) */\n\t  COMPLEX_MUL3(ct2, Jp, MC2, SPAc);\n\t  COMPLEX_MUL3(ct3, Jp, MC3, SPA);\n\t  COMPLEX_SUB(ct1, ct2, ct3);\n\t  COMPLEX_MUL2(DFDP, ct1, ggPD);\n\t}\n\tbreak;\n      case 3:     /* XY wrt Vpol */\n\tif (souFit[isou][paramNumber]) {\n\t  /* (MC1*DPAc - MC4*DPA) * gX[ia1] * gX[ia2] * exp(j PD) */\n\t  COMPLEX_MUL2(ct2, MC1, DPAc);\n\t  COMPLEX_MUL2(ct3, MC4, DPA);\n\t  COMPLEX_SUB(ct1, ct2, ct3);\n\t  COMPLEX_MUL2(DFDP, ct1, ggPD);\n\t}\n\tbreak;  \n      default:\n\tbreak;\n      }; /* end source parameter switch */\n      /* end source param */\n    } else if (paramType==polnParmGain) {   /* Antenna Gains */\n      switch (paramNumber) {   /* Switch over parameter */\n      case 0:     /* XY wrt gX */\n\tif (isAnt1 && (antGainFit[ia1][paramNumber])) {\n\t  /* part = (S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) \n                           * gY[ia2]  * exp(j PD) */\n\t  COMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4);\n\t  COMPLEX_SET (ct2, antGain[ia2*2+1], 0);\n\t  COMPLEX_EXP (ct3, PD);\n\t  COMPLEX_MUL3 (DFDP, ct1, ct2, ct3);\n\t  /* part2 = 0 */\n\t}\n\tbreak;\n      case 1:     /* XY wrt gY */\n\tif (isAnt2 && (antGainFit[ia2][paramNumber])) {\n\t  /* part = {S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) \n\t                    * gX[ia1] * exp(j PD) */\n\t  COMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4);\n\t  COMPLEX_SET (ct2, antGain[ia1*2+0], 0);\n\t  COMPLEX_EXP (ct3, PD);\n\t  COMPLEX_MUL3 (DFDP, ct1, ct2, ct3);\n\t  /* part2 = 0 */\n\t}\n\tbreak;\n       default:\n\tbreak;\n      } /* end gain switch */\n  } else if (paramType==polnParmPD) {   /* X-Y phase difference */\n      /* part = (0,  1) * VXY */   \n      COMPLEX_MUL2 (DFDP, Jp, VXY);\n      /* part2 = -VXY */\n      COMPLEX_NEGATE(DFDP2, VXY);\n  } /* end parameter types */\n\n   /* Accumulate partials */\n    if (paramType!=polnParmUnspec) {\n      sumd  += 2.0 * isigma * (residR*DFDP.real + residI*DFDP.imag);\n      sumd2 += 2.0 * isigma * (DFDP.real*DFDP.real + DFDP.imag*DFDP.imag +\n\t\t\t       residR*DFDP2.real + residI*DFDP2.imag);\n   } /* end set partials */\n  } /* end valid data */\n  \n    /*        YX */\n  if (wt[idata*4+3]>0.0) {\n    /* Increase X hand weight */\n    isigma = 3.0 * wt[idata*4+3];\n    /* VYX = {S[0] * SY[ia1] * CXc[ia2] +       \n              S[1] * SY[ia1] * SXc[ia2] +\n\t      S[2] * CY[ia1] * CXc[ia2]  + \n\t      S[3] * CY[ia1] * SXc[ia2]} * g1Y * g2X * exp(-j PD)\n    */\n    COMPLEX_MUL2 (MC1, SY[ia1], CXc[ia2]);\n    COMPLEX_MUL2 (MC2, SY[ia1], SXc[ia2]);\n    COMPLEX_MUL2 (MC3, CY[ia1], CXc[ia2]);\n    COMPLEX_MUL2 (MC4, CY[ia1], SXc[ia2]);\n    COMPLEX_MUL2 (SM1, S[0], MC1);\n    COMPLEX_MUL2 (SM2, S[1], MC2);\n    COMPLEX_MUL2 (SM3, S[2], MC3);\n    COMPLEX_MUL2 (SM4, S[3], MC4);\n    COMPLEX_ADD4 (ct5, SM1, SM2, SM3, SM4);\n    COMPLEX_SET (ct1,  antGain[ia1*2+1]*antGain[ia2*2+0], 0);\n    COMPLEX_EXP (ct2, -PD);\n    COMPLEX_MUL2 (ggPD, ct1, ct2);\n    COMPLEX_MUL2 (VYX, ct5, ggPD);\n    residR = VYX.real - data[idata*10+8];\n    sum += isigma * residR * residR; sumwt += isigma;\n    residI = VYX.imag - data[idata*10+9];\n    sum += isigma * residI * residI; sumwt += isigma;\n    nXobs++;\n    sumXResid += residR * residR + residI * residI;\n    /* Derivatives */\n    /* Default partials  */\n    COMPLEX_SET (DFDP,  0.0, 0.0);\n    COMPLEX_SET (DFDP2, 0.0, 0.0);      \n    if (paramType==polnParmAnt) {         /* Antenna parameters */\n      switch (paramNumber) {   /* Switch over parameter */\n      case 0:     /* YX wrt Ox */\n\tif (isAnt2) {\n\t  if (antFit[ia2][paramNumber]) {\n\t    /* part = {(0,  1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + \n                       (0,  1) * S[2] * MC3 + (0, -1) * S[3] * MC4} * \n\t\t       gY[ia1] * gX[ia2]  * exp(-j PD) */\n\t    COMPLEX_ADD2 (ct1, SM1, SM3);\n\t    COMPLEX_MUL2 (ct2, Jp, ct1);\n\t    COMPLEX_ADD2 (ct1, SM2, SM4);\n\t    COMPLEX_MUL2 (ct3, Jm, ct1);\n\t    COMPLEX_ADD2 (ct2, ct2, ct3);\n\t    COMPLEX_MUL2 (DFDP,  ct2, ggPD);\n\t    /*   part2 = -VYX  */\n\t    COMPLEX_NEGATE(DFDP2, VYX);\n\t  }\n\t} \n\tbreak;\n      case 1:     /* YX wrt Ex */\n\tif (isAnt2) {\n\t  if (antFit[ia2][paramNumber]) {\n\t    /* part = {-S[0] * SY[ia1] * SX[ia2] + \n\t                S[1] * SY[ia1] * CX[ia2] -\n\t\t        S[2] * CY[ia1] * SX[ia2] + \n\t\t        S[3] * CY[ia1] * CX[ia2]} * \n\t\t\t\t        gY[ia1] * gX[ia2] * exp(-j PD)*/\n\t    COMPLEX_MUL3(ct5, S[0], SY[ia1], SX[ia2]);\n\t    COMPLEX_NEGATE(ct1, ct5);\n\t    COMPLEX_MUL3(ct2, S[1], SY[ia1], CX[ia2]);\n\t    COMPLEX_MUL3(ct5, S[2], CY[ia1], SX[ia2]);\n\t    COMPLEX_NEGATE(ct3, ct5);\n\t    COMPLEX_MUL3(ct4, S[3], CY[ia1], CX[ia2]);\n\t    COMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4);\n\t    COMPLEX_MUL2(DFDP, ct5, ggPD);\n\t    /*   part2 = -VYX  */\n\t    COMPLEX_NEGATE(DFDP2, VYX);\n\t  }\n\t}\n\tbreak;\n      case 2:     /* YX wrt Oy */\n\tif (isAnt1) {\n\t  if (antFit[ia1][paramNumber]) {\n\t    /* part = {(0, -1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + \n\t               (0,  1) * S[2] * MC3 + (0,  1) * S[3] * MC4} * \n\t\t       gX[ia1] * gY[ia2] * exp(-j PD) */\n\t    COMPLEX_ADD2 (ct1, SM1, SM2);\n\t    COMPLEX_MUL2 (ct2, Jm, ct1);\n\t    COMPLEX_ADD2 (ct1, SM3, SM4);\n\t    COMPLEX_MUL2 (ct3, Jp, ct1);\n\t    COMPLEX_ADD2 (ct2, ct2, ct3);\n\t    COMPLEX_MUL2 (DFDP, ct2, ggPD);\n\t    /* part2 = -VYX */\n\t    COMPLEX_NEGATE(DFDP2, VYX);\n\t  }\n\t}\n\tbreak;\n      case 3:     /* YX wrt Ey */\n\tif (isAnt1) {\n\t  if (antFit[ia1][paramNumber]) {\n\t    /* part = {-S[0] * CXc[ia2] * CYc[ia1] -       \n\t                S[1] * SXc[ia2] * CYc[ia1] +\n\t\t        S[2] * CXc[ia2] * SYc[ia1] + \n\t\t        S[3] * SXc[ia2] * SYc[ia1]} * \n\t\t\t\t gY[ia1] * gX[ia2] * exp(-j PD) */\n\t    COMPLEX_MUL3(ct5, S[0], CXc[ia2], CYc[ia1]);\n\t    COMPLEX_NEGATE(ct1, ct5);\n\t    COMPLEX_MUL3(ct5, S[1], SXc[ia2], CYc[ia1]);\n\t    COMPLEX_NEGATE(ct2, ct5);\n\t    COMPLEX_MUL3(ct3, S[2], CXc[ia2], SYc[ia1]);\n\t    COMPLEX_MUL3(ct4, S[3], SXc[ia2], SYc[ia1]);\n\t    COMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4);\n\t    COMPLEX_MUL2(DFDP, ct5, ggPD);\n\t    /* part2 = -VYX */\n\t    COMPLEX_NEGATE(DFDP2, VYX);\n\t  }\n\t}\n\tbreak;\n      default:\n\tbreak;\n      }; /* end antenna parameter switch */\n      /* end antenna param */\n    } else if (paramType==polnParmSou) {   /* Source parameters */\n      switch (paramNumber) {   /* Switch over parameter */\n      case 0:     /* YX wrt IPol */\n\tif (souFit[isou][paramNumber]) {\n\t  /* part =   (MC1*DPAc + MC4*DPA) * gX[ia1] * gX[ia2] * exp(-j PD) */\n\t  COMPLEX_MUL2(ct2, MC1, DPAc);\n\t  COMPLEX_MUL2(ct3, MC4, DPA);\n\t  COMPLEX_ADD2(ct1, ct2, ct3);\n\t  COMPLEX_MUL2(DFDP, ct1, ggPD);\n\t}\n\tbreak;\n      case 1:     /* YX wrt QPol */\n\tif (souFit[isou][paramNumber]) {\n\t  /* part = (MC2*SPAc + MC3*SPA) * gX[ia1] * gX[ia2] * exp(-j PD) */\n\t  COMPLEX_MUL2(ct2, MC2, SPAc);\n\t  COMPLEX_MUL2(ct3, MC3, SPA);\n\t  COMPLEX_ADD2(ct1, ct2, ct3);\n\t  COMPLEX_MUL2(DFDP, ct1, ggPD);\n\t}\n\tbreak;\n      case 2:     /* YX wrt UPol */\n\tif (souFit[isou][paramNumber]) {\n\t  /* (j MC2*SPAc - j MC3*SPA) * gX[ia1] * gX[ia2] * exp(-j PD) */\n\t  COMPLEX_MUL3(ct2, Jp, MC2, SPAc);\n\t  COMPLEX_MUL3(ct3, Jp, MC3, SPA);\n\t  COMPLEX_SUB(ct1, ct2, ct3);\n\t  COMPLEX_MUL2(DFDP, ct1, ggPD);\n\t}\n\tbreak;\n      case 3:     /* YX wrt Vpol */\n\tif (souFit[isou][paramNumber]) {\n\t  /* (MC1*DPAc - MC4*DPA) * gX[ia1] * gX[ia2] * exp(-j PD) */\n\t  COMPLEX_MUL2(ct2, MC1, DPAc);\n\t  COMPLEX_MUL2(ct3, MC4, DPA);\n\t  COMPLEX_SUB(ct1, ct2, ct3);\n\t  COMPLEX_MUL2(DFDP, ct1, ggPD);\n\t}\n\tbreak;  \n      default:\n\tbreak;\n      }; /* end source parameter switch */\n      /* end source param */\n    } else if (paramType==polnParmGain) {   /* Antenna Gains */\n      switch (paramNumber) {   /* Switch over parameter */\n      case 0:     /* YX wrt gX */\n\tif (isAnt2 && (antGainFit[ia2][paramNumber])) {\n\t  /* part = (S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) \n                           * gY[ia1]  * exp(-j PD) */\n\t  COMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4);\n\t  COMPLEX_SET (ct2, antGain[ia1*2+1], 0);\n\t  COMPLEX_EXP (ct3, -PD);\n\t  COMPLEX_MUL3 (DFDP, ct1, ct2, ct3);\n\t  /* part2 = 0 */\n\t}\n\tbreak;\n      case 1:     /* YX wrt gY */\n\tif  (isAnt1 && (antGainFit[ia1][paramNumber])) {\n\t  /* part =  (S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) * \n\t                 gX[ia2] * exp(-j PD) */\n\t  COMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4);\n\t  COMPLEX_SET (ct2, antGain[ia2*2+0], 0);\n\t  COMPLEX_EXP (ct3, -PD);\n\t  COMPLEX_MUL3 (DFDP, ct1, ct2, ct3);\n\t}\n\tbreak;\n       default:\n\tbreak;\n      } /* end gain switch */\n  } else if (paramType==polnParmPD) {   /* X-Y phase difference */\n      /* part = (0, -1) * VYX */   \n      COMPLEX_MUL2 (DFDP, Jm, VYX);\n      /* part2 = -VYX */\n      COMPLEX_NEGATE(DFDP2, VYX);\n  } /* end parameter types */\n\n    /* Accumulate partials */\n    if (paramType!=polnParmUnspec) {\n      sumd  += 2.0 * isigma * (residR*DFDP.real + residI*DFDP.imag);\n      sumd2 += 2.0*isigma * (DFDP.real*DFDP.real + DFDP.imag*DFDP.imag +\n\t\t\t      residR*DFDP2.real + residI*DFDP2.imag);\n      } /* end set partials */\n  }  /* end valid data */\n  } /* End loop over visibilities */\n  \n  if (sumwt<=0.0) sumwt = 1.0;  /* Trap no data */\n  args->ChiSq       = sum;   /* Save results  */\n  args->sumParResid = sumParResid;\n  args->sumXResid   = sumXResid;\n  args->sumWt       = sumwt;\n  args->nPobs       = nPobs;\n  args->nXobs       = nXobs;\n  if (paramType!=polnParmUnspec) args->sumDeriv  = sumd;\n  if (paramType!=polnParmUnspec) args->sumDeriv2 = sumd2;\n\n /* Indicate completion if threaded */\n  if (args->ithread>=0)\n    ObitThreadPoolDone (args->thread, (gpointer)&args->ithread);\n\n  return NULL;\n\n} /*  end ThreadPolnFitXYChi2 */\n\n/**\n * Create threading arguments\n * \\param in       Fitting object\n * \\param err      Obit error stack object.\n */\nstatic void MakePolnFitFuncArgs (ObitPolnCalFit *in, ObitErr *err)\n{\n  olong i, nVisPerThread;\n\n  /* If they already exist, first delete */\n  if (in->thArgs) KillPolnFitFuncArgs(in);\n\n  /* How many threads? */\n  in->nThread   = MAX (1, ObitThreadNumProc(in->thread));\n  nVisPerThread = in->nvis / in->nThread;\n\n  /* Initialize threadArg array */\n  in->thArgs = g_malloc0(in->nThread*sizeof(PolnFitArg*));\n  for (i=0; i<in->nThread; i++) \n    in->thArgs[i] = g_malloc0(sizeof(PolnFitArg)); \n  for (i=0; i<in->nThread; i++) {\n    in->thArgs[i]->thread   = ObitThreadRef(in->thread);\n    in->thArgs[i]->err      = ObitErrRef(err);\n    in->thArgs[i]->ithread  = i;\n    if (in->nThread<=1) in->thArgs[i]->ithread = -1;\n    in->thArgs[i]->doError  = in->doError;\n    in->thArgs[i]->lo       = i*nVisPerThread;     /* Zero rel first */\n    in->thArgs[i]->hi       = (i+1)*nVisPerThread; /* Zero rel last */\n    in->thArgs[i]->ndata    = in->nvis*8;\n    in->thArgs[i]->inData   = in->inData;\n    in->thArgs[i]->inWt     = in->inWt;\n    in->thArgs[i]->souNo    = in->souNo;\n    in->thArgs[i]->antNo    = in->antNo;\n    in->thArgs[i]->nant     = in->nant;\n    in->thArgs[i]->refAnt   = in->refAnt;\n    in->thArgs[i]->doFitRL  = in->doFitRL;\n    in->thArgs[i]->doFitI   = in->doFitI;\n    in->thArgs[i]->doFitPol = in->doFitPol;\n    in->thArgs[i]->doFitV   = in->doFitV;\n    in->thArgs[i]->doFitGain= in->doFitGain;\n    in->thArgs[i]->isCircFeed= in->isCircFeed;\n    in->thArgs[i]->antParm  = in->antParm;\n    in->thArgs[i]->antErr   = in->antErr;\n    in->thArgs[i]->antFit   = in->antFit;\n    in->thArgs[i]->antPNumb = in->antPNumb;\n    in->thArgs[i]->antGain      = in->antGain;\n    in->thArgs[i]->antGainErr   = in->antGainErr;\n    in->thArgs[i]->antGainFit   = in->antGainFit;\n    in->thArgs[i]->antGainPNumb = in->antGainPNumb;\n    in->thArgs[i]->nsou     = in->nsou;\n    in->thArgs[i]->souParm  = in->souParm;\n    in->thArgs[i]->souErr   = in->souErr;\n    in->thArgs[i]->souFit   = in->souFit;\n    in->thArgs[i]->souPNumb = in->souPNumb;\n    in->thArgs[i]->souIDs   = in->souIDs;\n    in->thArgs[i]->isouIDs  = in->isouIDs;\n    in->thArgs[i]->nparam   = in->nparam;\n    in->thArgs[i]->freq     = in->inDesc->freq;\n    in->thArgs[i]->refFreq  = in->freq;\n    in->thArgs[i]->curFreq  = in->freq;   /* Initial value */\n    in->thArgs[i]->RLPhase  = in->RLPhase;\n    in->thArgs[i]->PPol     = in->PPol;\n    in->thArgs[i]->dPPol    = in->dPPol;\n    in->thArgs[i]->Chan     = 0;\n    in->thArgs[i]->IFno     = 0;\n    in->thArgs[i]->ChiSq    = 0.0;\n    in->thArgs[i]->maxAnt   = 100;\n  } /* end loop over thread args */\n\n  /* Make sure do all data */\n  i = in->nThread-1;\n  in->thArgs[i]->hi = MAX (in->thArgs[i]->hi, in->nvis);\n\n} /* end MakePolnFitFuncArgs */\n\n/**\n * Delete threading arguments\n * \\param in       Fitting object\n */\nstatic void KillPolnFitFuncArgs (ObitPolnCalFit *in)\n{\n  olong i;\n\n  /* If they already exist? */\n  if (in->thArgs==NULL) return;\n\n  /* Loop over threadArg arrays */\n  for (i=0; i<in->nThread; i++) {\n    ObitThreadUnref(in->thArgs[i]->thread);\n    ObitErrUnref(in->thArgs[i]->err);\n    g_free(in->thArgs[i]);  in->thArgs[i] = NULL;\n  } /* end loop over thread args */\n  g_free(in->thArgs );  in->thArgs = NULL;\n} /* end  KillPolnFitFuncArgs*/\n\n/**\n * Check for crazy antenna solutions, reset defaults if so.\n * If One antenna is the cause of large errors, disable it\n * \\param in           Fitting object\n * \\param err          Obit error stack object.\n * \\return             TRUE if refitting needed\n */\nstatic gboolean CheckCrazyOne(ObitPolnCalFit *in, ObitErr *err)\n{\n  gboolean crazyOne = FALSE;\n  odouble sum, RMS, test, maxDif;\n  ofloat fblank = ObitMagicF();\n  olong i, k, imax, idata;\n\n  if (err->error) return crazyOne;  /* Error detected? */\n\n  /* Was final Chi^2 not 50% better than initial \n   and Was parallel hand fit better than cross?*/\n  if ((in->ChiSq>0.5*in->initChiSq) && \n      (in->XRMS>1.1*in->ParRMS)) goto reset;\n\n  /* Get mean square difference from default elipticity */\n  sum = 0.0; maxDif=0.0; imax = -1;\n  for (i=0; i<in->nant; i++) {\n    if (in->isCircFeed) {\n      /* Circular feeds ori_r, elip_r, ori_l, elip_l */\n     test = (in->antParm[i*4+1] - G_PI/4.0)*(in->antParm[i*4+1] - G_PI/4.0) + \n            (in->antParm[i*4+3] + G_PI/4.0)*(in->antParm[i*4+3] + G_PI/4.0);\n    } else {\n      /* Linear feeds  ori_x, elip_x, ori_y, elip_y,  */\n      test = (in->antParm[i*4+1])*(in->antParm[i*4+1]) + \n             (in->antParm[i*4+3])*(in->antParm[i*4+3]);\n    }\n    sum += test;\n    if (maxDif<test) {maxDif = test; imax=i;}\n  } /* end loop over antennas */\n\n  /* is it OK? */\n  sum /= in->nant*2.0;\n  RMS =  sqrt(sum)*RAD2DG;\n  crazyOne = (RMS > 10.0);\n  if (!crazyOne) return FALSE;\n\n  /* See if it's OK if we chuck the worst */\n  sum = 0.0; \n  for (i=0; i<in->nant; i++) {\n    if (i==imax) continue;\n    if (in->isCircFeed) {\n      /* Circular feeds ori_r, elip_r, ori_l, elip_l */\n     test = (in->antParm[i*4+1] - G_PI/4.0)*(in->antParm[i*4+1] - G_PI/4.0) + \n            (in->antParm[i*4+3] + G_PI/4.0)*(in->antParm[i*4+3] + G_PI/4.0);\n    } else {\n      /* Linear feeds  ori_x, elip_x, ori_y, elip_y,  */\n      test = (in->antParm[i*4+1])*(in->antParm[i*4+1]) + \n             (in->antParm[i*4+3])*(in->antParm[i*4+3]);\n    }\n    sum += test;\n  } /* end loop over antennas */\n\n  /* is it OK now? */\n  sum /= in->nant*2.0;\n  RMS =  sqrt(sum)*RAD2DG;\n  crazyOne = (RMS <= 10.0);  /* OK = True */\n  if (!crazyOne) return FALSE;\n  \n  if (err->prtLv>=2) {\n    Obit_log_error(err, OBIT_InfoWarn, \"Tossing bad antenna %d - refit\", imax+1);\n    ObitErrLog(err); \n  }\n \n  /* Antenna imax+1 is the baddest, rest ~ OK - Flag */\n  in->gotAnt[imax]     = FALSE;\n  for (idata=0; idata<in->nvis; idata++) {\n    if ((in->antNo[idata*2+0]==imax) || (in->antNo[idata*2+1]==imax)) {\n      for (k=0; k<4; k++) in->inWt[idata*4+k] = 0.0;\n    }\n  }\n  \n  /* Flag solutions - don't refit */\n  if (!in->isCircFeed ) {   /* Linear feed */\n    /*in->antGainFit[imax][0] = in->antGainFit[imax][1] = FALSE;*/\n    in->antGain[imax*2+0] = in->antGain[imax*2+1] = 1.0;\n  }\n  /*in->antFit[imax][0]   = in->antFit[imax][1]   = in->antFit[imax][2]   = in->antFit[imax][3]   = FALSE;*/\n  in->antParm[imax*4+0] = in->antParm[imax*4+1] = in->antParm[imax*4+2] = in->antParm[imax*4+3] = fblank;\n\n  return TRUE;\n\n  /* Reset solutions */\n reset:\n  Obit_log_error(err, OBIT_InfoWarn, \"Questionable solution, reset, retry\");\n  ResetAllSoln (in);\n  return TRUE;\n} /* end CheckCrazyOne */\n\n/**\n * Check for crazy antenna solutions, reset defaults if so.\n * If the RMS deviation from the default elipticity exceeds 10 deg\n * the fit is deemed crazy.\n * Uses last valid set of source parameters in reset\n * \\param in           Fitting object\n * \\param err          Obit error stack object.\n * \\return             TRUE if reset defaults, else FALSE\n */\nstatic gboolean CheckCrazy(ObitPolnCalFit *in, ObitErr *err)\n{\n  gboolean crazy = FALSE;\n  odouble sum, RMS;\n  ofloat fblank = ObitMagicF();\n  olong i, j;\n\n  if (err->error) return crazy;  /* Error detected? */\n\n  /* Get mean square difference from default elipticity */\n  sum = 0.0;\n  for (i=0; i<in->nant; i++) {\n    if ((!in->gotAnt[i]) || (in->antParm[i*4+1]==fblank) || \n\t((in->antParm[i*4+3]==fblank))) continue;\n    if (in->isCircFeed) {\n      /* Circular feeds ori_r, elip_r, ori_l, elip_l */\n     sum += (in->antParm[i*4+1] - G_PI/4.0)*(in->antParm[i*4+1] - G_PI/4.0) + \n            (in->antParm[i*4+3] + G_PI/4.0)*(in->antParm[i*4+3] + G_PI/4.0);\n    } else {\n      /* Linear feeds  ori_x, elip_x, ori_y, elip_y,  */\n      sum += (in->antParm[i*4+1])*(in->antParm[i*4+1]) + \n             (in->antParm[i*4+3])*(in->antParm[i*4+3]);\n    }\n  } /* end loop over antennas */\n\n  /* mean */\n  sum /= in->nant*2.0;\n  RMS =  sqrt(sum)*RAD2DG;\n  crazy = RMS > 10.0;\n\n  /* Crazy? -> reset */\n  if (crazy) {\n    Obit_log_error(err, OBIT_InfoWarn, \"Antenna solution crazy, RMS %lf, reseting defaults\", RMS);\n    ResetAllSoln (in);\n  } /* end reset */\n  else {  /* OK - save source parameters */\n    for (i=0; i<in->nsou; i++) {\n      for (j=0; j<4; j++) in->lastSouParm[i*4+j] = in->souParm[i*4+j];\n    }\n  } /* end save parameters */\n  \n  return crazy;\n} /* end CheckCrazy */\n\n/**\n * Resets all solutions to the default\n * \\param in           Fitting object\n */\nstatic void ResetAllSoln(ObitPolnCalFit *in)\n{\n  olong i, j;\n\n  for (i=0; i<in->nant; i++) {\n    for (j=0; j<4; j++) in->antParm[i*4+j] = 0.0;\n    if (in->isCircFeed) {\n      /* Circular feeds ori_r, elip_r, ori_l, elip_l */\n      in->antParm[i*4+0] = 0.0;\n      in->antParm[i*4+1] = G_PI/4.0;\n      in->antParm[i*4+2] =  0.0;\n      in->antParm[i*4+3] =  -G_PI/4.0;\n    } else {\n      /* Linear feeds, if the antenna angles on sky are given in the AntennaList[0] use then, \n\t otherwise assume Feeds are X, Y\n\t ori_x, elip_x, ori_y, elip_y,  */\n      if (fabs (in->AntLists[0]->ANlist[i]->FeedAPA-in->AntLists[0]->ANlist[i]->FeedBPA)<1.0) {\n\t/* Assume X, Y */\n\tin->antParm[i*4+0] = 0.0;\n\tin->antParm[i*4+2] = +G_PI/2.0;\n      } else {  /* Use what's in the AN table as initial convert to radians */\n\tin->antParm[i*4+0] = in->AntLists[0]->ANlist[i]->FeedAPA*DG2RAD;\n\tin->antParm[i*4+2] = in->AntLists[0]->ANlist[i]->FeedBPA*DG2RAD;\n      } /* end if antenna angle given */\n    }\n  } /* end loop over antennas */\n  \n    /* Reset source parameters */\n  for (i=0; i<in->nsou; i++) {\n    for (j=0; j<4; j++) {\n      if (in->lastSouParm[i*4+j]>0.0) \n\tin->souParm[i*4+j] = in->lastSouParm[i*4+j];\n      else \tin->souParm[i*4+j] = 0.0;\n    } \n  }\n} /* end ResetAllSoln */\n\n/**\n * Reset blanked antenna solutions\n * \\param in           Fitting object\n */\nstatic void resetSoln(ObitPolnCalFit *in)\n{\n  ofloat fblank = ObitMagicF();\n  olong i;\n  for (i=0; i<in->nant; i++) {\n    if (in->gotAnt[i] && \n\t((in->antParm[i*4+1]==fblank) || (in->antParm[i*4+3]==fblank))) {\n      /*in->antFit[i][0] = in->antFit[i][1] = in->antFit[i][2] = in->antFit[i][3] = TRUE;*/\n      if (in->isCircFeed) {\n\t/* Circular feeds ori_r, elip_r, ori_l, elip_l */\n\tin->antParm[i*4+0] =  0.0;\n\tin->antParm[i*4+1] =  G_PI/4.0;\n\tin->antParm[i*4+2] =  0.0;\n\tin->antParm[i*4+3] = -G_PI/4.0;\n      } else {\n\t/*in->antGainFit[i][0] = in->antGainFit[i][1] = TRUE;*/\n\tin->antGain[i*2+0] = in->antGain[i*2+1] = 1.0;\n\t/* Linear feeds, if the antenna angles on sky are given in the AntennaList[0] use then, \n\t   otherwise assume Feeds are X, Y\n\t   ori_x, elip_x, ori_y, elip_y,  */\n\tin->antParm[i*4+1] = 0.0;  /* ellipticity */\n\tin->antParm[i*4+3] = 0.0;\n\tif (fabs (in->AntLists[0]->ANlist[i]->FeedAPA-in->AntLists[0]->ANlist[i]->FeedBPA)<1.0) {\n\t  /* Assume X, Y */\n\t  in->antParm[i*4+0] = 0.0;\n\t  in->antParm[i*4+2] = +G_PI/2.0;\n\t} else {  /* Use what's in the AN table as initial convert to radians */\n\t  in->antParm[i*4+0] = in->AntLists[0]->ANlist[i]->FeedAPA*DG2RAD;\n\t  in->antParm[i*4+2] = in->AntLists[0]->ANlist[i]->FeedBPA*DG2RAD;\n\t}\n      }\n    }\n  }\n} /* end resetSoln */\n/**\n * Constrain linear feed values if refAnt<0\n * subtract average\n * \\param in           Fitting object\n * \\return amount by which ellipticies were corrected in deg.\n */\nstatic ofloat ConstrLinFeed(ObitPolnCalFit *in)\n{\n  ofloat out, sum;\n  ofloat fblank = ObitMagicF();\n  olong i, cnt;\n  /* Do I want to do this? */\n  out = 0.0;\n  if (in->isCircFeed) return out;\n  if (in->refAnt>=0) return out;\n  /* Sum values */\n  sum = 0.0; cnt = 0;\n  for (i=0; i<in->nant; i++) {\n    if (in->gotAnt[i] && in->antFit[i][1] && (in->antParm[i*4+1]!=fblank)) {\n      cnt++;\n      sum += in->antParm[i*4+1];\n    }\n    if (in->gotAnt[i] && in->antFit[i][3] && (in->antParm[i*4+3]!=fblank)) {\n      cnt++;\n      sum -= in->antParm[i*4+3];  /* Opposite sign */\n    }\n  } /* end summing loop */\n  /* Correction */\n  out = sum / cnt;\n  /* Correct values */\n  for (i=0; i<in->nant; i++) {\n    if (in->gotAnt[i] && in->antFit[i][1] && (in->antParm[i*4+1]!=fblank)) {\n      in->antParm[i*4+1] -= out;\n    }\n    if (in->gotAnt[i] && in->antFit[i][3] && (in->antParm[i*4+3]!=fblank)) {\n      in->antParm[i*4+3] += out;\n    }\n  } /* end correcting loop */\n  return out*RAD2DG;\n} /* end ConstrLinFeed */\n\n#ifdef HAVE_GSL\n/**\n * Circular feed function evaluator for polarization fitting solver\n * Orientation/Ellipticity version\n * Evaluates (model-observed) / sigma\n * Function from \n * \\param x       Vector of parameters to be fitted\n *                Flux,array_of polarization_terms\n * \\param param   Function parameter structure (ObitPolnCalFit)\n * \\param f       Vector of (model-obs)/sigma for data points\n * \\return completion code GSL_SUCCESS=OK\n */\nstatic int PolnFitFuncOERL (const gsl_vector *x, void *params, \n\t\t\t    gsl_vector *f)\n{\n  ObitPolnCalFit *args = (ObitPolnCalFit*)params;\n  ofloat *data, *wt;\n  gboolean **antFit  = args->antFit;\n  olong   **antPNumb = args->antPNumb;\n  odouble  *antParm  = args->antParm;\n  gboolean **souFit  = args->souFit;\n  odouble  *souParm  = args->souParm;\n  olong   **souPNumb = args->souPNumb;\n  dcomplex   *RS     = args->RS;\n  dcomplex   *RD     = args->RD;\n  dcomplex   *LS     = args->LS;\n  dcomplex   *LD     = args->LD;\n  dcomplex   *RSc    = args->RSc;\n  dcomplex   *RDc    = args->RDc;\n  dcomplex   *LSc    = args->LSc;\n  dcomplex   *LDc    = args->LDc;\n  ofloat PD, chi1, chi2, PPol;\n  double val;\n  odouble ipol=0.0, qpol=0.0, upol=0.0, vpol=0.0;\n  odouble residR=0.0, residI=0.0, isigma=0.0;\n  olong k, iant, ia1, ia2, isou, idata;\n  olong isouLast=-999;\n  dcomplex PRref, PLref, PPRL, PPLR, PA1, PA2, PA1c, PA2c, ct1, ct2;\n  dcomplex S[4], VRR, VRL, VLR, VLL;\n  ofloat root2, maxElp=G_PI/4;\n  size_t i, j;\n\n  /* Initialize output */\n  val = 0.0;\n  for (i=0; i<args->ndata; i++) gsl_vector_set(f, i, val);\n\n  COMPLEX_SET (S[0], 0.0, 0.0);  /* Initialize poln vector */\n  COMPLEX_SET (S[1], 0.0, 0.0);\n  COMPLEX_SET (S[2], 0.0, 0.0);\n  COMPLEX_SET (S[3], 0.0, 0.0);\n  \n  /* R-L phase difference  at reference antenna */\n  if (args->doFitRL) {\n    j = args->PDPNumb;\n    PD = gsl_vector_get(x, j);\n  } else PD = args->PD;\n\n  /* get model parameters - first antenna */\n  for (iant=0; iant<args->nant; iant++) {\n    /* Loop over parameters */\n    for (k=0; k<4; k++) {\n      /* Fitting? */\n      if ((antFit[iant][k]) && (args->gotAnt[iant])) {\n\tj = antPNumb[iant][k];\n\tantParm[iant*4+k] = gsl_vector_get(x, j);\n      }\n    } /* end loop over parameters */\n  } /* end loop over antennas */\n\n  /* now source */\n  for (isou=0; isou<args->nsou; isou++) {\n    /* Loop over parameters */\n    for (k=0; k<4; k++) {\n      /* Fitting? */\n      if (souFit[isou][k]) {\n\tj = souPNumb[isou][k];\n\tsouParm[isou*4+k] = gsl_vector_get(x, j);\n      }\n    } /* end loop over parameters */\n  } /* end loop over sources */\n\n  /* data & wt pointers */\n  data = args->inData;\n  wt   = args->inWt;\n\n  /* Injest model factorize into antenna components - \n     data in order Orientation R/X, Elipticity R/X, Orientation L/Y, Elipticity L/Y*/\n  root2 = 1.0 / sqrt(2.0);\n  /* Elipticity, Orientation terms */\n  for (i=0; i<args->nant; i++) {\n    COMPLEX_SET(RS[i], root2*(cos(antParm[i*4+1]) + sin(antParm[i*4+1])), 0.);\n    COMPLEX_SET(ct1,   root2*(cos(antParm[i*4+1]) - sin(antParm[i*4+1])), 0.);\n    COMPLEX_EXP(ct2, 2*antParm[i*4+0]);\n    COMPLEX_MUL2 (RD[i], ct1, ct2);\n    COMPLEX_SET (ct1, root2*(cos(antParm[i*4+3]) + sin(antParm[i*4+3])), 0.);\n    COMPLEX_EXP (ct2, -2*antParm[i*4+2]);\n    COMPLEX_MUL2 (LS[i], ct1, ct2);\n    COMPLEX_SET (LD[i], root2*(cos(antParm[i*4+3]) - sin(antParm[i*4+3])), 0.);\n    COMPLEX_CONJUGATE (RSc[i], RS[i]);\n    COMPLEX_CONJUGATE (RDc[i], RD[i]);\n    COMPLEX_CONJUGATE (LSc[i], LS[i]);\n    COMPLEX_CONJUGATE (LDc[i], LD[i]);\n  }\n\n  /* Reference antenna phase terms */\n  if (args->refAnt>0) {\n    COMPLEX_EXP (PRref,  antParm[(args->refAnt-1)*4+0]);\n    COMPLEX_EXP (PLref, -antParm[(args->refAnt-1)*4+2]+PD);\n  } else {\n    COMPLEX_SET (PRref, 1.0, 0.0);\n    COMPLEX_EXP (PLref, PD);\n  }\n  COMPLEX_CONJUGATE (ct1, PLref);\n  COMPLEX_MUL2 (PPRL, PRref, ct1);\n  COMPLEX_CONJUGATE (ct1, PRref);\n  COMPLEX_MUL2 (PPLR, PLref, ct1);\n\n  /* Loop over data */\n  i = 0;\n  for (idata=0; idata<args->nvis; idata++) {\n    /* Parallactic angle terms */\n    chi1  = data[idata*10+0];   /* parallactic angle ant 1 */\n    chi2  = data[idata*10+1];   /* parallactic angle ant 2 */\n    COMPLEX_EXP (PA1, 2*chi1);\n    COMPLEX_EXP (PA2, 2*chi2);\n    COMPLEX_CONJUGATE (PA1c, PA1);\n    COMPLEX_CONJUGATE (PA2c, PA2);\n\n    isou  = MAX (0, args->souNo[idata]);    /* Source number */\n    /* New source? get parameters */\n    if (isou!=isouLast) {\n      isouLast = isou;\n      /* Source parameters */\n      ipol = souParm[isou*4+0];\n      /* Fitting or fixed? */\n      if (args->souFit[isou][1]) \n\tqpol = souParm[isou*4+1];\n      else {\n\tPPol = args->PPol[isou] + args->dPPol[isou]*(args->freq-args->refFreq);\n\tqpol = PPol*cos(args->RLPhase[isou]);}\n      if (args->souFit[isou][2]) \n\tupol = souParm[isou*4+2];\n      else {\n\tPPol = args->PPol[isou] + args->dPPol[isou]*(args->freq-args->refFreq);\n\tupol = PPol*ipol*sin(args->RLPhase[isou]);}\n      vpol = souParm[isou*4+3];\n      /* Complex Stokes array */\n      COMPLEX_SET (S[0], ipol+vpol, 0.0);\n      COMPLEX_SET (S[1], qpol,  upol);\n      COMPLEX_SET (S[2], qpol, -upol);\n      COMPLEX_SET (S[3], ipol-vpol, 0.0);\n    }\n\n    /* Antenna parameters (0 ref) */\n    ia1    = args->antNo[idata*2+0];\n    ia2    = args->antNo[idata*2+1]; \n    \n    /* Loop over correlations calcularing residuals */\n    for (k=0; k<4; k++) {\n      isigma = wt[idata*4+k];\n      if (k<2) isigma *= 0.3;  /* Downweight parallel hand */\n      switch (k) { \n      case 0:     /* RR */\n\tif (wt[idata*4+k]>0.0) {\n\t  /* Check for ellipticity in range */\n\t  if ((antParm[ia1*4+1]>maxElp) || (antParm[ia2*4+1]>maxElp)) {\n\t    /* out of range - give big residual */\n\t    residR = MAX((antParm[ia1*4+1]-maxElp),(antParm[ia2*4+1]-maxElp)) * \n\t      ipol * 100.;\n\t    residI = residR;\n\t  } else {  /* OK */\n\t    /* VRR = S[0] * RS[ia1] * RSc[ia2] +        \n\t             S[1] * RS[ia1] * RDc[ia2] * PA2c + \n\t             S[2] * RD[ia1] * RSc[ia2] * PA1  + \n\t             S[3] * RD[ia1] * RDc[ia2] * PA1  * PA2c; */\n\t    COMPLEX_MUL3 (VRR, S[0], RS[ia1],  RSc[ia2]);\n\t    COMPLEX_MUL4 (ct1, S[1], RS[ia1],  RDc[ia2],  PA2c);\n\t    COMPLEX_ADD2 (VRR, VRR,  ct1);\n\t    COMPLEX_MUL4 (ct1, S[2], RD[ia1], RSc[ia2], PA1);\n\t    COMPLEX_ADD2 (VRR, VRR,  ct1);\n\t    COMPLEX_MUL5 (ct1, S[3], RD[ia1], RDc[ia2], PA1, PA2c);\n\t    COMPLEX_ADD2 (VRR, VRR,  ct1);\n\t    residR = VRR.real - data[idata*10+(k+1)*2];\n\t    residI = VRR.imag - data[idata*10+(k+1)*2+1];\n\t  }\n\t} else  residR = residI = 0.0; /* Invalid data */\n\tbreak;\n      case 1:     /* LL */\n\tif (wt[idata*4+k]>0.0) {\n\t  /* Check for ellipticity in range */\n\t  if ((antParm[ia1*4+3]<-maxElp) || (antParm[ia2*4+3]<-maxElp)) {\n\t    /* out of range - give big residual */\n\t    residR = MAX((maxElp-antParm[ia1*4+3]),(maxElp-antParm[ia2*4+3])) * \n\t      ipol * 100.;\n\t    residI = residR;\n\t  } else {  /* OK */\n\t    /* VLL = S[0] * LS[ia1] * LSc[ia2] * PA1c * PA2 +\t\n\t             S[1] * LS[ia1] * LDc[ia2] * PA1c +\n\t  \t     S[2] * LD[ia1] * LSc[ia2] * PA2  +\n\t\t     S[3] * LD[ia1] * LDc[ia2]; */\n\t    COMPLEX_MUL5 (VLL, S[0], LS[ia1], LSc[ia2], PA1c, PA2);\n\t    COMPLEX_MUL4 (ct1, S[1], LS[ia1], LDc[ia2], PA1c);\n\t    COMPLEX_ADD2 (VLL, VLL,  ct1);\n\t    COMPLEX_MUL4 (ct1, S[2], LD[ia1], LSc[ia2], PA2);\n\t    COMPLEX_ADD2 (VLL, VLL,  ct1);\n\t    COMPLEX_MUL3 (ct1, S[3], LD[ia1], LDc[ia2]);\n\t    COMPLEX_ADD2 (VLL, VLL,  ct1);\n\t    residR = VLL.real - data[idata*10+(k+1)*2];\n\t    residI = VLL.imag - data[idata*10+(k+1)*2+1];\n\t  }\n\t} else  residR = residI = 0.0; /* Invalid data */\n\tbreak;\n      case 2:     /* RL */\n\tif (wt[idata*4+k]>0.0) {\n\t  /* Check for ellipticity in range */\n\t  if ((antParm[ia1*4+1]>maxElp) || (antParm[ia2*4+3]<-maxElp)) {\n\t    /* out of range - give big residual */\n\t    residR = MAX((antParm[ia1*4+1]-maxElp),(maxElp-antParm[ia2*4+3])) * \n\t      ipol * 100.;\n\t    residI = residR;\n\t  } else {  /* OK */\n\t    /* VRL = PPRL * S[0] * RS[ia1] * LSc[ia2] * PA2 +\n\t             PPRL * S[1] * RS[ia1] * LDc[ia2] + \n\t\t     PPRL * S[2] * RD[ia1] * LSc[ia2] * PA1 * PA2 +\n\t\t     PPRL * S[3] * RD[ia1] * LDc[ia2] * PA1; */\n\t    COMPLEX_MUL4 (VRL, S[0], RS[ia1], LSc[ia2], PA2);\n\t    COMPLEX_MUL3 (ct1, S[1], RS[ia1], LDc[ia2]);\n\t    COMPLEX_ADD2 (VRL, VRL,  ct1);\n\t    COMPLEX_MUL5 (ct1, S[2], RD[ia1], LSc[ia2],  PA1,  PA2);\n\t    COMPLEX_ADD2 (VRL, VRL,  ct1);\n\t    COMPLEX_MUL4 (ct1, S[3], RD[ia1], LDc[ia2],  PA1);\n\t    COMPLEX_ADD2 (ct2, VRL,  ct1);\n\t    COMPLEX_MUL2 (VRL, PPRL, ct2);\n\t    residR = VRL.real - data[idata*10+(k+1)*2];\n\t    residI = VRL.imag - data[idata*10+(k+1)*2+1];\n\t  }\n\t} else  residR = residI = 0.0; /* Invalid data */\n\tbreak;\n      case 3:     /* LR */\n\tif (wt[idata*4+k]>0.0) {\n\t  /* Check for ellipticity in range */\n\t  if ((antParm[ia1*4+3]<-maxElp) || (antParm[ia2*4+1]>maxElp)) {\n\t    /* out of range - give big residual */\n\t    residR = MAX((maxElp-antParm[ia1*4+3]),(antParm[ia2*4+1]-maxElp)) * \n\t      ipol * 100.;\n\t    residI = residR;\n\t  } else {  /* OK */\n\t    /* VLR = PPLR * S[0] * LS[ia1] * RSc[ia2] * PA1c +\n\t             PPLR * S[1] * LS[ia1] * RDc[ia2] * PA1c * PA2c +\n\t\t     PPLR * S[2] * LD[ia1] * RSc[ia2] +\n\t\t     PPLR * S[3] * LD[ia1] * RDc[ia2] * PA2c */\n\t    COMPLEX_MUL4 (VLR, S[0], LS[ia1], RSc[ia2], PA1c);\n\t    COMPLEX_MUL5 (ct1, S[1], LS[ia1], RDc[ia2], PA1c,  PA2c);\n\t    COMPLEX_ADD2 (VLR, VLR,  ct1);\n\t    COMPLEX_MUL3 (ct1, S[2], LD[ia1], RSc[ia2]);\n\t    COMPLEX_ADD2 (VLR, VLR,  ct1);\n\t    COMPLEX_MUL4 (ct1, S[3], LD[ia1], RDc[ia2], PA2c);\n\t    COMPLEX_ADD2 (ct2, VLR,  ct1);\n\t    COMPLEX_MUL2 (VLR, PPLR, ct2);\n\t    residR = VLR.real - data[idata*10+(k+1)*2];\n\t    residI = VLR.imag - data[idata*10+(k+1)*2+1];\n\t  }\n\t} else  residR = residI = 0.0; /* Invalid data */\n\tbreak;\n      default:\n\tbreak;\n      }; /* end switch */\n      gsl_vector_set(f, i*2,   residR*isigma); /* Save function resids */\n      gsl_vector_set(f, i*2+1, residI*isigma); /* Save function resids */\n      i++;  /* Update datum number */\n    } /* end loop over correlations */\n  } /* End loop over visibilities */\n  \n  return GSL_SUCCESS;\n} /*  end PolnFitFuncOERL */\n\n/**\n * Circular feed Jacobian evaluator for polarization fitting solver\n * Orientation/Ellipticity version\n * Evaluates partial derivatives of model wrt each parameter\n * \\param x       Vector of parameters to be fitted\n *                Flux,array_of polarization_terms\n * \\param param   Function parameter structure (ObitPolnCalFit)\n * \\param J       Jacobian matrix J[data_point, parameter]\n * \\return completion code GSL_SUCCESS=OK\n */\nstatic int PolnFitJacOERL (const gsl_vector *x, void *params, \n\t\t\t gsl_matrix *J)\n{\n  ObitPolnCalFit *args = (ObitPolnCalFit*)params;\n  ofloat *data, *wt;\n  gboolean **antFit  = args->antFit;\n  olong   **antPNumb = args->antPNumb;\n  odouble  *antParm  = args->antParm;\n  gboolean **souFit  = args->souFit;\n  odouble  *souParm  = args->souParm;\n  olong   **souPNumb = args->souPNumb;\n  odouble    *SR     = args->SR;\n  odouble    *DR     = args->DR;\n  odouble    *SL     = args->SL;\n  odouble    *DL     = args->DL;\n  dcomplex   *PR     = args->PR;\n  dcomplex   *PRc    = args->PRc;\n  dcomplex   *PL     = args->PL;\n  dcomplex   *PLc    = args->PLc;\n  dcomplex   *RS     = args->RS;\n  dcomplex   *RD     = args->RD;\n  dcomplex   *LS     = args->LS;\n  dcomplex   *LD     = args->LD;\n  dcomplex   *RSc    = args->RSc;\n  dcomplex   *RDc    = args->RDc;\n  dcomplex   *LSc    = args->LSc;\n  dcomplex   *LDc    = args->LDc;\n  ofloat PD, chi1, chi2, PPol;\n  double val;\n  odouble ipol=0.0, qpol=0.0, upol=0.0, vpol=0.0;\n  odouble modelR, modelI, residR, residI, gradR, gradI, isigma;\n  olong k, kk, iant, ia1, ia2, isou, idata, refAnt;\n  olong isouLast=-999;\n  dcomplex PRref, PLref, PPRL, PPLR, PA1, PA2, PA1c, PA2c;\n  dcomplex ct1, ct2, ct3, ct4, ct5, ct6;\n  dcomplex S[4], VRR, VRL, VLR, VLL, DFDP, MC1, MC2, MC3, MC4;\n  ofloat root2, maxElp=G_PI/4;\n  size_t i, j;\n\n   /* Initialize output */\n  val = 0.0;\n  for (i=0; i<args->ndata; i++) {\n    for (j=0; j<args->nparam; j++) gsl_matrix_set(J, i, j, val);\n  }\n\n  COMPLEX_SET (S[0], 0.0, 0.0);  /* Initialize poln vector */\n  COMPLEX_SET (S[1], 0.0, 0.0);\n  COMPLEX_SET (S[2], 0.0, 0.0);\n  COMPLEX_SET (S[3], 0.0, 0.0);\n  COMPLEX_SET (MC1, 0.0, 0.0);  /* Other stuff */\n  COMPLEX_SET (MC2, 0.0, 0.0);\n  COMPLEX_SET (MC3, 0.0, 0.0);\n  COMPLEX_SET (MC4, 0.0, 0.0);\n  COMPLEX_SET (VRR, 0.0, 0.0);\n  COMPLEX_SET (VLL, 0.0, 0.0);\n  COMPLEX_SET (VLR, 0.0, 0.0);\n  COMPLEX_SET (VRL, 0.0, 0.0);\n  \n  /* R-L phase difference  at reference antenna */\n  if (args->doFitRL) {\n    j = args->PDPNumb;\n    PD = gsl_vector_get(x, j);\n  } else PD = args->PD;\n  \n  /* get model parameters - first antenna */\n  for (iant=0; iant<args->nant; iant++) {\n    /* Loop over antenna parameters */\n    for (k=0; k<4; k++) {\n      /* Fitting? */\n      if ((antFit[iant][k]) && (args->gotAnt[iant])) {\n\tj = antPNumb[iant][k];\n\tantParm[iant*4+k] = gsl_vector_get(x, j);\n      }\n    } /* end loop over antenna parameters */\n  } /* end loop over antennas */\n  \n  /* Ref antenna - 0 rel */\n  refAnt = MAX(-1, args->refAnt-1);\n  \n  /* now source */\n  for (isou=0; isou<args->nsou; isou++) {\n    /* Loop over source parameters */\n    for (k=0; k<4; k++) {\n      /* Fitting? */\n      if (souFit[isou][k]) {\n\tj = souPNumb[isou][k];\n\tsouParm[isou*4+k] = gsl_vector_get(x, j);\n      }\n    } /* end loop over source parameters */\n  } /* end loop over sources */\n  \n  /* data & wt pointers */\n  data = args->inData;\n  wt   = args->inWt;\n\n  /* Injest model factorize into antenna components - \n     data in order Orientation R/X, Elipticity R/X, Orientation L/Y, Elipticity L/Y*/\n  root2 = 1.0 / sqrt(2.0);\n  /* Elipticity, Orientation terms */\n  for (i=0; i<args->nant; i++) {\n    SR[i] = cos(antParm[i*4+1]) + sin(antParm[i*4+1]);\n    DR[i] = cos(antParm[i*4+1]) - sin(antParm[i*4+1]);\n    SL[i] = cos(antParm[i*4+3]) + sin(antParm[i*4+3]);\n    DL[i] = cos(antParm[i*4+3]) - sin(antParm[i*4+3]);\n    COMPLEX_SET  (RS[i], root2*SR[i], 0.);\n    COMPLEX_SET  (ct1,   root2*DR[i], 0.);\n    COMPLEX_EXP  (PR[i], 2*antParm[i*4+0]);\n    COMPLEX_CONJUGATE (PRc[i], PR[i]);\n    COMPLEX_MUL2 (RD[i], ct1, PR[i]);\n    COMPLEX_SET  (ct1, root2*SL[i], 0.);\n    COMPLEX_EXP  (PL[i], -2*antParm[i*4+2]);\n    COMPLEX_CONJUGATE (PLc[i], PL[i]);\n    COMPLEX_MUL2 (LS[i], ct1, PL[i]);\n    COMPLEX_SET  (LD[i], root2*DL[i], 0.);\n    COMPLEX_CONJUGATE (RSc[i], RS[i]);\n    COMPLEX_CONJUGATE (RDc[i], RD[i]);\n    COMPLEX_CONJUGATE (LSc[i], LS[i]);\n    COMPLEX_CONJUGATE (LDc[i], LD[i]);\n  }\n\n  /* Reference antenna phase terms */\n  if (args->refAnt>0) {\n    COMPLEX_EXP (PRref,  antParm[(args->refAnt-1)*4+0]);\n    COMPLEX_EXP (PLref, -antParm[(args->refAnt-1)*4+2]+PD);\n  } else {\n    COMPLEX_SET (PRref, 1.0, 0.0);\n    COMPLEX_EXP (PLref, PD);\n  }\n  COMPLEX_CONJUGATE (ct1, PLref);\n  COMPLEX_MUL2 (PPRL, PRref, ct1);\n  COMPLEX_CONJUGATE (ct1, PRref);\n  COMPLEX_MUL2 (PPLR, PLref, ct1);\n\n  /* Loop over data */\n  i = 0;\n  for (idata=0; idata<args->nvis; idata++) {\n    /* Parallactic angle terms */\n    chi1  = data[idata*10+0];   /* parallactic angle ant 1 */\n    chi2  = data[idata*10+1];   /* parallactic angle ant 2 */\n    COMPLEX_EXP (PA1, 2*chi1);\n    COMPLEX_EXP (PA2, 2*chi2);\n    COMPLEX_CONJUGATE (PA1c, PA1);\n    COMPLEX_CONJUGATE (PA2c, PA2);\n\n    isou  = MAX (0, args->souNo[idata]);    /* Source number */\n    /* New source? get parameters */\n    if (isou!=isouLast) {\n      isouLast = isou;\n      /* Source parameters */\n      ipol = souParm[isou*4+0];\n      /* Fitting or fixed? */\n      if (args->souFit[isou][1]) \n\tqpol = souParm[isou*4+1];\n      else {\n\tPPol = args->PPol[isou] + args->dPPol[isou]*(args->freq-args->refFreq);\n\tqpol = PPol*ipol*cos(args->RLPhase[isou]);}\n      if (args->souFit[isou][2]) \n\tupol = souParm[isou*4+2];\n      else {\n\tPPol = args->PPol[isou] + args->dPPol[isou]*(args->freq-args->refFreq);\n\tupol = PPol*ipol*sin(args->RLPhase[isou]);}\n      vpol = souParm[isou*4+3];\n      /* Complex Stokes array */\n      COMPLEX_SET (S[0], ipol+vpol, 0.0);\n      COMPLEX_SET (S[1], qpol,  upol);\n      COMPLEX_SET (S[2], qpol, -upol);\n      COMPLEX_SET (S[3], ipol-vpol, 0.0);\n    }\n\n    /* Antenna parameters */\n    ia1    = args->antNo[idata*2+0];\n    ia2    = args->antNo[idata*2+1]; \n  \n    /* i = datum number */\n    /* Loop over correlations calculating derivatives */\n    for (kk=0; kk<4; kk++) {\n      isigma = wt[idata*4+kk];\n      if (kk<2) isigma *= 0.3;  /* Downweight parallel hand */\n      switch (kk) { \n      case 0:     /* RR */\n\tif (wt[idata*4+kk]>0.0) {\n\t  /* VRR = S[0] * RS[ia1] * RSc[ia2] +        \n\t           S[1] * RS[ia1] * RDc[ia2] * PA2c + \n\t\t   S[2] * RD[ia1] * RSc[ia2] * PA1  + \n\t\t   S[3] * RD[ia1] * RDc[ia2] * PA1  * PA2c; */\n\t  COMPLEX_MUL2 (MC1, RS[ia1], RSc[ia2]);\n\t  COMPLEX_MUL2 (VRR, S[0], MC1);\n\t  COMPLEX_MUL3 (MC2, RS[ia1], RDc[ia2],  PA2c);\n\t  COMPLEX_MUL2 (ct1, S[1], MC2);\n\t  COMPLEX_ADD2 (VRR, VRR,  ct1);\n\t  COMPLEX_MUL3 (MC3, RD[ia1], RSc[ia2], PA1);\n\t  COMPLEX_MUL2 (ct1, S[2], MC3);\n\t  COMPLEX_ADD2 (VRR, VRR,  ct1);\n\t  COMPLEX_MUL4 (MC4, RD[ia1], RDc[ia2], PA1, PA2c);\n\t  COMPLEX_MUL2 (ct1, S[3], MC4);\n\t  COMPLEX_ADD2 (VRR, VRR,  ct1);\n\t  modelR = VRR.real; modelI = VRR.imag;\n\t  /* Check for ellipticity in range */\n\t  if ((antParm[ia1*4+1]>maxElp) || (antParm[ia2*4+1]>maxElp)) {\n\t    /* out of range - give big residual */\n\t    residR = MAX((antParm[ia1*4+1]-maxElp),(antParm[ia2*4+1]-maxElp)) * \n\t      ipol * 100.;\n\t    residI = residR;\n\t  } else {  /* OK */\n\t    residR = modelR - data[idata*10+(kk+1)*2];\n\t    residI = modelI - data[idata*10+(kk+1)*2+1];\n\t  }\n\t} else  residR = residI = 0.0; /* Invalid data */\n\t\n\t/* Loop over first antenna parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* wrt Or1 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* (0, 2 i) * (S[2]*MC3 + S[3]*MC4) */\n\t\tCOMPLEX_MUL2(ct1, S[2], MC3);\n\t\tCOMPLEX_MUL2(ct2, S[3], MC4);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct1, 0.0, 2.0);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ct3);\n\t\tgradR = DFDP.real;    /* RrrR wrt Or1 */\n\t\tgradI = DFDP.imag;    /* RrrI wrt Or1 */\n\t      } else gradR = gradI =0.0;     /* Invalid data */\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* wrt Er1 */\n\t    /* Fitting? */\n \t    if (antFit[ia1][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* Derivative of model wrt Er1 */\n\t\t/* part = r2 * DR[ia1] * (S[0] * RSc[ia2] + S[1] * RDc[ia2] * PA2c) -\n\t\t          r2 * SR[ia1] * PR[ia1] * (S[2] * RSc[ia2] * PA1 + S[3] * RDc[ia2] * PA1  * PA2c) */\n\t\tCOMPLEX_MUL2(ct1, S[0], RSc[ia2]);\n\t\tCOMPLEX_MUL3(ct2, S[1], RDc[ia2], PA2c);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct4, root2*DR[ia1], 0.0);\n\t\tCOMPLEX_MUL2(ct5, ct4, ct3);\n\t\tCOMPLEX_MUL3(ct1, S[2], RSc[ia2], PA1);\n\t\tCOMPLEX_MUL4(ct2, S[3], RDc[ia2], PA1, PA2c);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct4, root2*SR[ia1], 0.0);\n\t\tCOMPLEX_MUL3(ct6, ct4, PR[ia1], ct3);\n\t\tCOMPLEX_SUB (DFDP, ct5, ct6);\n\t\tgradR = DFDP.real;    /* RrrR wrt Er1 */\n\t\tgradI = DFDP.imag;    /* RrrI wrt Er1 */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* wrt OL1 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* wrt EL1 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);\n\t    }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end first antenna parameter switch */\n\t} /* end loop over first antenna parameters */\n\t\n\t/* Loop over second antenna parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* wrt Or2 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* Derivative of model wrt Or1 */\n\t\t/* (0,-2 i) * (S[1]*MC2 + S[3]*MC4) */\n\t\tCOMPLEX_MUL2(ct1, S[1], MC2);\n\t\tCOMPLEX_MUL2(ct2, S[3], MC4);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct1, 0.0, -2.0);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ct3);\n\t\tgradR = DFDP.real;    /* RrrR wrt Ol2 */\n\t\tgradI = DFDP.imag;    /* RrrI wrt Ol2 */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* wrt Er2 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* Derivative of model wrt Er2 */\n\t\t/* part = r2 * DR[ia2] * (S[0] * RS[ia1] + S[2] * RD[ia1] * PA1) -\n\t\t          r2 * SR[ia2] * PRc[ia2] * (S[1] * RS[ia1] * PA2c + S[3] * RD[ia1] * PA1  * PA2c) */\n\t\tCOMPLEX_MUL2(ct1, S[0], RS[ia1]);\n\t\tCOMPLEX_MUL3(ct2, S[2], RD[ia1], PA1);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct4, root2*DR[ia2], 0.0);\n\t\tCOMPLEX_MUL2(ct5, ct4, ct3);\n\t\tCOMPLEX_MUL3(ct1, S[1], RS[ia1], PA2c );\n\t\tCOMPLEX_MUL4(ct2, S[3], RD[ia1], PA1, PA2c);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct4, root2*SR[ia2], 0.0);\n\t\tCOMPLEX_MUL3(ct6, ct4, PRc[ia2], ct3);\n\t\tCOMPLEX_SUB (DFDP, ct5, ct6);\n\t\tgradR = DFDP.real;    /* RrrR wrt Ol2 */\n\t\tgradI = DFDP.imag;    /* RrrI wrt Ol2 */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* wrt Ol2 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* wrt El2 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */\n\t    }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end second antenna parameter switch */\n\t}  /* end loop over second antenna parameters */\n\t\n\t/* Loop over source parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* wrt I */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = RS[ia1] * RSc[ia2] + RD[ia1] * RDc[ia2] * PA1 * PA2c */\n\t\tCOMPLEX_MUL2(ct1, RS[ia1], RSc[ia2]);\n\t\tCOMPLEX_MUL4(ct2, RD[ia1], RDc[ia2], PA1, PA2c);\n\t\tCOMPLEX_ADD2(DFDP, ct1, ct2);\n\t\tgradR = DFDP.real;    /* RrrR wrt ipol */\n\t\tgradI = DFDP.imag;    /* RrrI wrt ipol */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* wrt qpol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = RS[ia1] * RDc[ia2] * PA2c + RD[ia1] * RSc[ia2] * PA1 */\n\t\tCOMPLEX_MUL3(ct1, RS[ia1], RDc[ia2], PA2c);\n\t\tCOMPLEX_MUL3(ct2, RD[ia1], RSc[ia2], PA1);\n\t\tCOMPLEX_ADD2(DFDP, ct1, ct2);\n\t\tgradR = DFDP.real;    /* RrrR wrt qpol */\n\t\tgradI = DFDP.imag;    /* RrrI wrt qpol */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* wrt upol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = i (RS[ia1] * RDc[ia2] * PA2c - RD[ia1] * RSc[ia2] * PA1) */\n\t\tCOMPLEX_MUL3(ct1, RS[ia1], RDc[ia2], PA2c);\n\t\tCOMPLEX_MUL3(ct2, RD[ia1], RSc[ia2], PA1);\n\t\tCOMPLEX_SUB (ct3, ct1, ct2);\n \t\tCOMPLEX_SET(ct4, 0.0, 1.0);\n\t\tCOMPLEX_MUL2(DFDP, ct4, ct3);\n\t\tgradR = DFDP.real;    /* RrrR wrt upol */\n\t\tgradI = DFDP.imag;    /* RrrI wrt upol */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* wrt V */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = RS[ia1] * RSc[ia2] - RD[ia1] * RDc[ia2] * PA1 * PA2c */\n\t\tCOMPLEX_MUL2(ct1, RS[ia1], RSc[ia2]);\n\t\tCOMPLEX_MUL4(ct2, RD[ia1], RDc[ia2], PA1, PA2c);\n\t\tCOMPLEX_SUB (DFDP, ct1, ct2);\n\t\tgradR = DFDP.real;    /* RrrR wrt vpol */\n\t\tgradI = DFDP.imag;    /* RrrI wrt vpol */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t    }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end source parameter switch */\n\t} /* end loop over source parameters */\n      \n\t/* gradient wrt PD = 0 */\n\tif (args->doFitRL) {\n\t  gradR = gradI = 0.0;\n\t  j = args->PDPNumb;\n\t  gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t  gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t}\n\t\n\tbreak;  /* End RR */\n\t    \n      case 1:     /* LL */\n \tif (wt[idata*4+kk]>0.0) {\n\t  /* VLL = S[0] * LS[ia1] * LSc[ia2] * PA1c * PA2 +\t\n\t           S[1] * LS[ia1] * LDc[ia2] * PA1c +\n\t\t   S[2] * LD[ia1] * LSc[ia2] * PA2  +\n\t\t   S[3] * LD[ia1] * LDc[ia2]; */\n\t  COMPLEX_MUL4 (MC1, LS[ia1], LSc[ia2], PA1c, PA2);\n\t  COMPLEX_MUL2 (VLL, S[0], MC1);\n\t  COMPLEX_MUL3 (MC2, LS[ia1], LDc[ia2], PA1c);\n\t  COMPLEX_MUL2 (ct1, S[1], MC2);\n\t  COMPLEX_ADD2 (VLL, VLL,  ct1);\n\t  COMPLEX_MUL3 (MC3, LD[ia1], LSc[ia2], PA2);\n\t  COMPLEX_MUL2 (ct1, S[2], MC3);\n\t  COMPLEX_ADD2 (VLL, VLL,  ct1);\n\t  COMPLEX_MUL2 (MC4, LD[ia1], LDc[ia2]);\n\t  COMPLEX_MUL2 (ct1, S[3], MC4);\n\t  COMPLEX_ADD2 (VLL, VLL,  ct1);\n\t  modelR = VLL.real; modelI = VLL.imag;\n\t  /* Check for ellipticity in range */\n\t  if ((antParm[ia1*4+3]<-maxElp) || (antParm[ia2*4+3]<-maxElp)) {\n\t    /* out of range - give big residual */\n\t    residR = MAX((maxElp-antParm[ia1*4+3]),(maxElp-antParm[ia2*4+3])) * \n\t      ipol * 100.;\n\t    residI = residR;\n\t  } else {  /* OK */\n\t    residR = modelR - data[idata*10+(kk+1)*2];\n\t    residI = modelI - data[idata*10+(kk+1)*2+1];\n\t  }\n\t} else  residR = residI = 0.0; /* Invalid data */\n\t  \n\t/* Loop over first antenna parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* wrt OR1 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* wrt Er1 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* wrt Ol1 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* Derivative of model wrt Or1 */\n\t\t/* (0,-2 i) * (S[0]*MC1 + S[1]*MC2) */\n\t\tCOMPLEX_MUL2(ct1, S[0], MC1);\n\t\tCOMPLEX_MUL2(ct2, S[1], MC2);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct1, 0.0, -2.0);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ct3);\n\t\tgradR = DFDP.real;    /* RllR wrt Ol1 */\n\t\tgradI = DFDP.imag;    /* RllI wrt Ol1 */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* wrt El1 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* Derivative of model wrt El1 */\n\t\t/* part = r2 * DL[ia1] * PL[ia1] * (S[0] * LSc[ia2] * PA1c * PA2 + \n                                                    S[1] * LDc[ia2] * PA1c) -\n                          r2 * SL[ia1] * (S[2] * LSc[ia2] * PA2  + S[3] * LDc[ia2]) */\n\t\tCOMPLEX_MUL4(ct1, S[0], LSc[ia2], PA1c, PA2);\n\t\tCOMPLEX_MUL3(ct2, S[1], LDc[ia2], PA1c);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct4, root2*DL[ia1], 0.0);\n\t\tCOMPLEX_MUL3(ct5, ct4, PL[ia1], ct3);\n\t\tCOMPLEX_MUL3(ct1, S[2], LSc[ia2], PA2);\n\t\tCOMPLEX_MUL2(ct2, S[3], LDc[ia2]);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct4, root2*SL[ia1], 0.0);\n\t\tCOMPLEX_MUL2(ct6, ct4, ct3);\n\t\tCOMPLEX_SUB (DFDP, ct5, ct6);\n\t\tgradR = DFDP.real;    /* RllR wrt El1 */\n\t\tgradI = DFDP.imag;    /* RllI wrt El1 */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t    }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end first antenna parameter switch */\n\t} /* end loop over first antenna parameters */\n\t\n\t/* Loop over second antenna parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* wrt Or2 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* Rll wrt E2r = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* Rll wrt Ol2 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* Derivative of model wrt Ol2 */\n\t\t/* (0, 2 i) * (S[0]*MC1 + S[2]*MC3) */\n\t\tCOMPLEX_MUL2(ct1, S[0], MC1);\n\t\tCOMPLEX_MUL2(ct2, S[2], MC3);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct1, 0.0, 2.0);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ct3);\n\t\tgradR = DFDP.real;    /* RllR wrt Ol2 */\n\t\tgradI = DFDP.imag;    /* RllI wrt Ol2 */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* wrt El2  */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* Derivative of model wrt El2 */\n\t\t/* part = r2 * DL[ia2] * PLc[ia2] * (S[0] * LS[ia1] * PA1c * PA2 + \n                                                     S[2] * LD[ia1] * PA2) -\n                          r2 * SL[ia2] * (S[1] * LS[ia1] * PA1c + S[3] * LD[ia1]) */\n\t\tCOMPLEX_MUL4(ct1, S[0], LS[ia1], PA1c, PA2);\n\t\tCOMPLEX_MUL3(ct2, S[2], LD[ia1], PA2);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct4, root2*DL[ia2], 0.0);\n\t\tCOMPLEX_MUL3(ct5, ct4, PLc[ia2], ct3);\n\t\tCOMPLEX_MUL3(ct1, S[1], LS[ia1], PA1c);\n\t\tCOMPLEX_MUL2(ct2, S[3], LD[ia1]);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct4, root2*SL[ia2], 0.0);\n\t\tCOMPLEX_MUL2(ct6, ct4, ct3);\n\t\tCOMPLEX_SUB (DFDP, ct5, ct6);\n\t\tgradR = DFDP.real;    /* RllR wrt El2 */\n\t\tgradI = DFDP.imag;    /* RllI wrt El2 */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t    }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end second antenna parameter switch */\n\t} /* end loop over second antenna parameters */\n\t\n\t/* Loop over source parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* wrt I */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = LS[ia1] * LSc[ia2] * PA1c * PA2 + LD[ia1] * LDc[ia2] */\n\t\tCOMPLEX_MUL4(ct1, LS[ia1], LSc[ia2], PA1c, PA2);\n\t\tCOMPLEX_MUL2(ct2, LD[ia1], LDc[ia2]);\n\t\tCOMPLEX_ADD2(DFDP, ct1, ct2);\n\t\tgradR = DFDP.real;    /* RLLR wrt ipol */\n\t\tgradI = DFDP.imag;    /* RLLI wrt ipol */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* wrt Qpol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = (LS[ia1] * LDc[ia2] * PA1c + LD[ia1] * LSc[ia2] * PA2) */\n\t\tCOMPLEX_MUL3(ct1, LS[ia1], LDc[ia2], PA1c);\n\t\tCOMPLEX_MUL3(ct2, LD[ia1], LSc[ia2], PA2);\n\t\tCOMPLEX_ADD2(DFDP, ct1, ct2);\n\t\tgradR = DFDP.real;    /* RllR wrt qpol */\n\t\tgradI = DFDP.imag;    /* RllI wrt qpol */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* wrt UPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part =  i( LS[ia1] * LDc[ia2] * PA1c - LD[ia1] * LSc[ia2] * PA2) */\n\t\tCOMPLEX_MUL3(ct1, LS[ia1], LDc[ia2], PA1c);\n\t\tCOMPLEX_MUL3(ct2, LD[ia1], LSc[ia2], PA2);\n\t\tCOMPLEX_SUB (ct3, ct1, ct2);\n\t\tCOMPLEX_SET(ct4, 0.0, 1.0);\n\t\tCOMPLEX_MUL2(DFDP, ct4, ct3);\n\t\tgradR = DFDP.real;    /* RllR wrt upol */\n\t\tgradI = DFDP.imag;    /* RllI wrt upol */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* wrt V */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = LS[ia1] * LSc[ia2] * PA1c * PA2 - LD[ia1] * LDc[ia2] */\n\t\tCOMPLEX_MUL4(ct1, LS[ia1], LSc[ia2], PA1c, PA2);\n\t\tCOMPLEX_MUL2(ct2, LD[ia1], LDc[ia2]);\n\t\tCOMPLEX_SUB (DFDP, ct1, ct2);\n\t\tgradR = DFDP.real;    /* RllR wrt vpol */\n\t\tgradI = DFDP.imag;    /* RllI wrt vpol */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t    }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end source parameter switch */\n\t} /* end loop over source parameters */\n\n\t/* gradient wrt PD - no effect */\n\tif (args->doFitRL) {\n\t  gradR = gradI = 0.0;\n\t  j = args->PDPNumb;\n\t  gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t  gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t}\n\t\n\tbreak;  /* End LL */\n\tbreak;  /* End LL */\n\n        case 2:     /* RL */\n\tif (wt[idata*4+kk]>0.0) {\n\t  /* VRL = PPRL * S[0] * RS[ia1] * LSc[ia2] * PA2 +\n\t           PPRL * S[1] * RS[ia1] * LDc[ia2] + \n\t\t   PPRL * S[2] * RD[ia1] * LSc[ia2] * PA1 * PA2 +\n\t\t   PPRL * S[3] * RD[ia1] * LDc[ia2] * PA1; */\n\t  COMPLEX_MUL4 (MC1, PPRL, RS[ia1], LSc[ia2], PA2);\n\t  COMPLEX_MUL2 (VRL, S[0], MC1);\n\t  COMPLEX_MUL3 (MC2, PPRL, RS[ia1], LDc[ia2]);\n\t  COMPLEX_MUL2 (ct1, S[1], MC2);\n\t  COMPLEX_ADD2 (VRL, VRL,  ct1);\n\t  COMPLEX_MUL5 (MC3, PPRL, RD[ia1], LSc[ia2],  PA1,  PA2);\n\t  COMPLEX_MUL2 (ct1, S[2], MC3);\n\t  COMPLEX_ADD2 (VRL, VRL,  ct1);\n\t  COMPLEX_MUL4 (MC4, PPRL, RD[ia1], LDc[ia2],  PA1);\n\t  COMPLEX_MUL2 (ct1, S[3], MC4);\n\t  COMPLEX_ADD2 (VRL, VRL,  ct1);\n\t  modelR = VRL.real; modelI = VRL.imag;\n\t  /* Check for ellipticity in range */\n\t  if ((antParm[ia1*4+1]>maxElp) || (antParm[ia2*4+3]<-maxElp)) {\n\t    /* out of range - give big residual */\n\t    residR = MAX((antParm[ia1*4+1]-maxElp),(maxElp-antParm[ia2*4+3])) * \n\t      ipol * 100.;\n\t    residI = residR;\n\t  } else {  /* OK */\n\t    residR = modelR - data[idata*10+(kk+1)*2];\n\t    residI = modelI - data[idata*10+(kk+1)*2+1];\n\t  }\n\t} else  residR = residI = 0.0; /* Invalid data */\n\n\t/* Loop over first antenna parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* wrt Or1 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* (0, 2 i) * (S[2]*MC3 + S[3]*MC4) */\n\t\tCOMPLEX_MUL2(ct1, S[2], MC3);\n\t\tCOMPLEX_MUL2(ct2, S[3], MC4);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct1, 0.0,  2.0);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ct3);\n\t\t/* If ia1==refant) */\n\t\tif (ia1==refAnt) {\n\t\t  COMPLEX_MUL2(ct2, ct1, VRL);\n\t\t  COMPLEX_ADD2(DFDP, DFDP, ct2);\n\t\t}\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* wrt Er1 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = r2 * DR[ia1] * (PPRL * S[0] * LSc[ia2] * PA2 + PPRL * S[1] * LDc[ia2]) -\n                          r2 * SR[ia1] * PR[ia1] * (PPRL * S[2] * LSc[ia2] * PA1 * PA2 +\n\t\t\t                           PPRL * S[3] * LDc[ia2] * PA1) */\n\t\tCOMPLEX_MUL4(ct1, PPRL, S[0], LSc[ia2], PA2);\n\t\tCOMPLEX_MUL3(ct2, PPRL, S[1], LDc[ia2]);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct4, root2*DR[ia1], 0.0);\n\t\tCOMPLEX_MUL2(ct5, ct4, ct3);\n\t\tCOMPLEX_MUL5(ct1, PPRL, S[2], LSc[ia2], PA1, PA2);\n\t\tCOMPLEX_MUL4(ct2, PPRL, S[3], LDc[ia2], PA1);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct4, root2*SR[ia1], 0.0);\n\t\tCOMPLEX_MUL3(ct6, ct4, PR[ia1], ct3);\n\t\tCOMPLEX_SUB (DFDP, ct5, ct6);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* wrt Ol1 =0 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* wrt El1 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */\n\t    }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end first antenna parameter switch */\n\t} /* end loop over first antenna parameters */\n      \n\t/* Loop over second antenna parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* wrt Or2 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* wrt Er2 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* wrt Ol2 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* (0, 2 i) * (S[0]*MC1 + S[2]*MC3) */\n\t\tCOMPLEX_MUL2(ct1, S[0], MC1);\n\t\tCOMPLEX_MUL2(ct2, S[2], MC3);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct1, 0.0,  2.0);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ct3);\n\t\t/* If ia2==refant) */\n\t\tif (ia2==refAnt) {\n\t\t  COMPLEX_SET (ct1, 0.0, 2.0);\n\t\t  COMPLEX_MUL2(ct2, ct1, VRL);\n\t\t  COMPLEX_ADD2(DFDP, DFDP, ct2);\n\t\t}\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* wrt El2 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = r2 * DL[ia2] * PLc[ia2] * (PPRL * S[0] * RS[ia1] * PA2 + \n                                                     PPRL * S[2] * RD[ia1] * PA1 * PA2) -\n\t\t\t  r2 * SL[ia2] * (PPRL * S[1] * RS[ia1] + PPRL * S[3] * RD[ia1] * PA1) */\n\t\tCOMPLEX_MUL4(ct1, PPRL, S[0], RS[ia1], PA2);\n\t\tCOMPLEX_MUL5(ct2, PPRL, S[2], RD[ia1], PA1, PA2);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct4, root2*DL[ia2], 0.0);\n\t\tCOMPLEX_MUL3(ct5, ct4, PLc[ia2], ct3);\n\t\tCOMPLEX_MUL3(ct1, PPRL, S[1], RS[ia1]);\n\t\tCOMPLEX_MUL4(ct2, PPRL, S[3], RD[ia1], PA1);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct4, root2*SL[ia2], 0.0);\n\t\tCOMPLEX_MUL2(ct6, ct4, ct3);\n\t\tCOMPLEX_SUB (DFDP, ct5, ct6);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t    }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end second antenna parameter switch */\n\t} /* end loop over second antenna parameters */\n  \n\t/* Loop over source parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* wrt I */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part =  PPRL * RS[ia1] * LSc[ia2] * PA2 + PPRL * RD[ia1] * LDc[ia2] * PA1*/\n\t\tCOMPLEX_MUL4(ct1, PPRL, RS[ia1], LSc[ia2], PA2 );\n\t\tCOMPLEX_MUL4(ct2, PPRL, RD[ia1], LDc[ia2], PA1);\n\t\tCOMPLEX_ADD2(DFDP, ct1, ct2);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* wrt QPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = (PPRL * RS[ia1] * LDc[ia2] + PPRL * RD[ia1] * LSc[ia2] * PA1 * PA2) */\n\t\tCOMPLEX_MUL3(ct1, PPRL, RS[ia1], LDc[ia2]);\n\t\tCOMPLEX_MUL5(ct2, PPRL, RD[ia1], LSc[ia2], PA1, PA2);\n\t\tCOMPLEX_ADD2(DFDP, ct1, ct2);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* wrt UPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = i(PPRL * RS[ia1] * LDc[ia2] - PPRL * RD[ia1] * LSc[ia2] * PA1 * PA2) */\n\t\tCOMPLEX_MUL2(ct1, RS[ia1], LDc[ia2]);\n\t\tCOMPLEX_MUL4(ct2, RD[ia1], LSc[ia2], PA1, PA2);\n\t\tCOMPLEX_SUB (ct3, ct1, ct2);\n\t\tCOMPLEX_SET(ct4, 0.0, 1.0);\n\t\tCOMPLEX_MUL3(DFDP, ct4, PPRL, ct3);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* wrt V */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = PPRL * RS[ia1] * LSc[ia2] * PA2 - PPRL * RD[ia1] * LDc[ia2] * PA1 */\n\t\tCOMPLEX_MUL4(ct1, PPRL, RS[ia1], LSc[ia2], PA2);\n\t\tCOMPLEX_MUL4(ct2, PPRL, RD[ia1], LDc[ia2], PA1);\n\t\tCOMPLEX_SUB (DFDP, ct1, ct2);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t    }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end source parameter switch */\n\t} /* end loop over source parameters */\n      \n\t/* gradient wrt PD */\n\tif (args->doFitRL) {\n\t  if (wt[idata*4+kk]>0.0) {\n\t    COMPLEX_SET(ct1, 0.0, 1.0);\n\t    COMPLEX_MUL2(DFDP, ct1, VRL);\n\t    gradR = DFDP.real;\n\t    gradI = DFDP.imag;\n\t  } else gradR = gradI = 0.0;    /* invalid data */\n\t  j = args->PDPNumb;\n\t  gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t  gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t}\n\t\n\tbreak;  /* End RL */\n      case 3:     /* LR */\n\tif (wt[idata*4+kk]>0.0) {\n\t  /* VLR = PPLR * S[0] * LS[ia1] * RSc[ia2] * PA1c +\n\t           PPLR * S[1] * LS[ia1] * RDc[ia2] * PA1c * PA2c +\n\t\t   PPLR * S[2] * LD[ia1] * RSc[ia2] +\n\t\t   PPLR * S[3] * LD[ia1] * RDc[ia2] * PA2c */\n\t  COMPLEX_MUL4 (MC1, PPLR, LS[ia1], RSc[ia2], PA1c);\n\t  COMPLEX_MUL2 (VLR, S[0], MC1);\n\t  COMPLEX_MUL5 (MC2, PPLR, LS[ia1], RDc[ia2], PA1c,  PA2c);\n\t  COMPLEX_MUL2 (ct1, S[1], MC2);\n\t  COMPLEX_ADD2 (VLR, VLR,  ct1);\n\t  COMPLEX_MUL3 (MC3, PPLR, LD[ia1], RSc[ia2]);\n\t  COMPLEX_MUL2 (ct1, S[2], MC3);\n\t  COMPLEX_ADD2 (VLR, VLR,  ct1);\n\t  COMPLEX_MUL4 (MC4, PPLR, LD[ia1], RDc[ia2],  PA2c);\n\t  COMPLEX_MUL2 (ct1, S[3], MC4);\n\t  COMPLEX_ADD2 (VLR, VLR, ct1);\n\t  modelR = VLR.real; modelI = VLR.imag;\n\t  /* Check for ellipticity in range */\n\t  if ((antParm[ia1*4+3]<-maxElp) || (antParm[ia2*4+1]>maxElp)) {\n\t    /* out of range - give big residual */\n\t    residR = MAX((maxElp-antParm[ia1*4+3]),(antParm[ia2*4+1]-maxElp)) * \n\t      ipol * 100.;\n\t    residI = residI;\n\t  } else {  /* OK */\n\t    residR = modelR - data[idata*10+(kk+1)*2];\n\t    residI = modelI - data[idata*10+(kk+1)*2+1];\n\t  }\n\t} else  residR = residI = 0.0; /* Invalid data */\n\t\n\t/* Loop over first antenna parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* wrt Or1 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* wrt Er1 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* wrt Ol1 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* (0,-2 i) * (S[0]*MC1 + S[1]*MC2) */\n\t\tCOMPLEX_MUL2(ct1, S[0], MC1);\n\t\tCOMPLEX_MUL2(ct2, S[1], MC2);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct1, 0.0, -2.0);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ct3);\n\t\t/* If ia1==refant) */\n\t\tif (ia1==refAnt) {\n\t\t  COMPLEX_SET (ct1, 0.0, -2.0);\n\t\t  COMPLEX_MUL2(ct2, ct1, VLR);\n\t\t  COMPLEX_ADD2(DFDP, DFDP, ct2);\n\t\t}\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* wrt El1 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = r2 * DL[ia1] * PL[ia1] * (PPLR * S[0] * RSc[ia2] * PA1c + \n                                                    PPLR * S[1] * RDc[ia2] * PA1c * PA2c) -\n                          r2 * SL[ia1] * (PPLR * S[2] * RSc[ia2] + PPLR * S[3] * RDc[ia2] * PA2c) */\n\t\tCOMPLEX_MUL4(ct1, PPLR, S[0], RSc[ia2], PA1c);\n\t\tCOMPLEX_MUL5(ct2, PPLR, S[1], RDc[ia2], PA1c, PA2c);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct4, root2*DL[ia1], 0.0);\n\t\tCOMPLEX_MUL3(ct5, ct4, PL[ia1], ct3);\n\t\tCOMPLEX_MUL3(ct1, PPLR, S[2], RSc[ia2]);\n\t\tCOMPLEX_MUL4(ct2, PPLR, S[3], RDc[ia2], PA2c);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct4, root2*SL[ia1], 0.0);\n\t\tCOMPLEX_MUL2(ct6, ct4, ct3);\n\t\tCOMPLEX_SUB (DFDP, ct5, ct6);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t    }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end first antenna parameter switch */\n\t} /* end loop over first antenna parameters */\n\t\n\t/* Loop over second antenna parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* wrt Or2 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* (0,-2 i) * (S[1]*MC2 + S[3]*MC4) */\n\t\tCOMPLEX_MUL2(ct1, S[1], MC2);\n\t\tCOMPLEX_MUL2(ct2, S[3], MC4);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct1, 0.0, -2.0);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ct3);\n\t\t/* If ia2==refant */\n\t\tif (ia2==refAnt) {\n\t\t  COMPLEX_MUL2(ct2, ct1, VLR);\n\t\t  COMPLEX_ADD2(DFDP, DFDP, ct2);\n\t\t}\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* wrt Er2 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = r2 * DR[ia2] * (PPLR * S[0] * LS[ia1] * PA1c + PPLR * S[2] * LD[ia1]) -\n                          r2 * SR[ia2] * PRc[ia2] * (PPLR * S[1] * LS[ia1] * PA1c * PA2c + \n                                                     PPLR * S[3] * LD[ia1] * PA2c) */\n\t\tCOMPLEX_MUL4(ct1, PPLR, S[0], LS[ia1], PA1c);\n\t\tCOMPLEX_MUL3(ct2, PPLR, S[2], LD[ia1]);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct4, root2*DR[ia2], 0.0);\n\t\tCOMPLEX_MUL2(ct5, ct4, ct3);\n\t\tCOMPLEX_MUL5(ct1, PPLR, S[1], LS[ia1], PA1c, PA2c);\n\t\tCOMPLEX_MUL4(ct2, PPLR, S[3], LD[ia1], PA2c);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct4, root2*SR[ia2], 0.0);\n\t\tCOMPLEX_MUL3(ct6, ct4, PRc[ia2], ct3);\n\t\tCOMPLEX_SUB (DFDP, ct5, ct6);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* wrt Ol2 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* wrt El2 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */\n\t    }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end second antenna parameter switch */\n\t} /* end loop over second antenna parameters */\n\t\n\t/* Loop over source parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* wrt I */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = PPLR * LS[ia1] * RSc[ia2] * PA1c + PPLR * LD[ia1] * RDc[ia2] * PA2c */\n\t\tCOMPLEX_MUL4(ct1, PPLR, LS[ia1], RSc[ia2], PA1c);\n\t\tCOMPLEX_MUL4(ct2, PPLR, LD[ia1], RDc[ia2], PA2c);\n\t\tCOMPLEX_ADD2(DFDP, ct1, ct2);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* wrt QPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = (PPLR * LS[ia1] * RDc[ia2] * PA1c * PA2c + PPLR * LD[ia1] * RSc[ia2]) */\n\t\tCOMPLEX_MUL5(ct1, PPLR, LS[ia1], RDc[ia2], PA1c, PA2c);\n\t\tCOMPLEX_MUL3(ct2, PPLR, LD[ia1], RSc[ia2]);\n\t\tCOMPLEX_ADD2(DFDP, ct1, ct2);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* wrt UPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = i (PPLR * LS[ia1] * RDc[ia2] * PA1c * PA2c - PPLR * LD[ia1] * RSc[ia2]) */\n\t\tCOMPLEX_MUL4(ct1, LS[ia1], RDc[ia2], PA1c, PA2c);\n\t\tCOMPLEX_MUL2(ct2, LD[ia1], RSc[ia2]);\n\t\tCOMPLEX_SUB (ct3, ct1, ct2);\n\t\tCOMPLEX_SET(ct4, 0.0, 1.0);\n\t\tCOMPLEX_MUL3(DFDP, ct4, PPLR, ct3);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* wrt Vpol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = PPLR * LS[ia1] * RSc[ia2] * PA1c - PPLR * LD[ia1] * RDc[ia2] * PA2c */\n\t\tCOMPLEX_MUL4(ct1, PPLR, LS[ia1], RSc[ia2], PA1c);\n\t\tCOMPLEX_MUL4(ct2, PPLR, LD[ia1], RDc[ia2], PA2c);\n\t\tCOMPLEX_SUB (DFDP, ct1, ct2);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t    }\n\tbreak;\n      default:\n\tbreak;\n\t  }; /* end source parameter switch */\n\t} /* end loop over source parameters */\n\n\t/* gradient wrt PD */\n\tif (args->doFitRL) {\n\t  if (wt[idata*4+kk]>0.0) {\n\t    COMPLEX_SET(ct1, 0.0, -1.0);\n\t    COMPLEX_MUL2(DFDP, ct1, VLR);\n\t    gradR = DFDP.real;\n\t    gradI = DFDP.imag;\n\t  } else gradR = gradI = 0.0;    /* invalid data */\n\t  j = args->PDPNumb;\n\t  gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t  gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t}\n\t/* End LR */\n      }; /* end switch over data correlation */\n      i++;  /* Update complex datum number */\n    } /* end loop over correlations */\n  } /* End loop over visibilities */\n\n  return GSL_SUCCESS;\n} /*  end PolnFitJacOERL */\n\n/**\n * Circular feed Function & Jacobian evaluator for polarization fitting solver\n * Orientation/Ellipticity for circular feeds version\n * Evaluates partial derivatives of model wrt each parameter\n * \\param x       Vector of parameters to be fitted\n *                Flux,array_of polarization_terms\n * \\param param   Function parameter structure (ObitPolnCalFit)\n * \\param f       Vector of (model-obs)/sigma for data points\n * \\param J       Jacobian matrix J[data_point, parameter]\n * \\return completion code GSL_SUCCESS=OK\n */\nstatic int PolnFitFuncJacOERL (const gsl_vector *x, void *params, \n\t\t\t       gsl_vector *f, gsl_matrix *J)\n{\n  ObitPolnCalFit *args = (ObitPolnCalFit*)params;\n  ofloat *data, *wt;\n  gboolean **antFit  = args->antFit;\n  olong   **antPNumb = args->antPNumb;\n  odouble  *antParm  = args->antParm;\n  gboolean **souFit  = args->souFit;\n  odouble  *souParm  = args->souParm;\n  olong   **souPNumb = args->souPNumb;\n  odouble    *SR     = args->SR;\n  odouble    *DR     = args->DR;\n  odouble    *SL     = args->SL;\n  odouble    *DL     = args->DL;\n  dcomplex   *PR     = args->PR;\n  dcomplex   *PRc    = args->PRc;\n  dcomplex   *PL     = args->PL;\n  dcomplex   *PLc    = args->PLc;\n  dcomplex   *RS     = args->RS;\n  dcomplex   *RD     = args->RD;\n  dcomplex   *LS     = args->LS;\n  dcomplex   *LD     = args->LD;\n  dcomplex   *RSc    = args->RSc;\n  dcomplex   *RDc    = args->RDc;\n  dcomplex   *LSc    = args->LSc;\n  dcomplex   *LDc    = args->LDc;\n  ofloat PD, chi1, chi2, PPol;\n  double val;\n  odouble ipol=0.0, qpol=0.0, upol=0.0, vpol=0.0;\n  odouble residR, residI, gradR, gradI, modelR, modelI, isigma;\n  olong k, kk, iant, ia1, ia2, isou, idata, refAnt;\n  olong isouLast=-999;\n  dcomplex PRref, PLref, PPRL, PPLR, PA1, PA2, PA1c, PA2c;\n  dcomplex ct1, ct2, ct3, ct4, ct5, ct6;\n  dcomplex S[4], VRR, VRL, VLR, VLL, DFDP, MC1, MC2, MC3, MC4;\n  ofloat root2, maxElp=G_PI/4;\n  size_t i, j;\n\n   /* Initialize output */\n  val = 0.0;\n  for (i=0; i<args->ndata; i++) {\n    gsl_vector_set(f, i, val);\n    for (j=0; j<args->nparam; j++) gsl_matrix_set(J, i, j, val);\n  }\n\n  COMPLEX_SET (S[0], 0.0, 0.0);  /* Initialize poln vector */\n  COMPLEX_SET (S[1], 0.0, 0.0);\n  COMPLEX_SET (S[2], 0.0, 0.0);\n  COMPLEX_SET (S[3], 0.0, 0.0);\n  COMPLEX_SET (MC1, 0.0, 0.0);  /* Other stuff */\n  COMPLEX_SET (MC2, 0.0, 0.0);\n  COMPLEX_SET (MC3, 0.0, 0.0);\n  COMPLEX_SET (MC4, 0.0, 0.0);\n  COMPLEX_SET (VRR, 0.0, 0.0);\n  COMPLEX_SET (VLL, 0.0, 0.0);\n  COMPLEX_SET (VLR, 0.0, 0.0);\n  COMPLEX_SET (VRL, 0.0, 0.0);\n  \n  /* R-L phase difference  at reference antenna */\n  if (args->doFitRL) {\n    j = args->PDPNumb;\n    PD = gsl_vector_get(x, j);\n  } else PD = args->PD;\n  \n  /* get model parameters - first antenna */\n  for (iant=0; iant<args->nant; iant++) {\n    /* Loop over antenna parameters */\n    for (k=0; k<4; k++) {\n      /* Fitting? */\n      if ((antFit[iant][k]) && (args->gotAnt[iant])) {\n\tj = antPNumb[iant][k];\n\tantParm[iant*4+k] = gsl_vector_get(x, j);\n      }\n    } /* end loop over antenna parameters */\n  } /* end loop over antennas */\n  \n  /* Ref antenna - 0 rel */\n  refAnt = MAX(-1, args->refAnt-1);\n  \n  /* now source */\n  for (isou=0; isou<args->nsou; isou++) {\n    /* Loop over source parameters */\n    for (k=0; k<4; k++) {\n      /* Fitting? */\n      if (souFit[isou][k]) {\n\tj = souPNumb[isou][k];\n\tsouParm[isou*4+k] = gsl_vector_get(x, j);\n      }\n    } /* end loop over source parameters */\n  } /* end loop over sources */\n  \n  /* data & wt pointers */\n  data = args->inData;\n  wt   = args->inWt;\n\n  /* Injest model factorize into antenna components - \n     data in order Orientation R/X, Elipticity R/X, Orientation L/Y, Elipticity L/Y*/\n  root2 = 1.0 / sqrt(2.0);\n  /* Elipticity, Orientation terms */\n  for (i=0; i<args->nant; i++) {\n    SR[i] = cos(antParm[i*4+1]) + sin(antParm[i*4+1]);\n    DR[i] = cos(antParm[i*4+1]) - sin(antParm[i*4+1]);\n    SL[i] = cos(antParm[i*4+3]) + sin(antParm[i*4+3]);\n    DL[i] = cos(antParm[i*4+3]) - sin(antParm[i*4+3]);\n    COMPLEX_SET  (RS[i], root2*SR[i], 0.);\n    COMPLEX_SET  (ct1,   root2*DR[i], 0.);\n    COMPLEX_EXP  (PR[i], 2*antParm[i*4+0]);\n    COMPLEX_CONJUGATE (PRc[i], PR[i]);\n    COMPLEX_MUL2 (RD[i], ct1, PR[i]);\n    COMPLEX_SET  (ct1, root2*SL[i], 0.);\n    COMPLEX_EXP  (PL[i], -2*antParm[i*4+2]);\n    COMPLEX_CONJUGATE (PLc[i], PL[i]);\n    COMPLEX_MUL2 (LS[i], ct1, PL[i]);\n    COMPLEX_SET  (LD[i], root2*DL[i], 0.);\n    COMPLEX_CONJUGATE (RSc[i], RS[i]);\n    COMPLEX_CONJUGATE (RDc[i], RD[i]);\n    COMPLEX_CONJUGATE (LSc[i], LS[i]);\n    COMPLEX_CONJUGATE (LDc[i], LD[i]);\n  }\n\n  /* Reference antenna phase terms */\n  if (args->refAnt>0) {\n    COMPLEX_EXP (PRref,  antParm[(args->refAnt-1)*4+0]);\n    COMPLEX_EXP (PLref, -antParm[(args->refAnt-1)*4+2]+PD);\n   } else {\n    COMPLEX_SET (PRref, 1.0, 0.0);\n    COMPLEX_EXP (PLref, PD);\n  }\n  COMPLEX_CONJUGATE (ct1, PLref);\n  COMPLEX_MUL2 (PPRL, PRref, ct1);\n  COMPLEX_CONJUGATE (ct1, PRref);\n  COMPLEX_MUL2 (PPLR, PLref, ct1);\n\n  /* Loop over data */\n  i = 0;\n  for (idata=0; idata<args->nvis; idata++) {\n    /* Parallactic angle terms */\n    chi1  = data[idata*10+0];   /* parallactic angle ant 1 */\n    chi2  = data[idata*10+1];   /* parallactic angle ant 2 */\n    COMPLEX_EXP (PA1, 2*chi1);\n    COMPLEX_EXP (PA2, 2*chi2);\n    COMPLEX_CONJUGATE (PA1c, PA1);\n    COMPLEX_CONJUGATE (PA2c, PA2);\n\n    isou  = MAX (0, args->souNo[idata]);    /* Source number */\n    /* New source? get parameters */\n    if (isou!=isouLast) {\n      isouLast = isou;\n      /* Source parameters */\n      ipol = souParm[isou*4+0];\n      /* Fitting or fixed? */\n      if (args->souFit[isou][1]) \n\tqpol = souParm[isou*4+1];\n      else {\n\tPPol = args->PPol[isou] + args->dPPol[isou]*(args->freq-args->refFreq);\n\tqpol = PPol*ipol*cos(args->RLPhase[isou]);}\n      if (args->souFit[isou][2]) \n\tupol = souParm[isou*4+2];\n      else {\n\tPPol = args->PPol[isou] + args->dPPol[isou]*(args->freq-args->refFreq);\n\tupol = PPol*ipol*sin(args->RLPhase[isou]);}\n      vpol = souParm[isou*4+3];\n      /* Complex Stokes array */\n      COMPLEX_SET (S[0], ipol+vpol, 0.0);\n      COMPLEX_SET (S[1], qpol,  upol);\n      COMPLEX_SET (S[2], qpol, -upol);\n      COMPLEX_SET (S[3], ipol-vpol, 0.0);\n    }\n\n    /* Antenna parameters */\n    ia1    = args->antNo[idata*2+0];\n    ia2    = args->antNo[idata*2+1]; \n    \n    /* i = datum number */\n    /* Loop over correlations calculating derivatives */\n    for (kk=0; kk<4; kk++) {\n      isigma = wt[idata*4+kk];\n      if (kk<2) isigma *= 0.3;  /* Downweight parallel hand */\n      switch (kk) { \n\t\n      case 0:     /* RR */\n\tif (wt[idata*4+kk]>0.0) {\n\t  /* VRR = S[0] * RS[ia1] * RSc[ia2] +        \n\t           S[1] * RS[ia1] * RDc[ia2] * PA2c + \n\t\t   S[2] * RD[ia1] * RSc[ia2] * PA1  + \n\t\t   S[3] * RD[ia1] * RDc[ia2] * PA1  * PA2c; */\n\t  COMPLEX_MUL2 (MC1, RS[ia1], RSc[ia2]);\n\t  COMPLEX_MUL2 (VRR, S[0], MC1);\n\t  COMPLEX_MUL3 (MC2, RS[ia1], RDc[ia2],  PA2c);\n\t  COMPLEX_MUL2 (ct1, S[1], MC2);\n\t  COMPLEX_ADD2 (VRR, VRR,  ct1);\n\t  COMPLEX_MUL3 (MC3, RD[ia1], RSc[ia2], PA1);\n\t  COMPLEX_MUL2 (ct1, S[2], MC3);\n\t  COMPLEX_ADD2 (VRR, VRR,  ct1);\n\t  COMPLEX_MUL4 (MC4, RD[ia1], RDc[ia2], PA1, PA2c);\n\t  COMPLEX_MUL2 (ct1, S[3], MC4);\n\t  COMPLEX_ADD2 (VRR, VRR,  ct1);\n\t  modelR = VRR.real; modelI = VRR.imag;\n\t  /* Check for ellipticity in range */\n\t  if ((antParm[ia1*4+1]>maxElp) || (antParm[ia2*4+1]>maxElp)) {\n\t    /* out of range - give big residual */\n\t    residR = MAX((antParm[ia1*4+1]-maxElp),(antParm[ia2*4+1]-maxElp)) * \n\t      ipol * 100.;\n\t    residI = residR;\n\t  } else {  /* OK */\n\t    residR = modelR - data[idata*10+(kk+1)*2];\n\t    residI = modelI - data[idata*10+(kk+1)*2+1];\n\t  }\n\t  gsl_vector_set(f, i*2,   residR*isigma); /* Save function resids */\n\t  gsl_vector_set(f, i*2+1, residI*isigma); /* Save function resids */\n\t} else  residR = residI = 0.0; /* Invalid data */\n\t\n\t/* Loop over first antenna parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* wrt Or1 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* (0, 2 i) * (S[2]*MC3 + S[3]*MC4) */\n\t\tCOMPLEX_MUL2(ct1, S[2], MC3);\n\t\tCOMPLEX_MUL2(ct2, S[3], MC4);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct1, 0.0, 2.0);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ct3);\n\t\tgradR = DFDP.real;    /* RrrR wrt Or1 */\n\t\tgradI = DFDP.imag;    /* RrrI wrt Or1 */\n\t      } else gradR = gradI =0.0;     /* Invalid data */\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* wrt Er1 */\n\t    /* Fitting? */\n \t    if (antFit[ia1][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* Derivative of model wrt Er1 */\n\t\t/* part = r2 * DR[ia1] * (S[0] * RSc[ia2] + S[1] * RDc[ia2] * PA2c) -\n\t\t          r2 * SR[ia1] * PR[ia1] * (S[2] * RSc[ia2] * PA1 + S[3] * RDc[ia2] * PA1  * PA2c) */\n\t\tCOMPLEX_MUL2(ct1, S[0], RSc[ia2]);\n\t\tCOMPLEX_MUL3(ct2, S[1], RDc[ia2], PA2c);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct4, root2*DR[ia1], 0.0);\n\t\tCOMPLEX_MUL2(ct5, ct4, ct3);\n\t\tCOMPLEX_MUL3(ct1, S[2], RSc[ia2], PA1);\n\t\tCOMPLEX_MUL4(ct2, S[3], RDc[ia2], PA1, PA2c);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct4, root2*SR[ia1], 0.0);\n\t\tCOMPLEX_MUL3(ct6, ct4, PR[ia1], ct3);\n\t\tCOMPLEX_SUB (DFDP, ct5, ct6);\n\t\tgradR = DFDP.real;    /* RrrR wrt Er1 */\n\t\tgradI = DFDP.imag;    /* RrrI wrt Er1 */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* wrt OL1 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* wrt EL1 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end first antenna parameter switch */\n\t} /* end loop over first antenna parameters */\n\t\n\t/* Loop over second antenna parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* wrt Or2 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* Derivative of model wrt Or1 */\n\t\t/* (0,-2 i) * (S[1]*MC2 + S[3]*MC4) */\n\t\tCOMPLEX_MUL2(ct1, S[1], MC2);\n\t\tCOMPLEX_MUL2(ct2, S[3], MC4);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct1, 0.0, -2.0);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ct3);\n\t\tgradR = DFDP.real;    /* RrrR wrt Ol2 */\n\t\tgradI = DFDP.imag;    /* RrrI wrt Ol2 */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* wrt Er2 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* Derivative of model wrt Er1 */\n\t\t/* part = r2 * DR[ia2] * (S[0] * RS[ia1] + S[2] * RD[ia1] * PA1) -\n\t\t          r2 * SR[ia2] * PRc[ia2] * (S[1] * RS[ia1] * PA2c + S[3] * RD[ia1] * PA1  * PA2c) */\n\t\tCOMPLEX_MUL2(ct1, S[0], RS[ia1]);\n\t\tCOMPLEX_MUL3(ct2, S[2], RD[ia1], PA1);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct4, root2*DR[ia2], 0.0);\n\t\tCOMPLEX_MUL2(ct5, ct4, ct3);\n\t\tCOMPLEX_MUL3(ct1, S[1], RS[ia1], PA2c );\n\t\tCOMPLEX_MUL4(ct2, S[3], RD[ia1], PA1, PA2c);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct4, root2*SR[ia2], 0.0);\n\t\tCOMPLEX_MUL3(ct6, ct4, PRc[ia2], ct3);\n\t\tCOMPLEX_SUB (DFDP, ct5, ct6);\n\t\tgradR = DFDP.real;    /* RrrR wrt Ol2 */\n\t\tgradI = DFDP.imag;    /* RrrI wrt Ol2 */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* wrt Ol2 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* wrt El2 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end second antenna parameter switch */\n\t}  /* end loop over second antenna parameters */\n\t\n\t/* Loop over source parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* wrt IPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = RS[ia1] * RSc[ia2] + RD[ia1] * RDc[ia2] * PA1 * PA2c */\n\t\tCOMPLEX_MUL2(ct1, RS[ia1], RSc[ia2]);\n\t\tCOMPLEX_MUL4(ct2, RD[ia1], RDc[ia2], PA1, PA2c);\n\t\tCOMPLEX_ADD2(DFDP, ct1, ct2);\n\t\tgradR = DFDP.real;    /* RrrR wrt ipol */\n\t\tgradI = DFDP.imag;    /* RrrI wrt ipol */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* wrt QPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = (RS[ia1] * RDc[ia2] * PA2c + RD[ia1] * RSc[ia2] * PA1) */\n\t\tCOMPLEX_MUL3(ct1, RS[ia1], RDc[ia2], PA2c);\n\t\tCOMPLEX_MUL3(ct2, RD[ia1], RSc[ia2], PA1);\n\t\tCOMPLEX_ADD2(DFDP, ct1, ct2);\n\t\tgradR = DFDP.real;    /* RrrR wrt qpol */\n\t\tgradI = DFDP.imag;    /* RrrI wrt qpol */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* wrt UPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = i (RS[ia1] * RDc[ia2] * PA2c - RD[ia1] * RSc[ia2] * PA1) */\n\t\tCOMPLEX_MUL3(ct1, RS[ia1], RDc[ia2], PA2c);\n\t\tCOMPLEX_MUL3(ct2, RD[ia1], RSc[ia2], PA1);\n\t\tCOMPLEX_SUB (ct3, ct1, ct2);\n \t\tCOMPLEX_SET(ct4, 0.0, 1.0);\n\t\tCOMPLEX_MUL2(DFDP, ct4, ct3);\n \t\tgradR = DFDP.real;    /* RrrR wrt upol */\n\t\tgradI = DFDP.imag;    /* RrrI wrt upol */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* wrt VPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = RS[ia1] * RSc[ia2] - RD[ia1] * RDc[ia2] * PA1 * PA2c */\n\t\tCOMPLEX_MUL2(ct1, RS[ia1], RSc[ia2]);\n\t\tCOMPLEX_MUL4(ct2, RD[ia1], RDc[ia2], PA1, PA2c);\n\t\tCOMPLEX_SUB (DFDP, ct1, ct2);\n\t\tgradR = DFDP.real;    /* RrrR wrt vpol */\n\t\tgradI = DFDP.imag;    /* RrrI wrt vpol */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end source parameter switch */\n\t} /* end loop over source parameters */\n\n\t/* gradient wrt PD = 0 */\n\tif (args->doFitRL) {\n\t  gradR = gradI = 0.0;\n\t  j = args->PDPNumb;\n\t  gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t  gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t}\n\t\n\tbreak;  /* End RR */\n\t\n      case 1:     /* LL */\n\tif (wt[idata*4+kk]>0.0) {\n\t  /* VLL = S[0] * LS[ia1] * LSc[ia2] * PA1c * PA2 +\t\n\t           S[1] * LS[ia1] * LDc[ia2] * PA1c +\n\t\t   S[2] * LD[ia1] * LSc[ia2] * PA2  +\n\t\t   S[3] * LD[ia1] * LDc[ia2]; */\n\t  COMPLEX_MUL4 (MC1, LS[ia1], LSc[ia2], PA1c, PA2);\n\t  COMPLEX_MUL2 (VLL, S[0], MC1);\n\t  COMPLEX_MUL3 (MC2, LS[ia1], LDc[ia2], PA1c);\n\t  COMPLEX_MUL2 (ct1, S[1], MC2);\n\t  COMPLEX_ADD2 (VLL, VLL,  ct1);\n\t  COMPLEX_MUL3 (MC3, LD[ia1], LSc[ia2], PA2);\n\t  COMPLEX_MUL2 (ct1, S[2], MC3);\n\t  COMPLEX_ADD2 (VLL, VLL,  ct1);\n\t  COMPLEX_MUL2 (MC4, LD[ia1], LDc[ia2]);\n\t  COMPLEX_MUL2 (ct1, S[3], MC4);\n\t  COMPLEX_ADD2 (VLL, VLL,  ct1);\n\t  modelR = VLL.real; modelI = VLL.imag;\n\t  /* Check for ellipticity in range */\n\t  if ((antParm[ia1*4+3]<-maxElp) || (antParm[ia2*4+3]<-maxElp)) {\n\t    /* out of range - give big residual */\n\t    residR = MAX((maxElp-antParm[ia1*4+3]),(maxElp-antParm[ia2*4+3])) * \n\t      ipol * 100.;\n\t    residI = residR;\n\t  } else {  /* OK */\n\t    residR = modelR - data[idata*10+(kk+1)*2];\n\t    residI = modelI - data[idata*10+(kk+1)*2+1];\n\t  }\n\t  gsl_vector_set(f, i*2,   residR*isigma); /* Save function resids */\n\t  gsl_vector_set(f, i*2+1, residI*isigma); /* Save function resids */\n\t} else  residR = residI = 0.0; /* Invalid data */\n\t  \n\t/* Loop over first antenna parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* wrt OR1 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* wrt Er1 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* wrt Ol1 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* Derivative of model wrt Or1 */\n\t\t/* (0,-2 i) * (S[0]*MC1 + S[1]*MC2) */\n\t\tCOMPLEX_MUL2(ct1, S[0], MC1);\n\t\tCOMPLEX_MUL2(ct2, S[1], MC2);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct1, 0.0, -2.0);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ct3);\n\t\tgradR = DFDP.real;    /* RllR wrt Ol1 */\n\t\tgradI = DFDP.imag;    /* RllI wrt Ol1 */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* wrt El1 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* Derivative of model wrt El1 */\n\t\t/* part = r2 * DL[ia1] * PL[ia1] * (S[0] * LSc[ia2] * PA1c * PA2 + \n                                                    S[1] * LDc[ia2] * PA1c) -\n                          r2 * SL[ia1] * (S[2] * LSc[ia2] * PA2  + S[3] * LDc[ia2]) */\n\t\tCOMPLEX_MUL4(ct1, S[0], LSc[ia2], PA1c, PA2);\n\t\tCOMPLEX_MUL3(ct2, S[1], LDc[ia2], PA1c);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct4, root2*DL[ia1], 0.0);\n\t\tCOMPLEX_MUL3(ct5, ct4, PL[ia1], ct3);\n\t\tCOMPLEX_MUL3(ct1, S[2], LSc[ia2], PA2);\n\t\tCOMPLEX_MUL2(ct2, S[3], LDc[ia2]);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct4, root2*SL[ia1], 0.0);\n\t\tCOMPLEX_MUL2(ct6, ct4, ct3);\n\t\tCOMPLEX_SUB (DFDP, ct5, ct6);\n\t\tgradR = DFDP.real;    /* RllR wrt El1 */\n\t\tgradI = DFDP.imag;    /* RllI wrt El1 */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end first antenna parameter switch */\n\t} /* end loop over first antenna parameters */\n\t\n\t/* Loop over second antenna parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* wrt Or2 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* Rll wrt E2r = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* Rll wrt Ol2 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* Derivative of model wrt Ol2 */\n\t\t/* (0, 2 i) * (S[0]*MC1 + S[2]*MC3) */\n\t\tCOMPLEX_MUL2(ct1, S[0], MC1);\n\t\tCOMPLEX_MUL2(ct2, S[2], MC3);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct1, 0.0, 2.0);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ct3);\n\t\tgradR = DFDP.real;    /* RllR wrt Ol2 */\n\t\tgradI = DFDP.imag;    /* RllI wrt Ol2 */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* wrt El2  */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* Derivative of model wrt El2 */\n\t\t/* part = r2 * DL[ia2] * PLc[ia2] * (S[0] * LS[ia1] * PA1c * PA2 + \n                                                     S[2] * LD[ia1] * PA2) -\n                          r2 * SL[ia2] * (S[1] * LS[ia1] * PA1c + S[3] * LD[ia1]) */\n\t\tCOMPLEX_MUL4(ct1, S[0], LS[ia1], PA1c, PA2);\n\t\tCOMPLEX_MUL3(ct2, S[2], LD[ia1], PA2);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct4, root2*DL[ia2], 0.0);\n\t\tCOMPLEX_MUL3(ct5, ct4, PLc[ia2], ct3);\n\t\tCOMPLEX_MUL3(ct1, S[1], LS[ia1], PA1c);\n\t\tCOMPLEX_MUL2(ct2, S[3], LD[ia1]);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct4, root2*SL[ia2], 0.0);\n\t\tCOMPLEX_MUL2(ct6, ct4, ct3);\n\t\tCOMPLEX_SUB (DFDP, ct5, ct6);\n\t\tgradR = DFDP.real;    /* RllR wrt El2 */\n\t\tgradI = DFDP.imag;    /* RllI wrt El2 */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end second antenna parameter switch */\n\t} /* end loop over second antenna parameters */\n\t\n\t/* Loop over source parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* wrt IPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = LS[ia1] * LSc[ia2] * PA1c * PA2 + LD[ia1] * LDc[ia2] */\n\t\tCOMPLEX_MUL4(ct1, LS[ia1], LSc[ia2], PA1c, PA2);\n\t\tCOMPLEX_MUL2(ct2, LD[ia1], LDc[ia2]);\n\t\tCOMPLEX_ADD2(DFDP, ct1, ct2);\n\t\tgradR = DFDP.real;    /* RLLR wrt ipol */\n\t\tgradI = DFDP.imag;    /* RLLI wrt ipol */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* wrt Qpol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = (LS[ia1] * LDc[ia2] * PA1c + LD[ia1] * LSc[ia2] * PA2) */\n\t\tCOMPLEX_MUL3(ct1, LS[ia1], LDc[ia2], PA1c);\n\t\tCOMPLEX_MUL3(ct2, LD[ia1], LSc[ia2], PA2);\n\t\tCOMPLEX_ADD2(DFDP, ct1, ct2);\n\t\tgradR = DFDP.real;    /* RllR wrt qpol */\n\t\tgradI = DFDP.imag;    /* RllI wrt qpol */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* wrt UPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part =  i (LS[ia1] * LDc[ia2] * PA1c - LD[ia1] * LSc[ia2] * PA2) */\n\t\tCOMPLEX_MUL3(ct1, LS[ia1], LDc[ia2], PA1c);\n\t\tCOMPLEX_MUL3(ct2, LD[ia1], LSc[ia2], PA2);\n\t\tCOMPLEX_SUB (ct3, ct1, ct2);\n \t\tCOMPLEX_SET(ct4, 0.0, 1.0);\n\t\tCOMPLEX_MUL2(DFDP, ct4, ct3);\n\t\tgradR = DFDP.real;    /* RllR wrt upol */\n\t\tgradI = DFDP.imag;    /* RllI wrt upol */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* wrt VPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = LS[ia1] * LSc[ia2] * PA1c * PA2 - LD[ia1] * LDc[ia2] */\n\t\tCOMPLEX_MUL4(ct1, LS[ia1], LSc[ia2], PA1c, PA2);\n\t\tCOMPLEX_MUL2(ct2, LD[ia1], LDc[ia2]);\n\t\tCOMPLEX_SUB(DFDP, ct1, ct2);\n\t\tgradR = DFDP.real;    /* RllR wrt vpol */\n\t\tgradI = DFDP.imag;    /* RllI wrt vpol */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end source parameter switch */\n\t} /* end loop over source parameters */\n\n\t/* gradient wrt PD - no effect */\n\tif (args->doFitRL) {\n\t  gradR = gradI = 0.0;\n\t  j = args->PDPNumb;\n\t  gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t  gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t}\n\t\n\tbreak;  /* End LL */\n\t\n      case 2:     /* RL */\n\tif (wt[idata*4+kk]>0.0) {\n\t  /* VRL = PPRL * S[0] * RS[ia1] * LSc[ia2] * PA2 +\n\t           PPRL * S[1] * RS[ia1] * LDc[ia2] + \n\t\t   PPRL * S[2] * RD[ia1] * LSc[ia2] * PA1 * PA2 +\n\t\t   PPRL * S[3] * RD[ia1] * LDc[ia2] * PA1; */\n\t  COMPLEX_MUL4 (MC1, PPRL, RS[ia1], LSc[ia2], PA2);\n\t  COMPLEX_MUL2 (VRL, S[0], MC1);\n\t  COMPLEX_MUL3 (MC2, PPRL, RS[ia1], LDc[ia2]);\n\t  COMPLEX_MUL2 (ct1, S[1], MC2);\n\t  COMPLEX_ADD2 (VRL, VRL,  ct1);\n\t  COMPLEX_MUL5 (MC3, PPRL, RD[ia1], LSc[ia2],  PA1,  PA2);\n\t  COMPLEX_MUL2 (ct1, S[2], MC3);\n\t  COMPLEX_ADD2 (VRL, VRL,  ct1);\n\t  COMPLEX_MUL4 (MC4, PPRL, RD[ia1], LDc[ia2],  PA1);\n\t  COMPLEX_MUL2 (ct1, S[3], MC4);\n\t  COMPLEX_ADD2 (VRL, VRL,  ct1);\n\t  modelR = VRL.real; modelI = VRL.imag;\n\t  /* Check for ellipticity in range */\n\t  if ((antParm[ia1*4+1]>maxElp) || (antParm[ia2*4+3]<-maxElp)) {\n\t    /* out of range - give big residual */\n\t    residR = MAX((antParm[ia1*4+1]-maxElp),(maxElp-antParm[ia2*4+3])) * \n\t      ipol * 100.;\n\t    residI = residR;\n\t  } else {  /* OK */\n\t    residR = modelR - data[idata*10+(kk+1)*2];\n\t    residI = modelI - data[idata*10+(kk+1)*2+1];\n\t  }\n\t  gsl_vector_set(f, i*2,   residR*isigma); /* Save function resids */\n\t  gsl_vector_set(f, i*2+1, residI*isigma); /* Save function resids */\n\t} else  residR = residI = 0.0; /* Invalid data */\n\t\n\t/* Loop over first antenna parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* wrt Or1 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* (0, 2 i) * (S[2]*MC3 + S[3]*MC4) */\n\t\tCOMPLEX_MUL2(ct1, S[2], MC3);\n\t\tCOMPLEX_MUL2(ct2, S[3], MC4);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct1, 0.0,  2.0);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ct3);\n\t\t/* If ia1==refant) */\n\t\tif (ia1==refAnt) {\n\t\t  COMPLEX_MUL2(ct2, ct1, VRL);\n\t\t  COMPLEX_ADD2(DFDP, DFDP, ct2);\n\t\t}\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* wrt Er1 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = r2 * DR[ia1] * (PPRL * S[0] * LSc[ia2] * PA2 + PPRL * S[1] * LDc[ia2]) -\n                          r2 * SR[ia1] * PR[ia1] * (PPRL * S[2] * LSc[ia2] * PA1 * PA2 +\n\t\t\t                           PPRL * S[3] * LDc[ia2] * PA1) */\n\t\tCOMPLEX_MUL4(ct1, PPRL, S[0], LSc[ia2], PA2);\n\t\tCOMPLEX_MUL3(ct2, PPRL, S[1], LDc[ia2]);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct4, root2*DR[ia1], 0.0);\n\t\tCOMPLEX_MUL2(ct5, ct4, ct3);\n\t\tCOMPLEX_MUL5(ct1, PPRL, S[2], LSc[ia2], PA1, PA2);\n\t\tCOMPLEX_MUL4(ct2, PPRL, S[3], LDc[ia2], PA1);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct4, root2*SR[ia1], 0.0);\n\t\tCOMPLEX_MUL3(ct6, ct4, PR[ia1], ct3);\n\t\tCOMPLEX_SUB (DFDP, ct5, ct6);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* wrt Ol1 =0 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* wrt El1 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end first antenna parameter switch */\n\t} /* end loop over first antenna parameters */\n\t\n\t/* Loop over second antenna parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* wrt Or2 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* wrt Er2 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* wrt Ol2 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* (0, 2 i) * (S[0]*MC1 + S[2]*MC3) */\n\t\tCOMPLEX_MUL2(ct1, S[0], MC1);\n\t\tCOMPLEX_MUL2(ct2, S[2], MC3);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct1, 0.0,  2.0);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ct3);\n\t\t/* If ia2==refant) */\n\t\tif (ia2==refAnt) {\n\t\t  COMPLEX_SET (ct1, 0.0, 2.0);\n\t\t  COMPLEX_MUL2(ct2, ct1, VRL);\n\t\t  COMPLEX_ADD2(DFDP, DFDP, ct2);\n\t\t}\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* wrt El2 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = r2 * DL[ia2] * PLc[ia2] * (PPRL * S[0] * RS[ia1] * PA2 + \n                                                     PPRL * S[2] * RD[ia1] * PA1 * PA2) -\n\t\t\t  r2 * SL[ia2] * (PPRL * S[1] * RS[ia1] + PPRL * S[3] * RD[ia1] * PA1) */\n\t\tCOMPLEX_MUL4(ct1, PPRL, S[0], RS[ia1], PA2);\n\t\tCOMPLEX_MUL5(ct2, PPRL, S[2], RD[ia1], PA1, PA2);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct4, root2*DL[ia2], 0.0);\n\t\tCOMPLEX_MUL3(ct5, ct4, PLc[ia2], ct3);\n\t\tCOMPLEX_MUL3(ct1, PPRL, S[1], RS[ia1]);\n\t\tCOMPLEX_MUL4(ct2, PPRL, S[3], RD[ia1], PA1);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct4, root2*SL[ia2], 0.0);\n\t\tCOMPLEX_MUL2(ct6, ct4, ct3);\n\t\tCOMPLEX_SUB (DFDP, ct5, ct6);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end second antenna parameter switch */\n\t  } /* end loop over second antenna parameters */\n\t\n\t/* Loop over source parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* wrt IPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part =  PPRL * RS[ia1] * LSc[ia2] * PA2 + PPRL * RD[ia1] * LDc[ia2] * PA1*/\n\t\tCOMPLEX_MUL4(ct1, PPRL, RS[ia1], LSc[ia2], PA2);\n\t\tCOMPLEX_MUL4(ct2, PPRL, RD[ia1], LDc[ia2], PA1);\n\t\tCOMPLEX_ADD2(DFDP, ct1, ct2);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* wrt QPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = (PPRL * RS[ia1] * LDc[ia2] - PPRL * RD[ia1] * LSc[ia2] * PA1 * PA2) */\n\t\tCOMPLEX_MUL3(ct1, PPRL, RS[ia1], LDc[ia2]);\n\t\tCOMPLEX_MUL5(ct2, PPRL, RD[ia1], LSc[ia2], PA1, PA2);\n\t\tCOMPLEX_ADD2(DFDP, ct1, ct2);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* wrt UPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = i (PPRL * RS[ia1] * LDc[ia2] - PPRL * RD[ia1] * LSc[ia2] * PA1 * PA2) */\n\t\tCOMPLEX_MUL2(ct1, RS[ia1], LDc[ia2]);\n\t\tCOMPLEX_MUL4(ct2, RD[ia1], LSc[ia2], PA1, PA2);\n\t\tCOMPLEX_SUB(ct3, ct1, ct2);\n\t\tCOMPLEX_SET(ct4, 0.0, 1.0);\n\t\tCOMPLEX_MUL3(DFDP, ct4, PPRL, ct3);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* wrt VPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = PPRL * RS[ia1] * LSc[ia2] * PA2 - PPRL * RD[ia1] * LDc[ia2] * PA1 */\n\t\tCOMPLEX_MUL4(ct1, PPRL, RS[ia1], LSc[ia2], PA2);\n\t\tCOMPLEX_MUL4(ct2, PPRL, RD[ia1], LDc[ia2], PA1);\n\t\tCOMPLEX_SUB (DFDP, ct1, ct2);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t   } \n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end source parameter switch */\n\t} /* end loop over source parameters */\n\t\n\t/* gradient wrt PD */\n\tif (args->doFitRL) {\n\t  if (wt[idata*4+kk]>0.0) {\n\t    COMPLEX_SET(ct1, 0.0, 1.0);\n\t    COMPLEX_MUL2(DFDP, ct1, VRL);\n\t    gradR = DFDP.real;\n\t    gradI = DFDP.imag;\n\t  } else gradR = gradI = 0.0;    /* invalid data */\n\t  j = args->PDPNumb;\n\t  gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t  gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t}\n\t\n\tbreak;  /* End RL */\n\t\n      case 3:     /* LR */\n\tif (wt[idata*4+kk]>0.0) {\n\t  /* VLR = PPLR * S[0] * LS[ia1] * RSc[ia2] * PA1c +\n\t           PPLR * S[1] * LS[ia1] * RDc[ia2] * PA1c * PA2c +\n\t\t   PPLR * S[2] * LD[ia1] * RSc[ia2] +\n\t\t   PPLR * S[3] * LD[ia1] * RDc[ia2] * PA2c */\n\t  COMPLEX_MUL4 (MC1, PPLR, LS[ia1], RSc[ia2], PA1c);\n\t  COMPLEX_MUL2 (VLR, S[0], MC1);\n\t  COMPLEX_MUL5 (MC2, PPLR, LS[ia1], RDc[ia2], PA1c,  PA2c);\n\t  COMPLEX_MUL2 (ct1, S[1], MC2);\n\t  COMPLEX_ADD2 (VLR, VLR,  ct1);\n\t  COMPLEX_MUL3 (MC3, PPLR, LD[ia1], RSc[ia2]);\n\t  COMPLEX_MUL2 (ct1, S[2], MC3);\n\t  COMPLEX_ADD2 (VLR, VLR,  ct1);\n\t  COMPLEX_MUL4 (MC4, PPLR, LD[ia1], RDc[ia2], PA2c);\n\t  COMPLEX_MUL2 (ct1, S[3], MC4);\n\t  COMPLEX_ADD2 (VLR, VLR, ct1);\n\t  modelR = VLR.real; modelI = VLR.imag;\n\t  /* Check for ellipticity in range */\n\t  if ((antParm[ia1*4+3]<-maxElp) || (antParm[ia2*4+1]>maxElp)) {\n\t    /* out of range - give big residual */\n\t    residR = MAX((maxElp-antParm[ia1*4+3]),(antParm[ia2*4+1]-maxElp)) * \n\t      ipol * 100.;\n\t    residI = residR;\n\t  } else {  /* OK */\n\t    residR = modelR - data[idata*10+(kk+1)*2];\n\t    residI = modelI - data[idata*10+(kk+1)*2+1];\n\t  }\n\t  gsl_vector_set(f, i*2,   residR*isigma); /* Save function resids */\n\t  gsl_vector_set(f, i*2+1, residI*isigma); /* Save function resids */\n\t} else  residR = residI = 0.0; /* Invalid data */\n\t\n\t/* Loop over first antenna parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* wrt Or1 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* wrt Er1 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* wrt Ol1 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* (0,-2 i) * (S[0]*MC1 + S[1]*MC2) */\n\t\tCOMPLEX_MUL2(ct1, S[0], MC1);\n\t\tCOMPLEX_MUL2(ct2, S[1], MC2);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct1, 0.0, -2.0);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ct3);\n\t\t/* If ia1==refant) */\n\t\tif (ia1==refAnt) {\n\t\t  COMPLEX_MUL2(ct2, ct1, VLR);\n\t\t  COMPLEX_ADD2(DFDP, DFDP, ct2);\n\t\t}\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* wrt El1 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = r2 * DL[ia1] * PL[ia1] * (PPLR * S[0] * RSc[ia2] * PA1c + \n                                                    PPLR * S[1] * RDc[ia2] * PA1c * PA2c) -\n                          r2 * SL[ia1] * (PPLR * S[2] * RSc[ia2] + PPLR * S[3] * RDc[ia2] * PA2c) */\n\t\tCOMPLEX_MUL4(ct1, PPLR, S[0], RSc[ia2], PA1c);\n\t\tCOMPLEX_MUL5(ct2, PPLR, S[1], RDc[ia2], PA1c, PA2c);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct4, root2*DL[ia1], 0.0);\n\t\tCOMPLEX_MUL3(ct5, ct4, PL[ia1], ct3);\n\t\tCOMPLEX_MUL3(ct1, PPLR, S[2], RSc[ia2]);\n\t\tCOMPLEX_MUL4(ct2, PPLR, S[3], RDc[ia2], PA2c);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct4, root2*SL[ia1], 0.0);\n\t\tCOMPLEX_MUL2(ct6, ct4, ct3);\n\t\tCOMPLEX_SUB (DFDP, ct5, ct6);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end first antenna parameter switch */\n\t} /* end loop over first antenna parameters */\n\t\n\t/* Loop over second antenna parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* wrt Or2 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* (0,-2 i) * (S[1]*MC2 + S[3]*MC4) */\n\t\tCOMPLEX_MUL2(ct1, S[1], MC2);\n\t\tCOMPLEX_MUL2(ct2, S[3], MC4);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct1, 0.0, -2.0);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ct3);\n\t\t/* If ia2==refant */\n\t\tif (ia2==refAnt) {\n\t\t  COMPLEX_MUL2(ct2, ct1, VLR);\n\t\t  COMPLEX_ADD2(DFDP, DFDP, ct2);\n\t\t}\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* wrt Er2 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = r2 * DR[ia2] * (PPLR * S[0] * LS[ia1] * PA1c + PPLR * S[2] * LD[ia1]) -\n                          r2 * SR[ia2] * PRc[ia2] * (PPLR * S[1] * LS[ia1] * PA1c * PA2c + \n                                                     PPLR * S[3] * LD[ia1] * PA2c) */\n\t\tCOMPLEX_MUL4(ct1, PPLR, S[0], LS[ia1], PA1c);\n\t\tCOMPLEX_MUL3(ct2, PPLR, S[2], LD[ia1]);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct4, root2*DR[ia2], 0.0);\n\t\tCOMPLEX_MUL2(ct5, ct4, ct3);\n\t\tCOMPLEX_MUL5(ct1, PPLR, S[1], LS[ia1], PA1c, PA2c);\n\t\tCOMPLEX_MUL4(ct2, PPLR, S[3], LD[ia1], PA2c);\n\t\tCOMPLEX_ADD2(ct3, ct1, ct2);\n\t\tCOMPLEX_SET (ct4, root2*SR[ia2], 0.0);\n\t\tCOMPLEX_MUL3(ct6, ct4, PRc[ia2], ct3);\n\t\tCOMPLEX_SUB (DFDP, ct5, ct6);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* wrt Ol2 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* wrt El2 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end second antenna parameter switch */\n\t} /* end loop over second antenna parameters */\n\t\n\t/* Loop over source parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* wrt IPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = PPLR * LS[ia1] * RSc[ia2] * PA1c + PPLR * LD[ia1] * RDc[ia2] * PA2c */\n\t\tCOMPLEX_MUL4(ct1, PPLR, LS[ia1], RSc[ia2], PA1c);\n\t\tCOMPLEX_MUL4(ct2, PPLR, LD[ia1], RDc[ia2], PA2c);\n\t\tCOMPLEX_ADD2(DFDP, ct1, ct2);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* wrt QPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = (PPLR * LS[ia1] * RDc[ia2] * PA1c * PA2c + PPLR * LD[ia1] * RSc[ia2]) */\n\t\tCOMPLEX_MUL5(ct1, PPLR, LS[ia1], RDc[ia2], PA1c, PA2c);\n\t\tCOMPLEX_MUL3(ct2, PPLR, LD[ia1], RSc[ia2]);\n\t\tCOMPLEX_ADD2(DFDP, ct1, ct2);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* wrt UPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = i (PPLR * LS[ia1] * RDc[ia2] * PA1c * PA2c - PPLR * LD[ia1] * RSc[ia2]) */\n\t\tCOMPLEX_MUL4(ct1, LS[ia1], RDc[ia2], PA1c, PA2c);\n\t\tCOMPLEX_MUL2(ct2, LD[ia1], RSc[ia2]);\n\t\tCOMPLEX_SUB (ct3, ct1, ct2);\n\t\tCOMPLEX_SET(ct4, 0.0, 1.0);\n\t\tCOMPLEX_MUL3(DFDP, ct4, PPLR, ct3);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* wrt VPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = PPLR * LS[ia1] * RSc[ia2] * PA1c - PPLR * LD[ia1] * RDc[ia2] * PA2c */\n\t\tCOMPLEX_MUL4(ct1, PPLR, LS[ia1], RSc[ia2], PA1c);\n\t\tCOMPLEX_MUL4(ct2, PPLR, LD[ia1], RDc[ia2], PA2c);\n\t\tCOMPLEX_SUB (DFDP, ct1, ct2);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\tbreak;\n      default:\n\tbreak;\n\t  }; /* end source parameter switch */\n\t} /* end loop over source parameters */\n\t\n\t/* gradient wrt PD */\n\tif (args->doFitRL) {\n\t  if (wt[idata*4+kk]>0.0) {\n\t    COMPLEX_SET(ct1, 0.0, -1.0);\n\t    COMPLEX_MUL2(DFDP, ct1, VLR);\n\t    gradR = DFDP.real;\n\t    gradI = DFDP.imag;\n\t  } else gradR = gradI = 0.0;    /* invalid data */\n\t  j = args->PDPNumb;\n\t  gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t  gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t}\n\t/* End LR */\t\n      }; /* end switch over data correlation */\n      \n      i++;  /* Update complex datum number */\n    } /* end loop over correlations */\n  } /* End loop over visibilities */\n\n  return GSL_SUCCESS;\n} /*  end PolnFitFuncJacOERL */\n\n/**\n * Linear feed function evaluator for polarization fitting solver\n * Orientation/Ellipticity version\n * Evaluates (model-observed) / sigma\n * Function from \n * \\param x       Vector of parameters to be fitted\n *                Flux,array_of polarization_terms\n * \\param param   Function parameter structure (ObitPolnCalFit)\n * \\param f       Vector of (model-obs)/sigma for data points\n * \\return completion code GSL_SUCCESS=OK\n */\nstatic int PolnFitFuncOEXY (const gsl_vector *x, void *params, \n\t\t\t    gsl_vector *f)\n{\n  ObitPolnCalFit *args = (ObitPolnCalFit*)params;\n  ofloat *data, *wt;\n  gboolean  **antFit     = args->antFit;\n  olong     **antPNumb   = args->antPNumb;\n  odouble    *antGain    = args->antGain;\n  gboolean  **antGainFit = args->antGainFit;\n  olong     **antGainPNumb  = args->antGainPNumb;\n  odouble    *antParm    = args->antParm;\n  gboolean  **souFit     = args->souFit;\n  odouble    *souParm    = args->souParm;\n  olong     **souPNumb   = args->souPNumb;\n  dcomplex   *CX     = args->RS;\n  dcomplex   *SX     = args->RD;\n  dcomplex   *CY     = args->LS;\n  dcomplex   *SY     = args->LD;\n  dcomplex   *CXc    = args->RSc;\n  dcomplex   *SXc    = args->RDc;\n  dcomplex   *CYc    = args->LSc;\n  dcomplex   *SYc    = args->LDc;\n  ofloat PD, chi1, chi2, PPol;\n  double val;\n  odouble ipol=0.0, qpol=0.0, upol=0.0, vpol=0.0;\n  odouble residR, residI, modelR, modelI, isigma;\n  olong k, kk, iant, ia1, ia2, isou, idata;\n  olong isouLast=-999;\n  dcomplex  SPA, DPA, SPAc, DPAc, ggPD;\n  dcomplex ct1, ct2, ct5;\n  dcomplex S0[4], S[4], VXX, VXY, VYX, VYY, MC1, MC2, MC3, MC4;\n  dcomplex SM1, SM2, SM3, SM4;\n  size_t i, j;\n\n   /* Initialize output */\n  val = 0.0;\n  for (i=0; i<args->ndata; i++) {\n    gsl_vector_set(f, i, val);\n  }\n\n  COMPLEX_SET (S[0], 0.0, 0.0);  /* Initialize poln vector */\n  COMPLEX_SET (S[1], 0.0, 0.0);\n  COMPLEX_SET (S[2], 0.0, 0.0);\n  COMPLEX_SET (S[3], 0.0, 0.0);\n  COMPLEX_SET (S0[0], 0.0, 0.0);\n  COMPLEX_SET (S0[1], 0.0, 0.0);\n  COMPLEX_SET (S0[2], 0.0, 0.0);\n  COMPLEX_SET (S0[3], 0.0, 0.0);\n  COMPLEX_SET (MC1, 0.0, 0.0);  /* Other stuff */\n  COMPLEX_SET (MC2, 0.0, 0.0);\n  COMPLEX_SET (MC3, 0.0, 0.0);\n  COMPLEX_SET (MC4, 0.0, 0.0);\n  COMPLEX_SET (VXX, 0.0, 0.0);\n  COMPLEX_SET (VYY, 0.0, 0.0);\n  COMPLEX_SET (VYX, 0.0, 0.0);\n  COMPLEX_SET (VXY, 0.0, 0.0);\n  \n  /* R-L phase difference  at reference antenna */\n  if (args->doFitRL) {\n    j = args->PDPNumb;\n    PD = gsl_vector_get(x, j);\n  } else PD = args->PD;\n  \n  /* get model parameters - first antenna */\n  for (iant=0; iant<args->nant; iant++) {\n    /* Loop over antenna parameters */\n    for (k=0; k<4; k++) {\n      /* Fitting? */\n      if ((antFit[iant][k]) && (args->gotAnt[iant])) {\n\tj = antPNumb[iant][k];\n\tantParm[iant*4+k] = gsl_vector_get(x, j);\n      }\n    } /* end loop over antenna parameters */\n  } /* end loop over antennas */\n  \n  /* antenna gain */\n  for (iant=0; iant<args->nant; iant++) {\n    /* Loop over antenna gains */\n    for (k=0; k<2; k++) {\n      /* Fitting? */\n      if ((antGainFit[iant][k]) && (args->gotAnt[iant])) {\n\tj = antGainPNumb[iant][k];\n\tantGain[iant*2+k] = gsl_vector_get(x, j);\n      }\n    } /* end loop over antenna parameters */\n    /* Default X gain = 1.0/Y gain\n    if (!antGainFit[iant][0]) antGain[iant*2+0] = 1.0 / antGain[iant*2+1]; */\n   } /* end loop over antennas */\n  \n  /* now source */\n  for (isou=0; isou<args->nsou; isou++) {\n    /* Loop over source parameters */\n    for (k=0; k<4; k++) {\n      /* Fitting? */\n      if (souFit[isou][k]) {\n\tj = souPNumb[isou][k];\n\tsouParm[isou*4+k] = gsl_vector_get(x, j);\n      }\n    } /* end loop over source parameters */\n  } /* end loop over sources */\n  \n\n  /* data & wt pointers */\n  data = args->inData;\n  wt   = args->inWt;\n\n   /* Injest model, factorize into antenna components - \n     data in order Orientation R/X, Elipticity R/X, Orientation L/Y, Elipticity L/Y */\n  /* Elipticity, Orientation terms */\n  for (i=0; i<args->nant; i++) {\n    COMPLEX_EXP (ct1, -antParm[i*4+0]);\n    COMPLEX_SET (ct2, cos(G_PI*0.25+antParm[i*4+1]), 0.0);\n    COMPLEX_MUL2 (CX[i], ct1, ct2);\n    COMPLEX_EXP (ct1, antParm[i*4+0]);\n    COMPLEX_SET (ct2, sin(G_PI*0.25+antParm[i*4+1]), 0.0);\n    COMPLEX_MUL2 (SX[i], ct1, ct2);\n    COMPLEX_EXP (ct1, antParm[i*4+2]);\n    COMPLEX_SET (ct2, cos(G_PI*0.25-antParm[i*4+3]), 0.0);\n    COMPLEX_MUL2 (CY[i], ct1, ct2);\n    COMPLEX_EXP (ct1, -antParm[i*4+2]);\n    COMPLEX_SET (ct2, sin(G_PI*0.25-antParm[i*4+3]), 0.0);\n    COMPLEX_MUL2 (SY[i], ct1, ct2);\n\n    COMPLEX_CONJUGATE (CXc[i], CX[i]);\n    COMPLEX_CONJUGATE (SXc[i], SX[i]);\n    COMPLEX_CONJUGATE (CYc[i], CY[i]);\n    COMPLEX_CONJUGATE (SYc[i], SY[i]);\n  }\n\n  /* Loop over data */\n  i = 0;\n  for (idata=0; idata<args->nvis; idata++) {\n    /* Parallactic angle terms */\n    chi1  = data[idata*10+0];   /* parallactic angle ant 1 */\n    chi2  = data[idata*10+1];   /* parallactic angle ant 2 */\n    COMPLEX_EXP (SPA,(chi1+chi2));\n    COMPLEX_EXP (DPA,chi1-chi2);\n    COMPLEX_CONJUGATE (SPAc, SPA);\n    COMPLEX_CONJUGATE (DPAc, DPA);\n\n    isou  = MAX (0, args->souNo[idata]);    /* Source number */\n    /* New source? get parameters */\n    if (isou!=isouLast) {\n      isouLast = isou;\n      /* Source parameters */\n      ipol = souParm[isou*4+0];\n      /* Fitting or fixed? */\n      if (args->souFit[isou][1]) \n\tqpol = souParm[isou*4+1];\n      else {\n\tPPol = args->PPol[isou] + args->dPPol[isou]*(args->freq-args->refFreq);\n\tqpol = PPol*ipol*cos(args->RLPhase[isou]);}\n      if (args->souFit[isou][2]) \n\tupol = souParm[isou*4+2];\n      else {\n\tPPol = args->PPol[isou] + args->dPPol[isou]*(args->freq-args->refFreq);\n\tupol = PPol*ipol*sin(args->RLPhase[isou]);}\n      vpol = souParm[isou*4+3];\n       /* Complex Stokes array */\n      COMPLEX_SET (S0[0], ipol+vpol, 0.0);\n      COMPLEX_SET (S0[1], qpol,  upol);\n      COMPLEX_SET (S0[2], qpol, -upol);\n      COMPLEX_SET (S0[3], ipol-vpol, 0.0);\n    }\n\n    /* Rotate Stokes by parallactic angle */\n    COMPLEX_MUL2(S[0], DPAc, S0[0]);\n    COMPLEX_MUL2(S[1], SPAc, S0[1]);\n    COMPLEX_MUL2(S[2], SPA,  S0[2]);\n    COMPLEX_MUL2(S[3], DPA,  S0[3]);\n \n    /* Antenna parameters */\n    ia1    = args->antNo[idata*2+0];\n    ia2    = args->antNo[idata*2+1]; \n    \n    /* idata = datum number */\n    /* Loop over correlations calculating derivatives */\n    for (kk=0; kk<4; kk++) {\n      switch (kk) { \n\t\n      case 0:     /* XX */\n\tif (wt[idata*4+kk]>0.0) {\n\t  isigma = wt[idata*4+kk];\n\t  /* VXX = {S[0] * CX[ia1] * CXc[ia2]  +\n\t            S[1] * CX[ia1] * SXc[ia2]  +\n\t\t    S[2] * SX[ia1] * CXc[ia2]  + \n\t\t    S[3] * SX[ia1] * SXc[ia2]} * g1X * g2X ;\n\t  */\n\t  COMPLEX_MUL2 (MC1, CX[ia1], CXc[ia2]);\n\t  COMPLEX_MUL2 (MC2, CX[ia1], SXc[ia2]);\n\t  COMPLEX_MUL2 (MC3, SX[ia1], CXc[ia2]);\n\t  COMPLEX_MUL2 (MC4, SX[ia1], SXc[ia2]);\n\t  COMPLEX_MUL2 (SM1, S[0], MC1);\n\t  COMPLEX_MUL2 (SM2, S[1], MC2);\n\t  COMPLEX_MUL2 (SM3, S[2], MC3);\n\t  COMPLEX_MUL2 (SM4, S[3], MC4);\n\t  COMPLEX_ADD4 (ct5, SM1, SM2, SM3, SM4);\n\t  COMPLEX_SET (ggPD,  antGain[ia1*2+0]*antGain[ia2*2+0], 0);\n\t  COMPLEX_MUL2 (VXX, ct5, ggPD);\n\t  modelR = VXX.real; modelI = VXX.imag;\n\t  residR = modelR - data[idata*10+(kk+1)*2];\n\t  residI = modelI - data[idata*10+(kk+1)*2+1];\n\t  gsl_vector_set(f, i*2,   residR*isigma); /* Save function resids */\n\t  gsl_vector_set(f, i*2+1, residI*isigma); /* Save function resids */\n\t} \n\t\n\tbreak;  /* End XX */\n\t\n      case 1:     /* YY */\n\tif (wt[idata*4+kk]>0.0) {\n\t  isigma = wt[idata*4+kk];\n\t  /* VYY = {S[0] * SY[ia1] * SYc[ia2] +       \n\t            S[1] * SY[ia1] * CYc[ia2] +\n\t\t    S[2] * CY[ia1] * SYc[ia2]  + \n\t\t    S[3] * CY[ia1] * CYc[ia2]} * g1Y * g2Y ;\n\t  */\n\t  COMPLEX_MUL2 (MC1, SY[ia1], SYc[ia2]);\n\t  COMPLEX_MUL2 (MC2, SY[ia1], CYc[ia2]);\n\t  COMPLEX_MUL2 (MC3, CY[ia1], SYc[ia2]);\n\t  COMPLEX_MUL2 (MC4, CY[ia1], CYc[ia2]);\n\t  COMPLEX_MUL2 (SM1, S[0], MC1);\n\t  COMPLEX_MUL2 (SM2, S[1], MC2);\n\t  COMPLEX_MUL2 (SM3, S[2], MC3);\n\t  COMPLEX_MUL2 (SM4, S[3], MC4);\n\t  COMPLEX_ADD4 (ct5, SM1, SM2, SM3, SM4);\n\t  COMPLEX_SET (ggPD, antGain[ia1*2+1]*antGain[ia2*2+1], 0); \n\t  COMPLEX_MUL2 (VYY, ct5, ggPD);\n\t  modelR = VYY.real; modelI = VYY.imag;\n\t  residR = modelR - data[idata*10+(kk+1)*2];\n\t  residI = modelI - data[idata*10+(kk+1)*2+1];\n\t  gsl_vector_set(f, i*2,   residR*isigma); /* Save function resids */\n\t  gsl_vector_set(f, i*2+1, residI*isigma); /* Save function resids */\n\t} \n\t  \n\tbreak;  /* End YY */\n\t\n      case 2:     /* XY */\n\tif (wt[idata*4+kk]>0.0) {\n\t  isigma = wt[idata*4+kk];\n\t  /* VXY = {S[0] * CX[ia1] * SYc[ia2] +       \n\t            S[1] * CX[ia1] * CYc[ia2] +\n\t\t    S[2] * SX[ia1] * SYc[ia2]  + \n\t\t    S[3] * SX[ia1] * CYc[ia2]}} * g1X * g2Y * exp(j PD);\n\t  */\n\t  COMPLEX_MUL2 (MC1, CX[ia1], SYc[ia2]);\n\t  COMPLEX_MUL2 (MC2, CX[ia1], CYc[ia2]);\n\t  COMPLEX_MUL2 (MC3, SX[ia1], SYc[ia2]);\n\t  COMPLEX_MUL2 (MC4, SX[ia1], CYc[ia2]);\n\t  COMPLEX_MUL2 (SM1, S[0], MC1);\n\t  COMPLEX_MUL2 (SM2, S[1], MC2);\n\t  COMPLEX_MUL2 (SM3, S[2], MC3);\n\t  COMPLEX_MUL2 (SM4, S[3], MC4);\n\t  COMPLEX_ADD4 (ct5, SM1, SM2, SM3, SM4);\n\t  COMPLEX_SET (ct1,  antGain[ia1*2+0]*antGain[ia2*2+1], 0);\n\t  COMPLEX_EXP (ct2, PD);\n\t  COMPLEX_MUL2 (ggPD, ct1, ct2);\n\t  COMPLEX_MUL2 (VXY, ct5, ggPD);\n\t  modelR = VXY.real; modelI = VXY.imag;\n\t  residR = modelR - data[idata*10+(kk+1)*2];\n\t  residI = modelI - data[idata*10+(kk+1)*2+1];\n\t  gsl_vector_set(f, i*2,   residR*isigma); /* Save function resids */\n\t  gsl_vector_set(f, i*2+1, residI*isigma); /* Save function resids */\n\t} \n\t\n\tbreak;  /* End XY */\n      \t\n      case 3:     /* YX */\n\tif (wt[idata*4+kk]>0.0) {\n\t  isigma = wt[idata*4+kk];\n\t  /* VYX = {S[0] * SY[ia1] * CXc[ia2] +       \n\t            S[1] * SY[ia1] * SXc[ia2] +\n\t\t    S[2] * CY[ia1] * CXc[ia2] + \n\t\t    S[3] * CY[ia1] * SXc[ia2]} * g1Y * g2X * exp(-j PD)\n\t  */\n\t  COMPLEX_MUL2 (MC1, SY[ia1], CXc[ia2]);\n\t  COMPLEX_MUL2 (MC2, SY[ia1], SXc[ia2]);\n\t  COMPLEX_MUL2 (MC3, CY[ia1], CXc[ia2]);\n\t  COMPLEX_MUL2 (MC4, CY[ia1], SXc[ia2]);\n\t  COMPLEX_MUL2 (SM1, S[0], MC1);\n\t  COMPLEX_MUL2 (SM2, S[1], MC2);\n\t  COMPLEX_MUL2 (SM3, S[2], MC3);\n\t  COMPLEX_MUL2 (SM4, S[3], MC4);\n\t  COMPLEX_ADD4 (ct5, SM1, SM2, SM3, SM4);\n\t  COMPLEX_SET (ct1,  antGain[ia1*2+1]*antGain[ia2*2+0], 0);\n\t  COMPLEX_EXP (ct2, -PD);\n\t  COMPLEX_MUL2 (ggPD, ct1, ct2);\n\t  COMPLEX_MUL2 (VYX, ct5, ggPD);\n\t  modelR = VYX.real; modelI = VYY.imag;\n\t  residR = modelR - data[idata*10+(kk+1)*2];\n\t  residI = modelI - data[idata*10+(kk+1)*2+1];\n\t  gsl_vector_set(f, i*2,   residR*isigma); /* Save function resids */\n\t  gsl_vector_set(f, i*2+1, residI*isigma); /* Save function resids */\n\t} \n\t\t\n\tbreak;  /* End YX */\n\t\n      default:\n\t  break;\n\t}; /* end switch over data correlation */\n      \n      i++;  /* Update complex datum number */\n    } /* end loop over correlations */\n  } /* End loop over visibilities */\n\n  return GSL_SUCCESS;\n} /*  end PolnFitFuncOEXY */\n\n/**\n * Linear feed Jacobian evaluator for polarization fitting solver\n * Orientation/Ellipticity version\n * Evaluates partial derivatives of model wrt each parameter\n * \\param x       Vector of parameters to be fitted\n *                Flux,array_of polarization_terms\n * \\param param   Function parameter structure (ObitPolnCalFit)\n * \\param J       Jacobian matrix J[data_point, parameter]\n * \\return completion code GSL_SUCCESS=OK\n */\nstatic int PolnFitJacOEXY (const gsl_vector *x, void *params, \n\t\t\t   gsl_matrix *J)\n{\n  ObitPolnCalFit *args = (ObitPolnCalFit*)params;\n  ofloat *data, *wt;\n  gboolean  **antFit     = args->antFit;\n  olong     **antPNumb   = args->antPNumb;\n  odouble    *antParm    = args->antParm;\n  odouble    *antGain    = args->antGain;\n  gboolean  **antGainFit = args->antGainFit;\n  olong     **antGainPNumb  = args->antGainPNumb;\n  gboolean  **souFit     = args->souFit;\n  odouble    *souParm    = args->souParm;\n  olong     **souPNumb   = args->souPNumb;\n  dcomplex   *CX     = args->RS;\n  dcomplex   *SX     = args->RD;\n  dcomplex   *CY     = args->LS;\n  dcomplex   *SY     = args->LD;\n  dcomplex   *CXc    = args->RSc;\n  dcomplex   *SXc    = args->RDc;\n  dcomplex   *CYc    = args->LSc;\n  dcomplex   *SYc    = args->LDc;\n  ofloat PD, chi1, chi2, PPol;\n  double val;\n  odouble ipol=0.0, qpol=0.0, upol=0.0, vpol=0.0;\n  odouble gradR=0.0, gradI=0.0, isigma=0.0;\n  olong k, kk, iant, ia1, ia2, isou, idata;\n  olong isouLast=-999;\n  dcomplex  SPA, DPA, SPAc, DPAc, ggPD;\n  dcomplex ct1, ct2, ct3, ct4, ct5, Jm, Jp;\n  dcomplex S0[4], S[4], VXX, VXY, VYX, VYY, MC1, MC2, MC3, MC4, DFDP;\n  dcomplex SM1, SM2, SM3, SM4;\n  size_t i, j;\n\n   /* Initialize output */\n  val = 0.0;\n  for (i=0; i<args->ndata; i++) {\n    for (j=0; j<args->nparam; j++) gsl_matrix_set(J, i, j, val);\n  }\n\n  COMPLEX_SET (S[0], 0.0, 0.0);  /* Initialize poln vector */\n  COMPLEX_SET (S[1], 0.0, 0.0);\n  COMPLEX_SET (S[2], 0.0, 0.0);\n  COMPLEX_SET (S[3], 0.0, 0.0);\n  COMPLEX_SET (S0[0], 0.0, 0.0);\n  COMPLEX_SET (S0[1], 0.0, 0.0);\n  COMPLEX_SET (S0[2], 0.0, 0.0);\n  COMPLEX_SET (S0[3], 0.0, 0.0);\n  COMPLEX_SET (MC1, 0.0, 0.0);  /* Other stuff */\n  COMPLEX_SET (MC2, 0.0, 0.0);\n  COMPLEX_SET (MC3, 0.0, 0.0);\n  COMPLEX_SET (MC4, 0.0, 0.0);\n  COMPLEX_SET (VXX, 0.0, 0.0);\n  COMPLEX_SET (VYY, 0.0, 0.0);\n  COMPLEX_SET (VYX, 0.0, 0.0);\n  COMPLEX_SET (VXY, 0.0, 0.0);\n  COMPLEX_SET (Jm,  0.0,-1.0);\n  COMPLEX_SET (Jp,  0.0, 1.0);\n  COMPLEX_SET (SM1, 0.0, 0.0);\n  COMPLEX_SET (SM2, 0.0, 0.0);\n  COMPLEX_SET (SM3, 0.0, 0.0);\n  COMPLEX_SET (SM4, 0.0, 0.0);\n  COMPLEX_SET (ggPD, 0.0, 0.0);\n  \n  /* R-L phase difference  at reference antenna */\n  if (args->doFitRL) {\n    j = args->PDPNumb;\n    PD = gsl_vector_get(x, j);\n  } else PD = args->PD;\n  \n  /* get model parameters - first antenna */\n  for (iant=0; iant<args->nant; iant++) {\n    /* Loop over antenna parameters */\n    for (k=0; k<4; k++) {\n      /* Fitting? */\n      if ((antFit[iant][k]) && (args->gotAnt[iant])) {\n\tj = antPNumb[iant][k];\n\tantParm[iant*4+k] = gsl_vector_get(x, j);\n      }\n    } /* end loop over antenna parameters */\n  } /* end loop over antennas */\n  \n  /* antenna gain */\n  for (iant=0; iant<args->nant; iant++) {\n    /* Loop over antenna gains */\n    for (k=0; k<2; k++) {\n      /* Fitting? */\n      if ((antGainFit[iant][k]) && (args->gotAnt[iant])) {\n\tj = antGainPNumb[iant][k];\n\tantGain[iant*2+k] = gsl_vector_get(x, j);\n      }\n    } /* end loop over antenna parameters */\n    /* Default X gain = 1.0/Y gain\n    if (!antGainFit[iant][0]) antGain[iant*2+0] = 1.0 / antGain[iant*2+1]; */\n  } /* end loop over antennas */\n  \n  /* now source */\n  for (isou=0; isou<args->nsou; isou++) {\n    /* Loop over source parameters */\n    for (k=0; k<4; k++) {\n      /* Fitting? */\n      if (souFit[isou][k]) {\n\tj = souPNumb[isou][k];\n\tsouParm[isou*4+k] = gsl_vector_get(x, j);\n      }\n    } /* end loop over source parameters */\n  } /* end loop over sources */\n  \n  /* data & wt pointers */\n  data = args->inData;\n  wt   = args->inWt;\n\n   /* Injest model, factorize into antenna components - \n     data in order Orientation R/X, Elipticity R/X, Orientation L/Y, Elipticity L/Y */\n  /* Elipticity, Orientation terms */\n  for (i=0; i<args->nant; i++) {\n    COMPLEX_EXP (ct1, -antParm[i*4+0]);\n    COMPLEX_SET (ct2, cos(G_PI*0.25+antParm[i*4+1]), 0.0);\n    COMPLEX_MUL2 (CX[i], ct1, ct2);\n    COMPLEX_EXP (ct1, antParm[i*4+0]);\n    COMPLEX_SET (ct2, sin(G_PI*0.25+antParm[i*4+1]), 0.0);\n    COMPLEX_MUL2 (SX[i], ct1, ct2);\n    COMPLEX_EXP (ct1, antParm[i*4+2]);\n    COMPLEX_SET (ct2, cos(G_PI*0.25-antParm[i*4+3]), 0.0);\n    COMPLEX_MUL2 (CY[i], ct1, ct2);\n    COMPLEX_EXP (ct1, -antParm[i*4+2]);\n    COMPLEX_SET (ct2, sin(G_PI*0.25-antParm[i*4+3]), 0.0);\n    COMPLEX_MUL2 (SY[i], ct1, ct2);\n\n    COMPLEX_CONJUGATE (CXc[i], CX[i]);\n    COMPLEX_CONJUGATE (SXc[i], SX[i]);\n    COMPLEX_CONJUGATE (CYc[i], CY[i]);\n    COMPLEX_CONJUGATE (SYc[i], SY[i]);\n  }\n\n  /* Loop over data */\n  i = 0;\n  for (idata=0; idata<args->nvis; idata++) {\n    /* Parallactic angle terms */\n    chi1  = data[idata*10+0];   /* parallactic angle ant 1 */\n    chi2  = data[idata*10+1];   /* parallactic angle ant 2 */\n    COMPLEX_EXP (SPA,(chi1+chi2));\n    COMPLEX_EXP (DPA,chi1-chi2);\n    COMPLEX_CONJUGATE (SPAc, SPA);\n    COMPLEX_CONJUGATE (DPAc, DPA);\n\n    isou  = MAX (0, args->souNo[idata]);    /* Source number */\n    /* New source? get parameters */\n    if (isou!=isouLast) {\n      isouLast = isou;\n      /* Source parameters */\n      ipol = souParm[isou*4+0];\n      /* Fitting or fixed? */\n      if (args->souFit[isou][1]) \n\tqpol = souParm[isou*4+1];\n      else {\n\tPPol = args->PPol[isou] + args->dPPol[isou]*(args->freq-args->refFreq);\n\tqpol = PPol*ipol*cos(args->RLPhase[isou]);}\n      if (args->souFit[isou][2]) \n\tupol = souParm[isou*4+2];\n      else {\n\tPPol = args->PPol[isou] + args->dPPol[isou]*(args->freq-args->refFreq);\n\tupol = PPol*ipol*sin(args->RLPhase[isou]);}\n      vpol = souParm[isou*4+3];\n       /* Complex Stokes array */\n      COMPLEX_SET (S0[0], ipol+vpol, 0.0);\n      COMPLEX_SET (S0[1], qpol,  upol);\n      COMPLEX_SET (S0[2], qpol, -upol);\n      COMPLEX_SET (S0[3], ipol-vpol, 0.0);\n    }\n\n    /* Rotate Stokes by parallactic angle */\n    COMPLEX_MUL2(S[0], DPAc, S0[0]);\n    COMPLEX_MUL2(S[1], SPAc, S0[1]);\n    COMPLEX_MUL2(S[2], SPA,  S0[2]);\n    COMPLEX_MUL2(S[3], DPA,  S0[3]);\n  \n    /* Antenna parameters */\n    ia1    = args->antNo[idata*2+0];\n    ia2    = args->antNo[idata*2+1]; \n    \n    /* i = datum number */\n    /* Loop over correlations calculating derivatives */\n    for (kk=0; kk<4; kk++) {\n      switch (kk) { \n\t\n      case 0:     /* XX */\n\tif (wt[idata*4+kk]>0.0) {\n\t  isigma = wt[idata*4+kk];\n\t  /* VXX = {S[0] * CX[ia1] * CXc[ia2]  +\n\t            S[1] * CX[ia1] * SXc[ia2]  +\n\t\t    S[2] * SX[ia1] * CXc[ia2]  + \n\t\t    S[3] * SX[ia1] * SXc[ia2]} * g1X * g2X ;\n\t  */\n\t  COMPLEX_MUL2 (MC1, CX[ia1], CXc[ia2]);\n\t  COMPLEX_MUL2 (MC2, CX[ia1], SXc[ia2]);\n\t  COMPLEX_MUL2 (MC3, SX[ia1], CXc[ia2]);\n\t  COMPLEX_MUL2 (MC4, SX[ia1], SXc[ia2]);\n\t  COMPLEX_MUL2 (SM1, S[0], MC1);\n\t  COMPLEX_MUL2 (SM2, S[1], MC2);\n\t  COMPLEX_MUL2 (SM3, S[2], MC3);\n\t  COMPLEX_MUL2 (SM4, S[3], MC4);\n\t  COMPLEX_ADD4 (ct5, SM1, SM2, SM3, SM4);\n\t  COMPLEX_SET (ggPD,  antGain[ia1*2+0]*antGain[ia2*2+0], 0);\n\t  COMPLEX_MUL2 (VXX, ct5, ggPD);\n\t}\n\t\n\t/* Loop over first antenna parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* XX wrt Ox1 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* {(0, -1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + \n\t\t    (0,  1) * S[2] * MC3 + (0,  1) * S[3] * MC4}  * gX[ia1] * gX[ia2]  */\n\t\tCOMPLEX_ADD2 (ct1, SM1, SM2);\n\t\tCOMPLEX_MUL2 (ct2, Jm, ct1);\n\t\tCOMPLEX_ADD2 (ct1, SM3, SM4);\n\t\tCOMPLEX_MUL2 (ct3, Jp, ct1);\n\t\tCOMPLEX_ADD2 (ct2, ct2, ct3);\n\t\tCOMPLEX_MUL2 (DFDP, ct2, ggPD);\n\t\tgradR = DFDP.real;    /* RxxR wrt Ox1 */\n\t\tgradI = DFDP.imag;    /* RxxI wrt Ox1 */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI =0.0;     /* Invalid data */\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* XX wrt Ex1 */\n\t    /* Fitting? */\n \t    if (antFit[ia1][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = {-S[0] * CXc[ia2] * SXc[ia1] -\n\t\t            S[1] * SXc[ia2] * SXc[ia1] +\n\t\t\t    S[2] * CXc[ia2] * CXc[ia1] +\t       \n\t\t\t    S[3] * SXc[ia2] * CXc[ia1]}  * gX[ia1] * gX[ia2]  */\n\t\tCOMPLEX_MUL3(ct5, S[0], CXc[ia2], SXc[ia1]);\n\t\tCOMPLEX_NEGATE(ct1, ct5);\n\t\tCOMPLEX_MUL3(ct5, S[1], SXc[ia2], SXc[ia1]);\n\t\tCOMPLEX_NEGATE(ct2, ct5);\n\t\tCOMPLEX_MUL3(ct3, S[2], CXc[ia2], SXc[ia1]);\n\t\tCOMPLEX_MUL3(ct4, S[3], SXc[ia2], CXc[ia1]);\n\t\tCOMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4);\n\t\tCOMPLEX_MUL2(DFDP, ct5, ggPD);\n\t\tgradR = DFDP.real;    /* RxxR wrt Ex1 */\n\t\tgradI = DFDP.imag;    /* RxxI wrt Ex1 */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* XX wrt OY1 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* XX wrt EY1 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end first antenna parameter switch */\n\t} /* end loop over first antenna parameters */\n\t\n\t/* Loop over second antenna parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* XX wrt Ox2 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* {(0,  1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + \n\t\t    (0,  1) * S[2] * MC3 + (0, -1) * S[3] * MC4}  * gX[ia1] * gX[ia2]   */\n\t\tCOMPLEX_ADD2 (ct1, SM1, SM3);\n\t\tCOMPLEX_MUL2 (ct2, Jp, ct1);\n\t\tCOMPLEX_ADD2 (ct1, SM2, SM4);\n\t\tCOMPLEX_MUL2 (ct3, Jm, ct1);\n\t\tCOMPLEX_ADD2 (ct2, ct2, ct3);\n\t\tCOMPLEX_MUL2 (DFDP, ct2, ggPD);\n\t\tgradR = DFDP.real;    /* RxxR wrt Ox2 */\n\t\tgradI = DFDP.imag;    /* RxxI wrt Ox2 */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* XX wrt Ex2 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = {-S[0] * CX[ia1] * SX[ia2] +\n\t\t            S[1] * CX[ia1] * CX[ia2] -\n\t\t\t    S[2] * SX[ia1] * SX[ia2] +\n\t\t\t    S[3] * SX[ia1] * CX[ia2]} * gX[ia1] * gX[ia2]  */\n\t\tCOMPLEX_MUL3(ct5, S[0], CX[ia1], SX[ia2]);\n\t\tCOMPLEX_NEGATE(ct1, ct5);\n\t\tCOMPLEX_MUL3(ct2, S[1], CX[ia1], CX[ia2]);\n\t\tCOMPLEX_MUL3(ct5, S[2], SX[ia1], SX[ia2]);\n\t\tCOMPLEX_NEGATE(ct3, ct5);\n\t\tCOMPLEX_MUL3(ct4, S[3], SX[ia1], CX[ia2]);\n\t\tCOMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4);\n\t\tCOMPLEX_MUL2(DFDP, ct5, ggPD);\n\t\tgradR = DFDP.real;    /* RxxR wrt Ox2 */\n\t\tgradI = DFDP.imag;    /* RxxI wrt Ox2 */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* XX wrt Oy2 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* XX wrt Ey2 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */\n\t    }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end second antenna parameter switch */\n\t}  /* end loop over second antenna parameters */\n\t\n\t/* Loop over source parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* XX wrt IPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part =   (MC1*DPAc + MC4*DPA) * gX[ia1] * gX[ia2] */\n\t\tCOMPLEX_MUL2(ct2, MC1, DPAc);\n\t\tCOMPLEX_MUL2(ct3, MC4, DPA);\n\t\tCOMPLEX_ADD2(ct1, ct2, ct3);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ggPD);\n\t\tgradR = DFDP.real;    /* RxxR wrt ipol */\n\t\tgradI = DFDP.imag;    /* RxxI wrt ipol */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* XX wrt QPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = (MC2*SPAc + MC3*SPA) * gX[ia1] * gX[ia2] */\n\t\tCOMPLEX_MUL2(ct2, MC2, SPAc);\n\t\tCOMPLEX_MUL2(ct3, MC3, SPA);\n\t\tCOMPLEX_ADD2(ct1, ct2, ct3);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ggPD);\n\t\tgradR = DFDP.real;    /* RxxR wrt qpol */\n\t\tgradI = DFDP.imag;    /* RxxI wrt qpol */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* XX wrt UPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* (j MC2*SPAc - j MC3*SPA) * gX[ia1] * gX[ia2] */\n\t\tCOMPLEX_MUL3(ct2, Jp, MC2, SPAc);\n\t\tCOMPLEX_MUL3(ct3, Jp, MC3, SPA);\n\t\tCOMPLEX_SUB(ct1, ct2, ct3);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ggPD);\n \t\tgradR = DFDP.real;    /* RxxR wrt upol */\n\t\tgradI = DFDP.imag;    /* RxxI wrt upol */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* XX wrt VPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* (MC1*DPAc - MC4*DPA) * gX[ia1] * gX[ia2] */\n\t\tCOMPLEX_MUL2(ct2, MC1, DPAc);\n\t\tCOMPLEX_MUL2(ct3, MC4, DPA);\n\t\tCOMPLEX_SUB(ct1, ct2, ct3);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ggPD);\n\t\tgradR = DFDP.real;    /* RxxR wrt vpol */\n\t\tgradI = DFDP.imag;    /* RxxI wrt vpol */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end source parameter switch */\n\t} /* end loop over source parameters */\n\n\t/* gradient wrt PD = 0 */\n\tif (args->doFitRL) {\n\t  gradR = gradI = 0.0;\n\t  j = args->PDPNumb;\n\t  gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t  gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t}\n\n\t/* Loop over antenna gains */\n\tfor (k=0; k<2; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* XX wrt gX1 */\n\t    /* Fitting? */\n\t    if (antGainFit[ia1][0]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = (S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) * gX[ia2] */\n\t\tCOMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4);\n\t\tCOMPLEX_SET (ct2, antGain[ia2*2+0], 0);\n\t\tCOMPLEX_MUL2 (DFDP, ct1, ct2);\n\t\tgradR = DFDP.real;    /* RxxR wrt gX1 */\n\t\tgradI = DFDP.imag;    /* RxxI wrt gX1 */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = antGainPNumb[ia1][0];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t      }\n\t    break;\n\t  case 1:  /* XX wrt gX2 */\n\t    if (antGainFit[ia2][0]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = (S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) * gX[ia1] */\n\t\tCOMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4);\n\t\tCOMPLEX_SET (ct2, antGain[ia1*2+0], 0);\n\t\tCOMPLEX_MUL2 (DFDP, ct1, ct2);\n\t\tgradR = DFDP.real;    /* RxxR wrt gX2 */\n\t\tgradI = DFDP.imag;    /* RxxI wrt gX2 */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = antGainPNumb[ia2][0];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t      }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end gain switch */\n\t} /* end loop over gains */\n\tbreak;  /* End XX */\n\t\n      case 1:     /* YY */\n\tif (wt[idata*4+kk]>0.0) {\n\t  isigma = wt[idata*4+kk];\n\t  /* VYY = {S[0] * SY[ia1] * SYc[ia2] +       \n\t            S[1] * SY[ia1] * CYc[ia2] +\n\t\t    S[2] * CY[ia1] * SYc[ia2] + \n\t\t    S[3] * CY[ia1] * CYc[ia2]} * g1Y * g2Y ;\n\t  */\n\t  COMPLEX_MUL2 (MC1, SY[ia1], SYc[ia2]);\n\t  COMPLEX_MUL2 (MC2, SY[ia1], CYc[ia2]);\n\t  COMPLEX_MUL2 (MC3, CY[ia1], SYc[ia2]);\n\t  COMPLEX_MUL2 (MC4, CY[ia1], CYc[ia2]);\n\t  COMPLEX_MUL2 (SM1, S[0], MC1);\n\t  COMPLEX_MUL2 (SM2, S[1], MC2);\n\t  COMPLEX_MUL2 (SM3, S[2], MC3);\n\t  COMPLEX_MUL2 (SM4, S[3], MC4);\n\t  COMPLEX_ADD4 (ct5, SM1, SM2, SM3, SM4);\n\t  COMPLEX_SET (ggPD,  antGain[ia1*2+1]*antGain[ia2*2+1], 0);\n\t  COMPLEX_MUL2 (VYY, ct5, ggPD);\n\t} \n\t  \n\t/* Loop over first antenna parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* YY wrt Ox1 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* YY wrt Ex1 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* YY wrt Oy1 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = {(0, -1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + \n\t\t           (0,  1) * S[2] * MC2 + (0,  1) * S[3] * MC4} * gY[ia1] * gY[ia2] */\n\t\tCOMPLEX_ADD2 (ct1, SM1, SM2);\n\t\tCOMPLEX_MUL2 (ct2, Jm, ct1);\n\t\tCOMPLEX_ADD2 (ct1, SM3, SM4);\n\t\tCOMPLEX_MUL2 (ct3, Jp, ct1);\n\t\tCOMPLEX_ADD2 (ct2, ct2, ct3);\n\t\tCOMPLEX_MUL2 (DFDP, ct2, ggPD);\n\t\tgradR = DFDP.real;    /* RyyR wrt Oy2 */\n\t\tgradI = DFDP.imag;    /* RyyI wrt Oy2 */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* YY wrt Ey1 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = {-S[0] * SYc[ia2] * CYc[ia1] -\n                            S[1] * CYc[ia2] * CYc[ia1] +\n\t\t\t    S[2] * SYc[ia2] * SYc[ia1] +\t       \n\t\t\t    S[3] * CYc[ia2] * SYc[ia1]}  * gX[ia1] * gX[ia2]  */\n\t\tCOMPLEX_MUL3(ct5, S[0], SYc[ia2], CYc[ia1]);\n\t\tCOMPLEX_NEGATE(ct1, ct5);\n\t\tCOMPLEX_MUL3(ct5, S[1], CYc[ia2], CYc[ia1]);\n\t\tCOMPLEX_NEGATE(ct2, ct5);\n\t\tCOMPLEX_MUL3(ct3, S[2], SYc[ia2], SYc[ia1]);\n\t\tCOMPLEX_MUL3(ct4, S[3], CYc[ia2], SYc[ia1]);\n\t\tCOMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4);\n\t\tCOMPLEX_MUL2(DFDP, ct5, ggPD);\n\t\tgradR = DFDP.real;    /* RyyR wrt Ey1 */\n\t\tgradI = DFDP.imag;    /* RyyI wrt Ey1 */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t    }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end first antenna parameter switch */\n\t} /* end loop over first antenna parameters */\n\t\n\t/* Loop over second antenna parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* YY wrt Ox2 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* YY wrt Ex2 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* YY wrt Oy2 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = {(0,  1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + \n\t\t           (0,  1) * S[2] * MC3 + (0, -1) * S[3] * MC4} * gY[ia1] * gY[ia2]  */\n\t\tCOMPLEX_ADD2 (ct1, SM1, SM3);\n\t\tCOMPLEX_MUL2 (ct2, Jp, ct1);\n\t\tCOMPLEX_ADD2 (ct1, SM2, SM4);\n\t\tCOMPLEX_MUL2 (ct3, Jm, ct1);\n\t\tCOMPLEX_ADD2 (ct2, ct2, ct3);\n\t\tCOMPLEX_MUL2 (DFDP,  ct2, ggPD);\n\t\tgradR = DFDP.real;    /* RyyR wrt Oy2 */\n\t\tgradI = DFDP.imag;    /* RyyI wrt Oy2 */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* YY wrt Ey2  */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = {-S[0] * SY[ia1] * CY[ia2] + \n                            S[1] * SY[ia1] * SY[ia2] -\n\t\t\t    S[2] * CY[ia1] * CY[ia2]  + \n\t\t\t    S[3] * CY[ia1] * SY[ia2]} * gY[ia1] * gY[ia2] */\n\t\tCOMPLEX_MUL3(ct5, S[0], SY[ia1], CY[ia2]);\n\t\tCOMPLEX_NEGATE(ct1, ct5);\n\t\tCOMPLEX_MUL3(ct2, S[1], SY[ia1], SY[ia2]);\n\t\tCOMPLEX_MUL3(ct5, S[2], CY[ia1], CY[ia2]);\n\t\tCOMPLEX_NEGATE(ct3, ct5);\n\t\tCOMPLEX_MUL3(ct4, S[3], CY[ia1], SY[ia2]);\n\t\tCOMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4);\n\t\tCOMPLEX_MUL2(DFDP, ct5, ggPD);\n\t\tgradR = DFDP.real;    /* RyyR wrt Ey2 */\n\t\tgradI = DFDP.imag;    /* RyyI wrt Ey2 */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end second antenna parameter switch */\n\t} /* end loop over second antenna parameters */\n\t\n\t/* Loop over source parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* YY wrt IPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part =   (MC1*DPAc + MC4*DPA) * gX[ia1] * gX[ia2] */\n\t\tCOMPLEX_MUL2(ct2, MC1, DPAc);\n\t\tCOMPLEX_MUL2(ct3, MC4, DPA);\n\t\tCOMPLEX_ADD2(ct1, ct2, ct3);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ggPD);\n\t\tgradR = DFDP.real;    /* RyyR wrt ipol */\n\t\tgradI = DFDP.imag;    /* RyyI wrt ipol */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* YY wrt Qpol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = (MC2*SPAc + MC3*SPA) * gX[ia1] * gX[ia2] */\n\t\tCOMPLEX_MUL2(ct2, MC2, SPAc);\n\t\tCOMPLEX_MUL2(ct3, MC3, SPA);\n\t\tCOMPLEX_ADD2(ct1, ct2, ct3);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ggPD);\n\t\tgradR = DFDP.real;    /* RyyR wrt qpol */\n\t\tgradI = DFDP.imag;    /* RyyI wrt qpol */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* YY wrt UPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* (j MC2*SPAc - j MC3*SPA) * gX[ia1] * gX[ia2] */\n\t\tCOMPLEX_MUL3(ct2, Jp, MC2, SPAc);\n\t\tCOMPLEX_MUL3(ct3, Jp, MC3, SPA);\n\t\tCOMPLEX_SUB(ct1, ct2, ct3);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ggPD);\n\t\tgradR = DFDP.real;    /* RyyR wrt upol */\n\t\tgradI = DFDP.imag;    /* RyyI wrt upol */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* YY wrt VPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* (MC1*DPAc - MC4*DPA) * gX[ia1] * gX[ia2] */\n\t\tCOMPLEX_MUL2(ct2, MC1, DPAc);\n\t\tCOMPLEX_MUL2(ct3, MC4, DPA);\n\t\tCOMPLEX_SUB(ct1, ct2, ct3);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ggPD);\n\t\tgradR = DFDP.real;    /* RyyR wrt vpol */\n\t\tgradI = DFDP.imag;    /* RyyI wrt vpol */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end source parameter switch */\n\t} /* end loop over source parameters */\n\n\t/* gradient wrt PD - no effect */\n\tif (args->doFitRL) {\n\t  gradR = gradI = 0.0;\n\t  j = args->PDPNumb;\n\t  gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t  gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t}\n\n\t/* Loop over antenna gains */\n\tfor (k=0; k<2; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* YY wrt gY1 */\n\t    /* Fitting? */\n\t    if (antGainFit[ia1][1]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = (S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) * gY[ia2] */\n\t\tCOMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4);\n\t\tCOMPLEX_SET (ct2, antGain[ia2*2+1], 0);\n\t\tCOMPLEX_MUL2 (DFDP, ct1, ct2);\n\t\tgradR = DFDP.real;    /* RyyR wrt gY1 */\n\t\tgradI = DFDP.imag;    /* RyyI wrt gY1 */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = antGainPNumb[ia1][1];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t      }\n\t    break;\n\t  case 1:  /* YY wrt gY2 */\n\t    if (antGainFit[ia2][1]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = (S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) * gY[ia1] */\n\t\tCOMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4);\n\t\tCOMPLEX_SET (ct2, antGain[ia1*2+0], 1);\n\t\tCOMPLEX_MUL2 (DFDP, ct1, ct2);\n\t\tgradR = DFDP.real;    /* RyyR wrt gY2 */\n\t\tgradI = DFDP.imag;    /* RyyI wrt gY2 */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = antGainPNumb[ia2][1];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t      }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end gain switch */\n\t} /* end loop over gains */\n\t\n\tbreak;  /* End YY */\n\t\n      case 2:     /* XY */\n\tif (wt[idata*4+kk]>0.0) {\n\t  isigma = wt[idata*4+kk];\n\t  /* VXY = {S[0] * CX[ia1] * SYc[ia2] +       \n\t            S[1] * CX[ia1] * CYc[ia2] +\n\t\t    S[2] * SX[ia1] * SYc[ia2] + \n\t\t    S[3] * SX[ia1] * CYc[ia2]}} * g1X * g2Y * exp(j PD);\n\t  */\n\t  COMPLEX_MUL2 (MC1, CX[ia1], SYc[ia2]);\n\t  COMPLEX_MUL2 (MC2, CX[ia1], CYc[ia2]);\n\t  COMPLEX_MUL2 (MC3, SX[ia1], SYc[ia2]);\n\t  COMPLEX_MUL2 (MC4, SX[ia1], CYc[ia2]);\n\t  COMPLEX_MUL2 (SM1, S[0], MC1);\n\t  COMPLEX_MUL2 (SM2, S[1], MC2);\n\t  COMPLEX_MUL2 (SM3, S[2], MC3);\n\t  COMPLEX_MUL2 (SM4, S[3], MC4);\n\t  COMPLEX_ADD4 (ct5, SM1, SM2, SM3, SM4);\n\t  COMPLEX_SET (ct1,  antGain[ia1*2+0]*antGain[ia2*2+1], 0);\n\t  COMPLEX_EXP (ct2, PD);\n\t  COMPLEX_MUL2 (ggPD, ct1, ct2);\n\t  COMPLEX_MUL2 (VXY, ct5, ggPD);\n\t} \n\t\n\t/* Loop over first antenna parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* XY wrt Ox1 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = {(0, -1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + \n\t\t           (0,  1) * S[2] * MC3 + (0,  1) * S[3] * MC4} *\n\t\t\t   gX[ia1] * gY[ia2] * exp(j PD) */\n\t\tCOMPLEX_ADD2 (ct1, SM1, SM2);\n\t\tCOMPLEX_MUL2 (ct2, Jm, ct1);\n\t\tCOMPLEX_ADD2 (ct1, SM3, SM4);\n\t\tCOMPLEX_MUL2 (ct3, Jp, ct1);\n\t\tCOMPLEX_ADD2 (ct2, ct2, ct3);\n\t\tCOMPLEX_MUL2 (DFDP, ct2, ggPD);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* XY wrt Ex1 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part =  {-S[0] * SYc[ia2] * SXc[ia1]  - \n\t\t   S[1] * CYc[ia2] * SXc[ia1]  +\n\t\t   S[2] * SYc[ia2] * CXc[ia1]  + \n\t\t   S[3] * CYc[ia2] * CXc[ia1]  } * \n\t\t            gX[ia1] * gY[ia2] * exp(j PD) */\n\t\tCOMPLEX_MUL3(ct5, S[0], SYc[ia2], SXc[ia1]);\n\t\tCOMPLEX_NEGATE(ct1, ct5);\n\t\tCOMPLEX_MUL3(ct5, S[1], CYc[ia2], SXc[ia1]);\n\t\tCOMPLEX_NEGATE(ct2, ct5);\n\t\tCOMPLEX_MUL3(ct3, S[2], SYc[ia2], CXc[ia1]);\n\t\tCOMPLEX_MUL3(ct4, S[3], CYc[ia2], CXc[ia1]);\n\t\tCOMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4);\n\t\tCOMPLEX_MUL2(DFDP, ct5, ggPD);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* XY wrt Oy1 =0 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* XY wrt Ey1 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end first antenna parameter switch */\n\t} /* end loop over first antenna parameters */\n\t\n\t/* Loop over second antenna parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* XY wrt Ox2 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* XY wrt Ex2 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* XY wrt Oy2 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = {(0,  1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + \n\t\t           (0,  1) * S[2] * MC3 + (0, -1) * S[3] * MC4} * \n                                 gX[ia1] * gY[ia2] * exp(j PD) */\n\t\tCOMPLEX_ADD2 (ct1, SM1, SM3);\n\t\tCOMPLEX_MUL2 (ct2, Jp, ct1);\n\t\tCOMPLEX_ADD2 (ct1, SM2, SM4);\n\t\tCOMPLEX_MUL2 (ct3, Jm, ct1);\n\t\tCOMPLEX_ADD2 (ct2, ct2, ct3);\n\t\tCOMPLEX_MUL2 (DFDP,  ct2, ggPD);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* XY wrt Ey2 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = {-S[0] * CX[ia1] * CY[ia2] +       \n\t                    S[1] * CX[ia1] * SY[ia2] -\n\t\t\t    S[2] * SX[ia1] * CY[ia2] + \n\t\t\t    S[3] * SX[ia1] * SY[ia2]} * \n\t\t\t        gX[ia1] * gY[ia2] * exp(j PD) */\n\t\tCOMPLEX_MUL3(ct5, S[0], CX[ia1], CY[ia2]);\n\t\tCOMPLEX_NEGATE(ct1, ct5);\n\t\tCOMPLEX_MUL3(ct5, S[1], CX[ia1], SY[ia2]);\n\t\tCOMPLEX_NEGATE(ct2, ct5);\n\t\tCOMPLEX_MUL3(ct3, S[2], SX[ia1], CY[ia2]);\n\t\tCOMPLEX_MUL3(ct4, S[3], SX[ia1], SY[ia2]);\n\t\tCOMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4);\n\t\tCOMPLEX_MUL2(DFDP, ct5, ggPD);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end second antenna parameter switch */\n\t} /* end loop over second antenna parameters */\n\t\n\t/* Loop over source parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* XY wrt IPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part =   (MC1*DPAc + MC4*DPA) * gX[ia1] * gX[ia2] * exp(j PD) */\n\t\tCOMPLEX_MUL2(ct2, MC1, DPAc);\n\t\tCOMPLEX_MUL2(ct3, MC4, DPA);\n\t\tCOMPLEX_ADD2(ct1, ct2, ct3);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ggPD);\n\t\tgradR = DFDP.real;    /* RyxR wrt gY1 */\n\t\tgradI = DFDP.imag;    /* RyxI wrt gY1 */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* XY wrt QPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = (MC2*SPAc + MC3*SPA) * gX[ia1] * gX[ia2] * exp(j PD) */\n\t\tCOMPLEX_MUL2(ct2, MC2, SPAc);\n\t\tCOMPLEX_MUL2(ct3, MC3, SPA);\n\t\tCOMPLEX_ADD2(ct1, ct2, ct3);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ggPD);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* XY wrt UPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* (j MC2*SPAc - j MC3*SPA) * gX[ia1] * gX[ia2] * exp(j PD) */\n\t\tCOMPLEX_MUL3(ct2, Jp, MC2, SPAc);\n\t\tCOMPLEX_MUL3(ct3, Jp, MC3, SPA);\n\t\tCOMPLEX_SUB(ct1, ct2, ct3);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ggPD);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* XY wrt VPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* (MC1*DPAc - MC4*DPA) * gX[ia1] * gX[ia2] * exp(j PD) */\n\t\tCOMPLEX_MUL2(ct2, MC1, DPAc);\n\t\tCOMPLEX_MUL2(ct3, MC4, DPA);\n\t\tCOMPLEX_SUB(ct1, ct2, ct3);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ggPD);\n\t\tgradR = DFDP.real;    /* RyxR wrt gY1 */\n\t\tgradI = DFDP.imag;    /* RyxI wrt gY1 */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t   } \n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end source parameter switch */\n\t} /* end loop over source parameters */\n\t\n\t/* gradient wrt PD */\n\tif (args->doFitRL) {\n\t  if (wt[idata*4+kk]>0.0) {\n\t    /* part = (0,  1) * VXY */   \n\t    COMPLEX_MUL2 (DFDP, Jp, VXY);\n\t    gradR = DFDP.real;\n\t    gradI = DFDP.imag;\n\t    /*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t  } else gradR = gradI = 0.0;    /* invalid data */\n\t  j = args->PDPNumb;\n\t  gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t  gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t}\n\t\n\t/* Loop over antenna gains */\n\tfor (k=0; k<2; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* XY wrt gX1 */\n\t    /* Fitting? */\n\t    if (antGainFit[ia1][0]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = (S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) \n\t\t             * gY[ia2]  * exp(j PD) */\n\t\tCOMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4);\n\t\tCOMPLEX_SET (ct2, 1./antGain[ia2*2+1], 0);\n\t\tCOMPLEX_EXP (ct3, PD);\n\t\tCOMPLEX_MUL3 (DFDP, ct1, ct2, ct3);\n\t\tgradR = DFDP.real;    /* RxyR wrt gX1 */\n\t\tgradI = DFDP.imag;    /* RxyI wrt gX1 */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = antGainPNumb[ia1][0];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t      }\n\t    break;\n\t  case 1:  /* XY wrt gY2 */\n\t    if (antGainFit[ia2][1]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = {S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) \n\t                    * gX[ia1] * exp(j PD) */\n\t\tCOMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4);\n\t\tCOMPLEX_SET (ct2, antGain[ia1*2+0], 0);\n\t\tCOMPLEX_EXP (ct3, PD);\n\t\tCOMPLEX_MUL3 (DFDP, ct1, ct2, ct3);\n\t\tgradR = DFDP.real;    /* RxyR wrt gY2 */\n\t\tgradI = DFDP.imag;    /* RxyI wrt gY2 */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = antGainPNumb[ia2][1];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t      }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end gain switch */\n\t} /* end loop over gains */\n\t\n\tbreak;  /* End XY */\n      \t\n      case 3:     /* YX */\n\tif (wt[idata*4+kk]>0.0) {\n\t  isigma = wt[idata*4+kk];\n\t  /* VYX = {S[0] * SY[ia1] * CXc[ia2] +       \n\t            S[1] * SY[ia1] * SXc[ia2] +\n\t\t    S[2] * CY[ia1] * CXc[ia2]  + \n\t\t    S[3] * CY[ia1] * SXc[ia2]} * g1Y * g2X * exp(-j PD)\n\t  */\n\t  COMPLEX_MUL2 (MC1, SY[ia1], CXc[ia2]);\n\t  COMPLEX_MUL2 (MC2, SY[ia1], SXc[ia2]);\n\t  COMPLEX_MUL2 (MC3, CY[ia1], CXc[ia2]);\n\t  COMPLEX_MUL2 (MC4, CY[ia1], SXc[ia2]);\n\t  COMPLEX_MUL2 (SM1, S[0], MC1);\n\t  COMPLEX_MUL2 (SM2, S[1], MC2);\n\t  COMPLEX_MUL2 (SM3, S[2], MC3);\n\t  COMPLEX_MUL2 (SM4, S[3], MC4);\n\t  COMPLEX_ADD4 (ct5, SM1, SM2, SM3, SM4);\n\t  COMPLEX_SET (ct1,  antGain[ia1*2+1]*antGain[ia2*2+0], 0);\n\t  COMPLEX_EXP (ct2, -PD);\n\t  COMPLEX_MUL2 (ggPD, ct1, ct2);\n\t  COMPLEX_MUL2 (VYX, ct5, ggPD);\n\t} \n\t\n\t/* Loop over first antenna parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* YX wrt Ox1 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* YX wrt Ex1 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* YX wrt Oy1 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = {(0, -1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + \n\t\t   (        0,  1) * S[2] * MC3 + (0,  1) * S[3] * MC4} * \n\t                          gX[ia1] * gY[ia2] * exp(-j PD) */\n\t\tCOMPLEX_ADD2 (ct1, SM1, SM2);\n\t\tCOMPLEX_MUL2 (ct2, Jm, ct1);\n\t\tCOMPLEX_ADD2 (ct1, SM3, SM4);\n\t\tCOMPLEX_MUL2 (ct3, Jp, ct1);\n\t\tCOMPLEX_ADD2 (ct2, ct2, ct3);\n\t\tCOMPLEX_MUL2 (DFDP, ct2, ggPD);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* YX wrt Ey1 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = {-S[0] * CXc[ia2] * CYc[ia1] -       \n\t                    S[1] * SXc[ia2] * CYc[ia1] +\n\t\t\t    S[2] * CXc[ia2] * SYc[ia1] + \n\t\t\t    S[3] * SXc[ia2] * SYc[ia1]} * \n\t\t\t           gY[ia1] * gX[ia2] * exp(-j PD) */\n\t\tCOMPLEX_MUL3(ct5, S[0], CXc[ia2], CYc[ia1]);\n\t\tCOMPLEX_NEGATE(ct1, ct5);\n\t\tCOMPLEX_MUL3(ct5, S[1], SXc[ia2], CYc[ia1]);\n\t\tCOMPLEX_NEGATE(ct2, ct5);\n\t\tCOMPLEX_MUL3(ct3, S[2], CXc[ia2], SYc[ia1]);\n\t\tCOMPLEX_MUL3(ct4, S[3], SXc[ia2], SYc[ia1]);\n\t\tCOMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4);\n\t\tCOMPLEX_MUL2(DFDP, ct5, ggPD);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end first antenna parameter switch */\n\t} /* end loop over first antenna parameters */\n\t\n\t/* Loop over second antenna parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* YX wrt Ox2 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = {(0,  1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + \n\t\t           (0,  1) * S[2] * MC3 + (0, -1) * S[3] * MC4} * \n\t\t\t         gY[ia1] * gX[ia2]  * exp(-j PD) */\n\t\tCOMPLEX_ADD2 (ct1, SM1, SM3);\n\t\tCOMPLEX_MUL2 (ct2, Jp, ct1);\n\t\tCOMPLEX_ADD2 (ct1, SM2, SM4);\n\t\tCOMPLEX_MUL2 (ct3, Jm, ct1);\n\t\tCOMPLEX_ADD2 (ct2, ct2, ct3);\n\t\tCOMPLEX_MUL2 (DFDP, ct2, ggPD);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* YX wrt Ex2 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = {-S[0] * SY[ia1] * SX[ia2] + \n\t                    S[1] * SY[ia1] * CX[ia2] -\n\t\t\t    S[2] * CY[ia1] * SX[ia2] + \n\t\t\t    S[3] * CY[ia1] * CX[ia2]} * \n\t\t\t        gY[ia1] * gX[ia2] * exp(-j PD)*/\n\t\tCOMPLEX_MUL3(ct5, S[0], SY[ia1], SX[ia2]);\n\t\tCOMPLEX_NEGATE(ct1, ct5);\n\t\tCOMPLEX_MUL3(ct2, S[1], SY[ia1], CX[ia2]);\n\t\tCOMPLEX_MUL3(ct5, S[2], CY[ia1], SX[ia2]);\n\t\tCOMPLEX_NEGATE(ct3, ct5);\n\t\tCOMPLEX_MUL3(ct4, S[3], CY[ia1], CX[ia2]);\n\t\tCOMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4);\n\t\tCOMPLEX_MUL2(DFDP, ct5, ggPD);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* YX wrt Oy2 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* YX wrt Ey2 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end second antenna parameter switch */\n\t} /* end loop over second antenna parameters */\n\t\n\t/* Loop over source parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* YX wrt IPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part =   (MC1*DPAc + MC4*DPA) * gX[ia1] * gX[ia2] * exp(-j PD) */\n\t\tCOMPLEX_MUL2(ct2, MC1, DPAc);\n\t\tCOMPLEX_MUL2(ct3, MC4, DPA);\n\t\tCOMPLEX_ADD2(ct1, ct2, ct3);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ggPD);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* YX wrt QPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = (MC2*SPAc + MC3*SPA) * gX[ia1] * gX[ia2] * exp(-j PD) */\n\t\tCOMPLEX_MUL2(ct2, MC2, SPAc);\n\t\tCOMPLEX_MUL2(ct3, MC3, SPA);\n\t\tCOMPLEX_ADD2(ct1, ct2, ct3);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ggPD);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* YX wrt UPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* (j MC2*SPAc - j MC3*SPA) * gX[ia1] * gX[ia2] * exp(-j PD) */\n\t\tCOMPLEX_MUL3(ct2, Jp, MC2, SPAc);\n\t\tCOMPLEX_MUL3(ct3, Jp, MC3, SPA);\n\t\tCOMPLEX_SUB(ct1, ct2, ct3);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ggPD);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* YX wrt VPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* (MC1*DPAc - MC4*DPA) * gX[ia1] * gX[ia2] * exp(-j PD) */\n\t\tCOMPLEX_MUL2(ct2, MC1, DPAc);\n\t\tCOMPLEX_MUL2(ct3, MC4, DPA);\n\t\tCOMPLEX_SUB(ct1, ct2, ct3);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ggPD);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\tbreak;\n      default:\n\tbreak;\n\t  }; /* end source parameter switch */\n\t} /* end loop over source parameters */\n\t\n\t/* gradient wrt PD */\n\tif (args->doFitRL) {\n\t  if (wt[idata*4+kk]>0.0) {\n\t    /* part = (0, -1) * VYX */   \n\t    COMPLEX_MUL2 (DFDP, Jm, VYX);\n\t    gradR = DFDP.real;\n\t    gradI = DFDP.imag;\n\t    /*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t  } else gradR = gradI = 0.0;    /* invalid data */\n\t  j = args->PDPNumb;\n\t  gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t  gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t}\n\t/* Loop over antenna gains */\n\tfor (k=0; k<2; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* YX wrt gY1 */\n\t    /* Fitting? */\n\t    if (antGainFit[ia1][1]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = (S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) \n                           * gY[ia1]  * exp(-j PD) */\n\t\tCOMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4);\n\t\tCOMPLEX_SET (ct2, antGain[ia1*2+1], 0);\n\t\tCOMPLEX_EXP (ct3, -PD);\n\t\tCOMPLEX_MUL3 (DFDP, ct1, ct2, ct3);\n\t\tgradR = DFDP.real;    /* RyxR wrt gY1 */\n\t\tgradI = DFDP.imag;    /* RyxI wrt gY1 */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = antGainPNumb[ia1][1];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t      }\n\t    break;\n\t  case 1:  /* wrt gX2 */\n\t    if (antGainFit[ia2][0]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = (S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) \n                              * gY[ia1]  * exp(-j PD) */\n\t\tCOMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4);\n\t\tCOMPLEX_SET (ct2, antGain[ia1*2+1], 0);\n\t\tCOMPLEX_EXP (ct3, -PD);\n\t\tCOMPLEX_MUL3 (DFDP, ct1, ct2, ct3);\n\t\tgradR = DFDP.real;    /* RyxR wrt gX2 */\n\t\tgradI = DFDP.imag;    /* RyxI wrt gX2 */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = antGainPNumb[ia2][0];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t      }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end gain switch */\n\t} /* end loop over gains */\n\t/* End YX */\t\n\t\n      default:\n\t  break;\n\t}; /* end switch over data correlation */\n      \n      i++;  /* Update complex datum number */\n    } /* end loop over correlations */\n  } /* End loop over visibilities */\n\n  return GSL_SUCCESS;\n} /*  end PolnFitJacOEXY */\n\n/**\n * Linear feed Function & Jacobian evaluator for polarization fitting solver\n * Orientation/Ellipticity for linear feeds version\n * Evaluates partial derivatives of model wrt each parameter\n * \\param x       Vector of parameters to be fitted\n *                Flux,array_of polarization_terms\n * \\param param   Function parameter structure (ObitPolnCalFit)\n * \\param f       Vector of (model-obs)/sigma for data points\n * \\param J       Jacobian matrix J[data_point, parameter]\n * \\return completion code GSL_SUCCESS=OK\n */\nstatic int PolnFitFuncJacOEXY (const gsl_vector *x, void *params, \n\t\t\t       gsl_vector *f, gsl_matrix *J)\n{\n  ObitPolnCalFit *args = (ObitPolnCalFit*)params;\n  ofloat *data, *wt;\n  gboolean   **antFit    = args->antFit;\n  olong      **antPNumb  = args->antPNumb;\n  odouble     *antParm   = args->antParm;\n  odouble    *antGain    = args->antGain;\n  gboolean   **antGainFit= args->antGainFit;\n  olong     **antGainPNumb  = args->antGainPNumb;\n  gboolean   **souFit    = args->souFit;\n  odouble    *souParm    = args->souParm;\n  olong      **souPNumb  = args->souPNumb;\n  dcomplex   *CX     = args->RS;\n  dcomplex   *SX     = args->RD;\n  dcomplex   *CY     = args->LS;\n  dcomplex   *SY     = args->LD;\n  dcomplex   *CXc    = args->RSc;\n  dcomplex   *SXc    = args->RDc;\n  dcomplex   *CYc    = args->LSc;\n  dcomplex   *SYc    = args->LDc;\n  ofloat PD, chi1, chi2, PPol;\n  double val;\n  odouble ipol=0.0, qpol=0.0, upol=0.0, vpol=0.0;\n  odouble residR=0.0, residI=0.0, gradR=0.0, gradI=0.0, modelR=0.0, modelI=0.0, isigma=0.0;\n  olong k, kk, iant, ia1, ia2, isou, idata;\n  olong isouLast=-999;\n  dcomplex  SPA, DPA, SPAc, DPAc, ggPD;\n  dcomplex ct1, ct2, ct3, ct4, ct5, Jm, Jp;\n  dcomplex S0[4], S[4], VXX, VXY, VYX, VYY, MC1, MC2, MC3, MC4, DFDP;\n  dcomplex SM1, SM2, SM3, SM4;\n  size_t i, j;\n\n   /* Initialize output */\n  val = 0.0;\n  for (i=0; i<args->ndata; i++) {\n    gsl_vector_set(f, i, val);\n    for (j=0; j<args->nparam; j++) \n      gsl_matrix_set(J, i, j, val);\n  }\n\n  COMPLEX_SET (S[0], 0.0, 0.0);  /* Initialize poln vector */\n  COMPLEX_SET (S[1], 0.0, 0.0);\n  COMPLEX_SET (S[2], 0.0, 0.0);\n  COMPLEX_SET (S[3], 0.0, 0.0);\n  COMPLEX_SET (S0[0], 0.0, 0.0);\n  COMPLEX_SET (S0[1], 0.0, 0.0);\n  COMPLEX_SET (S0[2], 0.0, 0.0);\n  COMPLEX_SET (S0[3], 0.0, 0.0);\n  COMPLEX_SET (MC1, 0.0, 0.0);  /* Other stuff */\n  COMPLEX_SET (MC2, 0.0, 0.0);\n  COMPLEX_SET (MC3, 0.0, 0.0);\n  COMPLEX_SET (MC4, 0.0, 0.0);\n  COMPLEX_SET (VXX, 0.0, 0.0);\n  COMPLEX_SET (VYY, 0.0, 0.0);\n  COMPLEX_SET (VYX, 0.0, 0.0);\n  COMPLEX_SET (VXY, 0.0, 0.0);\n  COMPLEX_SET (Jm,  0.0,-1.0);\n  COMPLEX_SET (Jp,  0.0, 1.0);\n  COMPLEX_SET (SM1, 0.0, 0.0);\n  COMPLEX_SET (SM2, 0.0, 0.0);\n  COMPLEX_SET (SM3, 0.0, 0.0);\n  COMPLEX_SET (SM4, 0.0, 0.0);\n  COMPLEX_SET (ggPD, 0.0, 0.0);\n  \n  /* R-L phase difference */\n  if (args->doFitRL) {\n    j = args->PDPNumb;\n    PD = gsl_vector_get(x, j);\n  } else PD = args->PD;\n  \n  /* get model parameters - first antenna */\n  for (iant=0; iant<args->nant; iant++) {\n    /* Loop over antenna parameters */\n    for (k=0; k<4; k++) {\n      /* Fitting? */\n      if ((antFit[iant][k]) && (args->gotAnt[iant])) {\n\tj = antPNumb[iant][k];\n\tantParm[iant*4+k] = gsl_vector_get(x, j);\n      }\n    } /* end loop over antenna parameters */\n  } /* end loop over antennas */\n  \n  /* antenna gain */\n  for (iant=0; iant<args->nant; iant++) {\n    /* Loop over antenna gains */\n    for (k=0; k<2; k++) {\n      /* Fitting? */\n      if ((antGainFit[iant][k]) && (args->gotAnt[iant])) {\n\tj = antGainPNumb[iant][k];\n\tantGain[iant*2+k] = gsl_vector_get(x, j);\n      }\n    } /* end loop over antenna parameters */\n     /* Default X gain = 1.0/Y gain\n    if (!antGainFit[iant][0]) antGain[iant*2+0] = 1.0 / antGain[iant*2+1]; */\n } /* end loop over antennas */\n  \n  /* now source */\n  for (isou=0; isou<args->nsou; isou++) {\n    /* Loop over source parameters */\n    for (k=0; k<4; k++) {\n      /* Fitting? */\n      if (souFit[isou][k]) {\n\tj = souPNumb[isou][k];\n\tsouParm[isou*4+k] = gsl_vector_get(x, j);\n      }\n    } /* end loop over source parameters */\n  } /* end loop over sources */\n  \n  /* data & wt pointers */\n  data = args->inData;\n  wt   = args->inWt;\n\n   /* Injest model, factorize into antenna components - \n     data in order Orientation R/X, Elipticity R/X, Orientation L/Y, Elipticity L/Y */\n  /* Elipticity, Orientation terms */\n  for (i=0; i<args->nant; i++) {\n    COMPLEX_EXP (ct1, -antParm[i*4+0]);\n    COMPLEX_SET (ct2, cos(G_PI*0.25+antParm[i*4+1]), 0.0);\n    COMPLEX_MUL2 (CX[i], ct1, ct2);\n    COMPLEX_EXP (ct1, antParm[i*4+0]);\n    COMPLEX_SET (ct2, sin(G_PI*0.25+antParm[i*4+1]), 0.0);\n    COMPLEX_MUL2 (SX[i], ct1, ct2);\n    COMPLEX_EXP (ct1, antParm[i*4+2]);\n    COMPLEX_SET (ct2, cos(G_PI*0.25-antParm[i*4+3]), 0.0);\n    COMPLEX_MUL2 (CY[i], ct1, ct2);\n    COMPLEX_EXP (ct1, -antParm[i*4+2]);\n    COMPLEX_SET (ct2, sin(G_PI*0.25-antParm[i*4+3]), 0.0);\n    COMPLEX_MUL2 (SY[i], ct1, ct2);\n \n    COMPLEX_CONJUGATE (CXc[i], CX[i]);\n    COMPLEX_CONJUGATE (SXc[i], SX[i]);\n    COMPLEX_CONJUGATE (CYc[i], CY[i]);\n    COMPLEX_CONJUGATE (SYc[i], SY[i]);\n  }\n\n  /* Loop over data */\n  i = 0;\n  for (idata=0; idata<args->nvis; idata++) {\n    /* Parallactic angle terms */\n    chi1  = data[idata*10+0];   /* parallactic angle ant 1 */\n    chi2  = data[idata*10+1];   /* parallactic angle ant 2 */\n    COMPLEX_EXP (SPA,(chi1+chi2));\n    COMPLEX_EXP (DPA,chi1-chi2);\n    COMPLEX_CONJUGATE (SPAc, SPA);\n    COMPLEX_CONJUGATE (DPAc, DPA);\n\n    isou  = MAX (0, args->souNo[idata]);    /* Source number */\n    /* New source? get parameters */\n    if (isou!=isouLast) {\n      isouLast = isou;\n      /* Source parameters */\n      ipol = souParm[isou*4+0];\n      /* Fitting or fixed? */\n      if (args->souFit[isou][1]) \n\tqpol = souParm[isou*4+1];\n      else {\n\tPPol = args->PPol[isou] + args->dPPol[isou]*(args->freq-args->refFreq);\n\tqpol = PPol*ipol*cos(args->RLPhase[isou]);}\n      if (args->souFit[isou][2]) \n\tupol = souParm[isou*4+2];\n      else {\n\tPPol = args->PPol[isou] + args->dPPol[isou]*(args->freq-args->refFreq);\n\tupol = PPol*ipol*sin(args->RLPhase[isou]);}\n      vpol = souParm[isou*4+3];\n      /* Complex Stokes array */\n      COMPLEX_SET (S0[0], ipol+vpol, 0.0);\n      COMPLEX_SET (S0[1], qpol,  upol);\n      COMPLEX_SET (S0[2], qpol, -upol);\n      COMPLEX_SET (S0[3], ipol-vpol, 0.0);\n    }\n\n    /* Rotate Stokes by parallactic angle */\n    COMPLEX_MUL2(S[0], DPAc, S0[0]);\n    COMPLEX_MUL2(S[1], SPAc, S0[1]);\n    COMPLEX_MUL2(S[2], SPA,  S0[2]);\n    COMPLEX_MUL2(S[3], DPA,  S0[3]);\n \n    /* Antenna parameters */\n    ia1    = args->antNo[idata*2+0];\n    ia2    = args->antNo[idata*2+1]; \n    \n    /* i = datum number */\n    /* Loop over correlations calculating derivatives */\n    for (kk=0; kk<4; kk++) {\n      switch (kk) { \n\t\n      case 0:     /* XX */\n\tif (wt[idata*4+kk]>0.0) {\n\t  isigma = wt[idata*4+kk];\n\t  /* VXX = {S[0] * CX[ia1] * CXc[ia2] +\n\t            S[1] * CX[ia1] * SXc[ia2] +\n\t\t    S[2] * SX[ia1] * CXc[ia2] + \n\t\t    S[3] * SX[ia1] * SXc[ia2]} * g1X * g2X ;\n\t  */\n\t  COMPLEX_MUL2 (MC1, CX[ia1], CXc[ia2]);\n\t  COMPLEX_MUL2 (MC2, CX[ia1], SXc[ia2]);\n\t  COMPLEX_MUL2 (MC3, SX[ia1], CXc[ia2]);\n\t  COMPLEX_MUL2 (MC4, SX[ia1], SXc[ia2]);\n\t  COMPLEX_MUL2 (SM1, S[0], MC1);\n\t  COMPLEX_MUL2 (SM2, S[1], MC2);\n\t  COMPLEX_MUL2 (SM3, S[2], MC3);\n\t  COMPLEX_MUL2 (SM4, S[3], MC4);\n\t  COMPLEX_ADD4 (ct5, SM1, SM2, SM3, SM4);\n\t  COMPLEX_SET (ggPD,  antGain[ia1*2+0]*antGain[ia2*2+0], 0);\n\t  COMPLEX_MUL2 (VXX, ct5, ggPD);\n\t  modelR = VXX.real; modelI = VXX.imag;\n\t  residR = modelR - data[idata*10+(kk+1)*2];\n\t  residI = modelI - data[idata*10+(kk+1)*2+1];\n\t  gsl_vector_set(f, i*2,   residR*isigma); /* Save function resids */\n\t  gsl_vector_set(f, i*2+1, residI*isigma); /* Save function resids */\n\t} else  residR = residI = 0.0; /* Invalid data */\n\t\n\t/* Loop over first antenna parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* XX wrt Ox1 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* {(0, -1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + \n\t\t    (0,  1) * S[2] * MC3 + (0,  1) * S[3] * MC4}  * gX[ia1] * gX[ia2]  */\n\t\tCOMPLEX_ADD2 (ct1, SM1, SM2);\n\t\tCOMPLEX_MUL2 (ct2, Jm, ct1);\n\t\tCOMPLEX_ADD2 (ct1, SM3, SM4);\n\t\tCOMPLEX_MUL2 (ct3, Jp, ct1);\n\t\tCOMPLEX_ADD2 (ct2, ct2, ct3);\n\t\tCOMPLEX_MUL2 (DFDP, ct2, ggPD);\n\t\tgradR = DFDP.real;    /* RxxR wrt Ox1 */\n\t\tgradI = DFDP.imag;    /* RxxI wrt Ox1 */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI =0.0;     /* Invalid data */\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* XX wrt Ex1 */\n\t    /* Fitting? */\n \t    if (antFit[ia1][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = {-S[0] * CXc[ia2] * SXc[ia1] -\n\t\t            S[1] * SXc[ia2] * SXc[ia1] +\n\t\t\t    S[2] * CXc[ia2] * CXc[ia1] +\t       \n\t\t\t    S[3] * SXc[ia2] * CXc[ia1]}  * gX[ia1] * gX[ia2]  */\n\t\tCOMPLEX_MUL3(ct5, S[0], CXc[ia2], SXc[ia1]);\n\t\tCOMPLEX_NEGATE(ct1, ct5);\n\t\tCOMPLEX_MUL3(ct5, S[1], SXc[ia2], SXc[ia1]);\n\t\tCOMPLEX_NEGATE(ct2, ct5);\n\t\tCOMPLEX_MUL3(ct3, S[2], CXc[ia2], SXc[ia1]);\n\t\tCOMPLEX_MUL3(ct4, S[3], SXc[ia2], CXc[ia1]);\n\t\tCOMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4);\n\t\tCOMPLEX_MUL2(DFDP, ct5, ggPD);\n\t\tgradR = DFDP.real;    /* RxxR wrt Ex1 */\n\t\tgradI = DFDP.imag;    /* RxxI wrt Ex1 */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* XX wrt OY1 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* XX wrt EY1 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end first antenna parameter switch */\n\t} /* end loop over first antenna parameters */\n\t\n\t/* Loop over second antenna parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* XX wrt Ox2 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* {(0,  1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + \n\t\t    (0,  1) * S[2] * MC3 + (0, -1) * S[3] * MC4}  * gX[ia1] * gX[ia2]   */\n\t\tCOMPLEX_ADD2 (ct1, SM1, SM3);\n\t\tCOMPLEX_MUL2 (ct2, Jp, ct1);\n\t\tCOMPLEX_ADD2 (ct1, SM2, SM4);\n\t\tCOMPLEX_MUL2 (ct3, Jm, ct1);\n\t\tCOMPLEX_ADD2 (ct2, ct2, ct3);\n\t\tCOMPLEX_MUL2 (DFDP, ct2, ggPD);\n\t\tgradR = DFDP.real;    /* RxxR wrt Ox2 */\n\t\tgradI = DFDP.imag;    /* RxxI wrt Ox2 */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* XX wrt Ex2 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = {-S[0] * CX[ia1] * SX[ia2] +\n\t\t            S[1] * CX[ia1] * CX[ia2] -\n\t\t\t    S[2] * SX[ia1] * SX[ia2] +\n\t\t\t    S[3] * SX[ia1] * CX[ia2]} * gX[ia1] * gX[ia2]  */\n\t\tCOMPLEX_MUL3(ct5, S[0], CX[ia1], SX[ia2]);\n\t\tCOMPLEX_NEGATE(ct1, ct5);\n\t\tCOMPLEX_MUL3(ct2, S[1], CX[ia1], CX[ia2]);\n\t\tCOMPLEX_MUL3(ct5, S[2], SX[ia1], SX[ia2]);\n\t\tCOMPLEX_NEGATE(ct3, ct5);\n\t\tCOMPLEX_MUL3(ct4, S[3], SX[ia1], CX[ia2]);\n\t\tCOMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4);\n\t\tCOMPLEX_MUL2(DFDP, ct5, ggPD);\n\t\tgradR = DFDP.real;    /* RxxR wrt Ox2 */\n\t\tgradI = DFDP.imag;    /* RxxI wrt Ox2 */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* XX wrt Oy2 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* XX wrt Ey2 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end second antenna parameter switch */\n\t}  /* end loop over second antenna parameters */\n\t\n\t/* Loop over source parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* XX wrt IPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part =   (MC1*DPAc + MC4*DPA) * gX[ia1] * gX[ia2] */\n\t\tCOMPLEX_MUL2(ct2, MC1, DPAc);\n\t\tCOMPLEX_MUL2(ct3, MC4, DPA);\n\t\tCOMPLEX_ADD2(ct1, ct2, ct3);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ggPD);\n\t\tgradR = DFDP.real;    /* RxxR wrt ipol */\n\t\tgradI = DFDP.imag;    /* RxxI wrt ipol */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* XX wrt QPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = (MC2*SPAc + MC3*SPA) * gX[ia1] * gX[ia2] */\n\t\tCOMPLEX_MUL2(ct2, MC2, SPAc);\n\t\tCOMPLEX_MUL2(ct3, MC3, SPA);\n\t\tCOMPLEX_ADD2(ct1, ct2, ct3);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ggPD);\n\t\tgradR = DFDP.real;    /* RxxR wrt qpol */\n\t\tgradI = DFDP.imag;    /* RxxI wrt qpol */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* XX wrt UPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* (j MC2*SPAc - j MC3*SPA) * gX[ia1] * gX[ia2] */\n\t\tCOMPLEX_MUL3(ct2, Jp, MC2, SPAc);\n\t\tCOMPLEX_MUL3(ct3, Jp, MC3, SPA);\n\t\tCOMPLEX_SUB(ct1, ct2, ct3);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ggPD);\n \t\tgradR = DFDP.real;    /* RxxR wrt upol */\n\t\tgradI = DFDP.imag;    /* RxxI wrt upol */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* XX wrt VPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* (MC1*DPAc - MC4*DPA) * gX[ia1] * gX[ia2] */\n\t\tCOMPLEX_MUL2(ct2, MC1, DPAc);\n\t\tCOMPLEX_MUL2(ct3, MC4, DPA);\n\t\tCOMPLEX_SUB(ct1, ct2, ct3);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ggPD);\n\t\tgradR = DFDP.real;    /* RxxR wrt vpol */\n\t\tgradI = DFDP.imag;    /* RxxI wrt vpol */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end source parameter switch */\n\t} /* end loop over source parameters */\n\n\t/* gradient wrt PD = 0 */\n\tif (args->doFitRL) {\n\t  gradR = gradI = 0.0;\n\t  j = args->PDPNumb;\n\t  gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t  gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t}\n\n\t/* Loop over antenna gains */\n\tfor (k=0; k<2; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* XX wrt gX1 */\n\t    /* Fitting? */\n\t    if (antGainFit[ia1][0]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = (S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) * gX[ia2] */\n\t\tCOMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4);\n\t\tCOMPLEX_SET (ct2, antGain[ia2*2+0], 0);\n\t\tCOMPLEX_MUL2 (DFDP, ct1, ct2);\n\t\tgradR = DFDP.real;    /* RxxR wrt gX1 */\n\t\tgradI = DFDP.imag;    /* RxxI wrt gX1 */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = antGainPNumb[ia1][0];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t      }\n\t    break;\n\t  case 1:  /* XX wrt gX2 */\n\t    if (antGainFit[ia2][0]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = (S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) * gX[ia1] */\n\t\tCOMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4);\n\t\tCOMPLEX_SET (ct2, antGain[ia1*2+0], 0);\n\t\tCOMPLEX_MUL2 (DFDP, ct1, ct2);\n\t\tgradR = DFDP.real;    /* RxxR wrt gX2 */\n\t\tgradI = DFDP.imag;    /* RxxI wrt gX2 */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = antGainPNumb[ia2][0];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t      }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end gain switch */\n\t} /* end loop over gains */\n\tbreak;  /* End XX */\n\t\n      case 1:     /* YY */\n\tif (wt[idata*4+kk]>0.0) {\n\t  isigma = wt[idata*4+kk];\n\t  /* VYY = {S[0] * SY[ia1] * SYc[ia2] +       \n\t            S[1] * SY[ia1] * CYc[ia2] +\n\t\t    S[2] * CY[ia1] * SYc[ia2] + \n\t\t    S[3] * CY[ia1] * CYc[ia2]} * g1Y * g2Y ;\n\t  */\n\t  COMPLEX_MUL2 (MC1, SY[ia1], SYc[ia2]);\n\t  COMPLEX_MUL2 (MC2, SY[ia1], CYc[ia2]);\n\t  COMPLEX_MUL2 (MC3, CY[ia1], SYc[ia2]);\n\t  COMPLEX_MUL2 (MC4, CY[ia1], CYc[ia2]);\n\t  COMPLEX_MUL2 (SM1, S[0], MC1);\n\t  COMPLEX_MUL2 (SM2, S[1], MC2);\n\t  COMPLEX_MUL2 (SM3, S[2], MC3);\n\t  COMPLEX_MUL2 (SM4, S[3], MC4);\n\t  COMPLEX_ADD4 (ct5, SM1, SM2, SM3, SM4);\n\t  COMPLEX_SET (ggPD,  antGain[ia1*2+1]*antGain[ia2*2+1], 0);\n\t  COMPLEX_MUL2 (VYY, ct5, ggPD);\n\t  modelR = VYY.real; modelI = VYY.imag;\n\t  residR = modelR - data[idata*10+(kk+1)*2];\n\t  residI = modelI - data[idata*10+(kk+1)*2+1];\n\t  gsl_vector_set(f, i*2,   residR*isigma); /* Save function resids */\n\t  gsl_vector_set(f, i*2+1, residI*isigma); /* Save function resids */\n\t} else  residR = residI = 0.0; /* Invalid data */\n\t  \n\t/* Loop over first antenna parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* YY wrt Ox1 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* YY wrt Ex1 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* YY wrt Oy1 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = {(0, -1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + \n\t\t           (0,  1) * S[2] * MC2 + (0,  1) * S[3] * MC4} * gY[ia1] * gY[ia2] */\n\t\tCOMPLEX_ADD2 (ct1, SM1, SM2);\n\t\tCOMPLEX_MUL2 (ct2, Jm, ct1);\n\t\tCOMPLEX_ADD2 (ct1, SM3, SM4);\n\t\tCOMPLEX_MUL2 (ct3, Jp, ct1);\n\t\tCOMPLEX_ADD2 (ct2, ct2, ct3);\n\t\tCOMPLEX_MUL2 (DFDP, ct2, ggPD);\n\t\tgradR = DFDP.real;    /* RyyR wrt Oy1 */\n\t\tgradI = DFDP.imag;    /* RyyI wrt Oy1 */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* YY wrt Ey1 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = {-S[0] * SYc[ia2] * CYc[ia1] -\n                            S[1] * CYc[ia2] * CYc[ia1] +\n\t\t\t    S[2] * SYc[ia2] * SYc[ia1] +\t       \n\t\t\t    S[3] * CYc[ia2] * SYc[ia1]}  * gX[ia1] * gX[ia2]  */\n\t\tCOMPLEX_MUL3(ct5, S[0], SYc[ia2], CYc[ia1]);\n\t\tCOMPLEX_NEGATE(ct1, ct5);\n\t\tCOMPLEX_MUL3(ct5, S[1], CYc[ia2], CYc[ia1]);\n\t\tCOMPLEX_NEGATE(ct2, ct5);\n\t\tCOMPLEX_MUL3(ct3, S[2], SYc[ia2], SYc[ia1]);\n\t\tCOMPLEX_MUL3(ct4, S[3], CYc[ia2], SYc[ia1]);\n\t\tCOMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4);\n\t\tCOMPLEX_MUL2(DFDP, ct5, ggPD);\n\t\tgradR = DFDP.real;    /* RyyR wrt Ey1 */\n\t\tgradI = DFDP.imag;    /* RyyI wrt Ey1 */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end first antenna parameter switch */\n\t} /* end loop over first antenna parameters */\n\t\n\t/* Loop over second antenna parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* YY wrt Ox2 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* YY wrt Ex2 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* YY wrt Oy2 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = {(0,  1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + \n\t\t           (0,  1) * S[2] * MC3 + (0, -1) * S[3] * MC4} * gY[ia1] * gY[ia2]  */\n\t\tCOMPLEX_ADD2 (ct1, SM1, SM3);\n\t\tCOMPLEX_MUL2 (ct2, Jp, ct1);\n\t\tCOMPLEX_ADD2 (ct1, SM2, SM4);\n\t\tCOMPLEX_MUL2 (ct3, Jm, ct1);\n\t\tCOMPLEX_ADD2 (ct2, ct2, ct3);\n\t\tCOMPLEX_MUL2 (DFDP,  ct2, ggPD);\n\t\tgradR = DFDP.real;    /* RyyR wrt Oy2 */\n\t\tgradI = DFDP.imag;    /* RyyI wrt Oy2 */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* YY wrt Ey2  */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = {-S[0] * SY[ia1] * CY[ia2] + \n                            S[1] * SY[ia1] * SY[ia2] -\n\t\t\t    S[2] * CY[ia1] * CY[ia2]  + \n\t\t\t    S[3] * CY[ia1] * SY[ia2]} * gY[ia1] * gY[ia2] */\n\t\tCOMPLEX_MUL3(ct5, S[0], SY[ia1], CY[ia2]);\n\t\tCOMPLEX_NEGATE(ct1, ct5);\n\t\tCOMPLEX_MUL3(ct2, S[1], SY[ia1], SY[ia2]);\n\t\tCOMPLEX_MUL3(ct5, S[2], CY[ia1], CY[ia2]);\n\t\tCOMPLEX_NEGATE(ct3, ct5);\n\t\tCOMPLEX_MUL3(ct4, S[3], CY[ia1], SY[ia2]);\n\t\tCOMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4);\n\t\tCOMPLEX_MUL2(DFDP, ct5, ggPD);\n\t\tgradR = DFDP.real;    /* RyyR wrt Ey2 */\n\t\tgradI = DFDP.imag;    /* RyyI wrt Ey2 */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end second antenna parameter switch */\n\t} /* end loop over second antenna parameters */\n\t\n\t/* Loop over source parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* YY wrt IPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part =   (MC1*DPAc + MC4*DPA) * gX[ia1] * gX[ia2] */\n\t\tCOMPLEX_MUL2(ct2, MC1, DPAc);\n\t\tCOMPLEX_MUL2(ct3, MC4, DPA);\n\t\tCOMPLEX_ADD2(ct1, ct2, ct3);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ggPD);\n\t\tgradR = DFDP.real;    /* RyyR wrt ipol */\n\t\tgradI = DFDP.imag;    /* RyyI wrt ipol */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* YY wrt Qpol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = (MC2*SPAc + MC3*SPA) * gX[ia1] * gX[ia2] */\n\t\tCOMPLEX_MUL2(ct2, MC2, SPAc);\n\t\tCOMPLEX_MUL2(ct3, MC3, SPA);\n\t\tCOMPLEX_ADD2(ct1, ct2, ct3);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ggPD);\n\t\tgradR = DFDP.real;    /* RyyR wrt qpol */\n\t\tgradI = DFDP.imag;    /* RyyI wrt qpol */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* YY wrt UPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* (j MC2*SPAc - j MC3*SPA) * gX[ia1] * gX[ia2] */\n\t\tCOMPLEX_MUL3(ct2, Jp, MC2, SPAc);\n\t\tCOMPLEX_MUL3(ct3, Jp, MC3, SPA);\n\t\tCOMPLEX_SUB(ct1, ct2, ct3);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ggPD);\n\t\tgradR = DFDP.real;    /* RyyR wrt upol */\n\t\tgradI = DFDP.imag;    /* RyyI wrt upol */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* YY wrt VPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* (MC1*DPAc - MC4*DPA) * gX[ia1] * gX[ia2] */\n\t\tCOMPLEX_MUL2(ct2, MC1, DPAc);\n\t\tCOMPLEX_MUL2(ct3, MC4, DPA);\n\t\tCOMPLEX_SUB(ct1, ct2, ct3);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ggPD);\n\t\tgradR = DFDP.real;    /* RyyR wrt vpol */\n\t\tgradI = DFDP.imag;    /* RyyI wrt vpol */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end source parameter switch */\n\t} /* end loop over source parameters */\n\n\t/* gradient wrt PD - no effect */\n\tif (args->doFitRL) {\n\t  gradR = gradI = 0.0;\n\t  j = args->PDPNumb;\n\t  gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t  gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t}\n\n\t/* Loop over antenna gains */\n\tfor (k=0; k<2; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* YY wrt gY1 */\n\t    /* Fitting? */\n\t    if (antGainFit[ia1][1]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = (S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) * gY[ia2] */\n\t\tCOMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4);\n\t\tCOMPLEX_SET (ct2, antGain[ia2*2+1], 0);\n\t\tCOMPLEX_MUL2 (DFDP, ct1, ct2);\n\t\tgradR = DFDP.real;    /* RyyR wrt gY1 */\n\t\tgradI = DFDP.imag;    /* RyyI wrt gY1 */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = antGainPNumb[ia1][1];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t      }\n\t    break;\n\t  case 1:  /* YY wrt gY2 */\n\t    if (antGainFit[ia2][1]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = (S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) * gY[ia1] */\n\t\tCOMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4);\n\t\tCOMPLEX_SET (ct2, antGain[ia1*2+0], 1);\n\t\tCOMPLEX_MUL2 (DFDP, ct1, ct2);\n\t\tgradR = DFDP.real;    /* RyyR wrt gY2 */\n\t\tgradI = DFDP.imag;    /* RyyI wrt gY2 */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = antGainPNumb[ia2][1];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t      }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end gain switch */\n\t} /* end loop over gains */\n\t\n\tbreak;  /* End YY */\n\t\n      case 2:     /* XY */\n\tif (wt[idata*4+kk]>0.0) {\n\t  isigma = wt[idata*4+kk];\n\t  /* VXY = {S[0] * CX[ia1] * SYc[ia2] +       \n\t            S[1] * CX[ia1] * CYc[ia2] +\n\t\t    S[2] * SX[ia1] * SYc[ia2] + \n\t\t    S[3] * SX[ia1] * CYc[ia2]}} * g1X * g2Y * exp(j PD);\n\t  */\n\t  COMPLEX_MUL2 (MC1, CX[ia1], SYc[ia2]);\n\t  COMPLEX_MUL2 (MC2, CX[ia1], CYc[ia2]);\n\t  COMPLEX_MUL2 (MC3, SX[ia1], SYc[ia2]);\n\t  COMPLEX_MUL2 (MC4, SX[ia1], CYc[ia2]);\n\t  COMPLEX_MUL2 (SM1, S[0], MC1);\n\t  COMPLEX_MUL2 (SM2, S[1], MC2);\n\t  COMPLEX_MUL2 (SM3, S[2], MC3);\n\t  COMPLEX_MUL2 (SM4, S[3], MC4);\n\t  COMPLEX_ADD4 (ct5, SM1, SM2, SM3, SM4);\n\t  COMPLEX_SET (ct1,  antGain[ia1*2+0]*antGain[ia2*2+1], 0);\n\t  COMPLEX_EXP (ct2, PD);\n\t  COMPLEX_MUL2 (ggPD, ct1, ct2);\n\t  COMPLEX_MUL2 (VXY, ct5, ggPD);\n\t  modelR = VXY.real; modelI = VXY.imag;\n\t  residR = modelR - data[idata*10+(kk+1)*2];\n\t  residI = modelI - data[idata*10+(kk+1)*2+1];\n\t  gsl_vector_set(f, i*2,   residR*isigma); /* Save function resids */\n\t  gsl_vector_set(f, i*2+1, residI*isigma); /* Save function resids */\n\t} else  residR = residI = 0.0; /* Invalid data */\n\t\n\t/* Loop over first antenna parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* XY wrt Ox1 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = {(0, -1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + \n\t\t           (0,  1) * S[2] * MC3 + (0,  1) * S[3] * MC4} *\n\t\t\t   gX[ia1] * gY[ia2] * exp(j PD) */\n\t\tCOMPLEX_ADD2 (ct1, SM1, SM2);\n\t\tCOMPLEX_MUL2 (ct2, Jm, ct1);\n\t\tCOMPLEX_ADD2 (ct1, SM3, SM4);\n\t\tCOMPLEX_MUL2 (ct3, Jp, ct1);\n\t\tCOMPLEX_ADD2 (ct2, ct2, ct3);\n\t\tCOMPLEX_MUL2 (DFDP, ct2, ggPD);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* XY wrt Ex1 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part =  {-S[0] * SYc[ia2] * SXc[ia1]  - \n\t\t   S[1] * CYc[ia2] * SXc[ia1]  +\n\t\t   S[2] * SYc[ia2] * CXc[ia1]  + \n\t\t   S[3] * CYc[ia2] * CXc[ia1]  } * \n\t\t            gX[ia1] * gY[ia2] * exp(j PD) */\n\t\tCOMPLEX_MUL3(ct5, S[0], SYc[ia2], SXc[ia1]);\n\t\tCOMPLEX_NEGATE(ct1, ct5);\n\t\tCOMPLEX_MUL3(ct5, S[1], CYc[ia2], SXc[ia1]);\n\t\tCOMPLEX_NEGATE(ct2, ct5);\n\t\tCOMPLEX_MUL3(ct3, S[2], SYc[ia2], CXc[ia1]);\n\t\tCOMPLEX_MUL3(ct4, S[3], CYc[ia2], CXc[ia1]);\n\t\tCOMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4);\n\t\tCOMPLEX_MUL2(DFDP, ct5, ggPD);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* XY wrt Oy1 =0 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* XY wrt Ey1 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end first antenna parameter switch */\n\t} /* end loop over first antenna parameters */\n\t\n\t/* Loop over second antenna parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* XY wrt Ox2 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* XY wrt Ex2 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* XYwrt Oy2 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = {(0,  1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + \n\t\t           (0,  1) * S[2] * MC3 + (0, -1) * S[3] * MC4} * \n                                 gX[ia1] * gY[ia2] * exp(j PD) */\n\t\tCOMPLEX_ADD2 (ct1, SM1, SM3);\n\t\tCOMPLEX_MUL2 (ct2, Jp, ct1);\n\t\tCOMPLEX_ADD2 (ct1, SM2, SM4);\n\t\tCOMPLEX_MUL2 (ct3, Jm, ct1);\n\t\tCOMPLEX_ADD2 (ct2, ct2, ct3);\n\t\tCOMPLEX_MUL2 (DFDP,  ct2, ggPD);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* XY wrt Ey2 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = {-S[0] * CX[ia1] * CY[ia2] +       \n\t                    S[1] * CX[ia1] * SY[ia2] -\n\t\t\t    S[2] * SX[ia1] * CY[ia2] + \n\t\t\t    S[3] * SX[ia1] * SY[ia2]} * \n\t\t\t        gX[ia1] * gY[ia2] * exp(j PD) */\n\t\tCOMPLEX_MUL3(ct5, S[0], CX[ia1], CY[ia2]);\n\t\tCOMPLEX_NEGATE(ct1, ct5);\n\t\tCOMPLEX_MUL3(ct5, S[1], CX[ia1], SY[ia2]);\n\t\tCOMPLEX_NEGATE(ct2, ct5);\n\t\tCOMPLEX_MUL3(ct3, S[2], SX[ia1], CY[ia2]);\n\t\tCOMPLEX_MUL3(ct4, S[3], SX[ia1], SY[ia2]);\n\t\tCOMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4);\n\t\tCOMPLEX_MUL2(DFDP, ct5, ggPD);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end second antenna parameter switch */\n\t} /* end loop over second antenna parameters */\n\t\n\t/* Loop over source parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* XY wrt IPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part =   (MC1*DPAc + MC4*DPA) * gX[ia1] * gX[ia2] * exp(j PD) */\n\t\tCOMPLEX_MUL2(ct2, MC1, DPAc);\n\t\tCOMPLEX_MUL2(ct3, MC4, DPA);\n\t\tCOMPLEX_ADD2(ct1, ct2, ct3);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ggPD);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* XY wrt QPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = (MC2*SPAc + MC3*SPA) * gX[ia1] * gX[ia2] * exp(j PD) */\n\t\tCOMPLEX_MUL2(ct2, MC2, SPAc);\n\t\tCOMPLEX_MUL2(ct3, MC3, SPA);\n\t\tCOMPLEX_ADD2(ct1, ct2, ct3);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ggPD);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* XY wrt UPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* (j MC2*SPAc - j MC3*SPA) * gX[ia1] * gX[ia2] * exp(j PD) */\n\t\tCOMPLEX_MUL3(ct2, Jp, MC2, SPAc);\n\t\tCOMPLEX_MUL3(ct3, Jp, MC3, SPA);\n\t\tCOMPLEX_SUB(ct1, ct2, ct3);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ggPD);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t\tgradR = -gradR; gradI = -gradI;  /*  DEBUG why does this help??? */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* XY wrt VPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* (MC1*DPAc - MC4*DPA) * gX[ia1] * gX[ia2] * exp(j PD) */\n\t\tCOMPLEX_MUL2(ct2, MC1, DPAc);\n\t\tCOMPLEX_MUL2(ct3, MC4, DPA);\n\t\tCOMPLEX_SUB(ct1, ct2, ct3);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ggPD);\n\t\tgradR = DFDP.real;    /* RyxR wrt gY1 */\n\t\tgradI = DFDP.imag;    /* RyxI wrt gY1 */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t   } \n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end source parameter switch */\n\t} /* end loop over source parameters */\n\t\n\t/* gradient wrt PD */\n\tif (args->doFitRL) {\n\t  if (wt[idata*4+kk]>0.0) {\n\t    /* part = (0,  1) * VXY */   \n\t    COMPLEX_MUL2 (DFDP, Jp, VXY);\n\t    gradR = DFDP.real;\n\t    gradI = DFDP.imag;\n\t    /*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t  } else gradR = gradI = 0.0;    /* invalid data */\n\t  j = args->PDPNumb;\n\t  gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t  gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t}\n\t\n\t/* Loop over antenna gains */\n\tfor (k=0; k<2; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* XY wrt gX1 */\n\t    /* Fitting? */\n\t    if (antGainFit[ia1][0]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = (S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) \n\t\t             * gY[ia2]  * exp(j PD) */\n\t\tCOMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4);\n\t\tCOMPLEX_SET (ct2, antGain[ia2*2+1], 0);\n\t\tCOMPLEX_EXP (ct3, PD);\n\t\tCOMPLEX_MUL3 (DFDP, ct1, ct2, ct3);\n\t\tgradR = DFDP.real;    /* RxyR wrt gX1 */\n\t\tgradI = DFDP.imag;    /* RxyI wrt gX1 */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = antGainPNumb[ia1][0];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t      }\n\t    break;\n\t  case 1:  /* XY wrt gY2 */\n\t    if (antGainFit[ia2][1]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = {S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) \n\t                    * gX[ia1] * exp(j PD) */\n\t\tCOMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4);\n\t\tCOMPLEX_SET (ct2, antGain[ia1*2+0], 0);\n\t\tCOMPLEX_EXP (ct3, PD);\n\t\tCOMPLEX_MUL3 (DFDP, ct1, ct2, ct3);\n\t\tgradR = DFDP.real;    /* RxyR wrt gY2 */\n\t\tgradI = DFDP.imag;    /* RxyI wrt gY2 */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = antGainPNumb[ia2][1];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t      }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end gain switch */\n\t} /* end loop over gains */\n\t\n\tbreak;  /* End XY */\n      \t\n      case 3:     /* YX */\n\tif (wt[idata*4+kk]>0.0) {\n\t  isigma = wt[idata*4+kk];\n\t  /* VYX = {S[0] * SY[ia1] * CXc[ia2] +       \n\t            S[1] * SY[ia1] * SXc[ia2] +\n\t\t    S[2] * CY[ia1] * CXc[ia2] + \n\t\t    S[3] * CY[ia1] * SXc[ia2]} * g1Y * g2X * exp(-j PD)\n\t  */\n\t  COMPLEX_MUL2 (MC1, SY[ia1], CXc[ia2]);\n\t  COMPLEX_MUL2 (MC2, SY[ia1], SXc[ia2]);\n\t  COMPLEX_MUL2 (MC3, CY[ia1], CXc[ia2]);\n\t  COMPLEX_MUL2 (MC4, CY[ia1], SXc[ia2]);\n\t  COMPLEX_MUL2 (SM1, S[0], MC1);\n\t  COMPLEX_MUL2 (SM2, S[1], MC2);\n\t  COMPLEX_MUL2 (SM3, S[2], MC3);\n\t  COMPLEX_MUL2 (SM4, S[3], MC4);\n\t  COMPLEX_ADD4 (ct5, SM1, SM2, SM3, SM4);\n\t  COMPLEX_SET (ct1,  antGain[ia1*2+1]*antGain[ia2*2+0], 0);\n\t  COMPLEX_EXP (ct2, -PD);\n\t  COMPLEX_MUL2 (ggPD, ct1, ct2);\n\t  COMPLEX_MUL2 (VYX, ct5, ggPD);\n\t  modelR = VYX.real; modelI = VYX.imag;\n\t  residR = modelR - data[idata*10+(kk+1)*2];\n\t  residI = modelI - data[idata*10+(kk+1)*2+1];\n\t  gsl_vector_set(f, i*2,   residR*isigma); /* Save function resids */\n\t  gsl_vector_set(f, i*2+1, residI*isigma); /* Save function resids */\n\t} else  residR = residI = 0.0; /* Invalid data */\n\t\n\t/* Loop over first antenna parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* YX wrt Ox1 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* YX wrt Ex1 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* YX wrt Oy1 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = {(0, -1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + \n\t\t   (        0,  1) * S[2] * MC3 + (0,  1) * S[3] * MC4} * \n\t                          gX[ia1] * gY[ia2] * exp(-j PD) */\n\t\tCOMPLEX_ADD2 (ct1, SM1, SM2);\n\t\tCOMPLEX_MUL2 (ct2, Jm, ct1);\n\t\tCOMPLEX_ADD2 (ct1, SM3, SM4);\n\t\tCOMPLEX_MUL2 (ct3, Jp, ct1);\n\t\tCOMPLEX_ADD2 (ct2, ct2, ct3);\n\t\tCOMPLEX_MUL2 (DFDP, ct2, ggPD);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* YX wrt Ey1 */\n\t    /* Fitting? */\n\t    if (antFit[ia1][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = {-S[0] * CXc[ia2] * CYc[ia1] -       \n\t                    S[1] * SXc[ia2] * CYc[ia1] +\n\t\t\t    S[2] * CXc[ia2] * SYc[ia1] + \n\t\t\t    S[3] * SXc[ia2] * SYc[ia1]} * \n\t\t\t           gY[ia1] * gX[ia2] * exp(-j PD) */\n\t\tCOMPLEX_MUL3(ct5, S[0], CXc[ia2], CYc[ia1]);\n\t\tCOMPLEX_NEGATE(ct1, ct5);\n\t\tCOMPLEX_MUL3(ct5, S[1], SXc[ia2], CYc[ia1]);\n\t\tCOMPLEX_NEGATE(ct2, ct5);\n\t\tCOMPLEX_MUL3(ct3, S[2], CXc[ia2], SYc[ia1]);\n\t\tCOMPLEX_MUL3(ct4, S[3], SXc[ia2], SYc[ia1]);\n\t\tCOMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4);\n\t\tCOMPLEX_MUL2(DFDP, ct5, ggPD);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = antPNumb[ia1][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end first antenna parameter switch */\n\t} /* end loop over first antenna parameters */\n\t\n\t/* Loop over second antenna parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* YX wrt Ox2 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = {(0,  1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + \n\t\t           (0,  1) * S[2] * MC3 + (0, -1) * S[3] * MC4} * \n\t\t\t         gY[ia1] * gX[ia2]  * exp(-j PD) */\n\t\tCOMPLEX_ADD2 (ct1, SM1, SM3);\n\t\tCOMPLEX_MUL2 (ct2, Jp, ct1);\n\t\tCOMPLEX_ADD2 (ct1, SM2, SM4);\n\t\tCOMPLEX_MUL2 (ct3, Jm, ct1);\n\t\tCOMPLEX_ADD2 (ct2, ct2, ct3);\n\t\tCOMPLEX_MUL2 (DFDP, ct2, ggPD);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* YX wrt Ex2 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = {-S[0] * SY[ia1] * SX[ia2] + \n\t                    S[1] * SY[ia1] * CX[ia2] -\n\t\t\t    S[2] * CY[ia1] * SX[ia2] + \n\t\t\t    S[3] * CY[ia1] * CX[ia2]} * \n\t\t\t        gY[ia1] * gX[ia2] * exp(-j PD)*/\n\t\tCOMPLEX_MUL3(ct5, S[0], SY[ia1], SX[ia2]);\n\t\tCOMPLEX_NEGATE(ct1, ct5);\n\t\tCOMPLEX_MUL3(ct2, S[1], SY[ia1], CX[ia2]);\n\t\tCOMPLEX_MUL3(ct5, S[2], CY[ia1], SX[ia2]);\n\t\tCOMPLEX_NEGATE(ct3, ct5);\n\t\tCOMPLEX_MUL3(ct4, S[3], CY[ia1], CX[ia2]);\n\t\tCOMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4);\n\t\tCOMPLEX_MUL2(DFDP, ct5, ggPD);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* YX wrt Oy2 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* YX wrt Ey2 = 0 */\n\t    /* Fitting? */\n\t    if (antFit[ia2][k]) {\n\t      gradR = gradI = 0.0;\n\t      j = antPNumb[ia2][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end second antenna parameter switch */\n\t} /* end loop over second antenna parameters */\n\t\n\t/* Loop over source parameters */\n\tfor (k=0; k<4; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* YX wrt IPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part =   (MC1*DPAc + MC4*DPA) * gX[ia1] * gX[ia2] * exp(-j PD) */\n\t\tCOMPLEX_MUL2(ct2, MC1, DPAc);\n\t\tCOMPLEX_MUL2(ct3, MC4, DPA);\n\t\tCOMPLEX_ADD2(ct1, ct2, ct3);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ggPD);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 1:     /* YX wrt QPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = (MC2*SPAc + MC3*SPA) * gX[ia1] * gX[ia2] * exp(-j PD) */\n\t\tCOMPLEX_MUL2(ct2, MC2, SPAc);\n\t\tCOMPLEX_MUL2(ct3, MC3, SPA);\n\t\tCOMPLEX_ADD2(ct1, ct2, ct3);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ggPD);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 2:     /* YX wrt UPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* (j MC2*SPAc - j MC3*SPA) * gX[ia1] * gX[ia2] * exp(-j PD) */\n\t\tCOMPLEX_MUL3(ct2, Jp, MC2, SPAc);\n\t\tCOMPLEX_MUL3(ct3, Jp, MC3, SPA);\n\t\tCOMPLEX_SUB(ct1, ct2, ct3);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ggPD);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t\tgradR = -gradR; gradI = -gradI; /*   DEBUG  why does this help??? */\n\t\t/*gradR = gradI = 0.0;  DEBUG */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\t    break;\n\t  case 3:     /* YX wrt VPol */\n\t    /* Fitting? */\n\t    if (souFit[isou][k]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* (MC1*DPAc - MC4*DPA) * gX[ia1] * gX[ia2] * exp(-j PD) */\n\t\tCOMPLEX_MUL2(ct2, MC1, DPAc);\n\t\tCOMPLEX_MUL2(ct3, MC4, DPA);\n\t\tCOMPLEX_SUB(ct1, ct2, ct3);\n\t\tCOMPLEX_MUL2(DFDP, ct1, ggPD);\n\t\tgradR = DFDP.real;\n\t\tgradI = DFDP.imag;\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;   /* invalid data */\n\t      j = souPNumb[isou][k];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t    }\n\tbreak;\n      default:\n\tbreak;\n\t  }; /* end source parameter switch */\n\t} /* end loop over source parameters */\n\t\n\t/* gradient wrt PD */\n\tif (args->doFitRL) {\n\t  if (wt[idata*4+kk]>0.0) {\n\t    /* part = (0, -1) * VYX */   \n\t    COMPLEX_MUL2 (DFDP, Jm, VYX);\n\t    gradR = DFDP.real;\n\t    gradI = DFDP.imag;\n\t    /*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t  } else gradR = gradI = 0.0;    /* invalid data */\n\t  j = args->PDPNumb;\n\t  gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t  gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t}\n\t/* Loop over antenna gains */\n\tfor (k=0; k<2; k++) {\n\t  switch (k) {   /* Switch over parameter */\n\t  case 0:     /* YX wrt gY1 */\n\t    /* Fitting? */\n\t    if (antGainFit[ia1][1]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = (S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) \n                           * gY[ia1]  * exp(-j PD) */\n\t\tCOMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4);\n\t\tCOMPLEX_SET (ct2, antGain[ia1*2+1], 0);\n\t\tCOMPLEX_EXP (ct3, -PD);\n\t\tCOMPLEX_MUL3 (DFDP, ct1, ct2, ct3);\n\t\tgradR = DFDP.real;    /* RyxR wrt gY1 */\n\t\tgradI = DFDP.imag;    /* RyxI wrt gY1 */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = antGainPNumb[ia1][1];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t      }\n\t    break;\n\t  case 1:  /* YX wrt gX2 */\n\t    if (antGainFit[ia2][0]) {\n\t      if (wt[idata*4+kk]>0.0) {\n\t\t/* part = (S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) \n                              * gY[ia1]  * exp(-j PD) */\n\t\tCOMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4);\n\t\tCOMPLEX_SET (ct2, antGain[ia1*2+1], 0);\n\t\tCOMPLEX_EXP (ct3, -PD);\n\t\tCOMPLEX_MUL3 (DFDP, ct1, ct2, ct3);\n\t\tgradR = DFDP.real;    /* RyxR wrt gX2 */\n\t\tgradI = DFDP.imag;    /* RyxI wrt gX2 */\n\t\t/*gradR = -gradR; gradI = -gradI;    DEBUG */\n\t      } else gradR = gradI = 0.0;    /* invalid data */\n\t      j = antGainPNumb[ia2][0];\n\t      gsl_matrix_set(J, i*2,   j, gradR*isigma);  /* Save Jacobian */\n\t      gsl_matrix_set(J, i*2+1, j, gradI*isigma);  /* Save Jacobian */\n\t      }\n\t    break;\n\t  default:\n\t    break;\n\t  }; /* end gain switch */\n\t} /* end loop over gains */\n\t/* End YX */\t\n\t\n      default:\n\t  break;\n\t}; /* end switch over data correlation */\n      \n      i++;  /* Update complex datum number */\n    } /* end loop over correlations */\n  } /* End loop over visibilities */\n\n  return GSL_SUCCESS;\n} /*  end PolnFitFuncJacOEXY */\n\n#endif /* HAVE_GSL */ \n", "meta": {"hexsha": "f697932a75854d23bb9b36ebc38c6cfef5235876", "size": 402773, "ext": "c", "lang": "C", "max_stars_repo_path": "ObitSystem/Obit/src/ObitPolnCalFit.c", "max_stars_repo_name": "kettenis/Obit", "max_stars_repo_head_hexsha": "3f835799918065b149a1e73a6a140cb5eed466c5", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ObitSystem/Obit/src/ObitPolnCalFit.c", "max_issues_repo_name": "kettenis/Obit", "max_issues_repo_head_hexsha": "3f835799918065b149a1e73a6a140cb5eed466c5", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ObitSystem/Obit/src/ObitPolnCalFit.c", "max_forks_repo_name": "kettenis/Obit", "max_forks_repo_head_hexsha": "3f835799918065b149a1e73a6a140cb5eed466c5", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-22T14:07:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-22T14:07:41.000Z", "avg_line_length": 35.2907211075, "max_line_length": 180, "alphanum_fraction": 0.5543792657, "num_tokens": 159772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.17106119167858438, "lm_q2_score": 0.01566364753419677, "lm_q1q2_score": 0.002679442213233019}}
{"text": "#pragma once\n\n#define NOMINMAX\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <string_view>\n#include <sstream>\n#include <variant>\n#include <codecvt>\n#include <locale>\n#include <filesystem>\n#include <fstream>\n#include <chrono>\n#include <functional>\n#include <numeric>\n\n#include <wrl/client.h>\n#include <wil/result.h>\n#include <Windows.h>\n#include <d3d12.h>\n#include <dxcore.h>\n\n#include <gsl/gsl>\n\n#define DML_TARGET_VERSION_USE_LATEST\n#include <DirectML.h>\n#include <directx/d3dx12.h>\n#include \"DirectMLX.h\"\n\n#include <rapidjson/document.h>\n#include <rapidjson/istreamwrapper.h>\n\n#include <fmt/format.h>", "meta": {"hexsha": "0750632a6eb6504d47101405059fd770add3c92e", "size": 622, "ext": "h", "lang": "C", "max_stars_repo_path": "src/dxdispatch/pch.h", "max_stars_repo_name": "jstoecker/dxdispatch", "max_stars_repo_head_hexsha": "24a73560ee14d4fe99ae859ef6f5df341e4fbbda", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-21T08:11:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-21T08:11:12.000Z", "max_issues_repo_path": "src/dxdispatch/pch.h", "max_issues_repo_name": "jstoecker/dxdispatch", "max_issues_repo_head_hexsha": "24a73560ee14d4fe99ae859ef6f5df341e4fbbda", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dxdispatch/pch.h", "max_forks_repo_name": "jstoecker/dxdispatch", "max_forks_repo_head_hexsha": "24a73560ee14d4fe99ae859ef6f5df341e4fbbda", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.7714285714, "max_line_length": 37, "alphanum_fraction": 0.7459807074, "num_tokens": 155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11124121240045177, "lm_q2_score": 0.024053550795599545, "lm_q1q2_score": 0.0026757461530383447}}
{"text": "#pragma once\n\n#include <gsl\\gsl>\n#include <winrt\\base.h>\n#include <d3d11.h>\n#include \"DrawableGameComponent.h\"\n#include \"BasicTessellationMaterial.h\"\n#include \"RenderStateHelper.h\"\n\nnamespace Rendering\n{\n\tclass BasicTessellationDemo final : public Library::DrawableGameComponent\n\t{\n\tpublic:\n\t\tBasicTessellationDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera);\n\t\tBasicTessellationDemo(const BasicTessellationDemo&) = delete;\n\t\tBasicTessellationDemo(BasicTessellationDemo&&) = default;\n\t\tBasicTessellationDemo& operator=(const BasicTessellationDemo&) = default;\t\t\n\t\tBasicTessellationDemo& operator=(BasicTessellationDemo&&) = default;\n\t\t~BasicTessellationDemo();\n\n\t\tbool UseUniformTessellation() const;\n\t\tvoid SetUseUniformTessellation(bool useUniformTessellation);\n\t\tvoid ToggleUseUniformTessellation();\n\t\tbool ShowQuadTopology() const;\n\t\tvoid SetShowQuadTopology(bool showQuadTopology);\n\t\tvoid ToggleTopology();\n\n\t\tgsl::span<const float> EdgeFactors() const;\n\t\tvoid SetUniformEdgeFactors(float factor);\n\t\tvoid SetEdgeFactor(float factor, std::uint32_t index);\n\t\tvoid SetInsideFactor(float factor, std::uint32_t index);\n\n\t\tgsl::span<const float> InsideFactors() const;\n\n\t\tvirtual void Initialize() override;\n\t\tvirtual void Draw(const Library::GameTime& gameTime) override;\n\n\tprivate:\n\t\t/*void UpdateEdgeFactors();\n\t\tvoid UpdateInsideEdgeFactors();*/\n\n\t\tLibrary::RenderStateHelper mRenderStateHelper;\n\t\tBasicTessellationMaterial mMaterial;\n\t\twinrt::com_ptr<ID3D11Buffer> mTriVertexBuffer;\n\t\twinrt::com_ptr<ID3D11Buffer> mQuadVertexBuffer;\n\t\tbool mUpdateMaterial{ true };\n\t\tbool mUseUniformTessellation{ true };\n\t};\n}", "meta": {"hexsha": "52c52a26defb45b733c09807e20653634b8b6b4c", "size": 1639, "ext": "h", "lang": "C", "max_stars_repo_path": "source/10.2_Basic_Tessellation/BasicTessellationDemo.h", "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/10.2_Basic_Tessellation/BasicTessellationDemo.h", "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/10.2_Basic_Tessellation/BasicTessellationDemo.h", "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.78, "max_line_length": 93, "alphanum_fraction": 0.7858450275, "num_tokens": 421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.20181321265898594, "lm_q2_score": 0.01322282311331546, "lm_q1q2_score": 0.0026685404129196872}}
{"text": "/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */\n/*\n *     Copyright 2017-Present Couchbase, Inc.\n *\n *   Use of this software is governed by the Business Source License included\n *   in the file licenses/BSL-Couchbase.txt.  As of the Change Date specified\n *   in that file, in accordance with the Business Source License, use of this\n *   software will be governed by the Apache License, Version 2.0, included in\n *   the file licenses/APL2.txt.\n */\n\n#pragma once\n\n#include \"atomic.h\"\n#include \"monotonic.h\"\n\n#include <memcached/types.h>\n#include <gsl/gsl>\n\n#include <functional>\n#include <unordered_map>\n\nstruct DocKey;\n\nnamespace Collections {\n\n// The reserved name of the system owned, default collection.\nconst char* const DefaultCollectionName = \"_default\";\nstatic std::string_view DefaultCollectionIdentifier(DefaultCollectionName);\n\nconst char* const DefaultScopeName = \"_default\";\nstatic std::string_view DefaultScopeIdentifier(DefaultScopeName);\n\n// The SystemEvent keys are given some human readable tags to make disk or\n// memory dumps etc... more helpful.\nconst char* const CollectionEventDebugTag = \"_collection\";\nconst char* const ScopeEventDebugTag = \"_scope\";\n\n// Couchstore private file name for manifest data\nconst char CouchstoreManifest[] = \"_local/collections_manifest\";\n\n// Name of file where the manifest will be kept on persistent buckets\nconst char* const ManifestFile = \"collections.manifest\";\nstatic std::string_view ManifestFileName(ManifestFile);\n\n// Length of the string excluding the zero terminator (i.e. strlen)\nconst size_t CouchstoreManifestLen = sizeof(CouchstoreManifest) - 1;\n\nusing ManifestUid = WeaklyMonotonic<uint64_t>;\n\n// Struct/Map used in summary stat collecting (where we do vb accumulation)\nstruct AccumulatedStats {\n    AccumulatedStats& operator+=(const AccumulatedStats& other);\n    uint64_t itemCount{0};\n    uint64_t diskSize{0};\n    uint64_t opsStore{0};\n    uint64_t opsDelete{0};\n    uint64_t opsGet{0};\n};\nusing Summary = std::unordered_map<CollectionID, AccumulatedStats>;\n\nstruct ManifestUidNetworkOrder {\n    explicit ManifestUidNetworkOrder(ManifestUid uid) : uid(htonll(uid)) {\n    }\n    ManifestUid to_host() const {\n        return ManifestUid(ntohll(uid));\n    }\n    ManifestUid::value_type uid;\n};\nstatic_assert(sizeof(ManifestUidNetworkOrder) == 8,\n              \"ManifestUidNetworkOrder must have fixed size of 8 bytes as \"\n              \"written to disk.\");\n\n/**\n * Return a ManifestUid from a C-string.\n * A valid ManifestUid is a C-string where each character satisfies\n * std::isxdigit and can be converted to a ManifestUid by std::strtoull.\n *\n * @param uid C-string uid\n * @param len a length for validation purposes\n * @throws std::invalid_argument if uid is invalid\n */\nManifestUid makeUid(const char* uid, size_t len = 16);\n\n/**\n * Return a ManifestUid from a std::string\n * A valid ManifestUid is a std::string where each character satisfies\n * std::isxdigit and can be converted to a ManifestUid by std::strtoull.\n *\n * @param uid std::string\n * @throws std::invalid_argument if uid is invalid\n */\nstatic inline ManifestUid makeUid(const std::string& uid) {\n    return makeUid(uid.c_str());\n}\n\n/**\n * Return a CollectionID from a C-string.\n * A valid CollectionID is a C-string where each character satisfies\n * std::isxdigit and can be converted to a CollectionID by std::strtoul.\n *\n * @param uid C-string uid\n * @throws std::invalid_argument if uid is invalid\n */\nstatic inline CollectionID makeCollectionID(const char* uid) {\n    // CollectionID is 8 characters max and smaller than a ManifestUid\n    return gsl::narrow_cast<CollectionID>(makeUid(uid, 8));\n}\n\n/**\n * Return a CollectionID from a std::string\n * A valid CollectionID is a std::string where each character satisfies\n * std::isxdigit and can be converted to a CollectionID by std::strtoul\n *\n * @param uid std::string\n * @throws std::invalid_argument if uid is invalid\n */\nstatic inline CollectionID makeCollectionID(const std::string& uid) {\n    return makeCollectionID(uid.c_str());\n}\n\n/**\n * Return a ScopeID from a C-string.\n * A valid CollectionID is a std::string where each character satisfies\n * std::isxdigit and can be converted to a CollectionID by std::strtoul\n * @param uid C-string uid\n * @return std::invalid_argument if uid is invalid\n */\nstatic inline ScopeID makeScopeID(const char* uid) {\n    // ScopeId is 8 characters max and smaller than a ManifestUid\n    return gsl::narrow_cast<ScopeID>(makeUid(uid, 8));\n}\n\n/**\n * Return a ScopeID from a std::string\n * A valid ScopeID is a std::string where each character satisfies\n * std::isxdigit and can be converted to a CollectionID by std::strtoul\n * @param uid std::string\n * @return std::invalid_argument if uid is invalid\n */\nstatic inline ScopeID makeScopeID(const std::string& uid) {\n    return makeScopeID(uid.c_str());\n}\n\n/**\n * The metadata of a single collection\n *\n * Default construction yields the default collection\n */\nstruct CollectionMetaData {\n    ScopeID sid{ScopeID::Default}; // The scope that the collection belongs to\n    CollectionID cid{CollectionID::Default}; // The collection's ID\n    std::string name{DefaultCollectionName}; // The collection's name\n    cb::ExpiryLimit maxTtl{}; // The collection's maxTTL\n\n    bool operator==(const CollectionMetaData& other) const {\n        return sid == other.sid && cid == other.cid && name == other.name &&\n               maxTtl == other.maxTtl;\n    }\n};\n\n/**\n * The metadata of a single scope\n *\n * Default construction yields the default scope\n */\nstruct ScopeMetaData {\n    ScopeID sid{ScopeID::Default}; // The scope's ID\n    std::string name{DefaultScopeName}; // The scope's name\n\n    bool operator==(const ScopeMetaData& other) const {\n        return sid == other.sid && name == other.name;\n    }\n};\n\n/**\n * For creation of collection SystemEvents - The SystemEventFactory\n * glues the CollectionID into the event key (so create of x doesn't\n * collide with create of y). This method yields the 'keyExtra' parameter\n *\n * @param collection The value to turn into a string\n * @return the keyExtra parameter to be passed to SystemEventFactory\n */\nstd::string makeCollectionIdIntoString(CollectionID collection);\n\n/**\n * For creation of collection SystemEvents - The SystemEventFactory\n * glues the CollectionID into the event key (so create of x doesn't\n * collide with create of y). This method basically reverses\n * makeCollectionIdIntoString so we can get a CollectionID from a\n * SystemEvent key\n *\n * @param key DocKey from an Item in the System namespace and is a collection\n *        event\n * @return the ID which was in the event\n */\nCollectionID getCollectionIDFromKey(const DocKey& key);\n\n/// Same as getCollectionIDFromKey but for events changing scopes\nScopeID getScopeIDFromKey(const DocKey& key);\n\n/**\n * Callback function for processing against dropped collections in an ephemeral\n * vb, returns true if the key at seqno should be dropped\n *\n * @param DocKey the key of the item we should process\n * @param int64_t the seqno of the item\n */\nusing IsDroppedEphemeralCb = std::function<bool(const DocKey&, int64_t)>;\n\n/**\n * A function for determining if a collection is visible\n */\nusing IsVisibleFunction =\n        std::function<bool(ScopeID, std::optional<CollectionID>)>;\n\nnamespace VB {\nenum class ManifestUpdateStatus {\n    Success,\n    // The new Manifest has a 'UID' that is < current.\n    Behind,\n    // The new Manifest has a 'UID' that is == current, but adds/drops\n    // collections/scopes.\n    EqualUidWithDifferences,\n    // The new Manifest changes scopes or collections immutable properties, e.g.\n    // current has {id:8, name:\"c1\"} and new has {id:8,name:\"c2\"}.\n    ImmutablePropertyModified\n};\nstd::string to_string(ManifestUpdateStatus);\n\n/// values required by the flusher to calculate new collection statistics\nstruct StatsForFlush {\n    uint64_t itemCount;\n    size_t diskSize;\n    uint64_t highSeqno;\n};\n\n// Following classes define the metadata that will be held by the Manager but\n// referenced from VB::Manifest\nclass CollectionSharedMetaData;\nclass CollectionSharedMetaDataView {\npublic:\n    CollectionSharedMetaDataView(std::string_view name,\n                                 ScopeID scope,\n                                 cb::ExpiryLimit maxTtl);\n    CollectionSharedMetaDataView(const CollectionSharedMetaData&);\n    std::string to_string() const;\n    std::string_view name;\n    const ScopeID scope;\n    const cb::ExpiryLimit maxTtl;\n};\n\n// The type stored by the Manager SharedMetaDataTable\nclass CollectionSharedMetaData : public RCValue {\npublic:\n    CollectionSharedMetaData(std::string_view name,\n                             ScopeID scope,\n                             cb::ExpiryLimit maxTtl);\n    CollectionSharedMetaData(const CollectionSharedMetaDataView& view);\n    bool operator==(const CollectionSharedMetaDataView& view) const;\n    bool operator!=(const CollectionSharedMetaDataView& view) const {\n        return !(*this == view);\n    }\n    bool operator==(const CollectionSharedMetaData& meta) const;\n    bool operator!=(const CollectionSharedMetaData& meta) const {\n        return !(*this == meta);\n    }\n\n    const std::string name;\n    const ScopeID scope;\n    const cb::ExpiryLimit maxTtl;\n};\nstd::ostream& operator<<(std::ostream& os,\n                         const CollectionSharedMetaData& meta);\n\nclass ScopeSharedMetaData;\nclass ScopeSharedMetaDataView {\npublic:\n    ScopeSharedMetaDataView(const ScopeSharedMetaData&);\n    ScopeSharedMetaDataView(std::string_view name) : name(name) {\n    }\n    std::string to_string() const;\n    std::string_view name;\n};\n\n// The type stored by the Manager SharedMetaDataTable\nclass ScopeSharedMetaData : public RCValue {\npublic:\n    ScopeSharedMetaData(const ScopeSharedMetaDataView& view);\n    bool operator==(const ScopeSharedMetaDataView& view) const;\n    bool operator!=(const ScopeSharedMetaDataView& view) const {\n        return !(*this == view);\n    }\n    bool operator==(const ScopeSharedMetaData& meta) const;\n    bool operator!=(const ScopeSharedMetaData& meta) const {\n        return !(*this == meta);\n    }\n\n    const std::string name;\n};\nstd::ostream& operator<<(std::ostream& os, const ScopeSharedMetaData& meta);\n\n} // namespace VB\n\n} // end namespace Collections\n", "meta": {"hexsha": "9e0d59a26965f179b1b98e9ff9fd733970458566", "size": 10300, "ext": "h", "lang": "C", "max_stars_repo_path": "engines/ep/src/collections/collections_types.h", "max_stars_repo_name": "vpn03/kv_engine", "max_stars_repo_head_hexsha": "a3131a099154c39a0f7b0458bf0cc4ea38363a64", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "engines/ep/src/collections/collections_types.h", "max_issues_repo_name": "vpn03/kv_engine", "max_issues_repo_head_hexsha": "a3131a099154c39a0f7b0458bf0cc4ea38363a64", "max_issues_repo_licenses": ["MIT", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "engines/ep/src/collections/collections_types.h", "max_forks_repo_name": "vpn03/kv_engine", "max_forks_repo_head_hexsha": "a3131a099154c39a0f7b0458bf0cc4ea38363a64", "max_forks_repo_licenses": ["MIT", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.660130719, "max_line_length": 80, "alphanum_fraction": 0.7205825243, "num_tokens": 2383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14804719051380197, "lm_q2_score": 0.01798621364681958, "lm_q1q2_score": 0.0026628083983926435}}
{"text": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n#pragma once\n\n#include \"arcana/bob/bob_helpers.h\"\n\n#include <cstdint>\n#include <string>\n#include <vector>\n\n#include <cereal/cereal.hpp>\n#include <cereal/types/vector.hpp>\n\n#include <gsl/gsl>\n\nnamespace mira\n{\n    namespace bob\n    {\n        namespace v1\n        {\n            namespace\n            {\n                constexpr std::uint32_t VERSION = 1;\n            }\n\n            //\n            // manifest and stream_file_header are both types found in the json\n            // manifest file. This file describes in a human readable format what the bob\n            // stream contains and which data it depends on.\n            //\n            // entry_instance is the header data of each instance of an entry stream in the\n            // binary stream file (.bob).\n            //\n\n            //\n            //  Describes what the binary stream file contains\n            //\n            class stream_file_header\n            {\n            public:\n                //\n                //  An entry describes the properties of one type of packet found in the stream\n                //\n                class entry\n                {\n                public:\n                    entry()\n                        : m_name{}\n                        , m_type{}\n                        , m_version{}\n                    {}\n\n                    entry(std::string name, ::uint32_t version)\n                        : m_name{ std::move(name) }\n                        , m_type{}\n                        , m_version{ version }\n                    {}\n\n                    entry(std::string name, std::string type, ::uint32_t version)\n                        : m_name{ std::move(name) }\n                        , m_type{ std::move(type) }\n                        , m_version{ version }\n                    {}\n\n                    const std::string& name() const\n                    {\n                        return m_name;\n                    }\n\n                    const std::string& type() const\n                    {\n                        return m_type;\n                    }\n\n                    std::uint32_t version() const\n                    {\n                        return m_version;\n                    }\n\n                    template<typename Archive>\n                    void serialize(Archive& ar)\n                    {\n                        ar(cereal::make_nvp(\"Name\", m_name), cereal::make_nvp(\"Type\", m_type), cereal::make_nvp(\"Version\", m_version));\n                    }\n\n                private:\n                    std::string m_name;\n                    std::string m_type;\n                    std::uint32_t m_version;\n                };\n\n                stream_file_header() = default;\n\n                explicit stream_file_header(std::vector<entry> entries)\n                    : m_entries(std::move(entries))\n                {}\n\n                std::uint32_t version() const\n                {\n                    return VERSION;\n                }\n\n                const std::vector<entry>& entries() const\n                {\n                    return m_entries;\n                }\n\n                template<typename Archive>\n                void serialize(Archive& ar, const std::uint32_t version)\n                {\n                    if (version != VERSION)\n                        throw_invalid_version();\n\n                    ar(cereal::make_nvp(\"Entries\", m_entries));\n                }\n\n            private:\n                std::vector<entry> m_entries;\n            };\n\n            class manifest\n            {\n            public:\n                manifest() = default;\n\n                manifest(stream_file_header header)\n                    : m_stream{ std::move(header) }\n                {}\n\n                std::uint32_t version() const\n                {\n                    return VERSION;\n                }\n\n                const stream_file_header& stream() const\n                {\n                    return m_stream;\n                }\n\n                template<typename Archive>\n                void serialize(Archive& ar, const std::uint32_t version)\n                {\n                    if (version != VERSION)\n                        throw_invalid_version();\n\n                    ar(cereal::make_nvp(\"Stream\", m_stream));\n                }\n\n            private:\n                stream_file_header m_stream;\n            };\n\n            //\n            // describes an entry in the binary stream, the data for the entry\n            // is contained between this block and the next.\n            //\n            struct entry_instance\n            {\n                std::int64_t Timestamp;\n                std::int64_t NextBlockOffset;\n                std::int32_t EntryIdx;\n\n                template<typename Archive>\n                void serialize(Archive& ar, const std::uint32_t version)\n                {\n                    if (version != VERSION)\n                        throw_invalid_version();\n\n                    ar(CEREAL_NVP(Timestamp), CEREAL_NVP(NextBlockOffset), CEREAL_NVP(EntryIdx));\n                }\n            };\n        }\n\n        using namespace v1;\n    }\n}\n\nCEREAL_CLASS_VERSION(::mira::bob::v1::manifest, ::mira::bob::v1::VERSION);\nCEREAL_CLASS_VERSION(::mira::bob::v1::stream_file_header, ::mira::bob::v1::VERSION);\n", "meta": {"hexsha": "a19f8ff4c4e5df5d8e31334334fdee11258e565a", "size": 5332, "ext": "h", "lang": "C", "max_stars_repo_path": "Dependencies/Arcana/Shared/arcana/bob/bob_data.h", "max_stars_repo_name": "syntheticmagus/mageslam", "max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z", "max_issues_repo_path": "Dependencies/Arcana/Shared/arcana/bob/bob_data.h", "max_issues_repo_name": "syntheticmagus/mageslam", "max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z", "max_forks_repo_path": "Dependencies/Arcana/Shared/arcana/bob/bob_data.h", "max_forks_repo_name": "syntheticmagus/mageslam", "max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z", "avg_line_length": 29.2967032967, "max_line_length": 135, "alphanum_fraction": 0.4292948237, "num_tokens": 951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11757213972942691, "lm_q2_score": 0.022629202010461903, "lm_q1q2_score": 0.0026605637007394555}}
{"text": "#pragma once\n\n#include <gsl\\gsl>\n#include <winrt\\base.h>\n#include <d3d11.h>\n#include \"DrawableGameComponent.h\"\n#include \"FullScreenQuad.h\"\n\nnamespace Rendering\n{\n\tclass ComputeShaderMaterial;\n\n\tclass ComputeShaderDemo final : public Library::DrawableGameComponent\n\t{\n\tpublic:\n\t\tComputeShaderDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera);\n\t\tComputeShaderDemo(const ComputeShaderDemo&) = delete;\n\t\tComputeShaderDemo(ComputeShaderDemo&&) = default;\n\t\tComputeShaderDemo& operator=(const ComputeShaderDemo&) = default;\t\t\n\t\tComputeShaderDemo& operator=(ComputeShaderDemo&&) = default;\n\t\t~ComputeShaderDemo();\n\n\t\tbool AnimationEnabled() const;\n\t\tvoid SetAnimationEnabled(bool enabled);\n\n\t\tfloat BlueColor() const;\n\t\tvoid SetBlueColor(float blueColor);\n\n\t\tvirtual void Initialize() override;\n\t\tvirtual void Update(const Library::GameTime& gameTime) override;\n\t\tvirtual void Draw(const Library::GameTime& gameTime) override;\n\n\tprivate:\n\t\tstd::unique_ptr<ComputeShaderMaterial> mMaterial;\t\t\n\t\tLibrary::FullScreenQuad mFullScreenQuad;\n\t\twinrt::com_ptr<ID3D11ShaderResourceView> mColorTexture;\n\t\tbool mAnimationEnabled{ true };\n\t};\n}", "meta": {"hexsha": "53f5e8ceb3eae3cc2f2c560e93382dd65656822e", "size": 1149, "ext": "h", "lang": "C", "max_stars_repo_path": "source/11.2_Compute_Shaders/ComputeShaderDemo.h", "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/11.2_Compute_Shaders/ComputeShaderDemo.h", "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/11.2_Compute_Shaders/ComputeShaderDemo.h", "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4615384615, "max_line_length": 89, "alphanum_fraction": 0.7754569191, "num_tokens": 277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.17781088690575272, "lm_q2_score": 0.01495708673036521, "lm_q1q2_score": 0.0026595328570525032}}
{"text": "#pragma once\n/*\n * (C) Copyright 2020-2021 UCAR\n *\n * This software is licensed under the terms of the Apache Licence Version 2.0\n * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.\n */\n/*! \\addtogroup ioda_cxx_variable\n *\n * @{\n * \\file Has_Variables.h\n * \\brief Interfaces for ioda::Has_Variables and related classes.\n */\n\n#include <cstring>\n#include <gsl/gsl-lite.hpp>\n#include <iostream>\n#include <map>\n#include <memory>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include \"ioda/Attributes/Attribute_Creator.h\"\n#include \"ioda/Exception.h\"\n#include \"ioda/Layout.h\"\n#include \"ioda/Misc/Eigen_Compat.h\"\n#include \"ioda/Misc/MergeMethods.h\"\n#include \"ioda/Types/Type.h\"\n#include \"ioda/Variables/FillPolicy.h\"\n#include \"ioda/Variables/Variable.h\"\n#include \"ioda/defs.h\"\n\nnamespace ioda {\nclass Has_Variables;\nclass ObsGroup;\nstruct Named_Variable;\nnamespace detail {\nclass Has_Variables_Backend;\nclass Has_Variables_Base;\nclass DataLayoutPolicy;\nclass Group_Base;\n\n}  // namespace detail\n\n/// \\brief A few chunking strategies for Variables\nnamespace chunking {\n/// Convenience function for setting default chunking parameters.\ninline bool Chunking_Max(const std::vector<Dimensions_t>& in, std::vector<Dimensions_t>& out) {\n  out = in;\n  return true;\n}\n}  // namespace chunking\n\n/// \\brief Used to specify Variable creation-time properties.\n/// \\ingroup ioda_cxx_variable\nstruct IODA_DL VariableCreationParameters {\nprivate:\n  std::vector<std::pair<unsigned int, Variable> > dimsToAttach_;\n  std::string dimScaleName_;\n\npublic:\n  /// @name Fill Value\n  /// @{\n\n  detail::FillValueData_t fillValue_;\n\n  template <class DataType>\n  VariableCreationParameters& setFillValue(DataType fill) {\n    detail::assignFillValue<DataType>(fillValue_, fill);\n    return *this;\n  }\n  inline VariableCreationParameters& unsetFillValue() {\n    fillValue_.set_ = false;\n    return *this;\n  }\n\n  /// @}\n  /// @name Chunking and compression\n  /// @{\n\n  /// \\brief Do we chunk this variable? Required for extendible / compressible Variables.\n  /// \\details Requires a chunking strategy.\n  bool chunk = false;\n\n  /// \\brief Manually specify the chunks. Never directly use. Use getChunks(...) instead.\n  std::vector<Dimensions_t> chunks;\n  /// Set variable chunking strategy. Used only if chunk == true and chunks.size() == 0.\n  std::function<bool(const std::vector<Dimensions_t>&, std::vector<Dimensions_t>&)>\n    fChunkingStrategy = chunking::Chunking_Max;\n  /// Figure out the chunking size\n  /// \\param cur_dims are the current dimensions\n  std::vector<Dimensions_t> getChunks(const std::vector<Dimensions_t>& cur_dims) const {\n    if (chunks.size()) return chunks;\n    std::vector<Dimensions_t> res;\n    if (fChunkingStrategy(cur_dims, res)) return res;\n    throw Exception(\"Cannot figure out an appropriate chunking size.\", ioda_Here());\n  }\n\n  bool gzip_                        = false;\n  bool szip_                        = false;\n  int gzip_level_                   = 6;  // 1 (fastest) - 9 (most compression)\n  unsigned int szip_PixelsPerBlock_ = 16;\n  unsigned int szip_options_        = 4;  // Defined as H5_SZIP_EC_OPTION_MASK in hdf5.h;\n\n  void noCompress();\n  void compressWithGZIP(int level = 6);\n  void compressWithSZIP(unsigned PixelsPerBlock = 16, unsigned options = 4);\n\n  /// @}\n  /// @name General Functions\n  /// @{\n\n  /// Set any initial attributes here\n  Attribute_Creator_Store atts;\n\n  VariableCreationParameters();\n  VariableCreationParameters(const VariableCreationParameters&);\n  VariableCreationParameters& operator=(const VariableCreationParameters&);\n\n  template<class DataType>\n  static VariableCreationParameters defaulted() {\n    VariableCreationParameters ret;\n    ret.chunk = true;\n    ret.compressWithGZIP();\n    FillValuePolicies::applyFillValuePolicy<DataType>(FillValuePolicy::NETCDF4, ret.fillValue_);\n    return ret;\n  }\n  template <class DataType>\n  static VariableCreationParameters defaults() {\n    return defaulted<DataType>();\n  }\n\n  /// Finalize routine to make sure struct members are intact (e.g. for fill values)\n  detail::FillValueData_t::FillValueUnion_t finalize() const { return fillValue_.finalize(); }\n\n  detail::python_bindings::VariableCreationFillValues<VariableCreationParameters> _py_setFillValue;\n\nprivate:\n  friend class detail::Has_Variables_Base;\n  /// Apply the properties to a Variable (second pass; after Variable is created).\n  Variable applyImmediatelyAfterVariableCreation(Variable h) const;\n\n  /// @}\n};\n\ntypedef std::vector<Variable> NewVariables_Scales_t;\n/// \\brief Used to specify a new variable with the collective createWithScales function.\nstruct IODA_DL NewVariable_Base : std::enable_shared_from_this<NewVariable_Base> {\n  /// Name of the variable.\n  std::string name_;\n  /// Type of the new dimension. Int, char, etc. Used if a type is not passed directly.\n  std::type_index dataType_;\n  /// Type of the new dimension. Used if a type is passed directly.\n  Type dataTypeKnown_;\n  /// Dimension scales\n  NewVariables_Scales_t scales_;\n  /// Var creation params\n  VariableCreationParameters vcp_;\n\n  virtual ~NewVariable_Base() {}\n\n  NewVariable_Base(const std::string& name, const Type& dataType,\n                   const NewVariables_Scales_t& scales,\n                   const VariableCreationParameters& params)\n      : name_(name), dataType_(typeid(void)), dataTypeKnown_(dataType),\n        scales_(scales),\n        vcp_(params) {}\n\n  NewVariable_Base(const std::string& name, const std::type_index& dataType,\n                   const NewVariables_Scales_t& scales,\n                   const VariableCreationParameters& params)\n      : name_(name),\n        dataType_(dataType),\n        scales_(scales),\n        vcp_(params) {}\n};\ntypedef std::vector<std::shared_ptr<NewVariable_Base>> NewVariables_t;\n\ntemplate <class DataType>\ninline std::shared_ptr<NewVariable_Base> NewVariable(\n  const std::string& name, const NewVariables_Scales_t& scales,\n  const VariableCreationParameters& params = VariableCreationParameters::defaulted<DataType>()) {\n  return std::make_shared<NewVariable_Base>(name, typeid(DataType), scales, params);\n}\n\ninline std::shared_ptr<NewVariable_Base> NewVariable(const std::string& name,\n                                                     const Type& DataType,\n                                                     const NewVariables_Scales_t& scales,\n                                                     const VariableCreationParameters& params\n                                                     = VariableCreationParameters()) {\n  return std::make_shared<NewVariable_Base>(name, DataType, scales, params);\n}\n\n\nnamespace detail {\n\n/// \\ingroup ioda_cxx_variable\nclass IODA_DL Has_Variables_Base {\n  // friend class Group_Base;\nprivate:\n  /// Using an opaque object to implement the backend.\n  std::shared_ptr<Has_Variables_Backend> backend_;\n  /// Set by ObsGroup.\n  std::shared_ptr<const detail::DataLayoutPolicy> layout_;\n  std::vector<ComplementaryVariableCreationParameters> complementaryVariables_;\n  /// \\brief FillValuePolicy helper\n  /// \\details Hides the template function calls, so that the headers are smaller.\n  static void _py_fvp_helper(BasicTypes dataType, FillValuePolicy& fvp,\n                             VariableCreationParameters& params);\n\n  ComplementaryVariableCreationParameters createDerivedVariableParameters(\n      const std::string &inputName, const std::string &outputName, size_t position);\n  std::vector<std::vector<std::string>> loadComponentVariableData(\n      const ComplementaryVariableCreationParameters& derivedVariableParams);\n\nprotected:\n  Has_Variables_Base(std::shared_ptr<Has_Variables_Backend>,\n                     std::shared_ptr<const DataLayoutPolicy> = nullptr);\n\npublic:\n  virtual ~Has_Variables_Base();\n\n  /// Set the mapping policy to determine the Layout of Variables stored under this Group.\n  /// Usually only set by ObsGroup when we create / open.\n  virtual void setLayout(std::shared_ptr<const detail::DataLayoutPolicy>);\n\n  /// Query the backend and get the type provider.\n  virtual Type_Provider* getTypeProvider() const;\n\n  /// \\brief Get the fill value policy used for Variables within this Group\n  /// \\details The backend has to be consulted for this operation. Storage of this policy is\n  /// backend-dependent.\n  virtual FillValuePolicy getFillValuePolicy() const;\n\n  /// @name General Functions\n  /// @{\n  ///\n\n  /// \\brief Does a Variable with the specified name exist?\n  /// \\param name is the name of the Variable that we are looking for.\n  /// \\returns true if it exists.\n  /// \\returns false otherwise.\n  virtual bool exists(const std::string& name) const;\n  /// \\brief Delete an Attribute with the specified name.\n  /// \\param attname is the name of the Variable that we are deleting.\n  /// \\throws ioda::Exception if no such attribute exists.\n  virtual void remove(const std::string& name);\n  /// \\brief Open a Variable by name\n  /// \\param name is the name of the Variable to be opened.\n  /// \\returns An instance of a Variable that can be queried (with getDimensions()) and read.\n  virtual Variable open(const std::string& name) const;\n  /// \\brief Open a Variable by name\n  /// \\param name is the name of the Variable to be opened.\n  /// \\returns An instance of a Variable that can be queried (with getDimensions()) and read.\n  inline Variable operator[](const std::string& name) const { return open(name); }\n\n  /// List all Variables under this group (one-level search).\n  /// \\see Group_Base::listObjects if you need to enumerate both Groups and Variables, or\n  ///   if you need recursion.\n  virtual std::vector<std::string> list() const;\n  /// Convenience function to list all Variables under this group (one-level search).\n  /// \\see Group_Base::listObjects if you need to enumerate both Groups and Variables, or\n  ///   if you need recursion.\n  inline std::vector<std::string> operator()() const { return list(); }\n\n  /// \\brief Combines all complementary variables as specified in the mapping file, opens them,\n  /// and optionally removes the originals from the ObsGroup.\n  ///\n  /// \\p removeOriginals determines if the original complementary variables should be removed from\n  /// the ObsGroup. Later functionality will ensure that the original complementary variables can\n  /// be recreated on writing back to the original file.\n  void stitchComplementaryVariables(bool removeOriginals = true);\n\n  /// \\brief Converts unit to SI for all eligible variables. If conversion function not defined,\n  /// stores unit as attribute.\n  ///\n  /// Makes the conversion if the variable's unit is defined in the mapping file and the unit conversion\n  /// is defined in UnitConversions.h.\n  void convertVariableUnits(std::ostream &out = std::cerr);\n\n  /// \\brief Create a Variable without setting its data.\n  /// \\param attrname is the name of the Variable.\n  /// \\param dimensions is a vector representing the size of the metadata.\n  ///   Each element of the vector is a dimension with a certain size.\n  /// \\param in_memory_datatype is the runtime description of the Attribute's data type.\n  /// \\returns A Variable that can be written to.\n  virtual Variable create(const std::string& name, const Type& in_memory_dataType,\n                          const std::vector<Dimensions_t>& dimensions     = {1},\n                          const std::vector<Dimensions_t>& max_dimensions = {},\n                          const VariableCreationParameters& params = VariableCreationParameters());\n\n  /// Python compatability function\n  /// \\note Multiple ways to specify dimensions to match possible\n  ///   Python function signatures.\n  Variable _create_py(const std::string& name, BasicTypes dataType,\n                             const std::vector<Dimensions_t>& cur_dimensions = {1},\n                             const std::vector<Dimensions_t>& max_dimensions = {},\n                             const std::vector<Variable>& dimension_scales   = {},\n                             const VariableCreationParameters& params\n                             = VariableCreationParameters());\n\n  inline Variable create(const std::string& name, const Type& in_memory_dataType,\n                         const ioda::Dimensions& dims,\n                         const VariableCreationParameters& params = VariableCreationParameters()) {\n    return create(name, in_memory_dataType, dims.dimsCur, dims.dimsMax, params);\n  }\n\n  /// \\brief Create a Variable without setting its data.\n  /// \\tparam DataType is the type of the data. I.e. float, int32_t, uint16_t, std::string, etc.\n  /// \\param name is the name of the Variable.\n  /// \\param dimensions is a vector representing the size of the metadata. Each element of the\n  ///   vector is a dimension with a certain size.\n  /// \\returns A Variable that can be written to.\n  template <class DataType>\n  Variable create(const std::string& name, const std::vector<Dimensions_t>& dimensions = {1},\n                  const std::vector<Dimensions_t>& max_dimensions = {},\n                  const VariableCreationParameters& params        = VariableCreationParameters::defaulted<DataType>()) {\n    try {\n      VariableCreationParameters params2 = params;\n      FillValuePolicies::applyFillValuePolicy<DataType>(getFillValuePolicy(), params2.fillValue_);\n      Type in_memory_dataType = Types::GetType<DataType>(getTypeProvider());\n      auto var                = create(name, in_memory_dataType, dimensions,\n        max_dimensions, params2);\n      return var;\n    } catch (...) {\n      std::throw_with_nested(Exception(ioda_Here()));\n    }\n  }\n\n  template <class DataType>\n  Variable create(const std::string& name, const ioda::Dimensions& dims,\n                  const VariableCreationParameters& params\n                  = VariableCreationParameters::defaulted<DataType>()) {\n    try {\n      VariableCreationParameters params2 = params;\n      FillValuePolicies::applyFillValuePolicy<DataType>(getFillValuePolicy(), params2.fillValue_);\n      return create<DataType>(name, dims.dimsCur, dims.dimsMax, params2);\n    } catch (...) {\n      std::throw_with_nested(Exception(ioda_Here()));\n    }\n  }\n\n  /// \\brief Convenience function to create a Variable from certain dimension scales.\n  /// \\tparam DataType is the type of the data. I.e. int, int32_t, uint16_t, std::string, etc.\n  /// \\param name is the name of the Variable.\n  /// \\param dimensions is a vector representing the size of the metadata. Each element of the\n  ///   vector is a dimension with a certain size.\n  /// \\returns A Variable that can be written to.\n  template <class DataType>\n  Variable createWithScales(const std::string& name,\n                            const std::vector<Variable>& dimension_scales,\n                            const VariableCreationParameters& params\n                            = VariableCreationParameters::defaulted<DataType>()) {\n    try {\n      Type in_memory_dataType = Types::GetType<DataType>(getTypeProvider());\n\n      NewVariables_t newvars{NewVariable(name, in_memory_dataType, dimension_scales, params)};\n      createWithScales(newvars);\n      return open(name);\n    } catch (...) {\n      std::throw_with_nested(Exception(ioda_Here()));\n    }\n  }\n\n  /// @brief Collective function optimized to mass-construct variables and attach scales.\n  /// @param newvars is a vector of the new variables to be created.\n  /// @see NewVariable for the signature of the objects to add.\n  void createWithScales(const NewVariables_t& newvars);\n\n  /// @}\n  /// @name Collective functions\n  /// @brief These functions apply the an operation to a *set* of variables in situations where\n  ///   such an operation would produce better performance results than a loop of serial\n  ///   function calls.\n  /// @{\n  \n  /// @brief Attach dimension scales to many Dimension Numbers in a set of Variables.\n  /// @param DimensionNumber \n  /// @param mapping is the scale mappings for each variable. The first part of the pair refers\n  ///   to the variable that you are attaching scales to. The second part is a sequence of\n  ///   scales that are attached along each dimension (indexed by the vector).\n  /// @details\n  /// For some backends, particularly HDF5, attaching a dimension scale to a variable is a slow\n  /// procedure when you have many variables. This function batches low-level calls and avoids\n  /// loops.\n  virtual void attachDimensionScales(\n    const std::vector<std::pair<Variable, std::vector<Variable>>>& mapping);\n\n  /// @}\n};\n\nclass IODA_DL Has_Variables_Backend : public detail::Has_Variables_Base {\nprotected:\n  Has_Variables_Backend();\n\npublic:\n  virtual ~Has_Variables_Backend();\n  FillValuePolicy getFillValuePolicy() const override;\n  void attachDimensionScales(\n    const std::vector<std::pair<Variable, std::vector<Variable>>>& mapping) override;\n};\n}  // namespace detail\n\n/// \\brief This class exists inside of ioda::Group and provides the interface to manipulating\n///   Variables.\n/// \\ingroup ioda_cxx_variable\n///\n/// \\note It should only be constructed inside of a Group. It has no meaning elsewhere.\n/// \\see ioda::Variable for the class that represents individual variables.\n/// \\throws ioda::Exception on all exceptions.\nclass IODA_DL Has_Variables : public detail::Has_Variables_Base {\npublic:\n  virtual ~Has_Variables();\n  Has_Variables();\n  Has_Variables(std::shared_ptr<detail::Has_Variables_Backend>,\n                std::shared_ptr<const detail::DataLayoutPolicy> = nullptr);\n};\n}  // namespace ioda\n\n/// @}\n", "meta": {"hexsha": "b33570cd8f5d32132a53d816b2aadd5e14626aab", "size": 17442, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engines/ioda/include/ioda/Variables/Has_Variables.h", "max_stars_repo_name": "NOAA-EMC/ioda", "max_stars_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/engines/ioda/include/ioda/Variables/Has_Variables.h", "max_issues_repo_name": "NOAA-EMC/ioda", "max_issues_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engines/ioda/include/ioda/Variables/Has_Variables.h", "max_forks_repo_name": "NOAA-EMC/ioda", "max_forks_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.3317535545, "max_line_length": 120, "alphanum_fraction": 0.7021557161, "num_tokens": 3871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08151975374329136, "lm_q2_score": 0.03258974641032064, "lm_q1q2_score": 0.002656708101925652}}
{"text": "#pragma once\n#include \"halley/plugin/iasset_importer.h\"\n#include <yaml-cpp/node/node.h>\n#include \"halley/core/graphics/material/material_definition.h\"\n#include <gsl/span>\n\nnamespace Halley\n{\n\tclass MaterialDefinition;\n\n\tclass MaterialImporter : public IAssetImporter\n\t{\n\tpublic:\n\t\tImportAssetType getType() const override { return ImportAssetType::MaterialDefinition; }\n\n\t\tvoid import(const ImportingAsset& asset, IAssetCollector& collector) override;\n\n\t\tMaterialDefinition parseMaterial(Path basePath, gsl::span<const gsl::byte> data, IAssetCollector& collector) const;\n\n\tprivate:\n\t\tstatic void loadPass(MaterialDefinition& material, const ConfigNode& node, IAssetCollector& collector, int passN);\n\t\tstatic void loadUniforms(MaterialDefinition& material, const YAML::Node& topNode);\n\t\tstatic void loadTextures(MaterialDefinition& material, const YAML::Node& topNode);\n\t\tstatic void loadAttributes(MaterialDefinition& material, const YAML::Node& topNode);\n\n\t\tstatic ShaderParameterType parseParameterType(String rawType);\n\t\tstatic int getAttributeSize(ShaderParameterType type);\n\n\t\tstatic Bytes loadShader(const String& name, IAssetCollector& collector);\n\t\tstatic Bytes doLoadShader(const String& name, IAssetCollector& collector, std::set<String>& loaded);\t\t\n\t};\n}\n", "meta": {"hexsha": "afc66dd702423636d6a8bb0d4636c878349e140a", "size": 1266, "ext": "h", "lang": "C", "max_stars_repo_path": "src/tools/tools/src/assets/importers/material_importer.h", "max_stars_repo_name": "code-disaster/halley", "max_stars_repo_head_hexsha": "5c85c889b76c69c6bdef6f4801c6aba282b7af80", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3262.0, "max_stars_repo_stars_event_min_datetime": "2016-04-10T15:24:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:47:08.000Z", "max_issues_repo_path": "src/tools/tools/src/assets/importers/material_importer.h", "max_issues_repo_name": "code-disaster/halley", "max_issues_repo_head_hexsha": "5c85c889b76c69c6bdef6f4801c6aba282b7af80", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 53.0, "max_issues_repo_issues_event_min_datetime": "2016-10-09T16:25:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-10T13:52:37.000Z", "max_forks_repo_path": "src/tools/tools/src/assets/importers/material_importer.h", "max_forks_repo_name": "code-disaster/halley", "max_forks_repo_head_hexsha": "5c85c889b76c69c6bdef6f4801c6aba282b7af80", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 193.0, "max_forks_repo_forks_event_min_datetime": "2017-10-23T06:08:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T12:59:58.000Z", "avg_line_length": 38.3636363636, "max_line_length": 117, "alphanum_fraction": 0.7954186414, "num_tokens": 278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1066905825840872, "lm_q2_score": 0.0247981607811673, "lm_q1q2_score": 0.0026457302207566025}}
{"text": "#ifndef _EM_IO_H_\n#define _EM_IO_H_ 1\n\n#include <petsc.h>\n\nstruct EMContext;\n\nPetscErrorCode read_mdl(const char *, EMContext *);\nPetscErrorCode read_emd(const char *, EMContext *);\n\nPetscErrorCode save_mesh(EMContext *, const char *, int);\nPetscErrorCode save_rsp(EMContext *, const char *);\n\n#endif\n", "meta": {"hexsha": "5a00e207e9c061b20a77a9a3d1eac29d53c88a98", "size": 301, "ext": "h", "lang": "C", "max_stars_repo_path": "src/em_io.h", "max_stars_repo_name": "emfem/emfem", "max_stars_repo_head_hexsha": "9129e28610d7fcb83a88021528575dfeaadad502", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-03T12:22:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-03T12:22:37.000Z", "max_issues_repo_path": "src/em_io.h", "max_issues_repo_name": "emfem/emfem", "max_issues_repo_head_hexsha": "9129e28610d7fcb83a88021528575dfeaadad502", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/em_io.h", "max_forks_repo_name": "emfem/emfem", "max_forks_repo_head_hexsha": "9129e28610d7fcb83a88021528575dfeaadad502", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0666666667, "max_line_length": 57, "alphanum_fraction": 0.7574750831, "num_tokens": 77, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.09138210059264242, "lm_q2_score": 0.028870906319603686, "lm_q1q2_score": 0.0026382840654987794}}
{"text": "/*\t$Id$ */\n/*\n * Copyright (c) 2014, 2015 Kristaps Dzonsons <kristaps@kcons.eu>\n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n */\n#include <assert.h>\n#include <inttypes.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include <cairo.h>\n#include <cairo-pdf.h>\n#include <cairo-ps.h>\n#include <gtk/gtk.h>\n#include <gsl/gsl_multifit.h>\n#include <kplot.h>\n\n#include \"extern.h\"\n\nenum\tsavetype {\n\tSAVE_PDF,\n\tSAVE_PS,\n\tSAVE_EPS\n};\n\nstatic int\nsavepng(const gchar *fname, const struct curwin *c)\n{\n\tcairo_surface_t\t*surf;\n\tcairo_t\t\t*cr;\n\tcairo_status_t\t st;\n\n\tg_debug(\"%p: Saving: %s\", c, fname);\n\tsurf = cairo_image_surface_create\n\t\t(CAIRO_FORMAT_ARGB32, 600, 400);\n\tst = cairo_surface_status(surf);\n\tif (CAIRO_STATUS_SUCCESS != st) {\n\t\tg_debug(\"%s\", cairo_status_to_string(st));\n\t\tcairo_surface_destroy(surf);\n\t\treturn(0);\n\t}\n\n\tcr = cairo_create(surf);\n\tcairo_surface_destroy(surf);\n\n\tst = cairo_status(cr);\n\tif (CAIRO_STATUS_SUCCESS != st) {\n\t\tg_debug(\"%s\", cairo_status_to_string(st));\n\t\tcairo_destroy(cr);\n\t\treturn(0);\n\n\t}\n\n\tcairo_set_source_rgb(cr, 1.0, 1.0, 1.0); \n\tcairo_rectangle(cr, 0.0, 0.0, 600.0, 400.0);\n\tcairo_fill(cr);\n\tkplot_draw(c->views[c->view], 600.0, 400.0, cr);\n\n\tst = cairo_surface_write_to_png(cairo_get_target(cr), fname);\n\n\tif (CAIRO_STATUS_SUCCESS != st) {\n\t\tg_debug(\"%s\", cairo_status_to_string(st));\n\t\tcairo_destroy(cr);\n\t\treturn(0);\n\t}\n\n\tcairo_destroy(cr);\n\treturn(1);\n}\n\nstatic int\nsavepdf(const gchar *fname, struct curwin *c, enum savetype type)\n{\n\tcairo_surface_t\t*surf;\n\tcairo_t\t\t*cr;\n\tcairo_status_t\t st;\n\tstruct kplotcfg\t*cfg;\n\tstruct kdatacfg\t*datas;\n\tsize_t\t\t datasz, i, j;\n\tint\t\t rc;\n\tdouble\t\t svtic, svaxis, svborder, svgrid, sv, svticln;\n\tconst double\t w = 72 * 6, h = 72 * 5;\n\n\tg_debug(\"%p: Saving: %s\", c, fname);\n\tswitch (type) {\n\tcase (SAVE_PDF):\n\t\tsurf = cairo_pdf_surface_create(fname, w, h);\n\t\tbreak;\n\tcase (SAVE_EPS):\n\t\tsurf = cairo_ps_surface_create(fname, w, h);\n\t\tcairo_ps_surface_set_eps(surf, 1);\n\t\tbreak;\n\tcase (SAVE_PS):\n\t\tsurf = cairo_ps_surface_create(fname, w, h);\n\t\tcairo_ps_surface_set_eps(surf, 0);\n\t\tbreak;\n\tdefault:\n\t\tabort();\n\t}\n\n\tst = cairo_surface_status(surf);\n\tif (CAIRO_STATUS_SUCCESS != st) {\n\t\tg_debug(\"%s\", cairo_status_to_string(st));\n\t\tcairo_surface_destroy(surf);\n\t\treturn(0);\n\t}\n\n\tcr = cairo_create(surf);\n\tcairo_surface_destroy(surf);\n\n\tst = cairo_status(cr);\n\tif (CAIRO_STATUS_SUCCESS != st) {\n\t\tg_debug(\"%s\", cairo_status_to_string(st));\n\t\tcairo_destroy(cr);\n\t\treturn(0);\n\n\t}\n\n\tcfg = kplot_get_plotcfg(c->views[c->view]);\n\n\tsvtic = cfg->ticlabelfont.sz;\n\tsvaxis = cfg->axislabelfont.sz;\n\tsvborder = cfg->borderline.sz;\n\tsvgrid = cfg->gridline.sz;\n\tsvticln = cfg->ticline.sz;\n\tsv = 0.0; /* Silence compiler. */\n\n\tcfg->ticlabelfont.sz = 9.0;\n\tcfg->axislabelfont.sz = 9.0;\n\tcfg->borderline.sz = 0.5;\n\tcfg->gridline.sz = 0.5;\n\tcfg->ticline.sz = 0.5;\n\n\tfor (i = 0; ; i++) {\n\t\trc = kplot_get_datacfg(c->views[c->view],\n\t\t\ti, &datas, &datasz);\n\t\tif (0 == rc)\n\t\t\tbreak;\n\t\tfor (j = 0; j < datasz; j++) {\n\t\t\tsv = datas[j].line.sz;\n\t\t\tdatas[j].line.sz = 1.0;\n\t\t}\n\t}\n\n\tcairo_set_source_rgb(cr, 1.0, 1.0, 1.0); \n\tcairo_rectangle(cr, 0.0, 0.0, w, h);\n\tcairo_fill(cr);\n\tkplot_draw(c->views[c->view], w, h, cr);\n\tcairo_destroy(cr);\n\n\tcfg->ticlabelfont.sz = svtic;\n\tcfg->axislabelfont.sz = svaxis;\n\tcfg->borderline.sz = svborder;\n\tcfg->gridline.sz = svgrid;\n\tcfg->ticline.sz = svticln;\n\n\tfor (i = 0; ; i++) {\n\t\trc = kplot_get_datacfg(c->views[c->view],\n\t\t\ti, &datas, &datasz);\n\t\tif (0 == rc)\n\t\t\tbreak;\n\t\tfor (j = 0; j < datasz; j++)\n\t\t\tdatas[j].line.sz = sv;\n\t}\n\n\treturn(1);\n}\n\nint\nsave(const gchar *fname, struct curwin *cur)\n{\n\n\tif (g_str_has_suffix(fname, \".pdf\")) \n\t\treturn(savepdf(fname, cur, SAVE_PDF));\n\telse if (g_str_has_suffix(fname, \".ps\")) \n\t\treturn(savepdf(fname, cur, SAVE_PS));\n\telse if (g_str_has_suffix(fname, \".eps\")) \n\t\treturn(savepdf(fname, cur, SAVE_EPS));\n\telse\n\t\treturn(savepng(fname, cur));\n}\n\nint\nsaveconfig(const gchar *fname, const struct curwin *cur)\n{\n\tFILE\t\t*f;\n\tstruct sim\t*sim;\n\tGList\t\t*l;\n\n\tg_debug(\"%p: Saving configuration: %s\", cur, fname);\n\n\tif (NULL == (f = fopen(fname, \"w\"))) {\n\t\tg_debug(\"%s: %s\", fname, strerror(errno));\n\t\treturn(0);\n\t}\n\n\tfor (l = cur->sims; NULL != l; l = g_list_next(l)) {\n\t\tsim = l->data;\n\t\tfprintf(f, \"Name: %s\\n\", sim->name);\n\t\tfprintf(f, \"Colour: #%.2x%.2x%.2x\\n\", \n\t\t\t(unsigned int)(cur->b->clrs[sim->colour].rgba[0] * 255),\n\t\t\t(unsigned int)(cur->b->clrs[sim->colour].rgba[1] * 255),\n\t\t\t(unsigned int)(cur->b->clrs[sim->colour].rgba[2] * 255));\n\t\tfprintf(f, \"Function: %s\\n\", sim->func);\n\t\tfprintf(f, \"Threads: %zu\\n\", sim->nprocs);\n\t\tfprintf(f, \"Multiplier: %g(1 + %g lambda)\\n\", \n\t\t\tsim->alpha, sim->delta);\n\t\tfprintf(f, \"Max generations: %zu\\n\", sim->stop);\n\t\tfprintf(f, \"Migration: %g (%suniform)\\n\", \n\t\t\tsim->m, NULL != sim->ms ? \"non-\" : \"\");\n\t\tfprintf(f, \"Incumbents: %zu, [%g,%g)\\n\", \n\t\t\tsim->dims, sim->xmin, sim->xmax);\n\t\tfprintf(f, \"Rolling average window: %zu\\n\", sim->smoothing);\n\t\tswitch (sim->maptop) {\n\t\tcase (MAPTOP_RECORD):\n\t\t\tfprintf(f, \"Map: record-based\\n\");\n\t\t\tbreak;\n\t\tcase (MAPTOP_RAND):\n\t\t\tfprintf(f, \"Map: random\\n\");\n\t\t\tbreak;\n\t\tcase (MAPTOP_TORUS):\n\t\t\tfprintf(f, \"Map: torus\\n\");\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tabort();\n\t\t}\n\t\tswitch (sim->migrant) {\n\t\tcase (MAPMIGRANT_UNIFORM):\n\t\t\tfprintf(f, \"Migration: uniform\\n\");\n\t\t\tbreak;\n\t\tcase (MAPMIGRANT_DISTANCE):\n\t\t\tfprintf(f, \"Migration: distance\\n\");\n\t\t\tbreak;\n\t\tcase (MAPMIGRANT_NEAREST):\n\t\t\tfprintf(f, \"Migration: nearest\\n\");\n\t\t\tbreak;\n\t\tcase (MAPMIGRANT_TWONEAREST):\n\t\t\tfprintf(f, \"Migration: two nearest\\n\");\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tabort();\n\t\t}\n\t\tif (MAPINDEX_STRIPED == sim->mapindex)\n\t\t\tfprintf(f, \"Mutant index case: striped\\n\");\n\t\telse\n\t\t\tfprintf(f, \"Mutant index case: fixed (%zu)\\n\",\n\t\t\t\tsim->mapindexfix);\n\t\tif (MUTANTS_DISCRETE == sim->mutants)\n\t\t\tfprintf(f, \"Mutants: %zu, [%g,%g)\\n\", \n\t\t\t\tsim->dims, sim->ymin, sim->ymax);\n\t\telse\n\t\t\tfprintf(f, \"Mutants: N(sigma=%g), [%g,%g)\\n\", \n\t\t\t\tsim->mutantsigma, sim->ymin, sim->ymax);\n\t\tfprintf(f, \"Islands: %zu (%zu islanders)\\n\", \n\t\t\tsim->islands, sim->totalpop);\n\t\tif (NULL != sim->pops)\n\t\t\tfprintf(f, \"Island populations: non-uniform\\n\");\n\t\telse\n\t\t\tfprintf(f, \"Island populations: %zu\\n\", sim->pop);\n\t\tfprintf(f, \"Fit polynomial: %zu (%sweighted)\\n\",\n\t\t\tsim->fitpoly, 0 == sim->weighted ? \"un\" : \"\");\n\n\t\tfprintf(f, \"\\n\");\n\t}\n\n\tfclose(f);\n\treturn(1);\n}\n", "meta": {"hexsha": "6b8557cbfcc153baf568f540f3e8c90d89eaa203", "size": 7002, "ext": "c", "lang": "C", "max_stars_repo_path": "save.c", "max_stars_repo_name": "kristapsdz/bmigrate", "max_stars_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-03-03T17:13:19.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-03T17:13:19.000Z", "max_issues_repo_path": "save.c", "max_issues_repo_name": "kristapsdz/bmigrate", "max_issues_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "save.c", "max_forks_repo_name": "kristapsdz/bmigrate", "max_forks_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9181494662, "max_line_length": 75, "alphanum_fraction": 0.6498143388, "num_tokens": 2300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12940273494909918, "lm_q2_score": 0.020332352452212373, "lm_q1q2_score": 0.0026310620152653046}}
{"text": "/* -----------------------------------------------------------------------------\n * Copyright 2021 Jonathan Haigh\n * SPDX-License-Identifier: MIT\n * ---------------------------------------------------------------------------*/\n\n#ifndef SQ_INCLUDE_GUARD_system_schema_h_\n#define SQ_INCLUDE_GUARD_system_schema_h_\n\n#include \"core/Primitive.h\"\n#include \"core/typeutil.h\"\n\n#include <cstddef>\n#include <gsl/gsl>\n#include <optional>\n#include <string_view>\n\nnamespace sq::system {\n\nclass SchemaImpl;\n\n/**\n * Represents the schema for a primitive type.\n */\nclass PrimitiveTypeSchema {\npublic:\n  constexpr explicit PrimitiveTypeSchema(std::string_view name,\n                                         std::string_view doc)\n      : name_{name}, doc_{doc} {}\n\n  SQ_ND std::string_view name() const;\n  SQ_ND std::string_view doc() const;\n\nprivate:\n  std::string_view name_;\n  std::string_view doc_;\n};\n\n/**\n * Represents the schema for a parameter of field of a system object.\n */\nclass ParamSchema {\npublic:\n  constexpr ParamSchema(std::string_view name, std::string_view doc,\n                        std::size_t index, std::size_t type_index,\n                        bool required, std::string_view default_value_str,\n                        std::string_view default_value_doc)\n      : name_{name}, doc_{doc}, index_{index}, type_index_{type_index},\n        required_{required}, default_value_str_{default_value_str},\n        default_value_doc_{default_value_doc} {}\n\n  SQ_ND std::string_view name() const;\n  SQ_ND std::string_view doc() const;\n  SQ_ND std::size_t index() const;\n  SQ_ND const PrimitiveTypeSchema &type() const;\n  SQ_ND bool required() const;\n  SQ_ND std::optional<Primitive> default_value() const;\n  SQ_ND std::string_view default_value_doc() const;\n\nprivate:\n  std::string_view name_;\n  std::string_view doc_;\n  std::size_t index_;\n  std::size_t type_index_;\n  bool required_;\n  std::string_view default_value_str_;\n  std::string_view default_value_doc_;\n};\n\nclass TypeSchema;\n\n/**\n * Represents the schema for a field of a system object.\n */\nclass FieldSchema {\npublic:\n  constexpr FieldSchema(std::string_view name, std::string_view doc,\n                        std::size_t params_begin_index,\n                        std::size_t params_end_index,\n                        std::size_t return_type_index, bool return_list,\n                        bool null)\n      : name_{name}, doc_{doc}, params_begin_index_{params_begin_index},\n        params_end_index_{params_end_index},\n        return_type_index_{return_type_index},\n        return_list_{return_list}, null_{null} {}\n\n  SQ_ND std::string_view name() const;\n  SQ_ND std::string_view doc() const;\n  SQ_ND gsl::span<const ParamSchema> params() const;\n  SQ_ND const TypeSchema &return_type() const;\n  SQ_ND bool return_list() const;\n  SQ_ND bool null() const;\n\nprivate:\n  std::string_view name_;\n  std::string_view doc_;\n  std::size_t params_begin_index_;\n  std::size_t params_end_index_;\n  std::size_t return_type_index_;\n  bool return_list_;\n  bool null_;\n};\n\n/**\n * Represents the schema for a system object.\n */\nclass TypeSchema {\npublic:\n  constexpr TypeSchema(std::string_view name, std::string_view doc,\n                       std::size_t fields_begin_index,\n                       std::size_t fields_end_index)\n      : name_{name}, doc_{doc}, fields_begin_index_{fields_begin_index},\n        fields_end_index_{fields_end_index} {}\n\n  SQ_ND std::string_view name() const;\n  SQ_ND std::string_view doc() const;\n  SQ_ND gsl::span<const FieldSchema> fields() const;\n\nprivate:\n  std::string_view name_;\n  std::string_view doc_;\n  std::size_t fields_begin_index_;\n  std::size_t fields_end_index_;\n};\n\n/**\n * Represents the whole SQ schema.\n */\nstruct Schema {\npublic:\n  SQ_ND gsl::span<const TypeSchema> types() const;\n  SQ_ND gsl::span<const PrimitiveTypeSchema> primitive_types() const;\n  SQ_ND const TypeSchema &root_type() const;\n};\n\n/**\n * Get the whole SQ schema.\n */\nconst Schema &schema();\n\n} // namespace sq::system\n\n#endif // SQ_INCLUDE_GUARD_system_schema_h_\n", "meta": {"hexsha": "c4f6a972a0930230c846193b17b00007048de980", "size": 4031, "ext": "h", "lang": "C", "max_stars_repo_path": "src/system/include/system/schema.h", "max_stars_repo_name": "jonathanhaigh/sq", "max_stars_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-12T16:21:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-12T16:21:41.000Z", "max_issues_repo_path": "src/system/include/system/schema.h", "max_issues_repo_name": "jonathanhaigh/sq", "max_issues_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 44.0, "max_issues_repo_issues_event_min_datetime": "2021-02-08T19:17:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-05T18:51:38.000Z", "max_forks_repo_path": "src/system/include/system/schema.h", "max_forks_repo_name": "jonathanhaigh/sq", "max_forks_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1888111888, "max_line_length": 80, "alphanum_fraction": 0.664599355, "num_tokens": 921, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09534945461636171, "lm_q2_score": 0.027585281327434107, "lm_q1q2_score": 0.0026302415300097485}}
{"text": "#pragma once\n#include \"Ds4Color.h\"\n#include <gsl/span>\n\n/**\n * \\brief PoD for setting \\c Ds4Device parameters like motor speed, light color, etc.\n */\nstruct Ds4Output\n{\n\tuint8_t  rightMotor    = 0;\n\tuint8_t  leftMotor     = 0;\n\tDs4Color lightColor    = {};\n\tuint8_t  flashOnDur    = 0;\n\tuint8_t  flashOffDur   = 0;\n\tuint8_t  volumeLeft    = 50;\n\tuint8_t  volumeRight   = 50;\n\tuint8_t  volumeMic     = 50;\n\tuint8_t  volumeSpeaker = 50;\n\n\t/**\n\t * \\brief Updates a buffer with the stored device parameters.\n\t * \\param buffer Buffer to update.\n\t * \\return \\c true if changes have been made to \\a buffer.\n\t */\n\tbool update(const gsl::span<uint8_t>& buffer) const;\n};\n", "meta": {"hexsha": "6ff7fa24edf3b9874bfb275a1c9604a70907eb93", "size": 662, "ext": "h", "lang": "C", "max_stars_repo_path": "ds4wizard-cpp/Ds4Output.h", "max_stars_repo_name": "SonicFreak94/ds4wizard", "max_stars_repo_head_hexsha": "4d2ddc15b7db7cc5618c8676c91cf81614921c3c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T19:23:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-13T08:35:31.000Z", "max_issues_repo_path": "ds4wizard-cpp/Ds4Output.h", "max_issues_repo_name": "SonicFreak94/ds4wizard", "max_issues_repo_head_hexsha": "4d2ddc15b7db7cc5618c8676c91cf81614921c3c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-01-29T20:34:26.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-30T04:00:38.000Z", "max_forks_repo_path": "ds4wizard-cpp/Ds4Output.h", "max_forks_repo_name": "SonicFreak94/ds4wizard", "max_forks_repo_head_hexsha": "4d2ddc15b7db7cc5618c8676c91cf81614921c3c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5185185185, "max_line_length": 85, "alphanum_fraction": 0.66918429, "num_tokens": 204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12421302132013363, "lm_q2_score": 0.020964241544503406, "lm_q1q2_score": 0.002604031781927833}}
{"text": "// SPDX-License-Identifier: MIT\n// The MIT License (MIT)\n//\n// Copyright (c) 2014-2018, Institute for Software & Systems Engineering\n// Copyright (c) 2018-2019, Johannes Leupolz\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n#ifndef PEMC_GENERIC_TRAVERSER_TRAVERSAL_TRANSITION_H_\n#define PEMC_GENERIC_TRAVERSER_TRAVERSAL_TRANSITION_H_\n\n#include <gsl/gsl_byte>\n#include <cstdint>\n\n#include \"pemc/basic/tsc_index.h\"\n#include \"pemc/basic/label.h\"\n\nnamespace pemc {\n\n  enum TraversalTransitionFlags : uint32_t {\n    NoFlag,\n\n\t\t/// If set, the value of targetStateIndex is set and targetState is invalid.\n\t\t/// If unset, the value of targetState is set and targetStateIndex is invalid.\n    IsTargetStateTransformedToIndex = 1,\n\n    /// If set, the transition is invalid and should be ignored\n    IsTransitionInvalid = 2,\n\n    /// If set, the transition leads to the stuttering state and the state in targetState\n    /// shall be ignored.\n    IsToStutteringState = 4\n  };\n\n  struct TraversalTransition {\n    // 4 bytes / 8 bytes\n    union {\n      gsl::byte* targetState;  // is set prior to adding  the state to state storage\n      StateIndex targetStateIndex; // is set after having added the state to state storage\n    };\n\n    // 4 bytes\n    TraversalTransitionFlags flags;\n\n    // 4 bytes\n    Label label;\n\n    TraversalTransition()\n      : targetState(nullptr), flags(TraversalTransitionFlags::NoFlag), label(Label()){\n    }\n\n    TraversalTransition(gsl::byte* _targetState, Label _label)\n      : targetState(_targetState), flags(TraversalTransitionFlags::NoFlag), label(_label) {\n    }\n  };\n\n\n  inline TraversalTransitionFlags operator|(TraversalTransitionFlags a, TraversalTransitionFlags b) {\n    return static_cast<TraversalTransitionFlags>(static_cast<uint32_t>(a) | static_cast<uint32_t>(b));\n  }\n\n  inline TraversalTransitionFlags operator|=(TraversalTransitionFlags a, const TraversalTransitionFlags b) {\n    a =  static_cast<TraversalTransitionFlags>(static_cast<uint32_t>(a) | static_cast<uint32_t>(b));\n    return a;\n  }\n\n}\n\n#endif  // PEMC_GENERIC_TRAVERSER_TRAVERSAL_TRANSITION_H_\n", "meta": {"hexsha": "c69a88437875a9e8fb5e70429fe5149c836cf3a4", "size": 3121, "ext": "h", "lang": "C", "max_stars_repo_path": "pemc/generic_traverser/traversal_transition.h", "max_stars_repo_name": "joleuger/pemc", "max_stars_repo_head_hexsha": "14deb5b97d4219ba3c92d3834ab71332997e9b13", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pemc/generic_traverser/traversal_transition.h", "max_issues_repo_name": "joleuger/pemc", "max_issues_repo_head_hexsha": "14deb5b97d4219ba3c92d3834ab71332997e9b13", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pemc/generic_traverser/traversal_transition.h", "max_forks_repo_name": "joleuger/pemc", "max_forks_repo_head_hexsha": "14deb5b97d4219ba3c92d3834ab71332997e9b13", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2906976744, "max_line_length": 108, "alphanum_fraction": 0.7459147709, "num_tokens": 739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09534945461636173, "lm_q2_score": 0.027169234194192645, "lm_q1q2_score": 0.002590571662760475}}
{"text": "#pragma once\n#ifndef _SECURE_ATL\n#define _SECURE_ATL 1\n#endif\n#include \"framework.h\"\n#include <strsafe.h>\n\n// <tas=uncomment to use Guidelines Support Library https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md\">\n#pragma warning (push)\n#pragma warning (disable: 4003)\n//#include <gsl/gsl>\n//#include <gsl/gsl_algorithm> // copy\n#include <gsl/gsl_assert> // Ensures/Expects\n//#include <gsl/gsl_byte> // byte\n#include <gsl/gsl_util> // finally()/narrow()/narrow_cast()...\n//#include <gsl/multi_span> // multi_span, strided_span...\n#include <gsl/pointers> // owner, not_null\n//#include <gsl/span> // span\n#include <gsl/string_span> // zstring, string_span, zstring_builder...\n#pragma warning (pop)\n// </tas>\n#include \"Resource.h\"\n\n// OD_OLE_SUPPORT\n// Vectorization support for OLE objects on Windows can be obtained by including this module: OdOleItemHandler\n// Source for this module is located in [kernel root]/Extensions/win/OleItemHandler.\n// OLE support can be enabled by linking in the OdOleItemHandler module and registering \"OdOleItemHandler\" using the ODRX_DEFINE_STATIC_APPLICATION macro.\n// For the DLL version, place the OdOleItemHandler.tx module in the same directory as the DLLs (no explicit registration required).\n// Uncomment #define for support \n// #define OD_OLE_SUPPORT 1\n#include <OdaCommon.h>\n#include <Ge/GePoint3d.h>\n#include <Ge/GeVector3d.h>\n#include <Ge/GeMatrix3d.h>\n\nunsigned AFXAPI HashKey(CString& string) noexcept;\n\n#include \"SafeMath.h\"\n\ninline double MillimetersToInches(const double millimeters) {\n\treturn millimeters / kMmPerInch;\n}\n\ninline double InchesToMillimeters(const double inches) {\n\treturn inches * kMmPerInch;\n}\n\n// <tas=\"Static analysis\"/>\n// Compiler warnings that are off by default (https://docs.microsoft.com/en-us/cpp/preprocessor/compiler-warnings-that-are-off-by-default?view=vs-2019)\n#pragma warning (default: 4165) // (level 1) 'HRESULT' is being converted to 'bool'; are you sure this is what you want ?\n#pragma warning (default: 4264) // (level 1) 'virtual_function': no override available for virtual member function from base 'class'; function is hidden\n#pragma warning (default: 4342) // (level 1) behavior change : 'function' called, but a member operator was called in previous versions\n#pragma warning (default: 4350) // (level 1) behavior change : 'member1' called instead of 'member2'\n#pragma warning (default: 4426) // (level 1) optimization flags changed after including header, may be due to #pragma optimize()\n#pragma warning (default: 4472) // (level 1) 'identifier' is a native enum : add an access specifier(private / public) to declare a managed enum\n#pragma warning (default: 4545) // (level 1) expression before comma evaluates to a function which is missing an argument list\n#pragma warning (default: 4545) // (level 1) expression before comma evaluates to a function which is missing an argument list\n#pragma warning (default: 4546) // (level 1) function call before comma missing argument list\n#pragma warning (default: 4547) // (level 1) 'operator': operator before comma has no effect; expected operator with side - effect\n#pragma warning (default: 4548) // (level 1) expression before comma has no effect; expected expression with side - effect\n#pragma warning (default: 4549) // (level 1) 'operator1': operator before comma has no effect; did you intend 'operator2' ?\n#pragma warning (default: 4555) // (level 1) expression has no effect; expected expression with side - effect\n#pragma warning (default: 4577) // (level 1) 'noexcept' used with no exception handling mode specified; termination on exception is not guaranteed.Specify / EHsc\n#pragma warning (default: 4587) // (level 1) 'anonymous_structure': behavior change : constructor is no longer implicitly called\n#pragma warning (default: 4588) // (level 1) 'anonymous_structure' : behavior change : destructor is no longer implicitly called\n#pragma warning (default: 4598) // (level 1 and level 3) '#include \"header\"': header number number in the precompiled header does not match current compilation at that position\n#pragma warning (default: 4605) // (level 1) '/Dmacro' specified on current command line, but was not specified when precompiled header was built\n#pragma warning (default: 4628) // (level 1) digraphs not supported with - Ze.Character sequence 'digraph' not interpreted as alternate token for 'char'\n#pragma warning (default: 4692) // (level 1) 'function': signature of non - private member contains assembly private native type 'native_type'\n#pragma warning (default: 4822) // (level 1) 'member' : local class member function does not have a body\n#pragma warning (default: 4905) // (level 1) wide string literal cast to 'LPSTR'\n#pragma warning (default: 4906) // (level 1) string literal cast to 'LPWSTR'\n#pragma warning (default: 4917) // (level 1) 'declarator' : a GUID can only be associated with a class, interface, or namespace\n#pragma warning (default: 4928) // (level 1) illegal copy - initialization; more than one user - defined conversion has been implicitly applied\n#pragma warning (default: 4946) // (level 1) reinterpret_cast used between related classes : 'class1'and 'class2'\n#pragma warning (default: 5026) // (level 1 and level 4) 'type' : move constructor was implicitly defined as deleted\n#pragma warning (default: 5027) // (level 1 and level 4) 'type' : move assignment operator was implicitly defined as deleted\n#pragma warning (default: 5036) // (level 1) varargs function pointer conversion when compiling with / hybrid : x86arm64 'type1' to 'type2'\n#pragma warning (default: 4412) // (level 2) 'function': function signature contains type 'type'; C++ objects are unsafe to pass between pure code and mixed or native\n#pragma warning (default: 4826) // (level 2) Conversion from 'type1' to 'type2' is sign - extended.This may cause unexpected runtime behavior.\n#pragma warning (default: 4191) // (level 3) 'operator': unsafe conversion from 'type_of_expression' to 'type_required'\n#pragma warning (default: 4265) // (level 3) 'class' : class has virtual functions, but destructor is not virtual\n#pragma warning (default: 4287) // (level 3) 'operator' : unsigned / negative constant mismatch\n#pragma warning (default: 4370) // (level 3) layout of class has changed from a previous version of the compiler due to better packing\n#pragma warning (default: 4371) // (level 3) 'classname' : layout of class may have changed from a previous version of the compiler due to better packing of member 'member'\n#pragma warning (default: 4444) // (level 3) top level '__unaligned' is not implemented in this context\n#pragma warning (default: 4557) // (level 3) '__assume' contains effect 'effect'\n#pragma warning (default: 4599) // (level 3) 'option path' : command - line argument number number does not match pre - compiled header 14.3\n#pragma warning (default: 4608) // (level 3) 'union_member' has already been initialized by another union member in the initializer list, 'union_member' Perm\n#pragma warning (default: 4619) // (level 3) #pragma warning : there is no warning number 'number'\n#pragma warning (default: 4640) // (level 3) 'instance' : construction of local static object is not thread - safe\n#pragma warning (default: 4647) // (level 3) behavior change : __is_pod(type) has different value in previous versions\n#pragma warning (default: 4686) // (level 3) 'user-defined type' : possible change in behavior, change in UDT return calling convention\n#pragma warning (default: 4738) // (level 3) storing 32 - bit float result in memory, possible loss of performance\n#pragma warning (default: 4768) // (level 3) __declspec attributes before linkage specification are ignored\n#pragma warning (default: 4786) // (level 3) 'symbol' : object name was truncated to 'number' characters in the debug information\n#pragma warning (default: 5042) // (level 3) 'function' : function declarations at block scope cannot be specified 'inline' in standard C++; remove 'inline' specifier\n#pragma warning (default: 4061) // (level 4) enumerator 'identifier' in a switch of enum 'enumeration' is not explicitly handled by a case label\n#pragma warning (default: 4062) // (level 4) enumerator 'identifier' in a switch of enum 'enumeration' is not handled\n#pragma warning (default: 4242) // (level 4) 'identifier': conversion from 'type1' to 'type2', possible loss of data\n#pragma warning (default: 4254) // (level 4) 'operator' : conversion from 'type1' to 'type2', possible loss of data\n#pragma warning (default: 4255) // (level 4) 'function': no function prototype given: converting '()' to '(void)'\n#pragma warning (default: 4263) // (level 4) 'function' : member function does not override any base class virtual member function\n#pragma warning (default: 4266) // (level 4) 'function': no override available for virtual member function from base 'type'; function is hidden\n#pragma warning (default: 4289) // (level 4) nonstandard extension used : 'var' : loop control variable declared in the for - loop is used outside the for - loop scope\n#pragma warning (default: 4296) // (level 4) 'operator' : expression is always false\n#pragma warning (default: 4339) // (level 4) 'type' : use of undefined type detected in CLR meta - data - use of this type may lead to a runtime exception\n#pragma warning (default: 4365) // (level 4) 'action' : conversion from 'type_1' to 'type_2', signed/unsigned mismatch\n#pragma warning (default: 4388) // (level 4) signed / unsigned mismatch\n#pragma warning (default: 4435) // (level 4) 'class1' : Object layout under / vd2 will change due to virtual base 'class2'\n#pragma warning (default: 4437) // (level 4) dynamic_cast from virtual base 'class1' to 'class2' could fail in some contexts\n#pragma warning (default: 4464) // (level 4) relative include path contains '..'\n#pragma warning (default: 4471) // (level 4) a forward declaration of an unscoped enumeration must have an underlying type(int assumed) Perm\n#pragma warning (default: 4514) // (level 4) 'function' : unreferenced inline function has been removed\n#pragma warning (default: 4536) // (level 4) 'type name' : type - name exceeds meta - data limit of 'limit' characters\n#pragma warning (default: 4571) // (level 4) informational : catch (...) semantics changed since Visual C++ 7.1; structured exceptions(SEH) are no longer caught\n#pragma warning (default: 4574) // (level 4) 'identifier' is defined to be '0': did you mean to use '#if identifier' ?\n#pragma warning (default: 4582) // (level 4) 'type' : constructor is not implicitly called\n#pragma warning (default: 4583) // (level 4) 'type' : destructor is not implicitly called\n#pragma warning (default: 4596) // (level 4) 'identifier' : illegal qualified name in member declaration 14.3 Perm\n#pragma warning (default: 4623) // (level 4) 'derived class' : default constructor could not be generated because a base class default constructor is inaccessible\n#pragma warning (default: 4625) // (level 4) 'derived class' : copy constructor could not be generated because a base class copy constructor is inaccessible\n#pragma warning (default: 4626) // (level 4) 'derived class' : assignment operator could not be generated because a base class assignment operator is inaccessible\n#pragma warning (default: 4643) // (level 4) Forward declaring 'identifier' in namespace std is not permitted by the C++ Standard.\n#pragma warning (default: 4654) // (level 4) Code placed before include of precompiled header line will be ignored.Add code to precompiled header.\n#pragma warning (default: 4668) // (level 4) 'symbol' is not defined as a preprocessor macro, replacing with '0' for 'directives'\n#pragma warning (default: 4682) // (level 4) 'symbol' : no directional parameter attribute specified, defaulting to[in]\n#pragma warning (default: 4710) // (level 4) 'function' : function not inlined\n#pragma warning (default: 4749) // (level 4) conditionally supported : offsetof applied to non - standard - layout type 'type'\n#pragma warning (default: 4767) // (level 4) section name 'symbol' is longer than 8 characters and will be truncated by the linker\n#pragma warning (default: 4774) // (level 4) 'string' : format string expected in argument number is not a string literal\n#pragma warning (default: 4777) // (level 4) 'function' : format string 'string' requires an argument of type 'type1', but variadic argument number has type 'type2'\n// <tas=\"requires VS 2019\"/>#pragma warning (default: 4800) // (level 4) Implicit conversion from 'type' to bool.Possible information loss\n#pragma warning (default: 4820) // (level 4) 'bytes' bytes padding added after construct 'member_name'\n#pragma warning (default: 4837) // (level 4) trigraph detected : '??character' replaced by 'character'\n#pragma warning (default: 4841) // (level 4) non - standard extension used : compound member designator used in offsetof\n#pragma warning (default: 4842) // (level 4) the result of 'offsetof' applied to a type using multiple inheritance is not guaranteed to be consistent between compiler releases\n#pragma warning (default: 4868) // (level 4) 'file(line_number)' compiler may not enforce left - to - right evaluation order in braced initialization list\n#pragma warning (default: 4931) // (level 4) we are assuming the type library was built for number - bit pointers\n#pragma warning (default: 4986) // (level 4) 'symbol' : exception specification does not match previous declaration\n#pragma warning (default: 4987) // (level 4) nonstandard extension used : 'throw (...)'\n#pragma warning (default: 4988) // (level 4) 'symbol' : variable declared outside class / function scope\n#pragma warning (default: 5024) // (level 4) 'type' : move constructor was implicitly defined as deleted\n#pragma warning (default: 5025) // (level 4) 'type' : move assignment operator was implicitly defined as deleted\n#pragma warning (default: 5029) // (level 4) nonstandard extension used : alignment attributes in C++ apply to variables, data members and tag types only\n#pragma warning (default: 5031) // (level 4) #pragma warning(pop) : likely mismatch, popping warning state pushed in different file\n#pragma warning (default: 5032) // (level 4) detected #pragma warning(push) with no corresponding #pragma warning(pop)\n#pragma warning (default: 5039) // (level 4) 'function' : pointer or reference to potentially throwing function passed to extern C function under - EHc.Undefined behavior may occur if this function throws an exception.\n#pragma warning (default: 5038) // (level 4) data member 'member1' will be initialized after data member 'member2'\n#pragma warning (default: 4355) // 'this' : used in base member initializer list\n#pragma warning (default: 4746) // volatile access of 'expression' is subject to / volatile : <iso | ms> setting; consider using __iso_volatile_load / store intrinsic functions\n#pragma warning (default: 4962) // 'function': profile - guided optimizations disabled because optimizations caused profile data to become inconsistent\n#pragma warning (default: 5022) // 'type' : multiple move constructors specified\n#pragma warning (default: 5023) // 'type' : multiple move assignment operators specified\n#pragma warning (default: 5034) // use of intrinsic 'intrinsic' causes function function to be compiled as guest code\n#pragma warning (default: 5035) // use of feature 'feature' causes function function to be compiled as guest code\n\n// <tas=\"Following default warnings count many thousands. For later evaluation separately\"/>\n#pragma warning(disable : 5026) // (level 1 and level 4) 'type': move constructor was implicitly defined as deleted\n#pragma warning (disable: 5027) // (level 1 and level 4) 'type' : move assignment operator was implicitly defined as deleted\n#pragma warning (disable: 5031) // #pragma warning(pop) : likely mismatch, popping warning state pushed in different file\n\n// <tas=\"Following warnings occur many times in Oda libraries\"/>\n#pragma warning(disable : 4619) // (level 3) there is no warning number 'number'\n\n// <tas=\"Following off by default warnings (defaulted above) occur many times in Oda libraries. For later evaluation separately\"/>\n#pragma warning(disable : 4514) // (level 4) 'function' : unreferenced inline function has been removed\n#pragma warning (disable: 4625) // (level 4) 'derived class' : copy constructor could not be generated because a base class copy constructor is inaccessible\n#pragma warning (disable: 4626) // (level 4) 'derived class' : assignment operator could not be generated because a base class assignment operator is inaccessible\n#pragma warning (disable: 4800) // (level 4) Implicit conversion from 'type' to bool.Possible information loss\n#pragma warning (disable: 4820) // (level 4) 'bytes' bytes padding added after construct 'member_name'\n", "meta": {"hexsha": "4dc8a16e956c169064b98e3b00d77914414fb988", "size": 16727, "ext": "h", "lang": "C", "max_stars_repo_path": "AeSys/Stdafx.h", "max_stars_repo_name": "terry-texas-us/Eo", "max_stars_repo_head_hexsha": "5652b68468c0bacd8e8da732befa2374360a4bbd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-07T07:06:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-07T07:06:19.000Z", "max_issues_repo_path": "AeSys/Stdafx.h", "max_issues_repo_name": "terry-texas-us/Eo", "max_issues_repo_head_hexsha": "5652b68468c0bacd8e8da732befa2374360a4bbd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AeSys/Stdafx.h", "max_forks_repo_name": "terry-texas-us/Eo", "max_forks_repo_head_hexsha": "5652b68468c0bacd8e8da732befa2374360a4bbd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-10-24T00:36:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-30T16:45:56.000Z", "avg_line_length": 97.25, "max_line_length": 218, "alphanum_fraction": 0.7526753154, "num_tokens": 4210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11436851712592715, "lm_q2_score": 0.022629197478864004, "lm_q1q2_score": 0.0025880677594074452}}
{"text": "#pragma once\n\n#include \"memcached/types.h\"\n#include \"slabs.h\"\n\n#include <gsl/gsl-lite.h>\n#include <atomic>\n#include <cstddef>\n#include <cstring>\n\n/*\n * You should not try to aquire any of the item locks before calling these\n * functions.\n */\ntypedef struct _hash_item {\n    struct _hash_item* next;\n    struct _hash_item* prev;\n    struct _hash_item* h_next; /* hash chain next */\n    /**\n     * The unique identifier for this item (it is guaranteed to be unique\n     * per key, which means that a two different version of a document\n     * cannot have the same CAS value (This is not true after a server\n     * restart given that default_bucket is an in-memory bucket).\n     */\n    uint64_t cas;\n\n    /** least recent access */\n    rel_time_t time;\n\n    /** When the item will expire (relative to process startup) */\n    rel_time_t exptime;\n\n    /**\n     * When the current lock for the object expire. If locktime < \"current\n     * time\" the item isn't locked anymore (timed out). If locktime >=\n     * \"current time\" the object is locked.\n     */\n    rel_time_t locktime;\n\n    /** The total size of the data (in bytes) */\n    uint32_t nbytes;\n\n    /** Flags associated with the item (in network byte order) */\n    uint32_t flags;\n\n    /**\n     * The number of entities holding a reference to this item object (we\n     * operate in a copy'n'write context so it is always safe for all of\n     * our clients to share an existing object, but we need the refcount\n     * so that we know when we can release the object.\n     */\n    uint16_t refcount;\n\n    /** Intermal flags used by the engine.*/\n    std::atomic<uint8_t> iflag;\n\n    /** which slab class we're in */\n    uint8_t slabs_clsid;\n\n    /** to identify the type of the data */\n    uint8_t datatype;\n\n    // There is 3 spare bytes due to alignment\n} hash_item;\n\n/*\n    The structure of the key we hash with.\n\n    This is a combination of the bucket index and the client's key.\n\n    To respect the memcached protocol we support keys > 250, even\n    though the current frontend doesn't.\n\n    Keys upto 128 bytes long will be carried wholly on the stack,\n    larger keys go on the heap.\n*/\ntypedef struct _hash_key_sized {\n    bucket_id_t bucket_index;\n    uint8_t client_key[128];\n} hash_key_sized;\n\ntypedef struct _hash_key_data {\n    bucket_id_t bucket_index;\n    uint8_t client_key[1];\n} hash_key_data;\n\ntypedef struct _hash_key_header {\n    uint16_t len; /* length of the hash key (bucket_index+client) */\n    hash_key_data* full_key; /* points to hash_key::key_storage or a malloc blob*/\n} hash_key_header;\n\ntypedef struct _hash_key {\n    hash_key_header header;\n    hash_key_sized key_storage;\n} hash_key;\n\nstatic inline uint8_t* hash_key_get_key(const hash_key* key) {\n    return (uint8_t*)key->header.full_key;\n}\n\nstatic inline bucket_id_t hash_key_get_bucket_index(const hash_key* key) {\n    return key->header.full_key->bucket_index;\n}\n\nstatic inline void hash_key_set_bucket_index(hash_key* key,\n                                             bucket_id_t bucket_index) {\n    key->header.full_key->bucket_index = bucket_index;\n}\n\nstatic inline uint16_t hash_key_get_key_len(const hash_key* key) {\n    return key->header.len;\n}\n\nstatic inline void hash_key_set_len(hash_key* key, uint16_t len) {\n    key->header.len = len;\n}\n\nstatic inline uint8_t* hash_key_get_client_key(const hash_key* key) {\n    return key->header.full_key->client_key;\n}\n\nstatic inline uint16_t hash_key_get_client_key_len(const hash_key* key) {\n    return hash_key_get_key_len(key) -\n           gsl::narrow<uint16_t>(sizeof(key->header.full_key->bucket_index));\n}\n\nstatic inline void hash_key_set_client_key(hash_key* key,\n                                           const void* client_key,\n                                           const size_t client_key_len) {\n    memcpy(key->header.full_key->client_key, client_key, client_key_len);\n}\n\n/*\n * return the bytes needed to store the hash_key structure\n * in a single contiguous allocation.\n */\nstatic inline size_t hash_key_get_alloc_size(const hash_key* key) {\n    return offsetof(hash_key, key_storage) + hash_key_get_key_len(key);\n}\n\ntypedef struct {\n    unsigned int evicted;\n    unsigned int evicted_nonzero;\n    rel_time_t evicted_time;\n    unsigned int outofmemory;\n    unsigned int tailrepairs;\n    unsigned int reclaimed;\n} itemstats_t;\n\nstruct items {\n   hash_item *heads[POWER_LARGEST];\n   hash_item *tails[POWER_LARGEST];\n   itemstats_t itemstats[POWER_LARGEST];\n   unsigned int sizes[POWER_LARGEST];\n   /*\n    * serialise access to the items data\n   */\n   std::mutex lock;\n};\n\n\n/**\n * Allocate and initialize a new item structure\n * @param engine handle to the storage engine\n * @param key the key for the new item\n * @param nkey the number of bytes in the key\n * @param flags the flags in the new item\n * @param exptime when the object should expire\n * @param nbytes the number of bytes in the body for the item\n * @return a pointer to an item on success NULL otherwise\n */\nhash_item *item_alloc(struct default_engine *engine,\n                      const void *key, const size_t nkey, int flags,\n                      rel_time_t exptime, int nbytes, const void *cookie,\n                      uint8_t datatype);\n\n/**\n * Get an item from the cache\n *\n * @param engine handle to the storage engine\n * @param cookie connection cookie\n * @param key the key for the item to get\n * @param nkey the number of bytes in the key\n * @param state Only return documents in this state\n * @return pointer to the item if it exists or NULL otherwise\n */\nhash_item* item_get(struct default_engine* engine,\n                    const void* cookie,\n                    const void* key,\n                    const size_t nkey,\n                    const DocStateFilter state);\n\n/**\n * Get an item from the cache using a hash_key\n *\n * @param engine handle to the storage engine\n * @param cookie connection cookie\n * @param key to lookup\n * @param state Only return documents in this state\n * @return pointer to the item if it exists or NULL otherwise\n */\nhash_item* item_get(struct default_engine* engine,\n                    const void* cookie,\n                    const hash_key& key,\n                    const DocStateFilter state);\n\n/**\n * Get an item from the cache and acquire the lock.\n *\n * @param engine handle to the storage engine\n * @param cookie connection cookie\n * @param where to return the item (if found)\n * @param key the key for the item to get\n * @param nkey the number of bytes in the key\n * @param locktime when the item expire\n * @return ENGINE_SUCCESS for success\n */\nENGINE_ERROR_CODE item_get_locked(struct default_engine* engine,\n                                  const void* cookie,\n                                  hash_item** it,\n                                  const void* key,\n                                  const size_t nkey,\n                                  rel_time_t locktime);\n\n/**\n * Get and touch an item\n *\n * @param engine handle to the storage engine\n * @param cookie connection cookie\n * @param where to return the item (if found)\n * @param key the key for the item to get\n * @param nkey the number of bytes in the key\n * @param exptime The new expiry time\n * @return ENGINE_SUCCESS for success\n */\nENGINE_ERROR_CODE item_get_and_touch(struct default_engine* engine,\n                                     const void* cookie,\n                                     hash_item** it,\n                                     const void* key,\n                                     const size_t nkey,\n                                     rel_time_t exptime);\n\n\n/**\n * Unlock an item in the cache\n *\n * @param engine handle to the storage engine\n * @param cookie connection cookie\n * @param key the key for the item to unlock\n * @param nkey the number of bytes in the key\n * @param cas value for the locked value\n * @return ENGINE_SUCCESS for success\n */\nENGINE_ERROR_CODE item_unlock(struct default_engine* engine,\n                              const void* cookie,\n                              const void* key,\n                              const size_t nkey,\n                              uint64_t cas);\n\n/**\n * Reset the item statistics\n * @param engine handle to the storage engine\n */\nvoid item_stats_reset(struct default_engine *engine);\n\n/**\n * Get item statitistics\n * @param engine handle to the storage engine\n * @param add_stat callback provided by the core used to\n *                 push statistics into the response\n * @param cookie cookie provided by the core to identify the client\n */\nvoid item_stats(struct default_engine* engine,\n                const AddStatFn& add_stat,\n                const void* cookie);\n\n/**\n * Get detaild item statitistics\n * @param engine handle to the storage engine\n * @param add_stat callback provided by the core used to\n *                 push statistics into the response\n * @param cookie cookie provided by the core to identify the client\n */\nvoid item_stats_sizes(struct default_engine* engine,\n                      const AddStatFn& add_stat,\n                      const void* cookie);\n\n/**\n * Flush expired items from the cache\n * @param engine handle to the storage engine\n */\nvoid  item_flush_expired(struct default_engine *engine);\n\n/**\n * Release our reference to the current item\n * @param engine handle to the storage engine\n * @param it the item to release\n */\nvoid item_release(struct default_engine *engine, hash_item *it);\n\n/**\n * Unlink the item from the hash table (make it inaccessible)\n * @param engine handle to the storage engine\n * @param it the item to unlink\n */\nvoid item_unlink(struct default_engine *engine, hash_item *it);\n\n/**\n * Unlink the item from the hash table (make it inaccessible),\n * but only if the CAS value in the item is the same as the\n * one in the hash table (two different connections may operate\n * on the same objects, so the cas value for the value in the\n * hashtable may be different than the items value. We need\n * to have exclusive access to the hashtable to do the actual\n * unlink)\n *\n * @param engine handle to the storage engine\n * @param it the item to unlink\n */\nENGINE_ERROR_CODE safe_item_unlink(struct default_engine *engine,\n                                   hash_item *it);\n\n/**\n * Store an item in the cache\n * @param engine handle to the storage engine\n * @param item the item to store\n * @param cas the cas value (OUT)\n * @param operation what kind of store operation is this (ADD/SET etc)\n * @param document_state the state of the document to store\n * @return ENGINE_SUCCESS on success\n *\n * @todo should we refactor this into hash_item ** and remove the cas\n *       there so that we can get it from the item instead?\n */\nENGINE_ERROR_CODE store_item(struct default_engine *engine,\n                             hash_item *item,\n                             uint64_t *cas,\n                             ENGINE_STORE_OPERATION operation,\n                             const void *cookie,\n                             const DocumentState document_state);\n\n/**\n * Run a single scrub loop for the engine.\n * @param engine handle to the storage engine\n */\nvoid item_scrubber_main(struct default_engine *engine);\n\n/**\n * Start the item scrubber for the engine\n * @param engine handle to the storage engine\n * @return true if the scrubber has been invoked\n */\nbool item_start_scrub(struct default_engine *engine);\n", "meta": {"hexsha": "3177d49768358de4ada0d7cd5410612f663b6caf", "size": 11335, "ext": "h", "lang": "C", "max_stars_repo_path": "engines/default_engine/items.h", "max_stars_repo_name": "hrajput89/kv_engine", "max_stars_repo_head_hexsha": "33fb1ab2c9787f55555e5f7edea38807b3dbc371", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-13T07:33:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-13T07:33:09.000Z", "max_issues_repo_path": "engines/default_engine/items.h", "max_issues_repo_name": "paolococchi/kv_engine", "max_issues_repo_head_hexsha": "40256dca6bf77fb4bcc18e8ef7d9b8f991bf4e45", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "engines/default_engine/items.h", "max_forks_repo_name": "paolococchi/kv_engine", "max_forks_repo_head_hexsha": "40256dca6bf77fb4bcc18e8ef7d9b8f991bf4e45", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-01-15T16:52:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-15T16:52:37.000Z", "avg_line_length": 32.0197740113, "max_line_length": 82, "alphanum_fraction": 0.6599911778, "num_tokens": 2487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1311732373477186, "lm_q2_score": 0.01971912817935751, "lm_q1q2_score": 0.002586621880960949}}
{"text": "//\r\n//  Author  : github.com/luncliff (luncliff@gmail.com)\r\n//  License : CC BY 4.0\r\n//\r\n//  Note\r\n//      Async I/O operation support for socket\r\n//\r\n#pragma once\r\n// clang-format off\r\n#if defined(FORCE_STATIC_LINK)\r\n#   define _INTERFACE_\r\n#   define _HIDDEN_\r\n#elif defined(_MSC_VER) // MSVC or clang-cl\r\n#   define _HIDDEN_\r\n#   ifdef _WINDLL\r\n#       define _INTERFACE_ __declspec(dllexport)\r\n#   else\r\n#       define _INTERFACE_ __declspec(dllimport)\r\n#   endif\r\n#elif defined(__GNUC__) || defined(__clang__)\r\n#   define _INTERFACE_ __attribute__((visibility(\"default\")))\r\n#   define _HIDDEN_ __attribute__((visibility(\"hidden\")))\r\n#else\r\n#   error \"unexpected linking configuration\"\r\n#endif\r\n// clang-format on\r\n\r\n#ifndef COROUTINE_NET_IO_H\r\n#define COROUTINE_NET_IO_H\r\n\r\n#include <chrono>\r\n#include <gsl/gsl>\r\n#include <coroutine/yield.hpp>\r\n\r\n#if __has_include(<WinSock2.h>) // use winsock\r\n#include <WS2tcpip.h>\r\n#include <WinSock2.h>\r\n#include <ws2def.h>\r\n\r\nusing io_control_block = OVERLAPPED;\r\n\r\nstatic constexpr bool is_winsock = true;\r\nstatic constexpr bool is_netinet = false;\r\n\r\n#elif __has_include(<netinet/in.h>) // use netinet\r\n#include <fcntl.h>\r\n#include <netdb.h>\r\n#include <netinet/in.h>\r\n#include <netinet/tcp.h>\r\n#include <sys/socket.h>\r\n#include <unistd.h>\r\n\r\n// Follow the definition of Windows `OVERLAPPED`\r\nstruct io_control_block {\r\n    uint64_t internal;      // uint32_t errc, int32_t flag\r\n    uint64_t internal_high; // int64_t len, socklen_t addrlen\r\n    union {\r\n        struct {\r\n            int32_t offset;\r\n            int32_t offset_high;\r\n        };\r\n        void* ptr; // sockaddr* addr;\r\n    };\r\n    int64_t handle; // int64_t sd;\r\n};\r\n\r\nstatic constexpr bool is_winsock = false;\r\nstatic constexpr bool is_netinet = true;\r\n\r\n#endif // winsock || netinet\r\n\r\nnamespace coro {\r\nusing namespace std;\r\nusing namespace std::experimental;\r\n\r\n//  1 I/O task == 1 coroutine function\r\nusing io_task_t = coroutine_handle<void>;\r\n\r\n//  This is simply a view to storage. Be aware that it doesn't have ownership\r\nusing io_buffer_t = gsl::span<std::byte>;\r\nstatic_assert(sizeof(io_buffer_t) <= sizeof(void*) * 2);\r\n\r\n//  A struct to describe \"1 I/O request\" to system API\r\nclass io_work_t : public io_control_block {\r\n  public:\r\n    io_task_t task{};\r\n    io_buffer_t buffer{};\r\n\r\n  protected:\r\n    _INTERFACE_ bool ready() const noexcept;\r\n\r\n  public:\r\n    // Multiple retrieving won't be a matter\r\n    _INTERFACE_ uint32_t error() const noexcept;\r\n};\r\nstatic_assert(sizeof(io_work_t) <= 56);\r\n\r\n//  Type to perform `sendto` I/O request\r\nclass io_send_to final : public io_work_t {\r\n  private:\r\n    // This function must be used through `co_await`\r\n    _INTERFACE_ void suspend(io_task_t t) noexcept(false);\r\n    // This function must be used through `co_await`\r\n    // Unlike inherited `error` function, multiple invoke of this will\r\n    // lead to malfunction.\r\n    _INTERFACE_ int64_t resume() noexcept;\r\n\r\n  public:\r\n    bool await_ready() const noexcept {\r\n        return this->ready();\r\n    }\r\n    void await_suspend(io_task_t t) noexcept(false) {\r\n        return this->suspend(t);\r\n    }\r\n    auto await_resume() noexcept {\r\n        return this->resume();\r\n    }\r\n};\r\nstatic_assert(sizeof(io_send_to) == sizeof(io_work_t));\r\n\r\n//  Type to perform `recvfrom` I/O request\r\nclass io_recv_from final : public io_work_t {\r\n  private:\r\n    // This function must be used through `co_await`\r\n    _INTERFACE_ void suspend(io_task_t t) noexcept(false);\r\n    // This function must be used through `co_await`\r\n    // Unlike inherited `error` function, multiple invoke of this will\r\n    // lead to malfunction.\r\n    _INTERFACE_ int64_t resume() noexcept;\r\n\r\n  public:\r\n    bool await_ready() const noexcept {\r\n        return this->ready();\r\n    }\r\n    void await_suspend(io_task_t t) noexcept(false) {\r\n        return this->suspend(t);\r\n    }\r\n    auto await_resume() noexcept {\r\n        return this->resume();\r\n    }\r\n};\r\nstatic_assert(sizeof(io_recv_from) == sizeof(io_work_t));\r\n\r\n//  Type to perform `send` I/O request\r\nclass io_send final : public io_work_t {\r\n  private:\r\n    // This function must be used through `co_await`\r\n    _INTERFACE_ void suspend(io_task_t t) noexcept(false);\r\n    // This function must be used through `co_await`\r\n    // Unlike inherited `error` function, multiple invoke of this will\r\n    // lead to malfunction.\r\n    _INTERFACE_ int64_t resume() noexcept;\r\n\r\n  public:\r\n    bool await_ready() const noexcept {\r\n        return this->ready();\r\n    }\r\n    void await_suspend(io_task_t t) noexcept(false) {\r\n        return this->suspend(t);\r\n    }\r\n    auto await_resume() noexcept {\r\n        return this->resume();\r\n    }\r\n};\r\nstatic_assert(sizeof(io_send) == sizeof(io_work_t));\r\n\r\n//  Type to perform `recv` I/O request\r\nclass io_recv final : public io_work_t {\r\n  private:\r\n    // This function must be used through `co_await`\r\n    _INTERFACE_ void suspend(io_task_t t) noexcept(false);\r\n    // This function must be used through `co_await`\r\n    // Unlike inherited `error` function, multiple invoke of this will\r\n    // lead to malfunction.\r\n    _INTERFACE_ int64_t resume() noexcept;\r\n\r\n  public:\r\n    bool await_ready() const noexcept {\r\n        return this->ready();\r\n    }\r\n    void await_suspend(io_task_t t) noexcept(false) {\r\n        return this->suspend(t);\r\n    }\r\n    auto await_resume() noexcept {\r\n        return this->resume();\r\n    }\r\n};\r\nstatic_assert(sizeof(io_recv) == sizeof(io_work_t));\r\n\r\n//  Constructs awaitable `io_send_to` object with the given parameters\r\n[[nodiscard]] _INTERFACE_                                     //\r\n    auto                                                      //\r\n    send_to(uint64_t sd, const sockaddr_in& remote,           //\r\n            io_buffer_t buf, io_work_t& work) noexcept(false) //\r\n    -> io_send_to&;\r\n\r\n//  Constructs awaitable `io_send_to` object with the given parameters\r\n[[nodiscard]] _INTERFACE_                                             //\r\n    auto                                                              //\r\n    send_to(uint64_t sd, const sockaddr_in6& remote, io_buffer_t buf, //\r\n            io_work_t& work) noexcept(false)                          //\r\n    -> io_send_to&;\r\n\r\n//  Constructs awaitable `io_recv_from` object with the given parameters\r\n[[nodiscard]] _INTERFACE_                                        //\r\n    auto                                                         //\r\n    recv_from(uint64_t sd, sockaddr_in& remote, io_buffer_t buf, //\r\n              io_work_t& work) noexcept(false)                   //\r\n    -> io_recv_from&;\r\n\r\n//  Constructs awaitable `io_recv_from` object with the given parameters\r\n[[nodiscard]] _INTERFACE_                                         //\r\n    auto                                                          //\r\n    recv_from(uint64_t sd, sockaddr_in6& remote, io_buffer_t buf, //\r\n              io_work_t& work) noexcept(false)                    //\r\n    -> io_recv_from&;\r\n\r\n//  Constructs awaitable `io_send` object with the given parameters\r\n[[nodiscard]] _INTERFACE_                                    //\r\n    auto                                                     //\r\n    send_stream(uint64_t sd, io_buffer_t buf, uint32_t flag, //\r\n                io_work_t& work) noexcept(false)             //\r\n    -> io_send&;\r\n\r\n//  Constructs awaitable `io_recv` object with the given parameters\r\n[[nodiscard]] _INTERFACE_                                    //\r\n    auto                                                     //\r\n    recv_stream(uint64_t sd, io_buffer_t buf, uint32_t flag, //\r\n                io_work_t& work) noexcept(false)             //\r\n    -> io_recv&;\r\n\r\n//  This function is for non-Windows platform.\r\n//  Over Windows api, it always yields **nothing**.\r\n//\r\n//  Its caller must continue the loop without break\r\n//  so there is no leak of the I/O events\r\n//\r\n//  Also, the library doesn't guarantee all coroutines(i/o tasks) will be\r\n//  fetched at once. Therefore it is strongly recommended for user to have\r\n//  another method to detect that watching I/O coroutines are returned.\r\n_INTERFACE_\r\nvoid wait_net_tasks(enumerable<io_task_t>& tasks,\r\n                    chrono::nanoseconds timeout) noexcept(false);\r\n\r\ninline auto wait_net_tasks(chrono::nanoseconds timeout) noexcept(false) {\r\n    enumerable<io_task_t> tasks{};\r\n    wait_net_tasks(tasks, timeout);\r\n    return tasks;\r\n}\r\n\r\n//\r\n//  Name resolution utilities\r\n//\r\n\r\nusing zstring_host = gsl::zstring<NI_MAXHOST>;\r\nusing zstring_serv = gsl::zstring<NI_MAXSERV>;\r\nusing czstring_host = gsl::czstring<NI_MAXHOST>;\r\nusing czstring_serv = gsl::czstring<NI_MAXSERV>;\r\n\r\n//  Combination of `getaddrinfo` functions\r\n//  If there is an error, the enumerable is untouched\r\n_INTERFACE_\r\nint32_t resolve(enumerable<sockaddr>& g, const addrinfo& hint, //\r\n                czstring_host name, czstring_serv serv) noexcept;\r\n\r\n// construct system_error using `gai_strerror` function\r\n_INTERFACE_\r\nauto resolve_error(int32_t ec) noexcept -> std::system_error;\r\n\r\ninline auto resolve(const addrinfo& hint, //\r\n                    czstring_host name, czstring_serv serv) noexcept(false)\r\n    -> enumerable<sockaddr> {\r\n    enumerable<sockaddr> g{};\r\n    if (const auto ec = resolve(g, hint, name, serv)) {\r\n        throw resolve_error(ec);\r\n    }\r\n    return g;\r\n}\r\n\r\n//  Thin wrapper of `getnameinfo`. Parameter 'serv' can be nullptr.\r\n_INTERFACE_\r\nint32_t get_name(const sockaddr_in& addr, zstring_host name, zstring_serv serv,\r\n                 int32_t flags = NI_NUMERICHOST | NI_NUMERICSERV) noexcept;\r\n_INTERFACE_\r\nint32_t get_name(const sockaddr_in6& addr, zstring_host name, zstring_serv serv,\r\n                 int32_t flags = NI_NUMERICHOST | NI_NUMERICSERV) noexcept;\r\n\r\n} // namespace coro\r\n\r\n#endif // COROUTINE_NET_IO_H\r\n", "meta": {"hexsha": "20098f7d6b06a607f903ab17776fe2decbbd8d19", "size": 9796, "ext": "h", "lang": "C", "max_stars_repo_path": "interface/coroutine/net.h", "max_stars_repo_name": "Farwaykorse/coroutine", "max_stars_repo_head_hexsha": "cfe7f0ca5ab4670e539a9f4d6c69d85ba4cb18f7", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "interface/coroutine/net.h", "max_issues_repo_name": "Farwaykorse/coroutine", "max_issues_repo_head_hexsha": "cfe7f0ca5ab4670e539a9f4d6c69d85ba4cb18f7", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "interface/coroutine/net.h", "max_forks_repo_name": "Farwaykorse/coroutine", "max_forks_repo_head_hexsha": "cfe7f0ca5ab4670e539a9f4d6c69d85ba4cb18f7", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6632302405, "max_line_length": 81, "alphanum_fraction": 0.6246427113, "num_tokens": 2213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.05419873440629665, "lm_q2_score": 0.04742587469223236, "lm_q1q2_score": 0.0025704223864306077}}
{"text": "/* -----------------------------------------------------------------------------\n * Copyright 2021 Jonathan Haigh\n * SPDX-License-Identifier: MIT\n * ---------------------------------------------------------------------------*/\n\n#ifndef SQ_INCLUDE_GUARD_parser_FilterSpec_h_\n#define SQ_INCLUDE_GUARD_parser_FilterSpec_h_\n\n#include \"core/Primitive.h\"\n#include \"core/typeutil.h\"\n\n#include <compare>\n#include <gsl/gsl>\n#include <iosfwd>\n#include <optional>\n#include <variant>\n\nnamespace sq::parser {\n\n/**\n * Represents the lack of a filter specification for a field access.\n */\nstruct NoFilterSpec {\n  SQ_ND auto operator<=>(const NoFilterSpec &) const = default;\n};\nstd::ostream &operator<<(std::ostream &os, NoFilterSpec nlfs);\n\n/**\n * Represents access of an indexed element in a list of results for a field\n * access.\n */\nstruct ElementAccessSpec {\n  gsl::index index_;\n  SQ_ND auto operator<=>(const ElementAccessSpec &) const = default;\n};\nstd::ostream &operator<<(std::ostream &os, ElementAccessSpec leas);\n\n/**\n * Represents a Python-style slice of a list of results for a field access.\n */\nstruct SliceSpec {\n  std::optional<gsl::index> start_;\n  std::optional<gsl::index> stop_;\n  std::optional<gsl::index> step_;\n  SQ_ND auto operator<=>(const SliceSpec &) const = default;\n};\nstd::ostream &operator<<(std::ostream &os, SliceSpec lss);\n\nenum class ComparisonOperator {\n  GreaterThanOrEqualTo,\n  GreaterThan,\n  LessThanOrEqualTo,\n  LessThan,\n  Equals\n};\n\n/**\n * Represents a comparison to determine whether to keep a field or not.\n */\nstruct ComparisonSpec {\n  std::string member_;\n  ComparisonOperator op_;\n  Primitive value_;\n  SQ_ND auto operator<=>(const ComparisonSpec &) const = default;\n};\n\nstd::ostream &operator<<(std::ostream &os, const ComparisonOperator &op);\nstd::ostream &operator<<(std::ostream &os, const ComparisonSpec &cs);\n\nusing FilterSpec =\n    std::variant<NoFilterSpec, ElementAccessSpec, SliceSpec, ComparisonSpec>;\n\n} // namespace sq::parser\n\n#endif // SQ_INCLUDE_GUARD_parser_FilterSpec_h_\n", "meta": {"hexsha": "af58e43b58ba955b0520a3f5a140e6d3e5f5043b", "size": 2022, "ext": "h", "lang": "C", "max_stars_repo_path": "src/parser/include/parser/FilterSpec.h", "max_stars_repo_name": "jonathanhaigh/sq", "max_stars_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-12T16:21:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-12T16:21:41.000Z", "max_issues_repo_path": "src/parser/include/parser/FilterSpec.h", "max_issues_repo_name": "jonathanhaigh/sq", "max_issues_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 44.0, "max_issues_repo_issues_event_min_datetime": "2021-02-08T19:17:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-05T18:51:38.000Z", "max_forks_repo_path": "src/parser/include/parser/FilterSpec.h", "max_forks_repo_name": "jonathanhaigh/sq", "max_forks_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6052631579, "max_line_length": 80, "alphanum_fraction": 0.6770524233, "num_tokens": 457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12592277139559052, "lm_q2_score": 0.02033235230380465, "lm_q1q2_score": 0.002560306151086601}}
{"text": "#pragma once\n\n#include <gsl/pointers>  // contains gsl::not_null\n\nclass Consultant;\n\nclass PaymentCalculator {\n public:\n  double calculate() const { return {}; }\n\n  void setConsultant(const Consultant &c) { consultant_ = &consultant_; }\n\n  void setTaxPercentage(double tax) { taxPercentage_ = tax; }\n\n private:\n  gsl::not_null<const Consultant *> consultant_;\n  double taxPercentage_;\n};\n", "meta": {"hexsha": "7a8dc4d5139a41470352459ed09935176eb5376a", "size": 388, "ext": "h", "lang": "C", "max_stars_repo_path": "Chapter02/state/PaymentCalculatorV2.h", "max_stars_repo_name": "gbellizio/Software-Architecture-with-Cpp", "max_stars_repo_head_hexsha": "eb0f7a52ef1253d9b0091714eee9c94c156b02bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 193.0, "max_stars_repo_stars_event_min_datetime": "2021-03-27T00:46:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T07:25:00.000Z", "max_issues_repo_path": "Chapter02/state/PaymentCalculatorV2.h", "max_issues_repo_name": "gbellizio/Software-Architecture-with-Cpp", "max_issues_repo_head_hexsha": "eb0f7a52ef1253d9b0091714eee9c94c156b02bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T05:48:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T12:16:54.000Z", "max_forks_repo_path": "Chapter02/state/PaymentCalculatorV2.h", "max_forks_repo_name": "gbellizio/Software-Architecture-with-Cpp", "max_forks_repo_head_hexsha": "eb0f7a52ef1253d9b0091714eee9c94c156b02bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 64.0, "max_forks_repo_forks_event_min_datetime": "2021-04-01T02:18:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T12:32:29.000Z", "avg_line_length": 20.4210526316, "max_line_length": 73, "alphanum_fraction": 0.7242268041, "num_tokens": 90, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.0675466911396291, "lm_q2_score": 0.03789242486405945, "lm_q1q2_score": 0.0025595079188242263}}
{"text": "#pragma once\n\n#include <gsl/span>\n\n/**\n* This header is mainly for shorthands when dealing with `gsl::span`s\n* see the `gsl` or c++ core guidelines for more info on what a `gsl::span` is/does.\n*/\n\nnamespace riner {\n    \n    template<class T, std::ptrdiff_t Extent = gsl::dynamic_extent>\n    using span = gsl::span<T, Extent>;\n\n    template<std::ptrdiff_t Extent = gsl::dynamic_extent>\n    using ByteSpan = span<uint8_t, Extent>;\n\n    template<std::ptrdiff_t Extent = gsl::dynamic_extent>\n    using cByteSpan = span<const uint8_t, Extent>;\n}\n", "meta": {"hexsha": "81a1ee0b959d615c447d1260fdb3527a7692033f", "size": 541, "ext": "h", "lang": "C", "max_stars_repo_path": "src/common/Span.h", "max_stars_repo_name": "DavHau/Riner", "max_stars_repo_head_hexsha": "f9e9815b713572f03497f0e4e66c3f82a0241b66", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-07-24T03:24:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T07:41:08.000Z", "max_issues_repo_path": "src/common/Span.h", "max_issues_repo_name": "DavHau/Riner", "max_issues_repo_head_hexsha": "f9e9815b713572f03497f0e4e66c3f82a0241b66", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-07-30T22:10:39.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-15T15:57:08.000Z", "max_forks_repo_path": "src/common/Span.h", "max_forks_repo_name": "DavHau/Riner", "max_forks_repo_head_hexsha": "f9e9815b713572f03497f0e4e66c3f82a0241b66", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-07-30T21:33:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T20:53:11.000Z", "avg_line_length": 25.7619047619, "max_line_length": 83, "alphanum_fraction": 0.6894639556, "num_tokens": 149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.07369626563712976, "lm_q2_score": 0.034618836349163955, "lm_q1q2_score": 0.0025512789596363102}}
{"text": "/*\n   Copyright [2017-2020] [IBM Corporation]\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n       http://www.apache.org/licenses/LICENSE-2.0\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\n#ifndef __API_FABRIC_ITF__\n#define __API_FABRIC_ITF__\n\n#include <component/base.h> /* component::IBase, DECLARE_COMPONENT_UUID, DECLARE_INTERFACE_UUID */\n#include <common/byte_span.h>\n#include <common/string_view.h>\n\n#include <gsl/span>\n#include <chrono>\n#include <cstddef> /* size_t */\n#include <cstdint> /* uint16_t, uint64_t */\n#include <functional>\n#include <stdexcept> /* runtime_error */\n#include <vector>\n\n#ifndef FABRIC_H\n#define FI_READ (1ULL << 8)\n#define FI_WRITE (1ULL << 9)\n#define FI_RECV (1ULL << 10)\n#define FI_SEND (1ULL << 11)\n#define FI_TRANSMIT FI_SEND\n#define FI_REMOTE_READ (1ULL << 12)\n#define FI_REMOTE_WRITE (1ULL << 13)\n\n#define FI_MULTI_RECV (1ULL << 16)\n#define FI_REMOTE_CQ_DATA (1ULL << 17)\n#define FI_MORE (1ULL << 18)\n#define FI_PEEK (1ULL << 19)\n#define FI_TRIGGER (1ULL << 20)\n#define FI_FENCE (1ULL << 21)\n\n#define FI_COMPLETION (1ULL << 24)\n#define FI_EVENT FI_COMPLETION\n#define FI_INJECT (1ULL << 25)\n#define FI_INJECT_COMPLETE (1ULL << 26)\n#define FI_TRANSMIT_COMPLETE (1ULL << 27)\n#define FI_DELIVERY_COMPLETE (1ULL << 28)\n#define FI_AFFINITY (1ULL << 29)\n#define FI_COMMIT_COMPLETE (1ULL << 30)\n\n#define FI_VARIABLE_MSG (1ULL << 48)\n#define FI_RMA_PMEM (1ULL << 49)\n#define FI_SOURCE_ERR (1ULL << 50)\n#define FI_LOCAL_COMM (1ULL << 51)\n#define FI_REMOTE_COMM (1ULL << 52)\n#define FI_SHARED_AV (1ULL << 53)\n#define FI_PROV_ATTR_ONLY (1ULL << 54)\n#define FI_NUMERICHOST (1ULL << 55)\n#define FI_RMA_EVENT (1ULL << 56)\n#define FI_SOURCE (1ULL << 57)\n#define FI_NAMED_RX_CTX (1ULL << 58)\n#define FI_DIRECTED_RECV (1ULL << 59)\n#endif\n\nstruct iovec; /* definition in <sys/uio.h> */\n\nnamespace component\n{\n\nclass IFabric_runtime_error : public std::runtime_error {\n public:\n  explicit IFabric_runtime_error(const common::string_view what_arg);\n  /**\n   * @return The libfabric error code (enumeration in <rdma/fi_errno.h>)\n   */\n  virtual unsigned id() const noexcept = 0;\n};\n\n/**\n * Fabric/RDMA-based network component\n *\n */\n#pragma GCC diagnostic push\n#if defined            __GNUC__ && 6 < __GNUC__\n#pragma GCC diagnostic ignored \"-Wnoexcept-type\"\n#endif\n\nstruct IFabric_memory_region;\n\nclass IFabric_op_completer {\n public:\n  virtual ~IFabric_op_completer() {}\n\n  /*\n   * Functionality which probably belongs to a higher layer, but which landed\n   * here. Callbacks which return DEFER are enqueued, to be retried after\n   * later callbacks are given a first chance to run.\n   */\n  enum class cb_acceptance { ACCEPT, DEFER };\n\n  /**\n   * Poll completion events; service completion queues and store\n   * events not belonging to group (stall them).  This method will\n   * BOTH service the completion queues and service those events\n   * stalled previously\n   *\n   *  completion_flags,\n   * FI_{SEND,RECV,RMA,ATOMIC,MSG,TAGGED,MULTICAST,(REMOTE_)?READ,(REMOTE_)?WRITE,REMOTE_CQ_DATA,MULTI_RECV},\n   *  are described in \"man fi_cq\" and defined in\n   * libfabric/include/rdma/fabric.h\n   *\n   * @param completion_callback (context_t, completion_flags, std::size_t len,\n   * status_t status, void* error_data)\n   *\n   * @return Number of completions processed\n   */\n  using complete_old = std::function<void(void *context, ::status_t)>;\n  using complete_definite =\n      std::function<void(void *context, ::status_t, std::uint64_t completion_flags, std::size_t len, void *error_data)>;\n  using complete_tentative = std::function<\n      cb_acceptance(void *context, ::status_t, std::uint64_t completion_flags, std::size_t len, void *error_data)>;\n  using complete_param_definite = std::function<\n      void(void *context, ::status_t, std::uint64_t completion_flags, std::size_t len, void *error_data, void *param)>;\n  using complete_param_tentative              = std::function<cb_acceptance(void *context,\n                                                               ::status_t,\n                                                               std::uint64_t completion_flags,\n                                                               std::size_t   len,\n                                                               void *        error_data,\n                                                               void *        param)>;\n  using complete_param_definite_ptr_noexcept  = void (*)(void *context,\n                                                        ::status_t,\n                                                        std::uint64_t completion_flags,\n                                                        std::size_t   len,\n                                                        void *        error_data,\n                                                        void *        param)\n#if 201703L <= __cplusplus\n\tnoexcept\n#endif\n    ;\n  using complete_param_tentative_ptr_noexcept = cb_acceptance (*)(void *context,\n                                                                  ::status_t,\n                                                                  std::uint64_t completion_flags,\n                                                                  std::size_t   len,\n                                                                  void *        error_data,\n                                                                  void *        param)\n#if 201703L <= __cplusplus\n\tnoexcept\n#endif\n\t;\n\n  /**\n   * @throw IFabric_runtime_error - cq_read unhandled error\n   * @throw std::logic_error - called on closed connection\n   */\n  virtual std::size_t poll_completions(const complete_old &completion_callback) = 0;\n  /**\n   * @throw IFabric_runtime_error - cq_read unhandled error\n   * @throw std::logic_error - called on closed connection\n   */\n  virtual std::size_t poll_completions(const complete_definite &completion_callback) = 0;\n  /**\n   * @throw IFabric_runtime_error - cq_read unhandled error\n   * @throw std::logic_error - called on closed connection\n   */\n  virtual std::size_t poll_completions_tentative(const complete_tentative &completion_callback) = 0;\n  /**\n   * @throw IFabric_runtime_error - cq_read unhandled error\n   * @throw std::logic_error - called on closed connection\n   */\n  virtual std::size_t poll_completions(const complete_param_definite &completion_callback, void *callback_param) = 0;\n  /**\n   * @throw IFabric_runtime_error - cq_read unhandled error\n   * @throw std::logic_error - called on closed connection\n   */\n  virtual std::size_t poll_completions_tentative(const complete_param_tentative &completion_callback,\n                                                 void *                          callback_param) = 0;\n  /**\n   * @throw IFabric_runtime_error - cq_read unhandled error\n   * @throw std::logic_error - called on closed connection\n   */\n  virtual std::size_t poll_completions(complete_param_definite_ptr_noexcept completion_callback,\n                                       void *                               callback_param) = 0;\n  /**\n   * @throw IFabric_runtime_error - cq_read unhandled error\n   * @throw std::logic_error - called on closed connection\n   */\n  virtual std::size_t poll_completions_tentative(complete_param_tentative_ptr_noexcept completion_callback,\n                                                 void *                                callback_param) = 0;\n\n  /**\n   * Get count of stalled completions.\n   *\n   * @throw std::system_error, e.g. for locking\n   */\n  virtual std::size_t stalled_completion_count() = 0;\n\n  /**\n   * Block and wait for next completion.\n   *\n   * @param polls_limit Maximum number of polls\n   *\n   * @return (was next completion context. But poll_completions can retrieve\n   * that)\n   *\n   * @throw IFabric_runtime_error - ::fi_control fail\n   * @throw std::system_error - pselect fail\n   */\n  virtual void wait_for_next_completion(unsigned polls_limit = 0) = 0;\n  /**\n   * Block and wait for next completion.\n   *\n   * @param polls_limit Maximum time to wait\n   *\n   * @return (was next completion context. But poll_completions can retrieve\n   * that)\n   *\n   * @throw IFabric_runtime_error - ::fi_control fail\n   * @throw std::system_error - pselect fail\n   */\n  virtual void wait_for_next_completion(std::chrono::milliseconds timeout) = 0;\n\n  /**\n   * Unblock any threads waiting on completions\n   *\n   * @throw std::system_error, e.g. for locking\n   */\n  virtual void unblock_completions() = 0;\n\n  /* Additional TODO:\n     - support for completion and event counters\n     - support for statistics collection\n  */\n};\n\nclass IFabric_memory_control {\n public:\n  using const_byte_span = common::const_byte_span;\n  virtual ~IFabric_memory_control() {}\n\n  using memory_region_t = IFabric_memory_region *;\n  /**\n   * Register buffer for RDMA\n   *\n   * @param contig_addr Pointer to contiguous region\n   * @param size Size of buffer in bytes\n   * @param key Requested key for the remote memory. Note: if the fabric\n   * provider uses the key (i.e., the fabric provider memory region attributes\n   *            do not include the FI_MR_PROV_KEY bit), then the key must be\n   *            unique among registered memory regions. As this API does not\n   *            expose these attributes, the only safe strategy is to assume\n   * that the key must be unique among registered memory regsions.\n   * @param flags Flags e.g., FI_REMOTE_READ|FI_REMOTE_WRITE. Flag definitions\n   * are in <rdma/fabric.h>\n   *\n   * @return Memory region handle\n   *\n   * @throw std::range_error - address already registered\n   * @throw std::logic_error - inconsistent memory registry\n   */\n  virtual memory_region_t register_memory(const void *  contig_addr,\n                                          std::size_t   size,\n                                          std::uint64_t key,\n                                          std::uint64_t flags)\n  { return register_memory(common::make_const_byte_span(contig_addr, size), key, flags); }\n  virtual memory_region_t register_memory(const_byte_span contig_,\n                                          std::uint64_t key,\n                                          std::uint64_t flags) = 0;\n\n  /**\n   * De-register memory region\n   *\n   * @param memory_region Memory region to de-register\n   *\n   * @throw std::range_error - address not registered\n   * @throw std::logic_error - inconsistent memory registry\n   */\n  virtual void deregister_memory(memory_region_t memory_region) = 0;\n\n  virtual std::uint64_t get_memory_remote_key(memory_region_t) const noexcept = 0;\n  virtual void *        get_memory_descriptor(memory_region_t) const noexcept = 0;\n\n  /**\n   * Asynchronously post a buffer to receive data\n   *\n   * @param buffers Buffer span (containing regions should be registered)\n   *\n   * @return Work (context) identifier\n   *\n   * @throw IFabric_runtime_error - ::fi_recvv fail\n   */\n  virtual void post_recv(gsl::span<const ::iovec> buffers, void **descriptors, void *context) = 0;\n  void post_recv(const ::iovec *first, const ::iovec *last, void **descriptors, void *context) { return post_recv( {first, last}, descriptors, context); }\n  virtual void post_recv(gsl::span<const ::iovec> buffers, void *context)                           = 0;\n};\n\nclass IFabric_client;\nclass IFabric_client_grouped;\n\n/**\n * IFabric_initiator\n *  operations unique to a connected endpoint\n */\nclass IFabric_initiator\n{\n public:\n\tvirtual ~IFabric_initiator() {}\n  /**\n   * Asynchronously post a buffer to the connection\n   *\n   * @param buffers Buffer span (containing regions should be registered)\n   *\n   * @return Work (context) identifier\n   *\n   * @throw IFabric_runtime_error std::runtime_error - ::fi_sendv fail\n   */\n  virtual void post_send(gsl::span<const ::iovec> buffers, void **descriptors, void *context) = 0;\n  void post_send(const ::iovec *first, const ::iovec *last, void **descriptors, void *context) { return post_send( {first, last}, descriptors, context); }\n  virtual void post_send(gsl::span<const ::iovec> buffers, void *context)                     = 0;\n\n  /**\n   * Post RDMA read operation\n   *\n   * @param buffers Destination buffer span\n   * @param remote_addr Remote address\n   * @param key Key for remote address\n   * @param out_context\n   *\n   * @throw IFabric_runtime_error - ::fi_readv fail\n   *\n   */\n  virtual void post_read(gsl::span<const ::iovec> buffers,\n                         void **        descriptors,\n                         std::uint64_t  remote_addr,\n                         std::uint64_t  key,\n                         void *         context) = 0;\n\n  void post_read(const ::iovec *first,\n                         const ::iovec *last,\n                         void **        descriptors,\n                         std::uint64_t  remote_addr,\n                         std::uint64_t  key,\n                         void *         context) { return post_read( { first, last }, descriptors, remote_addr, key, context); }\n\n  virtual void post_read(gsl::span<const ::iovec> buffers,\n                         std::uint64_t               remote_addr,\n                         std::uint64_t               key,\n                         void *                      context) = 0;\n\n  /**\n   * Post RDMA write operation\n   *\n   * @param buffers Source buffer span\n   * @param remote_addr Remote address\n   * @param key Key for remote address\n   * @param out_context\n   *\n   * @throw IFabric_runtime_error - ::fi_writev fail\n   *\n   */\n  virtual void post_write(const gsl::span<const ::iovec> buffers,\n                          void **        descriptors,\n                          std::uint64_t  remote_addr,\n                          std::uint64_t  key,\n                          void *         context) = 0;\n\n  void post_write(const ::iovec *first,\n                          const ::iovec *last,\n                          void **        descriptors,\n                          std::uint64_t  remote_addr,\n                          std::uint64_t  key,\n                          void *         context)\n  {\n    return post_write(\n      gsl::span<const ::iovec>(first, last), descriptors, remote_addr, key, context);\n  }\n\n  virtual void post_write(const gsl::span<const ::iovec> buffers,\n                          std::uint64_t               remote_addr,\n                          std::uint64_t               key,\n                          void *                      context) = 0;\n\n  /**\n   * Send message without completion\n   *\n   * @param connection Connection to inject on\n   * @param buf Data to send\n   * @param buf Length of data to send (must not exceed\n   * IFabric_connection::max_inject_size())\n   *\n   * @throw IFabric_runtime_error - ::fi_inject fail\n   */\n  virtual void inject_send(const void *buf, std::size_t len) = 0;\n\n  /* TODO: atomic RMA operations\n  */\n};\n\n/**\n * IFabric_endpoint_connected\n *  operations available to a connected endpoint\n */\nclass IFabric_endpoint_connected\n\t: public IFabric_memory_control\n\t, public IFabric_initiator\n\t, public IFabric_op_completer\n{\n  /* TODO: statistics collection\n  */\n};\n\nclass IFabric_endpoint_unconnected\n\t: public IFabric_memory_control\n{\n};\n\n/**\n * Fabric/RDMA-based network component\n *  an acrive bit not connected endpoint\n */\nclass IFabric_endpoint_unconnected_client : public IFabric_endpoint_unconnected {\n public:\n\n  /**\n   * Open a fabric client (active endpoint) connection to a server. Active\n   * endpoints usually correspond with hardware resources, e.g. verbs queue\n   * pair. Options may not conflict with those specified for the fabric.\n   *\n   * @param json_configuration Configuration string in JSON\n   * @param remote_endpoint The IP address (URL) of the server\n   * @param port The IP port on the server\n   *\n   * @return the endpoint\n   *\n   * @throw std::bad_alloc - destination address alloc failed\n   * @throw std::bad_alloc - libfabric out of memory\n   * @throw std::bad_alloc - libfabric out of memory (creating a new server)\n   * @throw std::bad_alloc - out of memory\n   * @throw std::domain_error : json file parse-detected error\n   * @throw std::logic_error : socket initialized with a negative value (from\n   * ::socket) in Fd_control\n   * @throw std::logic_error : unexpected event\n   * @throw std::system_error : error receiving fabric server name\n   * @throw std::system_error : pselect fail (expecting event)\n   * @throw std::system_error : resolving address\n   * @throw std::system_error : pselect fail\n   * @throw std::system_error : read error on event pipe\n   * @throw std::system_error - writing event pipe (normal callback)\n   * @throw std::system_error - writing event pipe (readerr_eq)\n   * @throw std::system_error - receiving data on socket\n   * @throw IFabric_runtime_error - ::fi_domain fail\n   * @throw IFabric_runtime_error - ::fi_connect fail\n   * @throw IFabric_runtime_error - ::fi_ep_bind fail\n   * @throw IFabric_runtime_error - ::fi_enable fail\n   * @throw IFabric_runtime_error - ::fi_ep_bind fail (event registration)\n   *\n   */\n  virtual IFabric_client *make_open_client() = 0;\n\n  /**\n   * Open a fabric endpoint for which communications are divided into smaller\n   * entities (groups). Options may not conflict with those specified for the\n   * fabric.\n   *\n   * @param json_configuration Configuration string in JSON\n   * @param remote_endpoint The IP address (URL) of the server\n   * @param port The IP port on the server\n   *\n   * @return the endpoint\n   *\n   * @throw std::bad_alloc - destination address alloc failed\n   * @throw std::bad_alloc - libfabric out of memory\n   * @throw std::bad_alloc - libfabric out of memory (creating a new server)\n   * @throw std::bad_alloc - out of memory\n   * @throw std::domain_error : json file parse-detected error\n   * @throw std::logic_error : socket initialized with a negative value (from\n   * ::socket) in Fd_control\n   * @throw std::logic_error : unexpected event\n   * @throw std::system_error : error receiving fabric server name\n   * @throw std::system_error : pselect fail (expecting event)\n   * @throw std::system_error : resolving address\n   * @throw std::system_error : pselect fail\n   * @throw std::system_error : read error on event pipe\n   * @throw std::system_error - writing event pipe (normal callback)\n   * @throw std::system_error - writing event pipe (readerr_eq)\n   * @throw std::system_error - receiving data on socket\n   * @throw IFabric_runtime_error - ::fi_domain fail\n   * @throw IFabric_runtime_error - ::fi_connect fail\n   * @throw IFabric_runtime_error - ::fi_ep_bind fail\n   * @throw IFabric_runtime_error - ::fi_enable fail\n   * @throw IFabric_runtime_error - ::fi_ep_bind fail (event registration)\n   *\n   */\n  virtual IFabric_client_grouped *make_open_client_grouped() = 0;\n};\n\nclass IFabric_connection {\n public:\n  virtual ~IFabric_connection() {}\n\n  /**\n   * Get address of connected peer (taken from fi_getpeer during\n   * connection instantiation). The fi_getpeer documentation says\n   * \"The address  must  be  in the same format as that specified using\n   * fi_info: addr_format when the endpoint was created\". Presumably\n   * this means that the address returned by fi_getpeer *will* be in\n   * that same form, and is thus dependent on the implementation of\n   * endpoint creation.\n   *\n   *\n   * @return Peer endpoint address\n   * @throw std::bad_alloc, e.g.\n   */\n  virtual std::string get_peer_addr() = 0;\n\n  /**\n   * Get local address of connection (taken from fi_getname during\n   * connection instantiation).\n   *\n   *\n   * @return Local endpoint address\n   * @throw std::bad_alloc, e.g.\n   */\n  virtual std::string get_local_addr() = 0;\n\n  /**\n   * Get the maximum message size for the provider\n   *\n   * @return Max message size in bytes\n   */\n  virtual std::size_t max_message_size() const noexcept = 0;\n\n  /**\n   * Get the maximum inject message size for the provider\n   *\n   * @return Max inject message size in bytes\n   */\n  virtual std::size_t max_inject_size() const noexcept = 0;\n\n  /* Additional TODO:\n     - support for atomic RMA operations\n     - support for completion and event counters\n     - support for statistics collection\n  */\n};\n\n/**\n * An endpoint with a communication channel. Distinguished from a connection\n * which can provide grouped communications channels, but does not of itself\n * provide communications.\n *\n */\nclass IFabric_endpoint_comm\n    : public IFabric_connection\n    , public IFabric_endpoint_connected {\n};\n\n/**\n * An endpoint established as a server.\n *\n */\nclass IFabric_server : public IFabric_endpoint_comm {\n};\n\n/**\n * An endpoint established as a client.\n *\n */\nclass IFabric_client : public IFabric_endpoint_comm {\n};\n\n/* A group: memory control, commands, and completions */\nclass IFabric_group\n\t: public IFabric_endpoint_connected\n{\n};\n\n/**\n * An endpoint \"grouped\", without a communication channel.\n * Can provide communications channels, but does not initiate operations\n *\n */\nclass IFabric_endpoint_grouped\n    : public IFabric_connection\n    , public IFabric_memory_control\n    , public IFabric_op_completer\n{\n public:\n  /**\n   * Allocate group (for partitioned completion handling)\n   *\n   * @throw std::system_error, e.g. for locking\n   * @throw std::bad_alloc, e.g.\n   */\n  virtual IFabric_group *allocate_group() = 0;\n};\n\n/**\n * A client endpoint which cannot initiate commands but which\n * can allocate \"commuicators\" which can initiate commands.\n *\n */\nclass IFabric_client_grouped : public IFabric_endpoint_grouped {\n};\n\n/**\n * A server endpoint which cannot initiate commands but which\n * can allocate \"commuicators\" which can initiate commands.\n *\n */\nclass IFabric_server_grouped : public IFabric_endpoint_grouped {\n};\n\n/**\n * Fabric passive endpoint. Instantiation of this interface normally creates\n * an active thread that uses the fabric connection manager to handle\n * connections (see man fi_cm).  On release of the interface, the endpoint\n * is destroyed.\n */\nclass IFabric_passive_endpoint {\n public:\n  virtual ~IFabric_passive_endpoint() {}\n\n  /**\n   * Get the maximum message size for the provider\n   *\n   * @return Max message size in bytes\n   */\n  virtual std::size_t max_message_size() const noexcept = 0;\n\n  /**\n   * Get provider name\n   *\n   *\n   * @return Provider name\n   *\n   * @throw std::bad_alloc, e.g.\n   */\n  virtual std::string get_provider_name() const = 0;\n};\n\nclass IFabric_endpoint_unconnected_server\n\t: public IFabric_endpoint_unconnected\n{\n};\n\n/**\n * Fabric passive endpoint providing servers with ordinary (not grouped)\n * communicators.\n */\nclass IFabric_server_factory : public IFabric_passive_endpoint {\n public:\n  /**\n   * Server/accept side handling of new connections (handled by the\n   * active thread) are queued so that they can be taken by a polling\n   * thread and integrated into the processing loop.  This method is\n   * normally invoked until NULL is returned.\n   *\n   * @return New connection, or NULL if no new connection.\n   *\n   * @throw std::system_error, e.g. for locking\n   * @throw std::logic_error : unexpected event\n   * @throw std::system_error : read error on event pipe\n   * @throw std::system_error : failure to listen for connections\n   */\n\tvirtual IFabric_endpoint_unconnected_server *get_new_endpoint_unconnected() = 0;\n\tvirtual IFabric_server *open_connection(IFabric_endpoint_unconnected_server *) = 0;\n\n  /**\n   * Close connection and release any associated resources\n   *\n   * @param connection\n   *\n   * @throw std::system_error, e.g. for locking\n   */\n  virtual void close_connection(IFabric_server *connection) = 0;\n\n  /**\n   * Used to get a vector of active connection belonging to this\n   * end point.\n   *\n   * @return Vector of active connections\n   *\n   * @throw std::bad_alloc, e.g.\n   */\n  virtual std::vector<IFabric_server *> connections() = 0;\n\n  /**\n   * Get provider name\n   *\n   *\n   * @return Provider name\n   *\n   * @throw std::bad_alloc, e.g.\n   */\n  virtual std::string get_provider_name() const = 0;\n};\n\n/* Fabric passive endpoint providing servers with grouped communicators.\n */\nclass IFabric_server_grouped_factory : public IFabric_passive_endpoint {\n public:\n  /**\n   * Server/accept side handling of new connections (handled by the\n   * active thread) are queued so that they can be taken by a polling\n   * thread an integrated into the processing loop.  This method is\n   * normally invoked until NULL is returned.\n   *\n   *\n   * @return New connection, or NULL if no new connection.\n   *\n   * @throw std::logic_error : unexpected event\n   * @throw std::system_error, e.g. for locking\n   * @throw std::system_error : read error on event pipe\n   */\n\tvirtual IFabric_endpoint_unconnected_server *get_new_endpoint_unconnected() = 0;\n\tvirtual IFabric_server_grouped *open_connection(IFabric_endpoint_unconnected_server *) = 0;\n\n  /**\n   * Close connection and release any associated resources\n   *\n   * @param connection\n   *\n   * @throw std::system_error, e.g. for locking\n   */\n  virtual void close_connection(IFabric_server_grouped *connection) = 0;\n\n  /**\n   * Used to get a vector of active connection belonging to this\n   * end point.\n   *\n   * @return Vector of active connections\n   * @throw std::bad_alloc, e.g.\n   */\n  virtual std::vector<IFabric_server_grouped *> connections() = 0;\n};\n\nclass IFabric {\n public:\n  using memory_region_t = IFabric_memory_region *;\n\n  DECLARE_INTERFACE_UUID(0xc373d083, 0xe629, 0x46c9, 0x86fa, 0x6f, 0x96, 0x40, 0x61, 0x10, 0xdf);\n  virtual ~IFabric() {}\n  /**\n   * Open a fabric server factory. Endpoints usually correspond with hardware\n   * resources, e.g. verbs queue pair. Options may not conflict with those\n   * specified for the fabric.\n   *\n   * @param json_configuration Configuration string in JSON\n   *\n   * @return the endpoint\n   *\n   * @throw std::domain_error : json file parse-detected error\n   * @throw IFabric_runtime_error - ::fi_passive_ep fail\n   * @throw IFabric_runtime_error - ::fi_pep_bind fail\n   * @throw IFabric_runtime_error - ::fi_listen fail\n   */\n  virtual IFabric_server_factory *open_server_factory(const common::string_view json_configuration, std::uint16_t port) = 0;\n  /**\n   * Open a fabric \"server grouped\" factory. Endpoints usually correspond with\n   * hardware resources, e.g. verbs queue pair. Options may not conflict with\n   * those specified for the fabric. \"Server groups\" are servers in which each\n   * operation is assigned to a \"communication group.\" Each \"completion group\"\n   * may be separately polled for completions.\n   *\n   * @param json_configuration Configuration string in JSON\n   *\n   * @return the endpoint\n   *\n   * @throw std::domain_error : json file parse-detected error\n   * @throw IFabric_runtime_error - ::fi_passive_ep fail\n   * @throw IFabric_runtime_error - ::fi_pep_bind fail\n   * @throw IFabric_runtime_error - ::fi_listen fail\n   */\n  virtual IFabric_server_grouped_factory *open_server_grouped_factory(const common::string_view json_configuration,\n                                                                      std::uint16_t      port) = 0;\n\n  virtual IFabric_endpoint_unconnected_client *make_endpoint(const common::string_view json_configuration, common::string_view remote_endpoint, std::uint16_t port) = 0;\n\n  /*\n   * provider name in the fabric.\n   */\n  virtual const char *prov_name() const noexcept = 0;\n};\n\nclass IFabric_factory : public component::IBase {\n public:\n  DECLARE_INTERFACE_UUID(0xfac3d083, 0xe629, 0x46c9, 0x86fa, 0x6f, 0x96, 0x40, 0x61, 0x10, 0xdf);\n\n  /**\n   * Open a fabric endpoint.  Endpoints usually correspond with hardware\n   * resources, e.g. verbs queue pair Options should include provider,\n   * capabilities, active thread core.\n   *\n   * @param json_configuration Configuration string in JSON\n   * form. e.g. { \"caps\":[\"FI_MSG\",\"FI_RMA\"], \"preferred_provider\" : \"verbs\"}\n   * @return\n   */\n  virtual ~IFabric_factory() {}\n  /**\n   * @throw std::bad_alloc - out of memory\n   * @throw std::domain_error : json file parse-detected error\n   * @throw IFabric_runtime_error - ::fi_control fail\n   */\n  virtual IFabric *make_fabric(const common::string_view json_configuration) = 0;\n};\n\n}  // namespace component\n\n#endif  // __API_FABRIC_ITF__\n", "meta": {"hexsha": "9b00735a33b312e8e5cfd05d6fb7c33c53892d5f", "size": 28441, "ext": "h", "lang": "C", "max_stars_repo_path": "src/components/api/fabric_itf.h", "max_stars_repo_name": "omriarad/mcas", "max_stars_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 60.0, "max_stars_repo_stars_event_min_datetime": "2020-04-28T08:15:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T10:35:15.000Z", "max_issues_repo_path": "src/components/api/fabric_itf.h", "max_issues_repo_name": "omriarad/mcas", "max_issues_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 66.0, "max_issues_repo_issues_event_min_datetime": "2020-09-03T23:40:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T20:34:52.000Z", "max_forks_repo_path": "src/components/api/fabric_itf.h", "max_forks_repo_name": "omriarad/mcas", "max_forks_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2019-11-02T06:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T01:56:42.000Z", "avg_line_length": 34.9827798278, "max_line_length": 168, "alphanum_fraction": 0.658169544, "num_tokens": 6737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07807816514495095, "lm_q2_score": 0.0325897412425357, "lm_q1q2_score": 0.002544547198765921}}
{"text": "/***\n * Copyright 2020 The Katla Authors\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n#ifndef KATLA_SQLITE_DATABASE_H\n#define KATLA_SQLITE_DATABASE_H\n\n#include \"katla/core/core.h\"\n#include \"katla/core/error.h\"\n\n#include \"sqlite3.h\"\n\n#include <memory>\n#include <vector>\n#include <optional>\n#include <gsl/span>\n\nnamespace katla {\n\nstruct SqliteTableData {\n    int nrOfColumns {};\n    std::vector<std::string> columnNames;\n    std::vector<std::string> data;\n};\n\nstruct SqliteQueryResult {\n    std::optional<SqliteTableData> queryResult;\n};\n\nclass SqliteDatabase {\npublic:\n    SqliteDatabase();\n    virtual ~SqliteDatabase();\n\n    outcome::result<void, Error> init();\n\n    outcome::result<void, Error> open();\n    outcome::result<void, Error> close();\n\n    outcome::result<void, Error> create(std::string path);\n\n    outcome::result<SqliteQueryResult, Error> exec(std::string sql);\n\n    outcome::result<SqliteQueryResult, Error> insert(std::string table,  gsl::span<std::pair<std::string, std::string>> values);\n\n    void setPath(std::string path) {\n        m_path = path;\n    }\n\n    bool isOpen () {\n        return m_handle != nullptr;\n    }\n\nprivate:\n    sqlite3* m_handle {};\n    std::string m_path {};\n};\n\n}\n\n#endif\n", "meta": {"hexsha": "f30b8231478fa57b772d13be412d05fa7faac4a1", "size": 1732, "ext": "h", "lang": "C", "max_stars_repo_path": "sqlite/sqlite-database.h", "max_stars_repo_name": "plok/katla", "max_stars_repo_head_hexsha": "aaaeb8baf041bba7259275beefc71c8452a16223", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sqlite/sqlite-database.h", "max_issues_repo_name": "plok/katla", "max_issues_repo_head_hexsha": "aaaeb8baf041bba7259275beefc71c8452a16223", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-03-25T14:33:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-16T14:21:56.000Z", "max_forks_repo_path": "sqlite/sqlite-database.h", "max_forks_repo_name": "plok/katla", "max_forks_repo_head_hexsha": "aaaeb8baf041bba7259275beefc71c8452a16223", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-26T13:32:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-26T13:32:36.000Z", "avg_line_length": 23.7260273973, "max_line_length": 128, "alphanum_fraction": 0.6963048499, "num_tokens": 416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08035746882220708, "lm_q2_score": 0.031618768523357654, "lm_q1q2_score": 0.0025408042058122954}}
{"text": "/**\n *  Copyright (C) 2021 FISCO BCOS.\n *  SPDX-License-Identifier: Apache-2.0\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n * @brief implementation for BlockHeader\n * @file BlockHeaderImpl.h\n * @author: ancelmo\n * @date 2021-04-20\n */\n\n#pragma once\n#include \"bcos-tars-protocol/Common.h\"\n#include \"bcos-tars-protocol/tars/Block.h\"\n#include <bcos-framework/interfaces/crypto/CommonType.h>\n#include <bcos-framework/interfaces/crypto/CryptoSuite.h>\n#include <bcos-framework/interfaces/protocol/BlockHeader.h>\n#include <bcos-framework/interfaces/protocol/ProtocolTypeDef.h>\n#include <gsl/span>\n\nnamespace bcostars\n{\nnamespace protocol\n{\nclass BlockHeaderImpl : public bcos::protocol::BlockHeader\n{\npublic:\n    virtual ~BlockHeaderImpl() {}\n\n    BlockHeaderImpl() = delete;\n\n    BlockHeaderImpl(\n        bcos::crypto::CryptoSuite::Ptr cryptoSuite, std::function<bcostars::BlockHeader*()> inner)\n      : bcos::protocol::BlockHeader(cryptoSuite), m_inner(inner)\n    {}\n\n    void decode(bcos::bytesConstRef _data) override;\n    void encode(bcos::bytes& _encodeData) const override;\n    bcos::crypto::HashType hash() const override;\n\n    void clear() override;\n\n    int32_t version() const override { return m_inner()->data.version; }\n    gsl::span<const bcos::protocol::ParentInfo> parentInfo() const override;\n\n    bcos::crypto::HashType txsRoot() const override;\n    bcos::crypto::HashType stateRoot() const override;\n    bcos::crypto::HashType receiptsRoot() const override;\n    bcos::protocol::BlockNumber number() const override { return m_inner()->data.blockNumber; }\n    bcos::u256 gasUsed() const override;\n    int64_t timestamp() const override { return m_inner()->data.timestamp; }\n    int64_t sealer() const override { return m_inner()->data.sealer; }\n\n    gsl::span<const bcos::bytes> sealerList() const override\n    {\n        return gsl::span(reinterpret_cast<const bcos::bytes*>(m_inner()->data.sealerList.data()),\n            m_inner()->data.sealerList.size());\n    }\n    bcos::bytesConstRef extraData() const override\n    {\n        return bcos::bytesConstRef(\n            reinterpret_cast<const bcos::byte*>(m_inner()->data.extraData.data()),\n            m_inner()->data.extraData.size());\n    }\n    gsl::span<const bcos::protocol::Signature> signatureList() const override\n    {\n        return gsl::span(\n            reinterpret_cast<const bcos::protocol::Signature*>(m_inner()->signatureList.data()),\n            m_inner()->signatureList.size());\n    }\n\n    gsl::span<const uint64_t> consensusWeights() const override\n    {\n        return gsl::span(reinterpret_cast<const uint64_t*>(m_inner()->data.consensusWeights.data()),\n            m_inner()->data.consensusWeights.size());\n    }\n\n    void setVersion(int32_t _version) override { m_inner()->data.version = _version; }\n\n    void setParentInfo(gsl::span<const bcos::protocol::ParentInfo> const& _parentInfo) override;\n\n    void setParentInfo(bcos::protocol::ParentInfoList&& _parentInfo) override\n    {\n        setParentInfo(gsl::span(_parentInfo.data(), _parentInfo.size()));\n    }\n\n    void setTxsRoot(bcos::crypto::HashType _txsRoot) override\n    {\n        m_inner()->data.txsRoot.assign(_txsRoot.begin(), _txsRoot.end());\n    }\n    void setReceiptsRoot(bcos::crypto::HashType _receiptsRoot) override\n    {\n        m_inner()->data.receiptRoot.assign(_receiptsRoot.begin(), _receiptsRoot.end());\n    }\n    void setStateRoot(bcos::crypto::HashType _stateRoot) override\n    {\n        m_inner()->data.stateRoot.assign(_stateRoot.begin(), _stateRoot.end());\n    }\n    void setNumber(bcos::protocol::BlockNumber _blockNumber) override\n    {\n        m_inner()->data.blockNumber = _blockNumber;\n    }\n    void setGasUsed(bcos::u256 _gasUsed) override\n    {\n        m_inner()->data.gasUsed = boost::lexical_cast<std::string>(_gasUsed);\n    }\n    void setTimestamp(int64_t _timestamp) override { m_inner()->data.timestamp = _timestamp; }\n    void setSealer(int64_t _sealerId) override { m_inner()->data.sealer = _sealerId; }\n    void setSealerList(gsl::span<const bcos::bytes> const& _sealerList) override;\n    void setSealerList(std::vector<bcos::bytes>&& _sealerList) override\n    {\n        setSealerList(gsl::span(_sealerList.data(), _sealerList.size()));\n    }\n\n    void setConsensusWeights(gsl::span<const uint64_t> const& _weightList) override\n    {\n        m_inner()->data.consensusWeights.assign(_weightList.begin(), _weightList.end());\n    }\n\n    void setConsensusWeights(std::vector<uint64_t>&& _weightList) override\n    {\n        setConsensusWeights(gsl::span(_weightList.data(), _weightList.size()));\n    }\n\n    void setExtraData(bcos::bytes const& _extraData) override\n    {\n        m_inner()->data.extraData.assign(_extraData.begin(), _extraData.end());\n    }\n    void setExtraData(bcos::bytes&& _extraData) override\n    {\n        m_inner()->data.extraData.assign(_extraData.begin(), _extraData.end());\n    }\n    void setSignatureList(\n        gsl::span<const bcos::protocol::Signature> const& _signatureList) override;\n\n    void setSignatureList(bcos::protocol::SignatureList&& _signatureList) override\n    {\n        setSignatureList(gsl::span(_signatureList.data(), _signatureList.size()));\n    }\n\n    const bcostars::BlockHeader& inner() const { return *m_inner(); }\n\n    void setInner(const bcostars::BlockHeader& blockHeader) { *m_inner() = blockHeader; }\n    void setInner(bcostars::BlockHeader&& blockHeader) { *m_inner() = std::move(blockHeader); }\n\nprivate:\n    std::function<bcostars::BlockHeader*()> m_inner;\n    mutable std::vector<bcos::protocol::ParentInfo> m_parentInfo;\n};\n}  // namespace protocol\n}  // namespace bcostars", "meta": {"hexsha": "45fd2e07fa4190c0b1688dc191883a1d5757a887", "size": 6128, "ext": "h", "lang": "C", "max_stars_repo_path": "bcos-tars-protocol/protocol/BlockHeaderImpl.h", "max_stars_repo_name": "xueying4402/FISCO-BCOS", "max_stars_repo_head_hexsha": "737e08752e8904c7c24e3737f8f46bf5327ef792", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bcos-tars-protocol/protocol/BlockHeaderImpl.h", "max_issues_repo_name": "xueying4402/FISCO-BCOS", "max_issues_repo_head_hexsha": "737e08752e8904c7c24e3737f8f46bf5327ef792", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 20.0, "max_issues_repo_issues_event_min_datetime": "2021-09-14T12:23:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-07T14:19:09.000Z", "max_forks_repo_path": "bcos-tars-protocol/protocol/BlockHeaderImpl.h", "max_forks_repo_name": "xueying4402/FISCO-BCOS", "max_forks_repo_head_hexsha": "737e08752e8904c7c24e3737f8f46bf5327ef792", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-09-08T02:39:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-06T06:35:57.000Z", "avg_line_length": 38.0621118012, "max_line_length": 100, "alphanum_fraction": 0.6953328982, "num_tokens": 1543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12940272151925927, "lm_q2_score": 0.019419346550877865, "lm_q1q2_score": 0.0025129162938092365}}
{"text": "\ufeff\n/** ***************************************************************************\n*\n*  Copyright 2018 Jose Fernando Lopez Fernandez - All Rights Reserved\n*  See the file AUTHORS included with the application distribution for\n*  specific information.\n*\n*  Redistribution and use in source and binary forms, with or without\n*  modification, are permitted provided that the following\n*  conditions are met:\n*\n*   * Redistributions of source code must retain the above copyright\n*     notice, this list of conditions and the following disclaimer.\n*\n*   * Redistributions in binary form must reproduce the above\n*     copyright notice, this list of conditions and the following\n*     disclaimer in the documentation and/or other materials provided\n*     with the distribution.\n*\n*     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND\n*     CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n*     INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n*     MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n*     DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n*     CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n*     SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n*     NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n*     LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n*     HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n*     CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n*     OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,\n*     EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\n*  ***************************************************************************\n*\n*  @author Jose Fernando Lopez Fernandez\n*  @date 15-June-2018\n*  @brief This is the main keygen driver file\n*\n*  Tasks:\n*      1. @todo Add file details\n*      2. @todo Add file details\n*\n*  **************************************************************************/\n\n#ifndef KEYGEN_INCLUDE_KEYGEN_H_\n#define KEYGEN_INCLUDE_KEYGEN_H_\n\n#define TRUE  1\n#define FALSE 0\n\n/** @def _CRT_SECURE_NO_WARNINGS\n*  @brief This preprocessor definition disables Visual Studio's warnings\n*  when not using the safe string functions provided by the MSVC runtime.\n*\n*  Disable the safe string library due to its lack of compatibility with\n*  *nix systems.\n*\n*/\n\n#define _CRT_SECURE_NO_WARNINGS\n\n#ifndef _CRT_SECURE_NO_WARNINGS\n#error \"The safe string library is not compatible with *nix systems\"\n#endif\n\n/** Include Microsoft's Guideline Support Library (GSL). \n*\n*  The Guideline Support Library (GSL) contains functions and types that are\n*  suggested for use by the C++ Core Guidelines maintained by the Standard C++\n*  Foundation. This repo contains Microsoft's implementation of GSL.\n*\n*  The library includes types like span<T>, string_span, owner<> and others.\n*\n*  The entire implementation is provided inline in the headers under the gsl\n*  directory. The implementation generally assumes a platform that implements\n*  C++14 support. There are specific workarounds to support MSVC 2015.\n*\n*  While some types have been broken out into their own headers\n*  (e.g. gsl/span), it is simplest to just include gsl/gsl and gain access to\n*  the entire library.\n*\n*/\n\n#include <gsl/gsl>\n\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <cstddef>\n#include <cstdint>\n#include <cerrno>\n#include <csignal>\n#include <cmath>\n#include <ctime>\n\n/** C++ Standard Library Headers\n*\n*/\n\n#include <algorithm>\n#include <chrono>\n#include <iostream>\n#include <limits>\n#include <ratio>\n#include <sstream>\n#include <string>\n#include <string_view>\n#include <vector>\n#include <utility>\n\n/** @file config.h\n *  @brief This file contains customization settings and project metadata such\n *  as the current release version, compilation settings, etc.\n *  \n */\n\n#include \"config.h\"\n#include \"password.h\"\n\n#endif // KEYGEN_KEYGEN_H_\n\n", "meta": {"hexsha": "0834b773d5dc8665d4f2fd0a0024788d27d4819a", "size": 3903, "ext": "h", "lang": "C", "max_stars_repo_path": "keygen/include/keygen.h", "max_stars_repo_name": "lopezfjose/KeyGen", "max_stars_repo_head_hexsha": "dd6c746a658ba225482411ea058d362445474ea8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-06-21T12:59:41.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-21T12:59:41.000Z", "max_issues_repo_path": "keygen/include/keygen.h", "max_issues_repo_name": "lopezfjose/KeyGen", "max_issues_repo_head_hexsha": "dd6c746a658ba225482411ea058d362445474ea8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2018-06-17T03:19:17.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-19T20:04:20.000Z", "max_forks_repo_path": "keygen/include/keygen.h", "max_forks_repo_name": "lopezfjose/KeyGen", "max_forks_repo_head_hexsha": "dd6c746a658ba225482411ea058d362445474ea8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7317073171, "max_line_length": 79, "alphanum_fraction": 0.6981808865, "num_tokens": 839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.13660839354130014, "lm_q2_score": 0.018264277550292526, "lm_q1q2_score": 0.0024950536153378945}}
{"text": "/**\n* Copyright 2016 BitTorrent Inc.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n*    http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*/\n#pragma once\n\n#include <scraps/config.h>\n\n#if SCRAPS_APPLE\n    #include <scraps/apple/HMAC.h>\n    namespace scraps { using HMACSHA256 = apple::HMAC<apple::HMACAlgorithmType::SHA256>; }\n#else\n    #include <scraps/sodium/HMACSHA256.h>\n    namespace scraps { using HMACSHA256 = sodium::HMACSHA256; }\n#endif\n\n#include <gsl.h>\n\nnamespace scraps {\n\ntemplate <typename BaseByteType>\nstruct HMACSHA256ByteTag {};\n\ntemplate <typename BaseByteType>\nusing HMACSHA256Byte = StrongByte<HMACSHA256ByteTag<BaseByteType>>;\n\ntemplate <typename KeyByteType, std::ptrdiff_t KeySize, typename ByteT, std::ptrdiff_t DataSize>\nstd::array<HMACSHA256Byte<std::remove_const_t<ByteT>>, HMACSHA256::kResultSize>\nGetHMACSHA256(gsl::span<KeyByteType, KeySize> key, gsl::span<ByteT, DataSize> data) {\n    std::array<HMACSHA256Byte<std::remove_const_t<ByteT>>, HMACSHA256::kResultSize> ret;\n\n    HMACSHA256 hmac(key.data(), key.size());\n    hmac.update(data.data(), data.size());\n    hmac.finish(ret.data());\n\n    return ret;\n}\n\n} // namespace scraps\n", "meta": {"hexsha": "58b85bbe8678435e1a5a094b52fb65dafc6336f3", "size": 1605, "ext": "h", "lang": "C", "max_stars_repo_path": "include/scraps/HMACSHA256.h", "max_stars_repo_name": "carlbrown/scraps", "max_stars_repo_head_hexsha": "78925a738540415ec04b9cbe23cb319421f44978", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/scraps/HMACSHA256.h", "max_issues_repo_name": "carlbrown/scraps", "max_issues_repo_head_hexsha": "78925a738540415ec04b9cbe23cb319421f44978", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/scraps/HMACSHA256.h", "max_forks_repo_name": "carlbrown/scraps", "max_forks_repo_head_hexsha": "78925a738540415ec04b9cbe23cb319421f44978", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4705882353, "max_line_length": 96, "alphanum_fraction": 0.7451713396, "num_tokens": 412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15405755492358, "lm_q2_score": 0.016152835591767212, "lm_q1q2_score": 0.0024884663563502353}}
{"text": "/**\n * This file is part of the \"libterminal\" project\n *   Copyright (c) 2019-2020 Christian Parpart <christian@parpart.family>\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n#pragma once\n\n#include <terminal/Color.h>\n#include <terminal/RenderBuffer.h>\n#include <terminal/Screen.h>\n\n#include <terminal_renderer/Atlas.h>\n#include <terminal_renderer/BoxDrawingRenderer.h>\n#include <terminal_renderer/RenderTarget.h>\n\n#include <text_shaper/font.h>\n#include <text_shaper/shaper.h>\n\n#include <crispy/FNV.h>\n#include <crispy/LRUCache.h>\n#include <crispy/point.h>\n#include <crispy/size.h>\n\n#include <unicode/convert.h>\n#include <unicode/run_segmenter.h>\n\n#include <gsl/span>\n#include <gsl/span_ext>\n\n#include <functional>\n#include <list>\n#include <memory>\n#include <unordered_map>\n#include <vector>\n\nnamespace terminal::renderer\n{\n\nenum class TextStyle\n{\n    Invalid = 0x00,\n    Regular = 0x10,\n    Bold = 0x11,\n    Italic = 0x12,\n    BoldItalic = 0x13,\n};\n\nconstexpr TextStyle operator|(TextStyle a, TextStyle b) noexcept\n{\n    return static_cast<TextStyle>(static_cast<unsigned>(a) | static_cast<unsigned>(b));\n}\n\nconstexpr bool operator<(TextStyle a, TextStyle b) noexcept\n{\n    return static_cast<unsigned>(a) < static_cast<unsigned>(b);\n}\n\nstruct TextCacheKey\n{\n    std::u32string_view text;\n    TextStyle style;\n\n    constexpr bool operator<(TextCacheKey const& _rhs) const noexcept\n    {\n        if (text < _rhs.text)\n            return true;\n\n        return text < _rhs.text || style < _rhs.style;\n    }\n\n    constexpr bool operator==(TextCacheKey const& _rhs) const noexcept\n    {\n        return text == _rhs.text && style == _rhs.style;\n    }\n\n    constexpr bool operator!=(TextCacheKey const& _rhs) const noexcept { return !(*this == _rhs); }\n};\n\n} // end namespace terminal::renderer\n\nnamespace std\n{\ntemplate <>\nstruct hash<terminal::renderer::TextCacheKey>\n{\n    size_t operator()(terminal::renderer::TextCacheKey const& _key) const noexcept\n    {\n        auto fnv = crispy::FNV<char32_t> {};\n        return static_cast<size_t>(fnv(fnv.basis(), _key.text, static_cast<char32_t>(_key.style)));\n    }\n};\n} // namespace std\n\nnamespace terminal::renderer\n{\n\nstruct GridMetrics;\n\nenum class TextShapingEngine\n{\n    OpenShaper, //!< Uses open-source implementation: harfbuzz/freetype/fontconfig\n    DWrite,     //!< native platform support: Windows\n    CoreText,   //!< native platform support: OS/X\n};\n\nenum class FontLocatorEngine\n{\n    Mock,       //!< mock font locator API\n    FontConfig, //!< platform independant font locator API\n    DWrite,     //!< native platform support: Windows\n    CoreText,   //!< native font locator on OS/X\n};\n\nstd::unique_ptr<text::font_locator> createFontLocator(FontLocatorEngine _engine);\n\nstruct FontDescriptions\n{\n    double dpiScale = 1.0;\n    crispy::Point dpi = { 0, 0 }; // 0 => auto-fill with defaults\n    text::font_size size;\n    text::font_description regular;\n    text::font_description bold;\n    text::font_description italic;\n    text::font_description boldItalic;\n    text::font_description emoji;\n    text::render_mode renderMode;\n    TextShapingEngine textShapingEngine = TextShapingEngine::OpenShaper;\n    FontLocatorEngine fontLocator = FontLocatorEngine::FontConfig;\n    bool builtinBoxDrawing = true;\n};\n\ninline bool operator==(FontDescriptions const& a, FontDescriptions const& b) noexcept\n{\n    return a.size.pt == b.size.pt && a.regular == b.regular && a.bold == b.bold && a.italic == b.italic\n           && a.boldItalic == b.boldItalic && a.emoji == b.emoji && a.renderMode == b.renderMode;\n}\n\ninline bool operator!=(FontDescriptions const& a, FontDescriptions const& b) noexcept\n{\n    return !(a == b);\n}\n\nstruct FontKeys\n{\n    text::font_key regular;\n    text::font_key bold;\n    text::font_key italic;\n    text::font_key boldItalic;\n    text::font_key emoji;\n};\n\n/// Text Rendering Pipeline\nclass TextRenderer: public Renderable\n{\n  public:\n    TextRenderer(GridMetrics const& _gridMetrics,\n                 text::shaper& _textShaper,\n                 FontDescriptions& _fontDescriptions,\n                 FontKeys const& _fontKeys);\n\n    void setRenderTarget(RenderTarget& _renderTarget) override;\n\n    void debugCache(std::ostream& _textOutput) const;\n    void clearCache() override;\n\n    void updateFontMetrics();\n\n    void setPressure(bool _pressure) noexcept { pressure_ = _pressure; }\n\n    /// Must be invoked before a new terminal frame is rendered.\n    void beginFrame();\n\n    /// Renders a given terminal's grid cell that has been\n    /// transformed into a RenderCell.\n    void renderCell(RenderCell const& _cell);\n\n    /// Must be invoked when rendering the terminal's text has finished for this frame.\n    void endFrame();\n\n  private:\n    /// Puts a sequence of codepoints that belong to the same grid cell at @p _pos\n    /// at the end of the currently filled line.\n    void appendCell(gsl::span<char32_t const> _codepoints, TextStyle _style, RGBColor _color);\n    text::shape_result const& cachedGlyphPositions();\n    text::shape_result requestGlyphPositions();\n    text::shape_result shapeRun(unicode::run_segmenter::range const& _run);\n    void endSequence();\n\n    void renderRun(crispy::Point _startPos,\n                   gsl::span<text::glyph_position const> _glyphPositions,\n                   RGBColor _color);\n\n    /// Renders an arbitrary texture.\n    void renderTexture(crispy::Point const& _pos,\n                       RGBAColor const& _color,\n                       atlas::TextureInfo const& _textureInfo);\n\n    // rendering\n    //\n    struct GlyphMetrics\n    {\n        ImageSize bitmapSize;  // glyph size in pixels\n        crispy::Point bearing; // offset baseline and left to top and left of the glyph's bitmap\n    };\n\n    using TextureAtlas = atlas::MetadataTextureAtlas<text::glyph_key, GlyphMetrics>;\n    using DataRef = TextureAtlas::DataRef;\n\n    std::optional<DataRef> getTextureInfo(text::glyph_key const& _id,\n                                          unicode::PresentationStyle _presentation);\n\n    void renderTexture(crispy::Point const& _pos,\n                       RGBAColor const& _color,\n                       atlas::TextureInfo const& _textureInfo,\n                       GlyphMetrics const& _glyphMetrics,\n                       text::glyph_position const& _gpos);\n\n    TextureAtlas* atlasForBitmapFormat(text::bitmap_format _format) noexcept\n    {\n        switch (_format)\n        {\n        case text::bitmap_format::alpha_mask: return monochromeAtlas_.get();\n        case text::bitmap_format::rgba: return colorAtlas_.get();\n        case text::bitmap_format::rgb: return lcdAtlas_.get();\n        default: return nullptr; // Should NEVER EVER happen.\n        }\n    }\n\n    // general properties\n    //\n    GridMetrics const& gridMetrics_;\n    FontDescriptions& fontDescriptions_;\n    FontKeys const& fonts_;\n\n    // performance optimizations\n    //\n    bool pressure_ = false;\n    std::unordered_map<text::glyph_key, text::bitmap_format> glyphToTextureMapping_;\n    std::list<std::u32string> cacheKeyStorage_;\n    crispy::LRUCache<TextCacheKey, text::shape_result> cache_;\n\n    // target surface rendering\n    //\n    text::shaper& textShaper_;\n    std::unique_ptr<TextureAtlas> monochromeAtlas_;\n    std::unique_ptr<TextureAtlas> colorAtlas_;\n    std::unique_ptr<TextureAtlas> lcdAtlas_;\n\n    // sub-renderer\n    //\n    BoxDrawingRenderer boxDrawingRenderer_;\n\n    // render states\n    TextStyle style_ = TextStyle::Invalid;\n    RGBColor color_ {};\n\n    crispy::Point textPosition_;\n    std::vector<char32_t> codepoints_;\n    std::vector<unsigned> clusters_;\n    unsigned cellCount_ = 0;\n    bool textStartFound_ = false;\n    bool forceCellGroupSplit_ = false;\n\n    // output fields\n    //\n    std::vector<text::shape_result> shapedLines_;\n};\n\n} // namespace terminal::renderer\n\nnamespace fmt\n{ // {{{\ntemplate <>\nstruct formatter<terminal::renderer::FontDescriptions>\n{\n    template <typename ParseContext>\n    constexpr auto parse(ParseContext& ctx)\n    {\n        return ctx.begin();\n    }\n    template <typename FormatContext>\n    auto format(terminal::renderer::FontDescriptions const& fd, FormatContext& ctx)\n    {\n        return format_to(ctx.out(),\n                         \"({}, {}, {}, {}, {}, {})\",\n                         fd.size,\n                         fd.regular,\n                         fd.bold,\n                         fd.italic,\n                         fd.boldItalic,\n                         fd.emoji,\n                         fd.renderMode);\n    }\n};\n\ntemplate <>\nstruct formatter<terminal::renderer::FontLocatorEngine>\n{\n    template <typename ParseContext>\n    constexpr auto parse(ParseContext& ctx)\n    {\n        return ctx.begin();\n    }\n    template <typename FormatContext>\n    auto format(terminal::renderer::FontLocatorEngine value, FormatContext& ctx)\n    {\n        using terminal::renderer::FontLocatorEngine;\n        switch (value)\n        {\n        case FontLocatorEngine::Mock: return format_to(ctx.out(), \"Mock\");\n        case FontLocatorEngine::FontConfig: return format_to(ctx.out(), \"FontConfig\");\n        case FontLocatorEngine::DWrite: return format_to(ctx.out(), \"DirectWrite\");\n        case FontLocatorEngine::CoreText: return format_to(ctx.out(), \"CoreText\");\n        }\n        return format_to(ctx.out(), \"UNKNOWN\");\n    }\n};\n\ntemplate <>\nstruct formatter<terminal::renderer::TextShapingEngine>\n{\n    template <typename ParseContext>\n    constexpr auto parse(ParseContext& ctx)\n    {\n        return ctx.begin();\n    }\n    template <typename FormatContext>\n    auto format(terminal::renderer::TextShapingEngine value, FormatContext& ctx)\n    {\n        using terminal::renderer::TextShapingEngine;\n        switch (value)\n        {\n        case TextShapingEngine::OpenShaper: return format_to(ctx.out(), \"OpenShaper\");\n        case TextShapingEngine::DWrite: return format_to(ctx.out(), \"DirectWrite\");\n        case TextShapingEngine::CoreText: return format_to(ctx.out(), \"CoreText\");\n        }\n        return format_to(ctx.out(), \"UNKNOWN\");\n    }\n};\n\ntemplate <>\nstruct formatter<terminal::renderer::TextCacheKey>\n{\n    template <typename ParseContext>\n    constexpr auto parse(ParseContext& ctx)\n    {\n        return ctx.begin();\n    }\n    template <typename FormatContext>\n    auto format(terminal::renderer::TextCacheKey value, FormatContext& ctx)\n    {\n        return format_to(ctx.out(), \"({}, \\\"{}\\\")\", value.style, unicode::convert_to<char>(value.text));\n    }\n};\n\n} // namespace fmt\n", "meta": {"hexsha": "f4ceb71b7934cabc782aa1a4374c882f13ad2a81", "size": 10868, "ext": "h", "lang": "C", "max_stars_repo_path": "src/terminal_renderer/TextRenderer.h", "max_stars_repo_name": "contour-terminal/contour", "max_stars_repo_head_hexsha": "21c4dab7f97b41017fb7f57d742defe765157413", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 404.0, "max_stars_repo_stars_event_min_datetime": "2021-07-01T11:38:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T19:16:18.000Z", "max_issues_repo_path": "src/terminal_renderer/TextRenderer.h", "max_issues_repo_name": "dankamongmen/contour", "max_issues_repo_head_hexsha": "21c4dab7f97b41017fb7f57d742defe765157413", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 204.0, "max_issues_repo_issues_event_min_datetime": "2021-07-01T10:10:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T09:46:05.000Z", "max_forks_repo_path": "src/terminal_renderer/TextRenderer.h", "max_forks_repo_name": "dankamongmen/contour", "max_forks_repo_head_hexsha": "21c4dab7f97b41017fb7f57d742defe765157413", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2021-07-02T15:40:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T16:24:42.000Z", "avg_line_length": 29.7753424658, "max_line_length": 104, "alphanum_fraction": 0.6657158631, "num_tokens": 2480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08882029240011771, "lm_q2_score": 0.028007517766397722, "lm_q1q2_score": 0.0024876359174129375}}
{"text": "/****************************************************************************\n *                                                                          *\n *  Author : lukasz.iwaszkiewicz@gmail.com                                  *\n *  ~~~~~~~~                                                                *\n *  License : see COPYING file for details.                                 *\n *  ~~~~~~~~~                                                               *\n ****************************************************************************/\n\n#pragma once\n#include <etl/cstring.h>\n// #include <fmt/core.h>\n// #include <fmt/format.h>\n#include <gsl/gsl>\n\nnamespace logging {\n\n/// Line size including tick number and task name.\nstatic constexpr size_t MAX_LINE_SIZE = 256;\n\n/// Have to be initialized.\nvoid init ();\n\n/**\n * Add a log. Do not call from an ISR.\n */\nbool log (gsl::czstring<> str);\n\n// template <typename Format, typename... Args> bool log2 (Format &&format, Args &&... args)\n// {\n//         etl::string<MAX_LINE_SIZE> buf;\n//         fmt::format_to (std::back_inserter (buf), std::forward<Format> (format), std::forward<Args> (args)...);\n//         log (buf.c_str ());\n//         return true;\n// }\n\n} // namespace logging", "meta": {"hexsha": "37cf819a860c068b2bf071dfc23e8fb08e86ca9c", "size": 1238, "ext": "h", "lang": "C", "max_stars_repo_path": "src/logging.h", "max_stars_repo_name": "iwasz/freertos-test", "max_stars_repo_head_hexsha": "e57f2d119668b588059a8c89f796340dfa06baf6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/logging.h", "max_issues_repo_name": "iwasz/freertos-test", "max_issues_repo_head_hexsha": "e57f2d119668b588059a8c89f796340dfa06baf6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/logging.h", "max_forks_repo_name": "iwasz/freertos-test", "max_forks_repo_head_hexsha": "e57f2d119668b588059a8c89f796340dfa06baf6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-25T11:16:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-25T11:16:21.000Z", "avg_line_length": 34.3888888889, "max_line_length": 114, "alphanum_fraction": 0.3998384491, "num_tokens": 230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09138210801622942, "lm_q2_score": 0.027169230058730266, "lm_q1q2_score": 0.0024827815159446766}}
{"text": "#include <float.h>\n#include <inttypes.h>\n#include <limits.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <string.h>\n#include <time.h>\n#include <unistd.h>\n#include <valgrind/callgrind.h>\n#include <gsl/gsl_histogram.h>\n#include <gsl/gsl_sort.h>\n#include <gsl/gsl_statistics.h>\n\n#include \"betree.h\"\n#include \"debug.h\"\n#include \"hashmap.h\"\n#include \"helper.h\"\n#include \"printer.h\"\n#include \"tree.h\"\n#include \"utils.h\"\n\n#define MAX_EXPRS 10000\n#define MAX_EVENTS 5000\n#define DEFAULT_SEARCH_COUNT 10\n\n// wc -L filename\n#define MAX_EVENT_CHARACTERS 20000\n#define MAX_EXPR_CHARACTERS 17000\n#define MAX_CONSTANT_CHARACTERS 20\n\nconst char* EXPRS_FILE = \"data/betree_exprs\";\nconst char* CONSTANTS_FILE = \"data/betree_constants\";\nconst char* EVENTS_FILE = \"data/betree_events\";\n\nstruct betree_events {\n    size_t count;\n    char** events;\n};\n\nvoid add_event(char* event, struct betree_events* events)\n{\n    if(events->count == 0) {\n        events->events = calloc(1, sizeof(*events->events));\n        if(events == NULL) {\n            fprintf(stderr, \"%s calloc failed\", __func__);\n            abort();\n        }\n    }\n    else {\n        char** new_events\n            = realloc(events->events, sizeof(*new_events) * ((events->count) + 1));\n        if(new_events == NULL) {\n            fprintf(stderr, \"%s realloc failed\", __func__);\n            abort();\n        }\n        events->events = new_events;\n    }\n    events->events[events->count] = strdup(event);\n    events->count++;\n}\n\nchar* strip_chars(const char* string, const char* chars)\n{\n    char* new_string = malloc(strlen(string) + 1);\n    int counter = 0;\n\n    for(; *string; string++) {\n        if(!strchr(chars, *string)) {\n            new_string[counter] = *string;\n            ++counter;\n        }\n    }\n    new_string[counter] = 0;\n    return new_string;\n}\n\nint event_parse(const char* text, struct betree_event** event);\n\nsize_t read_betree_events(struct betree_events* events)\n{\n    FILE* f = fopen(EVENTS_FILE, \"r\");\n    size_t count = 0;\n\n    char line[MAX_EVENT_CHARACTERS]; // Arbitrary from what I've seen\n    while(fgets(line, sizeof(line), f)) {\n        if(MAX_EVENTS != 0 && events->count == MAX_EVENTS) {\n            break;\n        }\n\n        add_event(line, events);\n        count++;\n    }\n    fclose(f);\n    return count;\n}\n\nsize_t read_betree_exprs(struct betree* tree)\n{\n\n    FILE* f = fopen(EXPRS_FILE, \"r\");\n    FILE* constants_f = fopen(CONSTANTS_FILE, \"r\");\n\n    //char* lines[MAX_EXPRS];\n    char line[MAX_EXPR_CHARACTERS]; // Arbitrary from what I've seen\n    char constants_line[MAX_CONSTANT_CHARACTERS];\n    size_t count = 0;\n    const struct betree_sub* subs[MAX_EXPRS];\n\n    enum e { constant_count = 3 };\n    while(fgets(line, sizeof(line), f)) {\n        char* ignore = fgets(constants_line, sizeof(constants_line), constants_f);\n        (void)ignore;\n        char* copy = strdup(constants_line);\n        char* rest = copy;\n        int64_t campaign_id = strtoll(strtok_r(rest, \",\", &rest), NULL, 10);\n        int64_t advertiser_id = strtoll(strtok_r(rest, \",\", &rest), NULL, 10);\n        int64_t flight_id = strtoll(strtok_r(rest, \"\\n\", &rest), NULL, 10);\n        const struct betree_constant* constants[constant_count] = {\n            betree_make_integer_constant(\"campaign_id\", campaign_id),\n            betree_make_integer_constant(\"advertiser_id\", advertiser_id),\n            betree_make_integer_constant(\"flight_id\", flight_id),\n        };\n\n        const struct betree_sub* sub = betree_make_sub(tree, count, constant_count, constants, line);\n        subs[count] = sub;\n        count++;\n        betree_free_constants(constant_count, (struct betree_constant**) constants);\n        free(copy);\n        if(MAX_EXPRS != 0 && count == MAX_EXPRS) {\n            break;\n        }\n    }\n    /*for(size_t i = 0; i < tree->config->attr_domain_count; i++) {*/\n        /*const struct attr_domain* attr_domain = tree->config->attr_domains[i];*/\n        /*print_attr_domain(attr_domain);*/\n    /*}*/\n    fclose(f);\n    fclose(constants_f);\n\n    for(size_t i = 0; i < count; i++) {\n        const struct betree_sub* sub = subs[i];\n        if(!betree_insert_sub(tree, sub)) {\n            printf(\"Can't insert expr %zu\\n\", i);\n            abort();\n        }\n    }\n\n    return count;\n}\n\nvoid read_betree_defs(struct betree* tree)\n{\n    FILE* f = fopen(\"data/betree_defs\", \"r\");\n\n    char line[LINE_MAX];\n    while(fgets(line, sizeof(line), f)) {\n        add_variable_from_string(tree, line);\n    }\n\n    fclose(f);\n}\n\nint compare_int( const void* a, const void* b )\n{\n    if( *(int*)a == *(int*)b ) return 0;\n    return *(int*)a < *(int*)b ? -1 : 1;\n}\n\nint main(int argc, char** argv)\n{\n    size_t search_count = DEFAULT_SEARCH_COUNT;\n    if(argc > 1) {\n        search_count = atoi(argv[1]);\n    }\n    if(access(\"data/betree_defs\", F_OK) == -1 || access(\"data/betree_events\", F_OK) == -1\n        || access(\"data/betree_exprs\", F_OK) == -1 || access(\"data/betree_constants\", F_OK) == -1) {\n        fprintf(stderr, \"Missing files, skipping the tests\");\n        return 0;\n    }\n    struct timespec start, insert_done, gen_event_done, search_done;\n\n    // Init\n    struct betree* tree = betree_make();\n    read_betree_defs(tree);\n\n    clock_gettime(CLOCK_MONOTONIC_RAW, &start);\n\n    // Insert\n    size_t expr_count = read_betree_exprs(tree);\n\n    clock_gettime(CLOCK_MONOTONIC_RAW, &insert_done);\n    uint64_t insert_us = (insert_done.tv_sec - start.tv_sec) * 1000000\n        + (insert_done.tv_nsec - start.tv_nsec) / 1000;\n    printf(\"    Insert took %\" PRIu64 \"\\n\", insert_us);\n\n    struct betree_events events = { .count = 0, .events = NULL };\n    size_t event_count = read_betree_events(&events);\n\n    uint64_t evaluated_sum = 0;\n    uint64_t matched_sum = 0;\n    uint64_t memoized_sum = 0;\n    uint64_t shorted_sum = 0;\n\n    const size_t search_us_count = search_count * events.count;\n    double search_us_data[search_us_count];\n\n    CALLGRIND_START_INSTRUMENTATION;\n\n    size_t search_us_i = 0;\n    \n    for(size_t j = 0; j < search_count; j++) {\n        for(size_t i = 0; i < events.count; i++) {\n            clock_gettime(CLOCK_MONOTONIC_RAW, &gen_event_done);\n\n            char* event = events.events[i];\n            struct report* report = make_report();\n            if(betree_search(tree, event, report) == false) {\n                fprintf(stderr, \"Failed to search with event\\n\");\n                abort();\n            }\n\n            clock_gettime(CLOCK_MONOTONIC_RAW, &search_done);\n\n            uint64_t search_us = (search_done.tv_sec - gen_event_done.tv_sec) * 1000000\n                + (search_done.tv_nsec - gen_event_done.tv_nsec) / 1000;\n\n            search_us_data[search_us_i] = (double)search_us;\n\n            evaluated_sum += report->evaluated;\n            matched_sum += report->matched;\n            memoized_sum += report->memoized;\n            shorted_sum += report->shorted;\n            free_report(report);\n            search_us_i++;\n        }\n        printf(\"Finished run %zu/%zu\\n\", j, search_count);\n    }\n\n    CALLGRIND_STOP_INSTRUMENTATION;\n    CALLGRIND_DUMP_STATS;\n\n    for(size_t i = 0; i < events.count; i++) {\n        free(events.events[i]);\n    }\n\n    double evaluated_average = (double)evaluated_sum / (double)MAX_EVENTS;\n    double matched_average = (double)matched_sum / (double)MAX_EVENTS;\n    double memoized_average = (double)memoized_sum / (double)MAX_EVENTS;\n    double shorted_average = (double)shorted_sum / (double)MAX_EVENTS;\n    printf(\"%zu searches, %zu expressions, %zu events, %zu preds, %zu memoize preds. Evaluated %.2f, matched %.2f, memoized %.2f, shorted %.2f\\n\",\n        search_us_count,\n        expr_count,\n        event_count,\n        tree->config->pred_map->pred_count,\n        tree->config->pred_map->memoize_count,\n        evaluated_average / search_count,\n        matched_average / search_count,\n        memoized_average / search_count,\n        shorted_average / search_count);\n\n    double search_us_min = gsl_stats_min(search_us_data, 1, search_us_count);\n    double search_us_max = gsl_stats_max(search_us_data, 1, search_us_count);\n    double search_us_mean = gsl_stats_mean(search_us_data, 1, search_us_count);\n    gsl_sort(search_us_data, 1, search_us_count);\n    double search_us_90 = gsl_stats_quantile_from_sorted_data(search_us_data, 1, search_us_count, 0.90);\n    double search_us_95 = gsl_stats_quantile_from_sorted_data(search_us_data, 1, search_us_count, 0.95);\n    double search_us_99 = gsl_stats_quantile_from_sorted_data(search_us_data, 1, search_us_count, 0.99);\n\n    printf(\"Min: %.1f, Mean: %.1f, Max: %.1f, 90: %.1f, 95: %.1f, 99: %.1f\\n\", search_us_min, search_us_mean, search_us_max, search_us_90, search_us_95, search_us_99);\n\n    printf(\"| %lu | %.1f | %.1f | %.1f | %.1f | %.1f | %.1f | |\\n\", insert_us, search_us_min, search_us_mean, search_us_max, search_us_90, search_us_95, search_us_99);\n\n    // DEBUG\n    write_dot_file(tree);\n    // DEBUG\n    \n    free(events.events);\n    betree_free(tree);\n    return 0;\n}\n\n", "meta": {"hexsha": "de69b1900a8decfc8ddd89c450633ef5fe8ae829", "size": 8969, "ext": "c", "lang": "C", "max_stars_repo_path": "tests/real_tests.c", "max_stars_repo_name": "jonahharris/be-tree", "max_stars_repo_head_hexsha": "51d7474cce329b6ea392ac873100e3963c23b471", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2018-03-28T13:42:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T03:55:44.000Z", "max_issues_repo_path": "tests/real_tests.c", "max_issues_repo_name": "jonahharris/be-tree", "max_issues_repo_head_hexsha": "51d7474cce329b6ea392ac873100e3963c23b471", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2018-04-05T22:00:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-03T01:49:39.000Z", "max_forks_repo_path": "tests/real_tests.c", "max_forks_repo_name": "jonahharris/be-tree", "max_forks_repo_head_hexsha": "51d7474cce329b6ea392ac873100e3963c23b471", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2018-04-06T14:57:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-02T14:17:50.000Z", "avg_line_length": 31.804964539, "max_line_length": 167, "alphanum_fraction": 0.6361913257, "num_tokens": 2377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.17106118745263715, "lm_q2_score": 0.014503578040743186, "lm_q1q2_score": 0.002480999281961522}}
{"text": "#pragma once\n\n#include <memory>\n#include <gsl/gsl>\n\n/// Holds code related to computer memory.\nnamespace MEMORY\n{\n    /// A type alias to improve readability for non-null raw pointers.\n    /// @tparam Type - The type of the underyling item being pointed to.\n    template <typename Type>\n    using NonNullRawPointer = gsl::strict_not_null<Type*>;\n\n    /// A type alias to improve readability for non-null unique pointers.\n    /// @tparam Type - The type of the underlying item in the pointer.\n    template <typename Type>\n    using NonNullUniquePointer = gsl::strict_not_null<std::unique_ptr<Type>>;\n\n    /// A type alias to improve readability for non-null shared pointers.\n    /// @tparam Type - The type of the underlying item in the pointer.\n    template <typename Type>\n    using NonNullSharedPointer = gsl::strict_not_null<std::shared_ptr<Type>>;\n}\n", "meta": {"hexsha": "b511177ac9adfa42d42fecd10e053b1564c424ad", "size": 854, "ext": "h", "lang": "C", "max_stars_repo_path": "Memory/Pointers.h", "max_stars_repo_name": "jpike/CppLibraries", "max_stars_repo_head_hexsha": "7db1595ef7b17a0485b8a07abeb20d8f9cd0ea63", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Memory/Pointers.h", "max_issues_repo_name": "jpike/CppLibraries", "max_issues_repo_head_hexsha": "7db1595ef7b17a0485b8a07abeb20d8f9cd0ea63", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 61.0, "max_issues_repo_issues_event_min_datetime": "2015-04-11T21:26:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-02T13:34:43.000Z", "max_forks_repo_path": "Memory/Pointers.h", "max_forks_repo_name": "jpike/CppLibraries", "max_forks_repo_head_hexsha": "7db1595ef7b17a0485b8a07abeb20d8f9cd0ea63", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5833333333, "max_line_length": 77, "alphanum_fraction": 0.7166276347, "num_tokens": 188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07159119350203819, "lm_q2_score": 0.034618835602160426, "lm_q1q2_score": 0.002478403758409516}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef dvt_31727ef2_2dfa_4e64_b93d_deab9c280036_h\r\n#define dvt_31727ef2_2dfa_4e64_b93d_deab9c280036_h\r\n\r\n#include <gslib/config.h>\r\n#include <gslib/type.h>\r\n#include <gslib/std.h>\r\n\r\n__gslib_begin__\r\n\r\ntemplate<class _targetfn>\r\ninline uint method_address(_targetfn fn)\r\n{\r\n    uint r;\r\n    memcpy(&r, &fn, sizeof(r));\r\n    return r;\r\n}\r\n\r\nextern uint dsm_get_address(uint addr, uint pthis);\r\nextern void dvt_recover_vtable(void* pthis, void* ovt, int vtsize);\r\n\r\nclass dvt_bridge_code;\r\n\r\ntemplate<class _cls>\r\nclass vtable_ops:\r\n    public _cls\r\n{\r\npublic:\r\n    typedef vtable_ops<_cls> myref;\r\n\r\npublic:\r\n    myref() {}\r\n    template<class _arg1>\r\n    myref(_arg1 a1): _cls(a1) {}\r\n    template<class _arg1, class _arg2>\r\n    myref(_arg1 a1, _arg2 a2): _cls(a1, a2) {}\r\n    template<class _arg1, class _arg2, class _arg3>\r\n    myref(_arg1 a1, _arg2 a2, _arg3 a3): _cls(a1, a2, a3) {}\r\n    virtual void end_of_vtable() { __asm { nop } }      /* add some real stuff in this function to prevent optimization in release. */\r\n\r\npublic:\r\n    int get_virtual_method_index(uint m) const\r\n    {\r\n        uint mv = dsm_final_address(m);\r\n        uint eov = dsm_final_address(method_address(&myref::end_of_vtable));\r\n        uint* ovt = *(uint**)this;\r\n        int i = 0;\r\n        for(;; ++ i) {\r\n            uint cv = dsm_final_address(ovt[i]);\r\n            if(cv == mv)\r\n                return i;\r\n            if(cv == eov) {\r\n                assert(!\"get index failed.\");\r\n                return i;\r\n            }\r\n        }\r\n        return -1;\r\n    }\r\n    int size_of_vtable() const\r\n    {\r\n        return get_virtual_method_index(\r\n            dsm_final_address(method_address(&myref::end_of_vtable))\r\n            );\r\n    }\r\n    void* create_per_instance_vtable(_cls* p, dvt_bridge_code& bridges)\r\n    {\r\n        assert(p);\r\n        int count = size_of_vtable();\r\n        byte* ovt = *(byte**)p;\r\n        void** pvt = (void**)VirtualAlloc(nullptr, count * 4, MEM_COMMIT, PAGE_EXECUTE_READWRITE);\r\n        assert(pvt);\r\n        bridges.install(ovt, count);\r\n        for(int i = 0; i < count; i ++)\r\n            pvt[i] = bridges.get_bridge(i);\r\n        memcpy(p, &pvt, 4);\r\n        DWORD oldpro;\r\n        VirtualProtect(pvt, count * 4, PAGE_EXECUTE_READ, &oldpro);\r\n        return ovt;\r\n    }\r\n    void destroy_per_instance_vtable(_cls* p, void* ovt)\r\n    {\r\n        assert(p && ovt);\r\n        dvt_recover_vtable(p, ovt, size_of_vtable());\r\n    }\r\n    template<class _func>\r\n    uint replace_vtable_method(_cls* p, int index, _func func)\r\n    {\r\n        uint* vt = *(uint**)p;\r\n        vt += index;\r\n        uint r = *vt;\r\n        DWORD oldpro;\r\n        VirtualProtect(vt, 4, PAGE_EXECUTE_READWRITE, &oldpro);\r\n        *vt = (uint)func;\r\n        VirtualProtect(vt, 4, oldpro, &oldpro);\r\n        return r;\r\n    }\r\n\r\nprivate:\r\n    uint dsm_final_address(uint addr) const\r\n    {\r\n        return dsm_get_address(\r\n            addr, (uint)((void*)this)\r\n        );\r\n    }\r\n};\r\n\r\nclass dvt_detour_code\r\n{\r\n    typedef unsigned long ulong;\r\n\r\npublic:\r\n    enum detour_type\r\n    {\r\n        detour_notify,\r\n        detour_reflect,\r\n    };\r\n\r\npublic:\r\n    dvt_detour_code(detour_type dty, int argsize);\r\n    ~dvt_detour_code();\r\n    void finalize(uint old_func, uint host, uint action);\r\n    uint get_code_address() const { return (uint)_ptr; }\r\n\r\nprivate:\r\n    detour_type     _type;\r\n    int             _argsize;\r\n    byte*           _ptr;\r\n    int             _len;\r\n    ulong           _oldpro;\r\n};\r\n\r\n/*\r\n * The two kind of DVT callings:\r\n * 1.notify:    the original function would be called first, and then the notify function will be called after, you MUST specify the size of the argument table.\r\n * 2.reflect:   the original function would NOT be called, simply jump to the reflect function, and the argument table of the reflect function SHOULD be exactly the same with the original function.\r\n */\r\n#define connect_typed_detour(targettype, target, trigger, host, action, dty, argsize) { \\\r\n    auto& vo = vtable_ops<targettype>(nullptr); \\\r\n    (target)->ensure_dvt_available<targettype>(); \\\r\n    auto* detour = (target)->add_detour(dty, argsize); \\\r\n    assert(detour); \\\r\n    uint old_func = vo.replace_vtable_method(target, vo.get_virtual_method_index(method_address(trigger)), detour->get_code_address()); \\\r\n    detour->finalize(old_func, (uint)host, method_address(action)); \\\r\n}\r\n\r\n#define connect_typed_notify(targettype, target, trigger, host, action, argsize) \\\r\n    connect_typed_detour(targettype, target, trigger, host, action, dvt_detour_code::detour_notify, argsize)\r\n\r\n#define connect_notify(target, trigger, host, action, argsize) \\\r\n    connect_typed_notify(std::remove_reference_t<decltype(*target)>, target, trigger, host, action, argsize)\r\n\r\n#define connect_typed_reflect(targettype, target, trigger, host, action) \\\r\n    connect_typed_detour(targettype, target, trigger, host, action, dvt_detour_code::detour_reflect, 0)\r\n\r\n#define connect_reflect(target, trigger, host, action) \\\r\n    connect_typed_reflect(std::remove_reference_t<decltype(*target)>, target, trigger, host, action)\r\n\r\n/*\r\n * Bridge to jump to the original vtable\r\n * The reason why we can't simply copy the original vtable was that it's hard to determine how long the vtable actually was.\r\n * If the target class had a complex derivations, missing a part of the vtable would make you unable to call __super::function.\r\n */\r\nclass dvt_bridge_code\r\n{\r\npublic:\r\n    dvt_bridge_code();\r\n    ~dvt_bridge_code();\r\n    void install(void* vt, int count);\r\n    void* get_bridge(int index) const;\r\n\r\nprotected:\r\n    byte*           _bridges;\r\n    int             _bridge_size;       /* in bytes */\r\n    int             _jt_stride;         /* jump table stride in bytes */\r\n};\r\n\r\nclass dvt_holder\r\n{\r\npublic:\r\n    typedef vector<dvt_detour_code*> detour_list;\r\n\r\npublic:\r\n    dvt_holder();\r\n    virtual ~dvt_holder();\r\n\r\nprivate:\r\n    void*           _backvt;\r\n    int             _backvtsize;\r\n    void*           _switchvt;\r\n    detour_list     _detours;\r\n    bool            _delete_later;\r\n    dvt_bridge_code _bridges;\r\n\r\npublic:\r\n    template<class _cls>\r\n    void ensure_dvt_available()\r\n    {\r\n        if(_backvt)\r\n            return;\r\n        auto& vo = vtable_ops<_cls>(nullptr);\r\n        _backvtsize = vo.size_of_vtable();\r\n        _backvt = vo.create_per_instance_vtable(static_cast<_cls*>(this), _bridges);\r\n    }\r\n    dvt_detour_code* add_detour(dvt_detour_code::detour_type dty, int argsize);\r\n    dvt_holder* switch_to_ovt();        /* switch to original vtable */\r\n    dvt_holder* switch_to_dvt();\r\n    /*\r\n     * In case the holder would be tagged more than once by the garbage collector, the cause might be\r\n     * a message re-entrant of the msg callback function. So here we tag it.\r\n     */\r\n    void set_delete_later() { _delete_later = true; }\r\n    bool is_delete_later() const { return _delete_later; }\r\n};\r\n\r\nclass dvt_collector\r\n{\r\npublic:\r\n    typedef vector<dvt_holder*> holder_list;\r\n\r\nprivate:\r\n    holder_list     _holders;\r\n    dvt_collector() {}\r\n\r\npublic:\r\n    static dvt_collector* get_singleton_ptr()\r\n    {\r\n        static dvt_collector inst;\r\n        return &inst;\r\n    }\r\n    ~dvt_collector() { cleanup(); }\r\n    bool set_delete_later(dvt_holder* holder);\r\n    void cleanup();\r\n};\r\n\r\n__gslib_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "a12943dacf778938ce4772f948530f78eba58db5", "size": 8591, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gslib/dvt.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/gslib/dvt.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gslib/dvt.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 32.5416666667, "max_line_length": 198, "alphanum_fraction": 0.6432312886, "num_tokens": 2163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07696083781311953, "lm_q2_score": 0.03210070405485706, "lm_q1q2_score": 0.0024704970784528027}}
{"text": "// SPDX-License-Identifier: MIT\n// The MIT License (MIT)\n//\n// Copyright (c) 2014-2018, Institute for Software & Systems Engineering\n// Copyright (c) 2018-2019, Johannes Leupolz\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n#ifndef PEMC_BASIC_RAW_MEMORY_H_\n#define PEMC_BASIC_RAW_MEMORY_H_\n\n#include <gsl/gsl_byte>\n#include <memory>\n\nnamespace pemc {\n\nusing deleter_t = std::function<void(void*)>;\n\nusing unique_void_ptr = std::unique_ptr<void, deleter_t>;\n\n// The following method can be used to reserve some bulk memory.\n// The unique_void_ptr keeps track of the memory to avoid leaks.\n// unique_ptr are not used, because they do not support void.\n// Example of usage:\n// > unique_void_ptr stateMemory = unique_void(::operator new(amount of memory )\n// ); > gsl::byte* p_stateMemory = static_cast<gsl::byte*>(stateMemory.get());\nunique_void_ptr unique_void(void* ptr);\n\n/// <summary>\n///   Compares the two buffers <paramref name=\"buffer1\" /> and <paramref\n///   name=\"buffer2\" />, returning <c>true</c> when the buffers are equivalent.\n/// </summary>\n/// <param name=\"buffer1\">The first buffer of memory to compare.</param>\n/// <param name=\"buffer2\">The second buffer of memory to compare.</param>\n/// <param name=\"sizeInBytes\">The size of the buffers in bytes.</param>\nbool areBuffersEqual(gsl::byte* buffer1,\n                     gsl::byte* buffer2,\n                     size_t sizeInBytes);\n\n/// <summary>\n///   Copies <paramref name=\"sizeInBytes\" />-many bytes from <paramref\n///   name=\"source\" /> to <see cref=\"destination\" />.\n/// </summary>\n/// <param name=\"source\">The first buffer of memory to compare.</param>\n/// <param name=\"destination\">The second buffer of memory to compare.</param>\n/// <param name=\"sizeInBytes\">The size of the buffers in bytes.</param>\nvoid copyBuffers(gsl::byte* source, gsl::byte* destination, size_t sizeInBytes);\n\n/// <summary>\n///   Hashes the <paramref name=\"buffer\" />.\n/// </summary>\n/// <param name=\"buffer\">The buffer of memory that should be hashed.</param>\n/// <param name=\"sizeInBytes\">The size of the buffer in bytes.</param>\n/// <param name=\"seed\">The seed value for the hash.</param>\n/// <remarks>See also https://en.wikipedia.org/wiki/MurmurHash (MurmurHash3\n/// implementation)</remarks>\nuint32_t hashBuffer(gsl::byte* buffer, size_t sizeInBytes, int32_t seed);\n\n}  // namespace pemc\n\n#endif  // PEMC_BASIC_RAW_MEMORY_H_\n", "meta": {"hexsha": "99d58be28d01f5565a510211c1b28ab745b66650", "size": 3407, "ext": "h", "lang": "C", "max_stars_repo_path": "pemc/basic/raw_memory.h", "max_stars_repo_name": "joleuger/pemc", "max_stars_repo_head_hexsha": "14deb5b97d4219ba3c92d3834ab71332997e9b13", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pemc/basic/raw_memory.h", "max_issues_repo_name": "joleuger/pemc", "max_issues_repo_head_hexsha": "14deb5b97d4219ba3c92d3834ab71332997e9b13", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pemc/basic/raw_memory.h", "max_forks_repo_name": "joleuger/pemc", "max_forks_repo_head_hexsha": "14deb5b97d4219ba3c92d3834ab71332997e9b13", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.6794871795, "max_line_length": 80, "alphanum_fraction": 0.7240974464, "num_tokens": 815, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.0769608272276531, "lm_q2_score": 0.03210070359187427, "lm_q1q2_score": 0.0024704967030203394}}
{"text": "#ifndef _GENMAP_QUALITY_H_\n#define _GENMAP_QUALITY_H_\n\n#include <gslib.h>\n\nvoid printPartStat(long long *vtx, int nel, int nv, comm_ext ce);\n\n#endif\n", "meta": {"hexsha": "dc127097a66eecd178a51bd5777a7f7df1c46151", "size": 149, "ext": "h", "lang": "C", "max_stars_repo_path": "3rd_party/nek5000_parRSB/src/genmap-quality.h", "max_stars_repo_name": "RonRahaman/nekRS", "max_stars_repo_head_hexsha": "ffc02bca33ece6ba3330c4ee24565b1c6b5f7242", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-09-07T03:00:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-06T18:08:27.000Z", "max_issues_repo_path": "3rd_party/nek5000_parRSB/src/genmap-quality.h", "max_issues_repo_name": "neams-th-coe/nekRS", "max_issues_repo_head_hexsha": "5d2c8ab3d14b3fb16db35682336a1f96000698bb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-06-27T02:07:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-24T04:47:42.000Z", "max_forks_repo_path": "3rd_party/nek5000_parRSB/src/genmap-quality.h", "max_forks_repo_name": "neams-th-coe/nekRS", "max_forks_repo_head_hexsha": "5d2c8ab3d14b3fb16db35682336a1f96000698bb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-10T20:12:48.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-10T20:12:48.000Z", "avg_line_length": 16.5555555556, "max_line_length": 65, "alphanum_fraction": 0.7718120805, "num_tokens": 44, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.08882029240011771, "lm_q2_score": 0.027585283326002772, "lm_q1q2_score": 0.002450132930955658}}
{"text": "#pragma once\n#include \"utility/types.h\"\n#include \"utility/c++std/optional.h\"\n#include \"utility/c++std/string_view.h\"\n#include <fmt/format.h>\n#include <gsl/gsl>\n\nnamespace cws80 {\n\nclass NkScreen;\nclass NativeUI;\nstruct Bank;\nstruct Program;\n\n///\nclass UIController {\npublic:\n    virtual ~UIController() {}\n\n    virtual NkScreen &screen() const = 0;\n    virtual NativeUI &native_ui() const = 0;\n    virtual const Program &program() const = 0;\n    virtual uint bank_number() const = 0;\n    virtual uint program_number() const = 0;\n    virtual gsl::span<const std::string> program_names() const = 0;\n    virtual i32 get_parameter(uint idx) const = 0;\n    virtual bool set_parameter(uint idx, i32 val) = 0;\n    virtual f32 get_f32_parameter(uint idx) const = 0;\n    virtual bool set_f32_parameter(uint idx, f32 val) = 0;\n    virtual void currently_editing_parameter(cxx::optional<uint> idx) = 0;\n    virtual void request_next_bank() = 0;\n    virtual void request_bank(uint num) = 0;\n    virtual void request_program(uint num) = 0;\n    virtual void request_rename_program(cxx::string_view name) = 0;\n    virtual void request_init_program() = 0;\n    virtual void request_write_program() = 0;\n    virtual void dlg_rename_program() = 0;\n    virtual void dlg_load_bank() = 0;\n    virtual void dlg_save_bank() = 0;\n    virtual void send_piano_events(const i8 events[128]) = 0;\n    virtual const std::string &led_message() = 0;\n    virtual void led_message(std::string msg) = 0;\n    virtual void led_priority_message(f64 timeout, std::string msg) = 0;\n    virtual const std::string &status_message() = 0;\n    virtual void status_message(std::string msg) = 0;\n    //\n    template <class A, class... As>\n    void led_fmt(const char *fmt, const A &x, const As &... xs)\n    {\n        led_message(fmt::format(fmt, x, xs...));\n    }\n    template <class A, class... As>\n    void led_priority_fmt(f64 timeout, const char *fmt, const A &x, const As &... xs)\n    {\n        led_priority_message(timeout, fmt::format(fmt, x, xs...));\n    }\n    //\n    template <class A, class... As>\n    void status_fmt(const char *fmt, const A &x, const As &... xs)\n    {\n        status_message(fmt::format(fmt, x, xs...));\n    }\n    //\n    enum {\n        debugging_input = true,\n        debugging_logic = true,\n    };\n    inline void debug_input(std::string str)\n    {\n        if (debugging_input)\n            status_message(std::move(str));\n    }\n    inline void debug_logic(std::string str)\n    {\n        if (debugging_logic)\n            status_message(std::move(str));\n    }\n    template <class A, class... As>\n    void debug_input_fmt(const char *fmt, const A &x, const As &... xs)\n    {\n        if (debugging_input)\n            status_fmt(fmt, x, xs...);\n    }\n    template <class A, class... As>\n    void debug_logic_fmt(const char *fmt, const A &x, const As &... xs)\n    {\n        if (debugging_logic)\n            status_fmt(fmt, x, xs...);\n    }\n};\n\n}  // namespace cws80\n", "meta": {"hexsha": "bd0832e593f0b18fb9fd55dc6d39db6e4570b656", "size": 2942, "ext": "h", "lang": "C", "max_stars_repo_path": "sources/ui/cws80_ui_controller.h", "max_stars_repo_name": "jpcima/cws80", "max_stars_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-05-20T19:27:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-03T04:21:53.000Z", "max_issues_repo_path": "sources/ui/cws80_ui_controller.h", "max_issues_repo_name": "jpcima/cws80", "max_issues_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-05-21T12:56:22.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-23T21:33:33.000Z", "max_forks_repo_path": "sources/ui/cws80_ui_controller.h", "max_forks_repo_name": "jpcima/cws80", "max_forks_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6344086022, "max_line_length": 85, "alphanum_fraction": 0.6346023114, "num_tokens": 780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12421299538397429, "lm_q2_score": 0.0197191275672647, "lm_q1q2_score": 0.0024493719014886503}}
{"text": "\n#pragma once\n\n#include <Windows.h>\n\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <cstddef>\n#include <cassert>\n#include <cstdarg>\n#include <climits>\n#include <cinttypes>\n#include <cmath>\n#include <ctime>\n\n#include <algorithm>\n#include <any>\n#include <array>\n#include <chrono>\n#include <complex>\n#include <deque>\n#include <exception>\n#include <filesystem>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <iterator>\n#include <list>\n#include <locale>\n#include <memory>\n#include <mutex>\n#include <new>\n#include <numeric>\n#include <optional>\n#include <random>\n#include <ratio>\n#include <sstream>\n#include <stack>\n#include <string>\n#include <string_view>\n#include <system_error>\n#include <thread>\n#include <tuple>\n#include <type_traits>\n#include <typeinfo>\n#include <unordered_set>\n#include <utility>\n#include <valarray>\n#include <vector>\n\n#include <gsl/gsl>\n", "meta": {"hexsha": "51932140d4e3e018bb648ef7c5ffe42073128e3d", "size": 895, "ext": "h", "lang": "C", "max_stars_repo_path": "digger/Digger.h", "max_stars_repo_name": "lopezfjose/Digger", "max_stars_repo_head_hexsha": "434aeb02fad1ba00ba05ca52ebcf7694b2397a3c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "digger/Digger.h", "max_issues_repo_name": "lopezfjose/Digger", "max_issues_repo_head_hexsha": "434aeb02fad1ba00ba05ca52ebcf7694b2397a3c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "digger/Digger.h", "max_forks_repo_name": "lopezfjose/Digger", "max_forks_repo_head_hexsha": "434aeb02fad1ba00ba05ca52ebcf7694b2397a3c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.8867924528, "max_line_length": 24, "alphanum_fraction": 0.7318435754, "num_tokens": 203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10818895456207037, "lm_q2_score": 0.022629198673557907, "lm_q1q2_score": 0.0024482293470696193}}
{"text": "#define MPICH_SKIP_MPICXX 1\n#define OMPI_SKIP_MPICXX 1\n#include <Python.h>\n#include <petsc.h>\n#include \"libpetsc4py/libpetsc4py.c\"\n", "meta": {"hexsha": "d422b210b15e360e962e1958225d6282c407ffab", "size": 131, "ext": "c", "lang": "C", "max_stars_repo_path": "src/libpetsc4py.c", "max_stars_repo_name": "underworldcode/petsc4py", "max_stars_repo_head_hexsha": "fdfdd79be39b8cbe95cf57010f29a6cb2ef463a6", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libpetsc4py.c", "max_issues_repo_name": "underworldcode/petsc4py", "max_issues_repo_head_hexsha": "fdfdd79be39b8cbe95cf57010f29a6cb2ef463a6", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libpetsc4py.c", "max_forks_repo_name": "underworldcode/petsc4py", "max_forks_repo_head_hexsha": "fdfdd79be39b8cbe95cf57010f29a6cb2ef463a6", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.8333333333, "max_line_length": 36, "alphanum_fraction": 0.7938931298, "num_tokens": 45, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1143685322190697, "lm_q2_score": 0.021287351871064498, "lm_q1q2_score": 0.0024346031883245136}}
{"text": "/*\n * Portions Copyright (c) 2010-Present Couchbase\n * Portions Copyright (c) 2008 Sun Microsystems\n *\n * Use of this software is governed by the Apache License, Version 2.0 and\n * BSD 3 Clause included in the files licenses/APL2.txt and\n * licenses/BSD-3-Clause-Sun-Microsystems.txt\n */\n#pragma once\n\n#include \"dockey.h\"\n\n#include <gsl/gsl-lite.hpp>\n#include <memcached/vbucket.h>\n#include <platform/socket.h>\n\n#ifndef WIN32\n#include <arpa/inet.h>\n#endif\n#include <cstdint>\n#include <stdexcept>\n#include <string>\n\nnamespace cb::durability {\nenum class Level : uint8_t;\n} // namespace cb::durability\n\n/**\n * \\addtogroup Protocol\n * @{\n */\n\n/**\n * This file contains definitions of the constants and packet formats\n * defined in the binary specification. Please note that you _MUST_ remember\n * to convert each multibyte field to / from network byte order to / from\n * host order.\n */\n\n#include <mcbp/protocol/datatype.h>\n#include <mcbp/protocol/dcp_stream_end_status.h>\n#include <mcbp/protocol/feature.h>\n#include <mcbp/protocol/magic.h>\n#include <mcbp/protocol/opcode.h>\n#include <mcbp/protocol/request.h>\n#include <mcbp/protocol/response.h>\n#include <mcbp/protocol/status.h>\n\n// For backward compatibility with old sources\n\n/**\n * Definition of the header structure for a request packet.\n * See section 2\n */\nunion protocol_binary_request_header {\n    cb::mcbp::Request request;\n    uint8_t bytes[24];\n};\n\n/**\n * Definition of the header structure for a response packet.\n * See section 2\n */\nunion protocol_binary_response_header {\n    cb::mcbp::Response response;\n    uint8_t bytes[24];\n};\n\n/**\n * Definition of a request-packet containing no extras\n */\ntypedef union {\n    struct {\n        protocol_binary_request_header header;\n    } message;\n    uint8_t bytes[sizeof(protocol_binary_request_header)];\n} protocol_binary_request_no_extras;\n\n/**\n * Definition of a response-packet containing no extras\n */\ntypedef union {\n    struct {\n        protocol_binary_response_header header;\n    } message;\n    uint8_t bytes[sizeof(protocol_binary_response_header)];\n} protocol_binary_response_no_extras;\n\n/**\n * Definition of the packet used by set, add and replace\n * See section 4\n */\nnamespace cb::mcbp::request {\n#pragma pack(1)\nclass MutationPayload {\npublic:\n    /// The memcached core keep the flags stored in network byte order\n    /// internally as it does not use them for anything else than sending\n    /// them back to the client\n    uint32_t getFlagsInNetworkByteOrder() const {\n        return flags;\n    }\n\n    uint32_t getFlags() const {\n        return ntohl(flags);\n    }\n\n    void setFlags(uint32_t flags) {\n        MutationPayload::flags = htonl(flags);\n    }\n    uint32_t getExpiration() const {\n        return ntohl(expiration);\n    }\n    void setExpiration(uint32_t expiration) {\n        MutationPayload::expiration = htonl(expiration);\n    }\n\n    cb::const_byte_buffer getBuffer() const {\n        return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};\n    }\n\nprotected:\n    uint32_t flags = 0;\n    uint32_t expiration = 0;\n};\nstatic_assert(sizeof(MutationPayload) == 8, \"Unexpected struct size\");\n\nclass ArithmeticPayload {\npublic:\n    uint64_t getDelta() const {\n        return ntohll(delta);\n    }\n    void setDelta(uint64_t delta) {\n        ArithmeticPayload::delta = htonll(delta);\n    }\n    uint64_t getInitial() const {\n        return ntohll(initial);\n    }\n    void setInitial(uint64_t initial) {\n        ArithmeticPayload::initial = htonll(initial);\n    }\n    uint32_t getExpiration() const {\n        return ntohl(expiration);\n    }\n    void setExpiration(uint32_t expiration) {\n        ArithmeticPayload::expiration = htonl(expiration);\n    }\n\n    cb::const_byte_buffer getBuffer() const {\n        return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};\n    }\n\nprivate:\n    uint64_t delta = 0;\n    uint64_t initial = 0;\n    uint32_t expiration = 0;\n};\nstatic_assert(sizeof(ArithmeticPayload) == 20, \"Unexpected struct size\");\n\nclass DeprecatedSetClusterConfigPayload {\npublic:\n    int32_t getRevision() const {\n        return ntohl(revision);\n    }\n\n    void setRevision(int32_t rev) {\n        revision = htonl(rev);\n    }\n\n    cb::const_byte_buffer getBuffer() const {\n        return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};\n    }\n\nprotected:\n    int32_t revision{};\n};\nstatic_assert(sizeof(DeprecatedSetClusterConfigPayload) == 4,\n              \"Unexpected struct size\");\n\nclass SetClusterConfigPayload {\npublic:\n    int64_t getEpoch() const {\n        return ntohll(epoch);\n    }\n\n    void setEpoch(int64_t ep) {\n        epoch = htonll(ep);\n    }\n\n    int64_t getRevision() const {\n        return ntohll(revision);\n    }\n\n    void setRevision(int64_t rev) {\n        revision = htonll(rev);\n    }\n\n    cb::const_byte_buffer getBuffer() const {\n        return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};\n    }\n\nprotected:\n    int64_t epoch{0};\n    int64_t revision{0};\n};\nstatic_assert(sizeof(SetClusterConfigPayload) == 16, \"Unexpected struct size\");\n\nclass VerbosityPayload {\npublic:\n    uint32_t getLevel() const {\n        return ntohl(level);\n    }\n    void setLevel(uint32_t level) {\n        VerbosityPayload::level = htonl(level);\n    }\n\n    cb::const_byte_buffer getBuffer() const {\n        return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};\n    }\n\nprotected:\n    uint32_t level = 0;\n};\nstatic_assert(sizeof(VerbosityPayload) == 4, \"Unexpected size\");\n\nclass TouchPayload {\npublic:\n    uint32_t getExpiration() const {\n        return ntohl(expiration);\n    }\n    void setExpiration(uint32_t expiration) {\n        TouchPayload::expiration = htonl(expiration);\n    }\n\n    cb::const_byte_buffer getBuffer() const {\n        return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};\n    }\n\nprotected:\n    uint32_t expiration = 0;\n};\nstatic_assert(sizeof(TouchPayload) == 4, \"Unexpected size\");\nusing GatPayload = TouchPayload;\nusing GetLockedPayload = TouchPayload;\n\nclass SetCtrlTokenPayload {\npublic:\n    uint64_t getCas() const {\n        return ntohll(cas);\n    }\n    void setCas(uint64_t cas) {\n        SetCtrlTokenPayload::cas = htonll(cas);\n    }\n\n    cb::const_byte_buffer getBuffer() const {\n        return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};\n    }\n\nprotected:\n    uint64_t cas = 0;\n};\nstatic_assert(sizeof(SetCtrlTokenPayload) == 8, \"Unexpected size\");\n\n#pragma pack()\n} // namespace cb::mcbp::request\n\n/**\n * Definitions for extended (flexible) metadata\n *\n * @1: Flex Code to identify the number of extended metadata fields\n * @2: Size of the Flex Code, set to 1 byte\n * @3: Current size of extended metadata\n */\ntypedef enum {\n    FLEX_META_CODE = 0x01,\n    FLEX_DATA_OFFSET = 1,\n    EXT_META_LEN = 1\n} protocol_binary_flexmeta;\n\n/**\n * Definitions of sub-document path flags (this is a bitmap)\n */\ntypedef enum : uint8_t {\n    /** No flags set */\n    SUBDOC_FLAG_NONE = 0x0,\n\n    /** (Mutation) Should non-existent intermediate paths be created? */\n    SUBDOC_FLAG_MKDIR_P = 0x01,\n\n    /**\n     * 0x02 is unused\n     */\n\n    /**\n     * If set, the path refers to an Extended Attribute (XATTR).\n     * If clear, the path refers to a path inside the document body.\n     */\n    SUBDOC_FLAG_XATTR_PATH = 0x04,\n\n    /**\n     * 0x08 is unused\n     */\n\n    /**\n     * Expand macro values inside extended attributes. The request is\n     * invalid if this flag is set without SUBDOC_FLAG_XATTR_PATH being\n     * set.\n     */\n    SUBDOC_FLAG_EXPAND_MACROS = 0x10,\n\n} protocol_binary_subdoc_flag;\n\nnamespace mcbp::subdoc {\n\n/**\n * Definitions of sub-document doc flags (this is a bitmap).\n */\nenum class doc_flag : uint8_t {\n    None = 0x0,\n\n    /**\n     * (Mutation) Create the document if it does not exist. Implies\n     * SUBDOC_FLAG_MKDIR_P and Set (upsert) mutation semantics. Not valid\n     * with Add.\n     */\n    Mkdoc = 0x1,\n\n    /**\n     * (Mutation) Add the document only if it does not exist. Implies\n     * SUBDOC_FLAG_MKDIR_P. Not valid with Mkdoc.\n     */\n    Add = 0x02,\n\n    /**\n     * Allow access to XATTRs for deleted documents (instead of\n     * returning KEY_ENOENT). The result of mutations on a deleted\n     * document is still a deleted document unless ReviveDocument is\n     * being used.\n     */\n    AccessDeleted = 0x04,\n\n    /**\n     * (Mutation) Used with Mkdoc / Add; if the document does not exist then\n     * create it in the Deleted state, instead of the normal Alive state.\n     * Not valid unless Mkdoc or Add specified.\n     */\n    CreateAsDeleted = 0x08,\n\n    /**\n     * (Mutation) If the document exists and isn't deleted the operation\n     * will fail with SubdocCanOnlyReviveDeletedDocuments. If the input\n     * document _is_ deleted the result of the operation will store the\n     * document as a \"live\" document instead of a deleted document.\n     */\n    ReviveDocument = 0x10,\n};\n\n/**\n * Used for validation at parsing the doc-flags.\n * The value depends on how many bits the doc_flag enum is actually using and\n * must change accordingly.\n */\nstatic constexpr uint8_t extrasDocFlagMask = 0xe0;\n\n} // namespace mcbp::subdoc\n\n/**\n * Definition of the packet used by SUBDOCUMENT single-path commands.\n *\n * The path, which is always required, is in the Body, after the Key.\n *\n *   Header:                        24 @0: <protocol_binary_request_header>\n *   Extras:\n *     Sub-document pathlen          2 @24: <variable>\n *     Sub-document flags            1 @26: <protocol_binary_subdoc_flag>\n *     Expiry                        4 @27: (Optional) Mutations only. The\n *                                          ttl\n *     Sub-document doc flags        1 @27: (Optional) @31 if expiry is\n *                                          set. Note these are the\n *                                          subdocument doc flags not the\n *                                          flag section in the document.\n *   Body:\n *     Key                      keylen @27: <variable>\n *     Path                    pathlen @27+keylen: <variable>\n *     Value to insert/replace\n *               vallen-keylen-pathlen @27+keylen+pathlen: [variable]\n */\ntypedef union {\n    struct {\n        protocol_binary_request_header header;\n        struct {\n            uint16_t pathlen; // Length in bytes of the sub-doc path.\n            uint8_t subdoc_flags; // See protocol_binary_subdoc_flag\n            /* uint32_t expiry     (optional for mutations only - present\n                                    if extlen == 7 or extlen == 8) */\n            /* uint8_t doc_flags   (optional - present if extlen == 4 or\n                                    extlen == 8)  Note these are the\n                                    subdocument doc flags not the flag\n                                    \\section in the document. */\n        } extras;\n    } message;\n    uint8_t bytes[sizeof(protocol_binary_request_header) + 3];\n} protocol_binary_request_subdocument;\n\n/** Definition of the packet used by SUBDOCUMENT responses.\n */\ntypedef union {\n    struct {\n        protocol_binary_response_header header;\n    } message;\n    uint8_t bytes[sizeof(protocol_binary_response_header)];\n} protocol_binary_response_subdocument;\n\n/**\n * Definition of the request packets used by SUBDOCUMENT multi-path commands.\n *\n * Multi-path sub-document commands differ from single-path in that they\n * encode a series of multiple paths to operate on (from a single key).\n * There are two multi-path commands - MULTI_LOOKUP and MULTI_MUTATION.\n * - MULTI_LOOKUP consists of variable number of subdoc lookup commands\n *                (SUBDOC_GET or SUBDOC_EXISTS).\n * - MULTI_MUTATION consists of a variable number of subdoc mutation\n *                  commands (i.e. all subdoc commands apart from\n *                  SUBDOC_{GET,EXISTS}).\n *\n * Each path to be operated on is specified by an Operation Spec, which are\n * contained in the body. This defines the opcode, path, and value\n * (for mutations).\n *\n * A maximum of MULTI_MAX_PATHS paths (operations) can be encoded in a\n * single multi-path command.\n *\n *  SUBDOC_MULTI_LOOKUP:\n *    Header:                24 @0:  <protocol_binary_request_header>\n *    Extras:            0 or 1 @24: (optional) doc_flags. Note these are\n *                                   the subdocument doc flags not the flag\n *                                   section in the document.\n *    Body:         <variable>  @24:\n *        Key            keylen @24: <variable>\n *        1..MULTI_MAX_PATHS [Lookup Operation Spec]\n *\n *        Lookup Operation Spec:\n *                            1 @0 : Opcode\n *                            1 @1 : Flags\n *                            2 @2 : Path Length\n *                      pathlen @4 : Path\n */\nstatic const int PROTOCOL_BINARY_SUBDOC_MULTI_MAX_PATHS = 16;\n\ntypedef struct {\n    cb::mcbp::ClientOpcode opcode;\n    uint8_t flags;\n    uint16_t pathlen;\n    /* uint8_t path[pathlen] */\n} protocol_binary_subdoc_multi_lookup_spec;\n\ntypedef protocol_binary_request_no_extras\n        protocol_binary_request_subdocument_multi_lookup;\n\n/*\n *\n * SUBDOC_MULTI_MUTATION\n *    Header:                24 @0:  <protocol_binary_request_header>\n *    Extras:            0 OR 4 @24: (optional) expiration\n *                       0 OR 1 @24: (optional) doc_flags. Note these are\n *                                   the subdocument doc flags not the\n *                                   flag section in the document.\n *    Body:           variable  @24 + extlen:\n *        Key            keylen @24: <variable>\n *        1..MULTI_MAX_PATHS [Mutation Operation Spec]\n *\n *        Mutation Operation Spec:\n *                            1 @0         : Opcode\n *                            1 @1         : Flags\n *                            2 @2         : Path Length\n *                            4 @4         : Value Length\n *                      pathlen @8         : Path\n *                       vallen @8+pathlen : Value\n */\ntypedef struct {\n    cb::mcbp::ClientOpcode opcode;\n    uint8_t flags;\n    uint16_t pathlen;\n    uint32_t valuelen;\n    /* uint8_t path[pathlen] */\n    /* uint8_t value[valuelen]  */\n} protocol_binary_subdoc_multi_mutation_spec;\n\ntypedef protocol_binary_request_no_extras\n        protocol_binary_request_subdocument_multi_mutation;\n\n/**\n * Definition of the response packets used by SUBDOCUMENT multi-path\n * commands.\n *\n * SUBDOC_MULTI_LOOKUP - Body consists of a series of lookup_result structs,\n *                       one per lookup_spec in the request.\n *\n * Lookup Result:\n *                            2 @0 : status\n *                            4 @2 : resultlen\n *                    resultlen @6 : result\n */\ntypedef struct {\n    protocol_binary_request_header header;\n    /* Variable-length 1..PROTOCOL_BINARY_SUBDOC_MULTI_MAX_PATHS */\n    protocol_binary_subdoc_multi_lookup_spec body[1];\n} protocol_binary_response_subdoc_multi_lookup;\n\n/**\n * SUBDOC_MULTI_MUTATION response\n *\n * Extras is either 0 or 16 if MUTATION_SEQNO is enabled.\n *\n * Body consists of a variable number of subdoc_multi_mutation_result_spec\n * structs:\n *\n * On success (header.status == SUCCESS), zero or more result specs, one for\n * each multi_mutation_spec which wishes to return a value.\n *\n * Mutation Result (success):\n *   [0..N] of:\n *                   1 @0 : index - Index of multi_mutation spec this result\n *                          corresponds to.\n *                   2 @1 : status - Status of the mutation (should always\n *                          be SUCCESS for successful multi-mutation\n *                          requests).\n *                   4 @3 : resultlen - Result value length\n *           resultlen @7 : Value payload\n *\n\n * On one of more of the mutation specs failing, there is exactly one\n * result spec, specifying the index and status code of the first failing\n * mutation spec.\n *\n * Mutation Result (failure):\n *   1 of:\n *                   1 @0 : index - Index of multi_mutation spec this result\n *                          corresponds to.\n *                   2 @1 : status - Status of the mutation (should always be\n *                          !SUCCESS for failures).\n *\n * (Note: On failure the multi_mutation_result_spec only includes the\n *        first two fields).\n */\ntypedef union {\n    struct {\n        protocol_binary_response_header header;\n    } message;\n    uint8_t bytes[sizeof(protocol_binary_response_header)];\n} protocol_binary_response_subdoc_multi_mutation;\n\n/* DCP related stuff */\n\nnamespace cb::mcbp {\nnamespace request {\n#pragma pack(1)\nclass DcpOpenPayload {\npublic:\n    uint32_t getSeqno() const {\n        return ntohl(seqno);\n    }\n    void setSeqno(uint32_t seqno) {\n        DcpOpenPayload::seqno = htonl(seqno);\n    }\n    uint32_t getFlags() const {\n        return ntohl(flags);\n    }\n    void setFlags(uint32_t flags) {\n        DcpOpenPayload::flags = htonl(flags);\n    }\n\n    // Flags is a bitmask where the following values are used:\n\n    /**\n     * If set a Producer connection should be opened, if clear a Consumer\n     * connection should be opened.\n     */\n    static const uint32_t Producer = 1;\n    /// Invalid - should not be set (Previously the Notifier flag)\n    static const uint32_t Invalid = 2;\n    /**\n     * Indicate that the server include the documents' XATTRs\n     * within mutation and deletion bodies.\n     */\n    static const uint32_t IncludeXattrs = 4;\n    /**\n     * Indicate that the server should strip off the values (note,\n     * if you add INCLUDE_XATTR those will be present)\n     */\n    static const uint32_t NoValue = 8;\n    static const uint32_t Unused = 16;\n    /**\n     * Request that DCP delete message include the time the a delete was\n     * persisted. This only applies to deletes being backfilled from storage,\n     * in-memory deletes will have a delete time of 0\n     */\n    static const uint32_t IncludeDeleteTimes = 32;\n\n    /**\n     * Indicates that the server should strip off the values, but return the\n     * datatype of the underlying document (note, if you add\n     * INCLUDE_XATTR those will be present).\n     * Note this differs from DCP_OPEN_NO_VALUE in that the datatype field will\n     * contain the underlying datatype of the document; not the datatype of the\n     * transmitted payload.\n     * This flag can be used to obtain the full, original datatype for a\n     * document without the user's value. Not valid to specify with\n     * DCP_OPEN_NO_VALUE.\n     */\n    static const uint32_t NoValueWithUnderlyingDatatype = 64;\n\n    /// Requst PiTR for the connection (only legal for Producers)\n    static const uint32_t PiTR = 128;\n\n    /**\n     * Indicates that the server includes the document UserXattrs within\n     * deletion values.\n     */\n    static const uint32_t IncludeDeletedUserXattrs = 256;\n\n    cb::const_byte_buffer getBuffer() const {\n        return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};\n    }\n\nprotected:\n    uint32_t seqno = 0;\n    uint32_t flags = 0;\n};\nstatic_assert(sizeof(DcpOpenPayload) == 8, \"Unexpected struct size\");\n} // namespace request\n\nnamespace response {\nclass DcpAddStreamPayload {\npublic:\n    uint32_t getOpaque() const {\n        return ntohl(opaque);\n    }\n    void setOpaque(uint32_t opaque) {\n        DcpAddStreamPayload::opaque = htonl(opaque);\n    }\n\n    cb::const_byte_buffer getBuffer() const {\n        return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};\n    }\n\nprotected:\n    uint32_t opaque = 0;\n};\nstatic_assert(sizeof(DcpAddStreamPayload) == 4, \"Unexpected struct size\");\n} // namespace response\n\nnamespace request {\nclass DcpAddStreamPayload {\npublic:\n    uint32_t getFlags() const {\n        return ntohl(flags);\n    }\n    void setFlags(uint32_t flags) {\n        DcpAddStreamPayload::flags = htonl(flags);\n    }\n\n    cb::const_byte_buffer getBuffer() const {\n        return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};\n    }\n\nprotected:\n/*\n * The following flags are defined\n */\n#define DCP_ADD_STREAM_FLAG_TAKEOVER 1\n#define DCP_ADD_STREAM_FLAG_DISKONLY 2\n#define DCP_ADD_STREAM_FLAG_LATEST 4\n/**\n * This flag is not used anymore, and should NOT be\n * set. It is replaced by DCP_OPEN_NO_VALUE.\n */\n#define DCP_ADD_STREAM_FLAG_NO_VALUE 8\n/**\n * Indicate the server to add stream only if the vbucket\n * is active.\n * If the vbucket is not active, the stream request fails with\n * error cb::engine_errc::not_my_vbucket\n */\n#define DCP_ADD_STREAM_ACTIVE_VB_ONLY 16\n/**\n * Indicate the server to check for vb_uuid match even at start_seqno 0 before\n * adding the stream successfully.\n * If the flag is set and there is a vb_uuid mismatch at start_seqno 0, then\n * the server returns cb::engine_errc::rollback error.\n */\n#define DCP_ADD_STREAM_STRICT_VBUUID 32\n    uint32_t flags = 0;\n};\nstatic_assert(sizeof(DcpAddStreamPayload) == 4, \"Unexpected struct size\");\n\nclass DcpStreamReqPayload {\npublic:\n    uint32_t getFlags() const {\n        return ntohl(flags);\n    }\n    void setFlags(uint32_t flags) {\n        DcpStreamReqPayload::flags = htonl(flags);\n    }\n    uint32_t getReserved() const {\n        return ntohl(reserved);\n    }\n    void setReserved(uint32_t reserved) {\n        DcpStreamReqPayload::reserved = htonl(reserved);\n    }\n    uint64_t getStartSeqno() const {\n        return ntohll(start_seqno);\n    }\n    void setStartSeqno(uint64_t start_seqno) {\n        DcpStreamReqPayload::start_seqno = htonll(start_seqno);\n    }\n    uint64_t getEndSeqno() const {\n        return ntohll(end_seqno);\n    }\n    void setEndSeqno(uint64_t end_seqno) {\n        DcpStreamReqPayload::end_seqno = htonll(end_seqno);\n    }\n    uint64_t getVbucketUuid() const {\n        return ntohll(vbucket_uuid);\n    }\n    void setVbucketUuid(uint64_t vbucket_uuid) {\n        DcpStreamReqPayload::vbucket_uuid = htonll(vbucket_uuid);\n    }\n    uint64_t getSnapStartSeqno() const {\n        return ntohll(snap_start_seqno);\n    }\n    void setSnapStartSeqno(uint64_t snap_start_seqno) {\n        DcpStreamReqPayload::snap_start_seqno = htonll(snap_start_seqno);\n    }\n    uint64_t getSnapEndSeqno() const {\n        return ntohll(snap_end_seqno);\n    }\n    void setSnapEndSeqno(uint64_t snap_end_seqno) {\n        DcpStreamReqPayload::snap_end_seqno = htonll(snap_end_seqno);\n    }\n\n    cb::const_byte_buffer getBuffer() const {\n        return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};\n    }\n\nprotected:\n    uint32_t flags = 0;\n    uint32_t reserved = 0;\n    uint64_t start_seqno = 0;\n    uint64_t end_seqno = 0;\n    uint64_t vbucket_uuid = 0;\n    uint64_t snap_start_seqno = 0;\n    uint64_t snap_end_seqno = 0;\n};\nstatic_assert(sizeof(DcpStreamReqPayload) == 48, \"Unexpected struct size\");\n\nclass DcpStreamEndPayload {\npublic:\n    DcpStreamEndStatus getStatus() const {\n        return DcpStreamEndStatus(ntohl(status));\n    }\n    void setStatus(DcpStreamEndStatus status) {\n        DcpStreamEndPayload::status = htonl(uint32_t(status));\n    }\n\n    cb::const_byte_buffer getBuffer() const {\n        return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};\n    }\n\nprotected:\n    /**\n     * Note the following is maintained in network/big endian\n     * see protocol/dcp_stream_end_status.h for values\n     */\n    uint32_t status = 0;\n};\nstatic_assert(sizeof(DcpStreamEndPayload) == 4, \"Unexpected struct size\");\n\nclass DcpSnapshotMarkerV1Payload {\npublic:\n    uint64_t getStartSeqno() const {\n        return ntohll(start_seqno);\n    }\n    void setStartSeqno(uint64_t start_seqno) {\n        DcpSnapshotMarkerV1Payload::start_seqno = htonll(start_seqno);\n    }\n    uint64_t getEndSeqno() const {\n        return ntohll(end_seqno);\n    }\n    void setEndSeqno(uint64_t end_seqno) {\n        DcpSnapshotMarkerV1Payload::end_seqno = htonll(end_seqno);\n    }\n    uint32_t getFlags() const {\n        return ntohl(flags);\n    }\n    void setFlags(uint32_t flags) {\n        DcpSnapshotMarkerV1Payload::flags = htonl(flags);\n    }\n    cb::const_byte_buffer getBuffer() const {\n        return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};\n    }\n\nprotected:\n    uint64_t start_seqno = 0;\n    uint64_t end_seqno = 0;\n    uint32_t flags = 0;\n};\nstatic_assert(sizeof(DcpSnapshotMarkerV1Payload) == 20,\n              \"Unexpected struct size\");\n\nenum class DcpSnapshotMarkerFlag : uint32_t {\n    Memory = 0x01,\n    Disk = 0x02,\n    Checkpoint = 0x04,\n    Acknowledge = 0x08\n};\n\nenum class DcpSnapshotMarkerV2xVersion : uint8_t { Zero = 0, One = 1 };\n\n// Version 2.x\nclass DcpSnapshotMarkerV2xPayload {\npublic:\n    explicit DcpSnapshotMarkerV2xPayload(DcpSnapshotMarkerV2xVersion v)\n        : version(v) {\n    }\n    DcpSnapshotMarkerV2xVersion getVersion() const {\n        return version;\n    }\n    void setVersion(DcpSnapshotMarkerV2xVersion v) {\n        version = v;\n    }\n    cb::const_byte_buffer getBuffer() const {\n        return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};\n    }\n\nprotected:\n    DcpSnapshotMarkerV2xVersion version{DcpSnapshotMarkerV2xVersion::Zero};\n};\nstatic_assert(sizeof(DcpSnapshotMarkerV2xPayload) == 1,\n              \"Unexpected struct size\");\n\nclass DcpSnapshotMarkerV2_0Value : public DcpSnapshotMarkerV1Payload {\npublic:\n    uint64_t getMaxVisibleSeqno() const {\n        return ntohll(maxVisibleSeqno);\n    }\n    void setMaxVisibleSeqno(uint64_t maxVisibleSeqno) {\n        DcpSnapshotMarkerV2_0Value::maxVisibleSeqno = htonll(maxVisibleSeqno);\n    }\n    uint64_t getHighCompletedSeqno() const {\n        return ntohll(highCompletedSeqno);\n    }\n    void setHighCompletedSeqno(uint64_t highCompletedSeqno) {\n        DcpSnapshotMarkerV2_0Value::highCompletedSeqno =\n                htonll(highCompletedSeqno);\n    }\n    cb::const_byte_buffer getBuffer() const {\n        return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};\n    }\n\nprotected:\n    uint64_t maxVisibleSeqno{0};\n    uint64_t highCompletedSeqno{0};\n};\nstatic_assert(sizeof(DcpSnapshotMarkerV2_0Value) == 36,\n              \"Unexpected struct size\");\n\nclass DcpSnapshotMarkerV2_1Value : public DcpSnapshotMarkerV2_0Value {\npublic:\n    uint64_t getTimestamp() const {\n        return ntohll(timestamp);\n    }\n    void setTimestamp(uint64_t value) {\n        timestamp = htonll(value);\n    }\n\n    cb::const_byte_buffer getBuffer() const {\n        return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};\n    }\n\nprotected:\n    uint64_t timestamp{0};\n};\nstatic_assert(sizeof(DcpSnapshotMarkerV2_1Value) == 44,\n              \"Unexpected struct size\");\n\nclass DcpMutationPayload {\npublic:\n    DcpMutationPayload() = default;\n    DcpMutationPayload(uint64_t by_seqno,\n                       uint64_t rev_seqno,\n                       uint32_t flags,\n                       uint32_t expiration,\n                       uint32_t lock_time,\n                       uint8_t nru)\n        : by_seqno(htonll(by_seqno)),\n          rev_seqno(htonll(rev_seqno)),\n          flags(flags),\n          expiration(htonl(expiration)),\n          lock_time(htonl(lock_time)),\n          nru(nru) {\n    }\n    uint64_t getBySeqno() const {\n        return ntohll(by_seqno);\n    }\n    void setBySeqno(uint64_t by_seqno) {\n        DcpMutationPayload::by_seqno = htonll(by_seqno);\n    }\n    uint64_t getRevSeqno() const {\n        return ntohll(rev_seqno);\n    }\n    void setRevSeqno(uint64_t rev_seqno) {\n        DcpMutationPayload::rev_seqno = htonll(rev_seqno);\n    }\n    uint32_t getFlags() const {\n        return flags;\n    }\n    void setFlags(uint32_t flags) {\n        DcpMutationPayload::flags = flags;\n    }\n    uint32_t getExpiration() const {\n        return ntohl(expiration);\n    }\n    void setExpiration(uint32_t expiration) {\n        DcpMutationPayload::expiration = htonl(expiration);\n    }\n    uint32_t getLockTime() const {\n        return ntohl(lock_time);\n    }\n    void setLockTime(uint32_t lock_time) {\n        DcpMutationPayload::lock_time = htonl(lock_time);\n    }\n    uint16_t getNmeta() const {\n        return ntohs(nmeta);\n    }\n    uint8_t getNru() const {\n        return nru;\n    }\n    void setNru(uint8_t nru) {\n        DcpMutationPayload::nru = nru;\n    }\n\n    std::string_view getBuffer() const {\n        return {reinterpret_cast<const char*>(this), sizeof(*this)};\n    }\n\nprotected:\n    uint64_t by_seqno = 0;\n    uint64_t rev_seqno = 0;\n    uint32_t flags = 0;\n    uint32_t expiration = 0;\n    uint32_t lock_time = 0;\n    /// We don't set this anymore, but old servers may send it to us\n    /// but we'll ignore it\n    const uint16_t nmeta = 0;\n    uint8_t nru = 0;\n};\nstatic_assert(sizeof(DcpMutationPayload) == 31, \"Unexpected struct size\");\n\nclass DcpDeletionV1Payload {\npublic:\n    DcpDeletionV1Payload(uint64_t _by_seqno, uint64_t _rev_seqno)\n        : by_seqno(htonll(_by_seqno)), rev_seqno(htonll(_rev_seqno)) {\n    }\n    uint64_t getBySeqno() const {\n        return ntohll(by_seqno);\n    }\n    void setBySeqno(uint64_t by_seqno) {\n        DcpDeletionV1Payload::by_seqno = htonll(by_seqno);\n    }\n    uint64_t getRevSeqno() const {\n        return ntohll(rev_seqno);\n    }\n    void setRevSeqno(uint64_t rev_seqno) {\n        DcpDeletionV1Payload::rev_seqno = htonll(rev_seqno);\n    }\n    uint16_t getNmeta() const {\n        return ntohs(nmeta);\n    }\n    cb::const_byte_buffer getBuffer() const {\n        return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};\n    }\n\nprotected:\n    uint64_t by_seqno = 0;\n    uint64_t rev_seqno = 0;\n    const uint16_t nmeta = 0;\n};\nstatic_assert(sizeof(DcpDeletionV1Payload) == 18, \"Unexpected struct size\");\n\nclass DcpDeleteRequestV1 {\npublic:\n    DcpDeleteRequestV1(uint32_t opaque,\n                       Vbid vbucket,\n                       uint64_t cas,\n                       uint16_t keyLen,\n                       uint32_t valueLen,\n                       protocol_binary_datatype_t datatype,\n                       uint64_t bySeqno,\n                       uint64_t revSeqno)\n        : req{}, body(bySeqno, revSeqno) {\n        req.setMagic(cb::mcbp::Magic::ClientRequest);\n        req.setOpcode(cb::mcbp::ClientOpcode::DcpDeletion);\n        req.setExtlen(gsl::narrow<uint8_t>(sizeof(body)));\n        req.setKeylen(keyLen);\n        req.setBodylen(gsl::narrow<uint32_t>(sizeof(body) + keyLen + valueLen));\n        req.setOpaque(opaque);\n        req.setVBucket(vbucket);\n        req.setCas(cas);\n        req.setDatatype(cb::mcbp::Datatype(datatype));\n    }\n\nprotected:\n    cb::mcbp::Request req;\n    DcpDeletionV1Payload body;\n};\nstatic_assert(sizeof(DcpDeleteRequestV1) == 42, \"Unexpected struct size\");\n\nclass DcpDeletionV2Payload {\npublic:\n    DcpDeletionV2Payload(uint64_t by_seqno,\n                         uint64_t rev_seqno,\n                         uint32_t delete_time)\n        : by_seqno(htonll(by_seqno)),\n          rev_seqno(htonll(rev_seqno)),\n          delete_time(htonl(delete_time)) {\n    }\n    uint64_t getBySeqno() const {\n        return ntohll(by_seqno);\n    }\n    void setBySeqno(uint64_t by_seqno) {\n        DcpDeletionV2Payload::by_seqno = htonll(by_seqno);\n    }\n    uint64_t getRevSeqno() const {\n        return ntohll(rev_seqno);\n    }\n    void setRevSeqno(uint64_t rev_seqno) {\n        DcpDeletionV2Payload::rev_seqno = htonll(rev_seqno);\n    }\n    uint32_t getDeleteTime() const {\n        return ntohl(delete_time);\n    }\n    void setDeleteTime(uint32_t delete_time) {\n        DcpDeletionV2Payload::delete_time = htonl(delete_time);\n    }\n    cb::const_byte_buffer getBuffer() const {\n        return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};\n    }\n\nprotected:\n    uint64_t by_seqno = 0;\n    uint64_t rev_seqno = 0;\n    uint32_t delete_time = 0;\n    const uint8_t unused = 0;\n};\nstatic_assert(sizeof(DcpDeletionV2Payload) == 21, \"Unexpected struct size\");\n\nclass DcpDeleteRequestV2 {\npublic:\n    DcpDeleteRequestV2(uint32_t opaque,\n                       Vbid vbucket,\n                       uint64_t cas,\n                       uint16_t keyLen,\n                       uint32_t valueLen,\n                       protocol_binary_datatype_t datatype,\n                       uint64_t bySeqno,\n                       uint64_t revSeqno,\n                       uint32_t deleteTime)\n        : req{}, body(bySeqno, revSeqno, deleteTime) {\n        req.setMagic(cb::mcbp::Magic::ClientRequest);\n        req.setOpcode(cb::mcbp::ClientOpcode::DcpDeletion);\n        req.setExtlen(gsl::narrow<uint8_t>(sizeof(body)));\n        req.setKeylen(keyLen);\n        req.setBodylen(gsl::narrow<uint32_t>(sizeof(body) + keyLen + valueLen));\n        req.setOpaque(opaque);\n        req.setVBucket(vbucket);\n        req.setCas(cas);\n        req.setDatatype(cb::mcbp::Datatype(datatype));\n    }\n\nprotected:\n    cb::mcbp::Request req;\n    DcpDeletionV2Payload body;\n};\nstatic_assert(sizeof(DcpDeleteRequestV2) == 45, \"Unexpected struct size\");\n\nclass DcpExpirationPayload {\npublic:\n    DcpExpirationPayload() = default;\n    DcpExpirationPayload(uint64_t by_seqno,\n                         uint64_t rev_seqno,\n                         uint32_t delete_time)\n        : by_seqno(htonll(by_seqno)),\n          rev_seqno(htonll(rev_seqno)),\n          delete_time(htonl(delete_time)) {\n    }\n\n    uint64_t getBySeqno() const {\n        return ntohll(by_seqno);\n    }\n    void setBySeqno(uint64_t by_seqno) {\n        DcpExpirationPayload::by_seqno = htonll(by_seqno);\n    }\n    uint64_t getRevSeqno() const {\n        return ntohll(rev_seqno);\n    }\n    void setRevSeqno(uint64_t rev_seqno) {\n        DcpExpirationPayload::rev_seqno = htonll(rev_seqno);\n    }\n    uint32_t getDeleteTime() const {\n        return ntohl(delete_time);\n    }\n    void setDeleteTime(uint32_t delete_time) {\n        DcpExpirationPayload::delete_time = htonl(delete_time);\n    }\n\n    cb::const_byte_buffer getBuffer() const {\n        return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};\n    }\n\nprotected:\n    uint64_t by_seqno = 0;\n    uint64_t rev_seqno = 0;\n    uint32_t delete_time = 0;\n};\nstatic_assert(sizeof(DcpExpirationPayload) == 20, \"Unexpected struct size\");\n\nclass DcpSetVBucketState {\npublic:\n    uint8_t getState() const {\n        return state;\n    }\n    void setState(uint8_t state) {\n        DcpSetVBucketState::state = state;\n    }\n\n    bool isValid() const {\n        return is_valid_vbucket_state_t(state);\n    }\n\n    cb::const_byte_buffer getBuffer() const {\n        return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};\n    }\n\nprotected:\n    uint8_t state;\n};\nstatic_assert(sizeof(DcpSetVBucketState) == 1, \"Unexpected struct size\");\n\nclass DcpBufferAckPayload {\npublic:\n    uint32_t getBufferBytes() const {\n        return ntohl(buffer_bytes);\n    }\n    void setBufferBytes(uint32_t buffer_bytes) {\n        DcpBufferAckPayload::buffer_bytes = htonl(buffer_bytes);\n    }\n\n    cb::const_byte_buffer getBuffer() const {\n        return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};\n    }\n\nprotected:\n    uint32_t buffer_bytes = 0;\n};\n\nstatic_assert(sizeof(DcpBufferAckPayload) == 4, \"Unexpected struct size\");\n\nenum class DcpOsoSnapshotFlags : uint32_t {\n    Start = 0x01,\n    End = 0x02,\n};\n\nclass DcpOsoSnapshotPayload {\npublic:\n    explicit DcpOsoSnapshotPayload(uint32_t flags) : flags(htonl(flags)) {\n    }\n    uint32_t getFlags() const {\n        return ntohl(flags);\n    }\n    void setFlags(uint32_t flags) {\n        DcpOsoSnapshotPayload::flags = htonl(flags);\n    }\n    cb::const_byte_buffer getBuffer() const {\n        return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};\n    }\n\nprotected:\n    uint32_t flags = 0;\n};\nstatic_assert(sizeof(DcpOsoSnapshotPayload) == 4, \"Unexpected struct size\");\n\nclass DcpSeqnoAdvancedPayload {\npublic:\n    explicit DcpSeqnoAdvancedPayload(uint64_t seqno) : by_seqno(htonll(seqno)) {\n    }\n    [[nodiscard]] uint64_t getSeqno() const {\n        return ntohll(by_seqno);\n    }\n    void setSeqno(uint64_t seqno) {\n        DcpSeqnoAdvancedPayload::by_seqno = htonll(seqno);\n    }\n    [[nodiscard]] cb::const_byte_buffer getBuffer() const {\n        return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};\n    }\n\nprotected:\n    uint64_t by_seqno = 0;\n};\nstatic_assert(sizeof(DcpSeqnoAdvancedPayload) == 8, \"Unexpected struct size\");\n\n#pragma pack()\n} // namespace request\n} // namespace cb::mcbp\n\n/**\n * Events that the system may send\n */\nnamespace mcbp::systemevent {\n\nenum class id : uint32_t {\n    CreateCollection = 0,\n    DeleteCollection = 1,\n    FlushCollection = 2,\n    CreateScope = 3,\n    DropScope = 4\n};\n\nenum class version : uint8_t { version0 = 0, version1 = 1 };\n} // namespace mcbp::systemevent\n\nnamespace cb::mcbp::request {\n#pragma pack(1)\n\nclass DcpSystemEventPayload {\npublic:\n    DcpSystemEventPayload() = default;\n    DcpSystemEventPayload(uint64_t by_seqno,\n                          ::mcbp::systemevent::id event,\n                          ::mcbp::systemevent::version version)\n        : by_seqno(htonll(by_seqno)),\n          event(htonl(static_cast<uint32_t>(event))),\n          version(static_cast<uint8_t>(version)) {\n    }\n\n    uint64_t getBySeqno() const {\n        return ntohll(by_seqno);\n    }\n    void setBySeqno(uint64_t by_seqno) {\n        DcpSystemEventPayload::by_seqno = htonll(by_seqno);\n    }\n    uint32_t getEvent() const {\n        return ntohl(event);\n    }\n    void setEvent(uint32_t event) {\n        DcpSystemEventPayload::event = htonl(event);\n    }\n    uint8_t getVersion() const {\n        return version;\n    }\n    void setVersion(uint8_t version) {\n        DcpSystemEventPayload::version = version;\n    }\n\n    cb::const_byte_buffer getBuffer() const {\n        return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};\n    }\n\n    /**\n     * Validate that the uint32_t event field represents a valid systemevent::id\n     */\n    bool isValidEvent() const {\n        using ::mcbp::systemevent::id;\n        switch (id(getEvent())) {\n        case id::CreateCollection:\n        case id::DeleteCollection:\n        case id::FlushCollection:\n        case id::CreateScope:\n        case id::DropScope:\n            return true;\n        }\n        return false;\n    }\n\n    /**\n     * Validate that the uint8_t version represents a valid systemevent::version\n     */\n    bool isValidVersion() const {\n        using ::mcbp::systemevent::version;\n        switch (version(getVersion())) {\n        case version::version0:\n        case version::version1:\n            return true;\n        }\n        return false;\n    }\n\nprotected:\n    uint64_t by_seqno = 0;\n    uint32_t event = 0;\n    uint8_t version = 0;\n};\nstatic_assert(sizeof(DcpSystemEventPayload) == 13, \"Unexpected struct size\");\n\nclass DcpPreparePayload {\npublic:\n    DcpPreparePayload() = default;\n    DcpPreparePayload(uint64_t by_seqno,\n                      uint64_t rev_seqno,\n                      uint32_t flags,\n                      uint32_t expiration,\n                      uint32_t lock_time,\n                      uint8_t nru)\n        : by_seqno(htonll(by_seqno)),\n          rev_seqno(htonll(rev_seqno)),\n          flags(flags),\n          expiration(htonl(expiration)),\n          lock_time(htonl(lock_time)),\n          nru(nru) {\n    }\n    uint64_t getBySeqno() const {\n        return ntohll(by_seqno);\n    }\n    void setBySeqno(uint64_t by_seqno) {\n        DcpPreparePayload::by_seqno = htonll(by_seqno);\n    }\n    uint64_t getRevSeqno() const {\n        return ntohll(rev_seqno);\n    }\n    void setRevSeqno(uint64_t rev_seqno) {\n        DcpPreparePayload::rev_seqno = htonll(rev_seqno);\n    }\n    uint32_t getFlags() const {\n        return flags;\n    }\n    void setFlags(uint32_t flags) {\n        DcpPreparePayload::flags = flags;\n    }\n    uint32_t getExpiration() const {\n        return ntohl(expiration);\n    }\n    void setExpiration(uint32_t expiration) {\n        DcpPreparePayload::expiration = htonl(expiration);\n    }\n    uint32_t getLockTime() const {\n        return ntohl(lock_time);\n    }\n    void setLockTime(uint32_t lock_time) {\n        DcpPreparePayload::lock_time = htonl(lock_time);\n    }\n    uint8_t getNru() const {\n        return nru;\n    }\n    void setNru(uint8_t nru) {\n        DcpPreparePayload::nru = nru;\n    }\n\n    uint8_t getDeleted() const {\n        return deleted;\n    }\n    void setDeleted(uint8_t deleted) {\n        DcpPreparePayload::deleted = deleted;\n    }\n\n    cb::const_byte_buffer getBuffer() const {\n        return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};\n    }\n\n    cb::durability::Level getDurabilityLevel() const;\n\n    void setDurabilityLevel(cb::durability::Level level);\n\nprotected:\n    uint64_t by_seqno = 0;\n    uint64_t rev_seqno = 0;\n    uint32_t flags = 0;\n    uint32_t expiration = 0;\n    uint32_t lock_time = 0;\n    uint8_t nru = 0;\n    // set to true if this is a document deletion\n    uint8_t deleted = 0;\n    uint8_t durability_level = 0;\n};\n\nstatic_assert(sizeof(DcpPreparePayload) == 31, \"Unexpected struct size\");\n\nclass DcpSeqnoAcknowledgedPayload {\npublic:\n    explicit DcpSeqnoAcknowledgedPayload(uint64_t prepared)\n        : prepared_seqno(htonll(prepared)) {\n    }\n\n    uint64_t getPreparedSeqno() const {\n        return ntohll(prepared_seqno);\n    }\n\n    cb::const_byte_buffer getBuffer() const {\n        return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};\n    }\n\nprotected:\n    // Stored in network order.\n    uint64_t prepared_seqno = 0;\n};\nstatic_assert(sizeof(DcpSeqnoAcknowledgedPayload) == 8,\n              \"Unexpected struct size\");\n\nclass DcpCommitPayload {\npublic:\n    DcpCommitPayload(uint64_t prepared, uint64_t committed)\n        : prepared_seqno(htonll(prepared)), commit_seqno(htonll(committed)) {\n    }\n\n    uint64_t getPreparedSeqno() const {\n        return ntohll(prepared_seqno);\n    }\n    void setPreparedSeqno(uint64_t prepared_seqno) {\n        DcpCommitPayload::prepared_seqno = htonll(prepared_seqno);\n    }\n    uint64_t getCommitSeqno() const {\n        return ntohll(commit_seqno);\n    }\n    void setCommitSeqno(uint64_t commit_seqno) {\n        DcpCommitPayload::commit_seqno = htonll(commit_seqno);\n    }\n\n    cb::const_byte_buffer getBuffer() const {\n        return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};\n    }\n\nprotected:\n    uint64_t prepared_seqno = 0;\n    uint64_t commit_seqno = 0;\n};\nstatic_assert(sizeof(DcpCommitPayload) == 16, \"Unexpected struct size\");\n\nclass DcpAbortPayload {\npublic:\n    DcpAbortPayload(uint64_t prepared, uint64_t aborted)\n        : prepared_seqno(htonll(prepared)), abort_seqno(htonll(aborted)) {\n    }\n\n    uint64_t getPreparedSeqno() const {\n        return ntohll(prepared_seqno);\n    }\n\n    void setPreparedSeqno(uint64_t seqno) {\n        prepared_seqno = htonll(seqno);\n    }\n\n    uint64_t getAbortSeqno() const {\n        return ntohll(abort_seqno);\n    }\n\n    void setAbortSeqno(uint64_t seqno) {\n        abort_seqno = htonll(seqno);\n    }\n\n    cb::const_byte_buffer getBuffer() const {\n        return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};\n    }\n\nprotected:\n    uint64_t prepared_seqno = 0;\n    uint64_t abort_seqno = 0;\n};\nstatic_assert(sizeof(DcpAbortPayload) == 16, \"Unexpected struct size\");\n\nclass SetParamPayload {\npublic:\n    enum class Type : uint32_t {\n        Flush = 1,\n        Replication,\n        Checkpoint,\n        Dcp,\n        Vbucket\n    };\n\n    Type getParamType() const {\n        return static_cast<Type>(ntohl(param_type));\n    }\n\n    void setParamType(Type param_type) {\n        SetParamPayload::param_type = htonl(static_cast<uint32_t>(param_type));\n    }\n\n    cb::const_byte_buffer getBuffer() const {\n        return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};\n    }\n\n    bool validate() const {\n        switch (getParamType()) {\n        case Type::Flush:\n        case Type::Replication:\n        case Type::Checkpoint:\n        case Type::Dcp:\n        case Type::Vbucket:\n            return true;\n        }\n        return false;\n    }\n\nprotected:\n    uint32_t param_type = 0;\n};\nstatic_assert(sizeof(SetParamPayload) == 4, \"Unexpected size\");\n#pragma pack()\n} // namespace cb::mcbp::request\n\n/**\n * This flag is used by the setWithMeta/addWithMeta/deleteWithMeta packets\n * to specify that the operation should be forced. The update will not\n * be subject to conflict resolution and the target vb can be active/pending or\n * replica.\n */\n#define FORCE_WITH_META_OP 0x01\n\n/**\n * This flag is used to indicate that the *_with_meta should be accepted\n * regardless of the bucket config. LWW buckets require this flag.\n */\n#define FORCE_ACCEPT_WITH_META_OPS 0x02\n\n/**\n * This flag asks that the server regenerates the CAS. The server requires\n * that SKIP_CONFLICT_RESOLUTION_FLAG is set along with this option.\n */\n#define REGENERATE_CAS 0x04\n\n/**\n * This flag is used by the setWithMeta/addWithMeta/deleteWithMeta packets\n * to specify that the conflict resolution mechanism should be skipped for\n * this operation.\n */\n#define SKIP_CONFLICT_RESOLUTION_FLAG 0x08\n\n/**\n * This flag is used by deleteWithMeta packets to specify if the delete sent\n * instead represents an expiration.\n */\n#define IS_EXPIRATION 0x10\n\n/**\n * This flag is used with the get meta response packet. If set it\n * specifies that the item recieved has been deleted, but that the\n * items meta data is still contained in ep-engine. Eg. the item\n * has been soft deleted.\n */\n#define GET_META_ITEM_DELETED_FLAG 0x01\n\nnamespace cb::mcbp::request {\n#pragma pack(1)\nclass SetWithMetaPayload {\npublic:\n    uint32_t getFlags() const {\n        return ntohl(flags);\n    }\n    uint32_t getFlagsInNetworkByteOrder() const {\n        return flags;\n    }\n    void setFlags(uint32_t flags) {\n        SetWithMetaPayload::flags = htonl(flags);\n    }\n    void setFlagsInNetworkByteOrder(uint32_t flags) {\n        SetWithMetaPayload::flags = flags;\n    }\n    uint32_t getExpiration() const {\n        return ntohl(expiration);\n    }\n    void setExpiration(uint32_t expiration) {\n        SetWithMetaPayload::expiration = htonl(expiration);\n    }\n    uint64_t getSeqno() const {\n        return ntohll(seqno);\n    }\n    void setSeqno(uint64_t seqno) {\n        SetWithMetaPayload::seqno = htonll(seqno);\n    }\n    uint64_t getCas() const {\n        return ntohll(cas);\n    }\n    void setCas(uint64_t cas) {\n        SetWithMetaPayload::cas = htonll(cas);\n    }\n    cb::const_byte_buffer getBuffer() const {\n        return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};\n    }\n\nprotected:\n    uint32_t flags = 0;\n    uint32_t expiration = 0;\n    uint64_t seqno = 0;\n    uint64_t cas = 0;\n};\nstatic_assert(sizeof(SetWithMetaPayload) == 24, \"Unexpected struct size\");\n\nclass DelWithMetaPayload {\npublic:\n    DelWithMetaPayload(uint32_t flags,\n                       uint32_t delete_time,\n                       uint64_t seqno,\n                       uint64_t cas)\n        : flags(htonl(flags)),\n          delete_time(htonl(delete_time)),\n          seqno(htonll(seqno)),\n          cas(htonll(cas)) {\n    }\n\n    uint32_t getFlags() const {\n        return ntohl(flags);\n    }\n    uint32_t getFlagsInNetworkByteOrder() const {\n        return flags;\n    }\n    void setFlags(uint32_t flags) {\n        DelWithMetaPayload::flags = htonl(flags);\n    }\n    uint32_t getDeleteTime() const {\n        return ntohl(delete_time);\n    }\n    void setDeleteTime(uint32_t delete_time) {\n        DelWithMetaPayload::delete_time = htonl(delete_time);\n    }\n    uint64_t getSeqno() const {\n        return ntohll(seqno);\n    }\n    void setSeqno(uint64_t seqno) {\n        DelWithMetaPayload::seqno = htonll(seqno);\n    }\n    uint64_t getCas() const {\n        return ntohll(cas);\n    }\n    void setCas(uint64_t cas) {\n        DelWithMetaPayload::cas = htonll(cas);\n    }\n    cb::const_byte_buffer getBuffer() const {\n        return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};\n    }\n\nprotected:\n    uint32_t flags = 0;\n    uint32_t delete_time = 0;\n    uint64_t seqno = 0;\n    uint64_t cas = 0;\n};\nstatic_assert(sizeof(DelWithMetaPayload) == 24, \"Unexpected struct size\");\n#pragma pack()\n} // namespace cb::mcbp::request\n\n/**\n * The physical layout for a CMD_GET_META command returns the meta-data\n * section for an item:\n */\ntypedef protocol_binary_request_no_extras protocol_binary_request_get_meta;\n\n/**\n * Structure holding getMeta command response fields\n */\n#pragma pack(1)\n\nstruct GetMetaResponse {\n    uint32_t deleted;\n    uint32_t flags;\n    uint32_t expiry;\n    uint64_t seqno;\n    uint8_t datatype;\n\n    GetMetaResponse() : deleted(0), flags(0), expiry(0), seqno(0), datatype(0) {\n    }\n\n    GetMetaResponse(uint32_t deleted,\n                    uint32_t flags,\n                    uint32_t expiry,\n                    uint64_t seqno,\n                    uint8_t datatype)\n        : deleted(deleted),\n          flags(flags),\n          expiry(expiry),\n          seqno(seqno),\n          datatype(datatype) {\n    }\n\n    cb::const_byte_buffer getBuffer() const {\n        return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};\n    }\n};\n\n#pragma pack()\n\nstatic_assert(sizeof(GetMetaResponse) == 21, \"Incorrect compiler padding\");\n\n/* Meta data versions for GET_META */\nenum class GetMetaVersion : uint8_t {\n    V1 = 1, // returns deleted, flags, expiry and seqno\n    V2 = 2, // The 'spock' version returns V1 + the datatype\n};\n\n/**\n * The physical layout for the CMD_RETURN_META\n */\nnamespace cb::mcbp::request {\n\n#pragma pack(1)\n\nenum class ReturnMetaType : uint32_t { Set = 1, Add = 2, Del = 3 };\n\nclass ReturnMetaPayload {\npublic:\n    ReturnMetaType getMutationType() const {\n        return static_cast<ReturnMetaType>(ntohl(mutation_type));\n    }\n    void setMutationType(ReturnMetaType mutation_type) {\n        ReturnMetaPayload::mutation_type =\n                htonl(static_cast<uint32_t>(mutation_type));\n    }\n    uint32_t getFlags() const {\n        return ntohl(flags);\n    }\n    void setFlags(uint32_t flags) {\n        ReturnMetaPayload::flags = htonl(flags);\n    }\n    uint32_t getExpiration() const {\n        return ntohl(expiration);\n    }\n    void setExpiration(uint32_t expiration) {\n        ReturnMetaPayload::expiration = htonl(expiration);\n    }\n\n    cb::const_byte_buffer getBuffer() const {\n        return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};\n    }\n\nprotected:\n    uint32_t mutation_type = 0;\n    uint32_t flags = 0;\n    uint32_t expiration = 0;\n};\nstatic_assert(sizeof(ReturnMetaPayload) == 12, \"Unexpected struct size\");\n\n/**\n * Message format for CMD_COMPACT_DB\n *\n * The PROTOCOL_BINARY_CMD_COMPACT_DB is used by ns_server to\n * issue a compaction request to ep-engine to compact the\n * underlying store's database files\n *\n * Request:\n *\n * Header: Contains the vbucket id. The vbucket id will be used\n *         to identify the database file if the backend is\n *         couchstore. If the vbucket id is set to 0xFFFF, then\n *         the vbid field will be used for compaction.\n * Body:\n * - purge_before_ts:  Deleted items whose expiry timestamp is less\n *                     than purge_before_ts will be purged.\n * - purge_before_seq: Deleted items whose sequence number is less\n *                     than purge_before_seq will be purged.\n * - drop_deletes:     whether to purge deleted items or not.\n * - vbid  :     Database file id for the underlying store.\n *\n * Response:\n *\n * The response will return a SUCCESS after compaction is done\n * successfully and a NOT_MY_VBUCKET (along with cluster config)\n * if the vbucket isn't found.\n */\nclass CompactDbPayload {\npublic:\n    uint64_t getPurgeBeforeTs() const {\n        return ntohll(purge_before_ts);\n    }\n    void setPurgeBeforeTs(uint64_t purge_before_ts) {\n        CompactDbPayload::purge_before_ts = htonll(purge_before_ts);\n    }\n    uint64_t getPurgeBeforeSeq() const {\n        return ntohll(purge_before_seq);\n    }\n    void setPurgeBeforeSeq(uint64_t purge_before_seq) {\n        CompactDbPayload::purge_before_seq = htonll(purge_before_seq);\n    }\n    uint8_t getDropDeletes() const {\n        return drop_deletes;\n    }\n    void setDropDeletes(uint8_t drop_deletes) {\n        CompactDbPayload::drop_deletes = drop_deletes;\n    }\n    const Vbid getDbFileId() const {\n        return db_file_id.ntoh();\n    }\n    void setDbFileId(const Vbid& db_file_id) {\n        CompactDbPayload::db_file_id = db_file_id.hton();\n    }\n\n    // Generate a method which use align_pad1 and 3 to avoid the compiler\n    // to generate a warning about unused member (because we\n    bool validate() const {\n        return align_pad1 == 0 && align_pad3 == 0;\n    }\n\n    cb::const_byte_buffer getBuffer() const {\n        return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};\n    }\n\nprotected:\n    uint64_t purge_before_ts = 0;\n    uint64_t purge_before_seq = 0;\n    uint8_t drop_deletes = 0;\n    uint8_t align_pad1 = 0;\n    Vbid db_file_id = Vbid{0};\n    uint32_t align_pad3 = 0;\n};\n#pragma pack()\nstatic_assert(sizeof(CompactDbPayload) == 24, \"Unexpected struct size\");\n} // namespace cb::mcbp::request\n\n#define OBS_STATE_NOT_PERSISTED 0x00\n#define OBS_STATE_PERSISTED 0x01\n#define OBS_STATE_NOT_FOUND 0x80\n#define OBS_STATE_LOGICAL_DEL 0x81\n\n/**\n * The physical layout for the PROTOCOL_BINARY_CMD_AUDIT_PUT\n */\ntypedef union {\n    struct {\n        protocol_binary_request_header header;\n        struct {\n            uint32_t id;\n        } body;\n    } message;\n    uint8_t bytes[sizeof(protocol_binary_request_header) + 4];\n} protocol_binary_request_audit_put;\n\ntypedef protocol_binary_response_no_extras protocol_binary_response_audit_put;\n\n/**\n * The PROTOCOL_BINARY_CMD_OBSERVE_SEQNO command is used by the\n * client to retrieve information about the vbucket in order to\n * find out if a particular mutation has been persisted or\n * replicated at the server side. In order to do so, the client\n * would pass the vbucket uuid of the vbucket that it wishes to\n * observe to the serve.  The response would contain the last\n * persisted sequence number and the latest sequence number in the\n * vbucket. For example, if a client sends a request to observe\n * the vbucket 0 with uuid 12345 and if the response contains the\n * values <58, 65> and then the client can infer that sequence\n * number 56 has been persisted, 60 has only been replicated and\n * not been persisted yet and 68 has not been replicated yet.\n */\n\n/**\n * Definition of the request packet for the observe_seqno command.\n *\n * Header: Contains the vbucket id of the vbucket that the client\n *         wants to observe.\n *\n * Body: Contains the vbucket uuid of the vbucket that the client\n *       wants to observe. The vbucket uuid is of type uint64_t.\n *\n */\ntypedef union {\n    struct {\n        protocol_binary_request_header header;\n        struct {\n            uint64_t uuid;\n        } body;\n    } message;\n    uint8_t bytes[sizeof(protocol_binary_request_header) + 8];\n} protocol_binary_request_observe_seqno;\n\n/**\n * Definition of the response packet for the observe_seqno command.\n * Body: Contains a tuple of the form\n *       <format_type, vbucket id, vbucket uuid, last_persisted_seqno,\n * current_seqno>\n *\n *       - format_type is of type uint8_t and it describes whether\n *         the vbucket has failed over or not. 1 indicates a hard\n *         failover, 0 indicates otherwise.\n *       - vbucket id is of type Vbid and it is the identifier for\n *         the vbucket.\n *       - vbucket uuid is of type uint64_t and it represents a UUID for\n *          the vbucket.\n *       - last_persisted_seqno is of type uint64_t and it is the\n *         last sequence number that was persisted for this\n *         vbucket.\n *       - current_seqno is of the type uint64_t and it is the\n *         sequence number of the latest mutation in the vbucket.\n *\n *       In the case of a hard failover, the tuple is of the form\n *       <format_type, vbucket id, vbucket uuid, last_persisted_seqno,\n * current_seqno, old vbucket uuid, last_received_seqno>\n *\n *       - old vbucket uuid is of type uint64_t and it is the\n *         vbucket UUID of the vbucket prior to the hard failover.\n *\n *       - last_received_seqno is of type uint64_t and it is the\n *         last received sequence number in the old vbucket uuid.\n *\n *       The other fields are the same as that mentioned in the normal case.\n */\ntypedef protocol_binary_response_no_extras\n        protocol_binary_response_observe_seqno;\n\n/**\n * Definition of the request packet for the command\n * PROTOCOL_BINARY_CMD_GET_ALL_VB_SEQNOS\n *\n * Header: Only opcode field is used.\n *\n * Body: Contains the vBucket state and/or collection id for which the vb\n *       sequence numbers are requested.\n *       Please note that these fields are optional, header.request.extlen is\n *       checked to see if they are present. If a vBucket state is not\n *       present or 0 it implies request is for all vbucket states. If\n *       collection id is not present it it implies the request is for the\n *       vBucket high seqno number.\n *\n */\ntypedef union {\n    struct {\n        protocol_binary_request_header header;\n        struct {\n            RequestedVBState state;\n            CollectionIDType cid;\n        } body;\n    } message;\n    uint8_t bytes[sizeof(protocol_binary_request_header) +\n                  sizeof(RequestedVBState) + sizeof(CollectionIDType)];\n} protocol_binary_request_get_all_vb_seqnos;\n\n/**\n * Definition of the payload in the PROTOCOL_BINARY_CMD_GET_ALL_VB_SEQNOS\n * response.\n *\n * The body contains a \"list\" of \"vbucket id - seqno pairs\" for all\n * active and replica buckets on the node in network byte order.\n *\n *\n *    Byte/     0       |       1       |       2       |       3       |\n *       /              |               |               |               |\n *      |0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|\n *      +---------------+---------------+---------------+---------------+\n *     0| VBID          | VBID          | SEQNO         | SEQNO         |\n *      +---------------+---------------+---------------+---------------+\n *     4| SEQNO         | SEQNO         | VBID          | VBID          |\n *      +---------------+---------------+---------------+---------------+\n *     4| SEQNO         | SEQNO         |\n *      +---------------+---------------+\n */\ntypedef protocol_binary_response_no_extras\n        protocol_binary_response_get_all_vb_seqnos;\n\n/**\n * Message format for PROTOCOL_BINARY_CMD_GET_KEYS\n *\n * The extras field may contain a 32 bit integer specifying the number\n * of keys to fetch. If no value specified 1000 keys is transmitted.\n *\n * Key is mandatory and specifies the starting key\n *\n * Get keys is used to fetch a sequence of keys from the server starting\n * at the specified key.\n */\ntypedef protocol_binary_request_no_extras protocol_binary_request_get_keys;\n\nnamespace cb::mcbp::request {\n#pragma pack(1)\n\nclass AdjustTimePayload {\npublic:\n    enum class TimeType : uint8_t { TimeOfDay = 0, Uptime = 1 };\n\n    uint64_t getOffset() const {\n        return ntohll(offset);\n    }\n    void setOffset(uint64_t offset) {\n        AdjustTimePayload::offset = htonll(offset);\n    }\n    TimeType getTimeType() const {\n        return time_type;\n    }\n    void setTimeType(TimeType time_type) {\n        AdjustTimePayload::time_type = time_type;\n    }\n\n    bool isValid() const {\n        switch (getTimeType()) {\n        case TimeType::TimeOfDay:\n        case TimeType::Uptime:\n            return true;\n        }\n        return false;\n    }\n\n    cb::const_byte_buffer getBuffer() const {\n        return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};\n    }\n\nprotected:\n    uint64_t offset = 0;\n    TimeType time_type = TimeType::TimeOfDay;\n};\nstatic_assert(sizeof(AdjustTimePayload) == 9, \"Unexpected struct size\");\n\n/**\n * Message format for PROTOCOL_BINARY_CMD_EWOULDBLOCK_CTL\n *\n * See engines/ewouldblock_engine for more information.\n */\nclass EWB_Payload {\npublic:\n    uint32_t getMode() const {\n        return ntohl(mode);\n    }\n    void setMode(uint32_t m) {\n        mode = htonl(m);\n    }\n    uint32_t getValue() const {\n        return ntohl(value);\n    }\n    void setValue(uint32_t v) {\n        value = htonl(v);\n    }\n    uint32_t getInjectError() const {\n        return ntohl(inject_error);\n    }\n    void setInjectError(uint32_t ie) {\n        inject_error = htonl(ie);\n    }\n\n    cb::const_byte_buffer getBuffer() const {\n        return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};\n    }\n\nprotected:\n    uint32_t mode = 0; // See EWB_Engine_Mode\n    uint32_t value = 0;\n    uint32_t inject_error = 0; // cb::engine_errc to inject.\n};\nstatic_assert(sizeof(EWB_Payload) == 12, \"Unepected struct size\");\n\n/**\n * Message format for PROTOCOL_BINARY_CMD_GET_ERRORMAP\n *\n * The payload (*not* specified as extras) contains a 2 byte payload\n * containing a 16 bit encoded version number. This version number should\n * indicate the highest version number of the error map the client is able\n * to understand. The server will return a JSON-formatted error map\n * which is formatted to either the version requested by the client, or\n * a lower version (thus, clients must be ready to parse lower version\n * formats).\n */\nclass GetErrmapPayload {\npublic:\n    uint16_t getVersion() const {\n        return ntohs(version);\n    }\n    void setVersion(uint16_t version) {\n        GetErrmapPayload::version = htons(version);\n    }\n\n    cb::const_byte_buffer getBuffer() const {\n        return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};\n    }\n\nprotected:\n    uint16_t version = 0;\n};\nstatic_assert(sizeof(GetErrmapPayload) == 2, \"Unexpected struct size\");\n#pragma pack()\n} // namespace cb::mcbp::request\n\n/**\n * Message format for PROTOCOL_BINARY_CMD_COLLECTIONS_SET_MANIFEST\n *\n * The body contains a JSON collections manifest.\n * No key and no extras\n */\ntypedef union {\n    struct {\n        protocol_binary_request_header header;\n    } message;\n    uint8_t bytes[sizeof(protocol_binary_request_header)];\n} protocol_binary_collections_set_manifest;\n\ntypedef protocol_binary_response_no_extras\n        protocol_binary_response_collections_set_manifest;\n\n/**\n * @}\n */\ninline protocol_binary_subdoc_flag operator|(protocol_binary_subdoc_flag a,\n                                             protocol_binary_subdoc_flag b) {\n    return protocol_binary_subdoc_flag(static_cast<uint8_t>(a) |\n                                       static_cast<uint8_t>(b));\n}\n\nnamespace mcbp::subdoc {\ninline constexpr mcbp::subdoc::doc_flag operator|(mcbp::subdoc::doc_flag a,\n                                                  mcbp::subdoc::doc_flag b) {\n    return mcbp::subdoc::doc_flag(static_cast<uint8_t>(a) |\n                                  static_cast<uint8_t>(b));\n}\n\ninline constexpr mcbp::subdoc::doc_flag operator&(mcbp::subdoc::doc_flag a,\n                                                  mcbp::subdoc::doc_flag b) {\n    return mcbp::subdoc::doc_flag(static_cast<uint8_t>(a) &\n                                  static_cast<uint8_t>(b));\n}\n\ninline constexpr mcbp::subdoc::doc_flag operator~(mcbp::subdoc::doc_flag a) {\n    return mcbp::subdoc::doc_flag(~static_cast<uint8_t>(a));\n}\n\ninline std::string to_string(mcbp::subdoc::doc_flag a) {\n    using mcbp::subdoc::doc_flag;\n    switch (a) {\n    case doc_flag::None:\n        return \"None\";\n    case doc_flag::Mkdoc:\n        return \"Mkdoc\";\n    case doc_flag::AccessDeleted:\n        return \"AccessDeleted\";\n    case doc_flag::Add:\n        return \"Add\";\n    case doc_flag::CreateAsDeleted:\n        return \"CreateAsDeleted\";\n    case doc_flag::ReviveDocument:\n        return \"ReviveDocument\";\n    }\n    return std::to_string(static_cast<uint8_t>(a));\n}\n\ninline bool hasAccessDeleted(mcbp::subdoc::doc_flag a) {\n    return (a & mcbp::subdoc::doc_flag::AccessDeleted) !=\n           mcbp::subdoc::doc_flag::None;\n}\n\ninline bool hasMkdoc(mcbp::subdoc::doc_flag a) {\n    return (a & mcbp::subdoc::doc_flag::Mkdoc) != mcbp::subdoc::doc_flag::None;\n}\n\ninline bool hasAdd(mcbp::subdoc::doc_flag a) {\n    return (a & mcbp::subdoc::doc_flag::Add) != mcbp::subdoc::doc_flag::None;\n}\n\ninline bool hasReviveDocument(mcbp::subdoc::doc_flag a) {\n    return (a & mcbp::subdoc::doc_flag::ReviveDocument) ==\n           mcbp::subdoc::doc_flag::ReviveDocument;\n}\n\ninline bool hasCreateAsDeleted(mcbp::subdoc::doc_flag a) {\n    return (a & mcbp::subdoc::doc_flag::CreateAsDeleted) !=\n           mcbp::subdoc::doc_flag::None;\n}\n\ninline bool isNone(mcbp::subdoc::doc_flag a) {\n    return a == mcbp::subdoc::doc_flag::None;\n}\ninline bool impliesMkdir_p(mcbp::subdoc::doc_flag a) {\n    return hasAdd(a) || hasMkdoc(a);\n}\n} // namespace mcbp::subdoc\n\nnamespace mcbp::cas {\n/**\n * The special value used as a wildcard and match all CAS values\n */\nconst uint64_t Wildcard = 0x0;\n} // namespace mcbp::cas\n\nnamespace cb::mcbp::request {\n#pragma pack(1)\n\n// Payload for get_collection_id opcode 0xbb, data stored in network byte order\nclass GetCollectionIDPayload {\npublic:\n    GetCollectionIDPayload() = default;\n    GetCollectionIDPayload(uint64_t manifestId, CollectionID collectionId)\n        : manifestId(htonll(manifestId)),\n          collectionId(htonl(uint32_t(collectionId))) {\n    }\n\n    CollectionID getCollectionId() const {\n        return ntohl(collectionId);\n    }\n\n    uint64_t getManifestId() const {\n        return ntohll(manifestId);\n    }\n\n    std::string_view getBuffer() const {\n        return {reinterpret_cast<const char*>(this), sizeof(*this)};\n    }\n\nprotected:\n    uint64_t manifestId{0};\n    uint32_t collectionId{0};\n};\n\n// Payload for get_scope_id opcode 0xbc, data stored in network byte order\nclass GetScopeIDPayload {\npublic:\n    GetScopeIDPayload() = default;\n    GetScopeIDPayload(uint64_t manifestId, ScopeID scopeId)\n        : manifestId(htonll(manifestId)), scopeId(htonl(uint32_t(scopeId))) {\n    }\n    ScopeID getScopeId() const {\n        return ntohl(scopeId);\n    }\n\n    uint64_t getManifestId() const {\n        return ntohll(manifestId);\n    }\n\n    std::string_view getBuffer() const {\n        return {reinterpret_cast<const char*>(this), sizeof(*this)};\n    }\n\nprotected:\n    uint64_t manifestId{0};\n    uint32_t scopeId{0};\n};\n\n// Payload for get_rando_key opcode 0xb6, data stored in network byte order\nclass GetRandomKeyPayload {\npublic:\n    GetRandomKeyPayload() = default;\n    explicit GetRandomKeyPayload(uint32_t collectionId)\n        : collectionId(htonl(collectionId)) {\n    }\n\n    CollectionID getCollectionId() const {\n        return ntohl(collectionId);\n    }\n\n    std::string_view getBuffer() const {\n        return {reinterpret_cast<const char*>(this), sizeof(*this)};\n    }\n\nprotected:\n    CollectionIDType collectionId{0};\n};\n#pragma pack()\n} // namespace cb::mcbp::request\n", "meta": {"hexsha": "2ef559e292ce7b52fb2668ef4ae2eedd927fa475", "size": 66262, "ext": "h", "lang": "C", "max_stars_repo_path": "include/memcached/protocol_binary.h", "max_stars_repo_name": "couchbase/kv_engine", "max_stars_repo_head_hexsha": "d9dd3f0be3700ef13cb59fa40e375b5ba73e5add", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": 104.0, "max_stars_repo_stars_event_min_datetime": "2017-05-22T20:41:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T00:18:34.000Z", "max_issues_repo_path": "include/memcached/protocol_binary.h", "max_issues_repo_name": "couchbase/kv_engine", "max_issues_repo_head_hexsha": "d9dd3f0be3700ef13cb59fa40e375b5ba73e5add", "max_issues_repo_licenses": ["MIT", "BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-11-14T08:12:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T11:14:17.000Z", "max_forks_repo_path": "include/memcached/protocol_binary.h", "max_forks_repo_name": "couchbase/kv_engine", "max_forks_repo_head_hexsha": "d9dd3f0be3700ef13cb59fa40e375b5ba73e5add", "max_forks_repo_licenses": ["MIT", "BSD-3-Clause"], "max_forks_count": 71.0, "max_forks_repo_forks_event_min_datetime": "2017-05-22T20:41:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T10:34:32.000Z", "avg_line_length": 29.4890965732, "max_line_length": 80, "alphanum_fraction": 0.6490447013, "num_tokens": 16550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15817434878009673, "lm_q2_score": 0.015189048975156444, "lm_q1q2_score": 0.002402517930234366}}
{"text": "\n#pragma once\n\n#include <functional>\n#include <vector>\n#include <map>\n\n#include <gsl/string_span>\n\nclass TabFileColumn {\n\tfriend class TabFileRecord;\npublic:\n\n\tbool IsEmpty() const {\n\t\treturn mValue.size() == 0;\n\t}\n\n\toperator bool() const {\n\t\treturn !IsEmpty();\n\t}\n\n\toperator gsl::cstring_span<>() const {\n\t\treturn mValue;\n\t}\n\n\tstd::string AsString() const {\n\t\treturn std::string(mValue.begin(), mValue.end());\n\t}\n\n\tbool EqualsIgnoreCase(const char *text) const {\n\t\treturn !_strnicmp(mValue.data(), text, mValue.size());\n\t}\n\n\tbool TryGetFloat(float &value) const {\n\t\tif (mValue.size() == 0) {\n\t\t\treturn false;\n\t\t}\n\t\treturn _snscanf_s(mValue.data(), mValue.size(), \"%f\", &value) == 1;\n\t}\n\n\ttemplate<typename T>\n\tbool TryGetEnum(const std::map<std::string, T> &mapping, T& value) {\n\t\tfor (auto it = mapping.begin(); it != mapping.end(); ++it) {\n\t\t\tif (!_strnicmp(it->first.c_str(), mValue.data(), mValue.size())) {\n\t\t\t\tvalue = it->second;\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\nprivate:\n\texplicit TabFileColumn(gsl::cstring_span<> value) : mValue(value) {\n\t}\n\tgsl::cstring_span<> mValue;\t\n};\n\nclass TabFileRecord {\nfriend class TabFile;\npublic:\n\tint GetLineNumber() const {\n\t\treturn mLineNumber;\n\t}\n\n\tsize_t GetColumnCount() const {\n\t\treturn mColumns.size();\n\t}\n\n\tTabFileColumn operator[](size_t i) const {\n\t\tif (i >= mColumns.size()) {\n\t\t\treturn TabFileColumn(mMissingColumn);\n\t\t}\n\t\treturn TabFileColumn(mColumns[i]);\n\t}\n\nprivate:\n\tstatic std::string mMissingColumn;\n\n\tint mLineNumber = 0;\n\tstd::vector<gsl::cstring_span<>> mColumns;\n};\n\nclass TabFile {\npublic:\n\t\n\ttypedef std::function<void(const TabFileRecord&)> Callback;\n\n\tstatic void ParseFile(\n\t\tconst std::string &filename,\n\t\tconst Callback &callback\n\t);\n\n\tstatic void ParseString(\n\t\tconst std::string &content,\n\t\tconst Callback &callback\n\t);\n\n};\n", "meta": {"hexsha": "eb9c09be62c5afcaf6d78c76a5ab4c6c8fcc014f", "size": 1810, "ext": "h", "lang": "C", "max_stars_repo_path": "Infrastructure/include/infrastructure/tabparser.h", "max_stars_repo_name": "edoipi/TemplePlus", "max_stars_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 69.0, "max_stars_repo_stars_event_min_datetime": "2015-05-05T14:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T06:13:04.000Z", "max_issues_repo_path": "Infrastructure/include/infrastructure/tabparser.h", "max_issues_repo_name": "edoipi/TemplePlus", "max_issues_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 457.0, "max_issues_repo_issues_event_min_datetime": "2015-05-01T22:07:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T02:19:10.000Z", "max_forks_repo_path": "Infrastructure/include/infrastructure/tabparser.h", "max_forks_repo_name": "edoipi/TemplePlus", "max_forks_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2016-02-04T21:19:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T23:14:51.000Z", "avg_line_length": 18.2828282828, "max_line_length": 69, "alphanum_fraction": 0.6718232044, "num_tokens": 489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08269734719655744, "lm_q2_score": 0.02887090370841958, "lm_q1q2_score": 0.0023875471478535517}}
{"text": "#pragma once\n\n#include <gsl.h>\n\n#include <mitkBaseData.h>\n\nnamespace crimson\n{\nclass QtPropertyStorage;\n\n/*! \\brief   A solver parameters data interface. */\nclass ISolverParametersData : public mitk::BaseData\n{\npublic:\n    mitkClassMacro(ISolverParametersData, BaseData);\n\n    /*!\n    * \\brief   Gets property storage for the SolverParametersData properties.\n    */\n    virtual gsl::not_null<QtPropertyStorage*> getPropertyStorage() = 0;\n\nprotected:\n    ISolverParametersData() { mitk::BaseData::InitializeTimeGeometry(1); }\n    virtual ~ISolverParametersData() {}\n\n    ISolverParametersData(const Self&) = default;\n\n    void SetRequestedRegion(const itk::DataObject*) override {}\n    void SetRequestedRegionToLargestPossibleRegion() override {}\n    bool RequestedRegionIsOutsideOfTheBufferedRegion() override { return true; }\n    bool VerifyRequestedRegion() override { return true; }\n};\n}\n", "meta": {"hexsha": "e0b6ff72e3cf5ce30aa4b90feebc123b892902f7", "size": 891, "ext": "h", "lang": "C", "max_stars_repo_path": "Modules/SolverSetupService/include/ISolverParametersData.h", "max_stars_repo_name": "carthurs/CRIMSONGUI", "max_stars_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-09-17T18:55:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T02:52:38.000Z", "max_issues_repo_path": "Modules/SolverSetupService/include/ISolverParametersData.h", "max_issues_repo_name": "carthurs/CRIMSONGUI", "max_issues_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Modules/SolverSetupService/include/ISolverParametersData.h", "max_forks_repo_name": "carthurs/CRIMSONGUI", "max_forks_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-05-19T09:02:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-26T17:39:57.000Z", "avg_line_length": 26.2058823529, "max_line_length": 80, "alphanum_fraction": 0.7407407407, "num_tokens": 204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.10230470789265304, "lm_q2_score": 0.023330766983429, "lm_q1q2_score": 0.002386847301151258}}
{"text": "/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */\n/*\n *     Copyright 2017 Couchbase, Inc.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n */\n\n#pragma once\n\n#include \"config.h\"\n\n#include <cJSON.h>\n#include <platform/socket.h>\n#include <gsl/gsl>\n\nclass NetworkInterface {\npublic:\n    /// Should a protocol be enabled, and if so how?\n    enum class Protocol {\n        Off, /// Do not enable protocol.\n        Optional, /// Protocol should be enabled, failure is non-fatal.\n        Required, /// Protocol must be enabled; failure is fatal.\n    };\n\n    NetworkInterface() = default;\n    explicit NetworkInterface(gsl::not_null<const cJSON*> json);\n\n    std::string host;\n    struct {\n        std::string key;\n        std::string cert;\n    } ssl;\n    int maxconn = 1000;\n    int backlog = 1024;\n    in_port_t port = 11211;\n    Protocol ipv6 = Protocol::Optional;\n    Protocol ipv4 = Protocol::Optional;\n    bool tcp_nodelay = true;\n    bool management = false;\n};\n\nstd::string to_string(const NetworkInterface::Protocol& proto);\n", "meta": {"hexsha": "05e0411383881b8282af0918397910182a445689", "size": 1583, "ext": "h", "lang": "C", "max_stars_repo_path": "daemon/network_interface.h", "max_stars_repo_name": "t3rm1n4l/kv_engine", "max_stars_repo_head_hexsha": "24d4546220f3181678d7eadedc68b4ea088d3538", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "daemon/network_interface.h", "max_issues_repo_name": "t3rm1n4l/kv_engine", "max_issues_repo_head_hexsha": "24d4546220f3181678d7eadedc68b4ea088d3538", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "daemon/network_interface.h", "max_forks_repo_name": "t3rm1n4l/kv_engine", "max_forks_repo_head_hexsha": "24d4546220f3181678d7eadedc68b4ea088d3538", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8679245283, "max_line_length": 79, "alphanum_fraction": 0.6689829438, "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08389039557214682, "lm_q2_score": 0.02843603345653338, "lm_q1q2_score": 0.002385510095171387}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef std_9154454e_8e1d_4505_9034_5c7a71b77dd0_h\r\n#define std_9154454e_8e1d_4505_9034_5c7a71b77dd0_h\r\n\r\n#include <xutility>\r\n#include <algorithm>\r\n#include <memory>\r\n#include <list>\r\n#include <vector>\r\n#include <deque>\r\n#include <queue>\r\n#include <map>\r\n#include <set>\r\n#include <stack>\r\n#include <unordered_map>\r\n#include <unordered_set>\r\n#include <comip.h>\r\n\r\n#include <gslib/type.h>\r\n#include <gslib/string.h>\r\n\r\n__gslib_begin__\r\n\r\nclass string;\r\n\r\n/* used for base type delegate */\r\ntemplate<class _inner>\r\nstruct base_delegator\r\n{\r\n    _inner          _puppet;\r\n\r\n    base_delegator() {}\r\n    base_delegator(const _inner& i): _puppet(i) {}\r\n    operator _inner() const { return _puppet; }\r\n    _inner& operator=(const _inner& i) { return _puppet = i; }\r\n};\r\n\r\ntemplate<class _inner>\r\nstruct base_ptr_delegator\r\n{\r\n    _inner*         _puppet;\r\n\r\n    base_ptr_delegator() { _puppet = 0; }\r\n    base_ptr_delegator(_inner* ptr) { _puppet = ptr; }\r\n    operator _inner*() { return _puppet; }\r\n    operator const _inner*() const { return _puppet; }\r\n    _inner* operator=(_inner* ptr) { return _puppet = ptr; }\r\n};\r\n\r\n#if defined(_MSC_VER) && (_MSC_VER < 1910)\r\n/* the same as the default std version */\r\ninline size_t hash_bytes(const byte str[], int size)\r\n{\r\n    size_t val = 2166136261U;\r\n    size_t first = 0;\r\n    size_t last = (size_t)size;\r\n    size_t stride = 1 + last / 10;\r\n    for( ; first < last; first += stride)\r\n        val = 16777619U * val ^ (size_t)str[first];\r\n    return val;\r\n}\r\n#elif defined(_MSC_VER) && (_MSC_VER < 1916)\r\ninline size_t hash_bytes(const byte str[], int size)\r\n{ return std::_Hash_bytes(str, size); }\r\n#else\r\ninline size_t hash_bytes(const byte str[], int size)\r\n{ return std::_Fnv1a_append_bytes(std::_FNV_offset_basis, str, size); }\r\n#endif\r\n\r\n#ifdef _UNICODE\r\ninline size_t string_hash(const string& str) { return hash_bytes((const byte*)str.c_str(), str.size() * sizeof(wchar)); }\r\n#else\r\ninline size_t string_hash(const string& str) { return hash_bytes((const byte*)str.c_str(), str.size()); }\r\n#endif\r\n\r\n#if defined(_MSC_VER) && (_MSC_VER <= 1600)\r\nclass hasher\r\n{\r\npublic:\r\n    hasher() { _val = 2166136261u; }\r\n    size_t add_bytes(const byte* str, int len)\r\n    {\r\n        size_t first = 0u;\r\n        size_t last = (size_t)len;\r\n        size_t stride = 1 + last / 10;\r\n        for(; first < last; first += stride)\r\n            _val = 16777619u * _val ^ (size_t)str[first];\r\n        return _val;\r\n    }\r\n    size_t get_value() const { return _val; }\r\n\r\nprivate:\r\n    size_t          _val;\r\n};\r\n#elif defined(_MSC_VER) && (_MSC_VER < 1916)\r\nclass hasher:\r\n    public std::_Fnv1a_hasher\r\n{\r\npublic:\r\n    size_t add_bytes(const byte* first, int len) { return _Add_bytes(first, first + len); }\r\n    size_t get_value() const { return _Val; }\r\n};\r\n#else\r\nclass hasher\r\n{\r\npublic:\r\n    hasher() { _val = std::_FNV_offset_basis; }\r\n    size_t add_bytes(const byte* first, int len) { return std::_Fnv1a_append_bytes(_val, first, len); }\r\n    size_t get_value() const { return _val; }\r\n\r\nprivate:\r\n    size_t          _val;\r\n};\r\n#endif\r\n\r\n/* switch to namespace tr1 and replace the hash for string */\r\n__gslib_end__\r\n\r\nnamespace std {\r\n\r\ntemplate<>\r\nclass hash<gs::string>\r\n#if defined(_MSC_VER) && (_MSC_VER < 1914)\r\n    : public unary_function<gs::string, size_t>\r\n#endif\r\n{\r\npublic:\r\n    size_t operator()(const gs::string& kval) const { return string_hash(kval); }\r\n};\r\n\r\n};\r\n__gslib_begin__\r\n\r\n/* wrappers for all kinds of vessels */\r\ntemplate<class _ty>\r\nusing list = std::list<_ty>;\r\ntemplate<class _ty>\r\nusing vector = std::vector<_ty>;\r\ntemplate<class _ty>\r\nusing queue = std::queue<_ty>;\r\ntemplate<class _ty>\r\nusing deque = std::deque<_ty>;\r\ntemplate<class _ty>\r\nusing stack = std::stack<_ty>;\r\n\r\ntemplate<class _kty, class _ty,\r\n    class _pr = std::less<_kty>\r\n    >\r\nusing map = std::map<_kty, _ty, _pr>;\r\ntemplate<class _ty, class _pr = std::less<_ty> >\r\nusing set = std::set<_ty, _pr>;\r\n\r\ntemplate<class _kty, class _ty,\r\n    class _pr = std::less<_kty>\r\n    >\r\nusing multimap = std::multimap<_kty, _ty, _pr>;\r\ntemplate<class _ty, class _pr = std::less<_ty> >\r\nusing multiset = std::multiset<_ty, _pr>;\r\n\r\ntemplate<class _kty, class _ty,\r\n    class _hs = std::hash<_kty>,\r\n    class _eq = std::equal_to<_kty>\r\n    >\r\nusing unordered_map = std::unordered_map<_kty, _ty, _hs, _eq>;\r\n\r\ntemplate<class _kty,\r\n    class _hs = std::hash<_kty>,\r\n    class _equ = std::equal_to<_kty>\r\n    >\r\nusing unordered_set = std::unordered_set<_kty, _hs, _equ>;\r\n\r\ntemplate<class _kty, class _ty,\r\n    class _hs = std::hash<_kty>\r\n    >\r\nusing unordered_multimap = std::unordered_multimap<_kty, _ty, _hs>;\r\n\r\ntemplate<class _kty, class _hs, class _equ>\r\nusing unordered_multiset = std::unordered_multiset<_kty, _hs, _equ>;\r\n\r\ntemplate<class _cls>\r\nclass com_ptr\r\n{\r\npublic:\r\n    typedef _cls* ptr_type;\r\n    typedef com_ptr<_cls> myref;\r\n\r\npublic:\r\n    com_ptr() { _ptr = nullptr; }\r\n    ~com_ptr()\r\n    {\r\n        if(_ptr) {\r\n            _ptr->Release();\r\n            _ptr = nullptr;\r\n        }\r\n    }\r\n    com_ptr(_cls* p)\r\n    {\r\n        _ptr = p;\r\n        if(_ptr)\r\n            _ptr->AddRef();\r\n    }\r\n    com_ptr(const myref& p)\r\n    {\r\n        _ptr = p.get();\r\n        if(_ptr)\r\n            _ptr->AddRef();\r\n    }\r\n    void attach(_cls* p)\r\n    {\r\n        if(_ptr)\r\n            _ptr->Release();\r\n        _ptr = p;\r\n    }\r\n    _cls* detach()\r\n    {\r\n        _cls* p = _ptr;\r\n        _ptr = nullptr;\r\n        return p;\r\n    }\r\n    void clear()\r\n    {\r\n        if(_ptr) {\r\n            _ptr->Release();\r\n            _ptr = nullptr;\r\n        }\r\n    }\r\n    _cls* operator=(_cls* p)\r\n    {\r\n        if(p) p->AddRef();\r\n        if(_ptr)\r\n            _ptr->Release();\r\n        return _ptr = p;\r\n    }\r\n    _cls* operator=(const myref& p)\r\n    {\r\n        if(p._ptr)\r\n            p._ptr->AddRef();\r\n        if(_ptr)\r\n            _ptr->Release();\r\n        return _ptr = p._ptr;\r\n    }\r\n    _cls** operator&()\r\n    {\r\n        assert(!_ptr);\r\n        return &_ptr;\r\n    }\r\n    _cls* get() const { return _ptr; }\r\n    _cls* operator->() const { return _ptr; }\r\n    bool operator!() const { return !_ptr; }\r\n    bool operator == (_cls* p) const { return _ptr == p; }\r\n    bool operator != (_cls* p) const { return _ptr != p; }\r\n\r\nprivate:\r\n    _cls*           _ptr;\r\n};\r\n\r\n__gslib_end__\r\n\r\n#endif", "meta": {"hexsha": "d08cd2747c4c780759d186c246adce11b06c8e9d", "size": 7586, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gslib/std.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/gslib/std.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gslib/std.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 26.6175438596, "max_line_length": 122, "alphanum_fraction": 0.6189032428, "num_tokens": 2089, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.0618759926434262, "lm_q2_score": 0.03846619036489695, "lm_q1q2_score": 0.0023801337120389955}}
{"text": "#pragma once\n#include \"ui/detail/nki_image.h\"\n#include \"ui/detail/nk_essential.h\"\n#include <gsl/gsl>\n#include <nuklear.h>\n\nnamespace cws80 {\n\nclass UIController;\nstruct FontRequest;\n\nenum class GraphicsType {\n    Other,\n    OpenGL,\n    Cairo,\n    Gdiplus,\n};\n\n//\nclass GraphicsDevice {\npublic:\n    explicit GraphicsDevice(UIController &ctl)\n        : ctl_(ctl)\n    {\n    }\n    virtual ~GraphicsDevice() {}\n\n    virtual GraphicsType type() const = 0;\n\n    virtual void setup_context() {}\n    virtual void initialize(gsl::span<const FontRequest> fontreqs) = 0;\n    virtual void cleanup() = 0;\n\n    im_texture load_texture(const im_image &img);\n    virtual im_texture load_texture(const u8 *data, uint w, uint h, uint channels) = 0;\n    virtual void unload_texture(nk_handle handle) = 0;\n\n    virtual void render(void *draw_context) = 0;\n\n    virtual nk_user_font *get_font(uint id) = 0;\n\nprotected:\n    UIController &ctl_;\n};\n\n//------------------------------------------------------------------------------\nstruct FontRequest {\n    static FontRequest Default(f32 height, const nk_rune *range);\n    static FontRequest File(f32 height, const char *path, const nk_rune *range);\n    static FontRequest Memory(f32 height, const void *data, size_t size, const nk_rune *range);\n\n    enum class Type { Default, File, Memory } type;\n    f32 height;\n    const nk_rune *range;\n\n    union {\n        struct {\n            const char *path;\n        } file;\n        struct {\n            const void *data;\n            size_t size;\n        } memory;\n    } un;\n};\n\ninline auto FontRequest::Default(f32 height, const nk_rune *range) -> FontRequest\n{\n    FontRequest req;\n    req.type = FontRequest::Type::Default;\n    req.height = height;\n    req.range = range;\n    return req;\n}\n\ninline auto FontRequest::File(f32 height, const char *path, const nk_rune *range) -> FontRequest\n{\n    FontRequest req;\n    req.type = FontRequest::Type::File;\n    req.height = height;\n    req.range = range;\n    req.un.file.path = path;\n    return req;\n}\n\ninline auto FontRequest::Memory(f32 height, const void *data, size_t size, const nk_rune *range) -> FontRequest\n{\n    FontRequest req;\n    req.type = FontRequest::Type::Memory;\n    req.height = height;\n    req.range = range;\n    req.un.memory.data = data;\n    req.un.memory.size = size;\n    return req;\n}\n\n}  // namespace cws80\n", "meta": {"hexsha": "230b50aa5efb5312ce78517ccbaba0d945e50ca8", "size": 2344, "ext": "h", "lang": "C", "max_stars_repo_path": "sources/ui/detail/device/dev_graphics.h", "max_stars_repo_name": "jpcima/cws80", "max_stars_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-05-20T19:27:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-03T04:21:53.000Z", "max_issues_repo_path": "sources/ui/detail/device/dev_graphics.h", "max_issues_repo_name": "jpcima/cws80", "max_issues_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-05-21T12:56:22.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-23T21:33:33.000Z", "max_forks_repo_path": "sources/ui/detail/device/dev_graphics.h", "max_forks_repo_name": "jpcima/cws80", "max_forks_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9183673469, "max_line_length": 111, "alphanum_fraction": 0.6352389078, "num_tokens": 579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08151976490042974, "lm_q2_score": 0.02887090527513001, "lm_q1q2_score": 0.0023535494104911753}}
{"text": "#pragma once\n#include \"halley/plugin/iasset_importer.h\"\n#include <gsl/gsl>\n#include \"halley/file_formats/config_file.h\"\n#include <yaml-cpp/node/node.h>\n\nnamespace Halley\n{\n\tclass ConfigFile;\n\n\tclass ConfigImporter : public IAssetImporter\n\t{\n\tpublic:\n\t\tImportAssetType getType() const override { return ImportAssetType::Config; }\n\n\t\tvoid import(const ImportingAsset& asset, IAssetCollector& collector) override;\n\n\t\tstatic ConfigNode parseYAMLNode(const YAML::Node& node);\n\t\tstatic void parseConfig(ConfigFile& config, gsl::span<const gsl::byte> data);\n\t};\n}\n", "meta": {"hexsha": "49ff2dc35c4219fb706b754e2d4fcb5309100912", "size": 557, "ext": "h", "lang": "C", "max_stars_repo_path": "src/tools/tools/src/assets/importers/config_importer.h", "max_stars_repo_name": "sunhay/halley", "max_stars_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T20:23:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T20:23:45.000Z", "max_issues_repo_path": "src/tools/tools/src/assets/importers/config_importer.h", "max_issues_repo_name": "sunhay/halley", "max_issues_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tools/tools/src/assets/importers/config_importer.h", "max_forks_repo_name": "sunhay/halley", "max_forks_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3181818182, "max_line_length": 80, "alphanum_fraction": 0.7666068223, "num_tokens": 136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.0826973381535205, "lm_q2_score": 0.028436030368928136, "lm_q1q2_score": 0.0023515840191630282}}
{"text": "#pragma once\n\n#include <gsl\\gsl>\n#include <winrt\\base.h>\n#include <d3d11.h>\n#include <DirectXTK\\SpriteBatch.h>\n#include \"DrawableGameComponent.h\"\n#include \"HeightmapTessellationMaterial.h\"\n#include \"RenderStateHelper.h\"\n\nnamespace Rendering\n{\n\tclass HeightmapTessellationDemo final : public Library::DrawableGameComponent\n\t{\n\tpublic:\n\t\tHeightmapTessellationDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera);\n\t\tHeightmapTessellationDemo(const HeightmapTessellationDemo&) = delete;\n\t\tHeightmapTessellationDemo(HeightmapTessellationDemo&&) = default;\n\t\tHeightmapTessellationDemo& operator=(const HeightmapTessellationDemo&) = default;\t\t\n\t\tHeightmapTessellationDemo& operator=(HeightmapTessellationDemo&&) = default;\n\t\t~HeightmapTessellationDemo();\n\n\t\tbool AnimationEnabled() const;\n\t\tvoid SetAnimationEnabled(bool enabled);\n\n\t\tgsl::span<const float> EdgeFactors() const;\n\t\tgsl::span<const float> InsideFactors() const;\n\t\tvoid SetUniformFactors(float factor);\n\n\t\tfloat DisplacementScale() const;\n\t\tvoid SetDisplacementScale(float displacementScale);\n\n\t\tvirtual void Initialize() override;\n\t\tvirtual void Update(const Library::GameTime& gameTime) override;\n\t\tvirtual void Draw(const Library::GameTime& gameTime) override;\n\n\tprivate:\n\t\tinline static const RECT HeightmapDestinationRectangle = { 0, 512, 256, 768 };\n\n\t\tLibrary::RenderStateHelper mRenderStateHelper;\n\t\tHeightmapTessellationMaterial mMaterial;\n\t\twinrt::com_ptr<ID3D11Buffer> mVertexBuffer;\n\t\tbool mUpdateMaterial{ true };\n\t\tstd::unique_ptr<DirectX::SpriteBatch> mSpriteBatch;\n\t\tstd::shared_ptr<Library::Texture2D> mHeightmap;\n\t\tbool mAnimationEnabled{ false };\n\t};\n}", "meta": {"hexsha": "50b3ab8a1d63e243b2506fc29d01f490e0647c2d", "size": 1648, "ext": "h", "lang": "C", "max_stars_repo_path": "source/10.3_Heightmap_Tessellation/HeightmapTessellationDemo.h", "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/10.3_Heightmap_Tessellation/HeightmapTessellationDemo.h", "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/10.3_Heightmap_Tessellation/HeightmapTessellationDemo.h", "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3333333333, "max_line_length": 97, "alphanum_fraction": 0.7888349515, "num_tokens": 421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1778108607641985, "lm_q2_score": 0.013222819370537438, "lm_q1q2_score": 0.002351160894004779}}
{"text": "#pragma once\n\n#include \"gl_helpers.h\"\n#include \"GL_Loader.h\"\n#include \"MappedGL.h\"\n#include \"Range.h\"\n\n#include <handy/Guard.h>\n\n#include <gsl/span>\n\n#include <type_traits>\n#include <vector>\n\n\nnamespace ad {\nnamespace graphics {\n\n\nstruct [[nodiscard]] VertexArrayObject : public ResourceGuard<GLuint>\n{\n    /// \\note Deleting a bound VAO reverts the binding to zero\n    VertexArrayObject() :\n        ResourceGuard<GLuint>{reserve(glGenVertexArrays),\n                              [](GLuint aIndex){glDeleteVertexArrays(1, &aIndex);}}\n    {}\n};\n\n\ninline void bind(const VertexArrayObject & aVertexArray)\n{\n    glBindVertexArray(aVertexArray);\n}\n\n// TODO Ad 2022/02/02: Is it a good idea to \"expect\" the object to unbind\n// when the underlying unbinding mechanism does not use it (just reset a default)? \ninline void unbind(const VertexArrayObject & aVertexArray)\n{\n    glBindVertexArray(0);\n}\n\n\n/// \\TODO understand when glDisableVertexAttribArray should actually be called\n///       (likely not specially before destruction, but more when rendering other objects\n///        since it is a current(i.e. global) VAO state)\n/// \\Note Well note even that: Activated vertex attribute array are per VAO, so changing VAO\n///       Already correctly handles that.\nstruct [[nodiscard]] VertexBufferObject : public ResourceGuard<GLuint>\n{\n    VertexBufferObject() :\n        ResourceGuard<GLuint>{reserve(glGenBuffers),\n                              [](GLuint aIndex){glDeleteBuffers(1, &aIndex);}}\n    {}\n};\n\n\ninline void bind(const VertexBufferObject & aVertexBuffer)\n{\n    glBindBuffer(GL_ARRAY_BUFFER, aVertexBuffer);\n}\n\ninline void unbind(const VertexBufferObject &)\n{\n    glBindBuffer(GL_ARRAY_BUFFER, 0);\n}\n\n\nstruct [[nodiscard]] IndexBufferObject : public ResourceGuard<GLuint>\n{\n    IndexBufferObject() :\n        ResourceGuard<GLuint>{reserve(glGenBuffers),\n                              [](GLuint aIndex){glDeleteBuffers(1, &aIndex);}}\n    {}\n};\n\n\ninline void bind(const IndexBufferObject & aIndexBuffer)\n{\n    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, aIndexBuffer);\n}\n\ninline void unbind(const IndexBufferObject &)\n{\n    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);\n}\n\n\n/// \\brief A VertexArray with a vector of VertexBuffers\nstruct [[nodiscard]] VertexSpecification\n{\n    VertexSpecification(VertexArrayObject aVertexArray={},\n                        std::vector<VertexBufferObject> aVertexBuffers={}) :\n        mVertexArray{std::move(aVertexArray)},\n        mVertexBuffers{std::move(aVertexBuffers)}\n    {}\n\n    VertexArrayObject mVertexArray;\n    std::vector<VertexBufferObject> mVertexBuffers;\n};\n\n\ninline void bind(const VertexSpecification & aVertexSpecification)\n{\n    bind(aVertexSpecification.mVertexArray);\n}\n\n\ninline void unbind(const VertexSpecification & aVertexSpecification)\n{\n    unbind(aVertexSpecification.mVertexArray);\n}\n\n\n\n/// \\brief Describes the attribute access from the shader (layout id, value type, normalization)\nstruct Attribute\n{\n    enum class Access\n    {\n        Float,\n        Integer,\n    };\n\n    constexpr Attribute(GLuint aValue) :\n        mIndex(aValue)\n    {}\n\n    constexpr Attribute(GLuint aValue, Access aAccess, bool aNormalize=false) :\n        mIndex(aValue),\n        mTypeInShader(aAccess),\n        mNormalize(aNormalize)\n    {}\n\n    GLuint mIndex; // index to match in vertex shader.\n    Access mTypeInShader{Access::Float}; // destination data type\n    bool mNormalize{false}; // if destination is float and source is integral, should it be normalized (value/type_max_value)\n};\n\n/// \\brief The complete description of an attribute expected by OpenGL\nstruct AttributeDescription : public Attribute\n{\n    GLuint mDimension;  // from 1 to 4 (explicit distinct attributes must be used for matrix data)\n    size_t mOffset;     // offset for the attribute within the vertex data structure (interleaved)\n    GLenum mDataType;   // attribute source data type\n};\n\nstd::ostream & operator<<(std::ostream &aOut, const AttributeDescription & aDescription);\n\ntypedef std::initializer_list<AttributeDescription> AttributeDescriptionList;\n\n\n/***\n *\n * Vertex Buffer\n *\n ***/\n\n/// \\brief Attach an existing VertexBuffer to an exisiting VertexArray,\n/// without providing initial data.\nvoid attachVertexBuffer(const VertexBufferObject & aVertexBuffer,\n                        const VertexArrayObject & aVertexArray,\n                        AttributeDescriptionList aAttributes,\n                        GLsizei aStride,\n                        GLuint aAttributeDivisor = 0);\n\n/// \\brief This overload deduces the stride from T_vertex.\ntemplate <class T_vertex>\nvoid attachVertexBuffer(const VertexBufferObject & aVertexBuffer,\n                        const VertexArrayObject & aVertexArray,\n                        AttributeDescriptionList aAttributes,\n                        GLuint aAttributeDivisor = 0)\n{\n    return attachVertexBuffer(aVertexBuffer, aVertexArray, aAttributes, sizeof(T_vertex), aAttributeDivisor);\n}\n\n/// \\brief Intialize a VertexBufferObject, without providing initial data.\n///\n/// This is an extension of `attachVertexBuffer()`, which constructs the vertex buffer it attaches,\n/// instead of expecting it as argument.\nVertexBufferObject initVertexBuffer(const VertexArrayObject & aVertexArray,\n                                    AttributeDescriptionList aAttributes,\n                                    GLsizei aStride,\n                                    GLuint aAttributeDivisor = 0);\n\n\n/// \\brief This overload deduces the stride from T_vertex.\ntemplate <class T_vertex>\nVertexBufferObject initVertexBuffer(const VertexArrayObject & aVertexArray,\n                                    AttributeDescriptionList aAttributes,\n                                    GLuint aAttributeDivisor = 0)\n{\n    return initVertexBuffer(aVertexArray, aAttributes, sizeof(T_vertex), aAttributeDivisor);\n}\n\n/// \\brief Create a VertexBufferObject with provided attributes, load it with data,\n/// and associate the data to attributes of `aVertexArray`.\n///\n/// This is an extension of `initVertexBuffer()`, which loads data into the initialized vertex buffer.\n///\n/// \\param aAttribute describes the associaiton.\n///\n/// \\note This is the lowest level overload, with explicit attribute description and raw data pointer.\n/// Other overloads end-up calling it.\nVertexBufferObject loadVertexBuffer(const VertexArrayObject & aVertexArray,\n                                    AttributeDescriptionList aAttributes,\n                                    GLsizei aStride,\n                                    size_t aSize,\n                                    const GLvoid * aData,\n                                    GLuint aAttributeDivisor = 0);\n\n\n/// \\brief This overload deduces the stride and size from T_vertex,\n/// which could itself be deduced from the provided span.\ntemplate <class T_vertex>\nVertexBufferObject loadVertexBuffer(const VertexArrayObject & aVertexArray,\n                                    const AttributeDescriptionList & aAttributes,\n                                    const gsl::span<T_vertex> aVertices,\n                                    GLuint aAttributeDivisor = 0)\n{\n    return loadVertexBuffer(aVertexArray,\n                            aAttributes,\n                            sizeof(T_vertex),\n                            aVertices.size_bytes(),\n                            aVertices.data(),\n                            aAttributeDivisor);\n}\n\n\n/// \\brief Create a VertexBufferObject and load it with provided data.\n/// But do **not** attach it to a VertexArrayObject / do **not** associate the vertex data to attributes.\n///\n/// \\note Attachment to a VertexArrayObject as well as attributes association might be done later with\n/// `attachVertexBuffer()`.\ntemplate <class T_vertex>\nVertexBufferObject loadUnattachedVertexBuffer(gsl::span<const T_vertex> aVertices,\n                                              GLenum aHint = GL_STATIC_DRAW)\n{\n    VertexBufferObject vbo;\n    glBindBuffer(GL_ARRAY_BUFFER, vbo);\n    glBufferData(GL_ARRAY_BUFFER, aVertices.size_bytes(), aVertices.data(), aHint);\n    return vbo;\n}\n\n\n/// \\brief High-level function directly appending a loaded VertexBuffer to a VertexSpecification.\n///\n/// This is an extension to `loadVertexBuffer()`, which appends the loaded vertex buffer to `aSpecification`.\ntemplate <class T_vertex>\nvoid appendToVertexSpecification(VertexSpecification & aSpecification,\n                                 const AttributeDescriptionList & aAttributes,\n                                 const gsl::span<T_vertex> aVertices,\n                                 GLuint aAttributeDivisor = 0)\n{\n    aSpecification.mVertexBuffers.push_back(\n            loadVertexBuffer(aSpecification.mVertexArray,\n                             aAttributes,\n                             std::move(aVertices),\n                             aAttributeDivisor));\n}\n\n\n/***\n *\n * Index Buffer\n *\n ***/\n\n/// \\brief Attach an existing IndexBuffer to an exisiting VertexArray,\n/// without providing initial data.\ninline void attachIndexBuffer(const IndexBufferObject & aIndexBuffer,\n                              const VertexArrayObject & aVertexArray)\n{\n    glBindVertexArray(aVertexArray);\n    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, aIndexBuffer);\n}\n\n\n/// \\brief Intialize and attach an IndexBufferObject, without providing initial data.\n///\n/// This is an extension of `attachIndexBuffer()`, which constructs the index buffer it attaches,\n/// instead of expecting it as argument.\ninline IndexBufferObject initIndexBuffer(const VertexArrayObject & aVertexArray)\n{\n    IndexBufferObject ibo;\n    attachIndexBuffer(ibo, aVertexArray);\n    return ibo;\n}\n\n\n/// \\brief Initialize, attach and load data into an IndexBufferObject.\n///\n/// This is an extension of `initIndexBuffer()`, which loads data into the initialized vertex buffer.\ntemplate <class T_index>\nIndexBufferObject loadIndexBuffer(const VertexArrayObject & aVertexArray,\n                                  const gsl::span<T_index> aIndices,\n                                  const BufferHint aHint)\n{\n    IndexBufferObject ibo = initIndexBuffer(aVertexArray);\n    glBufferData(GL_ELEMENT_ARRAY_BUFFER, aIndices.size_bytes(), aIndices.data(), getGLBufferHint(aHint));\n    return ibo;\n}\n\n\n/***\n * Buffer re-specification\n *\n * see: https://www.khronos.org/opengl/wiki/Buffer_Object_Streaming#Buffer_re-specification\n ***/\n\n/// \\brief Respecify content of a vertex buffer.\ninline void respecifyBuffer(const VertexBufferObject & aVBO, const GLvoid * aData, GLsizei aSize)\n{\n    glBindBuffer(GL_ARRAY_BUFFER, aVBO);\n\n    // Orphan the previous buffer\n    glBufferData(GL_ARRAY_BUFFER, aSize, NULL, GL_STATIC_DRAW);\n\n    // Copy value to new buffer\n    glBufferSubData(GL_ARRAY_BUFFER, 0, aSize, aData);\n}\n\n\n/// \\brief Respecify content of an index buffer.\ninline void respecifyBuffer(const IndexBufferObject & aIBO, const GLvoid * aData, GLsizei aSize)\n{\n    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, aIBO);\n\n    // Orphan the previous buffer\n    glBufferData(GL_ELEMENT_ARRAY_BUFFER, aSize, NULL, GL_STATIC_DRAW);\n\n    // Copy value to new buffer\n    glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, aSize, aData);\n}\n\n\n/// \\brief Overload accepting a span of generic values, instead of low-level void pointer.\n/// It works with both vertex and index buffers.\ntemplate <class T_values, class T_buffer>\nvoid respecifyBuffer(const T_buffer & aBufferObject, const gsl::span<T_values> aValues)\n{\n    respecifyBuffer(aBufferObject,\n                    aValues.data(),\n                    static_cast<GLsizei>(aValues.size_bytes()));\n}\n\n\n/// \\brief Respecify a vertex buffer with the exactly same size (allowing potential optimizations).\n///\n/// \\attention This is undefined behaviour is aData does not point to at least the same amount\n/// of data that was present before in the re-specified vertex buffer.\ninline void respecifyBufferSameSize(const VertexBufferObject & aVBO, const GLvoid * aData)\n{\n    GLint size;\n    glGetBufferParameteriv(GL_ARRAY_BUFFER, GL_BUFFER_SIZE, &size);\n\n    respecifyBuffer(aVBO, aData, size);\n}\n\n\n} // namespace graphics\n} // namespace ad\n", "meta": {"hexsha": "9600657d0ee6899ec9f923fed1d37ade2df50556", "size": 12078, "ext": "h", "lang": "C", "max_stars_repo_path": "src/lib/renderer/renderer/VertexSpecification.h", "max_stars_repo_name": "Adnn/Graphics", "max_stars_repo_head_hexsha": "335d54bdbb5d8d6042c9adfb9e47ccb14f612cf8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lib/renderer/renderer/VertexSpecification.h", "max_issues_repo_name": "Adnn/Graphics", "max_issues_repo_head_hexsha": "335d54bdbb5d8d6042c9adfb9e47ccb14f612cf8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lib/renderer/renderer/VertexSpecification.h", "max_forks_repo_name": "Adnn/Graphics", "max_forks_repo_head_hexsha": "335d54bdbb5d8d6042c9adfb9e47ccb14f612cf8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.364640884, "max_line_length": 125, "alphanum_fraction": 0.6794999172, "num_tokens": 2432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10230471062965231, "lm_q2_score": 0.022977370077286754, "lm_q1q2_score": 0.002350693196787253}}
{"text": "#pragma once\n\n#include <optional>\n\n#include <gsl/span>\n\n#include \"Ds4InputData.h\"\n\n/**\n * \\brief Serialized input report from a \\c Ds4Device\n * \\sa Ds4Device\n */\nclass Ds4Input\n{\npublic:\n\tDs4Input() = default;\n\t\n\t/**\n\t * \\brief Indicates if button press state has changed since the last poll.\n\t */\n\tbool buttonsChanged = false; // TODO: private set\n\n\t/**\n\t * \\brief Indicates if touch state has changed since last poll.\n\t */\n\tbool touchChanged = false; // TODO: private set\n\n\t/**\n\t * \\brief Buttons currently held.\n\t * \\sa Ds4Buttons, Ds4Buttons_t\n\t */\n\tDs4Buttons_t heldButtons = 0; // TODO: private set\n\n\t/**\n\t * \\brief Buttons pressed since last poll.\n\t * \\sa Ds4Buttons, Ds4Buttons_t\n\t */\n\tDs4Buttons_t pressedButtons = 0; // TODO: private set\n\n\t/**\n\t * \\brief Buttons released since last poll.\n\t * \\sa Ds4Buttons, Ds4Buttons_t\n\t */\n\tDs4Buttons_t releasedButtons = 0; // TODO: private set\n\n\t/**\n\t * \\brief Each axis that has changed since the last poll.\n\t * \\sa Ds4Axes, Ds4Axes_t\n\t */\n\tDs4Axes_t axes = 0; // TODO: private set\n\n\tDs4InputData data {};\n\n\t/**\n\t * \\brief Updates serialized data using the given buffer.\n\t * \\param buffer Buffer containing raw input report data.\n\t */\n\tvoid update(const gsl::span<uint8_t>& buffer);\n\n\t/**\n\t * \\brief Updates button change states since last poll.\n\t */\n\tvoid updateChangedState();\n\n\t/**\n\t * \\brief Get the magnitude of an axis.\n\t * \\param axis The axis to retrieve.\n\t * \\param polarity The desired polarity of the axis, or \\c std::nullopt for both positive and negative.\n\t * \\return The magnitude of the axis. If it does not align with the desired \\a polarity, \\c 0.0f is returned.\n\t */\n\t[[nodiscard]] float getAxis(Ds4Axes_t axis, const std::optional<AxisPolarity>& polarity) const;\n\nprivate:\n\tDs4Buttons_t lastHeldButtons = 0;\n\tuint8_t lastTouchFrame {};\n\n\tvoid addButton(bool pressed, Ds4Buttons_t buttons);\n\tvoid updateButtons();\n\tvoid updateAxes(const Ds4InputData& last);\n};\n", "meta": {"hexsha": "a61aeddaf0e4320817cd7f46fb7aca627788b318", "size": 1929, "ext": "h", "lang": "C", "max_stars_repo_path": "ds4wizard-cpp/Ds4Input.h", "max_stars_repo_name": "SonicFreak94/ds4wizard", "max_stars_repo_head_hexsha": "4d2ddc15b7db7cc5618c8676c91cf81614921c3c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T19:23:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-13T08:35:31.000Z", "max_issues_repo_path": "ds4wizard-cpp/Ds4Input.h", "max_issues_repo_name": "SonicFreak94/ds4wizard", "max_issues_repo_head_hexsha": "4d2ddc15b7db7cc5618c8676c91cf81614921c3c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-01-29T20:34:26.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-30T04:00:38.000Z", "max_forks_repo_path": "ds4wizard-cpp/Ds4Input.h", "max_forks_repo_name": "SonicFreak94/ds4wizard", "max_forks_repo_head_hexsha": "4d2ddc15b7db7cc5618c8676c91cf81614921c3c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8148148148, "max_line_length": 110, "alphanum_fraction": 0.6951788491, "num_tokens": 540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12421300835205339, "lm_q2_score": 0.018833128926708808, "lm_q1q2_score": 0.0023393196006685794}}
{"text": "/* $Id$   */\n/*--------------------------------------------------------------------*/\n/*;  Copyright (C) 2003-2018                                          */\n/*;  Associated Universities, Inc. Washington DC, USA.                */\n/*;                                                                   */\n/*;  This program is free software; you can redistribute it and/or    */\n/*;  modify it under the terms of the GNU General Public License as   */\n/*;  published by the Free Software Foundation; either version 2 of   */\n/*;  the License, or (at your option) any later version.              */\n/*;                                                                   */\n/*;  This program is distributed in the hope that it will be useful,  */\n/*;  but WITHOUT ANY WARRANTY; without even the implied warranty of   */\n/*;  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the    */\n/*;  GNU General Public License for more details.                     */\n/*;                                                                   */\n/*;  You should have received a copy of the GNU General Public        */\n/*;  License along with this program; if not, write to the Free       */\n/*;  Software Foundation, Inc., 675 Massachusetts Ave, Cambridge,     */\n/*;  MA 02139, USA.                                                   */\n/*;                                                                   */\n/*;Correspondence about this software should be addressed as follows: */\n/*;         Internet email: bcotton@nrao.edu.                         */\n/*;         Postal address: William Cotton                            */\n/*;                         National Radio Astronomy Observatory      */\n/*;                         520 Edgemont Road                         */\n/*;                         Charlottesville, VA 22903-2475 USA        */\n/*--------------------------------------------------------------------*/\n#ifndef OBITFARRAY_H \n#define OBITFARRAY_H \n\n#include \"Obit.h\"\n#include \"ObitErr.h\"\n#include \"ObitInfoList.h\"\n#include \"ObitThread.h\"\n#if HAVE_GSL==1  /* GSL stuff */\n#include <gsl/gsl_randist.h>\n#endif /* HAVE_GSL */\n\n/*-------- Obit: Merx mollis mortibus nuper ------------------*/\n/**\n * \\file ObitFArray.h\n * ObitFArray numeric array class definition.\n *\n * This class is derived from the #Obit class.\n * Related functions are in the \n * \\link ObitFArrayUtil.h ObitFArrayUtil \n * \\endlink module.\n *\n * This class is for creating and manipulating a Array as a memory resident \n * multidimensional rectangular array of floats.\n * Elements are stored in order of the increasing axis order (the reverse of the\n * usual c definition).\n * Except as noted, magic value blanking is supported (OBIT_MAGIC).\n * \n * \\section ObitFArrayaccess Creators and Destructors\n * An ObitFArray will usually be created using ObitFArrayCreate which allows \n * specifying a name for the object as well as dimensionality of the array.\n *\n * A copy of a pointer to an ObitFArray should always be made using the\n * #ObitFArrayRef function which updates the reference count in the object.\n * Then whenever freeing an ObitFArray or changing a pointer, the function\n * #ObitFArrayUnref will decrement the reference count and destroy the object\n * when the reference count hits 0.\n * There is no explicit destructor.\n */\n\n/*--------------Class definitions-------------------------------------*/\n/** ObitFArray Class structure. */\ntypedef struct {\n#include \"ObitFArrayDef.h\"   /* this class definition */\n} ObitFArray;\n\n/*----------------- Macroes ---------------------------*/\n/** \n * Macro to unreference (and possibly destroy) an ObitFArray\n * returns a ObitFArray*.\n * in = object to unreference\n */\n#define ObitFArrayUnref(in) ObitUnref (in)\n\n/** \n * Macro to reference (update reference count) an ObitFArray.\n * returns a ObitFArray*.\n * in = object to reference\n */\n#define ObitFArrayRef(in) ObitRef (in)\n\n/** \n * Macro to determine if an object is the member of this or a \n * derived class.\n * Returns TRUE if a member, else FALSE\n * in = object to reference\n */\n#define ObitFArrayIsA(in) ObitIsA (in, ObitFArrayGetClass())\n\n/** Maximum ObitFArray number of dimensions */\n#ifndef MAXFARRAYDIM\n#define MAXFARRAYDIM 10\n#endif\n\n/*---------------Public functions---------------------------*/\n/** Public: Class initializer. */\nvoid ObitFArrayClassInit (void);\n\n/** Public: Default Constructor. */\nObitFArray* newObitFArray (gchar* name);\n\n/** Public: Create/initialize ObitFArray structures */\nObitFArray* ObitFArrayCreate (gchar* name, olong ndim, olong *naxis);\n/** Typedef for definition of class pointer structure */\ntypedef void (*ObitFArrayCreateFP) (gchar* name, olong ndim, olong *naxis);\n\n/** Public: ClassInfo pointer */\ngconstpointer ObitFArrayGetClass (void);\n\n/** Public: Copy (deep) constructor. */\nObitFArray* ObitFArrayCopy  (ObitFArray *in, ObitFArray *out, ObitErr *err);\n\n/** Public: Copy structure. */\nvoid ObitFArrayClone (ObitFArray *in, ObitFArray *out, ObitErr *err);\n\n/** Public: Copy Subarray constructor. */\nObitFArray* ObitFArraySubArr  (ObitFArray *in, olong *blc, olong *trc, \n\t\t\t       ObitErr *err);\ntypedef ObitFArray* (*ObitFArraySubArrFP) (ObitFArray *in, olong *blc, olong *trc, \n\t\t\t\t\t   ObitErr *err);\n\n/** Public: Transpose constructor. */\nObitFArray* ObitFArrayTranspose  (ObitFArray *in, olong *order, ObitErr *err);\ntypedef ObitFArray* (*ObitFArrayTransposeFP) (ObitFArray *in, olong *order, \n\t\t\t\t\t      ObitErr *err);\n\n/** Public: Are two FArrays of compatable geometry. */\ngboolean ObitFArrayIsCompatable  (ObitFArray *in1, ObitFArray *in2);\ntypedef gboolean (*ObitFArrayIsCompatableFP) (ObitFArray *in1, ObitFArray *in2);\n\n/** Public: Reallocate/initialize ObitFArray structures */\nObitFArray* ObitFArrayRealloc (ObitFArray* in, olong ndim, olong *naxis);\ntypedef void (*ObitFArrayReallocFP) (ObitFArray* in, olong ndim, olong *naxis);\n\n/** Public: return pointer to a specified element */\nofloat* ObitFArrayIndex (ObitFArray* in, olong *pos);\ntypedef ofloat* (*ObitFArrayIndexFP) (ObitFArray* in, olong *pos);\n\n/** Public: Find Maximum value in an ObitFArray */\nofloat ObitFArrayMax (ObitFArray* in, olong *pos);\ntypedef ofloat (*ObitFArrayMaxFP) (ObitFArray* in, olong *pos);\n\n/** Public: Find Maximum abs value in an ObitFArray */\nofloat ObitFArrayMaxAbs (ObitFArray* in, olong *pos);\ntypedef ofloat (*ObitFArrayMaxAbsFP) (ObitFArray* in, olong *pos);\n\n/** Public: Find Minimum value in an ObitFArray */\nofloat ObitFArrayMin (ObitFArray* in, olong *pos);\ntypedef ofloat (*ObitFArrayMinFP) (ObitFArray* in, olong *pos);\n\n/** Public: Replace blanks in an ObitFArray */\nvoid ObitFArrayDeblank (ObitFArray* in, ofloat scalar);\ntypedef void (*ObitFArrayDeblankFP) (ObitFArray* in, ofloat scalar);\n\n/** Public: RMS of pixel distribution from histogram */\nofloat ObitFArrayRMS (ObitFArray* in);\ntypedef ofloat (*ObitFArrayRMSFP) (ObitFArray* in);\n\n/** Public: RMS of pixel distribution. */\nofloat ObitFArrayRawRMS (ObitFArray* in);\ntypedef ofloat (*ObitFArrayRawRMSFP) (ObitFArray* in);\n\n/** Public: RMS of pixel about zero. */\nofloat ObitFArrayRMS0 (ObitFArray* in);\ntypedef ofloat (*ObitFArrayRMS0FP) (ObitFArray* in);\n\n/** Public: Function for combining planes of multi frequency images */\nofloat ObitFArrayRMS0ST (ObitFArray* in);\ntypedef ofloat (*ObitFArrayRMS0STFP) (ObitFArray* in);\n\n/** Public: RMS of pixel in potentially quantized image. */\nofloat ObitFArrayRMSQuant (ObitFArray* in);\ntypedef ofloat (*ObitFArrayRMSQuantFP) (ObitFArray* in);\n\n/** Public: Determine quantization and offset in an image */\nvoid ObitFArrayQuant (ObitFArray* in, ofloat *quant, ofloat *zero);\ntypedef void (*ObitFArrayQuantFP) (ObitFArray* in, ofloat *quant, ofloat *zero);\n\n/** Public: Mode of pixel distribution. */\nofloat ObitFArrayMode (ObitFArray* in);\ntypedef ofloat (*ObitFArrayModeFP) (ObitFArray* in);\n\n/** Public: Mean of pixel distribution. */\nofloat ObitFArrayMean (ObitFArray* in);\ntypedef ofloat (*ObitFArrayMeanFP) (ObitFArray* in);\n\n/** Public: fill elements of an FArray */\nvoid ObitFArrayFill (ObitFArray* in, ofloat scalar);\ntypedef void (*ObitFArrayFillFP) (ObitFArray* in, ofloat scalar);\n\n/** Public: negate elements of an FArray */\nvoid ObitFArrayNeg (ObitFArray* in);\ntypedef void (*ObitFArrayNegFP) (ObitFArray* in);\n\n/** Public: taks absolute value of  elements of an FArray */\nvoid ObitFArrayAbs (ObitFArray* in);\ntypedef void (*ObitFArrayAbsFP) (ObitFArray* in);\n\n/** Public: sine of  elements of an FArray */\nvoid ObitFArraySin (ObitFArray* in);\ntypedef void (*ObitFArraySinFP) (ObitFArray* in);\n\n/** Public: cosine of  elements of an FArray */\nvoid ObitFArrayCos (ObitFArray* in);\ntypedef void (*ObitFArrayCosFP) (ObitFArray* in);\n\n/** Public: sine/cosine of  elements of an FArray */\nvoid ObitFArraySinCos (ObitFArray* in, ObitFArray* outS, ObitFArray* outC);\ntypedef void (*ObitFArraySinCosFP) (ObitFArray* in, ObitFArray* outS, ObitFArray* outC);\n\n/** Public: square root of  elements of an FArray */\nvoid ObitFArraySqrt (ObitFArray* in);\ntypedef void (*ObitFArraySqrtFP) (ObitFArray* in);\n\n/** Public: sum elements of an FArray */\nofloat ObitFArraySum (ObitFArray* in);\ntypedef ofloat (*ObitFArraySumFP) (ObitFArray* in);\n\n/** Public: number of valid elements in an FArray */\nolong ObitFArrayCount (ObitFArray* in);\ntypedef olong (*ObitFArrayCountFP) (ObitFArray* in);\n\n/** Public: Add a scalar to elements of an FArray */\nvoid ObitFArraySAdd (ObitFArray* in, ofloat scalar);\ntypedef void (*ObitFArraySAddFP) (ObitFArray* in, ofloat scalar);\n\n/** Public: Multiply elements of an FArray by a scalar*/\nvoid ObitFArraySMul (ObitFArray* in, ofloat scalar);\ntypedef void (*ObitFArraySMulFP) (ObitFArray* in, ofloat scalar);\n\n/** Public: Divide elements of an FArray into a scalar*/\nvoid ObitFArraySDiv (ObitFArray* in, ofloat scalar);\ntypedef void (*ObitFArraySDivFP) (ObitFArray* in, ofloat scalar);\n\n/** Public: Clip elements of an FArray outside of a given range */\nvoid ObitFArrayClip (ObitFArray* in, ofloat minVal, ofloat maxVal, ofloat newVal);\ntypedef void (*ObitFArrayClipFP) (ObitFArray* in, ofloat minVal, ofloat maxVal, \n\t\t\t\t  ofloat newVal);\n\n/** Public: Clip elements of an FArray inside of a given range */\nvoid ObitFArrayInClip (ObitFArray* in, ofloat minVal, ofloat maxVal, ofloat newVal);\ntypedef void (*ObitFArrayInClipFP) (ObitFArray* in, ofloat minVal, ofloat maxVal, \n\t\t\t\t    ofloat newVal);\n\n/** Public: Blank elements of an array where another is blanked */\nvoid ObitFArrayBlank (ObitFArray* in1, ObitFArray* in2, ObitFArray* out);\ntypedef void (*ObitFArrayBlankFP) (ObitFArray* in1, ObitFArray* in2, \n\t\t\t\t  ObitFArray* out);\n\n/** Public: Get larger elements of two FArrays */\nvoid ObitFArrayMaxArr (ObitFArray* in1, ObitFArray* in2, ObitFArray* out);\ntypedef void (*ObitFArrayMaxArrFP) (ObitFArray* in1, ObitFArray* in2, \n\t\t\t\t    ObitFArray* out);\n\n/** Public: Get lesser elements of two FArrays */\nvoid ObitFArrayMinArr (ObitFArray* in1, ObitFArray* in2, ObitFArray* out);\ntypedef void (*ObitFArrayMinArrFP) (ObitFArray* in1, ObitFArray* in2, \n\t\t\t\t    ObitFArray* out);\n\n/** Public: Get more extreme elements of two FArrays */\nvoid ObitFArrayExtArr (ObitFArray* in1, ObitFArray* in2, ObitFArray* out);\ntypedef void (*ObitFArrayExtArrFP) (ObitFArray* in1, ObitFArray* in2, \n\t\t\t\t    ObitFArray* out);\n\n/** Public: Sum nonblanked elements of two FArrays */\nvoid ObitFArraySumArr (ObitFArray* in1, ObitFArray* in2, ObitFArray* out);\ntypedef void (*ObitFArraySumArrFP) (ObitFArray* in1, ObitFArray* in2, \n\t\t\t\t    ObitFArray* out);\n\n/** Public: Average nonblanked elements of two FArrays */\nvoid ObitFArrayAvgArr (ObitFArray* in1, ObitFArray* in2, ObitFArray* out);\ntypedef void (*ObitFArrayAvgArrFP) (ObitFArray* in1, ObitFArray* in2, \n\t\t\t\t    ObitFArray* out);\n\n/** Public: Add elements of two FArrays */\nvoid ObitFArrayAdd (ObitFArray* in1, ObitFArray* in2, ObitFArray* out);\ntypedef void (*ObitFArrayAddFP) (ObitFArray* in1, ObitFArray* in2, \n\t\t\t\t  ObitFArray* out);\n\n/** Public: Abs Add elements of two FArrays */\nvoid ObitFArrayAddAbs (ObitFArray* in1, ObitFArray* in2, ObitFArray* out);\ntypedef void (*ObitFArrayAddAbsFP) (ObitFArray* in1, ObitFArray* in2, \n\t\t\t  \t  ObitFArray* out);\n\n/** Public: Subtract elements of two FArrays */\nvoid ObitFArraySub (ObitFArray* in1, ObitFArray* in2, ObitFArray* out);\ntypedef void (*ObitFArraySubFP) (ObitFArray* in1, ObitFArray* in2, \n\t\t\t\t  ObitFArray* out);\n/** Public: copy elements from one FArray to another */\nvoid ObitFArrayCopyData (ObitFArray* in, ObitFArray* out);\ntypedef void (*ObitFArrayCopyDataFP) (ObitFArray* in1, ObitFArray* out);\n\n/** Public: Give the elements of one array the sign of the other */\nvoid ObitFArraySign (ObitFArray* in1, ObitFArray* in2);\ntypedef void (*ObitFArraySignFP) (ObitFArray* in1, ObitFArray* in2);\n\n/** Public: Multiply elements of two FArrays */\nvoid ObitFArrayMul (ObitFArray* in1, ObitFArray* in2, ObitFArray* out);\ntypedef void (*ObitFArrayMulFP) (ObitFArray* in1, ObitFArray* in2, \n\t\t\t\t  ObitFArray* out);\n\n/** Public: Divide elements of two FArrays */\nvoid ObitFArrayDiv (ObitFArray* in1, ObitFArray* in2, ObitFArray* out);\ntypedef void (*ObitFArrayDivFP) (ObitFArray* in1, ObitFArray* in2, \n\t\t\t\t  ObitFArray* out);\n\n/** Public: Divide elements of two FArrays with clipping*/\nvoid ObitFArrayDivClip (ObitFArray* in1, ObitFArray* in2, ofloat minVal, ObitFArray* out);\ntypedef void (*ObitFArrayDivClipFP) (ObitFArray* in1, ObitFArray* in2, \n\t\t\t\t     ofloat minVal, ObitFArray* out);\n\n/** Public: \"Dot\" product to two arrays */\nofloat ObitFArrayDot (ObitFArray* in1, ObitFArray* in2);\ntypedef ofloat (*ObitFArrayDotFP) (ObitFArray* in1, ObitFArray* in2);\n\n/** Public: Multiply a 2D array by a Col vector * Row vector */\nvoid ObitFArrayMulColRow (ObitFArray* in, ObitFArray* row, ObitFArray* col,\n\t\t\t  ObitFArray* out);\ntypedef void (*ObitFArrayMulColRowFP) (ObitFArray* in, ObitFArray* row, \n\t\t\t\t       ObitFArray* col, ObitFArray* out);\n\n/** Public: Convert a 1D \"center at edges\" array to proper order */\nvoid ObitFArray1DCenter (ObitFArray* in);\ntypedef void (*ObitFArray1DCenterFP) (ObitFArray* in);\n\n/** Public: Convert a 2D \"center at edges\" array to proper order */\nvoid ObitFArray2DCenter (ObitFArray* in);\ntypedef void (*ObitFArray2DCenterFP) (ObitFArray* in);\n\n/** Public: inplace invert a symmetric 2D array */\nvoid ObitFArray2DSymInv (ObitFArray* in, olong *ierr);\ntypedef void (*ObitFArray2DSymInvFP) (ObitFArray* in, olong *ierr);\n\n/** Public: Make 2-D Circular Gaussian in FArray */\nvoid ObitFArray2DCGauss (ObitFArray* in, olong Cen[2], ofloat FWHM);\ntypedef void (*ObitFArray2DCGaussFP) (ObitFArray* in, olong Cen[2], ofloat FWHM);\n\n/** Public: Make 2-D Eliptical Gaussian in FArray */\nvoid ObitFArray2DEGauss (ObitFArray* in, ofloat amp, ofloat Cen[2], ofloat GauMod[3]);\ntypedef void (*ObitFArray2DEGaussFP) (ObitFArray* in, ofloat amp, ofloat Cen[2], \n\t\t\t\t      ofloat GauMod[3] );\n\n/** Public: Shift and Add scaled array */\nvoid ObitFArrayShiftAdd (ObitFArray* in1, olong *pos1, \n\t\t\t ObitFArray* in2, olong *pos2, \n\t\t\t ofloat scalar, ObitFArray* out);\ntypedef void \n(*ObitFArrayShiftAddFP) (ObitFArray* in1, olong *pos1, \n\t\t\t ObitFArray* in2, olong *pos2, \n\t\t\t ofloat scalar, ObitFArray* out);\n\n/** Public: Shift and Add scaled array, no threading */\nvoid ObitFArrayShiftAddNT (ObitFArray* in1, olong *pos1, \n\t\t\t   ObitFArray* in2, olong *pos2, \n\t\t\t   ofloat scalar, ObitFArray* out);\n/** Public: Zero pad an array */\nvoid  ObitFArrayPad (ObitFArray* in, ObitFArray* out, ofloat factor);\ntypedef void (*ObitFArrayPadFP) (ObitFArray* in, ObitFArray* out, \n\t\t\t\t ofloat factor);\n\n/** Public: Convolve a list of Gaussians onto an FArray */\nvoid  ObitFArrayConvGaus (ObitFArray* in, ObitFArray* list, olong ncomp, \n\t\t\t  ofloat gauss[3]);\ntypedef void (*ObitFArrayConvGausFP) (ObitFArray* in, ObitFArray* list, \n\t\t\t\t      olong ncomp, ofloat gauss[3]);\n\n/** Public: Select elements in an FArray by increment */\nvoid  ObitFArraySelInc (ObitFArray* in, ObitFArray* out, olong *blc, olong *trc, \n\t\t\tolong* inc, ObitErr *err);\ntypedef void (*ObitFArraySelIncFP) (ObitFArray* in, ObitFArray* out, \n\t\t\t\t    olong *blc, olong *trc, olong* inc, ObitErr *err);\n\n/** Public: return histogram of elements in an FArray */\nObitFArray*  ObitFArrayHisto (ObitFArray* in, olong n, ofloat min, ofloat max);\ntypedef ObitFArray*  (*ObitFArrayHistoFP) (ObitFArray* in, olong n, ofloat min, ofloat max);\n\n/** Public: exponentiate elements in an FArray */\nvoid ObitFArrayExp (ObitFArray* in, ObitFArray* out);\ntypedef void  (*ObitFArrayExpFP) (ObitFArray* in, ObitFArray* out);\n\n/** Public: natural log of elements in an FArray */\nvoid ObitFArrayLog (ObitFArray* in, ObitFArray* out);\ntypedef void  (*ObitFArrayLogFP) (ObitFArray* in, ObitFArray* out);\n\n/** Public: natural log of elements in an FArray */\nvoid ObitFArrayPow (ObitFArray* in1, ObitFArray* in2, ObitFArray* out);\ntypedef void  (*ObitFArrayPowFP) (ObitFArray* in1, ObitFArray* in2, ObitFArray* out);\n\n/** Public: Gaussian distributed random numbers */\nofloat ObitFArrayRandom (ofloat mean, ofloat sigma);\ntypedef ofloat  (*ObitFArrayRandomFP) (ofloat mean, ofloat sigma);\n\n/** Public: Fill with Gaussian distributed random numbers */\nvoid ObitFArrayRandomFill (ObitFArray* in, ofloat mean, ofloat sigma);\ntypedef void  (*ObitFArrayRandomFillFP) (ObitFArray* in, ofloat mean, ofloat sigma);\n\n/*----------- ClassInfo Structure -----------------------------------*/\n/**\n * ClassInfo Structure.\n * Contains class name, a pointer to any parent class\n * (NULL if none) and function pointers.\n */\ntypedef struct  {\n#include \"ObitFArrayClassDef.h\"\n} ObitFArrayClassInfo; \n\n#endif /* OBITFARRAY_H */ \n", "meta": {"hexsha": "d34e31ac397ad4e07e4e64986789e212ce6169e2", "size": 17605, "ext": "h", "lang": "C", "max_stars_repo_path": "ObitSystem/Obit/include/ObitFArray.h", "max_stars_repo_name": "sarrvesh/Obit", "max_stars_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-08-26T06:53:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-20T01:08:59.000Z", "max_issues_repo_path": "ObitSystem/Obit/include/ObitFArray.h", "max_issues_repo_name": "sarrvesh/Obit", "max_issues_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ObitSystem/Obit/include/ObitFArray.h", "max_forks_repo_name": "sarrvesh/Obit", "max_forks_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-08-29T15:12:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:16:08.000Z", "avg_line_length": 42.5241545894, "max_line_length": 92, "alphanum_fraction": 0.6912240841, "num_tokens": 5359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09268777613309749, "lm_q2_score": 0.02517884215778565, "lm_q1q2_score": 0.0023337708852114334}}
{"text": "#ifndef VM_CALL_STACK_H\n#define VM_CALL_STACK_H\n\n#include \"function/WasmFunction.h\"\n#include \"utilities/SimpleVector.h\"\n#include \"utilities/ListStack.h\"\n#include \"vm/alloc/StackResource.h\"\n#include <gsl/span>\n#include <sstream>\n\nnamespace wasm {\n\nnamespace ex {\n\ntemplate <class Container, class Index>\ndecltype(auto) at(Container&& c, const Index& index)\n{\n\tusing std::size;\n\tif(index < size(std::forward<Container>(c)))\n\t\treturn std::forward<Container>(c)[index];\n\tthrow std::out_of_range(\"Out-of-bounds container access in wasm::ex::at().\");\n}\n\n} /* namespace ex */\n\nnamespace detail {\nauto make_stack_size_guard(auto& stack)\n{\n\tauto initial_stack_size = stack.size();\n\treturn make_scope_guard([&stack, initial_stack_size]() {\n\t\tassert(stack.size() >= initial_stack_size);\n\t\tif(stack.size() > initial_stack_size)\n\t\t\tstack.pop_n(stack.size() - initial_stack_size);\n\t});\n}\n} /* namespace detail */ \n\nstruct BadBranchError:\n\tstd::logic_error\n{\nprivate:\n\tstatic std::string make_mesage(std::size_t depth, std::size_t limit)\n\t{\n\t\tstd::ostringstream s;\n\t\ts << \"Invald branch depth (\" << depth << \") to non-existant block.  \";\n\t\ts << \"(max depth is \" << limit << ')';\n\t\treturn s.str();\n\t}\npublic:\n\tBadBranchError(std::size_t branch_depth, std::size_t limit):\n\t\tstd::logic_error(make_message(branch_depth, limit)),\n\t\tdepth(branch_depth)\n\t{\n\t\t\n\t}\n\t\t\n\tconst std::size_t depth;\n};\n\nstd::ostream& operator<<(std::ostream& os, const SimpleStack<WasmValue>& stack)\n{\n\tos << \"Stack([\";\n\tif(stack.size() > 0u)\n\t{\n\t\tos << stack.front();\n\t\tfor(auto pos = std::next(stack.begin()); pos != stack.end(); ++pos)\n\t\t\tos << \", \" << *pos;\n\t}\n\tos << \"])\";\n\treturn os;\n}\n\nstd::ostream& operator<<(std::ostream& os, const SimpleStack<TaggedWasmValue>& stack)\n{\n\tos << \"Stack([\";\n\tif(stack.size() > 0u)\n\t{\n\t\tos << stack.front();\n\t\tfor(auto pos = std::next(stack.begin()); pos != stack.end(); ++pos)\n\t\t\tos << \", \" << *pos;\n\t}\n\tos << \"])\";\n\treturn os;\n}\n\ntemplate <class T>\nstruct Block {\n\t\n\tusing stack_type = SimpleStack<T>;\n\n\tBlock(const char* label_pos, std::size_t return_count, StackResource& resource):\n\t\tlabel(label_pos),\n\t\tarity(return_count),\n\t\tstack(resource)\n\t{\n\t\t\n\t}\n\n\tbool is_bottom() const\n\t{\n\t\tif(not label)\n\t\t{\n\t\t\tassert(not arity);\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tconst char* const label;\n\tconst std::size_t arity;\n\tstack_type stack;\n};\n\ntemplate <class T>\nstd::ostream& operator<<(std::ostream& os, const Block<T>& block)\n{\n\tos << \"Block(label = \" << block.label;\n\tos << \", arity = \" << block.arity;\n\tos << \", stack = \" << block.stack;\n\tos << ')';\n\treturn os;\n}\n\n\ntemplate <class T>\nstruct WasmStackFrame\n{\n\tusing value_type = T;\n\tusing block_type = Block<value_type>;\n\tusing block_list_type = std::forward_list<\n\t\tblock_type, pmr::polymorphic_allocator<block_type>\n\t>;\n\tusing locals_vector_type = gsl::span<value_type>;\n\tusing stack_type = SimpleStack<value_type>;\n\tusing block_iterator = block_list_type::iterator;\n\tusing const_block_iterator = block_list_type::const_iterator;\n\t\n\tWasmStackFrame(const WasmFunction& func, StackResource& r):\n\t\tcode_(func),\n\t\tlocals_(locals_count(func) + param_count(signature(func))),\n\t\tblocks_(r)\n\t{\n\t\tblocks_.emplace_front(nullptr, 0u, get_resource());\n\t}\n\n\tWasmStackFrame(CodeView code, gsl::span<T> locals, StackResource& r):\n\t\treturn_address_(),\n\t\tlocals_(locals),\n\t\tblocks_(r)\n\t{\n\t\tblocks_.push_front(nullptr, 0u, get_resource());\n\t}\n\n\t~WasmStackFrame()\n\t{\n\t\twhile(not blocks_.empty())\n\t\t\tblocks_.pop_front();\n\t}\n\t\n\tblock_iterator block_at(std::size_t depth)\n\t{\n\t\tstd::size_t count = 0;\n\t\tfor(auto pos = blocks_.begin(); pos != blocks_.end(); (void)++pos, ++count)\n\t\t{\n\t\t\tif(count == depth)\n\t\t\t\treturn pos;\n\t\t}\n\t\tassert(false and \"Attempt to access out-of-range block.\");\n\t}\n\t\n\tconst char* branch_depth(wasm_uint32_t depth)\n\t{ return branch(block_at(depth)); }\n\n\tconst char* try_branch_top() const\n\t{\n\t\tassert(blocks_.begin() != blocks.end())\n\t\tif(blocks_.front().is_bottom())\n\t\t\treturn nullptr;\n\t\telse\n\t\t\treturn branch_top();\n\t}\n\n\t[[nodiscard]]\n\tconst char* branch(const_block_iterator pos)\n\t{\n\t\tassert(pos != blocks_.end());\n\t\t// get the label\n\t\tauto code_pos = pos->label;\n\t\tauto arity = pos->arity;\n\t\tauto& dest_stack = pos->stack;\n\t\tauto& src_stack = current_stack(*this);\n\t\tassert(&src_stack != &dest_stack);\n\t\tassert(arity <= dest_stack.size());\n\t\tassert(arity <= src_stack.size());\n\t\tstd::copy(src_stack.begin(), src_stack.begin() + arity, dest_stack.begin());\n\t\t// TODO: assert(src_stack.size() == arity) for 'IF ... END' blocks\n\t\twhile(blocks_.begin() != pos)\n\t\t\tblocks_.pop_front();\n\t\treturn code_pos;\n\t}\n\n\tvoid push_block(const char* label, gsl::span<const LanguageType> signature)\n\t{\n\t\tassert(\n\t\t\t(label[-1] == static_cast<char>(OpCode::END))\n\t\t\tor (label[-(1 + (std::ptrdiff_t)sizeof(wasm_uint32_t))] == static_cast<char>(OpCode::ELSE))\n\t\t);\n\t\tauto guard_ = make_stack_size_guard(stack());\n\t\tfor(const auto& type: signature)\n\t\t{\n\t\t\t// push return values onto the stack\n\t\t\ttp::visit_value_type(\n\t\t\t\t[&](auto WasmValue::* p) { stack_emplace_top(p, 0); }, type\n\t\t\t);\n\t\t}\n\t\tblocks_.emplace_front(label, signature.size(), get_resource());\n\t}\n\n\t[[nodiscard]]\n\tconst char* branch_top()\n\t{\n\t\tassert(not blocks_.empty());\n\t\tassert(not blocks_.front().is_bottom());\n\t\treturn branch(blocks_.begin());\n\t}\n\n\tT& local_at(wasm_uint32_t index)\n\t{ return ex::at(locals_, index); }\n\n\tconst T& local_at(wasm_uint32_t index) const\n\t{ return ex::at(locals_, index); }\n\n\tT& stack_at(wasm_uint32_t index)\n\t{ return ex::at(stack(), index); }\n\n\tconst T& stack_at(wasm_uint32_t index)\n\t{ return ex::at(stack(), index); }\n\n\ttemplate <class U>\n\tconst std::decay_t<U>& stack_at(wasm_uint32_t index, U WasmValue::* p) const\n\t{ return stack().at().get(p); }\n\n\ttemplate <class U>\n\tconst U& stack_at(wasm_uint32_t index, const U WasmValue::* p) const\n\t{ return stack().at(index).get(p); }\n\n\ttemplate <class U>\n\tU& stack_at(wasm_uint32_t index, U WasmValue::* p)\n\t{ return stack().at(index).get(p); }\n\n\tT& stack_top()\n\t{ return stack().at(0u); }\n\n\tconst T& stack_top() const\n\t{ return stack().at(0u); }\n\n\ttemplate <class U>\n\tconst std::decay_t<U>& stack_top(U WasmValue::* p) const\n\t{ return stack_top().get(p); }\n\n\ttemplate <class U>\n\tconst U& stack_top(const U WasmValue::* p) const\n\t{ return stack_top().get(p); }\n\n\ttemplate <class U>\n\tU& stack_top(U WasmValue::* p)\n\t{ return stack_top().get(p); }\n\n\tstd::pair<const T&, const T&> stack_top_2() const\n\t{ return std::pair<const T&, const T&>(stack_at(1u), stack_at(0u)); }\n\n\tstd::pair<T&, T&> stack_top_2() const\n\t{ return std::pair<T&, T&>(stack_at(1u), stack_at(0u)); }\n\n\ttemplate <class L, class R>\n\tstd::pair<const std::decay_t<L>&, const std::decay_t<R>&> stack_top_2(L WasmValue::* l, R WasmValue::* r) const\n\t{\n\t\treturn std::pair<const std::decay_t<L>&, const std::decay_t<R>&>(\n\t\t\tstack_at(1u).get(l), stack_at(0u).get(r)\n\t\t); \n\t}\n\n\ttemplate <class U>\n\tvoid stack_pop_2_push_1(U WasmValue::* mem, U value)\n\t{\n\t\tstack_pop();\n\t\tstack_pop_1_push_1(mem, value);\n\t}\n\n\ttemplate <class U>\n\tvoid stack_pop_1_push_1(U WasmValue::* mem, U value)\n\t{ stack().replace_top(mem, value); }\n\n\tT stack_pop()\n\t{ return stack().pop(); }\n\n\ttemplate <class U>\n\tU stack_pop(U WasmValue::* mem)\n\t{\n\t\tauto v = stack_top(mem);\n\t\tstack_pop();\n\t\treturn v;\n\t}\n\n\ttemplate <class ... Args>\n\tT stack_emplace_top(Args&& ... args)\n\t{ return stack().emplace(std::forward<Args>(args)...); }\n\n\tvoid stack_pop_n(std::size_t n)\n\t{ stack().pop_n(n); }\n\n\tauto stack_size() const\n\t{ return stack().size(); }\n\n\tconst WasmFunction* function()\n\t{ return self.code_.function(); }\n\n\n\tfriend std::ostream& operator<<(std::ostream& os, const WasmStackFrame& frame)\n\t{\n\t\tos << \"StackFrame(\";\n\t\tos << \"function = \";\n\t\twrite_declataion(os, function(frame));\n\t\tos << \", locals = \" << frame.locals_;\n\t\tos << \", stack = [\";\n\t\tconst char* delim = \"\";\n\t\tfor(const auto& block: frame_.blocks_)\n\t\t{\n\t\t\tconst auto& stack = block.stack;\n\t\t\tfor(const auto& item: stack)\n\t\t\t{\n\t\t\t\tos << delim << item;\n\t\t\t\tdelim = \", \";\n\t\t\t}\n\t\t}\n\t\tfor(const auto& item: frame_.stack_)\n\t\t{\n\t\t\tos << delim << item;\n\t\t\tdelim = \", \";\n\t\t}\n\t\tos << \"])\";\n\t\treturn os;\n\t}\n\n\tbool is_function_call() const\n\t{ return static_cast<bool>(function()); }\n\n\tstd::optional<WasmInstruction> next_instruction() const\n\t{ return code_.next_instruction(); }\n\n\tvoid advance(const WasmInstruction& instr)\n\t{\n\t\tassert(next_instruction());\n\t\tif(not is_next_instruction(instr))\n\t\t\tthrow std::logic_error(\"Instruction does not match program counter on call stack.\");\n\t\tcode_.advance(instr);\n\t}\n\t\n\tbool is_next_instruction(const WasmInstruction& instr) const\n\t{ return instr.source().data() == code_.data(); }\n\nprivate:\n\tconst auto& stack() const\n\t{\n\t\tassert(not blocks_.empty());\n\t\treturn blocks_.front().stack;\n\t}\n\n\tauto& stack()\n\t{\n\t\tassert(not blocks_.empty());\n\t\treturn blocks_.front().stack;\n\t}\n\n\tStackResource& get_resource()\n\t{\n\t\tstd::memory_resource* rsc = blocks_.get_allocator().resource();\n\t\tassert(rsc);\n\t\tassert(static_cast<bool>(dynamic_cast<StackResource*>(rsc)));\n\t\treturn *static_cast<StackResource*>(rsc);\n\t}\n\n\tCodeView code_;\n\tconst gsl::span<T> locals_;\n\tblock_list_type blocks_;\n};\n\ntemplate <class T>\nstruct WasmCallStack \n{\n\tusing frame_stack_type = ListStack<\n\t\tWasmStackFrame<T>, \n\t\tpmr::polymorphic_allocator<WasmStackFrame<T>>\n\t>;\n\tusing frame_iterator = list_type::const_iterator;\n\n\tWasmCallStack(StackResource& \n\n\tconst WasmStackFrame<T>& current_frame() const\n\t{\n\t\tassert(not frames_.empty());\n\t\treturn frames_.top();\n\t}\n\n\tCodeView call_function(const Function& func, const WasmInstruction& call_instr)\n\t{\n\t\tassert(call_instr.opcode() == OpCode::CALL);\n\t\tif(func.is_wasm_function())\n\t\t{\n\t\t\treturn call_wasm_function(func.get_wasm_function(), call_instr);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcall_c_function(func.get_c_function());\n\t\t\treturn call_instr.after();\n\t\t}\n\t}\n\n\tCodeView call_wasm_function(const WasmFunction& func, const WasmInstruction& call_instr)\n\t{\n\t\tassert(call_instr.opcode() == OpCode::CALL);\n\t\tauto& stack = frames_.empty() ? frames_.top().stack() : base_stack_;\n\t\tauto func_sig = signature(func);\n\t\tauto arg_types = param_types(func_sig);\n\t\tauto locals_types = locals(func);\n\t\tauto ret_count = return_count(func);\n\t\tif(stack.size() < arg_types.size())\n\t\t\tassert(false); // TODO: throw an exception\n\n\t\t// push zero-initialized locals onto the stack.\n\t\tauto guard_ = make_stack_size_guard(stack);\n\t\tfor(LanguageType type: locals_types)\n\t\t{\n\t\t\ttp::visit_value_type(\n\t\t\t\t[&](auto WasmValue::* p) { stack.emplace(p, 0); }, type\n\t\t\t);\n\t\t}\n\t\tauto return_address = call_instr.after().pos();\n\t\tauto locals_vector_size = locals_types.size() + arg_types.size();\n\t\tauto locals_pos = stack.data() + (stack.size() - locals_vector_size);\n\t\tgsl::span<T> locals_vector(locals_pos, locals_vector_size);\n\t\tframes_.emplace(func, return_address, locals_vector);\n\t\treturn CodeView(func);\n\t}\n\n\tvoid return_from_expression()\n\t{\n\t\tassert(frames_.size() == 1u);\n\t\t_recurse_return_from_frame_unchecked();\n\t}\n\n\t[[nodiscard]]\n\tCodeView end_block()\n\t{\n\t\tif(const char* p = top_frame().try_branch_top(); p)\n\t\t{\n\t\t\t\n\t\t}\n\t}\n\n\t[[nodiscard]]\n\tCodeView return_from_function()\n\t{\n\t\tauto& frame = top_frame();\n\t\tassert(frame.is_function_call());\n\t\tauto ret_types = return_types(signature(*frame.funtion()));\n\t\tassert(frame.stack_size() >= ret_types.size());\n\t\tCodeView ret_addr = top_frame().return_address();\n\t\t_recurse_return_from_frame(return_types);\n\t\treturn ret_addr;\n\t}\n\n\t[[nodiscard]]\n\tCodeView call_table_function(const WasmTable& table, const WasmFunctionSignature& sig, const WasmInstruction& instr)\n\t{\n\t\tassert(instr.opcode() == OpCode::CALL_INDIRECT);\n\t\tassert(frames_.empty() or top_frame().can_exectute_instruction(instr));\n\t\tauto& stack = top_stack();\n\t\twasm_uint32_t offset = reinterpret_cast<const wasm_uint32_t&>(stack.top().get(tp::i32_c));\n\t\tconst TableFunction& func = table.at(offset);\n\t\tif(func.is_null())\n\t\t\tthrow NullTableFunctionError();\n\n\t\tif(func.is_wasm_function())\n\t\t{\n\t\t\tauto& f = func.get_wasm_function();\n\t\t\tif(signature(f) != sig)\n\t\t\t\tthrow BadTableFunctionSignature();\n\t\t\tstack.pop();\n\t\t\treturn call_wasm_function(func.get_wasm_function());\n\t\t}\n\t\tassert(func.is_c_function());\n\t\tauto& f = func.get_c_function();\n\t\tif(f.signature() != sig)\n\t\t\tthrow BadTableFunctionSignature();\n\n\t\t{ /* scope */\n\t\t\tauto stack_size = stack.size();\n\t\t\tauto guard_ = make_scope_guard(\n\t\t\t\t[&, stack_size]{\n\t\t\t\t\t// poor man's check to make sure the c function call  \n\t\t\t\t\t// doesn't modify 'this'.\n\t\t\t\t\tassert(stack.size() == stack_size);\n\t\t\t\t}\n\t\t\tcall_c_function(f, offset);\n\t\t} /* /scope */\n\t\treturn instr.after();\n\t}\n\n\tvoid call_c_function(const CFunction& cfunc) const\n\t{\n\t\tconst auto& sig = cfunc.signature();\n\t\tauto param_types = param_types(sig);\n\t\tauto return_types = return_types(sig);\n\t\tauto& stack = top_stack();\n\t\tassert(stack.size() >= param_types.size());\n\t\tauto args = gsl::span<const T>(stack.data(), stack.size()).last(param_types.size());\n\t\t{\n\t\t\tauto guard_ = make_stack_size_guard(stack());\n\t\t\tfor(LanguageType value_tp: return_types)\n\t\t\t\tstack.emplace(value_tp);\n\t\t\tauto results = gsl::span<T>(stack.data(), stack.size()).last(return_types.size());\n\t\t\tcfunc(results, args);\n\t\t}\n\t\tassert(stack.size() >= return_types.size() + param_types.size());\n\t\tstd::rotate(\n\t\t\tstack.begin(),\n\t\t\tstack.begin() + return_types.size(),\n\t\t\tstack.begin() + return_types.size() + param_types.size()\n\t\t);\n\t\tstack.pop_n(param_types.size());\n\t}\n\n\tstd::optional<WasmInstruction> next_instruction() const\n\t{ return top_frame().next_instruction(); }\n\n\tvoid execute(const WasmInstruction& instr, const WasmModule& module) const\n\t{\n\t\tif(not top_frame().is_next_instruction())\n\t\t\tthrow std::logic_error(\"Instruction does not match program counter on call stack.\");\n\t\tCodeView next = instr.execute(*this, module);\n\t\ttop_frame().code_.advance(next);\n\t}\n\nprivate:\n\tWasmStackFrame<T>& top_frame()\n\t{\n\t\tif(frames_.empty())\n\t\t\tthrow std::out_of_range(\"Attempt to access out-of-bounds call stack frame.\");\n\t\treturn frames_.top();\n\t}\n\n\tSimpleStack<T>& top_stack()\n\t{\n\t\tif(frames_.empty())\n\t\t\treturn base_stack_;\n\t\treturn frames_.top().stack();\n\t}\n\n\tstd::pair<WasmStackFrame<T>&, WasmStackFrame<T>&> top_two_frames()\n\t{\n\t\tif(frames_.empty())\n\t\t\tthrow std::out_of_range(\"Attempt to access out-of-bounds frame.\");\n\t\tauto pos = frames_.begin();\n\t\tconst auto& hi = *pos++;\n\t\tif(pos == frames_.end())\n\t\t\tthrow std::out_of_range(\"Attempt to access out-of-bounds frame.\");\n\t\tconst auto& lo = *pos++;\n\t\treturn std::pair<WasmStackFrame&, WasmStackFrame&>(lo, hi);\n\t}\n\n\tvoid _recurse_return_from_frame_unchecked()\n\t{\n\t\tif(auto& stack = top_frame().stack(); stack.empty())\n\t\t{\n\t\t\tframes_.pop();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tT ret_v = stack.pop();\n\t\t\t_recurse_return_from_frame_unchecked();\n\t\t\ttop_stack().emplace(ret_v);\n\t\t}\n\t}\n\tvoid _recurse_return_from_frame(const gsl::span<const LanguageType>& return_types, std::size_t index = 0u)\n\t{\n\t\tassert(not frames_.empty());\n\t\tif(index < return_types.size())\n\t\t{\n\t\t\t// one of the return values from the callee's frame\n\t\t\ttp::visit_value_type(\n\t\t\t\t[&](auto WasmValue::* p) {\n\t\t\t\t\tauto ret_v = top_frame().stack_at(index, p);\n\t\t\t\t\t// keep recursing until we exhaust the return\n\t\t\t\t\t// values.  Once we've done that, pop the callee's \n\t\t\t\t\t// frame, and then pop the locals vector and arguments \n\t\t\t\t\t// off the caller's stack.\n\t\t\t\t\t_recurse_return_from_frame(return_types, index);\n\t\t\t\t\t// now that we've popped the callee's frame from the call stack, \n\t\t\t\t\t// and the locals vector off of the caller's frame's stack, push \n\t\t\t\t\t// the return values onto the callee's frame's stack.\n\t\t\t\t\t//\n\t\t\t\t\t// note that there may be no frame below the one we popped, in which\n\t\t\t\t\t// case, the return values are pushed onto 'this->base_stack_'\n\t\t\t\t\ttop_stack().stack_emplace_top(p, ret_v);\n\t\t\t\t},\n\t\t\t\treturn_types[return_types.size() - index]\n\t\t\t);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tconst auto* func_p = top_frame.function();\n\t\t\tassert(func_p);\n\t\t\tconst auto& func = *func_p;\n\t\t\tstd::size_t total_locals = param_count(func) + locals_count(func);\n\t\t\t// pop the top frame\n\t\t\tframes_.pop_front();\n\t\t\tassert(not frames_.empty());\n\t\t\tauto& new_top_frame = frames_.front();\n\t\t\tassert(new_top_frame.stack_size() >= total_locals);\n\t\t\t// pop the locals (args + locals) vector of the frame we just popped\n\t\t\t// off of the stack.  note that the locals vector of the current frame\n\t\t\t// lives on the stack of the previous frame.\n\t\t\tnew_top_frame.stack_pop_n(total_locals);\n\t\t\t// push the return values of the frame we just popped... \n\t\t\t// ... by simply returning from _recurse_return_from_frame().  each\n\t\t\t// recursive call which took the if() branch above will push the return\n\t\t\t// values onto the new frame. \n\t\t}\n\t}\n\n\tconst StackResource& stack_resource() const\n\t{ return base_stack_.get_resource(); }\n\n\tStackResource& stack_resource()\n\t{ return base_stack_.get_resource(); }\n\n\tframe_stack_type frames_;\n\tSimpleStack<T> base_stack_;\n};\n\ntemplate <class T>\nconst T& local_at(const WasmCallStack<T>& self, std::size_t idx)\n{\n\tauto locals = locals(current_frame(self));\n\tif(idx >= locals.size())\n\t\tthrow ValidationError<std::out_of_range>(\"Attempt to access out-of-bounds local.\");\n\treturn locals[idx];\n}\n\ntemplate <class T>\nT& local_at(WasmCallStack<T>& self, std::size_t idx)\n{\n\tauto locals = locals(current_frame(self));\n\tif(idx >= locals.size())\n\t\tthrow ValidationError<std::out_of_range>(\"Attempt to access out-of-bounds local.\");\n\treturn locals[idx];\n}\n\ntemplate <class T>\nconst auto& current_stack(const WasmCallStack<T>& self, std::size_t idx)\n{ return current_stack(current_frame(self)); }\n\ntemplate <class T>\nauto& current_stack(WasmCallStack<T>& self, std::size_t idx)\n{ return current_stack(current_frame(self)); }\n\n\n} /* namespace wasm */\n\n#endif /* VM_CALL_STACK_H */\n", "meta": {"hexsha": "43869dcf61c45c855b76509d0f3643e6f5aed525", "size": 17622, "ext": "h", "lang": "C", "max_stars_repo_path": "include/vm/CallStack.h", "max_stars_repo_name": "tvanslyke/wasm-cpp", "max_stars_repo_head_hexsha": "8a56c1706e2723ece36e3642bae9e36792dbd7b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/vm/CallStack.h", "max_issues_repo_name": "tvanslyke/wasm-cpp", "max_issues_repo_head_hexsha": "8a56c1706e2723ece36e3642bae9e36792dbd7b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/vm/CallStack.h", "max_forks_repo_name": "tvanslyke/wasm-cpp", "max_forks_repo_head_hexsha": "8a56c1706e2723ece36e3642bae9e36792dbd7b2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2232142857, "max_line_length": 117, "alphanum_fraction": 0.6802292589, "num_tokens": 4762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11279541224768529, "lm_q2_score": 0.020645930889866774, "lm_q1q2_score": 0.0023287662859597428}}
{"text": "\n#pragma once\n\n#include <memory>\n\n#include <gsl/gsl>\n#include \"../platform/d3d.h\"\n#include \"../infrastructure/macros.h\"\n\nnamespace gfx {\n\nclass IndexBuffer {\n\tfriend class RenderingDevice;\npublic:\n\tIndexBuffer(CComPtr<ID3D11Buffer> buffer, size_t count);\n\t~IndexBuffer();\n\n\tvoid Update(gsl::span<uint16_t> data);\n\n\tNO_COPY_OR_MOVE(IndexBuffer)\nprivate:\n\tvoid Unlock();\n\n\tsize_t mCount;\n\tCComPtr<ID3D11Buffer> mBuffer;\n};\n\nusing IndexBufferPtr = std::shared_ptr<IndexBuffer>;\n\nclass VertexBuffer {\n\tfriend class RenderingDevice;\n\tfriend class BufferBinding;\npublic:\n\tVertexBuffer(CComPtr<ID3D11Buffer> vertexBufferNew, size_t size);\n\t~VertexBuffer();\n\n\tvoid Update(gsl::span<const uint8_t> data);\n\n\ttemplate <typename T>\n\tvoid Update(gsl::span<T> data) {\n\t\tUpdate(gsl::span(reinterpret_cast<const uint8_t*>(&data[0]), data.size_bytes()));\n\t}\n\n\tNO_COPY_OR_MOVE(VertexBuffer);\nprivate:\n\tsize_t mSize;\n\tCComPtr<ID3D11Buffer> mBuffer;\n};\n\nusing VertexBufferPtr = std::shared_ptr<VertexBuffer>;\n\n}\n", "meta": {"hexsha": "5aadb81ec819808795313195978e0e5b2954f244", "size": 992, "ext": "h", "lang": "C", "max_stars_repo_path": "Infrastructure/include/graphics/buffers.h", "max_stars_repo_name": "edoipi/TemplePlus", "max_stars_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 69.0, "max_stars_repo_stars_event_min_datetime": "2015-05-05T14:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T06:13:04.000Z", "max_issues_repo_path": "Infrastructure/include/graphics/buffers.h", "max_issues_repo_name": "edoipi/TemplePlus", "max_issues_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 457.0, "max_issues_repo_issues_event_min_datetime": "2015-05-01T22:07:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T02:19:10.000Z", "max_forks_repo_path": "Infrastructure/include/graphics/buffers.h", "max_forks_repo_name": "edoipi/TemplePlus", "max_forks_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2016-02-04T21:19:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T23:14:51.000Z", "avg_line_length": 18.7169811321, "max_line_length": 83, "alphanum_fraction": 0.7489919355, "num_tokens": 256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11279539733570562, "lm_q2_score": 0.020645932810633056, "lm_q1q2_score": 0.0023287661947416372}}
{"text": "#ifndef SEARCHPATTERNBASE_HHHHH\n#define SEARCHPATTERNBASE_HHHHH\n\n#include \"../../SigScannerMemoryData.h\"\n\n#include <vector>\n#include <string>\n#include <memory>\n\n#include <gsl/span>\n\nnamespace MPSig {\n    namespace detail {\n        class SearchPatternBase {\n        public:\n            virtual ~SearchPatternBase() = default;\n\n            using gsl_span_cit_t = typename gsl::span<const char>::const_iterator;\n            using gsl_span_crit_t = typename gsl::span<const char>::const_reverse_iterator;\n\n            template<typename It>\n            struct ExecFirstResult {\n                bool success; // If it was a success\n                It rangeBegin; // The first valid iterator \n                It rangeEnd; // The next depended iterator point (from which all other patterns depend on)\n            };\n\n            // ExecFirst can look up begin to end fully, without restrictions\n            virtual ExecFirstResult<gsl_span_cit_t> ExecFirst(const MPSig::SigScannerMemoryData& data, gsl_span_cit_t begin, gsl_span_cit_t end) const = 0;\n            virtual ExecFirstResult<gsl_span_crit_t> ExecFirst(const MPSig::SigScannerMemoryData& data, gsl_span_crit_t begin, gsl_span_crit_t end) const = 0;\n            \n            // ExecDepend must only check the current location as it depends on a search success\n            virtual ExecFirstResult<gsl_span_cit_t> ExecDepend(const MPSig::SigScannerMemoryData& data, gsl_span_cit_t begin, gsl_span_cit_t end) const = 0;\n            virtual ExecFirstResult<gsl_span_crit_t> ExecDepend(const MPSig::SigScannerMemoryData& data, gsl_span_crit_t begin, gsl_span_crit_t end) const = 0;\n        \n            virtual std::unique_ptr<SearchPatternBase> Clone() const = 0;\n        };\n\n    }    \n}\n\n#endif\n", "meta": {"hexsha": "f2d6371678a95bf6e8d111ebace0093545819655", "size": 1744, "ext": "h", "lang": "C", "max_stars_repo_path": "src/search/detail/SearchPatternBase.h", "max_stars_repo_name": "KevinW1998/MultipassSigScanner", "max_stars_repo_head_hexsha": "13f290ec593ddbeed3c59c7fba642c1704bfd529", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/search/detail/SearchPatternBase.h", "max_issues_repo_name": "KevinW1998/MultipassSigScanner", "max_issues_repo_head_hexsha": "13f290ec593ddbeed3c59c7fba642c1704bfd529", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/search/detail/SearchPatternBase.h", "max_forks_repo_name": "KevinW1998/MultipassSigScanner", "max_forks_repo_head_hexsha": "13f290ec593ddbeed3c59c7fba642c1704bfd529", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.5581395349, "max_line_length": 159, "alphanum_fraction": 0.6788990826, "num_tokens": 396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09534947518185825, "lm_q2_score": 0.02442309085295633, "lm_q1q2_score": 0.002328728895148229}}
{"text": "\n#pragma once\n\n#include <gsl/gsl_assert>\n#include <src/util/Logging.h>\n\n#ifndef NDEBUG\n    //#define RNR_EXPECTS(x) Expects(x)\n    //#define RNR_ENSURES(x) Ensures(x)\n\n/**\n * specifies a precondition that is expected to be true\n * terminates the program if the condition is not met and the program is compiled in debug mode\n */\n#define RNR_EXPECTS(x) \\\n  do { \\\n    if (!(x)) { \\\n        LOG(ERROR) << \"assertion failed: \" << #x; \\\n        std::terminate(); \\\n    } \\\n  } while (0)\n\n/**\n* specifies a postcondition that is expected to be made true by the code block above\n* terminates the program if the condition is not met and the program is compiled in debug mode\n*/\n#define RNR_ENSURES(x) \\\n  do { \\\n    if (!(x)) { \\\n        LOG(ERROR) << \"assertion failed: \" << #x; \\\n        std::terminate(); \\\n    } \\\n  } while (0)\n#else\n    #define RNR_EXPECTS(x)\n    #define RNR_ENSURES(x)\n#endif\n", "meta": {"hexsha": "6d74cf7601712c0cf27ec24f5c65c2c51a2ba4a6", "size": 891, "ext": "h", "lang": "C", "max_stars_repo_path": "src/common/Assert.h", "max_stars_repo_name": "DavHau/Riner", "max_stars_repo_head_hexsha": "f9e9815b713572f03497f0e4e66c3f82a0241b66", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-07-24T03:24:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T07:41:08.000Z", "max_issues_repo_path": "src/common/Assert.h", "max_issues_repo_name": "DavHau/Riner", "max_issues_repo_head_hexsha": "f9e9815b713572f03497f0e4e66c3f82a0241b66", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-07-30T22:10:39.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-15T15:57:08.000Z", "max_forks_repo_path": "src/common/Assert.h", "max_forks_repo_name": "DavHau/Riner", "max_forks_repo_head_hexsha": "f9e9815b713572f03497f0e4e66c3f82a0241b66", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-07-30T21:33:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T20:53:11.000Z", "avg_line_length": 23.4473684211, "max_line_length": 95, "alphanum_fraction": 0.6228956229, "num_tokens": 245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.04885777585230565, "lm_q2_score": 0.04742587250438209, "lm_q1q2_score": 0.0023171226484191257}}
{"text": "/// @brief Hyperion logging facilities.\n///\n/// Hyperion's logging facilities are robust and composable.\n/// Behavioral (Policy) configuration is configurable at compile time with via template parameters,\n/// and output configuration is configurable by supplying the desired `Sink`s on creation\n#pragma once\n\n#include <Hyperion/BasicTypes.h>\n#include <Hyperion/FmtIO.h>\n#include <Hyperion/Logger.h>\n#include <Hyperion/Option.h>\n#include <Hyperion/logging/Config.h>\n#include <Hyperion/logging/Entry.h>\n#include <Hyperion/logging/Queue.h>\n#include <Hyperion/logging/Sink.h>\n#include <Hyperion/synchronization/ReadWriteLock.h>\n#include <atomic>\n#include <chrono>\n#include <filesystem>\n#include <gsl/gsl>\n#include <iostream>\n#include <memory>\n#include <mutex>\n#include <system_error>\n#include <thread>\n\nnamespace hyperion {\n\n\t/// @brief Possible Error categories that can occur when using the logger\n\tenum class LoggerErrorCategory : i8 {\n\t\t/// @brief No Error occurred\n\t\tSuccess = 0,\n\t\t/// @brief failed to queue the entry for logging\n\t\tQueueingError,\n\t\t/// @brief the requested log level for the entry is\n\t\t/// lower than the minimum level for the logger\n\t\tLogLevelError,\n\t\tLoggerNotInitialized,\n\t\tUnknown = -1\n\t};\n\n\t/// @brief Alias for the Error type we might receive from the internal queue\n\tusing QueueError = LoggingQueueError;\n\n\tclass LoggerErrorDomain {\n\t  public:\n\t\tusing value_type = LoggerErrorCategory;\n\t\tusing LoggerStatusCode = error::StatusCode<LoggerErrorDomain>;\n\t\tusing LoggerErrorCode = error::ErrorCode<LoggerErrorDomain>;\n\n\t\tstatic const constexpr char (&UUID)[error::num_chars_in_uuid] // NOLINT\n\t\t\t= \"045dd371-9552-4ce1-bd4d-8e95b654fbe0\";\n\n\t\tstatic constexpr u64 ID = error::parse_uuid_from_string(UUID);\n\n\t\tconstexpr LoggerErrorDomain() noexcept = default;\n\t\texplicit constexpr LoggerErrorDomain(u64 uuid) noexcept : m_uuid(uuid) {\n\t\t}\n\t\texplicit constexpr LoggerErrorDomain(const error::UUIDString auto& uuid) noexcept\n\t\t\t: m_uuid(error::parse_uuid_from_string(uuid)) {\n\t\t}\n\t\tconstexpr LoggerErrorDomain(const LoggerErrorDomain&) noexcept = default;\n\t\tconstexpr LoggerErrorDomain(LoggerErrorDomain&&) noexcept = default;\n\t\tconstexpr ~LoggerErrorDomain() noexcept = default;\n\n\t\t[[nodiscard]] inline constexpr auto id() const noexcept -> u64 {\n\t\t\treturn m_uuid;\n\t\t}\n\n\t\t[[nodiscard]] inline constexpr auto name() const noexcept -> std::string_view { // NOLINT\n\t\t\treturn \"LoggerErrorDomain\";\n\t\t}\n\n\t\t[[nodiscard]] inline constexpr auto message(value_type code) // NOLINT\n\t\t\tconst noexcept -> std::string_view {\n\t\t\tif(code == value_type::Success) {\n\t\t\t\treturn \"Success\";\n\t\t\t}\n\t\t\telse if(code == value_type::QueueingError) {\n\t\t\t\treturn \"Logger failed to queue log entry.\";\n\t\t\t}\n\t\t\telse if(code == value_type::LogLevelError) {\n\t\t\t\treturn \"Requested log level for entry is lower than minimum level configured for \"\n\t\t\t\t\t   \"logger.\";\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn \"Unknown Logger error.\";\n\t\t\t}\n\t\t}\n\n\t\t[[nodiscard]] inline constexpr auto message(const LoggerStatusCode& code) // NOLINT\n\t\t\tconst noexcept -> std::string_view {\n\t\t\treturn message(code.code());\n\t\t}\n\n\t\t[[nodiscard]] inline constexpr auto is_error(const LoggerStatusCode& code) // NOLINT\n\t\t\tconst noexcept -> bool {\n\t\t\treturn code.code() != value_type::Success;\n\t\t}\n\n\t\t[[nodiscard]] inline constexpr auto is_success(const LoggerStatusCode& code) // NOLINT\n\t\t\tconst noexcept -> bool {\n\t\t\treturn code.code() == value_type::Success;\n\t\t}\n\n\t\ttemplate<typename Domain2>\n\t\t[[nodiscard]] inline constexpr auto\n\t\tare_equivalent(const LoggerStatusCode& lhs,\n\t\t\t\t\t   const error::StatusCode<Domain2>& rhs) const noexcept -> bool {\n\t\t\tif constexpr(concepts::Same<LoggerStatusCode, error::StatusCode<Domain2>>) {\n\t\t\t\treturn lhs.code() == rhs.code();\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\t[[nodiscard]] inline constexpr auto as_generic_code(const LoggerStatusCode& code) // NOLINT\n\t\t\tconst noexcept -> error::GenericStatusCode {\n\t\t\tif(code.code() == value_type::Success || code.code() == value_type::Unknown) {\n\t\t\t\treturn make_status_code(static_cast<error::Errno>(code.code()));\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn make_status_code(error::Errno::Unknown);\n\t\t\t}\n\t\t}\n\n\t\t[[nodiscard]] inline static constexpr auto success_value() noexcept -> value_type {\n\t\t\treturn value_type::Success;\n\t\t}\n\n\t\ttemplate<typename Domain>\n\t\tfriend inline constexpr auto\n\t\toperator==(const LoggerErrorDomain& lhs, const Domain& rhs) noexcept -> bool {\n\t\t\treturn rhs.id() == lhs.id();\n\t\t}\n\n\t\ttemplate<typename Domain>\n\t\tfriend inline constexpr auto\n\t\toperator!=(const LoggerErrorDomain& lhs, const Domain& rhs) noexcept -> bool {\n\t\t\treturn rhs.id() != lhs.id();\n\t\t}\n\n\t\tconstexpr auto operator=(const LoggerErrorDomain&) noexcept -> LoggerErrorDomain& = default;\n\t\tconstexpr auto operator=(LoggerErrorDomain&&) noexcept -> LoggerErrorDomain& = default;\n\n\t  private:\n\t\tu64 m_uuid = ID;\n\t};\n\n\tusing LoggerStatusCode = LoggerErrorDomain::LoggerStatusCode;\n\tusing LoggerErrorCode = LoggerErrorDomain::LoggerErrorCode;\n\tusing LoggerError = error::Error<LoggerErrorDomain>;\n\n} // namespace hyperion\n\ntemplate<>\ninline constexpr auto\nmake_status_code_domain<hyperion::LoggerErrorDomain>() noexcept -> hyperion::LoggerErrorDomain {\n\treturn {};\n}\n\nnamespace hyperion {\n\tstatic_assert(error::StatusCodeDomain<LoggerErrorDomain>);\n\n\ttemplate<>\n\tstruct error::status_code_enum_info<LoggerErrorCategory> {\n\t\tusing domain_type = LoggerErrorDomain;\n\t\tstatic constexpr bool value = true;\n\t};\n\n\tIGNORE_PADDING_START\n\n\tnamespace detail {\n#if HYPERION_HAS_JTHREAD\n\t\tusing thread = std::jthread;\n#else\n\t\tusing thread = std::thread;\n#endif\n\t\tstatic constexpr fmt::text_style MESSAGE_STYLE = fmt::fg(fmt::color::white);\n\t\tstatic constexpr fmt::text_style TRACE_STYLE = fmt::fg(fmt::color::steel_blue);\n\t\tstatic constexpr fmt::text_style INFO_STYLE\n\t\t\t= fmt::fg(fmt::color::light_green) | fmt::emphasis::italic;\n\t\tstatic constexpr fmt::text_style WARN_STYLE\n\t\t\t= fmt::fg(fmt::color::orange) | fmt::emphasis::bold;\n\t\tstatic constexpr fmt::text_style ERROR_STYLE\n\t\t\t= fmt::fg(fmt::color::red) | fmt::emphasis::bold;\n\n\t\tIGNORE_UNNEEDED_INTERNAL_DECL_START\n\t\t[[nodiscard]] inline static auto create_time_stamp() noexcept -> std::string {\n\t\t\treturn fmt::format(\"[{:%Y-%m-%d|%H-%M-%S}]\", fmt::localtime(std::time(nullptr)));\n\t\t}\n\n\t\tinline static auto\n\t\tcreate_default_sinks() noexcept -> Sinks { // NOLINT(bugprone-exception-escape)\n\t\t\tauto file = FileSink::create_file();\n\t\t\tauto file_sink = make_sink<FileSink>(file.expect(\"Failed to create default log file\"));\n\t\t\tauto stdout_sink = make_sink<StdoutSink<>>();\n\t\t\tauto stderr_sink = make_sink<StderrSink<>>();\n\t\t\treturn Sinks({std::move(file_sink), std::move(stdout_sink), std::move(stderr_sink)});\n\t\t}\n\t\tIGNORE_UNNEEDED_INTERNAL_DECL_STOP\n\n\t\tIGNORE_UNUSED_TEMPLATES_START\n\t\ttemplate<LogLevel Level, typename... Args>\n\t\tinline static auto\n\t\tformat_entry(Option<usize> thread_id, // NOLINT(bugprone-exception-escape)\n\t\t\t\t\t fmt::format_string<Args...>&& format_string,\n\t\t\t\t\t Args&&... args) noexcept -> Entry {\n\t\t\tconst auto timestamp = create_time_stamp();\n\t\t\tconst auto entry = fmt::format(format_string, std::forward<Args>(args)...);\n\t\t\tconst auto id = thread_id.is_some() ?\n\t\t\t\t\t\t\t\tthread_id.unwrap() :\n\t\t\t\t\t\t\t\t  std::hash<std::thread::id>()(std::this_thread::get_id());\n\n\t\t\tstd::string log_type;\n\t\t\tif constexpr(Level == LogLevel::MESSAGE) {\n\t\t\t\tlog_type = \"MESSAGE\"s;\n\t\t\t}\n\t\t\telse if constexpr(Level == LogLevel::TRACE) {\n\t\t\t\tlog_type = \"TRACE\"s;\n\t\t\t}\n\t\t\telse if constexpr(Level == LogLevel::INFO) {\n\t\t\t\tlog_type = \"INFO\"s;\n\t\t\t}\n\t\t\telse if constexpr(Level == LogLevel::WARN) {\n\t\t\t\tlog_type = \"WARN\"s;\n\t\t\t}\n\t\t\telse if constexpr(Level == LogLevel::ERROR) {\n\t\t\t\tlog_type = \"ERROR\"s;\n\t\t\t}\n\t\t\treturn make_entry<entry_level_t<Level>>(\"{0}  [Thread ID: {1}] [{2}]: {3}\",\n\t\t\t\t\t\t\t\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t\t\t\t\t\t\tlog_type,\n\t\t\t\t\t\t\t\t\t\t\t\t\tentry);\n\t\t}\n\t\tIGNORE_UNUSED_TEMPLATES_STOP\n\n\t\ttemplate<LogLevel MinimumLevel = DefaultLogParameters::minimum_level,\n\t\t\t\t LogThreadingPolicy ThreadingPolicy = DefaultLogParameters::threading_policy,\n\t\t\t\t LogAsyncPolicy AsyncPolicy = DefaultLogParameters::async_policy,\n\t\t\t\t usize QueueSize = DefaultLogParameters::queue_size>\n\t\tclass LogBase;\n\n\t\ttemplate<LogLevel MinimumLevel, LogAsyncPolicy AsyncPolicy>\n\t\tclass LogBase<MinimumLevel, LogThreadingPolicy::SingleThreaded, AsyncPolicy> {\n\t\t  public:\n\t\t\tstatic constexpr auto THREADING_POLICY = LogThreadingPolicy::SingleThreaded;\n\t\t\tstatic constexpr auto ASYNC_POLICY = AsyncPolicy;\n\t\t\tstatic constexpr auto MINIMUM_LEVEL = MinimumLevel;\n\n\t\t\tLogBase() : LogBase(create_default_sinks()) {\n\t\t\t}\n\t\t\texplicit LogBase(Sinks&& sinks) noexcept : m_sinks(std::move(sinks)) {\n\t\t\t}\n\t\t\tLogBase(const LogBase&) = delete;\n\t\t\tLogBase(LogBase&&) noexcept = default;\n\t\t\t~LogBase() noexcept = default;\n\n\t\t\ttemplate<LogLevel Level, typename... Args>\n\t\t\tinline auto log(Option<usize> thread_id,\n\t\t\t\t\t\t\tfmt::format_string<Args...>&& format_string,\n\t\t\t\t\t\t\tArgs&&... args) noexcept -> void {\n\t\t\t\tconst auto message = format_entry<Level>(std::move(thread_id),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t std::move(format_string),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t std::forward<Args>(args)...);\n\n\t\t\t\tstd::for_each(m_sinks.begin(), m_sinks.end(), [&](Sink& sink) noexcept -> void {\n\t\t\t\t\tsink.sink(message);\n\t\t\t\t});\n\t\t\t}\n\n\t\t\ttemplate<LogLevel, typename... Args>\n\t\t\tinline auto\n\t\t\tlog(fmt::format_string<Args...>&& format_string, Args&&... args) noexcept -> void {\n\t\t\t\treturn log(None(), std::move(format_string), std::forward<Args>(args)...);\n\t\t\t}\n\n\t\t\tinline auto flush() const noexcept -> void {\n\t\t\t\t// intentionally does nothing\n\t\t\t}\n\n\t\t\tauto operator=(const LogBase&) -> LogBase& = delete;\n\t\t\tauto operator=(LogBase&&) noexcept -> LogBase& = default;\n\n\t\t  private:\n\t\t\tSinks m_sinks;\n\t\t};\n\n\t\ttemplate<LogLevel MinimumLevel, LogAsyncPolicy AsyncPolicy, usize QueueSize>\n\t\tclass LogBase<MinimumLevel,\n\t\t\t\t\t  LogThreadingPolicy::SingleThreadedAsync,\n\t\t\t\t\t  AsyncPolicy,\n\t\t\t\t\t  QueueSize> {\n\t\t  public:\n\t\t\tstatic constexpr auto THREADING_POLICY = LogThreadingPolicy::SingleThreadedAsync;\n\t\t\tstatic constexpr auto ASYNC_POLICY = AsyncPolicy;\n\t\t\tstatic constexpr auto MINIMUM_LEVEL = MinimumLevel;\n\t\t\tstatic constexpr usize QUEUE_SIZE = QueueSize;\n\n\t\t\tLogBase() : LogBase(create_default_sinks()) {\n\t\t\t}\n\t\t\texplicit LogBase(Sinks&& sinks) noexcept : m_sinks(std::move(sinks)), m_queue() {\n#if HYPERION_HAS_JTHREAD\n\t\t\t\tm_logging_thread = detail::thread(\n\t\t\t\t\t[&](const std::stop_token& token) { message_thread_function(token); });\n#else\n\t\t\t\tm_logging_thread = detail::thread([&]() { message_thread_function(); });\n#endif\n\t\t\t}\n\t\t\tLogBase(const LogBase&) = delete;\n\t\t\tLogBase(LogBase&& logger) noexcept {\n\t\t\t\tstd::atomic_thread_fence(std::memory_order_acquire);\n\t\t\t\tlogger.request_thread_stop();\n\t\t\t\tlogger.m_logging_thread.join();\n\t\t\t\t// NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)\n\t\t\t\tm_sinks = std::move(logger.m_sinks);\n\t\t\t\t// NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)\n\t\t\t\tm_queue = std::move(logger.m_queue);\n#if HYPERION_HAS_JTHREAD\n\t\t\t\tm_logging_thread = detail::thread(\n\t\t\t\t\t[&](const std::stop_token& token) { message_thread_function(token); });\n#else\n\t\t\t\tm_logging_thread = detail::thread([&]() { message_thread_function(); });\n#endif\n\t\t\t\tstd::atomic_thread_fence(std::memory_order_release);\n\t\t\t}\n\t\t\t~LogBase() noexcept {\n\t\t\t\trequest_thread_stop();\n\t\t\t\tm_logging_thread.join();\n\t\t\t}\n\n\t\t\ttemplate<LogLevel Level, typename... Args>\n\t\t\tinline auto log(Option<usize> thread_id,\n\t\t\t\t\t\t\tfmt::format_string<Args...>&& format_string,\n\t\t\t\t\t\t\tArgs&&... args) noexcept {\n\t\t\t\tif constexpr(Level >= MINIMUM_LEVEL && MINIMUM_LEVEL != LogLevel::DISABLED) {\n\t\t\t\t\tauto message = format_entry<Level>(std::move(thread_id),\n\t\t\t\t\t\t\t\t\t\t\t\t\t   std::move(format_string),\n\t\t\t\t\t\t\t\t\t\t\t\t\t   std::forward<Args>(args)...);\n\t\t\t\t\tif constexpr(ASYNC_POLICY == LogAsyncPolicy::DropWhenFull) {\n\t\t\t\t\t\treturn log_dropping(std::move(message));\n\t\t\t\t\t}\n\t\t\t\t\telse if constexpr(ASYNC_POLICY == LogAsyncPolicy::FlushWhenFull) {\n\t\t\t\t\t\tlog_flushing(std::move(message));\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tlog_overwriting(std::move(message));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tignore(format_string, std::forward<Args>(args)...);\n\t\t\t\t\treturn Err(LoggerError(make_error_code(LoggerErrorCategory::LogLevelError)));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttemplate<LogLevel, typename... Args>\n\t\t\tinline auto log(fmt::format_string<Args...>&& format_string, Args&&... args) noexcept {\n\t\t\t\treturn log(None(), std::move(format_string), std::forward<Args>(args)...);\n\t\t\t}\n\n\t\t\tinline auto flush() noexcept -> void {\n\t\t\t\tm_flush.store(true);\n\t\t\t}\n\n\t\t\tauto operator=(const LogBase&) -> LogBase& = delete;\n\t\t\tauto operator=(LogBase&& logger) noexcept -> LogBase& {\n\t\t\t\tstd::atomic_thread_fence(std::memory_order_acquire);\n\t\t\t\tif(this == &logger) {\n\t\t\t\t\treturn *this;\n\t\t\t\t}\n\n\t\t\t\tlogger.request_thread_stop();\n\t\t\t\tlogger.m_logging_thread.join();\n\t\t\t\tm_sinks = std::move(logger.m_sinks);\n\t\t\t\tm_queue = std::move(logger.m_queue);\n\n\t\t\t\tstd::atomic_thread_fence(std::memory_order_release);\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t  private:\n\t\t\t[[nodiscard]] inline static consteval auto get_queue_policy() noexcept -> QueuePolicy {\n\t\t\t\tif constexpr(ASYNC_POLICY == LogAsyncPolicy::DropWhenFull\n\t\t\t\t\t\t\t || ASYNC_POLICY == LogAsyncPolicy::FlushWhenFull)\n\t\t\t\t{\n\t\t\t\t\treturn QueuePolicy::ErrWhenFull;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\treturn QueuePolicy::OverwriteWhenFull;\n\t\t\t\t}\n\t\t\t}\n\t\t\tusing Queue = LoggingQueue<Entry, get_queue_policy(), QUEUE_SIZE>;\n\n\t\t\tSinks m_sinks;\n\t\t\tQueue m_queue;\n\t\t\tstd::atomic_bool m_flush = false;\n#if !HYPERION_HAS_JTHREAD\n\t\t\tstd::atomic_bool m_exit_flag = false;\n#endif\n\t\t\tdetail::thread m_logging_thread;\n\n\t\t\tinline auto request_thread_stop() noexcept -> void {\n#if HYPERION_HAS_JTHREAD\n\t\t\t\tignore(m_logging_thread.request_stop());\n#else\n\t\t\t\tm_exit_flag.store(true);\n#endif\n\t\t\t}\n\n\t\t\tinline auto log_dropping(Entry&& message) noexcept -> Result<bool, LoggerError>\n\t\t\trequires(ASYNC_POLICY == LogAsyncPolicy::DropWhenFull) {\n\t\t\t\treturn m_queue.push(std::move(message))\n\t\t\t\t\t.map_err([]([[maybe_unused]] const QueueError& error) {\n\t\t\t\t\t\treturn LoggerError(LoggerErrorCategory::QueueingError);\n\t\t\t\t\t});\n\t\t\t}\n\n\t\t\tinline auto log_overwriting(Entry&& message) noexcept\n\t\t\t\t-> void requires(ASYNC_POLICY == LogAsyncPolicy::OverwriteWhenFull) {\n\t\t\t\tm_queue.push(std::move(message));\n\t\t\t}\n\n\t\t\tinline auto log_flushing(Entry&& message) noexcept\n\t\t\t\t-> void requires(ASYNC_POLICY == LogAsyncPolicy::FlushWhenFull) {\n\t\t\t\tif(m_queue.full()) {\n\t\t\t\t\tm_flush.store(true);\n\t\t\t\t}\n\n\t\t\t\tconst auto& mess = message;\n\t\t\t\twhile(!m_queue.push(mess)) {\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tinline auto try_read() noexcept -> Result<Entry, QueueError> {\n\t\t\t\treturn m_queue.read();\n\t\t\t}\n\n#if HYPERION_HAS_JTHREAD\n\t\t\t// NOLINTNEXTLINE(readability-function-cognitive-complexity)\n\t\t\tinline auto message_thread_function(const std::stop_token& token) noexcept -> void {\n\t\t\t\twhile(!token.stop_requested()) {\n#else\n\t\t\t// NOLINTNEXTLINE(readability-function-cognitive-complexity)\n\t\t\tinline auto message_thread_function() noexcept -> void {\n\t\t\t\twhile(!m_exit_flag.load()) {\n#endif\n\n\t\t\t\t\tauto res = try_read();\n\t\t\t\t\tif(res) {\n\t\t\t\t\t\tconst auto message = res.unwrap();\n\t\t\t\t\t\tstd::atomic_thread_fence(std::memory_order_acquire);\n\t\t\t\t\t\tstd::for_each(m_sinks.begin(),\n\t\t\t\t\t\t\t\t\t  m_sinks.end(),\n\t\t\t\t\t\t\t\t\t  [&](Sink& sink) noexcept -> void { sink.sink(message); });\n\t\t\t\t\t\tstd::atomic_thread_fence(std::memory_order_release);\n\t\t\t\t\t}\n\n\t\t\t\t\tif(m_flush.load()) {\n\t\t\t\t\t\tm_flush.store(false);\n\t\t\t\t\t\tdo {\n\t\t\t\t\t\t\tauto res2 = m_queue.read();\n\t\t\t\t\t\t\tif(res2) {\n\t\t\t\t\t\t\t\tconst auto message = res2.unwrap();\n\t\t\t\t\t\t\t\tstd::atomic_thread_fence(std::memory_order_acquire);\n\t\t\t\t\t\t\t\tstd::for_each(\n\t\t\t\t\t\t\t\t\tm_sinks.begin(),\n\t\t\t\t\t\t\t\t\tm_sinks.end(),\n\t\t\t\t\t\t\t\t\t[&](Sink& sink) noexcept -> void { sink.sink(message); });\n\t\t\t\t\t\t\t\tstd::atomic_thread_fence(std::memory_order_release);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} while(true);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tdo {\n\t\t\t\t\tauto res2 = m_queue.read();\n\t\t\t\t\tif(res2) {\n\t\t\t\t\t\tconst auto message = res2.unwrap();\n\t\t\t\t\t\tstd::atomic_thread_fence(std::memory_order_acquire);\n\t\t\t\t\t\tstd::for_each(m_sinks.begin(),\n\t\t\t\t\t\t\t\t\t  m_sinks.end(),\n\t\t\t\t\t\t\t\t\t  [&](Sink& sink) noexcept -> void { sink.sink(message); });\n\t\t\t\t\t\tstd::atomic_thread_fence(std::memory_order_release);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} while(true);\n\t\t\t}\n\t\t};\n\n\t\ttemplate<LogLevel MinimumLevel, LogAsyncPolicy AsyncPolicy>\n\t\tclass LogBase<MinimumLevel, LogThreadingPolicy::MultiThreaded, AsyncPolicy> {\n\t\t  public:\n\t\t\tstatic constexpr auto THREADING_POLICY = LogThreadingPolicy::MultiThreaded;\n\t\t\tstatic constexpr auto ASYNC_POLICY = AsyncPolicy;\n\t\t\tstatic constexpr auto MINIMUM_LEVEL = MinimumLevel;\n\n\t\t\tLogBase() : LogBase(create_default_sinks()) {\n\t\t\t}\n\t\t\texplicit LogBase(Sinks&& sinks) noexcept : m_sinks(std::move(sinks)) {\n\t\t\t}\n\t\t\tLogBase(const LogBase&) = delete;\n\t\t\tLogBase(LogBase&&) noexcept = default;\n\t\t\t~LogBase() noexcept = default;\n\n\t\t\ttemplate<LogLevel Level, typename... Args>\n\t\t\tinline auto log(Option<usize> thread_id,\n\t\t\t\t\t\t\tfmt::format_string<Args...>&& format_string,\n\t\t\t\t\t\t\tArgs&&... args) noexcept -> void {\n\t\t\t\tconst auto message = format_entry<Level>(std::move(thread_id),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t std::move(format_string),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t std::forward<Args>(args)...);\n\n\t\t\t\t{\n\t\t\t\t\tauto sinks_guard = m_sinks.write();\n\t\t\t\t\tstd::for_each(sinks_guard->begin(),\n\t\t\t\t\t\t\t\t  sinks_guard->end(),\n\t\t\t\t\t\t\t\t  [&](Sink& sink) noexcept -> void { sink.sink(message); });\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttemplate<LogLevel, typename... Args>\n\t\t\tinline auto\n\t\t\tlog(fmt::format_string<Args...>&& format_string, Args&&... args) noexcept -> void {\n\t\t\t\treturn log(None(), std::move(format_string), std::forward<Args>(args)...);\n\t\t\t}\n\n\t\t\tinline auto flush() const noexcept -> void {\n\t\t\t\t// intentionally does nothing\n\t\t\t}\n\n\t\t\tauto operator=(const LogBase&) -> LogBase& = delete;\n\t\t\tauto operator=(LogBase&&) noexcept -> LogBase& = default;\n\n\t\t  private:\n\t\t\tReadWriteLock<Sinks> m_sinks;\n\t\t};\n\n\t\ttemplate<LogLevel MinimumLevel, LogAsyncPolicy AsyncPolicy, usize QueueSize>\n\t\tclass LogBase<MinimumLevel,\n\t\t\t\t\t  LogThreadingPolicy::MultiThreadedAsync,\n\t\t\t\t\t  AsyncPolicy,\n\t\t\t\t\t  QueueSize> {\n\t\t  public:\n\t\t\tstatic constexpr auto THREADING_POLICY = LogThreadingPolicy::MultiThreadedAsync;\n\t\t\tstatic constexpr auto ASYNC_POLICY = AsyncPolicy;\n\t\t\tstatic constexpr auto MINIMUM_LEVEL = MinimumLevel;\n\t\t\tstatic constexpr usize QUEUE_SIZE = QueueSize;\n\n\t\t\tLogBase() : LogBase(create_default_sinks()) {\n\t\t\t}\n\t\t\texplicit LogBase(Sinks&& sinks) noexcept : m_sinks(std::move(sinks)), m_queue() {\n#if HYPERION_HAS_JTHREAD\n\t\t\t\tm_logging_thread = detail::thread(\n\t\t\t\t\t[&](const std::stop_token& token) { message_thread_function(token); });\n#else\n\t\t\t\tm_logging_thread = detail::thread([&]() { message_thread_function(); });\n#endif\n\t\t\t}\n\t\t\tLogBase(const LogBase&) = delete;\n\t\t\tLogBase(LogBase&& logger) noexcept {\n\t\t\t\tstd::atomic_thread_fence(std::memory_order_seq_cst);\n\t\t\t\tlogger.request_thread_stop();\n\t\t\t\tlogger.m_logging_thread.join();\n\t\t\t\t// NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)\n\t\t\t\tm_sinks = std::move(logger.m_sinks);\n\t\t\t\t// NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)\n\t\t\t\tm_queue = std::move(logger.m_queue);\n#if HYPERION_HAS_JTHREAD\n\t\t\t\tm_logging_thread = detail::thread(\n\t\t\t\t\t[&](const std::stop_token& token) { message_thread_function(token); });\n#else\n\t\t\t\tm_logging_thread = detail::thread([&]() { message_thread_function(); });\n#endif\n\t\t\t\tstd::atomic_thread_fence(std::memory_order_seq_cst);\n\t\t\t}\n\t\t\t~LogBase() noexcept {\n\t\t\t\trequest_thread_stop();\n\t\t\t\tm_logging_thread.join();\n\t\t\t}\n\n\t\t\ttemplate<LogLevel Level, typename... Args>\n\t\t\tinline auto log(Option<usize> thread_id,\n\t\t\t\t\t\t\tfmt::format_string<Args...>&& format_string,\n\t\t\t\t\t\t\tArgs&&... args) noexcept {\n\t\t\t\tif constexpr(Level >= MINIMUM_LEVEL && MINIMUM_LEVEL != LogLevel::DISABLED) {\n\t\t\t\t\tauto message = format_entry<Level>(std::move(thread_id),\n\t\t\t\t\t\t\t\t\t\t\t\t\t   std::move(format_string),\n\t\t\t\t\t\t\t\t\t\t\t\t\t   std::forward<Args>(args)...);\n\t\t\t\t\tif constexpr(ASYNC_POLICY == LogAsyncPolicy::DropWhenFull) {\n\t\t\t\t\t\treturn log_dropping(std::move(message));\n\t\t\t\t\t}\n\t\t\t\t\telse if constexpr(ASYNC_POLICY == LogAsyncPolicy::FlushWhenFull) {\n\t\t\t\t\t\tlog_flushing(std::move(message));\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tlog_overwriting(std::move(message));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tignore(format_string, std::forward<Args>(args)...);\n\t\t\t\t\treturn Err(LoggerError(make_error_code(LoggerErrorCategory::LogLevelError)));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttemplate<LogLevel, typename... Args>\n\t\t\tinline auto log(fmt::format_string<Args...>&& format_string, Args&&... args) noexcept {\n\t\t\t\treturn log(None(), std::move(format_string), std::forward<Args>(args)...);\n\t\t\t}\n\n\t\t\tinline auto flush() noexcept -> void {\n\t\t\t\tm_flush.store(true);\n\t\t\t}\n\n\t\t\tauto operator=(const LogBase&) -> LogBase& = delete;\n\t\t\tauto operator=(LogBase&& logger) noexcept -> LogBase& {\n\t\t\t\tstd::atomic_thread_fence(std::memory_order_seq_cst);\n\t\t\t\tif(this == &logger) {\n\t\t\t\t\treturn *this;\n\t\t\t\t}\n\n\t\t\t\tlogger.request_thread_stop();\n\t\t\t\tlogger.m_logging_thread.join();\n\t\t\t\tm_sinks = std::move(logger.m_sinks);\n\t\t\t\tm_queue = std::move(logger.m_queue);\n\n\t\t\t\tstd::atomic_thread_fence(std::memory_order_seq_cst);\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t  private:\n\t\t\t[[nodiscard]] inline static consteval auto get_queue_policy() noexcept -> QueuePolicy {\n\t\t\t\tif constexpr(ASYNC_POLICY == LogAsyncPolicy::DropWhenFull\n\t\t\t\t\t\t\t || ASYNC_POLICY == LogAsyncPolicy::FlushWhenFull)\n\t\t\t\t{\n\t\t\t\t\treturn QueuePolicy::ErrWhenFull;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\treturn QueuePolicy::OverwriteWhenFull;\n\t\t\t\t}\n\t\t\t}\n\t\t\tusing Queue = LoggingQueue<Entry, get_queue_policy(), QUEUE_SIZE>;\n\n\t\t\tSinks m_sinks;\n\t\t\tQueue m_queue;\n\t\t\tstd::atomic_bool m_flush = false;\n#if !HYPERION_HAS_JTHREAD\n\t\t\tstd::atomic_bool m_exit_flag = false;\n#endif\n\t\t\tdetail::thread m_logging_thread;\n\n\t\t\tinline auto request_thread_stop() noexcept -> void {\n\t\t\t\tstd::atomic_thread_fence(std::memory_order_seq_cst);\n#if HYPERION_HAS_JTHREAD\n\t\t\t\tignore(m_logging_thread.request_stop());\n#else\n\t\t\t\tm_exit_flag.store(true);\n#endif\n\t\t\t\tstd::atomic_thread_fence(std::memory_order_seq_cst);\n\t\t\t}\n\n\t\t\tinline auto log_dropping(Entry&& message) noexcept -> Result<bool, LoggerError>\n\t\t\trequires(ASYNC_POLICY == LogAsyncPolicy::DropWhenFull) {\n\t\t\t\tstd::atomic_thread_fence(std::memory_order_seq_cst);\n\t\t\t\tauto res = m_queue.push(std::move(message))\n\t\t\t\t\t\t\t   .map_err([]([[maybe_unused]] const QueueError& error) {\n\t\t\t\t\t\t\t\t   return LoggerError(LoggerErrorCategory::QueueingError);\n\t\t\t\t\t\t\t   });\n\t\t\t\tstd::atomic_thread_fence(std::memory_order_seq_cst);\n\t\t\t\treturn res;\n\t\t\t}\n\n\t\t\tinline auto log_overwriting(Entry&& message) noexcept\n\t\t\t\t-> void requires(ASYNC_POLICY == LogAsyncPolicy::OverwriteWhenFull) {\n\t\t\t\tstd::atomic_thread_fence(std::memory_order_seq_cst);\n\t\t\t\tm_queue.push(std::move(message));\n\t\t\t\tstd::atomic_thread_fence(std::memory_order_seq_cst);\n\t\t\t}\n\n\t\t\tinline auto log_flushing(Entry&& message) noexcept\n\t\t\t\t-> void requires(ASYNC_POLICY == LogAsyncPolicy::FlushWhenFull) {\n\t\t\t\tstd::atomic_thread_fence(std::memory_order_seq_cst);\n\t\t\t\tif(m_queue.full()) {\n\t\t\t\t\tm_flush.store(true);\n\t\t\t\t}\n\n\t\t\t\tconst auto& mess = message;\n\t\t\t\twhile(!m_queue.push(mess)) {\n\t\t\t\t}\n\t\t\t\tstd::atomic_thread_fence(std::memory_order_seq_cst);\n\t\t\t}\n\n\t\t\tinline auto try_read() noexcept -> Result<Entry, QueueError> {\n\t\t\t\tstd::atomic_thread_fence(std::memory_order_seq_cst);\n\t\t\t\treturn m_queue.read();\n\t\t\t}\n\n#if HYPERION_HAS_JTHREAD\n\t\t\t// NOLINTNEXTLINE(readability-function-cognitive-complexity)\n\t\t\tinline auto message_thread_function(const std::stop_token& token) noexcept -> void {\n\t\t\t\twhile(!token.stop_requested()) {\n#else\n\t\t\t// NOLINTNEXTLINE(readability-function-cognitive-complexity)\n\t\t\tinline auto message_thread_function() noexcept -> void {\n\t\t\t\twhile(!m_exit_flag.load()) {\n#endif\n\n\t\t\t\t\tauto res = try_read();\n\t\t\t\t\tif(res) {\n\t\t\t\t\t\tstd::atomic_thread_fence(std::memory_order_seq_cst);\n\t\t\t\t\t\tconst auto message = res.unwrap();\n\t\t\t\t\t\tstd::for_each(m_sinks.begin(),\n\t\t\t\t\t\t\t\t\t  m_sinks.end(),\n\t\t\t\t\t\t\t\t\t  [&](Sink& sink) noexcept -> void { sink.sink(message); });\n\t\t\t\t\t\tstd::atomic_thread_fence(std::memory_order_seq_cst);\n\t\t\t\t\t}\n\n\t\t\t\t\tif(m_flush.load()) {\n\t\t\t\t\t\tm_flush.store(false);\n\t\t\t\t\t\tdo {\n\t\t\t\t\t\t\tstd::atomic_thread_fence(std::memory_order_seq_cst);\n\t\t\t\t\t\t\tauto res2 = m_queue.read();\n\t\t\t\t\t\t\tif(res2) {\n\t\t\t\t\t\t\t\tconst auto message = res2.unwrap();\n\t\t\t\t\t\t\t\tstd::for_each(\n\t\t\t\t\t\t\t\t\tm_sinks.begin(),\n\t\t\t\t\t\t\t\t\tm_sinks.end(),\n\t\t\t\t\t\t\t\t\t[&](Sink& sink) noexcept -> void { sink.sink(message); });\n\t\t\t\t\t\t\t\tstd::atomic_thread_fence(std::memory_order_seq_cst);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tstd::atomic_thread_fence(std::memory_order_seq_cst);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} while(true);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tdo {\n\t\t\t\t\tstd::atomic_thread_fence(std::memory_order_seq_cst);\n\t\t\t\t\tauto res2 = m_queue.read();\n\t\t\t\t\tif(res2) {\n\t\t\t\t\t\tconst auto message = res2.unwrap();\n\t\t\t\t\t\tstd::for_each(m_sinks.begin(),\n\t\t\t\t\t\t\t\t\t  m_sinks.end(),\n\t\t\t\t\t\t\t\t\t  [&](Sink& sink) noexcept -> void { sink.sink(message); });\n\t\t\t\t\t\tstd::atomic_thread_fence(std::memory_order_seq_cst);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tstd::atomic_thread_fence(std::memory_order_seq_cst);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} while(true);\n\t\t\t}\n\t\t};\n\t} // namespace detail\n\n\t/// @brief Hyperion logging type for formatted logging.\n\t/// Uses fmtlib/fmt for entry formatting and stylizing\n\t///\n\t/// @tparam LogParameters - The parameters for how this logger should operate\n\ttemplate<LoggerParametersType LogParameters = DefaultLogParameters>\n\tclass Logger : public detail::LogBase<LogParameters::minimum_level,\n\t\t\t\t\t\t\t\t\t\t  LogParameters::threading_policy,\n\t\t\t\t\t\t\t\t\t\t  LogParameters::async_policy,\n\t\t\t\t\t\t\t\t\t\t  LogParameters::queue_size> {\n\t  public:\n\t\tstatic constexpr LogThreadingPolicy THREADING_POLICY = LogParameters::threading_policy;\n\t\tstatic constexpr LogAsyncPolicy ASYNC_POLICY = LogParameters::async_policy;\n\t\tstatic constexpr LogLevel MINIMUM_LEVEL = LogParameters::minimum_level;\n\t\tstatic constexpr usize QUEUE_SIZE = LogParameters::queue_size;\n\t\tusing LogBase = detail::LogBase<LogParameters::minimum_level,\n\t\t\t\t\t\t\t\t\t\tLogParameters::threading_policy,\n\t\t\t\t\t\t\t\t\t\tLogParameters::async_policy,\n\t\t\t\t\t\t\t\t\t\tLogParameters::queue_size>;\n\n\t\tLogger() = default;\n\t\texplicit Logger(Sinks&& sinks) noexcept : LogBase(std::move(sinks)) {\n\t\t}\n\t\tLogger(const Logger& logger) noexcept = delete;\n\t\tLogger(Logger&& logger) noexcept = default;\n\n\t\t~Logger() noexcept = default;\n\n\t\ttemplate<typename... Args>\n\t\tinline auto message(const Option<usize>& thread_id,\n\t\t\t\t\t\t\tfmt::format_string<Args...>&& format_string,\n\t\t\t\t\t\t\tArgs&&... args) noexcept {\n\t\t\treturn this->template log<LogLevel::MESSAGE>(thread_id,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t std::move(format_string),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t std::forward<Args>(args)...);\n\t\t}\n\n\t\ttemplate<typename... Args>\n\t\tinline auto message(fmt::format_string<Args...>&& format_string, Args&&... args) noexcept {\n\t\t\treturn message(None(), std::move(format_string), std::forward<Args>(args)...);\n\t\t}\n\n\t\ttemplate<typename... Args>\n\t\tinline auto trace(const Option<usize>& thread_id,\n\t\t\t\t\t\t  fmt::format_string<Args...>&& format_string,\n\t\t\t\t\t\t  Args&&... args) noexcept {\n\t\t\treturn this->template log<LogLevel::TRACE>(thread_id,\n\t\t\t\t\t\t\t\t\t\t\t\t\t   std::move(format_string),\n\t\t\t\t\t\t\t\t\t\t\t\t\t   std::forward<Args>(args)...);\n\t\t}\n\n\t\ttemplate<typename... Args>\n\t\tinline auto trace(fmt::format_string<Args...>&& format_string, Args&&... args) noexcept {\n\t\t\treturn trace(None(), std::move(format_string), std::forward<Args>(args)...);\n\t\t}\n\n\t\ttemplate<typename... Args>\n\t\tinline auto info(const Option<usize>& thread_id,\n\t\t\t\t\t\t fmt::format_string<Args...>&& format_string,\n\t\t\t\t\t\t Args&&... args) noexcept {\n\t\t\treturn this->template log<LogLevel::INFO>(thread_id,\n\t\t\t\t\t\t\t\t\t\t\t\t\t  std::move(format_string),\n\t\t\t\t\t\t\t\t\t\t\t\t\t  std::forward<Args>(args)...);\n\t\t}\n\n\t\ttemplate<typename... Args>\n\t\tinline auto info(fmt::format_string<Args...>&& format_string, Args&&... args) noexcept {\n\t\t\treturn info(None(), std::move(format_string), std::forward<Args>(args)...);\n\t\t}\n\n\t\ttemplate<typename... Args>\n\t\tinline auto warn(const Option<usize>& thread_id,\n\t\t\t\t\t\t fmt::format_string<Args...>&& format_string,\n\t\t\t\t\t\t Args&&... args) noexcept {\n\t\t\treturn this->template log<LogLevel::WARN>(thread_id,\n\t\t\t\t\t\t\t\t\t\t\t\t\t  std::move(format_string),\n\t\t\t\t\t\t\t\t\t\t\t\t\t  std::forward<Args>(args)...);\n\t\t}\n\n\t\ttemplate<typename... Args>\n\t\tinline auto warn(fmt::format_string<Args...>&& format_string, Args&&... args) noexcept {\n\t\t\treturn warn(None(), std::move(format_string), std::forward<Args>(args)...);\n\t\t}\n\n\t\ttemplate<typename... Args>\n\t\tinline auto error(const Option<usize>& thread_id,\n\t\t\t\t\t\t  fmt::format_string<Args...>&& format_string,\n\t\t\t\t\t\t  Args&&... args) noexcept {\n\t\t\treturn this->template log<LogLevel::ERROR>(thread_id,\n\t\t\t\t\t\t\t\t\t\t\t\t\t   std::move(format_string),\n\t\t\t\t\t\t\t\t\t\t\t\t\t   std::forward<Args>(args)...);\n\t\t}\n\n\t\ttemplate<typename... Args>\n\t\tinline auto error(fmt::format_string<Args...>&& format_string, Args&&... args) noexcept {\n\t\t\treturn error(None(), std::move(format_string), std::forward<Args>(args)...);\n\t\t}\n\n\t\tauto operator=(const Logger& logger) noexcept -> Logger& = delete;\n\t\tauto operator=(Logger&& logger) noexcept -> Logger& = default;\n\t};\n\tIGNORE_PADDING_STOP\n\n\tIGNORE_UNUSED_TEMPLATES_START\n\n#ifndef HYPERION_LOG_GLOBAL_LOGGER_PARAMETERS\n\t// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)\n\t#define HYPERION_LOG_GLOBAL_LOGGER_PARAMETERS DefaultLogParameters\n#endif\n\n\tstruct GlobalLog {\n\t\tusing Parameters = HYPERION_LOG_GLOBAL_LOGGER_PARAMETERS;\n\t\tstatic UniquePtr<Logger<Parameters>> GLOBAL_LOGGER; // NOLINT\n\n\t\t[[nodiscard]] inline static auto\n\t\tget_global_logger() noexcept -> Result<Logger<Parameters>*, LoggerError> {\n\t\t\tif(GLOBAL_LOGGER == nullptr) {\n\t\t\t\treturn Err(LoggerError(LoggerErrorCategory::LoggerNotInitialized));\n\t\t\t}\n\t\t\treturn Ok(GLOBAL_LOGGER.get());\n\t\t}\n\n\t\tinline static auto set_global_logger(Logger<Parameters>&& logger) noexcept -> void {\n\t\t\tGLOBAL_LOGGER = make_unique<Logger<Parameters>>(std::move(logger));\n\t\t}\n\n\t\ttemplate<typename... Args>\n\t\tinline static auto MESSAGE(const Option<usize>& thread_id,\n\t\t\t\t\t\t\t\t   fmt::format_string<Args...>&& format_string,\n\t\t\t\t\t\t\t\t   Args&&... args) noexcept {\n\t\t\treturn get_global_logger()\n\t\t\t\t.expect(\"Global Logger not initialized!\")\n\t\t\t\t->message(thread_id, std::move(format_string), std::forward<Args>(args)...);\n\t\t}\n\n\t\ttemplate<typename... Args>\n\t\tinline static auto\n\t\tMESSAGE(fmt::format_string<Args...>&& format_string, Args&&... args) noexcept {\n\t\t\treturn MESSAGE(None(), std::move(format_string), std::forward<Args>(args)...);\n\t\t}\n\n\t\ttemplate<typename... Args>\n\t\tinline static auto TRACE(const Option<usize>& thread_id,\n\t\t\t\t\t\t\t\t fmt::format_string<Args...>&& format_string,\n\t\t\t\t\t\t\t\t Args&&... args) noexcept {\n\t\t\treturn get_global_logger()\n\t\t\t\t.expect(\"Global Logger not initialized!\")\n\t\t\t\t->trace(thread_id, std::move(format_string), std::forward<Args>(args)...);\n\t\t}\n\n\t\ttemplate<typename... Args>\n\t\tinline static auto\n\t\tTRACE(fmt::format_string<Args...>&& format_string, Args&&... args) noexcept {\n\t\t\treturn TRACE(None(), std::move(format_string), std::forward<Args>(args)...);\n\t\t}\n\n\t\ttemplate<typename... Args>\n\t\tinline static auto INFO(const Option<usize>& thread_id,\n\t\t\t\t\t\t\t\tfmt::format_string<Args...>&& format_string,\n\t\t\t\t\t\t\t\tArgs&&... args) noexcept {\n\t\t\treturn get_global_logger()\n\t\t\t\t.expect(\"Global Logger not initialized!\")\n\t\t\t\t->info(thread_id, std::move(format_string), std::forward<Args>(args)...);\n\t\t}\n\n\t\ttemplate<typename... Args>\n\t\tinline static auto\n\t\tINFO(fmt::format_string<Args...>&& format_string, Args&&... args) noexcept {\n\t\t\treturn INFO(None(), std::move(format_string), std::forward<Args>(args)...);\n\t\t}\n\n\t\ttemplate<typename... Args>\n\t\tinline static auto WARN(const Option<usize>& thread_id,\n\t\t\t\t\t\t\t\tfmt::format_string<Args...>&& format_string,\n\t\t\t\t\t\t\t\tArgs&&... args) noexcept {\n\t\t\treturn get_global_logger()\n\t\t\t\t.expect(\"Global Logger not initialized!\")\n\t\t\t\t->warn(thread_id, std::move(format_string), std::forward<Args>(args)...);\n\t\t}\n\n\t\ttemplate<typename... Args>\n\t\tinline static auto\n\t\tWARN(fmt::format_string<Args...>&& format_string, Args&&... args) noexcept {\n\t\t\treturn WARN(None(), std::move(format_string), std::forward<Args>(args)...);\n\t\t}\n\n\t\ttemplate<typename... Args>\n\t\tinline static auto ERROR(const Option<usize>& thread_id,\n\t\t\t\t\t\t\t\t fmt::format_string<Args...>&& format_string,\n\t\t\t\t\t\t\t\t Args&&... args) noexcept {\n\t\t\treturn get_global_logger()\n\t\t\t\t.expect(\"Global Logger not initialized!\")\n\t\t\t\t->error(thread_id, std::move(format_string), std::forward<Args>(args)...);\n\t\t}\n\n\t\ttemplate<typename... Args>\n\t\tinline static auto\n\t\tERROR(fmt::format_string<Args...>&& format_string, Args&&... args) noexcept {\n\t\t\treturn ERROR(None(), std::move(format_string), std::forward<Args>(args)...);\n\t\t}\n\t};\n\n\tUniquePtr<Logger<GlobalLog::Parameters>> GlobalLog::GLOBAL_LOGGER = nullptr; // NOLINT\n\n\ttemplate<typename... Args>\n\tinline auto MESSAGE(const Option<usize>& thread_id,\n\t\t\t\t\t\tfmt::format_string<Args...>&& format_string,\n\t\t\t\t\t\tArgs&&... args) noexcept {\n\t\treturn GlobalLog::MESSAGE(thread_id, std::move(format_string), std::forward<Args>(args)...);\n\t}\n\n\ttemplate<typename... Args>\n\tinline static auto\n\tMESSAGE(fmt::format_string<Args...>&& format_string, Args&&... args) noexcept {\n\t\treturn GlobalLog::MESSAGE(None(), std::move(format_string), std::forward<Args>(args)...);\n\t}\n\n\ttemplate<typename... Args>\n\tinline static auto TRACE(const Option<usize>& thread_id,\n\t\t\t\t\t\t\t fmt::format_string<Args...>&& format_string,\n\t\t\t\t\t\t\t Args&&... args) noexcept {\n\t\treturn GlobalLog::TRACE(thread_id, std::move(format_string), std::forward<Args>(args)...);\n\t}\n\n\ttemplate<typename... Args>\n\tinline static auto TRACE(fmt::format_string<Args...>&& format_string, Args&&... args) noexcept {\n\t\treturn GlobalLog::TRACE(None(), std::move(format_string), std::forward<Args>(args)...);\n\t}\n\n\ttemplate<typename... Args>\n\tinline auto INFO(const Option<usize>& thread_id,\n\t\t\t\t\t fmt::format_string<Args...>&& format_string,\n\t\t\t\t\t Args&&... args) noexcept {\n\t\treturn GlobalLog::INFO(thread_id, std::move(format_string), std::forward<Args>(args)...);\n\t}\n\n\ttemplate<typename... Args>\n\tinline auto INFO(fmt::format_string<Args...>&& format_string, Args&&... args) noexcept {\n\t\treturn GlobalLog::INFO(None(), std::move(format_string), std::forward<Args>(args)...);\n\t}\n\n\ttemplate<typename... Args>\n\tinline auto WARN(const Option<usize>& thread_id,\n\t\t\t\t\t fmt::format_string<Args...>&& format_string,\n\t\t\t\t\t Args&&... args) noexcept {\n\t\treturn GlobalLog::WARN(thread_id, std::move(format_string), std::forward<Args>(args)...);\n\t}\n\n\ttemplate<typename... Args>\n\tinline auto WARN(fmt::format_string<Args...>&& format_string, Args&&... args) noexcept {\n\t\treturn GlobalLog::WARN(None(), std::move(format_string), std::forward<Args>(args)...);\n\t}\n\n\ttemplate<typename... Args>\n\tinline auto ERROR(const Option<usize>& thread_id,\n\t\t\t\t\t  fmt::format_string<Args...>&& format_string,\n\t\t\t\t\t  Args&&... args) noexcept {\n\t\treturn GlobalLog::ERROR(thread_id, std::move(format_string), std::forward<Args>(args)...);\n\t}\n\n\ttemplate<typename... Args>\n\tinline auto ERROR(fmt::format_string<Args...>&& format_string, Args&&... args) noexcept {\n\t\treturn GlobalLog::ERROR(None(), std::move(format_string), std::forward<Args>(args)...);\n\t}\n\n\tIGNORE_UNUSED_TEMPLATES_STOP\n} // namespace hyperion\n", "meta": {"hexsha": "a8a83c2a7ff9868dacf75122bb340d3dc24bd5cd", "size": 35075, "ext": "h", "lang": "C", "max_stars_repo_path": "include/Hyperion/Logger.h", "max_stars_repo_name": "braxtons12/Hyperion-Utils", "max_stars_repo_head_hexsha": "3873a116e2ea76fc74c9c056925f3740eee6dcd8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/Hyperion/Logger.h", "max_issues_repo_name": "braxtons12/Hyperion-Utils", "max_issues_repo_head_hexsha": "3873a116e2ea76fc74c9c056925f3740eee6dcd8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/Hyperion/Logger.h", "max_forks_repo_name": "braxtons12/Hyperion-Utils", "max_forks_repo_head_hexsha": "3873a116e2ea76fc74c9c056925f3740eee6dcd8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1196498054, "max_line_length": 99, "alphanum_fraction": 0.6805702067, "num_tokens": 8604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.0850990542883219, "lm_q2_score": 0.027169234095729248, "lm_q1q2_score": 0.0023120761272845897}}
{"text": "#pragma once\n#include <gsl/gsl>\n#include <map>\n#include \"halley/text/halleystring.h\"\n#include \"halley/maths/vector4.h\"\n\nnamespace Halley\n{\n\tclass Path;\n\tclass Image;\n\tstruct ImageData;\n\n\tclass AsepriteExternalReader\n\t{\n\tpublic:\n\t\tstatic std::vector<ImageData> importAseprite(String baseName, gsl::span<const gsl::byte> fileData, bool trim);\n\n\tprivate:\n\t\tstatic std::vector<ImageData> loadImagesFromPath(Path tmp, bool crop);\n\t\tstatic std::map<int, int> getSpriteDurations(Path jsonPath);\n\t\tstatic void processFrameData(String baseName, std::vector<ImageData>& frameData, std::map<int, int> durations);\n\t};\n\n\tclass AsepriteReader\n\t{\n\tpublic:\n\t\tstatic std::vector<ImageData> importAseprite(String baseName, gsl::span<const gsl::byte> fileData, bool trim);\n\t};\n}\n", "meta": {"hexsha": "9af78cc8effd03a4dacee0de80924dd5eb5b6f9d", "size": 760, "ext": "h", "lang": "C", "max_stars_repo_path": "src/tools/tools/src/sprites/aseprite_reader.h", "max_stars_repo_name": "lye/halley", "max_stars_repo_head_hexsha": "16b6c9783e4b21377f902a9d02366c1f19450a21", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tools/tools/src/sprites/aseprite_reader.h", "max_issues_repo_name": "lye/halley", "max_issues_repo_head_hexsha": "16b6c9783e4b21377f902a9d02366c1f19450a21", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tools/tools/src/sprites/aseprite_reader.h", "max_forks_repo_name": "lye/halley", "max_forks_repo_head_hexsha": "16b6c9783e4b21377f902a9d02366c1f19450a21", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3333333333, "max_line_length": 113, "alphanum_fraction": 0.75, "num_tokens": 200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12085323882332893, "lm_q2_score": 0.019124035493046376, "lm_q1q2_score": 0.0023112016287069525}}
{"text": "/*\n   Copyright [2021] [IBM Corporation]\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n       http://www.apache.org/licenses/LICENSE-2.0\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\n#ifndef __MM_PLUGIN_ITF_H__\n#define __MM_PLUGIN_ITF_H__\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-variable\"\n#pragma GCC diagnostic ignored \"-Wunused-parameter\"\n#pragma GCC diagnostic ignored \"-Wunused-function\"\n\n#define PUBLIC __attribute__((__visibility__(\"default\")))\n\n#if defined(__cplusplus)\n#pragma GCC diagnostic ignored \"-Weffc++\"\n#include <common/byte_span.h>\n#include <gsl/span>\n#include <functional>\n#endif\n\n#include <stdlib.h>\n#include <assert.h>\n\n#if defined(__cplusplus)\nextern \"C\"\n{\n#endif\n\n  typedef int status_t;\n  typedef void * mm_plugin_heap_t;\n  typedef void (*request_memory_callback_t)(void * param, size_t alignment, size_t size_hint, void * addr_hint);\n  typedef void (*release_memory_callback_t)(void * param, void * addr, size_t size);\n\n  /** \n   * Initialize mm library\n   * \n   * @return S_OK, E_FAIL\n   */\n  status_t mm_plugin_init();\n\n  /** \n   * Create a heap instance\n   * \n   * @param params Constructor parameters (e.g., JSON)\n   * @param root_ptr Root point for persistent heaps\n   * @param out_heap Heap context \n   * \n   * @return S_OK, E_FAIL\n   */\n  status_t mm_plugin_create(const char * params,\n                            void * root_ptr,\n                            mm_plugin_heap_t * out_heap);\n\n  /** \n   * Delete a heap instance\n   * \n   * @param heap Heap context to destroy\n   * \n   * @return S_OK, E_INVAL, E_FAIL\n   */\n  status_t mm_plugin_destroy(mm_plugin_heap_t heap);\n  \n  /** \n   * Add (slab) region of memory to fuel the allocator.  The passthru\n   * allocator does not need this as it takes directly from the OS.\n   * \n   * @param heap Heap context\n   * @param region_base Pointer to beginning of region\n   * @param region_size Region length in bytes\n   * \n   * @return E_NOT_IMPL, S_OK, E_FAIL, E_INVAL\n   */\n  status_t mm_plugin_add_managed_region(mm_plugin_heap_t heap,\n                                        void * region_base,\n                                        size_t region_size);\n  \n  /** \n   * Query memory regions being used by the allocator\n   * \n   * @param heap Heap context\n   * @param region_id Index counting from 0\n   * @param [out] Base address of region\n   * @param [out] Size of region in bytes\n   * \n   * @return S_MORE (continue to next region id), S_OK (done), E_INVAL\n   */  \n  status_t mm_plugin_query_managed_region(mm_plugin_heap_t heap,\n                                          unsigned region_id,\n                                          void** out_region_base,\n                                          size_t* out_region_size);\n  \n  /** \n   * Register callback the allocator can use to request more memory\n   * \n   * @param heap Heap context\n   * @param callback Call back function pointer\n   * @param param Optional parameter which will be pass to callback function\n   * \n   * @return E_NOT_IMPL, S_OK\n   */\n  status_t mm_plugin_register_callback_request_memory(mm_plugin_heap_t heap,\n                                                      request_memory_callback_t callback,\n                                                      void * param);\n  \n  /** \n   * Allocate a region of memory without alignment or hint\n   * \n   * @param heap Heap context\n   * @param Length in bytes\n   * @param [out] Pointer to allocated region\n   *\n   * @return S_OK or E_FAIL\n   */\n  status_t mm_plugin_allocate(mm_plugin_heap_t heap, size_t n, void ** out_ptr);\n  \n  /** \n   * Allocation region of memory that is aligned\n   * \n   * @param heap Heap context\n   * @param n Size of region in bytes\n   * @param alignment Alignment in bytes\n   * @param out_ptr Address if [in] nullptr, [out] pointer to allocated region\n   * \n   * @return S_OK, E_FAIL, E_INVAL (depending on implementation)\n   */\n  status_t mm_plugin_aligned_allocate(mm_plugin_heap_t heap, size_t n, size_t alignment, void ** out_ptr);\n  \n  /** \n   * Special case for EASTL\n   * \n   * @param heap Heap context\n   * @param n Size of region in bytes\n   * @param alignment Alignment in bytes\n   * @param offset Offset from start of region to location within region which satisfies alignment\n   * @param out_ptr Address if [in] nullptr, [out] pointer to allocated region\n   * \n   * @return \n   */\n  status_t mm_plugin_aligned_allocate_offset(mm_plugin_heap_t heap, size_t n, size_t alignment, size_t offset, void ** out_ptr);\n\n  /** \n   * Free a previously allocated region of memory with length known\n   * \n   * @param heap Heap context\n   * @param ptr Address of [in] pointer to previously allocated region, [out] nullptr\n   * @param size Length of region in bytes\n   *\n   * @return S_OK or E_INVAL;\n   */\n  status_t mm_plugin_deallocate(mm_plugin_heap_t heap, void ** ptr, size_t size);\n\n  /** \n   * Free previously allocated region without known length\n   * \n   * @param heap Heap context\n   * @param ptr Address of [in] pointer to previously allocated region, [out] nullptr\n   * \n   * @return S_OK\n   */\n  status_t mm_plugin_deallocate_without_size(mm_plugin_heap_t heap, void ** ptr);\n\n  /** \n   * Allocate region and zero memory\n   * \n   * @param heap Heap context\n   * @param size Size of region in bytes\n   * @param ptr [out] Pointer to allocated region\n   * \n   * @return S_OK\n   */\n  status_t mm_plugin_callocate(mm_plugin_heap_t heap, size_t n, void ** out_ptr);\n\n  /*\n    The POSIX realloc() function changes the size of the memory block pointed\n    to by ptr to size bytes.  The contents will be unchanged in the\n    range from the start of the region up to the minimum of the old and\n    new sizes.  If the new size is larger than the old size, the added\n    memory will not be initialized.  If ptr is NULL, then the call is\n    equivalent to malloc(size), for all values of size; if size is equal\n    to zero, and ptr is not NULL, then the call is equivalent to\n    free(ptr).  Unless ptr is NULL, it must have been returned by an\n    earlier call to malloc(), calloc(), or realloc().  If the area\n    pointed to was moved, a free(ptr) is done.\n  */\n\n  /** \n   * Resize an existing allocation\n   * \n   * @param heap Heap context\n   * @param in_out_ptr Address of pointer to [in] existing allocated region, [out] new reallocated region or null if unable to reallocate\n   * @param size New size in bytes\n   *\n   * \n   * @return S_OK\n   */\n  status_t mm_plugin_reallocate(mm_plugin_heap_t heap, void ** in_out_ptr, size_t size);\n\n  /** \n   * Get the number of usable bytes in block pointed to by ptr.  The\n   * allocator *may* not have this information and should then return\n   * E_NOT_IMPL. Returned size may be larger than requested allocation\n   * \n   * @param heap Heap context\n   * @param ptr Pointer to block base\n   * @param out_ptr [out] Number of bytes in allocated block\n   * \n   * @return S_OK, E_NOT_IMPL\n   */\n  status_t mm_plugin_usable_size(mm_plugin_heap_t heap, void * ptr, size_t * out_size);\n\n\n  /** \n   * Inject an allocation back into the allocator (reconstituing)\n   * \n   * @param heap Heap context\n   * @param ptr Pointer to region of memory to mark allocated\n   * @param size Size of region in bytes\n   * \n   * @return S_OK, E_NOT_IMPL\n   */\n  status_t mm_plugin_inject_allocation(mm_plugin_heap_t heap, void * ptr, size_t size);\n\n  /**\n   * Report bytes remaining\n   *\n   * @param bytes_remaining Bytes remaining for allocation\n   *\n   * @return S_OK, E_NOT_IMPL\n   */\n  status_t mm_plugin_bytes_remaining(mm_plugin_heap_t heap, size_t *bytes_remaining);\n\n  /** \n   * Get debugging information\n   * \n   * @param heap Heap context\n   */\n  void mm_plugin_debug(mm_plugin_heap_t heap);\n\n  /**\n   * Check for crash consistency libccpm behavior)\n   *\n   * @return non-zero iff the root_ptr parameter of mm_plugin_create is interpreted as a struct ccpm_params *.\n   */\n  int mm_plugin_is_crash_consistent(mm_plugin_heap_t heap);\n\n  /**\n   * Check for inject_allocation capability\n   *\n   * @return non-zero iff mm_plugin_inject_allocation is implemented\n   */\n  int mm_plugin_can_inject_allocation(mm_plugin_heap_t heap);\n\n  /** \n   * Function pointer table for all methods\n   * \n   */\n  typedef struct tag_mm_plugin_function_table_t\n  {\n    status_t (*mm_plugin_init)();\n    status_t (*mm_plugin_create)(const char * params, void * root_ptr\n\t\t\t, mm_plugin_heap_t * out_heap);\n    status_t (*mm_plugin_destroy)(mm_plugin_heap_t heap);\n    status_t (*mm_plugin_add_managed_region)(mm_plugin_heap_t heap,\n                                             void * region_base,\n                                             size_t region_size);\n    status_t (*mm_plugin_query_managed_region)(mm_plugin_heap_t heap,\n                                               unsigned region_id,\n                                               void** out_region_base,\n                                               size_t* out_region_size);\n    status_t (*mm_plugin_register_callback_request_memory)(mm_plugin_heap_t heap,\n                                                           request_memory_callback_t callback,\n                                                           void * param);\n    status_t (*mm_plugin_allocate)(mm_plugin_heap_t heap, size_t n, void ** out_ptr);\n    status_t (*mm_plugin_aligned_allocate)(mm_plugin_heap_t heap, size_t n, size_t alignment, void ** out_ptr);\n    status_t (*mm_plugin_aligned_allocate_offset)(mm_plugin_heap_t heap, size_t n, size_t alignment, size_t offset, void ** out_ptr);\n    status_t (*mm_plugin_deallocate)(mm_plugin_heap_t heap, void ** ptr, size_t size);\n    status_t (*mm_plugin_deallocate_without_size)(mm_plugin_heap_t heap, void ** ptr);\n    status_t (*mm_plugin_callocate)(mm_plugin_heap_t heap, size_t n, void ** out_ptr);\n    status_t (*mm_plugin_reallocate)(mm_plugin_heap_t heap, void ** in_out_ptr, size_t size);\n    status_t (*mm_plugin_usable_size)(mm_plugin_heap_t heap, void * ptr, size_t * out_size);\n    status_t (*mm_plugin_bytes_remaining)(mm_plugin_heap_t heap, size_t * bytes_remaining);\n    void     (*mm_plugin_debug)(mm_plugin_heap_t heap);\n    status_t (*mm_plugin_inject_allocation)(mm_plugin_heap_t heap, void * ptr, size_t size);\n    int (*mm_plugin_is_crash_consistent)(mm_plugin_heap_t heap);\n    int (*mm_plugin_can_inject_allocation)(mm_plugin_heap_t heap);\n  } mm_plugin_function_table_t;\n\n#if defined(__cplusplus)\n}\n#endif  \n\n\n#if defined(__cplusplus)\n\n#include <dlfcn.h>\n#include <string>\n#include <stdio.h>\n#include <stdexcept>\n\n#define LOAD_SYMBOL(X) _ft.X = reinterpret_cast<decltype(_ft.X)>(dlsym(_module, # X)); assert(_ft.X)\n\n/** \n * C++ wrapper on C-based plugin API\n * \n */\nclass MM_plugin_wrapper\n{\npublic:\n    \n  MM_plugin_wrapper(const std::string& plugin_path,\n                    const std::string& config = \"\",\n                    void * root_ptr = nullptr)\n  {\n    assert(plugin_path.empty() == false);\n    _module = dlopen(plugin_path.c_str(), RTLD_NOW | RTLD_NODELETE); // RTLD_DEEPBIND | \n    if(_module == nullptr) {\n      char err[1024];\n      sprintf(err, \"%s\\n\", dlerror());\n      throw std::invalid_argument(err);\n    }\n\n    LOAD_SYMBOL(mm_plugin_init);\n    LOAD_SYMBOL(mm_plugin_create);\n    LOAD_SYMBOL(mm_plugin_add_managed_region);\n    LOAD_SYMBOL(mm_plugin_query_managed_region);\n    LOAD_SYMBOL(mm_plugin_register_callback_request_memory);\n    LOAD_SYMBOL(mm_plugin_allocate);\n    LOAD_SYMBOL(mm_plugin_aligned_allocate);\n    LOAD_SYMBOL(mm_plugin_aligned_allocate_offset);\n    LOAD_SYMBOL(mm_plugin_deallocate);\n    LOAD_SYMBOL(mm_plugin_deallocate_without_size);\n    LOAD_SYMBOL(mm_plugin_callocate);\n    LOAD_SYMBOL(mm_plugin_reallocate);\n    LOAD_SYMBOL(mm_plugin_usable_size);\n    LOAD_SYMBOL(mm_plugin_debug);\n    LOAD_SYMBOL(mm_plugin_destroy);\n    LOAD_SYMBOL(mm_plugin_inject_allocation);\n    LOAD_SYMBOL(mm_plugin_bytes_remaining);\n    LOAD_SYMBOL(mm_plugin_is_crash_consistent);\n    LOAD_SYMBOL(mm_plugin_can_inject_allocation);\n\n    //      dlclose(_module);\n      \n    /* create heap instance */      \n    _ft.mm_plugin_create(config.c_str(), root_ptr, &_heap);\n  }\n\n  MM_plugin_wrapper(const MM_plugin_wrapper &) = delete;\n\n  MM_plugin_wrapper(MM_plugin_wrapper && other) noexcept\n    : _module(std::move(other._module))\n    , _ft(std::move(other._ft))\n    , _heap(std::move(other._heap))\n  {\n    other._heap = nullptr;\n  }\n\n  virtual ~MM_plugin_wrapper() noexcept {\n    if ( _heap )\n    {\n      _ft.mm_plugin_destroy(_heap);\n    }\n  }\n\n  /* forwarding in liners */\n  inline status_t init() noexcept {\n    return _ft.mm_plugin_init();\n  }\n\n  inline status_t add_managed_region(void * region_base, size_t region_size) noexcept {\n    return _ft.mm_plugin_add_managed_region(_heap, region_base, region_size);\n  }\n\n  inline status_t query_managed_region(unsigned region_id, void** out_region_base, size_t* out_region_size) noexcept {\n    return _ft.mm_plugin_query_managed_region(_heap, region_id, out_region_base, out_region_size);\n  }\n    \n  inline status_t register_callback_request_memory(request_memory_callback_t callback, void * param) noexcept {\n    return _ft.mm_plugin_register_callback_request_memory(_heap, callback, param);\n  }\n    \n  inline status_t allocate(size_t n, void ** out_ptr) noexcept {\n    return _ft.mm_plugin_allocate(_heap, n, out_ptr);\n  }\n    \n  inline status_t aligned_allocate(size_t n, size_t alignment, void ** out_ptr) noexcept {\n    return _ft.mm_plugin_aligned_allocate(_heap, n, alignment, out_ptr);\n  }\n    \n  inline status_t aligned_allocate_offset(size_t n, size_t alignment, size_t offset, void ** out_ptr) noexcept {\n    return _ft.mm_plugin_aligned_allocate_offset(_heap, n, alignment, offset, out_ptr);\n  }\n    \n  inline status_t deallocate(void ** ptr, size_t size) noexcept {\n    return _ft.mm_plugin_deallocate(_heap, ptr, size);\n  }\n    \n  inline status_t deallocate_without_size(void ** ptr) noexcept {\n    return _ft.mm_plugin_deallocate_without_size(_heap, ptr);\n  }\n    \n  inline status_t callocate(size_t n, void ** out_ptr) noexcept {\n    return _ft.mm_plugin_callocate(_heap, n, out_ptr);\n  }\n    \n  inline status_t reallocate(void ** in_out_ptr, size_t size) noexcept {\n    return _ft.mm_plugin_reallocate(_heap, in_out_ptr, size);\n  }\n    \n  inline status_t usable_size(void * ptr, size_t * out_size) noexcept {\n    return _ft.mm_plugin_usable_size(_heap, ptr, out_size);\n  }\n\n  inline status_t bytes_remaining(size_t *bytes_remaining) const noexcept {\n    return _ft.mm_plugin_bytes_remaining(_heap, bytes_remaining);\n  }\n    \n  inline void debug(mm_plugin_heap_t heap) noexcept {\n    return _ft.mm_plugin_debug(_heap);\n  }\n\n  inline status_t inject_allocation(void * ptr, size_t size) noexcept {\n    return _ft.mm_plugin_inject_allocation(_heap, ptr, size);\n  }\n\n  inline int is_crash_consistent() noexcept {\n    return _ft.mm_plugin_is_crash_consistent(_heap);\n  }\n\n  inline int can_inject_allocation() noexcept {\n    return _ft.mm_plugin_can_inject_allocation(_heap);\n  }\n\nprivate:\n  void *                     _module;\n  mm_plugin_function_table_t _ft;\n#if 0\n  /* intention, but we avoid appealing to moveable_ptr */\n  common::moveable_ptr<void> _heap;\n#else\n  void *                     _heap;\n#endif\n};\n\n#include <limits>\n#include <new>\n\n/** \n * Standard C++ allocator wrapper\n * \n */\ntemplate <class T>\nclass MM_plugin_cxx_allocator\n{\npublic:\n  using value_type    = T;\n  using pointer       = value_type*;\n  using const_pointer = typename std::pointer_traits<pointer>::template\n    rebind<value_type const>;\n  using void_pointer       = typename std::pointer_traits<pointer>::template\n    rebind<void>;\n  using const_void_pointer = typename std::pointer_traits<pointer>::template\n    rebind<const void>;\n  \n  using difference_type = typename std::pointer_traits<pointer>::difference_type;\n  using size_type       = std::make_unsigned_t<difference_type>;\n  \n  template <class U> struct rebind {typedef MM_plugin_cxx_allocator<U> other;};\n\n  MM_plugin_cxx_allocator(MM_plugin_wrapper& wrapper) noexcept : _wrapper(wrapper)\n  {\n  }\n  \n  template <class U>\n  MM_plugin_cxx_allocator(MM_plugin_cxx_allocator<U> const& a_) noexcept : _wrapper(a_._wrapper)  {}\n\n  pointer allocate(std::size_t n)\n  {\n    pointer p = nullptr;\n    auto status = _wrapper.allocate(n*sizeof(value_type), reinterpret_cast<void**>(&p));\n    if(status != 0) throw std::bad_alloc();\n    return p;\n  }\n\n  void deallocate(pointer p, std::size_t n) noexcept\n  {\n    _wrapper.deallocate(reinterpret_cast<void**>(&p), n);\n  }\n\n  pointer allocate(std::size_t n, const_void_pointer)\n  {\n    return allocate(n);\n  }\n\n  template <class U, class ...Args>\n  void construct(U* p, Args&& ...args)\n  {\n    ::new(p) U(std::forward<Args>(args)...);\n  }\n\n  template <class U>\n  void destroy(U* p) noexcept\n  {\n    p->~U();\n  }\n\n  std::size_t max_size() const noexcept\n  {\n    return std::numeric_limits<size_type>::max();\n  }\n\n  MM_plugin_cxx_allocator select_on_container_copy_construction() const\n  {\n    return *this;\n  }\n\n  using propagate_on_container_copy_assignment = std::false_type;\n  using propagate_on_container_move_assignment = std::false_type;\n  using propagate_on_container_swap            = std::false_type;\n  using is_always_equal                        = std::is_empty<MM_plugin_cxx_allocator>;\n  \n  MM_plugin_wrapper& _wrapper;\n};\n\ntemplate <class T, class U>\nbool\noperator==(MM_plugin_cxx_allocator<T> const&, MM_plugin_cxx_allocator<U> const&) noexcept\n{\n  return true;\n}\n\ntemplate <class T, class U>\nbool\noperator!=(MM_plugin_cxx_allocator<T> const& x, MM_plugin_cxx_allocator<U> const& y) noexcept\n{\n  return !(x == y);\n}\n\n\n#undef LOAD_SYMBOL\n#endif\n\n\n#pragma GCC diagnostic pop\n\n#endif // __MM_PLUGIN_ITF_H__\n", "meta": {"hexsha": "f2a16d84033022745de7d811fcc27af341309846", "size": 18047, "ext": "h", "lang": "C", "max_stars_repo_path": "src/mm/mm_plugin_itf.h", "max_stars_repo_name": "omriarad/mcas", "max_stars_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 60.0, "max_stars_repo_stars_event_min_datetime": "2020-04-28T08:15:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T10:35:15.000Z", "max_issues_repo_path": "src/mm/mm_plugin_itf.h", "max_issues_repo_name": "omriarad/mcas", "max_issues_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 66.0, "max_issues_repo_issues_event_min_datetime": "2020-09-03T23:40:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T20:34:52.000Z", "max_forks_repo_path": "src/mm/mm_plugin_itf.h", "max_forks_repo_name": "omriarad/mcas", "max_forks_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2019-11-02T06:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T01:56:42.000Z", "avg_line_length": 32.4003590664, "max_line_length": 137, "alphanum_fraction": 0.6860420014, "num_tokens": 4318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10521054231434403, "lm_q2_score": 0.021948252835208338, "lm_q1q2_score": 0.002309187583644608}}
{"text": "#if !defined(FINDFILEEXT_H_INCLUDED)\n#define FINDFILEEXT_H_INCLUDED\n\n#include \"FileEnumerator.h\"\n#include \"Utils.h\"\n\n#include <filesystem>\n#include <gsl/gsl>\n#include <iosfwd>\n#include <map>\n#include <string>\n#include <vector>\n\nclass FindFileExt\n{\npublic:\n\tstatic int usage(::std::ostream& strm, const ::std::string& progName,\n\t\tconst char* pMsg);\n\n\tFindFileExt(::gsl::span<const char*const> args);\n\tint run();\n\n\tFindFileExt(const FindFileExt&) = delete;\n\tFindFileExt& operator=(const FindFileExt&) = delete;\n\tFindFileExt(FindFileExt&&) = delete;\n\tFindFileExt& operator=(FindFileExt&&) = delete;\n\nPRIVATE_EXCEPT_IN_TEST:\n\tusing Path = ::std::filesystem::path;\n\tusing StrToCountMap = ::std::map< ::std::string, size_t >;\n\tusing PathList = ::std::vector<Path>;\n\n\tvoid countFiles();\n\tvoid reportExtension(const StrToCountMap::value_type& extToCountMapping);\n\n\tbool\t\t\t\tm_includeCounts;\n\tbool\t\t\t\tm_outputAsWildcards;\n\tFileEnumerator\tm_fileEnumerator;\n\tStrToCountMap\tm_extToCountMap;\n\tPathList\t\t\tm_noExtList;\n};\n\n#endif // FINDFILEEXT_H_INCLUDED\n", "meta": {"hexsha": "4b10e98be75024e4c753159b7d1cd9a408e49d7b", "size": 1040, "ext": "h", "lang": "C", "max_stars_repo_path": "FindFileExt.h", "max_stars_repo_name": "IanEmmons/CmdLineUtil", "max_stars_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FindFileExt.h", "max_issues_repo_name": "IanEmmons/CmdLineUtil", "max_issues_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FindFileExt.h", "max_forks_repo_name": "IanEmmons/CmdLineUtil", "max_forks_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.6363636364, "max_line_length": 74, "alphanum_fraction": 0.7451923077, "num_tokens": 280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09009299396195183, "lm_q2_score": 0.025565213459254256, "lm_q1q2_score": 0.0023032466218206034}}
{"text": "#pragma once\n#include \"../utils/utils.h\"\n#include <gsl/gsl>\n\nnamespace Halley {\n\tclass Compression {\n\tpublic:\n\t\tstatic Bytes deflate(const Bytes& bytes);\n\t\tstatic Bytes deflate(gsl::span<const gsl::byte> bytes);\n\t\tstatic Bytes inflate(const Bytes& bytes);\n\t\tstatic Bytes inflate(gsl::span<const gsl::byte> bytes);\n\t\tstatic std::shared_ptr<const char> inflateToSharedPtr(gsl::span<const gsl::byte> bytes, size_t& outSize);\n\t\tstatic unsigned char* inflateRaw(gsl::span<const gsl::byte> bytes, size_t& outSize);\n\t};\n}\n", "meta": {"hexsha": "1611de7c8c5cf14cfc90f03344a9adc937bc58b6", "size": 515, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engine/utils/include/halley/file/compression.h", "max_stars_repo_name": "Healthire/halley", "max_stars_repo_head_hexsha": "aa58e1abe22cda9e80637922721c03574779cd81", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/engine/utils/include/halley/file/compression.h", "max_issues_repo_name": "Healthire/halley", "max_issues_repo_head_hexsha": "aa58e1abe22cda9e80637922721c03574779cd81", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engine/utils/include/halley/file/compression.h", "max_forks_repo_name": "Healthire/halley", "max_forks_repo_head_hexsha": "aa58e1abe22cda9e80637922721c03574779cd81", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1875, "max_line_length": 107, "alphanum_fraction": 0.7300970874, "num_tokens": 129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.11436852618181247, "lm_q2_score": 0.020023441070156685, "lm_q1q2_score": 0.002290051444282194}}
{"text": "#pragma once\n\n#include \"Core/Delegate.h\"\n#include \"Core/Pointers.h\"\n#include \"Scene/Entity.h\"\n\n#include <gsl/span>\n\n#include <string>\n#include <unordered_map>\n#include <vector>\n\nclass CameraComponent;\nclass DirectionalLightComponent;\nclass ModelComponent;\nclass PointLightComponent;\nclass SpotLightComponent;\n\nclass Scene\n{\npublic:\n   Scene();\n   ~Scene();\n\n   void tick(float dt);\n\n   float getTime() const\n   {\n      return time;\n   }\n\n   float getDeltaTime() const\n   {\n      return deltaTime;\n   }\n\n   template<typename... ComponentTypes>\n   Entity* createEntity()\n   {\n      entities.push_back(Entity::create<ComponentTypes...>(*this));\n      return entities.back().get();\n   }\n\n   Entity* createEntity(gsl::span<std::string> componentClassNames)\n   {\n      entities.push_back(Entity::create(componentClassNames, *this));\n      return entities.back().get();\n   }\n\n   bool destroyEntity(Entity* entityToDestroy);\n\n   const std::vector<UPtr<Entity>>& getEntities() const\n   {\n      return entities;\n   }\n\n   CameraComponent* getActiveCameraComponent()\n   {\n      return activeCameraComponent;\n   }\n\n   const CameraComponent* getActiveCameraComponent() const\n   {\n      return activeCameraComponent;\n   }\n\n   void setActiveCameraComponent(CameraComponent* newActiveCameraComponent);\n\n   const std::vector<CameraComponent*>& getCameraComponents() const\n   {\n      return cameraComponents;\n   }\n\n   void registerCameraComponent(CameraComponent* cameraComponent);\n   void unregisterCameraComponent(CameraComponent* cameraComponent);\n\n   const std::vector<ModelComponent*>& getModelComponents() const\n   {\n      return modelComponents;\n   }\n\n   void registerModelComponent(ModelComponent* modelComponent);\n   void unregisterModelComponent(ModelComponent* modelComponent);\n\n   const std::vector<DirectionalLightComponent*>& getDirectionalLightComponents() const\n   {\n      return directionalLightComponents;\n   }\n\n   void registerDirectionalLightComponent(DirectionalLightComponent* directionalLightComponent);\n   void unregisterDirectionalLightComponent(DirectionalLightComponent* directionalLightComponent);\n\n   const std::vector<PointLightComponent*>& getPointLightComponents() const\n   {\n      return pointLightComponents;\n   }\n\n   void registerPointLightComponent(PointLightComponent* pointLightComponent);\n   void unregisterPointLightComponent(PointLightComponent* pointLightComponent);\n\n   const std::vector<SpotLightComponent*>& getSpotLightComponents() const\n   {\n      return spotLightComponents;\n   }\n\n   void registerSpotLightComponent(SpotLightComponent* spotLightComponent);\n   void unregisterSpotLightComponent(SpotLightComponent* spotLightComponent);\n\nprivate:\n   float time;\n   float deltaTime;\n\n   std::vector<UPtr<Entity>> entities;\n\n   std::vector<CameraComponent*> cameraComponents;\n   CameraComponent* activeCameraComponent;\n\n   std::vector<ModelComponent*> modelComponents;\n\n   std::vector<DirectionalLightComponent*> directionalLightComponents;\n   std::vector<PointLightComponent*> pointLightComponents;\n   std::vector<SpotLightComponent*> spotLightComponents;\n};\n", "meta": {"hexsha": "aa13c31dc56dce9a4eb0ad42998206dff80ef51b", "size": 3085, "ext": "h", "lang": "C", "max_stars_repo_path": "Source/Scene/Scene.h", "max_stars_repo_name": "aaronmjacobs/Swap", "max_stars_repo_head_hexsha": "955f36bc95b6829bf1a1a89b430df7816c065ac0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Source/Scene/Scene.h", "max_issues_repo_name": "aaronmjacobs/Swap", "max_issues_repo_head_hexsha": "955f36bc95b6829bf1a1a89b430df7816c065ac0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/Scene/Scene.h", "max_forks_repo_name": "aaronmjacobs/Swap", "max_forks_repo_head_hexsha": "955f36bc95b6829bf1a1a89b430df7816c065ac0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8790322581, "max_line_length": 98, "alphanum_fraction": 0.7510534846, "num_tokens": 634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11596071825396675, "lm_q2_score": 0.0197191271351992, "lm_q1q2_score": 0.002286644145938985}}
{"text": "//\n// Autogenerated based on code by L. J. Feldstein\n//\n\n#include <stdio.h>\n#include <gsl/gsl_matrix.h>\n#include \"cimple_controller.h\"\n", "meta": {"hexsha": "5ca87dc09ccd06b208cc27e39f4a0ddd1ca74a7c", "size": 135, "ext": "c", "lang": "C", "max_stars_repo_path": "Interface/Cimple/act_impl.c", "max_stars_repo_name": "shaesaert/TuLiPXML", "max_stars_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-28T23:44:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-28T23:44:28.000Z", "max_issues_repo_path": "Interface/Cimple/act_impl.c", "max_issues_repo_name": "shaesaert/TuLiPXML", "max_issues_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-10-03T18:54:08.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-21T09:50:09.000Z", "max_forks_repo_path": "Interface/Cimple/act_impl.c", "max_forks_repo_name": "shaesaert/TuLiPXML", "max_forks_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-06T12:58:52.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-06T12:58:52.000Z", "avg_line_length": 16.875, "max_line_length": 49, "alphanum_fraction": 0.7111111111, "num_tokens": 37, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.11757213354550883, "lm_q2_score": 0.01941934800510395, "lm_q1q2_score": 0.002283174177022792}}
{"text": "/**\n * This file is part of the \"libterminal\" project\n *   Copyright (c) 2019-2020 Christian Parpart <christian@parpart.family>\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n#pragma once\n\n#include <terminal/Color.h>\n#include <terminal/RenderBuffer.h>\n#include <terminal/Screen.h>\n\n#include <terminal_renderer/BoxDrawingRenderer.h>\n#include <terminal_renderer/FontDescriptions.h>\n#include <terminal_renderer/RenderTarget.h>\n#include <terminal_renderer/TextureAtlas.h>\n\n#include <text_shaper/font.h>\n#include <text_shaper/shaper.h>\n\n#include <crispy/FNV.h>\n#include <crispy/LRUCache.h>\n#include <crispy/point.h>\n#include <crispy/size.h>\n\n#include <unicode/convert.h>\n#include <unicode/run_segmenter.h>\n\n#include <gsl/span>\n#include <gsl/span_ext>\n\n#include <functional>\n#include <list>\n#include <memory>\n#include <unordered_map>\n#include <vector>\n\nnamespace terminal::renderer\n{\n\nstd::unique_ptr<text::font_locator> createFontLocator(FontLocatorEngine _engine);\n\nstruct FontKeys\n{\n    text::font_key regular;\n    text::font_key bold;\n    text::font_key italic;\n    text::font_key boldItalic;\n    text::font_key emoji;\n};\n\n/// Text Rendering Pipeline\nclass TextRenderer: public Renderable\n{\n  public:\n    TextRenderer(GridMetrics const& gridMetrics,\n                 text::shaper& textShaper,\n                 FontDescriptions& fontDescriptions,\n                 FontKeys const& fontKeys);\n\n    void setRenderTarget(RenderTarget& renderTarget, DirectMappingAllocator& directMappingAllocator) override;\n    void setTextureAtlas(TextureAtlas& atlas) override;\n\n    void inspect(std::ostream& _textOutput) const override;\n\n    void clearCache() override;\n\n    void updateFontMetrics();\n\n    void setPressure(bool _pressure) noexcept { pressure_ = _pressure; }\n\n    /// Must be invoked before a new terminal frame is rendered.\n    void beginFrame();\n\n    /// Renders a given terminal's grid cell that has been\n    /// transformed into a RenderCell.\n    void renderCell(RenderCell const& _cell);\n\n    /// Must be invoked when rendering the terminal's text has finished for this frame.\n    void endFrame();\n\n  private:\n    void initializeDirectMapping();\n\n    /// Puts a sequence of codepoints that belong to the same grid cell at @p _pos\n    /// at the end of the currently filled line.\n    void appendCellTextToClusterGroup(std::u32string const& _codepoints, TextStyle _style, RGBColor _color);\n\n    /// Gets the text shaping result of the current text cluster group\n    text::shape_result const& getOrCreateCachedGlyphPositions(crispy::StrongHash hash);\n    text::shape_result createTextShapedGlyphPositions();\n    text::shape_result shapeTextRun(unicode::run_segmenter::range const& _run);\n    void flushTextClusterGroup();\n\n    AtlasTileAttributes const* getOrCreateRasterizedMetadata(crispy::StrongHash const& hash,\n                                                             text::glyph_key const& glyphKey,\n                                                             unicode::PresentationStyle presentationStyle);\n\n    /**\n     * Creates (and rasterizes) a single glyph and returns its\n     * render tile attributes required for the render step.\n     */\n    std::optional<TextureAtlas::TileCreateData> createSlicedRasterizedGlyph(\n        atlas::TileLocation tileLocation,\n        text::glyph_key const& id,\n        unicode::PresentationStyle presentation,\n        crispy::StrongHash const& hash);\n\n    std::optional<TextureAtlas::TileCreateData> createRasterizedGlyph(\n        atlas::TileLocation tileLocation, text::glyph_key const& id, unicode::PresentationStyle presentation);\n\n    crispy::Point applyGlyphPositionToPen(crispy::Point pen,\n                                          AtlasTileAttributes const& tileAttributes,\n                                          text::glyph_position const& gpos) const noexcept;\n\n    void renderRasterizedGlyph(crispy::Point targetSurfacePosition,\n                               RGBAColor glyphColor,\n                               AtlasTileAttributes const& attributes);\n\n    // general properties\n    //\n    FontDescriptions& fontDescriptions_;\n    FontKeys const& fonts_;\n\n    // performance optimizations\n    //\n    bool pressure_ = false;\n\n    using ShapingResultCache = crispy::StrongLRUHashtable<text::shape_result>;\n    using ShapingResultCachePtr = ShapingResultCache::Ptr;\n\n    ShapingResultCachePtr textShapingCache_;\n    // TODO: make unique_ptr, get owned, export cref for other users in Renderer impl.\n    text::shaper& textShaper_;\n\n    DirectMapping _directMapping {};\n\n    // Maps from glyph index to tile index.\n    std::vector<uint32_t> _directMappedGlyphKeyToTileIndex {};\n\n    bool isGlyphDirectMapped(text::glyph_key const& glyph) const noexcept\n    {\n        return _directMapping                  // Is direct mapping enabled?\n               && glyph.font == fonts_.regular // Only regular font is direct-mapped for now.\n               && glyph.index.value < _directMappedGlyphKeyToTileIndex.size()\n               && _directMappedGlyphKeyToTileIndex[glyph.index.value] != 0;\n    }\n\n    // sub-renderer\n    //\n    BoxDrawingRenderer boxDrawingRenderer_;\n\n    // work-data for the current text cluster group\n    struct TextClusterGroup\n    {\n        // pen-start position of this text group\n        crispy::Point initialPenPosition {};\n\n        // uniform text style for this text group\n        TextStyle style = TextStyle::Invalid;\n\n        // uniform text color for this text group\n        RGBColor color {};\n\n        // codepoints within this text group with\n        // uniform unicode properties (script, language, direction).\n        std::vector<char32_t> codepoints;\n\n        // cluster indices for each codepoint\n        std::vector<unsigned> clusters;\n\n        // number of grid cells processed\n        int cellCount = 0; // FIXME: EA width vs actual cells\n\n        void resetAndMovePenForward(int penIncrementInX)\n        {\n            codepoints.clear();\n            clusters.clear();\n            cellCount = 0;\n            initialPenPosition.x += penIncrementInX;\n        }\n    };\n    TextClusterGroup textClusterGroup_ {};\n\n    bool textStartFound_ = false;\n    bool forceCellGroupSplit_ = false;\n};\n\n} // namespace terminal::renderer\n", "meta": {"hexsha": "53803f6217897780a7906e41ba5113de7b3be934", "size": 6631, "ext": "h", "lang": "C", "max_stars_repo_path": "src/terminal_renderer/TextRenderer.h", "max_stars_repo_name": "dandycheung/contour", "max_stars_repo_head_hexsha": "1364ec488def8a0494503b9879b370b3669e81f9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/terminal_renderer/TextRenderer.h", "max_issues_repo_name": "dandycheung/contour", "max_issues_repo_head_hexsha": "1364ec488def8a0494503b9879b370b3669e81f9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/terminal_renderer/TextRenderer.h", "max_forks_repo_name": "dandycheung/contour", "max_forks_repo_head_hexsha": "1364ec488def8a0494503b9879b370b3669e81f9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6598984772, "max_line_length": 110, "alphanum_fraction": 0.6855677877, "num_tokens": 1407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10230471610365104, "lm_q2_score": 0.022286188096151693, "lm_q1q2_score": 0.002279982146209366}}
{"text": "/* Copyright 2019-2020 Canaan Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n#pragma once\n#include \"compiler_defs.h\"\n#include <cstring>\n#include <gsl/gsl-lite.hpp>\n\nBEGIN_NS_NNCASE_RUNTIME\n\nclass span_reader\n{\npublic:\n    span_reader(gsl::span<const gsl::byte> span)\n        : span_(span)\n    {\n    }\n\n    bool empty() const noexcept { return span_.empty(); }\n    size_t avail() const noexcept { return span_.size_bytes(); }\n\n    template <class T>\n    T read()\n    {\n        auto value = *reinterpret_cast<const T *>(span_.data());\n        advance(sizeof(T));\n        return value;\n    }\n\n    template <class T>\n    T read_unaligned()\n    {\n        alignas(T) uint8_t storage[sizeof(T)];\n        std::memcpy(storage, span_.data(), sizeof(T));\n        advance(sizeof(T));\n        return *reinterpret_cast<const T *>(storage);\n    }\n\n    template <class T>\n    void read(T &value)\n    {\n        value = *reinterpret_cast<const T *>(span_.data());\n        advance(sizeof(T));\n    }\n\n    template <class T>\n    void read_span(gsl::span<const T> &span, size_t size)\n    {\n        span = { reinterpret_cast<const T *>(span_.data()), size };\n        advance(sizeof(T) * size);\n    }\n\n    template <class T = gsl::byte>\n    gsl::span<const T> read_span(size_t size)\n    {\n        gsl::span<const T> span(reinterpret_cast<const T *>(span_.data()), size);\n        advance(sizeof(T) * size);\n        return span;\n    }\n\n    void read_avail(gsl::span<const gsl::byte> &span)\n    {\n        span = span_;\n        span_ = {};\n    }\n\n    gsl::span<const gsl::byte> read_avail()\n    {\n        auto span = span_;\n        span_ = {};\n        return span;\n    }\n\n    gsl::span<const gsl::byte> peek_avail()\n    {\n        return span_;\n    }\n\n    template <class T>\n    T peek()\n    {\n        auto value = *reinterpret_cast<const T *>(span_.data());\n        return value;\n    }\n\n    template <class T>\n    T peek_unaligned()\n    {\n        T value;\n        std::memcpy(&value, span_.data(), sizeof(T));\n        return value;\n    }\n\n    template <class T>\n    T peek_unaligned_with_offset(size_t offset)\n    {\n        T value;\n        std::memcpy(&value, span_.data() + offset, sizeof(T));\n        return value;\n    }\n\n    template <class T>\n    const T *get_ref()\n    {\n        auto ptr = reinterpret_cast<const T *>(span_.data());\n        advance(sizeof(T));\n        return ptr;\n    }\n\n    template <class T>\n    void get_ref(const T *&ptr)\n    {\n        ptr = get_ref<T>();\n    }\n\n    void skip(size_t count)\n    {\n        advance(count);\n    }\n\nprivate:\n    void advance(size_t count)\n    {\n        span_ = span_.subspan(count);\n    }\n\nprivate:\n    gsl::span<const gsl::byte> span_;\n};\n\nEND_NS_NNCASE_RUNTIME\n", "meta": {"hexsha": "e3bb0f8bf63845d1eb6f1e1dc5a1564b6e767c95", "size": 3211, "ext": "h", "lang": "C", "max_stars_repo_path": "lib/nncase/v1/include/nncase/runtime/span_reader.h", "max_stars_repo_name": "zhen8838/kendryte-standalone-sdk", "max_stars_repo_head_hexsha": "0ce252641826d65e12621347992cc9865874e6e1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-31T09:53:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T09:53:44.000Z", "max_issues_repo_path": "include/nncase/runtime/span_reader.h", "max_issues_repo_name": "13129176346/nncase", "max_issues_repo_head_hexsha": "61e41170faed249303295d184f611f27cfefce9d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/nncase/runtime/span_reader.h", "max_forks_repo_name": "13129176346/nncase", "max_forks_repo_head_hexsha": "61e41170faed249303295d184f611f27cfefce9d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-04-21T01:27:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T09:48:53.000Z", "avg_line_length": 22.4545454545, "max_line_length": 81, "alphanum_fraction": 0.5886016817, "num_tokens": 779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08756383952305866, "lm_q2_score": 0.025957358610626615, "lm_q1q2_score": 0.0022729259838233937}}
{"text": "#pragma once\n\n#include <GLES2/gl2.h>\n#include <GLES2/gl2ext.h>\n#include <GLES3/gl3.h>\n#include <GLES3/gl3ext.h>\n#include <GLES3/gl3platform.h>\n#include <EGL/egl.h>\n#include <EGL/eglext.h>\n#include <gsl/gsl>\n\nnamespace android::OpenGLHelpers\n{\n    constexpr GLint GetTextureUnit(GLenum texture)\n    {\n        return texture - GL_TEXTURE0;\n    }\n\n    GLuint CreateShaderProgram(const char* vertShaderSource, const char* fragShaderSource);\n\n    namespace GLTransactions\n    {\n        inline auto MakeCurrent(EGLDisplay display, EGLSurface drawSurface, EGLSurface readSurface, EGLContext context)\n        {\n            EGLDisplay previousDisplay{ eglGetDisplay(EGL_DEFAULT_DISPLAY) };\n            EGLSurface previousDrawSurface{ eglGetCurrentSurface(EGL_DRAW) };\n            EGLSurface previousReadSurface{ eglGetCurrentSurface(EGL_READ) };\n            EGLContext previousContext{ eglGetCurrentContext() };\n            eglMakeCurrent(display, drawSurface, readSurface, context);\n            return gsl::finally([previousDisplay, previousDrawSurface, previousReadSurface, previousContext]() { eglMakeCurrent(previousDisplay, previousDrawSurface, previousReadSurface, previousContext); });\n        }\n    }\n}", "meta": {"hexsha": "d97af33bace18bf7df463d0a8a0f92b4b22f05bf", "size": 1201, "ext": "h", "lang": "C", "max_stars_repo_path": "Dependencies/AndroidExtensions/Include/AndroidExtensions/OpenGLHelpers.h", "max_stars_repo_name": "EricBeetsOfficial-Opuscope/BabylonNative", "max_stars_repo_head_hexsha": "fc7b2add9da4ef8e79ad86e087457685bdb2417f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Dependencies/AndroidExtensions/Include/AndroidExtensions/OpenGLHelpers.h", "max_issues_repo_name": "EricBeetsOfficial-Opuscope/BabylonNative", "max_issues_repo_head_hexsha": "fc7b2add9da4ef8e79ad86e087457685bdb2417f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Dependencies/AndroidExtensions/Include/AndroidExtensions/OpenGLHelpers.h", "max_forks_repo_name": "EricBeetsOfficial-Opuscope/BabylonNative", "max_forks_repo_head_hexsha": "fc7b2add9da4ef8e79ad86e087457685bdb2417f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3939393939, "max_line_length": 208, "alphanum_fraction": 0.7235636969, "num_tokens": 277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1066905939456512, "lm_q2_score": 0.021287349503854552, "lm_q1q2_score": 0.0022711599620949055}}
{"text": "#pragma once\n\n#include <memory>\n#include <gsl/span>\n\n#include \"halley/time/halleytime.h\"\n#include \"../session/network_session.h\"\n#include \"entity_network_remote_peer.h\"\n#include \"halley/bytes/serialization_dictionary.h\"\n\nnamespace Halley {\n\tclass EntityFactory;\n\tclass Resources;\n\tclass World;\n\tclass NetworkSession;\n\n\tclass EntitySessionSharedData : public SharedData {\n\tpublic:\n\t\t\n\t};\n\n\tclass EntityClientSharedData : public SharedData {\n\tpublic:\n\t\tstd::optional<Rect4i> viewRect;\n\n\t\tvoid serialize(Serializer& s) const override;\n\t\tvoid deserialize(Deserializer& s) override;\n\t};\n\n\tclass EntityNetworkSession : NetworkSession::IListener, NetworkSession::ISharedDataHandler {\n    public:\n\t\tclass IEntityNetworkSessionListener {\n\t\tpublic:\n\t\t\tvirtual ~IEntityNetworkSessionListener() = default;\n\t\t\tvirtual void onRemoteEntityCreated(EntityRef entity, NetworkSession::PeerId peerId) {}\n\t\t\tvirtual void onPreSendDelta(EntityDataDelta& delta) {}\n\t\t\tvirtual bool isEntityInView(EntityRef entity, const EntityClientSharedData& clientData) = 0;\n\t\t};\n\t\t\n\t\tEntityNetworkSession(std::shared_ptr<NetworkSession> session, Resources& resources, std::set<String> ignoreComponents, IEntityNetworkSessionListener* listener);\n\t\t~EntityNetworkSession() override;\n\n\t\tvoid setWorld(World& world);\n\t\t\n\t\tvoid sendUpdates(Time t, Rect4i viewRect, gsl::span<const std::pair<EntityId, uint8_t>> entityIds); // Takes pairs of entity id and owner peer id\n\t\tvoid receiveUpdates();\n\n\t\tWorld& getWorld() const;\n\t\tEntityFactory& getFactory() const;\n\t\tNetworkSession& getSession() const;\n\t\tbool hasWorld() const;\n\n\t\tconst EntityFactory::SerializationOptions& getEntitySerializationOptions() const;\n\t\tconst EntityDataDelta::Options& getEntityDeltaOptions() const;\n\t\tconst SerializerOptions& getByteSerializationOptions() const;\n\n\t\tTime getMinSendInterval() const;\n\n\t\tvoid onRemoteEntityCreated(EntityRef entity, NetworkSession::PeerId peerId);\n\t\tvoid onPreSendDelta(EntityDataDelta& delta);\n\n\t\tbool isReadyToStart() const;\n\t\tbool isEntityInView(EntityRef entity, const EntityClientSharedData& clientData) const;\n\n\t\tstd::vector<Rect4i> getRemoteViewPorts() const;\n\n\tprotected:\n\t\tvoid onStartSession(NetworkSession::PeerId myPeerId) override;\n\t\tvoid onPeerConnected(NetworkSession::PeerId peerId) override;\n\t\tvoid onPeerDisconnected(NetworkSession::PeerId peerId) override;\n\t\tstd::unique_ptr<SharedData> makeSessionSharedData() override;\n\t\tstd::unique_ptr<SharedData> makePeerSharedData() override;\n\t\n\tprivate:\n\t\tstruct QueuedPacket {\n\t\t\tNetworkSession::PeerId fromPeerId;\n\t\t\tEntityNetworkHeaderType type;\n\t\t\tInboundNetworkPacket packet;\n\t\t};\n\t\t\n\t\tResources& resources;\n\t\tstd::shared_ptr<EntityFactory> factory;\n\t\tIEntityNetworkSessionListener* listener = nullptr;\n\t\t\n\t\tEntityFactory::SerializationOptions entitySerializationOptions;\n\t\tEntityDataDelta::Options deltaOptions;\n\t\tSerializerOptions byteSerializationOptions;\n\t\tSerializationDictionary serializationDictionary;\n\n\t\tstd::shared_ptr<NetworkSession> session;\n\t\tstd::vector<EntityNetworkRemotePeer> peers;\n\n\t\tstd::vector<QueuedPacket> queuedPackets;\n\n\t\tbool readyToStart = false;\n\n\t\tvoid onReceiveEntityUpdate(NetworkSession::PeerId fromPeerId, EntityNetworkHeaderType type, InboundNetworkPacket packet);\n\t\tvoid onReceiveReady(NetworkSession::PeerId fromPeerId);\n\n\t\tvoid setupDictionary();\n\t};\n}\n", "meta": {"hexsha": "3cda999aa635109d19dfce668f8ba16746c7679d", "size": 3317, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engine/net/include/halley/net/entity/entity_network_session.h", "max_stars_repo_name": "JoelOtter/halley", "max_stars_repo_head_hexsha": "a093ed9c26a5141db87b560186c609cfe4810695", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/engine/net/include/halley/net/entity/entity_network_session.h", "max_issues_repo_name": "JoelOtter/halley", "max_issues_repo_head_hexsha": "a093ed9c26a5141db87b560186c609cfe4810695", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engine/net/include/halley/net/entity/entity_network_session.h", "max_forks_repo_name": "JoelOtter/halley", "max_forks_repo_head_hexsha": "a093ed9c26a5141db87b560186c609cfe4810695", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2038834951, "max_line_length": 162, "alphanum_fraction": 0.790171842, "num_tokens": 763, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10818894306026933, "lm_q2_score": 0.02096424292079466, "lm_q1q2_score": 0.0022680992836595078}}
{"text": "#pragma once\n\n#include <d3d11.h>\n#include <gsl\\gsl>\n#include \"Rectangle.h\"\n\nnamespace Library\n{\n\tclass TextureHelper final\n\t{\n\tpublic:\n\t\tstatic Point GetTextureSize(gsl::not_null<ID3D11Texture2D*> texture);\n\t\tstatic Rectangle GetTextureBounds(gsl::not_null<ID3D11Texture2D*> texture);\n\t\tstatic std::uint32_t BitsPerPixel(const DXGI_FORMAT format);\n\t\t\n\t\tTextureHelper() = delete;\n\t\tTextureHelper(const TextureHelper&) = delete;\n\t\tTextureHelper& operator=(const TextureHelper&) = delete;\n\t\tTextureHelper(TextureHelper&&) = delete;\n\t\tTextureHelper& operator=(TextureHelper&&) = delete;\n\t\t~TextureHelper() = default;\n\t};\n}", "meta": {"hexsha": "03c372930da68d0a5b3bd80407933ca1f9a84800", "size": 618, "ext": "h", "lang": "C", "max_stars_repo_path": "source/Library.Shared/TextureHelper.h", "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/Library.Shared/TextureHelper.h", "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/Library.Shared/TextureHelper.h", "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8695652174, "max_line_length": 77, "alphanum_fraction": 0.7508090615, "num_tokens": 159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10970578261038683, "lm_q2_score": 0.020645930061300985, "lm_q1q2_score": 0.0022649779150943363}}
{"text": "#ifndef EV3PLOTTER_MESSAGEQUEUE_H\n#define EV3PLOTTER_MESSAGEQUEUE_H\n\n#include <gsl/span>\n#include <memory>\n#include <string_view>\n#include <type_safe/flag_set.hpp>\n\nnamespace ev3plotter {\n\nclass message_queue {\n  public:\n    enum class option { read, write, non_blocking, remove_on_destruction, _flag_set_size };\n\n    enum class send_result { success, failure_queue_full, failure };\n\n    enum class receive_result { success, failure_no_messages, failure };\n\n    message_queue(std::string_view name, std::size_t max_message_size, type_safe::flag_set<option> options);\n    ~message_queue();\n\n    send_result send(std::string_view msg);\n    receive_result receive(gsl::span<char>& buffer);\n\n    std::size_t message_size() const noexcept;\n\n  private:\n    class impl;\n\n    std::unique_ptr<impl> impl_;\n};\n} // namespace ev3plotter\n\n#endif // EV3PLOTTER_MESSAGEQUEUE_H", "meta": {"hexsha": "b2d821e6ba9491162f25f2ca93515e1d2021ff63", "size": 862, "ext": "h", "lang": "C", "max_stars_repo_path": "mqueue/mqueue/message_queue.h", "max_stars_repo_name": "biocomp/ev3dev-lang-cpp2", "max_stars_repo_head_hexsha": "5c3aae6c2bc4cee2b5798fb26f35dfe81e2e503c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mqueue/mqueue/message_queue.h", "max_issues_repo_name": "biocomp/ev3dev-lang-cpp2", "max_issues_repo_head_hexsha": "5c3aae6c2bc4cee2b5798fb26f35dfe81e2e503c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mqueue/mqueue/message_queue.h", "max_forks_repo_name": "biocomp/ev3dev-lang-cpp2", "max_forks_repo_head_hexsha": "5c3aae6c2bc4cee2b5798fb26f35dfe81e2e503c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3529411765, "max_line_length": 108, "alphanum_fraction": 0.7494199536, "num_tokens": 207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.0769608314618395, "lm_q2_score": 0.0293122296913986, "lm_q1q2_score": 0.0022558935690504553}}
{"text": "\n#if !defined(TESTUTIL_H_INCLUDED)\n#define TESTUTIL_H_INCLUDED\n\n#include \"Exceptions.h\"\n\n#include <gsl/gsl>\n#include <iosfwd>\n\n// ===========================================================================\n//\n// Test case structs\n//\n// ===========================================================================\n\nusing ArgSpan = ::gsl::span<const char*const>;\n\nstruct CmdLineParseTestCase\n{\n\ttemplate<::std::size_t N>\n\tCmdLineParseTestCase(const char*const(&args)[N]) noexcept\n\t\t: m_args(::gsl::make_span(args + 1, N - 1)) {}\n\n\tArgSpan m_args;\n};\n\nstruct CmdLineParseFailTestCase : public CmdLineParseTestCase\n{\n\ttemplate<::std::size_t N>\n\tCmdLineParseFailTestCase(const char*const(&args)[N], char const* pExMsgPattern) noexcept :\n\t\tCmdLineParseTestCase(args),\n\t\tm_pExMsgPattern(pExMsgPattern)\n\t\t{}\n\tbool doesExMatch(CmdLineError const& ex) const;\n\n\tchar const*\tm_pExMsgPattern;\n};\n\n::std::ostream& operator<<(::std::ostream& ostrm, CmdLineParseTestCase const& tc);\n\n#endif // TESTUTIL_H_INCLUDED\n", "meta": {"hexsha": "1f2518d2246bc760179ad20ec90f954137458ef7", "size": 997, "ext": "h", "lang": "C", "max_stars_repo_path": "TestUtil.h", "max_stars_repo_name": "IanEmmons/CmdLineUtil", "max_stars_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "TestUtil.h", "max_issues_repo_name": "IanEmmons/CmdLineUtil", "max_issues_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TestUtil.h", "max_forks_repo_name": "IanEmmons/CmdLineUtil", "max_forks_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7380952381, "max_line_length": 91, "alphanum_fraction": 0.6218655968, "num_tokens": 244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08035747763179142, "lm_q2_score": 0.028007522228611345, "lm_q1q2_score": 0.0022506138410075373}}
{"text": "#ifndef ppom_57c54fa0_d309_4aad_9678_16fa29f7af42_h\r\n#define ppom_57c54fa0_d309_4aad_9678_16fa29f7af42_h\r\n\r\n#include <rathen\\config.h>\r\n#include <gslib\\tree.h>\r\n#include <rathen\\basis.h>\r\n\r\n__rathen_begin__\r\n\r\nclass ppom\r\n{\r\npublic:\r\n    typedef tree<object, _treenode_wrapper<object> > ppom_tree;\r\n    typedef ppom_tree::iterator iterator;\r\n    typedef ppom_tree::const_iterator const_iterator;\r\n    //typedef ;\r\n    \r\npublic:\r\n    ppom() {}\r\n\r\npublic:\r\n    template<class _cst>\r\n    iterator insert(iterator i) { return _tree.insert_tail<_cst>(i); }\r\n    template<class _cst>\r\n    iterator birth(iterator i) { return _tree.birth_tail<_cst>(i); }\r\n\r\nprotected:\r\n    ppom_tree       _tree;\r\n};\r\n\r\n__rathen_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "afdbe29af857f6db3561c1fc69a9304d3bff0e3e", "size": 723, "ext": "h", "lang": "C", "max_stars_repo_path": "include/rathen/ppom.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/rathen/ppom.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/rathen/ppom.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 21.2647058824, "max_line_length": 71, "alphanum_fraction": 0.7012448133, "num_tokens": 217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10230470241865472, "lm_q2_score": 0.02194825227542503, "lm_q1q2_score": 0.002245409417646919}}
{"text": "#pragma once\n\n#include <gsl\\gsl>\n#include \"Texture.h\"\n#include \"Rectangle.h\"\n\nnamespace Library\n{\n\tclass Texture2D final : public Texture\n\t{\n\t\tRTTI_DECLARATIONS(Texture2D, Texture)\n\n\tpublic:\n\t\tTexture2D(const GLuint textureID, GLuint width, GLuint height);\n\t\tTexture2D(const Texture2D&) = default;\n\t\tTexture2D& operator=(const Texture2D&) = default;\n\t\tTexture2D(Texture2D&&) = default;\n\t\tTexture2D& operator=(Texture2D&&) = default;\n\t\t~Texture2D() = default;\n\n\t\tstatic std::shared_ptr<Texture2D> CreateTexture2D(GLuint width, GLuint height, GLint mipLevels = 1, GLenum colorFormat = GL_RGBA16F);\n\n\t\tGLuint Width() const;\n\t\tGLuint Height() const;\n\t\tRectangle Bounds() const;\n\n\tprivate:\n\t\tGLuint mWidth;\n\t\tGLuint mHeight;\n\t};\n}", "meta": {"hexsha": "b5a65909f1f44387f743ad856cb8fb780cb54ebf", "size": 725, "ext": "h", "lang": "C", "max_stars_repo_path": "source/Library.Shared/Texture2D.h", "max_stars_repo_name": "DakkyDaWolf/OpenGL", "max_stars_repo_head_hexsha": "628e9aed116022175cc0c59c88ace7688309628c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/Library.Shared/Texture2D.h", "max_issues_repo_name": "DakkyDaWolf/OpenGL", "max_issues_repo_head_hexsha": "628e9aed116022175cc0c59c88ace7688309628c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/Library.Shared/Texture2D.h", "max_forks_repo_name": "DakkyDaWolf/OpenGL", "max_forks_repo_head_hexsha": "628e9aed116022175cc0c59c88ace7688309628c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3870967742, "max_line_length": 135, "alphanum_fraction": 0.7296551724, "num_tokens": 200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.13477590699708825, "lm_q2_score": 0.016657038514270934, "lm_q1q2_score": 0.0022449674736462963}}
{"text": "/**\n * This file is part of the \"libterminal\" project\n *   Copyright (c) 2019-2020 Christian Parpart <christian@parpart.family>\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n#pragma once\n\n#include <terminal/GraphicsAttributes.h>\n#include <terminal/Hyperlink.h>\n#include <terminal/primitives.h>\n\n#include <crispy/BufferObject.h>\n#include <crispy/Comparison.h>\n#include <crispy/assert.h>\n\n#include <gsl/span>\n#include <gsl/span_ext>\n\n#include <iterator>\n#include <sstream>\n#include <string>\n#include <vector>\n\nnamespace terminal\n{\n\nenum class LineFlags : uint8_t\n{\n    None = 0x0000,\n    Wrappable = 0x0001,\n    Wrapped = 0x0002,\n    Marked = 0x0004,\n    // TODO: DoubleWidth  = 0x0010,\n    // TODO: DoubleHeight = 0x0020,\n};\n\n// clang-format off\ntemplate <typename, bool> struct OptionalProperty;\ntemplate <typename T> struct OptionalProperty<T, false> {};\ntemplate <typename T> struct OptionalProperty<T, true> { T value; };\n// clang-format on\n\n/**\n * Line storage with call columns sharing the same SGR attributes.\n */\nstruct TrivialLineBuffer\n{\n    ColumnCount displayWidth;\n    GraphicsAttributes textAttributes;\n    GraphicsAttributes fillAttributes = textAttributes;\n    HyperlinkId hyperlink {};\n\n    ColumnCount usedColumns {};\n    crispy::BufferFragment text {};\n\n    void reset(GraphicsAttributes _attributes) noexcept\n    {\n        textAttributes = _attributes;\n        fillAttributes = _attributes;\n        hyperlink = {};\n        usedColumns = {};\n        text.reset();\n    }\n};\n\ntemplate <typename Cell>\nusing InflatedLineBuffer = std::vector<Cell>;\n\n/// Unpacks a TrivialLineBuffer into an InflatedLineBuffer<Cell>.\ntemplate <typename Cell>\nInflatedLineBuffer<Cell> inflate(TrivialLineBuffer const& input);\n\ntemplate <typename Cell>\nusing LineStorage = std::variant<TrivialLineBuffer, InflatedLineBuffer<Cell>>;\n\n/**\n * Line<Cell> API.\n *\n * TODO: Use custom allocator for ensuring cache locality of Cells to sibling lines.\n * TODO: Make the line optimization work.\n */\ntemplate <typename Cell>\nclass Line\n{\n  public:\n    Line() = default;\n    Line(Line const&) = default;\n    Line(Line&&) noexcept = default;\n    Line& operator=(Line const&) = default;\n    Line& operator=(Line&&) noexcept = default;\n\n    using TrivialBuffer = TrivialLineBuffer;\n    using InflatedBuffer = InflatedLineBuffer<Cell>;\n    using Storage = LineStorage<Cell>;\n    using value_type = Cell;\n    using iterator = typename InflatedBuffer::iterator;\n    using reverse_iterator = typename InflatedBuffer::reverse_iterator;\n    using const_iterator = typename InflatedBuffer::const_iterator;\n\n    Line(LineFlags _flags, ColumnCount _width, GraphicsAttributes _templateSGR):\n        storage_ { TrivialBuffer { _width, _templateSGR } }, flags_ { static_cast<unsigned>(_flags) }\n    {\n    }\n\n    Line(LineFlags _flags, InflatedBuffer _buffer):\n        storage_ { std::move(_buffer) }, flags_ { static_cast<unsigned>(_flags) }\n    {\n    }\n\n    void reset(LineFlags _flags, GraphicsAttributes _attributes) noexcept\n    {\n        flags_ = static_cast<unsigned>(_flags);\n        if (isTrivialBuffer())\n            trivialBuffer().reset(_attributes);\n        else\n            setBuffer(TrivialBuffer { size(), _attributes });\n    }\n\n    void fill(LineFlags _flags,\n              GraphicsAttributes const& _attributes,\n              char32_t _codepoint,\n              uint8_t _width) noexcept\n    {\n        if (_codepoint == 0)\n            reset(_flags, _attributes);\n        else\n        {\n            flags_ = static_cast<unsigned>(_flags);\n            for (Cell& cell: inflatedBuffer())\n            {\n                cell.reset();\n                cell.write(_attributes, _codepoint, _width);\n            }\n        }\n    }\n\n    /// Tests if all cells are empty.\n    [[nodiscard]] bool empty() const noexcept\n    {\n        if (isTrivialBuffer())\n            return trivialBuffer().text.empty();\n\n        for (auto const& cell: inflatedBuffer())\n            if (!cell.empty())\n                return false;\n        return true;\n    }\n\n    /**\n     * Fills this line with the given content.\n     *\n     * @p _start offset into this line of the first charater\n     * @p _sgr graphics rendition for the line starting at @c _start until the end\n     * @p _ascii the US-ASCII characters to fill with\n     */\n    void fill(ColumnOffset _start, GraphicsAttributes const& _sgr, std::string_view _ascii)\n    {\n        auto& buffer = inflatedBuffer();\n\n        assert(unbox<size_t>(_start) + _ascii.size() <= buffer.size());\n\n        auto constexpr ASCII_Width = 1;\n        auto const* s = _ascii.data();\n\n        Cell* i = &buffer[unbox<size_t>(_start)];\n        Cell* e = i + _ascii.size();\n        while (i != e)\n            (i++)->write(_sgr, static_cast<char32_t>(*s++), ASCII_Width);\n\n        auto const e2 = buffer.data() + buffer.size();\n        while (i != e2)\n            (i++)->reset();\n    }\n\n    [[nodiscard]] ColumnCount size() const noexcept\n    {\n        if (isTrivialBuffer())\n            return trivialBuffer().displayWidth;\n        else\n            return ColumnCount::cast_from(inflatedBuffer().size());\n    }\n\n    void resize(ColumnCount _count);\n\n    gsl::span<Cell const> trim_blank_right() const noexcept;\n\n    gsl::span<Cell const> cells() const noexcept { return inflatedBuffer(); }\n\n    gsl::span<Cell> useRange(ColumnOffset _start, ColumnCount _count) noexcept\n    {\n#if defined(__clang__) && __clang_major__ <= 11\n        auto const bufferSpan = gsl::span(inflatedBuffer());\n        return bufferSpan.subspan(unbox<size_t>(_start), unbox<size_t>(_count));\n#else\n        // Clang <= 11 cannot deal with this (e.g. FreeBSD 13 defaults to Clang 11).\n        return gsl::span(inflatedBuffer()).subspan(unbox<size_t>(_start), unbox<size_t>(_count));\n#endif\n    }\n\n    Cell& useCellAt(ColumnOffset _column) noexcept\n    {\n        Require(ColumnOffset(0) <= _column);\n        Require(_column <= ColumnOffset::cast_from(size())); // Allow off-by-one for sentinel.\n        return inflatedBuffer()[unbox<size_t>(_column)];\n    }\n\n    [[nodiscard]] uint8_t cellEmptyAt(ColumnOffset column) const noexcept\n    {\n        if (isTrivialBuffer())\n        {\n            Require(ColumnOffset(0) <= column);\n            Require(column < ColumnOffset::cast_from(size()));\n            return unbox<size_t>(column) >= trivialBuffer().text.size()\n                   || trivialBuffer().text[column.as<size_t>()] == 0x20;\n        }\n        return inflatedBuffer().at(unbox<size_t>(column)).empty();\n    }\n\n    [[nodiscard]] uint8_t cellWithAt(ColumnOffset column) const noexcept\n    {\n        if (isTrivialBuffer())\n        {\n            Require(ColumnOffset(0) <= column);\n            Require(column < ColumnOffset::cast_from(size()));\n            return 1; // TODO: When trivial line is to support Unicode, this should be adapted here.\n        }\n        return inflatedBuffer().at(unbox<size_t>(column)).width();\n    }\n\n    [[nodiscard]] LineFlags flags() const noexcept\n    {\n        return static_cast<LineFlags>(flags_);\n    }\n\n    [[nodiscard]] bool marked() const noexcept\n    {\n        return isFlagEnabled(LineFlags::Marked);\n    }\n    void setMarked(bool _enable)\n    {\n        setFlag(LineFlags::Marked, _enable);\n    }\n\n    [[nodiscard]] bool wrapped() const noexcept\n    {\n        return isFlagEnabled(LineFlags::Wrapped);\n    }\n    void setWrapped(bool _enable)\n    {\n        setFlag(LineFlags::Wrapped, _enable);\n    }\n\n    [[nodiscard]] bool wrappable() const noexcept\n    {\n        return isFlagEnabled(LineFlags::Wrappable);\n    }\n    void setWrappable(bool _enable)\n    {\n        setFlag(LineFlags::Wrappable, _enable);\n    }\n\n    [[nodiscard]] LineFlags wrappableFlag() const noexcept\n    {\n        return wrappable() ? LineFlags::Wrappable : LineFlags::None;\n    }\n    [[nodiscard]] LineFlags wrappedFlag() const noexcept\n    {\n        return marked() ? LineFlags::Wrapped : LineFlags::None;\n    }\n    [[nodiscard]] LineFlags markedFlag() const noexcept\n    {\n        return marked() ? LineFlags::Marked : LineFlags::None;\n    }\n\n    [[nodiscard]] LineFlags inheritableFlags() const noexcept\n    {\n        auto constexpr Inheritables = unsigned(LineFlags::Wrappable) | unsigned(LineFlags::Marked);\n        return static_cast<LineFlags>(flags_ & Inheritables);\n    }\n\n    void setFlag(LineFlags _flag, bool _enable) noexcept\n    {\n        if (_enable)\n            flags_ |= static_cast<unsigned>(_flag);\n        else\n            flags_ &= ~static_cast<unsigned>(_flag);\n    }\n\n    [[nodiscard]] bool isFlagEnabled(LineFlags _flag) const noexcept\n    {\n        return (flags_ & static_cast<unsigned>(_flag)) != 0;\n    }\n\n    [[nodiscard]] InflatedBuffer reflow(ColumnCount _newColumnCount);\n    [[nodiscard]] std::string toUtf8() const;\n    [[nodiscard]] std::string toUtf8Trimmed() const;\n\n    // Returns a reference to this mutable grid-line buffer.\n    //\n    // If this line has been stored in an optimized state, then\n    // the line will be first unpacked into a vector of grid cells.\n    InflatedBuffer& inflatedBuffer();\n    InflatedBuffer const& inflatedBuffer() const;\n\n    [[nodiscard]] TrivialBuffer& trivialBuffer() noexcept\n    {\n        return std::get<TrivialBuffer>(storage_);\n    }\n    [[nodiscard]] TrivialBuffer const& trivialBuffer() const noexcept\n    {\n        return std::get<TrivialBuffer>(storage_);\n    }\n\n    [[nodiscard]] bool isTrivialBuffer() const noexcept\n    {\n        return std::holds_alternative<TrivialBuffer>(storage_);\n    }\n    [[nodiscard]] bool isInflatedBuffer() const noexcept\n    {\n        return !std::holds_alternative<TrivialBuffer>(storage_);\n    }\n\n    void setBuffer(TrivialBuffer const& buffer) noexcept\n    {\n        storage_ = buffer;\n    }\n    void setBuffer(InflatedBuffer buffer)\n    {\n        storage_ = std::move(buffer);\n    }\n\n    void reset(GraphicsAttributes textAttributes,\n               GraphicsAttributes fillAttributes,\n               HyperlinkId hyperlink,\n               crispy::BufferFragment text,\n               ColumnCount columnsUsed)\n    {\n        storage_ =\n            TrivialBuffer { size(), textAttributes, fillAttributes, hyperlink, columnsUsed, std::move(text) };\n    }\n\n  private:\n    Storage storage_;\n    unsigned flags_ = 0;\n};\n\nconstexpr LineFlags operator|(LineFlags a, LineFlags b) noexcept\n{\n    return LineFlags(unsigned(a) | unsigned(b));\n}\n\nconstexpr LineFlags operator~(LineFlags a) noexcept\n{\n    return LineFlags(~unsigned(a));\n}\n\nconstexpr LineFlags operator&(LineFlags a, LineFlags b) noexcept\n{\n    return LineFlags(unsigned(a) & unsigned(b));\n}\n\ntemplate <typename Cell>\ninline typename Line<Cell>::InflatedBuffer& Line<Cell>::inflatedBuffer()\n{\n    if (std::holds_alternative<TrivialBuffer>(storage_))\n        storage_ = inflate<Cell>(std::get<TrivialBuffer>(storage_));\n    return std::get<InflatedBuffer>(storage_);\n}\n\ntemplate <typename Cell>\ninline typename Line<Cell>::InflatedBuffer const& Line<Cell>::inflatedBuffer() const\n{\n    return const_cast<Line<Cell>*>(this)->inflatedBuffer();\n}\n\n} // namespace terminal\n\nnamespace fmt // {{{\n{\ntemplate <>\nstruct formatter<terminal::LineFlags>\n{\n    template <typename ParseContext>\n    auto parse(ParseContext& ctx)\n    {\n        return ctx.begin();\n    }\n    template <typename FormatContext>\n    auto format(const terminal::LineFlags _flags, FormatContext& ctx) const\n    {\n        static const std::array<std::pair<terminal::LineFlags, std::string_view>, 3> nameMap = {\n            std::pair { terminal::LineFlags::Wrappable, std::string_view(\"Wrappable\") },\n            std::pair { terminal::LineFlags::Wrapped, std::string_view(\"Wrapped\") },\n            std::pair { terminal::LineFlags::Marked, std::string_view(\"Marked\") },\n        };\n        std::string s;\n        for (auto const& mapping: nameMap)\n        {\n            if ((mapping.first & _flags) != terminal::LineFlags::None)\n            {\n                if (!s.empty())\n                    s += \",\";\n                s += mapping.second;\n            }\n        }\n        return fmt::format_to(ctx.out(), \"{}\", s);\n    }\n};\n} // namespace fmt\n", "meta": {"hexsha": "3a94504a6f2ab4ad83940910384e77f741924e3d", "size": 12468, "ext": "h", "lang": "C", "max_stars_repo_path": "src/terminal/Line.h", "max_stars_repo_name": "christianparpart/libterminal", "max_stars_repo_head_hexsha": "0e6d75a2042437084c9f9880a5c8b5661a02da07", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-08-14T22:29:57.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-19T08:57:15.000Z", "max_issues_repo_path": "src/terminal/Line.h", "max_issues_repo_name": "christianparpart/libterminal", "max_issues_repo_head_hexsha": "0e6d75a2042437084c9f9880a5c8b5661a02da07", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 69.0, "max_issues_repo_issues_event_min_datetime": "2019-08-17T18:57:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-22T23:25:49.000Z", "max_forks_repo_path": "src/terminal/Line.h", "max_forks_repo_name": "christianparpart/libterminal", "max_forks_repo_head_hexsha": "0e6d75a2042437084c9f9880a5c8b5661a02da07", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8277511962, "max_line_length": 110, "alphanum_fraction": 0.6407603465, "num_tokens": 2919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08756384904745383, "lm_q2_score": 0.0255652142016788, "lm_q1q2_score": 0.0022385885572216253}}
{"text": "/* err/gsl_message.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_MESSAGE_H__\n#define __GSL_MESSAGE_H__\n#include <gsl/gsl_types.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\n/* Provide a general messaging service for client use.  Messages can\n * be selectively turned off at compile time by defining an\n * appropriate message mask. Client code which uses the GSL_MESSAGE()\n * macro must provide a mask which is or'ed with the GSL_MESSAGE_MASK.\n *\n * The messaging service can be completely turned off\n * by defining GSL_MESSAGING_OFF.  */\n\nvoid gsl_message(const char * message, const char * file, int line,\n                 unsigned int mask);\n\n#ifndef GSL_MESSAGE_MASK\n#define GSL_MESSAGE_MASK 0xffffffffu /* default all messages allowed */\n#endif\n\nGSL_VAR unsigned int gsl_message_mask ;\n\n/* Provide some symolic masks for client ease of use. */\n\nenum {\n  GSL_MESSAGE_MASK_A = 1,\n  GSL_MESSAGE_MASK_B = 2,\n  GSL_MESSAGE_MASK_C = 4,\n  GSL_MESSAGE_MASK_D = 8,\n  GSL_MESSAGE_MASK_E = 16,\n  GSL_MESSAGE_MASK_F = 32,\n  GSL_MESSAGE_MASK_G = 64,\n  GSL_MESSAGE_MASK_H = 128\n} ;\n\n#ifdef GSL_MESSAGING_OFF        /* throw away messages */ \n#define GSL_MESSAGE(message, mask) do { } while(0)\n#else                           /* output all messages */\n#define GSL_MESSAGE(message, mask) \\\n       do { \\\n       if (mask & GSL_MESSAGE_MASK) \\\n         gsl_message (message, __FILE__, __LINE__, mask) ; \\\n       } while (0)\n#endif\n\n__END_DECLS\n\n#endif /* __GSL_MESSAGE_H__ */\n\n\n", "meta": {"hexsha": "4d3a9d51302678270ca6428e2938548cd371996c", "size": 2420, "ext": "h", "lang": "C", "max_stars_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_message.h", "max_stars_repo_name": "snipekill/FPGen", "max_stars_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-07-06T02:44:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T21:02:18.000Z", "max_issues_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_message.h", "max_issues_repo_name": "snipekill/FPGen", "max_issues_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_message.h", "max_forks_repo_name": "snipekill/FPGen", "max_forks_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-06-27T11:11:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T19:22:30.000Z", "avg_line_length": 29.8765432099, "max_line_length": 81, "alphanum_fraction": 0.7190082645, "num_tokens": 600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06465348294947952, "lm_q2_score": 0.034618836847166316, "lm_q1q2_score": 0.0022382283778290806}}
{"text": "#pragma once\n\n#include <filesystem>\n#include <unordered_map>\n#include <optional>\n#include <variant>\n#include <string>\n#include <vector>\n#include <gsl/gsl>\n#include <DirectML.h>\n#include \"BucketAllocator.h\"\n\nclass Model\n{\npublic:\n    // When binding a buffer to an operator it is possible to use a subregion of\n    // the buffer by specifying an elementOffset, elementCount, and elementSizeInBytes.\n    // Additionally, an optional format specifier dictates how to interpret the buffer\n    // contents; when omitted the buffer will be interpreted using the same data type used\n    // to initialize it.\n    struct BufferBindingSource\n    {\n        std::string name;\n        uint64_t elementCount;\n        uint64_t elementSizeInBytes;\n        uint64_t elementOffset;\n        std::optional<DXGI_FORMAT> format;\n\n        // For Append/Consume buffers only:\n        std::optional<std::string> counterName;\n        uint64_t counterOffsetBytes;\n    };\n\n    using Bindings = std::unordered_map<std::string, std::vector<BufferBindingSource>>;\n\n    // RESOURCES\n    // ------------------------------------------------------------------------\n\n    struct BufferDesc\n    {\n        uint64_t sizeInBytes;\n        std::vector<std::byte> initialValues;\n        DML_TENSOR_DATA_TYPE initialValuesDataType;\n        uint64_t initialValuesOffsetInBytes;\n    };\n\n    struct ResourceDesc\n    {\n        std::string name;\n        std::variant<BufferDesc> value;\n    };\n\n    // DISPATCHABLES\n    // ------------------------------------------------------------------------\n\n    struct DmlDispatchableDesc\n    {\n        struct BindPoint\n        {\n            std::string name;\n            uint32_t resourceCount;\n            bool required;\n        };\n\n        struct BindPoints\n        {\n            std::vector<BindPoint> inputs;\n            std::vector<BindPoint> outputs;\n        };\n\n        DML_OPERATOR_DESC* desc;\n        BindPoints bindPoints;\n        DML_EXECUTION_FLAGS executionFlags;\n        Bindings initBindings;\n    };\n\n    struct HlslDispatchableDesc\n    {\n        enum class Compiler\n        {\n            DXC\n        };\n\n        std::filesystem::path sourcePath;\n        Compiler compiler;\n        std::vector<std::string> compilerArgs;\n    };\n\n    struct DispatchableDesc\n    {\n        std::string name;\n        std::variant<DmlDispatchableDesc, HlslDispatchableDesc> value;\n    };\n\n    // COMMANDS\n    // ------------------------------------------------------------------------\n\n    struct DispatchCommand\n    {\n        std::string dispatchableName;\n        Bindings bindings;\n        std::array<uint32_t, 3> threadGroupCount;\n    };\n\n    struct PrintCommand\n    {\n        std::string resourceName;\n    };\n\n    using Command = std::variant<DispatchCommand, PrintCommand>;\n\n    Model() = default;\n\n    Model(\n        std::vector<ResourceDesc>&& resourceDescs,\n        std::vector<DispatchableDesc>&& dispatchableDescs,\n        std::vector<Command>&& commands,\n        BucketAllocator&& allocator);\n\n    Model(const Model&) = delete;\n    Model& operator=(const Model&) = delete;\n    Model(Model&&) = default;\n    Model& operator=(Model&&) = default;\n\n    gsl::span<const ResourceDesc> GetResourceDescs() const { return m_resourceDescs; }\n    gsl::span<const DispatchableDesc> GetDispatchableDescs() const { return m_dispatchableDescs; }\n    gsl::span<const Command> GetCommands() const { return m_commands; }\n\n    const ResourceDesc& GetResource(std::string_view name) const { return *m_resourceDescsByName.find(name.data())->second; }\n    const DispatchableDesc& GetDispatchable(std::string_view name) const { return *m_dispatchableDescsByName.find(name.data())->second; }\n\nprivate:\n    std::vector<ResourceDesc> m_resourceDescs;\n    std::vector<DispatchableDesc> m_dispatchableDescs;\n    std::vector<Command> m_commands;\n    BucketAllocator m_allocator;\n    std::unordered_map<std::string, ResourceDesc*> m_resourceDescsByName;\n    std::unordered_map<std::string, DispatchableDesc*> m_dispatchableDescsByName;\n};", "meta": {"hexsha": "bcba7ac3fabd72d1bfa7c9357ab8de4fd081d6cf", "size": 4003, "ext": "h", "lang": "C", "max_stars_repo_path": "DxDispatch/src/model/Model.h", "max_stars_repo_name": "miaobin/DirectML", "max_stars_repo_head_hexsha": "d4657006a60a7b7d9baf17638c42aee27258c836", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2019-05-07T14:41:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-14T07:36:27.000Z", "max_issues_repo_path": "DxDispatch/src/model/Model.h", "max_issues_repo_name": "miaobin/DirectML", "max_issues_repo_head_hexsha": "d4657006a60a7b7d9baf17638c42aee27258c836", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2019-05-10T09:12:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-09T01:51:06.000Z", "max_forks_repo_path": "DxDispatch/src/model/Model.h", "max_forks_repo_name": "miaobin/DirectML", "max_forks_repo_head_hexsha": "d4657006a60a7b7d9baf17638c42aee27258c836", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2019-05-13T12:56:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-12T15:57:58.000Z", "avg_line_length": 28.7985611511, "max_line_length": 137, "alphanum_fraction": 0.6215338496, "num_tokens": 876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12252320610998797, "lm_q2_score": 0.018264276581735482, "lm_q1q2_score": 0.0022377977240738032}}
{"text": "#pragma once\n\n#include <gsl.h>\n#include <ImmutableRanges.h>\n#include <qobject.h>\n\n#include <mitkBaseData.h>\n#include <FaceIdentifier.h>\n\nclass QWidget;\n\nnamespace crimson\n{\nclass QtPropertyStorage;\n\n/*! \\brief   An interface for data associated with model faces.\n * \n * This includes boundary conditions and materials.\n */\nclass FaceData : public mitk::BaseData\n{\npublic:\n    mitkClassMacro(FaceData, BaseData);\n\n    /*!\n     * \\brief   Gets the FaceData object name.\n     */\n    virtual gsl::cstring_span<> getName() const = 0;\n\n    /*!\n     * \\brief   Gets the list of face types (as defined by FaceIdentifer::FaceType) that the face\n     *  data can be applied to.\n     */\n    virtual ImmutableRefRange<FaceIdentifier::FaceType> applicableFaceTypes() = 0;\n\n    ///@{ \n    /*!\n     * \\brief   Sets the identifiers of the faces the FaceData is applied to.\n     */\n    virtual void setFaces(ImmutableRefRange<FaceIdentifier> faces) = 0;\n\n    /*!\n    * \\brief   Gets the identifiers of the faces the FaceData is applied to.\n    */\n    virtual ImmutableRefRange<FaceIdentifier> getFaces() const = 0;\n    ///@} \n\n    /*!\n     * \\brief   Creates custom editor widget which should be added to the UI.\n     */\n    virtual QWidget* createCustomEditorWidget() { return nullptr; }\n\n    /*!\n     * \\brief   Gets property storage for the FaceData properties.\n     */\n    virtual gsl::not_null<QtPropertyStorage*> getPropertyStorage() = 0;\n\n\t/*!\n\t* \\brief  stores a pointer to C++ owned data object. For use in python-based boundary conditions that have the logic\n\timplemented in C++\n\t*/\n\tvirtual void setDataObject(QVariantList data){}; \n\n\tvirtual void setDataUID(std::string dataUID){};\n\n\tvirtual std::string getDataUID(){ return std::string{}; };\n\n\n\nprotected:\n    FaceData() { mitk::BaseData::InitializeTimeGeometry(1); }\n    virtual ~FaceData() {}\n\n    FaceData(const Self&) = default;\n\n    void SetRequestedRegion(const itk::DataObject*) override {}\n    void SetRequestedRegionToLargestPossibleRegion() override {}\n    bool RequestedRegionIsOutsideOfTheBufferedRegion() override { return true; }\n    bool VerifyRequestedRegion() override { return true; }\n};\n\n} // end namespace crimson\n", "meta": {"hexsha": "93c288e2a9be706fb883a0664ca092096b327179", "size": 2180, "ext": "h", "lang": "C", "max_stars_repo_path": "Modules/SolverSetupService/include/FaceData.h", "max_stars_repo_name": "carthurs/CRIMSONGUI", "max_stars_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-09-17T18:55:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T02:52:38.000Z", "max_issues_repo_path": "Modules/SolverSetupService/include/FaceData.h", "max_issues_repo_name": "carthurs/CRIMSONGUI", "max_issues_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Modules/SolverSetupService/include/FaceData.h", "max_forks_repo_name": "carthurs/CRIMSONGUI", "max_forks_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-05-19T09:02:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-26T17:39:57.000Z", "avg_line_length": 26.265060241, "max_line_length": 117, "alphanum_fraction": 0.6848623853, "num_tokens": 520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09807932874307332, "lm_q2_score": 0.02262920266960349, "lm_q1q2_score": 0.002219457007825673}}
{"text": "#pragma once\n#include \"utility/types.h\"\n#include <gsl/gsl>\n#include <array>\n\nnamespace cws80 {\n\nextern std::array<gsl::span<const u8>, 11> extra_bank_data;\n\n}  // namespace cws80\n", "meta": {"hexsha": "670e17db220dc4c839ad8e643e9ffc6f2bcd0ae3", "size": 179, "ext": "h", "lang": "C", "max_stars_repo_path": "sources/cws/cws80_data_banks.h", "max_stars_repo_name": "jpcima/cws80", "max_stars_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-05-20T19:27:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-03T04:21:53.000Z", "max_issues_repo_path": "sources/cws/cws80_data_banks.h", "max_issues_repo_name": "jpcima/cws80", "max_issues_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-05-21T12:56:22.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-23T21:33:33.000Z", "max_forks_repo_path": "sources/cws/cws80_data_banks.h", "max_forks_repo_name": "jpcima/cws80", "max_forks_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.2727272727, "max_line_length": 59, "alphanum_fraction": 0.7150837989, "num_tokens": 52, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.09807932874307332, "lm_q2_score": 0.022286183388160817, "lm_q1q2_score": 0.002185813906955844}}
{"text": "#pragma once\n\n#include \"Common.h\"\n#include \"PEFile.h\"\n#include \"DelayLoadedModule.h\"\n\n#include <gsl/gsl>\n\nnamespace winlogo::pe_parser {\n\nnamespace details {\n/**\n * This is an input iterator for iterating over the delay-loaded modules of the delay-load\n * directory.\n */\nclass DelayLoadDirectoryIterator {\npublic:\n    DelayLoadDirectoryIterator(PEFile file,\n                               gsl::span<IMAGE_DELAYLOAD_DESCRIPTOR>::iterator iterator);\n\n    bool operator==(const DelayLoadDirectoryIterator& other) const noexcept;\n    bool operator!=(const DelayLoadDirectoryIterator& other) const noexcept;\n\n    DelayLoadedModule operator*() const noexcept;\n    DelayLoadDirectoryIterator& operator++() noexcept;\n\nprivate:\n    PEFile m_peFile;\n    gsl::span<IMAGE_DELAYLOAD_DESCRIPTOR>::iterator m_current;\n};\n\n}  // namespace details\n\n/**\n * This class represents an iterable view of a PE file's delay-loaded directory.\n */\nclass DelayLoadDirectory {\npublic:\n    /**\n     * Initialize the delay-load directory from its PE file.\n     */\n    explicit DelayLoadDirectory(PEFile peFile);\n\n    /**\n     * Get the raw import descriptors.\n     */\n    gsl::span<IMAGE_DELAYLOAD_DESCRIPTOR> rawDelayLoadDescriptors() const noexcept;\n\n    // Iterators for iterating over the imported modules.\n\n    details::DelayLoadDirectoryIterator begin() const noexcept;\n    details::DelayLoadDirectoryIterator end() const noexcept;\n\nprivate:\n    /// The owning PE file.\n    PEFile m_peFile;\n    gsl::span<IMAGE_DELAYLOAD_DESCRIPTOR> m_delayLoadDescriptors;\n};\n\n}  // namespace winlogo::pe_parser\n", "meta": {"hexsha": "9d7da9e26a242eabd39719ff7638b2546e4b0a8b", "size": 1571, "ext": "h", "lang": "C", "max_stars_repo_path": "winlogo_core/DelayLoadDirectory.h", "max_stars_repo_name": "shsh999/WinLogo", "max_stars_repo_head_hexsha": "9ad51469e3ed4bb593303d4d7919c484a3be092e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2021-09-04T22:10:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T07:18:03.000Z", "max_issues_repo_path": "winlogo_core/DelayLoadDirectory.h", "max_issues_repo_name": "shsh999/WinLogo", "max_issues_repo_head_hexsha": "9ad51469e3ed4bb593303d4d7919c484a3be092e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-23T01:01:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-29T12:13:05.000Z", "max_forks_repo_path": "winlogo_core/DelayLoadDirectory.h", "max_forks_repo_name": "shsh999/WinLogo", "max_forks_repo_head_hexsha": "9ad51469e3ed4bb593303d4d7919c484a3be092e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-20T12:06:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T12:06:02.000Z", "avg_line_length": 25.7540983607, "max_line_length": 90, "alphanum_fraction": 0.723742839, "num_tokens": 332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08509904964767095, "lm_q2_score": 0.025565216660960226, "lm_q1q2_score": 0.002175575641884519}}
{"text": "#pragma once\n\n#include \"BasicTypes.h\"\n#include \"CharInfo.h\"\n#include \"Distance.h\"\n#include \"FontTypes.h\"\n#include \"types/ND0.h\"\n#include \"types/ND1_Node.h\"\n#include \"types/ND1_Box.h\"\n#include \"types/ND2_Char.h\"\n#include \"types/ND2_Box.h\"\n#include \"types/ND2_Rule.h\"\n#include \"types/ND2_Glue.h\"\n#include \"types/ND2_Kern.h\"\n#include \"types/ND2_Penalty.h\"\n#include <gsl.h>\n#include <list>\n\n", "meta": {"hexsha": "7741ef9fc9b866a0203787414766e71be4ac10db", "size": 387, "ext": "h", "lang": "C", "max_stars_repo_path": "include/node/BoxTypes.h", "max_stars_repo_name": "robin33n/formulae-cxx", "max_stars_repo_head_hexsha": "4b691e515b30508fb5e29c68426bad51d9629e72", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-25T04:00:03.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-25T04:00:03.000Z", "max_issues_repo_path": "include/node/BoxTypes.h", "max_issues_repo_name": "robin33n/formulae-cxx", "max_issues_repo_head_hexsha": "4b691e515b30508fb5e29c68426bad51d9629e72", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-09-25T11:10:39.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-26T11:32:00.000Z", "max_forks_repo_path": "include/node/BoxTypes.h", "max_forks_repo_name": "robin33n/formulae-cxx", "max_forks_repo_head_hexsha": "4b691e515b30508fb5e29c68426bad51d9629e72", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.3684210526, "max_line_length": 30, "alphanum_fraction": 0.7338501292, "num_tokens": 122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.12252319970181706, "lm_q2_score": 0.017712295333045497, "lm_q1q2_score": 0.0021701670982682956}}
{"text": "\ufeff/**\n * @file coroutine/unix.h\n * @author github.com/luncliff (luncliff@gmail.com)\n * @copyright CC BY 4.0\n */\n#ifndef COROUTINE_SYSTEM_WRAPPER_H\n#define COROUTINE_SYSTEM_WRAPPER_H\n#if !(defined(unix) || defined(__APPLE__) || defined(__FreeBSD__))\n#error \"expect UNIX platform for this file\"\n#endif\n#include <sys/event.h> // for BSD kqueue\n\n#include <gsl/gsl>\n\n#include <coroutine/return.h>\n\n/**\n * @defgroup BSD\n */\n\nnamespace coro {\n\n/**\n * @brief RAII wrapping for kqueue file descriptor\n * @ingroup BSD\n */\nclass kqueue_owner final {\n    int64_t kqfd;\n\n  public:\n    /**\n     * @brief create a fd with `kqueue`. Throw if the function fails.\n     * @see kqeueue\n     * @throw system_error\n     */\n    kqueue_owner() noexcept(false);\n    /**\n     * @brief close the current kqueue file descriptor\n     */\n    ~kqueue_owner() noexcept;\n    kqueue_owner(const kqueue_owner&) = delete;\n    kqueue_owner(kqueue_owner&&) = delete;\n    kqueue_owner& operator=(const kqueue_owner&) = delete;\n    kqueue_owner& operator=(kqueue_owner&&) = delete;\n\n  public:\n    /**\n     * @brief bind the event to kqueue\n     * @param req \n     * @see kevent64\n     * @throw system_error\n     * \n     * The function is named `change` because \n     * the given argument is used for 'change list' fo `kqueue64`\n     */\n    void change(kevent64_s& req) noexcept(false);\n\n    /**\n     * @brief fetch all events for the given kqeueue descriptor\n     * @param wait_time \n     * @param list \n     * @return ptrdiff_t \n     * @see kevent64\n     * @throw system_error\n     * \n     * The function is named `events` because \n     * the given argument is used for 'event list' fo `kqueue64`\n     * \n     * Timeout is not an error for this function\n     */\n    ptrdiff_t events(const timespec& wait_time,\n                     gsl::span<kevent64_s> list) noexcept(false);\n\n  public:\n    /**\n     * @brief return temporary awaitable object for given event\n     * @param req input for `change` operation \n     * @see change\n     * \n     * There is no guarantee of reusage of returned awaiter object\n     * When it is awaited, and `req.udata` is null(0),\n     * the value is set to `coroutine_handle<void>`\n     * \n     * @code\n     * auto read_async(kqueue_owner& kq, uint64_t fd) -> frame_t {\n     *     kevent64_s req{.ident = fd,\n     *                    .filter = EVFILT_READ,\n     *                    .flags = EV_ADD | EV_ENABLE | EV_ONESHOT};\n     *     co_await kq.submit(req);\n     *     // ...\n     *     co_await kq.submit(req);\n     *     // ...\n     * }\n     * @endcode\n     */\n    [[nodiscard]] auto submit(kevent64_s& req) noexcept {\n        class awaiter final : public suspend_always {\n            kqueue_owner& kq;\n            kevent64_s& req;\n\n          public:\n            constexpr awaiter(kqueue_owner& _kq, kevent64_s& _req)\n                : kq{_kq}, req{_req} {\n            }\n\n          public:\n            void await_suspend(coroutine_handle<void> coro) noexcept(false) {\n                if (req.udata == 0)\n                    req.udata = reinterpret_cast<uint64_t>(coro.address());\n                return kq.change(req);\n            }\n        };\n        return awaiter{*this, req};\n    }\n};\n\n} // namespace coro\n\n#endif // COROUTINE_SYSTEM_WRAPPER_H\n", "meta": {"hexsha": "5404743185aa6ecba3a1e4ea9e28df7e5d918cca", "size": 3241, "ext": "h", "lang": "C", "max_stars_repo_path": "interface/coroutine/unix.h", "max_stars_repo_name": "lanza/coroutine", "max_stars_repo_head_hexsha": "c90caab988f96997f5bc1bd6f1958b80524fa14a", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 368.0, "max_stars_repo_stars_event_min_datetime": "2018-11-22T22:57:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T04:04:54.000Z", "max_issues_repo_path": "interface/coroutine/unix.h", "max_issues_repo_name": "lanza/coroutine", "max_issues_repo_head_hexsha": "c90caab988f96997f5bc1bd6f1958b80524fa14a", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 35.0, "max_issues_repo_issues_event_min_datetime": "2018-11-09T04:38:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-27T01:10:02.000Z", "max_forks_repo_path": "interface/coroutine/unix.h", "max_forks_repo_name": "lanza/coroutine", "max_forks_repo_head_hexsha": "c90caab988f96997f5bc1bd6f1958b80524fa14a", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 29.0, "max_forks_repo_forks_event_min_datetime": "2018-12-26T14:03:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T17:36:55.000Z", "avg_line_length": 27.0083333333, "max_line_length": 77, "alphanum_fraction": 0.5896328294, "num_tokens": 852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07263670033827889, "lm_q2_score": 0.029760094806489328, "lm_q1q2_score": 0.0021616750884977352}}
{"text": "#pragma once\n\n#include \"BoundingVolume.h\"\n#include \"Library.h\"\n#include \"Tile.h\"\n#include \"TileContext.h\"\n#include \"TileID.h\"\n#include \"TileRefine.h\"\n#include \"TilesetOptions.h\"\n\n#include <CesiumAsync/AsyncSystem.h>\n#include <CesiumAsync/IAssetAccessor.h>\n#include <CesiumAsync/IAssetRequest.h>\n\n#include <gsl/span>\n#include <spdlog/fwd.h>\n\n#include <cstddef>\n#include <memory>\n\nnamespace Cesium3DTilesSelection {\n/**\n * @brief The information that is passed to a {@link TileContentLoader} to\n * create a {@link TileContentLoadResult}.\n *\n * For many types of tile content, only the `pRequest` field is required. The\n * other members are used for content that can generate child tiles, like\n * external tilesets or composite tiles. These members are usually initialized\n * from\n * the corresponding members of the {@link Tile} that the content belongs to.\n */\nstruct CESIUM3DTILESSELECTION_API TileContentLoadInput {\n\n  /**\n   * @brief Creates a new, uninitialized instance for the given tile.\n   *\n   * The `asyncSystem`, `pLogger`, `pAssetAccessor` and `pRequest` will have\n   * default values, and have to be initialized before this instance is passed\n   * to one of the loader functions.\n   *\n   * @param tile The {@link Tile} that the content belongs to\n   */\n  TileContentLoadInput(const Tile& tile);\n\n  /**\n   * @brief Creates a new instance\n   *\n   * @param asyncSystem The async system to use for tile content loading.\n   * @param pLogger The logger that will be used\n   * @param pAssetAccessor The asset accessor to make further requests with.\n   * @param pRequest The original tile request and its response.\n   * @param tile The {@link Tile} that the content belongs to.\n   */\n  TileContentLoadInput(\n      const CesiumAsync::AsyncSystem& asyncSystem,\n      const std::shared_ptr<spdlog::logger>& pLogger,\n      const std::shared_ptr<CesiumAsync::IAssetAccessor>& pAssetAccessor,\n      const std::shared_ptr<CesiumAsync::IAssetRequest>& pRequest,\n      const Tile& tile);\n\n  /**\n   * @brief Creates a new instance.\n   *\n   * @param asyncSystem The async system to use for tile content loading.\n   * @param pLogger The logger that will be used\n   * @param pAssetAccessor The asset accessor to make further requests with.\n   * @param pRequest The original tile request and its response.\n   * @param tileID The {@link TileID}\n   * @param tileBoundingVolume The tile {@link BoundingVolume}\n   * @param tileContentBoundingVolume The tile content {@link BoundingVolume}\n   * @param tileRefine The {@link TileRefine} strategy\n   * @param tileGeometricError The geometric error of the tile\n   * @param tileTransform The tile transform\n   */\n  TileContentLoadInput(\n      const CesiumAsync::AsyncSystem& asyncSystem,\n      const std::shared_ptr<spdlog::logger>& pLogger,\n      const std::shared_ptr<CesiumAsync::IAssetAccessor>& pAssetAccessor,\n      const std::shared_ptr<CesiumAsync::IAssetRequest>& pRequest,\n      const TileID& tileID,\n      const BoundingVolume& tileBoundingVolume,\n      const std::optional<BoundingVolume>& tileContentBoundingVolume,\n      TileRefine tileRefine,\n      double tileGeometricError,\n      const glm::dmat4& tileTransform,\n      const TilesetContentOptions& contentOptions);\n\n  /**\n   * @brief The async system to use for tile content loading.\n   */\n  CesiumAsync::AsyncSystem asyncSystem;\n\n  /**\n   * @brief The logger that receives details of loading errors and warnings.\n   */\n  std::shared_ptr<spdlog::logger> pLogger;\n\n  /**\n   * @brief The asset accessor to make further requests with.\n   */\n  std::shared_ptr<CesiumAsync::IAssetAccessor> pAssetAccessor;\n\n  /**\n   * @brief The asset request and response data for the tile.\n   */\n  std::shared_ptr<CesiumAsync::IAssetRequest> pRequest;\n\n  /**\n   * @brief The {@link TileID}.\n   */\n  TileID tileID;\n\n  /**\n   * @brief The tile {@link BoundingVolume}.\n   */\n  BoundingVolume tileBoundingVolume;\n\n  /**\n   * @brief Tile content {@link BoundingVolume}.\n   */\n  std::optional<BoundingVolume> tileContentBoundingVolume;\n\n  /**\n   * @brief The {@link TileRefine}.\n   */\n  TileRefine tileRefine;\n\n  /**\n   * @brief The geometric error.\n   */\n  double tileGeometricError;\n\n  /**\n   * @brief The tile transform\n   */\n  glm::dmat4 tileTransform;\n\n  /**\n   * @brief Options for parsing content and creating Gltf models.\n   */\n  TilesetContentOptions contentOptions;\n};\n} // namespace Cesium3DTilesSelection\n", "meta": {"hexsha": "b4f59680b7bfc2e2168e5145b6f3d8cbb13343c3", "size": 4389, "ext": "h", "lang": "C", "max_stars_repo_path": "Cesium3DTilesSelection/include/Cesium3DTilesSelection/TileContentLoadInput.h", "max_stars_repo_name": "JiangMuWen/cesium-native", "max_stars_repo_head_hexsha": "1d9912307336c833b74b7e9b7bc715d0a4e6c7ec", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-10-02T17:45:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-02T17:45:15.000Z", "max_issues_repo_path": "Cesium3DTilesSelection/include/Cesium3DTilesSelection/TileContentLoadInput.h", "max_issues_repo_name": "JiangMuWen/cesium-native", "max_issues_repo_head_hexsha": "1d9912307336c833b74b7e9b7bc715d0a4e6c7ec", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cesium3DTilesSelection/include/Cesium3DTilesSelection/TileContentLoadInput.h", "max_forks_repo_name": "JiangMuWen/cesium-native", "max_forks_repo_head_hexsha": "1d9912307336c833b74b7e9b7bc715d0a4e6c7ec", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4791666667, "max_line_length": 78, "alphanum_fraction": 0.7136021873, "num_tokens": 1078, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.0769608314618395, "lm_q2_score": 0.02800752060598813, "lm_q1q2_score": 0.0021554820730214494}}
{"text": "\ufeff// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License. See LICENSE in the project root for license information.\r\n\r\n#pragma once\r\n\r\n#define NOMINMAX\r\n\r\n#pragma warning(disable : 6221) // Disable implicit cast warning for C++/WinRT headers (tracked by Bug 17528784: C++/WinRT headers trigger C6221 comparing e.code() to int-typed things)\r\n\r\n// Disable factory caching in CppWinRT as the global COM pointers that are released during dll/process\r\n// unload are not safe. Setting this makes CppWinRT just call get_activation_factory directly every time.\r\n#define WINRT_DISABLE_FACTORY_CACHE 1\r\n\r\n#include \"targetver.h\"\r\n\r\n#include \"BuildMacros.h\"\r\n\r\n#ifndef WIN32_LEAN_AND_MEAN\r\n#define WIN32_LEAN_AND_MEAN\r\n#endif\r\n\r\n#include <windows.h>\r\n\r\n#include <wrl\\implements.h>\r\n#include <wrl\\module.h>\r\n#include <wrl\\event.h>\r\n\r\n#define MUX_ASSERT(X) _ASSERT(X) \r\n#define MUX_ASSERT_MSG(X, MSG) _ASSERT_EXPR(X, MSG)\r\n#define MUX_ASSERT_NOASSUME(X) _ASSERT(X)\r\n\r\n#define MUX_FAIL_FAST() RaiseFailFastException(nullptr, nullptr, 0);\r\n#define MUX_FAIL_FAST_MSG(MSG) RaiseFailFastException(nullptr, nullptr, 0);\r\n\r\n#ifdef BUILD_WINDOWS\r\n#include <gsl/gsl_util>\r\n#else\r\n#include <gsl_util.h>\r\n#endif\r\n\r\n// windows.ui.xaml.h accesses LoadLibrary in its inline declaration of CreateXamlUiPresenter\r\n// Accessing LoadLibrary is not always allowed (e.g. on phone), so we need to suppress that.\r\n// We can do so by making this define prior to including the header.\r\n#define CREATE_XAML_UI_PRESENTER_API\r\n#include <Windows.UI.Xaml.Hosting.ReferenceTracker.h>\r\n\r\n#include <WindowsNumerics.h>\r\n\r\n#include <strsafe.h>\r\n#include <robuffer.h>\r\n\r\n// STL\r\n#include <vector>\r\n#include <map>\r\n#include <functional>\r\n\r\n#define _USE_MATH_DEFINES\r\n#include <math.h>\r\n\r\n#ifdef BUILD_WINDOWS\r\n#include <staging.h>\r\n#include <featurestaging-xaml.h>\r\n\r\n#undef CATCH_RETURN // See our implementation in ErrorHandling.h\r\n\r\n#else\r\n#define WI_IS_FEATURE_PRESENT(FeatureName) 1\r\n#endif\r\n\r\n#undef GetCurrentTime\r\n\r\n#include \"CppWinRTIncludes.h\"", "meta": {"hexsha": "e99222be962ad5590773d25d6186393834af0eff", "size": 2042, "ext": "h", "lang": "C", "max_stars_repo_path": "dev/dll/pch.h", "max_stars_repo_name": "DotNetUX/microsoft-ui-xaml", "max_stars_repo_head_hexsha": "7f0068704a279afd1fb38fd3f576a21980e355b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-12-06T08:02:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-24T13:23:27.000Z", "max_issues_repo_path": "dev/dll/pch.h", "max_issues_repo_name": "agneszitte-nventive/microsoft-ui-xaml", "max_issues_repo_head_hexsha": "cd29bf314a888d18e7702fc857b193e2cb96302e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-12-07T16:49:26.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-07T16:50:00.000Z", "max_forks_repo_path": "dev/dll/pch.h", "max_forks_repo_name": "DotNetUX/microsoft-ui-xaml", "max_forks_repo_head_hexsha": "7f0068704a279afd1fb38fd3f576a21980e355b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-28T10:29:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-28T10:29:11.000Z", "avg_line_length": 28.3611111111, "max_line_length": 185, "alphanum_fraction": 0.7546523017, "num_tokens": 483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09807931819784702, "lm_q2_score": 0.021948254834434553, "lm_q1q2_score": 0.0021526698697939407}}
{"text": "// stdafx.h : include file for standard system include files,\n// or project specific include files that are used frequently, but\n// are changed infrequently\n//\n\n#pragma once\n#pragma warning (disable : 4514 4710 4711) // inlining\n#pragma warning (disable: 5045) // TODO Spectre\n\n// #define WIN32_LEAN_AND_MEAN             // Exclude rarely-used stuff from Windows headers\n// Windows Header Files:\n#pragma warning (push, 1)\n#pragma warning (disable : 5039 4668 4996 26814 4548 4355 4917 4702 26400 4987 4820 4365 4623 4625 4626 5026 5027 4571 4774 26412 26461 26426 26432 26447 26472 26446 26473 26440 26429 26496 26472 26482 26486 26487 26434)\n#include <gsl.h>\n#pragma warning (pop) // unbalanced push in span.h\n#include <windows.h>\n#include <Shlobj.h>\n#include <Strsafe.h>\n\n#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <memory>\n#include <string>\n#include <vector>\n#include <array>\n#include <ranges>\n#include <span>\n\n#include \"Resource.h\"\n#pragma warning (pop)\n", "meta": {"hexsha": "b5517d39f4d960e4e588e3db55d21301e073f963", "size": 1022, "ext": "h", "lang": "C", "max_stars_repo_path": "drophash/stdafx.h", "max_stars_repo_name": "SteveGilham/drophash", "max_stars_repo_head_hexsha": "8ff11aea865a5a1e5c7ada0c39d34b72f8f77ba6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "drophash/stdafx.h", "max_issues_repo_name": "SteveGilham/drophash", "max_issues_repo_head_hexsha": "8ff11aea865a5a1e5c7ada0c39d34b72f8f77ba6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "drophash/stdafx.h", "max_forks_repo_name": "SteveGilham/drophash", "max_forks_repo_head_hexsha": "8ff11aea865a5a1e5c7ada0c39d34b72f8f77ba6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0588235294, "max_line_length": 220, "alphanum_fraction": 0.7416829746, "num_tokens": 304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10230471884065047, "lm_q2_score": 0.020964241620964025, "lm_q1q2_score": 0.002144740844740187}}
{"text": "/*\n  Copyright [2017-2020] [IBM Corporation]\n  Licensed under the Apache License, Version 2.0 (the \"License\");\n  you may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n  http://www.apache.org/licenses/LICENSE-2.0\n  Unless required by applicable law or agreed to in writing, software\n  distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions and\n  limitations under the License.\n*/\n#ifndef __SHARD_CONNECTION_H__\n#define __SHARD_CONNECTION_H__\n\n#ifdef __cplusplus\n\n#include \"tls_session.h\"\n#include \"buffer_manager.h\"\n#include \"fabric_connection_base.h\"  // default to fabric transport\n#include \"mcas_config.h\"\n#include \"pool_manager.h\"\n#include \"protocol.h\"\n#include \"protocol_ostream.h\"\n#include \"region_manager.h\"\n#include \"connection_state.h\"\n\n#include <api/components.h>\n#include <api/fabric_itf.h>\n#include <api/kvstore_itf.h>\n#include <common/exceptions.h>\n#include <common/logging.h>\n#include <gsl/pointers>\n\n#include <cassert>\n#include <map>\n#include <queue>\n#include <utility> /* swap */\n#include <vector>\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Weffc++\"\n\nnamespace mcas\n{\nusing Connection_base = Fabric_connection_base;\n\n/**\n * Connection handler is instantiated for each \"connected\" client\n */\nclass Connection_handler\n  : public Connection_base,\n    public Region_manager,\n    private Connection_TLS_session\n{\n  friend class Connection_TLS_session;\n  friend struct TLS_transport;\n  \npublic:\n  enum {\n        TICK_RESPONSE_CONTINUE        = 0,\n        TICK_RESPONSE_BOOTSTRAP_SPAWN = 1,\n        TICK_RESPONSE_WAIT_SECURITY   = 2,\n        TICK_RESPONSE_CLOSE           = 0xFF,\n  };\n\n  enum {\n        ACTION_NONE = 0,\n        ACTION_RELEASE_VALUE_LOCK_EXCLUSIVE,\n        ACTION_POOL_DELETE,\n  };\n\n\nprivate:\n  Connection_state    _state       = Connection_state::INITIAL;\n  unsigned option_DEBUG = mcas::global::debug_level;\n\n  /* list of pre-registered memory regions; normally one region */\n  std::vector<component::IKVStore::memory_handle_t> _mr_vector;\n\n  uint64_t                            _tick_count alignas(8);\n  uint64_t                            _auth_id;\n  std::queue<buffer_t *>              _pending_msgs;\n  std::queue<action_t>                _pending_actions;\n  Pool_manager                        _pool_manager; /* instance shared across connections */\n\n  \n  /* Adaptor point for different transports */\n  using Connection = component::IFabric_server;\n  using Factory    = component::IFabric_server_factory;\n\n  struct stats {\n    uint64_t response_count;\n    uint64_t recv_msg_count;\n    uint64_t send_msg_count;\n    uint64_t wait_send_value_misses;\n    uint64_t wait_msg_recv_misses;\n    uint64_t wait_respond_complete_misses;\n    uint64_t last_count;\n    uint64_t next_stamp;\n    stats()\n      : response_count(0),\n        recv_msg_count(0),\n        send_msg_count(0),\n        wait_send_value_misses(0),\n        wait_msg_recv_misses(0),\n        wait_respond_complete_misses(0),\n        last_count(0),\n        next_stamp(0)\n    {\n    }\n  } _stats alignas(8);\n\n  void dump_stats()\n  {\n    PINF(\"-----------------------------------------\");\n    PINF(\"| Connection Handler Statistics         |\");\n    PINF(\"-----------------------------------------\");\n    PINF(\"Ticks                       : %lu\", _tick_count);\n    PINF(\"Open pools                  : %lu\", _pool_manager.open_pool_count());\n    PINF(\"NEW_MSG_RECV misses         : %lu\", _stats.wait_msg_recv_misses);\n    PINF(\"Recv message count          : %lu\", _stats.recv_msg_count);\n    PINF(\"Send message count          : %lu\", _stats.send_msg_count);\n    PINF(\"Response count              : %lu\", _stats.response_count);\n    PINF(\"WAIT_SEND_VALUE misses      : %lu\", _stats.wait_send_value_misses);\n    PINF(\"WAIT_RESPOND_COMPLETE misses: %lu\", _stats.wait_respond_complete_misses);\n    PINF(\"-----------------------------------------\");\n  }\n\n  /**\n   * Change state in FSM\n   *\n   * @param s\n   */\n  inline void set_state(Connection_state s)\n  {\n    if (2 < option_DEBUG) {\n      const std::map<Connection_state, const char *> m{\n                                          {Connection_state::INITIAL, \"INITIAL\"},\n                                          {Connection_state::WAIT_HANDSHAKE, \"WAIT_HANDSHAKE\"},\n                                          {Connection_state::WAIT_TLS_HANDSHAKE, \"WAIT_TLS_HANDSHAKE\"},\n                                          {Connection_state::CLIENT_DISCONNECTED, \"CLIENT_DISCONNECTED\"},\n                                          {Connection_state::CLOSE_CONNECTION, \"CLOSE_CONNECTION\"},\n                                          {Connection_state::WAIT_NEW_MSG_RECV, \"WAIT_NEW_MSG_RECV\"}};\n      PLOG(\"state %s -> %s\", m.find(_state)->second, m.find(s)->second);\n    }\n    _state = s; /* we could add transition checking later */\n  }\n\n  static void static_send_callback2(void *cnxn, buffer_t *iob) noexcept\n  {\n    auto base = static_cast<Fabric_connection_base *>(cnxn);\n    static_cast<Connection_handler *>(base)->send_callback2(iob);\n  }\n\n  void send_callback2(buffer_t *iob) noexcept\n  {\n    assert(iob->value_adjunct);\n    if (0 < option_DEBUG) {\n      PLOG(\"Completed send2 (value_adjunct %p)\", common::p_fmt(iob->value_adjunct));\n    }\n    _deferred_unlock.push(iob->value_adjunct);\n    send_callback(iob);\n  }\n\n  /** \n   * Send handshake response\n   * \n   * @param start_tls Set if a TLS handshake needs to be started\n   */\n  void respond_to_handshake(bool start_tls);\n\n\npublic:\n\n  explicit Connection_handler(unsigned debug_level,\n                              gsl::not_null<Factory *> factory,\n                              gsl::not_null<Connection *> connection);\n\n  virtual ~Connection_handler();\n\n  inline bool client_connected() { return _state != Connection_state::CLIENT_DISCONNECTED; }\n\n  auto allocate_send() { return allocate(static_send_callback); }\n  auto allocate_recv() { return allocate(static_recv_callback); }\n\n  /** \n   * Initialize security session\n   * \n   * @param bind_ipaddr \n   * @param bind_port \n   */\n  void configure_security(const std::string& bind_ipaddr,\n                          const unsigned bind_port,\n                          const std::string& cert_file,\n                          const std::string& key_file);\n    \n\n  /**\n   * State machine transition tick.  It is really important that this tick\n   * execution duration is small, so that other connections are not impacted by\n   * the thread not returning to them.\n   *\n   */\n  int tick();\n  /**\n   * Check for network completions\n   *\n   */\n  Fabric_connection_base::Completion_state check_network_completions()\n  {\n    auto state = poll_completions();\n\n    while (!_deferred_unlock.empty()) {\n      //      void *deferred_unlock = nullptr;\n      //???     std::swap(deferred_unlock, _deferred_unlock.front());\n      void *deferred_unlock = _deferred_unlock.front();\n      if (option_DEBUG > 2)\n        PLOG(\"adding action for deferred unlocking value @ %p\", deferred_unlock);\n      add_pending_action(action_t{ACTION_RELEASE_VALUE_LOCK_EXCLUSIVE, deferred_unlock});\n      _deferred_unlock.pop();\n    }\n\n    return state;\n  }\n\n  /**\n   * Peek at pending message from the connection. Used when the resources\n   * required to process a pending nessage may depend on the content of the\n   * message.\n   *\n   * @param msg [out] Pointer to base protocol message\n   *\n   * @return Pointer to buffer holding the message or null if there are none\n   */\n  inline mcas::protocol::Message *peek_pending_msg() const\n  {\n    return _pending_msgs.empty() ? nullptr\n      : static_cast<mcas::protocol::Message *>(_pending_msgs.front()->base().get());\n  }\n\n  /**\n   * Discard a pending message from the connection. Used along with tick\n   * (which adds pending messages) and peek (which peeks at them).\n   *\n   * @param msg [out] Pointer to base protocol message\n   *\n   * @return Pointer to buffer holding the message or null if there are none\n   */\n  inline buffer_t *pop_pending_msg()\n  {\n    assert(!_pending_msgs.empty());\n    auto iob = _pending_msgs.front();\n    _pending_msgs.pop();\n    return iob;\n  }\n\n  /**\n   * Get deferred actions\n   *\n   * @param action [out] Action\n   *\n   * @return True if action\n   */\n  inline bool get_pending_action(action_t &action)\n  {\n    if (_pending_actions.empty()) return false;\n\n    action = _pending_actions.front();\n\n    if (option_DEBUG > 2) PLOG(\"Connection_handler: popped pending action (%u, %p)\", action.op, action.parm);\n\n    _pending_actions.pop();\n    return true;\n  }\n\n  template <typename MT>\n  void msg_log(const unsigned level_, const MT *msg_, const char *desc_, const char *direction_)\n  {\n    if (level_ < Connection_base::debug_level()) {\n      std::ostringstream m;\n      m << *msg_;\n      PLOG(\"%s (%s) %s\", direction_, desc_, m.str().c_str());\n    }\n  }\n\n  template <typename MT>\n  void msg_recv_log(const MT *m, const char *desc)\n  {\n    msg_recv_log(1, m, desc);\n  }\n\n  template <typename MT>\n  void msg_recv_log(const unsigned level, const MT *msg, const char *desc)\n  {\n    msg_log(level, msg, desc, \"RECV\");\n  }\n\n  template <typename MT>\n  void msg_send_log(const MT *m, const char *desc)\n  {\n    msg_send_log(1, m, desc);\n  }\n\n  template <typename MT>\n  void msg_send_log(const unsigned level, const MT *msg, const char *desc)\n  {\n    msg_log(level, msg, desc, \"SEND\");\n  }\n\n  /**\n   * Add an action to the pending queue\n   *\n   * @param action Action to add\n   */\n  inline void add_pending_action(const action_t& action)\n  {\n    _pending_actions.push(action);\n  }\n\n  template <typename Msg>\n  void post_send_buffer(gsl::not_null<buffer_t *> buffer, Msg *msg, const char *desc)\n  {\n    msg_send_log(msg, desc);\n    Connection_base::post_send_buffer(buffer);\n  }\n\n  template <typename Msg>\n  void post_send_buffer_with_value(gsl::not_null<buffer_t *> buffer,\n                         const ::iovec &           val_iov,\n                         void *                    val_desc,\n                         Msg *                     msg,\n                         const char *              func_name)\n  {\n    msg_send_log(msg, func_name);\n    Connection_base::post_send_buffer2(buffer, val_iov, val_desc);\n  }\n\n  /**\n   * Post a response\n   *\n   * @param iob IO buffer to post\n   */\n  template <typename Msg>\n  inline void post_response_with_value(gsl::not_null<buffer_t *> iob,\n                             const ::iovec &           val_iov,\n                             void *                    val_desc,\n                             Msg *                     msg,\n                             const char *              func_name)\n  {\n    iob->set_completion(static_send_callback2, val_iov.iov_base);\n    post_send_buffer_with_value(iob, val_iov, val_desc, msg, func_name);\n    /* don't wait for this, let it be picked up in the check_completions cycle\n     */\n\n    _stats.response_count++;\n  }\n\n  /**\n   * Post a response\n   *\n   * @param iob IO buffer to post\n   */\n  template <typename Msg>\n  inline void post_response(gsl::not_null<buffer_t *> iob, Msg *msg, const char *desc)\n  {\n    post_send_buffer(iob, msg, desc);\n    /* don't wait for this, let it be picked up in the check_completions cycle\n     */\n\n    _stats.response_count++;\n  }\n\n  /**\n   * Set up for pending value send/recv\n   *\n   * @param target\n   * @param target_len\n   * @param region\n   */\n  void add_memory_handle(component::IKVStore::memory_handle_t handle) { _mr_vector.push_back(handle); }\n\n  component::IKVStore::memory_handle_t pop_memory_handle()\n  {\n    if (_mr_vector.empty()) return nullptr;\n    auto mr = _mr_vector.back();\n    _mr_vector.pop_back();\n    return mr;\n  }\n\n  inline uint64_t       auth_id() const { return _auth_id; }\n  inline void           set_auth_id(uint64_t id) { _auth_id = id; }\n  inline size_t         max_message_size() const { return _max_message_size; }\n  inline Pool_manager & pool_manager() { return _pool_manager; }\n\nprivate:\n  common::Byte_buffer _tls_buffer;\n};\n\n}  // namespace mcas\n\n#pragma GCC diagnostic pop\n\n#endif\n\n#endif  // __CONNECTION_HANDLER_H__\n", "meta": {"hexsha": "ad531007a56bf55c8f5dd4f152058a7aea202844", "size": 12166, "ext": "h", "lang": "C", "max_stars_repo_path": "src/server/mcas/src/connection_handler.h", "max_stars_repo_name": "moshik1/mcas", "max_stars_repo_head_hexsha": "a6af06bc278993fb3ffe780f230d2396b2287c26", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/server/mcas/src/connection_handler.h", "max_issues_repo_name": "moshik1/mcas", "max_issues_repo_head_hexsha": "a6af06bc278993fb3ffe780f230d2396b2287c26", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/server/mcas/src/connection_handler.h", "max_forks_repo_name": "moshik1/mcas", "max_forks_repo_head_hexsha": "a6af06bc278993fb3ffe780f230d2396b2287c26", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8918918919, "max_line_length": 109, "alphanum_fraction": 0.6320072333, "num_tokens": 2857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11920291576401233, "lm_q2_score": 0.017986211080669633, "lm_q1q2_score": 0.0021440088043628075}}
{"text": "#pragma once\r\n#include <gsl/assert>\r\n\r\nconstexpr char deathstring[] = \"Expected Death\";\r\nconstexpr char failed_set_terminate_deathstring[] = \".*\";\r\n\r\n// This prevents a failed call to set_terminate from failing the test suite.\r\nconstexpr const char* GetExpectedDeathString(std::terminate_handler handle)\r\n{\r\n    return handle ? deathstring : failed_set_terminate_deathstring;\r\n}\r\n", "meta": {"hexsha": "7bf242393f7bcff62c12cd985a87824f48f7bb0b", "size": 380, "ext": "h", "lang": "C", "max_stars_repo_path": "tests/deathTestCommon.h", "max_stars_repo_name": "Batfing/GSL", "max_stars_repo_head_hexsha": "4377f6e603c64a86c934f1546aa9db482f2e1a4e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3645.0, "max_stars_repo_stars_event_min_datetime": "2015-09-16T08:10:27.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-06T15:06:09.000Z", "max_issues_repo_path": "tests/deathTestCommon.h", "max_issues_repo_name": "Batfing/GSL", "max_issues_repo_head_hexsha": "4377f6e603c64a86c934f1546aa9db482f2e1a4e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 716.0, "max_issues_repo_issues_event_min_datetime": "2015-09-16T09:04:54.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-05T16:08:33.000Z", "max_forks_repo_path": "tests/deathTestCommon.h", "max_forks_repo_name": "Batfing/GSL", "max_forks_repo_head_hexsha": "4377f6e603c64a86c934f1546aa9db482f2e1a4e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 616.0, "max_forks_repo_forks_event_min_datetime": "2015-09-16T20:40:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-02T13:56:27.000Z", "avg_line_length": 31.6666666667, "max_line_length": 77, "alphanum_fraction": 0.7631578947, "num_tokens": 78, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06465348835622392, "lm_q2_score": 0.033085978388704126, "lm_q1q2_score": 0.0021391239185083585}}
{"text": "// SPDX-License-Identifier: MIT\n// The MIT License (MIT)\n//\n// Copyright (c) 2014-2018, Institute for Software & Systems Engineering\n// Copyright (c) 2018-2019, Johannes Leupolz\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n#ifndef PEMC_EXECUTABLE_MODEL_TEMPORARY_STATE_STORAGE_H_\n#define PEMC_EXECUTABLE_MODEL_TEMPORARY_STATE_STORAGE_H_\n\n#include <vector>\n#include <gsl/span>\n#include <cstdint>\n#include <atomic>\n#include <boost/align/aligned_allocator.hpp>\n\n#include \"pemc/basic/tsc_index.h\"\n#include \"pemc/basic/probability.h\"\n#include \"pemc/basic/label.h\"\n#include \"pemc/basic/model_capacity.h\"\n#include \"pemc/basic/raw_memory.h\"\n#include \"pemc/formula/formula.h\"\n\nnamespace pemc {\n\n  ///   We store states in a contiguous array, indexed by a continuous variable.\n  ///   The TemporaryStateStorage is not thread safe.\n  class TemporaryStateStorage {\n  private:\n\n      // The length in bytes of a state vector required for the analysis model.\n      int32_t modelStateVectorSize = 0;\n      // Extra bytes in state vector for preStateStorage modifiers.\n      int32_t preStateStorageModifierStateVectorSize = 0;\n      // The length in bytes of the state vector of the analysis model with the extra bytes\n      // required for the preStateStorage modifiers\n      int32_t stateVectorSize = 0;\n\n      // The number of saved states\n      StateIndex savedStates = 0;\n  \t  // The number of states that can be cached and the number of reserved states.\n      StateIndex totalCapacity;\n\n      // the memory that contains the serialized states\n      std::vector<gsl::byte> stateMemory;\n\n      void resizeStateBuffer();\n\n  public:\n      TemporaryStateStorage(StateIndex _capacity);\n\n      StateIndex getNumberOfSavedStates();\n\n      gsl::span<gsl::byte> operator [](size_t idx);\n\n      StateIndex getFreshStateIndex();\n\n      void setStateVectorSize(int32_t _modelStateVectorSize, int32_t _preStateStorageModifierStateVectorSize);\n\n      void clear();\n  };\n\n}\n\n#endif  // PEMC_EXECUTABLE_MODEL_TEMPORARY_STATE_STORAGE_H_\n", "meta": {"hexsha": "2d5e914ead62eda978b71601ee9930f8d9960683", "size": 3040, "ext": "h", "lang": "C", "max_stars_repo_path": "pemc/executable_model/temporary_state_storage.h", "max_stars_repo_name": "joleuger/pemc", "max_stars_repo_head_hexsha": "14deb5b97d4219ba3c92d3834ab71332997e9b13", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pemc/executable_model/temporary_state_storage.h", "max_issues_repo_name": "joleuger/pemc", "max_issues_repo_head_hexsha": "14deb5b97d4219ba3c92d3834ab71332997e9b13", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pemc/executable_model/temporary_state_storage.h", "max_forks_repo_name": "joleuger/pemc", "max_forks_repo_head_hexsha": "14deb5b97d4219ba3c92d3834ab71332997e9b13", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6265060241, "max_line_length": 110, "alphanum_fraction": 0.7490131579, "num_tokens": 689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08756384428525613, "lm_q2_score": 0.024423088278887034, "lm_q1q2_score": 0.002138579499017528}}
{"text": "#pragma once\n#include <typeinfo>\n#include <gsl/gsl_assert>\n#include <algorithm>\n#include \"halleystring.h\"\n#include <halley/support/exception.h>\n\nnamespace Halley\n{\n\n\ttemplate <typename T>\n\tstruct EnumNames {\n\t};\n\n\n\t\n\tstruct UserConverter\n\t{\n\t\ttemplate<typename T, typename std::enable_if<std::is_enum<T>::value, int>::type = 0>\n\t\tstatic String toString(const T& v)\n\t\t{\n\t\t\treturn EnumNames<T>()()[int(v)];\n\t\t}\n\n\t\ttemplate<typename T, typename std::enable_if<!std::is_enum<T>::value, int>::type = 0>\n\t\tstatic String toString(const T& v)\n\t\t{\n\t\t\treturn v.toString();\n\t\t}\n\n\t\ttemplate<typename T, typename std::enable_if<std::is_enum<T>::value, int>::type = 0>\n\t\tstatic T fromString(const String& str)\n\t\t{\n\t\t\tEnumNames<T> n;\n\t\t\tauto names = n();\n\t\t\tauto res = std::find_if(std::begin(names), std::end(names), [&](const char* v) { return str == v; });\n\t\t\tif (res == std::end(names)) {\n\t\t\t\tthrow Exception(\"String \\\"\" + str + \"\\\" does not exist in enum \\\"\" + typeid(T).name() + \"\\\".\", HalleyExceptions::Utils);\n\t\t\t}\n\t\t\treturn T(res - std::begin(names));\n\t\t}\n\n\t\ttemplate<typename T, typename std::enable_if<!std::is_enum<T>::value, int>::type = 0>\n\t\tstatic T fromString(const String& str)\n\t\t{\n\t\t\treturn T(str);\n\t\t}\n\t};\n\n\n\ttemplate <typename T>\n\tstruct ToStringConverter {\n\t\tString operator()(const T& s) const\n\t\t{\n\t\t\treturn UserConverter::toString(s);\n\t\t}\n\t};\n\n\ttemplate <typename T>\n\tstruct FromStringConverter {\n\t\tT operator()(const String& s) const\n\t\t{\n\t\t\treturn UserConverter::fromString<T>(s);\n\t\t}\n\t};\n\n\ttemplate<size_t N>\n\tstruct ToStringConverter<char[N]>\n\t{\n\t\tString operator()(const char s[N]) const\n\t\t{\n\t\t\treturn String(s);\n\t\t}\n\t};\n\t\n\ttemplate<>\n\tstruct ToStringConverter<const char*>\n\t{\n\t\tString operator()(const char* s) const\n\t\t{\n\t\t\treturn String(s);\n\t\t}\n\t};\n\n\ttemplate<>\n\tstruct ToStringConverter<char*>\n\t{\n\t\tString operator()(const char* s) const\n\t\t{\n\t\t\treturn String(s);\n\t\t}\n\t};\n\n\ttemplate<size_t N>\n\tstruct ToStringConverter<wchar_t[N]>\n\t{\n\t\tString operator()(const wchar_t s[N]) const\n\t\t{\n\t\t\treturn String(s);\n\t\t}\n\t};\n\n\ttemplate<>\n\tstruct ToStringConverter<const wchar_t*>\n\t{\n\t\tString operator()(const wchar_t* s) const\n\t\t{\n\t\t\treturn String(s);\n\t\t}\n\t};\n\n\ttemplate<>\n\tstruct ToStringConverter<wchar_t*>\n\t{\n\t\tString operator()(const wchar_t* s) const\n\t\t{\n\t\t\treturn String(s);\n\t\t}\n\t};\n\n\ttemplate<>\n\tstruct ToStringConverter<std::string>\n\t{\n\t\tString operator()(const std::string& s) const\n\t\t{\n\t\t\treturn String(s);\n\t\t}\n\t};\n\n\ttemplate<>\n\tstruct ToStringConverter<bool>\n\t{\n\t\tString operator()(bool s) const\n\t\t{\n\t\t\treturn String(s ? \"true\" : \"false\");\n\t\t}\n\t};\n\n\ttemplate<>\n\tstruct FromStringConverter<bool>\n\t{\n\t\tbool operator()(const String& s) const\n\t\t{\n\t\t\treturn s == \"true\";\n\t\t}\n\t};\n\n\t\n\ttemplate <typename T, typename std::enable_if<std::is_floating_point<T>::value, int>::type = 0>\n\tString toString(T src, int precisionDigits = -1, char decimalSeparator = '.')\n\t{\n\t\tExpects(precisionDigits >= -1 && precisionDigits <= 20);\n\t\tstd::stringstream str;\n\t\tif (precisionDigits != -1) {\n\t\t\tstr << std::fixed << std::setprecision(precisionDigits);\n\t\t}\n\t\tstr << src;\n\n\t\tString result;\n\t\tif (precisionDigits == -1) {\n\t\t\tresult = String::prettyFloat(str.str());\n\t\t} else {\n\t\t\tresult = str.str();\n\t\t}\n\n\t\tif (decimalSeparator != '.') {\n\t\t\tresult = result.replaceAll(String(\".\"), String(decimalSeparator));\n\t\t}\n\n\t\treturn result;\n\t}\n\n\ttemplate <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0>\n\tString toString(T value, int base = 10, int width = 1)\n\t{\n\t\tExpects(base == 10 || base == 16 || base == 8);\n\t\tstd::stringstream ss;\n\t\tif (base == 16) {\n\t\t\tss.setf(std::ios::hex, std::ios::basefield);\n\t\t} else if (base == 8) {\n\t\t\tss.setf(std::ios::oct, std::ios::basefield);\n\t\t}\n\t\tif (width > 1) {\n\t\t\tss << std::setfill('0') << std::setw(width);\n\t\t}\n\t\tss << value;\n\t\treturn ss.str();\n\t}\n\n\ttemplate <typename T, typename std::enable_if<!std::is_integral<T>::value && !std::is_floating_point<T>::value, int>::type = 0>\n\tString toString(const T& value)\n\t{\n\t\treturn ToStringConverter<typename std::remove_cv<T>::type>()(value);\n\t}\n\n\n\n\ttemplate <typename T>\n\tT fromString(const String& value)\n\t{\n\t\treturn FromStringConverter<T>()(value);\n\t}\n\n\n\n\ttemplate <typename T, typename std::enable_if<!std::is_same<T, String>::value, int>::type = 0>\n\tString operator+ (const String& lhp, const T& rhp)\n\t{\n\t\treturn lhp + toString<typename std::remove_cv<T>::type>(rhp);\n\t}\n\n\ttemplate <typename T, typename std::enable_if<!std::is_same<T, String>::value, int>::type = 0>\n\tString operator+ (const T& lhp, const String& rhp)\n\t{\n\t\treturn toString<typename std::remove_cv<T>::type>(lhp) + rhp;\n\t}\n\n}\n", "meta": {"hexsha": "9ae41f4f222203a6fed17cc10e7268468b6babbe", "size": 4593, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engine/utils/include/halley/text/string_converter.h", "max_stars_repo_name": "sunhay/halley", "max_stars_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T20:23:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T20:23:45.000Z", "max_issues_repo_path": "src/engine/utils/include/halley/text/string_converter.h", "max_issues_repo_name": "sunhay/halley", "max_issues_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engine/utils/include/halley/text/string_converter.h", "max_forks_repo_name": "sunhay/halley", "max_forks_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.9726027397, "max_line_length": 128, "alphanum_fraction": 0.6409753973, "num_tokens": 1316, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.090092998848117, "lm_q2_score": 0.023689469533103552, "lm_q1q2_score": 0.002134255351358401}}
{"text": "/*****************************************************************\\\n__\n/ /\n/ /                     __  __\n/ /______    _______    / / / / ________   __       __\n/ ______  \\  /_____  \\  / / / / / _____  | / /      / /\n/ /      | / _______| / / / / / / /____/ / / /      / /\n/ /      / / / _____  / / / / / / _______/ / /      / /\n/ /      / / / /____/ / / / / / / |______  / |______/ /\n/_/      /_/ |________/ / / / /  \\_______/  \\_______  /\n/_/ /_/                     / /\n/ /\nHigh Level Game Framework            /_/\n\n---------------------------------------------------------------\n\nCopyright (c) 2007-2011 - Rodrigo Braz Monteiro.\nThis file is subject to the terms of halley_license.txt.\n\n\\*****************************************************************/\n\n#pragma once\n\n#include \"halley/text/halleystring.h\"\n#include \"halley/file/path.h\"\n#include <memory>\n#include <functional>\n#include <halley/concurrency/future.h>\n#include <gsl/gsl>\n#include \"metadata.h\"\n\nnamespace Halley {\n\tenum class AssetType;\n\n\tclass ResourceDataReader {\n\tpublic:\n\t\tvirtual ~ResourceDataReader() {}\n\t\tvirtual size_t size() const = 0;\n\t\tvirtual int read(gsl::span<gsl::byte> dst) = 0;\n\t\tvirtual void seek(int64_t pos, int whence) = 0;\n\t\tvirtual size_t tell() const = 0;\n\t\tvirtual void close() = 0;\n\n\t\tBytes readAll();\n\t};\n\n\tclass ResourceData {\n\tpublic:\n\t\tResourceData(String path);\n\t\tvirtual ~ResourceData() {}\n\n\t\tString getPath() const { return path; }\n\n\tprivate:\n\t\tString path;\n\t};\n\n\tclass ResourceDataStatic : public ResourceData {\n\tpublic:\n\t\tResourceDataStatic(String path);\n\t\tResourceDataStatic(const void* data, size_t size, String path, bool owning = true);\n\n\t\tvoid set(const void* data, size_t size, bool owning = true);\n\t\tbool isLoaded() const;\n\n\t\tconst void* getData() const;\n\t\tgsl::span<const gsl::byte> getSpan() const;\n\t\tsize_t getSize() const;\n\t\tString getString() const;\n\t\tvoid inflate();\n\n\t\tstatic std::unique_ptr<ResourceDataStatic> loadFromFileSystem(Path path);\n\t\tvoid writeToFileSystem(String path) const;\n\n\tprivate:\n\t\tstd::shared_ptr<const char> data;\n\t\tsize_t size = 0;\n\t\tbool loaded;\n\t};\n\n\ttypedef std::function<std::unique_ptr<ResourceDataReader>()> ResourceDataMakeReader;\n\tclass ResourceDataStream : public ResourceData {\n\tpublic:\n\t\tResourceDataStream(String path, ResourceDataMakeReader makeReader);\n\t\tstd::unique_ptr<ResourceDataReader> getReader() const { return make(); }\n\n\tprivate:\n\t\tResourceDataMakeReader make;\n\t};\n\n\tclass IResourceLocator\n\t{\n\tpublic:\n\t\tvirtual ~IResourceLocator() {}\n\t\tvirtual const Metadata& getMetaData(const String& resource, AssetType type) const = 0;\n\t\tvirtual std::unique_ptr<ResourceDataStatic> getStatic(const String& asset, AssetType type) = 0;\n\t\tvirtual std::unique_ptr<ResourceDataStream> getStream(const String& asset, AssetType type) = 0;\n\t};\n\n\n\tenum class ResourceLoadPriority {\n\t\tLow = 0,\n\t\tNormal = 1,\n\t\tHigh = 2\n\t};\n\n\tclass HalleyAPI;\n\tclass Metadata;\n\n\tclass ResourceLoader\n\t{\n\t\tfriend class ResourceCollectionBase;\n\n\tpublic:\n\t\tconst String& getName() const { return name; }\n\t\tResourceLoadPriority getPriority() const { return priority; }\n\t\tconst HalleyAPI& getAPI() const { return *api; }\n\t\tconst Metadata& getMeta() const { return *metadata; }\n\n\t\tstd::unique_ptr<ResourceDataStatic> getStatic();\n\t\tstd::unique_ptr<ResourceDataStream> getStream();\n\t\tFuture<std::unique_ptr<ResourceDataStatic>> getAsync() const;\n\n\tprivate:\n\t\tResourceLoader(ResourceLoader&& loader) noexcept;\n\t\tResourceLoader(IResourceLocator& locator, const String& name, AssetType type, ResourceLoadPriority priority, const HalleyAPI* api);\n\t\t~ResourceLoader();\n\n\t\tIResourceLocator& locator;\n\t\tString name;\n\t\tAssetType type;\n\t\tResourceLoadPriority priority;\n\t\tconst HalleyAPI* api;\n\t\tconst Metadata* metadata;\n\t\tbool loaded = false;\n\t};\n\n}\n", "meta": {"hexsha": "60a26ef432ddc9d826a7b6093c7f94671d32bc68", "size": 3757, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engine/utils/include/halley/resources/resource_data.h", "max_stars_repo_name": "lye/halley", "max_stars_repo_head_hexsha": "16b6c9783e4b21377f902a9d02366c1f19450a21", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T20:23:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T20:23:45.000Z", "max_issues_repo_path": "src/engine/utils/include/halley/resources/resource_data.h", "max_issues_repo_name": "lye/halley", "max_issues_repo_head_hexsha": "16b6c9783e4b21377f902a9d02366c1f19450a21", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engine/utils/include/halley/resources/resource_data.h", "max_forks_repo_name": "lye/halley", "max_forks_repo_head_hexsha": "16b6c9783e4b21377f902a9d02366c1f19450a21", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0287769784, "max_line_length": 133, "alphanum_fraction": 0.6435986159, "num_tokens": 933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09009298418962222, "lm_q2_score": 0.02368946905922602, "lm_q1q2_score": 0.0021342549614133946}}
{"text": "#pragma once\r\n\r\n#include <functional>\r\n#include <memory>\r\n#include <vector>\r\n\r\n#include <gsl/gsl-lite.hpp> // gsl::span\r\n\r\n#include <QObject>\r\n\r\n#include \"HypCommands.h\" // Hyperion::RECORD_LENGTH\r\n\r\nclass DeviceLink;\r\nclass Recording;\r\n\r\nclass HypReader : public QObject\r\n{\r\n    Q_OBJECT\r\npublic:\r\n    explicit HypReader(std::function<void(const QString&)> msgCBck,\r\n                       std::function<void(size_t)> finishedCBck, \r\n                       QObject* parent = nullptr);\r\n\r\n    void DownloadFromDevice();\r\n    void EraseDevice();\r\n\r\n    bool LoadFromFile(const QString& filePath);\r\n    bool SaveToFile  (const QString& filePath);\r\n\r\n    size_t GetNumRecordings() const; // { return m_recordings.size(); }\r\n    const Recording& GetRecording(size_t idx) const;\r\n\r\n    Hyperion::DeviceType GetDeviceType() const;\r\n    int         GetFirmwareVersionX100() const;\r\n\r\nsignals:\r\n    void SeriesEnded();\r\n    void DownloadFinish(bool success);\r\n\r\nprivate:\r\n    void EndSeries();\r\n    void FinishDownload(bool success);\r\n\r\n    // These get called from DeviceLink worker thread.\r\n    // They emit the data to be processed on UI thread.\r\n    void MarkSeriesEnd();\r\n    void DownloadFinished(bool success);\r\n    void ReceiveDataChunk(const gsl::span<uint8_t>& data);\r\n\r\n//data:\r\n    std::function<void(const QString&)> m_msgCBck;\r\n    std::function<void(size_t)>         m_finishedCBck;\r\n    std::unique_ptr<DeviceLink>         m_deviceReader;\r\n\r\n    std::vector<std::vector<uint8_t>> m_downloadedRawData;\r\n    std::vector<Recording>            m_recordings;\r\n\r\npublic:\r\n    static const QString BS;\r\n};\r\n", "meta": {"hexsha": "d033d4399ae0d1cd1f91b84ffc35ec6002cb8b68", "size": 1608, "ext": "h", "lang": "C", "max_stars_repo_path": "src/HypReader.h", "max_stars_repo_name": "bsergeev/HyperionEmeter2", "max_stars_repo_head_hexsha": "105124530364cdf9f625a03046b5edba140c9114", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-01T08:01:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-01T08:01:08.000Z", "max_issues_repo_path": "src/HypReader.h", "max_issues_repo_name": "bsergeev/HyperionEmeter2", "max_issues_repo_head_hexsha": "105124530364cdf9f625a03046b5edba140c9114", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/HypReader.h", "max_forks_repo_name": "bsergeev/HyperionEmeter2", "max_forks_repo_head_hexsha": "105124530364cdf9f625a03046b5edba140c9114", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3606557377, "max_line_length": 72, "alphanum_fraction": 0.6536069652, "num_tokens": 355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09138209316905592, "lm_q2_score": 0.023330769954443126, "lm_q1q2_score": 0.002132014593682732}}
{"text": "#include <bindings.cmacros.h>\n#include <gsl/gsl_version.h>\n\nBC_GLOBALARRAY(GSL_VERSION,char)\nBC_GLOBALARRAY(gsl_version,char)\n", "meta": {"hexsha": "c77faaf380851ddb1ef25f37e37e4d1fd5efcc9d", "size": 126, "ext": "c", "lang": "C", "max_stars_repo_path": "bindings-gsl/src/Bindings/Gsl/Version.c", "max_stars_repo_name": "flip111/bindings-dsl", "max_stars_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2015-04-29T00:31:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T09:29:03.000Z", "max_issues_repo_path": "bindings-gsl/src/Bindings/Gsl/Version.c", "max_issues_repo_name": "flip111/bindings-dsl", "max_issues_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2015-01-04T06:32:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-07T09:49:12.000Z", "max_forks_repo_path": "bindings-gsl/src/Bindings/Gsl/Version.c", "max_forks_repo_name": "flip111/bindings-dsl", "max_forks_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2015-01-03T20:43:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-10T19:31:38.000Z", "avg_line_length": 21.0, "max_line_length": 32, "alphanum_fraction": 0.8174603175, "num_tokens": 32, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11124121829336078, "lm_q2_score": 0.019124034584604602, "lm_q1q2_score": 0.002127380905875782}}
{"text": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n#pragma once\n\n#include \"arcana/functional/inplace_function.h\"\n#include \"arcana/sentry.h\"\n\n#include \"affinity.h\"\n#include \"blocking_concurrent_queue.h\"\n\n#include <gsl/gsl>\n#include <vector>\n\nnamespace mira\n{\n    template<size_t WorkSize>\n    class dispatcher\n    {\n    public:\n        using callback_t = stdext::inplace_function<void(), WorkSize>;\n        static constexpr size_t work_size = WorkSize;\n\n        template<typename T>\n        void queue(T&& work)\n        {\n            m_work.push(std::forward<T>(work));\n        }\n\n        affinity get_affinity() const\n        {\n            return m_affinity;\n        }\n\n        dispatcher(const dispatcher&) = delete;\n        dispatcher& operator=(const dispatcher&) = delete;\n\n        virtual ~dispatcher() = default;\n\n    protected:\n        dispatcher() = default;\n        dispatcher& operator=(dispatcher&&) = default;\n        dispatcher(dispatcher&&) = default;\n\n        bool tick(const cancellation& token)\n        {\n            return internal_tick(token, false);\n        }\n\n        bool blocking_tick(const cancellation& token)\n        {\n            return internal_tick(token, true);\n        }\n\n        /*\n        Sets the dispatcher's tick thread affinity. Once this is set the methods\n        on this instance will need to be called by that thread.\n        */\n        void set_affinity(const affinity& aff)\n        {\n            m_affinity = aff;\n        }\n\n        void cancelled()\n        {\n            m_work.cancelled();\n        }\n\n        void clear()\n        {\n            m_work.clear();\n        }\n\n    private:\n        bool internal_tick(const cancellation& token, bool block)\n        {\n            GSL_CONTRACT_CHECK(\"thread affinity\", m_affinity.check());\n\n            if (block)\n            {\n                if (!m_work.blocking_drain(m_workload, token))\n                    return false;\n            }\n            else\n            {\n                if (!m_work.try_drain(m_workload, token))\n                    return false;\n            }\n\n            for (auto& work : m_workload)\n            {\n                work();\n            }\n\n            m_workload.clear();\n\n            return true;\n        }\n\n        blocking_concurrent_queue<callback_t> m_work;\n        affinity m_affinity;\n        std::vector<callback_t> m_workload;\n    };\n\n    template<size_t WorkSize>\n    class manual_dispatcher : public dispatcher<WorkSize>\n    {\n    public:\n        using dispatcher<WorkSize>::blocking_tick;\n        using dispatcher<WorkSize>::cancelled;\n        using dispatcher<WorkSize>::clear;\n        using dispatcher<WorkSize>::set_affinity;\n        using dispatcher<WorkSize>::tick;\n    };\n\n    template<size_t WorkSize>\n    class background_dispatcher : public dispatcher<WorkSize>\n    {\n    public:\n        background_dispatcher()\n            : m_registration{ m_cancellation.add_listener([this] { this->cancelled(); }) }\n        {\n            m_thread = std::thread{ [&]() {\n\n                // TODO: Set the affinity when usage bugs are fixed.\n                constexpr bool should_set_affinity{ false };\n                if (should_set_affinity)\n                {\n                    this->set_affinity(std::this_thread::get_id());\n                }\n\n                while (!m_cancellation.cancelled())\n                {\n                    this->blocking_tick(m_cancellation);\n                }\n            } };\n        }\n\n        void cancel()\n        {\n            m_cancellation.cancel();\n\n            if (m_thread.joinable())\n            {\n                m_thread.join();\n            }\n\n            this->clear();\n        }\n\n        ~background_dispatcher()\n        {\n            cancel();\n        }\n\n    private:\n        std::thread m_thread;\n        cancellation_source m_cancellation;\n        cancellation_source::ticket m_registration;\n    };\n}\n", "meta": {"hexsha": "53bf072b80cabc35b2e4da579bcdc900a5ee97c0", "size": 3902, "ext": "h", "lang": "C", "max_stars_repo_path": "Dependencies/Arcana/Shared/arcana/threading/dispatcher.h", "max_stars_repo_name": "syntheticmagus/mageslam", "max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z", "max_issues_repo_path": "Dependencies/Arcana/Shared/arcana/threading/dispatcher.h", "max_issues_repo_name": "syntheticmagus/mageslam", "max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z", "max_forks_repo_path": "Dependencies/Arcana/Shared/arcana/threading/dispatcher.h", "max_forks_repo_name": "syntheticmagus/mageslam", "max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z", "avg_line_length": 24.0864197531, "max_line_length": 90, "alphanum_fraction": 0.5320348539, "num_tokens": 764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09670580370950446, "lm_q2_score": 0.02194825531424887, "lm_q1q2_score": 0.0021225236701858394}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef rendersys_5fadb7a4_2c63_4b3a_8029_14043d2405e6_h\r\n#define rendersys_5fadb7a4_2c63_4b3a_8029_14043d2405e6_h\r\n\r\n#include <ariel/config.h>\r\n#include <ariel/type.h>\r\n#include <gslib/std.h>\r\n#include <ariel/image.h>\r\n\r\n__ariel_begin__\r\n\r\nenum shader_type\r\n{\r\n    st_vertex_shader,\r\n    st_pixel_shader,\r\n    st_geometry_shader,\r\n    st_hull_shader,\r\n    st_domain_shader,\r\n    st_tessellation_shader,\r\n    st_compute_shader,\r\n    /* more.. */\r\n};\r\n\r\nenum sampler_state_filter\r\n{\r\n    ssf_point,\r\n    ssf_linear,\r\n    ssf_anisotropic,\r\n};\r\n\r\nstruct render_device_info\r\n{\r\n    uint            vendor_id;\r\n};\r\n\r\nclass __gs_novtable rendersys abstract\r\n{\r\npublic:\r\n    typedef unordered_map<string, string> configs;\r\n    typedef render_vertex_buffer vertex_buffer;\r\n    typedef render_index_buffer index_buffer;\r\n    typedef render_constant_buffer constant_buffer;\r\n    typedef render_texture1d texture1d;\r\n    typedef render_texture2d texture2d;\r\n    typedef render_texture3d texture3d;\r\n    typedef render_sampler_state sampler_state;\r\n    typedef unordered_map<void*, rendersys*> rsys_map;\r\n    config_select_type(select_render_platform, vertex_format_desc);\r\n\r\npublic:\r\n    rendersys();\r\n    virtual ~rendersys() {}\r\n    virtual bool setup(uint hwnd, const configs& cfg) = 0;\r\n    virtual void destroy() = 0;\r\n    virtual void setup_pipeline_state() = 0;\r\n    virtual render_blob* compile_shader_from_file(const gchar* file, const gchar* entry, const gchar* sm, render_include* inc) = 0;\r\n    virtual render_blob* compile_shader_from_memory(const char* src, int len, const gchar* name, const gchar* entry, const gchar* sm, render_include* inc) = 0;\r\n    virtual vertex_shader* create_vertex_shader(const void* ptr, size_t len) = 0;\r\n    virtual pixel_shader* create_pixel_shader(const void* ptr, size_t len) = 0;\r\n    virtual compute_shader* create_compute_shader(const void* ptr, size_t len) = 0;\r\n    virtual geometry_shader* create_geometry_shader(const void* ptr, size_t len) = 0;\r\n    virtual hull_shader* create_hull_shader(const void* ptr, size_t len) = 0;\r\n    virtual domain_shader* create_domain_shader(const void* ptr, size_t len) = 0;\r\n    virtual vertex_format* create_vertex_format(const void* ptr, size_t len, vertex_format_desc desc[], uint n) = 0;\r\n    virtual vertex_buffer* create_vertex_buffer(uint stride, uint count, bool read, bool write, uint usage, const void* ptr = 0) = 0;\r\n    virtual index_buffer* create_index_buffer(uint count, bool read, bool write, uint usage, const void* ptr = 0) = 0;\r\n    virtual constant_buffer* create_constant_buffer(uint stride, bool read, bool write, const void* ptr = 0) = 0;\r\n    virtual shader_resource_view* create_shader_resource_view(render_resource* res) = 0;    /* texture view in GL */\r\n    virtual depth_stencil_view* create_depth_stencil_view(render_resource* res) = 0;\r\n    virtual unordered_access_view* create_unordered_access_view(render_resource* res) = 0;\r\n    virtual sampler_state* create_sampler_state(sampler_state_filter filter) = 0;\r\n    virtual texture2d* create_texture2d(const image& img, uint mips, uint usage, uint bindflags, uint cpuflags, uint miscflags) = 0;\r\n    virtual texture2d* create_texture2d(int width, int height, uint format, uint mips, uint usage, uint bindflags, uint cpuflags, uint miscflags) = 0;\r\n    virtual void load_with_mips(texture2d* tex, const image& img) = 0;\r\n    virtual void update_buffer(void* buf, int size, const void* ptr) = 0;\r\n    virtual void set_vertex_format(vertex_format* vfmt) = 0;\r\n    virtual void set_vertex_buffer(vertex_buffer* vb, uint stride, uint offset) = 0;\r\n    virtual void set_index_buffer(index_buffer* ib, uint offset) = 0;\r\n    virtual void begin_render() = 0;\r\n    virtual void end_render() = 0;\r\n    virtual void set_render_option(render_option opt, uint val) = 0;\r\n    virtual void set_vertex_shader(vertex_shader* vs) = 0;\r\n    virtual void set_pixel_shader(pixel_shader* ps) = 0;\r\n    virtual void set_geometry_shader(geometry_shader* gs) = 0;\r\n    virtual void set_viewport(const viewport& vp) = 0;\r\n    virtual void set_constant_buffer(uint slot, constant_buffer* cb, shader_type st) = 0;\r\n    virtual void set_sampler_state(uint slot, sampler_state* sstate, shader_type st) = 0;\r\n    virtual void set_shader_resource(uint slot, shader_resource_view* srv, shader_type st) = 0;\r\n    virtual void draw(uint count, uint start) = 0;\r\n    virtual void draw_indexed(uint count, uint start, int base = 0) = 0;\r\n    virtual void capture_screen(image& img, const rectf& rc, int buff_id) = 0;      /* before present, buff_id = 0; after present, buff_id = 1 */\r\n    virtual void enable_alpha_blend(bool b) = 0;\r\n    virtual void enable_depth(bool b) = 0;\r\n\r\npublic:\r\n    static bool is_vsync_enabled(const configs& cfg);\r\n    static bool is_full_screen(const configs& cfg);\r\n    static bool is_MSAA_enabled(const configs& cfg);\r\n    static uint get_MSAA_sampler_count(const configs& cfg);\r\n    static void register_dev_index_service(void* dev, rendersys* rsys);\r\n    static void unregister_dev_index_service(void* dev);\r\n    static rendersys* find_by_dev(void* dev);           /* we could usually find the rendersys by its device ptr */\r\n\r\nprotected:\r\n    render_device_info      _device_info;\r\n    float                   _bkcr[4];\r\n\r\npublic:\r\n    const render_device_info& get_device_info() const { return _device_info; }\r\n    void set_background_color(const color& cr);\r\n\r\nprivate:\r\n    static rsys_map         _dev_indexing;\r\n};\r\n\r\nextern void release_vertex_buffer(render_vertex_buffer* buf);\r\nextern void release_index_buffer(render_index_buffer* buf);\r\nextern void release_constant_buffer(render_constant_buffer* buf);\r\nextern void release_texture2d(render_texture2d* tex);\r\n\r\ntemplate<class res_class>\r\nrender_resource* convert_to_resource(res_class*);\r\n\r\ntemplate<class _pack>\r\ninline uint pack_cb_size()\r\n{\r\n    uint s = sizeof(_pack);\r\n    uint m = s % 16;\r\n    return !m ? s : s + (16 - m);\r\n}\r\n\r\n__ariel_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "8339f23d7f55f27aa7f60c78e349ea2a6379ba30", "size": 7240, "ext": "h", "lang": "C", "max_stars_repo_path": "include/ariel/rendersys.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/ariel/rendersys.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ariel/rendersys.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 44.9689440994, "max_line_length": 160, "alphanum_fraction": 0.7303867403, "num_tokens": 1752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07921033063001552, "lm_q2_score": 0.02675928357351743, "lm_q1q2_score": 0.002119611699280659}}
{"text": "/* err/stream.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#include <config.h>\n#include <stddef.h>\n#include <stdlib.h>\n#include <stdio.h>\n\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_message.h>\n\nFILE * gsl_stream = NULL ;\ngsl_stream_handler_t * gsl_stream_handler = NULL;\n\nvoid\ngsl_stream_printf (const char *label, const char *file, int line, \n\t\t   const char *reason)\n{\n  if (gsl_stream == NULL)\n    {\n      gsl_stream = stderr;\n    }\n  if (gsl_stream_handler)\n    {\n      (*gsl_stream_handler) (label, file, line, reason);\n      return;\n    }\n  fprintf (gsl_stream, \"gsl: %s:%d: %s: %s\\n\", file, line, label, reason);\n\n}\n\ngsl_stream_handler_t *\ngsl_set_stream_handler (gsl_stream_handler_t * new_handler)\n{\n  gsl_stream_handler_t * previous_handler = gsl_stream_handler;\n  gsl_stream_handler = new_handler;\n  return previous_handler;\n}\n\nFILE *\ngsl_set_stream (FILE * new_stream)\n{\n  FILE * previous_stream;\n  if (gsl_stream == NULL) {\n    gsl_stream = stderr;\n  }\n  previous_stream = gsl_stream;\n  gsl_stream = new_stream;\n  return previous_stream;\n}\n", "meta": {"hexsha": "801c1c085d62efa6d54ed84b205877e3a921e99d", "size": 1798, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/err/stream.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/err/stream.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/err/stream.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 26.8358208955, "max_line_length": 74, "alphanum_fraction": 0.7130144605, "num_tokens": 473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10521052828620037, "lm_q2_score": 0.020023439498517075, "lm_q1q2_score": 0.0021066766477457525}}
{"text": "// Implementation of the interface in uint8_image.h.\n\n#include <errno.h>\n#include <float.h>\n#include <limits.h>\n#include <math.h>\n#include <signal.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <unistd.h>\n#include <assert.h>\n\n#include <glib.h>\n#if GLIB_CHECK_VERSION (2, 6, 0)\n#  include <glib/gstdio.h>\n#endif\n#include <gsl/gsl_spline.h>\n#include <gsl/gsl_histogram.h>\n#include <gsl/gsl_math.h>\n\n#include \"asf_jpeg.h\"\n#include \"uint8_image.h\"\n#include \"asf.h\"\n\n#ifndef linux\n#ifndef darwin\n#ifndef win32\nstatic double\nround (double arg)\n{\n    return floor (arg + 0.5);\n}\n#endif // #ifndef win32\n#endif // #ifndef darwin\n#endif // #ifndef linux\n\n#include \"asf_glib.h\"\n\n// Default cache size to use is 16 megabytes.\nstatic const size_t default_cache_size = 16 * 1048576;\n// This class wide data element keeps track of the number of temporary\n// tile files opened by the current process, in order to give them\n// unique names.\nstatic unsigned long current_tile_file_number = 0;\n// We need to ensure that multiple threads trying to create their own\n// images concurently don't end up with the same temporary file\n// names.\n//G_LOCK_DEFINE_STATIC (current_tile_file_number);\n\n#ifndef win32\n// We don't want to let multiple threads twiddle the signal block mask\n// concurrently, or we might end up with the wrong set of signals\n// blocked.  This lock is used to guarantee this can't happen (see the\n// usage for a better explanation).\nG_LOCK_DEFINE_STATIC (signal_block_activity);\n#endif\n\n// Return a FILE pointer refering to a new, already unlinked file in a\n// location which hopefully has enough free space to serve as a block\n// cache.\nstatic FILE *\ninitialize_tile_cache_file (GString **tile_file_name)\n{\n  // Create the temporary tile oriented storage file.  This gets\n  // filled in in different ways depending on which creation routine\n  // we are using.\n  g_assert(*tile_file_name == NULL);\n  *tile_file_name = g_string_new (\"\");\n\n  // Here we do a slightly weird thing: if the current directory is\n  // writable, we create a temporary file in the current directory.\n  // We do this because the temporary file could well be pretty big\n  // and /tmp often maps to a small file system.  The idea is that the\n  // directory the user is in is more likely to have the extra space\n  // required to hold the temporary file.  Of course, if they have\n  // been carefully calculating their space requirements, they may be\n  // disappointed.  We use a weird name that no sane user would ever\n  // use for one of their files, we hope.\n  //G_LOCK (current_tile_file_number);\n  g_assert (sizeof (long) >= sizeof (pid_t));\n  g_string_append_printf (*tile_file_name,\n                          \".uint8_image_tile_file_%ld_%lu\",\n                          (long) getpid (),\n                          current_tile_file_number);\n\n  // This hard coded limit on the current number used to uniqueify\n  // file names limits us to creating no more than ULONG_MAX instances\n  // during a process.\n  g_assert (current_tile_file_number < ULONG_MAX);\n  current_tile_file_number++;\n  //G_UNLOCK (current_tile_file_number);\n\n#ifndef win32\n  // We block signals while we create and unlink this file, so we\n  // don't end up leaving a huge temporary file somewhere.\n  // Theoretically, two parallel instantiations of image could end up\n  // in a race condition which would result in all signals ending up\n  // blocked after both were done with this section, so we consider\n  // this section critical and protect it with a lock.\n  G_LOCK (signal_block_activity);\n  sigset_t all_signals, old_set;\n  int return_code = sigfillset (&all_signals);\n  g_assert (return_code == 0);\n  return_code = sigprocmask (SIG_SETMASK, &all_signals, &old_set);\n#endif\n\n  // FIXME?: It might be faster to use file descriptor based I/O\n  // everywhere, or at least for the big transfers.  I'm not sure its\n  // worth the trouble though.\n  FILE *tile_file = fopen_tmp_file ((*tile_file_name)->str, \"w+b\");\n  if ( tile_file == NULL ) {\n    if ( errno != EACCES ) {\n      g_warning (\"couldn't create file in current directory, and it wasn't\"\n                 \"just a permissions problem\");\n    }\n    else {\n      // Couldn't open in current directory, so try using tmpfile,\n      // which opens the file in the standardish place for the system.\n      // See the comment above about why opening in /tmp or the like\n      // is potentially bad.\n      tile_file = tmpfile ();\n      g_assert (tile_file != NULL);\n    }\n  }\n  else {\n#ifndef win32\n    return_code = unlink_tmp_file ((*tile_file_name)->str);\n    g_assert (return_code == 0);\n#endif\n  }\n  g_assert (tile_file != NULL);\n\n#ifndef win32\n  return_code = sigprocmask (SIG_SETMASK, &old_set, NULL);\n  G_UNLOCK (signal_block_activity);\n#endif\n\n  return tile_file;\n}\n\n// This routine does the work common to several of the differenct\n// creation routines.  Basically, it does everything but fill in the\n// contents of the disk tile store.\nstatic UInt8Image *\ninitialize_uint8_image_structure (ssize_t size_x, ssize_t size_y)\n{\n  // Allocate instance memory.\n  UInt8Image *self = g_new0 (UInt8Image, 1);\n\n  // Validate and remember image size.\n  g_assert (size_x > 0 && size_y > 0);\n  self->size_x = size_x;\n  self->size_y = size_y;\n\n  // Greater of size_x and size_y.\n  size_t largest_dimension = (size_x > size_y ? size_x : size_y);\n\n  // If we can fit the entire image in a single square tile, then we\n  // want just a single big tile and we won't need to bother with the\n  // cache file since it won't ever be used, so we do things slightly\n  // differently.  FIXME: it would be slightly better to also detect\n  // and specially handle the case where we have long narrow images\n  // that can fit in a single stip of tiles in the cache.\n  if ( largest_dimension * largest_dimension * sizeof (uint8_t)\n       <= default_cache_size ) {\n    self->cache_space = (largest_dimension * largest_dimension\n       * sizeof (uint8_t));\n    self->cache_area = self->cache_space / sizeof (uint8_t);\n    self->tile_size = largest_dimension;\n    self->cache_size_in_tiles = 1;\n    self->tile_count_x = 1;\n    self->tile_count_y = 1;\n    self->tile_count = 1;\n    self->tile_area = self->tile_size * self->tile_size;\n    self->cache = g_new (uint8_t, self->cache_area);\n    self->tile_addresses = g_new0 (uint8_t *, self->tile_count);\n    g_assert (NULL == 0x0);     // Ensure g_new0 effectively sets to NULL.\n    // The tile queue shouldn't ever be needed in this case.\n    self->tile_queue = NULL;\n    // The tile file shouldn't ever be needed, so we set it to NULL to\n    // indicate this to a few other methods that use it directly, and\n    // to hopefully ensure that it triggers an exception if it is\n    // used.\n    self->tile_file = NULL;\n\n    return self;\n  }\n\n  // The default cache size compiled into the class.\n  self->cache_space = default_cache_size;\n\n  // Memory cache space, in pixels.\n  g_assert (self->cache_space % sizeof (uint8_t) == 0);\n  self->cache_area = self->cache_space / sizeof (uint8_t);\n\n  // How small do our tiles have to be on a side to fit two full rows\n  // of them in the memory cache?  This is slightly tricky.  In order\n  // to provide the services promised in the interface, we need to\n  // solve\n  //\n  //      2 * pow (t, 2) * ceil ((double)largest_dimension / t)\n  //           <= self->cache_area\n  //\n  // for tile size t.  I don't know the closed form solution if there\n  // is one, so toss out the ceil() and solve the easier\n  //\n  //      2 * pow (t, 2) * ((double)largest_dimension / t) <= self->cache_area\n  //\n  // and then decrement t iteratively until things work.\n  self->tile_size = self->cache_area / (2 * largest_dimension);\n  while ( (2 * self->tile_size * self->tile_size\n           * ceil ((double) largest_dimension / self->tile_size))\n          > self->cache_area ) {\n    self->tile_size--;\n  }\n\n  // Area of tiles, in pixels.\n  self->tile_area = (size_t) (self->tile_size * self->tile_size);\n\n  // Number of tiles which will fit in image cache.\n  self->cache_size_in_tiles = self->cache_area / self->tile_area;\n  // Can we fit at least as much as we intended in the cache?\n  g_assert (self->cache_size_in_tiles\n            >= 2 * (size_t) ceil ((double) largest_dimension\n                                  / self->tile_size));\n\n  // Number of tiles image has been split into in x and y directions.\n  self->tile_count_x = (size_t) ceil ((double) self->size_x / self->tile_size);\n  self->tile_count_y = (size_t) ceil ((double) self->size_y / self->tile_size);\n\n  // Total number of image tiles image has been split into.\n  self->tile_count = self->tile_count_x * self->tile_count_y;\n\n  // We want to be able to pack a tile number into a pointer later, so\n  // we need it to fit into an integer.\n  g_assert (self->tile_count < INT_MAX);\n\n  // Did all that math work?\n  g_assert (self->tile_size * self->cache_size_in_tiles / 2\n            >= largest_dimension);\n  g_assert (self->cache_size_in_tiles * self->tile_area <= self->cache_area);\n\n  // Allocate memory for the in-memory cache.\n  self->cache = g_new (uint8_t, self->cache_area);\n  // Do we want to do mlock() here maybe?\n\n  // The addresses in the cache of the starts of each of the tiles.\n  // This array contains flattened tile addresses in the same way that\n  // image memory normally uses flattened pixel addresses, e.g. the\n  // address of tile x = 2, y = 4 is stored at self->tile_addresses[4\n  // * self->tile_count_x + 2].  If a tile isn't in the cache, the\n  // address is NULL (meaning it will have to be loaded).\n  self->tile_addresses = g_new0 (uint8_t *, self->tile_count);\n  g_assert (NULL == 0x0);       // Ensure g_new0 effectively sets to NULL.\n\n  // Create a queue in order to keep track of which tile was loaded\n  // longest ago.\n  self->tile_queue = g_queue_new ();\n\n  // Get a new empty tile cache file pointer.\n  self->tile_file_name = NULL;\n  self->tile_file = initialize_tile_cache_file ( &(self->tile_file_name) );\n\n  return self;\n}\n\nUInt8Image *\nuint8_image_thaw (FILE *file_pointer)\n{\n  FILE *fp = file_pointer;  // Convenience alias.\n\n  g_assert (file_pointer != NULL);\n\n  UInt8Image *self = g_new (UInt8Image, 1);\n\n  size_t read_count = fread (&(self->size_x), sizeof (size_t), 1, fp);\n  g_assert (read_count == 1);\n\n  read_count = fread (&(self->size_y), sizeof (size_t), 1, fp);\n  g_assert (read_count == 1);\n\n  read_count = fread (&(self->cache_space), sizeof (size_t), 1, fp);\n  g_assert (read_count == 1);\n\n  read_count = fread (&(self->cache_area), sizeof (size_t), 1, fp);\n  g_assert (read_count == 1);\n\n  read_count = fread (&(self->tile_size), sizeof (size_t), 1, fp);\n  g_assert (read_count == 1);\n\n  read_count = fread (&(self->cache_size_in_tiles), sizeof (size_t), 1, fp);\n  g_assert (read_count == 1);\n\n  read_count = fread (&(self->tile_count_x), sizeof (size_t), 1, fp);\n  g_assert (read_count == 1);\n\n  read_count = fread (&(self->tile_count_y), sizeof (size_t), 1, fp);\n  g_assert (read_count == 1);\n\n  read_count = fread (&(self->tile_count), sizeof (size_t), 1, fp);\n  g_assert (read_count == 1);\n\n  read_count = fread (&(self->tile_area), sizeof (size_t), 1, fp);\n  g_assert (read_count == 1);\n\n  // The cache isn't serialized -- its a bit of a pain and probably\n  // almost never worth it.\n  self->cache = g_new (uint8_t, self->cache_area);\n\n  self->tile_addresses = g_new0 (uint8_t *, self->tile_count);\n\n  // We don't actually keep the tile queue in the serialized instance,\n  // but if the serialized pointer to it is NULL, we know we aren't\n  // using a tile cache file (i.e. the whole image fits in the memory\n  // cache).\n  read_count = fread (&(self->tile_queue), sizeof (GQueue *), 1, fp);\n  g_assert (read_count == 1);\n\n  // If there was no cache file...\n  if ( self->tile_queue == NULL ) {\n    // The tile_file structure field should also be NULL.\n    self->tile_file = NULL;\n    // we restore the file directly into the first and only tile (see\n    // the end of the uint8_image_new method).\n    self->tile_addresses[0] = self->cache;\n    read_count = fread (self->tile_addresses[0], sizeof (uint8_t),\n      self->tile_area, fp);\n    g_assert (read_count == self->tile_area);\n  }\n  // otherwise, an empty tile queue needs to be initialized, and the\n  // remainder of the serialized version is the tile block cache.\n  else {\n    self->tile_queue = g_queue_new ();\n    self->tile_file_name = NULL;\n    self->tile_file = initialize_tile_cache_file ( &(self->tile_file_name) );\n    uint8_t *buffer = g_new (uint8_t, self->tile_area);\n    size_t ii;\n    for ( ii = 0 ; ii < self->tile_count ; ii++ ) {\n      read_count = fread (buffer, sizeof (uint8_t), self->tile_area, fp);\n      g_assert (read_count == self->tile_area);\n      size_t write_count = fwrite (buffer, sizeof (uint8_t), self->tile_area,\n           self->tile_file);\n      if ( write_count < self->tile_area ) {\n  if ( feof (self->tile_file) ) {\n    fprintf (stderr,\n       \"Premature end of file while trying to thaw UInt8Image \"\n       \"instance\\n\");\n  }\n  else {\n    g_assert (ferror (self->tile_file));\n    fprintf (stderr,\n       \"Error writing tile cache file for UInt8Image instance \"\n       \"during thaw: %s\\n\", strerror (errno));\n  }\n  exit (EXIT_FAILURE);\n      }\n      g_assert (write_count == self->tile_area);\n    }\n    g_free (buffer);\n  }\n\n  return self;\n}\n\n\n\nUInt8Image *\nuint8_image_new (ssize_t size_x, ssize_t size_y)\n{\n  g_assert (size_x > 0 && size_y > 0);\n\n  UInt8Image *self = initialize_uint8_image_structure (size_x, size_y);\n\n  // If we need a tile file for an image of this size, prepare it.\n  if ( self->tile_file != NULL ) {\n\n    // The total width or height of all the tiles is probably greater\n    // than the width or height of the image itself.\n    size_t total_width = self->tile_count_x * self->tile_size;\n    size_t total_height = self->tile_count_y * self->tile_size;\n\n    // Fill the file full of zeros.  FIXME: there is almost certainly\n    // a faster way to ensure that we have the disk space we need.\n    uint8_t *zero_line = g_new0 (uint8_t, total_width);\n    g_assert (0 == 0x0);      // Ensure the g_new0 did what we think.\n\n    // We don't have to write in tile order because its all zeros anyway.\n    size_t ii;\n    for ( ii = 0 ; ii < total_height ; ii++ ) {\n      size_t write_count = fwrite (zero_line, sizeof (uint8_t), total_width,\n                                   self->tile_file);\n      // If we wrote less than expected,\n      if ( write_count < total_width ) {\n        // it must have been a write error (probably no space left),\n        g_assert (ferror (self->tile_file));\n        // so print an error message,\n        fprintf (stderr,\n                 \"Error writing tile cache file for UInt8Image instance: \"\n                 \"%s\\n\", strerror (errno));\n        // and exit.\n        exit (EXIT_FAILURE);\n      }\n    }\n\n    // Done with the line of zeros.\n    g_free (zero_line);\n  }\n\n  // Everything fits in the cache (at the moment this means everything\n  // fits in the first tile, which is a bit of a FIXME), so just put\n  // it there.\n  else {\n    self->tile_addresses[0] = self->cache;\n    size_t ii, jj;\n    for ( ii = 0 ; ii < self->tile_size ; ii++ ) {\n      for ( jj = 0 ; jj < self->tile_size ; jj++ ) {\n        self->tile_addresses[0][ii * self->tile_size + jj] = 0;\n      }\n    }\n  }\n\n  return self;\n}\n\nUInt8Image *\nuint_image_new_with_value (ssize_t size_x, ssize_t size_y, uint8_t value)\n{\n  // Carefully clone-and-modified over from float_image.c, but not\n  // tested yet.\n  g_assert_not_reached ();\n\n  g_assert (size_x > 0 && size_y > 0);\n\n  UInt8Image *self = initialize_uint8_image_structure (size_x, size_y);\n\n  // If we need a tile file for an image of this size, prepare it.\n  if ( self->tile_file != NULL ) {\n\n    // The total width or height of all the tiles is probably greater\n    // than the width or height of the image itself.\n    size_t total_width = self->tile_count_x * self->tile_size;\n    size_t total_height = self->tile_count_y * self->tile_size;\n\n    // Fill the file full of the given value.\n    uint8_t *value_line = g_new (uint8_t, total_width);\n    size_t ii;\n    for ( ii = 0 ; ii < total_width ; ii++ ) {\n      value_line[ii] = value;\n    }\n    // We don't have to write in tile order because the values are all\n    // the same anyway.\n    for ( ii = 0 ; ii < total_height ; ii++ ) {\n      size_t write_count = fwrite (value_line, sizeof (uint8_t), total_width,\n                                   self->tile_file);\n      // If we wrote less than expected,\n      if ( write_count < total_width ) {\n        // it must have been a write error (probably no space left),\n        g_assert (ferror (self->tile_file));\n        // so print an error message,\n        fprintf (stderr,\n                 \"Error writing tile cache file for UInt8Image instance: \"\n                 \"%s\\n\", strerror (errno));\n        // and exit.\n        exit (EXIT_FAILURE);\n      }\n    }\n\n    // Done with the line of values.\n    g_free (value_line);\n  }\n\n  // Everything fits in the cache (at the moment this means everything\n  // fits in the first tile, which is a bit of a FIXME), so just put\n  // it there.\n  else {\n    self->tile_addresses[0] = self->cache;\n    size_t ii, jj;\n    for ( ii = 0 ; ii < self->tile_size ; ii++ ) {\n      for ( jj = 0 ; jj < self->tile_size ; jj++ ) {\n        self->tile_addresses[0][ii * self->tile_size + jj] = value;\n      }\n    }\n  }\n\n  return self;\n}\n\nUInt8Image *\nuint8_image_new_from_memory (ssize_t size_x, ssize_t size_y, uint8_t *buffer)\n{\n  g_assert (size_x > 0 && size_y > 0);\n\n  g_assert_not_reached ();      // Stubbed out for now.\n  // Compiler reassurance.\n  size_x = size_x;\n  size_y = size_y;\n  buffer = buffer;\n  return NULL;\n}\n\n// Bilinear interpolation for a point delta_x, delta_y from the lower\n// left corner between values ul (upper left), ur (upper right), etc.\n// The corner are considered to be corners of a unit square.\nstatic float\nbilinear_interpolate (double delta_x, double delta_y, float ul, float ur,\n                      float ll, float lr)\n{\n  float lv = ll + (lr - ll) * delta_x; // Lower value.\n  float uv = ul + (ur - ul) * delta_x; // Upper value.\n\n  return lv + (uv - lv) * delta_y;\n}\n\nUInt8Image *\nuint8_image_copy (UInt8Image *model)\n{\n  // This method should be totally fine, it is extremely trivial clone\n  // and modify from the corresponding method in float_image.c, but\n  // since its untested I disable it for the moment.\n  g_assert_not_reached ();\n\n  // FIXME: this could obviously be optimized a lot by copying the\n  // existed tile file, etc.\n  UInt8Image *self = uint8_image_new (model->size_x, model->size_y);\n\n  size_t ii, jj;\n  for ( ii = 0 ; ii < self->size_y ; ii++ ) {\n    for ( jj = 0 ; jj < self->size_x ; jj++ ) {\n      uint8_image_set_pixel (self, jj, ii,\n           uint8_image_get_pixel (model, jj, ii));\n    }\n  }\n\n  return self;\n}\n\nUInt8Image *\nuint8_image_new_from_model_scaled (UInt8Image *model, ssize_t scale_factor)\n{\n  g_assert (model->size_x > 0 && model->size_y > 0);\n\n  g_assert (scale_factor > 0);\n  g_assert (scale_factor % 2 == 1);\n\n  UInt8Image *self\n    = uint8_image_new (round ((double) model->size_x / scale_factor),\n           round ((double) model->size_y / scale_factor));\n\n  // This method hasn't yet made the jump from FloatImage to here.\n  // The implementation should ultimately follow the one in FloatImage\n  // to achieve the interface description given in uint8_image.h.\n  g_assert_not_reached ();\n\n  return self;\n}\n\nUInt8Image *\nuint8_image_new_subimage (UInt8Image *model, ssize_t x, ssize_t y,\n        ssize_t size_x, ssize_t size_y)\n{\n  // Upper left corner must be in model.\n  g_assert (x >= 0 && y >= 0);\n\n  // Size of image to be created must be strictly positive.\n  g_assert (size_x >= 1 && size_y >= 1);\n\n  // Given model must be big enough to allow a subimage of the\n  // requested size to fit.\n  g_assert (model->size_x <= SSIZE_MAX && model->size_y <= SSIZE_MAX);\n  g_assert (x + size_x <= (ssize_t) model->size_x);\n  g_assert (y + size_y <= (ssize_t) model->size_y);\n\n  UInt8Image *self = uint8_image_new (size_x, size_y);\n\n  // Copy the image pixels from the model.\n  ssize_t ii, jj;\n  for ( ii = 0 ; ii < (ssize_t) self->size_x ; ii++ ) {\n    for ( jj = 0 ; jj < (ssize_t) self->size_y ; jj++ ) {\n      uint8_t pv = uint8_image_get_pixel (model, x + ii, y + jj);\n      uint8_image_set_pixel (self, ii, jj, pv);\n    }\n  }\n\n  return self;\n}\n\n// Return true iff file is size or larger.\nstatic gboolean\nis_large_enough (const char *file, off_t size)\n{\n  struct stat stat_buffer;\n#if GLIB_CHECK_VERSION(2, 6, 0)\n  int return_code = g_stat (file, &stat_buffer);\n  if ( return_code != 0 ) {\n    g_error (\"Couldn't g_stat file %s: %s\", file, strerror (errno));\n  }\n#else\n  int return_code = stat (file, &stat_buffer);\n  if ( return_code != 0 ) {\n    g_error (\"Couldn't stat file %s: %s\", file, strerror (errno));\n  }\n#endif\n\n  return stat_buffer.st_size >= size;\n}\n\nUInt8Image *\nuint8_image_new_from_file (ssize_t size_x, ssize_t size_y, const char *file,\n                           off_t offset)\n{\n  g_assert (size_x > 0 && size_y > 0);\n\n  // Check in advance if the source file looks big enough (we will\n  // still need to check return codes as we read() data, of course).\n  g_assert (is_large_enough (file, offset + ((off_t) size_x * size_y\n               * sizeof (uint8_t))));\n\n  // Open the file to read data from.\n  FILE *fp = fopen (file, \"rb\");\n  // FIXME: we need some error handling and propagation here.\n  g_assert (fp != NULL);\n\n  UInt8Image *self = uint8_image_new_from_file_pointer (size_x, size_y, fp,\n                                                        offset);\n\n  // Close file we read image from.\n  int return_code = fclose (fp);\n  g_assert (return_code == 0);\n\n  return self;\n}\n\n// Return true iff file referred to by file_pointer is larger than size.\nstatic gboolean\nfile_pointed_to_larger_than (FILE *file_pointer, off_t size)\n{\n  struct stat stat_buffer;\n  int return_code = fstat (fileno (file_pointer), &stat_buffer);\n  g_assert (return_code == 0);\n  return stat_buffer.st_size >= size;\n}\n\n\nUInt8Image *\nuint8_image_new_from_file_pointer (ssize_t size_x, ssize_t size_y,\n                                   FILE *file_pointer, off_t offset)\n{\n  g_assert (size_x > 0 && size_y > 0);\n\n  // Check in advance if the source file looks big enough (we will\n  // still need to check return codes as we read() data, of course).\n  g_assert (file_pointed_to_larger_than (file_pointer,\n           offset + ((off_t) size_x * size_y\n               * sizeof (uint8_t))));\n\n  UInt8Image *self = initialize_uint8_image_structure (size_x, size_y);\n\n  FILE *fp = file_pointer;      // Convenience alias.\n\n  // Seek to the indicated offset in the file.\n  int return_code = FSEEK64 (fp, offset, SEEK_CUR);\n  g_assert (return_code == 0);\n\n  // If we need a tile file for an image of this size, we will load\n  // the data straight into it.\n  if ( self->tile_file != NULL ) {\n\n    // We will read the input image data in horizontal stips one tile\n    // high.  Note that we probably won't be able to entirely fill the\n    // last tiles in each dimension with real data, since the image\n    // sizes rarely divide evenly by the numbers of tiles.  So we fill\n    // it with zeros instead.  The data off the edges of the image\n    // should never be accessed directly anyway.\n\n    // Some data for doing zero fill.  If the tiles are bigger than\n    // the image itself, we need to make the available zero fill the\n    // size of the tile instead of the size of the file.\n    g_assert (self->tile_size <= SSIZE_MAX);\n    uint8_t *zero_line = g_new0 (uint8_t, (size_x > (ssize_t) self->tile_size ?\n             (size_t) size_x : self->tile_size));\n    g_assert (0 == 0x0);\n\n    // Buffer capable of holding a full strip.\n    uint8_t *buffer = g_new (uint8_t, self->tile_size * self->size_x);\n\n    // Reorganize data into tiles in tile oriented disk file.\n    size_t ii = 0;\n    for ( ii = 0 ; ii < self->tile_count_y ; ii++ ) {\n      // The \"effective_height\" of the strip is the portion of the\n      // strip for which data actually exists.  If the effective\n      // height is less than self->tile>size, we will have to add some\n      // junk to fill up the extra part of the tile (which should\n      // never be accessed).\n      size_t effective_height;\n      if ( ii < self->tile_count_y - 1\n           || self->size_y % self->tile_size == 0 ) {\n        effective_height = self->tile_size;\n      }\n      else {\n        effective_height = self->size_y % self->tile_size;\n      }\n      // Total area of the current strip.\n      size_t strip_area = effective_height * self->size_x;\n\n      // Read one strip of tiles worth of data from the file.\n      size_t read_count = fread (buffer, sizeof (uint8_t), strip_area, fp);\n      g_assert (read_count == strip_area);\n\n      // Write data from the strip into the tile store.\n      size_t jj;\n      for ( jj = 0 ; jj < self->tile_count_x ; jj++ ) {\n        // This is roughly analogous to effective_height.\n        size_t effective_width;\n        if ( jj < self->tile_count_x - 1\n             || self->size_x % self->tile_size == 0) {\n          effective_width = self->tile_size;\n        }\n        else {\n          effective_width = self->size_x % self->tile_size;\n        }\n        size_t write_count;     // For return of fwrite() calls.\n        size_t kk;\n        for ( kk = 0 ; kk < effective_height ; kk++ ) {\n          write_count\n            = fwrite (buffer + kk * self->size_x + jj * self->tile_size,\n                      sizeof (uint8_t), effective_width, self->tile_file);\n          // If we wrote less than expected,\n          if ( write_count < effective_width ) {\n            // it must have been a write error (probably no space left),\n            g_assert (ferror (self->tile_file));\n            // so print an error message,\n            fprintf (stderr,\n                     \"Error writing tile cache file for UInt8Image \"\n                     \"instance: %s\\n\", strerror (errno));\n            // and exit.\n            exit (EXIT_FAILURE);\n          }\n          if ( effective_width < self->tile_size ) {\n            // Amount we have left to write to fill out the last tile.\n            size_t edge_width = self->tile_size - effective_width;\n            write_count = fwrite (zero_line, sizeof (uint8_t), edge_width,\n                                  self->tile_file);\n            // If we wrote less than expected,\n            if ( write_count < edge_width ) {\n              // it must have been a write error (probably no space left),\n              g_assert (ferror (self->tile_file));\n              // so print an error message,\n              fprintf (stderr,\n                       \"Error writing tile cache file for UInt8Image \"\n                       \"instance: %s\\n\", strerror (errno));\n              // and exit.\n              exit (EXIT_FAILURE);\n            }\n          }\n        }\n        // Finish writing the bottom of the tile for which there is no\n        // image data (should only happen if we are on the last strip of\n        // tiles).\n        for ( ; kk < self->tile_size ; kk++ ) {\n          g_assert (ii == self->tile_count_y - 1);\n          write_count = fwrite (zero_line, sizeof (uint8_t), self->tile_size,\n                                self->tile_file);\n          // If we wrote less than expected,\n          if ( write_count < self->tile_size ) {\n            // it must have been a write error (probably no space left),\n            g_assert (ferror (self->tile_file));\n            // so print an error message,\n            fprintf (stderr,\n                     \"Error writing tile cache file for UInt8Image \"\n                     \"instance: %s\\n\", strerror (errno));\n            // and exit.\n            exit (EXIT_FAILURE);\n          }\n        }\n      }\n    }\n\n    // Did we write the correct total amount of data?\n    g_assert (FTELL64 (self->tile_file)\n        == ((off_t) self->tile_area * self->tile_count\n      * sizeof (uint8_t)));\n\n    // Free temporary buffers.\n    g_free (buffer);\n    g_free (zero_line);\n  }\n\n  // Everything fits in the cache (at the moment this means everything\n  // fits in the first tile, which is a bit of a FIXME), so just put\n  // it there.\n  else {\n    self->tile_addresses[0] = self->cache;\n\n    size_t ii;\n    for ( ii = 0 ; ii < self->size_y ; ii++ ) {\n      // Address where the current row of pixels should end up.\n      uint8_t *row_address = self->tile_addresses[0] + ii * self->tile_size;\n\n      // Read the data.\n      size_t read_count = fread (row_address, sizeof (uint8_t), self->size_x,\n         fp);\n      g_assert (read_count == self->size_x);\n    }\n  }\n\n  return self;\n}\n\nUInt8Image *\nuint8_image_new_from_file_scaled (ssize_t size_x, ssize_t size_y,\n                                  ssize_t original_size_x,\n                                  ssize_t original_size_y,\n          const char *file, off_t offset)\n{\n  // This method has been carefully translated from the corresponding\n  // method in float_image.c, but it hasn't been tested yet.\n  g_assert_not_reached ();\n\n  g_assert (size_x > 0 && size_y > 0);\n  g_assert (original_size_x > 0 && original_size_y > 0);\n\n  // Image can only be scaled down with this routine, not up.\n  g_assert (size_x < original_size_x);\n  g_assert (size_y < original_size_y);\n\n  // Check in advance if the source file looks big enough (we will\n  // still need to check return codes as we read() data, of course).\n  g_assert (is_large_enough (file,\n           offset + ((off_t) original_size_x\n               * original_size_y\n               * sizeof (uint8_t))));\n\n  // Find the stride that we need to use in each dimension to evenly\n  // cover the original image space.\n  double stride_x = (size_x == 1 ? 0.0\n         : (double) (original_size_x - 1) / (size_x - 1));\n  double stride_y = (size_y == 1 ? 0.0\n         : (double) (original_size_y - 1) / (size_y - 1));\n\n  // Open the file to read data from.\n  FILE *fp = fopen (file, \"rb\");\n  // FIXME: we need some error handling and propagation here.\n  g_assert (fp != NULL);\n\n  // We will do a row at a time to save some possibly expensive\n  // seeking.  So here we have an entire row worth of upper lefts,\n  // upper rights, etc.\n  uint8_t *uls = g_new (uint8_t, size_x);\n  uint8_t *urs = g_new (uint8_t, size_x);\n  uint8_t *lls = g_new (uint8_t, size_x);\n  uint8_t *lrs = g_new (uint8_t, size_x);\n\n  // Results of rounded bilinear interpolation for the current row.\n  uint8_t *interpolated_values = g_new (uint8_t, size_x);\n\n  // We will write the reduced resolution version of the image into a\n  // temporary file so we can leverage the new_from_file method and\n  // avoid trying to stick the whole reduced resolution image in\n  // memory.\n  FILE *reduced_image = tmpfile ();\n\n  ssize_t ii, jj;\n  for ( ii = 0 ; ii < size_y ; ii++ ) {\n    size_t read_count;          // For fread calls.\n    int return_code;            // For FSEEK64 calls.\n    // Input image y index of row above row of interest.\n    ssize_t in_ray = floor (ii * stride_y);\n    // Due to the vagaries of floating point arithmetic, we might run\n    // past the index of our last pixel by a little bit, so we correct.\n    if ( in_ray >= original_size_y - 1 ) {\n      // We better not be much over the last index though.\n      g_assert (in_ray < original_size_y);\n      // The index should be an integer, so floor should fix us up.\n      in_ray = floor (in_ray);\n      g_assert (in_ray == original_size_y - 1);\n    }\n    g_assert (in_ray < original_size_y);\n    // Input image y index of row below row of interest.  If we would\n    // be off the image, we just take the last row a second time, and\n    // let the interpolation work things out.\n    ssize_t in_rby;\n    if ( in_ray == original_size_y - 1 ) {\n      in_rby = in_ray;\n    }\n    else {\n      in_rby = in_ray + 1;\n    }\n    // Fetch the row above.\n    for ( jj = 0 ; jj < size_x ; jj++ ) {\n      // Input image indicies of current upper left corner pixel.\n      ssize_t in_ul_x = floor (jj * stride_x);\n      // Watch for floating point inexactness (see comment above).\n      if ( G_UNLIKELY (in_ul_x >= original_size_x - 1) ) {\n        g_assert (in_ul_x < original_size_x);\n        in_ul_x = floor (in_ul_x);\n        g_assert (in_ul_x == original_size_x - 1);\n      }\n      g_assert (in_ul_x < original_size_x);\n      size_t in_ul_y = in_ray;\n      off_t sample_offset\n  = offset + sizeof (uint8_t) * ((off_t) in_ul_y * original_size_x\n               + in_ul_x);\n      return_code = FSEEK64 (fp, sample_offset, SEEK_SET);\n      g_assert (return_code == 0);\n      read_count = fread (&(uls[jj]), sizeof (uint8_t), 1, fp);\n      g_assert (read_count == 1);\n      // If the upper left pixel was the last pixel in the input image,\n      if ( in_ul_x == original_size_x - 1 ) {\n        // just treat it as the upper right as well,\n        urs[jj] = uls[jj];\n      }\n      // otherwise read the next pixel as the upper right pixel.\n      else {\n        read_count = fread (&(urs[jj]), sizeof (uint8_t), 1, fp);\n        g_assert (read_count == 1);\n      }\n    }\n    // Fetch the row below.\n    for ( jj = 0 ; jj < size_x ; jj++ ) {\n      // Input image indicies of the lower left corner pixel.\n      ssize_t in_ll_x = floor (jj * stride_x);\n      // Watch for floating point inexactness (see comment above).\n      if ( G_UNLIKELY (in_ll_x >= original_size_y - 1) ) {\n        g_assert (in_ll_x < original_size_x);\n        in_ll_x = floor (in_ll_x);\n        g_assert (in_ll_x == original_size_x - 1);\n      }\n      g_assert (in_ll_x < original_size_x);\n      size_t in_ll_y = in_rby;\n      off_t sample_offset\n  = offset + sizeof (uint8_t) * ((off_t) in_ll_y * original_size_x\n               + in_ll_x);\n      return_code = FSEEK64 (fp, sample_offset, SEEK_SET);\n      g_assert (return_code == 0);\n      read_count = fread (&(lls[jj]), sizeof (uint8_t), 1, fp);\n      g_assert (read_count == 1);\n      // If the lower left pixel was the last pixel in the input image,\n      if ( in_ll_x == original_size_x - 1 ) {\n        // just treat it as the lower right as well,\n        lrs[jj] = lls[jj];\n      }\n      // otherwise read the next pixel as the lower right pixel.\n      else {\n        read_count = fread (&(lrs[jj]), sizeof (uint8_t), 1, fp);\n        g_assert (read_count == 1);\n      }\n    }\n\n    // Perform the interpolation.\n    for ( jj = 0 ; jj < size_x ; jj++ ) {\n      double delta_x = stride_x * jj - floor (stride_x * jj);\n      double delta_y = -(stride_y * ii - floor (stride_y * ii));\n      float interpolated_value = bilinear_interpolate (delta_x, delta_y,\n                   uls[jj], urs[jj],\n                   lls[jj], lrs[jj]);\n      g_assert (interpolated_value >= 0);\n      g_assert (interpolated_value <= UINT8_MAX);\n      interpolated_values[jj] = round (interpolated_value);\n    }\n    size_t write_count = fwrite (interpolated_values, sizeof (uint8_t), size_x,\n                                 reduced_image);\n    g_assert (write_count == (size_t) size_x);\n  }\n\n  // We are done with the temporary buffers.\n  g_free (interpolated_values);\n  g_free (lrs);\n  g_free (lls);\n  g_free (urs);\n  g_free (uls);\n\n  // Reposition to the beginning of the temporary file to fit with\n  // operation of new_from_file_pointer method.\n  int return_code = FSEEK64 (reduced_image, (off_t) 0, SEEK_SET);\n  g_assert (return_code == 0);\n\n  // Slurp the scaled file back in as an instance.\n  UInt8Image *self\n    = uint8_image_new_from_file_pointer (size_x, size_y, reduced_image,\n           (off_t) 0);\n\n  // Now that we have an instantiated version of the image we are done\n  // with this temporary file.\n  return_code = fclose (reduced_image);\n\n  return self;\n}\n\n// Returns a new UInt8Image, for the image corresponding to the given metadata.\nUInt8Image *\nuint8_image_new_from_metadata(meta_parameters *meta, const char *file)\n{\n  return uint8_image_band_new_from_metadata(meta, 0, file);\n}\n\n// Returns a new UInt8Image, for the image band corresponding to the\n// given metadata.\nUInt8Image *\nuint8_image_band_new_from_metadata(meta_parameters *meta,\n           int band, const char *file)\n{\n    int nl = meta->general->line_count;\n    int ns = meta->general->sample_count;\n\n    FILE * fp = FOPEN(file, \"rb\");\n    UInt8Image * bi = uint8_image_new(ns, nl);\n\n    int i,j;\n    unsigned char *buf = MALLOC(sizeof(unsigned char)*ns);\n    for (i = 0; i < nl; ++i) {\n        get_byte_line(fp, meta, i+band*nl, buf);\n        for (j = 0; j < ns; ++j)\n            uint8_image_set_pixel(bi, j, i, buf[j]);\n    }\n\n    free(buf);\n    fclose(fp);\n\n    return bi;\n}\n\n// Copy the contents of tile with flattened offset tile_offset from\n// the memory cache to the disk file.  Its probably easiest to\n// understand this function by looking at how its used.\nstatic void\ncached_tile_to_disk (UInt8Image *self, size_t tile_offset)\n{\n  // If we aren't using a tile file, this operation doesn't make\n  // sense.\n  g_assert (self->tile_file != NULL);\n\n  // We must have a legitimate tile_offset.\n  g_assert (tile_offset < self->tile_count);\n\n  // The tile we are trying to copy from cache to disk must be loaded\n  // in the cache for this operation to make sense.\n  g_assert (self->tile_addresses[tile_offset] != NULL);\n\n  int return_code\n    = FSEEK64 (self->tile_file,\n        (off_t) tile_offset * self->tile_area * sizeof (uint8_t),\n        SEEK_SET);\n  g_assert (return_code == 0);\n  size_t write_count = fwrite (self->tile_addresses[tile_offset],\n             sizeof (uint8_t), self->tile_area,\n             self->tile_file);\n  g_assert (write_count == self->tile_area);\n}\n\n// Return true iff tile (x, y) is already loaded into the memory cache.\nstatic gboolean\ntile_is_loaded (UInt8Image *self, ssize_t x, ssize_t y)\n{\n  g_assert (    x >= 0 && (size_t) x < self->tile_count_x\n             && y >= 0 && (size_t) y < self->tile_count_y );\n\n  size_t tile_offset = self->tile_count_x * y + x;\n\n  return self->tile_addresses[tile_offset] != NULL;\n}\n\n// Load (currently unloaded) tile (x, y) from disk cache into memory\n// cache, possibly displacing the oldest tile already loaded, updating\n// the load order queue, and returning the address of the tile loaded.\nstatic uint8_t *\nload_tile (UInt8Image *self, ssize_t x, ssize_t y)\n{\n  // Make sure we haven't screwed up somehow and not created a tile\n  // file when in fact we should have.\n  g_assert (self->tile_file != NULL);\n\n  g_assert (!tile_is_loaded (self, x, y));\n\n  // Address into which tile gets loaded (to be returned).\n  uint8_t *tile_address;\n\n  // Offset of tile in flattened array.\n  size_t tile_offset = self->tile_count_x * y + x;\n\n  // We have to check and see if we have to displace an already loaded\n  // tile or not.\n  if ( self->tile_queue->length == self->cache_size_in_tiles ) {\n    // Displace tile loaded longest ago.\n    size_t oldest_tile\n      = GPOINTER_TO_INT (g_queue_pop_tail (self->tile_queue));\n    cached_tile_to_disk (self, oldest_tile);\n    tile_address = self->tile_addresses[oldest_tile];\n    self->tile_addresses[oldest_tile] = NULL;\n  }\n  else {\n    // Load tile into first free slot.\n    tile_address = self->cache + self->tile_queue->length * self->tile_area;\n  }\n\n  // Put the new tile address into the index, and put the index into\n  // the load order queue.\n  self->tile_addresses[tile_offset] = tile_address;\n  // Stash in queue by converting to a pointer (so it must fit in an int).\n  g_assert (tile_offset < INT_MAX);\n  g_queue_push_head (self->tile_queue,\n                     GINT_TO_POINTER ((int) tile_offset));\n\n  // Load the tile data.\n  int return_code\n    = FSEEK64 (self->tile_file,\n              (off_t) tile_offset * self->tile_area * sizeof (uint8_t),\n              SEEK_SET);\n  g_assert (return_code == 0);\n  clearerr (self->tile_file);\n  size_t read_count = fread (tile_address, sizeof (uint8_t), self->tile_area,\n                             self->tile_file);\n  if ( read_count < self->tile_area ) {\n    if ( ferror (self->tile_file) ) {\n      perror (\"error reading tile cache file\");\n      g_assert_not_reached ();\n    }\n    if ( feof (self->tile_file) ) {\n      fprintf (stderr,\n               \"nothing left to read in tile cache file at offset %lld\\n\",\n               FTELL64 (self->tile_file));\n      g_assert_not_reached ();\n    }\n  }\n  g_assert (read_count == self->tile_area);\n\n  return tile_address;\n}\n\nuint8_t\nuint8_image_get_pixel (UInt8Image *self, ssize_t x, ssize_t y)\n{\n  // Are we at a valid image pixel?\n  g_assert (x >= 0 && (size_t) x < self->size_x);\n  g_assert (y >= 0 && (size_t) y < self->size_y);\n\n  // Get the pixel coordinates, including tile and pixel-in-tile.\n  g_assert (sizeof (long int) >= sizeof (size_t));\n  ldiv_t pc_x = ldiv (x, self->tile_size), pc_y = ldiv (y, self->tile_size);\n\n  // Offset of tile x, y, where tiles are viewed as pixels normally are.\n  size_t tile_offset = self->tile_count_x * pc_y.quot + pc_x.quot;\n\n  // Address of data for tile containing pixel of interest (may still\n  // have to be loaded from disk cache).\n  uint8_t *tile_address = self->tile_addresses[tile_offset];\n\n  // Load the tile containing the pixel of interest if necessary.\n  if ( G_UNLIKELY (tile_address == NULL) ) {\n    tile_address = load_tile (self, pc_x.quot, pc_y.quot);\n  }\n\n  // Return pixel of interest.\n  return tile_address[self->tile_size * pc_y.rem + pc_x.rem];\n}\n\nvoid\nuint8_image_set_pixel (UInt8Image *self, ssize_t x, ssize_t y, uint8_t value)\n{\n  // Are we at a valid image pixel?\n  g_assert (self != NULL);\n  g_assert (x >= 0 && (size_t) x <= self->size_x);\n  g_assert (y >= 0 && (size_t) y <= self->size_y);\n\n  // Get the pixel coordinates, including tile and pixel-in-tile.\n  g_assert (sizeof (long int) >= sizeof (size_t));\n  ldiv_t pc_x = ldiv (x, self->tile_size), pc_y = ldiv (y, self->tile_size);\n\n  // Offset of tile x, y, where tiles are viewed as pixels normally are.\n  size_t tile_offset = self->tile_count_x * pc_y.quot + pc_x.quot;\n\n  // Address of data for tile containing pixel of interest (may still\n  // have to be loaded from disk cache).\n  uint8_t *tile_address = self->tile_addresses[tile_offset];\n\n  // Load the tile containing the pixel of interest if necessary.\n  if ( G_UNLIKELY (tile_address == NULL) ) {\n    tile_address = load_tile (self, pc_x.quot, pc_y.quot);\n  }\n\n  // Set pixel of interest.\n  tile_address[self->tile_size * pc_y.rem + pc_x.rem] = value;\n}\n\nvoid\nuint8_image_get_region (UInt8Image *self, ssize_t x, ssize_t y, ssize_t size_x,\n                        ssize_t size_y, uint8_t *buffer)\n{\n  g_assert (size_x >= 0);\n  g_assert (x >= 0);\n  g_assert ((size_t) x + (size_t) size_x - 1 < self->size_x);\n  g_assert (size_y >= 0);\n  g_assert (y >= 0);\n  g_assert ((size_t) y + (size_t) size_y - 1 < self->size_y);\n\n  ssize_t ii, jj;               // Index variables.\n  for ( ii = 0 ; ii < size_y ; ii++ ) {\n    for ( jj = 0 ; jj < size_x ; jj++ ) {\n      // We are essentially returning a subimage from the big image.\n      // These are the indicies in the big image (self) of the current\n      // pixel.\n      size_t ix = x + jj, iy = y + ii;\n      buffer[ii * size_x + jj] = uint8_image_get_pixel (self, ix, iy);\n    }\n  }\n}\n\nvoid\nuint8_image_set_region (UInt8Image *self, size_t x, size_t y, size_t size_x,\n                        size_t size_y, uint8_t *buffer)\n{\n  g_assert_not_reached ();      // Stubbed out for now.\n  self = self; x = x; y = y; size_x = size_x, size_y = size_y; buffer = buffer;\n}\n\nvoid\nuint8_image_get_row (UInt8Image *self, size_t row, uint8_t *buffer)\n{\n  uint8_image_get_region (self, 0, row, self->size_x, 1, buffer);\n}\n\nuint8_t\nuint8_image_get_pixel_with_reflection (UInt8Image *self, ssize_t x, ssize_t y)\n{\n  // Carefully clone-and-modified over from float_image.c, but not\n  // tested yet.\n  //g_assert_not_reached ();\n\n  // Reflect at image edges as advertised.\n  if ( x < 0 ) {\n    x = -x;\n  }\n  else if ( (size_t) x >= self->size_x ) {\n    x = self->size_x - 2 - (x - self->size_x);\n  }\n  if ( y < 0 ) {\n    y = -y;\n  }\n  else if ( (size_t) y >= self->size_y ) {\n    y = self->size_y - 2 - (y - self->size_y);\n  }\n\n  return uint8_image_get_pixel (self, x, y);\n}\n\n\nvoid\nuint8_image_statistics (UInt8Image *self, uint8_t *min, uint8_t *max,\n                        double *mean, double *standard_deviation,\n      gboolean use_mask_value, uint8_t mask_value)\n{\n  // Carefully clone-and-modified over from float_image.c, but not\n  // tested yet.\n  //g_assert_not_reached ();\n\n  // Minimum and maximum sample values as integers.\n  int imin = INT_MAX, imax = INT_MIN;\n\n  // Buffer for one row of samples.\n  uint8_t *row_buffer = g_new (uint8_t, self->size_x);\n\n  *mean = 0.0;\n  double s = 0.0;\n\n  size_t sample_count = 0;      // Samples considered so far.\n  size_t ii, jj;\n  // If there is a mask value we are supposed to ignore,\n  if ( use_mask_value ) {\n    // iterate over all pixels, skipping pixels equal to mask value.\n    for ( ii = 0 ; ii < self->size_y ; ii++ ) {\n      asfPercentMeter((double)ii/(double)(self->size_y));\n      uint8_image_get_row (self, ii, row_buffer);\n      for ( jj = 0 ; jj < self->size_x ; jj++ ) {\n        uint8_t cs = row_buffer[jj];   // Current sample.\n        if ( cs == mask_value ) {\n          continue;\n        }\n        if ( G_UNLIKELY (cs < imin) ) { imin = cs; }\n        if ( G_UNLIKELY (cs > imax) ) { imax = cs; }\n        double old_mean = *mean;\n        *mean += (cs - *mean) / (sample_count + 1);\n        s += (cs - old_mean) * (cs - *mean);\n        sample_count++;\n      }\n    }\n    asfPercentMeter(1.0);\n  }\n  else {\n    // There is no mask value to ignore, so we do the same as the\n    // above loop, but without the possible continue statement.\n    for ( ii = 0 ; ii < self->size_y ; ii++ ) {\n      asfPercentMeter((double)ii/(double)(self->size_y));\n      uint8_image_get_row (self, ii, row_buffer);\n      for ( jj = 0 ; jj < self->size_x ; jj++ ) {\n        uint8_t cs = row_buffer[jj];   // Current sample.\n        if ( G_UNLIKELY (cs < imin) ) { imin = cs; }\n        if ( G_UNLIKELY (cs > imax) ) { imax = cs; }\n        double old_mean = *mean;\n        *mean += (cs - *mean) / (sample_count + 1);\n        s += (cs - old_mean) * (cs - *mean);\n        sample_count++;\n      }\n    }\n    asfPercentMeter(1.0);\n  }\n\n  g_free (row_buffer);\n\n  // Verify the new extrema have been found.\n  g_assert (imin != INT_MAX);\n  g_assert (imax != INT_MIN);\n\n  // The new extrema had better be in the range supported by uint8_t.\n  g_assert (imin >= 0);\n  g_assert (imax <= UINT8_MAX);\n\n  *min = imin;\n  *max = imax;\n  *standard_deviation = sqrt (s / (sample_count - 1));\n}\n\nint\nuint8_image_band_statistics (UInt8Image *self, meta_stats *stats,\n                             int line_count, int band_no,\n                             gboolean use_mask_value, uint8_t mask_value)\n{\n  // Carefully cloned-and-modified over from float_image.c, but not\n  // tested yet.\n  //g_assert_not_reached ();\n\n  // Minimum and maximum sample values as integers.\n  int imin = INT_MAX, imax = INT_MIN;\n\n  // Buffer for one row of samples.\n  uint8_t *row_buffer = g_new (uint8_t, self->size_x);\n\n  stats->mean = 0.0;\n  double s = 0.0;\n\n  size_t sample_count = 0;      // Samples considered so far.\n  size_t ii, jj;\n  // If there is a mask value we are supposed to ignore,\n  if ( use_mask_value ) {\n    // iterate over all pixels, skipping pixels equal to mask value.\n    for ( ii = (band_no * line_count); // 0-ordered band number times lines is offset into image\n          ii < (band_no+1) * line_count && ii < self->size_y;\n          ii++ )\n    {\n      asfPercentMeter( (double)(ii - band_no*line_count)/(double)line_count );\n      uint8_image_get_row (self, ii, row_buffer);\n      for ( jj = 0 ; jj < self->size_x ; jj++ ) {\n        uint8_t cs = row_buffer[jj];   // Current sample.\n        if ( cs == mask_value ) {\n          continue;\n        }\n        if ( G_UNLIKELY (cs < imin) ) { imin = cs; }\n        if ( G_UNLIKELY (cs > imax) ) { imax = cs; }\n        double old_mean = stats->mean;\n        stats->mean += (cs - stats->mean) / (sample_count + 1);\n        s += (cs - old_mean) * (cs - stats->mean);\n        sample_count++;\n      }\n    }\n    asfPercentMeter(1.0);\n  }\n  else {\n    // There is no mask value to ignore, so we do the same as the\n    // above loop, but without the possible continue statement.\n    for ( ii = (band_no * line_count); // 0-ordered band number times lines is offset into image\n          ii < (band_no+1) * line_count && ii < self->size_y;\n          ii++ )\n    {\n      asfPercentMeter( (double)(ii - band_no*line_count)/(double)line_count );\n      uint8_image_get_row (self, ii, row_buffer);\n      for ( jj = 0 ; jj < self->size_x ; jj++ ) {\n        uint8_t cs = row_buffer[jj];   // Current sample.\n        if ( G_UNLIKELY (cs < imin) ) { imin = cs; }\n        if ( G_UNLIKELY (cs > imax) ) { imax = cs; }\n        double old_mean = stats->mean;\n        stats->mean += (cs - stats->mean) / (sample_count + 1);\n        s += (cs - old_mean) * (cs - stats->mean);\n        sample_count++;\n      }\n    }\n    asfPercentMeter(1.0);\n  }\n\n  g_free (row_buffer);\n\n  // Verify the new extrema have been found.\n  if (imin == INT_MAX || imax == INT_MIN)\n    return 1;\n\n  // The new extrema had better be in the range supported by uint8_t.\n  if (imin < 0 || imax > UINT8_MAX)\n    return 1;\n\n  stats->min = imin;\n  stats->max = imax;\n  stats->std_deviation = sqrt (s / (sample_count - 1));\n\n  return 0;\n}\n\nvoid\nuint8_image_statistics_with_mask_interval (UInt8Image *self, uint8_t *min,\n             uint8_t *max, double *mean,\n             double *standard_deviation,\n             uint8_t interval_start,\n             uint8_t interval_end)\n{\n  // This method is a trivial clone-and-modify of\n  // float_image_statistics, but it is totally untested at the moment.\n  g_assert_not_reached ();\n\n  // Minimum and maximum sample values as integers.\n  int imin = INT_MAX, imax = INT_MIN;\n\n  // Buffer for one row of samples.\n  uint8_t *row_buffer = g_new (uint8_t, self->size_x);\n\n  *mean = 0.0;\n  double s = 0.0;\n\n  size_t sample_count = 0;      // Samples considered so far.\n  size_t ii, jj;\n  for ( ii = 0 ; ii < self->size_y ; ii++ ) {\n    uint8_image_get_row (self, ii, row_buffer);\n    for ( jj = 0 ; jj < self->size_x ; jj++ ) {\n      uint8_t cs = row_buffer[jj];   // Current sample.\n      // If in the mask interval, do not consider this pixel any\n      // further.\n      if ( cs >= interval_start && cs <= interval_end ) {\n  continue;\n      }\n      if ( G_UNLIKELY (cs < imin) ) { imin = cs; }\n      if ( G_UNLIKELY (cs > imax) ) { imax = cs; }\n      double old_mean = *mean;\n      *mean += (cs - *mean) / (sample_count + 1);\n      s += (cs - old_mean) * (cs - *mean);\n      sample_count++;\n    }\n  }\n\n  g_free (row_buffer);\n\n  // Verify the new extrema have been found.\n  g_assert (imin != INT_MAX);\n  g_assert (imax != INT_MIN);\n\n  // The new extrema had better be in the range supported by uint8_t.\n  g_assert (imin >= 0);\n  g_assert (imax <= UINT8_MAX);\n\n  *min = imin;\n  *max = imax;\n  *standard_deviation = sqrt (s / (sample_count - 1));\n}\n\nvoid\nuint8_image_approximate_statistics (UInt8Image *self, size_t stride,\n                                    double *mean, double *standard_deviation,\n            gboolean use_mask_value,\n            uint8_t mask_value)\n{\n  // Rows and columns of samples that fit in image given stride\n  // stride.\n  size_t sample_columns = ceil (self->size_x / stride);\n  size_t sample_rows = ceil (self->size_y / stride);\n  // Total number of samples.\n  size_t sample_count = sample_columns * sample_rows;\n\n  // Create an image holding the sample values.\n  UInt8Image *sample_image = uint8_image_new (sample_columns, sample_rows);\n\n  // Load the sample values.\n  size_t current_sample = 0;\n  size_t ii;\n  for ( ii = 0 ; ii < sample_columns ; ii++ ) {\n    size_t jj;\n    for ( jj = 0 ; jj < sample_rows ; jj++ ) {\n      uint8_t sample = uint8_image_get_pixel (self, ii * stride, jj * stride);\n      uint8_image_set_pixel (sample_image, ii, jj, sample);\n      current_sample++;\n    }\n  }\n\n  // Ensure that we got the right number of samples in our image.\n  g_assert (current_sample == sample_count);\n\n  // Compute the exact statistics of the sampled version of the image.\n  // The _statistics method wants to compute min and max, so we let\n  // it, even though we don't do anything with them (since they are\n  // inaccurate).\n  uint8_t min, max;\n  uint8_image_statistics (sample_image, &min, &max, mean, standard_deviation,\n                          use_mask_value, mask_value);\n\n  uint8_image_free (sample_image);\n}\n\nvoid\nuint8_image_approximate_statistics_with_mask_interval\n  (UInt8Image *self, size_t stride, double *mean, double *standard_deviation,\n   uint8_t interval_start, uint8_t interval_end)\n{\n  // This method is a trivial clone-and-modify of\n  // float_image_approximate_statistics, but it is totally untested at\n  // the moment.\n  g_assert_not_reached ();\n\n  // Rows and columns of samples that fit in image given stride\n  // stride.\n  size_t sample_columns = ceil (self->size_x / stride);\n  size_t sample_rows = ceil (self->size_y / stride);\n  // Total number of samples.\n  size_t sample_count = sample_columns * sample_rows;\n\n  // Create an image holding the sample values.\n  UInt8Image *sample_image = uint8_image_new (sample_columns, sample_rows);\n\n  // Load the sample values.\n  size_t current_sample = 0;\n  size_t ii;\n  for ( ii = 0 ; ii < sample_columns ; ii++ ) {\n    size_t jj;\n    for ( jj = 0 ; jj < sample_rows ; jj++ ) {\n      uint8_t sample = uint8_image_get_pixel (self, ii * stride, jj * stride);\n      uint8_image_set_pixel (sample_image, ii, jj, sample);\n      current_sample++;\n    }\n  }\n\n  // Ensure that we got the right number of samples in our image.\n  g_assert (current_sample == sample_count);\n\n  // Compute the exact statistics of the sampled version of the image.\n  // The _statistics method wants to compute min and max, so we let\n  // it, even though we don't do anything with them (since they are\n  // inaccurate).\n  uint8_t min, max;\n  uint8_image_statistics_with_mask_interval (sample_image, &min, &max,\n               mean, standard_deviation,\n               interval_start, interval_end);\n\n  uint8_image_free (sample_image);\n}\n\ngsl_histogram *\nuint8_image_gsl_histogram (UInt8Image *self, double min, double max,\n                           size_t bin_count)\n{\n  // Carefully clone-and-modified over from float_image.c, but not\n  // tested yet.\n  g_assert_not_reached ();\n\n  // Initialize the histogram.\n  gsl_histogram *histogram = gsl_histogram_alloc (bin_count);\n  gsl_histogram_set_ranges_uniform (histogram, min, max);\n\n  // Buffer for one row of samples.\n  uint8_t *row_buffer = g_new (uint8_t, self->size_x);\n\n  // Populate the histogram over every sample in the image.\n  size_t ii, jj;\n  for (ii = 0 ; ii < self->size_y ; ii++ ) {\n    uint8_image_get_row (self, ii, row_buffer);\n    for ( jj = 0 ; jj < self->size_x ; jj++ ) {\n      gsl_histogram_increment (histogram, row_buffer[jj]);\n    }\n  }\n\n  g_free (row_buffer);\n\n  return histogram;\n}\n\n\ndouble\nuint8_image_apply_kernel (UInt8Image *self, ssize_t x, ssize_t y,\n        gsl_matrix *kern)\n{\n  // Carefully clone-and-modified over from float_image.c, but not\n  // tested yet.\n  g_assert_not_reached ();\n\n  g_assert (x >= 0 && (size_t) x < self->size_x);\n  g_assert (y >= 0 && (size_t) y < self->size_y);\n  g_assert (kern->size2 % 2 == 1);\n  g_assert (kern->size2 == kern->size1);\n\n  size_t ks = kern->size2;    // Kernel size.\n\n  double sum = 0;                // Result.\n\n  size_t ii;\n  for ( ii = 0 ; ii < kern->size1 ; ii++ ) {\n    ssize_t iy = y - ks / 2 + ii; // Current image y pixel index.\n    size_t jj;\n    for ( jj = 0 ; jj < kern->size2 ; jj++ ) {\n      ssize_t ix = x - ks / 2 + jj; // Current image x pixel index\n      sum += (gsl_matrix_get (kern, jj, ii)\n              * uint8_image_get_pixel_with_reflection (self, ix, iy));\n    }\n  }\n\n  return sum;\n}\n\ndouble\nuint8_image_sample (UInt8Image *self, double x, double y,\n                    uint8_image_sample_method_t sample_method)\n{\n  g_assert (x >= 0.0 && x <= (double) self->size_x - 1.0);\n  g_assert (y >= 0.0 && y <= (double) self->size_y - 1.0);\n\n  switch ( sample_method ) {\n\n  case UINT8_IMAGE_SAMPLE_METHOD_NEAREST_NEIGHBOR:\n    return uint8_image_get_pixel (self, round (x), round (y));\n    break;\n\n  case UINT8_IMAGE_SAMPLE_METHOD_BILINEAR:\n    {\n      // Indicies of points we are interpolating between (x below, y\n      // below, etc., where below is interpreted in the numerical\n      // sense, not the image orientation sense.).\n      size_t xb = floor (x), yb = floor (y), xa = ceil (x), ya = ceil (y);\n      size_t ts = self->tile_size;   // Convenience alias.\n      // Offset of xb, yb, etc. relative to tiles they lie in.\n      size_t xbto = xb % ts, ybto = yb % ts, xato = xa % ts, yato = ya % ts;\n      // Values of points we are interpolating between.\n      uint8_t ul, ur, ll, lr;\n\n      // If the points were are interpolating between don't span a\n      // tile edge, we load them straight from tile memory to save\n      // some time.\n      if ( G_LIKELY (   xbto != ts - 1 && xato != 0\n                     && ybto != ts - 1 && yato != 0) ) {\n        // The tile indicies.\n        size_t tx = xb / ts, ty = yb / ts;\n        // Tile offset in flattened list of tile addresses.\n        size_t tile_offset = ty * self->tile_count_x + tx;\n        uint8_t *tile_address = self->tile_addresses[tile_offset];\n        if ( G_UNLIKELY (tile_address == NULL) ) {\n          tile_address = load_tile (self, tx, ty);\n        }\n        ul = tile_address[ybto * self->tile_size + xbto];\n        ur = tile_address[ybto * self->tile_size + xato];\n        ll = tile_address[yato * self->tile_size + xbto];\n        lr = tile_address[yato * self->tile_size + xato];\n      }\n      else {\n        // We are spanning a tile edge, so we just get the pixels\n        // using the inefficient but easy get_pixel method.\n        ul = uint8_image_get_pixel (self, floor (x), floor (y));\n        ur = uint8_image_get_pixel (self, ceil (x), floor (y));\n        ll = uint8_image_get_pixel (self, floor (x), ceil (y));\n        lr = uint8_image_get_pixel (self, ceil (x), ceil (y));\n      }\n\n      // Upper and lower values interpolated in the x direction.\n      double ux = ul + (ur - ul) * (x - floor (x));\n      double lx = ll + (lr - ll) * (x - floor (x));\n\n      return ux + (lx - ux) * (y - floor (y));\n    }\n    break;\n  case UINT8_IMAGE_SAMPLE_METHOD_BICUBIC:\n    {\n      // Should never be here ...bicubic resampling can result in negative\n      // values and should not be used for resampling unsigned values...\n      //g_assert_not_reached ();\n      asfPrintError (\"BICUBIC resampling for BYTE data is not supported.\\n\");\n\n      static gboolean first_time_through = TRUE;\n      // Splines in the x direction, and their lookup accelerators.\n      static double *x_indicies;\n      static double *values;\n      static gsl_spline **xss;\n      static gsl_interp_accel **xias;\n      // Spline between splines in the y direction, and lookup accelerator.\n      static double *y_spline_indicies;\n      static double *y_spline_values;\n      static gsl_spline *ys;\n      static gsl_interp_accel *yia;\n\n      // All these splines have size 4.\n      const size_t ss = 4;\n\n      size_t ii;                // Index variable.\n\n      if ( first_time_through ) {\n        // Allocate memory for the splines in the x direction.\n        x_indicies = g_new (double, ss);\n        values = g_new (double, ss);\n        xss = g_new (gsl_spline *, ss);\n        xias = g_new (gsl_interp_accel *, ss);\n        for ( ii = 0 ; ii < ss ; ii++ ) {\n          xss[ii] = gsl_spline_alloc (gsl_interp_cspline, ss);\n          xias[ii] = gsl_interp_accel_alloc ();\n        }\n\n        // Allocate memory for the spline in the y direction.\n        y_spline_indicies = g_new (double, ss);\n        y_spline_values = g_new (double, ss);\n        ys = gsl_spline_alloc (gsl_interp_cspline, ss);\n        yia = gsl_interp_accel_alloc ();\n        first_time_through = FALSE;\n      }\n\n      // Get the values for the nearest 16 points.\n      size_t jj;                // Index variable.\n      for ( ii = 0 ; ii < ss ; ii++ ) {\n        for ( jj = 0 ; jj < ss ; jj++ ) {\n          x_indicies[jj] = floor (x) - 1 + jj;\n          values[jj]\n            = uint8_image_get_pixel_with_reflection (self, x_indicies[jj],\n                                                     floor (y) - 1 + ii);\n        }\n        gsl_spline_init (xss[ii], x_indicies, values, ss);\n      }\n\n      // Set up the spline that runs in the y direction.\n      for ( ii = 0 ; ii < ss ; ii++ ) {\n        y_spline_indicies[ii] = floor (y) - 1 + ii;\n        y_spline_values[ii] = gsl_spline_eval (xss[ii], x, xias[ii]);\n      }\n      gsl_spline_init (ys, y_spline_indicies, y_spline_values, ss);\n\n      double ret_val = gsl_spline_eval (ys, y, yia);\n// NOTE... NOTE... BICUBIC resample returns negative values if the byte values are\n// too close to zero and the spline fit goes negative in the neighborhood of the pixel\n/*\n      if (ret_val > 255.0 || ret_val < 0.0) {\n        asfPrintWarning(\"Bicubic resampling of BYTE data returned out of range value (%f).\\n\"\n          \"...Continuing, but negative values will be forced to zero, and values above 255\\n\"\n          \" will be forced to 255\\n\",\n          ret_val);\n        if (ret_val > 265.0) {\n          asfPrintError(\"Bicubic resampling of BYTE data returned a value (%f) too far above 255.0 to\\n\"\n            \"cap to 255.0\\n\", ret_val);\n        }\n        if (ret_val < -10.0) {\n          asfPrintError(\"Bicubic resampling of BYTE data returned a value (%f) too far below 0.0 to\\n\"\n            \"cap to 0.0\\n\", ret_val);\n        }\n        ret_val = ret_val < 0.0 ? 0.0 : ret_val;\n        ret_val = ret_val > 255.0 ? 255.0 : ret_val;\n      }\n*/\n      return ret_val;\n    }\n    break;\n  default:\n    g_assert_not_reached ();\n    return -42;         // Reassure the compiler.\n  }\n}\n\ngboolean\nuint8_image_equals (UInt8Image *self, UInt8Image *other)\n{\n  // Compare image sizes.\n  if ( self->size_x != other->size_x ) {\n    return FALSE;\n  }\n  if ( self->size_y != other->size_y ) {\n    return FALSE;\n  }\n\n  size_t sz = self->size_x; // Convenience alias.\n\n  // Compare image pixels.\n  size_t ii, jj;\n  for ( ii = 0 ; ii < sz ; ii++ ) {\n    for ( jj = 0 ; jj < sz ; jj++ ) {\n      if ( G_UNLIKELY (uint8_image_get_pixel (self, jj, ii)\n           != uint8_image_get_pixel (other, jj, ii)) ) {\n  return FALSE;\n      }\n    }\n  }\n\n  return TRUE;\n}\n\n// Flip an image about a horizontal line through the center of the image\nvoid\nuint8_image_flip_y(UInt8Image *self)\n{\n  size_t ii, jj;\n\n  asfLineMeter(jj, self->size_y);\n  for (jj = 0; jj < self->size_y / 2; ++jj) {\n    asfLineMeter(2 * jj + 1, self->size_y);\n    size_t jj2 = self->size_y - 1 - jj;\n    for (ii = 0; ii < self->size_x; ++ii) {\n      uint8 a = uint8_image_get_pixel(self, ii, jj);\n      uint8 b = uint8_image_get_pixel(self, ii, jj2);\n      uint8_image_set_pixel(self, ii, jj, b);\n      uint8_image_set_pixel(self, ii, jj2, a);\n    }\n  }\n  asfLineMeter(1, 1);\n}\n\n// Flip an image about a vertical line through the center of the image\nvoid\nuint8_image_flip_x(UInt8Image *self)\n{\n  size_t ii, jj;\n\n  for (ii = 0; ii < self->size_x / 2; ++ii) {\n    asfLineMeter(2 * ii + 1, self->size_y);\n    size_t ii2 = self->size_x - 1 - ii;\n    for (jj = 0; jj < self->size_y; ++jj) {\n      uint8 a = uint8_image_get_pixel(self, ii, jj);\n      uint8 b = uint8_image_get_pixel(self, ii2, jj);\n      uint8_image_set_pixel(self, ii, jj, b);\n      uint8_image_set_pixel(self, ii2, jj, a);\n    }\n  }\n  asfLineMeter(1, 1);\n}\n\n// Bring the tile cache file on the disk fully into sync with the\n// latest image data stored in the memory cache.\nstatic void\nsynchronize_tile_file_with_memory_cache (UInt8Image *self)\n{\n  // If we aren't using a tile file, this operation doesn't make\n  // sense.\n  g_assert (self->tile_file != NULL);\n\n  guint ii;\n  for ( ii = 0 ; ii < self->tile_queue->length ; ii++ ) {\n    size_t tile_offset = GPOINTER_TO_INT (g_queue_peek_nth (self->tile_queue,\n                  ii));\n    cached_tile_to_disk (self, tile_offset);\n  }\n}\n\nvoid\nuint8_image_freeze (UInt8Image *self, FILE *file_pointer)\n{\n  FILE *fp = file_pointer;  // Convenience alias.\n\n  g_assert (file_pointer != NULL);\n\n  size_t write_count = fwrite (&(self->size_x), sizeof (size_t), 1, fp);\n  g_assert (write_count == 1);\n\n  write_count = fwrite (&(self->size_y), sizeof (size_t), 1, fp);\n  g_assert (write_count == 1);\n\n  write_count = fwrite (&(self->cache_space), sizeof (size_t), 1, fp);\n  g_assert (write_count == 1);\n\n  write_count = fwrite (&(self->cache_area), sizeof (size_t), 1, fp);\n  g_assert (write_count == 1);\n\n  write_count = fwrite (&(self->tile_size), sizeof (size_t), 1, fp);\n  g_assert (write_count == 1);\n\n  write_count = fwrite (&(self->cache_size_in_tiles), sizeof (size_t), 1, fp);\n  g_assert (write_count == 1);\n\n  write_count = fwrite (&(self->tile_count_x), sizeof (size_t), 1, fp);\n  g_assert (write_count == 1);\n\n  write_count = fwrite (&(self->tile_count_y), sizeof (size_t), 1, fp);\n  g_assert (write_count == 1);\n\n  write_count = fwrite (&(self->tile_count), sizeof (size_t), 1, fp);\n  g_assert (write_count == 1);\n\n  write_count = fwrite (&(self->tile_area), sizeof (size_t), 1, fp);\n  g_assert (write_count == 1);\n\n  // We don't bother serializing the cache -- its a pain to keep track\n  // of and probably almost never worth it.\n\n  // We write the tile queue pointer away, so that when we later thaw\n  // the serialized version, we can tell if a cache file is in use or\n  // not (if it isn't tile_queue will be NULL).\n  write_count = fwrite (&(self->tile_queue), sizeof (GQueue *), 1, fp);\n  g_assert (write_count == 1);\n\n  // If there was no cache file...\n  if ( self->tile_queue == NULL ) {\n    // We store the contents of the first tile and are done.\n    write_count = fwrite (self->tile_addresses[0], sizeof (uint8_t),\n        self->tile_area, fp);\n    if ( write_count < self->tile_area ) {\n      if ( ferror (fp) ) {\n  fprintf (stderr, \"Error writing serialized UInt8Image instance during \"\n     \"freeze: %s\\n\", strerror (errno));\n  exit (EXIT_FAILURE);\n      }\n    }\n    g_assert (write_count == self->tile_area);\n  }\n  // otherwise, the in memory cache needs to be copied into the tile\n  // file and the tile file saved in the serialized version of self.\n  else {\n    synchronize_tile_file_with_memory_cache (self);\n    uint8_t *buffer = g_new (uint8_t, self->tile_area);\n    size_t ii;\n    off_t tmp = FTELL64 (self->tile_file);\n    int return_code = FSEEK64 (self->tile_file, 0, SEEK_SET);\n    g_assert (return_code == 0);\n    for ( ii = 0 ; ii < self->tile_count ; ii++ ) {\n      size_t read_count = fread (buffer, sizeof (uint8_t), self->tile_area,\n         self->tile_file);\n      g_assert (read_count == self->tile_area);\n      write_count = fwrite (buffer, sizeof (uint8_t), self->tile_area, fp);\n      g_assert (write_count == self->tile_area);\n    }\n    return_code = FSEEK64 (self->tile_file, tmp, SEEK_SET);\n    g_assert (return_code == 0);\n    g_free (buffer);\n  }\n}\n\nint\nuint8_image_band_store(UInt8Image *self, const char *file,\n           meta_parameters *meta, int append_flag)\n{\n  // Give status\n  if (meta->general->band_count == 1)\n    asfPrintStatus(\"\\n\\nStoring image ...\\n\");\n  else\n    asfPrintStatus(\"\\n\\nStoring band ...\\n\");\n\n  // Open the file to write to.\n  FILE *fp = fopen (file, append_flag ? \"ab\" : \"wb\");\n  // FIXME: we need some error handling and propagation here.\n  g_assert (fp != NULL);\n\n  // We will write the image data in horizontal stips one line at a time.\n  uint8_t *line_buffer = g_new (uint8_t, self->size_x);\n\n  // Sanity check\n  if (meta->general->line_count != (int)self->size_y ||\n      meta->general->sample_count != (int)self->size_x)\n  {\n      asfPrintError(\"Inconsistency between metadata and image!\\n\"\n                    \"Metadata says: %dx%d LxS, image has %dx%d\\n\"\n                    \"Possibly did not write metadata before storing image.\\n\",\n                    meta->general->line_count, meta->general->sample_count,\n                    self->size_y, self->size_x);\n  }\n\n  // Reorganize data into tiles in tile oriented disk file.\n  int ii;\n  for ( ii = 0 ; ii < (int)self->size_y ; ii++ ) {\n    uint8_image_get_row (self, ii, line_buffer);\n\n    size_t write_count =\n      fwrite(line_buffer, sizeof(uint8_t), self->size_x, fp);\n\n    if (write_count < self->size_x) {\n      // it must have been a write error (no space left, possibly)\n      g_assert(ferror(self->tile_file));\n      // so print an error message\n      fprintf(stderr, \"Error writing file %s: %s\\n\", file, strerror(errno));\n      // and exit\n      exit (EXIT_FAILURE);\n    }\n\n    g_assert(write_count == self->size_x);\n  }\n\n  // Done with the line buffer.\n  g_free (line_buffer);\n\n  // Close file being written.\n  int return_code = fclose (fp);\n  g_assert (return_code == 0);\n\n  // Return success code.\n  return 0;\n}\n\nint\nuint8_image_store (UInt8Image *self, const char *file)\n{\n  meta_parameters *meta;\n  meta = meta_read(file);\n\n  int ret = uint8_image_band_store(self, file, meta, 0);\n  meta_free(meta);\n\n  return ret;\n}\n\nint\nuint8_image_export_as_jpeg (UInt8Image *self, const char *file,\n                            size_t max_dimension, gboolean use_mask_value,\n          uint8_t mask_value)\n{\n  // Carefully clone-and-modified over from float_image.c, but not\n  // tested yet.\n  g_assert_not_reached ();\n\n  size_t scale_factor;          // Scale factor to use for output image.\n  if ( self->size_x > self->size_y ) {\n    scale_factor = ceil ((double) self->size_x / max_dimension);\n  }\n  else {\n    scale_factor = ceil ((double) self->size_y / max_dimension);\n  }\n\n  // We want the scale factor to be odd, so that we can easily use a\n  // standard kernel to average things.\n  if ( scale_factor % 2 == 0 ) {\n    scale_factor++;\n  }\n\n  // Output JPEG x and y dimensions.\n  size_t osx = self->size_x / scale_factor;\n  size_t osy = self->size_y / scale_factor;\n\n  // Number of pixels in output image.\n  size_t pixel_count = osx * osy;\n\n  // Pixels of the output image.\n  unsigned char *pixels = g_new (unsigned char, pixel_count);\n\n  JSAMPLE test_jsample;         // For verifying properties of JSAMPLE type.\n  /* Here are some very funky checks to try to ensure that the JSAMPLE\n     really is the type we expect, so we can scale properly.  */\n  g_assert (sizeof (unsigned char) == 1);\n  g_assert (sizeof (unsigned char) == sizeof (JSAMPLE));\n  test_jsample = 0;\n  test_jsample--;\n  g_assert (test_jsample == UCHAR_MAX);\n\n  // Stuff needed by libjpeg.\n  struct jpeg_compress_struct cinfo;\n  struct jpeg_error_mgr jerr;\n  cinfo.err = jpeg_std_error (&jerr);\n  jpeg_create_compress (&cinfo);\n\n  // Open output file.\n  FILE *fp = fopen (file, \"wb\");\n  if ( fp == NULL ) { perror (\"error opening file\"); }\n  // FIXME: we need some error handling and propagation here.\n  g_assert (fp != NULL);\n\n  // Connect jpeg output to the output file to be used.\n  jpeg_stdio_dest (&cinfo, fp);\n\n  // Set image parameters that libjpeg needs to know about.\n  cinfo.image_width = osx;\n  cinfo.image_height = osy;\n  cinfo.input_components = 1;   // Grey scale => 1 color component / pixel.\n  cinfo.in_color_space = JCS_GRAYSCALE;\n  jpeg_set_defaults (&cinfo);   // Use default compression parameters.\n  // Reassure libjpeg that we will be writing a complete JPEG file.\n  jpeg_start_compress (&cinfo, TRUE);\n\n  // As advertised, we will average pixels together.\n  g_assert (scale_factor % 2 != 0);\n  size_t kernel_size = scale_factor;\n  gsl_matrix *averaging_kernel\n    = gsl_matrix_alloc (kernel_size, kernel_size);\n  double kernel_value = 1.0 / ((double)kernel_size * kernel_size);\n  size_t ii, jj;                // Index values.\n  for ( ii = 0 ; ii < averaging_kernel->size1 ; ii++ ) {\n    for ( jj = 0 ; jj < averaging_kernel->size2 ; jj++ ) {\n      gsl_matrix_set (averaging_kernel, ii, jj, kernel_value);\n    }\n  }\n\n  // Sample input image, putting scaled results into output image.\n  size_t sample_stride = scale_factor;\n  for ( ii = 0 ; ii < osy ; ii++ ) {\n    for ( jj = 0 ; jj < osx ; jj++ ) {\n      // Input image average pixel value.\n      double ival = uint8_image_apply_kernel (self, jj * sample_stride,\n                ii * sample_stride,\n                averaging_kernel);\n      // Set output value.\n      int32_t oval = round (ival);\n      // In case floating point arithmetic wierdness gets us in\n      // trouble, we correct.\n      if ( oval < 0 ) {\n  oval = 0;\n      }\n      else if ( oval > UINT8_MAX ) {\n  oval = UINT8_MAX;\n      }\n      pixels[ii * osx + jj] = oval;\n    }\n  }\n\n  // Write the jpeg, one row at a time.\n  const int rows_to_write = 1;\n  JSAMPROW *row_pointer = g_new (JSAMPROW, rows_to_write);\n  while ( cinfo.next_scanline < cinfo.image_height ) {\n    int rows_written;\n    row_pointer[0] = &(pixels[cinfo.next_scanline * osx]);\n    rows_written = jpeg_write_scanlines (&cinfo, row_pointer, rows_to_write);\n    g_assert (rows_written == rows_to_write);\n  }\n  g_free (row_pointer);\n\n  // Finsh compression and close the jpeg.\n  jpeg_finish_compress (&cinfo);\n  int return_code = fclose (fp);\n  g_assert (return_code == 0);\n  jpeg_destroy_compress (&cinfo);\n\n  g_free (pixels);\n\n  return 0;                     // Return success indicator.\n}\n\nsize_t\nuint8_image_get_cache_size (UInt8Image *self)\n{\n  g_assert_not_reached ();      // Stubbed out for now.\n  // Compiler reassurance.\n  self = self;\n  return 0;\n}\n\nvoid\nuint8_image_set_cache_size (UInt8Image *self, size_t size)\n{\n  g_assert_not_reached ();      // Stubbed out for now.\n  // Compiler reassurance.\n  self = self; size = size;\n}\n\nvoid\nuint8_image_free (UInt8Image *self)\n{\n  // Close the tile file (which shouldn't have to remove it since its\n  // already unlinked), if we were ever using it.\n  if ( self->tile_file != NULL ) {\n    int return_code = fclose (self->tile_file);\n    g_assert (return_code == 0);\n  }\n\n  // Deallocate dynamic memory.\n\n  g_free (self->tile_addresses);\n\n  // If we didn't need a tile file, we also won't have a tile queue.\n  if ( self->tile_queue != NULL ) {\n    g_queue_free (self->tile_queue);\n  }\n\n  g_free (self->cache);\n\n  if (self->tile_file_name) {\n#ifdef win32\n     unlink_tmp_file(self->tile_file_name->str);\n     g_string_free(self->tile_file_name, TRUE);\n#endif\n  }\n\n  g_free (self);\n}\n", "meta": {"hexsha": "3e3cf7a2f48c8061b191c7e5f979029023c37096", "size": 74367, "ext": "c", "lang": "C", "max_stars_repo_path": "src/libasf_raster/uint8_image.c", "max_stars_repo_name": "glshort/MapReady", "max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z", "max_issues_repo_path": "src/libasf_raster/uint8_image.c", "max_issues_repo_name": "glshort/MapReady", "max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libasf_raster/uint8_image.c", "max_forks_repo_name": "glshort/MapReady", "max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z", "avg_line_length": 34.2705069124, "max_line_length": 104, "alphanum_fraction": 0.6358734385, "num_tokens": 20383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.13846180123433283, "lm_q2_score": 0.015189046634741674, "lm_q1q2_score": 0.0021031027560786137}}
{"text": "#pragma once\n\n#include <gsl\\gsl>\n#include \"Texture.h\"\n#include \"Rectangle.h\"\n\nnamespace Library\n{\n\tclass Texture2D final : public Texture\n\t{\n\t\tRTTI_DECLARATIONS(Texture2D, Texture)\n\n\tpublic:\n\t\tTexture2D(const winrt::com_ptr<ID3D11ShaderResourceView>& shaderResourceView, std::uint32_t width, std::uint32_t height);\n\t\tTexture2D(const Texture2D&) = default;\n\t\tTexture2D& operator=(const Texture2D&) = default;\n\t\tTexture2D(Texture2D&&) = default;\n\t\tTexture2D& operator=(Texture2D&&) = default;\n\t\t~Texture2D() = default;\n\n\t\tstatic std::shared_ptr<Texture2D> CreateTexture2D(gsl::not_null<ID3D11Device*> device, const D3D11_TEXTURE2D_DESC& textureDesc);\n\t\tstatic std::shared_ptr<Texture2D> CreateTexture2D(gsl::not_null<ID3D11Device*> device, std::uint32_t width, std::uint32_t height, std::uint32_t mipLevels = 1, std::uint32_t arraySize = 1, DXGI_FORMAT format = DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC sampleDesc = { 1, 0 }, std::uint32_t bindFlags = D3D11_BIND_UNORDERED_ACCESS | D3D11_BIND_SHADER_RESOURCE, std::uint32_t cpuAccessFlags = 0);\n\n\t\tstd::uint32_t Width() const;\n\t\tstd::uint32_t Height() const;\n\t\tRectangle Bounds() const;\n\n\tprivate:\n\t\tstd::uint32_t mWidth;\n\t\tstd::uint32_t mHeight;\n\t};\n}", "meta": {"hexsha": "5d472f0eba5306e42dca6985b7d72803e4a8f852", "size": 1204, "ext": "h", "lang": "C", "max_stars_repo_path": "source/Library.Shared/Texture2D.h", "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/Library.Shared/Texture2D.h", "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/Library.Shared/Texture2D.h", "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.625, "max_line_length": 397, "alphanum_fraction": 0.7599667774, "num_tokens": 371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1384617905689644, "lm_q2_score": 0.01518904610536219, "lm_q1q2_score": 0.002103102520783004}}
{"text": "#pragma once\n\n#include <gsl.h>\n\n#include <mitkPythonService.h>\n#include \"PythonSolverSetupServiceActivator.h\"\n\nnamespace crimson\n{\n\ninline QVariant getClassVariable(PythonQtObjectPtr obj, QString variableName)\n{\n    return PythonQtObjectPtr{obj.getVariable(\"__class__\")}.getVariable(variableName);\n}\n\ninline PythonQtObjectPtr clonePythonObject(PythonQtObjectPtr object)\n{\n    Expects(!object.isNull());\n\n    auto pythonService = PythonSolverSetupServiceActivator::getPythonService();\n    pythonService->Execute(\"import copy\");\n\n    auto result = PythonQtObjectPtr{\n        pythonService->GetPythonManager()->mainContext().call(\"copy.deepcopy\", QVariantList{QVariant::fromValue(object)})};\n\n    Ensures(!result.isNull());\n    return result;\n}\n} // namespace crimson", "meta": {"hexsha": "8afba3cf219738cd8af5480fa1d16bba4d3eee73", "size": 764, "ext": "h", "lang": "C", "max_stars_repo_path": "Modules/PythonSolverSetupService/src/SolverSetupPythonUtils.h", "max_stars_repo_name": "carthurs/CRIMSONGUI", "max_stars_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-09-17T18:55:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T02:52:38.000Z", "max_issues_repo_path": "Modules/PythonSolverSetupService/src/SolverSetupPythonUtils.h", "max_issues_repo_name": "carthurs/CRIMSONGUI", "max_issues_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Modules/PythonSolverSetupService/src/SolverSetupPythonUtils.h", "max_forks_repo_name": "carthurs/CRIMSONGUI", "max_forks_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-05-19T09:02:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-26T17:39:57.000Z", "avg_line_length": 26.3448275862, "max_line_length": 123, "alphanum_fraction": 0.7643979058, "num_tokens": 168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09138210306717136, "lm_q2_score": 0.022977368488305956, "lm_q1q2_score": 0.00209972025541075}}
{"text": "/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */\n/*\n *     Copyright 2016 Couchbase, Inc\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n */\n/** \\file\n * This file is internal to the inner workings of\n * Phosphor and is not intended for public consumption.\n */\n\n#pragma once\n\n#include <array>\n#include <iterator>\n#include <memory>\n#include <thread>\n#include <type_traits>\n#include <vector>\n#include <functional>\n\n#include <gsl_p/iterator.h>\n\n#include \"phosphor/platform/core.h\"\n#include \"trace_event.h\"\n\nnamespace phosphor {\n\n#ifndef PHOSPHOR_CHUNK_PAGE_COUNT\n#define PHOSPHOR_CHUNK_PAGE_COUNT 1\n#endif\n\n    /**\n     * TraceChunk represents an array of TraceEvents\n     *\n     * The TraceChunk should be used from a single thread to\n     * store various events.\n     */\n    class PHOSPHOR_API TraceChunk {\n    public:\n        static constexpr auto chunk_page_count = PHOSPHOR_CHUNK_PAGE_COUNT;\n        static constexpr auto page_size = 4096;\n        static constexpr auto array_offset = 64;\n        static constexpr auto chunk_size =\n            (((page_size * chunk_page_count) - array_offset) /\n             sizeof(TraceEvent));\n        using event_array = std::array<TraceEvent, chunk_size>;\n\n        using const_iterator = event_array::const_iterator;\n\n        /**\n         * Constructor for a TraceChunk\n         */\n        TraceChunk() = default;\n\n        /**\n         * Reset the state of the TraceChunk\n         *\n         * This should be called before the TraceChunk is first used\n         * as TraceChunk is a trivial type and requires initialisation.\n         */\n        void reset();\n\n        /**\n         * Used for adding TraceEvents to the chunk\n         *\n         * @return A reference to a TraceEvent to be replaced\n         */\n        TraceEvent& addEvent();\n\n        /**\n         * Used for reviewing TraceEvents in the chunk\n         *\n         * Valid indexes are from 0 to `count()`. There is no\n         * bounds checking.\n         *\n         * @return A const reference to a TraceEvent in the chunk\n         *         that can be used to review the event data\n         */\n        const TraceEvent& operator[](const int index) const;\n\n        /**\n         * Determine if the chunk is full\n         *\n         * @return true if the chunk is full (and should be replaced)\n         *         or false otherwise.\n         */\n        bool isFull() const;\n\n        /**\n         * Determine up to which index of events is initialised\n         *\n         * @return The number of initialised events in the chunk\n         */\n        size_t count() const;\n\n        /**\n         * @return Const iterator to the start of the chunk\n         */\n        const_iterator begin() const;\n\n        /**\n         * @return Const iterator to the last initialised event in the chunk\n         */\n        const_iterator end() const;\n\n    private:\n        unsigned short next_free;\n        event_array chunk;\n    };\n\n    // Forward decl\n    class StatsCallback;\n\n    /**\n     * Abstract base-class for a buffer of TraceEvents\n     *\n     * The TraceBuffer loans out TraceChunks to individual\n     * threads to reduce lock-contention on event logging.\n     *\n     * This class is *not* thread-safe and should only be directly\n     * interacted either with the global lock owned by the TraceLog\n     * or after tracing has been finished.\n     *\n     * A trace buffer can be iterated over using C++11 style range\n     * iteration:\n     *\n     *     for(const auto& event : trace_buffer) {\n     *         std::cout << event << std::endl;\n     *     }\n     *\n     * Alternatively more complex iteration can be accomplished by\n     * using the iterators returned by TraceBuffer::begin() and\n     * TraceBuffer::end().\n     *\n     * Iteration should not be attempted while chunks are loaned out.\n     */\n    class TraceBuffer {\n    public:\n        /**\n         * Virtual destructor to allow subclasses to be cleaned up\n         * properly.\n         */\n        virtual ~TraceBuffer() = default;\n\n        /**\n         * Used for getting a TraceChunk to add events to\n         *\n         * @return A pointer to a TraceChunk to insert events into or\n         *         nullptr if the buffer is full.\n         */\n        virtual TraceChunk* getChunk() = 0;\n\n        /**\n         * Used for returning a TraceChunk once full\n         *\n         * For some buffer implementations this *may* be a no-op\n         * but for others which might reuse chunks this can be\n         * used to only reuse chunks that have been finished with.\n         *\n         * @param chunk The chunk to be returned\n         */\n        virtual void returnChunk(TraceChunk& chunk) = 0;\n\n        /**\n         * Determine if there are no remaining chunks left to be\n         * used\n         *\n         * @return true if there are no chunks left or false\n         *         otherwise\n         */\n        virtual bool isFull() const = 0;\n\n        /**\n         * Callback for retrieving stats from the Buffer implementation\n         *\n         * Implementations MUST supply the following stats as minimum:\n         *\n         * - buffer_name <cstring_span>: Textual representation of buffer type\n         * - buffer_is_full <bool>: True if the buffer is full\n         * - buffer_chunk_count <size_t>: Chunks that are returned or loaned\n         * - buffer_loaned_chunks <size_t>: Currently loaned chunks\n         * - buffer_total_loaned <size_t>: Count of all chunks ever loaned\n         * - buffer_size <size_t>: Max number of chunks that fit in the buffer\n         * - buffer_generation <size_t>: Generation number of the buffer\n         *\n         * On a non-rotating buffer, if buffer_chunk_count is equal to\n         * buffer-size then that must suggest the buffer is full and\n         * there are no more chunks to be loaned. On a rotating buffer\n         * it suggests that chunks are being reused.\n         *\n         * Buffer implementations may include other relevant stats but\n         * end-users SHOULD NOT assume the existence of those stats.\n         */\n        virtual void getStats(StatsCallback& addStats) const = 0;\n\n        /**\n         * Used for accessing TraceChunks in the buffer\n         *\n         * Valid indexes are from 0 to `count()`. There is no\n         * bounds checking.\n         *\n         * @return A const reference to a TraceEvent in the chunk\n         *         that can be used to review the event data\n         * @throw std::logic_error if chunks are currently loaned\n         *        out to chunk tenants.\n         */\n        virtual const TraceChunk& operator[](const int index) const = 0;\n\n        /**\n         * Used for determining the number of chunks in the buffer\n         *\n         * @return Number of chunks currently in the buffer\n         */\n        virtual size_t chunk_count() const = 0;\n\n        /**\n         * @return The generation number of the TraceBuffer\n         */\n        virtual size_t getGeneration() const = 0;\n\n        /**\n         * Const bi-directional iterator over the TraceChunks in a TraceBuffer\n         *\n         * Usage:\n         *\n         *    chunk_iterator it = buffer.chunk_start();\n         *     std::cout << *(it->start()) << std::endl;\n         *\n         *     for(const auto& chunk : buffer.chunks()) {\n         *         for(const auto& event : chunk) {\n         *             std::cout << event << std::endl;\n         *         }\n         *     }\n         */\n        class PHOSPHOR_API chunk_iterator\n            : public std::iterator<std::bidirectional_iterator_tag,\n                                   TraceChunk> {\n            using const_reference = const TraceChunk&;\n            using const_pointer = const TraceChunk*;\n            using _self = chunk_iterator;\n\n        public:\n            chunk_iterator() = default;\n            chunk_iterator(const TraceBuffer& buffer_);\n            chunk_iterator(const TraceBuffer& buffer_, size_t index_);\n            const_reference operator*() const;\n            const_pointer operator->() const;\n            chunk_iterator& operator++();\n            bool operator==(const chunk_iterator& other) const;\n            bool operator!=(const chunk_iterator& other) const;\n\n        protected:\n            const TraceBuffer& buffer;\n            size_t index;\n        };\n\n        /**\n         * @return A const iterator to the first chunk of the TraceBuffer\n         */\n        virtual chunk_iterator chunk_begin() const = 0;\n\n        /**\n         * @return A const iterator to after the last chunk of the TraceBuffer\n         */\n        virtual chunk_iterator chunk_end() const = 0;\n\n        /**\n         * Const iterator over a TraceBuffer, implements required methods of\n         * a bi-directional iterator.\n         *\n         * Usage:\n         *\n         *     event_iterator it = trace_buffer.start();\n         *     std::cout << *it << std::endl;\n         *     std::cout << *(++it) << std::endl;\n         *\n         *     for(const auto& event : trace_buffer) {\n         *         std::cout << event << std::endl;\n         *     }\n         *\n         * For resource efficiency event_iterator does not have\n         * post-increment\n         */\n        using event_iterator = gsl_p::multidimensional_iterator<chunk_iterator>;\n\n        /**\n         * @return A const iterator to the first event of the TraceBuffer\n         */\n        virtual event_iterator begin() const = 0;\n\n        /**\n         * @return A const iterator to after the last event of the TraceBuffer\n         */\n        virtual event_iterator end() const = 0;\n\n        /**\n         * Helper class that can be used to create for-range loops over\n         * the chunks of the TraceBuffer\n         *\n         *     for(const auto& chunk : TraceBuffer::chunk_iterable(buffer) {\n         *         // Do something with every chunk\n         *     }\n         */\n        class PHOSPHOR_API chunk_iterable {\n        public:\n            /**\n             * @param buffer_ The buffer to iterate over\n             */\n            chunk_iterable(const TraceBuffer& buffer_) : buffer(buffer_) {}\n\n            /**\n             * @return A const iterator to the first chunk of the buffer\n             */\n            chunk_iterator begin() {\n                return buffer.chunk_begin();\n            }\n\n            /**\n             * @return A const iterator to after the last chunk of the buffer\n             */\n            chunk_iterator end() {\n                return buffer.chunk_end();\n            }\n\n        private:\n            const TraceBuffer& buffer;\n        };\n\n        /**\n         * Helper function for creating a chunk_iterable over the buffer\n         *\n         *     for(const auto& chunk : buffer.chunks() {\n         *         // Do something with every chunk\n         *     }\n         *\n         * @return An iterable over the class\n         */\n        chunk_iterable chunks() const {\n            return chunk_iterable(*this);\n        }\n    };\n\n    using buffer_ptr = std::unique_ptr<TraceBuffer>;\n\n    /**\n     * Interface for a TraceBuffer factory\n     */\n    using trace_buffer_factory =\n        std::function<buffer_ptr(size_t generation, size_t buffer_size)>;\n\n    PHOSPHOR_API\n    buffer_ptr make_fixed_buffer(size_t generation, size_t buffer_size);\n\n    PHOSPHOR_API\n    buffer_ptr make_ring_buffer(size_t generation, size_t buffer_size);\n}\n", "meta": {"hexsha": "213ef2bd7f3893661f0e612f7b823eccdc3b7ac5", "size": 11867, "ext": "h", "lang": "C", "max_stars_repo_path": "include/phosphor/trace_buffer.h", "max_stars_repo_name": "Chippiewill/Phosphor", "max_stars_repo_head_hexsha": "ef090fa5b331dd94301cd8562b24c78c0c2030f1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/phosphor/trace_buffer.h", "max_issues_repo_name": "Chippiewill/Phosphor", "max_issues_repo_head_hexsha": "ef090fa5b331dd94301cd8562b24c78c0c2030f1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/phosphor/trace_buffer.h", "max_forks_repo_name": "Chippiewill/Phosphor", "max_forks_repo_head_hexsha": "ef090fa5b331dd94301cd8562b24c78c0c2030f1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2472826087, "max_line_length": 80, "alphanum_fraction": 0.5732704138, "num_tokens": 2508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09268778114565464, "lm_q2_score": 0.022629198220398144, "lm_q1q2_score": 0.0020974501721539008}}
{"text": "/*****************************************************************\\\n           __\n          / /\n\t\t / /                     __  __\n\t\t/ /______    _______    / / / / ________   __       __\n\t   / ______  \\  /_____  \\  / / / / / _____  | / /      / /\n\t  / /      | / _______| / / / / / / /____/ / / /      / /\n\t / /      / / / _____  / / / / / / _______/ / /      / /\n\t/ /      / / / /____/ / / / / / / |______  / |______/ /\n   /_/      /_/ |________/ / / / /  \\_______/  \\_______  /\n                          /_/ /_/                     / /\n\t\t\t                                         / /\n\t\t       High Level Game Framework            /_/\n\n  ---------------------------------------------------------------\n\n  Copyright (c) 2007-2011 - Rodrigo Braz Monteiro.\n  This file is subject to the terms of halley_license.txt.\n\n\\*****************************************************************/\n\n\n#pragma once\n\n#include <string>\n#include <sstream>\n#include <halley/data_structures/vector.h>\n#include <gsl/gsl_assert>\n#include <iomanip>\n#include <cstdint>\n\nnamespace Halley {\n\n\ttypedef char Character;\n\ttypedef wchar_t utf16type;\n\ttypedef char32_t utf32type;\n\ttypedef std::wstring StringUTF16;\n\ttypedef std::u32string StringUTF32;\n\n\t// String class\n\tclass String {\n\tpublic:\n\t\tconst static size_t npos = size_t(-1);\n\n\t\tString();\n\t\tString(const char* utf8);\n\t\tString(const char* utf8,size_t bytes);\n\t\tString(const std::basic_string<Character>& str);\n\t\tString(const String& str) noexcept;\n\t\tString(String&& str) noexcept;\n\n\t\texplicit String(const wchar_t* utf16);\n\t\texplicit String(const StringUTF32 &utf32);\n\t\texplicit String(char character);\n\t\texplicit String(wchar_t character);\n\t\texplicit String(int character);\n\t\texplicit String(float number);\n\t\texplicit String(double number);\n\n\t\tString& operator=(const char* utf8);\n\t\tString& operator=(const std::basic_string<Character>& str);\n\t\tString& operator=(String&& str) noexcept;\n\t\tString& operator=(const String& str);\n\n\t\toperator std::string() const;\n\t\t\n\t\tbool isEmpty() const;\n\t\tsize_t length() const;\n\t\t\n\t\tvoid setSize(size_t size);\n\t\tvoid truncate(size_t size);\n\n\t\tString& trim(bool fromRight);\n\t\tString& trimBoth();\n\n\t\tbool contains(const String& string) const;\n\t\tsize_t find(String str) const;\n\n\t\tString replaceAll(const String& before, const String& after) const;\n\t\tString replaceOne(const String& before, const String& after) const;\n\t\tvoid shrink();\n\n\t\tString left(size_t n) const;\n\t\tString right(size_t n) const;\n\t\tString mid(size_t start,size_t count=npos) const;\n\n\t\tbool startsWith(const String& string,bool caseSensitive=true) const;\n\t\tbool endsWith(const String& string,bool caseSensitive=true) const;\n\n\t\tvoid writeText(const Character* src,size_t len,size_t &pos);\n\t\tvoid writeChar(const Character &src,size_t &pos);\n\t\tvoid writeNumber(Character *temp,int number,int pad,size_t &pos);\n\n\t\tbool isNumber() const;\n\t\tbool isInteger() const;\n\n\t\tString asciiLower() const;\n\t\tString asciiUpper() const;\n\t\tvoid asciiMakeUpper();\n\t\tvoid asciiMakeLower();\n\t\tbool asciiCompareNoCase(const Character *src) const;\n\n\t\tvoid appendCharacter(int unicode);\n\n\t\t// Convert a string to a number\n\t\tint toInteger() const;\n\t\tlong long toInteger64() const;\n\t\tfloat toFloat() const;\n\t\tint subToInteger(size_t start,size_t end) const;\n\n\t\t// std::string methods\n\t\tconst char* c_str() const;\n\t\tString substr(size_t pos, size_t len=npos) const;\n\t\tsize_t find(Character character, size_t pos=0) const;\n\t\tsize_t find(const char* str, size_t pos=0) const;\n\t\tsize_t find_last_of(char character) const;\n\t\tsize_t size() const;\n\t\tconst char& operator[](size_t pos) const;\n\t\tchar& operator[](size_t pos);\n\n\t\tstatic const Character* stringPtrTrim(Character *chr,size_t len,size_t startPos);\n\t\tstatic const Character* stringTrim(String &str,size_t startPos);\n\n\t\t// Number tidy up functions\n\t\tstatic String prettyFloat(String src);\n\t\tstatic String prettySize(long long bytes);\n\n\t\t// Unicode routines\n\t\tStringUTF16 getUTF16() const;\n\t\tStringUTF32 getUTF32() const;\n\t\tsize_t getUTF32Len() const;\n\n\t\t// Static unicode routines\n\t\tstatic size_t getUTF8Len(const wchar_t *utf16);\n\t\tstatic size_t getUTF8Len(const StringUTF32 &utf32);\n\t\tstatic size_t getUTF16Len(const StringUTF32 &utf32);\n\n\t\tinline std::string& cppStr() { return str; }\n\t\tinline const std::string& cppStr() const { return str; }\n\n\t\tVector<String> split(char delimiter) const;\n\t\tVector<String> split(String delimiter) const;\n\t\tstatic String concatList(const Vector<String>& list, String separator);\n\n\t\t//////////\n\n\t\tString operator += (const String &p);\n\t\tString operator += (const char* p);\n\t\tString operator += (const wchar_t* p);\n\t\tString operator += (const double &p);\n\t\tString operator += (const int &p);\n\t\tString operator += (const Character &p);\n\n\t\tbool operator== (const String& rhp) const;\n\t\tbool operator!= (const String& rhp) const;\n\t\tbool operator< (const String& rhp) const;\n\t\tbool operator> (const String& rhp) const;\n\t\tbool operator<= (const String& rhp) const;\n\t\tbool operator>= (const String& rhp) const;\n\n\tprivate:\n\t\tCharacter* getCharPointer(size_t pos);\n\t\tstatic size_t UTF8toUTF16(const char *utf8,wchar_t *utf16);\n\t\tstatic size_t UTF16toUTF8(const wchar_t *utf16,char *utf8);\n\t\tstatic size_t UTF32toUTF8(const utf32type *utf32,char *utf8);\n\n\t\tstd::string str;\n\t};\n\n\tString operator+ (const String& lhp, const String& rhp);\n\tstd::ostream& operator<< (std::ostream& os, const String& rhp);\n\tstd::istream& operator>> (std::istream& is, String& rhp);\n\n\tusing StringArray = Vector<String>;\n\n\t\n}\n\nnamespace std {\n\ttemplate<>\n\tstruct hash<Halley::String>\n\t{\n\t\tsize_t operator()(const Halley::String& s) const \n\t\t{\n\t\t\treturn std::hash<std::string>()(s.cppStr());\n\t\t}\n\t};\n}\n", "meta": {"hexsha": "4e299ec984f5c7c085a768d9a3c1db96eabf7fe8", "size": 5654, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engine/utils/include/halley/text/halleystring.h", "max_stars_repo_name": "Healthire/halley", "max_stars_repo_head_hexsha": "aa58e1abe22cda9e80637922721c03574779cd81", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/engine/utils/include/halley/text/halleystring.h", "max_issues_repo_name": "Healthire/halley", "max_issues_repo_head_hexsha": "aa58e1abe22cda9e80637922721c03574779cd81", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engine/utils/include/halley/text/halleystring.h", "max_forks_repo_name": "Healthire/halley", "max_forks_repo_head_hexsha": "aa58e1abe22cda9e80637922721c03574779cd81", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9153439153, "max_line_length": 83, "alphanum_fraction": 0.6475061903, "num_tokens": 1440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08151976043757421, "lm_q2_score": 0.025565214155277266, "lm_q1q2_score": 0.002084070133473484}}
{"text": "#ifndef VKST_PLAT_FILE_HANDLE_H\n#define VKST_PLAT_FILE_HANDLE_H\n\n#include <plat/filesystem.h>\n#include <turf/c/core.h>\n#include <gsl.h>\n\nnamespace plat {\n\n// A RAII wrapper around the C stdio file handle\nclass file_handle {\npublic:\n  enum class open_modes : uint8_t {\n    read = 0x1,\n    write = 0x2,\n    append = 0x4,\n  }; // enum class open_modes\n\n  static file_handle open(plat::filesystem::path const& path, open_modes mode,\n                          std::error_code& ec) noexcept;\n\n  file_handle() noexcept = default;\n\n  std::FILE* get() noexcept { return _handle.get(); }\n  operator std::FILE*() noexcept { return get(); }\n\n  explicit operator bool() noexcept { return static_cast<bool>(_handle); }\n\n  void reset() noexcept { _handle.reset(); }\n\nprivate:\n  file_handle(FILE* handle) noexcept : _handle{handle, &std::fclose} {}\n\n  using file_ptr = gsl::unique_ptr<std::FILE, decltype(&std::fclose)>;\n  file_ptr _handle{nullptr, &std::fclose};\n}; // class file_handle\n\ninline constexpr auto operator|(file_handle::open_modes a,\n                                file_handle::open_modes b) noexcept {\n  using U = std::underlying_type_t<file_handle::open_modes>;\n  return static_cast<file_handle::open_modes>(static_cast<U>(a) |\n                                              static_cast<U>(b));\n}\n\ninline constexpr auto operator&(file_handle::open_modes a,\n                                file_handle::open_modes b) noexcept {\n  using U = std::underlying_type_t<file_handle::open_modes>;\n  return static_cast<file_handle::open_modes>(static_cast<U>(a) &\n                                              static_cast<U>(b));\n}\n\n} // namespace plat\n\n#endif // VKST_PLAT_FILE_HANDLE_H", "meta": {"hexsha": "41af5e62c3700f11abe31e2776a05ef0f84047b4", "size": 1677, "ext": "h", "lang": "C", "max_stars_repo_path": "src/plat/file_handle.h", "max_stars_repo_name": "wesleygriffin/vkst", "max_stars_repo_head_hexsha": "5f1210ef8aeecdd2bbc3904b0cc4dd09892f239c", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/plat/file_handle.h", "max_issues_repo_name": "wesleygriffin/vkst", "max_issues_repo_head_hexsha": "5f1210ef8aeecdd2bbc3904b0cc4dd09892f239c", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/plat/file_handle.h", "max_forks_repo_name": "wesleygriffin/vkst", "max_forks_repo_head_hexsha": "5f1210ef8aeecdd2bbc3904b0cc4dd09892f239c", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0555555556, "max_line_length": 78, "alphanum_fraction": 0.6481812761, "num_tokens": 399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.05582313956382589, "lm_q2_score": 0.037326887745718636, "lm_q1q2_score": 0.002083704064112514}}
{"text": "// stdafx.h : include file for standard system include files,\n// or project specific include files that are used frequently, but\n// are changed infrequently\n//\n\n#pragma once\n#define _CRT_SECURE_NO_WARNINGS\n#define _SCL_SECURE_NO_WARNINGS\n#define _CRT_NON_CONFORMING_SWPRINTFS\n#define HPX_COMPONENT_EXPORTS\n#include \"targetver.h\"\n\n#include <gsl.h>\n#include <stdio.h>\n#include <tchar.h>\n#include <iostream>\n#include <string>\n\n\n// TODO: reference additional headers your program requires here\n#include <hpx/hpx_init.hpp>\n#include <hpx/include/actions.hpp>\n#include <hpx/include/lcos.hpp>\n#include <hpx/include/components.hpp>\n#include <hpx/include/serialization.hpp>\n\n#include <boost/any.hpp>\n#include <hpx/include/iostreams.hpp>\n\n#include \"functions.hpp\"\n#include \"components.hpp\"\n#include \"stubs.h\"\n#include \"clients.h\"\n\n// SmallServer references\n#include \"../../Libs/SmallServer/SmallServer.h\"", "meta": {"hexsha": "db4adde40c6d03584c6546c9bc34624c4f38bd98", "size": 893, "ext": "h", "lang": "C", "max_stars_repo_path": "Apps/HpxTest_1/stdafx.h", "max_stars_repo_name": "brakmic/HPX_Projects", "max_stars_repo_head_hexsha": "747f011e10b9201e78b1d605ee170931ef3b6b72", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2016-02-21T10:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-01T23:28:02.000Z", "max_issues_repo_path": "Apps/HpxTest_1/stdafx.h", "max_issues_repo_name": "brakmic/HPX_Projects", "max_issues_repo_head_hexsha": "747f011e10b9201e78b1d605ee170931ef3b6b72", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Apps/HpxTest_1/stdafx.h", "max_forks_repo_name": "brakmic/HPX_Projects", "max_forks_repo_head_hexsha": "747f011e10b9201e78b1d605ee170931ef3b6b72", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-02-23T06:29:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-17T02:27:20.000Z", "avg_line_length": 24.8055555556, "max_line_length": 66, "alphanum_fraction": 0.7737961926, "num_tokens": 209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08756384428525611, "lm_q2_score": 0.023689471428613766, "lm_q1q2_score": 0.0020743411873751596}}
{"text": "// stdafx.h : include file for standard system include files,\n// or project specific include files that are used frequently, but\n// are changed infrequently\n//\n\n#pragma once\n\n#include \"targetver.h\"\n#define _NO_SCRIPT_GUIDS 0\n//#define WIN32_LEAN_AND_MEAN             // Exclude rarely-used stuff from Windows headers\n// Windows Header Files\n#include <windows.h>\n#include <d3d11.h>\n\n// C RunTime Header Files\n#include <stdlib.h>\n#include <malloc.h>\n#include <memory.h>\n#include <tchar.h>\n#include <guiddef.h>\n\n\n// Spectre\n#include <NativeRenderer/Engine.h>\n#include <NativeRenderer/Resources/IndexBuffer.h>\n#include <NativeRenderer/Resources/ShaderProgram.h>\n#include <NativeRenderer/Resources/VertexBuffer.h>\n#include <NativeRendererD3D11/RendererD3D11.h>\n#include <NativeRendererD3D11/RenderOutputD3D11.h>\n#include <Framework/PerformanceTraceLogging.h>\n//\n// angle\n#include <common/platform.h>\n#include <angle_gl.h>\n#include <EGL/egl.h>\n#include <EGL/eglext.h>\n#include <libANGLE/Context.h>\n#include <libANGLE/renderer/d3d/d3d11/Context11.h>\n//\n// Chakra\n#include <jsrt.h>\n//\n//// C++/WinRT\n//#include <winrt/Windows.ApplicationModel.h>\n//#include <winrt/Windows.Graphics.Display.h>\n//#include <winrt/Windows.UI.Core.h>\n\n// Arcana\n#include <arcana/macros.h>\n#include <arcana/string.h>\n#include <arcana/experimental/array.h>\n#include <arcana/threading/cancellation.h>\n#include <arcana/threading/coroutine.h>\n#include <arcana/threading/dispatcher.h>\n#include <arcana/threading/task.h>\n#include <arcana/threading/task_conversions.h>\n\n//// GSL\n//#include <gsl/gsl>\n//\n// C++ standard library\n#include <algorithm>\n#include <cstddef>\n#include <exception>\n#include <functional>\n#include <memory>\n#include <optional>\n#include <sstream>\n#include <string>\n#include <string_view>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n#include <variant>\n\n// C standard library\n#include <assert.h>\n\n// N-API\n#define NODE_ADDON_API_DISABLE_DEPRECATED\n#include <napi.h>\n", "meta": {"hexsha": "2c1539b24a4f1175928f8202e3f6d0e4e3d130df", "size": 1964, "ext": "h", "lang": "C", "max_stars_repo_path": "TestApp/Source/Win32/pch.h", "max_stars_repo_name": "zloop1982/BabylonNative", "max_stars_repo_head_hexsha": "dc15fbde9eb8df3f72d4d14aa8f896341005aea2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-02-18T22:03:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T11:42:08.000Z", "max_issues_repo_path": "TestApp/Source/Win32/pch.h", "max_issues_repo_name": "zloop1982/BabylonNative", "max_issues_repo_head_hexsha": "dc15fbde9eb8df3f72d4d14aa8f896341005aea2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-03T22:56:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-13T00:01:39.000Z", "max_forks_repo_path": "TestApp/Source/Win32/pch.h", "max_forks_repo_name": "ryantrem/BabylonNative", "max_forks_repo_head_hexsha": "548684984126ee6cd242f2d73ecff8c6f5614b02", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9512195122, "max_line_length": 91, "alphanum_fraction": 0.7515274949, "num_tokens": 496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10669059394565118, "lm_q2_score": 0.019419348998234026, "lm_q1q2_score": 0.0020718618786594745}}
{"text": "#pragma once\n\n#ifndef _NOGSL\n#include <gsl/gsl_vector.h>\n#else\n#include \"CustomSolver.h\"\n#endif\n#include \"ValueGrad.h\"\n#include \"BooleanNodes.h\"\n#include \"BooleanDAG.h\"\n#include \"NodeVisitor.h\"\n#include \"VarStore.h\"\n#include <map>\n#include <set>\n#include \"SymbolicEvaluator.h\"\n#include \"Interface.h\"\n\n#include <iostream>\n\n\nusing namespace std;\n\nclass Path {\npublic:\n\tmap<int, int> nodeToVal;\n\n\tPath() { }\n\tvoid add(map<int, int>& initMap) {\n\t\tnodeToVal.insert(initMap.begin(), initMap.end());\n\t}\n\tvoid addCond(int nodeid, int val) {\n\t\tAssert(nodeToVal.find(nodeid) == nodeToVal.end(), \"Node already has value\");\n\t\tnodeToVal[nodeid] = val;\n\t}\n\n\tstring toString() {\n\t\tstringstream s;\n\t\tfor (auto it = nodeToVal.begin(); it != nodeToVal.end(); it++) {\n\t\t\ts << \"(\" << it->first << \",\" << it->second << \");\";\n\t\t}\n\t\treturn s.str();\n\t}\n\n\tint getVal(int nodeid) {\n\t\tif (nodeToVal.find(nodeid) == nodeToVal.end()) {\n\t\t\treturn -1;\n\t\t} else {\n\t\t\treturn nodeToVal[nodeid];\n\t\t}\n\t}\n\n\tvoid empty() {\n\t\tnodeToVal.clear();\n\t}\n\n\tint length() {\n\t\treturn nodeToVal.size();\n\t}\n\n\tint lowestId() {\n\t\tif (nodeToVal.size() == 0) {\n\t\t\treturn -1;\n\t\t}\n\t\treturn nodeToVal.begin()->first;\n\t}\n\t\n\tstatic bool isCompatible(Path* p1, Path* p2) {\n\t\tint size1 = p1->nodeToVal.size();\n\t\tint size2 = p2->nodeToVal.size();\n\t\tif (size1 == 0 || size2 == 0) {\n\t\t\treturn true;\n\t\t}\n\t\tPath* pl;\n\t\tPath* ps;\n\t\tif (size1 > size2) {\n\t\t\tpl = p1;\n\t\t\tps = p2;\n\t\t} else {\n\t\t\tpl = p2;\n\t\t\tps = p1;\n\t\t}\n\t\tfor (auto it = pl->nodeToVal.begin(); it != pl->nodeToVal.end(); it++) {\n\t\t\tint nodeid = it->first;\n\t\t\tint val = it->second;\n\t\t\tint val1 = ps->getVal(nodeid);\n\t\t\tif (val1 != -1 && val != val1) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\tstatic void combinePaths(Path* p1, Path* p2, Path* p) {\n\t\t// assumes that paths are compatible\n\t\tp->nodeToVal.clear();\n\t\tp->add(p1->nodeToVal);\n\t\tp->add(p2->nodeToVal);\n\t}\n\n\tstatic void combinePath(Path* p1, Path* p) {\n\t\tp->nodeToVal.clear();\n\t\tp->add(p1->nodeToVal);\n\t}\n\n\tstatic void combinePaths(vector<Path*>& paths, Path* p2, Path* p) {\n\t\tp->nodeToVal.clear();\n\t\tp->add(p2->nodeToVal);\n\t\t// TODO: need to add common conditions in paths to p\n\t}\n\n\tstatic Path* pIntersect(Path* p1, Path* p2) {\n\t\t// assumes that the paths are compatible\n\t\tPath* p = new Path();\n\t\tp->add(p1->nodeToVal);\n\t\tp->add(p2->nodeToVal);\n\t\treturn p;\n\t}\n\n\t// only one cond  should differ\n\tstatic int isConjugate(Path* p1, Path* p2) {\n\t\t//cout << \"Conjugate check: \" << p1->toString() << \" | \" << p2->toString() << endl;\n\t\tif (p1->length() != p2->length()) {\n\t\t\treturn -1;\n\t\t}\n\t\tint conjIdx = -1;\n\t\tint ctr = 0;\n\t\tfor (auto it = p1->nodeToVal.begin(); it != p1->nodeToVal.end(); it++) {\n\t\t\tif (p2->getVal(it->first) == -1) {\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tif (p2->getVal(it->first) != it->second) {\n\t\t\t\tif (conjIdx == -1) {\n\t\t\t\t\tconjIdx = ctr;\n\t\t\t\t} else {\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tctr++;\n\t\t}\n\t\t//cout << conjIdx << endl;\n\t\treturn conjIdx;\n\t}\n\n\tstatic Path* pUnion(Path* p1, Path* p2) {\n\t\t// assumes that the paths are conjugates\n\t\tPath* p = new Path();\n\t\tfor (auto it = p1->nodeToVal.begin(); it != p1->nodeToVal.end(); it++) {\n\t\t\tif (p2->getVal(it->first) == it->second) {\n\t\t\t\tp->addCond(it->first, it->second);\n\t\t\t}\n\t\t\t\n\t\t}\n\t\treturn p;\n\n\t}\n\n\tstatic bool isSubset(Path* p1, Path* p2) {\n\t\tif (p1->length() == 0) return true;\n\t\tfor (auto it = p1->nodeToVal.begin(); it != p1->nodeToVal.end(); it++) {\n\t\t\tif (p2->getVal(it->first) != it->second) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\n\t}\n\n\t// no common condition\n\tstatic bool isDisjoint(Path* p1, Path* p2) {\n\t\tif (p1->length() == 0 || p2->length() == 0) return false;\n\t\tfor (auto it = p1->nodeToVal.begin(); it != p1->nodeToVal.end(); it++) {\n\t\t\tif (p2->getVal(it->first) != -1) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n};\n\nclass MergeNodesList {\n\tvector<tuple<int, int, int, int>> nodesToMerge;\n\npublic:\n\tvoid add(int node1, int idx1, int node2, int idx2) {\n\t\tnodesToMerge.push_back(make_tuple(node1, idx1, node2, idx2));\n\t}\n\n\tstring print() {\n\t\tstringstream s;\n\t\tfor (int i = 0; i < nodesToMerge.size(); i++) {\n\t\t\tauto& t = nodesToMerge[i];\n\t\t\ts << \"(\" << get<0>(t) << \",\" << get<1>(t) << \",\" << get<2>(t) << \",\" << get<3>(t) << \") \";\n\t\t}\n\t\treturn s.str();\n\t}\n\n\tint size() {\n\t\treturn nodesToMerge.size();\n\t}\n\n\ttuple<int, int, int, int>& getTuple(int idx) {\n\t\treturn nodesToMerge[idx];\n\t}\n};\n\n\nclass KLocalityAutoDiff: public NodeVisitor, public SymbolicEvaluator\n{\n\tBooleanDAG& bdag;\n\tmap<string, int>& floatCtrls; // Maps float ctrl names to indices within grad vector\n\tint nctrls; // number of float ctrls\n\tgsl_vector* ctrls; // ctrl values\n\tvector<vector<ValueGrad*>> values; // Keeps track of values along with gradients for each node\n\tvector<vector<DistanceGrad*>> distances; // Keeps track of distance metric for boolean nodes\n\tvector<vector<Path*>> paths;\n\tvector<int> sizes;\n    Interface* inputValues;\n\n    set<string> pathStrings;\n\n\n    int MAX_REGIONS = 16 + 1; // 0th idx is for final merging\n\n    vector<vector<MergeNodesList*>> mergeNodes;\n\npublic:\n    int DEFAULT_INP = -32;\n    KLocalityAutoDiff(BooleanDAG& bdag_p, map<string, int>& floatCtrls_p);\n    \n\t~KLocalityAutoDiff(void);\n\t\n\tvirtual void visit( SRC_node& node );\n\tvirtual void visit( DST_node& node );\n\tvirtual void visit( CTRL_node& node );\n\tvirtual void visit( PLUS_node& node );\n\tvirtual void visit( TIMES_node& node );\n\tvirtual void visit( ARRACC_node& node );\n\tvirtual void visit( DIV_node& node );\n\tvirtual void visit( MOD_node& node );\n\tvirtual void visit( NEG_node& node );\n\tvirtual void visit( CONST_node& node );\n\tvirtual void visit( LT_node& node );\n\tvirtual void visit( EQ_node& node );\n\tvirtual void visit( AND_node& node );\n\tvirtual void visit( OR_node& node );\n\tvirtual void visit( NOT_node& node );\n\tvirtual void visit( ARRASS_node& node );\n\tvirtual void visit( UFUN_node& node );\n\tvirtual void visit( TUPLE_R_node& node );\n\tvirtual void visit( ASSERT_node& node );\n\t\n    virtual void setInputs(Interface* inputValues_p);\n\n\tvirtual void run(const gsl_vector* ctrls_p, const set<int>& nodesSubset) {\n\t\tAssert(false, \"Not yet supported\");\n\t}\n    virtual void run(const gsl_vector* ctrls_p);\n    \n    virtual double getErrorOnConstraint(int nodeid, gsl_vector* grad);\n    double getSqrtError(bool_node* node, gsl_vector* grad);\n    double getAssertError(bool_node* node, gsl_vector* grad);\n    double getBoolCtrlError(bool_node* node, gsl_vector* grad);\n    double getBoolExprError(bool_node* node, gsl_vector* grad);\n    \n    virtual double getErrorOnConstraint(int nodeid);\n    double getSqrtError(bool_node* node);\n    double getAssertError(bool_node* node);\n    double getBoolCtrlError(bool_node* node);\n    double getBoolExprError(bool_node* node);\n\n    virtual double getErrorForAsserts(const set<int>& assertIds, gsl_vector* grad) {\n    \tAssert(false, \"TODO\");\n    }\n\n\tvirtual double getErrorForAssert(int assertId, gsl_vector* grad) {\n\t\tAssert(false, \"TODO\");\n\t}\n    \n\n\tvoid setvalue(bool_node& bn, int idx, ValueGrad* v) {\n\t\tvalues[bn.id][idx] = v;\n\t}\n\t\n\tValueGrad* v(bool_node& bn, int idx) {\n\t\tValueGrad* val = values[bn.id][idx];\n\t\tif (val == NULL) {\n\t\t\tgsl_vector* g = gsl_vector_alloc(nctrls);\n\t\t\tGradUtil::default_grad(g);\n\t\t\tval = new ValueGrad(0, g);\n\t\t\tsetvalue(bn, idx, val);\n\t\t}\n\t\treturn val;\n\t}\n\t\n\tValueGrad* v(bool_node* bn, int idx) {\n\t\treturn v(*bn, idx);\n\t}\n\t\n\tvoid setdistance(bool_node& bn, int idx, DistanceGrad* d) {\n\t\tdistances[bn.id][idx] = d;\n\t}\n\t\n\tDistanceGrad* d(bool_node& bn, int idx) {\n\t\tDistanceGrad* dist = distances[bn.id][idx];\n\t\tif (dist == NULL) {\n\t\t\tgsl_vector* g = gsl_vector_alloc(nctrls);\n\t\t\tGradUtil::default_grad(g);\n\t\t\tdist = new DistanceGrad(0, g);\n\t\t\tsetdistance(bn, idx, dist);\n\t\t}\n\t\treturn dist;\n\t}\n\t\n\tDistanceGrad* d(bool_node* bn, int idx) {\n\t\treturn d(*bn, idx);\n\t}\n\n\tint size(bool_node& bn) {\n\t\treturn sizes[bn.id];\n\t}\n\n\tint size(bool_node* bn) {\n\t\treturn size(*bn);\n\t}\n\n\tvoid setsize(bool_node& bn, int sz) {\n\t\tsizes[bn.id] = sz;\n\t}\n\n\tvoid setsize(bool_node* n, int sz) {\n\t\tsetsize(*n, sz);\n\t}\n\n\tvoid setpath(bool_node& bn, int idx, Path* p) {\n\t\tpaths[bn.id][idx] = p;\n\t}\n\n\tPath* path(bool_node& bn, int idx) {\n\t\tPath* p = paths[bn.id][idx];\n\t\tif (p == NULL) {\n\t\t\tp = new Path();\n\t\t\tsetpath(bn, idx, p);\n\t\t}\n\t\treturn p;\n\t}\n\n\tPath* path(bool_node* bn, int idx) {\n\t\treturn path(*bn, idx);\n\t}\n\n\t\n\tvirtual double dist(int nid) {\n\t\tValueGrad* val = v(bdag[nid], 0);\n\t\treturn val->getVal();\n\t}\n\n\tvirtual double dist(int nid, gsl_vector* grad) {\n\t\tValueGrad* val = v(bdag[nid], 0);\n\t\tgsl_vector_memcpy(grad, val->getGrad());\n\t\treturn val->getVal();\n\t}\n\n\tvirtual void print() {\n\t\t/*for (int i = 0; i < bdag.size(); i++) {\n\t\t\tif (bdag[i]->type == bool_node::ASSERT) {\n\t\t\t\tDistanceGrad* dist = d(bdag[i]->mother);\n\t\t\t\tif (dist->set) {\n\t\t\t\tdouble gmag = gsl_blas_dnrm2(dist->grad);\n\t\t\t\tif (dist->dist < 0.1) {\n\t\t\t\t\tcout << bdag[i]->mother->lprint() << endl;\n\t\t\t\t\tcout << dist->printFull() << endl;\n\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn;*/\n\t\tfor (int i = 0; i < bdag.size(); i++) {\n\t\t\tcout << bdag[i]->lprint() << \" \";\n\t\t\tif (bdag[i]->getOtype() == OutType::FLOAT) {\n\t\t\t\tif (v(bdag[i], 0)->set) {\n\t\t\t\t\tcout << v(bdag[i], 0)->print() << endl;\n\t\t\t\t} else {\n\t\t\t\t\tcout << \"UNSET\" << endl;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (d(bdag[i], 0)->set) {\n\t\t\t\t\tcout << d(bdag[i], 0)->print() << endl;\n\t\t\t\t} else {\n\t\t\t\t\tcout << \"UNSET\" << endl;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tvirtual void printFull() {\n\t\tfor (int i = 0; i < bdag.size(); i++) {\n\t\t\tcout << bdag[i]->lprint() << endl;\n\t\t\tif (bdag[i]->getOtype() == OutType::FLOAT) {\n\t\t\t\tif (v(bdag[i],0)->set) {\n\t\t\t\t\tcout << v(bdag[i],0)->printFull() << endl;\n\t\t\t\t} else {\n\t\t\t\t\tcout << \"UNSET\" <<endl;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif(d(bdag[i],0)->set) {\n\t\t\t\t\tcout << d(bdag[i],0)->printFull() << endl;\n\t\t\t\t} else {\n\t\t\t\t\tcout << \"UNSET\" << endl;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (bdag[i]->type == bool_node::PLUS) {\n\t\t\t\tcout << v(bdag[i]->mother(),0)->getVal() << \" + \" << v(bdag[i]->father(), 0)->getVal() << endl;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tbool isFloat(bool_node& bn) {\n\t\treturn (bn.getOtype() == OutType::FLOAT);\n\t}\n\t\n\tbool isFloat(bool_node* bn) {\n\t\treturn (bn->getOtype() == OutType::FLOAT);\n\t}\n\t\n\tint getInputValue(bool_node& bn) {\n\t\tif (inputValues->hasValue(bn.id)) {\n\t\t\tint val = inputValues->getValue(bn.id);\n\t\t\treturn val;\n\t\t} else {\n\t\t\treturn DEFAULT_INP;\n\t\t}\n\t}\n\t\n\tint getInputValue(bool_node* bn) {\n\t\treturn getInputValue(*bn);\n\t}\n\n\n\tvoid doUfun(UFUN_node& node, ValueGrad* mval, ValueGrad* val);\n\t\n\tvoid copyNodes(bool_node& node, bool_node* m);\n\tdouble merge(bool_node* n, gsl_vector* grad);\n\n\tvoid mergePaths(vector<tuple<double, vector<tuple<int, int, int>>, Path*>>& mergedPaths);\n\tvoid getMergeNodesBinop(bool_node* n);\n\tvoid getMergeNodesUnop(bool_node* n, bool_node* m);\n\tvoid getMergeNodesArracc(bool_node* node);\n\tvoid getMergeNodes();\n\n\tvoid combineDistance(bool_node& node, int nodeid1, int idx1, int nodeid2, int idx2, double& dist, gsl_vector* dg_grad);\n\tvoid doPair(bool_node& node, int nodeid1, int idx1, int nodeid2, int idx2, double& val, gsl_vector* val_grad);\n\tvoid pairNodes(bool_node& node);\n\tvoid normalize(bool_node* n);\n\n};\n", "meta": {"hexsha": "edcd5a2df596100602b2c437d6e33e5c1547361c", "size": 10994, "ext": "h", "lang": "C", "max_stars_repo_path": "src/SketchSolver/NumericalSynthesis/SymbolicEvaluators/KLocalityAutoDiff.h", "max_stars_repo_name": "natebragg/sketch-backend", "max_stars_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_stars_repo_licenses": ["X11"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2020-08-20T14:54:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T00:28:40.000Z", "max_issues_repo_path": "src/SketchSolver/NumericalSynthesis/SymbolicEvaluators/KLocalityAutoDiff.h", "max_issues_repo_name": "natebragg/sketch-backend", "max_issues_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_issues_repo_licenses": ["X11"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-01T16:53:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T04:02:09.000Z", "max_forks_repo_path": "src/SketchSolver/NumericalSynthesis/SymbolicEvaluators/KLocalityAutoDiff.h", "max_forks_repo_name": "natebragg/sketch-backend", "max_forks_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_forks_repo_licenses": ["X11"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-04T20:47:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-06T01:45:04.000Z", "avg_line_length": 24.1626373626, "max_line_length": 120, "alphanum_fraction": 0.6181553575, "num_tokens": 3492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15817436862177234, "lm_q2_score": 0.01302049262720419, "lm_q1q2_score": 0.0020595082004524643}}
{"text": "/*\n   Copyright [2017-2021] [IBM Corporation]\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n       http://www.apache.org/licenses/LICENSE-2.0\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\n\n#ifndef _MCAS_HSTORE_POOL_MANAGER_H\n#define _MCAS_HSTORE_POOL_MANAGER_H\n\n#include <api/kvstore_itf.h> /* status_t */\n\n#include \"alloc_key.h\" /* AK_FORMAL */\n#include \"pool_error.h\"\n\n#include <common/logging.h> /* log_source */\n#include <common/string_view.h>\n#include <nupm/region_descriptor.h>\n#include <gsl/pointers>\n#include <sys/uio.h>\n#include <cstddef>\n#include <functional>\n#include <string>\n#include <system_error>\n\nstruct pool_path;\n\nstruct dax_manager;\n\ntemplate <typename Pool>\n  struct pool_manager\n    : protected common::log_source\n  {\n    using string_view = common::string_view;\n    pool_manager(unsigned debug_level_) : common::log_source(debug_level_) {}\n    virtual ~pool_manager() {}\n\n    virtual void pool_create_check(const std::size_t size_) = 0;\n\n    virtual void pool_close_check(const string_view) = 0;\n\n    virtual nupm::region_descriptor pool_get_regions(const Pool &) const = 0;\n\n    /*\n     * throws pool_error if create_region fails\n     */\n    virtual auto pool_create_1(\n      const pool_path &path_\n      , std::size_t size_\n    ) -> nupm::region_descriptor = 0;\n\n    virtual auto pool_create_2(\n      AK_FORMAL\n      const nupm::region_descriptor & rac\n      , component::IKVStore::flags_t flags\n      , std::size_t expected_obj_count\n    ) -> std::unique_ptr<Pool> = 0;\n\n    virtual auto pool_open_1(\n      const pool_path &path_\n    ) -> nupm::region_descriptor = 0;\n\n    virtual auto pool_open_2(\n      AK_FORMAL\n      const nupm::region_descriptor & access_\n      , component::IKVStore::flags_t flags_\n    ) -> std::unique_ptr<Pool> = 0;\n\n    virtual void pool_delete(const pool_path &path) = 0;\n    virtual const std::unique_ptr<dax_manager> & get_dax_manager() const = 0;\n  };\n\n#endif\n", "meta": {"hexsha": "f6725c1eeeabea3f1177eafcf223aff46d24c50c", "size": 2326, "ext": "h", "lang": "C", "max_stars_repo_path": "src/components/store/hstore/src/pool_manager.h", "max_stars_repo_name": "fQuinzan/mcas", "max_stars_repo_head_hexsha": "efaf438eb20cffa18b13f176c74a2b3153f89c07", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/components/store/hstore/src/pool_manager.h", "max_issues_repo_name": "fQuinzan/mcas", "max_issues_repo_head_hexsha": "efaf438eb20cffa18b13f176c74a2b3153f89c07", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/components/store/hstore/src/pool_manager.h", "max_forks_repo_name": "fQuinzan/mcas", "max_forks_repo_head_hexsha": "efaf438eb20cffa18b13f176c74a2b3153f89c07", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7160493827, "max_line_length": 77, "alphanum_fraction": 0.7110920034, "num_tokens": 583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.0769608420473065, "lm_q2_score": 0.02675928376755457, "lm_q1q2_score": 0.0020594170113338198}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\n * Contact: lymastee@hotmail.com\n *\n * This file is part of the gslib project.\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n#pragma once\n\n#ifndef fsysdwrite_c5ab9cfc_e66a_40b6_8ea1_29b3bde4f5e3_h\n#define fsysdwrite_c5ab9cfc_e66a_40b6_8ea1_29b3bde4f5e3_h\n\n#include <d3d11.h>\n#include <d3d10_1.h>\n#include <dxgi.h>\n#include <d2d1.h>\n#include <dwrite.h>\n#include <gslib/std.h>\n#include <ariel/sysop.h>\n#include <ariel/rendersysd3d11.h>\n\n__ariel_begin__\n\ntypedef unordered_map<font, IDWriteTextFormat*> dwrite_font_map;\n\nclass fsys_dwrite:\n    public fontsys\n{\npublic:\n    fsys_dwrite();\n    virtual ~fsys_dwrite();\n    virtual void initialize() override;\n    virtual void set_font(const font& f) override;\n    virtual bool query_size(const gchar* str, int& w, int& h, int len = -1) override;\n    virtual bool create_text_image(image& img, const gchar* str, int x, int y, const color& cr, int len = -1) override;\n    virtual bool create_text_texture(texture2d** tex, const gchar* str, int margin, const color& cr, int len = -1) override;\n    virtual void draw(image& img, const gchar* str, int x, int y, const color& cr, int len = -1) override;\n\nprotected:\n    dwrite_font_map                     _font_map;\n    IDWriteTextFormat*                  _current_font;\n    com_ptr<ID3D11Device>               _dev11;\n    com_ptr<ID3D10Device1>              _dev101;\n    com_ptr<IDWriteFactory>             _dwfactory;\n    com_ptr<ID2D1Factory>               _d2dfactory;\n\nprotected:\n    void destroy_font_map();\n};\n\n__ariel_end__\n\n#endif\n", "meta": {"hexsha": "7497fb28da675c1e89f36bb62d8d0c1c91bee8b0", "size": 2628, "ext": "h", "lang": "C", "max_stars_repo_path": "include/ariel/fsysdwrite.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/ariel/fsysdwrite.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ariel/fsysdwrite.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 36.5, "max_line_length": 124, "alphanum_fraction": 0.7226027397, "num_tokens": 695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07696083569602614, "lm_q2_score": 0.02675928250631317, "lm_q1q2_score": 0.0020594167443119147}}
{"text": "#pragma once\n\n// View structures\n// STATUS: prototype, NSC\n\n#include <vector>\n\n#include <gsl.h>\n\nnamespace duck {\n/* span<T> represents a reference to a segment of a T array.\n * Equivalent to a (T* base, int len).\n */\nusing gsl::span;\n\n/* string_view: Const reference (pointer) to a sequence of char.\n * Does not own the data, only points to it.\n * The char sequence may not be null terminated.\n *\n * std::string_view exists in C++17, but not before sadly.\n */\nusing string_view = gsl::cstring_span;\n\nusing gsl::to_string; // Create new std::string from string_view\n\nbool is_prefix_of (string_view prefix, string_view str);\nbool is_prefix_of (char prefix, string_view str);\n\n// Split at separator. Does not remove empty parts, does not trim whitespace.\nstd::vector<string_view> split (char separator, string_view text);\n} // namespace duck\n", "meta": {"hexsha": "06e9eb56421d44de0a48fc6fce247e78471b9492", "size": 840, "ext": "h", "lang": "C", "max_stars_repo_path": "cpp/duck/view.h", "max_stars_repo_name": "lereldarion/duck", "max_stars_repo_head_hexsha": "dc419c0ec496c1d7e809b6f1b473e03a709c75bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp/duck/view.h", "max_issues_repo_name": "lereldarion/duck", "max_issues_repo_head_hexsha": "dc419c0ec496c1d7e809b6f1b473e03a709c75bd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/duck/view.h", "max_forks_repo_name": "lereldarion/duck", "max_forks_repo_head_hexsha": "dc419c0ec496c1d7e809b6f1b473e03a709c75bd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.25, "max_line_length": 77, "alphanum_fraction": 0.7285714286, "num_tokens": 202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.0481367738476972, "lm_q2_score": 0.042722197698843806, "lm_q1q2_score": 0.0020565087689058538}}
{"text": "/*  Copyright (C) 2006 Imperial College London and others.\n    \n    Please see the AUTHORS file in the main source directory for a full list\n    of copyright holders.\n\n    Prof. C Pain\n    Applied Modelling and Computation Group\n    Department of Earth Science and Engineering\n    Imperial College London\n\n    amcgsoftware@imperial.ac.uk\n    \n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation,\n    version 2.1 of the License.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307\n    USA\n*/\n\n#ifndef COMMAND_LINE_OPTIONS_H\n#define COMMAND_LINE_OPTIONS_H\n#include \"confdefs.h\"\n#include \"version.h\"\n\n#include \"Tokenize.h\"\n\n#ifdef _AIX\n#include <unistd.h>\n#else\n#include <getopt.h>\n#endif\n\n#ifdef HAVE_MPI\n#include <mpi.h>\n#endif\n\n#ifdef HAVE_PETSC\n#include <petsc.h>\n#endif\n\n#include <signal.h>\n\n#include <cstdlib>\n#include <iostream>\n#include <map>\n#include <sstream>\n#include <string>\n#include <vector>\n#include \"fmangle.h\"\n\nextern std::map<std::string, std::string> fl_command_line_options;\n\nvoid ParseArguments(int argc, char** argv);\nvoid PetscInit(int argc, char** argv);\nvoid print_version(std::ostream& stream = std::cerr);\nvoid qg_usage(char *cmd);\n\nextern \"C\" {\n  void set_global_debug_level_fc(int *val);\n}\n\n#endif\n", "meta": {"hexsha": "23ba4c54b646583798b8e2d61a3e0dc1d82c850b", "size": 1779, "ext": "h", "lang": "C", "max_stars_repo_path": "software/multifluids_icferst/include/qg_usage.h", "max_stars_repo_name": "msc-acse/acse-9-independent-research-project-Wade003", "max_stars_repo_head_hexsha": "cfcba990d52ccf535171cf54c0a91b184db6f276", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-05-11T02:39:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-11T03:08:38.000Z", "max_issues_repo_path": "software/multifluids_icferst/include/qg_usage.h", "max_issues_repo_name": "msc-acse/acse-9-independent-research-project-Wade003", "max_issues_repo_head_hexsha": "cfcba990d52ccf535171cf54c0a91b184db6f276", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "software/multifluids_icferst/include/qg_usage.h", "max_forks_repo_name": "msc-acse/acse-9-independent-research-project-Wade003", "max_forks_repo_head_hexsha": "cfcba990d52ccf535171cf54c0a91b184db6f276", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-05-21T22:50:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-28T17:16:31.000Z", "avg_line_length": 24.7083333333, "max_line_length": 76, "alphanum_fraction": 0.7358066329, "num_tokens": 417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.0803574622150194, "lm_q2_score": 0.02556521452648954, "lm_q1q2_score": 0.002054355760331248}}
{"text": "/*\n   Copyright [2017-2021] [IBM Corporation]\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n       http://www.apache.org/licenses/LICENSE-2.0\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\n\n#ifndef _MCAS_HSTORE_NUPM_H\n#define _MCAS_HSTORE_NUPM_H\n\n#include \"pool_manager.h\"\n\n#include \"alloc_key.h\" /* AK_FORMAL */\n#include \"hstore_nupm_types.h\"\n#include \"hstore_open_pool.h\"\n#include \"persister_nupm.h\"\n\n#include <common/string_view.h>\n#include <gsl/pointers>\n\n#include <cstring> /* strerror */\n\n#include <cinttypes> /* PRIx64 */\n#include <cstdlib> /* getenv */\n\nstruct dax_manager;\n\ntemplate <typename PersistData, typename Heap>\n  struct region;\n\n#pragma GCC diagnostic push\n/* Note: making enable_shared_from_this private avoids the non-virtual-dtor error but\n * generates a different error with no error text (G++ 5.4.0)\n */\n#pragma GCC diagnostic ignored \"-Wnon-virtual-dtor\"\n\n/* Region is region<persist_data_t, heap_rc>, Table is hstore::table_t Allocator is table_t::allocator_type, LockType is hstore::locK_type_t */\ntemplate <typename Region, typename Table, typename Allocator, typename LockType>\n  struct hstore_nupm\n    : public pool_manager<::open_pool<non_owner<Region>>>\n  {\n    using region_type = Region;\n  private:\n    using table_t = Table;\n    using allocator_t = Allocator;\n    using lock_type_t = LockType;\n    using string_view = common::string_view;\n  public:\n    using open_pool_handle = ::open_pool<non_owner<region_type>>;\n    using base = pool_manager<open_pool_handle>;\n  private:\n    std::unique_ptr<dax_manager> _dax_manager;\n    unsigned _numa_node;\n\n    static unsigned name_to_numa_node(const string_view name);\n  public:\n    hstore_nupm(unsigned debug_level_, const string_view, const string_view name_, std::unique_ptr<dax_manager> mgr_);\n\n    virtual ~hstore_nupm();\n\n    const std::unique_ptr<dax_manager> & get_dax_manager() const override { return _dax_manager; }\n    void pool_create_check(std::size_t) override;\n\n    auto pool_create_1(\n      const pool_path &path_\n      , std::size_t size_\n    ) -> nupm::region_descriptor override;\n\n    auto pool_create_2(\n      AK_FORMAL\n      const nupm::region_descriptor &rac\n      , component::IKVStore::flags_t flags\n      , std::size_t expected_obj_count\n    ) -> std::unique_ptr<open_pool_handle> override;\n\n    nupm::region_descriptor pool_open_1(\n      const pool_path &path_\n    ) override;\n\n    auto pool_open_2(\n      AK_FORMAL\n      const nupm::region_descriptor & v_\n      , component::IKVStore::flags_t flags_\n    ) -> std::unique_ptr<open_pool_handle> override;\n\n    void pool_close_check(const string_view) override;\n\n    void pool_delete(const pool_path &path_) override;\n\n    /* ERROR: want get_pool_regions(<proper type>, std::vector<::iovec>&) */\n    nupm::region_descriptor pool_get_regions(const open_pool_handle &) const override;\n  };\n#pragma GCC diagnostic pop\n\n#include \"hstore_nupm.tcc\"\n\n#endif\n", "meta": {"hexsha": "456e92b13b32370cc1b2e4b8c8544c8ab30adf51", "size": 3313, "ext": "h", "lang": "C", "max_stars_repo_path": "src/components/store/hstore/src/hstore_nupm.h", "max_stars_repo_name": "fQuinzan/mcas", "max_stars_repo_head_hexsha": "efaf438eb20cffa18b13f176c74a2b3153f89c07", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/components/store/hstore/src/hstore_nupm.h", "max_issues_repo_name": "fQuinzan/mcas", "max_issues_repo_head_hexsha": "efaf438eb20cffa18b13f176c74a2b3153f89c07", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/components/store/hstore/src/hstore_nupm.h", "max_forks_repo_name": "fQuinzan/mcas", "max_forks_repo_head_hexsha": "efaf438eb20cffa18b13f176c74a2b3153f89c07", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5523809524, "max_line_length": 143, "alphanum_fraction": 0.7343797163, "num_tokens": 823, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.083890393281755, "lm_q2_score": 0.024423092850079244, "lm_q1q2_score": 0.0020488628643499664}}
{"text": "#pragma once\n\n#include \"internal/Buffer.h\"\n#include <gsl/span>\n\nnamespace ge::gl4\n{\n\nusing namespace gl45;\n\nclass BufferView\n{\npublic:\n\tBufferView(Buffer &buffer, GLenum type, gsl::span<uint8_t> range);\n\n\t// Mapping Functions\n\tauto map(BufferAccessMask accessFlags) -> void *;\n\tvoid flush();\n\tvoid unmap();\n\n\tvoid bindToIndex(GLuint index);\n\tstatic void unbind(GLenum target, GLuint index);\n\n\tauto getBuffer() const -> Buffer &;\n\n\tconst GLenum type;\n\tconst gsl::span<uint8_t> range;\nprivate:\n\tBuffer *buffer_;\n};\n\n}", "meta": {"hexsha": "1775ea61a6ef898d2a243b33573491191d2f016d", "size": 515, "ext": "h", "lang": "C", "max_stars_repo_path": "src/Renderer/BufferView.h", "max_stars_repo_name": "mmha/gravity", "max_stars_repo_head_hexsha": "5499b77cde89589abefa88618205a0db5f342443", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Renderer/BufferView.h", "max_issues_repo_name": "mmha/gravity", "max_issues_repo_head_hexsha": "5499b77cde89589abefa88618205a0db5f342443", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Renderer/BufferView.h", "max_forks_repo_name": "mmha/gravity", "max_forks_repo_head_hexsha": "5499b77cde89589abefa88618205a0db5f342443", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.09375, "max_line_length": 67, "alphanum_fraction": 0.7184466019, "num_tokens": 127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.10230469694465663, "lm_q2_score": 0.020023440448810777, "lm_q1q2_score": 0.002048492006904966}}
{"text": "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\n#pragma once\n\n#include <gsl/gsl>\n\nnamespace onnxruntime {\n// Inspired by Fekir's Blog https://fekir.info/post/span-the-missing-constructor/\n// Used under MIT license\n\n// Use AsSpan for less typing on any container including initializer list to create a span\n// (unnamed, untyped initializer list does not automatically convert to gsl::span).\n// {1, 2, 3} as such does not have a type \n// (see https://scottmeyers.blogspot.com/2014/03/if-braced-initializers-have-no-type-why.html)\n// \n//   Example: AsSpan({1, 2, 3}) results in gsl::span<const int>\n// \n// The above would deduce to std::initializer_list<int> and the result is gsl::span<const int>\n//\n// AsSpan<int64_t>({1, 2, 3}) produces gsl::span<const int64_t>\n// \n// We can also do std::array<int64_t, 3>{1, 2, 3} that can be automatically converted to span\n// without memory allocation.\n//\n// If type conversion is not required, then for C++17 std::array template parameters are\n// auto-deduced. Example: std::array{1, 2, 3}.\n// We are aiming at not allocating memory dynamically.\n\nnamespace details {\ntemplate <class P>\nconstexpr auto AsSpanImpl(P* p, size_t s) {\n  return gsl::span<P>(p, s);\n}\n}  // namespace details\n\ntemplate <class C>\nconstexpr auto AsSpan(C& c) {\n  return details::AsSpanImpl(c.data(), c.size());\n}\n \ntemplate <class C>\nconstexpr auto AsSpan(const C& c) {\n  return details::AsSpanImpl(c.data(), c.size());\n}\n\ntemplate <class C>\nconstexpr auto AsSpan(C&& c) {\n  return details::AsSpanImpl(c.data(), c.size());\n}\n\ntemplate <class T>\nconstexpr auto AsSpan(std::initializer_list<T> c) {\n  return details::AsSpanImpl(c.begin(), c.size());\n}\n\ntemplate <class T, size_t N>\nconstexpr auto AsSpan(T (&arr)[N]) {\n  return details::AsSpanImpl(arr, N);\n}\n\ntemplate <class T, size_t N>\nconstexpr auto AsSpan(const T (&arr)[N]) {\n  return details::AsSpanImpl(arr, N);\n}\n\n}", "meta": {"hexsha": "998fc6e71dcbb814ca642ab8f3177b93aad88297", "size": 1933, "ext": "h", "lang": "C", "max_stars_repo_path": "include/onnxruntime/core/common/span_utils.h", "max_stars_repo_name": "SiriusKY/onnxruntime", "max_stars_repo_head_hexsha": "3c5853dcbc9d5dda2476afa8c6105802d2b8e53d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 669.0, "max_stars_repo_stars_event_min_datetime": "2018-12-03T22:00:31.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-06T19:42:49.000Z", "max_issues_repo_path": "include/onnxruntime/core/common/span_utils.h", "max_issues_repo_name": "SiriusKY/onnxruntime", "max_issues_repo_head_hexsha": "3c5853dcbc9d5dda2476afa8c6105802d2b8e53d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 440.0, "max_issues_repo_issues_event_min_datetime": "2018-12-03T21:09:56.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-06T20:47:23.000Z", "max_forks_repo_path": "include/onnxruntime/core/common/span_utils.h", "max_forks_repo_name": "SiriusKY/onnxruntime", "max_forks_repo_head_hexsha": "3c5853dcbc9d5dda2476afa8c6105802d2b8e53d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 140.0, "max_forks_repo_forks_event_min_datetime": "2018-12-03T21:15:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-06T18:02:36.000Z", "avg_line_length": 28.8507462687, "max_line_length": 94, "alphanum_fraction": 0.7030522504, "num_tokens": 533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06465349376296874, "lm_q2_score": 0.03161876806709868, "lm_q1q2_score": 0.0020442638240189197}}
{"text": "/* Author:  Lisandro Dalcin   */\n/* Contact: dalcinl@gmail.com */\n\n#ifndef PETSC4PY_H\n#define PETSC4PY_H\n\n#include <Python.h>\n#include <petsc.h>\n#include \"petsc4py.PETSc_api.h\"\n\nstatic int import_petsc4py(void) {\n  if (import_petsc4py__PETSc() < 0) goto bad;\n  return 0;\n bad:\n  return -1;\n}\n\n#endif /* !PETSC4PY_H */\n", "meta": {"hexsha": "45930b6275099b806c5a81bd3022850d82634cb5", "size": 318, "ext": "h", "lang": "C", "max_stars_repo_path": "src/include/petsc4py/petsc4py.h", "max_stars_repo_name": "underworldcode/petsc4py", "max_stars_repo_head_hexsha": "fdfdd79be39b8cbe95cf57010f29a6cb2ef463a6", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/include/petsc4py/petsc4py.h", "max_issues_repo_name": "underworldcode/petsc4py", "max_issues_repo_head_hexsha": "fdfdd79be39b8cbe95cf57010f29a6cb2ef463a6", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/include/petsc4py/petsc4py.h", "max_forks_repo_name": "underworldcode/petsc4py", "max_forks_repo_head_hexsha": "fdfdd79be39b8cbe95cf57010f29a6cb2ef463a6", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.7368421053, "max_line_length": 45, "alphanum_fraction": 0.6855345912, "num_tokens": 111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.0656048374590693, "lm_q2_score": 0.031143829860339416, "lm_q1q2_score": 0.0020431858958404763}}
{"text": "\n#if !defined(MAIN_H_INCLUDED)\n#define MAIN_H_INCLUDED\n\n#include \"Exceptions.h\"\n\n#include <cstdlib>\n#include <filesystem>\n#include <gsl/gsl>\n#include <iostream>\n#include <stdexcept>\n\ntemplate <typename T>\nint commonMain(size_t argCount, const char*const*const argList)\n{\n\tusing ::std::filesystem::path;\n\tusing ::gsl::make_span;\n\tusing ::std::cout;\n\tusing ::std::endl;\n\n\tauto exitCode{EXIT_FAILURE};\n\ttry\n\t{\n\t\t// Pass the argument list, not including the program name (0th element):\n\t\tT program{make_span(argList + 1, argCount - 1)};\n\t\texitCode = program.run();\n\t}\n\tcatch (const CmdLineError& ex)\n\t{\n\t\texitCode = T::usage(cout, path{argList[0]}.stem().generic_string(), ex.what());\n\t}\n\tcatch (const ::std::exception& ex)\n\t{\n\t\tcout << endl\n\t\t\t<< \"Exception of type \" << typeid(ex).name() << endl\n\t\t\t<< \"   \" << ex.what() << endl\n\t\t\t<< endl;\n\t}\n\treturn exitCode;\n}\n\n#endif // MAIN_H_INCLUDED\n", "meta": {"hexsha": "623b5ae7ec39885b659e655788be214ff6e37648", "size": 889, "ext": "h", "lang": "C", "max_stars_repo_path": "main.h", "max_stars_repo_name": "IanEmmons/CmdLineUtil", "max_stars_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.h", "max_issues_repo_name": "IanEmmons/CmdLineUtil", "max_issues_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.h", "max_forks_repo_name": "IanEmmons/CmdLineUtil", "max_forks_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.6744186047, "max_line_length": 81, "alphanum_fraction": 0.6681664792, "num_tokens": 253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08882028516430054, "lm_q2_score": 0.022977367986522567, "lm_q1q2_score": 0.0020408563768880045}}
{"text": "#pragma once\n\n#include <cstdint>\n#include <string>\n#include <vector>\n\n#include <gsl/span>\n\nnamespace terminal_editor {\n\n/// Returns name of passed control character, or nullptr if given byte was not recognized.\n/// ISO 30112 defines POSIX control characters as Unicode characters U+0000..U+001F, U+007F..U+009F, U+2028, and U+2029 (Unicode classes Cc, Zl, and Zp) \"\n/// See also: https://en.wikipedia.org/wiki/C0_and_C1_control_codes\n/// @param codePoint    Code point for which name to return.\nconst char* controlCharacterName(uint32_t codePoint);\n\n/// Describes return value of getFirstCodePoint() function.\nstruct CodePointInfo {\n    bool valid;                          ///< True if valid code point was decoded. False otherwise.\n    gsl::span<const char> consumedInput; ///< Bytes consumed from the input data. Length will be from 1 to 6.\n    std::string info;                    ///< Arbitrary information about consumed bytes. If 'valid' is false will contain error information.\n    uint32_t codePoint;                  ///< Decoded code point. Valid only if 'valid' is true.\n};\n\n/// Figures out what grapeheme is at the begining of data and returns it.\n/// See: https://pl.wikipedia.org/wiki/UTF-8#Spos%C3%B3b_kodowania\n/// @note All invalid byte sequences will be rendered as hex representations, with detailed explanation why it is invalid.\n///       All control characters will be rendered as symbolic replacements.\n///       Tab characters will be rendered as symbolic replacement.\n/// @param data     Input string. It is assumed to be in UTF-8, but can contain invalid characters (which will be rendered as special Graphemes).\n/// @param Returns number of bytes from input consumed.\nCodePointInfo getFirstCodePoint(gsl::span<const char> data);\n\n/// Parses a line of text into a list of CodePointInfos.\nstd::vector<CodePointInfo> parseLine(gsl::span<const char> inputData);\n\n/// Analyzes given input data.\n/// @param inputData     Input string. It is assumed to be in UTF-8, but can contain invalid characters (which will be annotated specially).\n/// @return Valid UTF-8 string that describes what original string contains.\nstd::string analyzeData(gsl::span<const char> inputData);\n\n/// Appends UTF-8 representation of given code point to a string.\n/// @todo Move to some string utilities.\n/// @param text         Text to append code point to.\n/// @param codePoint    UTF-32 code point to append.\nvoid appendCodePoint(std::string& text, uint32_t codePoint);\n\n/// Appends UTF-8 representation of given code point to an output stream.\n/// @todo Move to some string utilities.\n/// @param os           Output stream to append code point to.\n/// @param codePoint    UTF-32 code point to append.\nvoid appendCodePoint(std::ostream& os, uint32_t codePoint);\n\n} // namespace terminal_editor\n", "meta": {"hexsha": "b4c4f15bbd785d7ac47ba5ed8717fff3cd1fc0ed", "size": 2794, "ext": "h", "lang": "C", "max_stars_repo_path": "editorlib/text_parser.h", "max_stars_repo_name": "Zbyl/terminal-editor", "max_stars_repo_head_hexsha": "375ac936f09543bab9c01fcb5a2dc8de9af83a58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "editorlib/text_parser.h", "max_issues_repo_name": "Zbyl/terminal-editor", "max_issues_repo_head_hexsha": "375ac936f09543bab9c01fcb5a2dc8de9af83a58", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "editorlib/text_parser.h", "max_forks_repo_name": "Zbyl/terminal-editor", "max_forks_repo_head_hexsha": "375ac936f09543bab9c01fcb5a2dc8de9af83a58", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-12-21T00:37:06.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-21T00:37:06.000Z", "avg_line_length": 50.8, "max_line_length": 154, "alphanum_fraction": 0.7236936292, "num_tokens": 641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10669060246682488, "lm_q2_score": 0.019124036017147416, "lm_q1q2_score": 0.002040354924266716}}
{"text": "#pragma once\n\n#include <memory>\n#include <gsl/span>\n\n#include \"halley/time/halleytime.h\"\n#include \"../session/network_session.h\"\n#include \"entity_network_remote_peer.h\"\n#include \"halley/bytes/serialization_dictionary.h\"\n#include \"halley/entity/system.h\"\n#include \"halley/entity/world.h\"\n\nnamespace Halley {\n\tclass EntityFactory;\n\tclass Resources;\n\tclass World;\n\tclass NetworkSession;\n\n\tclass EntitySessionSharedData : public SharedData {\n\tpublic:\n\t\t\n\t};\n\n\tclass EntityClientSharedData : public SharedData {\n\tpublic:\n\t\tstd::optional<Rect4i> viewRect;\n\n\t\tvoid serialize(Serializer& s) const override;\n\t\tvoid deserialize(Deserializer& s) override;\n\t};\n\n\tclass EntityNetworkSession : NetworkSession::IListener, NetworkSession::ISharedDataHandler, public IWorldNetworkInterface {\n    public:\n\t\tclass IEntityNetworkSessionListener {\n\t\tpublic:\n\t\t\tvirtual ~IEntityNetworkSessionListener() = default;\n\t\t\tvirtual void onStartSession(NetworkSession::PeerId myPeerId) = 0;\n\t\t\tvirtual void onRemoteEntityCreated(EntityRef entity, NetworkSession::PeerId peerId) {}\n\t\t\tvirtual void setupInterpolators(DataInterpolatorSet& interpolatorSet, EntityRef entity, bool remote) = 0;\n\t\t\tvirtual bool isEntityInView(EntityRef entity, const EntityClientSharedData& clientData) = 0;\n\t\t};\n\t\t\n\t\tEntityNetworkSession(std::shared_ptr<NetworkSession> session, Resources& resources, std::set<String> ignoreComponents, IEntityNetworkSessionListener* listener);\n\t\t~EntityNetworkSession() override;\n\n\t\tvoid setWorld(World& world, SystemMessageBridge bridge);\n\t\t\n\t\tvoid sendUpdates(Time t, Rect4i viewRect, gsl::span<const std::pair<EntityId, uint8_t>> entityIds); // Takes pairs of entity id and owner peer id\n\t\tvoid receiveUpdates();\n\n\t\tWorld& getWorld() const;\n\t\tEntityFactory& getFactory() const;\n\t\tNetworkSession& getSession() const;\n\t\tbool hasWorld() const;\n\n\t\tconst EntityFactory::SerializationOptions& getEntitySerializationOptions() const;\n\t\tconst EntityDataDelta::Options& getEntityDeltaOptions() const;\n\t\tconst SerializerOptions& getByteSerializationOptions() const;\n\t\tSerializationDictionary& getSerializationDictionary();\n\n\t\tTime getMinSendInterval() const;\n\n\t\tvoid onRemoteEntityCreated(EntityRef entity, NetworkSession::PeerId peerId);\n\t\tvoid requestSetupInterpolators(DataInterpolatorSet& interpolatorSet, EntityRef entity, bool remote);\n\t\tvoid setupOutboundInterpolators(EntityRef entity);\n\n\t\tbool isReadyToStart() const;\n\t\tbool isEntityInView(EntityRef entity, const EntityClientSharedData& clientData) const;\n\n\t\tVector<Rect4i> getRemoteViewPorts() const;\n\n\t\tbool isHost() override;\n\t\tbool isRemote(ConstEntityRef entity) const override;\n\t\tvoid sendEntityMessage(EntityRef entity, int messageType, Bytes messageData) override;\n\t\tvoid sendSystemMessage(String targetSystem, int messageType, Bytes messageData, SystemMessageDestination destination, SystemMessageCallback callback) override;\n\n\t\tvoid sendToAll(EntityNetworkMessage msg);\n\t\tvoid sendToPeer(EntityNetworkMessage msg, NetworkSession::PeerId peerId);\n\n\tprotected:\n\t\tvoid onStartSession(NetworkSession::PeerId myPeerId) override;\n\t\tvoid onPeerConnected(NetworkSession::PeerId peerId) override;\n\t\tvoid onPeerDisconnected(NetworkSession::PeerId peerId) override;\n\t\tstd::unique_ptr<SharedData> makeSessionSharedData() override;\n\t\tstd::unique_ptr<SharedData> makePeerSharedData() override;\n\t\n\tprivate:\n\t\tstruct QueuedMessage {\n\t\t\tNetworkSession::PeerId fromPeerId;\n\t\t\tEntityNetworkMessage message;\n\t\t};\n\n\t\tstruct PendingSysMsgResponse {\n\t\t\tSystemMessageCallback callback;\n\t\t};\n\t\t\n\t\tResources& resources;\n\t\tstd::shared_ptr<EntityFactory> factory;\n\t\tIEntityNetworkSessionListener* listener = nullptr;\n\t\tSystemMessageBridge messageBridge;\n\t\tuint32_t systemMessageId = 0;\n\t\tHashMap<uint32_t, PendingSysMsgResponse>  pendingSysMsgResponses;\n\t\t\n\t\tEntityFactory::SerializationOptions entitySerializationOptions;\n\t\tEntityDataDelta::Options deltaOptions;\n\t\tSerializerOptions byteSerializationOptions;\n\t\tSerializationDictionary serializationDictionary;\n\n\t\tstd::shared_ptr<NetworkSession> session;\n\t\tVector<EntityNetworkRemotePeer> peers;\n\n\t\tVector<QueuedMessage> queuedPackets;\n\n\t\tHashMap<int, Vector<EntityNetworkMessage>> outbox;\n\n\t\tbool readyToStart = false;\n\n\t\tbool canProcessMessage(const EntityNetworkMessage& msg) const;\n\t\tvoid processMessage(NetworkSession::PeerId fromPeerId, EntityNetworkMessage msg);\n\t\tvoid onReceiveEntityUpdate(NetworkSession::PeerId fromPeerId, EntityNetworkMessage msg);\n\t\tvoid onReceiveReady(NetworkSession::PeerId fromPeerId, const EntityNetworkMessageReadyToStart& msg);\n\t\tvoid onReceiveMessageToEntity(NetworkSession::PeerId fromPeerId, const EntityNetworkMessageEntityMsg& msg);\n\t\tvoid onReceiveSystemMessage(NetworkSession::PeerId fromPeerId, const EntityNetworkMessageSystemMsg& msg);\n\t\tvoid onReceiveSystemMessageResponse(NetworkSession::PeerId fromPeerId, const EntityNetworkMessageSystemMsgResponse& msg);\n\n\t\tvoid sendMessages();\n\t\t\n\t\tvoid setupDictionary();\n\t};\n}\n", "meta": {"hexsha": "cdb33cc917e721893a2577db710fb1a3a18442ec", "size": 4932, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engine/net/include/halley/net/entity/entity_network_session.h", "max_stars_repo_name": "amrezzd/halley", "max_stars_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/engine/net/include/halley/net/entity/entity_network_session.h", "max_issues_repo_name": "amrezzd/halley", "max_issues_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engine/net/include/halley/net/entity/entity_network_session.h", "max_forks_repo_name": "amrezzd/halley", "max_forks_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.6488549618, "max_line_length": 162, "alphanum_fraction": 0.8051500406, "num_tokens": 1109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10818895456207034, "lm_q2_score": 0.018833129339734182, "lm_q1q2_score": 0.002037536574398095}}
{"text": "#pragma once\n#include <vector>\n#include <gsl/gsl>\n#include \"halley/utils/utils.h\"\n\nnamespace Halley\n{\n\tclass NetworkPacketBase\n\t{\n\tpublic:\n\t\tsize_t copyTo(gsl::span<gsl::byte> dst) const;\n\t\tsize_t getSize() const;\n\t\tgsl::span<const gsl::byte> getBytes() const;\n\n\t\tNetworkPacketBase(NetworkPacketBase&& other) = delete;\n\t\tNetworkPacketBase& operator=(NetworkPacketBase&& other) = delete;\n\n\tprotected:\n\t\tNetworkPacketBase();\n\t\tNetworkPacketBase(gsl::span<const gsl::byte> data, size_t prePadding);\n\n\t\tsize_t dataStart;\n\t\tstd::vector<gsl::byte> data;\n\t};\n\n\tclass OutboundNetworkPacket : public NetworkPacketBase\n\t{\n\tpublic:\n\t\tOutboundNetworkPacket(const OutboundNetworkPacket& other);\n\t\texplicit OutboundNetworkPacket(OutboundNetworkPacket&& other) noexcept;\n\t\texplicit OutboundNetworkPacket(gsl::span<const gsl::byte> data);\n\t\texplicit OutboundNetworkPacket(const Bytes& data);\n\t\t\n\t\tvoid addHeader(gsl::span<const gsl::byte> src);\n\n\t\ttemplate <typename T>\n\t\tvoid addHeader(const T& h)\n\t\t{\n\t\t\taddHeader(gsl::as_bytes(gsl::span<const T>(&h, 1)));\n\t\t}\n\n\t\tOutboundNetworkPacket& operator=(OutboundNetworkPacket&& other) noexcept;\n\t};\n\n\tclass InboundNetworkPacket : public NetworkPacketBase\n\t{\n\tpublic:\n\t\tInboundNetworkPacket();\n\t\texplicit InboundNetworkPacket(InboundNetworkPacket&& other);\n\t\texplicit InboundNetworkPacket(gsl::span<const gsl::byte> data);\n\t\tvoid extractHeader(gsl::span<gsl::byte> dst);\n\n\t\ttemplate <typename T>\n\t\tvoid extractHeader(T& h)\n\t\t{\n\t\t\textractHeader(gsl::as_writeable_bytes(gsl::span<T>(&h, 1)));\n\t\t}\n\n\t\tInboundNetworkPacket& operator=(InboundNetworkPacket&& other);\n\t};\n}\n", "meta": {"hexsha": "eba42788a5c886ee17d496040c8a2c7a6810b8e5", "size": 1595, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engine/net/include/halley/net/connection/network_packet.h", "max_stars_repo_name": "sunhay/halley", "max_stars_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T20:23:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T20:23:45.000Z", "max_issues_repo_path": "src/engine/net/include/halley/net/connection/network_packet.h", "max_issues_repo_name": "sunhay/halley", "max_issues_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engine/net/include/halley/net/connection/network_packet.h", "max_forks_repo_name": "sunhay/halley", "max_forks_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7258064516, "max_line_length": 75, "alphanum_fraction": 0.7410658307, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11757213354550881, "lm_q2_score": 0.01717670740864591, "lm_q1q2_score": 0.002019502137321448}}
{"text": "// MIT License\n//\n// Copyright (c) 2020 SunnyCase\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n#pragma once\n#include <chino/ddk/kernel.h>\n#include <cstdint>\n#include <gsl/gsl-lite.hpp>\n\nnamespace chino::arch\n{\n// No asynchronous interrupt is supported by this target\n// Only save callee saved registers in context\nstruct armv7m_thread_context\n{\n    uintptr_t r4;\n    uintptr_t r5;\n    uintptr_t r6;\n    uintptr_t r7;\n    uintptr_t r8;\n    uintptr_t r9;\n    uintptr_t r10;\n    uintptr_t r11;\n    uintptr_t lr;\n    uintptr_t sp;\n    uintptr_t stack_bottom;\n};\n\nusing thread_context_t = armv7m_thread_context;\n\nstruct armv7m_arch\n{\n    static constexpr size_t ALLOCATE_ALIGNMENT = 8;\n\n    static uint32_t current_processor() noexcept { return 0; }\n    static void yield_processor() noexcept;\n\n    static uintptr_t disable_irq() noexcept;\n    static void restore_irq(uintptr_t state) noexcept;\n\n    static void init_thread_context(thread_context_t &context, gsl::span<uintptr_t> stack, kernel::thread_thunk_t start, void *arg0, void *arg1) noexcept;\n    [[noreturn]] static void start_schedule(thread_context_t &context) noexcept;\n    static void yield(thread_context_t &old_context, thread_context_t &new_context) noexcept;\n\n    static void init_stack_check() noexcept;\n};\n\nusing arch_t = armv7m_arch;\n}\n", "meta": {"hexsha": "674a5f4c6e1e129a86f0af45b1e38f96e4cd44f3", "size": 2331, "ext": "h", "lang": "C", "max_stars_repo_path": "src/hal/include/chino/arch/arm/armv7-m/arch.h", "max_stars_repo_name": "chino-os/chino-os", "max_stars_repo_head_hexsha": "e4b444983a059231636b81dc5f33206e16a859c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2018-04-28T09:50:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T11:42:23.000Z", "max_issues_repo_path": "src/hal/include/chino/arch/arm/armv7-m/arch.h", "max_issues_repo_name": "dotnetGame/chino-os", "max_issues_repo_head_hexsha": "e4b444983a059231636b81dc5f33206e16a859c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2018-05-15T02:15:33.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-30T14:46:51.000Z", "max_forks_repo_path": "src/hal/include/chino/arch/arm/armv7-m/arch.h", "max_forks_repo_name": "dotnetGame/chino-os", "max_forks_repo_head_hexsha": "e4b444983a059231636b81dc5f33206e16a859c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2018-05-18T03:54:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T10:14:07.000Z", "avg_line_length": 34.7910447761, "max_line_length": 154, "alphanum_fraction": 0.7546117546, "num_tokens": 537, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06560483745906928, "lm_q2_score": 0.03067580315069389, "lm_q1q2_score": 0.002012481079627678}}
{"text": "/*\n   Copyright [2021] [IBM Corporation]\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n       http://www.apache.org/licenses/LICENSE-2.0\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\n#ifndef MCAS_HSTORE_HEAP_MC_SHIM_H\n#define MCAS_HSTORE_HEAP_MC_SHIM_H\n\n#include <mm_plugin_itf.h>\n\n#include <ccpm/interfaces.h> /* ownership_callback, (IHeap_expandable, region_vector_t) */\n#include <common/byte_span.h>\n#include <common/string_view.h>\n#include <gsl/span>\n\n#include <cstddef> /* size_t */\n#include <functional> /* function */\n\nstruct heap_mc_shim\n\t: public ccpm::IHeap_expandable\n{\nprivate:\n\tMM_plugin_wrapper _mm;\npublic:\n\theap_mc_shim(common::string_view path, ccpm::persister *pe, gsl::span<common::byte_span> range, std::function<bool(const void *)> callee_owns);\n\theap_mc_shim(common::string_view path, ccpm::persister *pe);\n\theap_mc_shim(MM_plugin_wrapper &&pw);\n\n\tbool reconstitute(\n\t\tccpm::region_span regions\n\t\t, ccpm::ownership_callback_t resolver\n\t\t, bool force_init\n\t) override;\n\n\tstatus_t allocate(void * & ptr\n\t\t, std::size_t bytes\n\t\t, std::size_t alignment\n\t) override;\n\n\tstatus_t free(void * & ptr\n\t\t, std::size_t bytes\n\t) override;\n\n\tstatus_t remaining(std::size_t& out_size) const override;\n\n\tccpm::region_vector_t get_regions() const override;\n\n\tvoid add_regions(ccpm::region_span regions) override;\n\n\tbool includes(const void *ptr) const override;\n\n\tbool is_crash_consistent() const;\n};\n\n#endif\n", "meta": {"hexsha": "1504b3c5b4194cf5002921860d4c0afab4d42b05", "size": 1825, "ext": "h", "lang": "C", "max_stars_repo_path": "src/components/store/hstore/src/heap_mc_shim.h", "max_stars_repo_name": "omriarad/mcas", "max_stars_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 60.0, "max_stars_repo_stars_event_min_datetime": "2020-04-28T08:15:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T10:35:15.000Z", "max_issues_repo_path": "src/components/store/hstore/src/heap_mc_shim.h", "max_issues_repo_name": "omriarad/mcas", "max_issues_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 66.0, "max_issues_repo_issues_event_min_datetime": "2020-09-03T23:40:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T20:34:52.000Z", "max_forks_repo_path": "src/components/store/hstore/src/heap_mc_shim.h", "max_forks_repo_name": "omriarad/mcas", "max_forks_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2019-11-02T06:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T01:56:42.000Z", "avg_line_length": 28.515625, "max_line_length": 144, "alphanum_fraction": 0.7523287671, "num_tokens": 466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10970577387797077, "lm_q2_score": 0.018264275479584417, "lm_q1q2_score": 0.0020036964758082545}}
{"text": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n#pragma once\n\n#include <codecvt>\n#include <string>\n#include <locale>\n\n#include <gsl/gsl>\n\nnamespace mira\n{\n    inline std::string utf16_to_utf8(const wchar_t* input)\n    {\n        std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;\n        return converter.to_bytes(input);\n    }\n\n    inline std::wstring utf8_to_utf16(const char* input)\n    {\n        std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;\n        return converter.from_bytes(input);\n    }\n\n    inline std::string utf16_to_utf8(const std::wstring& input)\n    {\n        return utf16_to_utf8(input.data());\n    }\n\n    inline std::wstring utf8_to_utf16(const std::string& input)\n    {\n        return utf8_to_utf16(input.data());\n    }\n\n    struct string_compare\n    {\n        using is_transparent = std::true_type;\n\n        bool operator()(gsl::cstring_span<> a, gsl::cstring_span<> b) const\n        {\n            return std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end());\n        }\n\n        bool operator()(gsl::czstring_span<> a, gsl::czstring_span<> b) const\n        {\n            return (*this)(a.as_string_span(), b.as_string_span());\n        }\n\n        bool operator()(const char* a, const char* b) const\n        {\n            return strcmp(a, b) < 0;\n        }\n    };\n}\n", "meta": {"hexsha": "8df3646470491bb0c8c828d44f12dc1eea22a166", "size": 1354, "ext": "h", "lang": "C", "max_stars_repo_path": "Dependencies/Arcana/Shared/arcana/string.h", "max_stars_repo_name": "syntheticmagus/mageslam", "max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z", "max_issues_repo_path": "Dependencies/Arcana/Shared/arcana/string.h", "max_issues_repo_name": "syntheticmagus/mageslam", "max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z", "max_forks_repo_path": "Dependencies/Arcana/Shared/arcana/string.h", "max_forks_repo_name": "syntheticmagus/mageslam", "max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z", "avg_line_length": 24.1785714286, "max_line_length": 88, "alphanum_fraction": 0.6122599705, "num_tokens": 333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07369626970604845, "lm_q2_score": 0.027169231043364113, "lm_q1q2_score": 0.0020022709786777057}}
{"text": "/*\n *     Copyright 2016 Couchbase, Inc\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n */\n\n#pragma once\n\n#include <memcached/dockey.h>\n#include <gsl/gsl>\n#include <limits>\n#include <memory>\n#include <string>\n#include <type_traits>\n\n#include \"ep_types.h\"\n\nclass SerialisedDocKey;\n\n/**\n * StoredDocKey is a container for key data\n *\n * Internally an n byte key is stored in a n + sizeof(CollectionID) std::string.\n *  a) We zero terminate so that data() is safe for printing as a c-string.\n *  b) We store the CollectionID in byte 0:3. This is because StoredDocKey\n *    typically ends up being written to disk and the CollectionID forms part\n *    of the on-disk key. Accounting and for for the CollectionID means storage\n *    components don't have to create a new buffer into which they can layout\n *    CollectionID and key data.\n */\nclass StoredDocKey : public DocKeyInterface<StoredDocKey> {\npublic:\n    /**\n     * Construct empty - required for some std containers\n     */\n    StoredDocKey() : keydata() {\n    }\n\n    /**\n     * Create a StoredDocKey from a DocKey\n     * @param key DocKey that is to be copied-in\n     */\n    StoredDocKey(const DocKey& key) {\n        if (key.getEncoding() == DocKeyEncodesCollectionId::Yes) {\n            keydata.resize(key.size());\n            std::copy(key.data(), key.data() + key.size(), keydata.begin());\n        } else {\n            // This key is for the default collection (which has a fixed value)\n            keydata.resize(key.size() + 1);\n            keydata[0] = DefaultCollectionLeb128Encoded;\n            std::copy(key.data(), key.data() + key.size(), keydata.begin() + 1);\n        }\n    }\n\n    /**\n     * Create a StoredDocKey from a std::string (test code uses this)\n     * @param key std::string to be copied-in\n     * @param cid the CollectionID that the key applies to (and will be encoded\n     *        into the stored data)\n     */\n    StoredDocKey(const std::string& key, CollectionID cid);\n\n    const uint8_t* data() const {\n        return reinterpret_cast<const uint8_t*>(keydata.data());\n    }\n\n    size_t size() const {\n        return keydata.size();\n    }\n\n    DocNamespace getDocNamespace() const {\n        return getCollectionID();\n    }\n\n    CollectionID getCollectionID() const;\n\n    DocKeyEncodesCollectionId getEncoding() const {\n        return DocKeyEncodesCollectionId::Yes;\n    }\n\n    /**\n     * @return a DocKey that views this StoredDocKey but without any\n     * collection-ID prefix.\n     */\n    DocKey makeDocKeyWithoutCollectionID() const;\n\n    /**\n     * Intended for debug use only\n     * @returns cid:key\n     */\n    std::string to_string() const;\n\n    /**\n     * For tests only\n     * @returns the 'key' part of the StoredDocKey\n     */\n    const char* c_str() const;\n\n    int compare(const StoredDocKey& rhs) const {\n        return keydata.compare(rhs.keydata);\n    }\n\n    bool operator==(const StoredDocKey& rhs) const {\n        return keydata == rhs.keydata;\n    }\n\n    bool operator!=(const StoredDocKey& rhs) const {\n        return !(*this == rhs);\n    }\n\n    bool operator<(const StoredDocKey& rhs) const {\n        return keydata < rhs.keydata;\n    }\n\n    operator DocKey() const {\n        return {keydata, DocKeyEncodesCollectionId::Yes};\n    }\n\nprotected:\n    std::string keydata;\n};\n\nstd::ostream& operator<<(std::ostream& os, const StoredDocKey& key);\n\nstatic_assert(sizeof(CollectionID) == sizeof(uint32_t),\n              \"StoredDocKey: CollectionID has changed size\");\n\n/**\n * A hash function for StoredDocKey so they can be used in std::map and friends.\n */\nnamespace std {\ntemplate <>\nstruct hash<StoredDocKey> {\n    std::size_t operator()(const StoredDocKey& key) const {\n        return key.hash();\n    }\n};\n}\n\nclass MutationLogEntryV2;\nclass StoredValue;\n\n/**\n * SerialisedDocKey maintains the key data in an allocation that is not owned by\n * the class. The class is essentially immutable, providing a \"view\" onto the\n * larger block.\n *\n * For example where a StoredDocKey needs to exist as part of a bigger block of\n * data, SerialisedDocKey is the class to use.\n *\n * A limited number of classes are friends and only those classes can construct\n * a SerialisedDocKey.\n */\nclass SerialisedDocKey : public DocKeyInterface<SerialisedDocKey> {\npublic:\n    /**\n     * The copy constructor is deleted due to the bytes living outside of the\n     * object.\n     */\n    SerialisedDocKey(const SerialisedDocKey& obj) = delete;\n\n    const uint8_t* data() const {\n        return bytes;\n    }\n\n    size_t size() const {\n        return length;\n    }\n\n    DocNamespace getDocNamespace() const {\n        return getCollectionID();\n    }\n\n    CollectionID getCollectionID() const;\n\n    DocKeyEncodesCollectionId getEncoding() const {\n        return DocKeyEncodesCollectionId::Yes;\n    }\n\n    bool operator==(const DocKey& rhs) const;\n\n    /**\n     * Return how many bytes are (or need to be) allocated to this object\n     */\n    size_t getObjectSize() const {\n        return getObjectSize(length);\n    }\n\n    /**\n     * Return how many bytes are needed to store the DocKey\n     * @param key a DocKey that needs to be stored in a SerialisedDocKey\n     */\n    static size_t getObjectSize(const DocKey key) {\n        return getObjectSize(key.size());\n    }\n\n    /**\n     * Create a SerialisedDocKey and return a unique_ptr to the object.\n     * Note that the allocation is bigger than sizeof(SerialisedDocKey)\n     * @param key a DocKey to be stored as a SerialisedDocKey\n     */\n    struct SerialisedDocKeyDelete {\n        void operator()(SerialisedDocKey* p) {\n            p->~SerialisedDocKey();\n            delete[] reinterpret_cast<uint8_t*>(p);\n        }\n    };\n\n    operator DocKey() const {\n        return {bytes, length, DocKeyEncodesCollectionId::Yes};\n    }\n\n    /**\n     * make a SerialisedDocKey and return a unique_ptr to it - this is used\n     * in test code only.\n     */\n    static std::unique_ptr<SerialisedDocKey, SerialisedDocKeyDelete> make(\n            const StoredDocKey& key) {\n        std::unique_ptr<SerialisedDocKey, SerialisedDocKeyDelete> rval(\n                reinterpret_cast<SerialisedDocKey*>(\n                        new uint8_t[getObjectSize(key)]));\n        new (rval.get()) SerialisedDocKey(key);\n        return rval;\n    }\n\nprotected:\n    /**\n     * These following classes are \"white-listed\". They know how to allocate\n     * and construct this object so are allowed access to the constructor.\n     */\n    friend class MutationLogEntryV2;\n    friend class MutationLogEntryV3;\n    friend class StoredValue;\n\n    SerialisedDocKey() : length(0), bytes() {\n    }\n\n    /**\n     * Create a SerialisedDocKey from a DocKey. Protected constructor as\n     * this must be used by friends who know how to pre-allocate the object\n     * storage\n     * @param key a DocKey to be copied in\n     */\n    SerialisedDocKey(const DocKey& key)\n        : length(gsl::narrow_cast<uint8_t>(key.size())) {\n        if (key.getEncoding() == DocKeyEncodesCollectionId::Yes) {\n            std::copy(key.data(), key.data() + key.size(), bytes);\n        } else {\n            // This key is for the default collection\n            bytes[0] = DefaultCollectionLeb128Encoded;\n            std::copy(key.data(), key.data() + key.size(), bytes + 1);\n            length++;\n        }\n    }\n\n    /**\n     * Create a SerialisedDocKey from a byte_buffer that has no collection data\n     * and requires the caller to state the collection-ID\n     * This is used by MutationLogEntryV1/V2 to V3 upgrades\n     */\n    SerialisedDocKey(cb::const_byte_buffer key, CollectionID cid);\n\n    /**\n     * Create a SerialisedDocKey from a byte_buffer that has collection data\n     */\n    SerialisedDocKey(cb::const_byte_buffer key)\n        : length(gsl::narrow_cast<uint8_t>(key.size())) {\n        std::copy(key.begin(), key.end(), bytes);\n    }\n\n    /**\n     * Returns the size in bytes of this object - fixed size plus the variable\n     * length for the bytes making up the key.\n     */\n    static size_t getObjectSize(size_t len) {\n        return sizeof(SerialisedDocKey) +\n               (len - sizeof(SerialisedDocKey().bytes));\n    }\n\n    uint8_t length{0};\n    uint8_t bytes[1];\n};\n\nstd::ostream& operator<<(std::ostream& os, const SerialisedDocKey& key);\n\nstatic_assert(std::is_standard_layout<SerialisedDocKey>::value,\n              \"SeralisedDocKey: must satisfy is_standard_layout\");\n", "meta": {"hexsha": "fa3590e1155abee6f28ca58c202f9bedb30788fb", "size": 8889, "ext": "h", "lang": "C", "max_stars_repo_path": "engines/ep/src/storeddockey.h", "max_stars_repo_name": "t3rm1n4l/kv_engine", "max_stars_repo_head_hexsha": "24d4546220f3181678d7eadedc68b4ea088d3538", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "engines/ep/src/storeddockey.h", "max_issues_repo_name": "t3rm1n4l/kv_engine", "max_issues_repo_head_hexsha": "24d4546220f3181678d7eadedc68b4ea088d3538", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "engines/ep/src/storeddockey.h", "max_forks_repo_name": "t3rm1n4l/kv_engine", "max_forks_repo_head_hexsha": "24d4546220f3181678d7eadedc68b4ea088d3538", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8288590604, "max_line_length": 80, "alphanum_fraction": 0.6472044099, "num_tokens": 2140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07477003672283378, "lm_q2_score": 0.026759284689231017, "lm_q1q2_score": 0.002000792698890567}}
{"text": "#ifdef __cplusplus\n#include <string>\n#include <algorithm>\n#include \"halley/data_structures/vector.h\"\n#include <map>\n#include <set>\n#include <array>\n#include <charconv>\n#include <gsl/gsl>\n#include <cstddef>\n#include <limits>\n#include <memory>\n#include <chrono>\n#include <thread>\n#include <mutex>\n#include <iomanip>\n#include <optional>\n#include <atomic>\n#include <deque>\n#include <iostream>\n#include <sstream>\n#include <istream>\n#include <ostream>\n#endif\n", "meta": {"hexsha": "127ce8261a30819fcffa8a7b0431c36f9d7826be", "size": 453, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engine/utils/src/prec.h", "max_stars_repo_name": "amrezzd/halley", "max_stars_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/engine/utils/src/prec.h", "max_issues_repo_name": "amrezzd/halley", "max_issues_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engine/utils/src/prec.h", "max_forks_repo_name": "amrezzd/halley", "max_forks_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.12, "max_line_length": 42, "alphanum_fraction": 0.7373068433, "num_tokens": 105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.09670579329612156, "lm_q2_score": 0.020645932697646797, "lm_q1q2_score": 0.0019965812998642683}}
{"text": "/* -----------------------------------------------------------------------------\n * Copyright 2021 Jonathan Haigh\n * SPDX-License-Identifier: MIT\n * ---------------------------------------------------------------------------*/\n\n#ifndef SQ_INCLUDE_GUARD_core_test_Primitive_test_util_h_\n#define SQ_INCLUDE_GUARD_core_test_Primitive_test_util_h_\n\n#include \"core/Primitive.h\"\n#include \"core/typeutil.h\"\n\n#include <gsl/gsl>\n#include <string_view>\n\nnamespace sq::test {\n\nSQ_ND Primitive to_primitive(PrimitiveString &&v);\nSQ_ND Primitive to_primitive(const PrimitiveString &v);\nSQ_ND Primitive to_primitive(std::string_view v);\nSQ_ND Primitive to_primitive(gsl::czstring<> v);\nSQ_ND Primitive to_primitive(PrimitiveInt v);\nSQ_ND Primitive to_primitive(int v);\nSQ_ND Primitive to_primitive(PrimitiveFloat v);\nSQ_ND Primitive to_primitive(PrimitiveBool v);\nSQ_ND Primitive to_primitive(PrimitiveNull v);\n\n} // namespace sq::test\n\n#endif // SQ_INCLUDE_GUARD_core_test_Primitive_test_util_h_\n", "meta": {"hexsha": "85e96e0580364d763a8dfec4bb1d2ad7ad7c3eaa", "size": 983, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/test/include/test/Primitive_test_util.h", "max_stars_repo_name": "jonathanhaigh/sq", "max_stars_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-12T16:21:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-12T16:21:41.000Z", "max_issues_repo_path": "src/core/test/include/test/Primitive_test_util.h", "max_issues_repo_name": "jonathanhaigh/sq", "max_issues_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 44.0, "max_issues_repo_issues_event_min_datetime": "2021-02-08T19:17:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-05T18:51:38.000Z", "max_forks_repo_path": "src/core/test/include/test/Primitive_test_util.h", "max_forks_repo_name": "jonathanhaigh/sq", "max_forks_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7666666667, "max_line_length": 80, "alphanum_fraction": 0.6856561546, "num_tokens": 203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.09268777863937604, "lm_q2_score": 0.021287349387434398, "lm_q1q2_score": 0.0019730771278415765}}
{"text": "#ifndef AMICI_HDF5_H\n#define AMICI_HDF5_H\n\n#include <string>\n#include <memory>\n#include <vector>\n\n#include <H5Cpp.h>\n\n#include <gsl/gsl-lite.hpp>\n\n#undef AMI_HDF5_H_DEBUG\n\n/* Macros for enabling/disabling  HDF5 error auto-printing\n * AMICI_H5_SAVE_ERROR_HANDLER and AMICI_H5_RESTORE_ERROR_HANDLER must be called\n * within the same context, otherwise the stack handler is lost. */\n#define AMICI_H5_SAVE_ERROR_HANDLER                                            \\\n    herr_t (*old_func)(void *);                                                \\\n    void *old_client_data;                                                     \\\n    H5Eget_auto1(&old_func, &old_client_data);                                 \\\n    H5Eset_auto1(NULL, NULL)\n\n#define AMICI_H5_RESTORE_ERROR_HANDLER H5Eset_auto1(old_func, old_client_data)\n\nnamespace amici {\n\nclass ReturnData;\nclass ExpData;\nclass Model;\nclass Solver;\n\nnamespace hdf5 {\n\n\n/* Functions for reading and writing AMICI data to/from HDF5 files. */\n\n/**\n * @brief Open the given file for writing. Append if exists, create if not.\n * @param hdf5filename\n * @return\n */\nH5::H5File createOrOpenForWriting(std::string const& hdf5filename);\n\n/**\n * @brief Read solver options from HDF5 file\n * @param fileId hdf5 file handle to read from\n * @param solver solver to set options on\n * @param datasetPath Path inside the HDF5 file\n */\nvoid readSolverSettingsFromHDF5(const H5::H5File &file, Solver& solver,\n                                std::string const& datasetPath);\n\n/**\n * @brief Read solver options from HDF5 file\n * @param hdffile Name of HDF5 file\n * @param solver solver to set options on\n * @param datasetPath Path inside the HDF5 file\n */\nvoid readSolverSettingsFromHDF5(std::string const& hdffile, Solver& solver,\n                                std::string const& datasetPath);\n\n/**\n * @brief Read model data from HDF5 file\n * @param hdffile Name of HDF5 file\n * @param model model to set data on\n * @param datasetPath Path inside the HDF5 file\n */\nvoid readModelDataFromHDF5(std::string const& hdffile, Model& model,\n                           std::string const& datasetPath);\n\n/**\n * @brief Read model data from HDF5 file\n * @param fileId hdf5 file handle to read from\n * @param model model to set data on\n * @param datasetPath Path inside the HDF5 file\n */\nvoid readModelDataFromHDF5(H5::H5File const&file, Model& model,\n                           std::string const& datasetPath);\n\n\n/**\n  * @brief Write ReturnData struct to HDF5 dataset\n  * @param rdata Data to write\n  * @param hdffile Filename of HDF5 file\n  * @param datasetPath Full dataset path inside the HDF5 file (will be created)\n  */\n\nvoid writeReturnData(const ReturnData &rdata,\n                     H5::H5File const& file,\n                     const std::string& hdf5Location);\n\nvoid writeReturnData(const ReturnData &rdata,\n                     std::string const& hdf5Filename,\n                     const std::string& hdf5Location);\n\nvoid writeReturnDataDiagnosis(const ReturnData &rdata,\n                              H5::H5File const& file,\n                              const std::string& hdf5Location);\n\n/**\n * @brief Create the given group and possibly parents\n * @param file\n * @param groupPath\n * @param recursively\n */\nvoid createGroup(const H5::H5File &file,\n                 std::string const& groupPath,\n                 bool recursively = true);\n\n/**\n * @brief readSimulationExpData reads AMICI experimental data from\n * attributes in HDF5 file.\n * @param hdf5Filename Name of HDF5 file\n * @param hdf5Root Path inside the HDF5 file to object having ExpData as\n * attributes\n * @param model The model for which data is to be read\n * @return\n */\n\nstd::unique_ptr<ExpData> readSimulationExpData(const std::string &hdf5Filename,\n                                               const std::string &hdf5Root,\n                                               const Model &model);\n\n/**\n * @brief writeSimulationExpData writes AMICI experimental data to\n * attributes in HDF5 file.\n * @param edata The experimental data which is to be written\n * @param hdf5Filename Name of HDF5 file\n * @param hdf5Root Path inside the HDF5 file to object having ExpData as\n * attributes\n */\n\nvoid writeSimulationExpData(const ExpData &edata,\n                            H5::H5File const& file,\n                            const std::string &hdf5Location);\n\n/**\n * @brief attributeExists Check whether an attribute with the given\n * name exists on the given dataset\n * @param fileId The HDF5 file object\n * @param datasetPath Dataset of which attributes should be checked\n * @param attributeName Name of the attribute of interest\n * @return\n */\nbool attributeExists(H5::H5File const& file,\n                     const std::string &optionsObject,\n                     const std::string &attributeName);\n\nbool attributeExists(H5::H5Object const& object,\n                     const std::string &attributeName);\n\n\nvoid createAndWriteInt1DDataset(H5::H5File const& file,\n                                std::string const& datasetName,\n                                gsl::span<const int> buffer);\n\nvoid createAndWriteInt2DDataset(H5::H5File const& file,\n                                std::string const& datasetName,\n                                gsl::span<const int> buffer, hsize_t m,\n                                hsize_t n);\n\nvoid createAndWriteDouble1DDataset(H5::H5File const& file,\n                                   std::string const& datasetName,\n                                   gsl::span<const double> buffer);\n\nvoid createAndWriteDouble2DDataset(H5::H5File const& file,\n                                   std::string const& datasetName,\n                                   gsl::span<const double> buffer, hsize_t m,\n                                   hsize_t n);\n\nvoid createAndWriteDouble3DDataset(H5::H5File const& file,\n                                   std::string const& datasetName,\n                                   gsl::span<const double> buffer, hsize_t m,\n                                   hsize_t n, hsize_t o);\n\ndouble getDoubleScalarAttribute(const H5::H5File& file,\n                                const std::string &optionsObject,\n                                const std::string &attributeName);\n\nint getIntScalarAttribute(const H5::H5File &file,\n                          const std::string &optionsObject,\n                          const std::string &attributeName);\n\n\nstd::vector<int> getIntDataset1D(const H5::H5File &file,\n                                 std::string const& name);\n\nstd::vector<double> getDoubleDataset1D(const H5::H5File &file,\n                                       std::string const& name);\n\nstd::vector<double> getDoubleDataset2D(const H5::H5File &file,\n                                       std::string const& name,\n                                       hsize_t &m, hsize_t &n);\n\nstd::vector<double> getDoubleDataset3D(const H5::H5File &file,\n                                       std::string const& name,\n                                       hsize_t &m, hsize_t &n, hsize_t &o);\n\n/**\n * @brief Check if the given location (group, link or dataset) exists in the\n * given file\n * @param filename\n * @param location\n * @return\n */\nbool locationExists(std::string const& filename, std::string const& location);\n\nbool locationExists(H5::H5File const& file, std::string const& location);\n\n} // namespace hdf5\n} // namespace amici\n\n#endif\n", "meta": {"hexsha": "49f27f890569bfed54a0a061770925f426c3dc3d", "size": 7388, "ext": "h", "lang": "C", "max_stars_repo_path": "include/amici/hdf5.h", "max_stars_repo_name": "paszkow/AMICI", "max_stars_repo_head_hexsha": "a0407673453d6e18a9abec5b6f73758dd09f7aaf", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/amici/hdf5.h", "max_issues_repo_name": "paszkow/AMICI", "max_issues_repo_head_hexsha": "a0407673453d6e18a9abec5b6f73758dd09f7aaf", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/amici/hdf5.h", "max_forks_repo_name": "paszkow/AMICI", "max_forks_repo_head_hexsha": "a0407673453d6e18a9abec5b6f73758dd09f7aaf", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.523364486, "max_line_length": 80, "alphanum_fraction": 0.6042230644, "num_tokens": 1643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.0769608272276531, "lm_q2_score": 0.025565212531223618, "lm_q1q2_score": 0.0019675199046537326}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef sysop_eb634adc_cca3_4f8f_853c_7852abe06d2d_h\r\n#define sysop_eb634adc_cca3_4f8f_853c_7852abe06d2d_h\r\n\r\n#include <gslib/type.h>\r\n#include <gslib/std.h>\r\n#include <ariel/type.h>\r\n#include <ariel/image.h>\r\n\r\n__ariel_begin__\r\n\r\nenum unimask\r\n{\r\n    declare_mask(um_shift,      0),\r\n    declare_mask(um_sshift,     1),\r\n    declare_mask(um_control,    2),\r\n    declare_mask(um_scontrol,   3),\r\n    declare_mask(um_reserve,    4),\r\n    declare_mask(um_alter,      6),\r\n    declare_mask(um_salter,     7),\r\n    declare_mask(um_lmouse,     8),\r\n    declare_mask(um_rmouse,     9),\r\n};\r\n\r\nenum stylemask\r\n{\r\n    declare_mask(sm_hitable,    0),\r\n    declare_mask(sm_visible,    1),\r\n};\r\n\r\n/*\r\n * part1. ascii codes\r\n * part2. reserved\r\n * part3. mouse keys\r\n * part4. joystick keys\r\n * part5. keyboard controls\r\n */\r\nenum unikey\r\n{\r\n    uk_null = 0,        /* null */\r\n    uk_soh,             /* start of heading */\r\n    uk_stx,             /* start of text */\r\n    uk_etx,             /* end of text */\r\n    uk_eot,             /* end of transmission */\r\n    uk_enq,             /* enquiry */\r\n    uk_ack,             /* acknowledge */\r\n    uk_bel,             /* bell */\r\n    uk_bs,              /* backspace */\r\n    uk_tab,             /* horizontal tab */\r\n    uk_lf,              /* nl line feed, new line */\r\n    uk_vt,              /* vertical tab */\r\n    uk_ff,              /* np form feed, new page */\r\n    uk_cr,              /* carriage return */\r\n    uk_so,              /* shift out */\r\n    uk_si,              /* shift in */\r\n    uk_dle,             /* data link escape */\r\n    uk_dc1,             /* device control 1 */\r\n    uk_dc2,             /* device control 2 */\r\n    uk_dc3,             /* device control 3 */\r\n    uk_dc4,             /* device control 4 */\r\n    uk_nak,             /* negative acknowledge */\r\n    uk_syn,             /* synchronous idle */\r\n    uk_etb,             /* end of trans. block */\r\n    uk_can,             /* cancel */\r\n    uk_em,              /* end of medium */\r\n    uk_sub,             /* substitute */\r\n    uk_esc,             /* escape */\r\n    uk_fs,              /* file separator */\r\n    uk_gs,              /* group separator */\r\n    uk_rs,              /* record separator */\r\n    uk_us,              /* unit separator */\r\n    uk_sp,              /* space, blank */\r\n                        /* ! - ~ */\r\n    uk_del  = 0x7f,     /* delete */\r\n\r\n    mk_left,\r\n    mk_center,\r\n    mk_right,\r\n\r\n    vk_insert,          /* insert */\r\n    vk_caps,            /* caps lock */\r\n    vk_pscr,            /* print screen */\r\n    vk_numlock,         /* number lock */\r\n    vk_home,            /* home */\r\n    vk_end,             /* end */\r\n    vk_pageup,          /* page up */\r\n    vk_pagedown,        /* page down */\r\n    vk_left,            /* left arrow */\r\n    vk_up,              /* up arrow */\r\n    vk_right,           /* right arrow */\r\n    vk_down,            /* down arrow */\r\n\r\n    vk_shift,\r\n    vk_control,\r\n    vk_alter,\r\n\r\n    vk_f1,              /* f1 - f12 */\r\n    vk_f2,\r\n    vk_f3,\r\n    vk_f4,\r\n    vk_f5,\r\n    vk_f6,\r\n    vk_f7,\r\n    vk_f8,\r\n    vk_f9,\r\n    vk_f10,\r\n    vk_f11,\r\n    vk_f12,\r\n};\r\n\r\nenum cursor_type\r\n{\r\n    cur_arrow,\r\n    cur_beam,\r\n    cur_cross,\r\n    cur_up_arrow,\r\n    cur_size_nwse,\r\n    cur_size_nesw,\r\n    cur_size_we,\r\n    cur_size_ns,\r\n    cur_size_all,\r\n    cur_hand,\r\n    cur_help,\r\n};\r\n\r\nclass system_driver;\r\ntypedef render_texture2d texture2d;\r\n\r\nclass __gs_novtable system_notify abstract\r\n{\r\npublic:\r\n    virtual void on_show(bool b) = 0;\r\n    virtual void on_create(system_driver* ptr, const rect& rc) = 0;\r\n    virtual void on_close() = 0;\r\n    virtual void on_resize(const rect& rc) = 0;\r\n    virtual void on_paint(const rect& rc) = 0;\r\n    virtual void on_halt() = 0;\r\n    virtual void on_resume() = 0;\r\n    virtual bool on_mouse_down(uint um, unikey uk, const point& pt) = 0;\r\n    virtual bool on_mouse_up(uint um, unikey uk, const point& pt) = 0;\r\n    virtual bool on_mouse_move(uint um, const point& pt) = 0;\r\n    virtual bool on_key_down(uint um, unikey uk) = 0;\r\n    virtual bool on_key_up(uint um, unikey uk) = 0;\r\n    virtual bool on_char(uint um, uint ch) = 0;\r\n    virtual void on_timer(uint tid) = 0;\r\n};\r\n\r\nenum clipfmt\r\n{\r\n    cf_text,\r\n    cf_bitmap,\r\n};\r\n\r\nclass __gs_novtable clipboard_data abstract\r\n{\r\npublic:\r\n    virtual ~clipboard_data() {}\r\n    virtual clipfmt get_format() const = 0;\r\n    virtual void* get_ptr() = 0;\r\n    virtual int get_size() const = 0;\r\n    template<class _tdata>\r\n    _tdata* get_data() { return (_tdata*)get_ptr(); }\r\n};\r\n\r\nclass clipboard_list:\r\n    public list<clipboard_data*>\r\n{\r\npublic:\r\n    ~clipboard_list()\r\n    {\r\n        for(auto* p : *this) {\r\n            assert(p);\r\n            delete p;\r\n        }\r\n        clear();\r\n    }\r\n};\r\n\r\nstruct clipboard_text:\r\n    public clipboard_data, public string\r\n{\r\n    virtual clipfmt get_format() const { return cf_text; }\r\n    virtual void* get_ptr() { return (void*)static_cast<string*>(this); }\r\n    virtual int get_size() const { return string::length(); }\r\n};\r\n\r\nstruct clipboard_bitmap:\r\n    public clipboard_data, public image\r\n{\r\n    virtual clipfmt get_format() const { return cf_bitmap; }\r\n    virtual void* get_ptr() { return (void*)static_cast<image*>(this); }\r\n    virtual int get_size() const { return -1; }\r\n};\r\n\r\nstruct system_context\r\n{\r\n    enum\r\n    {\r\n        sct_notify      = 0x01,\r\n        sct_painter     = 0x02,\r\n        sct_rectangle   = 0x04,\r\n        sct_hwnd        = 0x08,\r\n        sct_hinst       = 0x10,\r\n        sct_everything  = 0xffffffff,\r\n    };\r\n\r\n    uint                mask;\r\n    system_notify*      notify;\r\n    void*               painter;\r\n    rect                rectangle;\r\n    uint                hwnd;\r\n    uint                hinst;\r\n};\r\n\r\nclass __gs_novtable system_driver abstract\r\n{\r\npublic:\r\n    virtual ~system_driver() {}\r\n    virtual void initialize(const system_context& ctx) = 0;\r\n    virtual void setup() = 0;\r\n    virtual void close() = 0;\r\n    virtual void set_timer(uint tid, int t) = 0;\r\n    virtual void kill_timer(uint tid) = 0;\r\n    virtual void update() = 0;\r\n    virtual void emit(int msgid, void* msg, int size) = 0;\r\n    virtual void set_ime(point pt, const font& ft) = 0;\r\n    virtual void set_cursor(cursor_type curty) = 0;\r\n    //virtual void set_clipboard(const gchar* fmt, const void* ptr, int size) = 0;\r\n    //virtual int get_clipboard(const gchar* fmt, const void*& ptr) = 0;\r\n    //virtual int get_clipboard(clipboard_list& cl, int c) = 0;\r\n};\r\n\r\nclass __gs_novtable fontsys abstract\r\n{\r\npublic:\r\n    virtual ~fontsys() {}\r\n    virtual void initialize() = 0;\r\n    virtual void set_font(const font& f) = 0;\r\n    virtual bool query_size(const gchar* str, int& w, int& h, int len = -1) = 0;\r\n    virtual bool create_text_image(image& img, const gchar* str, int x, int y, const color& cr, int len = -1) = 0;\r\n    virtual bool create_text_texture(texture2d** tex, const gchar* str, int margin, const color& cr, int len = -1) = 0;\r\n    virtual void draw(image& img, const gchar* str, int x, int y, const color& cr, int len = -1) = 0;\r\n};\r\n\r\n__ariel_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "7c8b9a0bd42850685a998d1a0808e13d41606f52", "size": 8398, "ext": "h", "lang": "C", "max_stars_repo_path": "include/ariel/sysop.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/ariel/sysop.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ariel/sysop.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 30.6496350365, "max_line_length": 120, "alphanum_fraction": 0.57239819, "num_tokens": 2168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06853749303199023, "lm_q2_score": 0.028436031398129846, "lm_q1q2_score": 0.00194893430380678}}
{"text": "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\n#pragma once\n\n#include <string>\n\n#include <gsl/gsl>\n\n#include \"onnx/onnx_pb.h\"\n\n#include \"core/graph/basic_types.h\"\n\nnamespace onnxruntime::utils {\n\n// keep these signatures in sync with DECLARE_MAKE_ATTRIBUTE_FNS below\n/** Creates an AttributeProto with the specified name and value. */\nONNX_NAMESPACE::AttributeProto MakeAttribute(std::string attr_name, int64_t value);\n/** Creates an AttributeProto with the specified name and values. */\nONNX_NAMESPACE::AttributeProto MakeAttribute(std::string attr_name, gsl::span<const int64_t> values);\n\n#define DECLARE_MAKE_ATTRIBUTE_FNS(type)                                           \\\n  ONNX_NAMESPACE::AttributeProto MakeAttribute(std::string attr_name, type value); \\\n  ONNX_NAMESPACE::AttributeProto MakeAttribute(std::string attr_name, gsl::span<const type> values)\n\nDECLARE_MAKE_ATTRIBUTE_FNS(float);\nDECLARE_MAKE_ATTRIBUTE_FNS(std::string);\nDECLARE_MAKE_ATTRIBUTE_FNS(ONNX_NAMESPACE::TensorProto);\n#if !defined(DISABLE_SPARSE_TENSORS)\nDECLARE_MAKE_ATTRIBUTE_FNS(ONNX_NAMESPACE::SparseTensorProto);\n#endif\nDECLARE_MAKE_ATTRIBUTE_FNS(ONNX_NAMESPACE::TypeProto);\nDECLARE_MAKE_ATTRIBUTE_FNS(ONNX_NAMESPACE::GraphProto);\n\n#undef DECLARE_MAKE_ATTRIBUTE_FNS\n\n// The below overload is made so the compiler does not attempt to resolve\n// string literals with the gsl::span overload\ninline ONNX_NAMESPACE::AttributeProto MakeAttribute(std::string attr_name, const char* value) {\n  return MakeAttribute(std::move(attr_name), std::string{value});\n}\n\n/**\n * Sets an attribute in `node_attributes` with key `attribute.name()` and value `attribute`.\n * If an attribute with the same name exists, it will be overwritten.\n * @return Pair of (iterator to attribute, whether attribute was added (true) or updated (false)).\n */\nstd::pair<NodeAttributes::iterator, bool> SetNodeAttribute(ONNX_NAMESPACE::AttributeProto attribute,\n                                                           NodeAttributes& node_attributes);\n\n}  // namespace onnxruntime::utils\n", "meta": {"hexsha": "94242e8d264043ef1615797384a65efa790ac6fe", "size": 2085, "ext": "h", "lang": "C", "max_stars_repo_path": "onnxruntime/core/graph/node_attr_utils.h", "max_stars_repo_name": "SiriusKY/onnxruntime", "max_stars_repo_head_hexsha": "3c5853dcbc9d5dda2476afa8c6105802d2b8e53d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 669.0, "max_stars_repo_stars_event_min_datetime": "2018-12-03T22:00:31.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-06T19:42:49.000Z", "max_issues_repo_path": "onnxruntime/core/graph/node_attr_utils.h", "max_issues_repo_name": "SiriusKY/onnxruntime", "max_issues_repo_head_hexsha": "3c5853dcbc9d5dda2476afa8c6105802d2b8e53d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 440.0, "max_issues_repo_issues_event_min_datetime": "2018-12-03T21:09:56.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-06T20:47:23.000Z", "max_forks_repo_path": "onnxruntime/core/graph/node_attr_utils.h", "max_forks_repo_name": "SiriusKY/onnxruntime", "max_forks_repo_head_hexsha": "3c5853dcbc9d5dda2476afa8c6105802d2b8e53d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 140.0, "max_forks_repo_forks_event_min_datetime": "2018-12-03T21:15:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-06T18:02:36.000Z", "avg_line_length": 40.0961538462, "max_line_length": 101, "alphanum_fraction": 0.7582733813, "num_tokens": 442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.0913820956435847, "lm_q2_score": 0.021287350551635973, "lm_q1q2_score": 0.0019452827041081138}}
{"text": "#include \"cconfigspace_internal.h\"\n#include <stdlib.h>\n#include <gsl/gsl_rng.h>\n\nconst ccs_datum_t ccs_none = CCS_NONE_VAL;\nconst ccs_datum_t ccs_inactive = CCS_INACTIVE_VAL;\nconst ccs_datum_t ccs_true = CCS_TRUE_VAL;\nconst ccs_datum_t ccs_false = CCS_FALSE_VAL;\nconst ccs_version_t ccs_version = { 0, 1, 0, 0 };\n\nccs_result_t\nccs_init() {\n\tgsl_rng_env_setup();\n\treturn CCS_SUCCESS;\n}\n\nccs_result_t\nccs_fini() {\n\treturn CCS_SUCCESS;\n}\n\nccs_version_t\nccs_get_version() {\n\treturn ccs_version;\n}\n\nccs_result_t\nccs_retain_object(ccs_object_t object) {\n\t_ccs_object_internal_t *obj = (_ccs_object_internal_t *)object;\n        if (!obj || obj->refcount <= 0)\n\t\treturn -CCS_INVALID_OBJECT;\n\tobj->refcount += 1;\n\treturn CCS_SUCCESS;\n}\n\nccs_result_t\nccs_release_object(ccs_object_t object) {\n\t_ccs_object_internal_t *obj = (_ccs_object_internal_t *)object;\n\tif (!obj || obj->refcount <= 0)\n\t\treturn -CCS_INVALID_OBJECT;\n\tobj->refcount -= 1;\n\tif (obj->refcount == 0) {\n\t\tif (obj->callbacks) {\n\t\t\t_ccs_object_callback_t *cb = NULL;\n\t\t\twhile ( (cb = (_ccs_object_callback_t *)\n\t\t\t              utarray_prev(obj->callbacks, cb)) ) {\n\t\t\t\tcb->callback(object, cb->user_data);\n\t\t\t}\n\t\t\tutarray_free(obj->callbacks);\n\t\t}\n\t\tCCS_VALIDATE(obj->ops->del(object));\n\t\tfree(object);\n\t}\n\treturn CCS_SUCCESS;\n}\n\nccs_result_t\nccs_object_get_type(ccs_object_t       object,\n                     ccs_object_type_t *type_ret) {\n\t_ccs_object_internal_t *obj = (_ccs_object_internal_t *)object;\n\tif (!obj)\n\t\treturn -CCS_INVALID_OBJECT;\n\tCCS_CHECK_PTR(type_ret);\n\t*type_ret = obj->type;\n\treturn CCS_SUCCESS;\n}\n\nccs_result_t\nccs_object_get_refcount(ccs_object_t  object,\n                         int32_t      *refcount_ret) {\n\t_ccs_object_internal_t *obj = (_ccs_object_internal_t *)object;\n\tif (!obj)\n\t\treturn -CCS_INVALID_OBJECT;\n\tCCS_CHECK_PTR(refcount_ret);\n\t*refcount_ret = obj->refcount;\n\treturn CCS_SUCCESS;\n}\n\nstatic const UT_icd _object_callback_icd = {\n\tsizeof(_ccs_object_callback_t),\n\tNULL,\n\tNULL,\n\tNULL\n};\n\nccs_result_t\nccs_object_set_destroy_callback(ccs_object_t  object,\n                                void (*callback)(\n                                  ccs_object_t object,\n                                  void *user_data),\n                                void *user_data) {\n\t_ccs_object_internal_t *obj = (_ccs_object_internal_t *)object;\n\tif (!obj)\n\t\treturn -CCS_INVALID_OBJECT;\n\tif (!callback)\n\t\treturn -CCS_INVALID_VALUE;\n\tif (!obj->callbacks)\n\t\tutarray_new(obj->callbacks, &_object_callback_icd);\n\n\t_ccs_object_callback_t cb = { callback, user_data };\n\tutarray_push_back(obj->callbacks, &cb);\n\treturn CCS_SUCCESS;\n}\n\n", "meta": {"hexsha": "9931f0f85ed665dad30d183061de80f4b364a553", "size": 2607, "ext": "c", "lang": "C", "max_stars_repo_path": "src/cconfigspace.c", "max_stars_repo_name": "deephyper/CCS", "max_stars_repo_head_hexsha": "dd8c976eca2a510c995862cc5c871e81932f3ff4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-29T16:31:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T16:31:28.000Z", "max_issues_repo_path": "src/cconfigspace.c", "max_issues_repo_name": "deephyper/CCS", "max_issues_repo_head_hexsha": "dd8c976eca2a510c995862cc5c871e81932f3ff4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-15T10:37:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-15T10:48:24.000Z", "max_forks_repo_path": "src/cconfigspace.c", "max_forks_repo_name": "deephyper/CCS", "max_forks_repo_head_hexsha": "dd8c976eca2a510c995862cc5c871e81932f3ff4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-16T18:20:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-07T17:54:11.000Z", "avg_line_length": 24.8285714286, "max_line_length": 64, "alphanum_fraction": 0.6931338703, "num_tokens": 717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09401018469323502, "lm_q2_score": 0.020645932132715525, "lm_q1q2_score": 0.001940927892960582}}
{"text": "#pragma once\n/*\n * (C) Copyright 2020-2021 UCAR\n *\n * This software is licensed under the terms of the Apache Licence Version 2.0\n * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.\n */\n/*! \\addtogroup ioda_cxx_attribute\n *\n * @{\n * \\file Has_Attributes.h\n * \\brief Interfaces for ioda::Has_Attributes and related classes.\n */\n\n#include <gsl/gsl-lite.hpp>\n#include <iostream>\n#include <memory>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include \"ioda/Attributes/Attribute.h\"\n#include \"ioda/Exception.h\"\n#include \"ioda/Misc/Dimensions.h\"\n#include \"ioda/Misc/Eigen_Compat.h\"\n#include \"ioda/Types/Type.h\"\n#include \"ioda/defs.h\"\n\nnamespace ioda {\nclass Has_Attributes;\nnamespace detail {\nclass Has_Attributes_Backend;\nclass Has_Attributes_Base;\nclass Variable_Backend;\nclass Group_Backend;\n\n/// \\brief Describes the functions that can add attributes\n/// \\ingroup ioda_cxx_attribute\n/// \\details Using the (Curiously Recurring Template\n/// Pattern)[https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern] to implement this\n/// since we want to use the same functions for placeholder attribute construction.\n/// \\see Has_Attributes\n/// \\see Attribute_Creator\ntemplate <class DerivedHasAtts>\nclass CanAddAttributes {\npublic:\n  /// @name Convenience functions for adding attributes\n  /// @{\n\n  /// \\brief Create and write an Attribute, for arbitrary dimensions.\n  /// \\tparam DataType is the type of the data. I.e. float, int, int32_t, uint16_t, std::string, etc.\n  /// \\param attrname is the name of the Attribute to be created.\n  /// \\param data is a gsl::span (a pointer-length pair) that contains the data to be written.\n  /// \\param dimensions is an initializer list representing the size of the metadata. Each element\n  /// is a dimension with a certain size.\n  /// \\returns Another instance of this Has_Attribute. Used for operation chaining.\n  /// \\throws jedi::xError if data.size() does not match the number of total elements\n  ///   described by dimensions.\n  /// \\see gsl::span for details of how to make a span.\n  template <class DataType>\n  DerivedHasAtts add(const std::string& attrname, ::gsl::span<const DataType> data,\n                     const ::std::vector<Dimensions_t>& dimensions) {\n    auto derivedThis = static_cast<DerivedHasAtts*>(this);\n    auto att         = derivedThis->template create<DataType>(attrname, dimensions);\n    att.template write<DataType>(data);\n    return *derivedThis;\n  }\n\n  /// \\brief Create and write an Attribute, for arbitrary dimensions.\n  /// \\tparam DataType is the type of the data. I.e. float, int, int32_t, uint16_t, std::string, etc.\n  /// \\param attrname is the name of the Attribute to be created.\n  /// \\param data is an initializer list that contains the data to be written.\n  /// \\param dimensions is an initializer list representing the size of the metadata. Each\n  ///   element is a dimension with a certain size.\n  /// \\returns Another instance of this Has_Attribute. Used for operation chaining.\n  /// \\throws jedi::xError if data.size() does not match the number of total\n  ///   elements described by dimensions.\n  template <class DataType>\n  DerivedHasAtts add(const std::string& attrname, ::std::initializer_list<DataType> data,\n                     const ::std::vector<Dimensions_t>& dimensions) {\n    auto derivedThis = static_cast<DerivedHasAtts*>(this);\n    auto att         = derivedThis->template create<DataType>(attrname, dimensions);\n    att.template write<DataType>(data);\n    return *derivedThis;\n  }\n\n  /// \\brief Create and write an Attribute, for a single-dimensional span of 1-D data.\n  /// \\tparam DataType is the type of the data. I.e. float, int, int32_t, uint16_t, std::string, etc.\n  /// \\param attrname is the name of the Attribute to be created.\n  /// \\param data is a gsl::span (a pointer-length pair) that contains the data to be written.\n  ///   The new Attribute will be one-dimensional and the length of the overall span.\n  /// \\returns Another instance of this Has_Attribute. Used for operation chaining.\n  /// \\see gsl::span for details of how to make a span.\n  /// \\see gsl::make_span\n  template <class DataType>\n  DerivedHasAtts add(const std::string& attrname, ::gsl::span<const DataType> data) {\n    return add(attrname, data, {gsl::narrow<Dimensions_t>(data.size())});\n  }\n\n  /// \\brief Create and write an Attribute, for a 1-D initializer list.\n  /// \\tparam DataType is the type of the data. I.e. float, int, int32_t, uint16_t, std::string, etc.\n  /// \\param attrname is the name of the Attribute to be created.\n  /// \\param data is an initializer list that contains the data to be written.\n  ///   The new Attribute will be one-dimensional and the length of the overall span.\n  /// \\returns Another instance of this Has_Attribute. Used for operation chaining.\n  template <class DataType>\n  DerivedHasAtts add(const std::string& attrname, ::std::initializer_list<DataType> data) {\n    return add(attrname, data, {gsl::narrow<Dimensions_t>(data.size())});\n  }\n\n  /// \\brief Create and write a single datum of an Attribute.\n  /// \\tparam DataType is the type of the data. I.e. float, int, int32_t, uint16_t, std::string, etc.\n  /// \\param attrname is the name of the Attribute to be created.\n  /// \\param data is the data to be written. The new Attribute will be zero-dimensional and will\n  /// contain only this datum.\n  /// \\note Even 0-dimensional data have a type, which may be a compound\n  /// array (i.e. a single string of variable length).\n  /// \\returns Another instance of this Has_Attribute. Used for operation chaining.\n  template <class DataType>\n  DerivedHasAtts add(const std::string& attrname, const DataType& data) {\n    return add(attrname, gsl::make_span(&data, 1), {1});\n  }\n\n  template <class EigenClass>\n  DerivedHasAtts addWithEigenRegular(const std::string& attrname, const EigenClass& data,\n                                     bool is2D = true) {\n#if 1  //__has_include(\"Eigen/Dense\")\n    typedef typename EigenClass::Scalar ScalarType;\n    // If d is already in Row Major form, then this is optimized out.\n    Eigen::Array<ScalarType, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> dout;\n    dout.resize(data.rows(), data.cols());\n    dout               = data;\n    const auto& dconst = dout;  // To make some compilers happy.\n    auto sp            = gsl::make_span(dconst.data(), static_cast<int>(data.rows() * data.cols()));\n\n    if (is2D)\n      return add(attrname, sp,\n                 {gsl::narrow<Dimensions_t>(data.rows()), gsl::narrow<Dimensions_t>(data.cols())});\n    else\n      return add(attrname, sp);\n#else\n    static_assert(false, \"The Eigen headers cannot be found, so this function cannot be used.\");\n#endif\n  }\n\n  template <class EigenClass>\n  DerivedHasAtts addWithEigenTensor(const std::string& attrname, const EigenClass& data) {\n#if 1  //__has_include(\"unsupported/Eigen/CXX11/Tensor\")\n    typedef typename EigenClass::Scalar ScalarType;\n    ioda::Dimensions dims = detail::EigenCompat::getTensorDimensions(data);\n\n    auto derived_this = static_cast<DerivedHasAtts*>(this);\n    Attribute att     = derived_this->template create<ScalarType>(attrname, dims.dimsCur);\n\n    att.writeWithEigenTensor(data);\n    return *derived_this;\n#else\n    static_assert(\n      false, \"The Eigen unsupported/ headers cannot be found, so this function cannot be used.\");\n#endif\n  }\n\n  /// @}\n};\n\n/// \\brief Describes the functions that can read attributes\n/// \\ingroup ioda_cxx_attribute\n/// \\details Uses the (CRTP)[https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern]\n///   to implement this as we use the same functions for placeholder attribute construction.\n/// \\see Has_Attributes\ntemplate <class DerivedHasAtts>\nclass CanReadAttributes {\nprotected:\n  CanReadAttributes() {}\n\npublic:\n  virtual ~CanReadAttributes() {}\n\n  /// @name Convenience functions for reading attributes\n  /// @{\n\n  /// \\brief Open and read an Attribute, for expected dimensions.\n  /// \\tparam DataType is the type of the data. I.e. float, int, int32_t, uint16_t, std::string, etc.\n  /// \\param attrname is the name of the Attribute to be read.\n  /// \\param data is a pointer-size pair to the data buffer that is filled with the metadata's\n  ///   contents. It should be pre-sized to accomodate all of the matadata. See\n  ///   getDimensions().numElements. Data will be filled in row-major order.\n  /// \\throws jedi::xError on a size mismatch between Attribute dimensions and data.size().\n  template <class DataType>\n  const DerivedHasAtts read(const std::string& attrname, gsl::span<DataType> data) const {\n    // Attribute att = this->open(attrname);\n    Attribute att = static_cast<const DerivedHasAtts*>(this)->open(attrname);\n    att.read(data);\n    return *(static_cast<const DerivedHasAtts*>(this));\n  }\n\n  /// \\brief Open and read an Attribute, with unknown dimensions.\n  /// \\tparam DataType is the type of the data. I.e. float, int, int32_t, uint16_t, std::string, etc.\n  /// \\param attrname is the name of the Attribute to be read.\n  /// \\param data is a vector acting as a data buffer that is filled with the metadata's\n  ///   contents. It gets resized as needed. data will be filled in row-major order.\n  template <class DataType>\n  const DerivedHasAtts read(const std::string& attrname, std::vector<DataType>& data) const {\n    Attribute att = static_cast<const DerivedHasAtts*>(this)->open(attrname);\n    att.read(data);\n    return *(static_cast<const DerivedHasAtts*>(this));\n  }\n\n  /// \\brief Open and read an Attribute, with unknown dimensions.\n  /// \\tparam DataType is the type of the data. I.e. float, int, int32_t, uint16_t, std::string, etc.\n  /// \\param attrname is the name of the Attribute to be read.\n  /// \\param data is a valarray acting as a data buffer that is filled with the metadata's\n  ///   contents. It gets resized as needed. data will be filled in row-major order.\n  template <class DataType>\n  const DerivedHasAtts read(const std::string& attrname, std::valarray<DataType>& data) const {\n    Attribute att = static_cast<const DerivedHasAtts*>(this)->open(attrname);\n    att.read(data);\n    return *(static_cast<const DerivedHasAtts*>(this));\n  }\n\n  /// \\brief Read a datum of an Attribute.\n  /// \\tparam DataType is the type of the data. I.e. float, int, int32_t, uint16_t, std::string, etc.\n  /// \\param attrname is the name of the Attribute to be read.\n  /// \\param data is a datum of type DataType.\n  /// \\throws jedi::xError if the underlying data have size > 1.\n  template <class DataType>\n  const DerivedHasAtts read(const std::string& attrname, DataType& data) const {\n    Attribute att = static_cast<const DerivedHasAtts*>(this)->open(attrname);\n    att.read<DataType>(data);\n    return *(static_cast<const DerivedHasAtts*>(this));\n  }\n\n  /// \\brief Read a datum of an Attribute.\n  /// \\tparam DataType is the type of the data. I.e. float, int, int32_t, uint16_t, std::string, etc.\n  /// \\param attrname is the name of the Attribute to be read.\n  /// \\returns A datum of type DataType.\n  /// \\throws jedi::xError if the underlying data have size > 1.\n  template <class DataType>\n  DataType read(const std::string& attrname) const {\n    Attribute att = static_cast<const DerivedHasAtts*>(this)->open(attrname);\n    return att.read<DataType>();\n  }\n\n  template <class EigenClass, bool Resize = detail::EigenCompat::CanResize<EigenClass>::value>\n  DerivedHasAtts readWithEigenRegular(const std::string& attrname, EigenClass& data) {\n#if 1  // __has_include(\"Eigen/Dense\")\n    Attribute att = static_cast<const DerivedHasAtts*>(this)->open(attrname);\n    att.readWithEigenRegular<EigenClass, Resize>(data);\n    return *(static_cast<const DerivedHasAtts*>(this));\n#else\n    static_assert(false, \"The Eigen headers cannot be found, so this function cannot be used.\")\n#endif\n  }\n\n  template <class EigenClass>\n  DerivedHasAtts readWithEigenTensor(const std::string& attrname, EigenClass& data) {\n#if 1  //__has_include(\"unsupported/Eigen/CXX11/Tensor\")\n    Attribute att = static_cast<const DerivedHasAtts*>(this)->open(attrname);\n    att.readWithEigenTensor<EigenClass>(data);\n    return *(static_cast<const DerivedHasAtts*>(this));\n#else\n    static_assert(\n      false, \"The Eigen unsupported/ headers cannot be found, so this function cannot be used.\");\n#endif\n  }\n\n  /// @}\n};\n\n/// \\ingroup ioda_cxx_attribute\nclass IODA_DL Has_Attributes_Base {\nprivate:\n  /// Using an opaque object to implement the backend.\n  std::shared_ptr<Has_Attributes_Backend> backend_;\n\n  // Backend classes do occasionally need access to the Attribute_Backend object.\n  friend class Group_Backend;\n  friend class Variable_Backend;\n\nprotected:\n  Has_Attributes_Base(std::shared_ptr<Has_Attributes_Backend>);\n\npublic:\n  virtual ~Has_Attributes_Base();\n\n  /// Query the backend and get the type provider.\n  virtual detail::Type_Provider* getTypeProvider() const;\n\n  /// @name General Functions\n  /// @{\n  ///\n\n  /// List all attributes\n  /// \\returns an unordered vector of attribute names for an object.\n  virtual std::vector<std::string> list() const;\n  /// List all attributes\n  /// \\returns an unordered vector of attribute names for an object.\n  inline std::vector<std::string> operator()() const { return list(); }\n\n  /// \\brief Does an Attribute with the specified name exist?\n  /// \\param attname is the name of the Attribute that we are looking for.\n  /// \\returns true if it exists.\n  /// \\returns false otherwise.\n  virtual bool exists(const std::string& attname) const;\n  /// \\brief Delete an Attribute with the specified name.\n  /// \\param attname is the name of the Attribute that we are deleting.\n  /// \\throws jedi::xError if no such attribute exists.\n  virtual void remove(const std::string& attname);\n  /// \\brief Open an Attribute by name\n  /// \\param name is the name of the Attribute to be opened.\n  /// \\returns An instance of an Attribute that can be queried (with getDimensions()) and read.\n  virtual Attribute open(const std::string& name) const;\n  /// \\brief Open Attribute by name\n  /// \\param name is the name of the Attribute to be opened.\n  /// \\returns An instance of Attribute that can be queried (with getDimensions()) and read.\n  inline Attribute operator[](const std::string& name) const { return open(name); }\n\n  /// \\brief Open all attributes in an object.\n  /// \\details This is a collective call, optimized for performance.\n  /// \\return A sequence of (name, Attribute) pairs.\n  virtual std::vector<std::pair<std::string, Attribute>> openAll() const;\n\n  /// \\brief Create an Attribute without setting its data.\n  /// \\param attrname is the name of the Attribute.\n  /// \\param dimensions is a vector representing the size of the metadata.\n  ///   Each element of the vector is a dimension with a certain size.\n  /// \\param in_memory_datatype is the runtime description of the Attribute's data type.\n  /// \\returns An instance of Attribute that can be written to.\n  virtual Attribute create(const std::string& attrname, const Type& in_memory_dataType,\n                           const std::vector<Dimensions_t>& dimensions = {1});\n\n  /// Python compatability function\n  inline Attribute _create_py(const std::string& attrname, BasicTypes dataType,\n                              const std::vector<Dimensions_t>& dimensions = {1}) {\n    return create(attrname, ::ioda::Type(dataType, getTypeProvider()), dimensions);\n  }\n\n  /// \\brief Create an Attribute without setting its data.\n  /// \\tparam DataType is the type of the data. I.e. float, int, uint16_t, std::string, etc.\n  /// \\param attrname is the name of the Attribute.\n  /// \\param dimensions is a vector representing the size of the metadata. Each element of the\n  ///   vector is a dimension with a certain size.\n  /// \\returns An instance of Attribute that can be written to.\n  template <class DataType, class TypeWrapper = Types::GetType_Wrapper<DataType>>\n  Attribute create(const std::string& attrname,\n                   const std::vector<Dimensions_t>& dimensions = {1}) {\n    try {\n      Type in_memory_dataType = TypeWrapper::GetType(getTypeProvider());\n      auto att                = create(attrname, in_memory_dataType, dimensions);\n      return att;\n    } catch (...) {\n      std::throw_with_nested(Exception(ioda_Here()));\n    }\n  }\n\n  /// \\brief Rename an Attribute\n  /// \\param oldName is the name of the Attribute to be changed.\n  /// \\param newName is the new name of the Attribute.\n  /// \\throws jedi::xError if oldName is not found.\n  /// \\throws jedi::xError if newName already exists.\n  virtual void rename(const std::string& oldName, const std::string& newName);\n\n  /// @}\n};\n\nclass IODA_DL Has_Attributes_Backend : public Has_Attributes_Base {\nprotected:\n  Has_Attributes_Backend();\n\npublic:\n  virtual ~Has_Attributes_Backend();\n\n  /// \\brief Default implementation of Has_Attributes_Base::openAll.\n  /// \\see Has_Attributes_Base::openAll.\n  std::vector<std::pair<std::string, Attribute>> openAll() const override;\n};\n}  // namespace detail\n\n/** \\brief This class exists inside of ioda::Group or ioda::Variable and provides\n *         the interface to manipulating Attributes.\n * \\ingroup ioda_cxx_attribute\n *\n * \\note It should only be constructed inside of a Group or Variable.\n *       It has no meaning elsewhere.\n * \\see Attribute for the class that represents individual attributes.\n * \\throws jedi::xError on all exceptions.\n **/\nclass IODA_DL Has_Attributes : public detail::CanAddAttributes<Has_Attributes>,\n                               public detail::CanReadAttributes<Has_Attributes>,\n                               public detail::Has_Attributes_Base {\npublic:\n  Has_Attributes();\n  Has_Attributes(std::shared_ptr<detail::Has_Attributes_Backend>);\n  virtual ~Has_Attributes();\n};\n\n}  // namespace ioda\n\n/// @} // End Doxygen block\n", "meta": {"hexsha": "9785a8515685b7010bdd96d26adc8217b94bde89", "size": 17752, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engines/ioda/include/ioda/Attributes/Has_Attributes.h", "max_stars_repo_name": "Gibies/ioda", "max_stars_repo_head_hexsha": "5bd372e548eb61d5f7b56a0b3d4cf0ca05e49e75", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-09T16:11:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-09T16:11:50.000Z", "max_issues_repo_path": "src/engines/ioda/include/ioda/Attributes/Has_Attributes.h", "max_issues_repo_name": "Gibies/ioda", "max_issues_repo_head_hexsha": "5bd372e548eb61d5f7b56a0b3d4cf0ca05e49e75", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engines/ioda/include/ioda/Attributes/Has_Attributes.h", "max_forks_repo_name": "Gibies/ioda", "max_forks_repo_head_hexsha": "5bd372e548eb61d5f7b56a0b3d4cf0ca05e49e75", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-06-09T16:12:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-14T09:19:25.000Z", "avg_line_length": 44.38, "max_line_length": 101, "alphanum_fraction": 0.7084272195, "num_tokens": 4299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.0769608314618395, "lm_q2_score": 0.02517884069479755, "lm_q1q2_score": 0.0019377845151168202}}
{"text": "#pragma once\n\n#include \"ShaderCompiler.h\"\n#include \"BgfxCallback.h\"\n\n#include <Babylon/JsRuntime.h>\n#include <Babylon/JsRuntimeScheduler.h>\n\n#include <GraphicsImpl.h>\n\n#include <NativeWindow.h>\n\n#include <napi/napi.h>\n\n#include <bgfx/bgfx.h>\n#include <bgfx/platform.h>\n#include <bimg/bimg.h>\n#include <bx/allocator.h>\n\n#include <gsl/gsl>\n\n#include <assert.h>\n\n#include <arcana/containers/weak_table.h>\n#include <arcana/threading/cancellation.h>\n#include <unordered_map>\n\nnamespace Babylon\n{\n    class ClearState final\n    {\n    public:\n        void UpdateColor(float r, float g, float b, float a)\n        {\n            const bool needToUpdate = r != Red || g != Green || b != Blue || a != Alpha;\n            if (needToUpdate)\n            {\n                Red = r;\n                Green = g;\n                Blue = b;\n                Alpha = a;\n                Update();\n            }\n        }\n\n        void UpdateFlags(const Napi::CallbackInfo& info)\n        {\n            const auto flags = static_cast<uint16_t>(info[0].As<Napi::Number>().Uint32Value());\n            Flags = flags;\n            Update();\n        }\n\n        void UpdateDepth(const Napi::CallbackInfo& info)\n        {\n            const auto depth = info[0].As<Napi::Number>().FloatValue();\n            const bool needToUpdate = Depth != depth;\n            if (needToUpdate)\n            {\n                Depth = depth;\n                Update();\n            }\n        }\n\n        void UpdateStencil(const Napi::CallbackInfo& info)\n        {\n            const auto stencil = static_cast<uint8_t>(info[0].As<Napi::Number>().Int32Value());\n            const bool needToUpdate = Stencil != stencil;\n            if (needToUpdate)\n            {\n                Stencil = stencil;\n                Update();\n            }\n        }\n\n        arcana::weak_table<std::function<void()>>::ticket AddUpdateCallback(std::function<void()> callback)\n        {\n            return m_callbacks.insert(std::move(callback));\n        }\n\n        void Update()\n        {\n            m_callbacks.apply_to_all([](std::function<void()>& callback) {\n                callback();\n            });\n        }\n\n        uint32_t Color() const\n        {\n            uint32_t color = 0x0;\n            color += static_cast<uint8_t>(Red * std::numeric_limits<uint8_t>::max());\n            color = color << 8;\n            color += static_cast<uint8_t>(Green * std::numeric_limits<uint8_t>::max());\n            color = color << 8;\n            color += static_cast<uint8_t>(Blue * std::numeric_limits<uint8_t>::max());\n            color = color << 8;\n            color += static_cast<uint8_t>(Alpha * std::numeric_limits<uint8_t>::max());\n            return color;\n        }\n\n        float Red{68.f / 255.f};\n        float Green{51.f / 255.f};\n        float Blue{85.f / 255.f};\n        float Alpha{1.f};\n        float Depth{1.f};\n        uint16_t Flags{BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH};\n        uint8_t Stencil{0};\n\n    private:\n        arcana::weak_table<std::function<void()>> m_callbacks{};\n    };\n\n    class ViewClearState final\n    {\n    public:\n        ViewClearState(uint16_t viewId, ClearState& clearState)\n            : m_viewId{viewId} \n            , m_clearState{clearState}\n            , m_callbackTicket{m_clearState.AddUpdateCallback([this]() { Update(); })}\n        {\n        }\n\n        void UpdateColor(float r, float g, float b, float a = 1.f)\n        {\n            m_clearState.UpdateColor(r, g, b, a);\n        }\n\n        void UpdateColor(const Napi::CallbackInfo& info)\n        {\n            const auto r = info[0].As<Napi::Number>().FloatValue();\n            const auto g = info[1].As<Napi::Number>().FloatValue();\n            const auto b = info[2].As<Napi::Number>().FloatValue();\n            const auto a = info[3].IsUndefined() ? 1.f : info[3].As<Napi::Number>().FloatValue();\n            m_clearState.UpdateColor(r, g, b, a);\n        }\n\n        void UpdateFlags(const Napi::CallbackInfo& info)\n        {\n            m_clearState.UpdateFlags(info);\n        }\n\n        void UpdateDepth(const Napi::CallbackInfo& info)\n        {\n            m_clearState.UpdateDepth(info);\n        }\n\n        void UpdateStencil(const Napi::CallbackInfo& info)\n        {\n            m_clearState.UpdateStencil(info);\n        }\n\n        void UpdateViewId(uint16_t viewId)\n        {\n            m_viewId = viewId;\n            Update();\n        }\n\n    private:\n\n        void Update() const\n        {\n            bgfx::setViewClear(m_viewId, m_clearState.Flags, m_clearState.Color(), m_clearState.Depth, m_clearState.Stencil);\n            // discard any previous set state\n            bgfx::discard();\n        }\n\n        uint16_t m_viewId{};\n        ClearState& m_clearState;\n        arcana::weak_table<std::function<void()>>::ticket m_callbackTicket;\n    };\n\n    struct FrameBufferData final\n    {\n    private:\n        std::unique_ptr<ClearState> m_clearState{};\n\n    public:\n        FrameBufferData(bgfx::FrameBufferHandle frameBuffer, uint16_t viewId, uint16_t width, uint16_t height, bool actAsBackBuffer = false)\n            : m_clearState{std::make_unique<ClearState>()}\n            , FrameBuffer{frameBuffer}\n            , ViewId{viewId}\n            , ViewClearState{ViewId, *m_clearState}\n            , Width{width}\n            , Height{height}\n            , ActAsBackBuffer{actAsBackBuffer}\n        {\n            assert(ViewId < bgfx::getCaps()->limits.maxViews);\n        }\n\n        FrameBufferData(bgfx::FrameBufferHandle frameBuffer, uint16_t viewId, ClearState& clearState, uint16_t width, uint16_t height, bool actAsBackBuffer = false)\n            : m_clearState{}\n            , FrameBuffer{frameBuffer}\n            , ViewId{viewId}\n            , ViewClearState{ViewId, clearState}\n            , Width{width}\n            , Height{height}\n            , ActAsBackBuffer{actAsBackBuffer}\n        {\n            assert(ViewId < bgfx::getCaps()->limits.maxViews);\n        }\n\n        FrameBufferData(FrameBufferData&) = delete;\n\n        ~FrameBufferData()\n        {\n            bgfx::destroy(FrameBuffer);\n        }\n\n        void UseViewId(uint16_t viewId)\n        {\n            ViewId = viewId;\n            ViewClearState.UpdateViewId(ViewId);\n        }\n\n        void SetUpView(uint16_t viewId)\n        {\n            bgfx::setViewFrameBuffer(viewId, FrameBuffer);\n            UseViewId(viewId);\n            bgfx::setViewRect(ViewId, 0, 0, Width, Height);\n        }\n\n        bgfx::FrameBufferHandle FrameBuffer{bgfx::kInvalidHandle};\n        bgfx::ViewId ViewId{};\n        Babylon::ViewClearState ViewClearState;\n        uint16_t Width{};\n        uint16_t Height{};\n        // When a FrameBuffer acts as a back buffer, it means it will not be used as a texture in a shader.\n        // For example as a post process. It will be used as-is in a swapchain or for direct rendering (XR)\n        // When this flag is true, projection matrix will not be flipped for API that would normaly need it.\n        // Namely Direct3D and Metal.\n        bool ActAsBackBuffer{false};\n    };\n\n    struct FrameBufferManager final\n    {\n        FrameBufferManager()\n        {\n            m_boundFrameBuffer = m_backBuffer = new FrameBufferData(BGFX_INVALID_HANDLE, GetNewViewId(), bgfx::getStats()->width, bgfx::getStats()->height);\n        }\n\n        FrameBufferData* CreateNew(bgfx::FrameBufferHandle frameBufferHandle, uint16_t width, uint16_t height)\n        {\n            return new FrameBufferData(frameBufferHandle, GetNewViewId(), width, height);\n        }\n\n        FrameBufferData* CreateNew(bgfx::FrameBufferHandle frameBufferHandle, ClearState& clearState, uint16_t width, uint16_t height, bool actAsBackBuffer)\n        {\n            return new FrameBufferData(frameBufferHandle, GetNewViewId(), clearState, width, height, actAsBackBuffer);\n        }\n\n        void Bind(FrameBufferData* data)\n        {\n            m_boundFrameBuffer = data;\n\n            // TODO: Consider doing this only on bgfx::reset(); the effects of this call don't survive reset, but as\n            // long as there's no reset this doesn't technically need to be called every time the frame buffer is bound.\n            m_boundFrameBuffer->SetUpView(GetNewViewId());\n\n            // bgfx::setTexture()? Why?\n            // TODO: View order?\n            m_renderingToTarget = !m_boundFrameBuffer->ActAsBackBuffer;\n        }\n\n        FrameBufferData& GetBound() const\n        {\n            return *m_boundFrameBuffer;\n        }\n\n        void Unbind(FrameBufferData* data)\n        {\n            // this assert is commented because of an issue with XR described here : https://github.com/BabylonJS/BabylonNative/issues/344\n            //assert(m_boundFrameBuffer == data);\n            (void)data;\n            m_boundFrameBuffer = m_backBuffer;\n            m_renderingToTarget = false;\n        }\n\n        uint16_t GetNewViewId()\n        {\n            m_nextId++;\n            assert(m_nextId < bgfx::getCaps()->limits.maxViews);\n            return m_nextId;\n        }\n\n        void Reset()\n        {\n            m_nextId = 0;\n        }\n\n        bool IsRenderingToTarget() const\n        {\n            return m_renderingToTarget;\n        }\n\n    private:\n        FrameBufferData* m_boundFrameBuffer{nullptr};\n        FrameBufferData* m_backBuffer{nullptr};\n        uint16_t m_nextId{0};\n        bool m_renderingToTarget{false};\n    };\n\n    struct TextureData final\n    {\n        ~TextureData()\n        {\n            if (bgfx::isValid(Handle))\n            {\n                bgfx::destroy(Handle);\n            }\n        }\n\n        bgfx::TextureHandle Handle{bgfx::kInvalidHandle};\n        uint32_t Width{0};\n        uint32_t Height{0};\n        uint32_t Flags{0};\n        uint8_t AnisotropicLevel{0};\n    };\n\n    struct ImageData final\n    {\n        ~ImageData()\n        {\n            if (Image)\n            {\n                bimg::imageFree(Image.get());\n            }\n        }\n        std::unique_ptr<bimg::ImageContainer> Image;\n    };\n\n    struct UniformInfo final\n    {\n        uint8_t Stage{};\n        bgfx::UniformHandle Handle{bgfx::kInvalidHandle};\n        bool YFlip{false};\n    };\n\n    struct ProgramData final\n    {\n        ProgramData() = default;\n        ProgramData(const ProgramData&) = delete;\n        ProgramData(ProgramData&&) = delete;\n\n        ~ProgramData()\n        {\n            bgfx::destroy(Program);\n        }\n\n        std::unordered_map<std::string, uint32_t> VertexAttributeLocations{};\n        std::unordered_map<std::string, UniformInfo> VertexUniformInfos{};\n        std::unordered_map<std::string, UniformInfo> FragmentUniformInfos{};\n\n        bgfx::ProgramHandle Program{};\n\n        struct UniformValue\n        {\n            std::vector<float> Data{};\n            uint16_t ElementLength{};\n            bool YFlip{false};\n        };\n\n        std::unordered_map<uint16_t, UniformValue> Uniforms{};\n\n        void SetUniform(bgfx::UniformHandle handle, gsl::span<const float> data, bool YFlip, size_t elementLength = 1)\n        {\n            UniformValue& value = Uniforms[handle.idx];\n            value.Data.assign(data.begin(), data.end());\n            value.ElementLength = static_cast<uint16_t>(elementLength);\n            value.YFlip = YFlip;\n        }\n    };\n\n    class IndexBufferData;\n    class VertexBufferData;\n\n    struct VertexArray final\n    {\n        ~VertexArray()\n        {\n            for (auto& vertexBuffer : vertexBuffers)\n            {\n                bgfx::destroy(vertexBuffer.vertexLayoutHandle);\n            }\n        }\n\n        struct IndexBuffer\n        {\n            const IndexBufferData* data{};\n        };\n\n        IndexBuffer indexBuffer{};\n\n        struct VertexBuffer\n        {\n            const VertexBufferData* data{};\n            uint32_t startVertex{};\n            bgfx::VertexLayoutHandle vertexLayoutHandle{};\n        };\n\n        std::vector<VertexBuffer> vertexBuffers{};\n    };\n\n    class NativeEngine final : public Napi::ObjectWrap<NativeEngine>\n    {\n        static constexpr auto JS_CLASS_NAME = \"_NativeEngine\";\n        static constexpr auto JS_ENGINE_CONSTRUCTOR_NAME = \"Engine\";\n        static constexpr auto JS_AUTO_RENDER_PROPERTY_NAME = \"_AUTO_RENDER\";\n\n    public:\n        NativeEngine(const Napi::CallbackInfo& info);\n        NativeEngine(const Napi::CallbackInfo& info, JsRuntime& runtime, Plugins::Internal::NativeWindow& nativeWindow);\n        ~NativeEngine();\n\n        static void Initialize(Napi::Env, bool autoRender);\n\n        FrameBufferManager& GetFrameBufferManager();\n        void Dispatch(std::function<void()>);\n\n        void ScheduleRender();\n\n        const bool AutomaticRenderingEnabled{};\n        JsRuntimeScheduler RuntimeScheduler;\n\n    private:\n        void Dispose();\n\n        void Dispose(const Napi::CallbackInfo& info);\n        Napi::Value GetEngine(const Napi::CallbackInfo& info); // TODO: Hack, temporary method. Remove as part of the change to get rid of NapiBridge.\n        void RequestAnimationFrame(const Napi::CallbackInfo& info);\n        Napi::Value CreateVertexArray(const Napi::CallbackInfo& info);\n        void DeleteVertexArray(const Napi::CallbackInfo& info);\n        void BindVertexArray(const Napi::CallbackInfo& info);\n        Napi::Value CreateIndexBuffer(const Napi::CallbackInfo& info);\n        void DeleteIndexBuffer(const Napi::CallbackInfo& info);\n        void RecordIndexBuffer(const Napi::CallbackInfo& info);\n        void UpdateDynamicIndexBuffer(const Napi::CallbackInfo& info);\n        Napi::Value CreateVertexBuffer(const Napi::CallbackInfo& info);\n        void DeleteVertexBuffer(const Napi::CallbackInfo& info);\n        void RecordVertexBuffer(const Napi::CallbackInfo& info);\n        void UpdateDynamicVertexBuffer(const Napi::CallbackInfo& info);\n        Napi::Value CreateProgram(const Napi::CallbackInfo& info);\n        Napi::Value GetUniforms(const Napi::CallbackInfo& info);\n        Napi::Value GetAttributes(const Napi::CallbackInfo& info);\n        void SetProgram(const Napi::CallbackInfo& info);\n        void SetState(const Napi::CallbackInfo& info);\n        void SetZOffset(const Napi::CallbackInfo& info);\n        Napi::Value GetZOffset(const Napi::CallbackInfo& info);\n        void SetDepthTest(const Napi::CallbackInfo& info);\n        Napi::Value GetDepthWrite(const Napi::CallbackInfo& info);\n        void SetDepthWrite(const Napi::CallbackInfo& info);\n        void SetColorWrite(const Napi::CallbackInfo& info);\n        void SetBlendMode(const Napi::CallbackInfo& info);\n        void SetMatrix(const Napi::CallbackInfo& info);\n        void SetInt(const Napi::CallbackInfo& info);\n        void SetIntArray(const Napi::CallbackInfo& info);\n        void SetIntArray2(const Napi::CallbackInfo& info);\n        void SetIntArray3(const Napi::CallbackInfo& info);\n        void SetIntArray4(const Napi::CallbackInfo& info);\n        void SetFloatArray(const Napi::CallbackInfo& info);\n        void SetFloatArray2(const Napi::CallbackInfo& info);\n        void SetFloatArray3(const Napi::CallbackInfo& info);\n        void SetFloatArray4(const Napi::CallbackInfo& info);\n        void SetMatrices(const Napi::CallbackInfo& info);\n        void SetMatrix3x3(const Napi::CallbackInfo& info);\n        void SetMatrix2x2(const Napi::CallbackInfo& info);\n        void SetFloat(const Napi::CallbackInfo& info);\n        void SetFloat2(const Napi::CallbackInfo& info);\n        void SetFloat3(const Napi::CallbackInfo& info);\n        void SetFloat4(const Napi::CallbackInfo& info);\n        Napi::Value CreateTexture(const Napi::CallbackInfo& info);\n        Napi::Value CreateDepthTexture(const Napi::CallbackInfo& info);\n        void LoadTexture(const Napi::CallbackInfo& info);\n        void LoadCubeTexture(const Napi::CallbackInfo& info);\n        void LoadCubeTextureWithMips(const Napi::CallbackInfo& info);\n        Napi::Value GetTextureWidth(const Napi::CallbackInfo& info);\n        Napi::Value GetTextureHeight(const Napi::CallbackInfo& info);\n        void SetTextureSampling(const Napi::CallbackInfo& info);\n        void SetTextureWrapMode(const Napi::CallbackInfo& info);\n        void SetTextureAnisotropicLevel(const Napi::CallbackInfo& info);\n        void SetTexture(const Napi::CallbackInfo& info);\n        void DeleteTexture(const Napi::CallbackInfo& info);\n        Napi::Value CreateFrameBuffer(const Napi::CallbackInfo& info);\n        void DeleteFrameBuffer(const Napi::CallbackInfo& info);\n        void BindFrameBuffer(const Napi::CallbackInfo& info);\n        void UnbindFrameBuffer(const Napi::CallbackInfo& info);\n        void DrawIndexed(const Napi::CallbackInfo& info);\n        void Draw(const Napi::CallbackInfo& info);\n        void Clear(const Napi::CallbackInfo& info);\n        void ClearColor(const Napi::CallbackInfo& info);\n        void ClearStencil(const Napi::CallbackInfo& info);\n        void ClearDepth(const Napi::CallbackInfo& info);\n        Napi::Value GetRenderWidth(const Napi::CallbackInfo& info);\n        Napi::Value GetRenderHeight(const Napi::CallbackInfo& info);\n        void SetViewPort(const Napi::CallbackInfo& info);\n        void GetFramebufferData(const Napi::CallbackInfo& info);\n        Napi::Value GetRenderAPI(const Napi::CallbackInfo& info);\n\n        void UpdateSize(size_t width, size_t height);\n\n        template<typename SchedulerT>\n        arcana::task<void, std::exception_ptr> GetRequestAnimationFrameTask(SchedulerT&);\n        \n        bool m_isRenderScheduled{false};\n\n        arcana::cancellation_source m_cancelSource{};\n\n        ShaderCompiler m_shaderCompiler;\n\n        ProgramData* m_currentProgram{nullptr};\n        arcana::weak_table<std::unique_ptr<ProgramData>> m_programDataCollection{};\n\n        JsRuntime& m_runtime;\n        Graphics::Impl& m_graphicsImpl;\n\n        bx::DefaultAllocator m_allocator;\n        uint64_t m_engineState;\n\n        FrameBufferManager m_frameBufferManager{};\n\n        Plugins::Internal::NativeWindow::NativeWindow::OnResizeCallbackTicket m_resizeCallbackTicket;\n\n        template<int size, typename arrayType>\n        void SetTypeArrayN(const Napi::CallbackInfo& info);\n\n        template<int size>\n        void SetFloatN(const Napi::CallbackInfo& info);\n\n        template<int size>\n        void SetMatrixN(const Napi::CallbackInfo& info);\n\n        // Scratch vector used for data alignment.\n        std::vector<float> m_scratch{};\n        \n        Napi::FunctionReference m_requestAnimationFrameCallback{};\n\n        // webgl/opengl draw call parameters allow to set first index and number of indices used for that call\n        // but with bgfx, those parameters must be set when binding the index buffer\n        // at the time of webgl binding, we don't know those values yet\n        // so a pointer to the to-bind buffer is kept and the buffer is bound to bgfx at the time of the drawcall\n        const IndexBufferData* m_currentBoundIndexBuffer{};\n    };\n}\n", "meta": {"hexsha": "a6170cc44ebc39bd7096566876eb43b70b8c62f8", "size": 18767, "ext": "h", "lang": "C", "max_stars_repo_path": "Plugins/NativeEngine/Source/NativeEngine.h", "max_stars_repo_name": "syntheticmagus/BabylonNative", "max_stars_repo_head_hexsha": "e81f65f129e5f93a343ab79e0fc93a18f4f10899", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Plugins/NativeEngine/Source/NativeEngine.h", "max_issues_repo_name": "syntheticmagus/BabylonNative", "max_issues_repo_head_hexsha": "e81f65f129e5f93a343ab79e0fc93a18f4f10899", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Plugins/NativeEngine/Source/NativeEngine.h", "max_forks_repo_name": "syntheticmagus/BabylonNative", "max_forks_repo_head_hexsha": "e81f65f129e5f93a343ab79e0fc93a18f4f10899", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6254612546, "max_line_length": 164, "alphanum_fraction": 0.6135237385, "num_tokens": 4245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09670579850281288, "lm_q2_score": 0.020023440887407887, "lm_q1q2_score": 0.001936382839790652}}
{"text": "#ifndef Dark_Arts_Exception_h\r\n#define Dark_Arts_Exception_h\r\n\r\n#include \"Exception_Types.h\"\r\n#include <stdlib.h>\r\n#include <iostream>\r\n#include <sstream>\r\n#include <petsc.h>\r\n\r\nclass Dark_Arts_Exception\r\n{\r\npublic:\r\n  Dark_Arts_Exception( EXCEPTION_TYPE ex_type , const std::string& ex_message);\r\n  Dark_Arts_Exception( EXCEPTION_TYPE ex_type , const std::stringstream& ex_message);\r\n  Dark_Arts_Exception();\r\n  virtual ~Dark_Arts_Exception(){}\r\n\r\n  void message(void) const;\r\n  void testing_message(void) const;\r\n  \r\nprivate:\r\n  std::string error_message;\r\n};\r\n\r\n\r\n#endif\r\n\r\n", "meta": {"hexsha": "849138ce6ff0217469636de2e408252028ed13c9", "size": 577, "ext": "h", "lang": "C", "max_stars_repo_path": "src/exceptions/Dark_Arts_Exception.h", "max_stars_repo_name": "pgmaginot/DARK_ARTS", "max_stars_repo_head_hexsha": "f04b0a30dcac911ef06fe0916921020826f5c42b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/exceptions/Dark_Arts_Exception.h", "max_issues_repo_name": "pgmaginot/DARK_ARTS", "max_issues_repo_head_hexsha": "f04b0a30dcac911ef06fe0916921020826f5c42b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/exceptions/Dark_Arts_Exception.h", "max_forks_repo_name": "pgmaginot/DARK_ARTS", "max_forks_repo_head_hexsha": "f04b0a30dcac911ef06fe0916921020826f5c42b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.6071428571, "max_line_length": 86, "alphanum_fraction": 0.7348353553, "num_tokens": 130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.05500528829345414, "lm_q2_score": 0.03514484804299783, "lm_q1q2_score": 0.0019331524986347332}}
{"text": "#pragma once\n\n#include <bgfx/bgfx.h>\n#include <napi/napi.h>\n#include <gsl/gsl>\n\n#include <optional>\n\nnamespace Babylon\n{\n    class IndexBuffer final\n    {\n    public:\n        IndexBuffer(gsl::span<uint8_t> bytes, uint16_t flags, bool dynamic);\n        ~IndexBuffer();\n\n        void Dispose();\n\n        void Update(Napi::Env env, gsl::span<uint8_t> bytes, uint32_t startIndex);\n        bool CreateHandle();\n        void Set(bgfx::Encoder* encoder, uint32_t firstIndex, uint32_t numIndices);\n\n    private:\n        std::optional<std::vector<uint8_t>> m_bytes{};\n        uint16_t m_flags{};\n        bool m_dynamic{};\n\n        union\n        {\n            bgfx::IndexBufferHandle m_handle{bgfx::kInvalidHandle};\n            bgfx::DynamicIndexBufferHandle m_dynamicHandle;\n        };\n\n        bool m_disposed{};\n    };\n}\n", "meta": {"hexsha": "b30dbaa8336876aac2dff28a8462dc8c557a5db2", "size": 814, "ext": "h", "lang": "C", "max_stars_repo_path": "Modules/@babylonjs/react-native/submodules/BabylonNative/Plugins/NativeEngine/Source/IndexBuffer.h", "max_stars_repo_name": "HarveyLijh/ReactNativeBabylon", "max_stars_repo_head_hexsha": "d9ac79d1e1a00f03f9a4fcf5419e5b118e65e586", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Modules/@babylonjs/react-native/submodules/BabylonNative/Plugins/NativeEngine/Source/IndexBuffer.h", "max_issues_repo_name": "HarveyLijh/ReactNativeBabylon", "max_issues_repo_head_hexsha": "d9ac79d1e1a00f03f9a4fcf5419e5b118e65e586", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Modules/@babylonjs/react-native/submodules/BabylonNative/Plugins/NativeEngine/Source/IndexBuffer.h", "max_forks_repo_name": "HarveyLijh/ReactNativeBabylon", "max_forks_repo_head_hexsha": "d9ac79d1e1a00f03f9a4fcf5419e5b118e65e586", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0, "max_line_length": 83, "alphanum_fraction": 0.6154791155, "num_tokens": 200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1023047024186547, "lm_q2_score": 0.018833128582521005, "lm_q1q2_score": 0.0019267176152470717}}
{"text": "//          Copyright Jean Pierre Cimalando 2019.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE.md or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n#pragma once\n#include \"keystate.h\"\n#include <gsl/gsl>\n#include <string>\n#include <cstdint>\n\nstruct Midi_Output {\n    std::string id;\n    std::string name;\n};\n\nenum Midi_Message_Flag {\n    Midi_Message_Is_First = 1,\n};\n\n///\nclass Midi_Instrument {\npublic:\n    Midi_Instrument();\n    virtual ~Midi_Instrument() {}\n    void send_message(const uint8_t *data, unsigned len, double ts, uint8_t flags);\n    void initialize();\n    void all_sound_off();\n\n    const Keyboard_State &keyboard_state() const noexcept { return kbs_; }\n\n    virtual void flush_events() {}\n\n    virtual void open_midi_output(gsl::cstring_span id) = 0;\n    virtual void close_midi_output() = 0;\n\n    virtual bool is_synth() const { return false; }\n\nprotected:\n    virtual void handle_send_message(const uint8_t *data, unsigned len, double ts, uint8_t flags) = 0;\n\nprivate:\n    Keyboard_State kbs_;\n};\n", "meta": {"hexsha": "1bac9210de3c8de8ac24182adbe01a3aca48c5c2", "size": 1081, "ext": "h", "lang": "C", "max_stars_repo_path": "sources/player/instrument.h", "max_stars_repo_name": "jpcima/smf-dsp", "max_stars_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2020-07-08T15:23:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T23:08:17.000Z", "max_issues_repo_path": "sources/player/instrument.h", "max_issues_repo_name": "jpcima/smf-dsp", "max_issues_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2020-07-05T23:59:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-16T20:44:07.000Z", "max_forks_repo_path": "sources/player/instrument.h", "max_forks_repo_name": "jpcima/smf-dsp", "max_forks_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-07-10T18:48:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-22T08:05:13.000Z", "avg_line_length": 24.0222222222, "max_line_length": 102, "alphanum_fraction": 0.6956521739, "num_tokens": 267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.0850990380460446, "lm_q2_score": 0.022629199662270155, "lm_q1q2_score": 0.0019257231230110675}}
{"text": "#pragma once\n\n#include \"Cesium3DTiles/BoundingVolume.h\"\n#include \"Cesium3DTiles/Gltf.h\"\n#include \"Cesium3DTiles/Library.h\"\n#include \"Cesium3DTiles/TileContentLoadResult.h\"\n#include \"Cesium3DTiles/TileContentLoader.h\"\n#include \"Cesium3DTiles/TileID.h\"\n#include \"Cesium3DTiles/TileRefine.h\"\n#include \"CesiumGltf/GltfReader.h\"\n#include <cstddef>\n#include <glm/mat4x4.hpp>\n#include <gsl/span>\n#include <spdlog/fwd.h>\n\nnamespace Cesium3DTiles {\n\nclass Tileset;\n\n/**\n * @brief Creates {@link TileContentLoadResult} from glTF data.\n */\nclass CESIUM3DTILES_API GltfContent final : public TileContentLoader {\npublic:\n  /**\n   * @copydoc TileContentLoader::load\n   *\n   * The result will only contain the `model`. Other fields will be\n   * empty or have default values.\n   */\n  std::unique_ptr<TileContentLoadResult>\n  load(const TileContentLoadInput& input) override;\n\n  /**\n   * @brief Create a {@link TileContentLoadResult} from the given data.\n   *\n   * (Only public to be called from `Batched3DModelContent`)\n   *\n   * @param pLogger Only used for logging\n   * @param url The URL, only used for logging\n   * @param data The actual glTF data\n   * @return The {@link TileContentLoadResult}\n   */\n  static std::unique_ptr<TileContentLoadResult> load(\n      const std::shared_ptr<spdlog::logger>& pLogger,\n      const std::string& url,\n      const gsl::span<const std::byte>& data);\n\n  /**\n   * @brief Creates texture coordinates for raster tiles that are mapped to 3D\n   * tiles.\n   *\n   * This is not supposed to be called by clients.\n   *\n   * It will be called for all {@link RasterMappedTo3DTile} objects of a\n   * {@link Tile}, and extend the accessors of the given glTF model with\n   * accessors that contain the texture coordinate sets for different\n   * projections. Further details are not specified here.\n   *\n   * @param gltf The glTF model.\n   * @param textureCoordinateID The texture coordinate ID.\n   * @param projection The {@link CesiumGeospatial::Projection}.\n   * @param rectangle The {@link CesiumGeometry::Rectangle}.\n   * @return The bounding region.\n   */\n  static CesiumGeospatial::BoundingRegion createRasterOverlayTextureCoordinates(\n      CesiumGltf::Model& gltf,\n      uint32_t textureCoordinateID,\n      const CesiumGeospatial::Projection& projection,\n      const CesiumGeometry::Rectangle& rectangle);\n\nprivate:\n  static CesiumGltf::GltfReader _gltfReader;\n};\n\n} // namespace Cesium3DTiles\n", "meta": {"hexsha": "edd11c5d0ecfec1ae0546de0ff9a42696f221d66", "size": 2411, "ext": "h", "lang": "C", "max_stars_repo_path": "Cesium3DTiles/include/Cesium3DTiles/GltfContent.h", "max_stars_repo_name": "zy6p/cesium-native", "max_stars_repo_head_hexsha": "d7b02d0c229e54e626e313bf2cfab31ed6e8ac3b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Cesium3DTiles/include/Cesium3DTiles/GltfContent.h", "max_issues_repo_name": "zy6p/cesium-native", "max_issues_repo_head_hexsha": "d7b02d0c229e54e626e313bf2cfab31ed6e8ac3b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cesium3DTiles/include/Cesium3DTiles/GltfContent.h", "max_forks_repo_name": "zy6p/cesium-native", "max_forks_repo_head_hexsha": "d7b02d0c229e54e626e313bf2cfab31ed6e8ac3b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3116883117, "max_line_length": 80, "alphanum_fraction": 0.7274989631, "num_tokens": 641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09268777112054057, "lm_q2_score": 0.02064593224570178, "lm_q1q2_score": 0.0019136254425597948}}
{"text": "/*\n *  Copyright (C) 2021 FISCO BCOS.\n *  SPDX-License-Identifier: Apache-2.0\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n * @brief interface for BlockHeader\n * @file BlockHeader.h\n * @author: yujiechen\n * @date: 2021-03-22\n */\n#pragma once\n#include \"Exceptions.h\"\n#include \"ProtocolTypeDef.h\"\n#include <bcos-crypto/interfaces/crypto/CryptoSuite.h>\n#include <bcos-utilities/DataConvertUtility.h>\n#include <gsl/span>\n\nnamespace bcos\n{\nnamespace protocol\n{\nclass BlockHeader\n{\npublic:\n    using Ptr = std::shared_ptr<BlockHeader>;\n    using ConstPtr = std::shared_ptr<const BlockHeader>;\n    using BlockHeadersPtr = std::shared_ptr<std::vector<BlockHeader::Ptr> >;\n    explicit BlockHeader(bcos::crypto::CryptoSuite::Ptr _cryptoSuite) : m_cryptoSuite(_cryptoSuite)\n    {}\n\n    virtual ~BlockHeader() {}\n\n    virtual void decode(bytesConstRef _data) = 0;\n    virtual void encode(bytes& _encodeData) const = 0;\n\n    virtual bcos::crypto::HashType hash() const { return {}; }\n\n    virtual void populateFromParents(BlockHeadersPtr _parents, BlockNumber _number)\n    {\n        // set parentInfo\n        ParentInfoList parentInfoList;\n        for (auto parentHeader : *_parents)\n        {\n            ParentInfo parentInfo;\n            parentInfo.blockNumber = parentHeader->number();\n            parentInfo.blockHash = parentHeader->hash();\n            parentInfoList.emplace_back(parentInfo);\n        }\n        setParentInfo(std::move(parentInfoList));\n        setNumber(_number);\n    }\n\n    virtual void clear() = 0;\n\n    // verifySignatureList verifys the signatureList\n    virtual void verifySignatureList() const\n    {\n        auto signatures = signatureList();\n        auto sealers = sealerList();\n        if (signatures.size() < sealers.size())\n        {\n            BOOST_THROW_EXCEPTION(InvalidBlockHeader() << errinfo_comment(\n                                      \"Invalid blockHeader for the size of sealerList \"\n                                      \"is smaller than the size of signatureList\"));\n        }\n        for (auto signature : signatures)\n        {\n            auto sealerIndex = signature.index;\n            auto signatureData = signature.signature;\n            if (!m_cryptoSuite->signatureImpl()->verify(\n                    std::shared_ptr<const bytes>(&((sealers)[sealerIndex]), [](const bytes*) {}),\n                    hash(), bytesConstRef(signatureData.data(), signatureData.size())))\n            {\n                BOOST_THROW_EXCEPTION(\n                    InvalidSignatureList()\n                    << errinfo_comment(\"Invalid signatureList for verify failed, signatureData:\" +\n                                       *toHexString(signatureData)));\n            }\n        }\n    }\n    virtual void populateEmptyBlock(\n        BlockNumber _number, int64_t _sealerId, int64_t _timestamp = utcTime())\n    {\n        setNumber(_number);\n        setSealer(_sealerId);\n        setTimestamp(_timestamp);\n    }\n\n    // version returns the version of the blockHeader\n    virtual int32_t version() const = 0;\n    // parentInfo returns the parent information, including (parentBlockNumber, parentHash)\n    virtual gsl::span<const ParentInfo> parentInfo() const = 0;\n    // txsRoot returns the txsRoot of the current block\n    virtual bcos::crypto::HashType txsRoot() const = 0;\n    // receiptsRoot returns the receiptsRoot of the current block\n    virtual bcos::crypto::HashType receiptsRoot() const = 0;\n    // stateRoot returns the stateRoot of the current block\n    virtual bcos::crypto::HashType stateRoot() const = 0;\n    // number returns the number of the current block\n    virtual BlockNumber number() const = 0;\n    virtual u256 gasUsed() const = 0;\n    virtual int64_t timestamp() const = 0;\n    // sealer returns the sealer that generate this block\n    virtual int64_t sealer() const = 0;\n    // sealerList returns the current sealer list\n    virtual gsl::span<const bytes> sealerList() const = 0;\n    virtual bytesConstRef extraData() const = 0;\n    virtual gsl::span<const Signature> signatureList() const = 0;\n    virtual gsl::span<const uint64_t> consensusWeights() const = 0;\n\n    virtual void setVersion(int32_t _version) = 0;\n    virtual void setParentInfo(gsl::span<const ParentInfo> const& _parentInfo) = 0;\n    virtual void setParentInfo(ParentInfoList&& _parentInfo) = 0;\n\n    virtual void setTxsRoot(bcos::crypto::HashType _txsRoot) = 0;\n    virtual void setReceiptsRoot(bcos::crypto::HashType _receiptsRoot) = 0;\n    virtual void setStateRoot(bcos::crypto::HashType _stateRoot) = 0;\n    virtual void setNumber(BlockNumber _blockNumber) = 0;\n    virtual void setGasUsed(u256 _gasUsed) = 0;\n    virtual void setTimestamp(int64_t _timestamp) = 0;\n    virtual void setSealer(int64_t _sealerId) = 0;\n\n    virtual void setSealerList(gsl::span<const bytes> const& _sealerList) = 0;\n    virtual void setSealerList(std::vector<bytes>&& _sealerList) = 0;\n\n    virtual void setConsensusWeights(gsl::span<const uint64_t> const& _weightList) = 0;\n    virtual void setConsensusWeights(std::vector<uint64_t>&& _weightList) = 0;\n\n    virtual void setExtraData(bytes const& _extraData) = 0;\n    virtual void setExtraData(bytes&& _extraData) = 0;\n\n    virtual void setSignatureList(gsl::span<const Signature> const& _signatureList) = 0;\n    virtual void setSignatureList(SignatureList&& _signatureList) = 0;\n    virtual bcos::crypto::CryptoSuite::Ptr cryptoSuite() { return m_cryptoSuite; }\n\nprotected:\n    bcos::crypto::CryptoSuite::Ptr m_cryptoSuite;\n};\n}  // namespace protocol\n}  // namespace bcos", "meta": {"hexsha": "af7d77f1df8da912da52e8b13d9ec415571de83f", "size": 6039, "ext": "h", "lang": "C", "max_stars_repo_path": "bcos-framework/interfaces/protocol/BlockHeader.h", "max_stars_repo_name": "contropist/FISCO-BCOS", "max_stars_repo_head_hexsha": "1605c371448b410674559bb1c9e98bab722f036b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bcos-framework/interfaces/protocol/BlockHeader.h", "max_issues_repo_name": "contropist/FISCO-BCOS", "max_issues_repo_head_hexsha": "1605c371448b410674559bb1c9e98bab722f036b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bcos-framework/interfaces/protocol/BlockHeader.h", "max_forks_repo_name": "contropist/FISCO-BCOS", "max_forks_repo_head_hexsha": "1605c371448b410674559bb1c9e98bab722f036b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.26, "max_line_length": 99, "alphanum_fraction": 0.6756085445, "num_tokens": 1460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10970577678877605, "lm_q2_score": 0.0174424844808256, "lm_q1q2_score": 0.0019135413090951435}}
{"text": "#ifndef __GSL_BLOCK_H__\n#define __GSL_BLOCK_H__\n\n#include <gsl/gsl_block_complex_long_double.h>\n#include <gsl/gsl_block_complex_double.h>\n#include <gsl/gsl_block_complex_float.h>\n\n#include <gsl/gsl_block_long_double.h>\n#include <gsl/gsl_block_double.h>\n#include <gsl/gsl_block_float.h>\n\n#include <gsl/gsl_block_ulong.h>\n#include <gsl/gsl_block_long.h>\n\n#include <gsl/gsl_block_uint.h>\n#include <gsl/gsl_block_int.h>\n\n#include <gsl/gsl_block_ushort.h>\n#include <gsl/gsl_block_short.h>\n\n#include <gsl/gsl_block_uchar.h>\n#include <gsl/gsl_block_char.h>\n\n#endif /* __GSL_BLOCK_H__ */\n", "meta": {"hexsha": "c9cc863a3b6fa34082af3d03be8c1268c8b4d7ba", "size": 580, "ext": "h", "lang": "C", "max_stars_repo_path": "gsl-2.6/gsl/gsl_block.h", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gsl-2.6/gsl/gsl_block.h", "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gsl-2.6/gsl/gsl_block.h", "max_forks_repo_name": "ielomariala/Hex-Game", "max_forks_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-30T20:40:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-30T20:40:25.000Z", "avg_line_length": 23.2, "max_line_length": 46, "alphanum_fraction": 0.7931034483, "num_tokens": 170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1259227648351323, "lm_q2_score": 0.015189052179296291, "lm_q1q2_score": 0.0019126474456420805}}
{"text": "#pragma once\n\n#include <memory>\n#include <string>\n\n#include <gsl/gsl>\n\n#include \"chainerx/backend.h\"\n#include \"chainerx/device.h\"\n#include \"chainerx/kernel_registry.h\"\n\nnamespace chainerx {\nnamespace native {\n\nclass NativeDevice;\nclass NativeBackend;\n\nnamespace native_internal {\n\n// Creates a device instance.\n// This function is meant to be used from the backend class. Never use it for other purpose.\n// This is defined in internal namespace in order to make it a friend of NativeDevice\n// class.\nNativeDevice* CreateDevice(NativeBackend& backend, int index);\n\n}  // namespace native_internal\n\nclass NativeBackend : public Backend {\npublic:\n    static constexpr const char* kDefaultName = \"native\";\n\n    using Backend::Backend;\n\n    std::string GetName() const override;\n\n    int GetDeviceCount() const override;\n\n    bool SupportsTransfer(Device& src_device, Device& dst_device) override;\n\n    static KernelRegistry& GetGlobalKernelRegistry() {\n        static gsl::owner<KernelRegistry*> global_kernel_registry = new KernelRegistry{};\n        return *global_kernel_registry;\n    }\n\nprotected:\n    KernelRegistry& GetParentKernelRegistry() override { return GetGlobalKernelRegistry(); }\n\nprivate:\n    std::unique_ptr<Device> CreateDevice(int index) override;\n};\n\n}  // namespace native\n}  // namespace chainerx\n", "meta": {"hexsha": "cb9ab4b2ff9e88987e59618b36d86e97d9f9c0cc", "size": 1314, "ext": "h", "lang": "C", "max_stars_repo_path": "chainerx_cc/chainerx/native/native_backend.h", "max_stars_repo_name": "tkerola/chainer", "max_stars_repo_head_hexsha": "572f6eef2c3f1470911ac08332c2b5c3440edf44", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-26T10:27:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-26T10:27:25.000Z", "max_issues_repo_path": "chainerx_cc/chainerx/native/native_backend.h", "max_issues_repo_name": "tkerola/chainer", "max_issues_repo_head_hexsha": "572f6eef2c3f1470911ac08332c2b5c3440edf44", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chainerx_cc/chainerx/native/native_backend.h", "max_forks_repo_name": "tkerola/chainer", "max_forks_repo_head_hexsha": "572f6eef2c3f1470911ac08332c2b5c3440edf44", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-07-16T00:24:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-26T10:27:27.000Z", "avg_line_length": 24.3333333333, "max_line_length": 92, "alphanum_fraction": 0.7473363775, "num_tokens": 282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09670579850281288, "lm_q2_score": 0.019719127531259237, "lm_q1q2_score": 0.001906953973689226}}
{"text": "#pragma once\n\n#include \"RTTI.h\"\n#include <d3d11.h>\n#include <stack>\n#include <gsl\\gsl>\n#include <vector>\n\nnamespace Library\n{\n\tclass RenderTarget : public RTTI\n\t{\n\t\tRTTI_DECLARATIONS(RenderTarget, RTTI)\n\n\tpublic:\n\t\tRenderTarget() = default;\n\t\tRenderTarget(const RenderTarget&) = delete;\n\t\tRenderTarget(RenderTarget&&) = default;\n\t\tRenderTarget& operator=(const RenderTarget&) = delete;\t\t\n\t\tRenderTarget& operator=(RenderTarget&&) = default;\n\t\tvirtual ~RenderTarget() = default;\n\n\t\tvirtual void Begin() = 0;\n\t\tvirtual void End() = 0;\n\n\tprotected:\n\t\tstruct RenderTargetData\n\t\t{\n\t\t\tuint32_t ViewCount() const { return gsl::narrow_cast<uint32_t>(RenderTargetViews.size()); }\n\n\t\t\tstd::vector<ID3D11RenderTargetView*> RenderTargetViews;\n\t\t\tgsl::not_null<ID3D11DepthStencilView*> DepthStencilView;\n\t\t\tD3D11_VIEWPORT Viewport;\n\n\t\t\tRenderTargetData(const gsl::span<ID3D11RenderTargetView*>& renderTargetViews, gsl::not_null<ID3D11DepthStencilView*> depthStencilView, const D3D11_VIEWPORT& viewport) :\n\t\t\t\tRenderTargetViews(renderTargetViews.begin(), renderTargetViews.end()), DepthStencilView(depthStencilView), Viewport(viewport) { }\n\t\t};\n\n\t\tvoid Begin(gsl::not_null<ID3D11DeviceContext*> deviceContext, const gsl::span<ID3D11RenderTargetView*>& renderTargetViews, gsl::not_null<ID3D11DepthStencilView*> depthStencilView, const D3D11_VIEWPORT& viewport);\n\t\tvoid End(gsl::not_null<ID3D11DeviceContext*> deviceContext);\n\t\tvoid RebindCurrentRenderTargets(gsl::not_null<ID3D11DeviceContext*> deviceContext);\n\n\tprivate:\n\t\tstatic std::stack<RenderTargetData> sRenderTargetStack;\n\t};\n}", "meta": {"hexsha": "942d41873fa296c37135a2455b5c5243edcf8ffe", "size": 1570, "ext": "h", "lang": "C", "max_stars_repo_path": "source/Library.Shared/RenderTarget.h", "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/Library.Shared/RenderTarget.h", "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/Library.Shared/RenderTarget.h", "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1304347826, "max_line_length": 214, "alphanum_fraction": 0.7694267516, "num_tokens": 412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10087861462065478, "lm_q2_score": 0.018833131232767256, "lm_q1q2_score": 0.0018998601877305453}}
{"text": "/*\n *  Copyright (C) 2021 FISCO BCOS.\n *  SPDX-License-Identifier: Apache-2.0\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n * @brief interface of Table\n * @file Table.h\n * @author: xingqiangbai\n * @date: 2021-04-07\n */\n#pragma once\n\n#include \"../../interfaces/protocol/ProtocolTypeDef.h\"\n#include \"../../libutilities/Error.h\"\n#include \"boost/algorithm/string.hpp\"\n#include \"tbb/spin_mutex.h\"\n#include \"tbb/spin_rw_mutex.h\"\n#include <boost/throw_exception.hpp>\n#include <algorithm>\n#include <any>\n#include <cstdlib>\n#include <gsl/span>\n#include <map>\n#include <memory>\n#include <string>\n#include <utility>\n#include <vector>\n\n#define STORAGE_LOG(LEVEL) BCOS_LOG(LEVEL) << \"[STORAGE]\"\n\nnamespace bcos\n{\nnamespace storage\n{\nenum StorageError\n{\n    UnknownError = -60000,\n    TableNotExists,\n    SystemTableNotExists,\n    TableExists,\n    UnknownEntryType,\n    ReadError,\n    WriteError,\n    EmptyStorage,\n    ReadOnly,\n};\n\nstruct Condition\n{\n    Condition() = default;\n    ~Condition() = default;\n    void NE(const std::string& value) { m_conditions.emplace_back(Comparator::NE, value); }\n    // string compare, \"2\" > \"12\"\n    void GT(const std::string& value) { m_conditions.emplace_back(Comparator::GT, value); }\n    void GE(const std::string& value) { m_conditions.emplace_back(Comparator::GE, value); }\n    // string compare, \"12\" < \"2\"\n    void LT(const std::string& value) { m_conditions.emplace_back(Comparator::LT, value); }\n    void LE(const std::string& value) { m_conditions.emplace_back(Comparator::LE, value); }\n    void limit(size_t start, size_t end) { m_limit = std::pair<size_t, size_t>(start, end); }\n\n    std::pair<size_t, size_t> getLimit() const { return m_limit; }\n\n    bool isValid(const std::string_view& key) const\n    {  // all conditions must be satisfied\n        for (auto& cond : m_conditions)\n        {  // conditions should few, so not parallel check for now\n            switch (cond.cmp)\n            {\n            case Comparator::NE:\n                if (key == cond.value)\n                {\n                    return false;\n                }\n                break;\n            case Comparator::GT:\n                if (key <= cond.value)\n                {\n                    return false;\n                }\n                break;\n            case Comparator::GE:\n                if (key < cond.value)\n                {\n                    return false;\n                }\n                break;\n            case Comparator::LT:\n                if (key >= cond.value)\n                {\n                    return false;\n                }\n                break;\n            case Comparator::LE:\n                if (key > cond.value)\n                {\n                    return false;\n                }\n                break;\n            default:\n                // undefined Comparator\n                break;\n            }\n        }\n        return true;\n    }\n\n    enum class Comparator\n    {\n        EQ,\n        NE,\n        GT,\n        GE,\n        LT,\n        LE,\n    };\n    struct cond\n    {\n        cond(Comparator _cmp, const std::string& _value) : cmp(_cmp), value(_value) {}\n        Comparator cmp;\n        std::string value;\n    };\n\n    std::vector<cond> m_conditions;\n    std::pair<size_t, size_t> m_limit;\n};\n\nclass TableInfo\n{\npublic:\n    using Ptr = std::shared_ptr<TableInfo>;\n    using ConstPtr = std::shared_ptr<const TableInfo>;\n\n    TableInfo(std::string name, std::vector<std::string> fields)\n      : m_name(std::move(name)), m_fields(std::move(fields))\n    {\n        m_order.reserve(m_fields.size());\n        for (size_t i = 0; i < m_fields.size(); ++i)\n        {\n            m_order.push_back({m_fields[i], i});\n        }\n        std::sort(m_order.begin(), m_order.end(),\n            [](auto&& lhs, auto&& rhs) { return std::get<0>(lhs) < std::get<0>(rhs); });\n    }\n\n    std::string_view name() const { return m_name; }\n\n    const std::vector<std::string>& fields() const { return m_fields; }\n\n    size_t fieldIndex(const std::string_view& field) const\n    {\n        auto it = std::lower_bound(m_order.begin(), m_order.end(), field,\n            [](auto&& lhs, auto&& rhs) { return std::get<0>(lhs) < rhs; });\n        if (it != m_order.end() && std::get<0>(*it) == field)\n        {\n            return std::get<1>(*it);\n        }\n        else\n        {\n            BOOST_THROW_EXCEPTION(\n                BCOS_ERROR(-1, std::string(\"Can't find field: \") + std::string(field)));\n        }\n    }\n\nprivate:\n    std::string m_name;\n    std::vector<std::string> m_fields;\n    std::vector<std::tuple<std::string_view, size_t>> m_order;\n\nprivate:\n    void* operator new(size_t s) { return malloc(s); };\n    void operator delete(void* p) { free(p); };\n};\n\n}  // namespace storage\n}  // namespace bcos\n", "meta": {"hexsha": "18c411a922791d42b4731d958a66f792422c596b", "size": 5257, "ext": "h", "lang": "C", "max_stars_repo_path": "bcos-framework/interfaces/storage/Common.h", "max_stars_repo_name": "xueying4402/FISCO-BCOS", "max_stars_repo_head_hexsha": "737e08752e8904c7c24e3737f8f46bf5327ef792", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bcos-framework/interfaces/storage/Common.h", "max_issues_repo_name": "xueying4402/FISCO-BCOS", "max_issues_repo_head_hexsha": "737e08752e8904c7c24e3737f8f46bf5327ef792", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 267.0, "max_issues_repo_issues_event_min_datetime": "2021-03-01T02:12:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-17T08:18:34.000Z", "max_forks_repo_path": "bcos-framework/interfaces/storage/Common.h", "max_forks_repo_name": "xueying4402/FISCO-BCOS", "max_forks_repo_head_hexsha": "737e08752e8904c7c24e3737f8f46bf5327ef792", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2021-02-22T03:47:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-06T06:41:02.000Z", "avg_line_length": 28.2634408602, "max_line_length": 93, "alphanum_fraction": 0.5655316721, "num_tokens": 1261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09401018215490362, "lm_q2_score": 0.02002343942541756, "lm_q1q2_score": 0.0018824071877511833}}
{"text": "// The MIT License (MIT)\n//\n// Copyright (c) 2018 Mateusz Pusz\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#pragma once\n\n#include <gsl/gsl-lite.hpp>\n#include <units/bits/external/hacks.h>\n#include <utility>\n\ninline constexpr struct validated_tag {\n} validated;\n\ntemplate<std::movable T, std::predicate<T> Validator>\nclass validated_type {\n  T value_;\npublic:\n  using value_type = T;\n\n  static constexpr bool validate(const T& value) { return Validator()(value); }\n\n  constexpr explicit validated_type(const T& value) noexcept(std::is_nothrow_copy_constructible_v<T>)\n    requires std::copyable<T>\n  : value_(value)\n  {\n    gsl_Expects(validate(value_));\n  }\n\n  constexpr explicit validated_type(T&& value) noexcept(std::is_nothrow_move_constructible_v<T>) :\n      value_(std::move(value))\n  {\n    gsl_Expects(validate(value_));\n  }\n\n  constexpr validated_type(const T& value, validated_tag) noexcept(std::is_nothrow_copy_constructible_v<T>)\n    requires std::copyable<T>\n  : value_(value)\n  {\n  }\n\n  constexpr validated_type(T&& value, validated_tag) noexcept(std::is_nothrow_move_constructible_v<T>) :\n      value_(std::move(value))\n  {\n  }\n\n  constexpr explicit(false) operator T() const noexcept(std::is_nothrow_copy_constructible_v<T>)\n    requires std::copyable<T>\n  {\n    return value_;\n  }\n\n  constexpr T& value() & noexcept = delete;\n  constexpr const T& value() const& noexcept { return value_; }\n  constexpr T&& value() && noexcept { return std::move(value_); }\n  constexpr const T&& value() const&& noexcept { return std::move(value_); }\n\n  bool operator==(const validated_type&) const\n    requires std::equality_comparable<T>\n  = default;\n  auto operator<=>(const validated_type&) const\n    requires std::three_way_comparable<T>\n  = default;\n};\n", "meta": {"hexsha": "bf44bbbcaa948ba002d7e196223e9c36d3d48803", "size": 2789, "ext": "h", "lang": "C", "max_stars_repo_path": "example/include/validated_type.h", "max_stars_repo_name": "chiphogg/units", "max_stars_repo_head_hexsha": "8c0f9d4f8ef712633d4709bac1cbd00b71b50570", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/include/validated_type.h", "max_issues_repo_name": "chiphogg/units", "max_issues_repo_head_hexsha": "8c0f9d4f8ef712633d4709bac1cbd00b71b50570", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-02-24T01:18:54.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-24T01:18:54.000Z", "max_forks_repo_path": "example/include/validated_type.h", "max_forks_repo_name": "chiphogg/units", "max_forks_repo_head_hexsha": "8c0f9d4f8ef712633d4709bac1cbd00b71b50570", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.012195122, "max_line_length": 107, "alphanum_fraction": 0.7339548225, "num_tokens": 640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09807932874307333, "lm_q2_score": 0.019124035458106307, "lm_q1q2_score": 0.0018756725605897995}}
{"text": "#pragma once\n#include \"halley/utils/utils.h\"\n#include \"halley/text/halleystring.h\"\n#include <memory>\n#include <gsl/span>\n#include \"halley/resources/resource_data.h\"\n\nnamespace Halley {\n\tenum class AssetType;\n\tclass Deserializer;\n\tclass Serializer;\n\tclass AssetDatabase;\n\tclass ResourceData;\n\tclass ResourceDataReader;\n\n\tstruct AssetPackHeader {\n\t\tstd::array<char, 8> identifier;\n\t\tstd::array<char, 16> iv;\n\t\tuint64_t assetDbStartPos;\n\t\tuint64_t dataStartPos;\n\n\t\tvoid init(size_t assetDbSize);\n\t};\n\n    class AssetPack {\n    public:\n\t\tAssetPack();\n\t\tAssetPack(const AssetPack& other) = delete;\n\t\tAssetPack(AssetPack&& other) noexcept;\n\t\tAssetPack(std::unique_ptr<ResourceDataReader> reader, const String& encryptionKey = \"\", bool preLoad = false);\n\t\t~AssetPack();\n\n\t\tAssetPack& operator=(const AssetPack& other) = delete;\n\t\tAssetPack& operator=(AssetPack&& other) noexcept;\n\n\t\tAssetDatabase& getAssetDatabase();\n\t\tconst AssetDatabase& getAssetDatabase() const;\n\t\tBytes& getData();\n\t\tconst Bytes& getData() const;\n\n\t\tBytes writeOut() const;\n\n\t\tstd::unique_ptr<ResourceData> getData(const String& asset, AssetType type, bool stream);\n\n\t\tvoid readToMemory();\n\t\tvoid encrypt(const String& key);\n\t\tvoid decrypt(const String& key);\n\t    \n    \tvoid readData(size_t pos, gsl::span<gsl::byte> dst);\n\n\t\tstd::unique_ptr<ResourceDataReader> extractReader();\n\n    private:\n\t\tstd::unique_ptr<AssetDatabase> assetDb;\n\t\tstd::unique_ptr<ResourceDataReader> reader;\n\t\tstd::atomic<bool> hasReader;\n\t\tstd::mutex readerMutex;\n\t\tsize_t dataOffset = 0;\n\t\tBytes data;\n\t\tstd::array<char, 16> iv;\n    };\n\n\n\tclass PackDataReader final : public ResourceDataReader {\n\tpublic:\n\t\tPackDataReader(AssetPack& pack, size_t startPos, size_t fileSize);\n\n\t\tsize_t size() const override;\n\t\tint read(gsl::span<gsl::byte> dst) override;\n\t\tvoid seek(int64_t pos, int whence) override;\n\t\tsize_t tell() const override;\n\t\tvoid close() override;\n\n\tprivate:\n\t\tAssetPack& pack;\n\t\tconst size_t startPos;\n\t\tconst size_t fileSize;\n\t\tsize_t curPos = 0;\n\t\tmutable std::mutex mutex;\n\t};\n}\n", "meta": {"hexsha": "2eaa56e3e8accab2c50da1f099b35c39bd137336", "size": 2034, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engine/core/include/halley/core/resources/asset_pack.h", "max_stars_repo_name": "code-disaster/halley", "max_stars_repo_head_hexsha": "5c85c889b76c69c6bdef6f4801c6aba282b7af80", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3262.0, "max_stars_repo_stars_event_min_datetime": "2016-04-10T15:24:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:47:08.000Z", "max_issues_repo_path": "src/engine/core/include/halley/core/resources/asset_pack.h", "max_issues_repo_name": "code-disaster/halley", "max_issues_repo_head_hexsha": "5c85c889b76c69c6bdef6f4801c6aba282b7af80", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 53.0, "max_issues_repo_issues_event_min_datetime": "2016-10-09T16:25:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-10T13:52:37.000Z", "max_forks_repo_path": "src/engine/core/include/halley/core/resources/asset_pack.h", "max_forks_repo_name": "code-disaster/halley", "max_forks_repo_head_hexsha": "5c85c889b76c69c6bdef6f4801c6aba282b7af80", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 193.0, "max_forks_repo_forks_event_min_datetime": "2017-10-23T06:08:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T12:59:58.000Z", "avg_line_length": 24.8048780488, "max_line_length": 112, "alphanum_fraction": 0.7261553589, "num_tokens": 527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09947021121253753, "lm_q2_score": 0.01883313119834847, "lm_q1q2_score": 0.0018733355380931523}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <gsl/gsl_rng.h>\n#include <time.h>\n#include <assert.h>\n\n#include \"core_allvars.h\"\n#include \"core_proto.h\"\n#include \"temporal_array.h\"\n\nvoid init_galaxy(int p, int halonr, int treenr, int32_t filenr)\n{\n  int32_t j, step, status;\n  \n\tassert(halonr == Halo[halonr].FirstHaloInFOFgroup);\n\n  Gal[p].FileNr = filenr;\n\n  Gal[p].Type = 0;\n  Gal[p].TreeNr = treenr;\n\n  Gal[p].GalaxyNr = GalaxyCounter;\n  GalaxyCounter++;\n  \n  Gal[p].HaloNr = halonr;\n   \n  Gal[p].MostBoundID = Halo[halonr].MostBoundID;\n  //Gal[p].MostBoundID = -1; \n  Gal[p].SnapNum = Halo[halonr].SnapNum - 1;\n\n  Gal[p].mergeType = 0;\n  Gal[p].mergeIntoID = -1;\n  Gal[p].mergeIntoSnapNum = -1;\n  Gal[p].dT = -1.0;\n\n  for(j = 0; j < 3; j++)\n  {\n    Gal[p].Pos[j] = Halo[halonr].Pos[j];\n    Gal[p].Vel[j] = Halo[halonr].Vel[j];\n  }\n\n  Gal[p].Len = Halo[halonr].Len;\n  Gal[p].Vmax = Halo[halonr].Vmax;\n  Gal[p].Vvir = get_virial_velocity(halonr);\n  Gal[p].Mvir = get_virial_mass(halonr);\n  Gal[p].Rvir = get_virial_radius(halonr);\n\n  Gal[p].deltaMvir = 0.0;\n\n  Gal[p].ColdGas = 0.0;\n  Gal[p].StellarMass = 0.0;\n  Gal[p].BulgeMass = 0.0;\n  Gal[p].HotGas = 0.0;\n  Gal[p].EjectedMass = 0.0;\n  Gal[p].EjectedMassSN = 0.0;\n  Gal[p].EjectedMassQSO = 0.0;\n  Gal[p].BlackHoleMass = 0.0;\n  Gal[p].ICS = 0.0;\n\n  Gal[p].MetalsColdGas = 0.0;\n  Gal[p].MetalsStellarMass = 0.0;\n  Gal[p].MetalsBulgeMass = 0.0;\n  Gal[p].MetalsHotGas = 0.0;\n  Gal[p].MetalsEjectedMass = 0.0;\n  Gal[p].MetalsICS = 0.0;\n  \n  for(step = 0; step < STEPS; step++)\n  {\n    Gal[p].SfrDisk[step] = 0.0;\n    Gal[p].SfrBulge[step] = 0.0;\n    Gal[p].SfrDiskColdGas[step] = 0.0;\n    Gal[p].SfrDiskColdGasMetals[step] = 0.0;\n    Gal[p].SfrBulgeColdGas[step] = 0.0;\n    Gal[p].SfrBulgeColdGasMetals[step] = 0.0;\n  }\n\n  Gal[p].DiskScaleRadius = get_disk_radius(halonr, p);\n  Gal[p].MergTime = 999.9;\n  Gal[p].Cooling = 0.0;\n  Gal[p].Heating = 0.0;\n  Gal[p].r_heat = 0.0;\n  Gal[p].QuasarModeBHaccretionMass = 0.0;\n  Gal[p].TimeOfLastMajorMerger = -1.0;\n  Gal[p].TimeOfLastMinorMerger = -1.0;\n  Gal[p].OutflowRate = 0.0;\n\tGal[p].TotalSatelliteBaryons = 0.0;\n\t// infall properties\n  Gal[p].infallMvir = -1.0;  \n  Gal[p].infallVvir = -1.0;\n  Gal[p].infallVmax = -1.0;\n \n  Gal[p].IsMerged = -1;\n\n  status = malloc_temporal_arrays(&Gal[p]);\n  if (status == EXIT_FAILURE)\n  {\n    ABORT(EXIT_FAILURE);\n  }\n  ++gal_mallocs;\t\n \n  for (j = 0; j < MAXSNAPS; ++j)\n  {\n    Gal[p].GridType[j] = -1;\n    Gal[p].GridFoFHaloNr[j] = -1;\n    Gal[p].GridHistory[j] = -1;\n    Gal[p].GridColdGas[j] = 0.0;\n    Gal[p].GridHotGas[j] = 0.0;\n    Gal[p].GridEjectedMass[j] = 0.0;\n    Gal[p].GridDustColdGas[j] = 0.0;\n    Gal[p].GridDustHotGas[j] = 0.0;\n    Gal[p].GridDustEjectedMass[j] = 0.0;\n    Gal[p].GridStellarMass[j] = 0.0;\n    Gal[p].GridBHMass[j] = 0.0;\n    Gal[p].GridSFR[j] = 0.0;\n    Gal[p].GridZ[j] = 0.0;\n    Gal[p].GridFoFMass[j] = 0.0;\n    Gal[p].GridHaloMass[j] = 0.0;\n    Gal[p].EjectedFraction[j] = 0.0;\n    Gal[p].EjectedFractionSN[j] = 0.0;\n    Gal[p].EjectedFractionQSO[j] = 0.0;\n    Gal[p].LenHistory[j] = -1;\n    Gal[p].GridOutflowRate[j] = 0.0;\n    Gal[p].GridInfallRate[j] = 0.0;\n    Gal[p].QuasarActivity[j] = 0;\n    Gal[p].QuasarSubstep[j] = -1;\n    Gal[p].DynamicalTime[j] = 0.0;\n    Gal[p].LenMergerGal[j] = -1;\n    Gal[p].GridReionMod[j] = -1.0;\n    Gal[p].GridNgamma_HI[j] = 0.0;\n    Gal[p].Gridfesc[j] = 0.0;\n    Gal[p].ColdCrit[j] = 0.0;\n    Gal[p].MUV[j] = 999.99;\n  }\n\n  Gal[p].GrandSum = 0.0;\n \n  Gal[p].StellarAge_Numerator = 0.0;\n  Gal[p].StellarAge_Denominator = 0.0;\n\n  Gal[p].reheated_mass = 0.0;\n  Gal[p].ejected_mass = 0.0;\n  Gal[p].mass_stars_recycled = 0.0;\n  Gal[p].mass_metals_new = 0.0; \n  Gal[p].NSN = 0.0;\n\n  if (IRA == 0)\n  {\n    for (j = 0; j < SN_Array_Len; ++j)\n    {\n      Gal[p].SN_Stars[j] = 0.0;\n    }\n  }\n  Gal[p].Total_SN_SF_Time = 0.0;\n  Gal[p].Total_SN_Stars = 0.0;\n\n  // Dust Reservoirs.\n\n  Gal[p].DustColdGas = 0.0;\n  Gal[p].DustHotGas = 0.0;\n  Gal[p].DustEjectedMass = 0.0;\n\n  // Quasar Activity Tracking \n  \n  Gal[p].QuasarActivityToggle = 0;\n  Gal[p].TargetQuasarTime = 0.0;\n  Gal[p].QuasarBoostActiveTime = 0.0;\n  Gal[p].QuasarFractionalPhotons = 0.0;\n\n  // Stellar Age Tracking\n\n  if (PhotonPrescription == 1)\n  {\n    for (j = 0; j < StellarTracking_Len; ++j)\n    {\n      Gal[p].Stellar_Stars[j] = 0.0;\n    }\n  }\n  Gal[p].Total_Stellar_SF_Time = 0.0;\n  Gal[p].Total_Stellar_Stars = 0.0;\n\n}\n\ndouble get_disk_radius(int halonr, int p)\n{\n  double SpinMagnitude, SpinParameter;\n  \n\tif(Gal[p].Vvir > 0.0 && Gal[p].Rvir > 0.0)\n\t{\n\t\t// See Mo, Shude & White (1998) eq12, and using a Bullock style lambda.\n\t\tSpinMagnitude = sqrt(Halo[halonr].Spin[0] * Halo[halonr].Spin[0] + \n\t\t\tHalo[halonr].Spin[1] * Halo[halonr].Spin[1] + Halo[halonr].Spin[2] * Halo[halonr].Spin[2]);\n  \n\t\tSpinParameter = SpinMagnitude / (1.414 * Gal[p].Vvir * Gal[p].Rvir);\n\t\treturn (SpinParameter / 1.414) * Gal[p].Rvir;\t\t\n\t}\n\telse\n\t\treturn 0.1 * Gal[p].Rvir;\n\n}\n\n\n\ndouble get_metallicity(double gas, double metals)\n{\n  double metallicity;\n\n  if(gas > 0.0 && metals > 0.0)\n  {\n    metallicity = metals / gas;\n    if(metallicity < 1.0)\n      return metallicity;\n    else\n      return 1.0;\n  }\n  else\n    return 0.0;\n\n}\n\ndouble get_dust_fraction(double gas, double dust)\n{\n\n  double dust_fraction;\n  if (gas > 0.0 && dust > 0.0)\n  {\n    dust_fraction = dust / gas;\n    if (dust_fraction < 1.0)\n      return dust_fraction;\n    else\n      return 1.0;\n  }\n  else\n  {\n    return 0.0;\n  }\n  \n}\n\ndouble dmax(double x, double y)\n{\n  if(x > y)\n    return x;\n  else\n    return y;\n}\n\n\n\ndouble get_virial_mass(int halonr)\n{\n  if(halonr == Halo[halonr].FirstHaloInFOFgroup && Halo[halonr].Mvir >= 0.0)\n  {\n    ++count_Mvir;\n    return Halo[halonr].Mvir;   /* take spherical overdensity mass estimate */\n  } \n  else\n  {    \n    ++count_Len;\n    return Halo[halonr].Len * PartMass;\n  }\n}\n\n\n\ndouble get_virial_velocity(int halonr)\n{\n\tdouble Rvir;\n\t\n\tRvir = get_virial_radius(halonr);\n\t\n  if(Rvir > 0.0)\n\t\treturn sqrt(sage_G * get_virial_mass(halonr) / Rvir);\n\telse\n\t\treturn 0.0;\n}\n\n\n\ndouble get_virial_radius(int halonr)\n{\n  // return Halo[halonr].Rvir;  // Used for Bolshoi\n\n  double zplus1, hubble_of_z_sq, rhocrit, fac;\n  \n  zplus1 = 1 + ZZ[Halo[halonr].SnapNum];\n  hubble_of_z_sq =\n    sage_Hubble * sage_Hubble *(Omega * zplus1 * zplus1 * zplus1 + (1 - Omega - OmegaLambda) * zplus1 * zplus1 +\n    OmegaLambda);\n  \n  rhocrit = 3 * hubble_of_z_sq / (8 * M_PI * sage_G);\n  fac = 1 / (200 * 4 * M_PI / 3.0 * rhocrit);\n  \n  return cbrt(get_virial_mass(halonr) * fac);\n}\n\nint32_t determine_1D_idx(float pos_x, float pos_y, float pos_z, int32_t *grid_1D)\n{\n\n  int32_t x_grid, y_grid, z_grid;\n\n  x_grid = round(pos_x * GridSize/BoxSize);\n  if (x_grid == GridSize)\n    --x_grid;\n\n  y_grid = round(pos_y * GridSize/BoxSize);\n  if (y_grid == GridSize)\n    --y_grid;\n\n  z_grid = round(pos_z * GridSize/BoxSize);\n  if (z_grid == GridSize)\n    --z_grid;\n  \n\n  *grid_1D = (z_grid*GridSize+y_grid)*GridSize+x_grid; // Convert the grid (x,y,z) to a 1D value.\n\n  if(*grid_1D > CUBE(GridSize) || *grid_1D < 0) // Sanity check to ensure that no Grid Positions are outside the box.\n  {\n    fprintf(stderr, \"Found a Grid Position outside the bounds of the box or negative\\nPos[0] = %.4f\\tPos[1] = %.4f\\tPos[2] = %.4f\\n\", pos_x, pos_y, pos_z);\n    fprintf(stderr, \"Grid indices were x = %d\\ty = %d\\tz = %d\\t1D = %d\\tMaximum Allowed = %d\\n\", x_grid, y_grid, z_grid, *grid_1D, CUBE(GridSize) - 1);\n \n    return EXIT_FAILURE;\n  }\n\n  return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "af494f3f40b312e1c6ab4a839da5f42ec509cd6d", "size": 7519, "ext": "c", "lang": "C", "max_stars_repo_path": "src/sage/model_misc.c", "max_stars_repo_name": "jacobseiler/rsage", "max_stars_repo_head_hexsha": "b3b0a3fa3c676eab188991e37d06894396bfc74f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-23T04:11:32.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-23T04:11:32.000Z", "max_issues_repo_path": "src/sage/model_misc.c", "max_issues_repo_name": "jacobseiler/rsage", "max_issues_repo_head_hexsha": "b3b0a3fa3c676eab188991e37d06894396bfc74f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2018-08-17T05:04:57.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-16T05:40:16.000Z", "max_forks_repo_path": "src/sage/model_misc.c", "max_forks_repo_name": "jacobseiler/rsage", "max_forks_repo_head_hexsha": "b3b0a3fa3c676eab188991e37d06894396bfc74f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8541033435, "max_line_length": 155, "alphanum_fraction": 0.6153743849, "num_tokens": 2966, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18952109132967757, "lm_q2_score": 0.009859854985312994, "lm_q1q2_score": 0.0018686504771688805}}
{"text": "#pragma once\n#include <gsl/gsl>\n#include <map>\n#include \"halley/text/halleystring.h\"\n#include \"halley/maths/vector4.h\"\n\nnamespace Halley\n{\n\tclass Path;\n\tclass Image;\n\tstruct ImageData;\n\n\tclass AsepriteReader\n\t{\n\tpublic:\n\t\tstatic std::vector<ImageData> importAseprite(String baseName, gsl::span<const gsl::byte> fileData, bool trim);\n\t};\n}\n", "meta": {"hexsha": "637b311e4692c9183cd844869c628d846c6104b1", "size": 339, "ext": "h", "lang": "C", "max_stars_repo_path": "src/tools/tools/src/sprites/aseprite_reader.h", "max_stars_repo_name": "sunhay/halley", "max_stars_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T20:23:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T20:23:45.000Z", "max_issues_repo_path": "src/tools/tools/src/sprites/aseprite_reader.h", "max_issues_repo_name": "sunhay/halley", "max_issues_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tools/tools/src/sprites/aseprite_reader.h", "max_forks_repo_name": "sunhay/halley", "max_forks_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.8421052632, "max_line_length": 112, "alphanum_fraction": 0.7374631268, "num_tokens": 92, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.10521054231434401, "lm_q2_score": 0.017712297147857856, "lm_q1q2_score": 0.0018635203885589337}}
{"text": "#pragma once\n\n#include <winrt\\Windows.Foundation.h>\n#include <d3d11.h>\n#include <cstdint>\n#include <array>\n#include <limits>\n#include <gsl\\gsl>\n\nnamespace Library\n{\n\tclass Game;\n\n\tclass RenderStateHelper final\n\t{\n\tpublic:\n\t\tRenderStateHelper(Game& game);\n\t\tRenderStateHelper(const RenderStateHelper&) = delete;\n\t\tRenderStateHelper(RenderStateHelper&&) = default;\n\t\tRenderStateHelper& operator=(const RenderStateHelper&) = delete;\t\t\n\t\tRenderStateHelper& operator=(RenderStateHelper&&) = default;\n\t\t~RenderStateHelper() = default;\n\n\t\tstatic void ResetAll(gsl::not_null<ID3D11DeviceContext*> deviceContext);\n\t\tstatic void ResetRasterizerState(gsl::not_null<ID3D11DeviceContext*> deviceContext);\n\t\tstatic void ResetBlendState(gsl::not_null<ID3D11DeviceContext*> deviceContext);\n\t\tstatic void ResetDepthStencilState(gsl::not_null<ID3D11DeviceContext*> deviceContext);\n\n\t\tID3D11RasterizerState* RasterizerState();\n\t\tID3D11BlendState* BlendState();\n\t\tID3D11DepthStencilState* DepthStencilState();\n\n\t\tvoid SaveRasterizerState();\n\t\tvoid RestoreRasterizerState() const;\n\n\t\tvoid SaveBlendState();\n\t\tvoid RestoreBlendState() const;\n\n\t\tvoid SaveDepthStencilState();\n\t\tvoid RestoreDepthStencilState() const;\n\n\t\tvoid SaveAll();\n\t\tvoid RestoreAll() const;\n\t\tvoid ClearAll();\n\n\tprivate:\n\t\tGame& mGame;\n\n\t\twinrt::com_ptr<ID3D11RasterizerState> mRasterizerState;\n\t\twinrt::com_ptr<ID3D11BlendState> mBlendState;\n\t\tstd::array<float, 4> mBlendFactor;\n\t\tstd::uint32_t mSampleMask{ std::numeric_limits<std::uint32_t>::max() };\n\t\twinrt::com_ptr<ID3D11DepthStencilState> mDepthStencilState;\n\t\tstd::uint32_t mStencilRef{ std::numeric_limits<std::uint32_t>::max() };\n\t};\n}", "meta": {"hexsha": "b9abd483393d67f5709351e9376537aa47506105", "size": 1644, "ext": "h", "lang": "C", "max_stars_repo_path": "source/Library.Shared/RenderStateHelper.h", "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/Library.Shared/RenderStateHelper.h", "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/Library.Shared/RenderStateHelper.h", "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3571428571, "max_line_length": 88, "alphanum_fraction": 0.7700729927, "num_tokens": 441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09009299396195185, "lm_q2_score": 0.020645932810633056, "lm_q1q2_score": 0.0018600539000472275}}
{"text": "#pragma once\n\n#include \"continuation_scheduler.h\"\n\n#include <arcana/threading/cancellation.h>\n#include <arcana/threading/task.h>\n\n#include <gsl/gsl>\n\n#include <condition_variable>\n#include <mutex>\n#include <optional>\n\nnamespace Babylon::Graphics\n{\n    class SafeTimespanGuarantor\n    {\n    public:\n        SafeTimespanGuarantor(std::optional<arcana::cancellation_source>&);\n\n        continuation_scheduler<>& OpenScheduler()\n        {\n            return m_openDispatcher.scheduler();\n        }\n\n        continuation_scheduler<>& CloseScheduler()\n        {\n            return m_closeDispatcher.scheduler();\n        }\n\n        using SafetyGuarantee = gsl::final_action<std::function<void()>>;\n        SafetyGuarantee GetSafetyGuarantee();\n        \n        void Open();\n        void RequestClose();\n        void Lock();\n        void Unlock();\n\n    private:\n        enum class State\n        {\n            Open,\n            Closing,\n            Closed,\n            Locked\n        };\n\n        std::optional<arcana::cancellation_source>& m_cancellation;\n        State m_state{State::Locked};\n        uint32_t m_count{};\n        std::mutex m_mutex{};\n        std::condition_variable m_condition_variable{};\n        continuation_dispatcher<> m_openDispatcher{};\n        continuation_dispatcher<> m_closeDispatcher{};\n    };\n}\n", "meta": {"hexsha": "23ecb8cafc567b6d0cc0c32ff777ecbbc2bd4d95", "size": 1317, "ext": "h", "lang": "C", "max_stars_repo_path": "Core/Graphics/InternalInclude/Babylon/Graphics/SafeTimespanGuarantor.h", "max_stars_repo_name": "SergioRZMasson/BabylonNative", "max_stars_repo_head_hexsha": "18ea83ee51e4e5d8b1763cf8d9ef5b48b2f9bb0a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Core/Graphics/InternalInclude/Babylon/Graphics/SafeTimespanGuarantor.h", "max_issues_repo_name": "SergioRZMasson/BabylonNative", "max_issues_repo_head_hexsha": "18ea83ee51e4e5d8b1763cf8d9ef5b48b2f9bb0a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Core/Graphics/InternalInclude/Babylon/Graphics/SafeTimespanGuarantor.h", "max_forks_repo_name": "SergioRZMasson/BabylonNative", "max_forks_repo_head_hexsha": "18ea83ee51e4e5d8b1763cf8d9ef5b48b2f9bb0a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1052631579, "max_line_length": 75, "alphanum_fraction": 0.6119969628, "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09268778866449086, "lm_q2_score": 0.020023441326005004, "lm_q1q2_score": 0.0018559284979605844}}
{"text": "#pragma once\n\n#include \"icode_generator.h\"\n#include <halley/data_structures/hash_map.h>\n#include <gsl/gsl>\n#include \"halley/file/path.h\"\n\nnamespace YAML\n{\n\tclass Node;\n}\n\nnamespace Halley\n{\n\tclass ECSData;\n\tclass ComponentSchema;\n\tclass SystemSchema;\n\tclass MessageSchema;\n\tclass CustomTypeSchema;\n\t\n\tclass Codegen\n\t{\t\n\t\tstruct Stats\n\t\t{\n\t\t\tint written = 0;\n\t\t\tint skipped = 0;\n\t\t\tstd::vector<Path> files;\n\t\t};\n\n\tpublic:\n\t\tusing ProgressReporter = std::function<bool(float, String)>;\n\n\t\tstatic void run(Path inDir, Path outDir);\n\t\tstatic std::vector<Path> generateCode(const ECSData& data, Path directory);\n\n\tprivate:\n\t\tstatic bool writeFile(Path path, const char* data, size_t dataSize, bool stub);\n\t\tstatic void writeFiles(Path directory, const CodeGenResult& files, Stats& stats);\n\t};\n}", "meta": {"hexsha": "d900fc143704a4de4acd82d6bb0d33a018785b52", "size": 789, "ext": "h", "lang": "C", "max_stars_repo_path": "src/tools/tools/include/halley/tools/codegen/codegen.h", "max_stars_repo_name": "code-disaster/halley", "max_stars_repo_head_hexsha": "5c85c889b76c69c6bdef6f4801c6aba282b7af80", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3262.0, "max_stars_repo_stars_event_min_datetime": "2016-04-10T15:24:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:47:08.000Z", "max_issues_repo_path": "src/tools/tools/include/halley/tools/codegen/codegen.h", "max_issues_repo_name": "code-disaster/halley", "max_issues_repo_head_hexsha": "5c85c889b76c69c6bdef6f4801c6aba282b7af80", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 53.0, "max_issues_repo_issues_event_min_datetime": "2016-10-09T16:25:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-10T13:52:37.000Z", "max_forks_repo_path": "src/tools/tools/include/halley/tools/codegen/codegen.h", "max_forks_repo_name": "code-disaster/halley", "max_forks_repo_head_hexsha": "5c85c889b76c69c6bdef6f4801c6aba282b7af80", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 193.0, "max_forks_repo_forks_event_min_datetime": "2017-10-23T06:08:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T12:59:58.000Z", "avg_line_length": 19.725, "max_line_length": 83, "alphanum_fraction": 0.7262357414, "num_tokens": 198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10230469694465662, "lm_q2_score": 0.01798620762623757, "lm_q1q2_score": 0.0018400735203859063}}
{"text": "#pragma once\n\n#include <tuple>\n\n#include \"arcana/threading/dispatcher.h\"\n\n#include \"router.h\"\n\n#include <gsl/gsl>\n\nnamespace arcana\n{\n    //\n    // A mediator is an event pool that ensures all events are sent\n    // through the right dispatcher (execution context).\n    // This is usefull when you want anyone to be able to send\n    // events but only want to process the events from one thread.\n    //\n    template<typename DispatcherT, typename... EventTs>\n    class mediator\n    {\n        using router_t = router<EventTs...>;\n\n    public:\n        using dispatcher_t = DispatcherT;\n\n        explicit mediator(dispatcher_t& dispatcher)\n            : m_dispatcher{ dispatcher }\n        {}\n\n        template<typename T>\n        void send(T&& evt)\n        {\n            m_dispatcher.queue([ this, evt = std::forward<T>(evt) ]() { m_router.fire(evt); });\n        }\n\n        template<typename EventT, typename T>\n        ticket add_listener(T&& listener)\n        {\n            GSL_CONTRACT_CHECK(\"thread affinity\", m_dispatcher.get_affinity().check());\n            return m_router.template add_listener<EventT>(std::forward<T>(listener));\n        }\n\n        dispatcher_t& dispatcher()\n        {\n            return m_dispatcher;\n        }\n\n    private:\n        dispatcher_t& m_dispatcher;\n        router_t m_router;\n    };\n}\n", "meta": {"hexsha": "5a28911375818020a3d40039ff48d24f9e482b13", "size": 1320, "ext": "h", "lang": "C", "max_stars_repo_path": "Source/Shared/arcana/messaging/mediator.h", "max_stars_repo_name": "andrei-datcu/arcana.cpp", "max_stars_repo_head_hexsha": "3c4757cbee49b3272130bf8b72094c2c62fd36c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 65.0, "max_stars_repo_stars_event_min_datetime": "2019-05-08T01:53:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T15:05:38.000Z", "max_issues_repo_path": "Source/Shared/arcana/messaging/mediator.h", "max_issues_repo_name": "andrei-datcu/arcana.cpp", "max_issues_repo_head_hexsha": "3c4757cbee49b3272130bf8b72094c2c62fd36c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2019-08-13T03:18:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T20:12:24.000Z", "max_forks_repo_path": "Source/Shared/arcana/messaging/mediator.h", "max_forks_repo_name": "andrei-datcu/arcana.cpp", "max_forks_repo_head_hexsha": "3c4757cbee49b3272130bf8b72094c2c62fd36c5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2019-05-09T23:07:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-26T14:24:29.000Z", "avg_line_length": 24.4444444444, "max_line_length": 95, "alphanum_fraction": 0.6068181818, "num_tokens": 280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06954174836258786, "lm_q2_score": 0.026355354662400805, "lm_q1q2_score": 0.0018327974419394336}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef file_d50c3538_0c5e_49a3_bc6f_5d6bc6144520_h\r\n#define file_d50c3538_0c5e_49a3_bc6f_5d6bc6144520_h\r\n\r\n#include <stdio.h>\r\n#include <gslib/config.h>\r\n#include <gslib/string.h>\r\n\r\n__gslib_begin__\r\n\r\ntypedef FILE*   fileptr;\r\ntypedef fpos_t  fpos;\r\n\r\nclass file\r\n{\r\nprotected:\r\n    fileptr     _file;\r\n\r\npublic:\r\n    file(): _file(0) {}\r\n    file(const gchar* name, const gchar* mode): _file(0) { open(name, mode); }\r\n    ~file() { close(); }\r\n\r\n#ifndef _UNICODE\r\n\r\n    void open(const gchar* name, const gchar* mode) { fopen_s(&_file, name, mode); }\r\n    void open_text(const gchar* name, bool readonly)\r\n    {\r\n        readonly ? fopen_s(&_file, name, _t(\"r\")) :\r\n            fopen_s(&_file, name, _t(\"w\"));\r\n    }\r\n    int read(gchar buf[], int len)\r\n    {\r\n        assert(buf && len);\r\n        return fgets(buf, len, _file) ? strlen(buf) : 0;\r\n    }\r\n    int write(const gchar str[])\r\n    {\r\n        assert(str);\r\n        return (int)fputs(str, _file);\r\n    }\r\n\r\n#else\r\n    \r\n    void open(const gchar* name, const gchar* mode) { _wfopen_s(&_file, name, mode); }\r\n    void open_text(const gchar* name, bool readonly)\r\n    {\r\n        readonly ? _wfopen_s(&_file, name, _t(\"r,ccs=UNICODE\")) :\r\n            _wfopen_s(&_file, name, _t(\"w,ccs=UNICODE\"));\r\n    }\r\n    int read(gchar buf[], int len)\r\n    {\r\n        assert(buf && len);\r\n        return fgetws(buf, len, _file) ? wcslen(buf) : 0;\r\n    }\r\n    int write(const gchar str[])\r\n    {\r\n        assert(str);\r\n        return fputws(str, _file);\r\n    }\r\n\r\n#endif\r\n\r\n    bool is_valid() const { return _file != 0; }\r\n    void flush() { fflush(_file); }\r\n    void rewind() { ::rewind(_file); }\r\n    int current() const { return ftell(_file); }\r\n    int seek(int offset, int sps) { return fseek(_file, offset, sps); }\r\n    int size()\r\n    {\r\n        int old = current();\r\n        seek(0, SEEK_END);\r\n        int pos = current();\r\n        seek(old, SEEK_SET);\r\n        return pos;\r\n    }\r\n    void close()\r\n    {\r\n        if (_file) {\r\n            fclose(_file);\r\n            _file = 0;\r\n        }\r\n    }\r\n    int read_fillup(gchar buf[], int len)\r\n    {\r\n        assert(buf && len > 0);\r\n        int acc = 0;\r\n        while(acc < len) {\r\n            int r = read(buf + acc, len - acc);\r\n            if(r <= 0)\r\n                break;\r\n            acc += r;\r\n        }\r\n        return acc;\r\n    }\r\n    int read(string& buf, int start, int len)\r\n    {\r\n        int lento = start + len;\r\n        if(lento && buf.size() < lento)\r\n            buf.resize(lento);\r\n        return read(&buf.front() + start, len);\r\n    }\r\n    void read_all(string& buf)\r\n    {\r\n        int total = size() + 1;     /* a weird problem about fgetws. */\r\n        if(buf.size() < total)\r\n            buf.resize(total);\r\n        for(int i = 0, j; j = read(buf, i, total-i); i += j);\r\n        /* right trim */\r\n        int p = buf.find_last_not_of(_t('\\0'));\r\n        if(p != string::npos) {\r\n            p += 1;\r\n            if(p <= buf.length())\r\n                buf.resize(p);\r\n        }\r\n    }\r\n    int write(const string& buf) { return write(&buf.front()); }\r\n    int get(byte buf[], int len) { return (int)fread_s(buf, len, 1, len, _file); }\r\n    int get(word buf[], int len) { return (int)fread_s(buf, len * 2, 2, len, _file); }\r\n    int get(dword buf[], int len) { return (int)fread_s(buf, len * 4, 4, len, _file); }\r\n    int get(qword buf[], int len) { return (int)fread_s(buf, len * 8, 8, len, _file); }\r\n    int put(const byte buf[], int len) { return (int)fwrite(buf, 1, len, _file); }\r\n    int put(const word buf[], int len) { return (int)fwrite(buf, 2, len, _file); }\r\n    int put(const dword buf[], int len) { return (int)fwrite(buf, 4, len, _file); }\r\n    int put(const qword buf[], int len) { return (int)fwrite(buf, 8, len, _file); }\r\n\r\npublic:\r\n    template<int _szelem>\r\n    int put_elem(const void* buf, int len) {}\r\n    template<>\r\n    int put_elem<1>(const void* buf, int len) { return put((const byte*)buf, len); }\r\n    template<>\r\n    int put_elem<2>(const void* buf, int len) { return put((const word*)buf, len); }\r\n    template<>\r\n    int put_elem<4>(const void* buf, int len) { return put((const dword*)buf, len); }\r\n    template<>\r\n    int put_elem<8>(const void* buf, int len) { return put((const qword*)buf, len); }\r\n};\r\n\r\n__gslib_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "e5d5b7c42a2471a119f566b577133a4348dc4148", "size": 5563, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gslib/file.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/gslib/file.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gslib/file.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 32.9171597633, "max_line_length": 88, "alphanum_fraction": 0.578285098, "num_tokens": 1514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.045352584425245944, "lm_q2_score": 0.040237944925478955, "lm_q1q2_score": 0.001824894794331181}}
{"text": "/* ----------------------------------------------------------------------------\n * This file was automatically generated by SWIG (http://www.swig.org).\n * Version 1.3.36\n * \n * This file is not intended to be easily readable and contains a number of \n * coding conventions designed to improve portability and efficiency. Do not make\n * changes to this file unless you know what you are doing--modify the SWIG \n * interface file instead. \n * ----------------------------------------------------------------------------- */\n\n#define SWIGPYTHON\n#define SWIG_PYTHON_DIRECTOR_NO_VTABLE\n/* -----------------------------------------------------------------------------\n *  This section contains generic SWIG labels for method/variable\n *  declarations/attributes, and other compiler dependent labels.\n * ----------------------------------------------------------------------------- */\n\n/* template workaround for compilers that cannot correctly implement the C++ standard */\n#ifndef SWIGTEMPLATEDISAMBIGUATOR\n# if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x560)\n#  define SWIGTEMPLATEDISAMBIGUATOR template\n# elif defined(__HP_aCC)\n/* Needed even with `aCC -AA' when `aCC -V' reports HP ANSI C++ B3910B A.03.55 */\n/* If we find a maximum version that requires this, the test would be __HP_aCC <= 35500 for A.03.55 */\n#  define SWIGTEMPLATEDISAMBIGUATOR template\n# else\n#  define SWIGTEMPLATEDISAMBIGUATOR\n# endif\n#endif\n\n/* inline attribute */\n#ifndef SWIGINLINE\n# if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__))\n#   define SWIGINLINE inline\n# else\n#   define SWIGINLINE\n# endif\n#endif\n\n/* attribute recognised by some compilers to avoid 'unused' warnings */\n#ifndef SWIGUNUSED\n# if defined(__GNUC__)\n#   if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))\n#     define SWIGUNUSED __attribute__ ((__unused__)) \n#   else\n#     define SWIGUNUSED\n#   endif\n# elif defined(__ICC)\n#   define SWIGUNUSED __attribute__ ((__unused__)) \n# else\n#   define SWIGUNUSED \n# endif\n#endif\n\n#ifndef SWIG_MSC_UNSUPPRESS_4505\n# if defined(_MSC_VER)\n#   pragma warning(disable : 4505) /* unreferenced local function has been removed */\n# endif \n#endif\n\n#ifndef SWIGUNUSEDPARM\n# ifdef __cplusplus\n#   define SWIGUNUSEDPARM(p)\n# else\n#   define SWIGUNUSEDPARM(p) p SWIGUNUSED \n# endif\n#endif\n\n/* internal SWIG method */\n#ifndef SWIGINTERN\n# define SWIGINTERN static SWIGUNUSED\n#endif\n\n/* internal inline SWIG method */\n#ifndef SWIGINTERNINLINE\n# define SWIGINTERNINLINE SWIGINTERN SWIGINLINE\n#endif\n\n/* exporting methods */\n#if (__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)\n#  ifndef GCC_HASCLASSVISIBILITY\n#    define GCC_HASCLASSVISIBILITY\n#  endif\n#endif\n\n#ifndef SWIGEXPORT\n# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)\n#   if defined(STATIC_LINKED)\n#     define SWIGEXPORT\n#   else\n#     define SWIGEXPORT __declspec(dllexport)\n#   endif\n# else\n#   if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY)\n#     define SWIGEXPORT __attribute__ ((visibility(\"default\")))\n#   else\n#     define SWIGEXPORT\n#   endif\n# endif\n#endif\n\n/* calling conventions for Windows */\n#ifndef SWIGSTDCALL\n# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)\n#   define SWIGSTDCALL __stdcall\n# else\n#   define SWIGSTDCALL\n# endif \n#endif\n\n/* Deal with Microsoft's attempt at deprecating C standard runtime functions */\n#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE)\n# define _CRT_SECURE_NO_DEPRECATE\n#endif\n\n/* Deal with Microsoft's attempt at deprecating methods in the standard C++ library */\n#if !defined(SWIG_NO_SCL_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_SCL_SECURE_NO_DEPRECATE)\n# define _SCL_SECURE_NO_DEPRECATE\n#endif\n\n\n\n/* Python.h has to appear first */\n#include <Python.h>\n\n/* -----------------------------------------------------------------------------\n * swigrun.swg\n *\n * This file contains generic CAPI SWIG runtime support for pointer\n * type checking.\n * ----------------------------------------------------------------------------- */\n\n/* This should only be incremented when either the layout of swig_type_info changes,\n   or for whatever reason, the runtime changes incompatibly */\n#define SWIG_RUNTIME_VERSION \"4\"\n\n/* define SWIG_TYPE_TABLE_NAME as \"SWIG_TYPE_TABLE\" */\n#ifdef SWIG_TYPE_TABLE\n# define SWIG_QUOTE_STRING(x) #x\n# define SWIG_EXPAND_AND_QUOTE_STRING(x) SWIG_QUOTE_STRING(x)\n# define SWIG_TYPE_TABLE_NAME SWIG_EXPAND_AND_QUOTE_STRING(SWIG_TYPE_TABLE)\n#else\n# define SWIG_TYPE_TABLE_NAME\n#endif\n\n/*\n  You can use the SWIGRUNTIME and SWIGRUNTIMEINLINE macros for\n  creating a static or dynamic library from the swig runtime code.\n  In 99.9% of the cases, swig just needs to declare them as 'static'.\n  \n  But only do this if is strictly necessary, ie, if you have problems\n  with your compiler or so.\n*/\n\n#ifndef SWIGRUNTIME\n# define SWIGRUNTIME SWIGINTERN\n#endif\n\n#ifndef SWIGRUNTIMEINLINE\n# define SWIGRUNTIMEINLINE SWIGRUNTIME SWIGINLINE\n#endif\n\n/*  Generic buffer size */\n#ifndef SWIG_BUFFER_SIZE\n# define SWIG_BUFFER_SIZE 1024\n#endif\n\n/* Flags for pointer conversions */\n#define SWIG_POINTER_DISOWN        0x1\n#define SWIG_CAST_NEW_MEMORY       0x2\n\n/* Flags for new pointer objects */\n#define SWIG_POINTER_OWN           0x1\n\n\n/* \n   Flags/methods for returning states.\n   \n   The swig conversion methods, as ConvertPtr, return and integer \n   that tells if the conversion was successful or not. And if not,\n   an error code can be returned (see swigerrors.swg for the codes).\n   \n   Use the following macros/flags to set or process the returning\n   states.\n   \n   In old swig versions, you usually write code as:\n\n     if (SWIG_ConvertPtr(obj,vptr,ty.flags) != -1) {\n       // success code\n     } else {\n       //fail code\n     }\n\n   Now you can be more explicit as:\n\n    int res = SWIG_ConvertPtr(obj,vptr,ty.flags);\n    if (SWIG_IsOK(res)) {\n      // success code\n    } else {\n      // fail code\n    }\n\n   that seems to be the same, but now you can also do\n\n    Type *ptr;\n    int res = SWIG_ConvertPtr(obj,(void **)(&ptr),ty.flags);\n    if (SWIG_IsOK(res)) {\n      // success code\n      if (SWIG_IsNewObj(res) {\n        ...\n\tdelete *ptr;\n      } else {\n        ...\n      }\n    } else {\n      // fail code\n    }\n    \n   I.e., now SWIG_ConvertPtr can return new objects and you can\n   identify the case and take care of the deallocation. Of course that\n   requires also to SWIG_ConvertPtr to return new result values, as\n\n      int SWIG_ConvertPtr(obj, ptr,...) {         \n        if (<obj is ok>) {\t\t\t       \n          if (<need new object>) {\t\t       \n            *ptr = <ptr to new allocated object>; \n            return SWIG_NEWOBJ;\t\t       \n          } else {\t\t\t\t       \n            *ptr = <ptr to old object>;\t       \n            return SWIG_OLDOBJ;\t\t       \n          } \t\t\t\t       \n        } else {\t\t\t\t       \n          return SWIG_BADOBJ;\t\t       \n        }\t\t\t\t\t       \n      }\n\n   Of course, returning the plain '0(success)/-1(fail)' still works, but you can be\n   more explicit by returning SWIG_BADOBJ, SWIG_ERROR or any of the\n   swig errors code.\n\n   Finally, if the SWIG_CASTRANK_MODE is enabled, the result code\n   allows to return the 'cast rank', for example, if you have this\n\n       int food(double)\n       int fooi(int);\n\n   and you call\n \n      food(1)   // cast rank '1'  (1 -> 1.0)\n      fooi(1)   // cast rank '0'\n\n   just use the SWIG_AddCast()/SWIG_CheckState()\n\n\n */\n#define SWIG_OK                    (0) \n#define SWIG_ERROR                 (-1)\n#define SWIG_IsOK(r)               (r >= 0)\n#define SWIG_ArgError(r)           ((r != SWIG_ERROR) ? r : SWIG_TypeError)  \n\n/* The CastRankLimit says how many bits are used for the cast rank */\n#define SWIG_CASTRANKLIMIT         (1 << 8)\n/* The NewMask denotes the object was created (using new/malloc) */\n#define SWIG_NEWOBJMASK            (SWIG_CASTRANKLIMIT  << 1)\n/* The TmpMask is for in/out typemaps that use temporal objects */\n#define SWIG_TMPOBJMASK            (SWIG_NEWOBJMASK << 1)\n/* Simple returning values */\n#define SWIG_BADOBJ                (SWIG_ERROR)\n#define SWIG_OLDOBJ                (SWIG_OK)\n#define SWIG_NEWOBJ                (SWIG_OK | SWIG_NEWOBJMASK)\n#define SWIG_TMPOBJ                (SWIG_OK | SWIG_TMPOBJMASK)\n/* Check, add and del mask methods */\n#define SWIG_AddNewMask(r)         (SWIG_IsOK(r) ? (r | SWIG_NEWOBJMASK) : r)\n#define SWIG_DelNewMask(r)         (SWIG_IsOK(r) ? (r & ~SWIG_NEWOBJMASK) : r)\n#define SWIG_IsNewObj(r)           (SWIG_IsOK(r) && (r & SWIG_NEWOBJMASK))\n#define SWIG_AddTmpMask(r)         (SWIG_IsOK(r) ? (r | SWIG_TMPOBJMASK) : r)\n#define SWIG_DelTmpMask(r)         (SWIG_IsOK(r) ? (r & ~SWIG_TMPOBJMASK) : r)\n#define SWIG_IsTmpObj(r)           (SWIG_IsOK(r) && (r & SWIG_TMPOBJMASK))\n\n\n/* Cast-Rank Mode */\n#if defined(SWIG_CASTRANK_MODE)\n#  ifndef SWIG_TypeRank\n#    define SWIG_TypeRank             unsigned long\n#  endif\n#  ifndef SWIG_MAXCASTRANK            /* Default cast allowed */\n#    define SWIG_MAXCASTRANK          (2)\n#  endif\n#  define SWIG_CASTRANKMASK          ((SWIG_CASTRANKLIMIT) -1)\n#  define SWIG_CastRank(r)           (r & SWIG_CASTRANKMASK)\nSWIGINTERNINLINE int SWIG_AddCast(int r) { \n  return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r;\n}\nSWIGINTERNINLINE int SWIG_CheckState(int r) { \n  return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0; \n}\n#else /* no cast-rank mode */\n#  define SWIG_AddCast\n#  define SWIG_CheckState(r) (SWIG_IsOK(r) ? 1 : 0)\n#endif\n\n\n\n\n#include <string.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\ntypedef void *(*swig_converter_func)(void *, int *);\ntypedef struct swig_type_info *(*swig_dycast_func)(void **);\n\n/* Structure to store information on one type */\ntypedef struct swig_type_info {\n  const char             *name;\t\t\t/* mangled name of this type */\n  const char             *str;\t\t\t/* human readable name of this type */\n  swig_dycast_func        dcast;\t\t/* dynamic cast function down a hierarchy */\n  struct swig_cast_info  *cast;\t\t\t/* linked list of types that can cast into this type */\n  void                   *clientdata;\t\t/* language specific type data */\n  int                    owndata;\t\t/* flag if the structure owns the clientdata */\n} swig_type_info;\n\n/* Structure to store a type and conversion function used for casting */\ntypedef struct swig_cast_info {\n  swig_type_info         *type;\t\t\t/* pointer to type that is equivalent to this type */\n  swig_converter_func     converter;\t\t/* function to cast the void pointers */\n  struct swig_cast_info  *next;\t\t\t/* pointer to next cast in linked list */\n  struct swig_cast_info  *prev;\t\t\t/* pointer to the previous cast */\n} swig_cast_info;\n\n/* Structure used to store module information\n * Each module generates one structure like this, and the runtime collects\n * all of these structures and stores them in a circularly linked list.*/\ntypedef struct swig_module_info {\n  swig_type_info         **types;\t\t/* Array of pointers to swig_type_info structures that are in this module */\n  size_t                 size;\t\t        /* Number of types in this module */\n  struct swig_module_info *next;\t\t/* Pointer to next element in circularly linked list */\n  swig_type_info         **type_initial;\t/* Array of initially generated type structures */\n  swig_cast_info         **cast_initial;\t/* Array of initially generated casting structures */\n  void                    *clientdata;\t\t/* Language specific module data */\n} swig_module_info;\n\n/* \n  Compare two type names skipping the space characters, therefore\n  \"char*\" == \"char *\" and \"Class<int>\" == \"Class<int >\", etc.\n\n  Return 0 when the two name types are equivalent, as in\n  strncmp, but skipping ' '.\n*/\nSWIGRUNTIME int\nSWIG_TypeNameComp(const char *f1, const char *l1,\n\t\t  const char *f2, const char *l2) {\n  for (;(f1 != l1) && (f2 != l2); ++f1, ++f2) {\n    while ((*f1 == ' ') && (f1 != l1)) ++f1;\n    while ((*f2 == ' ') && (f2 != l2)) ++f2;\n    if (*f1 != *f2) return (*f1 > *f2) ? 1 : -1;\n  }\n  return (int)((l1 - f1) - (l2 - f2));\n}\n\n/*\n  Check type equivalence in a name list like <name1>|<name2>|...\n  Return 0 if not equal, 1 if equal\n*/\nSWIGRUNTIME int\nSWIG_TypeEquiv(const char *nb, const char *tb) {\n  int equiv = 0;\n  const char* te = tb + strlen(tb);\n  const char* ne = nb;\n  while (!equiv && *ne) {\n    for (nb = ne; *ne; ++ne) {\n      if (*ne == '|') break;\n    }\n    equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0;\n    if (*ne) ++ne;\n  }\n  return equiv;\n}\n\n/*\n  Check type equivalence in a name list like <name1>|<name2>|...\n  Return 0 if equal, -1 if nb < tb, 1 if nb > tb\n*/\nSWIGRUNTIME int\nSWIG_TypeCompare(const char *nb, const char *tb) {\n  int equiv = 0;\n  const char* te = tb + strlen(tb);\n  const char* ne = nb;\n  while (!equiv && *ne) {\n    for (nb = ne; *ne; ++ne) {\n      if (*ne == '|') break;\n    }\n    equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0;\n    if (*ne) ++ne;\n  }\n  return equiv;\n}\n\n\n/* think of this as a c++ template<> or a scheme macro */\n#define SWIG_TypeCheck_Template(comparison, ty)         \\\n  if (ty) {                                             \\\n    swig_cast_info *iter = ty->cast;                    \\\n    while (iter) {                                      \\\n      if (comparison) {                                 \\\n        if (iter == ty->cast) return iter;              \\\n        /* Move iter to the top of the linked list */   \\\n        iter->prev->next = iter->next;                  \\\n        if (iter->next)                                 \\\n          iter->next->prev = iter->prev;                \\\n        iter->next = ty->cast;                          \\\n        iter->prev = 0;                                 \\\n        if (ty->cast) ty->cast->prev = iter;            \\\n        ty->cast = iter;                                \\\n        return iter;                                    \\\n      }                                                 \\\n      iter = iter->next;                                \\\n    }                                                   \\\n  }                                                     \\\n  return 0\n\n/*\n  Check the typename\n*/\nSWIGRUNTIME swig_cast_info *\nSWIG_TypeCheck(const char *c, swig_type_info *ty) {\n  SWIG_TypeCheck_Template(strcmp(iter->type->name, c) == 0, ty);\n}\n\n/* Same as previous function, except strcmp is replaced with a pointer comparison */\nSWIGRUNTIME swig_cast_info *\nSWIG_TypeCheckStruct(swig_type_info *from, swig_type_info *into) {\n  SWIG_TypeCheck_Template(iter->type == from, into);\n}\n\n/*\n  Cast a pointer up an inheritance hierarchy\n*/\nSWIGRUNTIMEINLINE void *\nSWIG_TypeCast(swig_cast_info *ty, void *ptr, int *newmemory) {\n  return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr, newmemory);\n}\n\n/* \n   Dynamic pointer casting. Down an inheritance hierarchy\n*/\nSWIGRUNTIME swig_type_info *\nSWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) {\n  swig_type_info *lastty = ty;\n  if (!ty || !ty->dcast) return ty;\n  while (ty && (ty->dcast)) {\n    ty = (*ty->dcast)(ptr);\n    if (ty) lastty = ty;\n  }\n  return lastty;\n}\n\n/*\n  Return the name associated with this type\n*/\nSWIGRUNTIMEINLINE const char *\nSWIG_TypeName(const swig_type_info *ty) {\n  return ty->name;\n}\n\n/*\n  Return the pretty name associated with this type,\n  that is an unmangled type name in a form presentable to the user.\n*/\nSWIGRUNTIME const char *\nSWIG_TypePrettyName(const swig_type_info *type) {\n  /* The \"str\" field contains the equivalent pretty names of the\n     type, separated by vertical-bar characters.  We choose\n     to print the last name, as it is often (?) the most\n     specific. */\n  if (!type) return NULL;\n  if (type->str != NULL) {\n    const char *last_name = type->str;\n    const char *s;\n    for (s = type->str; *s; s++)\n      if (*s == '|') last_name = s+1;\n    return last_name;\n  }\n  else\n    return type->name;\n}\n\n/* \n   Set the clientdata field for a type\n*/\nSWIGRUNTIME void\nSWIG_TypeClientData(swig_type_info *ti, void *clientdata) {\n  swig_cast_info *cast = ti->cast;\n  /* if (ti->clientdata == clientdata) return; */\n  ti->clientdata = clientdata;\n  \n  while (cast) {\n    if (!cast->converter) {\n      swig_type_info *tc = cast->type;\n      if (!tc->clientdata) {\n\tSWIG_TypeClientData(tc, clientdata);\n      }\n    }    \n    cast = cast->next;\n  }\n}\nSWIGRUNTIME void\nSWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) {\n  SWIG_TypeClientData(ti, clientdata);\n  ti->owndata = 1;\n}\n  \n/*\n  Search for a swig_type_info structure only by mangled name\n  Search is a O(log #types)\n  \n  We start searching at module start, and finish searching when start == end.  \n  Note: if start == end at the beginning of the function, we go all the way around\n  the circular list.\n*/\nSWIGRUNTIME swig_type_info *\nSWIG_MangledTypeQueryModule(swig_module_info *start, \n                            swig_module_info *end, \n\t\t            const char *name) {\n  swig_module_info *iter = start;\n  do {\n    if (iter->size) {\n      register size_t l = 0;\n      register size_t r = iter->size - 1;\n      do {\n\t/* since l+r >= 0, we can (>> 1) instead (/ 2) */\n\tregister size_t i = (l + r) >> 1; \n\tconst char *iname = iter->types[i]->name;\n\tif (iname) {\n\t  register int compare = strcmp(name, iname);\n\t  if (compare == 0) {\t    \n\t    return iter->types[i];\n\t  } else if (compare < 0) {\n\t    if (i) {\n\t      r = i - 1;\n\t    } else {\n\t      break;\n\t    }\n\t  } else if (compare > 0) {\n\t    l = i + 1;\n\t  }\n\t} else {\n\t  break; /* should never happen */\n\t}\n      } while (l <= r);\n    }\n    iter = iter->next;\n  } while (iter != end);\n  return 0;\n}\n\n/*\n  Search for a swig_type_info structure for either a mangled name or a human readable name.\n  It first searches the mangled names of the types, which is a O(log #types)\n  If a type is not found it then searches the human readable names, which is O(#types).\n  \n  We start searching at module start, and finish searching when start == end.  \n  Note: if start == end at the beginning of the function, we go all the way around\n  the circular list.\n*/\nSWIGRUNTIME swig_type_info *\nSWIG_TypeQueryModule(swig_module_info *start, \n                     swig_module_info *end, \n\t\t     const char *name) {\n  /* STEP 1: Search the name field using binary search */\n  swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name);\n  if (ret) {\n    return ret;\n  } else {\n    /* STEP 2: If the type hasn't been found, do a complete search\n       of the str field (the human readable name) */\n    swig_module_info *iter = start;\n    do {\n      register size_t i = 0;\n      for (; i < iter->size; ++i) {\n\tif (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name)))\n\t  return iter->types[i];\n      }\n      iter = iter->next;\n    } while (iter != end);\n  }\n  \n  /* neither found a match */\n  return 0;\n}\n\n/* \n   Pack binary data into a string\n*/\nSWIGRUNTIME char *\nSWIG_PackData(char *c, void *ptr, size_t sz) {\n  static const char hex[17] = \"0123456789abcdef\";\n  register const unsigned char *u = (unsigned char *) ptr;\n  register const unsigned char *eu =  u + sz;\n  for (; u != eu; ++u) {\n    register unsigned char uu = *u;\n    *(c++) = hex[(uu & 0xf0) >> 4];\n    *(c++) = hex[uu & 0xf];\n  }\n  return c;\n}\n\n/* \n   Unpack binary data from a string\n*/\nSWIGRUNTIME const char *\nSWIG_UnpackData(const char *c, void *ptr, size_t sz) {\n  register unsigned char *u = (unsigned char *) ptr;\n  register const unsigned char *eu = u + sz;\n  for (; u != eu; ++u) {\n    register char d = *(c++);\n    register unsigned char uu;\n    if ((d >= '0') && (d <= '9'))\n      uu = ((d - '0') << 4);\n    else if ((d >= 'a') && (d <= 'f'))\n      uu = ((d - ('a'-10)) << 4);\n    else \n      return (char *) 0;\n    d = *(c++);\n    if ((d >= '0') && (d <= '9'))\n      uu |= (d - '0');\n    else if ((d >= 'a') && (d <= 'f'))\n      uu |= (d - ('a'-10));\n    else \n      return (char *) 0;\n    *u = uu;\n  }\n  return c;\n}\n\n/* \n   Pack 'void *' into a string buffer.\n*/\nSWIGRUNTIME char *\nSWIG_PackVoidPtr(char *buff, void *ptr, const char *name, size_t bsz) {\n  char *r = buff;\n  if ((2*sizeof(void *) + 2) > bsz) return 0;\n  *(r++) = '_';\n  r = SWIG_PackData(r,&ptr,sizeof(void *));\n  if (strlen(name) + 1 > (bsz - (r - buff))) return 0;\n  strcpy(r,name);\n  return buff;\n}\n\nSWIGRUNTIME const char *\nSWIG_UnpackVoidPtr(const char *c, void **ptr, const char *name) {\n  if (*c != '_') {\n    if (strcmp(c,\"NULL\") == 0) {\n      *ptr = (void *) 0;\n      return name;\n    } else {\n      return 0;\n    }\n  }\n  return SWIG_UnpackData(++c,ptr,sizeof(void *));\n}\n\nSWIGRUNTIME char *\nSWIG_PackDataName(char *buff, void *ptr, size_t sz, const char *name, size_t bsz) {\n  char *r = buff;\n  size_t lname = (name ? strlen(name) : 0);\n  if ((2*sz + 2 + lname) > bsz) return 0;\n  *(r++) = '_';\n  r = SWIG_PackData(r,ptr,sz);\n  if (lname) {\n    strncpy(r,name,lname+1);\n  } else {\n    *r = 0;\n  }\n  return buff;\n}\n\nSWIGRUNTIME const char *\nSWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) {\n  if (*c != '_') {\n    if (strcmp(c,\"NULL\") == 0) {\n      memset(ptr,0,sz);\n      return name;\n    } else {\n      return 0;\n    }\n  }\n  return SWIG_UnpackData(++c,ptr,sz);\n}\n\n#ifdef __cplusplus\n}\n#endif\n\n/*  Errors in SWIG */\n#define  SWIG_UnknownError    \t   -1 \n#define  SWIG_IOError        \t   -2 \n#define  SWIG_RuntimeError   \t   -3 \n#define  SWIG_IndexError     \t   -4 \n#define  SWIG_TypeError      \t   -5 \n#define  SWIG_DivisionByZero \t   -6 \n#define  SWIG_OverflowError  \t   -7 \n#define  SWIG_SyntaxError    \t   -8 \n#define  SWIG_ValueError     \t   -9 \n#define  SWIG_SystemError    \t   -10\n#define  SWIG_AttributeError \t   -11\n#define  SWIG_MemoryError    \t   -12 \n#define  SWIG_NullReferenceError   -13\n\n\n\n\n/* Add PyOS_snprintf for old Pythons */\n#if PY_VERSION_HEX < 0x02020000\n# if defined(_MSC_VER) || defined(__BORLANDC__) || defined(_WATCOM)\n#  define PyOS_snprintf _snprintf\n# else\n#  define PyOS_snprintf snprintf\n# endif\n#endif\n\n/* A crude PyString_FromFormat implementation for old Pythons */\n#if PY_VERSION_HEX < 0x02020000\n\n#ifndef SWIG_PYBUFFER_SIZE\n# define SWIG_PYBUFFER_SIZE 1024\n#endif\n\nstatic PyObject *\nPyString_FromFormat(const char *fmt, ...) {\n  va_list ap;\n  char buf[SWIG_PYBUFFER_SIZE * 2];\n  int res;\n  va_start(ap, fmt);\n  res = vsnprintf(buf, sizeof(buf), fmt, ap);\n  va_end(ap);\n  return (res < 0 || res >= (int)sizeof(buf)) ? 0 : PyString_FromString(buf);\n}\n#endif\n\n/* Add PyObject_Del for old Pythons */\n#if PY_VERSION_HEX < 0x01060000\n# define PyObject_Del(op) PyMem_DEL((op))\n#endif\n#ifndef PyObject_DEL\n# define PyObject_DEL PyObject_Del\n#endif\n\n/* A crude PyExc_StopIteration exception for old Pythons */\n#if PY_VERSION_HEX < 0x02020000\n# ifndef PyExc_StopIteration\n#  define PyExc_StopIteration PyExc_RuntimeError\n# endif\n# ifndef PyObject_GenericGetAttr\n#  define PyObject_GenericGetAttr 0\n# endif\n#endif\n/* Py_NotImplemented is defined in 2.1 and up. */\n#if PY_VERSION_HEX < 0x02010000\n# ifndef Py_NotImplemented\n#  define Py_NotImplemented PyExc_RuntimeError\n# endif\n#endif\n\n\n/* A crude PyString_AsStringAndSize implementation for old Pythons */\n#if PY_VERSION_HEX < 0x02010000\n# ifndef PyString_AsStringAndSize\n#  define PyString_AsStringAndSize(obj, s, len) {*s = PyString_AsString(obj); *len = *s ? strlen(*s) : 0;}\n# endif\n#endif\n\n/* PySequence_Size for old Pythons */\n#if PY_VERSION_HEX < 0x02000000\n# ifndef PySequence_Size\n#  define PySequence_Size PySequence_Length\n# endif\n#endif\n\n\n/* PyBool_FromLong for old Pythons */\n#if PY_VERSION_HEX < 0x02030000\nstatic\nPyObject *PyBool_FromLong(long ok)\n{\n  PyObject *result = ok ? Py_True : Py_False;\n  Py_INCREF(result);\n  return result;\n}\n#endif\n\n/* Py_ssize_t for old Pythons */\n/* This code is as recommended by: */\n/* http://www.python.org/dev/peps/pep-0353/#conversion-guidelines */\n#if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN)\ntypedef int Py_ssize_t;\n# define PY_SSIZE_T_MAX INT_MAX\n# define PY_SSIZE_T_MIN INT_MIN\n#endif\n\n/* -----------------------------------------------------------------------------\n * error manipulation\n * ----------------------------------------------------------------------------- */\n\nSWIGRUNTIME PyObject*\nSWIG_Python_ErrorType(int code) {\n  PyObject* type = 0;\n  switch(code) {\n  case SWIG_MemoryError:\n    type = PyExc_MemoryError;\n    break;\n  case SWIG_IOError:\n    type = PyExc_IOError;\n    break;\n  case SWIG_RuntimeError:\n    type = PyExc_RuntimeError;\n    break;\n  case SWIG_IndexError:\n    type = PyExc_IndexError;\n    break;\n  case SWIG_TypeError:\n    type = PyExc_TypeError;\n    break;\n  case SWIG_DivisionByZero:\n    type = PyExc_ZeroDivisionError;\n    break;\n  case SWIG_OverflowError:\n    type = PyExc_OverflowError;\n    break;\n  case SWIG_SyntaxError:\n    type = PyExc_SyntaxError;\n    break;\n  case SWIG_ValueError:\n    type = PyExc_ValueError;\n    break;\n  case SWIG_SystemError:\n    type = PyExc_SystemError;\n    break;\n  case SWIG_AttributeError:\n    type = PyExc_AttributeError;\n    break;\n  default:\n    type = PyExc_RuntimeError;\n  }\n  return type;\n}\n\n\nSWIGRUNTIME void\nSWIG_Python_AddErrorMsg(const char* mesg)\n{\n  PyObject *type = 0;\n  PyObject *value = 0;\n  PyObject *traceback = 0;\n\n  if (PyErr_Occurred()) PyErr_Fetch(&type, &value, &traceback);\n  if (value) {\n    PyObject *old_str = PyObject_Str(value);\n    PyErr_Clear();\n    Py_XINCREF(type);\n    PyErr_Format(type, \"%s %s\", PyString_AsString(old_str), mesg);\n    Py_DECREF(old_str);\n    Py_DECREF(value);\n  } else {\n    PyErr_SetString(PyExc_RuntimeError, mesg);\n  }\n}\n\n\n\n#if defined(SWIG_PYTHON_NO_THREADS)\n#  if defined(SWIG_PYTHON_THREADS)\n#    undef SWIG_PYTHON_THREADS\n#  endif\n#endif\n#if defined(SWIG_PYTHON_THREADS) /* Threading support is enabled */\n#  if !defined(SWIG_PYTHON_USE_GIL) && !defined(SWIG_PYTHON_NO_USE_GIL)\n#    if (PY_VERSION_HEX >= 0x02030000) /* For 2.3 or later, use the PyGILState calls */\n#      define SWIG_PYTHON_USE_GIL\n#    endif\n#  endif\n#  if defined(SWIG_PYTHON_USE_GIL) /* Use PyGILState threads calls */\n#    ifndef SWIG_PYTHON_INITIALIZE_THREADS\n#     define SWIG_PYTHON_INITIALIZE_THREADS  PyEval_InitThreads() \n#    endif\n#    ifdef __cplusplus /* C++ code */\n       class SWIG_Python_Thread_Block {\n         bool status;\n         PyGILState_STATE state;\n       public:\n         void end() { if (status) { PyGILState_Release(state); status = false;} }\n         SWIG_Python_Thread_Block() : status(true), state(PyGILState_Ensure()) {}\n         ~SWIG_Python_Thread_Block() { end(); }\n       };\n       class SWIG_Python_Thread_Allow {\n         bool status;\n         PyThreadState *save;\n       public:\n         void end() { if (status) { PyEval_RestoreThread(save); status = false; }}\n         SWIG_Python_Thread_Allow() : status(true), save(PyEval_SaveThread()) {}\n         ~SWIG_Python_Thread_Allow() { end(); }\n       };\n#      define SWIG_PYTHON_THREAD_BEGIN_BLOCK   SWIG_Python_Thread_Block _swig_thread_block\n#      define SWIG_PYTHON_THREAD_END_BLOCK     _swig_thread_block.end()\n#      define SWIG_PYTHON_THREAD_BEGIN_ALLOW   SWIG_Python_Thread_Allow _swig_thread_allow\n#      define SWIG_PYTHON_THREAD_END_ALLOW     _swig_thread_allow.end()\n#    else /* C code */\n#      define SWIG_PYTHON_THREAD_BEGIN_BLOCK   PyGILState_STATE _swig_thread_block = PyGILState_Ensure()\n#      define SWIG_PYTHON_THREAD_END_BLOCK     PyGILState_Release(_swig_thread_block)\n#      define SWIG_PYTHON_THREAD_BEGIN_ALLOW   PyThreadState *_swig_thread_allow = PyEval_SaveThread()\n#      define SWIG_PYTHON_THREAD_END_ALLOW     PyEval_RestoreThread(_swig_thread_allow)\n#    endif\n#  else /* Old thread way, not implemented, user must provide it */\n#    if !defined(SWIG_PYTHON_INITIALIZE_THREADS)\n#      define SWIG_PYTHON_INITIALIZE_THREADS\n#    endif\n#    if !defined(SWIG_PYTHON_THREAD_BEGIN_BLOCK)\n#      define SWIG_PYTHON_THREAD_BEGIN_BLOCK\n#    endif\n#    if !defined(SWIG_PYTHON_THREAD_END_BLOCK)\n#      define SWIG_PYTHON_THREAD_END_BLOCK\n#    endif\n#    if !defined(SWIG_PYTHON_THREAD_BEGIN_ALLOW)\n#      define SWIG_PYTHON_THREAD_BEGIN_ALLOW\n#    endif\n#    if !defined(SWIG_PYTHON_THREAD_END_ALLOW)\n#      define SWIG_PYTHON_THREAD_END_ALLOW\n#    endif\n#  endif\n#else /* No thread support */\n#  define SWIG_PYTHON_INITIALIZE_THREADS\n#  define SWIG_PYTHON_THREAD_BEGIN_BLOCK\n#  define SWIG_PYTHON_THREAD_END_BLOCK\n#  define SWIG_PYTHON_THREAD_BEGIN_ALLOW\n#  define SWIG_PYTHON_THREAD_END_ALLOW\n#endif\n\n/* -----------------------------------------------------------------------------\n * Python API portion that goes into the runtime\n * ----------------------------------------------------------------------------- */\n\n#ifdef __cplusplus\nextern \"C\" {\n#if 0\n} /* cc-mode */\n#endif\n#endif\n\n/* -----------------------------------------------------------------------------\n * Constant declarations\n * ----------------------------------------------------------------------------- */\n\n/* Constant Types */\n#define SWIG_PY_POINTER 4\n#define SWIG_PY_BINARY  5\n\n/* Constant information structure */\ntypedef struct swig_const_info {\n  int type;\n  char *name;\n  long lvalue;\n  double dvalue;\n  void   *pvalue;\n  swig_type_info **ptype;\n} swig_const_info;\n\n#ifdef __cplusplus\n#if 0\n{ /* cc-mode */\n#endif\n}\n#endif\n\n\n/* -----------------------------------------------------------------------------\n * See the LICENSE file for information on copyright, usage and redistribution\n * of SWIG, and the README file for authors - http://www.swig.org/release.html.\n *\n * pyrun.swg\n *\n * This file contains the runtime support for Python modules\n * and includes code for managing global variables and pointer\n * type checking.\n *\n * ----------------------------------------------------------------------------- */\n\n/* Common SWIG API */\n\n/* for raw pointers */\n#define SWIG_Python_ConvertPtr(obj, pptr, type, flags)  SWIG_Python_ConvertPtrAndOwn(obj, pptr, type, flags, 0)\n#define SWIG_ConvertPtr(obj, pptr, type, flags)         SWIG_Python_ConvertPtr(obj, pptr, type, flags)\n#define SWIG_ConvertPtrAndOwn(obj,pptr,type,flags,own)  SWIG_Python_ConvertPtrAndOwn(obj, pptr, type, flags, own)\n#define SWIG_NewPointerObj(ptr, type, flags)            SWIG_Python_NewPointerObj(ptr, type, flags)\n#define SWIG_CheckImplicit(ty)                          SWIG_Python_CheckImplicit(ty) \n#define SWIG_AcquirePtr(ptr, src)                       SWIG_Python_AcquirePtr(ptr, src)\n#define swig_owntype                                    int\n\n/* for raw packed data */\n#define SWIG_ConvertPacked(obj, ptr, sz, ty)            SWIG_Python_ConvertPacked(obj, ptr, sz, ty)\n#define SWIG_NewPackedObj(ptr, sz, type)                SWIG_Python_NewPackedObj(ptr, sz, type)\n\n/* for class or struct pointers */\n#define SWIG_ConvertInstance(obj, pptr, type, flags)    SWIG_ConvertPtr(obj, pptr, type, flags)\n#define SWIG_NewInstanceObj(ptr, type, flags)           SWIG_NewPointerObj(ptr, type, flags)\n\n/* for C or C++ function pointers */\n#define SWIG_ConvertFunctionPtr(obj, pptr, type)        SWIG_Python_ConvertFunctionPtr(obj, pptr, type)\n#define SWIG_NewFunctionPtrObj(ptr, type)               SWIG_Python_NewPointerObj(ptr, type, 0)\n\n/* for C++ member pointers, ie, member methods */\n#define SWIG_ConvertMember(obj, ptr, sz, ty)            SWIG_Python_ConvertPacked(obj, ptr, sz, ty)\n#define SWIG_NewMemberObj(ptr, sz, type)                SWIG_Python_NewPackedObj(ptr, sz, type)\n\n\n/* Runtime API */\n\n#define SWIG_GetModule(clientdata)                      SWIG_Python_GetModule()\n#define SWIG_SetModule(clientdata, pointer)             SWIG_Python_SetModule(pointer)\n#define SWIG_NewClientData(obj)                         PySwigClientData_New(obj)\n\n#define SWIG_SetErrorObj                                SWIG_Python_SetErrorObj                            \n#define SWIG_SetErrorMsg                        \tSWIG_Python_SetErrorMsg\t\t\t\t   \n#define SWIG_ErrorType(code)                    \tSWIG_Python_ErrorType(code)                        \n#define SWIG_Error(code, msg)            \t\tSWIG_Python_SetErrorMsg(SWIG_ErrorType(code), msg) \n#define SWIG_fail                        \t\tgoto fail\t\t\t\t\t   \n\n\n/* Runtime API implementation */\n\n/* Error manipulation */\n\nSWIGINTERN void \nSWIG_Python_SetErrorObj(PyObject *errtype, PyObject *obj) {\n  SWIG_PYTHON_THREAD_BEGIN_BLOCK; \n  PyErr_SetObject(errtype, obj);\n  Py_DECREF(obj);\n  SWIG_PYTHON_THREAD_END_BLOCK;\n}\n\nSWIGINTERN void \nSWIG_Python_SetErrorMsg(PyObject *errtype, const char *msg) {\n  SWIG_PYTHON_THREAD_BEGIN_BLOCK;\n  PyErr_SetString(errtype, (char *) msg);\n  SWIG_PYTHON_THREAD_END_BLOCK;\n}\n\n#define SWIG_Python_Raise(obj, type, desc)  SWIG_Python_SetErrorObj(SWIG_Python_ExceptionType(desc), obj)\n\n/* Set a constant value */\n\nSWIGINTERN void\nSWIG_Python_SetConstant(PyObject *d, const char *name, PyObject *obj) {   \n  PyDict_SetItemString(d, (char*) name, obj);\n  Py_DECREF(obj);                            \n}\n\n/* Append a value to the result obj */\n\nSWIGINTERN PyObject*\nSWIG_Python_AppendOutput(PyObject* result, PyObject* obj) {\n#if !defined(SWIG_PYTHON_OUTPUT_TUPLE)\n  if (!result) {\n    result = obj;\n  } else if (result == Py_None) {\n    Py_DECREF(result);\n    result = obj;\n  } else {\n    if (!PyList_Check(result)) {\n      PyObject *o2 = result;\n      result = PyList_New(1);\n      PyList_SetItem(result, 0, o2);\n    }\n    PyList_Append(result,obj);\n    Py_DECREF(obj);\n  }\n  return result;\n#else\n  PyObject*   o2;\n  PyObject*   o3;\n  if (!result) {\n    result = obj;\n  } else if (result == Py_None) {\n    Py_DECREF(result);\n    result = obj;\n  } else {\n    if (!PyTuple_Check(result)) {\n      o2 = result;\n      result = PyTuple_New(1);\n      PyTuple_SET_ITEM(result, 0, o2);\n    }\n    o3 = PyTuple_New(1);\n    PyTuple_SET_ITEM(o3, 0, obj);\n    o2 = result;\n    result = PySequence_Concat(o2, o3);\n    Py_DECREF(o2);\n    Py_DECREF(o3);\n  }\n  return result;\n#endif\n}\n\n/* Unpack the argument tuple */\n\nSWIGINTERN int\nSWIG_Python_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, PyObject **objs)\n{\n  if (!args) {\n    if (!min && !max) {\n      return 1;\n    } else {\n      PyErr_Format(PyExc_TypeError, \"%s expected %s%d arguments, got none\", \n\t\t   name, (min == max ? \"\" : \"at least \"), (int)min);\n      return 0;\n    }\n  }  \n  if (!PyTuple_Check(args)) {\n    PyErr_SetString(PyExc_SystemError, \"UnpackTuple() argument list is not a tuple\");\n    return 0;\n  } else {\n    register Py_ssize_t l = PyTuple_GET_SIZE(args);\n    if (l < min) {\n      PyErr_Format(PyExc_TypeError, \"%s expected %s%d arguments, got %d\", \n\t\t   name, (min == max ? \"\" : \"at least \"), (int)min, (int)l);\n      return 0;\n    } else if (l > max) {\n      PyErr_Format(PyExc_TypeError, \"%s expected %s%d arguments, got %d\", \n\t\t   name, (min == max ? \"\" : \"at most \"), (int)max, (int)l);\n      return 0;\n    } else {\n      register int i;\n      for (i = 0; i < l; ++i) {\n\tobjs[i] = PyTuple_GET_ITEM(args, i);\n      }\n      for (; l < max; ++l) {\n\tobjs[l] = 0;\n      }\n      return i + 1;\n    }    \n  }\n}\n\n/* A functor is a function object with one single object argument */\n#if PY_VERSION_HEX >= 0x02020000\n#define SWIG_Python_CallFunctor(functor, obj)\t        PyObject_CallFunctionObjArgs(functor, obj, NULL);\n#else\n#define SWIG_Python_CallFunctor(functor, obj)\t        PyObject_CallFunction(functor, \"O\", obj);\n#endif\n\n/*\n  Helper for static pointer initialization for both C and C++ code, for example\n  static PyObject *SWIG_STATIC_POINTER(MyVar) = NewSomething(...);\n*/\n#ifdef __cplusplus\n#define SWIG_STATIC_POINTER(var)  var\n#else\n#define SWIG_STATIC_POINTER(var)  var = 0; if (!var) var\n#endif\n\n/* -----------------------------------------------------------------------------\n * Pointer declarations\n * ----------------------------------------------------------------------------- */\n\n/* Flags for new pointer objects */\n#define SWIG_POINTER_NOSHADOW       (SWIG_POINTER_OWN      << 1)\n#define SWIG_POINTER_NEW            (SWIG_POINTER_NOSHADOW | SWIG_POINTER_OWN)\n\n#define SWIG_POINTER_IMPLICIT_CONV  (SWIG_POINTER_DISOWN   << 1)\n\n#ifdef __cplusplus\nextern \"C\" {\n#if 0\n} /* cc-mode */\n#endif\n#endif\n\n/*  How to access Py_None */\n#if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)\n#  ifndef SWIG_PYTHON_NO_BUILD_NONE\n#    ifndef SWIG_PYTHON_BUILD_NONE\n#      define SWIG_PYTHON_BUILD_NONE\n#    endif\n#  endif\n#endif\n\n#ifdef SWIG_PYTHON_BUILD_NONE\n#  ifdef Py_None\n#   undef Py_None\n#   define Py_None SWIG_Py_None()\n#  endif\nSWIGRUNTIMEINLINE PyObject * \n_SWIG_Py_None(void)\n{\n  PyObject *none = Py_BuildValue((char*)\"\");\n  Py_DECREF(none);\n  return none;\n}\nSWIGRUNTIME PyObject * \nSWIG_Py_None(void)\n{\n  static PyObject *SWIG_STATIC_POINTER(none) = _SWIG_Py_None();\n  return none;\n}\n#endif\n\n/* The python void return value */\n\nSWIGRUNTIMEINLINE PyObject * \nSWIG_Py_Void(void)\n{\n  PyObject *none = Py_None;\n  Py_INCREF(none);\n  return none;\n}\n\n/* PySwigClientData */\n\ntypedef struct {\n  PyObject *klass;\n  PyObject *newraw;\n  PyObject *newargs;\n  PyObject *destroy;\n  int delargs;\n  int implicitconv;\n} PySwigClientData;\n\nSWIGRUNTIMEINLINE int \nSWIG_Python_CheckImplicit(swig_type_info *ty)\n{\n  PySwigClientData *data = (PySwigClientData *)ty->clientdata;\n  return data ? data->implicitconv : 0;\n}\n\nSWIGRUNTIMEINLINE PyObject *\nSWIG_Python_ExceptionType(swig_type_info *desc) {\n  PySwigClientData *data = desc ? (PySwigClientData *) desc->clientdata : 0;\n  PyObject *klass = data ? data->klass : 0;\n  return (klass ? klass : PyExc_RuntimeError);\n}\n\n\nSWIGRUNTIME PySwigClientData * \nPySwigClientData_New(PyObject* obj)\n{\n  if (!obj) {\n    return 0;\n  } else {\n    PySwigClientData *data = (PySwigClientData *)malloc(sizeof(PySwigClientData));\n    /* the klass element */\n    data->klass = obj;\n    Py_INCREF(data->klass);\n    /* the newraw method and newargs arguments used to create a new raw instance */\n    if (PyClass_Check(obj)) {\n      data->newraw = 0;\n      data->newargs = obj;\n      Py_INCREF(obj);\n    } else {\n#if (PY_VERSION_HEX < 0x02020000)\n      data->newraw = 0;\n#else\n      data->newraw = PyObject_GetAttrString(data->klass, (char *)\"__new__\");\n#endif\n      if (data->newraw) {\n\tPy_INCREF(data->newraw);\n\tdata->newargs = PyTuple_New(1);\n\tPyTuple_SetItem(data->newargs, 0, obj);\n      } else {\n\tdata->newargs = obj;\n      }\n      Py_INCREF(data->newargs);\n    }\n    /* the destroy method, aka as the C++ delete method */\n    data->destroy = PyObject_GetAttrString(data->klass, (char *)\"__swig_destroy__\");\n    if (PyErr_Occurred()) {\n      PyErr_Clear();\n      data->destroy = 0;\n    }\n    if (data->destroy) {\n      int flags;\n      Py_INCREF(data->destroy);\n      flags = PyCFunction_GET_FLAGS(data->destroy);\n#ifdef METH_O\n      data->delargs = !(flags & (METH_O));\n#else\n      data->delargs = 0;\n#endif\n    } else {\n      data->delargs = 0;\n    }\n    data->implicitconv = 0;\n    return data;\n  }\n}\n\nSWIGRUNTIME void \nPySwigClientData_Del(PySwigClientData* data)\n{\n  Py_XDECREF(data->newraw);\n  Py_XDECREF(data->newargs);\n  Py_XDECREF(data->destroy);\n}\n\n/* =============== PySwigObject =====================*/\n\ntypedef struct {\n  PyObject_HEAD\n  void *ptr;\n  swig_type_info *ty;\n  int own;\n  PyObject *next;\n} PySwigObject;\n\nSWIGRUNTIME PyObject *\nPySwigObject_long(PySwigObject *v)\n{\n  return PyLong_FromVoidPtr(v->ptr);\n}\n\nSWIGRUNTIME PyObject *\nPySwigObject_format(const char* fmt, PySwigObject *v)\n{\n  PyObject *res = NULL;\n  PyObject *args = PyTuple_New(1);\n  if (args) {\n    if (PyTuple_SetItem(args, 0, PySwigObject_long(v)) == 0) {\n      PyObject *ofmt = PyString_FromString(fmt);\n      if (ofmt) {\n\tres = PyString_Format(ofmt,args);\n\tPy_DECREF(ofmt);\n      }\n      Py_DECREF(args);\n    }\n  }\n  return res;\n}\n\nSWIGRUNTIME PyObject *\nPySwigObject_oct(PySwigObject *v)\n{\n  return PySwigObject_format(\"%o\",v);\n}\n\nSWIGRUNTIME PyObject *\nPySwigObject_hex(PySwigObject *v)\n{\n  return PySwigObject_format(\"%x\",v);\n}\n\nSWIGRUNTIME PyObject *\n#ifdef METH_NOARGS\nPySwigObject_repr(PySwigObject *v)\n#else\nPySwigObject_repr(PySwigObject *v, PyObject *args)\n#endif\n{\n  const char *name = SWIG_TypePrettyName(v->ty);\n  PyObject *hex = PySwigObject_hex(v);    \n  PyObject *repr = PyString_FromFormat(\"<Swig Object of type '%s' at 0x%s>\", name, PyString_AsString(hex));\n  Py_DECREF(hex);\n  if (v->next) {\n#ifdef METH_NOARGS\n    PyObject *nrep = PySwigObject_repr((PySwigObject *)v->next);\n#else\n    PyObject *nrep = PySwigObject_repr((PySwigObject *)v->next, args);\n#endif\n    PyString_ConcatAndDel(&repr,nrep);\n  }\n  return repr;  \n}\n\nSWIGRUNTIME int\nPySwigObject_print(PySwigObject *v, FILE *fp, int SWIGUNUSEDPARM(flags))\n{\n#ifdef METH_NOARGS\n  PyObject *repr = PySwigObject_repr(v);\n#else\n  PyObject *repr = PySwigObject_repr(v, NULL);\n#endif\n  if (repr) {\n    fputs(PyString_AsString(repr), fp);\n    Py_DECREF(repr);\n    return 0; \n  } else {\n    return 1; \n  }\n}\n\nSWIGRUNTIME PyObject *\nPySwigObject_str(PySwigObject *v)\n{\n  char result[SWIG_BUFFER_SIZE];\n  return SWIG_PackVoidPtr(result, v->ptr, v->ty->name, sizeof(result)) ?\n    PyString_FromString(result) : 0;\n}\n\nSWIGRUNTIME int\nPySwigObject_compare(PySwigObject *v, PySwigObject *w)\n{\n  void *i = v->ptr;\n  void *j = w->ptr;\n  return (i < j) ? -1 : ((i > j) ? 1 : 0);\n}\n\nSWIGRUNTIME PyTypeObject* _PySwigObject_type(void);\n\nSWIGRUNTIME PyTypeObject*\nPySwigObject_type(void) {\n  static PyTypeObject *SWIG_STATIC_POINTER(type) = _PySwigObject_type();\n  return type;\n}\n\nSWIGRUNTIMEINLINE int\nPySwigObject_Check(PyObject *op) {\n  return ((op)->ob_type == PySwigObject_type())\n    || (strcmp((op)->ob_type->tp_name,\"PySwigObject\") == 0);\n}\n\nSWIGRUNTIME PyObject *\nPySwigObject_New(void *ptr, swig_type_info *ty, int own);\n\nSWIGRUNTIME void\nPySwigObject_dealloc(PyObject *v)\n{\n  PySwigObject *sobj = (PySwigObject *) v;\n  PyObject *next = sobj->next;\n  if (sobj->own == SWIG_POINTER_OWN) {\n    swig_type_info *ty = sobj->ty;\n    PySwigClientData *data = ty ? (PySwigClientData *) ty->clientdata : 0;\n    PyObject *destroy = data ? data->destroy : 0;\n    if (destroy) {\n      /* destroy is always a VARARGS method */\n      PyObject *res;\n      if (data->delargs) {\n\t/* we need to create a temporal object to carry the destroy operation */\n\tPyObject *tmp = PySwigObject_New(sobj->ptr, ty, 0);\n\tres = SWIG_Python_CallFunctor(destroy, tmp);\n\tPy_DECREF(tmp);\n      } else {\n\tPyCFunction meth = PyCFunction_GET_FUNCTION(destroy);\n\tPyObject *mself = PyCFunction_GET_SELF(destroy);\n\tres = ((*meth)(mself, v));\n      }\n      Py_XDECREF(res);\n    } \n#if !defined(SWIG_PYTHON_SILENT_MEMLEAK)\n    else {\n      const char *name = SWIG_TypePrettyName(ty);\n      printf(\"swig/python detected a memory leak of type '%s', no destructor found.\\n\", (name ? name : \"unknown\"));\n    }\n#endif\n  } \n  Py_XDECREF(next);\n  PyObject_DEL(v);\n}\n\nSWIGRUNTIME PyObject* \nPySwigObject_append(PyObject* v, PyObject* next)\n{\n  PySwigObject *sobj = (PySwigObject *) v;\n#ifndef METH_O\n  PyObject *tmp = 0;\n  if (!PyArg_ParseTuple(next,(char *)\"O:append\", &tmp)) return NULL;\n  next = tmp;\n#endif\n  if (!PySwigObject_Check(next)) {\n    return NULL;\n  }\n  sobj->next = next;\n  Py_INCREF(next);\n  return SWIG_Py_Void();\n}\n\nSWIGRUNTIME PyObject* \n#ifdef METH_NOARGS\nPySwigObject_next(PyObject* v)\n#else\nPySwigObject_next(PyObject* v, PyObject *SWIGUNUSEDPARM(args))\n#endif\n{\n  PySwigObject *sobj = (PySwigObject *) v;\n  if (sobj->next) {    \n    Py_INCREF(sobj->next);\n    return sobj->next;\n  } else {\n    return SWIG_Py_Void();\n  }\n}\n\nSWIGINTERN PyObject*\n#ifdef METH_NOARGS\nPySwigObject_disown(PyObject *v)\n#else\nPySwigObject_disown(PyObject* v, PyObject *SWIGUNUSEDPARM(args))\n#endif\n{\n  PySwigObject *sobj = (PySwigObject *)v;\n  sobj->own = 0;\n  return SWIG_Py_Void();\n}\n\nSWIGINTERN PyObject*\n#ifdef METH_NOARGS\nPySwigObject_acquire(PyObject *v)\n#else\nPySwigObject_acquire(PyObject* v, PyObject *SWIGUNUSEDPARM(args))\n#endif\n{\n  PySwigObject *sobj = (PySwigObject *)v;\n  sobj->own = SWIG_POINTER_OWN;\n  return SWIG_Py_Void();\n}\n\nSWIGINTERN PyObject*\nPySwigObject_own(PyObject *v, PyObject *args)\n{\n  PyObject *val = 0;\n#if (PY_VERSION_HEX < 0x02020000)\n  if (!PyArg_ParseTuple(args,(char *)\"|O:own\",&val))\n#else\n  if (!PyArg_UnpackTuple(args, (char *)\"own\", 0, 1, &val)) \n#endif\n    {\n      return NULL;\n    } \n  else\n    {\n      PySwigObject *sobj = (PySwigObject *)v;\n      PyObject *obj = PyBool_FromLong(sobj->own);\n      if (val) {\n#ifdef METH_NOARGS\n\tif (PyObject_IsTrue(val)) {\n\t  PySwigObject_acquire(v);\n\t} else {\n\t  PySwigObject_disown(v);\n\t}\n#else\n\tif (PyObject_IsTrue(val)) {\n\t  PySwigObject_acquire(v,args);\n\t} else {\n\t  PySwigObject_disown(v,args);\n\t}\n#endif\n      } \n      return obj;\n    }\n}\n\n#ifdef METH_O\nstatic PyMethodDef\nswigobject_methods[] = {\n  {(char *)\"disown\",  (PyCFunction)PySwigObject_disown,  METH_NOARGS,  (char *)\"releases ownership of the pointer\"},\n  {(char *)\"acquire\", (PyCFunction)PySwigObject_acquire, METH_NOARGS,  (char *)\"aquires ownership of the pointer\"},\n  {(char *)\"own\",     (PyCFunction)PySwigObject_own,     METH_VARARGS, (char *)\"returns/sets ownership of the pointer\"},\n  {(char *)\"append\",  (PyCFunction)PySwigObject_append,  METH_O,       (char *)\"appends another 'this' object\"},\n  {(char *)\"next\",    (PyCFunction)PySwigObject_next,    METH_NOARGS,  (char *)\"returns the next 'this' object\"},\n  {(char *)\"__repr__\",(PyCFunction)PySwigObject_repr,    METH_NOARGS,  (char *)\"returns object representation\"},\n  {0, 0, 0, 0}  \n};\n#else\nstatic PyMethodDef\nswigobject_methods[] = {\n  {(char *)\"disown\",  (PyCFunction)PySwigObject_disown,  METH_VARARGS,  (char *)\"releases ownership of the pointer\"},\n  {(char *)\"acquire\", (PyCFunction)PySwigObject_acquire, METH_VARARGS,  (char *)\"aquires ownership of the pointer\"},\n  {(char *)\"own\",     (PyCFunction)PySwigObject_own,     METH_VARARGS,  (char *)\"returns/sets ownership of the pointer\"},\n  {(char *)\"append\",  (PyCFunction)PySwigObject_append,  METH_VARARGS,  (char *)\"appends another 'this' object\"},\n  {(char *)\"next\",    (PyCFunction)PySwigObject_next,    METH_VARARGS,  (char *)\"returns the next 'this' object\"},\n  {(char *)\"__repr__\",(PyCFunction)PySwigObject_repr,   METH_VARARGS,  (char *)\"returns object representation\"},\n  {0, 0, 0, 0}  \n};\n#endif\n\n#if PY_VERSION_HEX < 0x02020000\nSWIGINTERN PyObject *\nPySwigObject_getattr(PySwigObject *sobj,char *name)\n{\n  return Py_FindMethod(swigobject_methods, (PyObject *)sobj, name);\n}\n#endif\n\nSWIGRUNTIME PyTypeObject*\n_PySwigObject_type(void) {\n  static char swigobject_doc[] = \"Swig object carries a C/C++ instance pointer\";\n  \n  static PyNumberMethods PySwigObject_as_number = {\n    (binaryfunc)0, /*nb_add*/\n    (binaryfunc)0, /*nb_subtract*/\n    (binaryfunc)0, /*nb_multiply*/\n    (binaryfunc)0, /*nb_divide*/\n    (binaryfunc)0, /*nb_remainder*/\n    (binaryfunc)0, /*nb_divmod*/\n    (ternaryfunc)0,/*nb_power*/\n    (unaryfunc)0,  /*nb_negative*/\n    (unaryfunc)0,  /*nb_positive*/\n    (unaryfunc)0,  /*nb_absolute*/\n    (inquiry)0,    /*nb_nonzero*/\n    0,\t\t   /*nb_invert*/\n    0,\t\t   /*nb_lshift*/\n    0,\t\t   /*nb_rshift*/\n    0,\t\t   /*nb_and*/\n    0,\t\t   /*nb_xor*/\n    0,\t\t   /*nb_or*/\n    (coercion)0,   /*nb_coerce*/\n    (unaryfunc)PySwigObject_long, /*nb_int*/\n    (unaryfunc)PySwigObject_long, /*nb_long*/\n    (unaryfunc)0,                 /*nb_float*/\n    (unaryfunc)PySwigObject_oct,  /*nb_oct*/\n    (unaryfunc)PySwigObject_hex,  /*nb_hex*/\n#if PY_VERSION_HEX >= 0x02050000 /* 2.5.0 */\n    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_index */\n#elif PY_VERSION_HEX >= 0x02020000 /* 2.2.0 */\n    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_true_divide */\n#elif PY_VERSION_HEX >= 0x02000000 /* 2.0.0 */\n    0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_or */\n#endif\n  };\n\n  static PyTypeObject pyswigobject_type;  \n  static int type_init = 0;\n  if (!type_init) {\n    const PyTypeObject tmp\n      = {\n\tPyObject_HEAD_INIT(NULL)\n\t0,\t\t\t\t    /* ob_size */\n\t(char *)\"PySwigObject\",\t\t    /* tp_name */\n\tsizeof(PySwigObject),\t\t    /* tp_basicsize */\n\t0,\t\t\t            /* tp_itemsize */\n\t(destructor)PySwigObject_dealloc,   /* tp_dealloc */\n\t(printfunc)PySwigObject_print,\t    /* tp_print */\n#if PY_VERSION_HEX < 0x02020000\n\t(getattrfunc)PySwigObject_getattr,  /* tp_getattr */ \n#else\n\t(getattrfunc)0,\t\t\t    /* tp_getattr */ \n#endif\n\t(setattrfunc)0,\t\t\t    /* tp_setattr */ \n\t(cmpfunc)PySwigObject_compare,\t    /* tp_compare */ \n\t(reprfunc)PySwigObject_repr,\t    /* tp_repr */    \n\t&PySwigObject_as_number,\t    /* tp_as_number */\n\t0,\t\t\t\t    /* tp_as_sequence */\n\t0,\t\t\t\t    /* tp_as_mapping */\n\t(hashfunc)0,\t\t\t    /* tp_hash */\n\t(ternaryfunc)0,\t\t\t    /* tp_call */\n\t(reprfunc)PySwigObject_str,\t    /* tp_str */\n\tPyObject_GenericGetAttr,            /* tp_getattro */\n\t0,\t\t\t\t    /* tp_setattro */\n\t0,\t\t                    /* tp_as_buffer */\n\tPy_TPFLAGS_DEFAULT,\t            /* tp_flags */\n\tswigobject_doc, \t            /* tp_doc */        \n\t0,                                  /* tp_traverse */\n\t0,                                  /* tp_clear */\n\t0,                                  /* tp_richcompare */\n\t0,                                  /* tp_weaklistoffset */\n#if PY_VERSION_HEX >= 0x02020000\n\t0,                                  /* tp_iter */\n\t0,                                  /* tp_iternext */\n\tswigobject_methods,\t\t    /* tp_methods */ \n\t0,\t\t\t            /* tp_members */\n\t0,\t\t\t\t    /* tp_getset */\t    \t\n\t0,\t\t\t            /* tp_base */\t        \n\t0,\t\t\t\t    /* tp_dict */\t    \t\n\t0,\t\t\t\t    /* tp_descr_get */  \t\n\t0,\t\t\t\t    /* tp_descr_set */  \t\n\t0,\t\t\t\t    /* tp_dictoffset */ \t\n\t0,\t\t\t\t    /* tp_init */\t    \t\n\t0,\t\t\t\t    /* tp_alloc */\t    \t\n\t0,\t\t\t            /* tp_new */\t    \t\n\t0,\t                            /* tp_free */\t   \n        0,                                  /* tp_is_gc */  \n\t0,\t\t\t\t    /* tp_bases */   \n\t0,\t\t\t\t    /* tp_mro */\n\t0,\t\t\t\t    /* tp_cache */   \n \t0,\t\t\t\t    /* tp_subclasses */\n\t0,\t\t\t\t    /* tp_weaklist */\n#endif\n#if PY_VERSION_HEX >= 0x02030000\n\t0,                                  /* tp_del */\n#endif\n#ifdef COUNT_ALLOCS\n\t0,0,0,0                             /* tp_alloc -> tp_next */\n#endif\n      };\n    pyswigobject_type = tmp;\n    pyswigobject_type.ob_type = &PyType_Type;\n    type_init = 1;\n  }\n  return &pyswigobject_type;\n}\n\nSWIGRUNTIME PyObject *\nPySwigObject_New(void *ptr, swig_type_info *ty, int own)\n{\n  PySwigObject *sobj = PyObject_NEW(PySwigObject, PySwigObject_type());\n  if (sobj) {\n    sobj->ptr  = ptr;\n    sobj->ty   = ty;\n    sobj->own  = own;\n    sobj->next = 0;\n  }\n  return (PyObject *)sobj;\n}\n\n/* -----------------------------------------------------------------------------\n * Implements a simple Swig Packed type, and use it instead of string\n * ----------------------------------------------------------------------------- */\n\ntypedef struct {\n  PyObject_HEAD\n  void *pack;\n  swig_type_info *ty;\n  size_t size;\n} PySwigPacked;\n\nSWIGRUNTIME int\nPySwigPacked_print(PySwigPacked *v, FILE *fp, int SWIGUNUSEDPARM(flags))\n{\n  char result[SWIG_BUFFER_SIZE];\n  fputs(\"<Swig Packed \", fp); \n  if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) {\n    fputs(\"at \", fp); \n    fputs(result, fp); \n  }\n  fputs(v->ty->name,fp); \n  fputs(\">\", fp);\n  return 0; \n}\n  \nSWIGRUNTIME PyObject *\nPySwigPacked_repr(PySwigPacked *v)\n{\n  char result[SWIG_BUFFER_SIZE];\n  if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) {\n    return PyString_FromFormat(\"<Swig Packed at %s%s>\", result, v->ty->name);\n  } else {\n    return PyString_FromFormat(\"<Swig Packed %s>\", v->ty->name);\n  }  \n}\n\nSWIGRUNTIME PyObject *\nPySwigPacked_str(PySwigPacked *v)\n{\n  char result[SWIG_BUFFER_SIZE];\n  if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))){\n    return PyString_FromFormat(\"%s%s\", result, v->ty->name);\n  } else {\n    return PyString_FromString(v->ty->name);\n  }  \n}\n\nSWIGRUNTIME int\nPySwigPacked_compare(PySwigPacked *v, PySwigPacked *w)\n{\n  size_t i = v->size;\n  size_t j = w->size;\n  int s = (i < j) ? -1 : ((i > j) ? 1 : 0);\n  return s ? s : strncmp((char *)v->pack, (char *)w->pack, 2*v->size);\n}\n\nSWIGRUNTIME PyTypeObject* _PySwigPacked_type(void);\n\nSWIGRUNTIME PyTypeObject*\nPySwigPacked_type(void) {\n  static PyTypeObject *SWIG_STATIC_POINTER(type) = _PySwigPacked_type();\n  return type;\n}\n\nSWIGRUNTIMEINLINE int\nPySwigPacked_Check(PyObject *op) {\n  return ((op)->ob_type == _PySwigPacked_type()) \n    || (strcmp((op)->ob_type->tp_name,\"PySwigPacked\") == 0);\n}\n\nSWIGRUNTIME void\nPySwigPacked_dealloc(PyObject *v)\n{\n  if (PySwigPacked_Check(v)) {\n    PySwigPacked *sobj = (PySwigPacked *) v;\n    free(sobj->pack);\n  }\n  PyObject_DEL(v);\n}\n\nSWIGRUNTIME PyTypeObject*\n_PySwigPacked_type(void) {\n  static char swigpacked_doc[] = \"Swig object carries a C/C++ instance pointer\";\n  static PyTypeObject pyswigpacked_type;\n  static int type_init = 0;  \n  if (!type_init) {\n    const PyTypeObject tmp\n      = {\n\tPyObject_HEAD_INIT(NULL)\n\t0,\t\t\t\t    /* ob_size */\t\n\t(char *)\"PySwigPacked\",\t\t    /* tp_name */\t\n\tsizeof(PySwigPacked),\t\t    /* tp_basicsize */\t\n\t0,\t\t\t\t    /* tp_itemsize */\t\n\t(destructor)PySwigPacked_dealloc,   /* tp_dealloc */\t\n\t(printfunc)PySwigPacked_print,\t    /* tp_print */   \t\n\t(getattrfunc)0,\t\t\t    /* tp_getattr */ \t\n\t(setattrfunc)0,\t\t\t    /* tp_setattr */ \t\n\t(cmpfunc)PySwigPacked_compare,\t    /* tp_compare */ \t\n\t(reprfunc)PySwigPacked_repr,\t    /* tp_repr */    \t\n\t0,\t                            /* tp_as_number */\t\n\t0,\t\t\t\t    /* tp_as_sequence */\n\t0,\t\t\t\t    /* tp_as_mapping */\t\n\t(hashfunc)0,\t\t\t    /* tp_hash */\t\n\t(ternaryfunc)0,\t\t\t    /* tp_call */\t\n\t(reprfunc)PySwigPacked_str,\t    /* tp_str */\t\n\tPyObject_GenericGetAttr,            /* tp_getattro */\n\t0,\t\t\t\t    /* tp_setattro */\n\t0,\t\t                    /* tp_as_buffer */\n\tPy_TPFLAGS_DEFAULT,\t            /* tp_flags */\n\tswigpacked_doc, \t            /* tp_doc */\n\t0,                                  /* tp_traverse */\n\t0,                                  /* tp_clear */\n\t0,                                  /* tp_richcompare */\n\t0,                                  /* tp_weaklistoffset */\n#if PY_VERSION_HEX >= 0x02020000\n\t0,                                  /* tp_iter */\n\t0,                                  /* tp_iternext */\n\t0,\t\t                    /* tp_methods */ \n\t0,\t\t\t            /* tp_members */\n\t0,\t\t\t\t    /* tp_getset */\t    \t\n\t0,\t\t\t            /* tp_base */\t        \n\t0,\t\t\t\t    /* tp_dict */\t    \t\n\t0,\t\t\t\t    /* tp_descr_get */  \t\n\t0,\t\t\t\t    /* tp_descr_set */  \t\n\t0,\t\t\t\t    /* tp_dictoffset */ \t\n\t0,\t\t\t\t    /* tp_init */\t    \t\n\t0,\t\t\t\t    /* tp_alloc */\t    \t\n\t0,\t\t\t            /* tp_new */\t    \t\n\t0, \t                            /* tp_free */\t   \n        0,                                  /* tp_is_gc */  \n\t0,\t\t\t\t    /* tp_bases */   \n\t0,\t\t\t\t    /* tp_mro */\n\t0,\t\t\t\t    /* tp_cache */   \n \t0,\t\t\t\t    /* tp_subclasses */\n\t0,\t\t\t\t    /* tp_weaklist */\n#endif\n#if PY_VERSION_HEX >= 0x02030000\n\t0,                                  /* tp_del */\n#endif\n#ifdef COUNT_ALLOCS\n\t0,0,0,0                             /* tp_alloc -> tp_next */\n#endif\n      };\n    pyswigpacked_type = tmp;\n    pyswigpacked_type.ob_type = &PyType_Type;\n    type_init = 1;\n  }\n  return &pyswigpacked_type;\n}\n\nSWIGRUNTIME PyObject *\nPySwigPacked_New(void *ptr, size_t size, swig_type_info *ty)\n{\n  PySwigPacked *sobj = PyObject_NEW(PySwigPacked, PySwigPacked_type());\n  if (sobj) {\n    void *pack = malloc(size);\n    if (pack) {\n      memcpy(pack, ptr, size);\n      sobj->pack = pack;\n      sobj->ty   = ty;\n      sobj->size = size;\n    } else {\n      PyObject_DEL((PyObject *) sobj);\n      sobj = 0;\n    }\n  }\n  return (PyObject *) sobj;\n}\n\nSWIGRUNTIME swig_type_info *\nPySwigPacked_UnpackData(PyObject *obj, void *ptr, size_t size)\n{\n  if (PySwigPacked_Check(obj)) {\n    PySwigPacked *sobj = (PySwigPacked *)obj;\n    if (sobj->size != size) return 0;\n    memcpy(ptr, sobj->pack, size);\n    return sobj->ty;\n  } else {\n    return 0;\n  }\n}\n\n/* -----------------------------------------------------------------------------\n * pointers/data manipulation\n * ----------------------------------------------------------------------------- */\n\nSWIGRUNTIMEINLINE PyObject *\n_SWIG_This(void)\n{\n  return PyString_FromString(\"this\");\n}\n\nSWIGRUNTIME PyObject *\nSWIG_This(void)\n{\n  static PyObject *SWIG_STATIC_POINTER(swig_this) = _SWIG_This();\n  return swig_this;\n}\n\n/* #define SWIG_PYTHON_SLOW_GETSET_THIS */\n\nSWIGRUNTIME PySwigObject *\nSWIG_Python_GetSwigThis(PyObject *pyobj) \n{\n  if (PySwigObject_Check(pyobj)) {\n    return (PySwigObject *) pyobj;\n  } else {\n    PyObject *obj = 0;\n#if (!defined(SWIG_PYTHON_SLOW_GETSET_THIS) && (PY_VERSION_HEX >= 0x02030000))\n    if (PyInstance_Check(pyobj)) {\n      obj = _PyInstance_Lookup(pyobj, SWIG_This());      \n    } else {\n      PyObject **dictptr = _PyObject_GetDictPtr(pyobj);\n      if (dictptr != NULL) {\n\tPyObject *dict = *dictptr;\n\tobj = dict ? PyDict_GetItem(dict, SWIG_This()) : 0;\n      } else {\n#ifdef PyWeakref_CheckProxy\n\tif (PyWeakref_CheckProxy(pyobj)) {\n\t  PyObject *wobj = PyWeakref_GET_OBJECT(pyobj);\n\t  return wobj ? SWIG_Python_GetSwigThis(wobj) : 0;\n\t}\n#endif\n\tobj = PyObject_GetAttr(pyobj,SWIG_This());\n\tif (obj) {\n\t  Py_DECREF(obj);\n\t} else {\n\t  if (PyErr_Occurred()) PyErr_Clear();\n\t  return 0;\n\t}\n      }\n    }\n#else\n    obj = PyObject_GetAttr(pyobj,SWIG_This());\n    if (obj) {\n      Py_DECREF(obj);\n    } else {\n      if (PyErr_Occurred()) PyErr_Clear();\n      return 0;\n    }\n#endif\n    if (obj && !PySwigObject_Check(obj)) {\n      /* a PyObject is called 'this', try to get the 'real this'\n\t PySwigObject from it */ \n      return SWIG_Python_GetSwigThis(obj);\n    }\n    return (PySwigObject *)obj;\n  }\n}\n\n/* Acquire a pointer value */\n\nSWIGRUNTIME int\nSWIG_Python_AcquirePtr(PyObject *obj, int own) {\n  if (own == SWIG_POINTER_OWN) {\n    PySwigObject *sobj = SWIG_Python_GetSwigThis(obj);\n    if (sobj) {\n      int oldown = sobj->own;\n      sobj->own = own;\n      return oldown;\n    }\n  }\n  return 0;\n}\n\n/* Convert a pointer value */\n\nSWIGRUNTIME int\nSWIG_Python_ConvertPtrAndOwn(PyObject *obj, void **ptr, swig_type_info *ty, int flags, int *own) {\n  if (!obj) return SWIG_ERROR;\n  if (obj == Py_None) {\n    if (ptr) *ptr = 0;\n    return SWIG_OK;\n  } else {\n    PySwigObject *sobj = SWIG_Python_GetSwigThis(obj);\n    if (own)\n      *own = 0;\n    while (sobj) {\n      void *vptr = sobj->ptr;\n      if (ty) {\n\tswig_type_info *to = sobj->ty;\n\tif (to == ty) {\n\t  /* no type cast needed */\n\t  if (ptr) *ptr = vptr;\n\t  break;\n\t} else {\n\t  swig_cast_info *tc = SWIG_TypeCheck(to->name,ty);\n\t  if (!tc) {\n\t    sobj = (PySwigObject *)sobj->next;\n\t  } else {\n\t    if (ptr) {\n              int newmemory = 0;\n              *ptr = SWIG_TypeCast(tc,vptr,&newmemory);\n              if (newmemory == SWIG_CAST_NEW_MEMORY) {\n                assert(own);\n                if (own)\n                  *own = *own | SWIG_CAST_NEW_MEMORY;\n              }\n            }\n\t    break;\n\t  }\n\t}\n      } else {\n\tif (ptr) *ptr = vptr;\n\tbreak;\n      }\n    }\n    if (sobj) {\n      if (own)\n        *own = *own | sobj->own;\n      if (flags & SWIG_POINTER_DISOWN) {\n\tsobj->own = 0;\n      }\n      return SWIG_OK;\n    } else {\n      int res = SWIG_ERROR;\n      if (flags & SWIG_POINTER_IMPLICIT_CONV) {\n\tPySwigClientData *data = ty ? (PySwigClientData *) ty->clientdata : 0;\n\tif (data && !data->implicitconv) {\n\t  PyObject *klass = data->klass;\n\t  if (klass) {\n\t    PyObject *impconv;\n\t    data->implicitconv = 1; /* avoid recursion and call 'explicit' constructors*/\n\t    impconv = SWIG_Python_CallFunctor(klass, obj);\n\t    data->implicitconv = 0;\n\t    if (PyErr_Occurred()) {\n\t      PyErr_Clear();\n\t      impconv = 0;\n\t    }\n\t    if (impconv) {\n\t      PySwigObject *iobj = SWIG_Python_GetSwigThis(impconv);\n\t      if (iobj) {\n\t\tvoid *vptr;\n\t\tres = SWIG_Python_ConvertPtrAndOwn((PyObject*)iobj, &vptr, ty, 0, 0);\n\t\tif (SWIG_IsOK(res)) {\n\t\t  if (ptr) {\n\t\t    *ptr = vptr;\n\t\t    /* transfer the ownership to 'ptr' */\n\t\t    iobj->own = 0;\n\t\t    res = SWIG_AddCast(res);\n\t\t    res = SWIG_AddNewMask(res);\n\t\t  } else {\n\t\t    res = SWIG_AddCast(res);\t\t    \n\t\t  }\n\t\t}\n\t      }\n\t      Py_DECREF(impconv);\n\t    }\n\t  }\n\t}\n      }\n      return res;\n    }\n  }\n}\n\n/* Convert a function ptr value */\n\nSWIGRUNTIME int\nSWIG_Python_ConvertFunctionPtr(PyObject *obj, void **ptr, swig_type_info *ty) {\n  if (!PyCFunction_Check(obj)) {\n    return SWIG_ConvertPtr(obj, ptr, ty, 0);\n  } else {\n    void *vptr = 0;\n    \n    /* here we get the method pointer for callbacks */\n    const char *doc = (((PyCFunctionObject *)obj) -> m_ml -> ml_doc);\n    const char *desc = doc ? strstr(doc, \"swig_ptr: \") : 0;\n    if (desc) {\n      desc = ty ? SWIG_UnpackVoidPtr(desc + 10, &vptr, ty->name) : 0;\n      if (!desc) return SWIG_ERROR;\n    }\n    if (ty) {\n      swig_cast_info *tc = SWIG_TypeCheck(desc,ty);\n      if (tc) {\n        int newmemory = 0;\n        *ptr = SWIG_TypeCast(tc,vptr,&newmemory);\n        assert(!newmemory); /* newmemory handling not yet implemented */\n      } else {\n        return SWIG_ERROR;\n      }\n    } else {\n      *ptr = vptr;\n    }\n    return SWIG_OK;\n  }\n}\n\n/* Convert a packed value value */\n\nSWIGRUNTIME int\nSWIG_Python_ConvertPacked(PyObject *obj, void *ptr, size_t sz, swig_type_info *ty) {\n  swig_type_info *to = PySwigPacked_UnpackData(obj, ptr, sz);\n  if (!to) return SWIG_ERROR;\n  if (ty) {\n    if (to != ty) {\n      /* check type cast? */\n      swig_cast_info *tc = SWIG_TypeCheck(to->name,ty);\n      if (!tc) return SWIG_ERROR;\n    }\n  }\n  return SWIG_OK;\n}  \n\n/* -----------------------------------------------------------------------------\n * Create a new pointer object\n * ----------------------------------------------------------------------------- */\n\n/*\n  Create a new instance object, whitout calling __init__, and set the\n  'this' attribute.\n*/\n\nSWIGRUNTIME PyObject* \nSWIG_Python_NewShadowInstance(PySwigClientData *data, PyObject *swig_this)\n{\n#if (PY_VERSION_HEX >= 0x02020000)\n  PyObject *inst = 0;\n  PyObject *newraw = data->newraw;\n  if (newraw) {\n    inst = PyObject_Call(newraw, data->newargs, NULL);\n    if (inst) {\n#if !defined(SWIG_PYTHON_SLOW_GETSET_THIS)\n      PyObject **dictptr = _PyObject_GetDictPtr(inst);\n      if (dictptr != NULL) {\n\tPyObject *dict = *dictptr;\n\tif (dict == NULL) {\n\t  dict = PyDict_New();\n\t  *dictptr = dict;\n\t  PyDict_SetItem(dict, SWIG_This(), swig_this);\n\t}\n      }\n#else\n      PyObject *key = SWIG_This();\n      PyObject_SetAttr(inst, key, swig_this);\n#endif\n    }\n  } else {\n    PyObject *dict = PyDict_New();\n    PyDict_SetItem(dict, SWIG_This(), swig_this);\n    inst = PyInstance_NewRaw(data->newargs, dict);\n    Py_DECREF(dict);\n  }\n  return inst;\n#else\n#if (PY_VERSION_HEX >= 0x02010000)\n  PyObject *inst;\n  PyObject *dict = PyDict_New();\n  PyDict_SetItem(dict, SWIG_This(), swig_this);\n  inst = PyInstance_NewRaw(data->newargs, dict);\n  Py_DECREF(dict);\n  return (PyObject *) inst;\n#else\n  PyInstanceObject *inst = PyObject_NEW(PyInstanceObject, &PyInstance_Type);\n  if (inst == NULL) {\n    return NULL;\n  }\n  inst->in_class = (PyClassObject *)data->newargs;\n  Py_INCREF(inst->in_class);\n  inst->in_dict = PyDict_New();\n  if (inst->in_dict == NULL) {\n    Py_DECREF(inst);\n    return NULL;\n  }\n#ifdef Py_TPFLAGS_HAVE_WEAKREFS\n  inst->in_weakreflist = NULL;\n#endif\n#ifdef Py_TPFLAGS_GC\n  PyObject_GC_Init(inst);\n#endif\n  PyDict_SetItem(inst->in_dict, SWIG_This(), swig_this);\n  return (PyObject *) inst;\n#endif\n#endif\n}\n\nSWIGRUNTIME void\nSWIG_Python_SetSwigThis(PyObject *inst, PyObject *swig_this)\n{\n PyObject *dict;\n#if (PY_VERSION_HEX >= 0x02020000) && !defined(SWIG_PYTHON_SLOW_GETSET_THIS)\n PyObject **dictptr = _PyObject_GetDictPtr(inst);\n if (dictptr != NULL) {\n   dict = *dictptr;\n   if (dict == NULL) {\n     dict = PyDict_New();\n     *dictptr = dict;\n   }\n   PyDict_SetItem(dict, SWIG_This(), swig_this);\n   return;\n }\n#endif\n dict = PyObject_GetAttrString(inst, (char*)\"__dict__\");\n PyDict_SetItem(dict, SWIG_This(), swig_this);\n Py_DECREF(dict);\n} \n\n\nSWIGINTERN PyObject *\nSWIG_Python_InitShadowInstance(PyObject *args) {\n  PyObject *obj[2];\n  if (!SWIG_Python_UnpackTuple(args,(char*)\"swiginit\", 2, 2, obj)) {\n    return NULL;\n  } else {\n    PySwigObject *sthis = SWIG_Python_GetSwigThis(obj[0]);\n    if (sthis) {\n      PySwigObject_append((PyObject*) sthis, obj[1]);\n    } else {\n      SWIG_Python_SetSwigThis(obj[0], obj[1]);\n    }\n    return SWIG_Py_Void();\n  }\n}\n\n/* Create a new pointer object */\n\nSWIGRUNTIME PyObject *\nSWIG_Python_NewPointerObj(void *ptr, swig_type_info *type, int flags) {\n  if (!ptr) {\n    return SWIG_Py_Void();\n  } else {\n    int own = (flags & SWIG_POINTER_OWN) ? SWIG_POINTER_OWN : 0;\n    PyObject *robj = PySwigObject_New(ptr, type, own);\n    PySwigClientData *clientdata = type ? (PySwigClientData *)(type->clientdata) : 0;\n    if (clientdata && !(flags & SWIG_POINTER_NOSHADOW)) {\n      PyObject *inst = SWIG_Python_NewShadowInstance(clientdata, robj);\n      if (inst) {\n\tPy_DECREF(robj);\n\trobj = inst;\n      }\n    }\n    return robj;\n  }\n}\n\n/* Create a new packed object */\n\nSWIGRUNTIMEINLINE PyObject *\nSWIG_Python_NewPackedObj(void *ptr, size_t sz, swig_type_info *type) {\n  return ptr ? PySwigPacked_New((void *) ptr, sz, type) : SWIG_Py_Void();\n}\n\n/* -----------------------------------------------------------------------------*\n *  Get type list \n * -----------------------------------------------------------------------------*/\n\n#ifdef SWIG_LINK_RUNTIME\nvoid *SWIG_ReturnGlobalTypeList(void *);\n#endif\n\nSWIGRUNTIME swig_module_info *\nSWIG_Python_GetModule(void) {\n  static void *type_pointer = (void *)0;\n  /* first check if module already created */\n  if (!type_pointer) {\n#ifdef SWIG_LINK_RUNTIME\n    type_pointer = SWIG_ReturnGlobalTypeList((void *)0);\n#else\n    type_pointer = PyCObject_Import((char*)\"swig_runtime_data\" SWIG_RUNTIME_VERSION,\n\t\t\t\t    (char*)\"type_pointer\" SWIG_TYPE_TABLE_NAME);\n    if (PyErr_Occurred()) {\n      PyErr_Clear();\n      type_pointer = (void *)0;\n    }\n#endif\n  }\n  return (swig_module_info *) type_pointer;\n}\n\n#if PY_MAJOR_VERSION < 2\n/* PyModule_AddObject function was introduced in Python 2.0.  The following function\n   is copied out of Python/modsupport.c in python version 2.3.4 */\nSWIGINTERN int\nPyModule_AddObject(PyObject *m, char *name, PyObject *o)\n{\n  PyObject *dict;\n  if (!PyModule_Check(m)) {\n    PyErr_SetString(PyExc_TypeError,\n\t\t    \"PyModule_AddObject() needs module as first arg\");\n    return SWIG_ERROR;\n  }\n  if (!o) {\n    PyErr_SetString(PyExc_TypeError,\n\t\t    \"PyModule_AddObject() needs non-NULL value\");\n    return SWIG_ERROR;\n  }\n  \n  dict = PyModule_GetDict(m);\n  if (dict == NULL) {\n    /* Internal error -- modules must have a dict! */\n    PyErr_Format(PyExc_SystemError, \"module '%s' has no __dict__\",\n\t\t PyModule_GetName(m));\n    return SWIG_ERROR;\n  }\n  if (PyDict_SetItemString(dict, name, o))\n    return SWIG_ERROR;\n  Py_DECREF(o);\n  return SWIG_OK;\n}\n#endif\n\nSWIGRUNTIME void\nSWIG_Python_DestroyModule(void *vptr)\n{\n  swig_module_info *swig_module = (swig_module_info *) vptr;\n  swig_type_info **types = swig_module->types;\n  size_t i;\n  for (i =0; i < swig_module->size; ++i) {\n    swig_type_info *ty = types[i];\n    if (ty->owndata) {\n      PySwigClientData *data = (PySwigClientData *) ty->clientdata;\n      if (data) PySwigClientData_Del(data);\n    }\n  }\n  Py_DECREF(SWIG_This());\n}\n\nSWIGRUNTIME void\nSWIG_Python_SetModule(swig_module_info *swig_module) {\n  static PyMethodDef swig_empty_runtime_method_table[] = { {NULL, NULL, 0, NULL} };/* Sentinel */\n\n  PyObject *module = Py_InitModule((char*)\"swig_runtime_data\" SWIG_RUNTIME_VERSION,\n\t\t\t\t   swig_empty_runtime_method_table);\n  PyObject *pointer = PyCObject_FromVoidPtr((void *) swig_module, SWIG_Python_DestroyModule);\n  if (pointer && module) {\n    PyModule_AddObject(module, (char*)\"type_pointer\" SWIG_TYPE_TABLE_NAME, pointer);\n  } else {\n    Py_XDECREF(pointer);\n  }\n}\n\n/* The python cached type query */\nSWIGRUNTIME PyObject *\nSWIG_Python_TypeCache(void) {\n  static PyObject *SWIG_STATIC_POINTER(cache) = PyDict_New();\n  return cache;\n}\n\nSWIGRUNTIME swig_type_info *\nSWIG_Python_TypeQuery(const char *type)\n{\n  PyObject *cache = SWIG_Python_TypeCache();\n  PyObject *key = PyString_FromString(type); \n  PyObject *obj = PyDict_GetItem(cache, key);\n  swig_type_info *descriptor;\n  if (obj) {\n    descriptor = (swig_type_info *) PyCObject_AsVoidPtr(obj);\n  } else {\n    swig_module_info *swig_module = SWIG_Python_GetModule();\n    descriptor = SWIG_TypeQueryModule(swig_module, swig_module, type);\n    if (descriptor) {\n      obj = PyCObject_FromVoidPtr(descriptor, NULL);\n      PyDict_SetItem(cache, key, obj);\n      Py_DECREF(obj);\n    }\n  }\n  Py_DECREF(key);\n  return descriptor;\n}\n\n/* \n   For backward compatibility only\n*/\n#define SWIG_POINTER_EXCEPTION  0\n#define SWIG_arg_fail(arg)      SWIG_Python_ArgFail(arg)\n#define SWIG_MustGetPtr(p, type, argnum, flags)  SWIG_Python_MustGetPtr(p, type, argnum, flags)\n\nSWIGRUNTIME int\nSWIG_Python_AddErrMesg(const char* mesg, int infront)\n{\n  if (PyErr_Occurred()) {\n    PyObject *type = 0;\n    PyObject *value = 0;\n    PyObject *traceback = 0;\n    PyErr_Fetch(&type, &value, &traceback);\n    if (value) {\n      PyObject *old_str = PyObject_Str(value);\n      Py_XINCREF(type);\n      PyErr_Clear();\n      if (infront) {\n\tPyErr_Format(type, \"%s %s\", mesg, PyString_AsString(old_str));\n      } else {\n\tPyErr_Format(type, \"%s %s\", PyString_AsString(old_str), mesg);\n      }\n      Py_DECREF(old_str);\n    }\n    return 1;\n  } else {\n    return 0;\n  }\n}\n  \nSWIGRUNTIME int\nSWIG_Python_ArgFail(int argnum)\n{\n  if (PyErr_Occurred()) {\n    /* add information about failing argument */\n    char mesg[256];\n    PyOS_snprintf(mesg, sizeof(mesg), \"argument number %d:\", argnum);\n    return SWIG_Python_AddErrMesg(mesg, 1);\n  } else {\n    return 0;\n  }\n}\n\nSWIGRUNTIMEINLINE const char *\nPySwigObject_GetDesc(PyObject *self)\n{\n  PySwigObject *v = (PySwigObject *)self;\n  swig_type_info *ty = v ? v->ty : 0;\n  return ty ? ty->str : (char*)\"\";\n}\n\nSWIGRUNTIME void\nSWIG_Python_TypeError(const char *type, PyObject *obj)\n{\n  if (type) {\n#if defined(SWIG_COBJECT_TYPES)\n    if (obj && PySwigObject_Check(obj)) {\n      const char *otype = (const char *) PySwigObject_GetDesc(obj);\n      if (otype) {\n\tPyErr_Format(PyExc_TypeError, \"a '%s' is expected, 'PySwigObject(%s)' is received\",\n\t\t     type, otype);\n\treturn;\n      }\n    } else \n#endif      \n    {\n      const char *otype = (obj ? obj->ob_type->tp_name : 0); \n      if (otype) {\n\tPyObject *str = PyObject_Str(obj);\n\tconst char *cstr = str ? PyString_AsString(str) : 0;\n\tif (cstr) {\n\t  PyErr_Format(PyExc_TypeError, \"a '%s' is expected, '%s(%s)' is received\",\n\t\t       type, otype, cstr);\n\t} else {\n\t  PyErr_Format(PyExc_TypeError, \"a '%s' is expected, '%s' is received\",\n\t\t       type, otype);\n\t}\n\tPy_XDECREF(str);\n\treturn;\n      }\n    }   \n    PyErr_Format(PyExc_TypeError, \"a '%s' is expected\", type);\n  } else {\n    PyErr_Format(PyExc_TypeError, \"unexpected type is received\");\n  }\n}\n\n\n/* Convert a pointer value, signal an exception on a type mismatch */\nSWIGRUNTIME void *\nSWIG_Python_MustGetPtr(PyObject *obj, swig_type_info *ty, int argnum, int flags) {\n  void *result;\n  if (SWIG_Python_ConvertPtr(obj, &result, ty, flags) == -1) {\n    PyErr_Clear();\n    if (flags & SWIG_POINTER_EXCEPTION) {\n      SWIG_Python_TypeError(SWIG_TypePrettyName(ty), obj);\n      SWIG_Python_ArgFail(argnum);\n    }\n  }\n  return result;\n}\n\n\n#ifdef __cplusplus\n#if 0\n{ /* cc-mode */\n#endif\n}\n#endif\n\n\n\n#define SWIG_exception_fail(code, msg) do { SWIG_Error(code, msg); SWIG_fail; } while(0) \n\n#define SWIG_contract_assert(expr, msg) if (!(expr)) { SWIG_Error(SWIG_RuntimeError, msg); SWIG_fail; } else \n\n\n\n  #define SWIG_exception(code, msg) do { SWIG_Error(code, msg); SWIG_fail;; } while(0) \n\n\n/* -------- TYPES TABLE (BEGIN) -------- */\n\n#define SWIGTYPE_p_FILE swig_types[0]\n#define SWIGTYPE_p_char swig_types[1]\n#define SWIGTYPE_p_double swig_types[2]\n#define SWIGTYPE_p_gsl_cheb_series swig_types[3]\n#define SWIGTYPE_p_gsl_function swig_types[4]\n#define SWIGTYPE_p_gsl_function_fdf swig_types[5]\n#define SWIGTYPE_p_gsl_integration_qawo_table swig_types[6]\n#define SWIGTYPE_p_gsl_integration_qaws_table swig_types[7]\n#define SWIGTYPE_p_gsl_integration_workspace swig_types[8]\n#define SWIGTYPE_p_gsl_matrix swig_types[9]\n#define SWIGTYPE_p_gsl_min_fminimizer swig_types[10]\n#define SWIGTYPE_p_gsl_min_fminimizer_type swig_types[11]\n#define SWIGTYPE_p_gsl_monte_function swig_types[12]\n#define SWIGTYPE_p_gsl_monte_miser_state swig_types[13]\n#define SWIGTYPE_p_gsl_monte_plain_state swig_types[14]\n#define SWIGTYPE_p_gsl_monte_vegas_state swig_types[15]\n#define SWIGTYPE_p_gsl_multifit_fdfsolver swig_types[16]\n#define SWIGTYPE_p_gsl_multifit_fdfsolver_type swig_types[17]\n#define SWIGTYPE_p_gsl_multifit_fsolver swig_types[18]\n#define SWIGTYPE_p_gsl_multifit_fsolver_type swig_types[19]\n#define SWIGTYPE_p_gsl_multifit_function swig_types[20]\n#define SWIGTYPE_p_gsl_multifit_function_fdf swig_types[21]\n#define SWIGTYPE_p_gsl_multifit_linear_workspace swig_types[22]\n#define SWIGTYPE_p_gsl_multimin_fdfminimizer swig_types[23]\n#define SWIGTYPE_p_gsl_multimin_fdfminimizer_type swig_types[24]\n#define SWIGTYPE_p_gsl_multimin_fminimizer swig_types[25]\n#define SWIGTYPE_p_gsl_multimin_fminimizer_type swig_types[26]\n#define SWIGTYPE_p_gsl_multimin_function swig_types[27]\n#define SWIGTYPE_p_gsl_multimin_function_fdf swig_types[28]\n#define SWIGTYPE_p_gsl_multiroot_fdfsolver swig_types[29]\n#define SWIGTYPE_p_gsl_multiroot_fdfsolver_type swig_types[30]\n#define SWIGTYPE_p_gsl_multiroot_fsolver swig_types[31]\n#define SWIGTYPE_p_gsl_multiroot_fsolver_type swig_types[32]\n#define SWIGTYPE_p_gsl_multiroot_function swig_types[33]\n#define SWIGTYPE_p_gsl_multiroot_function_fdf swig_types[34]\n#define SWIGTYPE_p_gsl_odeiv_control swig_types[35]\n#define SWIGTYPE_p_gsl_odeiv_control_type swig_types[36]\n#define SWIGTYPE_p_gsl_odeiv_evolve swig_types[37]\n#define SWIGTYPE_p_gsl_odeiv_step swig_types[38]\n#define SWIGTYPE_p_gsl_odeiv_step_type swig_types[39]\n#define SWIGTYPE_p_gsl_rng swig_types[40]\n#define SWIGTYPE_p_gsl_root_fdfsolver swig_types[41]\n#define SWIGTYPE_p_gsl_root_fdfsolver_type swig_types[42]\n#define SWIGTYPE_p_gsl_root_fsolver swig_types[43]\n#define SWIGTYPE_p_gsl_root_fsolver_type swig_types[44]\n#define SWIGTYPE_p_gsl_vector swig_types[45]\n#define SWIGTYPE_p_unsigned_int swig_types[46]\nstatic swig_type_info *swig_types[48];\nstatic swig_module_info swig_module = {swig_types, 47, 0, 0, 0, 0};\n#define SWIG_TypeQuery(name) SWIG_TypeQueryModule(&swig_module, &swig_module, name)\n#define SWIG_MangledTypeQuery(name) SWIG_MangledTypeQueryModule(&swig_module, &swig_module, name)\n\n/* -------- TYPES TABLE (END) -------- */\n\n#if (PY_VERSION_HEX <= 0x02000000)\n# if !defined(SWIG_PYTHON_CLASSIC)\n#  error \"This python version requires swig to be run with the '-classic' option\"\n# endif\n#endif\n\n/*-----------------------------------------------\n              @(target):= __callback.so\n  ------------------------------------------------*/\n#define SWIG_init    init__callback\n\n#define SWIG_name    \"__callback\"\n\n#define SWIGVERSION 0x010336 \n#define SWIG_VERSION SWIGVERSION\n\n\n#define SWIG_as_voidptr(a) (void *)((const void *)(a)) \n#define SWIG_as_voidptrptr(a) ((void)SWIG_as_voidptr(*a),(void**)(a)) \n\n\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_errno.h>\n#include <assert.h>\n#include <float.h>\n#include <setjmp.h>\n#include <pygsl/utils.h>\n#include <pygsl/function_helpers.h>\n\n\n#define  PyGSL_gsl_function_GET_PARAMS(sys) \\\n         (sys)->params\n#define  PyGSL_gsl_function_fdf_GET_PARAMS(sys) \\\n         (sys)->params\n\n   \n#include <pygsl/utils.h>\n#include <pygsl/error_helpers.h>\ntypedef int gsl_error_flag;\ntypedef int gsl_error_flag_drop;\nPyObject *pygsl_module_for_error_treatment = NULL;\n                        \n\n\n#include <pygsl/utils.h>\n#include <pygsl/block_helpers.h>\n#include <typemaps/block_conversion_functions.h>\n#include <string.h>\n#include <assert.h>\n\n\n#include <pygsl/error_helpers.h>\n#include \"function_helpers.c\"\n#include \"chars.c\"   \n\n\n  gsl_function * gsl_function_init(gsl_function * STORE)\n  {\n    return STORE;\n    /* Do Not need to do anything here. All done in the typemaps */\n  }\n  gsl_function_fdf * gsl_function_init_fdf(gsl_function_fdf * STORE)\n  {\n    return STORE;\n    /* Do Not need to do anything here. All done in the typemaps */\n  }\n\n  void gsl_function_free(gsl_function * FREE)\n  {\n    /* Do Not need to do anything here. All done in the typemaps */\n  }\n  void gsl_function_free_fdf(gsl_function_fdf * FREE)\n  {\n    /* Do Not need to do anything here. All done in the typemaps */\n  }\n\n\n\n#include <gsl/gsl_monte.h>\n#include <gsl/gsl_monte_plain.h>\n#include <gsl/gsl_monte_miser.h>\n#include <gsl/gsl_monte_vegas.h>\n\n\n#include <pygsl/block_helpers.h>\n#include <gsl/gsl_interp.h>\n#include <gsl/gsl_spline.h>\n#include <stdio.h>\n\n\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_rng.h>\n#include <pygsl/rng.h>\n#include <pygsl/rng_helpers.h>\n\n\n  /*\n   * Normally Microsofts (R) Visual C (TM) Compiler is used to compile python \n   * on windows.\n   * When I used MinGW to compile I could not convert Python File Objects to \n   * C File Structs (The function PyFile_AsFile generated a core). Therefore \n   * I raise a python exception if someone tries to use this Code when it was \n   * compiled with MinGW. Do you know a better solution? Perhaps how to get it \n   * work?\n   */\n#ifdef __MINGW32__\n#define HANDLE_MINGW() \\\n  do { \\\n  PyGSL_add_traceback(NULL, __FILE__, __FUNCTION__, __LINE__); \\\n  PyErr_SetString(PyExc_TypeError, \"This Module was compiled using MinGW32. \" \\\n\t\t  \"Conversion of python files to C files is not supported.\");\\\n  goto fail; \\\n  } while(0)\n#else\n#define HANDLE_MINGW()\n#endif   \n\n\n#define PyGSL_gsl_monte_function_GET_PARAMS(sys)   \\\n        (sys)->params;\n\n\n  gsl_monte_function * gsl_monte_function_init(gsl_monte_function * STORE)\n  {\n       FUNC_MESS(\"BEGIN\");\n       assert(STORE);\n       FUNC_MESS(\"END\");\n       return STORE;\n  }\n  void gsl_monte_function_free(gsl_monte_function * FREE)\n  {\n       ;\n  }\n\n\nSWIGINTERN int\nSWIG_AsVal_double (PyObject *obj, double *val)\n{\n  int res = SWIG_TypeError;\n  if (PyFloat_Check(obj)) {\n    if (val) *val = PyFloat_AsDouble(obj);\n    return SWIG_OK;\n  } else if (PyInt_Check(obj)) {\n    if (val) *val = PyInt_AsLong(obj);\n    return SWIG_OK;\n  } else if (PyLong_Check(obj)) {\n    double v = PyLong_AsDouble(obj);\n    if (!PyErr_Occurred()) {\n      if (val) *val = v;\n      return SWIG_OK;\n    } else {\n      PyErr_Clear();\n    }\n  }\n#ifdef SWIG_PYTHON_CAST_MODE\n  {\n    int dispatch = 0;\n    double d = PyFloat_AsDouble(obj);\n    if (!PyErr_Occurred()) {\n      if (val) *val = d;\n      return SWIG_AddCast(SWIG_OK);\n    } else {\n      PyErr_Clear();\n    }\n    if (!dispatch) {\n      long v = PyLong_AsLong(obj);\n      if (!PyErr_Occurred()) {\n\tif (val) *val = v;\n\treturn SWIG_AddCast(SWIG_AddCast(SWIG_OK));\n      } else {\n\tPyErr_Clear();\n      }\n    }\n  }\n#endif\n  return res;\n}\n\n\n#include <float.h>\n\n\n#include <math.h>\n\n\nSWIGINTERNINLINE int\nSWIG_CanCastAsInteger(double *d, double min, double max) {\n  double x = *d;\n  if ((min <= x && x <= max)) {\n   double fx = floor(x);\n   double cx = ceil(x);\n   double rd =  ((x - fx) < 0.5) ? fx : cx; /* simple rint */\n   if ((errno == EDOM) || (errno == ERANGE)) {\n     errno = 0;\n   } else {\n     double summ, reps, diff;\n     if (rd < x) {\n       diff = x - rd;\n     } else if (rd > x) {\n       diff = rd - x;\n     } else {\n       return 1;\n     }\n     summ = rd + x;\n     reps = diff/summ;\n     if (reps < 8*DBL_EPSILON) {\n       *d = rd;\n       return 1;\n     }\n   }\n  }\n  return 0;\n}\n\n\nSWIGINTERN int\nSWIG_AsVal_unsigned_SS_long (PyObject *obj, unsigned long *val) \n{\n  if (PyInt_Check(obj)) {\n    long v = PyInt_AsLong(obj);\n    if (v >= 0) {\n      if (val) *val = v;\n      return SWIG_OK;\n    } else {\n      return SWIG_OverflowError;\n    }\n  } else if (PyLong_Check(obj)) {\n    unsigned long v = PyLong_AsUnsignedLong(obj);\n    if (!PyErr_Occurred()) {\n      if (val) *val = v;\n      return SWIG_OK;\n    } else {\n      PyErr_Clear();\n    }\n  }\n#ifdef SWIG_PYTHON_CAST_MODE\n  {\n    int dispatch = 0;\n    unsigned long v = PyLong_AsUnsignedLong(obj);\n    if (!PyErr_Occurred()) {\n      if (val) *val = v;\n      return SWIG_AddCast(SWIG_OK);\n    } else {\n      PyErr_Clear();\n    }\n    if (!dispatch) {\n      double d;\n      int res = SWIG_AddCast(SWIG_AsVal_double (obj,&d));\n      if (SWIG_IsOK(res) && SWIG_CanCastAsInteger(&d, 0, ULONG_MAX)) {\n\tif (val) *val = (unsigned long)(d);\n\treturn res;\n      }\n    }\n  }\n#endif\n  return SWIG_TypeError;\n}\n\n\nSWIGINTERNINLINE int\nSWIG_AsVal_size_t (PyObject * obj, size_t *val)\n{\n  unsigned long v;\n  int res = SWIG_AsVal_unsigned_SS_long (obj, val ? &v : 0);\n  if (SWIG_IsOK(res) && val) *val = (size_t)(v);\n  return res;\n}\n\n\n  #define SWIG_From_double   PyFloat_FromDouble \n\n\n     size_t\n\t  pygsl_monte_miser_get_min_calls(gsl_monte_miser_state * s){\n\t  return s->min_calls;\n     }\n     size_t\n\t  pygsl_monte_miser_get_min_calls_per_bisection(gsl_monte_miser_state * s){\n\t  return s->min_calls_per_bisection;\n     }\n     double\n\t  pygsl_monte_miser_get_dither(gsl_monte_miser_state * s){\n\t  return s->dither;\n     }\n     double\n\t  pygsl_monte_miser_get_estimate_frac(gsl_monte_miser_state * s){\n\t  return s->estimate_frac;\n     }\n     double\n\t  pygsl_monte_miser_get_alpha(gsl_monte_miser_state * s){\n\t  return s->alpha;\n     }\n\n     void\n\t  pygsl_monte_miser_set_min_calls(gsl_monte_miser_state * s, int NONNEGATIVE){\n\t   s->min_calls = (size_t) NONNEGATIVE;\n     }\n     void\n\t  pygsl_monte_miser_set_min_calls_per_bisection(gsl_monte_miser_state * s, int NONNEGATIVE){\n\t   s->min_calls_per_bisection = (size_t) NONNEGATIVE;\n     }\n     void\n\t  pygsl_monte_miser_set_dither(gsl_monte_miser_state * s, double d){\n\t   s->dither = d;\n     }\n     void\n\t  pygsl_monte_miser_set_estimate_frac(gsl_monte_miser_state * s, double e){\n\t   s->estimate_frac = e;\n     }\n     void\n\t  pygsl_monte_miser_set_alpha(gsl_monte_miser_state * s, double alpha){\n\t   s->alpha = alpha;\n     }\n\n\n  #define SWIG_From_long   PyInt_FromLong \n\n\nSWIGINTERNINLINE PyObject* \nSWIG_From_unsigned_SS_long  (unsigned long value)\n{\n  return (value > LONG_MAX) ?\n    PyLong_FromUnsignedLong(value) : PyInt_FromLong((long)(value)); \n}\n\n\nSWIGINTERNINLINE PyObject *\nSWIG_From_size_t  (size_t value)\n{    \n  return SWIG_From_unsigned_SS_long  ((unsigned long)(value));\n}\n\n\n#include <limits.h>\n#if !defined(SWIG_NO_LLONG_MAX)\n# if !defined(LLONG_MAX) && defined(__GNUC__) && defined (__LONG_LONG_MAX__)\n#   define LLONG_MAX __LONG_LONG_MAX__\n#   define LLONG_MIN (-LLONG_MAX - 1LL)\n#   define ULLONG_MAX (LLONG_MAX * 2ULL + 1ULL)\n# endif\n#endif\n\n\nSWIGINTERN int\nSWIG_AsVal_long (PyObject *obj, long* val)\n{\n  if (PyInt_Check(obj)) {\n    if (val) *val = PyInt_AsLong(obj);\n    return SWIG_OK;\n  } else if (PyLong_Check(obj)) {\n    long v = PyLong_AsLong(obj);\n    if (!PyErr_Occurred()) {\n      if (val) *val = v;\n      return SWIG_OK;\n    } else {\n      PyErr_Clear();\n    }\n  }\n#ifdef SWIG_PYTHON_CAST_MODE\n  {\n    int dispatch = 0;\n    long v = PyInt_AsLong(obj);\n    if (!PyErr_Occurred()) {\n      if (val) *val = v;\n      return SWIG_AddCast(SWIG_OK);\n    } else {\n      PyErr_Clear();\n    }\n    if (!dispatch) {\n      double d;\n      int res = SWIG_AddCast(SWIG_AsVal_double (obj,&d));\n      if (SWIG_IsOK(res) && SWIG_CanCastAsInteger(&d, LONG_MIN, LONG_MAX)) {\n\tif (val) *val = (long)(d);\n\treturn res;\n      }\n    }\n  }\n#endif\n  return SWIG_TypeError;\n}\n\n\nSWIGINTERN int\nSWIG_AsVal_int (PyObject * obj, int *val)\n{\n  long v;\n  int res = SWIG_AsVal_long (obj, &v);\n  if (SWIG_IsOK(res)) {\n    if ((v < INT_MIN || v > INT_MAX)) {\n      return SWIG_OverflowError;\n    } else {\n      if (val) *val = (int)(v);\n    }\n  }  \n  return res;\n}\n\n\nSWIGINTERNINLINE PyObject *\nSWIG_From_int  (int value)\n{    \n  return SWIG_From_long  (value);\n}\n\n\n     double pygsl_monte_vegas_get_result(gsl_monte_vegas_state *s){return     s->result    ;}\n     double pygsl_monte_vegas_get_sigma(gsl_monte_vegas_state *s){return      s->sigma     ;}\n     double pygsl_monte_vegas_get_chisq(gsl_monte_vegas_state *s){return      s->chisq     ;}     \n     double pygsl_monte_vegas_get_alpha(gsl_monte_vegas_state *s){return      s->alpha     ;}\n     size_t pygsl_monte_vegas_get_iterations(gsl_monte_vegas_state *s){return s->iterations;}\n     int    pygsl_monte_vegas_get_stage(gsl_monte_vegas_state *s){return      s->stage     ;}\n     int    pygsl_monte_vegas_get_mode(gsl_monte_vegas_state *s){return       s->mode      ;}\n     int    pygsl_monte_vegas_get_verbose(gsl_monte_vegas_state *s){return    s->verbose   ;}\n     FILE * pygsl_monte_vegas_get_ostream(gsl_monte_vegas_state *s){return    s->ostream   ;}\n\n     void pygsl_monte_vegas_set_result(gsl_monte_vegas_state *s    , double v){      s->result     = v;}\n     void pygsl_monte_vegas_set_sigma(gsl_monte_vegas_state *s     , double v){      s->sigma      = v;}\n     void pygsl_monte_vegas_set_chisq(gsl_monte_vegas_state *s     , double v){      s->chisq      = v;}     \n     void pygsl_monte_vegas_set_alpha(gsl_monte_vegas_state *s     , double v){      s->alpha      = v;}\n     void pygsl_monte_vegas_set_iterations(gsl_monte_vegas_state *s, int  NONNEGATIVE){      s->iterations = (size_t) NONNEGATIVE;}\n     void pygsl_monte_vegas_set_stage(gsl_monte_vegas_state *s     , int    NONNEGATIVE){      s->stage      = NONNEGATIVE;}\n     void pygsl_monte_vegas_set_mode(gsl_monte_vegas_state *s      , int    v){      s->mode       = v;}\n     void pygsl_monte_vegas_set_verbose(gsl_monte_vegas_state *s   , int    v){      s->verbose    = v;}\n     void pygsl_monte_vegas_set_ostream(gsl_monte_vegas_state *s   , FILE * v){      s->ostream    = v;}\n\n\n\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_roots.h>\n\n\n#define PyGSL_gsl_root_fsolver_GET_PARAMS(sys)   \\\n        (sys)->function->params\n\n#define PyGSL_gsl_root_fdfsolver_GET_PARAMS(sys)   \\\n        (sys)->fdf->params\n\n\nSWIGINTERN swig_type_info*\nSWIG_pchar_descriptor(void)\n{\n  static int init = 0;\n  static swig_type_info* info = 0;\n  if (!init) {\n    info = SWIG_TypeQuery(\"_p_char\");\n    init = 1;\n  }\n  return info;\n}\n\n\nSWIGINTERNINLINE PyObject *\nSWIG_FromCharPtrAndSize(const char* carray, size_t size)\n{\n  if (carray) {\n    if (size > INT_MAX) {\n      swig_type_info* pchar_descriptor = SWIG_pchar_descriptor();\n      return pchar_descriptor ? \n\tSWIG_NewPointerObj((char *)(carray), pchar_descriptor, 0) : SWIG_Py_Void();\n    } else {\n      return PyString_FromStringAndSize(carray, (int)(size));\n    }\n  } else {\n    return SWIG_Py_Void();\n  }\n}\n\n\nSWIGINTERNINLINE PyObject * \nSWIG_FromCharPtr(const char *cptr)\n{ \n  return SWIG_FromCharPtrAndSize(cptr, (cptr ? strlen(cptr) : 0));\n}\n\n\n#include <gsl/gsl_min.h>\n\n\n#define PyGSL_gsl_min_fminimizer_GET_PARAMS(sys)   \\\n        (sys)->function->params\n\n\n#include <gsl/gsl_multiroots.h>\n\n\n  gsl_multiroot_function * gsl_multiroot_function_init(gsl_multiroot_function * STORE)\n  {\n    return STORE;\n    /* Do Not need to do anything here. All done in the typemaps */\n  }\n  gsl_multiroot_function_fdf * gsl_multiroot_function_init_fdf(gsl_multiroot_function_fdf * STORE)\n  {\n    return STORE;\n    /* Do Not need to do anything here. All done in the typemaps */\n  }\n  typedef gsl_vector gsl_multiroot_solver_data;\n  gsl_multiroot_solver_data * gsl_multiroot_function_getf(gsl_multiroot_fsolver * s)\n  {\n    return s->f;\n  }\n  gsl_multiroot_solver_data * gsl_multiroot_function_fdf_getf(gsl_multiroot_fdfsolver * s)\n  {\n    return s->f;\n  }\n  gsl_multiroot_solver_data * gsl_multiroot_function_getx(gsl_multiroot_fsolver * s)\n  {\n    return s->x;\n  }\n  gsl_multiroot_solver_data * gsl_multiroot_function_fdf_getx(gsl_multiroot_fdfsolver * s)\n  {\n    return s->x;\n  }\n  \n  void gsl_multiroot_function_free(gsl_multiroot_function * FREE)\n  {\n    /* Do Not need to do anything here. All done in the typemaps */\n  }\n  void gsl_multiroot_function_free_fdf(gsl_multiroot_function_fdf * FREE)\n  {\n    /* Do Not need to do anything here. All done in the typemaps */\n  }\n\n\n\n#include <gsl/gsl_multimin.h>\n\n\n#define PyGSL_gsl_multimin_fminimizer_GET_PARAMS(sys)   \\\n        (sys)->f->params;\n#define PyGSL_gsl_multimin_fdfminimizer_GET_PARAMS(sys)   \\\n        (sys)->fdf->params;\n#define  PyGSL_gsl_multimin_function_GET_PARAMS(sys) \\\n         (sys)->params\n#define  PyGSL_gsl_multimin_function_fdf_GET_PARAMS(sys) \\\n         (sys)->params\n\n\n  typedef gsl_vector gsl_multimin_solver_data;\n\n\n  gsl_multimin_function * gsl_multimin_function_init(gsl_multimin_function * STORE)\n  {\n    return STORE;\n  }\n  gsl_multimin_function_fdf * gsl_multimin_function_init_fdf(gsl_multimin_function_fdf * STORE)\n  {\n\t return STORE;\n    /* Do Not need to do anything here. All done in the typemaps */\n  }\n  void gsl_multimin_function_free(gsl_multimin_function * FREE)\n  {\n       ;\n  }\n\n  void gsl_multimin_function_free_fdf(gsl_multimin_function_fdf * FREE)\n  {\n    /* Do Not need to do anything here. All done in the typemaps */\n       ;\n  }\n\n\n  double  gsl_multimin_fminimizer_f(gsl_multimin_fminimizer * s)\n  {\t\n    \treturn s->fval;\n  }\n\n\n  double  gsl_multimin_fdfminimizer_f(gsl_multimin_fdfminimizer * s)\n  {\t\n    \treturn s->f;\n  }\n\n\n\t  /* \n\t   * Try to find what level of GSL I am running. If less than zero, \n\t   * give a NULL. The overlying wrapper must check for NULL and raise \n           * an approbriate error message.\n\t   */\n#include <pygsl/pygsl_features.h>\n#ifdef _PYGSL_GSL_HAS_FMINIMIZER_NMSIMPLEX\n\t  extern const\n\t       gsl_multimin_fminimizer_type *gsl_multimin_fminimizer_nmsimplex;\n#else\n\t  gsl_multimin_fminimizer_type *gsl_multimin_fminimizer_nmsimplex = NULL;\n#endif\n\n\n#include <gsl/gsl_multifit_nlin.h>\n#include \"pygsl_multifit.ic\"\n\n\n  typedef gsl_vector gsl_multifit_solver_vector;\n  typedef gsl_matrix gsl_multifit_solver_matrix;\n\n\n  gsl_multifit_function * gsl_multifit_function_init(gsl_multifit_function * STORE)\n  {\n    return STORE;\n    /* Do Not need to do anything here. All done in the typemaps */\n  }\n  gsl_multifit_function_fdf * gsl_multifit_function_init_fdf(gsl_multifit_function_fdf * STORE)\n  {\n    return STORE;\n    /* Do Not need to do anything here. All done in the typemaps */\n  }\n  gsl_multifit_solver_vector * gsl_multifit_fsolver_getdx(gsl_multifit_fsolver * s)\n  {\n       return s->dx;\n  }\n\n  gsl_multifit_solver_vector * gsl_multifit_fsolver_getx(gsl_multifit_fsolver * s)\n  {\n       return s->x;\n  }\n  gsl_multifit_solver_vector * gsl_multifit_fsolver_getf(gsl_multifit_fsolver * s)\n  {\n       return s->f;\n  }\n  gsl_multifit_solver_vector * gsl_multifit_fdfsolver_getdx(gsl_multifit_fdfsolver * s)\n  {\n       return s->dx;\n  }\n\n  gsl_multifit_solver_vector * gsl_multifit_fdfsolver_getx(gsl_multifit_fdfsolver * s)\n  {\n       return s->x;\n  }\n  gsl_multifit_solver_vector * gsl_multifit_fdfsolver_getf(gsl_multifit_fdfsolver * s)\n  {\n       return s->f;\n  }\n  gsl_multifit_solver_matrix * gsl_multifit_fdfsolver_getJ(gsl_multifit_fdfsolver * s)\n  {\n       return s->J;\n  }\n  void gsl_multifit_function_free(gsl_multifit_function * FREE)\n  {\n    /* Do Not need to do anything here. All done in the typemaps */\n  }\n  void gsl_multifit_function_free_fdf(gsl_multifit_function_fdf * FREE)\n  {\n    /* Do Not need to do anything here. All done in the typemaps */\n  }\n\n\n\n#include <gsl/gsl_integration.h>\n\n\nsize_t \ngsl_integration_workspace_get_size(gsl_integration_workspace * w)\n{\n     return w->size;\n}\n\n\nSWIGINTERNINLINE PyObject *\nSWIG_From_unsigned_SS_int  (unsigned int value)\n{    \n  return SWIG_From_unsigned_SS_long  (value);\n}\n\n\n#include <gsl/gsl_chebyshev.h>\n\n \n     PyObject *\n     pygsl_cheb_get_coefficients(gsl_cheb_series * s){\n\t  gsl_vector_view v;\n\t  v = gsl_vector_view_array(s->c, s->order);\n\t  return (PyObject *) PyGSL_copy_gslvector_to_pyarray(&v.vector);\n    }\n\n\n     int\n     pygsl_cheb_set_coefficients(gsl_cheb_series * s, gsl_vector *coef){\n\t  size_t i, v_size;\n\t  v_size = coef->size;\n\t  if(v_size != s->order){\n\t       PyGSL_ERROR(\"The number of coefficients does not match the specified order.\", GSL_EBADLEN);\n\t       return GSL_EBADLEN;\n\t  }\n\t  for (i=0; i<v_size; i++){\n\t       s->c[i] = gsl_vector_get(coef, i);\n          }\n\t  return GSL_SUCCESS;\n     }\n\n\n \n     double\n\t  pygsl_cheb_get_a(gsl_cheb_series *s){\n\t  return s->a;\n     }\n     double\n\t  pygsl_cheb_get_b(gsl_cheb_series *s){\n\t  return s->b;\n     }\n     void\n\t  pygsl_cheb_set_a(gsl_cheb_series *s, double a){\n\t  s->a = a;\n     }\n     void\n\t  pygsl_cheb_set_b(gsl_cheb_series *s, double b){\n\t  s->b = b;\n     }\n     size_t\n\t  pygsl_cheb_get_order_sp(gsl_cheb_series *s){\n\t  return s->order_sp;\n     }\n     void\n\t  pygsl_cheb_set_order_sp(gsl_cheb_series *s, size_t sp){\n\t  s->order_sp = sp;\n     }\n     double\n\t  pygsl_cheb_get_f(gsl_cheb_series *s){\n\t  return *(s->f);\n     }\n     \n     void\n\t  pygsl_cheb_set_f(gsl_cheb_series *s, double f){\n\t  *(s->f) = f;\n     }\n     \n\n\n\n#include <gsl/gsl_odeiv.h>\n#include <stdlib.h>\n#include <assert.h>\n  /* Some functions needed hand coded wrapper. These are in here. */\n#include <odeiv.ic>\n\n\n#include <gsl/gsl_multifit.h>\n#include <gsl/gsl_fit.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_vector.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\nSWIGINTERN PyObject *_wrap_gsl_function_init(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_function *arg1 = (gsl_function *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"STORE\", NULL \n  };\n  gsl_function *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_function_init\",kwnames,&obj0)) SWIG_fail;\n  {\n    FUNC_MESS(\"gsl_function STORE BEGIN\");\n    arg1 = PyGSL_convert_to_gsl_function (obj0);\n    FUNC_MESS(\"gsl_function STORE END\");\n    if(arg1==NULL) goto fail;\n  }\n  result = (gsl_function *)gsl_function_init(arg1);\n  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_gsl_function, 0 |  0 );\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_function_init_fdf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_function_fdf *arg1 = (gsl_function_fdf *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"STORE\", NULL \n  };\n  gsl_function_fdf *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_function_init_fdf\",kwnames,&obj0)) SWIG_fail;\n  {\n    FUNC_MESS(\"gsl_function STORE BEGIN\");\n    arg1 = PyGSL_convert_to_gsl_function_fdf (obj0);\n    FUNC_MESS(\"gsl_function STORE END\");\n    if(arg1==NULL) goto fail;\n  }\n  result = (gsl_function_fdf *)gsl_function_init_fdf(arg1);\n  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_gsl_function_fdf, 0 |  0 );\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_function_free(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_function *arg1 = (gsl_function *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"FREE\", NULL \n  };\n  \n  \n  gsl_function *_function1 = NULL;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_function_free\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_function, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_function_free\" \"', argument \" \"1\"\" of type '\" \"gsl_function *\"\"'\"); \n  }\n  arg1 = (gsl_function *)(argp1);\n  {\n    DEBUG_MESS(2, \"gsl_function STORE IN ptr @ %p\", arg1);\n    if(arg1==NULL) goto fail;\n    \n    _function1 = arg1;\n  }\n  gsl_function_free(arg1);\n  resultobj = SWIG_Py_Void();\n  {\n    DEBUG_MESS(2, \"gsl_function freeing %p\", _function1);\n    if(_function1){\n      assert(arg1 == _function1);\n      PyGSL_params_free((callback_function_params *) arg1->params);\n      free(arg1);    \n    }\n    _function1 = NULL;\n    DEBUG_MESS(2, \"gsl_function freed %p\", _function1);\n    \n  }\n  return resultobj;\nfail:\n  {\n    DEBUG_MESS(2, \"gsl_function freeing %p\", _function1);\n    if(_function1){\n      assert(arg1 == _function1);\n      PyGSL_params_free((callback_function_params *) arg1->params);\n      free(arg1);    \n    }\n    _function1 = NULL;\n    DEBUG_MESS(2, \"gsl_function freed %p\", _function1);\n    \n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_function_free_fdf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_function_fdf *arg1 = (gsl_function_fdf *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"FREE\", NULL \n  };\n  \n  \n  gsl_function_fdf *_function1 = NULL;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_function_free_fdf\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_function_fdf, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_function_free_fdf\" \"', argument \" \"1\"\" of type '\" \"gsl_function_fdf *\"\"'\"); \n  }\n  arg1 = (gsl_function_fdf *)(argp1);\n  {\n    DEBUG_MESS(2, \"gsl_function STORE IN ptr @ %p\", arg1);\n    if(arg1==NULL) goto fail;\n    \n    _function1 = arg1;\n  }\n  gsl_function_free_fdf(arg1);\n  resultobj = SWIG_Py_Void();\n  {\n    DEBUG_MESS(2, \"gsl_function freeing %p\", _function1);\n    if(_function1){\n      assert(arg1 == _function1);\n      PyGSL_params_free((callback_function_params *) arg1->params);\n      free(arg1);    \n    }\n    _function1 = NULL;\n    DEBUG_MESS(2, \"gsl_function freed %p\", _function1);\n    \n  }\n  return resultobj;\nfail:\n  {\n    DEBUG_MESS(2, \"gsl_function freeing %p\", _function1);\n    if(_function1){\n      assert(arg1 == _function1);\n      PyGSL_params_free((callback_function_params *) arg1->params);\n      free(arg1);    \n    }\n    _function1 = NULL;\n    DEBUG_MESS(2, \"gsl_function freed %p\", _function1);\n    \n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_monte_function_init(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_monte_function *arg1 = (gsl_monte_function *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"STORE\", NULL \n  };\n  gsl_monte_function *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_monte_function_init\",kwnames,&obj0)) SWIG_fail;\n  {\n    FUNC_MESS(\"gsl_function STORE BEGIN\");\n    arg1 = PyGSL_convert_to_gsl_monte_function (obj0);\n    FUNC_MESS(\"gsl_function STORE END\");\n    if(arg1==NULL) goto fail;\n  }\n  result = (gsl_monte_function *)gsl_monte_function_init(arg1);\n  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_gsl_monte_function, 0 |  0 );\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_monte_function_free(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_monte_function *arg1 = (gsl_monte_function *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"FREE\", NULL \n  };\n  \n  \n  gsl_monte_function *_function1 = NULL;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_monte_function_free\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_monte_function, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_monte_function_free\" \"', argument \" \"1\"\" of type '\" \"gsl_monte_function *\"\"'\"); \n  }\n  arg1 = (gsl_monte_function *)(argp1);\n  {\n    DEBUG_MESS(2, \"gsl_function STORE IN ptr @ %p\", arg1);\n    if(arg1==NULL) goto fail;\n    \n    _function1 = arg1;\n  }\n  gsl_monte_function_free(arg1);\n  resultobj = SWIG_Py_Void();\n  {\n    DEBUG_MESS(2, \"gsl_function freeing %p\", _function1);\n    if(_function1){\n      assert(arg1 == _function1);\n      PyGSL_params_free((callback_function_params *) arg1->params);\n      free(arg1);    \n    }\n    _function1 = NULL;\n    DEBUG_MESS(2, \"gsl_function freed %p\", _function1);\n    \n  }\n  return resultobj;\nfail:\n  {\n    DEBUG_MESS(2, \"gsl_function freeing %p\", _function1);\n    if(_function1){\n      assert(arg1 == _function1);\n      PyGSL_params_free((callback_function_params *) arg1->params);\n      free(arg1);    \n    }\n    _function1 = NULL;\n    DEBUG_MESS(2, \"gsl_function freed %p\", _function1);\n    \n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_monte_plain_integrate(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_monte_function *arg1 = (gsl_monte_function *) 0 ;\n  double *arg2 ;\n  double *arg3 ;\n  size_t arg4 ;\n  size_t arg5 ;\n  gsl_rng *arg6 = (gsl_rng *) 0 ;\n  gsl_monte_plain_state *arg7 = (gsl_monte_plain_state *) 0 ;\n  double *arg8 = (double *) 0 ;\n  double *arg9 = (double *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  size_t val5 ;\n  int ecode5 = 0 ;\n  void *argp7 = 0 ;\n  int res7 = 0 ;\n  double temp8 ;\n  int res8 = SWIG_TMPOBJ ;\n  double temp9 ;\n  int res9 = SWIG_TMPOBJ ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  PyObject * obj3 = 0 ;\n  PyObject * obj4 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"BUFFER\",(char *) \"xl\",(char *) \"calls\",(char *) \"r\",(char *) \"state\", NULL \n  };\n  gsl_error_flag_drop result;\n  \n  \n  gsl_monte_function * volatile _solver1 = NULL;\n  \n  \n  PyArrayObject *_PyVector_12 = NULL;\n  PyArrayObject *_PyVector_22 = NULL;\n  \n  arg8 = &temp8;\n  arg9 = &temp9;\n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOOOO:gsl_monte_plain_integrate\",kwnames,&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_monte_function, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_monte_plain_integrate\" \"', argument \" \"1\"\" of type '\" \"gsl_monte_function const *\"\"'\"); \n  }\n  arg1 = (gsl_monte_function *)(argp1);\n  {\n    int mysize = 0;\n    if(!PySequence_Check(obj1)){\n      PyErr_SetString(PyExc_TypeError, \"Expected a sequence of two arrays!\");\n      goto fail;\n    }\n    if(PySequence_Size(obj1) != 2){\n      PyErr_SetString(PyExc_TypeError, \"Expected a sequence of two arrays! Number of sequence arguments did not match!\");\n      goto fail;\n    }\n    _PyVector_12 = PyGSL_vector_check(PySequence_GetItem(obj1, 0), -1, PyGSL_DARRAY_CINPUT(2), NULL, NULL);\n    if (_PyVector_12 == NULL)\n    goto fail;\n    \n    mysize = _PyVector_12->dimensions[0];\n    \n    _PyVector_22 = PyGSL_vector_check(PySequence_GetItem(obj1, 1), mysize, PyGSL_DARRAY_CINPUT(2+1), NULL, NULL);\n    if (_PyVector_22 == NULL)\n    goto fail;\n    \n    arg2 = (double *)(_PyVector_12->data);\n    arg3 = (double *)(_PyVector_22->data);\n    arg4 = (size_t) mysize;\n    \n  }\n  ecode5 = SWIG_AsVal_size_t(obj2, &val5);\n  if (!SWIG_IsOK(ecode5)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode5), \"in method '\" \"gsl_monte_plain_integrate\" \"', argument \" \"5\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg5 = (size_t)(val5);\n  {\n    arg6= (gsl_rng*) PyGSL_gsl_rng_from_pyobject(obj3);     \n    if(arg6 == NULL)\n    goto fail;\n  }\n  res7 = SWIG_ConvertPtr(obj4, &argp7,SWIGTYPE_p_gsl_monte_plain_state, 0 |  0 );\n  if (!SWIG_IsOK(res7)) {\n    SWIG_exception_fail(SWIG_ArgError(res7), \"in method '\" \"gsl_monte_plain_integrate\" \"', argument \" \"7\"\" of type '\" \"gsl_monte_plain_state *\"\"'\"); \n  }\n  arg7 = (gsl_monte_plain_state *)(argp7);\n  {\n    int flag;\n    callback_function_params * p;\n    \n    FUNC_MESS(\"\\t\\t Setting jump buffer\");\n    assert(arg1);\n    \n    \n    _solver1 = arg1;\n    p = (callback_function_params *) \n    PyGSL_gsl_monte_function_GET_PARAMS(_solver1);\n    \n    if((flag=setjmp(p->buffer)) == 0){\n      FUNC_MESS(\"\\t\\t Setting Jmp Buffer\");\n      p->buffer_is_set = 1;\n    } else {\n      FUNC_MESS(\"\\t\\t Returning from Jmp Buffer\");\n      p->buffer_is_set = 0;\n      goto fail;\n    }\n    \n    FUNC_MESS(\"\\t\\t END Setting jump buffer\");\n  }\n  {\n    ;\n  }\n  result = gsl_monte_plain_integrate((gsl_monte_function const *)arg1,(double const (*))arg2,(double const (*))arg3,arg4,arg5,arg6,arg7,arg8,arg9);\n  {\n    /* \n    \tassert(result >= 0);  assertion removed as PyGSL_error_flag can deal with\n    \tnegative numbers.\n         */\n    if(GSL_FAILURE == PyGSL_ERROR_FLAG(result)){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 74); \n      goto fail;\n    }\n    Py_INCREF(Py_None);\n    resultobj = Py_None;\n  }\n  if (SWIG_IsTmpObj(res8)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg8)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res8) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg8), SWIGTYPE_p_double, new_flags));\n  }\n  if (SWIG_IsTmpObj(res9)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg9)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res9) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg9), SWIGTYPE_p_double, new_flags));\n  }\n  {\n    callback_function_params * p;\n    if(_solver1){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params *)  \n      PyGSL_gsl_monte_function_GET_PARAMS(_solver1);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  {\n    Py_XDECREF(_PyVector_12);\n    Py_XDECREF(_PyVector_22);\n  }\n  return resultobj;\nfail:\n  {\n    callback_function_params * p;\n    if(_solver1){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params *)  \n      PyGSL_gsl_monte_function_GET_PARAMS(_solver1);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  {\n    Py_XDECREF(_PyVector_12);\n    Py_XDECREF(_PyVector_22);\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_monte_plain_alloc(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  size_t arg1 ;\n  size_t val1 ;\n  int ecode1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"dim\", NULL \n  };\n  gsl_monte_plain_state *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_monte_plain_alloc\",kwnames,&obj0)) SWIG_fail;\n  ecode1 = SWIG_AsVal_size_t(obj0, &val1);\n  if (!SWIG_IsOK(ecode1)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode1), \"in method '\" \"gsl_monte_plain_alloc\" \"', argument \" \"1\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg1 = (size_t)(val1);\n  result = (gsl_monte_plain_state *)gsl_monte_plain_alloc(arg1);\n  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_gsl_monte_plain_state, 0 |  0 );\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_monte_plain_init(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_monte_plain_state *arg1 = (gsl_monte_plain_state *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"state\", NULL \n  };\n  gsl_error_flag_drop result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_monte_plain_init\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_monte_plain_state, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_monte_plain_init\" \"', argument \" \"1\"\" of type '\" \"gsl_monte_plain_state *\"\"'\"); \n  }\n  arg1 = (gsl_monte_plain_state *)(argp1);\n  result = gsl_monte_plain_init(arg1);\n  {\n    /* \n    \tassert(result >= 0);  assertion removed as PyGSL_error_flag can deal with\n    \tnegative numbers.\n         */\n    if(GSL_FAILURE == PyGSL_ERROR_FLAG(result)){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 74); \n      goto fail;\n    }\n    Py_INCREF(Py_None);\n    resultobj = Py_None;\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_monte_plain_free(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_monte_plain_state *arg1 = (gsl_monte_plain_state *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"state\", NULL \n  };\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_monte_plain_free\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_monte_plain_state, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_monte_plain_free\" \"', argument \" \"1\"\" of type '\" \"gsl_monte_plain_state *\"\"'\"); \n  }\n  arg1 = (gsl_monte_plain_state *)(argp1);\n  gsl_monte_plain_free(arg1);\n  resultobj = SWIG_Py_Void();\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_pygsl_monte_miser_get_min_calls(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_monte_miser_state *arg1 = (gsl_monte_miser_state *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  size_t result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:pygsl_monte_miser_get_min_calls\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_monte_miser_state, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"pygsl_monte_miser_get_min_calls\" \"', argument \" \"1\"\" of type '\" \"gsl_monte_miser_state *\"\"'\"); \n  }\n  arg1 = (gsl_monte_miser_state *)(argp1);\n  result = (size_t)pygsl_monte_miser_get_min_calls(arg1);\n  resultobj = SWIG_From_size_t((size_t)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_pygsl_monte_miser_get_min_calls_per_bisection(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_monte_miser_state *arg1 = (gsl_monte_miser_state *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  size_t result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:pygsl_monte_miser_get_min_calls_per_bisection\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_monte_miser_state, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"pygsl_monte_miser_get_min_calls_per_bisection\" \"', argument \" \"1\"\" of type '\" \"gsl_monte_miser_state *\"\"'\"); \n  }\n  arg1 = (gsl_monte_miser_state *)(argp1);\n  result = (size_t)pygsl_monte_miser_get_min_calls_per_bisection(arg1);\n  resultobj = SWIG_From_size_t((size_t)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_pygsl_monte_miser_get_dither(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_monte_miser_state *arg1 = (gsl_monte_miser_state *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  double result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:pygsl_monte_miser_get_dither\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_monte_miser_state, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"pygsl_monte_miser_get_dither\" \"', argument \" \"1\"\" of type '\" \"gsl_monte_miser_state *\"\"'\"); \n  }\n  arg1 = (gsl_monte_miser_state *)(argp1);\n  result = (double)pygsl_monte_miser_get_dither(arg1);\n  resultobj = SWIG_From_double((double)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_pygsl_monte_miser_get_estimate_frac(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_monte_miser_state *arg1 = (gsl_monte_miser_state *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  double result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:pygsl_monte_miser_get_estimate_frac\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_monte_miser_state, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"pygsl_monte_miser_get_estimate_frac\" \"', argument \" \"1\"\" of type '\" \"gsl_monte_miser_state *\"\"'\"); \n  }\n  arg1 = (gsl_monte_miser_state *)(argp1);\n  result = (double)pygsl_monte_miser_get_estimate_frac(arg1);\n  resultobj = SWIG_From_double((double)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_pygsl_monte_miser_get_alpha(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_monte_miser_state *arg1 = (gsl_monte_miser_state *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  double result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:pygsl_monte_miser_get_alpha\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_monte_miser_state, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"pygsl_monte_miser_get_alpha\" \"', argument \" \"1\"\" of type '\" \"gsl_monte_miser_state *\"\"'\"); \n  }\n  arg1 = (gsl_monte_miser_state *)(argp1);\n  result = (double)pygsl_monte_miser_get_alpha(arg1);\n  resultobj = SWIG_From_double((double)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_pygsl_monte_miser_set_min_calls(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_monte_miser_state *arg1 = (gsl_monte_miser_state *) 0 ;\n  int arg2 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  int val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\",(char *) \"NONNEGATIVE\", NULL \n  };\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:pygsl_monte_miser_set_min_calls\",kwnames,&obj0,&obj1)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_monte_miser_state, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"pygsl_monte_miser_set_min_calls\" \"', argument \" \"1\"\" of type '\" \"gsl_monte_miser_state *\"\"'\"); \n  }\n  arg1 = (gsl_monte_miser_state *)(argp1);\n  ecode2 = SWIG_AsVal_int(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"pygsl_monte_miser_set_min_calls\" \"', argument \" \"2\"\" of type '\" \"int\"\"'\");\n  } \n  arg2 = (int)(val2);\n  {\n    if (arg2 < 0) {\n      SWIG_exception(SWIG_ValueError,\"Expected a non-negative value.\");\n    }\n  }\n  pygsl_monte_miser_set_min_calls(arg1,arg2);\n  resultobj = SWIG_Py_Void();\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_pygsl_monte_miser_set_min_calls_per_bisection(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_monte_miser_state *arg1 = (gsl_monte_miser_state *) 0 ;\n  int arg2 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  int val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\",(char *) \"NONNEGATIVE\", NULL \n  };\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:pygsl_monte_miser_set_min_calls_per_bisection\",kwnames,&obj0,&obj1)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_monte_miser_state, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"pygsl_monte_miser_set_min_calls_per_bisection\" \"', argument \" \"1\"\" of type '\" \"gsl_monte_miser_state *\"\"'\"); \n  }\n  arg1 = (gsl_monte_miser_state *)(argp1);\n  ecode2 = SWIG_AsVal_int(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"pygsl_monte_miser_set_min_calls_per_bisection\" \"', argument \" \"2\"\" of type '\" \"int\"\"'\");\n  } \n  arg2 = (int)(val2);\n  {\n    if (arg2 < 0) {\n      SWIG_exception(SWIG_ValueError,\"Expected a non-negative value.\");\n    }\n  }\n  pygsl_monte_miser_set_min_calls_per_bisection(arg1,arg2);\n  resultobj = SWIG_Py_Void();\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_pygsl_monte_miser_set_dither(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_monte_miser_state *arg1 = (gsl_monte_miser_state *) 0 ;\n  double arg2 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\",(char *) \"d\", NULL \n  };\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:pygsl_monte_miser_set_dither\",kwnames,&obj0,&obj1)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_monte_miser_state, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"pygsl_monte_miser_set_dither\" \"', argument \" \"1\"\" of type '\" \"gsl_monte_miser_state *\"\"'\"); \n  }\n  arg1 = (gsl_monte_miser_state *)(argp1);\n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"pygsl_monte_miser_set_dither\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  pygsl_monte_miser_set_dither(arg1,arg2);\n  resultobj = SWIG_Py_Void();\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_pygsl_monte_miser_set_estimate_frac(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_monte_miser_state *arg1 = (gsl_monte_miser_state *) 0 ;\n  double arg2 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\",(char *) \"e\", NULL \n  };\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:pygsl_monte_miser_set_estimate_frac\",kwnames,&obj0,&obj1)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_monte_miser_state, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"pygsl_monte_miser_set_estimate_frac\" \"', argument \" \"1\"\" of type '\" \"gsl_monte_miser_state *\"\"'\"); \n  }\n  arg1 = (gsl_monte_miser_state *)(argp1);\n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"pygsl_monte_miser_set_estimate_frac\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  pygsl_monte_miser_set_estimate_frac(arg1,arg2);\n  resultobj = SWIG_Py_Void();\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_pygsl_monte_miser_set_alpha(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_monte_miser_state *arg1 = (gsl_monte_miser_state *) 0 ;\n  double arg2 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\",(char *) \"alpha\", NULL \n  };\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:pygsl_monte_miser_set_alpha\",kwnames,&obj0,&obj1)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_monte_miser_state, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"pygsl_monte_miser_set_alpha\" \"', argument \" \"1\"\" of type '\" \"gsl_monte_miser_state *\"\"'\"); \n  }\n  arg1 = (gsl_monte_miser_state *)(argp1);\n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"pygsl_monte_miser_set_alpha\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  pygsl_monte_miser_set_alpha(arg1,arg2);\n  resultobj = SWIG_Py_Void();\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_monte_miser_integrate(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_monte_function *arg1 = (gsl_monte_function *) 0 ;\n  double *arg2 ;\n  double *arg3 ;\n  size_t arg4 ;\n  size_t arg5 ;\n  gsl_rng *arg6 = (gsl_rng *) 0 ;\n  gsl_monte_miser_state *arg7 = (gsl_monte_miser_state *) 0 ;\n  double *arg8 = (double *) 0 ;\n  double *arg9 = (double *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  size_t val5 ;\n  int ecode5 = 0 ;\n  void *argp7 = 0 ;\n  int res7 = 0 ;\n  double temp8 ;\n  int res8 = SWIG_TMPOBJ ;\n  double temp9 ;\n  int res9 = SWIG_TMPOBJ ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  PyObject * obj3 = 0 ;\n  PyObject * obj4 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"BUFFER\",(char *) \"xl\",(char *) \"calls\",(char *) \"r\",(char *) \"state\", NULL \n  };\n  gsl_error_flag_drop result;\n  \n  \n  gsl_monte_function * volatile _solver1 = NULL;\n  \n  \n  PyArrayObject *_PyVector_12 = NULL;\n  PyArrayObject *_PyVector_22 = NULL;\n  \n  arg8 = &temp8;\n  arg9 = &temp9;\n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOOOO:gsl_monte_miser_integrate\",kwnames,&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_monte_function, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_monte_miser_integrate\" \"', argument \" \"1\"\" of type '\" \"gsl_monte_function *\"\"'\"); \n  }\n  arg1 = (gsl_monte_function *)(argp1);\n  {\n    int mysize = 0;\n    if(!PySequence_Check(obj1)){\n      PyErr_SetString(PyExc_TypeError, \"Expected a sequence of two arrays!\");\n      goto fail;\n    }\n    if(PySequence_Size(obj1) != 2){\n      PyErr_SetString(PyExc_TypeError, \"Expected a sequence of two arrays! Number of sequence arguments did not match!\");\n      goto fail;\n    }\n    _PyVector_12 = PyGSL_vector_check(PySequence_GetItem(obj1, 0), -1, PyGSL_DARRAY_CINPUT(2), NULL, NULL);\n    if (_PyVector_12 == NULL)\n    goto fail;\n    \n    mysize = _PyVector_12->dimensions[0];\n    \n    _PyVector_22 = PyGSL_vector_check(PySequence_GetItem(obj1, 1), mysize, PyGSL_DARRAY_CINPUT(2+1), NULL, NULL);\n    if (_PyVector_22 == NULL)\n    goto fail;\n    \n    arg2 = (double *)(_PyVector_12->data);\n    arg3 = (double *)(_PyVector_22->data);\n    arg4 = (size_t) mysize;\n    \n  }\n  ecode5 = SWIG_AsVal_size_t(obj2, &val5);\n  if (!SWIG_IsOK(ecode5)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode5), \"in method '\" \"gsl_monte_miser_integrate\" \"', argument \" \"5\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg5 = (size_t)(val5);\n  {\n    arg6= (gsl_rng*) PyGSL_gsl_rng_from_pyobject(obj3);     \n    if(arg6 == NULL)\n    goto fail;\n  }\n  res7 = SWIG_ConvertPtr(obj4, &argp7,SWIGTYPE_p_gsl_monte_miser_state, 0 |  0 );\n  if (!SWIG_IsOK(res7)) {\n    SWIG_exception_fail(SWIG_ArgError(res7), \"in method '\" \"gsl_monte_miser_integrate\" \"', argument \" \"7\"\" of type '\" \"gsl_monte_miser_state *\"\"'\"); \n  }\n  arg7 = (gsl_monte_miser_state *)(argp7);\n  {\n    int flag;\n    callback_function_params * p;\n    \n    FUNC_MESS(\"\\t\\t Setting jump buffer\");\n    assert(arg1);\n    \n    \n    _solver1 = arg1;\n    p = (callback_function_params *) \n    PyGSL_gsl_monte_function_GET_PARAMS(_solver1);\n    \n    if((flag=setjmp(p->buffer)) == 0){\n      FUNC_MESS(\"\\t\\t Setting Jmp Buffer\");\n      p->buffer_is_set = 1;\n    } else {\n      FUNC_MESS(\"\\t\\t Returning from Jmp Buffer\");\n      p->buffer_is_set = 0;\n      goto fail;\n    }\n    \n    FUNC_MESS(\"\\t\\t END Setting jump buffer\");\n  }\n  {\n    ;\n  }\n  result = gsl_monte_miser_integrate(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9);\n  {\n    /* \n    \tassert(result >= 0);  assertion removed as PyGSL_error_flag can deal with\n    \tnegative numbers.\n         */\n    if(GSL_FAILURE == PyGSL_ERROR_FLAG(result)){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 74); \n      goto fail;\n    }\n    Py_INCREF(Py_None);\n    resultobj = Py_None;\n  }\n  if (SWIG_IsTmpObj(res8)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg8)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res8) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg8), SWIGTYPE_p_double, new_flags));\n  }\n  if (SWIG_IsTmpObj(res9)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg9)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res9) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg9), SWIGTYPE_p_double, new_flags));\n  }\n  {\n    callback_function_params * p;\n    if(_solver1){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params *)  \n      PyGSL_gsl_monte_function_GET_PARAMS(_solver1);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  {\n    Py_XDECREF(_PyVector_12);\n    Py_XDECREF(_PyVector_22);\n  }\n  return resultobj;\nfail:\n  {\n    callback_function_params * p;\n    if(_solver1){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params *)  \n      PyGSL_gsl_monte_function_GET_PARAMS(_solver1);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  {\n    Py_XDECREF(_PyVector_12);\n    Py_XDECREF(_PyVector_22);\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_monte_miser_alloc(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  size_t arg1 ;\n  size_t val1 ;\n  int ecode1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"dim\", NULL \n  };\n  gsl_monte_miser_state *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_monte_miser_alloc\",kwnames,&obj0)) SWIG_fail;\n  ecode1 = SWIG_AsVal_size_t(obj0, &val1);\n  if (!SWIG_IsOK(ecode1)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode1), \"in method '\" \"gsl_monte_miser_alloc\" \"', argument \" \"1\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg1 = (size_t)(val1);\n  result = (gsl_monte_miser_state *)gsl_monte_miser_alloc(arg1);\n  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_gsl_monte_miser_state, 0 |  0 );\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_monte_miser_init(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_monte_miser_state *arg1 = (gsl_monte_miser_state *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"state\", NULL \n  };\n  gsl_error_flag_drop result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_monte_miser_init\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_monte_miser_state, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_monte_miser_init\" \"', argument \" \"1\"\" of type '\" \"gsl_monte_miser_state *\"\"'\"); \n  }\n  arg1 = (gsl_monte_miser_state *)(argp1);\n  result = gsl_monte_miser_init(arg1);\n  {\n    /* \n    \tassert(result >= 0);  assertion removed as PyGSL_error_flag can deal with\n    \tnegative numbers.\n         */\n    if(GSL_FAILURE == PyGSL_ERROR_FLAG(result)){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 74); \n      goto fail;\n    }\n    Py_INCREF(Py_None);\n    resultobj = Py_None;\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_monte_miser_free(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_monte_miser_state *arg1 = (gsl_monte_miser_state *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"state\", NULL \n  };\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_monte_miser_free\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_monte_miser_state, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_monte_miser_free\" \"', argument \" \"1\"\" of type '\" \"gsl_monte_miser_state *\"\"'\"); \n  }\n  arg1 = (gsl_monte_miser_state *)(argp1);\n  gsl_monte_miser_free(arg1);\n  resultobj = SWIG_Py_Void();\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_pygsl_monte_vegas_get_result(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_monte_vegas_state *arg1 = (gsl_monte_vegas_state *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  double result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:pygsl_monte_vegas_get_result\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_monte_vegas_state, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"pygsl_monte_vegas_get_result\" \"', argument \" \"1\"\" of type '\" \"gsl_monte_vegas_state *\"\"'\"); \n  }\n  arg1 = (gsl_monte_vegas_state *)(argp1);\n  result = (double)pygsl_monte_vegas_get_result(arg1);\n  resultobj = SWIG_From_double((double)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_pygsl_monte_vegas_get_sigma(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_monte_vegas_state *arg1 = (gsl_monte_vegas_state *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  double result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:pygsl_monte_vegas_get_sigma\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_monte_vegas_state, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"pygsl_monte_vegas_get_sigma\" \"', argument \" \"1\"\" of type '\" \"gsl_monte_vegas_state *\"\"'\"); \n  }\n  arg1 = (gsl_monte_vegas_state *)(argp1);\n  result = (double)pygsl_monte_vegas_get_sigma(arg1);\n  resultobj = SWIG_From_double((double)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_pygsl_monte_vegas_get_chisq(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_monte_vegas_state *arg1 = (gsl_monte_vegas_state *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  double result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:pygsl_monte_vegas_get_chisq\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_monte_vegas_state, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"pygsl_monte_vegas_get_chisq\" \"', argument \" \"1\"\" of type '\" \"gsl_monte_vegas_state *\"\"'\"); \n  }\n  arg1 = (gsl_monte_vegas_state *)(argp1);\n  result = (double)pygsl_monte_vegas_get_chisq(arg1);\n  resultobj = SWIG_From_double((double)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_pygsl_monte_vegas_get_alpha(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_monte_vegas_state *arg1 = (gsl_monte_vegas_state *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  double result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:pygsl_monte_vegas_get_alpha\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_monte_vegas_state, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"pygsl_monte_vegas_get_alpha\" \"', argument \" \"1\"\" of type '\" \"gsl_monte_vegas_state *\"\"'\"); \n  }\n  arg1 = (gsl_monte_vegas_state *)(argp1);\n  result = (double)pygsl_monte_vegas_get_alpha(arg1);\n  resultobj = SWIG_From_double((double)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_pygsl_monte_vegas_get_iterations(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_monte_vegas_state *arg1 = (gsl_monte_vegas_state *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  size_t result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:pygsl_monte_vegas_get_iterations\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_monte_vegas_state, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"pygsl_monte_vegas_get_iterations\" \"', argument \" \"1\"\" of type '\" \"gsl_monte_vegas_state *\"\"'\"); \n  }\n  arg1 = (gsl_monte_vegas_state *)(argp1);\n  result = (size_t)pygsl_monte_vegas_get_iterations(arg1);\n  resultobj = SWIG_From_size_t((size_t)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_pygsl_monte_vegas_get_stage(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_monte_vegas_state *arg1 = (gsl_monte_vegas_state *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  int result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:pygsl_monte_vegas_get_stage\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_monte_vegas_state, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"pygsl_monte_vegas_get_stage\" \"', argument \" \"1\"\" of type '\" \"gsl_monte_vegas_state *\"\"'\"); \n  }\n  arg1 = (gsl_monte_vegas_state *)(argp1);\n  result = (int)pygsl_monte_vegas_get_stage(arg1);\n  resultobj = SWIG_From_int((int)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_pygsl_monte_vegas_get_mode(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_monte_vegas_state *arg1 = (gsl_monte_vegas_state *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  int result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:pygsl_monte_vegas_get_mode\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_monte_vegas_state, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"pygsl_monte_vegas_get_mode\" \"', argument \" \"1\"\" of type '\" \"gsl_monte_vegas_state *\"\"'\"); \n  }\n  arg1 = (gsl_monte_vegas_state *)(argp1);\n  result = (int)pygsl_monte_vegas_get_mode(arg1);\n  resultobj = SWIG_From_int((int)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_pygsl_monte_vegas_get_verbose(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_monte_vegas_state *arg1 = (gsl_monte_vegas_state *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  int result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:pygsl_monte_vegas_get_verbose\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_monte_vegas_state, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"pygsl_monte_vegas_get_verbose\" \"', argument \" \"1\"\" of type '\" \"gsl_monte_vegas_state *\"\"'\"); \n  }\n  arg1 = (gsl_monte_vegas_state *)(argp1);\n  result = (int)pygsl_monte_vegas_get_verbose(arg1);\n  resultobj = SWIG_From_int((int)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_pygsl_monte_vegas_get_ostream(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_monte_vegas_state *arg1 = (gsl_monte_vegas_state *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  FILE *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:pygsl_monte_vegas_get_ostream\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_monte_vegas_state, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"pygsl_monte_vegas_get_ostream\" \"', argument \" \"1\"\" of type '\" \"gsl_monte_vegas_state *\"\"'\"); \n  }\n  arg1 = (gsl_monte_vegas_state *)(argp1);\n  result = (FILE *)pygsl_monte_vegas_get_ostream(arg1);\n  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_FILE, 0 |  0 );\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_pygsl_monte_vegas_set_result(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_monte_vegas_state *arg1 = (gsl_monte_vegas_state *) 0 ;\n  double arg2 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\",(char *) \"v\", NULL \n  };\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:pygsl_monte_vegas_set_result\",kwnames,&obj0,&obj1)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_monte_vegas_state, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"pygsl_monte_vegas_set_result\" \"', argument \" \"1\"\" of type '\" \"gsl_monte_vegas_state *\"\"'\"); \n  }\n  arg1 = (gsl_monte_vegas_state *)(argp1);\n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"pygsl_monte_vegas_set_result\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  pygsl_monte_vegas_set_result(arg1,arg2);\n  resultobj = SWIG_Py_Void();\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_pygsl_monte_vegas_set_sigma(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_monte_vegas_state *arg1 = (gsl_monte_vegas_state *) 0 ;\n  double arg2 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\",(char *) \"v\", NULL \n  };\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:pygsl_monte_vegas_set_sigma\",kwnames,&obj0,&obj1)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_monte_vegas_state, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"pygsl_monte_vegas_set_sigma\" \"', argument \" \"1\"\" of type '\" \"gsl_monte_vegas_state *\"\"'\"); \n  }\n  arg1 = (gsl_monte_vegas_state *)(argp1);\n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"pygsl_monte_vegas_set_sigma\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  pygsl_monte_vegas_set_sigma(arg1,arg2);\n  resultobj = SWIG_Py_Void();\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_pygsl_monte_vegas_set_chisq(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_monte_vegas_state *arg1 = (gsl_monte_vegas_state *) 0 ;\n  double arg2 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\",(char *) \"v\", NULL \n  };\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:pygsl_monte_vegas_set_chisq\",kwnames,&obj0,&obj1)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_monte_vegas_state, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"pygsl_monte_vegas_set_chisq\" \"', argument \" \"1\"\" of type '\" \"gsl_monte_vegas_state *\"\"'\"); \n  }\n  arg1 = (gsl_monte_vegas_state *)(argp1);\n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"pygsl_monte_vegas_set_chisq\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  pygsl_monte_vegas_set_chisq(arg1,arg2);\n  resultobj = SWIG_Py_Void();\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_pygsl_monte_vegas_set_alpha(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_monte_vegas_state *arg1 = (gsl_monte_vegas_state *) 0 ;\n  double arg2 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\",(char *) \"v\", NULL \n  };\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:pygsl_monte_vegas_set_alpha\",kwnames,&obj0,&obj1)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_monte_vegas_state, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"pygsl_monte_vegas_set_alpha\" \"', argument \" \"1\"\" of type '\" \"gsl_monte_vegas_state *\"\"'\"); \n  }\n  arg1 = (gsl_monte_vegas_state *)(argp1);\n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"pygsl_monte_vegas_set_alpha\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  pygsl_monte_vegas_set_alpha(arg1,arg2);\n  resultobj = SWIG_Py_Void();\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_pygsl_monte_vegas_set_iterations(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_monte_vegas_state *arg1 = (gsl_monte_vegas_state *) 0 ;\n  int arg2 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  int val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\",(char *) \"NONNEGATIVE\", NULL \n  };\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:pygsl_monte_vegas_set_iterations\",kwnames,&obj0,&obj1)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_monte_vegas_state, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"pygsl_monte_vegas_set_iterations\" \"', argument \" \"1\"\" of type '\" \"gsl_monte_vegas_state *\"\"'\"); \n  }\n  arg1 = (gsl_monte_vegas_state *)(argp1);\n  ecode2 = SWIG_AsVal_int(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"pygsl_monte_vegas_set_iterations\" \"', argument \" \"2\"\" of type '\" \"int\"\"'\");\n  } \n  arg2 = (int)(val2);\n  {\n    if (arg2 < 0) {\n      SWIG_exception(SWIG_ValueError,\"Expected a non-negative value.\");\n    }\n  }\n  pygsl_monte_vegas_set_iterations(arg1,arg2);\n  resultobj = SWIG_Py_Void();\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_pygsl_monte_vegas_set_stage(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_monte_vegas_state *arg1 = (gsl_monte_vegas_state *) 0 ;\n  int arg2 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  int val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\",(char *) \"NONNEGATIVE\", NULL \n  };\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:pygsl_monte_vegas_set_stage\",kwnames,&obj0,&obj1)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_monte_vegas_state, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"pygsl_monte_vegas_set_stage\" \"', argument \" \"1\"\" of type '\" \"gsl_monte_vegas_state *\"\"'\"); \n  }\n  arg1 = (gsl_monte_vegas_state *)(argp1);\n  ecode2 = SWIG_AsVal_int(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"pygsl_monte_vegas_set_stage\" \"', argument \" \"2\"\" of type '\" \"int\"\"'\");\n  } \n  arg2 = (int)(val2);\n  {\n    if (arg2 < 0) {\n      SWIG_exception(SWIG_ValueError,\"Expected a non-negative value.\");\n    }\n  }\n  pygsl_monte_vegas_set_stage(arg1,arg2);\n  resultobj = SWIG_Py_Void();\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_pygsl_monte_vegas_set_mode(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_monte_vegas_state *arg1 = (gsl_monte_vegas_state *) 0 ;\n  int arg2 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  int val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\",(char *) \"v\", NULL \n  };\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:pygsl_monte_vegas_set_mode\",kwnames,&obj0,&obj1)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_monte_vegas_state, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"pygsl_monte_vegas_set_mode\" \"', argument \" \"1\"\" of type '\" \"gsl_monte_vegas_state *\"\"'\"); \n  }\n  arg1 = (gsl_monte_vegas_state *)(argp1);\n  ecode2 = SWIG_AsVal_int(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"pygsl_monte_vegas_set_mode\" \"', argument \" \"2\"\" of type '\" \"int\"\"'\");\n  } \n  arg2 = (int)(val2);\n  pygsl_monte_vegas_set_mode(arg1,arg2);\n  resultobj = SWIG_Py_Void();\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_pygsl_monte_vegas_set_verbose(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_monte_vegas_state *arg1 = (gsl_monte_vegas_state *) 0 ;\n  int arg2 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  int val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\",(char *) \"v\", NULL \n  };\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:pygsl_monte_vegas_set_verbose\",kwnames,&obj0,&obj1)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_monte_vegas_state, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"pygsl_monte_vegas_set_verbose\" \"', argument \" \"1\"\" of type '\" \"gsl_monte_vegas_state *\"\"'\"); \n  }\n  arg1 = (gsl_monte_vegas_state *)(argp1);\n  ecode2 = SWIG_AsVal_int(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"pygsl_monte_vegas_set_verbose\" \"', argument \" \"2\"\" of type '\" \"int\"\"'\");\n  } \n  arg2 = (int)(val2);\n  pygsl_monte_vegas_set_verbose(arg1,arg2);\n  resultobj = SWIG_Py_Void();\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_pygsl_monte_vegas_set_ostream(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_monte_vegas_state *arg1 = (gsl_monte_vegas_state *) 0 ;\n  FILE *arg2 = (FILE *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\",(char *) \"v\", NULL \n  };\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:pygsl_monte_vegas_set_ostream\",kwnames,&obj0,&obj1)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_monte_vegas_state, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"pygsl_monte_vegas_set_ostream\" \"', argument \" \"1\"\" of type '\" \"gsl_monte_vegas_state *\"\"'\"); \n  }\n  arg1 = (gsl_monte_vegas_state *)(argp1);\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj1)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg2 = PyFile_AsFile(obj1);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg2, fileno(arg2));\n    assert(arg2 != NULL);\n    \n  }\n  pygsl_monte_vegas_set_ostream(arg1,arg2);\n  resultobj = SWIG_Py_Void();\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_monte_vegas_integrate(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_monte_function *arg1 = (gsl_monte_function *) 0 ;\n  double *arg2 ;\n  double *arg3 ;\n  size_t arg4 ;\n  size_t arg5 ;\n  gsl_rng *arg6 = (gsl_rng *) 0 ;\n  gsl_monte_vegas_state *arg7 = (gsl_monte_vegas_state *) 0 ;\n  double *arg8 = (double *) 0 ;\n  double *arg9 = (double *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  size_t val5 ;\n  int ecode5 = 0 ;\n  void *argp7 = 0 ;\n  int res7 = 0 ;\n  double temp8 ;\n  int res8 = SWIG_TMPOBJ ;\n  double temp9 ;\n  int res9 = SWIG_TMPOBJ ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  PyObject * obj3 = 0 ;\n  PyObject * obj4 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"BUFFER\",(char *) \"xl\",(char *) \"calls\",(char *) \"r\",(char *) \"state\", NULL \n  };\n  gsl_error_flag_drop result;\n  \n  \n  gsl_monte_function * volatile _solver1 = NULL;\n  \n  \n  PyArrayObject *_PyVector_12 = NULL;\n  PyArrayObject *_PyVector_22 = NULL;\n  \n  arg8 = &temp8;\n  arg9 = &temp9;\n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOOOO:gsl_monte_vegas_integrate\",kwnames,&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_monte_function, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_monte_vegas_integrate\" \"', argument \" \"1\"\" of type '\" \"gsl_monte_function *\"\"'\"); \n  }\n  arg1 = (gsl_monte_function *)(argp1);\n  {\n    int mysize = 0;\n    if(!PySequence_Check(obj1)){\n      PyErr_SetString(PyExc_TypeError, \"Expected a sequence of two arrays!\");\n      goto fail;\n    }\n    if(PySequence_Size(obj1) != 2){\n      PyErr_SetString(PyExc_TypeError, \"Expected a sequence of two arrays! Number of sequence arguments did not match!\");\n      goto fail;\n    }\n    _PyVector_12 = PyGSL_vector_check(PySequence_GetItem(obj1, 0), -1, PyGSL_DARRAY_CINPUT(2), NULL, NULL);\n    if (_PyVector_12 == NULL)\n    goto fail;\n    \n    mysize = _PyVector_12->dimensions[0];\n    \n    _PyVector_22 = PyGSL_vector_check(PySequence_GetItem(obj1, 1), mysize, PyGSL_DARRAY_CINPUT(2+1), NULL, NULL);\n    if (_PyVector_22 == NULL)\n    goto fail;\n    \n    arg2 = (double *)(_PyVector_12->data);\n    arg3 = (double *)(_PyVector_22->data);\n    arg4 = (size_t) mysize;\n    \n  }\n  ecode5 = SWIG_AsVal_size_t(obj2, &val5);\n  if (!SWIG_IsOK(ecode5)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode5), \"in method '\" \"gsl_monte_vegas_integrate\" \"', argument \" \"5\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg5 = (size_t)(val5);\n  {\n    arg6= (gsl_rng*) PyGSL_gsl_rng_from_pyobject(obj3);     \n    if(arg6 == NULL)\n    goto fail;\n  }\n  res7 = SWIG_ConvertPtr(obj4, &argp7,SWIGTYPE_p_gsl_monte_vegas_state, 0 |  0 );\n  if (!SWIG_IsOK(res7)) {\n    SWIG_exception_fail(SWIG_ArgError(res7), \"in method '\" \"gsl_monte_vegas_integrate\" \"', argument \" \"7\"\" of type '\" \"gsl_monte_vegas_state *\"\"'\"); \n  }\n  arg7 = (gsl_monte_vegas_state *)(argp7);\n  {\n    int flag;\n    callback_function_params * p;\n    \n    FUNC_MESS(\"\\t\\t Setting jump buffer\");\n    assert(arg1);\n    \n    \n    _solver1 = arg1;\n    p = (callback_function_params *) \n    PyGSL_gsl_monte_function_GET_PARAMS(_solver1);\n    \n    if((flag=setjmp(p->buffer)) == 0){\n      FUNC_MESS(\"\\t\\t Setting Jmp Buffer\");\n      p->buffer_is_set = 1;\n    } else {\n      FUNC_MESS(\"\\t\\t Returning from Jmp Buffer\");\n      p->buffer_is_set = 0;\n      goto fail;\n    }\n    \n    FUNC_MESS(\"\\t\\t END Setting jump buffer\");\n  }\n  {\n    ;\n  }\n  result = gsl_monte_vegas_integrate(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9);\n  {\n    /* \n    \tassert(result >= 0);  assertion removed as PyGSL_error_flag can deal with\n    \tnegative numbers.\n         */\n    if(GSL_FAILURE == PyGSL_ERROR_FLAG(result)){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 74); \n      goto fail;\n    }\n    Py_INCREF(Py_None);\n    resultobj = Py_None;\n  }\n  if (SWIG_IsTmpObj(res8)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg8)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res8) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg8), SWIGTYPE_p_double, new_flags));\n  }\n  if (SWIG_IsTmpObj(res9)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg9)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res9) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg9), SWIGTYPE_p_double, new_flags));\n  }\n  {\n    callback_function_params * p;\n    if(_solver1){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params *)  \n      PyGSL_gsl_monte_function_GET_PARAMS(_solver1);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  {\n    Py_XDECREF(_PyVector_12);\n    Py_XDECREF(_PyVector_22);\n  }\n  return resultobj;\nfail:\n  {\n    callback_function_params * p;\n    if(_solver1){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params *)  \n      PyGSL_gsl_monte_function_GET_PARAMS(_solver1);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  {\n    Py_XDECREF(_PyVector_12);\n    Py_XDECREF(_PyVector_22);\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_monte_vegas_alloc(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  size_t arg1 ;\n  size_t val1 ;\n  int ecode1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"dim\", NULL \n  };\n  gsl_monte_vegas_state *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_monte_vegas_alloc\",kwnames,&obj0)) SWIG_fail;\n  ecode1 = SWIG_AsVal_size_t(obj0, &val1);\n  if (!SWIG_IsOK(ecode1)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode1), \"in method '\" \"gsl_monte_vegas_alloc\" \"', argument \" \"1\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg1 = (size_t)(val1);\n  result = (gsl_monte_vegas_state *)gsl_monte_vegas_alloc(arg1);\n  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_gsl_monte_vegas_state, 0 |  0 );\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_monte_vegas_init(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_monte_vegas_state *arg1 = (gsl_monte_vegas_state *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"state\", NULL \n  };\n  gsl_error_flag_drop result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_monte_vegas_init\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_monte_vegas_state, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_monte_vegas_init\" \"', argument \" \"1\"\" of type '\" \"gsl_monte_vegas_state *\"\"'\"); \n  }\n  arg1 = (gsl_monte_vegas_state *)(argp1);\n  result = gsl_monte_vegas_init(arg1);\n  {\n    /* \n    \tassert(result >= 0);  assertion removed as PyGSL_error_flag can deal with\n    \tnegative numbers.\n         */\n    if(GSL_FAILURE == PyGSL_ERROR_FLAG(result)){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 74); \n      goto fail;\n    }\n    Py_INCREF(Py_None);\n    resultobj = Py_None;\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_monte_vegas_free(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_monte_vegas_state *arg1 = (gsl_monte_vegas_state *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"state\", NULL \n  };\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_monte_vegas_free\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_monte_vegas_state, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_monte_vegas_free\" \"', argument \" \"1\"\" of type '\" \"gsl_monte_vegas_state *\"\"'\"); \n  }\n  arg1 = (gsl_monte_vegas_state *)(argp1);\n  gsl_monte_vegas_free(arg1);\n  resultobj = SWIG_Py_Void();\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN int Swig_var_gsl_root_fsolver_bisection_set(PyObject *_val SWIGUNUSED) {\n  SWIG_Error(SWIG_AttributeError,\"Variable gsl_root_fsolver_bisection is read-only.\");\n  return 1;\n}\n\n\nSWIGINTERN PyObject *Swig_var_gsl_root_fsolver_bisection_get(void) {\n  PyObject *pyobj = 0;\n  \n  pyobj = SWIG_NewPointerObj(SWIG_as_voidptr(gsl_root_fsolver_bisection), SWIGTYPE_p_gsl_root_fsolver_type,  0 );\n  return pyobj;\n}\n\n\nSWIGINTERN int Swig_var_gsl_root_fsolver_brent_set(PyObject *_val SWIGUNUSED) {\n  SWIG_Error(SWIG_AttributeError,\"Variable gsl_root_fsolver_brent is read-only.\");\n  return 1;\n}\n\n\nSWIGINTERN PyObject *Swig_var_gsl_root_fsolver_brent_get(void) {\n  PyObject *pyobj = 0;\n  \n  pyobj = SWIG_NewPointerObj(SWIG_as_voidptr(gsl_root_fsolver_brent), SWIGTYPE_p_gsl_root_fsolver_type,  0 );\n  return pyobj;\n}\n\n\nSWIGINTERN int Swig_var_gsl_root_fsolver_falsepos_set(PyObject *_val SWIGUNUSED) {\n  SWIG_Error(SWIG_AttributeError,\"Variable gsl_root_fsolver_falsepos is read-only.\");\n  return 1;\n}\n\n\nSWIGINTERN PyObject *Swig_var_gsl_root_fsolver_falsepos_get(void) {\n  PyObject *pyobj = 0;\n  \n  pyobj = SWIG_NewPointerObj(SWIG_as_voidptr(gsl_root_fsolver_falsepos), SWIGTYPE_p_gsl_root_fsolver_type,  0 );\n  return pyobj;\n}\n\n\nSWIGINTERN int Swig_var_gsl_root_fdfsolver_newton_set(PyObject *_val SWIGUNUSED) {\n  SWIG_Error(SWIG_AttributeError,\"Variable gsl_root_fdfsolver_newton is read-only.\");\n  return 1;\n}\n\n\nSWIGINTERN PyObject *Swig_var_gsl_root_fdfsolver_newton_get(void) {\n  PyObject *pyobj = 0;\n  \n  pyobj = SWIG_NewPointerObj(SWIG_as_voidptr(gsl_root_fdfsolver_newton), SWIGTYPE_p_gsl_root_fdfsolver_type,  0 );\n  return pyobj;\n}\n\n\nSWIGINTERN int Swig_var_gsl_root_fdfsolver_secant_set(PyObject *_val SWIGUNUSED) {\n  SWIG_Error(SWIG_AttributeError,\"Variable gsl_root_fdfsolver_secant is read-only.\");\n  return 1;\n}\n\n\nSWIGINTERN PyObject *Swig_var_gsl_root_fdfsolver_secant_get(void) {\n  PyObject *pyobj = 0;\n  \n  pyobj = SWIG_NewPointerObj(SWIG_as_voidptr(gsl_root_fdfsolver_secant), SWIGTYPE_p_gsl_root_fdfsolver_type,  0 );\n  return pyobj;\n}\n\n\nSWIGINTERN int Swig_var_gsl_root_fdfsolver_steffenson_set(PyObject *_val SWIGUNUSED) {\n  SWIG_Error(SWIG_AttributeError,\"Variable gsl_root_fdfsolver_steffenson is read-only.\");\n  return 1;\n}\n\n\nSWIGINTERN PyObject *Swig_var_gsl_root_fdfsolver_steffenson_get(void) {\n  PyObject *pyobj = 0;\n  \n  pyobj = SWIG_NewPointerObj(SWIG_as_voidptr(gsl_root_fdfsolver_steffenson), SWIGTYPE_p_gsl_root_fdfsolver_type,  0 );\n  return pyobj;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_root_fsolver_alloc(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_root_fsolver_type *arg1 = (gsl_root_fsolver_type *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"T\", NULL \n  };\n  gsl_root_fsolver *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_root_fsolver_alloc\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_root_fsolver_type, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_root_fsolver_alloc\" \"', argument \" \"1\"\" of type '\" \"gsl_root_fsolver_type const *\"\"'\"); \n  }\n  arg1 = (gsl_root_fsolver_type *)(argp1);\n  result = (gsl_root_fsolver *)gsl_root_fsolver_alloc((gsl_root_fsolver_type const *)arg1);\n  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_gsl_root_fsolver, 0 |  0 );\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_root_fsolver_free(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_root_fsolver *arg1 = (gsl_root_fsolver *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_root_fsolver_free\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_root_fsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_root_fsolver_free\" \"', argument \" \"1\"\" of type '\" \"gsl_root_fsolver *\"\"'\"); \n  }\n  arg1 = (gsl_root_fsolver *)(argp1);\n  gsl_root_fsolver_free(arg1);\n  resultobj = SWIG_Py_Void();\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_root_fdfsolver_alloc(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_root_fdfsolver_type *arg1 = (gsl_root_fdfsolver_type *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"T\", NULL \n  };\n  gsl_root_fdfsolver *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_root_fdfsolver_alloc\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_root_fdfsolver_type, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_root_fdfsolver_alloc\" \"', argument \" \"1\"\" of type '\" \"gsl_root_fdfsolver_type const *\"\"'\"); \n  }\n  arg1 = (gsl_root_fdfsolver_type *)(argp1);\n  result = (gsl_root_fdfsolver *)gsl_root_fdfsolver_alloc((gsl_root_fdfsolver_type const *)arg1);\n  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_gsl_root_fdfsolver, 0 |  0 );\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_root_fdfsolver_free(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_root_fdfsolver *arg1 = (gsl_root_fdfsolver *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_root_fdfsolver_free\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_root_fdfsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_root_fdfsolver_free\" \"', argument \" \"1\"\" of type '\" \"gsl_root_fdfsolver *\"\"'\"); \n  }\n  arg1 = (gsl_root_fdfsolver *)(argp1);\n  gsl_root_fdfsolver_free(arg1);\n  resultobj = SWIG_Py_Void();\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_root_fsolver_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_root_fsolver *arg1 = (gsl_root_fsolver *) 0 ;\n  gsl_function *arg2 = (gsl_function *) 0 ;\n  double arg3 ;\n  double arg4 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  void *argp2 = 0 ;\n  int res2 = 0 ;\n  double val3 ;\n  int ecode3 = 0 ;\n  double val4 ;\n  int ecode4 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  PyObject * obj3 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\",(char *) \"BUFFER\",(char *) \"X_LOWER\",(char *) \"X_UPPER\", NULL \n  };\n  int result;\n  \n  \n  gsl_function * volatile _solver2 = NULL;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOOO:gsl_root_fsolver_set\",kwnames,&obj0,&obj1,&obj2,&obj3)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_root_fsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_root_fsolver_set\" \"', argument \" \"1\"\" of type '\" \"gsl_root_fsolver *\"\"'\"); \n  }\n  arg1 = (gsl_root_fsolver *)(argp1);\n  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_gsl_function, 0 |  0 );\n  if (!SWIG_IsOK(res2)) {\n    SWIG_exception_fail(SWIG_ArgError(res2), \"in method '\" \"gsl_root_fsolver_set\" \"', argument \" \"2\"\" of type '\" \"gsl_function *\"\"'\"); \n  }\n  arg2 = (gsl_function *)(argp2);\n  ecode3 = SWIG_AsVal_double(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_root_fsolver_set\" \"', argument \" \"3\"\" of type '\" \"double\"\"'\");\n  } \n  arg3 = (double)(val3);\n  ecode4 = SWIG_AsVal_double(obj3, &val4);\n  if (!SWIG_IsOK(ecode4)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode4), \"in method '\" \"gsl_root_fsolver_set\" \"', argument \" \"4\"\" of type '\" \"double\"\"'\");\n  } \n  arg4 = (double)(val4);\n  {\n    int flag;\n    callback_function_params * p;\n    \n    FUNC_MESS(\"\\t\\t Setting jump buffer\");\n    assert(arg2);\n    \n    \n    _solver2 = arg2;\n    p = (callback_function_params *) \n    PyGSL_gsl_function_GET_PARAMS(_solver2);\n    \n    if((flag=setjmp(p->buffer)) == 0){\n      FUNC_MESS(\"\\t\\t Setting Jmp Buffer\");\n      p->buffer_is_set = 1;\n    } else {\n      FUNC_MESS(\"\\t\\t Returning from Jmp Buffer\");\n      p->buffer_is_set = 0;\n      goto fail;\n    }\n    \n    FUNC_MESS(\"\\t\\t END Setting jump buffer\");\n  }\n  result = (int)gsl_root_fsolver_set(arg1,arg2,arg3,arg4);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  {\n    callback_function_params * p;\n    if(_solver2){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params *)  \n      PyGSL_gsl_function_GET_PARAMS(_solver2);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  return resultobj;\nfail:\n  {\n    callback_function_params * p;\n    if(_solver2){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params *)  \n      PyGSL_gsl_function_GET_PARAMS(_solver2);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_root_fdfsolver_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_root_fdfsolver *arg1 = (gsl_root_fdfsolver *) 0 ;\n  gsl_function_fdf *arg2 = (gsl_function_fdf *) 0 ;\n  double arg3 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  void *argp2 = 0 ;\n  int res2 = 0 ;\n  double val3 ;\n  int ecode3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\",(char *) \"BUFFER\",(char *) \"ROOT\", NULL \n  };\n  int result;\n  \n  \n  gsl_function_fdf * volatile _solver2 = NULL;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_root_fdfsolver_set\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_root_fdfsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_root_fdfsolver_set\" \"', argument \" \"1\"\" of type '\" \"gsl_root_fdfsolver *\"\"'\"); \n  }\n  arg1 = (gsl_root_fdfsolver *)(argp1);\n  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_gsl_function_fdf, 0 |  0 );\n  if (!SWIG_IsOK(res2)) {\n    SWIG_exception_fail(SWIG_ArgError(res2), \"in method '\" \"gsl_root_fdfsolver_set\" \"', argument \" \"2\"\" of type '\" \"gsl_function_fdf *\"\"'\"); \n  }\n  arg2 = (gsl_function_fdf *)(argp2);\n  ecode3 = SWIG_AsVal_double(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_root_fdfsolver_set\" \"', argument \" \"3\"\" of type '\" \"double\"\"'\");\n  } \n  arg3 = (double)(val3);\n  {\n    int flag;\n    callback_function_params_fdf * p;\n    \n    FUNC_MESS(\"\\t\\t Setting jump buffer\");\n    assert(arg2);\n    \n    _solver2 = arg2;\n    p = (callback_function_params_fdf *) \n    PyGSL_gsl_function_fdf_GET_PARAMS(_solver2);\n    \n    if((flag=setjmp(p->buffer)) == 0){\n      FUNC_MESS(\"\\t\\t Setting Jmp Buffer\");\n      /* Set jump buffer */\n      p->buffer_is_set = 1;\n    } else {\n      FUNC_MESS(\"\\t\\t Returning from Jmp Buffer\");\n      p->buffer_is_set = 0;\n      goto fail;\n    }\n    \n    FUNC_MESS(\"\\t\\t END Setting jump buffer\");\n  }\n  result = (int)gsl_root_fdfsolver_set(arg1,arg2,arg3);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  {\n    callback_function_params_fdf * p;\n    if(_solver2){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params_fdf *)  \n      PyGSL_gsl_function_fdf_GET_PARAMS(_solver2);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  return resultobj;\nfail:\n  {\n    callback_function_params_fdf * p;\n    if(_solver2){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params_fdf *)  \n      PyGSL_gsl_function_fdf_GET_PARAMS(_solver2);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_root_fsolver_name(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_root_fsolver *arg1 = (gsl_root_fsolver *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"S\", NULL \n  };\n  char *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_root_fsolver_name\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_root_fsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_root_fsolver_name\" \"', argument \" \"1\"\" of type '\" \"gsl_root_fsolver const *\"\"'\"); \n  }\n  arg1 = (gsl_root_fsolver *)(argp1);\n  result = (char *)gsl_root_fsolver_name((gsl_root_fsolver const *)arg1);\n  resultobj = SWIG_FromCharPtr((const char *)result);\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_root_fdfsolver_name(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_root_fdfsolver *arg1 = (gsl_root_fdfsolver *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"S\", NULL \n  };\n  char *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_root_fdfsolver_name\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_root_fdfsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_root_fdfsolver_name\" \"', argument \" \"1\"\" of type '\" \"gsl_root_fdfsolver const *\"\"'\"); \n  }\n  arg1 = (gsl_root_fdfsolver *)(argp1);\n  result = (char *)gsl_root_fdfsolver_name((gsl_root_fdfsolver const *)arg1);\n  resultobj = SWIG_FromCharPtr((const char *)result);\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_root_fsolver_iterate(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_root_fsolver *arg1 = (gsl_root_fsolver *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"BUFFER\", NULL \n  };\n  int result;\n  \n  \n  gsl_root_fsolver * volatile _solver1 = NULL;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_root_fsolver_iterate\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_root_fsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_root_fsolver_iterate\" \"', argument \" \"1\"\" of type '\" \"gsl_root_fsolver *\"\"'\"); \n  }\n  arg1 = (gsl_root_fsolver *)(argp1);\n  {\n    int flag;\n    callback_function_params * p;\n    \n    FUNC_MESS(\"\\t\\t Setting jump buffer\");\n    assert(arg1);\n    \n    \n    _solver1 = arg1;\n    p = (callback_function_params *) \n    PyGSL_gsl_root_fsolver_GET_PARAMS(_solver1);\n    \n    if((flag=setjmp(p->buffer)) == 0){\n      FUNC_MESS(\"\\t\\t Setting Jmp Buffer\");\n      p->buffer_is_set = 1;\n    } else {\n      FUNC_MESS(\"\\t\\t Returning from Jmp Buffer\");\n      p->buffer_is_set = 0;\n      goto fail;\n    }\n    \n    FUNC_MESS(\"\\t\\t END Setting jump buffer\");\n  }\n  result = (int)gsl_root_fsolver_iterate(arg1);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  {\n    callback_function_params * p;\n    if(_solver1){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params *)  \n      PyGSL_gsl_root_fsolver_GET_PARAMS(_solver1);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  return resultobj;\nfail:\n  {\n    callback_function_params * p;\n    if(_solver1){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params *)  \n      PyGSL_gsl_root_fsolver_GET_PARAMS(_solver1);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_root_fdfsolver_iterate(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_root_fdfsolver *arg1 = (gsl_root_fdfsolver *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"BUFFER\", NULL \n  };\n  int result;\n  \n  \n  gsl_root_fdfsolver * volatile _solver1 = NULL;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_root_fdfsolver_iterate\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_root_fdfsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_root_fdfsolver_iterate\" \"', argument \" \"1\"\" of type '\" \"gsl_root_fdfsolver *\"\"'\"); \n  }\n  arg1 = (gsl_root_fdfsolver *)(argp1);\n  {\n    int flag;\n    callback_function_params_fdf * p;\n    \n    FUNC_MESS(\"\\t\\t Setting jump buffer\");\n    assert(arg1);\n    \n    _solver1 = arg1;\n    p = (callback_function_params_fdf *) \n    PyGSL_gsl_root_fdfsolver_GET_PARAMS(_solver1);\n    \n    if((flag=setjmp(p->buffer)) == 0){\n      FUNC_MESS(\"\\t\\t Setting Jmp Buffer\");\n      /* Set jump buffer */\n      p->buffer_is_set = 1;\n    } else {\n      FUNC_MESS(\"\\t\\t Returning from Jmp Buffer\");\n      p->buffer_is_set = 0;\n      goto fail;\n    }\n    \n    FUNC_MESS(\"\\t\\t END Setting jump buffer\");\n  }\n  result = (int)gsl_root_fdfsolver_iterate(arg1);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  {\n    callback_function_params_fdf * p;\n    if(_solver1){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params_fdf *)  \n      PyGSL_gsl_root_fdfsolver_GET_PARAMS(_solver1);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  return resultobj;\nfail:\n  {\n    callback_function_params_fdf * p;\n    if(_solver1){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params_fdf *)  \n      PyGSL_gsl_root_fdfsolver_GET_PARAMS(_solver1);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_root_fsolver_root(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_root_fsolver *arg1 = (gsl_root_fsolver *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"S\", NULL \n  };\n  double result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_root_fsolver_root\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_root_fsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_root_fsolver_root\" \"', argument \" \"1\"\" of type '\" \"gsl_root_fsolver const *\"\"'\"); \n  }\n  arg1 = (gsl_root_fsolver *)(argp1);\n  result = (double)gsl_root_fsolver_root((gsl_root_fsolver const *)arg1);\n  resultobj = SWIG_From_double((double)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_root_fdfsolver_root(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_root_fdfsolver *arg1 = (gsl_root_fdfsolver *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"S\", NULL \n  };\n  double result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_root_fdfsolver_root\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_root_fdfsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_root_fdfsolver_root\" \"', argument \" \"1\"\" of type '\" \"gsl_root_fdfsolver const *\"\"'\"); \n  }\n  arg1 = (gsl_root_fdfsolver *)(argp1);\n  result = (double)gsl_root_fdfsolver_root((gsl_root_fdfsolver const *)arg1);\n  resultobj = SWIG_From_double((double)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_root_fsolver_x_lower(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_root_fsolver *arg1 = (gsl_root_fsolver *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"S\", NULL \n  };\n  double result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_root_fsolver_x_lower\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_root_fsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_root_fsolver_x_lower\" \"', argument \" \"1\"\" of type '\" \"gsl_root_fsolver const *\"\"'\"); \n  }\n  arg1 = (gsl_root_fsolver *)(argp1);\n  result = (double)gsl_root_fsolver_x_lower((gsl_root_fsolver const *)arg1);\n  resultobj = SWIG_From_double((double)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_root_fsolver_x_upper(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_root_fsolver *arg1 = (gsl_root_fsolver *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"S\", NULL \n  };\n  double result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_root_fsolver_x_upper\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_root_fsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_root_fsolver_x_upper\" \"', argument \" \"1\"\" of type '\" \"gsl_root_fsolver const *\"\"'\"); \n  }\n  arg1 = (gsl_root_fsolver *)(argp1);\n  result = (double)gsl_root_fsolver_x_upper((gsl_root_fsolver const *)arg1);\n  resultobj = SWIG_From_double((double)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_root_test_interval(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  double arg1 ;\n  double arg2 ;\n  double arg3 ;\n  double arg4 ;\n  double val1 ;\n  int ecode1 = 0 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  double val3 ;\n  int ecode3 = 0 ;\n  double val4 ;\n  int ecode4 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  PyObject * obj3 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"X_LOWER\",(char *) \"X_UPPER\",(char *) \"EPSABS\",(char *) \"EPSREL\", NULL \n  };\n  int result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOOO:gsl_root_test_interval\",kwnames,&obj0,&obj1,&obj2,&obj3)) SWIG_fail;\n  ecode1 = SWIG_AsVal_double(obj0, &val1);\n  if (!SWIG_IsOK(ecode1)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode1), \"in method '\" \"gsl_root_test_interval\" \"', argument \" \"1\"\" of type '\" \"double\"\"'\");\n  } \n  arg1 = (double)(val1);\n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_root_test_interval\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  ecode3 = SWIG_AsVal_double(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_root_test_interval\" \"', argument \" \"3\"\" of type '\" \"double\"\"'\");\n  } \n  arg3 = (double)(val3);\n  ecode4 = SWIG_AsVal_double(obj3, &val4);\n  if (!SWIG_IsOK(ecode4)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode4), \"in method '\" \"gsl_root_test_interval\" \"', argument \" \"4\"\" of type '\" \"double\"\"'\");\n  } \n  arg4 = (double)(val4);\n  result = (int)gsl_root_test_interval(arg1,arg2,arg3,arg4);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_root_test_delta(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  double arg1 ;\n  double arg2 ;\n  double arg3 ;\n  double arg4 ;\n  double val1 ;\n  int ecode1 = 0 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  double val3 ;\n  int ecode3 = 0 ;\n  double val4 ;\n  int ecode4 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  PyObject * obj3 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"X1\",(char *) \"X0\",(char *) \"EPSREL\",(char *) \"EPSABS\", NULL \n  };\n  int result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOOO:gsl_root_test_delta\",kwnames,&obj0,&obj1,&obj2,&obj3)) SWIG_fail;\n  ecode1 = SWIG_AsVal_double(obj0, &val1);\n  if (!SWIG_IsOK(ecode1)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode1), \"in method '\" \"gsl_root_test_delta\" \"', argument \" \"1\"\" of type '\" \"double\"\"'\");\n  } \n  arg1 = (double)(val1);\n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_root_test_delta\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  ecode3 = SWIG_AsVal_double(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_root_test_delta\" \"', argument \" \"3\"\" of type '\" \"double\"\"'\");\n  } \n  arg3 = (double)(val3);\n  ecode4 = SWIG_AsVal_double(obj3, &val4);\n  if (!SWIG_IsOK(ecode4)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode4), \"in method '\" \"gsl_root_test_delta\" \"', argument \" \"4\"\" of type '\" \"double\"\"'\");\n  } \n  arg4 = (double)(val4);\n  result = (int)gsl_root_test_delta(arg1,arg2,arg3,arg4);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_root_test_residual(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  double arg1 ;\n  double arg2 ;\n  double val1 ;\n  int ecode1 = 0 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"F\",(char *) \"EPSABS\", NULL \n  };\n  int result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_root_test_residual\",kwnames,&obj0,&obj1)) SWIG_fail;\n  ecode1 = SWIG_AsVal_double(obj0, &val1);\n  if (!SWIG_IsOK(ecode1)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode1), \"in method '\" \"gsl_root_test_residual\" \"', argument \" \"1\"\" of type '\" \"double\"\"'\");\n  } \n  arg1 = (double)(val1);\n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_root_test_residual\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  result = (int)gsl_root_test_residual(arg1,arg2);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN int Swig_var_gsl_min_fminimizer_goldensection_set(PyObject *_val SWIGUNUSED) {\n  SWIG_Error(SWIG_AttributeError,\"Variable gsl_min_fminimizer_goldensection is read-only.\");\n  return 1;\n}\n\n\nSWIGINTERN PyObject *Swig_var_gsl_min_fminimizer_goldensection_get(void) {\n  PyObject *pyobj = 0;\n  \n  pyobj = SWIG_NewPointerObj(SWIG_as_voidptr(gsl_min_fminimizer_goldensection), SWIGTYPE_p_gsl_min_fminimizer_type,  0 );\n  return pyobj;\n}\n\n\nSWIGINTERN int Swig_var_gsl_min_fminimizer_brent_set(PyObject *_val SWIGUNUSED) {\n  SWIG_Error(SWIG_AttributeError,\"Variable gsl_min_fminimizer_brent is read-only.\");\n  return 1;\n}\n\n\nSWIGINTERN PyObject *Swig_var_gsl_min_fminimizer_brent_get(void) {\n  PyObject *pyobj = 0;\n  \n  pyobj = SWIG_NewPointerObj(SWIG_as_voidptr(gsl_min_fminimizer_brent), SWIGTYPE_p_gsl_min_fminimizer_type,  0 );\n  return pyobj;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_min_fminimizer_alloc(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_min_fminimizer_type *arg1 = (gsl_min_fminimizer_type *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"T\", NULL \n  };\n  gsl_min_fminimizer *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_min_fminimizer_alloc\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_min_fminimizer_type, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_min_fminimizer_alloc\" \"', argument \" \"1\"\" of type '\" \"gsl_min_fminimizer_type const *\"\"'\"); \n  }\n  arg1 = (gsl_min_fminimizer_type *)(argp1);\n  result = (gsl_min_fminimizer *)gsl_min_fminimizer_alloc((gsl_min_fminimizer_type const *)arg1);\n  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_gsl_min_fminimizer, 0 |  0 );\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_min_fminimizer_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_min_fminimizer *arg1 = (gsl_min_fminimizer *) 0 ;\n  gsl_function *arg2 = (gsl_function *) 0 ;\n  double arg3 ;\n  double arg4 ;\n  double arg5 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  void *argp2 = 0 ;\n  int res2 = 0 ;\n  double val3 ;\n  int ecode3 = 0 ;\n  double val4 ;\n  int ecode4 = 0 ;\n  double val5 ;\n  int ecode5 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  PyObject * obj3 = 0 ;\n  PyObject * obj4 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\",(char *) \"BUFFER\",(char *) \"X_MINIMUM\",(char *) \"X_LOWER\",(char *) \"X_UPPER\", NULL \n  };\n  int result;\n  \n  \n  gsl_function * volatile _solver2 = NULL;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOOOO:gsl_min_fminimizer_set\",kwnames,&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_min_fminimizer, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_min_fminimizer_set\" \"', argument \" \"1\"\" of type '\" \"gsl_min_fminimizer *\"\"'\"); \n  }\n  arg1 = (gsl_min_fminimizer *)(argp1);\n  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_gsl_function, 0 |  0 );\n  if (!SWIG_IsOK(res2)) {\n    SWIG_exception_fail(SWIG_ArgError(res2), \"in method '\" \"gsl_min_fminimizer_set\" \"', argument \" \"2\"\" of type '\" \"gsl_function *\"\"'\"); \n  }\n  arg2 = (gsl_function *)(argp2);\n  ecode3 = SWIG_AsVal_double(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_min_fminimizer_set\" \"', argument \" \"3\"\" of type '\" \"double\"\"'\");\n  } \n  arg3 = (double)(val3);\n  ecode4 = SWIG_AsVal_double(obj3, &val4);\n  if (!SWIG_IsOK(ecode4)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode4), \"in method '\" \"gsl_min_fminimizer_set\" \"', argument \" \"4\"\" of type '\" \"double\"\"'\");\n  } \n  arg4 = (double)(val4);\n  ecode5 = SWIG_AsVal_double(obj4, &val5);\n  if (!SWIG_IsOK(ecode5)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode5), \"in method '\" \"gsl_min_fminimizer_set\" \"', argument \" \"5\"\" of type '\" \"double\"\"'\");\n  } \n  arg5 = (double)(val5);\n  {\n    int flag;\n    callback_function_params * p;\n    \n    FUNC_MESS(\"\\t\\t Setting jump buffer\");\n    assert(arg2);\n    \n    \n    _solver2 = arg2;\n    p = (callback_function_params *) \n    PyGSL_gsl_function_GET_PARAMS(_solver2);\n    \n    if((flag=setjmp(p->buffer)) == 0){\n      FUNC_MESS(\"\\t\\t Setting Jmp Buffer\");\n      p->buffer_is_set = 1;\n    } else {\n      FUNC_MESS(\"\\t\\t Returning from Jmp Buffer\");\n      p->buffer_is_set = 0;\n      goto fail;\n    }\n    \n    FUNC_MESS(\"\\t\\t END Setting jump buffer\");\n  }\n  result = (int)gsl_min_fminimizer_set(arg1,arg2,arg3,arg4,arg5);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  {\n    callback_function_params * p;\n    if(_solver2){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params *)  \n      PyGSL_gsl_function_GET_PARAMS(_solver2);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  return resultobj;\nfail:\n  {\n    callback_function_params * p;\n    if(_solver2){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params *)  \n      PyGSL_gsl_function_GET_PARAMS(_solver2);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_min_fminimizer_set_with_values(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_min_fminimizer *arg1 = (gsl_min_fminimizer *) 0 ;\n  gsl_function *arg2 = (gsl_function *) 0 ;\n  double arg3 ;\n  double arg4 ;\n  double arg5 ;\n  double arg6 ;\n  double arg7 ;\n  double arg8 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  void *argp2 = 0 ;\n  int res2 = 0 ;\n  double val3 ;\n  int ecode3 = 0 ;\n  double val4 ;\n  int ecode4 = 0 ;\n  double val5 ;\n  int ecode5 = 0 ;\n  double val6 ;\n  int ecode6 = 0 ;\n  double val7 ;\n  int ecode7 = 0 ;\n  double val8 ;\n  int ecode8 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  PyObject * obj3 = 0 ;\n  PyObject * obj4 = 0 ;\n  PyObject * obj5 = 0 ;\n  PyObject * obj6 = 0 ;\n  PyObject * obj7 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\",(char *) \"BUFFER\",(char *) \"X_MINIMUM\",(char *) \"F_MINIMUM\",(char *) \"X_LOWER\",(char *) \"F_LOWER\",(char *) \"X_UPPER\",(char *) \"F_UPPER\", NULL \n  };\n  int result;\n  \n  \n  gsl_function * volatile _solver2 = NULL;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOOOOOOO:gsl_min_fminimizer_set_with_values\",kwnames,&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_min_fminimizer, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_min_fminimizer_set_with_values\" \"', argument \" \"1\"\" of type '\" \"gsl_min_fminimizer *\"\"'\"); \n  }\n  arg1 = (gsl_min_fminimizer *)(argp1);\n  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_gsl_function, 0 |  0 );\n  if (!SWIG_IsOK(res2)) {\n    SWIG_exception_fail(SWIG_ArgError(res2), \"in method '\" \"gsl_min_fminimizer_set_with_values\" \"', argument \" \"2\"\" of type '\" \"gsl_function *\"\"'\"); \n  }\n  arg2 = (gsl_function *)(argp2);\n  ecode3 = SWIG_AsVal_double(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_min_fminimizer_set_with_values\" \"', argument \" \"3\"\" of type '\" \"double\"\"'\");\n  } \n  arg3 = (double)(val3);\n  ecode4 = SWIG_AsVal_double(obj3, &val4);\n  if (!SWIG_IsOK(ecode4)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode4), \"in method '\" \"gsl_min_fminimizer_set_with_values\" \"', argument \" \"4\"\" of type '\" \"double\"\"'\");\n  } \n  arg4 = (double)(val4);\n  ecode5 = SWIG_AsVal_double(obj4, &val5);\n  if (!SWIG_IsOK(ecode5)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode5), \"in method '\" \"gsl_min_fminimizer_set_with_values\" \"', argument \" \"5\"\" of type '\" \"double\"\"'\");\n  } \n  arg5 = (double)(val5);\n  ecode6 = SWIG_AsVal_double(obj5, &val6);\n  if (!SWIG_IsOK(ecode6)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode6), \"in method '\" \"gsl_min_fminimizer_set_with_values\" \"', argument \" \"6\"\" of type '\" \"double\"\"'\");\n  } \n  arg6 = (double)(val6);\n  ecode7 = SWIG_AsVal_double(obj6, &val7);\n  if (!SWIG_IsOK(ecode7)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode7), \"in method '\" \"gsl_min_fminimizer_set_with_values\" \"', argument \" \"7\"\" of type '\" \"double\"\"'\");\n  } \n  arg7 = (double)(val7);\n  ecode8 = SWIG_AsVal_double(obj7, &val8);\n  if (!SWIG_IsOK(ecode8)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode8), \"in method '\" \"gsl_min_fminimizer_set_with_values\" \"', argument \" \"8\"\" of type '\" \"double\"\"'\");\n  } \n  arg8 = (double)(val8);\n  {\n    int flag;\n    callback_function_params * p;\n    \n    FUNC_MESS(\"\\t\\t Setting jump buffer\");\n    assert(arg2);\n    \n    \n    _solver2 = arg2;\n    p = (callback_function_params *) \n    PyGSL_gsl_function_GET_PARAMS(_solver2);\n    \n    if((flag=setjmp(p->buffer)) == 0){\n      FUNC_MESS(\"\\t\\t Setting Jmp Buffer\");\n      p->buffer_is_set = 1;\n    } else {\n      FUNC_MESS(\"\\t\\t Returning from Jmp Buffer\");\n      p->buffer_is_set = 0;\n      goto fail;\n    }\n    \n    FUNC_MESS(\"\\t\\t END Setting jump buffer\");\n  }\n  result = (int)gsl_min_fminimizer_set_with_values(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  {\n    callback_function_params * p;\n    if(_solver2){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params *)  \n      PyGSL_gsl_function_GET_PARAMS(_solver2);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  return resultobj;\nfail:\n  {\n    callback_function_params * p;\n    if(_solver2){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params *)  \n      PyGSL_gsl_function_GET_PARAMS(_solver2);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_min_fminimizer_free(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_min_fminimizer *arg1 = (gsl_min_fminimizer *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"S\", NULL \n  };\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_min_fminimizer_free\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_min_fminimizer, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_min_fminimizer_free\" \"', argument \" \"1\"\" of type '\" \"gsl_min_fminimizer *\"\"'\"); \n  }\n  arg1 = (gsl_min_fminimizer *)(argp1);\n  gsl_min_fminimizer_free(arg1);\n  resultobj = SWIG_Py_Void();\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_min_fminimizer_name(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_min_fminimizer *arg1 = (gsl_min_fminimizer *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"S\", NULL \n  };\n  char *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_min_fminimizer_name\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_min_fminimizer, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_min_fminimizer_name\" \"', argument \" \"1\"\" of type '\" \"gsl_min_fminimizer const *\"\"'\"); \n  }\n  arg1 = (gsl_min_fminimizer *)(argp1);\n  result = (char *)gsl_min_fminimizer_name((gsl_min_fminimizer const *)arg1);\n  resultobj = SWIG_FromCharPtr((const char *)result);\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_min_fminimizer_iterate(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_min_fminimizer *arg1 = (gsl_min_fminimizer *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"BUFFER\", NULL \n  };\n  int result;\n  \n  \n  gsl_min_fminimizer * volatile _solver1 = NULL;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_min_fminimizer_iterate\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_min_fminimizer, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_min_fminimizer_iterate\" \"', argument \" \"1\"\" of type '\" \"gsl_min_fminimizer *\"\"'\"); \n  }\n  arg1 = (gsl_min_fminimizer *)(argp1);\n  {\n    int flag;\n    callback_function_params * p;\n    \n    FUNC_MESS(\"\\t\\t Setting jump buffer\");\n    assert(arg1);\n    \n    \n    _solver1 = arg1;\n    p = (callback_function_params *) \n    PyGSL_gsl_min_fminimizer_GET_PARAMS(_solver1);\n    \n    if((flag=setjmp(p->buffer)) == 0){\n      FUNC_MESS(\"\\t\\t Setting Jmp Buffer\");\n      p->buffer_is_set = 1;\n    } else {\n      FUNC_MESS(\"\\t\\t Returning from Jmp Buffer\");\n      p->buffer_is_set = 0;\n      goto fail;\n    }\n    \n    FUNC_MESS(\"\\t\\t END Setting jump buffer\");\n  }\n  result = (int)gsl_min_fminimizer_iterate(arg1);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  {\n    callback_function_params * p;\n    if(_solver1){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params *)  \n      PyGSL_gsl_min_fminimizer_GET_PARAMS(_solver1);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  return resultobj;\nfail:\n  {\n    callback_function_params * p;\n    if(_solver1){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params *)  \n      PyGSL_gsl_min_fminimizer_GET_PARAMS(_solver1);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_min_fminimizer_minimum(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_min_fminimizer *arg1 = (gsl_min_fminimizer *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"S\", NULL \n  };\n  double result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_min_fminimizer_minimum\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_min_fminimizer, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_min_fminimizer_minimum\" \"', argument \" \"1\"\" of type '\" \"gsl_min_fminimizer const *\"\"'\"); \n  }\n  arg1 = (gsl_min_fminimizer *)(argp1);\n  result = (double)gsl_min_fminimizer_minimum((gsl_min_fminimizer const *)arg1);\n  resultobj = SWIG_From_double((double)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_min_fminimizer_x_upper(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_min_fminimizer *arg1 = (gsl_min_fminimizer *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"S\", NULL \n  };\n  double result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_min_fminimizer_x_upper\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_min_fminimizer, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_min_fminimizer_x_upper\" \"', argument \" \"1\"\" of type '\" \"gsl_min_fminimizer const *\"\"'\"); \n  }\n  arg1 = (gsl_min_fminimizer *)(argp1);\n  result = (double)gsl_min_fminimizer_x_upper((gsl_min_fminimizer const *)arg1);\n  resultobj = SWIG_From_double((double)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_min_fminimizer_x_lower(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_min_fminimizer *arg1 = (gsl_min_fminimizer *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"S\", NULL \n  };\n  double result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_min_fminimizer_x_lower\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_min_fminimizer, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_min_fminimizer_x_lower\" \"', argument \" \"1\"\" of type '\" \"gsl_min_fminimizer const *\"\"'\"); \n  }\n  arg1 = (gsl_min_fminimizer *)(argp1);\n  result = (double)gsl_min_fminimizer_x_lower((gsl_min_fminimizer const *)arg1);\n  resultobj = SWIG_From_double((double)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_min_test_interval(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  double arg1 ;\n  double arg2 ;\n  double arg3 ;\n  double arg4 ;\n  double val1 ;\n  int ecode1 = 0 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  double val3 ;\n  int ecode3 = 0 ;\n  double val4 ;\n  int ecode4 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  PyObject * obj3 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"X_LOWER\",(char *) \"X_UPPER\",(char *) \"EPSABS\",(char *) \"EPSREL\", NULL \n  };\n  int result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOOO:gsl_min_test_interval\",kwnames,&obj0,&obj1,&obj2,&obj3)) SWIG_fail;\n  ecode1 = SWIG_AsVal_double(obj0, &val1);\n  if (!SWIG_IsOK(ecode1)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode1), \"in method '\" \"gsl_min_test_interval\" \"', argument \" \"1\"\" of type '\" \"double\"\"'\");\n  } \n  arg1 = (double)(val1);\n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_min_test_interval\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  ecode3 = SWIG_AsVal_double(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_min_test_interval\" \"', argument \" \"3\"\" of type '\" \"double\"\"'\");\n  } \n  arg3 = (double)(val3);\n  ecode4 = SWIG_AsVal_double(obj3, &val4);\n  if (!SWIG_IsOK(ecode4)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode4), \"in method '\" \"gsl_min_test_interval\" \"', argument \" \"4\"\" of type '\" \"double\"\"'\");\n  } \n  arg4 = (double)(val4);\n  result = (int)gsl_min_test_interval(arg1,arg2,arg3,arg4);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multiroot_function_init(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multiroot_function *arg1 = (gsl_multiroot_function *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"STORE\", NULL \n  };\n  gsl_multiroot_function *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multiroot_function_init\",kwnames,&obj0)) SWIG_fail;\n  {\n    FUNC_MESS(\"gsl_function STORE BEGIN\");\n    arg1 = PyGSL_convert_to_gsl_multiroot_function (obj0);\n    FUNC_MESS(\"gsl_function STORE END\");\n    if(arg1==NULL) goto fail;\n  }\n  result = (gsl_multiroot_function *)gsl_multiroot_function_init(arg1);\n  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_gsl_multiroot_function, 0 |  0 );\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multiroot_function_init_fdf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multiroot_function_fdf *arg1 = (gsl_multiroot_function_fdf *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"STORE\", NULL \n  };\n  gsl_multiroot_function_fdf *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multiroot_function_init_fdf\",kwnames,&obj0)) SWIG_fail;\n  {\n    FUNC_MESS(\"gsl_function STORE BEGIN\");\n    arg1 = PyGSL_convert_to_gsl_multiroot_function_fdf (obj0);\n    FUNC_MESS(\"gsl_function STORE END\");\n    if(arg1==NULL) goto fail;\n  }\n  result = (gsl_multiroot_function_fdf *)gsl_multiroot_function_init_fdf(arg1);\n  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_gsl_multiroot_function_fdf, 0 |  0 );\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multiroot_function_getf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multiroot_fsolver *arg1 = (gsl_multiroot_fsolver *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  gsl_multiroot_solver_data *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multiroot_function_getf\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multiroot_fsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multiroot_function_getf\" \"', argument \" \"1\"\" of type '\" \"gsl_multiroot_fsolver *\"\"'\"); \n  }\n  arg1 = (gsl_multiroot_fsolver *)(argp1);\n  result = (gsl_multiroot_solver_data *)gsl_multiroot_function_getf(arg1);\n  {\n    PyArrayObject *a_array;  \n    a_array = PyGSL_copy_gslvector_to_pyarray(result);\n    resultobj = (PyObject *) a_array;\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multiroot_function_fdf_getf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multiroot_fdfsolver *arg1 = (gsl_multiroot_fdfsolver *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  gsl_multiroot_solver_data *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multiroot_function_fdf_getf\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multiroot_fdfsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multiroot_function_fdf_getf\" \"', argument \" \"1\"\" of type '\" \"gsl_multiroot_fdfsolver *\"\"'\"); \n  }\n  arg1 = (gsl_multiroot_fdfsolver *)(argp1);\n  result = (gsl_multiroot_solver_data *)gsl_multiroot_function_fdf_getf(arg1);\n  {\n    PyArrayObject *a_array;  \n    a_array = PyGSL_copy_gslvector_to_pyarray(result);\n    resultobj = (PyObject *) a_array;\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multiroot_function_getx(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multiroot_fsolver *arg1 = (gsl_multiroot_fsolver *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  gsl_multiroot_solver_data *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multiroot_function_getx\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multiroot_fsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multiroot_function_getx\" \"', argument \" \"1\"\" of type '\" \"gsl_multiroot_fsolver *\"\"'\"); \n  }\n  arg1 = (gsl_multiroot_fsolver *)(argp1);\n  result = (gsl_multiroot_solver_data *)gsl_multiroot_function_getx(arg1);\n  {\n    PyArrayObject *a_array;  \n    a_array = PyGSL_copy_gslvector_to_pyarray(result);\n    resultobj = (PyObject *) a_array;\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multiroot_function_fdf_getx(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multiroot_fdfsolver *arg1 = (gsl_multiroot_fdfsolver *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  gsl_multiroot_solver_data *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multiroot_function_fdf_getx\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multiroot_fdfsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multiroot_function_fdf_getx\" \"', argument \" \"1\"\" of type '\" \"gsl_multiroot_fdfsolver *\"\"'\"); \n  }\n  arg1 = (gsl_multiroot_fdfsolver *)(argp1);\n  result = (gsl_multiroot_solver_data *)gsl_multiroot_function_fdf_getx(arg1);\n  {\n    PyArrayObject *a_array;  \n    a_array = PyGSL_copy_gslvector_to_pyarray(result);\n    resultobj = (PyObject *) a_array;\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multiroot_function_free(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multiroot_function *arg1 = (gsl_multiroot_function *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"FREE\", NULL \n  };\n  \n  \n  gsl_multiroot_function *_function1 = NULL;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multiroot_function_free\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multiroot_function, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multiroot_function_free\" \"', argument \" \"1\"\" of type '\" \"gsl_multiroot_function *\"\"'\"); \n  }\n  arg1 = (gsl_multiroot_function *)(argp1);\n  {\n    DEBUG_MESS(2, \"gsl_function STORE IN ptr @ %p\", arg1);\n    if(arg1==NULL) goto fail;\n    \n    _function1 = arg1;\n  }\n  gsl_multiroot_function_free(arg1);\n  resultobj = SWIG_Py_Void();\n  {\n    DEBUG_MESS(2, \"gsl_function freeing %p\", _function1);\n    if(_function1){\n      assert(arg1 == _function1);\n      PyGSL_params_free((callback_function_params *) arg1->params);\n      free(arg1);    \n    }\n    _function1 = NULL;\n    DEBUG_MESS(2, \"gsl_function freed %p\", _function1);\n    \n  }\n  return resultobj;\nfail:\n  {\n    DEBUG_MESS(2, \"gsl_function freeing %p\", _function1);\n    if(_function1){\n      assert(arg1 == _function1);\n      PyGSL_params_free((callback_function_params *) arg1->params);\n      free(arg1);    \n    }\n    _function1 = NULL;\n    DEBUG_MESS(2, \"gsl_function freed %p\", _function1);\n    \n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multiroot_function_free_fdf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multiroot_function_fdf *arg1 = (gsl_multiroot_function_fdf *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"FREE\", NULL \n  };\n  \n  \n  gsl_multiroot_function_fdf *_function1 = NULL;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multiroot_function_free_fdf\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multiroot_function_fdf, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multiroot_function_free_fdf\" \"', argument \" \"1\"\" of type '\" \"gsl_multiroot_function_fdf *\"\"'\"); \n  }\n  arg1 = (gsl_multiroot_function_fdf *)(argp1);\n  {\n    DEBUG_MESS(2, \"gsl_function STORE IN ptr @ %p\", arg1);\n    if(arg1==NULL) goto fail;\n    \n    _function1 = arg1;\n  }\n  gsl_multiroot_function_free_fdf(arg1);\n  resultobj = SWIG_Py_Void();\n  {\n    DEBUG_MESS(2, \"gsl_function freeing %p\", _function1);\n    if(_function1){\n      assert(arg1 == _function1);\n      PyGSL_params_free((callback_function_params *) arg1->params);\n      free(arg1);    \n    }\n    _function1 = NULL;\n    DEBUG_MESS(2, \"gsl_function freed %p\", _function1);\n    \n  }\n  return resultobj;\nfail:\n  {\n    DEBUG_MESS(2, \"gsl_function freeing %p\", _function1);\n    if(_function1){\n      assert(arg1 == _function1);\n      PyGSL_params_free((callback_function_params *) arg1->params);\n      free(arg1);    \n    }\n    _function1 = NULL;\n    DEBUG_MESS(2, \"gsl_function freed %p\", _function1);\n    \n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multiroot_fsolver_alloc(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multiroot_fsolver_type *arg1 = (gsl_multiroot_fsolver_type *) 0 ;\n  size_t arg2 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"T\",(char *) \"n\", NULL \n  };\n  gsl_multiroot_fsolver *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_multiroot_fsolver_alloc\",kwnames,&obj0,&obj1)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multiroot_fsolver_type, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multiroot_fsolver_alloc\" \"', argument \" \"1\"\" of type '\" \"gsl_multiroot_fsolver_type const *\"\"'\"); \n  }\n  arg1 = (gsl_multiroot_fsolver_type *)(argp1);\n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_multiroot_fsolver_alloc\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  result = (gsl_multiroot_fsolver *)gsl_multiroot_fsolver_alloc((gsl_multiroot_fsolver_type const *)arg1,arg2);\n  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_gsl_multiroot_fsolver, 0 |  0 );\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multiroot_fsolver_free(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multiroot_fsolver *arg1 = (gsl_multiroot_fsolver *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multiroot_fsolver_free\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multiroot_fsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multiroot_fsolver_free\" \"', argument \" \"1\"\" of type '\" \"gsl_multiroot_fsolver *\"\"'\"); \n  }\n  arg1 = (gsl_multiroot_fsolver *)(argp1);\n  gsl_multiroot_fsolver_free(arg1);\n  resultobj = SWIG_Py_Void();\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multiroot_fsolver_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multiroot_fsolver *arg1 = (gsl_multiroot_fsolver *) 0 ;\n  gsl_multiroot_function *arg2 = (gsl_multiroot_function *) 0 ;\n  gsl_vector *arg3 = (gsl_vector *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  void *argp2 = 0 ;\n  int res2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\",(char *) \"f\",(char *) \"IN\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector3 = NULL;\n  TYPE_VIEW_gsl_vector _vector3;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_multiroot_fsolver_set\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multiroot_fsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multiroot_fsolver_set\" \"', argument \" \"1\"\" of type '\" \"gsl_multiroot_fsolver *\"\"'\"); \n  }\n  arg1 = (gsl_multiroot_fsolver *)(argp1);\n  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_gsl_multiroot_function, 0 |  0 );\n  if (!SWIG_IsOK(res2)) {\n    SWIG_exception_fail(SWIG_ArgError(res2), \"in method '\" \"gsl_multiroot_fsolver_set\" \"', argument \" \"2\"\" of type '\" \"gsl_multiroot_function *\"\"'\"); \n  }\n  arg2 = (gsl_multiroot_function *)(argp2);\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj2, arg3, _PyVector3, _vector3,\n        PyGSL_INPUT_ARRAY, gsl_vector, 3, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_multiroot_fsolver_set(arg1,arg2,arg3);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  {\n    Py_XDECREF(_PyVector3);\n    _PyVector3 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyVector3);\n    _PyVector3 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multiroot_fsolver_iterate(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multiroot_fsolver *arg1 = (gsl_multiroot_fsolver *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  int result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multiroot_fsolver_iterate\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multiroot_fsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multiroot_fsolver_iterate\" \"', argument \" \"1\"\" of type '\" \"gsl_multiroot_fsolver *\"\"'\"); \n  }\n  arg1 = (gsl_multiroot_fsolver *)(argp1);\n  result = (int)gsl_multiroot_fsolver_iterate(arg1);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multiroot_fsolver_name(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multiroot_fsolver *arg1 = (gsl_multiroot_fsolver *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  char *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multiroot_fsolver_name\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multiroot_fsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multiroot_fsolver_name\" \"', argument \" \"1\"\" of type '\" \"gsl_multiroot_fsolver const *\"\"'\"); \n  }\n  arg1 = (gsl_multiroot_fsolver *)(argp1);\n  result = (char *)gsl_multiroot_fsolver_name((gsl_multiroot_fsolver const *)arg1);\n  resultobj = SWIG_FromCharPtr((const char *)result);\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multiroot_fsolver_root(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multiroot_fsolver *arg1 = (gsl_multiroot_fsolver *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  gsl_vector *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multiroot_fsolver_root\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multiroot_fsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multiroot_fsolver_root\" \"', argument \" \"1\"\" of type '\" \"gsl_multiroot_fsolver const *\"\"'\"); \n  }\n  arg1 = (gsl_multiroot_fsolver *)(argp1);\n  result = (gsl_vector *)gsl_multiroot_fsolver_root((gsl_multiroot_fsolver const *)arg1);\n  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_gsl_vector, 0 |  0 );\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multiroot_fdfsolver_alloc(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multiroot_fdfsolver_type *arg1 = (gsl_multiroot_fdfsolver_type *) 0 ;\n  size_t arg2 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"T\",(char *) \"n\", NULL \n  };\n  gsl_multiroot_fdfsolver *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_multiroot_fdfsolver_alloc\",kwnames,&obj0,&obj1)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multiroot_fdfsolver_type, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multiroot_fdfsolver_alloc\" \"', argument \" \"1\"\" of type '\" \"gsl_multiroot_fdfsolver_type const *\"\"'\"); \n  }\n  arg1 = (gsl_multiroot_fdfsolver_type *)(argp1);\n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_multiroot_fdfsolver_alloc\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  result = (gsl_multiroot_fdfsolver *)gsl_multiroot_fdfsolver_alloc((gsl_multiroot_fdfsolver_type const *)arg1,arg2);\n  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_gsl_multiroot_fdfsolver, 0 |  0 );\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multiroot_fdfsolver_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multiroot_fdfsolver *arg1 = (gsl_multiroot_fdfsolver *) 0 ;\n  gsl_multiroot_function_fdf *arg2 = (gsl_multiroot_function_fdf *) 0 ;\n  gsl_vector *arg3 = (gsl_vector *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  void *argp2 = 0 ;\n  int res2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\",(char *) \"fdf\",(char *) \"IN\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector3 = NULL;\n  TYPE_VIEW_gsl_vector _vector3;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_multiroot_fdfsolver_set\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multiroot_fdfsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multiroot_fdfsolver_set\" \"', argument \" \"1\"\" of type '\" \"gsl_multiroot_fdfsolver *\"\"'\"); \n  }\n  arg1 = (gsl_multiroot_fdfsolver *)(argp1);\n  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_gsl_multiroot_function_fdf, 0 |  0 );\n  if (!SWIG_IsOK(res2)) {\n    SWIG_exception_fail(SWIG_ArgError(res2), \"in method '\" \"gsl_multiroot_fdfsolver_set\" \"', argument \" \"2\"\" of type '\" \"gsl_multiroot_function_fdf *\"\"'\"); \n  }\n  arg2 = (gsl_multiroot_function_fdf *)(argp2);\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj2, arg3, _PyVector3, _vector3,\n        PyGSL_INPUT_ARRAY, gsl_vector, 3, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_multiroot_fdfsolver_set(arg1,arg2,arg3);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  {\n    Py_XDECREF(_PyVector3);\n    _PyVector3 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyVector3);\n    _PyVector3 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multiroot_fdfsolver_iterate(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multiroot_fdfsolver *arg1 = (gsl_multiroot_fdfsolver *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  int result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multiroot_fdfsolver_iterate\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multiroot_fdfsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multiroot_fdfsolver_iterate\" \"', argument \" \"1\"\" of type '\" \"gsl_multiroot_fdfsolver *\"\"'\"); \n  }\n  arg1 = (gsl_multiroot_fdfsolver *)(argp1);\n  result = (int)gsl_multiroot_fdfsolver_iterate(arg1);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multiroot_fdfsolver_free(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multiroot_fdfsolver *arg1 = (gsl_multiroot_fdfsolver *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multiroot_fdfsolver_free\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multiroot_fdfsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multiroot_fdfsolver_free\" \"', argument \" \"1\"\" of type '\" \"gsl_multiroot_fdfsolver *\"\"'\"); \n  }\n  arg1 = (gsl_multiroot_fdfsolver *)(argp1);\n  gsl_multiroot_fdfsolver_free(arg1);\n  resultobj = SWIG_Py_Void();\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multiroot_fdfsolver_name(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multiroot_fdfsolver *arg1 = (gsl_multiroot_fdfsolver *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  char *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multiroot_fdfsolver_name\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multiroot_fdfsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multiroot_fdfsolver_name\" \"', argument \" \"1\"\" of type '\" \"gsl_multiroot_fdfsolver const *\"\"'\"); \n  }\n  arg1 = (gsl_multiroot_fdfsolver *)(argp1);\n  result = (char *)gsl_multiroot_fdfsolver_name((gsl_multiroot_fdfsolver const *)arg1);\n  resultobj = SWIG_FromCharPtr((const char *)result);\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multiroot_fdfsolver_root(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multiroot_fdfsolver *arg1 = (gsl_multiroot_fdfsolver *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  gsl_vector *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multiroot_fdfsolver_root\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multiroot_fdfsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multiroot_fdfsolver_root\" \"', argument \" \"1\"\" of type '\" \"gsl_multiroot_fdfsolver const *\"\"'\"); \n  }\n  arg1 = (gsl_multiroot_fdfsolver *)(argp1);\n  result = (gsl_vector *)gsl_multiroot_fdfsolver_root((gsl_multiroot_fdfsolver const *)arg1);\n  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_gsl_vector, 0 |  0 );\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multiroot_test_delta(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector *arg1 = (gsl_vector *) 0 ;\n  gsl_vector *arg2 = (gsl_vector *) 0 ;\n  double arg3 ;\n  double arg4 ;\n  double val3 ;\n  int ecode3 = 0 ;\n  double val4 ;\n  int ecode4 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  PyObject * obj3 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\",(char *) \"IN\",(char *) \"epsabs\",(char *) \"epsrel\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector _vector1;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOOO:gsl_multiroot_test_delta\",kwnames,&obj0,&obj1,&obj2,&obj3)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2,\n        PyGSL_INPUT_ARRAY, gsl_vector, 2, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  ecode3 = SWIG_AsVal_double(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_multiroot_test_delta\" \"', argument \" \"3\"\" of type '\" \"double\"\"'\");\n  } \n  arg3 = (double)(val3);\n  ecode4 = SWIG_AsVal_double(obj3, &val4);\n  if (!SWIG_IsOK(ecode4)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode4), \"in method '\" \"gsl_multiroot_test_delta\" \"', argument \" \"4\"\" of type '\" \"double\"\"'\");\n  } \n  arg4 = (double)(val4);\n  result = (int)gsl_multiroot_test_delta((gsl_vector const *)arg1,(gsl_vector const *)arg2,arg3,arg4);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  {\n    Py_XDECREF(_PyVector1);\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyVector2);\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyVector1);\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyVector2);\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multiroot_test_residual(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector *arg1 = (gsl_vector *) 0 ;\n  double arg2 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\",(char *) \"epsabs\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_multiroot_test_residual\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_multiroot_test_residual\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  result = (int)gsl_multiroot_test_residual((gsl_vector const *)arg1,arg2);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  {\n    Py_XDECREF(_PyVector1);\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyVector1);\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN int Swig_var_gsl_multiroot_fsolver_dnewton_set(PyObject *_val SWIGUNUSED) {\n  SWIG_Error(SWIG_AttributeError,\"Variable gsl_multiroot_fsolver_dnewton is read-only.\");\n  return 1;\n}\n\n\nSWIGINTERN PyObject *Swig_var_gsl_multiroot_fsolver_dnewton_get(void) {\n  PyObject *pyobj = 0;\n  \n  pyobj = SWIG_NewPointerObj(SWIG_as_voidptr(gsl_multiroot_fsolver_dnewton), SWIGTYPE_p_gsl_multiroot_fsolver_type,  0 );\n  return pyobj;\n}\n\n\nSWIGINTERN int Swig_var_gsl_multiroot_fsolver_broyden_set(PyObject *_val SWIGUNUSED) {\n  SWIG_Error(SWIG_AttributeError,\"Variable gsl_multiroot_fsolver_broyden is read-only.\");\n  return 1;\n}\n\n\nSWIGINTERN PyObject *Swig_var_gsl_multiroot_fsolver_broyden_get(void) {\n  PyObject *pyobj = 0;\n  \n  pyobj = SWIG_NewPointerObj(SWIG_as_voidptr(gsl_multiroot_fsolver_broyden), SWIGTYPE_p_gsl_multiroot_fsolver_type,  0 );\n  return pyobj;\n}\n\n\nSWIGINTERN int Swig_var_gsl_multiroot_fsolver_hybrid_set(PyObject *_val SWIGUNUSED) {\n  SWIG_Error(SWIG_AttributeError,\"Variable gsl_multiroot_fsolver_hybrid is read-only.\");\n  return 1;\n}\n\n\nSWIGINTERN PyObject *Swig_var_gsl_multiroot_fsolver_hybrid_get(void) {\n  PyObject *pyobj = 0;\n  \n  pyobj = SWIG_NewPointerObj(SWIG_as_voidptr(gsl_multiroot_fsolver_hybrid), SWIGTYPE_p_gsl_multiroot_fsolver_type,  0 );\n  return pyobj;\n}\n\n\nSWIGINTERN int Swig_var_gsl_multiroot_fsolver_hybrids_set(PyObject *_val SWIGUNUSED) {\n  SWIG_Error(SWIG_AttributeError,\"Variable gsl_multiroot_fsolver_hybrids is read-only.\");\n  return 1;\n}\n\n\nSWIGINTERN PyObject *Swig_var_gsl_multiroot_fsolver_hybrids_get(void) {\n  PyObject *pyobj = 0;\n  \n  pyobj = SWIG_NewPointerObj(SWIG_as_voidptr(gsl_multiroot_fsolver_hybrids), SWIGTYPE_p_gsl_multiroot_fsolver_type,  0 );\n  return pyobj;\n}\n\n\nSWIGINTERN int Swig_var_gsl_multiroot_fdfsolver_newton_set(PyObject *_val SWIGUNUSED) {\n  SWIG_Error(SWIG_AttributeError,\"Variable gsl_multiroot_fdfsolver_newton is read-only.\");\n  return 1;\n}\n\n\nSWIGINTERN PyObject *Swig_var_gsl_multiroot_fdfsolver_newton_get(void) {\n  PyObject *pyobj = 0;\n  \n  pyobj = SWIG_NewPointerObj(SWIG_as_voidptr(gsl_multiroot_fdfsolver_newton), SWIGTYPE_p_gsl_multiroot_fdfsolver_type,  0 );\n  return pyobj;\n}\n\n\nSWIGINTERN int Swig_var_gsl_multiroot_fdfsolver_gnewton_set(PyObject *_val SWIGUNUSED) {\n  SWIG_Error(SWIG_AttributeError,\"Variable gsl_multiroot_fdfsolver_gnewton is read-only.\");\n  return 1;\n}\n\n\nSWIGINTERN PyObject *Swig_var_gsl_multiroot_fdfsolver_gnewton_get(void) {\n  PyObject *pyobj = 0;\n  \n  pyobj = SWIG_NewPointerObj(SWIG_as_voidptr(gsl_multiroot_fdfsolver_gnewton), SWIGTYPE_p_gsl_multiroot_fdfsolver_type,  0 );\n  return pyobj;\n}\n\n\nSWIGINTERN int Swig_var_gsl_multiroot_fdfsolver_hybridj_set(PyObject *_val SWIGUNUSED) {\n  SWIG_Error(SWIG_AttributeError,\"Variable gsl_multiroot_fdfsolver_hybridj is read-only.\");\n  return 1;\n}\n\n\nSWIGINTERN PyObject *Swig_var_gsl_multiroot_fdfsolver_hybridj_get(void) {\n  PyObject *pyobj = 0;\n  \n  pyobj = SWIG_NewPointerObj(SWIG_as_voidptr(gsl_multiroot_fdfsolver_hybridj), SWIGTYPE_p_gsl_multiroot_fdfsolver_type,  0 );\n  return pyobj;\n}\n\n\nSWIGINTERN int Swig_var_gsl_multiroot_fdfsolver_hybridsj_set(PyObject *_val SWIGUNUSED) {\n  SWIG_Error(SWIG_AttributeError,\"Variable gsl_multiroot_fdfsolver_hybridsj is read-only.\");\n  return 1;\n}\n\n\nSWIGINTERN PyObject *Swig_var_gsl_multiroot_fdfsolver_hybridsj_get(void) {\n  PyObject *pyobj = 0;\n  \n  pyobj = SWIG_NewPointerObj(SWIG_as_voidptr(gsl_multiroot_fdfsolver_hybridsj), SWIGTYPE_p_gsl_multiroot_fdfsolver_type,  0 );\n  return pyobj;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multimin_function_init(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multimin_function *arg1 = (gsl_multimin_function *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"STORE\", NULL \n  };\n  gsl_multimin_function *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multimin_function_init\",kwnames,&obj0)) SWIG_fail;\n  {\n    FUNC_MESS(\"gsl_function STORE BEGIN\");\n    arg1 = PyGSL_convert_to_gsl_multimin_function (obj0);\n    FUNC_MESS(\"gsl_function STORE END\");\n    if(arg1==NULL) goto fail;\n  }\n  result = (gsl_multimin_function *)gsl_multimin_function_init(arg1);\n  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_gsl_multimin_function, 0 |  0 );\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multimin_function_init_fdf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multimin_function_fdf *arg1 = (gsl_multimin_function_fdf *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"STORE\", NULL \n  };\n  gsl_multimin_function_fdf *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multimin_function_init_fdf\",kwnames,&obj0)) SWIG_fail;\n  {\n    FUNC_MESS(\"gsl_function STORE BEGIN\");\n    arg1 = PyGSL_convert_to_gsl_multimin_function_fdf (obj0);\n    FUNC_MESS(\"gsl_function STORE END\");\n    if(arg1==NULL) goto fail;\n  }\n  result = (gsl_multimin_function_fdf *)gsl_multimin_function_init_fdf(arg1);\n  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_gsl_multimin_function_fdf, 0 |  0 );\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multimin_function_free(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multimin_function *arg1 = (gsl_multimin_function *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"FREE\", NULL \n  };\n  \n  \n  gsl_multimin_function *_function1 = NULL;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multimin_function_free\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multimin_function, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multimin_function_free\" \"', argument \" \"1\"\" of type '\" \"gsl_multimin_function *\"\"'\"); \n  }\n  arg1 = (gsl_multimin_function *)(argp1);\n  {\n    DEBUG_MESS(2, \"gsl_function STORE IN ptr @ %p\", arg1);\n    if(arg1==NULL) goto fail;\n    \n    _function1 = arg1;\n  }\n  gsl_multimin_function_free(arg1);\n  resultobj = SWIG_Py_Void();\n  {\n    DEBUG_MESS(2, \"gsl_function freeing %p\", _function1);\n    if(_function1){\n      assert(arg1 == _function1);\n      PyGSL_params_free((callback_function_params *) arg1->params);\n      free(arg1);    \n    }\n    _function1 = NULL;\n    DEBUG_MESS(2, \"gsl_function freed %p\", _function1);\n    \n  }\n  return resultobj;\nfail:\n  {\n    DEBUG_MESS(2, \"gsl_function freeing %p\", _function1);\n    if(_function1){\n      assert(arg1 == _function1);\n      PyGSL_params_free((callback_function_params *) arg1->params);\n      free(arg1);    \n    }\n    _function1 = NULL;\n    DEBUG_MESS(2, \"gsl_function freed %p\", _function1);\n    \n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multimin_function_free_fdf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multimin_function_fdf *arg1 = (gsl_multimin_function_fdf *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"FREE\", NULL \n  };\n  \n  \n  gsl_multimin_function_fdf *_function1 = NULL;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multimin_function_free_fdf\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multimin_function_fdf, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multimin_function_free_fdf\" \"', argument \" \"1\"\" of type '\" \"gsl_multimin_function_fdf *\"\"'\"); \n  }\n  arg1 = (gsl_multimin_function_fdf *)(argp1);\n  {\n    DEBUG_MESS(2, \"gsl_function STORE IN ptr @ %p\", arg1);\n    if(arg1==NULL) goto fail;\n    \n    _function1 = arg1;\n  }\n  gsl_multimin_function_free_fdf(arg1);\n  resultobj = SWIG_Py_Void();\n  {\n    DEBUG_MESS(2, \"gsl_function freeing %p\", _function1);\n    if(_function1){\n      assert(arg1 == _function1);\n      PyGSL_params_free((callback_function_params *) arg1->params);\n      free(arg1);    \n    }\n    _function1 = NULL;\n    DEBUG_MESS(2, \"gsl_function freed %p\", _function1);\n    \n  }\n  return resultobj;\nfail:\n  {\n    DEBUG_MESS(2, \"gsl_function freeing %p\", _function1);\n    if(_function1){\n      assert(arg1 == _function1);\n      PyGSL_params_free((callback_function_params *) arg1->params);\n      free(arg1);    \n    }\n    _function1 = NULL;\n    DEBUG_MESS(2, \"gsl_function freed %p\", _function1);\n    \n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multimin_fminimizer_f(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multimin_fminimizer *arg1 = (gsl_multimin_fminimizer *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  double result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multimin_fminimizer_f\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multimin_fminimizer, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multimin_fminimizer_f\" \"', argument \" \"1\"\" of type '\" \"gsl_multimin_fminimizer *\"\"'\"); \n  }\n  arg1 = (gsl_multimin_fminimizer *)(argp1);\n  result = (double)gsl_multimin_fminimizer_f(arg1);\n  resultobj = SWIG_From_double((double)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multimin_fminimizer_alloc(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multimin_fminimizer_type *arg1 = (gsl_multimin_fminimizer_type *) 0 ;\n  size_t arg2 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"T\",(char *) \"n\", NULL \n  };\n  gsl_multimin_fminimizer *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_multimin_fminimizer_alloc\",kwnames,&obj0,&obj1)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multimin_fminimizer_type, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multimin_fminimizer_alloc\" \"', argument \" \"1\"\" of type '\" \"gsl_multimin_fminimizer_type const *\"\"'\"); \n  }\n  arg1 = (gsl_multimin_fminimizer_type *)(argp1);\n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_multimin_fminimizer_alloc\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  result = (gsl_multimin_fminimizer *)gsl_multimin_fminimizer_alloc((gsl_multimin_fminimizer_type const *)arg1,arg2);\n  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_gsl_multimin_fminimizer, 0 |  0 );\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multimin_fminimizer_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multimin_fminimizer *arg1 = (gsl_multimin_fminimizer *) 0 ;\n  gsl_multimin_function *arg2 = (gsl_multimin_function *) 0 ;\n  gsl_vector *arg3 = (gsl_vector *) 0 ;\n  gsl_vector *arg4 = (gsl_vector *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  void *argp2 = 0 ;\n  int res2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  PyObject * obj3 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\",(char *) \"BUFFER\",(char *) \"IN\",(char *) \"IN\", NULL \n  };\n  int result;\n  \n  \n  gsl_multimin_function * volatile _solver2 = NULL;\n  \n  \n  PyArrayObject * volatile _PyVector3 = NULL;\n  TYPE_VIEW_gsl_vector _vector3;\n  \n  \n  PyArrayObject * volatile _PyVector4 = NULL;\n  TYPE_VIEW_gsl_vector _vector4;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOOO:gsl_multimin_fminimizer_set\",kwnames,&obj0,&obj1,&obj2,&obj3)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multimin_fminimizer, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multimin_fminimizer_set\" \"', argument \" \"1\"\" of type '\" \"gsl_multimin_fminimizer *\"\"'\"); \n  }\n  arg1 = (gsl_multimin_fminimizer *)(argp1);\n  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_gsl_multimin_function, 0 |  0 );\n  if (!SWIG_IsOK(res2)) {\n    SWIG_exception_fail(SWIG_ArgError(res2), \"in method '\" \"gsl_multimin_fminimizer_set\" \"', argument \" \"2\"\" of type '\" \"gsl_multimin_function *\"\"'\"); \n  }\n  arg2 = (gsl_multimin_function *)(argp2);\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj2, arg3, _PyVector3, _vector3,\n        PyGSL_INPUT_ARRAY, gsl_vector, 3, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj3, arg4, _PyVector4, _vector4,\n        PyGSL_INPUT_ARRAY, gsl_vector, 4, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  {\n    int flag;\n    callback_function_params * p;\n    \n    FUNC_MESS(\"\\t\\t Setting jump buffer\");\n    assert(arg2);\n    \n    \n    _solver2 = arg2;\n    p = (callback_function_params *) \n    PyGSL_gsl_multimin_function_GET_PARAMS(_solver2);\n    \n    if((flag=setjmp(p->buffer)) == 0){\n      FUNC_MESS(\"\\t\\t Setting Jmp Buffer\");\n      p->buffer_is_set = 1;\n    } else {\n      FUNC_MESS(\"\\t\\t Returning from Jmp Buffer\");\n      p->buffer_is_set = 0;\n      goto fail;\n    }\n    \n    FUNC_MESS(\"\\t\\t END Setting jump buffer\");\n  }\n  result = (int)gsl_multimin_fminimizer_set(arg1,arg2,(gsl_vector const *)arg3,(gsl_vector const *)arg4);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  {\n    callback_function_params * p;\n    if(_solver2){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params *)  \n      PyGSL_gsl_multimin_function_GET_PARAMS(_solver2);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  {\n    Py_XDECREF(_PyVector3);\n    _PyVector3 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyVector4);\n    _PyVector4 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    callback_function_params * p;\n    if(_solver2){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params *)  \n      PyGSL_gsl_multimin_function_GET_PARAMS(_solver2);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  {\n    Py_XDECREF(_PyVector3);\n    _PyVector3 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyVector4);\n    _PyVector4 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multimin_fminimizer_free(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multimin_fminimizer *arg1 = (gsl_multimin_fminimizer *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multimin_fminimizer_free\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multimin_fminimizer, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multimin_fminimizer_free\" \"', argument \" \"1\"\" of type '\" \"gsl_multimin_fminimizer *\"\"'\"); \n  }\n  arg1 = (gsl_multimin_fminimizer *)(argp1);\n  gsl_multimin_fminimizer_free(arg1);\n  resultobj = SWIG_Py_Void();\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multimin_fminimizer_name(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multimin_fminimizer *arg1 = (gsl_multimin_fminimizer *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  char *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multimin_fminimizer_name\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multimin_fminimizer, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multimin_fminimizer_name\" \"', argument \" \"1\"\" of type '\" \"gsl_multimin_fminimizer const *\"\"'\"); \n  }\n  arg1 = (gsl_multimin_fminimizer *)(argp1);\n  result = (char *)gsl_multimin_fminimizer_name((gsl_multimin_fminimizer const *)arg1);\n  resultobj = SWIG_FromCharPtr((const char *)result);\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multimin_fminimizer_iterate(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multimin_fminimizer *arg1 = (gsl_multimin_fminimizer *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  int result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multimin_fminimizer_iterate\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multimin_fminimizer, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multimin_fminimizer_iterate\" \"', argument \" \"1\"\" of type '\" \"gsl_multimin_fminimizer *\"\"'\"); \n  }\n  arg1 = (gsl_multimin_fminimizer *)(argp1);\n  result = (int)gsl_multimin_fminimizer_iterate(arg1);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multimin_fminimizer_x(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multimin_fminimizer *arg1 = (gsl_multimin_fminimizer *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  gsl_multimin_solver_data *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multimin_fminimizer_x\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multimin_fminimizer, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multimin_fminimizer_x\" \"', argument \" \"1\"\" of type '\" \"gsl_multimin_fminimizer const *\"\"'\"); \n  }\n  arg1 = (gsl_multimin_fminimizer *)(argp1);\n  result = (gsl_multimin_solver_data *)gsl_multimin_fminimizer_x((gsl_multimin_fminimizer const *)arg1);\n  {\n    PyArrayObject *a_array;  \n    a_array = PyGSL_copy_gslvector_to_pyarray(result);\n    resultobj = (PyObject *) a_array;\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multimin_fminimizer_minimum(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multimin_fminimizer *arg1 = (gsl_multimin_fminimizer *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  double result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multimin_fminimizer_minimum\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multimin_fminimizer, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multimin_fminimizer_minimum\" \"', argument \" \"1\"\" of type '\" \"gsl_multimin_fminimizer const *\"\"'\"); \n  }\n  arg1 = (gsl_multimin_fminimizer *)(argp1);\n  result = (double)gsl_multimin_fminimizer_minimum((gsl_multimin_fminimizer const *)arg1);\n  resultobj = SWIG_From_double((double)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multimin_fminimizer_size(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multimin_fminimizer *arg1 = (gsl_multimin_fminimizer *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  double result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multimin_fminimizer_size\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multimin_fminimizer, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multimin_fminimizer_size\" \"', argument \" \"1\"\" of type '\" \"gsl_multimin_fminimizer const *\"\"'\"); \n  }\n  arg1 = (gsl_multimin_fminimizer *)(argp1);\n  result = (double)gsl_multimin_fminimizer_size((gsl_multimin_fminimizer const *)arg1);\n  resultobj = SWIG_From_double((double)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multimin_fdfminimizer_alloc(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multimin_fdfminimizer_type *arg1 = (gsl_multimin_fdfminimizer_type *) 0 ;\n  size_t arg2 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"T\",(char *) \"n\", NULL \n  };\n  gsl_multimin_fdfminimizer *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_multimin_fdfminimizer_alloc\",kwnames,&obj0,&obj1)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multimin_fdfminimizer_type, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multimin_fdfminimizer_alloc\" \"', argument \" \"1\"\" of type '\" \"gsl_multimin_fdfminimizer_type const *\"\"'\"); \n  }\n  arg1 = (gsl_multimin_fdfminimizer_type *)(argp1);\n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_multimin_fdfminimizer_alloc\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  result = (gsl_multimin_fdfminimizer *)gsl_multimin_fdfminimizer_alloc((gsl_multimin_fdfminimizer_type const *)arg1,arg2);\n  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_gsl_multimin_fdfminimizer, 0 |  0 );\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multimin_fdfminimizer_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multimin_fdfminimizer *arg1 = (gsl_multimin_fdfminimizer *) 0 ;\n  gsl_multimin_function_fdf *arg2 = (gsl_multimin_function_fdf *) 0 ;\n  gsl_vector *arg3 = (gsl_vector *) 0 ;\n  double arg4 ;\n  double arg5 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  void *argp2 = 0 ;\n  int res2 = 0 ;\n  double val4 ;\n  int ecode4 = 0 ;\n  double val5 ;\n  int ecode5 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  PyObject * obj3 = 0 ;\n  PyObject * obj4 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\",(char *) \"BUFFER\",(char *) \"IN\",(char *) \"step_size\",(char *) \"tol\", NULL \n  };\n  int result;\n  \n  \n  gsl_multimin_function_fdf * volatile _solver2 = NULL;\n  \n  \n  PyArrayObject * volatile _PyVector3 = NULL;\n  TYPE_VIEW_gsl_vector _vector3;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOOOO:gsl_multimin_fdfminimizer_set\",kwnames,&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multimin_fdfminimizer, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multimin_fdfminimizer_set\" \"', argument \" \"1\"\" of type '\" \"gsl_multimin_fdfminimizer *\"\"'\"); \n  }\n  arg1 = (gsl_multimin_fdfminimizer *)(argp1);\n  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_gsl_multimin_function_fdf, 0 |  0 );\n  if (!SWIG_IsOK(res2)) {\n    SWIG_exception_fail(SWIG_ArgError(res2), \"in method '\" \"gsl_multimin_fdfminimizer_set\" \"', argument \" \"2\"\" of type '\" \"gsl_multimin_function_fdf *\"\"'\"); \n  }\n  arg2 = (gsl_multimin_function_fdf *)(argp2);\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj2, arg3, _PyVector3, _vector3,\n        PyGSL_INPUT_ARRAY, gsl_vector, 3, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  ecode4 = SWIG_AsVal_double(obj3, &val4);\n  if (!SWIG_IsOK(ecode4)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode4), \"in method '\" \"gsl_multimin_fdfminimizer_set\" \"', argument \" \"4\"\" of type '\" \"double\"\"'\");\n  } \n  arg4 = (double)(val4);\n  ecode5 = SWIG_AsVal_double(obj4, &val5);\n  if (!SWIG_IsOK(ecode5)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode5), \"in method '\" \"gsl_multimin_fdfminimizer_set\" \"', argument \" \"5\"\" of type '\" \"double\"\"'\");\n  } \n  arg5 = (double)(val5);\n  {\n    int flag;\n    callback_function_params_fdf * p;\n    \n    FUNC_MESS(\"\\t\\t Setting jump buffer\");\n    assert(arg2);\n    \n    _solver2 = arg2;\n    p = (callback_function_params_fdf *) \n    PyGSL_gsl_multimin_function_fdf_GET_PARAMS(_solver2);\n    \n    if((flag=setjmp(p->buffer)) == 0){\n      FUNC_MESS(\"\\t\\t Setting Jmp Buffer\");\n      /* Set jump buffer */\n      p->buffer_is_set = 1;\n    } else {\n      FUNC_MESS(\"\\t\\t Returning from Jmp Buffer\");\n      p->buffer_is_set = 0;\n      goto fail;\n    }\n    \n    FUNC_MESS(\"\\t\\t END Setting jump buffer\");\n  }\n  result = (int)gsl_multimin_fdfminimizer_set(arg1,arg2,(gsl_vector const *)arg3,arg4,arg5);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  {\n    callback_function_params_fdf * p;\n    if(_solver2){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params_fdf *)  \n      PyGSL_gsl_multimin_function_fdf_GET_PARAMS(_solver2);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  {\n    Py_XDECREF(_PyVector3);\n    _PyVector3 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    callback_function_params_fdf * p;\n    if(_solver2){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params_fdf *)  \n      PyGSL_gsl_multimin_function_fdf_GET_PARAMS(_solver2);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  {\n    Py_XDECREF(_PyVector3);\n    _PyVector3 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multimin_fdfminimizer_free(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multimin_fdfminimizer *arg1 = (gsl_multimin_fdfminimizer *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multimin_fdfminimizer_free\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multimin_fdfminimizer, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multimin_fdfminimizer_free\" \"', argument \" \"1\"\" of type '\" \"gsl_multimin_fdfminimizer *\"\"'\"); \n  }\n  arg1 = (gsl_multimin_fdfminimizer *)(argp1);\n  gsl_multimin_fdfminimizer_free(arg1);\n  resultobj = SWIG_Py_Void();\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multimin_fdfminimizer_name(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multimin_fdfminimizer *arg1 = (gsl_multimin_fdfminimizer *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  char *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multimin_fdfminimizer_name\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multimin_fdfminimizer, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multimin_fdfminimizer_name\" \"', argument \" \"1\"\" of type '\" \"gsl_multimin_fdfminimizer const *\"\"'\"); \n  }\n  arg1 = (gsl_multimin_fdfminimizer *)(argp1);\n  result = (char *)gsl_multimin_fdfminimizer_name((gsl_multimin_fdfminimizer const *)arg1);\n  resultobj = SWIG_FromCharPtr((const char *)result);\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multimin_fdfminimizer_iterate(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multimin_fdfminimizer *arg1 = (gsl_multimin_fdfminimizer *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"BUFFER\", NULL \n  };\n  int result;\n  \n  \n  gsl_multimin_fdfminimizer * volatile _solver1 = NULL;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multimin_fdfminimizer_iterate\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multimin_fdfminimizer, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multimin_fdfminimizer_iterate\" \"', argument \" \"1\"\" of type '\" \"gsl_multimin_fdfminimizer *\"\"'\"); \n  }\n  arg1 = (gsl_multimin_fdfminimizer *)(argp1);\n  {\n    int flag;\n    callback_function_params_fdf * p;\n    \n    FUNC_MESS(\"\\t\\t Setting jump buffer\");\n    assert(arg1);\n    \n    _solver1 = arg1;\n    p = (callback_function_params_fdf *) \n    PyGSL_gsl_multimin_fdfminimizer_GET_PARAMS(_solver1);\n    \n    if((flag=setjmp(p->buffer)) == 0){\n      FUNC_MESS(\"\\t\\t Setting Jmp Buffer\");\n      /* Set jump buffer */\n      p->buffer_is_set = 1;\n    } else {\n      FUNC_MESS(\"\\t\\t Returning from Jmp Buffer\");\n      p->buffer_is_set = 0;\n      goto fail;\n    }\n    \n    FUNC_MESS(\"\\t\\t END Setting jump buffer\");\n  }\n  result = (int)gsl_multimin_fdfminimizer_iterate(arg1);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  {\n    callback_function_params_fdf * p;\n    if(_solver1){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params_fdf *)  \n      PyGSL_gsl_multimin_fdfminimizer_GET_PARAMS(_solver1);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  return resultobj;\nfail:\n  {\n    callback_function_params_fdf * p;\n    if(_solver1){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params_fdf *)  \n      PyGSL_gsl_multimin_fdfminimizer_GET_PARAMS(_solver1);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multimin_fdfminimizer_restart(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multimin_fdfminimizer *arg1 = (gsl_multimin_fdfminimizer *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"BUFFER\", NULL \n  };\n  int result;\n  \n  \n  gsl_multimin_fdfminimizer * volatile _solver1 = NULL;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multimin_fdfminimizer_restart\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multimin_fdfminimizer, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multimin_fdfminimizer_restart\" \"', argument \" \"1\"\" of type '\" \"gsl_multimin_fdfminimizer *\"\"'\"); \n  }\n  arg1 = (gsl_multimin_fdfminimizer *)(argp1);\n  {\n    int flag;\n    callback_function_params_fdf * p;\n    \n    FUNC_MESS(\"\\t\\t Setting jump buffer\");\n    assert(arg1);\n    \n    _solver1 = arg1;\n    p = (callback_function_params_fdf *) \n    PyGSL_gsl_multimin_fdfminimizer_GET_PARAMS(_solver1);\n    \n    if((flag=setjmp(p->buffer)) == 0){\n      FUNC_MESS(\"\\t\\t Setting Jmp Buffer\");\n      /* Set jump buffer */\n      p->buffer_is_set = 1;\n    } else {\n      FUNC_MESS(\"\\t\\t Returning from Jmp Buffer\");\n      p->buffer_is_set = 0;\n      goto fail;\n    }\n    \n    FUNC_MESS(\"\\t\\t END Setting jump buffer\");\n  }\n  result = (int)gsl_multimin_fdfminimizer_restart(arg1);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  {\n    callback_function_params_fdf * p;\n    if(_solver1){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params_fdf *)  \n      PyGSL_gsl_multimin_fdfminimizer_GET_PARAMS(_solver1);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  return resultobj;\nfail:\n  {\n    callback_function_params_fdf * p;\n    if(_solver1){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params_fdf *)  \n      PyGSL_gsl_multimin_fdfminimizer_GET_PARAMS(_solver1);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multimin_test_gradient(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector *arg1 = (gsl_vector *) 0 ;\n  double arg2 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\",(char *) \"epsabs\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_multimin_test_gradient\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_multimin_test_gradient\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  result = (int)gsl_multimin_test_gradient((gsl_vector const *)arg1,arg2);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  {\n    Py_XDECREF(_PyVector1);\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyVector1);\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multimin_test_size(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  double arg1 ;\n  double arg2 ;\n  double val1 ;\n  int ecode1 = 0 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"size\",(char *) \"epsabs\", NULL \n  };\n  int result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_multimin_test_size\",kwnames,&obj0,&obj1)) SWIG_fail;\n  ecode1 = SWIG_AsVal_double(obj0, &val1);\n  if (!SWIG_IsOK(ecode1)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode1), \"in method '\" \"gsl_multimin_test_size\" \"', argument \" \"1\"\" of type '\" \"double\"\"'\");\n  } \n  arg1 = (double)(val1);\n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_multimin_test_size\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  result = (int)gsl_multimin_test_size(arg1,arg2);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multimin_fdfminimizer_f(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multimin_fdfminimizer *arg1 = (gsl_multimin_fdfminimizer *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  double result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multimin_fdfminimizer_f\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multimin_fdfminimizer, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multimin_fdfminimizer_f\" \"', argument \" \"1\"\" of type '\" \"gsl_multimin_fdfminimizer *\"\"'\"); \n  }\n  arg1 = (gsl_multimin_fdfminimizer *)(argp1);\n  result = (double)gsl_multimin_fdfminimizer_f(arg1);\n  resultobj = SWIG_From_double((double)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multimin_fdfminimizer_x(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multimin_fdfminimizer *arg1 = (gsl_multimin_fdfminimizer *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  gsl_multimin_solver_data *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multimin_fdfminimizer_x\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multimin_fdfminimizer, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multimin_fdfminimizer_x\" \"', argument \" \"1\"\" of type '\" \"gsl_multimin_fdfminimizer *\"\"'\"); \n  }\n  arg1 = (gsl_multimin_fdfminimizer *)(argp1);\n  result = (gsl_multimin_solver_data *)gsl_multimin_fdfminimizer_x(arg1);\n  {\n    PyArrayObject *a_array;  \n    a_array = PyGSL_copy_gslvector_to_pyarray(result);\n    resultobj = (PyObject *) a_array;\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multimin_fdfminimizer_dx(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multimin_fdfminimizer *arg1 = (gsl_multimin_fdfminimizer *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  gsl_multimin_solver_data *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multimin_fdfminimizer_dx\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multimin_fdfminimizer, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multimin_fdfminimizer_dx\" \"', argument \" \"1\"\" of type '\" \"gsl_multimin_fdfminimizer *\"\"'\"); \n  }\n  arg1 = (gsl_multimin_fdfminimizer *)(argp1);\n  result = (gsl_multimin_solver_data *)gsl_multimin_fdfminimizer_dx(arg1);\n  {\n    PyArrayObject *a_array;  \n    a_array = PyGSL_copy_gslvector_to_pyarray(result);\n    resultobj = (PyObject *) a_array;\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multimin_fdfminimizer_gradient(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multimin_fdfminimizer *arg1 = (gsl_multimin_fdfminimizer *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  gsl_multimin_solver_data *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multimin_fdfminimizer_gradient\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multimin_fdfminimizer, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multimin_fdfminimizer_gradient\" \"', argument \" \"1\"\" of type '\" \"gsl_multimin_fdfminimizer *\"\"'\"); \n  }\n  arg1 = (gsl_multimin_fdfminimizer *)(argp1);\n  result = (gsl_multimin_solver_data *)gsl_multimin_fdfminimizer_gradient(arg1);\n  {\n    PyArrayObject *a_array;  \n    a_array = PyGSL_copy_gslvector_to_pyarray(result);\n    resultobj = (PyObject *) a_array;\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multimin_fdfminimizer_minimum(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multimin_fdfminimizer *arg1 = (gsl_multimin_fdfminimizer *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  double result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multimin_fdfminimizer_minimum\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multimin_fdfminimizer, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multimin_fdfminimizer_minimum\" \"', argument \" \"1\"\" of type '\" \"gsl_multimin_fdfminimizer *\"\"'\"); \n  }\n  arg1 = (gsl_multimin_fdfminimizer *)(argp1);\n  result = (double)gsl_multimin_fdfminimizer_minimum(arg1);\n  resultobj = SWIG_From_double((double)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN int Swig_var_gsl_multimin_fdfminimizer_steepest_descent_set(PyObject *_val SWIGUNUSED) {\n  SWIG_Error(SWIG_AttributeError,\"Variable gsl_multimin_fdfminimizer_steepest_descent is read-only.\");\n  return 1;\n}\n\n\nSWIGINTERN PyObject *Swig_var_gsl_multimin_fdfminimizer_steepest_descent_get(void) {\n  PyObject *pyobj = 0;\n  \n  pyobj = SWIG_NewPointerObj(SWIG_as_voidptr(gsl_multimin_fdfminimizer_steepest_descent), SWIGTYPE_p_gsl_multimin_fdfminimizer_type,  0 );\n  return pyobj;\n}\n\n\nSWIGINTERN int Swig_var_gsl_multimin_fdfminimizer_conjugate_pr_set(PyObject *_val SWIGUNUSED) {\n  SWIG_Error(SWIG_AttributeError,\"Variable gsl_multimin_fdfminimizer_conjugate_pr is read-only.\");\n  return 1;\n}\n\n\nSWIGINTERN PyObject *Swig_var_gsl_multimin_fdfminimizer_conjugate_pr_get(void) {\n  PyObject *pyobj = 0;\n  \n  pyobj = SWIG_NewPointerObj(SWIG_as_voidptr(gsl_multimin_fdfminimizer_conjugate_pr), SWIGTYPE_p_gsl_multimin_fdfminimizer_type,  0 );\n  return pyobj;\n}\n\n\nSWIGINTERN int Swig_var_gsl_multimin_fdfminimizer_conjugate_fr_set(PyObject *_val SWIGUNUSED) {\n  SWIG_Error(SWIG_AttributeError,\"Variable gsl_multimin_fdfminimizer_conjugate_fr is read-only.\");\n  return 1;\n}\n\n\nSWIGINTERN PyObject *Swig_var_gsl_multimin_fdfminimizer_conjugate_fr_get(void) {\n  PyObject *pyobj = 0;\n  \n  pyobj = SWIG_NewPointerObj(SWIG_as_voidptr(gsl_multimin_fdfminimizer_conjugate_fr), SWIGTYPE_p_gsl_multimin_fdfminimizer_type,  0 );\n  return pyobj;\n}\n\n\nSWIGINTERN int Swig_var_gsl_multimin_fdfminimizer_vector_bfgs_set(PyObject *_val SWIGUNUSED) {\n  SWIG_Error(SWIG_AttributeError,\"Variable gsl_multimin_fdfminimizer_vector_bfgs is read-only.\");\n  return 1;\n}\n\n\nSWIGINTERN PyObject *Swig_var_gsl_multimin_fdfminimizer_vector_bfgs_get(void) {\n  PyObject *pyobj = 0;\n  \n  pyobj = SWIG_NewPointerObj(SWIG_as_voidptr(gsl_multimin_fdfminimizer_vector_bfgs), SWIGTYPE_p_gsl_multimin_fdfminimizer_type,  0 );\n  return pyobj;\n}\n\n\nSWIGINTERN int Swig_var_gsl_multimin_fminimizer_nmsimplex_set(PyObject *_val SWIGUNUSED) {\n  SWIG_Error(SWIG_AttributeError,\"Variable gsl_multimin_fminimizer_nmsimplex is read-only.\");\n  return 1;\n}\n\n\nSWIGINTERN PyObject *Swig_var_gsl_multimin_fminimizer_nmsimplex_get(void) {\n  PyObject *pyobj = 0;\n  \n  pyobj = SWIG_NewPointerObj(SWIG_as_voidptr(gsl_multimin_fminimizer_nmsimplex), SWIGTYPE_p_gsl_multimin_fminimizer_type,  0 );\n  return pyobj;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multifit_function_init(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multifit_function *arg1 = (gsl_multifit_function *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"STORE\", NULL \n  };\n  gsl_multifit_function *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multifit_function_init\",kwnames,&obj0)) SWIG_fail;\n  {\n    FUNC_MESS(\"gsl_function STORE BEGIN\");\n    arg1 = PyGSL_convert_to_gsl_multifit_function (obj0);\n    FUNC_MESS(\"gsl_function STORE END\");\n    if(arg1==NULL) goto fail;\n  }\n  result = (gsl_multifit_function *)gsl_multifit_function_init(arg1);\n  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_gsl_multifit_function, 0 |  0 );\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multifit_function_init_fdf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multifit_function_fdf *arg1 = (gsl_multifit_function_fdf *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"STORE\", NULL \n  };\n  gsl_multifit_function_fdf *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multifit_function_init_fdf\",kwnames,&obj0)) SWIG_fail;\n  {\n    FUNC_MESS(\"gsl_function STORE BEGIN\");\n    arg1 = PyGSL_convert_to_gsl_multifit_function_fdf (obj0);\n    FUNC_MESS(\"gsl_function STORE END\");\n    if(arg1==NULL) goto fail;\n  }\n  result = (gsl_multifit_function_fdf *)gsl_multifit_function_init_fdf(arg1);\n  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_gsl_multifit_function_fdf, 0 |  0 );\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multifit_fsolver_getdx(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multifit_fsolver *arg1 = (gsl_multifit_fsolver *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  gsl_multifit_solver_vector *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multifit_fsolver_getdx\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multifit_fsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multifit_fsolver_getdx\" \"', argument \" \"1\"\" of type '\" \"gsl_multifit_fsolver *\"\"'\"); \n  }\n  arg1 = (gsl_multifit_fsolver *)(argp1);\n  result = (gsl_multifit_solver_vector *)gsl_multifit_fsolver_getdx(arg1);\n  {\n    PyArrayObject *a_array;  \n    a_array = PyGSL_copy_gslvector_to_pyarray(result);\n    resultobj = (PyObject *) a_array;\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multifit_fsolver_getx(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multifit_fsolver *arg1 = (gsl_multifit_fsolver *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  gsl_multifit_solver_vector *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multifit_fsolver_getx\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multifit_fsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multifit_fsolver_getx\" \"', argument \" \"1\"\" of type '\" \"gsl_multifit_fsolver *\"\"'\"); \n  }\n  arg1 = (gsl_multifit_fsolver *)(argp1);\n  result = (gsl_multifit_solver_vector *)gsl_multifit_fsolver_getx(arg1);\n  {\n    PyArrayObject *a_array;  \n    a_array = PyGSL_copy_gslvector_to_pyarray(result);\n    resultobj = (PyObject *) a_array;\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multifit_fsolver_getf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multifit_fsolver *arg1 = (gsl_multifit_fsolver *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  gsl_multifit_solver_vector *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multifit_fsolver_getf\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multifit_fsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multifit_fsolver_getf\" \"', argument \" \"1\"\" of type '\" \"gsl_multifit_fsolver *\"\"'\"); \n  }\n  arg1 = (gsl_multifit_fsolver *)(argp1);\n  result = (gsl_multifit_solver_vector *)gsl_multifit_fsolver_getf(arg1);\n  {\n    PyArrayObject *a_array;  \n    a_array = PyGSL_copy_gslvector_to_pyarray(result);\n    resultobj = (PyObject *) a_array;\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multifit_fdfsolver_getdx(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multifit_fdfsolver *arg1 = (gsl_multifit_fdfsolver *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  gsl_multifit_solver_vector *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multifit_fdfsolver_getdx\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multifit_fdfsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multifit_fdfsolver_getdx\" \"', argument \" \"1\"\" of type '\" \"gsl_multifit_fdfsolver *\"\"'\"); \n  }\n  arg1 = (gsl_multifit_fdfsolver *)(argp1);\n  result = (gsl_multifit_solver_vector *)gsl_multifit_fdfsolver_getdx(arg1);\n  {\n    PyArrayObject *a_array;  \n    a_array = PyGSL_copy_gslvector_to_pyarray(result);\n    resultobj = (PyObject *) a_array;\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multifit_fdfsolver_getx(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multifit_fdfsolver *arg1 = (gsl_multifit_fdfsolver *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  gsl_multifit_solver_vector *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multifit_fdfsolver_getx\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multifit_fdfsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multifit_fdfsolver_getx\" \"', argument \" \"1\"\" of type '\" \"gsl_multifit_fdfsolver *\"\"'\"); \n  }\n  arg1 = (gsl_multifit_fdfsolver *)(argp1);\n  result = (gsl_multifit_solver_vector *)gsl_multifit_fdfsolver_getx(arg1);\n  {\n    PyArrayObject *a_array;  \n    a_array = PyGSL_copy_gslvector_to_pyarray(result);\n    resultobj = (PyObject *) a_array;\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multifit_fdfsolver_getf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multifit_fdfsolver *arg1 = (gsl_multifit_fdfsolver *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  gsl_multifit_solver_vector *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multifit_fdfsolver_getf\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multifit_fdfsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multifit_fdfsolver_getf\" \"', argument \" \"1\"\" of type '\" \"gsl_multifit_fdfsolver *\"\"'\"); \n  }\n  arg1 = (gsl_multifit_fdfsolver *)(argp1);\n  result = (gsl_multifit_solver_vector *)gsl_multifit_fdfsolver_getf(arg1);\n  {\n    PyArrayObject *a_array;  \n    a_array = PyGSL_copy_gslvector_to_pyarray(result);\n    resultobj = (PyObject *) a_array;\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multifit_fdfsolver_getJ(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multifit_fdfsolver *arg1 = (gsl_multifit_fdfsolver *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  gsl_multifit_solver_matrix *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multifit_fdfsolver_getJ\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multifit_fdfsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multifit_fdfsolver_getJ\" \"', argument \" \"1\"\" of type '\" \"gsl_multifit_fdfsolver *\"\"'\"); \n  }\n  arg1 = (gsl_multifit_fdfsolver *)(argp1);\n  result = (gsl_multifit_solver_matrix *)gsl_multifit_fdfsolver_getJ(arg1);\n  {\n    PyArrayObject *a_array = NULL;  \n    a_array = PyGSL_copy_gslmatrix_to_pyarray(result);\n    resultobj = (PyObject *) a_array;\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multifit_function_free(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multifit_function *arg1 = (gsl_multifit_function *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"FREE\", NULL \n  };\n  \n  \n  gsl_multifit_function *_function1 = NULL;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multifit_function_free\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multifit_function, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multifit_function_free\" \"', argument \" \"1\"\" of type '\" \"gsl_multifit_function *\"\"'\"); \n  }\n  arg1 = (gsl_multifit_function *)(argp1);\n  {\n    DEBUG_MESS(2, \"gsl_function STORE IN ptr @ %p\", arg1);\n    if(arg1==NULL) goto fail;\n    \n    _function1 = arg1;\n  }\n  gsl_multifit_function_free(arg1);\n  resultobj = SWIG_Py_Void();\n  {\n    DEBUG_MESS(2, \"gsl_function freeing %p\", _function1);\n    if(_function1){\n      assert(arg1 == _function1);\n      PyGSL_params_free((callback_function_params *) arg1->params);\n      free(arg1);    \n    }\n    _function1 = NULL;\n    DEBUG_MESS(2, \"gsl_function freed %p\", _function1);\n    \n  }\n  return resultobj;\nfail:\n  {\n    DEBUG_MESS(2, \"gsl_function freeing %p\", _function1);\n    if(_function1){\n      assert(arg1 == _function1);\n      PyGSL_params_free((callback_function_params *) arg1->params);\n      free(arg1);    \n    }\n    _function1 = NULL;\n    DEBUG_MESS(2, \"gsl_function freed %p\", _function1);\n    \n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multifit_function_free_fdf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multifit_function_fdf *arg1 = (gsl_multifit_function_fdf *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"FREE\", NULL \n  };\n  \n  \n  gsl_multifit_function_fdf *_function1 = NULL;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multifit_function_free_fdf\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multifit_function_fdf, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multifit_function_free_fdf\" \"', argument \" \"1\"\" of type '\" \"gsl_multifit_function_fdf *\"\"'\"); \n  }\n  arg1 = (gsl_multifit_function_fdf *)(argp1);\n  {\n    DEBUG_MESS(2, \"gsl_function STORE IN ptr @ %p\", arg1);\n    if(arg1==NULL) goto fail;\n    \n    _function1 = arg1;\n  }\n  gsl_multifit_function_free_fdf(arg1);\n  resultobj = SWIG_Py_Void();\n  {\n    DEBUG_MESS(2, \"gsl_function freeing %p\", _function1);\n    if(_function1){\n      assert(arg1 == _function1);\n      PyGSL_params_free((callback_function_params *) arg1->params);\n      free(arg1);    \n    }\n    _function1 = NULL;\n    DEBUG_MESS(2, \"gsl_function freed %p\", _function1);\n    \n  }\n  return resultobj;\nfail:\n  {\n    DEBUG_MESS(2, \"gsl_function freeing %p\", _function1);\n    if(_function1){\n      assert(arg1 == _function1);\n      PyGSL_params_free((callback_function_params *) arg1->params);\n      free(arg1);    \n    }\n    _function1 = NULL;\n    DEBUG_MESS(2, \"gsl_function freed %p\", _function1);\n    \n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multifit_fsolver_alloc(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multifit_fsolver_type *arg1 = (gsl_multifit_fsolver_type *) 0 ;\n  size_t arg2 ;\n  size_t arg3 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  size_t val3 ;\n  int ecode3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"T\",(char *) \"n\",(char *) \"p\", NULL \n  };\n  gsl_multifit_fsolver *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_multifit_fsolver_alloc\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multifit_fsolver_type, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multifit_fsolver_alloc\" \"', argument \" \"1\"\" of type '\" \"gsl_multifit_fsolver_type const *\"\"'\"); \n  }\n  arg1 = (gsl_multifit_fsolver_type *)(argp1);\n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_multifit_fsolver_alloc\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  ecode3 = SWIG_AsVal_size_t(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_multifit_fsolver_alloc\" \"', argument \" \"3\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg3 = (size_t)(val3);\n  result = (gsl_multifit_fsolver *)gsl_multifit_fsolver_alloc((gsl_multifit_fsolver_type const *)arg1,arg2,arg3);\n  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_gsl_multifit_fsolver, 0 |  0 );\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multifit_fsolver_free(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multifit_fsolver *arg1 = (gsl_multifit_fsolver *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multifit_fsolver_free\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multifit_fsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multifit_fsolver_free\" \"', argument \" \"1\"\" of type '\" \"gsl_multifit_fsolver *\"\"'\"); \n  }\n  arg1 = (gsl_multifit_fsolver *)(argp1);\n  gsl_multifit_fsolver_free(arg1);\n  resultobj = SWIG_Py_Void();\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multifit_fsolver_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multifit_fsolver *arg1 = (gsl_multifit_fsolver *) 0 ;\n  gsl_multifit_function *arg2 = (gsl_multifit_function *) 0 ;\n  gsl_vector *arg3 = (gsl_vector *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  void *argp2 = 0 ;\n  int res2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\",(char *) \"f\",(char *) \"IN\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector3 = NULL;\n  TYPE_VIEW_gsl_vector _vector3;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_multifit_fsolver_set\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multifit_fsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multifit_fsolver_set\" \"', argument \" \"1\"\" of type '\" \"gsl_multifit_fsolver *\"\"'\"); \n  }\n  arg1 = (gsl_multifit_fsolver *)(argp1);\n  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_gsl_multifit_function, 0 |  0 );\n  if (!SWIG_IsOK(res2)) {\n    SWIG_exception_fail(SWIG_ArgError(res2), \"in method '\" \"gsl_multifit_fsolver_set\" \"', argument \" \"2\"\" of type '\" \"gsl_multifit_function *\"\"'\"); \n  }\n  arg2 = (gsl_multifit_function *)(argp2);\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj2, arg3, _PyVector3, _vector3,\n        PyGSL_INPUT_ARRAY, gsl_vector, 3, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_multifit_fsolver_set(arg1,arg2,arg3);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  {\n    Py_XDECREF(_PyVector3);\n    _PyVector3 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyVector3);\n    _PyVector3 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multifit_fsolver_iterate(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multifit_fsolver *arg1 = (gsl_multifit_fsolver *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  int result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multifit_fsolver_iterate\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multifit_fsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multifit_fsolver_iterate\" \"', argument \" \"1\"\" of type '\" \"gsl_multifit_fsolver *\"\"'\"); \n  }\n  arg1 = (gsl_multifit_fsolver *)(argp1);\n  result = (int)gsl_multifit_fsolver_iterate(arg1);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multifit_fsolver_name(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multifit_fsolver *arg1 = (gsl_multifit_fsolver *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  char *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multifit_fsolver_name\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multifit_fsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multifit_fsolver_name\" \"', argument \" \"1\"\" of type '\" \"gsl_multifit_fsolver const *\"\"'\"); \n  }\n  arg1 = (gsl_multifit_fsolver *)(argp1);\n  result = (char *)gsl_multifit_fsolver_name((gsl_multifit_fsolver const *)arg1);\n  resultobj = SWIG_FromCharPtr((const char *)result);\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multifit_fsolver_position(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multifit_fsolver *arg1 = (gsl_multifit_fsolver *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  gsl_vector *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multifit_fsolver_position\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multifit_fsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multifit_fsolver_position\" \"', argument \" \"1\"\" of type '\" \"gsl_multifit_fsolver const *\"\"'\"); \n  }\n  arg1 = (gsl_multifit_fsolver *)(argp1);\n  result = (gsl_vector *)gsl_multifit_fsolver_position((gsl_multifit_fsolver const *)arg1);\n  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_gsl_vector, 0 |  0 );\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multifit_fdfsolver_alloc(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multifit_fdfsolver_type *arg1 = (gsl_multifit_fdfsolver_type *) 0 ;\n  size_t arg2 ;\n  size_t arg3 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  size_t val3 ;\n  int ecode3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"T\",(char *) \"n\",(char *) \"p\", NULL \n  };\n  gsl_multifit_fdfsolver *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_multifit_fdfsolver_alloc\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multifit_fdfsolver_type, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multifit_fdfsolver_alloc\" \"', argument \" \"1\"\" of type '\" \"gsl_multifit_fdfsolver_type const *\"\"'\"); \n  }\n  arg1 = (gsl_multifit_fdfsolver_type *)(argp1);\n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_multifit_fdfsolver_alloc\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  ecode3 = SWIG_AsVal_size_t(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_multifit_fdfsolver_alloc\" \"', argument \" \"3\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg3 = (size_t)(val3);\n  result = (gsl_multifit_fdfsolver *)gsl_multifit_fdfsolver_alloc((gsl_multifit_fdfsolver_type const *)arg1,arg2,arg3);\n  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_gsl_multifit_fdfsolver, 0 |  0 );\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multifit_fdfsolver_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multifit_fdfsolver *arg1 = (gsl_multifit_fdfsolver *) 0 ;\n  gsl_multifit_function_fdf *arg2 = (gsl_multifit_function_fdf *) 0 ;\n  gsl_vector *arg3 = (gsl_vector *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  void *argp2 = 0 ;\n  int res2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\",(char *) \"fdf\",(char *) \"IN\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector3 = NULL;\n  TYPE_VIEW_gsl_vector _vector3;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_multifit_fdfsolver_set\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multifit_fdfsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multifit_fdfsolver_set\" \"', argument \" \"1\"\" of type '\" \"gsl_multifit_fdfsolver *\"\"'\"); \n  }\n  arg1 = (gsl_multifit_fdfsolver *)(argp1);\n  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_gsl_multifit_function_fdf, 0 |  0 );\n  if (!SWIG_IsOK(res2)) {\n    SWIG_exception_fail(SWIG_ArgError(res2), \"in method '\" \"gsl_multifit_fdfsolver_set\" \"', argument \" \"2\"\" of type '\" \"gsl_multifit_function_fdf *\"\"'\"); \n  }\n  arg2 = (gsl_multifit_function_fdf *)(argp2);\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj2, arg3, _PyVector3, _vector3,\n        PyGSL_INPUT_ARRAY, gsl_vector, 3, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_multifit_fdfsolver_set(arg1,arg2,arg3);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  {\n    Py_XDECREF(_PyVector3);\n    _PyVector3 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyVector3);\n    _PyVector3 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multifit_fdfsolver_iterate(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multifit_fdfsolver *arg1 = (gsl_multifit_fdfsolver *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  int result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multifit_fdfsolver_iterate\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multifit_fdfsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multifit_fdfsolver_iterate\" \"', argument \" \"1\"\" of type '\" \"gsl_multifit_fdfsolver *\"\"'\"); \n  }\n  arg1 = (gsl_multifit_fdfsolver *)(argp1);\n  result = (int)gsl_multifit_fdfsolver_iterate(arg1);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multifit_fdfsolver_free(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multifit_fdfsolver *arg1 = (gsl_multifit_fdfsolver *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multifit_fdfsolver_free\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multifit_fdfsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multifit_fdfsolver_free\" \"', argument \" \"1\"\" of type '\" \"gsl_multifit_fdfsolver *\"\"'\"); \n  }\n  arg1 = (gsl_multifit_fdfsolver *)(argp1);\n  gsl_multifit_fdfsolver_free(arg1);\n  resultobj = SWIG_Py_Void();\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multifit_fdfsolver_name(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multifit_fdfsolver *arg1 = (gsl_multifit_fdfsolver *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  char *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multifit_fdfsolver_name\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multifit_fdfsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multifit_fdfsolver_name\" \"', argument \" \"1\"\" of type '\" \"gsl_multifit_fdfsolver const *\"\"'\"); \n  }\n  arg1 = (gsl_multifit_fdfsolver *)(argp1);\n  result = (char *)gsl_multifit_fdfsolver_name((gsl_multifit_fdfsolver const *)arg1);\n  resultobj = SWIG_FromCharPtr((const char *)result);\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multifit_fdfsolver_position(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multifit_fdfsolver *arg1 = (gsl_multifit_fdfsolver *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  gsl_vector *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multifit_fdfsolver_position\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multifit_fdfsolver, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multifit_fdfsolver_position\" \"', argument \" \"1\"\" of type '\" \"gsl_multifit_fdfsolver const *\"\"'\"); \n  }\n  arg1 = (gsl_multifit_fdfsolver *)(argp1);\n  result = (gsl_vector *)gsl_multifit_fdfsolver_position((gsl_multifit_fdfsolver const *)arg1);\n  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_gsl_vector, 0 |  0 );\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multifit_test_delta(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector *arg1 = (gsl_vector *) 0 ;\n  gsl_vector *arg2 = (gsl_vector *) 0 ;\n  double arg3 ;\n  double arg4 ;\n  double val3 ;\n  int ecode3 = 0 ;\n  double val4 ;\n  int ecode4 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  PyObject * obj3 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\",(char *) \"IN\",(char *) \"epsabs\",(char *) \"epsrel\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector _vector1;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOOO:gsl_multifit_test_delta\",kwnames,&obj0,&obj1,&obj2,&obj3)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2,\n        PyGSL_INPUT_ARRAY, gsl_vector, 2, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  ecode3 = SWIG_AsVal_double(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_multifit_test_delta\" \"', argument \" \"3\"\" of type '\" \"double\"\"'\");\n  } \n  arg3 = (double)(val3);\n  ecode4 = SWIG_AsVal_double(obj3, &val4);\n  if (!SWIG_IsOK(ecode4)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode4), \"in method '\" \"gsl_multifit_test_delta\" \"', argument \" \"4\"\" of type '\" \"double\"\"'\");\n  } \n  arg4 = (double)(val4);\n  result = (int)gsl_multifit_test_delta((gsl_vector const *)arg1,(gsl_vector const *)arg2,arg3,arg4);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  {\n    Py_XDECREF(_PyVector1);\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyVector2);\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyVector1);\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyVector2);\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multifit_test_gradient(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector *arg1 = (gsl_vector *) 0 ;\n  double arg2 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\",(char *) \"epsabs\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_multifit_test_gradient\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_multifit_test_gradient\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  result = (int)gsl_multifit_test_gradient((gsl_vector const *)arg1,arg2);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  {\n    Py_XDECREF(_PyVector1);\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyVector1);\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN int Swig_var_gsl_multifit_fdfsolver_lmder_set(PyObject *_val SWIGUNUSED) {\n  SWIG_Error(SWIG_AttributeError,\"Variable gsl_multifit_fdfsolver_lmder is read-only.\");\n  return 1;\n}\n\n\nSWIGINTERN PyObject *Swig_var_gsl_multifit_fdfsolver_lmder_get(void) {\n  PyObject *pyobj = 0;\n  \n  pyobj = SWIG_NewPointerObj(SWIG_as_voidptr(gsl_multifit_fdfsolver_lmder), SWIGTYPE_p_gsl_multifit_fdfsolver_type,  0 );\n  return pyobj;\n}\n\n\nSWIGINTERN int Swig_var_gsl_multifit_fdfsolver_lmsder_set(PyObject *_val SWIGUNUSED) {\n  SWIG_Error(SWIG_AttributeError,\"Variable gsl_multifit_fdfsolver_lmsder is read-only.\");\n  return 1;\n}\n\n\nSWIGINTERN PyObject *Swig_var_gsl_multifit_fdfsolver_lmsder_get(void) {\n  PyObject *pyobj = 0;\n  \n  pyobj = SWIG_NewPointerObj(SWIG_as_voidptr(gsl_multifit_fdfsolver_lmsder), SWIGTYPE_p_gsl_multifit_fdfsolver_type,  0 );\n  return pyobj;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_integration_workspace_alloc(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  size_t arg1 ;\n  size_t val1 ;\n  int ecode1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"n\", NULL \n  };\n  gsl_integration_workspace *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_integration_workspace_alloc\",kwnames,&obj0)) SWIG_fail;\n  ecode1 = SWIG_AsVal_size_t(obj0, &val1);\n  if (!SWIG_IsOK(ecode1)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode1), \"in method '\" \"gsl_integration_workspace_alloc\" \"', argument \" \"1\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg1 = (size_t)(val1);\n  result = (gsl_integration_workspace *)gsl_integration_workspace_alloc(arg1);\n  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_gsl_integration_workspace, 0 |  0 );\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_integration_workspace_free(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_integration_workspace *arg1 = (gsl_integration_workspace *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"w\", NULL \n  };\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_integration_workspace_free\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_integration_workspace, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_integration_workspace_free\" \"', argument \" \"1\"\" of type '\" \"gsl_integration_workspace *\"\"'\"); \n  }\n  arg1 = (gsl_integration_workspace *)(argp1);\n  gsl_integration_workspace_free(arg1);\n  resultobj = SWIG_Py_Void();\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_integration_workspace_get_size(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_integration_workspace *arg1 = (gsl_integration_workspace *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"w\", NULL \n  };\n  size_t result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_integration_workspace_get_size\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_integration_workspace, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_integration_workspace_get_size\" \"', argument \" \"1\"\" of type '\" \"gsl_integration_workspace *\"\"'\"); \n  }\n  arg1 = (gsl_integration_workspace *)(argp1);\n  result = (size_t)gsl_integration_workspace_get_size(arg1);\n  resultobj = SWIG_From_size_t((size_t)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_integration_qaws_table_alloc(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  double arg1 ;\n  double arg2 ;\n  int arg3 ;\n  int arg4 ;\n  double val1 ;\n  int ecode1 = 0 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  int val3 ;\n  int ecode3 = 0 ;\n  int val4 ;\n  int ecode4 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  PyObject * obj3 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"alpha\",(char *) \"beta\",(char *) \"mu\",(char *) \"nu\", NULL \n  };\n  gsl_integration_qaws_table *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOOO:gsl_integration_qaws_table_alloc\",kwnames,&obj0,&obj1,&obj2,&obj3)) SWIG_fail;\n  ecode1 = SWIG_AsVal_double(obj0, &val1);\n  if (!SWIG_IsOK(ecode1)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode1), \"in method '\" \"gsl_integration_qaws_table_alloc\" \"', argument \" \"1\"\" of type '\" \"double\"\"'\");\n  } \n  arg1 = (double)(val1);\n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_integration_qaws_table_alloc\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  ecode3 = SWIG_AsVal_int(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_integration_qaws_table_alloc\" \"', argument \" \"3\"\" of type '\" \"int\"\"'\");\n  } \n  arg3 = (int)(val3);\n  ecode4 = SWIG_AsVal_int(obj3, &val4);\n  if (!SWIG_IsOK(ecode4)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode4), \"in method '\" \"gsl_integration_qaws_table_alloc\" \"', argument \" \"4\"\" of type '\" \"int\"\"'\");\n  } \n  arg4 = (int)(val4);\n  result = (gsl_integration_qaws_table *)gsl_integration_qaws_table_alloc(arg1,arg2,arg3,arg4);\n  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_gsl_integration_qaws_table, 0 |  0 );\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_integration_qaws_table_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_integration_qaws_table *arg1 = (gsl_integration_qaws_table *) 0 ;\n  double arg2 ;\n  double arg3 ;\n  int arg4 ;\n  int arg5 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  double val3 ;\n  int ecode3 = 0 ;\n  int val4 ;\n  int ecode4 = 0 ;\n  int val5 ;\n  int ecode5 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  PyObject * obj3 = 0 ;\n  PyObject * obj4 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"t\",(char *) \"alpha\",(char *) \"beta\",(char *) \"mu\",(char *) \"nu\", NULL \n  };\n  int result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOOOO:gsl_integration_qaws_table_set\",kwnames,&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_integration_qaws_table, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_integration_qaws_table_set\" \"', argument \" \"1\"\" of type '\" \"gsl_integration_qaws_table *\"\"'\"); \n  }\n  arg1 = (gsl_integration_qaws_table *)(argp1);\n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_integration_qaws_table_set\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  ecode3 = SWIG_AsVal_double(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_integration_qaws_table_set\" \"', argument \" \"3\"\" of type '\" \"double\"\"'\");\n  } \n  arg3 = (double)(val3);\n  ecode4 = SWIG_AsVal_int(obj3, &val4);\n  if (!SWIG_IsOK(ecode4)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode4), \"in method '\" \"gsl_integration_qaws_table_set\" \"', argument \" \"4\"\" of type '\" \"int\"\"'\");\n  } \n  arg4 = (int)(val4);\n  ecode5 = SWIG_AsVal_int(obj4, &val5);\n  if (!SWIG_IsOK(ecode5)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode5), \"in method '\" \"gsl_integration_qaws_table_set\" \"', argument \" \"5\"\" of type '\" \"int\"\"'\");\n  } \n  arg5 = (int)(val5);\n  result = (int)gsl_integration_qaws_table_set(arg1,arg2,arg3,arg4,arg5);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_integration_qaws_table_free(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_integration_qaws_table *arg1 = (gsl_integration_qaws_table *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"t\", NULL \n  };\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_integration_qaws_table_free\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_integration_qaws_table, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_integration_qaws_table_free\" \"', argument \" \"1\"\" of type '\" \"gsl_integration_qaws_table *\"\"'\"); \n  }\n  arg1 = (gsl_integration_qaws_table *)(argp1);\n  gsl_integration_qaws_table_free(arg1);\n  resultobj = SWIG_Py_Void();\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_integration_qawo_table_alloc(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  double arg1 ;\n  double arg2 ;\n  enum gsl_integration_qawo_enum arg3 ;\n  size_t arg4 ;\n  double val1 ;\n  int ecode1 = 0 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  int val3 ;\n  int ecode3 = 0 ;\n  size_t val4 ;\n  int ecode4 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  PyObject * obj3 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"omega\",(char *) \"L\",(char *) \"sine\",(char *) \"n\", NULL \n  };\n  gsl_integration_qawo_table *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOOO:gsl_integration_qawo_table_alloc\",kwnames,&obj0,&obj1,&obj2,&obj3)) SWIG_fail;\n  ecode1 = SWIG_AsVal_double(obj0, &val1);\n  if (!SWIG_IsOK(ecode1)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode1), \"in method '\" \"gsl_integration_qawo_table_alloc\" \"', argument \" \"1\"\" of type '\" \"double\"\"'\");\n  } \n  arg1 = (double)(val1);\n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_integration_qawo_table_alloc\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  ecode3 = SWIG_AsVal_int(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_integration_qawo_table_alloc\" \"', argument \" \"3\"\" of type '\" \"enum gsl_integration_qawo_enum\"\"'\");\n  } \n  arg3 = (enum gsl_integration_qawo_enum)(val3);\n  ecode4 = SWIG_AsVal_size_t(obj3, &val4);\n  if (!SWIG_IsOK(ecode4)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode4), \"in method '\" \"gsl_integration_qawo_table_alloc\" \"', argument \" \"4\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg4 = (size_t)(val4);\n  result = (gsl_integration_qawo_table *)gsl_integration_qawo_table_alloc(arg1,arg2,arg3,arg4);\n  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_gsl_integration_qawo_table, 0 |  0 );\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_integration_qawo_table_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_integration_qawo_table *arg1 = (gsl_integration_qawo_table *) 0 ;\n  double arg2 ;\n  double arg3 ;\n  enum gsl_integration_qawo_enum arg4 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  double val3 ;\n  int ecode3 = 0 ;\n  int val4 ;\n  int ecode4 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  PyObject * obj3 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"t\",(char *) \"omega\",(char *) \"L\",(char *) \"sine\", NULL \n  };\n  int result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOOO:gsl_integration_qawo_table_set\",kwnames,&obj0,&obj1,&obj2,&obj3)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_integration_qawo_table, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_integration_qawo_table_set\" \"', argument \" \"1\"\" of type '\" \"gsl_integration_qawo_table *\"\"'\"); \n  }\n  arg1 = (gsl_integration_qawo_table *)(argp1);\n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_integration_qawo_table_set\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  ecode3 = SWIG_AsVal_double(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_integration_qawo_table_set\" \"', argument \" \"3\"\" of type '\" \"double\"\"'\");\n  } \n  arg3 = (double)(val3);\n  ecode4 = SWIG_AsVal_int(obj3, &val4);\n  if (!SWIG_IsOK(ecode4)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode4), \"in method '\" \"gsl_integration_qawo_table_set\" \"', argument \" \"4\"\" of type '\" \"enum gsl_integration_qawo_enum\"\"'\");\n  } \n  arg4 = (enum gsl_integration_qawo_enum)(val4);\n  result = (int)gsl_integration_qawo_table_set(arg1,arg2,arg3,arg4);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_integration_qawo_table_set_length(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_integration_qawo_table *arg1 = (gsl_integration_qawo_table *) 0 ;\n  double arg2 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"t\",(char *) \"L\", NULL \n  };\n  int result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_integration_qawo_table_set_length\",kwnames,&obj0,&obj1)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_integration_qawo_table, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_integration_qawo_table_set_length\" \"', argument \" \"1\"\" of type '\" \"gsl_integration_qawo_table *\"\"'\"); \n  }\n  arg1 = (gsl_integration_qawo_table *)(argp1);\n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_integration_qawo_table_set_length\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  result = (int)gsl_integration_qawo_table_set_length(arg1,arg2);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_integration_qawo_table_free(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_integration_qawo_table *arg1 = (gsl_integration_qawo_table *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"t\", NULL \n  };\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_integration_qawo_table_free\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_integration_qawo_table, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_integration_qawo_table_free\" \"', argument \" \"1\"\" of type '\" \"gsl_integration_qawo_table *\"\"'\"); \n  }\n  arg1 = (gsl_integration_qawo_table *)(argp1);\n  gsl_integration_qawo_table_free(arg1);\n  resultobj = SWIG_Py_Void();\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_integration_qng(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_function *arg1 = (gsl_function *) 0 ;\n  double arg2 ;\n  double arg3 ;\n  double arg4 ;\n  double arg5 ;\n  double *arg6 = (double *) 0 ;\n  double *arg7 = (double *) 0 ;\n  size_t *arg8 = (size_t *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  double val3 ;\n  int ecode3 = 0 ;\n  double val4 ;\n  int ecode4 = 0 ;\n  double val5 ;\n  int ecode5 = 0 ;\n  double temp6 ;\n  int res6 = SWIG_TMPOBJ ;\n  double temp7 ;\n  int res7 = SWIG_TMPOBJ ;\n  size_t temp8 ;\n  int res8 = SWIG_TMPOBJ ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  PyObject * obj3 = 0 ;\n  PyObject * obj4 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"BUFFER\",(char *) \"a\",(char *) \"b\",(char *) \"epsabs\",(char *) \"epsrel\", NULL \n  };\n  int result;\n  \n  \n  gsl_function * volatile _solver1 = NULL;\n  \n  arg6 = &temp6;\n  arg7 = &temp7;\n  arg8 = &temp8;\n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOOOO:gsl_integration_qng\",kwnames,&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_function, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_integration_qng\" \"', argument \" \"1\"\" of type '\" \"gsl_function const *\"\"'\"); \n  }\n  arg1 = (gsl_function *)(argp1);\n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_integration_qng\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  ecode3 = SWIG_AsVal_double(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_integration_qng\" \"', argument \" \"3\"\" of type '\" \"double\"\"'\");\n  } \n  arg3 = (double)(val3);\n  ecode4 = SWIG_AsVal_double(obj3, &val4);\n  if (!SWIG_IsOK(ecode4)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode4), \"in method '\" \"gsl_integration_qng\" \"', argument \" \"4\"\" of type '\" \"double\"\"'\");\n  } \n  arg4 = (double)(val4);\n  ecode5 = SWIG_AsVal_double(obj4, &val5);\n  if (!SWIG_IsOK(ecode5)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode5), \"in method '\" \"gsl_integration_qng\" \"', argument \" \"5\"\" of type '\" \"double\"\"'\");\n  } \n  arg5 = (double)(val5);\n  {\n    int flag;\n    callback_function_params * p;\n    \n    FUNC_MESS(\"\\t\\t Setting jump buffer\");\n    assert(arg1);\n    \n    \n    _solver1 = arg1;\n    p = (callback_function_params *) \n    PyGSL_gsl_function_GET_PARAMS(_solver1);\n    \n    if((flag=setjmp(p->buffer)) == 0){\n      FUNC_MESS(\"\\t\\t Setting Jmp Buffer\");\n      p->buffer_is_set = 1;\n    } else {\n      FUNC_MESS(\"\\t\\t Returning from Jmp Buffer\");\n      p->buffer_is_set = 0;\n      goto fail;\n    }\n    \n    FUNC_MESS(\"\\t\\t END Setting jump buffer\");\n  }\n  result = (int)gsl_integration_qng((gsl_function const *)arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  if (SWIG_IsTmpObj(res6)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg6)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res6) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg6), SWIGTYPE_p_double, new_flags));\n  }\n  if (SWIG_IsTmpObj(res7)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg7)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res7) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg7), SWIGTYPE_p_double, new_flags));\n  }\n  if (SWIG_IsTmpObj(res8)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_unsigned_SS_int((*arg8)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res8) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg8), SWIGTYPE_p_unsigned_int, new_flags));\n  }\n  {\n    callback_function_params * p;\n    if(_solver1){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params *)  \n      PyGSL_gsl_function_GET_PARAMS(_solver1);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  return resultobj;\nfail:\n  {\n    callback_function_params * p;\n    if(_solver1){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params *)  \n      PyGSL_gsl_function_GET_PARAMS(_solver1);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_integration_qag(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_function *arg1 = (gsl_function *) 0 ;\n  double arg2 ;\n  double arg3 ;\n  double arg4 ;\n  double arg5 ;\n  size_t arg6 ;\n  int arg7 ;\n  gsl_integration_workspace *arg8 = (gsl_integration_workspace *) 0 ;\n  double *arg9 = (double *) 0 ;\n  double *arg10 = (double *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  double val3 ;\n  int ecode3 = 0 ;\n  double val4 ;\n  int ecode4 = 0 ;\n  double val5 ;\n  int ecode5 = 0 ;\n  size_t val6 ;\n  int ecode6 = 0 ;\n  int val7 ;\n  int ecode7 = 0 ;\n  void *argp8 = 0 ;\n  int res8 = 0 ;\n  double temp9 ;\n  int res9 = SWIG_TMPOBJ ;\n  double temp10 ;\n  int res10 = SWIG_TMPOBJ ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  PyObject * obj3 = 0 ;\n  PyObject * obj4 = 0 ;\n  PyObject * obj5 = 0 ;\n  PyObject * obj6 = 0 ;\n  PyObject * obj7 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"BUFFER\",(char *) \"a\",(char *) \"b\",(char *) \"epsabs\",(char *) \"epsrel\",(char *) \"limit\",(char *) \"key\",(char *) \"workspace\", NULL \n  };\n  int result;\n  \n  \n  gsl_function * volatile _solver1 = NULL;\n  \n  arg9 = &temp9;\n  arg10 = &temp10;\n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOOOOOOO:gsl_integration_qag\",kwnames,&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_function, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_integration_qag\" \"', argument \" \"1\"\" of type '\" \"gsl_function const *\"\"'\"); \n  }\n  arg1 = (gsl_function *)(argp1);\n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_integration_qag\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  ecode3 = SWIG_AsVal_double(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_integration_qag\" \"', argument \" \"3\"\" of type '\" \"double\"\"'\");\n  } \n  arg3 = (double)(val3);\n  ecode4 = SWIG_AsVal_double(obj3, &val4);\n  if (!SWIG_IsOK(ecode4)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode4), \"in method '\" \"gsl_integration_qag\" \"', argument \" \"4\"\" of type '\" \"double\"\"'\");\n  } \n  arg4 = (double)(val4);\n  ecode5 = SWIG_AsVal_double(obj4, &val5);\n  if (!SWIG_IsOK(ecode5)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode5), \"in method '\" \"gsl_integration_qag\" \"', argument \" \"5\"\" of type '\" \"double\"\"'\");\n  } \n  arg5 = (double)(val5);\n  ecode6 = SWIG_AsVal_size_t(obj5, &val6);\n  if (!SWIG_IsOK(ecode6)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode6), \"in method '\" \"gsl_integration_qag\" \"', argument \" \"6\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg6 = (size_t)(val6);\n  ecode7 = SWIG_AsVal_int(obj6, &val7);\n  if (!SWIG_IsOK(ecode7)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode7), \"in method '\" \"gsl_integration_qag\" \"', argument \" \"7\"\" of type '\" \"int\"\"'\");\n  } \n  arg7 = (int)(val7);\n  res8 = SWIG_ConvertPtr(obj7, &argp8,SWIGTYPE_p_gsl_integration_workspace, 0 |  0 );\n  if (!SWIG_IsOK(res8)) {\n    SWIG_exception_fail(SWIG_ArgError(res8), \"in method '\" \"gsl_integration_qag\" \"', argument \" \"8\"\" of type '\" \"gsl_integration_workspace *\"\"'\"); \n  }\n  arg8 = (gsl_integration_workspace *)(argp8);\n  {\n    int flag;\n    callback_function_params * p;\n    \n    FUNC_MESS(\"\\t\\t Setting jump buffer\");\n    assert(arg1);\n    \n    \n    _solver1 = arg1;\n    p = (callback_function_params *) \n    PyGSL_gsl_function_GET_PARAMS(_solver1);\n    \n    if((flag=setjmp(p->buffer)) == 0){\n      FUNC_MESS(\"\\t\\t Setting Jmp Buffer\");\n      p->buffer_is_set = 1;\n    } else {\n      FUNC_MESS(\"\\t\\t Returning from Jmp Buffer\");\n      p->buffer_is_set = 0;\n      goto fail;\n    }\n    \n    FUNC_MESS(\"\\t\\t END Setting jump buffer\");\n  }\n  result = (int)gsl_integration_qag((gsl_function const *)arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  if (SWIG_IsTmpObj(res9)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg9)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res9) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg9), SWIGTYPE_p_double, new_flags));\n  }\n  if (SWIG_IsTmpObj(res10)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg10)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res10) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg10), SWIGTYPE_p_double, new_flags));\n  }\n  {\n    callback_function_params * p;\n    if(_solver1){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params *)  \n      PyGSL_gsl_function_GET_PARAMS(_solver1);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  return resultobj;\nfail:\n  {\n    callback_function_params * p;\n    if(_solver1){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params *)  \n      PyGSL_gsl_function_GET_PARAMS(_solver1);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_integration_qagi(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_function *arg1 = (gsl_function *) 0 ;\n  double arg2 ;\n  double arg3 ;\n  size_t arg4 ;\n  gsl_integration_workspace *arg5 = (gsl_integration_workspace *) 0 ;\n  double *arg6 = (double *) 0 ;\n  double *arg7 = (double *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  double val3 ;\n  int ecode3 = 0 ;\n  size_t val4 ;\n  int ecode4 = 0 ;\n  void *argp5 = 0 ;\n  int res5 = 0 ;\n  double temp6 ;\n  int res6 = SWIG_TMPOBJ ;\n  double temp7 ;\n  int res7 = SWIG_TMPOBJ ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  PyObject * obj3 = 0 ;\n  PyObject * obj4 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"BUFFER\",(char *) \"epsabs\",(char *) \"epsrel\",(char *) \"limit\",(char *) \"workspace\", NULL \n  };\n  int result;\n  \n  \n  gsl_function * volatile _solver1 = NULL;\n  \n  arg6 = &temp6;\n  arg7 = &temp7;\n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOOOO:gsl_integration_qagi\",kwnames,&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_function, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_integration_qagi\" \"', argument \" \"1\"\" of type '\" \"gsl_function *\"\"'\"); \n  }\n  arg1 = (gsl_function *)(argp1);\n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_integration_qagi\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  ecode3 = SWIG_AsVal_double(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_integration_qagi\" \"', argument \" \"3\"\" of type '\" \"double\"\"'\");\n  } \n  arg3 = (double)(val3);\n  ecode4 = SWIG_AsVal_size_t(obj3, &val4);\n  if (!SWIG_IsOK(ecode4)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode4), \"in method '\" \"gsl_integration_qagi\" \"', argument \" \"4\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg4 = (size_t)(val4);\n  res5 = SWIG_ConvertPtr(obj4, &argp5,SWIGTYPE_p_gsl_integration_workspace, 0 |  0 );\n  if (!SWIG_IsOK(res5)) {\n    SWIG_exception_fail(SWIG_ArgError(res5), \"in method '\" \"gsl_integration_qagi\" \"', argument \" \"5\"\" of type '\" \"gsl_integration_workspace *\"\"'\"); \n  }\n  arg5 = (gsl_integration_workspace *)(argp5);\n  {\n    int flag;\n    callback_function_params * p;\n    \n    FUNC_MESS(\"\\t\\t Setting jump buffer\");\n    assert(arg1);\n    \n    \n    _solver1 = arg1;\n    p = (callback_function_params *) \n    PyGSL_gsl_function_GET_PARAMS(_solver1);\n    \n    if((flag=setjmp(p->buffer)) == 0){\n      FUNC_MESS(\"\\t\\t Setting Jmp Buffer\");\n      p->buffer_is_set = 1;\n    } else {\n      FUNC_MESS(\"\\t\\t Returning from Jmp Buffer\");\n      p->buffer_is_set = 0;\n      goto fail;\n    }\n    \n    FUNC_MESS(\"\\t\\t END Setting jump buffer\");\n  }\n  result = (int)gsl_integration_qagi(arg1,arg2,arg3,arg4,arg5,arg6,arg7);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  if (SWIG_IsTmpObj(res6)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg6)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res6) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg6), SWIGTYPE_p_double, new_flags));\n  }\n  if (SWIG_IsTmpObj(res7)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg7)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res7) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg7), SWIGTYPE_p_double, new_flags));\n  }\n  {\n    callback_function_params * p;\n    if(_solver1){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params *)  \n      PyGSL_gsl_function_GET_PARAMS(_solver1);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  return resultobj;\nfail:\n  {\n    callback_function_params * p;\n    if(_solver1){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params *)  \n      PyGSL_gsl_function_GET_PARAMS(_solver1);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_integration_qagiu(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_function *arg1 = (gsl_function *) 0 ;\n  double arg2 ;\n  double arg3 ;\n  double arg4 ;\n  size_t arg5 ;\n  gsl_integration_workspace *arg6 = (gsl_integration_workspace *) 0 ;\n  double *arg7 = (double *) 0 ;\n  double *arg8 = (double *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  double val3 ;\n  int ecode3 = 0 ;\n  double val4 ;\n  int ecode4 = 0 ;\n  size_t val5 ;\n  int ecode5 = 0 ;\n  void *argp6 = 0 ;\n  int res6 = 0 ;\n  double temp7 ;\n  int res7 = SWIG_TMPOBJ ;\n  double temp8 ;\n  int res8 = SWIG_TMPOBJ ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  PyObject * obj3 = 0 ;\n  PyObject * obj4 = 0 ;\n  PyObject * obj5 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"BUFFER\",(char *) \"a\",(char *) \"epsabs\",(char *) \"epsrel\",(char *) \"limit\",(char *) \"workspace\", NULL \n  };\n  int result;\n  \n  \n  gsl_function * volatile _solver1 = NULL;\n  \n  arg7 = &temp7;\n  arg8 = &temp8;\n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOOOOO:gsl_integration_qagiu\",kwnames,&obj0,&obj1,&obj2,&obj3,&obj4,&obj5)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_function, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_integration_qagiu\" \"', argument \" \"1\"\" of type '\" \"gsl_function *\"\"'\"); \n  }\n  arg1 = (gsl_function *)(argp1);\n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_integration_qagiu\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  ecode3 = SWIG_AsVal_double(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_integration_qagiu\" \"', argument \" \"3\"\" of type '\" \"double\"\"'\");\n  } \n  arg3 = (double)(val3);\n  ecode4 = SWIG_AsVal_double(obj3, &val4);\n  if (!SWIG_IsOK(ecode4)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode4), \"in method '\" \"gsl_integration_qagiu\" \"', argument \" \"4\"\" of type '\" \"double\"\"'\");\n  } \n  arg4 = (double)(val4);\n  ecode5 = SWIG_AsVal_size_t(obj4, &val5);\n  if (!SWIG_IsOK(ecode5)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode5), \"in method '\" \"gsl_integration_qagiu\" \"', argument \" \"5\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg5 = (size_t)(val5);\n  res6 = SWIG_ConvertPtr(obj5, &argp6,SWIGTYPE_p_gsl_integration_workspace, 0 |  0 );\n  if (!SWIG_IsOK(res6)) {\n    SWIG_exception_fail(SWIG_ArgError(res6), \"in method '\" \"gsl_integration_qagiu\" \"', argument \" \"6\"\" of type '\" \"gsl_integration_workspace *\"\"'\"); \n  }\n  arg6 = (gsl_integration_workspace *)(argp6);\n  {\n    int flag;\n    callback_function_params * p;\n    \n    FUNC_MESS(\"\\t\\t Setting jump buffer\");\n    assert(arg1);\n    \n    \n    _solver1 = arg1;\n    p = (callback_function_params *) \n    PyGSL_gsl_function_GET_PARAMS(_solver1);\n    \n    if((flag=setjmp(p->buffer)) == 0){\n      FUNC_MESS(\"\\t\\t Setting Jmp Buffer\");\n      p->buffer_is_set = 1;\n    } else {\n      FUNC_MESS(\"\\t\\t Returning from Jmp Buffer\");\n      p->buffer_is_set = 0;\n      goto fail;\n    }\n    \n    FUNC_MESS(\"\\t\\t END Setting jump buffer\");\n  }\n  result = (int)gsl_integration_qagiu(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  if (SWIG_IsTmpObj(res7)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg7)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res7) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg7), SWIGTYPE_p_double, new_flags));\n  }\n  if (SWIG_IsTmpObj(res8)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg8)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res8) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg8), SWIGTYPE_p_double, new_flags));\n  }\n  {\n    callback_function_params * p;\n    if(_solver1){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params *)  \n      PyGSL_gsl_function_GET_PARAMS(_solver1);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  return resultobj;\nfail:\n  {\n    callback_function_params * p;\n    if(_solver1){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params *)  \n      PyGSL_gsl_function_GET_PARAMS(_solver1);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_integration_qagil(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_function *arg1 = (gsl_function *) 0 ;\n  double arg2 ;\n  double arg3 ;\n  double arg4 ;\n  size_t arg5 ;\n  gsl_integration_workspace *arg6 = (gsl_integration_workspace *) 0 ;\n  double *arg7 = (double *) 0 ;\n  double *arg8 = (double *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  double val3 ;\n  int ecode3 = 0 ;\n  double val4 ;\n  int ecode4 = 0 ;\n  size_t val5 ;\n  int ecode5 = 0 ;\n  void *argp6 = 0 ;\n  int res6 = 0 ;\n  double temp7 ;\n  int res7 = SWIG_TMPOBJ ;\n  double temp8 ;\n  int res8 = SWIG_TMPOBJ ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  PyObject * obj3 = 0 ;\n  PyObject * obj4 = 0 ;\n  PyObject * obj5 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"BUFFER\",(char *) \"b\",(char *) \"epsabs\",(char *) \"epsrel\",(char *) \"limit\",(char *) \"workspace\", NULL \n  };\n  int result;\n  \n  \n  gsl_function * volatile _solver1 = NULL;\n  \n  arg7 = &temp7;\n  arg8 = &temp8;\n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOOOOO:gsl_integration_qagil\",kwnames,&obj0,&obj1,&obj2,&obj3,&obj4,&obj5)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_function, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_integration_qagil\" \"', argument \" \"1\"\" of type '\" \"gsl_function *\"\"'\"); \n  }\n  arg1 = (gsl_function *)(argp1);\n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_integration_qagil\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  ecode3 = SWIG_AsVal_double(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_integration_qagil\" \"', argument \" \"3\"\" of type '\" \"double\"\"'\");\n  } \n  arg3 = (double)(val3);\n  ecode4 = SWIG_AsVal_double(obj3, &val4);\n  if (!SWIG_IsOK(ecode4)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode4), \"in method '\" \"gsl_integration_qagil\" \"', argument \" \"4\"\" of type '\" \"double\"\"'\");\n  } \n  arg4 = (double)(val4);\n  ecode5 = SWIG_AsVal_size_t(obj4, &val5);\n  if (!SWIG_IsOK(ecode5)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode5), \"in method '\" \"gsl_integration_qagil\" \"', argument \" \"5\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg5 = (size_t)(val5);\n  res6 = SWIG_ConvertPtr(obj5, &argp6,SWIGTYPE_p_gsl_integration_workspace, 0 |  0 );\n  if (!SWIG_IsOK(res6)) {\n    SWIG_exception_fail(SWIG_ArgError(res6), \"in method '\" \"gsl_integration_qagil\" \"', argument \" \"6\"\" of type '\" \"gsl_integration_workspace *\"\"'\"); \n  }\n  arg6 = (gsl_integration_workspace *)(argp6);\n  {\n    int flag;\n    callback_function_params * p;\n    \n    FUNC_MESS(\"\\t\\t Setting jump buffer\");\n    assert(arg1);\n    \n    \n    _solver1 = arg1;\n    p = (callback_function_params *) \n    PyGSL_gsl_function_GET_PARAMS(_solver1);\n    \n    if((flag=setjmp(p->buffer)) == 0){\n      FUNC_MESS(\"\\t\\t Setting Jmp Buffer\");\n      p->buffer_is_set = 1;\n    } else {\n      FUNC_MESS(\"\\t\\t Returning from Jmp Buffer\");\n      p->buffer_is_set = 0;\n      goto fail;\n    }\n    \n    FUNC_MESS(\"\\t\\t END Setting jump buffer\");\n  }\n  result = (int)gsl_integration_qagil(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  if (SWIG_IsTmpObj(res7)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg7)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res7) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg7), SWIGTYPE_p_double, new_flags));\n  }\n  if (SWIG_IsTmpObj(res8)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg8)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res8) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg8), SWIGTYPE_p_double, new_flags));\n  }\n  {\n    callback_function_params * p;\n    if(_solver1){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params *)  \n      PyGSL_gsl_function_GET_PARAMS(_solver1);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  return resultobj;\nfail:\n  {\n    callback_function_params * p;\n    if(_solver1){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params *)  \n      PyGSL_gsl_function_GET_PARAMS(_solver1);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_integration_qags(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_function *arg1 = (gsl_function *) 0 ;\n  double arg2 ;\n  double arg3 ;\n  double arg4 ;\n  double arg5 ;\n  size_t arg6 ;\n  gsl_integration_workspace *arg7 = (gsl_integration_workspace *) 0 ;\n  double *arg8 = (double *) 0 ;\n  double *arg9 = (double *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  double val3 ;\n  int ecode3 = 0 ;\n  double val4 ;\n  int ecode4 = 0 ;\n  double val5 ;\n  int ecode5 = 0 ;\n  size_t val6 ;\n  int ecode6 = 0 ;\n  void *argp7 = 0 ;\n  int res7 = 0 ;\n  double temp8 ;\n  int res8 = SWIG_TMPOBJ ;\n  double temp9 ;\n  int res9 = SWIG_TMPOBJ ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  PyObject * obj3 = 0 ;\n  PyObject * obj4 = 0 ;\n  PyObject * obj5 = 0 ;\n  PyObject * obj6 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"BUFFER\",(char *) \"a\",(char *) \"b\",(char *) \"epsabs\",(char *) \"epsrel\",(char *) \"limit\",(char *) \"workspace\", NULL \n  };\n  int result;\n  \n  \n  gsl_function * volatile _solver1 = NULL;\n  \n  arg8 = &temp8;\n  arg9 = &temp9;\n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOOOOOO:gsl_integration_qags\",kwnames,&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_function, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_integration_qags\" \"', argument \" \"1\"\" of type '\" \"gsl_function const *\"\"'\"); \n  }\n  arg1 = (gsl_function *)(argp1);\n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_integration_qags\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  ecode3 = SWIG_AsVal_double(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_integration_qags\" \"', argument \" \"3\"\" of type '\" \"double\"\"'\");\n  } \n  arg3 = (double)(val3);\n  ecode4 = SWIG_AsVal_double(obj3, &val4);\n  if (!SWIG_IsOK(ecode4)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode4), \"in method '\" \"gsl_integration_qags\" \"', argument \" \"4\"\" of type '\" \"double\"\"'\");\n  } \n  arg4 = (double)(val4);\n  ecode5 = SWIG_AsVal_double(obj4, &val5);\n  if (!SWIG_IsOK(ecode5)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode5), \"in method '\" \"gsl_integration_qags\" \"', argument \" \"5\"\" of type '\" \"double\"\"'\");\n  } \n  arg5 = (double)(val5);\n  ecode6 = SWIG_AsVal_size_t(obj5, &val6);\n  if (!SWIG_IsOK(ecode6)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode6), \"in method '\" \"gsl_integration_qags\" \"', argument \" \"6\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg6 = (size_t)(val6);\n  res7 = SWIG_ConvertPtr(obj6, &argp7,SWIGTYPE_p_gsl_integration_workspace, 0 |  0 );\n  if (!SWIG_IsOK(res7)) {\n    SWIG_exception_fail(SWIG_ArgError(res7), \"in method '\" \"gsl_integration_qags\" \"', argument \" \"7\"\" of type '\" \"gsl_integration_workspace *\"\"'\"); \n  }\n  arg7 = (gsl_integration_workspace *)(argp7);\n  {\n    int flag;\n    callback_function_params * p;\n    \n    FUNC_MESS(\"\\t\\t Setting jump buffer\");\n    assert(arg1);\n    \n    \n    _solver1 = arg1;\n    p = (callback_function_params *) \n    PyGSL_gsl_function_GET_PARAMS(_solver1);\n    \n    if((flag=setjmp(p->buffer)) == 0){\n      FUNC_MESS(\"\\t\\t Setting Jmp Buffer\");\n      p->buffer_is_set = 1;\n    } else {\n      FUNC_MESS(\"\\t\\t Returning from Jmp Buffer\");\n      p->buffer_is_set = 0;\n      goto fail;\n    }\n    \n    FUNC_MESS(\"\\t\\t END Setting jump buffer\");\n  }\n  result = (int)gsl_integration_qags((gsl_function const *)arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  if (SWIG_IsTmpObj(res8)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg8)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res8) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg8), SWIGTYPE_p_double, new_flags));\n  }\n  if (SWIG_IsTmpObj(res9)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg9)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res9) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg9), SWIGTYPE_p_double, new_flags));\n  }\n  {\n    callback_function_params * p;\n    if(_solver1){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params *)  \n      PyGSL_gsl_function_GET_PARAMS(_solver1);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  return resultobj;\nfail:\n  {\n    callback_function_params * p;\n    if(_solver1){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params *)  \n      PyGSL_gsl_function_GET_PARAMS(_solver1);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_integration_qagp(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_function *arg1 = (gsl_function *) 0 ;\n  double *arg2 = (double *) 0 ;\n  size_t arg3 ;\n  double arg4 ;\n  double arg5 ;\n  size_t arg6 ;\n  gsl_integration_workspace *arg7 = (gsl_integration_workspace *) 0 ;\n  double *arg8 = (double *) 0 ;\n  double *arg9 = (double *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  double val4 ;\n  int ecode4 = 0 ;\n  double val5 ;\n  int ecode5 = 0 ;\n  size_t val6 ;\n  int ecode6 = 0 ;\n  void *argp7 = 0 ;\n  int res7 = 0 ;\n  double temp8 ;\n  int res8 = SWIG_TMPOBJ ;\n  double temp9 ;\n  int res9 = SWIG_TMPOBJ ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  PyObject * obj3 = 0 ;\n  PyObject * obj4 = 0 ;\n  PyObject * obj5 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"BUFFER\",(char *) \"pts\",(char *) \"epsabs\",(char *) \"epsrel\",(char *) \"limit\",(char *) \"workspace\", NULL \n  };\n  int result;\n  \n  \n  gsl_function * volatile _solver1 = NULL;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  \n  arg8 = &temp8;\n  arg9 = &temp9;\n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOOOOO:gsl_integration_qagp\",kwnames,&obj0,&obj1,&obj2,&obj3,&obj4,&obj5)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_function, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_integration_qagp\" \"', argument \" \"1\"\" of type '\" \"gsl_function const *\"\"'\"); \n  }\n  arg1 = (gsl_function *)(argp1);\n  \n  _PyVector2 = PyGSL_vector_check(obj1, -1, PyGSL_DARRAY_CINPUT(2), NULL, NULL);\n  if (_PyVector2 == NULL)\n  goto fail;\n  arg2 = (double*)(_PyVector2->data);\n  arg3 = _PyVector2->dimensions[0];\n  \n  ecode4 = SWIG_AsVal_double(obj2, &val4);\n  if (!SWIG_IsOK(ecode4)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode4), \"in method '\" \"gsl_integration_qagp\" \"', argument \" \"4\"\" of type '\" \"double\"\"'\");\n  } \n  arg4 = (double)(val4);\n  ecode5 = SWIG_AsVal_double(obj3, &val5);\n  if (!SWIG_IsOK(ecode5)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode5), \"in method '\" \"gsl_integration_qagp\" \"', argument \" \"5\"\" of type '\" \"double\"\"'\");\n  } \n  arg5 = (double)(val5);\n  ecode6 = SWIG_AsVal_size_t(obj4, &val6);\n  if (!SWIG_IsOK(ecode6)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode6), \"in method '\" \"gsl_integration_qagp\" \"', argument \" \"6\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg6 = (size_t)(val6);\n  res7 = SWIG_ConvertPtr(obj5, &argp7,SWIGTYPE_p_gsl_integration_workspace, 0 |  0 );\n  if (!SWIG_IsOK(res7)) {\n    SWIG_exception_fail(SWIG_ArgError(res7), \"in method '\" \"gsl_integration_qagp\" \"', argument \" \"7\"\" of type '\" \"gsl_integration_workspace *\"\"'\"); \n  }\n  arg7 = (gsl_integration_workspace *)(argp7);\n  {\n    int flag;\n    callback_function_params * p;\n    \n    FUNC_MESS(\"\\t\\t Setting jump buffer\");\n    assert(arg1);\n    \n    \n    _solver1 = arg1;\n    p = (callback_function_params *) \n    PyGSL_gsl_function_GET_PARAMS(_solver1);\n    \n    if((flag=setjmp(p->buffer)) == 0){\n      FUNC_MESS(\"\\t\\t Setting Jmp Buffer\");\n      p->buffer_is_set = 1;\n    } else {\n      FUNC_MESS(\"\\t\\t Returning from Jmp Buffer\");\n      p->buffer_is_set = 0;\n      goto fail;\n    }\n    \n    FUNC_MESS(\"\\t\\t END Setting jump buffer\");\n  }\n  result = (int)gsl_integration_qagp((gsl_function const *)arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  {\n    Py_XDECREF(_PyVector2);\n  }\n  if (SWIG_IsTmpObj(res8)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg8)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res8) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg8), SWIGTYPE_p_double, new_flags));\n  }\n  if (SWIG_IsTmpObj(res9)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg9)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res9) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg9), SWIGTYPE_p_double, new_flags));\n  }\n  {\n    callback_function_params * p;\n    if(_solver1){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params *)  \n      PyGSL_gsl_function_GET_PARAMS(_solver1);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  return resultobj;\nfail:\n  {\n    callback_function_params * p;\n    if(_solver1){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params *)  \n      PyGSL_gsl_function_GET_PARAMS(_solver1);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_integration_qawc(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_function *arg1 = (gsl_function *) 0 ;\n  double arg2 ;\n  double arg3 ;\n  double arg4 ;\n  double arg5 ;\n  double arg6 ;\n  size_t arg7 ;\n  gsl_integration_workspace *arg8 = (gsl_integration_workspace *) 0 ;\n  double *arg9 = (double *) 0 ;\n  double *arg10 = (double *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  double val3 ;\n  int ecode3 = 0 ;\n  double val4 ;\n  int ecode4 = 0 ;\n  double val5 ;\n  int ecode5 = 0 ;\n  double val6 ;\n  int ecode6 = 0 ;\n  size_t val7 ;\n  int ecode7 = 0 ;\n  void *argp8 = 0 ;\n  int res8 = 0 ;\n  double temp9 ;\n  int res9 = SWIG_TMPOBJ ;\n  double temp10 ;\n  int res10 = SWIG_TMPOBJ ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  PyObject * obj3 = 0 ;\n  PyObject * obj4 = 0 ;\n  PyObject * obj5 = 0 ;\n  PyObject * obj6 = 0 ;\n  PyObject * obj7 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"BUFFER\",(char *) \"a\",(char *) \"b\",(char *) \"c\",(char *) \"epsabs\",(char *) \"epsrel\",(char *) \"limit\",(char *) \"workspace\", NULL \n  };\n  int result;\n  \n  \n  gsl_function * volatile _solver1 = NULL;\n  \n  arg9 = &temp9;\n  arg10 = &temp10;\n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOOOOOOO:gsl_integration_qawc\",kwnames,&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_function, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_integration_qawc\" \"', argument \" \"1\"\" of type '\" \"gsl_function *\"\"'\"); \n  }\n  arg1 = (gsl_function *)(argp1);\n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_integration_qawc\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  ecode3 = SWIG_AsVal_double(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_integration_qawc\" \"', argument \" \"3\"\" of type '\" \"double\"\"'\");\n  } \n  arg3 = (double)(val3);\n  ecode4 = SWIG_AsVal_double(obj3, &val4);\n  if (!SWIG_IsOK(ecode4)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode4), \"in method '\" \"gsl_integration_qawc\" \"', argument \" \"4\"\" of type '\" \"double\"\"'\");\n  } \n  arg4 = (double)(val4);\n  ecode5 = SWIG_AsVal_double(obj4, &val5);\n  if (!SWIG_IsOK(ecode5)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode5), \"in method '\" \"gsl_integration_qawc\" \"', argument \" \"5\"\" of type '\" \"double\"\"'\");\n  } \n  arg5 = (double)(val5);\n  ecode6 = SWIG_AsVal_double(obj5, &val6);\n  if (!SWIG_IsOK(ecode6)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode6), \"in method '\" \"gsl_integration_qawc\" \"', argument \" \"6\"\" of type '\" \"double\"\"'\");\n  } \n  arg6 = (double)(val6);\n  ecode7 = SWIG_AsVal_size_t(obj6, &val7);\n  if (!SWIG_IsOK(ecode7)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode7), \"in method '\" \"gsl_integration_qawc\" \"', argument \" \"7\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg7 = (size_t)(val7);\n  res8 = SWIG_ConvertPtr(obj7, &argp8,SWIGTYPE_p_gsl_integration_workspace, 0 |  0 );\n  if (!SWIG_IsOK(res8)) {\n    SWIG_exception_fail(SWIG_ArgError(res8), \"in method '\" \"gsl_integration_qawc\" \"', argument \" \"8\"\" of type '\" \"gsl_integration_workspace *\"\"'\"); \n  }\n  arg8 = (gsl_integration_workspace *)(argp8);\n  {\n    int flag;\n    callback_function_params * p;\n    \n    FUNC_MESS(\"\\t\\t Setting jump buffer\");\n    assert(arg1);\n    \n    \n    _solver1 = arg1;\n    p = (callback_function_params *) \n    PyGSL_gsl_function_GET_PARAMS(_solver1);\n    \n    if((flag=setjmp(p->buffer)) == 0){\n      FUNC_MESS(\"\\t\\t Setting Jmp Buffer\");\n      p->buffer_is_set = 1;\n    } else {\n      FUNC_MESS(\"\\t\\t Returning from Jmp Buffer\");\n      p->buffer_is_set = 0;\n      goto fail;\n    }\n    \n    FUNC_MESS(\"\\t\\t END Setting jump buffer\");\n  }\n  result = (int)gsl_integration_qawc(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  if (SWIG_IsTmpObj(res9)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg9)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res9) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg9), SWIGTYPE_p_double, new_flags));\n  }\n  if (SWIG_IsTmpObj(res10)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg10)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res10) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg10), SWIGTYPE_p_double, new_flags));\n  }\n  {\n    callback_function_params * p;\n    if(_solver1){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params *)  \n      PyGSL_gsl_function_GET_PARAMS(_solver1);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  return resultobj;\nfail:\n  {\n    callback_function_params * p;\n    if(_solver1){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params *)  \n      PyGSL_gsl_function_GET_PARAMS(_solver1);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_integration_qaws(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_function *arg1 = (gsl_function *) 0 ;\n  double arg2 ;\n  double arg3 ;\n  gsl_integration_qaws_table *arg4 = (gsl_integration_qaws_table *) 0 ;\n  double arg5 ;\n  double arg6 ;\n  size_t arg7 ;\n  gsl_integration_workspace *arg8 = (gsl_integration_workspace *) 0 ;\n  double *arg9 = (double *) 0 ;\n  double *arg10 = (double *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  double val3 ;\n  int ecode3 = 0 ;\n  void *argp4 = 0 ;\n  int res4 = 0 ;\n  double val5 ;\n  int ecode5 = 0 ;\n  double val6 ;\n  int ecode6 = 0 ;\n  size_t val7 ;\n  int ecode7 = 0 ;\n  void *argp8 = 0 ;\n  int res8 = 0 ;\n  double temp9 ;\n  int res9 = SWIG_TMPOBJ ;\n  double temp10 ;\n  int res10 = SWIG_TMPOBJ ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  PyObject * obj3 = 0 ;\n  PyObject * obj4 = 0 ;\n  PyObject * obj5 = 0 ;\n  PyObject * obj6 = 0 ;\n  PyObject * obj7 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"BUFFER\",(char *) \"a\",(char *) \"b\",(char *) \"t\",(char *) \"epsabs\",(char *) \"epsrel\",(char *) \"limit\",(char *) \"workspace\", NULL \n  };\n  int result;\n  \n  \n  gsl_function * volatile _solver1 = NULL;\n  \n  arg9 = &temp9;\n  arg10 = &temp10;\n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOOOOOOO:gsl_integration_qaws\",kwnames,&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_function, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_integration_qaws\" \"', argument \" \"1\"\" of type '\" \"gsl_function *\"\"'\"); \n  }\n  arg1 = (gsl_function *)(argp1);\n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_integration_qaws\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  ecode3 = SWIG_AsVal_double(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_integration_qaws\" \"', argument \" \"3\"\" of type '\" \"double\"\"'\");\n  } \n  arg3 = (double)(val3);\n  res4 = SWIG_ConvertPtr(obj3, &argp4,SWIGTYPE_p_gsl_integration_qaws_table, 0 |  0 );\n  if (!SWIG_IsOK(res4)) {\n    SWIG_exception_fail(SWIG_ArgError(res4), \"in method '\" \"gsl_integration_qaws\" \"', argument \" \"4\"\" of type '\" \"gsl_integration_qaws_table *\"\"'\"); \n  }\n  arg4 = (gsl_integration_qaws_table *)(argp4);\n  ecode5 = SWIG_AsVal_double(obj4, &val5);\n  if (!SWIG_IsOK(ecode5)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode5), \"in method '\" \"gsl_integration_qaws\" \"', argument \" \"5\"\" of type '\" \"double\"\"'\");\n  } \n  arg5 = (double)(val5);\n  ecode6 = SWIG_AsVal_double(obj5, &val6);\n  if (!SWIG_IsOK(ecode6)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode6), \"in method '\" \"gsl_integration_qaws\" \"', argument \" \"6\"\" of type '\" \"double\"\"'\");\n  } \n  arg6 = (double)(val6);\n  ecode7 = SWIG_AsVal_size_t(obj6, &val7);\n  if (!SWIG_IsOK(ecode7)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode7), \"in method '\" \"gsl_integration_qaws\" \"', argument \" \"7\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg7 = (size_t)(val7);\n  res8 = SWIG_ConvertPtr(obj7, &argp8,SWIGTYPE_p_gsl_integration_workspace, 0 |  0 );\n  if (!SWIG_IsOK(res8)) {\n    SWIG_exception_fail(SWIG_ArgError(res8), \"in method '\" \"gsl_integration_qaws\" \"', argument \" \"8\"\" of type '\" \"gsl_integration_workspace *\"\"'\"); \n  }\n  arg8 = (gsl_integration_workspace *)(argp8);\n  {\n    int flag;\n    callback_function_params * p;\n    \n    FUNC_MESS(\"\\t\\t Setting jump buffer\");\n    assert(arg1);\n    \n    \n    _solver1 = arg1;\n    p = (callback_function_params *) \n    PyGSL_gsl_function_GET_PARAMS(_solver1);\n    \n    if((flag=setjmp(p->buffer)) == 0){\n      FUNC_MESS(\"\\t\\t Setting Jmp Buffer\");\n      p->buffer_is_set = 1;\n    } else {\n      FUNC_MESS(\"\\t\\t Returning from Jmp Buffer\");\n      p->buffer_is_set = 0;\n      goto fail;\n    }\n    \n    FUNC_MESS(\"\\t\\t END Setting jump buffer\");\n  }\n  result = (int)gsl_integration_qaws(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  if (SWIG_IsTmpObj(res9)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg9)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res9) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg9), SWIGTYPE_p_double, new_flags));\n  }\n  if (SWIG_IsTmpObj(res10)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg10)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res10) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg10), SWIGTYPE_p_double, new_flags));\n  }\n  {\n    callback_function_params * p;\n    if(_solver1){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params *)  \n      PyGSL_gsl_function_GET_PARAMS(_solver1);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  return resultobj;\nfail:\n  {\n    callback_function_params * p;\n    if(_solver1){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params *)  \n      PyGSL_gsl_function_GET_PARAMS(_solver1);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_integration_qawo(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_function *arg1 = (gsl_function *) 0 ;\n  double arg2 ;\n  double arg3 ;\n  double arg4 ;\n  size_t arg5 ;\n  gsl_integration_workspace *arg6 = (gsl_integration_workspace *) 0 ;\n  gsl_integration_qawo_table *arg7 = (gsl_integration_qawo_table *) 0 ;\n  double *arg8 = (double *) 0 ;\n  double *arg9 = (double *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  double val3 ;\n  int ecode3 = 0 ;\n  double val4 ;\n  int ecode4 = 0 ;\n  size_t val5 ;\n  int ecode5 = 0 ;\n  void *argp6 = 0 ;\n  int res6 = 0 ;\n  void *argp7 = 0 ;\n  int res7 = 0 ;\n  double temp8 ;\n  int res8 = SWIG_TMPOBJ ;\n  double temp9 ;\n  int res9 = SWIG_TMPOBJ ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  PyObject * obj3 = 0 ;\n  PyObject * obj4 = 0 ;\n  PyObject * obj5 = 0 ;\n  PyObject * obj6 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"BUFFER\",(char *) \"a\",(char *) \"epsabs\",(char *) \"epsrel\",(char *) \"limit\",(char *) \"workspace\",(char *) \"wf\", NULL \n  };\n  int result;\n  \n  \n  gsl_function * volatile _solver1 = NULL;\n  \n  arg8 = &temp8;\n  arg9 = &temp9;\n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOOOOOO:gsl_integration_qawo\",kwnames,&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_function, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_integration_qawo\" \"', argument \" \"1\"\" of type '\" \"gsl_function *\"\"'\"); \n  }\n  arg1 = (gsl_function *)(argp1);\n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_integration_qawo\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  ecode3 = SWIG_AsVal_double(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_integration_qawo\" \"', argument \" \"3\"\" of type '\" \"double\"\"'\");\n  } \n  arg3 = (double)(val3);\n  ecode4 = SWIG_AsVal_double(obj3, &val4);\n  if (!SWIG_IsOK(ecode4)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode4), \"in method '\" \"gsl_integration_qawo\" \"', argument \" \"4\"\" of type '\" \"double\"\"'\");\n  } \n  arg4 = (double)(val4);\n  ecode5 = SWIG_AsVal_size_t(obj4, &val5);\n  if (!SWIG_IsOK(ecode5)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode5), \"in method '\" \"gsl_integration_qawo\" \"', argument \" \"5\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg5 = (size_t)(val5);\n  res6 = SWIG_ConvertPtr(obj5, &argp6,SWIGTYPE_p_gsl_integration_workspace, 0 |  0 );\n  if (!SWIG_IsOK(res6)) {\n    SWIG_exception_fail(SWIG_ArgError(res6), \"in method '\" \"gsl_integration_qawo\" \"', argument \" \"6\"\" of type '\" \"gsl_integration_workspace *\"\"'\"); \n  }\n  arg6 = (gsl_integration_workspace *)(argp6);\n  res7 = SWIG_ConvertPtr(obj6, &argp7,SWIGTYPE_p_gsl_integration_qawo_table, 0 |  0 );\n  if (!SWIG_IsOK(res7)) {\n    SWIG_exception_fail(SWIG_ArgError(res7), \"in method '\" \"gsl_integration_qawo\" \"', argument \" \"7\"\" of type '\" \"gsl_integration_qawo_table *\"\"'\"); \n  }\n  arg7 = (gsl_integration_qawo_table *)(argp7);\n  {\n    int flag;\n    callback_function_params * p;\n    \n    FUNC_MESS(\"\\t\\t Setting jump buffer\");\n    assert(arg1);\n    \n    \n    _solver1 = arg1;\n    p = (callback_function_params *) \n    PyGSL_gsl_function_GET_PARAMS(_solver1);\n    \n    if((flag=setjmp(p->buffer)) == 0){\n      FUNC_MESS(\"\\t\\t Setting Jmp Buffer\");\n      p->buffer_is_set = 1;\n    } else {\n      FUNC_MESS(\"\\t\\t Returning from Jmp Buffer\");\n      p->buffer_is_set = 0;\n      goto fail;\n    }\n    \n    FUNC_MESS(\"\\t\\t END Setting jump buffer\");\n  }\n  result = (int)gsl_integration_qawo(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  if (SWIG_IsTmpObj(res8)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg8)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res8) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg8), SWIGTYPE_p_double, new_flags));\n  }\n  if (SWIG_IsTmpObj(res9)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg9)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res9) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg9), SWIGTYPE_p_double, new_flags));\n  }\n  {\n    callback_function_params * p;\n    if(_solver1){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params *)  \n      PyGSL_gsl_function_GET_PARAMS(_solver1);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  return resultobj;\nfail:\n  {\n    callback_function_params * p;\n    if(_solver1){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params *)  \n      PyGSL_gsl_function_GET_PARAMS(_solver1);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_integration_qawf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_function *arg1 = (gsl_function *) 0 ;\n  double arg2 ;\n  double arg3 ;\n  size_t arg4 ;\n  gsl_integration_workspace *arg5 = (gsl_integration_workspace *) 0 ;\n  gsl_integration_workspace *arg6 = (gsl_integration_workspace *) 0 ;\n  gsl_integration_qawo_table *arg7 = (gsl_integration_qawo_table *) 0 ;\n  double *arg8 = (double *) 0 ;\n  double *arg9 = (double *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  double val3 ;\n  int ecode3 = 0 ;\n  size_t val4 ;\n  int ecode4 = 0 ;\n  void *argp5 = 0 ;\n  int res5 = 0 ;\n  void *argp6 = 0 ;\n  int res6 = 0 ;\n  void *argp7 = 0 ;\n  int res7 = 0 ;\n  double temp8 ;\n  int res8 = SWIG_TMPOBJ ;\n  double temp9 ;\n  int res9 = SWIG_TMPOBJ ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  PyObject * obj3 = 0 ;\n  PyObject * obj4 = 0 ;\n  PyObject * obj5 = 0 ;\n  PyObject * obj6 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"BUFFER\",(char *) \"a\",(char *) \"epsabs\",(char *) \"limit\",(char *) \"workspace\",(char *) \"cycle_workspace\",(char *) \"wf\", NULL \n  };\n  int result;\n  \n  \n  gsl_function * volatile _solver1 = NULL;\n  \n  arg8 = &temp8;\n  arg9 = &temp9;\n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOOOOOO:gsl_integration_qawf\",kwnames,&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_function, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_integration_qawf\" \"', argument \" \"1\"\" of type '\" \"gsl_function *\"\"'\"); \n  }\n  arg1 = (gsl_function *)(argp1);\n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_integration_qawf\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  ecode3 = SWIG_AsVal_double(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_integration_qawf\" \"', argument \" \"3\"\" of type '\" \"double\"\"'\");\n  } \n  arg3 = (double)(val3);\n  ecode4 = SWIG_AsVal_size_t(obj3, &val4);\n  if (!SWIG_IsOK(ecode4)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode4), \"in method '\" \"gsl_integration_qawf\" \"', argument \" \"4\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg4 = (size_t)(val4);\n  res5 = SWIG_ConvertPtr(obj4, &argp5,SWIGTYPE_p_gsl_integration_workspace, 0 |  0 );\n  if (!SWIG_IsOK(res5)) {\n    SWIG_exception_fail(SWIG_ArgError(res5), \"in method '\" \"gsl_integration_qawf\" \"', argument \" \"5\"\" of type '\" \"gsl_integration_workspace *\"\"'\"); \n  }\n  arg5 = (gsl_integration_workspace *)(argp5);\n  res6 = SWIG_ConvertPtr(obj5, &argp6,SWIGTYPE_p_gsl_integration_workspace, 0 |  0 );\n  if (!SWIG_IsOK(res6)) {\n    SWIG_exception_fail(SWIG_ArgError(res6), \"in method '\" \"gsl_integration_qawf\" \"', argument \" \"6\"\" of type '\" \"gsl_integration_workspace *\"\"'\"); \n  }\n  arg6 = (gsl_integration_workspace *)(argp6);\n  res7 = SWIG_ConvertPtr(obj6, &argp7,SWIGTYPE_p_gsl_integration_qawo_table, 0 |  0 );\n  if (!SWIG_IsOK(res7)) {\n    SWIG_exception_fail(SWIG_ArgError(res7), \"in method '\" \"gsl_integration_qawf\" \"', argument \" \"7\"\" of type '\" \"gsl_integration_qawo_table *\"\"'\"); \n  }\n  arg7 = (gsl_integration_qawo_table *)(argp7);\n  {\n    int flag;\n    callback_function_params * p;\n    \n    FUNC_MESS(\"\\t\\t Setting jump buffer\");\n    assert(arg1);\n    \n    \n    _solver1 = arg1;\n    p = (callback_function_params *) \n    PyGSL_gsl_function_GET_PARAMS(_solver1);\n    \n    if((flag=setjmp(p->buffer)) == 0){\n      FUNC_MESS(\"\\t\\t Setting Jmp Buffer\");\n      p->buffer_is_set = 1;\n    } else {\n      FUNC_MESS(\"\\t\\t Returning from Jmp Buffer\");\n      p->buffer_is_set = 0;\n      goto fail;\n    }\n    \n    FUNC_MESS(\"\\t\\t END Setting jump buffer\");\n  }\n  result = (int)gsl_integration_qawf(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  if (SWIG_IsTmpObj(res8)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg8)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res8) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg8), SWIGTYPE_p_double, new_flags));\n  }\n  if (SWIG_IsTmpObj(res9)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg9)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res9) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg9), SWIGTYPE_p_double, new_flags));\n  }\n  {\n    callback_function_params * p;\n    if(_solver1){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params *)  \n      PyGSL_gsl_function_GET_PARAMS(_solver1);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  return resultobj;\nfail:\n  {\n    callback_function_params * p;\n    if(_solver1){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params *)  \n      PyGSL_gsl_function_GET_PARAMS(_solver1);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_cheb_alloc(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  size_t arg1 ;\n  size_t val1 ;\n  int ecode1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"order\", NULL \n  };\n  gsl_cheb_series *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_cheb_alloc\",kwnames,&obj0)) SWIG_fail;\n  ecode1 = SWIG_AsVal_size_t(obj0, &val1);\n  if (!SWIG_IsOK(ecode1)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode1), \"in method '\" \"gsl_cheb_alloc\" \"', argument \" \"1\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg1 = (size_t)(val1);\n  result = (gsl_cheb_series *)gsl_cheb_alloc(arg1);\n  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_gsl_cheb_series, 0 |  0 );\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_cheb_free(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_cheb_series *arg1 = (gsl_cheb_series *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"cs\", NULL \n  };\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_cheb_free\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_cheb_series, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_cheb_free\" \"', argument \" \"1\"\" of type '\" \"gsl_cheb_series *\"\"'\"); \n  }\n  arg1 = (gsl_cheb_series *)(argp1);\n  gsl_cheb_free(arg1);\n  resultobj = SWIG_Py_Void();\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_cheb_init(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_cheb_series *arg1 = (gsl_cheb_series *) 0 ;\n  gsl_function *arg2 = (gsl_function *) 0 ;\n  double arg3 ;\n  double arg4 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  void *argp2 = 0 ;\n  int res2 = 0 ;\n  double val3 ;\n  int ecode3 = 0 ;\n  double val4 ;\n  int ecode4 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  PyObject * obj3 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"cs\",(char *) \"BUFFER\",(char *) \"a\",(char *) \"b\", NULL \n  };\n  int result;\n  \n  \n  gsl_function * volatile _solver2 = NULL;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOOO:gsl_cheb_init\",kwnames,&obj0,&obj1,&obj2,&obj3)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_cheb_series, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_cheb_init\" \"', argument \" \"1\"\" of type '\" \"gsl_cheb_series *\"\"'\"); \n  }\n  arg1 = (gsl_cheb_series *)(argp1);\n  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_gsl_function, 0 |  0 );\n  if (!SWIG_IsOK(res2)) {\n    SWIG_exception_fail(SWIG_ArgError(res2), \"in method '\" \"gsl_cheb_init\" \"', argument \" \"2\"\" of type '\" \"gsl_function const *\"\"'\"); \n  }\n  arg2 = (gsl_function *)(argp2);\n  ecode3 = SWIG_AsVal_double(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_cheb_init\" \"', argument \" \"3\"\" of type '\" \"double\"\"'\");\n  } \n  arg3 = (double)(val3);\n  ecode4 = SWIG_AsVal_double(obj3, &val4);\n  if (!SWIG_IsOK(ecode4)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode4), \"in method '\" \"gsl_cheb_init\" \"', argument \" \"4\"\" of type '\" \"double\"\"'\");\n  } \n  arg4 = (double)(val4);\n  {\n    int flag;\n    callback_function_params * p;\n    \n    FUNC_MESS(\"\\t\\t Setting jump buffer\");\n    assert(arg2);\n    \n    \n    _solver2 = arg2;\n    p = (callback_function_params *) \n    PyGSL_gsl_function_GET_PARAMS(_solver2);\n    \n    if((flag=setjmp(p->buffer)) == 0){\n      FUNC_MESS(\"\\t\\t Setting Jmp Buffer\");\n      p->buffer_is_set = 1;\n    } else {\n      FUNC_MESS(\"\\t\\t Returning from Jmp Buffer\");\n      p->buffer_is_set = 0;\n      goto fail;\n    }\n    \n    FUNC_MESS(\"\\t\\t END Setting jump buffer\");\n  }\n  result = (int)gsl_cheb_init(arg1,(gsl_function const *)arg2,arg3,arg4);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  {\n    callback_function_params * p;\n    if(_solver2){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params *)  \n      PyGSL_gsl_function_GET_PARAMS(_solver2);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  return resultobj;\nfail:\n  {\n    callback_function_params * p;\n    if(_solver2){\n      FUNC_MESS(\"\\t\\t Looking for pointer params\");\n      p = (callback_function_params *)  \n      PyGSL_gsl_function_GET_PARAMS(_solver2);\n      if(p){\n        FUNC_MESS(\"\\t\\t Setting buffer_is_set = 0\");\n        p->buffer_is_set = 0;\n      }\n    }\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_cheb_eval(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_cheb_series *arg1 = (gsl_cheb_series *) 0 ;\n  double arg2 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"cs\",(char *) \"x\", NULL \n  };\n  double result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_cheb_eval\",kwnames,&obj0,&obj1)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_cheb_series, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_cheb_eval\" \"', argument \" \"1\"\" of type '\" \"gsl_cheb_series const *\"\"'\"); \n  }\n  arg1 = (gsl_cheb_series *)(argp1);\n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_cheb_eval\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  result = (double)gsl_cheb_eval((gsl_cheb_series const *)arg1,arg2);\n  resultobj = SWIG_From_double((double)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_cheb_eval_err(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_cheb_series *arg1 = (gsl_cheb_series *) 0 ;\n  double arg2 ;\n  double *arg3 = (double *) 0 ;\n  double *arg4 = (double *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  double temp3 ;\n  int res3 = SWIG_TMPOBJ ;\n  double temp4 ;\n  int res4 = SWIG_TMPOBJ ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"cs\",(char *) \"x\", NULL \n  };\n  int result;\n  \n  arg3 = &temp3;\n  arg4 = &temp4;\n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_cheb_eval_err\",kwnames,&obj0,&obj1)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_cheb_series, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_cheb_eval_err\" \"', argument \" \"1\"\" of type '\" \"gsl_cheb_series const *\"\"'\"); \n  }\n  arg1 = (gsl_cheb_series *)(argp1);\n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_cheb_eval_err\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  result = (int)gsl_cheb_eval_err((gsl_cheb_series const *)arg1,arg2,arg3,arg4);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  if (SWIG_IsTmpObj(res3)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg3)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res3) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg3), SWIGTYPE_p_double, new_flags));\n  }\n  if (SWIG_IsTmpObj(res4)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg4)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res4) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg4), SWIGTYPE_p_double, new_flags));\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_cheb_eval_n(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_cheb_series *arg1 = (gsl_cheb_series *) 0 ;\n  size_t arg2 ;\n  double arg3 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  double val3 ;\n  int ecode3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"cs\",(char *) \"order\",(char *) \"x\", NULL \n  };\n  double result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_cheb_eval_n\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_cheb_series, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_cheb_eval_n\" \"', argument \" \"1\"\" of type '\" \"gsl_cheb_series const *\"\"'\"); \n  }\n  arg1 = (gsl_cheb_series *)(argp1);\n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_cheb_eval_n\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  ecode3 = SWIG_AsVal_double(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_cheb_eval_n\" \"', argument \" \"3\"\" of type '\" \"double\"\"'\");\n  } \n  arg3 = (double)(val3);\n  result = (double)gsl_cheb_eval_n((gsl_cheb_series const *)arg1,arg2,arg3);\n  resultobj = SWIG_From_double((double)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_cheb_eval_n_err(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_cheb_series *arg1 = (gsl_cheb_series *) 0 ;\n  size_t arg2 ;\n  double arg3 ;\n  double *arg4 = (double *) 0 ;\n  double *arg5 = (double *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  double val3 ;\n  int ecode3 = 0 ;\n  double temp4 ;\n  int res4 = SWIG_TMPOBJ ;\n  double temp5 ;\n  int res5 = SWIG_TMPOBJ ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"cs\",(char *) \"order\",(char *) \"x\", NULL \n  };\n  int result;\n  \n  arg4 = &temp4;\n  arg5 = &temp5;\n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_cheb_eval_n_err\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_cheb_series, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_cheb_eval_n_err\" \"', argument \" \"1\"\" of type '\" \"gsl_cheb_series const *\"\"'\"); \n  }\n  arg1 = (gsl_cheb_series *)(argp1);\n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_cheb_eval_n_err\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  ecode3 = SWIG_AsVal_double(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_cheb_eval_n_err\" \"', argument \" \"3\"\" of type '\" \"double\"\"'\");\n  } \n  arg3 = (double)(val3);\n  result = (int)gsl_cheb_eval_n_err((gsl_cheb_series const *)arg1,arg2,arg3,arg4,arg5);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  if (SWIG_IsTmpObj(res4)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg4)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res4) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg4), SWIGTYPE_p_double, new_flags));\n  }\n  if (SWIG_IsTmpObj(res5)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg5)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res5) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg5), SWIGTYPE_p_double, new_flags));\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_cheb_calc_deriv(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_cheb_series *arg1 = (gsl_cheb_series *) 0 ;\n  gsl_cheb_series *arg2 = (gsl_cheb_series *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  void *argp2 = 0 ;\n  int res2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"deriv\",(char *) \"cs\", NULL \n  };\n  int result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_cheb_calc_deriv\",kwnames,&obj0,&obj1)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_cheb_series, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_cheb_calc_deriv\" \"', argument \" \"1\"\" of type '\" \"gsl_cheb_series *\"\"'\"); \n  }\n  arg1 = (gsl_cheb_series *)(argp1);\n  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_gsl_cheb_series, 0 |  0 );\n  if (!SWIG_IsOK(res2)) {\n    SWIG_exception_fail(SWIG_ArgError(res2), \"in method '\" \"gsl_cheb_calc_deriv\" \"', argument \" \"2\"\" of type '\" \"gsl_cheb_series const *\"\"'\"); \n  }\n  arg2 = (gsl_cheb_series *)(argp2);\n  result = (int)gsl_cheb_calc_deriv(arg1,(gsl_cheb_series const *)arg2);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_cheb_calc_integ(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_cheb_series *arg1 = (gsl_cheb_series *) 0 ;\n  gsl_cheb_series *arg2 = (gsl_cheb_series *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  void *argp2 = 0 ;\n  int res2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"integ\",(char *) \"cs\", NULL \n  };\n  int result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_cheb_calc_integ\",kwnames,&obj0,&obj1)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_cheb_series, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_cheb_calc_integ\" \"', argument \" \"1\"\" of type '\" \"gsl_cheb_series *\"\"'\"); \n  }\n  arg1 = (gsl_cheb_series *)(argp1);\n  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_gsl_cheb_series, 0 |  0 );\n  if (!SWIG_IsOK(res2)) {\n    SWIG_exception_fail(SWIG_ArgError(res2), \"in method '\" \"gsl_cheb_calc_integ\" \"', argument \" \"2\"\" of type '\" \"gsl_cheb_series const *\"\"'\"); \n  }\n  arg2 = (gsl_cheb_series *)(argp2);\n  result = (int)gsl_cheb_calc_integ(arg1,(gsl_cheb_series const *)arg2);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_pygsl_cheb_get_coefficients(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_cheb_series *arg1 = (gsl_cheb_series *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  PyObject *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:pygsl_cheb_get_coefficients\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_cheb_series, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"pygsl_cheb_get_coefficients\" \"', argument \" \"1\"\" of type '\" \"gsl_cheb_series *\"\"'\"); \n  }\n  arg1 = (gsl_cheb_series *)(argp1);\n  result = (PyObject *)pygsl_cheb_get_coefficients(arg1);\n  resultobj = result;\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_pygsl_cheb_set_coefficients(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_cheb_series *arg1 = (gsl_cheb_series *) 0 ;\n  gsl_vector *arg2 = (gsl_vector *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\",(char *) \"IN\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:pygsl_cheb_set_coefficients\",kwnames,&obj0,&obj1)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_cheb_series, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"pygsl_cheb_set_coefficients\" \"', argument \" \"1\"\" of type '\" \"gsl_cheb_series *\"\"'\"); \n  }\n  arg1 = (gsl_cheb_series *)(argp1);\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2,\n        PyGSL_INPUT_ARRAY, gsl_vector, 2, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)pygsl_cheb_set_coefficients(arg1,arg2);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  {\n    Py_XDECREF(_PyVector2);\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyVector2);\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_pygsl_cheb_get_a(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_cheb_series *arg1 = (gsl_cheb_series *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  double result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:pygsl_cheb_get_a\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_cheb_series, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"pygsl_cheb_get_a\" \"', argument \" \"1\"\" of type '\" \"gsl_cheb_series *\"\"'\"); \n  }\n  arg1 = (gsl_cheb_series *)(argp1);\n  result = (double)pygsl_cheb_get_a(arg1);\n  resultobj = SWIG_From_double((double)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_pygsl_cheb_get_b(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_cheb_series *arg1 = (gsl_cheb_series *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  double result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:pygsl_cheb_get_b\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_cheb_series, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"pygsl_cheb_get_b\" \"', argument \" \"1\"\" of type '\" \"gsl_cheb_series *\"\"'\"); \n  }\n  arg1 = (gsl_cheb_series *)(argp1);\n  result = (double)pygsl_cheb_get_b(arg1);\n  resultobj = SWIG_From_double((double)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_pygsl_cheb_set_a(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_cheb_series *arg1 = (gsl_cheb_series *) 0 ;\n  double arg2 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\",(char *) \"a\", NULL \n  };\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:pygsl_cheb_set_a\",kwnames,&obj0,&obj1)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_cheb_series, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"pygsl_cheb_set_a\" \"', argument \" \"1\"\" of type '\" \"gsl_cheb_series *\"\"'\"); \n  }\n  arg1 = (gsl_cheb_series *)(argp1);\n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"pygsl_cheb_set_a\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  pygsl_cheb_set_a(arg1,arg2);\n  resultobj = SWIG_Py_Void();\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_pygsl_cheb_set_b(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_cheb_series *arg1 = (gsl_cheb_series *) 0 ;\n  double arg2 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\",(char *) \"b\", NULL \n  };\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:pygsl_cheb_set_b\",kwnames,&obj0,&obj1)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_cheb_series, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"pygsl_cheb_set_b\" \"', argument \" \"1\"\" of type '\" \"gsl_cheb_series *\"\"'\"); \n  }\n  arg1 = (gsl_cheb_series *)(argp1);\n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"pygsl_cheb_set_b\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  pygsl_cheb_set_b(arg1,arg2);\n  resultobj = SWIG_Py_Void();\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_pygsl_cheb_get_order_sp(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_cheb_series *arg1 = (gsl_cheb_series *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  size_t result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:pygsl_cheb_get_order_sp\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_cheb_series, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"pygsl_cheb_get_order_sp\" \"', argument \" \"1\"\" of type '\" \"gsl_cheb_series *\"\"'\"); \n  }\n  arg1 = (gsl_cheb_series *)(argp1);\n  result = (size_t)pygsl_cheb_get_order_sp(arg1);\n  resultobj = SWIG_From_size_t((size_t)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_pygsl_cheb_set_order_sp(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_cheb_series *arg1 = (gsl_cheb_series *) 0 ;\n  size_t arg2 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\",(char *) \"sp\", NULL \n  };\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:pygsl_cheb_set_order_sp\",kwnames,&obj0,&obj1)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_cheb_series, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"pygsl_cheb_set_order_sp\" \"', argument \" \"1\"\" of type '\" \"gsl_cheb_series *\"\"'\"); \n  }\n  arg1 = (gsl_cheb_series *)(argp1);\n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"pygsl_cheb_set_order_sp\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  pygsl_cheb_set_order_sp(arg1,arg2);\n  resultobj = SWIG_Py_Void();\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_pygsl_cheb_get_f(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_cheb_series *arg1 = (gsl_cheb_series *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  double result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:pygsl_cheb_get_f\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_cheb_series, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"pygsl_cheb_get_f\" \"', argument \" \"1\"\" of type '\" \"gsl_cheb_series *\"\"'\"); \n  }\n  arg1 = (gsl_cheb_series *)(argp1);\n  result = (double)pygsl_cheb_get_f(arg1);\n  resultobj = SWIG_From_double((double)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_pygsl_cheb_set_f(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_cheb_series *arg1 = (gsl_cheb_series *) 0 ;\n  double arg2 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\",(char *) \"f\", NULL \n  };\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:pygsl_cheb_set_f\",kwnames,&obj0,&obj1)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_cheb_series, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"pygsl_cheb_set_f\" \"', argument \" \"1\"\" of type '\" \"gsl_cheb_series *\"\"'\"); \n  }\n  arg1 = (gsl_cheb_series *)(argp1);\n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"pygsl_cheb_set_f\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  pygsl_cheb_set_f(arg1,arg2);\n  resultobj = SWIG_Py_Void();\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN int Swig_var_gsl_odeiv_step_rk2_set(PyObject *_val SWIGUNUSED) {\n  SWIG_Error(SWIG_AttributeError,\"Variable gsl_odeiv_step_rk2 is read-only.\");\n  return 1;\n}\n\n\nSWIGINTERN PyObject *Swig_var_gsl_odeiv_step_rk2_get(void) {\n  PyObject *pyobj = 0;\n  \n  pyobj = SWIG_NewPointerObj(SWIG_as_voidptr(gsl_odeiv_step_rk2), SWIGTYPE_p_gsl_odeiv_step_type,  0 );\n  return pyobj;\n}\n\n\nSWIGINTERN int Swig_var_gsl_odeiv_step_rk4_set(PyObject *_val SWIGUNUSED) {\n  SWIG_Error(SWIG_AttributeError,\"Variable gsl_odeiv_step_rk4 is read-only.\");\n  return 1;\n}\n\n\nSWIGINTERN PyObject *Swig_var_gsl_odeiv_step_rk4_get(void) {\n  PyObject *pyobj = 0;\n  \n  pyobj = SWIG_NewPointerObj(SWIG_as_voidptr(gsl_odeiv_step_rk4), SWIGTYPE_p_gsl_odeiv_step_type,  0 );\n  return pyobj;\n}\n\n\nSWIGINTERN int Swig_var_gsl_odeiv_step_rkf45_set(PyObject *_val SWIGUNUSED) {\n  SWIG_Error(SWIG_AttributeError,\"Variable gsl_odeiv_step_rkf45 is read-only.\");\n  return 1;\n}\n\n\nSWIGINTERN PyObject *Swig_var_gsl_odeiv_step_rkf45_get(void) {\n  PyObject *pyobj = 0;\n  \n  pyobj = SWIG_NewPointerObj(SWIG_as_voidptr(gsl_odeiv_step_rkf45), SWIGTYPE_p_gsl_odeiv_step_type,  0 );\n  return pyobj;\n}\n\n\nSWIGINTERN int Swig_var_gsl_odeiv_step_rkck_set(PyObject *_val SWIGUNUSED) {\n  SWIG_Error(SWIG_AttributeError,\"Variable gsl_odeiv_step_rkck is read-only.\");\n  return 1;\n}\n\n\nSWIGINTERN PyObject *Swig_var_gsl_odeiv_step_rkck_get(void) {\n  PyObject *pyobj = 0;\n  \n  pyobj = SWIG_NewPointerObj(SWIG_as_voidptr(gsl_odeiv_step_rkck), SWIGTYPE_p_gsl_odeiv_step_type,  0 );\n  return pyobj;\n}\n\n\nSWIGINTERN int Swig_var_gsl_odeiv_step_rk8pd_set(PyObject *_val SWIGUNUSED) {\n  SWIG_Error(SWIG_AttributeError,\"Variable gsl_odeiv_step_rk8pd is read-only.\");\n  return 1;\n}\n\n\nSWIGINTERN PyObject *Swig_var_gsl_odeiv_step_rk8pd_get(void) {\n  PyObject *pyobj = 0;\n  \n  pyobj = SWIG_NewPointerObj(SWIG_as_voidptr(gsl_odeiv_step_rk8pd), SWIGTYPE_p_gsl_odeiv_step_type,  0 );\n  return pyobj;\n}\n\n\nSWIGINTERN int Swig_var_gsl_odeiv_step_rk2imp_set(PyObject *_val SWIGUNUSED) {\n  SWIG_Error(SWIG_AttributeError,\"Variable gsl_odeiv_step_rk2imp is read-only.\");\n  return 1;\n}\n\n\nSWIGINTERN PyObject *Swig_var_gsl_odeiv_step_rk2imp_get(void) {\n  PyObject *pyobj = 0;\n  \n  pyobj = SWIG_NewPointerObj(SWIG_as_voidptr(gsl_odeiv_step_rk2imp), SWIGTYPE_p_gsl_odeiv_step_type,  0 );\n  return pyobj;\n}\n\n\nSWIGINTERN int Swig_var_gsl_odeiv_step_rk4imp_set(PyObject *_val SWIGUNUSED) {\n  SWIG_Error(SWIG_AttributeError,\"Variable gsl_odeiv_step_rk4imp is read-only.\");\n  return 1;\n}\n\n\nSWIGINTERN PyObject *Swig_var_gsl_odeiv_step_rk4imp_get(void) {\n  PyObject *pyobj = 0;\n  \n  pyobj = SWIG_NewPointerObj(SWIG_as_voidptr(gsl_odeiv_step_rk4imp), SWIGTYPE_p_gsl_odeiv_step_type,  0 );\n  return pyobj;\n}\n\n\nSWIGINTERN int Swig_var_gsl_odeiv_step_bsimp_set(PyObject *_val SWIGUNUSED) {\n  SWIG_Error(SWIG_AttributeError,\"Variable gsl_odeiv_step_bsimp is read-only.\");\n  return 1;\n}\n\n\nSWIGINTERN PyObject *Swig_var_gsl_odeiv_step_bsimp_get(void) {\n  PyObject *pyobj = 0;\n  \n  pyobj = SWIG_NewPointerObj(SWIG_as_voidptr(gsl_odeiv_step_bsimp), SWIGTYPE_p_gsl_odeiv_step_type,  0 );\n  return pyobj;\n}\n\n\nSWIGINTERN int Swig_var_gsl_odeiv_step_gear1_set(PyObject *_val SWIGUNUSED) {\n  SWIG_Error(SWIG_AttributeError,\"Variable gsl_odeiv_step_gear1 is read-only.\");\n  return 1;\n}\n\n\nSWIGINTERN PyObject *Swig_var_gsl_odeiv_step_gear1_get(void) {\n  PyObject *pyobj = 0;\n  \n  pyobj = SWIG_NewPointerObj(SWIG_as_voidptr(gsl_odeiv_step_gear1), SWIGTYPE_p_gsl_odeiv_step_type,  0 );\n  return pyobj;\n}\n\n\nSWIGINTERN int Swig_var_gsl_odeiv_step_gear2_set(PyObject *_val SWIGUNUSED) {\n  SWIG_Error(SWIG_AttributeError,\"Variable gsl_odeiv_step_gear2 is read-only.\");\n  return 1;\n}\n\n\nSWIGINTERN PyObject *Swig_var_gsl_odeiv_step_gear2_get(void) {\n  PyObject *pyobj = 0;\n  \n  pyobj = SWIG_NewPointerObj(SWIG_as_voidptr(gsl_odeiv_step_gear2), SWIGTYPE_p_gsl_odeiv_step_type,  0 );\n  return pyobj;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_odeiv_step_alloc(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_odeiv_step_type *arg1 = (gsl_odeiv_step_type *) 0 ;\n  size_t arg2 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"T\",(char *) \"dim\", NULL \n  };\n  gsl_odeiv_step *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_odeiv_step_alloc\",kwnames,&obj0,&obj1)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_odeiv_step_type, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_odeiv_step_alloc\" \"', argument \" \"1\"\" of type '\" \"gsl_odeiv_step_type const *\"\"'\"); \n  }\n  arg1 = (gsl_odeiv_step_type *)(argp1);\n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_odeiv_step_alloc\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  result = (gsl_odeiv_step *)gsl_odeiv_step_alloc((gsl_odeiv_step_type const *)arg1,arg2);\n  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_gsl_odeiv_step, 0 |  0 );\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_odeiv_step_reset(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_odeiv_step *arg1 = (gsl_odeiv_step *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  int result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_odeiv_step_reset\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_odeiv_step, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_odeiv_step_reset\" \"', argument \" \"1\"\" of type '\" \"gsl_odeiv_step *\"\"'\"); \n  }\n  arg1 = (gsl_odeiv_step *)(argp1);\n  result = (int)gsl_odeiv_step_reset(arg1);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_odeiv_step_free(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_odeiv_step *arg1 = (gsl_odeiv_step *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_odeiv_step_free\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_odeiv_step, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_odeiv_step_free\" \"', argument \" \"1\"\" of type '\" \"gsl_odeiv_step *\"\"'\"); \n  }\n  arg1 = (gsl_odeiv_step *)(argp1);\n  gsl_odeiv_step_free(arg1);\n  resultobj = SWIG_Py_Void();\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_odeiv_step_name(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_odeiv_step *arg1 = (gsl_odeiv_step *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *)\"arg1\", NULL \n  };\n  char *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_odeiv_step_name\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_odeiv_step, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_odeiv_step_name\" \"', argument \" \"1\"\" of type '\" \"gsl_odeiv_step const *\"\"'\"); \n  }\n  arg1 = (gsl_odeiv_step *)(argp1);\n  result = (char *)gsl_odeiv_step_name((gsl_odeiv_step const *)arg1);\n  resultobj = SWIG_FromCharPtr((const char *)result);\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_odeiv_step_order(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_odeiv_step *arg1 = (gsl_odeiv_step *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"s\", NULL \n  };\n  unsigned int result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_odeiv_step_order\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_odeiv_step, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_odeiv_step_order\" \"', argument \" \"1\"\" of type '\" \"gsl_odeiv_step const *\"\"'\"); \n  }\n  arg1 = (gsl_odeiv_step *)(argp1);\n  result = (unsigned int)gsl_odeiv_step_order((gsl_odeiv_step const *)arg1);\n  resultobj = SWIG_From_unsigned_SS_int((unsigned int)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_odeiv_control_alloc(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_odeiv_control_type *arg1 = (gsl_odeiv_control_type *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"T\", NULL \n  };\n  gsl_odeiv_control *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_odeiv_control_alloc\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_odeiv_control_type, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_odeiv_control_alloc\" \"', argument \" \"1\"\" of type '\" \"gsl_odeiv_control_type const *\"\"'\"); \n  }\n  arg1 = (gsl_odeiv_control_type *)(argp1);\n  result = (gsl_odeiv_control *)gsl_odeiv_control_alloc((gsl_odeiv_control_type const *)arg1);\n  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_gsl_odeiv_control, 0 |  0 );\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_odeiv_control_init(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_odeiv_control *arg1 = (gsl_odeiv_control *) 0 ;\n  double arg2 ;\n  double arg3 ;\n  double arg4 ;\n  double arg5 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  double val3 ;\n  int ecode3 = 0 ;\n  double val4 ;\n  int ecode4 = 0 ;\n  double val5 ;\n  int ecode5 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  PyObject * obj3 = 0 ;\n  PyObject * obj4 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"c\",(char *) \"eps_abs\",(char *) \"eps_rel\",(char *) \"a_y\",(char *) \"a_dydt\", NULL \n  };\n  int result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOOOO:gsl_odeiv_control_init\",kwnames,&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_odeiv_control, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_odeiv_control_init\" \"', argument \" \"1\"\" of type '\" \"gsl_odeiv_control *\"\"'\"); \n  }\n  arg1 = (gsl_odeiv_control *)(argp1);\n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_odeiv_control_init\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  ecode3 = SWIG_AsVal_double(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_odeiv_control_init\" \"', argument \" \"3\"\" of type '\" \"double\"\"'\");\n  } \n  arg3 = (double)(val3);\n  ecode4 = SWIG_AsVal_double(obj3, &val4);\n  if (!SWIG_IsOK(ecode4)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode4), \"in method '\" \"gsl_odeiv_control_init\" \"', argument \" \"4\"\" of type '\" \"double\"\"'\");\n  } \n  arg4 = (double)(val4);\n  ecode5 = SWIG_AsVal_double(obj4, &val5);\n  if (!SWIG_IsOK(ecode5)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode5), \"in method '\" \"gsl_odeiv_control_init\" \"', argument \" \"5\"\" of type '\" \"double\"\"'\");\n  } \n  arg5 = (double)(val5);\n  result = (int)gsl_odeiv_control_init(arg1,arg2,arg3,arg4,arg5);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_odeiv_control_free(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_odeiv_control *arg1 = (gsl_odeiv_control *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"c\", NULL \n  };\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_odeiv_control_free\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_odeiv_control, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_odeiv_control_free\" \"', argument \" \"1\"\" of type '\" \"gsl_odeiv_control *\"\"'\"); \n  }\n  arg1 = (gsl_odeiv_control *)(argp1);\n  gsl_odeiv_control_free(arg1);\n  resultobj = SWIG_Py_Void();\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_odeiv_control_name(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_odeiv_control *arg1 = (gsl_odeiv_control *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"c\", NULL \n  };\n  char *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_odeiv_control_name\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_odeiv_control, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_odeiv_control_name\" \"', argument \" \"1\"\" of type '\" \"gsl_odeiv_control const *\"\"'\"); \n  }\n  arg1 = (gsl_odeiv_control *)(argp1);\n  result = (char *)gsl_odeiv_control_name((gsl_odeiv_control const *)arg1);\n  resultobj = SWIG_FromCharPtr((const char *)result);\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_odeiv_control_standard_new(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  double arg1 ;\n  double arg2 ;\n  double arg3 ;\n  double arg4 ;\n  double val1 ;\n  int ecode1 = 0 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  double val3 ;\n  int ecode3 = 0 ;\n  double val4 ;\n  int ecode4 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  PyObject * obj3 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"eps_abs\",(char *) \"eps_rel\",(char *) \"a_y\",(char *) \"a_dydt\", NULL \n  };\n  gsl_odeiv_control *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOOO:gsl_odeiv_control_standard_new\",kwnames,&obj0,&obj1,&obj2,&obj3)) SWIG_fail;\n  ecode1 = SWIG_AsVal_double(obj0, &val1);\n  if (!SWIG_IsOK(ecode1)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode1), \"in method '\" \"gsl_odeiv_control_standard_new\" \"', argument \" \"1\"\" of type '\" \"double\"\"'\");\n  } \n  arg1 = (double)(val1);\n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_odeiv_control_standard_new\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  ecode3 = SWIG_AsVal_double(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_odeiv_control_standard_new\" \"', argument \" \"3\"\" of type '\" \"double\"\"'\");\n  } \n  arg3 = (double)(val3);\n  ecode4 = SWIG_AsVal_double(obj3, &val4);\n  if (!SWIG_IsOK(ecode4)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode4), \"in method '\" \"gsl_odeiv_control_standard_new\" \"', argument \" \"4\"\" of type '\" \"double\"\"'\");\n  } \n  arg4 = (double)(val4);\n  result = (gsl_odeiv_control *)gsl_odeiv_control_standard_new(arg1,arg2,arg3,arg4);\n  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_gsl_odeiv_control, 0 |  0 );\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_odeiv_control_y_new(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  double arg1 ;\n  double arg2 ;\n  double val1 ;\n  int ecode1 = 0 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"eps_abs\",(char *) \"eps_rel\", NULL \n  };\n  gsl_odeiv_control *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_odeiv_control_y_new\",kwnames,&obj0,&obj1)) SWIG_fail;\n  ecode1 = SWIG_AsVal_double(obj0, &val1);\n  if (!SWIG_IsOK(ecode1)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode1), \"in method '\" \"gsl_odeiv_control_y_new\" \"', argument \" \"1\"\" of type '\" \"double\"\"'\");\n  } \n  arg1 = (double)(val1);\n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_odeiv_control_y_new\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  result = (gsl_odeiv_control *)gsl_odeiv_control_y_new(arg1,arg2);\n  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_gsl_odeiv_control, 0 |  0 );\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_odeiv_control_yp_new(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  double arg1 ;\n  double arg2 ;\n  double val1 ;\n  int ecode1 = 0 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"eps_abs\",(char *) \"eps_rel\", NULL \n  };\n  gsl_odeiv_control *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_odeiv_control_yp_new\",kwnames,&obj0,&obj1)) SWIG_fail;\n  ecode1 = SWIG_AsVal_double(obj0, &val1);\n  if (!SWIG_IsOK(ecode1)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode1), \"in method '\" \"gsl_odeiv_control_yp_new\" \"', argument \" \"1\"\" of type '\" \"double\"\"'\");\n  } \n  arg1 = (double)(val1);\n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_odeiv_control_yp_new\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  result = (gsl_odeiv_control *)gsl_odeiv_control_yp_new(arg1,arg2);\n  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_gsl_odeiv_control, 0 |  0 );\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_odeiv_evolve_alloc(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  size_t arg1 ;\n  size_t val1 ;\n  int ecode1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"dim\", NULL \n  };\n  gsl_odeiv_evolve *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_odeiv_evolve_alloc\",kwnames,&obj0)) SWIG_fail;\n  ecode1 = SWIG_AsVal_size_t(obj0, &val1);\n  if (!SWIG_IsOK(ecode1)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode1), \"in method '\" \"gsl_odeiv_evolve_alloc\" \"', argument \" \"1\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg1 = (size_t)(val1);\n  result = (gsl_odeiv_evolve *)gsl_odeiv_evolve_alloc(arg1);\n  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_gsl_odeiv_evolve, 0 |  0 );\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_odeiv_evolve_reset(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_odeiv_evolve *arg1 = (gsl_odeiv_evolve *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *)\"arg1\", NULL \n  };\n  int result;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_odeiv_evolve_reset\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_odeiv_evolve, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_odeiv_evolve_reset\" \"', argument \" \"1\"\" of type '\" \"gsl_odeiv_evolve *\"\"'\"); \n  }\n  arg1 = (gsl_odeiv_evolve *)(argp1);\n  result = (int)gsl_odeiv_evolve_reset(arg1);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_odeiv_evolve_free(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_odeiv_evolve *arg1 = (gsl_odeiv_evolve *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *)\"arg1\", NULL \n  };\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_odeiv_evolve_free\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_odeiv_evolve, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_odeiv_evolve_free\" \"', argument \" \"1\"\" of type '\" \"gsl_odeiv_evolve *\"\"'\"); \n  }\n  arg1 = (gsl_odeiv_evolve *)(argp1);\n  gsl_odeiv_evolve_free(arg1);\n  resultobj = SWIG_Py_Void();\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multifit_linear_alloc(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  size_t arg1 ;\n  size_t arg2 ;\n  size_t val1 ;\n  int ecode1 = 0 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"n\",(char *) \"p\", NULL \n  };\n  gsl_multifit_linear_workspace *result = 0 ;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_multifit_linear_alloc\",kwnames,&obj0,&obj1)) SWIG_fail;\n  ecode1 = SWIG_AsVal_size_t(obj0, &val1);\n  if (!SWIG_IsOK(ecode1)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode1), \"in method '\" \"gsl_multifit_linear_alloc\" \"', argument \" \"1\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg1 = (size_t)(val1);\n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_multifit_linear_alloc\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  result = (gsl_multifit_linear_workspace *)gsl_multifit_linear_alloc(arg1,arg2);\n  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_gsl_multifit_linear_workspace, 0 |  0 );\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multifit_linear_free(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_multifit_linear_workspace *arg1 = (gsl_multifit_linear_workspace *) 0 ;\n  void *argp1 = 0 ;\n  int res1 = 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"work\", NULL \n  };\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_multifit_linear_free\",kwnames,&obj0)) SWIG_fail;\n  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_gsl_multifit_linear_workspace, 0 |  0 );\n  if (!SWIG_IsOK(res1)) {\n    SWIG_exception_fail(SWIG_ArgError(res1), \"in method '\" \"gsl_multifit_linear_free\" \"', argument \" \"1\"\" of type '\" \"gsl_multifit_linear_workspace *\"\"'\"); \n  }\n  arg1 = (gsl_multifit_linear_workspace *)(argp1);\n  gsl_multifit_linear_free(arg1);\n  resultobj = SWIG_Py_Void();\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multifit_linear(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix *arg1 = (gsl_matrix *) 0 ;\n  gsl_vector *arg2 = (gsl_vector *) 0 ;\n  gsl_vector *arg3 = (gsl_vector *) 0 ;\n  gsl_matrix *arg4 = (gsl_matrix *) 0 ;\n  double *arg5 = (double *) 0 ;\n  gsl_multifit_linear_workspace *arg6 = (gsl_multifit_linear_workspace *) 0 ;\n  double temp5 ;\n  int res5 = SWIG_TMPOBJ ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\",(char *) \"IN\",(char *) \"work_provide\", NULL \n  };\n  gsl_error_flag_drop result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix _matrix1;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector _vector2;\n  \n  \n  PyArrayObject * volatile _PyVector3 = NULL;\n  TYPE_VIEW_gsl_vector _vector3;\n  \n  \n  PyArrayObject * _PyMatrix4 = NULL;\n  TYPE_VIEW_gsl_matrix _matrix4;\n  \n  \n  PyGSL_array_index_t _work_provide_n_work_provide = -1;\n  PyGSL_array_index_t _work_provide_p_work_provide = -1;\n  \n  \n  /* All done in check as the workspace stores the information about the required size */\n  \n  \n  /* All done in check as the workspace stores the information about the required size */\n  \n  arg5 = &temp5;\n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_multifit_linear\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2,\n        PyGSL_INPUT_ARRAY, gsl_vector, 2, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  {\n    if ((SWIG_ConvertPtr(obj2, (void **) &arg6, SWIGTYPE_p_gsl_multifit_linear_workspace,1)) == -1){\n      goto fail;\n    }\n    _work_provide_n_work_provide = (int) arg6->n;\n    _work_provide_p_work_provide = (int) arg6->p;\n  }\n  {\n    PyGSL_array_index_t stride;\n    \n    _PyVector3 = (PyArrayObject *) PyGSL_New_Array(1, &_work_provide_p_work_provide, PyArray_DOUBLE);\n    if(NULL == _PyVector3){\n      goto fail;\n    }\n    \n    if(PyGSL_STRIDE_RECALC(_PyVector3->strides[0], sizeof(BASIS_TYPE(gsl_vector)), &stride) != GSL_SUCCESS)\n    goto fail;\n    \n    _vector3  = TYPE_VIEW_ARRAY_STRIDES_gsl_vector((BASIS_C_TYPE(gsl_vector) *) _PyVector3->data,\n      stride,\n      _PyVector3->dimensions[0]);\n    arg3 = (gsl_vector *) &(_vector3.vector);\n    \n  }\n  {\n    PyArrayObject * a_array;\n    \n    PyGSL_array_index_t stride_recalc=0, dimensions[2];\n    dimensions[0] = _work_provide_p_work_provide;\n    dimensions[1] = _work_provide_p_work_provide;\n    a_array = (PyArrayObject *) PyGSL_New_Array(2, dimensions, PyArray_DOUBLE);\n    if(NULL == a_array){\n      goto fail;\n    }\n    _PyMatrix4 = a_array;\n    \n    \n    if(PyGSL_STRIDE_RECALC(a_array->strides[0], sizeof(BASIS_TYPE(gsl_matrix)), &stride_recalc) != GSL_SUCCESS)\n    goto fail;\n    /* (BASIS_TYPE_gsl_matrix *) */\n    _matrix4  = TYPE_VIEW_ARRAY_gsl_matrix((BASIS_C_TYPE(gsl_matrix) *) a_array->data, \n      a_array->dimensions[0], a_array->dimensions[1]);\n    \n    arg4 = (gsl_matrix *) &(_matrix4.matrix);\n  }\n  result = gsl_multifit_linear((gsl_matrix const *)arg1,(gsl_vector const *)arg2,arg3,arg4,arg5,arg6);\n  {\n    /* \n    \tassert(result >= 0);  assertion removed as PyGSL_error_flag can deal with\n    \tnegative numbers.\n         */\n    if(GSL_FAILURE == PyGSL_ERROR_FLAG(result)){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 74); \n      goto fail;\n    }\n    Py_INCREF(Py_None);\n    resultobj = Py_None;\n  }\n  {\n    resultobj = SWIG_Python_AppendOutput(resultobj,  (PyObject *) _PyVector3);\n    _PyVector3 =NULL;\n  }\n  {\n    resultobj = SWIG_Python_AppendOutput(resultobj,  (PyObject *) _PyMatrix4);\n    _PyMatrix4 =NULL;\n  }\n  if (SWIG_IsTmpObj(res5)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg5)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res5) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg5), SWIGTYPE_p_double, new_flags));\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyVector2);\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyVector3);\n    _PyVector3 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix4);\n    _PyMatrix4 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyVector2);\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyVector3);\n    _PyVector3 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix4);\n    _PyMatrix4 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multifit_linear_svd(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix *arg1 = (gsl_matrix *) 0 ;\n  gsl_vector *arg2 = (gsl_vector *) 0 ;\n  double arg3 ;\n  size_t *arg4 = (size_t *) 0 ;\n  gsl_vector *arg5 = (gsl_vector *) 0 ;\n  gsl_matrix *arg6 = (gsl_matrix *) 0 ;\n  double *arg7 = (double *) 0 ;\n  gsl_multifit_linear_workspace *arg8 = (gsl_multifit_linear_workspace *) 0 ;\n  double val3 ;\n  int ecode3 = 0 ;\n  size_t temp4 ;\n  int res4 = SWIG_TMPOBJ ;\n  double temp7 ;\n  int res7 = SWIG_TMPOBJ ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  PyObject * obj3 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\",(char *) \"IN\",(char *) \"TOL\",(char *) \"work_provide\", NULL \n  };\n  gsl_error_flag_drop result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix _matrix1;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector _vector2;\n  \n  \n  PyArrayObject * volatile _PyVector5 = NULL;\n  TYPE_VIEW_gsl_vector _vector5;\n  \n  \n  PyArrayObject * _PyMatrix6 = NULL;\n  TYPE_VIEW_gsl_matrix _matrix6;\n  \n  \n  PyGSL_array_index_t _work_provide_n_work_provide = -1;\n  PyGSL_array_index_t _work_provide_p_work_provide = -1;\n  \n  arg4 = &temp4;\n  \n  /* All done in check as the workspace stores the information about the required size */\n  \n  \n  /* All done in check as the workspace stores the information about the required size */\n  \n  arg7 = &temp7;\n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOOO:gsl_multifit_linear_svd\",kwnames,&obj0,&obj1,&obj2,&obj3)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2,\n        PyGSL_INPUT_ARRAY, gsl_vector, 2, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  ecode3 = SWIG_AsVal_double(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_multifit_linear_svd\" \"', argument \" \"3\"\" of type '\" \"double\"\"'\");\n  } \n  arg3 = (double)(val3);\n  {\n    if ((SWIG_ConvertPtr(obj3, (void **) &arg8, SWIGTYPE_p_gsl_multifit_linear_workspace,1)) == -1){\n      goto fail;\n    }\n    _work_provide_n_work_provide = (int) arg8->n;\n    _work_provide_p_work_provide = (int) arg8->p;\n  }\n  {\n    PyGSL_array_index_t stride;\n    \n    _PyVector5 = (PyArrayObject *) PyGSL_New_Array(1, &_work_provide_p_work_provide, PyArray_DOUBLE);\n    if(NULL == _PyVector5){\n      goto fail;\n    }\n    \n    if(PyGSL_STRIDE_RECALC(_PyVector5->strides[0], sizeof(BASIS_TYPE(gsl_vector)), &stride) != GSL_SUCCESS)\n    goto fail;\n    \n    _vector5  = TYPE_VIEW_ARRAY_STRIDES_gsl_vector((BASIS_C_TYPE(gsl_vector) *) _PyVector5->data,\n      stride,\n      _PyVector5->dimensions[0]);\n    arg5 = (gsl_vector *) &(_vector5.vector);\n    \n  }\n  {\n    PyArrayObject * a_array;\n    \n    PyGSL_array_index_t stride_recalc=0, dimensions[2];\n    dimensions[0] = _work_provide_p_work_provide;\n    dimensions[1] = _work_provide_p_work_provide;\n    a_array = (PyArrayObject *) PyGSL_New_Array(2, dimensions, PyArray_DOUBLE);\n    if(NULL == a_array){\n      goto fail;\n    }\n    _PyMatrix6 = a_array;\n    \n    \n    if(PyGSL_STRIDE_RECALC(a_array->strides[0], sizeof(BASIS_TYPE(gsl_matrix)), &stride_recalc) != GSL_SUCCESS)\n    goto fail;\n    /* (BASIS_TYPE_gsl_matrix *) */\n    _matrix6  = TYPE_VIEW_ARRAY_gsl_matrix((BASIS_C_TYPE(gsl_matrix) *) a_array->data, \n      a_array->dimensions[0], a_array->dimensions[1]);\n    \n    arg6 = (gsl_matrix *) &(_matrix6.matrix);\n  }\n  result = gsl_multifit_linear_svd((gsl_matrix const *)arg1,(gsl_vector const *)arg2,arg3,arg4,arg5,arg6,arg7,arg8);\n  {\n    /* \n    \tassert(result >= 0);  assertion removed as PyGSL_error_flag can deal with\n    \tnegative numbers.\n         */\n    if(GSL_FAILURE == PyGSL_ERROR_FLAG(result)){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 74); \n      goto fail;\n    }\n    Py_INCREF(Py_None);\n    resultobj = Py_None;\n  }\n  if (SWIG_IsTmpObj(res4)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_size_t((*arg4)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res4) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg4), SWIGTYPE_p_unsigned_int, new_flags));\n  }\n  {\n    resultobj = SWIG_Python_AppendOutput(resultobj,  (PyObject *) _PyVector5);\n    _PyVector5 =NULL;\n  }\n  {\n    resultobj = SWIG_Python_AppendOutput(resultobj,  (PyObject *) _PyMatrix6);\n    _PyMatrix6 =NULL;\n  }\n  if (SWIG_IsTmpObj(res7)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg7)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res7) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg7), SWIGTYPE_p_double, new_flags));\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyVector2);\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyVector5);\n    _PyVector5 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix6);\n    _PyMatrix6 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyVector2);\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyVector5);\n    _PyVector5 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix6);\n    _PyMatrix6 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multifit_wlinear(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix *arg1 = (gsl_matrix *) 0 ;\n  gsl_vector *arg2 = (gsl_vector *) 0 ;\n  gsl_vector *arg3 = (gsl_vector *) 0 ;\n  gsl_vector *arg4 = (gsl_vector *) 0 ;\n  gsl_matrix *arg5 = (gsl_matrix *) 0 ;\n  double *arg6 = (double *) 0 ;\n  gsl_multifit_linear_workspace *arg7 = (gsl_multifit_linear_workspace *) 0 ;\n  double temp6 ;\n  int res6 = SWIG_TMPOBJ ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  PyObject * obj3 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\",(char *) \"IN\",(char *) \"IN\",(char *) \"work_provide\", NULL \n  };\n  gsl_error_flag_drop result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix _matrix1;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector _vector2;\n  \n  \n  PyArrayObject * volatile _PyVector3 = NULL;\n  TYPE_VIEW_gsl_vector _vector3;\n  \n  \n  PyArrayObject * volatile _PyVector4 = NULL;\n  TYPE_VIEW_gsl_vector _vector4;\n  \n  \n  PyArrayObject * _PyMatrix5 = NULL;\n  TYPE_VIEW_gsl_matrix _matrix5;\n  \n  \n  PyGSL_array_index_t _work_provide_n_work_provide = -1;\n  PyGSL_array_index_t _work_provide_p_work_provide = -1;\n  \n  \n  /* All done in check as the workspace stores the information about the required size */\n  \n  \n  /* All done in check as the workspace stores the information about the required size */\n  \n  arg6 = &temp6;\n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOOO:gsl_multifit_wlinear\",kwnames,&obj0,&obj1,&obj2,&obj3)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2,\n        PyGSL_INPUT_ARRAY, gsl_vector, 2, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj2, arg3, _PyVector3, _vector3,\n        PyGSL_INPUT_ARRAY, gsl_vector, 3, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  {\n    if ((SWIG_ConvertPtr(obj3, (void **) &arg7, SWIGTYPE_p_gsl_multifit_linear_workspace,1)) == -1){\n      goto fail;\n    }\n    _work_provide_n_work_provide = (int) arg7->n;\n    _work_provide_p_work_provide = (int) arg7->p;\n  }\n  {\n    PyGSL_array_index_t stride;\n    \n    _PyVector4 = (PyArrayObject *) PyGSL_New_Array(1, &_work_provide_p_work_provide, PyArray_DOUBLE);\n    if(NULL == _PyVector4){\n      goto fail;\n    }\n    \n    if(PyGSL_STRIDE_RECALC(_PyVector4->strides[0], sizeof(BASIS_TYPE(gsl_vector)), &stride) != GSL_SUCCESS)\n    goto fail;\n    \n    _vector4  = TYPE_VIEW_ARRAY_STRIDES_gsl_vector((BASIS_C_TYPE(gsl_vector) *) _PyVector4->data,\n      stride,\n      _PyVector4->dimensions[0]);\n    arg4 = (gsl_vector *) &(_vector4.vector);\n    \n  }\n  {\n    PyArrayObject * a_array;\n    \n    PyGSL_array_index_t stride_recalc=0, dimensions[2];\n    dimensions[0] = _work_provide_p_work_provide;\n    dimensions[1] = _work_provide_p_work_provide;\n    a_array = (PyArrayObject *) PyGSL_New_Array(2, dimensions, PyArray_DOUBLE);\n    if(NULL == a_array){\n      goto fail;\n    }\n    _PyMatrix5 = a_array;\n    \n    \n    if(PyGSL_STRIDE_RECALC(a_array->strides[0], sizeof(BASIS_TYPE(gsl_matrix)), &stride_recalc) != GSL_SUCCESS)\n    goto fail;\n    /* (BASIS_TYPE_gsl_matrix *) */\n    _matrix5  = TYPE_VIEW_ARRAY_gsl_matrix((BASIS_C_TYPE(gsl_matrix) *) a_array->data, \n      a_array->dimensions[0], a_array->dimensions[1]);\n    \n    arg5 = (gsl_matrix *) &(_matrix5.matrix);\n  }\n  result = gsl_multifit_wlinear((gsl_matrix const *)arg1,(gsl_vector const *)arg2,(gsl_vector const *)arg3,arg4,arg5,arg6,arg7);\n  {\n    /* \n    \tassert(result >= 0);  assertion removed as PyGSL_error_flag can deal with\n    \tnegative numbers.\n         */\n    if(GSL_FAILURE == PyGSL_ERROR_FLAG(result)){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 74); \n      goto fail;\n    }\n    Py_INCREF(Py_None);\n    resultobj = Py_None;\n  }\n  {\n    resultobj = SWIG_Python_AppendOutput(resultobj,  (PyObject *) _PyVector4);\n    _PyVector4 =NULL;\n  }\n  {\n    resultobj = SWIG_Python_AppendOutput(resultobj,  (PyObject *) _PyMatrix5);\n    _PyMatrix5 =NULL;\n  }\n  if (SWIG_IsTmpObj(res6)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg6)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res6) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg6), SWIGTYPE_p_double, new_flags));\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyVector2);\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyVector3);\n    _PyVector3 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyVector4);\n    _PyVector4 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix5);\n    _PyMatrix5 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyVector2);\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyVector3);\n    _PyVector3 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyVector4);\n    _PyVector4 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix5);\n    _PyMatrix5 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multifit_wlinear_svd(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix *arg1 = (gsl_matrix *) 0 ;\n  gsl_vector *arg2 = (gsl_vector *) 0 ;\n  gsl_vector *arg3 = (gsl_vector *) 0 ;\n  double arg4 ;\n  size_t *arg5 = (size_t *) 0 ;\n  gsl_vector *arg6 = (gsl_vector *) 0 ;\n  gsl_matrix *arg7 = (gsl_matrix *) 0 ;\n  double *arg8 = (double *) 0 ;\n  gsl_multifit_linear_workspace *arg9 = (gsl_multifit_linear_workspace *) 0 ;\n  double val4 ;\n  int ecode4 = 0 ;\n  size_t temp5 ;\n  int res5 = SWIG_TMPOBJ ;\n  double temp8 ;\n  int res8 = SWIG_TMPOBJ ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  PyObject * obj3 = 0 ;\n  PyObject * obj4 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\",(char *) \"IN\",(char *) \"IN\",(char *) \"TOL\",(char *) \"work_provide\", NULL \n  };\n  gsl_error_flag_drop result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix _matrix1;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector _vector2;\n  \n  \n  PyArrayObject * volatile _PyVector3 = NULL;\n  TYPE_VIEW_gsl_vector _vector3;\n  \n  \n  PyArrayObject * volatile _PyVector6 = NULL;\n  TYPE_VIEW_gsl_vector _vector6;\n  \n  \n  PyArrayObject * _PyMatrix7 = NULL;\n  TYPE_VIEW_gsl_matrix _matrix7;\n  \n  \n  PyGSL_array_index_t _work_provide_n_work_provide = -1;\n  PyGSL_array_index_t _work_provide_p_work_provide = -1;\n  \n  arg5 = &temp5;\n  \n  /* All done in check as the workspace stores the information about the required size */\n  \n  \n  /* All done in check as the workspace stores the information about the required size */\n  \n  arg8 = &temp8;\n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOOOO:gsl_multifit_wlinear_svd\",kwnames,&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2,\n        PyGSL_INPUT_ARRAY, gsl_vector, 2, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj2, arg3, _PyVector3, _vector3,\n        PyGSL_INPUT_ARRAY, gsl_vector, 3, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  ecode4 = SWIG_AsVal_double(obj3, &val4);\n  if (!SWIG_IsOK(ecode4)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode4), \"in method '\" \"gsl_multifit_wlinear_svd\" \"', argument \" \"4\"\" of type '\" \"double\"\"'\");\n  } \n  arg4 = (double)(val4);\n  {\n    if ((SWIG_ConvertPtr(obj4, (void **) &arg9, SWIGTYPE_p_gsl_multifit_linear_workspace,1)) == -1){\n      goto fail;\n    }\n    _work_provide_n_work_provide = (int) arg9->n;\n    _work_provide_p_work_provide = (int) arg9->p;\n  }\n  {\n    PyGSL_array_index_t stride;\n    \n    _PyVector6 = (PyArrayObject *) PyGSL_New_Array(1, &_work_provide_p_work_provide, PyArray_DOUBLE);\n    if(NULL == _PyVector6){\n      goto fail;\n    }\n    \n    if(PyGSL_STRIDE_RECALC(_PyVector6->strides[0], sizeof(BASIS_TYPE(gsl_vector)), &stride) != GSL_SUCCESS)\n    goto fail;\n    \n    _vector6  = TYPE_VIEW_ARRAY_STRIDES_gsl_vector((BASIS_C_TYPE(gsl_vector) *) _PyVector6->data,\n      stride,\n      _PyVector6->dimensions[0]);\n    arg6 = (gsl_vector *) &(_vector6.vector);\n    \n  }\n  {\n    PyArrayObject * a_array;\n    \n    PyGSL_array_index_t stride_recalc=0, dimensions[2];\n    dimensions[0] = _work_provide_p_work_provide;\n    dimensions[1] = _work_provide_p_work_provide;\n    a_array = (PyArrayObject *) PyGSL_New_Array(2, dimensions, PyArray_DOUBLE);\n    if(NULL == a_array){\n      goto fail;\n    }\n    _PyMatrix7 = a_array;\n    \n    \n    if(PyGSL_STRIDE_RECALC(a_array->strides[0], sizeof(BASIS_TYPE(gsl_matrix)), &stride_recalc) != GSL_SUCCESS)\n    goto fail;\n    /* (BASIS_TYPE_gsl_matrix *) */\n    _matrix7  = TYPE_VIEW_ARRAY_gsl_matrix((BASIS_C_TYPE(gsl_matrix) *) a_array->data, \n      a_array->dimensions[0], a_array->dimensions[1]);\n    \n    arg7 = (gsl_matrix *) &(_matrix7.matrix);\n  }\n  result = gsl_multifit_wlinear_svd((gsl_matrix const *)arg1,(gsl_vector const *)arg2,(gsl_vector const *)arg3,arg4,arg5,arg6,arg7,arg8,arg9);\n  {\n    /* \n    \tassert(result >= 0);  assertion removed as PyGSL_error_flag can deal with\n    \tnegative numbers.\n         */\n    if(GSL_FAILURE == PyGSL_ERROR_FLAG(result)){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 74); \n      goto fail;\n    }\n    Py_INCREF(Py_None);\n    resultobj = Py_None;\n  }\n  if (SWIG_IsTmpObj(res5)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_size_t((*arg5)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res5) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg5), SWIGTYPE_p_unsigned_int, new_flags));\n  }\n  {\n    resultobj = SWIG_Python_AppendOutput(resultobj,  (PyObject *) _PyVector6);\n    _PyVector6 =NULL;\n  }\n  {\n    resultobj = SWIG_Python_AppendOutput(resultobj,  (PyObject *) _PyMatrix7);\n    _PyMatrix7 =NULL;\n  }\n  if (SWIG_IsTmpObj(res8)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg8)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res8) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg8), SWIGTYPE_p_double, new_flags));\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyVector2);\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyVector3);\n    _PyVector3 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyVector6);\n    _PyVector6 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix7);\n    _PyMatrix7 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyVector2);\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyVector3);\n    _PyVector3 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyVector6);\n    _PyVector6 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix7);\n    _PyMatrix7 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multifit_linear_est(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector *arg1 = (gsl_vector *) 0 ;\n  gsl_vector *arg2 = (gsl_vector *) 0 ;\n  gsl_matrix *arg3 = (gsl_matrix *) 0 ;\n  double *arg4 = (double *) 0 ;\n  double *arg5 = (double *) 0 ;\n  double temp4 ;\n  int res4 = SWIG_TMPOBJ ;\n  double temp5 ;\n  int res5 = SWIG_TMPOBJ ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\",(char *) \"IN\",(char *) \"IN\", NULL \n  };\n  gsl_error_flag_drop result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector _vector1;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector _vector2;\n  \n  \n  PyArrayObject * _PyMatrix3 = NULL;\n  TYPE_VIEW_gsl_matrix _matrix3;\n  \n  arg4 = &temp4;\n  arg5 = &temp5;\n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_multifit_linear_est\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2,\n        PyGSL_INPUT_ARRAY, gsl_vector, 2, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj2, arg3, _PyMatrix3, _matrix3,\n        PyGSL_INPUT_ARRAY, gsl_matrix, 3, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = gsl_multifit_linear_est((gsl_vector const *)arg1,(gsl_vector const *)arg2,(gsl_matrix const *)arg3,arg4,arg5);\n  {\n    /* \n    \tassert(result >= 0);  assertion removed as PyGSL_error_flag can deal with\n    \tnegative numbers.\n         */\n    if(GSL_FAILURE == PyGSL_ERROR_FLAG(result)){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 74); \n      goto fail;\n    }\n    Py_INCREF(Py_None);\n    resultobj = Py_None;\n  }\n  if (SWIG_IsTmpObj(res4)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg4)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res4) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg4), SWIGTYPE_p_double, new_flags));\n  }\n  if (SWIG_IsTmpObj(res5)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg5)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res5) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg5), SWIGTYPE_p_double, new_flags));\n  }\n  {\n    Py_XDECREF(_PyVector1);\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyVector2);\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix3);\n    _PyMatrix3 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyVector1);\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyVector2);\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix3);\n    _PyMatrix3 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_multifit_linear_est_matrix(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix *arg1 = (gsl_matrix *) 0 ;\n  gsl_vector *arg2 = (gsl_vector *) 0 ;\n  gsl_matrix *arg3 = (gsl_matrix *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\",(char *) \"IN\",(char *) \"IN\", NULL \n  };\n  PyObject *result = 0 ;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix _matrix1;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector _vector2;\n  \n  \n  PyArrayObject * _PyMatrix3 = NULL;\n  TYPE_VIEW_gsl_matrix _matrix3;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_multifit_linear_est_matrix\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2,\n        PyGSL_INPUT_ARRAY, gsl_vector, 2, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj2, arg3, _PyMatrix3, _matrix3,\n        PyGSL_INPUT_ARRAY, gsl_matrix, 3, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (PyObject *)gsl_multifit_linear_est_matrix((gsl_matrix const *)arg1,(gsl_vector const *)arg2,(gsl_matrix const *)arg3);\n  resultobj = result;\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyVector2);\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix3);\n    _PyMatrix3 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyVector2);\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix3);\n    _PyMatrix3 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_fit_linear(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  double *arg1 = (double *) 0 ;\n  size_t arg2 ;\n  double *arg3 = (double *) 0 ;\n  size_t arg4 ;\n  size_t arg5 ;\n  double *arg6 = (double *) 0 ;\n  double *arg7 = (double *) 0 ;\n  double *arg8 = (double *) 0 ;\n  double *arg9 = (double *) 0 ;\n  double *arg10 = (double *) 0 ;\n  double *arg11 = (double *) 0 ;\n  double temp6 ;\n  int res6 = SWIG_TMPOBJ ;\n  double temp7 ;\n  int res7 = SWIG_TMPOBJ ;\n  double temp8 ;\n  int res8 = SWIG_TMPOBJ ;\n  double temp9 ;\n  int res9 = SWIG_TMPOBJ ;\n  double temp10 ;\n  int res10 = SWIG_TMPOBJ ;\n  double temp11 ;\n  int res11 = SWIG_TMPOBJ ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"x\",(char *) \"y\", NULL \n  };\n  gsl_error_flag_drop result;\n  \n  \n  PyArrayObject *_PyVector1 = NULL;\n  size_t         _PyVectorLengthx   = 0; \n  \n  \n  PyArrayObject *_PyVector3 = NULL;\n  size_t         _PyVectorLengthy   = 0; \n  \n  {\n    arg5 = 0;\n  }\n  arg6 = &temp6;\n  arg7 = &temp7;\n  arg8 = &temp8;\n  arg9 = &temp9;\n  arg10 = &temp10;\n  arg11 = &temp11;\n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_fit_linear\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    PyGSL_array_index_t strides, size;\n    /* This should be a preprocessor directive. */\n    if ( 'x' == 'x' )\n    size = -1;\n    else\n    size = _PyVectorLengthx;\n    _PyVector1 = PyGSL_vector_check(obj0, size, PyGSL_DARRAY_INPUT(1), &strides, NULL);\n    if (_PyVector1 == NULL)\n    goto fail;\n    \n    arg1 = (double *) (_PyVector1->data);\n    arg2 = (size_t) strides;\n    _PyVectorLengthx = (size_t) _PyVector1->dimensions[0];\n  }\n  {\n    PyGSL_array_index_t strides, size;\n    /* This should be a preprocessor directive. */\n    if ( 'y' == 'x' )\n    size = -1;\n    else\n    size = _PyVectorLengthx;\n    _PyVector3 = PyGSL_vector_check(obj1, size, PyGSL_DARRAY_INPUT(3), &strides, NULL);\n    if (_PyVector3 == NULL)\n    goto fail;\n    \n    arg3 = (double *) (_PyVector3->data);\n    arg4 = (size_t) strides;\n    _PyVectorLengthy = (size_t) _PyVector3->dimensions[0];\n  }\n  {\n    arg5 = _PyVectorLengthx;\n  }\n  result = gsl_fit_linear((double const *)arg1,arg2,(double const *)arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10,arg11);\n  {\n    /* \n    \tassert(result >= 0);  assertion removed as PyGSL_error_flag can deal with\n    \tnegative numbers.\n         */\n    if(GSL_FAILURE == PyGSL_ERROR_FLAG(result)){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 74); \n      goto fail;\n    }\n    Py_INCREF(Py_None);\n    resultobj = Py_None;\n  }\n  {\n    Py_XDECREF(_PyVector1);\n  }\n  {\n    Py_XDECREF(_PyVector3);\n  }\n  if (SWIG_IsTmpObj(res6)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg6)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res6) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg6), SWIGTYPE_p_double, new_flags));\n  }\n  if (SWIG_IsTmpObj(res7)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg7)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res7) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg7), SWIGTYPE_p_double, new_flags));\n  }\n  if (SWIG_IsTmpObj(res8)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg8)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res8) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg8), SWIGTYPE_p_double, new_flags));\n  }\n  if (SWIG_IsTmpObj(res9)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg9)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res9) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg9), SWIGTYPE_p_double, new_flags));\n  }\n  if (SWIG_IsTmpObj(res10)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg10)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res10) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg10), SWIGTYPE_p_double, new_flags));\n  }\n  if (SWIG_IsTmpObj(res11)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg11)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res11) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg11), SWIGTYPE_p_double, new_flags));\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_fit_wlinear(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  double *arg1 = (double *) 0 ;\n  size_t arg2 ;\n  double *arg3 = (double *) 0 ;\n  size_t arg4 ;\n  double *arg5 = (double *) 0 ;\n  size_t arg6 ;\n  size_t arg7 ;\n  double *arg8 = (double *) 0 ;\n  double *arg9 = (double *) 0 ;\n  double *arg10 = (double *) 0 ;\n  double *arg11 = (double *) 0 ;\n  double *arg12 = (double *) 0 ;\n  double *arg13 = (double *) 0 ;\n  double temp8 ;\n  int res8 = SWIG_TMPOBJ ;\n  double temp9 ;\n  int res9 = SWIG_TMPOBJ ;\n  double temp10 ;\n  int res10 = SWIG_TMPOBJ ;\n  double temp11 ;\n  int res11 = SWIG_TMPOBJ ;\n  double temp12 ;\n  int res12 = SWIG_TMPOBJ ;\n  double temp13 ;\n  int res13 = SWIG_TMPOBJ ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"x\",(char *) \"w\",(char *) \"y\", NULL \n  };\n  gsl_error_flag_drop result;\n  \n  \n  PyArrayObject *_PyVector1 = NULL;\n  size_t         _PyVectorLengthx   = 0; \n  \n  \n  PyArrayObject *_PyVector3 = NULL;\n  size_t         _PyVectorLengthw   = 0; \n  \n  \n  PyArrayObject *_PyVector5 = NULL;\n  size_t         _PyVectorLengthy   = 0; \n  \n  {\n    arg7 = 0;\n  }\n  arg8 = &temp8;\n  arg9 = &temp9;\n  arg10 = &temp10;\n  arg11 = &temp11;\n  arg12 = &temp12;\n  arg13 = &temp13;\n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_fit_wlinear\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  {\n    PyGSL_array_index_t strides, size;\n    /* This should be a preprocessor directive. */\n    if ( 'x' == 'x' )\n    size = -1;\n    else\n    size = _PyVectorLengthx;\n    _PyVector1 = PyGSL_vector_check(obj0, size, PyGSL_DARRAY_INPUT(1), &strides, NULL);\n    if (_PyVector1 == NULL)\n    goto fail;\n    \n    arg1 = (double *) (_PyVector1->data);\n    arg2 = (size_t) strides;\n    _PyVectorLengthx = (size_t) _PyVector1->dimensions[0];\n  }\n  {\n    PyGSL_array_index_t strides, size;\n    /* This should be a preprocessor directive. */\n    if ( 'w' == 'x' )\n    size = -1;\n    else\n    size = _PyVectorLengthx;\n    _PyVector3 = PyGSL_vector_check(obj1, size, PyGSL_DARRAY_INPUT(3), &strides, NULL);\n    if (_PyVector3 == NULL)\n    goto fail;\n    \n    arg3 = (double *) (_PyVector3->data);\n    arg4 = (size_t) strides;\n    _PyVectorLengthw = (size_t) _PyVector3->dimensions[0];\n  }\n  {\n    PyGSL_array_index_t strides, size;\n    /* This should be a preprocessor directive. */\n    if ( 'y' == 'x' )\n    size = -1;\n    else\n    size = _PyVectorLengthx;\n    _PyVector5 = PyGSL_vector_check(obj2, size, PyGSL_DARRAY_INPUT(5), &strides, NULL);\n    if (_PyVector5 == NULL)\n    goto fail;\n    \n    arg5 = (double *) (_PyVector5->data);\n    arg6 = (size_t) strides;\n    _PyVectorLengthy = (size_t) _PyVector5->dimensions[0];\n  }\n  {\n    arg7 = _PyVectorLengthx;\n  }\n  result = gsl_fit_wlinear((double const *)arg1,arg2,(double const *)arg3,arg4,(double const *)arg5,arg6,arg7,arg8,arg9,arg10,arg11,arg12,arg13);\n  {\n    /* \n    \tassert(result >= 0);  assertion removed as PyGSL_error_flag can deal with\n    \tnegative numbers.\n         */\n    if(GSL_FAILURE == PyGSL_ERROR_FLAG(result)){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 74); \n      goto fail;\n    }\n    Py_INCREF(Py_None);\n    resultobj = Py_None;\n  }\n  {\n    Py_XDECREF(_PyVector1);\n  }\n  {\n    Py_XDECREF(_PyVector3);\n  }\n  {\n    Py_XDECREF(_PyVector5);\n  }\n  if (SWIG_IsTmpObj(res8)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg8)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res8) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg8), SWIGTYPE_p_double, new_flags));\n  }\n  if (SWIG_IsTmpObj(res9)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg9)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res9) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg9), SWIGTYPE_p_double, new_flags));\n  }\n  if (SWIG_IsTmpObj(res10)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg10)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res10) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg10), SWIGTYPE_p_double, new_flags));\n  }\n  if (SWIG_IsTmpObj(res11)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg11)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res11) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg11), SWIGTYPE_p_double, new_flags));\n  }\n  if (SWIG_IsTmpObj(res12)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg12)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res12) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg12), SWIGTYPE_p_double, new_flags));\n  }\n  if (SWIG_IsTmpObj(res13)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg13)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res13) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg13), SWIGTYPE_p_double, new_flags));\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_fit_linear_est(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  double arg1 ;\n  double arg2 ;\n  double arg3 ;\n  double arg4 ;\n  double arg5 ;\n  double arg6 ;\n  double *arg7 = (double *) 0 ;\n  double *arg8 = (double *) 0 ;\n  double val1 ;\n  int ecode1 = 0 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  double val3 ;\n  int ecode3 = 0 ;\n  double val4 ;\n  int ecode4 = 0 ;\n  double val5 ;\n  int ecode5 = 0 ;\n  double val6 ;\n  int ecode6 = 0 ;\n  double temp7 ;\n  int res7 = SWIG_TMPOBJ ;\n  double temp8 ;\n  int res8 = SWIG_TMPOBJ ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  PyObject * obj3 = 0 ;\n  PyObject * obj4 = 0 ;\n  PyObject * obj5 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"x\",(char *) \"c0\",(char *) \"c1\",(char *) \"c00\",(char *) \"c01\",(char *) \"c11\", NULL \n  };\n  gsl_error_flag_drop result;\n  \n  arg7 = &temp7;\n  arg8 = &temp8;\n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOOOOO:gsl_fit_linear_est\",kwnames,&obj0,&obj1,&obj2,&obj3,&obj4,&obj5)) SWIG_fail;\n  ecode1 = SWIG_AsVal_double(obj0, &val1);\n  if (!SWIG_IsOK(ecode1)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode1), \"in method '\" \"gsl_fit_linear_est\" \"', argument \" \"1\"\" of type '\" \"double\"\"'\");\n  } \n  arg1 = (double)(val1);\n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_fit_linear_est\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  ecode3 = SWIG_AsVal_double(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_fit_linear_est\" \"', argument \" \"3\"\" of type '\" \"double\"\"'\");\n  } \n  arg3 = (double)(val3);\n  ecode4 = SWIG_AsVal_double(obj3, &val4);\n  if (!SWIG_IsOK(ecode4)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode4), \"in method '\" \"gsl_fit_linear_est\" \"', argument \" \"4\"\" of type '\" \"double\"\"'\");\n  } \n  arg4 = (double)(val4);\n  ecode5 = SWIG_AsVal_double(obj4, &val5);\n  if (!SWIG_IsOK(ecode5)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode5), \"in method '\" \"gsl_fit_linear_est\" \"', argument \" \"5\"\" of type '\" \"double\"\"'\");\n  } \n  arg5 = (double)(val5);\n  ecode6 = SWIG_AsVal_double(obj5, &val6);\n  if (!SWIG_IsOK(ecode6)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode6), \"in method '\" \"gsl_fit_linear_est\" \"', argument \" \"6\"\" of type '\" \"double\"\"'\");\n  } \n  arg6 = (double)(val6);\n  result = gsl_fit_linear_est(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8);\n  {\n    /* \n    \tassert(result >= 0);  assertion removed as PyGSL_error_flag can deal with\n    \tnegative numbers.\n         */\n    if(GSL_FAILURE == PyGSL_ERROR_FLAG(result)){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 74); \n      goto fail;\n    }\n    Py_INCREF(Py_None);\n    resultobj = Py_None;\n  }\n  if (SWIG_IsTmpObj(res7)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg7)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res7) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg7), SWIGTYPE_p_double, new_flags));\n  }\n  if (SWIG_IsTmpObj(res8)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg8)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res8) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg8), SWIGTYPE_p_double, new_flags));\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_fit_mul(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  double *arg1 = (double *) 0 ;\n  size_t arg2 ;\n  double *arg3 = (double *) 0 ;\n  size_t arg4 ;\n  size_t arg5 ;\n  double *arg6 = (double *) 0 ;\n  double *arg7 = (double *) 0 ;\n  double *arg8 = (double *) 0 ;\n  double temp6 ;\n  int res6 = SWIG_TMPOBJ ;\n  double temp7 ;\n  int res7 = SWIG_TMPOBJ ;\n  double temp8 ;\n  int res8 = SWIG_TMPOBJ ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"x\",(char *) \"y\", NULL \n  };\n  gsl_error_flag_drop result;\n  \n  \n  PyArrayObject *_PyVector1 = NULL;\n  size_t         _PyVectorLengthx   = 0; \n  \n  \n  PyArrayObject *_PyVector3 = NULL;\n  size_t         _PyVectorLengthy   = 0; \n  \n  {\n    arg5 = 0;\n  }\n  arg6 = &temp6;\n  arg7 = &temp7;\n  arg8 = &temp8;\n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_fit_mul\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    PyGSL_array_index_t strides, size;\n    /* This should be a preprocessor directive. */\n    if ( 'x' == 'x' )\n    size = -1;\n    else\n    size = _PyVectorLengthx;\n    _PyVector1 = PyGSL_vector_check(obj0, size, PyGSL_DARRAY_INPUT(1), &strides, NULL);\n    if (_PyVector1 == NULL)\n    goto fail;\n    \n    arg1 = (double *) (_PyVector1->data);\n    arg2 = (size_t) strides;\n    _PyVectorLengthx = (size_t) _PyVector1->dimensions[0];\n  }\n  {\n    PyGSL_array_index_t strides, size;\n    /* This should be a preprocessor directive. */\n    if ( 'y' == 'x' )\n    size = -1;\n    else\n    size = _PyVectorLengthx;\n    _PyVector3 = PyGSL_vector_check(obj1, size, PyGSL_DARRAY_INPUT(3), &strides, NULL);\n    if (_PyVector3 == NULL)\n    goto fail;\n    \n    arg3 = (double *) (_PyVector3->data);\n    arg4 = (size_t) strides;\n    _PyVectorLengthy = (size_t) _PyVector3->dimensions[0];\n  }\n  {\n    arg5 = _PyVectorLengthx;\n  }\n  result = gsl_fit_mul((double const *)arg1,arg2,(double const *)arg3,arg4,arg5,arg6,arg7,arg8);\n  {\n    /* \n    \tassert(result >= 0);  assertion removed as PyGSL_error_flag can deal with\n    \tnegative numbers.\n         */\n    if(GSL_FAILURE == PyGSL_ERROR_FLAG(result)){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 74); \n      goto fail;\n    }\n    Py_INCREF(Py_None);\n    resultobj = Py_None;\n  }\n  {\n    Py_XDECREF(_PyVector1);\n  }\n  {\n    Py_XDECREF(_PyVector3);\n  }\n  if (SWIG_IsTmpObj(res6)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg6)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res6) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg6), SWIGTYPE_p_double, new_flags));\n  }\n  if (SWIG_IsTmpObj(res7)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg7)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res7) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg7), SWIGTYPE_p_double, new_flags));\n  }\n  if (SWIG_IsTmpObj(res8)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg8)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res8) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg8), SWIGTYPE_p_double, new_flags));\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_fit_wmul(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  double *arg1 = (double *) 0 ;\n  size_t arg2 ;\n  double *arg3 = (double *) 0 ;\n  size_t arg4 ;\n  double *arg5 = (double *) 0 ;\n  size_t arg6 ;\n  size_t arg7 ;\n  double *arg8 = (double *) 0 ;\n  double *arg9 = (double *) 0 ;\n  double *arg10 = (double *) 0 ;\n  double temp8 ;\n  int res8 = SWIG_TMPOBJ ;\n  double temp9 ;\n  int res9 = SWIG_TMPOBJ ;\n  double temp10 ;\n  int res10 = SWIG_TMPOBJ ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"x\",(char *) \"w\",(char *) \"y\", NULL \n  };\n  gsl_error_flag_drop result;\n  \n  \n  PyArrayObject *_PyVector1 = NULL;\n  size_t         _PyVectorLengthx   = 0; \n  \n  \n  PyArrayObject *_PyVector3 = NULL;\n  size_t         _PyVectorLengthw   = 0; \n  \n  \n  PyArrayObject *_PyVector5 = NULL;\n  size_t         _PyVectorLengthy   = 0; \n  \n  {\n    arg7 = 0;\n  }\n  arg8 = &temp8;\n  arg9 = &temp9;\n  arg10 = &temp10;\n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_fit_wmul\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  {\n    PyGSL_array_index_t strides, size;\n    /* This should be a preprocessor directive. */\n    if ( 'x' == 'x' )\n    size = -1;\n    else\n    size = _PyVectorLengthx;\n    _PyVector1 = PyGSL_vector_check(obj0, size, PyGSL_DARRAY_INPUT(1), &strides, NULL);\n    if (_PyVector1 == NULL)\n    goto fail;\n    \n    arg1 = (double *) (_PyVector1->data);\n    arg2 = (size_t) strides;\n    _PyVectorLengthx = (size_t) _PyVector1->dimensions[0];\n  }\n  {\n    PyGSL_array_index_t strides, size;\n    /* This should be a preprocessor directive. */\n    if ( 'w' == 'x' )\n    size = -1;\n    else\n    size = _PyVectorLengthx;\n    _PyVector3 = PyGSL_vector_check(obj1, size, PyGSL_DARRAY_INPUT(3), &strides, NULL);\n    if (_PyVector3 == NULL)\n    goto fail;\n    \n    arg3 = (double *) (_PyVector3->data);\n    arg4 = (size_t) strides;\n    _PyVectorLengthw = (size_t) _PyVector3->dimensions[0];\n  }\n  {\n    PyGSL_array_index_t strides, size;\n    /* This should be a preprocessor directive. */\n    if ( 'y' == 'x' )\n    size = -1;\n    else\n    size = _PyVectorLengthx;\n    _PyVector5 = PyGSL_vector_check(obj2, size, PyGSL_DARRAY_INPUT(5), &strides, NULL);\n    if (_PyVector5 == NULL)\n    goto fail;\n    \n    arg5 = (double *) (_PyVector5->data);\n    arg6 = (size_t) strides;\n    _PyVectorLengthy = (size_t) _PyVector5->dimensions[0];\n  }\n  {\n    arg7 = _PyVectorLengthx;\n  }\n  result = gsl_fit_wmul((double const *)arg1,arg2,(double const *)arg3,arg4,(double const *)arg5,arg6,arg7,arg8,arg9,arg10);\n  {\n    /* \n    \tassert(result >= 0);  assertion removed as PyGSL_error_flag can deal with\n    \tnegative numbers.\n         */\n    if(GSL_FAILURE == PyGSL_ERROR_FLAG(result)){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 74); \n      goto fail;\n    }\n    Py_INCREF(Py_None);\n    resultobj = Py_None;\n  }\n  {\n    Py_XDECREF(_PyVector1);\n  }\n  {\n    Py_XDECREF(_PyVector3);\n  }\n  {\n    Py_XDECREF(_PyVector5);\n  }\n  if (SWIG_IsTmpObj(res8)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg8)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res8) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg8), SWIGTYPE_p_double, new_flags));\n  }\n  if (SWIG_IsTmpObj(res9)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg9)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res9) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg9), SWIGTYPE_p_double, new_flags));\n  }\n  if (SWIG_IsTmpObj(res10)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg10)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res10) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg10), SWIGTYPE_p_double, new_flags));\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_fit_mul_est(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  double arg1 ;\n  double arg2 ;\n  double arg3 ;\n  double *arg4 = (double *) 0 ;\n  double *arg5 = (double *) 0 ;\n  double val1 ;\n  int ecode1 = 0 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  double val3 ;\n  int ecode3 = 0 ;\n  double temp4 ;\n  int res4 = SWIG_TMPOBJ ;\n  double temp5 ;\n  int res5 = SWIG_TMPOBJ ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"x\",(char *) \"c1\",(char *) \"c11\", NULL \n  };\n  gsl_error_flag_drop result;\n  \n  arg4 = &temp4;\n  arg5 = &temp5;\n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_fit_mul_est\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  ecode1 = SWIG_AsVal_double(obj0, &val1);\n  if (!SWIG_IsOK(ecode1)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode1), \"in method '\" \"gsl_fit_mul_est\" \"', argument \" \"1\"\" of type '\" \"double\"\"'\");\n  } \n  arg1 = (double)(val1);\n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_fit_mul_est\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  ecode3 = SWIG_AsVal_double(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_fit_mul_est\" \"', argument \" \"3\"\" of type '\" \"double\"\"'\");\n  } \n  arg3 = (double)(val3);\n  result = gsl_fit_mul_est(arg1,arg2,arg3,arg4,arg5);\n  {\n    /* \n    \tassert(result >= 0);  assertion removed as PyGSL_error_flag can deal with\n    \tnegative numbers.\n         */\n    if(GSL_FAILURE == PyGSL_ERROR_FLAG(result)){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 74); \n      goto fail;\n    }\n    Py_INCREF(Py_None);\n    resultobj = Py_None;\n  }\n  if (SWIG_IsTmpObj(res4)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg4)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res4) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg4), SWIGTYPE_p_double, new_flags));\n  }\n  if (SWIG_IsTmpObj(res5)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg5)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res5) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg5), SWIGTYPE_p_double, new_flags));\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nstatic PyMethodDef SwigMethods[] = {\n\t { (char *)\"gsl_function_init\", (PyCFunction) _wrap_gsl_function_init, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_function_init_fdf\", (PyCFunction) _wrap_gsl_function_init_fdf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_function_free\", (PyCFunction) _wrap_gsl_function_free, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_function_free_fdf\", (PyCFunction) _wrap_gsl_function_free_fdf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_monte_function_init\", (PyCFunction) _wrap_gsl_monte_function_init, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_monte_function_free\", (PyCFunction) _wrap_gsl_monte_function_free, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_monte_plain_integrate\", (PyCFunction) _wrap_gsl_monte_plain_integrate, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_monte_plain_alloc\", (PyCFunction) _wrap_gsl_monte_plain_alloc, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_monte_plain_init\", (PyCFunction) _wrap_gsl_monte_plain_init, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_monte_plain_free\", (PyCFunction) _wrap_gsl_monte_plain_free, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"pygsl_monte_miser_get_min_calls\", (PyCFunction) _wrap_pygsl_monte_miser_get_min_calls, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"pygsl_monte_miser_get_min_calls_per_bisection\", (PyCFunction) _wrap_pygsl_monte_miser_get_min_calls_per_bisection, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"pygsl_monte_miser_get_dither\", (PyCFunction) _wrap_pygsl_monte_miser_get_dither, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"pygsl_monte_miser_get_estimate_frac\", (PyCFunction) _wrap_pygsl_monte_miser_get_estimate_frac, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"pygsl_monte_miser_get_alpha\", (PyCFunction) _wrap_pygsl_monte_miser_get_alpha, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"pygsl_monte_miser_set_min_calls\", (PyCFunction) _wrap_pygsl_monte_miser_set_min_calls, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"pygsl_monte_miser_set_min_calls_per_bisection\", (PyCFunction) _wrap_pygsl_monte_miser_set_min_calls_per_bisection, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"pygsl_monte_miser_set_dither\", (PyCFunction) _wrap_pygsl_monte_miser_set_dither, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"pygsl_monte_miser_set_estimate_frac\", (PyCFunction) _wrap_pygsl_monte_miser_set_estimate_frac, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"pygsl_monte_miser_set_alpha\", (PyCFunction) _wrap_pygsl_monte_miser_set_alpha, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_monte_miser_integrate\", (PyCFunction) _wrap_gsl_monte_miser_integrate, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_monte_miser_alloc\", (PyCFunction) _wrap_gsl_monte_miser_alloc, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_monte_miser_init\", (PyCFunction) _wrap_gsl_monte_miser_init, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_monte_miser_free\", (PyCFunction) _wrap_gsl_monte_miser_free, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"pygsl_monte_vegas_get_result\", (PyCFunction) _wrap_pygsl_monte_vegas_get_result, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"pygsl_monte_vegas_get_sigma\", (PyCFunction) _wrap_pygsl_monte_vegas_get_sigma, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"pygsl_monte_vegas_get_chisq\", (PyCFunction) _wrap_pygsl_monte_vegas_get_chisq, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"pygsl_monte_vegas_get_alpha\", (PyCFunction) _wrap_pygsl_monte_vegas_get_alpha, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"pygsl_monte_vegas_get_iterations\", (PyCFunction) _wrap_pygsl_monte_vegas_get_iterations, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"pygsl_monte_vegas_get_stage\", (PyCFunction) _wrap_pygsl_monte_vegas_get_stage, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"pygsl_monte_vegas_get_mode\", (PyCFunction) _wrap_pygsl_monte_vegas_get_mode, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"pygsl_monte_vegas_get_verbose\", (PyCFunction) _wrap_pygsl_monte_vegas_get_verbose, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"pygsl_monte_vegas_get_ostream\", (PyCFunction) _wrap_pygsl_monte_vegas_get_ostream, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"pygsl_monte_vegas_set_result\", (PyCFunction) _wrap_pygsl_monte_vegas_set_result, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"pygsl_monte_vegas_set_sigma\", (PyCFunction) _wrap_pygsl_monte_vegas_set_sigma, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"pygsl_monte_vegas_set_chisq\", (PyCFunction) _wrap_pygsl_monte_vegas_set_chisq, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"pygsl_monte_vegas_set_alpha\", (PyCFunction) _wrap_pygsl_monte_vegas_set_alpha, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"pygsl_monte_vegas_set_iterations\", (PyCFunction) _wrap_pygsl_monte_vegas_set_iterations, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"pygsl_monte_vegas_set_stage\", (PyCFunction) _wrap_pygsl_monte_vegas_set_stage, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"pygsl_monte_vegas_set_mode\", (PyCFunction) _wrap_pygsl_monte_vegas_set_mode, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"pygsl_monte_vegas_set_verbose\", (PyCFunction) _wrap_pygsl_monte_vegas_set_verbose, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"pygsl_monte_vegas_set_ostream\", (PyCFunction) _wrap_pygsl_monte_vegas_set_ostream, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_monte_vegas_integrate\", (PyCFunction) _wrap_gsl_monte_vegas_integrate, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_monte_vegas_alloc\", (PyCFunction) _wrap_gsl_monte_vegas_alloc, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_monte_vegas_init\", (PyCFunction) _wrap_gsl_monte_vegas_init, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_monte_vegas_free\", (PyCFunction) _wrap_gsl_monte_vegas_free, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_root_fsolver_alloc\", (PyCFunction) _wrap_gsl_root_fsolver_alloc, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_root_fsolver_free\", (PyCFunction) _wrap_gsl_root_fsolver_free, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_root_fdfsolver_alloc\", (PyCFunction) _wrap_gsl_root_fdfsolver_alloc, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_root_fdfsolver_free\", (PyCFunction) _wrap_gsl_root_fdfsolver_free, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_root_fsolver_set\", (PyCFunction) _wrap_gsl_root_fsolver_set, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_root_fdfsolver_set\", (PyCFunction) _wrap_gsl_root_fdfsolver_set, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_root_fsolver_name\", (PyCFunction) _wrap_gsl_root_fsolver_name, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_root_fdfsolver_name\", (PyCFunction) _wrap_gsl_root_fdfsolver_name, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_root_fsolver_iterate\", (PyCFunction) _wrap_gsl_root_fsolver_iterate, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_root_fdfsolver_iterate\", (PyCFunction) _wrap_gsl_root_fdfsolver_iterate, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_root_fsolver_root\", (PyCFunction) _wrap_gsl_root_fsolver_root, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_root_fdfsolver_root\", (PyCFunction) _wrap_gsl_root_fdfsolver_root, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_root_fsolver_x_lower\", (PyCFunction) _wrap_gsl_root_fsolver_x_lower, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_root_fsolver_x_upper\", (PyCFunction) _wrap_gsl_root_fsolver_x_upper, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_root_test_interval\", (PyCFunction) _wrap_gsl_root_test_interval, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_root_test_delta\", (PyCFunction) _wrap_gsl_root_test_delta, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_root_test_residual\", (PyCFunction) _wrap_gsl_root_test_residual, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_min_fminimizer_alloc\", (PyCFunction) _wrap_gsl_min_fminimizer_alloc, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_min_fminimizer_set\", (PyCFunction) _wrap_gsl_min_fminimizer_set, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_min_fminimizer_set_with_values\", (PyCFunction) _wrap_gsl_min_fminimizer_set_with_values, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_min_fminimizer_free\", (PyCFunction) _wrap_gsl_min_fminimizer_free, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_min_fminimizer_name\", (PyCFunction) _wrap_gsl_min_fminimizer_name, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_min_fminimizer_iterate\", (PyCFunction) _wrap_gsl_min_fminimizer_iterate, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_min_fminimizer_minimum\", (PyCFunction) _wrap_gsl_min_fminimizer_minimum, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_min_fminimizer_x_upper\", (PyCFunction) _wrap_gsl_min_fminimizer_x_upper, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_min_fminimizer_x_lower\", (PyCFunction) _wrap_gsl_min_fminimizer_x_lower, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_min_test_interval\", (PyCFunction) _wrap_gsl_min_test_interval, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multiroot_function_init\", (PyCFunction) _wrap_gsl_multiroot_function_init, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multiroot_function_init_fdf\", (PyCFunction) _wrap_gsl_multiroot_function_init_fdf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multiroot_function_getf\", (PyCFunction) _wrap_gsl_multiroot_function_getf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multiroot_function_fdf_getf\", (PyCFunction) _wrap_gsl_multiroot_function_fdf_getf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multiroot_function_getx\", (PyCFunction) _wrap_gsl_multiroot_function_getx, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multiroot_function_fdf_getx\", (PyCFunction) _wrap_gsl_multiroot_function_fdf_getx, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multiroot_function_free\", (PyCFunction) _wrap_gsl_multiroot_function_free, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multiroot_function_free_fdf\", (PyCFunction) _wrap_gsl_multiroot_function_free_fdf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multiroot_fsolver_alloc\", (PyCFunction) _wrap_gsl_multiroot_fsolver_alloc, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multiroot_fsolver_free\", (PyCFunction) _wrap_gsl_multiroot_fsolver_free, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multiroot_fsolver_set\", (PyCFunction) _wrap_gsl_multiroot_fsolver_set, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multiroot_fsolver_iterate\", (PyCFunction) _wrap_gsl_multiroot_fsolver_iterate, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multiroot_fsolver_name\", (PyCFunction) _wrap_gsl_multiroot_fsolver_name, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multiroot_fsolver_root\", (PyCFunction) _wrap_gsl_multiroot_fsolver_root, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multiroot_fdfsolver_alloc\", (PyCFunction) _wrap_gsl_multiroot_fdfsolver_alloc, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multiroot_fdfsolver_set\", (PyCFunction) _wrap_gsl_multiroot_fdfsolver_set, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multiroot_fdfsolver_iterate\", (PyCFunction) _wrap_gsl_multiroot_fdfsolver_iterate, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multiroot_fdfsolver_free\", (PyCFunction) _wrap_gsl_multiroot_fdfsolver_free, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multiroot_fdfsolver_name\", (PyCFunction) _wrap_gsl_multiroot_fdfsolver_name, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multiroot_fdfsolver_root\", (PyCFunction) _wrap_gsl_multiroot_fdfsolver_root, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multiroot_test_delta\", (PyCFunction) _wrap_gsl_multiroot_test_delta, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multiroot_test_residual\", (PyCFunction) _wrap_gsl_multiroot_test_residual, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multimin_function_init\", (PyCFunction) _wrap_gsl_multimin_function_init, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multimin_function_init_fdf\", (PyCFunction) _wrap_gsl_multimin_function_init_fdf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multimin_function_free\", (PyCFunction) _wrap_gsl_multimin_function_free, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multimin_function_free_fdf\", (PyCFunction) _wrap_gsl_multimin_function_free_fdf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multimin_fminimizer_f\", (PyCFunction) _wrap_gsl_multimin_fminimizer_f, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multimin_fminimizer_alloc\", (PyCFunction) _wrap_gsl_multimin_fminimizer_alloc, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multimin_fminimizer_set\", (PyCFunction) _wrap_gsl_multimin_fminimizer_set, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multimin_fminimizer_free\", (PyCFunction) _wrap_gsl_multimin_fminimizer_free, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multimin_fminimizer_name\", (PyCFunction) _wrap_gsl_multimin_fminimizer_name, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multimin_fminimizer_iterate\", (PyCFunction) _wrap_gsl_multimin_fminimizer_iterate, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multimin_fminimizer_x\", (PyCFunction) _wrap_gsl_multimin_fminimizer_x, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multimin_fminimizer_minimum\", (PyCFunction) _wrap_gsl_multimin_fminimizer_minimum, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multimin_fminimizer_size\", (PyCFunction) _wrap_gsl_multimin_fminimizer_size, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multimin_fdfminimizer_alloc\", (PyCFunction) _wrap_gsl_multimin_fdfminimizer_alloc, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multimin_fdfminimizer_set\", (PyCFunction) _wrap_gsl_multimin_fdfminimizer_set, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multimin_fdfminimizer_free\", (PyCFunction) _wrap_gsl_multimin_fdfminimizer_free, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multimin_fdfminimizer_name\", (PyCFunction) _wrap_gsl_multimin_fdfminimizer_name, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multimin_fdfminimizer_iterate\", (PyCFunction) _wrap_gsl_multimin_fdfminimizer_iterate, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multimin_fdfminimizer_restart\", (PyCFunction) _wrap_gsl_multimin_fdfminimizer_restart, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multimin_test_gradient\", (PyCFunction) _wrap_gsl_multimin_test_gradient, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multimin_test_size\", (PyCFunction) _wrap_gsl_multimin_test_size, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multimin_fdfminimizer_f\", (PyCFunction) _wrap_gsl_multimin_fdfminimizer_f, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multimin_fdfminimizer_x\", (PyCFunction) _wrap_gsl_multimin_fdfminimizer_x, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multimin_fdfminimizer_dx\", (PyCFunction) _wrap_gsl_multimin_fdfminimizer_dx, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multimin_fdfminimizer_gradient\", (PyCFunction) _wrap_gsl_multimin_fdfminimizer_gradient, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multimin_fdfminimizer_minimum\", (PyCFunction) _wrap_gsl_multimin_fdfminimizer_minimum, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multifit_function_init\", (PyCFunction) _wrap_gsl_multifit_function_init, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multifit_function_init_fdf\", (PyCFunction) _wrap_gsl_multifit_function_init_fdf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multifit_fsolver_getdx\", (PyCFunction) _wrap_gsl_multifit_fsolver_getdx, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multifit_fsolver_getx\", (PyCFunction) _wrap_gsl_multifit_fsolver_getx, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multifit_fsolver_getf\", (PyCFunction) _wrap_gsl_multifit_fsolver_getf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multifit_fdfsolver_getdx\", (PyCFunction) _wrap_gsl_multifit_fdfsolver_getdx, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multifit_fdfsolver_getx\", (PyCFunction) _wrap_gsl_multifit_fdfsolver_getx, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multifit_fdfsolver_getf\", (PyCFunction) _wrap_gsl_multifit_fdfsolver_getf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multifit_fdfsolver_getJ\", (PyCFunction) _wrap_gsl_multifit_fdfsolver_getJ, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multifit_function_free\", (PyCFunction) _wrap_gsl_multifit_function_free, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multifit_function_free_fdf\", (PyCFunction) _wrap_gsl_multifit_function_free_fdf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multifit_gradient\", PyGSL_gsl_multifit_gradient, METH_VARARGS, NULL},\n\t { (char *)\"gsl_multifit_covar\", PyGSL_gsl_multifit_covar, METH_VARARGS, NULL},\n\t { (char *)\"gsl_multifit_fsolver_alloc\", (PyCFunction) _wrap_gsl_multifit_fsolver_alloc, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multifit_fsolver_free\", (PyCFunction) _wrap_gsl_multifit_fsolver_free, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multifit_fsolver_set\", (PyCFunction) _wrap_gsl_multifit_fsolver_set, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multifit_fsolver_iterate\", (PyCFunction) _wrap_gsl_multifit_fsolver_iterate, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multifit_fsolver_name\", (PyCFunction) _wrap_gsl_multifit_fsolver_name, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multifit_fsolver_position\", (PyCFunction) _wrap_gsl_multifit_fsolver_position, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multifit_fdfsolver_alloc\", (PyCFunction) _wrap_gsl_multifit_fdfsolver_alloc, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multifit_fdfsolver_set\", (PyCFunction) _wrap_gsl_multifit_fdfsolver_set, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multifit_fdfsolver_iterate\", (PyCFunction) _wrap_gsl_multifit_fdfsolver_iterate, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multifit_fdfsolver_free\", (PyCFunction) _wrap_gsl_multifit_fdfsolver_free, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multifit_fdfsolver_name\", (PyCFunction) _wrap_gsl_multifit_fdfsolver_name, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multifit_fdfsolver_position\", (PyCFunction) _wrap_gsl_multifit_fdfsolver_position, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multifit_test_delta\", (PyCFunction) _wrap_gsl_multifit_test_delta, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multifit_test_gradient\", (PyCFunction) _wrap_gsl_multifit_test_gradient, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_integration_workspace_alloc\", (PyCFunction) _wrap_gsl_integration_workspace_alloc, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_integration_workspace_free\", (PyCFunction) _wrap_gsl_integration_workspace_free, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_integration_workspace_get_size\", (PyCFunction) _wrap_gsl_integration_workspace_get_size, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_integration_qaws_table_alloc\", (PyCFunction) _wrap_gsl_integration_qaws_table_alloc, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_integration_qaws_table_set\", (PyCFunction) _wrap_gsl_integration_qaws_table_set, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_integration_qaws_table_free\", (PyCFunction) _wrap_gsl_integration_qaws_table_free, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_integration_qawo_table_alloc\", (PyCFunction) _wrap_gsl_integration_qawo_table_alloc, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_integration_qawo_table_set\", (PyCFunction) _wrap_gsl_integration_qawo_table_set, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_integration_qawo_table_set_length\", (PyCFunction) _wrap_gsl_integration_qawo_table_set_length, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_integration_qawo_table_free\", (PyCFunction) _wrap_gsl_integration_qawo_table_free, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_integration_qng\", (PyCFunction) _wrap_gsl_integration_qng, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_integration_qag\", (PyCFunction) _wrap_gsl_integration_qag, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_integration_qagi\", (PyCFunction) _wrap_gsl_integration_qagi, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_integration_qagiu\", (PyCFunction) _wrap_gsl_integration_qagiu, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_integration_qagil\", (PyCFunction) _wrap_gsl_integration_qagil, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_integration_qags\", (PyCFunction) _wrap_gsl_integration_qags, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_integration_qagp\", (PyCFunction) _wrap_gsl_integration_qagp, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_integration_qawc\", (PyCFunction) _wrap_gsl_integration_qawc, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_integration_qaws\", (PyCFunction) _wrap_gsl_integration_qaws, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_integration_qawo\", (PyCFunction) _wrap_gsl_integration_qawo, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_integration_qawf\", (PyCFunction) _wrap_gsl_integration_qawf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_cheb_alloc\", (PyCFunction) _wrap_gsl_cheb_alloc, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_cheb_free\", (PyCFunction) _wrap_gsl_cheb_free, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_cheb_init\", (PyCFunction) _wrap_gsl_cheb_init, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_cheb_eval\", (PyCFunction) _wrap_gsl_cheb_eval, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_cheb_eval_err\", (PyCFunction) _wrap_gsl_cheb_eval_err, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_cheb_eval_n\", (PyCFunction) _wrap_gsl_cheb_eval_n, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_cheb_eval_n_err\", (PyCFunction) _wrap_gsl_cheb_eval_n_err, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_cheb_calc_deriv\", (PyCFunction) _wrap_gsl_cheb_calc_deriv, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_cheb_calc_integ\", (PyCFunction) _wrap_gsl_cheb_calc_integ, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"pygsl_cheb_get_coefficients\", (PyCFunction) _wrap_pygsl_cheb_get_coefficients, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"pygsl_cheb_set_coefficients\", (PyCFunction) _wrap_pygsl_cheb_set_coefficients, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"pygsl_cheb_get_a\", (PyCFunction) _wrap_pygsl_cheb_get_a, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"pygsl_cheb_get_b\", (PyCFunction) _wrap_pygsl_cheb_get_b, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"pygsl_cheb_set_a\", (PyCFunction) _wrap_pygsl_cheb_set_a, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"pygsl_cheb_set_b\", (PyCFunction) _wrap_pygsl_cheb_set_b, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"pygsl_cheb_get_order_sp\", (PyCFunction) _wrap_pygsl_cheb_get_order_sp, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"pygsl_cheb_set_order_sp\", (PyCFunction) _wrap_pygsl_cheb_set_order_sp, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"pygsl_cheb_get_f\", (PyCFunction) _wrap_pygsl_cheb_get_f, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"pygsl_cheb_set_f\", (PyCFunction) _wrap_pygsl_cheb_set_f, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_odeiv_step_alloc\", (PyCFunction) _wrap_gsl_odeiv_step_alloc, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_odeiv_step_reset\", (PyCFunction) _wrap_gsl_odeiv_step_reset, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_odeiv_step_free\", (PyCFunction) _wrap_gsl_odeiv_step_free, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_odeiv_step_name\", (PyCFunction) _wrap_gsl_odeiv_step_name, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_odeiv_step_order\", (PyCFunction) _wrap_gsl_odeiv_step_order, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_odeiv_step_apply\", pygsl_odeiv_step_apply, METH_VARARGS, NULL},\n\t { (char *)\"gsl_odeiv_control_alloc\", (PyCFunction) _wrap_gsl_odeiv_control_alloc, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_odeiv_control_init\", (PyCFunction) _wrap_gsl_odeiv_control_init, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_odeiv_control_free\", (PyCFunction) _wrap_gsl_odeiv_control_free, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_odeiv_control_hadjust\", pygsl_odeiv_control_hadjust, METH_VARARGS, NULL},\n\t { (char *)\"gsl_odeiv_control_name\", (PyCFunction) _wrap_gsl_odeiv_control_name, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_odeiv_control_standard_new\", (PyCFunction) _wrap_gsl_odeiv_control_standard_new, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_odeiv_control_y_new\", (PyCFunction) _wrap_gsl_odeiv_control_y_new, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_odeiv_control_yp_new\", (PyCFunction) _wrap_gsl_odeiv_control_yp_new, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_odeiv_evolve_alloc\", (PyCFunction) _wrap_gsl_odeiv_evolve_alloc, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_odeiv_evolve_reset\", (PyCFunction) _wrap_gsl_odeiv_evolve_reset, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_odeiv_evolve_free\", (PyCFunction) _wrap_gsl_odeiv_evolve_free, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_odeiv_evolve_apply\", pygsl_odeiv_evolve_apply, METH_VARARGS, NULL},\n\t { (char *)\"gsl_odeiv_evolve_apply_vector\", pygsl_odeiv_evolve_apply_vector, METH_VARARGS, NULL},\n\t { (char *)\"gsl_multifit_linear_alloc\", (PyCFunction) _wrap_gsl_multifit_linear_alloc, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multifit_linear_free\", (PyCFunction) _wrap_gsl_multifit_linear_free, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multifit_linear\", (PyCFunction) _wrap_gsl_multifit_linear, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multifit_linear_svd\", (PyCFunction) _wrap_gsl_multifit_linear_svd, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multifit_wlinear\", (PyCFunction) _wrap_gsl_multifit_wlinear, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multifit_wlinear_svd\", (PyCFunction) _wrap_gsl_multifit_wlinear_svd, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multifit_linear_est\", (PyCFunction) _wrap_gsl_multifit_linear_est, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_multifit_linear_est_matrix\", (PyCFunction) _wrap_gsl_multifit_linear_est_matrix, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_fit_linear\", (PyCFunction) _wrap_gsl_fit_linear, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_fit_wlinear\", (PyCFunction) _wrap_gsl_fit_wlinear, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_fit_linear_est\", (PyCFunction) _wrap_gsl_fit_linear_est, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_fit_mul\", (PyCFunction) _wrap_gsl_fit_mul, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_fit_wmul\", (PyCFunction) _wrap_gsl_fit_wmul, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_fit_mul_est\", (PyCFunction) _wrap_gsl_fit_mul_est, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { NULL, NULL, 0, NULL }\n};\n\n\n/* -------- TYPE CONVERSION AND EQUIVALENCE RULES (BEGIN) -------- */\n\nstatic swig_type_info _swigt__p_FILE = {\"_p_FILE\", \"FILE *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_char = {\"_p_char\", \"char *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_double = {\"_p_double\", \"double *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_cheb_series = {\"_p_gsl_cheb_series\", \"gsl_cheb_series *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_function = {\"_p_gsl_function\", \"gsl_function *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_function_fdf = {\"_p_gsl_function_fdf\", \"gsl_function_fdf *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_integration_qawo_table = {\"_p_gsl_integration_qawo_table\", \"gsl_integration_qawo_table *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_integration_qaws_table = {\"_p_gsl_integration_qaws_table\", \"gsl_integration_qaws_table *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_integration_workspace = {\"_p_gsl_integration_workspace\", \"gsl_integration_workspace *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_matrix = {\"_p_gsl_matrix\", \"gsl_matrix *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_min_fminimizer = {\"_p_gsl_min_fminimizer\", \"gsl_min_fminimizer *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_min_fminimizer_type = {\"_p_gsl_min_fminimizer_type\", \"gsl_min_fminimizer_type *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_monte_function = {\"_p_gsl_monte_function\", \"gsl_monte_function *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_monte_miser_state = {\"_p_gsl_monte_miser_state\", \"gsl_monte_miser_state *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_monte_plain_state = {\"_p_gsl_monte_plain_state\", \"gsl_monte_plain_state *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_monte_vegas_state = {\"_p_gsl_monte_vegas_state\", \"gsl_monte_vegas_state *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_multifit_fdfsolver = {\"_p_gsl_multifit_fdfsolver\", \"gsl_multifit_fdfsolver *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_multifit_fdfsolver_type = {\"_p_gsl_multifit_fdfsolver_type\", \"gsl_multifit_fdfsolver_type *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_multifit_fsolver = {\"_p_gsl_multifit_fsolver\", \"gsl_multifit_fsolver *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_multifit_fsolver_type = {\"_p_gsl_multifit_fsolver_type\", \"gsl_multifit_fsolver_type *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_multifit_function = {\"_p_gsl_multifit_function\", \"gsl_multifit_function *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_multifit_function_fdf = {\"_p_gsl_multifit_function_fdf\", \"gsl_multifit_function_fdf *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_multifit_linear_workspace = {\"_p_gsl_multifit_linear_workspace\", \"gsl_multifit_linear_workspace *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_multimin_fdfminimizer = {\"_p_gsl_multimin_fdfminimizer\", \"gsl_multimin_fdfminimizer *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_multimin_fdfminimizer_type = {\"_p_gsl_multimin_fdfminimizer_type\", \"gsl_multimin_fdfminimizer_type *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_multimin_fminimizer = {\"_p_gsl_multimin_fminimizer\", \"gsl_multimin_fminimizer *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_multimin_fminimizer_type = {\"_p_gsl_multimin_fminimizer_type\", \"gsl_multimin_fminimizer_type *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_multimin_function = {\"_p_gsl_multimin_function\", \"gsl_multimin_function *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_multimin_function_fdf = {\"_p_gsl_multimin_function_fdf\", \"gsl_multimin_function_fdf *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_multiroot_fdfsolver = {\"_p_gsl_multiroot_fdfsolver\", \"gsl_multiroot_fdfsolver *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_multiroot_fdfsolver_type = {\"_p_gsl_multiroot_fdfsolver_type\", \"gsl_multiroot_fdfsolver_type *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_multiroot_fsolver = {\"_p_gsl_multiroot_fsolver\", \"gsl_multiroot_fsolver *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_multiroot_fsolver_type = {\"_p_gsl_multiroot_fsolver_type\", \"gsl_multiroot_fsolver_type *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_multiroot_function = {\"_p_gsl_multiroot_function\", \"gsl_multiroot_function *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_multiroot_function_fdf = {\"_p_gsl_multiroot_function_fdf\", \"gsl_multiroot_function_fdf *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_odeiv_control = {\"_p_gsl_odeiv_control\", \"gsl_odeiv_control *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_odeiv_control_type = {\"_p_gsl_odeiv_control_type\", \"gsl_odeiv_control_type *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_odeiv_evolve = {\"_p_gsl_odeiv_evolve\", \"gsl_odeiv_evolve *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_odeiv_step = {\"_p_gsl_odeiv_step\", \"gsl_odeiv_step *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_odeiv_step_type = {\"_p_gsl_odeiv_step_type\", \"gsl_odeiv_step_type *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_rng = {\"_p_gsl_rng\", \"gsl_rng *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_root_fdfsolver = {\"_p_gsl_root_fdfsolver\", \"gsl_root_fdfsolver *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_root_fdfsolver_type = {\"_p_gsl_root_fdfsolver_type\", \"gsl_root_fdfsolver_type *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_root_fsolver = {\"_p_gsl_root_fsolver\", \"gsl_root_fsolver *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_root_fsolver_type = {\"_p_gsl_root_fsolver_type\", \"gsl_root_fsolver_type *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_vector = {\"_p_gsl_vector\", \"gsl_multiroot_solver_data *|gsl_vector *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_unsigned_int = {\"_p_unsigned_int\", \"size_t *|unsigned int *|gsl_mode_t *\", 0, 0, (void*)0, 0};\n\nstatic swig_type_info *swig_type_initial[] = {\n  &_swigt__p_FILE,\n  &_swigt__p_char,\n  &_swigt__p_double,\n  &_swigt__p_gsl_cheb_series,\n  &_swigt__p_gsl_function,\n  &_swigt__p_gsl_function_fdf,\n  &_swigt__p_gsl_integration_qawo_table,\n  &_swigt__p_gsl_integration_qaws_table,\n  &_swigt__p_gsl_integration_workspace,\n  &_swigt__p_gsl_matrix,\n  &_swigt__p_gsl_min_fminimizer,\n  &_swigt__p_gsl_min_fminimizer_type,\n  &_swigt__p_gsl_monte_function,\n  &_swigt__p_gsl_monte_miser_state,\n  &_swigt__p_gsl_monte_plain_state,\n  &_swigt__p_gsl_monte_vegas_state,\n  &_swigt__p_gsl_multifit_fdfsolver,\n  &_swigt__p_gsl_multifit_fdfsolver_type,\n  &_swigt__p_gsl_multifit_fsolver,\n  &_swigt__p_gsl_multifit_fsolver_type,\n  &_swigt__p_gsl_multifit_function,\n  &_swigt__p_gsl_multifit_function_fdf,\n  &_swigt__p_gsl_multifit_linear_workspace,\n  &_swigt__p_gsl_multimin_fdfminimizer,\n  &_swigt__p_gsl_multimin_fdfminimizer_type,\n  &_swigt__p_gsl_multimin_fminimizer,\n  &_swigt__p_gsl_multimin_fminimizer_type,\n  &_swigt__p_gsl_multimin_function,\n  &_swigt__p_gsl_multimin_function_fdf,\n  &_swigt__p_gsl_multiroot_fdfsolver,\n  &_swigt__p_gsl_multiroot_fdfsolver_type,\n  &_swigt__p_gsl_multiroot_fsolver,\n  &_swigt__p_gsl_multiroot_fsolver_type,\n  &_swigt__p_gsl_multiroot_function,\n  &_swigt__p_gsl_multiroot_function_fdf,\n  &_swigt__p_gsl_odeiv_control,\n  &_swigt__p_gsl_odeiv_control_type,\n  &_swigt__p_gsl_odeiv_evolve,\n  &_swigt__p_gsl_odeiv_step,\n  &_swigt__p_gsl_odeiv_step_type,\n  &_swigt__p_gsl_rng,\n  &_swigt__p_gsl_root_fdfsolver,\n  &_swigt__p_gsl_root_fdfsolver_type,\n  &_swigt__p_gsl_root_fsolver,\n  &_swigt__p_gsl_root_fsolver_type,\n  &_swigt__p_gsl_vector,\n  &_swigt__p_unsigned_int,\n};\n\nstatic swig_cast_info _swigc__p_FILE[] = {  {&_swigt__p_FILE, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_char[] = {  {&_swigt__p_char, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_double[] = {  {&_swigt__p_double, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_cheb_series[] = {  {&_swigt__p_gsl_cheb_series, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_function[] = {  {&_swigt__p_gsl_function, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_function_fdf[] = {  {&_swigt__p_gsl_function_fdf, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_integration_qawo_table[] = {  {&_swigt__p_gsl_integration_qawo_table, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_integration_qaws_table[] = {  {&_swigt__p_gsl_integration_qaws_table, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_integration_workspace[] = {  {&_swigt__p_gsl_integration_workspace, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_matrix[] = {  {&_swigt__p_gsl_matrix, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_min_fminimizer[] = {  {&_swigt__p_gsl_min_fminimizer, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_min_fminimizer_type[] = {  {&_swigt__p_gsl_min_fminimizer_type, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_monte_function[] = {  {&_swigt__p_gsl_monte_function, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_monte_miser_state[] = {  {&_swigt__p_gsl_monte_miser_state, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_monte_plain_state[] = {  {&_swigt__p_gsl_monte_plain_state, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_monte_vegas_state[] = {  {&_swigt__p_gsl_monte_vegas_state, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_multifit_fdfsolver[] = {  {&_swigt__p_gsl_multifit_fdfsolver, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_multifit_fdfsolver_type[] = {  {&_swigt__p_gsl_multifit_fdfsolver_type, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_multifit_fsolver[] = {  {&_swigt__p_gsl_multifit_fsolver, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_multifit_fsolver_type[] = {  {&_swigt__p_gsl_multifit_fsolver_type, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_multifit_function[] = {  {&_swigt__p_gsl_multifit_function, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_multifit_function_fdf[] = {  {&_swigt__p_gsl_multifit_function_fdf, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_multifit_linear_workspace[] = {  {&_swigt__p_gsl_multifit_linear_workspace, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_multimin_fdfminimizer[] = {  {&_swigt__p_gsl_multimin_fdfminimizer, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_multimin_fdfminimizer_type[] = {  {&_swigt__p_gsl_multimin_fdfminimizer_type, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_multimin_fminimizer[] = {  {&_swigt__p_gsl_multimin_fminimizer, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_multimin_fminimizer_type[] = {  {&_swigt__p_gsl_multimin_fminimizer_type, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_multimin_function[] = {  {&_swigt__p_gsl_multimin_function, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_multimin_function_fdf[] = {  {&_swigt__p_gsl_multimin_function_fdf, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_multiroot_fdfsolver[] = {  {&_swigt__p_gsl_multiroot_fdfsolver, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_multiroot_fdfsolver_type[] = {  {&_swigt__p_gsl_multiroot_fdfsolver_type, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_multiroot_fsolver[] = {  {&_swigt__p_gsl_multiroot_fsolver, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_multiroot_fsolver_type[] = {  {&_swigt__p_gsl_multiroot_fsolver_type, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_multiroot_function[] = {  {&_swigt__p_gsl_multiroot_function, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_multiroot_function_fdf[] = {  {&_swigt__p_gsl_multiroot_function_fdf, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_odeiv_control[] = {  {&_swigt__p_gsl_odeiv_control, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_odeiv_control_type[] = {  {&_swigt__p_gsl_odeiv_control_type, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_odeiv_evolve[] = {  {&_swigt__p_gsl_odeiv_evolve, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_odeiv_step[] = {  {&_swigt__p_gsl_odeiv_step, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_odeiv_step_type[] = {  {&_swigt__p_gsl_odeiv_step_type, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_rng[] = {  {&_swigt__p_gsl_rng, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_root_fdfsolver[] = {  {&_swigt__p_gsl_root_fdfsolver, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_root_fdfsolver_type[] = {  {&_swigt__p_gsl_root_fdfsolver_type, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_root_fsolver[] = {  {&_swigt__p_gsl_root_fsolver, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_root_fsolver_type[] = {  {&_swigt__p_gsl_root_fsolver_type, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_vector[] = {  {&_swigt__p_gsl_vector, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_unsigned_int[] = {  {&_swigt__p_unsigned_int, 0, 0, 0},{0, 0, 0, 0}};\n\nstatic swig_cast_info *swig_cast_initial[] = {\n  _swigc__p_FILE,\n  _swigc__p_char,\n  _swigc__p_double,\n  _swigc__p_gsl_cheb_series,\n  _swigc__p_gsl_function,\n  _swigc__p_gsl_function_fdf,\n  _swigc__p_gsl_integration_qawo_table,\n  _swigc__p_gsl_integration_qaws_table,\n  _swigc__p_gsl_integration_workspace,\n  _swigc__p_gsl_matrix,\n  _swigc__p_gsl_min_fminimizer,\n  _swigc__p_gsl_min_fminimizer_type,\n  _swigc__p_gsl_monte_function,\n  _swigc__p_gsl_monte_miser_state,\n  _swigc__p_gsl_monte_plain_state,\n  _swigc__p_gsl_monte_vegas_state,\n  _swigc__p_gsl_multifit_fdfsolver,\n  _swigc__p_gsl_multifit_fdfsolver_type,\n  _swigc__p_gsl_multifit_fsolver,\n  _swigc__p_gsl_multifit_fsolver_type,\n  _swigc__p_gsl_multifit_function,\n  _swigc__p_gsl_multifit_function_fdf,\n  _swigc__p_gsl_multifit_linear_workspace,\n  _swigc__p_gsl_multimin_fdfminimizer,\n  _swigc__p_gsl_multimin_fdfminimizer_type,\n  _swigc__p_gsl_multimin_fminimizer,\n  _swigc__p_gsl_multimin_fminimizer_type,\n  _swigc__p_gsl_multimin_function,\n  _swigc__p_gsl_multimin_function_fdf,\n  _swigc__p_gsl_multiroot_fdfsolver,\n  _swigc__p_gsl_multiroot_fdfsolver_type,\n  _swigc__p_gsl_multiroot_fsolver,\n  _swigc__p_gsl_multiroot_fsolver_type,\n  _swigc__p_gsl_multiroot_function,\n  _swigc__p_gsl_multiroot_function_fdf,\n  _swigc__p_gsl_odeiv_control,\n  _swigc__p_gsl_odeiv_control_type,\n  _swigc__p_gsl_odeiv_evolve,\n  _swigc__p_gsl_odeiv_step,\n  _swigc__p_gsl_odeiv_step_type,\n  _swigc__p_gsl_rng,\n  _swigc__p_gsl_root_fdfsolver,\n  _swigc__p_gsl_root_fdfsolver_type,\n  _swigc__p_gsl_root_fsolver,\n  _swigc__p_gsl_root_fsolver_type,\n  _swigc__p_gsl_vector,\n  _swigc__p_unsigned_int,\n};\n\n\n/* -------- TYPE CONVERSION AND EQUIVALENCE RULES (END) -------- */\n\nstatic swig_const_info swig_const_table[] = {\n{0, 0, 0, 0.0, 0, 0}};\n\n#ifdef __cplusplus\n}\n#endif\n/* -----------------------------------------------------------------------------\n * Type initialization:\n * This problem is tough by the requirement that no dynamic \n * memory is used. Also, since swig_type_info structures store pointers to \n * swig_cast_info structures and swig_cast_info structures store pointers back\n * to swig_type_info structures, we need some lookup code at initialization. \n * The idea is that swig generates all the structures that are needed. \n * The runtime then collects these partially filled structures. \n * The SWIG_InitializeModule function takes these initial arrays out of \n * swig_module, and does all the lookup, filling in the swig_module.types\n * array with the correct data and linking the correct swig_cast_info\n * structures together.\n *\n * The generated swig_type_info structures are assigned staticly to an initial \n * array. We just loop through that array, and handle each type individually.\n * First we lookup if this type has been already loaded, and if so, use the\n * loaded structure instead of the generated one. Then we have to fill in the\n * cast linked list. The cast data is initially stored in something like a\n * two-dimensional array. Each row corresponds to a type (there are the same\n * number of rows as there are in the swig_type_initial array). Each entry in\n * a column is one of the swig_cast_info structures for that type.\n * The cast_initial array is actually an array of arrays, because each row has\n * a variable number of columns. So to actually build the cast linked list,\n * we find the array of casts associated with the type, and loop through it \n * adding the casts to the list. The one last trick we need to do is making\n * sure the type pointer in the swig_cast_info struct is correct.\n *\n * First off, we lookup the cast->type name to see if it is already loaded. \n * There are three cases to handle:\n *  1) If the cast->type has already been loaded AND the type we are adding\n *     casting info to has not been loaded (it is in this module), THEN we\n *     replace the cast->type pointer with the type pointer that has already\n *     been loaded.\n *  2) If BOTH types (the one we are adding casting info to, and the \n *     cast->type) are loaded, THEN the cast info has already been loaded by\n *     the previous module so we just ignore it.\n *  3) Finally, if cast->type has not already been loaded, then we add that\n *     swig_cast_info to the linked list (because the cast->type) pointer will\n *     be correct.\n * ----------------------------------------------------------------------------- */\n\n#ifdef __cplusplus\nextern \"C\" {\n#if 0\n} /* c-mode */\n#endif\n#endif\n\n#if 0\n#define SWIGRUNTIME_DEBUG\n#endif\n\n\nSWIGRUNTIME void\nSWIG_InitializeModule(void *clientdata) {\n  size_t i;\n  swig_module_info *module_head, *iter;\n  int found, init;\n  \n  clientdata = clientdata;\n  \n  /* check to see if the circular list has been setup, if not, set it up */\n  if (swig_module.next==0) {\n    /* Initialize the swig_module */\n    swig_module.type_initial = swig_type_initial;\n    swig_module.cast_initial = swig_cast_initial;\n    swig_module.next = &swig_module;\n    init = 1;\n  } else {\n    init = 0;\n  }\n  \n  /* Try and load any already created modules */\n  module_head = SWIG_GetModule(clientdata);\n  if (!module_head) {\n    /* This is the first module loaded for this interpreter */\n    /* so set the swig module into the interpreter */\n    SWIG_SetModule(clientdata, &swig_module);\n    module_head = &swig_module;\n  } else {\n    /* the interpreter has loaded a SWIG module, but has it loaded this one? */\n    found=0;\n    iter=module_head;\n    do {\n      if (iter==&swig_module) {\n        found=1;\n        break;\n      }\n      iter=iter->next;\n    } while (iter!= module_head);\n    \n    /* if the is found in the list, then all is done and we may leave */\n    if (found) return;\n    /* otherwise we must add out module into the list */\n    swig_module.next = module_head->next;\n    module_head->next = &swig_module;\n  }\n  \n  /* When multiple interpeters are used, a module could have already been initialized in\n       a different interpreter, but not yet have a pointer in this interpreter.\n       In this case, we do not want to continue adding types... everything should be\n       set up already */\n  if (init == 0) return;\n  \n  /* Now work on filling in swig_module.types */\n#ifdef SWIGRUNTIME_DEBUG\n  printf(\"SWIG_InitializeModule: size %d\\n\", swig_module.size);\n#endif\n  for (i = 0; i < swig_module.size; ++i) {\n    swig_type_info *type = 0;\n    swig_type_info *ret;\n    swig_cast_info *cast;\n    \n#ifdef SWIGRUNTIME_DEBUG\n    printf(\"SWIG_InitializeModule: type %d %s\\n\", i, swig_module.type_initial[i]->name);\n#endif\n    \n    /* if there is another module already loaded */\n    if (swig_module.next != &swig_module) {\n      type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name);\n    }\n    if (type) {\n      /* Overwrite clientdata field */\n#ifdef SWIGRUNTIME_DEBUG\n      printf(\"SWIG_InitializeModule: found type %s\\n\", type->name);\n#endif\n      if (swig_module.type_initial[i]->clientdata) {\n        type->clientdata = swig_module.type_initial[i]->clientdata;\n#ifdef SWIGRUNTIME_DEBUG\n        printf(\"SWIG_InitializeModule: found and overwrite type %s \\n\", type->name);\n#endif\n      }\n    } else {\n      type = swig_module.type_initial[i];\n    }\n    \n    /* Insert casting types */\n    cast = swig_module.cast_initial[i];\n    while (cast->type) {\n      /* Don't need to add information already in the list */\n      ret = 0;\n#ifdef SWIGRUNTIME_DEBUG\n      printf(\"SWIG_InitializeModule: look cast %s\\n\", cast->type->name);\n#endif\n      if (swig_module.next != &swig_module) {\n        ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name);\n#ifdef SWIGRUNTIME_DEBUG\n        if (ret) printf(\"SWIG_InitializeModule: found cast %s\\n\", ret->name);\n#endif\n      }\n      if (ret) {\n        if (type == swig_module.type_initial[i]) {\n#ifdef SWIGRUNTIME_DEBUG\n          printf(\"SWIG_InitializeModule: skip old type %s\\n\", ret->name);\n#endif\n          cast->type = ret;\n          ret = 0;\n        } else {\n          /* Check for casting already in the list */\n          swig_cast_info *ocast = SWIG_TypeCheck(ret->name, type);\n#ifdef SWIGRUNTIME_DEBUG\n          if (ocast) printf(\"SWIG_InitializeModule: skip old cast %s\\n\", ret->name);\n#endif\n          if (!ocast) ret = 0;\n        }\n      }\n      \n      if (!ret) {\n#ifdef SWIGRUNTIME_DEBUG\n        printf(\"SWIG_InitializeModule: adding cast %s\\n\", cast->type->name);\n#endif\n        if (type->cast) {\n          type->cast->prev = cast;\n          cast->next = type->cast;\n        }\n        type->cast = cast;\n      }\n      cast++;\n    }\n    /* Set entry in modules->types array equal to the type */\n    swig_module.types[i] = type;\n  }\n  swig_module.types[i] = 0;\n  \n#ifdef SWIGRUNTIME_DEBUG\n  printf(\"**** SWIG_InitializeModule: Cast List ******\\n\");\n  for (i = 0; i < swig_module.size; ++i) {\n    int j = 0;\n    swig_cast_info *cast = swig_module.cast_initial[i];\n    printf(\"SWIG_InitializeModule: type %d %s\\n\", i, swig_module.type_initial[i]->name);\n    while (cast->type) {\n      printf(\"SWIG_InitializeModule: cast type %s\\n\", cast->type->name);\n      cast++;\n      ++j;\n    }\n    printf(\"---- Total casts: %d\\n\",j);\n  }\n  printf(\"**** SWIG_InitializeModule: Cast List ******\\n\");\n#endif\n}\n\n/* This function will propagate the clientdata field of type to\n* any new swig_type_info structures that have been added into the list\n* of equivalent types.  It is like calling\n* SWIG_TypeClientData(type, clientdata) a second time.\n*/\nSWIGRUNTIME void\nSWIG_PropagateClientData(void) {\n  size_t i;\n  swig_cast_info *equiv;\n  static int init_run = 0;\n  \n  if (init_run) return;\n  init_run = 1;\n  \n  for (i = 0; i < swig_module.size; i++) {\n    if (swig_module.types[i]->clientdata) {\n      equiv = swig_module.types[i]->cast;\n      while (equiv) {\n        if (!equiv->converter) {\n          if (equiv->type && !equiv->type->clientdata)\n          SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata);\n        }\n        equiv = equiv->next;\n      }\n    }\n  }\n}\n\n#ifdef __cplusplus\n#if 0\n{\n  /* c-mode */\n#endif\n}\n#endif\n\n\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n  \n  /* Python-specific SWIG API */\n#define SWIG_newvarlink()                             SWIG_Python_newvarlink()\n#define SWIG_addvarlink(p, name, get_attr, set_attr)  SWIG_Python_addvarlink(p, name, get_attr, set_attr)\n#define SWIG_InstallConstants(d, constants)           SWIG_Python_InstallConstants(d, constants)\n  \n  /* -----------------------------------------------------------------------------\n   * global variable support code.\n   * ----------------------------------------------------------------------------- */\n  \n  typedef struct swig_globalvar {\n    char       *name;                  /* Name of global variable */\n    PyObject *(*get_attr)(void);       /* Return the current value */\n    int       (*set_attr)(PyObject *); /* Set the value */\n    struct swig_globalvar *next;\n  } swig_globalvar;\n  \n  typedef struct swig_varlinkobject {\n    PyObject_HEAD\n    swig_globalvar *vars;\n  } swig_varlinkobject;\n  \n  SWIGINTERN PyObject *\n  swig_varlink_repr(swig_varlinkobject *SWIGUNUSEDPARM(v)) {\n    return PyString_FromString(\"<Swig global variables>\");\n  }\n  \n  SWIGINTERN PyObject *\n  swig_varlink_str(swig_varlinkobject *v) {\n    PyObject *str = PyString_FromString(\"(\");\n    swig_globalvar  *var;\n    for (var = v->vars; var; var=var->next) {\n      PyString_ConcatAndDel(&str,PyString_FromString(var->name));\n      if (var->next) PyString_ConcatAndDel(&str,PyString_FromString(\", \"));\n    }\n    PyString_ConcatAndDel(&str,PyString_FromString(\")\"));\n    return str;\n  }\n  \n  SWIGINTERN int\n  swig_varlink_print(swig_varlinkobject *v, FILE *fp, int SWIGUNUSEDPARM(flags)) {\n    PyObject *str = swig_varlink_str(v);\n    fprintf(fp,\"Swig global variables \");\n    fprintf(fp,\"%s\\n\", PyString_AsString(str));\n    Py_DECREF(str);\n    return 0;\n  }\n  \n  SWIGINTERN void\n  swig_varlink_dealloc(swig_varlinkobject *v) {\n    swig_globalvar *var = v->vars;\n    while (var) {\n      swig_globalvar *n = var->next;\n      free(var->name);\n      free(var);\n      var = n;\n    }\n  }\n  \n  SWIGINTERN PyObject *\n  swig_varlink_getattr(swig_varlinkobject *v, char *n) {\n    PyObject *res = NULL;\n    swig_globalvar *var = v->vars;\n    while (var) {\n      if (strcmp(var->name,n) == 0) {\n        res = (*var->get_attr)();\n        break;\n      }\n      var = var->next;\n    }\n    if (res == NULL && !PyErr_Occurred()) {\n      PyErr_SetString(PyExc_NameError,\"Unknown C global variable\");\n    }\n    return res;\n  }\n  \n  SWIGINTERN int\n  swig_varlink_setattr(swig_varlinkobject *v, char *n, PyObject *p) {\n    int res = 1;\n    swig_globalvar *var = v->vars;\n    while (var) {\n      if (strcmp(var->name,n) == 0) {\n        res = (*var->set_attr)(p);\n        break;\n      }\n      var = var->next;\n    }\n    if (res == 1 && !PyErr_Occurred()) {\n      PyErr_SetString(PyExc_NameError,\"Unknown C global variable\");\n    }\n    return res;\n  }\n  \n  SWIGINTERN PyTypeObject*\n  swig_varlink_type(void) {\n    static char varlink__doc__[] = \"Swig var link object\";\n    static PyTypeObject varlink_type;\n    static int type_init = 0;  \n    if (!type_init) {\n      const PyTypeObject tmp\n      = {\n        PyObject_HEAD_INIT(NULL)\n        0,                                  /* Number of items in variable part (ob_size) */\n        (char *)\"swigvarlink\",              /* Type name (tp_name) */\n        sizeof(swig_varlinkobject),         /* Basic size (tp_basicsize) */\n        0,                                  /* Itemsize (tp_itemsize) */\n        (destructor) swig_varlink_dealloc,   /* Deallocator (tp_dealloc) */ \n        (printfunc) swig_varlink_print,     /* Print (tp_print) */\n        (getattrfunc) swig_varlink_getattr, /* get attr (tp_getattr) */\n        (setattrfunc) swig_varlink_setattr, /* Set attr (tp_setattr) */\n        0,                                  /* tp_compare */\n        (reprfunc) swig_varlink_repr,       /* tp_repr */\n        0,                                  /* tp_as_number */\n        0,                                  /* tp_as_sequence */\n        0,                                  /* tp_as_mapping */\n        0,                                  /* tp_hash */\n        0,                                  /* tp_call */\n        (reprfunc)swig_varlink_str,        /* tp_str */\n        0,                                  /* tp_getattro */\n        0,                                  /* tp_setattro */\n        0,                                  /* tp_as_buffer */\n        0,                                  /* tp_flags */\n        varlink__doc__,                     /* tp_doc */\n        0,                                  /* tp_traverse */\n        0,                                  /* tp_clear */\n        0,                                  /* tp_richcompare */\n        0,                                  /* tp_weaklistoffset */\n#if PY_VERSION_HEX >= 0x02020000\n        0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* tp_iter -> tp_weaklist */\n#endif\n#if PY_VERSION_HEX >= 0x02030000\n        0,                                  /* tp_del */\n#endif\n#ifdef COUNT_ALLOCS\n        0,0,0,0                             /* tp_alloc -> tp_next */\n#endif\n      };\n      varlink_type = tmp;\n      varlink_type.ob_type = &PyType_Type;\n      type_init = 1;\n    }\n    return &varlink_type;\n  }\n  \n  /* Create a variable linking object for use later */\n  SWIGINTERN PyObject *\n  SWIG_Python_newvarlink(void) {\n    swig_varlinkobject *result = PyObject_NEW(swig_varlinkobject, swig_varlink_type());\n    if (result) {\n      result->vars = 0;\n    }\n    return ((PyObject*) result);\n  }\n  \n  SWIGINTERN void \n  SWIG_Python_addvarlink(PyObject *p, char *name, PyObject *(*get_attr)(void), int (*set_attr)(PyObject *p)) {\n    swig_varlinkobject *v = (swig_varlinkobject *) p;\n    swig_globalvar *gv = (swig_globalvar *) malloc(sizeof(swig_globalvar));\n    if (gv) {\n      size_t size = strlen(name)+1;\n      gv->name = (char *)malloc(size);\n      if (gv->name) {\n        strncpy(gv->name,name,size);\n        gv->get_attr = get_attr;\n        gv->set_attr = set_attr;\n        gv->next = v->vars;\n      }\n    }\n    v->vars = gv;\n  }\n  \n  SWIGINTERN PyObject *\n  SWIG_globals(void) {\n    static PyObject *_SWIG_globals = 0; \n    if (!_SWIG_globals) _SWIG_globals = SWIG_newvarlink();  \n    return _SWIG_globals;\n  }\n  \n  /* -----------------------------------------------------------------------------\n   * constants/methods manipulation\n   * ----------------------------------------------------------------------------- */\n  \n  /* Install Constants */\n  SWIGINTERN void\n  SWIG_Python_InstallConstants(PyObject *d, swig_const_info constants[]) {\n    PyObject *obj = 0;\n    size_t i;\n    for (i = 0; constants[i].type; ++i) {\n      switch(constants[i].type) {\n      case SWIG_PY_POINTER:\n        obj = SWIG_NewPointerObj(constants[i].pvalue, *(constants[i]).ptype,0);\n        break;\n      case SWIG_PY_BINARY:\n        obj = SWIG_NewPackedObj(constants[i].pvalue, constants[i].lvalue, *(constants[i].ptype));\n        break;\n      default:\n        obj = 0;\n        break;\n      }\n      if (obj) {\n        PyDict_SetItemString(d, constants[i].name, obj);\n        Py_DECREF(obj);\n      }\n    }\n  }\n  \n  /* -----------------------------------------------------------------------------*/\n  /* Fix SwigMethods to carry the callback ptrs when needed */\n  /* -----------------------------------------------------------------------------*/\n  \n  SWIGINTERN void\n  SWIG_Python_FixMethods(PyMethodDef *methods,\n    swig_const_info *const_table,\n    swig_type_info **types,\n    swig_type_info **types_initial) {\n    size_t i;\n    for (i = 0; methods[i].ml_name; ++i) {\n      const char *c = methods[i].ml_doc;\n      if (c && (c = strstr(c, \"swig_ptr: \"))) {\n        int j;\n        swig_const_info *ci = 0;\n        const char *name = c + 10;\n        for (j = 0; const_table[j].type; ++j) {\n          if (strncmp(const_table[j].name, name, \n              strlen(const_table[j].name)) == 0) {\n            ci = &(const_table[j]);\n            break;\n          }\n        }\n        if (ci) {\n          size_t shift = (ci->ptype) - types;\n          swig_type_info *ty = types_initial[shift];\n          size_t ldoc = (c - methods[i].ml_doc);\n          size_t lptr = strlen(ty->name)+2*sizeof(void*)+2;\n          char *ndoc = (char*)malloc(ldoc + lptr + 10);\n          if (ndoc) {\n            char *buff = ndoc;\n            void *ptr = (ci->type == SWIG_PY_POINTER) ? ci->pvalue : 0;\n            if (ptr) {\n              strncpy(buff, methods[i].ml_doc, ldoc);\n              buff += ldoc;\n              strncpy(buff, \"swig_ptr: \", 10);\n              buff += 10;\n              SWIG_PackVoidPtr(buff, ptr, ty->name, lptr);\n              methods[i].ml_doc = ndoc;\n            }\n          }\n        }\n      }\n    }\n  } \n  \n#ifdef __cplusplus\n}\n#endif\n\n/* -----------------------------------------------------------------------------*\n *  Partial Init method\n * -----------------------------------------------------------------------------*/\n\n#ifdef __cplusplus\nextern \"C\"\n#endif\nSWIGEXPORT void SWIG_init(void) {\n  PyObject *m, *d;\n  \n  /* Fix SwigMethods to carry the callback ptrs when needed */\n  SWIG_Python_FixMethods(SwigMethods, swig_const_table, swig_types, swig_type_initial);\n  \n  m = Py_InitModule((char *) SWIG_name, SwigMethods);\n  d = PyModule_GetDict(m);\n  \n  SWIG_InitializeModule(0);\n  SWIG_InstallConstants(d,swig_const_table);\n  \n  \n  \n  pygsl_module_for_error_treatment = m;\n  \n  \n  /* To use the numeric extension */\n  init_pygsl();\n  \n  \n  import_pygsl_rng();\n  \n  SWIG_Python_SetConstant(d, \"GSL_VEGAS_MODE_IMPORTANCE\",SWIG_From_int((int)(GSL_VEGAS_MODE_IMPORTANCE)));\n  SWIG_Python_SetConstant(d, \"GSL_VEGAS_MODE_IMPORTANCE_ONLY\",SWIG_From_int((int)(GSL_VEGAS_MODE_IMPORTANCE_ONLY)));\n  SWIG_Python_SetConstant(d, \"GSL_VEGAS_MODE_STRATIFIED\",SWIG_From_int((int)(GSL_VEGAS_MODE_STRATIFIED)));\n  PyDict_SetItemString(d,(char*)\"cvar\", SWIG_globals());\n  SWIG_addvarlink(SWIG_globals(),(char*)\"gsl_root_fsolver_bisection\",Swig_var_gsl_root_fsolver_bisection_get, Swig_var_gsl_root_fsolver_bisection_set);\n  SWIG_addvarlink(SWIG_globals(),(char*)\"gsl_root_fsolver_brent\",Swig_var_gsl_root_fsolver_brent_get, Swig_var_gsl_root_fsolver_brent_set);\n  SWIG_addvarlink(SWIG_globals(),(char*)\"gsl_root_fsolver_falsepos\",Swig_var_gsl_root_fsolver_falsepos_get, Swig_var_gsl_root_fsolver_falsepos_set);\n  SWIG_addvarlink(SWIG_globals(),(char*)\"gsl_root_fdfsolver_newton\",Swig_var_gsl_root_fdfsolver_newton_get, Swig_var_gsl_root_fdfsolver_newton_set);\n  SWIG_addvarlink(SWIG_globals(),(char*)\"gsl_root_fdfsolver_secant\",Swig_var_gsl_root_fdfsolver_secant_get, Swig_var_gsl_root_fdfsolver_secant_set);\n  SWIG_addvarlink(SWIG_globals(),(char*)\"gsl_root_fdfsolver_steffenson\",Swig_var_gsl_root_fdfsolver_steffenson_get, Swig_var_gsl_root_fdfsolver_steffenson_set);\n  SWIG_addvarlink(SWIG_globals(),(char*)\"gsl_min_fminimizer_goldensection\",Swig_var_gsl_min_fminimizer_goldensection_get, Swig_var_gsl_min_fminimizer_goldensection_set);\n  SWIG_addvarlink(SWIG_globals(),(char*)\"gsl_min_fminimizer_brent\",Swig_var_gsl_min_fminimizer_brent_get, Swig_var_gsl_min_fminimizer_brent_set);\n  SWIG_addvarlink(SWIG_globals(),(char*)\"gsl_multiroot_fsolver_dnewton\",Swig_var_gsl_multiroot_fsolver_dnewton_get, Swig_var_gsl_multiroot_fsolver_dnewton_set);\n  SWIG_addvarlink(SWIG_globals(),(char*)\"gsl_multiroot_fsolver_broyden\",Swig_var_gsl_multiroot_fsolver_broyden_get, Swig_var_gsl_multiroot_fsolver_broyden_set);\n  SWIG_addvarlink(SWIG_globals(),(char*)\"gsl_multiroot_fsolver_hybrid\",Swig_var_gsl_multiroot_fsolver_hybrid_get, Swig_var_gsl_multiroot_fsolver_hybrid_set);\n  SWIG_addvarlink(SWIG_globals(),(char*)\"gsl_multiroot_fsolver_hybrids\",Swig_var_gsl_multiroot_fsolver_hybrids_get, Swig_var_gsl_multiroot_fsolver_hybrids_set);\n  SWIG_addvarlink(SWIG_globals(),(char*)\"gsl_multiroot_fdfsolver_newton\",Swig_var_gsl_multiroot_fdfsolver_newton_get, Swig_var_gsl_multiroot_fdfsolver_newton_set);\n  SWIG_addvarlink(SWIG_globals(),(char*)\"gsl_multiroot_fdfsolver_gnewton\",Swig_var_gsl_multiroot_fdfsolver_gnewton_get, Swig_var_gsl_multiroot_fdfsolver_gnewton_set);\n  SWIG_addvarlink(SWIG_globals(),(char*)\"gsl_multiroot_fdfsolver_hybridj\",Swig_var_gsl_multiroot_fdfsolver_hybridj_get, Swig_var_gsl_multiroot_fdfsolver_hybridj_set);\n  SWIG_addvarlink(SWIG_globals(),(char*)\"gsl_multiroot_fdfsolver_hybridsj\",Swig_var_gsl_multiroot_fdfsolver_hybridsj_get, Swig_var_gsl_multiroot_fdfsolver_hybridsj_set);\n  SWIG_addvarlink(SWIG_globals(),(char*)\"gsl_multimin_fdfminimizer_steepest_descent\",Swig_var_gsl_multimin_fdfminimizer_steepest_descent_get, Swig_var_gsl_multimin_fdfminimizer_steepest_descent_set);\n  SWIG_addvarlink(SWIG_globals(),(char*)\"gsl_multimin_fdfminimizer_conjugate_pr\",Swig_var_gsl_multimin_fdfminimizer_conjugate_pr_get, Swig_var_gsl_multimin_fdfminimizer_conjugate_pr_set);\n  SWIG_addvarlink(SWIG_globals(),(char*)\"gsl_multimin_fdfminimizer_conjugate_fr\",Swig_var_gsl_multimin_fdfminimizer_conjugate_fr_get, Swig_var_gsl_multimin_fdfminimizer_conjugate_fr_set);\n  SWIG_addvarlink(SWIG_globals(),(char*)\"gsl_multimin_fdfminimizer_vector_bfgs\",Swig_var_gsl_multimin_fdfminimizer_vector_bfgs_get, Swig_var_gsl_multimin_fdfminimizer_vector_bfgs_set);\n  SWIG_addvarlink(SWIG_globals(),(char*)\"gsl_multimin_fminimizer_nmsimplex\",Swig_var_gsl_multimin_fminimizer_nmsimplex_get, Swig_var_gsl_multimin_fminimizer_nmsimplex_set);\n  SWIG_addvarlink(SWIG_globals(),(char*)\"gsl_multifit_fdfsolver_lmder\",Swig_var_gsl_multifit_fdfsolver_lmder_get, Swig_var_gsl_multifit_fdfsolver_lmder_set);\n  SWIG_addvarlink(SWIG_globals(),(char*)\"gsl_multifit_fdfsolver_lmsder\",Swig_var_gsl_multifit_fdfsolver_lmsder_get, Swig_var_gsl_multifit_fdfsolver_lmsder_set);\n  SWIG_Python_SetConstant(d, \"GSL_INTEG_COSINE\",SWIG_From_int((int)(GSL_INTEG_COSINE)));\n  SWIG_Python_SetConstant(d, \"GSL_INTEG_SINE\",SWIG_From_int((int)(GSL_INTEG_SINE)));\n  SWIG_Python_SetConstant(d, \"GSL_INTEG_GAUSS15\",SWIG_From_int((int)(GSL_INTEG_GAUSS15)));\n  SWIG_Python_SetConstant(d, \"GSL_INTEG_GAUSS21\",SWIG_From_int((int)(GSL_INTEG_GAUSS21)));\n  SWIG_Python_SetConstant(d, \"GSL_INTEG_GAUSS31\",SWIG_From_int((int)(GSL_INTEG_GAUSS31)));\n  SWIG_Python_SetConstant(d, \"GSL_INTEG_GAUSS41\",SWIG_From_int((int)(GSL_INTEG_GAUSS41)));\n  SWIG_Python_SetConstant(d, \"GSL_INTEG_GAUSS51\",SWIG_From_int((int)(GSL_INTEG_GAUSS51)));\n  SWIG_Python_SetConstant(d, \"GSL_INTEG_GAUSS61\",SWIG_From_int((int)(GSL_INTEG_GAUSS61)));\n  SWIG_addvarlink(SWIG_globals(),(char*)\"gsl_odeiv_step_rk2\",Swig_var_gsl_odeiv_step_rk2_get, Swig_var_gsl_odeiv_step_rk2_set);\n  SWIG_addvarlink(SWIG_globals(),(char*)\"gsl_odeiv_step_rk4\",Swig_var_gsl_odeiv_step_rk4_get, Swig_var_gsl_odeiv_step_rk4_set);\n  SWIG_addvarlink(SWIG_globals(),(char*)\"gsl_odeiv_step_rkf45\",Swig_var_gsl_odeiv_step_rkf45_get, Swig_var_gsl_odeiv_step_rkf45_set);\n  SWIG_addvarlink(SWIG_globals(),(char*)\"gsl_odeiv_step_rkck\",Swig_var_gsl_odeiv_step_rkck_get, Swig_var_gsl_odeiv_step_rkck_set);\n  SWIG_addvarlink(SWIG_globals(),(char*)\"gsl_odeiv_step_rk8pd\",Swig_var_gsl_odeiv_step_rk8pd_get, Swig_var_gsl_odeiv_step_rk8pd_set);\n  SWIG_addvarlink(SWIG_globals(),(char*)\"gsl_odeiv_step_rk2imp\",Swig_var_gsl_odeiv_step_rk2imp_get, Swig_var_gsl_odeiv_step_rk2imp_set);\n  SWIG_addvarlink(SWIG_globals(),(char*)\"gsl_odeiv_step_rk4imp\",Swig_var_gsl_odeiv_step_rk4imp_get, Swig_var_gsl_odeiv_step_rk4imp_set);\n  SWIG_addvarlink(SWIG_globals(),(char*)\"gsl_odeiv_step_bsimp\",Swig_var_gsl_odeiv_step_bsimp_get, Swig_var_gsl_odeiv_step_bsimp_set);\n  SWIG_addvarlink(SWIG_globals(),(char*)\"gsl_odeiv_step_gear1\",Swig_var_gsl_odeiv_step_gear1_get, Swig_var_gsl_odeiv_step_gear1_set);\n  SWIG_addvarlink(SWIG_globals(),(char*)\"gsl_odeiv_step_gear2\",Swig_var_gsl_odeiv_step_gear2_get, Swig_var_gsl_odeiv_step_gear2_set);\n  SWIG_Python_SetConstant(d, \"gsl_odeiv_hadj_dec\",SWIG_From_int((int)(GSL_ODEIV_HADJ_DEC)));\n  SWIG_Python_SetConstant(d, \"gsl_odeiv_hadj_inc\",SWIG_From_int((int)(GSL_ODEIV_HADJ_INC)));\n  SWIG_Python_SetConstant(d, \"gsl_odeiv_hadj_nil\",SWIG_From_int((int)(GSL_ODEIV_HADJ_NIL)));\n}\n\n", "meta": {"hexsha": "aeb9eb31d56e0e0ccdb7a2db46b1a29ae5318e8d", "size": 545520, "ext": "c", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/swig_src/callback_wrap.c", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/swig_src/callback_wrap.c", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/swig_src/callback_wrap.c", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 34.0418096724, "max_line_length": 199, "alphanum_fraction": 0.6777020091, "num_tokens": 176830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.05582313799303739, "lm_q2_score": 0.03258974511837433, "lm_q1q2_score": 0.0018192618389009268}}
{"text": "/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */\n#pragma once\n\n#include <mcbp/protocol/status.h>\n#include <cstdint>\n#include <functional>\n#include <gsl/gsl>\n\nstruct EngineIface;\n\n/**\n * Callback for any function producing stats.\n *\n * @param key the stat's key\n * @param value the stat's value in an ascii form (e.g. text form of a number)\n * @param cookie magic callback cookie\n */\nusing AddStatFn = std::function<void(std::string_view key,\n                                     std::string_view value,\n                                     gsl::not_null<const void*> cookie)>;\n\n/**\n * Callback for adding a response backet\n * @param key The key to put in the response\n * @param extras The data to put in the extended field in the response\n * @param body The data body\n * @param datatype This is currently not used and should be set to 0\n * @param status The status code of the return packet (see in protocol_binary\n *               for the legal values)\n * @param cas The cas to put in the return packet\n * @param cookie The cookie provided by the frontend\n * @return true if return message was successfully created, false if an\n *              error occured that prevented the message from being sent\n */\nusing AddResponseFn = std::function<bool(std::string_view key,\n                                         std::string_view extras,\n                                         std::string_view body,\n                                         uint8_t datatype,\n                                         cb::mcbp::Status status,\n                                         uint64_t cas,\n                                         const void* cookie)>;\n", "meta": {"hexsha": "43dec8d6476e663c226c7e5af071d4ae81ceeff3", "size": 1671, "ext": "h", "lang": "C", "max_stars_repo_path": "include/memcached/engine_common.h", "max_stars_repo_name": "rohansuri/kv_engine", "max_stars_repo_head_hexsha": "6d377448a787ce5dc268c95def2850e36f5f1328", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/memcached/engine_common.h", "max_issues_repo_name": "rohansuri/kv_engine", "max_issues_repo_head_hexsha": "6d377448a787ce5dc268c95def2850e36f5f1328", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/memcached/engine_common.h", "max_forks_repo_name": "rohansuri/kv_engine", "max_forks_repo_head_hexsha": "6d377448a787ce5dc268c95def2850e36f5f1328", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-10-11T14:00:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-06T09:20:15.000Z", "avg_line_length": 39.7857142857, "max_line_length": 78, "alphanum_fraction": 0.579293836, "num_tokens": 339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08509904268669496, "lm_q2_score": 0.021287353927820888, "lm_q1q2_score": 0.0018115334405904135}}
{"text": "#ifndef S3D_CV_IMAGE_OPERATION_IMAGE_OPERATION_H\n#define S3D_CV_IMAGE_OPERATION_IMAGE_OPERATION_H\n\n#include <gsl/gsl>\n\nnamespace cv {\n  class Mat;\n}\n\nnamespace s3d {\n  struct StanResults;\n}\n\nnamespace s3d {\nnamespace image_operation {\n\nclass ImageOperation {\npublic:\n  bool applyOnImagesIfEnabled(cv::Mat *leftImage, cv::Mat *rightImage, StanResults* results);\n\n  bool isEnabled();\n  void enable();\n  void disable();\n\nprivate:\n  virtual bool applyOnImage(cv::Mat *leftImage, cv::Mat *rightImage, StanResults* results) = 0;\n\n  bool isEnabled_{true};\n};\n\n} // namespace s3d\n} // namespace image_operation\n\n#endif // S3D_CV_IMAGE_OPERATION_IMAGE_OPERATION_H\n", "meta": {"hexsha": "3742ff8ee84267afa4f4ea74076bb1e771c3be96", "size": 655, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/cv/include/s3d/cv/image_operation/image_operation.h", "max_stars_repo_name": "hugbed/OpenS3D", "max_stars_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-16T16:38:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-20T03:23:15.000Z", "max_issues_repo_path": "src/core/cv/include/s3d/cv/image_operation/image_operation.h", "max_issues_repo_name": "hugbed/OpenS3D", "max_issues_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 40.0, "max_issues_repo_issues_event_min_datetime": "2017-04-12T17:24:44.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-21T18:41:23.000Z", "max_forks_repo_path": "src/core/cv/include/s3d/cv/image_operation/image_operation.h", "max_forks_repo_name": "hugbed/OpenS3D", "max_forks_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-07-13T21:51:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-18T16:22:03.000Z", "avg_line_length": 18.7142857143, "max_line_length": 95, "alphanum_fraction": 0.7603053435, "num_tokens": 167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.07055960009622166, "lm_q2_score": 0.02556521596493716, "lm_q1q2_score": 0.0018038714148595075}}
{"text": "#pragma once\n//=============================================================================\n// EXTERNAL DECLARATIONS\n//=============================================================================\n#include <Core/Components/IdType.h>\n#include \"Core/Game/IManager.h\"\n#include <gsl/span>\n#include <memory>\n\nnamespace engine\n{\n//=============================================================================\n// FORWARD DECLARATIONS\n//=============================================================================\nclass IGameEngine;\nusing GameEngineRef = std::shared_ptr<IGameEngine>;\nusing GameEngineWeakRef = std::weak_ptr<IGameEngine>;\n\n\n//=============================================================================\n// INTERFACE IManagerComponent\n//=============================================================================\nclass IManagerComponent\n{\npublic:\n\tvirtual ~IManagerComponent() {}\n\npublic:\n\tvirtual gsl::span<IdType> interfaces() = 0;\n\tvirtual void onAttached(const GameEngineRef &iGameEngine) = 0;\n\tvirtual void onDetached(const GameEngineRef &iGameEngine) = 0;\n};\n} // namespace engine\n", "meta": {"hexsha": "d2eb7aa0669179e2d628e04f911df89a9fe522e2", "size": 1100, "ext": "h", "lang": "C", "max_stars_repo_path": "Core/Game/IManagerComponent.h", "max_stars_repo_name": "gaspardpetit/INF740-GameEngine", "max_stars_repo_head_hexsha": "075b6563204fb3d1cf7531599f30dd296c2c9239", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Core/Game/IManagerComponent.h", "max_issues_repo_name": "gaspardpetit/INF740-GameEngine", "max_issues_repo_head_hexsha": "075b6563204fb3d1cf7531599f30dd296c2c9239", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Core/Game/IManagerComponent.h", "max_forks_repo_name": "gaspardpetit/INF740-GameEngine", "max_forks_repo_head_hexsha": "075b6563204fb3d1cf7531599f30dd296c2c9239", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-09-25T22:24:16.000Z", "max_forks_repo_forks_event_max_datetime": "2015-09-25T22:24:16.000Z", "avg_line_length": 32.3529411765, "max_line_length": 79, "alphanum_fraction": 0.4336363636, "num_tokens": 173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06465349015847215, "lm_q2_score": 0.027585279828507704, "lm_q1q2_score": 0.001783484617911123}}
{"text": "// Implementation of the interface in float_image.h.\n\n#include <errno.h>\n#include <float.h>\n#include <limits.h>\n#include <math.h>\n#include <signal.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <unistd.h>\n#include <setjmp.h>\n\n#include <glib.h>\n#if GLIB_CHECK_VERSION (2, 6, 0)\n#  include <glib/gstdio.h>\n#endif\n#include <gsl/gsl_spline.h>\n#include <gsl/gsl_histogram.h>\n#include <gsl/gsl_math.h>\n\n#include \"asf.h\"\n#include \"asf_tiff.h\"\n#include \"asf_jpeg.h\"\n#include \"float_image.h\"\n\n#ifndef linux\n#ifndef darwin\n#ifndef win32\nstatic double\nround (double arg)\n{\n    return floor (arg + 0.5);\n}\n#endif // #ifndef win32\n#endif // #ifndef darwin\n#endif // #ifndef linux\n\n#include \"asf_glib.h\"\n\n// Default cache size to use is 16 megabytes.\nstatic const size_t default_cache_size = 16 * 1048576;\n// This class wide data element keeps track of the number of temporary\n// tile files opened by the current process, in order to give them\n// unique names.\nstatic unsigned long current_tile_file_number = 0;\n\n#ifndef win32\n// We need to ensure that multiple threads trying to create their own\n// images concurently don't end up with the same temporary file names.\nG_LOCK_DEFINE_STATIC (current_tile_file_number);\n\n// We don't want to let multiple threads twiddle the signal block mask\n// concurrently, or we might end up with the wrong set of signals\n// blocked.  This lock is used to gaurantee this can't happen (see the\n// usage for a better explanation).\nG_LOCK_DEFINE_STATIC (signal_block_activity);\n#endif\n\n// Return a FILE pointer refering to a new, already unlinked file in a\n// location which hopefully has enough free space to serve as a block\n// cache.\nstatic FILE *\ninitialize_tile_cache_file (GString **tile_file_name)\n{\n  // Create the temporary tile oriented storage file.  This gets\n  // filled in in different ways depending on which creation routine\n  // we are using.\n  g_assert(*tile_file_name == NULL);\n  *tile_file_name = g_string_new (\"\");\n\n  // Here we do a slightly weird thing: if the current directory is\n  // writable, we create a temporary file in the current directory.\n  // We do this because the temporary file could well be pretty big\n  // and /tmp often maps to a small file system.  The idea is that the\n  // directory the user is in is more likely to have the extra space\n  // required to hold the temporary file.  Of course, if they have\n  // been carefully calculating their space requirements, they may be\n  // disappointed.  We use a weird name that no sane user would ever\n  // use for one of their files, we hope.\n#ifndef win32\n  G_LOCK (current_tile_file_number);\n  g_assert (sizeof (long) >= sizeof (pid_t));\n#endif\n\n  g_string_append_printf (*tile_file_name,\n                          \".float_image_tile_file_%ld_%lu\",\n                          (long) getpid (),\n                          current_tile_file_number);\n  //g_free (current_dir);\n  // This hard coded limit on the current number used to uniqueify\n  // file names limits us to creating no more than ULONG_MAX instances\n  // during a process.\n  g_assert (current_tile_file_number < ULONG_MAX);\n  current_tile_file_number++;\n\n#ifndef win32\n  G_UNLOCK (current_tile_file_number);\n\n  // We block signals while we create and unlink this file, so we\n  // don't end up leaving a huge temporary file somewhere.\n  // Theoretically, two parallel instantiations of image could end up\n  // in a race condition which would result in all signals ending up\n  // blocked after both were done with this section, so we consider\n  // this section critical and protect it with a lock.\n  G_LOCK (signal_block_activity);\n  sigset_t all_signals, old_set;\n  int return_code = sigfillset (&all_signals);\n  g_assert (return_code == 0);\n  return_code = sigprocmask (SIG_SETMASK, &all_signals, &old_set);\n#endif\n\n  // now open new tile file in the tmp dir\n  FILE *tile_file = fopen_tmp_file ((*tile_file_name)->str, \"w+b\");\n  if ( tile_file == NULL ) {\n    if ( errno != EACCES ) {\n      g_warning (\"couldn't create file in tmp directory (%s), and it wasn't\"\n                 \"just a permissions problem\", get_asf_tmp_dir());\n    }\n    else {\n      // Couldn't open in current directory, so try using tmpfile,\n      // which opens the file in the standardish place for the system.\n      // See the comment above about why opening in /tmp or the like\n      // is potentially bad.\n      tile_file = tmpfile ();\n      g_assert (tile_file != NULL);\n    }\n  }\n  else {\n    // the open-then-delete trick does not seem to work on MinGW\n#ifndef win32\n    return_code = unlink_tmp_file ((*tile_file_name)->str);\n    g_assert (return_code == 0);\n#endif\n  }\n  g_assert (tile_file != NULL);\n\n#ifndef win32\n  return_code = sigprocmask (SIG_SETMASK, &old_set, NULL);\n  G_UNLOCK (signal_block_activity);\n#endif\n\n  return tile_file;\n}\n\n// This routine does the work common to several of the differenct\n// creation routines.  Basicly, it does everything but fill in the\n// contents of the disk tile store.\nstatic FloatImage *\ninitialize_float_image_structure (ssize_t size_x, ssize_t size_y)\n{\n  // Allocate instance memory.\n  FloatImage *self = g_new0 (FloatImage, 1);\n\n  // Validate and remember image size.\n  g_assert (size_x > 0 && size_y > 0);\n  self->size_x = size_x;\n  self->size_y = size_y;\n\n  // Greater of size_x and size_y.\n  size_t largest_dimension = (size_x > size_y ? size_x : size_y);\n\n  // If we can fit the entire image in a single square tile, then we\n  // want just a single big tile and we won't need to bother with the\n  // cache file since it won't ever be used, so we do things slightly\n  // differently.  FIXME: it would be slightly better to also detect\n  // and specially handle the case where we have long narrow images\n  // that can fit in a single stip of tiles in the cache.\n  if ( largest_dimension * largest_dimension * sizeof (float)\n       <= default_cache_size ) {\n    self->cache_space = largest_dimension * largest_dimension * sizeof (float);\n    self->cache_area = self->cache_space / sizeof (float);\n    self->tile_size = largest_dimension;\n    self->cache_size_in_tiles = 1;\n    self->tile_count_x = 1;\n    self->tile_count_y = 1;\n    self->tile_count = 1;\n    self->tile_area = self->tile_size * self->tile_size;\n    self->cache = g_new (float, self->cache_area);\n    self->tile_addresses = g_new0 (float *, self->tile_count);\n    g_assert (NULL == 0x0);     // Ensure g_new0 effectively sets to NULL.\n    // The tile queue shouldn't ever be needed in this case.\n    self->tile_queue = NULL;\n    // The tile file shouldn't ever be needed, so we set it to NULL to\n    // indicate this to a few other methods that use it directly, and\n    // to hopefully ensure that it triggers an exception if it is\n    // used.\n    self->tile_file = NULL;\n\n    // Objects are born with one reference.\n    self->reference_count = 1;\n\n    return self;\n  }\n\n  // The default cache size compiled into the class.\n  self->cache_space = default_cache_size;\n\n  // Memory cache space, in pixels.\n  g_assert (self->cache_space % sizeof (float) == 0);\n  self->cache_area = self->cache_space / sizeof (float);\n\n  // How small do our tiles have to be on a side to fit two full rows\n  // of them in the memory cache?  This is slightly tricky.  In order\n  // to provide the services promised in the interface, we need to\n  // solve\n  //\n  //      2 * pow (t, 2) * ceil ((double)largest_dimension / t)\n  //           <= self->cache_area\n  //\n  // for tile size t.  I don't know the closed form solution if there\n  // is one, so toss out the ceil() and solve the easier\n  //\n  //      2 * pow (t, 2) * ((double)largest_dimension / t) <= self->cache_area\n  //\n  // and then decrement t iteratively until things work.\n  self->tile_size = self->cache_area / (2 * largest_dimension);\n  while ( (2 * self->tile_size * self->tile_size\n           * ceil ((double) largest_dimension / self->tile_size))\n          > self->cache_area ) {\n    self->tile_size--;\n  }\n\n  // If we end up with a tile size of 0, it means we tried to create a\n  // truly gigantic image (compared to the size of the tile cache at\n  // least.  Really, if we end up with a sufficiently small tile size,\n  // there probably isn't much point in going on.  Picking an\n  // arbitrary tile size to call too small is tricky, but we do it\n  // anyway :).\n  const size_t minimum_tile_size = 4;\n  g_assert (self->tile_size >= minimum_tile_size);\n\n  // Area of tiles, in pixels.\n  self->tile_area = (size_t) (self->tile_size * self->tile_size);\n\n  // Number of tiles which will fit in image cache.\n  self->cache_size_in_tiles = self->cache_area / self->tile_area;\n  // Can we fit at least as much as we intended in the cache?\n  g_assert (self->cache_size_in_tiles\n            >= 2 * (size_t) ceil ((double) largest_dimension\n                                  / self->tile_size));\n\n  // Number of tiles image has been split into in x and y directions.\n  self->tile_count_x = (size_t) ceil ((double) self->size_x / self->tile_size);\n  self->tile_count_y = (size_t) ceil ((double) self->size_y / self->tile_size);\n\n  // Total number of image tiles image has been split into.\n  self->tile_count = self->tile_count_x * self->tile_count_y;\n\n  // We want to be able to pack a tile number into a pointer later, so\n  // we need it to fit into an integer.\n  g_assert (self->tile_count < INT_MAX);\n\n  // Did all that math work?\n  g_assert (self->tile_size * self->cache_size_in_tiles / 2\n            >= largest_dimension);\n  g_assert (self->cache_size_in_tiles * self->tile_area <= self->cache_area);\n\n  // Allocate memory for the in-memory cache.\n  self->cache = g_new (float, self->cache_area);\n  // Do we want to do mlock() here maybe?\n\n  // The addresses in the cache of the starts of each of the tiles.\n  // This array contains flattened tile addresses in the same way that\n  // image memory normally uses flattened pixel addresses, e.g. the\n  // address of tile x = 2, y = 4 is stored at self->tile_addresses[4\n  // * self->tile_count_x + 2].  If a tile isn't in the cache, the\n  // address is NULL (meaning it will have to be loaded).\n  self->tile_addresses = g_new0 (float *, self->tile_count);\n  g_assert (NULL == 0x0);       // Ensure g_new0 effectively sets to NULL.\n\n  // Create a queue in order to keep track of which tile was loaded\n  // longest ago.\n  self->tile_queue = g_queue_new ();\n\n  // Get a new empty tile cache file pointer.\n  self->tile_file_name = NULL;\n  self->tile_file = initialize_tile_cache_file (&(self->tile_file_name));\n\n  // Objects are born with one reference.\n  self->reference_count = 1;\n\n  return self;\n}\n\nFloatImage *\nfloat_image_thaw (FILE *file_pointer)\n{\n  FILE *fp = file_pointer;  // Convenience alias.\n\n  g_assert (file_pointer != NULL);\n\n  FloatImage *self = g_new0 (FloatImage, 1);\n\n  size_t read_count = fread (&(self->size_x), sizeof (size_t), 1, fp);\n  g_assert (read_count == 1);\n\n  read_count = fread (&(self->size_y), sizeof (size_t), 1, fp);\n  g_assert (read_count == 1);\n\n  read_count = fread (&(self->cache_space), sizeof (size_t), 1, fp);\n  g_assert (read_count == 1);\n\n  read_count = fread (&(self->cache_area), sizeof (size_t), 1, fp);\n  g_assert (read_count == 1);\n\n  read_count = fread (&(self->tile_size), sizeof (size_t), 1, fp);\n  g_assert (read_count == 1);\n\n  read_count = fread (&(self->cache_size_in_tiles), sizeof (size_t), 1, fp);\n  g_assert (read_count == 1);\n\n  read_count = fread (&(self->tile_count_x), sizeof (size_t), 1, fp);\n  g_assert (read_count == 1);\n\n  read_count = fread (&(self->tile_count_y), sizeof (size_t), 1, fp);\n  g_assert (read_count == 1);\n\n  read_count = fread (&(self->tile_count), sizeof (size_t), 1, fp);\n  g_assert (read_count == 1);\n\n  read_count = fread (&(self->tile_area), sizeof (size_t), 1, fp);\n  g_assert (read_count == 1);\n\n  // The cache isn't serialized -- its a bit of a pain and probably\n  // almost never worth it.\n  self->cache = g_new (float, self->cache_area);\n\n  self->tile_addresses = g_new0 (float *, self->tile_count);\n\n  // We don't actually keep the tile queue in the serialized instance,\n  // but if the serialized pointer to it is NULL, we know we aren't\n  // using a tile cache file (i.e. the whole image fits in the memory\n  // cache).\n  read_count = fread (&(self->tile_queue), sizeof (GQueue *), 1, fp);\n  g_assert (read_count == 1);\n\n  // If there was no cache file...\n  if ( self->tile_queue == NULL ) {\n    // The tile_file structure field should also be NULL.\n    self->tile_file = NULL;\n    // we restore the file directly into the first and only tile (see\n    // the end of the float_image_new method).\n    self->tile_addresses[0] = self->cache;\n    read_count = fread (self->tile_addresses[0], sizeof (float),\n      self->tile_area, fp);\n    g_assert (read_count == self->tile_area);\n  }\n  // otherwise, an empty tile queue needs to be initialized, and the\n  // remainder of the serialized version is the tile block cache.\n  else {\n    self->tile_queue = g_queue_new ();\n    self->tile_file_name = NULL;\n    self->tile_file = initialize_tile_cache_file (&(self->tile_file_name));\n    float *buffer = g_new (float, self->tile_area);\n    size_t ii;\n    for ( ii = 0 ; ii < self->tile_count ; ii++ ) {\n      read_count = fread (buffer, sizeof (float), self->tile_area, fp);\n      g_assert (read_count == self->tile_area);\n      size_t write_count = fwrite (buffer, sizeof (float), self->tile_area,\n           self->tile_file);\n      if ( write_count < self->tile_area ) {\n  if ( feof (self->tile_file) ) {\n    fprintf (stderr,\n       \"Premature end of file while trying to thaw FloatImage \"\n       \"instance\\n\");\n  }\n  else {\n    g_assert (ferror (self->tile_file));\n    fprintf (stderr,\n       \"Error writing tile cache file for FloatImage instance \"\n       \"during thaw: %s\\n\", strerror (errno));\n  }\n  exit (EXIT_FAILURE);\n      }\n      g_assert (write_count == self->tile_area);\n    }\n    g_free (buffer);\n  }\n\n  // We didn't call initialize_float_image_structure directly or\n  // indirectly for this creation method, so we still have to set the\n  // reference count appropriately.\n  self->reference_count = 1;\n\n  return self;\n}\n\n\n\nFloatImage *\nfloat_image_new (ssize_t size_x, ssize_t size_y)\n{\n  g_assert (size_x > 0 && size_y > 0);\n\n  FloatImage *self = initialize_float_image_structure (size_x, size_y);\n\n  // If we need a tile file for an image of this size, prepare it.\n  if ( self->tile_file != NULL ) {\n    // The total width or height of all the tiles is probably greater\n    // than the width or height of the image itself.\n    size_t total_width = self->tile_count_x * self->tile_size;\n    size_t total_height = self->tile_count_y * self->tile_size;\n\n    // Fill the file full of zeros.  FIXME: there is almost certainly\n    // a faster way to ensure that we have the disk space we need.\n    float *zero_line = g_new0 (float, total_width);\n    g_assert (0.0 == 0x0);      // Ensure the g_new0 did what we think.\n\n    // We don't have to write in tile order because its all zeros anyway.\n    size_t ii;\n    for ( ii = 0 ; ii < total_height ; ii++ ) {\n      size_t write_count = fwrite (zero_line, sizeof (float), total_width,\n                                   self->tile_file);\n      // If we wrote less than expected,\n      if ( write_count < total_width ) {\n        // it must have been a write error (probably no space left),\n        g_assert (ferror (self->tile_file));\n        // so print an error message,\n        fprintf (stderr,\n                 \"Error writing tile cache file for FloatImage instance: %s\\n\",\n                 strerror (errno));\n        // and exit.\n        exit (EXIT_FAILURE);\n      }\n    }\n\n    // Done with the line of zeros.\n    g_free (zero_line);\n  }\n\n  // Everything fits in the cache (at the moment this means everything\n  // fits in the first tile, which is a bit of a FIXME), so just put\n  // it there.\n  else {\n    self->tile_addresses[0] = self->cache;\n    size_t ii, jj;\n    for ( ii = 0 ; ii < self->tile_size ; ii++ ) {\n      for ( jj = 0 ; jj < self->tile_size ; jj++ ) {\n        self->tile_addresses[0][ii * self->tile_size + jj] = 0.0;\n      }\n    }\n  }\n\n  return self;\n}\n\nFloatImage *\nfloat_image_new_with_value (ssize_t size_x, ssize_t size_y, float value)\n{\n  g_assert (size_x > 0 && size_y > 0);\n\n  FloatImage *self = initialize_float_image_structure (size_x, size_y);\n\n  // If we need a tile file for an image of this size, prepare it.\n  if ( self->tile_file != NULL ) {\n\n    // The total width or height of all the tiles is probably greater\n    // than the width or height of the image itself.\n    size_t total_width = self->tile_count_x * self->tile_size;\n    size_t total_height = self->tile_count_y * self->tile_size;\n\n    // Fill the file full of the given value.\n    float *value_line = g_new (float, total_width);\n    size_t ii;\n    for ( ii = 0 ; ii < total_width ; ii++ ) {\n      value_line[ii] = value;\n    }\n    // We don't have to write in tile order because the values are all\n    // the same anyway.\n    for ( ii = 0 ; ii < total_height ; ii++ ) {\n      size_t write_count = fwrite (value_line, sizeof (float), total_width,\n                                   self->tile_file);\n      // If we wrote less than expected,\n      if ( write_count < total_width ) {\n        // it must have been a write error (probably no space left),\n        g_assert (ferror (self->tile_file));\n        // so print an error message,\n        fprintf (stderr,\n                 \"Error writing tile cache file for FloatImage instance: %s\\n\",\n                 strerror (errno));\n        // and exit.\n        exit (EXIT_FAILURE);\n      }\n    }\n\n    // Done with the line of values.\n    g_free (value_line);\n  }\n\n  // Everything fits in the cache (at the moment this means everything\n  // fits in the first tile, which is a bit of a FIXME), so just put\n  // it there.\n  else {\n    self->tile_addresses[0] = self->cache;\n    size_t ii, jj;\n    for ( ii = 0 ; ii < self->tile_size ; ii++ ) {\n      for ( jj = 0 ; jj < self->tile_size ; jj++ ) {\n        self->tile_addresses[0][ii * self->tile_size + jj] = value;\n      }\n    }\n  }\n\n  return self;\n}\n\n// Swap the byte order of a 32 bit value, hopefully converting from\n// big endian to little endian or vice versa.  There is unfortunately\n// some question whether or not this always works right for floating\n// point values.\nstatic void\nswap_bytes_32 (unsigned char *in)\n{\n  g_assert (sizeof (unsigned char) == 1);\n  int tmp = in[0];\n  in[0] = in[3];\n  in[3] = tmp;\n  tmp = in[1];\n  in[1] = in[2];\n  in[2] = tmp;\n}\n\n// Swap the byte order of a 16 bit value, hopefully converting from\n// big endian to little endian or vice versa.\n//static void\n//swap_bytes_16 (unsigned char *in)\n//{\n//  g_assert (sizeof (unsigned char) == 1);\n//  int tmp = in[0];\n//  in[0] = in[1];\n//  in[1] = tmp;\n//}\n\nFloatImage *\nfloat_image_new_from_memory (ssize_t size_x, ssize_t size_y, float *buffer)\n{\n  g_assert (size_x > 0 && size_y > 0);\n\n  // FIXME: this is an inefficient implementation.\n\n  FloatImage *self = float_image_new (size_x, size_y);\n\n  ssize_t ii, jj;\n  for ( ii = 0 ; ii < size_x ; ii++ ) {\n    for ( jj = 0 ; jj < size_y ; jj++ ) {\n      float_image_set_pixel (self, ii, jj, buffer[jj * size_x + ii]);\n    }\n  }\n\n  return self;\n}\n\nFloatImage *\nfloat_image_copy (FloatImage *model)\n{\n  g_assert (model->reference_count > 0); // Harden against missed ref=1 in new\n\n  // FIXME: this could obviously be optimized a lot by copying the\n  // existed tile file, etc.\n  FloatImage *self = float_image_new (model->size_x, model->size_y);\n\n  size_t ii, jj;\n  for ( ii = 0 ; ii < self->size_y ; ii++ ) {\n    for ( jj = 0 ; jj < self->size_x ; jj++ ) {\n      float_image_set_pixel (self, jj, ii,\n           float_image_get_pixel (model, jj, ii));\n    }\n  }\n\n  return self;\n}\n\n// Bilinear interpolation for a point delta_x, delta_y from the lower\n// left corner between values ul (upper left), ur (upper right), etc.\n// The corner are considered to be corners of a unit square.\nstatic float\nbilinear_interpolate (double delta_x, double delta_y, float ul, float ur,\n                      float ll, float lr)\n{\n  float lv = ll + (lr - ll) * delta_x; // Lower value.\n  float uv = ul + (ur - ul) * delta_x; // Upper value.\n\n  return lv + (uv - lv) * delta_y;\n}\n\nFloatImage *\nfloat_image_new_from_model_scaled (FloatImage *model, ssize_t scale_factor)\n{\n  g_assert (model->reference_count > 0); // Harden against missed ref=1 in new\n\n  g_assert (model->size_x > 0 && model->size_y > 0);\n\n  g_assert (scale_factor > 0);\n  g_assert (scale_factor % 2 == 1);\n\n  FloatImage *self\n    = float_image_new (round ((double) model->size_x / scale_factor),\n           round ((double) model->size_y / scale_factor));\n\n  // Form an averaging kernel of the required size.\n  size_t kernel_size = scale_factor;\n  gsl_matrix_float *averaging_kernel\n    = gsl_matrix_float_alloc (kernel_size, kernel_size);\n  float kernel_value = 1.0 / ((float)kernel_size * kernel_size);\n  size_t ii, jj;                // Index values.\n  for ( ii = 0 ; ii < averaging_kernel->size1 ; ii++ ) {\n    for ( jj = 0 ; jj < averaging_kernel->size2 ; jj++ ) {\n      gsl_matrix_float_set (averaging_kernel, ii, jj, kernel_value);\n    }\n  }\n\n  // \"Sample\" the model by applying the averaging kernel, putting\n  // results into the new image.\n  size_t sample_stride = scale_factor;\n  for ( ii = 0 ; ii < self->size_y ; ii++ ) {\n    for ( jj = 0 ; jj < self->size_x ; jj++ ) {\n      float pv = float_image_apply_kernel (model, jj * sample_stride,\n                                           ii * sample_stride,\n                                           averaging_kernel);\n      float_image_set_pixel (self, jj, ii, pv);\n    }\n  }\n\n  return self;\n}\n\nFloatImage *\nfloat_image_new_subimage (FloatImage *model, ssize_t x, ssize_t y,\n        ssize_t size_x, ssize_t size_y)\n{\n  g_assert (model->reference_count > 0); // Harden against missed ref=1 in new\n\n  // Upper left corner must be in model.\n  g_assert (x >= 0 && y >= 0);\n\n  // Size of image to be created must be strictly positive.\n  g_assert (size_x >= 1 && size_y >= 1);\n\n  // Given model must be big enough to allow a subimage of the\n  // requested size to fit.\n  g_assert (model->size_x <= SSIZE_MAX && model->size_y <= SSIZE_MAX);\n  g_assert (x + size_x <= (ssize_t) model->size_x);\n  g_assert (y + size_y <= (ssize_t) model->size_y);\n\n  FloatImage *self = float_image_new (size_x, size_y);\n\n  // Copy the image pixels from the model.\n  ssize_t ii, jj;\n  for ( ii = 0 ; ii < (ssize_t) self->size_x ; ii++ ) {\n    for ( jj = 0 ; jj < (ssize_t) self->size_y ; jj++ ) {\n      float pv = float_image_get_pixel (model, x + ii, y + jj);\n      float_image_set_pixel (self, ii, jj, pv);\n    }\n  }\n\n  return self;\n}\n\n// Return true iff file is size or larger.\nstatic gboolean\nis_large_enough (const char *file, off_t size)\n{\n  struct stat stat_buffer;\n#if GLIB_CHECK_VERSION(2, 6, 0)\n  int return_code = g_stat (file, &stat_buffer);\n  if ( return_code != 0 ) {\n    g_error (\"Couldn't g_stat file %s: %s\", file, strerror (errno));\n  }\n#else\n  int return_code = stat (file, &stat_buffer);\n  if ( return_code != 0 ) {\n    g_error (\"Couldn't stat file %s: %s\", file, strerror (errno));\n  }\n#endif\n\n  return stat_buffer.st_size >= size;\n}\n\nFloatImage *\nfloat_image_new_from_file (ssize_t size_x, ssize_t size_y, const char *file,\n                           off_t offset, float_image_byte_order_t byte_order)\n{\n  g_assert (size_x > 0 && size_y > 0);\n\n  // Check in advance if the source file looks big enough (we will\n  // still need to check return codes as we read() data, of course).\n  //g_assert (is_large_enough (file, offset + ((off_t) size_x * size_y\n  //               * sizeof (float))));\n\n  // Open the file to read data from.\n  FILE *fp = fopen (file, \"rb\");\n  // FIXME: we need some error handling and propagation here.\n  g_assert (fp != NULL);\n\n  FloatImage *self = float_image_new_from_file_pointer (size_x, size_y, fp,\n                                                        offset, byte_order);\n\n  // Close file we read image from.\n  int return_code = fclose (fp);\n  g_assert (return_code == 0);\n\n  return self;\n}\n\n// Return true iff byte_order is not the native byte order on the\n// current platform.\nstatic gboolean\nnon_native_byte_order (float_image_byte_order_t byte_order)\n{\n  return ((G_BYTE_ORDER == G_LITTLE_ENDIAN\n           && byte_order == FLOAT_IMAGE_BYTE_ORDER_BIG_ENDIAN)\n          || (G_BYTE_ORDER == G_BIG_ENDIAN\n              && byte_order == FLOAT_IMAGE_BYTE_ORDER_LITTLE_ENDIAN));\n}\n\nFloatImage *\nfloat_image_new_from_file_pointer (ssize_t size_x, ssize_t size_y,\n                                   FILE *file_pointer, off_t offset,\n                                   float_image_byte_order_t byte_order)\n{\n  g_assert (size_x > 0 && size_y > 0);\n\n  FloatImage *self = initialize_float_image_structure (size_x, size_y);\n\n  FILE *fp = file_pointer;      // Convenience alias.\n\n  // Seek to the indicated offset in the file.\n  int return_code = FSEEK64 (fp, offset, SEEK_CUR);\n  g_assert (return_code == 0);\n\n  // If we need a tile file for an image of this size, we will load\n  // the data straight into it.\n  if ( self->tile_file != NULL ) {\n\n    // We will read the input image data in horizontal stips one tile\n    // high.  Note that we probably won't be able to entirely fill the\n    // last tiles in each dimension with real data, since the image\n    // sizes rarely divide evenly by the numbers of tiles.  So we fill\n    // it with zeros instead.  The data off the edges of the image\n    // should never be accessed directly anyway.\n\n    // Some data for doing zero fill.  If the tiles are bigger than\n    // the image itself, we need to make the available zero fill the\n    // size of the tile instead of the size of the file.\n    g_assert (self->tile_size <= SSIZE_MAX);\n    float *zero_line = g_new0 (float, (size_x > (ssize_t) self->tile_size ?\n                                       (size_t) size_x : self->tile_size));\n    g_assert (0.0 == 0x0);\n\n    // Buffer capable of holding a full strip.\n    float *buffer = g_new (float, self->tile_size * self->size_x);\n\n    // Reorganize data into tiles in tile oriented disk file.\n    size_t ii = 0;\n    for ( ii = 0 ; ii < self->tile_count_y ; ii++ ) {\n      asfPercentMeter((float)ii/(self->tile_count_y-1));\n\n      // The \"effective_height\" of the strip is the portion of the\n      // strip for which data actually exists.  If the effective\n      // height is less than self->tile>size, we will have to add some\n      // junk to fill up the extra part of the tile (which should\n      // never be accessed).\n      size_t effective_height;\n      if ( ii < self->tile_count_y - 1\n           || self->size_y % self->tile_size == 0 ) {\n        effective_height = self->tile_size;\n      }\n      else {\n        effective_height = self->size_y % self->tile_size;\n      }\n      // Total area of the current strip.\n      size_t strip_area = effective_height * self->size_x;\n\n      // Read one strip of tiles worth of data from the file.\n      size_t read_count = fread (buffer, sizeof (float), strip_area, fp);\n      g_assert (read_count == strip_area);\n\n      // Convert from the byte order on disk to the host byte order,\n      // if necessary.  Doing this with floats is somewhat\n      // questionable apparently: major libraries don't seem to\n      // support it with their macros, and the perl documentation says\n      // it can't be done in a truly portable way... but it seems to\n      // work.\n      if ( non_native_byte_order (byte_order) ) {\n        // Floats better be four bytes for this to work.\n        g_assert (sizeof (float) == 4);\n        size_t idx;\n        for ( idx = 0 ; idx < strip_area ; idx++ ) {\n          swap_bytes_32 ((unsigned char *) &(buffer[idx]));\n        }\n      }\n\n      // Write data from the strip into the tile store.\n      size_t jj;\n      for ( jj = 0 ; jj < self->tile_count_x ; jj++ ) {\n        // This is roughly analogous to effective_height.\n        size_t effective_width;\n        if ( jj < self->tile_count_x - 1\n             || self->size_x % self->tile_size == 0) {\n          effective_width = self->tile_size;\n        }\n        else {\n          effective_width = self->size_x % self->tile_size;\n        }\n        size_t write_count;     // For return of fwrite() calls.\n        size_t kk;\n        for ( kk = 0 ; kk < effective_height ; kk++ ) {\n          write_count\n            = fwrite (buffer + kk * self->size_x + jj * self->tile_size,\n                      sizeof (float), effective_width, self->tile_file);\n          // If we wrote less than expected,\n          if ( write_count < effective_width ) {\n            // it must have been a write error (probably no space left),\n            g_assert (ferror (self->tile_file));\n            // so print an error message,\n            fprintf (stderr,\n                     \"Error writing tile cache file for FloatImage instance: \"\n                     \"%s\\n\", strerror (errno));\n            // and exit.\n            exit (EXIT_FAILURE);\n          }\n          if ( effective_width < self->tile_size ) {\n            // Amount we have left to write to fill out the last tile.\n            size_t edge_width = self->tile_size - effective_width;\n            write_count = fwrite (zero_line, sizeof (float), edge_width,\n                                  self->tile_file);\n            // If we wrote less than expected,\n            if ( write_count < edge_width ) {\n              // it must have been a write error (probably no space left),\n              g_assert (ferror (self->tile_file));\n              // so print an error message,\n              fprintf (stderr,\n                       \"Error writing tile cache file for FloatImage \"\n                       \"instance: %s\\n\", strerror (errno));\n              // and exit.\n              exit (EXIT_FAILURE);\n            }\n          }\n        }\n        // Finish writing the bottom of the tile for which there is no\n        // image data (should only happen if we are on the last strip of\n        // tiles).\n        for ( ; kk < self->tile_size ; kk++ ) {\n          g_assert (ii == self->tile_count_y - 1);\n          write_count = fwrite (zero_line, sizeof (float), self->tile_size,\n                                self->tile_file);\n          // If we wrote less than expected,\n          if ( write_count < self->tile_size ) {\n            // it must have been a write error (probably no space left),\n            g_assert (ferror (self->tile_file));\n            // so print an error message,\n            fprintf (stderr,\n                     \"Error writing tile cache file for FloatImage instance: \"\n                     \"%s\\n\", strerror (errno));\n            // and exit.\n            exit (EXIT_FAILURE);\n          }\n        }\n      }\n    }\n\n    // Did we write the correct total amount of data?\n    g_assert (FTELL64 (self->tile_file)\n        == (off_t) (self->tile_area * self->tile_count * sizeof (float)));\n\n    // Free temporary buffers.\n    g_free (buffer);\n    g_free (zero_line);\n  }\n\n  // Everything fits in the cache (at the moment this means everything\n  // fits in the first tile, which is a bit of a FIXME), so just put\n  // it there.\n  else {\n    self->tile_addresses[0] = self->cache;\n\n    size_t ii;\n    for ( ii = 0 ; ii < self->size_y ; ii++ ) {\n      // Address where the current row of pixels should end up.\n      float *row_address = self->tile_addresses[0] + ii * self->tile_size;\n\n      // Read the data.\n      size_t read_count = fread (row_address, sizeof (float), self->size_x,\n         fp);\n      g_assert (read_count == self->size_x);\n\n      // Convert from the byte order on disk to the host byte order,\n      // if necessary.  Doing this with floats is somewhat\n      // questionable: major libraries don't seem to support it with\n      // their macros, and the perl documentation says it can't be\n      // done in a truly portable way... but it seems to work.\n      if ( non_native_byte_order (byte_order) ) {\n  g_assert (sizeof (float) == 4);\n  size_t jj;\n  for ( jj = 0 ; jj < self->size_x ; jj++ ) {\n    swap_bytes_32 ((unsigned char *) &(row_address[jj]));\n  }\n      }\n    }\n  }\n\n  return self;\n}\n\nFloatImage *\nfloat_image_new_from_file_scaled (ssize_t size_x, ssize_t size_y,\n                                  ssize_t original_size_x,\n                                  ssize_t original_size_y,\n                                  const char *file, off_t offset,\n                                  float_image_byte_order_t byte_order)\n{\n  g_assert (size_x > 0 && size_y > 0);\n  g_assert (original_size_x > 0 && original_size_y > 0);\n\n  // Image can only be scaled down with this routine, not up.\n  g_assert (size_x < original_size_x);\n  g_assert (size_y < original_size_y);\n\n  // Check in advance if the source file looks big enough (we will\n  // still need to check return codes as we read() data, of course).\n  g_assert (is_large_enough (file,\n           offset + ((off_t) original_size_x\n               * original_size_y\n               * sizeof (float))));\n\n  // Find the stride that we need to use in each dimension to evenly\n  // cover the original image space.\n  double stride_x = (size_x == 1 ? 0.0\n         : (double) (original_size_x - 1) / (size_x - 1));\n  double stride_y = (size_y == 1 ? 0.0\n         : (double) (original_size_y - 1) / (size_y - 1));\n\n  // Open the file to read data from.\n  FILE *fp = fopen (file, \"rb\");\n  // FIXME: we need some error handling and propagation here.\n  g_assert (fp != NULL);\n\n  // We will do a row at a time to save some possibly expensive\n  // seeking.  So here we have an entire row worth of upper lefts,\n  // upper rights, etc.\n  float *uls = g_new (float, size_x);\n  float *urs = g_new (float, size_x);\n  float *lls = g_new (float, size_x);\n  float *lrs = g_new (float, size_x);\n\n  // Results of bilinear interpolation for the current row.\n  float *interpolated_values = g_new (float, size_x);\n\n  // We will write the reduced resolution version of the image into a\n  // temporary file so we can leverage the new_from_file method and\n  // avoid trying to stick the whole reduced resolution image in\n  // memory.\n  FILE *reduced_image = tmpfile ();\n\n  ssize_t ii, jj;\n  for ( ii = 0 ; ii < size_y ; ii++ ) {\n    size_t read_count;          // For fread calls.\n    int return_code;            // For FSEEK64 calls.\n    // Input image y index of row above row of interest.\n    ssize_t in_ray = floor (ii * stride_y);\n    // Due to the vagaries of floating point arithmetic, we might run\n    // past the index of our last pixel by a little bit, so we correct.\n    if ( in_ray >= original_size_y - 1 ) {\n      // We better not be much over the last index though.\n      g_assert (in_ray < original_size_y);\n      // The index should be an integer, so floor should fix us up.\n      in_ray = floor (in_ray);\n      g_assert (in_ray == original_size_y - 1);\n    }\n    g_assert (in_ray < original_size_y);\n    // Input image y index of row below row of interest.  If we would\n    // be off the image, we just take the last row a second time, and\n    // let the interpolation work things out.\n    ssize_t in_rby;\n    if ( in_ray == original_size_y - 1 ) {\n      in_rby = in_ray;\n    }\n    else {\n      in_rby = in_ray + 1;\n    }\n    // Fetch the row above.\n    for ( jj = 0 ; jj < size_x ; jj++ ) {\n      // Input image indicies of current upper left corner pixel.\n      ssize_t in_ul_x = floor (jj * stride_x);\n      // Watch for floating point inexactness (see comment above).\n      if ( G_UNLIKELY (in_ul_x >= original_size_x - 1) ) {\n        g_assert (in_ul_x < original_size_x);\n        in_ul_x = floor (in_ul_x);\n        g_assert (in_ul_x == original_size_x - 1);\n      }\n      g_assert (in_ul_x < original_size_x);\n      size_t in_ul_y = in_ray;\n      off_t sample_offset\n  = offset + sizeof (float) * ((off_t) in_ul_y * original_size_x\n             + in_ul_x);\n      return_code = FSEEK64 (fp, sample_offset, SEEK_SET);\n      g_assert (return_code == 0);\n      read_count = fread (&(uls[jj]), sizeof (float), 1, fp);\n      g_assert (read_count == 1);\n      // If the upper left pixel was the last pixel in the input image,\n      if ( in_ul_x == original_size_x - 1 ) {\n        // just treat it as the upper right as well,\n        urs[jj] = uls[jj];\n      }\n      // otherwise read the next pixel as the upper right pixel.\n      else {\n        read_count = fread (&(urs[jj]), sizeof (float), 1, fp);\n        g_assert (read_count == 1);\n      }\n    }\n    // Fetch the row below.\n    for ( jj = 0 ; jj < size_x ; jj++ ) {\n      // Input image indicies of the lower left corner pixel.\n      ssize_t in_ll_x = floor (jj * stride_x);\n      // Watch for floating point inexactness (see comment above).\n      if ( G_UNLIKELY (in_ll_x >= original_size_y - 1) ) {\n        g_assert (in_ll_x < original_size_x);\n        in_ll_x = floor (in_ll_x);\n        g_assert (in_ll_x == original_size_x - 1);\n      }\n      g_assert (in_ll_x < original_size_x);\n      size_t in_ll_y = in_rby;\n      off_t sample_offset\n  = offset + sizeof (float) * ((off_t) in_ll_y * original_size_x\n             + in_ll_x);\n      return_code = FSEEK64 (fp, sample_offset, SEEK_SET);\n      g_assert (return_code == 0);\n      read_count = fread (&(lls[jj]), sizeof (float), 1, fp);\n      g_assert (read_count == 1);\n      // If the lower left pixel was the last pixel in the input image,\n      if ( in_ll_x == original_size_x - 1 ) {\n        // just treat it as the lower right as well,\n        lrs[jj] = lls[jj];\n      }\n      // otherwise read the next pixel as the lower right pixel.\n      else {\n        read_count = fread (&(lrs[jj]), sizeof (float), 1, fp);\n        g_assert (read_count == 1);\n      }\n    }\n    // If things aren't in the native byte order, we must byte swap them.\n    if ( non_native_byte_order (byte_order) ) {\n      for ( jj = 0 ; jj < size_x ; jj++ ) {\n        g_assert (sizeof (float) == 4);\n        swap_bytes_32 ((unsigned char *) &(uls[jj]));\n        swap_bytes_32 ((unsigned char *) &(urs[jj]));\n        swap_bytes_32 ((unsigned char *) &(lls[jj]));\n        swap_bytes_32 ((unsigned char *) &(lrs[jj]));\n      }\n    }\n    // Perform the interpolation.\n    for ( jj = 0 ; jj < size_x ; jj++ ) {\n      double delta_x = stride_x * jj - floor (stride_x * jj);\n      double delta_y = -(stride_y * ii - floor (stride_y * ii));\n      interpolated_values[jj] = bilinear_interpolate (delta_x, delta_y,\n                                                      uls[jj], urs[jj],\n                                                      lls[jj], lrs[jj]);\n    }\n    size_t write_count = fwrite (interpolated_values, sizeof (float), size_x,\n                                 reduced_image);\n    g_assert (write_count == (size_t) size_x);\n  }\n\n  // We are done with the temporary buffers.\n  g_free (interpolated_values);\n  g_free (lrs);\n  g_free (lls);\n  g_free (urs);\n  g_free (uls);\n\n  // Reposition to the beginning of the temporary file to fit with\n  // operation of new_from_file_pointer method.\n  int return_code = FSEEK64 (reduced_image, (off_t) 0, SEEK_SET);\n  g_assert (return_code == 0);\n\n  // The file we have written should be in host byte order, so we need\n  // to determine what that is so we can re-read it correctly.\n  float_image_byte_order_t host_byte_order;\n#if G_BYTE_ORDER == G_LITTLE_ENDIAN\n  host_byte_order = FLOAT_IMAGE_BYTE_ORDER_LITTLE_ENDIAN;\n#elif G_BYTE_ORDER == G_BIG_ENDIAN\n  host_byte_order = FLOAT_IMAGE_BYTE_ORDER_BIG_ENDIAN;\n#else\n#  error\n#endif\n\n  // Slurp the scaled file back in as an instance.\n  FloatImage *self\n    = float_image_new_from_file_pointer (size_x, size_y, reduced_image,\n                                         (off_t) 0, host_byte_order);\n\n  // Now that we have an instantiated version of the image we are done\n  // with this temporary file.\n  return_code = fclose (reduced_image);\n\n  return self;\n}\n\n// Returns a new FloatImage, for the image corresponding to the given metadata.\nFloatImage *\nfloat_image_new_from_metadata(meta_parameters *meta, const char *file)\n{\n  //return float_image_new_from_file(meta->general->sample_count,\n  //    meta->general->line_count, file, 0,\n  //    FLOAT_IMAGE_BYTE_ORDER_BIG_ENDIAN);\n  return float_image_band_new_from_metadata(meta, 0, file);\n}\n\n// Returns a new FloatImage, for the image band corresponding to the\n// given metadata.\nFloatImage *\nfloat_image_band_new_from_metadata(meta_parameters *meta,\n           int band, const char *file)\n{\n    int nl = meta->general->line_count;\n    int ns = meta->general->sample_count;\n\n    FILE * fp = FOPEN(file, \"rb\");\n    FloatImage * fi = float_image_new(ns, nl);\n\n    int i,j;\n    float *buf = MALLOC(sizeof(float)*ns);\n    for (i = 0; i < nl; ++i) {\n        get_float_line(fp, meta, i+band*nl, buf);\n        for (j = 0; j < ns; ++j)\n\t  if (meta->general->radiometry >= r_SIGMA_DB &&\n\t      meta->general->radiometry <= r_GAMMA_DB)\n            float_image_set_pixel(fi, j, i, pow(10, buf[j]/10.0));\n\t  else\n            float_image_set_pixel(fi, j, i, buf[j]);\n        asfPercentMeter((float)i/(float)(nl-1));\n    }\n\n    free(buf);\n    fclose(fp);\n\n    return fi;\n}\n\n// Copy the contents of tile with flattened offset tile_offset from\n// the memory cache to the disk file.  Its probably easiest to\n// understand this function by looking at how its used.\nstatic void\ncached_tile_to_disk (FloatImage *self, size_t tile_offset)\n{\n  // If we aren't using a tile file, this operation doesn't make\n  // sense.\n  g_assert (self->tile_file != NULL);\n\n  // We must have a legitimate tile_offset.\n  g_assert (tile_offset < self->tile_count);\n\n  // The tile we are trying to copy from cache to disk must be loaded\n  // in the cache for this operation to make sense.\n  g_assert (self->tile_addresses[tile_offset] != NULL);\n\n  int return_code\n    = FSEEK64 (self->tile_file,\n        (off_t) tile_offset * self->tile_area * sizeof (float),\n        SEEK_SET);\n  g_assert (return_code == 0);\n  size_t write_count = fwrite (self->tile_addresses[tile_offset],\n             sizeof (float), self->tile_area,\n             self->tile_file);\n  g_assert (write_count == self->tile_area);\n}\n\n// Return true iff tile (x, y) is already loaded into the memory cache.\nstatic gboolean\ntile_is_loaded (FloatImage *self, ssize_t x, ssize_t y)\n{\n  g_assert (    x >= 0 && (size_t) x < self->tile_count_x\n             && y >= 0 && (size_t) y < self->tile_count_y );\n\n  size_t tile_offset = self->tile_count_x * y + x;\n\n  return self->tile_addresses[tile_offset] != NULL;\n}\n\n// Load (currently unloaded) tile (x, y) from disk cache into memory\n// cache, possibly displacing the oldest tile already loaded, updating\n// the load order queue, and returning the address of the tile loaded.\nstatic float *\nload_tile (FloatImage *self, ssize_t x, ssize_t y)\n{\n  // Make sure we haven't screwed up somehow and not created a tile\n  // file when in fact we should have.\n  g_assert (self->tile_file != NULL);\n\n  g_assert (!tile_is_loaded (self, x, y));\n\n  // Address into which tile gets loaded (to be returned).\n  float *tile_address;\n\n  // Offset of tile in flattened array.\n  size_t tile_offset = self->tile_count_x * y + x;\n\n  // We have to check and see if we have to displace an already loaded\n  // tile or not.\n  if ( self->tile_queue->length == self->cache_size_in_tiles ) {\n    // Displace tile loaded longest ago.\n    size_t oldest_tile\n      = GPOINTER_TO_INT (g_queue_pop_tail (self->tile_queue));\n    cached_tile_to_disk (self, oldest_tile);\n    tile_address = self->tile_addresses[oldest_tile];\n    self->tile_addresses[oldest_tile] = NULL;\n  }\n  else {\n    // Load tile into first free slot.\n    tile_address = self->cache + self->tile_queue->length * self->tile_area;\n  }\n\n  // Put the new tile address into the index, and put the index into\n  // the load order queue.\n  self->tile_addresses[tile_offset] = tile_address;\n  // Stash in queue by converting to a pointer (so it must fit in an int).\n  g_assert (tile_offset < INT_MAX);\n  g_queue_push_head (self->tile_queue,\n                     GINT_TO_POINTER ((int) tile_offset));\n\n  // Load the tile data.\n  int return_code\n    = FSEEK64 (self->tile_file,\n              (off_t) tile_offset * self->tile_area * sizeof (float),\n              SEEK_SET);\n  g_assert (return_code == 0);\n  clearerr (self->tile_file);\n  size_t read_count = fread (tile_address, sizeof (float), self->tile_area,\n                             self->tile_file);\n  if ( read_count < self->tile_area ) {\n    if ( ferror (self->tile_file) ) {\n      perror (\"error reading tile cache file\");\n      g_assert_not_reached ();\n    }\n    if ( feof (self->tile_file) ) {\n      fprintf (stderr,\n               \"nothing left to read in tile cache file at offset %lld\\n\",\n               FTELL64 (self->tile_file));\n      g_assert_not_reached ();\n    }\n  }\n  g_assert (read_count == self->tile_area);\n\n  return tile_address;\n}\n\nfloat\nfloat_image_get_pixel (FloatImage *self, ssize_t x, ssize_t y)\n{\n  // Are we at a valid image pixel?\n  asfRequire (x >= 0 && (size_t) x < self->size_x,\n              \"%d >= 0 && %d < %d\\n\"\n              \"Invalid pixel index in the x dimension\\n\",\n              (int)x, (int)x, (int)(self->size_x));\n  asfRequire (y >= 0 && (size_t) y < self->size_y,\n              \"%d >= 0 && %d < %d\\n\"\n              \"Invalid pixel index in the y dimension\\n\",\n              (int)y, (int)y, (int)(self->size_y));\n\n  // Get the pixel coordinates, including tile and pixel-in-tile.\n  g_assert (sizeof (long int) >= sizeof (size_t));\n  ldiv_t pc_x = ldiv (x, self->tile_size), pc_y = ldiv (y, self->tile_size);\n\n  // Offset of tile x, y, where tiles are viewed as pixels normally are.\n  size_t tile_offset = self->tile_count_x * pc_y.quot + pc_x.quot;\n\n  // Address of data for tile containing pixel of interest (may still\n  // have to be loaded from disk cache).\n  float *tile_address = self->tile_addresses[tile_offset];\n\n  // Load the tile containing the pixel of interest if necessary.\n  if ( G_UNLIKELY (tile_address == NULL) ) {\n    tile_address = load_tile (self, pc_x.quot, pc_y.quot);\n  }\n\n  // Return pixel of interest.\n  return tile_address[self->tile_size * pc_y.rem + pc_x.rem];\n}\n\nvoid\nfloat_image_set_pixel (FloatImage *self, ssize_t x, ssize_t y, float value)\n{\n  // Are we at a valid image pixel?\n  g_assert (x >= 0 && (size_t) x <= self->size_x);\n  g_assert (y >= 0 && (size_t) y <= self->size_y);\n\n  // Get the pixel coordinates, including tile and pixel-in-tile.\n  g_assert (sizeof (long int) >= sizeof (size_t));\n  ldiv_t pc_x = ldiv (x, self->tile_size), pc_y = ldiv (y, self->tile_size);\n\n  // Offset of tile x, y, where tiles are viewed as pixels normally are.\n  size_t tile_offset = self->tile_count_x * pc_y.quot + pc_x.quot;\n\n  // Address of data for tile containing pixel of interest (may still\n  // have to be loaded from disk cache).\n  float *tile_address = self->tile_addresses[tile_offset];\n\n  // Load the tile containing the pixel of interest if necessary.\n  if ( G_UNLIKELY (tile_address == NULL) ) {\n    tile_address = load_tile (self, pc_x.quot, pc_y.quot);\n  }\n\n  // Set pixel of interest.\n  tile_address[self->tile_size * pc_y.rem + pc_x.rem] = value;\n}\n\nvoid\nfloat_image_get_region (FloatImage *self, ssize_t x, ssize_t y, ssize_t size_x,\n                        ssize_t size_y, float *buffer)\n{\n  g_assert (self->reference_count > 0); // Harden against missed ref=1 in new\n\n  g_assert (size_x >= 0);\n  g_assert (x >= 0);\n  g_assert ((size_t) x + (size_t) size_x - 1 < self->size_x);\n  g_assert (size_y >= 0);\n  g_assert (y >= 0);\n  g_assert ((size_t) y + (size_t) size_y - 1 < self->size_y);\n\n  ssize_t ii, jj;               // Index variables.\n  for ( ii = 0 ; ii < size_y ; ii++ ) {\n    for ( jj = 0 ; jj < size_x ; jj++ ) {\n      // We are essentially returning a subimage from the big image.\n      // These are the indicies in the big image (self) of the current\n      // pixel.\n      size_t ix = x + jj, iy = y + ii;\n      buffer[ii * size_x + jj] = float_image_get_pixel (self, ix, iy);\n    }\n  }\n}\n\nvoid\nfloat_image_set_region (FloatImage *self, size_t x, size_t y, size_t size_x,\n                        size_t size_y, float *buffer)\n{\n  g_assert_not_reached ();      // Stubbed out for now.\n  self = self; x = x; y = y; size_x = size_x, size_y = size_y; buffer = buffer;\n}\n\nvoid\nfloat_image_get_row (FloatImage *self, size_t row, float *buffer)\n{\n  float_image_get_region (self, 0, row, self->size_x, 1, buffer);\n}\n\nfloat\nfloat_image_get_pixel_with_reflection (FloatImage *self, ssize_t x, ssize_t y)\n{\n  // Reflect at image edges as advertised.\n  if ( x < 0 ) {\n    x = -x;\n  }\n  else if ( (size_t) x >= self->size_x ) {\n    x = self->size_x - 2 - (x - self->size_x);\n  }\n  if ( y < 0 ) {\n    y = -y;\n  }\n  else if ( (size_t) y >= self->size_y ) {\n    y = self->size_y - 2 - (y - self->size_y);\n  }\n\n  return float_image_get_pixel (self, x, y);\n}\n\n\nvoid\nfloat_image_statistics (FloatImage *self, float *min, float *max,\n                        float *mean, float *standard_deviation, float mask)\n{\n  g_assert (self->reference_count > 0); // Harden against missed ref=1 in new\n\n  *min = FLT_MAX;\n  *max = -FLT_MAX;\n\n  // Buffer for one row of samples.\n  float *row_buffer = g_new (float, self->size_x);\n\n  // Its best to keep track of things internally using doubles in\n  // order to minimize error buildup.\n  double mean_as_double = 0;\n  double s = 0;\n\n  size_t sample_count = 0;      // Samples considered so far.\n  size_t ii, jj;\n  for ( ii = 0 ; ii < self->size_y ; ii++ ) {\n    asfPercentMeter((double)ii/(double)(self->size_y));\n    float_image_get_row (self, ii, row_buffer);\n    for ( jj = 0 ; jj < self->size_x ; jj++ ) {\n      float cs = row_buffer[jj];   // Current sample.\n      if ( !isnan (mask) && (gsl_fcmp (cs, mask, 0.00000000001) == 0) )\n        continue;\n      if ( G_UNLIKELY (cs < *min) ) { *min = cs; }\n      if ( G_UNLIKELY (cs > *max) ) { *max = cs; }\n      double old_mean = mean_as_double;\n      mean_as_double += (cs - mean_as_double) / (sample_count + 1);\n      s += (cs - old_mean) * (cs - mean_as_double);\n      sample_count++;\n    }\n  }\n  asfPercentMeter(1.0);\n\n  g_free (row_buffer);\n\n  if (*min == FLT_MAX || *max == -FLT_MAX)\n      asfPrintError (\"Image did not contain any valid data!\\n\");\n\n  double standard_deviation_as_double = sqrt (s / (sample_count - 1));\n\n  g_assert (fabs (mean_as_double) <= FLT_MAX);\n  g_assert (fabs (standard_deviation_as_double) <= FLT_MAX);\n\n  *mean = mean_as_double;\n  *standard_deviation = standard_deviation_as_double;\n}\n\nint\nfloat_image_band_statistics (FloatImage *self, meta_stats *stats,\n                             int line_count, int band_no, float mask)\n{\n  g_assert (self->reference_count > 0); // Harden against missed ref=1 in new\n\n  stats->min = FLT_MAX;\n  stats->max = -FLT_MAX;\n\n  // Buffer for one row of samples.\n  float *row_buffer = g_new (float, self->size_x);\n\n  // Its best to keep track of things internally using doubles in\n  // order to minimize error buildup.\n  double mean_as_double = 0;\n  double s = 0;\n\n  size_t sample_count = 0;      // Samples considered so far.\n  size_t ii, jj;\n  for ( ii = (band_no * line_count); // 0-ordered band number times lines is offset into image\n        ii < ((size_t)band_no+1) * line_count && ii < self->size_y;\n        ii++ )\n  {\n    asfPercentMeter( (double)(ii - band_no*line_count)/(double)line_count );\n    float_image_get_row (self, ii, row_buffer);\n    for ( jj = 0 ; jj < self->size_x ; jj++ ) {\n      float cs = row_buffer[jj];   // Current sample.\n      if ( !isnan (mask) && (gsl_fcmp (cs, mask, 0.00000000001) == 0) )\n        continue;\n      if ( G_UNLIKELY (cs < stats->min) ) { stats->min = cs; }\n      if ( G_UNLIKELY (cs > stats->max) ) { stats->max = cs; }\n      double old_mean = mean_as_double;\n      mean_as_double += (cs - mean_as_double) / (sample_count + 1);\n      s += (cs - old_mean) * (cs - mean_as_double);\n      sample_count++;\n    }\n  }\n  asfPercentMeter(1.0);\n\n  g_free (row_buffer);\n\n  if (stats->min == FLT_MAX || stats->max == -FLT_MAX)\n    return 1;\n\n  double standard_deviation_as_double = sqrt (s / (sample_count - 1));\n\n  if (fabs (mean_as_double) > FLT_MAX ||\n      fabs (standard_deviation_as_double) > FLT_MAX)\n    return 1;\n\n  stats->mean = mean_as_double;\n  stats->std_deviation = standard_deviation_as_double;\n\n  return 0;\n}\n\nvoid\nfloat_image_statistics_with_mask_interval (FloatImage *self, float *min,\n             float *max, float *mean,\n             float *standard_deviation,\n             double interval_start,\n             double interval_end)\n{\n  g_assert (self->reference_count > 0); // Harden against missed ref=1 in new\n\n  *min = FLT_MAX;\n  *max = -FLT_MAX;\n\n  // Buffer for one row of samples.\n  float *row_buffer = g_new (float, self->size_x);\n\n  // Its best to keep track of things internally using doubles in\n  // order to minimize error buildup.\n  double mean_as_double = 0;\n  double s = 0;\n\n  size_t sample_count = 0;      // Samples considered so far.\n  size_t ii, jj;\n  for ( ii = 0 ; ii < self->size_y ; ii++ ) {\n    float_image_get_row (self, ii, row_buffer);\n    for ( jj = 0 ; jj < self->size_x ; jj++ ) {\n      float cs = row_buffer[jj];   // Current sample.\n      // If in the mask interval, do not consider this pixel any further.\n      if ( cs >= interval_start && cs <= interval_end ) {\n  continue;\n      }\n      if ( G_UNLIKELY (cs < *min) ) { *min = cs; }\n      if ( G_UNLIKELY (cs > *max) ) { *max = cs; }\n      double old_mean = mean_as_double;\n      mean_as_double += (cs - mean_as_double) / (sample_count + 1);\n      s += (cs - old_mean) * (cs - mean_as_double);\n      sample_count++;\n    }\n  }\n\n  g_free (row_buffer);\n\n  if (*min == FLT_MAX || *max == -FLT_MAX)\n      asfPrintError (\"Image did not contain any valid data!\\n\");\n\n  double standard_deviation_as_double = sqrt (s / (sample_count - 1));\n\n  g_assert (fabs (mean_as_double) <= FLT_MAX);\n  g_assert (fabs (standard_deviation_as_double) <= FLT_MAX);\n\n  *mean = mean_as_double;\n  *standard_deviation = standard_deviation_as_double;\n}\n\nvoid\nfloat_image_approximate_statistics (FloatImage *self, size_t stride,\n                                    float *mean, float *standard_deviation,\n                                    float mask)\n{\n  // Rows and columns of samples that fit in image given stride\n  // stride.\n  size_t sample_columns = ceil (self->size_x / stride);\n  size_t sample_rows = ceil (self->size_y / stride);\n  // Total number of samples.\n  size_t sample_count = sample_columns * sample_rows;\n\n  // Create an image holding the sample values.\n  FloatImage *sample_image = float_image_new (sample_columns, sample_rows);\n\n  // Load the sample values.\n  size_t current_sample = 0;\n  size_t ii;\n  for ( ii = 0 ; ii < sample_columns ; ii++ ) {\n    size_t jj;\n    for ( jj = 0 ; jj < sample_rows ; jj++ ) {\n      double sample = float_image_get_pixel (self, ii * stride, jj * stride);\n      float_image_set_pixel (sample_image, ii, jj, sample);\n      current_sample++;\n    }\n  }\n\n  // Ensure that we got the right number of samples in our image.\n  g_assert (current_sample == sample_count);\n\n  // Compute the exact statistics of the sampled version of the image.\n  // The _statistics method wants to compute min and max, so we let\n  // it, even though we don't do anything with them (since they are\n  // inaccurate).\n  float min, max;\n  float_image_statistics (sample_image, &min, &max, mean, standard_deviation,\n                          mask);\n\n  float_image_free (sample_image);\n}\n\nvoid\nfloat_image_approximate_statistics_with_mask_interval\n  (FloatImage *self, size_t stride, float *mean, float *standard_deviation,\n   double interval_start, double interval_end)\n{\n  // This method is a trivial clone-and-modify of\n  // float_image_approximate_statistics, but it is totally untested at\n  // the moment.\n  g_assert_not_reached ();\n\n  // Rows and columns of samples that fit in image given stride\n  // stride.\n  size_t sample_columns = ceil (self->size_x / stride);\n  size_t sample_rows = ceil (self->size_y / stride);\n  // Total number of samples.\n  size_t sample_count = sample_columns * sample_rows;\n\n  // Create an image holding the sample values.\n  FloatImage *sample_image = float_image_new (sample_columns, sample_rows);\n\n  // Load the sample values.\n  size_t current_sample = 0;\n  size_t ii;\n  for ( ii = 0 ; ii < sample_columns ; ii++ ) {\n    size_t jj;\n    for ( jj = 0 ; jj < sample_rows ; jj++ ) {\n      double sample = float_image_get_pixel (self, ii * stride, jj * stride);\n      float_image_set_pixel (sample_image, ii, jj, sample);\n      current_sample++;\n    }\n  }\n\n  // Ensure that we got the right number of samples in our image.\n  g_assert (current_sample == sample_count);\n\n  // Compute the exact statistics of the sampled version of the image.\n  // The _statistics method wants to compute min and max, so we let\n  // it, even though we don't do anything with them (since they are\n  // inaccurate).\n  float min, max;\n  float_image_statistics_with_mask_interval (sample_image, &min, &max,\n               mean, standard_deviation,\n               interval_start, interval_end);\n\n  float_image_free (sample_image);\n}\n\ngsl_histogram *\nfloat_image_gsl_histogram (FloatImage *self, float min, float max,\n                           size_t num_bins)\n{\n  g_assert (self->reference_count > 0); // Harden against missed ref=1 in new\n\n  // Initialize the histogram.\n  gsl_histogram *hist = gsl_histogram_alloc (num_bins);\n  gsl_histogram_set_ranges_uniform (hist, min, max);\n\n  // Buffer for one row of samples.\n  float *row_buffer = g_new (float, self->size_x);\n\n  // Populate the histogram over every sample in the image.\n  size_t ii, jj;\n  for (ii = 0 ; ii < self->size_y ; ii++ ) {\n    float_image_get_row (self, ii, row_buffer);\n    for ( jj = 0 ; jj < self->size_x ; jj++ ) {\n      gsl_histogram_increment (hist, row_buffer[jj]);\n    }\n  }\n\n  g_free (row_buffer);\n\n  return hist;\n}\n\n\nfloat\nfloat_image_apply_kernel (FloatImage *self, ssize_t x, ssize_t y,\n                          gsl_matrix_float *kernel)\n{\n  g_assert (self->reference_count > 0); // Harden against missed ref=1 in new\n\n  g_assert (x >= 0 && (size_t) x < self->size_x);\n  g_assert (y >= 0 && (size_t) y < self->size_y);\n  g_assert (kernel->size2 % 2 == 1);\n  g_assert (kernel->size2 == kernel->size1);\n\n  size_t ks = kernel->size2;    // Kernel size.\n\n  float sum = 0;                // Result.\n\n  size_t ii;\n  for ( ii = 0 ; ii < kernel->size1 ; ii++ ) {\n    ssize_t iy = y - ks / 2 + ii; // Current image y pixel index.\n    size_t jj;\n    for ( jj = 0 ; jj < kernel->size2 ; jj++ ) {\n      ssize_t ix = x - ks / 2 + jj; // Current image x pixel index\n      sum += (gsl_matrix_float_get (kernel, jj, ii)\n              * float_image_get_pixel_with_reflection (self, ix, iy));\n    }\n  }\n\n  return sum;\n}\n\nfloat\nfloat_image_sample (FloatImage *self, float x, float y,\n                    float_image_sample_method_t sample_method)\n{\n  g_assert (x >= 0.0 && x <= (double) self->size_x - 1.0);\n  g_assert (y >= 0.0 && y <= (double) self->size_y - 1.0);\n\n  switch ( sample_method ) {\n\n  case FLOAT_IMAGE_SAMPLE_METHOD_NEAREST_NEIGHBOR:\n    return float_image_get_pixel (self, round (x), round (y));\n    break;\n\n  case FLOAT_IMAGE_SAMPLE_METHOD_BILINEAR:\n    {\n      // Indicies of points we are interpolating between (x below, y\n      // below, etc., where below is interpreted in the numerical\n      // sense, not the image orientation sense.).\n      size_t xb = floor (x), yb = floor (y), xa = ceil (x), ya = ceil (y);\n      size_t ts = self->tile_size;   // Convenience alias.\n      // Offset of xb, yb, etc. relative to tiles they lie in.\n      size_t xbto = xb % ts, ybto = yb % ts, xato = xa % ts, yato = ya % ts;\n      // Values of points we are interpolating between.\n      float ul, ur, ll, lr;\n\n      // If the points were are interpolating between don't span a\n      // tile edge, we load them straight from tile memory to save\n      // some time.\n      if ( G_LIKELY (   xbto != ts - 1 && xato != 0\n                     && ybto != ts - 1 && yato != 0) ) {\n        // The tile indicies.\n        size_t tx = xb / ts, ty = yb / ts;\n        // Tile offset in flattened list of tile addresses.\n        size_t tile_offset = ty * self->tile_count_x + tx;\n        float *tile_address = self->tile_addresses[tile_offset];\n        if ( G_UNLIKELY (tile_address == NULL) ) {\n          tile_address = load_tile (self, tx, ty);\n        }\n        ul = tile_address[ybto * self->tile_size + xbto];\n        ur = tile_address[ybto * self->tile_size + xato];\n        ll = tile_address[yato * self->tile_size + xbto];\n        lr = tile_address[yato * self->tile_size + xato];\n      }\n      else {\n        // We are spanning a tile edge, so we just get the pixels\n        // using the inefficient but easy get_pixel method.\n        ul = float_image_get_pixel (self, floor (x), floor (y));\n        ur = float_image_get_pixel (self, ceil (x), floor (y));\n        ll = float_image_get_pixel (self, floor (x), ceil (y));\n        lr = float_image_get_pixel (self, ceil (x), ceil (y));\n      }\n\n      // Upper and lower values interpolated in the x direction.\n      float ux = ul + (ur - ul) * (x - floor (x));\n      float lx = ll + (lr - ll) * (x - floor (x));\n\n      return ux + (lx - ux) * (y - floor (y));\n    }\n    break;\n  case FLOAT_IMAGE_SAMPLE_METHOD_BICUBIC:\n    {\n      static gboolean first_time_through = TRUE;\n      // Splines in the x direction, and their lookup accelerators.\n      static double *x_indicies;\n      static double *values;\n      static gsl_spline **xss;\n      static gsl_interp_accel **xias;\n      // Spline between splines in the y direction, and lookup accelerator.\n      static double *y_spline_indicies;\n      static double *y_spline_values;\n      static gsl_spline *ys;\n      static gsl_interp_accel *yia;\n\n      // All these splines have size 4.\n      const size_t ss = 4;\n\n      size_t ii;                // Index variable.\n\n      if ( first_time_through ) {\n        // Allocate memory for the splines in the x direction.\n        x_indicies = g_new (double, ss);\n        values = g_new (double, ss);\n        xss = g_new (gsl_spline *, ss);\n        xias = g_new (gsl_interp_accel *, ss);\n        for ( ii = 0 ; ii < ss ; ii++ ) {\n          xss[ii] = gsl_spline_alloc (gsl_interp_cspline, ss);\n          xias[ii] = gsl_interp_accel_alloc ();\n        }\n\n        // Allocate memory for the spline in the y direction.\n        y_spline_indicies = g_new (double, ss);\n        y_spline_values = g_new (double, ss);\n        ys = gsl_spline_alloc (gsl_interp_cspline, ss);\n        yia = gsl_interp_accel_alloc ();\n        first_time_through = FALSE;\n      }\n\n      // Get the values for the nearest 16 points.\n      size_t jj;                // Index variable.\n      for ( ii = 0 ; ii < ss ; ii++ ) {\n        for ( jj = 0 ; jj < ss ; jj++ ) {\n          x_indicies[jj] = floor (x) - 1 + jj;\n          values[jj]\n            = float_image_get_pixel_with_reflection (self, x_indicies[jj],\n                                                     floor (y) - 1 + ii);\n        }\n        gsl_spline_init (xss[ii], x_indicies, values, ss);\n      }\n\n      // Set up the spline that runs in the y direction.\n      for ( ii = 0 ; ii < ss ; ii++ ) {\n        y_spline_indicies[ii] = floor (y) - 1 + ii;\n        y_spline_values[ii] = gsl_spline_eval (xss[ii], x, xias[ii]);\n      }\n      gsl_spline_init (ys, y_spline_indicies, y_spline_values, ss);\n\n      return (float) gsl_spline_eval (ys, y, yia);\n    }\n    break;\n  default:\n    g_assert_not_reached ();\n    return -42;         // Reassure the compiler.\n  }\n}\n\ngboolean\nfloat_image_equals (FloatImage *self, FloatImage *other, float epsilon)\n{\n  g_assert (self->reference_count > 0); // Harden against missed ref=1 in new\n\n  // Compare image sizes.\n  if ( self->size_x != other->size_x ) {\n    return FALSE;\n  }\n  if ( self->size_y != other->size_y ) {\n    return FALSE;\n  }\n\n  size_t sz_x = self->size_x; // Convenience alias.\n  size_t sz_y = self->size_y;\n\n  // Compare image pixels.\n  size_t ii, jj;\n  for ( ii = 0 ; ii < sz_y ; ii++ ) {\n    for ( jj = 0 ; jj < sz_x ; jj++ ) {\n      if ( G_UNLIKELY (gsl_fcmp (float_image_get_pixel (self, jj, ii),\n         float_image_get_pixel (other, jj, ii),\n         epsilon) != 0) ) {\n  return FALSE;\n      }\n    }\n  }\n\n  return TRUE;\n}\n\n// Flip an image about a horizontal line through the center of the image\nvoid\nfloat_image_flip_y(FloatImage *self)\n{\n  g_assert (self->reference_count > 0); // Harden against missed ref=1 in new\n\n  size_t ii, jj;\n\n  for (jj = 0; jj < self->size_y / 2; ++jj) {\n    size_t jj2 = self->size_y - 1 - jj;\n    for (ii = 0; ii < self->size_x; ++ii) {\n      float a = float_image_get_pixel(self, ii, jj);\n      float b = float_image_get_pixel(self, ii, jj2);\n      float_image_set_pixel(self, ii, jj, b);\n      float_image_set_pixel(self, ii, jj2, a);\n    }\n  }\n}\n\n// Flip an image about a vertical line through the center of the image\nvoid\nfloat_image_flip_x(FloatImage *self)\n{\n  g_assert (self->reference_count > 0); // Harden against missed ref=1 in new\n\n  size_t ii, jj;\n\n  for (ii = 0; ii < self->size_x / 2; ++ii) {\n    size_t ii2 = self->size_x - 1 - ii;\n    for (jj = 0; jj < self->size_y; ++jj) {\n      float a = float_image_get_pixel(self, ii, jj);\n      float b = float_image_get_pixel(self, ii2, jj);\n      float_image_set_pixel(self, ii, jj, b);\n      float_image_set_pixel(self, ii2, jj, a);\n    }\n  }\n}\n\n// Bring the tile cache file on the disk fully into sync with the\n// latest image data stored in the memory cache.\nstatic void\nsynchronize_tile_file_with_memory_cache (FloatImage *self)\n{\n  // If we aren't using a tile file, this operation doesn't make\n  // sense.\n  g_assert (self->tile_file != NULL);\n\n  guint ii;\n  for ( ii = 0 ; ii < self->tile_queue->length ; ii++ ) {\n    size_t tile_offset = GPOINTER_TO_INT (g_queue_peek_nth (self->tile_queue,\n                  ii));\n    cached_tile_to_disk (self, tile_offset);\n  }\n}\n\nvoid\nfloat_image_freeze (FloatImage *self, FILE *file_pointer)\n{\n  g_assert (self->reference_count > 0); // Harden against missed ref=1 in new\n\n  FILE *fp = file_pointer;  // Convenience alias.\n\n  g_assert (file_pointer != NULL);\n\n  size_t write_count = fwrite (&(self->size_x), sizeof (size_t), 1, fp);\n  g_assert (write_count == 1);\n\n  write_count = fwrite (&(self->size_y), sizeof (size_t), 1, fp);\n  g_assert (write_count == 1);\n\n  write_count = fwrite (&(self->cache_space), sizeof (size_t), 1, fp);\n  g_assert (write_count == 1);\n\n  write_count = fwrite (&(self->cache_area), sizeof (size_t), 1, fp);\n  g_assert (write_count == 1);\n\n  write_count = fwrite (&(self->tile_size), sizeof (size_t), 1, fp);\n  g_assert (write_count == 1);\n\n  write_count = fwrite (&(self->cache_size_in_tiles), sizeof (size_t), 1, fp);\n  g_assert (write_count == 1);\n\n  write_count = fwrite (&(self->tile_count_x), sizeof (size_t), 1, fp);\n  g_assert (write_count == 1);\n\n  write_count = fwrite (&(self->tile_count_y), sizeof (size_t), 1, fp);\n  g_assert (write_count == 1);\n\n  write_count = fwrite (&(self->tile_count), sizeof (size_t), 1, fp);\n  g_assert (write_count == 1);\n\n  write_count = fwrite (&(self->tile_area), sizeof (size_t), 1, fp);\n  g_assert (write_count == 1);\n\n  // We don't bother serializing the cache -- its a pain to keep track\n  // of and probably almost never worth it.\n\n  // We write the tile queue pointer away, so that when we later thaw\n  // the serialized version, we can tell if a cache file is in use or\n  // not (if it isn't tile_queue will be NULL).\n  write_count = fwrite (&(self->tile_queue), sizeof (GQueue *), 1, fp);\n  g_assert (write_count == 1);\n\n  // If there was no cache file...\n  if ( self->tile_queue == NULL ) {\n    // We store the contents of the first tile and are done.\n    write_count = fwrite (self->tile_addresses[0], sizeof (float),\n        self->tile_area, fp);\n    if ( write_count < self->tile_area ) {\n      if ( ferror (fp) ) {\n  fprintf (stderr, \"Error writing serialized FloatImage instance during \"\n     \"freeze: %s\\n\", strerror (errno));\n  exit (EXIT_FAILURE);\n      }\n    }\n    g_assert (write_count == self->tile_area);\n  }\n  // otherwise, the in memory cache needs to be copied into the tile\n  // file and the tile file saved in the serialized version of self.\n  else {\n    synchronize_tile_file_with_memory_cache (self);\n    float *buffer = g_new (float, self->tile_area);\n    size_t ii;\n    off_t tmp = FTELL64 (self->tile_file);\n    int return_code = FSEEK64 (self->tile_file, 0, SEEK_SET);\n    g_assert (return_code == 0);\n    for ( ii = 0 ; ii < self->tile_count ; ii++ ) {\n      size_t read_count = fread (buffer, sizeof (float), self->tile_area,\n         self->tile_file);\n      g_assert (read_count == self->tile_area);\n      write_count = fwrite (buffer, sizeof (float), self->tile_area, fp);\n      g_assert (write_count == self->tile_area);\n    }\n    return_code = FSEEK64 (self->tile_file, tmp, SEEK_SET);\n    g_assert (return_code == 0);\n    g_free (buffer);\n  }\n}\n\nint\nfloat_image_band_store(FloatImage *self, const char *file,\n           meta_parameters *meta, int append_flag)\n{\n  g_assert (self->reference_count > 0); // Harden against missed ref=1 in new\n\n  // Give status\n  if (meta->general->band_count == 1)\n    asfPrintStatus(\"Storing image ...\\n\");\n  else\n    asfPrintStatus(\"Storing band ...\\n\");\n\n  // Establish byte order\n  /*\n  float_image_byte_order_t byte_order = 0;\n  if (strcmp(meta->general->system, \"big_ieee\") == 0)\n    byte_order = FLOAT_IMAGE_BYTE_ORDER_BIG_ENDIAN;\n  else if (strcmp(meta->general->system, \"lil_ieee\") == 0)\n    byte_order = FLOAT_IMAGE_BYTE_ORDER_LITTLE_ENDIAN;\n  */\n\n  // Open the file to write to.\n  FILE *fp = fopen (file, append_flag ? \"ab\" : \"wb\");\n  // FIXME: we need some error handling and propagation here.\n  g_assert (fp != NULL);\n\n  // We will write the image data in horizontal stips one line at a time.\n  float *line_buffer = g_new (float, self->size_x);\n\n  // Sanity check\n  if (meta->general->line_count != (int)self->size_y ||\n      meta->general->sample_count != (int)self->size_x)\n  {\n      asfPrintError(\"Inconsistency between metadata and image!\\n\"\n                    \"Metadata says: %dx%d LxS, image has %dx%d\\n\"\n                    \"Possibly did not write metadata before storing image.\\n\",\n                    meta->general->line_count, meta->general->sample_count,\n                    self->size_y, self->size_x);\n  }\n\n  // Reorganize data into tiles in tile oriented disk file.\n  int ii;\n  for ( ii = 0 ; ii < (int)self->size_y ; ii++ ) {\n    float_image_get_row (self, ii, line_buffer);\n\n    // Write the data.\n    put_float_line(fp, meta, ii, line_buffer);\n  }\n\n  // Done with the line buffer.\n  g_free (line_buffer);\n\n  // Close file being written.\n  int return_code = fclose (fp);\n  g_assert (return_code == 0);\n\n  // Return success code.\n  return 0;\n}\n\nint\nfloat_image_store (FloatImage *self, const char *file,\n                   float_image_byte_order_t byte_order)\n{\n  meta_parameters *meta;\n  meta = meta_read(file);\n\n  //float_image_byte_order_t meta_byte_order = 0;\n  //if (strcmp(meta->general->system, \"big_ieee\") == 0)\n  //  meta_byte_order = FLOAT_IMAGE_BYTE_ORDER_BIG_ENDIAN;\n  //else if (strcmp(meta->general->system, \"lil_ieee\") == 0)\n  //  meta_byte_order = FLOAT_IMAGE_BYTE_ORDER_LITTLE_ENDIAN;\n\n  //if (meta_byte_order != byte_order)\n  //    asfPrintWarning(\"Passed-in byte order overriden by metadata!\\n\");\n\n  int ret = float_image_band_store(self, file, meta, 0);\n  meta_free(meta);\n\n  return ret;\n}\n\n/*\n * JPEG ERROR HANDLING:\n *\n * Override the \"error_exit\" method so that control is returned to the\n * library's caller when a fatal error occurs, rather than calling exit()\n * as the standard error_exit method does.\n *\n * We use C's setjmp/longjmp facility to return control.  This means that the\n * routine which calls the JPEG library must first execute a setjmp() call to\n * establish the return point.  We want the replacement error_exit to do a\n * longjmp().  But we need to make the setjmp buffer accessible to the\n * error_exit routine.  To do this, we make a private extension of the\n * standard JPEG error handler object.  (If we were using C++, we'd say we\n * were making a subclass of the regular error handler.)\n *\n * Here's the extended error handler struct:\n */\nstruct my_error_mgr {\n  struct jpeg_error_mgr pub;  /* \"public\" fields */\n\n  jmp_buf setjmp_buffer;  /* for return to caller */\n};\n\ntypedef struct my_error_mgr * my_error_ptr;\n\nMETHODDEF(void)\nmy_error_exit (j_common_ptr cinfo)\n{\n  /* cinfo->err really points to a my_error_mgr struct, so coerce pointer */\n  my_error_ptr myerr = (my_error_ptr) cinfo->err;\n\n  /* Always display the message. */\n  /* We could postpone this until after returning, if we chose. */\n  (*cinfo->err->output_message) (cinfo);\n\n  /* Return control to the setjmp point */\n  longjmp(myerr->setjmp_buffer, 1);\n}\n\nint\nfloat_image_export_as_jpeg (FloatImage *self, const char *file,\n                            size_t max_dimension, double mask)\n{\n  g_assert (self->reference_count > 0); // Harden against missed ref=1 in new\n\n  //size_t scale_factor;          // Scale factor to use for output image.\n  float fscale_factor;\n  size_t scale_factor;\n  if ( self->size_x > self->size_y ) {\n    //scale_factor = ceil ((double) self->size_x / max_dimension);\n    fscale_factor = (float)self->size_x / (float)max_dimension;\n  }\n  else {\n    //scale_factor = ceil ((double) self->size_y / max_dimension);\n    fscale_factor = (float)self->size_y / (float)max_dimension;\n  }\n\n  // We want the scale factor to be odd, so that we can easily use a\n  // standard kernel to average things.\n  //if ( scale_factor % 2 == 0 ) {\n    //scale_factor++;\n  //}\n\n  // Output JPEG x and y dimensions.\n  scale_factor = (size_t)(fscale_factor + 0.5);\n  if (scale_factor < 1) {\n    // Someone tried to _grow_ the image rather than shrink it ...unsupported at this time!\n    asfPrintWarning(\"Maximum dimension that was selected is larger than the maximum\\n\"\n        \"dimension in the image.  Only scaling down is supported.  Defaulting to a\\n\"\n        \"scale factor of 1.0 (maintain original size.)\\n\");\n  }\n  scale_factor = scale_factor < 1 ? 1 : scale_factor;\n  size_t osx = (size_t)((float)self->size_x / (float)scale_factor);\n  size_t osy = (size_t)((float)self->size_y / (float)scale_factor);\n  while ((osx >= MIN_DIMENSION || osy >= MIN_DIMENSION) &&\n         (osx % 2 == 0         || osy % 2 == 0)         &&\n         scale_factor != 1)\n  {\n    // Fine tune scale factor until output image dimensions are odd\n    // in both directions so an odd-sized filter kernel will fit (odd\n    // sized kernels have a center pixel)\n    fscale_factor += 0.25;\n    scale_factor = (size_t)(fscale_factor + 0.5);\n    osx = (size_t)((float)self->size_x / (float)scale_factor);\n    osy = (size_t)((float)self->size_y / (float)scale_factor);\n  }\n  asfRequire(osx >= MIN_DIMENSION || osy >= MIN_DIMENSION, \"Output dimensions too small\");\n  size_t kernel_size = scale_factor;\n  kernel_size = kernel_size % 2 ? kernel_size : kernel_size - 1;\n\n  // Number of pixels in output image.\n  size_t pixel_count = osx * osy;\n\n  // Pixels of the output image.\n  unsigned char *pixels = g_new (unsigned char, pixel_count);\n\n  JSAMPLE test_jsample;         // For verifying properties of JSAMPLE type.\n  /* Here are some very funky checks to try to ensure that the JSAMPLE\n     really is the type we expect, so we can scale properly.  */\n  g_assert (sizeof (unsigned char) == 1);\n  g_assert (sizeof (unsigned char) == sizeof (JSAMPLE));\n  test_jsample = 0;\n  test_jsample--;\n  g_assert (test_jsample == UCHAR_MAX);\n\n  // Stuff needed by libjpeg.\n  struct jpeg_compress_struct cinfo;\n  struct my_error_mgr jerr;\n  //cinfo.err = jpeg_std_error (&jerr);\n  jpeg_create_compress (&cinfo);\n\n  // Open output file.\n  FILE *fp = fopen (file, \"wb\");\n  if ( fp == NULL ) {\n    printf(\"Error opening file %s: %s\\n\", file, strerror(errno));\n    return FALSE;\n  }\n\n  /* We set up the normal JPEG error routines, then override error_exit. */\n  cinfo.err = jpeg_std_error(&jerr.pub);\n  jerr.pub.error_exit = my_error_exit;\n  /* Establish the setjmp return context for my_error_exit to use. */\n  if (setjmp(jerr.setjmp_buffer)) {\n    /* If we get here, the JPEG code has signaled an error.\n     * We need to clean up the JPEG object, close the input file, and return.\n     */\n    jpeg_destroy_compress(&cinfo);\n    g_free(pixels);\n    fclose(fp);\n    return 1;\n  }\n  // Connect jpeg output to the output file to be used.\n  jpeg_stdio_dest (&cinfo, fp);\n\n  // Set image parameters that libjpeg needs to know about.\n  cinfo.image_width = osx;\n  cinfo.image_height = osy;\n  cinfo.input_components = 1;   // Grey scale => 1 color component / pixel.\n  cinfo.in_color_space = JCS_GRAYSCALE;\n  jpeg_set_defaults (&cinfo);   // Use default compression parameters.\n  // Reassure libjpeg that we will be writing a complete JPEG file.\n  jpeg_start_compress (&cinfo, TRUE);\n\n  // Gather image statistics so we know how to map image values into\n  // the output.\n  float min, max, mean, standard_deviation;\n  float_image_statistics (self, &min, &max, &mean, &standard_deviation, mask);\n\n  // If the statistics don't work, something is beastly wrong and we\n  // don't want to deal with it.\n#ifndef solaris\n#ifndef win32\n  // Solaris doesn't have isfinite().\n  g_assert (isfinite (min) && isfinite (max) && isfinite (mean)\n            && isfinite (standard_deviation));\n#endif\n#endif\n\n  // If min == max, the pixel values are all the same.  There is no\n  // reason to average or scale anything, so we don't.  There is a\n  // good chance that the user would like zero to correspond to black,\n  // so we do that.  Anything else will be pure white.\n  if ( min == max ) {\n    // FIXME: this path is broken.  The trouble is that much of the\n    // stuff after this if branch shouldn't happen if we do this, but\n    // some of it should.  So for now its disabled.\n    g_assert_not_reached ();\n    unsigned char oval;         // Output value to use.\n    if ( min == 0.0 ) {\n      oval = 0;\n    }\n    else {\n      oval = UCHAR_MAX;\n    }\n    size_t ii, jj;\n    for ( ii = 0 ; ii < osy ; ii++ ) {\n      for ( jj = 0 ; jj < osx ; jj++ ) {\n        pixels[ii * osx + jj] = oval;\n      }\n    }\n  }\n\n  // Range of input pixel values which are to be linearly scaled into\n  // the output (values outside this range will be clamped).\n  double lin_min = mean - 2 * standard_deviation;\n  double lin_max = mean + 2 * standard_deviation;\n\n  // As advertised, we will average pixels together.\n  //g_assert (scale_factor % 2 != 0);\n  //size_t kernel_size = scale_factor;\n  gsl_matrix_float *averaging_kernel = NULL;\n  size_t ii, jj;\n  if (scale_factor > 1) {\n    averaging_kernel = gsl_matrix_float_alloc (kernel_size, kernel_size);\n    float kernel_value = 1.0 / ((float)kernel_size * kernel_size);\n    for ( ii = 0 ; ii < averaging_kernel->size1 ; ii++ ) {\n      for ( jj = 0 ; jj < averaging_kernel->size2 ; jj++ ) {\n        gsl_matrix_float_set (averaging_kernel, ii, jj, kernel_value);\n      }\n    }\n  }\n\n    // Sample input image, putting scaled results into output image.\n  size_t sample_stride = scale_factor;\n  for ( ii = 0 ; ii < osy ; ii++ ) {\n    for ( jj = 0 ; jj < osx ; jj++ ) {\n      // Input image average pixel value.\n      float ival;\n      if (scale_factor > 1) {\n        ival = float_image_apply_kernel (self, jj * sample_stride,\n                                         ii * sample_stride,\n                                         averaging_kernel);\n      }\n      else if (scale_factor == 1) {\n        ival = float_image_get_pixel(self, jj, ii);\n      }\n      else {\n        asfPrintError(\"Invalid scale factor.  Scale factor must be 1 or greater.\\n\");\n      }\n      unsigned char oval;       // Output value.\n\n      if (!meta_is_valid_double(ival)) {\n        oval = 0;\n      }\n      else if ( ival < lin_min ) {\n        oval = 0;\n      }\n      else if ( ival > lin_max) {\n        oval = UCHAR_MAX;\n      }\n      else {\n        int oval_int\n            = round (((ival - lin_min) / (lin_max - lin_min)) * UCHAR_MAX);\n        // Make sure we haven't screwed up the scaling.\n        g_assert (oval_int >= 0 && oval_int <= UCHAR_MAX);\n        oval = oval_int;\n      }\n      pixels[ii * osx + jj] = oval;\n    }\n  }\n\n  if (averaging_kernel != NULL) gsl_matrix_float_free(averaging_kernel);\n\n  // Write the jpeg, one row at a time.\n  const int rows_to_write = 1;\n  JSAMPROW *row_pointer = g_new (JSAMPROW, rows_to_write);\n  while ( cinfo.next_scanline < cinfo.image_height ) {\n    int rows_written;\n    row_pointer[0] = &(pixels[cinfo.next_scanline * osx]);\n    rows_written = jpeg_write_scanlines (&cinfo, row_pointer, rows_to_write);\n    g_assert (rows_written == rows_to_write);\n  }\n  g_free (row_pointer);\n\n  // Finsh compression and close the jpeg.\n  jpeg_finish_compress (&cinfo);\n  int return_code = fclose (fp);\n  g_assert (return_code == 0);\n  jpeg_destroy_compress (&cinfo);\n\n  g_free (pixels);\n\n  return 0;                     // Return success indicator.\n}\n\nint\nfloat_image_export_as_jpeg_with_mask_interval (FloatImage *self,\n                 const char *file,\n                 ssize_t max_dimension,\n                 double interval_start,\n                 double interval_end)\n{\n  g_assert (self->reference_count > 0); // Harden against missed ref=1 in new\n\n  size_t scale_factor;          // Scale factor to use for output image.\n  if ( self->size_x > self->size_y ) {\n    scale_factor = ceil ((double) self->size_x / max_dimension);\n  }\n  else {\n    scale_factor = ceil ((double) self->size_y / max_dimension);\n  }\n\n  // We want the scale factor to be odd, so that we can easily use a\n  // standard kernel to average things.\n  if ( scale_factor % 2 == 0 ) {\n    scale_factor++;\n  }\n\n  // Output JPEG x and y dimensions.\n  size_t osx = self->size_x / scale_factor;\n  size_t osy = self->size_y / scale_factor;\n\n  // Number of pixels in output image.\n  size_t pixel_count = osx * osy;\n\n  // Pixels of the output image.\n  unsigned char *pixels = g_new (unsigned char, pixel_count);\n\n  JSAMPLE test_jsample;         // For verifying properties of JSAMPLE type.\n  /* Here are some very funky checks to try to ensure that the JSAMPLE\n     really is the type we expect, so we can scale properly.  */\n  g_assert (sizeof (unsigned char) == 1);\n  g_assert (sizeof (unsigned char) == sizeof (JSAMPLE));\n  test_jsample = 0;\n  test_jsample--;\n  g_assert (test_jsample == UCHAR_MAX);\n\n  // Stuff needed by libjpeg.\n  struct jpeg_compress_struct cinfo;\n  struct jpeg_error_mgr jerr;\n  cinfo.err = jpeg_std_error (&jerr);\n  jpeg_create_compress (&cinfo);\n\n  // Open output file.\n  FILE *fp = fopen (file, \"wb\");\n  if ( fp == NULL ) { perror (\"error opening file\"); }\n  // FIXME: we need some error handling and propagation here.\n  g_assert (fp != NULL);\n\n  // Connect jpeg output to the output file to be used.\n  jpeg_stdio_dest (&cinfo, fp);\n\n  // Set image parameters that libjpeg needs to know about.\n  cinfo.image_width = osx;\n  cinfo.image_height = osy;\n  cinfo.input_components = 1;   // Grey scale => 1 color component / pixel.\n  cinfo.in_color_space = JCS_GRAYSCALE;\n  jpeg_set_defaults (&cinfo);   // Use default compression parameters.\n  // Reassure libjpeg that we will be writing a complete JPEG file.\n  jpeg_start_compress (&cinfo, TRUE);\n\n  // Gather image statistics so we know how to map image values into\n  // the output.\n  float min, max, mean, standard_deviation;\n  float_image_statistics_with_mask_interval (self, &min, &max, &mean,\n               &standard_deviation,\n               interval_start,\n               interval_end);\n\n  // If the statistics don't work, something is beastly wrong and we\n  // don't want to deal with it.\n#ifndef solaris\n#ifndef win32\n  // Solaris doesn't have isfinite().\n  g_assert (isfinite (min) && isfinite (max) && isfinite (mean)\n            && isfinite (standard_deviation));\n#endif\n#endif\n\n  // If min == max, the pixel values are all the same.  There is no\n  // reason to average or scale anything, so we don't.  There is a\n  // good chance that the user would like zero to correspond to black,\n  // so we do that.  Anything else will be pure white.\n  if ( min == max ) {\n    // FIXME: this path seems to be broken somehow -- we end up with\n    // jpegs of size zero.\n    g_assert_not_reached ();\n    unsigned char oval;         // Output value to use.\n    if ( min == 0.0 ) {\n      oval = 0;\n    }\n    else {\n      oval = UCHAR_MAX;\n    }\n    size_t ii, jj;\n    for ( ii = 0 ; ii < osy ; ii++ ) {\n      for ( jj = 0 ; jj < osx ; jj++ ) {\n        pixels[ii * osx + jj] = oval;\n      }\n    }\n    return 0;\n  }\n\n  // Range of input pixel values which are to be linearly scaled into\n  // the output (values outside this range will be clamped).\n  double lin_min = mean - 2 * standard_deviation;\n  double lin_max = mean + 2 * standard_deviation;\n\n  // As advertised, we will average pixels together.\n  g_assert (scale_factor % 2 != 0);\n  size_t kernel_size = scale_factor;\n  gsl_matrix_float *averaging_kernel\n    = gsl_matrix_float_alloc (kernel_size, kernel_size);\n  float kernel_value = 1.0 / ((float)kernel_size * kernel_size);\n  size_t ii, jj;                // Index values.\n  for ( ii = 0 ; ii < averaging_kernel->size1 ; ii++ ) {\n    for ( jj = 0 ; jj < averaging_kernel->size2 ; jj++ ) {\n      gsl_matrix_float_set (averaging_kernel, ii, jj, kernel_value);\n    }\n  }\n\n  // Sample input image, putting scaled results into output image.\n  size_t sample_stride = scale_factor;\n  for ( ii = 0 ; ii < osy ; ii++ ) {\n    for ( jj = 0 ; jj < osx ; jj++ ) {\n      // Input image average pixel value.\n      float ival = float_image_apply_kernel (self, jj * sample_stride,\n                                             ii * sample_stride,\n                                             averaging_kernel);\n      unsigned char oval;       // Output value.\n      if ( ival < lin_min ) {\n        oval = 0;\n      }\n      else if ( ival > lin_max) {\n        oval = UCHAR_MAX;\n      }\n      else {\n        int oval_int\n          = round (((ival - lin_min) / (lin_max - lin_min)) * UCHAR_MAX);\n        // Make sure we haven't screwed up the scaling.\n        g_assert (oval_int >= 0 && oval_int <= UCHAR_MAX);\n        oval = oval_int;\n      }\n      pixels[ii * osx + jj] = oval;\n    }\n  }\n\n  // Write the jpeg, one row at a time.\n  const int rows_to_write = 1;\n  JSAMPROW *row_pointer = g_new (JSAMPROW, rows_to_write);\n  while ( cinfo.next_scanline < cinfo.image_height ) {\n    int rows_written;\n    row_pointer[0] = &(pixels[cinfo.next_scanline * osx]);\n    rows_written = jpeg_write_scanlines (&cinfo, row_pointer, rows_to_write);\n    g_assert (rows_written == rows_to_write);\n  }\n  g_free (row_pointer);\n\n  // Finsh compression and close the jpeg.\n  jpeg_finish_compress (&cinfo);\n  int return_code = fclose (fp);\n  g_assert (return_code == 0);\n  jpeg_destroy_compress (&cinfo);\n\n  g_free (pixels);\n\n  return 0;                     // Return success indicator.\n}\n\nint\nfloat_image_export_as_tiff (FloatImage *self, const char *file,\n                            size_t max_dimension, double mask)\n{\n    g_assert (self->reference_count > 0); // Harden against missed ref=1 in new\n\n    size_t scale_factor;          // Scale factor to use for output image.\n    if ( self->size_x > self->size_y ) {\n        scale_factor = ceil ((double) self->size_x / max_dimension);\n    }\n    else {\n        scale_factor = ceil ((double) self->size_y / max_dimension);\n    }\n\n    // We want the scale factor to be odd, so that we can easily use a\n    // standard kernel to average things.\n    if ( scale_factor % 2 == 0 ) {\n        scale_factor++;\n    }\n\n    // Output JPEG x and y dimensions.\n    size_t osx = self->size_x / scale_factor;\n    size_t osy = self->size_y / scale_factor;\n\n    // Number of pixels in output image.\n    size_t pixel_count = osx * osy;\n\n    // Pixels of the output image.\n    unsigned char *pixels = g_new (unsigned char, pixel_count);\n\n    // Stuff needed by libtiff\n    TIFF *otif = NULL;\n\n    // Open output file.\n    otif = TIFFOpen(file, \"wb\");\n    if (otif == NULL ) {\n        asfPrintError(\"Error opening TIFF file %s: %s\\n\", file, strerror(errno));\n        return FALSE;\n    }\n\n    // Initialize the TIFF file\n    TIFFSetField(otif, TIFFTAG_SUBFILETYPE, 0);\n    TIFFSetField(otif, TIFFTAG_IMAGEWIDTH, osx);\n    TIFFSetField(otif, TIFFTAG_IMAGELENGTH, osy);\n    TIFFSetField(otif, TIFFTAG_BITSPERSAMPLE, 8); // byte greyscale\n    TIFFSetField(otif, TIFFTAG_COMPRESSION, COMPRESSION_NONE);\n    TIFFSetField(otif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);\n    TIFFSetField(otif, TIFFTAG_SAMPLESPERPIXEL, 1);\n    TIFFSetField(otif, TIFFTAG_ROWSPERSTRIP, 1);\n    TIFFSetField(otif, TIFFTAG_XRESOLUTION, 1.0);\n    TIFFSetField(otif, TIFFTAG_YRESOLUTION, 1.0);\n    TIFFSetField(otif, TIFFTAG_RESOLUTIONUNIT, RESUNIT_NONE);\n    TIFFSetField(otif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);\n    TIFFSetField(otif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);\n\n  // Gather image statistics so we know how to map image values into\n  // the output.\n    float min, max, mean, standard_deviation;\n    float_image_statistics (self, &min, &max, &mean, &standard_deviation, mask);\n\n  // If the statistics don't work, something is beastly wrong and we\n  // don't want to deal with it.\n#ifndef solaris\n#ifndef win32\n  // Solaris doesn't have isfinite().\n  g_assert (isfinite (min) && isfinite (max) && isfinite (mean)\n            && isfinite (standard_deviation));\n#endif\n#endif\n\n  // If min == max, the pixel values are all the same.  There is no\n  // reason to average or scale anything, so we don't.  There is a\n  // good chance that the user would like zero to correspond to black,\n  // so we do that.  Anything else will be pure white.\n  if ( min == max ) {\n    // FIXME: this path is broken.  The trouble is that much of the\n    // stuff after this if branch shouldn't happen if we do this, but\n    // some of it should.  So for now its disabled.\n               g_assert_not_reached ();\n       unsigned char oval;         // Output value to use.\n       if ( min == 0.0 ) {\n           oval = 0;\n       }\n       else {\n           oval = UCHAR_MAX;\n       }\n       size_t ii, jj;\n       for ( ii = 0 ; ii < osy ; ii++ ) {\n           for ( jj = 0 ; jj < osx ; jj++ ) {\n               pixels[ii * osx + jj] = oval;\n           }\n       }\n  }\n\n  // Range of input pixel values which are to be linearly scaled into\n  // the output (values outside this range will be clamped).\n  double lin_min = mean - 2 * standard_deviation;\n  double lin_max = mean + 2 * standard_deviation;\n\n  // As advertised, we will average pixels together.\n  g_assert (scale_factor % 2 != 0);\n  size_t kernel_size = scale_factor;\n  gsl_matrix_float *averaging_kernel\n          = gsl_matrix_float_alloc (kernel_size, kernel_size);\n  float kernel_value = 1.0 / ((float)kernel_size * kernel_size);\n  size_t ii, jj;                // Index values.\n  for ( ii = 0 ; ii < averaging_kernel->size1 ; ii++ ) {\n      for ( jj = 0 ; jj < averaging_kernel->size2 ; jj++ ) {\n          gsl_matrix_float_set (averaging_kernel, ii, jj, kernel_value);\n      }\n  }\n\n  // Sample input image, putting scaled results into output image.\n  size_t sample_stride = scale_factor;\n  for ( ii = 0 ; ii < osy ; ii++ ) {\n      for ( jj = 0 ; jj < osx ; jj++ ) {\n      // Input image average pixel value.\n          float ival = float_image_apply_kernel (self, jj * sample_stride,\n                  ii * sample_stride,\n                  averaging_kernel);\n          unsigned char oval;       // Output value.\n\n          if (!meta_is_valid_double(ival)) {\n              oval = 0;\n          }\n          else if ( ival < lin_min ) {\n              oval = 0;\n          }\n          else if ( ival > lin_max) {\n              oval = UCHAR_MAX;\n          }\n          else {\n              int oval_int\n                      = round (((ival - lin_min) / (lin_max - lin_min)) * UCHAR_MAX);\n              // Make sure we haven't screwed up the scaling.\n              g_assert (oval_int >= 0 && oval_int <= UCHAR_MAX);\n              oval = oval_int;\n          }\n          pixels[ii * osx + jj] = oval;\n      }\n  }\n\n  gsl_matrix_float_free(averaging_kernel);\n  // Write the tiff, one row at a time.\n  unsigned char *byte_line=NULL;\n  for (ii=0; ii<osy; ii++) {\n      byte_line = (unsigned char*)(&pixels[ii*osx]);\n      TIFFWriteScanline(otif, byte_line, ii, 0);\n  }\n\n  // Finalize the TIFF\n  if (otif != NULL) {\n      TIFFClose (otif);\n  }\n\n  g_free (pixels);\n\n  return 0;                     // Return success indicator.\n}\n\nint\nfloat_image_export_as_csv (FloatImage *self, const char * filename)\n{\n  g_assert (self->reference_count > 0); // Harden against missed ref=1 in new\n\n  size_t ii, jj;\n\n  g_assert (self->size_x < 256);\n  g_assert (self->size_y < 256);\n\n  FILE *fout = fopen (filename, \"wt\");\n  if ( fout == NULL ) {\n    printf(\"Attempting to create csv file: %s\\n\", filename);\n    perror (\"error opening file\");\n  }\n\n  for (ii = 0; ii < self->size_x; ++ii) {\n    for (jj = 0; jj < self->size_y; ++jj) {\n      fprintf(fout, \"%5.3f%c\", float_image_get_pixel(self, ii, jj),\n        jj == self->size_y - 1 ? '\\n' : ',');\n    }\n  }\n\n  fclose(fout);\n  return 0;\n}\n\nsize_t\nfloat_image_get_cache_size (FloatImage *self)\n{\n  g_assert_not_reached ();      // Stubbed out for now.\n  // Compiler reassurance.\n  self = self;\n  return 0;\n}\n\nvoid\nfloat_image_set_cache_size (FloatImage *self, size_t size)\n{\n  g_assert_not_reached ();      // Stubbed out for now.\n  // Compiler reassurance.\n  self = self; size = size;\n}\n\nFloatImage *\nfloat_image_ref (FloatImage *self)\n{\n  g_assert (self->reference_count > 0); // Harden against missed ref=1 in new\n\n  self->reference_count++;\n\n  return self;\n}\n\nvoid\nfloat_image_unref (FloatImage *self)\n{\n  self->reference_count--;\n\n  if ( self->reference_count == 0 ) {\n    float_image_free (self);\n  }\n}\n\nvoid\nfloat_image_free (FloatImage *self)\n{\n  // Close the tile file (which shouldn't have to remove it since its\n  // already unlinked), if we were ever using it.\n  if ( self->tile_file != NULL ) {\n    int return_code = fclose (self->tile_file);\n    g_assert (return_code == 0);\n  }\n\n  // Deallocate dynamic memory.\n\n  g_free (self->tile_addresses);\n\n  // If we didn't need a tile file, we also won't have a tile queue.\n  if ( self->tile_queue != NULL ) {\n    g_queue_free (self->tile_queue);\n  }\n\n  g_free (self->cache);\n\n  if (self->tile_file_name) {\n\n      // On Windows (mingw), we delete the file now, since it isn't\n      // automatically deleted on close.\n#ifdef win32\n      int return_code = unlink_tmp_file (self->tile_file_name->str);\n      g_assert (return_code == 0);\n#endif\n\n      g_string_free(self->tile_file_name, TRUE);\n  }\n\n  g_free (self);\n}\n", "meta": {"hexsha": "90d911df9b5ff1a56a549c0240d95f1df74ea4cd", "size": 94626, "ext": "c", "lang": "C", "max_stars_repo_path": "src/libasf_raster/float_image.c", "max_stars_repo_name": "glshort/MapReady", "max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z", "max_issues_repo_path": "src/libasf_raster/float_image.c", "max_issues_repo_name": "glshort/MapReady", "max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libasf_raster/float_image.c", "max_forks_repo_name": "glshort/MapReady", "max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z", "avg_line_length": 34.4344978166, "max_line_length": 94, "alphanum_fraction": 0.6352059688, "num_tokens": 25391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11920291576401235, "lm_q2_score": 0.014957083492086314, "lm_q1q2_score": 0.0017829279635824646}}
{"text": "#pragma once\n#include \"Buffer.h\"\n#include \"Enum.h\"\n#include \"Error.h\"\n#include \"detail/Defaulted.h\"\n#include <boost/hana/define_struct.hpp>\n#include <gsl/span>\n#include <json.hpp>\n\nnamespace gltfpp {\n\tinline namespace v1 {\n\t\tBETTER_ENUM(BufferViewTarget, int32_t, ARRAY_BUFFER = 34962, ELEMENT_ARRAY_BUFFER = 34963)\n\n\t\tstruct BufferView {\n\t\t\tBufferView()\n\t\t\t    : byteStride{0} {\n\t\t\t}\n\n\t\t\tBOOST_HANA_DEFINE_STRUCT(BufferView,\n\t\t\t                         (option<BufferViewTarget>, target),\n\t\t\t                         (option<std::string>, name),\n\t\t\t                         (defaulted<uint8_t>, byteStride),\n\t\t\t                         (option<nlohmann::json>, extensions),\n\t\t\t                         (option<nlohmann::json>, extras));\n\t\t\tgsl::span<byte const> span;\n\t\t\tBuffer const *buffer;\n\t\t};\n\n\t\tauto parse(BufferView &) noexcept;\n\t}    // namespace v1\n}    // namespace gltfpp\n", "meta": {"hexsha": "8a4b8516451bb719037f95d352e79e3d1be9781c", "size": 884, "ext": "h", "lang": "C", "max_stars_repo_path": "gltfpp/include/BufferView.h", "max_stars_repo_name": "mmha/gltfpp", "max_stars_repo_head_hexsha": "9e9e2fe5f8da374838a5b6b03d97963bed87956d", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2017-05-03T04:09:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-06T04:23:54.000Z", "max_issues_repo_path": "gltfpp/include/BufferView.h", "max_issues_repo_name": "mmha/gltfpp", "max_issues_repo_head_hexsha": "9e9e2fe5f8da374838a5b6b03d97963bed87956d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2017-06-02T16:53:11.000Z", "max_issues_repo_issues_event_max_datetime": "2017-06-02T18:05:45.000Z", "max_forks_repo_path": "gltfpp/include/BufferView.h", "max_forks_repo_name": "mmha/gltfpp", "max_forks_repo_head_hexsha": "9e9e2fe5f8da374838a5b6b03d97963bed87956d", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2017-06-01T14:38:11.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-18T07:04:15.000Z", "avg_line_length": 27.625, "max_line_length": 92, "alphanum_fraction": 0.5950226244, "num_tokens": 214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.13660839002621936, "lm_q2_score": 0.013020491980911222, "lm_q1q2_score": 0.0017787084468615817}}
{"text": "#ifndef SETTINGSWIDGET_H\n#define SETTINGSWIDGET_H\n\n#include <QWidget>\n\n#include \"utilities/usersettings.h\"\n\n#include <gsl/gsl>\n\n#include <memory>\n\nclass QDoubleSpinBox;\n\nnamespace Ui {\nclass DisparitySettingsWidget;\n}\n\nclass DisparitySettingsWidget : public QWidget {\n  Q_OBJECT\n\n public:\n  explicit DisparitySettingsWidget(QWidget* parent = 0);\n  ~DisparitySettingsWidget() override;\n\n  void setUserSettings(gsl::not_null<UserSettings*> settings);\n  UserSettings getUserSettings();\n  void conditionalAutoUpdate();\n\n signals:\n  void settingsUpdated(UserSettings updatedSettings);\n  void accepted();\n  void rejected();\n\n private:\n  void ensureMinSmallerThanMax(gsl::not_null<QDoubleSpinBox*> min,\n                               gsl::not_null<QDoubleSpinBox*> max);\n\n  void ensureMaxLargerThanMin(gsl::not_null<QDoubleSpinBox*> min,\n                              gsl::not_null<QDoubleSpinBox*> max);\n\n  std::unique_ptr<Ui::DisparitySettingsWidget> ui;\n};\n\n#endif  // SETTINGSWIDGET_H\n", "meta": {"hexsha": "182e9c1770f346eece1ad8b396a5a3cf1bfad504", "size": 982, "ext": "h", "lang": "C", "max_stars_repo_path": "src/apps/S3DAnalyzer/widgets/disparitysettingswidget.h", "max_stars_repo_name": "hugbed/OpenS3D", "max_stars_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-16T16:38:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-20T03:23:15.000Z", "max_issues_repo_path": "src/apps/S3DAnalyzer/widgets/disparitysettingswidget.h", "max_issues_repo_name": "hugbed/OpenS3D", "max_issues_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 40.0, "max_issues_repo_issues_event_min_datetime": "2017-04-12T17:24:44.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-21T18:41:23.000Z", "max_forks_repo_path": "src/apps/S3DAnalyzer/widgets/disparitysettingswidget.h", "max_forks_repo_name": "hugbed/OpenS3D", "max_forks_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-07-13T21:51:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-18T16:22:03.000Z", "avg_line_length": 21.8222222222, "max_line_length": 67, "alphanum_fraction": 0.7270875764, "num_tokens": 217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09401017961657228, "lm_q2_score": 0.01883312803182053, "lm_q1q2_score": 0.0017705057490133504}}
{"text": "#pragma once\n\n#include \"Cesium3DTiles/BoundingVolume.h\"\n#include \"Cesium3DTiles/Gltf.h\"\n#include \"Cesium3DTiles/Library.h\"\n#include \"Cesium3DTiles/RasterMappedTo3DTile.h\"\n#include \"Cesium3DTiles/RasterOverlayTile.h\"\n#include \"Cesium3DTiles/TileContext.h\"\n#include \"Cesium3DTiles/TileID.h\"\n#include \"Cesium3DTiles/TileRefine.h\"\n#include \"Cesium3DTiles/TileSelectionState.h\"\n#include \"CesiumAsync/IAssetRequest.h\"\n#include \"CesiumGeospatial/Projection.h\"\n#include \"CesiumUtility/DoublyLinkedList.h\"\n#include <atomic>\n#include <glm/mat4x4.hpp>\n#include <gsl/span>\n#include <memory>\n#include <optional>\n#include <string>\n#include <vector>\n\nnamespace Cesium3DTiles {\nclass Tileset;\nclass TileContent;\nstruct TileContentLoadResult;\n\n/**\n * @brief A tile in a {@link Tileset}.\n *\n * The tiles of a tileset form a hierarchy, where each tile may contain\n * renderable content, and each tile has an associated bounding volume.\n *\n * The actual hierarchy is represented with the {@link Tile::getParent}\n * and {@link Tile::getChildren} functions.\n *\n * The renderable content is provided as a {@link TileContentLoadResult}\n * from the {@link Tile::getContent} function.\n * The {@link Tile::getGeometricError} function returns the geometric\n * error of the representation of the renderable content of a tile.\n *\n * The {@link BoundingVolume} is given by the {@link Tile::getBoundingVolume}\n * function. This bounding volume encloses the renderable content of the\n * tile itself, as well as the renderable content of all children, yielding\n * a spatially coherent hierarchy of bounding volumes.\n *\n * The bounding volume of the content of an individual tile is given\n * by the {@link Tile::getContentBoundingVolume} function.\n *\n */\nclass CESIUM3DTILES_API Tile final {\npublic:\n  /**\n   * The current state of this tile in the loading process.\n   */\n  enum class LoadState {\n    /**\n     * @brief This tile is in the process of being destroyed.\n     *\n     * Any pointers to it will soon be invalid.\n     */\n    Destroying = -3,\n\n    /**\n     * @brief Something went wrong while loading this tile and it will not be\n     * retried.\n     */\n    Failed = -2,\n\n    /**\n     * @brief Something went wrong while loading this tile, but it may be a\n     * temporary problem.\n     */\n    FailedTemporarily = -1,\n\n    /**\n     * @brief The tile is not yet loaded at all, beyond the metadata in\n     * tileset.json.\n     */\n    Unloaded = 0,\n\n    /**\n     * @brief The tile content is currently being loaded.\n     *\n     * Note that while a tile is in this state, its {@link Tile::getContent},\n     * and {@link Tile::getState}, methods may be called from the load thread,\n     * and the state may change due to the internal loading process.\n     */\n    ContentLoading = 1,\n\n    /**\n     * @brief The tile content has finished loading.\n     */\n    ContentLoaded = 2,\n\n    /**\n     * @brief The tile is completely done loading.\n     */\n    Done = 3\n  };\n\n  /**\n   * @brief Default constructor for an empty, uninitialized tile.\n   */\n  Tile() noexcept;\n\n  /**\n   * @brief Default destructor, which clears all resources associated with this\n   * tile.\n   */\n  ~Tile();\n\n  /**\n   * @brief Copy constructor.\n   *\n   * @param rhs The other instance.\n   */\n  Tile(Tile& rhs) noexcept = delete;\n\n  /**\n   * @brief Move constructor.\n   *\n   * @param rhs The other instance.\n   */\n  Tile(Tile&& rhs) noexcept;\n\n  /**\n   * @brief Move assignment operator.\n   *\n   * @param rhs The other instance.\n   */\n  Tile& operator=(Tile&& rhs) noexcept;\n\n  /**\n   * @brief Returns the {@link Tileset} to which this tile belongs.\n   */\n  Tileset* getTileset() noexcept { return this->_pContext->pTileset; }\n\n  /** @copydoc Tile::getTileset() */\n  const Tileset* getTileset() const noexcept {\n    return this->_pContext->pTileset;\n  }\n\n  /**\n   * @brief Returns the {@link TileContext} of this tile.\n   *\n   * This function is not supposed to be called by clients.\n   *\n   * @return The tile context.\n   */\n  TileContext* getContext() noexcept { return this->_pContext; }\n\n  /** @copydoc Tile::getContext() */\n  const TileContext* getContext() const noexcept { return this->_pContext; }\n\n  /**\n   * @brief Set the {@link TileContext} of this tile.\n   *\n   * This function is not supposed to be called by clients.\n   *\n   * @param pContext The tile context.\n   */\n  void setContext(TileContext* pContext) noexcept {\n    this->_pContext = pContext;\n  }\n\n  /**\n   * @brief Returns the parent of this tile in the tile hierarchy.\n   *\n   * This will be the `nullptr` if this is the root tile.\n   *\n   * @return The parent.\n   */\n  Tile* getParent() noexcept { return this->_pParent; }\n\n  /** @copydoc Tile::getParent() */\n  const Tile* getParent() const noexcept { return this->_pParent; }\n\n  /**\n   * @brief Set the parent of this tile.\n   *\n   * This function is not supposed to be called by clients.\n   *\n   * @param pParent The parent tile .\n   */\n  void setParent(Tile* pParent) noexcept { this->_pParent = pParent; }\n\n  /**\n   * @brief Returns a *view* on the children of this tile.\n   *\n   * The returned span will become invalid when this tile is destroyed.\n   *\n   * @return The children of this tile.\n   */\n  gsl::span<Tile> getChildren() noexcept {\n    return gsl::span<Tile>(this->_children);\n  }\n\n  /** @copydoc Tile::getChildren() */\n  gsl::span<const Tile> getChildren() const noexcept {\n    return gsl::span<const Tile>(this->_children);\n  }\n\n  /**\n   * @brief Allocates space for the given number of child tiles.\n   *\n   * This function is not supposed to be called by clients.\n   *\n   * @param count The number of child tiles.\n   * @throws `std::runtime_error` if this tile already has children.\n   */\n  void createChildTiles(size_t count);\n\n  /**\n   * @brief Assigns the given child tiles to this tile.\n   *\n   * This function is not supposed to be called by clients.\n   *\n   * @param children The child tiles.\n   * @throws `std::runtime_error` if this tile already has children.\n   */\n  void createChildTiles(std::vector<Tile>&& children);\n\n  /**\n   * @brief Returns the {@link BoundingVolume} of this tile.\n   *\n   * This is a bounding volume that encloses the content of this tile,\n   * as well as the content of all child tiles.\n   *\n   * @see Tile::getContentBoundingVolume\n   *\n   * @return The bounding volume.\n   */\n  const BoundingVolume& getBoundingVolume() const noexcept {\n    return this->_boundingVolume;\n  }\n\n  /**\n   * @brief Set the {@link BoundingVolume} of this tile.\n   *\n   * This function is not supposed to be called by clients.\n   *\n   * @param value The bounding volume.\n   */\n  void setBoundingVolume(const BoundingVolume& value) noexcept {\n    this->_boundingVolume = value;\n  }\n\n  /**\n   * @brief Returns the viewer request volume of this tile.\n   *\n   * The viewer request volume is an optional {@link BoundingVolume} that\n   * may be associated with a tile. It allows controlling the rendering\n   * process of the tile content: If the viewer request volume is present,\n   * then the content of the tile will only be rendered when the viewer\n   * (i.e. the camera position) is inside the viewer request volume.\n   *\n   * @return The viewer request volume, or an empty optional.\n   */\n  const std::optional<BoundingVolume>& getViewerRequestVolume() const noexcept {\n    return this->_viewerRequestVolume;\n  }\n\n  /**\n   * @brief Set the viewer request volume of this tile.\n   *\n   * This function is not supposed to be called by clients.\n   *\n   * @param value The viewer request volume.\n   */\n  void\n  setViewerRequestVolume(const std::optional<BoundingVolume>& value) noexcept {\n    this->_viewerRequestVolume = value;\n  }\n\n  /**\n   * @brief Returns the geometric error of this tile.\n   *\n   * This is the error, in meters, introduced if this tile is rendered and its\n   * children are not. This is used to compute screen space error, i.e., the\n   * error measured in pixels.\n   *\n   * @return The geometric error of this tile, in meters.\n   */\n  double getGeometricError() const noexcept { return this->_geometricError; }\n\n  /**\n   * @brief Set the geometric error of the contents of this tile.\n   *\n   * This function is not supposed to be called by clients.\n   *\n   * @param value The geometric error, in meters.\n   */\n  void setGeometricError(double value) noexcept {\n    this->_geometricError = value;\n  }\n\n  /**\n   * @brief The refinement strategy of this tile.\n   *\n   * Returns the {@link TileRefine} value that indicates the refinement strategy\n   * for this tile. This is `Add` when the content of the\n   * child tiles is *added* to the content of this tile during refinement, and\n   * `Replace` when the content of the child tiles *replaces*\n   * the content of this tile during refinement.\n   *\n   * @return The refinement strategy.\n   */\n  TileRefine getRefine() const noexcept { return this->_refine; }\n\n  /**\n   * @brief Set the refinement strategy of this tile.\n   *\n   * This function is not supposed to be called by clients.\n   *\n   * @param value The refinement strategy.\n   */\n  void setRefine(TileRefine value) noexcept { this->_refine = value; }\n\n  /**\n   * @brief Gets the transformation matrix for this tile.\n   *\n   * This matrix does _not_ need to be multiplied with the tile's parent's\n   * transform as this has already been done.\n   *\n   * @return The transform matrix.\n   */\n  const glm::dmat4x4& getTransform() const noexcept { return this->_transform; }\n\n  /**\n   * @brief Set the transformation matrix for this tile.\n   *\n   * This function is not supposed to be called by clients.\n   *\n   * @param value The transform matrix.\n   */\n  void setTransform(const glm::dmat4x4& value) noexcept {\n    this->_transform = value;\n  }\n\n  /**\n   * @brief Returns the {@link TileID} of this tile.\n   *\n   * This function is not supposed to be called by clients.\n   *\n   * @return The tile ID.\n   */\n  const TileID& getTileID() const noexcept { return this->_id; }\n\n  /**\n   * @brief Set the {@link TileID} of this tile.\n   *\n   * This function is not supposed to be called by clients.\n   *\n   * @param id The tile ID.\n   */\n  void setTileID(const TileID& id) noexcept;\n\n  /**\n   * @brief Returns the {@link BoundingVolume} of the renderable content of this\n   * tile.\n   *\n   * The content bounding volume is a bounding volume that tightly fits only the\n   * renderable content of the tile. This enables tighter view frustum culling,\n   * making it possible to exclude from rendering any content not in the view\n   * frustum.\n   *\n   * @see Tile::getBoundingVolume\n   */\n  const std::optional<BoundingVolume>&\n  getContentBoundingVolume() const noexcept {\n    return this->_contentBoundingVolume;\n  }\n\n  /**\n   * @brief Set the {@link BoundingVolume} of the renderable content of this\n   * tile.\n   *\n   * This function is not supposed to be called by clients.\n   *\n   * @param value The content bounding volume\n   */\n  void setContentBoundingVolume(\n      const std::optional<BoundingVolume>& value) noexcept {\n    this->_contentBoundingVolume = value;\n  }\n\n  /**\n   * @brief Returns the {@link TileContentLoadResult} for the content of this\n   * tile.\n   *\n   * This will be a `nullptr` if the content of this tile has not yet been\n   * loaded, as indicated by the indicated by the {@link Tile::getState} of this\n   * tile not being {@link Tile::LoadState::ContentLoaded}.\n   *\n   * @return The tile content load result, or `nullptr` if no content is loaded\n   */\n  TileContentLoadResult* getContent() noexcept { return this->_pContent.get(); }\n\n  /** @copydoc Tile::getContent() */\n  const TileContentLoadResult* getContent() const noexcept {\n    return this->_pContent.get();\n  }\n\n  /**\n   * @brief Returns internal resources required for rendering this tile.\n   *\n   * This function is not supposed to be called by clients.\n   *\n   * @return The renderer resources.\n   */\n  void* getRendererResources() const noexcept {\n    return this->_pRendererResources;\n  }\n\n  /**\n   * @brief Returns the {@link LoadState} of this tile.\n   */\n  LoadState getState() const noexcept {\n    return this->_state.load(std::memory_order::memory_order_acquire);\n  }\n\n  /**\n   * @brief Returns the {@link TileSelectionState} of this tile.\n   *\n   * This function is not supposed to be called by clients.\n   *\n   * @return The last selection state\n   */\n  TileSelectionState& getLastSelectionState() noexcept {\n    return this->_lastSelectionState;\n  }\n\n  /** @copydoc Tile::getLastSelectionState() */\n  const TileSelectionState& getLastSelectionState() const noexcept {\n    return this->_lastSelectionState;\n  }\n\n  /**\n   * @brief Set the {@link TileSelectionState} of this tile.\n   *\n   * This function is not supposed to be called by clients.\n   *\n   * @param newState The new stace\n   */\n  void setLastSelectionState(const TileSelectionState& newState) noexcept {\n    this->_lastSelectionState = newState;\n  }\n\n  /**\n   * @brief Returns the raster overlay tiles that have been mapped to this tile.\n   */\n  std::vector<RasterMappedTo3DTile>& getMappedRasterTiles() noexcept {\n    return this->_rasterTiles;\n  }\n\n  /** @copydoc Tile::getMappedRasterTiles() */\n  const std::vector<RasterMappedTo3DTile>&\n  getMappedRasterTiles() const noexcept {\n    return this->_rasterTiles;\n  }\n\n  /**\n   * @brief Determines if this tile is currently renderable.\n   */\n  bool isRenderable() const noexcept;\n\n  /**\n   * @brief Trigger the process of loading the {@link Tile::getContent}.\n   *\n   * This function is not supposed to be called by clients.\n   *\n   * If this tile is not in its initial state (indicated by the\n   * {@link Tile::getState} of this tile being *not*\n   * {@link Tile::LoadState::Unloaded}), then nothing will be done.\n   *\n   * Otherwise, the tile will go into the\n   * {@link Tile::LoadState::ContentLoading} state, and the request for\n   * loading the tile content will be sent out.\n   * The function will then return, and the response of the request will\n   * be received asynchronously. Depending on the type of the tile and\n   * the response, the tile will eventually go into the\n   * {@link Tile::LoadState::ContentLoaded} state, and the\n   * {@link Tile::getContent} will be available.\n   */\n  void loadContent();\n\n  /**\n   * @brief Frees all resources that have been allocated for the\n   * {@link Tile::getContent}.\n   *\n   * This function is not supposed to be called by clients.\n   *\n   * If the operation for loading the tile content is currently in progress, as\n   * indicated by the {@link Tile::getState} of this tile being\n   * {@link Tile::LoadState::ContentLoading}), then nothing will be done,\n   * and `false` will be returned.\n   *\n   * Otherwise, the resources that have been allocated for the tile content will\n   * be freed.\n   *\n   * @return Whether the content was unloaded.\n   */\n  bool unloadContent() noexcept;\n\n  /**\n   * @brief Gives this tile a chance to update itself each render frame.\n   *\n   * @param previousFrameNumber The number of the previous render frame.\n   * @param currentFrameNumber The number of the current render frame.\n   */\n  void update(int32_t previousFrameNumber, int32_t currentFrameNumber);\n\n  /**\n   * @brief Marks the tile as permanently failing to load.\n   *\n   * This function is not supposed to be called by clients.\n   *\n   * Moves the tile from the `FailedTemporarily` state to the `Failed` state.\n   * If the tile is not in the `FailedTemporarily` state, this method does\n   * nothing.\n   */\n  void markPermanentlyFailed() noexcept;\n\n  /**\n   * @brief Determines the number of bytes in this tile's geometry and texture\n   * data.\n   */\n  int64_t computeByteSize() const noexcept;\n\nprivate:\n  /**\n   * @brief Set the {@link LoadState} of this tile.\n   */\n  void setState(LoadState value) noexcept;\n\n  /**\n   * @brief Generates texture coordiantes for the raster overlays of the content\n   * of this tile.\n   *\n   * This will extend the accessors of the glTF model of the content of this\n   * tile with accessors that contain the texture coordinate sets for different\n   * projections. Further details are not specified here.\n   *\n   * @return The bounding region\n   */\n  static std::optional<CesiumGeospatial::BoundingRegion>\n  generateTextureCoordinates(\n      CesiumGltf::Model& model,\n      const BoundingVolume& boundingVolume,\n      const std::vector<CesiumGeospatial::Projection>& projections);\n\n  /**\n   * @brief Upsample the parent of this tile.\n   *\n   * This method should only be called when this tile's parent is already\n   * loaded.\n   */\n  void upsampleParent(std::vector<CesiumGeospatial::Projection>&& projections);\n\n  // Position in bounding-volume hierarchy.\n  TileContext* _pContext;\n  Tile* _pParent;\n  std::vector<Tile> _children;\n\n  // Properties from tileset.json.\n  // These are immutable after the tile leaves TileState::Unloaded.\n  BoundingVolume _boundingVolume;\n  std::optional<BoundingVolume> _viewerRequestVolume;\n  double _geometricError;\n  TileRefine _refine;\n  glm::dmat4x4 _transform;\n\n  TileID _id;\n  std::optional<BoundingVolume> _contentBoundingVolume;\n\n  // Load state and data.\n  std::atomic<LoadState> _state;\n  std::unique_ptr<TileContentLoadResult> _pContent;\n  void* _pRendererResources;\n\n  // Selection state\n  TileSelectionState _lastSelectionState;\n\n  // Overlays\n  std::vector<RasterMappedTo3DTile> _rasterTiles;\n\n  CesiumUtility::DoublyLinkedListPointers<Tile> _loadedTilesLinks;\n\npublic:\n  /**\n   * @brief A {@link CesiumUtility::DoublyLinkedList} for tile objects.\n   */\n  typedef CesiumUtility::DoublyLinkedList<Tile, &Tile::_loadedTilesLinks>\n      LoadedLinkedList;\n};\n\n} // namespace Cesium3DTiles\n", "meta": {"hexsha": "e9da87a3a78f4da6d9aece239346f739b5603dd0", "size": 17525, "ext": "h", "lang": "C", "max_stars_repo_path": "Cesium3DTiles/include/Cesium3DTiles/Tile.h", "max_stars_repo_name": "zy6p/cesium-native", "max_stars_repo_head_hexsha": "d7b02d0c229e54e626e313bf2cfab31ed6e8ac3b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Cesium3DTiles/include/Cesium3DTiles/Tile.h", "max_issues_repo_name": "zy6p/cesium-native", "max_issues_repo_head_hexsha": "d7b02d0c229e54e626e313bf2cfab31ed6e8ac3b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cesium3DTiles/include/Cesium3DTiles/Tile.h", "max_forks_repo_name": "zy6p/cesium-native", "max_forks_repo_head_hexsha": "d7b02d0c229e54e626e313bf2cfab31ed6e8ac3b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2570951586, "max_line_length": 80, "alphanum_fraction": 0.6841084165, "num_tokens": 4329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09670580110615862, "lm_q2_score": 0.018264279821392, "lm_q1q2_score": 0.0017662618117547612}}
{"text": "#ifndef VKST_WSI_INPUT_H\n#define VKST_WSI_INPUT_H\n\n#include <gsl.h>\n#include <wsi/types.h>\n#include <bitset>\n\nnamespace wsi {\n\nenum class keys {\n  eUnknown = 0,\n\n  eSpace = 32,\n  eApostrophe = 39,\n  eComma = 44,\n  eMinus = 45,\n  ePeriod = 46,\n  eSlash = 47,\n  e0 = 48,\n  e1 = 49,\n  e2 = 50,\n  e3 = 51,\n  e4 = 52,\n  e5 = 53,\n  e6 = 54,\n  e7 = 55,\n  e8 = 56,\n  e9 = 57,\n  eSemicolon = 59,\n  eEqual = 61,\n  eA = 65,\n  eB = 66,\n  eC = 67,\n  eD = 68,\n  eE = 69,\n  eF = 70,\n  eG = 71,\n  eH = 72,\n  eI = 73,\n  eJ = 74,\n  eK = 75,\n  eL = 76,\n  eM = 77,\n  eN = 78,\n  eO = 79,\n  eP = 80,\n  eQ = 81,\n  eR = 82,\n  eS = 83,\n  eT = 84,\n  eU = 85,\n  eV = 86,\n  eW = 87,\n  eX = 88,\n  eY = 89,\n  eZ = 90,\n  eLeftBracket = 91,\n  eBackslash = 92,\n  eRightBracket = 93,\n  eGraveAccent = 96,\n\n  eEscape = 156,\n  eEnter = 157,\n  eTab = 158,\n  eBackspace = 159,\n  eInsert = 160,\n  eDelete = 161,\n  eRight = 162,\n  eLeft = 163,\n  eDown = 164,\n  eUp = 165,\n  ePageUp = 166,\n  ePageDown = 167,\n  eHome = 168,\n  eEnd = 169,\n\n  eCapsLock = 180,\n  eScrollLock = 181,\n  eNumLock = 182,\n  ePrintScreen = 183,\n  ePause = 184,\n\n  eF1 = 190,\n  eF2 = 191,\n  eF3 = 192,\n  eF4 = 193,\n  eF5 = 194,\n  eF6 = 195,\n  eF7 = 196,\n  eF8 = 197,\n  eF9 = 198,\n  eF10 = 199,\n  eF11 = 200,\n  eF12 = 201,\n  eF13 = 202,\n  eF14 = 203,\n  eF15 = 204,\n  eF16 = 205,\n  eF17 = 206,\n  eF18 = 207,\n  eF19 = 208,\n  eF20 = 209,\n  eF21 = 210,\n  eF22 = 211,\n  eF23 = 212,\n  eF24 = 213,\n  eF25 = 214,\n\n  eKeypad0 = 220,\n  eKeypad1 = 221,\n  eKeypad2 = 222,\n  eKeypad3 = 223,\n  eKeypad4 = 224,\n  eKeypad5 = 225,\n  eKeypad6 = 226,\n  eKeypad7 = 227,\n  eKeypad8 = 228,\n  eKeypad9 = 229,\n  eKeypadDecimal = 230,\n  eKeypadDivide = 231,\n  eKeypadMultiply = 232,\n  eKeypadSubtract = 233,\n  eKeypadAdd = 234,\n  eKeypadEnter = 235,\n  eKeypadEqual = 236,\n\n  eLeftShift = 240,\n  eLeftControl = 241,\n  eLeftAlt = 242,\n  eLeftSuper = 243,\n  eRightShift = 244,\n  eRightControl = 245,\n  eRightAlt = 246,\n  eRightSuper = 247,\n  eMenu = 248,\n}; // enum class keys\n\nclass keyset final {\n  std::bitset<256> _keys;\n\npublic:\n  using reference = decltype(_keys)::reference;\n\n  bool all() const { return _keys.all(); }\n  bool any() const { return _keys.any(); }\n  bool none() const { return _keys.none(); }\n\n  constexpr bool operator[](keys key) const {\n    return _keys[static_cast<std::size_t>(key)];\n  }\n\n  reference operator[](keys key) {\n    return _keys[static_cast<std::size_t>(key)];\n  }\n\n  keyset& set(keys key, bool value = true) noexcept {\n    _keys[static_cast<std::size_t>(key)] = value;\n    return *this;\n  }\n\n  keyset& reset(keys key) noexcept {\n    _keys[static_cast<std::size_t>(key)] = false;\n    return *this;\n  }\n}; // class keyset\n\nenum class buttons {\n  e1 = 1,\n  e2,\n  e3,\n  e4,\n  e5,\n  e6,\n  e7,\n  e8,\n  e9,\n  e10,\n}; // enum class buttons\n\nclass buttonset final {\n  std::bitset<32> _buttons;\n\npublic:\n  using reference = decltype(_buttons)::reference;\n\n  bool all() const { return _buttons.all(); }\n  bool any() const { return _buttons.any(); }\n  bool none() const { return _buttons.none(); }\n\n  constexpr bool operator[](buttons button) const {\n    return _buttons[static_cast<std::size_t>(button)];\n  }\n\n  reference operator[](buttons button) {\n    return _buttons[static_cast<std::size_t>(button)];\n  }\n\n  buttonset& set(buttons button, bool value = true) noexcept {\n    _buttons[static_cast<std::size_t>(button)] = value;\n    return *this;\n  }\n\n  buttonset& reset(buttons button) noexcept {\n    _buttons[static_cast<std::size_t>(button)] = false;\n    return *this;\n  }\n}; // class buttonset\n\nclass window;\n\nclass input final {\npublic:\n  input(gsl::not_null<window*> win) noexcept;\n\n  bool key_pressed(keys key) const noexcept {\n    return !_prev_keys[key] && _curr_keys[key];\n  }\n\n  bool key_released(keys key) const noexcept {\n    return _prev_keys[key] && !_curr_keys[key];\n  }\n\n  bool key_down(keys key) const noexcept {\n    return _prev_keys[key] && _curr_keys[key];\n  }\n\n  bool button_pressed(buttons button) const noexcept {\n    return !_prev_buttons[button] && _curr_buttons[button];\n  }\n\n  bool button_released(buttons button) const noexcept {\n    return _prev_buttons[button] && !_curr_buttons[button];\n  }\n\n  bool button_down(buttons button) const noexcept {\n    return _prev_buttons[button] && _curr_buttons[button];\n  }\n\n  int prev_scroll() const noexcept { return _prev_scroll; }\n  int curr_scroll() const noexcept { return _curr_scroll; }\n\n  int scroll_delta() const noexcept { return _curr_scroll - _prev_scroll; }\n\n  offset2d cursor_pos() const noexcept;\n\n  offset2d prev_cursor_pos() const noexcept { return _prev_pos; }\n  offset2d curr_cursor_pos() const noexcept { return _curr_pos; }\n\n  offset2d cursor_delta() const noexcept { return _curr_pos - _prev_pos; }\n\n  void tick() noexcept;\n\nprivate:\n  window* _win;\n  keyset _prev_keys, _curr_keys;\n  buttonset _prev_buttons, _curr_buttons;\n  int _prev_scroll, _curr_scroll;\n  offset2d _prev_pos, _curr_pos;\n}; // class input\n\n} // namespace wsi\n\n#endif // VKST_WSI_INPUT_H\n", "meta": {"hexsha": "ae6e5b645eeb10d5f97216fe65989888855cd7c8", "size": 4978, "ext": "h", "lang": "C", "max_stars_repo_path": "src/wsi/input.h", "max_stars_repo_name": "wesleygriffin/vkst", "max_stars_repo_head_hexsha": "5f1210ef8aeecdd2bbc3904b0cc4dd09892f239c", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/wsi/input.h", "max_issues_repo_name": "wesleygriffin/vkst", "max_issues_repo_head_hexsha": "5f1210ef8aeecdd2bbc3904b0cc4dd09892f239c", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/wsi/input.h", "max_forks_repo_name": "wesleygriffin/vkst", "max_forks_repo_head_hexsha": "5f1210ef8aeecdd2bbc3904b0cc4dd09892f239c", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.8560606061, "max_line_length": 75, "alphanum_fraction": 0.6343913218, "num_tokens": 1773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06954175029096785, "lm_q2_score": 0.025178844260831185, "lm_q1q2_score": 0.0017509809002018912}}
{"text": "#include <bindings.cmacros.h>\n#include <gsl/gsl_errno.h>\n\nBC_INLINE2(GSL_ERROR_SELECT_2,int,int,int)\nBC_INLINE3(GSL_ERROR_SELECT_3,int,int,int,int)\nBC_INLINE4(GSL_ERROR_SELECT_4,int,int,int,int,int)\nBC_INLINE5(GSL_ERROR_SELECT_5,int,int,int,int,int,int)\nBC_INLINE2VOID(GSL_STATUS_UPDATE,int*,int)\n", "meta": {"hexsha": "ed682a55ef036e40696571b01e6577e38754d870", "size": 297, "ext": "c", "lang": "C", "max_stars_repo_path": "bindings-gsl/src/Bindings/Gsl/ErrorHandling.c", "max_stars_repo_name": "flip111/bindings-dsl", "max_stars_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2015-04-29T00:31:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T09:29:03.000Z", "max_issues_repo_path": "bindings-gsl/src/Bindings/Gsl/ErrorHandling.c", "max_issues_repo_name": "flip111/bindings-dsl", "max_issues_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2015-01-04T06:32:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-07T09:49:12.000Z", "max_forks_repo_path": "bindings-gsl/src/Bindings/Gsl/ErrorHandling.c", "max_forks_repo_name": "flip111/bindings-dsl", "max_forks_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2015-01-03T20:43:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-10T19:31:38.000Z", "avg_line_length": 33.0, "max_line_length": 54, "alphanum_fraction": 0.8282828283, "num_tokens": 86, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07159119944455249, "lm_q2_score": 0.02442309040915126, "lm_q1q2_score": 0.0017484783365338849}}
{"text": "#pragma once\n\n#include \"text_parser.h\"\n#include \"text_renderer.h\"\n#include \"terminal_io.h\"\n#include \"geometry.h\"\n\n#include <string>\n#include <vector>\n\n#include <gsl/span>\n\nnamespace terminal_editor {\n\nenum class Color {\n    Black\t        = 30,\n    Red\t            = 31,\n    Green\t        = 32,\n    Yellow\t        = 33,\n    Blue\t        = 34,\n    Magenta\t        = 35,\n    Cyan\t        = 36,\n    White\t        = 37,\n    Bright_Black\t= 90,\n    Bright_Red\t    = 91,\n    Bright_Green\t= 92,\n    Bright_Yellow\t= 93,\n    Bright_Blue\t    = 94,\n    Bright_Magenta\t= 95,\n    Bright_Cyan\t    = 96,\n    Bright_White\t= 97,\n};\n\nenum class Style {\n    Bold        = 1,\n    Normal      = 22,\n};\n\nstruct Attributes {\n    Color fgColor;\n    Color bgColor;\n    Style style;\n};\n\nclass ScreenBuffer;\n\nclass ScreenCanvas {\n    ScreenBuffer& m_screenBuffer;\n    Point m_origin;  ///< Point in screen coordinates that all drawing functions are relative to.\n    Rect m_clipRect; ///< In screen coordinates.\npublic:\n    /// clipRect will be clipped to screenBuffer bounds.\n    ScreenCanvas(ScreenBuffer& screenBuffer, Point origin, Rect clipRect);\n\n    /// Sub canvas will be clipped to this canvas size.\n    /// @param rect     Sub rectangle of this canvas. Rect is relative to this canvas' origin.\n    ScreenCanvas getSubCanvas(Rect rect);\n\n    /// Clears canvas to given color.\n    void clear(Color bgColor) {\n        auto localRect = m_clipRect;\n        localRect.move(-m_origin.asSize()); // In local coordinates.\n        fill(localRect, bgColor);\n    }\n\n    /// Draw filled rectangle.\n    void fill(Rect rect, Color bgColor);\n\n    /// Draw rectangle.\n    void fillRect(Rect rect, bool doubleEdge, bool fill, Attributes attributes);\n\n    /// Draws given text on the canvas.\n    /// Text is clipped to boundaries of the canvas.\n    /// So only graphemes fully inside are drawn.\n    /// @param text     Input string, doesn't have to be valid or printable UTF-8.\n    void print(Point pt, const std::string& text, Attributes normal, Attributes invalid, Attributes replacement);\n\n    /// Draws given text on the canvas.\n    /// Text is clipped to boundaries of the canvas.\n    /// So only graphemes fully inside are drawn.\n    /// @param graphemes    Graphemes to draw.\n    void print(Point pt, gsl::span<const Grapheme> graphemes, Attributes normal, Attributes invalid, Attributes replacement);\n};\n\nclass ScreenBuffer {\npublic:\n    struct Character {\n        std::string text; ///< UTF-8 text to draw. If empty, then this place will be drawn by preceeding character with width > 1.\n        int width;        ///< Width of text once it will be rendered.\n        Attributes attributes;\n\n        bool operator==(const Character& other) const {\n            if (text != other.text) return false;\n            if (width != other.width) return false;\n            if (attributes.fgColor != other.attributes.fgColor) return false;\n            if (attributes.bgColor != other.attributes.bgColor) return false;\n            if (attributes.style != other.attributes.style) return false;\n            return true;\n        }\n    };\n\nprivate:\n    Size size;\n    std::vector<Character> characters;\n    std::vector<Character> previousCharacters;\n    bool fullRepaintNeeded;     ///< If true while screen will be repainted. Otherwise only changes from previousCharacters will be repainted.\n\npublic:\n    ScreenBuffer()\n        : fullRepaintNeeded(true) {\n    }\n\n    ScreenCanvas getCanvas() {\n        return ScreenCanvas(*this, Point{0, 0}, getSize());\n    }\n\n    /// Sets fullRepaintNeeded flag. Used when contents of the screen were changed without ScreenBuffer.\n    void setFullRepaintNeeded() {\n        fullRepaintNeeded = true;\n    }\n\n    Size getSize() const {\n        return size;\n    }\n\n    int getWidth() const {\n        return size.width;\n    }\n\n    int getHeight() const {\n        return size.height;\n    }\n\n    /// Resizes this screen buffer.\n    void resize(int w, int h);\n\n    /// Clears screen to given color.\n    void clear(Color bgColor);\n\n    /// Draws a filled rectangle with given color.\n    /// Rectangle is first clipped to fit the scren buffer.\n    void fillRect(Rect rect, Color bgColor);\n\n    /// Draws given text on the screen.\n    /// Throws if text is not entirely on the screen.\n    /// @param text     Input string, doesn't have to be valid or printable UTF-8.\n    void print(int x, int y, const std::string& text, Attributes attributes);\n\n    /// Draws given graphemes on the screen.\n    /// Throws if text is not entirely on the screen.\n    /// @param graphemes    Graphemes to draw.\n    void print(int x, int y, gsl::span<const Grapheme> graphemes, Attributes attributes);\n\n    /// Draws this screen buffer to the console.\n    void present();\n};\n\n/// Returns Grapheme that corresponds to given simpleCharacter.\n/// @param simpleCharacter      Must be a valid UTF-8 string, that converts to a printable character of width 1.\ntemplate<int N>\nGrapheme simpleGrapheme(const char (&simpleChar)[N]) {\n    return { GraphemeKind::NORMAL, simpleChar, \"\", 1, {simpleChar, N - 1} };\n}\n\n/// Draws a rectangle with borders.\n/// Rectangle is clipped by the clipRect. clipRect must be wholy inside screen buffer.\nvoid draw_rect(ScreenBuffer& screenBuffer, Rect clipRect, Rect rect, bool doubleEdge, bool fill, Attributes attributes);\n\n/// Measures given text on the terminal\n/// @param eventQueue   Event queue to use for listening for the result.\n/// @param codePoints   List of code points to measure.\n/// @return Length of the code points. Can be zero.\nint measureText(EventQueue& eventQueue, gsl::span<uint32_t> codePoints);\n\n} // namespace terminal_editor\n", "meta": {"hexsha": "21ded3e9f4c51302b062287709fa21527df6d695", "size": 5632, "ext": "h", "lang": "C", "max_stars_repo_path": "text_ui/screen_buffer.h", "max_stars_repo_name": "Zbyl/terminal-editor", "max_stars_repo_head_hexsha": "375ac936f09543bab9c01fcb5a2dc8de9af83a58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "text_ui/screen_buffer.h", "max_issues_repo_name": "Zbyl/terminal-editor", "max_issues_repo_head_hexsha": "375ac936f09543bab9c01fcb5a2dc8de9af83a58", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "text_ui/screen_buffer.h", "max_forks_repo_name": "Zbyl/terminal-editor", "max_forks_repo_head_hexsha": "375ac936f09543bab9c01fcb5a2dc8de9af83a58", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-12-21T00:37:06.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-21T00:37:06.000Z", "avg_line_length": 32.0, "max_line_length": 142, "alphanum_fraction": 0.6587357955, "num_tokens": 1284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.13846180478945583, "lm_q2_score": 0.012624948515340243, "lm_q1q2_score": 0.0017480731568079708}}
{"text": "/* block/gsl_block_char.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_BLOCK_CHAR_H__\n#define __GSL_BLOCK_CHAR_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_types.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\nstruct gsl_block_char_struct\n{\n  size_t size;\n  char *data;\n};\n\ntypedef struct gsl_block_char_struct gsl_block_char;\n\nGSL_EXPORT gsl_block_char *gsl_block_char_alloc (const size_t n);\nGSL_EXPORT gsl_block_char *gsl_block_char_calloc (const size_t n);\nGSL_EXPORT void gsl_block_char_free (gsl_block_char * b);\n\nGSL_EXPORT int gsl_block_char_fread (FILE * stream, gsl_block_char * b);\nGSL_EXPORT int gsl_block_char_fwrite (FILE * stream, const gsl_block_char * b);\nGSL_EXPORT int gsl_block_char_fscanf (FILE * stream, gsl_block_char * b);\nGSL_EXPORT int gsl_block_char_fprintf (FILE * stream, const gsl_block_char * b, const char *format);\n\nGSL_EXPORT int gsl_block_char_raw_fread (FILE * stream, char * b, const size_t n, const size_t stride);\nGSL_EXPORT int gsl_block_char_raw_fwrite (FILE * stream, const char * b, const size_t n, const size_t stride);\nGSL_EXPORT int gsl_block_char_raw_fscanf (FILE * stream, char * b, const size_t n, const size_t stride);\nGSL_EXPORT int gsl_block_char_raw_fprintf (FILE * stream, const char * b, const size_t n, const size_t stride, const char *format);\n\nGSL_EXPORT size_t gsl_block_char_size (const gsl_block_char * b);\nGSL_EXPORT char * gsl_block_char_data (const gsl_block_char * b);\n\n__END_DECLS\n\n#endif /* __GSL_BLOCK_CHAR_H__ */\n", "meta": {"hexsha": "d197bea88cd6efe81c95ca6f61dd13565a6da2cf", "size": 2454, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/gsl/include/gsl/gsl_block_char.h", "max_stars_repo_name": "dynaryu/vaws", "max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/gsl/include/gsl/gsl_block_char.h", "max_issues_repo_name": "dynaryu/vaws", "max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/gsl/include/gsl/gsl_block_char.h", "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6268656716, "max_line_length": 131, "alphanum_fraction": 0.772208639, "num_tokens": 641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09268776861426219, "lm_q2_score": 0.018833131886724176, "lm_q1q2_score": 0.0017456009705985734}}
{"text": "/*\n  Copyright [2017-2021] [IBM Corporation]\n  Licensed under the Apache License, Version 2.0 (the \"License\");\n  you may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n  http://www.apache.org/licenses/LICENSE-2.0\n  Unless required by applicable law or agreed to in writing, software\n  distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions and\n  limitations under the License.\n*/\n\n#ifndef __API_MCAS_ITF__\n#define __API_MCAS_ITF__\n\n#include <api/components.h>\n#include <api/kvindex_itf.h>\n#include <api/kvstore_itf.h>\n#include <boost/optional.hpp>\n#include <common/byte_span.h>\n#include <common/pointer_cast.h>\n#include <common/string_view.h>\n#include <gsl/span>\n\n#include <array>\n#include <cstdint> /* uint16_t */\n#include <memory>\n\n#define DECLARE_OPAQUE_TYPE(NAME)               \\\n  struct Opaque_##NAME {                        \\\n    virtual ~Opaque_##NAME() {}                 \\\n  }\n\nnamespace component\n{\n/**\n * mcas client interface (this will include both KV and AS capabilities)\n */\n\nclass IMCAS : public component::IBase,\n              public KVStore\n{\npublic:\n  // clang-format off\n  DECLARE_INTERFACE_UUID(0x33af1b99,0xbc51,0x49ff,0xa27b,0xd4,0xe8,0x19,0x03,0xbb,0x02);\n  // clang-format on\n\npublic:\n  DECLARE_OPAQUE_TYPE(async_handle);\n\n  using async_handle_t  = Opaque_async_handle*;\n  using pool_t          = component::KVStore::pool_t;\n  using key_t           = KVStore::key_t;\n  using Attribute       = KVStore::Attribute;\n  using Addr            = KVStore::Addr;\n\n  static constexpr async_handle_t  ASYNC_HANDLE_INIT  = nullptr;\n\n  enum {\n        FLAGS_NONE        = KVStore::FLAGS_NONE,\n        FLAGS_READ_ONLY   = KVStore::FLAGS_READ_ONLY,\n        FLAGS_SET_SIZE    = KVStore::FLAGS_SET_SIZE,\n        FLAGS_CREATE_ONLY = KVStore::FLAGS_CREATE_ONLY,\n        FLAGS_DONT_STOMP  = KVStore::FLAGS_DONT_STOMP,\n        FLAGS_NO_RESIZE   = KVStore::FLAGS_NO_RESIZE,\n        FLAGS_MAX_VALUE   = KVStore::FLAGS_MAX_VALUE,\n  };\n\n\n  /* per-shard statistics */\n  struct Shard_stats {\n    uint64_t op_request_count;\n    uint64_t op_put_count;\n    uint64_t op_get_count;\n    uint64_t op_put_direct_count;\n    uint64_t op_get_direct_count;\n    uint64_t op_get_twostage_count;\n    uint64_t op_ado_count;\n    uint64_t op_erase_count;\n    uint64_t op_get_direct_offset_count;\n    uint64_t op_failed_request_count;\n    uint64_t last_op_count_snapshot;\n    uint16_t client_count;\n\n  public:\n    Shard_stats()\n      : op_request_count(0)\n      , op_put_count(0), op_get_count(0), op_put_direct_count(0), op_get_direct_count(0), op_get_twostage_count(0)\n      , op_ado_count(0), op_erase_count(0), op_get_direct_offset_count(0)\n      , op_failed_request_count(0), last_op_count_snapshot(0), client_count(0)\n    {\n    }\n  } __attribute__((packed));\n\n  using ado_flags_t = uint32_t;\n\n  static constexpr ado_flags_t ADO_FLAG_NONE = 0;\n  /*< operation is asynchronous */\n  static constexpr ado_flags_t ADO_FLAG_ASYNC = (1 << 0);\n  /*< create KV pair if needed */\n  static constexpr ado_flags_t ADO_FLAG_CREATE_ON_DEMAND = (1 << 1);\n  /*< create only - allocate key,value but don't call ADO */\n  static constexpr ado_flags_t ADO_FLAG_CREATE_ONLY = (1 << 2);\n  /*< do not overwrite value if it already exists */\n  static constexpr ado_flags_t ADO_FLAG_NO_OVERWRITE = (1 << 3);\n  /*< create value but do not attach to key, unless key does not exist */\n  static constexpr ado_flags_t ADO_FLAG_DETACHED = (1 << 4);\n  /*< only take read lock */\n  static constexpr ado_flags_t ADO_FLAG_READ_ONLY = (1 << 5);\n  /*< zero any newly allocated value memory */\n  static constexpr ado_flags_t ADO_FLAG_ZERO_NEW_VALUE = (1 << 6);\n  /*< internal use only: on return provide IO response */\n  static constexpr ado_flags_t ADO_FLAG_INTERNAL_IO_RESPONSE = (1 << 7);\n  /*< internal use only: on return provide IO response with value buffer */\n  static constexpr ado_flags_t ADO_FLAG_INTERNAL_IO_RESPONSE_VALUE = (1 << 8);\n\npublic:\n  /**\n   * Determine thread safety of the component\n   *\n   *\n   * @return THREAD_MODEL_XXXX\n   */\n  virtual int thread_safety() const = 0;\n\n  /**\n   * If the ADO is configured for the shard then the ADO process is\n   * instantiated \"attached\" to the pool.\n   *\n   * The \"base\" parameter is unused.\n   */\n  using KVStore::create_pool;\n  using KVStore::open_pool;\n\n  using KVStore::delete_pool;\n\n  /**\n   * Close and delete an existing pool from a pool handle. Only one\n   * reference count should exist. Any ADO plugin is notified before\n   * the pool is deleted.\n   *\n   * @param pool Pool handle\n   *\n   * @return S_OK or E_BUSY if reference count > 1\n   */\n  virtual status_t delete_pool(const pool_t pool) = 0;\n\n  /**\n   * Configure a pool\n   *\n   * @param setting Configuration request (e.g., AddIndex::VolatileTree)\n\n   *\n   * @return S_OK on success\n   */\n  virtual status_t configure_pool(const pool_t pool, const std::string& setting) = 0;\n\n  using KVStore::put;\n\n  virtual status_t put(const pool_t pool,\n                       const std::string&  key,\n                       const std::string&  value,\n                       const unsigned int  flags = FLAGS_NONE)\n  {\n    /* this does not store any null terminator */\n    return put(pool, key, value.data(), value.length(), flags);\n  }\n\n  /*\n   * Asynchronous put operation.  Use check_async_completion to check for\n   * completion. This operation is not normally used, simple put is fast.\n   *\n   * @param pool Pool handle\n   * @param key Object key\n   * @param value Value\n\n   * @param value_len Value length in bytes\n   * @param out_handle Async work handle\n   * @param flags Optional flags\n   *\n   * @return S_OK or other error code\n   */\n  virtual status_t async_put(const IMCAS::pool_t pool,\n                             const std::string&  key,\n                             const void*         value,\n                             const size_t        value_len,\n                             async_handle_t&     out_handle,\n                             const unsigned int  flags = IMCAS::FLAGS_NONE) = 0;\n\n  virtual status_t async_put(const IMCAS::pool_t pool,\n                             const std::string&  key,\n                             const std::string&  value,\n                             async_handle_t&     out_handle,\n                             const unsigned int  flags = IMCAS::FLAGS_NONE)\n  {\n    (void)out_handle; // unused\n    return async_put(pool, key, value.data(), value.length(), out_handle, flags);\n  }\n\n  /**\n   * Zero-copy only if value size > ~2MiB or FORCE_DIRECT=1 is set.\n   */\n  using KVStore::put_direct;\n\n  /**\n   * Asynchronous put_direct operation.  Use check_async_completion to check for\n   * completion.\n   *\n   * @param pool Pool handle\n   * @param key Object key\n   * @param value Value\n   * @param value_len Value length in bytes\n   * @param handle Memory registration handle\n   * @param out_handle Async handle\n   * @param flags Optional flags\n   *\n   * @return S_OK or other error code\n   */\n  virtual status_t async_put_direct(const IMCAS::pool_t   pool,\n                                    const std::string&    key,\n                                    const void*           value,\n                                    const size_t          value_len,\n                                    async_handle_t&       out_handle,\n                                    const memory_handle_t handle = IMCAS::MEMORY_HANDLE_NONE,\n                                    const unsigned int    flags  = IMCAS::FLAGS_NONE)\n  {\n    return\n      async_put_direct(\n                       pool\n                       , key\n                       , std::array<common::const_byte_span,1>{common::make_const_byte_span(value, value_len)}\n                       , out_handle, std::array<memory_handle_t,1>{handle}\n                       , flags\n                       );\n  }\n\n  /**\n   * Asynchronous put_direct operation.  Use check_async_completion to check for\n   * completion.\n   *\n   * @param pool Pool handle\n   * @param key Object key\n   * @param values list of value sources\n   * @param out_handle Async handle\n   * @param handle List of memory registration handle\n   * @param flags Optional flags\n   *\n   * @return S_OK or other error code\n   */\n  virtual status_t async_put_direct(const IMCAS::pool_t   pool,\n                                    const std::string&    key,\n                                    gsl::span<const common::const_byte_span> value,\n                                    async_handle_t&       out_handle,\n                                    gsl::span<const memory_handle_t> handles = gsl::span<const memory_handle_t>(),\n                                    const unsigned int    flags  = IMCAS::FLAGS_NONE) = 0;\n\n  using KVStore::get;\n\n  virtual status_t get(const pool_t pool,\n                       const std::string& key,\n                       std::string& out_value)\n  {\n    void*  val      = nullptr;\n    size_t val_size = 0;\n    auto   s        = this->get(pool, key, val, val_size);\n\n    /* copy result */\n    if (s == S_OK) {\n      out_value.assign(static_cast<char*>(val), val_size);\n      this->free_memory(val);\n    }\n    return s;\n  }\n\n  /**\n   * Asynchronously read an object value directly into client-provided memory.\n   *\n   * @param pool Pool handle\n   * @param key Object key\n   * @param out_value Client provided buffer for value\n   * @param out_value_len [in] size of value memory in bytes [out] size of value\n   * @param out_handle Async work handle\n   * @param handle Memory registration handle\n   *\n   * @return S_OK, S_MORE if only a portion of value is read, E_BAD_ALIGNMENT on\n   * invalid alignment, or other error code\n   */\n  virtual status_t async_get_direct(const IMCAS::pool_t          pool,\n                                    const std::string&           key,\n                                    void*                        out_value,\n                                    size_t&                      out_value_len,\n                                    async_handle_t&              out_handle,\n                                    const IMCAS::memory_handle_t handle = IMCAS::MEMORY_HANDLE_NONE) = 0;\n\n  /**\n   * Read memory directly into client-provided memory.\n   *\n   * @param pool Pool handle\n   * @param offset offset within ithe concatenation of the pool's memory regions\n   * @param size requested size (becomes available size)\n   * @param out_buffer Client provided buffer for value\n   * @param out_handle Async work handle\n   * @param handle Memory registration handle\n   *\n   * @return S_OK, or error code\n   */\n  virtual status_t async_get_direct_offset(const IMCAS::pool_t pool,\n                                           const offset_t offset,\n                                           size_t &size,\n                                           void* out_buffer,\n                                           async_handle_t& out_handle,\n                                           const IMCAS::memory_handle_t handle = IMCAS::MEMORY_HANDLE_NONE) = 0;\n\n  virtual status_t get_direct_offset(const IMCAS::pool_t pool,\n                                     const offset_t offset,\n                                     size_t &size,\n                                     void* out_buffer,\n                                     const IMCAS::memory_handle_t handle = IMCAS::MEMORY_HANDLE_NONE) = 0;\n\n  /**\n   * Write memory directly into client-provided memory.\n   *\n   * @param pool Pool handle\n   * @param offset offset within ithe concatenation of the pool's memory regions\n   * @param size offered size (becomes available size)\n   * @param buffer Client provided value\n   * @param out_handle Async work handle\n   * @param handle Memory registration handle\n   *\n   * @return S_OK, or error code\n   */\n  virtual status_t async_put_direct_offset(const IMCAS::pool_t pool,\n                                           const offset_t offset,\n                                           size_t &size,\n                                           const void *const buffer,\n                                           async_handle_t& out_handle,\n                                           const IMCAS::memory_handle_t handle = IMCAS::MEMORY_HANDLE_NONE) = 0;\n\n  virtual status_t put_direct_offset(const IMCAS::pool_t pool,\n                                     const offset_t offset,\n                                     size_t &size,\n                                     const void *const buffer,\n                                     const IMCAS::memory_handle_t handle = IMCAS::MEMORY_HANDLE_NONE) = 0;\n\n  /**\n   * Check for completion from asynchronous invocation\n   *\n   * @param handle Asynchronous work handle.\n   *\n   * @return S_OK or E_BUSY if not yet complete\n   */\n  virtual status_t check_async_completion(async_handle_t& handle) = 0;\n\n  /**\n   * Perform key search based on regex or prefix\n   *\n   * @param pool Pool handle\n   * @param key_expression Regular expression or prefix (e.g. \"prefix:carKey\")\n   * @param offset Offset from which to search\n   * @param out_matched_offset Out offset of match\n   * @param out_keys Out vector of matching keys\n   *\n   * @return S_OK on success\n   */\n  virtual status_t find(const IMCAS::pool_t pool,\n                        const std::string&  key_expression,\n                        const offset_t      offset,\n                        offset_t&           out_matched_offset,\n                        std::string&        out_matched_key) = 0;\n\n  /**\n   * Erase an object asynchronously\n   *\n   * @param pool Pool handle\n   * @param key Object key\n   * @param out_handle Async work handle\n   *\n   * @return S_OK or error code\n   */\n  virtual status_t async_erase(const IMCAS::pool_t pool, const std::string& key, async_handle_t& out_handle) = 0;\n\n  /**\n   * Retrieve shard statistics\n   *\n   * @param out_stats\n   *\n   * @return S_OK on success\n   */\n  virtual status_t get_statistics(Shard_stats& out_stats) = 0;\n\n  /**\n   * ADO_response data structure manages response data sent back from the ADO\n   * invocations.  The free function is so we can eventually support zero-copy.\n   * The layer id identifies which ADO plugin the response came from.\n   */\n  class ADO_response {\n\n  private:\n\n#pragma GCC diagnostic push /* pointer members are considered inefficient */\n#pragma GCC diagnostic ignored \"-Weffc++\"\n\n    class Data_reference {\n    public:\n      Data_reference(void * data) : _data(data) { assert(data); }\n      Data_reference() = delete;\n      virtual ~Data_reference() { assert(_data); ::free(_data); }\n      void * _data;\n    };\n\n#pragma GCC diagnostic pop\n\n  public:\n    ADO_response() = delete;\n\n    ADO_response(void* data, size_t data_len, uint32_t layer_id)\n      : _ref(std::make_shared<Data_reference>(data)),\n        _data_len(data_len),\n        _layer_id(layer_id) {}\n\n    ADO_response(ADO_response&& src) noexcept\n      : _ref(src.datasp()),\n        _data_len(src.data_len()),\n        _layer_id(src.layer_id()) {}\n\n    inline std::string str() const { return std::string(data(), data_len()); }\n    inline const char* data() const { return static_cast<const char*>(_ref->_data); }\n    inline size_t data_len() const { return _data_len; }\n    inline uint32_t layer_id() const { return _layer_id; }\n    inline std::shared_ptr<Data_reference>& datasp() { return _ref; }\n\n    template <typename T>\n    inline T* cast_data() const  {  return static_cast<T*>(_ref->_data);   }\n\n  private:\n    std::shared_ptr<Data_reference> _ref; /* smart pointer */\n    size_t                          _data_len;\n    uint32_t                        _layer_id; /* optional layer identifier */\n  };\n\n\n  /**\n   * Used to invoke an operation on an active data object\n   *\n   * Roughly, the shard locates a data value by key and calls ADO (with accessors to both the key and data).\n   *   Several variations:\n   *       1) Skip the \"locate data\" operation (could have been directed by a null\n   *          key address in the basic_string_view form, or by a flag, but is\n   *          instead indicated by a zero-length key)\n   *       2) Skip the ADO call (directed by ADO_FLAG_CREATE_ONLY)\n   *       3) Create uninitialized data of size value_size if the key was not found\n   *          (directed by ADO_FLAG_CREATE_ON_DEMAND)\n   *       4) Create uninitialized data of size value_size if the key was not found(?)\n   *          not associated with the key and maybe also create a \"root value\" which\n   *          which is attached to the key (directed by ADO_FLAG_DETACHED)\n   *\n   * @param pool Pool handle\n   * @param key Key. Note, if key is empty, the work request is key-less.\n   * @param request Request data\n   * @param request_len Length of request in bytes\n   * @param flags Flags for invocation (see ADO_FLAG_CREATE_ONLY, ADO_FLAG_READ_ONLY)\n   * @param out_response Responses from invocation\n   * @param value_size Optional parameter to define value size to create for\n   * on-demand\n   *\n   * @return S_OK on success\n   */\n  virtual status_t invoke_ado(const IMCAS::pool_t           pool,\n                              const basic_string_view<byte> key,\n                              const basic_string_view<byte> request,\n                              const ado_flags_t             flags,\n                              std::vector<ADO_response>&    out_response,\n                              const size_t                  value_size = 0) = 0;\n\n  virtual status_t invoke_ado(const IMCAS::pool_t        pool,\n                              const std::string&         key,\n                              const void*                request,\n                              const size_t               request_len,\n                              const ado_flags_t          flags,\n                              std::vector<ADO_response>& out_response,\n                              const size_t               value_size = 0)\n  {\n    return\n      invoke_ado(pool,\n                 basic_string_view<byte>(common::pointer_cast<const byte>(key.data()), key.size()),\n                 basic_string_view<byte>(static_cast<const byte *>(request), request_len),\n                 flags, out_response, value_size);\n  }\n\n  inline status_t invoke_ado(const IMCAS::pool_t        pool,\n                             const std::string&         key,\n                             const std::string&         request,\n                             const ado_flags_t          flags,\n                             std::vector<ADO_response>& out_response,\n                             const size_t               value_size = 0)\n  {\n    return\n      invoke_ado(pool, key, request.data(), request.length(), flags, out_response, value_size);\n  }\n\n\n  /**\n   * Used to asynchronously invoke an operation on an ADO\n   *\n   * Roughly, the shard locates a data value by key and calls ADO (with accessors to both the key and data).\n   *\n   * @param pool Pool handle\n   * @param key Key. Note, if key is empty, the work request is key-less.\n   * @param request Request data\n   * @param request_len Length of request in bytes\n   * @param flags Flags for invocation (see ADO_FLAG_XXX)\n   * @param out_response Response passed back from ADO invocation\n   * @param out_async_handle Handle to task for later result collection\n   * @param value_size Optional parameter to define value size to create for on-demand\n   *\n   * @return S_OK on success\n   */\n  virtual status_t async_invoke_ado(const IMCAS::pool_t           pool,\n                                    const basic_string_view<byte> key,\n                                    const basic_string_view<byte> request,\n                                    const ado_flags_t             flags,\n                                    std::vector<ADO_response>&    out_response,\n                                    async_handle_t&               out_async_handle,\n                                    const size_t                  value_size = 0) = 0;\n\n  inline status_t async_invoke_ado(const IMCAS::pool_t        pool,\n                                   const std::string&         key,\n                                   const std::string&         request,\n                                   const ado_flags_t          flags,\n                                   std::vector<ADO_response>& out_response,\n                                   async_handle_t&            out_async_handle,\n                                   const size_t               value_size = 0)\n  {\n    return\n      async_invoke_ado(pool,\n                       basic_string_view<byte>(common::pointer_cast<const byte>(key.data()), key.size()),\n                       basic_string_view<byte>(common::pointer_cast<const byte>(request.data()), request.length()),\n                       flags, out_response, out_async_handle, value_size);\n  }\n\n  inline status_t async_invoke_ado(const IMCAS::pool_t        pool,\n                                   const std::string&         key,\n                                   const void*                request,\n                                   const size_t               request_len,\n                                   const ado_flags_t          flags,\n                                   std::vector<ADO_response>& out_response,\n                                   async_handle_t&            out_async_handle,\n                                   const size_t               value_size = 0)\n  {\n    return\n      async_invoke_ado(pool,\n                       basic_string_view<byte>(common::pointer_cast<const byte>(key.data()), key.size()),\n                       basic_string_view<byte>(static_cast<const byte *>(request), request_len),\n                       flags, out_response, out_async_handle, value_size);\n  }\n\n\n  /**\n   * Used to invoke a combined put + ADO operation on an active data object.\n   *\n   * Roughly, the shard writes a data value by key and calls ADO (with accessors to both the key and data).\n   *\n   * @param pool Pool handle\n   * @param key Key\n   * @param request Request data\n   * @param request_len Length of request data in bytes\n   * @param value Value data\n   * @param value_len Length of value data in bytes\n   * @param root_len Length to allocate for root value (with ADO_FLAG_DETACHED)\n   * @param flags Flags for invocation (ADO_FLAG_NO_OVERWRITE, ADO_FLAG_DETACHED)\n   * @param out_response Response passed back from ADO invocation\n   *\n   * @return S_OK on success\n   */\n  virtual status_t invoke_put_ado(const IMCAS::pool_t           pool,\n                                  const basic_string_view<byte> key,\n                                  const basic_string_view<byte> request,\n                                  const basic_string_view<byte> value,\n                                  const size_t                  root_len,\n                                  const ado_flags_t             flags,\n                                  std::vector<ADO_response>&    out_response) = 0;\n\n  virtual status_t invoke_put_ado(const IMCAS::pool_t        pool,\n                                  const std::string&         key,\n                                  const void*                request,\n                                  const size_t               request_len,\n                                  const void*                value,\n                                  const size_t               value_len,\n                                  const size_t               root_len,\n                                  const ado_flags_t          flags,\n                                  std::vector<ADO_response>& out_response)\n  {\n    return\n      invoke_put_ado(pool,\n                     basic_string_view<byte>(common::pointer_cast<const byte>(key.data()), key.size()),\n                     basic_string_view<byte>(static_cast<const byte *>(request), request_len),\n                     basic_string_view<byte>(static_cast<const byte *>(value), value_len),\n                     root_len, flags, out_response);\n  }\n\n  inline status_t invoke_put_ado(const IMCAS::pool_t        pool,\n                                 const std::string&         key,\n                                 const std::string&         request,\n                                 const std::string&         value,\n                                 const size_t               root_len,\n                                 const ado_flags_t          flags,\n                                 std::vector<ADO_response>& out_response)\n  {\n    return invoke_put_ado(pool,\n                          key,\n                          request.data(),\n                          request.length(),\n                          value.data(),\n                          value.length(),\n                          root_len,\n                          flags,\n                          out_response);\n  }\n\n  /**\n   * Used to asynchronously invoke a combined put + ADO operation on an active data object.\n   *\n   * Roughly, the shard writes a data value by key and calls ADO (with accessors to both the key and data).\n   *\n   * @param pool Pool handle\n   * @param key Key\n   * @param request Request data\n   * @param request_len Length of request data in bytes\n   * @param value Value data\n   * @param value_len Length of value data in bytes\n   * @param root_len Length to allocate for root value (with ADO_FLAG_DETACHED)\n   * @param flags Flags for invocation (ADO_FLAG_NO_OVERWRITE, ADO_FLAG_DETACHED)\n   * @param out_response Responses from ADO invocation\n   * @param out_async_handle Handle to task for later result collection\n   *\n   * @return S_OK on success\n   */\n  virtual status_t async_invoke_put_ado(const IMCAS::pool_t           pool,\n                                        const basic_string_view<byte> key,\n                                        const basic_string_view<byte> request,\n                                        const basic_string_view<byte> value,\n                                        const size_t                  root_len,\n                                        const ado_flags_t             flags,\n                                        std::vector<ADO_response>&    out_response,\n                                        async_handle_t&               out_async_handle) = 0;\n\n  virtual status_t async_invoke_put_ado(const IMCAS::pool_t        pool,\n                                        const std::string&         key,\n                                        const void*                request,\n                                        const size_t               request_len,\n                                        const void*                value,\n                                        const size_t               value_len,\n                                        const size_t               root_len,\n                                        const ado_flags_t          flags,\n                                        std::vector<ADO_response>& out_response,\n                                        async_handle_t&            out_async_handle)\n  {\n    return\n      async_invoke_put_ado(pool,\n                           basic_string_view<byte>(common::pointer_cast<const byte>(key.data()), key.size()),\n                           basic_string_view<byte>(static_cast<const byte *>(request), request_len),\n                           basic_string_view<byte>(static_cast<const byte *>(value), value_len),\n                           root_len, flags, out_response, out_async_handle);\n  }\n\n  inline status_t async_invoke_put_ado(const IMCAS::pool_t        pool,\n                                       const std::string&         key,\n                                       const std::string&         request,\n                                       const std::string&         value,\n                                       const size_t               root_len,\n                                       const ado_flags_t          flags,\n                                       std::vector<ADO_response>& out_response,\n                                       async_handle_t&            out_async_handle)\n  {\n    return async_invoke_put_ado(pool,\n                                key,\n                                request.data(),\n                                request.length(),\n                                value.data(),\n                                value.length(),\n                                root_len,\n                                flags,\n                                out_response,\n                                out_async_handle);\n  }\n\n\n\n  /**\n   * Debug routine\n   *\n   * @param pool Pool handle\n   * @param cmd Debug command\n   * @param arg Parameter for debug operation\n   */\n  virtual void debug(const IMCAS::pool_t pool, const unsigned cmd, const uint64_t arg) = 0;\n};\n\n\nclass IMCAS_factory : public IKVStore_factory {\n  using string_view = common::string_view;\npublic:\n  // clang-format off\n  DECLARE_INTERFACE_UUID(0xfacf1b99,0xbc51,0x49ff,0xa27b,0xd4,0xe8,0x19,0x03,0xbb,0x02);\n  // clang-format on\n\n  /**\n   * Create a session to a remote shard\n   *\n   * @param debug_level         Debug level (0-3)\n   * @param patience            Time out patience in seconds\n   * @param owner               Owner info (not used)\n   * @param src_nic_device      Client-side network device (e.g., mlx5_0, eth0)\n   * @param src_ip_addr         Client-side IP address\n   * @param dest_addr_with_port Server-side IP address and port (e.g. 10.0.0.21:11911, 9.1.75.6:11911:sockets)\n   * @param other               Other optional parameters (e.g. { \"security\":\"tls:auth\" })\n   *\n   * @return Pointer to IMCAS instance. Use release_ref() to close.\n   */\n  virtual IMCAS* mcas_create_nsd(const unsigned, // debug_level\n                                 const unsigned, // patience\n                                 const string_view, // owner\n                                 const string_view, // src_nic_device\n                                 const string_view, // src_ip_addr\n                                 const string_view, // dest_addr_with_port\n                                 const string_view = string_view()) // other\n  {\n    throw API_exception(\"IMCAS_factory::mcas_create(debug_level,patience,owner,addr_with_port,nic_device) not implemented\");\n  }\n\n  /** \n   * Create a session to a remote shard (alternative)\n   * \n   * @param debug_level          Debug level\n   * @param patience             Timeout patience in seconds\n   * @param owner                Owner information (not used)\n   * @param dest_addr_with_port  Destination server IP address and port\n   * @param nic_device           Local NIC device to use (e.g., mlx5_0, eth0)\n   * @param other                Other optional parameters (e.g. { \"security\":\"tls:auth\" })\n   * \n   * @return Pointer to IMCAS instance. Use release_ref() to close.\n   */\n  IMCAS* mcas_create(const unsigned    debug_level,\n                     const unsigned    patience,\n                     const string_view owner,\n                     const string_view dest_addr_with_port,\n                     const string_view nic_device,\n                     const string_view other = string_view())\n  {\n    return mcas_create_nsd(debug_level, patience, owner, nic_device, string_view(), dest_addr_with_port, other);\n  }\n};\n\n}  // namespace component\n\n#endif\n", "meta": {"hexsha": "6cd25105178115cf74054b1f7c7c9b94876b9d21", "size": 31183, "ext": "h", "lang": "C", "max_stars_repo_path": "src/components/api/mcas_itf.h", "max_stars_repo_name": "IBM/artemis", "max_stars_repo_head_hexsha": "f655d6e952577de11b52e2f4ab6f48c73ce5dba1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/components/api/mcas_itf.h", "max_issues_repo_name": "IBM/artemis", "max_issues_repo_head_hexsha": "f655d6e952577de11b52e2f4ab6f48c73ce5dba1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/components/api/mcas_itf.h", "max_forks_repo_name": "IBM/artemis", "max_forks_repo_head_hexsha": "f655d6e952577de11b52e2f4ab6f48c73ce5dba1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.1385224274, "max_line_length": 124, "alphanum_fraction": 0.5580925504, "num_tokens": 6508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.0769608272276531, "lm_q2_score": 0.022629198096809116, "lm_q1q2_score": 0.0017415618050288628}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef widget_c3b57c97_cea3_4794_b683_762a7b11af49_h\r\n#define widget_c3b57c97_cea3_4794_b683_762a7b11af49_h\r\n\r\n#include <gslib/std.h>\r\n#include <gslib/dvt.h>\r\n#include <gslib/uuid.h>\r\n#include <ariel/sysop.h>\r\n#include <ariel/painter.h>\r\n\r\n__ariel_begin__\r\n\r\nclass wsys_manager;\r\n\r\nclass widget:\r\n    public dvt_holder\r\n{\r\n    friend class wsys_manager;\r\n\r\npublic:\r\n    widget(wsys_manager* m);\r\n    virtual ~widget();\r\n    virtual void* query_interface(const uuid& uid);\r\n    virtual bool create(widget* ptr, const gchar* name, const rect& rc, uint style);\r\n    virtual void close();\r\n    virtual void show(bool b);\r\n    virtual void enable(bool b);\r\n    virtual void move(const rect& rc);\r\n    virtual void refresh(const rect& rc, bool imm = false);\r\n    virtual void draw(painter* paint) {}\r\n    virtual widget* capture(bool b);\r\n    virtual widget* focus();\r\n    virtual bool hit_test(const point& pt) { return (_style & sm_hitable) != 0; }\r\n\r\npublic:\r\n    enum laytag\r\n    {\r\n        lay_before,\r\n        lay_after,\r\n        lay_first,\r\n        lay_last,\r\n    };\r\n    virtual void lay(widget* ptr, laytag t);\r\n\r\npublic:\r\n    virtual void on_press(uint um, unikey uk, const point& pt);\r\n    virtual void on_click(uint um, unikey uk, const point& pt);\r\n    virtual void on_hover(uint um, const point& pt);\r\n    virtual void on_leave(uint um, const point& pt);\r\n    virtual void on_keydown(uint um, unikey uk) {}\r\n    virtual void on_keyup(uint um, unikey uk) {}\r\n    virtual void on_char(uint um, uint ch) {}\r\n    virtual void on_caret() {}\r\n    virtual void on_capture(bool b) {}\r\n    virtual void on_focus(bool b) {}\r\n    virtual void on_accelerator(unikey key, uint mask) {}\r\n\r\nprotected:\r\n    wsys_manager*   _manager;\r\n    string          _name;\r\n    uint            _style;\r\n    rect            _pos;\r\n    bool            _visible;\r\n    bool            _enabled;\r\n\r\npublic:\r\n    const string& get_name() const { return _name; }\r\n    const rect& get_rect() const { return _pos; }\r\n    rectf get_rectf() const { return to_rectf(get_rect()); }\r\n    bool is_visible() const { return _visible && (_style & sm_visible); }\r\n    bool is_enabled() const { return _enabled; }\r\n    bool is_focused() const;\r\n    void hide() { show(false); }\r\n    void disable() { enable(false); }\r\n    point& to_global(point& pt) const;\r\n    rect& to_global(rect& rc) const;\r\n    point& to_local(point& pt) const;\r\n    rect& to_local(rect& rc) const;\r\n    void move(const point& pt);\r\n    void resize(int w, int h);\r\n    void refresh(bool imm);\r\n    int get_width() const { return _pos.width(); }\r\n    int get_height() const { return _pos.height(); }\r\n    wsys_manager* get_manager() const { return _manager; }\r\n    bool register_accelerator(unikey key, uint mask);\r\n    widget* unregister_accelerator(unikey key, uint mask);\r\n\r\nprotected:\r\n    widget*         _prev;\r\n    widget*         _next;\r\n    widget*         _child;\r\n    widget*         _last_child;\r\n    widget*         _parent;\r\n\r\npublic:\r\n    widget* get_parent() const { return _parent; }\r\n    widget* get_prev() const { return _prev; }\r\n    widget* get_next() const { return _next; }\r\n    widget* get_child() const { return _child; }\r\n    widget* get_last_child() const { return _last_child; }\r\n\r\npublic:\r\n    template<class _lamb>\r\n    static int traverse_widget(widget* w, _lamb trav_to_stop)\r\n    {\r\n        assert(w);\r\n        for(auto* p = w; p; p = p->get_next()) {\r\n            if(auto r = trav_to_stop(p))\r\n                return r;\r\n        }\r\n        return 0;\r\n    }\r\n    template<class _lamb>\r\n    static int traverse_widget_reversed(widget* w, _lamb trav_to_stop)\r\n    {\r\n        assert(w);\r\n        for(auto* p = w; p; p = p->get_prev()) {\r\n            if(auto r = trav_to_stop(p))\r\n                return r;\r\n        }\r\n        return 0;\r\n    }\r\n    template<class _lamb>\r\n    int traverse_child_widget(_lamb trav_to_stop) { return traverse_widget(_child, trav_to_stop); }\r\n    template<class _lamb>\r\n    int traverse_child_widget_reversed(_lamb trav_to_stop) { return traverse_widget_reversed(_last_child, trav_to_stop); }\r\n};\r\n\r\nclass button:\r\n    public widget\r\n{\r\npublic:\r\n    typedef widget superref;\r\n    typedef button self;\r\n\r\npublic:\r\n    button(wsys_manager* m);\r\n    virtual ~button();\r\n    virtual void draw(painter* paint) override;\r\n    virtual void enable(bool b) override;\r\n    virtual void on_press(uint um, unikey uk, const point& pt) override;\r\n    virtual void on_click(uint um, unikey uk, const point& pt) override;\r\n    virtual void on_hover(uint um, const point& pt) override;\r\n    virtual void on_leave(uint um, const point& pt) override;\r\n\r\nprotected:\r\n    virtual void set_press();\r\n    virtual void set_normal();\r\n    virtual void set_hover();\r\n    virtual void set_gray();\r\n\r\nprotected:\r\n    texture2d*      _source;\r\n    texture2d*      _bkground;\r\n    bool            _4states;\r\n\r\npublic:\r\n    void set_image(texture2d* img, bool fs = false);\r\n\r\n    enum btnstate\r\n    {\r\n        bs_none     = 0,\r\n        bs_press,\r\n        bs_hover,\r\n        bs_normal,\r\n    };\r\n    void set_btnstate(btnstate bs) { _btnstate = bs; }\r\n    btnstate get_btnstate() const { return _btnstate; }\r\n\r\nprotected:\r\n    btnstate        _btnstate;\r\n};\r\n\r\nclass edit_line:\r\n    public widget\r\n{\r\npublic:\r\n    typedef widget superref;\r\n    typedef edit_line self;\r\n\r\npublic:\r\n    edit_line(wsys_manager* m);\r\n    virtual void draw(painter* paint) override;\r\n    virtual void on_press(uint um, unikey uk, const point& pt) override;\r\n    virtual void on_click(uint um, unikey uk, const point& pt) override;\r\n    virtual void on_hover(uint um, const point& pt) override;\r\n    virtual void on_char(uint um, uint ch) override;\r\n    virtual void on_keydown(uint um, unikey uk) override;\r\n    virtual void on_caret() override;\r\n    virtual void on_focus(bool b) override;\r\n\r\nprotected:\r\n    bool            _caret_on;\r\n    int             _caretpos;\r\n    string          _textbuf;\r\n    int             _sel_start;\r\n    int             _sel_end;\r\n\r\npublic:\r\n    virtual void set_text(const gchar* str);\r\n    virtual void set_caret(int n);\r\n    virtual void set_select(int start, int end);\r\n    virtual void replace_select(const gchar* str);\r\n\r\nprotected:\r\n    virtual void draw_background(painter* paint);\r\n    virtual void draw_normal_text(painter* paint);\r\n    virtual void draw_select_text(painter* paint);\r\n    virtual void draw_caret(painter* paint);\r\n\r\npublic:\r\n    void set_font(const font& ft) { _font = ft; }\r\n    void set_bkground(texture2d* ptr) { _bkground = ptr; }\r\n    void set_text_color(color cr) { _txtcolor = cr; }\r\n    void set_select_color(color cr) { _selcolor = cr; }\r\n    void set_caret_color(color cr) { _crtcolor = cr; }\r\n    const gchar* get_text() const { return _textbuf.c_str(); }\r\n    void del_select();\r\n    int hit_char(point pt);\r\n    int prev_char(int pos);\r\n    int next_char(int pos);\r\n    int prev_logic_char(int pos);\r\n    int next_logic_char(int pos);\r\n    bool no_select() const { return _sel_start == -1 || _sel_start == _sel_end; }\r\n\r\nprotected:\r\n    texture2d*      _bkground;\r\n    color           _txtcolor;\r\n    color           _selcolor;\r\n    color           _crtcolor;\r\n    font            _font;\r\n\r\nprotected:\r\n    int trim_if_overrun(bool alarm);\r\n};\r\n\r\ntypedef system_driver wsys_driver;\r\ntypedef system_notify wsys_notify;\r\n\r\nclass timer:\r\n    public dvt_holder\r\n{\r\npublic:\r\n    timer(wsys_manager* mgr);\r\n    void start(int elapse);\r\n    void start_single(int elapse);\r\n    void set_user_data(uint usd) { _userdata = usd; }\r\n    uint get_user_data() const { return _userdata; }\r\n\r\npublic:\r\n    virtual ~timer();\r\n    virtual void on_timer(uint tid) {}\r\n    virtual void on_notified();             /* CANNOT be used by connect notify */\r\n\r\nprotected:\r\n    wsys_driver*    _driver;\r\n    uint            _userdata;\r\n    int             _elapse;\r\n    bool            _single;\r\n\r\nprivate:\r\n    void initialize(wsys_driver* drv);\r\n};\r\n\r\nstruct accel_key\r\n{\r\n    unikey          key;\r\n    uint            mask;\r\n\r\npublic:\r\n    accel_key(): key((unikey)-1), mask(0) {}        /* invalid */\r\n    accel_key(unikey k, uint m): key(k), mask(m) {}\r\n    bool is_valid() const { return key != (unikey)-1; }\r\n    bool operator == (const accel_key& that) const { return key == that.key && mask == that.mask; }\r\n    bool from_string(const string& str);\r\n    const string& to_string(string& str) const;\r\n};\r\n\r\nclass wsys_manager:\r\n    public wsys_notify\r\n{\r\npublic:\r\n    wsys_manager();\r\n    void set_wsysdrv(wsys_driver* drv);\r\n    void set_painter(painter* paint);\r\n    painter* get_painter() const { return _painter; }\r\n    wsys_driver* get_driver() const { return _driver; }\r\n    void initialize(const rect& rc);\r\n\r\nprotected:\r\n    wsys_driver*    _driver;\r\n    painter*        _painter;\r\n    dirty_list      _dirty;\r\n    int             _width;\r\n    int             _height;\r\n    timer*          _caret;\r\n\r\npublic:\r\n    void set_dimension(int w, int h);\r\n    int get_width() const { return _width; }\r\n    int get_height() const { return _height; }\r\n    void refresh() { _dirty.set_whole(); }\r\n    void refresh(const rect& rc, bool imm = false);\r\n    void update();\r\n    void update(widget* w);\r\n    widget* hit_test(point pt) { return hit_test(_root, pt); }\r\n    widget* hit_test(widget* ptr, point pt);\r\n    widget* hit_proc(const point& pt, point& pt1);\r\n    widget* set_capture(widget* ptr, bool b);\r\n    widget* set_focus(widget* ptr);\r\n    void on_caret(uint);\r\n    widget* get_capture() const { return _capture; }\r\n    widget* get_focus() const { return _focus; }\r\n    void set_cursor(cursor_type curty);\r\n    void reset_cursor() { set_cursor(cur_arrow); }\r\n\r\npublic:\r\n    virtual ~wsys_manager();\r\n    virtual void on_show(bool b) override;\r\n    virtual void on_create(wsys_driver* ptr, const rect& rc) override;\r\n    virtual void on_close() override;\r\n    virtual void on_resize(const rect& rc) override;\r\n    virtual void on_paint(const rect& rc) override;\r\n    virtual void on_halt() override;\r\n    virtual void on_resume() override;\r\n    virtual bool on_mouse_down(uint um, unikey uk, const point& pt) override;\r\n    virtual bool on_mouse_up(uint um, unikey uk, const point& pt) override;\r\n    virtual bool on_mouse_move(uint um, const point& pt) override;\r\n    virtual bool on_key_down(uint um, unikey uk) override;\r\n    virtual bool on_key_up(uint um, unikey uk) override;\r\n    virtual bool on_char(uint um, uint ch) override;\r\n    virtual void on_timer(uint tid) override;\r\n\r\nprotected:\r\n    widget*         _hover;\r\n    widget*         _capture;\r\n    widget*         _focus;\r\n    widget*         _root;\r\n\r\nprivate:\r\n    typedef unordered_map<string, widget*> widget_map;\r\n    widget_map      _widget_map;\r\n\r\npublic:\r\n    template<class _ctor>\r\n    _ctor* add_widget(widget* ptr, const gchar* name, const rect& rc, uint style)\r\n    {\r\n        if(name && name[0] && _widget_map.find(name) != _widget_map.end())\r\n            return nullptr;\r\n        if(!ptr && _root)\r\n            ptr = _root;\r\n        _ctor* p = new _ctor(this);\r\n        assert(p);\r\n        if(!p->create(ptr, name ? name : _t(\"\"), rc, style)) {\r\n            delete p;\r\n            return nullptr;\r\n        }\r\n        if(name && name[0]) {\r\n            _widget_map.insert(\r\n                std::make_pair(name, p)\r\n                );\r\n        }\r\n        if(!ptr && !_root)\r\n            _root = p;\r\n        return p;\r\n    }\r\n    widget* get_root() const { return _root; }\r\n    widget* find_widget(const string& name);\r\n    bool remove_widget(widget* ptr);\r\n    bool remove_widget(const string& name);\r\n\r\nprotected:\r\n    bool remove_widget_internal(widget* ptr);\r\n\r\npublic:\r\n    void set_ime(widget* ptr, point pt, const font& ft);\r\n    void set_clipboard(clipfmt fmt, const void* ptr, int size);\r\n    int get_clipboard(clipfmt fmt, const void*& ptr);\r\n    int get_clipboard(clipboard_list& cl, int c);\r\n\r\nprotected:\r\n    struct accel_key_hasher { size_t operator()(const accel_key& kval) const { return hash_bytes((const byte*)&kval, sizeof(kval)); } };\r\n    typedef unordered_map<accel_key, widget*, accel_key_hasher> accel_map;\r\n    friend bool try_proceed_accelerator(const accel_map&, unikey, uint);\r\n    accel_map       _accel_map;\r\n\r\npublic:\r\n    bool register_accelerator(widget* w, unikey key, uint mask);\r\n    widget* unregister_accelerator(unikey key, uint mask);\r\n};\r\n\r\nextern const uuid uuid_widget;\r\n\r\n__ariel_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "41e97c1c282cc8c95ca1ebb3f48fc758de588a0f", "size": 13677, "ext": "h", "lang": "C", "max_stars_repo_path": "include/ariel/widget.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/ariel/widget.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ariel/widget.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 32.3333333333, "max_line_length": 137, "alphanum_fraction": 0.633691599, "num_tokens": 3312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06187599091348027, "lm_q2_score": 0.028007521924369488, "lm_q1q2_score": 0.0017329931721013858}}
{"text": "#pragma once\n#include \"iarglist.h\"\n#include \"optioninfo.h\"\n#include \"configaccess.h\"\n#include \"format.h\"\n#include \"streamreader.h\"\n#include <gsl/gsl>\n#include <cmdlime/errors.h>\n#include <cmdlime/customnames.h>\n#include <vector>\n#include <sstream>\n#include <functional>\n#include <memory>\n\nnamespace cmdlime::detail{\n\ntemplate <typename T>\nclass ArgList : public IArgList{\npublic:\n    ArgList(std::string name,\n            std::string type,\n            std::function<std::vector<T>&()> argListGetter)\n        : info_(std::move(name), {}, std::move(type))\n        , argListGetter_(std::move(argListGetter))\n    {\n    }\n\n    void setDefaultValue(const std::vector<T>& value)\n    {\n        hasValue_ = true;\n        defaultValue_ = value;\n    }\n\n    OptionInfo& info() override\n    {\n        return info_;\n    }\n\n    const OptionInfo& info() const override\n    {\n        return info_;\n    }\n\nprivate:\n    bool read(const std::string& data) override\n    {\n        if (!isDefaultValueOverwritten_){\n            argListGetter_().clear();\n            isDefaultValueOverwritten_ = true;\n        }\n        auto stream = std::stringstream{data};        \n        argListGetter_().emplace_back();\n        if (!readFromStream(stream, argListGetter_().back()))\n            return false;\n        hasValue_ = true;\n        return true;\n    }\n\n    bool hasValue() const override\n    {\n        return hasValue_;\n    }\n\n    bool isOptional() const override\n    {\n        return defaultValue_.has_value();\n    }\n\n    std::string defaultValue() const override\n    {\n        if (!defaultValue_.has_value())\n            return {};\n        auto stream = std::stringstream{};\n        stream << \"{\";\n        auto firstVal = true;\n        for (auto& val : defaultValue_.value()){\n            if (firstVal)\n                stream << val;\n            else\n                stream << \", \" << val;\n            firstVal = false;\n        }\n        stream << \"}\";\n        return stream.str();\n    }\n\nprivate:\n    OptionInfo info_;\n    std::function<std::vector<T>&()> argListGetter_;\n    bool hasValue_ = false;\n    std::optional<std::vector<T>> defaultValue_;\n    bool isDefaultValueOverwritten_ = false;\n};\n\ntemplate <>\ninline bool ArgList<std::string>::read(const std::string& data)\n{\n    argListGetter_().push_back(data);\n    hasValue_ = true;\n    return true;\n}\n\ntemplate<typename T, typename TConfig>\nclass ArgListCreator{\n    using NameProvider = typename Format<ConfigAccess<TConfig>::format()>::nameProvider;\n\npublic:\n    ArgListCreator(TConfig& cfg,\n                   const std::string& varName,\n                   const std::string& type,\n                   std::function<std::vector<T>&()> argListGetter)\n        : cfg_(cfg)\n    {\n        Expects(!varName.empty());\n        Expects(!type.empty());\n        argList_ = std::make_unique<ArgList<T>>(NameProvider::fullName(varName),\n                                                NameProvider::valueName(type),\n                                                std::move(argListGetter));\n    }\n\n    ArgListCreator<T, TConfig>& operator<<(const std::string& info)\n    {\n        argList_->info().addDescription(info);\n        return *this;\n    }\n\n    ArgListCreator<T, TConfig>& operator<<(const Name& customName)\n    {\n        argList_->info().resetName(customName.value());\n        return *this;\n    }\n\n    ArgListCreator<T, TConfig>& operator<<(const ValueName& valueName)\n    {\n        argList_->info().resetValueName(valueName.value());\n        return *this;\n    }\n\n    ArgListCreator<T, TConfig>& operator()(std::vector<T> defaultValue = {})\n    {\n        defaultValue_ = std::move(defaultValue);\n        argList_->setDefaultValue(defaultValue_);\n        return *this;\n    }\n\n    operator std::vector<T>()\n    {\n        ConfigAccess<TConfig>{cfg_}.setArgList(std::move(argList_));\n        return defaultValue_;\n    }\n\nprivate:\n    std::unique_ptr<ArgList<T>> argList_;\n    std::vector<T> defaultValue_;\n    TConfig& cfg_;\n};\n\ntemplate <typename T, typename TConfig>\nArgListCreator<T, TConfig> makeArgListCreator(TConfig& cfg,\n                                              const std::string& varName,\n                                              const std::string& type,\n                                              std::function<std::vector<T>&()> argListGetter)\n{\n    return ArgListCreator<T, TConfig>{cfg, varName, type, std::move(argListGetter)};\n}\n\n}\n", "meta": {"hexsha": "3c64f95b80e6c0be7f0a74137aa2c521606b0293", "size": 4383, "ext": "h", "lang": "C", "max_stars_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/arglist.h", "max_stars_repo_name": "GerHobbelt/hypertextcpp", "max_stars_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_stars_repo_licenses": ["MS-PL"], "max_stars_count": 77.0, "max_stars_repo_stars_event_min_datetime": "2021-05-20T18:05:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T21:37:54.000Z", "max_issues_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/arglist.h", "max_issues_repo_name": "GerHobbelt/hypertextcpp", "max_issues_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_issues_repo_licenses": ["MS-PL"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2021-05-20T22:04:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-21T08:13:28.000Z", "max_forks_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/arglist.h", "max_forks_repo_name": "GerHobbelt/hypertextcpp", "max_forks_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_forks_repo_licenses": ["MS-PL"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-22T00:36:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-22T00:36:08.000Z", "avg_line_length": 26.0892857143, "max_line_length": 93, "alphanum_fraction": 0.5728952772, "num_tokens": 979, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.0850990357257195, "lm_q2_score": 0.020332352452212377, "lm_q1q2_score": 0.0017302635877187416}}
{"text": "#ifndef LIC_RUNTIME_TYPE\n#define LIC_RUNTIME_TYPE\n\n#include <string>\n#include <gsl/gsl>\n\n#include <format/Opcodes.h>\n\nnamespace lic\n{\n\nclass RuntimeType\n{\npublic:\n    virtual ~RuntimeType();\n\n    virtual std::string Name() const = 0;\n    virtual std::string ToString(gsl::byte* data) const = 0;\n\n    virtual void PerformUnaryOp(Opcode op, gsl::byte* data) const;\n    virtual void PerformBinaryOp(Opcode op, gsl::byte* leftData, RuntimeType* rightType, gsl::byte* rightData) const;\n\nprotected:\n    RuntimeType();\n};\n\n}\n\n#endif // !LIC_RUNTIME_TYPE\n", "meta": {"hexsha": "7273d3632096d5fa8f96fba773d1c5f528466884", "size": 547, "ext": "h", "lang": "C", "max_stars_repo_path": "src/types/RuntimeType.h", "max_stars_repo_name": "roberthusak/lic", "max_stars_repo_head_hexsha": "5ad4a7014673bb60b748390856e0c7cb11eaca09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-05-18T11:44:16.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-18T11:44:16.000Z", "max_issues_repo_path": "src/types/RuntimeType.h", "max_issues_repo_name": "roberthusak/lic", "max_issues_repo_head_hexsha": "5ad4a7014673bb60b748390856e0c7cb11eaca09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/types/RuntimeType.h", "max_forks_repo_name": "roberthusak/lic", "max_forks_repo_head_hexsha": "5ad4a7014673bb60b748390856e0c7cb11eaca09", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.2333333333, "max_line_length": 117, "alphanum_fraction": 0.7129798903, "num_tokens": 141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.07263670836828977, "lm_q2_score": 0.023689473151804995, "lm_q1q2_score": 0.0017207253527260896}}
{"text": "#pragma once\n\n#include <gsl/gsl>\n\n#include \"halley/file_formats/config_file.h\"\n\nnamespace YAML {\n\tclass Node;\n\tclass Emitter;\n}\n\nnamespace Halley {\n\tclass Path;\n\n\tclass YAMLConvert {\n\tpublic:\n\t\tclass EmitOptions {\n\t\tpublic:\n\t\t\tVector<String> mapKeyOrder;\n\t\t};\n\t\t\n\t\tstatic void parseConfig(ConfigFile& config, gsl::span<const gsl::byte> data);\n\t\tstatic ConfigNode parseYAMLNode(const YAML::Node& node);\n\t\tstatic ConfigFile parseConfig(gsl::span<const gsl::byte> data);\n\t\tstatic ConfigFile parseConfig(const Bytes& data);\n\t\tstatic ConfigNode parseConfig(const String& str);\n\t\t\n\t\tstatic String generateYAML(const ConfigFile& config, const EmitOptions& options);\n\t\tstatic String generateYAML(const ConfigNode& node, const EmitOptions& options);\n\n\tprivate:\n\t\tstatic void emitNode(const ConfigNode& node, YAML::Emitter& emitter, const EmitOptions& options);\n\t\tstatic void emitSequence(const ConfigNode& node, YAML::Emitter& emitter, const EmitOptions& options);\n\t\tstatic void emitMap(const ConfigNode& node, YAML::Emitter& emitter, const EmitOptions& options);\n\t\tstatic bool isCompactSequence(const ConfigNode& node, int depth);\n\t};\n\n}", "meta": {"hexsha": "d3afa84ee26a7a847ad49047e1fd09b1045f536e", "size": 1129, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engine/utils/include/halley/file_formats/yaml_convert.h", "max_stars_repo_name": "amrezzd/halley", "max_stars_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/engine/utils/include/halley/file_formats/yaml_convert.h", "max_issues_repo_name": "amrezzd/halley", "max_issues_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engine/utils/include/halley/file_formats/yaml_convert.h", "max_forks_repo_name": "amrezzd/halley", "max_forks_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7105263158, "max_line_length": 103, "alphanum_fraction": 0.7573073516, "num_tokens": 264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.057493285260075494, "lm_q2_score": 0.029760097065367842, "lm_q1q2_score": 0.0017110057499467289}}
{"text": "/* ----------------------------------------------------------------------------\n * This file was automatically generated by SWIG (http://www.swig.org).\n * Version 1.3.36\n * \n * This file is not intended to be easily readable and contains a number of \n * coding conventions designed to improve portability and efficiency. Do not make\n * changes to this file unless you know what you are doing--modify the SWIG \n * interface file instead. \n * ----------------------------------------------------------------------------- */\n\n#define SWIGPYTHON\n#define SWIG_PYTHON_DIRECTOR_NO_VTABLE\n/* -----------------------------------------------------------------------------\n *  This section contains generic SWIG labels for method/variable\n *  declarations/attributes, and other compiler dependent labels.\n * ----------------------------------------------------------------------------- */\n\n/* template workaround for compilers that cannot correctly implement the C++ standard */\n#ifndef SWIGTEMPLATEDISAMBIGUATOR\n# if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x560)\n#  define SWIGTEMPLATEDISAMBIGUATOR template\n# elif defined(__HP_aCC)\n/* Needed even with `aCC -AA' when `aCC -V' reports HP ANSI C++ B3910B A.03.55 */\n/* If we find a maximum version that requires this, the test would be __HP_aCC <= 35500 for A.03.55 */\n#  define SWIGTEMPLATEDISAMBIGUATOR template\n# else\n#  define SWIGTEMPLATEDISAMBIGUATOR\n# endif\n#endif\n\n/* inline attribute */\n#ifndef SWIGINLINE\n# if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__))\n#   define SWIGINLINE inline\n# else\n#   define SWIGINLINE\n# endif\n#endif\n\n/* attribute recognised by some compilers to avoid 'unused' warnings */\n#ifndef SWIGUNUSED\n# if defined(__GNUC__)\n#   if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))\n#     define SWIGUNUSED __attribute__ ((__unused__)) \n#   else\n#     define SWIGUNUSED\n#   endif\n# elif defined(__ICC)\n#   define SWIGUNUSED __attribute__ ((__unused__)) \n# else\n#   define SWIGUNUSED \n# endif\n#endif\n\n#ifndef SWIG_MSC_UNSUPPRESS_4505\n# if defined(_MSC_VER)\n#   pragma warning(disable : 4505) /* unreferenced local function has been removed */\n# endif \n#endif\n\n#ifndef SWIGUNUSEDPARM\n# ifdef __cplusplus\n#   define SWIGUNUSEDPARM(p)\n# else\n#   define SWIGUNUSEDPARM(p) p SWIGUNUSED \n# endif\n#endif\n\n/* internal SWIG method */\n#ifndef SWIGINTERN\n# define SWIGINTERN static SWIGUNUSED\n#endif\n\n/* internal inline SWIG method */\n#ifndef SWIGINTERNINLINE\n# define SWIGINTERNINLINE SWIGINTERN SWIGINLINE\n#endif\n\n/* exporting methods */\n#if (__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)\n#  ifndef GCC_HASCLASSVISIBILITY\n#    define GCC_HASCLASSVISIBILITY\n#  endif\n#endif\n\n#ifndef SWIGEXPORT\n# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)\n#   if defined(STATIC_LINKED)\n#     define SWIGEXPORT\n#   else\n#     define SWIGEXPORT __declspec(dllexport)\n#   endif\n# else\n#   if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY)\n#     define SWIGEXPORT __attribute__ ((visibility(\"default\")))\n#   else\n#     define SWIGEXPORT\n#   endif\n# endif\n#endif\n\n/* calling conventions for Windows */\n#ifndef SWIGSTDCALL\n# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)\n#   define SWIGSTDCALL __stdcall\n# else\n#   define SWIGSTDCALL\n# endif \n#endif\n\n/* Deal with Microsoft's attempt at deprecating C standard runtime functions */\n#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE)\n# define _CRT_SECURE_NO_DEPRECATE\n#endif\n\n/* Deal with Microsoft's attempt at deprecating methods in the standard C++ library */\n#if !defined(SWIG_NO_SCL_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_SCL_SECURE_NO_DEPRECATE)\n# define _SCL_SECURE_NO_DEPRECATE\n#endif\n\n\n\n/* Python.h has to appear first */\n#include <Python.h>\n\n/* -----------------------------------------------------------------------------\n * swigrun.swg\n *\n * This file contains generic CAPI SWIG runtime support for pointer\n * type checking.\n * ----------------------------------------------------------------------------- */\n\n/* This should only be incremented when either the layout of swig_type_info changes,\n   or for whatever reason, the runtime changes incompatibly */\n#define SWIG_RUNTIME_VERSION \"4\"\n\n/* define SWIG_TYPE_TABLE_NAME as \"SWIG_TYPE_TABLE\" */\n#ifdef SWIG_TYPE_TABLE\n# define SWIG_QUOTE_STRING(x) #x\n# define SWIG_EXPAND_AND_QUOTE_STRING(x) SWIG_QUOTE_STRING(x)\n# define SWIG_TYPE_TABLE_NAME SWIG_EXPAND_AND_QUOTE_STRING(SWIG_TYPE_TABLE)\n#else\n# define SWIG_TYPE_TABLE_NAME\n#endif\n\n/*\n  You can use the SWIGRUNTIME and SWIGRUNTIMEINLINE macros for\n  creating a static or dynamic library from the swig runtime code.\n  In 99.9% of the cases, swig just needs to declare them as 'static'.\n  \n  But only do this if is strictly necessary, ie, if you have problems\n  with your compiler or so.\n*/\n\n#ifndef SWIGRUNTIME\n# define SWIGRUNTIME SWIGINTERN\n#endif\n\n#ifndef SWIGRUNTIMEINLINE\n# define SWIGRUNTIMEINLINE SWIGRUNTIME SWIGINLINE\n#endif\n\n/*  Generic buffer size */\n#ifndef SWIG_BUFFER_SIZE\n# define SWIG_BUFFER_SIZE 1024\n#endif\n\n/* Flags for pointer conversions */\n#define SWIG_POINTER_DISOWN        0x1\n#define SWIG_CAST_NEW_MEMORY       0x2\n\n/* Flags for new pointer objects */\n#define SWIG_POINTER_OWN           0x1\n\n\n/* \n   Flags/methods for returning states.\n   \n   The swig conversion methods, as ConvertPtr, return and integer \n   that tells if the conversion was successful or not. And if not,\n   an error code can be returned (see swigerrors.swg for the codes).\n   \n   Use the following macros/flags to set or process the returning\n   states.\n   \n   In old swig versions, you usually write code as:\n\n     if (SWIG_ConvertPtr(obj,vptr,ty.flags) != -1) {\n       // success code\n     } else {\n       //fail code\n     }\n\n   Now you can be more explicit as:\n\n    int res = SWIG_ConvertPtr(obj,vptr,ty.flags);\n    if (SWIG_IsOK(res)) {\n      // success code\n    } else {\n      // fail code\n    }\n\n   that seems to be the same, but now you can also do\n\n    Type *ptr;\n    int res = SWIG_ConvertPtr(obj,(void **)(&ptr),ty.flags);\n    if (SWIG_IsOK(res)) {\n      // success code\n      if (SWIG_IsNewObj(res) {\n        ...\n\tdelete *ptr;\n      } else {\n        ...\n      }\n    } else {\n      // fail code\n    }\n    \n   I.e., now SWIG_ConvertPtr can return new objects and you can\n   identify the case and take care of the deallocation. Of course that\n   requires also to SWIG_ConvertPtr to return new result values, as\n\n      int SWIG_ConvertPtr(obj, ptr,...) {         \n        if (<obj is ok>) {\t\t\t       \n          if (<need new object>) {\t\t       \n            *ptr = <ptr to new allocated object>; \n            return SWIG_NEWOBJ;\t\t       \n          } else {\t\t\t\t       \n            *ptr = <ptr to old object>;\t       \n            return SWIG_OLDOBJ;\t\t       \n          } \t\t\t\t       \n        } else {\t\t\t\t       \n          return SWIG_BADOBJ;\t\t       \n        }\t\t\t\t\t       \n      }\n\n   Of course, returning the plain '0(success)/-1(fail)' still works, but you can be\n   more explicit by returning SWIG_BADOBJ, SWIG_ERROR or any of the\n   swig errors code.\n\n   Finally, if the SWIG_CASTRANK_MODE is enabled, the result code\n   allows to return the 'cast rank', for example, if you have this\n\n       int food(double)\n       int fooi(int);\n\n   and you call\n \n      food(1)   // cast rank '1'  (1 -> 1.0)\n      fooi(1)   // cast rank '0'\n\n   just use the SWIG_AddCast()/SWIG_CheckState()\n\n\n */\n#define SWIG_OK                    (0) \n#define SWIG_ERROR                 (-1)\n#define SWIG_IsOK(r)               (r >= 0)\n#define SWIG_ArgError(r)           ((r != SWIG_ERROR) ? r : SWIG_TypeError)  \n\n/* The CastRankLimit says how many bits are used for the cast rank */\n#define SWIG_CASTRANKLIMIT         (1 << 8)\n/* The NewMask denotes the object was created (using new/malloc) */\n#define SWIG_NEWOBJMASK            (SWIG_CASTRANKLIMIT  << 1)\n/* The TmpMask is for in/out typemaps that use temporal objects */\n#define SWIG_TMPOBJMASK            (SWIG_NEWOBJMASK << 1)\n/* Simple returning values */\n#define SWIG_BADOBJ                (SWIG_ERROR)\n#define SWIG_OLDOBJ                (SWIG_OK)\n#define SWIG_NEWOBJ                (SWIG_OK | SWIG_NEWOBJMASK)\n#define SWIG_TMPOBJ                (SWIG_OK | SWIG_TMPOBJMASK)\n/* Check, add and del mask methods */\n#define SWIG_AddNewMask(r)         (SWIG_IsOK(r) ? (r | SWIG_NEWOBJMASK) : r)\n#define SWIG_DelNewMask(r)         (SWIG_IsOK(r) ? (r & ~SWIG_NEWOBJMASK) : r)\n#define SWIG_IsNewObj(r)           (SWIG_IsOK(r) && (r & SWIG_NEWOBJMASK))\n#define SWIG_AddTmpMask(r)         (SWIG_IsOK(r) ? (r | SWIG_TMPOBJMASK) : r)\n#define SWIG_DelTmpMask(r)         (SWIG_IsOK(r) ? (r & ~SWIG_TMPOBJMASK) : r)\n#define SWIG_IsTmpObj(r)           (SWIG_IsOK(r) && (r & SWIG_TMPOBJMASK))\n\n\n/* Cast-Rank Mode */\n#if defined(SWIG_CASTRANK_MODE)\n#  ifndef SWIG_TypeRank\n#    define SWIG_TypeRank             unsigned long\n#  endif\n#  ifndef SWIG_MAXCASTRANK            /* Default cast allowed */\n#    define SWIG_MAXCASTRANK          (2)\n#  endif\n#  define SWIG_CASTRANKMASK          ((SWIG_CASTRANKLIMIT) -1)\n#  define SWIG_CastRank(r)           (r & SWIG_CASTRANKMASK)\nSWIGINTERNINLINE int SWIG_AddCast(int r) { \n  return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r;\n}\nSWIGINTERNINLINE int SWIG_CheckState(int r) { \n  return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0; \n}\n#else /* no cast-rank mode */\n#  define SWIG_AddCast\n#  define SWIG_CheckState(r) (SWIG_IsOK(r) ? 1 : 0)\n#endif\n\n\n\n\n#include <string.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\ntypedef void *(*swig_converter_func)(void *, int *);\ntypedef struct swig_type_info *(*swig_dycast_func)(void **);\n\n/* Structure to store information on one type */\ntypedef struct swig_type_info {\n  const char             *name;\t\t\t/* mangled name of this type */\n  const char             *str;\t\t\t/* human readable name of this type */\n  swig_dycast_func        dcast;\t\t/* dynamic cast function down a hierarchy */\n  struct swig_cast_info  *cast;\t\t\t/* linked list of types that can cast into this type */\n  void                   *clientdata;\t\t/* language specific type data */\n  int                    owndata;\t\t/* flag if the structure owns the clientdata */\n} swig_type_info;\n\n/* Structure to store a type and conversion function used for casting */\ntypedef struct swig_cast_info {\n  swig_type_info         *type;\t\t\t/* pointer to type that is equivalent to this type */\n  swig_converter_func     converter;\t\t/* function to cast the void pointers */\n  struct swig_cast_info  *next;\t\t\t/* pointer to next cast in linked list */\n  struct swig_cast_info  *prev;\t\t\t/* pointer to the previous cast */\n} swig_cast_info;\n\n/* Structure used to store module information\n * Each module generates one structure like this, and the runtime collects\n * all of these structures and stores them in a circularly linked list.*/\ntypedef struct swig_module_info {\n  swig_type_info         **types;\t\t/* Array of pointers to swig_type_info structures that are in this module */\n  size_t                 size;\t\t        /* Number of types in this module */\n  struct swig_module_info *next;\t\t/* Pointer to next element in circularly linked list */\n  swig_type_info         **type_initial;\t/* Array of initially generated type structures */\n  swig_cast_info         **cast_initial;\t/* Array of initially generated casting structures */\n  void                    *clientdata;\t\t/* Language specific module data */\n} swig_module_info;\n\n/* \n  Compare two type names skipping the space characters, therefore\n  \"char*\" == \"char *\" and \"Class<int>\" == \"Class<int >\", etc.\n\n  Return 0 when the two name types are equivalent, as in\n  strncmp, but skipping ' '.\n*/\nSWIGRUNTIME int\nSWIG_TypeNameComp(const char *f1, const char *l1,\n\t\t  const char *f2, const char *l2) {\n  for (;(f1 != l1) && (f2 != l2); ++f1, ++f2) {\n    while ((*f1 == ' ') && (f1 != l1)) ++f1;\n    while ((*f2 == ' ') && (f2 != l2)) ++f2;\n    if (*f1 != *f2) return (*f1 > *f2) ? 1 : -1;\n  }\n  return (int)((l1 - f1) - (l2 - f2));\n}\n\n/*\n  Check type equivalence in a name list like <name1>|<name2>|...\n  Return 0 if not equal, 1 if equal\n*/\nSWIGRUNTIME int\nSWIG_TypeEquiv(const char *nb, const char *tb) {\n  int equiv = 0;\n  const char* te = tb + strlen(tb);\n  const char* ne = nb;\n  while (!equiv && *ne) {\n    for (nb = ne; *ne; ++ne) {\n      if (*ne == '|') break;\n    }\n    equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0;\n    if (*ne) ++ne;\n  }\n  return equiv;\n}\n\n/*\n  Check type equivalence in a name list like <name1>|<name2>|...\n  Return 0 if equal, -1 if nb < tb, 1 if nb > tb\n*/\nSWIGRUNTIME int\nSWIG_TypeCompare(const char *nb, const char *tb) {\n  int equiv = 0;\n  const char* te = tb + strlen(tb);\n  const char* ne = nb;\n  while (!equiv && *ne) {\n    for (nb = ne; *ne; ++ne) {\n      if (*ne == '|') break;\n    }\n    equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0;\n    if (*ne) ++ne;\n  }\n  return equiv;\n}\n\n\n/* think of this as a c++ template<> or a scheme macro */\n#define SWIG_TypeCheck_Template(comparison, ty)         \\\n  if (ty) {                                             \\\n    swig_cast_info *iter = ty->cast;                    \\\n    while (iter) {                                      \\\n      if (comparison) {                                 \\\n        if (iter == ty->cast) return iter;              \\\n        /* Move iter to the top of the linked list */   \\\n        iter->prev->next = iter->next;                  \\\n        if (iter->next)                                 \\\n          iter->next->prev = iter->prev;                \\\n        iter->next = ty->cast;                          \\\n        iter->prev = 0;                                 \\\n        if (ty->cast) ty->cast->prev = iter;            \\\n        ty->cast = iter;                                \\\n        return iter;                                    \\\n      }                                                 \\\n      iter = iter->next;                                \\\n    }                                                   \\\n  }                                                     \\\n  return 0\n\n/*\n  Check the typename\n*/\nSWIGRUNTIME swig_cast_info *\nSWIG_TypeCheck(const char *c, swig_type_info *ty) {\n  SWIG_TypeCheck_Template(strcmp(iter->type->name, c) == 0, ty);\n}\n\n/* Same as previous function, except strcmp is replaced with a pointer comparison */\nSWIGRUNTIME swig_cast_info *\nSWIG_TypeCheckStruct(swig_type_info *from, swig_type_info *into) {\n  SWIG_TypeCheck_Template(iter->type == from, into);\n}\n\n/*\n  Cast a pointer up an inheritance hierarchy\n*/\nSWIGRUNTIMEINLINE void *\nSWIG_TypeCast(swig_cast_info *ty, void *ptr, int *newmemory) {\n  return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr, newmemory);\n}\n\n/* \n   Dynamic pointer casting. Down an inheritance hierarchy\n*/\nSWIGRUNTIME swig_type_info *\nSWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) {\n  swig_type_info *lastty = ty;\n  if (!ty || !ty->dcast) return ty;\n  while (ty && (ty->dcast)) {\n    ty = (*ty->dcast)(ptr);\n    if (ty) lastty = ty;\n  }\n  return lastty;\n}\n\n/*\n  Return the name associated with this type\n*/\nSWIGRUNTIMEINLINE const char *\nSWIG_TypeName(const swig_type_info *ty) {\n  return ty->name;\n}\n\n/*\n  Return the pretty name associated with this type,\n  that is an unmangled type name in a form presentable to the user.\n*/\nSWIGRUNTIME const char *\nSWIG_TypePrettyName(const swig_type_info *type) {\n  /* The \"str\" field contains the equivalent pretty names of the\n     type, separated by vertical-bar characters.  We choose\n     to print the last name, as it is often (?) the most\n     specific. */\n  if (!type) return NULL;\n  if (type->str != NULL) {\n    const char *last_name = type->str;\n    const char *s;\n    for (s = type->str; *s; s++)\n      if (*s == '|') last_name = s+1;\n    return last_name;\n  }\n  else\n    return type->name;\n}\n\n/* \n   Set the clientdata field for a type\n*/\nSWIGRUNTIME void\nSWIG_TypeClientData(swig_type_info *ti, void *clientdata) {\n  swig_cast_info *cast = ti->cast;\n  /* if (ti->clientdata == clientdata) return; */\n  ti->clientdata = clientdata;\n  \n  while (cast) {\n    if (!cast->converter) {\n      swig_type_info *tc = cast->type;\n      if (!tc->clientdata) {\n\tSWIG_TypeClientData(tc, clientdata);\n      }\n    }    \n    cast = cast->next;\n  }\n}\nSWIGRUNTIME void\nSWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) {\n  SWIG_TypeClientData(ti, clientdata);\n  ti->owndata = 1;\n}\n  \n/*\n  Search for a swig_type_info structure only by mangled name\n  Search is a O(log #types)\n  \n  We start searching at module start, and finish searching when start == end.  \n  Note: if start == end at the beginning of the function, we go all the way around\n  the circular list.\n*/\nSWIGRUNTIME swig_type_info *\nSWIG_MangledTypeQueryModule(swig_module_info *start, \n                            swig_module_info *end, \n\t\t            const char *name) {\n  swig_module_info *iter = start;\n  do {\n    if (iter->size) {\n      register size_t l = 0;\n      register size_t r = iter->size - 1;\n      do {\n\t/* since l+r >= 0, we can (>> 1) instead (/ 2) */\n\tregister size_t i = (l + r) >> 1; \n\tconst char *iname = iter->types[i]->name;\n\tif (iname) {\n\t  register int compare = strcmp(name, iname);\n\t  if (compare == 0) {\t    \n\t    return iter->types[i];\n\t  } else if (compare < 0) {\n\t    if (i) {\n\t      r = i - 1;\n\t    } else {\n\t      break;\n\t    }\n\t  } else if (compare > 0) {\n\t    l = i + 1;\n\t  }\n\t} else {\n\t  break; /* should never happen */\n\t}\n      } while (l <= r);\n    }\n    iter = iter->next;\n  } while (iter != end);\n  return 0;\n}\n\n/*\n  Search for a swig_type_info structure for either a mangled name or a human readable name.\n  It first searches the mangled names of the types, which is a O(log #types)\n  If a type is not found it then searches the human readable names, which is O(#types).\n  \n  We start searching at module start, and finish searching when start == end.  \n  Note: if start == end at the beginning of the function, we go all the way around\n  the circular list.\n*/\nSWIGRUNTIME swig_type_info *\nSWIG_TypeQueryModule(swig_module_info *start, \n                     swig_module_info *end, \n\t\t     const char *name) {\n  /* STEP 1: Search the name field using binary search */\n  swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name);\n  if (ret) {\n    return ret;\n  } else {\n    /* STEP 2: If the type hasn't been found, do a complete search\n       of the str field (the human readable name) */\n    swig_module_info *iter = start;\n    do {\n      register size_t i = 0;\n      for (; i < iter->size; ++i) {\n\tif (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name)))\n\t  return iter->types[i];\n      }\n      iter = iter->next;\n    } while (iter != end);\n  }\n  \n  /* neither found a match */\n  return 0;\n}\n\n/* \n   Pack binary data into a string\n*/\nSWIGRUNTIME char *\nSWIG_PackData(char *c, void *ptr, size_t sz) {\n  static const char hex[17] = \"0123456789abcdef\";\n  register const unsigned char *u = (unsigned char *) ptr;\n  register const unsigned char *eu =  u + sz;\n  for (; u != eu; ++u) {\n    register unsigned char uu = *u;\n    *(c++) = hex[(uu & 0xf0) >> 4];\n    *(c++) = hex[uu & 0xf];\n  }\n  return c;\n}\n\n/* \n   Unpack binary data from a string\n*/\nSWIGRUNTIME const char *\nSWIG_UnpackData(const char *c, void *ptr, size_t sz) {\n  register unsigned char *u = (unsigned char *) ptr;\n  register const unsigned char *eu = u + sz;\n  for (; u != eu; ++u) {\n    register char d = *(c++);\n    register unsigned char uu;\n    if ((d >= '0') && (d <= '9'))\n      uu = ((d - '0') << 4);\n    else if ((d >= 'a') && (d <= 'f'))\n      uu = ((d - ('a'-10)) << 4);\n    else \n      return (char *) 0;\n    d = *(c++);\n    if ((d >= '0') && (d <= '9'))\n      uu |= (d - '0');\n    else if ((d >= 'a') && (d <= 'f'))\n      uu |= (d - ('a'-10));\n    else \n      return (char *) 0;\n    *u = uu;\n  }\n  return c;\n}\n\n/* \n   Pack 'void *' into a string buffer.\n*/\nSWIGRUNTIME char *\nSWIG_PackVoidPtr(char *buff, void *ptr, const char *name, size_t bsz) {\n  char *r = buff;\n  if ((2*sizeof(void *) + 2) > bsz) return 0;\n  *(r++) = '_';\n  r = SWIG_PackData(r,&ptr,sizeof(void *));\n  if (strlen(name) + 1 > (bsz - (r - buff))) return 0;\n  strcpy(r,name);\n  return buff;\n}\n\nSWIGRUNTIME const char *\nSWIG_UnpackVoidPtr(const char *c, void **ptr, const char *name) {\n  if (*c != '_') {\n    if (strcmp(c,\"NULL\") == 0) {\n      *ptr = (void *) 0;\n      return name;\n    } else {\n      return 0;\n    }\n  }\n  return SWIG_UnpackData(++c,ptr,sizeof(void *));\n}\n\nSWIGRUNTIME char *\nSWIG_PackDataName(char *buff, void *ptr, size_t sz, const char *name, size_t bsz) {\n  char *r = buff;\n  size_t lname = (name ? strlen(name) : 0);\n  if ((2*sz + 2 + lname) > bsz) return 0;\n  *(r++) = '_';\n  r = SWIG_PackData(r,ptr,sz);\n  if (lname) {\n    strncpy(r,name,lname+1);\n  } else {\n    *r = 0;\n  }\n  return buff;\n}\n\nSWIGRUNTIME const char *\nSWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) {\n  if (*c != '_') {\n    if (strcmp(c,\"NULL\") == 0) {\n      memset(ptr,0,sz);\n      return name;\n    } else {\n      return 0;\n    }\n  }\n  return SWIG_UnpackData(++c,ptr,sz);\n}\n\n#ifdef __cplusplus\n}\n#endif\n\n/*  Errors in SWIG */\n#define  SWIG_UnknownError    \t   -1 \n#define  SWIG_IOError        \t   -2 \n#define  SWIG_RuntimeError   \t   -3 \n#define  SWIG_IndexError     \t   -4 \n#define  SWIG_TypeError      \t   -5 \n#define  SWIG_DivisionByZero \t   -6 \n#define  SWIG_OverflowError  \t   -7 \n#define  SWIG_SyntaxError    \t   -8 \n#define  SWIG_ValueError     \t   -9 \n#define  SWIG_SystemError    \t   -10\n#define  SWIG_AttributeError \t   -11\n#define  SWIG_MemoryError    \t   -12 \n#define  SWIG_NullReferenceError   -13\n\n\n\n\n/* Add PyOS_snprintf for old Pythons */\n#if PY_VERSION_HEX < 0x02020000\n# if defined(_MSC_VER) || defined(__BORLANDC__) || defined(_WATCOM)\n#  define PyOS_snprintf _snprintf\n# else\n#  define PyOS_snprintf snprintf\n# endif\n#endif\n\n/* A crude PyString_FromFormat implementation for old Pythons */\n#if PY_VERSION_HEX < 0x02020000\n\n#ifndef SWIG_PYBUFFER_SIZE\n# define SWIG_PYBUFFER_SIZE 1024\n#endif\n\nstatic PyObject *\nPyString_FromFormat(const char *fmt, ...) {\n  va_list ap;\n  char buf[SWIG_PYBUFFER_SIZE * 2];\n  int res;\n  va_start(ap, fmt);\n  res = vsnprintf(buf, sizeof(buf), fmt, ap);\n  va_end(ap);\n  return (res < 0 || res >= (int)sizeof(buf)) ? 0 : PyString_FromString(buf);\n}\n#endif\n\n/* Add PyObject_Del for old Pythons */\n#if PY_VERSION_HEX < 0x01060000\n# define PyObject_Del(op) PyMem_DEL((op))\n#endif\n#ifndef PyObject_DEL\n# define PyObject_DEL PyObject_Del\n#endif\n\n/* A crude PyExc_StopIteration exception for old Pythons */\n#if PY_VERSION_HEX < 0x02020000\n# ifndef PyExc_StopIteration\n#  define PyExc_StopIteration PyExc_RuntimeError\n# endif\n# ifndef PyObject_GenericGetAttr\n#  define PyObject_GenericGetAttr 0\n# endif\n#endif\n/* Py_NotImplemented is defined in 2.1 and up. */\n#if PY_VERSION_HEX < 0x02010000\n# ifndef Py_NotImplemented\n#  define Py_NotImplemented PyExc_RuntimeError\n# endif\n#endif\n\n\n/* A crude PyString_AsStringAndSize implementation for old Pythons */\n#if PY_VERSION_HEX < 0x02010000\n# ifndef PyString_AsStringAndSize\n#  define PyString_AsStringAndSize(obj, s, len) {*s = PyString_AsString(obj); *len = *s ? strlen(*s) : 0;}\n# endif\n#endif\n\n/* PySequence_Size for old Pythons */\n#if PY_VERSION_HEX < 0x02000000\n# ifndef PySequence_Size\n#  define PySequence_Size PySequence_Length\n# endif\n#endif\n\n\n/* PyBool_FromLong for old Pythons */\n#if PY_VERSION_HEX < 0x02030000\nstatic\nPyObject *PyBool_FromLong(long ok)\n{\n  PyObject *result = ok ? Py_True : Py_False;\n  Py_INCREF(result);\n  return result;\n}\n#endif\n\n/* Py_ssize_t for old Pythons */\n/* This code is as recommended by: */\n/* http://www.python.org/dev/peps/pep-0353/#conversion-guidelines */\n#if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN)\ntypedef int Py_ssize_t;\n# define PY_SSIZE_T_MAX INT_MAX\n# define PY_SSIZE_T_MIN INT_MIN\n#endif\n\n/* -----------------------------------------------------------------------------\n * error manipulation\n * ----------------------------------------------------------------------------- */\n\nSWIGRUNTIME PyObject*\nSWIG_Python_ErrorType(int code) {\n  PyObject* type = 0;\n  switch(code) {\n  case SWIG_MemoryError:\n    type = PyExc_MemoryError;\n    break;\n  case SWIG_IOError:\n    type = PyExc_IOError;\n    break;\n  case SWIG_RuntimeError:\n    type = PyExc_RuntimeError;\n    break;\n  case SWIG_IndexError:\n    type = PyExc_IndexError;\n    break;\n  case SWIG_TypeError:\n    type = PyExc_TypeError;\n    break;\n  case SWIG_DivisionByZero:\n    type = PyExc_ZeroDivisionError;\n    break;\n  case SWIG_OverflowError:\n    type = PyExc_OverflowError;\n    break;\n  case SWIG_SyntaxError:\n    type = PyExc_SyntaxError;\n    break;\n  case SWIG_ValueError:\n    type = PyExc_ValueError;\n    break;\n  case SWIG_SystemError:\n    type = PyExc_SystemError;\n    break;\n  case SWIG_AttributeError:\n    type = PyExc_AttributeError;\n    break;\n  default:\n    type = PyExc_RuntimeError;\n  }\n  return type;\n}\n\n\nSWIGRUNTIME void\nSWIG_Python_AddErrorMsg(const char* mesg)\n{\n  PyObject *type = 0;\n  PyObject *value = 0;\n  PyObject *traceback = 0;\n\n  if (PyErr_Occurred()) PyErr_Fetch(&type, &value, &traceback);\n  if (value) {\n    PyObject *old_str = PyObject_Str(value);\n    PyErr_Clear();\n    Py_XINCREF(type);\n    PyErr_Format(type, \"%s %s\", PyString_AsString(old_str), mesg);\n    Py_DECREF(old_str);\n    Py_DECREF(value);\n  } else {\n    PyErr_SetString(PyExc_RuntimeError, mesg);\n  }\n}\n\n\n\n#if defined(SWIG_PYTHON_NO_THREADS)\n#  if defined(SWIG_PYTHON_THREADS)\n#    undef SWIG_PYTHON_THREADS\n#  endif\n#endif\n#if defined(SWIG_PYTHON_THREADS) /* Threading support is enabled */\n#  if !defined(SWIG_PYTHON_USE_GIL) && !defined(SWIG_PYTHON_NO_USE_GIL)\n#    if (PY_VERSION_HEX >= 0x02030000) /* For 2.3 or later, use the PyGILState calls */\n#      define SWIG_PYTHON_USE_GIL\n#    endif\n#  endif\n#  if defined(SWIG_PYTHON_USE_GIL) /* Use PyGILState threads calls */\n#    ifndef SWIG_PYTHON_INITIALIZE_THREADS\n#     define SWIG_PYTHON_INITIALIZE_THREADS  PyEval_InitThreads() \n#    endif\n#    ifdef __cplusplus /* C++ code */\n       class SWIG_Python_Thread_Block {\n         bool status;\n         PyGILState_STATE state;\n       public:\n         void end() { if (status) { PyGILState_Release(state); status = false;} }\n         SWIG_Python_Thread_Block() : status(true), state(PyGILState_Ensure()) {}\n         ~SWIG_Python_Thread_Block() { end(); }\n       };\n       class SWIG_Python_Thread_Allow {\n         bool status;\n         PyThreadState *save;\n       public:\n         void end() { if (status) { PyEval_RestoreThread(save); status = false; }}\n         SWIG_Python_Thread_Allow() : status(true), save(PyEval_SaveThread()) {}\n         ~SWIG_Python_Thread_Allow() { end(); }\n       };\n#      define SWIG_PYTHON_THREAD_BEGIN_BLOCK   SWIG_Python_Thread_Block _swig_thread_block\n#      define SWIG_PYTHON_THREAD_END_BLOCK     _swig_thread_block.end()\n#      define SWIG_PYTHON_THREAD_BEGIN_ALLOW   SWIG_Python_Thread_Allow _swig_thread_allow\n#      define SWIG_PYTHON_THREAD_END_ALLOW     _swig_thread_allow.end()\n#    else /* C code */\n#      define SWIG_PYTHON_THREAD_BEGIN_BLOCK   PyGILState_STATE _swig_thread_block = PyGILState_Ensure()\n#      define SWIG_PYTHON_THREAD_END_BLOCK     PyGILState_Release(_swig_thread_block)\n#      define SWIG_PYTHON_THREAD_BEGIN_ALLOW   PyThreadState *_swig_thread_allow = PyEval_SaveThread()\n#      define SWIG_PYTHON_THREAD_END_ALLOW     PyEval_RestoreThread(_swig_thread_allow)\n#    endif\n#  else /* Old thread way, not implemented, user must provide it */\n#    if !defined(SWIG_PYTHON_INITIALIZE_THREADS)\n#      define SWIG_PYTHON_INITIALIZE_THREADS\n#    endif\n#    if !defined(SWIG_PYTHON_THREAD_BEGIN_BLOCK)\n#      define SWIG_PYTHON_THREAD_BEGIN_BLOCK\n#    endif\n#    if !defined(SWIG_PYTHON_THREAD_END_BLOCK)\n#      define SWIG_PYTHON_THREAD_END_BLOCK\n#    endif\n#    if !defined(SWIG_PYTHON_THREAD_BEGIN_ALLOW)\n#      define SWIG_PYTHON_THREAD_BEGIN_ALLOW\n#    endif\n#    if !defined(SWIG_PYTHON_THREAD_END_ALLOW)\n#      define SWIG_PYTHON_THREAD_END_ALLOW\n#    endif\n#  endif\n#else /* No thread support */\n#  define SWIG_PYTHON_INITIALIZE_THREADS\n#  define SWIG_PYTHON_THREAD_BEGIN_BLOCK\n#  define SWIG_PYTHON_THREAD_END_BLOCK\n#  define SWIG_PYTHON_THREAD_BEGIN_ALLOW\n#  define SWIG_PYTHON_THREAD_END_ALLOW\n#endif\n\n/* -----------------------------------------------------------------------------\n * Python API portion that goes into the runtime\n * ----------------------------------------------------------------------------- */\n\n#ifdef __cplusplus\nextern \"C\" {\n#if 0\n} /* cc-mode */\n#endif\n#endif\n\n/* -----------------------------------------------------------------------------\n * Constant declarations\n * ----------------------------------------------------------------------------- */\n\n/* Constant Types */\n#define SWIG_PY_POINTER 4\n#define SWIG_PY_BINARY  5\n\n/* Constant information structure */\ntypedef struct swig_const_info {\n  int type;\n  char *name;\n  long lvalue;\n  double dvalue;\n  void   *pvalue;\n  swig_type_info **ptype;\n} swig_const_info;\n\n#ifdef __cplusplus\n#if 0\n{ /* cc-mode */\n#endif\n}\n#endif\n\n\n/* -----------------------------------------------------------------------------\n * See the LICENSE file for information on copyright, usage and redistribution\n * of SWIG, and the README file for authors - http://www.swig.org/release.html.\n *\n * pyrun.swg\n *\n * This file contains the runtime support for Python modules\n * and includes code for managing global variables and pointer\n * type checking.\n *\n * ----------------------------------------------------------------------------- */\n\n/* Common SWIG API */\n\n/* for raw pointers */\n#define SWIG_Python_ConvertPtr(obj, pptr, type, flags)  SWIG_Python_ConvertPtrAndOwn(obj, pptr, type, flags, 0)\n#define SWIG_ConvertPtr(obj, pptr, type, flags)         SWIG_Python_ConvertPtr(obj, pptr, type, flags)\n#define SWIG_ConvertPtrAndOwn(obj,pptr,type,flags,own)  SWIG_Python_ConvertPtrAndOwn(obj, pptr, type, flags, own)\n#define SWIG_NewPointerObj(ptr, type, flags)            SWIG_Python_NewPointerObj(ptr, type, flags)\n#define SWIG_CheckImplicit(ty)                          SWIG_Python_CheckImplicit(ty) \n#define SWIG_AcquirePtr(ptr, src)                       SWIG_Python_AcquirePtr(ptr, src)\n#define swig_owntype                                    int\n\n/* for raw packed data */\n#define SWIG_ConvertPacked(obj, ptr, sz, ty)            SWIG_Python_ConvertPacked(obj, ptr, sz, ty)\n#define SWIG_NewPackedObj(ptr, sz, type)                SWIG_Python_NewPackedObj(ptr, sz, type)\n\n/* for class or struct pointers */\n#define SWIG_ConvertInstance(obj, pptr, type, flags)    SWIG_ConvertPtr(obj, pptr, type, flags)\n#define SWIG_NewInstanceObj(ptr, type, flags)           SWIG_NewPointerObj(ptr, type, flags)\n\n/* for C or C++ function pointers */\n#define SWIG_ConvertFunctionPtr(obj, pptr, type)        SWIG_Python_ConvertFunctionPtr(obj, pptr, type)\n#define SWIG_NewFunctionPtrObj(ptr, type)               SWIG_Python_NewPointerObj(ptr, type, 0)\n\n/* for C++ member pointers, ie, member methods */\n#define SWIG_ConvertMember(obj, ptr, sz, ty)            SWIG_Python_ConvertPacked(obj, ptr, sz, ty)\n#define SWIG_NewMemberObj(ptr, sz, type)                SWIG_Python_NewPackedObj(ptr, sz, type)\n\n\n/* Runtime API */\n\n#define SWIG_GetModule(clientdata)                      SWIG_Python_GetModule()\n#define SWIG_SetModule(clientdata, pointer)             SWIG_Python_SetModule(pointer)\n#define SWIG_NewClientData(obj)                         PySwigClientData_New(obj)\n\n#define SWIG_SetErrorObj                                SWIG_Python_SetErrorObj                            \n#define SWIG_SetErrorMsg                        \tSWIG_Python_SetErrorMsg\t\t\t\t   \n#define SWIG_ErrorType(code)                    \tSWIG_Python_ErrorType(code)                        \n#define SWIG_Error(code, msg)            \t\tSWIG_Python_SetErrorMsg(SWIG_ErrorType(code), msg) \n#define SWIG_fail                        \t\tgoto fail\t\t\t\t\t   \n\n\n/* Runtime API implementation */\n\n/* Error manipulation */\n\nSWIGINTERN void \nSWIG_Python_SetErrorObj(PyObject *errtype, PyObject *obj) {\n  SWIG_PYTHON_THREAD_BEGIN_BLOCK; \n  PyErr_SetObject(errtype, obj);\n  Py_DECREF(obj);\n  SWIG_PYTHON_THREAD_END_BLOCK;\n}\n\nSWIGINTERN void \nSWIG_Python_SetErrorMsg(PyObject *errtype, const char *msg) {\n  SWIG_PYTHON_THREAD_BEGIN_BLOCK;\n  PyErr_SetString(errtype, (char *) msg);\n  SWIG_PYTHON_THREAD_END_BLOCK;\n}\n\n#define SWIG_Python_Raise(obj, type, desc)  SWIG_Python_SetErrorObj(SWIG_Python_ExceptionType(desc), obj)\n\n/* Set a constant value */\n\nSWIGINTERN void\nSWIG_Python_SetConstant(PyObject *d, const char *name, PyObject *obj) {   \n  PyDict_SetItemString(d, (char*) name, obj);\n  Py_DECREF(obj);                            \n}\n\n/* Append a value to the result obj */\n\nSWIGINTERN PyObject*\nSWIG_Python_AppendOutput(PyObject* result, PyObject* obj) {\n#if !defined(SWIG_PYTHON_OUTPUT_TUPLE)\n  if (!result) {\n    result = obj;\n  } else if (result == Py_None) {\n    Py_DECREF(result);\n    result = obj;\n  } else {\n    if (!PyList_Check(result)) {\n      PyObject *o2 = result;\n      result = PyList_New(1);\n      PyList_SetItem(result, 0, o2);\n    }\n    PyList_Append(result,obj);\n    Py_DECREF(obj);\n  }\n  return result;\n#else\n  PyObject*   o2;\n  PyObject*   o3;\n  if (!result) {\n    result = obj;\n  } else if (result == Py_None) {\n    Py_DECREF(result);\n    result = obj;\n  } else {\n    if (!PyTuple_Check(result)) {\n      o2 = result;\n      result = PyTuple_New(1);\n      PyTuple_SET_ITEM(result, 0, o2);\n    }\n    o3 = PyTuple_New(1);\n    PyTuple_SET_ITEM(o3, 0, obj);\n    o2 = result;\n    result = PySequence_Concat(o2, o3);\n    Py_DECREF(o2);\n    Py_DECREF(o3);\n  }\n  return result;\n#endif\n}\n\n/* Unpack the argument tuple */\n\nSWIGINTERN int\nSWIG_Python_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, PyObject **objs)\n{\n  if (!args) {\n    if (!min && !max) {\n      return 1;\n    } else {\n      PyErr_Format(PyExc_TypeError, \"%s expected %s%d arguments, got none\", \n\t\t   name, (min == max ? \"\" : \"at least \"), (int)min);\n      return 0;\n    }\n  }  \n  if (!PyTuple_Check(args)) {\n    PyErr_SetString(PyExc_SystemError, \"UnpackTuple() argument list is not a tuple\");\n    return 0;\n  } else {\n    register Py_ssize_t l = PyTuple_GET_SIZE(args);\n    if (l < min) {\n      PyErr_Format(PyExc_TypeError, \"%s expected %s%d arguments, got %d\", \n\t\t   name, (min == max ? \"\" : \"at least \"), (int)min, (int)l);\n      return 0;\n    } else if (l > max) {\n      PyErr_Format(PyExc_TypeError, \"%s expected %s%d arguments, got %d\", \n\t\t   name, (min == max ? \"\" : \"at most \"), (int)max, (int)l);\n      return 0;\n    } else {\n      register int i;\n      for (i = 0; i < l; ++i) {\n\tobjs[i] = PyTuple_GET_ITEM(args, i);\n      }\n      for (; l < max; ++l) {\n\tobjs[l] = 0;\n      }\n      return i + 1;\n    }    \n  }\n}\n\n/* A functor is a function object with one single object argument */\n#if PY_VERSION_HEX >= 0x02020000\n#define SWIG_Python_CallFunctor(functor, obj)\t        PyObject_CallFunctionObjArgs(functor, obj, NULL);\n#else\n#define SWIG_Python_CallFunctor(functor, obj)\t        PyObject_CallFunction(functor, \"O\", obj);\n#endif\n\n/*\n  Helper for static pointer initialization for both C and C++ code, for example\n  static PyObject *SWIG_STATIC_POINTER(MyVar) = NewSomething(...);\n*/\n#ifdef __cplusplus\n#define SWIG_STATIC_POINTER(var)  var\n#else\n#define SWIG_STATIC_POINTER(var)  var = 0; if (!var) var\n#endif\n\n/* -----------------------------------------------------------------------------\n * Pointer declarations\n * ----------------------------------------------------------------------------- */\n\n/* Flags for new pointer objects */\n#define SWIG_POINTER_NOSHADOW       (SWIG_POINTER_OWN      << 1)\n#define SWIG_POINTER_NEW            (SWIG_POINTER_NOSHADOW | SWIG_POINTER_OWN)\n\n#define SWIG_POINTER_IMPLICIT_CONV  (SWIG_POINTER_DISOWN   << 1)\n\n#ifdef __cplusplus\nextern \"C\" {\n#if 0\n} /* cc-mode */\n#endif\n#endif\n\n/*  How to access Py_None */\n#if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)\n#  ifndef SWIG_PYTHON_NO_BUILD_NONE\n#    ifndef SWIG_PYTHON_BUILD_NONE\n#      define SWIG_PYTHON_BUILD_NONE\n#    endif\n#  endif\n#endif\n\n#ifdef SWIG_PYTHON_BUILD_NONE\n#  ifdef Py_None\n#   undef Py_None\n#   define Py_None SWIG_Py_None()\n#  endif\nSWIGRUNTIMEINLINE PyObject * \n_SWIG_Py_None(void)\n{\n  PyObject *none = Py_BuildValue((char*)\"\");\n  Py_DECREF(none);\n  return none;\n}\nSWIGRUNTIME PyObject * \nSWIG_Py_None(void)\n{\n  static PyObject *SWIG_STATIC_POINTER(none) = _SWIG_Py_None();\n  return none;\n}\n#endif\n\n/* The python void return value */\n\nSWIGRUNTIMEINLINE PyObject * \nSWIG_Py_Void(void)\n{\n  PyObject *none = Py_None;\n  Py_INCREF(none);\n  return none;\n}\n\n/* PySwigClientData */\n\ntypedef struct {\n  PyObject *klass;\n  PyObject *newraw;\n  PyObject *newargs;\n  PyObject *destroy;\n  int delargs;\n  int implicitconv;\n} PySwigClientData;\n\nSWIGRUNTIMEINLINE int \nSWIG_Python_CheckImplicit(swig_type_info *ty)\n{\n  PySwigClientData *data = (PySwigClientData *)ty->clientdata;\n  return data ? data->implicitconv : 0;\n}\n\nSWIGRUNTIMEINLINE PyObject *\nSWIG_Python_ExceptionType(swig_type_info *desc) {\n  PySwigClientData *data = desc ? (PySwigClientData *) desc->clientdata : 0;\n  PyObject *klass = data ? data->klass : 0;\n  return (klass ? klass : PyExc_RuntimeError);\n}\n\n\nSWIGRUNTIME PySwigClientData * \nPySwigClientData_New(PyObject* obj)\n{\n  if (!obj) {\n    return 0;\n  } else {\n    PySwigClientData *data = (PySwigClientData *)malloc(sizeof(PySwigClientData));\n    /* the klass element */\n    data->klass = obj;\n    Py_INCREF(data->klass);\n    /* the newraw method and newargs arguments used to create a new raw instance */\n    if (PyClass_Check(obj)) {\n      data->newraw = 0;\n      data->newargs = obj;\n      Py_INCREF(obj);\n    } else {\n#if (PY_VERSION_HEX < 0x02020000)\n      data->newraw = 0;\n#else\n      data->newraw = PyObject_GetAttrString(data->klass, (char *)\"__new__\");\n#endif\n      if (data->newraw) {\n\tPy_INCREF(data->newraw);\n\tdata->newargs = PyTuple_New(1);\n\tPyTuple_SetItem(data->newargs, 0, obj);\n      } else {\n\tdata->newargs = obj;\n      }\n      Py_INCREF(data->newargs);\n    }\n    /* the destroy method, aka as the C++ delete method */\n    data->destroy = PyObject_GetAttrString(data->klass, (char *)\"__swig_destroy__\");\n    if (PyErr_Occurred()) {\n      PyErr_Clear();\n      data->destroy = 0;\n    }\n    if (data->destroy) {\n      int flags;\n      Py_INCREF(data->destroy);\n      flags = PyCFunction_GET_FLAGS(data->destroy);\n#ifdef METH_O\n      data->delargs = !(flags & (METH_O));\n#else\n      data->delargs = 0;\n#endif\n    } else {\n      data->delargs = 0;\n    }\n    data->implicitconv = 0;\n    return data;\n  }\n}\n\nSWIGRUNTIME void \nPySwigClientData_Del(PySwigClientData* data)\n{\n  Py_XDECREF(data->newraw);\n  Py_XDECREF(data->newargs);\n  Py_XDECREF(data->destroy);\n}\n\n/* =============== PySwigObject =====================*/\n\ntypedef struct {\n  PyObject_HEAD\n  void *ptr;\n  swig_type_info *ty;\n  int own;\n  PyObject *next;\n} PySwigObject;\n\nSWIGRUNTIME PyObject *\nPySwigObject_long(PySwigObject *v)\n{\n  return PyLong_FromVoidPtr(v->ptr);\n}\n\nSWIGRUNTIME PyObject *\nPySwigObject_format(const char* fmt, PySwigObject *v)\n{\n  PyObject *res = NULL;\n  PyObject *args = PyTuple_New(1);\n  if (args) {\n    if (PyTuple_SetItem(args, 0, PySwigObject_long(v)) == 0) {\n      PyObject *ofmt = PyString_FromString(fmt);\n      if (ofmt) {\n\tres = PyString_Format(ofmt,args);\n\tPy_DECREF(ofmt);\n      }\n      Py_DECREF(args);\n    }\n  }\n  return res;\n}\n\nSWIGRUNTIME PyObject *\nPySwigObject_oct(PySwigObject *v)\n{\n  return PySwigObject_format(\"%o\",v);\n}\n\nSWIGRUNTIME PyObject *\nPySwigObject_hex(PySwigObject *v)\n{\n  return PySwigObject_format(\"%x\",v);\n}\n\nSWIGRUNTIME PyObject *\n#ifdef METH_NOARGS\nPySwigObject_repr(PySwigObject *v)\n#else\nPySwigObject_repr(PySwigObject *v, PyObject *args)\n#endif\n{\n  const char *name = SWIG_TypePrettyName(v->ty);\n  PyObject *hex = PySwigObject_hex(v);    \n  PyObject *repr = PyString_FromFormat(\"<Swig Object of type '%s' at 0x%s>\", name, PyString_AsString(hex));\n  Py_DECREF(hex);\n  if (v->next) {\n#ifdef METH_NOARGS\n    PyObject *nrep = PySwigObject_repr((PySwigObject *)v->next);\n#else\n    PyObject *nrep = PySwigObject_repr((PySwigObject *)v->next, args);\n#endif\n    PyString_ConcatAndDel(&repr,nrep);\n  }\n  return repr;  \n}\n\nSWIGRUNTIME int\nPySwigObject_print(PySwigObject *v, FILE *fp, int SWIGUNUSEDPARM(flags))\n{\n#ifdef METH_NOARGS\n  PyObject *repr = PySwigObject_repr(v);\n#else\n  PyObject *repr = PySwigObject_repr(v, NULL);\n#endif\n  if (repr) {\n    fputs(PyString_AsString(repr), fp);\n    Py_DECREF(repr);\n    return 0; \n  } else {\n    return 1; \n  }\n}\n\nSWIGRUNTIME PyObject *\nPySwigObject_str(PySwigObject *v)\n{\n  char result[SWIG_BUFFER_SIZE];\n  return SWIG_PackVoidPtr(result, v->ptr, v->ty->name, sizeof(result)) ?\n    PyString_FromString(result) : 0;\n}\n\nSWIGRUNTIME int\nPySwigObject_compare(PySwigObject *v, PySwigObject *w)\n{\n  void *i = v->ptr;\n  void *j = w->ptr;\n  return (i < j) ? -1 : ((i > j) ? 1 : 0);\n}\n\nSWIGRUNTIME PyTypeObject* _PySwigObject_type(void);\n\nSWIGRUNTIME PyTypeObject*\nPySwigObject_type(void) {\n  static PyTypeObject *SWIG_STATIC_POINTER(type) = _PySwigObject_type();\n  return type;\n}\n\nSWIGRUNTIMEINLINE int\nPySwigObject_Check(PyObject *op) {\n  return ((op)->ob_type == PySwigObject_type())\n    || (strcmp((op)->ob_type->tp_name,\"PySwigObject\") == 0);\n}\n\nSWIGRUNTIME PyObject *\nPySwigObject_New(void *ptr, swig_type_info *ty, int own);\n\nSWIGRUNTIME void\nPySwigObject_dealloc(PyObject *v)\n{\n  PySwigObject *sobj = (PySwigObject *) v;\n  PyObject *next = sobj->next;\n  if (sobj->own == SWIG_POINTER_OWN) {\n    swig_type_info *ty = sobj->ty;\n    PySwigClientData *data = ty ? (PySwigClientData *) ty->clientdata : 0;\n    PyObject *destroy = data ? data->destroy : 0;\n    if (destroy) {\n      /* destroy is always a VARARGS method */\n      PyObject *res;\n      if (data->delargs) {\n\t/* we need to create a temporal object to carry the destroy operation */\n\tPyObject *tmp = PySwigObject_New(sobj->ptr, ty, 0);\n\tres = SWIG_Python_CallFunctor(destroy, tmp);\n\tPy_DECREF(tmp);\n      } else {\n\tPyCFunction meth = PyCFunction_GET_FUNCTION(destroy);\n\tPyObject *mself = PyCFunction_GET_SELF(destroy);\n\tres = ((*meth)(mself, v));\n      }\n      Py_XDECREF(res);\n    } \n#if !defined(SWIG_PYTHON_SILENT_MEMLEAK)\n    else {\n      const char *name = SWIG_TypePrettyName(ty);\n      printf(\"swig/python detected a memory leak of type '%s', no destructor found.\\n\", (name ? name : \"unknown\"));\n    }\n#endif\n  } \n  Py_XDECREF(next);\n  PyObject_DEL(v);\n}\n\nSWIGRUNTIME PyObject* \nPySwigObject_append(PyObject* v, PyObject* next)\n{\n  PySwigObject *sobj = (PySwigObject *) v;\n#ifndef METH_O\n  PyObject *tmp = 0;\n  if (!PyArg_ParseTuple(next,(char *)\"O:append\", &tmp)) return NULL;\n  next = tmp;\n#endif\n  if (!PySwigObject_Check(next)) {\n    return NULL;\n  }\n  sobj->next = next;\n  Py_INCREF(next);\n  return SWIG_Py_Void();\n}\n\nSWIGRUNTIME PyObject* \n#ifdef METH_NOARGS\nPySwigObject_next(PyObject* v)\n#else\nPySwigObject_next(PyObject* v, PyObject *SWIGUNUSEDPARM(args))\n#endif\n{\n  PySwigObject *sobj = (PySwigObject *) v;\n  if (sobj->next) {    \n    Py_INCREF(sobj->next);\n    return sobj->next;\n  } else {\n    return SWIG_Py_Void();\n  }\n}\n\nSWIGINTERN PyObject*\n#ifdef METH_NOARGS\nPySwigObject_disown(PyObject *v)\n#else\nPySwigObject_disown(PyObject* v, PyObject *SWIGUNUSEDPARM(args))\n#endif\n{\n  PySwigObject *sobj = (PySwigObject *)v;\n  sobj->own = 0;\n  return SWIG_Py_Void();\n}\n\nSWIGINTERN PyObject*\n#ifdef METH_NOARGS\nPySwigObject_acquire(PyObject *v)\n#else\nPySwigObject_acquire(PyObject* v, PyObject *SWIGUNUSEDPARM(args))\n#endif\n{\n  PySwigObject *sobj = (PySwigObject *)v;\n  sobj->own = SWIG_POINTER_OWN;\n  return SWIG_Py_Void();\n}\n\nSWIGINTERN PyObject*\nPySwigObject_own(PyObject *v, PyObject *args)\n{\n  PyObject *val = 0;\n#if (PY_VERSION_HEX < 0x02020000)\n  if (!PyArg_ParseTuple(args,(char *)\"|O:own\",&val))\n#else\n  if (!PyArg_UnpackTuple(args, (char *)\"own\", 0, 1, &val)) \n#endif\n    {\n      return NULL;\n    } \n  else\n    {\n      PySwigObject *sobj = (PySwigObject *)v;\n      PyObject *obj = PyBool_FromLong(sobj->own);\n      if (val) {\n#ifdef METH_NOARGS\n\tif (PyObject_IsTrue(val)) {\n\t  PySwigObject_acquire(v);\n\t} else {\n\t  PySwigObject_disown(v);\n\t}\n#else\n\tif (PyObject_IsTrue(val)) {\n\t  PySwigObject_acquire(v,args);\n\t} else {\n\t  PySwigObject_disown(v,args);\n\t}\n#endif\n      } \n      return obj;\n    }\n}\n\n#ifdef METH_O\nstatic PyMethodDef\nswigobject_methods[] = {\n  {(char *)\"disown\",  (PyCFunction)PySwigObject_disown,  METH_NOARGS,  (char *)\"releases ownership of the pointer\"},\n  {(char *)\"acquire\", (PyCFunction)PySwigObject_acquire, METH_NOARGS,  (char *)\"aquires ownership of the pointer\"},\n  {(char *)\"own\",     (PyCFunction)PySwigObject_own,     METH_VARARGS, (char *)\"returns/sets ownership of the pointer\"},\n  {(char *)\"append\",  (PyCFunction)PySwigObject_append,  METH_O,       (char *)\"appends another 'this' object\"},\n  {(char *)\"next\",    (PyCFunction)PySwigObject_next,    METH_NOARGS,  (char *)\"returns the next 'this' object\"},\n  {(char *)\"__repr__\",(PyCFunction)PySwigObject_repr,    METH_NOARGS,  (char *)\"returns object representation\"},\n  {0, 0, 0, 0}  \n};\n#else\nstatic PyMethodDef\nswigobject_methods[] = {\n  {(char *)\"disown\",  (PyCFunction)PySwigObject_disown,  METH_VARARGS,  (char *)\"releases ownership of the pointer\"},\n  {(char *)\"acquire\", (PyCFunction)PySwigObject_acquire, METH_VARARGS,  (char *)\"aquires ownership of the pointer\"},\n  {(char *)\"own\",     (PyCFunction)PySwigObject_own,     METH_VARARGS,  (char *)\"returns/sets ownership of the pointer\"},\n  {(char *)\"append\",  (PyCFunction)PySwigObject_append,  METH_VARARGS,  (char *)\"appends another 'this' object\"},\n  {(char *)\"next\",    (PyCFunction)PySwigObject_next,    METH_VARARGS,  (char *)\"returns the next 'this' object\"},\n  {(char *)\"__repr__\",(PyCFunction)PySwigObject_repr,   METH_VARARGS,  (char *)\"returns object representation\"},\n  {0, 0, 0, 0}  \n};\n#endif\n\n#if PY_VERSION_HEX < 0x02020000\nSWIGINTERN PyObject *\nPySwigObject_getattr(PySwigObject *sobj,char *name)\n{\n  return Py_FindMethod(swigobject_methods, (PyObject *)sobj, name);\n}\n#endif\n\nSWIGRUNTIME PyTypeObject*\n_PySwigObject_type(void) {\n  static char swigobject_doc[] = \"Swig object carries a C/C++ instance pointer\";\n  \n  static PyNumberMethods PySwigObject_as_number = {\n    (binaryfunc)0, /*nb_add*/\n    (binaryfunc)0, /*nb_subtract*/\n    (binaryfunc)0, /*nb_multiply*/\n    (binaryfunc)0, /*nb_divide*/\n    (binaryfunc)0, /*nb_remainder*/\n    (binaryfunc)0, /*nb_divmod*/\n    (ternaryfunc)0,/*nb_power*/\n    (unaryfunc)0,  /*nb_negative*/\n    (unaryfunc)0,  /*nb_positive*/\n    (unaryfunc)0,  /*nb_absolute*/\n    (inquiry)0,    /*nb_nonzero*/\n    0,\t\t   /*nb_invert*/\n    0,\t\t   /*nb_lshift*/\n    0,\t\t   /*nb_rshift*/\n    0,\t\t   /*nb_and*/\n    0,\t\t   /*nb_xor*/\n    0,\t\t   /*nb_or*/\n    (coercion)0,   /*nb_coerce*/\n    (unaryfunc)PySwigObject_long, /*nb_int*/\n    (unaryfunc)PySwigObject_long, /*nb_long*/\n    (unaryfunc)0,                 /*nb_float*/\n    (unaryfunc)PySwigObject_oct,  /*nb_oct*/\n    (unaryfunc)PySwigObject_hex,  /*nb_hex*/\n#if PY_VERSION_HEX >= 0x02050000 /* 2.5.0 */\n    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_index */\n#elif PY_VERSION_HEX >= 0x02020000 /* 2.2.0 */\n    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_true_divide */\n#elif PY_VERSION_HEX >= 0x02000000 /* 2.0.0 */\n    0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_or */\n#endif\n  };\n\n  static PyTypeObject pyswigobject_type;  \n  static int type_init = 0;\n  if (!type_init) {\n    const PyTypeObject tmp\n      = {\n\tPyObject_HEAD_INIT(NULL)\n\t0,\t\t\t\t    /* ob_size */\n\t(char *)\"PySwigObject\",\t\t    /* tp_name */\n\tsizeof(PySwigObject),\t\t    /* tp_basicsize */\n\t0,\t\t\t            /* tp_itemsize */\n\t(destructor)PySwigObject_dealloc,   /* tp_dealloc */\n\t(printfunc)PySwigObject_print,\t    /* tp_print */\n#if PY_VERSION_HEX < 0x02020000\n\t(getattrfunc)PySwigObject_getattr,  /* tp_getattr */ \n#else\n\t(getattrfunc)0,\t\t\t    /* tp_getattr */ \n#endif\n\t(setattrfunc)0,\t\t\t    /* tp_setattr */ \n\t(cmpfunc)PySwigObject_compare,\t    /* tp_compare */ \n\t(reprfunc)PySwigObject_repr,\t    /* tp_repr */    \n\t&PySwigObject_as_number,\t    /* tp_as_number */\n\t0,\t\t\t\t    /* tp_as_sequence */\n\t0,\t\t\t\t    /* tp_as_mapping */\n\t(hashfunc)0,\t\t\t    /* tp_hash */\n\t(ternaryfunc)0,\t\t\t    /* tp_call */\n\t(reprfunc)PySwigObject_str,\t    /* tp_str */\n\tPyObject_GenericGetAttr,            /* tp_getattro */\n\t0,\t\t\t\t    /* tp_setattro */\n\t0,\t\t                    /* tp_as_buffer */\n\tPy_TPFLAGS_DEFAULT,\t            /* tp_flags */\n\tswigobject_doc, \t            /* tp_doc */        \n\t0,                                  /* tp_traverse */\n\t0,                                  /* tp_clear */\n\t0,                                  /* tp_richcompare */\n\t0,                                  /* tp_weaklistoffset */\n#if PY_VERSION_HEX >= 0x02020000\n\t0,                                  /* tp_iter */\n\t0,                                  /* tp_iternext */\n\tswigobject_methods,\t\t    /* tp_methods */ \n\t0,\t\t\t            /* tp_members */\n\t0,\t\t\t\t    /* tp_getset */\t    \t\n\t0,\t\t\t            /* tp_base */\t        \n\t0,\t\t\t\t    /* tp_dict */\t    \t\n\t0,\t\t\t\t    /* tp_descr_get */  \t\n\t0,\t\t\t\t    /* tp_descr_set */  \t\n\t0,\t\t\t\t    /* tp_dictoffset */ \t\n\t0,\t\t\t\t    /* tp_init */\t    \t\n\t0,\t\t\t\t    /* tp_alloc */\t    \t\n\t0,\t\t\t            /* tp_new */\t    \t\n\t0,\t                            /* tp_free */\t   \n        0,                                  /* tp_is_gc */  \n\t0,\t\t\t\t    /* tp_bases */   \n\t0,\t\t\t\t    /* tp_mro */\n\t0,\t\t\t\t    /* tp_cache */   \n \t0,\t\t\t\t    /* tp_subclasses */\n\t0,\t\t\t\t    /* tp_weaklist */\n#endif\n#if PY_VERSION_HEX >= 0x02030000\n\t0,                                  /* tp_del */\n#endif\n#ifdef COUNT_ALLOCS\n\t0,0,0,0                             /* tp_alloc -> tp_next */\n#endif\n      };\n    pyswigobject_type = tmp;\n    pyswigobject_type.ob_type = &PyType_Type;\n    type_init = 1;\n  }\n  return &pyswigobject_type;\n}\n\nSWIGRUNTIME PyObject *\nPySwigObject_New(void *ptr, swig_type_info *ty, int own)\n{\n  PySwigObject *sobj = PyObject_NEW(PySwigObject, PySwigObject_type());\n  if (sobj) {\n    sobj->ptr  = ptr;\n    sobj->ty   = ty;\n    sobj->own  = own;\n    sobj->next = 0;\n  }\n  return (PyObject *)sobj;\n}\n\n/* -----------------------------------------------------------------------------\n * Implements a simple Swig Packed type, and use it instead of string\n * ----------------------------------------------------------------------------- */\n\ntypedef struct {\n  PyObject_HEAD\n  void *pack;\n  swig_type_info *ty;\n  size_t size;\n} PySwigPacked;\n\nSWIGRUNTIME int\nPySwigPacked_print(PySwigPacked *v, FILE *fp, int SWIGUNUSEDPARM(flags))\n{\n  char result[SWIG_BUFFER_SIZE];\n  fputs(\"<Swig Packed \", fp); \n  if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) {\n    fputs(\"at \", fp); \n    fputs(result, fp); \n  }\n  fputs(v->ty->name,fp); \n  fputs(\">\", fp);\n  return 0; \n}\n  \nSWIGRUNTIME PyObject *\nPySwigPacked_repr(PySwigPacked *v)\n{\n  char result[SWIG_BUFFER_SIZE];\n  if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) {\n    return PyString_FromFormat(\"<Swig Packed at %s%s>\", result, v->ty->name);\n  } else {\n    return PyString_FromFormat(\"<Swig Packed %s>\", v->ty->name);\n  }  \n}\n\nSWIGRUNTIME PyObject *\nPySwigPacked_str(PySwigPacked *v)\n{\n  char result[SWIG_BUFFER_SIZE];\n  if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))){\n    return PyString_FromFormat(\"%s%s\", result, v->ty->name);\n  } else {\n    return PyString_FromString(v->ty->name);\n  }  \n}\n\nSWIGRUNTIME int\nPySwigPacked_compare(PySwigPacked *v, PySwigPacked *w)\n{\n  size_t i = v->size;\n  size_t j = w->size;\n  int s = (i < j) ? -1 : ((i > j) ? 1 : 0);\n  return s ? s : strncmp((char *)v->pack, (char *)w->pack, 2*v->size);\n}\n\nSWIGRUNTIME PyTypeObject* _PySwigPacked_type(void);\n\nSWIGRUNTIME PyTypeObject*\nPySwigPacked_type(void) {\n  static PyTypeObject *SWIG_STATIC_POINTER(type) = _PySwigPacked_type();\n  return type;\n}\n\nSWIGRUNTIMEINLINE int\nPySwigPacked_Check(PyObject *op) {\n  return ((op)->ob_type == _PySwigPacked_type()) \n    || (strcmp((op)->ob_type->tp_name,\"PySwigPacked\") == 0);\n}\n\nSWIGRUNTIME void\nPySwigPacked_dealloc(PyObject *v)\n{\n  if (PySwigPacked_Check(v)) {\n    PySwigPacked *sobj = (PySwigPacked *) v;\n    free(sobj->pack);\n  }\n  PyObject_DEL(v);\n}\n\nSWIGRUNTIME PyTypeObject*\n_PySwigPacked_type(void) {\n  static char swigpacked_doc[] = \"Swig object carries a C/C++ instance pointer\";\n  static PyTypeObject pyswigpacked_type;\n  static int type_init = 0;  \n  if (!type_init) {\n    const PyTypeObject tmp\n      = {\n\tPyObject_HEAD_INIT(NULL)\n\t0,\t\t\t\t    /* ob_size */\t\n\t(char *)\"PySwigPacked\",\t\t    /* tp_name */\t\n\tsizeof(PySwigPacked),\t\t    /* tp_basicsize */\t\n\t0,\t\t\t\t    /* tp_itemsize */\t\n\t(destructor)PySwigPacked_dealloc,   /* tp_dealloc */\t\n\t(printfunc)PySwigPacked_print,\t    /* tp_print */   \t\n\t(getattrfunc)0,\t\t\t    /* tp_getattr */ \t\n\t(setattrfunc)0,\t\t\t    /* tp_setattr */ \t\n\t(cmpfunc)PySwigPacked_compare,\t    /* tp_compare */ \t\n\t(reprfunc)PySwigPacked_repr,\t    /* tp_repr */    \t\n\t0,\t                            /* tp_as_number */\t\n\t0,\t\t\t\t    /* tp_as_sequence */\n\t0,\t\t\t\t    /* tp_as_mapping */\t\n\t(hashfunc)0,\t\t\t    /* tp_hash */\t\n\t(ternaryfunc)0,\t\t\t    /* tp_call */\t\n\t(reprfunc)PySwigPacked_str,\t    /* tp_str */\t\n\tPyObject_GenericGetAttr,            /* tp_getattro */\n\t0,\t\t\t\t    /* tp_setattro */\n\t0,\t\t                    /* tp_as_buffer */\n\tPy_TPFLAGS_DEFAULT,\t            /* tp_flags */\n\tswigpacked_doc, \t            /* tp_doc */\n\t0,                                  /* tp_traverse */\n\t0,                                  /* tp_clear */\n\t0,                                  /* tp_richcompare */\n\t0,                                  /* tp_weaklistoffset */\n#if PY_VERSION_HEX >= 0x02020000\n\t0,                                  /* tp_iter */\n\t0,                                  /* tp_iternext */\n\t0,\t\t                    /* tp_methods */ \n\t0,\t\t\t            /* tp_members */\n\t0,\t\t\t\t    /* tp_getset */\t    \t\n\t0,\t\t\t            /* tp_base */\t        \n\t0,\t\t\t\t    /* tp_dict */\t    \t\n\t0,\t\t\t\t    /* tp_descr_get */  \t\n\t0,\t\t\t\t    /* tp_descr_set */  \t\n\t0,\t\t\t\t    /* tp_dictoffset */ \t\n\t0,\t\t\t\t    /* tp_init */\t    \t\n\t0,\t\t\t\t    /* tp_alloc */\t    \t\n\t0,\t\t\t            /* tp_new */\t    \t\n\t0, \t                            /* tp_free */\t   \n        0,                                  /* tp_is_gc */  \n\t0,\t\t\t\t    /* tp_bases */   \n\t0,\t\t\t\t    /* tp_mro */\n\t0,\t\t\t\t    /* tp_cache */   \n \t0,\t\t\t\t    /* tp_subclasses */\n\t0,\t\t\t\t    /* tp_weaklist */\n#endif\n#if PY_VERSION_HEX >= 0x02030000\n\t0,                                  /* tp_del */\n#endif\n#ifdef COUNT_ALLOCS\n\t0,0,0,0                             /* tp_alloc -> tp_next */\n#endif\n      };\n    pyswigpacked_type = tmp;\n    pyswigpacked_type.ob_type = &PyType_Type;\n    type_init = 1;\n  }\n  return &pyswigpacked_type;\n}\n\nSWIGRUNTIME PyObject *\nPySwigPacked_New(void *ptr, size_t size, swig_type_info *ty)\n{\n  PySwigPacked *sobj = PyObject_NEW(PySwigPacked, PySwigPacked_type());\n  if (sobj) {\n    void *pack = malloc(size);\n    if (pack) {\n      memcpy(pack, ptr, size);\n      sobj->pack = pack;\n      sobj->ty   = ty;\n      sobj->size = size;\n    } else {\n      PyObject_DEL((PyObject *) sobj);\n      sobj = 0;\n    }\n  }\n  return (PyObject *) sobj;\n}\n\nSWIGRUNTIME swig_type_info *\nPySwigPacked_UnpackData(PyObject *obj, void *ptr, size_t size)\n{\n  if (PySwigPacked_Check(obj)) {\n    PySwigPacked *sobj = (PySwigPacked *)obj;\n    if (sobj->size != size) return 0;\n    memcpy(ptr, sobj->pack, size);\n    return sobj->ty;\n  } else {\n    return 0;\n  }\n}\n\n/* -----------------------------------------------------------------------------\n * pointers/data manipulation\n * ----------------------------------------------------------------------------- */\n\nSWIGRUNTIMEINLINE PyObject *\n_SWIG_This(void)\n{\n  return PyString_FromString(\"this\");\n}\n\nSWIGRUNTIME PyObject *\nSWIG_This(void)\n{\n  static PyObject *SWIG_STATIC_POINTER(swig_this) = _SWIG_This();\n  return swig_this;\n}\n\n/* #define SWIG_PYTHON_SLOW_GETSET_THIS */\n\nSWIGRUNTIME PySwigObject *\nSWIG_Python_GetSwigThis(PyObject *pyobj) \n{\n  if (PySwigObject_Check(pyobj)) {\n    return (PySwigObject *) pyobj;\n  } else {\n    PyObject *obj = 0;\n#if (!defined(SWIG_PYTHON_SLOW_GETSET_THIS) && (PY_VERSION_HEX >= 0x02030000))\n    if (PyInstance_Check(pyobj)) {\n      obj = _PyInstance_Lookup(pyobj, SWIG_This());      \n    } else {\n      PyObject **dictptr = _PyObject_GetDictPtr(pyobj);\n      if (dictptr != NULL) {\n\tPyObject *dict = *dictptr;\n\tobj = dict ? PyDict_GetItem(dict, SWIG_This()) : 0;\n      } else {\n#ifdef PyWeakref_CheckProxy\n\tif (PyWeakref_CheckProxy(pyobj)) {\n\t  PyObject *wobj = PyWeakref_GET_OBJECT(pyobj);\n\t  return wobj ? SWIG_Python_GetSwigThis(wobj) : 0;\n\t}\n#endif\n\tobj = PyObject_GetAttr(pyobj,SWIG_This());\n\tif (obj) {\n\t  Py_DECREF(obj);\n\t} else {\n\t  if (PyErr_Occurred()) PyErr_Clear();\n\t  return 0;\n\t}\n      }\n    }\n#else\n    obj = PyObject_GetAttr(pyobj,SWIG_This());\n    if (obj) {\n      Py_DECREF(obj);\n    } else {\n      if (PyErr_Occurred()) PyErr_Clear();\n      return 0;\n    }\n#endif\n    if (obj && !PySwigObject_Check(obj)) {\n      /* a PyObject is called 'this', try to get the 'real this'\n\t PySwigObject from it */ \n      return SWIG_Python_GetSwigThis(obj);\n    }\n    return (PySwigObject *)obj;\n  }\n}\n\n/* Acquire a pointer value */\n\nSWIGRUNTIME int\nSWIG_Python_AcquirePtr(PyObject *obj, int own) {\n  if (own == SWIG_POINTER_OWN) {\n    PySwigObject *sobj = SWIG_Python_GetSwigThis(obj);\n    if (sobj) {\n      int oldown = sobj->own;\n      sobj->own = own;\n      return oldown;\n    }\n  }\n  return 0;\n}\n\n/* Convert a pointer value */\n\nSWIGRUNTIME int\nSWIG_Python_ConvertPtrAndOwn(PyObject *obj, void **ptr, swig_type_info *ty, int flags, int *own) {\n  if (!obj) return SWIG_ERROR;\n  if (obj == Py_None) {\n    if (ptr) *ptr = 0;\n    return SWIG_OK;\n  } else {\n    PySwigObject *sobj = SWIG_Python_GetSwigThis(obj);\n    if (own)\n      *own = 0;\n    while (sobj) {\n      void *vptr = sobj->ptr;\n      if (ty) {\n\tswig_type_info *to = sobj->ty;\n\tif (to == ty) {\n\t  /* no type cast needed */\n\t  if (ptr) *ptr = vptr;\n\t  break;\n\t} else {\n\t  swig_cast_info *tc = SWIG_TypeCheck(to->name,ty);\n\t  if (!tc) {\n\t    sobj = (PySwigObject *)sobj->next;\n\t  } else {\n\t    if (ptr) {\n              int newmemory = 0;\n              *ptr = SWIG_TypeCast(tc,vptr,&newmemory);\n              if (newmemory == SWIG_CAST_NEW_MEMORY) {\n                assert(own);\n                if (own)\n                  *own = *own | SWIG_CAST_NEW_MEMORY;\n              }\n            }\n\t    break;\n\t  }\n\t}\n      } else {\n\tif (ptr) *ptr = vptr;\n\tbreak;\n      }\n    }\n    if (sobj) {\n      if (own)\n        *own = *own | sobj->own;\n      if (flags & SWIG_POINTER_DISOWN) {\n\tsobj->own = 0;\n      }\n      return SWIG_OK;\n    } else {\n      int res = SWIG_ERROR;\n      if (flags & SWIG_POINTER_IMPLICIT_CONV) {\n\tPySwigClientData *data = ty ? (PySwigClientData *) ty->clientdata : 0;\n\tif (data && !data->implicitconv) {\n\t  PyObject *klass = data->klass;\n\t  if (klass) {\n\t    PyObject *impconv;\n\t    data->implicitconv = 1; /* avoid recursion and call 'explicit' constructors*/\n\t    impconv = SWIG_Python_CallFunctor(klass, obj);\n\t    data->implicitconv = 0;\n\t    if (PyErr_Occurred()) {\n\t      PyErr_Clear();\n\t      impconv = 0;\n\t    }\n\t    if (impconv) {\n\t      PySwigObject *iobj = SWIG_Python_GetSwigThis(impconv);\n\t      if (iobj) {\n\t\tvoid *vptr;\n\t\tres = SWIG_Python_ConvertPtrAndOwn((PyObject*)iobj, &vptr, ty, 0, 0);\n\t\tif (SWIG_IsOK(res)) {\n\t\t  if (ptr) {\n\t\t    *ptr = vptr;\n\t\t    /* transfer the ownership to 'ptr' */\n\t\t    iobj->own = 0;\n\t\t    res = SWIG_AddCast(res);\n\t\t    res = SWIG_AddNewMask(res);\n\t\t  } else {\n\t\t    res = SWIG_AddCast(res);\t\t    \n\t\t  }\n\t\t}\n\t      }\n\t      Py_DECREF(impconv);\n\t    }\n\t  }\n\t}\n      }\n      return res;\n    }\n  }\n}\n\n/* Convert a function ptr value */\n\nSWIGRUNTIME int\nSWIG_Python_ConvertFunctionPtr(PyObject *obj, void **ptr, swig_type_info *ty) {\n  if (!PyCFunction_Check(obj)) {\n    return SWIG_ConvertPtr(obj, ptr, ty, 0);\n  } else {\n    void *vptr = 0;\n    \n    /* here we get the method pointer for callbacks */\n    const char *doc = (((PyCFunctionObject *)obj) -> m_ml -> ml_doc);\n    const char *desc = doc ? strstr(doc, \"swig_ptr: \") : 0;\n    if (desc) {\n      desc = ty ? SWIG_UnpackVoidPtr(desc + 10, &vptr, ty->name) : 0;\n      if (!desc) return SWIG_ERROR;\n    }\n    if (ty) {\n      swig_cast_info *tc = SWIG_TypeCheck(desc,ty);\n      if (tc) {\n        int newmemory = 0;\n        *ptr = SWIG_TypeCast(tc,vptr,&newmemory);\n        assert(!newmemory); /* newmemory handling not yet implemented */\n      } else {\n        return SWIG_ERROR;\n      }\n    } else {\n      *ptr = vptr;\n    }\n    return SWIG_OK;\n  }\n}\n\n/* Convert a packed value value */\n\nSWIGRUNTIME int\nSWIG_Python_ConvertPacked(PyObject *obj, void *ptr, size_t sz, swig_type_info *ty) {\n  swig_type_info *to = PySwigPacked_UnpackData(obj, ptr, sz);\n  if (!to) return SWIG_ERROR;\n  if (ty) {\n    if (to != ty) {\n      /* check type cast? */\n      swig_cast_info *tc = SWIG_TypeCheck(to->name,ty);\n      if (!tc) return SWIG_ERROR;\n    }\n  }\n  return SWIG_OK;\n}  \n\n/* -----------------------------------------------------------------------------\n * Create a new pointer object\n * ----------------------------------------------------------------------------- */\n\n/*\n  Create a new instance object, whitout calling __init__, and set the\n  'this' attribute.\n*/\n\nSWIGRUNTIME PyObject* \nSWIG_Python_NewShadowInstance(PySwigClientData *data, PyObject *swig_this)\n{\n#if (PY_VERSION_HEX >= 0x02020000)\n  PyObject *inst = 0;\n  PyObject *newraw = data->newraw;\n  if (newraw) {\n    inst = PyObject_Call(newraw, data->newargs, NULL);\n    if (inst) {\n#if !defined(SWIG_PYTHON_SLOW_GETSET_THIS)\n      PyObject **dictptr = _PyObject_GetDictPtr(inst);\n      if (dictptr != NULL) {\n\tPyObject *dict = *dictptr;\n\tif (dict == NULL) {\n\t  dict = PyDict_New();\n\t  *dictptr = dict;\n\t  PyDict_SetItem(dict, SWIG_This(), swig_this);\n\t}\n      }\n#else\n      PyObject *key = SWIG_This();\n      PyObject_SetAttr(inst, key, swig_this);\n#endif\n    }\n  } else {\n    PyObject *dict = PyDict_New();\n    PyDict_SetItem(dict, SWIG_This(), swig_this);\n    inst = PyInstance_NewRaw(data->newargs, dict);\n    Py_DECREF(dict);\n  }\n  return inst;\n#else\n#if (PY_VERSION_HEX >= 0x02010000)\n  PyObject *inst;\n  PyObject *dict = PyDict_New();\n  PyDict_SetItem(dict, SWIG_This(), swig_this);\n  inst = PyInstance_NewRaw(data->newargs, dict);\n  Py_DECREF(dict);\n  return (PyObject *) inst;\n#else\n  PyInstanceObject *inst = PyObject_NEW(PyInstanceObject, &PyInstance_Type);\n  if (inst == NULL) {\n    return NULL;\n  }\n  inst->in_class = (PyClassObject *)data->newargs;\n  Py_INCREF(inst->in_class);\n  inst->in_dict = PyDict_New();\n  if (inst->in_dict == NULL) {\n    Py_DECREF(inst);\n    return NULL;\n  }\n#ifdef Py_TPFLAGS_HAVE_WEAKREFS\n  inst->in_weakreflist = NULL;\n#endif\n#ifdef Py_TPFLAGS_GC\n  PyObject_GC_Init(inst);\n#endif\n  PyDict_SetItem(inst->in_dict, SWIG_This(), swig_this);\n  return (PyObject *) inst;\n#endif\n#endif\n}\n\nSWIGRUNTIME void\nSWIG_Python_SetSwigThis(PyObject *inst, PyObject *swig_this)\n{\n PyObject *dict;\n#if (PY_VERSION_HEX >= 0x02020000) && !defined(SWIG_PYTHON_SLOW_GETSET_THIS)\n PyObject **dictptr = _PyObject_GetDictPtr(inst);\n if (dictptr != NULL) {\n   dict = *dictptr;\n   if (dict == NULL) {\n     dict = PyDict_New();\n     *dictptr = dict;\n   }\n   PyDict_SetItem(dict, SWIG_This(), swig_this);\n   return;\n }\n#endif\n dict = PyObject_GetAttrString(inst, (char*)\"__dict__\");\n PyDict_SetItem(dict, SWIG_This(), swig_this);\n Py_DECREF(dict);\n} \n\n\nSWIGINTERN PyObject *\nSWIG_Python_InitShadowInstance(PyObject *args) {\n  PyObject *obj[2];\n  if (!SWIG_Python_UnpackTuple(args,(char*)\"swiginit\", 2, 2, obj)) {\n    return NULL;\n  } else {\n    PySwigObject *sthis = SWIG_Python_GetSwigThis(obj[0]);\n    if (sthis) {\n      PySwigObject_append((PyObject*) sthis, obj[1]);\n    } else {\n      SWIG_Python_SetSwigThis(obj[0], obj[1]);\n    }\n    return SWIG_Py_Void();\n  }\n}\n\n/* Create a new pointer object */\n\nSWIGRUNTIME PyObject *\nSWIG_Python_NewPointerObj(void *ptr, swig_type_info *type, int flags) {\n  if (!ptr) {\n    return SWIG_Py_Void();\n  } else {\n    int own = (flags & SWIG_POINTER_OWN) ? SWIG_POINTER_OWN : 0;\n    PyObject *robj = PySwigObject_New(ptr, type, own);\n    PySwigClientData *clientdata = type ? (PySwigClientData *)(type->clientdata) : 0;\n    if (clientdata && !(flags & SWIG_POINTER_NOSHADOW)) {\n      PyObject *inst = SWIG_Python_NewShadowInstance(clientdata, robj);\n      if (inst) {\n\tPy_DECREF(robj);\n\trobj = inst;\n      }\n    }\n    return robj;\n  }\n}\n\n/* Create a new packed object */\n\nSWIGRUNTIMEINLINE PyObject *\nSWIG_Python_NewPackedObj(void *ptr, size_t sz, swig_type_info *type) {\n  return ptr ? PySwigPacked_New((void *) ptr, sz, type) : SWIG_Py_Void();\n}\n\n/* -----------------------------------------------------------------------------*\n *  Get type list \n * -----------------------------------------------------------------------------*/\n\n#ifdef SWIG_LINK_RUNTIME\nvoid *SWIG_ReturnGlobalTypeList(void *);\n#endif\n\nSWIGRUNTIME swig_module_info *\nSWIG_Python_GetModule(void) {\n  static void *type_pointer = (void *)0;\n  /* first check if module already created */\n  if (!type_pointer) {\n#ifdef SWIG_LINK_RUNTIME\n    type_pointer = SWIG_ReturnGlobalTypeList((void *)0);\n#else\n    type_pointer = PyCObject_Import((char*)\"swig_runtime_data\" SWIG_RUNTIME_VERSION,\n\t\t\t\t    (char*)\"type_pointer\" SWIG_TYPE_TABLE_NAME);\n    if (PyErr_Occurred()) {\n      PyErr_Clear();\n      type_pointer = (void *)0;\n    }\n#endif\n  }\n  return (swig_module_info *) type_pointer;\n}\n\n#if PY_MAJOR_VERSION < 2\n/* PyModule_AddObject function was introduced in Python 2.0.  The following function\n   is copied out of Python/modsupport.c in python version 2.3.4 */\nSWIGINTERN int\nPyModule_AddObject(PyObject *m, char *name, PyObject *o)\n{\n  PyObject *dict;\n  if (!PyModule_Check(m)) {\n    PyErr_SetString(PyExc_TypeError,\n\t\t    \"PyModule_AddObject() needs module as first arg\");\n    return SWIG_ERROR;\n  }\n  if (!o) {\n    PyErr_SetString(PyExc_TypeError,\n\t\t    \"PyModule_AddObject() needs non-NULL value\");\n    return SWIG_ERROR;\n  }\n  \n  dict = PyModule_GetDict(m);\n  if (dict == NULL) {\n    /* Internal error -- modules must have a dict! */\n    PyErr_Format(PyExc_SystemError, \"module '%s' has no __dict__\",\n\t\t PyModule_GetName(m));\n    return SWIG_ERROR;\n  }\n  if (PyDict_SetItemString(dict, name, o))\n    return SWIG_ERROR;\n  Py_DECREF(o);\n  return SWIG_OK;\n}\n#endif\n\nSWIGRUNTIME void\nSWIG_Python_DestroyModule(void *vptr)\n{\n  swig_module_info *swig_module = (swig_module_info *) vptr;\n  swig_type_info **types = swig_module->types;\n  size_t i;\n  for (i =0; i < swig_module->size; ++i) {\n    swig_type_info *ty = types[i];\n    if (ty->owndata) {\n      PySwigClientData *data = (PySwigClientData *) ty->clientdata;\n      if (data) PySwigClientData_Del(data);\n    }\n  }\n  Py_DECREF(SWIG_This());\n}\n\nSWIGRUNTIME void\nSWIG_Python_SetModule(swig_module_info *swig_module) {\n  static PyMethodDef swig_empty_runtime_method_table[] = { {NULL, NULL, 0, NULL} };/* Sentinel */\n\n  PyObject *module = Py_InitModule((char*)\"swig_runtime_data\" SWIG_RUNTIME_VERSION,\n\t\t\t\t   swig_empty_runtime_method_table);\n  PyObject *pointer = PyCObject_FromVoidPtr((void *) swig_module, SWIG_Python_DestroyModule);\n  if (pointer && module) {\n    PyModule_AddObject(module, (char*)\"type_pointer\" SWIG_TYPE_TABLE_NAME, pointer);\n  } else {\n    Py_XDECREF(pointer);\n  }\n}\n\n/* The python cached type query */\nSWIGRUNTIME PyObject *\nSWIG_Python_TypeCache(void) {\n  static PyObject *SWIG_STATIC_POINTER(cache) = PyDict_New();\n  return cache;\n}\n\nSWIGRUNTIME swig_type_info *\nSWIG_Python_TypeQuery(const char *type)\n{\n  PyObject *cache = SWIG_Python_TypeCache();\n  PyObject *key = PyString_FromString(type); \n  PyObject *obj = PyDict_GetItem(cache, key);\n  swig_type_info *descriptor;\n  if (obj) {\n    descriptor = (swig_type_info *) PyCObject_AsVoidPtr(obj);\n  } else {\n    swig_module_info *swig_module = SWIG_Python_GetModule();\n    descriptor = SWIG_TypeQueryModule(swig_module, swig_module, type);\n    if (descriptor) {\n      obj = PyCObject_FromVoidPtr(descriptor, NULL);\n      PyDict_SetItem(cache, key, obj);\n      Py_DECREF(obj);\n    }\n  }\n  Py_DECREF(key);\n  return descriptor;\n}\n\n/* \n   For backward compatibility only\n*/\n#define SWIG_POINTER_EXCEPTION  0\n#define SWIG_arg_fail(arg)      SWIG_Python_ArgFail(arg)\n#define SWIG_MustGetPtr(p, type, argnum, flags)  SWIG_Python_MustGetPtr(p, type, argnum, flags)\n\nSWIGRUNTIME int\nSWIG_Python_AddErrMesg(const char* mesg, int infront)\n{\n  if (PyErr_Occurred()) {\n    PyObject *type = 0;\n    PyObject *value = 0;\n    PyObject *traceback = 0;\n    PyErr_Fetch(&type, &value, &traceback);\n    if (value) {\n      PyObject *old_str = PyObject_Str(value);\n      Py_XINCREF(type);\n      PyErr_Clear();\n      if (infront) {\n\tPyErr_Format(type, \"%s %s\", mesg, PyString_AsString(old_str));\n      } else {\n\tPyErr_Format(type, \"%s %s\", PyString_AsString(old_str), mesg);\n      }\n      Py_DECREF(old_str);\n    }\n    return 1;\n  } else {\n    return 0;\n  }\n}\n  \nSWIGRUNTIME int\nSWIG_Python_ArgFail(int argnum)\n{\n  if (PyErr_Occurred()) {\n    /* add information about failing argument */\n    char mesg[256];\n    PyOS_snprintf(mesg, sizeof(mesg), \"argument number %d:\", argnum);\n    return SWIG_Python_AddErrMesg(mesg, 1);\n  } else {\n    return 0;\n  }\n}\n\nSWIGRUNTIMEINLINE const char *\nPySwigObject_GetDesc(PyObject *self)\n{\n  PySwigObject *v = (PySwigObject *)self;\n  swig_type_info *ty = v ? v->ty : 0;\n  return ty ? ty->str : (char*)\"\";\n}\n\nSWIGRUNTIME void\nSWIG_Python_TypeError(const char *type, PyObject *obj)\n{\n  if (type) {\n#if defined(SWIG_COBJECT_TYPES)\n    if (obj && PySwigObject_Check(obj)) {\n      const char *otype = (const char *) PySwigObject_GetDesc(obj);\n      if (otype) {\n\tPyErr_Format(PyExc_TypeError, \"a '%s' is expected, 'PySwigObject(%s)' is received\",\n\t\t     type, otype);\n\treturn;\n      }\n    } else \n#endif      \n    {\n      const char *otype = (obj ? obj->ob_type->tp_name : 0); \n      if (otype) {\n\tPyObject *str = PyObject_Str(obj);\n\tconst char *cstr = str ? PyString_AsString(str) : 0;\n\tif (cstr) {\n\t  PyErr_Format(PyExc_TypeError, \"a '%s' is expected, '%s(%s)' is received\",\n\t\t       type, otype, cstr);\n\t} else {\n\t  PyErr_Format(PyExc_TypeError, \"a '%s' is expected, '%s' is received\",\n\t\t       type, otype);\n\t}\n\tPy_XDECREF(str);\n\treturn;\n      }\n    }   \n    PyErr_Format(PyExc_TypeError, \"a '%s' is expected\", type);\n  } else {\n    PyErr_Format(PyExc_TypeError, \"unexpected type is received\");\n  }\n}\n\n\n/* Convert a pointer value, signal an exception on a type mismatch */\nSWIGRUNTIME void *\nSWIG_Python_MustGetPtr(PyObject *obj, swig_type_info *ty, int argnum, int flags) {\n  void *result;\n  if (SWIG_Python_ConvertPtr(obj, &result, ty, flags) == -1) {\n    PyErr_Clear();\n    if (flags & SWIG_POINTER_EXCEPTION) {\n      SWIG_Python_TypeError(SWIG_TypePrettyName(ty), obj);\n      SWIG_Python_ArgFail(argnum);\n    }\n  }\n  return result;\n}\n\n\n#ifdef __cplusplus\n#if 0\n{ /* cc-mode */\n#endif\n}\n#endif\n\n\n\n#define SWIG_exception_fail(code, msg) do { SWIG_Error(code, msg); SWIG_fail; } while(0) \n\n#define SWIG_contract_assert(expr, msg) if (!(expr)) { SWIG_Error(SWIG_RuntimeError, msg); SWIG_fail; } else \n\n\n\n/* -------- TYPES TABLE (BEGIN) -------- */\n\n#define SWIGTYPE_p_FILE swig_types[0]\n#define SWIGTYPE_p_char swig_types[1]\n#define SWIGTYPE_p_double swig_types[2]\n#define SWIGTYPE_p_float swig_types[3]\n#define SWIGTYPE_p_gsl_complex swig_types[4]\n#define SWIGTYPE_p_gsl_complex_float swig_types[5]\n#define SWIGTYPE_p_gsl_matrix swig_types[6]\n#define SWIGTYPE_p_gsl_matrix_char swig_types[7]\n#define SWIGTYPE_p_gsl_matrix_complex swig_types[8]\n#define SWIGTYPE_p_gsl_matrix_complex_float swig_types[9]\n#define SWIGTYPE_p_gsl_matrix_float swig_types[10]\n#define SWIGTYPE_p_gsl_matrix_int swig_types[11]\n#define SWIGTYPE_p_gsl_matrix_long swig_types[12]\n#define SWIGTYPE_p_gsl_matrix_short swig_types[13]\n#define SWIGTYPE_p_gsl_vector swig_types[14]\n#define SWIGTYPE_p_gsl_vector_char swig_types[15]\n#define SWIGTYPE_p_gsl_vector_complex swig_types[16]\n#define SWIGTYPE_p_gsl_vector_complex_float swig_types[17]\n#define SWIGTYPE_p_gsl_vector_float swig_types[18]\n#define SWIGTYPE_p_gsl_vector_int swig_types[19]\n#define SWIGTYPE_p_gsl_vector_long swig_types[20]\n#define SWIGTYPE_p_gsl_vector_short swig_types[21]\n#define SWIGTYPE_p_int swig_types[22]\n#define SWIGTYPE_p_long swig_types[23]\n#define SWIGTYPE_p_short swig_types[24]\n#define SWIGTYPE_p_unsigned_int swig_types[25]\nstatic swig_type_info *swig_types[27];\nstatic swig_module_info swig_module = {swig_types, 26, 0, 0, 0, 0};\n#define SWIG_TypeQuery(name) SWIG_TypeQueryModule(&swig_module, &swig_module, name)\n#define SWIG_MangledTypeQuery(name) SWIG_MangledTypeQueryModule(&swig_module, &swig_module, name)\n\n/* -------- TYPES TABLE (END) -------- */\n\n#if (PY_VERSION_HEX <= 0x02000000)\n# if !defined(SWIG_PYTHON_CLASSIC)\n#  error \"This python version requires swig to be run with the '-classic' option\"\n# endif\n#endif\n\n/*-----------------------------------------------\n              @(target):= __block.so\n  ------------------------------------------------*/\n#define SWIG_init    init__block\n\n#define SWIG_name    \"__block\"\n\n#define SWIGVERSION 0x010336 \n#define SWIG_VERSION SWIGVERSION\n\n\n#define SWIG_as_voidptr(a) (void *)((const void *)(a)) \n#define SWIG_as_voidptrptr(a) ((void)SWIG_as_voidptr(*a),(void**)(a)) \n\n\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_complex.h>\n#include <stdlib.h>\n#include <assert.h>\n#include <pygsl/error_helpers.h>\n\n\n  /*\n   * Normally Microsofts (R) Visual C (TM) Compiler is used to compile python \n   * on windows.\n   * When I used MinGW to compile I could not convert Python File Objects to \n   * C File Structs (The function PyFile_AsFile generated a core). Therefore \n   * I raise a python exception if someone tries to use this Code when it was \n   * compiled with MinGW. Do you know a better solution? Perhaps how to get it \n   * work?\n   */\n#ifdef __MINGW32__\n#define HANDLE_MINGW() \\\n  do { \\\n  PyGSL_add_traceback(NULL, __FILE__, __FUNCTION__, __LINE__); \\\n  PyErr_SetString(PyExc_TypeError, \"This Module was compiled using MinGW32. \" \\\n\t\t  \"Conversion of python files to C files is not supported.\");\\\n  goto fail; \\\n  } while(0)\n#else\n#define HANDLE_MINGW()\n#endif   \n\n\n#include <pygsl/utils.h>\n#include <pygsl/block_helpers.h>\n#include <typemaps/block_conversion_functions.h>\n#include <string.h>\n#include <assert.h>\n\n   \n#include <pygsl/utils.h>\n#include <pygsl/error_helpers.h>\ntypedef int gsl_error_flag;\ntypedef int gsl_error_flag_drop;\nPyObject *pygsl_module_for_error_treatment = NULL;\n                        \n\n\nSWIGINTERN int\nSWIG_AsVal_double (PyObject *obj, double *val)\n{\n  int res = SWIG_TypeError;\n  if (PyFloat_Check(obj)) {\n    if (val) *val = PyFloat_AsDouble(obj);\n    return SWIG_OK;\n  } else if (PyInt_Check(obj)) {\n    if (val) *val = PyInt_AsLong(obj);\n    return SWIG_OK;\n  } else if (PyLong_Check(obj)) {\n    double v = PyLong_AsDouble(obj);\n    if (!PyErr_Occurred()) {\n      if (val) *val = v;\n      return SWIG_OK;\n    } else {\n      PyErr_Clear();\n    }\n  }\n#ifdef SWIG_PYTHON_CAST_MODE\n  {\n    int dispatch = 0;\n    double d = PyFloat_AsDouble(obj);\n    if (!PyErr_Occurred()) {\n      if (val) *val = d;\n      return SWIG_AddCast(SWIG_OK);\n    } else {\n      PyErr_Clear();\n    }\n    if (!dispatch) {\n      long v = PyLong_AsLong(obj);\n      if (!PyErr_Occurred()) {\n\tif (val) *val = v;\n\treturn SWIG_AddCast(SWIG_AddCast(SWIG_OK));\n      } else {\n\tPyErr_Clear();\n      }\n    }\n  }\n#endif\n  return res;\n}\n\n\n#include <float.h>\n\n\n#include <math.h>\n\n\nSWIGINTERNINLINE int\nSWIG_CanCastAsInteger(double *d, double min, double max) {\n  double x = *d;\n  if ((min <= x && x <= max)) {\n   double fx = floor(x);\n   double cx = ceil(x);\n   double rd =  ((x - fx) < 0.5) ? fx : cx; /* simple rint */\n   if ((errno == EDOM) || (errno == ERANGE)) {\n     errno = 0;\n   } else {\n     double summ, reps, diff;\n     if (rd < x) {\n       diff = x - rd;\n     } else if (rd > x) {\n       diff = rd - x;\n     } else {\n       return 1;\n     }\n     summ = rd + x;\n     reps = diff/summ;\n     if (reps < 8*DBL_EPSILON) {\n       *d = rd;\n       return 1;\n     }\n   }\n  }\n  return 0;\n}\n\n\nSWIGINTERN int\nSWIG_AsVal_unsigned_SS_long (PyObject *obj, unsigned long *val) \n{\n  if (PyInt_Check(obj)) {\n    long v = PyInt_AsLong(obj);\n    if (v >= 0) {\n      if (val) *val = v;\n      return SWIG_OK;\n    } else {\n      return SWIG_OverflowError;\n    }\n  } else if (PyLong_Check(obj)) {\n    unsigned long v = PyLong_AsUnsignedLong(obj);\n    if (!PyErr_Occurred()) {\n      if (val) *val = v;\n      return SWIG_OK;\n    } else {\n      PyErr_Clear();\n    }\n  }\n#ifdef SWIG_PYTHON_CAST_MODE\n  {\n    int dispatch = 0;\n    unsigned long v = PyLong_AsUnsignedLong(obj);\n    if (!PyErr_Occurred()) {\n      if (val) *val = v;\n      return SWIG_AddCast(SWIG_OK);\n    } else {\n      PyErr_Clear();\n    }\n    if (!dispatch) {\n      double d;\n      int res = SWIG_AddCast(SWIG_AsVal_double (obj,&d));\n      if (SWIG_IsOK(res) && SWIG_CanCastAsInteger(&d, 0, ULONG_MAX)) {\n\tif (val) *val = (unsigned long)(d);\n\treturn res;\n      }\n    }\n  }\n#endif\n  return SWIG_TypeError;\n}\n\n\nSWIGINTERNINLINE int\nSWIG_AsVal_size_t (PyObject * obj, size_t *val)\n{\n  unsigned long v;\n  int res = SWIG_AsVal_unsigned_SS_long (obj, val ? &v : 0);\n  if (SWIG_IsOK(res) && val) *val = (size_t)(v);\n  return res;\n}\n\n\nSWIGINTERN swig_type_info*\nSWIG_pchar_descriptor(void)\n{\n  static int init = 0;\n  static swig_type_info* info = 0;\n  if (!init) {\n    info = SWIG_TypeQuery(\"_p_char\");\n    init = 1;\n  }\n  return info;\n}\n\n\nSWIGINTERN int\nSWIG_AsCharPtrAndSize(PyObject *obj, char** cptr, size_t* psize, int *alloc)\n{\n  if (PyString_Check(obj)) {\n    char *cstr; Py_ssize_t len;\n    PyString_AsStringAndSize(obj, &cstr, &len);\n    if (cptr)  {\n      if (alloc) {\n\t/* \n\t   In python the user should not be able to modify the inner\n\t   string representation. To warranty that, if you define\n\t   SWIG_PYTHON_SAFE_CSTRINGS, a new/copy of the python string\n\t   buffer is always returned.\n\n\t   The default behavior is just to return the pointer value,\n\t   so, be careful.\n\t*/ \n#if defined(SWIG_PYTHON_SAFE_CSTRINGS)\n\tif (*alloc != SWIG_OLDOBJ) \n#else\n\tif (*alloc == SWIG_NEWOBJ) \n#endif\n\t  {\n\t    *cptr = (char *)memcpy((char *)malloc((len + 1)*sizeof(char)), cstr, sizeof(char)*(len + 1));\n\t    *alloc = SWIG_NEWOBJ;\n\t  }\n\telse {\n\t  *cptr = cstr;\n\t  *alloc = SWIG_OLDOBJ;\n\t}\n      } else {\n\t*cptr = PyString_AsString(obj);\n      }\n    }\n    if (psize) *psize = len + 1;\n    return SWIG_OK;\n  } else {\n    swig_type_info* pchar_descriptor = SWIG_pchar_descriptor();\n    if (pchar_descriptor) {\n      void* vptr = 0;\n      if (SWIG_ConvertPtr(obj, &vptr, pchar_descriptor, 0) == SWIG_OK) {\n\tif (cptr) *cptr = (char *) vptr;\n\tif (psize) *psize = vptr ? (strlen((char *)vptr) + 1) : 0;\n\tif (alloc) *alloc = SWIG_OLDOBJ;\n\treturn SWIG_OK;\n      }\n    }\n  }\n  return SWIG_TypeError;\n}\n\n\n\n\n\n  #define SWIG_From_double   PyFloat_FromDouble \n\n\n  #define SWIG_From_long   PyInt_FromLong \n\n\nSWIGINTERNINLINE PyObject* \nSWIG_From_unsigned_SS_long  (unsigned long value)\n{\n  return (value > LONG_MAX) ?\n    PyLong_FromUnsignedLong(value) : PyInt_FromLong((long)(value)); \n}\n\n\nSWIGINTERNINLINE PyObject *\nSWIG_From_size_t  (size_t value)\n{    \n  return SWIG_From_unsigned_SS_long  ((unsigned long)(value));\n}\n\n\nSWIGINTERNINLINE PyObject *\nSWIG_From_int  (int value)\n{    \n  return SWIG_From_long  (value);\n}\n\n\nSWIGINTERN int\nSWIG_AsVal_float (PyObject * obj, float *val)\n{\n  double v;\n  int res = SWIG_AsVal_double (obj, &v);\n  if (SWIG_IsOK(res)) {\n    if ((v < -FLT_MAX || v > FLT_MAX)) {\n      return SWIG_OverflowError;\n    } else {\n      if (val) *val = (float)(v);\n    }\n  }  \n  return res;\n}\n\n\nSWIGINTERNINLINE PyObject *\nSWIG_From_float  (float value)\n{    \n  return SWIG_From_double  (value);\n}\n\n\nSWIGINTERN int\nSWIG_AsVal_long (PyObject *obj, long* val)\n{\n  if (PyInt_Check(obj)) {\n    if (val) *val = PyInt_AsLong(obj);\n    return SWIG_OK;\n  } else if (PyLong_Check(obj)) {\n    long v = PyLong_AsLong(obj);\n    if (!PyErr_Occurred()) {\n      if (val) *val = v;\n      return SWIG_OK;\n    } else {\n      PyErr_Clear();\n    }\n  }\n#ifdef SWIG_PYTHON_CAST_MODE\n  {\n    int dispatch = 0;\n    long v = PyInt_AsLong(obj);\n    if (!PyErr_Occurred()) {\n      if (val) *val = v;\n      return SWIG_AddCast(SWIG_OK);\n    } else {\n      PyErr_Clear();\n    }\n    if (!dispatch) {\n      double d;\n      int res = SWIG_AddCast(SWIG_AsVal_double (obj,&d));\n      if (SWIG_IsOK(res) && SWIG_CanCastAsInteger(&d, LONG_MIN, LONG_MAX)) {\n\tif (val) *val = (long)(d);\n\treturn res;\n      }\n    }\n  }\n#endif\n  return SWIG_TypeError;\n}\n\n\n#include <limits.h>\n#if !defined(SWIG_NO_LLONG_MAX)\n# if !defined(LLONG_MAX) && defined(__GNUC__) && defined (__LONG_LONG_MAX__)\n#   define LLONG_MAX __LONG_LONG_MAX__\n#   define LLONG_MIN (-LLONG_MAX - 1LL)\n#   define ULLONG_MAX (LLONG_MAX * 2ULL + 1ULL)\n# endif\n#endif\n\n\nSWIGINTERN int\nSWIG_AsVal_int (PyObject * obj, int *val)\n{\n  long v;\n  int res = SWIG_AsVal_long (obj, &v);\n  if (SWIG_IsOK(res)) {\n    if ((v < INT_MIN || v > INT_MAX)) {\n      return SWIG_OverflowError;\n    } else {\n      if (val) *val = (int)(v);\n    }\n  }  \n  return res;\n}\n\n\nSWIGINTERN int\nSWIG_AsVal_short (PyObject * obj, short *val)\n{\n  long v;\n  int res = SWIG_AsVal_long (obj, &v);\n  if (SWIG_IsOK(res)) {\n    if ((v < SHRT_MIN || v > SHRT_MAX)) {\n      return SWIG_OverflowError;\n    } else {\n      if (val) *val = (short)(v);\n    }\n  }  \n  return res;\n}\n\n\nSWIGINTERNINLINE PyObject *\nSWIG_From_short  (short value)\n{    \n  return SWIG_From_long  (value);\n}\n\n\nSWIGINTERN int\nSWIG_AsCharArray(PyObject * obj, char *val, size_t size)\n{ \n  char* cptr = 0; size_t csize = 0; int alloc = SWIG_OLDOBJ;\n  int res = SWIG_AsCharPtrAndSize(obj, &cptr, &csize, &alloc);\n  if (SWIG_IsOK(res)) {\n    if ((csize == size + 1) && cptr && !(cptr[csize-1])) --csize;\n    if (csize <= size) {\n      if (val) {\n\tif (csize) memcpy(val, cptr, csize*sizeof(char));\n\tif (csize < size) memset(val + csize, 0, (size - csize)*sizeof(char));\n      }\n      if (alloc == SWIG_NEWOBJ) {\n\tfree((char*)cptr);\n\tres = SWIG_DelNewMask(res);\n      }      \n      return res;\n    }\n    if (alloc == SWIG_NEWOBJ) free((char*)cptr);\n  }\n  return SWIG_TypeError;\n}\n\n\nSWIGINTERN int\nSWIG_AsVal_char (PyObject * obj, char *val)\n{    \n  int res = SWIG_AsCharArray(obj, val, 1);\n  if (!SWIG_IsOK(res)) {\n    long v;\n    res = SWIG_AddCast(SWIG_AsVal_long (obj, &v));\n    if (SWIG_IsOK(res)) {\n      if ((CHAR_MIN <= v) && (v <= CHAR_MAX)) {\n\tif (val) *val = (char)(v);\n      } else {\n\tres = SWIG_OverflowError;\n      }\n    }\n  }\n  return res;\n}\n\n\nSWIGINTERNINLINE PyObject *\nSWIG_FromCharPtrAndSize(const char* carray, size_t size)\n{\n  if (carray) {\n    if (size > INT_MAX) {\n      swig_type_info* pchar_descriptor = SWIG_pchar_descriptor();\n      return pchar_descriptor ? \n\tSWIG_NewPointerObj((char *)(carray), pchar_descriptor, 0) : SWIG_Py_Void();\n    } else {\n      return PyString_FromStringAndSize(carray, (int)(size));\n    }\n  } else {\n    return SWIG_Py_Void();\n  }\n}\n\n\nSWIGINTERNINLINE PyObject *\nSWIG_From_char  (char c) \n{ \n  return SWIG_FromCharPtrAndSize(&c,1);\n}\n\n\n#define _GSL_BLOCK_COMPLEX_FUNCTIONS_C\n\n\n#include <gsl/gsl_errno.h>\n#include <pygsl/utils.h>\n#include <pygsl/complex_helpers.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\nSWIGINTERN PyObject *_wrap_gsl_vector_set_zero(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector *arg1 = (gsl_vector *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\", NULL \n  };\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_set_zero\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    int flag;\n    _vector1.vector.data = NULL;\n    flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1,\n      PyGSL_OUTPUT_ARRAY, gsl_vector, 1, &stride);\n    if (flag != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  gsl_vector_set_zero(arg1);\n  resultobj = SWIG_Py_Void();\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyVector1);\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyVector1);\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_set_all(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector *arg1 = (gsl_vector *) 0 ;\n  double arg2 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\",(char *) \"x\", NULL \n  };\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_set_all\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    int flag;\n    _vector1.vector.data = NULL;\n    flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1,\n      PyGSL_OUTPUT_ARRAY, gsl_vector, 1, &stride);\n    if (flag != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_vector_set_all\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  gsl_vector_set_all(arg1,arg2);\n  resultobj = SWIG_Py_Void();\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyVector1);\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyVector1);\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_set_basis(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector *arg1 = (gsl_vector *) 0 ;\n  size_t arg2 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\",(char *) \"i\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_set_basis\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    int flag;\n    _vector1.vector.data = NULL;\n    flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1,\n      PyGSL_OUTPUT_ARRAY, gsl_vector, 1, &stride);\n    if (flag != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_vector_set_basis\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  result = (int)gsl_vector_set_basis(arg1,arg2);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyVector1);\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyVector1);\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_fread(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_vector *arg2 = (gsl_vector *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN_SIZE_OUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_fread\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride;\n    int flag;\n    _vector2.vector.data = NULL;\n    flag = PyGSL_VECTOR_GENERATE(obj1, arg2, _PyVector2, _vector2,\n      PyGSL_OUTPUT_ARRAY, gsl_vector, 2, &stride);\n    if (flag != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_fread(arg1,arg2);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  {\n    assert(_PyVector2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector2));\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyVector2);\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyVector2);\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_fwrite(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_vector *arg2 = (gsl_vector *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_fwrite\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2,\n        PyGSL_INPUT_ARRAY, gsl_vector, 2, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_fwrite(arg1,(gsl_vector const *)arg2);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  {\n    Py_XDECREF(_PyVector2);\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyVector2);\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_fscanf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_vector *arg2 = (gsl_vector *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN_SIZE_OUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_fscanf\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride;\n    int flag;\n    _vector2.vector.data = NULL;\n    flag = PyGSL_VECTOR_GENERATE(obj1, arg2, _PyVector2, _vector2,\n      PyGSL_OUTPUT_ARRAY, gsl_vector, 2, &stride);\n    if (flag != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_fscanf(arg1,arg2);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  {\n    assert(_PyVector2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector2));\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyVector2);\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyVector2);\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_fprintf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_vector *arg2 = (gsl_vector *) 0 ;\n  char *arg3 = (char *) 0 ;\n  int res3 ;\n  char *buf3 = 0 ;\n  int alloc3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN\",(char *) \"format\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_vector_fprintf\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2,\n        PyGSL_INPUT_ARRAY, gsl_vector, 2, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3);\n  if (!SWIG_IsOK(res3)) {\n    SWIG_exception_fail(SWIG_ArgError(res3), \"in method '\" \"gsl_vector_fprintf\" \"', argument \" \"3\"\" of type '\" \"char const *\"\"'\");\n  }\n  arg3 = (char *)(buf3);\n  result = (int)gsl_vector_fprintf(arg1,(gsl_vector const *)arg2,(char const *)arg3);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  {\n    Py_XDECREF(_PyVector2);\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  if (alloc3 == SWIG_NEWOBJ) free((char*)buf3);\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyVector2);\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  if (alloc3 == SWIG_NEWOBJ) free((char*)buf3);\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_reverse(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector *arg1 = (gsl_vector *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_reverse\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_IO_ARRAY, gsl_vector, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_reverse(arg1);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyVector1);\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyVector1);\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_swap(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector *arg1 = (gsl_vector *) 0 ;\n  gsl_vector *arg2 = (gsl_vector *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"INOUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector _vector1;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_swap\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_IO_ARRAY, gsl_vector, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2,\n        PyGSL_IO_ARRAY, gsl_vector, 2, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_swap(arg1,arg2);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    assert(_PyVector2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector2));\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyVector1);\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyVector2);\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyVector1);\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyVector2);\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_swap_elements(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector *arg1 = (gsl_vector *) 0 ;\n  size_t arg2 ;\n  size_t arg3 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  size_t val3 ;\n  int ecode3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"i\",(char *) \"j\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_vector_swap_elements\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_IO_ARRAY, gsl_vector, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_vector_swap_elements\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  ecode3 = SWIG_AsVal_size_t(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_vector_swap_elements\" \"', argument \" \"3\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg3 = (size_t)(val3);\n  result = (int)gsl_vector_swap_elements(arg1,arg2,arg3);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyVector1);\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyVector1);\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_max(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector *arg1 = (gsl_vector *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  double result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_max\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (double)gsl_vector_max((gsl_vector const *)arg1);\n  resultobj = SWIG_From_double((double)(result));\n  {\n    Py_XDECREF(_PyVector1);\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyVector1);\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_min(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector *arg1 = (gsl_vector *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  double result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_min\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (double)gsl_vector_min((gsl_vector const *)arg1);\n  resultobj = SWIG_From_double((double)(result));\n  {\n    Py_XDECREF(_PyVector1);\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyVector1);\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_minmax(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector *arg1 = (gsl_vector *) 0 ;\n  double *arg2 = (double *) 0 ;\n  double *arg3 = (double *) 0 ;\n  double temp2 ;\n  int res2 = SWIG_TMPOBJ ;\n  double temp3 ;\n  int res3 = SWIG_TMPOBJ ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector _vector1;\n  \n  arg2 = &temp2;\n  arg3 = &temp3;\n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_minmax\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  gsl_vector_minmax((gsl_vector const *)arg1,arg2,arg3);\n  resultobj = SWIG_Py_Void();\n  if (SWIG_IsTmpObj(res2)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg2)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res2) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg2), SWIGTYPE_p_double, new_flags));\n  }\n  if (SWIG_IsTmpObj(res3)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg3)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res3) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg3), SWIGTYPE_p_double, new_flags));\n  }\n  {\n    Py_XDECREF(_PyVector1);\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyVector1);\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_max_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector *arg1 = (gsl_vector *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  size_t result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_max_index\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (size_t)gsl_vector_max_index((gsl_vector const *)arg1);\n  resultobj = SWIG_From_size_t((size_t)(result));\n  {\n    Py_XDECREF(_PyVector1);\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyVector1);\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_min_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector *arg1 = (gsl_vector *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  size_t result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_min_index\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (size_t)gsl_vector_min_index((gsl_vector const *)arg1);\n  resultobj = SWIG_From_size_t((size_t)(result));\n  {\n    Py_XDECREF(_PyVector1);\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyVector1);\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_minmax_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector *arg1 = (gsl_vector *) 0 ;\n  size_t *arg2 = (size_t *) 0 ;\n  size_t *arg3 = (size_t *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector _vector1;\n  \n  \n  size_t _size_t_temp2;\n  \n  \n  size_t _size_t_temp3;\n  \n  \n  {\n    _size_t_temp2 = 0;\n    arg2 = &_size_t_temp2;\n  }\n  \n  \n  {\n    _size_t_temp3 = 0;\n    arg3 = &_size_t_temp3;\n  }\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_minmax_index\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  gsl_vector_minmax_index((gsl_vector const *)arg1,arg2,arg3);\n  resultobj = SWIG_Py_Void();\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg2));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg3));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    Py_XDECREF(_PyVector1);\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyVector1);\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_isnull(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector *arg1 = (gsl_vector *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_isnull\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_isnull((gsl_vector const *)arg1);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    Py_XDECREF(_PyVector1);\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyVector1);\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_set_zero(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix *arg1 = (gsl_matrix *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_set_zero\",kwnames,&obj0)) SWIG_fail;\n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix, 1, &stride) !=GSL_SUCCESS)\n    goto fail;\n  }\n  gsl_matrix_set_zero(arg1);\n  resultobj = SWIG_Py_Void();\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_set_all(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix *arg1 = (gsl_matrix *) 0 ;\n  double arg2 ;\n  double val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\",(char *) \"x\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_set_all\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix, 1, &stride) !=GSL_SUCCESS)\n    goto fail;\n  }\n  ecode2 = SWIG_AsVal_double(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_set_all\" \"', argument \" \"2\"\" of type '\" \"double\"\"'\");\n  } \n  arg2 = (double)(val2);\n  gsl_matrix_set_all(arg1,arg2);\n  resultobj = SWIG_Py_Void();\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_set_identity(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix *arg1 = (gsl_matrix *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_set_identity\",kwnames,&obj0)) SWIG_fail;\n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix, 1, &stride) !=GSL_SUCCESS)\n    goto fail;\n  }\n  gsl_matrix_set_identity(arg1);\n  resultobj = SWIG_Py_Void();\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_fread(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_matrix *arg2 = (gsl_matrix *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN_SIZE_OUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix2 = NULL;\n  TYPE_VIEW_gsl_matrix _matrix2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_fread\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_GENERATE(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_OUTPUT_ARRAY, gsl_matrix, 2, &stride) !=GSL_SUCCESS)\n    goto fail;\n  }\n  result = (int)gsl_matrix_fread(arg1,arg2);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  {\n    assert((PyObject *) _PyMatrix2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix2));\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_fwrite(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_matrix *arg2 = (gsl_matrix *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix2 = NULL;\n  TYPE_VIEW_gsl_matrix _matrix2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_fwrite\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2,\n        PyGSL_INPUT_ARRAY, gsl_matrix, 2, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (int)gsl_matrix_fwrite(arg1,(gsl_matrix const *)arg2);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_fscanf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_matrix *arg2 = (gsl_matrix *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN_SIZE_OUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix2 = NULL;\n  TYPE_VIEW_gsl_matrix _matrix2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_fscanf\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_GENERATE(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_OUTPUT_ARRAY, gsl_matrix, 2, &stride) !=GSL_SUCCESS)\n    goto fail;\n  }\n  result = (int)gsl_matrix_fscanf(arg1,arg2);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  {\n    assert((PyObject *) _PyMatrix2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix2));\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_fprintf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_matrix *arg2 = (gsl_matrix *) 0 ;\n  char *arg3 = (char *) 0 ;\n  int res3 ;\n  char *buf3 = 0 ;\n  int alloc3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN\",(char *) \"format\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix2 = NULL;\n  TYPE_VIEW_gsl_matrix _matrix2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_matrix_fprintf\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2,\n        PyGSL_INPUT_ARRAY, gsl_matrix, 2, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3);\n  if (!SWIG_IsOK(res3)) {\n    SWIG_exception_fail(SWIG_ArgError(res3), \"in method '\" \"gsl_matrix_fprintf\" \"', argument \" \"3\"\" of type '\" \"char const *\"\"'\");\n  }\n  arg3 = (char *)(buf3);\n  result = (int)gsl_matrix_fprintf(arg1,(gsl_matrix const *)arg2,(char const *)arg3);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  if (alloc3 == SWIG_NEWOBJ) free((char*)buf3);\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  if (alloc3 == SWIG_NEWOBJ) free((char*)buf3);\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_swap(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix *arg1 = (gsl_matrix *) 0 ;\n  gsl_matrix *arg2 = (gsl_matrix *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"INOUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix _matrix1;\n  \n  \n  PyArrayObject * _PyMatrix2 = NULL;\n  TYPE_VIEW_gsl_matrix _matrix2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_swap\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_IO_ARRAY, gsl_matrix, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2,\n        PyGSL_IO_ARRAY, gsl_matrix, 2, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (int)gsl_matrix_swap(arg1,arg2);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    assert((PyObject *) _PyMatrix2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix2));\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_swap_rows(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix *arg1 = (gsl_matrix *) 0 ;\n  size_t arg2 ;\n  size_t arg3 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  size_t val3 ;\n  int ecode3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"i\",(char *) \"j\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_matrix_swap_rows\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_IO_ARRAY, gsl_matrix, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_swap_rows\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  ecode3 = SWIG_AsVal_size_t(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_matrix_swap_rows\" \"', argument \" \"3\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg3 = (size_t)(val3);\n  result = (int)gsl_matrix_swap_rows(arg1,arg2,arg3);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_swap_columns(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix *arg1 = (gsl_matrix *) 0 ;\n  size_t arg2 ;\n  size_t arg3 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  size_t val3 ;\n  int ecode3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"i\",(char *) \"j\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_matrix_swap_columns\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_IO_ARRAY, gsl_matrix, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_swap_columns\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  ecode3 = SWIG_AsVal_size_t(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_matrix_swap_columns\" \"', argument \" \"3\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg3 = (size_t)(val3);\n  result = (int)gsl_matrix_swap_columns(arg1,arg2,arg3);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_swap_rowcol(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix *arg1 = (gsl_matrix *) 0 ;\n  size_t arg2 ;\n  size_t arg3 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  size_t val3 ;\n  int ecode3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"i\",(char *) \"j\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_matrix_swap_rowcol\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_IO_ARRAY, gsl_matrix, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_swap_rowcol\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  ecode3 = SWIG_AsVal_size_t(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_matrix_swap_rowcol\" \"', argument \" \"3\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg3 = (size_t)(val3);\n  result = (int)gsl_matrix_swap_rowcol(arg1,arg2,arg3);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_transpose(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix *arg1 = (gsl_matrix *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_transpose\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_IO_ARRAY, gsl_matrix, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (int)gsl_matrix_transpose(arg1);\n  {\n    resultobj = PyGSL_ERROR_FLAG_TO_PYINT(result);\n    if (resultobj == NULL){\n      PyGSL_add_traceback(pygsl_module_for_error_treatment, \"typemaps/gsl_error_typemap.i\", \n        __FUNCTION__, 48);\n      goto fail;\n    }\n  }\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_max(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix *arg1 = (gsl_matrix *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  double result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_max\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (double)gsl_matrix_max((gsl_matrix const *)arg1);\n  resultobj = SWIG_From_double((double)(result));\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_min(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix *arg1 = (gsl_matrix *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  double result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_min\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (double)gsl_matrix_min((gsl_matrix const *)arg1);\n  resultobj = SWIG_From_double((double)(result));\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_minmax(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix *arg1 = (gsl_matrix *) 0 ;\n  double *arg2 = (double *) 0 ;\n  double *arg3 = (double *) 0 ;\n  double temp2 ;\n  int res2 = SWIG_TMPOBJ ;\n  double temp3 ;\n  int res3 = SWIG_TMPOBJ ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix _matrix1;\n  \n  arg2 = &temp2;\n  arg3 = &temp3;\n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_minmax\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  gsl_matrix_minmax((gsl_matrix const *)arg1,arg2,arg3);\n  resultobj = SWIG_Py_Void();\n  if (SWIG_IsTmpObj(res2)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg2)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res2) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg2), SWIGTYPE_p_double, new_flags));\n  }\n  if (SWIG_IsTmpObj(res3)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg3)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res3) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg3), SWIGTYPE_p_double, new_flags));\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_max_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix *arg1 = (gsl_matrix *) 0 ;\n  size_t *arg2 = (size_t *) 0 ;\n  size_t *arg3 = (size_t *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix _matrix1;\n  \n  \n  size_t _size_t_temp2;\n  \n  \n  size_t _size_t_temp3;\n  \n  \n  {\n    _size_t_temp2 = 0;\n    arg2 = &_size_t_temp2;\n  }\n  \n  \n  {\n    _size_t_temp3 = 0;\n    arg3 = &_size_t_temp3;\n  }\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_max_index\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  gsl_matrix_max_index((gsl_matrix const *)arg1,arg2,arg3);\n  resultobj = SWIG_Py_Void();\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg2));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg3));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_min_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix *arg1 = (gsl_matrix *) 0 ;\n  size_t *arg2 = (size_t *) 0 ;\n  size_t *arg3 = (size_t *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix _matrix1;\n  \n  \n  size_t _size_t_temp2;\n  \n  \n  size_t _size_t_temp3;\n  \n  \n  {\n    _size_t_temp2 = 0;\n    arg2 = &_size_t_temp2;\n  }\n  \n  \n  {\n    _size_t_temp3 = 0;\n    arg3 = &_size_t_temp3;\n  }\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_min_index\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  gsl_matrix_min_index((gsl_matrix const *)arg1,arg2,arg3);\n  resultobj = SWIG_Py_Void();\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg2));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg3));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_minmax_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix *arg1 = (gsl_matrix *) 0 ;\n  size_t *arg2 = (size_t *) 0 ;\n  size_t *arg3 = (size_t *) 0 ;\n  size_t *arg4 = (size_t *) 0 ;\n  size_t *arg5 = (size_t *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix _matrix1;\n  \n  \n  size_t _size_t_temp2;\n  \n  \n  size_t _size_t_temp3;\n  \n  \n  size_t _size_t_temp4;\n  \n  \n  size_t _size_t_temp5;\n  \n  \n  {\n    _size_t_temp2 = 0;\n    arg2 = &_size_t_temp2;\n  }\n  \n  \n  {\n    _size_t_temp3 = 0;\n    arg3 = &_size_t_temp3;\n  }\n  \n  \n  {\n    _size_t_temp4 = 0;\n    arg4 = &_size_t_temp4;\n  }\n  \n  \n  {\n    _size_t_temp5 = 0;\n    arg5 = &_size_t_temp5;\n  }\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_minmax_index\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  gsl_matrix_minmax_index((gsl_matrix const *)arg1,arg2,arg3,arg4,arg5);\n  resultobj = SWIG_Py_Void();\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg2));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg3));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg4));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg5));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_isnull(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix *arg1 = (gsl_matrix *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_isnull\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (int)gsl_matrix_isnull((gsl_matrix const *)arg1);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_diagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix *arg1 = (gsl_matrix *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  gsl_vector_view result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_diagonal\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = gsl_matrix_diagonal(arg1);\n  {\n    PyArrayObject * out = NULL; \n    gsl_vector_view vectmp; \n    PyGSL_array_index_t tmp;\n    if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_view, vectmp, tmp) != GSL_SUCCESS){\n      goto fail;\n    }\n    resultobj = PyGSL_array_return(out);\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_subdiagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix *arg1 = (gsl_matrix *) 0 ;\n  size_t arg2 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\",(char *) \"k\", NULL \n  };\n  gsl_vector_view result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_subdiagonal\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_subdiagonal\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  result = gsl_matrix_subdiagonal(arg1,arg2);\n  {\n    PyArrayObject * out = NULL; \n    gsl_vector_view vectmp; \n    PyGSL_array_index_t tmp;\n    if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_view, vectmp, tmp) != GSL_SUCCESS){\n      goto fail;\n    }\n    resultobj = PyGSL_array_return(out);\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_superdiagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix *arg1 = (gsl_matrix *) 0 ;\n  size_t arg2 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\",(char *) \"k\", NULL \n  };\n  gsl_vector_view result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_superdiagonal\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_superdiagonal\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  result = gsl_matrix_superdiagonal(arg1,arg2);\n  {\n    PyArrayObject * out = NULL; \n    gsl_vector_view vectmp; \n    PyGSL_array_index_t tmp;\n    if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_view, vectmp, tmp) != GSL_SUCCESS){\n      goto fail;\n    }\n    resultobj = PyGSL_array_return(out);\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_float_set_zero(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_float *arg1 = (gsl_vector_float *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\", NULL \n  };\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_float _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_float_set_zero\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    int flag;\n    _vector1.vector.data = NULL;\n    flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1,\n      PyGSL_OUTPUT_ARRAY, gsl_vector_float, 1, &stride);\n    if (flag != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  gsl_vector_float_set_zero(arg1);\n  resultobj = SWIG_Py_Void();\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_float_set_all(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_float *arg1 = (gsl_vector_float *) 0 ;\n  float arg2 ;\n  float val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\",(char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_float _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_float_set_all\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    int flag;\n    _vector1.vector.data = NULL;\n    flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1,\n      PyGSL_OUTPUT_ARRAY, gsl_vector_float, 1, &stride);\n    if (flag != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  ecode2 = SWIG_AsVal_float(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_vector_float_set_all\" \"', argument \" \"2\"\" of type '\" \"float\"\"'\");\n  } \n  arg2 = (float)(val2);\n  gsl_vector_float_set_all(arg1,arg2);\n  resultobj = SWIG_Py_Void();\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_float_set_basis(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_float *arg1 = (gsl_vector_float *) 0 ;\n  size_t arg2 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\",(char *) \"i\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_float _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_float_set_basis\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    int flag;\n    _vector1.vector.data = NULL;\n    flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1,\n      PyGSL_OUTPUT_ARRAY, gsl_vector_float, 1, &stride);\n    if (flag != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_vector_float_set_basis\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  result = (int)gsl_vector_float_set_basis(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_float_fread(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_vector_float *arg2 = (gsl_vector_float *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN_SIZE_OUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector_float _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_float_fread\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride;\n    int flag;\n    _vector2.vector.data = NULL;\n    flag = PyGSL_VECTOR_GENERATE(obj1, arg2, _PyVector2, _vector2,\n      PyGSL_OUTPUT_ARRAY, gsl_vector_float, 2, &stride);\n    if (flag != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_float_fread(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert(_PyVector2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector2));\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_float_fwrite(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_vector_float *arg2 = (gsl_vector_float *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector_float _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_float_fwrite\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2,\n        PyGSL_INPUT_ARRAY, gsl_vector_float, 2, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_float_fwrite(arg1,(gsl_vector_float const *)arg2);\n  resultobj = SWIG_From_int((int)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_float_fscanf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_vector_float *arg2 = (gsl_vector_float *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN_SIZE_OUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector_float _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_float_fscanf\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride;\n    int flag;\n    _vector2.vector.data = NULL;\n    flag = PyGSL_VECTOR_GENERATE(obj1, arg2, _PyVector2, _vector2,\n      PyGSL_OUTPUT_ARRAY, gsl_vector_float, 2, &stride);\n    if (flag != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_float_fscanf(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert(_PyVector2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector2));\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_float_fprintf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_vector_float *arg2 = (gsl_vector_float *) 0 ;\n  char *arg3 = (char *) 0 ;\n  int res3 ;\n  char *buf3 = 0 ;\n  int alloc3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN\",(char *) \"format\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector_float _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_vector_float_fprintf\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2,\n        PyGSL_INPUT_ARRAY, gsl_vector_float, 2, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3);\n  if (!SWIG_IsOK(res3)) {\n    SWIG_exception_fail(SWIG_ArgError(res3), \"in method '\" \"gsl_vector_float_fprintf\" \"', argument \" \"3\"\" of type '\" \"char const *\"\"'\");\n  }\n  arg3 = (char *)(buf3);\n  result = (int)gsl_vector_float_fprintf(arg1,(gsl_vector_float const *)arg2,(char const *)arg3);\n  resultobj = SWIG_From_int((int)(result));\n  if (alloc3 == SWIG_NEWOBJ) free((char*)buf3);\n  return resultobj;\nfail:\n  if (alloc3 == SWIG_NEWOBJ) free((char*)buf3);\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_float_reverse(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_float *arg1 = (gsl_vector_float *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_float _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_float_reverse\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_IO_ARRAY, gsl_vector_float, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_float_reverse(arg1);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_float_swap(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_float *arg1 = (gsl_vector_float *) 0 ;\n  gsl_vector_float *arg2 = (gsl_vector_float *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"INOUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_float _vector1;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector_float _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_float_swap\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_IO_ARRAY, gsl_vector_float, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2,\n        PyGSL_IO_ARRAY, gsl_vector_float, 2, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_float_swap(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    assert(_PyVector2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector2));\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_float_swap_elements(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_float *arg1 = (gsl_vector_float *) 0 ;\n  size_t arg2 ;\n  size_t arg3 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  size_t val3 ;\n  int ecode3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"i\",(char *) \"j\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_float _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_vector_float_swap_elements\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_IO_ARRAY, gsl_vector_float, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_vector_float_swap_elements\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  ecode3 = SWIG_AsVal_size_t(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_vector_float_swap_elements\" \"', argument \" \"3\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg3 = (size_t)(val3);\n  result = (int)gsl_vector_float_swap_elements(arg1,arg2,arg3);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_float_max(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_float *arg1 = (gsl_vector_float *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  double result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_float _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_float_max\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector_float, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (double)gsl_vector_float_max((gsl_vector_float const *)arg1);\n  resultobj = SWIG_From_double((double)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_float_min(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_float *arg1 = (gsl_vector_float *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  double result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_float _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_float_min\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector_float, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (double)gsl_vector_float_min((gsl_vector_float const *)arg1);\n  resultobj = SWIG_From_double((double)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_float_minmax(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_float *arg1 = (gsl_vector_float *) 0 ;\n  float *arg2 = (float *) 0 ;\n  float *arg3 = (float *) 0 ;\n  float temp2 ;\n  int res2 = SWIG_TMPOBJ ;\n  float temp3 ;\n  int res3 = SWIG_TMPOBJ ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_float _vector1;\n  \n  arg2 = &temp2;\n  arg3 = &temp3;\n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_float_minmax\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector_float, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  gsl_vector_float_minmax((gsl_vector_float const *)arg1,arg2,arg3);\n  resultobj = SWIG_Py_Void();\n  if (SWIG_IsTmpObj(res2)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_float((*arg2)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res2) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg2), SWIGTYPE_p_float, new_flags));\n  }\n  if (SWIG_IsTmpObj(res3)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_float((*arg3)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res3) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg3), SWIGTYPE_p_float, new_flags));\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_float_max_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_float *arg1 = (gsl_vector_float *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  size_t result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_float _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_float_max_index\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector_float, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (size_t)gsl_vector_float_max_index((gsl_vector_float const *)arg1);\n  resultobj = SWIG_From_size_t((size_t)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_float_min_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_float *arg1 = (gsl_vector_float *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  size_t result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_float _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_float_min_index\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector_float, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (size_t)gsl_vector_float_min_index((gsl_vector_float const *)arg1);\n  resultobj = SWIG_From_size_t((size_t)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_float_minmax_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_float *arg1 = (gsl_vector_float *) 0 ;\n  size_t *arg2 = (size_t *) 0 ;\n  size_t *arg3 = (size_t *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_float _vector1;\n  \n  \n  size_t _size_t_temp2;\n  \n  \n  size_t _size_t_temp3;\n  \n  \n  {\n    _size_t_temp2 = 0;\n    arg2 = &_size_t_temp2;\n  }\n  \n  \n  {\n    _size_t_temp3 = 0;\n    arg3 = &_size_t_temp3;\n  }\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_float_minmax_index\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector_float, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  gsl_vector_float_minmax_index((gsl_vector_float const *)arg1,arg2,arg3);\n  resultobj = SWIG_Py_Void();\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg2));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg3));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_float_isnull(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_float *arg1 = (gsl_vector_float *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_float _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_float_isnull\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector_float, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_float_isnull((gsl_vector_float const *)arg1);\n  resultobj = SWIG_From_int((int)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_float_set_zero(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_float *arg1 = (gsl_matrix_float *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_float _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_float_set_zero\",kwnames,&obj0)) SWIG_fail;\n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix_float, 1, &stride) !=GSL_SUCCESS)\n    goto fail;\n  }\n  gsl_matrix_float_set_zero(arg1);\n  resultobj = SWIG_Py_Void();\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_float_set_all(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_float *arg1 = (gsl_matrix_float *) 0 ;\n  float arg2 ;\n  float val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\",(char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_float _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_float_set_all\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix_float, 1, &stride) !=GSL_SUCCESS)\n    goto fail;\n  }\n  ecode2 = SWIG_AsVal_float(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_float_set_all\" \"', argument \" \"2\"\" of type '\" \"float\"\"'\");\n  } \n  arg2 = (float)(val2);\n  gsl_matrix_float_set_all(arg1,arg2);\n  resultobj = SWIG_Py_Void();\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_float_set_identity(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_float *arg1 = (gsl_matrix_float *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_float _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_float_set_identity\",kwnames,&obj0)) SWIG_fail;\n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix_float, 1, &stride) !=GSL_SUCCESS)\n    goto fail;\n  }\n  gsl_matrix_float_set_identity(arg1);\n  resultobj = SWIG_Py_Void();\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_float_fread(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_matrix_float *arg2 = (gsl_matrix_float *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN_SIZE_OUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix2 = NULL;\n  TYPE_VIEW_gsl_matrix_float _matrix2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_float_fread\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_GENERATE(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_OUTPUT_ARRAY, gsl_matrix_float, 2, &stride) !=GSL_SUCCESS)\n    goto fail;\n  }\n  result = (int)gsl_matrix_float_fread(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix2));\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_float_fwrite(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_matrix_float *arg2 = (gsl_matrix_float *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix2 = NULL;\n  TYPE_VIEW_gsl_matrix_float _matrix2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_float_fwrite\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2,\n        PyGSL_INPUT_ARRAY, gsl_matrix_float, 2, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (int)gsl_matrix_float_fwrite(arg1,(gsl_matrix_float const *)arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_float_fscanf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_matrix_float *arg2 = (gsl_matrix_float *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN_SIZE_OUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix2 = NULL;\n  TYPE_VIEW_gsl_matrix_float _matrix2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_float_fscanf\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_GENERATE(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_OUTPUT_ARRAY, gsl_matrix_float, 2, &stride) !=GSL_SUCCESS)\n    goto fail;\n  }\n  result = (int)gsl_matrix_float_fscanf(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix2));\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_float_fprintf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_matrix_float *arg2 = (gsl_matrix_float *) 0 ;\n  char *arg3 = (char *) 0 ;\n  int res3 ;\n  char *buf3 = 0 ;\n  int alloc3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN\",(char *) \"format\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix2 = NULL;\n  TYPE_VIEW_gsl_matrix_float _matrix2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_matrix_float_fprintf\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2,\n        PyGSL_INPUT_ARRAY, gsl_matrix_float, 2, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3);\n  if (!SWIG_IsOK(res3)) {\n    SWIG_exception_fail(SWIG_ArgError(res3), \"in method '\" \"gsl_matrix_float_fprintf\" \"', argument \" \"3\"\" of type '\" \"char const *\"\"'\");\n  }\n  arg3 = (char *)(buf3);\n  result = (int)gsl_matrix_float_fprintf(arg1,(gsl_matrix_float const *)arg2,(char const *)arg3);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  if (alloc3 == SWIG_NEWOBJ) free((char*)buf3);\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  if (alloc3 == SWIG_NEWOBJ) free((char*)buf3);\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_float_swap(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_float *arg1 = (gsl_matrix_float *) 0 ;\n  gsl_matrix_float *arg2 = (gsl_matrix_float *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"INOUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_float _matrix1;\n  \n  \n  PyArrayObject * _PyMatrix2 = NULL;\n  TYPE_VIEW_gsl_matrix_float _matrix2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_float_swap\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_IO_ARRAY, gsl_matrix_float, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2,\n        PyGSL_IO_ARRAY, gsl_matrix_float, 2, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (int)gsl_matrix_float_swap(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    assert((PyObject *) _PyMatrix2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix2));\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_float_swap_rows(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_float *arg1 = (gsl_matrix_float *) 0 ;\n  size_t arg2 ;\n  size_t arg3 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  size_t val3 ;\n  int ecode3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"i\",(char *) \"j\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_float _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_matrix_float_swap_rows\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_IO_ARRAY, gsl_matrix_float, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_float_swap_rows\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  ecode3 = SWIG_AsVal_size_t(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_matrix_float_swap_rows\" \"', argument \" \"3\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg3 = (size_t)(val3);\n  result = (int)gsl_matrix_float_swap_rows(arg1,arg2,arg3);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_float_swap_columns(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_float *arg1 = (gsl_matrix_float *) 0 ;\n  size_t arg2 ;\n  size_t arg3 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  size_t val3 ;\n  int ecode3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"i\",(char *) \"j\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_float _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_matrix_float_swap_columns\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_IO_ARRAY, gsl_matrix_float, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_float_swap_columns\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  ecode3 = SWIG_AsVal_size_t(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_matrix_float_swap_columns\" \"', argument \" \"3\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg3 = (size_t)(val3);\n  result = (int)gsl_matrix_float_swap_columns(arg1,arg2,arg3);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_float_swap_rowcol(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_float *arg1 = (gsl_matrix_float *) 0 ;\n  size_t arg2 ;\n  size_t arg3 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  size_t val3 ;\n  int ecode3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"i\",(char *) \"j\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_float _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_matrix_float_swap_rowcol\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_IO_ARRAY, gsl_matrix_float, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_float_swap_rowcol\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  ecode3 = SWIG_AsVal_size_t(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_matrix_float_swap_rowcol\" \"', argument \" \"3\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg3 = (size_t)(val3);\n  result = (int)gsl_matrix_float_swap_rowcol(arg1,arg2,arg3);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_float_transpose(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_float *arg1 = (gsl_matrix_float *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_float _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_float_transpose\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_IO_ARRAY, gsl_matrix_float, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (int)gsl_matrix_float_transpose(arg1);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_float_max(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_float *arg1 = (gsl_matrix_float *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  double result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_float _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_float_max\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_float, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (double)gsl_matrix_float_max((gsl_matrix_float const *)arg1);\n  resultobj = SWIG_From_double((double)(result));\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_float_min(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_float *arg1 = (gsl_matrix_float *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  double result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_float _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_float_min\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_float, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (double)gsl_matrix_float_min((gsl_matrix_float const *)arg1);\n  resultobj = SWIG_From_double((double)(result));\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_float_minmax(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_float *arg1 = (gsl_matrix_float *) 0 ;\n  float *arg2 = (float *) 0 ;\n  float *arg3 = (float *) 0 ;\n  float temp2 ;\n  int res2 = SWIG_TMPOBJ ;\n  float temp3 ;\n  int res3 = SWIG_TMPOBJ ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_float _matrix1;\n  \n  arg2 = &temp2;\n  arg3 = &temp3;\n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_float_minmax\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_float, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  gsl_matrix_float_minmax((gsl_matrix_float const *)arg1,arg2,arg3);\n  resultobj = SWIG_Py_Void();\n  if (SWIG_IsTmpObj(res2)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_float((*arg2)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res2) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg2), SWIGTYPE_p_float, new_flags));\n  }\n  if (SWIG_IsTmpObj(res3)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_float((*arg3)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res3) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg3), SWIGTYPE_p_float, new_flags));\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_float_max_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_float *arg1 = (gsl_matrix_float *) 0 ;\n  size_t *arg2 = (size_t *) 0 ;\n  size_t *arg3 = (size_t *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_float _matrix1;\n  \n  \n  size_t _size_t_temp2;\n  \n  \n  size_t _size_t_temp3;\n  \n  \n  {\n    _size_t_temp2 = 0;\n    arg2 = &_size_t_temp2;\n  }\n  \n  \n  {\n    _size_t_temp3 = 0;\n    arg3 = &_size_t_temp3;\n  }\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_float_max_index\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_float, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  gsl_matrix_float_max_index((gsl_matrix_float const *)arg1,arg2,arg3);\n  resultobj = SWIG_Py_Void();\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg2));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg3));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_float_min_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_float *arg1 = (gsl_matrix_float *) 0 ;\n  size_t *arg2 = (size_t *) 0 ;\n  size_t *arg3 = (size_t *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_float _matrix1;\n  \n  \n  size_t _size_t_temp2;\n  \n  \n  size_t _size_t_temp3;\n  \n  \n  {\n    _size_t_temp2 = 0;\n    arg2 = &_size_t_temp2;\n  }\n  \n  \n  {\n    _size_t_temp3 = 0;\n    arg3 = &_size_t_temp3;\n  }\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_float_min_index\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_float, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  gsl_matrix_float_min_index((gsl_matrix_float const *)arg1,arg2,arg3);\n  resultobj = SWIG_Py_Void();\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg2));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg3));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_float_minmax_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_float *arg1 = (gsl_matrix_float *) 0 ;\n  size_t *arg2 = (size_t *) 0 ;\n  size_t *arg3 = (size_t *) 0 ;\n  size_t *arg4 = (size_t *) 0 ;\n  size_t *arg5 = (size_t *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_float _matrix1;\n  \n  \n  size_t _size_t_temp2;\n  \n  \n  size_t _size_t_temp3;\n  \n  \n  size_t _size_t_temp4;\n  \n  \n  size_t _size_t_temp5;\n  \n  \n  {\n    _size_t_temp2 = 0;\n    arg2 = &_size_t_temp2;\n  }\n  \n  \n  {\n    _size_t_temp3 = 0;\n    arg3 = &_size_t_temp3;\n  }\n  \n  \n  {\n    _size_t_temp4 = 0;\n    arg4 = &_size_t_temp4;\n  }\n  \n  \n  {\n    _size_t_temp5 = 0;\n    arg5 = &_size_t_temp5;\n  }\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_float_minmax_index\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_float, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  gsl_matrix_float_minmax_index((gsl_matrix_float const *)arg1,arg2,arg3,arg4,arg5);\n  resultobj = SWIG_Py_Void();\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg2));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg3));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg4));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg5));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_float_isnull(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_float *arg1 = (gsl_matrix_float *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_float _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_float_isnull\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_float, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (int)gsl_matrix_float_isnull((gsl_matrix_float const *)arg1);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_float_diagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_float *arg1 = (gsl_matrix_float *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  gsl_vector_float_view result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_float _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_float_diagonal\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_float, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = gsl_matrix_float_diagonal(arg1);\n  {\n    PyArrayObject * out = NULL; \n    gsl_vector_float_view vectmp; \n    PyGSL_array_index_t tmp;\n    if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_float_view, vectmp, tmp) != GSL_SUCCESS){\n      goto fail;\n    }\n    resultobj = PyGSL_array_return(out);\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_float_subdiagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_float *arg1 = (gsl_matrix_float *) 0 ;\n  size_t arg2 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\",(char *) \"k\", NULL \n  };\n  gsl_vector_float_view result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_float _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_float_subdiagonal\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_float, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_float_subdiagonal\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  result = gsl_matrix_float_subdiagonal(arg1,arg2);\n  {\n    PyArrayObject * out = NULL; \n    gsl_vector_float_view vectmp; \n    PyGSL_array_index_t tmp;\n    if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_float_view, vectmp, tmp) != GSL_SUCCESS){\n      goto fail;\n    }\n    resultobj = PyGSL_array_return(out);\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_float_superdiagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_float *arg1 = (gsl_matrix_float *) 0 ;\n  size_t arg2 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\",(char *) \"k\", NULL \n  };\n  gsl_vector_float_view result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_float _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_float_superdiagonal\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_float, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_float_superdiagonal\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  result = gsl_matrix_float_superdiagonal(arg1,arg2);\n  {\n    PyArrayObject * out = NULL; \n    gsl_vector_float_view vectmp; \n    PyGSL_array_index_t tmp;\n    if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_float_view, vectmp, tmp) != GSL_SUCCESS){\n      goto fail;\n    }\n    resultobj = PyGSL_array_return(out);\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_long_set_zero(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_long *arg1 = (gsl_vector_long *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\", NULL \n  };\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_long _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_long_set_zero\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    int flag;\n    _vector1.vector.data = NULL;\n    flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1,\n      PyGSL_OUTPUT_ARRAY, gsl_vector_long, 1, &stride);\n    if (flag != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  gsl_vector_long_set_zero(arg1);\n  resultobj = SWIG_Py_Void();\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_long_set_all(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_long *arg1 = (gsl_vector_long *) 0 ;\n  long arg2 ;\n  long val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\",(char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_long _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_long_set_all\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    int flag;\n    _vector1.vector.data = NULL;\n    flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1,\n      PyGSL_OUTPUT_ARRAY, gsl_vector_long, 1, &stride);\n    if (flag != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  ecode2 = SWIG_AsVal_long(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_vector_long_set_all\" \"', argument \" \"2\"\" of type '\" \"long\"\"'\");\n  } \n  arg2 = (long)(val2);\n  gsl_vector_long_set_all(arg1,arg2);\n  resultobj = SWIG_Py_Void();\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_long_set_basis(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_long *arg1 = (gsl_vector_long *) 0 ;\n  size_t arg2 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\",(char *) \"i\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_long _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_long_set_basis\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    int flag;\n    _vector1.vector.data = NULL;\n    flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1,\n      PyGSL_OUTPUT_ARRAY, gsl_vector_long, 1, &stride);\n    if (flag != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_vector_long_set_basis\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  result = (int)gsl_vector_long_set_basis(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_long_fread(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_vector_long *arg2 = (gsl_vector_long *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN_SIZE_OUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector_long _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_long_fread\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride;\n    int flag;\n    _vector2.vector.data = NULL;\n    flag = PyGSL_VECTOR_GENERATE(obj1, arg2, _PyVector2, _vector2,\n      PyGSL_OUTPUT_ARRAY, gsl_vector_long, 2, &stride);\n    if (flag != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_long_fread(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert(_PyVector2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector2));\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_long_fwrite(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_vector_long *arg2 = (gsl_vector_long *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector_long _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_long_fwrite\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2,\n        PyGSL_INPUT_ARRAY, gsl_vector_long, 2, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_long_fwrite(arg1,(gsl_vector_long const *)arg2);\n  resultobj = SWIG_From_int((int)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_long_fscanf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_vector_long *arg2 = (gsl_vector_long *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN_SIZE_OUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector_long _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_long_fscanf\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride;\n    int flag;\n    _vector2.vector.data = NULL;\n    flag = PyGSL_VECTOR_GENERATE(obj1, arg2, _PyVector2, _vector2,\n      PyGSL_OUTPUT_ARRAY, gsl_vector_long, 2, &stride);\n    if (flag != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_long_fscanf(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert(_PyVector2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector2));\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_long_fprintf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_vector_long *arg2 = (gsl_vector_long *) 0 ;\n  char *arg3 = (char *) 0 ;\n  int res3 ;\n  char *buf3 = 0 ;\n  int alloc3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN\",(char *) \"format\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector_long _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_vector_long_fprintf\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2,\n        PyGSL_INPUT_ARRAY, gsl_vector_long, 2, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3);\n  if (!SWIG_IsOK(res3)) {\n    SWIG_exception_fail(SWIG_ArgError(res3), \"in method '\" \"gsl_vector_long_fprintf\" \"', argument \" \"3\"\" of type '\" \"char const *\"\"'\");\n  }\n  arg3 = (char *)(buf3);\n  result = (int)gsl_vector_long_fprintf(arg1,(gsl_vector_long const *)arg2,(char const *)arg3);\n  resultobj = SWIG_From_int((int)(result));\n  if (alloc3 == SWIG_NEWOBJ) free((char*)buf3);\n  return resultobj;\nfail:\n  if (alloc3 == SWIG_NEWOBJ) free((char*)buf3);\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_long_reverse(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_long *arg1 = (gsl_vector_long *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_long _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_long_reverse\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_IO_ARRAY, gsl_vector_long, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_long_reverse(arg1);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_long_swap(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_long *arg1 = (gsl_vector_long *) 0 ;\n  gsl_vector_long *arg2 = (gsl_vector_long *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"INOUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_long _vector1;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector_long _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_long_swap\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_IO_ARRAY, gsl_vector_long, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2,\n        PyGSL_IO_ARRAY, gsl_vector_long, 2, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_long_swap(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    assert(_PyVector2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector2));\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_long_swap_elements(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_long *arg1 = (gsl_vector_long *) 0 ;\n  size_t arg2 ;\n  size_t arg3 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  size_t val3 ;\n  int ecode3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"i\",(char *) \"j\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_long _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_vector_long_swap_elements\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_IO_ARRAY, gsl_vector_long, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_vector_long_swap_elements\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  ecode3 = SWIG_AsVal_size_t(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_vector_long_swap_elements\" \"', argument \" \"3\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg3 = (size_t)(val3);\n  result = (int)gsl_vector_long_swap_elements(arg1,arg2,arg3);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_long_max(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_long *arg1 = (gsl_vector_long *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  double result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_long _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_long_max\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector_long, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (double)gsl_vector_long_max((gsl_vector_long const *)arg1);\n  resultobj = SWIG_From_double((double)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_long_min(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_long *arg1 = (gsl_vector_long *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  double result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_long _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_long_min\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector_long, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (double)gsl_vector_long_min((gsl_vector_long const *)arg1);\n  resultobj = SWIG_From_double((double)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_long_minmax(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_long *arg1 = (gsl_vector_long *) 0 ;\n  long *arg2 = (long *) 0 ;\n  long *arg3 = (long *) 0 ;\n  long temp2 ;\n  int res2 = SWIG_TMPOBJ ;\n  long temp3 ;\n  int res3 = SWIG_TMPOBJ ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_long _vector1;\n  \n  arg2 = &temp2;\n  arg3 = &temp3;\n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_long_minmax\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector_long, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  gsl_vector_long_minmax((gsl_vector_long const *)arg1,arg2,arg3);\n  resultobj = SWIG_Py_Void();\n  if (SWIG_IsTmpObj(res2)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_long((*arg2)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res2) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg2), SWIGTYPE_p_long, new_flags));\n  }\n  if (SWIG_IsTmpObj(res3)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_long((*arg3)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res3) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg3), SWIGTYPE_p_long, new_flags));\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_long_max_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_long *arg1 = (gsl_vector_long *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  size_t result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_long _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_long_max_index\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector_long, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (size_t)gsl_vector_long_max_index((gsl_vector_long const *)arg1);\n  resultobj = SWIG_From_size_t((size_t)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_long_min_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_long *arg1 = (gsl_vector_long *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  size_t result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_long _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_long_min_index\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector_long, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (size_t)gsl_vector_long_min_index((gsl_vector_long const *)arg1);\n  resultobj = SWIG_From_size_t((size_t)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_long_minmax_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_long *arg1 = (gsl_vector_long *) 0 ;\n  size_t *arg2 = (size_t *) 0 ;\n  size_t *arg3 = (size_t *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_long _vector1;\n  \n  \n  size_t _size_t_temp2;\n  \n  \n  size_t _size_t_temp3;\n  \n  \n  {\n    _size_t_temp2 = 0;\n    arg2 = &_size_t_temp2;\n  }\n  \n  \n  {\n    _size_t_temp3 = 0;\n    arg3 = &_size_t_temp3;\n  }\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_long_minmax_index\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector_long, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  gsl_vector_long_minmax_index((gsl_vector_long const *)arg1,arg2,arg3);\n  resultobj = SWIG_Py_Void();\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg2));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg3));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_long_isnull(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_long *arg1 = (gsl_vector_long *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_long _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_long_isnull\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector_long, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_long_isnull((gsl_vector_long const *)arg1);\n  resultobj = SWIG_From_int((int)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_long_set_zero(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_long *arg1 = (gsl_matrix_long *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_long _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_long_set_zero\",kwnames,&obj0)) SWIG_fail;\n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix_long, 1, &stride) !=GSL_SUCCESS)\n    goto fail;\n  }\n  gsl_matrix_long_set_zero(arg1);\n  resultobj = SWIG_Py_Void();\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_long_set_all(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_long *arg1 = (gsl_matrix_long *) 0 ;\n  long arg2 ;\n  long val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\",(char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_long _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_long_set_all\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix_long, 1, &stride) !=GSL_SUCCESS)\n    goto fail;\n  }\n  ecode2 = SWIG_AsVal_long(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_long_set_all\" \"', argument \" \"2\"\" of type '\" \"long\"\"'\");\n  } \n  arg2 = (long)(val2);\n  gsl_matrix_long_set_all(arg1,arg2);\n  resultobj = SWIG_Py_Void();\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_long_set_identity(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_long *arg1 = (gsl_matrix_long *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_long _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_long_set_identity\",kwnames,&obj0)) SWIG_fail;\n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix_long, 1, &stride) !=GSL_SUCCESS)\n    goto fail;\n  }\n  gsl_matrix_long_set_identity(arg1);\n  resultobj = SWIG_Py_Void();\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_long_fread(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_matrix_long *arg2 = (gsl_matrix_long *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN_SIZE_OUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix2 = NULL;\n  TYPE_VIEW_gsl_matrix_long _matrix2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_long_fread\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_GENERATE(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_OUTPUT_ARRAY, gsl_matrix_long, 2, &stride) !=GSL_SUCCESS)\n    goto fail;\n  }\n  result = (int)gsl_matrix_long_fread(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix2));\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_long_fwrite(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_matrix_long *arg2 = (gsl_matrix_long *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix2 = NULL;\n  TYPE_VIEW_gsl_matrix_long _matrix2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_long_fwrite\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2,\n        PyGSL_INPUT_ARRAY, gsl_matrix_long, 2, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (int)gsl_matrix_long_fwrite(arg1,(gsl_matrix_long const *)arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_long_fscanf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_matrix_long *arg2 = (gsl_matrix_long *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN_SIZE_OUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix2 = NULL;\n  TYPE_VIEW_gsl_matrix_long _matrix2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_long_fscanf\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_GENERATE(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_OUTPUT_ARRAY, gsl_matrix_long, 2, &stride) !=GSL_SUCCESS)\n    goto fail;\n  }\n  result = (int)gsl_matrix_long_fscanf(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix2));\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_long_fprintf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_matrix_long *arg2 = (gsl_matrix_long *) 0 ;\n  char *arg3 = (char *) 0 ;\n  int res3 ;\n  char *buf3 = 0 ;\n  int alloc3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN\",(char *) \"format\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix2 = NULL;\n  TYPE_VIEW_gsl_matrix_long _matrix2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_matrix_long_fprintf\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2,\n        PyGSL_INPUT_ARRAY, gsl_matrix_long, 2, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3);\n  if (!SWIG_IsOK(res3)) {\n    SWIG_exception_fail(SWIG_ArgError(res3), \"in method '\" \"gsl_matrix_long_fprintf\" \"', argument \" \"3\"\" of type '\" \"char const *\"\"'\");\n  }\n  arg3 = (char *)(buf3);\n  result = (int)gsl_matrix_long_fprintf(arg1,(gsl_matrix_long const *)arg2,(char const *)arg3);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  if (alloc3 == SWIG_NEWOBJ) free((char*)buf3);\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  if (alloc3 == SWIG_NEWOBJ) free((char*)buf3);\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_long_swap(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_long *arg1 = (gsl_matrix_long *) 0 ;\n  gsl_matrix_long *arg2 = (gsl_matrix_long *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"INOUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_long _matrix1;\n  \n  \n  PyArrayObject * _PyMatrix2 = NULL;\n  TYPE_VIEW_gsl_matrix_long _matrix2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_long_swap\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_IO_ARRAY, gsl_matrix_long, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2,\n        PyGSL_IO_ARRAY, gsl_matrix_long, 2, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (int)gsl_matrix_long_swap(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    assert((PyObject *) _PyMatrix2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix2));\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_long_swap_rows(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_long *arg1 = (gsl_matrix_long *) 0 ;\n  size_t arg2 ;\n  size_t arg3 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  size_t val3 ;\n  int ecode3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"i\",(char *) \"j\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_long _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_matrix_long_swap_rows\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_IO_ARRAY, gsl_matrix_long, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_long_swap_rows\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  ecode3 = SWIG_AsVal_size_t(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_matrix_long_swap_rows\" \"', argument \" \"3\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg3 = (size_t)(val3);\n  result = (int)gsl_matrix_long_swap_rows(arg1,arg2,arg3);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_long_swap_columns(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_long *arg1 = (gsl_matrix_long *) 0 ;\n  size_t arg2 ;\n  size_t arg3 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  size_t val3 ;\n  int ecode3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"i\",(char *) \"j\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_long _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_matrix_long_swap_columns\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_IO_ARRAY, gsl_matrix_long, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_long_swap_columns\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  ecode3 = SWIG_AsVal_size_t(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_matrix_long_swap_columns\" \"', argument \" \"3\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg3 = (size_t)(val3);\n  result = (int)gsl_matrix_long_swap_columns(arg1,arg2,arg3);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_long_swap_rowcol(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_long *arg1 = (gsl_matrix_long *) 0 ;\n  size_t arg2 ;\n  size_t arg3 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  size_t val3 ;\n  int ecode3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"i\",(char *) \"j\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_long _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_matrix_long_swap_rowcol\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_IO_ARRAY, gsl_matrix_long, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_long_swap_rowcol\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  ecode3 = SWIG_AsVal_size_t(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_matrix_long_swap_rowcol\" \"', argument \" \"3\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg3 = (size_t)(val3);\n  result = (int)gsl_matrix_long_swap_rowcol(arg1,arg2,arg3);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_long_transpose(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_long *arg1 = (gsl_matrix_long *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_long _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_long_transpose\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_IO_ARRAY, gsl_matrix_long, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (int)gsl_matrix_long_transpose(arg1);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_long_max(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_long *arg1 = (gsl_matrix_long *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  double result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_long _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_long_max\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_long, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (double)gsl_matrix_long_max((gsl_matrix_long const *)arg1);\n  resultobj = SWIG_From_double((double)(result));\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_long_min(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_long *arg1 = (gsl_matrix_long *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  double result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_long _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_long_min\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_long, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (double)gsl_matrix_long_min((gsl_matrix_long const *)arg1);\n  resultobj = SWIG_From_double((double)(result));\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_long_minmax(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_long *arg1 = (gsl_matrix_long *) 0 ;\n  long *arg2 = (long *) 0 ;\n  long *arg3 = (long *) 0 ;\n  long temp2 ;\n  int res2 = SWIG_TMPOBJ ;\n  long temp3 ;\n  int res3 = SWIG_TMPOBJ ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_long _matrix1;\n  \n  arg2 = &temp2;\n  arg3 = &temp3;\n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_long_minmax\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_long, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  gsl_matrix_long_minmax((gsl_matrix_long const *)arg1,arg2,arg3);\n  resultobj = SWIG_Py_Void();\n  if (SWIG_IsTmpObj(res2)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_long((*arg2)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res2) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg2), SWIGTYPE_p_long, new_flags));\n  }\n  if (SWIG_IsTmpObj(res3)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_long((*arg3)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res3) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg3), SWIGTYPE_p_long, new_flags));\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_long_max_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_long *arg1 = (gsl_matrix_long *) 0 ;\n  size_t *arg2 = (size_t *) 0 ;\n  size_t *arg3 = (size_t *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_long _matrix1;\n  \n  \n  size_t _size_t_temp2;\n  \n  \n  size_t _size_t_temp3;\n  \n  \n  {\n    _size_t_temp2 = 0;\n    arg2 = &_size_t_temp2;\n  }\n  \n  \n  {\n    _size_t_temp3 = 0;\n    arg3 = &_size_t_temp3;\n  }\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_long_max_index\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_long, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  gsl_matrix_long_max_index((gsl_matrix_long const *)arg1,arg2,arg3);\n  resultobj = SWIG_Py_Void();\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg2));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg3));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_long_min_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_long *arg1 = (gsl_matrix_long *) 0 ;\n  size_t *arg2 = (size_t *) 0 ;\n  size_t *arg3 = (size_t *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_long _matrix1;\n  \n  \n  size_t _size_t_temp2;\n  \n  \n  size_t _size_t_temp3;\n  \n  \n  {\n    _size_t_temp2 = 0;\n    arg2 = &_size_t_temp2;\n  }\n  \n  \n  {\n    _size_t_temp3 = 0;\n    arg3 = &_size_t_temp3;\n  }\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_long_min_index\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_long, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  gsl_matrix_long_min_index((gsl_matrix_long const *)arg1,arg2,arg3);\n  resultobj = SWIG_Py_Void();\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg2));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg3));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_long_minmax_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_long *arg1 = (gsl_matrix_long *) 0 ;\n  size_t *arg2 = (size_t *) 0 ;\n  size_t *arg3 = (size_t *) 0 ;\n  size_t *arg4 = (size_t *) 0 ;\n  size_t *arg5 = (size_t *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_long _matrix1;\n  \n  \n  size_t _size_t_temp2;\n  \n  \n  size_t _size_t_temp3;\n  \n  \n  size_t _size_t_temp4;\n  \n  \n  size_t _size_t_temp5;\n  \n  \n  {\n    _size_t_temp2 = 0;\n    arg2 = &_size_t_temp2;\n  }\n  \n  \n  {\n    _size_t_temp3 = 0;\n    arg3 = &_size_t_temp3;\n  }\n  \n  \n  {\n    _size_t_temp4 = 0;\n    arg4 = &_size_t_temp4;\n  }\n  \n  \n  {\n    _size_t_temp5 = 0;\n    arg5 = &_size_t_temp5;\n  }\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_long_minmax_index\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_long, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  gsl_matrix_long_minmax_index((gsl_matrix_long const *)arg1,arg2,arg3,arg4,arg5);\n  resultobj = SWIG_Py_Void();\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg2));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg3));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg4));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg5));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_long_isnull(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_long *arg1 = (gsl_matrix_long *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_long _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_long_isnull\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_long, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (int)gsl_matrix_long_isnull((gsl_matrix_long const *)arg1);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_long_diagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_long *arg1 = (gsl_matrix_long *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  gsl_vector_long_view result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_long _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_long_diagonal\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_long, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = gsl_matrix_long_diagonal(arg1);\n  {\n    PyArrayObject * out = NULL; \n    gsl_vector_long_view vectmp; \n    PyGSL_array_index_t tmp;\n    if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_long_view, vectmp, tmp) != GSL_SUCCESS){\n      goto fail;\n    }\n    resultobj = PyGSL_array_return(out);\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_long_subdiagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_long *arg1 = (gsl_matrix_long *) 0 ;\n  size_t arg2 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\",(char *) \"k\", NULL \n  };\n  gsl_vector_long_view result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_long _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_long_subdiagonal\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_long, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_long_subdiagonal\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  result = gsl_matrix_long_subdiagonal(arg1,arg2);\n  {\n    PyArrayObject * out = NULL; \n    gsl_vector_long_view vectmp; \n    PyGSL_array_index_t tmp;\n    if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_long_view, vectmp, tmp) != GSL_SUCCESS){\n      goto fail;\n    }\n    resultobj = PyGSL_array_return(out);\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_long_superdiagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_long *arg1 = (gsl_matrix_long *) 0 ;\n  size_t arg2 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\",(char *) \"k\", NULL \n  };\n  gsl_vector_long_view result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_long _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_long_superdiagonal\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_long, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_long_superdiagonal\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  result = gsl_matrix_long_superdiagonal(arg1,arg2);\n  {\n    PyArrayObject * out = NULL; \n    gsl_vector_long_view vectmp; \n    PyGSL_array_index_t tmp;\n    if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_long_view, vectmp, tmp) != GSL_SUCCESS){\n      goto fail;\n    }\n    resultobj = PyGSL_array_return(out);\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_int_set_zero(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_int *arg1 = (gsl_vector_int *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\", NULL \n  };\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_int _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_int_set_zero\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    int flag;\n    _vector1.vector.data = NULL;\n    flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1,\n      PyGSL_OUTPUT_ARRAY, gsl_vector_int, 1, &stride);\n    if (flag != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  gsl_vector_int_set_zero(arg1);\n  resultobj = SWIG_Py_Void();\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_int_set_all(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_int *arg1 = (gsl_vector_int *) 0 ;\n  int arg2 ;\n  int val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\",(char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_int _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_int_set_all\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    int flag;\n    _vector1.vector.data = NULL;\n    flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1,\n      PyGSL_OUTPUT_ARRAY, gsl_vector_int, 1, &stride);\n    if (flag != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  ecode2 = SWIG_AsVal_int(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_vector_int_set_all\" \"', argument \" \"2\"\" of type '\" \"int\"\"'\");\n  } \n  arg2 = (int)(val2);\n  gsl_vector_int_set_all(arg1,arg2);\n  resultobj = SWIG_Py_Void();\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_int_set_basis(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_int *arg1 = (gsl_vector_int *) 0 ;\n  size_t arg2 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\",(char *) \"i\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_int _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_int_set_basis\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    int flag;\n    _vector1.vector.data = NULL;\n    flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1,\n      PyGSL_OUTPUT_ARRAY, gsl_vector_int, 1, &stride);\n    if (flag != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_vector_int_set_basis\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  result = (int)gsl_vector_int_set_basis(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_int_fread(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_vector_int *arg2 = (gsl_vector_int *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN_SIZE_OUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector_int _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_int_fread\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride;\n    int flag;\n    _vector2.vector.data = NULL;\n    flag = PyGSL_VECTOR_GENERATE(obj1, arg2, _PyVector2, _vector2,\n      PyGSL_OUTPUT_ARRAY, gsl_vector_int, 2, &stride);\n    if (flag != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_int_fread(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert(_PyVector2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector2));\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_int_fwrite(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_vector_int *arg2 = (gsl_vector_int *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector_int _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_int_fwrite\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2,\n        PyGSL_INPUT_ARRAY, gsl_vector_int, 2, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_int_fwrite(arg1,(gsl_vector_int const *)arg2);\n  resultobj = SWIG_From_int((int)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_int_fscanf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_vector_int *arg2 = (gsl_vector_int *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN_SIZE_OUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector_int _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_int_fscanf\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride;\n    int flag;\n    _vector2.vector.data = NULL;\n    flag = PyGSL_VECTOR_GENERATE(obj1, arg2, _PyVector2, _vector2,\n      PyGSL_OUTPUT_ARRAY, gsl_vector_int, 2, &stride);\n    if (flag != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_int_fscanf(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert(_PyVector2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector2));\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_int_fprintf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_vector_int *arg2 = (gsl_vector_int *) 0 ;\n  char *arg3 = (char *) 0 ;\n  int res3 ;\n  char *buf3 = 0 ;\n  int alloc3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN\",(char *) \"format\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector_int _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_vector_int_fprintf\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2,\n        PyGSL_INPUT_ARRAY, gsl_vector_int, 2, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3);\n  if (!SWIG_IsOK(res3)) {\n    SWIG_exception_fail(SWIG_ArgError(res3), \"in method '\" \"gsl_vector_int_fprintf\" \"', argument \" \"3\"\" of type '\" \"char const *\"\"'\");\n  }\n  arg3 = (char *)(buf3);\n  result = (int)gsl_vector_int_fprintf(arg1,(gsl_vector_int const *)arg2,(char const *)arg3);\n  resultobj = SWIG_From_int((int)(result));\n  if (alloc3 == SWIG_NEWOBJ) free((char*)buf3);\n  return resultobj;\nfail:\n  if (alloc3 == SWIG_NEWOBJ) free((char*)buf3);\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_int_reverse(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_int *arg1 = (gsl_vector_int *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_int _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_int_reverse\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_IO_ARRAY, gsl_vector_int, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_int_reverse(arg1);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_int_swap(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_int *arg1 = (gsl_vector_int *) 0 ;\n  gsl_vector_int *arg2 = (gsl_vector_int *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"INOUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_int _vector1;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector_int _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_int_swap\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_IO_ARRAY, gsl_vector_int, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2,\n        PyGSL_IO_ARRAY, gsl_vector_int, 2, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_int_swap(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    assert(_PyVector2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector2));\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_int_swap_elements(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_int *arg1 = (gsl_vector_int *) 0 ;\n  size_t arg2 ;\n  size_t arg3 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  size_t val3 ;\n  int ecode3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"i\",(char *) \"j\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_int _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_vector_int_swap_elements\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_IO_ARRAY, gsl_vector_int, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_vector_int_swap_elements\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  ecode3 = SWIG_AsVal_size_t(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_vector_int_swap_elements\" \"', argument \" \"3\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg3 = (size_t)(val3);\n  result = (int)gsl_vector_int_swap_elements(arg1,arg2,arg3);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_int_max(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_int *arg1 = (gsl_vector_int *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  double result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_int _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_int_max\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector_int, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (double)gsl_vector_int_max((gsl_vector_int const *)arg1);\n  resultobj = SWIG_From_double((double)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_int_min(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_int *arg1 = (gsl_vector_int *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  double result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_int _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_int_min\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector_int, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (double)gsl_vector_int_min((gsl_vector_int const *)arg1);\n  resultobj = SWIG_From_double((double)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_int_minmax(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_int *arg1 = (gsl_vector_int *) 0 ;\n  int *arg2 = (int *) 0 ;\n  int *arg3 = (int *) 0 ;\n  int temp2 ;\n  int res2 = SWIG_TMPOBJ ;\n  int temp3 ;\n  int res3 = SWIG_TMPOBJ ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_int _vector1;\n  \n  arg2 = &temp2;\n  arg3 = &temp3;\n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_int_minmax\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector_int, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  gsl_vector_int_minmax((gsl_vector_int const *)arg1,arg2,arg3);\n  resultobj = SWIG_Py_Void();\n  if (SWIG_IsTmpObj(res2)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_int((*arg2)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res2) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg2), SWIGTYPE_p_int, new_flags));\n  }\n  if (SWIG_IsTmpObj(res3)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_int((*arg3)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res3) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg3), SWIGTYPE_p_int, new_flags));\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_int_max_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_int *arg1 = (gsl_vector_int *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  size_t result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_int _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_int_max_index\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector_int, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (size_t)gsl_vector_int_max_index((gsl_vector_int const *)arg1);\n  resultobj = SWIG_From_size_t((size_t)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_int_min_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_int *arg1 = (gsl_vector_int *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  size_t result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_int _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_int_min_index\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector_int, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (size_t)gsl_vector_int_min_index((gsl_vector_int const *)arg1);\n  resultobj = SWIG_From_size_t((size_t)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_int_minmax_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_int *arg1 = (gsl_vector_int *) 0 ;\n  size_t *arg2 = (size_t *) 0 ;\n  size_t *arg3 = (size_t *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_int _vector1;\n  \n  \n  size_t _size_t_temp2;\n  \n  \n  size_t _size_t_temp3;\n  \n  \n  {\n    _size_t_temp2 = 0;\n    arg2 = &_size_t_temp2;\n  }\n  \n  \n  {\n    _size_t_temp3 = 0;\n    arg3 = &_size_t_temp3;\n  }\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_int_minmax_index\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector_int, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  gsl_vector_int_minmax_index((gsl_vector_int const *)arg1,arg2,arg3);\n  resultobj = SWIG_Py_Void();\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg2));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg3));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_int_isnull(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_int *arg1 = (gsl_vector_int *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_int _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_int_isnull\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector_int, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_int_isnull((gsl_vector_int const *)arg1);\n  resultobj = SWIG_From_int((int)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_int_set_zero(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_int *arg1 = (gsl_matrix_int *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_int _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_int_set_zero\",kwnames,&obj0)) SWIG_fail;\n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix_int, 1, &stride) !=GSL_SUCCESS)\n    goto fail;\n  }\n  gsl_matrix_int_set_zero(arg1);\n  resultobj = SWIG_Py_Void();\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_int_set_all(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_int *arg1 = (gsl_matrix_int *) 0 ;\n  int arg2 ;\n  int val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\",(char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_int _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_int_set_all\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix_int, 1, &stride) !=GSL_SUCCESS)\n    goto fail;\n  }\n  ecode2 = SWIG_AsVal_int(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_int_set_all\" \"', argument \" \"2\"\" of type '\" \"int\"\"'\");\n  } \n  arg2 = (int)(val2);\n  gsl_matrix_int_set_all(arg1,arg2);\n  resultobj = SWIG_Py_Void();\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_int_set_identity(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_int *arg1 = (gsl_matrix_int *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_int _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_int_set_identity\",kwnames,&obj0)) SWIG_fail;\n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix_int, 1, &stride) !=GSL_SUCCESS)\n    goto fail;\n  }\n  gsl_matrix_int_set_identity(arg1);\n  resultobj = SWIG_Py_Void();\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_int_fread(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_matrix_int *arg2 = (gsl_matrix_int *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN_SIZE_OUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix2 = NULL;\n  TYPE_VIEW_gsl_matrix_int _matrix2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_int_fread\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_GENERATE(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_OUTPUT_ARRAY, gsl_matrix_int, 2, &stride) !=GSL_SUCCESS)\n    goto fail;\n  }\n  result = (int)gsl_matrix_int_fread(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix2));\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_int_fwrite(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_matrix_int *arg2 = (gsl_matrix_int *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix2 = NULL;\n  TYPE_VIEW_gsl_matrix_int _matrix2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_int_fwrite\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2,\n        PyGSL_INPUT_ARRAY, gsl_matrix_int, 2, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (int)gsl_matrix_int_fwrite(arg1,(gsl_matrix_int const *)arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_int_fscanf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_matrix_int *arg2 = (gsl_matrix_int *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN_SIZE_OUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix2 = NULL;\n  TYPE_VIEW_gsl_matrix_int _matrix2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_int_fscanf\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_GENERATE(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_OUTPUT_ARRAY, gsl_matrix_int, 2, &stride) !=GSL_SUCCESS)\n    goto fail;\n  }\n  result = (int)gsl_matrix_int_fscanf(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix2));\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_int_fprintf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_matrix_int *arg2 = (gsl_matrix_int *) 0 ;\n  char *arg3 = (char *) 0 ;\n  int res3 ;\n  char *buf3 = 0 ;\n  int alloc3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN\",(char *) \"format\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix2 = NULL;\n  TYPE_VIEW_gsl_matrix_int _matrix2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_matrix_int_fprintf\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2,\n        PyGSL_INPUT_ARRAY, gsl_matrix_int, 2, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3);\n  if (!SWIG_IsOK(res3)) {\n    SWIG_exception_fail(SWIG_ArgError(res3), \"in method '\" \"gsl_matrix_int_fprintf\" \"', argument \" \"3\"\" of type '\" \"char const *\"\"'\");\n  }\n  arg3 = (char *)(buf3);\n  result = (int)gsl_matrix_int_fprintf(arg1,(gsl_matrix_int const *)arg2,(char const *)arg3);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  if (alloc3 == SWIG_NEWOBJ) free((char*)buf3);\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  if (alloc3 == SWIG_NEWOBJ) free((char*)buf3);\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_int_swap(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_int *arg1 = (gsl_matrix_int *) 0 ;\n  gsl_matrix_int *arg2 = (gsl_matrix_int *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"INOUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_int _matrix1;\n  \n  \n  PyArrayObject * _PyMatrix2 = NULL;\n  TYPE_VIEW_gsl_matrix_int _matrix2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_int_swap\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_IO_ARRAY, gsl_matrix_int, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2,\n        PyGSL_IO_ARRAY, gsl_matrix_int, 2, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (int)gsl_matrix_int_swap(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    assert((PyObject *) _PyMatrix2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix2));\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_int_swap_rows(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_int *arg1 = (gsl_matrix_int *) 0 ;\n  size_t arg2 ;\n  size_t arg3 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  size_t val3 ;\n  int ecode3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"i\",(char *) \"j\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_int _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_matrix_int_swap_rows\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_IO_ARRAY, gsl_matrix_int, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_int_swap_rows\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  ecode3 = SWIG_AsVal_size_t(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_matrix_int_swap_rows\" \"', argument \" \"3\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg3 = (size_t)(val3);\n  result = (int)gsl_matrix_int_swap_rows(arg1,arg2,arg3);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_int_swap_columns(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_int *arg1 = (gsl_matrix_int *) 0 ;\n  size_t arg2 ;\n  size_t arg3 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  size_t val3 ;\n  int ecode3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"i\",(char *) \"j\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_int _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_matrix_int_swap_columns\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_IO_ARRAY, gsl_matrix_int, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_int_swap_columns\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  ecode3 = SWIG_AsVal_size_t(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_matrix_int_swap_columns\" \"', argument \" \"3\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg3 = (size_t)(val3);\n  result = (int)gsl_matrix_int_swap_columns(arg1,arg2,arg3);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_int_swap_rowcol(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_int *arg1 = (gsl_matrix_int *) 0 ;\n  size_t arg2 ;\n  size_t arg3 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  size_t val3 ;\n  int ecode3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"i\",(char *) \"j\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_int _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_matrix_int_swap_rowcol\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_IO_ARRAY, gsl_matrix_int, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_int_swap_rowcol\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  ecode3 = SWIG_AsVal_size_t(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_matrix_int_swap_rowcol\" \"', argument \" \"3\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg3 = (size_t)(val3);\n  result = (int)gsl_matrix_int_swap_rowcol(arg1,arg2,arg3);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_int_transpose(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_int *arg1 = (gsl_matrix_int *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_int _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_int_transpose\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_IO_ARRAY, gsl_matrix_int, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (int)gsl_matrix_int_transpose(arg1);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_int_max(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_int *arg1 = (gsl_matrix_int *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  double result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_int _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_int_max\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_int, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (double)gsl_matrix_int_max((gsl_matrix_int const *)arg1);\n  resultobj = SWIG_From_double((double)(result));\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_int_min(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_int *arg1 = (gsl_matrix_int *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  double result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_int _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_int_min\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_int, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (double)gsl_matrix_int_min((gsl_matrix_int const *)arg1);\n  resultobj = SWIG_From_double((double)(result));\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_int_minmax(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_int *arg1 = (gsl_matrix_int *) 0 ;\n  int *arg2 = (int *) 0 ;\n  int *arg3 = (int *) 0 ;\n  int temp2 ;\n  int res2 = SWIG_TMPOBJ ;\n  int temp3 ;\n  int res3 = SWIG_TMPOBJ ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_int _matrix1;\n  \n  arg2 = &temp2;\n  arg3 = &temp3;\n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_int_minmax\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_int, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  gsl_matrix_int_minmax((gsl_matrix_int const *)arg1,arg2,arg3);\n  resultobj = SWIG_Py_Void();\n  if (SWIG_IsTmpObj(res2)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_int((*arg2)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res2) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg2), SWIGTYPE_p_int, new_flags));\n  }\n  if (SWIG_IsTmpObj(res3)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_int((*arg3)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res3) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg3), SWIGTYPE_p_int, new_flags));\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_int_max_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_int *arg1 = (gsl_matrix_int *) 0 ;\n  size_t *arg2 = (size_t *) 0 ;\n  size_t *arg3 = (size_t *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_int _matrix1;\n  \n  \n  size_t _size_t_temp2;\n  \n  \n  size_t _size_t_temp3;\n  \n  \n  {\n    _size_t_temp2 = 0;\n    arg2 = &_size_t_temp2;\n  }\n  \n  \n  {\n    _size_t_temp3 = 0;\n    arg3 = &_size_t_temp3;\n  }\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_int_max_index\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_int, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  gsl_matrix_int_max_index((gsl_matrix_int const *)arg1,arg2,arg3);\n  resultobj = SWIG_Py_Void();\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg2));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg3));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_int_min_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_int *arg1 = (gsl_matrix_int *) 0 ;\n  size_t *arg2 = (size_t *) 0 ;\n  size_t *arg3 = (size_t *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_int _matrix1;\n  \n  \n  size_t _size_t_temp2;\n  \n  \n  size_t _size_t_temp3;\n  \n  \n  {\n    _size_t_temp2 = 0;\n    arg2 = &_size_t_temp2;\n  }\n  \n  \n  {\n    _size_t_temp3 = 0;\n    arg3 = &_size_t_temp3;\n  }\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_int_min_index\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_int, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  gsl_matrix_int_min_index((gsl_matrix_int const *)arg1,arg2,arg3);\n  resultobj = SWIG_Py_Void();\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg2));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg3));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_int_minmax_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_int *arg1 = (gsl_matrix_int *) 0 ;\n  size_t *arg2 = (size_t *) 0 ;\n  size_t *arg3 = (size_t *) 0 ;\n  size_t *arg4 = (size_t *) 0 ;\n  size_t *arg5 = (size_t *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_int _matrix1;\n  \n  \n  size_t _size_t_temp2;\n  \n  \n  size_t _size_t_temp3;\n  \n  \n  size_t _size_t_temp4;\n  \n  \n  size_t _size_t_temp5;\n  \n  \n  {\n    _size_t_temp2 = 0;\n    arg2 = &_size_t_temp2;\n  }\n  \n  \n  {\n    _size_t_temp3 = 0;\n    arg3 = &_size_t_temp3;\n  }\n  \n  \n  {\n    _size_t_temp4 = 0;\n    arg4 = &_size_t_temp4;\n  }\n  \n  \n  {\n    _size_t_temp5 = 0;\n    arg5 = &_size_t_temp5;\n  }\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_int_minmax_index\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_int, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  gsl_matrix_int_minmax_index((gsl_matrix_int const *)arg1,arg2,arg3,arg4,arg5);\n  resultobj = SWIG_Py_Void();\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg2));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg3));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg4));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg5));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_int_isnull(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_int *arg1 = (gsl_matrix_int *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_int _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_int_isnull\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_int, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (int)gsl_matrix_int_isnull((gsl_matrix_int const *)arg1);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_int_diagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_int *arg1 = (gsl_matrix_int *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  gsl_vector_int_view result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_int _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_int_diagonal\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_int, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = gsl_matrix_int_diagonal(arg1);\n  {\n    PyArrayObject * out = NULL; \n    gsl_vector_int_view vectmp; \n    PyGSL_array_index_t tmp;\n    if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_int_view, vectmp, tmp) != GSL_SUCCESS){\n      goto fail;\n    }\n    resultobj = PyGSL_array_return(out);\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_int_subdiagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_int *arg1 = (gsl_matrix_int *) 0 ;\n  size_t arg2 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\",(char *) \"k\", NULL \n  };\n  gsl_vector_int_view result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_int _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_int_subdiagonal\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_int, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_int_subdiagonal\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  result = gsl_matrix_int_subdiagonal(arg1,arg2);\n  {\n    PyArrayObject * out = NULL; \n    gsl_vector_int_view vectmp; \n    PyGSL_array_index_t tmp;\n    if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_int_view, vectmp, tmp) != GSL_SUCCESS){\n      goto fail;\n    }\n    resultobj = PyGSL_array_return(out);\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_int_superdiagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_int *arg1 = (gsl_matrix_int *) 0 ;\n  size_t arg2 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\",(char *) \"k\", NULL \n  };\n  gsl_vector_int_view result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_int _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_int_superdiagonal\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_int, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_int_superdiagonal\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  result = gsl_matrix_int_superdiagonal(arg1,arg2);\n  {\n    PyArrayObject * out = NULL; \n    gsl_vector_int_view vectmp; \n    PyGSL_array_index_t tmp;\n    if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_int_view, vectmp, tmp) != GSL_SUCCESS){\n      goto fail;\n    }\n    resultobj = PyGSL_array_return(out);\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_short_set_zero(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_short *arg1 = (gsl_vector_short *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\", NULL \n  };\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_short _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_short_set_zero\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    int flag;\n    _vector1.vector.data = NULL;\n    flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1,\n      PyGSL_OUTPUT_ARRAY, gsl_vector_short, 1, &stride);\n    if (flag != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  gsl_vector_short_set_zero(arg1);\n  resultobj = SWIG_Py_Void();\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_short_set_all(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_short *arg1 = (gsl_vector_short *) 0 ;\n  short arg2 ;\n  short val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\",(char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_short _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_short_set_all\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    int flag;\n    _vector1.vector.data = NULL;\n    flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1,\n      PyGSL_OUTPUT_ARRAY, gsl_vector_short, 1, &stride);\n    if (flag != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  ecode2 = SWIG_AsVal_short(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_vector_short_set_all\" \"', argument \" \"2\"\" of type '\" \"short\"\"'\");\n  } \n  arg2 = (short)(val2);\n  gsl_vector_short_set_all(arg1,arg2);\n  resultobj = SWIG_Py_Void();\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_short_set_basis(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_short *arg1 = (gsl_vector_short *) 0 ;\n  size_t arg2 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\",(char *) \"i\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_short _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_short_set_basis\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    int flag;\n    _vector1.vector.data = NULL;\n    flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1,\n      PyGSL_OUTPUT_ARRAY, gsl_vector_short, 1, &stride);\n    if (flag != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_vector_short_set_basis\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  result = (int)gsl_vector_short_set_basis(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_short_fread(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_vector_short *arg2 = (gsl_vector_short *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN_SIZE_OUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector_short _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_short_fread\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride;\n    int flag;\n    _vector2.vector.data = NULL;\n    flag = PyGSL_VECTOR_GENERATE(obj1, arg2, _PyVector2, _vector2,\n      PyGSL_OUTPUT_ARRAY, gsl_vector_short, 2, &stride);\n    if (flag != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_short_fread(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert(_PyVector2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector2));\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_short_fwrite(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_vector_short *arg2 = (gsl_vector_short *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector_short _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_short_fwrite\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2,\n        PyGSL_INPUT_ARRAY, gsl_vector_short, 2, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_short_fwrite(arg1,(gsl_vector_short const *)arg2);\n  resultobj = SWIG_From_int((int)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_short_fscanf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_vector_short *arg2 = (gsl_vector_short *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN_SIZE_OUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector_short _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_short_fscanf\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride;\n    int flag;\n    _vector2.vector.data = NULL;\n    flag = PyGSL_VECTOR_GENERATE(obj1, arg2, _PyVector2, _vector2,\n      PyGSL_OUTPUT_ARRAY, gsl_vector_short, 2, &stride);\n    if (flag != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_short_fscanf(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert(_PyVector2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector2));\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_short_fprintf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_vector_short *arg2 = (gsl_vector_short *) 0 ;\n  char *arg3 = (char *) 0 ;\n  int res3 ;\n  char *buf3 = 0 ;\n  int alloc3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN\",(char *) \"format\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector_short _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_vector_short_fprintf\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2,\n        PyGSL_INPUT_ARRAY, gsl_vector_short, 2, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3);\n  if (!SWIG_IsOK(res3)) {\n    SWIG_exception_fail(SWIG_ArgError(res3), \"in method '\" \"gsl_vector_short_fprintf\" \"', argument \" \"3\"\" of type '\" \"char const *\"\"'\");\n  }\n  arg3 = (char *)(buf3);\n  result = (int)gsl_vector_short_fprintf(arg1,(gsl_vector_short const *)arg2,(char const *)arg3);\n  resultobj = SWIG_From_int((int)(result));\n  if (alloc3 == SWIG_NEWOBJ) free((char*)buf3);\n  return resultobj;\nfail:\n  if (alloc3 == SWIG_NEWOBJ) free((char*)buf3);\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_short_reverse(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_short *arg1 = (gsl_vector_short *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_short _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_short_reverse\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_IO_ARRAY, gsl_vector_short, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_short_reverse(arg1);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_short_swap(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_short *arg1 = (gsl_vector_short *) 0 ;\n  gsl_vector_short *arg2 = (gsl_vector_short *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"INOUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_short _vector1;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector_short _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_short_swap\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_IO_ARRAY, gsl_vector_short, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2,\n        PyGSL_IO_ARRAY, gsl_vector_short, 2, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_short_swap(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    assert(_PyVector2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector2));\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_short_swap_elements(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_short *arg1 = (gsl_vector_short *) 0 ;\n  size_t arg2 ;\n  size_t arg3 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  size_t val3 ;\n  int ecode3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"i\",(char *) \"j\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_short _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_vector_short_swap_elements\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_IO_ARRAY, gsl_vector_short, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_vector_short_swap_elements\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  ecode3 = SWIG_AsVal_size_t(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_vector_short_swap_elements\" \"', argument \" \"3\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg3 = (size_t)(val3);\n  result = (int)gsl_vector_short_swap_elements(arg1,arg2,arg3);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_short_max(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_short *arg1 = (gsl_vector_short *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  double result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_short _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_short_max\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector_short, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (double)gsl_vector_short_max((gsl_vector_short const *)arg1);\n  resultobj = SWIG_From_double((double)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_short_min(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_short *arg1 = (gsl_vector_short *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  double result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_short _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_short_min\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector_short, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (double)gsl_vector_short_min((gsl_vector_short const *)arg1);\n  resultobj = SWIG_From_double((double)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_short_minmax(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_short *arg1 = (gsl_vector_short *) 0 ;\n  short *arg2 = (short *) 0 ;\n  short *arg3 = (short *) 0 ;\n  short temp2 ;\n  int res2 = SWIG_TMPOBJ ;\n  short temp3 ;\n  int res3 = SWIG_TMPOBJ ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_short _vector1;\n  \n  arg2 = &temp2;\n  arg3 = &temp3;\n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_short_minmax\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector_short, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  gsl_vector_short_minmax((gsl_vector_short const *)arg1,arg2,arg3);\n  resultobj = SWIG_Py_Void();\n  if (SWIG_IsTmpObj(res2)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_short((*arg2)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res2) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg2), SWIGTYPE_p_short, new_flags));\n  }\n  if (SWIG_IsTmpObj(res3)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_short((*arg3)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res3) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg3), SWIGTYPE_p_short, new_flags));\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_short_max_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_short *arg1 = (gsl_vector_short *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  size_t result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_short _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_short_max_index\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector_short, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (size_t)gsl_vector_short_max_index((gsl_vector_short const *)arg1);\n  resultobj = SWIG_From_size_t((size_t)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_short_min_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_short *arg1 = (gsl_vector_short *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  size_t result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_short _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_short_min_index\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector_short, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (size_t)gsl_vector_short_min_index((gsl_vector_short const *)arg1);\n  resultobj = SWIG_From_size_t((size_t)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_short_minmax_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_short *arg1 = (gsl_vector_short *) 0 ;\n  size_t *arg2 = (size_t *) 0 ;\n  size_t *arg3 = (size_t *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_short _vector1;\n  \n  \n  size_t _size_t_temp2;\n  \n  \n  size_t _size_t_temp3;\n  \n  \n  {\n    _size_t_temp2 = 0;\n    arg2 = &_size_t_temp2;\n  }\n  \n  \n  {\n    _size_t_temp3 = 0;\n    arg3 = &_size_t_temp3;\n  }\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_short_minmax_index\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector_short, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  gsl_vector_short_minmax_index((gsl_vector_short const *)arg1,arg2,arg3);\n  resultobj = SWIG_Py_Void();\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg2));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg3));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_short_isnull(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_short *arg1 = (gsl_vector_short *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_short _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_short_isnull\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector_short, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_short_isnull((gsl_vector_short const *)arg1);\n  resultobj = SWIG_From_int((int)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_short_set_zero(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_short *arg1 = (gsl_matrix_short *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_short _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_short_set_zero\",kwnames,&obj0)) SWIG_fail;\n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix_short, 1, &stride) !=GSL_SUCCESS)\n    goto fail;\n  }\n  gsl_matrix_short_set_zero(arg1);\n  resultobj = SWIG_Py_Void();\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_short_set_all(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_short *arg1 = (gsl_matrix_short *) 0 ;\n  short arg2 ;\n  short val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\",(char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_short _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_short_set_all\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix_short, 1, &stride) !=GSL_SUCCESS)\n    goto fail;\n  }\n  ecode2 = SWIG_AsVal_short(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_short_set_all\" \"', argument \" \"2\"\" of type '\" \"short\"\"'\");\n  } \n  arg2 = (short)(val2);\n  gsl_matrix_short_set_all(arg1,arg2);\n  resultobj = SWIG_Py_Void();\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_short_set_identity(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_short *arg1 = (gsl_matrix_short *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_short _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_short_set_identity\",kwnames,&obj0)) SWIG_fail;\n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix_short, 1, &stride) !=GSL_SUCCESS)\n    goto fail;\n  }\n  gsl_matrix_short_set_identity(arg1);\n  resultobj = SWIG_Py_Void();\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_short_fread(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_matrix_short *arg2 = (gsl_matrix_short *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN_SIZE_OUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix2 = NULL;\n  TYPE_VIEW_gsl_matrix_short _matrix2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_short_fread\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_GENERATE(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_OUTPUT_ARRAY, gsl_matrix_short, 2, &stride) !=GSL_SUCCESS)\n    goto fail;\n  }\n  result = (int)gsl_matrix_short_fread(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix2));\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_short_fwrite(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_matrix_short *arg2 = (gsl_matrix_short *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix2 = NULL;\n  TYPE_VIEW_gsl_matrix_short _matrix2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_short_fwrite\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2,\n        PyGSL_INPUT_ARRAY, gsl_matrix_short, 2, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (int)gsl_matrix_short_fwrite(arg1,(gsl_matrix_short const *)arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_short_fscanf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_matrix_short *arg2 = (gsl_matrix_short *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN_SIZE_OUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix2 = NULL;\n  TYPE_VIEW_gsl_matrix_short _matrix2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_short_fscanf\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_GENERATE(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_OUTPUT_ARRAY, gsl_matrix_short, 2, &stride) !=GSL_SUCCESS)\n    goto fail;\n  }\n  result = (int)gsl_matrix_short_fscanf(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix2));\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_short_fprintf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_matrix_short *arg2 = (gsl_matrix_short *) 0 ;\n  char *arg3 = (char *) 0 ;\n  int res3 ;\n  char *buf3 = 0 ;\n  int alloc3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN\",(char *) \"format\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix2 = NULL;\n  TYPE_VIEW_gsl_matrix_short _matrix2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_matrix_short_fprintf\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2,\n        PyGSL_INPUT_ARRAY, gsl_matrix_short, 2, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3);\n  if (!SWIG_IsOK(res3)) {\n    SWIG_exception_fail(SWIG_ArgError(res3), \"in method '\" \"gsl_matrix_short_fprintf\" \"', argument \" \"3\"\" of type '\" \"char const *\"\"'\");\n  }\n  arg3 = (char *)(buf3);\n  result = (int)gsl_matrix_short_fprintf(arg1,(gsl_matrix_short const *)arg2,(char const *)arg3);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  if (alloc3 == SWIG_NEWOBJ) free((char*)buf3);\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  if (alloc3 == SWIG_NEWOBJ) free((char*)buf3);\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_short_swap(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_short *arg1 = (gsl_matrix_short *) 0 ;\n  gsl_matrix_short *arg2 = (gsl_matrix_short *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"INOUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_short _matrix1;\n  \n  \n  PyArrayObject * _PyMatrix2 = NULL;\n  TYPE_VIEW_gsl_matrix_short _matrix2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_short_swap\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_IO_ARRAY, gsl_matrix_short, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2,\n        PyGSL_IO_ARRAY, gsl_matrix_short, 2, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (int)gsl_matrix_short_swap(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    assert((PyObject *) _PyMatrix2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix2));\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_short_swap_rows(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_short *arg1 = (gsl_matrix_short *) 0 ;\n  size_t arg2 ;\n  size_t arg3 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  size_t val3 ;\n  int ecode3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"i\",(char *) \"j\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_short _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_matrix_short_swap_rows\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_IO_ARRAY, gsl_matrix_short, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_short_swap_rows\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  ecode3 = SWIG_AsVal_size_t(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_matrix_short_swap_rows\" \"', argument \" \"3\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg3 = (size_t)(val3);\n  result = (int)gsl_matrix_short_swap_rows(arg1,arg2,arg3);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_short_swap_columns(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_short *arg1 = (gsl_matrix_short *) 0 ;\n  size_t arg2 ;\n  size_t arg3 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  size_t val3 ;\n  int ecode3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"i\",(char *) \"j\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_short _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_matrix_short_swap_columns\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_IO_ARRAY, gsl_matrix_short, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_short_swap_columns\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  ecode3 = SWIG_AsVal_size_t(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_matrix_short_swap_columns\" \"', argument \" \"3\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg3 = (size_t)(val3);\n  result = (int)gsl_matrix_short_swap_columns(arg1,arg2,arg3);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_short_swap_rowcol(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_short *arg1 = (gsl_matrix_short *) 0 ;\n  size_t arg2 ;\n  size_t arg3 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  size_t val3 ;\n  int ecode3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"i\",(char *) \"j\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_short _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_matrix_short_swap_rowcol\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_IO_ARRAY, gsl_matrix_short, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_short_swap_rowcol\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  ecode3 = SWIG_AsVal_size_t(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_matrix_short_swap_rowcol\" \"', argument \" \"3\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg3 = (size_t)(val3);\n  result = (int)gsl_matrix_short_swap_rowcol(arg1,arg2,arg3);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_short_transpose(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_short *arg1 = (gsl_matrix_short *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_short _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_short_transpose\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_IO_ARRAY, gsl_matrix_short, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (int)gsl_matrix_short_transpose(arg1);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_short_max(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_short *arg1 = (gsl_matrix_short *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  double result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_short _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_short_max\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_short, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (double)gsl_matrix_short_max((gsl_matrix_short const *)arg1);\n  resultobj = SWIG_From_double((double)(result));\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_short_min(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_short *arg1 = (gsl_matrix_short *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  double result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_short _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_short_min\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_short, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (double)gsl_matrix_short_min((gsl_matrix_short const *)arg1);\n  resultobj = SWIG_From_double((double)(result));\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_short_minmax(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_short *arg1 = (gsl_matrix_short *) 0 ;\n  short *arg2 = (short *) 0 ;\n  short *arg3 = (short *) 0 ;\n  short temp2 ;\n  int res2 = SWIG_TMPOBJ ;\n  short temp3 ;\n  int res3 = SWIG_TMPOBJ ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_short _matrix1;\n  \n  arg2 = &temp2;\n  arg3 = &temp3;\n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_short_minmax\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_short, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  gsl_matrix_short_minmax((gsl_matrix_short const *)arg1,arg2,arg3);\n  resultobj = SWIG_Py_Void();\n  if (SWIG_IsTmpObj(res2)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_short((*arg2)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res2) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg2), SWIGTYPE_p_short, new_flags));\n  }\n  if (SWIG_IsTmpObj(res3)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_short((*arg3)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res3) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg3), SWIGTYPE_p_short, new_flags));\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_short_max_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_short *arg1 = (gsl_matrix_short *) 0 ;\n  size_t *arg2 = (size_t *) 0 ;\n  size_t *arg3 = (size_t *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_short _matrix1;\n  \n  \n  size_t _size_t_temp2;\n  \n  \n  size_t _size_t_temp3;\n  \n  \n  {\n    _size_t_temp2 = 0;\n    arg2 = &_size_t_temp2;\n  }\n  \n  \n  {\n    _size_t_temp3 = 0;\n    arg3 = &_size_t_temp3;\n  }\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_short_max_index\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_short, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  gsl_matrix_short_max_index((gsl_matrix_short const *)arg1,arg2,arg3);\n  resultobj = SWIG_Py_Void();\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg2));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg3));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_short_min_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_short *arg1 = (gsl_matrix_short *) 0 ;\n  size_t *arg2 = (size_t *) 0 ;\n  size_t *arg3 = (size_t *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_short _matrix1;\n  \n  \n  size_t _size_t_temp2;\n  \n  \n  size_t _size_t_temp3;\n  \n  \n  {\n    _size_t_temp2 = 0;\n    arg2 = &_size_t_temp2;\n  }\n  \n  \n  {\n    _size_t_temp3 = 0;\n    arg3 = &_size_t_temp3;\n  }\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_short_min_index\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_short, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  gsl_matrix_short_min_index((gsl_matrix_short const *)arg1,arg2,arg3);\n  resultobj = SWIG_Py_Void();\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg2));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg3));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_short_minmax_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_short *arg1 = (gsl_matrix_short *) 0 ;\n  size_t *arg2 = (size_t *) 0 ;\n  size_t *arg3 = (size_t *) 0 ;\n  size_t *arg4 = (size_t *) 0 ;\n  size_t *arg5 = (size_t *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_short _matrix1;\n  \n  \n  size_t _size_t_temp2;\n  \n  \n  size_t _size_t_temp3;\n  \n  \n  size_t _size_t_temp4;\n  \n  \n  size_t _size_t_temp5;\n  \n  \n  {\n    _size_t_temp2 = 0;\n    arg2 = &_size_t_temp2;\n  }\n  \n  \n  {\n    _size_t_temp3 = 0;\n    arg3 = &_size_t_temp3;\n  }\n  \n  \n  {\n    _size_t_temp4 = 0;\n    arg4 = &_size_t_temp4;\n  }\n  \n  \n  {\n    _size_t_temp5 = 0;\n    arg5 = &_size_t_temp5;\n  }\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_short_minmax_index\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_short, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  gsl_matrix_short_minmax_index((gsl_matrix_short const *)arg1,arg2,arg3,arg4,arg5);\n  resultobj = SWIG_Py_Void();\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg2));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg3));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg4));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg5));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_short_isnull(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_short *arg1 = (gsl_matrix_short *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_short _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_short_isnull\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_short, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (int)gsl_matrix_short_isnull((gsl_matrix_short const *)arg1);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_short_diagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_short *arg1 = (gsl_matrix_short *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  gsl_vector_short_view result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_short _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_short_diagonal\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_short, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = gsl_matrix_short_diagonal(arg1);\n  {\n    PyArrayObject * out = NULL; \n    gsl_vector_short_view vectmp; \n    PyGSL_array_index_t tmp;\n    if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_short_view, vectmp, tmp) != GSL_SUCCESS){\n      goto fail;\n    }\n    resultobj = PyGSL_array_return(out);\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_short_subdiagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_short *arg1 = (gsl_matrix_short *) 0 ;\n  size_t arg2 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\",(char *) \"k\", NULL \n  };\n  gsl_vector_short_view result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_short _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_short_subdiagonal\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_short, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_short_subdiagonal\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  result = gsl_matrix_short_subdiagonal(arg1,arg2);\n  {\n    PyArrayObject * out = NULL; \n    gsl_vector_short_view vectmp; \n    PyGSL_array_index_t tmp;\n    if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_short_view, vectmp, tmp) != GSL_SUCCESS){\n      goto fail;\n    }\n    resultobj = PyGSL_array_return(out);\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_short_superdiagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_short *arg1 = (gsl_matrix_short *) 0 ;\n  size_t arg2 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\",(char *) \"k\", NULL \n  };\n  gsl_vector_short_view result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_short _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_short_superdiagonal\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_short, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_short_superdiagonal\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  result = gsl_matrix_short_superdiagonal(arg1,arg2);\n  {\n    PyArrayObject * out = NULL; \n    gsl_vector_short_view vectmp; \n    PyGSL_array_index_t tmp;\n    if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_short_view, vectmp, tmp) != GSL_SUCCESS){\n      goto fail;\n    }\n    resultobj = PyGSL_array_return(out);\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_char_set_zero(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_char *arg1 = (gsl_vector_char *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\", NULL \n  };\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_char _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_char_set_zero\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    int flag;\n    _vector1.vector.data = NULL;\n    flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1,\n      PyGSL_OUTPUT_ARRAY, gsl_vector_char, 1, &stride);\n    if (flag != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  gsl_vector_char_set_zero(arg1);\n  resultobj = SWIG_Py_Void();\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_char_set_all(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_char *arg1 = (gsl_vector_char *) 0 ;\n  char arg2 ;\n  char val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\",(char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_char _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_char_set_all\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    int flag;\n    _vector1.vector.data = NULL;\n    flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1,\n      PyGSL_OUTPUT_ARRAY, gsl_vector_char, 1, &stride);\n    if (flag != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  ecode2 = SWIG_AsVal_char(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_vector_char_set_all\" \"', argument \" \"2\"\" of type '\" \"char\"\"'\");\n  } \n  arg2 = (char)(val2);\n  gsl_vector_char_set_all(arg1,arg2);\n  resultobj = SWIG_Py_Void();\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_char_set_basis(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_char *arg1 = (gsl_vector_char *) 0 ;\n  size_t arg2 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\",(char *) \"i\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_char _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_char_set_basis\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    int flag;\n    _vector1.vector.data = NULL;\n    flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1,\n      PyGSL_OUTPUT_ARRAY, gsl_vector_char, 1, &stride);\n    if (flag != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_vector_char_set_basis\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  result = (int)gsl_vector_char_set_basis(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_char_fread(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_vector_char *arg2 = (gsl_vector_char *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN_SIZE_OUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector_char _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_char_fread\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride;\n    int flag;\n    _vector2.vector.data = NULL;\n    flag = PyGSL_VECTOR_GENERATE(obj1, arg2, _PyVector2, _vector2,\n      PyGSL_OUTPUT_ARRAY, gsl_vector_char, 2, &stride);\n    if (flag != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_char_fread(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert(_PyVector2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector2));\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_char_fwrite(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_vector_char *arg2 = (gsl_vector_char *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector_char _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_char_fwrite\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2,\n        PyGSL_INPUT_ARRAY, gsl_vector_char, 2, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_char_fwrite(arg1,(gsl_vector_char const *)arg2);\n  resultobj = SWIG_From_int((int)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_char_fscanf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_vector_char *arg2 = (gsl_vector_char *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN_SIZE_OUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector_char _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_char_fscanf\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride;\n    int flag;\n    _vector2.vector.data = NULL;\n    flag = PyGSL_VECTOR_GENERATE(obj1, arg2, _PyVector2, _vector2,\n      PyGSL_OUTPUT_ARRAY, gsl_vector_char, 2, &stride);\n    if (flag != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_char_fscanf(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert(_PyVector2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector2));\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_char_fprintf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_vector_char *arg2 = (gsl_vector_char *) 0 ;\n  char *arg3 = (char *) 0 ;\n  int res3 ;\n  char *buf3 = 0 ;\n  int alloc3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN\",(char *) \"format\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector_char _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_vector_char_fprintf\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2,\n        PyGSL_INPUT_ARRAY, gsl_vector_char, 2, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3);\n  if (!SWIG_IsOK(res3)) {\n    SWIG_exception_fail(SWIG_ArgError(res3), \"in method '\" \"gsl_vector_char_fprintf\" \"', argument \" \"3\"\" of type '\" \"char const *\"\"'\");\n  }\n  arg3 = (char *)(buf3);\n  result = (int)gsl_vector_char_fprintf(arg1,(gsl_vector_char const *)arg2,(char const *)arg3);\n  resultobj = SWIG_From_int((int)(result));\n  if (alloc3 == SWIG_NEWOBJ) free((char*)buf3);\n  return resultobj;\nfail:\n  if (alloc3 == SWIG_NEWOBJ) free((char*)buf3);\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_char_reverse(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_char *arg1 = (gsl_vector_char *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_char _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_char_reverse\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_IO_ARRAY, gsl_vector_char, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_char_reverse(arg1);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_char_swap(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_char *arg1 = (gsl_vector_char *) 0 ;\n  gsl_vector_char *arg2 = (gsl_vector_char *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"INOUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_char _vector1;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector_char _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_char_swap\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_IO_ARRAY, gsl_vector_char, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2,\n        PyGSL_IO_ARRAY, gsl_vector_char, 2, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_char_swap(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    assert(_PyVector2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector2));\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_char_swap_elements(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_char *arg1 = (gsl_vector_char *) 0 ;\n  size_t arg2 ;\n  size_t arg3 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  size_t val3 ;\n  int ecode3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"i\",(char *) \"j\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_char _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_vector_char_swap_elements\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_IO_ARRAY, gsl_vector_char, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_vector_char_swap_elements\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  ecode3 = SWIG_AsVal_size_t(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_vector_char_swap_elements\" \"', argument \" \"3\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg3 = (size_t)(val3);\n  result = (int)gsl_vector_char_swap_elements(arg1,arg2,arg3);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_char_max(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_char *arg1 = (gsl_vector_char *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  double result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_char _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_char_max\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector_char, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (double)gsl_vector_char_max((gsl_vector_char const *)arg1);\n  resultobj = SWIG_From_double((double)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_char_min(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_char *arg1 = (gsl_vector_char *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  double result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_char _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_char_min\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector_char, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (double)gsl_vector_char_min((gsl_vector_char const *)arg1);\n  resultobj = SWIG_From_double((double)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_char_minmax(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_char *arg1 = (gsl_vector_char *) 0 ;\n  char *arg2 = (char *) 0 ;\n  char *arg3 = (char *) 0 ;\n  char temp2 ;\n  int res2 = SWIG_TMPOBJ ;\n  char temp3 ;\n  int res3 = SWIG_TMPOBJ ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_char _vector1;\n  \n  arg2 = &temp2;\n  arg3 = &temp3;\n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_char_minmax\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector_char, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  gsl_vector_char_minmax((gsl_vector_char const *)arg1,arg2,arg3);\n  resultobj = SWIG_Py_Void();\n  if (SWIG_IsTmpObj(res2)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_char((*arg2)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res2) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg2), SWIGTYPE_p_char, new_flags));\n  }\n  if (SWIG_IsTmpObj(res3)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_char((*arg3)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res3) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg3), SWIGTYPE_p_char, new_flags));\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_char_max_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_char *arg1 = (gsl_vector_char *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  size_t result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_char _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_char_max_index\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector_char, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (size_t)gsl_vector_char_max_index((gsl_vector_char const *)arg1);\n  resultobj = SWIG_From_size_t((size_t)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_char_min_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_char *arg1 = (gsl_vector_char *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  size_t result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_char _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_char_min_index\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector_char, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (size_t)gsl_vector_char_min_index((gsl_vector_char const *)arg1);\n  resultobj = SWIG_From_size_t((size_t)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_char_minmax_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_char *arg1 = (gsl_vector_char *) 0 ;\n  size_t *arg2 = (size_t *) 0 ;\n  size_t *arg3 = (size_t *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_char _vector1;\n  \n  \n  size_t _size_t_temp2;\n  \n  \n  size_t _size_t_temp3;\n  \n  \n  {\n    _size_t_temp2 = 0;\n    arg2 = &_size_t_temp2;\n  }\n  \n  \n  {\n    _size_t_temp3 = 0;\n    arg3 = &_size_t_temp3;\n  }\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_char_minmax_index\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector_char, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  gsl_vector_char_minmax_index((gsl_vector_char const *)arg1,arg2,arg3);\n  resultobj = SWIG_Py_Void();\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg2));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg3));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_char_isnull(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_char *arg1 = (gsl_vector_char *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_char _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_char_isnull\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector_char, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_char_isnull((gsl_vector_char const *)arg1);\n  resultobj = SWIG_From_int((int)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_char_set_zero(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_char *arg1 = (gsl_matrix_char *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_char _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_char_set_zero\",kwnames,&obj0)) SWIG_fail;\n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix_char, 1, &stride) !=GSL_SUCCESS)\n    goto fail;\n  }\n  gsl_matrix_char_set_zero(arg1);\n  resultobj = SWIG_Py_Void();\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_char_set_all(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_char *arg1 = (gsl_matrix_char *) 0 ;\n  char arg2 ;\n  char val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\",(char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_char _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_char_set_all\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix_char, 1, &stride) !=GSL_SUCCESS)\n    goto fail;\n  }\n  ecode2 = SWIG_AsVal_char(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_char_set_all\" \"', argument \" \"2\"\" of type '\" \"char\"\"'\");\n  } \n  arg2 = (char)(val2);\n  gsl_matrix_char_set_all(arg1,arg2);\n  resultobj = SWIG_Py_Void();\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_char_set_identity(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_char *arg1 = (gsl_matrix_char *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_char _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_char_set_identity\",kwnames,&obj0)) SWIG_fail;\n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix_char, 1, &stride) !=GSL_SUCCESS)\n    goto fail;\n  }\n  gsl_matrix_char_set_identity(arg1);\n  resultobj = SWIG_Py_Void();\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_char_fread(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_matrix_char *arg2 = (gsl_matrix_char *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN_SIZE_OUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix2 = NULL;\n  TYPE_VIEW_gsl_matrix_char _matrix2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_char_fread\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_GENERATE(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_OUTPUT_ARRAY, gsl_matrix_char, 2, &stride) !=GSL_SUCCESS)\n    goto fail;\n  }\n  result = (int)gsl_matrix_char_fread(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix2));\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_char_fwrite(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_matrix_char *arg2 = (gsl_matrix_char *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix2 = NULL;\n  TYPE_VIEW_gsl_matrix_char _matrix2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_char_fwrite\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2,\n        PyGSL_INPUT_ARRAY, gsl_matrix_char, 2, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (int)gsl_matrix_char_fwrite(arg1,(gsl_matrix_char const *)arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_char_fscanf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_matrix_char *arg2 = (gsl_matrix_char *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN_SIZE_OUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix2 = NULL;\n  TYPE_VIEW_gsl_matrix_char _matrix2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_char_fscanf\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_GENERATE(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_OUTPUT_ARRAY, gsl_matrix_char, 2, &stride) !=GSL_SUCCESS)\n    goto fail;\n  }\n  result = (int)gsl_matrix_char_fscanf(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix2));\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_char_fprintf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_matrix_char *arg2 = (gsl_matrix_char *) 0 ;\n  char *arg3 = (char *) 0 ;\n  int res3 ;\n  char *buf3 = 0 ;\n  int alloc3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN\",(char *) \"format\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix2 = NULL;\n  TYPE_VIEW_gsl_matrix_char _matrix2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_matrix_char_fprintf\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2,\n        PyGSL_INPUT_ARRAY, gsl_matrix_char, 2, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3);\n  if (!SWIG_IsOK(res3)) {\n    SWIG_exception_fail(SWIG_ArgError(res3), \"in method '\" \"gsl_matrix_char_fprintf\" \"', argument \" \"3\"\" of type '\" \"char const *\"\"'\");\n  }\n  arg3 = (char *)(buf3);\n  result = (int)gsl_matrix_char_fprintf(arg1,(gsl_matrix_char const *)arg2,(char const *)arg3);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  if (alloc3 == SWIG_NEWOBJ) free((char*)buf3);\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  if (alloc3 == SWIG_NEWOBJ) free((char*)buf3);\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_char_swap(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_char *arg1 = (gsl_matrix_char *) 0 ;\n  gsl_matrix_char *arg2 = (gsl_matrix_char *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"INOUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_char _matrix1;\n  \n  \n  PyArrayObject * _PyMatrix2 = NULL;\n  TYPE_VIEW_gsl_matrix_char _matrix2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_char_swap\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_IO_ARRAY, gsl_matrix_char, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2,\n        PyGSL_IO_ARRAY, gsl_matrix_char, 2, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (int)gsl_matrix_char_swap(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    assert((PyObject *) _PyMatrix2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix2));\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_char_swap_rows(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_char *arg1 = (gsl_matrix_char *) 0 ;\n  size_t arg2 ;\n  size_t arg3 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  size_t val3 ;\n  int ecode3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"i\",(char *) \"j\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_char _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_matrix_char_swap_rows\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_IO_ARRAY, gsl_matrix_char, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_char_swap_rows\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  ecode3 = SWIG_AsVal_size_t(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_matrix_char_swap_rows\" \"', argument \" \"3\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg3 = (size_t)(val3);\n  result = (int)gsl_matrix_char_swap_rows(arg1,arg2,arg3);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_char_swap_columns(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_char *arg1 = (gsl_matrix_char *) 0 ;\n  size_t arg2 ;\n  size_t arg3 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  size_t val3 ;\n  int ecode3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"i\",(char *) \"j\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_char _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_matrix_char_swap_columns\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_IO_ARRAY, gsl_matrix_char, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_char_swap_columns\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  ecode3 = SWIG_AsVal_size_t(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_matrix_char_swap_columns\" \"', argument \" \"3\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg3 = (size_t)(val3);\n  result = (int)gsl_matrix_char_swap_columns(arg1,arg2,arg3);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_char_swap_rowcol(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_char *arg1 = (gsl_matrix_char *) 0 ;\n  size_t arg2 ;\n  size_t arg3 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  size_t val3 ;\n  int ecode3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"i\",(char *) \"j\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_char _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_matrix_char_swap_rowcol\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_IO_ARRAY, gsl_matrix_char, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_char_swap_rowcol\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  ecode3 = SWIG_AsVal_size_t(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_matrix_char_swap_rowcol\" \"', argument \" \"3\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg3 = (size_t)(val3);\n  result = (int)gsl_matrix_char_swap_rowcol(arg1,arg2,arg3);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_char_transpose(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_char *arg1 = (gsl_matrix_char *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_char _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_char_transpose\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_IO_ARRAY, gsl_matrix_char, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (int)gsl_matrix_char_transpose(arg1);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_char_max(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_char *arg1 = (gsl_matrix_char *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  double result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_char _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_char_max\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_char, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (double)gsl_matrix_char_max((gsl_matrix_char const *)arg1);\n  resultobj = SWIG_From_double((double)(result));\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_char_min(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_char *arg1 = (gsl_matrix_char *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  double result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_char _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_char_min\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_char, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (double)gsl_matrix_char_min((gsl_matrix_char const *)arg1);\n  resultobj = SWIG_From_double((double)(result));\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_char_minmax(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_char *arg1 = (gsl_matrix_char *) 0 ;\n  char *arg2 = (char *) 0 ;\n  char *arg3 = (char *) 0 ;\n  char temp2 ;\n  int res2 = SWIG_TMPOBJ ;\n  char temp3 ;\n  int res3 = SWIG_TMPOBJ ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_char _matrix1;\n  \n  arg2 = &temp2;\n  arg3 = &temp3;\n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_char_minmax\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_char, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  gsl_matrix_char_minmax((gsl_matrix_char const *)arg1,arg2,arg3);\n  resultobj = SWIG_Py_Void();\n  if (SWIG_IsTmpObj(res2)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_char((*arg2)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res2) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg2), SWIGTYPE_p_char, new_flags));\n  }\n  if (SWIG_IsTmpObj(res3)) {\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_char((*arg3)));\n  } else {\n    int new_flags = SWIG_IsNewObj(res3) ? (SWIG_POINTER_OWN |  0 ) :  0 ;\n    resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg3), SWIGTYPE_p_char, new_flags));\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_char_max_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_char *arg1 = (gsl_matrix_char *) 0 ;\n  size_t *arg2 = (size_t *) 0 ;\n  size_t *arg3 = (size_t *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_char _matrix1;\n  \n  \n  size_t _size_t_temp2;\n  \n  \n  size_t _size_t_temp3;\n  \n  \n  {\n    _size_t_temp2 = 0;\n    arg2 = &_size_t_temp2;\n  }\n  \n  \n  {\n    _size_t_temp3 = 0;\n    arg3 = &_size_t_temp3;\n  }\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_char_max_index\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_char, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  gsl_matrix_char_max_index((gsl_matrix_char const *)arg1,arg2,arg3);\n  resultobj = SWIG_Py_Void();\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg2));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg3));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_char_min_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_char *arg1 = (gsl_matrix_char *) 0 ;\n  size_t *arg2 = (size_t *) 0 ;\n  size_t *arg3 = (size_t *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_char _matrix1;\n  \n  \n  size_t _size_t_temp2;\n  \n  \n  size_t _size_t_temp3;\n  \n  \n  {\n    _size_t_temp2 = 0;\n    arg2 = &_size_t_temp2;\n  }\n  \n  \n  {\n    _size_t_temp3 = 0;\n    arg3 = &_size_t_temp3;\n  }\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_char_min_index\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_char, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  gsl_matrix_char_min_index((gsl_matrix_char const *)arg1,arg2,arg3);\n  resultobj = SWIG_Py_Void();\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg2));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg3));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_char_minmax_index(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_char *arg1 = (gsl_matrix_char *) 0 ;\n  size_t *arg2 = (size_t *) 0 ;\n  size_t *arg3 = (size_t *) 0 ;\n  size_t *arg4 = (size_t *) 0 ;\n  size_t *arg5 = (size_t *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_char _matrix1;\n  \n  \n  size_t _size_t_temp2;\n  \n  \n  size_t _size_t_temp3;\n  \n  \n  size_t _size_t_temp4;\n  \n  \n  size_t _size_t_temp5;\n  \n  \n  {\n    _size_t_temp2 = 0;\n    arg2 = &_size_t_temp2;\n  }\n  \n  \n  {\n    _size_t_temp3 = 0;\n    arg3 = &_size_t_temp3;\n  }\n  \n  \n  {\n    _size_t_temp4 = 0;\n    arg4 = &_size_t_temp4;\n  }\n  \n  \n  {\n    _size_t_temp5 = 0;\n    arg5 = &_size_t_temp5;\n  }\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_char_minmax_index\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_char, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  gsl_matrix_char_minmax_index((gsl_matrix_char const *)arg1,arg2,arg3,arg4,arg5);\n  resultobj = SWIG_Py_Void();\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg2));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg3));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg4));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    PyObject *o;\n    o = PyInt_FromLong((long) (*arg5));\n    resultobj = SWIG_Python_AppendOutput(resultobj, o);\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_char_isnull(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_char *arg1 = (gsl_matrix_char *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_char _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_char_isnull\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_char, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (int)gsl_matrix_char_isnull((gsl_matrix_char const *)arg1);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_char_diagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_char *arg1 = (gsl_matrix_char *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  gsl_vector_char_view result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_char _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_char_diagonal\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_char, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = gsl_matrix_char_diagonal(arg1);\n  {\n    PyArrayObject * out = NULL; \n    gsl_vector_char_view vectmp; \n    PyGSL_array_index_t tmp;\n    if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_char_view, vectmp, tmp) != GSL_SUCCESS){\n      goto fail;\n    }\n    resultobj = PyGSL_array_return(out);\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_char_subdiagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_char *arg1 = (gsl_matrix_char *) 0 ;\n  size_t arg2 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\",(char *) \"k\", NULL \n  };\n  gsl_vector_char_view result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_char _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_char_subdiagonal\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_char, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_char_subdiagonal\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  result = gsl_matrix_char_subdiagonal(arg1,arg2);\n  {\n    PyArrayObject * out = NULL; \n    gsl_vector_char_view vectmp; \n    PyGSL_array_index_t tmp;\n    if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_char_view, vectmp, tmp) != GSL_SUCCESS){\n      goto fail;\n    }\n    resultobj = PyGSL_array_return(out);\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_char_superdiagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_char *arg1 = (gsl_matrix_char *) 0 ;\n  size_t arg2 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\",(char *) \"k\", NULL \n  };\n  gsl_vector_char_view result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_char _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_char_superdiagonal\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_char, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_char_superdiagonal\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  result = gsl_matrix_char_superdiagonal(arg1,arg2);\n  {\n    PyArrayObject * out = NULL; \n    gsl_vector_char_view vectmp; \n    PyGSL_array_index_t tmp;\n    if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_char_view, vectmp, tmp) != GSL_SUCCESS){\n      goto fail;\n    }\n    resultobj = PyGSL_array_return(out);\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_complex_set_zero(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_complex *arg1 = (gsl_vector_complex *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\", NULL \n  };\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_complex _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_complex_set_zero\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    int flag;\n    _vector1.vector.data = NULL;\n    flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1,\n      PyGSL_OUTPUT_ARRAY, gsl_vector_complex, 1, &stride);\n    if (flag != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  gsl_vector_complex_set_zero(arg1);\n  resultobj = SWIG_Py_Void();\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_complex_set_all(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_complex *arg1 = (gsl_vector_complex *) 0 ;\n  gsl_complex arg2 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\",(char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_complex _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_complex_set_all\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    int flag;\n    _vector1.vector.data = NULL;\n    flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1,\n      PyGSL_OUTPUT_ARRAY, gsl_vector_complex, 1, &stride);\n    if (flag != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  {\n    gsl_complex tmp;\n    if(PyGSL_PyCOMPLEX_TO_gsl_complex(obj1, &tmp) != GSL_SUCCESS)\n    goto fail;\n    arg2 = tmp;\n  }\n  gsl_vector_complex_set_all(arg1,arg2);\n  resultobj = SWIG_Py_Void();\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_complex_set_basis(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_complex *arg1 = (gsl_vector_complex *) 0 ;\n  size_t arg2 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\",(char *) \"i\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_complex _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_complex_set_basis\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    int flag;\n    _vector1.vector.data = NULL;\n    flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1,\n      PyGSL_OUTPUT_ARRAY, gsl_vector_complex, 1, &stride);\n    if (flag != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_vector_complex_set_basis\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  result = (int)gsl_vector_complex_set_basis(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_complex_fread(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_vector_complex *arg2 = (gsl_vector_complex *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN_SIZE_OUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector_complex _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_complex_fread\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride;\n    int flag;\n    _vector2.vector.data = NULL;\n    flag = PyGSL_VECTOR_GENERATE(obj1, arg2, _PyVector2, _vector2,\n      PyGSL_OUTPUT_ARRAY, gsl_vector_complex, 2, &stride);\n    if (flag != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_complex_fread(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert(_PyVector2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector2));\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_complex_fwrite(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_vector_complex *arg2 = (gsl_vector_complex *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector_complex _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_complex_fwrite\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2,\n        PyGSL_INPUT_ARRAY, gsl_vector_complex, 2, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_complex_fwrite(arg1,(gsl_vector_complex const *)arg2);\n  resultobj = SWIG_From_int((int)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_complex_fscanf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_vector_complex *arg2 = (gsl_vector_complex *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN_SIZE_OUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector_complex _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_complex_fscanf\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride;\n    int flag;\n    _vector2.vector.data = NULL;\n    flag = PyGSL_VECTOR_GENERATE(obj1, arg2, _PyVector2, _vector2,\n      PyGSL_OUTPUT_ARRAY, gsl_vector_complex, 2, &stride);\n    if (flag != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_complex_fscanf(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert(_PyVector2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector2));\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_complex_fprintf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_vector_complex *arg2 = (gsl_vector_complex *) 0 ;\n  char *arg3 = (char *) 0 ;\n  int res3 ;\n  char *buf3 = 0 ;\n  int alloc3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN\",(char *) \"format\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector_complex _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_vector_complex_fprintf\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2,\n        PyGSL_INPUT_ARRAY, gsl_vector_complex, 2, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3);\n  if (!SWIG_IsOK(res3)) {\n    SWIG_exception_fail(SWIG_ArgError(res3), \"in method '\" \"gsl_vector_complex_fprintf\" \"', argument \" \"3\"\" of type '\" \"char const *\"\"'\");\n  }\n  arg3 = (char *)(buf3);\n  result = (int)gsl_vector_complex_fprintf(arg1,(gsl_vector_complex const *)arg2,(char const *)arg3);\n  resultobj = SWIG_From_int((int)(result));\n  if (alloc3 == SWIG_NEWOBJ) free((char*)buf3);\n  return resultobj;\nfail:\n  if (alloc3 == SWIG_NEWOBJ) free((char*)buf3);\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_complex_reverse(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_complex *arg1 = (gsl_vector_complex *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_complex _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_complex_reverse\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_IO_ARRAY, gsl_vector_complex, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_complex_reverse(arg1);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_complex_swap(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_complex *arg1 = (gsl_vector_complex *) 0 ;\n  gsl_vector_complex *arg2 = (gsl_vector_complex *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"INOUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_complex _vector1;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector_complex _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_complex_swap\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_IO_ARRAY, gsl_vector_complex, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2,\n        PyGSL_IO_ARRAY, gsl_vector_complex, 2, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_complex_swap(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    assert(_PyVector2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector2));\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_complex_swap_elements(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_complex *arg1 = (gsl_vector_complex *) 0 ;\n  size_t arg2 ;\n  size_t arg3 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  size_t val3 ;\n  int ecode3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"i\",(char *) \"j\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_complex _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_vector_complex_swap_elements\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_IO_ARRAY, gsl_vector_complex, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_vector_complex_swap_elements\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  ecode3 = SWIG_AsVal_size_t(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_vector_complex_swap_elements\" \"', argument \" \"3\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg3 = (size_t)(val3);\n  result = (int)gsl_vector_complex_swap_elements(arg1,arg2,arg3);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_complex_isnull(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_complex *arg1 = (gsl_vector_complex *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_complex _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_complex_isnull\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector_complex, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_complex_isnull((gsl_vector_complex const *)arg1);\n  resultobj = SWIG_From_int((int)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_complex_set_zero(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_complex *arg1 = (gsl_matrix_complex *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_complex _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_complex_set_zero\",kwnames,&obj0)) SWIG_fail;\n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix_complex, 1, &stride) !=GSL_SUCCESS)\n    goto fail;\n  }\n  gsl_matrix_complex_set_zero(arg1);\n  resultobj = SWIG_Py_Void();\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_complex_set_all(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_complex *arg1 = (gsl_matrix_complex *) 0 ;\n  gsl_complex arg2 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\",(char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_complex _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_complex_set_all\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix_complex, 1, &stride) !=GSL_SUCCESS)\n    goto fail;\n  }\n  {\n    gsl_complex tmp;\n    if(PyGSL_PyCOMPLEX_TO_gsl_complex(obj1, &tmp) != GSL_SUCCESS)\n    goto fail;\n    arg2 = tmp;\n  }\n  gsl_matrix_complex_set_all(arg1,arg2);\n  resultobj = SWIG_Py_Void();\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_complex_set_identity(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_complex *arg1 = (gsl_matrix_complex *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_complex _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_complex_set_identity\",kwnames,&obj0)) SWIG_fail;\n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix_complex, 1, &stride) !=GSL_SUCCESS)\n    goto fail;\n  }\n  gsl_matrix_complex_set_identity(arg1);\n  resultobj = SWIG_Py_Void();\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_complex_fread(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_matrix_complex *arg2 = (gsl_matrix_complex *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN_SIZE_OUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix2 = NULL;\n  TYPE_VIEW_gsl_matrix_complex _matrix2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_complex_fread\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_GENERATE(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_OUTPUT_ARRAY, gsl_matrix_complex, 2, &stride) !=GSL_SUCCESS)\n    goto fail;\n  }\n  result = (int)gsl_matrix_complex_fread(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix2));\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_complex_fwrite(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_matrix_complex *arg2 = (gsl_matrix_complex *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix2 = NULL;\n  TYPE_VIEW_gsl_matrix_complex _matrix2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_complex_fwrite\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2,\n        PyGSL_INPUT_ARRAY, gsl_matrix_complex, 2, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (int)gsl_matrix_complex_fwrite(arg1,(gsl_matrix_complex const *)arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_complex_fscanf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_matrix_complex *arg2 = (gsl_matrix_complex *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN_SIZE_OUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix2 = NULL;\n  TYPE_VIEW_gsl_matrix_complex _matrix2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_complex_fscanf\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_GENERATE(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_OUTPUT_ARRAY, gsl_matrix_complex, 2, &stride) !=GSL_SUCCESS)\n    goto fail;\n  }\n  result = (int)gsl_matrix_complex_fscanf(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix2));\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_complex_fprintf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_matrix_complex *arg2 = (gsl_matrix_complex *) 0 ;\n  char *arg3 = (char *) 0 ;\n  int res3 ;\n  char *buf3 = 0 ;\n  int alloc3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN\",(char *) \"format\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix2 = NULL;\n  TYPE_VIEW_gsl_matrix_complex _matrix2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_matrix_complex_fprintf\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2,\n        PyGSL_INPUT_ARRAY, gsl_matrix_complex, 2, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3);\n  if (!SWIG_IsOK(res3)) {\n    SWIG_exception_fail(SWIG_ArgError(res3), \"in method '\" \"gsl_matrix_complex_fprintf\" \"', argument \" \"3\"\" of type '\" \"char const *\"\"'\");\n  }\n  arg3 = (char *)(buf3);\n  result = (int)gsl_matrix_complex_fprintf(arg1,(gsl_matrix_complex const *)arg2,(char const *)arg3);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  if (alloc3 == SWIG_NEWOBJ) free((char*)buf3);\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  if (alloc3 == SWIG_NEWOBJ) free((char*)buf3);\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_complex_swap(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_complex *arg1 = (gsl_matrix_complex *) 0 ;\n  gsl_matrix_complex *arg2 = (gsl_matrix_complex *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"INOUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_complex _matrix1;\n  \n  \n  PyArrayObject * _PyMatrix2 = NULL;\n  TYPE_VIEW_gsl_matrix_complex _matrix2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_complex_swap\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_IO_ARRAY, gsl_matrix_complex, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2,\n        PyGSL_IO_ARRAY, gsl_matrix_complex, 2, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (int)gsl_matrix_complex_swap(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    assert((PyObject *) _PyMatrix2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix2));\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_complex_swap_rows(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_complex *arg1 = (gsl_matrix_complex *) 0 ;\n  size_t arg2 ;\n  size_t arg3 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  size_t val3 ;\n  int ecode3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"i\",(char *) \"j\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_complex _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_matrix_complex_swap_rows\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_IO_ARRAY, gsl_matrix_complex, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_complex_swap_rows\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  ecode3 = SWIG_AsVal_size_t(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_matrix_complex_swap_rows\" \"', argument \" \"3\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg3 = (size_t)(val3);\n  result = (int)gsl_matrix_complex_swap_rows(arg1,arg2,arg3);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_complex_swap_columns(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_complex *arg1 = (gsl_matrix_complex *) 0 ;\n  size_t arg2 ;\n  size_t arg3 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  size_t val3 ;\n  int ecode3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"i\",(char *) \"j\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_complex _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_matrix_complex_swap_columns\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_IO_ARRAY, gsl_matrix_complex, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_complex_swap_columns\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  ecode3 = SWIG_AsVal_size_t(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_matrix_complex_swap_columns\" \"', argument \" \"3\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg3 = (size_t)(val3);\n  result = (int)gsl_matrix_complex_swap_columns(arg1,arg2,arg3);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_complex_swap_rowcol(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_complex *arg1 = (gsl_matrix_complex *) 0 ;\n  size_t arg2 ;\n  size_t arg3 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  size_t val3 ;\n  int ecode3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"i\",(char *) \"j\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_complex _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_matrix_complex_swap_rowcol\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_IO_ARRAY, gsl_matrix_complex, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_complex_swap_rowcol\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  ecode3 = SWIG_AsVal_size_t(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_matrix_complex_swap_rowcol\" \"', argument \" \"3\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg3 = (size_t)(val3);\n  result = (int)gsl_matrix_complex_swap_rowcol(arg1,arg2,arg3);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_complex_transpose(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_complex *arg1 = (gsl_matrix_complex *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_complex _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_complex_transpose\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_IO_ARRAY, gsl_matrix_complex, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (int)gsl_matrix_complex_transpose(arg1);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_complex_isnull(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_complex *arg1 = (gsl_matrix_complex *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_complex _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_complex_isnull\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_complex, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (int)gsl_matrix_complex_isnull((gsl_matrix_complex const *)arg1);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_complex_diagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_complex *arg1 = (gsl_matrix_complex *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  gsl_vector_complex_view result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_complex _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_complex_diagonal\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_complex, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = gsl_matrix_complex_diagonal(arg1);\n  {\n    PyArrayObject * out = NULL; \n    gsl_vector_complex_view vectmp; \n    PyGSL_array_index_t tmp;\n    if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_complex_view, vectmp, tmp) != GSL_SUCCESS){\n      goto fail;\n    }\n    resultobj = PyGSL_array_return(out);\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_complex_subdiagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_complex *arg1 = (gsl_matrix_complex *) 0 ;\n  size_t arg2 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\",(char *) \"k\", NULL \n  };\n  gsl_vector_complex_view result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_complex _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_complex_subdiagonal\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_complex, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_complex_subdiagonal\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  result = gsl_matrix_complex_subdiagonal(arg1,arg2);\n  {\n    PyArrayObject * out = NULL; \n    gsl_vector_complex_view vectmp; \n    PyGSL_array_index_t tmp;\n    if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_complex_view, vectmp, tmp) != GSL_SUCCESS){\n      goto fail;\n    }\n    resultobj = PyGSL_array_return(out);\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_complex_superdiagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_complex *arg1 = (gsl_matrix_complex *) 0 ;\n  size_t arg2 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\",(char *) \"k\", NULL \n  };\n  gsl_vector_complex_view result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_complex _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_complex_superdiagonal\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_complex, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_complex_superdiagonal\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  result = gsl_matrix_complex_superdiagonal(arg1,arg2);\n  {\n    PyArrayObject * out = NULL; \n    gsl_vector_complex_view vectmp; \n    PyGSL_array_index_t tmp;\n    if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_complex_view, vectmp, tmp) != GSL_SUCCESS){\n      goto fail;\n    }\n    resultobj = PyGSL_array_return(out);\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_complex_float_set_zero(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_complex_float *arg1 = (gsl_vector_complex_float *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\", NULL \n  };\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_complex_float _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_complex_float_set_zero\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    int flag;\n    _vector1.vector.data = NULL;\n    flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1,\n      PyGSL_OUTPUT_ARRAY, gsl_vector_complex_float, 1, &stride);\n    if (flag != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  gsl_vector_complex_float_set_zero(arg1);\n  resultobj = SWIG_Py_Void();\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_complex_float_set_all(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_complex_float *arg1 = (gsl_vector_complex_float *) 0 ;\n  gsl_complex_float arg2 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\",(char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_complex_float _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_complex_float_set_all\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    int flag;\n    _vector1.vector.data = NULL;\n    flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1,\n      PyGSL_OUTPUT_ARRAY, gsl_vector_complex_float, 1, &stride);\n    if (flag != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  {\n    gsl_complex_float tmp;\n    if(PyGSL_PyCOMPLEX_TO_gsl_complex_float(obj1, &tmp) != GSL_SUCCESS)\n    goto fail;\n    arg2 = tmp;\n  }\n  gsl_vector_complex_float_set_all(arg1,arg2);\n  resultobj = SWIG_Py_Void();\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_complex_float_set_basis(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_complex_float *arg1 = (gsl_vector_complex_float *) 0 ;\n  size_t arg2 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\",(char *) \"i\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_complex_float _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_complex_float_set_basis\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    int flag;\n    _vector1.vector.data = NULL;\n    flag = PyGSL_VECTOR_GENERATE(obj0, arg1, _PyVector1, _vector1,\n      PyGSL_OUTPUT_ARRAY, gsl_vector_complex_float, 1, &stride);\n    if (flag != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_vector_complex_float_set_basis\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  result = (int)gsl_vector_complex_float_set_basis(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_complex_float_fread(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_vector_complex_float *arg2 = (gsl_vector_complex_float *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN_SIZE_OUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector_complex_float _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_complex_float_fread\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride;\n    int flag;\n    _vector2.vector.data = NULL;\n    flag = PyGSL_VECTOR_GENERATE(obj1, arg2, _PyVector2, _vector2,\n      PyGSL_OUTPUT_ARRAY, gsl_vector_complex_float, 2, &stride);\n    if (flag != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_complex_float_fread(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert(_PyVector2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector2));\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_complex_float_fwrite(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_vector_complex_float *arg2 = (gsl_vector_complex_float *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector_complex_float _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_complex_float_fwrite\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2,\n        PyGSL_INPUT_ARRAY, gsl_vector_complex_float, 2, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_complex_float_fwrite(arg1,(gsl_vector_complex_float const *)arg2);\n  resultobj = SWIG_From_int((int)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_complex_float_fscanf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_vector_complex_float *arg2 = (gsl_vector_complex_float *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN_SIZE_OUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector_complex_float _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_complex_float_fscanf\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride;\n    int flag;\n    _vector2.vector.data = NULL;\n    flag = PyGSL_VECTOR_GENERATE(obj1, arg2, _PyVector2, _vector2,\n      PyGSL_OUTPUT_ARRAY, gsl_vector_complex_float, 2, &stride);\n    if (flag != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_complex_float_fscanf(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert(_PyVector2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector2));\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_complex_float_fprintf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_vector_complex_float *arg2 = (gsl_vector_complex_float *) 0 ;\n  char *arg3 = (char *) 0 ;\n  int res3 ;\n  char *buf3 = 0 ;\n  int alloc3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN\",(char *) \"format\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector_complex_float _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_vector_complex_float_fprintf\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2,\n        PyGSL_INPUT_ARRAY, gsl_vector_complex_float, 2, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3);\n  if (!SWIG_IsOK(res3)) {\n    SWIG_exception_fail(SWIG_ArgError(res3), \"in method '\" \"gsl_vector_complex_float_fprintf\" \"', argument \" \"3\"\" of type '\" \"char const *\"\"'\");\n  }\n  arg3 = (char *)(buf3);\n  result = (int)gsl_vector_complex_float_fprintf(arg1,(gsl_vector_complex_float const *)arg2,(char const *)arg3);\n  resultobj = SWIG_From_int((int)(result));\n  if (alloc3 == SWIG_NEWOBJ) free((char*)buf3);\n  return resultobj;\nfail:\n  if (alloc3 == SWIG_NEWOBJ) free((char*)buf3);\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_complex_float_reverse(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_complex_float *arg1 = (gsl_vector_complex_float *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_complex_float _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_complex_float_reverse\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_IO_ARRAY, gsl_vector_complex_float, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_complex_float_reverse(arg1);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_complex_float_swap(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_complex_float *arg1 = (gsl_vector_complex_float *) 0 ;\n  gsl_vector_complex_float *arg2 = (gsl_vector_complex_float *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"INOUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_complex_float _vector1;\n  \n  \n  PyArrayObject * volatile _PyVector2 = NULL;\n  TYPE_VIEW_gsl_vector_complex_float _vector2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_vector_complex_float_swap\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_IO_ARRAY, gsl_vector_complex_float, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj1, arg2, _PyVector2, _vector2,\n        PyGSL_IO_ARRAY, gsl_vector_complex_float, 2, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_complex_float_swap(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    assert(_PyVector2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector2));\n    _PyVector2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_complex_float_swap_elements(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_complex_float *arg1 = (gsl_vector_complex_float *) 0 ;\n  size_t arg2 ;\n  size_t arg3 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  size_t val3 ;\n  int ecode3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"i\",(char *) \"j\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_complex_float _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_vector_complex_float_swap_elements\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_IO_ARRAY, gsl_vector_complex_float, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_vector_complex_float_swap_elements\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  ecode3 = SWIG_AsVal_size_t(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_vector_complex_float_swap_elements\" \"', argument \" \"3\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg3 = (size_t)(val3);\n  result = (int)gsl_vector_complex_float_swap_elements(arg1,arg2,arg3);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert(_PyVector1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyVector1));\n    _PyVector1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_vector_complex_float_isnull(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_vector_complex_float *arg1 = (gsl_vector_complex_float *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * volatile _PyVector1 = NULL;\n  TYPE_VIEW_gsl_vector_complex_float _vector1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_vector_complex_float_isnull\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride=0;\n    if(PyGSL_VECTOR_CONVERT(obj0, arg1, _PyVector1, _vector1,\n        PyGSL_INPUT_ARRAY, gsl_vector_complex_float, 1, &stride) != GSL_SUCCESS){\n      goto fail;\n    }\n  }\n  \n  result = (int)gsl_vector_complex_float_isnull((gsl_vector_complex_float const *)arg1);\n  resultobj = SWIG_From_int((int)(result));\n  return resultobj;\nfail:\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_complex_float_set_zero(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_complex_float *arg1 = (gsl_matrix_complex_float *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_complex_float _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_complex_float_set_zero\",kwnames,&obj0)) SWIG_fail;\n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix_complex_float, 1, &stride) !=GSL_SUCCESS)\n    goto fail;\n  }\n  gsl_matrix_complex_float_set_zero(arg1);\n  resultobj = SWIG_Py_Void();\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_complex_float_set_all(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_complex_float *arg1 = (gsl_matrix_complex_float *) 0 ;\n  gsl_complex_float arg2 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\",(char *) \"IN\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_complex_float _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_complex_float_set_all\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix_complex_float, 1, &stride) !=GSL_SUCCESS)\n    goto fail;\n  }\n  {\n    gsl_complex_float tmp;\n    if(PyGSL_PyCOMPLEX_TO_gsl_complex_float(obj1, &tmp) != GSL_SUCCESS)\n    goto fail;\n    arg2 = tmp;\n  }\n  gsl_matrix_complex_float_set_all(arg1,arg2);\n  resultobj = SWIG_Py_Void();\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_complex_float_set_identity(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_complex_float *arg1 = (gsl_matrix_complex_float *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN_SIZE_OUT\", NULL \n  };\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_complex_float _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_complex_float_set_identity\",kwnames,&obj0)) SWIG_fail;\n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_GENERATE(obj0, arg1, _PyMatrix1, _matrix1, PyGSL_OUTPUT_ARRAY, gsl_matrix_complex_float, 1, &stride) !=GSL_SUCCESS)\n    goto fail;\n  }\n  gsl_matrix_complex_float_set_identity(arg1);\n  resultobj = SWIG_Py_Void();\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_complex_float_fread(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_matrix_complex_float *arg2 = (gsl_matrix_complex_float *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN_SIZE_OUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix2 = NULL;\n  TYPE_VIEW_gsl_matrix_complex_float _matrix2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_complex_float_fread\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_GENERATE(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_OUTPUT_ARRAY, gsl_matrix_complex_float, 2, &stride) !=GSL_SUCCESS)\n    goto fail;\n  }\n  result = (int)gsl_matrix_complex_float_fread(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix2));\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_complex_float_fwrite(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_matrix_complex_float *arg2 = (gsl_matrix_complex_float *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix2 = NULL;\n  TYPE_VIEW_gsl_matrix_complex_float _matrix2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_complex_float_fwrite\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2,\n        PyGSL_INPUT_ARRAY, gsl_matrix_complex_float, 2, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (int)gsl_matrix_complex_float_fwrite(arg1,(gsl_matrix_complex_float const *)arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_complex_float_fscanf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_matrix_complex_float *arg2 = (gsl_matrix_complex_float *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN_SIZE_OUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix2 = NULL;\n  TYPE_VIEW_gsl_matrix_complex_float _matrix2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_complex_float_fscanf\",kwnames,&obj0,&obj1)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_GENERATE(obj1, arg2, _PyMatrix2, _matrix2, PyGSL_OUTPUT_ARRAY, gsl_matrix_complex_float, 2, &stride) !=GSL_SUCCESS)\n    goto fail;\n  }\n  result = (int)gsl_matrix_complex_float_fscanf(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix2));\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_complex_float_fprintf(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  FILE *arg1 = (FILE *) 0 ;\n  gsl_matrix_complex_float *arg2 = (gsl_matrix_complex_float *) 0 ;\n  char *arg3 = (char *) 0 ;\n  int res3 ;\n  char *buf3 = 0 ;\n  int alloc3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"stream\",(char *) \"IN\",(char *) \"format\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix2 = NULL;\n  TYPE_VIEW_gsl_matrix_complex_float _matrix2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_matrix_complex_float_fprintf\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  {\n    FUNC_MESS_BEGIN();\n    HANDLE_MINGW();\n    if (!PyFile_Check(obj0)) {\n      PyErr_SetString(PyExc_TypeError, \"Need a file!\");\n      PyGSL_add_traceback(NULL, \"typemaps/file_typemaps.i\", __FUNCTION__, 33);\n      goto fail;\n    }\n    FUNC_MESS(\"Convert Python File to C File\");\n    arg1 = PyFile_AsFile(obj0);\n    DEBUG_MESS(2, \"Using file at %p with filedes %d\", (void *) arg1, fileno(arg1));\n    assert(arg1 != NULL);\n    \n  }\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2,\n        PyGSL_INPUT_ARRAY, gsl_matrix_complex_float, 2, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3);\n  if (!SWIG_IsOK(res3)) {\n    SWIG_exception_fail(SWIG_ArgError(res3), \"in method '\" \"gsl_matrix_complex_float_fprintf\" \"', argument \" \"3\"\" of type '\" \"char const *\"\"'\");\n  }\n  arg3 = (char *)(buf3);\n  result = (int)gsl_matrix_complex_float_fprintf(arg1,(gsl_matrix_complex_float const *)arg2,(char const *)arg3);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  if (alloc3 == SWIG_NEWOBJ) free((char*)buf3);\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  if (alloc3 == SWIG_NEWOBJ) free((char*)buf3);\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_complex_float_swap(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_complex_float *arg1 = (gsl_matrix_complex_float *) 0 ;\n  gsl_matrix_complex_float *arg2 = (gsl_matrix_complex_float *) 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"INOUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_complex_float _matrix1;\n  \n  \n  PyArrayObject * _PyMatrix2 = NULL;\n  TYPE_VIEW_gsl_matrix_complex_float _matrix2;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_complex_float_swap\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_IO_ARRAY, gsl_matrix_complex_float, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj1, arg2, _PyMatrix2, _matrix2,\n        PyGSL_IO_ARRAY, gsl_matrix_complex_float, 2, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (int)gsl_matrix_complex_float_swap(arg1,arg2);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    assert((PyObject *) _PyMatrix2 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix2));\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix2);\n    _PyMatrix2 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_complex_float_swap_rows(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_complex_float *arg1 = (gsl_matrix_complex_float *) 0 ;\n  size_t arg2 ;\n  size_t arg3 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  size_t val3 ;\n  int ecode3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"i\",(char *) \"j\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_complex_float _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_matrix_complex_float_swap_rows\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_IO_ARRAY, gsl_matrix_complex_float, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_complex_float_swap_rows\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  ecode3 = SWIG_AsVal_size_t(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_matrix_complex_float_swap_rows\" \"', argument \" \"3\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg3 = (size_t)(val3);\n  result = (int)gsl_matrix_complex_float_swap_rows(arg1,arg2,arg3);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_complex_float_swap_columns(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_complex_float *arg1 = (gsl_matrix_complex_float *) 0 ;\n  size_t arg2 ;\n  size_t arg3 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  size_t val3 ;\n  int ecode3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"i\",(char *) \"j\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_complex_float _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_matrix_complex_float_swap_columns\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_IO_ARRAY, gsl_matrix_complex_float, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_complex_float_swap_columns\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  ecode3 = SWIG_AsVal_size_t(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_matrix_complex_float_swap_columns\" \"', argument \" \"3\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg3 = (size_t)(val3);\n  result = (int)gsl_matrix_complex_float_swap_columns(arg1,arg2,arg3);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_complex_float_swap_rowcol(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_complex_float *arg1 = (gsl_matrix_complex_float *) 0 ;\n  size_t arg2 ;\n  size_t arg3 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  size_t val3 ;\n  int ecode3 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  PyObject * obj2 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\",(char *) \"i\",(char *) \"j\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_complex_float _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OOO:gsl_matrix_complex_float_swap_rowcol\",kwnames,&obj0,&obj1,&obj2)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_IO_ARRAY, gsl_matrix_complex_float, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_complex_float_swap_rowcol\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  ecode3 = SWIG_AsVal_size_t(obj2, &val3);\n  if (!SWIG_IsOK(ecode3)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode3), \"in method '\" \"gsl_matrix_complex_float_swap_rowcol\" \"', argument \" \"3\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg3 = (size_t)(val3);\n  result = (int)gsl_matrix_complex_float_swap_rowcol(arg1,arg2,arg3);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_complex_float_transpose(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_complex_float *arg1 = (gsl_matrix_complex_float *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"INOUT\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_complex_float _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_complex_float_transpose\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_IO_ARRAY, gsl_matrix_complex_float, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (int)gsl_matrix_complex_float_transpose(arg1);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    assert((PyObject *) _PyMatrix1 != NULL);\n    resultobj = SWIG_Python_AppendOutput(resultobj,  PyGSL_array_return(_PyMatrix1));\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_complex_float_isnull(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_complex_float *arg1 = (gsl_matrix_complex_float *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  int result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_complex_float _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_complex_float_isnull\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_complex_float, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = (int)gsl_matrix_complex_float_isnull((gsl_matrix_complex_float const *)arg1);\n  resultobj = SWIG_From_int((int)(result));\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_complex_float_diagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_complex_float *arg1 = (gsl_matrix_complex_float *) 0 ;\n  PyObject * obj0 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\", NULL \n  };\n  gsl_vector_complex_float_view result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_complex_float _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"O:gsl_matrix_complex_float_diagonal\",kwnames,&obj0)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_complex_float, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  result = gsl_matrix_complex_float_diagonal(arg1);\n  {\n    PyArrayObject * out = NULL; \n    gsl_vector_complex_float_view vectmp; \n    PyGSL_array_index_t tmp;\n    if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_complex_float_view, vectmp, tmp) != GSL_SUCCESS){\n      goto fail;\n    }\n    resultobj = PyGSL_array_return(out);\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_complex_float_subdiagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_complex_float *arg1 = (gsl_matrix_complex_float *) 0 ;\n  size_t arg2 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\",(char *) \"k\", NULL \n  };\n  gsl_vector_complex_float_view result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_complex_float _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_complex_float_subdiagonal\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_complex_float, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_complex_float_subdiagonal\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  result = gsl_matrix_complex_float_subdiagonal(arg1,arg2);\n  {\n    PyArrayObject * out = NULL; \n    gsl_vector_complex_float_view vectmp; \n    PyGSL_array_index_t tmp;\n    if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_complex_float_view, vectmp, tmp) != GSL_SUCCESS){\n      goto fail;\n    }\n    resultobj = PyGSL_array_return(out);\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nSWIGINTERN PyObject *_wrap_gsl_matrix_complex_float_superdiagonal(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {\n  PyObject *resultobj = 0;\n  gsl_matrix_complex_float *arg1 = (gsl_matrix_complex_float *) 0 ;\n  size_t arg2 ;\n  size_t val2 ;\n  int ecode2 = 0 ;\n  PyObject * obj0 = 0 ;\n  PyObject * obj1 = 0 ;\n  char *  kwnames[] = {\n    (char *) \"IN\",(char *) \"k\", NULL \n  };\n  gsl_vector_complex_float_view result;\n  \n  \n  PyArrayObject * _PyMatrix1 = NULL;\n  TYPE_VIEW_gsl_matrix_complex_float _matrix1;\n  \n  if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\"OO:gsl_matrix_complex_float_superdiagonal\",kwnames,&obj0,&obj1)) SWIG_fail;\n  \n  {\n    PyGSL_array_index_t stride;\n    if(PyGSL_MATRIX_CONVERT(obj0, arg1, _PyMatrix1, _matrix1,\n        PyGSL_INPUT_ARRAY, gsl_matrix_complex_float, 1, &stride) != GSL_SUCCESS)\n    goto fail;\t  \n  }\n  \n  ecode2 = SWIG_AsVal_size_t(obj1, &val2);\n  if (!SWIG_IsOK(ecode2)) {\n    SWIG_exception_fail(SWIG_ArgError(ecode2), \"in method '\" \"gsl_matrix_complex_float_superdiagonal\" \"', argument \" \"2\"\" of type '\" \"size_t\"\"'\");\n  } \n  arg2 = (size_t)(val2);\n  result = gsl_matrix_complex_float_superdiagonal(arg1,arg2);\n  {\n    PyArrayObject * out = NULL; \n    gsl_vector_complex_float_view vectmp; \n    PyGSL_array_index_t tmp;\n    if(PyGSL_VECTORVIEW_COPY(out, result, gsl_vector_complex_float_view, vectmp, tmp) != GSL_SUCCESS){\n      goto fail;\n    }\n    resultobj = PyGSL_array_return(out);\n  }\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return resultobj;\nfail:\n  {\n    Py_XDECREF(_PyMatrix1);\n    _PyMatrix1 = NULL;\n    FUNC_MESS_END();\n  }\n  return NULL;\n}\n\n\nstatic PyMethodDef SwigMethods[] = {\n\t { (char *)\"gsl_vector_set_zero\", (PyCFunction) _wrap_gsl_vector_set_zero, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_set_all\", (PyCFunction) _wrap_gsl_vector_set_all, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_set_basis\", (PyCFunction) _wrap_gsl_vector_set_basis, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_fread\", (PyCFunction) _wrap_gsl_vector_fread, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_fwrite\", (PyCFunction) _wrap_gsl_vector_fwrite, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_fscanf\", (PyCFunction) _wrap_gsl_vector_fscanf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_fprintf\", (PyCFunction) _wrap_gsl_vector_fprintf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_reverse\", (PyCFunction) _wrap_gsl_vector_reverse, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_swap\", (PyCFunction) _wrap_gsl_vector_swap, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_swap_elements\", (PyCFunction) _wrap_gsl_vector_swap_elements, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_max\", (PyCFunction) _wrap_gsl_vector_max, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_min\", (PyCFunction) _wrap_gsl_vector_min, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_minmax\", (PyCFunction) _wrap_gsl_vector_minmax, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_max_index\", (PyCFunction) _wrap_gsl_vector_max_index, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_min_index\", (PyCFunction) _wrap_gsl_vector_min_index, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_minmax_index\", (PyCFunction) _wrap_gsl_vector_minmax_index, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_isnull\", (PyCFunction) _wrap_gsl_vector_isnull, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_set_zero\", (PyCFunction) _wrap_gsl_matrix_set_zero, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_set_all\", (PyCFunction) _wrap_gsl_matrix_set_all, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_set_identity\", (PyCFunction) _wrap_gsl_matrix_set_identity, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_fread\", (PyCFunction) _wrap_gsl_matrix_fread, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_fwrite\", (PyCFunction) _wrap_gsl_matrix_fwrite, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_fscanf\", (PyCFunction) _wrap_gsl_matrix_fscanf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_fprintf\", (PyCFunction) _wrap_gsl_matrix_fprintf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_swap\", (PyCFunction) _wrap_gsl_matrix_swap, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_swap_rows\", (PyCFunction) _wrap_gsl_matrix_swap_rows, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_swap_columns\", (PyCFunction) _wrap_gsl_matrix_swap_columns, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_swap_rowcol\", (PyCFunction) _wrap_gsl_matrix_swap_rowcol, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_transpose\", (PyCFunction) _wrap_gsl_matrix_transpose, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_max\", (PyCFunction) _wrap_gsl_matrix_max, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_min\", (PyCFunction) _wrap_gsl_matrix_min, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_minmax\", (PyCFunction) _wrap_gsl_matrix_minmax, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_max_index\", (PyCFunction) _wrap_gsl_matrix_max_index, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_min_index\", (PyCFunction) _wrap_gsl_matrix_min_index, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_minmax_index\", (PyCFunction) _wrap_gsl_matrix_minmax_index, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_isnull\", (PyCFunction) _wrap_gsl_matrix_isnull, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_diagonal\", (PyCFunction) _wrap_gsl_matrix_diagonal, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_subdiagonal\", (PyCFunction) _wrap_gsl_matrix_subdiagonal, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_superdiagonal\", (PyCFunction) _wrap_gsl_matrix_superdiagonal, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_float_set_zero\", (PyCFunction) _wrap_gsl_vector_float_set_zero, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_float_set_all\", (PyCFunction) _wrap_gsl_vector_float_set_all, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_float_set_basis\", (PyCFunction) _wrap_gsl_vector_float_set_basis, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_float_fread\", (PyCFunction) _wrap_gsl_vector_float_fread, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_float_fwrite\", (PyCFunction) _wrap_gsl_vector_float_fwrite, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_float_fscanf\", (PyCFunction) _wrap_gsl_vector_float_fscanf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_float_fprintf\", (PyCFunction) _wrap_gsl_vector_float_fprintf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_float_reverse\", (PyCFunction) _wrap_gsl_vector_float_reverse, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_float_swap\", (PyCFunction) _wrap_gsl_vector_float_swap, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_float_swap_elements\", (PyCFunction) _wrap_gsl_vector_float_swap_elements, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_float_max\", (PyCFunction) _wrap_gsl_vector_float_max, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_float_min\", (PyCFunction) _wrap_gsl_vector_float_min, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_float_minmax\", (PyCFunction) _wrap_gsl_vector_float_minmax, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_float_max_index\", (PyCFunction) _wrap_gsl_vector_float_max_index, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_float_min_index\", (PyCFunction) _wrap_gsl_vector_float_min_index, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_float_minmax_index\", (PyCFunction) _wrap_gsl_vector_float_minmax_index, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_float_isnull\", (PyCFunction) _wrap_gsl_vector_float_isnull, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_float_set_zero\", (PyCFunction) _wrap_gsl_matrix_float_set_zero, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_float_set_all\", (PyCFunction) _wrap_gsl_matrix_float_set_all, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_float_set_identity\", (PyCFunction) _wrap_gsl_matrix_float_set_identity, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_float_fread\", (PyCFunction) _wrap_gsl_matrix_float_fread, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_float_fwrite\", (PyCFunction) _wrap_gsl_matrix_float_fwrite, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_float_fscanf\", (PyCFunction) _wrap_gsl_matrix_float_fscanf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_float_fprintf\", (PyCFunction) _wrap_gsl_matrix_float_fprintf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_float_swap\", (PyCFunction) _wrap_gsl_matrix_float_swap, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_float_swap_rows\", (PyCFunction) _wrap_gsl_matrix_float_swap_rows, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_float_swap_columns\", (PyCFunction) _wrap_gsl_matrix_float_swap_columns, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_float_swap_rowcol\", (PyCFunction) _wrap_gsl_matrix_float_swap_rowcol, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_float_transpose\", (PyCFunction) _wrap_gsl_matrix_float_transpose, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_float_max\", (PyCFunction) _wrap_gsl_matrix_float_max, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_float_min\", (PyCFunction) _wrap_gsl_matrix_float_min, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_float_minmax\", (PyCFunction) _wrap_gsl_matrix_float_minmax, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_float_max_index\", (PyCFunction) _wrap_gsl_matrix_float_max_index, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_float_min_index\", (PyCFunction) _wrap_gsl_matrix_float_min_index, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_float_minmax_index\", (PyCFunction) _wrap_gsl_matrix_float_minmax_index, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_float_isnull\", (PyCFunction) _wrap_gsl_matrix_float_isnull, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_float_diagonal\", (PyCFunction) _wrap_gsl_matrix_float_diagonal, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_float_subdiagonal\", (PyCFunction) _wrap_gsl_matrix_float_subdiagonal, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_float_superdiagonal\", (PyCFunction) _wrap_gsl_matrix_float_superdiagonal, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_long_set_zero\", (PyCFunction) _wrap_gsl_vector_long_set_zero, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_long_set_all\", (PyCFunction) _wrap_gsl_vector_long_set_all, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_long_set_basis\", (PyCFunction) _wrap_gsl_vector_long_set_basis, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_long_fread\", (PyCFunction) _wrap_gsl_vector_long_fread, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_long_fwrite\", (PyCFunction) _wrap_gsl_vector_long_fwrite, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_long_fscanf\", (PyCFunction) _wrap_gsl_vector_long_fscanf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_long_fprintf\", (PyCFunction) _wrap_gsl_vector_long_fprintf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_long_reverse\", (PyCFunction) _wrap_gsl_vector_long_reverse, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_long_swap\", (PyCFunction) _wrap_gsl_vector_long_swap, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_long_swap_elements\", (PyCFunction) _wrap_gsl_vector_long_swap_elements, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_long_max\", (PyCFunction) _wrap_gsl_vector_long_max, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_long_min\", (PyCFunction) _wrap_gsl_vector_long_min, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_long_minmax\", (PyCFunction) _wrap_gsl_vector_long_minmax, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_long_max_index\", (PyCFunction) _wrap_gsl_vector_long_max_index, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_long_min_index\", (PyCFunction) _wrap_gsl_vector_long_min_index, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_long_minmax_index\", (PyCFunction) _wrap_gsl_vector_long_minmax_index, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_long_isnull\", (PyCFunction) _wrap_gsl_vector_long_isnull, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_long_set_zero\", (PyCFunction) _wrap_gsl_matrix_long_set_zero, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_long_set_all\", (PyCFunction) _wrap_gsl_matrix_long_set_all, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_long_set_identity\", (PyCFunction) _wrap_gsl_matrix_long_set_identity, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_long_fread\", (PyCFunction) _wrap_gsl_matrix_long_fread, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_long_fwrite\", (PyCFunction) _wrap_gsl_matrix_long_fwrite, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_long_fscanf\", (PyCFunction) _wrap_gsl_matrix_long_fscanf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_long_fprintf\", (PyCFunction) _wrap_gsl_matrix_long_fprintf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_long_swap\", (PyCFunction) _wrap_gsl_matrix_long_swap, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_long_swap_rows\", (PyCFunction) _wrap_gsl_matrix_long_swap_rows, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_long_swap_columns\", (PyCFunction) _wrap_gsl_matrix_long_swap_columns, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_long_swap_rowcol\", (PyCFunction) _wrap_gsl_matrix_long_swap_rowcol, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_long_transpose\", (PyCFunction) _wrap_gsl_matrix_long_transpose, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_long_max\", (PyCFunction) _wrap_gsl_matrix_long_max, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_long_min\", (PyCFunction) _wrap_gsl_matrix_long_min, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_long_minmax\", (PyCFunction) _wrap_gsl_matrix_long_minmax, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_long_max_index\", (PyCFunction) _wrap_gsl_matrix_long_max_index, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_long_min_index\", (PyCFunction) _wrap_gsl_matrix_long_min_index, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_long_minmax_index\", (PyCFunction) _wrap_gsl_matrix_long_minmax_index, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_long_isnull\", (PyCFunction) _wrap_gsl_matrix_long_isnull, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_long_diagonal\", (PyCFunction) _wrap_gsl_matrix_long_diagonal, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_long_subdiagonal\", (PyCFunction) _wrap_gsl_matrix_long_subdiagonal, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_long_superdiagonal\", (PyCFunction) _wrap_gsl_matrix_long_superdiagonal, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_int_set_zero\", (PyCFunction) _wrap_gsl_vector_int_set_zero, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_int_set_all\", (PyCFunction) _wrap_gsl_vector_int_set_all, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_int_set_basis\", (PyCFunction) _wrap_gsl_vector_int_set_basis, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_int_fread\", (PyCFunction) _wrap_gsl_vector_int_fread, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_int_fwrite\", (PyCFunction) _wrap_gsl_vector_int_fwrite, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_int_fscanf\", (PyCFunction) _wrap_gsl_vector_int_fscanf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_int_fprintf\", (PyCFunction) _wrap_gsl_vector_int_fprintf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_int_reverse\", (PyCFunction) _wrap_gsl_vector_int_reverse, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_int_swap\", (PyCFunction) _wrap_gsl_vector_int_swap, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_int_swap_elements\", (PyCFunction) _wrap_gsl_vector_int_swap_elements, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_int_max\", (PyCFunction) _wrap_gsl_vector_int_max, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_int_min\", (PyCFunction) _wrap_gsl_vector_int_min, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_int_minmax\", (PyCFunction) _wrap_gsl_vector_int_minmax, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_int_max_index\", (PyCFunction) _wrap_gsl_vector_int_max_index, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_int_min_index\", (PyCFunction) _wrap_gsl_vector_int_min_index, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_int_minmax_index\", (PyCFunction) _wrap_gsl_vector_int_minmax_index, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_int_isnull\", (PyCFunction) _wrap_gsl_vector_int_isnull, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_int_set_zero\", (PyCFunction) _wrap_gsl_matrix_int_set_zero, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_int_set_all\", (PyCFunction) _wrap_gsl_matrix_int_set_all, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_int_set_identity\", (PyCFunction) _wrap_gsl_matrix_int_set_identity, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_int_fread\", (PyCFunction) _wrap_gsl_matrix_int_fread, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_int_fwrite\", (PyCFunction) _wrap_gsl_matrix_int_fwrite, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_int_fscanf\", (PyCFunction) _wrap_gsl_matrix_int_fscanf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_int_fprintf\", (PyCFunction) _wrap_gsl_matrix_int_fprintf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_int_swap\", (PyCFunction) _wrap_gsl_matrix_int_swap, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_int_swap_rows\", (PyCFunction) _wrap_gsl_matrix_int_swap_rows, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_int_swap_columns\", (PyCFunction) _wrap_gsl_matrix_int_swap_columns, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_int_swap_rowcol\", (PyCFunction) _wrap_gsl_matrix_int_swap_rowcol, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_int_transpose\", (PyCFunction) _wrap_gsl_matrix_int_transpose, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_int_max\", (PyCFunction) _wrap_gsl_matrix_int_max, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_int_min\", (PyCFunction) _wrap_gsl_matrix_int_min, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_int_minmax\", (PyCFunction) _wrap_gsl_matrix_int_minmax, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_int_max_index\", (PyCFunction) _wrap_gsl_matrix_int_max_index, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_int_min_index\", (PyCFunction) _wrap_gsl_matrix_int_min_index, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_int_minmax_index\", (PyCFunction) _wrap_gsl_matrix_int_minmax_index, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_int_isnull\", (PyCFunction) _wrap_gsl_matrix_int_isnull, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_int_diagonal\", (PyCFunction) _wrap_gsl_matrix_int_diagonal, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_int_subdiagonal\", (PyCFunction) _wrap_gsl_matrix_int_subdiagonal, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_int_superdiagonal\", (PyCFunction) _wrap_gsl_matrix_int_superdiagonal, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_short_set_zero\", (PyCFunction) _wrap_gsl_vector_short_set_zero, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_short_set_all\", (PyCFunction) _wrap_gsl_vector_short_set_all, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_short_set_basis\", (PyCFunction) _wrap_gsl_vector_short_set_basis, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_short_fread\", (PyCFunction) _wrap_gsl_vector_short_fread, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_short_fwrite\", (PyCFunction) _wrap_gsl_vector_short_fwrite, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_short_fscanf\", (PyCFunction) _wrap_gsl_vector_short_fscanf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_short_fprintf\", (PyCFunction) _wrap_gsl_vector_short_fprintf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_short_reverse\", (PyCFunction) _wrap_gsl_vector_short_reverse, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_short_swap\", (PyCFunction) _wrap_gsl_vector_short_swap, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_short_swap_elements\", (PyCFunction) _wrap_gsl_vector_short_swap_elements, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_short_max\", (PyCFunction) _wrap_gsl_vector_short_max, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_short_min\", (PyCFunction) _wrap_gsl_vector_short_min, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_short_minmax\", (PyCFunction) _wrap_gsl_vector_short_minmax, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_short_max_index\", (PyCFunction) _wrap_gsl_vector_short_max_index, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_short_min_index\", (PyCFunction) _wrap_gsl_vector_short_min_index, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_short_minmax_index\", (PyCFunction) _wrap_gsl_vector_short_minmax_index, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_short_isnull\", (PyCFunction) _wrap_gsl_vector_short_isnull, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_short_set_zero\", (PyCFunction) _wrap_gsl_matrix_short_set_zero, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_short_set_all\", (PyCFunction) _wrap_gsl_matrix_short_set_all, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_short_set_identity\", (PyCFunction) _wrap_gsl_matrix_short_set_identity, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_short_fread\", (PyCFunction) _wrap_gsl_matrix_short_fread, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_short_fwrite\", (PyCFunction) _wrap_gsl_matrix_short_fwrite, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_short_fscanf\", (PyCFunction) _wrap_gsl_matrix_short_fscanf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_short_fprintf\", (PyCFunction) _wrap_gsl_matrix_short_fprintf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_short_swap\", (PyCFunction) _wrap_gsl_matrix_short_swap, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_short_swap_rows\", (PyCFunction) _wrap_gsl_matrix_short_swap_rows, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_short_swap_columns\", (PyCFunction) _wrap_gsl_matrix_short_swap_columns, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_short_swap_rowcol\", (PyCFunction) _wrap_gsl_matrix_short_swap_rowcol, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_short_transpose\", (PyCFunction) _wrap_gsl_matrix_short_transpose, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_short_max\", (PyCFunction) _wrap_gsl_matrix_short_max, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_short_min\", (PyCFunction) _wrap_gsl_matrix_short_min, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_short_minmax\", (PyCFunction) _wrap_gsl_matrix_short_minmax, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_short_max_index\", (PyCFunction) _wrap_gsl_matrix_short_max_index, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_short_min_index\", (PyCFunction) _wrap_gsl_matrix_short_min_index, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_short_minmax_index\", (PyCFunction) _wrap_gsl_matrix_short_minmax_index, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_short_isnull\", (PyCFunction) _wrap_gsl_matrix_short_isnull, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_short_diagonal\", (PyCFunction) _wrap_gsl_matrix_short_diagonal, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_short_subdiagonal\", (PyCFunction) _wrap_gsl_matrix_short_subdiagonal, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_short_superdiagonal\", (PyCFunction) _wrap_gsl_matrix_short_superdiagonal, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_char_set_zero\", (PyCFunction) _wrap_gsl_vector_char_set_zero, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_char_set_all\", (PyCFunction) _wrap_gsl_vector_char_set_all, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_char_set_basis\", (PyCFunction) _wrap_gsl_vector_char_set_basis, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_char_fread\", (PyCFunction) _wrap_gsl_vector_char_fread, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_char_fwrite\", (PyCFunction) _wrap_gsl_vector_char_fwrite, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_char_fscanf\", (PyCFunction) _wrap_gsl_vector_char_fscanf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_char_fprintf\", (PyCFunction) _wrap_gsl_vector_char_fprintf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_char_reverse\", (PyCFunction) _wrap_gsl_vector_char_reverse, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_char_swap\", (PyCFunction) _wrap_gsl_vector_char_swap, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_char_swap_elements\", (PyCFunction) _wrap_gsl_vector_char_swap_elements, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_char_max\", (PyCFunction) _wrap_gsl_vector_char_max, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_char_min\", (PyCFunction) _wrap_gsl_vector_char_min, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_char_minmax\", (PyCFunction) _wrap_gsl_vector_char_minmax, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_char_max_index\", (PyCFunction) _wrap_gsl_vector_char_max_index, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_char_min_index\", (PyCFunction) _wrap_gsl_vector_char_min_index, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_char_minmax_index\", (PyCFunction) _wrap_gsl_vector_char_minmax_index, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_char_isnull\", (PyCFunction) _wrap_gsl_vector_char_isnull, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_char_set_zero\", (PyCFunction) _wrap_gsl_matrix_char_set_zero, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_char_set_all\", (PyCFunction) _wrap_gsl_matrix_char_set_all, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_char_set_identity\", (PyCFunction) _wrap_gsl_matrix_char_set_identity, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_char_fread\", (PyCFunction) _wrap_gsl_matrix_char_fread, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_char_fwrite\", (PyCFunction) _wrap_gsl_matrix_char_fwrite, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_char_fscanf\", (PyCFunction) _wrap_gsl_matrix_char_fscanf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_char_fprintf\", (PyCFunction) _wrap_gsl_matrix_char_fprintf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_char_swap\", (PyCFunction) _wrap_gsl_matrix_char_swap, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_char_swap_rows\", (PyCFunction) _wrap_gsl_matrix_char_swap_rows, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_char_swap_columns\", (PyCFunction) _wrap_gsl_matrix_char_swap_columns, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_char_swap_rowcol\", (PyCFunction) _wrap_gsl_matrix_char_swap_rowcol, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_char_transpose\", (PyCFunction) _wrap_gsl_matrix_char_transpose, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_char_max\", (PyCFunction) _wrap_gsl_matrix_char_max, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_char_min\", (PyCFunction) _wrap_gsl_matrix_char_min, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_char_minmax\", (PyCFunction) _wrap_gsl_matrix_char_minmax, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_char_max_index\", (PyCFunction) _wrap_gsl_matrix_char_max_index, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_char_min_index\", (PyCFunction) _wrap_gsl_matrix_char_min_index, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_char_minmax_index\", (PyCFunction) _wrap_gsl_matrix_char_minmax_index, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_char_isnull\", (PyCFunction) _wrap_gsl_matrix_char_isnull, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_char_diagonal\", (PyCFunction) _wrap_gsl_matrix_char_diagonal, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_char_subdiagonal\", (PyCFunction) _wrap_gsl_matrix_char_subdiagonal, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_char_superdiagonal\", (PyCFunction) _wrap_gsl_matrix_char_superdiagonal, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_complex_set_zero\", (PyCFunction) _wrap_gsl_vector_complex_set_zero, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_complex_set_all\", (PyCFunction) _wrap_gsl_vector_complex_set_all, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_complex_set_basis\", (PyCFunction) _wrap_gsl_vector_complex_set_basis, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_complex_fread\", (PyCFunction) _wrap_gsl_vector_complex_fread, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_complex_fwrite\", (PyCFunction) _wrap_gsl_vector_complex_fwrite, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_complex_fscanf\", (PyCFunction) _wrap_gsl_vector_complex_fscanf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_complex_fprintf\", (PyCFunction) _wrap_gsl_vector_complex_fprintf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_complex_reverse\", (PyCFunction) _wrap_gsl_vector_complex_reverse, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_complex_swap\", (PyCFunction) _wrap_gsl_vector_complex_swap, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_complex_swap_elements\", (PyCFunction) _wrap_gsl_vector_complex_swap_elements, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_complex_isnull\", (PyCFunction) _wrap_gsl_vector_complex_isnull, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_complex_set_zero\", (PyCFunction) _wrap_gsl_matrix_complex_set_zero, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_complex_set_all\", (PyCFunction) _wrap_gsl_matrix_complex_set_all, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_complex_set_identity\", (PyCFunction) _wrap_gsl_matrix_complex_set_identity, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_complex_fread\", (PyCFunction) _wrap_gsl_matrix_complex_fread, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_complex_fwrite\", (PyCFunction) _wrap_gsl_matrix_complex_fwrite, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_complex_fscanf\", (PyCFunction) _wrap_gsl_matrix_complex_fscanf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_complex_fprintf\", (PyCFunction) _wrap_gsl_matrix_complex_fprintf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_complex_swap\", (PyCFunction) _wrap_gsl_matrix_complex_swap, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_complex_swap_rows\", (PyCFunction) _wrap_gsl_matrix_complex_swap_rows, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_complex_swap_columns\", (PyCFunction) _wrap_gsl_matrix_complex_swap_columns, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_complex_swap_rowcol\", (PyCFunction) _wrap_gsl_matrix_complex_swap_rowcol, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_complex_transpose\", (PyCFunction) _wrap_gsl_matrix_complex_transpose, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_complex_isnull\", (PyCFunction) _wrap_gsl_matrix_complex_isnull, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_complex_diagonal\", (PyCFunction) _wrap_gsl_matrix_complex_diagonal, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_complex_subdiagonal\", (PyCFunction) _wrap_gsl_matrix_complex_subdiagonal, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_complex_superdiagonal\", (PyCFunction) _wrap_gsl_matrix_complex_superdiagonal, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_complex_float_set_zero\", (PyCFunction) _wrap_gsl_vector_complex_float_set_zero, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_complex_float_set_all\", (PyCFunction) _wrap_gsl_vector_complex_float_set_all, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_complex_float_set_basis\", (PyCFunction) _wrap_gsl_vector_complex_float_set_basis, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_complex_float_fread\", (PyCFunction) _wrap_gsl_vector_complex_float_fread, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_complex_float_fwrite\", (PyCFunction) _wrap_gsl_vector_complex_float_fwrite, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_complex_float_fscanf\", (PyCFunction) _wrap_gsl_vector_complex_float_fscanf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_complex_float_fprintf\", (PyCFunction) _wrap_gsl_vector_complex_float_fprintf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_complex_float_reverse\", (PyCFunction) _wrap_gsl_vector_complex_float_reverse, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_complex_float_swap\", (PyCFunction) _wrap_gsl_vector_complex_float_swap, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_complex_float_swap_elements\", (PyCFunction) _wrap_gsl_vector_complex_float_swap_elements, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_vector_complex_float_isnull\", (PyCFunction) _wrap_gsl_vector_complex_float_isnull, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_complex_float_set_zero\", (PyCFunction) _wrap_gsl_matrix_complex_float_set_zero, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_complex_float_set_all\", (PyCFunction) _wrap_gsl_matrix_complex_float_set_all, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_complex_float_set_identity\", (PyCFunction) _wrap_gsl_matrix_complex_float_set_identity, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_complex_float_fread\", (PyCFunction) _wrap_gsl_matrix_complex_float_fread, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_complex_float_fwrite\", (PyCFunction) _wrap_gsl_matrix_complex_float_fwrite, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_complex_float_fscanf\", (PyCFunction) _wrap_gsl_matrix_complex_float_fscanf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_complex_float_fprintf\", (PyCFunction) _wrap_gsl_matrix_complex_float_fprintf, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_complex_float_swap\", (PyCFunction) _wrap_gsl_matrix_complex_float_swap, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_complex_float_swap_rows\", (PyCFunction) _wrap_gsl_matrix_complex_float_swap_rows, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_complex_float_swap_columns\", (PyCFunction) _wrap_gsl_matrix_complex_float_swap_columns, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_complex_float_swap_rowcol\", (PyCFunction) _wrap_gsl_matrix_complex_float_swap_rowcol, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_complex_float_transpose\", (PyCFunction) _wrap_gsl_matrix_complex_float_transpose, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_complex_float_isnull\", (PyCFunction) _wrap_gsl_matrix_complex_float_isnull, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_complex_float_diagonal\", (PyCFunction) _wrap_gsl_matrix_complex_float_diagonal, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_complex_float_subdiagonal\", (PyCFunction) _wrap_gsl_matrix_complex_float_subdiagonal, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { (char *)\"gsl_matrix_complex_float_superdiagonal\", (PyCFunction) _wrap_gsl_matrix_complex_float_superdiagonal, METH_VARARGS | METH_KEYWORDS, NULL},\n\t { NULL, NULL, 0, NULL }\n};\n\n\n/* -------- TYPE CONVERSION AND EQUIVALENCE RULES (BEGIN) -------- */\n\nstatic swig_type_info _swigt__p_FILE = {\"_p_FILE\", \"FILE *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_char = {\"_p_char\", \"char *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_double = {\"_p_double\", \"double *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_float = {\"_p_float\", \"float *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_complex = {\"_p_gsl_complex\", \"gsl_complex *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_complex_float = {\"_p_gsl_complex_float\", \"gsl_complex_float *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_matrix = {\"_p_gsl_matrix\", \"gsl_matrix *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_matrix_char = {\"_p_gsl_matrix_char\", \"gsl_matrix_char *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_matrix_complex = {\"_p_gsl_matrix_complex\", \"gsl_matrix_complex *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_matrix_complex_float = {\"_p_gsl_matrix_complex_float\", \"gsl_matrix_complex_float *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_matrix_float = {\"_p_gsl_matrix_float\", \"gsl_matrix_float *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_matrix_int = {\"_p_gsl_matrix_int\", \"gsl_matrix_int *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_matrix_long = {\"_p_gsl_matrix_long\", \"gsl_matrix_long *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_matrix_short = {\"_p_gsl_matrix_short\", \"gsl_matrix_short *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_vector = {\"_p_gsl_vector\", \"gsl_vector *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_vector_char = {\"_p_gsl_vector_char\", \"gsl_vector_char *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_vector_complex = {\"_p_gsl_vector_complex\", \"gsl_vector_complex *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_vector_complex_float = {\"_p_gsl_vector_complex_float\", \"gsl_vector_complex_float *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_vector_float = {\"_p_gsl_vector_float\", \"gsl_vector_float *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_vector_int = {\"_p_gsl_vector_int\", \"gsl_vector_int *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_vector_long = {\"_p_gsl_vector_long\", \"gsl_vector_long *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_gsl_vector_short = {\"_p_gsl_vector_short\", \"gsl_vector_short *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_int = {\"_p_int\", \"int *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_long = {\"_p_long\", \"long *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_short = {\"_p_short\", \"short *\", 0, 0, (void*)0, 0};\nstatic swig_type_info _swigt__p_unsigned_int = {\"_p_unsigned_int\", \"size_t *|unsigned int *\", 0, 0, (void*)0, 0};\n\nstatic swig_type_info *swig_type_initial[] = {\n  &_swigt__p_FILE,\n  &_swigt__p_char,\n  &_swigt__p_double,\n  &_swigt__p_float,\n  &_swigt__p_gsl_complex,\n  &_swigt__p_gsl_complex_float,\n  &_swigt__p_gsl_matrix,\n  &_swigt__p_gsl_matrix_char,\n  &_swigt__p_gsl_matrix_complex,\n  &_swigt__p_gsl_matrix_complex_float,\n  &_swigt__p_gsl_matrix_float,\n  &_swigt__p_gsl_matrix_int,\n  &_swigt__p_gsl_matrix_long,\n  &_swigt__p_gsl_matrix_short,\n  &_swigt__p_gsl_vector,\n  &_swigt__p_gsl_vector_char,\n  &_swigt__p_gsl_vector_complex,\n  &_swigt__p_gsl_vector_complex_float,\n  &_swigt__p_gsl_vector_float,\n  &_swigt__p_gsl_vector_int,\n  &_swigt__p_gsl_vector_long,\n  &_swigt__p_gsl_vector_short,\n  &_swigt__p_int,\n  &_swigt__p_long,\n  &_swigt__p_short,\n  &_swigt__p_unsigned_int,\n};\n\nstatic swig_cast_info _swigc__p_FILE[] = {  {&_swigt__p_FILE, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_char[] = {  {&_swigt__p_char, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_double[] = {  {&_swigt__p_double, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_float[] = {  {&_swigt__p_float, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_complex[] = {  {&_swigt__p_gsl_complex, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_complex_float[] = {  {&_swigt__p_gsl_complex_float, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_matrix[] = {  {&_swigt__p_gsl_matrix, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_matrix_char[] = {  {&_swigt__p_gsl_matrix_char, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_matrix_complex[] = {  {&_swigt__p_gsl_matrix_complex, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_matrix_complex_float[] = {  {&_swigt__p_gsl_matrix_complex_float, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_matrix_float[] = {  {&_swigt__p_gsl_matrix_float, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_matrix_int[] = {  {&_swigt__p_gsl_matrix_int, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_matrix_long[] = {  {&_swigt__p_gsl_matrix_long, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_matrix_short[] = {  {&_swigt__p_gsl_matrix_short, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_vector[] = {  {&_swigt__p_gsl_vector, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_vector_char[] = {  {&_swigt__p_gsl_vector_char, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_vector_complex[] = {  {&_swigt__p_gsl_vector_complex, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_vector_complex_float[] = {  {&_swigt__p_gsl_vector_complex_float, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_vector_float[] = {  {&_swigt__p_gsl_vector_float, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_vector_int[] = {  {&_swigt__p_gsl_vector_int, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_vector_long[] = {  {&_swigt__p_gsl_vector_long, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_gsl_vector_short[] = {  {&_swigt__p_gsl_vector_short, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_int[] = {  {&_swigt__p_int, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_long[] = {  {&_swigt__p_long, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_short[] = {  {&_swigt__p_short, 0, 0, 0},{0, 0, 0, 0}};\nstatic swig_cast_info _swigc__p_unsigned_int[] = {  {&_swigt__p_unsigned_int, 0, 0, 0},{0, 0, 0, 0}};\n\nstatic swig_cast_info *swig_cast_initial[] = {\n  _swigc__p_FILE,\n  _swigc__p_char,\n  _swigc__p_double,\n  _swigc__p_float,\n  _swigc__p_gsl_complex,\n  _swigc__p_gsl_complex_float,\n  _swigc__p_gsl_matrix,\n  _swigc__p_gsl_matrix_char,\n  _swigc__p_gsl_matrix_complex,\n  _swigc__p_gsl_matrix_complex_float,\n  _swigc__p_gsl_matrix_float,\n  _swigc__p_gsl_matrix_int,\n  _swigc__p_gsl_matrix_long,\n  _swigc__p_gsl_matrix_short,\n  _swigc__p_gsl_vector,\n  _swigc__p_gsl_vector_char,\n  _swigc__p_gsl_vector_complex,\n  _swigc__p_gsl_vector_complex_float,\n  _swigc__p_gsl_vector_float,\n  _swigc__p_gsl_vector_int,\n  _swigc__p_gsl_vector_long,\n  _swigc__p_gsl_vector_short,\n  _swigc__p_int,\n  _swigc__p_long,\n  _swigc__p_short,\n  _swigc__p_unsigned_int,\n};\n\n\n/* -------- TYPE CONVERSION AND EQUIVALENCE RULES (END) -------- */\n\nstatic swig_const_info swig_const_table[] = {\n{0, 0, 0, 0.0, 0, 0}};\n\n#ifdef __cplusplus\n}\n#endif\n/* -----------------------------------------------------------------------------\n * Type initialization:\n * This problem is tough by the requirement that no dynamic \n * memory is used. Also, since swig_type_info structures store pointers to \n * swig_cast_info structures and swig_cast_info structures store pointers back\n * to swig_type_info structures, we need some lookup code at initialization. \n * The idea is that swig generates all the structures that are needed. \n * The runtime then collects these partially filled structures. \n * The SWIG_InitializeModule function takes these initial arrays out of \n * swig_module, and does all the lookup, filling in the swig_module.types\n * array with the correct data and linking the correct swig_cast_info\n * structures together.\n *\n * The generated swig_type_info structures are assigned staticly to an initial \n * array. We just loop through that array, and handle each type individually.\n * First we lookup if this type has been already loaded, and if so, use the\n * loaded structure instead of the generated one. Then we have to fill in the\n * cast linked list. The cast data is initially stored in something like a\n * two-dimensional array. Each row corresponds to a type (there are the same\n * number of rows as there are in the swig_type_initial array). Each entry in\n * a column is one of the swig_cast_info structures for that type.\n * The cast_initial array is actually an array of arrays, because each row has\n * a variable number of columns. So to actually build the cast linked list,\n * we find the array of casts associated with the type, and loop through it \n * adding the casts to the list. The one last trick we need to do is making\n * sure the type pointer in the swig_cast_info struct is correct.\n *\n * First off, we lookup the cast->type name to see if it is already loaded. \n * There are three cases to handle:\n *  1) If the cast->type has already been loaded AND the type we are adding\n *     casting info to has not been loaded (it is in this module), THEN we\n *     replace the cast->type pointer with the type pointer that has already\n *     been loaded.\n *  2) If BOTH types (the one we are adding casting info to, and the \n *     cast->type) are loaded, THEN the cast info has already been loaded by\n *     the previous module so we just ignore it.\n *  3) Finally, if cast->type has not already been loaded, then we add that\n *     swig_cast_info to the linked list (because the cast->type) pointer will\n *     be correct.\n * ----------------------------------------------------------------------------- */\n\n#ifdef __cplusplus\nextern \"C\" {\n#if 0\n} /* c-mode */\n#endif\n#endif\n\n#if 0\n#define SWIGRUNTIME_DEBUG\n#endif\n\n\nSWIGRUNTIME void\nSWIG_InitializeModule(void *clientdata) {\n  size_t i;\n  swig_module_info *module_head, *iter;\n  int found, init;\n  \n  clientdata = clientdata;\n  \n  /* check to see if the circular list has been setup, if not, set it up */\n  if (swig_module.next==0) {\n    /* Initialize the swig_module */\n    swig_module.type_initial = swig_type_initial;\n    swig_module.cast_initial = swig_cast_initial;\n    swig_module.next = &swig_module;\n    init = 1;\n  } else {\n    init = 0;\n  }\n  \n  /* Try and load any already created modules */\n  module_head = SWIG_GetModule(clientdata);\n  if (!module_head) {\n    /* This is the first module loaded for this interpreter */\n    /* so set the swig module into the interpreter */\n    SWIG_SetModule(clientdata, &swig_module);\n    module_head = &swig_module;\n  } else {\n    /* the interpreter has loaded a SWIG module, but has it loaded this one? */\n    found=0;\n    iter=module_head;\n    do {\n      if (iter==&swig_module) {\n        found=1;\n        break;\n      }\n      iter=iter->next;\n    } while (iter!= module_head);\n    \n    /* if the is found in the list, then all is done and we may leave */\n    if (found) return;\n    /* otherwise we must add out module into the list */\n    swig_module.next = module_head->next;\n    module_head->next = &swig_module;\n  }\n  \n  /* When multiple interpeters are used, a module could have already been initialized in\n       a different interpreter, but not yet have a pointer in this interpreter.\n       In this case, we do not want to continue adding types... everything should be\n       set up already */\n  if (init == 0) return;\n  \n  /* Now work on filling in swig_module.types */\n#ifdef SWIGRUNTIME_DEBUG\n  printf(\"SWIG_InitializeModule: size %d\\n\", swig_module.size);\n#endif\n  for (i = 0; i < swig_module.size; ++i) {\n    swig_type_info *type = 0;\n    swig_type_info *ret;\n    swig_cast_info *cast;\n    \n#ifdef SWIGRUNTIME_DEBUG\n    printf(\"SWIG_InitializeModule: type %d %s\\n\", i, swig_module.type_initial[i]->name);\n#endif\n    \n    /* if there is another module already loaded */\n    if (swig_module.next != &swig_module) {\n      type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name);\n    }\n    if (type) {\n      /* Overwrite clientdata field */\n#ifdef SWIGRUNTIME_DEBUG\n      printf(\"SWIG_InitializeModule: found type %s\\n\", type->name);\n#endif\n      if (swig_module.type_initial[i]->clientdata) {\n        type->clientdata = swig_module.type_initial[i]->clientdata;\n#ifdef SWIGRUNTIME_DEBUG\n        printf(\"SWIG_InitializeModule: found and overwrite type %s \\n\", type->name);\n#endif\n      }\n    } else {\n      type = swig_module.type_initial[i];\n    }\n    \n    /* Insert casting types */\n    cast = swig_module.cast_initial[i];\n    while (cast->type) {\n      /* Don't need to add information already in the list */\n      ret = 0;\n#ifdef SWIGRUNTIME_DEBUG\n      printf(\"SWIG_InitializeModule: look cast %s\\n\", cast->type->name);\n#endif\n      if (swig_module.next != &swig_module) {\n        ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name);\n#ifdef SWIGRUNTIME_DEBUG\n        if (ret) printf(\"SWIG_InitializeModule: found cast %s\\n\", ret->name);\n#endif\n      }\n      if (ret) {\n        if (type == swig_module.type_initial[i]) {\n#ifdef SWIGRUNTIME_DEBUG\n          printf(\"SWIG_InitializeModule: skip old type %s\\n\", ret->name);\n#endif\n          cast->type = ret;\n          ret = 0;\n        } else {\n          /* Check for casting already in the list */\n          swig_cast_info *ocast = SWIG_TypeCheck(ret->name, type);\n#ifdef SWIGRUNTIME_DEBUG\n          if (ocast) printf(\"SWIG_InitializeModule: skip old cast %s\\n\", ret->name);\n#endif\n          if (!ocast) ret = 0;\n        }\n      }\n      \n      if (!ret) {\n#ifdef SWIGRUNTIME_DEBUG\n        printf(\"SWIG_InitializeModule: adding cast %s\\n\", cast->type->name);\n#endif\n        if (type->cast) {\n          type->cast->prev = cast;\n          cast->next = type->cast;\n        }\n        type->cast = cast;\n      }\n      cast++;\n    }\n    /* Set entry in modules->types array equal to the type */\n    swig_module.types[i] = type;\n  }\n  swig_module.types[i] = 0;\n  \n#ifdef SWIGRUNTIME_DEBUG\n  printf(\"**** SWIG_InitializeModule: Cast List ******\\n\");\n  for (i = 0; i < swig_module.size; ++i) {\n    int j = 0;\n    swig_cast_info *cast = swig_module.cast_initial[i];\n    printf(\"SWIG_InitializeModule: type %d %s\\n\", i, swig_module.type_initial[i]->name);\n    while (cast->type) {\n      printf(\"SWIG_InitializeModule: cast type %s\\n\", cast->type->name);\n      cast++;\n      ++j;\n    }\n    printf(\"---- Total casts: %d\\n\",j);\n  }\n  printf(\"**** SWIG_InitializeModule: Cast List ******\\n\");\n#endif\n}\n\n/* This function will propagate the clientdata field of type to\n* any new swig_type_info structures that have been added into the list\n* of equivalent types.  It is like calling\n* SWIG_TypeClientData(type, clientdata) a second time.\n*/\nSWIGRUNTIME void\nSWIG_PropagateClientData(void) {\n  size_t i;\n  swig_cast_info *equiv;\n  static int init_run = 0;\n  \n  if (init_run) return;\n  init_run = 1;\n  \n  for (i = 0; i < swig_module.size; i++) {\n    if (swig_module.types[i]->clientdata) {\n      equiv = swig_module.types[i]->cast;\n      while (equiv) {\n        if (!equiv->converter) {\n          if (equiv->type && !equiv->type->clientdata)\n          SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata);\n        }\n        equiv = equiv->next;\n      }\n    }\n  }\n}\n\n#ifdef __cplusplus\n#if 0\n{\n  /* c-mode */\n#endif\n}\n#endif\n\n\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n  \n  /* Python-specific SWIG API */\n#define SWIG_newvarlink()                             SWIG_Python_newvarlink()\n#define SWIG_addvarlink(p, name, get_attr, set_attr)  SWIG_Python_addvarlink(p, name, get_attr, set_attr)\n#define SWIG_InstallConstants(d, constants)           SWIG_Python_InstallConstants(d, constants)\n  \n  /* -----------------------------------------------------------------------------\n   * global variable support code.\n   * ----------------------------------------------------------------------------- */\n  \n  typedef struct swig_globalvar {\n    char       *name;                  /* Name of global variable */\n    PyObject *(*get_attr)(void);       /* Return the current value */\n    int       (*set_attr)(PyObject *); /* Set the value */\n    struct swig_globalvar *next;\n  } swig_globalvar;\n  \n  typedef struct swig_varlinkobject {\n    PyObject_HEAD\n    swig_globalvar *vars;\n  } swig_varlinkobject;\n  \n  SWIGINTERN PyObject *\n  swig_varlink_repr(swig_varlinkobject *SWIGUNUSEDPARM(v)) {\n    return PyString_FromString(\"<Swig global variables>\");\n  }\n  \n  SWIGINTERN PyObject *\n  swig_varlink_str(swig_varlinkobject *v) {\n    PyObject *str = PyString_FromString(\"(\");\n    swig_globalvar  *var;\n    for (var = v->vars; var; var=var->next) {\n      PyString_ConcatAndDel(&str,PyString_FromString(var->name));\n      if (var->next) PyString_ConcatAndDel(&str,PyString_FromString(\", \"));\n    }\n    PyString_ConcatAndDel(&str,PyString_FromString(\")\"));\n    return str;\n  }\n  \n  SWIGINTERN int\n  swig_varlink_print(swig_varlinkobject *v, FILE *fp, int SWIGUNUSEDPARM(flags)) {\n    PyObject *str = swig_varlink_str(v);\n    fprintf(fp,\"Swig global variables \");\n    fprintf(fp,\"%s\\n\", PyString_AsString(str));\n    Py_DECREF(str);\n    return 0;\n  }\n  \n  SWIGINTERN void\n  swig_varlink_dealloc(swig_varlinkobject *v) {\n    swig_globalvar *var = v->vars;\n    while (var) {\n      swig_globalvar *n = var->next;\n      free(var->name);\n      free(var);\n      var = n;\n    }\n  }\n  \n  SWIGINTERN PyObject *\n  swig_varlink_getattr(swig_varlinkobject *v, char *n) {\n    PyObject *res = NULL;\n    swig_globalvar *var = v->vars;\n    while (var) {\n      if (strcmp(var->name,n) == 0) {\n        res = (*var->get_attr)();\n        break;\n      }\n      var = var->next;\n    }\n    if (res == NULL && !PyErr_Occurred()) {\n      PyErr_SetString(PyExc_NameError,\"Unknown C global variable\");\n    }\n    return res;\n  }\n  \n  SWIGINTERN int\n  swig_varlink_setattr(swig_varlinkobject *v, char *n, PyObject *p) {\n    int res = 1;\n    swig_globalvar *var = v->vars;\n    while (var) {\n      if (strcmp(var->name,n) == 0) {\n        res = (*var->set_attr)(p);\n        break;\n      }\n      var = var->next;\n    }\n    if (res == 1 && !PyErr_Occurred()) {\n      PyErr_SetString(PyExc_NameError,\"Unknown C global variable\");\n    }\n    return res;\n  }\n  \n  SWIGINTERN PyTypeObject*\n  swig_varlink_type(void) {\n    static char varlink__doc__[] = \"Swig var link object\";\n    static PyTypeObject varlink_type;\n    static int type_init = 0;  \n    if (!type_init) {\n      const PyTypeObject tmp\n      = {\n        PyObject_HEAD_INIT(NULL)\n        0,                                  /* Number of items in variable part (ob_size) */\n        (char *)\"swigvarlink\",              /* Type name (tp_name) */\n        sizeof(swig_varlinkobject),         /* Basic size (tp_basicsize) */\n        0,                                  /* Itemsize (tp_itemsize) */\n        (destructor) swig_varlink_dealloc,   /* Deallocator (tp_dealloc) */ \n        (printfunc) swig_varlink_print,     /* Print (tp_print) */\n        (getattrfunc) swig_varlink_getattr, /* get attr (tp_getattr) */\n        (setattrfunc) swig_varlink_setattr, /* Set attr (tp_setattr) */\n        0,                                  /* tp_compare */\n        (reprfunc) swig_varlink_repr,       /* tp_repr */\n        0,                                  /* tp_as_number */\n        0,                                  /* tp_as_sequence */\n        0,                                  /* tp_as_mapping */\n        0,                                  /* tp_hash */\n        0,                                  /* tp_call */\n        (reprfunc)swig_varlink_str,        /* tp_str */\n        0,                                  /* tp_getattro */\n        0,                                  /* tp_setattro */\n        0,                                  /* tp_as_buffer */\n        0,                                  /* tp_flags */\n        varlink__doc__,                     /* tp_doc */\n        0,                                  /* tp_traverse */\n        0,                                  /* tp_clear */\n        0,                                  /* tp_richcompare */\n        0,                                  /* tp_weaklistoffset */\n#if PY_VERSION_HEX >= 0x02020000\n        0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* tp_iter -> tp_weaklist */\n#endif\n#if PY_VERSION_HEX >= 0x02030000\n        0,                                  /* tp_del */\n#endif\n#ifdef COUNT_ALLOCS\n        0,0,0,0                             /* tp_alloc -> tp_next */\n#endif\n      };\n      varlink_type = tmp;\n      varlink_type.ob_type = &PyType_Type;\n      type_init = 1;\n    }\n    return &varlink_type;\n  }\n  \n  /* Create a variable linking object for use later */\n  SWIGINTERN PyObject *\n  SWIG_Python_newvarlink(void) {\n    swig_varlinkobject *result = PyObject_NEW(swig_varlinkobject, swig_varlink_type());\n    if (result) {\n      result->vars = 0;\n    }\n    return ((PyObject*) result);\n  }\n  \n  SWIGINTERN void \n  SWIG_Python_addvarlink(PyObject *p, char *name, PyObject *(*get_attr)(void), int (*set_attr)(PyObject *p)) {\n    swig_varlinkobject *v = (swig_varlinkobject *) p;\n    swig_globalvar *gv = (swig_globalvar *) malloc(sizeof(swig_globalvar));\n    if (gv) {\n      size_t size = strlen(name)+1;\n      gv->name = (char *)malloc(size);\n      if (gv->name) {\n        strncpy(gv->name,name,size);\n        gv->get_attr = get_attr;\n        gv->set_attr = set_attr;\n        gv->next = v->vars;\n      }\n    }\n    v->vars = gv;\n  }\n  \n  SWIGINTERN PyObject *\n  SWIG_globals(void) {\n    static PyObject *_SWIG_globals = 0; \n    if (!_SWIG_globals) _SWIG_globals = SWIG_newvarlink();  \n    return _SWIG_globals;\n  }\n  \n  /* -----------------------------------------------------------------------------\n   * constants/methods manipulation\n   * ----------------------------------------------------------------------------- */\n  \n  /* Install Constants */\n  SWIGINTERN void\n  SWIG_Python_InstallConstants(PyObject *d, swig_const_info constants[]) {\n    PyObject *obj = 0;\n    size_t i;\n    for (i = 0; constants[i].type; ++i) {\n      switch(constants[i].type) {\n      case SWIG_PY_POINTER:\n        obj = SWIG_NewPointerObj(constants[i].pvalue, *(constants[i]).ptype,0);\n        break;\n      case SWIG_PY_BINARY:\n        obj = SWIG_NewPackedObj(constants[i].pvalue, constants[i].lvalue, *(constants[i].ptype));\n        break;\n      default:\n        obj = 0;\n        break;\n      }\n      if (obj) {\n        PyDict_SetItemString(d, constants[i].name, obj);\n        Py_DECREF(obj);\n      }\n    }\n  }\n  \n  /* -----------------------------------------------------------------------------*/\n  /* Fix SwigMethods to carry the callback ptrs when needed */\n  /* -----------------------------------------------------------------------------*/\n  \n  SWIGINTERN void\n  SWIG_Python_FixMethods(PyMethodDef *methods,\n    swig_const_info *const_table,\n    swig_type_info **types,\n    swig_type_info **types_initial) {\n    size_t i;\n    for (i = 0; methods[i].ml_name; ++i) {\n      const char *c = methods[i].ml_doc;\n      if (c && (c = strstr(c, \"swig_ptr: \"))) {\n        int j;\n        swig_const_info *ci = 0;\n        const char *name = c + 10;\n        for (j = 0; const_table[j].type; ++j) {\n          if (strncmp(const_table[j].name, name, \n              strlen(const_table[j].name)) == 0) {\n            ci = &(const_table[j]);\n            break;\n          }\n        }\n        if (ci) {\n          size_t shift = (ci->ptype) - types;\n          swig_type_info *ty = types_initial[shift];\n          size_t ldoc = (c - methods[i].ml_doc);\n          size_t lptr = strlen(ty->name)+2*sizeof(void*)+2;\n          char *ndoc = (char*)malloc(ldoc + lptr + 10);\n          if (ndoc) {\n            char *buff = ndoc;\n            void *ptr = (ci->type == SWIG_PY_POINTER) ? ci->pvalue : 0;\n            if (ptr) {\n              strncpy(buff, methods[i].ml_doc, ldoc);\n              buff += ldoc;\n              strncpy(buff, \"swig_ptr: \", 10);\n              buff += 10;\n              SWIG_PackVoidPtr(buff, ptr, ty->name, lptr);\n              methods[i].ml_doc = ndoc;\n            }\n          }\n        }\n      }\n    }\n  } \n  \n#ifdef __cplusplus\n}\n#endif\n\n/* -----------------------------------------------------------------------------*\n *  Partial Init method\n * -----------------------------------------------------------------------------*/\n\n#ifdef __cplusplus\nextern \"C\"\n#endif\nSWIGEXPORT void SWIG_init(void) {\n  PyObject *m, *d;\n  \n  /* Fix SwigMethods to carry the callback ptrs when needed */\n  SWIG_Python_FixMethods(SwigMethods, swig_const_table, swig_types, swig_type_initial);\n  \n  m = Py_InitModule((char *) SWIG_name, SwigMethods);\n  d = PyModule_GetDict(m);\n  \n  SWIG_InitializeModule(0);\n  SWIG_InstallConstants(d,swig_const_table);\n  \n  \n  \n  init_pygsl();\n  \n  \n  pygsl_module_for_error_treatment = m;\n  \n}\n\n", "meta": {"hexsha": "be2bfb86925c9e0e8c5d6ce8f63fe00a5e074c4b", "size": 559751, "ext": "c", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/swig_src/block_wrap.c", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/swig_src/block_wrap.c", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/swig_src/block_wrap.c", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 28.9711195073, "max_line_length": 150, "alphanum_fraction": 0.6712413198, "num_tokens": 173790, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.05749328041530818, "lm_q2_score": 0.029760092117348452, "lm_q1q2_score": 0.001711005321288117}}
{"text": "/**\n * VGMTrans (c) - 2002-2021\n * Licensed under the zlib license\n * See the included LICENSE for more information\n */\n\n#pragma once\n\n#include <vector>\n#include <fluidsynth.h>\n#include <gsl-lite.hpp>\n#include <QObject>\n#include <QString>\n\nclass VGMColl;\n\nclass MusicPlayer : public QObject {\n  Q_OBJECT\npublic:\n  static auto &the() {\n    static MusicPlayer instance;\n    return instance;\n  }\n\n  MusicPlayer(const MusicPlayer &) = delete;\n  MusicPlayer &operator=(const MusicPlayer &) = delete;\n  MusicPlayer(MusicPlayer &&) = delete;\n  MusicPlayer &operator=(MusicPlayer &&) = delete;\n\n  ~MusicPlayer();\n\n  /**\n   * Toggles the status of the player\n   * @returns true if the player is playing\n   */\n  bool toggle();\n  /**\n   * Stops the player (unloads resources)\n   */\n  void stop();\n  /**\n   * Moves the player position\n   * @param position relative to song start\n   */\n  void seek(int position);\n\n  /**\n   * Returns the title of the song currently playing\n   * @return the song title\n   */\n  [[nodiscard]] QString songTitle() const;\n\n  /**\n   * Loads a VGMColl for playback\n   * @param collection\n   * @return true if data was loaded correctly\n   */\n  bool playCollection(VGMColl *collection);\n\n  /**\n   * Checks whether the player is playing\n   * @return true if playing\n   */\n  [[nodiscard]] bool playing() const;\n  /**\n   * The number of MIDI ticks elapsed since the player was started\n   * @return number of ticks relative to song start\n   */\n  [[nodiscard]] int elapsedTicks() const;\n  /**\n   * The total number of MIDI ticks in the song\n   * @return total ticks in the song\n   */\n  [[nodiscard]] int totalTicks() const;\n\n  /**\n   * Gets all the audio driver the player supports\n   * @return the driver list\n   */\n  [[nodiscard]] std::vector<const char *> getAvailableDrivers() const;\n  /**\n   * Changes the current audio driver and restarts playing\n   * @param driver_name\n   * @return true if the driver changed\n   */\n  bool setAudioDriver(const char *driver_name);\n\n  /**\n   * Checks the value of a setting of the player corresponds to the passed value\n   * @param setting\n   * @param value\n   * @return true if the value matches\n   */\n  [[nodiscard]] bool checkSetting(const char *setting, const char *value) const;\n  /**\n   * Sets a parameter of the player to the corrisponding passed value\n   * @param setting\n   * @param value\n   */\n  void updateSetting(const char *setting, const char *value);\n\nsignals:\n  void statusChange(bool playing);\n  void playbackPositionChanged(int current, int max);\n\nprivate:\n  MusicPlayer();\n\n  fluid_settings_t *m_settings = nullptr;\n  fluid_synth_t *m_synth = nullptr;\n  fluid_audio_driver_t *m_active_driver = nullptr;\n  fluid_player_t *m_active_player = nullptr;\n  VGMColl *m_active_coll = nullptr;\n\n  void makeSettings();\n  void makeSynth();\n  void makePlayer();\n};\n", "meta": {"hexsha": "9890c3199c7cc0ca6de8ee326c1bbc5099af98f0", "size": 2816, "ext": "h", "lang": "C", "max_stars_repo_path": "src/ui/qt/MusicPlayer.h", "max_stars_repo_name": "Sci3ntia/vgmtrans", "max_stars_repo_head_hexsha": "39d4c74ad2380ca9dca00535ecb8c9c1c56f5d78", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 538.0, "max_stars_repo_stars_event_min_datetime": "2015-02-22T22:10:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T22:57:42.000Z", "max_issues_repo_path": "src/ui/qt/MusicPlayer.h", "max_issues_repo_name": "DubiousDoggo/vgmtrans", "max_issues_repo_head_hexsha": "fa032cb66c63af2af2fb3c3d23fbf0582d465618", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 230.0, "max_issues_repo_issues_event_min_datetime": "2015-01-04T14:29:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-28T17:25:02.000Z", "max_forks_repo_path": "src/ui/qt/MusicPlayer.h", "max_forks_repo_name": "DubiousDoggo/vgmtrans", "max_forks_repo_head_hexsha": "fa032cb66c63af2af2fb3c3d23fbf0582d465618", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 105.0, "max_forks_repo_forks_event_min_datetime": "2015-01-07T12:22:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T14:16:42.000Z", "avg_line_length": 23.6638655462, "max_line_length": 80, "alphanum_fraction": 0.6789772727, "num_tokens": 697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08035747763179142, "lm_q2_score": 0.021287354044241067, "lm_q1q2_score": 0.0017105980764501262}}
{"text": "#pragma once\n\n#include <winrt\\Windows.Foundation.h>\n#include <d3d11.h>\n#include <gsl\\gsl>\n\nnamespace Library\n{\n\tclass DepthStencilStates final\n\t{\n\tpublic:\n\t\tinline static winrt::com_ptr<ID3D11DepthStencilState> DefaultDepthCulling;\n\t\tinline static winrt::com_ptr<ID3D11DepthStencilState> NoDepthCulling;\n\n\t\tstatic void Initialize(gsl::not_null<ID3D11Device*> direct3DDevice);\n\t\tstatic void Shutdown();\n\n\t\tDepthStencilStates() = delete;\n\t\tDepthStencilStates(const DepthStencilStates&) = delete;\n\t\tDepthStencilStates& operator=(const DepthStencilStates&) = delete;\n\t\tDepthStencilStates(DepthStencilStates&&) = delete;\n\t\tDepthStencilStates& operator=(DepthStencilStates&&) = delete;\n\t\t~DepthStencilStates() = default;\n\t};\n}\n", "meta": {"hexsha": "b28d367ac27c45a153adea9768ca3f9726d0c8da", "size": 721, "ext": "h", "lang": "C", "max_stars_repo_path": "source/Library.Shared/DepthStencilStates.h", "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/Library.Shared/DepthStencilStates.h", "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/Library.Shared/DepthStencilStates.h", "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7307692308, "max_line_length": 76, "alphanum_fraction": 0.7780859917, "num_tokens": 190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08632348598851412, "lm_q2_score": 0.019719126955171907, "lm_q1q2_score": 0.0017022237794205133}}
{"text": "#pragma once\n\n#include <winrt\\Windows.Foundation.h>\n#include <d3d11.h>\n#include <gsl\\gsl>\n\nnamespace Library\n{\n\tclass RasterizerStates final\n\t{\n\tpublic:\n\t\tinline static winrt::com_ptr<ID3D11RasterizerState> BackCulling;\n\t\tinline static winrt::com_ptr<ID3D11RasterizerState> FrontCulling;\n\t\tinline static winrt::com_ptr<ID3D11RasterizerState> DisabledCulling;\n\t\tinline static winrt::com_ptr<ID3D11RasterizerState> Wireframe;\n\n\t\tstatic void Initialize(gsl::not_null<ID3D11Device*> direct3DDevice);\n\t\tstatic void Shutdown();\n\n\t\tRasterizerStates() = delete;\n\t\tRasterizerStates(const RasterizerStates&) = delete;\n\t\tRasterizerStates& operator=(const RasterizerStates&) = delete;\n\t\tRasterizerStates(RasterizerStates&&) = delete;\n\t\tRasterizerStates& operator=(RasterizerStates&&) = delete;\n\t\t~RasterizerStates() = default;\n\t};\n}\n", "meta": {"hexsha": "7e9b075a8b875476a3fabe343e09855bca1afdc3", "size": 821, "ext": "h", "lang": "C", "max_stars_repo_path": "source/Library.Shared/RasterizerStates.h", "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/Library.Shared/RasterizerStates.h", "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/Library.Shared/RasterizerStates.h", "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3214285714, "max_line_length": 70, "alphanum_fraction": 0.778319123, "num_tokens": 229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07263670234578153, "lm_q2_score": 0.02333076766251791, "lm_q1q2_score": 0.0016946700262008986}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef res_92f78d87_1896_40fa_bc63_c52e2793c970_h\r\n#define res_92f78d87_1896_40fa_bc63_c52e2793c970_h\r\n\r\n#include <gslib/config.h>\r\n#include <gslib/std.h>\r\n\r\n__gslib_begin__\r\n\r\nclass resvdir\r\n{\r\npublic:\r\n    resvdir(const gchar* path);\r\n    resvdir(const gchar* dir, const gchar* file);\r\n    const gchar* get_dir() const { return _dir.c_str(); }\r\n    const gchar* get_file() const { return _file.c_str(); }\r\n    const gchar* get_postfix() const;\r\n    const gchar* get_path(string& path) const;\r\n\r\npublic:\r\n    static bool is_valid_path(const gchar* path);\r\n    static bool is_valid_dir(const gchar* dir);\r\n    static const gchar* get_root(const gchar* path);\r\n    static const gchar* get_next_node(const gchar* path);\r\n\r\nprotected:\r\n    string      _dir;\r\n    string      _file;\r\n};\r\n\r\ntypedef unsigned char res;\r\n\r\nclass resnode\r\n{\r\npublic:\r\n    struct hash\r\n    {\r\n        size_t operator()(const resnode& that) const\r\n        { return string_hash(that._key); }\r\n    };\r\n    struct equal_to\r\n    {\r\n        bool operator()(const resnode& r1, const resnode& r2) const\r\n        { return string_hash(r1._key) == string_hash(r2._key); }\r\n    };\r\n    typedef unordered_set<resnode, hash, equal_to> resset;\r\n    typedef resset::iterator iterator;\r\n    typedef resset::const_iterator const_iterator;\r\n    typedef void (*fndestroy)(res*, int);\r\n\r\npublic:\r\n    resnode();\r\n    resnode(const gchar* key);\r\n    resnode(const resnode& that) { assign(const_cast<resnode&>(that)); }\r\n    ~resnode() { destroy(); }\r\n    void set_destroy(fndestroy del) { _del = del; }\r\n    void set_resource(res* ptr, int len) { _res = ptr; _len = len; }\r\n    res* get_resource() const { return _res; }\r\n    const gchar* get_key() const { return _key.size() ? _key.c_str() : 0; }\r\n    void destroy();\r\n    void assign(resnode& that);\r\n    bool operator<(const resnode& that) const { return _key < that._key; }\r\n    iterator begin() { return _subs.begin(); }\r\n    const_iterator begin() const { return _subs.end(); }\r\n    iterator end() { return _subs.end(); }\r\n    const_iterator end() const { return _subs.end(); }\r\n    resnode* add(const gchar* key, res* ptr = 0, int len = 0);\r\n    resnode* add(resnode* node);\r\n    resnode* find(const gchar* key);\r\n    const resnode* find(const gchar* key) const;\r\n\r\nprotected:\r\n    string      _key;\r\n    res*        _res;\r\n    int         _len;\r\n    fndestroy   _del;\r\n    resset      _subs;\r\n};\r\n\r\nclass respack\r\n{\r\npublic:\r\n    typedef resnode::resset resset;\r\n    typedef resnode::iterator iterator;\r\n    typedef resnode::const_iterator const_iterator;\r\n    typedef resnode::fndestroy fndestroy;\r\n\r\npublic:\r\n    respack(): _root(_t(\":\")) {}\r\n    resnode* get_root() { return &_root; }\r\n    const resnode* get_root() const { return &_root; }\r\n    resnode* add(const gchar* path) { return add(resvdir(path)); }\r\n    resnode* add(const resvdir& vdir) { return add(get_root(), resvdir::get_root(vdir.get_dir()), vdir.get_file()); }\r\n    resnode* add(resnode* node, const gchar* dir, const gchar* file);\r\n    resnode* find(const gchar* path) { return find(get_root(), resvdir::get_root(path)); }\r\n    resnode* find(resnode* node, const gchar* path);\r\n    const resnode* find(const gchar* path) const { return find(get_root(), resvdir::get_root(path)); }\r\n    const resnode* find(const resnode* node, const gchar* path) const;\r\n    resnode* reg(const gchar* path, res* ptr, int len, fndestroy del = 0)\r\n    {\r\n        if(resnode* node = add(path)) {\r\n            node->set_resource(ptr, len);\r\n            node->set_destroy(del);\r\n            return node;\r\n        }\r\n        return 0;\r\n    }\r\n\r\nprotected:\r\n    resnode     _root;\r\n};\r\n\r\nextern respack* get_default_respack();\r\n\r\n__gslib_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "eea6577e0db2ed21d21aefe7906b0ad825f6a354", "size": 4977, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gslib/res.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/gslib/res.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gslib/res.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 34.5625, "max_line_length": 118, "alphanum_fraction": 0.6594333936, "num_tokens": 1264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.05340333431947304, "lm_q2_score": 0.031618770006199386, "lm_q1q2_score": 0.0016885477454115926}}
{"text": "#ifndef __GSL_VERSION_H__\n#define __GSL_VERSION_H__\n\n#include <gsl/gsl_types.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n__BEGIN_DECLS\n\n\n#define GSL_VERSION \"2.2.1\"\n#define GSL_MAJOR_VERSION 2\n#define GSL_MINOR_VERSION 2\n\nGSL_VAR const char * gsl_version;\n\n__END_DECLS\n\n#endif /* __GSL_VERSION_H__ */\n", "meta": {"hexsha": "c5bac549d166fff750f05f0c28c423fa12b1dcd8", "size": 460, "ext": "h", "lang": "C", "max_stars_repo_path": "3rdparty/wingsl/include/gsl/gsl_version.h", "max_stars_repo_name": "Tjoppen/fmigo", "max_stars_repo_head_hexsha": "0ad5e82b49a973cf710f85daa9dffc45261b36ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-12-18T16:35:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-14T07:38:05.000Z", "max_issues_repo_path": "3rdparty/wingsl/include/gsl/gsl_version.h", "max_issues_repo_name": "Tjoppen/fmigo", "max_issues_repo_head_hexsha": "0ad5e82b49a973cf710f85daa9dffc45261b36ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3rdparty/wingsl/include/gsl/gsl_version.h", "max_forks_repo_name": "Tjoppen/fmigo", "max_forks_repo_head_hexsha": "0ad5e82b49a973cf710f85daa9dffc45261b36ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-20T15:50:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T15:50:01.000Z", "avg_line_length": 17.037037037, "max_line_length": 35, "alphanum_fraction": 0.7717391304, "num_tokens": 123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06371499069622687, "lm_q2_score": 0.026355350265088992, "lm_q1q2_score": 0.0016792308969359455}}
{"text": "/*\n  Copyright [2017-2021] [IBM Corporation]\n  Licensed under the Apache License, Version 2.0 (the \"License\");\n  you may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n  http://www.apache.org/licenses/LICENSE-2.0\n  Unless required by applicable law or agreed to in writing, software\n  distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions and\n  limitations under the License.\n*/\n\n#ifndef _API_KVSTORE_H_\n#define _API_KVSTORE_H_\n\n#include <api/components.h>\n#include <api/registrar_memory_direct.h>\n#include <common/byte.h>\n#include <common/byte_span.h>\n#include <common/errors.h> /* ERROR_BASE */\n#include <common/string_view.h>\n#include <common/time.h>\n#include <gsl/span>\n#include <sys/uio.h> /* iovec */\n\n#include <cinttypes> /* PRIx64 */\n#include <cstdlib>\n#include <functional>\n#include <map>\n#include <list>\n#include <mutex>\n#include <vector>\n\nnamespace nupm\n{\n  struct region_descriptor;\n}\n\n/* print format for the pool type */\n#define PRIxIKVSTORE_POOL_T PRIx64\n\nnamespace component\n{\n\n#define DECLARE_OPAQUE_TYPE(NAME) \\\n  struct Opaque_##NAME {          \\\n    virtual ~Opaque_##NAME() {}   \\\n  }\n\n/**\n * Key-value interface for pluggable backend (e.g. mapstore, hstore, hstore-cc)\n */\nclass KVStore : public Registrar_memory_direct {\n\nprotected:\n  ~KVStore() {}\n private:\n  DECLARE_OPAQUE_TYPE(lock_handle);\n  template <typename E, typename ... Args>\n    static E error_value(\n      E e, Args && ...\n    ) { return e; }\n\n public:\n  DECLARE_OPAQUE_TYPE(memory_region); /* Buffer_manager::buffer_t need this */\n  DECLARE_OPAQUE_TYPE(key);\n  DECLARE_OPAQUE_TYPE(pool_iterator);\n\n public:\n  using pool_t          = uint64_t;\n  // using memory_handle_t = Opaque_memory_region*;\n  using key_t           = Opaque_key*;\n  using pool_lock_t     = Opaque_lock_handle*;\n  using pool_iterator_t = Opaque_pool_iterator*;\n  using byte            = common::byte;\n\n template <typename C>\n    using basic_string_view = common::basic_string_view<C>;\n  using string_view = common::string_view;\n  using string_view_byte = basic_string_view<byte>;\n  using string_view_key = string_view_byte;\n  using string_view_value = string_view_byte;\n\n  static constexpr memory_handle_t HANDLE_NONE = nullptr; /* old name */\n  static constexpr memory_handle_t MEMORY_HANDLE_NONE = nullptr; /* better name */\n  static constexpr key_t           KEY_NONE    = nullptr;\n\n  struct Addr {\n    explicit Addr(addr_t addr_) : addr(addr_) {}\n    Addr() = delete;\n    addr_t addr;\n  };\n  \n\n  enum {\n    THREAD_MODEL_UNSAFE,\n    THREAD_MODEL_SINGLE_PER_POOL,\n    THREAD_MODEL_RWLOCK_PER_POOL,\n    THREAD_MODEL_MULTI_PER_POOL,\n  };\n\n  using flags_t = std::uint32_t ;\n  static constexpr flags_t FLAGS_NONE          = 0x0;\n  static constexpr flags_t FLAGS_READ_ONLY     = 0x1; /* lock read-only */\n  static constexpr flags_t FLAGS_SET_SIZE      = 0x2;\n  static constexpr flags_t FLAGS_CREATE_ONLY   = 0x4;  /* only succeed if no existing k-v pair exist */\n  static constexpr flags_t FLAGS_DONT_STOMP    = 0x8;  /* do not overwrite existing k-v pair */\n  static constexpr flags_t FLAGS_NO_RESIZE     = 0x10; /* if size < existing size, do not resize */\n  static constexpr flags_t FLAGS_MAX_VALUE     = 0x10;\n\n  using unlock_flags_t = std::uint32_t;\n  static constexpr unlock_flags_t UNLOCK_FLAGS_NONE = 0x0;\n  static constexpr unlock_flags_t UNLOCK_FLAGS_FLUSH = 0x1; /* indicates for PM backends to flush */\n\n  static constexpr pool_t POOL_ERROR = 0;\n\n  enum class Capability {\n    POOL_DELETE_CHECK, /*< checks if pool is open before allowing delete */\n    RWLOCK_PER_POOL,   /*< pools are locked with RW-lock */\n    POOL_THREAD_SAFE,  /*< pools can be shared across multiple client threads */\n    WRITE_TIMESTAMPS,  /*< support for write timestamping */\n  };\n\n  enum class Op_type {\n    WRITE, /* copy bytes into memory region */\n    ZERO,  /* zero the memory region */\n    INCREMENT_UINT64,\n    CAS_UINT64,\n  };\n\n\n  enum Attribute : std::uint32_t {\n    VALUE_LEN                = 1, /* length of a value associated with key */\n    COUNT                    = 2, /* number of objects */\n    CRC32                    = 3, /* get CRC32 of a value */\n    AUTO_HASHTABLE_EXPANSION = 4, /* set to true if the hash table should expand */\n    PERCENT_USED             = 5, /* get percent used pool capacity at current size */\n    WRITE_EPOCH_TIME         = 6, /* epoch time at which the key-value pair was last\n                                     written or locked with STORE_LOCK_WRITE */\n    MEMORY_TYPE              = 7, /* type of memory */\n    MEMORY_SIZE              = 8, /* size of pool or store in bytes */\n    NUMA_MASK                = 9, /* mask of first 64 numa nodes eligible for mapstore allocation */\n  };\n\n  enum {\n    MEMORY_TYPE_DRAM        = 0x1,\n    MEMORY_TYPE_PMEM_DEVDAX = 0x2,\n    MEMORY_TYPE_PMEM_FSDAX  = 0x3,\n    MEMORY_TYPE_UNKNOWN     = 0xFF,\n  };\n\n  enum lock_type_t {\n    STORE_LOCK_NONE  = 0,\n    STORE_LOCK_READ  = 1,\n    STORE_LOCK_WRITE = 2,\n  };\n\n  enum {\n    /* see common/errors.h */\n    S_MORE           = 2,\n    E_KEY_EXISTS     = E_ERROR_BASE - 1,\n    E_KEY_NOT_FOUND  = E_ERROR_BASE - 2,\n    E_POOL_NOT_FOUND = E_ERROR_BASE - 3,\n    E_BAD_ALIGNMENT  = E_ERROR_BASE - 4,\n    E_TOO_LARGE      = E_ERROR_BASE - 5, /* -55 */\n    E_ALREADY_OPEN   = E_ERROR_BASE - 6,\n  };\n\n  std::string strerro(int e)\n  {\n    static std::map<int, std::string> errs {\n      { S_MORE, \"MORE\" }\n      , { E_KEY_EXISTS, \"E_KEY_EXISTS\" }\n      , { E_KEY_NOT_FOUND, \"E_KEY_NOT_FOUND\" }\n      , { E_POOL_NOT_FOUND, \"E_POOL_NOT_FOUND\" }\n      , { E_BAD_ALIGNMENT, \"E_BAD_ALIGNMENT\" }\n      , { E_TOO_LARGE, \"E_TOO_LARGE\" }\n      , { E_ALREADY_OPEN, \"E_ALREADY_OPEN\" }\n    };\n    auto it = errs.find(e);\n    return it == errs.end() ? ( \"non-IKVStore error \" + std::to_string(e) ) : it->second;\n  }\n\n\n  class Operation {\n    Op_type _type;\n    size_t  _offset;\n\n   protected:\n    Operation(Op_type type, size_t offset) : _type(type), _offset(offset) {}\n\n   public:\n    Op_type type() const noexcept { return _type; }\n    size_t  offset() const noexcept { return _offset; }\n  };\n\n  class Operation_sized : public Operation {\n    size_t _len;\n\n   protected:\n    Operation_sized(Op_type type, size_t offset_, size_t len) : Operation(type, offset_), _len(len) {}\n\n   public:\n    size_t size() const noexcept { return _len; }\n  };\n\n  class Operation_write : public Operation_sized {\n    const void* _data;\n\n   public:\n    Operation_write(size_t offset, size_t len, const void* data)\n        : Operation_sized(Op_type::WRITE, offset, len), _data(data)\n    {\n    }\n    const void* data() const noexcept { return _data; }\n  };\n\n  class Operation_zero : public Operation_sized {\n\n   public:\n    Operation_zero(size_t offset, size_t len)\n        : Operation_sized(Op_type::ZERO, offset, len)\n    {\n    }\n  };\n\n  /**\n   * Determine thread safety of the component\n   * Check capability of component\n   *\n   * @param cap Capability type\n   *\n   * @return THREAD_MODEL_XXXX\n   */\n  virtual int thread_safety() const = 0;\n\n  /**\n   * Check capability of component\n   *\n   * @param cap Capability type\n   *\n   * @return THREAD_MODEL_XXXX\n   */\n  virtual int get_capability(Capability cap) const { return error_value(-1, cap); }\n\n  /**\n   * Create an object pool. If the pool exists and the FLAGS_CREATE_ONLY\n   * is not provided, then the existing pool will be opened.  If\n   * FLAGS_CREATE_ONLY is specified and the pool exists, POOL ERROR will be\n   * returned.\n   *\n   * @param pool_name Unique pool name\n   * @param size Size of pool in bytes (for keys,values and metadata)\n   * @param flags Creation flags\n   * @param expected_obj_count Expected maximum object count (optimization)\n   * @param base Optional base address\n   *\n   * @return Pool handle or POOL_ERROR\n   */\n  virtual pool_t create_pool(const std::string& pool_name,\n                             const size_t       size,\n                             flags_t            flags              = 0,\n                             uint64_t           expected_obj_count = 0,\n                             const Addr         base_addr = Addr{0})\n  {\n    PERR(\"create_pool not implemented\");\n    return error_value(POOL_ERROR, pool_name, size, flags, expected_obj_count, base_addr);\n  }\n\n  virtual pool_t create_pool(const std::string& path,\n                             const std::string& name,\n                             const size_t       size,\n                             flags_t            flags              = 0,\n                             uint64_t           expected_obj_count = 0,\n                             const Addr         base_addr_unused = Addr{0}) __attribute__((deprecated))\n  {\n    return create_pool(path + name, size, flags, expected_obj_count, base_addr_unused);\n  }\n\n  /**\n   * Open an existing pool.\n   *\n   * @param name Name of object pool\n   * @param flags Optional flags e.g., FLAGS_READ_ONLY\n   * @param base Optional base address\n   *\n   * @return Pool handle or POOL_ERROR if pool cannot be opened, or flags\n   * unsupported\n   */\n  virtual pool_t open_pool(const std::string& pool_name,\n                           flags_t flags = 0,\n                           const Addr base_addr_unused = Addr{0})\n  {\n    return error_value(POOL_ERROR, pool_name, flags, base_addr_unused);\n  }\n\n  virtual pool_t open_pool(const std::string& path,\n                           const std::string& name,\n                           flags_t flags = 0,\n                           const Addr base_addr_unused = Addr{0}) __attribute__((deprecated))\n  {\n    return open_pool(path + name, flags, base_addr_unused);\n  }\n\n  /**\n   * Close pool handle\n   *\n   * @param pool Pool handle\n   *\n   * @return S_OK on success, E_POOL_NOT_FOUND, E_ALREADY_OPEN if pool cannot be\n   * closed due to open session.\n   */\n  virtual status_t close_pool(pool_t pool) = 0;\n\n  /**\n   * Delete an existing pool\n   *\n   * @param name Name of object pool\n   *\n   * @return S_OK on success, E_POOL_NOT_FOUND, E_ALREADY_OPEN if pool cannot be\n   * deleted\n   */\n  virtual status_t delete_pool(const std::string& name) = 0;\n\n  /** \n   * Get a list of pool names\n   * \n   * @param inout_pool_names [inout] List of pool names\n   * \n   * @return S_OK or E_NOT_IMPL;\n   */\n  virtual status_t get_pool_names(std::list<std::string>& inout_pool_names) = 0;\n  \n  /**\n   * Get mapped memory regions for pool.  This is used for pre-registration with\n   * DMA engines.\n   *\n   * @param pool Pool handle\n   * @param out_regions Backing file name (if any), Mapped memory regions\n   *\n   * @return S_OK on success or E_POOL_NOT_FOUND.  Components that do not\n   * support this return E_NOT_SUPPORTED.\n   */\n  virtual status_t get_pool_regions(const pool_t pool, nupm::region_descriptor & out_regions)\n  {\n    return error_value(E_NOT_SUPPORTED, pool, out_regions); /* not supported in FileStore */\n  }\n\n  /**\n   * Dynamically expand a pool.  Typically, this will add to the regions\n   * belonging to a pool.\n   *\n   * @param pool Pool handle\n   * @param increment_size Size in bytes to expand by\n   * @param reconfigured_size [out] new size of pool\n   *\n   * @return S_OK on success or E_POOL_NOT_FOUND. Components that do not support\n   * this return E_NOT_SUPPORTED (e.g. MCAS client)\n   */\n  virtual status_t grow_pool(const pool_t pool,\n                             const size_t increment_size,\n                             size_t& reconfigured_size)\n  {\n    PERR(\"grow_pool: not supported\");\n    return error_value(E_NOT_SUPPORTED, pool, increment_size, reconfigured_size);\n  }\n\n  /**\n   * Write or overwrite an object value. If there already exists an\n   * object with matching key, then it should be replaced\n   * (i.e. reallocated) or overwritten.\n   *\n   * @param pool Pool handle\n   * @param key Object key\n   * @param value Value data\n   * @param value_len Size of value in bytes\n   *\n   * @return S_OK or E_POOL_NOT_FOUND, E_KEY_EXISTS\n   */\n  virtual status_t put(const pool_t       pool,\n                       const std::string& key,\n                       const void*        value,\n                       const size_t       value_len,\n                       flags_t            flags = FLAGS_NONE)\n  {\n    return error_value(E_NOT_SUPPORTED, pool, key, value, value_len, flags);\n  }\n\n  /**\n   * Zero-copy put operation.  If there does not exist an object\n   * with matching key, then an error E_KEY_EXISTS should be returned.\n   *\n   * @param pool Pool handle\n   * @param key Object key\n   * @param value Value\n   * @param value_len Value length in bytes\n   * @param handle Memory registration handle\n   * @param flags Optional flags\n   *\n   * @return S_OK or E_POOL_NOT_FOUND, E_KEY_EXISTS\n   */\n  virtual status_t put_direct(const pool_t   pool,\n                              const std::string&    key,\n                              gsl::span<const common::const_byte_span> values,\n                              gsl::span<const memory_handle_t> handles = gsl::span<const memory_handle_t>(),\n                              flags_t        flags  = FLAGS_NONE)\n  {\n    return error_value(E_NOT_SUPPORTED, pool, key, values, handles, flags);\n  }\n\n\n /**\n   * Zero-copy put operation (see exceptions above).\n   *\n   * @param pool Pool handle\n   * @param key Object key\n   * @param value Value\n   * @param value_len Value length in bytes\n   * @param handle Memory registration handle\n   * @param flags Optional flags\n   *\n   * @return S_OK or error code\n   */\n  virtual status_t put_direct(const pool_t   pool,\n                              const std::string&    key,\n                              const void*           value,\n                              const size_t          value_len,\n                              const memory_handle_t handle = MEMORY_HANDLE_NONE,\n                              flags_t        flags  = FLAGS_NONE)\n  {\n    return put_direct(\n      pool\n      , key\n      , std::array<const common::const_byte_span,1>{common::make_const_byte_span(value, value_len)}\n      , std::array<memory_handle_t,1>{handle}\n      , flags\n    );\n  }\n\n  /**\n   * Resize memory for a value\n   *\n   * @param pool Pool handle\n   * @param key Object key (should be unlocked)\n   * @param new_size New size of value in bytes (can be more or less)\n   *\n   * @return S_OK on success, E_BAD_ALIGNMENT, E_POOL_NOT_FOUND,\n   * E_KEY_NOT_FOUND, E_TOO_LARGE, E_ALREADY(?)\n   */\n  virtual status_t resize_value(const pool_t       pool,\n                                const std::string& key,\n                                const size_t       new_size,\n                                const size_t       alignment)\n  {\n    return error_value(E_NOT_SUPPORTED, pool, key, new_size, alignment);\n  }\n\n  /**\n   * Read an object value\n   *\n   * @param pool Pool handle\n   * @param key Object key\n   * @param out_value Value data (if null, component will allocate memory)\n   * @param out_value_len Size of value in bytes\n   *\n   * @return S_OK or E_POOL_NOT_FOUND, E_KEY_NOT_FOUND if key not found\n   */\n  virtual status_t get(const pool_t       pool,\n                       const std::string& key,\n                       void*&             out_value, /* release with free_memory() API */\n                       size_t&            out_value_len) = 0;\n\n  /**\n   * Read an object value directly into client-provided memory.\n   *\n   * @param pool Pool handle\n   * @param key Object key\n   * @param out_value Client provided buffer for value\n   * @param out_value_len [in] size of value memory in bytes [out] size of value\n   * @param handle Memory registration handle\n   *\n   * @return S_OK, S_MORE if only a portion of value is read,\n   * E_BAD_ALIGNMENT on invalid alignment, E_POOL_NOT_FOUND, E_KEY_NOT_FOUND, or other\n   * error code\n   *\n   * Note: S_MORE is reduncant, it could have been inferred from S_OK and\n   * out_value_len [in] < out_value_len [out].\n   */\n  virtual status_t get_direct(pool_t             pool,\n                              const std::string& key,\n                              void*              out_value,\n                              size_t&            out_value_len,\n                              memory_handle_t    handle = HANDLE_NONE)\n  {\n    return error_value(E_NOT_SUPPORTED, pool, key, out_value, out_value_len, handle);\n  }\n\n  /**\n   * Get attribute for key or pool (see enum Attribute)\n   *\n   * @param pool Pool handle\n   * @param attr Attribute to retrieve\n   * @param out_value Vector of attribute values\n   * @param key [optional] Key\n   *\n   * @return S_OK on success, E_POOL_NOT_FOUND, E_INVALID_ARG, E_KEY_NOT_FOUND\n   */\n  virtual status_t get_attribute(pool_t                 pool,\n                                 Attribute              attr,\n                                 std::vector<uint64_t>& out_value,\n                                 const std::string*     key = nullptr) = 0;\n\n  /**\n   * Atomically (crash-consistent for pmem) swap keys (K,V)(K',V') -->\n   * (K,V')(K',V).  Before calling this API, both KV-pairs must be\n   * unlocked.\n   *\n   * @param pool Pool handle\n   * @param key0 First key\n   * @param key1 Second key\n   *\n   * @return S_OK on success, E_POOL_NOT_FOUND, E_KEY_NOT_FOUND, E_LOCKED\n   * (unable to take both locks)\n   */\n  virtual status_t swap_keys(const pool_t pool,\n                             const std::string key0,\n                             const std::string key1)\n  {\n    return error_value(E_NOT_SUPPORTED, pool, key0, key1);\n  }\n\n  /**\n   * Set attribute on a pool.\n   *\n   * @param pool Pool handle\n   * @param attr Attribute to set\n   * @param value Vector of values to set (for boolean 0=false, 1=true)\n   * @param key [optional] key\n   *\n   * @return S_OK, E_INVALID_ARG (e.g. key==nullptr), E_POOL_NOT_FOUND\n   */\n  virtual status_t set_attribute(const pool_t                 pool,\n                                 const Attribute              attr,\n                                 const std::vector<uint64_t>& value,\n                                 const std::string*           key = nullptr)\n  {\n    return error_value(E_NOT_SUPPORTED, pool, attr, value, key);\n  }\n\n  /**\n   * Allocate memory for zero copy DMA\n   *\n   * @param vaddr [out] allocated memory buffer\n   * @param len [in] length of memory buffer in bytes\n   * @param handle memory handle\n   *\n   */\n  virtual status_t allocate_direct_memory(void*& vaddr,\n                                          size_t len,\n                                          memory_handle_t& handle)\n  {\n    return error_value(E_NOT_SUPPORTED, vaddr, len, handle);\n  }\n\n  /**\n   * Free memory for zero copy DMA\n   *\n   * @param handle handle to memory region to free\n   *\n   * @return S_OK on success\n   */\n  virtual status_t free_direct_memory(memory_handle_t handle)\n  {\n    return error_value(E_NOT_SUPPORTED, handle);\n  }\n\n  /**\n   * Register memory for zero copy DMA\n   *\n   * @param vaddr Appropriately aligned memory buffer\n   *\n   * @return Memory handle or NULL on not supported.\n   */\n\n  memory_handle_t register_direct_memory(common::const_byte_span bytes) override\n  {\n    return error_value(nullptr, bytes);\n  }\n\n  using Registrar_memory_direct::register_direct_memory;\n\n  /**\n   * Direct memory regions should be unregistered before the memory is released\n   * on the client side.\n   *\n   * @param handle (as returned by register_direct_memory) of region to deregister.\n   *\n   * @return S_OK on success\n   */\n  status_t unregister_direct_memory(memory_handle_t handle) override\n  {\n    return error_value(E_NOT_SUPPORTED, handle);\n  }\n\n  /**\n   * Take a lock on an object. If the object does not exist and inout_value_len\n   * is non-zero, create it with value space according to out_value_len (this\n   * is very important for mcas context). If the object does not exist and\n   * inout_value_len is zero, return E_KEY_NOT_FOUND.\n   *\n   * @param pool Pool handle\n   * @param key Key\n   * @param type STORE_LOCK_READ | STORE_LOCK_WRITE\n   * @param out_value [out] Pointer to data\n   * @param inout_value_len [in-out] Size of data in bytes\n   * @param alignment [in] Alignment of new value space in bytes.\n   * @param out_key [out]  Handle to key for unlock\n   * @param out_key_ptr [out]  Optional request for key-string pointer (set to\n   * nullptr if not required)\n   *\n   * @return S_OK, S_CREATED_OK (if created on demand), E_KEY_NOT_FOUND,\n   * E_LOCKED (already locked), E_INVAL (e.g., no key & no length),\n   * E_TOO_LARGE (cannot allocate space for lock), E_NOT_SUPPORTED\n   * if unable to take lock or other error\n   */\n  virtual status_t lock(const pool_t       pool,\n                        const std::string& key,\n                        const lock_type_t  type,\n                        void*&             out_value,\n                        size_t&            inout_value_len,\n                        size_t             alignment,\n                        key_t&             out_key_handle,\n                        const char**       out_key_ptr = nullptr)\n  {\n    return error_value(E_NOT_SUPPORTED, pool, key, type, out_value, inout_value_len, alignment,\n                       out_key_handle, out_key_ptr);\n  }\n\n  /**\n   * Unlock a key-value pair\n   *\n   * @param pool Pool handle\n   * @param key_handle Handle (opaque) for key used to unlock\n   * @param flags Optional unlock flags, UNLOCK_FLAGS_FLUSH\n   *\n   * @return S_OK, S_MORE (for async), E_INVAL or other error\n   */\n  virtual status_t unlock(const pool_t pool,\n                          const key_t key_handle,\n                          const unlock_flags_t flags = UNLOCK_FLAGS_NONE)\n  {\n    return error_value(E_NOT_SUPPORTED, pool, key_handle, flags);\n  }\n\n  /**\n   * Update an existing value by applying a series of operations.\n   * Together the set of operations make up an atomic transaction.\n   * If the operation requires a result the operation type may provide\n   * a method to accept the result. No operation currently requires\n   * a result, but compare and swap probably would.\n   *\n   * @param pool Pool handle\n   * @param key Object key\n   * @param op_vector Operation vector\n   * @param take_lock Set to true for automatic locking of object\n   *\n   * @return S_OK or error code\n   */\n  virtual status_t atomic_update(const pool_t                   pool,\n                                 const std::string&             key,\n                                 const std::vector<Operation*>& op_vector,\n                                 bool                           take_lock = true)\n  {\n    return error_value(E_NOT_SUPPORTED, pool, key, op_vector, take_lock);\n  }\n\n  /**\n   * Erase an object\n   *\n   * @param pool Pool handle\n   * @param key Object key\n   *\n   * @return S_OK or error code (e.g. E_LOCKED)\n   */\n  virtual status_t erase(pool_t pool, const std::string& key) = 0;\n\n  /**\n   * Return number of objects in the pool\n   *\n   * @param pool Pool handle\n   *\n   * @return Number of objects\n   */\n  virtual size_t count(pool_t pool) = 0;\n\n  /**\n   * Apply functor to all objects in the pool\n   *\n   * @param pool Pool handle\n   * @param function Functor to apply\n   *\n   * @return S_OK, E_POOL_NOT_FOUND\n   */\n  virtual status_t map(const pool_t pool,\n                       std::function<int(const void* key,\n                                         const size_t key_len,\n                                         const void* value,\n                                         const size_t value_len)> function)\n  {\n    return error_value(E_NOT_SUPPORTED, pool, function);\n  }\n\n  /**\n   * Apply functor to all objects in the pool according\n   * to given time constraints\n   *\n   * @param pool Pool handle\n   * @param function Functor to apply (not in time order). If\n   *                 functor returns < 0, then map aborts\n   * @param t_begin Time must be after or equal. If set to zero, no constraint.\n   * @param t_end Time must be before or equal. If set to zero, no constraint.\n   *\n   * @return S_OK, E_POOL_NOT_FOUND\n   */\n  virtual status_t map(const pool_t pool,\n                       std::function<int(const void*              key,\n                                         const size_t             key_len,\n                                         const void*              value,\n                                         const size_t             value_len,\n                                         const common::tsc_time_t timestamp)> function,\n                       const common::epoch_time_t t_begin,\n                       const common::epoch_time_t t_end)\n  {\n    return error_value(E_NOT_SUPPORTED, pool, function, t_begin, t_end);\n  }\n\n  /**\n   * Apply functor to all keys only. Useful for file_store (now deprecated)\n   *\n   * @param pool Pool handle\n   * @param function Functor\n   *\n   * @return S_OK, E_POOL_NOT_FOUND\n   */\n  virtual status_t map_keys(const pool_t pool, std::function<int(const std::string& key)> function)\n  {\n    return error_value(E_NOT_SUPPORTED, pool, function);\n  }\n\n  /*\n     auto iter = open_pool_iterator(pool);\n\n     while(deref_pool_iterator(iter, ref, true) == S_OK)\n       process_record(ref);\n\n     close_pool_iterator(iter);\n  */\n\n  struct pool_reference_t {\n  public:\n    pool_reference_t()\n      : key(nullptr), key_len(0), value(nullptr), value_len(0), timestamp() {}\n\n    const void*          key;\n    size_t               key_len;\n    const void*          value;\n    size_t               value_len;\n    common::epoch_time_t timestamp; /* zero if not supported */\n    \n    inline std::string get_key() const {\n      std::string k(static_cast<const char*>(key), key_len);\n      return k;\n    }\n\n  };\n\n  /**\n   * Open pool iterator to iterate over objects in pool.\n   *\n   * @param pool Pool handle\n   *\n   * @return Pool iterator or nullptr\n   */\n  virtual pool_iterator_t open_pool_iterator(const pool_t pool)\n  {\n    return error_value(nullptr, pool);\n  }\n\n  /**\n   * Deference pool iterator position and optionally increment\n   *\n   * @param pool Pool handle\n   * @param iter Pool iterator\n   * @param t_begin Time must be after or equal. If set to zero, no constraint.\n   * @param t_end Time must be before or equal. If set to zero, no constraint.\n   * @param ref [out] Output reference record\n   * @param ref [out] Set to true if within time bounds\n   * @param increment Move iterator forward one position\n   *\n   * @return S_OK on success and valid reference, E_INVAL (bad iterator),\n   *   E_OUT_OF_BOUNDS (when attempting to dereference out of bounds)\n   *   E_ITERATOR_DISTURBED (when writes have been made since last iteration)\n   */\n  virtual status_t deref_pool_iterator(const pool_t       pool,\n                                       pool_iterator_t    iter,\n                                       const common::epoch_time_t t_begin,\n                                       const common::epoch_time_t t_end,\n                                       pool_reference_t&  ref,\n                                       bool&              time_match,\n                                       bool               increment = true)\n  {\n    /* Not sure of the difference between \"not supported\" and \"not implemented\",\n     * but they are separated codes.\n     */\n    return error_value(E_NOT_IMPL, pool, iter, t_begin, t_end, ref, time_match, increment);\n  }\n\n  /**\n   * Unlock pool, release iterator and associated resources\n   *\n   * @param pool Pool handle\n   * @param iter Pool iterator\n   *\n   * @return S_OK on success, E_INVAL (bad iterator)\n   */\n  virtual status_t close_pool_iterator(const pool_t pool,\n                                       pool_iterator_t iter)\n  {\n    return error_value(E_NOT_IMPL, pool, iter);\n  }\n\n  /**\n   * Free server-side allocated memory\n   *\n   * @param p Pointer to memory allocated through a get call\n   *\n   * @return S_OK on success\n   */\n  virtual status_t free_memory(void* p)\n  {\n    ::free(p);\n    return S_OK;\n  }\n\n  /**\n   * Allocate memory from pool\n   *\n   * @param pool Pool handle\n   * @param size Size in bytes\n   * @param alignment Alignment hint in bytes, 0 if no alignment is needed\n   * @param out_addr Pointer to allocated region\n   *\n   * @return S_OK on success, E_BAD_ALIGNMENT, E_POOL_NOT_FOUND, E_NOT_SUPPORTED\n   */\n  virtual status_t allocate_pool_memory(const pool_t pool,\n                                        const size_t size,\n                                        const size_t alignment_hint,\n                                        void*&       out_addr)\n  {\n    return error_value(E_NOT_SUPPORTED, pool, size, alignment_hint, out_addr);\n  }\n\n  /**\n   * Free memory from pool\n   *\n   * @param pool Pool handle\n   * @param addr Address of memory to free\n   * @param size Size in bytes of allocation; if provided this accelerates\n   * release\n   *\n   * @return S_OK on success, E_INVAL, E_POOL_NOT_FOUND, E_NOT_SUPPORTED\n   */\n  virtual status_t free_pool_memory(pool_t pool, const void* addr, size_t size = 0)\n  {\n    return error_value(E_NOT_SUPPORTED, pool, addr, size);\n  }\n\n  /**\n   * Flush memory from pool\n   *\n   * @param pool Pool handle\n   * @param addr Address of memory to flush\n   * @param size Size in bytes to flush\n   *\n   * @return S_OK on success, E_INVAL, E_POOL_NOT_FOUND, E_NOT_SUPPORTED\n   */\n  virtual status_t flush_pool_memory(pool_t pool, const void* addr, size_t size)\n  {\n    return error_value(E_NOT_SUPPORTED, pool, addr, size);\n  }\n\n  /**\n   * Perform control invocation on component\n   *\n   * @param command String representation of command (component-interpreted)\n   *\n   * @return S_OK on success or error otherwise\n   */\n  virtual status_t ioctl(const std::string& command) { return error_value(E_NOT_SUPPORTED, command); }\n\n  /**\n   * Debug routine\n   *\n   * @param pool Pool handle\n   * @param cmd Debug command\n   * @param arg Parameter for debug operation\n   */\n  virtual void debug(pool_t pool, unsigned cmd, uint64_t arg) = 0;\n};\n\n}  // namespace component\n#endif\n", "meta": {"hexsha": "aeb8946a39af9bc2a673d371470c2a226a1a4964", "size": 29861, "ext": "h", "lang": "C", "max_stars_repo_path": "src/components/api/kvstore.h", "max_stars_repo_name": "IBM/artemis", "max_stars_repo_head_hexsha": "f655d6e952577de11b52e2f4ab6f48c73ce5dba1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/components/api/kvstore.h", "max_issues_repo_name": "IBM/artemis", "max_issues_repo_head_hexsha": "f655d6e952577de11b52e2f4ab6f48c73ce5dba1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/components/api/kvstore.h", "max_forks_repo_name": "IBM/artemis", "max_forks_repo_head_hexsha": "f655d6e952577de11b52e2f4ab6f48c73ce5dba1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.670678337, "max_line_length": 108, "alphanum_fraction": 0.61394461, "num_tokens": 7075, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06656918897050168, "lm_q2_score": 0.025178843940802505, "lm_q1q2_score": 0.0016761352203540532}}
{"text": "#ifndef parser_496ce533_26fe_412b_8db6_e61b852be838_h\r\n#define parser_496ce533_26fe_412b_8db6_e61b852be838_h\r\n\r\n#include <rathen\\config.h>\r\n#include <rathen\\basis.h>\r\n#include <gslib\\tree.h>\r\n\r\n__rathen_begin__\r\n\r\nclass __gs_novtable ps_obj:\r\n    public object\r\n{\r\npublic:\r\n    enum\r\n    {\r\n        pt_root,\r\n        pt_block,\r\n        pt_value,\r\n        pt_expression,\r\n        pt_operator,\r\n        pt_function,\r\n        pt_calling,\r\n        pt_if_statement,\r\n        pt_loop_statement,\r\n        pt_go_statement,\r\n        pt_stop_statement,\r\n        pt_exit_statement,\r\n        pt_variable,\r\n        pt_constant,\r\n    };\r\n\r\n    enum\r\n    {\r\n        vt_string,\r\n        vt_integer,\r\n        vt_float,\r\n    };\r\n\r\npublic:\r\n    ps_obj() { _parent = 0; }\r\n    ps_obj(ps_obj* parent) { _parent = parent; }\r\n    ps_obj* get_parent() const { return _parent; }\r\n\r\npublic:\r\n    virtual ~ps_obj() {}\r\n    virtual bool is_anonymous() const = 0;\r\n\r\nprotected:\r\n    ps_obj*         _parent;\r\n};\r\n\r\nstruct ps_trait_pass {};\r\nstruct ps_trait_hold {};\r\n\r\ntemplate<uint tag, bool anony, class ph_trait, class bsc = ps_obj>\r\nclass ps_proto:\r\n    public bsc\r\n{\r\npublic:\r\n    ps_proto();\r\n    ps_proto(ps_obj* parent);\r\n    bool is_holder() const override;\r\n    uint get_tag() const override;\r\n    bool is_anonymous() const override;\r\n};\r\n\r\ntemplate<uint tag, bool anony, class bsc>\r\nclass ps_proto<tag, anony, ps_trait_pass, bsc>:\r\n    public bsc\r\n{\r\npublic:\r\n    ps_proto() {}\r\n    ps_proto(ps_obj* parent): bsc(parent) {}\r\n    bool is_holder() const override { return false; }\r\n    uint get_tag() const override { return tag; }\r\n    bool is_anonymous() const override { return anony; }\r\n};\r\n\r\ntemplate<uint tag, bool anony, class bsc>\r\nclass ps_proto<tag, anony, ps_trait_hold, bsc>:\r\n    public bsc\r\n{\r\npublic:\r\n    ps_proto() {}\r\n    ps_proto(ps_obj* parent): bsc(parent) {}\r\n    bool is_holder() const override { return true; }\r\n    uint get_tag() const override { return tag; }\r\n    bool is_anonymous() const override { return anony; }\r\n\r\npublic:\r\n    virtual void add_indexing(object* obj) { _indexing.add_value(obj); }\r\n    virtual indexing& get_indexing() { return _indexing; }\r\n\r\nprotected:\r\n    indexing        _indexing;\r\n\r\npublic:\r\n    object* find_object(const gchar* name) { return _indexing.find_value(name); }\r\n    const object* find_object(const gchar* name) const { return _indexing.find_value(name); } \r\n};\r\n\r\ntemplate<class mc, class pc>\r\nclass ps_join:\r\n    public mc,\r\n    public pc\r\n{\r\npublic:\r\n    ps_join() {}\r\n    ps_join(ps_obj* parent): mc(parent) {}\r\n};\r\n\r\nclass ps_comp_value\r\n{\r\npublic:\r\n    ps_comp_value() { _type = 0, _global = false, _ref = false; }\r\n    void set_type(type* ty) { _type = ty; }\r\n    void set_global(bool g) { _global = g; }\r\n    void set_ref(bool r) { _ref = r; }\r\n    type* get_type() const { return _type; }\r\n    bool is_complex() const { return _type->is_complex(); }\r\n    bool is_global() const { return _global; }\r\n    bool is_ref() const { return _ref; }\r\n\r\nprotected:\r\n    type*           _type;\r\n    bool            _global;\r\n    bool            _ref;\r\n};\r\n\r\nclass ps_comp_operator\r\n{\r\npublic:\r\n    ps_comp_operator() { _opr = 0; }\r\n    void set_opr(const oprnode* opr) { _opr = opr; }\r\n    void set_opr(const oprinfo& opr) { _opr = opr_manager::get_singleton_ptr()->get_operator(opr); }\r\n    const oprnode* get_opr_info() const { return _opr; }\r\n    bool is_unary() const { return _opr->unary; }\r\n    int get_priority() const { return _opr->prior; }\r\n    const gchar* get_opr_name() const { return _opr->opr; }\r\n    \r\nprotected:\r\n    const oprnode*  _opr;\r\n};\r\n\r\nclass ps_comp_variable\r\n{\r\npublic:\r\n    ps_comp_variable() { _value = 0; }\r\n    void set_value(ps_obj* value) { _value = value; }\r\n    ps_obj* get_value() const { return _value; }\r\n\r\nprotected:\r\n    ps_obj*         _value;\r\n};\r\n\r\nclass ps_comp_constant\r\n{\r\npublic:\r\n    union vdif\r\n    {\r\n        int         i;\r\n        real32      r;\r\n        int64       i64;\r\n        real        r64;\r\n    };\r\n\r\npublic:\r\n    ps_comp_constant() {}\r\n    void set_string(const gchar* str) { _cvtag = ps_obj::vt_string, _vstr = str; }\r\n    void set_integer(int i) { _cvtag = ps_obj::vt_integer, _value.i = i; }\r\n    void set_float(real32 r) { _cvtag = ps_obj::vt_float, _value.r = r; }\r\n    uint get_value_tag() const { return _cvtag; }\r\n    const string& get_string() const { return _vstr; }\r\n    int get_integer() const { return _value.i; }\r\n    real32 get_float() const { return _value.r; }\r\n\r\nprotected:\r\n    uint            _cvtag;\r\n    string          _vstr;\r\n    vdif            _value;\r\n};\r\n\r\nclass ps_comp_function\r\n{\r\npublic:\r\n    ps_comp_function() { _rety = 0, _parent = 0, _retr = false; }\r\n    void set_retv_type(type* ty) { _rety = ty; }\r\n    void set_retv_ref(bool tr) { _retr = tr; }\r\n    type* get_retv_type() const { return _rety; }\r\n    bool get_retv_ref() const { return _retr; }\r\n    void set_parent(ps_obj* obj) { _parent = obj; }\r\n    ps_obj* get_parent() const { return _parent; }\r\n    bool is_top_level() const { return _parent->get_tag() == ps_obj::pt_root; }\r\n\r\nprotected:\r\n    type*           _rety;\r\n    bool            _retr;\r\n    ps_obj*         _parent;\r\n};\r\n\r\nclass ps_comp_statement\r\n{\r\npublic:\r\n    ps_comp_statement() { _condition = 0, _block = 0; }\r\n    void set_condition(ps_obj* condition) { _condition = condition; }\r\n    void set_block(ps_obj* block) { _block = block; }\r\n    ps_obj* get_condition() const { return _condition; }\r\n    ps_obj* get_block() const { return _block; }\r\n\r\nprotected:\r\n    ps_obj*         _condition;\r\n    ps_obj*         _block;\r\n};\r\n\r\nclass ps_comp_if_statement:\r\n    public ps_comp_statement\r\n{\r\npublic:\r\n    ps_comp_if_statement() { _prevbr = _nextbr = _lastbr = 0; }\r\n    void set_prev_branch(ps_obj* branch) { _prevbr = branch; }\r\n    void set_next_branch(ps_obj* branch) { _nextbr = branch; }\r\n    void set_last_branch(ps_obj* branch) { _lastbr = branch; }\r\n    ps_obj* get_prev_branch() const { return _prevbr; }\r\n    ps_obj* get_next_branch() const { return _nextbr; }\r\n    ps_obj* get_last_branch() const { return _lastbr; }\r\n\r\nprotected:\r\n    ps_obj*         _prevbr;\r\n    ps_obj*         _nextbr;\r\n    ps_obj*         _lastbr;\r\n};\r\n\r\nclass ps_comp_loop_statement:\r\n    public ps_comp_statement\r\n{\r\n};\r\n\r\nclass ps_comp_exit_statement\r\n{\r\npublic:\r\n    ps_comp_exit_statement() { _conclusion = 0; }\r\n    void set_conclusion(ps_obj* conclusion) { _conclusion = conclusion; }\r\n    ps_obj* get_conclusion() const { return _conclusion; }\r\n\r\nprotected:\r\n    ps_obj*         _conclusion;\r\n};\r\n\r\ntypedef ps_proto<ps_obj::pt_root, true, ps_trait_hold> ps_root;\r\ntypedef ps_proto<ps_obj::pt_block, true, ps_trait_hold> ps_block;\r\ntypedef ps_proto<ps_obj::pt_value, false, ps_trait_pass, ps_join<ps_obj, ps_comp_value> > ps_value;\r\ntypedef ps_proto<ps_obj::pt_expression, true, ps_trait_pass> ps_expression;\r\ntypedef ps_proto<ps_obj::pt_operator, true, ps_trait_pass, ps_join<ps_obj, ps_comp_operator> > ps_operator;\r\ntypedef ps_proto<ps_obj::pt_function, false, ps_trait_hold, ps_join<ps_obj, ps_comp_function> > ps_function;\r\ntypedef ps_proto<ps_obj::pt_calling, true, ps_trait_pass> ps_calling;\r\ntypedef ps_proto<ps_obj::pt_go_statement, true, ps_trait_pass> ps_go_statement;\r\ntypedef ps_proto<ps_obj::pt_stop_statement, true, ps_trait_pass> ps_stop_statement;\r\ntypedef ps_proto<ps_obj::pt_if_statement, true, ps_trait_pass, ps_join<ps_obj, ps_comp_if_statement> > ps_if_statement;\r\ntypedef ps_proto<ps_obj::pt_loop_statement, true, ps_trait_pass, ps_join<ps_obj, ps_comp_loop_statement> > ps_loop_statement;\r\ntypedef ps_proto<ps_obj::pt_exit_statement, true, ps_trait_pass, ps_join<ps_obj, ps_comp_exit_statement> > ps_exit_statement;\r\ntypedef ps_proto<ps_obj::pt_variable, false, ps_trait_pass, ps_join<ps_obj, ps_comp_variable> > ps_variable;\r\ntypedef ps_proto<ps_obj::pt_constant, false, ps_trait_pass, ps_join<ps_obj, ps_comp_constant> > ps_constant;\r\n\r\nclass parser:\r\n    private tree<ps_obj, _treenode_wrapper<ps_obj> >\r\n{\r\npublic:\r\n    typedef _treenode_wrapper<ps_obj> wrapper;\r\n    typedef ps_obj value;\r\n    typedef tree<ps_obj, wrapper> superref;\r\n    typedef superref::iterator iterator;\r\n    typedef superref::const_iterator const_iterator;\r\n\r\npublic:\r\n    parser() { insert<ps_root>(iterator()); }\r\n    const gchar* get_name() const;\r\n    void set_root(const gchar* name);\r\n    template<class _cst>\r\n    iterator insert(iterator i) { return superref::insert_tail<_cst>(i); }\r\n    template<class _cst>\r\n    iterator birth(iterator i) { return superref::birth_tail<_cst>(i); }\r\n\r\npublic:\r\n    using superref::clear;\r\n    using superref::erase;\r\n    using superref::get_root;\r\n    using superref::for_each;\r\n    using superref::detach;\r\n    using superref::attach;\r\n    using superref::debug_check;\r\n\r\npublic:\r\n    iterator find(iterator i, const gchar* name);\r\n};\r\n\r\n__rathen_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "726b40244fb0eddf5e5230c67bfaea9a0bd54051", "size": 8865, "ext": "h", "lang": "C", "max_stars_repo_path": "include/rathen/parser.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/rathen/parser.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/rathen/parser.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 29.6488294314, "max_line_length": 126, "alphanum_fraction": 0.6541455161, "num_tokens": 2361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09009299396195182, "lm_q2_score": 0.01854656512240668, "lm_q1q2_score": 0.0016709155795879313}}
{"text": "/* -----------------------------------------------------------------------------\n * Copyright 2021 Jonathan Haigh\n * SPDX-License-Identifier: MIT\n * ---------------------------------------------------------------------------*/\n\n#ifndef SQ_INCLUDE_GUARD_system_linux_SqPrimitiveTypeSchemaImpl_h_\n#define SQ_INCLUDE_GUARD_system_linux_SqPrimitiveTypeSchemaImpl_h_\n\n#include \"core/typeutil.h\"\n#include \"system/SqPrimitiveTypeSchema.gen.h\"\n#include \"system/schema.h\"\n\n#include <gsl/gsl>\n\nnamespace sq::system::linux {\n\nclass SqPrimitiveTypeSchemaImpl\n    : public SqPrimitiveTypeSchema<SqPrimitiveTypeSchemaImpl> {\npublic:\n  explicit SqPrimitiveTypeSchemaImpl(\n      const PrimitiveTypeSchema &primitive_type_schema);\n\n  SQ_ND Result get_name() const;\n  SQ_ND Result get_doc() const;\n\n  SQ_ND Primitive to_primitive() const override;\n\nprivate:\n  gsl::not_null<const PrimitiveTypeSchema *> primitive_type_schema_;\n};\n\n} // namespace sq::system::linux\n\n#endif // SQ_INCLUDE_GUARD_system_linux_SqPrimitiveTypeSchemaImpl_h_\n", "meta": {"hexsha": "3928ecc5e879f588423f27cfcf3f6604770f20ae", "size": 1016, "ext": "h", "lang": "C", "max_stars_repo_path": "src/system/include/system/linux/SqPrimitiveTypeSchemaImpl.h", "max_stars_repo_name": "jonathanhaigh/sq", "max_stars_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-12T16:21:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-12T16:21:41.000Z", "max_issues_repo_path": "src/system/include/system/linux/SqPrimitiveTypeSchemaImpl.h", "max_issues_repo_name": "jonathanhaigh/sq", "max_issues_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 44.0, "max_issues_repo_issues_event_min_datetime": "2021-02-08T19:17:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-05T18:51:38.000Z", "max_forks_repo_path": "src/system/include/system/linux/SqPrimitiveTypeSchemaImpl.h", "max_forks_repo_name": "jonathanhaigh/sq", "max_forks_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0285714286, "max_line_length": 80, "alphanum_fraction": 0.6811023622, "num_tokens": 205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.0715912053870672, "lm_q2_score": 0.023330768511379073, "lm_q1q2_score": 0.0016702778403362593}}
{"text": "//          Copyright Jean Pierre Cimalando 2019.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE.md or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n#pragma once\n#include <gsl/gsl>\n#include <string>\n\nstd::string get_home_directory();\nstd::string get_current_directory();\nbool is_path_absolute(gsl::cstring_span path);\nbool is_path_separator(char32_t character);\nvoid append_path_separator(std::string &path);\nstd::string normalize_path_separators(gsl::cstring_span path);\nstd::string make_path_canonical(gsl::cstring_span path);\nstd::string expand_path_tilde(gsl::cstring_span path);\ngsl::cstring_span path_file_name(gsl::cstring_span path);\ngsl::cstring_span path_directory(gsl::cstring_span path);\n\nstd::string get_display_path(gsl::cstring_span path);\n\n#if defined(_WIN32)\nstd::string known_folder_path(int csidl, std::error_code &ec);\nstd::string known_folder_path(int csidl);\n#endif\n", "meta": {"hexsha": "8e95320a7bdfd47d96c5d58f1d3e5d29a5b729e1", "size": 953, "ext": "h", "lang": "C", "max_stars_repo_path": "sources/utility/paths.h", "max_stars_repo_name": "jpcima/smf-dsp", "max_stars_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2020-07-08T15:23:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T23:08:17.000Z", "max_issues_repo_path": "sources/utility/paths.h", "max_issues_repo_name": "jpcima/smf-dsp", "max_issues_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2020-07-05T23:59:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-16T20:44:07.000Z", "max_forks_repo_path": "sources/utility/paths.h", "max_forks_repo_name": "jpcima/smf-dsp", "max_forks_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-07-10T18:48:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-22T08:05:13.000Z", "avg_line_length": 35.2962962963, "max_line_length": 62, "alphanum_fraction": 0.777544596, "num_tokens": 230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.07263670033827889, "lm_q2_score": 0.022977370579070188, "lm_q1q2_score": 0.001669000381313507}}
{"text": "// Distributed under MIT License, see LICENSE file\n// (c) 2018 Zbigniew Skowron, zbychs@gmail.com\n\n#pragma once\n\n#include \"text_buffer.h\"\n#include \"text_parser.h\"\n#include \"text_renderer.h\"\n#include \"geometry.h\"\n\n#include <string>\n#include <vector>\n#include <iostream>\n\n#include <gsl/span>\n\nnamespace terminal_editor {\n\n/// This class describes position in a TextBuffer.\n/// Positions are logically between characters.\nstruct GraphemePosition : Position {\n    int screenColumn; ///< Column on the screen (zero indexed).\n\n    GraphemePosition() : screenColumn(0) {}\n    GraphemePosition(Position position, int screenColumn) : Position(position), screenColumn(screenColumn) {}\n\n    friend std::ostream& operator<<(std::ostream& os, GraphemePosition graphemePosition) {\n        return os << \"GraphemePosition{\" << graphemePosition.row << \", \" << graphemePosition.column << \", scrCol=\" << graphemePosition.screenColumn << \"}\";\n    }\n};\n\n/// This class is an editable container of lines of graphemes.\n/// @note By screen coordinates below we mean coordinates that take into account rendered sizes of graphemes in screen cells, but not window position or text offset inside a window.\n/// @note This is a very straighforward implementation. It is not efficient.\nclass GraphemeBuffer {\nprivate:\n    TextBuffer& m_textBuffer;\n    std::vector<std::vector<Grapheme>> renderedLines; ///< Will always have at least one line.\n\npublic:\n    GraphemeBuffer(TextBuffer& textBuffer);\n\n    /// Empty virtual destructor.\n    virtual ~GraphemeBuffer() {\n    }\n\n    /// Replaces contents of this text buffer with contents of given file.\n    /// @param fileName     Name of file to load.\n    virtual void loadFile(const std::string& fileName);\n\n    /// Returns number of lines in this text buffer.\n    /// @note It will always be 1 + number of LF's in file.\n    int getNumberOfLines() const;\n\n    /// Returns length of the longest line, on screen.\n    int getLongestLineLength() const;\n\n    /// Returns contents of given line.\n    /// If row is less than zero or greater than number of lines - 1, empty span is returned.\n    /// Span is valid only until next edit on the buffer.\n    /// @param row          Row to return (zero indexed).\n    gsl::span<const Grapheme> getLine(int row) const;\n\n    /// Returns part of given line from colStart (inclusive) to colEnd (exclusive).\n    /// colStart and colEnd are first clamped to the range 0 (inclusive) to line length (inclusive).\n    /// Span is valid only until next edit on the buffer.\n    /// @param row          Row to return (zero indexed).\n    /// @param colStart     First grapheme to return (zero indexed).\n    /// @param colEnd       One past last grapheme to return (zero indexed).\n    gsl::span<const Grapheme> getLineRange(int row, int colStart, int colEnd) const;\n\n    /// Returns Point that corresponds to screen coordinates of given Position.\n    /// @param Position     Position of a grapheme (can be one past end of line).\n    /// @return Point in screen coordinates of first cell of the grapheme.\n    [[nodiscard]]\n    Point positionToPoint(Position position);\n\n    /// Returns Position that corresponds to given Point in screen coordinates.\n    /// @note If point row is outside of row bounds, it is clamped to valid range.\n    /// @note If point is after the line end, returns position one past end of line.\n    /// @note If point is before the line start, returns position of first grapheme in line.\n    /// @param point    Point in screen coordinates.\n    /// @param after    If point is not on first screen cell of a grapheme, return position after a grapheme.\n    ///                 Otherwise return position of grapheme under point.\n    /// @return Position of grapheme under point (can be one past end of line).\n    ///         Returned Position is clamped to valid line row/column.\n    [[nodiscard]]\n    Position pointToPosition(Point point, bool after);\n\n    /// Inserts given text into this grapheme buffer.\n    /// position is first clamped to a valid range.\n    /// @param position     Position to insert into.\n    /// @param text         Text to insert. May contain new lines. Doesn't have to be valid UTF-8.\n    /// @returns Position of the end of inserted text in the new grapheme buffer.\n    virtual Position insertText(Position position, const std::string& text);\n\n    /// Deletes text between two positions: from startPosition (inclusive) to endPosition (exclusive).\n    /// positions are first clamped to valid range.\n    /// positions can be on different lines.\n    /// If startPosition is past endPosition no characters are removed.\n    /// @param startPosition    Start position. This is first position that will be removed.\n    /// @param endPosition      End position. This is first position that will not be removed.\n    /// @returns Characters removed (including newlines).\n    virtual std::string deleteText(Position startPosition, Position endPosition);\n\n    /// Clamps position to a valid range, so:\n    /// - row is clamped to range from 0 to number of lines (inclusive),\n    /// - column is clamped to range from 0 to line length (inclusive).\n    [[nodiscard]]\n    Position clampPosition(Position position) const;\n\nprotected:\n    /// Maps grapheme position to position in underlying text buffer.\n    [[nodiscard]]\n    Position positionToTextPosition(Position position) const;\n\n    /// Maps position in underlying text buffer to grapheme position.\n    /// @param after    If position is not on first byte of a grapheme, return position after a grapheme.\n    ///                 Otherwise return position of grapheme with given byte.\n    [[nodiscard]]\n    Position textPositionToPosition(Position textPosition, bool after) const;\n\n    /// Re-renders all lines based on TextBuffer.\n    /// renderedLines is re-initialized.\n    void rerenderAllLines();\n\n    /// Re-renders given line.\n    void rerenderLine(int row);\n};\n\n} // namespace terminal_editor\n", "meta": {"hexsha": "fd74b73a29b9364c3d421b1c9ffd904e10c750f7", "size": 5922, "ext": "h", "lang": "C", "max_stars_repo_path": "editorlib/grapheme_buffer.h", "max_stars_repo_name": "Zbyl/terminal-editor", "max_stars_repo_head_hexsha": "375ac936f09543bab9c01fcb5a2dc8de9af83a58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "editorlib/grapheme_buffer.h", "max_issues_repo_name": "Zbyl/terminal-editor", "max_issues_repo_head_hexsha": "375ac936f09543bab9c01fcb5a2dc8de9af83a58", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "editorlib/grapheme_buffer.h", "max_forks_repo_name": "Zbyl/terminal-editor", "max_forks_repo_head_hexsha": "375ac936f09543bab9c01fcb5a2dc8de9af83a58", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-12-21T00:37:06.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-21T00:37:06.000Z", "avg_line_length": 44.8636363636, "max_line_length": 181, "alphanum_fraction": 0.6992570078, "num_tokens": 1292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11124119472172639, "lm_q2_score": 0.01495708310788378, "lm_q1q2_score": 0.001663843794473144}}
{"text": "#pragma once\n\n#if __has_include(<span>) && (__cplusplus > 201703L)\n#include <span>\n#else\n#include <gsl/span>\nnamespace std {\ntemplate <class T, std::size_t Extent = gsl::dynamic_extent>\nusing span = gsl::span<T, Extent>;\n}\n#endif\n", "meta": {"hexsha": "66496e0962b5343c2cee36d8457d15f55ceeb6b5", "size": 230, "ext": "h", "lang": "C", "max_stars_repo_path": "include/infra/span.h", "max_stars_repo_name": "VITObelgium/cpp-infra", "max_stars_repo_head_hexsha": "2a95a112439b21ff9125c2e6e29810a418b94a4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-23T03:15:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T03:15:54.000Z", "max_issues_repo_path": "include/infra/span.h", "max_issues_repo_name": "VITObelgium/cpp-infra", "max_issues_repo_head_hexsha": "2a95a112439b21ff9125c2e6e29810a418b94a4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/infra/span.h", "max_forks_repo_name": "VITObelgium/cpp-infra", "max_forks_repo_head_hexsha": "2a95a112439b21ff9125c2e6e29810a418b94a4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.1666666667, "max_line_length": 60, "alphanum_fraction": 0.7043478261, "num_tokens": 65, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.0526189548333655, "lm_q2_score": 0.03161876761083971, "lm_q1q2_score": 0.0016637465048014546}}
{"text": "#pragma once\n#include \"iparam.h\"\n#include \"configaccess.h\"\n#include \"optioninfo.h\"\n#include \"format.h\"\n#include \"streamreader.h\"\n#include <gsl/gsl>\n#include <cmdlime/errors.h>\n#include <cmdlime/customnames.h>\n#include <sstream>\n#include <optional>\n#include <memory>\n#include <functional>\n\nnamespace cmdlime::detail{\n\ntemplate<typename T>\nclass Param : public IParam{\npublic:\n    Param(std::string name,\n          std::string shortName,\n          std::string type,\n          std::function<T&()> paramGetter)\n        : info_(std::move(name), std::move(shortName), std::move(type))\n        , paramGetter_(std::move(paramGetter))\n    {       \n    }\n\n    void setDefaultValue(const T& value)\n    {\n        hasValue_ = true;\n        defaultValue_ = value;\n    }\n\n    OptionInfo& info() override\n    {\n        return info_;\n    }\n\n    const OptionInfo& info() const override\n    {\n        return info_;\n    }\n\nprivate:\n    bool read(const std::string& data) override\n    {\n        auto stream = std::stringstream{data};\n        if (!readFromStream(stream, paramGetter_()))\n            return false;\n        hasValue_ = true;\n        return true;\n    }\n\n    bool hasValue() const override\n    {\n        return hasValue_;\n    }\n\n    bool isOptional() const override\n    {\n        return defaultValue_.has_value();\n    }\n\n    std::string defaultValue() const override\n    {\n        if (!defaultValue_.has_value())\n            return {};\n        auto stream = std::stringstream{};\n        stream << defaultValue_.value();\n        return stream.str();\n    }\n\nprivate:\n    OptionInfo info_;\n    std::function<T&()> paramGetter_;\n    std::optional<T> defaultValue_;\n    bool hasValue_ = false;\n};\n\ntemplate <>\ninline bool Param<std::string>::read(const std::string& data)\n{    \n    paramGetter_() = data;\n    hasValue_ = true;\n    return true;\n}\n\ntemplate<typename T, typename TConfig>\nclass ParamCreator{\n    using NameProvider = typename Format<ConfigAccess<TConfig>::format()>::nameProvider;\npublic:\n    ParamCreator(TConfig& cfg,\n                 const std::string& varName,\n                 const std::string& type,\n                 std::function<T&()> paramGetter)\n        : cfg_(cfg)\n    {\n        Expects(!varName.empty());\n        Expects(!type.empty());\n        param_ = std::make_unique<Param<T>>(NameProvider::name(varName),\n                                            NameProvider::shortName(varName),\n                                            NameProvider::valueName(type),\n                                            std::move(paramGetter));\n    }\n\n    ParamCreator<T, TConfig>& operator<<(const std::string& info)\n    {\n        param_->info().addDescription(info);\n        return *this;\n    }\n\n    ParamCreator<T, TConfig>& operator<<(const Name& customName)\n    {\n        param_->info().resetName(customName.value());\n        return *this;\n    }\n\n    ParamCreator<T, TConfig>& operator<<(const ShortName& customName)\n    {\n        static_assert(Format<ConfigAccess<TConfig>::format()>::shortNamesEnabled,\n                      \"Current command line format doesn't support short names\");\n        param_->info().resetShortName(customName.value());\n        return *this;\n    }\n\n    ParamCreator<T, TConfig>& operator<<(const WithoutShortName&)\n    {\n        static_assert(Format<ConfigAccess<TConfig>::format()>::shortNamesEnabled,\n                      \"Current command line format doesn't support short names\");\n        param_->info().resetShortName({});\n        return *this;\n    }\n\n    ParamCreator<T, TConfig>& operator<<(const ValueName& valueName)\n    {\n        param_->info().resetValueName(valueName.value());\n        return *this;\n    }\n\n    ParamCreator<T, TConfig>& operator()(T defaultValue = {})\n    {\n        defaultValue_ = std::move(defaultValue);\n        param_->setDefaultValue(defaultValue_);\n        return *this;\n    }\n\n    operator T()\n    {\n        ConfigAccess<TConfig>{cfg_}.addParam(std::move(param_));\n        return defaultValue_;\n    }\n\nprivate:\n    std::unique_ptr<Param<T>> param_;\n    T defaultValue_;\n    TConfig& cfg_;\n};\n\ntemplate <typename T, typename TConfig>\nParamCreator<T, TConfig> makeParamCreator(TConfig& cfg,\n                                          const std::string& varName,\n                                          const std::string& type,\n                                          std::function<T&()> paramGetter)\n{\n    return ParamCreator<T, TConfig>{cfg, varName, type, std::move(paramGetter)};\n}\n\n}\n", "meta": {"hexsha": "7b1a3e27ad2c9038c5763fdb1f6bfd875b9ba5f8", "size": 4456, "ext": "h", "lang": "C", "max_stars_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/param.h", "max_stars_repo_name": "GerHobbelt/hypertextcpp", "max_stars_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_stars_repo_licenses": ["MS-PL"], "max_stars_count": 77.0, "max_stars_repo_stars_event_min_datetime": "2021-05-20T18:05:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T21:37:54.000Z", "max_issues_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/param.h", "max_issues_repo_name": "GerHobbelt/hypertextcpp", "max_issues_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_issues_repo_licenses": ["MS-PL"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2021-05-20T22:04:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-21T08:13:28.000Z", "max_forks_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/param.h", "max_forks_repo_name": "GerHobbelt/hypertextcpp", "max_forks_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_forks_repo_licenses": ["MS-PL"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-22T00:36:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-22T00:36:08.000Z", "avg_line_length": 26.2117647059, "max_line_length": 88, "alphanum_fraction": 0.5821364452, "num_tokens": 968, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07807816514495096, "lm_q2_score": 0.02128735167703089, "lm_q1q2_score": 0.0016620773597378665}}
{"text": "#ifndef DART_COMMON_H\n#define DART_COMMON_H\n\n// Automatically detect libraries if possible.\n#if defined(__has_include)\n# if !defined(DART_HAS_RAPIDJSON)\n#   define DART_HAS_RAPIDJSON __has_include(<rapidjson/reader.h>) && __has_include(<rapidjson/writer.h>)\n# endif\n# ifndef DART_HAS_YAML\n#   define DART_HAS_YAML __has_include(<yaml.h>)\n# endif\n#endif\n\n/*----- System Includes -----*/\n\n#include <map>\n#include <vector>\n#include <math.h>\n#include <gsl/gsl>\n#include <errno.h>\n#include <cstdlib>\n#include <stdarg.h>\n#include <limits.h>\n#include <algorithm>\n\n\n#if DART_HAS_RAPIDJSON\n#include <rapidjson/reader.h>\n#include <rapidjson/writer.h>\n#include <rapidjson/document.h>\n#include <rapidjson/error/en.h>\n#endif\n\n#if DART_HAS_YAML\n#include <yaml.h>\n#endif\n\n/*----- Local Includes -----*/\n\n#include \"shim.h\"\n#include \"meta.h\"\n#include \"support/ptrs.h\"\n#include \"support/ordered.h\"\n\n/*----- System Includes with Compiler Flags -----*/\n\n// Current version of sajson emits unused parameter\n// warnings on Clang.\n#ifdef DART_USE_SAJSON\n#if DART_USING_CLANG\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wunknown-pragmas\"\n#pragma clang diagnostic ignored \"-Wunused-parameter\"\n#endif\n#include <sajson.h>\n#if DART_USING_CLANG\n#pragma clang diagnostic pop\n#endif\n#endif\n\n/*----- Macro Definitions -----*/\n\n#define DART_FROM_THIS                                                                                        \\\n  reinterpret_cast<gsl::byte const*>(this)\n\n#define DART_FROM_THIS_MUT                                                                                    \\\n  reinterpret_cast<gsl::byte*>(this)\n\n/*----- Global Declarations -----*/\n\nnamespace dart {\n\n  template <class Object>\n  class basic_object;\n  template <class Array>\n  class basic_array;\n  template <class String>\n  class basic_string;\n  template <class Number>\n  class basic_number;\n  template <class Boolean>\n  class basic_flag;\n  template <class Null>\n  class basic_null;\n\n  template <template <class> class RefCount>\n  class basic_heap;\n  template <template <class> class RefCount>\n  class basic_buffer;\n  template <template <class> class RefCount>\n  class basic_packet;\n\n  struct type_error : std::logic_error {\n    type_error(char const* msg) : logic_error(msg) {}\n  };\n\n  struct state_error : std::runtime_error {\n    state_error(char const* msg) : runtime_error(msg) {}\n  };\n\n  struct parse_error : std::runtime_error {\n    parse_error(char const* msg) : runtime_error(msg) {}\n  };\n\n  struct validation_error : std::runtime_error {\n    validation_error(char const* msg) : runtime_error(msg) {}\n  };\n\n  namespace detail {\n\n    template <class T>\n    struct is_dart_type : std::false_type {};\n    template <template <class> class RC>\n    struct is_dart_type<dart::basic_heap<RC>> : std::true_type {};\n    template <template <class> class RC>\n    struct is_dart_type<dart::basic_buffer<RC>> : std::true_type {};\n    template <template <class> class RC>\n    struct is_dart_type<dart::basic_packet<RC>> : std::true_type {};\n\n    template <class T>\n    struct is_wrapper_type : std::false_type {};\n    template <class T>\n    struct is_wrapper_type<dart::basic_object<T>> : std::true_type {};\n    template <class T>\n    struct is_wrapper_type<dart::basic_array<T>> : std::true_type {};\n    template <class T>\n    struct is_wrapper_type<dart::basic_string<T>> : std::true_type {};\n    template <class T>\n    struct is_wrapper_type<dart::basic_number<T>> : std::true_type {};\n    template <class T>\n    struct is_wrapper_type<dart::basic_flag<T>> : std::true_type {};\n    template <class T>\n    struct is_wrapper_type<dart::basic_null<T>> : std::true_type {};\n\n    template <class T>\n    struct is_dart_api_type : std::false_type {};\n    template <template <class> class RC>\n    struct is_dart_api_type<dart::basic_heap<RC>> : std::true_type {};\n    template <template <class> class RC>\n    struct is_dart_api_type<dart::basic_buffer<RC>> : std::true_type {};\n    template <template <class> class RC>\n    struct is_dart_api_type<dart::basic_packet<RC>> : std::true_type {};\n    template <class T>\n    struct is_dart_api_type<dart::basic_object<T>> : std::true_type {};\n    template <class T>\n    struct is_dart_api_type<dart::basic_array<T>> : std::true_type {};\n    template <class T>\n    struct is_dart_api_type<dart::basic_string<T>> : std::true_type {};\n    template <class T>\n    struct is_dart_api_type<dart::basic_number<T>> : std::true_type {};\n    template <class T>\n    struct is_dart_api_type<dart::basic_flag<T>> : std::true_type {};\n    template <class T>\n    struct is_dart_api_type<dart::basic_null<T>> : std::true_type {};\n\n    template <class T>\n    struct maybe_cast_return {\n      template <class U, class =\n        std::enable_if_t<\n          std::is_pointer<U>::value\n          ||\n          is_dart_type<U>::value\n        >\n      >\n      static U detect(int);\n\n      template <class U>\n      static shim::optional<U> detect(...);\n\n      using type = decltype(detect<T>(0));\n    };\n    template <class T>\n    using maybe_cast_return_t = typename maybe_cast_return<T>::type;\n\n    /**\n     *  @brief\n     *  Enum encodes the type of an individual packet instance.\n     *\n     *  @details\n     *  Internally, dart::packet manages a much larger set of types that encode ancillary information\n     *  such as precision, signedness, alignment, size, however, all internal types map onto one of those\n     *  contained in dart::packet::type, and all public API functions conceptually interact with objects\n     *  of these types.\n     */\n    enum class type : uint8_t {\n      object,\n      array,\n      string,\n      integer,\n      decimal,\n      boolean,\n      null\n    };\n\n    /**\n     *  @brief\n     *  Low-level type information that encodes information about the underlying machine-type,\n     *  like precision, signedness, etc.\n     */\n    enum class raw_type : uint8_t {\n      object,\n      array,\n      string,\n      small_string,\n      big_string,\n      short_integer,\n      integer,\n      long_integer,\n      decimal,\n      long_decimal,\n      boolean,\n      null\n    };\n\n    /**\n     *  @brief\n     *  Used internally in scenarios where two dart types aren't contained within\n     *  some existing data structure, but they need to be paired together.\n     */\n    template <class Packet>\n    struct basic_pair {\n\n      /*----- Lifecycle Functions -----*/\n\n      basic_pair() = default;\n      template <class P, class =\n        std::enable_if_t<\n          std::is_convertible<\n            P,\n            Packet\n          >::value\n        >\n      >\n      basic_pair(P&& key, P&& value) : key(std::forward<P>(key)), value(std::forward<P>(value)) {}\n      basic_pair(basic_pair const&) = default;\n      basic_pair(basic_pair&&) = default;\n      ~basic_pair() = default;\n\n      /*----- Operators -----*/\n\n      basic_pair& operator =(basic_pair const&) = default;\n      basic_pair& operator =(basic_pair&&) = default;\n\n      /*----- Members -----*/\n\n      Packet key, value;\n\n    };\n    template <template <class> class RefCount>\n    using heap_pair = basic_pair<basic_heap<RefCount>>;\n    template <template <class> class RefCount>\n    using buffer_pair = basic_pair<basic_buffer<RefCount>>;\n    template <template <class> class RefCount>\n    using packet_pair = basic_pair<basic_packet<RefCount>>;\n\n    /**\n     *  @brief\n     *  Helper-struct for sorting `dart::packet`s within `std::map`s.\n     */\n    template <template <class> class RefCount>\n    struct dart_comparator {\n      using is_transparent = shim::string_view;\n\n      bool operator ()(shim::string_view lhs, shim::string_view rhs) const;\n\n      // Comparison between some packet type and a string\n      template <template <template <class> class> class Packet>\n      bool operator ()(Packet<RefCount> const& lhs, shim::string_view rhs) const;\n      template <template <template <class> class> class Packet>\n      bool operator ()(shim::string_view lhs, Packet<RefCount> const& rhs) const;\n\n      // Comparison between a key-value pair of some packet type and a string\n      template <template <template <class> class> class Packet>\n      bool operator ()(basic_pair<Packet<RefCount>> const& lhs, shim::string_view rhs) const;\n      template <template <template <class> class> class Packet>\n      bool operator ()(shim::string_view lhs, basic_pair<Packet<RefCount>> const& rhs) const;\n\n      // Comparison between two, potentially disparate, packet types\n      template <\n        template <template <class> class> class LhsPacket,\n        template <template <class> class> class RhsPacket\n      >\n      bool operator ()(LhsPacket<RefCount> const& lhs, RhsPacket<RefCount> const& rhs) const;\n\n      // Comparison between a key-value pair of some packet type and some,\n      // potentially disparate, packet type\n      template <\n        template <template <class> class> class LhsPacket,\n        template <template <class> class> class RhsPacket\n      >\n      bool operator ()(basic_pair<LhsPacket<RefCount>> const& lhs, RhsPacket<RefCount> const& rhs) const;\n      template <\n        template <template <class> class> class LhsPacket,\n        template <template <class> class> class RhsPacket\n      >\n      bool operator ()(LhsPacket<RefCount> const& lhs, basic_pair<RhsPacket<RefCount>> const& rhs) const;\n\n      // Comparison between a key-value pair of some packet type and\n      // a key-value pair of some, potentially disparate, packet type.\n      template <\n        template <template <class> class> class LhsPacket,\n        template <template <class> class> class RhsPacket\n      >\n      bool operator ()(basic_pair<LhsPacket<RefCount>> const& lhs, basic_pair<RhsPacket<RefCount>> const& rhs) const;\n    };\n\n    struct dynamic_string_layout {\n      bool operator ==(dynamic_string_layout const& other) const noexcept {\n        if (len != other.len) return false;\n        else return !strcmp(ptr.get(), other.ptr.get());\n      }\n      bool operator !=(dynamic_string_layout const& other) const noexcept {\n        return !(*this == other);\n      }\n\n      std::shared_ptr<char> ptr;\n      size_t len;\n    };\n    struct inline_string_layout {\n      bool operator ==(inline_string_layout const& other) const noexcept {\n        if (left != other.left) return false;\n        else return !strcmp(buffer.data(), other.buffer.data());\n      }\n      bool operator !=(inline_string_layout const& other) const noexcept {\n        return !(*this == other);\n      }\n\n      std::array<char, sizeof(dynamic_string_layout) - sizeof(uint8_t)> buffer;\n      uint8_t left;\n    };\n\n    /**\n     *  @brief\n     *  Helper-struct for safely comparing objects of any type.\n     */\n    struct typeless_comparator {\n      template <class Lhs, class Rhs>\n      bool operator ()(Lhs&& lhs, Rhs&& rhs) const noexcept;\n    };\n\n    template <template <class> class RefCount>\n    using buffer_refcount_type = shareable_ptr<RefCount<gsl::byte const>>;\n\n    class prefix_entry;\n    template <class>\n    struct table_layout {\n      using offset_type = uint32_t;\n      static constexpr auto max_offset = std::numeric_limits<offset_type>::max();\n\n      alignas(4) little_order<offset_type> offset;\n      alignas(4) little_order<uint8_t> type;\n    };\n    template <>\n    struct table_layout<prefix_entry> {\n      using offset_type = uint32_t;\n      using prefix_type = uint16_t;\n      static constexpr auto max_offset = std::numeric_limits<offset_type>::max();\n\n      alignas(4) little_order<uint32_t> offset;\n      alignas(1) little_order<uint8_t> type;\n      alignas(1) little_order<uint8_t> len;\n      alignas(2) prefix_type prefix;\n    };\n\n    /**\n     *  @brief\n     *  Macro customizes functionality usually provided by assert().\n     *\n     *  @details\n     *  Not strictly necessary, but tries to provide a bit more context and\n     *  information as to why I just murdered the user's program (in production, no doubt).\n     *\n     *  @remarks\n     *  Don't actually know if Doxygen lets you document macros, guess we'll see.\n     */\n    template <class T>\n    class vtable_entry {\n\n      public:\n\n        /*----- Lifecycle Functions -----*/\n\n        vtable_entry(detail::raw_type type, uint32_t offset);\n        vtable_entry(vtable_entry const&) = default;\n\n        /*----- Operators -----*/\n\n        vtable_entry& operator =(vtable_entry const&) = default;\n\n        /*----- Public API -----*/\n\n        raw_type get_type() const noexcept;\n        uint32_t get_offset() const noexcept;\n\n        // This sucks, but we need it for dart::buffer::inject\n        void adjust_offset(std::ptrdiff_t diff) noexcept;\n\n      protected:\n\n        /*----- Protected Members -----*/\n\n        table_layout<T> layout;\n\n    };\n\n    /**\n     *  @brief\n     *  Class represents an entry in the vtable of an object.\n     *\n     *  @details\n     *  Class wraps memory that is stored in little endian byte order,\n     *  irrespective of the native ordering of the host machine.\n     *  In other words, attempt to subvert its API at your peril.\n     *\n     *  @remarks\n     *  Although class inherts from vtable_entry, and can be safely\n     *  be used as such, it remains a standard layout type due to some\n     *  hackery with its internals.\n     */\n    class prefix_entry : public vtable_entry<prefix_entry> {\n\n      public:\n\n        /*----- Public Types -----*/\n\n        using prefix_type = table_layout<prefix_entry>::prefix_type;\n\n        /*----- Lifecycle Functions -----*/\n\n        inline prefix_entry(detail::raw_type type, uint32_t offset, shim::string_view prefix) noexcept;\n        prefix_entry(prefix_entry const&) = default;\n\n        /*----- Operators -----*/\n\n        prefix_entry& operator =(prefix_entry const&) = default;\n\n        /*----- Public API -----*/\n\n        inline int prefix_compare(shim::string_view str) const noexcept;\n\n      private:\n\n        /*----- Private Helpers -----*/\n\n        inline int compare_impl(char const* const str, size_t const len) const noexcept;\n\n        /*----- Private Types -----*/\n\n        using storage_t = std::aligned_storage_t<sizeof(prefix_type), 4>;\n\n    };\n\n    using object_entry = prefix_entry;\n    using array_entry = vtable_entry<void>;\n    using object_layout = table_layout<prefix_entry>;\n    using array_layout = table_layout<void>;\n    static_assert(std::is_standard_layout<array_entry>::value, \"dart library is misconfigured\");\n    static_assert(std::is_standard_layout<object_entry>::value, \"dart library is misconfigured\");\n\n    // Aliases for STL structures.\n    template <template <class> class RefCount>\n    using packet_elements = std::vector<refcount::owner_indirection_t<basic_heap, RefCount>>;\n    template <template <class> class RefCount>\n    using packet_fields = std::map<\n      refcount::owner_indirection_t<basic_heap, RefCount>,\n      refcount::owner_indirection_t<basic_heap, RefCount>,\n      refcount::owner_indirection_t<dart_comparator, RefCount>\n    >;\n\n    /**\n     *  @brief\n     *  Struct represents the minimum context required to perform\n     *  an operation on a dart::buffer object.\n     *\n     *  @details\n     *  At its core, this is what dart::buffer \"is\".\n     *  It just provides a nice API, and some memory safety around\n     *  this structure, which is why it's so fast.\n     */\n    struct raw_element {\n      raw_type type;\n      gsl::byte const* buffer;\n    };\n\n    /**\n     *  @brief\n     *  Struct is the lowest level abstraction for safe iteration over a dart::buffer\n     *  object/array.\n     *\n     *  @details\n     *  Struct holds onto the context for what vtable entry it's currently on,\n     *  where the base of its aggregate is, and how to dereference itself.\n     *\n     *  @remarks\n     *  ll_iterator holds onto more state than I'd like, but it's kind of unavoidable\n     *  given the fact that the vtable provides offsets from the base of the aggregate\n     *  itself and the fact that we may be iterating over values OR pairs of values.\n     */\n    template <template <class> class RefCount>\n    struct ll_iterator {\n\n      /*----- Types -----*/\n\n      using value_type = raw_element;\n      using loading_function = value_type (gsl::byte const*, size_t idx);\n\n      /*----- Lifecycle Functions -----*/\n\n      ll_iterator() = delete;\n      ll_iterator(size_t idx, gsl::byte const* base, loading_function* load_func) noexcept :\n        idx(idx),\n        base(base),\n        load_func(load_func)\n      {}\n      ll_iterator(ll_iterator const&) = default;\n      ll_iterator(ll_iterator&&) noexcept = default;\n      ~ll_iterator() = default;\n\n      /*----- Operators -----*/\n\n      ll_iterator& operator =(ll_iterator const&) = default;\n      ll_iterator& operator =(ll_iterator&&) noexcept = default;\n\n      bool operator ==(ll_iterator const& other) const noexcept;\n      bool operator !=(ll_iterator const& other) const noexcept;\n\n      auto operator ++() noexcept -> ll_iterator&;\n      auto operator --() noexcept -> ll_iterator&;\n      auto operator ++(int) noexcept -> ll_iterator;\n      auto operator --(int) noexcept -> ll_iterator;\n\n      auto operator *() const noexcept -> value_type;\n\n      /*----- Members -----*/\n\n      size_t idx;\n      gsl::byte const* base;\n      loading_function* load_func;\n\n    };\n\n    /**\n     *  @brief\n     *  Struct is the lowest level abstraction for safe iteration over a dart::heap\n     *  object/array.\n     *\n     *  @details\n     *  Struct simply wraps an STL iterator of some type, and a way to dereference it.\n     */\n    template <template <class> class RefCount>\n    struct dn_iterator {\n\n      /*----- Types -----*/\n\n      using value_type = basic_heap<RefCount>;\n      using reference = value_type const&;\n      using fields_deref_func = reference (typename packet_fields<RefCount>::const_iterator const&);\n      using elements_deref_func = reference (typename packet_elements<RefCount>::const_iterator const&);\n\n      struct fields_layout {\n        fields_deref_func* deref;\n        typename packet_fields<RefCount>::const_iterator it;\n      };\n\n      struct elements_layout {\n        elements_deref_func* deref;\n        typename packet_elements<RefCount>::const_iterator it;\n      };\n\n      using implerator = shim::variant<fields_layout, elements_layout>;\n\n      /*----- Lifecycle Functions -----*/\n\n      dn_iterator() = delete;\n      dn_iterator(typename packet_fields<RefCount>::const_iterator it, fields_deref_func* func) noexcept :\n        impl(fields_layout {func, it})\n      {}\n      dn_iterator(typename packet_elements<RefCount>::const_iterator it, elements_deref_func* func) noexcept :\n        impl(elements_layout {func, it})\n      {}\n      dn_iterator(dn_iterator const&) = default;\n      dn_iterator(dn_iterator&&) noexcept = default;\n      ~dn_iterator() = default;\n\n      /*----- Operators -----*/\n\n      dn_iterator& operator =(dn_iterator const&) = default;\n      dn_iterator& operator =(dn_iterator&&) noexcept = default;\n\n      bool operator ==(dn_iterator const& other) const noexcept;\n      bool operator !=(dn_iterator const& other) const noexcept;\n\n      auto operator ++() noexcept -> dn_iterator&;\n      auto operator --() noexcept -> dn_iterator&;\n      auto operator ++(int) noexcept -> dn_iterator;\n      auto operator --(int) noexcept -> dn_iterator;\n\n      auto operator *() const noexcept -> reference;\n\n      /*----- Members -----*/\n\n      implerator impl;\n\n    };\n    template <template <class> class RefCount>\n    using dynamic_iterator = refcount::owner_indirection_t<dn_iterator, RefCount>;\n\n    /**\n     *  @brief\n     *  Class is the lowest level abstraction for safe interaction with\n     *  a dart::buffer object.\n     *\n     *  @details\n     *  Class wraps memory that is stored in little endian byte order,\n     *  irrespective of the native ordering of the host machine.\n     *  In other words, attempt to subvert its API at your peril.\n     */\n    template <template <class> class RefCount>\n    class object {\n\n      public:\n\n        /*----- Lifecycle Functions -----*/\n\n        object() = delete;\n\n        // JSON Constructors\n#ifdef DART_USE_SAJSON\n        explicit object(sajson::value fields) noexcept;\n#endif\n#if DART_HAS_RAPIDJSON\n        explicit object(rapidjson::Value const& fields) noexcept;\n#endif\n\n        // Direct constructors\n        explicit object(gsl::span<packet_pair<RefCount>> pairs) noexcept;\n        explicit object(packet_fields<RefCount> const* fields) noexcept;\n\n        // Special constructors\n        object(object const* base, object const* incoming) noexcept;\n        template <class Key>\n        object(object const* base, gsl::span<Key const*> key_ptrs) noexcept;\n\n        object(object const&) = delete;\n        ~object() = delete;\n\n        /*----- Operators -----*/\n\n        object& operator =(object const&) = delete;\n\n        /*----- Public API -----*/\n\n        template <bool silent>\n        bool is_valid(size_t bytes) const noexcept(silent);\n\n        size_t size() const noexcept;\n        size_t get_sizeof() const noexcept;\n\n        auto begin() const noexcept -> ll_iterator<RefCount>;\n        auto key_begin() const noexcept -> ll_iterator<RefCount>;\n        auto end() const noexcept -> ll_iterator<RefCount>;\n        auto key_end() const noexcept -> ll_iterator<RefCount>;\n\n        template <class Callback>\n        auto get_key(shim::string_view const key, Callback&& cb) const noexcept -> raw_element;\n        auto get_it(shim::string_view const key) const noexcept -> ll_iterator<RefCount>;\n        auto get_key_it(shim::string_view const key) const noexcept -> ll_iterator<RefCount>;\n        auto get_value(shim::string_view const key) const noexcept -> raw_element;\n        auto at_value(shim::string_view const key) const -> raw_element;\n\n        static auto load_key(gsl::byte const* base, size_t idx) noexcept -> typename ll_iterator<RefCount>::value_type;\n        static auto load_value(gsl::byte const* base, size_t idx) noexcept -> typename ll_iterator<RefCount>::value_type;\n\n        /*----- Public Members -----*/\n\n        static constexpr auto alignment = sizeof(int64_t);\n\n      private:\n\n        /*----- Private Helpers -----*/\n\n        size_t realign(size_t guess, size_t offset) noexcept;\n\n        template <class Callback>\n        auto get_value_impl(shim::string_view const key, Callback&& cb) const -> raw_element;\n\n        object_entry* vtable() noexcept;\n        object_entry const* vtable() const noexcept;\n\n        gsl::byte* raw_vtable() noexcept;\n        gsl::byte const* raw_vtable() const noexcept;\n\n        /*----- Private Members -----*/\n\n        alignas(4) little_order<uint32_t> bytes;\n        alignas(4) little_order<uint32_t> elems;\n\n        static constexpr auto header_len = sizeof(bytes) + sizeof(elems);\n\n    };\n    static_assert(std::is_standard_layout<object<std::shared_ptr>>::value, \"dart library is misconfigured\");\n\n    /**\n     *  @brief\n     *  Class is the lowest level abstraction for safe interaction with\n     *  a dart::buffer array.\n     *\n     *  @details\n     *  Class wraps memory that is stored in little endian byte order,\n     *  irrespective of the native ordering of the host machine.\n     *  In other words, attempt to subvert its API at your peril.\n     */\n    template <template <class> class RefCount>\n    class array {\n\n      public:\n\n        /*----- Lifecycle Functions -----*/\n\n        array() = delete;\n#ifdef DART_USE_SAJSON\n        explicit array(sajson::value elems) noexcept;\n#endif\n#if DART_HAS_RAPIDJSON\n        explicit array(rapidjson::Value const& elems) noexcept;\n#endif\n        array(packet_elements<RefCount> const* elems) noexcept;\n        array(array const&) = delete;\n        ~array() = delete;\n\n        /*----- Operators -----*/\n\n        array& operator =(array const&) = delete;\n\n        /*----- Public API -----*/\n\n        template <bool silent>\n        bool is_valid(size_t bytes) const noexcept(silent);\n\n        size_t size() const noexcept;\n        size_t get_sizeof() const noexcept;\n\n        auto begin() const noexcept -> ll_iterator<RefCount>;\n        auto end() const noexcept -> ll_iterator<RefCount>;\n\n        auto get_elem(size_t index) const noexcept -> raw_element;\n        auto at_elem(size_t index) const -> raw_element;\n\n        static auto load_elem(gsl::byte const* base, size_t idx) noexcept -> typename ll_iterator<RefCount>::value_type;\n\n        /*----- Public Members -----*/\n\n        static constexpr auto alignment = sizeof(int64_t);\n\n      private:\n\n        /*----- Private Helpers -----*/\n\n        auto get_elem_impl(size_t index, bool throw_if_absent) const -> raw_element;\n\n        array_entry* vtable() noexcept;\n        array_entry const* vtable() const noexcept;\n\n        gsl::byte* raw_vtable() noexcept;\n        gsl::byte const* raw_vtable() const noexcept;\n\n        /*----- Private Members -----*/\n\n        alignas(4) little_order<uint32_t> bytes;\n        alignas(4) little_order<uint32_t> elems;\n\n        static constexpr auto header_len = sizeof(bytes) + sizeof(elems);\n\n    };\n    static_assert(std::is_standard_layout<array<std::shared_ptr>>::value, \"dart library is misconfigured\");\n\n    /**\n     *  @brief\n     *  Class is the lowest level abstraction for safe interaction with\n     *  a dart::buffer string.\n     *\n     *  @details\n     *  Class wraps memory that is stored in little endian byte order,\n     *  irrespective of the native ordering of the host machine.\n     *  In other words, attempt to subvert its API at your peril.\n     */\n    template <class SizeType>\n    class basic_string {\n\n      public:\n\n        /*----- Public Types -----*/\n\n        using size_type = SizeType;\n\n        /*----- Lifecycle Functions -----*/\n\n        basic_string() = delete;\n        explicit basic_string(shim::string_view strv) noexcept;\n        explicit basic_string(char const* str, size_t len) noexcept;\n        basic_string(basic_string const&) = delete;\n        ~basic_string() = delete;\n\n        /*----- Operators -----*/\n\n        basic_string& operator =(basic_string const&) = delete;\n\n        /*----- Public API -----*/\n\n        template <bool silent>\n        bool is_valid(size_t bytes) const noexcept(silent);\n\n        size_t size() const noexcept;\n        size_t get_sizeof() const noexcept;\n\n        shim::string_view get_strv() const noexcept;\n\n        static size_t static_sizeof(size_type len) noexcept;\n\n        /*----- Public Members -----*/\n\n        static constexpr auto alignment = sizeof(size_type);\n\n      private:\n\n        /*----- Private Helpers -----*/\n\n        char* data() noexcept;\n        char const* data() const noexcept;\n\n        /*----- Private Members -----*/\n\n        alignas(alignment) little_order<size_type> len;\n\n        static constexpr auto header_len = sizeof(len);\n\n    };\n    using string = basic_string<uint16_t>;\n    using big_string = basic_string<uint32_t>;\n    static_assert(std::is_standard_layout<string>::value, \"dart library is misconfigured\");\n    static_assert(std::is_standard_layout<big_string>::value, \"dart library is misconfigured\");\n\n    /**\n     *  @brief\n     *  Class is the lowest level abstraction for safe interaction with\n     *  a dart::buffer primitive value.\n     *\n     *  @details\n     *  Class wraps memory that is stored in little endian byte order,\n     *  irrespective of the native ordering of the host machine.\n     *  In other words, attempt to subvert its API at your peril.\n     */\n    template <class T>\n    class primitive {\n\n      public:\n\n        /*----- Lifecycle Functions -----*/\n\n        primitive() = delete;\n        explicit primitive(T data) noexcept : data(data) {}\n        primitive(primitive const&) = delete;\n        ~primitive() = delete;\n\n        /*---- Operators -----*/\n\n        primitive& operator =(primitive const&) = delete;\n\n        /*----- Public API -----*/\n\n        template <bool silent>\n        bool is_valid(size_t bytes) const noexcept(silent);\n\n        size_t get_sizeof() const noexcept;\n\n        T get_data() const noexcept;\n\n        static size_t static_sizeof() noexcept;\n\n        /*----- Public Members -----*/\n\n        static constexpr auto alignment = sizeof(T);\n\n      private:\n\n        /*----- Private Members -----*/\n\n        alignas(alignment) little_order<T> data;\n\n        static constexpr auto header_len = sizeof(data);\n\n    };\n    static_assert(std::is_standard_layout<primitive<int>>::value, \"dart library is misconfigured\");\n\n    template <template <class> class RefCount>\n    struct buffer_builder {\n      using buffer = basic_buffer<RefCount>;\n\n      template <class Span>\n      static auto build_buffer(Span pairs) -> buffer;\n      static auto merge_buffers(buffer const& base, buffer const& incoming) -> buffer;\n\n      template <class Spannable>\n      static auto project_keys(buffer const& base, Spannable const& keys) -> buffer;\n\n      template <class Callback>\n      static void each_unique_pair(object<RefCount> const* base, object<RefCount> const* incoming, Callback&& cb);\n      template <class Key, class Callback>\n      static void project_each_pair(object<RefCount> const* base, gsl::span<Key const*> key_ptrs, Callback&& cb);\n\n      template <class Span>\n      static size_t max_bytes(Span pairs);\n    };\n\n    // Used for tag dispatch from factory functions.\n    struct view_tag {};\n    struct object_tag {\n      static constexpr auto alignment = object<std::shared_ptr>::alignment;\n    };\n    struct array_tag {\n      static constexpr auto alignment = array<std::shared_ptr>::alignment;\n    };\n    struct string_tag {\n      static constexpr auto alignment = big_string::alignment;\n    };\n    struct small_string_tag : string_tag {\n      static constexpr auto alignment = string::alignment;\n    };\n    struct big_string_tag : string_tag {\n      static constexpr auto alignment = string_tag::alignment;\n    };\n    struct integer_tag {\n      static constexpr auto alignment = primitive<int64_t>::alignment;\n    };\n    struct short_integer_tag : integer_tag {\n      static constexpr auto alignment = primitive<int16_t>::alignment;\n    };\n    struct medium_integer_tag : integer_tag {\n      static constexpr auto alignment = primitive<int32_t>::alignment;\n    };\n    struct long_integer_tag : integer_tag {\n      static constexpr auto alignment = integer_tag::alignment;\n    };\n    struct decimal_tag {\n      static constexpr auto alignment = primitive<double>::alignment;\n    };\n    struct short_decimal_tag : decimal_tag {\n      static constexpr auto alignment = primitive<float>::alignment;\n    };\n    struct long_decimal_tag : decimal_tag {\n      static constexpr auto alignment = decimal_tag::alignment;\n    };\n    struct boolean_tag {\n      static constexpr auto alignment = primitive<bool>::alignment;\n    };\n    struct null_tag {\n      static constexpr auto alignment = 1;\n    };\n\n    /**\n     *  @brief\n     *  Function converts between internal type information and\n     *  user-facing type information.\n     *\n     *  @details\n     *  Dart internally has to encode significantly more complicated\n     *  type information than it publicly exposes, so this function\n     *  works as a an efficient go-between for the two.\n     */\n    inline type simplify_type(raw_type type) noexcept {\n      switch (type) {\n        case raw_type::object:\n          return detail::type::object;\n        case raw_type::array:\n          return detail::type::array;\n        case raw_type::small_string:\n        case raw_type::string:\n        case raw_type::big_string:\n          return detail::type::string;\n        case raw_type::short_integer:\n        case raw_type::integer:\n        case raw_type::long_integer:\n          return detail::type::integer;\n        case raw_type::decimal:\n        case raw_type::long_decimal:\n          return detail::type::decimal;\n        case raw_type::boolean:\n          return detail::type::boolean;\n        default:\n          DART_ASSERT(type == raw_type::null);\n          return detail::type::null;\n      }\n    }\n\n    inline bool valid_type(raw_type type) noexcept {\n      switch (type) {\n        case raw_type::object:\n        case raw_type::array:\n        case raw_type::string:\n        case raw_type::small_string:\n        case raw_type::big_string:\n        case raw_type::short_integer:\n        case raw_type::integer:\n        case raw_type::long_integer:\n        case raw_type::decimal:\n        case raw_type::long_decimal:\n        case raw_type::boolean:\n        case raw_type::null:\n          return true;\n        default:\n          return false;\n      }\n    }\n\n    /**\n     *  @brief\n     *  Function provides a \"safe\" bridge between the high level\n     *  and low level object apis.\n     *\n     *  @details\n     *  Don't pass it null.\n     *  Tries its damndest not to invoke UB, but god knows.\n     */\n    template <template <class> class RefCount>\n    object<RefCount> const* get_object(raw_element raw) {\n      if (simplify_type(raw.type) == type::object) {\n        DART_ASSERT(raw.buffer != nullptr);\n        return shim::launder(reinterpret_cast<object<RefCount> const*>(raw.buffer));\n      } else {\n        throw type_error(\"dart::buffer is not a finalized object and cannot be accessed as such\");\n      }\n    }\n\n    /**\n     *  @brief\n     *  Function provides a \"safe\" bridge between the high level\n     *  and low level array apis.\n     *\n     *  @details\n     *  Don't pass it null.\n     *  Tries its damndest not to invoke UB, but god knows.\n     */\n    template <template <class> class RefCount>\n    array<RefCount> const* get_array(raw_element raw) {\n      if (simplify_type(raw.type) == type::array) {\n        DART_ASSERT(raw.buffer != nullptr);\n        return shim::launder(reinterpret_cast<array<RefCount> const*>(raw.buffer));\n      } else {\n        throw type_error(\"dart::buffer is not a finalized array and cannot be accessed as such\");\n      }\n    }\n\n    /**\n     *  @brief\n     *  Function provides a \"safe\" bridge between the high level\n     *  and low level string apis.\n     *\n     *  @details\n     *  Don't pass it null.\n     *  Tries its damndest not to invoke UB, but god knows.\n     */\n    inline string const* get_string(raw_element raw) {\n      if (raw.type == raw_type::small_string || raw.type == raw_type::string) {\n        DART_ASSERT(raw.buffer != nullptr);\n        return shim::launder(reinterpret_cast<string const*>(raw.buffer));\n      } else {\n        throw type_error(\"dart::buffer is not a finalized string and cannot be accessed as such\");\n      }\n    }\n\n    /**\n     *  @brief\n     *  Function provides a \"safe\" bridge between the high level\n     *  and low level string apis.\n     *\n     *  @details\n     *  Don't pass it null.\n     *  Tries its damndest not to invoke UB, but god knows.\n     */\n    inline big_string const* get_big_string(raw_element raw) {\n      if (raw.type == raw_type::big_string) {\n        DART_ASSERT(raw.buffer != nullptr);\n        return shim::launder(reinterpret_cast<big_string const*>(raw.buffer));\n      } else {\n        throw type_error(\"dart::buffer is not a finalized string and cannot be accessed as such\");\n      }\n    }\n\n    /**\n     *  @brief\n     *  Function provides a \"safe\" bridge between the high level\n     *  and low level primitive apis.\n     *\n     *  @details\n     *  Don't pass it null.\n     *  Tries its damndest not to invoke UB, but god knows.\n     */\n    template <class T>\n    primitive<T> const* get_primitive(raw_element raw) {\n      auto simple = simplify_type(raw.type);\n      if (simple == type::integer || simple == type::decimal || simple == type::boolean) {\n        DART_ASSERT(raw.buffer != nullptr);\n        return shim::launder(reinterpret_cast<primitive<T> const*>(raw.buffer));\n      } else {\n        throw type_error(\"dart::buffer is not a finalized primitive and cannot be accessed as such\");\n      }\n    }\n\n    template <template <class> class RefCount, class Callback>\n    auto aggregate_deref(Callback&& cb, raw_element raw)\n      -> std::common_type_t<\n        decltype(std::forward<Callback>(cb)(std::declval<object<RefCount>&>())),\n        decltype(std::forward<Callback>(cb)(std::declval<array<RefCount>&>()))\n      >\n    {\n      switch (raw.type) {\n        case raw_type::object:\n          return std::forward<Callback>(cb)(*get_object<RefCount>(raw));\n        case raw_type::array:\n          return std::forward<Callback>(cb)(*get_array<RefCount>(raw));\n        default:\n          throw type_error(\"dart::buffer is not a finalized aggregate and cannot be accessed as such\");\n      }\n    }\n\n    template <class Callback>\n    auto string_deref(Callback&& cb, raw_element raw)\n      -> std::common_type_t<\n        decltype(std::forward<Callback>(cb)(std::declval<string&>())),\n        decltype(std::forward<Callback>(cb)(std::declval<big_string&>()))\n      >\n    {\n      switch (raw.type) {\n        case raw_type::small_string:\n        case raw_type::string:\n          return std::forward<Callback>(cb)(*get_string(raw));\n        case raw_type::big_string:\n          return std::forward<Callback>(cb)(*get_big_string(raw));\n        default:\n          throw type_error(\"dart::buffer is not a finalized string and cannot be accessed as such\");\n      }\n    }\n\n    template <class Callback>\n    auto integer_deref(Callback&& cb, raw_element raw)\n      -> std::common_type_t<\n        decltype(std::forward<Callback>(cb)(std::declval<primitive<int16_t>&>())),\n        decltype(std::forward<Callback>(cb)(std::declval<primitive<int32_t>&>())),\n        decltype(std::forward<Callback>(cb)(std::declval<primitive<int64_t>&>()))\n      >\n    {\n      switch (raw.type) {\n        case raw_type::short_integer:\n          return std::forward<Callback>(cb)(*get_primitive<int16_t>(raw));\n        case raw_type::integer:\n          return std::forward<Callback>(cb)(*get_primitive<int32_t>(raw));\n        case raw_type::long_integer:\n          return std::forward<Callback>(cb)(*get_primitive<int64_t>(raw));\n        default:\n          throw type_error(\"dart::buffer is not a finalized integer and cannot be accessed as such\");\n      }\n    }\n\n    template <class Callback>\n    auto decimal_deref(Callback&& cb, raw_element raw)\n      -> std::common_type_t<\n        decltype(std::forward<Callback>(cb)(std::declval<primitive<float>&>())),\n        decltype(std::forward<Callback>(cb)(std::declval<primitive<double>&>()))\n      >\n    {\n      switch (raw.type) {\n        case raw_type::decimal:\n          return std::forward<Callback>(cb)(*get_primitive<float>(raw));\n        case raw_type::long_decimal:\n          return std::forward<Callback>(cb)(*get_primitive<double>(raw));\n        default:\n          throw type_error(\"dart::buffer is not a finalized decimal and cannot be accessed as such\");\n      }\n    }\n\n    template <class Callback>\n    auto match_generic(Callback&& cb, raw_type raw)\n      -> std::common_type_t<\n        decltype(std::forward<Callback>(cb)(object_tag {})),\n        decltype(std::forward<Callback>(cb)(array_tag {})),\n        decltype(std::forward<Callback>(cb)(small_string_tag {})),\n        decltype(std::forward<Callback>(cb)(big_string_tag {})),\n        decltype(std::forward<Callback>(cb)(short_integer_tag {})),\n        decltype(std::forward<Callback>(cb)(medium_integer_tag {})),\n        decltype(std::forward<Callback>(cb)(long_integer_tag {})),\n        decltype(std::forward<Callback>(cb)(short_decimal_tag {})),\n        decltype(std::forward<Callback>(cb)(long_decimal_tag {})),\n        decltype(std::forward<Callback>(cb)(boolean_tag {})),\n        decltype(std::forward<Callback>(cb)(null_tag {}))\n      >\n    {\n      switch (raw) {\n        case raw_type::object:\n          return std::forward<Callback>(cb)(object_tag {});\n        case raw_type::array:\n          return std::forward<Callback>(cb)(array_tag {});\n        case raw_type::small_string:\n        case raw_type::string:\n          return std::forward<Callback>(cb)(small_string_tag {});\n        case raw_type::big_string:\n          return std::forward<Callback>(cb)(big_string_tag {});\n        case raw_type::short_integer:\n          return std::forward<Callback>(cb)(short_integer_tag {});\n        case raw_type::integer:\n          return std::forward<Callback>(cb)(medium_integer_tag {});\n        case raw_type::long_integer:\n          return std::forward<Callback>(cb)(long_integer_tag {});\n        case raw_type::decimal:\n          return std::forward<Callback>(cb)(short_decimal_tag {});\n        case raw_type::long_decimal:\n          return std::forward<Callback>(cb)(long_decimal_tag {});\n        case raw_type::boolean:\n          return std::forward<Callback>(cb)(boolean_tag {});\n        default:\n          DART_ASSERT(raw == raw_type::null);\n          return std::forward<Callback>(cb)(null_tag {});\n      }\n    }\n\n    template <template <class> class RefCount, class Callback>\n    auto generic_deref(Callback&& cb, raw_element raw)\n      -> std::common_type_t<\n        decltype(aggregate_deref<RefCount>(std::forward<Callback>(cb), raw)),\n        decltype(string_deref(std::forward<Callback>(cb), raw)),\n        decltype(integer_deref(std::forward<Callback>(cb), raw)),\n        decltype(decimal_deref(std::forward<Callback>(cb), raw)),\n        decltype(std::forward<Callback>(cb)(std::declval<primitive<bool>&>()))\n      >\n    {\n      switch (raw.type) {\n        case raw_type::object:\n        case raw_type::array:\n          return aggregate_deref<RefCount>(std::forward<Callback>(cb), raw);\n        case raw_type::small_string:\n        case raw_type::string:\n        case raw_type::big_string:\n          return string_deref(std::forward<Callback>(cb), raw);\n        case raw_type::short_integer:\n        case raw_type::integer:\n        case raw_type::long_integer:\n          return integer_deref(std::forward<Callback>(cb), raw);\n        case raw_type::decimal:\n        case raw_type::long_decimal:\n          return decimal_deref(std::forward<Callback>(cb), raw);\n        case raw_type::boolean:\n          return std::forward<Callback>(cb)(*get_primitive<bool>(raw));\n        default:\n          DART_ASSERT(raw.type == raw_type::null);\n          throw type_error(\"dart::buffer is null, and has no value to access\");\n      }\n    }\n\n    // Returns the native alignment requirements of the given type.\n    template <template <class> class RefCount>\n    constexpr size_t alignment_of(raw_type type) noexcept {\n      return match_generic([] (auto v) { return decltype(v)::alignment; }, type);\n    }\n\n    // Function takes a pointer and returns a pointer to the \"next\" (greater than OR equal to) boundary\n    // conforming to the native alignment of the given type.\n    // Assumes that all alignment requests are for powers of two.\n    template <template <class> class RefCount, class T>\n    constexpr T* align_pointer(T* ptr, raw_type type) noexcept {\n      // Get the required alignment for a pointer of this type.\n      auto alignment = alignment_of<RefCount>(type);\n\n      // Bump forward to the next boundary of the given alignment requirement.\n      uintptr_t offset = reinterpret_cast<uintptr_t>(ptr);\n      return reinterpret_cast<T*>((offset + (alignment - 1)) & ~(alignment - 1));\n    }\n\n    template <template <class> class RefCount, class T>\n    constexpr T pad_bytes(T bytes, raw_type type) noexcept {\n      // Get the required alignment for a pointer of this type.\n      auto alignment = alignment_of<RefCount>(type);\n\n      // Pad the given bytes to ensure its end lands on an alignment boundary.\n      return (bytes + (alignment - 1)) & ~(alignment - 1);\n    }\n\n    template <template <class> class RefCount>\n    size_t find_sizeof(raw_element elem) noexcept {\n      if (elem.type != raw_type::null) {\n        return generic_deref<RefCount>([] (auto& v) { return v.get_sizeof(); }, elem);\n      } else {\n        return 0;\n      }\n    }\n\n    template <bool silent, template <class> class RefCount>\n    bool valid_buffer(raw_element elem, size_t bytes) noexcept(silent) {\n      // Null is a special case because it occupies zero space in the network buffer\n      // Check if the given element has a valid type.\n      // If we're validating against corrupted garbage it likely won't\n      if (elem.type == raw_type::null) return true;\n      else if (!valid_type(elem.type)) return false;\n\n      // Call through to our implementation\n      return generic_deref<RefCount>([=] (auto& v) { return v.template is_valid<silent>(bytes); }, elem);\n    }\n\n    template <template <class> class RefCount>\n    constexpr size_t sso_bytes() {\n      return basic_heap<RefCount>::sso_bytes;\n    }\n\n    template <template <class> class RefCount>\n    raw_type identify_string(shim::string_view base, shim::string_view app = \"\") noexcept {\n      auto total = base.size() + app.size();\n      if (total > std::numeric_limits<uint16_t>::max()) {\n        return detail::raw_type::big_string;\n      } else if (total > sso_bytes<RefCount>()) {\n        return detail::raw_type::string;\n      } else {\n        return detail::raw_type::small_string;\n      }\n    }\n\n    constexpr raw_type identify_integer(int64_t val) noexcept {\n      if (val > INT32_MAX || val < INT32_MIN) return raw_type::long_integer;\n      else if (val > INT16_MAX || val < INT16_MIN) return raw_type::integer;\n      else return raw_type::short_integer;\n    }\n\n    // Returns the smallest floating point type capable of precisely representing the given\n    // value.\n    constexpr raw_type identify_decimal(double val) noexcept {\n      // XXX: I'm not impressed by this check either, but I can't find any legit way\n      // to check if a double will be precisely representable as a float.\n      if (val != static_cast<float>(val)) return raw_type::long_decimal;\n      else return raw_type::decimal;\n    }\n\n// Dart is header-only, so I think the scenarios where the ABI stability of\n// symbol mangling will be relevant are relatively few.\n#if DART_USING_GCC\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wpragmas\"\n#pragma GCC diagnostic ignored \"-Wnoexcept-type\"\n#elif DART_USING_CLANG\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wunknown-pragmas\"\n#pragma clang diagnostic ignored \"-Wc++17-compat-mangling\"\n#pragma clang diagnostic ignored \"-Wc++1z-compat\"\n#endif\n\n    template <class Packet, class T>\n    T safe_optional_access(Packet const& that, T opt,\n        bool (Packet::* guard) () const noexcept, T (Packet::* accessor) () const) {\n      if (!(that.*guard)()) {\n        return opt;\n      } else try {\n        return (that.*accessor)();\n      } catch (...) {\n        return opt;\n      }\n    }\n\n#if DART_USING_GCC\n#pragma GCC diagnostic pop\n#elif DART_USING_CLANG\n#pragma clang diagnostic pop\n#endif\n\n    template <template <class> class RefCount, class Owner = buffer_refcount_type<RefCount>, class Callback>\n    Owner aligned_alloc(size_t bytes, raw_type type, Callback&& cb) {\n      // Make an aligned allocation.\n      gsl::byte* tmp;\n      int retval = shim::aligned_alloc(reinterpret_cast<void**>(&tmp), alignment_of<RefCount>(type), bytes);\n      if (retval) throw std::bad_alloc();\n\n      // Associate it with an owner in case anything goes wrong.\n      Owner ref {tmp, +[] (gsl::byte const* ptr) { shim::aligned_free(const_cast<gsl::byte*>(ptr)); }};\n\n      // Hand out mutable access and return.\n      cb(tmp);\n      return ref;\n    }\n\n    template <template <class> class RefCount, size_t static_elems = 8, class Spannable, class Callback>\n    decltype(auto) sort_spannable(Spannable const& elems, Callback&& cb) {\n      // XXX: This is necessary because I'm supporting an ANCIENT version of gsl-lite that\n      // doesn't contain the nested type alias value_type, only element_type\n      // Modern versions of gsl-lite, and Microsoft GSL, and std::span, include a value_type\n      // As a fix, meta::spannable_value_type_t returns value_type if it exists,\n      // next element_type if it exists,\n      // and finally meta::nonesuch if neither alias exists\n      using value_type = meta::spannable_value_type_t<Spannable>;\n      static_assert(\n        !std::is_same<\n          value_type,\n          meta::nonesuch\n        >::value,\n        \"Sort spannable only supports types that conform to the std::span interface\"\n      );\n\n      // Check if we can perform the sorting statically.\n      dart_comparator<RefCount> comp;\n      auto const size = static_cast<size_t>(elems.size());\n      if (size <= static_elems) {\n        // We've got enough static space, setup a local array.\n        std::array<value_type const*, static_elems> ptrs;\n        std::transform(std::begin(elems), std::end(elems), std::begin(ptrs), [] (auto& e) { return &e; });\n\n        // Sort the pointers and pass back to the user.\n        std::sort(ptrs.data(), ptrs.data() + size, [&] (auto* lhs, auto* rhs) { return comp(*lhs, *rhs); });\n        return cb(gsl::make_span(ptrs.data(), size));\n      } else {\n        // Dynamic fallback.\n        std::vector<value_type const*> ptrs(size, nullptr);\n        std::transform(std::begin(elems), std::end(elems), std::begin(ptrs), [] (auto& e) { return &e; });\n\n        // Sort and pass back.\n        std::sort(std::begin(ptrs), std::end(ptrs), [&] (auto* lhs, auto* rhs) { return comp(*lhs, *rhs); });\n        return cb(gsl::make_span(ptrs));\n      }\n    }\n\n#ifdef DART_USE_SAJSON\n    // FIXME: Find somewhere better to put these functions.\n    template <template <class> class RefCount>\n    raw_type json_identify(sajson::value curr_val) {\n      switch (curr_val.get_type()) {\n        case sajson::TYPE_OBJECT:\n          return raw_type::object;\n        case sajson::TYPE_ARRAY:\n          return raw_type::array;\n        case sajson::TYPE_STRING:\n          // Figure out what type of string we've been given.\n          return identify_string<RefCount>({curr_val.as_cstring(), curr_val.get_string_length()});\n        case sajson::TYPE_INTEGER:\n          return identify_integer(curr_val.get_integer_value());\n        case sajson::TYPE_DOUBLE:\n          return identify_decimal(curr_val.get_double_value());\n        case sajson::TYPE_FALSE:\n        case sajson::TYPE_TRUE:\n          return raw_type::boolean;\n        default:\n          DART_ASSERT(curr_val.get_type() == sajson::TYPE_NULL);\n          return raw_type::null;\n      }\n    }\n\n    template <template <class> class RefCount>\n    size_t json_lower(gsl::byte* buffer, sajson::value curr_val) {\n      auto raw = json_identify<RefCount>(curr_val);\n      switch (raw) {\n        case raw_type::object:\n          new(buffer) object<RefCount>(curr_val);\n          break;\n        case raw_type::array:\n          new(buffer) array<RefCount>(curr_val);\n          break;\n        case raw_type::small_string:\n        case raw_type::string:\n          new(buffer) string(curr_val.as_cstring(), curr_val.get_string_length());\n          break;\n        case raw_type::big_string:\n          new(buffer) big_string(curr_val.as_cstring(), curr_val.get_string_length());\n          break;\n        case raw_type::short_integer:\n          new(buffer) primitive<int16_t>(curr_val.get_integer_value());\n          break;\n        case raw_type::integer:\n          new(buffer) primitive<int32_t>(curr_val.get_integer_value());\n          break;\n        case raw_type::long_integer:\n          new(buffer) primitive<int64_t>(curr_val.get_integer_value());\n          break;\n        case raw_type::decimal:\n          new(buffer) primitive<float>(curr_val.get_double_value());\n          break;\n        case raw_type::long_decimal:\n          new(buffer) primitive<double>(curr_val.get_double_value());\n          break;\n        case raw_type::boolean:\n          new(buffer) detail::primitive<bool>((curr_val.get_type() == sajson::TYPE_TRUE) ? true : false);\n          break;\n        default:\n          DART_ASSERT(curr_val.get_type() == sajson::TYPE_NULL);\n          break;\n      }\n      return detail::find_sizeof<RefCount>({raw, buffer});\n    }\n#endif\n\n#if DART_HAS_RAPIDJSON\n    // FIXME: Find somewhere better to put these functions.\n    template <template <class> class RefCount>\n    raw_type json_identify(rapidjson::Value const& curr_val) {\n      switch (curr_val.GetType()) {\n        case rapidjson::kObjectType:\n          return raw_type::object;\n        case rapidjson::kArrayType:\n          return raw_type::array;\n        case rapidjson::kStringType:\n          // Figure out what type of string we've been given.\n          return identify_string<RefCount>({curr_val.GetString(), curr_val.GetStringLength()});\n        case rapidjson::kNumberType:\n          // Figure out what type of number we've been given.\n          if (curr_val.IsInt64()) return identify_integer(curr_val.GetInt64());\n          else return identify_decimal(curr_val.GetDouble());\n        case rapidjson::kTrueType:\n        case rapidjson::kFalseType:\n          return raw_type::boolean;\n        default:\n          DART_ASSERT(curr_val.IsNull());\n          return raw_type::null;\n      }\n    }\n\n    template <template <class> class RefCount>\n    size_t json_lower(gsl::byte* buffer, rapidjson::Value const& curr_val) {\n      auto raw = json_identify<RefCount>(curr_val);\n      switch (raw) {\n        case raw_type::object:\n          new(buffer) object<RefCount>(curr_val);\n          break;\n        case raw_type::array:\n          new(buffer) array<RefCount>(curr_val);\n          break;\n        case raw_type::small_string:\n        case raw_type::string:\n          new(buffer) string(curr_val.GetString(), curr_val.GetStringLength());\n          break;\n        case raw_type::big_string:\n          new(buffer) big_string(curr_val.GetString(), curr_val.GetStringLength());\n          break;\n        case raw_type::short_integer:\n          new(buffer) primitive<int16_t>(curr_val.GetInt());\n          break;\n        case raw_type::integer:\n          new(buffer) primitive<int32_t>(curr_val.GetInt());\n          break;\n        case raw_type::long_integer:\n          new(buffer) primitive<int64_t>(curr_val.GetInt64());\n          break;\n        case raw_type::decimal:\n          new(buffer) primitive<float>(curr_val.GetFloat());\n          break;\n        case raw_type::long_decimal:\n          new(buffer) primitive<double>(curr_val.GetDouble());\n          break;\n        case raw_type::boolean:\n          new(buffer) detail::primitive<bool>(curr_val.GetBool());\n          break;\n        default:\n          DART_ASSERT(curr_val.IsNull());\n          break;\n      }\n      return detail::find_sizeof<RefCount>({raw, buffer});\n    }\n#endif\n\n    // Helper function handles the edge case where we're working with\n    // a view type, and we need to cast it back to an owner, ONLY IF\n    // we are an owner ourselves.\n    template <class MaybeView, class View>\n    decltype(auto) view_return_indirection(View&& view) {\n      return shim::compose_together(\n        [] (auto&& v, std::true_type) -> decltype(auto) {\n          return std::forward<decltype(v)>(v);\n        },\n        [] (auto&& v, std::false_type) -> decltype(auto) {\n          return std::forward<decltype(v)>(v).as_owner();\n        }\n      )(std::forward<View>(view), std::is_same<std::decay_t<MaybeView>, std::decay_t<View>> {});\n    }\n\n    template <class Packet>\n    Packet get_nested_impl(Packet haystack, shim::string_view needle, char separator) {\n      // Spin through the provided needle until we reach the end, or hit a leaf.\n      auto start = needle.begin();\n      typename Packet::view curr = haystack;\n      while (start < needle.end() && curr.is_object()) {\n        // Tokenize up the needle and drag the current packet through each one.\n        auto stop = std::find(start, needle.end(), separator);\n        curr = curr[needle.substr(start - needle.begin(), stop - start)];\n\n        // Prepare for next iteration.\n        stop == needle.end() ? start = stop : start = stop + 1;\n      }\n\n      // If we finished, find our final value, otherwise return null.\n      if (start < needle.end()) return Packet::make_null();\n      else return view_return_indirection<Packet>(curr);\n    }\n\n    template <class Packet>\n    std::vector<Packet> keys_impl(Packet const& that) {\n      std::vector<Packet> packets;\n      packets.reserve(that.size());\n      for (auto it = that.key_begin(); it != that.key_end(); ++it) {\n        packets.push_back(*it);\n      }\n      return packets;\n    }\n\n    template <class Packet>\n    std::vector<Packet> values_impl(Packet const& that) {\n      std::vector<Packet> packets;\n      packets.reserve(that.size());\n      for (auto entry : that) packets.push_back(std::move(entry));\n      return packets;\n    }\n\n    template <class T>\n    decltype(auto) maybe_dereference(T&& maybeptr, std::true_type) {\n      return *std::forward<T>(maybeptr);\n    }\n    template <class T>\n    decltype(auto) maybe_dereference(T&& maybeptr, std::false_type) {\n      return std::forward<T>(maybeptr);\n    }\n\n  }\n\n}\n\n// Include main header file for all implementation files.\n#include \"../dart.h\"\n#include \"common.tcc\"\n\n#endif\n", "meta": {"hexsha": "7527ef370476399542e836160b4100e7ff950d59", "size": 56597, "ext": "h", "lang": "C", "max_stars_repo_path": "include/dart/common.h", "max_stars_repo_name": "Cfretz244/libdart", "max_stars_repo_head_hexsha": "987b01aa1f11455ac6aaf89f8e60825e92e6ec25", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2019-05-09T19:12:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-07T16:31:55.000Z", "max_issues_repo_path": "include/dart/common.h", "max_issues_repo_name": "Cfretz244/libdart", "max_issues_repo_head_hexsha": "987b01aa1f11455ac6aaf89f8e60825e92e6ec25", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2019-05-09T22:37:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-29T03:25:16.000Z", "max_forks_repo_path": "include/dart/common.h", "max_forks_repo_name": "Cfretz244/libdart", "max_forks_repo_head_hexsha": "987b01aa1f11455ac6aaf89f8e60825e92e6ec25", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-05-11T08:05:10.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-11T11:05:17.000Z", "avg_line_length": 34.7220858896, "max_line_length": 121, "alphanum_fraction": 0.636005442, "num_tokens": 12933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07807815870926199, "lm_q2_score": 0.02128734954266127, "lm_q1q2_score": 0.0016620770560914423}}
{"text": "#pragma once\n\n#include \"RTTI.h\"\n#include <stack>\n#include <gsl\\gsl>\n#include <GL/gl3w.h>\n#include \"Framebuffer.h\"\n\nnamespace Library\n{\n\tclass RenderTarget : public RTTI\n\t{\n\t\tRTTI_DECLARATIONS(RenderTarget, RTTI)\n\n\tpublic:\n\t\tRenderTarget() = default;\n\t\tRenderTarget(const RenderTarget&) = delete;\n\t\tRenderTarget(RenderTarget&&) = default;\n\t\tRenderTarget& operator=(const RenderTarget&) = delete;\n\t\tRenderTarget& operator=(RenderTarget&&) = default;\n\t\tvirtual ~RenderTarget() = default;\n\n\t\tvoid GenTexture(GLuint width, GLuint height);\n\n\t\tGLuint GetTextureID();\n\n\t\tvoid Begin();\n\t\tvoid End();\n\t\tvoid RebindCurrentRenderTargets();\n\n\tprotected:\n\t\tstd::shared_ptr<Framebuffer> mDrawTarget;\n\n\tprivate:\n\t\tstatic std::stack<std::shared_ptr<Framebuffer>> sRenderTargetStack;\n\t};\n}", "meta": {"hexsha": "1f94051f1d69f5f1893c88e496a534343e9b20e5", "size": 771, "ext": "h", "lang": "C", "max_stars_repo_path": "source/Library.Shared/RenderTarget.h", "max_stars_repo_name": "DakkyDaWolf/OpenGL", "max_stars_repo_head_hexsha": "628e9aed116022175cc0c59c88ace7688309628c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/Library.Shared/RenderTarget.h", "max_issues_repo_name": "DakkyDaWolf/OpenGL", "max_issues_repo_head_hexsha": "628e9aed116022175cc0c59c88ace7688309628c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/Library.Shared/RenderTarget.h", "max_forks_repo_name": "DakkyDaWolf/OpenGL", "max_forks_repo_head_hexsha": "628e9aed116022175cc0c59c88ace7688309628c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.8378378378, "max_line_length": 69, "alphanum_fraction": 0.7302204929, "num_tokens": 190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09670579329612156, "lm_q2_score": 0.017176707880314276, "lm_q1q2_score": 0.0016610871617815347}}
{"text": "#pragma once\n\n#include \"icode_generator.h\"\n#include <halley/data_structures/hash_map.h>\n#include <gsl/gsl>\n#include \"halley/file/path.h\"\n\nnamespace YAML\n{\n\tclass Node;\n}\n\nnamespace Halley\n{\n\tclass ECSData;\n\tclass ComponentSchema;\n\tclass SystemSchema;\n\tclass MessageSchema;\n\tclass CustomTypeSchema;\n\t\n\tclass Codegen\n\t{\t\n\t\tstruct Stats\n\t\t{\n\t\t\tint written = 0;\n\t\t\tint skipped = 0;\n\t\t\tVector<Path> files;\n\t\t};\n\n\tpublic:\n\t\tconstexpr static int currentCodegenVersion = 105;\n\t\t\n\t\tusing ProgressReporter = std::function<bool(float, String)>;\n\n\t\tstatic void run(Path inDir, Path outDir);\n\t\tstatic Vector<Path> generateCode(const ECSData& data, Path directory);\n\n\tprivate:\n\t\tstatic bool writeFile(const Path& path, gsl::span<const char> data, bool stub);\n\t\tstatic void writeFiles(const Path& directory, const CodeGenResult& files, Stats& stats);\n\t\tstatic int getHeaderVersion(gsl::span<const char> data, size_t& endOfHeader);\n\t};\n}", "meta": {"hexsha": "905a50a41d8ffa6022be5986fb7c1c2e2ffd0465", "size": 921, "ext": "h", "lang": "C", "max_stars_repo_path": "src/tools/tools/include/halley/tools/codegen/codegen.h", "max_stars_repo_name": "amrezzd/halley", "max_stars_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tools/tools/include/halley/tools/codegen/codegen.h", "max_issues_repo_name": "amrezzd/halley", "max_issues_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tools/tools/include/halley/tools/codegen/codegen.h", "max_forks_repo_name": "amrezzd/halley", "max_forks_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.4186046512, "max_line_length": 90, "alphanum_fraction": 0.7318132465, "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09807932874307332, "lm_q2_score": 0.016914916147267065, "lm_q1q2_score": 0.0016590036214693257}}
{"text": "/* Copyright 2019-2020 Canaan Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n#pragma once\n#include \"allocator.h\"\n#include \"model.h\"\n#include \"result.h\"\n#include \"runtime_module.h\"\n#include <gsl/gsl-lite.hpp>\n#include <memory>\n#include <unordered_map>\n\nBEGIN_NS_NNCASE_RUNTIME\n\nclass NNCASE_API options_dict\n{\npublic:\n    template <class T>\n    result<T> get(const char *name)\n    {\n        auto it = values_.find(name);\n        if (it != values_.end())\n            return ok(it->second.as<T>());\n        else\n            return err(std::errc::result_out_of_range);\n    }\n\n    template <class T>\n    result<void> set(const char *name, T value)\n    {\n        values_[name] = scalar(value);\n        return ok();\n    }\n\nprivate:\n    std::unordered_map<const char *, scalar> values_;\n};\n\nclass NNCASE_API interpreter\n{\npublic:\n    interpreter() noexcept;\n    interpreter(interpreter &) = delete;\n    interpreter(interpreter &&) = default;\n\n    NNCASE_NODISCARD result<void> load_model(gsl::span<const gsl::byte> buffer) noexcept;\n\n    size_t inputs_size() const noexcept;\n    size_t outputs_size() const noexcept;\n    const memory_range &input_desc(size_t index) const noexcept;\n    const memory_range &output_desc(size_t index) const noexcept;\n    const runtime_shape_t &input_shape(size_t index) const noexcept;\n    const runtime_shape_t &output_shape(size_t index) const noexcept;\n    result<runtime_tensor> input_tensor(size_t index) noexcept;\n    result<void> input_tensor(size_t index, runtime_tensor tensor) noexcept;\n    result<runtime_tensor> output_tensor(size_t index) noexcept;\n    result<void> output_tensor(size_t index, runtime_tensor tensor) noexcept;\n\n    result<void> run() noexcept;\n\n    result<runtime_module *> find_module_by_id(size_t index) noexcept;\n    options_dict &options() noexcept;\n\nprivate:\n    std::vector<std::unique_ptr<runtime_module>> modules_;\n    runtime_module *main_module_;\n    options_dict options_;\n};\n\nEND_NS_NNCASE_RUNTIME\n", "meta": {"hexsha": "a068ba12cdecc781c4ed8a2a8e1c318d9971a571", "size": 2483, "ext": "h", "lang": "C", "max_stars_repo_path": "lib/nncase/v1/include/nncase/runtime/interpreter.h", "max_stars_repo_name": "zhen8838/kendryte-standalone-sdk", "max_stars_repo_head_hexsha": "0ce252641826d65e12621347992cc9865874e6e1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-31T09:53:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T09:53:44.000Z", "max_issues_repo_path": "include/nncase/runtime/interpreter.h", "max_issues_repo_name": "13129176346/nncase", "max_issues_repo_head_hexsha": "61e41170faed249303295d184f611f27cfefce9d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/nncase/runtime/interpreter.h", "max_forks_repo_name": "13129176346/nncase", "max_forks_repo_head_hexsha": "61e41170faed249303295d184f611f27cfefce9d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-04-21T01:27:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T09:48:53.000Z", "avg_line_length": 30.2804878049, "max_line_length": 89, "alphanum_fraction": 0.716069271, "num_tokens": 569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10374863795103806, "lm_q2_score": 0.015906389116869566, "lm_q1q2_score": 0.0016502662055944326}}
{"text": "#pragma once\n\n#include \"Cesium3DTilesSelection/Library.h\"\n#include <glm/mat4x4.hpp>\n#include <glm/vec2.hpp>\n#include <gsl/span>\n\nnamespace CesiumGeometry {\nstruct Rectangle;\n}\n\nnamespace CesiumGltf {\nstruct ImageCesium;\nstruct Model;\n} // namespace CesiumGltf\n\nnamespace Cesium3DTilesSelection {\n\nclass Tile;\nclass RasterOverlayTile;\n\n/**\n * @brief When implemented for a rendering engine, allows renderer resources to\n * be created and destroyed under the control of a {@link Tileset}.\n *\n * It is not supposed to be used directly by clients. It is implemented\n * for specific rendering engines to provide an infrastructure for preparing the\n * data of a {@link Tile} so that it can be used for rendering.\n *\n * Instances of this class are associated with a {@link Tileset}, in the\n * {@link TilesetExternals} structure that can be obtained\n * via {@link Tileset::getExternals}.\n */\nclass CESIUM3DTILESSELECTION_API IPrepareRendererResources {\npublic:\n  virtual ~IPrepareRendererResources() = default;\n\n  /**\n   * @brief Prepares renderer resources for the given tile.\n   *\n   * This method is invoked in the load thread, and it may not modify the tile.\n   *\n   * @param model The glTF model to prepare.\n   * @param transform The tile's transformation.\n   * @returns Arbitrary data representing the result of the load process. This\n   * data is passed to {@link prepareInMainThread} as the `pLoadThreadResult`\n   * parameter.\n   */\n  virtual void* prepareInLoadThread(\n      const CesiumGltf::Model& model,\n      const glm::dmat4& transform) = 0;\n\n  /**\n   * @brief Further prepares renderer resources.\n   *\n   * This is called after {@link prepareInLoadThread}, and unlike that method,\n   * this one is called from the same thread that called\n   * {@link Tileset::updateView}.\n   *\n   * @param tile The tile to prepare.\n   * @param pLoadThreadResult The value returned from\n   * {@link prepareInLoadThread}.\n   * @returns Arbitrary data representing the result of the load process.\n   * Note that the value returned by {@link prepareInLoadThread} will _not_ be\n   * automatically preserved and passed to {@link free}. If you need to free\n   * that value, do it in this method before returning. If you need that value\n   * later, add it to the object returned from this method.\n   */\n  virtual void* prepareInMainThread(Tile& tile, void* pLoadThreadResult) = 0;\n\n  /**\n   * @brief Frees previously-prepared renderer resources.\n   *\n   * This method is always called from the thread that called\n   * {@link Tileset::updateView} or deleted the tileset.\n   *\n   * @param tile The tile for which to free renderer resources.\n   * @param pLoadThreadResult The result returned by\n   * {@link prepareInLoadThread}. If {@link prepareInMainThread} has\n   * already been called, this parameter will be `nullptr`.\n   * @param pMainThreadResult The result returned by\n   * {@link prepareInMainThread}. If {@link prepareInMainThread} has\n   * not yet been called, this parameter will be `nullptr`.\n   */\n  virtual void free(\n      Tile& tile,\n      void* pLoadThreadResult,\n      void* pMainThreadResult) noexcept = 0;\n\n  /**\n   * @brief Prepares a raster overlay tile.\n   *\n   * This method is invoked in the load thread, and it may not modify the tile.\n   *\n   * @param image The raster tile image to prepare.\n   * @returns Arbitrary data representing the result of the load process. This\n   * data is passed to {@link prepareRasterInMainThread} as the\n   * `pLoadThreadResult` parameter.\n   */\n  virtual void*\n  prepareRasterInLoadThread(const CesiumGltf::ImageCesium& image) = 0;\n\n  /**\n   * @brief Further preprares a raster overlay tile.\n   *\n   * This is called after {@link prepareRasterInLoadThread}, and unlike that\n   * method, this one is called from the same thread that called\n   * {@link Tileset::updateView}.\n   *\n   * @param rasterTile The raster tile to prepare.\n   * @param pLoadThreadResult The value returned from\n   * {@link prepareInLoadThread}.\n   * @returns Arbitrary data representing the result of the load process. Note\n   * that the value returned by {@link prepareRasterInLoadThread} will _not_ be\n   * automatically preserved and passed to {@link free}. If you need to free\n   * that value, do it in this method before returning. If you need that value\n   * later, add it to the object returned from this method.\n   */\n  virtual void* prepareRasterInMainThread(\n      const RasterOverlayTile& rasterTile,\n      void* pLoadThreadResult) = 0;\n\n  /**\n   * @brief Frees previously-prepared renderer resources for a raster tile.\n   *\n   * This method is always called from the thread that called\n   * {@link Tileset::updateView} or deleted the tileset.\n   *\n   * @param rasterTile The tile for which to free renderer resources.\n   * @param pLoadThreadResult The result returned by\n   * {@link prepareRasterInLoadThread}. If {@link prepareRasterInMainThread}\n   * has already been called, this parameter will be `nullptr`.\n   * @param pMainThreadResult The result returned by\n   * {@link prepareRasterInMainThread}. If {@link prepareRasterInMainThread}\n   * has not yet been called, this parameter will be `nullptr`.\n   */\n  virtual void freeRaster(\n      const RasterOverlayTile& rasterTile,\n      void* pLoadThreadResult,\n      void* pMainThreadResult) noexcept = 0;\n\n  /**\n   * @brief Attaches a raster overlay tile to a geometry tile.\n   *\n   * @param tile The geometry tile.\n   * @param overlayTextureCoordinateID The ID of the overlay texture coordinate\n   * set to use.\n   * @param rasterTile The raster overlay tile to add. The raster tile will have\n   * been previously prepared with a call to {@link prepareRasterInLoadThread}\n   * followed by {@link prepareRasterInMainThread}.\n   * @param pMainThreadRendererResources The renderer resources for this raster\n   * tile, as created and returned by {@link prepareRasterInMainThread}.\n   * @param textureCoordinateRectangle Defines the range of texture coordinates\n   * in which this raster tile should be applied, in the order west, south, east\n   * north. Each coordinate is in the range 0.0 (southwest corner) to 1.0\n   * (northeast corner).\n   * @param translation The translation to apply to the texture coordinates\n   * identified by `overlayTextureCoordinateID`. The texture coordinates to use\n   * to sample the raster image are computed as `overlayTextureCoordinates *\n   * scale + translation`.\n   * @param scale The scale to apply to the texture coordinates identified by\n   * `overlayTextureCoordinateID`. The texture coordinates to use to sample the\n   * raster image are computed as `overlayTextureCoordinates * scale +\n   * translation`.\n   */\n  virtual void attachRasterInMainThread(\n      const Tile& tile,\n      uint32_t overlayTextureCoordinateID,\n      const RasterOverlayTile& rasterTile,\n      void* pMainThreadRendererResources,\n      const CesiumGeometry::Rectangle& textureCoordinateRectangle,\n      const glm::dvec2& translation,\n      const glm::dvec2& scale) = 0;\n\n  /**\n   * @brief Detaches a raster overlay tile from a geometry tile.\n   *\n   * @param tile The geometry tile.\n   * @param overlayTextureCoordinateID The ID of the overlay texture coordinate\n   * set to which the raster tile was previously attached.\n   * @param rasterTile The raster overlay tile to remove.\n   * @param pMainThreadRendererResources The renderer resources for this raster\n   * tile, as created and returned by {@link prepareRasterInMainThread}.\n   * @param textureCoordinateRectangle Defines the range of texture coordinates\n   * in which this raster tile should be applied, in the order west, south, east\n   * north. Each coordinate is in the range 0.0 (southwest corner) to 1.0\n   * (northeast corner).\n   */\n  virtual void detachRasterInMainThread(\n      const Tile& tile,\n      uint32_t overlayTextureCoordinateID,\n      const RasterOverlayTile& rasterTile,\n      void* pMainThreadRendererResources,\n      const CesiumGeometry::Rectangle& textureCoordinateRectangle) noexcept = 0;\n};\n\n} // namespace Cesium3DTilesSelection\n", "meta": {"hexsha": "145ee77148f9d23ce76178515628db10b39778d9", "size": 8006, "ext": "h", "lang": "C", "max_stars_repo_path": "Cesium3DTilesSelection/include/Cesium3DTilesSelection/IPrepareRendererResources.h", "max_stars_repo_name": "zrkcode/cesium-native", "max_stars_repo_head_hexsha": "5265a65053542fe02928c272762c6b89fa2b29bb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Cesium3DTilesSelection/include/Cesium3DTilesSelection/IPrepareRendererResources.h", "max_issues_repo_name": "zrkcode/cesium-native", "max_issues_repo_head_hexsha": "5265a65053542fe02928c272762c6b89fa2b29bb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cesium3DTilesSelection/include/Cesium3DTilesSelection/IPrepareRendererResources.h", "max_forks_repo_name": "zrkcode/cesium-native", "max_forks_repo_head_hexsha": "5265a65053542fe02928c272762c6b89fa2b29bb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.4343434343, "max_line_length": 80, "alphanum_fraction": 0.729702723, "num_tokens": 1892, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.0715911915212002, "lm_q2_score": 0.022977371875344106, "lm_q1q2_score": 0.001644977430581599}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef zip_efeefa3a_157a_4c4c_83b0_99ec8e0364a1_h\r\n#define zip_efeefa3a_157a_4c4c_83b0_99ec8e0364a1_h\r\n\r\n#include <gslib/config.h>\r\n#include <gslib/tree.h>\r\n#include <gslib/vdir.h>\r\n\r\n__gslib_begin__\r\n\r\ntypedef void* zip_handle;\r\n\r\nstruct zip_argument\r\n{\r\n    int             level;      /* 0-9, default -1 */\r\n    const gchar*    name;\r\n    const gchar*    comment;\r\n\r\n    zip_argument() { level = -1, comment = name = 0; }\r\n    zip_argument(const gchar* n) { level = -1, name = n, comment = 0; }\r\n    zip_argument(int l, const gchar* n, const gchar* c) { level = l, name = n, comment = c; }\r\n};\r\n\r\nstruct zip_node\r\n{\r\n    enum\r\n    {\r\n        zt_folder,\r\n        zt_file,\r\n        zt_buffer,\r\n    };\r\n    uint            tag;\r\n    string          name;\r\n};\r\n\r\ntypedef _treenode_wrapper<zip_node> zip_wrapper;\r\ntypedef tree<zip_node, zip_wrapper> zip_directory;\r\n\r\nstruct zip_folder:\r\n    public zip_node\r\n{\r\n    zip_folder() { tag = zt_folder; }\r\n};\r\n\r\nstruct zip_file:\r\n    public zip_node\r\n{\r\n    string          password;\r\n    string          comment;\r\n    string          path;\r\n    zip_file() { tag = zt_file; }\r\n};\r\n\r\nstruct zip_buffer:\r\n    public zip_node\r\n{\r\n    string          password;\r\n    string          comment;\r\n    vessel          buffer;\r\n    zip_buffer() { tag = zt_buffer; }\r\n};\r\n\r\nextern void get_zip_path(string& path, const zip_wrapper* w);\r\nextern void create_zip_directory(zip_directory& dir, const gchar* path);\r\nextern void convert_zip_directory(zip_directory& dir, vdir& vd);\r\nextern bool do_zip(const zip_argument& arg, const zip_directory& dir);\r\nextern bool do_zip(const zip_argument& arg, const gchar* path);\r\n\r\nstruct zip_info_node\r\n{\r\n    string          name;\r\n    int             length;\r\n    int             size;\r\n    float           ratio;\r\n    uint            crc;\r\n};\r\n\r\ntypedef list<zip_info_node> zip_info;\r\n\r\nextern bool view_zip_info(zip_info& info, const gchar* path);\r\nextern void do_unzip(const gchar* src, const gchar* dest);\r\nextern void do_unzip(const gchar* src, vdir& vd);\r\n\r\nclass zip\r\n{\r\npublic:\r\n    zip() { _zh = 0; }\r\n    ~zip() { close(0); }\r\n    void create(const zip_argument& arg);\r\n    void close(const gchar* comment);\r\n    bool start(const gchar* name, const gchar* password, const gchar* comment);\r\n    bool write(const void* buf, int size);\r\n    void finish();\r\n\r\nprotected:\r\n    zip_handle      _zh;\r\n    zip_argument    _arg;\r\n};\r\n\r\nclass unzip\r\n{\r\npublic:\r\n    unzip() { _zh = 0; }\r\n    ~unzip() { close(); }\r\n    bool open(const gchar* filename);\r\n    void close();\r\n    bool view(zip_info& info);\r\n    bool extract(const gchar* path);\r\n    bool extract_item(const gchar* path, const gchar* name, const gchar* password);\r\n    bool extract(vdir& vd);\r\n    bool extract_item(vdir& vd, const gchar* name, const gchar* password);\r\n\r\nprotected:\r\n    zip_handle      _zh;\r\n};\r\n\r\n__gslib_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "c089e9c017acb995a57160cb07cf0135d5ce0e07", "size": 4137, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gslib/zip.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/gslib/zip.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gslib/zip.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 28.3356164384, "max_line_length": 94, "alphanum_fraction": 0.650229635, "num_tokens": 1009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.05108273406781928, "lm_q2_score": 0.03210070382336566, "lm_q1q2_score": 0.0016397917167988178}}
{"text": "/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */\n#pragma once\n\n#include <event.h>\n#include <memcached/engine_error.h>\n#include <memcached/types.h>\n#include <platform/socket.h>\n#include <subdoc/operations.h>\n#include <gsl/gsl>\n\n#include <mutex>\n#include <queue>\n#include <unordered_map>\n#include <vector>\n\n/** \\file\n * The main memcached header holding commonly used data\n * structures and function prototypes.\n */\n\n/** Maximum length of a key. */\n#define KEY_MAX_LENGTH 250\n\n#define MAX_SENDBUF_SIZE (256 * 1024 * 1024)\n\n/* Maximum length of config which can be validated */\n#define CONFIG_VALIDATE_MAX_LENGTH (64 * 1024)\n\n/* Maximum IOCTL get/set key and payload (body) length */\n#define IOCTL_KEY_LENGTH 128\n#define IOCTL_VAL_LENGTH 128\n\n#define MAX_VERBOSITY_LEVEL 2\n\nclass Cookie;\nclass Connection;\nstruct thread_stats;\n\nvoid initialize_buckets();\nvoid cleanup_buckets();\n\nvoid associate_initial_bucket(Connection& connection);\n\n/*\n * Functions such as the libevent-related calls that need to do cross-thread\n * communication in multithreaded mode (rather than actually doing the work\n * in the current thread) are called via \"dispatch_\" frontends, which are\n * also #define-d to directly call the underlying code in singlethreaded mode.\n */\nvoid worker_threads_init();\n\nvoid threads_shutdown();\nvoid threads_cleanup();\n\n/**\n * Create a socketpair and make it non-blocking\n *\n * @param sockets Where to store the sockets\n * @return true if success, false otherwise (and the error reason logged)\n */\nbool create_nonblocking_socketpair(std::array<SOCKET, 2>& sockets);\n\nclass ListeningPort;\nvoid dispatch_conn_new(SOCKET sfd, std::shared_ptr<ListeningPort>& interface);\n\nvoid threadlocal_stats_reset(std::vector<thread_stats>& thread_stats);\n\nvoid notify_io_complete(gsl::not_null<const void*> cookie,\n                        ENGINE_ERROR_CODE status);\nvoid safe_close(SOCKET sfd);\nint add_conn_to_pending_io_list(Connection* c,\n                                Cookie* cookie,\n                                ENGINE_ERROR_CODE status);\nconst char* get_server_version();\nbool is_memcached_shutting_down();\n\n/**\n * Connection-related functions\n */\n\n/**\n * Increments topkeys count for the key specified within the command context\n * provided by the cookie.\n */\nvoid update_topkeys(const Cookie& cookie);\n\nstruct ServerApi;\nServerApi* get_server_api();\n\nvoid shutdown_server();\nbool associate_bucket(Connection& connection, const char* name);\nvoid disassociate_bucket(Connection& connection);\n\nvoid disable_listen();\nbool is_listen_disabled();\n\n/**\n * The executor pool used to pick up the result for requests spawn by the\n * client io threads and dispatched over to a background thread (in order\n * to allow for out of order replies).\n */\nnamespace cb {\nclass ExecutorPool;\n}\nextern std::unique_ptr<cb::ExecutorPool> executorPool;\n\nvoid iterate_all_connections(std::function<void(Connection&)> callback);\n\nvoid start_stdin_listener(std::function<void()> function);\n", "meta": {"hexsha": "a6070a2b3b84f160c982cbc3e0154b6bb0c67cb2", "size": 2996, "ext": "h", "lang": "C", "max_stars_repo_path": "daemon/memcached.h", "max_stars_repo_name": "daverigby/kv_engine", "max_stars_repo_head_hexsha": "82f8b20bcd3851bf31c196bd0f228b8c45eb0632", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "daemon/memcached.h", "max_issues_repo_name": "daverigby/kv_engine", "max_issues_repo_head_hexsha": "82f8b20bcd3851bf31c196bd0f228b8c45eb0632", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "daemon/memcached.h", "max_forks_repo_name": "daverigby/kv_engine", "max_forks_repo_head_hexsha": "82f8b20bcd3851bf31c196bd0f228b8c45eb0632", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-10-11T14:00:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-06T09:20:15.000Z", "avg_line_length": 27.2363636364, "max_line_length": 79, "alphanum_fraction": 0.7443257677, "num_tokens": 642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.0900930037342824, "lm_q2_score": 0.017986212824335584, "lm_q1q2_score": 0.0016204319391484637}}
{"text": "/*\t$Id$ */\n/*\n * Copyright (c) 2014, 2015 Kristaps Dzonsons <kristaps@kcons.eu>\n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n */\n#include <assert.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <string.h>\n\n#ifdef MAC_INTEGRATION\n#include <gtkosxapplication.h>\n#endif\n#include <gtk/gtk.h>\n#include <gdk/gdk.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_multifit.h>\n#include <gsl/gsl_histogram.h>\n#include <kplot.h>\n\n#include \"extern.h\"\n\nstatic void\nswin_init(struct swin *c, enum view view, GtkBuilder *b)\n{\n\n\tc->window = win_init_window(b, \"window1\");\n\tc->menu = win_init_menubar(b, \"menubar1\");\n\tc->draw = win_init_draw(b, \"drawingarea1\");\n\tc->boxconfig = win_init_box(b, \"box3\");\n\tc->menufile = win_init_menuitem(b, \"menuitem1\");\n\tc->menuview = win_init_menuitem(b, \"menuitem2\");\n\tc->menutools = win_init_menuitem(b, \"menuitem3\");\n\tc->viewclone = win_init_menuitem(b, \"menuitem15\");\n\tc->viewpause = win_init_menuitem(b, \"menuitem20\");\n\tc->viewunpause = win_init_menuitem(b, \"menuitem21\");\n\tc->views[VIEW_ISLANDMEAN] = win_init_menucheck(b, \"menuitem45\");\n\tc->views[VIEW_ISLANDERMEAN] = win_init_menucheck(b, \"menuitem46\");\n\tc->views[VIEW_MEAN] = win_init_menucheck(b, \"menuitem8\");\n\tc->views[VIEW_SMEAN] = win_init_menucheck(b, \"menuitem37\");\n\tc->views[VIEW_SEXTM] = win_init_menucheck(b, \"menuitem43\");\n\tc->views[VIEW_SEXTI] = win_init_menucheck(b, \"menuitem44\");\n\tc->views[VIEW_EXTM] = win_init_menucheck(b, \"menuitem25\");\n\tc->views[VIEW_TIMESPDF] = win_init_menucheck(b, \"menuitem38\");\n\tc->views[VIEW_TIMESCDF] = win_init_menucheck(b, \"menuitem39\");\n\tc->views[VIEW_EXTMMAXPDF] = win_init_menucheck(b, \"menuitem28\");\n\tc->views[VIEW_EXTMMAXCDF] = win_init_menucheck(b, \"menuitem29\");\n\tc->views[VIEW_EXTI] = win_init_menucheck(b, \"menuitem26\");\n\tc->views[VIEW_EXTIMINPDF] = win_init_menucheck(b, \"menuitem27\");\n\tc->views[VIEW_EXTIMINCDF] = win_init_menucheck(b, \"menuitem30\");\n\tc->views[VIEW_EXTIMINS] = win_init_menucheck(b, \"menuitem35\");\n\tc->views[VIEW_DEV] = win_init_menucheck(b, \"menuitem6\");\n\tc->views[VIEW_POLY] = win_init_menucheck(b, \"menuitem7\");\n\tc->views[VIEW_POLYMINPDF] = win_init_menucheck(b, \"menuitem9\");\n\tc->views[VIEW_POLYMINCDF] = win_init_menucheck(b, \"menuitem11\");\n\tc->views[VIEW_MEANMINPDF] = win_init_menucheck(b, \"menuitem10\");\n\tc->views[VIEW_MEANMINCDF] = win_init_menucheck(b, \"menuitem12\");\n\tc->views[VIEW_MEANMINQ] = win_init_menucheck(b, \"menuitem13\");\n\tc->views[VIEW_MEANMINS] = win_init_menucheck(b, \"menuitem22\");\n\tc->views[VIEW_POLYMINS] = win_init_menucheck(b, \"menuitem31\");\n\tc->views[VIEW_EXTMMAXS] = win_init_menucheck(b, \"menuitem33\");\n\tc->views[VIEW_POLYMINQ] = win_init_menucheck(b, \"menuitem14\");\n\tc->menuquit = win_init_menuitem(b, \"menuitem5\");\n\tc->menuautoexport = win_init_menuitem(b, \"menuitem49\");\n\tc->menuunautoexport = win_init_menuitem(b, \"menuitem50\");\n\tc->menuclose = win_init_menuitem(b, \"menuitem24\");\n\tc->menusave = win_init_menuitem(b, \"menuitem34\");\n\tc->menusaveall = win_init_menuitem(b, \"menuitem47\");\n\n\tgtk_widget_show_all(GTK_WIDGET(c->window));\n\n\tgtk_window_set_title(GTK_WINDOW(c->window),\n\t\tgtk_menu_item_get_label\n\t\t(GTK_MENU_ITEM(c->views[view])));\n\n\tgtk_widget_hide(GTK_WIDGET(c->menuunautoexport));\n\n#ifdef MAC_INTEGRATION\n\tgtk_widget_hide(GTK_WIDGET(c->menu));\n\tgtk_widget_hide(GTK_WIDGET(c->menuquit));\n\tgtkosx_application_set_menu_bar\n\t\t(gtkosx_application_get(), \n\t\t GTK_MENU_SHELL(c->menu));\n\tgtkosx_application_sync_menubar\n\t\t(gtkosx_application_get());\n#endif\n}\n\n/*\n * Dereference a simulation.\n * This means that we've closed an output window that's looking at a\n * particular simulation.\n * When the simulation has no more references (i.e., no more windows are\n * painting that simulation), then the simulation destroys itself.\n */\nstatic void\non_sim_deref(gpointer dat)\n{\n\tstruct sim\t*sim = dat;\n\n\tg_debug(\"%p: Simulation deref (now %zu)\", sim, sim->refs - 1);\n\tif (0 != --sim->refs) \n\t\treturn;\n\tg_debug(\"%p: Simulation terminating\", sim);\n\tsim_stop(sim, NULL);\n}\n\n/*\n * Dereference all simulations owned by a given window.\n * This happens when a window is closing.\n */\nstatic void\non_sims_deref(gpointer dat)\n{\n\n\tg_list_free_full(dat, on_sim_deref);\n}\n\nstatic void\ncurwin_free(gpointer dat)\n{\n\tstruct curwin\t*cur = dat;\n\tsize_t\t\t i;\n\n\tg_debug(\"%p: Simwin freeing\", cur);\n\tkdata_destroy(cur->winmean);\n\tkdata_destroy(cur->winstddev);\n\tkdata_destroy(cur->winfitmean);\n\tkdata_destroy(cur->winfitstddev);\n\tkdata_destroy(cur->winmextinctmean);\n\tkdata_destroy(cur->winmextinctstddev);\n\tkdata_destroy(cur->winiextinctmean);\n\tkdata_destroy(cur->winiextinctstddev);\n\tfor (i = 0; i < VIEW__MAX; i++)\n\t\tkplot_free(cur->views[i]);\n\tcur->b->windows = g_list_remove(cur->b->windows, cur);\n\ton_sims_deref(cur->sims);\n\tg_free(cur->autosave);\n\tg_free(cur);\n}\n\nstatic void\nwindow_add_configmarkup(GtkWidget *box, const gchar *fmt, ...)\n{\n\tgchar\t\t buf[1024];\n\tGtkWidget\t*w;\n\tva_list\t\t ap;\n\n\tva_start(ap, fmt);\n\tg_vsnprintf(buf, sizeof(buf), fmt, ap);\n\tva_end(ap);\n\n\tw = gtk_label_new(NULL);\n\tgtk_label_set_markup(GTK_LABEL(w), buf);\n\tgtk_misc_set_alignment(GTK_MISC(w), 0.0, 0.5);\n\tgtk_container_add(GTK_CONTAINER(box), w);\n}\n\n\nstatic void\nwindow_add_config(GtkWidget *box, const gchar *fmt, ...)\n{\n\tgchar\t\t buf[1024];\n\tGtkWidget\t*w;\n\tva_list\t\t ap;\n\n\tva_start(ap, fmt);\n\tg_vsnprintf(buf, sizeof(buf), fmt, ap);\n\tva_end(ap);\n\n\tw = gtk_label_new(buf);\n\tgtk_misc_set_alignment(GTK_MISC(w), 0.0, 0.5);\n\tgtk_container_add(GTK_CONTAINER(box), w);\n}\n\nstatic void\nwindow_add_sim(struct curwin *cur, struct sim *sim)\n{\n\tGtkWidget\t*box, *outbox, *leftbox;\n\tstruct kdata\t*stats[2];\n\tenum kplottype\t ts[2];\n\tstruct kdatacfg\t solidcfg, transcfg;\n\tstruct kdatacfg\t*cfgs[2];\n\tdouble\t\t solid[4], trans[4];\n\tgchar\t\t label[64];\n\tstruct ksmthcfg\t smth;\n\n\t/* Get our colours. */\n\n\tmemcpy(solid, cur->b->clrs[sim->colour % \n\t\tcur->b->clrsz].rgba, sizeof(solid));\n\tmemcpy(trans, solid, sizeof(trans));\n\ttrans[3] = 0.4;\n\n\t/* Append to the per-window simulation views. */\n\tkdata_vector_append(cur->winmean, \n\t\tg_list_length(cur->sims), 0.0);\n\tkdata_vector_append(cur->winstddev, \n\t\tg_list_length(cur->sims), 0.0);\n\tkdata_vector_append(cur->winfitmean, \n\t\tg_list_length(cur->sims), 0.0);\n\tkdata_vector_append(cur->winfitstddev, \n\t\tg_list_length(cur->sims), 0.0);\n\tkdata_vector_append(cur->winmextinctmean, \n\t\tg_list_length(cur->sims), 0.0);\n\tkdata_vector_append(cur->winmextinctstddev, \n\t\tg_list_length(cur->sims), 0.0);\n\tkdata_vector_append(cur->winiextinctmean, \n\t\tg_list_length(cur->sims), 0.0);\n\tkdata_vector_append(cur->winiextinctstddev, \n\t\tg_list_length(cur->sims), 0.0);\n\n\t/* Append our configuration. */\n\toutbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 2);\n\n\tg_snprintf(label, sizeof(label),\n\t\t\"<span bgcolor=\\\"#%.2x%.2x%.2x\\\">\"\n\t\t\"&#x00a0;&#x00a0;&#x00a0;&#x00a0;\"\n\t\t\"</span>\",\n\t\t(unsigned int)(solid[0] * 255),\n\t\t(unsigned int)(solid[1] * 255),\n\t\t(unsigned int)(solid[2] * 255));\n\tleftbox = gtk_label_new(NULL);\n\tgtk_misc_set_alignment(GTK_MISC(leftbox), 0.0, 0.0);\n\tgtk_label_set_markup(GTK_LABEL(leftbox), label);\n\tgtk_container_add(GTK_CONTAINER(outbox), leftbox);\n\tbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 2);\n\tgtk_container_add(GTK_CONTAINER(outbox), box);\n\twindow_add_config(box, \"Name: %s\", sim->name);\n\twindow_add_configmarkup(box, \"Payoffs: &#x03c0; = %s; \"\n\t\t\"T = %zu\", sim->func, sim->stop);\n\twindow_add_configmarkup(box, \"Poisson offspring: \"\n\t\t\"&#x03bb; = %g(1 + %g * &#x03c0;)\", \n\t\tsim->alpha, sim->delta);\n\twindow_add_config(box, \"Incumbents: \"\n\t\t\"x = [%g, %g), %zu slices\", \n\t\tsim->xmin, sim->xmax, sim->dims);\n\tif (MUTANTS_DISCRETE == sim->mutants)\n\t\twindow_add_config(box, \"Mutants: y = [%g, %g), \"\n\t\t\t\"%zu slices\", sim->ymin, sim->ymax, sim->dims);\n\telse\n\t\twindow_add_configmarkup(box, \"Mutants: \"\n\t\t\t\"Gaussian &#x03c3; = %g, Y = [%g, %g)\", \n\t\t\tsim->mutantsigma, sim->ymin, sim->ymax);\n\n\tswitch (sim->input) {\n\tcase (INPUT_UNIFORM):\n\t\twindow_add_config(box, \"Population: uniform %zu \"\n\t\t\t\"islands, %zu islanders (%zu total), m = %g\",\n\t\t\tsim->pop, sim->islands, sim->totalpop, sim->m);\n\t\tbreak;\n\tcase (INPUT_VARIABLE):\n\t\twindow_add_config(box, \"Population: variable %zu \"\n\t\t\t\"islands (%zu total, %suniform), m = %g\", \n\t\t\tsim->islands, sim->totalpop, \n\t\t\tNULL != sim->ms ? \"non-\" : \"\", sim->m);\n\t\tif (sim->ideathmean)\n\t\t\twindow_add_config(box, \n\t\t\t\t\"Island death Poisson mean: %zu, \"\n\t\t\t\t\"coefficient %g\", \n\t\t\t\tsim->ideathmean, sim->ideathcoef);\n\t\tbreak;\n\tcase (INPUT_MAPPED):\n\t\twindow_add_config(box, \"Population: mapped %zu \"\n\t\t\t\"islands (%zu total, %suniform), m = %g\", \n\t\t\tsim->islands, sim->totalpop, \n\t\t\tNULL != sim->ms ? \"non-\" : \"\", sim->m);\n\t\tswitch (sim->maptop) {\n\t\tcase (MAPTOP_RECORD):\n\t\t\twindow_add_config(box, \"Map topology: \"\n\t\t\t\t\"KML records\");\n\t\t\tbreak;\n\t\tcase (MAPTOP_RAND):\n\t\t\twindow_add_config(box, \"Map topology: \"\n\t\t\t\t\"random records\");\n\t\t\tbreak;\n\t\tcase (MAPTOP_TORUS):\n\t\t\twindow_add_config(box, \"Map topology: \"\n\t\t\t\t\"toroidal records\");\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tabort();\n\t\t}\n\t\tswitch (sim->migrant) {\n\t\tcase (MAPMIGRANT_UNIFORM):\n\t\t\twindow_add_config(box, \"Map migration: \"\n\t\t\t\t\"uniform random\");\n\t\t\tbreak;\n\t\tcase (MAPMIGRANT_DISTANCE):\n\t\t\twindow_add_config(box, \"Map migration: \"\n\t\t\t\t\"inverse square distance\");\n\t\t\tbreak;\n\t\tcase (MAPMIGRANT_NEAREST):\n\t\t\twindow_add_config(box, \"Map migration: \"\n\t\t\t\t\"first nearest neighbour\");\n\t\t\tbreak;\n\t\tcase (MAPMIGRANT_TWONEAREST):\n\t\t\twindow_add_config(box, \"Map migration: \"\n\t\t\t\t\"two-nearest neighbours\");\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tabort();\n\t\t}\n\t\tbreak;\n\tdefault:\n\t\tabort();\n\t}\n\n\tif (0 == sim->fitpoly) \n\t\twindow_add_config(box, \"Polynomial fitting: disabled\");\n\telse\n\t\twindow_add_config(box, \"Polynomial fitting: order \"\n\t\t\t\"%zu (%sweighted)\", sim->fitpoly, \n\t\t\tsim->weighted ?  \"\" : \"un\");\n\n\tgtk_container_add(GTK_CONTAINER(cur->wins.boxconfig), outbox);\n\tgtk_widget_show_all(GTK_WIDGET(cur->wins.boxconfig));\n\n\t/* Configure our line and point style. */\n\tksmthcfg_defaults(&smth);\n\tsmth.movsamples = sim->smoothing;\n\tkdatacfg_defaults(&solidcfg);\n\tsolidcfg.point.clr.type = KPLOTCTYPE_RGBA;\n\tmemcpy(solidcfg.point.clr.rgba, solid, sizeof(solid));\n\tsolidcfg.line.clr.type = KPLOTCTYPE_RGBA;\n\tmemcpy(solidcfg.line.clr.rgba, solid, sizeof(solid));\n\n\tkdatacfg_defaults(&transcfg);\n\ttranscfg.point.clr.type = KPLOTCTYPE_RGBA;\n\tmemcpy(transcfg.point.clr.rgba, trans, sizeof(trans));\n\ttranscfg.line.clr.type = KPLOTCTYPE_RGBA;\n\tmemcpy(transcfg.line.clr.rgba, trans, sizeof(trans));\n\n\t/* Mean view. */\n\tkplot_attach_data(cur->views[VIEW_MEAN], \n\t\tsim->bufs.means->cold, KPLOT_LINES, &solidcfg);\n\n\t/* Mutant mean view. */\n\tkplot_attach_data(cur->views[VIEW_EXTM], \n\t\tsim->bufs.mextinct->cold, KPLOT_LINES, &solidcfg);\n\n\t/* Incumbent mean view. */\n\tkplot_attach_data(cur->views[VIEW_EXTI], \n\t\tsim->bufs.iextinct->cold, KPLOT_LINES, &solidcfg);\n\n\t/* Mean and poly-fitted line. */\n\tkplot_attach_data(cur->views[VIEW_POLY], \n\t\tsim->bufs.fitpolybuf, KPLOT_LINES, &solidcfg);\n\tkplot_attach_data(cur->views[VIEW_POLY], \n\t\tsim->bufs.means->cold, KPLOT_LINES, &transcfg);\n\n\t/* Mutant mean and smoothed line. */\n\tkplot_attach_smooth(cur->views[VIEW_SEXTM], \n\t\tsim->bufs.mextinct->cold, KPLOT_LINES, &solidcfg,\n\t\tKSMOOTH_MOVAVG, &smth);\n\tkplot_attach_data(cur->views[VIEW_SEXTM], \n\t\tsim->bufs.mextinct->cold, KPLOT_LINES, &transcfg);\n\n\t/* Mutant mean and smoothed line. */\n\tkplot_attach_smooth(cur->views[VIEW_SEXTI], \n\t\tsim->bufs.iextinct->cold, KPLOT_LINES, &solidcfg,\n\t\tKSMOOTH_MOVAVG, &smth);\n\tkplot_attach_data(cur->views[VIEW_SEXTI], \n\t\tsim->bufs.iextinct->cold, KPLOT_LINES, &transcfg);\n\n\t/* Mean and smoothed lines. */\n\tkplot_attach_smooth(cur->views[VIEW_SMEAN], \n\t\tsim->bufs.means->cold, KPLOT_LINES, &solidcfg,\n\t\tKSMOOTH_MOVAVG, &smth);\n\tkplot_attach_data(cur->views[VIEW_SMEAN], \n\t\tsim->bufs.means->cold, KPLOT_LINES, &transcfg);\n\n\t/* Mean and stddev.  */\n\tts[0] = ts[1] = KPLOT_LINES;\n\tstats[0] = sim->bufs.means->cold;\n\tstats[1] = sim->bufs.stddevs->cold;\n\tcfgs[0] = &solidcfg;\n\tcfgs[1] = &transcfg;\n\tkplot_attach_datas(cur->views[VIEW_DEV], 2, stats, ts, \n\t\t(const struct kdatacfg *const *)cfgs, \n\t\tKPLOTS_YERRORLINE);\n\n\t/* Island mean and stddev. */\n\tts[0] = ts[1] = KPLOT_POINTS;\n\tstats[0] = sim->bufs.islandmeans->cold;\n\tstats[1] = sim->bufs.islandstddevs->cold;\n\tcfgs[0] = &solidcfg;\n\tcfgs[1] = &transcfg;\n\tkplot_attach_datas(cur->views[VIEW_ISLANDERMEAN], 2, stats, ts, \n\t\t(const struct kdatacfg *const *)cfgs, \n\t\tKPLOTS_YERRORBAR);\n\n\t/* Island mean and stddev. */\n\tts[0] = ts[1] = KPLOT_POINTS;\n\tstats[0] = sim->bufs.imeans->cold;\n\tstats[1] = sim->bufs.istddevs->cold;\n\tcfgs[0] = &solidcfg;\n\tcfgs[1] = &transcfg;\n\tkplot_attach_datas(cur->views[VIEW_ISLANDMEAN], 2, stats, ts, \n\t\t(const struct kdatacfg *const *)cfgs, \n\t\tKPLOTS_YERRORBAR);\n\n\t/* Time PMF views. */\n\tkplot_attach_smooth(cur->views[VIEW_TIMESPDF], \n\t\tsim->bufs.times->cold, KPLOT_LINES, &solidcfg,\n\t\tKSMOOTH_PMF, NULL);\n\tkplot_attach_smooth(cur->views[VIEW_TIMESCDF], \n\t\tsim->bufs.times->cold, KPLOT_LINES, &solidcfg,\n\t\tKSMOOTH_CDF, NULL);\n\n\t/* Mean PMF views. */\n\tkplot_attach_smooth(cur->views[VIEW_MEANMINPDF], \n\t\tsim->bufs.meanmins, KPLOT_LINES, &solidcfg,\n\t\tKSMOOTH_PMF, NULL);\n\tkplot_attach_smooth(cur->views[VIEW_MEANMINCDF], \n\t\tsim->bufs.meanmins, KPLOT_LINES, &solidcfg,\n\t\tKSMOOTH_CDF, NULL);\n\n\t/* Mutant PMF views. */\n\tkplot_attach_smooth(cur->views[VIEW_EXTMMAXPDF], \n\t\tsim->bufs.mextinctmaxs, KPLOT_LINES, &solidcfg,\n\t\tKSMOOTH_PMF, NULL);\n\tkplot_attach_smooth(cur->views[VIEW_EXTMMAXCDF], \n\t\tsim->bufs.mextinctmaxs, KPLOT_LINES, &solidcfg,\n\t\tKSMOOTH_CDF, NULL);\n\n\t/* Incumbent PMF views. */\n\tkplot_attach_smooth(cur->views[VIEW_EXTIMINPDF], \n\t\tsim->bufs.iextinctmins, KPLOT_LINES, &solidcfg,\n\t\tKSMOOTH_PMF, NULL);\n\tkplot_attach_smooth(cur->views[VIEW_EXTIMINCDF], \n\t\tsim->bufs.iextinctmins, KPLOT_LINES, &solidcfg,\n\t\tKSMOOTH_CDF, NULL);\n\n\t/* Fit poly PMF views. */\n\tkplot_attach_smooth(cur->views[VIEW_POLYMINPDF], \n\t\tsim->bufs.fitpolymins, KPLOT_LINES, &solidcfg,\n\t\tKSMOOTH_PMF, NULL);\n\tkplot_attach_smooth(cur->views[VIEW_POLYMINCDF], \n\t\tsim->bufs.fitpolymins, KPLOT_LINES, &solidcfg,\n\t\tKSMOOTH_CDF, NULL);\n\n\tkplot_attach_data(cur->views[VIEW_MEANMINQ], \n\t\tsim->bufs.meanminqbuf, KPLOT_LINES, &solidcfg);\n\n\tkplot_attach_data(cur->views[VIEW_POLYMINQ], \n\t\tsim->bufs.fitminqbuf, KPLOT_LINES, &solidcfg);\n}\n\n/*\n * Indicate that a given simulation is now being referenced by a new\n * window.\n */\nstatic void\nsim_ref(gpointer dat, gpointer unused)\n{\n\tstruct sim\t*sim = dat;\n\n\t++sim->refs;\n\tg_debug(\"%p: Simulation ref (now %zu)\", sim, sim->refs);\n}\n\n/*\n * Transfer the other widget's data into our own.\n */\nvoid\non_drag_recv(GtkWidget *widget, GdkDragContext *ctx, \n\tgint x, gint y, GtkSelectionData *sel, \n\tguint target, guint time, gpointer dat)\n{\n\tGObject\t\t*srcptr, *dstptr;\n\tstruct curwin\t*cur;\n\tGList\t\t*srcsims, *l, *ll;\n\n\t/* Get pointers to our and the other's window. */\n\tassert(NULL != sel);\n\tdstptr = G_OBJECT(gtk_widget_get_toplevel(widget));\n\tsrcptr = G_OBJECT(*(void **)\n\t\tgtk_selection_data_get_data(sel));\n\tassert(NULL != srcptr);\n\tgtk_drag_finish(ctx, TRUE, FALSE, time);\n\n\t/* Don't copy into ourselves. */\n\tif (dstptr == srcptr)\n\t\treturn;\n\n\t/* Get the simulation lists. */\n\tcur = g_object_get_data(srcptr, \"cfg\");\n\tsrcsims = cur->sims;\n\tassert(NULL != srcsims);\n\tcur = g_object_get_data(dstptr, \"cfg\");\n\n\t/* Concatenate the simulation lists. */\n\t/* XXX: use g_list_concat? */\n\tfor (l = srcsims; NULL != l; l = l->next) {\n\t\tg_debug(\"%p: Copying simulation\", l->data);\n\t\tfor (ll = cur->sims; NULL != ll; ll = ll->next)\n\t\t\tif (ll->data == l->data)\n\t\t\t\tbreak;\n\n\t\tif (NULL != ll) {\n\t\t\tg_debug(\"Simulation %p duplicate\", l->data);\n\t\t\tcontinue;\n\t\t}\n\n\t\tsim_ref(l->data, NULL);\n\t\tcur->sims = g_list_append(cur->sims, l->data);\n\t\twindow_add_sim(cur, l->data);\n\t}\n}\n\n/*\n * Signifity sight-unseen that we can transfer data.\n * We're only using DnD for one particular thing, so there's no need for\n * elaborate security measures.\n */\ngboolean\non_drag_drop(GtkWidget *widget, GdkDragContext *ctx, \n\tgint x, gint y, guint time, gpointer dat)\n{\n\n\tgtk_drag_get_data(widget, ctx, 0, time);\n\treturn(TRUE);\n}\n\n/*\n * Send our identifier to the destination of the DnD.\n * They'll query our data separately.\n */\nvoid\non_drag_get(GtkWidget *widget, GdkDragContext *ctx, \n\tGtkSelectionData *sel, guint targ, guint time, gpointer dat)\n{\n\tvoid\t*ptr;\n\n\tptr = gtk_widget_get_toplevel(widget);\n\tgtk_selection_data_set(sel, \n\t\tgtk_selection_data_get_target(sel), \n\t\tsizeof(intptr_t) * 8, \n\t\t(const guchar *)&ptr, sizeof(intptr_t));\n}\n\n/*\n * Initialise a simulation (or simulations) window.\n * This is either called when we've just made a new simulation \n */\nstatic void\nwindow_init(struct bmigrate *b, struct curwin *cur, GList *sims)\n{\n\tGtkBuilder\t*builder;\n\tGtkTargetEntry   target;\n\tGList\t\t*l;\n\tstruct kdata\t*stats[2];\n\tenum kplottype\t ts[2];\n\tsize_t\t\t i;\n\tstruct kplotcfg\t cfg;\n\n\tbuilder = builder_get(\"simwin.glade\");\n\tg_assert(NULL != builder);\n\tswin_init(&cur->wins, cur->view, builder);\n\tgtk_builder_connect_signals(builder, cur);\n\tg_object_unref(G_OBJECT(builder));\n\n\tcur->winmean = kdata_vector_alloc(1);\n\tcur->winstddev = kdata_vector_alloc(1);\n\tcur->winfitmean = kdata_vector_alloc(1);\n\tcur->winfitstddev = kdata_vector_alloc(1);\n\tcur->winmextinctmean = kdata_vector_alloc(1);\n\tcur->winmextinctstddev = kdata_vector_alloc(1);\n\tcur->winiextinctmean = kdata_vector_alloc(1);\n\tcur->winiextinctstddev = kdata_vector_alloc(1);\n\n\tfor (i = 0; i < VIEW__MAX; i++) {\n\t\tkplotcfg_defaults(&cfg);\n\t\tswitch (i) {\n\t\tcase (VIEW_DEV):\n\t\tcase (VIEW_POLY):\n\t\tcase (VIEW_EXTIMINS):\n\t\tcase (VIEW_EXTMMAXS):\n\t\tcase (VIEW_MEANMINS):\n\t\tcase (VIEW_POLYMINS):\n\t\tcase (VIEW_ISLANDMEAN):\n\t\tcase (VIEW_ISLANDERMEAN):\n\t\t\tcfg.extrema_ymin = 0.0;\n\t\t\tcfg.extrema = EXTREMA_YMIN;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\n\t\tswitch (i) {\n\t\tcase (VIEW_DEV): \n\t\tcase (VIEW_EXTI):\n\t\tcase (VIEW_EXTIMINCDF):\n\t\tcase (VIEW_EXTIMINPDF):\n\t\tcase (VIEW_EXTM):\n\t\tcase (VIEW_EXTMMAXCDF):\n\t\tcase (VIEW_EXTMMAXPDF):\n\t\tcase (VIEW_MEAN):\n\t\tcase (VIEW_MEANMINCDF):\n\t\tcase (VIEW_MEANMINPDF):\n\t\tcase (VIEW_POLY):\n\t\tcase (VIEW_POLYMINCDF):\n\t\tcase (VIEW_POLYMINPDF):\n\t\tcase (VIEW_SEXTM):\n\t\tcase (VIEW_SEXTI):\n\t\tcase (VIEW_SMEAN):\n\t\t\tcfg.xaxislabel = \"incumbent\";\n\t\t\tbreak;\n\t\tcase (VIEW_ISLANDMEAN):\n\t\tcase (VIEW_ISLANDERMEAN):\n\t\t\tcfg.xaxislabel = \"island\";\n\t\t\tbreak;\n\t\tcase (VIEW_TIMESCDF):\n\t\tcase (VIEW_TIMESPDF):\n\t\t\tcfg.xaxislabel = \"exit time\";\n\t\t\tbreak;\n\t\tcase (VIEW_EXTIMINS):\n\t\tcase (VIEW_EXTMMAXS):\n\t\tcase (VIEW_MEANMINS):\n\t\tcase (VIEW_POLYMINS):\n\t\t\tcfg.xaxislabel = \"simulation\";\n\t\t\tbreak;\n\t\tcase (VIEW_MEANMINQ):\n\t\tcase (VIEW_POLYMINQ):\n\t\t\tcfg.xaxislabel = \"relative time\";\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tabort();\n\t\t}\n\n\t\tcfg.yaxislabelrot = M_PI / 2;\n\n\t\tswitch (i) {\n\t\tcase (VIEW_POLY):\n\t\tcase (VIEW_DEV): \n\t\tcase (VIEW_MEAN):\n\t\tcase (VIEW_SMEAN):\n\t\t\tcfg.y2axislabel = \"mutant fraction\";\n\t\t\tbreak;\n\t\tcase (VIEW_SEXTI):\n\t\tcase (VIEW_EXTI):\n\t\t\tcfg.y2axislabel = \"incumbent extinction\";\n\t\t\tbreak;\n\t\tcase (VIEW_SEXTM):\n\t\tcase (VIEW_EXTM):\n\t\t\tcfg.y2axislabel = \"mutant extinction\";\n\t\t\tbreak;\n\t\tcase (VIEW_EXTIMINCDF):\n\t\tcase (VIEW_EXTIMINPDF):\n\t\tcase (VIEW_EXTMMAXCDF):\n\t\tcase (VIEW_EXTMMAXPDF):\n\t\tcase (VIEW_MEANMINCDF):\n\t\tcase (VIEW_MEANMINPDF):\n\t\tcase (VIEW_POLYMINCDF):\n\t\tcase (VIEW_POLYMINPDF):\n\t\tcase (VIEW_TIMESCDF):\n\t\tcase (VIEW_TIMESPDF):\n\t\t\tbreak;\n\t\tcase (VIEW_ISLANDMEAN):\n\t\tcase (VIEW_ISLANDERMEAN):\n\t\t\tcfg.y2axislabel = \"mutant fraction mean\";\n\t\t\tbreak;\n\t\tcase (VIEW_EXTMMAXS):\n\t\tcase (VIEW_EXTIMINS):\n\t\tcase (VIEW_MEANMINS):\n\t\tcase (VIEW_POLYMINS):\n\t\tcase (VIEW_MEANMINQ):\n\t\tcase (VIEW_POLYMINQ):\n\t\t\tcfg.y2axislabel = \"incumbent\";\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tabort();\n\t\t}\n\t\tcur->views[i] = kplot_alloc(&cfg);\n\t\tg_assert(NULL != cur->views[i]);\n\t}\n\n\tts[0] = ts[1] = KPLOT_POINTS;\n\tstats[0] = cur->winmean;\n\tstats[1] = cur->winstddev;\n\tkplot_attach_datas(cur->views[VIEW_MEANMINS], 2,\n\t\tstats, ts, NULL, KPLOTS_YERRORBAR);\n\n\tts[0] = ts[1] = KPLOT_POINTS;\n\tstats[0] = cur->winfitmean;\n\tstats[1] = cur->winfitstddev;\n\tkplot_attach_datas(cur->views[VIEW_POLYMINS], 2,\n\t\tstats, ts, NULL, KPLOTS_YERRORBAR);\n\n\tts[0] = ts[1] = KPLOT_POINTS;\n\tstats[0] = cur->winmextinctmean;\n\tstats[1] = cur->winmextinctstddev;\n\tkplot_attach_datas(cur->views[VIEW_EXTMMAXS], 2,\n\t\tstats, ts, NULL, KPLOTS_YERRORBAR);\n\n\tts[0] = ts[1] = KPLOT_POINTS;\n\tstats[0] = cur->winiextinctmean;\n\tstats[1] = cur->winiextinctstddev;\n\tkplot_attach_datas(cur->views[VIEW_EXTIMINS], 2,\n\t\tstats, ts, NULL, KPLOTS_YERRORBAR);\n\n\tcur->redraw = 1;\n\tcur->sims = sims;\n\tcur->b = b;\n\n\tg_object_set_data_full(G_OBJECT\n\t\t(cur->wins.window), \"cfg\", cur, curwin_free);\n\tb->windows = g_list_append(b->windows, cur);\n\n\t/* \n\t * Coordinate drag-and-drop. \n\t * We only allow drag-and-drop between us and other windows of\n\t * this same simulation.\n\t */\n\ttarget.target = g_strdup(\"integer\");\n\ttarget.flags = GTK_TARGET_SAME_APP|GTK_TARGET_OTHER_WIDGET;\n\ttarget.info = 0;\n\n\tgtk_drag_dest_set(GTK_WIDGET(cur->wins.draw),\n\t\tGTK_DEST_DEFAULT_ALL, &target, 1, GDK_ACTION_COPY);\n\tgtk_drag_source_set(GTK_WIDGET(cur->wins.draw),\n\t\tGDK_BUTTON1_MASK, &target, 1, GDK_ACTION_COPY);\n\tg_free(target.target);\n\n\tfor (l = cur->sims; NULL != l; l = g_list_next(l))\n\t\twindow_add_sim(cur, l->data);\n}\n\n/*\n * Clone the current window.\n * We create a new window, intialised in the same way as for a new\n * single simulation, but give it an existing list of simulations.\n */\nvoid\nonclone(GtkMenuItem *menuitem, gpointer dat)\n{\n\tstruct curwin\t*oldcur = dat, *newcur;\n\tGList\t\t*oldsims, *newsims;\n\n\toldsims = oldcur->sims;\n\tg_list_foreach(oldsims, sim_ref, NULL);\n\tnewsims = g_list_copy(oldsims);\n\tnewcur = g_malloc0(sizeof(struct curwin));\n\tnewcur->view = oldcur->view;\n\twindow_init(oldcur->b, newcur, newsims);\n}\n\n/*\n * Brute-force scan all possible pi values (and Poisson means) by\n * scanning through the strategy space.\n */\nstatic gboolean\non_rangefind_idle(gpointer dat)\n{\n\n\treturn(rangefind(dat));\n}\n\nstatic int\nentry2func(GtkEntry *entry, struct hnode ***exp, GtkLabel *error)\n{\n\tconst gchar\t*txt;\n\tGdkRGBA\t \t bad = { 1.0, 0.0, 0.0, 0.5 };\n\n\ttxt = gtk_entry_get_text(entry);\n\t*exp = hnode_parse((const gchar **)&txt);\n\tif (NULL != *exp) {\n\t\tgtk_widget_override_background_color\n\t\t\t(GTK_WIDGET(entry), \n\t\t\t GTK_STATE_FLAG_NORMAL, NULL);\n\t\treturn(1);\n\t}\n\n\tgtk_label_set_text(error, \"Error: not a function.\");\n\tgtk_widget_show_all(GTK_WIDGET(error));\n\tgtk_widget_override_background_color\n\t\t(GTK_WIDGET(entry), GTK_STATE_FLAG_NORMAL, &bad);\n\treturn(0);\n}\n\nstatic int\nentryworder(GtkEntry *mine, GtkEntry *maxe, \n\tdouble min, double max, GtkLabel *error)\n{\n\tGdkRGBA\t bad = { 1.0, 0.0, 0.0, 0.5 };\n\n\tif (min < max) {\n\t\tgtk_widget_override_background_color\n\t\t\t(GTK_WIDGET(mine), \n\t\t\t GTK_STATE_FLAG_NORMAL, NULL);\n\t\tgtk_widget_override_background_color\n\t\t\t(GTK_WIDGET(maxe), \n\t\t\t GTK_STATE_FLAG_NORMAL, NULL);\n\t\treturn(1);\n\t}\n\n\tgtk_label_set_text(error, \"Error: bad weak ordering.\");\n\tgtk_widget_show_all(GTK_WIDGET(error));\n\tgtk_widget_override_background_color\n\t\t(GTK_WIDGET(mine), GTK_STATE_FLAG_NORMAL, &bad);\n\tgtk_widget_override_background_color\n\t\t(GTK_WIDGET(maxe), GTK_STATE_FLAG_NORMAL, &bad);\n\treturn(0);\n}\n\nstatic int\nentryorder(GtkEntry *mine, GtkEntry *maxe, \n\tdouble min, double max, GtkLabel *error)\n{\n\tGdkRGBA\t bad = { 1.0, 0.0, 0.0, 0.5 };\n\n\tif (min <= max) {\n\t\tgtk_widget_override_background_color\n\t\t\t(GTK_WIDGET(mine), \n\t\t\t GTK_STATE_FLAG_NORMAL, NULL);\n\t\tgtk_widget_override_background_color\n\t\t\t(GTK_WIDGET(maxe), \n\t\t\t GTK_STATE_FLAG_NORMAL, NULL);\n\t\treturn(1);\n\t}\n\n\tgtk_label_set_text(error, \"Error: bad ordering.\");\n\tgtk_widget_show_all(GTK_WIDGET(error));\n\tgtk_widget_override_background_color\n\t\t(GTK_WIDGET(mine), GTK_STATE_FLAG_NORMAL, &bad);\n\tgtk_widget_override_background_color\n\t\t(GTK_WIDGET(maxe), GTK_STATE_FLAG_NORMAL, &bad);\n\treturn(0);\n}\n\nstatic int\nentry2double(GtkEntry *entry, gdouble *sz, GtkLabel *error)\n{\n\tgchar\t*ep;\n\tGdkRGBA\t bad = { 1.0, 0.0, 0.0, 0.5 };\n\n\t*sz = g_ascii_strtod(gtk_entry_get_text(entry), &ep);\n\n\tif (ERANGE != errno && '\\0' == *ep) {\n\t\tgtk_widget_override_background_color\n\t\t\t(GTK_WIDGET(entry), \n\t\t\t GTK_STATE_FLAG_NORMAL, NULL);\n\t\treturn(1);\n\t}\n\n\tgtk_label_set_text(error, \"Error: not a decimal number.\");\n\tgtk_widget_show_all(GTK_WIDGET(error));\n\tgtk_widget_override_background_color\n\t\t(GTK_WIDGET(entry), GTK_STATE_FLAG_NORMAL, &bad);\n\treturn(0);\n}\n\nstatic int\nentry2size(GtkEntry *entry, size_t *sz, GtkLabel *error, size_t min)\n{\n\tguint64\t v;\n\tgchar\t*ep;\n\tGdkRGBA\t bad = { 1.0, 0.0, 0.0, 0.5 };\n\n\tv = g_ascii_strtoull(gtk_entry_get_text(entry), &ep, 10);\n\tif (ERANGE == errno || '\\0' != *ep || v >= SIZE_MAX) {\n\t\tgtk_label_set_text\n\t\t\t(error, \"Error: not a natural number.\");\n\t\tgtk_widget_show_all(GTK_WIDGET(error));\n\t\tgtk_widget_override_background_color\n\t\t\t(GTK_WIDGET(entry), \n\t\t\t GTK_STATE_FLAG_NORMAL, &bad);\n\t\treturn(0);\n\t} else if (v < min) {\n\t\tgtk_label_set_text\n\t\t\t(error, \"Error: number too small.\");\n\t\tgtk_widget_show_all(GTK_WIDGET(error));\n\t\tgtk_widget_override_background_color\n\t\t\t(GTK_WIDGET(entry), \n\t\t\t GTK_STATE_FLAG_NORMAL, &bad);\n\t\treturn(0);\n\t}\n\n\t*sz = (size_t)v;\n\tgtk_widget_override_background_color\n\t\t(GTK_WIDGET(entry), \n\t\t GTK_STATE_FLAG_NORMAL, NULL);\n\treturn(1);\n}\n\n/*\n * We have various ways of auto-setting the name of the simulation.\n * By default, it's set to the current date-time.\n */\nstatic void\ndonamefill(struct hwin *c)\n{\n\tenum namefill\t v;\n\tGTimeVal\t gt;\n\tenum input\t input;\n\tgchar\t\t buf[1024];\n\tgchar\t\t*bufp;\n\tenum mutants\t mutants;\n\n\tinput = gtk_notebook_get_current_page(c->inputs);\n\tg_assert(input < INPUT__MAX);\n\n\tfor (mutants = 0; mutants < MUTANTS__MAX; mutants++)\n\t\tif (gtk_toggle_button_get_active\n\t\t\t(GTK_TOGGLE_BUTTON(c->mutants[mutants])))\n\t\t\tbreak;\n\n\tfor (v = 0; v < NAMEFILL__MAX; v++)\n\t\tif (gtk_toggle_button_get_active(c->namefill[v]))\n\t\t\tbreak;\n\n\tbufp = buf;\n\tswitch (v) {\n\tcase (NAMEFILL_M):\n\t\tg_snprintf(buf, sizeof(buf), \"m=%s\", \n\t\t\tgtk_entry_get_text(c->migrate[input]));\n\t\tbreak;\n\tcase (NAMEFILL_T):\n\t\tg_snprintf(buf, sizeof(buf), \"T=%s\", \n\t\t\tgtk_entry_get_text(c->stop));\n\t\tbreak;\n\tcase (NAMEFILL_MUTANTS):\n\t\tif (MUTANTS_DISCRETE == mutants) {\n\t\t\tg_snprintf(buf, sizeof(buf), \n\t\t\t\t\"discrete [%s,%s)\", \n\t\t\t\tgtk_entry_get_text(c->xmin),\n\t\t\t\tgtk_entry_get_text(c->xmax));\n\t\t\tbreak;\n\t\t}\n\t\tg_snprintf(buf, sizeof(buf), \n\t\t\t\"Gaussian s=%s, [%s,%s)\", \n\t\t\tgtk_entry_get_text(c->mutantsigma),\n\t\t\tgtk_entry_get_text(c->ymin),\n\t\t\tgtk_entry_get_text(c->ymax));\n\t\tbreak;\n\tcase (NAMEFILL_DATE):\n\t\tg_get_current_time(&gt);\n\t\tbufp = g_time_val_to_iso8601(&gt);\n\t\tbreak;\n\tcase (NAMEFILL_NONE):\n\t\treturn;\n\tdefault:\n\t\tabort();\n\t}\n\n\tgtk_entry_set_text(c->name, bufp);\n\tif (bufp != buf)\n\t\tg_free(bufp);\n}\n\n\nvoid\nonnametoggle(GtkToggleButton *editable, gpointer dat)\n{\n\tstruct bmigrate\t*b = dat;\n\n\tdonamefill(&b->wins);\n}\n\nvoid\nonnameupdate(GtkEditable *editable, gpointer dat)\n{\n\tstruct bmigrate\t*b = dat;\n\n\tdonamefill(&b->wins);\n}\n\n\n/*\n * We want to run the given simulation.\n * First, verify all data; then, start the simulation; lastly, open a\n * window assigned specifically to that simulation.\n */\nvoid\nonactivate(GtkButton *button, gpointer dat)\n{\n\tgint\t \t  input;\n\tstruct bmigrate\t *b = dat;\n\tstruct hnode\t**exp;\n\tenum mapmigrant\t  migrants;\n\tGtkWidget\t *w;\n\tstruct kml\t *kml;\n\tGList\t\t *l, *cl;\n\tGtkLabel\t *err = b->wins.error;\n\tconst gchar\t *name, *func;\n\tgchar\t  \t *file;\n\tgdouble\t\t**ms;\n\tgdouble\t\t  xmin, xmax, delta, alpha, m, sigma,\n\t\t\t  ymin, ymax, idcoef, strat;\n\tenum mutants\t  mutants;\n\tsize_t\t\t  i, totalpop, islands, stop, ideathmean,\n\t\t\t  slices, islandpop, mapindexfix;\n\tsize_t\t\t *islandpops;\n\tstruct sim\t *sim;\n\tstruct curwin\t *cur;\n\tstruct kmlplace\t *kmlp;\n\tGError\t\t *er;\n\tenum maptop\t  maptop;\n\tenum mapindex\t  mapindex;\n\n\tsigma = idcoef = 0.0;\n\tislandpops = NULL;\n\tislandpop = 0;\n\tms = NULL;\n\tkml = NULL;\n\texp = NULL;\n\n\tif ( ! entry2size(b->wins.stop, &stop, err, 1))\n\t\tgoto cleanup;\n\n\tfor (migrants = 0; migrants < MAPMIGRANT__MAX; migrants++)\n\t\tif (gtk_toggle_button_get_active\n\t\t\t (b->wins.mapmigrants[migrants]))\n\t\t\tbreak;\n\tg_assert(migrants < MAPMIGRANT__MAX);\n\n\tfor (mapindex = 0; mapindex < MAPINDEX__MAX; mapindex++)\n\t\tif (gtk_toggle_button_get_active\n\t\t\t (b->wins.mapindices[mapindex]))\n\t\t\tbreak;\n\tg_assert(mapindex < MAPINDEX__MAX);\n\tmapindexfix = MAPINDEX_FIXED != mapindex ? 0 :\n\t\tgtk_adjustment_get_value(b->wins.mapindexfix);\n\n\tfor (maptop = 0; maptop < MAPTOP__MAX; maptop++)\n\t\tif (gtk_toggle_button_get_active\n\t\t\t (b->wins.maptop[maptop]))\n\t\t\tbreak;\n\tg_assert(maptop < MAPTOP__MAX);\n\n\tinput = gtk_notebook_get_current_page(b->wins.inputs);\n\tswitch (input) {\n\tcase (INPUT_UNIFORM):\n\t\t/*\n\t\t * In the simplest possible case, we use uniform values\n\t\t * for both migration (no inter-island migration) and\n\t\t * populations.\n\t\t */\n\t\tislands = gtk_adjustment_get_value(b->wins.islands);\n\t\tislandpop = gtk_adjustment_get_value(b->wins.pop);\n\t\tbreak;\n\tcase (INPUT_VARIABLE):\n\t\t/*\n\t\t * Variable number of islands.\n\t\t * We also add a check to see if we're really running\n\t\t * with different island sizes or not.\n\t\t */\n\t\tif ( ! entry2double(b->wins.ideathcoef, &idcoef, err))\n\t\t\tgoto cleanup;\n\t\tif (idcoef < 0.0 || idcoef > 1.0) {\n\t\t\tgtk_label_set_text(err, \"Death coefficient \"\n\t\t\t\t\"must be in the unit interval.\");\n\t\t\tgtk_widget_show_all(GTK_WIDGET(err));\n\t\t\tgoto cleanup;\n\t\t} \n\t\tl = gtk_container_get_children\n\t\t\t(GTK_CONTAINER(b->wins.mapbox));\n\t\tislands = g_list_length(l);\n\t\tislandpops = g_malloc0_n(islands, sizeof(size_t));\n\t\tfor (i = 0; i < islands; i++) {\n\t\t\tw = GTK_WIDGET(g_list_nth_data(l, i));\n\t\t\tcl = gtk_container_get_children(GTK_CONTAINER(w));\n\t\t\tislandpops[i] = gtk_spin_button_get_value_as_int\n\t\t\t\t(GTK_SPIN_BUTTON(g_list_next(cl)->data));\n\t\t\tg_list_free(cl);\n\t\t}\n\t\tg_list_free(l);\n\t\tbreak;\n\tcase (INPUT_MAPPED):\n\t\t/*\n\t\t * Possibly variable island sizes, possibly variable\n\t\t * inter-island migration.\n\t\t */\n\t\tswitch (maptop) {\n\t\tcase (MAPTOP_RECORD):\n\t\t\t/* Try to read KML from file. */\n\t\t\tfile = gtk_file_chooser_get_filename\n\t\t\t\t(b->wins.mapfile);\n\t\t\tif (NULL == file) {\n\t\t\t\tgtk_label_set_text(err, \"Error: \"\n\t\t\t\t\t\"map file not specified.\");\n\t\t\t\tgtk_widget_show_all(GTK_WIDGET(err));\n\t\t\t\tgoto cleanup;\n\t\t\t} \n\t\t\ter = NULL;\n\t\t\tkml = kml_parse(file, &er);\n\t\t\tg_free(file);\n\t\t\tif (NULL == kml) {\n\t\t\t\tfile = g_strdup_printf(\"Error: \"\n\t\t\t\t\t\"bad map file: %s\", \n\t\t\t\t\tNULL != er ? er->message :\n\t\t\t\t\t\"cannot load file\");\n\t\t\t\tgtk_label_set_text(err, file);\n\t\t\t\tgtk_widget_show_all(GTK_WIDGET(err));\n\t\t\t\tg_free(file);\n\t\t\t\tif (NULL != er)\n\t\t\t\t\tg_error_free(er);\n\t\t\t\tgoto cleanup;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase (MAPTOP_RAND):\n\t\t\tislands = gtk_adjustment_get_value\n\t\t\t\t(b->wins.maprandislands);\n\t\t\tislandpop = gtk_adjustment_get_value\n\t\t\t\t(b->wins.maprandislanders);\n\t\t\tkml = kml_rand(islands, islandpop);\n\t\t\tislandpop = islands = 0;\n\t\t\tbreak;\n\t\tcase (MAPTOP_TORUS):\n\t\t\tislands = gtk_adjustment_get_value\n\t\t\t\t(b->wins.maptorusislands);\n\t\t\tislandpop = gtk_adjustment_get_value\n\t\t\t\t(b->wins.maptorusislanders);\n\t\t\tkml = kml_torus(islands, islandpop);\n\t\t\tislandpop = islands = 0;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tabort();\n\t\t}\n\n\t\t/*\n\t\t * Grok our island populations from the input file.\n\t\t * This will have a reasonable default, but make sure\n\t\t * anyway with some assertions.\n\t\t */\n\t\tislands = (size_t)g_list_length(kml->kmls);\n\t\tislandpops = g_malloc0_n(islands, sizeof(size_t));\n\t\tfor (i = 0; i < islands; i++) {\n\t\t\tkmlp = g_list_nth_data(kml->kmls, i);\n\t\t\tislandpops[i] = kmlp->pop;\n\t\t}\n\n\t\t/*\n\t\t * If we're uniformly migrating, then stop processing\n\t\t * right now.\n\t\t * If we're distance-migrating, then have the kml file\n\t\t * set the inter-island migration probabilities.\n\t\t */\n\t\tswitch (migrants) {\n\t\tcase (MAPMIGRANT_UNIFORM):\n\t\t\tms = kml_migration_distance(kml->kmls, maptop);\n\t\t\tbreak;\n\t\tcase (MAPMIGRANT_NEAREST):\n\t\t\tms = kml_migration_nearest(kml->kmls, maptop);\n\t\t\tbreak;\n\t\tcase (MAPMIGRANT_TWONEAREST):\n\t\t\tms = kml_migration_twonearest(kml->kmls, maptop);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\tdefault:\n\t\tabort();\n\t}\n\n\t/*\n\t * Base check: we need at least two islands.\n\t */\n\tif (islands < 2) {\n\t\tgtk_label_set_text(err, \n\t\t\t\"Error: need at least two islands.\");\n\t\tgtk_widget_show_all(GTK_WIDGET(err));\n\t\tgoto cleanup;\n\t}\n\n\tideathmean = gtk_adjustment_get_value(b->wins.ideathmean);\n\n\t/*\n\t * If we have an array of island populations, make sure that\n\t * each has more than two islanders.\n\t * While here, revert to a single island population size if our\n\t * sizes are, in fact, uniform.\n\t * Calculate our total population size as well.\n\t */\n\tif (NULL != islandpops) {\n\t\tg_assert(0 == islandpop);\n\t\tfor (i = 0; i < islands; i++) {\n\t\t\tif (islandpops[i] > 1)\n\t\t\t\tcontinue;\n\t\t\tgtk_label_set_text(err, \"Error: need at \"\n\t\t\t\t\"least two islanders per island.\");\n\t\t\tgtk_widget_show_all(GTK_WIDGET(err));\n\t\t\tgoto cleanup;\n\t\t}\n\t\tfor (totalpop = i = 0; i < islands; i++)\n\t\t\ttotalpop += islandpops[i];\n\n\t\t/* Check for uniformity. */\n\t\tfor (i = 1; i < islands; i++)\n\t\t\tif (islandpops[i] != islandpops[0])\n\t\t\t\tbreak;\n\t\tif (i == islands && 0 == ideathmean) {\n\t\t\tg_debug(\"Reverting to uniform island \"\n\t\t\t\t\"populations: all islands have \"\n\t\t\t\t\"the same (with no death process): \"\n\t\t\t\t\"%zu\", islandpops[0]);\n\t\t\tislandpop = islandpops[0];\n\t\t\tg_free(islandpops);\n\t\t\tislandpops = NULL;\n\t\t}\n\t} \n\t\n\t/*\n\t * Handle uniform island sizes.\n\t * (This isn't part of the conditional above because we might\n\t * set ourselves to be uniform whilst processing.)\n\t */\n\tif (NULL == islandpops && islandpop < 2) {\n\t\tgtk_label_set_text(err, \"Error: need at \"\n\t\t\t\"least two islanders per island.\");\n\t\tgtk_widget_show_all(GTK_WIDGET(err));\n\t\tgoto cleanup;\n\t} else if (NULL == islandpops)\n\t\ttotalpop = islands * islandpop;\n\n\tfor (mutants = 0; mutants < MUTANTS__MAX; mutants++)\n\t\tif (gtk_toggle_button_get_active\n\t\t\t(GTK_TOGGLE_BUTTON(b->wins.mutants[mutants])))\n\t\t\tbreak;\n\n\tif ( ! entry2double(b->wins.xmin, &xmin, err))\n\t\tgoto cleanup;\n\tif ( ! entry2double(b->wins.xmax, &xmax, err))\n\t\tgoto cleanup;\n\tif ( ! entryworder(b->wins.xmin, b->wins.xmax, xmin, xmax, err))\n\t\tgoto cleanup;\n\tymin = xmin;\n\tymax = xmax;\n\tif (MUTANTS_GAUSSIAN == mutants) {\n\t\tif ( ! entry2double(b->wins.ymin, &ymin, err))\n\t\t\tgoto cleanup;\n\t\tif ( ! entry2double(b->wins.ymax, &ymax, err))\n\t\t\tgoto cleanup;\n\t\tif ( ! entryorder(b->wins.ymin, \n\t\t\t\tb->wins.xmin, ymin, xmin, err))\n\t\t\tgoto cleanup;\n\t\tif ( ! entryorder(b->wins.xmax, \n\t\t\t\tb->wins.ymax, xmax, ymax, err))\n\t\t\tgoto cleanup;\n\t\tif ( ! entryworder(b->wins.ymin, \n\t\t\t\tb->wins.ymax, ymin, ymax, err))\n\t\t\tgoto cleanup;\n\t\tif ( ! entry2double(b->wins.mutantsigma, &sigma, err))\n\t\t\tgoto cleanup;\n\t}\n\tif ( ! entry2double(b->wins.alpha, &alpha, err))\n\t\tgoto cleanup;\n\tif ( ! entry2double(b->wins.delta, &delta, err))\n\t\tgoto cleanup;\n\tif ( ! entry2double(b->wins.migrate[input], &m, err))\n\t\tgoto cleanup;\n\tif ( ! entry2size(b->wins.incumbents, &slices, err, 1))\n\t\tgoto cleanup;\n\tif ( ! entry2func(b->wins.func, &exp, err))\n\t\tgoto cleanup;\n\n\tfunc = gtk_entry_get_text(b->wins.func);\n\tname = gtk_entry_get_text(b->wins.name);\n\n\tif ('\\0' == *name)\n\t\tname = \"unnamed\";\n\n\tgtk_widget_hide(GTK_WIDGET(err));\n\n\t/* \n\t * All parameters check out!\n\t * Allocate the simulation now.\n\t */\n\tif (button == b->wins.buttonrange) {\n\t\tif (0 == b->rangeid) {\n\t\t\tg_debug(\"Starting rangefinder\");\n\t\t\tb->rangeid = g_idle_add\n\t\t\t\t((GSourceFunc)on_rangefind_idle, b);\n\t\t} else \n\t\t\tg_debug(\"Re-using rangefinder\");\n\n\t\thnode_free(b->range.exp);\n\t\tif (NULL != islandpops) {\n\t\t\tb->range.n = 0;\n\t\t\tfor (i = 0; i < islands; i++)\n\t\t\t\tb->range.n = islandpops[i] > b->range.n ? \n\t\t\t\t\tislandpops[i] : b->range.n;\n\t\t} else\n\t\t\tb->range.n = islandpop;\n\n\t\tb->range.exp = exp;\n\t\tb->range.alpha = alpha;\n\t\tb->range.delta = delta;\n\t\tb->range.slices = slices;\n\t\tb->range.slicex = b->range.slicey = 0;\n\t\tb->range.piaggr = 0.0;\n\t\tb->range.picount = 0;\n\t\tb->range.pimin = DBL_MAX;\n\t\tb->range.pimax = -DBL_MAX;\n\t\tb->range.xmin = b->range.ymin = xmin;\n\t\tb->range.xmax = b->range.ymax = xmax;\n\t\tif (MUTANTS_GAUSSIAN == mutants) {\n\t\t\tb->range.ymin = ymin;\n\t\t\tb->range.ymax = ymax;\n\t\t}\n\t\texp = NULL;\n\t\tfile = g_strdup_printf\n\t\t\t(\"%s, X=[%g, %g), Y=[%g, %g), n=%zu\",\n\t\t\tfunc, b->range.xmin, b->range.xmax, \n\t\t\tb->range.ymin, b->range.ymax,\n\t\t\tb->range.n);\n\t\tgtk_label_set_text(b->wins.rangefunc, file);\n\t\tg_free(file);\n\n\t\tfile = g_strdup_printf\n\t\t\t(\"%g(1 + %g&#x03c0;)\",\n\t\t\t b->range.alpha, b->range.delta);\n\t\tgtk_label_set_markup(b->wins.rangeparms, file);\n\t\tg_free(file);\n\n\t\tgtk_widget_hide(GTK_WIDGET(b->wins.rangeerrorbox));\n\t\tgtk_widget_set_visible\n\t\t\t(GTK_WIDGET(b->wins.rangefind), TRUE);\n\t\tgoto cleanup;\n\t}\n\n\tsim = g_malloc0(sizeof(struct sim));\n\tsim->dims = slices;\n\tsim->islands = islands;\n\tsim->mutants = mutants;\n\tsim->mutantsigma = sigma;\n\tsim->func = g_strdup(func);\n\tsim->name = g_strdup(name);\n\tsim->fitpoly = gtk_adjustment_get_value(b->wins.fitpoly);\n\tsim->weighted = gtk_toggle_button_get_active(b->wins.weighted);\n\tsim->smoothing = gtk_adjustment_get_value(b->wins.smoothing);\n\tsim->ideathmean = ideathmean;\n\tsim->ideathcoef = idcoef;\n\tsim->kml = kml;\n\tsim->migrant = migrants;\n\tsim->maptop = maptop;\n\tsim->mapindex = mapindex;\n\tif ((sim->mapindexfix = mapindexfix) > sim->islands) {\n\t\tg_debug(\"Clamping map index to %zu\", sim->islands - 1);\n\t\tsim->mapindexfix = sim->islands - 1;\n\t}\n\tg_mutex_init(&sim->hot.mux);\n\tg_cond_init(&sim->hot.cond);\n\n\t/* Source for the fraction of mutants. */\n\tsim->bufs.fractions = kdata_array_alloc(NULL, slices);\n\tg_assert(NULL != sim->bufs.fractions);\n\tsim->bufs.ifractions = kdata_array_alloc(NULL, islands);\n\tg_assert(NULL != sim->bufs.ifractions);\n\tsim->bufs.mutants = kdata_array_alloc(NULL, slices);\n\tg_assert(NULL != sim->bufs.mutants);\n\tsim->bufs.incumbents = kdata_array_alloc(NULL, slices);\n\tg_assert(NULL != sim->bufs.incumbents);\n\tsim->bufs.islands = kdata_array_alloc(NULL, islands);\n\tg_assert(NULL != sim->bufs.islands);\n\tsim->bufs.meanmins = kdata_array_alloc(NULL, slices);\n\tg_assert(NULL != sim->bufs.meanmins);\n\tsim->bufs.mextinctmaxs = kdata_array_alloc(NULL, slices);\n\tg_assert(NULL != sim->bufs.mextinctmaxs);\n\tsim->bufs.iextinctmins = kdata_array_alloc(NULL, slices);\n\tg_assert(NULL != sim->bufs.iextinctmins);\n\tsim->bufs.fitpoly = kdata_array_alloc(NULL, slices);\n\tg_assert(NULL != sim->bufs.fitpoly);\n\tsim->bufs.fitpolybuf = kdata_buffer_alloc(slices);\n\tg_assert(NULL != sim->bufs.fitpolybuf);\n\tsim->bufs.fitpolymins = kdata_array_alloc(NULL, slices);\n\tg_assert(NULL != sim->bufs.fitpolymins);\n\tsim->bufs.meanminqbuf = kdata_array_alloc(NULL, CQUEUESZ);\n\tg_assert(NULL != sim->bufs.meanminqbuf);\n\tsim->bufs.fitminqbuf = kdata_array_alloc(NULL, CQUEUESZ);\n\tg_assert(NULL != sim->bufs.fitminqbuf);\n\n\tfor (i = 0; i < slices; i++) {\n\t\tstrat = xmin + (xmax - xmin) * (i / (double)slices);\n\t\tkdata_array_set(sim->bufs.fractions, i, strat, 0);\n\t\tkdata_array_set(sim->bufs.mutants, i, strat, 0);\n\t\tkdata_array_set(sim->bufs.incumbents, i, strat, 0);\n\t\tkdata_array_set(sim->bufs.meanmins, i, strat, 0);\n\t\tkdata_array_set(sim->bufs.mextinctmaxs, i, strat, 0);\n\t\tkdata_array_set(sim->bufs.iextinctmins, i, strat, 0);\n\t\tkdata_array_set(sim->bufs.fitpoly, i, strat, 0);\n\t\tkdata_array_set(sim->bufs.fitpolymins, i, strat, 0);\n\t}\n\n\tsim->bufs.times = simbuf_alloc\n\t\t(kdata_array_alloc(NULL, stop + 1), stop + 1);\n\tsim->bufs.islandmeans = simbuf_alloc\n\t\t(kdata_mean_alloc(sim->bufs.islands), islands);\n\tsim->bufs.islandstddevs = simbuf_alloc\n\t\t(kdata_stddev_alloc(sim->bufs.islands), islands);\n\tsim->bufs.imeans = simbuf_alloc\n\t\t(kdata_mean_alloc(sim->bufs.ifractions), islands);\n\tsim->bufs.istddevs = simbuf_alloc\n\t\t(kdata_stddev_alloc(sim->bufs.ifractions), islands);\n\tsim->bufs.means = simbuf_alloc\n\t\t(kdata_mean_alloc(sim->bufs.fractions), slices);\n\tsim->bufs.stddevs = simbuf_alloc\n\t\t(kdata_stddev_alloc(sim->bufs.fractions), slices);\n\tsim->bufs.mextinct = simbuf_alloc\n\t\t(kdata_mean_alloc(sim->bufs.mutants), slices);\n\tsim->bufs.iextinct = simbuf_alloc\n\t\t(kdata_mean_alloc(sim->bufs.incumbents), slices);\n\n\t/*\n\t * Conditionally allocate our fitness polynomial structures.\n\t * These are per-simulation as they're only run by one thread at\n\t * any one time during the simulation.\n\t */\n\tif (sim->fitpoly) {\n\t\tsim->work.X = gsl_matrix_alloc\n\t\t\t(sim->dims, sim->fitpoly + 1);\n\t\tsim->work.y = gsl_vector_alloc(sim->dims);\n\t\tsim->work.w = gsl_vector_alloc(sim->dims);\n\t\tsim->work.c = gsl_vector_alloc(sim->fitpoly + 1);\n\t\tsim->work.cov = gsl_matrix_alloc\n\t\t\t(sim->fitpoly + 1, sim->fitpoly + 1);\n\t\tsim->work.work = gsl_multifit_linear_alloc\n\t\t\t(sim->dims, sim->fitpoly + 1);\n\t\tsim->work.coeffs = g_malloc0_n\n\t\t\t(sim->fitpoly + 1, sizeof(double));\n\t}\n\n\tsim->nprocs = gtk_adjustment_get_value(b->wins.nthreads);\n\tsim->totalpop = totalpop;\n\tsim->stop = stop;\n\tsim->alpha = alpha;\n\tsim->colour = b->nextcolour++;\n\tsim->delta = delta;\n\tsim->m = m;\n\tsim->ms = ms;\n\tsim->pop = islandpop;\n\tsim->pops = islandpops;\n\tsim->input = input;\n\tsim->exp = exp;\n\tsim->xmin = xmin;\n\tsim->xmax = xmax;\n\tsim->ymin = ymin;\n\tsim->ymax = ymax;\n\tb->sims = g_list_append(b->sims, sim);\n\tsim_ref(sim, NULL);\n\tsim->threads = g_malloc0_n(sim->nprocs, sizeof(struct simthr));\n\tg_debug(\"%p: Simulation created\", sim);\n\n\t/* Create the simulation threads. */\n\tfor (i = 0; i < sim->nprocs; i++) {\n\t\tsim->threads[i].rank = i;\n\t\tsim->threads[i].sim = sim;\n\t\tsim->threads[i].thread = g_thread_new\n\t\t\t(NULL, simulation, &sim->threads[i]);\n\t}\n\n\t/* Create the simulation window. */\n\tcur = g_malloc0(sizeof(struct curwin));\n\tcur->view = VIEW_MEAN;\n\twindow_init(b, cur, g_list_append(NULL, sim));\n\n\t/* Initialise the name of our simulation. */\n\tdonamefill(&b->wins);\n\treturn;\ncleanup:\n\tif (NULL != ms)\n\t\tfor (i = 0; i < islands; i++)\n\t\t\tg_free(ms[i]);\n\tg_free(islandpops);\n\tg_free(ms);\n\thnode_free(exp);\n\tkml_free(kml);\n}\n", "meta": {"hexsha": "ba4729942773e0b6d57c6a2560957855c4d3febd", "size": 41957, "ext": "c", "lang": "C", "max_stars_repo_path": "simwin.c", "max_stars_repo_name": "kristapsdz/bmigrate", "max_stars_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-03-03T17:13:19.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-03T17:13:19.000Z", "max_issues_repo_path": "simwin.c", "max_issues_repo_name": "kristapsdz/bmigrate", "max_issues_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simwin.c", "max_forks_repo_name": "kristapsdz/bmigrate", "max_forks_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3110661269, "max_line_length": 75, "alphanum_fraction": 0.6923040255, "num_tokens": 13251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10818895168662, "lm_q2_score": 0.014957085303326966, "lm_q1q2_score": 0.0016181913792542952}}
{"text": "// Copyright 2014 The Chromium Authors. All rights reserved.\n// Inspired by Chromium video capture interface\n// Simplified and stripped from internal base code\n\n#ifndef S3D_VIDEO_CAPTURE_VIDEO_CAPTURE_DEVICE_DECKLINK_H\n#define S3D_VIDEO_CAPTURE_VIDEO_CAPTURE_DEVICE_DECKLINK_H\n\n#include <s3d/video/capture/video_capture_device.h>\n#include <s3d/video/capture/video_capture_device_factory.h>\n\n#include <gsl/gsl>\n\n#include <chrono>\n\nnamespace s3d {\n\nclass DecklinkCaptureDelegate;\n\nclass VideoCaptureDeviceDecklink : public VideoCaptureDevice {\n public:\n  explicit VideoCaptureDeviceDecklink(const VideoCaptureDeviceDescriptor& deviceDescriptor);\n\n  gsl::owner<VideoCaptureDevice*> clone() const override;\n\n  ~VideoCaptureDeviceDecklink() override;\n\n  void AllocateAndStart(const VideoCaptureFormat& format,\n                        VideoCaptureDevice::Client* client) override;\n\n  void StopAndDeAllocate() override;\n\n  // called from delegate\n  void OnIncomingCapturedData(const VideoCaptureDevice::Client::Images& images,\n                              const VideoCaptureFormat& frameFormat,\n                              std::chrono::microseconds /*timestamp*/);\n\n  VideoCaptureFormat DefaultFormat() override;\n\n private:\n  VideoCaptureDevice::Client* client_{};\n  std::unique_ptr<DecklinkCaptureDelegate> captureDelegate_;\n};\n\n}  // namespace s3d\n\n#endif  // S3D_VIDEO_CAPTURE_VIDEO_CAPTURE_DEVICE_DECKLINK_H\n", "meta": {"hexsha": "84081849e7b785cd0d3a88ccdf70f22bab5cec45", "size": 1408, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/decklink/include/s3d/video/capture/video_capture_device_decklink.h", "max_stars_repo_name": "hugbed/OpenS3D", "max_stars_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-16T16:38:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-20T03:23:15.000Z", "max_issues_repo_path": "src/core/decklink/include/s3d/video/capture/video_capture_device_decklink.h", "max_issues_repo_name": "hugbed/OpenS3D", "max_issues_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 40.0, "max_issues_repo_issues_event_min_datetime": "2017-04-12T17:24:44.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-21T18:41:23.000Z", "max_forks_repo_path": "src/core/decklink/include/s3d/video/capture/video_capture_device_decklink.h", "max_forks_repo_name": "hugbed/OpenS3D", "max_forks_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-07-13T21:51:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-18T16:22:03.000Z", "avg_line_length": 29.9574468085, "max_line_length": 92, "alphanum_fraction": 0.7670454545, "num_tokens": 298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.0592102540615268, "lm_q2_score": 0.02716922956641336, "lm_q1q2_score": 0.0016086969852832807}}
{"text": "//\n//  Author\n//      luncliff@gmail.com\n//\n#pragma once\n#ifndef _NDCAM_INCLUDE_H_\n#define _NDCAM_INCLUDE_H_\n\n#include <gsl/gsl>\n\n#include <android/hardware_buffer.h>\n#include <android/native_window.h>\n#include <android/native_window_jni.h>\n\n#include <media/NdkImage.h>\n#include <media/NdkImageReader.h>\n\n#include <camera/NdkCameraCaptureSession.h>\n#include <camera/NdkCameraDevice.h>\n#include <camera/NdkCameraError.h>\n#include <camera/NdkCameraManager.h>\n#include <camera/NdkCameraMetadata.h>\n#include <camera/NdkCameraMetadataTags.h>\n#include <camera/NdkCaptureRequest.h>\n\nusing native_window_ptr =\n    std::unique_ptr<ANativeWindow, void (*)(ANativeWindow*)>;\nusing capture_session_output_container_ptr =\n    std::unique_ptr<ACaptureSessionOutputContainer,\n                    void (*)(ACaptureSessionOutputContainer*)>;\nusing capture_session_output_ptr =\n    std::unique_ptr<ACaptureSessionOutput, void (*)(ACaptureSessionOutput*)>;\nusing capture_request_ptr =\n    std::unique_ptr<ACaptureRequest, void (*)(ACaptureRequest*)>;\n\nusing camera_output_target_ptr =\n    std::unique_ptr<ACameraOutputTarget, void (*)(ACameraOutputTarget*)>;\n\n/**\n * Library context. Supports auto releasing and facade for features\n *\n * !!! All NDK type members must be public. There will be no encapsulation !!!\n */\nstruct camera_group_t final {\n    // without external camera, 2 is enough(back + front).\n    // But we will use more since there might be multiple(for now, 2) external\n    // camera...\n    static constexpr auto max_camera_count = 4;\n\n  public:\n    // Android camera manager. After the context is initialized, this must be\n    // non-null if this variable is null, then the context is considered as 'not\n    // initailized' and all operation *can* be ignored\n    ACameraManager* manager = nullptr;\n    ACameraIdList* id_list = nullptr;\n\n    // cached metadata\n    std::array<ACameraMetadata*, max_camera_count> metadata_set{};\n\n    //\n    // even though android system limits the number of maximum open camera\n    // device, we will consider multiple camera are working concurrently.\n    //\n    // if element is nullptr, it means the device is not open.\n    std::array<ACameraDevice*, max_camera_count> device_set{};\n\n    // if there is no session, session pointer will be null\n    std::array<ACameraCaptureSession*, max_camera_count> session_set{};\n\n    // sequence number from capture session\n    std::array<int, max_camera_count> seq_id_set{};\n\n  public:\n    camera_group_t() noexcept = default;\n    // copy-move is disabled\n    camera_group_t(const camera_group_t&) = delete;\n    camera_group_t(camera_group_t&&) = delete;\n    camera_group_t& operator=(const camera_group_t&) = delete;\n    camera_group_t& operator=(camera_group_t&&) = delete;\n    ~camera_group_t() noexcept {\n        this->release(); // ensure release precedure\n    }\n\n  public:\n    void release() noexcept;\n\n  public:\n    auto open_device(uint16_t id,\n                     ACameraDevice_StateCallbacks& callbacks) noexcept\n        -> camera_status_t;\n\n    // Notice that this routine doesn't free metadata\n    void close_device(uint16_t id) noexcept;\n\n    auto start_repeat(\n        uint16_t id, ANativeWindow* window,\n        ACameraCaptureSession_stateCallbacks& on_session_changed,\n        ACameraCaptureSession_captureCallbacks& on_capture_event) noexcept\n        -> camera_status_t;\n    void stop_repeat(uint16_t id) noexcept;\n\n    auto start_capture(\n        uint16_t id, ANativeWindow* window,\n        ACameraCaptureSession_stateCallbacks& on_session_changed,\n        ACameraCaptureSession_captureCallbacks& on_capture_event) noexcept\n        -> camera_status_t;\n    void stop_capture(uint16_t id) noexcept;\n\n    // ACAMERA_LENS_FACING_FRONT\n    // ACAMERA_LENS_FACING_BACK\n    // ACAMERA_LENS_FACING_EXTERNAL\n    uint16_t get_facing(uint16_t id) noexcept;\n};\n\n// device callbacks\n\nvoid context_on_device_disconnected(camera_group_t& context,\n                                    ACameraDevice* device) noexcept;\n\nvoid context_on_device_error(camera_group_t& context, ACameraDevice* device,\n                             int error) noexcept;\n\n// session state callbacks\n\nvoid context_on_session_active(camera_group_t& context,\n                               ACameraCaptureSession* session) noexcept;\n\nvoid context_on_session_closed(camera_group_t& context,\n                               ACameraCaptureSession* session) noexcept;\n\nvoid context_on_session_ready(camera_group_t& context,\n                              ACameraCaptureSession* session) noexcept;\n\n// capture callbacks\n\nvoid context_on_capture_started(camera_group_t& context,\n                                ACameraCaptureSession* session,\n                                const ACaptureRequest* request,\n                                uint64_t time_point) noexcept;\n\nvoid context_on_capture_progressed(camera_group_t& context,\n                                   ACameraCaptureSession* session,\n                                   ACaptureRequest* request,\n                                   const ACameraMetadata* result) noexcept;\n\nvoid context_on_capture_completed(camera_group_t& context,\n                                  ACameraCaptureSession* session,\n                                  ACaptureRequest* request,\n                                  const ACameraMetadata* result) noexcept;\n\nvoid context_on_capture_failed(camera_group_t& context,\n                               ACameraCaptureSession* session,\n                               ACaptureRequest* request,\n                               ACameraCaptureFailure* failure) noexcept;\n\nvoid context_on_capture_buffer_lost(camera_group_t& context,\n                                    ACameraCaptureSession* session,\n                                    ACaptureRequest* request,\n                                    ANativeWindow* window,\n                                    int64_t frame_number) noexcept;\n\nvoid context_on_capture_sequence_abort(camera_group_t& context,\n                                       ACameraCaptureSession* session,\n                                       int sequence_id) noexcept;\n\nvoid context_on_capture_sequence_complete(camera_group_t& context,\n                                          ACameraCaptureSession* session,\n                                          int sequence_id,\n                                          int64_t frame_number) noexcept;\n\n// status - error code to string\n\nauto camera_error_message(camera_status_t status) noexcept -> const char*;\n\n#endif", "meta": {"hexsha": "e9179bd265f527da09432c6228387797af707c41", "size": 6494, "ext": "h", "lang": "C", "max_stars_repo_path": "include/ndk_camera.h", "max_stars_repo_name": "luncliff/NdkCamera", "max_stars_repo_head_hexsha": "85c37ef9ec061280b6aea8ecac9c1b99f2941abd", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2018-10-30T06:09:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-01T13:25:32.000Z", "max_issues_repo_path": "include/ndk_camera.h", "max_issues_repo_name": "jerry-deng-pico/NdkCamera", "max_issues_repo_head_hexsha": "85c37ef9ec061280b6aea8ecac9c1b99f2941abd", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-10-17T15:58:54.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-14T06:33:15.000Z", "max_forks_repo_path": "include/ndk_camera.h", "max_forks_repo_name": "jerry-deng-pico/NdkCamera", "max_forks_repo_head_hexsha": "85c37ef9ec061280b6aea8ecac9c1b99f2941abd", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2019-03-12T09:25:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-30T10:38:06.000Z", "avg_line_length": 37.1085714286, "max_line_length": 80, "alphanum_fraction": 0.6603018171, "num_tokens": 1283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06278920684328233, "lm_q2_score": 0.025565214387284933, "lm_q1q2_score": 0.001605219534156091}}
{"text": "#ifndef TTT_GFX_TEXT_H\n#define TTT_GFX_TEXT_H\n\n#include <SDL_render.h>\n#include <SDL_ttf.h>\n\n#include <gsl/pointers>\n#include <gsl/util>\n\n#include <memory>\n#include <string_view>\n#include <string>\n#include <stdexcept>\n#include <cstdint>\n\nnamespace ttt::gfx\n{\n\tclass TextError final : public std::runtime_error\n\t{\n\tpublic:\n\t\tTextError(const std::string &msg) noexcept;\n\t};\n\n\tinline TextError::TextError(const std::string &msg) noexcept\n\t\t: runtime_error{msg}\n\t{\n\t}\n\n\t// A very simple class for rendering text.\n\tclass Text final\n\t{\n\tpublic:\n\t\tText() = default;\n\t\tText(std::string_view str, gsl::not_null<TTF_Font *> font, const SDL_Colour &colour, bool shadow, gsl::not_null<SDL_Renderer *> renderer);\n\n\t\tvoid setText(std::string_view str, gsl::not_null<TTF_Font *> font, const SDL_Colour &colour, bool shadow, gsl::not_null<SDL_Renderer *> renderer);\n\t\tvoid clear() noexcept;\n\n\t\tvoid render(gsl::not_null<SDL_Renderer *> renderer, const SDL_FPoint &pos, double angle = 0.0, const SDL_FPoint *centre = nullptr, SDL_RendererFlip flip = SDL_FLIP_NONE) const noexcept;\n\n\t\t[[nodiscard]] SDL_Point getSize() const noexcept { return size; }\n\n\tprivate:\n\t\tusing TexturePointer = std::unique_ptr<SDL_Texture, decltype(&SDL_DestroyTexture)>;\n\n\t\tTexturePointer primary{nullptr, SDL_DestroyTexture};\n\t\tTexturePointer secondary{nullptr, SDL_DestroyTexture};\n\t\tSDL_Point size{0, 0};\n\n\t\t[[nodiscard]] TexturePointer createTexture(std::string_view str, gsl::not_null<TTF_Font *> font, const SDL_Colour &colour, gsl::not_null<SDL_Renderer *> renderer);\n\t\t[[nodiscard]] SDL_Colour createShadowColour(const SDL_Colour &colour) const noexcept;\n\t};\n\n\tinline SDL_Colour Text::createShadowColour(const SDL_Colour &colour) const noexcept\n\t{\n\t\treturn {\n\t\t\tgsl::narrow_cast<std::uint8_t>(colour.r % 5),\n\t\t\tgsl::narrow_cast<std::uint8_t>(colour.g % 5),\n\t\t\tgsl::narrow_cast<std::uint8_t>(colour.b % 5),\n\t\t\tcolour.a\n\t\t};\n\t}\n}\n\n#endif", "meta": {"hexsha": "77efc761b40b7c99f1d6c5d57f187ce4c4f22390", "size": 1902, "ext": "h", "lang": "C", "max_stars_repo_path": "Source/Graphics/Text.h", "max_stars_repo_name": "itsArtem/TicTacToe", "max_stars_repo_head_hexsha": "8c70a77e4603dd0ff22ec0621b978ec0685ec3cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Source/Graphics/Text.h", "max_issues_repo_name": "itsArtem/TicTacToe", "max_issues_repo_head_hexsha": "8c70a77e4603dd0ff22ec0621b978ec0685ec3cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/Graphics/Text.h", "max_forks_repo_name": "itsArtem/TicTacToe", "max_forks_repo_head_hexsha": "8c70a77e4603dd0ff22ec0621b978ec0685ec3cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2615384615, "max_line_length": 187, "alphanum_fraction": 0.7376445846, "num_tokens": 520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06853749873974063, "lm_q2_score": 0.023330770973076616, "lm_q1q2_score": 0.0015990326861644159}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n \r\n#ifndef xml_f13c2b07_0230_4967_8a16_0c276e19b8a2_h\r\n#define xml_f13c2b07_0230_4967_8a16_0c276e19b8a2_h\r\n\r\n#include <gslib/std.h>\r\n#include <gslib/tree.h>\r\n\r\n__gslib_begin__\r\n\r\nstruct xml_kvpair { string key, value; };\r\ntypedef xml_kvpair xml_attr;\r\n\r\nstruct xml_key:\r\n    public xml_kvpair\r\n{\r\n    xml_key(const string& k) { key = k; }\r\n    xml_key(const gchar* c) { key.assign(c); }\r\n};\r\n\r\nstruct xml_kvp_hash\r\n{\r\n    size_t operator()(const xml_kvpair& kvp) const\r\n    { return string_hash(kvp.key); }\r\n};\r\n\r\nstruct xml_kvp_equalto\r\n{\r\n    bool operator()(const xml_kvpair& p1, const xml_kvpair& p2) const\r\n    { return p1.key == p2.key; }\r\n};\r\n\r\ntemplate<class _kvpvsl>\r\nstruct xml_kvp_search\r\n{\r\n    static string* find(_kvpvsl& v, const string& k)\r\n    {\r\n        auto i = v.find(xml_key(k));\r\n        return i != v.end() ? &(const_cast<string&>(i->value)) : nullptr;\r\n    }\r\n    static const string* find(const _kvpvsl& v, const string& k)\r\n    {\r\n        auto i = v.find(xml_key(k));\r\n        return i != v.end() ? &(i->value) : nullptr;\r\n    }\r\n};\r\n\r\nstruct __gs_novtable xml_node abstract\r\n{\r\n    typedef unordered_set<xml_kvpair, xml_kvp_hash, xml_kvp_equalto> kvplist;\r\n    typedef kvplist::iterator iterator;\r\n    typedef kvplist::const_iterator const_iterator;\r\n\r\npublic:\r\n    virtual bool is_value() const = 0;\r\n    virtual void add_attribute(const xml_attr& attr) = 0;\r\n    virtual string* get_attribute(const string& k) = 0;\r\n    virtual const string* get_attribute(const string& k) const = 0;\r\n    virtual void set_attribute(const gchar* k, int len1, const gchar* v, int len2) = 0;\r\n    virtual void set_attribute(const string& k, const string& v) = 0;\r\n    virtual int get_attribute_count() const = 0;\r\n    virtual const string& get_name() const = 0;\r\n    virtual void set_name(const gchar* str, int len) = 0;\r\n    virtual string to_string() const = 0;   /* for debug */\r\n\r\npublic:\r\n    string* get_attribute(const gchar* k) { return get_attribute(string(k)); }\r\n    const string* get_attribute(const gchar* k) const { return get_attribute(string(k)); }\r\n    string* get_attribute(const gchar* k, int len) { return get_attribute(string(k, len)); }\r\n    const string* get_attribute(const gchar* k, int len) const { return get_attribute(string(k, len)); }\r\n    bool has_attributes() const { return get_attribute_count() != 0; }\r\n    void set_name(const string& str) { set_name(str.c_str(), str.length()); }\r\n};\r\n\r\nstruct xml_element:\r\n    public xml_node\r\n{\r\n    string      key;\r\n    kvplist     attrlist;\r\n\r\npublic:\r\n    bool is_value() const override { return false; }\r\n    void add_attribute(const xml_attr& attr) override { attrlist.insert(attr); }\r\n    string* get_attribute(const string& k) override { return xml_kvp_search<kvplist>::find(attrlist, k); }\r\n    const string* get_attribute(const string& k) const override { return xml_kvp_search<kvplist>::find(attrlist, k); }\r\n    void set_attribute(const gchar* k, int len1, const gchar* v, int len2) override\r\n    {\r\n        assert(k && v);\r\n        string* vstr = get_attribute(string(k, len1));\r\n        if(vstr) {\r\n            vstr->assign(v, len2);\r\n            return;\r\n        }\r\n        xml_attr attr;\r\n        attr.key.assign(k, len1);\r\n        attr.value.assign(v, len2);\r\n        add_attribute(attr);\r\n    }\r\n    void set_attribute(const string& k, const string& v) override\r\n    {\r\n        string* vstr = get_attribute(k);\r\n        if(vstr) {\r\n            vstr->assign(v);\r\n            return;\r\n        }\r\n        xml_attr attr;\r\n        attr.key = k;\r\n        attr.value = v;\r\n        add_attribute(attr);\r\n    }\r\n    int get_attribute_count() const override { return (int)attrlist.size(); }\r\n    const string& get_name() const override { return key; }\r\n    void set_name(const gchar* str, int len) override { key.assign(str, len); }\r\n    void set_value(const string& v) { __super::set_name(v); }\r\n    kvplist& get_attributes() { return attrlist; }\r\n    const kvplist& const_attributes() const { return attrlist; }\r\n    string to_string() const override;\r\n};\r\n\r\nstruct xml_value:\r\n    public xml_node\r\n{\r\n    string      value;\r\n\r\npublic:\r\n    bool is_value() const override { return true; }\r\n    void add_attribute(const xml_attr& attr) override { assert(!\"error!\"); }\r\n    string* get_attribute(const string& k) override { return nullptr; }\r\n    const string* get_attribute(const string& k) const override { return nullptr; }\r\n    void set_attribute(const gchar* k, int len1, const gchar* v, int len2) override { assert(!\"error!\"); }\r\n    void set_attribute(const string& k, const string& v) override { assert(!\"error!\"); }\r\n    int get_attribute_count() const override { return 0; }\r\n    const string& get_name() const override { return value; }\r\n    void set_name(const gchar* str, int len) override { value.assign(str, len); }\r\n    string to_string() const override;\r\n};\r\n\r\nstruct xml_enum\r\n{\r\n    typedef xml_node::iterator iterator;\r\n    typedef xml_node::const_iterator const_iterator;\r\n\r\n    xml_element*  node;\r\n    iterator    iter;\r\n\r\n    xml_enum(xml_node* n)\r\n    {\r\n        assert(n && !n->is_value());\r\n        node = static_cast<xml_element*>(n);\r\n        iter = node->attrlist.begin();\r\n    }\r\n    xml_enum(xml_node* n, iterator i)\r\n    {\r\n        assert(n && !n->is_value());\r\n        node = static_cast<xml_element*>(n);\r\n        iter = i;\r\n    }\r\n    void rewind(iterator i) { iter = i; }\r\n    const xml_attr& get_attribute() const { return *iter; }\r\n    bool next()\r\n    {\r\n        if(iter == node->attrlist.end())\r\n            return false;\r\n        return ++ iter != node->attrlist.end();\r\n    }\r\n    template<class _lambda>\r\n    void for_each(_lambda lam) { for_each(node->attrlist.end(), lam); }\r\n    template<class _lambda>\r\n    void for_each(iterator end, _lambda lam)\r\n    {\r\n        iterator i = iter;\r\n        for( ; i != end; ++ i)\r\n            lam(*i);\r\n    }\r\n    template<class _lambda>\r\n    void const_for_each(_lambda lam) const { const_for_each(node->attrlist.end(), lam); }\r\n    template<class _lambda>\r\n    void const_for_each(const_iterator end, _lambda lam) const\r\n    {\r\n        const_iterator i = iter;\r\n        for( ; i != end; ++ i)\r\n            lam(*i);\r\n    }\r\n};\r\n\r\nstruct xml_const_enum\r\n{\r\n    typedef xml_node::iterator iterator;\r\n    typedef xml_node::const_iterator const_iterator;\r\n\r\n    const xml_element* node;\r\n    const_iterator  iter;\r\n\r\n    xml_const_enum(const xml_node* n)\r\n    {\r\n        assert(n && !n->is_value());\r\n        node = static_cast<const xml_element*>(n);\r\n        iter = node->attrlist.begin();\r\n    }\r\n    xml_const_enum(const xml_node* n, const_iterator i)\r\n    {\r\n        assert(n && !n->is_value());\r\n        node = static_cast<const xml_element*>(n);\r\n        iter = i;\r\n    }\r\n    void rewind(const_iterator i) { iter = i; }\r\n    const xml_attr& get_attribute() const { return *iter; }\r\n    bool next()\r\n    {\r\n        if(iter == node->attrlist.end())\r\n            return false;\r\n        return ++ iter != node->attrlist.end();\r\n    }\r\n    template<class _lambda>\r\n    void const_for_each(_lambda lam) const { const_for_each(node->attrlist.end(), lam); }\r\n    template<class _lambda>\r\n    void const_for_each(const_iterator end, _lambda lam) const\r\n    {\r\n        const_iterator i = iter;\r\n        for( ; i != end; ++ i)\r\n            lam(*i);\r\n    }\r\n};\r\n\r\ntypedef _treenode_wrapper<xml_node> xml_wrapper;\r\n\r\nclass xmltree:\r\n    public tree<xml_node, xml_wrapper>\r\n{\r\npublic:\r\n    enum encodesys\r\n    {\r\n        encodesys_unknown,\r\n        encodesys_ascii,\r\n        encodesys_mbc,          /* multi-byte compatible */\r\n        encodesys_wstr,         /* wide string */\r\n    };\r\n    enum encode\r\n    {\r\n        encode_unknown,\r\n        encode_ansi,\r\n        encode_gb2312,\r\n        encode_utf8,\r\n        encode_utf16,\r\n    };\r\n    encodesys       _encodesys;\r\n    encode          _encode;\r\n\r\nprotected:\r\n    static const gchar* skip(const gchar* str);\r\n    static const gchar* skip(const gchar* str, const gchar* skp);\r\n    static void replace(string& str, const gchar* s1, const gchar* s2);\r\n    static void filter_entity_reference(string& s);\r\n    static void recover_entity_reference(string& s);\r\n    static void write_attribute(string& str, const gchar* prefix, const xml_attr& attr, const gchar* postfix);\r\n    static void close_write_item(string& str, const gchar* prefix, const xml_node* node, const gchar* postfix);\r\n    static void begin_write_item(string& str, const gchar* prefix, const xml_node* node, const gchar* postfix);\r\n    static void end_write_item(string& str, const gchar* prefix, const xml_node* node, const gchar* postfix);\r\n\r\nprotected:\r\n    const gchar* check_header(const gchar* str, string& version, string& encoding);\r\n    const gchar* read_attribute(const gchar* str, string& k, string& v);\r\n    const gchar* read_item(const gchar* str, iterator p);\r\n    void setup_encoding_info(const string& enc);\r\n    void write_header(string& str) const;\r\n    void write_item(string& str, const_iterator i) const;\r\n\r\npublic:\r\n    xmltree();\r\n    bool load(const gchar* filename);\r\n    bool parse(const gchar* src);\r\n    void output(string& str) const;\r\n    void save(const gchar* filename) const;\r\n    void set_encode(encode enc) { _encode = enc; }\r\n\r\npublic:\r\n    /*\r\n     * Unique path locater\r\n     * It was designed to access the DOM easier by a specified string path.\r\n     * Usage:\r\n     * 1.basically, we use the string \"xx/yy/zz\" to specify a path, which means in current position, find a sub node named \"xx\",\r\n     *   go to the sub node; then find \"yy\", then \"zz\", and so on.\r\n     *   the separator could be \"/\", or backslash \"\\\", as well.\r\n     * 2.about the name selector \"$\".\r\n     *   you might also write the path as \"$xx/$yy/$zz\", it was the same as above; the selector \"$\" was skippable.\r\n     * 3.about the counter \"@\"\r\n     *   you could add a counter into the path, like \"$xx@3/yy/zz\", in this case, the selector \"$\" was unskippable.\r\n     *   you could make a nameless selection, like \"$@3/yy/zz\", which means in the first jump, it would always choose the third node.\r\n     *   or simply wrote \"$/yy/zz\", which means it would always choose the first node in the first jump.\r\n     * 4.about the condition specifier \"#\"\r\n     *   you could add a condition content into the selector;\r\n     *   a condition was defined like: \"$xx#aa,bb=cc,!dd|!ee,ff~=gg\",\r\n     *   there were two major binary connectors of conditions, \",\" refer to logic \"AND\", and \"|\" refer to logic \"OR\";\r\n     *   the priority of \"OR\" was higher than \"AND\".\r\n     *   if you need a negative condition, use \"!\" to reverse the logic, and the \"!\" should always follow \"|\"\r\n     *   if a condition content was like the above \"aa\", which means the selected node must have the attribute named \"aa\"\r\n     *   if a condition content was wrote like \"bb=cc\", which means the selected node must have an attribute named \"bb\" and valued \"cc\"\r\n     *   if a condition content was wrote like \"ff~=gg\", which means the selected node must have an attribute named \"ff\" and valued \"gg\",\r\n     *   the comparison was case insensitive.\r\n     * 5.the \"$\", \"@\", \"#\" could be used as a combo, and the announcement should always be in the specified order, $#@\r\n     */\r\n    iterator unique_path_locater(const gchar* ctlstr) { return unique_path_locater(get_root(), ctlstr); }\r\n    static iterator unique_path_locater(iterator i, const gchar* ctlstr)\r\n    {\r\n        assert(ctlstr);\r\n        string cpyctlstr(ctlstr);\r\n        ctlstr = cpyctlstr.c_str(); /* for trap */\r\n        ctlstr = upl_run_over(i, ctlstr);\r\n        if(ctlstr && !ctlstr[0])\r\n            return i;\r\n        return iterator(nullptr);\r\n    }\r\n\r\npublic:\r\n    static const gchar* upl_run_once(iterator& i, const gchar* ctlstr);\r\n    static const gchar* upl_run_over(iterator& i, const gchar* ctlstr)\r\n    {\r\n        while(ctlstr && ctlstr[0]) {\r\n            const gchar* ctlret = upl_run_once(i, ctlstr);\r\n            if(!ctlret)\r\n                return ctlstr;\r\n            ctlstr = ctlret;\r\n        }\r\n        return ctlstr;\r\n    }\r\n};\r\n\r\n__gslib_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "c7eb1fad48b07b08d580926818c2aad14fdb4f79", "size": 13349, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gslib/xml.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/gslib/xml.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gslib/xml.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 37.4971910112, "max_line_length": 138, "alphanum_fraction": 0.6360776088, "num_tokens": 3281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.051845462254755746, "lm_q2_score": 0.030675805033796792, "lm_q1q2_score": 0.001590401292013958}}
{"text": "#pragma once\n\n#include \"Core/Assert.h\"\n#include \"Core/Delegate.h\"\n#include \"Core/Pointers.h\"\n#include \"Scene/Components/Component.h\"\n\n#include <gsl/span>\n\n#include <string>\n#include <utility>\n#include <vector>\n\nclass Scene;\n\nclass Entity\n{\npublic:\n   using OnDestroyDelegate = MulticastDelegate<void, Entity*>;\n\n   ~Entity();\n\n   void destroy();\n\n   void tick(float dt);\n\n   template<typename T>\n   T* createComponent();\n\n   Component* createComponentByName(const std::string& className);\n   bool destroyComponent(Component* componentToDestroy);\n\n   template<typename T>\n   T* getComponentByClass();\n\n   template<typename T>\n   const T* getComponentByClass() const;\n\n   template<typename T>\n   std::vector<T*> getComponentsByClass();\n\n   template<typename T>\n   std::vector<const T*> getComponentsByClass() const;\n\n   DelegateHandle addOnDestroyDelegate(OnDestroyDelegate::FuncType&& function);\n   void removeOnDestroyDelegate(const DelegateHandle& handle);\n\n   Scene& getScene()\n   {\n      return scene;\n   }\n\n   const Scene& getScene() const\n   {\n      return scene;\n   }\n\nprivate:\n   friend class Scene;\n\n   template<typename... ComponentTypes>\n   static UPtr<Entity> create(Scene& scene);\n\n   static UPtr<Entity> create(gsl::span<std::string> componentClassNames, Scene& scene);\n\n   Entity(Scene& owningScene)\n      : scene(owningScene)\n   {\n   }\n\n   template<typename First, typename... Rest>\n   void constructComponentsHelper();\n\n   template<typename... ComponentTypes>\n   void constructComponents();\n\n   void onInitialized();\n   void onComponentCreated(Component* component);\n\n   std::vector<UPtr<Component>> components;\n   OnDestroyDelegate onDestroyDelegate;\n   Scene& scene;\n};\n\ntemplate<typename T>\nT* Entity::createComponent()\n{\n   UPtr<T> newComponent = ComponentRegistry::instance().createComponent<T>(*this);\n   ASSERT(newComponent, \"Failed to create a typed component\");\n\n   T* newComponentRaw = newComponent.get();\n   components.push_back(std::move(newComponent));\n   onComponentCreated(newComponentRaw);\n   return newComponentRaw;\n}\n\ntemplate<typename T>\nT* Entity::getComponentByClass()\n{\n   for (const UPtr<Component>& component : components)\n   {\n      if (T* castedComponent = dynamic_cast<T*>(component.get()))\n      {\n         return castedComponent;\n      }\n   }\n\n   return nullptr;\n}\n\ntemplate<typename T>\nconst T* Entity::getComponentByClass() const\n{\n   for (const UPtr<Component>& component : components)\n   {\n      if (const T* castedComponent = dynamic_cast<const T*>(component.get()))\n      {\n         return castedComponent;\n      }\n   }\n\n   return nullptr;\n}\n\ntemplate<typename T>\nstd::vector<T*> Entity::getComponentsByClass()\n{\n   std::vector<T*> componentsOfClass;\n\n   for (const UPtr<Component>& component : components)\n   {\n      if (T* castedComponent = dynamic_cast<T*>(component.get()))\n      {\n         componentsOfClass.push_back(castedComponent);\n      }\n   }\n\n   return componentsOfClass;\n}\n\ntemplate<typename T>\nstd::vector<const T*> Entity::getComponentsByClass() const\n{\n   std::vector<const T*> componentsOfClass;\n\n   for (const UPtr<Component>& component : components)\n   {\n      if (const T* castedComponent = dynamic_cast<const T*>(component.get()))\n      {\n         componentsOfClass.push_back(castedComponent);\n      }\n   }\n\n   return componentsOfClass;\n}\n\n// static\ntemplate<typename... ComponentTypes>\nUPtr<Entity> Entity::create(Scene& scene)\n{\n   UPtr<Entity> entity(new Entity(scene));\n\n   entity->constructComponents<ComponentTypes...>();\n   entity->onInitialized();\n\n   return entity;\n}\n\ntemplate<typename First, typename... Rest>\nvoid Entity::constructComponentsHelper()\n{\n   components.push_back(ComponentRegistry::instance().createComponent<First>(*this));\n   constructComponents<Rest...>();\n}\n\ntemplate<typename... ComponentTypes>\nvoid Entity::constructComponents()\n{\n   constructComponentsHelper<ComponentTypes...>();\n}\n\ntemplate<>\ninline void Entity::constructComponents()\n{\n}\n", "meta": {"hexsha": "9827b70e00864fd502deb8bdc052a64b254922ea", "size": 3945, "ext": "h", "lang": "C", "max_stars_repo_path": "Source/Scene/Entity.h", "max_stars_repo_name": "aaronmjacobs/Swap", "max_stars_repo_head_hexsha": "955f36bc95b6829bf1a1a89b430df7816c065ac0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Source/Scene/Entity.h", "max_issues_repo_name": "aaronmjacobs/Swap", "max_issues_repo_head_hexsha": "955f36bc95b6829bf1a1a89b430df7816c065ac0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/Scene/Entity.h", "max_forks_repo_name": "aaronmjacobs/Swap", "max_forks_repo_head_hexsha": "955f36bc95b6829bf1a1a89b430df7816c065ac0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.2096774194, "max_line_length": 88, "alphanum_fraction": 0.6986058302, "num_tokens": 868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.0769608272276531, "lm_q2_score": 0.020645931454798015, "lm_q1q2_score": 0.0015889279636466787}}
{"text": "/*\n  Copyright [2020] [IBM Corporation]\n  Licensed under the Apache License, Version 2.0 (the \"License\");\n  you may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n  http://www.apache.org/licenses/LICENSE-2.0\n  Unless required by applicable law or agreed to in writing, software\n  distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions and\n  limitations under the License.\n*/\n\n#ifndef MCAS_CCPM_LOG_H__\n#define MCAS_CCPM_LOG_H__\n\n#include <ccpm/interfaces.h>\n#include <gsl/pointers>\n#include <cstring>\n#include <cstddef>\n\nnamespace ccpm\n{\nstruct block_header;\n\nstruct log\n  : public ILog\n{\n  using heap_type = gsl::not_null<IHeap_expandable *>;\n  using persister_type = gsl::not_null<ccpm::persister *>;\nprivate:\n  /*\n   * The log needs to be stored persistently, and to use persistent storage.\n   * Use persister_type for the former and heap_type for the latter.\n   */\n  persister_type _persister; // not owned\n  heap_type _mr; // not owned\n  /* The log needs a root */\n  block_header *_root; // owned\n  void clear_top();\n\n  static constexpr size_t min_log_extend = std::size_t(65536U);\n\n  void extend(std::size_t size);\npublic:\n  explicit log(persister_type, heap_type mr_);\n\n  log(const log &) = delete;\n  log &operator=(const log &) = delete;\n  /*\n   * Restoration of a log from persistent memory is done by moving the\n   * log to itself with a move constructor. The persisted log has a vft\n   * pointer, which is invalid when the log is rediscovered in persistent\n   * memory. The move constructor creates valid vft pointer and (we hope)\n   * preserves the rest of the log member data.\n   */\n  log(log &&) = default;\n  log(log &&other, persister_type, heap_type);\n\n  ~log();\n  /*\n   * Make a record of an old value\n   */\n  void add(void *begin, std::size_t size) override;\n  /*\n   * Make a record of an allocate\n   */\n  void allocated(void *&p, std::size_t size) override;\n  /*\n   * Make a record of a free\n   */\n  void freed(void *&p, std::size_t size) override;\n  /*\n   * commit and discard all log entries\n   */\n  void commit() override;\n  /*\n   * Restore all data areas added after initialization (or the most recent clear)\n   * to the values present at their last add command.\n   */\n  void rollback() override;\n\n  bool includes(const void *addr) const { return _mr->includes(addr); }\n};\n\nstruct bad_alloc_log\n\t: public std::bad_alloc\n{\n\tbad_alloc_log()\n\t{}\n\tconst char *what() const noexcept override\n\t{\n\t\treturn \"bad undo log allocate\";\n\t}\n};\n\n}\n#endif\n", "meta": {"hexsha": "07578156a99aaaeef9858ae9c37006376707e5b6", "size": 2667, "ext": "h", "lang": "C", "max_stars_repo_path": "src/lib/libccpm/include/ccpm/log.h", "max_stars_repo_name": "omriarad/mcas", "max_stars_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 60.0, "max_stars_repo_stars_event_min_datetime": "2020-04-28T08:15:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T10:35:15.000Z", "max_issues_repo_path": "src/lib/libccpm/include/ccpm/log.h", "max_issues_repo_name": "omriarad/mcas", "max_issues_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 66.0, "max_issues_repo_issues_event_min_datetime": "2020-09-03T23:40:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T20:34:52.000Z", "max_forks_repo_path": "src/lib/libccpm/include/ccpm/log.h", "max_forks_repo_name": "omriarad/mcas", "max_forks_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2019-11-02T06:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T01:56:42.000Z", "avg_line_length": 26.9393939394, "max_line_length": 81, "alphanum_fraction": 0.7052868391, "num_tokens": 678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07921031976169719, "lm_q2_score": 0.02002343997366392, "lm_q1q2_score": 0.0015860630830430687}}
{"text": "\n#if !defined(REGEXMOVE_H_INCLUDED)\n#define REGEXMOVE_H_INCLUDED\n\n#include \"Utils.h\"\n\n#include <filesystem>\n#include <gsl/gsl>\n#include <iosfwd>\n#include <regex>\n#include <string>\n\nclass RegExMove\n{\npublic:\n\tstatic int usage(::std::ostream& strm, const ::std::string& progName,\n\t\tconst char* pMsg);\n\n\tRegExMove(::gsl::span<const char*const> args);\n\tint run() const;\n\n\tRegExMove(const RegExMove&) = delete;\n\tRegExMove& operator=(const RegExMove&) = delete;\n\tRegExMove(RegExMove&&) = delete;\n\tRegExMove& operator=(RegExMove&&) = delete;\n\nPRIVATE_EXCEPT_IN_TEST:\n\tusing Path = ::std::filesystem::path;\n\tusing DirEntry = ::std::filesystem::directory_entry;\n\n\ttemplate <typename DirIter> void processDirectoryEntries() const;\n\tvoid processDirectoryEntry(DirEntry const& dirEntry) const;\n\tvoid renamePath(Path const& p) const;\n\n\tbool\t\t\t\tm_caseSensitive;\n\tbool\t\t\t\tm_renameDirectories;\n\tbool\t\t\t\tm_renameFiles;\n\tbool\t\t\t\tm_recursiveSearch;\n\tbool\t\t\t\tm_verboseOutput;\n\tbool\t\t\t\tm_allowOverwriteOnNameCollision;\n\tPath\t\t\t\tm_rootDir;\n\t::std::string\tm_patternStr;\n\t::std::regex\tm_pattern;\n\t::std::string\tm_replacement;\n};\n\n#endif // REGEXMOVE_H_INCLUDED\n", "meta": {"hexsha": "b566678d3d32a9458160a27aca1ecec0b61e2985", "size": 1137, "ext": "h", "lang": "C", "max_stars_repo_path": "RegExMove.h", "max_stars_repo_name": "IanEmmons/CmdLineUtil", "max_stars_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RegExMove.h", "max_issues_repo_name": "IanEmmons/CmdLineUtil", "max_issues_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RegExMove.h", "max_forks_repo_name": "IanEmmons/CmdLineUtil", "max_forks_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.6875, "max_line_length": 70, "alphanum_fraction": 0.7405452946, "num_tokens": 303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09947022456038584, "lm_q2_score": 0.015906388708675986, "lm_q1q2_score": 0.0015822120567967862}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef scenegraph_979fc7df_3f68_4a38_9dea_5eed6d400c98_h\r\n#define scenegraph_979fc7df_3f68_4a38_9dea_5eed6d400c98_h\r\n\r\n#include <gslib/type.h>\r\n#include <gslib/tree.h>\r\n#include <ariel/config.h>\r\n\r\n__ariel_begin__\r\n\r\nclass scene_node\r\n{\r\npublic:\r\n    //typedef gs::string string;\r\n    typedef const string* sntype;\r\n    typedef void* snptr;\r\n    typedef snptr (*fnaccess)(int);\r\n    typedef void (*fndestroy)(snptr);\r\n\r\nprotected:\r\n    sntype          _tag;\r\n    snptr           _ptr;\r\n    string          _key;\r\n    fndestroy       _del;\r\n\r\npublic:\r\n    /* sntype declaration */\r\n#define declare_sntype(snt) \\\r\n    static sntype snt;\r\n#include <ariel\\snt.h>\r\n#undef declare_sntype\r\n\r\n    static void register_sntypes();\r\n\r\npublic:\r\n    scene_node() { reset(); }\r\n    scene_node(const gchar* name)\r\n    {\r\n        reset();\r\n        set_key(name);\r\n    }\r\n    scene_node(const gchar* name, sntype tag, snptr ptr, fndestroy del = 0)\r\n    {\r\n        set_key(name);\r\n        bind(tag, ptr, del);\r\n    }\r\n    ~scene_node()\r\n    {\r\n        destroy();\r\n        reset();\r\n    }\r\n    void reset()\r\n    {\r\n        _tag = sn_void;\r\n        _ptr = 0;\r\n        _del = 0;\r\n    }\r\n    void destroy() { if(_ptr && _del) _del(_ptr); }\r\n    sntype get_type() const { return _tag; }\r\n    snptr get_ptr() const { return _ptr; }\r\n    const gchar* get_name() const { return _key.c_str(); }\r\n    const string& get_key() const { return _key; }\r\n    void set_destroy(fndestroy del) { _del = del; }\r\n    void set_nodestroy() { set_destroy(0); }\r\n    void set_key(const gchar* key) { _key.assign(key); }\r\n    void bind(sntype tag, snptr ptr, fndestroy del = 0)\r\n    {\r\n        _tag = tag;\r\n        _ptr = ptr;\r\n        set_destroy(del);\r\n    }\r\n    void rebind(sntype tag, snptr ptr, fndestroy del = 0)\r\n    {\r\n        destroy();\r\n        bind(tag, ptr, del);\r\n    }\r\n    scene_node& operator=(const scene_node& that)\r\n    {\r\n        _tag = that._tag;\r\n        _ptr = that._ptr;\r\n        _key = that._key;\r\n        _del = that._del;\r\n        const_cast<scene_node&>(that)._del = 0;\r\n        return *this;\r\n    }\r\n};\r\n\r\nstruct scene_key\r\n{\r\n    const gchar*    _key;\r\n    scene_key() { _key = 0; }\r\n    scene_key(const gchar* k) { _key = k; }\r\n    scene_key(const scene_node* n) { _key = n->get_name(); }\r\n};\r\n\r\nclass scene_graph\r\n{\r\npublic:\r\n    struct snkey_hash\r\n    {\r\n        size_t operator()(const scene_key& key) const\r\n        { return string_hash(key._key); }\r\n    };\r\n    struct snkey_equal\r\n    {\r\n        bool operator()(const scene_key& k1, const scene_key& k2) const\r\n        { return string_hash(k1._key) == string_hash(k2._key); }\r\n    };\r\n\r\n    typedef tree<scene_node> sntree;\r\n    typedef sntree::wrapper wrapper;\r\n    typedef sntree::iterator iterator;\r\n    typedef sntree::const_iterator const_iterator;\r\n    typedef unordered_map<scene_key, scene_node*, snkey_hash, snkey_equal> sntable;\r\n    typedef scene_node::sntype sntype;\r\n    typedef scene_node::snptr snptr;\r\n    typedef scene_node::fndestroy fndestroy;\r\n\r\npublic:\r\n    template<class castop, int bias, class castp>\r\n    static castop fbop_cast(castp ptr) { return ptr ? reinterpret_cast<castop>(((int)ptr) + bias) : 0; }\r\n    template<class castop, class castp>\r\n    static castop fbop_cast(castp ptr, int bias) { return ptr ? reinterpret_cast<castop>(((int)ptr) + bias) : 0; }\r\n    static int wrapper_node_bias()\r\n    {\r\n        static wrapper inst;\r\n        static const int bias = (int)&inst - ((int)inst.get_ptr());\r\n        return bias;\r\n    }\r\n    static wrapper* node_to_wrapper(scene_node* ptr) { return fbop_cast<wrapper*>(ptr, -wrapper_node_bias()); }\r\n    static const wrapper* node_to_wrapper(const scene_node* ptr) { return fbop_cast<const wrapper*>(ptr, -wrapper_node_bias()); }\r\n    static scene_node* iter_to_node(iterator i) { return i.get_ptr(); }\r\n    static const scene_node* iter_to_node(const_iterator i) { return i.get_ptr(); }\r\n    static iterator node_to_iter(scene_node* ptr) { return iterator(node_to_wrapper(ptr)); }\r\n    static const_iterator node_to_iter(const scene_node* ptr) { return const_iterator(node_to_wrapper(ptr)); }\r\n\r\npublic:\r\n    scene_graph();\r\n    virtual ~scene_graph() {}\r\n\r\npublic:\r\n    scene_node* get_root_node() { return iter_to_node(_sntree.get_root()); }\r\n    const scene_node* get_root_node() const { return iter_to_node(_sntree.get_root()); }\r\n    bool is_node_attached(const scene_node* node) const { return node && _sntree.is_mine(node_to_iter(node)); }\r\n    sntree* get_node_tree(const scene_node* node);\r\n    const sntree* get_node_tree(const scene_node* node) const;\r\n    void fix_node(scene_node* old, scene_node* new1);\r\n    void map_node(scene_node* node, const gchar* name);\r\n    void unmap_node(scene_node* node);\r\n\r\npublic:\r\n    virtual scene_node* create_node(sntype tag = scene_node::sn_void, snptr ptr = 0, fndestroy del = 0);\r\n    virtual scene_node* create_node(const gchar* name, sntype tag = scene_node::sn_void, snptr ptr = 0, fndestroy del = 0);\r\n    virtual scene_node* attach_node(scene_node* parent, scene_node* node);\r\n    virtual scene_node* detach_node(scene_node* node);\r\n    virtual void destroy_node(scene_node* node);\r\n    virtual void clear_miscs();\r\n\r\nprotected:\r\n    sntree          _sntree;\r\n    sntree          _miscs;\r\n    sntable         _sntable;\r\n};\r\n\r\n__ariel_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "d3e8582e32f58d4fb534141a328c990b670934fa", "size": 6591, "ext": "h", "lang": "C", "max_stars_repo_path": "include/ariel/scenemgr.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/ariel/scenemgr.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ariel/scenemgr.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 33.9742268041, "max_line_length": 130, "alphanum_fraction": 0.6536185708, "num_tokens": 1709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06371499425196533, "lm_q2_score": 0.024798157898303943, "lm_q1q2_score": 0.0015800144879497644}}
{"text": "#ifndef SQ_INCLUDE_GUARD_core_SharedRange_h_\n#define SQ_INCLUDE_GUARD_core_SharedRange_h_\n\n#include <gsl/gsl>\n#include <memory>\n#include <range/v3/range/concepts.hpp>\n#include <vector>\n\nnamespace sq {\n\ntemplate <typename R> requires ranges::cpp20::range<R> struct SharedRange {\npublic:\n  explicit SharedRange(const std::shared_ptr<R> &base) : base_{base} {}\n\n  explicit SharedRange(std::shared_ptr<R> &&base) : base_{std::move(base)} {}\n\n  constexpr SharedRange() noexcept = default;\n  SharedRange(const SharedRange &) noexcept = default;\n  SharedRange(SharedRange &&) noexcept = default;\n  SharedRange &operator=(const SharedRange &) noexcept = default;\n  SharedRange &operator=(SharedRange &&) noexcept = default;\n  ~SharedRange() noexcept = default;\n\n  auto begin() {\n    Expects(base_ != nullptr);\n    return ranges::begin(*base_);\n  }\n  auto end() {\n    Expects(base_ != nullptr);\n    return ranges::end(*base_);\n  }\n\nprivate:\n  // views must be semiregular, which means that SharedRange must have a\n  // default constructor, which, unfortunately, means that we can't use\n  // gsl::not_null here.\n  std::shared_ptr<R> base_ = nullptr;\n};\n\n} // namespace sq\n\nnamespace ranges {\n\ntemplate <typename R>\ninline constexpr bool enable_view<sq::SharedRange<R>> = true;\n\n} // namespace ranges\n\nnamespace sq {\n\nstatic_assert(ranges::cpp20::range<SharedRange<std::vector<int>>>);\nstatic_assert(ranges::cpp20::view<SharedRange<std::vector<int>>>);\nstatic_assert(ranges::viewable_range<SharedRange<std::vector<int>>>);\n\n} // namespace sq\n\n#endif // SQ_INCLUDE_GUARD_core_SharedRange_h_\n", "meta": {"hexsha": "f01b92d08f1f38027e5fa18d3a0b9389b83c4783", "size": 1579, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/include/core/SharedRange.h", "max_stars_repo_name": "jonathanhaigh/sq", "max_stars_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-12T16:21:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-12T16:21:41.000Z", "max_issues_repo_path": "src/core/include/core/SharedRange.h", "max_issues_repo_name": "jonathanhaigh/sq", "max_issues_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 44.0, "max_issues_repo_issues_event_min_datetime": "2021-02-08T19:17:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-05T18:51:38.000Z", "max_forks_repo_path": "src/core/include/core/SharedRange.h", "max_forks_repo_name": "jonathanhaigh/sq", "max_forks_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.224137931, "max_line_length": 77, "alphanum_fraction": 0.7283090564, "num_tokens": 392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06954175029096782, "lm_q2_score": 0.022629199621073806, "lm_q1q2_score": 0.0015736741493331782}}
{"text": "#pragma once\n\n#include \"Cesium3DTiles/BoundingVolume.h\"\n#include \"Cesium3DTiles/Library.h\"\n#include \"Cesium3DTiles/Tile.h\"\n#include \"Cesium3DTiles/TileContext.h\"\n#include \"Cesium3DTiles/TileID.h\"\n#include \"Cesium3DTiles/TileRefine.h\"\n\n#include <gsl/span>\n#include <spdlog/fwd.h>\n\n#include <cstddef>\n#include <memory>\n\nnamespace Cesium3DTiles {\n/**\n * @brief The information that is passed to a {@link TileContentLoader} to\n * create a {@link TileContentLoadResult}.\n *\n * For many types of tile content, only the `data` field is required. The other\n * members are used for content that can generate child tiles, like external\n * tilesets or composite tiles. These members are usually initialized from\n * the corresponding members of the {@link Tile} that the content belongs to.\n */\nstruct CESIUM3DTILES_API TileContentLoadInput {\n\n  /**\n   * @brief Creates a new, uninitialized instance for the given tile.\n   *\n   * The `data`, `contentType` and `url` will have default values,\n   * and have to be initialized before this instance is passed to\n   * one of the loader functions.\n   *\n   * @param pLogger_ The logger that will be used\n   * @param tile_ The {@link Tile} that the content belongs to\n   */\n  TileContentLoadInput(\n      const std::shared_ptr<spdlog::logger> pLogger_,\n      const Tile& tile_)\n      : pLogger(pLogger_),\n        data(),\n        contentType(),\n        url(),\n        tileID(tile_.getTileID()),\n        tileBoundingVolume(tile_.getBoundingVolume()),\n        tileContentBoundingVolume(tile_.getContentBoundingVolume()),\n        tileRefine(tile_.getRefine()),\n        tileGeometricError(tile_.getGeometricError()),\n        tileTransform(tile_.getTransform()) {}\n\n  /**\n   * @brief Creates a new instance for the given tile.\n   *\n   * @param pLogger_ The logger that will be used\n   * @param data_ The actual data that the tile content will be created from\n   * @param contentType_ The content type, if the data was received via a\n   * network response\n   * @param url_ The URL that the data was loaded from\n   * @param tile_ The {@link Tile} that the content belongs to\n   */\n  TileContentLoadInput(\n      const std::shared_ptr<spdlog::logger> pLogger_,\n      const gsl::span<const std::byte>& data_,\n      const std::string& contentType_,\n      const std::string& url_,\n      const Tile& tile_)\n      : pLogger(pLogger_),\n        data(data_),\n        contentType(contentType_),\n        url(url_),\n        tileID(tile_.getTileID()),\n        tileBoundingVolume(tile_.getBoundingVolume()),\n        tileContentBoundingVolume(tile_.getContentBoundingVolume()),\n        tileRefine(tile_.getRefine()),\n        tileGeometricError(tile_.getGeometricError()),\n        tileTransform(tile_.getTransform()) {}\n\n  /**\n   * @brief Creates a new instance.\n   *\n   * For many types of tile content, only the `data` field is required. The\n   * other parameters are used for content that can generate child tiles, like\n   * external tilesets or composite tiles.\n   *\n   * @param pLogger_ The logger that will be used\n   * @param data_ The actual data that the tile content will be created from\n   * @param contentType_ The content type, if the data was received via a\n   * network response\n   * @param url_ The URL that the data was loaded from\n   * @param context_ The {@link TileContext}\n   * @param tileID_ The {@link TileID}\n   * @param tileBoundingVolume_ The tile {@link BoundingVolume}\n   * @param tileContentBoundingVolume_ The tile content {@link BoundingVolume}\n   * @param tileRefine_ The {@link TileRefine} strategy\n   * @param tileGeometricError_ The geometric error of the tile\n   * @param tileTransform_ The tile transform\n   */\n  TileContentLoadInput(\n      const std::shared_ptr<spdlog::logger> pLogger_,\n      const gsl::span<const std::byte>& data_,\n      const std::string& contentType_,\n      const std::string& url_,\n      const TileID& tileID_,\n      const BoundingVolume& tileBoundingVolume_,\n      const std::optional<BoundingVolume>& tileContentBoundingVolume_,\n      TileRefine tileRefine_,\n      double tileGeometricError_,\n      const glm::dmat4& tileTransform_)\n      : pLogger(pLogger_),\n        data(data_),\n        contentType(contentType_),\n        url(url_),\n        tileID(tileID_),\n        tileBoundingVolume(tileBoundingVolume_),\n        tileContentBoundingVolume(tileContentBoundingVolume_),\n        tileRefine(tileRefine_),\n        tileGeometricError(tileGeometricError_),\n        tileTransform(tileTransform_) {}\n\n  /**\n   * @brief The logger that receives details of loading errors and warnings.\n   */\n  std::shared_ptr<spdlog::logger> pLogger;\n\n  /**\n   * @brief The raw input data.\n   *\n   * The {@link TileContentFactory} will try to determine the type of the\n   * data using the first four bytes (i.e. the \"magic header\"). If this\n   * does not succeed, it will try to determine the type based on the\n   * `contentType` field.\n   */\n  gsl::span<const std::byte> data;\n\n  /**\n   * @brief The content type.\n   *\n   * If the data was obtained via a HTTP response, then this will be\n   * the `Content-Type` of that response. The {@link TileContentFactory}\n   * will try to interpret the data based on this content type.\n   *\n   * If the data was not directly obtained from an HTTP response, then\n   * this may be the empty string.\n   */\n  std::string contentType;\n\n  /**\n   * @brief The source URL.\n   */\n  std::string url;\n\n  /**\n   * @brief The {@link TileID}.\n   */\n  TileID tileID;\n\n  /**\n   * @brief The tile {@link BoundingVolume}.\n   */\n  BoundingVolume tileBoundingVolume;\n\n  /**\n   * @brief Tile content {@link BoundingVolume}.\n   */\n  std::optional<BoundingVolume> tileContentBoundingVolume;\n\n  /**\n   * @brief The {@link TileRefine}.\n   */\n  TileRefine tileRefine;\n\n  /**\n   * @brief The geometric error.\n   */\n  double tileGeometricError;\n\n  /**\n   * @brief The tile transform\n   */\n  glm::dmat4 tileTransform;\n};\n} // namespace Cesium3DTiles\n", "meta": {"hexsha": "215ebd26dfba6d8db39030d49c7eaea2336b7b40", "size": 5905, "ext": "h", "lang": "C", "max_stars_repo_path": "Cesium3DTiles/include/Cesium3DTiles/TileContentLoadInput.h", "max_stars_repo_name": "TJKoury/cesium-native", "max_stars_repo_head_hexsha": "b824699d3dd9503a5943007247f683b6adc132d4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-27T04:47:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-27T04:47:23.000Z", "max_issues_repo_path": "Cesium3DTiles/include/Cesium3DTiles/TileContentLoadInput.h", "max_issues_repo_name": "MAPSWorks/cesium-native", "max_issues_repo_head_hexsha": "18a295f47b3118cc2edfc22354d93b938a68069c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cesium3DTiles/include/Cesium3DTiles/TileContentLoadInput.h", "max_forks_repo_name": "MAPSWorks/cesium-native", "max_forks_repo_head_hexsha": "18a295f47b3118cc2edfc22354d93b938a68069c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0923913043, "max_line_length": 79, "alphanum_fraction": 0.6851820491, "num_tokens": 1458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07055959032390027, "lm_q2_score": 0.02228618326640245, "lm_q1q2_score": 0.0015725039611607186}}
{"text": "#pragma once\n#include \"iarg.h\"\n#include \"optioninfo.h\"\n#include \"configaccess.h\"\n#include \"format.h\"\n#include \"streamreader.h\"\n#include <gsl/gsl>\n#include <cmdlime/errors.h>\n#include <cmdlime/customnames.h>\n#include <sstream>\n#include <functional>\n#include <memory>\n\nnamespace cmdlime::detail{\n\ntemplate <typename T>\nclass Arg : public IArg{\npublic:\n    Arg(std::string name,\n        std::string type,\n        std::function<T&()> argGetter)\n        : info_(std::move(name), {}, std::move(type))\n        , argGetter_(std::move(argGetter))\n    {\n    }\n\n    OptionInfo& info() override\n    {\n        return info_;\n    }\n\n    const OptionInfo& info() const override\n    {\n        return info_;\n    }\n\nprivate:\n    bool read(const std::string& data) override\n    {\n        auto stream = std::stringstream{data};\n        return readFromStream(stream, argGetter_());\n    }\n\nprivate:\n    OptionInfo info_;\n    std::function<T&()> argGetter_;\n};\n\ntemplate <>\ninline bool Arg<std::string>::read(const std::string& data)\n{\n    argGetter_() = data;\n    return true;\n}\n\ntemplate<typename T, typename TConfig>\nclass ArgCreator{\n    using NameProvider = typename Format<ConfigAccess<TConfig>::format()>::nameProvider;\npublic:\n    ArgCreator(TConfig& cfg,\n               const std::string& varName,\n               const std::string& type,\n               std::function<T&()> argGetter)        \n        : cfg_(cfg)\n    {\n        Expects(!varName.empty());\n        Expects(!type.empty());\n        arg_ = std::make_unique<Arg<T>>(NameProvider::fullName(varName),\n                                        NameProvider::valueName(type),\n                                        std::move(argGetter));\n    }\n\n    ArgCreator<T, TConfig>& operator<<(const std::string& info)\n    {\n        arg_->info().addDescription(info);\n        return *this;\n    }\n\n    ArgCreator<T, TConfig>& operator<<(const Name& customName)\n    {\n        arg_->info().resetName(customName.value());\n        return *this;\n    }\n\n    ArgCreator<T, TConfig>& operator<<(const ValueName& valueName)\n    {\n        arg_->info().resetValueName(valueName.value());\n        return *this;\n    }\n\n    operator T()\n    {\n        ConfigAccess<TConfig>{cfg_}.addArg(std::move(arg_));\n        return T{};\n    }\n\nprivate:\n    std::unique_ptr<Arg<T>> arg_;\n    TConfig& cfg_;\n};\n\ntemplate <typename T, typename TConfig>\nArgCreator<T, TConfig> makeArgCreator(TConfig& cfg,\n                                       const std::string& varName,\n                                       const std::string& type,\n                                       std::function<T&()> argGetter)\n{\n    return ArgCreator<T, TConfig>{cfg, varName, type, std::move(argGetter)};\n}\n\n\n}\n", "meta": {"hexsha": "2919c483ba83fb5c0d0142986ceda1fd39e23d6d", "size": 2689, "ext": "h", "lang": "C", "max_stars_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/arg.h", "max_stars_repo_name": "GerHobbelt/hypertextcpp", "max_stars_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_stars_repo_licenses": ["MS-PL"], "max_stars_count": 77.0, "max_stars_repo_stars_event_min_datetime": "2021-05-20T18:05:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T21:37:54.000Z", "max_issues_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/arg.h", "max_issues_repo_name": "GerHobbelt/hypertextcpp", "max_issues_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_issues_repo_licenses": ["MS-PL"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2021-05-20T22:04:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-21T08:13:28.000Z", "max_forks_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/arg.h", "max_forks_repo_name": "GerHobbelt/hypertextcpp", "max_forks_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_forks_repo_licenses": ["MS-PL"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-22T00:36:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-22T00:36:08.000Z", "avg_line_length": 23.796460177, "max_line_length": 88, "alphanum_fraction": 0.5741911491, "num_tokens": 622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.05340333281292339, "lm_q2_score": 0.029312229267415522, "lm_q1q2_score": 0.0015653707350565048}}
{"text": "#pragma once\n\n#include <gsl.h>\n#include <memory>\n\nnamespace crimson {\n\nclass ISolverSetupManager;\n\n/*! \\brief   A solver setup service interface. */\nclass ISolverSetupService\n{\npublic:\n\n    /*!\n     * \\brief   Gets solver setup manager.\n     */\n    virtual gsl::not_null<ISolverSetupManager*> getSolverSetupManager() const = 0;\n    virtual ~ISolverSetupService() {}\n};\n\n}", "meta": {"hexsha": "c88748028d702979ca4167f717cfda1703580098", "size": 371, "ext": "h", "lang": "C", "max_stars_repo_path": "Modules/SolverSetupService/include/ISolverSetupService.h", "max_stars_repo_name": "carthurs/CRIMSONGUI", "max_stars_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-09-17T18:55:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T02:52:38.000Z", "max_issues_repo_path": "Modules/SolverSetupService/include/ISolverSetupService.h", "max_issues_repo_name": "carthurs/CRIMSONGUI", "max_issues_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Modules/SolverSetupService/include/ISolverSetupService.h", "max_forks_repo_name": "carthurs/CRIMSONGUI", "max_forks_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-05-19T09:02:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-26T17:39:57.000Z", "avg_line_length": 16.8636363636, "max_line_length": 82, "alphanum_fraction": 0.6846361186, "num_tokens": 89, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.07807816943541052, "lm_q2_score": 0.020023443226592625, "lm_q1q2_score": 0.001563393792926222}}
{"text": "#pragma once\n\n#include <csignal>\n#include <iostream>\n#include <sstream>\n#include <cassert>\n#include <vector>\n#include <algorithm>\n#include <array>\n#include <memory>\n#include <iomanip>\n#include <fstream>\n#include <filesystem>\n#include <cstdarg>\n#include <unordered_set>\n#include <unordered_map>\n#include <bitset>\n#include <numeric>\n#include <cmath>\n\n#ifdef _MSC_VER\n#\tpragma  warning(disable:4267)\n#endif\n\n#include <GLTFAsset.h>\n#include <GLTFScene.h>\n#include <GLTFBuffer.h>\n#include <GLTFBufferView.h>\n#include <GLTFAccessor.h>\n#include <GLTFMesh.h>\n#include <GLTFPrimitive.h>\n\n#ifdef _MSC_VER\n#\tpragma  warning(default:4267)\n#endif\n\n#include \"rapidjson/document.h\"\n#include \"rapidjson/prettywriter.h\"\n#include \"rapidjson/stringbuffer.h\"\n#include \"rapidjson/writer.h\"\n\n#include <gsl/span>\n\n#include <coveo/linq.h>\n#include <coveo/enumerable.h>\n\n#include <maya/MPxCommand.h>\n#include <maya/MFnPlugin.h>\n#include <maya/MIOStream.h>\n#include <maya/MGlobal.h>\n#include <maya/MArgList.h>\n#include <maya/MArgDatabase.h>\n#include <maya/MSyntax.h>\n#include <maya/MStreamUtils.h>\n#include <maya/MFileObject.h>\n#include <maya/MFileIO.h>\n#include <maya/MSelectionList.h>\n#include <maya/MFnMesh.h>\n#include <maya/MItMeshPolygon.h>\n#include <maya/MFloatPointArray.h>\n#include <maya/MFloatVectorArray.h>\n#include <maya/MDagPath.h>\n#include <maya/MPointArray.h>\n#include <maya/MFnAttribute.h>\n#include <maya/MFnStringArrayData.h>\n#include <maya/MFnMessageAttribute.h>\n#include <maya/MFnNumericAttribute.h>\n#include <maya/MFnTypedAttribute.h>\n#include <maya/MDagPathArray.h>\n#include <maya/MFnSet.h>\n#include <maya/MFnSingleIndexedComponent.h>\n#include <maya/MFnComponentListData.h>\n#include <maya/MDagModifier.h>\n#include <maya/MMatrix.h>\n#include <maya/MFnMatrixData.h>\n#include <maya/MFnTransform.h>\n#include <maya/MItDependencyGraph.h>\n#include <maya/MFnBlendShapeDeformer.h>\n#include <maya/MFnPhongShader.h>\n#include <maya/MFnLambertShader.h>\n#include <maya/MFnBlinnShader.h>\n#include <maya/MUuid.h>\n#include <maya/MImage.h>\n#include <maya/MFloatMatrix.h>\n#include <maya/MTime.h>\n#include <maya/MAnimControl.h>\n#include <maya/M3dView.h>\n#include <maya/MFnSkinCluster.h>\n#include <maya/MItGeometry.h>\n#include <maya/MItDependencyNodes.h>\n#include <maya/MItMeshFaceVertex.h>\n\n", "meta": {"hexsha": "2a9576c559177f321e0837c84f59320f3e688bef", "size": 2264, "ext": "h", "lang": "C", "max_stars_repo_path": "src/externals.h", "max_stars_repo_name": "hamilton555/gltf", "max_stars_repo_head_hexsha": "26853c20484a2cb17f3d8c2594e76efecda3cb2b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-06T01:49:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-06T01:49:54.000Z", "max_issues_repo_path": "src/externals.h", "max_issues_repo_name": "BigRoy/Maya2glTF", "max_issues_repo_head_hexsha": "14c09052bbe1437c9f4f26786284a7edf69df989", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/externals.h", "max_forks_repo_name": "BigRoy/Maya2glTF", "max_forks_repo_head_hexsha": "14c09052bbe1437c9f4f26786284a7edf69df989", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3440860215, "max_line_length": 43, "alphanum_fraction": 0.7667844523, "num_tokens": 655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10230469694465662, "lm_q2_score": 0.01518905226288256, "lm_q1q2_score": 0.0015539113886307511}}
{"text": "\n/*\n * BSD 3-Clause License\n *\n * Copyright (c) 2018, mtezych\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright notice,\n *   this list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above copyright notice,\n *   this list of conditions and the following disclaimer in the documentation\n *   and/or other materials provided with the distribution.\n *\n * * Neither the name of the copyright holder nor the names of its\n *   contributors may be used to endorse or promote products derived from\n *   this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,\n * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef CL_CONTEXT\n#define CL_CONTEXT\n\n#ifdef __APPLE__\n\t#include <OpenCL/cl.h>\n#else\n\t#include <CL/cl.h>\n#endif\n\n#include <cl/Device.h>\n\n#include <util/util.h>\n\n#include <gsl/span>\n\n#include <vector>\n#include <cstddef>\n\nnamespace cl\n{\n\tstruct Platform;\n\n\tstruct Context\n\t{\n\t\tcl_context clContext;\n\n\t\t//\n\t\t// @note: The NotifyCallback must be thread-safe.\n\t\t//\n\t\tusing NotifyCallback = void (CL_CALLBACK *)\n\t\t(\n\t\t\tconst char* errorInfo,\n\t\t\tconst void* privateInfo, size_t cb,\n\t\t\tvoid* userData\n\t\t);\n\n\t\tContext\n\t\t(\n\t\t\tconst Platform&         platform,\n\t\t\tgsl::span<const Device> devices\n\t\t);\n\n\t\tContext\n\t\t(\n\t\t\tconst Platform& platform,\n\t\t\tcl_device_type  deviceType\n\t\t);\n\n\t\t~Context ();\n\n\t\tContext (Context&& context);\n\t\tContext (const Context& context) = delete;\n\n\t\tContext& operator = (Context&& context);\n\t\tContext& operator = (const Context& context) = delete;\n\n\t\tenum class Info : cl_context_info\n\t\t{\n\t\t\tNumDevices     = CL_CONTEXT_NUM_DEVICES,\n\t\t\tReferenceCount = CL_CONTEXT_REFERENCE_COUNT,\n\t\t};\n\n\t\ttemplate <Info info>\n\t\tauto GetInfo() const\n\t\t{\n\t\t\tauto infoSize = std::size_t { 0 };\n\t\t\tauto result = clGetContextInfo\n\t\t\t(\n\t\t\t\tclContext, util::enum_cast(info),\n\t\t\t\t0, nullptr, &infoSize\n\t\t\t);\n\t\t\tassert(result == CL_SUCCESS);\n\n\t\t\tauto infoBytes = std::vector<std::byte>\n\t\t\t{\n\t\t\t\tinfoSize, std::byte { 0x00 }\n\t\t\t};\n\t\t\tresult = clGetContextInfo\n\t\t\t(\n\t\t\t\tclContext, util::enum_cast(info),\n\t\t\t\tinfoBytes.size(), infoBytes.data(), nullptr\n\t\t\t);\n\t\t\tassert(result == CL_SUCCESS);\n\n\t\t\treturn InfoResult<info>::FromBytes(infoBytes);\n\t\t}\n\n\tprivate:\n\n\t\ttemplate <Info info>\n\t\tstruct InfoResult;\n\t};\n\n\ttemplate <>\n\tstruct Context::InfoResult<Context::Info::NumDevices>\n\t{\n\t\tstatic cl_uint\n\t\tFromBytes (const std::vector<std::byte>& infoBytes);\n\t};\n\n\ttemplate <>\n\tstruct Context::InfoResult<Context::Info::ReferenceCount>\n\t{\n\t\tstatic cl_uint\n\t\tFromBytes (const std::vector<std::byte>& infoBytes);\n\t};\n}\n\n#endif\n", "meta": {"hexsha": "bffb961727691ab5dcf4beadb54ac7303bb28613", "size": 3505, "ext": "h", "lang": "C", "max_stars_repo_path": "cl/include/cl/Context.h", "max_stars_repo_name": "mtezych/cpp", "max_stars_repo_head_hexsha": "05c1b85eb89117a9b406f3f32470367937331614", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cl/include/cl/Context.h", "max_issues_repo_name": "mtezych/cpp", "max_issues_repo_head_hexsha": "05c1b85eb89117a9b406f3f32470367937331614", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cl/include/cl/Context.h", "max_forks_repo_name": "mtezych/cpp", "max_forks_repo_head_hexsha": "05c1b85eb89117a9b406f3f32470367937331614", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-12-21T00:31:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-14T23:16:23.000Z", "avg_line_length": 24.3402777778, "max_line_length": 78, "alphanum_fraction": 0.7095577746, "num_tokens": 843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06954174836258788, "lm_q2_score": 0.022286184849261332, "lm_q1q2_score": 0.00154982025874945}}
{"text": "/*\n * Copyright (c) 2016-2020 lymastee, All rights reserved.\n * Contact: lymastee@hotmail.com\n *\n * This file is part of the gslib project.\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n#pragma once\n\n#ifndef basis_40d2b174_3729_49b6_a8d6_5b7ac75a2483_h\n#define basis_40d2b174_3729_49b6_a8d6_5b7ac75a2483_h\n\n#include <gslib/std.h>\n#include <gslib/string.h>\n#include <gslib/tree.h>\n#include <ariel/widget.h>\n\nnamespace ui_editor {\n\nusing gs::rect;\nusing gs::rectf;\nusing gs::point;\nusing gs::pointf;\nusing gs::string;\nusing gs::list;\nusing gs::unordered_map;\nusing gs::gchar;\nusing gs::uint;\nusing gs::real;\nusing gs::real32;\nusing gs::ariel::painter;\nusing gs::ariel::wsys_manager;\nusing gs::ariel::unikey;\ntypedef gs::ariel::widget core_widget;\n\nstruct ui_proc_node;\ntypedef unordered_map<string, string> ui_prop_map;\ntypedef unordered_map<string, ui_proc_node> ui_proc_map;\n\nstruct ui_proc_node\n{\n    string              args;\n    string              injection;\n};\n\n// class ui_editor_configs\n// {\n// \n// };\n\nstruct ui_macro\n{\n    string              name;\n    string              definition;\n\npublic:\n    ui_macro(const string& n): name(n) {}\n    ui_macro(const string& n, const string& d): name(n), definition(d) {}\n};\n\ntypedef list<string> ui_includes;\ntypedef list<ui_macro> ui_macros;\n\nclass ui_src_entry\n{\npublic:\n    void add_include(const string& str);\n    void add_include_group(const string& strgroup);\n    void add_macro(const string& name) { _macro_list.push_back(ui_macro(name)); }\n    void add_macro(const string& name, const string& def) { _macro_list.push_back(ui_macro(name, def)); }\n    void set_preproc(const string& preproc) { _preproc_injections = preproc; }\n    void set_postproc(const string& postproc) { _postproc_injections = postproc; }\n    void set_output(const string& str) { _output_name = str; }\n    void set_export(const string& str) { _export_name = str; }\n    const ui_includes& get_includes() const { return _include_list; }\n    const ui_macros& get_macros() const { return _macro_list; }\n    const string& get_preproc() const { return _preproc_injections; }\n    const string& get_postproc() const { return _postproc_injections; }\n    const string& get_output() const { return _output_name; }\n    const string& get_export() const { return _export_name; }\n\nprotected:\n    ui_includes         _include_list;\n    ui_macros           _macro_list;\n    string              _preproc_injections;\n    string              _postproc_injections;\n    string              _output_name;       /* for output file name */\n    string              _export_name;       /* for export class name */\n};\n\nclass ui_editor_context\n{\npublic:\n    typedef unordered_map<string, int> var_index_map;\n\npublic:\n    ui_src_entry& get_src_entry() { return _src_entry; }\n    const ui_src_entry& const_src_entry() const { return _src_entry; }\n    int acquire_variable_index(const string& vartype);\n    int query_variable_index(const string& vartype) const;\n    int acquire_variable_name(string& name, const string& vartype);\n\nprotected:\n    ui_src_entry        _src_entry;\n    var_index_map       _index_map;\n};\n\nclass ui_node\n{\npublic:\n    rect                position;\n    string              type;\n    string              name;\n    string              variable;\n    bool                is_instance;\n    ui_prop_map         prop_map;\n    ui_proc_map         proc_map;\n    core_widget*        assoc_widget;\n\npublic:\n    ui_node(): is_instance(false), assoc_widget(nullptr) {}\n};\n\ntypedef gs::_treenode_cpy_wrapper<ui_node> ui_node_wrapper;\ntypedef gs::tree<ui_node, ui_node_wrapper> ui_tree;\n\ntypedef core_widget* (__stdcall *pfn_create_widget)(wsys_manager* wsys, core_widget* parent, ui_node& uinode);\n\nclass ui_transparent_layer:\n    public core_widget\n{\npublic:\n    ui_transparent_layer(wsys_manager* m);\n    void install_reflection_widget(core_widget* refw);\n    core_widget* get_reflection_widget() const { return _reflection_widget; }\n\npublic:\n    virtual ~ui_transparent_layer();\n    virtual void on_reflection_close();\n    virtual void on_reflection_show(bool b);\n    virtual void on_reflection_enable(bool b);\n    virtual void on_reflection_move(const rect& rc);\n    virtual void on_reflection_char(uint um, uint ch) {}\n    virtual void on_reflection_caret() {}\n    virtual void on_reflection_capture(bool b) {}\n    virtual void on_reflection_focus(bool b) {}\n    virtual void on_reflection_scroll(const point& pt, real32 scr, bool vert) {}\n    virtual void on_reflection_accelerator(unikey key, uint mask) {}\n\nprotected:\n    core_widget*        _reflection_widget;\n\nprotected:\n    void sync_size_with_reflection();\n};\n\nclass ui_edit_control;\n\nclass ui_editor_layer:\n    public ui_transparent_layer\n{\npublic:\n    enum size_orient\n    {\n        so_none,\n        so_n,\n        so_s,\n        so_e,\n        so_w,\n        so_ne,\n        so_nw,\n        so_se,\n        so_sw,\n    };\n\npublic:\n    ui_editor_layer(wsys_manager* m);\n    void initialize(ui_node& uinode);\n    void install_reflection_widget(core_widget* refw);\n    ui_node* get_ui_node() const { return _assoc_ui_node; }\n\npublic:\n    virtual void on_reflection_press(uint um, unikey uk, const point& pt);\n    virtual void on_reflection_click(uint um, unikey uk, const point& pt);\n    virtual void on_reflection_hover(uint um, const point& pt);\n    virtual void on_reflection_leave(uint um, const point& pt);\n    virtual void on_reflection_keydown(uint um, unikey uk);\n    virtual void on_reflection_keyup(uint um, unikey uk);\n\nprotected:\n    ui_node*            _assoc_ui_node;\n    ui_edit_control*    _edit_ctl;\n\nprotected:\n    void refresh_cursor(const point& pt);\n    size_orient get_size_orient(const point& pt, int accuracy = 3) const;\n    void try_install_edit_control(const point& pt);\n    void try_uninstall_edit_control();\n    void refresh_edit_control(uint um, const point& pt);\n};\n\nextern bool ui_create_widgets(wsys_manager* wsys, core_widget* root_layer, ui_tree& uicore);\n//extern bool ui_;\n\n}\n\n#endif\n", "meta": {"hexsha": "ad2513839fa0711a0e2cbb507cf621699eb03e43", "size": 7017, "ext": "h", "lang": "C", "max_stars_repo_path": "proj/uieditor/basis.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "proj/uieditor/basis.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "proj/uieditor/basis.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 31.0486725664, "max_line_length": 110, "alphanum_fraction": 0.7088499359, "num_tokens": 1701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.05500529216624421, "lm_q2_score": 0.02800752030174629, "lm_q1q2_score": 0.001540561837049571}}
{"text": "/* GLIB - Library of useful routines for C programming\n * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\t See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n */\n\n/*\n * Modified by the GLib Team and others 1997-2000.  See the AUTHORS\n * file for a list of people on the GLib Team.  See the ChangeLog\n * files for a list of changes.  These files are distributed with\n * GLib at ftp://ftp.gtk.org/pub/gtk/. \n */\n\n#ifndef __G_LIB_H__\n#define __G_LIB_H__\n\n#include <galloca.h>\n#include <garray.h>\n#include <gasyncqueue.h>\n#include <gbacktrace.h>\n#include <gcache.h>\n#include <gcompat.h>\n#include <gcompletion.h>\n#include <gconvert.h>\n#include <gdataset.h>\n#include <gdate.h>\n#include <gerror.h>\n#include <gfileutils.h>\n#include <ghash.h>\n#include <ghook.h>\n#include <giochannel.h>\n#include <glist.h>\n#include <gmacros.h>\n#include <gmain.h>\n#include <gmarkup.h>\n#include <gmem.h>\n#include <gmessages.h>\n#include <gnode.h>\n#include <gprimes.h>\n#include <gqsort.h>\n#include <gquark.h>\n#include <gqueue.h>\n#include <grand.h>\n#include <grel.h>\n#include <gscanner.h>\n#include <gshell.h>\n#include <gslist.h>\n#include <gspawn.h>\n#include <gstrfuncs.h>\n#include <gstring.h>\n#include <gthread.h>\n#include <gthreadpool.h>\n#include <gtimer.h>\n#include <gtree.h>\n#include <gtypes.h>\n#include <gunicode.h>\n#include <gutils.h>\n#ifdef G_OS_WIN32\n#include <gwin32.h>\n#endif\n\n#endif /* __G_LIB_H__ */\n", "meta": {"hexsha": "689f2e8699ece5f0e8ce8730ff1f641541dd7049", "size": 2094, "ext": "h", "lang": "C", "max_stars_repo_path": "vega-vc9/include/glib/glib.h", "max_stars_repo_name": "Ezeer/VegaStrike_win32FR", "max_stars_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vega-vc9/include/glib/glib.h", "max_issues_repo_name": "Ezeer/VegaStrike_win32FR", "max_issues_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vega-vc9/include/glib/glib.h", "max_forks_repo_name": "Ezeer/VegaStrike_win32FR", "max_forks_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5526315789, "max_line_length": 76, "alphanum_fraction": 0.7277936963, "num_tokens": 563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09670579329612154, "lm_q2_score": 0.015906391770128092, "lm_q1q2_score": 0.0015382402346091361}}
{"text": "/***\n * Copyright 2020 The Katla Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n#ifndef KATLA_MQTT_MESSAGE_H\n#define KATLA_MQTT_MESSAGE_H\n\n#include \"outcome/outcome.hpp\"\n\n#include <gsl/span>\n\nnamespace katla {\n\nenum class MqttQos {AtMostOnce = 0, AtLeastOnce = 1, ExactlyOnce = 2};\n\nstruct MqttMessage {\n    int messageId {};\n    std::string topic;\n    gsl::span<std::byte> payload;\n    MqttQos qos;\n    bool retain;\n};\n\n} // namespace katla\n\n#endif\n", "meta": {"hexsha": "c3ad4d30c787051be672fd36c810d0171a6ba6d1", "size": 969, "ext": "h", "lang": "C", "max_stars_repo_path": "mqtt/mqtt-message.h", "max_stars_repo_name": "plok/katla", "max_stars_repo_head_hexsha": "aaaeb8baf041bba7259275beefc71c8452a16223", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mqtt/mqtt-message.h", "max_issues_repo_name": "plok/katla", "max_issues_repo_head_hexsha": "aaaeb8baf041bba7259275beefc71c8452a16223", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-03-25T14:33:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-16T14:21:56.000Z", "max_forks_repo_path": "mqtt/mqtt-message.h", "max_forks_repo_name": "plok/katla", "max_forks_repo_head_hexsha": "aaaeb8baf041bba7259275beefc71c8452a16223", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-26T13:32:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-26T13:32:36.000Z", "avg_line_length": 25.5, "max_line_length": 75, "alphanum_fraction": 0.7244582043, "num_tokens": 241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.04813676702004151, "lm_q2_score": 0.031618769892134635, "lm_q1q2_score": 0.001522025359757988}}
{"text": "#pragma once\n\n#include <winrt\\Windows.Foundation.h>\n#include <d3d11.h>\n#include <DirectXMath.h>\n#include <gsl\\gsl>\n\nnamespace Library\n{\n\tclass SamplerStates final\n\t{\n\tpublic:\n\t\tinline static winrt::com_ptr<ID3D11SamplerState> TrilinearWrap;\n\t\tinline static winrt::com_ptr<ID3D11SamplerState> TrilinearMirror;\n\t\tinline static winrt::com_ptr<ID3D11SamplerState> TrilinearClamp;\n\t\tinline static winrt::com_ptr<ID3D11SamplerState> TrilinearBorder;\n\t\tinline static winrt::com_ptr<ID3D11SamplerState> PointClamp;\n\t\tinline static winrt::com_ptr<ID3D11SamplerState> DepthMap;\n\t\tinline static winrt::com_ptr<ID3D11SamplerState> ShadowMap;\n\t\tinline static winrt::com_ptr<ID3D11SamplerState> PcfShadowMap;\n\n\t\tstatic DirectX::XMVECTORF32 BorderColor;\n\t\tstatic DirectX::XMVECTORF32 ShadowMapBorderColor;\n\n\t\tstatic void Initialize(gsl::not_null<ID3D11Device*> direct3DDevice);\n\t\tstatic void Shutdown();\n\n\t\tSamplerStates() = delete;\n\t\tSamplerStates(const SamplerStates&) = delete;\n\t\tSamplerStates& operator=(const SamplerStates&) = delete;\n\t\tSamplerStates(SamplerStates&&) = delete;\n\t\tSamplerStates& operator=(SamplerStates&&) = delete;\n\t\t~SamplerStates() = default;\n\t};\n}", "meta": {"hexsha": "6dac2ba238b9c589f3ebae3ae0dbf432f1a52b63", "size": 1157, "ext": "h", "lang": "C", "max_stars_repo_path": "source/Library.Shared/SamplerStates.h", "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/Library.Shared/SamplerStates.h", "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/Library.Shared/SamplerStates.h", "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0571428571, "max_line_length": 70, "alphanum_fraction": 0.7856525497, "num_tokens": 318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09401017961657226, "lm_q2_score": 0.016152836302191477, "lm_q1q2_score": 0.0015185310420861096}}
{"text": "#ifndef _UI_HELPERS_H_\n#define _UI_HELPERS_H_\n\n#define OEMRESOURCE\n\n#include <algorithm>\n#include <functional>\n#include <memory>\n#include <optional>\n#include <span>\n#include <string>\n#include <type_traits>\n#include <unordered_map>\n#include <vector>\n\n#include <ppl.h>\n\n#include <gsl/gsl>\n\n// Included before windows.h, because pfc.h includes winsock2.h\n#include \"../pfc/pfc.h\"\n\n#include <windows.h>\n#include <WindowsX.h>\n#include <SHLWAPI.H>\n#include <vssym32.h>\n#include <uxtheme.h>\n#include <shldisp.h>\n#include <ShlObj.h>\n#include <gdiplus.h>\n#include <Usp10.h>\n#include <CommonControls.h>\n\n#include <wil/resource.h>\n\n// Windows SDK headers define min and max macros, which are used by gdiplus.h.\n//\n// This undefines them temporarily to avoid conflicts with the C++ standard\n// library. They are redefined at the end of this header.\n#ifdef max\n#define _UI_HELPERS_OLD_MAX_\n#undef max\n#endif\n\n#ifdef min\n#define _UI_HELPERS_OLD_MIN_\n#undef min\n#endif\n\n#include \"../mmh/stdafx.h\"\n\n#ifndef RECT_CX\n#define RECT_CX(rc) (rc.right - rc.left)\n#endif\n\n#ifndef RECT_CY\n#define RECT_CY(rc) (rc.bottom - rc.top)\n#endif\n\n#include \"literals.h\"\n\n#include \"handle.h\"\n#include \"win32_helpers.h\"\n#include \"ole.h\"\n\n#include \"dialog.h\"\n#include \"dpi.h\"\n#include \"container_window.h\"\n#include \"message_hook.h\"\n#include \"trackbar.h\"\n#include \"solid_fill.h\"\n#include \"theming.h\"\n\n#include \"gdi.h\"\n#include \"text_drawing.h\"\n#include \"list_view/list_view.h\"\n#include \"drag_image.h\"\n#include \"info_box.h\"\n#include \"menu.h\"\n\n#include \"ole/data_object.h\"\n#include \"ole/enum_format_etc.h\"\n\n#ifdef _UI_HELPERS_OLD_MAX_\n#define max(a, b) (((a) > (b)) ? (a) : (b))\n#undef _UI_HELPERS_OLD_MAX_\n#endif\n\n#ifdef _UI_HELPERS_OLD_MIN_\n#define min(a, b) (((a) < (b)) ? (a) : (b))\n#undef _UI_HELPERS_OLD_MIN_\n#endif\n\n#endif\n", "meta": {"hexsha": "3f838c0d89d00df7b8962c05caaef8b68793297d", "size": 1788, "ext": "h", "lang": "C", "max_stars_repo_path": "stdafx.h", "max_stars_repo_name": "reupen/ui_helpers", "max_stars_repo_head_hexsha": "7db30d91f58116ece51e2cdaf83c4e2be819609e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-04-12T13:45:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-30T17:17:02.000Z", "max_issues_repo_path": "stdafx.h", "max_issues_repo_name": "reupen/ui_helpers", "max_issues_repo_head_hexsha": "7db30d91f58116ece51e2cdaf83c4e2be819609e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-07-12T23:39:30.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-13T08:56:52.000Z", "max_forks_repo_path": "stdafx.h", "max_forks_repo_name": "reupen/ui_helpers", "max_forks_repo_head_hexsha": "7db30d91f58116ece51e2cdaf83c4e2be819609e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-04-12T13:45:38.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-12T23:37:01.000Z", "avg_line_length": 18.8210526316, "max_line_length": 78, "alphanum_fraction": 0.7253914989, "num_tokens": 491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07807816085449158, "lm_q2_score": 0.019419349884957346, "lm_q1q2_score": 0.0015162271240073523}}
{"text": "/*\n   Copyright [2017-2019] [IBM Corporation]\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n       http://www.apache.org/licenses/LICENSE-2.0\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\n\n#ifndef COMANCHE_HSTORE_POOL_MANAGER_H\n#define COMANCHE_HSTORE_POOL_MANAGER_H\n\n#include <api/kvstore_itf.h> /* status_t */\n\n#include \"alloc_key.h\"\n\n#include <common/logging.h> /* log_source */\n#include <nupm/region_descriptor.h>\n#include <gsl/pointers>\n#include <sys/uio.h>\n#include <cstddef>\n#include <functional>\n#include <string>\n#include <system_error>\n\nstruct pool_path;\n\n#pragma GCC diagnostic push\n// #pragma GCC diagnostic ignored \"-Wunused-parameter\"\n\nenum class pool_ec\n{\n  pool_fail,\n  pool_unsupported_mode,\n  region_fail,\n  region_fail_general_exception,\n  region_fail_api_exception,\n};\n\nstruct pool_category\n  : public std::error_category\n{\n  const char* name() const noexcept override { return \"pool_category\"; }\n  std::string message( int condition ) const noexcept override\n  {\n    switch ( condition )\n    {\n    case int(pool_ec::pool_fail):\n      return \"default pool failure\";\n    case int(pool_ec::pool_unsupported_mode):\n      return \"pool unsupported flags\";\n    case int(pool_ec::region_fail):\n      return \"region-backed pool failure\";\n    case int(pool_ec::region_fail_general_exception):\n      return \"region-backed pool failure (General_exception)\";\n    case int(pool_ec::region_fail_api_exception):\n      return \"region-backed pool failure (API_exception)\";\n    default:\n      return \"unknown pool failure\";\n    }\n  }\n};\n\nnamespace\n{\n  pool_category pool_error_category;\n}\n\nstruct pool_error\n  : public std::error_condition\n{\n  std::string _msg;\npublic:\n  pool_error(const std::string &msg_, pool_ec val_)\n    : std::error_condition(int(val_), pool_error_category)\n    , _msg(msg_)\n  {}\n\n};\n\nstruct dax_manager;\n\ntemplate <typename Pool>\n  struct pool_manager\n    : protected common::log_source\n  {\n    pool_manager(unsigned debug_level_) : common::log_source(debug_level_) {}\n    virtual ~pool_manager() {}\n\n    virtual void pool_create_check(const std::size_t size_) = 0;\n\n    virtual void pool_close_check(const std::string &) = 0;\n\n    virtual nupm::region_descriptor pool_get_regions(const Pool &) const = 0;\n\n    /*\n     * throws pool_error if create_region fails\n     */\n    virtual auto pool_create_1(\n      const pool_path &path_\n      , std::size_t size_\n    ) -> nupm::region_descriptor = 0;\n\n    virtual auto pool_create_2(\n      AK_FORMAL\n      const nupm::region_descriptor & rac\n      , component::IKVStore::flags_t flags\n      , std::size_t expected_obj_count\n    ) -> std::unique_ptr<Pool> = 0;\n\n    virtual auto pool_open_1(\n      const pool_path &path_\n    ) -> nupm::region_descriptor = 0;\n\n    virtual auto pool_open_2(\n      AK_FORMAL\n      const nupm::region_descriptor & access_\n      , component::IKVStore::flags_t flags_\n    ) -> std::unique_ptr<Pool> = 0;\n\n    virtual void pool_delete(const pool_path &path) = 0;\n    virtual const std::unique_ptr<dax_manager> & get_dax_manager() const = 0;\n  };\n#pragma GCC diagnostic pop\n\n#endif\n", "meta": {"hexsha": "c837194d3db090e41f131f6af34cf76bfd62e182", "size": 3488, "ext": "h", "lang": "C", "max_stars_repo_path": "src/components/store/hstore/src/pool_manager.h", "max_stars_repo_name": "moshik1/mcas", "max_stars_repo_head_hexsha": "a6af06bc278993fb3ffe780f230d2396b2287c26", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/components/store/hstore/src/pool_manager.h", "max_issues_repo_name": "moshik1/mcas", "max_issues_repo_head_hexsha": "a6af06bc278993fb3ffe780f230d2396b2287c26", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/components/store/hstore/src/pool_manager.h", "max_forks_repo_name": "moshik1/mcas", "max_forks_repo_head_hexsha": "a6af06bc278993fb3ffe780f230d2396b2287c26", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4242424242, "max_line_length": 77, "alphanum_fraction": 0.7121559633, "num_tokens": 839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.05665243008614414, "lm_q2_score": 0.026759285028796032, "lm_q1q2_score": 0.0015159785242490707}}
{"text": "\n/*\n * BSD 3-Clause License\n *\n * Copyright (c) 2018, mtezych\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright notice,\n *   this list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above copyright notice,\n *   this list of conditions and the following disclaimer in the documentation\n *   and/or other materials provided with the distribution.\n *\n * * Neither the name of the copyright holder nor the names of its\n *   contributors may be used to endorse or promote products derived from\n *   this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,\n * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef CL_COMMAND_QUEUE\n#define CL_COMMAND_QUEUE\n\n#ifdef __APPLE__\n\t#include <OpenCL/cl.h>\n#else\n\t#include <CL/cl.h>\n#endif\n\n#include <cl/Kernel.h>\n#include <cl/Event.h>\n#include <cl/Memory.h>\n\n#include <util/util.h>\n\n#include <gsl/span>\n\n#include <array>\n#include <vector>\n#include <cstddef>\n\nnamespace cl\n{\n\tstruct Context;\n\tstruct Device;\n\n\tenum NDRange : cl_uint\n\t{\n\t\tRange1D = 1,\n\t\tRange2D = 2,\n\t\tRange3D = 3,\n\t};\n\n\tstruct Range\n\t{\n\t\tstd::size_t offset;\n\t\tstd::size_t size;\n\t};\n\n\tenum class ExecMode : cl_command_queue_properties\n\t{\n\t\t   InOrder = 0,\n\t\tOutOfOrder = CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE,\n\t};\n\n\tenum class Profiling : cl_command_queue_properties\n\t{\n\t\t Enable = CL_QUEUE_PROFILING_ENABLE,\n\t\tDisable = 0,\n\t};\n\n\tstruct CommandQueue\n\t{\n\t\tcl_command_queue clCommandQueue;\n\n\t\tCommandQueue\n\t\t(\n\t\t\tconst Context& context, const Device& device,\n\t\t\tExecMode  execMode  = ExecMode::InOrder,\n\t\t\tProfiling profiling = Profiling::Disable\n\t\t);\n\n\t\t~CommandQueue ();\n\n\t\tCommandQueue (CommandQueue&& commandQueue);\n\t\tCommandQueue (const CommandQueue& commandQueue) = delete;\n\n\t\tCommandQueue& operator = (CommandQueue&& commandQueue);\n\t\tCommandQueue& operator = (const CommandQueue& commandQueue) = delete;\n\n\t\tstruct Properties\n\t\t{\n\t\t\tExecMode  execMode;\n\t\t\tProfiling profiling;\n\t\t};\n\n\t\tenum class Info : cl_command_queue_info\n\t\t{\n\t\t\tReferenceCount = CL_QUEUE_REFERENCE_COUNT,\n\t\t\tProperties     = CL_QUEUE_PROPERTIES,\n\t\t};\n\n\t\ttemplate <Info info>\n\t\tauto GetInfo() const\n\t\t{\n\t\t\tauto infoSize = std::size_t { 0 };\n\t\t\tauto result = clGetCommandQueueInfo\n\t\t\t(\n\t\t\t\tclCommandQueue, util::enum_cast(info),\n\t\t\t\t0, nullptr, &infoSize\n\t\t\t);\n\t\t\tassert(result == CL_SUCCESS);\n\n\t\t\tauto infoBytes = std::vector<std::byte>\n\t\t\t{\n\t\t\t\tinfoSize, std::byte { 0x00 }\n\t\t\t};\n\t\t\tresult = clGetCommandQueueInfo\n\t\t\t(\n\t\t\t\tclCommandQueue, util::enum_cast(info),\n\t\t\t\tinfoBytes.size(), infoBytes.data(), nullptr\n\t\t\t);\n\t\t\tassert(result == CL_SUCCESS);\n\n\t\t\treturn InfoResult<info>::FromBytes(infoBytes);\n\t\t}\n\n\t\ttemplate <NDRange WorkDimension>\n\t\tEvent EnqueueKernel\n\t\t(\n\t\t\tconst Kernel& kernel,\n\t\t\tconst std::array<size_t, WorkDimension>& globalWorkSize,\n\t\t\tconst std::array<size_t, WorkDimension>&  localWorkSize,\n\t\t\tconst std::vector<Event>& waitEvents\n\t\t)\n\t\t{\n\t\t\tstatic_assert(sizeof(Event) == sizeof(cl_event));\n\n\t\t\tconst auto globalWorkOffset = std::array<size_t, WorkDimension> { };\n\n\t\t\tauto signalEvent = cl_event { };\n\n\t\t\tauto result = clEnqueueNDRangeKernel\n\t\t\t(\n\t\t\t\tclCommandQueue, kernel.clKernel,\n\t\t\t\tWorkDimension,\n\t\t\t\tglobalWorkOffset.data(),\n\t\t\t\tglobalWorkSize.data(), localWorkSize.data(),\n\t\t\t\tstatic_cast<cl_uint>(waitEvents.size()),\n\t\t\t\treinterpret_cast<const cl_event*>(util::data_or_null(waitEvents)),\n\t\t\t\t&signalEvent\n\t\t\t);\n\t\t\tassert(result == CL_SUCCESS);\n\n\t\t\treturn Event { signalEvent };\n\t\t}\n\n\t\ttemplate <typename ValueType>\n\t\tEvent EnqueueReadBuffer\n\t\t(\n\t\t\tconst Memory<ValueType>& memory,\n\t\t\tconst gsl::span<ValueType> buffer,\n\t\t\tconst Range& range,\n\t\t\tconst std::vector<Event>& waitEvents\n\t\t)\n\t\t{\n\t\t\tassert(buffer.size() >= static_cast<std::ptrdiff_t>(range.size));\n\n\t\t\tauto signalEvent = cl_event { };\n\n\t\t\tauto result = clEnqueueReadBuffer\n\t\t\t(\n\t\t\t\tclCommandQueue, memory.clMemory,\n\t\t\t\tcl_bool { CL_BLOCKING },\n\t\t\t\trange.offset, sizeof(ValueType) * range.size,\n\t\t\t\tbuffer.data(),\n\t\t\t\tstatic_cast<cl_uint>(waitEvents.size()),\n\t\t\t\treinterpret_cast<const cl_event*>(util::data_or_null(waitEvents)),\n\t\t\t\t&signalEvent\n\t\t\t);\n\t\t\tassert(result == CL_SUCCESS);\n\n\t\t\treturn Event { signalEvent };\n\t\t}\n\n\tprivate:\n\n\t\ttemplate <Info info>\n\t\tstruct InfoResult;\n\t};\n\n\ttemplate <>\n\tstruct CommandQueue::InfoResult<CommandQueue::Info::ReferenceCount>\n\t{\n\t\tstatic cl_uint\n\t\tFromBytes (const std::vector<std::byte>& infoBytes);\n\t};\n\n\ttemplate <>\n\tstruct CommandQueue::InfoResult<CommandQueue::Info::Properties>\n\t{\n\t\tstatic CommandQueue::Properties\n\t\tFromBytes (const std::vector<std::byte>& infoBytes);\n\t};\n}\n\n#endif\n", "meta": {"hexsha": "bb6a0acd45839137d8bee1097dfd298cf493f87d", "size": 5497, "ext": "h", "lang": "C", "max_stars_repo_path": "cl/include/cl/CommandQueue.h", "max_stars_repo_name": "mtezych/cpp", "max_stars_repo_head_hexsha": "05c1b85eb89117a9b406f3f32470367937331614", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cl/include/cl/CommandQueue.h", "max_issues_repo_name": "mtezych/cpp", "max_issues_repo_head_hexsha": "05c1b85eb89117a9b406f3f32470367937331614", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cl/include/cl/CommandQueue.h", "max_forks_repo_name": "mtezych/cpp", "max_forks_repo_head_hexsha": "05c1b85eb89117a9b406f3f32470367937331614", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-12-21T00:31:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-14T23:16:23.000Z", "avg_line_length": 24.7612612613, "max_line_length": 78, "alphanum_fraction": 0.7143896671, "num_tokens": 1363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06754669301670264, "lm_q2_score": 0.021948255594140556, "lm_q1q2_score": 0.0014825320828695387}}
{"text": "//\n// Copyright (C) 2019 Assured Information Security, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n///\n/// @file bfgsl.h\n///\n\n#ifndef BFGSL_H\n#define BFGSL_H\n\n#if defined(__clang__) || defined(__GNUC__)\n#pragma GCC system_header\n#endif\n\n#include <string.h>\n\n/// @cond\n\n#define concat1(a,b) a ## b\n#define concat2(a,b) concat1(a,b)\n#define ___ concat2(dont_care, __COUNTER__)\n\n/// @endcond\n\n#ifndef NEED_GSL_LITE\n\n#include <gsl/gsl>\n\nnamespace gsl\n{\n\n/// @cond\n\n#define expects(cond) Expects(cond)\n#define ensures(cond) Ensures(cond)\n\ntemplate <class F>\nclass final_act_success\n{\npublic:\n    explicit final_act_success(F f) noexcept : f_(std::move(f)), invoke_(true) {}\n\n    final_act_success(final_act_success &&other) noexcept : f_(std::move(other.f_)), invoke_(other.invoke_)\n    {\n        other.invoke_ = false;\n    }\n\n    final_act_success(const final_act_success &) = delete;\n    final_act_success &operator=(const final_act_success &) = delete;\n\n    ~final_act_success() noexcept\n    {\n        if (std::uncaught_exception()) {\n            return;\n        }\n\n        if (invoke_) { f_(); }\n    }\n\nprivate:\n    F f_;\n    bool invoke_;\n};\n\ntemplate <class F>\nclass final_act_failure\n{\npublic:\n    explicit final_act_failure(F f) noexcept : f_(std::move(f)), invoke_(true) {}\n\n    final_act_failure(final_act_failure &&other) noexcept : f_(std::move(other.f_)), invoke_(other.invoke_)\n    {\n        other.invoke_ = false;\n    }\n\n    final_act_failure(const final_act_failure &) = delete;\n    final_act_failure &operator=(const final_act_failure &) = delete;\n\n    ~final_act_failure() noexcept\n    {\n        if (!std::uncaught_exception()) {\n            return;\n        }\n\n        if (invoke_) { f_(); }\n    }\n\nprivate:\n    F f_;\n    bool invoke_;\n};\n\ntemplate <class F>\ninline final_act_success<F> on_success(const F &f) noexcept\n{\n    return final_act_success<F>(f);\n}\n\ntemplate <class F>\ninline final_act_success<F> on_success(F &&f) noexcept\n{\n    return final_act_success<F>(std::forward<F>(f));\n}\n\ntemplate <class F>\ninline final_act_failure<F> on_failure(const F &f) noexcept\n{\n    return final_act_failure<F>(f);\n}\n\ntemplate <class F>\ninline final_act_failure<F> on_failure(F &&f) noexcept\n{\n    return final_act_failure<F>(std::forward<F>(f));\n}\n\n/// @endcond\n\n/// Memset\n///\n/// Same as std::memset, but for spans\n///\n/// @param dst The span to memset\n/// @param val The value to set the span to\n/// @return Returns dst\n///\ntemplate<class DstElementType, std::ptrdiff_t DstExtent, class T>\nauto memset(span<DstElementType, DstExtent> dst, T val)\n{\n    expects(dst.size() > 0);\n\n    return std::memset(\n               dst.data(),\n               static_cast<int>(val),\n               static_cast<std::size_t>(dst.size())\n           );\n}\n\n}\n\n#else\n\n#ifdef NEED_STD_LITE\n#include <bfstd.h>\n#endif\n\n/// @cond\n\n#if defined(__clang__) || defined(__GNUC__)\n#define gsl_likely(x) __builtin_expect(!!(x), 1)\n#define gsl_unlikely(x) __builtin_expect(!!(x), 0)\n#else\n#define gsl_likely(x) (x)\n#define gsl_unlikely(x) (x)\n#endif\n\n#ifndef GSL_ABORT\n#define GSL_ABORT abort\n#endif\n\n#define expects(cond)                                                                              \\\n    if (gsl_unlikely(!(cond))) {                                                                   \\\n        GSL_ABORT();                                                                               \\\n    }\n#define ensures(cond)                                                                              \\\n    if (gsl_unlikely(!(cond))) {                                                                   \\\n        GSL_ABORT();                                                                               \\\n    }\n\n/// @endcond\n\nnamespace gsl\n{\n\n/// Narrow Cast\n///\n/// A rename of static_cast to indicate a narrow (e.g. 64bit to 32bit)\n///\n/// @param u the value to narrow\n/// @return static_cast<T>(u)\n///\ntemplate<class T, class U>\ninline constexpr T\nnarrow_cast(U &&u) noexcept\n{\n    return static_cast<T>(std::forward<U>(u));\n}\n\n/// At\n///\n/// Returns a reference to an element in an array given an index. Unlike\n/// the [] operator, if the indexis out-of-bounds, an exception is thrown,\n/// or std::terminate() is called.\n///\n/// @param arr the array\n/// @param index the index of the element to retrieve.\n/// @return a reference to\n///\ntemplate<class T, size_t N, class I>\nconstexpr T &\nat(T(&arr)[N], I index)\n{\n    expects(index >= 0 && index < narrow_cast<I>(N));\n    return arr[static_cast<size_t>(index)];\n}\n\n/// At\n///\n/// Returns a reference to an element in an array given an index. Unlike\n/// the [] operator, if the indexis out-of-bounds, an exception is thrown,\n/// or std::terminate() is called.\n///\n/// @param arr the array\n/// @param index the index of the element to retrieve.\n/// @return a reference to\n///\ntemplate<class T, size_t N, class I>\nconst constexpr T &\nat(const T(&arr)[N], I index)\n{\n    expects(index >= 0 && index < narrow_cast<I>(N));\n    return arr[static_cast<size_t>(index)];\n}\n\n/// At\n///\n/// Returns a reference to an element in an array given an index. Unlike\n/// the [] operator, if the indexis out-of-bounds, an exception is thrown,\n/// or std::terminate() is called.\n///\n/// @param arr the array\n/// @param N the size of the array\n/// @param index the index of the element to retrieve.\n/// @return a reference to\n///\ntemplate<class T, class I>\nconstexpr T &\nat(T *arr, size_t N, I index)\n{\n    expects(index >= 0 && index < narrow_cast<I>(N));\n    return arr[static_cast<size_t>(index)];\n}\n\n/// At\n///\n/// Returns a reference to an element in an array given an index. Unlike\n/// the [] operator, if the indexis out-of-bounds, an exception is thrown,\n/// or std::terminate() is called.\n///\n/// @param arr the array\n/// @param N the size of the array\n/// @param index the index of the element to retrieve.\n/// @return a reference to\n///\ntemplate<class T, class I>\nconst constexpr T &\nat(const T *arr, size_t N, I index)\n{\n    expects(index >= 0 && index < narrow_cast<I>(N));\n    return arr[static_cast<size_t>(index)];\n}\n\n}\n\n#endif\n\n#endif\n", "meta": {"hexsha": "7367805e985a85e20757980c61e52345071518d9", "size": 7105, "ext": "h", "lang": "C", "max_stars_repo_path": "bfsdk/include/bfgsl.h", "max_stars_repo_name": "chp-io/hypervisor", "max_stars_repo_head_hexsha": "7c1dce35e9e54601de1c4655565fde803ab446f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-03-28T18:31:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T07:51:29.000Z", "max_issues_repo_path": "bfsdk/include/bfgsl.h", "max_issues_repo_name": "chp-io/hypervisor", "max_issues_repo_head_hexsha": "7c1dce35e9e54601de1c4655565fde803ab446f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2017-11-07T00:25:25.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-14T18:37:18.000Z", "max_forks_repo_path": "bfsdk/include/bfgsl.h", "max_forks_repo_name": "chp-io/hypervisor", "max_forks_repo_head_hexsha": "7c1dce35e9e54601de1c4655565fde803ab446f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-05-21T22:57:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-17T15:04:38.000Z", "avg_line_length": 24.8426573427, "max_line_length": 107, "alphanum_fraction": 0.6280084448, "num_tokens": 1691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.04146227152697139, "lm_q2_score": 0.03567855126224297, "lm_q1q2_score": 0.001479313780124086}}
{"text": "#pragma once\n/*For Engine Only*/\n//#include <glad\\glad.h>\n//#include <GLFW\\glfw3.h>\n//#include <gsl\\gsl>\n//#include <SOIL2.h>\n//#include <imgui.h>\n//#include <glm\\glm.hpp>\n//#include <spdlog\\spdlog.h>\n//\n///*Logger System*/\n//#include \"BooErEngine\\Utils\\Log.h\"\n//\n///*Event's System*/\n//#include \"BooErEngine\\Events\\Event.h\"\n//#include \"BooErEngine\\Events\\AppEvent.h\"\n//\n///* Layer System*/\n//#include \"BooErEngine\\Layers\\LayerSatck.h\"\n//\n///* InputMgr */\n//#include \"BooErEngine\\ImputMgr.h\"\n//#include \"BooErEngine\\Platforms\\Windows\\WindowsInputMgr.h\"\n\n\n\n\n", "meta": {"hexsha": "01ff15aa2d012a7956cba2114372a9d0c97b153e", "size": 557, "ext": "h", "lang": "C", "max_stars_repo_path": "BooErEngine/src/IncEngine.h", "max_stars_repo_name": "Concarster/booErEngine", "max_stars_repo_head_hexsha": "b2f390cbd5f7ec498307383d540f1381a7e634a6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "BooErEngine/src/IncEngine.h", "max_issues_repo_name": "Concarster/booErEngine", "max_issues_repo_head_hexsha": "b2f390cbd5f7ec498307383d540f1381a7e634a6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BooErEngine/src/IncEngine.h", "max_forks_repo_name": "Concarster/booErEngine", "max_forks_repo_head_hexsha": "b2f390cbd5f7ec498307383d540f1381a7e634a6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.8928571429, "max_line_length": 60, "alphanum_fraction": 0.6750448833, "num_tokens": 176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07369626563712976, "lm_q2_score": 0.02002344172805237, "lm_q1q2_score": 0.0014756528805601361}}
{"text": "#pragma once\n\n#include <boost/variant.hpp>\n//#include <gsl/span>\n#include <gsl/gsl>\n#include <boost/system/system_error.hpp>\n#include <boost/asio/read.hpp>\n#include <boost/asio/write.hpp>\n\nnamespace mothbus\n{\n\ttemplate<class ...T>\n\tusing variant = boost::variant<T...>;\n\n\n\ttemplate<class T>//, std::ptrdiff_t Extent=gsl::dynamic_extent>\n\tusing span = gsl::span<T>;//, Extent>;\n\n\tusing byte = gsl::byte;\n\n\n\ttemplate <typename SyncWriteStream, typename ConstBufferSequence>\n\tinline std::size_t write(SyncWriteStream& s, const ConstBufferSequence& buffers)\n\t{\n\t\treturn boost::asio::write(s, buffers);\n\t}\n\n\ttemplate <typename SyncWriteStream, typename ConstBufferSequence, typename ErrorCode>\n\tinline std::size_t write(SyncWriteStream& s, const ConstBufferSequence& buffers, ErrorCode& ec)\n\t{\n\t\treturn boost::asio::write(s, buffers, ec);\n\t}\n\n\ttemplate <typename SyncReadStream, typename MutableBufferSequence>\n\tinline std::size_t read(SyncReadStream& s, const MutableBufferSequence& buffers)\n\t{\n\t\treturn boost::asio::read(s, buffers);\n\t}\n\n\ttemplate <typename SyncReadStream, typename MutableBufferSequence, typename ErrorCode>\n\tinline std::size_t read(SyncReadStream& s, const MutableBufferSequence& buffers,  ErrorCode& ec)\n\t{\n\t\treturn boost::asio::read(s, buffers, ec);\n\t}\n\n\ttemplate <typename SyncReadStream, typename MutableBufferSequence, typename ReadHandler>\n\tinline void async_read(SyncReadStream& s, const MutableBufferSequence& buffers, ReadHandler&& handler)\n\t{\n\t\tboost::asio::async_read(s, buffers, std::forward<ReadHandler>(handler));\n\t}\n\n\tclass modbus_exception// : public std::runtime_error\n\t{\n\tpublic:\n\t\tmodbus_exception(int error_code):\n\t\terror_code(error_code)\n\t\t{}\n\n\t\tint error_code;\n\t};\n}\n", "meta": {"hexsha": "f34f0930f2ee4b33eaa1b17122bc711112fcbfc9", "size": 1705, "ext": "h", "lang": "C", "max_stars_repo_path": "include/mothbus/mothbus.h", "max_stars_repo_name": "ChrisBFX/mothbus", "max_stars_repo_head_hexsha": "0bd94c2878b4be04c968c2a60835b6aa3a085516", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-05-02T10:39:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-07T14:32:25.000Z", "max_issues_repo_path": "include/mothbus/mothbus.h", "max_issues_repo_name": "ChrisBFX/mothbus", "max_issues_repo_head_hexsha": "0bd94c2878b4be04c968c2a60835b6aa3a085516", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/mothbus/mothbus.h", "max_forks_repo_name": "ChrisBFX/mothbus", "max_forks_repo_head_hexsha": "0bd94c2878b4be04c968c2a60835b6aa3a085516", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5, "max_line_length": 103, "alphanum_fraction": 0.7530791789, "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07807816943541052, "lm_q2_score": 0.018833129511828087, "lm_q1q2_score": 0.0014704562770235436}}
{"text": "#pragma once\n#define VULKAN_H_ 1\n#include <vulkan/vk_platform.h>\n#include <vulkan/vulkan_core.h>\n\n#if defined(VK_USE_PLATFORM_WIN32_KHR)\n// This is to avoid including Windows.h\n#ifndef DECLARE_HANDLE\nusing HANDLE = void*;\n\n#define DECLARE_HANDLE(name) struct name##__; typedef struct name##__ *name\nDECLARE_HANDLE(HINSTANCE);\nDECLARE_HANDLE(HMONITOR);\nDECLARE_HANDLE(HWND);\n#undef DECLARE_HANDLE\n\nstruct _SECURITY_ATTRIBUTES;\nusing SECURITY_ATTRIBUTES = _SECURITY_ATTRIBUTES;\n\nusing LPCWSTR = const wchar_t*;\nusing PCWSTR = const wchar_t*;\nusing DWORD = unsigned long; // NOLINT(google-runtime-int)\n#endif\n\n// ReSharper disable once CppUnusedIncludeDirective\n#include <vulkan/vulkan_win32.h>\n#endif\n\n#if defined(VK_USE_PLATFORM_XCB_KHR)\ntypedef struct xcb_connection_t xcb_connection_t;\ntypedef uint32_t xcb_window_t;\ntypedef uint32_t xcb_visualid_t;\n\n// ReSharper disable once CppUnusedIncludeDirective\n#include <vulkan/vulkan_xcb.h>\n#endif\n\n#if defined(VK_USE_PLATFORM_XLIB_KHR)\ntypedef struct _XDisplay Display;\ntypedef unsigned long XID;\ntypedef XID Window;\ntypedef unsigned long VisualID;\n\n// ReSharper disable once CppUnusedIncludeDirective\n#include <vulkan/vulkan_xlib.h>\n#endif\n\n#if defined(VK_USE_PLATFORM_XLIB_XRANDR_EXT)\ntypedef struct _XDisplay Display;\ntypedef unsigned long XID;\ntypedef XID Window;\ntypedef unsigned long VisualID;\ntypedef XID RROutput;\n\n// ReSharper disable once CppUnusedIncludeDirective\n#include <vulkan/vulkan_xlib_xrandr.h>\n#endif\n\n#include \"Config.h\"\n\n#include <vulkan/vk_icd.h>\n\n#include <gsl/gsl>\n\n#if !defined(_MSC_VER)\n#define __debugbreak() __asm__(\"int3\")\n\ninline void strcpy_s(char* destination, const char* source)\n{\n\tstrcpy(destination, source);\n}\n#endif\n#define TODO_ERROR() if (1) { __debugbreak(); abort(); } else (void)0\n#define FATAL_ERROR() if (1) { __debugbreak(); abort(); } else (void)0\n\n#if defined(_MSC_VER)\n#define CP_DLL_EXPORT __declspec(dllexport)\n#else\n#define CP_DLL_EXPORT\n#endif\n\n#pragma warning(push)\n#pragma warning(disable: 26490 26474 26408 26409)\n\nstruct DeviceMemory;\n\nclass Buffer;\nclass BufferView;\nclass CommandBuffer;\nclass CommandPool;\nclass CompiledShaderModule;\nclass ComputePipeline;\nclass DescriptorPool;\nclass DescriptorSet;\nclass DescriptorSetLayout;\nclass Device;\nclass Event;\nclass Fence;\nclass Framebuffer;\nclass GraphicsPipeline;\nclass Image;\nclass ImageView;\nclass Instance;\nclass PhysicalDevice;\nclass Pipeline;\nclass PipelineCache;\nclass PipelineLayout;\nclass QueryPool;\nclass Queue;\nclass RenderPass;\nclass Sampler;\nclass Semaphore;\nclass ShaderModule;\n\n#if defined(VK_NV_ray_tracing)\nclass RayTracingPipeline;\n#endif\n\ntemplate<typename LocalType>\nstruct VulkanTypeHelper;\n\n#define VK_TYPE_HELPER(VulkanType, LocalType, NonDispatchable) template<> struct VulkanTypeHelper<LocalType> { static constexpr auto IsNonDispatchable = NonDispatchable; using Type = VulkanType; }\n\nVK_TYPE_HELPER(VkInstance, Instance, false);\n\nVK_TYPE_HELPER(VkPhysicalDevice, PhysicalDevice, false);\n\nVK_TYPE_HELPER(VkDevice, Device, false);\n\nVK_TYPE_HELPER(VkQueue, Queue, false);\n\nVK_TYPE_HELPER(VkSemaphore, Semaphore, true);\n\nVK_TYPE_HELPER(VkCommandBuffer, CommandBuffer, false);\n\nVK_TYPE_HELPER(VkFence, Fence, true);\n\nVK_TYPE_HELPER(VkDeviceMemory, DeviceMemory, true);\n\nVK_TYPE_HELPER(VkBuffer, Buffer, true);\n\nVK_TYPE_HELPER(VkImage, Image, true);\n\nVK_TYPE_HELPER(VkEvent, Event, true);\n\nVK_TYPE_HELPER(VkQueryPool, QueryPool, true);\n\nVK_TYPE_HELPER(VkBufferView, BufferView, true);\n\nVK_TYPE_HELPER(VkImageView, ImageView, true);\n\nVK_TYPE_HELPER(VkShaderModule, ShaderModule, true);\n\nVK_TYPE_HELPER(VkPipelineCache, PipelineCache, true);\n\nVK_TYPE_HELPER(VkPipelineLayout, PipelineLayout, true);\n\nVK_TYPE_HELPER(VkRenderPass, RenderPass, true);\n\nVK_TYPE_HELPER(VkPipeline, Pipeline, true);\n\nVK_TYPE_HELPER(VkPipeline, ComputePipeline, true);\n\nVK_TYPE_HELPER(VkPipeline, GraphicsPipeline, true);\n\n#if defined(VK_NV_ray_tracing)\nVK_TYPE_HELPER(VkPipeline, RayTracingPipeline, true);\n#endif\n\nVK_TYPE_HELPER(VkDescriptorSetLayout, DescriptorSetLayout, true);\n\nVK_TYPE_HELPER(VkSampler, Sampler, true);\n\nVK_TYPE_HELPER(VkDescriptorPool, DescriptorPool, true);\n\nVK_TYPE_HELPER(VkDescriptorSet, DescriptorSet, true);\n\nVK_TYPE_HELPER(VkFramebuffer, Framebuffer, true);\n\nVK_TYPE_HELPER(VkCommandPool, CommandPool, true);\n\n#if defined(VK_VERSION_1_1)\nclass DescriptorUpdateTemplate;\nclass SamplerYcbcrConversion;\n\nVK_TYPE_HELPER(VkSamplerYcbcrConversion, SamplerYcbcrConversion, true);\n\nVK_TYPE_HELPER(VkDescriptorUpdateTemplate, DescriptorUpdateTemplate, true);\n#endif\n\n#if defined(VK_KHR_surface)\nVK_TYPE_HELPER(VkSurfaceKHR, VkIcdSurfaceBase, true);\n\n#if defined(VK_USE_PLATFORM_WIN32_KHR)\nVK_TYPE_HELPER(VkSurfaceKHR, VkIcdSurfaceWin32, true);\n#endif\n\n#if defined(VK_USE_PLATFORM_XCB_KHR)\nVK_TYPE_HELPER(VkSurfaceKHR, VkIcdSurfaceXcb, true);\n#endif\n\n#if defined(VK_USE_PLATFORM_XLIB_KHR)\nVK_TYPE_HELPER(VkSurfaceKHR, VkIcdSurfaceXlib, true);\n#endif\n#endif\n\n#if defined(VK_KHR_swapchain)\nclass Swapchain;\nVK_TYPE_HELPER(VkSwapchainKHR, Swapchain, true);\n#endif\n\n#if defined(VK_KHR_display)\nclass VDisplay;\nclass DisplayMode;\n\nVK_TYPE_HELPER(VkDisplayKHR, VDisplay, true);\nVK_TYPE_HELPER(VkDisplayModeKHR, DisplayMode, true);\n#endif\n\n#if defined(VK_EXT_debug_report)\nclass DebugReportCallback;\nVK_TYPE_HELPER(VkDebugReportCallbackEXT, DebugReportCallback, true);\n#endif\n\n#if defined(VK_NVX_device_generated_commands)\nclass IndirectCommandsLayout;\nclass ObjectTable;\n\nVK_TYPE_HELPER(VkObjectTableNVX, ObjectTable, true);\n\nVK_TYPE_HELPER(VkIndirectCommandsLayoutNVX, IndirectCommandsLayout, true);\n#endif\n\n#if defined(VK_EXT_debug_utils)\nclass DebugUtilsMessenger;\nVK_TYPE_HELPER(VkDebugUtilsMessengerEXT, DebugUtilsMessenger, true);\n#endif\n\n#if defined(VK_EXT_validation_cache)\nclass ValidationCache;\nVK_TYPE_HELPER(VkValidationCacheEXT, ValidationCache, true);\n#endif\n\n#if defined(VK_NV_ray_tracing)\nclass AccelerationStructure;\nVK_TYPE_HELPER(VkAccelerationStructureNV, AccelerationStructure, true);\n#endif\n\n#if defined(VK_INTEL_performance_query)\nclass PerformanceConfiguration;\nVK_TYPE_HELPER(VkPerformanceConfigurationINTEL, PerformanceConfiguration, true);\n#endif\n\n#undef VK_TYPE_HELPER\n\ntemplate<typename T, class... Types>\nT* Allocate(const VkAllocationCallbacks* pAllocator, VkSystemAllocationScope allocationScope, Types&& ... args)\n{\n\tconstexpr auto size = VulkanTypeHelper<T>::IsNonDispatchable ? sizeof(T) : sizeof(T) + 16;\n\tconst auto data = pAllocator\n\t\t                  ? static_cast<uint8_t*>(pAllocator->pfnAllocation(pAllocator->pUserData, size, 16, allocationScope))\n\t\t                  : static_cast<uint8_t*>(malloc(size));\n\t\n\tif (!data)\n\t{\n\t\treturn nullptr;\n\t}\n\n\tif (VulkanTypeHelper<T>::IsNonDispatchable)\n\t{\n\t\treturn new(data) T(std::forward<Types>(args)...);\n\t}\n\n\t*static_cast<uintptr_t*>(static_cast<void*>(data)) = ICD_LOADER_MAGIC;\n\treturn new(data + 16) T(std::forward<Types>(args)...);\n}\n\ntemplate<typename T>\nvoid Free(T* value, const VkAllocationCallbacks* pAllocator) noexcept\n{\n\tvalue->OnDelete(pAllocator);\n\tvalue->~T();\n\tconst auto data = static_cast<uint8_t*>(static_cast<void*>(value)) - (VulkanTypeHelper<T>::IsNonDispatchable ? 0 : 16);\n\t\n\tif (pAllocator)\n\t{\n\t\tpAllocator->pfnFree(pAllocator->pUserData, data);\n\t}\n\telse\n\t{\n\t\tfree(data);\n\t}\n}\n\n#if defined(VK_USE_PLATFORM_WIN32_KHR)\ntemplate<>\ninline void Free(VkIcdSurfaceWin32* value, const VkAllocationCallbacks* pAllocator) noexcept\n{\n\tif (pAllocator)\n\t{\n\t\tpAllocator->pfnFree(pAllocator->pUserData, value);\n\t}\n\telse\n\t{\n\t\tfree(value);\n\t}\n}\n#endif\n\n#if defined(VK_USE_PLATFORM_XCB_KHR)\ntemplate<>\ninline void Free(VkIcdSurfaceXcb* value, const VkAllocationCallbacks* pAllocator) noexcept\n{\n\tif (pAllocator)\n\t{\n\t\tpAllocator->pfnFree(pAllocator->pUserData, value);\n\t}\n\telse\n\t{\n\t\tfree(value);\n\t}\n}\n#endif\n\n#if defined(VK_USE_PLATFORM_XLIB_KHR)\ntemplate<>\ninline void Free(VkIcdSurfaceXlib* value, const VkAllocationCallbacks* pAllocator) noexcept\n{\n\tif (pAllocator)\n\t{\n\t\tpAllocator->pfnFree(pAllocator->pUserData, value);\n\t}\n\telse\n\t{\n\t\tfree(value);\n\t}\n}\n#endif\n\ntemplate<bool IsNonDispatchable>\nvoid WrapVulkan(void* local, uint64_t* vulkan) noexcept;\n\ntemplate<bool IsNonDispatchable>\nvoid* UnwrapVulkan(uint64_t vulkanValue) noexcept;\n\ntemplate<>\ninline void WrapVulkan<false>(void* local, uint64_t* vulkan) noexcept\n{\n\tassert(local);\n\tassert(vulkan);\n\tconst auto data = static_cast<uint8_t*>(local);\n\t*vulkan = reinterpret_cast<uint64_t>(data - 16);\n}\n\ntemplate<>\ninline void* UnwrapVulkan<false>(uint64_t vulkanValue) noexcept\n{\n\tassert(vulkanValue);\n\treturn reinterpret_cast<void*>(vulkanValue + 16);\n}\n\ntemplate<>\ninline void WrapVulkan<true>(void* local, uint64_t* vulkan) noexcept\n{\n\tassert(local);\n\tassert(vulkan);\n\t*vulkan = reinterpret_cast<uint64_t>(local);\n}\n\ntemplate<>\ninline void* UnwrapVulkan<true>(uint64_t vulkanValue) noexcept\n{\n\tassert(vulkanValue);\n\treturn reinterpret_cast<void*>(vulkanValue);\n}\n\ntemplate<typename LocalType>\nvoid WrapVulkan(LocalType* local, typename VulkanTypeHelper<LocalType>::Type* vulkan) noexcept\n{\n\tWrapVulkan<VulkanTypeHelper<LocalType>::IsNonDispatchable>(local, reinterpret_cast<uint64_t*>(vulkan));\n}\n\ntemplate<typename LocalType>\nLocalType* UnwrapVulkan(typename VulkanTypeHelper<LocalType>::Type vulkanValue) noexcept\n{\n\treturn reinterpret_cast<LocalType*>(UnwrapVulkan<VulkanTypeHelper<LocalType>::IsNonDispatchable>(reinterpret_cast<uint64_t>(vulkanValue)));\n}\n#pragma warning(pop)\n\nconstexpr auto PI = 3.14159265358979323846;", "meta": {"hexsha": "bbe3d077fc884fd555e3740c60b4bcc1c2507036", "size": 9436, "ext": "h", "lang": "C", "max_stars_repo_path": "CPVulkanBase/Base.h", "max_stars_repo_name": "MatthewSmit/CPVulkan", "max_stars_repo_head_hexsha": "d96f2f6db4cbbabcc41c2023a48ec63d1950dec0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-13T00:47:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-13T00:47:05.000Z", "max_issues_repo_path": "CPVulkanBase/Base.h", "max_issues_repo_name": "MatthewSmit/CPVulkan", "max_issues_repo_head_hexsha": "d96f2f6db4cbbabcc41c2023a48ec63d1950dec0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CPVulkanBase/Base.h", "max_forks_repo_name": "MatthewSmit/CPVulkan", "max_forks_repo_head_hexsha": "d96f2f6db4cbbabcc41c2023a48ec63d1950dec0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1948717949, "max_line_length": 196, "alphanum_fraction": 0.7963119966, "num_tokens": 2366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07921033063001552, "lm_q2_score": 0.018546564546022264, "lm_q1q2_score": 0.0014690795097413473}}
{"text": "#pragma once\n\n#include \"icode_generator.h\"\n#include <halley/data_structures/hash_map.h>\n#include <gsl/gsl>\n#include \"halley/file/path.h\"\n\nnamespace YAML\n{\n\tclass Node;\n}\n\nnamespace Halley\n{\n\tclass ComponentSchema;\n\tclass SystemSchema;\n\tclass MessageSchema;\n\tclass CustomTypeSchema;\n\n\tclass Codegen\n\t{\n\t\tstruct Stats\n\t\t{\n\t\t\tint written = 0;\n\t\t\tint skipped = 0;\n\t\t\tstd::vector<Path> files;\n\t\t};\n\n\t\tstatic bool doNothing(float, String) { return true; }\n\n\tpublic:\n\t\tusing ProgressReporter = std::function<bool(float, String)>;\n\n\t\tstatic void run(Path inDir, Path outDir);\n\n\t\texplicit Codegen(bool verbose = false);\n\n\t\tvoid loadSources(std::vector<std::pair<String, gsl::span<const gsl::byte>>> files, ProgressReporter progress = &doNothing);\n\t\tvoid validate(ProgressReporter progress = &doNothing);\n\t\tvoid process();\n\t\tbool writeFile(Path path, const char* data, size_t dataSize, bool stub) const;\n\t\tvoid writeFiles(Path directory, const CodeGenResult& files, Stats& stats) const;\n\t\tstd::vector<Path> generateCode(Path directory, ProgressReporter progress = &doNothing);\n\n\tprivate:\n\t\tvoid addSource(String name, gsl::span<const gsl::byte> data);\n\t\tvoid addComponent(YAML::Node rootNode);\n\t\tvoid addSystem(YAML::Node rootNode);\n\t\tvoid addMessage(YAML::Node rootNode);\n\t\tvoid addType(YAML::Node rootNode);\n\t\tString getInclude(String typeName) const;\n\n\t\tbool verbose;\n\t\tHashMap<String, ComponentSchema> components;\n\t\tHashMap<String, SystemSchema> systems;\n\t\tHashMap<String, MessageSchema> messages;\n\t\tHashMap<String, CustomTypeSchema> types;\n\t};\n}", "meta": {"hexsha": "40011135ea81da0e8f1dd88ecae13dfd47c84c4d", "size": 1540, "ext": "h", "lang": "C", "max_stars_repo_path": "src/tools/tools/include/halley/tools/codegen/codegen.h", "max_stars_repo_name": "lye/halley", "max_stars_repo_head_hexsha": "16b6c9783e4b21377f902a9d02366c1f19450a21", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T20:23:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T20:23:45.000Z", "max_issues_repo_path": "src/tools/tools/include/halley/tools/codegen/codegen.h", "max_issues_repo_name": "lye/halley", "max_issues_repo_head_hexsha": "16b6c9783e4b21377f902a9d02366c1f19450a21", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tools/tools/include/halley/tools/codegen/codegen.h", "max_forks_repo_name": "lye/halley", "max_forks_repo_head_hexsha": "16b6c9783e4b21377f902a9d02366c1f19450a21", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1016949153, "max_line_length": 125, "alphanum_fraction": 0.7396103896, "num_tokens": 371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.0803574600126236, "lm_q2_score": 0.018264277082713255, "lm_q1q2_score": 0.001467670915333608}}
{"text": "#pragma once\n\n#include \"CesiumGltf/MetadataArrayView.h\"\n#include \"CesiumGltf/PropertyType.h\"\n#include \"CesiumGltf/PropertyTypeTraits.h\"\n\n#include <gsl/span>\n\n#include <cassert>\n#include <cstddef>\n#include <cstdint>\n#include <string_view>\n#include <type_traits>\n\nnamespace CesiumGltf {\n/**\n * @brief Indicates the status of a property view.\n *\n * The {@link MetadataPropertyView} constructor always completes successfully. However,\n * it may not always reflect the actual content of the {@link FeatureTableProperty}, but\n * instead indicate that its {@link MetadataPropertyView::size} is 0. This enumeration\n * provides the reason.\n */\nenum class MetadataPropertyViewStatus {\n  /**\n   * @brief This property view is valid and ready to use.\n   */\n  Valid,\n\n  /**\n   * @brief This property view does not exist in the FeatureTable.\n   */\n  InvalidPropertyNotExist,\n\n  /**\n   * @brief This property view does not have a correct type with what is\n   * specified in {@link ClassProperty::type}.\n   */\n  InvalidTypeMismatch,\n\n  /**\n   * @brief This property view does not have a valid value buffer view index.\n   */\n  InvalidValueBufferViewIndex,\n\n  /**\n   * @brief This array property view does not have a valid array offset buffer\n   * view index.\n   */\n  InvalidArrayOffsetBufferViewIndex,\n\n  /**\n   * @brief This string property view does not have a valid string offset buffer\n   * view index.\n   */\n  InvalidStringOffsetBufferViewIndex,\n\n  /**\n   * @brief This property view has a valid value buffer view index, but buffer\n   * view specifies an invalid buffer index\n   */\n  InvalidValueBufferIndex,\n\n  /**\n   * @brief This property view has a valid array string buffer view index, but\n   * buffer view specifies an invalid buffer index\n   */\n  InvalidArrayOffsetBufferIndex,\n\n  /**\n   * @brief This property view has a valid string offset buffer view index, but\n   * buffer view specifies an invalid buffer index\n   */\n  InvalidStringOffsetBufferIndex,\n\n  /**\n   * @brief This property view has buffer view's offset not aligned by 8 bytes\n   */\n  InvalidBufferViewNotAligned8Bytes,\n\n  /**\n   * @brief This property view has an out-of-bound buffer view\n   */\n  InvalidBufferViewOutOfBound,\n\n  /**\n   * @brief This property view has an invalid buffer view's length which is not\n   * a multiple of the size of its type or offset type\n   */\n  InvalidBufferViewSizeNotDivisibleByTypeSize,\n\n  /**\n   * @brief This property view has an invalid buffer view's length which cannot\n   * fit all the instances of the feature table\n   */\n  InvalidBufferViewSizeNotFitInstanceCount,\n\n  /**\n   * @brief This array property view has both component count and offset buffer\n   * view\n   */\n  InvalidArrayComponentCountAndOffsetBufferCoexist,\n\n  /**\n   * @brief This array property view doesn't have either component count or\n   * offset buffer view\n   */\n  InvalidArrayComponentCountOrOffsetBufferNotExist,\n\n  /**\n   * @brief This property view have an unknown offset type\n   */\n  InvalidOffsetType,\n\n  /**\n   * @brief This property view has offset values not sorted ascendingly\n   */\n  InvalidOffsetValuesNotSortedAscending,\n\n  /**\n   * @brief This property view has an offset point to an out of bound value\n   */\n  InvalidOffsetValuePointsToOutOfBoundBuffer\n};\n\n/**\n * @brief A view on the data of the FeatureTableProperty\n *\n * It provides utility to retrieve the actual data stored in the\n * {@link FeatureTableProperty::bufferView} like an array of elements.\n * Data of each instance can be accessed through the {@link get(int64_t instance)} method\n *\n * @param ElementType must be uin8_t, int8_t, uint16_t, int16_t,\n * uint32_t, int32_t, uint64_t, int64_t, float, double, bool, std::string_view,\n * and MetadataArrayView<T> with T must be one of the types mentioned above\n */\ntemplate <typename ElementType> class MetadataPropertyView {\npublic:\n  /**\n   * @brief Constructs a new instance viewing a non-existent property.\n   */\n  MetadataPropertyView()\n      : _status{MetadataPropertyViewStatus::InvalidPropertyNotExist},\n        _valueBuffer{},\n        _arrayOffsetBuffer{},\n        _stringOffsetBuffer{},\n        _offsetType{},\n        _offsetSize{},\n        _componentCount{},\n        _instanceCount{},\n        _normalized{} {}\n\n  /**\n   * @brief Construct a new instance pointing to the data specified by\n   * FeatureTableProperty\n   * @param valueBuffer The raw buffer specified by {@link FeatureTableProperty::bufferView}\n   * @param arrayOffsetBuffer The raw buffer specified by {@link FeatureTableProperty::arrayOffsetBufferView}\n   * @param stringOffsetBuffer The raw buffer specified by {@link FeatureTableProperty::stringOffsetBufferView}\n   * @param offsetType The offset type of the arrayOffsetBuffer and stringOffsetBuffer that is specified by {@link FeatureTableProperty::offsetType}\n   * @param componentCount The number of elements for fixed array value which is specified by {@link FeatureTableProperty::componentCount}\n   * @param instanceCount The number of instances specified by {@link FeatureTable::count}\n   * @param normalized Whether this property has a normalized integer type.\n   */\n  MetadataPropertyView(\n      MetadataPropertyViewStatus status,\n      gsl::span<const std::byte> valueBuffer,\n      gsl::span<const std::byte> arrayOffsetBuffer,\n      gsl::span<const std::byte> stringOffsetBuffer,\n      PropertyType offsetType,\n      int64_t componentCount,\n      int64_t instanceCount,\n      bool normalized) noexcept\n      : _status{status},\n        _valueBuffer{valueBuffer},\n        _arrayOffsetBuffer{arrayOffsetBuffer},\n        _stringOffsetBuffer{stringOffsetBuffer},\n        _offsetType{offsetType},\n        _offsetSize{getOffsetSize(offsetType)},\n        _componentCount{componentCount},\n        _instanceCount{instanceCount},\n        _normalized{normalized} {}\n\n  /**\n   * @brief Gets the status of this property view.\n   *\n   * Indicates whether the view accurately reflects the property's data, or\n   * whether an error occurred.\n   */\n  MetadataPropertyViewStatus status() const noexcept { return _status; }\n\n  /**\n   * @brief Get the value of an instance of the FeatureTable.\n   * @param instance The instance index\n   * @return The value of the instance\n   */\n  ElementType get(int64_t instance) const noexcept {\n    assert(\n        _status == MetadataPropertyViewStatus::Valid &&\n        \"Check the status() first to make sure view is valid\");\n    assert(\n        size() > 0 &&\n        \"Check the size() of the view to make sure it's not empty\");\n    assert(instance >= 0 && \"instance index must be positive\");\n\n    if constexpr (IsMetadataNumeric<ElementType>::value) {\n      return getNumeric(instance);\n    }\n\n    if constexpr (IsMetadataBoolean<ElementType>::value) {\n      return getBoolean(instance);\n    }\n\n    if constexpr (IsMetadataString<ElementType>::value) {\n      return getString(instance);\n    }\n\n    if constexpr (IsMetadataNumericArray<ElementType>::value) {\n      return getNumericArray<typename MetadataArrayType<ElementType>::type>(\n          instance);\n    }\n\n    if constexpr (IsMetadataBooleanArray<ElementType>::value) {\n      return getBooleanArray(instance);\n    }\n\n    if constexpr (IsMetadataStringArray<ElementType>::value) {\n      return getStringArray(instance);\n    }\n  }\n\n  /**\n   * @brief Get the number of instances in the FeatureTable\n   * @return The number of instances in the FeatureTable\n   */\n  int64_t size() const noexcept { return _instanceCount; }\n\n  /**\n   * @brief Get the component count of this property. Only applicable when the\n   * property is an array type.\n   *\n   * @return The component count of this property.\n   */\n  int64_t getComponentCount() const noexcept { return _componentCount; }\n\n  /**\n   * @brief Whether this property has a normalized integer type.\n   *\n   * @return Whether this property has a normalized integer type.\n   */\n  bool isNormalized() const noexcept { return _normalized; }\n\nprivate:\n  ElementType getNumeric(int64_t instance) const noexcept {\n    return reinterpret_cast<const ElementType*>(_valueBuffer.data())[instance];\n  }\n\n  bool getBoolean(int64_t instance) const noexcept {\n    const int64_t byteIndex = instance / 8;\n    const int64_t bitIndex = instance % 8;\n    const int bitValue =\n        static_cast<int>(_valueBuffer[byteIndex] >> bitIndex) & 1;\n    return bitValue == 1;\n  }\n\n  std::string_view getString(int64_t instance) const noexcept {\n    const size_t currentOffset =\n        getOffsetFromOffsetBuffer(instance, _stringOffsetBuffer, _offsetType);\n    const size_t nextOffset = getOffsetFromOffsetBuffer(\n        instance + 1,\n        _stringOffsetBuffer,\n        _offsetType);\n    return std::string_view(\n        reinterpret_cast<const char*>(_valueBuffer.data() + currentOffset),\n        (nextOffset - currentOffset));\n  }\n\n  template <typename T>\n  MetadataArrayView<T> getNumericArray(int64_t instance) const noexcept {\n    if (_componentCount > 0) {\n      const gsl::span<const std::byte> vals(\n          _valueBuffer.data() + instance * _componentCount * sizeof(T),\n          _componentCount * sizeof(T));\n      return MetadataArrayView<T>{vals};\n    }\n\n    const size_t currentOffset =\n        getOffsetFromOffsetBuffer(instance, _arrayOffsetBuffer, _offsetType);\n    const size_t nextOffset = getOffsetFromOffsetBuffer(\n        instance + 1,\n        _arrayOffsetBuffer,\n        _offsetType);\n    const gsl::span<const std::byte> vals(\n        _valueBuffer.data() + currentOffset,\n        (nextOffset - currentOffset));\n    return MetadataArrayView<T>{vals};\n  }\n\n  MetadataArrayView<std::string_view>\n  getStringArray(int64_t instance) const noexcept {\n    if (_componentCount > 0) {\n      const gsl::span<const std::byte> offsetVals(\n          _stringOffsetBuffer.data() + instance * _componentCount * _offsetSize,\n          (_componentCount + 1) * _offsetSize);\n      return MetadataArrayView<std::string_view>(\n          _valueBuffer,\n          offsetVals,\n          _offsetType,\n          _componentCount);\n    }\n\n    const size_t currentOffset =\n        getOffsetFromOffsetBuffer(instance, _arrayOffsetBuffer, _offsetType);\n    const size_t nextOffset = getOffsetFromOffsetBuffer(\n        instance + 1,\n        _arrayOffsetBuffer,\n        _offsetType);\n    const gsl::span<const std::byte> offsetVals(\n        _stringOffsetBuffer.data() + currentOffset,\n        (nextOffset - currentOffset + _offsetSize));\n    return MetadataArrayView<std::string_view>(\n        _valueBuffer,\n        offsetVals,\n        _offsetType,\n        (nextOffset - currentOffset) / _offsetSize);\n  }\n\n  MetadataArrayView<bool> getBooleanArray(int64_t instance) const noexcept {\n    if (_componentCount > 0) {\n      const size_t offsetBits = _componentCount * instance;\n      const size_t nextOffsetBits = _componentCount * (instance + 1);\n      const gsl::span<const std::byte> buffer(\n          _valueBuffer.data() + offsetBits / 8,\n          (nextOffsetBits / 8 - offsetBits / 8 + 1));\n      return MetadataArrayView<bool>(buffer, offsetBits % 8, _componentCount);\n    }\n\n    const size_t currentOffset =\n        getOffsetFromOffsetBuffer(instance, _arrayOffsetBuffer, _offsetType);\n    const size_t nextOffset = getOffsetFromOffsetBuffer(\n        instance + 1,\n        _arrayOffsetBuffer,\n        _offsetType);\n\n    const size_t totalBits = nextOffset - currentOffset;\n    const gsl::span<const std::byte> buffer(\n        _valueBuffer.data() + currentOffset / 8,\n        (nextOffset / 8 - currentOffset / 8 + 1));\n    return MetadataArrayView<bool>(buffer, currentOffset % 8, totalBits);\n  }\n\n  static int64_t getOffsetSize(PropertyType offsetType) noexcept {\n    switch (offsetType) {\n    case CesiumGltf::PropertyType::Uint8:\n      return sizeof(uint8_t);\n    case CesiumGltf::PropertyType::Uint16:\n      return sizeof(uint16_t);\n    case CesiumGltf::PropertyType::Uint32:\n      return sizeof(uint32_t);\n    case CesiumGltf::PropertyType::Uint64:\n      return sizeof(uint64_t);\n    default:\n      return 0;\n    }\n  }\n\n  static size_t getOffsetFromOffsetBuffer(\n      size_t instance,\n      const gsl::span<const std::byte>& offsetBuffer,\n      PropertyType offsetType) noexcept {\n    switch (offsetType) {\n    case PropertyType::Uint8: {\n      assert(instance < offsetBuffer.size() / sizeof(uint8_t));\n      const uint8_t offset = *reinterpret_cast<const uint8_t*>(\n          offsetBuffer.data() + instance * sizeof(uint8_t));\n      return static_cast<size_t>(offset);\n    }\n    case PropertyType::Uint16: {\n      assert(instance < offsetBuffer.size() / sizeof(uint16_t));\n      const uint16_t offset = *reinterpret_cast<const uint16_t*>(\n          offsetBuffer.data() + instance * sizeof(uint16_t));\n      return static_cast<size_t>(offset);\n    }\n    case PropertyType::Uint32: {\n      assert(instance < offsetBuffer.size() / sizeof(uint32_t));\n      const uint32_t offset = *reinterpret_cast<const uint32_t*>(\n          offsetBuffer.data() + instance * sizeof(uint32_t));\n      return static_cast<size_t>(offset);\n    }\n    case PropertyType::Uint64: {\n      assert(instance < offsetBuffer.size() / sizeof(uint64_t));\n      const uint64_t offset = *reinterpret_cast<const uint64_t*>(\n          offsetBuffer.data() + instance * sizeof(uint64_t));\n      return static_cast<size_t>(offset);\n    }\n    default:\n      assert(false && \"Offset type has unknown type\");\n      return 0;\n    }\n  }\n\n  MetadataPropertyViewStatus _status;\n  gsl::span<const std::byte> _valueBuffer;\n  gsl::span<const std::byte> _arrayOffsetBuffer;\n  gsl::span<const std::byte> _stringOffsetBuffer;\n  PropertyType _offsetType;\n  int64_t _offsetSize;\n  int64_t _componentCount;\n  int64_t _instanceCount;\n  bool _normalized;\n};\n} // namespace CesiumGltf\n", "meta": {"hexsha": "6b535d27db94d1e61314c6cbfacbc9c3612d2d69", "size": 13655, "ext": "h", "lang": "C", "max_stars_repo_path": "CesiumGltf/include/CesiumGltf/MetadataPropertyView.h", "max_stars_repo_name": "yieryi/cesium-native", "max_stars_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CesiumGltf/include/CesiumGltf/MetadataPropertyView.h", "max_issues_repo_name": "yieryi/cesium-native", "max_issues_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CesiumGltf/include/CesiumGltf/MetadataPropertyView.h", "max_forks_repo_name": "yieryi/cesium-native", "max_forks_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1432038835, "max_line_length": 148, "alphanum_fraction": 0.6976931527, "num_tokens": 3171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08151974928043641, "lm_q2_score": 0.01798621348232278, "lm_q1q2_score": 0.001466231613583358}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef rendersysd3d11_8555fd57_19e9_4747_97b5_8d3bfb0fb50f_h\r\n#define rendersysd3d11_8555fd57_19e9_4747_97b5_8d3bfb0fb50f_h\r\n\r\n#include <gslib/type.h>\r\n#include <ariel/rendersys.h>\r\n\r\n__ariel_begin__\r\n\r\nclass rendersys_d3d11:\r\n    public rendersys\r\n{\r\npublic:\r\n    rendersys_d3d11();\r\n    virtual ~rendersys_d3d11();\r\n    virtual bool setup(uint hwnd, const configs& cfg) override;\r\n    virtual void destroy() override;\r\n    virtual void setup_pipeline_state() override;\r\n    virtual render_blob* compile_shader_from_file(const gchar* file, const gchar* entry, const gchar* sm, render_include* inc) override;\r\n    virtual render_blob* compile_shader_from_memory(const char* src, int len, const gchar* name, const gchar* entry, const gchar* sm, render_include* inc) override;\r\n    virtual vertex_shader* create_vertex_shader(const void* ptr, size_t len) override;\r\n    virtual pixel_shader* create_pixel_shader(const void* ptr, size_t len) override;\r\n    virtual compute_shader* create_compute_shader(const void* ptr, size_t len) override;\r\n    virtual geometry_shader* create_geometry_shader(const void* ptr, size_t len) override;\r\n    virtual hull_shader* create_hull_shader(const void* ptr, size_t len) override;\r\n    virtual domain_shader* create_domain_shader(const void* ptr, size_t len) override;\r\n    virtual vertex_format* create_vertex_format(const void* ptr, size_t len, vertex_format_desc vfdesc[], uint n) override;\r\n    virtual vertex_buffer* create_vertex_buffer(uint stride, uint count, bool read, bool write, uint usage, const void* ptr) override;\r\n    virtual index_buffer* create_index_buffer(uint count, bool read, bool write, uint usage, const void* ptr) override;\r\n    virtual constant_buffer* create_constant_buffer(uint stride, bool read, bool write, const void* ptr) override;\r\n    virtual shader_resource_view* create_shader_resource_view(render_resource* res) override;\r\n    virtual depth_stencil_view* create_depth_stencil_view(render_resource* res) override;\r\n    virtual unordered_access_view* create_unordered_access_view(render_resource* res) override;\r\n    virtual sampler_state* create_sampler_state(sampler_state_filter filter) override;\r\n    virtual texture2d* create_texture2d(const image& img, uint mips, uint usage, uint bindflags, uint cpuflags, uint miscflags) override;\r\n    virtual texture2d* create_texture2d(int width, int height, uint format, uint mips, uint usage, uint bindflags, uint cpuflags, uint miscflags) override;\r\n    virtual void load_with_mips(texture2d* tex, const image& img) override;\r\n    virtual void update_buffer(void* buf, int size, const void* ptr) override;\r\n    virtual void set_vertex_format(vertex_format* vfmt) override;\r\n    virtual void set_vertex_buffer(vertex_buffer* vb, uint stride, uint offset) override;\r\n    virtual void set_index_buffer(index_buffer* ib, uint offset) override;\r\n    virtual void begin_render() override;\r\n    virtual void end_render() override;\r\n    virtual void set_render_option(render_option opt, uint val) override;\r\n    virtual void set_vertex_shader(vertex_shader* vs) override;\r\n    virtual void set_pixel_shader(pixel_shader* ps) override;\r\n    virtual void set_geometry_shader(geometry_shader* gs) override;\r\n    virtual void set_viewport(const viewport& vp) override;\r\n    virtual void set_constant_buffer(uint slot, constant_buffer* cb, shader_type st) override;\r\n    virtual void set_sampler_state(uint slot, sampler_state* sstate, shader_type st) override;\r\n    virtual void set_shader_resource(uint slot, shader_resource_view* srv, shader_type st) override;\r\n    virtual void draw(uint count, uint start) override;\r\n    virtual void draw_indexed(uint count, uint start, int base) override;\r\n    virtual void capture_screen(image& img, const rectf& rc, int buff_id) override;\r\n    virtual void enable_alpha_blend(bool b) override;\r\n    virtual void enable_depth(bool b) override;\r\n\r\nprotected:\r\n    D3D_DRIVER_TYPE         _drvtype        = D3D_DRIVER_TYPE_NULL;\r\n    D3D_FEATURE_LEVEL       _level          = D3D_FEATURE_LEVEL_11_0;\r\n    render_device*          _device         = nullptr;\r\n    render_context*         _context        = nullptr;\r\n    render_swap_chain*      _swapchain      = nullptr;\r\n    render_target_view*     _rtview         = nullptr;\r\n    render_blend_state*     _blendstate     = nullptr;\r\n    depth_stencil_view*     _dsview         = nullptr;\r\n    render_raster_state*    _rasterstate    = nullptr;\r\n    render_depth_state*     _depthstate     = nullptr;\r\n    uint                    _msaa_x         = 0;\r\n    bool                    _vsync          = false;\r\n    bool                    _fullscreen     = false;\r\n    bool                    _msaa           = false;\r\n\r\nprotected:\r\n    void install_configs(const configs& cfg);\r\n\r\npublic:\r\n    render_device* get_device() const { return _device; }\r\n    render_context* get_immediate_context() const { return _context; }\r\n};\r\n\r\ntemplate<class res_class>\r\ninline render_resource* convert_to_resource(res_class* p)\r\n{ return static_cast<render_resource*>(p); }\r\n\r\n__ariel_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "d454485979fddc39220ec6f3229dc34c345005e3", "size": 6339, "ext": "h", "lang": "C", "max_stars_repo_path": "include/ariel/rendersysd3d11.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/ariel/rendersysd3d11.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ariel/rendersysd3d11.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 55.1217391304, "max_line_length": 165, "alphanum_fraction": 0.7345007099, "num_tokens": 1437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08269734493579813, "lm_q2_score": 0.017712302365444393, "lm_q1q2_score": 0.001464760378322308}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n//\n// Copyright (c) 2015 Microsoft Corporation. All rights reserved.\n//\n// This code is licensed under the MIT License (MIT).\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef GSL_STRING_SPAN_H\n#define GSL_STRING_SPAN_H\n\n#include <gsl/gsl_assert> // for Ensures, Expects\n#include <gsl/gsl_util>   // for narrow_cast\n#include <gsl/span>       // for operator!=, operator==, dynamic_extent\n#include <gsl/pointers>   // for not_null\n\n#include <algorithm> // for equal, lexicographical_compare\n#include <array>     // for array\n#include <cstddef>   // for ptrdiff_t, size_t, nullptr_t\n#include <cstdint>   // for PTRDIFF_MAX\n#include <cstring>\n#include <string>      // for basic_string, allocator, char_traits\n#include <type_traits> // for declval, is_convertible, enable_if_t, add_...\n\n#ifdef _MSC_VER\n#pragma warning(push)\n\n// Turn MSVC /analyze rules that generate too much noise. TODO: fix in the tool.\n#pragma warning(disable : 26446) // TODO: bug in parser - attributes and templates\n#pragma warning(disable : 26481) // TODO: suppress does not work inside templates sometimes\n\n#if _MSC_VER < 1910\n#pragma push_macro(\"constexpr\")\n#define constexpr /*constexpr*/\n\n#endif // _MSC_VER < 1910\n#endif // _MSC_VER\n\nnamespace gsl\n{\n//\n// czstring and wzstring\n//\n// These are \"tag\" typedefs for C-style strings (i.e. null-terminated character arrays)\n// that allow static analysis to help find bugs.\n//\n// There are no additional features/semantics that we can find a way to add inside the\n// type system for these types that will not either incur significant runtime costs or\n// (sometimes needlessly) break existing programs when introduced.\n//\n\ntemplate <typename CharT, std::ptrdiff_t Extent = dynamic_extent>\nusing basic_zstring = CharT*;\n\ntemplate <std::ptrdiff_t Extent = dynamic_extent>\nusing czstring = basic_zstring<const char, Extent>;\n\ntemplate <std::ptrdiff_t Extent = dynamic_extent>\nusing cwzstring = basic_zstring<const wchar_t, Extent>;\n\ntemplate <std::ptrdiff_t Extent = dynamic_extent>\nusing cu16zstring = basic_zstring<const char16_t, Extent>;\n\ntemplate <std::ptrdiff_t Extent = dynamic_extent>\nusing cu32zstring = basic_zstring<const char32_t, Extent>;\n\ntemplate <std::ptrdiff_t Extent = dynamic_extent>\nusing zstring = basic_zstring<char, Extent>;\n\ntemplate <std::ptrdiff_t Extent = dynamic_extent>\nusing wzstring = basic_zstring<wchar_t, Extent>;\n\ntemplate <std::ptrdiff_t Extent = dynamic_extent>\nusing u16zstring = basic_zstring<char16_t, Extent>;\n\ntemplate <std::ptrdiff_t Extent = dynamic_extent>\nusing u32zstring = basic_zstring<char32_t, Extent>;\n\nnamespace details\n{\n    template <class CharT>\n    std::ptrdiff_t string_length(const CharT* str, std::ptrdiff_t n)\n    {\n        if (str == nullptr || n <= 0) return 0;\n\n        const span<const CharT> str_span{str, n};\n\n        std::ptrdiff_t len = 0;\n        while (len < n && str_span[len]) len++;\n\n        return len;\n    }\n} // namespace details\n\n//\n// ensure_sentinel()\n//\n// Provides a way to obtain an span from a contiguous sequence\n// that ends with a (non-inclusive) sentinel value.\n//\n// Will fail-fast if sentinel cannot be found before max elements are examined.\n//\ntemplate <typename T, const T Sentinel>\nspan<T, dynamic_extent> ensure_sentinel(T* seq, std::ptrdiff_t max = PTRDIFF_MAX)\n{\n    Ensures(seq != nullptr);\n\n    GSL_SUPPRESS(f.23) // NO-FORMAT: attribute // TODO: false positive // TODO: suppress does not work\n    auto cur = seq;\n    Ensures(cur != nullptr); // workaround for removing the warning\n\n    GSL_SUPPRESS(bounds.1) // NO-FORMAT: attribute // TODO: suppress does not work\n    while ((cur - seq) < max && *cur != Sentinel) ++cur;\n    Ensures(*cur == Sentinel);\n    return {seq, cur - seq};\n}\n\n//\n// ensure_z - creates a span for a zero terminated strings.\n// Will fail fast if a null-terminator cannot be found before\n// the limit of size_type.\n//\ntemplate <typename CharT>\nspan<CharT, dynamic_extent> ensure_z(CharT* const& sz, std::ptrdiff_t max = PTRDIFF_MAX)\n{\n    return ensure_sentinel<CharT, CharT(0)>(sz, max);\n}\n\ntemplate <typename CharT, std::size_t N>\nspan<CharT, dynamic_extent> ensure_z(CharT (&sz)[N])\n{\n    return ensure_z(&sz[0], narrow_cast<std::ptrdiff_t>(N));\n}\n\ntemplate <class Cont>\nspan<typename std::remove_pointer<typename Cont::pointer>::type, dynamic_extent>\nensure_z(Cont& cont)\n{\n    return ensure_z(cont.data(), narrow_cast<std::ptrdiff_t>(cont.size()));\n}\n\ntemplate <typename CharT, std::ptrdiff_t>\nclass basic_string_span;\n\nnamespace details {\n    template <typename T>\n    struct is_basic_string_span_oracle : std::false_type\n    {\n    };\n\n    template <typename CharT, std::ptrdiff_t Extent>\n    struct is_basic_string_span_oracle<basic_string_span<CharT, Extent>> : std::true_type\n    {\n    };\n\n    template <typename T>\n    struct is_basic_string_span : is_basic_string_span_oracle<std::remove_cv_t<T>>\n    {\n    };\n} // namespace details\n\n//\n// string_span and relatives\n//\ntemplate <typename CharT, std::ptrdiff_t Extent = dynamic_extent>\nclass basic_string_span\n{\npublic:\n    using element_type = CharT;\n    using pointer = std::add_pointer_t<element_type>;\n    using reference = std::add_lvalue_reference_t<element_type>;\n    using const_reference = std::add_lvalue_reference_t<std::add_const_t<element_type>>;\n    using impl_type = span<element_type, Extent>;\n\n    using index_type = typename impl_type::index_type;\n    using iterator = typename impl_type::iterator;\n    using const_iterator = typename impl_type::const_iterator;\n    using reverse_iterator = typename impl_type::reverse_iterator;\n    using const_reverse_iterator = typename impl_type::const_reverse_iterator;\n\n    // default (empty)\n    constexpr basic_string_span() noexcept = default;\n\n    // copy\n    constexpr basic_string_span(const basic_string_span& other) noexcept = default;\n\n    // assign\n    constexpr basic_string_span& operator=(const basic_string_span& other) noexcept = default;\n\n    constexpr basic_string_span(pointer ptr, index_type length) : span_(ptr, length) {}\n    constexpr basic_string_span(pointer firstElem, pointer lastElem) : span_(firstElem, lastElem) {}\n\n    // From static arrays - if 0-terminated, remove 0 from the view\n    // All other containers allow 0s within the length, so we do not remove them\n    template <std::size_t N>\n    constexpr basic_string_span(element_type (&arr)[N]) : span_(remove_z(arr))\n    {}\n\n    template <std::size_t N, class ArrayElementType = std::remove_const_t<element_type>>\n    constexpr basic_string_span(std::array<ArrayElementType, N>& arr) noexcept : span_(arr)\n    {}\n\n    template <std::size_t N, class ArrayElementType = std::remove_const_t<element_type>>\n    constexpr basic_string_span(const std::array<ArrayElementType, N>& arr) noexcept : span_(arr)\n    {}\n\n    // Container signature should work for basic_string after C++17 version exists\n    template <class Traits, class Allocator>\n    // GSL_SUPPRESS(bounds.4) // NO-FORMAT: attribute // TODO: parser bug\n    constexpr basic_string_span(std::basic_string<element_type, Traits, Allocator>& str)\n        : span_(&str[0], narrow_cast<std::ptrdiff_t>(str.length()))\n    {}\n\n    template <class Traits, class Allocator>\n    constexpr basic_string_span(const std::basic_string<element_type, Traits, Allocator>& str)\n        : span_(&str[0], str.length())\n    {}\n\n    // from containers. Containers must have a pointer type and data() function signatures\n    template <class Container,\n              class = std::enable_if_t<\n                  !details::is_basic_string_span<Container>::value &&\n                  std::is_convertible<typename Container::pointer, pointer>::value &&\n                  std::is_convertible<typename Container::pointer,\n                                      decltype(std::declval<Container>().data())>::value>>\n    constexpr basic_string_span(Container& cont) : span_(cont)\n    {}\n\n    template <class Container,\n              class = std::enable_if_t<\n                  !details::is_basic_string_span<Container>::value &&\n                  std::is_convertible<typename Container::pointer, pointer>::value &&\n                  std::is_convertible<typename Container::pointer,\n                                      decltype(std::declval<Container>().data())>::value>>\n    constexpr basic_string_span(const Container& cont) : span_(cont)\n    {}\n\n    // from string_span\n    template <\n        class OtherValueType, std::ptrdiff_t OtherExtent,\n        class = std::enable_if_t<std::is_convertible<\n            typename basic_string_span<OtherValueType, OtherExtent>::impl_type, impl_type>::value>>\n    constexpr basic_string_span(basic_string_span<OtherValueType, OtherExtent> other)\n        : span_(other.data(), other.length())\n    {}\n\n    template <index_type Count>\n    constexpr basic_string_span<element_type, Count> first() const\n    {\n        return {span_.template first<Count>()};\n    }\n\n    constexpr basic_string_span<element_type, dynamic_extent> first(index_type count) const\n    {\n        return {span_.first(count)};\n    }\n\n    template <index_type Count>\n    constexpr basic_string_span<element_type, Count> last() const\n    {\n        return {span_.template last<Count>()};\n    }\n\n    constexpr basic_string_span<element_type, dynamic_extent> last(index_type count) const\n    {\n        return {span_.last(count)};\n    }\n\n    template <index_type Offset, index_type Count>\n    constexpr basic_string_span<element_type, Count> subspan() const\n    {\n        return {span_.template subspan<Offset, Count>()};\n    }\n\n    constexpr basic_string_span<element_type, dynamic_extent>\n    subspan(index_type offset, index_type count = dynamic_extent) const\n    {\n        return {span_.subspan(offset, count)};\n    }\n\n    constexpr reference operator[](index_type idx) const { return span_[idx]; }\n    constexpr reference operator()(index_type idx) const { return span_[idx]; }\n\n    constexpr pointer data() const { return span_.data(); }\n\n    constexpr index_type length() const noexcept { return span_.size(); }\n    constexpr index_type size() const noexcept { return span_.size(); }\n    constexpr index_type size_bytes() const noexcept { return span_.size_bytes(); }\n    constexpr index_type length_bytes() const noexcept { return span_.length_bytes(); }\n    constexpr bool empty() const noexcept { return size() == 0; }\n\n    constexpr iterator begin() const noexcept { return span_.begin(); }\n    constexpr iterator end() const noexcept { return span_.end(); }\n\n    constexpr const_iterator cbegin() const noexcept { return span_.cbegin(); }\n    constexpr const_iterator cend() const noexcept { return span_.cend(); }\n\n    constexpr reverse_iterator rbegin() const noexcept { return span_.rbegin(); }\n    constexpr reverse_iterator rend() const noexcept { return span_.rend(); }\n\n    constexpr const_reverse_iterator crbegin() const noexcept { return span_.crbegin(); }\n    constexpr const_reverse_iterator crend() const noexcept { return span_.crend(); }\n\nprivate:\n    static impl_type remove_z(pointer const& sz, std::ptrdiff_t max)\n    {\n        return {sz, details::string_length(sz, max)};\n    }\n\n    template <std::size_t N>\n    static impl_type remove_z(element_type (&sz)[N])\n    {\n        return remove_z(&sz[0], narrow_cast<std::ptrdiff_t>(N));\n    }\n\n    impl_type span_;\n};\n\ntemplate <std::ptrdiff_t Extent = dynamic_extent>\nusing string_span = basic_string_span<char, Extent>;\n\ntemplate <std::ptrdiff_t Extent = dynamic_extent>\nusing cstring_span = basic_string_span<const char, Extent>;\n\ntemplate <std::ptrdiff_t Extent = dynamic_extent>\nusing wstring_span = basic_string_span<wchar_t, Extent>;\n\ntemplate <std::ptrdiff_t Extent = dynamic_extent>\nusing cwstring_span = basic_string_span<const wchar_t, Extent>;\n\ntemplate <std::ptrdiff_t Extent = dynamic_extent>\nusing u16string_span = basic_string_span<char16_t, Extent>;\n\ntemplate <std::ptrdiff_t Extent = dynamic_extent>\nusing cu16string_span = basic_string_span<const char16_t, Extent>;\n\ntemplate <std::ptrdiff_t Extent = dynamic_extent>\nusing u32string_span = basic_string_span<char32_t, Extent>;\n\ntemplate <std::ptrdiff_t Extent = dynamic_extent>\nusing cu32string_span = basic_string_span<const char32_t, Extent>;\n\n//\n// to_string() allow (explicit) conversions from string_span to string\n//\n\ntemplate <typename CharT, std::ptrdiff_t Extent>\nstd::basic_string<typename std::remove_const<CharT>::type>\nto_string(basic_string_span<CharT, Extent> view)\n{\n    return {view.data(), narrow_cast<std::size_t>(view.length())};\n}\n\ntemplate <typename CharT, typename Traits = typename std::char_traits<CharT>,\n          typename Allocator = std::allocator<CharT>, typename gCharT, std::ptrdiff_t Extent>\nstd::basic_string<CharT, Traits, Allocator> to_basic_string(basic_string_span<gCharT, Extent> view)\n{\n    return {view.data(), narrow_cast<std::size_t>(view.length())};\n}\n\ntemplate <class ElementType, std::ptrdiff_t Extent>\nbasic_string_span<const byte, details::calculate_byte_size<ElementType, Extent>::value>\nas_bytes(basic_string_span<ElementType, Extent> s) noexcept\n{\n    GSL_SUPPRESS(type.1) // NO-FORMAT: attribute\n    return {reinterpret_cast<const byte*>(s.data()), s.size_bytes()};\n}\n\ntemplate <class ElementType, std::ptrdiff_t Extent,\n          class = std::enable_if_t<!std::is_const<ElementType>::value>>\nbasic_string_span<byte, details::calculate_byte_size<ElementType, Extent>::value>\nas_writeable_bytes(basic_string_span<ElementType, Extent> s) noexcept\n{\n    GSL_SUPPRESS(type.1) // NO-FORMAT: attribute\n    return {reinterpret_cast<byte*>(s.data()), s.size_bytes()};\n}\n\n// zero-terminated string span, used to convert\n// zero-terminated spans to legacy strings\ntemplate <typename CharT, std::ptrdiff_t Extent = dynamic_extent>\nclass basic_zstring_span {\npublic:\n    using value_type = CharT;\n    using const_value_type = std::add_const_t<CharT>;\n\n    using pointer = std::add_pointer_t<value_type>;\n    using const_pointer = std::add_pointer_t<const_value_type>;\n\n    using zstring_type = basic_zstring<value_type, Extent>;\n    using const_zstring_type = basic_zstring<const_value_type, Extent>;\n\n    using impl_type = span<value_type, Extent>;\n    using string_span_type = basic_string_span<value_type, Extent>;\n\n    constexpr basic_zstring_span(impl_type s) : span_(s)\n    {\n        // expects a zero-terminated span\n        Expects(s[s.size() - 1] == '\\0');\n    }\n\n    // copy\n    constexpr basic_zstring_span(const basic_zstring_span& other) = default;\n\n    // move\n    constexpr basic_zstring_span(basic_zstring_span&& other) = default;\n\n    // assign\n    constexpr basic_zstring_span& operator=(const basic_zstring_span& other) = default;\n\n    // move assign\n    constexpr basic_zstring_span& operator=(basic_zstring_span&& other) = default;\n\n    constexpr bool empty() const noexcept { return span_.size() == 0; }\n\n    constexpr string_span_type as_string_span() const noexcept\n    {\n        const auto sz = span_.size();\n        return {span_.data(), sz > 1 ? sz - 1 : 0};\n    }\n    constexpr string_span_type ensure_z() const { return gsl::ensure_z(span_); }\n\n    constexpr const_zstring_type assume_z() const noexcept { return span_.data(); }\n\nprivate:\n    impl_type span_;\n};\n\ntemplate <std::ptrdiff_t Max = dynamic_extent>\nusing zstring_span = basic_zstring_span<char, Max>;\n\ntemplate <std::ptrdiff_t Max = dynamic_extent>\nusing wzstring_span = basic_zstring_span<wchar_t, Max>;\n\ntemplate <std::ptrdiff_t Max = dynamic_extent>\nusing u16zstring_span = basic_zstring_span<char16_t, Max>;\n\ntemplate <std::ptrdiff_t Max = dynamic_extent>\nusing u32zstring_span = basic_zstring_span<char32_t, Max>;\n\ntemplate <std::ptrdiff_t Max = dynamic_extent>\nusing czstring_span = basic_zstring_span<const char, Max>;\n\ntemplate <std::ptrdiff_t Max = dynamic_extent>\nusing cwzstring_span = basic_zstring_span<const wchar_t, Max>;\n\ntemplate <std::ptrdiff_t Max = dynamic_extent>\nusing cu16zstring_span = basic_zstring_span<const char16_t, Max>;\n\ntemplate <std::ptrdiff_t Max = dynamic_extent>\nusing cu32zstring_span = basic_zstring_span<const char32_t, Max>;\n\n// operator ==\ntemplate <class CharT, std::ptrdiff_t Extent, class T,\n          class = std::enable_if_t<\n              details::is_basic_string_span<T>::value ||\n              std::is_convertible<T, gsl::basic_string_span<std::add_const_t<CharT>>>::value>>\nbool operator==(const gsl::basic_string_span<CharT, Extent>& one, const T& other)\n{\n    const gsl::basic_string_span<std::add_const_t<CharT>> tmp(other);\n    return std::equal(one.begin(), one.end(), tmp.begin(), tmp.end());\n}\n\ntemplate <class CharT, std::ptrdiff_t Extent, class T,\n          class = std::enable_if_t<\n              !details::is_basic_string_span<T>::value &&\n              std::is_convertible<T, gsl::basic_string_span<std::add_const_t<CharT>>>::value>>\nbool operator==(const T& one, const gsl::basic_string_span<CharT, Extent>& other)\n{\n    const gsl::basic_string_span<std::add_const_t<CharT>> tmp(one);\n    return std::equal(tmp.begin(), tmp.end(), other.begin(), other.end());\n}\n\n// operator !=\ntemplate <typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,\n          typename = std::enable_if_t<std::is_convertible<\n              T, gsl::basic_string_span<std::add_const_t<CharT>, Extent>>::value>>\nbool operator!=(gsl::basic_string_span<CharT, Extent> one, const T& other)\n{\n    return !(one == other);\n}\n\ntemplate <\n    typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,\n    typename = std::enable_if_t<\n        std::is_convertible<T, gsl::basic_string_span<std::add_const_t<CharT>, Extent>>::value &&\n        !gsl::details::is_basic_string_span<T>::value>>\nbool operator!=(const T& one, gsl::basic_string_span<CharT, Extent> other)\n{\n    return !(one == other);\n}\n\n// operator<\ntemplate <typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,\n          typename = std::enable_if_t<std::is_convertible<\n              T, gsl::basic_string_span<std::add_const_t<CharT>, Extent>>::value>>\nbool operator<(gsl::basic_string_span<CharT, Extent> one, const T& other)\n{\n    const gsl::basic_string_span<std::add_const_t<CharT>, Extent> tmp(other);\n    return std::lexicographical_compare(one.begin(), one.end(), tmp.begin(), tmp.end());\n}\n\ntemplate <\n    typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,\n    typename = std::enable_if_t<\n        std::is_convertible<T, gsl::basic_string_span<std::add_const_t<CharT>, Extent>>::value &&\n        !gsl::details::is_basic_string_span<T>::value>>\nbool operator<(const T& one, gsl::basic_string_span<CharT, Extent> other)\n{\n    gsl::basic_string_span<std::add_const_t<CharT>, Extent> tmp(one);\n    return std::lexicographical_compare(tmp.begin(), tmp.end(), other.begin(), other.end());\n}\n\n#ifndef _MSC_VER\n\n// VS treats temp and const containers as convertible to basic_string_span,\n// so the cases below are already covered by the previous operators\n\ntemplate <\n    typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,\n    typename DataType = typename T::value_type,\n    typename = std::enable_if_t<\n        !gsl::details::is_span<T>::value && !gsl::details::is_basic_string_span<T>::value &&\n        std::is_convertible<DataType*, CharT*>::value &&\n        std::is_same<std::decay_t<decltype(std::declval<T>().size(), *std::declval<T>().data())>,\n                     DataType>::value>>\nbool operator<(gsl::basic_string_span<CharT, Extent> one, const T& other)\n{\n    gsl::basic_string_span<std::add_const_t<CharT>, Extent> tmp(other);\n    return std::lexicographical_compare(one.begin(), one.end(), tmp.begin(), tmp.end());\n}\n\ntemplate <\n    typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,\n    typename DataType = typename T::value_type,\n    typename = std::enable_if_t<\n        !gsl::details::is_span<T>::value && !gsl::details::is_basic_string_span<T>::value &&\n        std::is_convertible<DataType*, CharT*>::value &&\n        std::is_same<std::decay_t<decltype(std::declval<T>().size(), *std::declval<T>().data())>,\n                     DataType>::value>>\nbool operator<(const T& one, gsl::basic_string_span<CharT, Extent> other)\n{\n    gsl::basic_string_span<std::add_const_t<CharT>, Extent> tmp(one);\n    return std::lexicographical_compare(tmp.begin(), tmp.end(), other.begin(), other.end());\n}\n#endif\n\n// operator <=\ntemplate <typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,\n          typename = std::enable_if_t<std::is_convertible<\n              T, gsl::basic_string_span<std::add_const_t<CharT>, Extent>>::value>>\nbool operator<=(gsl::basic_string_span<CharT, Extent> one, const T& other)\n{\n    return !(other < one);\n}\n\ntemplate <\n    typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,\n    typename = std::enable_if_t<\n        std::is_convertible<T, gsl::basic_string_span<std::add_const_t<CharT>, Extent>>::value &&\n        !gsl::details::is_basic_string_span<T>::value>>\nbool operator<=(const T& one, gsl::basic_string_span<CharT, Extent> other)\n{\n    return !(other < one);\n}\n\n#ifndef _MSC_VER\n\n// VS treats temp and const containers as convertible to basic_string_span,\n// so the cases below are already covered by the previous operators\n\ntemplate <\n    typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,\n    typename DataType = typename T::value_type,\n    typename = std::enable_if_t<\n        !gsl::details::is_span<T>::value && !gsl::details::is_basic_string_span<T>::value &&\n        std::is_convertible<DataType*, CharT*>::value &&\n        std::is_same<std::decay_t<decltype(std::declval<T>().size(), *std::declval<T>().data())>,\n                     DataType>::value>>\nbool operator<=(gsl::basic_string_span<CharT, Extent> one, const T& other)\n{\n    return !(other < one);\n}\n\ntemplate <\n    typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,\n    typename DataType = typename T::value_type,\n    typename = std::enable_if_t<\n        !gsl::details::is_span<T>::value && !gsl::details::is_basic_string_span<T>::value &&\n        std::is_convertible<DataType*, CharT*>::value &&\n        std::is_same<std::decay_t<decltype(std::declval<T>().size(), *std::declval<T>().data())>,\n                     DataType>::value>>\nbool operator<=(const T& one, gsl::basic_string_span<CharT, Extent> other)\n{\n    return !(other < one);\n}\n#endif\n\n// operator>\ntemplate <typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,\n          typename = std::enable_if_t<std::is_convertible<\n              T, gsl::basic_string_span<std::add_const_t<CharT>, Extent>>::value>>\nbool operator>(gsl::basic_string_span<CharT, Extent> one, const T& other)\n{\n    return other < one;\n}\n\ntemplate <\n    typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,\n    typename = std::enable_if_t<\n        std::is_convertible<T, gsl::basic_string_span<std::add_const_t<CharT>, Extent>>::value &&\n        !gsl::details::is_basic_string_span<T>::value>>\nbool operator>(const T& one, gsl::basic_string_span<CharT, Extent> other)\n{\n    return other < one;\n}\n\n#ifndef _MSC_VER\n\n// VS treats temp and const containers as convertible to basic_string_span,\n// so the cases below are already covered by the previous operators\n\ntemplate <\n    typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,\n    typename DataType = typename T::value_type,\n    typename = std::enable_if_t<\n        !gsl::details::is_span<T>::value && !gsl::details::is_basic_string_span<T>::value &&\n        std::is_convertible<DataType*, CharT*>::value &&\n        std::is_same<std::decay_t<decltype(std::declval<T>().size(), *std::declval<T>().data())>,\n                     DataType>::value>>\nbool operator>(gsl::basic_string_span<CharT, Extent> one, const T& other)\n{\n    return other < one;\n}\n\ntemplate <\n    typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,\n    typename DataType = typename T::value_type,\n    typename = std::enable_if_t<\n        !gsl::details::is_span<T>::value && !gsl::details::is_basic_string_span<T>::value &&\n        std::is_convertible<DataType*, CharT*>::value &&\n        std::is_same<std::decay_t<decltype(std::declval<T>().size(), *std::declval<T>().data())>,\n                     DataType>::value>>\nbool operator>(const T& one, gsl::basic_string_span<CharT, Extent> other)\n{\n    return other < one;\n}\n#endif\n\n// operator >=\ntemplate <typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,\n          typename = std::enable_if_t<std::is_convertible<\n              T, gsl::basic_string_span<std::add_const_t<CharT>, Extent>>::value>>\nbool operator>=(gsl::basic_string_span<CharT, Extent> one, const T& other)\n{\n    return !(one < other);\n}\n\ntemplate <\n    typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,\n    typename = std::enable_if_t<\n        std::is_convertible<T, gsl::basic_string_span<std::add_const_t<CharT>, Extent>>::value &&\n        !gsl::details::is_basic_string_span<T>::value>>\nbool operator>=(const T& one, gsl::basic_string_span<CharT, Extent> other)\n{\n    return !(one < other);\n}\n\n#ifndef _MSC_VER\n\n// VS treats temp and const containers as convertible to basic_string_span,\n// so the cases below are already covered by the previous operators\n\ntemplate <\n    typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,\n    typename DataType = typename T::value_type,\n    typename = std::enable_if_t<\n        !gsl::details::is_span<T>::value && !gsl::details::is_basic_string_span<T>::value &&\n        std::is_convertible<DataType*, CharT*>::value &&\n        std::is_same<std::decay_t<decltype(std::declval<T>().size(), *std::declval<T>().data())>,\n                     DataType>::value>>\nbool operator>=(gsl::basic_string_span<CharT, Extent> one, const T& other)\n{\n    return !(one < other);\n}\n\ntemplate <\n    typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,\n    typename DataType = typename T::value_type,\n    typename = std::enable_if_t<\n        !gsl::details::is_span<T>::value && !gsl::details::is_basic_string_span<T>::value &&\n        std::is_convertible<DataType*, CharT*>::value &&\n        std::is_same<std::decay_t<decltype(std::declval<T>().size(), *std::declval<T>().data())>,\n                     DataType>::value>>\nbool operator>=(const T& one, gsl::basic_string_span<CharT, Extent> other)\n{\n    return !(one < other);\n}\n#endif\n} // namespace gsl\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n\n#if _MSC_VER < 1910\n#undef constexpr\n#pragma pop_macro(\"constexpr\")\n\n#endif // _MSC_VER < 1910\n#endif // _MSC_VER\n\n#endif // GSL_STRING_SPAN_H\n", "meta": {"hexsha": "d298039c0ab8d05af26f5546d7405acd6bd75203", "size": 27137, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gsl/string_span.h", "max_stars_repo_name": "Redchards/CVRP", "max_stars_repo_head_hexsha": "f372f2fa06cb374ebdac2f6eee7e6fe297d94103", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-09-01T14:40:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-15T05:01:23.000Z", "max_issues_repo_path": "include/gsl/string_span.h", "max_issues_repo_name": "Redchards/CVRP", "max_issues_repo_head_hexsha": "f372f2fa06cb374ebdac2f6eee7e6fe297d94103", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gsl/string_span.h", "max_forks_repo_name": "Redchards/CVRP", "max_forks_repo_head_hexsha": "f372f2fa06cb374ebdac2f6eee7e6fe297d94103", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-02T17:50:23.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-26T08:25:35.000Z", "avg_line_length": 37.6902777778, "max_line_length": 102, "alphanum_fraction": 0.6972767808, "num_tokens": 6637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.0646534883562239, "lm_q2_score": 0.0226291993326994, "lm_q1q2_score": 0.0014630566755673504}}
{"text": "// Copyright 2019-2020 CERN and copyright holders of ALICE O2.\n// See https://alice-o2.web.cern.ch/copyright for details of the copyright holders.\n// All rights not expressly granted are reserved.\n//\n// This software is distributed under the terms of the GNU General Public\n// License v3 (GPL Version 3), copied verbatim in the file \"COPYING\".\n//\n// In applying this license CERN does not waive the privileges and immunities\n// granted to it by virtue of its status as an Intergovernmental Organization\n// or submit itself to any jurisdiction.\n\n#ifndef O2_FRAMEWORK_ASOA_H_\n#define O2_FRAMEWORK_ASOA_H_\n\n#include \"Framework/Pack.h\"\n#include \"Framework/CheckTypes.h\"\n#include \"Framework/FunctionalHelpers.h\"\n#include \"Framework/CompilerBuiltins.h\"\n#include \"Framework/Traits.h\"\n#include \"Framework/Expressions.h\"\n#include \"Framework/ArrowTypes.h\"\n#include \"Framework/RuntimeError.h\"\n#include \"Framework/Kernels.h\"\n#include <arrow/table.h>\n#include <arrow/array.h>\n#include <arrow/util/variant.h>\n#include <gandiva/selection_vector.h>\n#include <cassert>\n#include <fmt/format.h>\n#include <typeinfo>\n#include <gsl/span>\n\nnamespace o2::soa\n{\ntemplate <typename... C>\nauto createSchemaFromColumns(framework::pack<C...>)\n{\n  return std::make_shared<arrow::Schema>(std::vector<std::shared_ptr<arrow::Field>>{C::asArrowField()...});\n}\nusing SelectionVector = std::vector<int64_t>;\n\ntemplate <typename, typename = void>\ninline constexpr bool is_index_column_v = false;\n\ntemplate <typename T>\ninline constexpr bool is_index_column_v<T, std::void_t<decltype(sizeof(typename T::binding_t))>> = true;\n\ntemplate <typename, typename = void>\ninline constexpr bool is_type_with_originals_v = false;\n\ntemplate <typename T>\ninline constexpr bool is_type_with_originals_v<T, std::void_t<decltype(sizeof(typename T::originals))>> = true;\n\ntemplate <typename T, typename = void>\ninline constexpr bool is_type_with_parent_v = false;\n\ntemplate <typename T>\ninline constexpr bool is_type_with_parent_v<T, std::void_t<decltype(sizeof(typename T::parent_t))>> = true;\n\ntemplate <typename, typename = void>\ninline constexpr bool is_type_with_metadata_v = false;\n\ntemplate <typename T>\ninline constexpr bool is_type_with_metadata_v<T, std::void_t<decltype(sizeof(typename T::metadata))>> = true;\n\ntemplate <typename, typename = void>\ninline constexpr bool is_type_with_binding_v = false;\n\ntemplate <typename T>\ninline constexpr bool is_type_with_binding_v<T, std::void_t<decltype(sizeof(typename T::binding_t))>> = true;\n\ntemplate <typename, typename = void>\ninline constexpr bool is_type_spawnable_v = false;\n\ntemplate <typename T>\ninline constexpr bool is_type_spawnable_v<T, std::void_t<decltype(sizeof(typename T::spawnable_t))>> = true;\n\ntemplate <typename, typename = void>\ninline constexpr bool is_soa_extension_table_v = false;\n\ntemplate <typename T>\ninline constexpr bool is_soa_extension_table_v<T, std::void_t<decltype(sizeof(typename T::expression_pack_t))>> = true;\n\ntemplate <typename T, typename = void>\ninline constexpr bool is_index_table_v = false;\n\ntemplate <typename T>\ninline constexpr bool is_index_table_v<T, std::void_t<decltype(sizeof(typename T::indexing_t))>> = true;\n\ntemplate <typename, typename = void>\ninline constexpr bool is_self_index_column_v = false;\n\ntemplate <typename T>\ninline constexpr bool is_self_index_column_v<T, std::void_t<decltype(sizeof(typename T::self_index_t))>> = true;\n\ntemplate <typename T, typename TLambda>\nvoid call_if_has_originals(TLambda&& lambda)\n{\n  if constexpr (is_type_with_originals_v<T>) {\n    lambda(static_cast<T*>(nullptr));\n  }\n}\n\ntemplate <typename T, typename TLambda>\nvoid call_if_has_not_originals(TLambda&& lambda)\n{\n  if constexpr (!is_type_with_originals_v<T>) {\n    lambda(static_cast<T*>(nullptr));\n  }\n}\n\ntemplate <typename H, typename... T>\nconstexpr auto make_originals_from_type()\n{\n  using decayed = std::decay_t<H>;\n  if constexpr (sizeof...(T) == 0) {\n    if constexpr (is_type_with_originals_v<decayed>) {\n      return typename decayed::originals{};\n    } else if constexpr (is_type_with_originals_v<typename decayed::table_t>) {\n      return typename decayed::table_t::originals{};\n    } else if constexpr (is_type_with_parent_v<decayed>) {\n      return make_originals_from_type<typename decayed::parent_t>();\n    } else {\n      return framework::pack<decayed>{};\n    }\n  } else if constexpr (is_type_with_originals_v<decayed>) {\n    return framework::concatenate_pack(typename decayed::originals{}, make_originals_from_type<T...>());\n  } else if constexpr (is_type_with_originals_v<typename decayed::table_t>) {\n    return framework::concatenate_pack(typename decayed::table_t::originals{}, make_originals_from_type<T...>());\n  } else {\n    return framework::concatenate_pack(framework::pack<decayed>{}, make_originals_from_type<T...>());\n  }\n}\n\ntemplate <typename... T>\nconstexpr auto make_originals_from_type(framework::pack<T...>)\n{\n  return make_originals_from_type<T...>();\n}\n\n/// Policy class for columns which are chunked. This\n/// will make the compiler take the most generic (and\n/// slow approach).\nstruct Chunked {\n  constexpr static bool chunked = true;\n};\n\n/// Policy class for columns which are known to be fully\n/// inside a chunk. This will generate optimal code.\nstruct Flat {\n  constexpr static bool chunked = false;\n};\n\n/// unwrapper\ntemplate <typename T>\nstruct unwrap {\n  using type = T;\n};\n\ntemplate <typename T>\nstruct unwrap<std::vector<T>> {\n  using type = T;\n};\n\ntemplate <>\nstruct unwrap<bool> {\n  using type = char;\n};\n\ntemplate <typename T>\nusing unwrap_t = typename unwrap<T>::type;\n\n/// Iterator on a single column.\n/// FIXME: the ChunkingPolicy for now is fixed to Flat and is a mere boolean\n/// which is used to switch off slow \"chunking aware\" parts. This is ok for\n/// now, but most likely we should move the whole chunk navigation logic there.\ntemplate <typename T, typename ChunkingPolicy = Chunked>\nclass ColumnIterator : ChunkingPolicy\n{\n  static constexpr char SCALE_FACTOR = std::is_same_v<std::decay_t<T>, bool> ? 3 : 0;\n\n public:\n  /// Constructor of the column iterator. Notice how it takes a pointer\n  /// to the ChunkedArray (for the data store) and to the index inside\n  /// it. This means that a ColumnIterator is actually only available\n  /// as part of a RowView.\n  ColumnIterator(arrow::ChunkedArray const* column)\n    : mColumn{column},\n      mCurrent{nullptr},\n      mCurrentPos{nullptr},\n      mLast{nullptr},\n      mFirstIndex{0},\n      mCurrentChunk{0},\n      mOffset{0}\n  {\n    auto array = getCurrentArray();\n    mCurrent = reinterpret_cast<unwrap_t<T> const*>(array->values()->data()) + (mOffset >> SCALE_FACTOR);\n    mLast = mCurrent + array->length();\n  }\n\n  ColumnIterator() = default;\n  ColumnIterator(ColumnIterator<T, ChunkingPolicy> const&) = default;\n  ColumnIterator<T, ChunkingPolicy>& operator=(ColumnIterator<T, ChunkingPolicy> const&) = default;\n\n  ColumnIterator(ColumnIterator<T, ChunkingPolicy>&&) = default;\n  ColumnIterator<T, ChunkingPolicy>& operator=(ColumnIterator<T, ChunkingPolicy>&&) = default;\n\n  /// Move the iterator to the next chunk.\n  void nextChunk() const\n  {\n    auto previousArray = getCurrentArray();\n    mFirstIndex += previousArray->length();\n\n    mCurrentChunk++;\n    auto array = getCurrentArray();\n    mCurrent = reinterpret_cast<unwrap_t<T> const*>(array->values()->data()) + (mOffset >> SCALE_FACTOR) - (mFirstIndex >> SCALE_FACTOR);\n    mLast = mCurrent + array->length() + (mFirstIndex >> SCALE_FACTOR);\n  }\n\n  void prevChunk() const\n  {\n    auto previousArray = getCurrentArray();\n    mFirstIndex -= previousArray->length();\n\n    mCurrentChunk--;\n    auto array = getCurrentArray();\n    mCurrent = reinterpret_cast<unwrap_t<T> const*>(array->values()->data()) + (mOffset >> SCALE_FACTOR) - (mFirstIndex >> SCALE_FACTOR);\n    mLast = mCurrent + array->length() + (mFirstIndex >> SCALE_FACTOR);\n  }\n\n  void moveToChunk(int chunk)\n  {\n    if (mCurrentChunk < chunk) {\n      while (mCurrentChunk != chunk) {\n        nextChunk();\n      }\n    } else {\n      while (mCurrentChunk != chunk) {\n        prevChunk();\n      }\n    }\n  }\n\n  /// Move the iterator to the end of the column.\n  void moveToEnd()\n  {\n    mCurrentChunk = mColumn->num_chunks() - 1;\n    auto array = getCurrentArray();\n    mFirstIndex = mColumn->length() - array->length();\n    mCurrent = reinterpret_cast<unwrap_t<T> const*>(array->values()->data()) + (mOffset >> SCALE_FACTOR) - (mFirstIndex >> SCALE_FACTOR);\n    mLast = mCurrent + array->length() + (mFirstIndex >> SCALE_FACTOR);\n  }\n\n  decltype(auto) operator*() const\n  {\n    if constexpr (ChunkingPolicy::chunked) {\n      if constexpr (std::is_same_v<arrow_array_for_t<T>, arrow::ListArray>) {\n        auto list = std::static_pointer_cast<arrow::ListArray>(mColumn->chunk(mCurrentChunk));\n        if (O2_BUILTIN_UNLIKELY(*mCurrentPos - mFirstIndex >= list->length())) {\n          nextChunk();\n        }\n      } else {\n        if (O2_BUILTIN_UNLIKELY(((mCurrent + (*mCurrentPos >> SCALE_FACTOR)) >= mLast))) {\n          nextChunk();\n        }\n      }\n    }\n    if constexpr (std::is_same_v<bool, std::decay_t<T>>) {\n      // FIXME: check if shifting the masked bit to the first position is better than != 0\n      return (*(mCurrent + (*mCurrentPos >> SCALE_FACTOR)) & (1 << ((*mCurrentPos + mOffset) & 0x7))) != 0;\n    } else if constexpr (std::is_same_v<arrow_array_for_t<T>, arrow::ListArray>) {\n      auto list = std::static_pointer_cast<arrow::ListArray>(mColumn->chunk(mCurrentChunk));\n      auto offset = list->value_offset(*mCurrentPos - mFirstIndex);\n      auto length = list->value_length(*mCurrentPos - mFirstIndex);\n      return gsl::span{mCurrent + mFirstIndex + offset, mCurrent + mFirstIndex + (offset + length)};\n    } else {\n      return *(mCurrent + (*mCurrentPos >> SCALE_FACTOR));\n    }\n  }\n\n  // Move to the chunk which containts element pos\n  ColumnIterator<T>& moveToPos()\n  {\n    // If we get outside range of the current chunk, go to the next.\n    if constexpr (ChunkingPolicy::chunked) {\n      while (O2_BUILTIN_UNLIKELY((mCurrent + (*mCurrentPos >> SCALE_FACTOR)) >= mLast)) {\n        nextChunk();\n      }\n    }\n    return *this;\n  }\n\n  // Move to the chunk which containts element pos\n  ColumnIterator<T>& checkNextChunk()\n  {\n    if constexpr (ChunkingPolicy::chunked) {\n      if (O2_BUILTIN_LIKELY((mCurrent + (*mCurrentPos >> SCALE_FACTOR)) <= mLast)) {\n        return *this;\n      }\n      nextChunk();\n    }\n    return *this;\n  }\n\n  mutable unwrap_t<T> const* mCurrent;\n  int64_t const* mCurrentPos;\n  mutable unwrap_t<T> const* mLast;\n  arrow::ChunkedArray const* mColumn;\n  mutable int mFirstIndex;\n  mutable int mCurrentChunk;\n  mutable int mOffset;\n\n private:\n  /// get pointer to mCurrentChunk chunk\n  auto getCurrentArray() const\n  {\n    std::shared_ptr<arrow::Array> chunkToUse = mColumn->chunk(mCurrentChunk);\n    mOffset = chunkToUse->offset();\n    if constexpr (std::is_same_v<arrow_array_for_t<T>, arrow::FixedSizeListArray>) {\n      chunkToUse = std::dynamic_pointer_cast<arrow::FixedSizeListArray>(chunkToUse)->values();\n      return std::static_pointer_cast<arrow_array_for_t<value_for_t<T>>>(chunkToUse);\n    } else if constexpr (std::is_same_v<arrow_array_for_t<T>, arrow::ListArray>) {\n      chunkToUse = std::dynamic_pointer_cast<arrow::ListArray>(chunkToUse)->values();\n      mOffset = chunkToUse->offset();\n      return std::static_pointer_cast<arrow_array_for_t<value_for_t<T>>>(chunkToUse);\n    } else {\n      return std::static_pointer_cast<arrow_array_for_t<T>>(chunkToUse);\n    }\n  }\n};\n\ntemplate <typename T, typename INHERIT>\nstruct Column {\n  using inherited_t = INHERIT;\n  Column(ColumnIterator<T> const& it)\n    : mColumnIterator{it}\n  {\n  }\n\n  Column() = default;\n  Column(Column const&) = default;\n  Column& operator=(Column const&) = default;\n\n  Column(Column&&) = default;\n  Column& operator=(Column&&) = default;\n\n  using persistent = std::true_type;\n  using type = T;\n  static constexpr const char* const& columnLabel() { return INHERIT::mLabel; }\n  ColumnIterator<T> const& getIterator() const\n  {\n    return mColumnIterator;\n  }\n\n  static auto asArrowField()\n  {\n    return std::make_shared<arrow::Field>(inherited_t::mLabel, framework::expressions::concreteArrowType(framework::expressions::selectArrowType<type>()));\n  }\n\n  /// FIXME: rather than keeping this public we should have a protected\n  /// non-const getter and mark this private.\n  ColumnIterator<T> mColumnIterator;\n};\n\n/// The purpose of this class is to store the lambda which is associated to the\n/// method call.\ntemplate <typename F, typename INHERIT>\nstruct DynamicColumn {\n  using inherited_t = INHERIT;\n\n  using persistent = std::false_type;\n  static constexpr const char* const& columnLabel() { return INHERIT::mLabel; }\n};\n\ntemplate <typename INHERIT>\nstruct IndexColumn {\n  using inherited_t = INHERIT;\n\n  using persistent = std::false_type;\n  static constexpr const char* const& columnLabel() { return INHERIT::mLabel; }\n};\n\ntemplate <int64_t START = 0, int64_t END = -1>\nstruct Index : o2::soa::IndexColumn<Index<START, END>> {\n  using base = o2::soa::IndexColumn<Index<START, END>>;\n  constexpr inline static int64_t start = START;\n  constexpr inline static int64_t end = END;\n\n  Index() = default;\n  Index(Index const&) = default;\n  Index(Index&&) = default;\n\n  Index& operator=(Index const&) = default;\n  Index& operator=(Index&&) = default;\n\n  Index(arrow::ChunkedArray const*)\n  {\n  }\n\n  constexpr inline int64_t rangeStart()\n  {\n    return START;\n  }\n\n  constexpr inline int64_t rangeEnd()\n  {\n    return END;\n  }\n\n  int64_t index() const\n  {\n    return index<0>();\n  }\n\n  int64_t filteredIndex() const\n  {\n    return index<1>();\n  }\n\n  int64_t globalIndex() const\n  {\n    return index<0>() + offsets<0>();\n  }\n\n  template <int N = 0>\n  int64_t index() const\n  {\n    return *std::get<N>(rowIndices);\n  }\n\n  template <int N = 0>\n  int64_t offsets() const\n  {\n    return *std::get<N>(rowOffsets);\n  }\n\n  void setIndices(std::tuple<int64_t const*, int64_t const*> indices)\n  {\n    rowIndices = indices;\n  }\n\n  void setOffsets(std::tuple<uint64_t const*> offsets)\n  {\n    rowOffsets = offsets;\n  }\n\n  static constexpr const char* mLabel = \"Index\";\n  using type = int64_t;\n\n  using bindings_t = typename o2::framework::pack<>;\n  std::tuple<> boundIterators;\n  std::tuple<int64_t const*, int64_t const*> rowIndices;\n  /// The offsets within larger tables. Currently only\n  /// one level of nesting is supported.\n  std::tuple<uint64_t const*> rowOffsets;\n};\n\ntemplate <typename T>\nusing is_dynamic_t = framework::is_specialization<typename T::base, DynamicColumn>;\n\ntemplate <typename T>\nusing is_persistent_t = typename std::decay_t<T>::persistent::type;\n\ntemplate <typename T>\nusing is_external_index_t = typename std::conditional<is_index_column_v<T>, std::true_type, std::false_type>::type;\n\ntemplate <typename T>\nusing is_self_index_t = typename std::conditional<is_self_index_column_v<T>, std::true_type, std::false_type>::type;\n\ntemplate <typename T, template <auto...> class Ref>\nstruct is_index : std::false_type {\n};\n\ntemplate <template <auto...> class Ref, auto... Args>\nstruct is_index<Ref<Args...>, Ref> : std::true_type {\n};\n\ntemplate <typename T>\nusing is_index_t = is_index<T, Index>;\n\nstruct IndexPolicyBase {\n  /// Position inside the current table\n  int64_t mRowIndex = 0;\n  /// Offset within a larger table\n  uint64_t mOffset = 0;\n};\n\nstruct RowViewSentinel {\n  uint64_t const index;\n};\n\nstruct DefaultIndexPolicy : IndexPolicyBase {\n  /// Needed to be able to copy the policy\n  DefaultIndexPolicy() = default;\n  DefaultIndexPolicy(DefaultIndexPolicy&&) = default;\n  DefaultIndexPolicy(DefaultIndexPolicy const&) = default;\n  DefaultIndexPolicy& operator=(DefaultIndexPolicy const&) = default;\n  DefaultIndexPolicy& operator=(DefaultIndexPolicy&&) = default;\n\n  /// mMaxRow is one behind the last row, so effectively equal to the number of\n  /// rows @a nRows. Offset indicates that the index is actually part of\n  /// a larger\n  DefaultIndexPolicy(int64_t nRows, uint64_t offset)\n    : IndexPolicyBase{0, offset},\n      mMaxRow(nRows)\n  {\n  }\n\n  void limitRange(int64_t start, int64_t end)\n  {\n    this->setCursor(start);\n    if (end >= 0) {\n      mMaxRow = std::min(end, mMaxRow);\n    }\n  }\n\n  std::tuple<int64_t const*, int64_t const*>\n    getIndices() const\n  {\n    return std::make_tuple(&mRowIndex, &mRowIndex);\n  }\n\n  std::tuple<uint64_t const*>\n    getOffsets() const\n  {\n    return std::make_tuple(&mOffset);\n  }\n\n  void setCursor(int64_t i)\n  {\n    this->mRowIndex = i;\n  }\n  void moveByIndex(int64_t i)\n  {\n    this->mRowIndex += i;\n  }\n\n  void moveToEnd()\n  {\n    this->setCursor(mMaxRow);\n  }\n\n  bool operator!=(DefaultIndexPolicy const& other) const\n  {\n    return O2_BUILTIN_LIKELY(this->mRowIndex != other.mRowIndex);\n  }\n\n  bool operator==(DefaultIndexPolicy const& other) const\n  {\n    return O2_BUILTIN_UNLIKELY(this->mRowIndex == other.mRowIndex);\n  }\n\n  bool operator!=(RowViewSentinel const& sentinel) const\n  {\n    return O2_BUILTIN_LIKELY(this->mRowIndex != sentinel.index);\n  }\n\n  bool operator==(RowViewSentinel const& sentinel) const\n  {\n    return O2_BUILTIN_UNLIKELY(this->mRowIndex == sentinel.index);\n  }\n\n  auto size() const\n  {\n    return mMaxRow;\n  }\n\n  int64_t mMaxRow = 0;\n};\n\nstruct FilteredIndexPolicy : IndexPolicyBase {\n  // We use -1 in the IndexPolicyBase to indicate that the index is\n  // invalid. What will validate the index is the this->setCursor()\n  // which happens below which will properly setup the first index\n  // by remapping the filtered index 0 to whatever unfiltered index\n  // it belongs to.\n  FilteredIndexPolicy(gsl::span<int64_t const> selection, uint64_t offset = 0)\n    : IndexPolicyBase{-1, offset},\n      mSelectedRows(selection),\n      mMaxSelection(selection.size())\n  {\n    this->setCursor(0);\n  }\n\n  FilteredIndexPolicy() = default;\n  FilteredIndexPolicy(FilteredIndexPolicy&&) = default;\n  FilteredIndexPolicy(FilteredIndexPolicy const&) = default;\n  FilteredIndexPolicy& operator=(FilteredIndexPolicy const&) = default;\n  FilteredIndexPolicy& operator=(FilteredIndexPolicy&&) = default;\n\n  std::tuple<int64_t const*, int64_t const*>\n    getIndices() const\n  {\n    return std::make_tuple(&mRowIndex, &mSelectionRow);\n  }\n\n  std::tuple<uint64_t const*>\n    getOffsets() const\n  {\n    return std::make_tuple(&mOffset);\n  }\n\n  void limitRange(int64_t start, int64_t end)\n  {\n    this->setCursor(start);\n    if (end >= 0) {\n      mMaxSelection = std::min(end, mMaxSelection);\n    }\n  }\n\n  void setCursor(int64_t i)\n  {\n    mSelectionRow = i;\n    updateRow();\n  }\n\n  void moveByIndex(int64_t i)\n  {\n    mSelectionRow += i;\n    updateRow();\n  }\n\n  bool operator!=(FilteredIndexPolicy const& other) const\n  {\n    return O2_BUILTIN_LIKELY(mSelectionRow != other.mSelectionRow);\n  }\n\n  bool operator==(FilteredIndexPolicy const& other) const\n  {\n    return O2_BUILTIN_UNLIKELY(mSelectionRow == other.mSelectionRow);\n  }\n\n  bool operator!=(RowViewSentinel const& sentinel) const\n  {\n    return O2_BUILTIN_LIKELY(mSelectionRow != sentinel.index);\n  }\n\n  bool operator==(RowViewSentinel const& sentinel) const\n  {\n    return O2_BUILTIN_UNLIKELY(mSelectionRow == sentinel.index);\n  }\n\n  /// Move iterator to one after the end. Since this is a view\n  /// we move the mSelectionRow to one past the view size and\n  /// the mRowIndex to one past the last entry in the selection\n  void moveToEnd()\n  {\n    this->mSelectionRow = this->mMaxSelection;\n    this->mRowIndex = -1;\n  }\n\n  auto getSelectionRow() const\n  {\n    return mSelectionRow;\n  }\n\n  auto size() const\n  {\n    return mMaxSelection;\n  }\n\n private:\n  inline void updateRow()\n  {\n    this->mRowIndex = O2_BUILTIN_LIKELY(mSelectionRow < mMaxSelection) ? mSelectedRows[mSelectionRow] : -1;\n  }\n  gsl::span<int64_t const> mSelectedRows;\n  int64_t mSelectionRow = 0;\n  int64_t mMaxSelection = 0;\n};\n\ntemplate <typename... C>\nclass Table;\n\n/// Similar to a pair but not a pair, to avoid\n/// exposing the second type everywhere.\ntemplate <typename C>\nstruct ColumnDataHolder {\n  C* first;\n  arrow::ChunkedArray* second;\n};\n\ntemplate <typename IP, typename... C>\nstruct RowViewCore : public IP, C... {\n public:\n  using policy_t = IP;\n  using table_t = o2::soa::Table<C...>;\n  using all_columns = framework::pack<C...>;\n  using persistent_columns_t = framework::selected_pack<is_persistent_t, C...>;\n  using dynamic_columns_t = framework::selected_pack<is_dynamic_t, C...>;\n  using index_columns_t = framework::selected_pack<is_index_t, C...>;\n  constexpr inline static bool has_index_v = framework::pack_size(index_columns_t{}) > 0;\n  using external_index_columns_t = framework::selected_pack<is_external_index_t, C...>;\n  using internal_index_columns_t = framework::selected_pack<is_self_index_t, C...>;\n\n  RowViewCore(arrow::ChunkedArray* columnData[sizeof...(C)], IP&& policy)\n    : IP{policy},\n      C(columnData[framework::has_type_at_v<C>(all_columns{})])...\n  {\n    bindIterators(persistent_columns_t{});\n    bindAllDynamicColumns(dynamic_columns_t{});\n    // In case we have an index column might need to constrain the actual\n    // number of rows in the view to the range provided by the index.\n    // FIXME: we should really understand what happens to an index when we\n    // have a RowViewFiltered.\n    if constexpr (has_index_v) {\n      this->limitRange(this->rangeStart(), this->rangeEnd());\n    }\n  }\n\n  RowViewCore() = default;\n  RowViewCore(RowViewCore<IP, C...> const& other)\n    : IP{static_cast<IP const&>(other)},\n      C(static_cast<C const&>(other))...\n  {\n    bindIterators(persistent_columns_t{});\n    bindAllDynamicColumns(dynamic_columns_t{});\n  }\n\n  RowViewCore(RowViewCore&& other) noexcept\n  {\n    IP::operator=(static_cast<IP&&>(other));\n    (void(static_cast<C&>(*this) = static_cast<C&&>(other)), ...);\n    bindIterators(persistent_columns_t{});\n    bindAllDynamicColumns(dynamic_columns_t{});\n  }\n\n  RowViewCore& operator=(RowViewCore const& other)\n  {\n    IP::operator=(static_cast<IP const&>(other));\n    (void(static_cast<C&>(*this) = static_cast<C const&>(other)), ...);\n    bindIterators(persistent_columns_t{});\n    bindAllDynamicColumns(dynamic_columns_t{});\n    return *this;\n  }\n\n  RowViewCore& operator=(RowViewCore&& other) noexcept\n  {\n    IP::operator=(static_cast<IP&&>(other));\n    (void(static_cast<C&>(*this) = static_cast<C&&>(other)), ...);\n    return *this;\n  }\n\n  RowViewCore& operator++()\n  {\n    this->moveByIndex(1);\n    return *this;\n  }\n\n  RowViewCore operator++(int)\n  {\n    RowViewCore<IP, C...> copy = *this;\n    this->operator++();\n    return copy;\n  }\n\n  RowViewCore& operator--()\n  {\n    this->moveByIndex(-1);\n    return *this;\n  }\n\n  RowViewCore operator--(int)\n  {\n    RowViewCore<IP, C...> copy = *this;\n    this->operator--();\n    return copy;\n  }\n\n  /// Allow incrementing by more than one the iterator\n  RowViewCore operator+(int64_t inc) const\n  {\n    RowViewCore copy = *this;\n    copy.moveByIndex(inc);\n    return copy;\n  }\n\n  RowViewCore operator-(int64_t dec) const\n  {\n    return operator+(-dec);\n  }\n\n  RowViewCore const& operator*() const\n  {\n    return *this;\n  }\n\n  /// Inequality operator. Actual implementation\n  /// depend on the policy we use for the index.\n  using IP::operator!=;\n\n  /// Equality operator. Actual implementation\n  /// depend on the policy we use for the index.\n  using IP::operator==;\n\n  template <typename... CL, typename TA>\n  void doSetCurrentIndex(framework::pack<CL...>, TA* current)\n  {\n    (CL::setCurrent(current), ...);\n  }\n\n  template <typename CL>\n  auto getCurrent() const\n  {\n    return CL::getCurrentRaw();\n  }\n\n  template <typename... Cs>\n  auto getIndexBindingsImpl(framework::pack<Cs...>) const\n  {\n    return std::vector<void const*>{static_cast<Cs const&>(*this).getCurrentRaw()...};\n  }\n\n  auto getIndexBindings() const\n  {\n    return getIndexBindingsImpl(external_index_columns_t{});\n  }\n\n  template <typename... TA>\n  void bindExternalIndices(TA*... current)\n  {\n    (doSetCurrentIndex(external_index_columns_t{}, current), ...);\n  }\n\n  template <typename... Cs>\n  void doSetCurrentIndexRaw(framework::pack<Cs...> p, std::vector<void const*>&& ptrs)\n  {\n    (Cs::setCurrentRaw(ptrs[framework::has_type_at_v<Cs>(p)]), ...);\n  }\n\n  template <typename... Cs, typename E>\n  void doSetCurrentInternal(framework::pack<Cs...>, E* ptr)\n  {\n    (Cs::setCurrentRaw(ptr), ...);\n  }\n\n  void bindExternalIndicesRaw(std::vector<void const*>&& ptrs)\n  {\n    doSetCurrentIndexRaw(external_index_columns_t{}, std::forward<std::vector<void const*>>(ptrs));\n  }\n\n  template <typename E>\n  void bindInternalIndices(E* table)\n  {\n    doSetCurrentInternal(internal_index_columns_t{}, table);\n  }\n\n private:\n  /// Helper to move to the correct chunk, if needed.\n  /// FIXME: not needed?\n  template <typename... PC>\n  void checkNextChunk(framework::pack<PC...>)\n  {\n    (PC::mColumnIterator.checkNextChunk(), ...);\n  }\n\n  /// Helper to move at the end of columns which actually have an iterator.\n  template <typename... PC>\n  void doMoveToEnd(framework::pack<PC...>)\n  {\n    (PC::mColumnIterator.moveToEnd(), ...);\n  }\n\n  /// Helper which binds all the ColumnIterators to the\n  /// index of a the associated RowView\n  template <typename... PC>\n  auto bindIterators(framework::pack<PC...>)\n  {\n    using namespace o2::soa;\n    (void(PC::mColumnIterator.mCurrentPos = &this->mRowIndex), ...);\n  }\n\n  template <typename... DC>\n  auto bindAllDynamicColumns(framework::pack<DC...>)\n  {\n    using namespace o2::soa;\n    (bindDynamicColumn<DC>(typename DC::bindings_t{}), ...);\n    if constexpr (has_index_v) {\n      this->setIndices(this->getIndices());\n      this->setOffsets(this->getOffsets());\n    }\n  }\n\n  template <typename DC, typename... B>\n  auto bindDynamicColumn(framework::pack<B...>)\n  {\n    DC::boundIterators = std::make_tuple(&(B::mColumnIterator)...);\n  }\n};\n\ntemplate <typename, typename = void>\nconstexpr bool is_type_with_policy_v = false;\n\ntemplate <typename T>\nconstexpr bool is_type_with_policy_v<T, std::void_t<decltype(sizeof(typename T::policy_t))>> = true;\n\nstruct ArrowHelpers {\n  static std::shared_ptr<arrow::Table> joinTables(std::vector<std::shared_ptr<arrow::Table>>&& tables);\n  static std::shared_ptr<arrow::Table> concatTables(std::vector<std::shared_ptr<arrow::Table>>&& tables);\n};\n\ntemplate <typename... T>\nusing originals_pack_t = decltype(make_originals_from_type<T...>());\n\ntemplate <typename T>\nusing is_soa_iterator_t = typename framework::is_base_of_template<RowViewCore, T>;\n\ntemplate <typename T>\nconstexpr bool is_soa_iterator_v()\n{\n  return is_soa_iterator_t<T>::value || framework::is_specialization_v<T, RowViewCore>;\n}\n\ntemplate <typename T>\nusing is_soa_table_t = typename framework::is_specialization<T, soa::Table>;\n\ntemplate <typename T>\nusing is_soa_table_like_t = typename framework::is_base_of_template<soa::Table, T>;\n\n/// Helper function to extract bound indices\ntemplate <typename... Is>\nstatic constexpr auto extractBindings(framework::pack<Is...>)\n{\n  return framework::pack<typename Is::binding_t...>{};\n}\n\ntemplate <typename T>\nclass Filtered;\n\nSelectionVector selectionToVector(gandiva::Selection const& sel);\n\ntemplate <typename T>\nauto select(T const& t, framework::expressions::Filter const& f)\n{\n  return Filtered<T>({t.asArrowTable()}, selectionToVector(framework::expressions::createSelection(t.asArrowTable(), f)));\n}\n\ntemplate <typename T>\nauto sliceBy(T const& t, framework::expressions::BindingNode const& node, int value)\n{\n  uint64_t offset = 0;\n  std::shared_ptr<arrow::Table> result = nullptr;\n  auto status = o2::framework::getSliceFor(value, node.name.c_str(), t.asArrowTable(), result, offset);\n  if (status.ok()) {\n    return T({result}, offset);\n  }\n  o2::framework::throw_error(o2::framework::runtime_error(\"Failed to slice table\"));\n  O2_BUILTIN_UNREACHABLE();\n}\n\narrow::ChunkedArray* getIndexFromLabel(arrow::Table* table, const char* label);\n\n/// A Table class which observes an arrow::Table and provides\n/// It is templated on a set of Column / DynamicColumn types.\ntemplate <typename... C>\nclass Table\n{\n public:\n  using table_t = Table<C...>;\n  using columns = framework::pack<C...>;\n  using column_types = framework::pack<typename C::type...>;\n  using persistent_columns_t = framework::selected_pack<is_persistent_t, C...>;\n  using external_index_columns_t = framework::selected_pack<is_external_index_t, C...>;\n\n  static constexpr auto hashes()\n  {\n    return std::set{typeid(C).hash_code()...};\n  }\n\n  template <typename IP, typename Parent, typename... T>\n  struct RowViewBase : public RowViewCore<IP, C...> {\n\n    using external_index_columns_t = framework::selected_pack<is_external_index_t, C...>;\n    using bindings_pack_t = decltype(extractBindings(external_index_columns_t{}));\n    using parent_t = Parent;\n    using originals = originals_pack_t<T...>;\n\n    RowViewBase(arrow::ChunkedArray* columnData[sizeof...(C)], IP&& policy)\n      : RowViewCore<IP, C...>(columnData, std::forward<decltype(policy)>(policy))\n    {\n    }\n\n    template <typename Tbl = table_t>\n    RowViewBase(RowViewBase<IP, Tbl, Tbl> const& other)\n      : RowViewCore<IP, C...>(other)\n    {\n    }\n\n    template <typename Tbl = table_t>\n    RowViewBase(RowViewBase<IP, Tbl, Tbl>&& other) noexcept\n      : RowViewCore<IP, C...>(other)\n    {\n    }\n\n    RowViewBase() = default;\n    RowViewBase(RowViewBase const&) = default;\n    RowViewBase(RowViewBase&&) = default;\n\n    RowViewBase& operator=(RowViewBase const&) = default;\n    RowViewBase& operator=(RowViewBase&&) = default;\n\n    RowViewBase& operator=(RowViewSentinel const& other)\n    {\n      this->mRowIndex = other.index;\n      return *this;\n    }\n\n    void matchTo(RowViewBase const& other)\n    {\n      this->mRowIndex = other.mRowIndex;\n    }\n\n    template <typename TI>\n    auto getId() const\n    {\n      using decayed = std::decay_t<TI>;\n      if constexpr (framework::has_type_v<decayed, bindings_pack_t>) {\n        constexpr auto idx = framework::has_type_at_v<decayed>(bindings_pack_t{});\n        return framework::pack_element_t<idx, external_index_columns_t>::getId();\n      } else if constexpr (std::is_same_v<decayed, Parent>) {\n        return this->globalIndex();\n      } else {\n        return static_cast<int32_t>(-1);\n      }\n    }\n\n    using IP::size;\n\n    using RowViewCore<IP, C...>::operator++;\n\n    /// Allow incrementing by more than one the iterator\n    RowViewBase operator+(int64_t inc) const\n    {\n      RowViewBase copy = *this;\n      copy.moveByIndex(inc);\n      return copy;\n    }\n\n    RowViewBase operator-(int64_t dec) const\n    {\n      return operator+(-dec);\n    }\n\n    RowViewBase const& operator*() const\n    {\n      return *this;\n    }\n  };\n  template <typename P, typename... Ts>\n  using RowView = RowViewBase<DefaultIndexPolicy, P, Ts...>;\n\n  template <typename P, typename... Ts>\n  using RowViewFiltered = RowViewBase<FilteredIndexPolicy, P, Ts...>;\n\n  using iterator = RowView<table_t, table_t>;\n  using const_iterator = RowView<table_t, table_t>;\n  using unfiltered_iterator = RowView<table_t, table_t>;\n  using unfiltered_const_iterator = RowView<table_t, table_t>;\n  using filtered_iterator = RowViewFiltered<table_t, table_t>;\n  using filtered_const_iterator = RowViewFiltered<table_t, table_t>;\n\n  Table(std::shared_ptr<arrow::Table> table, uint64_t offset = 0)\n    : mTable(table),\n      mEnd{static_cast<uint64_t>(table->num_rows())},\n      mOffset(offset)\n  {\n    if (mTable->num_rows() == 0) {\n      for (size_t ci = 0; ci < sizeof...(C); ++ci) {\n        mColumnChunks[ci] = nullptr;\n      }\n      mBegin = mEnd;\n    } else {\n      arrow::ChunkedArray* lookups[] = {lookupColumn<C>()...};\n      for (size_t ci = 0; ci < sizeof...(C); ++ci) {\n        mColumnChunks[ci] = lookups[ci];\n      }\n      mBegin = unfiltered_iterator{mColumnChunks, {table->num_rows(), offset}};\n      bindInternalIndices();\n    }\n  }\n\n  /// FIXME: this is to be able to construct a Filtered without explicit Join\n  ///        so that Filtered<Table1,Table2, ...> always means a Join which\n  ///        may or may not be a problem later\n  Table(std::vector<std::shared_ptr<arrow::Table>>&& tables, uint64_t offset = 0)\n    : Table(ArrowHelpers::joinTables(std::move(tables)), offset)\n  {\n  }\n\n  unfiltered_iterator begin()\n  {\n    return unfiltered_iterator(mBegin);\n  }\n\n  RowViewSentinel end()\n  {\n    return RowViewSentinel{mEnd};\n  }\n\n  filtered_iterator filtered_begin(gsl::span<int64_t const> selection)\n  {\n    // Note that the FilteredIndexPolicy will never outlive the selection which\n    // is held by the table, so we are safe passing the bare pointer. If it does it\n    // means that the iterator on a table is outliving the table itself, which is\n    // a bad idea.\n    return filtered_iterator(mColumnChunks, {selection, mOffset});\n  }\n\n  iterator iteratorAt(uint64_t i) const\n  {\n    return rawIteratorAt(i);\n  }\n\n  unfiltered_iterator rawIteratorAt(uint64_t i) const\n  {\n    auto it = mBegin + i;\n    it.bindInternalIndices((void*)this);\n    return it;\n  }\n\n  unfiltered_const_iterator begin() const\n  {\n    return unfiltered_const_iterator(mBegin);\n  }\n\n  RowViewSentinel end() const\n  {\n    return RowViewSentinel{mEnd};\n  }\n\n  /// Return a type erased arrow table backing store for / the type safe table.\n  std::shared_ptr<arrow::Table> asArrowTable() const\n  {\n    return mTable;\n  }\n  /// Return offset\n  auto offset() const\n  {\n    return mOffset;\n  }\n  /// Size of the table, in rows.\n  int64_t size() const\n  {\n    return mTable->num_rows();\n  }\n\n  int64_t tableSize() const\n  {\n    return size();\n  }\n\n  /// Bind the columns which refer to other tables\n  /// to the associated tables.\n  template <typename... TA>\n  void bindExternalIndices(TA*... current)\n  {\n    mBegin.bindExternalIndices(current...);\n  }\n\n  void bindInternalIndices()\n  {\n    mBegin.bindInternalIndices(this);\n  }\n\n  template <typename T>\n  void bindInternalIndicesTo(T* ptr)\n  {\n    mBegin.bindInternalIndices(ptr);\n  }\n\n  void bindExternalIndicesRaw(std::vector<void const*>&& ptrs)\n  {\n    mBegin.bindExternalIndicesRaw(std::forward<std::vector<void const*>>(ptrs));\n  }\n\n  template <typename T, typename... Cs>\n  void doCopyIndexBindings(framework::pack<Cs...>, T& dest) const\n  {\n    dest.bindExternalIndicesRaw(mBegin.getIndexBindings());\n  }\n\n  template <typename T>\n  void copyIndexBindings(T& dest) const\n  {\n    doCopyIndexBindings(external_index_columns_t{}, dest);\n  }\n\n  auto select(framework::expressions::Filter const& f) const\n  {\n    auto t = o2::soa::select(*this, f);\n    copyIndexBindings(t);\n    return t;\n  }\n\n  auto sliceByCached(framework::expressions::BindingNode const& node, int value)\n  {\n    uint64_t offset = 0;\n    std::shared_ptr<arrow::Table> result = nullptr;\n    auto status = this->getSliceFor(value, node.name.c_str(), result, offset);\n    if (status.ok()) {\n      auto t = table_t({result}, offset);\n      copyIndexBindings(t);\n      return t;\n    }\n    o2::framework::throw_error(o2::framework::runtime_error(\"Failed to slice table\"));\n    O2_BUILTIN_UNREACHABLE();\n  }\n\n  auto sliceBy(framework::expressions::BindingNode const& node, int value) const\n  {\n    auto t = o2::soa::sliceBy(*this, node, value);\n    copyIndexBindings(t);\n    return t;\n  }\n\n  auto slice(uint64_t start, uint64_t end) const\n  {\n    return rawSlice(start, end);\n  }\n\n  auto rawSlice(uint64_t start, uint64_t end) const\n  {\n    return table_t{mTable->Slice(start, end - start + 1), start};\n  }\n\n  auto emptySlice() const\n  {\n    return table_t{mTable->Slice(0, 0), 0};\n  }\n\n protected:\n  /// Offset of the table within a larger table.\n  uint64_t mOffset;\n\n private:\n  template <typename T>\n  arrow::ChunkedArray* lookupColumn()\n  {\n    if constexpr (T::persistent::value) {\n      auto label = T::columnLabel();\n      return getIndexFromLabel(mTable.get(), label);\n    } else {\n      return nullptr;\n    }\n  }\n  std::shared_ptr<arrow::Table> mTable;\n  // Cached pointers to the ChunkedArray associated to a column\n  arrow::ChunkedArray* mColumnChunks[sizeof...(C)];\n  /// Cached begin iterator for this table.\n  unfiltered_iterator mBegin;\n  /// Cached end iterator for this table.\n  RowViewSentinel mEnd;\n  std::string mCurrentKey;\n  std::shared_ptr<arrow::NumericArray<arrow::Int32Type>> mValues = nullptr;\n  std::shared_ptr<arrow::NumericArray<arrow::Int64Type>> mCounts = nullptr;\n\n  arrow::Status initializeSliceCaches(char const* key)\n  {\n    mCurrentKey = key;\n    return o2::framework::getSlices(key, mTable, mValues, mCounts);\n  }\n\n public:\n  arrow::Status getSliceFor(int value, const char* key, std::shared_ptr<arrow::Table>& output, uint64_t& offset)\n  {\n    arrow::Status status;\n    if (mCurrentKey != key) {\n      status = initializeSliceCaches(key);\n    }\n    if (!status.ok()) {\n      return status;\n    }\n    for (auto slice = 0; slice < mValues->length(); ++slice) {\n      if (mValues->Value(slice) == value) {\n        output = mTable->Slice(offset, mCounts->Value(slice));\n        return arrow::Status::OK();\n      }\n      offset += mCounts->Value(slice);\n    }\n    output = mTable->Slice(offset, 0);\n    return arrow::Status::OK();\n  }\n};\n\ntemplate <typename T>\nstruct PackToTable {\n  static_assert(framework::always_static_assert_v<T>, \"Not a pack\");\n};\n\ntemplate <typename... C>\nstruct PackToTable<framework::pack<C...>> {\n  using table = o2::soa::Table<C...>;\n};\n\ntemplate <typename... T>\nstruct TableWrap {\n  using all_columns = framework::concatenated_pack_unique_t<typename T::columns...>;\n  using table_t = typename PackToTable<all_columns>::table;\n};\n\n/// Template trait which allows to map a given\n/// Table type to its O2 DataModel origin and description\ntemplate <typename INHERIT>\nclass TableMetadata\n{\n public:\n  static constexpr char const* tableLabel() { return INHERIT::mLabel; }\n  static constexpr char const (&origin())[4] { return INHERIT::mOrigin; }\n  static constexpr char const (&description())[16] { return INHERIT::mDescription; }\n  static std::string sourceSpec() { return fmt::format(\"{}/{}/{}\", INHERIT::mLabel, INHERIT::mOrigin, INHERIT::mDescription); };\n};\n\n/// Helper template to define universal join\ntemplate <typename Key, typename H, typename... Ts>\nstruct IndexTable;\n\ntemplate <typename... C1, typename... C2>\nconstexpr auto joinTables(o2::soa::Table<C1...> const& t1, o2::soa::Table<C2...> const& t2)\n{\n  return o2::soa::Table<C1..., C2...>(ArrowHelpers::joinTables({t1.asArrowTable(), t2.asArrowTable()}));\n}\n\n// special case for appending an index\ntemplate <typename... C1, typename Key, typename H, typename... C2>\nconstexpr auto joinTables(o2::soa::Table<C1...> const& t1, o2::soa::IndexTable<Key, H, C2...> const& t2)\n{\n  return joinTables(t1, o2::soa::Table<H, C2...>{t2.asArrowTable()});\n}\n\ntemplate <typename T, typename... C, typename... O>\nconstexpr auto joinLeft(T const& t1, o2::soa::Table<C...> const& t2, framework::pack<O...>)\n{\n  return typename o2::soa::TableWrap<O..., o2::soa::Table<C...>>::table_t(ArrowHelpers::joinTables({t1.asArrowTable(), t2.asArrowTable()}));\n}\n\ntemplate <typename T, typename... C, typename... O>\nconstexpr auto joinRight(o2::soa::Table<C...> const& t1, T const& t2, framework::pack<O...>)\n{\n  return typename o2::soa::TableWrap<o2::soa::Table<C...>, O...>::table_t(ArrowHelpers::joinTables({t1.asArrowTable(), t2.asArrowTable()}));\n}\n\ntemplate <typename T1, typename T2, typename... O1, typename... O2>\nconstexpr auto joinBoth(T1 const& t1, T2 const& t2, framework::pack<O1...>, framework::pack<O2...>)\n{\n  return typename o2::soa::TableWrap<O1..., O2...>::table_t(ArrowHelpers::joinTables({t1.asArrowTable(), t2.asArrowTable()}));\n}\n\ntemplate <typename T1, typename T2>\nconstexpr auto join(T1 const& t1, T2 const& t2)\n{\n  if constexpr (soa::is_type_with_originals_v<T1>) {\n    if constexpr (soa::is_type_with_originals_v<T2>) {\n      return joinBoth(t1, t2, typename T1::originals{}, typename T2::originals{});\n    } else {\n      return joinLeft(t1, t2, typename T1::originals{});\n    }\n  } else {\n    if constexpr (soa::is_type_with_originals_v<T2>) {\n      return joinRight(t1, t2, typename T2::originals{});\n    } else {\n      return joinTables(t1, t2);\n    }\n  }\n}\n\ntemplate <typename T1, typename T2, typename... Ts>\nconstexpr auto join(T1 const& t1, T2 const& t2, Ts const&... ts)\n{\n  return join(t1, join(t2, ts...));\n}\n\ntemplate <typename T1, typename T2>\nconstexpr auto concat(T1&& t1, T2&& t2)\n{\n  using table_t = typename PackToTable<framework::intersected_pack_t<typename T1::columns, typename T2::columns>>::table;\n  return table_t(ArrowHelpers::concatTables({t1.asArrowTable(), t2.asArrowTable()}));\n}\n\ntemplate <typename... Ts>\nusing JoinBase = decltype(join(std::declval<Ts>()...));\n\ntemplate <typename T1, typename T2>\nusing ConcatBase = decltype(concat(std::declval<T1>(), std::declval<T2>()));\n\ntemplate <typename B, typename E>\nstruct EquivalentIndex {\n  constexpr static bool value = false;\n};\n\ntemplate <typename B, typename E>\nconstexpr bool is_index_equivalent_v = EquivalentIndex<B, E>::value || EquivalentIndex<E, B>::value;\n\ntemplate <typename T, typename... Os>\nconstexpr bool are_bindings_compatible_v(framework::pack<Os...>&&)\n{\n  if constexpr (is_type_with_originals_v<T>) {\n    return (are_bindings_compatible_v<Os>(originals_pack_t<T>{}) || ...);\n  } else {\n    return ((std::is_same_v<T, Os> || is_index_equivalent_v<T, Os>) || ...);\n  }\n}\n\ntemplate <typename T, typename B>\nconstexpr bool is_binding_compatible_v()\n{\n  return are_bindings_compatible_v<T>(originals_pack_t<B>{});\n}\n\nvoid notBoundTable(const char* tableName);\n} // namespace o2::soa\n\n#define DECLARE_SOA_STORE()          \\\n  template <typename T>              \\\n  struct MetadataTrait {             \\\n    using metadata = std::void_t<T>; \\\n  }\n\n#define DECLARE_EQUIVALENT_FOR_INDEX(_Base_, _Equiv_) \\\n  template <>                                         \\\n  struct EquivalentIndex<_Base_, _Equiv_> {           \\\n    constexpr static bool value = true;               \\\n  }\n\n#define DECLARE_SOA_COLUMN_FULL(_Name_, _Getter_, _Type_, _Label_)                                                                                                                \\\n  struct _Name_ : o2::soa::Column<_Type_, _Name_> {                                                                                                                               \\\n    static constexpr const char* mLabel = _Label_;                                                                                                                                \\\n    static_assert(!((*(mLabel + 1) == 'I' && *(mLabel + 2) == 'n' && *(mLabel + 3) == 'd' && *(mLabel + 4) == 'e' && *(mLabel + 5) == 'x')), \"Index is not a valid column name\"); \\\n    using base = o2::soa::Column<_Type_, _Name_>;                                                                                                                                 \\\n    using type = _Type_;                                                                                                                                                          \\\n    using column_t = _Name_;                                                                                                                                                      \\\n    _Name_(arrow::ChunkedArray const* column)                                                                                                                                     \\\n      : o2::soa::Column<_Type_, _Name_>(o2::soa::ColumnIterator<type>(column))                                                                                                    \\\n    {                                                                                                                                                                             \\\n    }                                                                                                                                                                             \\\n                                                                                                                                                                                  \\\n    _Name_() = default;                                                                                                                                                           \\\n    _Name_(_Name_ const& other) = default;                                                                                                                                        \\\n    _Name_& operator=(_Name_ const& other) = default;                                                                                                                             \\\n                                                                                                                                                                                  \\\n    decltype(auto) _Getter_() const                                                                                                                                               \\\n    {                                                                                                                                                                             \\\n      return *mColumnIterator;                                                                                                                                                    \\\n    }                                                                                                                                                                             \\\n  };                                                                                                                                                                              \\\n  static const o2::framework::expressions::BindingNode _Getter_ { _Label_, typeid(_Name_).hash_code(),                                                                            \\\n                                                                  o2::framework::expressions::selectArrowType<_Type_>() }\n\n#define DECLARE_SOA_COLUMN(_Name_, _Getter_, _Type_) \\\n  DECLARE_SOA_COLUMN_FULL(_Name_, _Getter_, _Type_, \"f\" #_Name_)\n\n/// An 'expression' column. i.e. a column that can be calculated from other\n/// columns with gandiva based on supplied C++ expression.\n#define DECLARE_SOA_EXPRESSION_COLUMN_FULL(_Name_, _Getter_, _Type_, _Label_, _Expression_)            \\\n  struct _Name_ : o2::soa::Column<_Type_, _Name_> {                                                    \\\n    static constexpr const char* mLabel = _Label_;                                                     \\\n    using base = o2::soa::Column<_Type_, _Name_>;                                                      \\\n    using type = _Type_;                                                                               \\\n    using column_t = _Name_;                                                                           \\\n    using spawnable_t = std::true_type;                                                                \\\n    _Name_(arrow::ChunkedArray const* column)                                                          \\\n      : o2::soa::Column<_Type_, _Name_>(o2::soa::ColumnIterator<type>(column))                         \\\n    {                                                                                                  \\\n    }                                                                                                  \\\n                                                                                                       \\\n    _Name_() = default;                                                                                \\\n    _Name_(_Name_ const& other) = default;                                                             \\\n    _Name_& operator=(_Name_ const& other) = default;                                                  \\\n                                                                                                       \\\n    decltype(auto) _Getter_() const                                                                    \\\n    {                                                                                                  \\\n      return *mColumnIterator;                                                                         \\\n    }                                                                                                  \\\n    static o2::framework::expressions::Projector Projector()                                           \\\n    {                                                                                                  \\\n      return _Expression_;                                                                             \\\n    }                                                                                                  \\\n  };                                                                                                   \\\n  static const o2::framework::expressions::BindingNode _Getter_ { _Label_, typeid(_Name_).hash_code(), \\\n                                                                  o2::framework::expressions::selectArrowType<_Type_>() }\n\n#define DECLARE_SOA_EXPRESSION_COLUMN(_Name_, _Getter_, _Type_, _Expression_) \\\n  DECLARE_SOA_EXPRESSION_COLUMN_FULL(_Name_, _Getter_, _Type_, \"f\" #_Name_, _Expression_);\n\n/// An index column is a column of indices to elements / of another table named\n/// _Name_##s. The column name will be _Name_##Id and will always be stored in\n/// \"fIndex\"#_Table_#[_Suffix_]. If _Suffix_ is not empty it has to begin\n/// with _ (underscore) to make the columns identifiable for the table merging\n/// It will also have two special methods, setCurrent(...)\n/// and getCurrent(...) which allow you to set / retrieve associated table.\n/// It also exposes a getter _Getter_ which allows you to retrieve the pointed\n/// object.\n/// Notice how in order to define an index column, the table it points\n/// to **must** be already declared. This is therefore only\n/// useful to express child -> parent relationships. In case one\n/// needs to go from parent to child, the only way is to either have\n/// a separate \"association\" with the two indices, or to use the standard\n/// grouping mechanism of AnalysisTask.\n///\n/// Normal index: returns iterator to a bound table\n/// Slice  index: return an instance of the bound table type with a slice defined by the values in 0 and 1st elements\n/// Array  index: return an array of iterators, defined by values in its elements\n\n/// SLICE\n#define DECLARE_SOA_SLICE_INDEX_COLUMN_FULL(_Name_, _Getter_, _Type_, _Table_, _Suffix_)    \\\n  struct _Name_##IdSlice : o2::soa::Column<_Type_[2], _Name_##IdSlice> {                    \\\n    static_assert(std::is_integral_v<_Type_>, \"Index type must be integral\");               \\\n    static_assert((*_Suffix_ == '\\0') || (*_Suffix_ == '_'), \"Suffix has to begin with _\"); \\\n    static constexpr const char* mLabel = \"fIndexSlice\" #_Table_ _Suffix_;                  \\\n    using base = o2::soa::Column<_Type_[2], _Name_##IdSlice>;                               \\\n    using type = _Type_[2];                                                                 \\\n    using column_t = _Name_##IdSlice;                                                       \\\n    using binding_t = _Table_;                                                              \\\n    _Name_##IdSlice(arrow::ChunkedArray const* column)                                      \\\n      : o2::soa::Column<_Type_[2], _Name_##IdSlice>(o2::soa::ColumnIterator<type>(column))  \\\n    {                                                                                       \\\n    }                                                                                       \\\n                                                                                            \\\n    _Name_##IdSlice() = default;                                                            \\\n    _Name_##IdSlice(_Name_##IdSlice const& other) = default;                                \\\n    _Name_##IdSlice& operator=(_Name_##IdSlice const& other) = default;                     \\\n    std::array<_Type_, 2> inline getIds() const                                             \\\n    {                                                                                       \\\n      return _Getter_##Ids();                                                               \\\n    }                                                                                       \\\n                                                                                            \\\n    bool has_##_Getter_() const                                                             \\\n    {                                                                                       \\\n      auto a = *mColumnIterator;                                                            \\\n      return a[0] >= 0 && a[1] >= 0;                                                        \\\n    }                                                                                       \\\n                                                                                            \\\n    std::array<_Type_, 2> _Getter_##Ids() const                                             \\\n    {                                                                                       \\\n      auto a = *mColumnIterator;                                                            \\\n      return std::array{a[0], a[1]};                                                        \\\n    }                                                                                       \\\n                                                                                            \\\n    template <typename T>                                                                   \\\n    auto _Getter_##_as() const                                                              \\\n    {                                                                                       \\\n      if (O2_BUILTIN_UNLIKELY(mBinding == nullptr)) {                                       \\\n        o2::soa::notBoundTable(#_Table_);                                                   \\\n      }                                                                                     \\\n      if (O2_BUILTIN_UNLIKELY(!has_##_Getter_())) {                                         \\\n        return static_cast<T const*>(mBinding)->emptySlice();                               \\\n      }                                                                                     \\\n      auto a = *mColumnIterator;                                                            \\\n      auto t = static_cast<T const*>(mBinding)->rawSlice(a[0], a[1]);                       \\\n      static_cast<T const*>(mBinding)->copyIndexBindings(t);                                \\\n      return t;                                                                             \\\n    }                                                                                       \\\n                                                                                            \\\n    auto _Getter_() const                                                                   \\\n    {                                                                                       \\\n      return _Getter_##_as<binding_t>();                                                    \\\n    }                                                                                       \\\n                                                                                            \\\n    template <typename T>                                                                   \\\n    bool setCurrent(T* current)                                                             \\\n    {                                                                                       \\\n      if constexpr (o2::soa::is_binding_compatible_v<T, binding_t>()) {                     \\\n        assert(current != nullptr);                                                         \\\n        this->mBinding = current;                                                           \\\n        return true;                                                                        \\\n      }                                                                                     \\\n      return false;                                                                         \\\n    }                                                                                       \\\n                                                                                            \\\n    bool setCurrentRaw(void const* current)                                                 \\\n    {                                                                                       \\\n      this->mBinding = current;                                                             \\\n      return true;                                                                          \\\n    }                                                                                       \\\n    binding_t const* getCurrent() const { return static_cast<binding_t const*>(mBinding); } \\\n    void const* getCurrentRaw() const { return mBinding; }                                  \\\n    void const* mBinding = nullptr;                                                         \\\n  };\n\n#define DECLARE_SOA_SLICE_INDEX_COLUMN(_Name_, _Getter_) DECLARE_SOA_SLICE_INDEX_COLUMN_FULL(_Name_, _Getter_, int32_t, _Name_##s, \"\")\n\n/// ARRAY\n#define DECLARE_SOA_ARRAY_INDEX_COLUMN_FULL(_Name_, _Getter_, _Type_, _Table_, _Suffix_)         \\\n  struct _Name_##Ids : o2::soa::Column<std::vector<_Type_>, _Name_##Ids> {                       \\\n    static_assert(std::is_integral_v<_Type_>, \"Index type must be integral\");                    \\\n    static_assert((*_Suffix_ == '\\0') || (*_Suffix_ == '_'), \"Suffix has to begin with _\");      \\\n    static constexpr const char* mLabel = \"fIndexArray\" #_Table_ _Suffix_;                       \\\n    using base = o2::soa::Column<std::vector<_Type_>, _Name_##Ids>;                              \\\n    using type = std::vector<_Type_>;                                                            \\\n    using column_t = _Name_##Ids;                                                                \\\n    using binding_t = _Table_;                                                                   \\\n    _Name_##Ids(arrow::ChunkedArray const* column)                                               \\\n      : o2::soa::Column<std::vector<_Type_>, _Name_##Ids>(o2::soa::ColumnIterator<type>(column)) \\\n    {                                                                                            \\\n    }                                                                                            \\\n                                                                                                 \\\n    _Name_##Ids() = default;                                                                     \\\n    _Name_##Ids(_Name_##Ids const& other) = default;                                             \\\n    _Name_##Ids& operator=(_Name_##Ids const& other) = default;                                  \\\n                                                                                                 \\\n    gsl::span<const _Type_> inline getIds() const                                                \\\n    {                                                                                            \\\n      return _Getter_##Ids();                                                                    \\\n    }                                                                                            \\\n                                                                                                 \\\n    gsl::span<const _Type_> _Getter_##Ids() const                                                \\\n    {                                                                                            \\\n      return *mColumnIterator;                                                                   \\\n    }                                                                                            \\\n                                                                                                 \\\n    bool has_##_Getter_() const                                                                  \\\n    {                                                                                            \\\n      return !(*mColumnIterator).empty();                                                        \\\n    }                                                                                            \\\n                                                                                                 \\\n    template <typename T>                                                                        \\\n    auto _Getter_##_as() const                                                                   \\\n    {                                                                                            \\\n      if (O2_BUILTIN_UNLIKELY(mBinding == nullptr)) {                                            \\\n        o2::soa::notBoundTable(#_Table_);                                                        \\\n      }                                                                                          \\\n      return getIterators<T>();                                                                  \\\n    }                                                                                            \\\n                                                                                                 \\\n    template <typename T>                                                                        \\\n    auto getIterators() const                                                                    \\\n    {                                                                                            \\\n      auto result = std::vector<typename T::unfiltered_iterator>();                              \\\n      for (auto& i : *mColumnIterator) {                                                         \\\n        result.push_back(static_cast<T const*>(mBinding)->rawIteratorAt(i));                     \\\n      }                                                                                          \\\n      return result;                                                                             \\\n    }                                                                                            \\\n                                                                                                 \\\n    auto _Getter_() const                                                                        \\\n    {                                                                                            \\\n      return _Getter_##_as<binding_t>();                                                         \\\n    }                                                                                            \\\n                                                                                                 \\\n    template <typename T>                                                                        \\\n    auto _Getter_##_first_as() const                                                             \\\n    {                                                                                            \\\n      if (O2_BUILTIN_UNLIKELY(mBinding == nullptr)) {                                            \\\n        o2::soa::notBoundTable(#_Table_);                                                        \\\n      }                                                                                          \\\n      return static_cast<T const*>(mBinding)->rawIteratorAt((*mColumnIterator)[0]);              \\\n    }                                                                                            \\\n                                                                                                 \\\n    template <typename T>                                                                        \\\n    auto _Getter_##_last_as() const                                                              \\\n    {                                                                                            \\\n      if (O2_BUILTIN_UNLIKELY(mBinding == nullptr)) {                                            \\\n        o2::soa::notBoundTable(#_Table_);                                                        \\\n      }                                                                                          \\\n      return static_cast<T const*>(mBinding)->rawIteratorAt((*mColumnIterator).back());          \\\n    }                                                                                            \\\n                                                                                                 \\\n    auto _Getter_first() const                                                                   \\\n    {                                                                                            \\\n      return _Getter_##_first_as<binding_t>();                                                   \\\n    }                                                                                            \\\n                                                                                                 \\\n    auto _Getter_last() const                                                                    \\\n    {                                                                                            \\\n      return _Getter_##_last_as<binding_t>();                                                    \\\n    }                                                                                            \\\n                                                                                                 \\\n    template <typename T>                                                                        \\\n    bool setCurrent(T* current)                                                                  \\\n    {                                                                                            \\\n      if constexpr (o2::soa::is_binding_compatible_v<T, binding_t>()) {                          \\\n        assert(current != nullptr);                                                              \\\n        this->mBinding = current;                                                                \\\n        return true;                                                                             \\\n      }                                                                                          \\\n      return false;                                                                              \\\n    }                                                                                            \\\n                                                                                                 \\\n    bool setCurrentRaw(void const* current)                                                      \\\n    {                                                                                            \\\n      this->mBinding = current;                                                                  \\\n      return true;                                                                               \\\n    }                                                                                            \\\n    binding_t const* getCurrent() const { return static_cast<binding_t const*>(mBinding); }      \\\n    void const* getCurrentRaw() const { return mBinding; }                                       \\\n    void const* mBinding = nullptr;                                                              \\\n  };\n\n#define DECLARE_SOA_ARRAY_INDEX_COLUMN(_Name_, _Getter_) DECLARE_SOA_ARRAY_INDEX_COLUMN_FULL(_Name_, _Getter_, int32_t, _Name_##s, \"\")\n\n/// NORMAL\n#define DECLARE_SOA_INDEX_COLUMN_FULL(_Name_, _Getter_, _Type_, _Table_, _Suffix_)                                                \\\n  struct _Name_##Id : o2::soa::Column<_Type_, _Name_##Id> {                                                                       \\\n    static_assert(std::is_integral_v<_Type_>, \"Index type must be integral\");                                                     \\\n    static_assert((*_Suffix_ == '\\0') || (*_Suffix_ == '_'), \"Suffix has to begin with _\");                                       \\\n    static constexpr const char* mLabel = \"fIndex\" #_Table_ _Suffix_;                                                             \\\n    using base = o2::soa::Column<_Type_, _Name_##Id>;                                                                             \\\n    using type = _Type_;                                                                                                          \\\n    using column_t = _Name_##Id;                                                                                                  \\\n    using binding_t = _Table_;                                                                                                    \\\n    _Name_##Id(arrow::ChunkedArray const* column)                                                                                 \\\n      : o2::soa::Column<_Type_, _Name_##Id>(o2::soa::ColumnIterator<type>(column))                                                \\\n    {                                                                                                                             \\\n    }                                                                                                                             \\\n                                                                                                                                  \\\n    _Name_##Id() = default;                                                                                                       \\\n    _Name_##Id(_Name_##Id const& other) = default;                                                                                \\\n    _Name_##Id& operator=(_Name_##Id const& other) = default;                                                                     \\\n    type inline getId() const                                                                                                     \\\n    {                                                                                                                             \\\n      return _Getter_##Id();                                                                                                      \\\n    }                                                                                                                             \\\n                                                                                                                                  \\\n    type _Getter_##Id() const                                                                                                     \\\n    {                                                                                                                             \\\n      return *mColumnIterator;                                                                                                    \\\n    }                                                                                                                             \\\n                                                                                                                                  \\\n    bool has_##_Getter_() const                                                                                                   \\\n    {                                                                                                                             \\\n      return *mColumnIterator >= 0;                                                                                               \\\n    }                                                                                                                             \\\n                                                                                                                                  \\\n    template <typename T>                                                                                                         \\\n    auto _Getter_##_as() const                                                                                                    \\\n    {                                                                                                                             \\\n      if (O2_BUILTIN_UNLIKELY(mBinding == nullptr)) {                                                                             \\\n        o2::soa::notBoundTable(#_Table_);                                                                                         \\\n      }                                                                                                                           \\\n      if (O2_BUILTIN_UNLIKELY(!has_##_Getter_())) {                                                                               \\\n        throw o2::framework::runtime_error_f(\"Accessing invalid index for %s\", #_Getter_);                                        \\\n      }                                                                                                                           \\\n      return static_cast<T const*>(mBinding)->rawIteratorAt(*mColumnIterator);                                                    \\\n    }                                                                                                                             \\\n                                                                                                                                  \\\n    auto _Getter_() const                                                                                                         \\\n    {                                                                                                                             \\\n      return _Getter_##_as<binding_t>();                                                                                          \\\n    }                                                                                                                             \\\n                                                                                                                                  \\\n    template <typename T>                                                                                                         \\\n    bool setCurrent(T* current)                                                                                                   \\\n    {                                                                                                                             \\\n      if constexpr (o2::soa::is_binding_compatible_v<T, binding_t>()) {                                                           \\\n        assert(current != nullptr);                                                                                               \\\n        this->mBinding = current;                                                                                                 \\\n        return true;                                                                                                              \\\n      }                                                                                                                           \\\n      return false;                                                                                                               \\\n    }                                                                                                                             \\\n                                                                                                                                  \\\n    bool setCurrentRaw(void const* current)                                                                                       \\\n    {                                                                                                                             \\\n      this->mBinding = current;                                                                                                   \\\n      return true;                                                                                                                \\\n    }                                                                                                                             \\\n    binding_t const* getCurrent() const { return static_cast<binding_t const*>(mBinding); }                                       \\\n    void const* getCurrentRaw() const { return mBinding; }                                                                        \\\n    void const* mBinding = nullptr;                                                                                               \\\n  };                                                                                                                              \\\n  static const o2::framework::expressions::BindingNode _Getter_##Id { \"fIndex\" #_Table_ _Suffix_, typeid(_Name_##Id).hash_code(), \\\n                                                                      o2::framework::expressions::selectArrowType<_Type_>() }\n\n#define DECLARE_SOA_INDEX_COLUMN(_Name_, _Getter_) DECLARE_SOA_INDEX_COLUMN_FULL(_Name_, _Getter_, int32_t, _Name_##s, \"\")\n\n/// SELF\n#define DECLARE_SOA_SELF_INDEX_COLUMN_FULL(_Name_, _Getter_, _Type_, _Label_)                                           \\\n  struct _Name_##Id : o2::soa::Column<_Type_, _Name_##Id> {                                                             \\\n    static_assert(std::is_integral_v<_Type_>, \"Index type must be integral\");                                           \\\n    static constexpr const char* mLabel = \"fIndex\" _Label_;                                                             \\\n    using base = o2::soa::Column<_Type_, _Name_##Id>;                                                                   \\\n    using type = _Type_;                                                                                                \\\n    using column_t = _Name_##Id;                                                                                        \\\n    using self_index_t = std::true_type;                                                                                \\\n    _Name_##Id(arrow::ChunkedArray const* column)                                                                       \\\n      : o2::soa::Column<_Type_, _Name_##Id>(o2::soa::ColumnIterator<type>(column))                                      \\\n    {                                                                                                                   \\\n    }                                                                                                                   \\\n                                                                                                                        \\\n    _Name_##Id() = default;                                                                                             \\\n    _Name_##Id(_Name_##Id const& other) = default;                                                                      \\\n    _Name_##Id& operator=(_Name_##Id const& other) = default;                                                           \\\n    type inline getId() const                                                                                           \\\n    {                                                                                                                   \\\n      return _Getter_##Id();                                                                                            \\\n    }                                                                                                                   \\\n                                                                                                                        \\\n    type _Getter_##Id() const                                                                                           \\\n    {                                                                                                                   \\\n      return *mColumnIterator;                                                                                          \\\n    }                                                                                                                   \\\n                                                                                                                        \\\n    bool has_##_Getter_() const                                                                                         \\\n    {                                                                                                                   \\\n      return *mColumnIterator >= 0;                                                                                     \\\n    }                                                                                                                   \\\n                                                                                                                        \\\n    template <typename T>                                                                                               \\\n    auto _Getter_##_as() const                                                                                          \\\n    {                                                                                                                   \\\n      if (O2_BUILTIN_UNLIKELY(!has_##_Getter_())) {                                                                     \\\n        throw o2::framework::runtime_error_f(\"Accessing invalid index for %s\", #_Getter_);                              \\\n      }                                                                                                                 \\\n      return static_cast<T const*>(mBinding)->rawIteratorAt(*mColumnIterator);                                          \\\n    }                                                                                                                   \\\n                                                                                                                        \\\n    bool setCurrentRaw(void const* current)                                                                             \\\n    {                                                                                                                   \\\n      this->mBinding = current;                                                                                         \\\n      return true;                                                                                                      \\\n    }                                                                                                                   \\\n    void const* getCurrentRaw() const { return mBinding; }                                                              \\\n    void const* mBinding = nullptr;                                                                                     \\\n  };                                                                                                                    \\\n  static const o2::framework::expressions::BindingNode _Getter_##Id { \"fIndex\" _Label_, typeid(_Name_##Id).hash_code(), \\\n                                                                      o2::framework::expressions::selectArrowType<_Type_>() }\n\n#define DECLARE_SOA_SELF_INDEX_COLUMN(_Name_, _Getter_) DECLARE_SOA_SELF_INDEX_COLUMN_FULL(_Name_, _Getter_, int32_t, #_Name_)\n/// SELF SLICE\n#define DECLARE_SOA_SELF_SLICE_INDEX_COLUMN_FULL(_Name_, _Getter_, _Type_, _Label_)        \\\n  struct _Name_##IdSlice : o2::soa::Column<_Type_[2], _Name_##IdSlice> {                   \\\n    static_assert(std::is_integral_v<_Type_>, \"Index type must be integral\");              \\\n    static constexpr const char* mLabel = \"fIndexSlice\" _Label_;                           \\\n    using base = o2::soa::Column<_Type_[2], _Name_##IdSlice>;                              \\\n    using type = _Type_[2];                                                                \\\n    using column_t = _Name_##IdSlice;                                                      \\\n    using self_index_t = std::true_type;                                                   \\\n    _Name_##IdSlice(arrow::ChunkedArray const* column)                                     \\\n      : o2::soa::Column<_Type_[2], _Name_##IdSlice>(o2::soa::ColumnIterator<type>(column)) \\\n    {                                                                                      \\\n    }                                                                                      \\\n                                                                                           \\\n    _Name_##IdSlice() = default;                                                           \\\n    _Name_##IdSlice(_Name_##IdSlice const& other) = default;                               \\\n    _Name_##IdSlice& operator=(_Name_##IdSlice const& other) = default;                    \\\n    std::array<_Type_, 2> inline getIds() const                                            \\\n    {                                                                                      \\\n      return _Getter_##Ids();                                                              \\\n    }                                                                                      \\\n                                                                                           \\\n    bool has_##_Getter_() const                                                            \\\n    {                                                                                      \\\n      auto a = *mColumnIterator;                                                           \\\n      return a[0] >= 0 && a[1] >= 0;                                                       \\\n    }                                                                                      \\\n                                                                                           \\\n    std::array<_Type_, 2> _Getter_##Ids() const                                            \\\n    {                                                                                      \\\n      auto a = *mColumnIterator;                                                           \\\n      return std::array{a[0], a[1]};                                                       \\\n    }                                                                                      \\\n                                                                                           \\\n    template <typename T>                                                                  \\\n    auto _Getter_##_as() const                                                             \\\n    {                                                                                      \\\n      if (O2_BUILTIN_UNLIKELY(!has_##_Getter_())) {                                        \\\n        return static_cast<T const*>(mBinding)->emptySlice();                              \\\n      }                                                                                    \\\n      auto a = *mColumnIterator;                                                           \\\n      auto t = static_cast<T const*>(mBinding)->rawSlice(a[0], a[1]);                      \\\n      static_cast<T const*>(mBinding)->copyIndexBindings(t);                               \\\n      return t;                                                                            \\\n    }                                                                                      \\\n                                                                                           \\\n    bool setCurrentRaw(void const* current)                                                \\\n    {                                                                                      \\\n      this->mBinding = current;                                                            \\\n      return true;                                                                         \\\n    }                                                                                      \\\n    void const* getCurrentRaw() const { return mBinding; }                                 \\\n    void const* mBinding = nullptr;                                                        \\\n  };\n\n#define DECLARE_SOA_SELF_SLICE_INDEX_COLUMN(_Name_, _Getter_) DECLARE_SOA_SELF_SLICE_INDEX_COLUMN_FULL(_Name_, _Getter_, int32_t, \"_\" #_Name_)\n/// SELF ARRAY\n#define DECLARE_SOA_SELF_ARRAY_INDEX_COLUMN_FULL(_Name_, _Getter_, _Type_, _Label_)              \\\n  struct _Name_##Ids : o2::soa::Column<std::vector<_Type_>, _Name_##Ids> {                       \\\n    static_assert(std::is_integral_v<_Type_>, \"Index type must be integral\");                    \\\n    static constexpr const char* mLabel = \"fIndexArray\" _Label_;                                 \\\n    using base = o2::soa::Column<std::vector<_Type_>, _Name_##Ids>;                              \\\n    using type = std::vector<_Type_>;                                                            \\\n    using column_t = _Name_##Ids;                                                                \\\n    using self_index_t = std::true_type;                                                         \\\n    _Name_##Ids(arrow::ChunkedArray const* column)                                               \\\n      : o2::soa::Column<std::vector<_Type_>, _Name_##Ids>(o2::soa::ColumnIterator<type>(column)) \\\n    {                                                                                            \\\n    }                                                                                            \\\n                                                                                                 \\\n    _Name_##Ids() = default;                                                                     \\\n    _Name_##Ids(_Name_##Ids const& other) = default;                                             \\\n    _Name_##Ids& operator=(_Name_##Ids const& other) = default;                                  \\\n    gsl::span<const _Type_> inline getIds() const                                                \\\n    {                                                                                            \\\n      return _Getter_##Ids();                                                                    \\\n    }                                                                                            \\\n                                                                                                 \\\n    gsl::span<const _Type_> _Getter_##Ids() const                                                \\\n    {                                                                                            \\\n      return *mColumnIterator;                                                                   \\\n    }                                                                                            \\\n                                                                                                 \\\n    bool has_##_Getter_() const                                                                  \\\n    {                                                                                            \\\n      return !(*mColumnIterator).empty();                                                        \\\n    }                                                                                            \\\n                                                                                                 \\\n    template <typename T>                                                                        \\\n    auto _Getter_##_as() const                                                                   \\\n    {                                                                                            \\\n      return getIterators<T>();                                                                  \\\n    }                                                                                            \\\n                                                                                                 \\\n    template <typename T>                                                                        \\\n    auto getIterators() const                                                                    \\\n    {                                                                                            \\\n      auto result = std::vector<typename T::unfiltered_iterator>();                              \\\n      for (auto& i : *mColumnIterator) {                                                         \\\n        result.push_back(static_cast<T const*>(mBinding)->rawIteratorAt(i));                     \\\n      }                                                                                          \\\n      return result;                                                                             \\\n    }                                                                                            \\\n                                                                                                 \\\n    template <typename T>                                                                        \\\n    auto _Getter_##_first_as() const                                                             \\\n    {                                                                                            \\\n      return static_cast<T const*>(mBinding)->rawIteratorAt((*mColumnIterator)[0]);              \\\n    }                                                                                            \\\n                                                                                                 \\\n    template <typename T>                                                                        \\\n    auto _Getter_##_last_as() const                                                              \\\n    {                                                                                            \\\n      return static_cast<T const*>(mBinding)->rawIteratorAt((*mColumnIterator).back());          \\\n    }                                                                                            \\\n                                                                                                 \\\n    bool setCurrentRaw(void const* current)                                                      \\\n    {                                                                                            \\\n      this->mBinding = current;                                                                  \\\n      return true;                                                                               \\\n    }                                                                                            \\\n    void const* getCurrentRaw() const { return mBinding; }                                       \\\n    void const* mBinding = nullptr;                                                              \\\n  };\n\n#define DECLARE_SOA_SELF_ARRAY_INDEX_COLUMN(_Name_, _Getter_) DECLARE_SOA_SELF_ARRAY_INDEX_COLUMN_FULL(_Name_, _Getter_, int32_t, \"_\" #_Name_)\n\n/// A dynamic column is a column whose values are derived\n/// from those of other real columns. These can be used for\n/// example to provide different coordinate systems (e.g. polar,\n/// cylindrical) from a persister representation (e.g. cartesian).\n/// _Name_ is a unique typename which will be associated with the\n/// column. _Getter_ is a mnemonic to retrieve the value of\n/// the column in a given row. The variadic template argument\n/// (...) is used to capture a lambda or callable object which\n/// will be used to perform the transformation.\n/// Notice that the macro will define a template type _Name_\n/// which will have as template argument the types of the columns\n/// to be bound for the operation.\n///\n/// For example, let's assume you have:\n///\n/// \\code{.cpp}\n///\n/// namespace point {\n/// DECLARE_SOA_COLUMN(X, x, float, \"fX\");\n/// DECLARE_SOA_COLUMN(Y, y, float, \"fY\");\n/// }\n///\n/// DECLARE_SOA_DYNAMIC_COLUMN(R2, r2, [](x, y) { return x*x + y+y; });\n///\n/// DECLARE_SOA_TABLE(Point, \"MISC\", \"POINT\",\n///                   X, Y, (R2<X,Y>));\n/// \\endcode\n///\n#define DECLARE_SOA_DYNAMIC_COLUMN(_Name_, _Getter_, ...)                                                                  \\\n  struct _Name_##Callback {                                                                                                \\\n    static inline constexpr auto getLambda() { return __VA_ARGS__; }                                                       \\\n  };                                                                                                                       \\\n                                                                                                                           \\\n  struct _Name_##Helper {                                                                                                  \\\n    using callable_t = decltype(o2::framework::FunctionMetadata(std::declval<decltype(_Name_##Callback::getLambda())>())); \\\n    using return_type = typename callable_t::return_type;                                                                  \\\n  };                                                                                                                       \\\n  template <typename... Bindings>                                                                                          \\\n  struct _Name_ : o2::soa::DynamicColumn<typename _Name_##Helper::callable_t::type, _Name_<Bindings...>> {                 \\\n    using base = o2::soa::DynamicColumn<typename _Name_##Helper::callable_t::type, _Name_<Bindings...>>;                   \\\n    using helper = _Name_##Helper;                                                                                         \\\n    using callback_holder_t = _Name_##Callback;                                                                            \\\n    using callable_t = helper::callable_t;                                                                                 \\\n    using callback_t = callable_t::type;                                                                                   \\\n                                                                                                                           \\\n    _Name_(arrow::ChunkedArray const*)                                                                                     \\\n    {                                                                                                                      \\\n    }                                                                                                                      \\\n    _Name_() = default;                                                                                                    \\\n    _Name_(_Name_ const& other) = default;                                                                                 \\\n    _Name_& operator=(_Name_ const& other) = default;                                                                      \\\n    static constexpr const char* mLabel = #_Name_;                                                                         \\\n    using type = typename callable_t::return_type;                                                                         \\\n                                                                                                                           \\\n    template <typename... FreeArgs>                                                                                        \\\n    type _Getter_(FreeArgs... freeArgs) const                                                                              \\\n    {                                                                                                                      \\\n      return boundGetter(std::make_index_sequence<std::tuple_size_v<decltype(boundIterators)>>{}, freeArgs...);            \\\n    }                                                                                                                      \\\n                                                                                                                           \\\n    template <size_t... Is, typename... FreeArgs>                                                                          \\\n    type boundGetter(std::integer_sequence<size_t, Is...>&&, FreeArgs... freeArgs) const                                   \\\n    {                                                                                                                      \\\n      return __VA_ARGS__((**std::get<Is>(boundIterators))..., freeArgs...);                                                \\\n    }                                                                                                                      \\\n                                                                                                                           \\\n    using bindings_t = typename o2::framework::pack<Bindings...>;                                                          \\\n    std::tuple<o2::soa::ColumnIterator<typename Bindings::type> const*...> boundIterators;                                 \\\n  }\n\n#define DECLARE_SOA_TABLE_FULL(_Name_, _Label_, _Origin_, _Description_, ...) \\\n  using _Name_ = o2::soa::Table<__VA_ARGS__>;                                 \\\n                                                                              \\\n  struct _Name_##Metadata : o2::soa::TableMetadata<_Name_##Metadata> {        \\\n    using table_t = _Name_;                                                   \\\n    static constexpr char const* mLabel = _Label_;                            \\\n    static constexpr char const mOrigin[4] = _Origin_;                        \\\n    static constexpr char const mDescription[16] = _Description_;             \\\n  };                                                                          \\\n                                                                              \\\n  template <>                                                                 \\\n  struct MetadataTrait<_Name_> {                                              \\\n    using metadata = _Name_##Metadata;                                        \\\n  };                                                                          \\\n                                                                              \\\n  template <>                                                                 \\\n  struct MetadataTrait<_Name_::unfiltered_iterator> {                         \\\n    using metadata = _Name_##Metadata;                                        \\\n  };\n\n#define DECLARE_SOA_TABLE(_Name_, _Origin_, _Description_, ...) \\\n  DECLARE_SOA_TABLE_FULL(_Name_, #_Name_, _Origin_, _Description_, __VA_ARGS__);\n\n#define DECLARE_SOA_EXTENDED_TABLE_FULL(_Name_, _Table_, _Origin_, _Description_, ...)                                          \\\n  struct _Name_##Extension : o2::soa::Table<__VA_ARGS__> {                                                                      \\\n    using base_t = o2::soa::Table<__VA_ARGS__>;                                                                                 \\\n    _Name_##Extension(std::shared_ptr<arrow::Table> table, uint64_t offset = 0) : o2::soa::Table<__VA_ARGS__>(table, offset){}; \\\n    _Name_##Extension(_Name_##Extension const&) = default;                                                                      \\\n    _Name_##Extension(_Name_##Extension&&) = default;                                                                           \\\n    using expression_pack_t = framework::pack<__VA_ARGS__>;                                                                     \\\n    using iterator = typename base_t::template RowView<_Name_##Extension, _Name_##Extension>;                                   \\\n    using const_iterator = iterator;                                                                                            \\\n  };                                                                                                                            \\\n  using _Name_ = o2::soa::Join<_Name_##Extension, _Table_>;                                                                     \\\n                                                                                                                                \\\n  struct _Name_##ExtensionMetadata : o2::soa::TableMetadata<_Name_##ExtensionMetadata> {                                        \\\n    using table_t = _Name_##Extension;                                                                                          \\\n    using base_table_t = typename _Table_::table_t;                                                                             \\\n    using expression_pack_t = typename _Name_##Extension::expression_pack_t;                                                    \\\n    using originals = soa::originals_pack_t<_Table_>;                                                                           \\\n    using sources = originals;                                                                                                  \\\n    static constexpr char const* mLabel = #_Name_ \"Extension\";                                                                  \\\n    static constexpr char const mOrigin[4] = _Origin_;                                                                          \\\n    static constexpr char const mDescription[16] = _Description_;                                                               \\\n  };                                                                                                                            \\\n                                                                                                                                \\\n  template <>                                                                                                                   \\\n  struct MetadataTrait<_Name_##Extension> {                                                                                     \\\n    using metadata = _Name_##ExtensionMetadata;                                                                                 \\\n  };\n\n#define DECLARE_SOA_EXTENDED_TABLE(_Name_, _Table_, _Description_, ...) \\\n  DECLARE_SOA_EXTENDED_TABLE_FULL(_Name_, _Table_, \"DYN\", _Description_, __VA_ARGS__)\n\n#define DECLARE_SOA_EXTENDED_TABLE_USER(_Name_, _Table_, _Description_, ...) \\\n  DECLARE_SOA_EXTENDED_TABLE_FULL(_Name_, _Table_, \"AOD\", _Description_, __VA_ARGS__)\n\n#define DECLARE_SOA_INDEX_TABLE_FULL(_Name_, _Key_, _Origin_, _Description_, _Exclusive_, ...)                                   \\\n  struct _Name_ : o2::soa::IndexTable<_Key_, __VA_ARGS__> {                                                                      \\\n    _Name_(std::shared_ptr<arrow::Table> table, uint64_t offset = 0) : o2::soa::IndexTable<_Key_, __VA_ARGS__>(table, offset){}; \\\n    _Name_(_Name_ const&) = default;                                                                                             \\\n    _Name_(_Name_&&) = default;                                                                                                  \\\n    using iterator = typename base_t::template RowView<_Name_, _Name_>;                                                          \\\n    using const_iterator = iterator;                                                                                             \\\n  };                                                                                                                             \\\n                                                                                                                                 \\\n  struct _Name_##Metadata : o2::soa::TableMetadata<_Name_##Metadata> {                                                           \\\n    using Key = _Key_;                                                                                                           \\\n    using index_pack_t = framework::pack<__VA_ARGS__>;                                                                           \\\n    using originals = decltype(soa::extractBindings(index_pack_t{}));                                                            \\\n    using sources = typename _Name_::sources_t;                                                                                  \\\n    static constexpr char const* mLabel = #_Name_;                                                                               \\\n    static constexpr char const mOrigin[4] = _Origin_;                                                                           \\\n    static constexpr char const mDescription[16] = _Description_;                                                                \\\n    static constexpr bool exclusive = _Exclusive_;                                                                               \\\n  };                                                                                                                             \\\n                                                                                                                                 \\\n  template <>                                                                                                                    \\\n  struct MetadataTrait<_Name_> {                                                                                                 \\\n    using metadata = _Name_##Metadata;                                                                                           \\\n  };                                                                                                                             \\\n                                                                                                                                 \\\n  template <>                                                                                                                    \\\n  struct MetadataTrait<_Name_::iterator> {                                                                                       \\\n    using metadata = _Name_##Metadata;                                                                                           \\\n  };\n\n#define DECLARE_SOA_INDEX_TABLE(_Name_, _Key_, _Description_, ...) \\\n  DECLARE_SOA_INDEX_TABLE_FULL(_Name_, _Key_, \"IDX\", _Description_, false, __VA_ARGS__)\n\n#define DECLARE_SOA_INDEX_TABLE_EXCLUSIVE(_Name_, _Key_, _Description_, ...) \\\n  DECLARE_SOA_INDEX_TABLE_FULL(_Name_, _Key_, \"IDX\", _Description_, true, __VA_ARGS__)\n\n#define DECLARE_SOA_INDEX_TABLE_USER(_Name_, _Key_, _Description_, ...) \\\n  DECLARE_SOA_INDEX_TABLE_FULL(_Name_, _Key_, \"AOD\", _Description_, false, __VA_ARGS__)\n\n#define DECLARE_SOA_INDEX_TABLE_EXCLUSIVE_USER(_Name_, _Key_, _Description_, ...) \\\n  DECLARE_SOA_INDEX_TABLE_FULL(_Name_, _Key_, \"AOD\", _Description_, true, __VA_ARGS__)\n\nnamespace o2::soa\n{\ntemplate <typename... Ts>\nstruct Join : JoinBase<Ts...> {\n  Join(std::vector<std::shared_ptr<arrow::Table>>&& tables, uint64_t offset = 0);\n\n  template <typename... ATs>\n  Join(uint64_t offset, std::shared_ptr<arrow::Table> t1, std::shared_ptr<arrow::Table> t2, ATs... ts);\n\n  using base = JoinBase<Ts...>;\n  using originals = originals_pack_t<Ts...>;\n\n  template <typename... TA>\n  void bindExternalIndices(TA*... externals);\n\n  using table_t = base;\n  using persistent_columns_t = typename table_t::persistent_columns_t;\n  using iterator = typename table_t::template RowView<Join<Ts...>, Ts...>;\n  using const_iterator = iterator;\n  using filtered_iterator = typename table_t::template RowViewFiltered<Join<Ts...>, Ts...>;\n  using filtered_const_iterator = filtered_iterator;\n};\n\ntemplate <typename... Ts>\nJoin<Ts...>::Join(std::vector<std::shared_ptr<arrow::Table>>&& tables, uint64_t offset)\n  : JoinBase<Ts...>{ArrowHelpers::joinTables(std::move(tables)), offset}\n{\n}\n\ntemplate <typename... Ts>\ntemplate <typename... ATs>\nJoin<Ts...>::Join(uint64_t offset, std::shared_ptr<arrow::Table> t1, std::shared_ptr<arrow::Table> t2, ATs... ts)\n  : Join<Ts...>(std::vector<std::shared_ptr<arrow::Table>>{t1, t2, ts...}, offset)\n{\n}\n\ntemplate <typename... Ts>\ntemplate <typename... TA>\nvoid Join<Ts...>::bindExternalIndices(TA*... externals)\n{\n  base::bindExternalIndices(externals...);\n}\n\ntemplate <typename T1, typename T2>\nstruct Concat : ConcatBase<T1, T2> {\n  Concat(std::shared_ptr<arrow::Table> t1, std::shared_ptr<arrow::Table> t2, uint64_t offset = 0)\n    : ConcatBase<T1, T2>{ArrowHelpers::concatTables({t1, t2}), offset} {}\n  Concat(std::vector<std::shared_ptr<arrow::Table>> tables, uint64_t offset = 0)\n    : ConcatBase<T1, T2>{ArrowHelpers::concatTables(std::move(tables)), offset} {}\n\n  using base = ConcatBase<T1, T2>;\n  using originals = framework::concatenated_pack_t<originals_pack_t<T1>, originals_pack_t<T2>>;\n\n  template <typename... TA>\n  void bindExternalIndices(TA*... externals)\n  {\n    base::bindExternalIndices(externals...);\n  }\n\n  // FIXME: can be remove when we do the same treatment we did for Join to Concatenate\n  using left_t = T1;\n  using right_t = T2;\n  using table_t = ConcatBase<T1, T2>;\n  using persistent_columns_t = typename table_t::persistent_columns_t;\n\n  using iterator = typename table_t::template RowView<Concat<T1, T2>, T1, T2>;\n  using filtered_iterator = typename table_t::template RowViewFiltered<Concat<T1, T2>, T1, T2>;\n};\n\ntemplate <typename T>\nusing is_soa_join_t = framework::is_specialization<T, soa::Join>;\n\ntemplate <typename T>\nusing is_soa_concat_t = framework::is_specialization<T, soa::Concat>;\n\ntemplate <typename T>\ninline constexpr bool is_soa_join_v = is_soa_join_t<T>::value;\n\ntemplate <typename T>\ninline constexpr bool is_soa_concat_v = is_soa_concat_t<T>::value;\n\ntemplate <typename T>\nclass FilteredBase : public T\n{\n public:\n  using self_t = FilteredBase<T>;\n  using originals = originals_pack_t<T>;\n  using table_t = typename T::table_t;\n  using persistent_columns_t = typename T::persistent_columns_t;\n  using external_index_columns_t = typename T::external_index_columns_t;\n\n  template <typename P, typename... Os>\n  constexpr static auto make_it(framework::pack<Os...> const&)\n  {\n    return typename table_t::template RowViewFiltered<P, Os...>{};\n  }\n  using iterator = decltype(make_it<FilteredBase<T>>(originals{}));\n  using const_iterator = iterator;\n\n  FilteredBase(std::vector<std::shared_ptr<arrow::Table>>&& tables, gandiva::Selection const& selection, uint64_t offset = 0)\n    : T{std::move(tables), offset},\n      mSelectedRows{getSpan(selection)}\n  {\n    resetRanges();\n  }\n\n  FilteredBase(std::vector<std::shared_ptr<arrow::Table>>&& tables, SelectionVector&& selection, uint64_t offset = 0)\n    : T{std::move(tables), offset},\n      mSelectedRowsCache{std::move(selection)},\n      mCached{true}\n  {\n    resetRanges();\n  }\n\n  FilteredBase(std::vector<std::shared_ptr<arrow::Table>>&& tables, gsl::span<int64_t const> const& selection, uint64_t offset = 0)\n    : T{std::move(tables), offset},\n      mSelectedRows{selection}\n  {\n    resetRanges();\n  }\n\n  iterator begin()\n  {\n    return iterator(mFilteredBegin);\n  }\n\n  RowViewSentinel end()\n  {\n    return RowViewSentinel{*mFilteredEnd};\n  }\n\n  const_iterator begin() const\n  {\n    return const_iterator(mFilteredBegin);\n  }\n\n  RowViewSentinel end() const\n  {\n    return RowViewSentinel{*mFilteredEnd};\n  }\n\n  iterator iteratorAt(uint64_t i)\n  {\n    return mFilteredBegin + i;\n  }\n\n  int64_t size() const\n  {\n    return mSelectedRows.size();\n  }\n\n  int64_t tableSize() const\n  {\n    return table_t::asArrowTable()->num_rows();\n  }\n\n  auto const& getSelectedRows() const\n  {\n    return mSelectedRows;\n  }\n\n  static inline auto getSpan(gandiva::Selection const& sel)\n  {\n    if (sel == nullptr) {\n      return gsl::span<int64_t const>{};\n    }\n    auto array = std::static_pointer_cast<arrow::Int64Array>(sel->ToArray());\n    auto start = array->raw_values();\n    auto stop = start + array->length();\n    return gsl::span{start, stop};\n  }\n\n  /// Bind the columns which refer to other tables\n  /// to the associated tables.\n  template <typename... TA>\n  void bindExternalIndices(TA*... current)\n  {\n    table_t::bindExternalIndices(current...);\n    mFilteredBegin.bindExternalIndices(current...);\n  }\n\n  void bindExternalIndicesRaw(std::vector<void const*>&& ptrs)\n  {\n    mFilteredBegin.bindExternalIndicesRaw(std::forward<std::vector<void const*>>(ptrs));\n  }\n\n  template <typename T1, typename... Cs>\n  void doCopyIndexBindings(framework::pack<Cs...>, T1& dest) const\n  {\n    dest.bindExternalIndicesRaw(mFilteredBegin.getIndexBindings());\n  }\n\n  template <typename T1>\n  void copyIndexBindings(T1& dest) const\n  {\n    doCopyIndexBindings(external_index_columns_t{}, dest);\n  }\n\n  auto rawSliceBy(framework::expressions::BindingNode const& node, int value) const\n  {\n    return (table_t)this->sliceBy(node, value);\n  }\n\n  auto sliceByCached(framework::expressions::BindingNode const& node, int value)\n  {\n    uint64_t offset = 0;\n    std::shared_ptr<arrow::Table> result = nullptr;\n    auto status = ((table_t*)this)->getSliceFor(value, node.name.c_str(), result, offset);\n    if (status.ok()) {\n      auto start = offset;\n      auto end = start + result->num_rows();\n      auto start_iterator = std::lower_bound(mSelectedRows.begin(), mSelectedRows.end(), start);\n      auto stop_iterator = std::lower_bound(start_iterator, mSelectedRows.end(), end);\n      SelectionVector slicedSelection{start_iterator, stop_iterator};\n      std::transform(slicedSelection.begin(), slicedSelection.end(), slicedSelection.begin(),\n                     [&](int64_t idx) {\n                       return idx - static_cast<int64_t>(start);\n                     });\n      self_t fresult{{result}, std::move(slicedSelection), start};\n      copyIndexBindings(fresult);\n      return fresult;\n    }\n    o2::framework::throw_error(o2::framework::runtime_error(\"Failed to slice table\"));\n    O2_BUILTIN_UNREACHABLE();\n  }\n\n  auto sliceBy(framework::expressions::BindingNode const& node, int value) const\n  {\n    auto t = o2::soa::sliceBy((table_t)(*this), node, value);\n    auto start = t.offset();\n    auto end = start + t.size();\n    auto start_iterator = std::lower_bound(mSelectedRows.begin(), mSelectedRows.end(), start);\n    auto stop_iterator = std::lower_bound(start_iterator, mSelectedRows.end(), end);\n    SelectionVector slicedSelection{start_iterator, stop_iterator};\n    std::transform(slicedSelection.begin(), slicedSelection.end(), slicedSelection.begin(),\n                   [&](int64_t idx) {\n                     return idx - static_cast<int64_t>(start);\n                   });\n    self_t result{{t.asArrowTable()}, std::move(slicedSelection), start};\n    copyIndexBindings(result);\n    return result;\n  }\n\n  auto select(framework::expressions::Filter const& f) const\n  {\n    auto t = o2::soa::select(*this, f);\n    copyIndexBindings(t);\n    return t;\n  }\n\n protected:\n  auto slice(uint64_t start, uint64_t end)\n  {\n    auto start_iterator = std::lower_bound(mSelectedRows.begin(), mSelectedRows.end(), start);\n    auto stop_iterator = std::lower_bound(start_iterator, mSelectedRows.end(), end);\n    SelectionVector slicedSelection{start_iterator, stop_iterator};\n    std::transform(slicedSelection.begin(), slicedSelection.end(), slicedSelection.begin(),\n                   [&](int64_t idx) {\n                     return idx - static_cast<int64_t>(start);\n                   });\n    return self_t{{this->asArrowTable()->Slice(start, end - start + 1)}, std::move(slicedSelection), start};\n  }\n\n  void sumWithSelection(SelectionVector const& selection)\n  {\n    mCached = true;\n    SelectionVector rowsUnion;\n    std::set_union(mSelectedRows.begin(), mSelectedRows.end(), selection.begin(), selection.end(), std::back_inserter(rowsUnion));\n    mSelectedRowsCache.clear();\n    mSelectedRowsCache = rowsUnion;\n    resetRanges();\n  }\n\n  void intersectWithSelection(SelectionVector const& selection)\n  {\n    mCached = true;\n    SelectionVector intersection;\n    std::set_intersection(mSelectedRows.begin(), mSelectedRows.end(), selection.begin(), selection.end(), std::back_inserter(intersection));\n    mSelectedRowsCache.clear();\n    mSelectedRowsCache = intersection;\n    resetRanges();\n  }\n\n  void sumWithSelection(gsl::span<int64_t const> const& selection)\n  {\n    mCached = true;\n    SelectionVector rowsUnion;\n    std::set_union(mSelectedRows.begin(), mSelectedRows.end(), selection.begin(), selection.end(), std::back_inserter(rowsUnion));\n    mSelectedRowsCache.clear();\n    mSelectedRowsCache = rowsUnion;\n    resetRanges();\n  }\n\n  void intersectWithSelection(gsl::span<int64_t const> const& selection)\n  {\n    mCached = true;\n    SelectionVector intersection;\n    std::set_intersection(mSelectedRows.begin(), mSelectedRows.end(), selection.begin(), selection.end(), std::back_inserter(intersection));\n    mSelectedRowsCache.clear();\n    mSelectedRowsCache = intersection;\n    resetRanges();\n  }\n\n private:\n  void resetRanges()\n  {\n    if (mCached) {\n      mSelectedRows = gsl::span{mSelectedRowsCache};\n    }\n    mFilteredEnd.reset(new RowViewSentinel{mSelectedRows.size()});\n    if (tableSize() == 0) {\n      mFilteredBegin = *mFilteredEnd;\n    } else {\n      mFilteredBegin = table_t::filtered_begin(mSelectedRows);\n    }\n  }\n\n  gsl::span<int64_t const> mSelectedRows;\n  SelectionVector mSelectedRowsCache;\n  bool mCached = false;\n  iterator mFilteredBegin;\n  std::shared_ptr<RowViewSentinel> mFilteredEnd;\n};\n\ntemplate <typename T>\nclass Filtered : public FilteredBase<T>\n{\n public:\n  using self_t = Filtered<T>;\n  Filtered(std::vector<std::shared_ptr<arrow::Table>>&& tables, gandiva::Selection const& selection, uint64_t offset = 0)\n    : FilteredBase<T>(std::move(tables), selection, offset) {}\n\n  Filtered(std::vector<std::shared_ptr<arrow::Table>>&& tables, SelectionVector&& selection, uint64_t offset = 0)\n    : FilteredBase<T>(std::move(tables), std::forward<SelectionVector>(selection), offset) {}\n\n  Filtered(std::vector<std::shared_ptr<arrow::Table>>&& tables, gsl::span<int64_t const> const& selection, uint64_t offset = 0)\n    : FilteredBase<T>(std::move(tables), selection, offset) {}\n\n  Filtered<T> operator+(SelectionVector const& selection)\n  {\n    Filtered<T> copy(*this);\n    copy.sumWithSelection(selection);\n    return copy;\n  }\n\n  Filtered<T> operator+(gsl::span<int64_t const> const& selection)\n  {\n    Filtered<T> copy(*this);\n    copy.sumWithSelection(selection);\n    return copy;\n  }\n\n  Filtered<T> operator+(Filtered<T> const& other)\n  {\n    return operator+(other.getSelectedRows());\n  }\n\n  Filtered<T> operator+=(SelectionVector const& selection)\n  {\n    this->sumWithSelection(selection);\n    return *this;\n  }\n\n  Filtered<T> operator+=(gsl::span<int64_t const> const& selection)\n  {\n    this->sumWithSelection(selection);\n    return *this;\n  }\n\n  Filtered<T> operator+=(Filtered<T> const& other)\n  {\n    return operator+=(other.getSelectedRows());\n  }\n\n  Filtered<T> operator*(SelectionVector const& selection)\n  {\n    Filtered<T> copy(*this);\n    copy.intersectWithSelection(selection);\n    return copy;\n  }\n\n  Filtered<T> operator*(gsl::span<int64_t const> const& selection)\n  {\n    Filtered<T> copy(*this);\n    copy.intersectWithSelection(selection);\n    return copy;\n  }\n\n  Filtered<T> operator*(Filtered<T> const& other)\n  {\n    return operator*(other.getSelectedRows());\n  }\n\n  Filtered<T> operator*=(SelectionVector const& selection)\n  {\n    this->intersectWithSelection(selection);\n    return *this;\n  }\n\n  Filtered<T> operator*=(gsl::span<int64_t const> const& selection)\n  {\n    this->intersectWithSelection(selection);\n    return *this;\n  }\n\n  Filtered<T> operator*=(Filtered<T> const& other)\n  {\n    return operator*=(other.getSelectedRows());\n  }\n  using FilteredBase<T>::sliceByCached;\n};\n\ntemplate <typename T>\nclass Filtered<Filtered<T>> : public FilteredBase<typename T::table_t>\n{\n public:\n  using self_t = Filtered<Filtered<T>>;\n  using table_t = typename FilteredBase<typename T::table_t>::table_t;\n\n  Filtered(std::vector<Filtered<T>>&& tables, gandiva::Selection const& selection, uint64_t offset = 0)\n    : FilteredBase<typename T::table_t>(std::move(extractTablesFromFiltered(std::move(tables))), selection, offset)\n  {\n    for (auto& table : tables) {\n      *this *= table;\n    }\n  }\n\n  Filtered(std::vector<Filtered<T>>&& tables, SelectionVector&& selection, uint64_t offset = 0)\n    : FilteredBase<typename T::table_t>(std::move(extractTablesFromFiltered(std::move(tables))), std::forward<SelectionVector>(selection), offset)\n  {\n    for (auto& table : tables) {\n      *this *= table;\n    }\n  }\n\n  Filtered(std::vector<Filtered<T>>&& tables, gsl::span<int64_t const> const& selection, uint64_t offset = 0)\n    : FilteredBase<typename T::table_t>(std::move(extractTablesFromFiltered(std::move(tables))), selection, offset)\n  {\n    for (auto& table : tables) {\n      *this *= table;\n    }\n  }\n\n  Filtered<Filtered<T>> operator+(SelectionVector const& selection)\n  {\n    Filtered<Filtered<T>> copy(*this);\n    copy.sumWithSelection(selection);\n    return copy;\n  }\n\n  Filtered<Filtered<T>> operator+(gsl::span<int64_t const> const& selection)\n  {\n    Filtered<Filtered<T>> copy(*this);\n    copy.sumWithSelection(selection);\n    return copy;\n  }\n\n  Filtered<Filtered<T>> operator+(Filtered<T> const& other)\n  {\n    return operator+(other.getSelectedRows());\n  }\n\n  Filtered<Filtered<T>> operator+=(SelectionVector const& selection)\n  {\n    this->sumWithSelection(selection);\n    return *this;\n  }\n\n  Filtered<Filtered<T>> operator+=(gsl::span<int64_t const> const& selection)\n  {\n    this->sumWithSelection(selection);\n    return *this;\n  }\n\n  Filtered<Filtered<T>> operator+=(Filtered<T> const& other)\n  {\n    return operator+=(other.getSelectedRows());\n  }\n\n  Filtered<Filtered<T>> operator*(SelectionVector const& selection)\n  {\n    Filtered<Filtered<T>> copy(*this);\n    copy.intersectionWithSelection(selection);\n    return copy;\n  }\n\n  Filtered<Filtered<T>> operator*(gsl::span<int64_t const> const& selection)\n  {\n    Filtered<Filtered<T>> copy(*this);\n    copy.intersectionWithSelection(selection);\n    return copy;\n  }\n\n  Filtered<Filtered<T>> operator*(Filtered<T> const& other)\n  {\n    return operator*(other.getSelectedRows());\n  }\n\n  Filtered<Filtered<T>> operator*=(SelectionVector const& selection)\n  {\n    this->intersectWithSelection(selection);\n    return *this;\n  }\n\n  Filtered<Filtered<T>> operator*=(gsl::span<int64_t const> const& selection)\n  {\n    this->intersectWithSelection(selection);\n    return *this;\n  }\n\n  Filtered<Filtered<T>> operator*=(Filtered<T> const& other)\n  {\n    return operator*=(other.getSelectedRows());\n  }\n\n  using FilteredBase<typename T::table_t>::sliceByCached;\n\n private:\n  std::vector<std::shared_ptr<arrow::Table>> extractTablesFromFiltered(std::vector<Filtered<T>>&& tables)\n  {\n    std::vector<std::shared_ptr<arrow::Table>> outTables;\n    for (auto& table : tables) {\n      outTables.push_back(table.asArrowTable());\n    }\n    return outTables;\n  }\n};\n\ntemplate <typename T>\nusing is_soa_filtered_t = typename framework::is_base_of_template<soa::FilteredBase, T>;\n\n/// Template for building an index table to access matching rows from non-\n/// joinable, but compatible tables, e.g. Collisions and ZDCs.\n/// First argument is the key table (BCs for the Collisions+ZDCs case), the rest\n/// are index columns defined for the required tables.\n/// First index will be used by process() as the grouping\ntemplate <typename Key, typename H, typename... Ts>\nstruct IndexTable : Table<soa::Index<>, H, Ts...> {\n  using base_t = Table<soa::Index<>, H, Ts...>;\n  using table_t = base_t;\n  using safe_base_t = Table<H, Ts...>;\n  using indexing_t = Key;\n  using first_t = typename H::binding_t;\n  using rest_t = framework::pack<typename Ts::binding_t...>;\n  using sources_t = originals_pack_t<Key, first_t, typename Ts::binding_t...>;\n\n  IndexTable(std::shared_ptr<arrow::Table> table, uint64_t offset = 0)\n    : base_t{table, offset}\n  {\n  }\n\n  IndexTable(IndexTable const&) = default;\n  IndexTable(IndexTable&&) = default;\n  IndexTable& operator=(IndexTable const&) = default;\n  IndexTable& operator=(IndexTable&&) = default;\n\n  using iterator = typename base_t::template RowView<IndexTable<Key, H, Ts...>, IndexTable<Key, H, Ts...>>;\n  using const_iterator = iterator;\n};\n\ntemplate <typename T>\nusing is_soa_index_table_t = typename framework::is_base_of_template<soa::IndexTable, T>;\n\ntemplate <typename T>\nstruct SmallGroups : Filtered<T> {\n  SmallGroups(std::vector<std::shared_ptr<arrow::Table>>&& tables, gandiva::Selection const& selection, uint64_t offset = 0)\n    : Filtered<T>(std::move(tables), selection, offset) {}\n\n  SmallGroups(std::vector<std::shared_ptr<arrow::Table>>&& tables, SelectionVector&& selection, uint64_t offset = 0)\n    : Filtered<T>(std::move(tables), std::forward<SelectionVector>(selection), offset) {}\n\n  SmallGroups(std::vector<std::shared_ptr<arrow::Table>>&& tables, gsl::span<int64_t const> const& selection, uint64_t offset = 0)\n    : Filtered<T>(std::move(tables), selection, offset) {}\n};\n\n} // namespace o2::soa\n\n#endif // O2_FRAMEWORK_ASOA_H_\n", "meta": {"hexsha": "ea9fcb770618259d2c5fd002d04f1f33beffbd8f", "size": 129290, "ext": "h", "lang": "C", "max_stars_repo_path": "o2data_model/ASoA.h", "max_stars_repo_name": "adriansev/AO2Dproto", "max_stars_repo_head_hexsha": "bf4f9009c2e16560ecfda9e4907321163281b7de", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "o2data_model/ASoA.h", "max_issues_repo_name": "adriansev/AO2Dproto", "max_issues_repo_head_hexsha": "bf4f9009c2e16560ecfda9e4907321163281b7de", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "o2data_model/ASoA.h", "max_forks_repo_name": "adriansev/AO2Dproto", "max_forks_repo_head_hexsha": "bf4f9009c2e16560ecfda9e4907321163281b7de", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-23T15:15:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-23T15:15:53.000Z", "avg_line_length": 48.0274888559, "max_line_length": 179, "alphanum_fraction": 0.4467785598, "num_tokens": 23736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09138209811811353, "lm_q2_score": 0.015906390837114055, "lm_q1q2_score": 0.0014535593681822185}}
{"text": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n#pragma once\n\n#include \"arcana/errors.h\"\n#include \"arcana/expected.h\"\n#include \"arcana/functional/inplace_function.h\"\n#include \"arcana/iterators.h\"\n#include \"arcana/type_traits.h\"\n\n#include \"cancellation.h\"\n\n#include <gsl/gsl>\n#include <memory>\n#include <stdexcept>\n\n#include <atomic>\n\nnamespace mira\n{\n    template<typename ResultT>\n    class task_completion_source;\n\n    //\n    // A scheduler that will invoke the continuation inline\n    // right after the previous task.\n    //\n    namespace\n    {\n        struct inline_scheduler_t\n        {\n            template<typename CallableT>\n            constexpr void queue(CallableT&& callable) const\n            {\n                callable();\n            }\n        };\n\n        constexpr inline_scheduler_t inline_scheduler{};\n    }\n}\n\n#include \"internal/internal_task.h\"\n\nnamespace mira\n{\n    //\n    //  Generic task system to run work with continuations on a generic scheduler.\n    //\n    //  The scheduler on which tasks are queued must satisfy this contract:\n    //\n    //      struct scheduler\n    //      {\n    //          template<CallableT>\n    //          void queue(CallableT&& callable)\n    //          {\n    //              callable must be usable like this: callable();\n    //          }\n    //      };\n    //\n    template<typename ResultT>\n    class task\n    {\n        using payload_t = internal::base_task_payload_with_return<ResultT>;\n        using payload_ptr = std::shared_ptr<payload_t>;\n\n        static_assert(std::is_same<typename as_expected<ResultT>::result, ResultT>::value,\n            \"task can't be of expected<T>\");\n\n    public:\n        using result_t = ResultT;\n\n        task() = default;\n\n        task(const task& other) = default;\n        task(task&& other) = default;\n\n        task(const task_completion_source<ResultT>& source)\n            : m_payload{ source.m_payload }\n        {}\n\n        task(task_completion_source<ResultT>&& source)\n            : m_payload{ std::move(source.m_payload) }\n        {}\n\n        task& operator=(task&& other) = default;\n        task& operator=(const task& other) = default;\n\n        bool operator==(const task& other)\n        {\n            return m_payload == other.m_payload;\n        }\n\n        //\n        // Executes a callable on this scheduler once this task is finished and\n        // returns a task that represents the callable.\n        //\n        // Calling .then() on the returned task will queue a task to run after the\n        // callable is run.\n        //\n        template<typename SchedulerT, typename CallableT>\n        auto then(SchedulerT& scheduler, cancellation& token, CallableT&& callable)\n        {\n            return internal::continuation_factory<ResultT>::create_continuation_task(\n                internal::input_output_wrapper<ResultT>::wrap_callable(std::forward<CallableT>(callable), token),\n                scheduler,\n                m_payload);\n        }\n\n    private:\n        explicit task(payload_ptr payload)\n            : m_payload{ std::move(payload) }\n        {}\n\n        template<typename CallableT, typename InputT>\n        explicit task(CallableT&& callable, type_of<InputT> input)\n        {\n            auto payload = std::make_shared<internal::task_payload<ResultT, sizeof(CallableT)>>(\n                std::forward<CallableT>(callable), input);\n\n            m_payload = std::move(payload);\n        }\n\n        template<typename OtherResultT, size_t WorkSize>\n        friend struct internal::task_payload;\n\n        template<typename OtherResultT>\n        friend class task;\n\n        friend class task_completion_source<ResultT>;\n\n        template<typename OtherResultT, typename InputT>\n        friend struct internal::task_factory;\n\n        template<typename OtherResultT>\n        friend struct internal::continuation_factory;\n\n        template<typename SchedulerT, typename CallableT>\n        friend auto make_task(SchedulerT& scheduler, cancellation& token, CallableT&& callable) -> typename internal::task_factory<typename as_expected<decltype(callable())>::result, void>::task_t;\n\n        template<typename OtherResultT>\n        friend task<typename as_expected<OtherResultT>::result> task_from_result(OtherResultT&& value);\n\n        friend task<void> task_from_result();\n\n        template<typename OtherResultT, typename ErrorT>\n        friend task<OtherResultT> task_from_error(const ErrorT& error);\n\n        payload_ptr m_payload;\n    };\n}\n\nnamespace mira\n{\n    template<typename ResultT>\n    class task_completion_source\n    {\n        using payload_t = internal::noop_task_payload<ResultT>;\n        using payload_ptr = std::shared_ptr<payload_t>;\n        using uninitialized = std::integral_constant<int, 0>;\n\n    public:\n        using result_t = ResultT;\n\n        task_completion_source()\n            : m_payload{ std::make_shared<payload_t>() }\n        {}\n\n        static task_completion_source<ResultT> make_uninitialized()\n        {\n            return task_completion_source<ResultT>{ uninitialized{} };\n        }\n\n        //\n        // Completes the task this source represents.\n        //\n        void complete()\n        {\n            static_assert(std::is_same<ResultT, void>::value,\n                \"complete with no arguments can only be used with a void completion source\");\n            m_payload->complete(expected<void>::make_valid());\n        }\n\n        //\n        // Completes the task this source represents.\n        //\n        template<typename ValueT>\n        void complete(ValueT&& value)\n        {\n            m_payload->complete(std::forward<ValueT>(value));\n        }\n\n        //\n        // Returns whether or not the current source has already been completed.\n        //\n        bool completed() const\n        {\n            return m_payload->completed();\n        }\n\n        //\n        // Converts this task_completion_source to a task object for consumers to use.\n        //\n        task<ResultT> as_task() const &\n        {\n            return task<ResultT>{ m_payload };\n        }\n\n        task<ResultT> as_task() &&\n        {\n            return task<ResultT>{ std::move(m_payload) };\n        }\n\n    private:\n        explicit task_completion_source(uninitialized)\n        {}\n\n        explicit task_completion_source(std::shared_ptr<payload_t> payload)\n            : m_payload{ std::move(payload) }\n        {}\n\n        friend class task<ResultT>;\n        friend class abstract_task_completion_source;\n\n        template<typename R, typename I>\n        friend struct internal::task_factory;\n\n        payload_ptr m_payload;\n    };\n\n    //\n    // a type erased version of task_completion_source.\n    //\n    class abstract_task_completion_source\n    {\n        using payload_t = internal::base_task_payload;\n        using payload_ptr = std::shared_ptr<payload_t>;\n\n    public:\n        abstract_task_completion_source()\n            : m_payload{}\n        {}\n\n        template<typename T>\n        explicit abstract_task_completion_source(const task_completion_source<T>& other)\n            : m_payload{ other.m_payload }\n        {}\n\n        template<typename T>\n        explicit abstract_task_completion_source(task_completion_source<T>&& other)\n            : m_payload{ std::move(other.m_payload) }\n        {}\n\n        //\n        // Returns whether or not the current source has already been completed.\n        //\n        bool completed() const\n        {\n            return m_payload->completed();\n        }\n\n        template<typename T>\n        bool operator==(const task_completion_source<T>& other)\n        {\n            return m_payload == other.m_payload;\n        }\n\n        template<typename T>\n        task_completion_source<T> unsafe_cast()\n        {\n            return task_completion_source<T>{ std::static_pointer_cast<internal::noop_task_payload<T>>(m_payload) };\n        }\n\n    private:\n        payload_ptr m_payload;\n    };\n\n    //\n    // creates a task and queues it to run on the given scheduler\n    //\n    template<typename SchedulerT, typename CallableT>\n    inline auto make_task(SchedulerT& scheduler, cancellation& token, CallableT&& callable) -> typename internal::task_factory<typename as_expected<decltype(callable())>::result, void>::task_t\n    {\n        using callable_return_t = typename as_expected<decltype(callable())>::result;\n        using wrapper = internal::input_output_wrapper<void>;\n\n        internal::task_factory<callable_return_t, void> factory(\n            wrapper::wrap_callable(std::forward<CallableT>(callable), token));\n\n        scheduler.queue([to_run = std::move(factory.to_run)]{ to_run.m_payload->run(nullptr); });\n\n        return factory.to_return;\n    }\n\n    //\n    // creates a completed task from the given result\n    //\n    template<typename ResultT>\n    inline task<typename as_expected<ResultT>::result> task_from_result(ResultT&& value)\n    {\n        task_completion_source<typename as_expected<ResultT>::result> result;\n        result.complete(std::forward<ResultT>(value));\n        return std::move(result);\n    }\n\n    inline task<void> task_from_result()\n    {\n        task_completion_source<void> result;\n        result.complete();\n        return std::move(result);\n    }\n\n    template<typename ResultT, typename ErrorT>\n    inline task<ResultT> task_from_error(const ErrorT& error)\n    {\n        task_completion_source<ResultT> result;\n        result.complete(std::make_error_code(error));\n        return std::move(result);\n    }\n\n    template<typename ResultT>\n    inline task<ResultT> task_from_error(const std::error_code& error)\n    {\n        task_completion_source<ResultT> result;\n        result.complete(error);\n        return std::move(result);\n    }\n\n    inline task<void> when_all(gsl::span<task<void>> tasks)\n    {\n        if (tasks.empty())\n        {\n            return task_from_result();\n        }\n\n        struct when_all_data\n        {\n            std::mutex mutex;\n            size_t pendingCount;\n            std::error_code error;\n        };\n\n        task_completion_source<void> result;\n        auto data = std::make_shared<when_all_data>();\n        data->pendingCount = tasks.size();\n\n        for (task<void>& task : tasks)\n        {\n            task.then(inline_scheduler, cancellation::none(), [data, result](const expected<void>& exp) mutable {\n                bool last = false;\n                {\n                    std::lock_guard<std::mutex> guard{ data->mutex };\n\n                    data->pendingCount -= 1;\n                    last = data->pendingCount == 0;\n\n                    if (exp.has_error() && !data->error)\n                    {\n                        // set the first error, as it might have cascaded\n                        data->error = exp.error();\n                    }\n                }\n\n                if (last) // we were the last task to complete\n                {\n                    if (data->error)\n                    {\n                        result.complete(data->error);\n                    }\n                    else\n                    {\n                        result.complete();\n                    }\n                }\n            });\n        }\n\n        return std::move(result);\n    }\n\n    template<typename T>\n    inline task<std::vector<T>> when_all(gsl::span<task<T>> tasks)\n    {\n        if (tasks.empty())\n        {\n            return task_from_result<std::vector<T>>(std::vector<T>());\n        }\n\n        struct when_all_data\n        {\n            std::mutex mutex;\n            size_t pendingCount;\n            std::error_code error;\n            std::vector<T> results;\n        };\n\n        task_completion_source<std::vector<T>> result;\n        auto data = std::make_shared<when_all_data>();\n        data->pendingCount = tasks.size();\n        data->results.resize(tasks.size());\n\n        //using forloop with index to be able to keep proper order of results\n        for (auto idx = 0U; idx < data->results.size(); idx++)\n        {\n            tasks[idx].then(mira::inline_scheduler, cancellation::none(), [data, result, idx](const expected<T>& exp) mutable {\n                bool last = false;\n                {\n                    std::lock_guard<std::mutex> guard{ data->mutex };\n\n                    data->pendingCount -= 1;\n                    last = data->pendingCount == 0;\n\n                    if (exp.has_error() && !data->error)\n                    {\n                        // set the first error, as it might have cascaded\n                        data->error = exp.error();\n                    }\n                    if (exp.has_value())\n                    {\n                        data->results[idx] = exp.value();\n                    }\n                }\n\n                if (last) // we were the last task to complete\n                {\n                    if (data->error)\n                    {\n                        result.complete(data->error);\n                    }\n                    else\n                    {\n                        result.complete(data->results);\n                    }\n                }\n            });\n        }\n\n        return std::move(result);\n    }\n\n    template<typename... ArgTs>\n    inline task<std::tuple<typename mira::void_passthrough<ArgTs>::type...>> when_all(task<ArgTs>... tasks)\n    {\n        using void_passthrough_tuple = std::tuple<typename mira::void_passthrough<ArgTs>::type...>;\n\n        struct when_all_data\n        {\n            std::mutex mutex;\n            int pending;\n            std::error_code error;\n            void_passthrough_tuple results;\n        };\n  \n        task_completion_source<void_passthrough_tuple> result;\n\n        auto data = std::make_shared<when_all_data>();\n        data->pending = std::tuple_size<void_passthrough_tuple>::value;\n\n        std::tuple<task<ArgTs>&...> taskrefs = std::make_tuple(std::ref(tasks)...);\n\n        iterate_tuple(taskrefs, [&](auto& task, auto idx) {\n            using task_t = std::remove_reference_t<decltype(task)>;\n\n            task.then(inline_scheduler,\n                cancellation::none(),\n                [data, result](const expected<typename task_t::result_t>& exp) mutable {\n                bool last = false;\n                {\n                    std::lock_guard<std::mutex> guard{ data->mutex };\n\n                    data->pending -= 1;\n                    last = data->pending == 0;\n\n                    internal::write_expected_to_tuple<decltype(idx)::value>(data->results, exp);\n                    \n                    if (exp.has_error() && !data->error)\n                    {\n                        // set the first error, as it might have cascaded\n                        data->error = exp.error();\n                    }\n                }\n\n                if (last) // we were the last task to complete\n                {\n                    if (data->error)\n                    {\n                        result.complete(data->error);\n                    }\n                    else\n                    {\n                        result.complete(std::move(data->results));\n                    }\n                }\n            });\n        });\n        return std::move(result);\n    }\n}\n", "meta": {"hexsha": "a6de9fc9d4158a281c4b92c24bfc2f428b75418a", "size": 15102, "ext": "h", "lang": "C", "max_stars_repo_path": "Dependencies/Arcana/Shared/arcana/threading/task.h", "max_stars_repo_name": "syntheticmagus/mageslam", "max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z", "max_issues_repo_path": "Dependencies/Arcana/Shared/arcana/threading/task.h", "max_issues_repo_name": "syntheticmagus/mageslam", "max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z", "max_forks_repo_path": "Dependencies/Arcana/Shared/arcana/threading/task.h", "max_forks_repo_name": "syntheticmagus/mageslam", "max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z", "avg_line_length": 30.204, "max_line_length": 197, "alphanum_fraction": 0.5541650113, "num_tokens": 2972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.0913820956435847, "lm_q2_score": 0.015906390049883503, "lm_q1q2_score": 0.0014535592568826181}}
{"text": "#pragma once\n\n#include <Windows.h>\n\n#include <cstdint>\n#include <string>\n#include <vector>\n\n#include <gsl/span>\n#include \"hid_handle.h\"\n\nnamespace hid\n{\n\tstruct HidOpenFlags\n\t{\n\t\tenum T : uint32_t\n\t\t{\n\t\t\tnone,\n\t\t\texclusive = 1u << 0u,\n\t\t\tasync     = 1u << 1u\n\t\t};\n\t};\n\n\tusing HidOpenFlags_t = uint32_t;\n\n\tstruct HidCaps\n\t{\n\t\tuint16_t usage;\n\t\tuint16_t usagePage;\n\t\tuint16_t inputReportSize;\n\t\tuint16_t outputReportSize;\n\t\tuint16_t featureReportSize;\n\t\tuint16_t linkCollectionNodes;\n\t\tuint16_t inputButtonCaps;\n\t\tuint16_t inputValueCaps;\n\t\tuint16_t inputDataIndices;\n\t\tuint16_t outputButtonCaps;\n\t\tuint16_t outputValueCaps;\n\t\tuint16_t outputDataIndices;\n\t\tuint16_t featureButtonCaps;\n\t\tuint16_t featureValueCaps;\n\t\tuint16_t featureDataIndices;\n\t};\n\n\tstruct HidAttributes\n\t{\n\t\tuint16_t vendorId;\n\t\tuint16_t productId;\n\t\tuint16_t versionNumber;\n\t};\n\n\tclass HidInstance\n\t{\n\t\tHidOpenFlags_t flags = 0;\n\n\t\tHandle handle = Handle(nullptr, true);\n\n\t\tHidCaps caps_ {};\n\t\tHidAttributes attributes_ {};\n\n\t\tOVERLAPPED overlappedIn = {};\n\t\tOVERLAPPED overlappedOut = {};\n\n\t\tbool pendingRead_ = false;\n\t\tbool pendingWrite_ = false;\n\n\t\tsize_t nativeError_ = 0;\n\n\tpublic:\n\t\tstd::wstring path;\n\t\tstd::wstring instanceId;\n\t\tstd::wstring serialString;\n\n\t\tstd::vector<uint8_t> inputBuffer;\n\t\tstd::vector<uint8_t> outputBuffer;\n\n\t\tHidInstance(const HidInstance&) = delete;\n\t\tHidInstance& operator=(const HidInstance&) = delete;\n\n\t\tHidInstance() = default;\n\n\t\tHidInstance(std::wstring path, std::wstring instanceId);\n\t\texplicit HidInstance(std::wstring path);\n\t\tHidInstance(HidInstance&& other) noexcept;\n\n\t\t~HidInstance();\n\n\t\tHidInstance& operator=(HidInstance&& other) noexcept;\n\n\t\tbool isOpen() const;\n\t\tbool isExclusive() const;\n\t\tbool isAsync() const;\n\t\tconst HidCaps& caps() const;\n\t\tconst HidAttributes& attributes() const;\n\n\t\tbool readMetadata();\n\t\tbool readCaps();\n\t\tbool readSerial();\n\t\tbool readAttributes();\n\t\tbool getFeature(const gsl::span<uint8_t>& buffer) const;\n\t\tbool setFeature(const gsl::span<uint8_t>& buffer) const;\n\n\t\tbool open(HidOpenFlags_t openFlags);\n\t\tvoid close();\n\n\t\tinline auto nativeError() const\n\t\t{\n\t\t\treturn nativeError_;\n\t\t}\n\n\t\tbool read(void* buffer, size_t size) const;\n\t\tbool read(const gsl::span<uint8_t>& buffer) const;\n\t\tbool read();\n\n\t\tbool readAsync();\n\n\t\tbool write(const void* buffer, size_t size) const;\n\t\tbool write(const gsl::span<const uint8_t>& buffer) const;\n\t\tbool write() const;\n\n\t\tbool writeAsync();\n\n\t\tbool asyncReadPending() const;\n\t\tbool asyncReadInProgress();\n\t\tbool asyncWritePending() const;\n\t\tbool asyncWriteInProgress();\n\n\t\tvoid cancelAsyncReadAndWait();\n\t\tvoid cancelAsyncWriteAndWait();\n\n\t\tbool setOutputReport(const gsl::span<uint8_t>& buffer) const;\n\t\tbool setOutputReport();\n\n\tprivate:\n\t\tvoid cancelAsyncAndWait(OVERLAPPED* overlapped);\n\t\tbool asyncInProgress(OVERLAPPED* overlapped);\n\n\t\tbool readCaps(HANDLE h);\n\t\tbool readSerial(HANDLE h);\n\t\tbool readAttributes(HANDLE h);\n\t};\n}\n", "meta": {"hexsha": "6cca2bbab12f9f6acdac625b72d7f6a67b1386d3", "size": 2927, "ext": "h", "lang": "C", "max_stars_repo_path": "libhid/hid_instance.h", "max_stars_repo_name": "SonicFreak94/ds4wizard", "max_stars_repo_head_hexsha": "4d2ddc15b7db7cc5618c8676c91cf81614921c3c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T19:23:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-13T08:35:31.000Z", "max_issues_repo_path": "libhid/hid_instance.h", "max_issues_repo_name": "SonicFreak94/ds4wizard", "max_issues_repo_head_hexsha": "4d2ddc15b7db7cc5618c8676c91cf81614921c3c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-01-29T20:34:26.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-30T04:00:38.000Z", "max_forks_repo_path": "libhid/hid_instance.h", "max_forks_repo_name": "SonicFreak94/ds4wizard", "max_forks_repo_head_hexsha": "4d2ddc15b7db7cc5618c8676c91cf81614921c3c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.4685314685, "max_line_length": 63, "alphanum_fraction": 0.724291083, "num_tokens": 801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07369626563712976, "lm_q2_score": 0.019719126703133704, "lm_q1q2_score": 0.0014532259996463603}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef framesys_300a49a6_c103_4a1f_8166_358e823a432b_h\r\n#define framesys_300a49a6_c103_4a1f_8166_358e823a432b_h\r\n\r\n#include <gslib/type.h>\r\n#include <ariel/sysop.h>\r\n#include <ariel/config.h>\r\n#include <ariel/rendersys.h>\r\n\r\n__ariel_begin__\r\n\r\nenum frame_strategy\r\n{\r\n    fs_busy_loop,\r\n    fs_lazy_passive,\r\n};\r\n\r\nstruct app_config;\r\nstruct app_env;\r\nclass framesys;\r\nstruct frame_event;\r\nclass frame_listener;\r\nclass rose;\r\n\r\nenum frame_event_id\r\n{\r\n    feid_invalid,\r\n    feid_draw,\r\n    feid_timer,\r\n    feid_paint,\r\n    feid_mouse_down,\r\n    feid_mouse_up,\r\n    feid_mouse_move,\r\n    feid_key_down,\r\n    feid_key_up,\r\n    feid_char,\r\n    feid_show,\r\n    feid_create,\r\n    feid_close,\r\n    feid_resize,\r\n    feid_halt,\r\n    feid_resume,\r\n    feid_custom,\r\n};\r\n\r\nstruct __gs_novtable frame_event abstract\r\n{\r\n    virtual uint get_id() const = 0;\r\n    virtual uint get_event_size() const = 0;\r\n};\r\n\r\nstruct frame_draw_event:\r\n    public frame_event\r\n{\r\npublic:\r\n    virtual uint get_id() const override { return feid_draw; }\r\n    virtual uint get_event_size() const override { return sizeof(*this); }\r\n};\r\n\r\nstruct frame_close_event:\r\n    public frame_event\r\n{\r\npublic:\r\n    virtual uint get_id() const override { return feid_close; }\r\n    virtual uint get_event_size() const override { return sizeof(*this); }\r\n};\r\n\r\nstruct frame_halt_event:\r\n    public frame_event\r\n{\r\npublic:\r\n    virtual uint get_id() const override { return feid_halt; }\r\n    virtual uint get_event_size() const override { return sizeof(*this); }\r\n};\r\n\r\nstruct frame_resume_event:\r\n    public frame_event\r\n{\r\npublic:\r\n    virtual uint get_id() const override { return feid_resume; }\r\n    virtual uint get_event_size() const override { return sizeof(*this); }\r\n};\r\n\r\nstruct frame_paint_event:\r\n    public frame_event\r\n{\r\n    rect            boundary;\r\n\r\npublic:\r\n    virtual uint get_id() const override { return feid_paint; }\r\n    virtual uint get_event_size() const override { return sizeof(*this); }\r\n};\r\n\r\nstruct frame_timer_event:\r\n    public frame_event\r\n{\r\n    uint            timerid;\r\n\r\npublic:\r\n    virtual uint get_id() const override { return feid_timer; }\r\n    virtual uint get_event_size() const override { return sizeof(*this); }\r\n};\r\n\r\nstruct frame_show_event:\r\n    public frame_event\r\n{\r\n    bool            show;\r\n\r\npublic:\r\n    virtual uint get_id() const override { return feid_show; }\r\n    virtual uint get_event_size() const override { return sizeof(*this); }\r\n};\r\n\r\nstruct frame_resize_event:\r\n    public frame_event\r\n{\r\n    rect            boundary;\r\n\r\npublic:\r\n    virtual uint get_id() const override { return feid_resize; }\r\n    virtual uint get_event_size() const override { return sizeof(*this); }\r\n};\r\n\r\nstruct frame_mouse_down_event:\r\n    public frame_event\r\n{\r\n    uint            modifier;\r\n    unikey          key;\r\n    point           position;\r\n\r\npublic:\r\n    virtual uint get_id() const override { return feid_mouse_down; }\r\n    virtual uint get_event_size() const override { return sizeof(*this); }\r\n};\r\n\r\nstruct frame_mouse_up_event:\r\n    public frame_event\r\n{\r\n    uint            modifier;\r\n    unikey          key;\r\n    point           position;\r\n\r\npublic:\r\n    virtual uint get_id() const override { return feid_mouse_up; }\r\n    virtual uint get_event_size() const override { return sizeof(*this); }\r\n};\r\n\r\nstruct frame_mouse_move_event:\r\n    public frame_event\r\n{\r\n    uint            modifier;\r\n    point           position;\r\n\r\npublic:\r\n    virtual uint get_id() const override { return feid_mouse_move; }\r\n    virtual uint get_event_size() const override { return sizeof(*this); }\r\n};\r\n\r\nstruct frame_key_down_event:\r\n    public frame_event\r\n{\r\n    uint            modifier;\r\n    unikey          key;\r\n\r\npublic:\r\n    virtual uint get_id() const override { return feid_key_down; }\r\n    virtual uint get_event_size() const override { return sizeof(*this); }\r\n};\r\n\r\nstruct frame_key_up_event:\r\n    public frame_event\r\n{\r\n    uint            modifier;\r\n    unikey          key;\r\n\r\npublic:\r\n    virtual uint get_id() const override { return feid_key_up; }\r\n    virtual uint get_event_size() const override { return sizeof(*this); }\r\n};\r\n\r\nstruct frame_char_event:\r\n    public frame_event\r\n{\r\n    uint            modifier;\r\n    uint            charactor;\r\n\r\npublic:\r\n    virtual uint get_id() const override { return feid_char; }\r\n    virtual uint get_event_size() const override { return sizeof(*this); }\r\n};\r\n\r\nstruct frame_create_event:\r\n    public frame_event\r\n{\r\n    system_driver*  driver;\r\n    rect            boundary;\r\n\r\npublic:\r\n    virtual uint get_id() const override { return feid_create; }\r\n    virtual uint get_event_size() const override { return sizeof(*this); }\r\n};\r\n\r\ntemplate<frame_event_id _feid>\r\nstruct frame_event_table;\r\n\r\n#define register_frame_event(feid, fevt) \\\r\n    template<> \\\r\n    struct frame_event_table<feid> { \\\r\n        typedef fevt type; \\\r\n    };\r\nregister_frame_event(feid_draw, frame_draw_event);\r\nregister_frame_event(feid_timer, frame_timer_event);\r\nregister_frame_event(feid_paint, frame_paint_event);\r\nregister_frame_event(feid_mouse_down, frame_mouse_down_event);\r\nregister_frame_event(feid_mouse_up, frame_mouse_up_event);\r\nregister_frame_event(feid_mouse_move, frame_mouse_move_event);\r\nregister_frame_event(feid_key_down, frame_key_down_event);\r\nregister_frame_event(feid_key_up, frame_key_up_event);\r\nregister_frame_event(feid_char, frame_char_event);\r\nregister_frame_event(feid_show, frame_show_event);\r\nregister_frame_event(feid_create, frame_create_event);\r\nregister_frame_event(feid_close, frame_close_event);\r\nregister_frame_event(feid_resize, frame_resize_event);\r\nregister_frame_event(feid_halt, frame_halt_event);\r\nregister_frame_event(feid_resume, frame_resume_event);\r\n#undef register_frame_event\r\n\r\nclass __gs_novtable frame_listener abstract\r\n{\r\npublic:\r\n    virtual ~frame_listener() {}\r\n    virtual void on_frame_start() = 0;\r\n    virtual void on_frame_end() = 0;\r\n    virtual bool on_frame_event(const frame_event& event) = 0;\r\n};\r\n\r\nclass frame_dispatcher:\r\n    public system_notify\r\n{\r\npublic:\r\n    virtual void on_show(bool b) override;\r\n    virtual void on_create(system_driver* ptr, const rect& rc) override;\r\n    virtual void on_close() override;\r\n    virtual void on_resize(const rect& rc) override;\r\n    virtual void on_paint(const rect& rc) override;\r\n    virtual void on_halt() override;\r\n    virtual void on_resume() override;\r\n    virtual bool on_mouse_down(uint um, unikey uk, const point& pt) override;\r\n    virtual bool on_mouse_up(uint um, unikey uk, const point& pt) override;\r\n    virtual bool on_mouse_move(uint um, const point& pt) override;\r\n    virtual bool on_key_down(uint um, unikey uk) override;\r\n    virtual bool on_key_up(uint um, unikey uk) override;\r\n    virtual bool on_char(uint um, uint ch) override;\r\n    virtual void on_timer(uint tid) override;\r\n\r\nprotected:\r\n    frame_listener*     _listener;\r\n\r\npublic:\r\n    frame_dispatcher() { _listener = 0; }\r\n    void set_listener(frame_listener* listenter) { _listener = listenter; }\r\n    void do_draw();\r\n    void on_frame_start();\r\n    void on_frame_end();\r\n};\r\n\r\nstruct frame_configs\r\n{\r\n    uint                handles;\r\n    int                 width;\r\n    int                 height;\r\n    /* more to come.. */\r\n};\r\n\r\nclass framesys:\r\n    public system_driver\r\n{\r\npublic:\r\n    friend class frame_dispatcher;\r\n    typedef void (framesys::*fn_empty_frame)();\r\n\r\npublic:\r\n    void set_frame_strategy(frame_strategy stt);\r\n    void set_notify(system_notify* notify) { _notify = notify; }\r\n    void set_frame_listener(frame_listener* lis) { _dispatcher.set_listener(lis); }\r\n    system_notify* get_notify() const { return _notify; }\r\n    rendersys* get_rendersys() const { return _rendersys; }\r\n    rose* get_rose() const { return _rose; }\r\n    const frame_configs& get_configs() const { return _configs; }\r\n    void initialize(const rect& rc);\r\n    void refresh();\r\n\r\npublic:\r\n    virtual ~framesys();\r\n    virtual void initialize(const system_context& ctx) override;\r\n    virtual void setup() override;\r\n    virtual void close() override;\r\n    virtual void set_timer(uint tid, int t) override;\r\n    virtual void kill_timer(uint tid) override;\r\n    virtual void update() override;\r\n    virtual void emit(int msgid, void* msg, int size) override;\r\n    virtual void set_ime(point pt, const font& ft) override;\r\n    virtual void set_cursor(cursor_type curty) override;\r\n\r\nprivate:\r\n    framesys();\r\n\r\npublic:\r\n    static int run();\r\n    static framesys* get_framesys()\r\n    {\r\n        static framesys inst;\r\n        return &inst;\r\n    }\r\n\r\n#if defined(WIN32) || defined(_WINDOWS)\r\n    static void set_default_config(app_config& cfg);\r\n    static void on_app_initialized(const app_env& env);\r\n    static void on_app_windowed(HWND);\r\n#endif\r\n\r\nprotected:\r\n    void idle()\r\n    {\r\n        assert(_empty_frame_proc);\r\n        (this->*_empty_frame_proc)();\r\n    }\r\n    void empty_frame_lazy();\r\n    void empty_frame_busy();\r\n\r\nprotected:\r\n    frame_strategy      _strategy;\r\n    frame_configs       _configs;\r\n    frame_dispatcher    _dispatcher;\r\n    system_notify*      _notify;\r\n    rendersys*          _rendersys;\r\n    rose*               _rose;\r\n    fn_empty_frame      _empty_frame_proc;\r\n};\r\n\r\n__ariel_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "2d32eade1bd0343fa2d91d59571d97ecef622cae", "size": 10540, "ext": "h", "lang": "C", "max_stars_repo_path": "include/ariel/framesys.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/ariel/framesys.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ariel/framesys.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 28.4864864865, "max_line_length": 84, "alphanum_fraction": 0.6859582543, "num_tokens": 2351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.05834584716123092, "lm_q2_score": 0.02479816033071988, "lm_q1q2_score": 0.0014468696725358817}}
{"text": "#ifndef VKST_PLAT_FS_NOTIFY_LINUX_H\n#define VKST_PLAT_FS_NOTIFY_LINUX_H\n\n#ifndef VKST_PLAT_FS_NOTIFY_H\n#error \"Include fs_notify.h only\"\n#endif\n\n#include \"fs_notify.h\"\n#include <gsl.h>\n#include <vector>\n\nnamespace plat {\n\nclass fs_notify final : public impl::fs_notify<fs_notify> {\npublic:\n\nprivate:\n  //std::vector<gsl::unique_ptr<watch>> _watches;\n\n  watch_id do_add(plat::filesystem::path path,\n                  impl::fs_notify<fs_notify>::notify_delegate delegate,\n                  bool recursive, std::error_code& ec) noexcept;\n\n  void do_remove(watch_id id) noexcept;\n\n  void do_tick() noexcept;\n\n  friend class impl::fs_notify<fs_notify>;\n}; // class fs_notify\n\n} // namespace plat\n\n#endif // VKST_PLAT_FS_NOTIFY_LINUX_H\n\n", "meta": {"hexsha": "306d95f8a7104ae4e77fc02d8b1d4ee58ebccc53", "size": 731, "ext": "h", "lang": "C", "max_stars_repo_path": "src/plat/fs_notify_linux.h", "max_stars_repo_name": "wesleygriffin/vkst", "max_stars_repo_head_hexsha": "5f1210ef8aeecdd2bbc3904b0cc4dd09892f239c", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/plat/fs_notify_linux.h", "max_issues_repo_name": "wesleygriffin/vkst", "max_issues_repo_head_hexsha": "5f1210ef8aeecdd2bbc3904b0cc4dd09892f239c", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/plat/fs_notify_linux.h", "max_forks_repo_name": "wesleygriffin/vkst", "max_forks_repo_head_hexsha": "5f1210ef8aeecdd2bbc3904b0cc4dd09892f239c", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.8857142857, "max_line_length": 71, "alphanum_fraction": 0.7277701778, "num_tokens": 184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.06097518427776045, "lm_q2_score": 0.023689472074810463, "lm_q1q2_score": 0.0014444699252044281}}
{"text": "#ifndef VKST_RENDERER_H\n#define VKST_RENDERER_H\n\n#include <plat/filesystem.h>\n#include <wsi/window.h>\n#include <vk/result.h>\n#include <gsl.h>\n#include <filesystem>\n#include <vector>\n\n// Holds all of the data for a surface. This includes the swapchain,\n// renderpass, and framebuffers.\n// Surfaces must be resized when the window is resized.\nclass surface {\npublic:\n  std::size_t num_images() const noexcept { return _color_images.size(); }\n\n  VkRenderPass render_pass() const noexcept { return _render_pass; }\n\n  VkFramebuffer framebuffer(std::size_t index) const noexcept {\n    return _framebuffers[index];\n  }\n\n  VkSampleCountFlagBits samples() const noexcept { return _samples; }\n\n  VkViewport& viewport() noexcept { return _viewport; }\n  VkViewport const& viewport() const noexcept { return _viewport; }\n\n  VkRect2D& scissor() noexcept { return _scissor; }\n  VkRect2D const& scissor() const noexcept { return _scissor; }\n\n  surface() noexcept {}\n  surface(surface const&) = delete;\n  surface(surface&& other) noexcept;\n  surface& operator=(surface const&) = delete;\n  surface& operator=(surface&& rhs) noexcept;\n  ~surface() noexcept = default;\n\nprivate:\n  VkSurfaceKHR _surface{VK_NULL_HANDLE};\n\n  VkSurfaceFormatKHR _color_format{};\n  VkFormat _depth_format{};\n  VkSampleCountFlagBits _samples{};\n  VkPresentModeKHR _present_mode{};\n\n  VkSemaphore _image_available{VK_NULL_HANDLE};\n  VkSemaphore _render_finished{VK_NULL_HANDLE};\n  VkRenderPass _render_pass{VK_NULL_HANDLE};\n\n  VkSurfaceCapabilitiesKHR _capabilities{};\n  VkExtent2D _extent{};\n  VkViewport _viewport{};\n  VkRect2D _scissor{};\n  VkSwapchainKHR _swapchain{VK_NULL_HANDLE};\n\n  constexpr static uint32_t MAX_IMAGES = 4;\n  std::vector<VkImage> _color_images{};\n  std::vector<VkImageView> _color_image_views{};\n\n  VkImage _depth_image{VK_NULL_HANDLE};\n  VkDeviceMemory _depth_image_memory{VK_NULL_HANDLE};\n  VkImageView _depth_image_view{VK_NULL_HANDLE};\n\n  VkImage _color_target{VK_NULL_HANDLE};\n  VkDeviceMemory _color_target_memory{VK_NULL_HANDLE};\n  VkImageView _color_target_view{VK_NULL_HANDLE};\n\n  VkImage _depth_target{VK_NULL_HANDLE};\n  VkDeviceMemory _depth_target_memory{VK_NULL_HANDLE};\n  VkImageView _depth_target_view{VK_NULL_HANDLE};\n\n  std::vector<VkFramebuffer> _framebuffers{};\n\n  friend class renderer;\n}; // class surface\n\n// Convenience class to hold both the VkShaderModule for a shader as well as\n// any error message from compiling the shader.\nclass shader {\npublic:\n  enum class types : uint8_t {\n    vertex = 0,\n    fragment = 1,\n  }; // enum class types\n\n  operator VkShaderModule() const noexcept { return _module; }\n\n  std::string const& error_message() const noexcept { return _error_message; }\n\n  shader() noexcept {}\n  shader(shader const&) = delete;\n  shader(shader&& other) noexcept;\n  shader& operator=(shader const&) = delete;\n  shader& operator=(shader&& rhs) noexcept;\n  ~shader() noexcept = default;\n\nprivate:\n  VkShaderModule _module{VK_NULL_HANDLE};\n  std::string _error_message{};\n\n  friend class renderer;\n}; // class shader\n\nenum class renderer_result {\n  success = 0,\n  no_device = 1,\n  initialization_failed = 2,\n  surface_not_supported = 3,\n  no_memory_type = 4,\n}; // class renderer_result\n\nclass renderer_result_category_impl : public std::error_category {\npublic:\n  virtual char const* name() const noexcept override {\n    return \"renderer_result\";\n  }\n\n  virtual std::string message(int ev) const override;\n}; // class renderer_result_category_impl\n\nstd::error_category const& renderer_result_category();\n\ninline std::error_code make_error_code(renderer_result e) noexcept {\n  return {static_cast<int>(e), renderer_result_category()};\n}\n\nenum class renderer_options : uint8_t {\n  none = 0,\n  use_integrated_gpu = (1 << 1),\n}; // renderer_options\n\n// Holds all of the data for rendering. Also provides methods for creating\n// surfaces, shaders, pipelines, and command buffers, as well as submitting\n// command buffers for execution on the device.\nclass renderer {\npublic:\n  // Create a new renderer. If ec is true, then an error occurred during\n  // creation and the renderer object is in an invalid state.\n  static renderer create(gsl::czstring application_name, renderer_options opts,\n                         PFN_vkDebugReportCallbackEXT debug_report_callback,\n                         uint32_t push_constant_size,\n                         std::error_code& ec) noexcept;\n\n  // Create a new surface. If ec is true, then an error occurred during\n  // creation and the surface object is in an invalid state.\n  surface create_surface(wsi::window const& window,\n                         std::error_code& ec) noexcept;\n\n  // Resize a surface. Must be called when the window that was passed for\n  // surface creation is resized. This is not automatically done to allow\n  // the render loop to determine when to perform the resize. If ec is true,\n  // then an error occurred during the resize.\n  void resize(surface& s, wsi::extent2d const& extent,\n              std::error_code& ec) noexcept;\n\n  // Acquire the next ready image in the swapchain for rendering to. This\n  // must be called and the returned index passed to submit_present. If\n  // ec is true, then an error occurred and the returned index is invalid.\n  uint32_t acquire_next_image(surface& s, std::error_code& ec) noexcept;\n\n  // Submit a set of command buffers for execution and then present the\n  // previously acquired swapchain image. image_index must come from an\n  // immediately preceding call to acquire_next_image. fence can be\n  // VK_NULL_HANDLE which indicates no fence should be signaled when the\n  // command buffers can be reused. If ec is true, then an error occurred\n  // during either the submit or present.\n  void submit_present(gsl::span<VkCommandBuffer> buffers, surface& s,\n                      uint32_t image_index, VkFence fence,\n                      std::error_code& ec) noexcept;\n\n  void destroy(surface& s) noexcept;\n\nprivate:\n  void release(surface& s) noexcept;\n\npublic:\n  // Allocate a set of command buffers. If ec is true, then an error occurred\n  // and the vector is invalid.\n  std::vector<VkCommandBuffer>\n  allocate_command_buffers(uint32_t count, std::error_code& ec) noexcept;\n\n  // Submit a set of command buffers. onetime indicates that the submit should\n  // use the onetime fence and wait for the submit to complete before\n  // continuing. If ec is true, then an error occurred.\n  void submit(gsl::span<VkCommandBuffer> command_buffers, bool onetime,\n              std::error_code& ec) noexcept;\n\n  void free(std::vector<VkCommandBuffer>& command_buffers) noexcept;\n\n  // Create a new shader from the given source code. path is expected to hold\n  // GLSL source code which will be compiled before creating the shader. If ec\n  // is true, then an error occurred and the shader is valid such that\n  // shader::error_message can be called to get any compilation errors.\n  shader create_shader(plat::filesystem::path const& path, shader::types type,\n                       std::error_code& ec) noexcept;\n\n  void destroy(shader& s) noexcept;\n\n  // Create a new pipeline layout. If ec is true, then an error occurred and\n  // the pipeline layout object is invalid.\n  VkPipelineLayout create_pipeline_layout(\n    gsl::span<VkDescriptorSetLayout> descriptor_set_layouts,\n    gsl::span<VkPushConstantRange> push_constant_ranges,\n    std::error_code& ec) noexcept;\n\n  void destroy(VkPipelineLayout layout) noexcept;\n\n  // Create a new set of pipelines. A single pipeline can also be created.\n  // If ec is true, then an error occurred and the vector of pipelines is\n  // invalid.\n  std::vector<VkPipeline>\n  create_pipelines(gsl::span<VkGraphicsPipelineCreateInfo> cinfos,\n                   std::error_code& ec) noexcept;\n\n  void destroy(gsl::span<VkPipeline> pipes) noexcept;\n\n  // Create a new fence. If ec is true, then an error occurred and the fence\n  // is invalid.\n  VkFence create_fence(bool signaled, std::error_code& ec) noexcept;\n\n  // Wait for a set of fences to be signaled. If wait_all is true, then all\n  // fences must be signaled before the call will return, if wait_all is\n  // false, then a single fence will cause the call to return. timeout\n  // specifies how long to wait, 0 returns immediately, and UINT64_MAX will\n  // wait indefinitely. If ec is true, and error occurred while waiting.\n  void wait(gsl::span<VkFence> fences, bool wait_all, uint64_t timeout,\n            std::error_code& ec) noexcept;\n\n  // Reset a set of fences from the signaled state to unsignaled. If ec is\n  // true then an error occured.\n  void reset(gsl::span<VkFence> fences, std::error_code& ec) noexcept;\n\n  void destroy(VkFence fence) noexcept;\n\n  constexpr renderer() noexcept {};\n  renderer(renderer const&) = delete;\n  renderer(renderer&& other) noexcept;\n  renderer& operator=(renderer const&) = delete;\n  renderer& operator=(renderer&& rhs) noexcept;\n  ~renderer() noexcept;\n\nprivate:\n  VkInstance _instance{VK_NULL_HANDLE};\n  VkDebugReportCallbackEXT _callback{VK_NULL_HANDLE};\n\n  VkPhysicalDevice _physical{VK_NULL_HANDLE};\n  VkDevice _device{VK_NULL_HANDLE};\n\n  uint32_t _graphics_queue_family_index{UINT32_MAX};\n  VkQueue _graphics_queue{VK_NULL_HANDLE};\n  VkCommandPool _graphics_command_pool{VK_NULL_HANDLE};\n  VkFence _graphics_onetime_fence{VK_NULL_HANDLE};\n}; // class renderer\n\ninline constexpr auto operator|(renderer_options a,\n                                renderer_options b) noexcept {\n  using U = std::underlying_type_t<renderer_options>;\n  return static_cast<renderer_options>(static_cast<U>(a) | static_cast<U>(b));\n}\n\ninline constexpr auto operator&(renderer_options a,\n                                renderer_options b) noexcept {\n  using U = std::underlying_type_t<renderer_options>;\n  return static_cast<renderer_options>(static_cast<U>(a) & static_cast<U>(b));\n}\n\n#endif // VKST_RENDERER_H\n", "meta": {"hexsha": "621b47c89059a0b2021aa751fefba4b409f1cf49", "size": 9835, "ext": "h", "lang": "C", "max_stars_repo_path": "src/renderer.h", "max_stars_repo_name": "wesleygriffin/vkst", "max_stars_repo_head_hexsha": "5f1210ef8aeecdd2bbc3904b0cc4dd09892f239c", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/renderer.h", "max_issues_repo_name": "wesleygriffin/vkst", "max_issues_repo_head_hexsha": "5f1210ef8aeecdd2bbc3904b0cc4dd09892f239c", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/renderer.h", "max_forks_repo_name": "wesleygriffin/vkst", "max_forks_repo_head_hexsha": "5f1210ef8aeecdd2bbc3904b0cc4dd09892f239c", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.56133829, "max_line_length": 79, "alphanum_fraction": 0.7359430605, "num_tokens": 2314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07055959423282868, "lm_q2_score": 0.020332354492818717, "lm_q1q2_score": 0.0014346426828113197}}
{"text": "#pragma once\n#include <memory>\n#include \"halley/resources/resource.h\"\n#include \"halley/utils/utils.h\"\n#include <gsl/gsl>\n#include \"halley/core/resources/resource_collection.h\"\n\nnamespace Halley\n{\n\tclass ResourceLoader;\n\n\tclass BinaryFile : public Resource\n\t{\n\tpublic:\n\t\tBinaryFile();\n\t\texplicit BinaryFile(const Bytes& data);\n        explicit BinaryFile(Bytes&& data);\n\t\texplicit BinaryFile(gsl::span<const gsl::byte> data);\n\t\texplicit BinaryFile(std::unique_ptr<ResourceDataStream> stream);\n\n\t\tstatic std::unique_ptr<BinaryFile> loadResource(ResourceLoader& loader);\n\t\tconstexpr static AssetType getAssetType() { return AssetType::BinaryFile; }\n\t\tvoid reload(Resource&& resource) override;\n\n\t\tconst Bytes& getBytes() const;\n\t\tBytes& getBytes();\n\t\tgsl::span<const gsl::byte> getSpan() const;\n\t\tgsl::span<gsl::byte> getSpan();\n\n\t\tstd::shared_ptr<ResourceDataStream> getStream() const;\n\n\tprivate:\n\t\tBytes data;\n\t\tstd::shared_ptr<ResourceDataStream> stream;\n\t\tbool streaming = false;\n\t};\n}\n", "meta": {"hexsha": "536f826289d907b69808b7caaf2e35230bc737d4", "size": 987, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engine/utils/include/halley/file_formats/binary_file.h", "max_stars_repo_name": "sunhay/halley", "max_stars_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T20:23:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T20:23:45.000Z", "max_issues_repo_path": "src/engine/utils/include/halley/file_formats/binary_file.h", "max_issues_repo_name": "sunhay/halley", "max_issues_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engine/utils/include/halley/file_formats/binary_file.h", "max_forks_repo_name": "sunhay/halley", "max_forks_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9736842105, "max_line_length": 77, "alphanum_fraction": 0.7406281662, "num_tokens": 237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08035746882220708, "lm_q2_score": 0.017712301684889544, "lm_q1q2_score": 0.0014233157304130374}}
{"text": "#ifndef TTT_GFX_BUTTON_H\n#define TTT_GFX_BUTTON_H\n\n#include <SDL_render.h>\n#include <SDL_mouse.h>\n#include <SDL_mixer.h>\n\n#include <gsl/pointers>\n\n#include <optional>\n\nnamespace ttt::gfx\n{\n\t// A basic clickable image button.\n\tclass Button final\n\t{\n\tpublic:\n\t\tButton() = default;\n\t\tButton(SDL_Texture *texture, const SDL_Rect &normalSrc, const SDL_FRect &dst, Mix_Chunk *sound) noexcept;\n\t\tButton(SDL_Texture *texture, const SDL_Rect &normalSrc, const std::optional<SDL_Rect> &hoverSrc, const std::optional<SDL_Rect> &pressedSrc, const SDL_FRect &dst, Mix_Chunk *sound) noexcept;\n\n\t\tvoid setTexture(SDL_Texture *texture, const SDL_Rect &normalSrc) noexcept;\n\t\tvoid setTexture(SDL_Texture *texture, const SDL_Rect &normalSrc, const std::optional<SDL_Rect> &hoverSrc, const std::optional<SDL_Rect> &pressedSrc) noexcept;\n\t\tvoid setDestination(const SDL_FRect &dst) noexcept;\n\t\tvoid setSound(Mix_Chunk *sound) noexcept;\n\n\t\tvoid update() noexcept;\n\t\tvoid render(gsl::not_null<SDL_Renderer *> renderer) const noexcept;\n\n\t\t[[nodiscard]] bool isHoveredOver() const noexcept;\n\t\t[[nodiscard]] bool isPressed() const noexcept;\n\t\t[[nodiscard]] bool wasReleased() const noexcept;\n\n\tprivate:\n\t\tSDL_Texture *texture{nullptr};\n\t\t\n\t\tSDL_Rect normalSrc{0, 0, 0, 0};\n\t\tstd::optional<SDL_Rect> hoverSrc;\n\t\tstd::optional<SDL_Rect> pressedSrc;\n\t\t\n\t\tSDL_FRect dst{0.0f, 0.0f, 0.0f, 0.0f};\n\t\tMix_Chunk *sound{nullptr};\n\n\t\tbool hoveredOver{false};\n\t\tbool pressed{false};\n\t\tbool released{false};\n\t\tstd::optional<SDL_Point> click;\n\t};\n\n\tinline void Button::setSound(Mix_Chunk *sound) noexcept { this->sound = sound; }\n\n\tinline bool Button::isHoveredOver() const noexcept { return hoveredOver; }\n\tinline bool Button::isPressed() const noexcept { return pressed; }\n\tinline bool Button::wasReleased() const noexcept { return released; }\n}\n\n#endif", "meta": {"hexsha": "7b90609e81782947047108c94119e10de7c6abe4", "size": 1816, "ext": "h", "lang": "C", "max_stars_repo_path": "Source/Graphics/Button.h", "max_stars_repo_name": "itsArtem/TicTacToe", "max_stars_repo_head_hexsha": "8c70a77e4603dd0ff22ec0621b978ec0685ec3cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Source/Graphics/Button.h", "max_issues_repo_name": "itsArtem/TicTacToe", "max_issues_repo_head_hexsha": "8c70a77e4603dd0ff22ec0621b978ec0685ec3cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/Graphics/Button.h", "max_forks_repo_name": "itsArtem/TicTacToe", "max_forks_repo_head_hexsha": "8c70a77e4603dd0ff22ec0621b978ec0685ec3cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8596491228, "max_line_length": 191, "alphanum_fraction": 0.7444933921, "num_tokens": 495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.061875985723642724, "lm_q2_score": 0.022977372084420553, "lm_q1q2_score": 0.001421747547062433}}
{"text": "\n#pragma once\n\n#include <string>\n#include <vector>\n#include <set>\n#include <map>\n\n#include <gsl/gsl>\n\n#include <gamesystems/map/sector.h>\n\n#include \"streams.h\"\n#include \"animgoals/anim.h\"\n\nstruct QuestSave {\n\tGameTime acceptedTime;\n\tuint32_t acceptedArea;\n\tuint32_t state;\n};\n\nstruct ObjRefSave {\n\tObjectId id;\n\tuint32_t mapId;\n\tlocXY location;\n};\n\nstruct AnimGoalSave {\n\tAnimGoalType type;\n\tObjRefSave selfObj;\n\tObjRefSave targetObj;\n\tObjRefSave blockObj;\n\tObjRefSave scratchObj;\n\tObjRefSave parentObj;\n\tlocXY targetLoc;\n\tlocXY range;\n\tint animId;\n\tint animIdPrev;\n\tint animData;\n\tint animData2;\n\tint spellData;\n\tint skillData;\n\tint flagsData;\n\tint scratchVal1;\n\tint scratchVal2;\n\tint scratchVal3;\n\tint scratchVal4;\n\tint scratchVal5;\n\tint scratchVal6;\n\tint soundHandle;\n};\n\nstruct AnimSlotSave {\n\tAnimSlotId id;\n\tuint32_t flags;\n\tint currentState;\n\tuint32_t field14;\n\tuint64_t field18;\n\tObjRefSave animObj;\n\tstd::vector<AnimGoalSave> goals;\n\tstd::array<uint8_t, 0xF8> unk;\n\tuint64_t pathInfo;\n\tGameTime someTime;\n\tuint32_t field2c90;\n};\n\nstruct SpellObjSave {\n\tObjectId id;\n\tuint32_t casterPartSysName;\n};\n\nstruct SpellSave {\n\tuint32_t spellId;\n\tuint32_t spellIdx;\n\tuint32_t active;\n\n\tuint32_t spellEnum;\n\tuint32_t spellEnumOrg;\n\tuint32_t flagsSth;\n\tObjectId caster;\n\tuint32_t casterPartSysName; // 0 if none\n\tuint32_t spellClass;\n\tuint32_t spellLevel;\n\tuint32_t baseCasterLevel;\n\tuint32_t spellDc;\n\tuint32_t spellObjCount; // Guess\n\tobjHndl unknownObj;\n\tstd::array<SpellObjSave, 128> spellObjs; // Not really sure if this is spell objs\n\tsize_t targetListNumItemsCopy;\n\tsize_t targetListNumItems;\n\tstd::array<SpellObjSave, 32> targets;\n\tuint32_t numProjectiles;\n\tstd::array<ObjectId, 5> projectiles;\n\tLocFull aoeCenter;\n\tuint32_t duration;\n\tuint32_t durationRemaining;\n\tuint32_t spellRange;\n\tuint32_t savingThrowResult;\n\tuint32_t metaMagic;\n\tuint32_t spellId2;\n};\n\nstruct TimeEventArgSave {\n\tint32_t intVal = 0;\n\tfloat floatVal = 0;\n\tObjRefSave objectRefVal;\n\tlocXY locVal = {0, 0};\n\tstd::string pythonObj;\n};\n\nstruct TimeEventSave {\n\tGameTime expiresAt;\n\tTimeEventType type;\n\tstd::vector<TimeEventArgSave> args;\n};\n\nclass SaveGameArchive {\npublic:\n\tstatic void Create(const std::string &folder,\n\t\tconst std::string &filename);\n\n\tstatic void Unpack(const std::string &filename, \n\t\tconst std::string &folder);\n\nprivate:\n\tstatic void AddFolder(const std::string &folder,\n\t\tOutputStream &indexStream,\n\t\tOutputStream &dataStream);\n\n\tstatic void UnpackFolder(const std::string &folder,\n\t\tInputStream &indexStream,\n\t\tInputStream &dataStream);\n\n\tstatic void UnpackFile(const std::string &folder,\n\t\tInputStream &indexStream,\n\t\tInputStream &dataStream);\n};\n\nclass SaveGame {\npublic:\n\n\tvoid Load(const std::string &path);\n\nprivate:\n\n\tvoid LoadDataSav(InputStream &in);\n\n\tstd::vector<std::string> mCustomDescriptions;\n\tbool mIronman = false;\n\tuint32_t mIronmanSaveNumber = 0;\n\tstd::string mIronmanSaveName;\n\tstd::vector<SectorTime> mSectorTimes;\n\tstd::vector<uint8_t> mGlobalVars;\n\tstd::vector<uint8_t> mGlobalFlags;\n\tuint32_t mStoryState = 0;\n\tstd::vector<int32_t> mEncounterQueue;\n\n\tstd::string mMapDataPath;\n\tstd::string mMapSavePath;\n\tstd::set<uint32_t> mVisitedMaps;\n\n\tuint32_t mNextSpellId = 0;\n\tstd::vector<SpellSave> mSpells;\n\n\tuint32_t mLightSchemeId = 0;\n\tuint32_t mLightSchemeHourOfDay = 0;\n\tstd::set<uint32_t> mKnownAreas;\n\tstd::vector<uint32_t> mSoundSchemeIds; // At most 2\n\tbool mSoundGameOverSound = false;\n\tstd::vector<uint32_t> mSoundGameOverStash; // 2 scheme ids\n\tbool mSoundGameInCombat = false;\n\tstd::vector<uint32_t> mSoundGameCombatStash; // 2 scheme ids\n\tstd::vector<QuestSave> mQuests;\n\n\tbool mInCombat = false;\n\n\tGameTime mRealTime;\n\tGameTime mGameTime;\n\tGameTime mAnimTime;\n\tstd::vector<TimeEventSave> mTimeEvents;\n\n\tuint32_t mNextAnimId = 0;\n\tuint32_t mActiveGoalCount = 0;\n\tbool mAnimCatchup = false;\n\tuint32_t mAnimActionId = 0;\n\tstd::vector<uint32_t> mUnkAnimVals;\n\tstd::map<size_t, AnimSlotSave> mAnimSlots;\n\n\tstatic AnimSlotSave ReadAnimSlot(InputStream &in);\n\tstatic ObjRefSave ReadObjRef(InputStream &in);\n\n\tstatic void ReadSystemFooter(InputStream &in, const char *system);\n};\n", "meta": {"hexsha": "c2ba229d4a88fed1dbf60009c50992c28bef6de9", "size": 4104, "ext": "h", "lang": "C", "max_stars_repo_path": "TemplePlus/util/savegame.h", "max_stars_repo_name": "edoipi/TemplePlus", "max_stars_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 69.0, "max_stars_repo_stars_event_min_datetime": "2015-05-05T14:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T06:13:04.000Z", "max_issues_repo_path": "TemplePlus/util/savegame.h", "max_issues_repo_name": "edoipi/TemplePlus", "max_issues_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 457.0, "max_issues_repo_issues_event_min_datetime": "2015-05-01T22:07:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T02:19:10.000Z", "max_forks_repo_path": "TemplePlus/util/savegame.h", "max_forks_repo_name": "edoipi/TemplePlus", "max_forks_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2016-02-04T21:19:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T23:14:51.000Z", "avg_line_length": 21.1546391753, "max_line_length": 82, "alphanum_fraction": 0.7658382066, "num_tokens": 1153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12940273159163906, "lm_q2_score": 0.010986941234038093, "lm_q1q2_score": 0.0014217402075213429}}
{"text": "/* The VCL screen capture library is released under the MIT license.\n * \n * Copyright(c) 2018 Basil Fierz\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files(the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions :\n * \n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n#pragma once\n\n// Abseil\n#include <absl/strings/string_view.h>\n\n// C++ standard library\n#include <array>\n#include <utility>\n\n// GSL\n#include <gsl/gsl>\n\n#ifdef VCL_GRAPHICS_RECORDER_EXPORTS\n#\tdefine VCL_GRAPHICS_RECORDER_API __declspec(dllexport)   \n#else  \n#\tdefine VCL_GRAPHICS_RECORDER_API __declspec(dllimport)   \n#endif \n\nextern \"C\"\n{\n\tstruct AVCodec;\n\tstruct AVCodecContext;\n\tstruct AVCodecParameters;\n\tstruct AVFormatContext;\n\tstruct AVFrame;\n\tstruct AVStream;\n}\n\nnamespace Vcl { namespace Graphics { namespace Recorder\n{\n\tenum class OutputFormat\n\t{\n\t\tAvi,\n\t\tMkv,\n\t\tMp4\n\t};\n\n\tenum class CodecType\n\t{\n\t\tH264\n\t};\n\n\tclass VCL_GRAPHICS_RECORDER_API Recorder\n\t{\n\tpublic:\n\t\tRecorder(OutputFormat out_fmt, CodecType codec);\n\t\t~Recorder();\n\n\tpublic:\n\t\tvoid open(absl::string_view sink_name, unsigned int width, unsigned int height, unsigned int frame_rate);\n\t\tvoid close();\n\n\t\tbool write(gsl::span<const uint8_t> Y, gsl::span<const uint8_t> U, gsl::span<const uint8_t> V);\n\t\tbool write(gsl::span<const uint8_t> Y, gsl::span<const std::array<uint8_t, 2>> UV);\n\t\tbool write(gsl::span<const std::array<uint8_t, 3>> rgb, unsigned int w, unsigned int h);\n\n\tprivate:\n\t\t//! Create the output format\n\t\t//! \\param fmt Format to create\n\t\t//! \\param ctx Context to assign the output format to\n\t\tvoid createOutputFormat(OutputFormat fmt, gsl::not_null<AVFormatContext*> ctx) const;\n\n\t\t//! Prepare codec\n\t\t//! \\param codec Codec to create\n\t\tstd::pair<AVCodec*, AVCodecContext*> createCodec(CodecType codec_cfg) const;\n\n\t\t//! Configure specific H264 parameters\n\t\tvoid configureH264();\n\n\t\t//! Write a single frame to the output\n\t\t//! \\param frame Frame to write out. Use 'nullptr' to flush the codec.\n\t\t//! \\note Notes about internal API used:\n\t\t//! * https://blogs.gentoo.org/lu_zero/2016/03/29/new-avcodec-api/\n\t\t//! * https://www.ffmpeg.org/doxygen/3.4/group__lavc__encdec.html\n\t\tbool write(AVFrame* frame);\n\n\t\t//! Hold the formating of the IO container\n\t\tAVFormatContext* _fmtCtx{nullptr};\n\n\t\t//! Recording stream\n\t\tAVStream* _videoStream{nullptr};\n\n\t\t//! Actual codec\n\t\tAVCodec* _codec{nullptr};\n\n\t\t//! Codec context\n\t\tAVCodecContext* _codecCtx{nullptr};\n\n\t\t//! Is the output open\n\t\tbool _isOpen{false};\n\n\t\t//! Temporary frames for data processing\n\t\tAVFrame* _processing_frame{nullptr};\n\n\t\t//! Current frame count\n\t\tint64_t _frames{0};\n\t};\n}}}\n", "meta": {"hexsha": "ac315c9de64ecea793b8feaea01b3d962e9b3030", "size": 3518, "ext": "h", "lang": "C", "max_stars_repo_path": "src/vcl/graphics/recorder/recorder.h", "max_stars_repo_name": "bfierz/vcl.graphics.recorder", "max_stars_repo_head_hexsha": "b5b69ddfbe0da1f3cecc74a5e99167511fb53b26", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/vcl/graphics/recorder/recorder.h", "max_issues_repo_name": "bfierz/vcl.graphics.recorder", "max_issues_repo_head_hexsha": "b5b69ddfbe0da1f3cecc74a5e99167511fb53b26", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/vcl/graphics/recorder/recorder.h", "max_forks_repo_name": "bfierz/vcl.graphics.recorder", "max_forks_repo_head_hexsha": "b5b69ddfbe0da1f3cecc74a5e99167511fb53b26", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0743801653, "max_line_length": 107, "alphanum_fraction": 0.7328027288, "num_tokens": 910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.055823136422248926, "lm_q2_score": 0.02517884298071649, "lm_q1q2_score": 0.0014055619866669214}}
{"text": "#ifndef XYCO_RUNTIME_UTILS_SELECT_H\n#define XYCO_RUNTIME_UTILS_SELECT_H\n\n#include <gsl/pointers>\n#include <utility>\n\n#include \"runtime/runtime.h\"\n#include \"type_wrapper.h\"\n\nnamespace xyco::runtime {\ntemplate <typename T1, typename T2>\nclass SelectFuture\n    : public Future<std::variant<TypeWrapper<T1>, TypeWrapper<T2>>> {\n  using CoOutput = std::variant<TypeWrapper<T1>, TypeWrapper<T2>>;\n\n public:\n  auto poll(Handle<void> self) -> Poll<CoOutput> override {\n    if (!ready_) {\n      ready_ = true;\n      auto [wrapper1, wrapper2] = std::pair<Future<void>, Future<void>>(\n          future_wrapper<T1, 0>(std::move(futures_.first)),\n          future_wrapper<T2, 1>(std::move(futures_.second)));\n      wrappers_ = {wrapper1.get_handle(), wrapper2.get_handle()};\n      RuntimeCtx::get_ctx()->spawn(std::move(wrapper1));\n      RuntimeCtx::get_ctx()->spawn(std::move(wrapper2));\n      return Pending();\n    }\n\n    if (result_.index() == 0) {\n      RuntimeCtx::get_ctx()->cancel_future(wrappers_.second);\n      return Ready<CoOutput>{\n          CoOutput(std::in_place_index<0>, std::get<0>(result_))};\n    }\n\n    RuntimeCtx::get_ctx()->cancel_future(wrappers_.first);\n    return Ready<CoOutput>{\n        CoOutput(std::in_place_index<1>, std::get<1>(result_))};\n  }\n\n  SelectFuture(Future<T1> &&future1, Future<T2> &&future2)\n      : Future<CoOutput>(nullptr),\n        ready_(false),\n        result_(std::in_place_index<2>, true),\n        futures_(std::move(future1), std::move(future2)) {}\n\n private:\n  template <typename T, int Index>\n  auto future_wrapper(Future<T> future) -> Future<void>\n  requires(!std::is_same_v<T, void>) {\n    auto result = co_await future;\n    if (result_.index() == 2) {\n      result_ = std::variant<TypeWrapper<T1>, TypeWrapper<T2>, bool>(\n          std::in_place_index<Index>, TypeWrapper<T>{result});\n      RuntimeCtx::get_ctx()->register_future(this);\n    }\n  }\n\n  template <typename T, int Index>\n  auto future_wrapper(Future<T> future) -> Future<void>\n  requires(std::is_same_v<T, void>) {\n    co_await future;\n    if (result_.index() == 2) {\n      result_ = std::variant<TypeWrapper<T1>, TypeWrapper<T2>, bool>(\n          std::in_place_index<Index>, TypeWrapper<T>());\n      RuntimeCtx::get_ctx()->register_future(this);\n    }\n  }\n\n  bool ready_;\n  std::variant<TypeWrapper<T1>, TypeWrapper<T2>, bool> result_;\n  std::pair<Future<T1>, Future<T2>> futures_;\n  std::pair<Handle<PromiseBase>, Handle<PromiseBase>> wrappers_;\n};\n\ntemplate <typename T1, typename T2>\nauto select(Future<T1> future1, Future<T2> future2)\n    -> Future<std::variant<TypeWrapper<T1>, TypeWrapper<T2>>> {\n  co_return co_await SelectFuture<T1, T2>(std::move(future1),\n                                          std::move(future2));\n}\n}  // namespace xyco::runtime\n\n#endif  // XYCO_RUNTIME_UTILS_SELECT_H", "meta": {"hexsha": "58f58f3afd3413e4f5ad8fbb0ad92425619eeaab", "size": 2804, "ext": "h", "lang": "C", "max_stars_repo_path": "src/runtime/utils/select.h", "max_stars_repo_name": "ddxy18/xyco", "max_stars_repo_head_hexsha": "7682652f17b82e2370fa7af17635c5d0c470efe0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/runtime/utils/select.h", "max_issues_repo_name": "ddxy18/xyco", "max_issues_repo_head_hexsha": "7682652f17b82e2370fa7af17635c5d0c470efe0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2021-10-30T06:10:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-18T06:16:15.000Z", "max_forks_repo_path": "src/runtime/utils/select.h", "max_forks_repo_name": "ddxy18/xyco", "max_forks_repo_head_hexsha": "7682652f17b82e2370fa7af17635c5d0c470efe0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7831325301, "max_line_length": 72, "alphanum_fraction": 0.6565620542, "num_tokens": 752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.05834584061168105, "lm_q2_score": 0.024053554468546266, "lm_q1q2_score": 0.0014034248551661889}}
{"text": "#ifndef __GSL_VERSION_H__\n#define __GSL_VERSION_H__\n\n#if !defined( GSL_FUN )\n#  if !defined( GSL_DLL )\n#    define GSL_FUN extern\n#  elif defined( BUILD_GSL_DLL )\n#    define GSL_FUN extern __declspec(dllexport)\n#  else\n#    define GSL_FUN extern __declspec(dllimport)\n#  endif\n#endif\n\n#include <gsl/gsl_types.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n__BEGIN_DECLS\n\n\n#define GSL_VERSION \"2.4\"\n#define GSL_MAJOR_VERSION 2\n#define GSL_MINOR_VERSION 4\n\nGSL_VAR const char * gsl_version;\n\n__END_DECLS\n\n#endif /* __GSL_VERSION_H__ */\n", "meta": {"hexsha": "ed7cb3275663921dcc3c0ee3b8723a89f0708a04", "size": 691, "ext": "h", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_version.h", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_version.h", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_version.h", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.6756756757, "max_line_length": 48, "alphanum_fraction": 0.7510853835, "num_tokens": 186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06560484293979195, "lm_q2_score": 0.021287353423333457, "lm_q1q2_score": 0.001396553477941634}}
{"text": "#pragma once\n\n#include \"../configuration.h\"\n#include <chrono>\n#include <gsl/gsl-lite.hpp>\n#include <string_view>\n#include <utility>\n#include <yaml-cpp/yaml.h>\n\nnamespace angonoka {\n/**\n    Load Configuration from a YAML string.\n\n    @param text Null-terminated string\n\n    @return An instance of Configuration\n*/\nConfiguration load_text(gsl::czstring text);\n\n/**\n    Load Configuration from a YAML file.\n\n    @param path YAML configuration location\n\n    @return An instance of Configuration\n*/\nConfiguration load_file(std::string_view path);\n} // namespace angonoka\n\nnamespace angonoka::detail {\n/**\n    Finds or inserts a group into Configuration.groups.\n\n    @param groups   An array of Groups\n    @param group    Group name\n\n    @return The index of the group in Configuration.groups\n    and whether the insertion took place.\n*/\nstd::pair<GroupIndex, bool>\nfind_or_insert_group(Groups& groups, std::string_view group);\n\n/**\n    Parses human-readable durations.\n\n    Parses durations with resolution ranging from seconds\n    up to and including months. Examples:\n\n    1h 15min\n    3 weeks and 5 months\n    30 seconds\n\n    @param text A string containing a duration.\n    @return The duration in seconds.\n*/\nstd::chrono::seconds parse_duration(std::string_view text);\n\n/**\n    Parses agents blocks.\n\n    Parses blocks such as these:\n\n    agents:\n      agent 1:\n      agent 2:\n\n    @param node     \"agents\" node\n    @param config   An instance of Configuration\n*/\nvoid parse_agents(const YAML::Node& node, Configuration& config);\n\n/**\n    Parses tasks blocks.\n\n    Parses blocks such as these:\n\n    tasks:\n      - name: task 1\n        duration:\n          min: 1 h\n          max: 3 h\n      - name: task 2\n        duration: 2h\n\n    @param node     \"tasks\" node\n    @param config   An instance of Configuration\n*/\nvoid parse_tasks(const YAML::Node& node, Configuration& config);\n} // namespace angonoka::detail\n", "meta": {"hexsha": "e44866e3f215e024a96d3a314f055045e59d4175", "size": 1907, "ext": "h", "lang": "C", "max_stars_repo_path": "src/config/load.h", "max_stars_repo_name": "coffee-lord/angonoka", "max_stars_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-10-23T18:05:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T21:53:24.000Z", "max_issues_repo_path": "src/config/load.h", "max_issues_repo_name": "coffee-lord/angonoka", "max_issues_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2022-02-12T19:52:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-12T19:55:52.000Z", "max_forks_repo_path": "src/config/load.h", "max_forks_repo_name": "coffee-lord/angonoka", "max_forks_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1888888889, "max_line_length": 65, "alphanum_fraction": 0.6832721552, "num_tokens": 443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08632346953458801, "lm_q2_score": 0.01615283248366141, "lm_q1q2_score": 0.0013943685428006493}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\n * Contact: lymastee@hotmail.com\n *\n * This file is part of the gslib project.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n#pragma once\n\n#ifndef thdpool_3a298e4f_792c_44ff_bc62_c639d1eb697c_h\n#define thdpool_3a298e4f_792c_44ff_bc62_c639d1eb697c_h\n\n#include <thread>\n#include <mutex>\n#include <condition_variable>\n#include <future>\n#include <functional>\n#include <gslib/std.h>\n\n__gslib_begin__\n\nusing std::thread;\nusing std::function;\n\nclass thread_pool\n{\npublic:\n    thread_pool(int threads)\n    {\n        for(int i = 0; i < threads; i ++) {\n            _workers.emplace_back(\n                [this]() {\n                    for(;;) {\n                        function<void()> task;\n                        {\n                            std::unique_lock<std::mutex> lock(_mtx_worker);\n                            _cv_worker.wait(lock, [this] { return _stop || !_tasks.empty(); });\n                            if(_stop && _tasks.empty())\n                                return;\n                            task = std::move(_tasks.front());\n                            _tasks.pop();\n                        }\n                        task();\n                        {\n                            std::unique_lock<std::mutex> lock(_mtx_main);\n                            -- _undone;\n                        }\n                        _cv_main.notify_one();\n                    }\n                }\n            );\n        }\n    }\n    ~thread_pool()\n    {\n        {\n            std::unique_lock<std::mutex> lock(_mtx_worker);\n            _stop = true;\n        }\n        _cv_worker.notify_all();\n        for(thread& worker : _workers)\n            worker.join();\n    }\n\nprotected:\n    vector<thread>          _workers;\n    queue<function<void()>> _tasks;\n    std::mutex              _mtx_worker;\n    std::mutex              _mtx_main;\n    std::condition_variable _cv_worker;\n    std::condition_variable _cv_main;\n    volatile bool           _stop = false;\n    volatile int            _undone = 0;\n\npublic:\n    template<class _func, class... _args>\n    auto add(_func&& f, _args&&... args) ->\n        std::future<typename std::result_of<_func(_args...)>::type>\n    {\n        using return_type = typename std::result_of<_func(_args...)>::type;\n        auto task = std::make_shared<std::packaged_task<return_type()>>(\n            std::bind(std::forward<_func>(f), std::forward<_args>(args)...)\n            );\n        std::future<return_type> res = task->get_future();\n        {\n            std::unique_lock<std::mutex> lock(_mtx_worker);\n            if(_stop)\n                throw std::runtime_error(\"enqueue on stopped thread pool.\");\n            _tasks.emplace([task]() { (*task)(); });\n        }\n        {\n            std::unique_lock<std::mutex> lock(_mtx_main);\n            ++ _undone;\n        }\n        _cv_worker.notify_one();\n        return res;\n    }\n    void join()\n    {\n        std::unique_lock<std::mutex> lock(_mtx_main);\n        _cv_main.wait(lock, [this] { return !_undone; });\n    }\n};\n\n__gslib_end__\n\n#endif\n\n", "meta": {"hexsha": "7bd8b8973277679ec76c44150f076f13a82697db", "size": 4111, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gslib/thdpool.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/gslib/thdpool.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gslib/thdpool.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 32.3700787402, "max_line_length": 95, "alphanum_fraction": 0.5682315738, "num_tokens": 912, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.04603389781857186, "lm_q2_score": 0.030214585866664676, "lm_q1q2_score": 0.0013908951584165072}}
{"text": "/****************************************************************************\n** Copyright (c) 2021, Fougue Ltd. <http://www.fougue.pro>\n** All rights reserved.\n** See license at https://github.com/fougue/mayo/blob/master/LICENSE.txt\n****************************************************************************/\n\n#pragma once\n\n#include <gsl/span>\n\nnamespace Mayo {\n\ntemplate<typename T> using Span = gsl::span<T>;\n\n} // namespace Mayo\n", "meta": {"hexsha": "7fc492f398e4d9afd21f70deb5261b8e1f04c857", "size": 435, "ext": "h", "lang": "C", "max_stars_repo_path": "src/base/span.h", "max_stars_repo_name": "Unionfab/mayo", "max_stars_repo_head_hexsha": "881b81b2b6febe6fb88967e4eef6ef22882e1734", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 382.0, "max_stars_repo_stars_event_min_datetime": "2018-02-24T23:46:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:08:24.000Z", "max_issues_repo_path": "src/base/span.h", "max_issues_repo_name": "Unionfab/mayo", "max_issues_repo_head_hexsha": "881b81b2b6febe6fb88967e4eef6ef22882e1734", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 102.0, "max_issues_repo_issues_event_min_datetime": "2017-05-18T09:36:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T15:24:28.000Z", "max_forks_repo_path": "src/base/span.h", "max_forks_repo_name": "Unionfab/mayo", "max_forks_repo_head_hexsha": "881b81b2b6febe6fb88967e4eef6ef22882e1734", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 124.0, "max_forks_repo_forks_event_min_datetime": "2017-10-22T23:40:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T08:57:23.000Z", "avg_line_length": 27.1875, "max_line_length": 77, "alphanum_fraction": 0.4505747126, "num_tokens": 77, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.04813676565451048, "lm_q2_score": 0.028870908408551135, "lm_q1q2_score": 0.001389752152295262}}
{"text": "#pragma once\n\n// Windows\n#if defined(_WIN32)\n#if !defined(NOMINMAX)\n#define NOMINMAX\n#endif\n#include <windows.h>\n#endif\n\n// Standard\n#include <cstdlib>\n#include <exception>\n#include <stdexcept>\n#include <cassert>\n#include <string>\n#include <vector>\n#include <map>\n#include <memory>\n#include <cstdint>\n#include <sstream>\n#include <fstream>\n#include <chrono>\n#include <functional>\n#include <algorithm>\n#include <iterator>\n\n#if defined(DEBUG) || defined(_DEBUG)\n#define _CRTDBG_MAP_ALLOC\n#include <crtdbg.h>\n#endif\n\n// Guidline Support Library\n#include <gsl/gsl>\n\n// OpenGL\n#include <GL/gl3w.h>\n#define GLFW_INCLUDE_GLCOREARB\n#include <GLFW/glfw3.h>\n\n#if defined(_LINUX)\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wconversion\"\n#endif\n\n#define GLM_ENABLE_EXPERIMENTAL\n#include <glm/glm.hpp>\n#include <glm/gtc/matrix_transform.hpp>\n\n#if defined(_LINUX)\n#pragma GCC diagnostic pop\n#endif\n\n//#include <SOIL/SOIL.h>\n\n// Assimp\n#if defined(_LINUX)\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wconversion\"\n#endif\n#include <assimp/scene.h>\n#include <assimp/Importer.hpp>\n#include <assimp/postprocess.h>\n#if defined(_LINUX)\n#pragma GCC diagnostic pop\n#endif\n\n// Local\n#include \"ServiceContainer.h\"\n\nnamespace Library\n{\n\textern ServiceContainer GlobalServices;\n}", "meta": {"hexsha": "58c31478292d98801e87c6a11e396dab0924a960", "size": 1284, "ext": "h", "lang": "C", "max_stars_repo_path": "source/Library.Shared/pch.h", "max_stars_repo_name": "DakkyDaWolf/OpenGL", "max_stars_repo_head_hexsha": "628e9aed116022175cc0c59c88ace7688309628c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/Library.Shared/pch.h", "max_issues_repo_name": "DakkyDaWolf/OpenGL", "max_issues_repo_head_hexsha": "628e9aed116022175cc0c59c88ace7688309628c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/Library.Shared/pch.h", "max_forks_repo_name": "DakkyDaWolf/OpenGL", "max_forks_repo_head_hexsha": "628e9aed116022175cc0c59c88ace7688309628c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.3513513514, "max_line_length": 45, "alphanum_fraction": 0.7546728972, "num_tokens": 315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09009299396195182, "lm_q2_score": 0.015424550752337503, "lm_q1q2_score": 0.0013896439577961621}}
{"text": "#pragma once\n\n#include <atomic>\n#include <array>\n#include <cstdint>\n#include <future>\n#include <functional>\n#include <optional>\n#include <bitset>\n\n#ifndef SPDLOG_FMT_EXTERNAL\n#define SPDLOG_FMT_EXTERNAL 1\n#endif\n#include <spdlog/spdlog.h>\n\n#include <gsl/gsl-lite.hpp>\n\n// TODO: leaf pulls in Windows.h via common.hpp, so we bypass that here to avoid the mess\n// if something did pull in windows.h, this is fine. custom_formatmessage is just a wrapper.\n#ifndef _WINDOWS_\n\n#ifndef LPVOID\n#define LPVOID void*\n#define LPVOID_redefined\n#endif\n#ifndef LPCSTR\n#define LPCSTR char*\n#define LPCSTR_redefined\n#endif\n\nnamespace mu\n{\n\tauto custom_formatmessage(\n\t\tunsigned long dwFlags,\n\t\tconst void*\t  lpSource,\n\t\tunsigned long dwMessageId,\n\t\tunsigned long dwLanguageId,\n\t\tchar*\t\t  lpBuffer,\n\t\tunsigned long nSize,\n\t\tva_list*\t  Arguments) noexcept -> unsigned long;\n}\n\n#define FormatMessageA(DWORD_dwFlags, LPCVOID_lpSource, DWORD_dwMessageId, DWORD_dwLanguageId, LPSTR_lpBuffer, DWORD_nSize, va_list_Arguments)                                     \\\n\tmu::custom_formatmessage(DWORD_dwFlags, LPCVOID_lpSource, DWORD_dwMessageId, DWORD_dwLanguageId, LPSTR_lpBuffer, DWORD_nSize, va_list_Arguments)\n#define _WINDOWS_\n#define _WINDOWS_redefined\t\t\t   true\n#define FORMAT_MESSAGE_ALLOCATE_BUFFER 0x00000100\n#define FORMAT_MESSAGE_FROM_SYSTEM\t   0x00001000\n#define FORMAT_MESSAGE_IGNORE_INSERTS  0x00000200\n#define MAKELANGID(p, s)\t\t\t   ((((unsigned short)(s)) << 10) | (unsigned short)(p))\n#define LANG_NEUTRAL\t\t\t\t   0x00\n#define SUBLANG_DEFAULT\t\t\t\t   0x01\n#define LPSTR\t\t\t\t\t\t   char*\n#else // #ifndef _WINDOWS_\n#define _WINDOWS_redefined false\n#endif // #else // #ifndef _WINDOWS_\n#include <boost/leaf.hpp>\n#if _WINDOWS_redefined\n#ifdef LPVOID_redefined\n#undef LPVOID\n#undef LPVOID_redefined\n#endif\n#ifdef LPCSTR_redefined\n#undef LPCSTR_redefined\n#undef LPCSTR\n#endif\n#undef FormatMessageA\n#undef _WINDOWS_\n#undef _WINDOWS_redefined\n#undef FORMAT_MESSAGE_ALLOCATE_BUFFER\n#undef FORMAT_MESSAGE_FROM_SYSTEM\n#undef FORMAT_MESSAGE_IGNORE_INSERTS\n#undef MAKELANGID\n#undef LANG_NEUTRAL\n#undef SUBLANG_DEFAULT\n#undef LPSTR\n#endif // #if _WINDOWS_redefined\n\nnamespace mu\n{\n\ttemplate<typename E>\n\tconstexpr auto underlying_cast(E e) noexcept -> typename std::underlying_type<E>::type\n\t{\n\t\treturn static_cast<typename std::underlying_type<E>::type>(e);\n\t}\n} // namespace mu\n\nnamespace mu\n{\n\tnamespace leaf = boost::leaf;\n\n\tstruct common_error\n\t{\n\t};\n\n\tstruct runtime_error\n\t{\n\t\tstruct not_specified : common_error\n\t\t{\n\t\t};\n\t};\n} // namespace mu\n\n#define MU_LEAF_IF_REPORT(r)                                                                                                                                                       \\\n\tauto&& BOOST_LEAF_TMP = r;                                                                                                                                                     \\\n\tstatic_assert(::boost::leaf::is_result_type<typename std::decay<decltype(BOOST_LEAF_TMP)>::type>::value, \"MU_LEAF_CHECK requires a result object (see is_result_type)\");       \\\n\tif (!BOOST_LEAF_TMP)                                                                                                                                                           \\\n\t\t/*TODO: REPORT*/;                                                                                                                                                          \\\n\telse\n\n#define MU_LEAF_RETHROW(r)                                                                                                                                                         \\\n\tauto&& BOOST_LEAF_TMP = r;                                                                                                                                                     \\\n\tstatic_assert(::boost::leaf::is_result_type<typename std::decay<decltype(BOOST_LEAF_TMP)>::type>::value, \"MU_LEAF_CHECK requires a result object (see is_result_type)\");       \\\n\tif (BOOST_LEAF_TMP)                                                                                                                                                            \\\n\t\t;                                                                                                                                                                          \\\n\telse                                                                                                                                                                           \\\n\t{                                                                                                                                                                              \\\n\t\tthrow BOOST_LEAF_TMP.error();                                                                                                                                              \\\n\t}\n\n#define MU_LEAF_ASSIGN(v, r)                                                                                                                                                       \\\n\tauto&& BOOST_LEAF_TMP = r;                                                                                                                                                     \\\n\tstatic_assert(                                                                                                                                                                 \\\n\t\t::boost::leaf::is_result_type<std::decay<decltype(BOOST_LEAF_TMP)>::type>::value,                                                                                          \\\n\t\t\"MU_LEAF_ASSIGN and MU_LEAF_AUTO require a result object as the second argument (see is_result_type)\");                                                                    \\\n\tif (!BOOST_LEAF_TMP)                                                                                                                                                           \\\n\t{                                                                                                                                                                              \\\n\t\treturn BOOST_LEAF_TMP.error();                                                                                                                                             \\\n\t}                                                                                                                                                                              \\\n\tv = std::forward<decltype(BOOST_LEAF_TMP)>(BOOST_LEAF_TMP).value()\n\n#define MU_LEAF_PUSH_BACK(v, r)                                                                                                                                                    \\\n\tauto&& BOOST_LEAF_TMP = r;                                                                                                                                                     \\\n\tstatic_assert(                                                                                                                                                                 \\\n\t\t::boost::leaf::is_result_type<std::decay<decltype(BOOST_LEAF_TMP)>::type>::value,                                                                                          \\\n\t\t\"MU_LEAF_ASSIGN and MU_LEAF_AUTO require a result object as the second argument (see is_result_type)\");                                                                    \\\n\tif (!BOOST_LEAF_TMP)                                                                                                                                                           \\\n\t{                                                                                                                                                                              \\\n\t\treturn BOOST_LEAF_TMP.error();                                                                                                                                             \\\n\t}                                                                                                                                                                              \\\n\tv.push_back(std::forward<decltype(BOOST_LEAF_TMP)>(BOOST_LEAF_TMP).value())\n\n#define MU_LEAF_EMPLACE_BACK(v, r)                                                                                                                                                 \\\n\tauto&& BOOST_LEAF_TMP = r;                                                                                                                                                     \\\n\tstatic_assert(                                                                                                                                                                 \\\n\t\t::boost::leaf::is_result_type<std::decay<decltype(BOOST_LEAF_TMP)>::type>::value,                                                                                          \\\n\t\t\"MU_LEAF_ASSIGN and MU_LEAF_AUTO require a result object as the second argument (see is_result_type)\");                                                                    \\\n\tif (!BOOST_LEAF_TMP)                                                                                                                                                           \\\n\t{                                                                                                                                                                              \\\n\t\treturn BOOST_LEAF_TMP.error();                                                                                                                                             \\\n\t}                                                                                                                                                                              \\\n\tv.emplace_back(std::forward<decltype(BOOST_LEAF_TMP)>(BOOST_LEAF_TMP).value())\n\n#define MU_LEAF_AUTO(v, r) MU_LEAF_ASSIGN(auto v, r)\n\n#define MU_LEAF_ASSIGN_THROW(v, r)                                                                                                                                                 \\\n\tauto&& BOOST_LEAF_TMP = r;                                                                                                                                                     \\\n\tstatic_assert(                                                                                                                                                                 \\\n\t\t::boost::leaf::is_result_type<std::decay<decltype(BOOST_LEAF_TMP)>::type>::value,                                                                                          \\\n\t\t\"MU_LEAF_ASSIGN and MU_LEAF_AUTO require a result object as the second argument (see is_result_type)\");                                                                    \\\n\tif (!BOOST_LEAF_TMP)                                                                                                                                                           \\\n\t{                                                                                                                                                                              \\\n\t\tthrow BOOST_LEAF_TMP.error();                                                                                                                                              \\\n\t}                                                                                                                                                                              \\\n\tv = std::forward<decltype(BOOST_LEAF_TMP)>(BOOST_LEAF_TMP).value()\n\n#define MU_LEAF_AUTO_THROW(v, r) MU_LEAF_ASSIGN_THROW(auto v, r)\n\n#define MU_LEAF_CHECK(r)                                                                                                                                                           \\\n\tauto&& BOOST_LEAF_TMP = r;                                                                                                                                                     \\\n\tstatic_assert(::boost::leaf::is_result_type<std::decay<decltype(BOOST_LEAF_TMP)>::type>::value, \"MU_LEAF_CHECK requires a result object (see is_result_type)\");                \\\n\tif (BOOST_LEAF_TMP)                                                                                                                                                            \\\n\t\t;                                                                                                                                                                          \\\n\telse                                                                                                                                                                           \\\n\t{                                                                                                                                                                              \\\n\t\treturn BOOST_LEAF_TMP.error();                                                                                                                                             \\\n\t}\n\n#define MU_LEAF_NEW_ERROR\t\t::boost::leaf::leaf_detail::inject_loc{__FILE__, __LINE__, __FUNCTION__} + ::boost::leaf::new_error\n#define MU_LEAF_EXCEPTION\t\t::boost::leaf::leaf_detail::inject_loc{__FILE__, __LINE__, __FUNCTION__} + ::boost::leaf::exception\n#define MU_LEAF_THROW_EXCEPTION ::boost::leaf::leaf_detail::throw_with_loc{__FILE__, __LINE__, __FUNCTION__} + ::boost::leaf::exception\n#define MU_LEAF_LOG_ERROR(...)\t((void)0)\n\nnamespace mu\n{\n\ttemplate<typename T>\n\tusing optional_future = std::future<std::optional<T>>;\n\n\ttemplate<typename T>\n\tinline auto future_is_ready(T const& f) noexcept -> bool\n\t{\n\t\treturn f.wait_for(std::chrono::seconds(0)) == std::future_status::ready;\n\t}\n} // namespace mu\n\nnamespace mu\n{\n\tnamespace details\n\t{\n\t\ttemplate<typename T>\n\t\tclass static_root_singleton\n\t\t{\n\t\tpublic:\n\t\t\tauto operator->() noexcept -> T*\n\t\t\t{\n\t\t\t\treturn s_instance;\n\t\t\t}\n\n\t\t\tauto operator->() const noexcept -> const T*\n\t\t\t{\n\t\t\t\treturn s_instance;\n\t\t\t}\n\n\t\t\tauto operator*() noexcept -> T&\n\t\t\t{\n\t\t\t\treturn *s_instance;\n\t\t\t}\n\n\t\t\tauto operator*() const noexcept -> const T&\n\t\t\t{\n\t\t\t\treturn *s_instance;\n\t\t\t}\n\n\t\t\tstatic_root_singleton() noexcept\n\t\t\t{\n\t\t\t\tstatic bool static_init = []() -> bool\n\t\t\t\t{\n\t\t\t\t\ts_instance = new (&s_instance_memory[0]) T();\n\t\t\t\t\tstd::atexit(destroy);\n\t\t\t\t\treturn true;\n\t\t\t\t}();\n\t\t\t}\n\n\t\tprotected:\n\t\t\tstatic void destroy() noexcept\n\t\t\t{\n\t\t\t\tif (s_instance)\n\t\t\t\t{\n\t\t\t\t\ts_instance->~T();\n\t\t\t\t\ts_instance = nullptr;\n\t\t\t\t}\n\t\t\t}\n\n\t\tprivate:\n\t\t\tstatic inline uint64_t s_instance_memory[1 + (sizeof(T) / sizeof(uint64_t))];\n\t\t\tstatic inline T*\t   s_instance = nullptr;\n\t\t};\n\n\t\ttemplate<size_t POOL_COUNT>\n\t\tclass singleton_cleanup_list\n\t\t{\n\t\tpublic:\n\t\t\tusing cleanup_func = std::function<void()>;\n\n\t\t\tvoid push(cleanup_func f) noexcept\n\t\t\t{\n\t\t\t\ts_cleanup_funcs[s_cleanup_index.fetch_add(1)] = f;\n\t\t\t}\n\n\t\t\t~singleton_cleanup_list() noexcept\n\t\t\t{\n\t\t\t\tfor (auto i = s_cleanup_index.load(); i > 0; --i)\n\t\t\t\t{\n\t\t\t\t\ts_cleanup_funcs[i - 1]();\n\t\t\t\t}\n\t\t\t\ts_cleanup_index.store(0);\n\t\t\t}\n\n\t\tprivate:\n\t\t\tstd::array<cleanup_func, POOL_COUNT> s_cleanup_funcs;\n\t\t\tstd::atomic_size_t\t\t\t\t\t s_cleanup_index = 0;\n\t\t};\n\n\t\tusing singleton_cleanup_root = details::static_root_singleton<details::singleton_cleanup_list<1024>>;\n\n\t\ttemplate<typename... T_DEPS>\n\t\tstruct singleton_dependencies\n\t\t{\n\t\tprivate:\n\t\t\ttemplate<typename T_ARG, typename... T_ARGS>\n\t\t\tstatic inline void update_dependencies_impl() noexcept\n\t\t\t{\n\t\t\t\tconst typename T_ARG::type* t = T_ARG().get();\n\t\t\t\tif constexpr (sizeof...(T_ARGS) > 0)\n\t\t\t\t{\n\t\t\t\t\tupdate_dependencies_impl<T_ARGS...>();\n\t\t\t\t}\n\t\t\t}\n\n\t\tpublic:\n\t\t\tstatic inline void update() noexcept\n\t\t\t{\n\t\t\t\tif constexpr (sizeof...(T_DEPS) > 0)\n\t\t\t\t{\n\t\t\t\t\tupdate_dependencies_impl<T_DEPS...>();\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\ttemplate<typename T, typename... T_DEPS>\n\t\tstruct singleton_factory\n\t\t{\n\t\t\tstatic inline auto create() noexcept -> T*\n\t\t\t{\n\t\t\t\tif constexpr (sizeof...(T_DEPS) > 0)\n\t\t\t\t{\n\t\t\t\t\tsingleton_dependencies<T_DEPS...>::update();\n\t\t\t\t}\n\t\t\t\treturn new T();\n\t\t\t}\n\t\t};\n\n\t\ttemplate<typename T>\n\t\tstruct virtual_singleton_factory\n\t\t{\n\t\t\tstatic auto create() noexcept -> T*;\n\t\t};\n\t} // namespace details\n\n#define MU_DEFINE_VIRTUAL_SINGLETON(T, T_DERIVED)                                                                                                                                  \\\n\tnamespace mu                                                                                                                                                                   \\\n\t{                                                                                                                                                                              \\\n\t\tnamespace details                                                                                                                                                          \\\n\t\t{                                                                                                                                                                          \\\n\t\t\ttemplate<>                                                                                                                                                             \\\n\t\t\tauto virtual_singleton_factory<T>::create() noexcept -> T*                                                                                                             \\\n\t\t\t{                                                                                                                                                                      \\\n\t\t\t\treturn new T_DERIVED;                                                                                                                                              \\\n\t\t\t}                                                                                                                                                                      \\\n\t\t}                                                                                                                                                                          \\\n\t}                                                                                                                                                                              \\\n\t/**/\n\n#define MU_DEFINE_VIRTUAL_SINGLETON_DEPS(T, T_DERIVED, ...)                                                                                                                        \\\n\tnamespace mu                                                                                                                                                                   \\\n\t{                                                                                                                                                                              \\\n\t\tnamespace details                                                                                                                                                          \\\n\t\t{                                                                                                                                                                          \\\n\t\t\ttemplate<>                                                                                                                                                             \\\n\t\t\tauto virtual_singleton_factory<T>::create() noexcept -> T*                                                                                                             \\\n\t\t\t{                                                                                                                                                                      \\\n\t\t\t\tsingleton_dependencies<__VA_ARGS__>::update();                                                                                                                     \\\n\t\t\t\treturn new T_DERIVED;                                                                                                                                              \\\n\t\t\t}                                                                                                                                                                      \\\n\t\t}                                                                                                                                                                          \\\n\t}                                                                                                                                                                              \\\n\t/**/\n\n\tnamespace details\n\t{\n\t\ttemplate<typename T, typename T_FACTORY>\n\t\tclass singleton_base\n\t\t{\n\t\tpublic:\n\t\t\tusing factory = T_FACTORY;\n\t\t\tusing type\t  = T;\n\n\t\t\tauto operator->() noexcept -> T*\n\t\t\t{\n\t\t\t\treturn s_instance;\n\t\t\t}\n\n\t\t\tauto operator->() const noexcept -> const T*\n\t\t\t{\n\t\t\t\treturn s_instance;\n\t\t\t}\n\n\t\t\tauto operator*() noexcept -> T&\n\t\t\t{\n\t\t\t\treturn *s_instance;\n\t\t\t}\n\n\t\t\tauto operator*() const noexcept -> const T&\n\t\t\t{\n\t\t\t\treturn *s_instance;\n\t\t\t}\n\n\t\t\tauto get() noexcept -> T*\n\t\t\t{\n\t\t\t\treturn s_instance;\n\t\t\t}\n\n\t\t\tauto get() const noexcept -> const T*\n\t\t\t{\n\t\t\t\treturn s_instance;\n\t\t\t}\n\n\t\t\tsingleton_base() noexcept\n\t\t\t{\n\t\t\t\tstatic bool static_init = []() -> bool\n\t\t\t\t{\n\t\t\t\t\ts_instance = factory::create();\n\t\t\t\t\tsingleton_cleanup_root()->push(\n\t\t\t\t\t\t[]() -> void\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tdelete s_instance;\n\t\t\t\t\t\t\ts_instance = nullptr;\n\t\t\t\t\t\t});\n\t\t\t\t\treturn true;\n\t\t\t\t}();\n\t\t\t}\n\n\t\tprivate:\n\t\t\tstatic inline T* s_instance;\n\t\t};\n\t} // namespace details\n\n\ttemplate<typename T, typename... T_DEPENDENCIES>\n\tusing singleton = details::singleton_base<T, details::singleton_factory<T, T_DEPENDENCIES...>>;\n\n\ttemplate<typename T, typename... T_DEPENDENCIES>\n\tusing virtual_singleton = details::singleton_base<T, details::virtual_singleton_factory<T>>;\n\n\ttemplate<typename T_SINGLETON>\n\tclass exported_singleton\n\t{\n\tpublic:\n\t\tusing singleton_type = T_SINGLETON;\n\t\tusing type\t\t\t = typename singleton_type::type;\n\n\t\tauto operator->() noexcept -> type*\n\t\t{\n\t\t\treturn s_instance;\n\t\t}\n\n\t\tauto operator->() const noexcept -> const type*\n\t\t{\n\t\t\treturn s_instance;\n\t\t}\n\n\t\tauto operator*() noexcept -> type&\n\t\t{\n\t\t\treturn *s_instance;\n\t\t}\n\n\t\tauto operator*() const noexcept -> const type&\n\t\t{\n\t\t\treturn *s_instance;\n\t\t}\n\n\t\tauto get() noexcept -> type*\n\t\t{\n\t\t\treturn s_instance;\n\t\t}\n\n\t\tauto get() const noexcept -> const type*\n\t\t{\n\t\t\treturn s_instance;\n\t\t}\n\n\t\texported_singleton() noexcept\n\t\t{\n\t\t\tstatic bool static_init = []() -> bool\n\t\t\t{\n\t\t\t\ts_instance = get_instance();\n\t\t\t\treturn true;\n\t\t\t}();\n\t\t}\n\n\tprivate:\n\t\tstatic inline type* s_instance;\n\t\tstatic type*\t\tget_instance() noexcept;\n\t};\n\n#define MU_EXPORT_SINGLETON(T)                                                                                                                                                     \\\n\ttemplate<>                                                                                                                                                                     \\\n\tauto T::get_instance() noexcept->T::type*                                                                                                                                      \\\n\t{                                                                                                                                                                              \\\n\t\treturn singleton_type().get();                                                                                                                                             \\\n\t}                                                                                                                                                                              \\\n\t/**/\n\n#define MU_EXPORT_SINGLETON_DEPS(T, ...)                                                                                                                                           \\\n\ttemplate<>                                                                                                                                                                     \\\n\tauto T::get_instance() noexcept->T::type*                                                                                                                                      \\\n\t{                                                                                                                                                                              \\\n\t\t::mu::details::singleton_dependencies<__VA_ARGS__>::update();                                                                                                              \\\n\t\treturn singleton_type().get();                                                                                                                                             \\\n\t}                                                                                                                                                                              \\\n\t/**/\n\n\tnamespace details\n\t{\n\t\ttemplate<typename T>\n\t\tclass static_root_thread_local_singleton\n\t\t{\n\t\tpublic:\n\t\t\tauto operator->() noexcept -> T*\n\t\t\t{\n\t\t\t\treturn s_instance;\n\t\t\t}\n\n\t\t\tauto operator->() const noexcept -> const T*\n\t\t\t{\n\t\t\t\treturn s_instance;\n\t\t\t}\n\n\t\t\tauto operator*() noexcept -> T&\n\t\t\t{\n\t\t\t\treturn *s_instance;\n\t\t\t}\n\n\t\t\tauto operator*() const noexcept -> const T&\n\t\t\t{\n\t\t\t\treturn *s_instance;\n\t\t\t}\n\n\t\t\tstatic_root_thread_local_singleton() noexcept\n\t\t\t{\n\t\t\t\tstatic bool static_init = []() -> bool\n\t\t\t\t{\n\t\t\t\t\ts_instance = new (&s_instance_memory[0]) T();\n\t\t\t\t\tstd::atexit(destroy);\n\t\t\t\t\treturn true;\n\t\t\t\t}();\n\t\t\t}\n\n\t\tprotected:\n\t\t\tstatic void destroy() noexcept\n\t\t\t{\n\t\t\t\tif (s_instance)\n\t\t\t\t{\n\t\t\t\t\ts_instance->~T();\n\t\t\t\t\ts_instance = nullptr;\n\t\t\t\t}\n\t\t\t}\n\n\t\tprivate:\n\t\t\tstatic inline thread_local uint64_t s_instance_memory[1 + (sizeof(T) / sizeof(uint64_t))];\n\t\t\tstatic inline thread_local T*\t\ts_instance = nullptr;\n\t\t};\n\n\t\tusing thread_local_singleton_cleanup_root = static_root_thread_local_singleton<singleton_cleanup_list<1024>>;\n\n\t\ttemplate<typename T, typename T_FACTORY>\n\t\tclass thread_local_singleton_base\n\t\t{\n\t\tpublic:\n\t\t\tusing type = T;\n\t\t\tauto operator->() noexcept -> T*\n\t\t\t{\n\t\t\t\treturn s_instance;\n\t\t\t}\n\n\t\t\tauto operator->() const noexcept -> const T*\n\t\t\t{\n\t\t\t\treturn s_instance;\n\t\t\t}\n\n\t\t\tauto operator*() noexcept -> T&\n\t\t\t{\n\t\t\t\treturn *s_instance;\n\t\t\t}\n\n\t\t\tauto operator*() const noexcept -> const T&\n\t\t\t{\n\t\t\t\treturn *s_instance;\n\t\t\t}\n\n\t\t\tauto get() noexcept -> T*\n\t\t\t{\n\t\t\t\treturn s_instance;\n\t\t\t}\n\n\t\t\tauto get() const noexcept -> const T*\n\t\t\t{\n\t\t\t\treturn s_instance;\n\t\t\t}\n\n\t\t\tthread_local_singleton_base() noexcept\n\t\t\t{\n\t\t\t\tstatic thread_local bool static_init = []() -> bool\n\t\t\t\t{\n\t\t\t\t\ts_instance = new T();\n\t\t\t\t\tthread_local_singleton_cleanup_root()->push(\n\t\t\t\t\t\t[]() -> void\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tdelete s_instance;\n\t\t\t\t\t\t\ts_instance = nullptr;\n\t\t\t\t\t\t});\n\t\t\t\t\treturn true;\n\t\t\t\t}();\n\t\t\t}\n\n\t\t\tstatic inline thread_local T* s_instance;\n\t\t};\n\t} // namespace details\n\n\ttemplate<typename T, typename... T_DEPENDENCIES>\n\tusing thread_local_singleton = details::thread_local_singleton_base<T, details::singleton_factory<T, T_DEPENDENCIES...>>;\n\n\ttemplate<typename T, typename... T_DEPENDENCIES>\n\tusing thread_local_virtual_singleton = details::thread_local_singleton_base<T, details::virtual_singleton_factory<T>>;\n\n\ttemplate<typename T_SINGLETON>\n\tclass exported_thread_local_singleton\n\t{\n\tpublic:\n\t\tusing singleton_type = T_SINGLETON;\n\t\tusing type\t\t\t = typename singleton_type::type;\n\n\t\tauto operator->() noexcept -> type*\n\t\t{\n\t\t\treturn s_instance;\n\t\t}\n\n\t\tauto operator->() const noexcept -> const type*\n\t\t{\n\t\t\treturn s_instance;\n\t\t}\n\n\t\tauto operator*() noexcept -> type&\n\t\t{\n\t\t\treturn *s_instance;\n\t\t}\n\n\t\tauto operator*() const noexcept -> const type&\n\t\t{\n\t\t\treturn *s_instance;\n\t\t}\n\n\t\tauto get() noexcept -> type*\n\t\t{\n\t\t\treturn s_instance;\n\t\t}\n\n\t\tauto get() const noexcept -> const type*\n\t\t{\n\t\t\treturn s_instance;\n\t\t}\n\n\t\texported_thread_local_singleton() noexcept\n\t\t{\n\t\t\tstatic thread_local bool static_init = []() -> bool\n\t\t\t{\n\t\t\t\ts_instance = get_instance();\n\t\t\t\treturn true;\n\t\t\t}();\n\t\t}\n\n\tprivate:\n\t\tstatic inline thread_local type* s_instance;\n\t\tstatic type*\t\t\t\t\t get_instance() noexcept;\n\t};\n\n#define MU_EXPORT_THREAD_LOCAL_SINGLETON(T)                                                                                                                                        \\\n\ttemplate<>                                                                                                                                                                     \\\n\tauto ::mu::exported_thread_local_singleton<T>::get_instance() noexcept->::mu::exported_thread_local_singleton<T>::type*                                                        \\\n\t{                                                                                                                                                                              \\\n\t\treturn singleton_type().get();                                                                                                                                             \\\n\t}                                                                                                                                                                              \\\n\t/**/\n} // namespace mu\n\nnamespace mu\n{\n\tnamespace time\n\t{\n\t\tauto performance_frequency() noexcept -> int64_t;\n\t\tauto get_now() noexcept -> int64_t;\n\t\tvoid sleep(const int64_t milliseconds) noexcept;\n\t\tvoid micro_sleep(const int64_t tx) noexcept;\n\t\tvoid init() noexcept;\n\t\tvoid calibrate() noexcept;\n\t\tvoid set_high_resolution_timer() noexcept;\n\t\tauto release_high_resolution_timer() noexcept -> leaf::result<void>;\n\n\t\tclass moment\n\t\t{\n\t\t\tfriend class run_time;\n\t\t\tfriend class long_clock;\n\n\t\tprotected:\n\t\t\tint64_t value;\n\n\t\t\tmoment(const int64_t v) noexcept : value(v) { }\n\n\t\t\tmoment(const long double v) noexcept : value(static_cast<int64_t>(v)) { }\n\n\t\t\tfriend auto now() noexcept -> moment;\n\n\t\t\ttemplate<typename T>\n\t\t\tfriend auto seconds(const T&) noexcept -> moment;\n\n\t\t\ttemplate<typename T>\n\t\t\tfriend auto milliseconds(const T&) noexcept -> moment;\n\n\t\t\ttemplate<typename T>\n\t\t\tfriend auto microseconds(const T&) noexcept -> moment;\n\n\t\t\ttemplate<typename T>\n\t\t\tfriend auto nanoseconds(const T&) noexcept -> moment;\n\n\t\tpublic:\n\t\t\tmoment() noexcept : value(0) { }\n\n\t\t\tinline auto operator=(const moment& rhs) noexcept -> moment&\n\t\t\t{\n\t\t\t\tvalue = rhs.value;\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\tinline auto operator+=(const moment& rhs) noexcept -> moment&\n\t\t\t{\n\t\t\t\tvalue += rhs.value;\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\tinline auto operator-=(const moment& rhs) noexcept -> moment&\n\t\t\t{\n\t\t\t\tvalue += rhs.value;\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\ttemplate<typename T>\n\t\t\tinline auto operator*=(const T& rhs) noexcept -> moment&\n\t\t\t{\n\t\t\t\tvalue = static_cast<int64_t>(static_cast<long double>(value) * static_cast<long double>(rhs));\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\ttemplate<typename T>\n\t\t\tinline auto operator/=(const T& rhs) noexcept -> moment&\n\t\t\t{\n\t\t\t\tvalue = static_cast<int64_t>(static_cast<long double>(value) / static_cast<long double>(rhs));\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\tinline auto add(const moment& rhs) const noexcept -> moment\n\t\t\t{\n\t\t\t\treturn moment{value + rhs.value};\n\t\t\t}\n\n\t\t\tinline auto sub(const moment& rhs) const noexcept -> moment\n\t\t\t{\n\t\t\t\treturn moment{value - rhs.value};\n\t\t\t}\n\n\t\t\ttemplate<typename T>\n\t\t\tinline auto div(const T& rhs) const noexcept -> moment\n\t\t\t{\n\t\t\t\treturn moment{static_cast<long double>(value) / static_cast<long double>(rhs)};\n\t\t\t}\n\n\t\t\ttemplate<typename T>\n\t\t\tinline auto mul(const T& rhs) const noexcept -> moment\n\t\t\t{\n\t\t\t\treturn moment{static_cast<long double>(value) * static_cast<long double>(rhs)};\n\t\t\t}\n\n\t\t\ttemplate<typename T>\n\t\t\tinline auto as_seconds() const noexcept -> T\n\t\t\t{\n\t\t\t\treturn static_cast<T>(static_cast<long double>(value) / static_cast<long double>(performance_frequency()));\n\t\t\t}\n\n\t\t\ttemplate<typename T>\n\t\t\tinline auto as_milliseconds() const noexcept -> T\n\t\t\t{\n\t\t\t\treturn static_cast<T>(static_cast<long double>(value) / ((static_cast<long double>(performance_frequency()) / static_cast<long double>(1000ull))));\n\t\t\t}\n\n\t\t\ttemplate<typename T>\n\t\t\tinline auto as_microseconds() const noexcept -> T\n\t\t\t{\n\t\t\t\treturn static_cast<T>(static_cast<long double>(value) / ((static_cast<long double>(performance_frequency()) / static_cast<long double>(1000ull * 1000ull))));\n\t\t\t}\n\n\t\t\ttemplate<typename T>\n\t\t\tinline auto as_nanoseconds() const noexcept -> T\n\t\t\t{\n\t\t\t\treturn static_cast<T>(\n\t\t\t\t\tstatic_cast<long double>(value) / ((static_cast<long double>(performance_frequency()) / static_cast<long double>(1000ull * 1000ull * 1000ull))));\n\t\t\t}\n\n\t\t\ttemplate<typename T>\n\t\t\tinline auto as_ticks() const noexcept -> T\n\t\t\t{\n\t\t\t\treturn static_cast<T>(value);\n\t\t\t}\n\n\t\t\ttemplate<typename T>\n\t\t\tinline auto set_seconds(const T& seconds) noexcept -> moment&\n\t\t\t{\n\t\t\t\tvalue = static_cast<int64_t>((static_cast<long double>(performance_frequency())) * static_cast<long double>(seconds));\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\ttemplate<typename T>\n\t\t\tinline auto set_milliseconds(const T& seconds) noexcept -> moment&\n\t\t\t{\n\t\t\t\tvalue = static_cast<int64_t>((static_cast<long double>(performance_frequency()) / static_cast<long double>(1000ull)) * static_cast<long double>(seconds));\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\ttemplate<typename T>\n\t\t\tinline auto set_microseconds(const T& seconds) noexcept -> moment&\n\t\t\t{\n\t\t\t\tvalue = static_cast<int64_t>((static_cast<long double>(performance_frequency()) / static_cast<long double>(1000ull * 1000ull)) * static_cast<long double>(seconds));\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\ttemplate<typename T>\n\t\t\tinline auto set_nanoseconds(const T& seconds) noexcept -> moment&\n\t\t\t{\n\t\t\t\tvalue = static_cast<int64_t>(\n\t\t\t\t\t(static_cast<long double>(performance_frequency()) / static_cast<long double>(1000ull * 1000ull * 1000ull)) * static_cast<long double>(seconds));\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\ttemplate<typename T>\n\t\t\tinline auto set_ticks(const T& tx) noexcept -> moment&\n\t\t\t{\n\t\t\t\tvalue = static_cast<int64_t>(tx);\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\tinline auto now() noexcept -> moment&\n\t\t\t{\n\t\t\t\tvalue = get_now();\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t};\n\n\t\tclass long_clock\n\t\t{\n\t\t\tuint64_t value;\n\t\t\tmoment\t last_moment;\n\n\t\tpublic:\n\t\t\tlong_clock() noexcept : value(0) { }\n\n\t\t\ttemplate<typename T>\n\t\t\tinline auto as_seconds() const noexcept -> T\n\t\t\t{\n\t\t\t\treturn static_cast<T>(static_cast<long double>(value) / static_cast<long double>(1000ull));\n\t\t\t}\n\n\t\t\ttemplate<typename T>\n\t\t\tinline auto as_milliseconds() const noexcept -> T\n\t\t\t{\n\t\t\t\treturn static_cast<T>(static_cast<long double>(value));\n\t\t\t}\n\n\t\t\ttemplate<typename T>\n\t\t\tinline auto as_microseconds() const noexcept -> T\n\t\t\t{\n\t\t\t\treturn static_cast<T>(static_cast<long double>(value) * static_cast<long double>(1000ull));\n\t\t\t}\n\n\t\t\tvoid update() noexcept;\n\t\t};\n\n\t\tinline auto operator<(const moment& lhs, const moment& rhs) noexcept -> bool\n\t\t{\n\t\t\treturn lhs.as_ticks<int64_t>() < rhs.as_ticks<int64_t>();\n\t\t}\n\n\t\tinline auto operator<=(const moment& lhs, const moment& rhs) noexcept -> bool\n\t\t{\n\t\t\treturn lhs.as_ticks<int64_t>() <= rhs.as_ticks<int64_t>();\n\t\t}\n\n\t\tinline auto operator>(const moment& lhs, const moment& rhs) noexcept -> bool\n\t\t{\n\t\t\treturn lhs.as_ticks<int64_t>() > rhs.as_ticks<int64_t>();\n\t\t}\n\n\t\tinline auto operator>=(const moment& lhs, const moment& rhs) noexcept -> bool\n\t\t{\n\t\t\treturn lhs.as_ticks<int64_t>() >= rhs.as_ticks<int64_t>();\n\t\t}\n\n\t\tinline auto operator==(const moment& lhs, const moment& rhs) noexcept -> bool\n\t\t{\n\t\t\treturn lhs.as_ticks<int64_t>() == rhs.as_ticks<int64_t>();\n\t\t}\n\n\t\tinline auto operator+(const moment& lhs, const moment& rhs) noexcept -> moment\n\t\t{\n\t\t\treturn lhs.add(rhs);\n\t\t}\n\n\t\tinline auto operator-(const moment& lhs, const moment& rhs) noexcept -> moment\n\t\t{\n\t\t\treturn lhs.sub(rhs);\n\t\t}\n\n\t\ttemplate<typename T>\n\t\tinline auto operator/(const moment& lhs, const T& rhs) noexcept -> moment\n\t\t{\n\t\t\treturn lhs.div(rhs);\n\t\t}\n\n\t\ttemplate<typename T>\n\t\tinline auto operator*(const moment& lhs, const T& rhs) noexcept -> moment\n\t\t{\n\t\t\treturn lhs.mul(rhs);\n\t\t}\n\n\t\tinline auto now() noexcept -> moment\n\t\t{\n\t\t\tmoment t;\n\t\t\treturn t.now();\n\t\t}\n\n\t\ttemplate<typename T>\n\t\tinline auto seconds(const T& val) noexcept -> moment\n\t\t{\n\t\t\tmoment t;\n\t\t\treturn t.set_seconds(val);\n\t\t}\n\n\t\ttemplate<typename T>\n\t\tinline auto milliseconds(const T& val) noexcept -> moment\n\t\t{\n\t\t\tmoment t;\n\t\t\treturn t.set_milliseconds(val);\n\t\t}\n\n\t\ttemplate<typename T>\n\t\tinline auto microseconds(const T& val) noexcept -> moment\n\t\t{\n\t\t\tmoment t;\n\t\t\treturn t.set_microseconds(val);\n\t\t}\n\n\t\ttemplate<typename T>\n\t\tinline auto nanoseconds(const T& val) noexcept -> moment\n\t\t{\n\t\t\tmoment t;\n\t\t\treturn t.set_nanoseconds(val);\n\t\t}\n\n\t\ttemplate<typename T>\n\t\tinline auto ticks(const T& val) noexcept -> moment\n\t\t{\n\t\t\tmoment t;\n\t\t\treturn t.set_ticks(val);\n\t\t}\n\n\t\ttemplate<typename T>\n\t\tinline void micro_sleep_seconds(const T& seconds) noexcept\n\t\t{\n\t\t\tmicro_sleep(static_cast<int64_t>((static_cast<long double>(performance_frequency())) * static_cast<long double>(seconds)));\n\t\t}\n\n\t\ttemplate<typename T>\n\t\tinline void micro_sleep_milliseconds(const T& seconds) noexcept\n\t\t{\n\t\t\tmicro_sleep(static_cast<int64_t>((static_cast<long double>(performance_frequency()) / static_cast<long double>(1000ull)) * static_cast<long double>(seconds)));\n\t\t}\n\n\t\ttemplate<typename T>\n\t\tinline void micro_sleep_microseconds(const T& seconds) noexcept\n\t\t{\n\t\t\tmicro_sleep(\n\t\t\t\tstatic_cast<int64_t>((static_cast<long double>(performance_frequency()) / static_cast<long double>(1000ull * 1000ull)) * static_cast<long double>(seconds)));\n\t\t}\n\n\t\ttemplate<typename T>\n\t\tinline void micro_sleep_ticks(const T& tx) noexcept\n\t\t{\n\t\t\tmicro_sleep(static_cast<int64_t>(tx));\n\t\t}\n\n\t\tinline void micro_sleep(const moment& t) noexcept\n\t\t{\n\t\t\tmicro_sleep(t.as_ticks<int64_t>());\n\t\t}\n\n\t\ttemplate<typename T>\n\t\tinline void sleepseconds(const T& seconds) noexcept\n\t\t{\n\t\t\tsleep(moment().set_seconds(seconds).template as_milliseconds<int64_t>());\n\t\t}\n\n\t\ttemplate<typename T>\n\t\tinline void sleepmilliseconds(const T& seconds) noexcept\n\t\t{\n\t\t\tsleep(moment().set_milliseconds(seconds).template as_milliseconds<int64_t>());\n\t\t}\n\n\t\ttemplate<typename T>\n\t\tinline void sleepmicroseconds(const T& seconds) noexcept\n\t\t{\n\t\t\tsleep(moment().set_microseconds(seconds).template as_milliseconds<int64_t>());\n\t\t}\n\n\t\ttemplate<typename T>\n\t\tinline void sleepticks(const T& tx) noexcept\n\t\t{\n\t\t\tsleep(moment().set_ticks(tx).template as_milliseconds<int64_t>());\n\t\t}\n\n\t\tinline void sleep(const moment& t) noexcept\n\t\t{\n\t\t\tsleep(t.template as_milliseconds<int64_t>());\n\t\t}\n\n\t\tinline void long_clock::update() noexcept\n\t\t{\n\t\t\tconst moment n = now();\n\t\t\tconst moment d = n - last_moment;\n\t\t\tlast_moment\t   = n;\n\t\t\tvalue += d.template as_milliseconds<int64_t>();\n\t\t}\n\t} // namespace time\n} // namespace mu\n\nnamespace mu\n{\n\tenum class messagebox_result : int\n\t{\n\t\tok = 0,\n\t\tcancel,\n\t\tyes,\n\t\tno,\n\t\tquit,\n\t\tnone,\n\t\terror\n\t};\n\n\tenum class messagebox_style : int\n\t{\n\t\tinfo = 0,\n\t\twarning,\n\t\terror,\n\t\tquestion\n\t};\n\n\tenum class messagebox_buttons : int\n\t{\n\t\tok = 0,\n\t\tokcancel,\n\t\tyesno,\n\t\tquit\n\t};\n\n\tnamespace details\n\t{\n\t\ttemplate<typename T>\n\t\tstruct future_helper\n\t\t{\n\t\t\tbool m_state = false;\n\t\t\tT\t m_future;\n\n\t\t\tusing value_type = decltype(m_future.get());\n\n\t\t\tauto is_active() const noexcept -> bool\n\t\t\t{\n\t\t\t\treturn m_state;\n\t\t\t}\n\n\t\t\tauto is_ready() const noexcept -> bool\n\t\t\t{\n\t\t\t\tif (m_state)\n\t\t\t\t{\n\t\t\t\t\treturn future_is_ready(m_future);\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tauto acquire_value() noexcept -> value_type\n\t\t\t{\n\t\t\t\tm_state = false;\n\t\t\t\treturn m_future.get();\n\t\t\t}\n\n\t\t\tauto get_value() noexcept -> std::optional<value_type>\n\t\t\t{\n\t\t\t\tif (is_ready())\n\t\t\t\t{\n\t\t\t\t\treturn acquire_value();\n\t\t\t\t}\n\t\t\t\treturn std::nullopt;\n\t\t\t}\n\t\t};\n\t} // namespace details\n\n\tnamespace details\n\t{\n\t\tauto show_messagebox(const char* message, const char* title, messagebox_style style, messagebox_buttons buttons) noexcept -> std::future<messagebox_result>;\n\t}\n\n\tusing messagebox_future = details::future_helper<decltype(details::show_messagebox(\"\", \"\", messagebox_style(), messagebox_buttons()))>;\n\tinline auto show_messagebox(const char* message, const char* title, messagebox_style style, messagebox_buttons buttons) noexcept -> messagebox_future\n\t{\n\t\treturn {true, details::show_messagebox(message, title, style, buttons)};\n\t}\n\n\tnamespace details\n\t{\n\t\tauto show_file_open_dialog(std::string_view origin, std::string_view filter) noexcept -> optional_future<std::string>;\n\t\tauto show_file_open_multiple_dialog(std::string_view origin, std::string_view filter) noexcept -> optional_future<std::vector<std::string>>;\n\t\tauto show_file_save_dialog(std::string_view origin, std::string_view filter) noexcept -> optional_future<std::string>;\n\t\tauto show_path_dialog(std::string_view origin, std::string_view filter) noexcept -> optional_future<std::string>;\n\t} // namespace details\n\n\tusing file_open_dialog_future = details::future_helper<decltype(details::show_file_open_dialog(std::string_view(), std::string_view()))>;\n\tinline auto show_file_open_dialog(std::string_view origin, std::string_view filter) noexcept -> file_open_dialog_future\n\t{\n\t\treturn {true, details::show_file_open_dialog(origin, filter)};\n\t}\n\n\tusing file_open_multiple_dialog_future = details::future_helper<decltype(details::show_file_open_multiple_dialog(std::string_view(), std::string_view()))>;\n\tinline auto show_file_open_multiple_dialog(std::string_view origin, std::string_view filter) noexcept -> file_open_multiple_dialog_future\n\t{\n\t\treturn {true, details::show_file_open_multiple_dialog(origin, filter)};\n\t}\n\n\tusing file_save_dialog_future = details::future_helper<decltype(details::show_file_save_dialog(std::string_view(), std::string_view()))>;\n\tinline auto show_file_save_dialog(std::string_view origin, std::string_view filter) noexcept -> file_save_dialog_future\n\t{\n\t\treturn {true, details::show_file_save_dialog(origin, filter)};\n\t}\n\n\tusing path_dialog_future = details::future_helper<decltype(details::show_path_dialog(std::string_view(), std::string_view()))>;\n\tinline auto show_path_dialog(std::string_view origin, std::string_view filter) noexcept -> path_dialog_future\n\t{\n\t\treturn {true, details::show_path_dialog(origin, filter)};\n\t}\n} // namespace mu\n\nnamespace backward\n{\n\tclass StackTrace;\n}\n\nnamespace mu\n{\n\tnamespace debug\n\t{\n\t\tnamespace details\n\t\t{\n\t\t\tstruct logger_interface\n\t\t\t{\n\t\t\t\tlogger_interface()\t\t\t= default;\n\t\t\t\tvirtual ~logger_interface() = default;\n\n\t\t\t\tvirtual auto stdout_logger() noexcept -> std::shared_ptr<spdlog::logger> = 0;\n\t\t\t\tvirtual auto stderr_logger() noexcept -> std::shared_ptr<spdlog::logger> = 0;\n\t\t\t};\n\t\t} // namespace details\n\n\t\tusing logger = mu::exported_singleton<mu::virtual_singleton<details::logger_interface>>;\n\n\t\tvoid log_stack_trace(spdlog::logger& l, spdlog::level::level_enum lvl, unsigned int level_skip) noexcept;\n\n\t} // namespace debug\n\n\tstatic inline auto error_handlers = std::make_tuple(\n\t\t[](runtime_error::not_specified x, leaf::e_source_location sl)\n\t\t{\n\t\t\tdebug::logger()->stderr_logger()->log(spdlog::level::err, \"{0} :: {1} -> {2} : runtime_error :: not_specified\", sl.line, sl.file, sl.function);\n\t\t},\n\t\t[](common_error x, leaf::e_source_location sl)\n\t\t{\n\t\t\tdebug::logger()->stderr_logger()->log(spdlog::level::err, \"{0} :: {1} -> {2} : common_error\", sl.line, sl.file, sl.function);\n\t\t},\n\t\t[]\n\t\t{\n\t\t\tdebug::logger()->stderr_logger()->log(spdlog::level::err, \"???\");\n\t\t});\n\n\ttemplate<class TryBlock>\n\tconstexpr inline auto try_handle(TryBlock&& try_block) -> typename std::decay<decltype(std::declval<TryBlock>()().value())>::type\n\t{\n\t\treturn leaf::try_handle_all(try_block, error_handlers);\n\t}\n\n} // namespace mu\n\nnamespace mu\n{\n\ttemplate<typename T_CONTAINER, typename T_FUNC, typename T_FUNC_RET>\n\tauto for_some_return(T_CONTAINER& container, T_FUNC func, T_FUNC_RET&& true_return_value, T_FUNC_RET&& false_return_value) noexcept -> T_FUNC_RET\n\t{\n\t\tfor (auto& itor : container)\n\t\t{\n\t\t\tif (func(itor))\n\t\t\t{\n\t\t\t\treturn true_return_value;\n\t\t\t}\n\t\t}\n\n\t\treturn false_return_value;\n\t}\n\n\ttemplate<typename T_CONTAINER, typename T_FUNC, typename T_FUNC_RET>\n\tauto for_some_optional_return(T_CONTAINER& container, T_FUNC func, T_FUNC_RET&& false_return_value) noexcept -> T_FUNC_RET\n\t{\n\t\tfor (auto& itor : container)\n\t\t{\n\t\t\tif (auto res = func(itor))\n\t\t\t{\n\t\t\t\treturn *res;\n\t\t\t}\n\t\t}\n\n\t\treturn false_return_value;\n\t}\n} // namespace mu\n\nnamespace mu\n{\n\tvoid enable_dpi_awareness() noexcept;\n\tauto get_dpi_scale_for_monitor(void* monitor) noexcept -> float;\n\tauto get_dpi_scale_for_hwnd(void* hwnd) noexcept -> float;\n} // namespace mu\n\nnamespace mu\n{\n\t\n} // namespace mu", "meta": {"hexsha": "63d789e3d7c524dca2cd775637afd4bb6b920fd9", "size": 44528, "ext": "h", "lang": "C", "max_stars_repo_path": "include/mu_stdlib.h", "max_stars_repo_name": "loopunit/mu_stdlib.cpmpckg", "max_stars_repo_head_hexsha": "0a8e1585dcf7b4d2f726c1436a72d73aec8d5ad3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-14T05:50:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-14T05:50:23.000Z", "max_issues_repo_path": "include/mu_stdlib.h", "max_issues_repo_name": "loopunit/mu_stdlib.cpmpckg", "max_issues_repo_head_hexsha": "0a8e1585dcf7b4d2f726c1436a72d73aec8d5ad3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/mu_stdlib.h", "max_forks_repo_name": "loopunit/mu_stdlib.cpmpckg", "max_forks_repo_head_hexsha": "0a8e1585dcf7b4d2f726c1436a72d73aec8d5ad3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6485596708, "max_line_length": 180, "alphanum_fraction": 0.4638429752, "num_tokens": 8035, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.076960839930213, "lm_q2_score": 0.01798620700114993, "lm_q1q2_score": 0.0013842335979671761}}
{"text": "/* block/gsl_block_ushort.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#ifndef __GSL_BLOCK_USHORT_H__\n#define __GSL_BLOCK_USHORT_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_errno.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\nstruct gsl_block_ushort_struct\n{\n  size_t size;\n  unsigned short *data;\n};\n\ntypedef struct gsl_block_ushort_struct gsl_block_ushort;\n\ngsl_block_ushort *gsl_block_ushort_alloc (const size_t n);\ngsl_block_ushort *gsl_block_ushort_calloc (const size_t n);\nvoid gsl_block_ushort_free (gsl_block_ushort * b);\n\nint gsl_block_ushort_fread (FILE * stream, gsl_block_ushort * b);\nint gsl_block_ushort_fwrite (FILE * stream, const gsl_block_ushort * b);\nint gsl_block_ushort_fscanf (FILE * stream, gsl_block_ushort * b);\nint gsl_block_ushort_fprintf (FILE * stream, const gsl_block_ushort * b, const char *format);\n\nint gsl_block_ushort_raw_fread (FILE * stream, unsigned short * b, const size_t n, const size_t stride);\nint gsl_block_ushort_raw_fwrite (FILE * stream, const unsigned short * b, const size_t n, const size_t stride);\nint gsl_block_ushort_raw_fscanf (FILE * stream, unsigned short * b, const size_t n, const size_t stride);\nint gsl_block_ushort_raw_fprintf (FILE * stream, const unsigned short * b, const size_t n, const size_t stride, const char *format);\n\nsize_t gsl_block_ushort_size (const gsl_block_ushort * b);\nunsigned short * gsl_block_ushort_data (const gsl_block_ushort * b);\n\n__END_DECLS\n\n#endif /* __GSL_BLOCK_USHORT_H__ */\n", "meta": {"hexsha": "f06f320d3e73fb7783926974159630adc10c1861", "size": 2381, "ext": "h", "lang": "C", "max_stars_repo_path": "gsl_subset/gsl/gsl_block_ushort.h", "max_stars_repo_name": "pvnuffel/test_repos", "max_stars_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2015-04-29T05:13:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T02:07:41.000Z", "max_issues_repo_path": "gsl_subset/gsl/gsl_block_ushort.h", "max_issues_repo_name": "pvnuffel/test_repos", "max_issues_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-11-07T05:42:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-20T16:32:02.000Z", "max_forks_repo_path": "gsl_subset/gsl/gsl_block_ushort.h", "max_forks_repo_name": "pvnuffel/test_repos", "max_forks_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-04-29T20:31:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-10T03:09:53.000Z", "avg_line_length": 36.0757575758, "max_line_length": 132, "alphanum_fraction": 0.7727845443, "num_tokens": 624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06560484293979194, "lm_q2_score": 0.020964243111946227, "lm_q1q2_score": 0.0013753558767108471}}
{"text": "/*\n  Copyright [2017-2019] [IBM Corporation]\n  Licensed under the Apache License, Version 2.0 (the \"License\");\n  you may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n  http://www.apache.org/licenses/LICENSE-2.0\n  Unless required by applicable law or agreed to in writing, software\n  distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions and\n  limitations under the License.\n*/\n#ifndef __MCAS_CLIENT_HANDLER_H__\n#define __MCAS_CLIENT_HANDLER_H__\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-parameter\"\n#pragma GCC diagnostic ignored \"-Weffc++\"\n\n#include \"fabric_transport.h\"\n#include \"mcas_client_config.h\"\n#include \"protocol.h\"\n#include \"protocol_ostream.h\"\n\n#include <api/fabric_itf.h>\n#include <api/mcas_itf.h>\n#include <common/exceptions.h>\n#include <common/utils.h>\n#include <common/byte_buffer.h>\n#include <common/string_view.h>\n#include <gsl/pointers>\n#include <sys/mman.h>\n#include <sys/uio.h>\n#include <unistd.h>\n#include <gnutls/gnutls.h>\n#include <gnutls/x509.h>\n#include <gnutls/crypto.h>\n\n#include <boost/numeric/conversion/cast.hpp>\n#include <map>\n#include <set>\n#include <tuple>\n\n/* Enable this to introduce locks to prevent re-entry by multiple\n   threads.  The client is not re-entrant because of the state machine\n   and multi-packet operations\n*/\n#define THREAD_SAFE_CLIENT\n\n#define CAFILE \"/etc/ssl/certs/ca-bundle.trust.crt\"\n\n#ifdef THREAD_SAFE_CLIENT\n#define API_LOCK() std::lock_guard<std::mutex> g(_api_lock);\n#else\n#define API_LOCK()\n#endif\n\nnamespace mcas\n{\n\nnamespace client\n{\n\nstruct TLS_transport\n{\n  static unsigned debug_level();\n  static ssize_t gnutls_pull_func(gnutls_transport_ptr_t, void*, size_t);\n  static ssize_t gnutls_vec_push_func(gnutls_transport_ptr_t, const giovec_t * , int );\n  static int gnutls_pull_timeout_func(gnutls_transport_ptr_t, unsigned int);\n};\n\n\n\nstruct async_buffer_set_t;\nstruct iob_free;\n\nstatic const char *env_scbe = ::getenv(\"SHORT_CIRCUIT_BACKEND\");\n\n/* Adaptor point for other transports */\nusing Connection_base = mcas::client::Fabric_transport;\n\n/**\n * Client side connection handler\n *\n */\nclass Connection_handler : public Connection_base {\n  using iob_ptr        = std::unique_ptr<client::Fabric_transport::buffer_t, iob_free>;\n  using locate_element = protocol::Message_IO_response::locate_element;\n\npublic:\n  friend struct TLS_transport;\n\n  using memory_region_t = typename Transport::memory_region_t;\n  template <typename T>\n    using basic_string_view = common::basic_string_view<T>;\n  using byte = common::byte;\n\n  /**\n   * Constructor\n   *\n   * @param debug_level\n   * @param connection\n   * @param patience Time to wait (in seconds) for single fabric post to complete\n   * @param other Additional configuration string\n   *\n   * @return\n   */\n  Connection_handler(const unsigned debug_level,\n                     Connection_base::Transport *connection,\n                     const unsigned patience,\n                     const std::string other);\n\n  ~Connection_handler();\n\nprivate:\n  enum State {\n              INITIALIZE,\n              HANDSHAKE_SEND,\n              HANDSHAKE_GET_RESPONSE,\n              SHUTDOWN,\n              STOPPED,\n              READY,\n  };\n\n  State _state = State::INITIALIZE;\n\n  template <typename MT>\n    status_t invoke_ado_common(\n      const iob_ptr & iobs\n      , const MT *msg\n      , std::vector<component::IMCAS::ADO_response>& out_response\n      , unsigned int flags\n    );\n\npublic:\n  using pool_t = uint64_t;\n\n  void bootstrap()\n  {\n    set_state(INITIALIZE);\n    while (tick() > 0)\n      ;\n  }\n\n  void shutdown()\n  {\n    set_state(SHUTDOWN);\n    while (tick() > 0) sleep(1);\n  }\n\n  pool_t open_pool(const std::string name,\n                   const unsigned int flags,\n                   const addr_t base);\n\n  pool_t create_pool(const std::string  name,\n                     const size_t       size,\n                     const unsigned int flags,\n                     const uint64_t     expected_obj_count,\n                     const addr_t       base);\n\n  status_t close_pool(const pool_t pool);\n\n  status_t delete_pool(const std::string &name);\n\n  status_t delete_pool(const pool_t pool);\n\n  status_t configure_pool(const component::IKVStore::pool_t pool, const std::string &json);\n\n  status_t put(const pool_t       pool,\n               const std::string  key,\n               const void *       value,\n               const size_t       value_len,\n               const unsigned int flags);\n\n  status_t put(const pool_t       pool,\n               const void *       key,\n               const size_t       key_len,\n               const void *       value,\n               const size_t       value_len,\n               const unsigned int flags);\n\n  status_t put_direct(pool_t                               pool,\n                      const void *                         key,\n                      size_t                               key_len,\n                      const void *                         value,\n                      size_t                               value_len,\n                      component::Registrar_memory_direct * rmd,\n                      component::IKVStore::memory_handle_t handle,\n                      unsigned int                         flags);\n\n  status_t async_put(const pool_t                      pool,\n                     const void *                      key,\n                     const size_t                      key_len,\n                     const void *                      value,\n                     size_t                            value_len,\n                     component::IMCAS::async_handle_t &out_handle,\n                     unsigned int                      flags);\n\n  status_t async_put_direct(const component::IMCAS::pool_t       pool,\n                            const void *                         key,\n                            size_t                               key_len,\n                            const void *                         value,\n                            size_t                               value_len,\n                            component::IMCAS::async_handle_t &   out_handle,\n                            component::Registrar_memory_direct * rmd,\n                            component::IKVStore::memory_handle_t handle = component::IMCAS::MEMORY_HANDLE_NONE,\n                            unsigned int                         flags  = component::IMCAS::FLAGS_NONE);\n\n  status_t async_get_direct(const component::IMCAS::pool_t       pool,\n                            const void *                         key,\n                            size_t                               key_len,\n                            void *                               value,\n                            size_t &                             value_len,\n                            component::IMCAS::async_handle_t &   out_handle,\n                            component::Registrar_memory_direct * rmd,\n                            component::IKVStore::memory_handle_t handle = component::IMCAS::MEMORY_HANDLE_NONE,\n                            unsigned int                         flags  = component::IMCAS::FLAGS_NONE);\n\n  status_t check_async_completion(component::IMCAS::async_handle_t &handle);\n\n  status_t get(const pool_t pool, const std::string &key, std::string &value);\n\n  status_t get(const pool_t pool, const std::string &key, void *&value, size_t &value_len);\n\n  status_t get_direct(const pool_t                         pool,\n                      const void *                         key,\n                      size_t                               key_len,\n                      void *                               value,\n                      size_t &                             out_value_len,\n                      component::Registrar_memory_direct * rmd,\n                      component::IKVStore::memory_handle_t handle = component::IKVStore::HANDLE_NONE);\n\n  status_t get_direct_offset(pool_t                              pool,\n                             std::size_t                         offset,\n                             std::size_t &                       length,\n                             void *                              buffer,\n                             component::Registrar_memory_direct *rmd,\n                             component::IMCAS::memory_handle_t   handle);\n\n  status_t async_get_direct_offset(pool_t                              pool,\n                                   std::size_t                         offset,\n                                   std::size_t &                       length,\n                                   void *                              buffer,\n                                   component::IMCAS::async_handle_t &  out_handle,\n                                   component::Registrar_memory_direct *rmd,\n                                   component::IMCAS::memory_handle_t   handle);\n\n  status_t put_direct_offset(pool_t                              pool,\n                             std::size_t                         offset,\n                             std::size_t &                       length,\n                             const void *                        buffer,\n                             component::Registrar_memory_direct *rmd,\n                             component::IMCAS::memory_handle_t   handle);\n\n  status_t async_put_direct_offset(pool_t                              pool,\n                                   std::size_t                         offset,\n                                   std::size_t &                       length,\n                                   const void *                        buffer,\n                                   component::IMCAS::async_handle_t &  out_handle,\n                                   component::Registrar_memory_direct *rmd,\n                                   component::IMCAS::memory_handle_t   handle);\n\n  status_t erase(const pool_t pool, const std::string &key);\n\n  status_t async_erase(const component::IMCAS::pool_t    pool,\n                       const std::string &               key,\n                       component::IMCAS::async_handle_t &out_handle);\n\n  uint64_t key_hash(const void *key, const size_t key_len);\n\n  uint64_t auth_id() const\n  {\n    /* temporary */\n    auto     env = getenv(\"MCAS_AUTH_ID\");\n    uint64_t auth_id;\n    if (env) {\n      auto id = std::strtoll(env, nullptr, 10);\n      auth_id = boost::numeric_cast<uint64_t>(id);\n    }\n    else {\n      auth_id = boost::numeric_cast<uint64_t>(getuid());\n    }\n\n    return auth_id;\n  }\n\n  size_t count(const pool_t pool);\n\n  status_t get_attribute(const component::IKVStore::pool_t    pool,\n                         const component::IKVStore::Attribute attr,\n                         std::vector<uint64_t> &              out_attr,\n                         const std::string *                  key);\n\n  status_t get_statistics(component::IMCAS::Shard_stats &out_stats);\n\n  status_t find(const component::IKVStore::pool_t pool,\n                const std::string &               key_expression,\n                const offset_t                    offset,\n                offset_t &                        out_matched_offset,\n                std::string &                     out_matched_key);\n\n  status_t invoke_ado(const component::IMCAS::pool_t               pool,\n                      basic_string_view<byte>                      key,\n                      basic_string_view<byte>                      request,\n                      const unsigned int                           flags,\n                      std::vector<component::IMCAS::ADO_response> &out_response,\n                      const size_t                                 value_size);\n\n  status_t invoke_ado_async(const component::IMCAS::pool_t               pool,\n                            basic_string_view<byte>                      key,\n                            basic_string_view<byte>                      request,\n                            const component::IMCAS::ado_flags_t          flags,\n                            std::vector<component::IMCAS::ADO_response> &out_response,\n                            component::IMCAS::async_handle_t &           out_async_handle,\n                            const size_t                                 value_size);\n\n  status_t invoke_put_ado(const component::IMCAS::pool_t               pool,\n                          basic_string_view<byte>                      key,\n                          basic_string_view<byte>                      request,\n                          basic_string_view<byte>                      value,\n                          size_t                                       root_len,\n                          const unsigned int                           flags,\n                          std::vector<component::IMCAS::ADO_response> &out_response);\n\n  status_t invoke_put_ado_async(const component::IMCAS::pool_t                  pool,\n                                const basic_string_view<byte>                   key,\n                                const basic_string_view<byte>                   request,\n                                const basic_string_view<byte>                   value,\n                                const size_t                                    root_len,\n                                const component::IMCAS::ado_flags_t             flags,\n                                std::vector<component::IMCAS::ADO_response>&    out_response,\n                                component::IMCAS::async_handle_t&               out_async_handle);\n\n  bool check_message_size(size_t size) const { return size > _max_message_size; }\n\n  status_t receive_and_process_ado_response(\n    const iob_ptr & iobr\n    , std::vector<component::IMCAS::ADO_response> & out_response\n  );\n\nprivate:\n  /**\n   * FSM tick call\n   *\n   */\n  int tick();\n\n  /**\n   * FSM state change\n   *\n   * @param s State to change to\n   */\n  inline void set_state(State s)\n  {\n    if (2 < debug_level()) {\n      static const std::map<State, const char *> m{\n                                                   {INITIALIZE, \"INITIALIZE\"},\n                                                   {HANDSHAKE_SEND, \"HANDSHAKE_SEND\"},\n                                                   {HANDSHAKE_GET_RESPONSE, \"HANDSHAKE_GET_RESPONSE\"},\n                                                   {SHUTDOWN, \"SHUTDOWN\"},\n                                                   {STOPPED, \"STOPPED\"},\n                                                   {READY, \"READY\"},\n      };\n      PLOG(\"Client state %s -> %s\", m.find(_state)->second, m.find(s)->second);\n    }\n    _state = s;\n  } /* we could add transition checking later */\n\n  void start_tls();\n\n  template <typename MT>\n  void msg_send_log(const MT *m, const void *context, const char *desc) { msg_send_log(1, m, context, desc); }\n\n  template <typename MT>\n  void msg_send_log(const unsigned level, const MT *msg, const void *context, const char *desc)\n  {\n    msg_log(level, msg, context, desc, \"SEND\");\n  }\n\n  template <typename MT>\n  void msg_log(const unsigned level_, const MT *msg_, const void *context_, const char *desc_, const char *direction_)\n  {\n    if ( level_ < debug_level() )\n      {\n        std::ostringstream m;\n        m << *msg_;\n        PLOG(\"%s (%p) (%s) %s\", direction_, context_, desc_, m.str().c_str());\n      }\n  }\n\n  template <typename MT>\n  void msg_recv_log(const MT *m, const void *context, const char *desc) { msg_recv_log(1, m, context, desc); }\n\n  template <typename MT>\n  void msg_recv_log(const unsigned level, const MT *msg, const void *context, const char *desc)\n  {\n    msg_log(level, msg, context, desc, \"RECV\");\n  }\n\npublic:\n\n  template <typename MT>\n  gsl::not_null<const MT *>msg_recv(const buffer_t *iob, const char *desc)\n  {\n    /*\n     * First, cast the response buffer to Message (checking version).\n     * Second, cast the Message to a specific message type (checking message type).\n     */\n    const auto *const msg = mcas::protocol::message_cast(iob->base());\n    const auto *const response_msg = msg->ptr_cast<MT>();\n    msg_recv_log(response_msg, iob, desc);\n    return response_msg;\n  }\n\n  template <typename MT>\n  void sync_inject_send(buffer_t *iob, const MT *msg, std::size_t size, const char *desc)\n  {\n    msg_send_log(msg, iob, desc);\n    Connection_base::sync_inject_send(iob, size);\n  }\n\n  template <typename MT>\n  void sync_inject_send(buffer_t *iob, const MT *msg, const char *desc)\n  {\n    sync_inject_send(iob, msg, msg->msg_len(), desc);\n  }\n\n  template <typename MT>\n  void sync_send(buffer_t *iob, const MT *msg, const char *desc)\n  {\n    msg_send_log(msg, iob, desc);\n    Connection_base::sync_send(iob);\n  }\n\n  void sync_inject_send(buffer_t *iob, std::size_t size)\n  {\n    Connection_base::sync_inject_send(iob, size);\n  }\n\n\nprivate:\n  /* unused */\n#if 0\n  void post_send(buffer_t *iob, const protocol::Message_IO_request *msg, buffer_external *iob_extra, const char *desc)\n  {\n    msg_send_log(msg, iob, desc);\n    Connection_base::post_send(iob, iob_extra);\n  }\n#endif\n  template <typename MT>\n  void post_send(buffer_t *iob, const MT *msg, const char *desc)\n  {\n    msg_send_log(2, msg, iob, desc);\n    Connection_base::post_send(iob);\n  }\n\n  template <typename MT>\n  void post_send(const ::iovec *first, const ::iovec *last, void **descriptors, void *context, const MT *msg, const char *desc)\n  {\n    msg_send_log(msg, context, desc);\n    Connection_base::post_send(first, last, descriptors, context);\n  }\n\n  /**\n   * Put used when the value exceeds the size of the basic\n   * IO buffer (e.g., 2MB).  This version of put will perform\n   * a two-stage exchange, advance notice and then value\n   *\n   * @param pool Pool identifier\n   * @param key Key\n   * @param key_len Key length\n   * @param value_len Value length\n   * @param flags ignored?\n   *\n   * @return\n   */\n  std::tuple<uint64_t, uint64_t> put_locate(const pool_t   pool,\n                                            const void *   key,\n                                            const size_t   key_len,\n                                            const size_t   value_len,\n                                            const unsigned flags);\n\n  component::IMCAS::async_handle_t put_locate_async(pool_t                              pool,\n                                                    const void *                        key,\n                                                    size_t                              key_len,\n                                                    const void *                        value,\n                                                    size_t                              value_len,\n                                                    component::Registrar_memory_direct *rmd,\n                                                    void *                              desc,\n                                                    unsigned                            flags);\n\n  std::tuple<uint64_t, uint64_t, std::size_t> get_locate(const pool_t   pool,\n                                                         const void *   key,\n                                                         const size_t   key_len,\n                                                         const unsigned flags);\n\n  component::IMCAS::async_handle_t get_locate_async(pool_t                              pool,\n                                                    const void *                        key,\n                                                    size_t                              key_len,\n                                                    void *                              value,\n                                                    size_t &                            value_len,\n                                                    component::Registrar_memory_direct *rmd,\n                                                    void *                              desc,\n                                                    unsigned                            flags);\npublic:\n  iob_ptr make_iob_ptr(buffer_t::completion_t);\n  iob_ptr make_iob_ptr_recv();\n  iob_ptr make_iob_ptr_send();\n  iob_ptr make_iob_ptr_write();\n  iob_ptr make_iob_ptr_read();\n\nprivate:\n  static void send_complete(void *, buffer_t *iob);\n  static void recv_complete(void *, buffer_t *iob);\n  static void write_complete(void *, buffer_t *iob);\n  static void read_complete(void *, buffer_t *iob);\n\n  std::tuple<uint64_t, std::vector<locate_element>> locate(pool_t pool, std::size_t offset, std::size_t size);\n\n  component::IMCAS::async_handle_t get_direct_offset_async(pool_t                              pool,\n                                                           std::size_t                         offset,\n                                                           void *                              buffer,\n                                                           std::size_t &                       length,\n                                                           component::Registrar_memory_direct *rmd,\n                                                           void *                              desc);\n\n  component::IMCAS::async_handle_t put_direct_offset_async(pool_t                              pool,\n                                                           std::size_t                         offset,\n                                                           const void *                        buffer,\n                                                           std::size_t &                       length,\n                                                           component::Registrar_memory_direct *rmd,\n                                                           void *                              desc);\n\nprivate:\n#ifdef THREAD_SAFE_CLIENT\n  std::mutex _api_lock;\n#endif\n\n  bool     _exit;\n  uint64_t _request_id;\n\npublic: /* for async \"move_along\" processing */\n  uint64_t request_id() { return ++_request_id; }\n\nprivate:\n  size_t _max_message_size;\n  size_t _max_inject_size;\n\n  struct options_s {\n    bool short_circuit_backend;\n    unsigned tls   : 1;\n    unsigned hmac : 1;\n\n    options_s()\n      : short_circuit_backend(env_scbe && env_scbe[0] == '1'), tls(0), hmac(0)\n    {}\n  };\n\n  options_s _options;\n\n  gnutls_certificate_credentials_t _xcred;\n  gnutls_priority_t                _priority;\n  gnutls_session_t                 _session;\n  common::Byte_buffer              _tls_buffer;\n\n};\n\n}  // namespace client\n}  // namespace mcas\n\n#pragma GCC diagnostic pop\n#endif\n", "meta": {"hexsha": "d61e8b9c533109c8048140dd927848cdfe973f8e", "size": 22702, "ext": "h", "lang": "C", "max_stars_repo_path": "src/components/client/mcas-client/src/connection.h", "max_stars_repo_name": "moshik1/mcas", "max_stars_repo_head_hexsha": "a6af06bc278993fb3ffe780f230d2396b2287c26", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/components/client/mcas-client/src/connection.h", "max_issues_repo_name": "moshik1/mcas", "max_issues_repo_head_hexsha": "a6af06bc278993fb3ffe780f230d2396b2287c26", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/components/client/mcas-client/src/connection.h", "max_forks_repo_name": "moshik1/mcas", "max_forks_repo_head_hexsha": "a6af06bc278993fb3ffe780f230d2396b2287c26", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.6195462478, "max_line_length": 127, "alphanum_fraction": 0.4973570611, "num_tokens": 4285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06656919082235042, "lm_q2_score": 0.020645930927528856, "lm_q1q2_score": 0.0013743829156197347}}
{"text": "/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */\n/*\n *     Copyright 2017 Couchbase, Inc.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n */\n#pragma once\n\n#include <mcbp/protocol/opcode.h>\n#include <mcbp/protocol/request.h>\n#include <mcbp/protocol/response.h>\n#include <mcbp/protocol/status.h>\n\n#include <gsl/gsl>\n\nnamespace cb {\nnamespace mcbp {\n\n/**\n * FrameBuilder allows you to build up a request / response frame in\n * a provided memory area. It provides helper methods which makes sure\n * that the fields is formatted in the correct byte order etc.\n */\ntemplate <typename T>\nclass FrameBuilder {\npublic:\n    FrameBuilder(cb::byte_buffer backing) : buffer(backing) {\n        checkSize(sizeof(T));\n        std::fill(backing.begin(), backing.begin() + sizeof(T), 0);\n    }\n\n    T* getFrame() {\n        return reinterpret_cast<T*>(buffer.data());\n    }\n\n    void setMagic(Magic magic) {\n        getFrame()->setMagic(magic);\n    }\n\n    void setOpcode(ClientOpcode opcode) {\n        getFrame()->setOpcode(opcode);\n    }\n\n    void setOpcode(ServerOpcode opcode) {\n        getFrame()->setOpcode(opcode);\n    }\n\n    void setDatatype(Datatype datatype) {\n        getFrame()->setDatatype(datatype);\n    }\n\n    void setVBucket(Vbid value) {\n        getFrame()->setVBucket(value);\n    }\n\n    void setOpaque(uint32_t opaque) {\n        getFrame()->setOpaque(opaque);\n    }\n\n    void setCas(uint64_t val) {\n        getFrame()->setCas(val);\n    }\n\n    /**\n     * Insert the provided extras in the appropriate location (right after\n     * the header) and updates the extlen and bodylen field.\n     *\n     * @param extras the extra field to insert\n     */\n    void setExtras(cb::const_byte_buffer extras) {\n        auto* req = getFrame();\n\n        // can we fit the extras?\n        checkSize(req->getExtlen(), extras.size());\n\n        // Start by moving key and body to where it belongs\n        const auto old_body_size = req->getBodylen() - req->getExtlen();\n        auto* start = buffer.data() + sizeof(*req);\n        uint8_t* old_start = start + req->getExtlen();\n        uint8_t* new_start = start + extras.size();\n        memmove(new_start, old_start, old_body_size);\n\n        // Insert the new extras:\n        std::copy(extras.begin(), extras.end(), start);\n        req->setExtlen(uint8_t(extras.size()));\n        req->setBodylen(gsl::narrow<uint32_t>(old_body_size + extras.size()));\n    }\n\n    /**\n     * Insert the provided key in the appropriate location (right after\n     * the extras field) and updates the keylen and bodylen field.\n     *\n     * @param key the key field to insert\n     */\n    void setKey(cb::const_byte_buffer key) {\n        auto* req = getFrame();\n        checkSize(req->getKeylen(), key.size());\n\n        // Start by moving the body to where it belongs\n        const auto old_body_size =\n                req->getBodylen() - req->getKeylen() - req->getExtlen();\n        auto* start = buffer.data() + sizeof(*req) + req->getExtlen();\n        uint8_t* old_start = start + req->getKeylen();\n        uint8_t* new_start = start + key.size();\n        memmove(new_start, old_start, old_body_size);\n\n        // Insert the new key:\n        std::copy(key.begin(), key.end(), start);\n        req->setKeylen(uint16_t(key.size()));\n        req->setBodylen(gsl::narrow<uint32_t>(old_body_size + req->getExtlen() +\n                                              key.size()));\n    }\n\n    /**\n     * Insert the provided value in the appropriate location (right after\n     * the key field) and update the bodylen field.\n     *\n     * @param value the value to insert into the body\n     */\n    void setValue(cb::const_byte_buffer value) {\n        auto* req = getFrame();\n\n        const auto old_size =\n                req->getBodylen() - req->getKeylen() - req->getExtlen();\n        checkSize(old_size, value.size());\n\n        auto* start = buffer.data() + sizeof(*req) + req->getExtlen() +\n                      req->getKeylen();\n        std::copy(value.begin(), value.end(), start);\n        req->setBodylen(gsl::narrow<uint32_t>(value.size() + req->getKeylen() +\n                                              req->getExtlen()));\n    }\n\n    /**\n     * Try to validate the underlying packet\n     */\n    void validate() {\n        getFrame()->isValid();\n    }\n\nprotected:\n    /**\n     * check that the requested size fits into the buffer\n     *\n     * @param size The total requested size (including header)\n     */\n    void checkSize(size_t size) {\n        if (size > buffer.size()) {\n            throw std::logic_error(\n                    \"FrameBuilder::checkSize: too big to fit in buffer\");\n        }\n    }\n\n    /**\n     * check if there is room in the buffer to replace the field with\n     * one with a different size\n     *\n     * @param oldfield\n     * @param newfield\n     */\n    void checkSize(size_t oldfield, size_t newfield) {\n        checkSize(sizeof(T) + getFrame()->getBodylen() - oldfield + newfield);\n    }\n\n    cb::byte_buffer buffer;\n};\n\n/**\n * Specialized class to build a Request\n */\nclass RequestBuilder : public FrameBuilder<Request> {\npublic:\n    RequestBuilder(cb::byte_buffer backing) : FrameBuilder<Request>(backing) {\n    }\n    void setVbucket(Vbid vbucket) {\n        getFrame()->setVBucket(vbucket);\n    }\n};\n\n/**\n * Specialized class to build a response\n */\nclass ResponseBuilder : public FrameBuilder<Response> {\npublic:\n    ResponseBuilder(cb::byte_buffer backing) : FrameBuilder<Response>(backing) {\n    }\n    void setStatus(Status status) {\n        getFrame()->setStatus(status);\n    }\n};\n\n} // namespace mcbp\n} // namespace cb\n", "meta": {"hexsha": "b0485ef0ea4119f4052b71d541de7263e1ef172d", "size": 6119, "ext": "h", "lang": "C", "max_stars_repo_path": "include/mcbp/protocol/framebuilder.h", "max_stars_repo_name": "t3rm1n4l/kv_engine", "max_stars_repo_head_hexsha": "24d4546220f3181678d7eadedc68b4ea088d3538", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/mcbp/protocol/framebuilder.h", "max_issues_repo_name": "t3rm1n4l/kv_engine", "max_issues_repo_head_hexsha": "24d4546220f3181678d7eadedc68b4ea088d3538", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/mcbp/protocol/framebuilder.h", "max_forks_repo_name": "t3rm1n4l/kv_engine", "max_forks_repo_head_hexsha": "24d4546220f3181678d7eadedc68b4ea088d3538", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9950980392, "max_line_length": 80, "alphanum_fraction": 0.6117012584, "num_tokens": 1457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06560483563216184, "lm_q2_score": 0.02064592836650742, "lm_q1q2_score": 0.0013544727369581067}}
{"text": "#ifndef __GSL_BLOCK_H__\n#define __GSL_BLOCK_H__\n\n#include <gsl/block/gsl_block_double.h>\n\n#endif /* __GSL_BLOCK_H__ */\n", "meta": {"hexsha": "b1e1e2ab1f7a655df9ada523c9bfd6d7ad3075c9", "size": 119, "ext": "h", "lang": "C", "max_stars_repo_path": "Cartwheel/cartwheel-3d/gsl/block/gsl_block.h", "max_stars_repo_name": "MontyThibault/centre-of-mass-awareness", "max_stars_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Cartwheel/cartwheel-3d/gsl/block/gsl_block.h", "max_issues_repo_name": "MontyThibault/centre-of-mass-awareness", "max_issues_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cartwheel/cartwheel-3d/gsl/block/gsl_block.h", "max_forks_repo_name": "MontyThibault/centre-of-mass-awareness", "max_forks_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.0, "max_line_length": 39, "alphanum_fraction": 0.7899159664, "num_tokens": 34, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06656919082235042, "lm_q2_score": 0.02033235360237229, "lm_q1q2_score": 0.001353508326823825}}
{"text": "#pragma once\n\n#include <gsl/gsl>\n\n#include <mutex>\n#include <condition_variable>\n\n#include <arcana/threading/affinity.h>\n\nnamespace Babylon\n{\n    class SafeTimespanGuarantor\n    {\n    public:\n        SafeTimespanGuarantor();\n\n        void BeginSafeTimespan();\n        void EndSafeTimespan();\n\n        using SafetyGuarantee = gsl::final_action<std::function<void()>>;\n        SafetyGuarantee GetSafetyGuarantee();\n\n    private:\n        arcana::affinity m_affinity{};\n        uint32_t m_count{};\n        std::mutex m_mutex{};\n        std::unique_lock<std::mutex> m_lock{};\n        std::condition_variable m_condition{};\n    };\n}\n", "meta": {"hexsha": "8db71f844291454019e93e01aa338fecb86ed997", "size": 627, "ext": "h", "lang": "C", "max_stars_repo_path": "Core/Graphics/Source/SafeTimespanGuarantor.h", "max_stars_repo_name": "chiamaka-123/BabylonNative", "max_stars_repo_head_hexsha": "7f1f9fd23bf649c9c8a1260f2b93752145b0c024", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 474.0, "max_stars_repo_stars_event_min_datetime": "2019-05-29T09:41:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:09:35.000Z", "max_issues_repo_path": "Core/Graphics/Source/SafeTimespanGuarantor.h", "max_issues_repo_name": "chiamaka-123/BabylonNative", "max_issues_repo_head_hexsha": "7f1f9fd23bf649c9c8a1260f2b93752145b0c024", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 593.0, "max_issues_repo_issues_event_min_datetime": "2019-05-31T23:56:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:25:09.000Z", "max_forks_repo_path": "Core/Graphics/Source/SafeTimespanGuarantor.h", "max_forks_repo_name": "chiamaka-123/BabylonNative", "max_forks_repo_head_hexsha": "7f1f9fd23bf649c9c8a1260f2b93752145b0c024", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 114.0, "max_forks_repo_forks_event_min_datetime": "2019-06-10T18:07:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T21:13:27.000Z", "avg_line_length": 20.2258064516, "max_line_length": 73, "alphanum_fraction": 0.644338118, "num_tokens": 148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06853748922682354, "lm_q2_score": 0.019719127639275615, "lm_q1q2_score": 0.0013514994981392108}}
{"text": "// Copyright 2021 atframework\n// Created by owent on\n\n#pragma once\n\n#include <stdint.h>\n#include <cstddef>\n#include <cstring>\n#include <memory>\n#include <string>\n#include <type_traits>\n\n#include <config/compiler/protobuf_prefix.h>\n\n#include <rapidjson/document.h>\n\n#include <config/compiler/protobuf_suffix.h>\n\n#include <gsl/select-gsl.h>\n\n#include <log/log_wrapper.h>\n\n#include <libatbus.h>\n\n#include \"atframe/atapp_config.h\"\n\nnamespace google {\nnamespace protobuf {\nclass Message;\nclass Timestamp;\nclass Duration;\n}  // namespace protobuf\n}  // namespace google\n\nnamespace atapp {\n\nstruct LIBATAPP_MACRO_API_HEAD_ONLY rapidsjon_loader_string_mode {\n  enum type {\n    RAW = 0,\n    URI,\n    URI_COMPONENT,\n  };\n};\n\nstruct LIBATAPP_MACRO_API_HEAD_ONLY rapidsjon_loader_load_options {\n  bool reserve_empty;\n  bool convert_large_number_to_string;  // it's friendly to JSON.parse(...) in javascript\n  rapidsjon_loader_string_mode::type string_mode;\n\n  inline rapidsjon_loader_load_options()\n      : reserve_empty(false), convert_large_number_to_string(false), string_mode(rapidsjon_loader_string_mode::RAW) {}\n};\n\nstruct LIBATAPP_MACRO_API_HEAD_ONLY rapidsjon_loader_dump_options {\n  rapidsjon_loader_string_mode::type string_mode;\n  bool convert_number_from_string;  // it's friendly to JSON.parse(...) in javascript\n  inline rapidsjon_loader_dump_options()\n      : string_mode(rapidsjon_loader_string_mode::RAW), convert_number_from_string(true) {}\n};\n\nLIBATAPP_MACRO_API std::string rapidsjon_loader_stringify(const rapidjson::Document &doc, size_t more_reserve_size = 0);\nLIBATAPP_MACRO_API bool rapidsjon_loader_unstringify(rapidjson::Document &doc, const std::string &json);\nLIBATAPP_MACRO_API const char *rapidsjon_loader_get_type_name(rapidjson::Type t);\n\nLIBATAPP_MACRO_API std::string rapidsjon_loader_stringify(\n    const ATBUS_MACRO_PROTOBUF_NAMESPACE_ID::Message &src,\n    const rapidsjon_loader_load_options &options = rapidsjon_loader_load_options());\nLIBATAPP_MACRO_API bool rapidsjon_loader_parse(\n    ATBUS_MACRO_PROTOBUF_NAMESPACE_ID::Message &dst, const std::string &src,\n    const rapidsjon_loader_dump_options &options = rapidsjon_loader_dump_options());\n\nLIBATAPP_MACRO_API void rapidsjon_loader_mutable_set_member(rapidjson::Value &parent, gsl::string_view key,\n                                                            rapidjson::Value &&val, rapidjson::Document &doc);\nLIBATAPP_MACRO_API void rapidsjon_loader_mutable_set_member(rapidjson::Value &parent, gsl::string_view key,\n                                                            const rapidjson::Value &val, rapidjson::Document &doc);\nLIBATAPP_MACRO_API void rapidsjon_loader_mutable_set_member(rapidjson::Value &parent, gsl::string_view key,\n                                                            gsl::string_view val, rapidjson::Document &doc);\n\nLIBATAPP_MACRO_API void rapidsjon_loader_append_to_list(rapidjson::Value &list_parent, gsl::string_view val,\n                                                        rapidjson::Document &doc);\n\nLIBATAPP_MACRO_API void rapidsjon_loader_dump_to(\n    const rapidjson::Document &src, ATBUS_MACRO_PROTOBUF_NAMESPACE_ID::Message &dst,\n    const rapidsjon_loader_dump_options &options = rapidsjon_loader_dump_options());\n\nLIBATAPP_MACRO_API void rapidsjon_loader_load_from(\n    rapidjson::Document &dst, const ATBUS_MACRO_PROTOBUF_NAMESPACE_ID::Message &src,\n    const rapidsjon_loader_load_options &options = rapidsjon_loader_load_options());\n\nLIBATAPP_MACRO_API void rapidsjon_loader_dump_to(\n    const rapidjson::Value &src, ATBUS_MACRO_PROTOBUF_NAMESPACE_ID::Message &dst,\n    const rapidsjon_loader_dump_options &options = rapidsjon_loader_dump_options());\n\nLIBATAPP_MACRO_API void rapidsjon_loader_load_from(\n    rapidjson::Value &dst, rapidjson::Document &doc, const ATBUS_MACRO_PROTOBUF_NAMESPACE_ID::Message &src,\n    const rapidsjon_loader_load_options &options = rapidsjon_loader_load_options());\n\n// ============ template implement ============\n\ntemplate <class TVAL, bool>\nstruct rapidsjon_loader_mutable_member_helper;\n\ntemplate <class TVAL>\nstruct rapidsjon_loader_mutable_member_helper<TVAL, true> {\n  static LIBATAPP_MACRO_API_HEAD_ONLY inline void set(rapidjson::Value &parent, gsl::string_view key, TVAL &&val,\n                                                      rapidjson::Document &doc) {\n    rapidsjon_loader_mutable_set_member(parent, key, gsl::string_view(std::forward<TVAL>(val)), doc);\n  }\n\n  static LIBATAPP_MACRO_API_HEAD_ONLY inline void append(rapidjson::Value &parent, TVAL &&val,\n                                                         rapidjson::Document &doc) {\n    rapidsjon_loader_append_to_list(parent, gsl::string_view(std::forward<TVAL>(val)), doc);\n  }\n};\n\ntemplate <class TVAL>\nstruct rapidsjon_loader_mutable_member_helper<TVAL, false> {\n  static LIBATAPP_MACRO_API_HEAD_ONLY inline void set(rapidjson::Value &parent, gsl::string_view key, TVAL &&val,\n                                                      rapidjson::Document &doc) {\n    if (parent.IsNull()) {\n      parent.SetObject();\n    }\n\n    if (!parent.IsObject()) {\n      FWLOGERROR(\"parent should be a object, but we got {}.\", rapidsjon_loader_get_type_name(parent.GetType()));\n      return;\n    }\n\n    rapidjson::Value jkey;\n    jkey.SetString(rapidjson::StringRef(key.data(), static_cast<rapidjson::SizeType>(key.size())));\n    rapidjson::Value::MemberIterator iter = parent.FindMember(jkey);\n    if (iter != parent.MemberEnd()) {\n      iter->value.Set(std::forward<TVAL>(val), doc.GetAllocator());\n    } else {\n      rapidjson::Value k;\n      k.SetString(key.data(), static_cast<rapidjson::SizeType>(key.size()), doc.GetAllocator());\n      parent.AddMember(k, std::forward<TVAL>(val), doc.GetAllocator());\n    }\n  }\n\n  static LIBATAPP_MACRO_API_HEAD_ONLY inline void append(rapidjson::Value &parent, TVAL &&val,\n                                                         rapidjson::Document &doc) {\n    if (parent.IsNull()) {\n      parent.SetArray();\n    }\n\n    if (!parent.IsArray()) {\n      FWLOGERROR(\"parent should be a array, but we got {}.\", rapidsjon_loader_get_type_name(parent.GetType()));\n      return;\n    }\n\n    parent.PushBack(std::forward<TVAL>(val), doc.GetAllocator());\n  }\n};\n\ntemplate <class TVAL, class = typename std::enable_if<\n                          !std::is_same<typename std::decay<TVAL>::type, gsl::string_view>::value>::type>\nLIBATAPP_MACRO_API_HEAD_ONLY void rapidsjon_loader_mutable_set_member(rapidjson::Value &parent, gsl::string_view key,\n                                                                      TVAL &&val, rapidjson::Document &doc) {\n  rapidsjon_loader_mutable_member_helper<TVAL, std::is_convertible<TVAL, gsl::string_view>::value>::set(\n      parent, key, std::forward<TVAL>(val), doc);\n}\n\ntemplate <class TVAL, class = typename std::enable_if<\n                          !std::is_same<typename std::decay<TVAL>::type, gsl::string_view>::value>::type>\nLIBATAPP_MACRO_API_HEAD_ONLY void rapidsjon_loader_append_to_list(rapidjson::Value &parent, TVAL &&val,\n                                                                  rapidjson::Document &doc) {\n  rapidsjon_loader_mutable_member_helper<TVAL, std::is_convertible<TVAL, gsl::string_view>::value>::append(\n      parent, std::forward<TVAL>(val), doc);\n}\n}  // namespace atapp\n", "meta": {"hexsha": "6383981df07f33f8495d8dfae601f99539d89522", "size": 7309, "ext": "h", "lang": "C", "max_stars_repo_path": "include/atframe/atapp_conf_rapidjson.h", "max_stars_repo_name": "atframework/libatapp", "max_stars_repo_head_hexsha": "54aae9e0972eb94c33a7c109bdd099ff3a89ee80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2018-06-23T04:38:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T01:22:54.000Z", "max_issues_repo_path": "include/atframe/atapp_conf_rapidjson.h", "max_issues_repo_name": "atframework/libatapp", "max_issues_repo_head_hexsha": "54aae9e0972eb94c33a7c109bdd099ff3a89ee80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/atframe/atapp_conf_rapidjson.h", "max_forks_repo_name": "atframework/libatapp", "max_forks_repo_head_hexsha": "54aae9e0972eb94c33a7c109bdd099ff3a89ee80", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-08-04T06:14:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-19T10:06:06.000Z", "avg_line_length": 42.4941860465, "max_line_length": 120, "alphanum_fraction": 0.6999589547, "num_tokens": 1670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.04885777515983834, "lm_q2_score": 0.027585283326002775, "lm_q1q2_score": 0.0013477555704622813}}
{"text": "#pragma once\n#include \"parser.h\"\n#include \"format.h\"\n#include \"nameutils.h\"\n#include \"utils.h\"\n#include <sfun/string_utils.h>\n#include <cmdlime/errors.h>\n#include <gsl/gsl>\n#include <algorithm>\n#include <sstream>\n#include <iomanip>\n#include <functional>\n#include <optional>\n\nnamespace cmdlime::detail{\nnamespace str = sfun::string_utils;\n\ntemplate <FormatType formatType>\nclass GNUParser : public Parser<formatType>\n{\n    using Parser<formatType>::Parser;\n    using FindMode = typename Parser<formatType>::FindMode;\n\n    void preProcess() override\n    {\n        checkNames();\n        foundParam_.clear();\n        foundParamPrefix_.clear();\n    }\n\n    void process(const std::string& token) override\n    {        \n        if (str::startsWith(token, \"--\") && token.size() > 2)\n            processCommand(token);\n        else if (str::startsWith(token, \"-\") && token.size() > 1)\n            processShortCommand(token);\n        else if (!foundParam_.empty()){\n            this->readParam(foundParam_, token);\n            foundParam_.clear();\n        }\n        else\n            this->readArg(token);\n    }\n\n    void postProcess() override\n    {\n        if (!foundParam_.empty())\n            throw ParsingError{\"Parameter '\" + foundParamPrefix_ + foundParam_ + \"' value can't be empty\"};\n    }\n\n    void processCommand(std::string command)\n    {\n        command = str::after(command, \"--\");\n        auto paramValue = std::optional<std::string>{};\n        if (command.find('=') != std::string::npos){\n            paramValue = str::after(command, \"=\");\n            command = str::before(command, \"=\");\n        }\n        if (isParamOrFlag(command) &&\n            !foundParam_.empty() &&\n            this->readMode_ != Parser<formatType>::ReadMode::ExitFlagsAndCommands)\n            throw ParsingError{\"Parameter '\" + foundParamPrefix_ + foundParam_ + \"' value can't be empty\"};\n        if (this->findParam(command, FindMode::Name) || this->findParamList(command, FindMode::Name)){\n            if (paramValue.has_value())\n                this->readParam(command, paramValue.value());\n            else{\n                foundParam_ = command;\n                foundParamPrefix_ = \"--\";\n            }\n        }\n        else if (this->findFlag(command, FindMode::Name))\n            this->readFlag(command);\n        else if (this->readMode_ != Parser<formatType>::ReadMode::ExitFlagsAndCommands)\n            throw ParsingError{\"Encountered unknown parameter or flag '--\" + command + \"'\"};\n    }\n\n    void processShortCommand(std::string command)\n    {\n        auto possibleNumberArg = command;\n        command = str::after(command, \"-\");\n        if (isShortParamOrFlag(command)){\n            if (!foundParam_.empty() && this->readMode_ != Parser<formatType>::ReadMode::ExitFlagsAndCommands)\n                throw ParsingError{\"Parameter '\" + foundParamPrefix_ + foundParam_ + \"' value can't be empty\"};\n            parseShortCommand(command);\n        }\n        else if (isNumber(possibleNumberArg))\n            this->readArg(possibleNumberArg);\n        else if (this->readMode_ != Parser<formatType>::ReadMode::ExitFlagsAndCommands)\n            throw ParsingError{\"Encountered unknown parameter or flag '-\" + command + \"'\"};\n    }\n\n    void parseShortCommand(const std::string& command)\n    {\n        if (command.empty())\n            throw ParsingError{\"Flags and parameters must have a name\"};\n        auto paramValue = std::string{};\n        for(auto ch : command){\n            auto opt = std::string{ch};\n            if (!foundParam_.empty())\n                paramValue += opt;\n            else if (this->findFlag(opt, FindMode::ShortName))\n                this->readFlag(opt);\n            else if (this->findParam(opt, FindMode::ShortName)){\n                foundParam_ = opt;\n                foundParamPrefix_ = \"-\";\n            }\n            else if (this->findParamList(opt, FindMode::ShortName)){\n                foundParam_ = opt;\n                foundParamPrefix_ = \"-\";\n            }\n            else if (this->readMode_ != Parser<formatType>::ReadMode::ExitFlagsAndCommands)\n                throw ParsingError{\"Unknown option '\" + opt + \"' in command '-\" + command + \"'\"};\n        }\n        if (!foundParam_.empty() && !paramValue.empty()){\n            this->readParam(foundParam_, paramValue);\n            foundParam_.clear();\n        }\n    }\n\n    void checkLongNames()\n    {\n        auto check = [](const OptionInfo& var, const std::string& varType){\n            if (!std::isalpha(var.name().front()))\n                throw ConfigError{varType + \"'s name '\" + var.name() + \"' must start with an alphabet character\"};\n            if (var.name().size() > 1){\n                auto nonSupportedCharIt = std::find_if(var.name().begin() + 1, var.name().end(), [](char ch){return !std::isalnum(ch) && ch != '-';});\n                if (nonSupportedCharIt != var.name().end())\n                    throw ConfigError{varType + \"'s name '\" + var.name() + \"' must consist of alphanumeric characters and hyphens\"};\n            }\n        };\n        this->forEachParamInfo([check](const OptionInfo& var){\n            check(var, \"Parameter\");\n        });\n        this->forEachParamListInfo([check](const OptionInfo& var){\n            check(var, \"Parameter\");\n        });\n        this->forEachFlagInfo([check](const OptionInfo& var){\n            check(var, \"Flag\");\n        });\n    }\n\n    void checkShortNames()\n    {\n        auto check = [](const OptionInfo& var, const std::string& varType){\n            if (var.shortName().empty())\n                return;\n            if (var.shortName().size() != 1)\n                throw ConfigError{varType + \"'s short name '\" + var.shortName() + \"' can't have more than one symbol\"};\n            if (!std::isalnum(var.shortName().front()))\n                throw ConfigError{varType + \"'s short name '\" + var.shortName() + \"' must be an alphanumeric character\"};\n        };\n        this->forEachParamInfo([check](const OptionInfo& var){\n            check(var, \"Parameter\");\n        });\n        this->forEachParamListInfo([check](const OptionInfo& var){\n            check(var, \"Parameter\");\n        });\n        this->forEachFlagInfo([check](const OptionInfo& var){\n            check(var, \"Flag\");\n        });\n    }\n\n    void checkNames()\n    {\n        checkLongNames();\n        checkShortNames();\n    }\n\n    bool isParamOrFlag(const std::string& str)\n    {\n        if (str.empty())\n            return false;\n        return this->findFlag(str, FindMode::Name) ||\n               this->findParam(str, FindMode::Name) ||\n               this->findParamList(str, FindMode::Name);\n    }\n\n    bool isShortParamOrFlag(const std::string& str)\n    {\n        if (str.empty())\n            return false;\n        auto opt = str.substr(0,1);\n        return this->findFlag(opt, FindMode::ShortName) ||\n               this->findParam(opt, FindMode::ShortName) ||\n               this->findParamList(opt, FindMode::ShortName);\n    }\n\nprivate:\n    std::string foundParam_;\n    std::string foundParamPrefix_;\n};\n\nclass GNUNameProvider{\npublic:\n    static std::string name(const std::string& optionName)\n    {\n        Expects(!optionName.empty());\n        return toKebabCase(optionName);\n    }\n\n    static std::string shortName(const std::string& optionName)\n    {\n        Expects(!optionName.empty());\n        return toLowerCase(optionName.substr(0, 1));\n    }\n\n    static std::string fullName(const std::string& optionName)\n    {\n        Expects(!optionName.empty());\n        return toKebabCase(optionName);\n    }\n\n    static std::string valueName(const std::string& typeName)\n    {\n        Expects(!typeName.empty());\n        return toKebabCase(templateType(typeNameWithoutNamespace(typeName)));\n    }\n};\n\n\nclass GNUOutputFormatter{\npublic:\n    static std::string paramUsageName(const IParam& param)\n    {\n        auto stream = std::stringstream{};\n        if (param.isOptional())\n            stream << \"[\" << paramPrefix() << param.info().name() << \" <\" << param.info().valueName() << \">]\";\n        else\n            stream << paramPrefix() << param.info().name() << \" <\" << param.info().valueName() << \">\";\n        return stream.str();\n    }\n\n    static std::string paramListUsageName(const IParamList& param)\n    {\n        auto stream = std::stringstream{};\n        if (param.isOptional())\n            stream << \"[\" << paramPrefix() << param.info().name() << \" <\" << param.info().valueName() << \">...]\";\n        else\n            stream << paramPrefix() << param.info().name() << \" <\" << param.info().valueName() << \">...\";\n        return stream.str();\n    }\n\n    static std::string paramDescriptionName(const IParam& param, int indent = 0)\n    {\n        auto stream = std::stringstream{};\n        stream << std::setw(indent);\n        if (!param.info().shortName().empty())\n            stream << \"-\" << param.info().shortName() << \", \";\n        else\n            stream << \" \" << \"   \";\n        stream << \"--\" << param.info().name() << \" <\" << param.info().valueName() << \">\";\n        return stream.str();\n    }\n\n    static std::string paramListDescriptionName(const IParamList& param, int indent = 0)\n    {\n        auto stream = std::stringstream{};\n        stream << std::setw(indent);\n        if (!param.info().shortName().empty())\n            stream << \"-\" << param.info().shortName() << \", \";\n        else\n            stream << \" \" << \"   \";\n        stream << \"--\" << param.info().name() << \" <\" << param.info().valueName() << \">\";\n        return stream.str();\n    }\n\n    static std::string paramPrefix()\n    {\n        return \"--\";\n    }\n\n    static std::string flagUsageName(const IFlag& flag)\n    {\n        auto stream = std::stringstream{};\n        stream << \"[\" << flagPrefix() << flag.info().name() << \"]\";\n        return stream.str();\n    }\n\n    static std::string flagDescriptionName(const IFlag& flag, int indent = 0)\n    {\n        auto stream = std::stringstream{};\n        stream << std::setw(indent) ;\n        if (!flag.info().shortName().empty())\n            stream << \"-\" << flag.info().shortName() << \", \";\n        else\n            stream << \" \" << \"   \";\n        stream << \"--\" << flag.info().name();\n        return stream.str();\n    }\n\n    static std::string flagPrefix()\n    {\n        return \"--\";\n    }    \n\n    static std::string argUsageName(const IArg& arg)\n    {\n        auto stream = std::stringstream{};\n        stream << \"<\" << arg.info().name() << \">\";\n        return stream.str();\n    }\n\n    static std::string argDescriptionName(const IArg& arg, int indent = 0)\n    {\n        auto stream = std::stringstream{};\n        if (indent)\n            stream << std::setw(indent) << \" \";\n        stream << \"<\" << arg.info().name() << \"> (\" << arg.info().valueName() << \")\";\n        return stream.str();\n    }\n\n    static std::string argListUsageName(const IArgList& argList)\n    {\n        auto stream = std::stringstream{};\n        if (argList.isOptional())\n            stream << \"[\" << argList.info().name() << \"...]\";\n        else\n            stream << \"<\" << argList.info().name() << \"...>\";\n        return stream.str();\n    }\n\n    static std::string argListDescriptionName(const IArgList& argList, int indent = 0)\n    {\n        auto stream = std::stringstream{};\n        if (indent)\n            stream << std::setw(indent) << \" \";\n        stream << \"<\" << argList.info().name() << \"> (\" << argList.info().valueName() << \")\";\n        return stream.str();\n    }\n\n};\n\ntemplate<>\nstruct Format<FormatType::GNU>\n{\n    using parser = GNUParser<FormatType::GNU>;\n    using nameProvider = GNUNameProvider;\n    using outputFormatter = GNUOutputFormatter;\n    static constexpr bool shortNamesEnabled = true;\n};\n\n\n}\n", "meta": {"hexsha": "fa283da571c57e9e2de55992d27731d55d403fdd", "size": 11631, "ext": "h", "lang": "C", "max_stars_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/gnuformat.h", "max_stars_repo_name": "GerHobbelt/hypertextcpp", "max_stars_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_stars_repo_licenses": ["MS-PL"], "max_stars_count": 77.0, "max_stars_repo_stars_event_min_datetime": "2021-05-20T18:05:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T21:37:54.000Z", "max_issues_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/gnuformat.h", "max_issues_repo_name": "GerHobbelt/hypertextcpp", "max_issues_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_issues_repo_licenses": ["MS-PL"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2021-05-20T22:04:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-21T08:13:28.000Z", "max_forks_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/gnuformat.h", "max_forks_repo_name": "GerHobbelt/hypertextcpp", "max_forks_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_forks_repo_licenses": ["MS-PL"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-22T00:36:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-22T00:36:08.000Z", "avg_line_length": 33.8110465116, "max_line_length": 150, "alphanum_fraction": 0.5503396097, "num_tokens": 2673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07263670033827889, "lm_q2_score": 0.018546566207365625, "lm_q1q2_score": 0.0013471613719084666}}
{"text": "/**\n *  Copyright (C) 2021 FISCO BCOS.\n *  SPDX-License-Identifier: Apache-2.0\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n * @brief interface for Ledger\n * @file LedgerInterface.h\n * @author: kyonRay\n * @date: 2021-04-07\n */\n\n#pragma once\n\n#include \"../../interfaces/crypto/CommonType.h\"\n#include \"../../interfaces/protocol/Block.h\"\n#include \"../../interfaces/protocol/BlockHeader.h\"\n#include \"../../interfaces/protocol/Transaction.h\"\n#include \"../../interfaces/protocol/TransactionReceipt.h\"\n#include \"../../interfaces/storage/StorageInterface.h\"\n#include \"LedgerConfig.h\"\n#include \"LedgerTypeDef.h\"\n#include \"bcos-utilities/Error.h\"\n#include <gsl/span>\n#include <map>\n\n\nnamespace bcos::ledger\n{\nclass LedgerInterface\n{\npublic:\n    using Ptr = std::shared_ptr<LedgerInterface>;\n    LedgerInterface() = default;\n    virtual ~LedgerInterface() {}\n\n    /**\n     * @brief async prewrite a block in scheduler module\n     * @param block the block to commit\n     * @param callback trigger this callback when write is finished\n     */\n    virtual void asyncPrewriteBlock(bcos::storage::StorageInterface::Ptr storage,\n        bcos::protocol::Block::ConstPtr block, std::function<void(Error::Ptr&&)> callback) = 0;\n\n    /**\n     * @brief async store txs in block when tx pool verify\n     * @param _txToStore tx bytes data list\n     * @param _txHashList tx hash list\n     * @param _onTxsStored callback\n     */\n    virtual void asyncStoreTransactions(std::shared_ptr<std::vector<bytesConstPtr>> _txToStore,\n        crypto::HashListPtr _txHashList, std::function<void(Error::Ptr)> _onTxStored) = 0;\n\n    /**\n     * @brief async get block by blockNumber\n     * @param _blockNumber number of block\n     * @param _blockFlag flag bit of what the block be callback contains,\n     *                   you can checkout all flags in LedgerTypeDef.h\n     * @param _onGetBlock\n     *\n     * @example\n     * asyncGetBlockDataByNumber(10, HEADER|TRANSACTIONS, [](error, block){ doSomething(); });\n     */\n    virtual void asyncGetBlockDataByNumber(protocol::BlockNumber _blockNumber, int32_t _blockFlag,\n        std::function<void(Error::Ptr, protocol::Block::Ptr)> _onGetBlock) = 0;\n\n    /**\n     * @brief async get latest block number\n     * @param _onGetBlock\n     */\n    virtual void asyncGetBlockNumber(\n        std::function<void(Error::Ptr, protocol::BlockNumber)> _onGetBlock) = 0;\n\n    /**\n     * @brief async get block hash by block number\n     * @param _blockNumber the number of block to get\n     * @param _onGetBlock\n     */\n    virtual void asyncGetBlockHashByNumber(protocol::BlockNumber _blockNumber,\n        std::function<void(Error::Ptr, crypto::HashType)> _onGetBlock) = 0;\n\n    /**\n     * @brief async get block number by block hash\n     * @param _blockHash the hash of block to get\n     * @param _onGetBlock\n     */\n    virtual void asyncGetBlockNumberByHash(crypto::HashType const& _blockHash,\n        std::function<void(Error::Ptr, protocol::BlockNumber)> _onGetBlock) = 0;\n\n    /**\n     * @brief async get a batch of transaction by transaction hash list\n     * @param _txHashList transaction hash list, hash should be hex\n     * @param _withProof if true then it will callback MerkleProofPtr map in _onGetTx\n     *                   if false then MerkleProofPtr map will be nullptr\n     * @param _onGetTx return <error, [tx data in bytes], map<txHash, merkleProof>\n     */\n    virtual void asyncGetBatchTxsByHashList(crypto::HashListPtr _txHashList, bool _withProof,\n        std::function<void(Error::Ptr, bcos::protocol::TransactionsPtr,\n            std::shared_ptr<std::map<std::string, MerkleProofPtr>>)>\n            _onGetTx) = 0;\n\n    /**\n     * @brief async get a transaction receipt by tx hash\n     * @param _txHash hash of transaction\n     * @param _withProof if true then it will callback MerkleProofPtr in _onGetTx\n     *                   if false then MerkleProofPtr will be nullptr\n     * @param _onGetTx\n     */\n    virtual void asyncGetTransactionReceiptByHash(crypto::HashType const& _txHash, bool _withProof,\n        std::function<void(Error::Ptr, protocol::TransactionReceipt::ConstPtr, MerkleProofPtr)>\n            _onGetTx) = 0;\n\n    /**\n     * @brief async get total transaction count and latest block number\n     * @param _callback callback totalTxCount, totalFailedTxCount, and latest block number\n     */\n    virtual void asyncGetTotalTransactionCount(std::function<void(Error::Ptr, int64_t _totalTxCount,\n            int64_t _failedTxCount, protocol::BlockNumber _latestBlockNumber)>\n            _callback) = 0;\n\n    /**\n     * @brief async get system config by table key\n     * @param _key the key of row, you can checkout all key in LedgerTypeDef.h\n     * @param _onGetConfig callback when get config, <value, latest block number>\n     */\n    virtual void asyncGetSystemConfigByKey(std::string const& _key,\n        std::function<void(Error::Ptr, std::string, protocol::BlockNumber)> _onGetConfig) = 0;\n\n    /**\n     * @brief async get node list by type, can be sealer or observer\n     * @param _type the type of node, CONSENSUS_SEALER or CONSENSUS_OBSERVER\n     * @param _onGetConfig\n     */\n    virtual void asyncGetNodeListByType(std::string const& _type,\n        std::function<void(Error::Ptr, consensus::ConsensusNodeListPtr)> _onGetConfig) = 0;\n\n    /**\n     * @brief async get a batch of nonce lists in blocks\n     * @param _startNumber start block number\n     * @param _offset batch offset, if batch is 0, then callback nonce list in start block number;\n     * if (_startNumber + _offset) > latest block number, then callback nonce lists in\n     * [_startNumber, latest number]\n     * @param _onGetList\n     */\n    virtual void asyncGetNonceList(protocol::BlockNumber _startNumber, int64_t _offset,\n        std::function<void(\n            Error::Ptr, std::shared_ptr<std::map<protocol::BlockNumber, protocol::NonceListPtr>>)>\n            _onGetList) = 0;\n};\n}  // namespace bcos::ledger\n", "meta": {"hexsha": "6ce1d1a3c461ee958418b9068f9f3cc9d2a285ab", "size": 6443, "ext": "h", "lang": "C", "max_stars_repo_path": "bcos-framework/interfaces/ledger/LedgerInterface.h", "max_stars_repo_name": "chuwen95/FISCO-BCOS", "max_stars_repo_head_hexsha": "e9cc29151c90dd1f4634f4d52ba773bb216700ac", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-06T10:46:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T10:46:12.000Z", "max_issues_repo_path": "bcos-framework/interfaces/ledger/LedgerInterface.h", "max_issues_repo_name": "chuwen95/FISCO-BCOS", "max_issues_repo_head_hexsha": "e9cc29151c90dd1f4634f4d52ba773bb216700ac", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bcos-framework/interfaces/ledger/LedgerInterface.h", "max_forks_repo_name": "chuwen95/FISCO-BCOS", "max_forks_repo_head_hexsha": "e9cc29151c90dd1f4634f4d52ba773bb216700ac", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.26875, "max_line_length": 100, "alphanum_fraction": 0.6860158311, "num_tokens": 1630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07477004290796137, "lm_q2_score": 0.017986214008712552, "lm_q1q2_score": 0.0013448299931832133}}
{"text": "/* -----------------------------------------------------------------------------\n * Copyright 2021 Jonathan Haigh\n * SPDX-License-Identifier: MIT\n * ---------------------------------------------------------------------------*/\n\n#ifndef SQ_INCLUDE_GUARD_system_linux_SqFieldSchemaImpl_h_\n#define SQ_INCLUDE_GUARD_system_linux_SqFieldSchemaImpl_h_\n\n#include \"core/typeutil.h\"\n#include \"system/SqFieldSchema.gen.h\"\n#include \"system/schema.h\"\n\n#include <gsl/gsl>\n\nnamespace sq::system::linux {\n\nclass SqFieldSchemaImpl : public SqFieldSchema<SqFieldSchemaImpl> {\npublic:\n  explicit SqFieldSchemaImpl(const FieldSchema &field_schema);\n\n  SQ_ND Result get_name() const;\n  SQ_ND Result get_doc() const;\n  SQ_ND Result get_params() const;\n  SQ_ND Result get_return_type() const;\n  SQ_ND Result get_return_list() const;\n  SQ_ND Result get_null() const;\n\n  SQ_ND Primitive to_primitive() const override;\n\nprivate:\n  gsl::not_null<const FieldSchema *> field_schema_;\n};\n\n} // namespace sq::system::linux\n\n#endif // SQ_INCLUDE_GUARD_system_linux_SqFieldSchemaImpl_h_\n", "meta": {"hexsha": "dffe25eaaae796556976608d08139eaac5bdddf4", "size": 1055, "ext": "h", "lang": "C", "max_stars_repo_path": "src/system/include/system/linux/SqFieldSchemaImpl.h", "max_stars_repo_name": "jonathanhaigh/sq", "max_stars_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-12T16:21:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-12T16:21:41.000Z", "max_issues_repo_path": "src/system/include/system/linux/SqFieldSchemaImpl.h", "max_issues_repo_name": "jonathanhaigh/sq", "max_issues_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 44.0, "max_issues_repo_issues_event_min_datetime": "2021-02-08T19:17:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-05T18:51:38.000Z", "max_forks_repo_path": "src/system/include/system/linux/SqFieldSchemaImpl.h", "max_forks_repo_name": "jonathanhaigh/sq", "max_forks_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5135135135, "max_line_length": 80, "alphanum_fraction": 0.6691943128, "num_tokens": 231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06008665690650098, "lm_q2_score": 0.022286186919153884, "lm_q1q2_score": 0.0013391024671653496}}
{"text": "#pragma once\n#include \"iflag.h\"\n#include \"optioninfo.h\"\n#include \"configaccess.h\"\n#include \"format.h\"\n#include <gsl/gsl>\n#include <cmdlime/customnames.h>\n#include <memory>\n#include <functional>\n#include <utility>\n\nnamespace cmdlime::detail{\n\nclass Flag : public IFlag{\npublic:\n    enum class Type{\n        Normal,\n        Exit\n    };\n\n    Flag(std::string name,\n         std::string shortName,\n         std::function<bool&()> flagGetter,\n         Type type)\n        : info_(std::move(name), std::move(shortName), {})\n        , flagGetter_(std::move(flagGetter))\n        , type_(type)\n    {\n    }\n\n    OptionInfo& info() override\n    {\n        return info_;\n    }\n\n    const OptionInfo& info() const override\n    {\n        return info_;\n    }\n\nprivate:\n    void set() override\n    {\n        flagGetter_() = true;\n    }\n\n    bool isSet() const override\n    {\n        return flagGetter_();\n    }\n\n    bool isExitFlag() const override\n    {\n        return type_ == Type::Exit;\n    }\n\nprivate:\n    OptionInfo info_;\n    std::function<bool&()> flagGetter_;\n    Type type_;\n};\n\ntemplate <typename TConfig>\nclass FlagCreator{\n    using NameProvider = typename Format<ConfigAccess<TConfig>::format()>::nameProvider;\n\npublic:\n    FlagCreator(TConfig& cfg,\n                const std::string& varName,\n                std::function<bool&()> flagGetter,\n                Flag::Type flagType = Flag::Type::Normal)\n        : cfg_(cfg)\n    {\n        Expects(!varName.empty());\n        flag_ = std::make_unique<Flag>(NameProvider::name(varName),\n                                       NameProvider::shortName(varName),\n                                       std::move(flagGetter),\n                                       flagType);\n    }\n\n    FlagCreator& operator<<(const std::string& info)\n    {\n        flag_->info().addDescription(info);\n        return *this;\n    }\n\n    FlagCreator& operator<<(const Name& customName)\n    {\n        flag_->info().resetName(customName.value());\n        return *this;\n    }\n\n    FlagCreator& operator<<(const ShortName& customName)\n    {\n        static_assert(Format<ConfigAccess<TConfig>::format()>::shortNamesEnabled,\n                      \"Current command line format doesn't support short names\");\n        flag_->info().resetShortName(customName.value());\n        return *this;\n    }\n\n    FlagCreator& operator<<(const WithoutShortName&)\n    {\n        static_assert(Format<ConfigAccess<TConfig>::format()>::shortNamesEnabled,\n                      \"Current command line format doesn't support short names\");\n        flag_->info().resetShortName({});\n        return *this;\n    }\n\n    operator bool()\n    {\n        ConfigAccess<TConfig>{cfg_}.addFlag(std::move(flag_));\n        return false;\n    }\n\nprivate:\n    std::unique_ptr<Flag> flag_;\n    TConfig& cfg_;\n};\n}\n\n\n", "meta": {"hexsha": "5195d22f7ce9cd1d252062500b881cae9aa8e6cf", "size": 2786, "ext": "h", "lang": "C", "max_stars_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/flag.h", "max_stars_repo_name": "GerHobbelt/hypertextcpp", "max_stars_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_stars_repo_licenses": ["MS-PL"], "max_stars_count": 77.0, "max_stars_repo_stars_event_min_datetime": "2021-05-20T18:05:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T21:37:54.000Z", "max_issues_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/flag.h", "max_issues_repo_name": "GerHobbelt/hypertextcpp", "max_issues_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_issues_repo_licenses": ["MS-PL"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2021-05-20T22:04:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-21T08:13:28.000Z", "max_forks_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/flag.h", "max_forks_repo_name": "GerHobbelt/hypertextcpp", "max_forks_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_forks_repo_licenses": ["MS-PL"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-22T00:36:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-22T00:36:08.000Z", "avg_line_length": 22.8360655738, "max_line_length": 88, "alphanum_fraction": 0.5728643216, "num_tokens": 622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06008665017400762, "lm_q2_score": 0.022286183712849815, "lm_q1q2_score": 0.0013391021244676731}}
{"text": "/// @file Span.h\n/// @author Braxton Salyer <braxtonsalyer@gmail.com>\n/// @brief A thin wrapper around `gsl::span`, providing `at` as a member function instead of a free\n/// function\n/// @version 0.1\n/// @date 2021-10-15\n///\n/// MIT License\n/// @copyright Copyright (c) 2021 Braxton Salyer <braxtonsalyer@gmail.com>\n///\n/// Permission is hereby granted, free of charge, to any person obtaining a copy\n/// of this software and associated documentation files (the \"Software\"), to deal\n/// in the Software without restriction, including without limitation the rights\n/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n/// copies of the Software, and to permit persons to whom the Software is\n/// furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in all\n/// copies or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n/// SOFTWARE.\n#pragma once\n\n#include <Hyperion/BasicTypes.h>\n#include <Hyperion/HyperionDef.h>\n#include <array>\n#include <gsl/gsl>\n#include <gsl/span>\n\nnamespace hyperion {\n\n\t/// @brief Thin wrapper around `gsl::span`\n\t///\n\t/// @tparam T - The type contained in the `Span`\n\t/// @tparam Size - The number of elements for constexpr sizes, or gsl::dynamic_extent (default)\n\t/// for run-time sizes\n\t/// @ingroup utils\n\t/// @headerfile \"Hyperion/Span.h\"\n\ttemplate<typename T, usize Size = gsl::dynamic_extent>\n\tclass Span {\n\t  public:\n\t\tusing Iterator = typename gsl::span<T, Size>::iterator;\n\t\tusing ReverseIterator = typename gsl::span<T, Size>::reverse_iterator;\n\t\ttemplate<usize Offset, usize Count>\n\t\tusing SubSpan = typename gsl::details::calculate_subspan_type<T, Size, Offset, Count>::type;\n\n\t\tSpan() noexcept = default;\n\n\t\t/// @brief Constructs a `Span` from a `gsl::span`\n\t\t///\n\t\t/// @param span - The `gsl::span` to wrap\n\t\t/// @ingroup utils\n\t\t/// @headerfile \"Hyperion/Span.h\"\n\t\texplicit constexpr Span(gsl::span<T, Size> span) noexcept : m_span_internal(span) {\n\t\t}\n\n\t\t/// @brief Copy constructs a `Span` from the given one\n\t\t///\n\t\t/// @param span - The `Span` to copy\n\t\t/// @ingroup utils\n\t\t/// @headerfile \"Hyperion/Span.h\"\n\t\tconstexpr Span(const Span<T, Size>& span) noexcept = default;\n\n\t\t/// @brief Move constructs the given `Span`\n\t\t///\n\t\t/// @param span - The `Span` to move\n\t\t/// @ingroup utils\n\t\t/// @headerfile \"Hyperion/Span.h\"\n\t\tconstexpr Span(Span<T, Size>&& span) noexcept = default;\n\t\t~Span() noexcept = default;\n\n\t\t/// @brief Returns the element at the given `index`\n\t\t///\n\t\t/// @param index - The index of the desired element\n\t\t/// @return - The element at `index`\n\t\t/// @ingroup utils\n\t\t/// @headerfile \"Hyperion/Span.h\"\n\t\t[[nodiscard]] inline constexpr auto at(usize index) noexcept -> T& {\n\t\t\treturn gsl::at(m_span_internal, static_cast<gsl::index>(index));\n\t\t}\n\n\t\t/// @brief Returns the first `Count` elements in the `Span`\n\t\t///\n\t\t/// @tparam Count - The number of elements to get\n\t\t/// @tparam size - The size of the `Span`, this should always be left defaulted\n\t\t/// @return - The first `Count` elements in the `Span`, as a `Span`\n\t\t/// @ingroup utils\n\t\t/// @headerfile \"Hyperion/Span.h\"\n\t\ttemplate<usize Count, usize size = Size>\n\t\trequires(size != gsl::dynamic_extent)\n\t\t\t[[nodiscard]] inline constexpr auto first() const noexcept -> Span<T, Count> {\n\t\t\treturn Span(m_span_internal.template first<Count>());\n\t\t}\n\n\t\t/// @brief Returns the first `count` elements in the `Span`\n\t\t///\n\t\t/// @tparam size - The size of the `Span`, this should always be left defaulted\n\t\t/// @param count - The number of elements to get\n\t\t/// @return - The first `count` elements in the `Span`, as a `Span`\n\t\t/// @ingroup utils\n\t\t/// @headerfile \"Hyperion/Span.h\"\n\t\ttemplate<usize size = Size>\n\t\trequires(size == gsl::dynamic_extent)\n\t\t\t[[nodiscard]] inline constexpr auto first(usize count) const noexcept -> Span<T, Size> {\n\t\t\treturn Span(m_span_internal.first(count));\n\t\t}\n\n\t\t/// @brief Returns the last `Count` elements in the `Span`\n\t\t///\n\t\t/// @tparam Count - The number of elements to get\n\t\t/// @tparam size - The size of the `Span`, this should always be left defaulted\n\t\t/// @return - The last `Count` elements in the `Span`, as a `Span`\n\t\t/// @ingroup utils\n\t\t/// @headerfile \"Hyperion/Span.h\"\n\t\ttemplate<usize Count, usize size = Size>\n\t\trequires(size != gsl::dynamic_extent)\n\t\t\t[[nodiscard]] inline constexpr auto last() const noexcept -> Span<T, Count> {\n\t\t\treturn Span(m_span_internal.template last<Count>());\n\t\t}\n\n\t\t/// @brief Returns the last `count` elements in the `Span`\n\t\t///\n\t\t/// @tparam size - The size of the `Span`, this should always be left defaulted\n\t\t/// @param count - The number of elements to get\n\t\t/// @return- The last `count` elements in the `Span` as a `Span`\n\t\t/// @ingroup utils\n\t\t/// @headerfile \"Hyperion/Span.h\"\n\t\ttemplate<usize size = Size>\n\t\trequires(size == gsl::dynamic_extent)\n\t\t\t[[nodiscard]] inline constexpr auto last(usize count) const noexcept -> Span<T, Size> {\n\t\t\treturn Span(m_span_internal.last(count));\n\t\t}\n\n\t\t/// @brief Returns a subspan starting at the given `Offset` with `Count` elements\n\t\t///\n\t\t/// @tparam Offset - The offset to start the subspan at\n\t\t/// @tparam Count - The number of elements to get in the subspan\n\t\t/// @return - The subspan starting at `Offset` of size `Count`\n\t\t/// @ingroup utils\n\t\t/// @headerfile \"Hyperion/Span.h\"\n\t\ttemplate<usize Offset, usize Count = gsl::dynamic_extent>\n\t\t[[nodiscard]] inline constexpr auto subspan() const noexcept -> SubSpan<Offset, Count> {\n\t\t\treturn Span(m_span_internal.template subspan<Offset, Count>());\n\t\t}\n\n\t\t/// @brief Returns a subspan starting at the given `offset` with `count` elements\n\t\t///\n\t\t/// @param offset - The offset to start the subspan at\n\t\t/// @param count - The number of elements to get in the subspan\n\t\t/// @return - The subspan starting at `offset` of size `count`\n\t\t/// @ingroup utils\n\t\t/// @headerfile \"Hyperion/Span.h\"\n\t\t[[nodiscard]] inline constexpr auto\n\t\tsubspan(usize offset, usize count = gsl::dynamic_extent) const noexcept\n\t\t\t-> Span<T, gsl::dynamic_extent> {\n\t\t\treturn Span(m_span_internal.subspan(offset, count));\n\t\t}\n\n\t\t/// @brief Returns the number of elements in the `Span`\n\t\t///\n\t\t/// @return - The number of elements in the `Span`\n\t\t/// @ingroup utils\n\t\t/// @headerfile \"Hyperion/Span.h\"\n\t\t[[nodiscard]] inline constexpr auto size() const noexcept -> usize {\n\t\t\treturn m_span_internal.size();\n\t\t}\n\n\t\t/// @brief Returns the size of the `Span` in bytes\n\t\t///\n\t\t/// @return - The size of the `Span` in bytes\n\t\t/// @ingroup utils\n\t\t/// @headerfile \"Hyperion/Span.h\"\n\t\t[[nodiscard]] inline constexpr auto size_bytes() const noexcept -> usize {\n\t\t\treturn m_span_internal.size_bytes();\n\t\t}\n\n\t\t/// @brief Returns whether the `Span` is empty\n\t\t///\n\t\t/// @return - If the `Span` is empty\n\t\t/// @ingroup utils\n\t\t/// @headerfile \"Hyperion/Span.h\"\n\t\t[[nodiscard]] inline constexpr auto is_empty() const noexcept -> bool {\n\t\t\treturn size() == 0;\n\t\t}\n\n\t\t/// @brief A pointer to the data contained in the `Span`\n\t\t///\n\t\t/// @return - A pointer to the data\n\t\t/// @ingroup utils\n\t\t/// @headerfile \"Hyperion/Span.h\"\n\t\t[[nodiscard]] inline constexpr auto data() const noexcept -> T* {\n\t\t\treturn m_span_internal.data();\n\t\t}\n\n\t\t/// @brief Returns the first element in the `Span`\n\t\t///\n\t\t/// @return - The first element\n\t\t/// @ingroup utils\n\t\t/// @headerfile \"Hyperion/Span.h\"\n\t\t[[nodiscard]] inline constexpr auto front() const noexcept -> T& {\n\t\t\treturn m_span_internal.front();\n\t\t}\n\n\t\t/// @brief Returns the last element in the `Span`\n\t\t///\n\t\t/// @return - The last element\n\t\t/// @ingroup utils\n\t\t/// @headerfile \"Hyperion/Span.h\"\n\t\t[[nodiscard]] inline constexpr auto back() const noexcept -> T& {\n\t\t\treturn m_span_internal.back();\n\t\t}\n\n\t\t/// @brief Returns an iterator at the beginning of the span\n\t\t///\n\t\t/// @return an iterator at the beginning of the span\n\t\t/// @ingroup utils\n\t\t/// @headerfile \"Hyperion/Span.h\"\n\t\t[[nodiscard]] inline constexpr auto begin() noexcept -> Iterator {\n\t\t\treturn m_span_internal.begin();\n\t\t}\n\n\t\t/// @brief Returns an iterator at the beginning of the span\n\t\t///\n\t\t/// @return an iterator at the beginning of the span\n\t\t/// @ingroup utils\n\t\t/// @headerfile \"Hyperion/Span.h\"\n\t\t[[nodiscard]] inline constexpr auto begin() const noexcept -> Iterator {\n\t\t\treturn m_span_internal.begin();\n\t\t}\n\n\t\t/// @brief Returns an iterator at the end of the span\n\t\t///\n\t\t/// @return an iterator at the end of the span\n\t\t/// @ingroup utils\n\t\t/// @headerfile \"Hyperion/Span.h\"\n\t\t[[nodiscard]] inline constexpr auto end() noexcept -> Iterator {\n\t\t\treturn m_span_internal.end();\n\t\t}\n\n\t\t/// @brief Returns an iterator at the end of the span\n\t\t///\n\t\t/// @return an iterator at the end of the span\n\t\t/// @ingroup utils\n\t\t/// @headerfile \"Hyperion/Span.h\"\n\t\t[[nodiscard]] inline constexpr auto end() const noexcept -> Iterator {\n\t\t\treturn m_span_internal.end();\n\t\t}\n\n\t\t/// @brief Returns an iterator at the beginning of the reversed iteration of the span\n\t\t///\n\t\t/// @return an iterator at the beginning of the reversed iteration of the span\n\t\t/// @ingroup utils\n\t\t/// @headerfile \"Hyperion/Span.h\"\n\t\t[[nodiscard]] inline constexpr auto rbegin() noexcept -> ReverseIterator {\n\t\t\treturn m_span_internal.rbegin();\n\t\t}\n\n\t\t/// @brief Returns an iterator at the beginning of the reversed iteration of the span\n\t\t///\n\t\t/// @return an iterator at the beginning of the reversed iteration of the span\n\t\t/// @ingroup utils\n\t\t/// @headerfile \"Hyperion/Span.h\"\n\t\t[[nodiscard]] inline constexpr auto rbegin() const noexcept -> ReverseIterator {\n\t\t\treturn m_span_internal.rbegin();\n\t\t}\n\n\t\t/// @brief Returns an iterator at the end of the reversed iteration of the span\n\t\t///\n\t\t/// @return an iterator at the end of the reversed iteration of the span\n\t\t/// @ingroup utils\n\t\t/// @headerfile \"Hyperion/Span.h\"\n\t\t[[nodiscard]] inline constexpr auto rend() noexcept -> ReverseIterator {\n\t\t\treturn m_span_internal.rend();\n\t\t}\n\n\t\t/// @brief Returns an iterator at the end of the reversed iteration of the span\n\t\t///\n\t\t/// @return an iterator at the end of the reversed iteration of the span\n\t\t/// @ingroup utils\n\t\t/// @headerfile \"Hyperion/Span.h\"\n\t\t[[nodiscard]] inline constexpr auto rend() const noexcept -> ReverseIterator {\n\t\t\treturn m_span_internal.rend();\n\t\t}\n\n#if HYPERION_PLATFORM_COMPILER_MSVC\n\t\t[[nodiscard]] inline constexpr auto _Unchecked_begin() const noexcept -> T* {\n\t\t\treturn m_span_internal._Unchecked_begin();\n\t\t}\n\n\t\t[[nodiscard]] inline constexpr auto _Unchecked_end() const noexcept -> T* {\n\t\t\treturn m_span_internal._Unchecked_end();\n\t\t}\n#endif // HYPERION_PLATFORM_COMPILER_MSVC\n\n\t\t/// @brief Returns the element at the given `index`\n\t\t///\n\t\t/// @param index - The index of the desired element\n\t\t/// @return - The element at `index`\n\t\t/// @ingroup utils\n\t\t/// @headerfile \"Hyperion/Span.h\"\n\t\t[[nodiscard]] inline constexpr auto operator[](usize index) noexcept -> T& {\n\t\t\treturn this->at(index);\n\t\t}\n\n\t\tconstexpr auto operator=(const Span<T, Size>& span) noexcept -> Span<T, Size>& = default;\n\t\tconstexpr auto operator=(Span<T, Size>&& span) noexcept -> Span<T, Size>& = default;\n\n\t  private:\n\t\tgsl::span<T, Size> m_span_internal = gsl::span<T, Size>();\n\t};\n\n\tIGNORE_UNUSED_TEMPLATES_START\n\n\t/// @brief Creates a `Span` from the given arguments\n\t///\n\t/// @tparam T - The type stored in the array\n\t///\n\t/// @param array - The array to get a `Span` over\n\t/// @param size - The size of the array\n\t///\n\t/// @return a `Span` over the given array\n\t/// @ingroup utils\n\t/// @headerfile \"Hyperion/Span.h\"\n\ttemplate<typename T>\n\t[[nodiscard]] inline static constexpr auto make_span(T* array, usize size) noexcept -> Span<T> {\n\t\treturn Span(gsl::make_span(array, static_cast<typename gsl::span<T>::size_type>(size)));\n\t}\n\n\t/// @brief Creates a `Span` from the given arguments\n\t///\n\t/// @tparam T - The type stored in the array\n\t///\n\t/// @param first - Pointer to the first element in the array\n\t/// @param last - Pointer to the last element in the array\n\t///\n\t/// @return a `Span` over the given array\n\t/// @ingroup utils\n\t/// @headerfile \"Hyperion/Span.h\"\n\ttemplate<typename T>\n\t[[nodiscard]] inline static constexpr auto make_span(T* first, T* last) noexcept -> Span<T> {\n\t\treturn Span(gsl::make_span(first, last));\n\t}\n\n\t/// @brief Creates a `Span` from the given arguments\n\t///\n\t/// @tparam T - The type stored in the array\n\t/// @tparam Size - The size of the array\n\t///\n\t/// @param array - The array to get a `Span` over\n\t///\n\t/// @return a `Span` over the given array\n\t/// @ingroup utils\n\t/// @headerfile \"Hyperion/Span.h\"\n\ttemplate<typename T, usize Size>\n\t[[nodiscard]] inline static constexpr auto\n\tmake_span(T (&array)[Size]) noexcept -> Span<T, Size> { // NOLINT\n\t\treturn Span(gsl::make_span(array));\n\t}\n\n\t/// @brief Creates a `Span` from the given arguments\n\t///\n\t/// @tparam Collection - The collection type to get a `Span` over\n\t///\n\t/// @param collection - The collection to get a `Span` over\n\t///\n\t/// @return a `Span` over the given collection\n\t/// @ingroup utils\n\t/// @headerfile \"Hyperion/Span.h\"\n\ttemplate<typename Collection>\n\t[[nodiscard]] inline static constexpr auto\n\tmake_span(Collection& collection) noexcept -> Span<typename Collection::value_type> {\n\t\treturn Span(gsl::make_span(collection));\n\t}\n\n\t/// @brief Creates a `Span` from the given arguments\n\t///\n\t/// @tparam Collection - The collection type to get a `Span` over\n\t///\n\t/// @param collection - The collection to get a `Span` over\n\t///\n\t/// @return a `Span` over the given collection\n\t/// @ingroup utils\n\t/// @headerfile \"Hyperion/Span.h\"\n\ttemplate<typename Collection>\n\t[[nodiscard]] inline static constexpr auto make_span(const Collection& collection) noexcept\n\t\t-> Span<const typename Collection::value_type> {\n\t\treturn Span(gsl::make_span(collection));\n\t}\n\n\t/// @brief Creates a `Span` from the given arguments\n\t///\n\t/// @tparam SmartPtr - The smart pointer type wrapping the array\n\t///\n\t/// @param array - The smart pointer wrapping the array to get a `Span` over\n\t/// @param size - The size of the array\n\t///\n\t/// @return a `Span` over the given array\n\t/// @ingroup utils\n\t/// @headerfile \"Hyperion/Span.h\"\n\ttemplate<typename SmartPtr>\n\t[[nodiscard]] inline static constexpr auto\n\tmake_span(SmartPtr& array, usize size) noexcept -> Span<typename SmartPtr::element_type> {\n\t\treturn Span(gsl::make_span(array, size));\n\t}\n\n\t/// @brief Creates a `Span` from the given arguments\n\t///\n\t/// @tparam T - The type stored in the array\n\t/// @tparam Size - The size of the array\n\t///\n\t/// @param array - The array to get a `Span` over\n\t///\n\t/// @return a `Span` over the given array\n\t/// @ingroup utils\n\t/// @headerfile \"Hyperion/Span.h\"\n\ttemplate<typename T, usize Size>\n\t[[nodiscard]] inline static constexpr auto\n\tmake_span(std::array<T, Size> array) noexcept -> Span<T, Size> {\n\t\treturn Span(gsl::make_span(array));\n\t}\n\n\tIGNORE_UNUSED_TEMPLATES_STOP\n} // namespace hyperion\n", "meta": {"hexsha": "6e3cb8839b633ed784d675da0e64511dd4a39257", "size": 15297, "ext": "h", "lang": "C", "max_stars_repo_path": "include/Hyperion/Span.h", "max_stars_repo_name": "braxtons12/Hyperion-Utils", "max_stars_repo_head_hexsha": "3873a116e2ea76fc74c9c056925f3740eee6dcd8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/Hyperion/Span.h", "max_issues_repo_name": "braxtons12/Hyperion-Utils", "max_issues_repo_head_hexsha": "3873a116e2ea76fc74c9c056925f3740eee6dcd8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/Hyperion/Span.h", "max_forks_repo_name": "braxtons12/Hyperion-Utils", "max_forks_repo_head_hexsha": "3873a116e2ea76fc74c9c056925f3740eee6dcd8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5744186047, "max_line_length": 99, "alphanum_fraction": 0.6788912859, "num_tokens": 4094, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.05665242052980392, "lm_q2_score": 0.02333076762007485, "lm_q1q2_score": 0.001321744458495613}}
{"text": "#pragma once\n\n#include <gsl.h>\n\n#include <QString>\n\nnamespace gsl {\n    inline QString to_QString(gsl::cstring_span<> view) { return QString::fromLatin1(view.data(), view.size()); }\n}", "meta": {"hexsha": "44b191616ab2993e52c7a860aea6382461349717", "size": 183, "ext": "h", "lang": "C", "max_stars_repo_path": "Modules/SolverSetupService/include/SolverSetupUtils.h", "max_stars_repo_name": "carthurs/CRIMSONGUI", "max_stars_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-09-17T18:55:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T02:52:38.000Z", "max_issues_repo_path": "Modules/SolverSetupService/include/SolverSetupUtils.h", "max_issues_repo_name": "carthurs/CRIMSONGUI", "max_issues_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Modules/SolverSetupService/include/SolverSetupUtils.h", "max_forks_repo_name": "carthurs/CRIMSONGUI", "max_forks_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-05-19T09:02:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-26T17:39:57.000Z", "avg_line_length": 20.3333333333, "max_line_length": 113, "alphanum_fraction": 0.6994535519, "num_tokens": 45, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06097518598415834, "lm_q2_score": 0.02161533378682472, "lm_q1q2_score": 0.0013179989977612988}}
{"text": "#pragma once\n\n#include \"arcana/expected.h\"\n#include \"arcana/functional/inplace_function.h\"\n#include \"arcana/iterators.h\"\n#include \"arcana/type_traits.h\"\n\n#include \"cancellation.h\"\n\n#include <gsl/gsl>\n#include <memory>\n#include <stdexcept>\n\n#include <atomic>\n\nnamespace arcana\n{\n    template<typename ResultT, typename ErrorT>\n    class task_completion_source;\n\n    //\n    // A scheduler that will invoke the continuation inline\n    // right after the previous task.\n    //\n    namespace\n    {\n        constexpr auto inline_scheduler = [](auto&& callable)\n        {\n            callable();\n        };\n    }\n}\n\n#include \"internal/internal_task.h\"\n\nnamespace arcana\n{\n    //\n    //  Generic task system to run work with continuations on a generic scheduler.\n    //\n    //  The scheduler on which tasks are queued must satisfy this contract:\n    //\n    //      struct scheduler\n    //      {\n    //          template<CallableT>\n    //          void queue(CallableT&& callable)\n    //          {\n    //              callable must be usable like this: callable();\n    //          }\n    //      };\n    //\n    template<typename ResultT, typename ErrorT>\n    class task\n    {\n        using payload_t = internal::task_payload_with_return<ResultT, ErrorT>;\n        using payload_ptr = std::shared_ptr<payload_t>;\n\n        static_assert(std::is_same<typename as_expected<ResultT, ErrorT>::value_type, ResultT>::value,\n            \"task can't be of expected<T>\");\n\n    public:\n        using result_type = ResultT;\n        using error_type = ErrorT;\n\n        task() = default;\n\n        task(const task& other) = default;\n        task(task&& other) = default;\n\n        task(const task_completion_source<ResultT, ErrorT>& source)\n            : m_payload{ source.m_payload }\n        {}\n\n        task(task_completion_source<ResultT, ErrorT>&& source)\n            : m_payload{ std::move(source.m_payload) }\n        {}\n\n        task& operator=(task&& other) = default;\n        task& operator=(const task& other) = default;\n\n        bool operator==(const task& other)\n        {\n            return m_payload == other.m_payload;\n        }\n\n        //\n        // Executes a callable on this scheduler once this task is finished and\n        // returns a task that represents the callable.\n        //\n        // Calling .then() on the returned task will queue a task to run after the\n        // callable is run.\n        //\n        template<typename SchedulerT, typename CallableT>\n        auto then(SchedulerT& scheduler, cancellation& token, CallableT&& callable)\n        {\n            using traits = internal::callable_traits<CallableT, result_type>;\n            using wrapper = internal::input_output_wrapper<result_type, error_type, traits::handles_expected::value>;\n\n            static_assert(error_priority<error_type>::value <= error_priority<typename traits::error_propagation_type>::value,\n                \"The error of a parent task needs to be convertible to the error of a child task.\");\n\n            static_assert(std::is_same_v<typename expected_error_or<typename traits::input_type, error_type>::type, error_type>,\n                \"Continuation expected input parameter needs to use the same error type as the parent task\");\n\n            auto factory{ internal::make_task_factory(\n                internal::make_work_payload<typename traits::expected_return_type::value_type, typename traits::error_propagation_type>(\n                    [callable = wrapper::wrap_callable(std::forward<CallableT>(callable), token)]\n                    (internal::base_task_payload* self) mutable noexcept\n                    {\n                        return callable(*static_cast<payload_t*>(self)->Result);\n                    })\n            ) };\n\n            m_payload->create_continuation([&scheduler](auto&& c)\n            {\n                scheduler(std::forward<decltype(c)>(c));\n            }, m_payload, std::move(factory.to_run.m_payload));\n\n            return factory.to_return;\n        }\n\n    private:\n        explicit task(payload_ptr payload)\n            : m_payload{ std::move(payload) }\n        {}\n\n        template<typename OtherResultT, typename OtherErrorT>\n        friend class task;\n\n        friend class task_completion_source<ResultT, ErrorT>;\n\n        template<typename OtherErrorT, typename OtherResultT>\n        friend struct internal::task_factory;\n\n        template<typename SchedulerT, typename CallableT>\n        friend auto make_task(SchedulerT& scheduler, cancellation& token, CallableT&& callable)\n            -> typename internal::task_factory<\n                            typename internal::callable_traits<CallableT, void>::error_propagation_type,\n                            typename internal::callable_traits<CallableT, void>::expected_return_type::value_type>::task_t;\n\n        payload_ptr m_payload;\n    };\n}\n\nnamespace arcana\n{\n    template<typename ResultT, typename ErrorT>\n    class task_completion_source\n    {\n        using payload_t = internal::task_payload_with_return<ResultT, ErrorT>;\n        using payload_ptr = std::shared_ptr<payload_t>;\n\n    public:\n        using result_type = ResultT;\n        using error_type = ErrorT;\n\n        task_completion_source()\n            : m_payload{ std::make_shared<payload_t>() }\n        {}\n\n        //\n        // Completes the task this source represents.\n        //\n        void complete()\n        {\n            static_assert(std::is_same<ResultT, void>::value,\n                \"complete with no arguments can only be used with a void completion source\");\n            m_payload->complete(basic_expected<void, ErrorT>::make_valid());\n        }\n\n        //\n        // Completes the task this source represents.\n        //\n        template<typename ValueT>\n        void complete(ValueT&& value)\n        {\n            m_payload->complete(std::forward<ValueT>(value));\n        }\n\n        //\n        // Returns whether or not the current source has already been completed.\n        //\n        bool completed() const\n        {\n            return m_payload->completed();\n        }\n\n        //\n        // Converts this task_completion_source to a task object for consumers to use.\n        //\n        task<ResultT, ErrorT> as_task() const &\n        {\n            return task<ResultT, ErrorT>{ m_payload };\n        }\n\n        task<ResultT, ErrorT> as_task() &&\n        {\n            return task<ResultT, ErrorT>{ std::move(m_payload) };\n        }\n\n    private:\n        explicit task_completion_source(std::shared_ptr<payload_t> payload)\n            : m_payload{ std::move(payload) }\n        {}\n\n        friend class task<ResultT, ErrorT>;\n        friend class abstract_task_completion_source;\n\n        template<typename E, typename R>\n        friend struct internal::task_factory;\n\n        payload_ptr m_payload;\n    };\n\n    //\n    // a type erased version of task_completion_source.\n    //\n    class abstract_task_completion_source\n    {\n        using payload_t = internal::base_task_payload;\n        using payload_ptr = std::shared_ptr<payload_t>;\n\n    public:\n        abstract_task_completion_source()\n            : m_payload{}\n        {}\n\n        template<typename T, typename E>\n        explicit abstract_task_completion_source(const task_completion_source<T, E>& other)\n            : m_payload{ other.m_payload }\n        {}\n\n        template<typename T, typename E>\n        explicit abstract_task_completion_source(task_completion_source<T, E>&& other)\n            : m_payload{ std::move(other.m_payload) }\n        {}\n\n        //\n        // Returns whether or not the current source has already been completed.\n        //\n        bool completed() const\n        {\n            return m_payload->completed();\n        }\n\n        template<typename T, typename E>\n        bool operator==(const task_completion_source<T, E>& other)\n        {\n            return m_payload == other.m_payload;\n        }\n\n        template<typename T, typename E>\n        task_completion_source<T, E> unsafe_cast()\n        {\n            return task_completion_source<T, E>{ std::static_pointer_cast<internal::task_payload_with_return<T, E>>(m_payload) };\n        }\n\n    private:\n        payload_ptr m_payload;\n    };\n\n    //\n    // creates a task and queues it to run on the given scheduler\n    //\n    template<typename SchedulerT, typename CallableT>\n    inline auto make_task(SchedulerT& scheduler, cancellation& token, CallableT&& callable)\n        -> typename internal::task_factory<\n                            typename internal::callable_traits<CallableT, void>::error_propagation_type,\n                            typename internal::callable_traits<CallableT, void>::expected_return_type::value_type>::task_t\n    {\n        using traits = internal::callable_traits<CallableT, void>;\n        using wrapper = internal::input_output_wrapper<void, typename traits::error_propagation_type, false>;\n\n        auto factory{ internal::make_task_factory(\n            internal::make_work_payload<typename traits::expected_return_type::value_type, typename traits::error_propagation_type>(\n                [callable = wrapper::wrap_callable(std::forward<CallableT>(callable), token)]\n                (internal::base_task_payload*) mutable noexcept\n                {\n                    return callable(basic_expected<void, typename traits::error_propagation_type>::make_valid());\n                })\n        ) };\n\n        scheduler([to_run = std::move(factory.to_run)]\n        {\n            to_run.m_payload->run(nullptr);\n        });\n\n        return factory.to_return;\n    }\n\n    //\n    // creates a completed task from the given result\n    //\n    template<typename ErrorT, typename ResultT>\n    inline task<typename as_expected<ResultT, ErrorT>::value_type, ErrorT> task_from_result(ResultT&& value)\n    {\n        task_completion_source<typename as_expected<ResultT, ErrorT>::value_type, ErrorT> result;\n        result.complete(std::forward<ResultT>(value));\n        return std::move(result);\n    }\n\n    template<typename ErrorT>\n    inline task<void, ErrorT> task_from_result()\n    {\n        task_completion_source<void, ErrorT> result;\n        result.complete();\n        return std::move(result);\n    }\n\n    template<typename ResultT, typename ErrorT>\n    inline task<ResultT, std::error_code> task_from_error(const ErrorT& error)\n    {\n        task_completion_source<ResultT, std::error_code> result;\n        result.complete(make_unexpected(make_error_code(error)));\n        return std::move(result);\n    }\n\n    template<typename ResultT>\n    inline task<ResultT, std::error_code> task_from_error(const std::error_code& error)\n    {\n        task_completion_source<ResultT, std::error_code> result;\n        result.complete(make_unexpected(error));\n        return std::move(result);\n    }\n\n    template<typename ResultT>\n    inline task<ResultT, std::exception_ptr> task_from_error(const std::exception_ptr& error)\n    {\n        task_completion_source<ResultT, std::exception_ptr> result;\n        result.complete(make_unexpected(error));\n        return std::move(result);\n    }\n\n    template<typename ErrorT>\n    inline task<void, ErrorT> when_all(gsl::span<task<void, ErrorT>> tasks)\n    {\n        if (tasks.empty())\n        {\n            return task_from_result<ErrorT>();\n        }\n\n        struct when_all_data\n        {\n            std::mutex mutex;\n            size_t pendingCount;\n            std::error_code error;\n        };\n\n        task_completion_source<void, ErrorT> result;\n        auto data = std::make_shared<when_all_data>();\n        data->pendingCount = tasks.size();\n\n        for (task<void, ErrorT>& task : tasks)\n        {\n            task.then(inline_scheduler, cancellation::none(), [data, result](const basic_expected<void, ErrorT>& exp) mutable noexcept {\n                bool last = false;\n                {\n                    std::lock_guard<std::mutex> guard{ data->mutex };\n\n                    data->pendingCount -= 1;\n                    last = data->pendingCount == 0;\n\n                    if (exp.has_error() && !data->error)\n                    {\n                        // set the first error, as it might have cascaded\n                        data->error = exp.error();\n                    }\n                }\n\n                if (last) // we were the last task to complete\n                {\n                    if (data->error)\n                    {\n                        result.complete(make_unexpected(data->error));\n                    }\n                    else\n                    {\n                        result.complete();\n                    }\n                }\n            });\n        }\n\n        return std::move(result);\n    }\n\n    template<typename T, typename ErrorT>\n    inline task<std::vector<T>, ErrorT> when_all(gsl::span<task<T, ErrorT>> tasks)\n    {\n        if (tasks.empty())\n        {\n            return task_from_result<ErrorT, std::vector<T>>(std::vector<T>());\n        }\n\n        struct when_all_data\n        {\n            std::mutex mutex;\n            size_t pendingCount;\n            std::error_code error;\n            std::vector<T> results;\n        };\n\n        task_completion_source<std::vector<T>, ErrorT> result;\n        auto data = std::make_shared<when_all_data>();\n        data->pendingCount = tasks.size();\n        data->results.resize(tasks.size());\n\n        //using forloop with index to be able to keep proper order of results\n        for (auto idx = 0U; idx < data->results.size(); idx++)\n        {\n            tasks[idx].then(arcana::inline_scheduler, cancellation::none(), [data, result, idx](const basic_expected<T, ErrorT>& exp) mutable noexcept {\n                bool last = false;\n                {\n                    std::lock_guard<std::mutex> guard{ data->mutex };\n\n                    data->pendingCount -= 1;\n                    last = data->pendingCount == 0;\n\n                    if (exp.has_error() && !data->error)\n                    {\n                        // set the first error, as it might have cascaded\n                        data->error = exp.error();\n                    }\n                    if (exp.has_value())\n                    {\n                        data->results[idx] = exp.value();\n                    }\n                }\n\n                if (last) // we were the last task to complete\n                {\n                    if (data->error)\n                    {\n                        result.complete(make_unexpected(data->error));\n                    }\n                    else\n                    {\n                        result.complete(data->results);\n                    }\n                }\n            });\n        }\n\n        return std::move(result);\n    }\n\n    template<typename ErrorT, typename... ArgTs>\n    inline task<std::tuple<typename arcana::void_passthrough<ArgTs>::type...>, ErrorT> when_all(task<ArgTs, ErrorT>... tasks)\n    {\n        using void_passthrough_tuple = std::tuple<typename arcana::void_passthrough<ArgTs>::type...>;\n\n        struct when_all_data\n        {\n            std::mutex mutex;\n            int pending;\n            ErrorT error;\n            void_passthrough_tuple results;\n        };\n  \n        task_completion_source<void_passthrough_tuple, ErrorT> result;\n\n        auto data = std::make_shared<when_all_data>();\n        data->pending = std::tuple_size<void_passthrough_tuple>::value;\n\n        std::tuple<task<ArgTs, ErrorT>&...> taskrefs = std::make_tuple(std::ref(tasks)...);\n\n        iterate_tuple(taskrefs, [&](auto& task, auto idx) {\n            using task_t = std::remove_reference_t<decltype(task)>;\n\n            task.then(inline_scheduler,\n                cancellation::none(),\n                [data, result](const basic_expected<typename task_t::result_type, ErrorT>& exp) mutable noexcept {\n                bool last = false;\n                {\n                    std::lock_guard<std::mutex> guard{ data->mutex };\n\n                    data->pending -= 1;\n                    last = data->pending == 0;\n\n                    internal::write_expected_to_tuple<decltype(idx)::value, ErrorT>(data->results, exp);\n                    \n                    if (exp.has_error() && !data->error)\n                    {\n                        // set the first error, as it might have cascaded\n                        data->error = exp.error();\n                    }\n                }\n\n                if (last) // we were the last task to complete\n                {\n                    if (data->error)\n                    {\n                        result.complete(make_unexpected(data->error));\n                    }\n                    else\n                    {\n                        result.complete(std::move(data->results));\n                    }\n                }\n\n                return basic_expected<void, ErrorT>::make_valid();\n            });\n        });\n        return std::move(result);\n    }\n}\n", "meta": {"hexsha": "762fa6872797110f9a87fe010cb6f4aaf96bc728", "size": 16794, "ext": "h", "lang": "C", "max_stars_repo_path": "Source/Shared/arcana/threading/task.h", "max_stars_repo_name": "syntheticmagus/arcana.cpp", "max_stars_repo_head_hexsha": "57abe0d7a24f2d529a0f22b4ff7cfa60e45b3e0c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-25T10:03:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T10:25:56.000Z", "max_issues_repo_path": "Source/Shared/arcana/threading/task.h", "max_issues_repo_name": "syntheticmagus/arcana.cpp", "max_issues_repo_head_hexsha": "57abe0d7a24f2d529a0f22b4ff7cfa60e45b3e0c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/Shared/arcana/threading/task.h", "max_forks_repo_name": "syntheticmagus/arcana.cpp", "max_forks_repo_head_hexsha": "57abe0d7a24f2d529a0f22b4ff7cfa60e45b3e0c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.124260355, "max_line_length": 152, "alphanum_fraction": 0.5649636775, "num_tokens": 3341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09807931819784702, "lm_q2_score": 0.01342825474196852, "lm_q1q2_score": 0.0013170340696792785}}
{"text": "#ifndef COMMON_STRUCTURES_H_R5TFSBX6\n#define COMMON_STRUCTURES_H_R5TFSBX6\n\n#include <gsl/gsl>\n#include <string_view>\n\nnamespace sens_loc::util {\n\n/// This data is common for all functionality that reads in files in\n/// batch-processing mode.\nstruct processing_input {\n    std::string_view input_pattern;\n    int              start;\n    int              end;\n\n    processing_input(std::string_view input_pattern,\n                     int              start,\n                     int              end) noexcept\n        : input_pattern{input_pattern}\n        , start{start}\n        , end{end} {\n        Expects(!input_pattern.empty());\n        Expects(start <= end);\n    }\n};\n\n}  // namespace sens_loc::util\n\n#endif /* end of include guard: COMMON_STRUCTURES_H_R5TFSBX6 */\n", "meta": {"hexsha": "c61696543878f989562837ee2ca4a9508a1f720e", "size": 770, "ext": "h", "lang": "C", "max_stars_repo_path": "src/apps/util/common_structures.h", "max_stars_repo_name": "JonasToth/depth-conversions", "max_stars_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-09-30T07:09:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T09:14:35.000Z", "max_issues_repo_path": "src/apps/util/common_structures.h", "max_issues_repo_name": "JonasToth/depth-conversions", "max_issues_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/apps/util/common_structures.h", "max_forks_repo_name": "JonasToth/depth-conversions", "max_forks_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6666666667, "max_line_length": 68, "alphanum_fraction": 0.6142857143, "num_tokens": 171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.03514484640079326, "lm_q2_score": 0.0373268908245691, "lm_q1q2_score": 0.0013118478446486604}}
{"text": "#pragma once\n\n#include \"halley/text/halleystring.h\"\n#include \"halley/utils/utils.h\"\n#include <gsl/span>\n\nnamespace Halley\n{\n\tclass Path\n\t{\n\tpublic:\n\t\tPath();\n\t\tPath(const char* name);\n\t\tPath(const std::string& name);\n\t\tPath(const String& name);\n\n\t\tPath(const Path& other) = default;\n\t\tPath(Path&& other) noexcept = default;\n\t\tPath& operator=(const Path& other) = default;\n\t\tPath& operator=(Path&& other) noexcept = default;\n\n\t\tPath& operator=(const std::string& other);\n\t\tPath& operator=(const String& other);\n\n\t\tPath getRoot() const;\n\t\tPath getFront(size_t n) const;\n\t\tPath getFilename() const;\n\t\tPath getStem() const;\n\t\tString getExtension() const;\n\t\tString getString() const;\n\t\tString getNativeString() const;\n\t\tString toString() const;\n\n\t\tsize_t getNumberPaths() const;\n\n\t\tPath dropFront(int numberFolders) const;\n\n\t\tPath parentPath() const;\n\t\tPath replaceExtension(String newExtension) const;\n\n\t\tPath operator/(const char* other) const;\n\t\tPath operator/(const Path& other) const;\n\t\tPath operator/(const String& other) const;\n\t\tPath operator/(const std::string& other) const;\n\n\t\tbool operator==(const char* other) const;\n\t\tbool operator==(const String& other) const;\n\t\tbool operator==(const Path& other) const;\n\n\t\tbool operator!=(const Path& other) const;\n\t\tbool operator<(const Path& other) const;\n\n\t\tstd::string string() const;\n\n\t\tstatic void writeFile(const Path& path, gsl::span<const gsl::byte> data);\n\t\tstatic void writeFile(const Path& path, const Bytes& data);\n\t\tstatic void writeFile(const Path& path, const String& data);\n\t\tstatic Bytes readFile(const Path& path);\n\t\tstatic void removeFile(const Path& path);\n\n\t\tPath makeRelativeTo(const Path& path) const;\n\t\tPath changeRelativeRoot(const Path& currentParent, const Path& newParent) const;\n\n\t\tbool isDirectory() const;\n\t\tbool isFile() const;\n\t\tbool isAbsolute() const;\n\t\tbool isEmpty() const;\n\n\tprivate:\n\t\tVector<String> pathParts;\n\t\tvoid normalise();\n\t\tvoid setPath(const String& value);\n\n\t\texplicit Path(Vector<String> parts);\n\t};\n\n\tusing TimestampedPath = std::pair<Path, int64_t>;\n}\n", "meta": {"hexsha": "7f83b6fffd240f2048f3fb368c4875f059a211fc", "size": 2051, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engine/utils/include/halley/file/path.h", "max_stars_repo_name": "amrezzd/halley", "max_stars_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/engine/utils/include/halley/file/path.h", "max_issues_repo_name": "amrezzd/halley", "max_issues_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engine/utils/include/halley/file/path.h", "max_forks_repo_name": "amrezzd/halley", "max_forks_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9620253165, "max_line_length": 82, "alphanum_fraction": 0.7142857143, "num_tokens": 508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.05834584388645592, "lm_q2_score": 0.021948255234279814, "lm_q1q2_score": 0.001280589473479379}}
{"text": "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\n#pragma once\n\n#include \"core/common/inlined_containers_fwd.h\"\n#include \"core/framework/kernel_registry.h\"\n#include \"core/graph/graph_viewer.h\"\n#include <gsl/gsl>\n\nnamespace onnxruntime {\n\n/**\n  Returns a list of nodes that are preferred on CPU.\n  They are commonly shape-related computation subgraphs.\n  @param graph Graph viewer\n  @param provider_type The target execution provider type\n  @param kernel_registries Kernel registries for the target EP\n  @param tentative_nodes Nodes that are tentative to be placed on on target EP\n  */\nInlinedHashSet<NodeIndex> GetCpuPreferredNodes(const GraphViewer& graph,\n                                               const std::string& provider_type,\n                                               gsl::span<const KernelRegistry* const> kernel_registries,\n                                               gsl::span<const NodeIndex> tentative_nodes);\n\n}  // namespace onnxruntime\n", "meta": {"hexsha": "fda5fdb188d1eec251e213e12fceb1130305b3c2", "size": 1012, "ext": "h", "lang": "C", "max_stars_repo_path": "onnxruntime/core/framework/fallback_cpu_capability.h", "max_stars_repo_name": "anwang2009/onnxruntime", "max_stars_repo_head_hexsha": "f4fd67cc2c55730ef15e589870eec8a3d19b16ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-09T21:24:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T21:24:30.000Z", "max_issues_repo_path": "onnxruntime/core/framework/fallback_cpu_capability.h", "max_issues_repo_name": "Grimig/onnxruntime", "max_issues_repo_head_hexsha": "4ef81b142dbd29abc3c64797084b8e61cf3212d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "onnxruntime/core/framework/fallback_cpu_capability.h", "max_forks_repo_name": "Grimig/onnxruntime", "max_forks_repo_head_hexsha": "4ef81b142dbd29abc3c64797084b8e61cf3212d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4814814815, "max_line_length": 104, "alphanum_fraction": 0.6788537549, "num_tokens": 196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06008664680776121, "lm_q2_score": 0.021287350745669575, "lm_q1q2_score": 0.00127908552572798}}
{"text": "#pragma once\n\n#include <cstddef>\n#include <cstdint>\n#include <functional>\n#include <initializer_list>\n#include <memory>\n#include <numeric>\n#include <set>\n#include <utility>\n#include <vector>\n\n#include <absl/container/flat_hash_map.h>\n#include <gsl/gsl>\n\n#include \"chainerx/array.h\"\n#include \"chainerx/array_body.h\"\n#include \"chainerx/array_node.h\"\n#include \"chainerx/constant.h\"\n#include \"chainerx/device.h\"\n#include \"chainerx/dtype.h\"\n#include \"chainerx/graph.h\"\n#include \"chainerx/macro.h\"\n#include \"chainerx/op_node.h\"\n#include \"chainerx/shape.h\"\n\nnamespace chainerx {\nnamespace backward_builder_detail {\n\n// This class is used by the BackwardBuilder to record retained inputs and outputs.\n// The records are used to create outer graph edges (between op nodes and previous array nodes) when the builder is finalized.\nclass RetentionRecord {\npublic:\n    explicit RetentionRecord(size_t size) : size_{size} { CHAINERX_ASSERT(size_ > 0); }\n\n    size_t size() const { return size_; }\n\n    void Record(size_t index) {\n        if (flags_.empty()) {\n            flags_.resize(size_);\n        }\n        gsl::at(flags_, index) = static_cast<int8_t>(true);\n    }\n\n    bool IsAnyRecorded() const { return !flags_.empty(); }\n\n    bool IsRecorded(size_t index) const { return static_cast<bool>(flags_[index]); }\n\nprivate:\n    size_t size_{};\n    std::vector<int8_t> flags_{};  // binary flags\n};\n\ntemplate <typename Tag>\nclass RetainedArrayToken {\npublic:\n    RetainedArrayToken(internal::ArrayBody::Params array_params, size_t index) : array_params_{std::move(array_params)}, index_{index} {}\n\n    ~RetainedArrayToken() = default;\n\n    RetainedArrayToken(const RetainedArrayToken&) = default;\n    RetainedArrayToken(RetainedArrayToken&&) noexcept = default;\n    RetainedArrayToken& operator=(const RetainedArrayToken&) = default;\n    // TODO(hvy): Make the move assignment operator noexcept.\n    RetainedArrayToken& operator=(RetainedArrayToken&&) = default;  // NOLINT(performance-noexcept-move-constructor)\n\nprivate:\n    friend class chainerx::BackwardContext;\n\n    // Returns the array index.\n    size_t index() const { return index_; }\n\n    const internal::ArrayBody::Params& array_params() const { return array_params_; }\n\n    internal::ArrayBody::Params array_params_;\n\n    size_t index_;\n};\n\n}  // namespace backward_builder_detail\n\n// An object used by op implementations to bridge between BackwardBuilder::RetainInput() and BackwardContext::GetRetainedInput().\n//\n// See BackwardBuilder::RetainInput() for details.\nusing RetainedInputToken = backward_builder_detail::RetainedArrayToken<struct InputTag>;\n\n// An object used by op implementations to bridge between BackwardBuilder::RetainOutput() and BackwardContext::GetRetainedOutput().\n//\n// See BackwardBuilder::RetainOutput() for details.\nusing RetainedOutputToken = backward_builder_detail::RetainedArrayToken<struct OutputTag>;\n\n// A class that is used to define backward operations and connect the graph.\n//\n// This class is not thread safe.\nclass BackwardBuilder {\npublic:\n    // Target is responsible to define edges from OpNode to input ArrayNodes with given BackwardFunction.\n    // Note that Targets built from the same BackwardBuilder share some properties not to compute again.\n    class Target {\n    public:\n        explicit operator bool() const { return is_definition_required(); }\n\n        // Defines a backward function with respect to specified input arrays (target).\n        void Define(const BackwardFunction& backward_func);\n\n        bool is_definition_required() const { return !graph_to_input_array_nodes_.empty(); }\n\n    private:\n        friend class BackwardBuilder;  // Only BackwardBuilder can create Target\n\n        using InputArrayNodes = std::vector<const std::shared_ptr<internal::ArrayNode>*>;\n\n        Target(BackwardBuilder& builder, std::vector<size_t> input_indices);\n\n        // Collect input ArrayNodes, grouped by graph considering IsBackpropRequired.\n        // This functions is only called once in the constructor.\n        absl::flat_hash_map<BackpropId, InputArrayNodes> CreateInputArrayNodesMap() const;\n\n        BackwardBuilder& builder_;\n        std::vector<size_t> input_indices_;\n\n        // TODO(hvy): Consider using linear search since elements are usually few.\n        absl::flat_hash_map<BackpropId, InputArrayNodes> graph_to_input_array_nodes_;\n    };\n\n    // TODO(niboshi): Add an overload to accept `const std::vector<Array>&` as `inputs` and `outputs`\n    // Note that simply overloading with the above type will results in ambiguous calls.\n    // One solution is to define a type that accepts all of the expected types of inputs.\n    BackwardBuilder(const char* op_name, std::vector<ConstArrayRef> inputs, std::vector<ConstArrayRef> outputs);\n    BackwardBuilder(const char* op_name, const Array& input, std::vector<ConstArrayRef> outputs)\n        : BackwardBuilder{op_name, std::vector<ConstArrayRef>{input}, std::move(outputs)} {}\n    BackwardBuilder(const char* op_name, std::vector<ConstArrayRef> inputs, const Array& output)\n        : BackwardBuilder{op_name, std::move(inputs), std::vector<ConstArrayRef>{output}} {}\n    BackwardBuilder(const char* op_name, const Array& input, const Array& output)\n        : BackwardBuilder{op_name, std::vector<ConstArrayRef>{input}, std::vector<ConstArrayRef>{output}} {}\n    ~BackwardBuilder() { CHAINERX_ASSERT(is_finalized_); }\n\n    BackwardBuilder(const BackwardBuilder&) = delete;\n    BackwardBuilder(BackwardBuilder&&) noexcept = default;\n    BackwardBuilder& operator=(const BackwardBuilder&) = delete;\n    BackwardBuilder& operator=(BackwardBuilder&&) = delete;\n\n    // Creates a backward target for the specified inputs.\n    Target CreateTarget(std::vector<size_t> input_indices) {\n        // input_indices shouldn't have duplicates.\n        CHAINERX_ASSERT((std::set<size_t>{input_indices.begin(), input_indices.end()}.size() == input_indices.size()));\n\n        for (size_t input_index : input_indices) {\n            CHAINERX_ASSERT(input_index < inputs_target_created_.size());\n            CHAINERX_ASSERT(!inputs_target_created_[input_index]);\n            inputs_target_created_[input_index] = true;\n        }\n        return Target{*this, std::move(input_indices)};\n    }\n\n    // Creates a backward target for the specified input.\n    Target CreateTarget(size_t input_index) { return CreateTarget(std::vector<size_t>{input_index}); }\n\n    // Creates a backward target for all the inputs.\n    Target CreateTarget() {\n        std::vector<size_t> input_indices;\n        input_indices.resize(inputs_.size());\n        std::iota(input_indices.begin(), input_indices.end(), size_t{0});\n\n        return CreateTarget(std::move(input_indices));\n    }\n\n    // TODO(hvy): Write comment.\n    RetainedInputToken RetainInput(size_t input_index);\n\n    std::vector<RetainedInputToken> RetainInput(std::vector<size_t> indices);\n\n    // Flags an output array to be retained for use in the backward pass.\n    // Op implementations can use this function in combination with BackwardContext::GetRetainedOutput() to retrieve output arrays in the\n    // backward pass.\n    //\n    // If an op implementation requires the output array of the forward pass in the backward pass, it should call\n    // BackwardBuilder::RetainOutput() in the forward pass and keep its return value (either assign a variable or capture by\n    // value in a lambda expression). In the backward pass, it should call BackwardContext::GetRetainedOutput() with this token to retrieve\n    // the output array.\n    //\n    // Capturing the output array directly with lambda expression would cause cyclic reference and therefore would lead to memory leak.\n    //\n    // Reusing the token for higher-order backward functions results in undefined behavior.\n    //\n    // `output` must be one of the arrays specified in the constructor of BackwardBuilder as output arrays.\n    // If invalid array is specified, ChainerxError will be thrown.\n    RetainedOutputToken RetainOutput(size_t output_index);\n    std::vector<RetainedOutputToken> RetainOutput(std::vector<size_t> indices);\n\n    // Finalizes the builder.\n    //\n    // This functions must be called when targets have been created for all inputs.\n    void Finalize();\n\nprivate:\n    // Create an op node for a specific graph.\n    // Edges from output nodes to the op node are connected.\n    std::shared_ptr<internal::OpNode>& FindOrCreateOpNode(const BackpropId& backprop_id);\n\n    // Add shared ptrs between op nodes and array nodes belonging to outer graphs.\n    // This functions is called once when the builder is finalized.\n    // These references are required to restore retained inputs/outputs.\n    void AddEdgesFromOpNodeToArrayNodeOfOuterGraphsForRetention();\n\n    void ConnectBackpropIds();\n\n    const char* op_name_;\n\n    Context& context_;\n\n    // Input arrays of the op.\n    std::vector<ConstArrayRef> inputs_;\n\n    // Flags indicating whether CreateTarget has been called for each of the input arrays.\n    // All of these flags must be true after all the backwards have been defined for a BackwardBuilder.\n    // This can be checked by calling is_complete();\n    std::vector<bool> inputs_target_created_;\n\n    // Output arrays of the op.\n    std::vector<ConstArrayRef> outputs_;\n\n    // A collection of op nodes, each of which corresponds to a graph.\n    // This record is increasingly populated as new graphs are encountered in multiple Define() calls.\n    absl::flat_hash_map<BackpropId, std::shared_ptr<internal::OpNode>> op_node_map_;\n\n    backward_builder_detail::RetentionRecord input_retention_record_;\n    backward_builder_detail::RetentionRecord output_retention_record_;\n\n    bool has_any_applicable_outputs_;\n    bool is_finalized_{false};\n};\n\n}  // namespace chainerx\n", "meta": {"hexsha": "aafa29e403c7ae51b50050d55f36c4094b8a3aca", "size": 9750, "ext": "h", "lang": "C", "max_stars_repo_path": "chainerx_cc/chainerx/backward_builder.h", "max_stars_repo_name": "zjzh/chainer", "max_stars_repo_head_hexsha": "e9da1423255c58c37be9733f51b158aa9b39dc93", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3705.0, "max_stars_repo_stars_event_min_datetime": "2017-06-01T07:36:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T10:46:15.000Z", "max_issues_repo_path": "chainerx_cc/chainerx/backward_builder.h", "max_issues_repo_name": "zjzh/chainer", "max_issues_repo_head_hexsha": "e9da1423255c58c37be9733f51b158aa9b39dc93", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5998.0, "max_issues_repo_issues_event_min_datetime": "2017-06-01T06:40:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T01:42:44.000Z", "max_forks_repo_path": "chainerx_cc/chainerx/backward_builder.h", "max_forks_repo_name": "zjzh/chainer", "max_forks_repo_head_hexsha": "e9da1423255c58c37be9733f51b158aa9b39dc93", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1150.0, "max_forks_repo_forks_event_min_datetime": "2017-06-02T03:39:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T02:29:32.000Z", "avg_line_length": 41.4893617021, "max_line_length": 139, "alphanum_fraction": 0.7310769231, "num_tokens": 2202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09670579850281288, "lm_q2_score": 0.013222822116861469, "lm_q1q2_score": 0.0012787235712717429}}
{"text": "//\n//  Encoder.h\n//  PretendToWork\n//\n//  Created by tqtifnypmb on 08/12/2017.\n//  Copyright \u00a9 2017 tqtifnypmb. All rights reserved.\n//\n\n#pragma once\n\n#include \"../types.h\"\n\n#include <string>\n#include <gsl/gsl>\n\nnamespace brick\n{\n\nstruct ASCIIConverter {\n    typedef std::string result_type;\n    \n    static detail::CodePointList encode(gsl::span<const char> bytes);\n    static result_type decode(const detail::CodePointList& cplist);\n};\n    \n//struct UTF8Converter {\n//    typedef std::string result_type;\n//    \n//    static detail::CodePointList encode(gsl::span<const char> bytes);\n//    static result_type decode(const detail::CodePointList& cplist);\n//    static size_t numOfLine(const detail::CodePointList& cplist);\n//};\n//    \n}   // namespace brick\n", "meta": {"hexsha": "269df9cd22ac1516a87cb952320a605d94aa62d0", "size": 759, "ext": "h", "lang": "C", "max_stars_repo_path": "src/converter/Converter.h", "max_stars_repo_name": "tqtifnypmb/brick", "max_stars_repo_head_hexsha": "49398f77113c57d4e256e838a5ad6b9a6381de6a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/converter/Converter.h", "max_issues_repo_name": "tqtifnypmb/brick", "max_issues_repo_head_hexsha": "49398f77113c57d4e256e838a5ad6b9a6381de6a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/converter/Converter.h", "max_forks_repo_name": "tqtifnypmb/brick", "max_forks_repo_head_hexsha": "49398f77113c57d4e256e838a5ad6b9a6381de6a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.6857142857, "max_line_length": 71, "alphanum_fraction": 0.6864295125, "num_tokens": 200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06097518598415834, "lm_q2_score": 0.020964239747678845, "lm_q1q2_score": 0.0012782984176312022}}
{"text": "/**\n * This file is part of the \"libterminal\" project\n *   Copyright (c) 2019-2020 Christian Parpart <christian@parpart.family>\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#pragma once\n\n#include <text_shaper/font.h>\n\n#include <fmt/format.h>\n\n#include <gsl/span>\n#include <gsl/span_ext>\n\n#include <optional>\n#include <variant>\n#include <vector>\n\nnamespace text\n{\n\n/// Holds the system path to a font file.\nstruct font_path\n{\n    std::string value;\n};\n\n/// Holds a view into the contents of a font file.\nstruct font_memory_ref\n{\n    std::string identifier;  //!< a unique identifier for this font\n    gsl::span<uint8_t> data; //!< font file contents (non-owned)\n};\n\n/// Represents a font source (such as file path or memory).\nusing font_source = std::variant<font_path, font_memory_ref>;\n\n/// Holds a list of fonts.\nusing font_source_list = std::vector<font_source>;\n\n/**\n * Font location API.\n *\n * Used for locating fonts and fallback fonts to be used\n * for text shaping and glyph rendering.\n */\nclass font_locator\n{\n  public:\n    virtual ~font_locator() = default;\n\n    /**\n     * Enumerates all available fonts.\n     */\n    virtual font_source_list all() = 0;\n\n    /**\n     * Locates the font matching the given description the best\n     * and an ordered list of fallback fonts.\n     */\n    virtual font_source_list locate(font_description const& description) = 0;\n\n    /**\n     * Resolves the given codepoint sequence into an ordered list of\n     * possible fonts that can be used for text shaping the given\n     * codepoint sequence.\n     */\n    virtual font_source_list resolve(gsl::span<const char32_t> codepoints) = 0;\n};\n\n} // namespace text\n\nnamespace fmt // {{{\n{\ntemplate <>\nstruct formatter<text::font_path>\n{\n    template <typename ParseContext>\n    constexpr auto parse(ParseContext& ctx)\n    {\n        return ctx.begin();\n    }\n    template <typename FormatContext>\n    auto format(text::font_path path, FormatContext& ctx)\n    {\n        return fmt::format_to(ctx.out(), \"path {}\", path.value);\n    }\n};\n\ntemplate <>\nstruct formatter<text::font_memory_ref>\n{\n    template <typename ParseContext>\n    constexpr auto parse(ParseContext& ctx)\n    {\n        return ctx.begin();\n    }\n    template <typename FormatContext>\n    auto format(text::font_memory_ref ref, FormatContext& ctx)\n    {\n        return fmt::format_to(ctx.out(), \"in-memory: {}\", ref.identifier);\n    }\n};\n\ntemplate <>\nstruct formatter<text::font_source>\n{\n    template <typename ParseContext>\n    constexpr auto parse(ParseContext& ctx)\n    {\n        return ctx.begin();\n    }\n    template <typename FormatContext>\n    auto format(text::font_source source, FormatContext& ctx)\n    {\n        if (std::holds_alternative<text::font_path>(source))\n            return fmt::format_to(ctx.out(), \"{}\", std::get<text::font_path>(source));\n        if (std::holds_alternative<text::font_memory_ref>(source))\n            return fmt::format_to(ctx.out(), \"{}\", std::get<text::font_memory_ref>(source));\n        return fmt::format_to(ctx.out(), \"UNKNOWN SOURCE\");\n    }\n};\n} // namespace fmt\n", "meta": {"hexsha": "e445137bb02f014d80c62ec1e0fb6245af484a9f", "size": 3484, "ext": "h", "lang": "C", "max_stars_repo_path": "src/text_shaper/font_locator.h", "max_stars_repo_name": "christianparpart/libterminal", "max_stars_repo_head_hexsha": "0e6d75a2042437084c9f9880a5c8b5661a02da07", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-08-14T22:29:57.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-19T08:57:15.000Z", "max_issues_repo_path": "src/text_shaper/font_locator.h", "max_issues_repo_name": "christianparpart/libterminal", "max_issues_repo_head_hexsha": "0e6d75a2042437084c9f9880a5c8b5661a02da07", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 69.0, "max_issues_repo_issues_event_min_datetime": "2019-08-17T18:57:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-22T23:25:49.000Z", "max_forks_repo_path": "src/text_shaper/font_locator.h", "max_forks_repo_name": "christianparpart/libterminal", "max_forks_repo_head_hexsha": "0e6d75a2042437084c9f9880a5c8b5661a02da07", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1954887218, "max_line_length": 92, "alphanum_fraction": 0.6782433984, "num_tokens": 800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.04401864735472289, "lm_q2_score": 0.02887090705073527, "lm_q1q2_score": 0.0012708582762772987}}
{"text": "/*\n\nCopyright (C) 2019-2021  Jan BOON (Kaetemi) <jan.boon@kaetemi.be>\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n1. Redistributions of source code must retain the above copyright notice, this\n   list of conditions and the following disclaimer.\n2. Redistributions in binary form must reproduce the above copyright notice,\n   this list of conditions and the following disclaimer in the documentation\n   and/or other materials provided with the distribution.\n3. Neither the name of the copyright holder nor the names of its contributors\n   may be used to endorse or promote products derived from this software\n   without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*/\n\n/*\n\nPolyverse O\u00dc base include file for C++.\n\n*/\n\n#pragma once\n#ifndef SEV_PLATFORM_H\n#define SEV_PLATFORM_H\n\n// Use C math defines for M_PI\n#define _USE_MATH_DEFINES\n\n#ifdef _WIN32\n// Include Win32.\n// Ensure malloc is included before anything else,\n// There are some odd macros that may conflict otherwise.\n// Include STL algorithm to ensure std::min and std::max\n// are used everywhere, instead of min and max macros.\n#define WIN32_LEAN_AND_MEAN\n#define _WIN32_WINNT 0x0600\n#ifdef __cplusplus\n#define NOMINMAX\n#endif /* __cplusplus */\n#include <malloc.h>\n#ifdef __cplusplus\n#include <algorithm>\nusing std::max;\nusing std::min;\n#endif /* __cplusplus */\n#include <Windows.h>\n#ifdef _MSC_VER\n// #include <codeanalysis\\sourceannotations.h>\n#endif\n#endif /* _WIN32 */\n\n// C++\n#ifdef __cplusplus\n\n// Require C++17\n#if defined(_MSC_VER) && (!defined(_HAS_CXX17) || !_HAS_CXX17)\nstatic_assert(false, \"C++17 is required\");\n#endif\n\n// Define null, with color highlight\n#ifndef null\nconstexpr decltype(nullptr) null = nullptr;\n#define null null\n#endif\n\n// Include STL string and allow string literals.\n// Always use sv suffix when declaring string literals.\n// Ideally, assign them as `constexpr std::string_view`.\n#include <string>\n#include <string_view>\nusing namespace std::string_literals;\nusing namespace std::string_view_literals;\n\n// Include GSL\n// auto _ = gsl::finally([&] { delete xyz; });\n#include <gsl/util>\n\n// The usual\n#include <functional>\n\n// Force inline\n#ifdef _MSC_VER\n#\tdefine SEV_FORCE_INLINE __forceinline\n#else\n#\tdefine SEV_FORCE_INLINE inline __attribute__((always_inline))\n#endif\n\n#if defined(_DEBUG) && !defined(NDEBUG)\n#define SEV_DEBUG\n#else\n#define SEV_RELEASE\n#endif\n\n// Include debug_break\n#include <debugbreak.h>\n#define SEV_RELEASE_BREAK() debug_break()\n\n#ifdef SEV_DEBUG\n#define SEV_DEBUG_BREAK() debug_break()\n#define SEV_ASSERT(cond) do { if (!(cond)) SEV_DEBUG_BREAK(); } while (false)\n#define SEV_VERIFY(cond) do { if (!(cond)) SEV_DEBUG_BREAK(); } while (false)\n#else\n#define SEV_DEBUG_BREAK() do { } while (false)\n#define SEV_ASSERT(cond) do { } while (false)\n#define SEV_VERIFY(cond) do { cond; } while (false)\n#endif\n\n// Library export decl\n#ifdef _MSC_VER\n#\tdefine SEV_DECL_EXPORT __declspec(dllexport)\n#\tdefine SEV_DECL_IMPORT __declspec(dllimport)\n#else\n#\tdefine SEV_DECL_EXPORT\n#\tdefine SEV_DECL_IMPORT\n#endif\n\n#if defined(SEV_LIB_EXPORT)\n#ifdef _MSC_VER\n#endif\n#  define SEV_LIB SEV_DECL_EXPORT\n#elif defined(SEV_LIB_STATIC)\n#  define SEV_LIB\n#else\n#  define SEV_LIB SEV_DECL_IMPORT\n#endif\n\n#endif /* __cplusplus */\n\n#endif /* SEV_PLATFORM_H */\n\n/* end of file */\n", "meta": {"hexsha": "c33021f6b0af5912f7a285f701e29681805971e6", "size": 4140, "ext": "h", "lang": "C", "max_stars_repo_path": "sev/platform.h", "max_stars_repo_name": "kaetemi/libsev", "max_stars_repo_head_hexsha": "72cfb0494a1ca5a5a0b637237d82937c8efd670c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-08-16T04:32:32.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-16T04:32:32.000Z", "max_issues_repo_path": "sev/platform.h", "max_issues_repo_name": "kaetemi/libsev", "max_issues_repo_head_hexsha": "72cfb0494a1ca5a5a0b637237d82937c8efd670c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sev/platform.h", "max_forks_repo_name": "kaetemi/libsev", "max_forks_repo_head_hexsha": "72cfb0494a1ca5a5a0b637237d82937c8efd670c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-14T20:01:08.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-14T20:01:08.000Z", "avg_line_length": 28.3561643836, "max_line_length": 78, "alphanum_fraction": 0.7678743961, "num_tokens": 971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.04813676975110368, "lm_q2_score": 0.026355354519010193, "lm_q1q2_score": 0.0012686616321903037}}
{"text": "#pragma once\n#include \"Common.h\"\n#include \"PEFile.h\"\n#include \"ImportedModule.h\"\n\n#include <gsl/gsl>\n\nnamespace winlogo::pe_parser {\n\nnamespace details {\n\n/**\n * This is an input iterator for iterating over the imported modules of an import directory.\n */\nclass ImportDirectoryIterator {\npublic:\n    ImportDirectoryIterator(PEFile file, gsl::span<IMAGE_IMPORT_DESCRIPTOR>::iterator iterator);\n\n    bool operator==(const ImportDirectoryIterator& other) const noexcept;\n    bool operator!=(const ImportDirectoryIterator& other) const noexcept;\n\n    ImportedModule operator*() const noexcept;\n    ImportDirectoryIterator& operator++() noexcept;\n\nprivate:\n    PEFile m_peFile;\n    gsl::span<IMAGE_IMPORT_DESCRIPTOR>::iterator m_current;\n};\n\n}  // namespace details\n\n/**\n * This class represents an iterable view of a PE file's import directory.\n */\nclass ImportDirectory {\npublic:\n    /**\n     * Initialize the import directory from its PE file.\n     */\n    explicit ImportDirectory(PEFile peFile);\n\n    /**\n     * Get the raw import descriptors.\n     */\n    gsl::span<IMAGE_IMPORT_DESCRIPTOR> rawImportDescriptors() const noexcept;\n\n    // Iterators for iterating over the imported modules.\n\n    details::ImportDirectoryIterator begin() const noexcept;\n    details::ImportDirectoryIterator end() const noexcept;\n\nprivate:\n    /// The owning PE file.\n    PEFile m_peFile;\n    gsl::span<IMAGE_IMPORT_DESCRIPTOR> m_importDescriptors;\n};\n\n}  // namespace winlogo::pe_parser\n", "meta": {"hexsha": "5fadf567123d447335f8475a381843bafc4770d1", "size": 1467, "ext": "h", "lang": "C", "max_stars_repo_path": "winlogo_core/ImportDirectory.h", "max_stars_repo_name": "shsh999/WinLogo", "max_stars_repo_head_hexsha": "9ad51469e3ed4bb593303d4d7919c484a3be092e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2021-09-04T22:10:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T07:18:03.000Z", "max_issues_repo_path": "winlogo_core/ImportDirectory.h", "max_issues_repo_name": "shsh999/WinLogo", "max_issues_repo_head_hexsha": "9ad51469e3ed4bb593303d4d7919c484a3be092e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-23T01:01:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-29T12:13:05.000Z", "max_forks_repo_path": "winlogo_core/ImportDirectory.h", "max_forks_repo_name": "shsh999/WinLogo", "max_forks_repo_head_hexsha": "9ad51469e3ed4bb593303d4d7919c484a3be092e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-20T12:06:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T12:06:02.000Z", "avg_line_length": 24.8644067797, "max_line_length": 96, "alphanum_fraction": 0.7300613497, "num_tokens": 309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.04958902157944974, "lm_q2_score": 0.025565214665694145, "lm_q1q2_score": 0.0012677539817403719}}
{"text": "\n#if !defined(INDENTCLASSIFIER_H_INCLUDED)\n#define INDENTCLASSIFIER_H_INCLUDED\n\n#include \"FileEnumerator.h\"\n#include \"Utils.h\"\n\n#include <filesystem>\n#include <gsl/gsl>\n#include <iosfwd>\n#include <map>\n#include <string>\n\n/// \\brief IndentType contains the enum constants that indicate the type of\n/// indentation for a line of text or a text file.\nenum class IndentType\n{\n\tspace, ///< Indents consist entirely of spaces\n\ttab, ///< Indents consist entirely of tabs\n\tjavadocTab,\t///< Indents are entirely tabs or tabs followed by exactly one space and asterisk, as in a tab-indented JavaDoc comment\n\tjavadocLeft,\t///< Indented exactly one space followed by an asterisk, as in an unindented JavaDoc comment (single-line only)\n\tmixed, ///< Indents are mixed tabs and spaces, or some are tabs and others are spaces\n\tindeterminate ///< Refers to lines with no whitespace indent\n};\n\nusing LineTypeCounts = ::std::map<IndentType, size_t>;\n\n/// \\brief The same as lineTypeCounts.at(indentType) except that it returns zero\n/// if the map does not contain an entry for indentType.\nsize_t get(const LineTypeCounts& lineTypeCounts, IndentType indentType);\n\nclass IndentClassifier\n{\npublic:\n\tstatic int usage(::std::ostream& strm, const ::std::string& progName, const char* pMsg);\n\n\tIndentClassifier(::gsl::span<const char*const> args);\n\tint run() const;\n\n\tIndentClassifier(const IndentClassifier&) = delete;\n\tIndentClassifier& operator=(const IndentClassifier&) = delete;\n\tIndentClassifier(IndentClassifier&&) = delete;\n\tIndentClassifier& operator=(IndentClassifier&&) = delete;\n\nPRIVATE_EXCEPT_IN_TEST:\n\tusing Path = ::std::filesystem::path;\n\n\tvoid processFile(const Path& p) const;\n\tstatic char indicatorLetter(IndentType iType);\n\tstatic ::std::string displayPath(const Path& p);\n\n\t/// \\brief Scans the input stream and counts lines of the various indent types.\n\tstatic LineTypeCounts scanFile(const Path& p);\n\tstatic LineTypeCounts scanFile(::std::istream& in, bool isJavaFile);\n\tstatic IndentType classifyLine(const ::std::string& line, bool isJavaFile);\n\tstatic IndentType classifyFile(const LineTypeCounts& lineTypeCounts);\n\n\tFileEnumerator m_fileEnumerator;\n};\n\n#endif // INDENTCLASSIFIER_H_INCLUDED\n", "meta": {"hexsha": "6d1bd83a38410648cbcb48dd15cc89a10ce27d3a", "size": 2194, "ext": "h", "lang": "C", "max_stars_repo_path": "IndentClassifier.h", "max_stars_repo_name": "IanEmmons/CmdLineUtil", "max_stars_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "IndentClassifier.h", "max_issues_repo_name": "IanEmmons/CmdLineUtil", "max_issues_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IndentClassifier.h", "max_forks_repo_name": "IanEmmons/CmdLineUtil", "max_forks_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3870967742, "max_line_length": 132, "alphanum_fraction": 0.7670920693, "num_tokens": 523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08269733589276139, "lm_q2_score": 0.015189051984261672, "lm_q1q2_score": 0.0012560941338351013}}
{"text": "/// @file PosixDomain.h\n/// @author Braxton Salyer <braxtonsalyer@gmail.com>\n/// @brief `StatusCodeDomain` supporting platform-implementation-specific values of `errno` in\n/// addition to those __required__ by POSIX\n/// @version 0.1\n/// @date 2021-11-10\n///\n/// MIT License\n/// @copyright Copyright (c) 2021 Braxton Salyer <braxtonsalyer@gmail.com>\n///\n/// Permission is hereby granted, free of charge, to any person obtaining a copy\n/// of this software and associated documentation files (the \"Software\"), to\n/// deal in the Software without restriction, including without limitation the\n/// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n/// sell copies of the Software, and to permit persons to whom the Software is\n/// furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in\n/// all copies or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n/// IN THE SOFTWARE.\n#pragma once\n\n#include <Hyperion/error/GenericDomain.h>\n#include <Hyperion/error/StatusCode.h>\n#include <cstring>\n#include <gsl/gsl>\n\nnamespace hyperion::error {\n\n\tclass PosixDomain;\n\n\tusing PosixStatusCode = StatusCode<PosixDomain>;\n\tusing PosixErrorCode = ErrorCode<PosixDomain>;\n\n\t/// @brief `PosixDomain` is the `StatusCodeDomain` that covers status codes covering a\n\t/// platform's specific implementation of `errno` values in addition to those __strictly__\n\t/// required by POSIX (those represented by `Errno`).\n\t/// @ingroup error\n\t/// @headerfile \"Hyperion/error/PosixDomain.h\"\n\tclass [[nodiscard(\"A StatusCodeDomain should always be used\")]] PosixDomain {\n\t  public:\n\t\t/// @brief The value type of `PosixDomain` status codes is `i64`\n\t\t/// @ingroup error\n\t\tusing value_type = i64;\n\n\t\tstatic const constexpr char(&UUID)[num_chars_in_uuid] // NOLINT\n\t\t\t= \"4a6a9b0f-c335-473e-bc42-d23974a25bb0\";\n\n\t\tstatic constexpr u64 ID = parse_uuid_from_string(UUID);\n\n\t\t/// @brief Constructs a `PosixDomain` with the default UUID\n\t\t/// @ingroup error\n\t\tconstexpr PosixDomain() noexcept = default;\n\t\t/// @brief Constructs a `PosixDomain` with a user-specific UUID\n\t\t///\n\t\t/// @note When using a custom UUID __**ALL**__ instances of `PosixDomain` in the program\n\t\t/// should be constructed with the same custom UUID, otherwise equality comparison between\n\t\t/// other domains and `PosixDomain` instances could give erroneous results, and equality\n\t\t/// comparison between different `PosixDomain` instances will give erroneous results.\n\t\t/// As a result, this constructor should only be used when you specifically require a custom\n\t\t/// UUID and **YOU KNOW WHAT YOU ARE DOING\u2122**\n\t\t///\n\t\t/// @param uuid - The UUID to use for `PosixDomain`\n\t\t/// @ingroup error\n\t\texplicit constexpr PosixDomain(u64 uuid) noexcept : m_uuid(uuid) {\n\t\t}\n\t\t/// @brief Constructs a `PosixDomain` with a user-specific UUID\n\t\t///\n\t\t/// @note When using a custom UUID __**ALL**__ instances of `PosixDomain` in the program\n\t\t/// should be constructed with the same custom UUID, otherwise equality comparison between\n\t\t/// other domains and `PosixDomain` instances could give erroneous results, and equality\n\t\t/// comparison between different `PosixDomain` instances will give erroneous results.\n\t\t/// As a result, this constructor should only be used when you specifically require a custom\n\t\t/// UUID and **YOU KNOW WHAT YOU ARE DOING\u2122**\n\t\t///\n\t\t/// @param uuid - The UUID to use for `PosixDomain`\n\t\t/// @ingroup error\n\t\ttemplate<UUIDString UUID>\n\t\texplicit constexpr PosixDomain(UUID && uuid) noexcept // NOLINT (forwarding reference)\n\t\t\t: m_uuid(parse_uuid_from_string(std::forward<UUID>(uuid))) {\n\t\t}\n\t\t/// @brief Copy-Constructor\n\t\t/// @ingroup error\n\t\tconstexpr PosixDomain(const PosixDomain&) noexcept = default;\n\t\t/// @brief Move-Constructor\n\t\t/// @ingroup error\n\t\tconstexpr PosixDomain(PosixDomain &&) noexcept = default;\n\t\t/// @brief Destructor\n\t\t/// @ingroup error\n\t\tconstexpr ~PosixDomain() noexcept = default;\n\n\t\t/// @brief Returns the UUID of the domain\n\t\t///\n\t\t/// @return the domain UUID\n\t\t/// @ingroup error\n\t\t[[nodiscard]] constexpr auto id() const noexcept->u64 {\n\t\t\treturn m_uuid;\n\t\t}\n\n\t\t/// @brief Returns the name of the domain\n\t\t///\n\t\t/// @return the domain name\n\t\t/// @ingroup error\n\t\t[[nodiscard]] constexpr auto name() const noexcept->std::string_view { // NOLINT\n\t\t\treturn \"POSIX domain\";\n\t\t}\n\n\t\t/// @brief Returns the textual message associated with the given status code\n\t\t///\n\t\t/// @param code - The status code to get the message for\n\t\t///\n\t\t/// @return the message associated with the code\n\t\t/// @ingroup error\n\t\t[[nodiscard]] auto message(value_type code) // NOLINT\n\t\t\tconst noexcept->std::string {\n\n\t\t\treturn as_string(code);\n\t\t}\n\n\t\t/// @brief Returns the textual message associated with the given status code\n\t\t///\n\t\t/// @param code - The status code to get the message for\n\t\t///\n\t\t/// @return the message associated with the code\n\t\t/// @ingroup error\n\t\t[[nodiscard]] auto message(const PosixStatusCode& code) // NOLINT\n\t\t\tconst noexcept->std::string {\n\n\t\t\treturn as_string(code.code());\n\t\t}\n\n\t\t/// @brief Returns whether the given status code represents an error\n\t\t///\n\t\t/// @param code - The status code to check\n\t\t///\n\t\t/// @return `true` if the code represents an error, otherwise `false`\n\t\t/// @ingroup error\n\t\t[[nodiscard]] constexpr auto is_error(const PosixStatusCode& code) // NOLINT\n\t\t\tconst noexcept->bool {\n\t\t\treturn code.code() != 0;\n\t\t}\n\n\t\t/// @brief Returns whether the given status code represents success\n\t\t///\n\t\t/// @param code - The status code to check\n\t\t///\n\t\t/// @return `true` if the code represents success, otherwise `false`\n\t\t/// @ingroup error\n\t\t[[nodiscard]] constexpr auto is_success(const PosixStatusCode& code) // NOLINT\n\t\t\tconst noexcept->bool {\n\t\t\treturn code.code() == 0;\n\t\t}\n\n\t\t/// @brief Returns whether the given status codes are semantically equivalent\n\t\t///\n\t\t/// Checks if the given codes are semantically equivalent. For most `StatusCodeDomain`s,\n\t\t/// this usually means checking the codes for equality after being converted to\n\t\t/// `GenericStatusCode`s.\n\t\t///\n\t\t/// @tparam Domain - The `StatusCodeDomain` of the second status code\n\t\t/// @param lhs - The first status code to compare\n\t\t/// @param rhs - The second status code to compare\n\t\t/// @return `true` if the codes are semantically equivalent, `false` otherwise\n\t\t/// @ingroup error\n\t\ttemplate<typename Domain>\n\t\t[[nodiscard]] constexpr auto are_equivalent(const PosixStatusCode& lhs,\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst StatusCode<Domain>& rhs)\n\t\t\tconst noexcept->bool {\n\t\t\tif constexpr(ConvertibleToGenericStatusCode<StatusCode<Domain>>) {\n\t\t\t\treturn as_generic_code(lhs) == rhs.as_generic_code();\n\t\t\t}\n\t\t\telse if(rhs.domain() == *this) {\n\t\t\t\tconst auto lhs_code = lhs.code();\n\t\t\t\tconst auto rhs_code = rhs.code();\n\t\t\t\treturn lhs_code == rhs_code && lhs_code != -1 && rhs_code != -1;\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\t/// @brief Converts the given status code to a `GenericStatusCode`\n\t\t///\n\t\t/// This will convert the given code to its semantically equivalent counterpart in the\n\t\t/// `GenericDomain`.\n\t\t///\n\t\t/// @param code - The status code to convert to a `GenericStatusCode`\n\t\t/// @return The given status code as a `GenericStatusCode`\n\t\t/// @note Not all status code values are convertible to the `GenericDomain`, even\n\t\t/// from domains fully compatible with `GenericDomain` and that satisfy\n\t\t/// `ConvertibleToGenericStatusCode`. In this case, they will map to `Errno::Unknown`.\n\t\t/// Codes of value `Errno::Unknown` will never compare as semantically equivalent.\n\t\t/// @ingroup error\n\t\t[[nodiscard]] constexpr auto as_generic_code(const PosixStatusCode& code) // NOLINT\n\t\t\tconst noexcept->GenericStatusCode {\n\t\t\treturn make_status_code(to_generic_code(code.code()));\n\t\t}\n\n\t\t/// @brief Returns the value indicating success for this domain\n\t\t///\n\t\t/// @return The domain's success value\n\t\t/// @ingroup error\n\t\t[[nodiscard]] static inline constexpr auto success_value() noexcept->value_type {\n\t\t\treturn 0;\n\t\t}\n\n\t\t/// @brief Returns the most recent value of `errno`\n\t\t///\n\t\t/// @return the value of `errno` at the time of the call\n\t\t/// @ingroup error\n\t\t[[nodiscard]] static inline auto get_last_error() noexcept->value_type {\n\t\t\treturn errno;\n\t\t}\n\n\t\t/// @brief Domain equality comparison operator\n\t\t///\n\t\t/// @tparam Domain - The type of the second domain to compare\n\t\t///\n\t\t/// @param lhs - The left-hand domain to compare\n\t\t/// @param rhs - The right-hand domain to compare\n\t\t///\n\t\t/// @return Whether the two domains are equal\n\t\t/// @ingroup error\n\t\ttemplate<typename Domain>\n\t\tfriend constexpr auto operator==(const PosixDomain& lhs, const Domain& rhs) noexcept->bool {\n\t\t\treturn lhs.id() == rhs.id();\n\t\t}\n\n\t\t/// @brief Domain inequality comparison operator\n\t\t///\n\t\t/// @tparam Domain - The type of the second domain to compare\n\t\t///\n\t\t/// @param lhs - The left-hand domain to compare\n\t\t/// @param rhs - The right-hand domain to compare\n\t\t///\n\t\t/// @return Whether the two domains are __not__ equal\n\t\t/// @ingroup error\n\t\ttemplate<typename Domain>\n\t\tfriend constexpr auto operator!=(const PosixDomain& lhs, const Domain& rhs) noexcept->bool {\n\t\t\treturn lhs.id() != rhs.id();\n\t\t}\n\n\t\t/// @brief Copy-assignment operator\n\t\t/// @ingroup error\n\t\tconstexpr auto operator=(const PosixDomain&) noexcept->PosixDomain& = default;\n\t\t/// @brief Move-assignment operator\n\t\t/// @ingroup error\n\t\tconstexpr auto operator=(PosixDomain&&) noexcept->PosixDomain& = default;\n\n\t  private:\n\t\tu64 m_uuid = ID;\n\n\t\t[[nodiscard]] static inline auto as_string(value_type code) noexcept->std::string {\n\t\t\tchar buffer[1024]; // NOLINT\n#if HYPERION_PLATFORM_WINDOWS\n\t\t\tstrerror_s(buffer, 1024, gsl::narrow_cast<i32>(code)); // NOLINT\n#elif defined(__gnu_linux__) && !defined(__ANDROID__)\n\t\t\tchar* message = strerror_r(gsl::narrow_cast<i32>(code), buffer, 1024); // NOLINT\n\t\t\tif(message != nullptr) {\n\t\t\t\tstrncpy(buffer, message, 1024); // NOLINT\n\t\t\t\tbuffer[1023] = 0;\t\t\t\t// NOLINT\n\t\t\t}\n#else\n\t\t\tstr_error_r(code, buffer, 1024); // NOLINT\n#endif\n\t\t\tusize length = strlen(buffer);\t\t// NOLINT\n\t\t\treturn std::string(buffer, length); // NOLINT\n\t\t}\n\n\t\t[[nodiscard]] static inline constexpr auto to_generic_code(\n\t\t\tvalue_type code) noexcept->Errno {\n\t\t\tswitch(code) {\n\t\t\t\tcase 0: return Errno::Success;\n\t\t\t\tcase EAFNOSUPPORT: return Errno::AddressFamilyNotSupported;\n\t\t\t\tcase EADDRINUSE: return Errno::AddressInUse;\n\t\t\t\tcase EADDRNOTAVAIL: return Errno::AddressNotAvailable;\n\t\t\t\tcase EISCONN: return Errno::AlreadyConnected;\n\t\t\t\tcase E2BIG: return Errno::ArgumentListTooLong;\n\t\t\t\tcase EDOM: return Errno::ArgumentOutOfDomain;\n\t\t\t\tcase EFAULT: return Errno::BadAddress;\n\t\t\t\tcase EBADF: return Errno::BadFileDescriptor;\n\t\t\t\tcase EBADMSG: return Errno::BadMessage;\n\t\t\t\tcase EPIPE: return Errno::BrokenPipe;\n\t\t\t\tcase ECONNABORTED: return Errno::ConnectionAborted;\n\t\t\t\tcase EALREADY: return Errno::ConnectionAlreadyInProgress;\n\t\t\t\tcase ECONNREFUSED: return Errno::ConnectionRefused;\n\t\t\t\tcase ECONNRESET: return Errno::ConnectionReset;\n\t\t\t\tcase EXDEV: return Errno::CrossDeviceLink;\n\t\t\t\tcase EDESTADDRREQ: return Errno::DestinationAddressRequired;\n\t\t\t\tcase EBUSY: return Errno::DeviceOrResourceBusy;\n\t\t\t\tcase ENOTEMPTY: return Errno::DirectoryNotEmpty;\n\t\t\t\tcase ENOEXEC: return Errno::ExecutableFormatError;\n\t\t\t\tcase EEXIST: return Errno::FileExists;\n\t\t\t\tcase EFBIG: return Errno::FileTooLarge;\n\t\t\t\tcase ENAMETOOLONG: return Errno::FilenameTooLong;\n\t\t\t\tcase ENOSYS: return Errno::FunctionNotSupported;\n\t\t\t\tcase EHOSTUNREACH: return Errno::HostUnreachable;\n\t\t\t\tcase EIDRM: return Errno::IdentifierRemoved;\n\t\t\t\tcase EILSEQ: return Errno::IllegalByteSequence;\n\t\t\t\tcase ENOTTY: return Errno::InappropriateIOControlOperation;\n\t\t\t\tcase EINTR: return Errno::Interrupted;\n\t\t\t\tcase EINVAL: return Errno::InvalidArgument;\n\t\t\t\tcase ESPIPE: return Errno::InvalidSeek;\n\t\t\t\tcase EIO: return Errno::IOError;\n\t\t\t\tcase EISDIR: return Errno::IsADirectory;\n\t\t\t\tcase EMSGSIZE: return Errno::MessageSize;\n\t\t\t\tcase ENETDOWN: return Errno::NetworkDown;\n\t\t\t\tcase ENETRESET: return Errno::NetworkReset;\n\t\t\t\tcase ENETUNREACH: return Errno::NetworkUnreachable;\n\t\t\t\tcase ENOBUFS: return Errno::NoBufferSpace;\n\t\t\t\tcase ECHILD: return Errno::NoChildProcess;\n\t\t\t\tcase ENOLINK: return Errno::NoLink;\n\t\t\t\tcase ENOLCK: return Errno::NoLockAvailable;\n\t\t\t\tcase ENODATA: return Errno::NoMessageAvailable;\n\t\t\t\tcase ENOMSG: return Errno::NoMessage;\n\t\t\t\tcase ENOPROTOOPT: return Errno::NoProtocolOption;\n\t\t\t\tcase ENOSPC: return Errno::NoSpaceOnDevice;\n\t\t\t\tcase ENOSR: return Errno::NoStreamResources;\n\t\t\t\tcase ENXIO: return Errno::NoSuchDeviceOrAddress;\n\t\t\t\tcase ENODEV: return Errno::NoSuchDevice;\n\t\t\t\tcase ENOENT: return Errno::NoSuchFileOrDirectory;\n\t\t\t\tcase ESRCH: return Errno::NoSuchProcess;\n\t\t\t\tcase ENOTDIR: return Errno::NotADirectory;\n\t\t\t\tcase ENOTSOCK: return Errno::NotASocket;\n\t\t\t\tcase ENOSTR: return Errno::NotAStream;\n\t\t\t\tcase ENOTCONN: return Errno::NotConnected;\n\t\t\t\tcase ENOMEM: return Errno::NotEnoughMemory;\n#if ENOTSUP != EOPNOTSUPP\n\t\t\t\tcase ENOTSUP: return Errno::NotSupported;\n#endif\n\t\t\t\tcase ECANCELED: return Errno::OperationCanceled;\n\t\t\t\tcase EINPROGRESS: return Errno::OperationInProgress;\n\t\t\t\tcase EPERM: return Errno::OperationNotPermitted;\n\t\t\t\tcase EOPNOTSUPP: return Errno::OperationNotSupported;\n#if EWOULDBLOCK != EAGAIN\n\t\t\t\tcase EWOULDBLOCK: return Errno::OperationWouldBlock;\n#endif\n\t\t\t\tcase EOWNERDEAD: return Errno::OwnerDead;\n\t\t\t\tcase EACCES: return Errno::PermissionDenied;\n\t\t\t\tcase EPROTO: return Errno::ProtocolError;\n\t\t\t\tcase EPROTONOSUPPORT: return Errno::ProtocolNotSupported;\n\t\t\t\tcase EROFS: return Errno::ReadOnlyFileSystem;\n\t\t\t\tcase EDEADLK: return Errno::ResourceDeadlockWouldOccur;\n\t\t\t\tcase EAGAIN: return Errno::ResourceUnavailableTryAgain;\n\t\t\t\tcase ERANGE: return Errno::ResultOutOfRange;\n\t\t\t\tcase ENOTRECOVERABLE: return Errno::StateNotRecoverable;\n\t\t\t\tcase ETIME: return Errno::StreamTimeout;\n\t\t\t\tcase ETXTBSY: return Errno::TextFileBusy;\n\t\t\t\tcase ETIMEDOUT: return Errno::TimedOut;\n\t\t\t\tcase ENFILE: return Errno::TooManyFilesOpenInSystem;\n\t\t\t\tcase EMFILE: return Errno::TooManyFilesOpen;\n\t\t\t\tcase EMLINK: return Errno::TooManyLinks;\n\t\t\t\tcase ELOOP: return Errno::TooManySymbolicLinkLevels;\n\t\t\t\tcase EOVERFLOW: return Errno::ValueTooLarge;\n\t\t\t\tcase EPROTOTYPE: return Errno::WrongProtocolType;\n\t\t\t\tdefault: return Errno::Unknown;\n\t\t\t}\n\t\t}\n\t};\n} // namespace hyperion::error\n\n/// @brief Specialize `make_status_code_domain` for `PosixDomain` and `u64`.\n/// Creates a `PosixDomain` with a custom UUID.\n///\n/// @note When using a custom UUID __**ALL**__ instances of `PosixDomain` in the program\n/// should be constructed with the same custom UUID, otherwise equality comparison between\n/// other domains and `PosixDomain` instances could give erroneous results, and equality\n/// comparison between different `PosixDomain` instances will give erroneous results.\n/// As a result, this constructor should only be used when you specifically require a custom\n/// UUID and **YOU KNOW WHAT YOU ARE DOING\u2122**\n///\n/// @param uuid - The UUID to use for `PosixDomain`\n///\n/// @return a `PosixDomain`\n/// @ingroup error\ntemplate<>\n[[nodiscard]] inline constexpr auto\n// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name)\nmake_status_code_domain<hyperion::error::PosixDomain, hyperion::u64>(hyperion::u64&& uuid) noexcept\n\t-> hyperion::error::PosixDomain {\n\treturn hyperion::error::PosixDomain(uuid);\n}\n\n/// @brief Specialize `make_status_code_domain` for `PosixDomain` and a `UUIDString`.\n/// Creates a `PosixDomain` with a custom UUID.\n///\n/// @note When using a custom UUID __**ALL**__ instances of `PosixDomain` in the program\n/// should be constructed with the same custom UUID, otherwise equality comparison between\n/// other domains and `PosixDomain` instances could give erroneous results, and equality\n/// comparison between different `PosixDomain` instances will give erroneous results.\n/// As a result, this constructor should only be used when you specifically require a custom\n/// UUID and **YOU KNOW WHAT YOU ARE DOING\u2122**\n///\n/// @param uuid - The UUID to use for `PosixDomain`\n///\n/// @return a `PosixDomain`\n/// @ingroup error\ntemplate<>\n[[nodiscard]] inline constexpr auto\n\t// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name)\n\tmake_status_code_domain<hyperion::error::PosixDomain,\n\t\t\t\t\t\t\tconst char (&)[hyperion::error::num_chars_in_uuid]> // NOLINT\n\t(const char (&uuid)[hyperion::error::num_chars_in_uuid]) noexcept\t\t\t// NOLINT\n\t-> hyperion::error::PosixDomain {\n\treturn hyperion::error::PosixDomain(uuid);\n}\n\n/// @brief Specialize `make_status_code_domain` for `PosixDomain` and an MS-style `UUIDString`.\n/// Creates a `PosixDomain` with a custom UUID.\n///\n/// @note When using a custom UUID __**ALL**__ instances of `PosixDomain` in the program\n/// should be constructed with the same custom UUID, otherwise equality comparison between\n/// other domains and `PosixDomain` instances could give erroneous results, and equality\n/// comparison between different `PosixDomain` instances will give erroneous results.\n/// As a result, this constructor should only be used when you specifically require a custom\n/// UUID and **YOU KNOW WHAT YOU ARE DOING\u2122**\n///\n/// @param uuid - The UUID to use for `PosixDomain`\n///\n/// @return a `PosixDomain`\n/// @ingroup error\ntemplate<>\n[[nodiscard]] inline constexpr auto\n\t// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name)\n\tmake_status_code_domain<hyperion::error::PosixDomain,\n\t\t\t\t\t\t\tconst char (&)[hyperion::error::num_chars_in_ms_uuid]> // NOLINT\n\t(const char (&uuid)[hyperion::error::num_chars_in_ms_uuid]) noexcept\t\t   // NOLINT\n\t-> hyperion::error::PosixDomain {\n\treturn hyperion::error::PosixDomain(uuid);\n}\n\n/// @brief Specialize `make_status_code_domain` for `PosixDomain` with no arguments. Creates\n/// a `PosixDomain` with the default UUID.\n///\n/// @return a `PosixDomain`\n/// @ingroup error\ntemplate<>\ninline constexpr auto\nmake_status_code_domain<hyperion::error::PosixDomain>() noexcept -> hyperion::error::PosixDomain {\n\treturn {};\n}\n\nnamespace hyperion::error {\n\tstatic_assert(StatusCodeDomain<PosixDomain>);\n} // namespace hyperion::error\n", "meta": {"hexsha": "ffd5987b7b5d1bd2630a600edca5a772f9c80518", "size": 18567, "ext": "h", "lang": "C", "max_stars_repo_path": "include/Hyperion/error/PosixDomain.h", "max_stars_repo_name": "braxtons12/Hyperion-Utils", "max_stars_repo_head_hexsha": "3873a116e2ea76fc74c9c056925f3740eee6dcd8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/Hyperion/error/PosixDomain.h", "max_issues_repo_name": "braxtons12/Hyperion-Utils", "max_issues_repo_head_hexsha": "3873a116e2ea76fc74c9c056925f3740eee6dcd8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/Hyperion/error/PosixDomain.h", "max_forks_repo_name": "braxtons12/Hyperion-Utils", "max_forks_repo_head_hexsha": "3873a116e2ea76fc74c9c056925f3740eee6dcd8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.9867549669, "max_line_length": 99, "alphanum_fraction": 0.7240264986, "num_tokens": 4821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.04023794492547895, "lm_q2_score": 0.03114382817424187, "lm_q1q2_score": 0.0012531636428437238}}
{"text": "#pragma once\r\n\r\n// v1.4 By Ook\r\n//\r\n\r\n#include <gsl/gsl>\r\n\r\n#include \"EnumConcepts.h\"\r\n\r\n// this enum is here to simplify debugging\r\nenum class WindowMessages\r\n\t: DWORD\r\n{\r\n\teWM_NULL,\r\n\teWM_CREATE,\t// lParam = LPCREATESTRUCT\r\n\teWM_DESTROY,\r\n\teWM_MOVE,\r\n\teWM_SIZEWAIT,\r\n\teWM_SIZE,\t// lParam = width/height\r\n\teWM_ACTIVATE,\r\n\teWM_SETFOCUS,\r\n\teWM_KILLFOCUS,\r\n\teWM_SETVISIBLE,\r\n\teWM_ENABLE,\r\n\teWM_SETREDRAW,\r\n\teWM_SETTEXT,\r\n\teWM_GETTEXT,\r\n\teWM_GETTEXTLENGTH,\r\n\teWM_PAINT,\r\n\teWM_CLOSE,\r\n\teWM_QUERYENDSESSION,\r\n\teWM_QUIT,\r\n\teWM_QUERYOPEN,\r\n\teWM_ERASEBKGND,\t// wParam = HDC\r\n\teWM_SYSCOLORCHANGE,\r\n\teWM_ENDSESSION,\r\n\teWM_SYSTEMERROR,\r\n\teWM_SHOWWINDOW,\r\n\teWM_CTLCOLOR,\r\n\teWM_WININICHANGE,\r\n\teWM_DEVMODECHANGE,\r\n\teWM_ACTIVATEAPP,\r\n\teWM_FONTCHANGE,\r\n\teWM_TIMECHANGE,\r\n\teWM_CANCELMODE,\r\n\teWM_SETCURSOR,\r\n\teWM_MOUSEACTIVATE,\r\n\teWM_CHILDACTIVATE,\r\n\teWM_QUEUESYNC,\r\n\teWM_GETMINMAXINFO,\r\n\teWM_LOGOFF,\r\n\teWM_PAINTICON,\r\n\teWM_ICONERASEBKGND,\r\n\teWM_NEXTDLGCTL,\r\n\teWM_ALTTABACTIVE,\r\n\teWM_SPOOLERSTATUS,\r\n\teWM_DRAWITEM,\r\n\teWM_MEASUREITEM,\r\n\teWM_DELETEITEM,\r\n\teWM_VKEYTOITEM,\r\n\teWM_CHARTOITEM,\r\n\teWM_SETFONT,\r\n\teWM_GETFONT,\r\n\teWM_SETHOTKEY,\r\n\teWM_GETHOTKEY,\r\n\teWM_SHELLNOTIFY,\r\n\teWM_ISACTIVEICON,\r\n\teWM_QUERYPARKICON,\r\n\teWM_QUERYDRAGICON,\r\n\teWM_WINHELP,\r\n\teWM_COMPAREITEM,\r\n\teWM_FULLSCREEN,\r\n\teWM_CLIENTSHUTDOWN,\r\n\teWM_DDEMLEVENT,\r\n\teWM_GETOBJECT,\r\n\teundefined_1,\r\n\teundefined_2,\r\n\teWM_TESTING,\r\n\teWM_COMPACTING,\r\n\teWM_OTHERWINDOWCREATED,\r\n\teWM_OTHERWINDOWDESTROYED,\r\n\teWM_COMMNOTIFY,\r\n\teundefined_3,\r\n\teWM_WINDOWPOSCHANGING,\r\n\teWM_WINDOWPOSCHANGED,\r\n\teWM_POWER,\r\n\teWM_COPYGLOBALDATA,\r\n\teWM_COPYDATA,\r\n\teWM_CANCELJOURNAL,\r\n\teundefined_4,\r\n\teWM_KEYF1,\r\n\teWM_NOTIFY,\r\n\teWM_ACCESS_WINDOW,\r\n\teWM_INPUTLANGCHANGEREQUEST,\r\n\teWM_INPUTLANGCHANGE,\r\n\teWM_TCARD,\r\n\teWM_HELP,\r\n\teWM_USERCHANGED,\r\n\teWM_NOTIFYFORMAT,\r\n\teundefined_5,\r\n\teundefined_6,\r\n\teundefined_7,\r\n\teundefined_8,\r\n\teundefined_9,\r\n\teundefined_10,\r\n\teundefined_11,\r\n\teundefined_12,\r\n\teundefined_13,\r\n\teundefined_14,\r\n\teundefined_15,\r\n\teundefined_16,\r\n\teundefined_17,\r\n\teundefined_18,\r\n\teundefined_19,\r\n\teundefined_20,\r\n\teundefined_21,\r\n\teundefined_22,\r\n\teundefined_23,\r\n\teundefined_24,\r\n\teundefined_25,\r\n\teundefined_26,\r\n\teundefined_27,\r\n\teundefined_28,\r\n\teundefined_29,\r\n\teundefined_30,\r\n\teWM_FINALDESTROY,\r\n\teWM_MEASUREITEM_CLIENTDATA,\r\n\teundefined_31,\r\n\teundefined_32,\r\n\teundefined_33,\r\n\teundefined_34,\r\n\teundefined_35,\r\n\teundefined_36,\r\n\teundefined_37,\r\n\teundefined_38,\r\n\teundefined_39,\r\n\teWM_CONTEXTMENU,\r\n\teWM_STYLECHANGING,\r\n\teWM_STYLECHANGED,\r\n\teWM_DISPLAYCHANGE,\r\n\teWM_GETICON,\r\n\teWM_SETICON,\r\n\teWM_NCCREATE,\t// lParam = LPCREATESTRUCT\r\n\teWM_NCDESTROY,\r\n\teWM_NCCALCSIZE,\r\n\teWM_NCHITTEST,\r\n\teWM_NCPAINT,\r\n\teWM_NCACTIVATE,\r\n\teWM_GETDLGCODE,\r\n\teWM_SYNCPAINT,\r\n\teWM_SYNCTASK,\r\n\teundefined_40,\r\n\teWM_KLUDGEMINRECT,\r\n\teWM_LPKDRAWSWITCHWND,\r\n\teundefined_41,\r\n\teundefined_42,\r\n\teundefined_43,\r\n\teWM_UAHDESTROYWINDOW,\r\n\teWM_UAHDRAWMENU,\r\n\teWM_UAHDRAWMENUITEM,\r\n\teWM_UAHINITMENU,\r\n\teWM_UAHMEASUREMENUITEM,\r\n\teWM_UAHNCPAINTMENUPOPUP,\r\n\teWM_UAHUPDATE,\r\n\teundefined_44,\r\n\teundefined_45,\r\n\teundefined_46,\r\n\teundefined_47,\r\n\teundefined_48,\r\n\teundefined_49,\r\n\teundefined_50,\r\n\teundefined_51,\r\n\teundefined_52,\r\n\teWM_NCMOUSEMOVE,\r\n\teWM_NCLBUTTONDOWN,\r\n\teWM_NCLBUTTONUP,\r\n\teWM_NCLBUTTONDBLCLK,\r\n\teWM_NCRBUTTONDOWN,\r\n\teWM_NCRBUTTONUP,\r\n\teWM_NCRBUTTONDBLCLK,\r\n\teWM_NCMBUTTONDOWN,\r\n\teWM_NCMBUTTONUP,\r\n\teWM_NCMBUTTONDBLCLK,\r\n\teundefined_53,\r\n\teWM_NCXBUTTONDOWN,\r\n\teWM_NCXBUTTONUP,\r\n\teWM_NCXBUTTONDBLCLK,\r\n\teWM_NCUAHDRAWCAPTION,\r\n\teWM_NCUAHDRAWFRAME,\t// wParam = HDC\r\n\teEM_GETSEL,\r\n\teEM_SETSEL,\r\n\teEM_GETRECT,\r\n\teEM_SETRECT,\r\n\teEM_SETRECTNP,\r\n\teEM_SCROLL,\r\n\teEM_LINESCROLL,\r\n\teEM_SCROLLCARET,\r\n\teEM_GETMODIFY,\r\n\teEM_SETMODIFY,\r\n\teEM_GETLINECOUNT,\r\n\teEM_LINEINDEX,\r\n\teEM_SETHANDLE,\r\n\teEM_GETHANDLE,\r\n\teEM_GETTHUMB,\r\n\teundefined_54,\r\n\teundefined_55,\r\n\teEM_LINELENGTH,\r\n\teEM_REPLACESEL,\r\n\teEM_SETFONT,\r\n\teEM_GETLINE,\r\n\teEM_LIMITTEXT,\r\n\teEM_CANUNDO,\r\n\teEM_UNDO,\r\n\teEM_FMTLINES,\r\n\teEM_LINEFROMCHAR,\r\n\teEM_SETWORDBREAK,\r\n\teEM_SETTABSTOPS,\r\n\teEM_SETPASSWORDCHAR,\r\n\teEM_EMPTYUNDOBUFFER,\r\n\teEM_GETFIRSTVISIBLELINE,\r\n\teEM_SETREADONLY,\r\n\teEM_SETWORDBREAKPROC,\r\n\teEM_GETWORDBREAKPROC,\r\n\teEM_GETPASSWORDCHAR,\r\n\teEM_SETMARGINS,\r\n\teEM_GETMARGINS,\r\n\teEM_GETLIMITTEXT,\r\n\teEM_POSFROMCHAR,\r\n\teEM_CHARFROMPOS,\r\n\teEM_SETIMESTATUS,\r\n\teEM_GETIMESTATUS,\r\n\teEM_MSGMAX,\r\n\teundefined_56,\r\n\teundefined_57,\r\n\teundefined_58,\r\n\teundefined_59,\r\n\teundefined_60,\r\n\teundefined_61,\r\n\teundefined_62,\r\n\teundefined_63,\r\n\teundefined_64,\r\n\teundefined_65,\r\n\teundefined_66,\r\n\teundefined_67,\r\n\teundefined_68,\r\n\teundefined_69,\r\n\teundefined_70,\r\n\teundefined_71,\r\n\teundefined_72,\r\n\teundefined_73,\r\n\teundefined_74,\r\n\teundefined_75,\r\n\teundefined_76,\r\n\teundefined_77,\r\n\teundefined_78,\r\n\teundefined_79,\r\n\teundefined_80,\r\n\teundefined_81,\r\n\teundefined_82,\r\n\teundefined_83,\r\n\teundefined_84,\r\n\teundefined_85,\r\n\teundefined_86,\r\n\teundefined_87,\r\n\teundefined_88,\r\n\teundefined_89,\r\n\teundefined_90,\r\n\teWM_INPUT_DEVICE_CHANGE,\r\n\teWM_INPUT,\r\n\teWM_KEYDOWN,\r\n\teWM_KEYUP,\r\n\teWM_CHAR,\r\n\teWM_DEADCHAR,\r\n\teWM_SYSKEYDOWN,\r\n\teWM_SYSKEYUP,\r\n\teWM_SYSCHAR,\r\n\teWM_SYSDEADCHAR,\r\n\teWM_YOMICHAR,\r\n\teWM_UNICHAR,\r\n\teWM_CONVERTREQUEST,\r\n\teWM_CONVERTRESULT,\r\n\teWM_INTERIM,\r\n\teWM_IME_STARTCOMPOSITION,\r\n\teWM_IME_ENDCOMPOSITION,\r\n\teWM_IME_COMPOSITION,\r\n\teWM_INITDIALOG,\r\n\teWM_COMMAND,\r\n\teWM_SYSCOMMAND,\r\n\teWM_TIMER,\r\n\teWM_HSCROLL,\r\n\teWM_VSCROLL,\r\n\teWM_INITMENU,\r\n\teWM_INITMENUPOPUP,\r\n\teWM_SYSTIMER,\r\n\teWM_GESTURE,\r\n\teWM_GESTURENOTIFY,\r\n\teWM_GESTUREINPUT,\r\n\teWM_GESTURENOTIFIED,\r\n\teundefined_91,\r\n\teundefined_92,\r\n\teWM_MENUSELECT,\r\n\teWM_MENUCHAR,\r\n\teWM_ENTERIDLE,\r\n\teWM_MENURBUTTONUP,\r\n\teWM_MENUDRAG,\r\n\teWM_MENUGETOBJECT,\r\n\teWM_UNINITMENUPOPUP,\r\n\teWM_MENUCOMMAND,\r\n\teWM_CHANGEUISTATE,\r\n\teWM_UPDATEUISTATE,\r\n\teWM_QUERYUISTATE,\r\n\teundefined_93,\r\n\teundefined_94,\r\n\teundefined_95,\r\n\teundefined_96,\r\n\teundefined_97,\r\n\teundefined_98,\r\n\teundefined_99,\r\n\teWM_LBTRACKPOINT,\r\n\teWM_CTLCOLORMSGBOX,\r\n\teWM_CTLCOLOREDIT,\r\n\teWM_CTLCOLORLISTBOX,\r\n\teWM_CTLCOLORBTN,\r\n\teWM_CTLCOLORDLG,\r\n\teWM_CTLCOLORSCROLLBAR,\r\n\teWM_CTLCOLORSTATIC,\r\n\teundefined_100,\r\n\teundefined_101,\r\n\teundefined_102,\r\n\teundefined_103,\r\n\teundefined_104,\r\n\teundefined_105,\r\n\teundefined_106,\r\n\teCB_GETEDITSEL,\r\n\teCB_LIMITTEXT,\r\n\teCB_SETEDITSEL,\r\n\teCB_ADDSTRING,\r\n\teCB_DELETESTRING,\r\n\teCB_DIR,\r\n\teCB_GETCOUNT,\r\n\teCB_GETCURSEL,\r\n\teCB_GETLBTEXT,\r\n\teCB_GETLBTEXTLEN,\r\n\teCB_INSERTSTRING,\r\n\teCB_RESETCONTENT,\r\n\teCB_FINDSTRING,\r\n\teCB_SELECTSTRING,\r\n\teCB_SETCURSEL,\r\n\teCB_SHOWDROPDOWN,\r\n\teCB_GETITEMDATA,\r\n\teCB_SETITEMDATA,\r\n\teCB_GETDROPPEDCONTROLRECT,\r\n\teCB_SETITEMHEIGHT,\r\n\teCB_GETITEMHEIGHT,\r\n\teCB_SETEXTENDEDUI,\r\n\teCB_GETEXTENDEDUI,\r\n\teCB_GETDROPPEDSTATE,\r\n\teCB_FINDSTRINGEXACT,\r\n\teCB_SETLOCALE,\r\n\teCB_GETLOCALE,\r\n\teCB_GETTOPINDEX,\r\n\teCB_SETTOPINDEX,\r\n\teCB_GETHORIZONTALEXTENT,\r\n\teCB_SETHORIZONTALEXTENT,\r\n\teCB_GETDROPPEDWIDTH,\r\n\teCB_SETDROPPEDWIDTH,\r\n\teCB_INITSTORAGE,\r\n\teCB_MSGMAX_OLD,\r\n\teCB_MULTIPLEADDSTRING,\r\n\teCB_GETCOMBOBOXINFO,\r\n\teCB_MSGMAX,\r\n\teCBEC_SETCOMBOFOCUS,\r\n\teCBEC_KILLCOMBOFOCUS,\r\n\teundefined_109,\r\n\teundefined_110,\r\n\teundefined_111,\r\n\teundefined_112,\r\n\teundefined_113,\r\n\teundefined_114,\r\n\teundefined_115,\r\n\teundefined_116,\r\n\teundefined_117,\r\n\teundefined_118,\r\n\teundefined_119,\r\n\teundefined_120,\r\n\teundefined_121,\r\n\teundefined_122,\r\n\teundefined_123,\r\n\teundefined_124,\r\n\teundefined_125,\r\n\teundefined_126,\r\n\teundefined_127,\r\n\teundefined_128,\r\n\teundefined_129,\r\n\teundefined_130,\r\n\teundefined_131,\r\n\teundefined_132,\r\n\teLB_ADDSTRING,\r\n\teLB_INSERTSTRING,\r\n\teLB_DELETESTRING,\r\n\teLB_SELITEMRANGEEX,\r\n\teLB_RESETCONTENT,\r\n\teLB_SETSEL,\r\n\teLB_SETCURSEL,\r\n\teLB_GETSEL,\r\n\teLB_GETCURSEL,\r\n\teLB_GETTEXT,\r\n\teLB_GETTEXTLEN,\r\n\teLB_GETCOUNT,\r\n\teLB_SELECTSTRING,\r\n\teLB_DIR,\r\n\teLB_GETTOPINDEX,\r\n\teLB_FINDSTRING,\r\n\teLB_GETSELCOUNT,\r\n\teLB_GETSELITEMS,\r\n\teLB_SETTABSTOPS,\r\n\teLB_GETHORIZONTALEXTENT,\r\n\teLB_SETHORIZONTALEXTENT,\r\n\teLB_SETCOLUMNWIDTH,\r\n\teLB_ADDFILE,\r\n\teLB_SETTOPINDEX,\r\n\teLB_GETITEMRECT,\r\n\teLB_GETITEMDATA,\r\n\teLB_SETITEMDATA,\r\n\teLB_SELITEMRANGE,\r\n\teLB_SETANCHORINDEX,\r\n\teLB_GETANCHORINDEX,\r\n\teLB_SETCARETINDEX,\r\n\teLB_GETCARETINDEX,\r\n\teLB_SETITEMHEIGHT,\r\n\teLB_GETITEMHEIGHT,\r\n\teLB_FINDSTRINGEXACT,\r\n\teLBCB_CARETON,\r\n\teLBCB_CARETOFF,\r\n\teLB_SETLOCALE,\r\n\teLB_GETLOCALE,\r\n\teLB_SETCOUNT,\r\n\teLB_INITSTORAGE,\r\n\teLB_ITEMFROMPOINT,\r\n\teLB_INSERTSTRINGUPPER,\r\n\teLB_INSERTSTRINGLOWER,\r\n\teLB_ADDSTRINGUPPER,\r\n\teLB_ADDSTRINGLOWER,\r\n\teLBCB_STARTTRACK,\r\n\teLBCB_ENDTRACK,\r\n\teLB_MSGMAX_OLD,\r\n\teLB_MULTIPLEADDSTRING,\r\n\teLB_GETLISTBOXINFO,\r\n\teLB_MSGMAX,\r\n\teundefined_133,\r\n\teundefined_134,\r\n\teundefined_135,\r\n\teundefined_136,\r\n\teundefined_137,\r\n\teundefined_138,\r\n\teundefined_139,\r\n\teundefined_140,\r\n\teundefined_141,\r\n\teundefined_142,\r\n\teundefined_143,\r\n\teundefined_144,\r\n\teundefined_145,\r\n\teundefined_146,\r\n\teundefined_147,\r\n\teundefined_148,\r\n\teundefined_149,\r\n\teundefined_150,\r\n\teundefined_151,\r\n\teundefined_152,\r\n\teundefined_153,\r\n\teundefined_154,\r\n\teundefined_155,\r\n\teundefined_156,\r\n\teundefined_157,\r\n\teundefined_158,\r\n\teundefined_159,\r\n\teundefined_160,\r\n\teundefined_161,\r\n\teundefined_162,\r\n\teundefined_163,\r\n\teundefined_164,\r\n\teundefined_165,\r\n\teundefined_166,\r\n\teundefined_167,\r\n\teundefined_168,\r\n\teundefined_169,\r\n\teundefined_170,\r\n\teundefined_171,\r\n\teundefined_172,\r\n\teundefined_173,\r\n\teundefined_174,\r\n\teundefined_175,\r\n\teundefined_176,\r\n\teMN_FIRST,\r\n\teMN_GETHMENU,\r\n\teMN_SIZEWINDOW,\r\n\teMN_OPENHIERARCHY,\r\n\teMN_CLOSEHIERARCHY,\r\n\teMN_SELECTITEM,\r\n\teMN_CANCELMENUS,\r\n\teMN_SELECTFIRSTVALIDITEM,\r\n\teundefined_183,\r\n\teundefined_184,\r\n\teMN_GETPPOPUPMENU,\r\n\teMN_FINDMENUWINDOWFROMPOINT,\t// returns HWND or zero\r\n\teMN_SHOWPOPUPWINDOW,\r\n\teMN_BUTTONDOWN,\r\n\teMN_MOUSEMOVE,\r\n\teMN_BUTTONUP,\r\n\teMN_SETTIMERTOOPENHIERARCHY,\r\n\teMN_DBLCLK,\r\n\teundefined_193,\r\n\teundefined_194,\r\n\teundefined_195,\r\n\teundefined_196,\r\n\teundefined_197,\r\n\teundefined_198,\r\n\teundefined_199,\r\n\teundefined_200,\r\n\teundefined_201,\r\n\teundefined_202,\r\n\teundefined_203,\r\n\teundefined_204,\r\n\teundefined_205,\r\n\teundefined_206,\r\n\teWM_MOUSEMOVE,\r\n\teWM_LBUTTONDOWN,\r\n\teWM_LBUTTONUP,\r\n\teWM_LBUTTONDBLCLK,\r\n\teWM_RBUTTONDOWN,\r\n\teWM_RBUTTONUP,\r\n\teWM_RBUTTONDBLCLK,\r\n\teWM_MBUTTONDOWN,\r\n\teWM_MBUTTONUP,\r\n\teWM_MBUTTONDBLCLK,\r\n\teWM_MOUSEWHEEL,\r\n\teWM_XBUTTONDOWN,\r\n\teWM_XBUTTONUP,\r\n\teWM_XBUTTONDBLCLK,\r\n\teWM_MOUSEHWHEEL,\r\n\teundefined_207,\r\n\teWM_PARENTNOTIFY,\r\n\teWM_ENTERMENULOOP,\r\n\teWM_EXITMENULOOP,\r\n\teWM_NEXTMENU,\r\n\teWM_SIZING,\r\n\teWM_CAPTURECHANGED,\r\n\teWM_MOVING,\r\n\teundefined_208,\r\n\teWM_POWERBROADCAST,\r\n\teWM_DEVICECHANGE,\r\n\teundefined_209,\r\n\teundefined_210,\r\n\teundefined_211,\r\n\teundefined_212,\r\n\teundefined_213,\r\n\teundefined_214,\r\n\teWM_MDICREATE,\r\n\teWM_MDIDESTROY,\r\n\teWM_MDIACTIVATE,\r\n\teWM_MDIRESTORE,\r\n\teWM_MDINEXT,\r\n\teWM_MDIMAXIMIZE,\r\n\teWM_MDITILE,\r\n\teWM_MDICASCADE,\r\n\teWM_MDIICONARRANGE,\r\n\teWM_MDIGETACTIVE,\r\n\teWM_DROPOBJECT,\r\n\teWM_QUERYDROPOBJECT,\r\n\teWM_BEGINDRAG,\r\n\teWM_DRAGLOOP,\r\n\teWM_DRAGSELECT,\r\n\teWM_DRAGMOVE,\r\n\teWM_MDISETMENU,\r\n\teWM_ENTERSIZEMOVE,\r\n\teWM_EXITSIZEMOVE,\r\n\teWM_DROPFILES,\r\n\teWM_MDIREFRESHMENU,\r\n\teundefined_215,\r\n\teundefined_216,\r\n\teundefined_217,\r\n\teWM_POINTERDEVICECHANGE,\r\n\teWM_POINTERDEVICEINRANGE,\r\n\teWM_POINTERDEVICEOUTOFRANGE,\r\n\teWM_STOPINERTIA,\r\n\teWM_ENDINERTIA,\r\n\teWM_EDGYINERTIA,\r\n\teundefined_218,\r\n\teundefined_219,\r\n\teWM_TOUCH,\r\n\teWM_NCPOINTERUPDATE,\r\n\teWM_NCPOINTERDOWN,\r\n\teWM_NCPOINTERUP,\r\n\teWM_NCPOINTERLAST,\r\n\teWM_POINTERUPDATE,\r\n\teWM_POINTERDOWN,\r\n\teWM_POINTERUP,\r\n\teWM_POINTER_reserved_248,\r\n\teWM_POINTERENTER,\r\n\teWM_POINTERLEAVE,\r\n\teWM_POINTERACTIVATE,\r\n\teWM_POINTERCAPTURECHANGED,\r\n\teWM_TOUCHHITTESTING,\r\n\teWM_POINTERWHEEL,\r\n\teWM_POINTERHWHEEL,\r\n\teWM_POINTER_reserved_250,\r\n\teWM_POINTER_reserved_251,\r\n\teWM_POINTER_reserved_252,\r\n\teWM_POINTER_reserved_253,\r\n\teWM_POINTER_reserved_254,\r\n\teWM_POINTER_reserved_255,\r\n\teWM_POINTER_reserved_256,\r\n\teWM_POINTERLAST,\r\n\teundefined_220,\r\n\teundefined_221,\r\n\teundefined_222,\r\n\teundefined_223,\r\n\teundefined_224,\r\n\teundefined_225,\r\n\teundefined_226,\r\n\teundefined_227,\r\n\teundefined_228,\r\n\teundefined_229,\r\n\teundefined_230,\r\n\teundefined_231,\r\n\teundefined_232,\r\n\teundefined_233,\r\n\teundefined_234,\r\n\teundefined_235,\r\n\teundefined_236,\r\n\teundefined_237,\r\n\teundefined_238,\r\n\teundefined_239,\r\n\teundefined_240,\r\n\teundefined_241,\r\n\teundefined_242,\r\n\teundefined_243,\r\n\teWM_VISIBILITYCHANGED,\r\n\teWM_VIEWSTATECHANGED,\r\n\teWM_UNREGISTER_WINDOW_SERVICES,\r\n\teWM_CONSOLIDATED,\r\n\teundefined_244,\r\n\teundefined_245,\r\n\teundefined_246,\r\n\teundefined_247,\r\n\teundefined_248,\r\n\teundefined_249,\r\n\teundefined_250,\r\n\teundefined_251,\r\n\teundefined_252,\r\n\teundefined_253,\r\n\teundefined_254,\r\n\teundefined_255,\r\n\teWM_IME_REPORT,\r\n\teWM_IME_SETCONTEXT,\r\n\teWM_IME_NOTIFY,\r\n\teWM_IME_CONTROL,\r\n\teWM_IME_COMPOSITIONFULL,\r\n\teWM_IME_SELECT,\r\n\teWM_IME_CHAR,\r\n\teWM_IME_SYSTEM,\r\n\teWM_IME_REQUEST,\r\n\teWM_KANJI_reserved_289,\r\n\teWM_KANJI_reserved_28a,\r\n\teWM_KANJI_reserved_28b,\r\n\teWM_KANJI_reserved_28c,\r\n\teWM_KANJI_reserved_28d,\r\n\teWM_KANJI_reserved_28e,\r\n\teWM_KANJI_reserved_28f,\r\n\teWM_IME_KEYDOWN,\r\n\teWM_IME_KEYUP,\r\n\teWM_KANJI_reserved_292,\r\n\teWM_KANJI_reserved_293,\r\n\teWM_KANJI_reserved_294,\r\n\teWM_KANJI_reserved_295,\r\n\teWM_KANJI_reserved_296,\r\n\teWM_KANJI_reserved_297,\r\n\teWM_KANJI_reserved_298,\r\n\teWM_KANJI_reserved_299,\r\n\teWM_KANJI_reserved_29a,\r\n\teWM_KANJI_reserved_29b,\r\n\teWM_KANJI_reserved_29c,\r\n\teWM_KANJI_reserved_29d,\r\n\teWM_KANJI_reserved_29e,\r\n\teWM_KANJILAST,\r\n\teWM_NCMOUSEHOVER,\r\n\teWM_MOUSEHOVER,\r\n\teWM_NCMOUSELEAVE,\r\n\teWM_MOUSELEAVE,\r\n\teWM_TRACKMOUSEEVENT__reserved_2a4,\r\n\teWM_TRACKMOUSEEVENT__reserved_2a5,\r\n\teWM_TRACKMOUSEEVENT__reserved_2a6,\r\n\teWM_TRACKMOUSEEVENT__reserved_2a7,\r\n\teWM_TRACKMOUSEEVENT__reserved_2a8,\r\n\teWM_TRACKMOUSEEVENT__reserved_2a9,\r\n\teWM_TRACKMOUSEEVENT__reserved_2aa,\r\n\teWM_TRACKMOUSEEVENT__reserved_2ab,\r\n\teWM_TRACKMOUSEEVENT__reserved_2ac,\r\n\teWM_TRACKMOUSEEVENT__reserved_2ad,\r\n\teWM_TRACKMOUSEEVENT__reserved_2ae,\r\n\teWM_TRACKMOUSEEVENT_LAST,\r\n\teundefined_256,\r\n\teWM_WTSSESSION_CHANGE,\r\n\teundefined_257,\r\n\teundefined_258,\r\n\teundefined_259,\r\n\teundefined_260,\r\n\teundefined_261,\r\n\teundefined_262,\r\n\teundefined_263,\r\n\teundefined_264,\r\n\teundefined_265,\r\n\teundefined_266,\r\n\teundefined_267,\r\n\teundefined_268,\r\n\teundefined_269,\r\n\teundefined_270,\r\n\teWM_TABLET_FIRST,\r\n\teWM_TABLET__reserved_2c1,\r\n\teWM_TABLET__reserved_2c2,\r\n\teWM_TABLET__reserved_2c3,\r\n\teWM_TABLET__reserved_2c4,\r\n\teWM_TABLET__reserved_2c5,\r\n\teWM_TABLET__reserved_2c6,\r\n\teWM_TABLET__reserved_2c7,\r\n\teWM_POINTERDEVICEADDED,\r\n\teWM_POINTERDEVICEDELETED,\r\n\teWM_TABLET__reserved_2ca,\r\n\teWM_FLICK,\r\n\teWM_TABLET__reserved_2cc,\r\n\teWM_FLICKINTERNAL,\r\n\teWM_BRIGHTNESSCHANGED,\r\n\teWM_TABLET__reserved_2cf,\r\n\teWM_TABLET__reserved_2d0,\r\n\teWM_TABLET__reserved_2d1,\r\n\teWM_TABLET__reserved_2d2,\r\n\teWM_TABLET__reserved_2d3,\r\n\teWM_TABLET__reserved_2d4,\r\n\teWM_TABLET__reserved_2d5,\r\n\teWM_TABLET__reserved_2d6,\r\n\teWM_TABLET__reserved_2d7,\r\n\teWM_TABLET__reserved_2d8,\r\n\teWM_TABLET__reserved_2d9,\r\n\teWM_TABLET__reserved_2da,\r\n\teWM_TABLET__reserved_2db,\r\n\teWM_TABLET__reserved_2dc,\r\n\teWM_TABLET__reserved_2dd,\r\n\teWM_TABLET__reserved_2de,\r\n\teWM_TABLET_LAST,\r\n\teWM_DPICHANGED,\r\n\teundefined_271,\r\n\teundefined_272,\r\n\teundefined_273,\r\n\teundefined_274,\r\n\teundefined_275,\r\n\teundefined_276,\r\n\teundefined_277,\r\n\teundefined_278,\r\n\teundefined_279,\r\n\teundefined_280,\r\n\teundefined_281,\r\n\teundefined_282,\r\n\teundefined_283,\r\n\teundefined_284,\r\n\teundefined_285,\r\n\teundefined_286,\r\n\teundefined_287,\r\n\teundefined_288,\r\n\teundefined_289,\r\n\teundefined_290,\r\n\teundefined_291,\r\n\teundefined_292,\r\n\teundefined_293,\r\n\teundefined_294,\r\n\teundefined_295,\r\n\teundefined_296,\r\n\teundefined_297,\r\n\teundefined_298,\r\n\teundefined_299,\r\n\teundefined_300,\r\n\teundefined_301,\r\n\teWM_CUT,\r\n\teWM_COPY,\r\n\teWM_PASTE,\r\n\teWM_CLEAR,\r\n\teWM_UNDO,\r\n\teWM_RENDERFORMAT,\r\n\teWM_RENDERALLFORMATS,\r\n\teWM_DESTROYCLIPBOARD,\r\n\teWM_DRAWCLIPBOARD,\r\n\teWM_PAINTCLIPBOARD,\r\n\teWM_VSCROLLCLIPBOARD,\r\n\teWM_SIZECLIPBOARD,\r\n\teWM_ASKCBFORMATNAME,\r\n\teWM_CHANGECBCHAIN,\r\n\teWM_HSCROLLCLIPBOARD,\r\n\teWM_QUERYNEWPALETTE,\r\n\teWM_PALETTEISCHANGING,\r\n\teWM_PALETTECHANGED,\r\n\teWM_HOTKEY,\r\n\teWM_SYSMENU,\r\n\teWM_HOOKMSG,\r\n\teWM_EXITPROCESS,\r\n\teWM_WAKETHREAD,\r\n\teWM_PRINT,\r\n\teWM_PRINTCLIENT,\r\n\teWM_APPCOMMAND,\r\n\teWM_THEMECHANGED,\r\n\teWM_UAHINIT,\r\n\teWM_DESKTOPNOTIFY,\r\n\teWM_CLIPBOARDUPDATE,\r\n\teWM_DWMCOMPOSITIONCHANGED,\r\n\teWM_DWMNCRENDERINGCHANGED,\r\n\teWM_DWMCOLORIZATIONCOLORCHANGED,\r\n\teWM_DWMWINDOWMAXIMIZEDCHANGE,\r\n\teWM_DWMEXILEFRAME,\r\n\teWM_DWMSENDICONICTHUMBNAIL,\r\n\teWM_MAGNIFICATION_STARTED,\r\n\teWM_MAGNIFICATION_ENDED,\r\n\teWM_DWMSENDICONICLIVEPREVIEWBITMAP,\r\n\teWM_DWMTHUMBNAILSIZECHANGED,\r\n\teWM_MAGNIFICATION_OUTPUT,\r\n\teWM_BSDRDATA,\r\n\teWM_DWMTRANSITIONSTATECHANGED,\r\n\teundefined_302,\r\n\teWM_KEYBOARDCORRECTIONCALLOUT,\r\n\teWM_KEYBOARDCORRECTIONACTION,\r\n\teWM_UIACTION,\r\n\teWM_ROUTED_UI_EVENT,\r\n\teWM_MEASURECONTROL,\r\n\teWM_GETACTIONTEXT,\r\n\teWM_CE_ONLY__reserved_332,\r\n\teWM_FORWARDKEYDOWN,\r\n\teWM_FORWARDKEYUP,\r\n\teWM_CE_ONLY__reserved_335,\r\n\teWM_CE_ONLY__reserved_336,\r\n\teWM_CE_ONLY__reserved_337,\r\n\teWM_CE_ONLY__reserved_338,\r\n\teWM_CE_ONLY__reserved_339,\r\n\teWM_CE_ONLY__reserved_33a,\r\n\teWM_CE_ONLY__reserved_33b,\r\n\teWM_CE_ONLY__reserved_33c,\r\n\teWM_CE_ONLY__reserved_33d,\r\n\teWM_CE_ONLY_LAST,\r\n\teWM_GETTITLEBARINFOEX,\r\n\teWM_NOTIFYWOW,\r\n\teundefined_303,\r\n\teundefined_304,\r\n\teundefined_305,\r\n\teundefined_306,\r\n\teundefined_307,\r\n\teundefined_308,\r\n\teundefined_309,\r\n\teundefined_310,\r\n\teundefined_311,\r\n\teundefined_312,\r\n\teundefined_313,\r\n\teundefined_314,\r\n\teundefined_315,\r\n\teundefined_316,\r\n\teundefined_317,\r\n\teundefined_318,\r\n\teundefined_319,\r\n\teundefined_320,\r\n\teundefined_321,\r\n\teundefined_322,\r\n\teundefined_323,\r\n\teundefined_324,\r\n\teundefined_325,\r\n\teWM_HANDHELDFIRST,\r\n\teWM_HANDHELD_reserved_359,\r\n\teWM_HANDHELD_reserved_35a,\r\n\teWM_HANDHELD_reserved_35b,\r\n\teWM_HANDHELD_reserved_35c,\r\n\teWM_HANDHELD_reserved_35d,\r\n\teWM_HANDHELD_reserved_35e,\r\n\teWM_HANDHELDLAST,\r\n\teWM_AFXFIRST,\r\n\teWM_AFX_reserved_361,\r\n\teWM_AFX_reserved_362,\r\n\teWM_AFX_reserved_363,\r\n\teWM_AFX_reserved_364,\r\n\teWM_AFX_reserved_365,\r\n\teWM_AFX_reserved_366,\r\n\teWM_AFX_reserved_367,\r\n\teWM_AFX_reserved_368,\r\n\teWM_AFX_reserved_369,\r\n\teWM_AFX_reserved_36a,\r\n\teWM_AFX_reserved_36b,\r\n\teWM_AFX_reserved_36c,\r\n\teWM_AFX_reserved_36d,\r\n\teWM_AFX_reserved_36e,\r\n\teWM_AFX_reserved_36f,\r\n\teWM_AFX_reserved_370,\r\n\teWM_AFX_reserved_371,\r\n\teWM_AFX_reserved_372,\r\n\teWM_AFX_reserved_373,\r\n\teWM_AFX_reserved_374,\r\n\teWM_AFX_reserved_375,\r\n\teWM_AFX_reserved_376,\r\n\teWM_AFX_reserved_377,\r\n\teWM_AFX_reserved_378,\r\n\teWM_AFX_reserved_379,\r\n\teWM_AFX_reserved_37a,\r\n\teWM_AFX_reserved_37b,\r\n\teWM_AFX_reserved_37c,\r\n\teWM_AFX_reserved_37d,\r\n\teWM_AFX_reserved_37e,\r\n\teWM_AFXLAST,\r\n\teWM_PENWINFIRST,\r\n\teWM_PENWIN_reserved_381,\r\n\teWM_PENWIN_reserved_382,\r\n\teWM_PENWIN_reserved_383,\r\n\teWM_PENWIN_reserved_384,\r\n\teWM_PENWIN_reserved_385,\r\n\teWM_PENWIN_reserved_386,\r\n\teWM_PENWIN_reserved_387,\r\n\teWM_PENWIN_reserved_388,\r\n\teWM_PENWIN_reserved_389,\r\n\teWM_PENWIN_reserved_38a,\r\n\teWM_PENWIN_reserved_38b,\r\n\teWM_PENWIN_reserved_38c,\r\n\teWM_PENWIN_reserved_38d,\r\n\teWM_PENWIN_reserved_38e,\r\n\teWM_PENWINLAST,\r\n\teWM_COALESCE_FIRST,\r\n\teWM_COALESCE__reserved_391,\r\n\teWM_COALESCE__reserved_392,\r\n\teWM_COALESCE__reserved_393,\r\n\teWM_COALESCE__reserved_394,\r\n\teWM_COALESCE__reserved_395,\r\n\teWM_COALESCE__reserved_396,\r\n\teWM_COALESCE__reserved_397,\r\n\teWM_COALESCE__reserved_398,\r\n\teWM_COALESCE__reserved_399,\r\n\teWM_COALESCE__reserved_39a,\r\n\teWM_COALESCE__reserved_39b,\r\n\teWM_COALESCE__reserved_39c,\r\n\teWM_COALESCE__reserved_39d,\r\n\teWM_COALESCE__reserved_39e,\r\n\teWM_COALESCE_LAST,\r\n\teWM_MM_RESERVED_FIRST,\r\n\teWM_MM_RESERVED__reserved_3a1,\r\n\teWM_MM_RESERVED__reserved_3a2,\r\n\teWM_MM_RESERVED__reserved_3a3,\r\n\teWM_MM_RESERVED__reserved_3a4,\r\n\teWM_MM_RESERVED__reserved_3a5,\r\n\teWM_MM_RESERVED__reserved_3a6,\r\n\teWM_MM_RESERVED__reserved_3a7,\r\n\teWM_MM_RESERVED__reserved_3a8,\r\n\teWM_MM_RESERVED__reserved_3a9,\r\n\teWM_MM_RESERVED__reserved_3aa,\r\n\teWM_MM_RESERVED__reserved_3ab,\r\n\teWM_MM_RESERVED__reserved_3ac,\r\n\teWM_MM_RESERVED__reserved_3ad,\r\n\teWM_MM_RESERVED__reserved_3ae,\r\n\teWM_MM_RESERVED__reserved_3af,\r\n\teWM_MM_RESERVED__reserved_3b0,\r\n\teWM_MM_RESERVED__reserved_3b1,\r\n\teWM_MM_RESERVED__reserved_3b2,\r\n\teWM_MM_RESERVED__reserved_3b3,\r\n\teWM_MM_RESERVED__reserved_3b4,\r\n\teWM_MM_RESERVED__reserved_3b5,\r\n\teWM_MM_RESERVED__reserved_3b6,\r\n\teWM_MM_RESERVED__reserved_3b7,\r\n\teWM_MM_RESERVED__reserved_3b8,\r\n\teWM_MM_RESERVED__reserved_3b9,\r\n\teWM_MM_RESERVED__reserved_3ba,\r\n\teWM_MM_RESERVED__reserved_3bb,\r\n\teWM_MM_RESERVED__reserved_3bc,\r\n\teWM_MM_RESERVED__reserved_3bd,\r\n\teWM_MM_RESERVED__reserved_3be,\r\n\teWM_MM_RESERVED__reserved_3bf,\r\n\teWM_MM_RESERVED__reserved_3c0,\r\n\teWM_MM_RESERVED__reserved_3c1,\r\n\teWM_MM_RESERVED__reserved_3c2,\r\n\teWM_MM_RESERVED__reserved_3c3,\r\n\teWM_MM_RESERVED__reserved_3c4,\r\n\teWM_MM_RESERVED__reserved_3c5,\r\n\teWM_MM_RESERVED__reserved_3c6,\r\n\teWM_MM_RESERVED__reserved_3c7,\r\n\teWM_MM_RESERVED__reserved_3c8,\r\n\teWM_MM_RESERVED__reserved_3c9,\r\n\teWM_MM_RESERVED__reserved_3ca,\r\n\teWM_MM_RESERVED__reserved_3cb,\r\n\teWM_MM_RESERVED__reserved_3cc,\r\n\teWM_MM_RESERVED__reserved_3cd,\r\n\teWM_MM_RESERVED__reserved_3ce,\r\n\teWM_MM_RESERVED__reserved_3cf,\r\n\teWM_MM_RESERVED__reserved_3d0,\r\n\teWM_MM_RESERVED__reserved_3d1,\r\n\teWM_MM_RESERVED__reserved_3d2,\r\n\teWM_MM_RESERVED__reserved_3d3,\r\n\teWM_MM_RESERVED__reserved_3d4,\r\n\teWM_MM_RESERVED__reserved_3d5,\r\n\teWM_MM_RESERVED__reserved_3d6,\r\n\teWM_MM_RESERVED__reserved_3d7,\r\n\teWM_MM_RESERVED__reserved_3d8,\r\n\teWM_MM_RESERVED__reserved_3d9,\r\n\teWM_MM_RESERVED__reserved_3da,\r\n\teWM_MM_RESERVED__reserved_3db,\r\n\teWM_MM_RESERVED__reserved_3dc,\r\n\teWM_MM_RESERVED__reserved_3dd,\r\n\teWM_MM_RESERVED__reserved_3de,\r\n\teWM_MM_RESERVED_LAST,\r\n\teWM_INTERNAL_DDE_FIRST,\r\n\teWM_INTERNAL_DDE__reserved_3e1,\r\n\teWM_INTERNAL_DDE__reserved_3e2,\r\n\teWM_INTERNAL_DDE__reserved_3e3,\r\n\teWM_INTERNAL_DDE__reserved_3e4,\r\n\teWM_INTERNAL_DDE__reserved_3e5,\r\n\teWM_INTERNAL_DDE__reserved_3e6,\r\n\teWM_INTERNAL_DDE__reserved_3e7,\r\n\teWM_INTERNAL_DDE__reserved_3e8,\r\n\teWM_INTERNAL_DDE__reserved_3e9,\r\n\teWM_INTERNAL_DDE__reserved_3ea,\r\n\teWM_INTERNAL_DDE__reserved_3eb,\r\n\teWM_INTERNAL_DDE__reserved_3ec,\r\n\teWM_INTERNAL_DDE__reserved_3ed,\r\n\teWM_INTERNAL_DDE__reserved_3ee,\r\n\teWM_INTERNAL_DDE_LAST,\r\n\teWM_CBT_RESERVED_FIRST,\r\n\teWM_CBT_RESERVED__reserved_3f1,\r\n\teWM_CBT_RESERVED__reserved_3f2,\r\n\teWM_CBT_RESERVED__reserved_3f3,\r\n\teWM_CBT_RESERVED__reserved_3f4,\r\n\teWM_CBT_RESERVED__reserved_3f5,\r\n\teWM_CBT_RESERVED__reserved_3f6,\r\n\teWM_CBT_RESERVED__reserved_3f7,\r\n\teWM_CBT_RESERVED__reserved_3f8,\r\n\teWM_CBT_RESERVED__reserved_3f9,\r\n\teWM_CBT_RESERVED__reserved_3fa,\r\n\teWM_CBT_RESERVED__reserved_3fb,\r\n\teWM_CBT_RESERVED__reserved_3fc,\r\n\teWM_CBT_RESERVED__reserved_3fd,\r\n\teWM_CBT_RESERVED__reserved_3fe,\r\n\teWM_CBT_RESERVED_LAST,\r\n};\r\n\r\n// Window Styles Helper enums.\r\n\r\nenum class WindowStyle\r\n\t: DWORD\r\n{\r\n\tNone,\r\n\tChild = WS_CHILD,\r\n\tBorder = WS_BORDER,\r\n\tCaption = WS_CAPTION,\r\n\tClipChildren = WS_CLIPCHILDREN,\r\n\tTabStop = WS_TABSTOP,\r\n\tLBS_MultiSel = LBS_MULTIPLESEL,\r\n\tLBS_ExtendedSel = LBS_EXTENDEDSEL,\r\n\tLBS_UseTabStops = LBS_USETABSTOPS,\r\n\tBS_Bitmap = BS_BITMAP,\r\n\tBS_OwnerDraw = BS_OWNERDRAW,\r\n\tSS_EndEllipsis = SS_ENDELLIPSIS,\r\n\tSS_PathEllipsis = SS_PATHELLIPSIS,\r\n\tSS_NoPrefix = SS_NOPREFIX,\r\n\tSS_LeftNoWordWrap = SS_LEFTNOWORDWRAP,\r\n\tSS_Center = SS_CENTER,\r\n\tSS_Right = SS_RIGHT,\r\n\tES_MultiLine = ES_MULTILINE,\r\n\tES_Password = ES_PASSWORD,\r\n\tES_ReadOnly = ES_READONLY,\r\n\tTVS_CheckBoxes = TVS_CHECKBOXES,\r\n\tCCS_NoParentAlign = CCS_NOPARENTALIGN,\r\n\tCCS_NoResize = CCS_NORESIZE,\r\n\tTCS_ForceLeftAlign = TCS_FORCELABELLEFT,\r\n\tPBS_Vertical = PBS_VERTICAL,\r\n\tMCS_MultiSelect = MCS_MULTISELECT,\r\n\tLVS_SingleSelect = LVS_SINGLESEL,\r\n\tLVS_ShowSelAlways = LVS_SHOWSELALWAYS,\r\n\tCBS_DropDown = CBS_DROPDOWN,\r\n\tCBS_Simple = CBS_SIMPLE,\r\n\tDTS_ShowNone = DTS_SHOWNONE\r\n};\r\n\r\nenum class WindowExStyle\r\n\t: DWORD\r\n{\r\n\tNone,\r\n\tDialogModalFrame = WS_EX_DLGMODALFRAME,\r\n\tParentNotify = WS_EX_NOPARENTNOTIFY,\r\n\tTopMost = WS_EX_TOPMOST,\r\n\tAcceptFiles = WS_EX_ACCEPTFILES,\r\n\tTransparent = WS_EX_TRANSPARENT,\r\n\tMDIChild = WS_EX_MDICHILD,\r\n\tToolWindow = WS_EX_TOOLWINDOW,\r\n\tWindowEdge = WS_EX_WINDOWEDGE,\r\n\tControlParent = WS_EX_CONTROLPARENT,\r\n\tClientEdge = WS_EX_CLIENTEDGE,\r\n\tComposited = WS_EX_COMPOSITED,\r\n\tLayered = WS_EX_LAYERED\r\n};\r\n\r\nenum class WindowAnimStyle\r\n\t: DWORD\r\n{\r\n\tNone\r\n};\r\n\r\ntemplate <EnumConcepts::IsNumeric T>\r\nconstexpr WindowStyle to_WindowStyle(T other) noexcept\r\n{\r\n\treturn gsl::narrow_cast<WindowStyle>(other);\r\n}\r\ntemplate <EnumConcepts::IsNumeric T>\r\nconstexpr WindowExStyle to_WindowExStyle(T other) noexcept\r\n{\r\n\treturn gsl::narrow_cast<WindowExStyle>(other);\r\n}\r\n\r\ninline WindowStyle dcxGetWindowStyle(HWND Hwnd) noexcept\r\n{\r\n\treturn to_WindowStyle(GetWindowLong(Hwnd, GWL_STYLE));\r\n}\r\n\r\ninline WindowExStyle dcxGetWindowExStyle(HWND Hwnd) noexcept\r\n{\r\n\treturn to_WindowExStyle(GetWindowLong(Hwnd, GWL_EXSTYLE));\r\n}\r\n\r\ninline WindowStyle dcxSetWindowStyle(HWND Hwnd, WindowStyle style) noexcept\r\n{\r\n\treturn to_WindowStyle(SetWindowLongPtr(Hwnd, GWL_STYLE, gsl::narrow_cast<LONG>(style)));\r\n}\r\n\r\ninline WindowExStyle dcxSetWindowExStyle(HWND Hwnd, WindowExStyle style) noexcept\r\n{\r\n\treturn to_WindowExStyle(SetWindowLongPtr(Hwnd, GWL_EXSTYLE, gsl::narrow_cast<LONG>(style)));\r\n}\r\n\r\ninline HWND dcxCreateWindow(const WindowExStyle ExStyles, const TCHAR* const szClass, const WindowStyle Styles, const RECT* const rc, HWND hParent, const UINT uID, const void* const pthis = nullptr) noexcept\r\n{\r\n\treturn CreateWindowEx(\r\n\t\tgsl::narrow_cast<DWORD>(ExStyles),\r\n\t\tszClass,\r\n\t\tnullptr,\r\n\t\tgsl::narrow_cast<DWORD>(Styles),\r\n\t\trc->left, rc->top, rc->right - rc->left, rc->bottom - rc->top,\r\n\t\thParent,\r\n\t\t(HMENU)uID,\r\n\t\tGetModuleHandle(nullptr),\r\n\t\t(LPVOID)pthis);\r\n}\r\n\r\ninline UINT dcxSetWindowID(HWND Hwnd, const UINT uID) noexcept\r\n{\r\n\treturn gsl::narrow_cast<UINT>(SetWindowLongPtr(Hwnd, GWLP_ID, gsl::narrow_cast<LONG>(uID)));\r\n}\r\n", "meta": {"hexsha": "8a2459930ef480c27c7746c66169811319f7d35a", "size": 25269, "ext": "h", "lang": "C", "max_stars_repo_path": "Classes/WindowStyles.h", "max_stars_repo_name": "twig/dcxdll", "max_stars_repo_head_hexsha": "cd0cb308b76daf0be614025d71670580007a0d78", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2015-02-21T05:41:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-26T00:48:31.000Z", "max_issues_repo_path": "Classes/WindowStyles.h", "max_issues_repo_name": "twig/dcxdll", "max_issues_repo_head_hexsha": "cd0cb308b76daf0be614025d71670580007a0d78", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 68.0, "max_issues_repo_issues_event_min_datetime": "2015-04-06T16:23:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T17:33:50.000Z", "max_forks_repo_path": "Classes/WindowStyles.h", "max_forks_repo_name": "twig/dcxdll", "max_forks_repo_head_hexsha": "cd0cb308b76daf0be614025d71670580007a0d78", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-04-01T09:39:33.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-04T23:53:29.000Z", "avg_line_length": 21.9539530843, "max_line_length": 208, "alphanum_fraction": 0.8039099292, "num_tokens": 8001, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09268776861426217, "lm_q2_score": 0.013428255038082983, "lm_q1q2_score": 0.0012446349958631358}}
{"text": "//          Copyright Jean Pierre Cimalando 2019.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE.md or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n#pragma once\n#include <gsl/gsl>\n#include <string>\n\nstruct fmidi_smf;\n\nstruct SMF_Encoding_Detector {\npublic:\n    void scan(const fmidi_smf &smf);\n\n    std::string general_encoding() const;\n    std::string encoding_for_text(gsl::cstring_span input) const;\n\n    std::string decode_to_utf8(gsl::cstring_span input) const;\n\nprivate:\n    static gsl::cstring_span encoding_from_marker(gsl::cstring_span input);\n    static gsl::cstring_span strip_encoding_marker(gsl::cstring_span text, gsl::cstring_span enc);\n\nprivate:\n    std::string encoding_;\n};\n", "meta": {"hexsha": "cb1f2fbbb9a4546ae9577181fb6cb668abe2b971", "size": 758, "ext": "h", "lang": "C", "max_stars_repo_path": "sources/player/smftext.h", "max_stars_repo_name": "jpcima/smf-dsp", "max_stars_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2020-07-08T15:23:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T23:08:17.000Z", "max_issues_repo_path": "sources/player/smftext.h", "max_issues_repo_name": "jpcima/smf-dsp", "max_issues_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2020-07-05T23:59:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-16T20:44:07.000Z", "max_forks_repo_path": "sources/player/smftext.h", "max_forks_repo_name": "jpcima/smf-dsp", "max_forks_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-07-10T18:48:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-22T08:05:13.000Z", "avg_line_length": 27.0714285714, "max_line_length": 98, "alphanum_fraction": 0.7321899736, "num_tokens": 186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.06371498891835771, "lm_q2_score": 0.019419346054312888, "lm_q1q2_score": 0.0012373034186522992}}
{"text": "#pragma once\n\n#include <gsl/gsl>\n#include <halley/text/halleystring.h>\n#include \"lua_reference.h\"\n\n#include \"halley/data_structures/hash_map.h\"\n\nstruct lua_State;\n\nnamespace Halley {\n\tclass Resources;\n\tclass LuaState;\n\n\tclass LuaState {\n\tpublic:\n\t\tLuaState(Resources& resources);\n\t\t~LuaState();\n\n\t\tconst LuaReference* tryGetModule(const String& moduleName) const;\n\t\tconst LuaReference& getModule(const String& moduleName) const;\n\t\tconst LuaReference& getOrLoadModule(const String& moduleName);\n\t\tconst LuaReference& loadModule(const String& moduleName, gsl::span<const gsl::byte> data);\n\t\tvoid unloadModule(const String& moduleName);\n\n\t\tvoid call(int nArgs, int nRets);\n\n\t\tlua_State* getRawState();\n\t\t\n\t\tvoid pushCallback(LuaCallback&& callback);\n\n\t\tvoid pushErrorHandler();\n\t\tvoid popErrorHandler();\n\t\tvoid pushLuaState(lua_State* lua);\n\t\tvoid popLuaState();\n\t\tString errorHandler(String message);\n\n\tprivate:\n\t\tlua_State* lua;\n\t\tVector<lua_State*> pushedStates;\n\t\tResources* resources;\n\n\t\tHashMap<String, LuaReference> modules;\n\t\tVector<std::unique_ptr<LuaCallback>> closures;\n\t\tstd::unique_ptr<LuaReference> errorHandlerRef;\n\t\tVector<int> errorHandlerStackPos;\n\n\t\tLuaReference loadScript(const String& chunkName, gsl::span<const gsl::byte> data);\n\n\t\tvoid print(String string);\n\t\tconst LuaReference& packageLoader(String moduleName);\n\t\tString printVariableAtTop(int maxDepth = 2, bool quote = true);\n\t};\n\n\tclass LuaStateOverrider {\n\tpublic:\n\t\tLuaStateOverrider(LuaState& state, lua_State* rawState);\n\t\t~LuaStateOverrider();\n\n\tprivate:\n\t\tLuaState& state;\n\t};\n}\n", "meta": {"hexsha": "675369eb2e74dfda8394864220f615a61a258254", "size": 1561, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engine/lua/include/halley/lua/lua_state.h", "max_stars_repo_name": "amrezzd/halley", "max_stars_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/engine/lua/include/halley/lua/lua_state.h", "max_issues_repo_name": "amrezzd/halley", "max_issues_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engine/lua/include/halley/lua/lua_state.h", "max_forks_repo_name": "amrezzd/halley", "max_forks_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.390625, "max_line_length": 92, "alphanum_fraction": 0.7540038437, "num_tokens": 380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06954175221934784, "lm_q2_score": 0.017712301036742092, "lm_q1q2_score": 0.0012317444499316164}}
{"text": "/*\n * Copyright (C) 2010-2011 Freescale Semiconductor, Inc. All Rights Reserved.\n */\n\n/*\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n\n * You should have received a copy of the GNU General Public License along\n * with this program; if not, write to the Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n */\n\n#include <gsl.h>\n\n#include <linux/timer.h>\n#include <linux/spinlock.h>\n#include <linux/slab.h>\n#include <linux/hardirq.h>\n#include <linux/semaphore.h>\n\ntypedef struct _gsl_autogate_t {\n    struct timer_list timer;\t\n    spinlock_t lock;\n    int active;\n    /* pending indicate the timer has been fired but clock not yet disabled. */\n    int pending;\n    int timeout;\n    gsl_device_t *dev;\n    struct work_struct dis_task;\n} gsl_autogate_t;\n\nstatic gsl_autogate_t *g_autogate[2];\nstatic DECLARE_MUTEX(sem_dev);\n\n#define KGSL_DEVICE_IDLE_TIMEOUT 5000\t/* unit ms */\n\nstatic void clk_disable_task(struct work_struct *work)\n{\n\tgsl_autogate_t *autogate;\n\tautogate = container_of(work, gsl_autogate_t, dis_task);\n\tif (autogate->dev->ftbl.device_idle)\n\t\tautogate->dev->ftbl.device_idle(autogate->dev, GSL_TIMEOUT_DEFAULT);\n\tkgsl_clock(autogate->dev->id, 0);\n\tautogate->pending = 0;\n}\n\nstatic int _kgsl_device_active(gsl_device_t *dev, int all)\n{\n\tunsigned long flags;\n\tint to_active = 0;\n\tgsl_autogate_t *autogate = dev->autogate;\n\tif (!autogate) {\n\t\tprintk(KERN_ERR \"%s: autogate has exited!\\n\", __func__);\n\t\treturn 0;\n\t}\n//\tprintk(KERN_ERR \"%s:%d id %d active %d\\n\", __func__, __LINE__, dev->id, autogate->active);\n\n\tspin_lock_irqsave(&autogate->lock, flags);\n\tif (in_interrupt()) {\n\t\tif (!autogate->active && !autogate->pending)\n\t\t\tBUG();\n\t} else {\n\t\tto_active = !autogate->active;\n\t\tautogate->active = 1;\n\t}\n\tmod_timer(&autogate->timer, jiffies + msecs_to_jiffies(autogate->timeout));\n\tspin_unlock_irqrestore(&autogate->lock, flags);\n\tif (to_active)\n\t\tkgsl_clock(autogate->dev->id, 1);\n\tif (to_active && all) {\n\t\tint index;\n\t\tindex = autogate->dev->id == GSL_DEVICE_G12 ? GSL_DEVICE_YAMATO - 1 :\n\t\t\tGSL_DEVICE_G12 - 1;\n\t\tdown(&sem_dev);\n\t\tif (g_autogate[index])\n\t\t\t_kgsl_device_active(g_autogate[index]->dev, 0);\n\t\tup(&sem_dev);\n\t}\n\treturn 0;\n}\nint kgsl_device_active(gsl_device_t *dev)\n{\n\treturn _kgsl_device_active(dev, 0);\n}\n\nstatic void kgsl_device_inactive(unsigned long data)\n{\n\tgsl_autogate_t *autogate = (gsl_autogate_t *)data;\n\tunsigned long flags;\n\n//\tprintk(KERN_ERR \"%s:%d id %d active %d\\n\", __func__, __LINE__, autogate->dev->id, autogate->active);\n\tdel_timer(&autogate->timer);\n\tspin_lock_irqsave(&autogate->lock, flags);\n\tWARN(!autogate->active, \"GPU Device %d is already inactive\\n\", autogate->dev->id);\n\tif (autogate->active) {\n\t\tautogate->active = 0;\n\t\tautogate->pending = 1;\n\t\tschedule_work(&autogate->dis_task);\n\t}\n\tspin_unlock_irqrestore(&autogate->lock, flags);\n}\n\nint kgsl_device_clock(gsl_deviceid_t id, int enable)\n{\n\tint ret = GSL_SUCCESS;\n\tgsl_device_t *device;\n\n\tdevice = &gsl_driver.device[id-1];       // device_id is 1 based\n\tif (device->flags & GSL_FLAGS_INITIALIZED) {\n\t\tif (enable)\n\t\t\tkgsl_device_active(device);\n\t\telse\n\t\t\tkgsl_device_inactive((unsigned long)device);\n\t} else {\n\t\tprintk(KERN_ERR \"%s: Dev %d clock is already off!\\n\", __func__, id);\n\t\tret = GSL_FAILURE;\n\t}\n\t\n\treturn ret;\n}\n\nint kgsl_device_autogate_init(gsl_device_t *dev)\n{\n\tgsl_autogate_t *autogate;\n\n//\tprintk(KERN_ERR \"%s:%d id %d\\n\", __func__, __LINE__, dev->id);\n\tautogate = kzalloc(sizeof(gsl_autogate_t), GFP_KERNEL);\n\tif (!autogate) {\n\t\tprintk(KERN_ERR \"%s: out of memory!\\n\", __func__);\n\t\treturn -ENOMEM;\n\t}\n\tdown(&sem_dev);\n\tautogate->dev = dev;\n\tautogate->active = 1;\n\tspin_lock_init(&autogate->lock);\n\tautogate->timeout = KGSL_DEVICE_IDLE_TIMEOUT;\n\tinit_timer(&autogate->timer);\n\tautogate->timer.expires = jiffies + msecs_to_jiffies(autogate->timeout);\n\tautogate->timer.function = kgsl_device_inactive;\n\tautogate->timer.data = (unsigned long)autogate;\n\tadd_timer(&autogate->timer);\n\tINIT_WORK(&autogate->dis_task, clk_disable_task);\n\tdev->autogate = autogate;\n\tg_autogate[dev->id - 1] = autogate;\n\tup(&sem_dev);\n\treturn 0;\n}\n\nvoid kgsl_device_autogate_exit(gsl_device_t *dev)\n{\n\tgsl_autogate_t *autogate = dev->autogate;\n\n//\tprintk(KERN_ERR \"%s:%d id %d active %d\\n\", __func__, __LINE__, dev->id,  autogate->active);\n\tdown(&sem_dev);\n\tdel_timer_sync(&autogate->timer);\n\tif (!autogate->active)\n\t\tkgsl_clock(autogate->dev->id, 1);\n\tflush_work(&autogate->dis_task);\n\tg_autogate[dev->id - 1] = NULL;\n\tup(&sem_dev);\n\tkfree(autogate);\n\tdev->autogate = NULL;\n}\n", "meta": {"hexsha": "210ce79eda7a0c5e7986dc05d19a292c965625e8", "size": 4972, "ext": "c", "lang": "C", "max_stars_repo_path": "linux-2.6.35.3/drivers/mxc/amd-gpu/platform/hal/linux/misc.c", "max_stars_repo_name": "isabella232/wireless-media-drive", "max_stars_repo_head_hexsha": "ab09fbd1194c8148131cf0a37425419253a137b0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2015-02-28T21:05:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T04:57:27.000Z", "max_issues_repo_path": "linux-2.6.35.3/drivers/mxc/amd-gpu/platform/hal/linux/misc.c", "max_issues_repo_name": "SanDisk-Open-Source/wireless-media-drive", "max_issues_repo_head_hexsha": "ab09fbd1194c8148131cf0a37425419253a137b0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-24T05:16:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-24T05:16:58.000Z", "max_forks_repo_path": "linux-2.6.35.3/drivers/mxc/amd-gpu/platform/hal/linux/misc.c", "max_forks_repo_name": "isabella232/wireless-media-drive", "max_forks_repo_head_hexsha": "ab09fbd1194c8148131cf0a37425419253a137b0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-11-19T16:42:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-07T12:39:23.000Z", "avg_line_length": 28.9069767442, "max_line_length": 103, "alphanum_fraction": 0.719227675, "num_tokens": 1521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08756384904745383, "lm_q2_score": 0.014063627353171185, "lm_q1q2_score": 0.0012314653426127244}}
{"text": "// stdafx.h\n// (c) 2008-2020, Charles Lechasseur\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n#pragma once\n\n// Including this header allows us to suppress C++ Core Guideline warnings more easily\n#include <CppCoreCheck\\warnings.h>\n\n// Disable C++ Core checks warnings in library headers since we don't control them\n#pragma warning(push)\n#pragma warning(disable: ALL_CPPCORECHECK_WARNINGS)\n\n#ifndef STRICT\n#define STRICT\n#endif\n\n#include \"targetver.h\"\n\n#define _ATL_APARTMENT_THREADED\n#define _ATL_NO_AUTOMATIC_NAMESPACE\n\n#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS\t// some CString constructors will be explicit\n\n//#define PCC_NO_CONTEXT_MENU_EXT2    // For testing purposes only\n\n#include <atlbase.h>\n#include <atlcom.h>\n#include <atlctl.h>\n#include <atlstr.h>\n#include <shlobj.h>\n#include <shobjidl.h>\n#include <windows.h>\n\n// Disable some warnings in GDI+ headers\n#pragma warning( push )\n#pragma warning( disable : 4458 )\n#include <gdiplus.h>\n#pragma warning( pop )\n\n// Undef the Windows min and max macros, since they conflict with STL\n// We can't define NOMINMAX because GDI actually needs those macros :(\n#undef min\n#undef max\n\n#include <algorithm>\n#include <cstdint>\n#include <exception>\n#include <functional>\n#include <map>\n#include <memory>\n#include <mutex>\n#include <set>\n#include <string>\n#include <vector>\n#include <utility>\n\n#include <assert.h>\n#include <memory.h>\n\n#include <resource.h>\n#include <PathCopyCopyLocalization_en\\rsrc\\resource.h>\n\n#include <gsl/gsl>\n\n#include <coveo/linq.h>\n\n#pragma warning(pop) // core checks in library headers\n\n#include \"PathCopyCopyPrivateTypes.h\"\n", "meta": {"hexsha": "48d4cdd58b68cfde97f0271e3c8404cb58b43f4e", "size": 2626, "ext": "h", "lang": "C", "max_stars_repo_path": "PathCopyCopy/prihdr/stdafx.h", "max_stars_repo_name": "subashnict/pathcopycopy", "max_stars_repo_head_hexsha": "27ab622b3d38e9db2e80837c4657d7e9f41d2316", "max_stars_repo_licenses": ["MIT", "Apache-2.0", "MS-PL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PathCopyCopy/prihdr/stdafx.h", "max_issues_repo_name": "subashnict/pathcopycopy", "max_issues_repo_head_hexsha": "27ab622b3d38e9db2e80837c4657d7e9f41d2316", "max_issues_repo_licenses": ["MIT", "Apache-2.0", "MS-PL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PathCopyCopy/prihdr/stdafx.h", "max_forks_repo_name": "subashnict/pathcopycopy", "max_forks_repo_head_hexsha": "27ab622b3d38e9db2e80837c4657d7e9f41d2316", "max_forks_repo_licenses": ["MIT", "Apache-2.0", "MS-PL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8409090909, "max_line_length": 88, "alphanum_fraction": 0.7619954303, "num_tokens": 602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.049589018770285855, "lm_q2_score": 0.024798161231614733, "lm_q1q2_score": 0.001229716482783118}}
{"text": "/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */\n/*\n *     Copyright 2017-Present Couchbase, Inc.\n *\n *   Use of this software is governed by the Business Source License included\n *   in the file licenses/BSL-Couchbase.txt.  As of the Change Date specified\n *   in that file, in accordance with the Business Source License, use of this\n *   software will be governed by the Apache License, Version 2.0, included in\n *   the file licenses/APL2.txt.\n */\n\n#pragma once\n\n#include <nlohmann/json_fwd.hpp>\n#include <gsl/gsl>\n\n#include <string>\n\nnamespace cb::breakpad {\n/**\n * What information should breakpad minidumps contain?\n */\nenum class Content {\n    /**\n     * Default content (threads+stack+env+arguments)\n     */\n    Default\n};\n\n/**\n * Settings for Breakpad crash catcher.\n */\nstruct Settings {\n    /**\n     * Default constructor initialize the object to be in a disabled state\n     */\n    Settings() = default;\n\n    /**\n     * Initialize the Breakpad object from the specified JSON structure\n     * which looks like:\n     *\n     *     {\n     *         \"enabled\" : true,\n     *         \"minidump_dir\" : \"/var/crash\",\n     *         \"content\" : \"default\"\n     *     }\n     *\n     * @param json The json to parse\n     * @throws std::invalid_argument if the json dosn't look as expected\n     */\n    explicit Settings(const nlohmann::json& json);\n\n    bool enabled{false};\n    std::string minidump_dir;\n    Content content{Content::Default};\n};\n\n} // namespace cb::breakpad\n\nstd::string to_string(cb::breakpad::Content content);\n", "meta": {"hexsha": "c1fb6a10456517e230968055b6d05cf8d2d403d0", "size": 1560, "ext": "h", "lang": "C", "max_stars_repo_path": "utilities/breakpad_settings.h", "max_stars_repo_name": "BenHuddleston/kv_engine", "max_stars_repo_head_hexsha": "78123c9aa2c2feb24b7c31eecc862bf2ed6325e4", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utilities/breakpad_settings.h", "max_issues_repo_name": "BenHuddleston/kv_engine", "max_issues_repo_head_hexsha": "78123c9aa2c2feb24b7c31eecc862bf2ed6325e4", "max_issues_repo_licenses": ["MIT", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utilities/breakpad_settings.h", "max_forks_repo_name": "BenHuddleston/kv_engine", "max_forks_repo_head_hexsha": "78123c9aa2c2feb24b7c31eecc862bf2ed6325e4", "max_forks_repo_licenses": ["MIT", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1612903226, "max_line_length": 79, "alphanum_fraction": 0.6365384615, "num_tokens": 386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.035144844379618526, "lm_q2_score": 0.03461883572666102, "lm_q1q2_score": 0.0012166735942170796}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef vdir_b62819a0_88a2_4eb7_9a92_6d287a152304_h\r\n#define vdir_b62819a0_88a2_4eb7_9a92_6d287a152304_h\r\n\r\n#include <gslib/config.h>\r\n#include <gslib/tree.h>\r\n#include <gslib/pool.h>\r\n\r\n__gslib_begin__\r\n\r\nclass dirop\r\n{\r\npublic:\r\n    virtual void get_current_dir(string& str);\r\n    virtual bool change_dir(const gchar* path);\r\n    virtual bool make_dir(const gchar* path);\r\n    virtual bool remove_dir(const gchar* path);\r\n};\r\n\r\nstruct vdirnode;\r\nstruct vdirfile;\r\ntypedef vdirnode vdirfolder;\r\ntypedef _treenode_wrapper<vdirnode> vdirwrapper;\r\ntypedef tree<vdirnode, vdirwrapper> vdirtree;\r\ntypedef vdirtree::iterator vdiriter;\r\ntypedef vdirtree::const_iterator vdirciter;\r\n\r\nstruct vdirnode\r\n{\r\n    enum\r\n    {\r\n        dt_folder,\r\n        dt_file,\r\n        dt_tag,\r\n    };\r\n    string          name;\r\n\r\npublic:\r\n    vdirnode() {}\r\n    vdirnode(const gchar* n) { name.assign(n); }\r\n    virtual uint get_tag() const { return dt_folder; }\r\n    virtual const gchar* get_name() const { return name.c_str(); }\r\n    void set_name(const gchar* str, int len) { name.assign(str, len); }\r\n    void set_name(const string& str) { name = str; }\r\n    void tracing() const;\r\n};\r\n\r\nstruct vdirfile:\r\n    public vdirnode\r\n{\r\n    vessel          vsl;\r\n\r\npublic:\r\n    vdirfile() {}\r\n    vdirfile(const gchar* n): vdirnode(n) {}\r\n    virtual uint get_tag() const override { return dt_file; }\r\n\r\npublic:\r\n    const gchar* get_postfix() const;\r\n    void set_file_data(const void* ptr, int size);\r\n    void set_file_data(const gchar* filename);\r\n};\r\n\r\nstruct vdirtag:\r\n    public vdirnode\r\n{\r\n    void*           binding;\r\n\r\npublic:\r\n    vdirtag() { binding = 0; }\r\n    vdirtag(const gchar* n): vdirnode(n) { binding = 0; }\r\n    virtual uint get_tag() const override { return dt_tag; }\r\n    void set_binding(void* p) { binding = p; }\r\n    void* get_binding() const { return binding; }\r\n};\r\n\r\nclass vdir:\r\n    public vdirtree\r\n{\r\npublic:\r\n    vdiriter create_folder(vdiriter pos, const gchar* name);\r\n    vdiriter create_file(vdiriter pos, const gchar* name);\r\n    vdiriter create_tag(vdiriter pos, const gchar* name);\r\n    void save(const gchar* path);\r\n};\r\n\r\nclass vdirop:\r\n    public dirop\r\n{\r\npublic:\r\n    vdirop(vdir& d): _dir(d) {}\r\n    virtual void get_current_dir(string& str) override;\r\n    virtual bool change_dir(const gchar* path) override;\r\n    virtual bool make_dir(const gchar* path) override;\r\n    virtual bool remove_dir(const gchar* path) override;\r\n\r\nprotected:\r\n    vdir&           _dir;\r\n    vdiriter        _curr;\r\n\r\npublic:\r\n    vdiriter step_or_create(vdiriter pos, const gchar* name);\r\n    vdiriter step_once(vdiriter pos, const gchar* name);\r\n    vdiriter step_to(vdiriter pos, const gchar* path);\r\n    vdiriter locate_folder(vdiriter pos, const gchar* name);\r\n    vdiriter locate_file(vdiriter pos, const gchar* name);\r\n    vdiriter create_folder(const gchar* name) { return _dir.create_folder(_curr, name); }\r\n    vdiriter create_file(const gchar* name) { return _dir.create_file(_curr, name); }\r\n    vdiriter get_current_iter() const { return _curr; }\r\n    void rewind_curr() { _curr = _dir.get_root(); }\r\n};\r\n\r\n__gslib_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "6c9d75d369b5a29eba22dbdf8095f32b074ec6ab", "size": 4409, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gslib/vdir.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/gslib/vdir.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gslib/vdir.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 31.0492957746, "max_line_length": 90, "alphanum_fraction": 0.6867770469, "num_tokens": 1111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.04535257926399331, "lm_q2_score": 0.026759284931777455, "lm_q1q2_score": 0.0012136025909162188}}
{"text": "\n#pragma once\n\n#include <gsl/gsl>\n\n#include <memory>\n#include <list>\n#include <chrono>\n\n#include <EASTL/fixed_vector.h>\n#include <EASTL/map.h>\n\n#include \"../platform/d3d.h\"\n\n#include \"buffers.h\"\n#include \"shaders.h\"\n#include \"camera.h\"\n#include \"textures.h\"\n\nstruct ID3D11Texture2D;\n\nnamespace gfx {\n\t\n\tclass RenderingDevice;\n\tclass Material;\n\tstruct RasterizerSpec;\n\tclass RasterizerState;\n\tstruct BlendSpec;\n\tclass BlendState;\n\tstruct DepthStencilSpec;\n\tclass DepthStencilState;\n\tstruct SamplerSpec;\n\tclass SamplerState;\n\tstruct MaterialSamplerSpec;\n\tclass BufferBinding;\n\tclass TextEngine;\n\t\n\tusing SamplerStatePtr = std::shared_ptr<SamplerState>;\n\tusing DepthStencilStatePtr = std::shared_ptr<DepthStencilState>;\n\tusing BlendStatePtr = std::shared_ptr<BlendState>;\n\tusing RasterizerStatePtr = std::shared_ptr<RasterizerState>;\n\n\tusing ResizeListener = std::function<void(int w, int h)>;\n\n\t// RAII style listener registration\n\tclass ResizeListenerRegistration {\n\t\tfriend class RenderingDevice;\n\tpublic:\t\t\n\t\t~ResizeListenerRegistration();\n\n\t\tNO_COPY(ResizeListenerRegistration);\n\n\t\tResizeListenerRegistration(ResizeListenerRegistration &&o) : mDevice(o.mDevice), mKey(o.mKey) {\n\t\t\to.mKey = 0;\n\t\t}\n\t\tResizeListenerRegistration &operator =(ResizeListenerRegistration &&o) = delete;\n\tprivate:\n\t\tResizeListenerRegistration(gfx::RenderingDevice &device, uint32_t key) : mDevice(device), mKey(key) {}\n\n\t\tgfx::RenderingDevice &mDevice;\n\t\tuint32_t mKey;\t\t\n\t};\n\n\tclass ResourceListener {\n\tpublic:\n\t\tvirtual ~ResourceListener();\n\n\t\tvirtual void CreateResources(RenderingDevice&) = 0;\n\t\tvirtual void FreeResources(RenderingDevice&) = 0;\n\t};\n\n\tenum class StandardSlotSemantic {\n\t\tViewProjMatrix,\n\t\tUiProjMatrix\n\t};\n\n\t// RAII class for managing resource listener registrations\n\tclass ResourceListenerRegistration {\n\tpublic:\n\t\texplicit ResourceListenerRegistration(RenderingDevice& device, ResourceListener* listener);\n\t\t~ResourceListenerRegistration();\n\n\t\tNO_COPY_OR_MOVE(ResourceListenerRegistration);\n\n\tprivate:\n\t\tRenderingDevice& mDevice;\n\t\tResourceListener* mListener;\n\t};\n\n\tusing DynamicTexturePtr = std::shared_ptr<class DynamicTexture>;\n\tusing RenderTargetTexturePtr = std::shared_ptr<class RenderTargetTexture>;\n\tusing RenderTargetDepthStencilPtr = std::shared_ptr<class RenderTargetDepthStencil>;\n\n\t// An output of a display device (think: monitor)\n\tstruct DisplayDeviceOutput {\n\t\t// Technical id for use in a configuration or log file\n\t\tstd::string id;\n\t\t// Name to display to the end user\n\t\tstd::string name;\n\t};\n\n\t// A display device that can be used to render the game (think: GPU)\n\tstruct DisplayDevice {\n\t\t// Technical id for use in a configuration or log file\n\t\tsize_t id;\n\t\t// Name to display to the end user\n\t\tstd::string name;\n\t\t// Outputs associated with this display device\n\t\teastl::fixed_vector<DisplayDeviceOutput, 4> outputs;\n\t};\n\n\tenum class PrimitiveType {\n\t\tTriangleList,\n\t\tTriangleStrip,\n\t\tLineStrip,\n\t\tLineList,\n\t\tPointList,\n\t};\n\n\tenum class BufferFormat {\n\t\tA8,\n\t\tA8R8G8B8,\n\t\tX8R8G8B8\n\t};\n\n\tenum class MapMode {\n\t\tRead,\n\t\tDiscard,\n\t\tNoOverwrite\n\t};\n\t\n\ttemplate<typename TBuffer, typename TElement>\n\tclass MappedBuffer {\n\tpublic:\n\n\t\tusing View = gsl::span<TElement>;\n\t\tusing Iterator = gsl::contiguous_span_iterator<View>;\n\n\t\tMappedBuffer(TBuffer &buffer,\n\t\t\tRenderingDevice &device,\n\t\t\tView data,\n\t\t\tuint32_t rowPitch) : mBuffer(buffer), mDevice(device), mData(data), mRowPitch(rowPitch) {}\n\n\t\tMappedBuffer(MappedBuffer&& o) : mBuffer(o.mBuffer), mDevice(o.mDevice), mData(o.mData), mRowPitch(o.rowPitch) {\n\t\t\to.mMoved = true;\n\t\t}\n\n\t\t~MappedBuffer();\n\n\t\tIterator begin() {\n\t\t\treturn mData.begin();\n\t\t}\n\n\t\tIterator end() {\n\t\t\treturn mData.end();\n\t\t}\n\n\t\tTElement &operator[](size_t idx) {\n\t\t\tassert(!mMoved);\n\t\t\treturn mData[idx];\n\t\t}\n\n\t\tsize_t size() const {\n\t\t\treturn mData.size();\n\t\t}\n\n\t\tTElement *GetData() const {\n\t\t\treturn mData.data();\n\t\t}\n\n\t\t// Only relevant for mapped texture buffers\n\t\tsize_t GetRowPitch() const {\n\t\t\treturn mRowPitch;\n\t\t}\n\n\t\tvoid Unmap();\n\n\tprivate:\n\t\tTBuffer& mBuffer;\n\t\tRenderingDevice &mDevice;\n\t\tView mData;\n\t\tsize_t mRowPitch;\n\t\tbool mMoved = false;\n\t};\n\n\ttemplate<typename TElement>\n\tusing MappedVertexBuffer = MappedBuffer<VertexBuffer, TElement>;\n\tusing MappedIndexBuffer = MappedBuffer<IndexBuffer, uint16_t>;\n\tusing MappedTexture = MappedBuffer<DynamicTexture, uint8_t>;\n\n\tclass RenderingDevice {\n\ttemplate<typename T>\n\tfriend class Shader;\n\tfriend class BufferBinding;\n\tfriend class TextureLoader;\n\tfriend class DebugUI;\n\tpublic:\n\t\tRenderingDevice(HWND mWindowHandle, uint32_t adapterIdx = 0, bool debugDevice = false);\n\t\t~RenderingDevice();\n\n\t\tbool BeginFrame();\n\t\tbool Present();\n\t\tvoid PresentForce();\n\t\tvoid Flush();\n\n\t\tvoid ClearCurrentColorTarget(XMCOLOR color);\n\n\t\tvoid ClearCurrentDepthTarget(bool clearDepth = true, \n\t\t\tbool clearStencil = true, \n\t\t\tfloat depthValue = 1.0f, \n\t\t\tuint8_t stencilValue = 0);\n\n\t\tusing Clock = std::chrono::high_resolution_clock;\n\t\tusing TimePoint = std::chrono::time_point<Clock>;\n\n\t\tTimePoint GetLastFrameStart() const {\n\t\t\treturn mLastFrameStart;\n\t\t}\n\t\tTimePoint GetDeviceCreated() const {\n\t\t\treturn mDeviceCreated;\n\t\t}\n\n\t\tconst eastl::vector<DisplayDevice> &GetDisplayDevices();\n\n\t\t// Resize the back buffer\n\t\tvoid ResizeBuffers(int w, int h);\n\n\t\tMaterial CreateMaterial(\n\t\t\tconst BlendSpec &blendSpec,\n\t\t\tconst DepthStencilSpec &depthStencilSpec,\n\t\t\tconst RasterizerSpec &rasterizerSpec,\n\t\t\tconst std::vector<MaterialSamplerSpec> &samplerSpecs,\n\t\t\tconst VertexShaderPtr &vs,\n\t\t\tconst PixelShaderPtr &ps\n\t\t);\n\n\t\tBlendStatePtr CreateBlendState(const BlendSpec &spec);\n\t\tDepthStencilStatePtr CreateDepthStencilState(const DepthStencilSpec &spec);\n\t\tRasterizerStatePtr CreateRasterizerState(const RasterizerSpec &spec);\n\t\tSamplerStatePtr CreateSamplerState(const SamplerSpec &spec);\n\n\t\t// Changes the current scissor rect to the given rectangle\n\t\tvoid SetScissorRect(int x, int y, int width, int height);\n\n\t\t// Resets the scissor rect to the current render target's size\n\t\tvoid ResetScissorRect();\n\t\t\t\t\n\t\tstd::shared_ptr<class IndexBuffer> CreateEmptyIndexBuffer(size_t count);\n\t\tstd::shared_ptr<class VertexBuffer> CreateEmptyVertexBuffer(size_t count, bool forPoints = false);\n\t\tDynamicTexturePtr CreateDynamicTexture(gfx::BufferFormat format, int width, int height);\n\t\tDynamicTexturePtr CreateDynamicStagingTexture(gfx::BufferFormat format, int width, int height);\n\t\tvoid CopyRenderTarget(gfx::RenderTargetTexture &renderTarget, gfx::DynamicTexture &stagingTexture);\n\t\tRenderTargetTexturePtr CreateRenderTargetTexture(gfx::BufferFormat format, int width, int height, bool multiSampled = false);\n\t\tRenderTargetTexturePtr CreateRenderTargetForNativeSurface(ID3D11Texture2D *surface);\n\t\tRenderTargetTexturePtr CreateRenderTargetForSharedSurface(IUnknown *surface);\n\t\tRenderTargetDepthStencilPtr CreateRenderTargetDepthStencil(int width, int height, bool multiSampled = false);\n\n\t\ttemplate<typename T>\n\t\tVertexBufferPtr CreateVertexBuffer(gsl::span<T> data, bool immutable = true);\n\t\tVertexBufferPtr CreateVertexBufferRaw(gsl::span<const uint8_t> data, bool immutable = true);\n\t\tIndexBufferPtr CreateIndexBuffer(gsl::span<const uint16_t> data, bool immutable = true);\n\n\t\tvoid SetMaterial(const Material &material);\n\t\tvoid SetVertexShaderConstant(uint32_t startRegister, StandardSlotSemantic semantic);\n\t\tvoid SetPixelShaderConstant(uint32_t startRegister, StandardSlotSemantic semantic);\n\n\t\tvoid SetRasterizerState(const RasterizerState &state);\n\t\tvoid SetBlendState(const BlendState &state);\n\t\tvoid SetDepthStencilState(const DepthStencilState &state);\n\t\tvoid SetSamplerState(int samplerIdx, const SamplerState &state);\n\n\t\tvoid SetTexture(uint32_t slot, gfx::Texture &texture);\n\n\t\tvoid SetIndexBuffer(const gfx::IndexBuffer &indexBuffer);\n\n\t\tvoid Draw(PrimitiveType type, uint32_t vertexCount, uint32_t startVertex = 0);\n\t\t\n\t\tvoid DrawIndexed(PrimitiveType type, uint32_t vertexCount, uint32_t indexCount, uint32_t startVertex = 0, uint32_t vertexBase = 0);\n\n\t\t/*\n\t\t  Changes the currently used cursor to the given surface.\n\t\t */\n\t\tvoid SetCursor(int hotspotX, int hotspotY, const gfx::TextureRef &texture);\n\t\tvoid ShowCursor();\n\t\tvoid HideCursor();\n\n\t\t/*\n\t\t\tTake a screenshot with the given size. The image will be stretched \n\t\t\tto the given size.\n\t\t*/\n\t\tvoid TakeScaledScreenshot(const std::string& filename, int width, int height, int quality = 90);\n\n\t\t// Creates a buffer binding for a MDF material that\n\t\t// is preinitialized with the correct shader\n\t\tBufferBinding CreateMdfBufferBinding();\n\n\t\tShaders& GetShaders() {\n\t\t\treturn mShaders;\n\t\t}\n\n\t\tTextures& GetTextures() {\n\t\t\treturn mTextures;\n\t\t}\n\n\t\tWorldCamera& GetCamera() {\n\t\t\treturn mCamera;\n\t\t}\n\n\t\tvoid SetAntiAliasing(bool enable, uint32_t samples, uint32_t quality);\n\t\t\n\t\ttemplate<typename T>\n\t\tvoid UpdateBuffer(VertexBuffer &buffer, gsl::span<T> data) {\n\t\t\tUpdateBuffer(buffer, data.data(), data.size_bytes());\n\t\t}\n\n\t\tvoid UpdateBuffer(VertexBuffer &buffer, const void *data, size_t size);\n\t\t\n\t\tvoid UpdateBuffer(IndexBuffer &buffer, gsl::span<uint16_t> data);\n\t\t\t\t\n\t\ttemplate<typename TElement>\n\t\tMappedVertexBuffer<TElement> Map(VertexBuffer &buffer, gfx::MapMode mode = gfx::MapMode::Discard) {\n\t\t\tauto data = MapVertexBufferRaw(buffer, mode);\n\t\t\tauto castData = gsl::span<TElement>((TElement*)data.data(), data.size() / sizeof(TElement));\n\t\t\treturn MappedVertexBuffer<TElement>(buffer, *this, castData, 0);\n\t\t}\n\t\tvoid Unmap(VertexBuffer &buffer);\n\n\t\t// Index buffer memory mapping techniques\n\t\tMappedIndexBuffer Map(IndexBuffer &buffer, gfx::MapMode mode = gfx::MapMode::Discard);\n\t\tvoid Unmap(IndexBuffer &buffer);\n\n\t\tMappedTexture Map(DynamicTexture &texture, gfx::MapMode mode = gfx::MapMode::Discard);\n\t\tvoid Unmap(DynamicTexture &texture);\n\n\t\tstatic constexpr uint32_t MaxVsConstantBufferSize = 2048;\n\n\t\ttemplate<typename T>\n\t\tvoid SetVertexShaderConstants(uint32_t slot, const T &buffer) {\n\t\t\tstatic_assert(sizeof(T) <= MaxVsConstantBufferSize, \"Constant buffer exceeds maximum size\");\n\t\t\tUpdateResource(mVsConstantBuffer, &buffer, sizeof(T));\n\t\t\tVSSetConstantBuffer(slot, mVsConstantBuffer);\n\t\t}\n\n\t\tstatic constexpr uint32_t MaxPsConstantBufferSize = 512;\n\n\t\ttemplate<typename T>\n\t\tvoid SetPixelShaderConstants(uint32_t slot, const T &buffer) {\n\t\t\tstatic_assert(sizeof(T) <= MaxPsConstantBufferSize, \"Constant buffer exceeds maximum size\");\n\t\t\tUpdateResource(mPsConstantBuffer, &buffer, sizeof(T));\n\t\t\tPSSetConstantBuffer(slot, mPsConstantBuffer);\n\t\t}\n\n\t\tconst gfx::Size &GetBackBufferSize() const;\n\n\t\t// Pushes the back buffer and it's depth buffer as the current render target\n\t\tvoid PushBackBufferRenderTarget();\n\t\tvoid PushRenderTarget(\n\t\t\tconst gfx::RenderTargetTexturePtr &colorBuffer,\n\t\t\tconst gfx::RenderTargetDepthStencilPtr &depthStencilBuffer\n\t\t);\n\t\tvoid PopRenderTarget();\n\t\tconst gfx::RenderTargetTexturePtr &GetCurrentRederTargetColorBuffer() const {\n\t\t\treturn mRenderTargetStack.back().colorBuffer;\n\t\t}\n\t\tconst gfx::RenderTargetDepthStencilPtr &GetCurrentRenderTargetDepthStencilBuffer() const {\n\t\t\treturn mRenderTargetStack.back().depthStencilBuffer;\n\t\t}\n\n\t\tResizeListenerRegistration AddResizeListener(ResizeListener listener);\n\n\t\tbool IsDebugDevice() const;\n\n\t\t/**\n\t\t * Emits the start of a rendering call group if the debug device is being used. \n\t\t * This information can be used in the graphic debugger.\n\t\t */\n\t\ttemplate<typename... T>\n\t\tvoid BeginPerfGroup(const char *format, const T &... args) const {\n\t\t\tif (IsDebugDevice()) {\n\t\t\t\tBeginPerfGroupInternal(fmt::format(format, args...).c_str());\n\t\t\t}\n\t\t}\n\t\t/**\n\t\t * Ends a previously started performance group.\n\t\t */\n\t\tvoid EndPerfGroup() const;\n\n\t\tTextEngine& GetTextEngine() const;\n\n\tprivate:\n\t\tfriend class ResourceListenerRegistration;\n\t\tfriend class ResizeListenerRegistration;\n\n\t\tvoid BeginPerfGroupInternal(const char *msg) const;\n\n\t\tvoid RemoveResizeListener(uint32_t key);\n\n\t\tvoid AddResourceListener(ResourceListener* resourceListener);\n\t\tvoid RemoveResourceListener(ResourceListener* resourceListener);\n\n\t\tvoid UpdateResource(ID3D11Resource *resource, const void *data, size_t size);\n\t\tCComPtr<ID3D11Buffer> CreateConstantBuffer(const void *initialData, size_t initialDataSize);\n\t\tvoid VSSetConstantBuffer(uint32_t slot, ID3D11Buffer *buffer);\n\t\tvoid PSSetConstantBuffer(uint32_t slot, ID3D11Buffer *buffer);\n\n\t\tgsl::span<uint8_t> MapVertexBufferRaw(VertexBuffer &buffer, MapMode mode);\n\t\t\n\t\tCComPtr<IDXGIAdapter1> GetAdapter(size_t index);\n\t\t\n\t\tint mBeginSceneDepth = 0;\n\t\t\n\t\tHWND mWindowHandle;\n\n\t\tCComPtr<IDXGIFactory1> mDxgiFactory;\n\n\t\t// The DXGI adapter we use\n\t\tCComPtr<IDXGIAdapter1> mAdapter;\n\t\t\t\t\n\t\t// D3D11 device and related\n\t\tCComPtr<ID3D11Device> mD3d11Device;\n\t\tCComPtr<ID3D11Device1> mD3d11Device1;\n\t\tDXGI_SWAP_CHAIN_DESC mSwapChainDesc;\n\t\tCComPtr<IDXGISwapChain> mSwapChain;\n\t\tCComPtr<ID3D11DeviceContext> mContext;\n\t\tgfx::RenderTargetTexturePtr mBackBufferNew;\n\t\tgfx::RenderTargetDepthStencilPtr mBackBufferDepthStencil;\n\t\t\n\t\tstruct RenderTarget {\n\t\t\tgfx::RenderTargetTexturePtr colorBuffer;\n\t\t\tgfx::RenderTargetDepthStencilPtr depthStencilBuffer;\n\t\t};\n\t\teastl::fixed_vector<RenderTarget, 16> mRenderTargetStack;\n\n\t\tD3D_FEATURE_LEVEL mFeatureLevel = D3D_FEATURE_LEVEL_9_1;\n\n\t\teastl::vector<DisplayDevice> mDisplayDevices;\n\t\t\n\t\tCComPtr<ID3D11Buffer> mVsConstantBuffer;\n\t\tCComPtr<ID3D11Buffer> mPsConstantBuffer;\n\t\t\n\t\teastl::map<uint32_t, ResizeListener> mResizeListeners;\n\t\tuint32_t mResizeListenersKey = 0;\n\n\t\tstd::list<ResourceListener*> mResourcesListeners;\n\t\tbool mResourcesCreated = false;\n\t\t\n\t\t\n\t\tTimePoint mLastFrameStart = Clock::now();\n\t\tTimePoint mDeviceCreated = Clock::now();\n\n\t\tsize_t mUsedSamplers = 0;\n\n\t\tShaders mShaders;\n\t\tTextures mTextures;\n\t\tWorldCamera mCamera;\n\n\t\tstruct Impl;\n\t\tstd::unique_ptr<Impl> mImpl;\n\t};\n\t\n\ttemplate <typename T>\n\tVertexBufferPtr RenderingDevice::CreateVertexBuffer(gsl::span<T> data, bool immutable) {\n\t\treturn CreateVertexBufferRaw(gsl::span(reinterpret_cast<const uint8_t*>(&data[0]), data.size_bytes()), immutable);\n\t}\n\n\textern RenderingDevice *renderingDevice;\n\n\ttemplate<typename TBuffer, typename TElement>\n\tinline MappedBuffer<TBuffer, TElement>::~MappedBuffer()\n\t{\n\t\tif (!mMoved) {\n\t\t\tmDevice.Unmap(mBuffer);\n\t\t}\n\t}\n\n\ttemplate<typename TBuffer, typename TElement>\n\tinline void MappedBuffer<TBuffer, TElement>::Unmap()\n\t{\n\t\tassert(!mMoved);\n\t\tmMoved = true;\n\t\tmDevice.Unmap(mBuffer);\n\t}\n\n\tinline ResizeListenerRegistration::~ResizeListenerRegistration() {\n\t\tmDevice.RemoveResizeListener(mKey);\n\t}\n\n\n\t// RAII style demarcation of render call groups for performance debugging\n\tclass PerfGroup {\n\tpublic:\n\t\ttemplate<typename... T>\n\t\tPerfGroup(RenderingDevice &device, const char *format, T... args) : mDevice(device) {\n\t\t\tdevice.BeginPerfGroup(format, args...);\n\t\t}\n\t\t~PerfGroup() {\n\t\t\tmDevice.EndPerfGroup();\n\t\t}\n\tprivate:\n\t\tconst RenderingDevice &mDevice;\n\t};\n\n}\n", "meta": {"hexsha": "c5fb4325206987a91be637a0ea3e015867b98d08", "size": 14786, "ext": "h", "lang": "C", "max_stars_repo_path": "Infrastructure/include/graphics/device.h", "max_stars_repo_name": "edoipi/TemplePlus", "max_stars_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Infrastructure/include/graphics/device.h", "max_issues_repo_name": "edoipi/TemplePlus", "max_issues_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Infrastructure/include/graphics/device.h", "max_forks_repo_name": "edoipi/TemplePlus", "max_forks_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3373015873, "max_line_length": 133, "alphanum_fraction": 0.7580819694, "num_tokens": 3743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09401017453990974, "lm_q2_score": 0.012821216918802756, "lm_q1q2_score": 0.001205324840350691}}
{"text": "/***\n * Copyright 2019 The Katla Authors\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#ifndef KATLA_CORE_H\n#define KATLA_CORE_H\n\n#include \"outcome/outcome.hpp\"\nnamespace outcome = OUTCOME_V2_NAMESPACE;\n\n#include \"fmt/format.h\"\n\n#include <gsl/span>\n\n#include <cstdio>\n#include <cstdlib>\n#include <string_view>\n\n#ifdef _MSC_VER\n    #ifdef KATLA_CORE_INDLL\n    # define KATLA_CORE_DECLSPEC __declspec(dllexport)\n    #else\n    # define KATLA_CORE_DECLSPEC __declspec(dllimport)\n    #endif\n#else\n    #define KATLA_CORE_DECLSPEC\n#endif\n\nnamespace katla {\n\n    template<class T, std::size_t Extent>\n    using span = gsl::span<T, Extent>;\n\n    /****\n     * Declare format and print here for convenience. Current implementation uses the Fmt lib,\n     * the idea is to use std c++ format later. Which is the reason for the indirection.\n     */\n    template <typename S, typename... Args>\n    inline std::string format(const S& format_str, Args&&... args) {\n        return fmt::format(format_str, args...);\n    }\n\n    template <typename S, typename... Args>\n    inline void print(std::FILE* f, const S& format_str, Args&&... args) {\n        fmt::print(f, format_str, args...);\n    }\n\n    template <typename S, typename... Args>\n    inline void printInfo(const S& message, Args&&... args) {\n        print(stdout, fmt::format(\"{}\\n\", message), args...);\n        fflush(stdout);\n    }\n\n    template <typename S, typename... Args>\n    inline void printError(const S& message, Args&&... args) {\n        print(stderr, fmt::format(\"{}\\n\", message), args...);\n        fflush(stderr);\n    }\n\n    template <typename S, typename... Args>\n    inline void fatal(const S& message, Args&&... args) {\n        print(stderr, fmt::format(\"{}\\n\", message), args...);\n        fflush(stderr);\n        std::abort();\n    }\n}\n\n#endif // KATLA_CORE_H\n", "meta": {"hexsha": "a6063c02be5477959cf5041afbbc428011c3d5db", "size": 2331, "ext": "h", "lang": "C", "max_stars_repo_path": "core/core.h", "max_stars_repo_name": "plok/katla", "max_stars_repo_head_hexsha": "aaaeb8baf041bba7259275beefc71c8452a16223", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "core/core.h", "max_issues_repo_name": "plok/katla", "max_issues_repo_head_hexsha": "aaaeb8baf041bba7259275beefc71c8452a16223", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-03-25T14:33:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-16T14:21:56.000Z", "max_forks_repo_path": "core/core.h", "max_forks_repo_name": "plok/katla", "max_forks_repo_head_hexsha": "aaaeb8baf041bba7259275beefc71c8452a16223", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-26T13:32:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-26T13:32:36.000Z", "avg_line_length": 28.7777777778, "max_line_length": 94, "alphanum_fraction": 0.6628056628, "num_tokens": 572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.03676946185350724, "lm_q2_score": 0.0325897412425357, "lm_q1q2_score": 0.001198307247433088}}
{"text": "//          Copyright Jean Pierre Cimalando 2019.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE.md or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n#pragma once\n#include \"configuration.h\"\n#include \"utility/geometry.h\"\n#include \"utility/SDL++.h\"\n#include <SDL.h>\n#include <gsl/gsl>\n#include <mutex>\n#include <vector>\n#include <memory>\nclass File_Browser;\nclass File_Entry;\nclass Metadata_Display;\nclass Level_Meter;\nclass Modal_Box;\nclass Player;\nstruct Player_State;\nclass Main_Layout;\nstruct Midi_Output;\n\nclass Application\n{\npublic:\n    static const Point size_;\n\n    Application();\n    ~Application();\n\n    SDL_Window *init_window();\n    SDL_Renderer *init_renderer();\n    void exec();\n\n    void set_scale_factor(SDL_Window *win, unsigned sf);\n    void paint(SDL_Renderer *rr, int paint);\n    void paint_scaled(SDL_Renderer *rr, int paint, unsigned scale);\n    void paint_cached_background(SDL_Renderer *rr);\n    bool handle_key_pressed(const SDL_KeyboardEvent &event);\n    bool handle_key_released(const SDL_KeyboardEvent &event);\n    bool handle_mouse_pressed(const SDL_MouseButtonEvent &event);\n    bool handle_mouse_released(const SDL_MouseButtonEvent &event);\n    bool handle_text_input(const SDL_TextInputEvent &event);\n\n    void play_file(const std::string &dir, const File_Entry *entries, size_t index, size_t count);\n    void play_random(const std::string &dir, const File_Entry &entry);\n    void set_current_path(const std::string &path);\n    static bool filter_file_name(const std::string &name);\n    static bool filter_file_entry(const File_Entry &ent);\n\n    void request_update();\n    void update_modals();\n    void open_help_dialog();\n    void open_fx_dialog();\n    void choose_midi_output(bool ask, gsl::cstring_span choice);\n    void choose_synth(bool ask, gsl::cstring_span choice);\n    void get_midi_outputs(std::vector<Midi_Output> &outputs);\n\n    void choose_theme(gsl::cstring_span choice);\n    void get_themes(std::vector<std::string> &themes);\n\n    void load_theme(gsl::cstring_span theme);\n    void load_default_theme();\n    void load_theme_configuration(const CSimpleIniA &ini);\n    void get_fx_parameters(const CSimpleIniA &ini, int *values) const;\n\n    void engage_shutdown();\n    void engage_shutdown_if_esc_key();\n    void advance_shutdown();\n    bool should_quit() const;\n\nprivate:\n    std::unique_ptr<CSimpleIniA> initialize_config();\n\nprivate:\n    void receive_state_in_other_thread(const Player_State &ps);\n\nprivate:\n    SDLpp_Window_u window_;\n    SDLpp_Renderer_u renderer_;\n\n    SDL_TimerID update_timer_ = 0;\n\n    std::unique_ptr<Main_Layout> layout_;\n    std::vector<std::unique_ptr<Modal_Box>> modal_;\n    SDLpp_Texture_u cached_background_;\n\n    SDLpp_Surface_u logo_image_;\n    SDLpp_Surface_u wallpaper_image_;\n\n    bool fadeout_engaged_ = false;\n    int fadeout_time_ = 0;\n\n    uint32_t esc_key_timer_ = 0;\n\n    unsigned scale_factor_ = 1;\n    std::unique_ptr<File_Browser> file_browser_;\n    std::unique_ptr<Metadata_Display> metadata_display_;\n    std::unique_ptr<Level_Meter> level_meter_[10];\n    std::unique_ptr<Player> player_;\n\n    std::string last_midi_output_choice_;\n    std::string last_synth_choice_;\n    std::string last_theme_choice_;\n\n    std::unique_ptr<Player_State> ps_;\n    std::mutex ps_mutex_;\n\n    enum Info_Mode {\n        Info_File,\n        Info_Metadata,\n        Info_Mode_Count,\n    };\n    Info_Mode info_mode_ = Info_File;\n};\n", "meta": {"hexsha": "856ae8e062860141a33bc8bfb8b1588f7c125548", "size": 3464, "ext": "h", "lang": "C", "max_stars_repo_path": "sources/application.h", "max_stars_repo_name": "jpcima/smf-dsp", "max_stars_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2020-07-08T15:23:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T23:08:17.000Z", "max_issues_repo_path": "sources/application.h", "max_issues_repo_name": "jpcima/smf-dsp", "max_issues_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2020-07-05T23:59:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-16T20:44:07.000Z", "max_forks_repo_path": "sources/application.h", "max_forks_repo_name": "jpcima/smf-dsp", "max_forks_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-07-10T18:48:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-22T08:05:13.000Z", "avg_line_length": 29.3559322034, "max_line_length": 98, "alphanum_fraction": 0.7338337182, "num_tokens": 809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08389038641057996, "lm_q2_score": 0.014281934947778723, "lm_q1q2_score": 0.0011981170414599232}}
{"text": "#ifndef DART_POINTERS_H\n#define DART_POINTERS_H\n\n/*----- System Includes -----*/\n\n#include <atomic>\n#include <memory>\n#include <gsl/gsl>\n#include <stdint.h>\n#include <functional>\n#include <type_traits>\n\n/*----- System Includes -----*/\n\n#include \"../refcount_traits.h\"\n\n/*----- Type Declarations -----*/\n\nnamespace dart {\n\n  namespace detail {\n\n    template <class T>\n    struct managed_ptr_deleter {\n      void operator ()(T ptr);\n    };\n\n    template <class T>\n    struct managed_ptr_deleter<T[]> {\n      void operator ()(std::remove_extent_t<T>* ptr);\n    };\n\n    // Type-erasure mechanism for counted_ptr_base.\n    template <class Counter>\n    struct managed_ptr {\n      managed_ptr(void* ptr, int64_t use_count) : ptr(ptr), use_count(use_count) {}\n      virtual ~managed_ptr() = default;\n      virtual void destroy() = 0;\n\n      void* ptr;\n      Counter use_count;\n    };\n    template <class Counter, class PtrType, class Deleter>\n    struct managed_ptr_eraser : managed_ptr<Counter> {\n      managed_ptr_eraser(void const* ptr, int64_t use_count) : managed_ptr<Counter>(const_cast<void*>(ptr), use_count) {}\n      managed_ptr_eraser(void const* ptr, int64_t use_count, Deleter const& deleter) :\n        managed_ptr<Counter>(const_cast<void*>(ptr), use_count),\n        deleter(deleter)\n      {}\n      managed_ptr_eraser(void const* ptr, int64_t use_count, Deleter&& deleter) :\n        managed_ptr<Counter>(const_cast<void*>(ptr), use_count),\n        deleter(std::move(deleter))\n      {}\n      virtual void destroy() override;\n\n      Deleter deleter;\n    };\n\n    template <class T, class Counter>\n    class counted_ptr_base {\n\n      public:\n\n        /*----- Public Types -----*/\n\n        using element_type = T;\n        using counter_type = Counter;\n        template <class U>\n        using ptr_type = std::conditional_t<std::is_array<U>::value, U, U*>;\n\n        /*----- Lifecycle Functions -----*/\n\n        counted_ptr_base() noexcept : value(nullptr) {}\n        counted_ptr_base(std::nullptr_t) noexcept : value(nullptr) {}\n        explicit counted_ptr_base(ptr_type<T> ptr) :\n          value(new managed_ptr_eraser<counter_type, ptr_type<T>, managed_ptr_deleter<ptr_type<T>>>(ptr, 1))\n        {}\n        template <class Deleter>\n        counted_ptr_base(ptr_type<T> ptr, Deleter&& deleter) :\n          value(new managed_ptr_eraser<counter_type, ptr_type<T>, Deleter>(ptr, 1, std::move(deleter)))\n        {}\n        template <class U, class EnableIf =\n          std::enable_if_t<\n            std::is_convertible<ptr_type<U>, ptr_type<T>>::value\n          >\n        >\n        counted_ptr_base(counted_ptr_base<U, counter_type> const& other) noexcept;\n        template <class U, class EnableIf =\n          std::enable_if_t<\n            std::is_convertible<ptr_type<U>, ptr_type<T>>::value\n          >\n        >\n        counted_ptr_base(counted_ptr_base<U, counter_type>&& other) noexcept;\n        template <class U, class Deleter, class EnableIf =\n          std::enable_if_t<\n            std::is_same<ptr_type<U>, ptr_type<T>>::value\n            ||\n            std::is_convertible<ptr_type<U>, ptr_type<T>>::value\n          >\n        >\n        counted_ptr_base(std::unique_ptr<U, Deleter>&& ptr);\n        counted_ptr_base(counted_ptr_base const& other) noexcept;\n        counted_ptr_base(counted_ptr_base&& other) noexcept;\n        ~counted_ptr_base() noexcept;\n\n        /*----- Operators -----*/\n\n        // Assignment.\n        template <class U, class EnableIf =\n          std::enable_if_t<\n            std::is_convertible<ptr_type<U>, ptr_type<T>>::value\n          >\n        >\n        counted_ptr_base& operator =(counted_ptr_base<U, counter_type> const& other) noexcept;\n        template <class U, class EnableIf =\n          std::enable_if_t<\n            std::is_convertible<ptr_type<U>, ptr_type<T>>::value\n          >\n        >\n        counted_ptr_base& operator =(counted_ptr_base<U, counter_type>&& other) noexcept;\n        counted_ptr_base& operator =(counted_ptr_base const& other) noexcept;\n        counted_ptr_base& operator =(counted_ptr_base&& other) noexcept;\n        template <class U, class Deleter, class EnableIf =\n          std::enable_if_t<\n            std::is_convertible<ptr_type<U>, ptr_type<T>>::value\n          >\n        >\n        counted_ptr_base& operator =(std::unique_ptr<U, Deleter>&& ptr)\n          noexcept(std::is_nothrow_move_constructible<Deleter>::value);\n\n        // Comparison.\n        bool operator ==(counted_ptr_base const& other) const noexcept;\n        bool operator !=(counted_ptr_base const& other) const noexcept;\n        bool operator <(counted_ptr_base const& other) const noexcept;\n        bool operator <=(counted_ptr_base const& other) const noexcept;\n        bool operator >(counted_ptr_base const& other) const noexcept;\n        bool operator >=(counted_ptr_base const& other) const noexcept;\n\n        // Conversion.\n        explicit operator bool() const noexcept;\n\n        /*----- Public API -----*/\n\n        // Accessors.\n        std::remove_extent_t<element_type>* get() const noexcept;\n        bool unique() const noexcept;\n        int64_t use_count() const noexcept;\n\n        // Mutators.\n        void reset() noexcept;\n        template <class U, class EnableIf =\n          std::enable_if_t<\n            std::is_convertible<U, ptr_type<T>>::value\n          >\n        >\n        void reset(U ptr);\n        template <class U, class Deleter, class EnableIf =\n          std::enable_if_t<\n            std::is_convertible<U, ptr_type<T>>::value\n          >\n        >\n        void reset(U ptr, Deleter&& deleter);\n\n      protected:\n\n        /*----- Protected Members -----*/\n\n        gsl::owner<managed_ptr<counter_type>*> value;\n\n        /*----- Friends -----*/\n\n        template <class U, class C>\n        friend class counted_ptr_base;\n\n    };\n\n    template <class T, class Counter>\n    struct counted_ptr_impl : counted_ptr_base<T, Counter> {\n\n      /*----- Types -----*/\n\n      using typename counted_ptr_base<T, Counter>::element_type;\n\n      /*----- Lifecycle Functions -----*/\n\n      using counted_ptr_base<T, Counter>::counted_ptr_base;\n\n      /*----- Operators -----*/\n\n      // Dereference.\n      auto operator *() const noexcept -> element_type&;\n      auto operator ->() const noexcept -> element_type*;\n\n      // Comparison.\n      using counted_ptr_base<T, Counter>::operator ==;\n      using counted_ptr_base<T, Counter>::operator !=;\n      using counted_ptr_base<T, Counter>::operator <;\n      using counted_ptr_base<T, Counter>::operator <=;\n      using counted_ptr_base<T, Counter>::operator >;\n      using counted_ptr_base<T, Counter>::operator >=;\n      using counted_ptr_base<T, Counter>::operator bool;\n\n    };\n\n    template <class T, class Counter>\n    struct counted_array_ptr_impl : counted_ptr_base<T, Counter> {\n\n      /*----- Types -----*/\n\n      using index_type = std::ptrdiff_t;\n      using element_type = std::remove_extent_t<typename counted_ptr_base<T, Counter>::element_type>;\n\n      /*----- Lifecycle Functions -----*/\n\n      using counted_ptr_base<T, Counter>::counted_ptr_base;\n\n      /*----- Operators -----*/\n\n      // Derefence.\n      element_type& operator [](index_type idx) const noexcept;\n\n      // Comparison.\n      using counted_ptr_base<T, Counter>::operator ==;\n      using counted_ptr_base<T, Counter>::operator !=;\n      using counted_ptr_base<T, Counter>::operator <;\n      using counted_ptr_base<T, Counter>::operator <=;\n      using counted_ptr_base<T, Counter>::operator >;\n      using counted_ptr_base<T, Counter>::operator >=;\n      using counted_ptr_base<T, Counter>::operator bool;\n\n    };\n\n  }\n\n  template <class T>\n  class shareable_ptr {\n\n    public:\n\n      /*----- Public Types -----*/\n\n      using value_type = T;\n      using element_type = typename refcount_traits<T>::element_type;\n\n    private:\n\n      struct is_nothrow_assignable :\n        meta::conjunction<\n          typename refcount_traits<T>::is_nothrow_copyable,\n          typename refcount_traits<T>::is_nothrow_moveable\n        >\n      {};\n\n      // XXX: MSVC gets confused if this is used directly in a noexcept specification.\n      struct is_nothrow_default_constructible :\n        std::integral_constant<bool,\n          refcount_traits<T>::template can_nothrow_take<element_type*, std::default_delete<element_type>>::value\n        >\n      {};\n    \n    public:\n\n      /*----- Lifecycle Functions -----*/\n\n      // Converting constructors.\n      shareable_ptr(std::nullptr_t)\n          noexcept(is_nothrow_default_constructible::value) :\n        shareable_ptr()\n      {}\n      template <class U, class D, class EnableIf =\n        std::enable_if_t<\n          refcount::can_take<T, U*, D>::value\n        >\n      >\n      explicit shareable_ptr(std::unique_ptr<U, D>&& ptr)\n          noexcept(refcount_traits<T>::template can_nothrow_take<U*, D>::value);\n      shareable_ptr(T const& other) noexcept(refcount_traits<T>::is_nothrow_copyable::value);\n      shareable_ptr(T&& other) noexcept(refcount_traits<T>::is_nothrow_moveable::value);\n\n      // Ownership transfer constructors.\n      template <class U, class =\n        std::enable_if_t<\n          refcount::can_take<T, U*, std::default_delete<U>>::value\n        >\n      >\n      explicit shareable_ptr(U* owner)\n          noexcept(refcount_traits<T>::template can_nothrow_take<U*, std::default_delete<U>>::value) :\n        shareable_ptr(owner, std::default_delete<U> {})\n      {}\n      template <class U, class D, class EnableIf =\n        std::enable_if_t<\n          refcount::can_take<T, U*, D>::value\n        >\n      >\n      explicit shareable_ptr(U* owner, D&& del)\n          noexcept(refcount_traits<T>::template can_nothrow_take<U*, D>::value);\n\n      // Special Constructors.\n      shareable_ptr() noexcept(is_nothrow_default_constructible::value);\n      shareable_ptr(shareable_ptr const& other) noexcept(refcount_traits<T>::is_nothrow_copyable::value);\n      shareable_ptr(shareable_ptr&& other) noexcept(refcount_traits<T>::is_nothrow_moveable::value);\n      ~shareable_ptr() noexcept;\n\n      /*----- Operators -----*/\n\n      // Assignment.\n      template <class U, class D, class EnableIf =\n        std::enable_if_t<\n          refcount::can_take<T, U*, D>::value\n        >\n      >\n      shareable_ptr& operator =(std::unique_ptr<U, D>&& ptr)\n          noexcept(refcount_traits<T>::template can_nothrow_take<U*, D>::value);\n      shareable_ptr& operator =(T const& other) noexcept(is_nothrow_assignable::value);\n      shareable_ptr& operator =(T&& other) noexcept;\n      shareable_ptr& operator =(std::nullptr_t) noexcept(is_nothrow_default_constructible::value);\n      shareable_ptr& operator =(shareable_ptr const& other) noexcept(is_nothrow_assignable::value);\n      shareable_ptr& operator =(shareable_ptr&& other) noexcept;\n\n      // Dereference.\n      auto operator *() const noexcept(refcount_traits<T>::is_nothrow_unwrappable::value) -> element_type&;\n      auto operator ->() const noexcept(refcount_traits<T>::is_nothrow_unwrappable::value) -> element_type*;\n\n      // Comparison.\n      bool operator ==(shareable_ptr const& other) const noexcept(refcount_traits<T>::is_nothrow_unwrappable::value);\n      bool operator !=(shareable_ptr const& other) const noexcept(refcount_traits<T>::is_nothrow_unwrappable::value);\n      bool operator <(shareable_ptr const& other) const noexcept(refcount_traits<T>::is_nothrow_unwrappable::value);\n      bool operator <=(shareable_ptr const& other) const noexcept(refcount_traits<T>::is_nothrow_unwrappable::value);\n      bool operator >(shareable_ptr const& other) const noexcept(refcount_traits<T>::is_nothrow_unwrappable::value);\n      bool operator >=(shareable_ptr const& other) const noexcept(refcount_traits<T>::is_nothrow_unwrappable::value);\n\n      // Conversion.\n      explicit operator bool() const noexcept(refcount_traits<T>::is_nothrow_unwrappable::value);\n\n      /*----- Public API -----*/\n\n      // Accessors.\n      auto get() const noexcept(refcount_traits<T>::is_nothrow_unwrappable::value) -> element_type*;\n      bool unique() const noexcept(refcount_traits<T>::has_nothrow_use_count::value);\n      int64_t use_count() const noexcept(refcount_traits<T>::has_nothrow_use_count::value);\n\n      // Mutators.\n      void reset() noexcept(refcount_traits<T>::has_nothrow_reset::value);\n\n      // Extremely awkward \"copy-constructor\" that allows us to copy our\n      // wrapped value into a raw instance of T.\n      // Function has to be written this way since we can't assume T is copyable/moveable\n      // The only thing we can definitely do with T is pass it into dart::refcount_traits::copy.\n      void share(T& ptr) const noexcept(refcount_traits<T>::is_nothrow_copyable::value);\n\n      // Extremely awkward \"move-constructor\" that allows us to move our\n      // wrapped value into a raw instance of T.\n      // Function has to be written this way since we can't assume T is copyable/moveable\n      // The only thing we can definitely do with T is pass it into dart::refcount_traits::move.\n      void transfer(T& ptr) && noexcept(refcount_traits<T>::is_nothrow_moveable::value);\n\n      auto raw() noexcept -> value_type&;\n      auto raw() const noexcept -> value_type const&;\n\n    private:\n\n      /*----- Private Types -----*/\n\n      struct partial_construction_tag {};\n\n      /*----- Private Lifecycle Functions -----*/\n\n      shareable_ptr(partial_construction_tag) {}\n\n      /*----- Private Members -----*/\n\n      union {\n        value_type impl;\n      };\n\n      /*----- Friends -----*/\n\n      template <class U, class... Args>\n      friend shareable_ptr<U> make_shareable(Args&&...);\n\n  };\n\n  template <template <class> class RefCount>\n  struct view_ptr_context {\n\n    template <class T>\n    class view_ptr {\n\n      public:\n\n        /*----- Public Types -----*/\n\n        using refcount_type = RefCount<T>;\n        using is_nonowning = refcount_type;\n        using element_type = typename refcount_traits<refcount_type>::element_type;\n\n        // XXX: Necessary to make logic in refcount_traits work.\n        template <template <template <class> class> class Binder>\n        using refcount_rebind = Binder<RefCount>;\n\n        /*----- Lifecycle Functions -----*/\n\n        // Functions must exist for refcount concept, but will throw if called\n        // as view_ptr doesn't have ownership semantics\n        explicit view_ptr(T*);\n        template <class Del>\n        explicit view_ptr(T*, Del&&);\n        \n        // I'm not currently disallowing construction from temporaries\n        // I can imagine scenarios where it could be useful, and generally,\n        // you'll need to know what you're doing to work with the view types\n        view_ptr(std::nullptr_t) noexcept : view_ptr() {}\n        view_ptr(refcount_type const& owner) noexcept : impl(&owner) {}\n\n        // Lifecycle functions mostly do nothing\n        view_ptr() noexcept : impl(nullptr) {}\n        view_ptr(view_ptr const&) = default;\n        view_ptr(view_ptr&& other) noexcept;\n        ~view_ptr() = default;\n\n        /*----- Operators -----*/\n\n        auto operator =(refcount_type const& owner) noexcept -> view_ptr&;\n\n        auto operator =(view_ptr const&) -> view_ptr& = default;\n        auto operator =(view_ptr&& other) noexcept -> view_ptr&;\n\n        auto operator *() const noexcept(refcount_traits<refcount_type>::is_nothrow_unwrappable::value) -> element_type&;\n        auto operator ->() const noexcept(refcount_traits<refcount_type>::is_nothrow_unwrappable::value) -> element_type*;\n\n        bool operator ==(view_ptr const& other) const noexcept(refcount_traits<refcount_type>::is_nothrow_unwrappable::value);\n        bool operator !=(view_ptr const& other) const noexcept(refcount_traits<refcount_type>::is_nothrow_unwrappable::value);\n        bool operator <(view_ptr const& other) const noexcept(refcount_traits<refcount_type>::is_nothrow_unwrappable::value);\n        bool operator <=(view_ptr const& other) const noexcept(refcount_traits<refcount_type>::is_nothrow_unwrappable::value);\n        bool operator >(view_ptr const& other) const noexcept(refcount_traits<refcount_type>::is_nothrow_unwrappable::value);\n        bool operator >=(view_ptr const& other) const noexcept(refcount_traits<refcount_type>::is_nothrow_unwrappable::value);\n\n        explicit operator bool() const noexcept(refcount_traits<refcount_type>::is_nothrow_unwrappable::value);\n\n        operator refcount_type const&() const;\n\n        /*----- Public API -----*/\n\n        auto get() const noexcept(refcount_traits<refcount_type>::is_nothrow_unwrappable::value) -> element_type*;\n        size_t use_count() const noexcept(refcount_traits<refcount_type>::has_nothrow_use_count::value);\n\n        void reset() noexcept;\n\n        auto raw() const noexcept -> refcount_type const&;\n\n      private:\n\n        /*----- Private Members -----*/\n\n        refcount_type const* impl;\n\n    };\n\n  };\n\n  template <class T>\n  using unsafe_ptr = std::conditional_t<\n    std::is_same<\n      std::remove_extent_t<T>,\n      T\n    >::value,\n    detail::counted_ptr_impl<T, int64_t>,\n    detail::counted_array_ptr_impl<T, int64_t>\n  >;\n\n  template <class T, class EnableIf =\n    std::enable_if_t<\n      std::is_array<T>::value\n    >\n  >\n  unsafe_ptr<T> make_unsafe(size_t idx);\n\n  template <class T, class... Args>\n  std::enable_if_t<!std::is_array<T>::value, unsafe_ptr<T>> make_unsafe(Args&&... the_args);\n\n  template <class T>\n  using skinny_ptr = std::conditional_t<\n    std::is_same<\n      std::remove_extent_t<T>,\n      T\n    >::value,\n    detail::counted_ptr_impl<T, std::atomic<int64_t>>,\n    detail::counted_array_ptr_impl<T, std::atomic<int64_t>>\n  >;\n\n  template <class T, class EnableIf =\n    std::enable_if_t<\n      std::is_array<T>::value\n    >\n  >\n  skinny_ptr<T> make_skinny(size_t idx);\n\n  template <class T, class... Args>\n  std::enable_if_t<!std::is_array<T>::value, skinny_ptr<T>> make_skinny(Args&&... the_args);\n\n}\n\n/*----- Template Implementations -----*/\n\n#include \"ptrs.tcc\"\n\n#endif\n", "meta": {"hexsha": "423d1744e39fcd1463354868d362c6c2fbc98d32", "size": 17948, "ext": "h", "lang": "C", "max_stars_repo_path": "include/dart/support/ptrs.h", "max_stars_repo_name": "Cfretz244/libdart", "max_stars_repo_head_hexsha": "987b01aa1f11455ac6aaf89f8e60825e92e6ec25", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2019-05-09T19:12:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-07T16:31:55.000Z", "max_issues_repo_path": "include/dart/support/ptrs.h", "max_issues_repo_name": "Cfretz244/libdart", "max_issues_repo_head_hexsha": "987b01aa1f11455ac6aaf89f8e60825e92e6ec25", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2019-05-09T22:37:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-29T03:25:16.000Z", "max_forks_repo_path": "include/dart/support/ptrs.h", "max_forks_repo_name": "Cfretz244/libdart", "max_forks_repo_head_hexsha": "987b01aa1f11455ac6aaf89f8e60825e92e6ec25", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-05-11T08:05:10.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-11T11:05:17.000Z", "avg_line_length": 35.3307086614, "max_line_length": 126, "alphanum_fraction": 0.6442500557, "num_tokens": 4171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.0675466911396291, "lm_q2_score": 0.017712299351558814, "lm_q1q2_score": 0.0011964072136723962}}
{"text": "#pragma once\n#include <exception>\n#include <iostream>\n#include <cstdlib>\n#include <functional>\n#include <memory>\n#include <vector>\n#include <gsl/gsl>\n\n#define VK_USE_PLATFORM_WIN32_KHR\n#include <vulkan/vulkan.h>\n#define GLFW_INCLUDE_VULKAN\n#include <GLFW/glfw3.h>\n#define GLFW_EXPOSE_NATIVE_WIN32\n#include <GLFW/glfw3native.h>\n\n#ifdef max\n#undef max\n#endif\n#ifdef min\n#undef min\n#endif\n\n\n/*\nWe define this in case we want to use VulkanMemoryAllocator's\nallocators.\n\n\t- https://github.com/GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator\n\nCurrently we are using the allocator by default so allocation of\nbuffers and images without VMA_USE_ALLOCATOR could not be fully supported.\n*/\n#define VMA_USE_ALLOCATOR\n\n#include \"../utils/Utils.h\"\n#include \"./RenderUtils.h\"\n#include \"../Configuration.h\"\n#include \"RenderData.h\"\n\n\n/**\nUsed for managing all the rendering logic of the application.\n\nManages creation, destruction and use of all the resources necessary\nto render to the screen using the Vulkan API.\n*/\nclass Renderer\n{\nprivate:\n\tusing WindowPtr = std::unique_ptr<GLFWwindow, GLFWWindowDestroyer>;\n\npublic:\n\t/**\n\tDefault Constructor.\n\tSince we tie a lot of the resources to this instance and we need to\n\tmanage them only from here the copy and move functionalities are not allowed.\n\t*/\n\t[[gsl::suppress(26439)]] Renderer();\n\tRenderer(const Renderer&) = delete;\n\tRenderer& operator=(const Renderer&) = delete;\n\tRenderer(Renderer&&) = delete;\n\tRenderer& operator=(Renderer&&) = delete;\n\t~Renderer();\n\n\t/* --------------------------------------------------------------------------------------------------------- */\n\t/* ---------------------------------------- PUBLIC FUNCTION MEMBERS ---------------------------------------- */\n\t/* --------------------------------------------------------------------------------------------------------- */\n\n\t/**\n\tUpdates the uniform buffer for the object being rendered\n\n\t@TODO: Reformat this function out of the renderer.\n\n\t@see m_uniform_buffer\n\t*/\n\tauto updateRotateTestUniformBuffer() ->void;\n\n\t/**\n\tSets up the beggining of a frame. Setting up the recording of a\n\tone time command buffer to submit to the rendering queue.\n\t*/\n\tauto beginFrame() -> void;\n\n\t/**\n\tFinishes the rendering stages and submits all the necessary information\n\tto the graphics card for rendering.\n\t*/\n\tauto endFrame() -> void;\n\n\t/**\n\tReturns true when we should close the application as far as the render manager\n\tis concerned. Currently it deals with the user closing the window itself.\n\n\t@return true if the window has been closed or we should end the application.\n\t*/\n\tauto shouldClose() const noexcept -> bool;\n\nprivate:\n\n\t/* ---------------------------------------------------------------------------------------------------------- */\n\t/* ---------------------------------------- PRIVATE FUNCTION MEMBERS ---------------------------------------- */\n\t/* ---------------------------------------------------------------------------------------------------------- */\n\n\t/**\n\tInitializes the physical window shown by the operating system\n\n\t@see m_window\n\t*/\n\tauto initWindow() noexcept -> void;\n\n\t/**\n\tInitializes all the Vulkan related components necessary for rendering to\n\tthe screen.\n\t*/\n\tauto initVulkan() -> void;\n\n\t/**\n\tRecreates all the necessary members to create a new swap chain, for example\n\twhen resizing the window.\n\t*/\n\tauto recreateSwapChain() -> void;\n\n\t/**\n\tCleans up all the resources that need to be explicitly cleaned up,\n\tmostly related to the Vulkan API and its resources.\n\t*/\n\tauto cleanup() noexcept -> void;\n\n\t/**\n\tCleans up all the resources related to the swap chain, this is useful when\n\trecreating the swap chain to be sure we are not leaking memory and resources.\n\t*/\n\tauto cleanupSwapChain() noexcept -> void;\n\n\t/**\n\tCreates a Vulkan instance based on the current configuration parameters.\n\n\t@see m_instance\n\t@return A Valid Vulkan Instance\n\t*/\n\tauto createInstance()->VkInstance;\n\n\t/**\n\tPrints to standard output all the extension names of all the extensions provided.\n\n\t@param a vector with the extensions you would like to print\n\t*/\n\tauto printInstanceExtensions(const std::vector<VkExtensionProperties>& extensions)\n\t\tconst -> void;\n\n\t/**\n\tChecks and prints if all the required extensions provided are available within the available ones.\n\n\t@param The vector of the names of the required extensions\n\t@param The vector of the struct with the properties of the available extensions\n\t@return true if all the required extensions are within the available ones, false otherwise.\n\t*/\n\t[[gsl::suppress(bounds.3)]] auto checkInstanceExtensionsNamesAvailable(\n\t\tconst std::vector<const char*>& required_extensions,\n\t\tconst std::vector<VkExtensionProperties>& available_extensions)\n\t\tconst -> bool;\n\n\t/**\n\tChecks and prints if all the required validation layers in the conficuration are available.\n\n\t@return true if all the required validation layers are within the available ones, false otherwise.\n\t*/\n\t[[gsl::suppress(bounds.3)]] auto checkValidationLayerSupport() const noexcept -> bool;\n\n\t/**\n\tCalculates and returns the necessary Vulkan extensions for this application based\n\ton configuration.\n\n\t@return A vector with the names of the required extensions\n\t*/\n\tauto getRequiredExtensions() const noexcept->std::vector<const char*>;\n\n\t/**\n\tCallback function called to receive messages from the validation layers when\n\tenabled (in debug mode).\n\n\tIt follows the parameters of the vulkan PFN_vkDebugReportCallbackEXT function\n\n\t@see PFN_vkDebugReportCallbackEXT\n\t@return VK_FALSE to indicate that the Vulkan call should NOT be aborted.\n\t*/\n#pragma warning( push )\n#pragma warning( disable : 4229)\n\tauto static VKAPI_ATTR VKAPI_CALL debugReportCallback(\n\t\tVkDebugReportFlagsEXT                       flags,\n\t\tVkDebugReportObjectTypeEXT                  object_type,\n\t\tuint64_t                                    object,\n\t\tsize_t                                      location,\n\t\tint32_t                                     msg_code,\n\t\tconst char*                                 layer_prefix,\n\t\tconst char*                                 msg,\n\t\tvoid*                                       user_data\n\t)->VkBool32;\n#pragma warning( pop )\n\n\t/**\n\tSets up the callback function to receive debug information from\n\tthe debug report validation layer.\n\n\t@see debugReportCallback\n\t@see m_debug_callback\n\t*/\n\tauto setupDebugCallback() -> void;\n\n\t/**\n\tCreates the window surface to which we will render to.\n\n\t@see m_surface\n\t*/\n\tauto createSurface() -> void;\n\n\t/**\n\tInterface to the vulkan function \"vkCreateDebugReportCallbackEXT\" to create\n\tthe debug function callback.\n\n\t@see vkCreateDebugReportCallbackEXT\n\t@return the result of vkCreateDebugReportCallbackEXT or VK_ERROR_EXTENSION_NOT_PRESENT if\n\twe can't find the function pointer.\n\t*/\n\tauto createDebugReportCallbackEXT(\n\t\tconst VkInstance& instance,\n\t\tconst VkDebugReportCallbackCreateInfoEXT * create_info,\n\t\tconst VkAllocationCallbacks* allocator,\n\t\tVkDebugReportCallbackEXT* callback\n\t) noexcept->VkResult;\n\n\n\t/**\n\tInterface to the vulkan function \"vkDestroyDebugReportCallbackEXT\" to destroy\n\tthe debug function callback.\n\n\t@see vkDestroyDebugReportCallbackEXT\n\t*/\n\tauto destroyDebugReportCallbackEXT(\n\t\tconst VkInstance& instance,\n\t\tconst VkDebugReportCallbackEXT& callback,\n\t\tconst VkAllocationCallbacks* allocator\n\t) noexcept -> void;\n\n\t/**\n\tIterates and picks the most suitable physical device\n\tavailable on the system for this application.\n\n\t@see m_physical_device\n\t@see m_physical_device_properties\n\t@see m_physical_device_features\n\t*/\n\tauto pickPhysicalDevice() -> void;\n\n\t/**\n\tChecks if the physical device is suitable for the application\n\tand gives it a score based on how suitable it is based on configuration.\n\n\t@param the physical device to rate\n\t@return a tuple with a bool representing that is true when the device is valid\n\tand an int representing the score, the higher the better.\n\t*/\n\tauto physicalDeviceSuitability(\n\t\tconst VkPhysicalDevice& device\n\t) const noexcept->std::tuple<bool, int>;\n\n\t/**\n\tChecks the queue families supported by the provided device and returns the indices for the\n\trequired ones in the struct QueueFamilyIndices (graphics and present queues right now).\n\n\t@see QueueFamilyIndices\n\t@see m_queue_family_indices\n\t@see PrintOptions\n\t@param The physical device to retrieve the queue families from\n\t@param The print options for the function to indicate the output desired to standard output\n\t@return The struct with the family queue indices required or -1 if they haven't been found\n\t*/\n\tauto findQueueFamilies(\n\t\tconst VkPhysicalDevice& physical_device,\n\t\tPrintOptions print_options\n\t) const->QueueFamilyIndices;\n\n\t/**\n\tCreates the vulkan logical device we are going to use and retrieves the graphics and present\n\tqueues from it.\n\n\t@see m_device\n\t@see m_graphics_queue\n\t@see m_present_queue\n\t*/\n\tauto createLogicalDevice() -> void;\n\n\t/**\n\tCreates the allocator used to reserve memory in vulkan\n\n\t@see m_vma_allocator\n\t*/\n\tauto createAllocator() noexcept ->void;\n\n\t/**\n\tChecks if the physical device provided supports all the extensions required by our configuration\n\n\t@param The physical device to check for extension support\n\t@return true if all the extensions are supported, false otherwise\n\t*/\n\t[[gsl::suppress(bounds.3)]]\n\tauto checkDeviceExtensionSupport(\n\t\tconst VkPhysicalDevice& device\n\t) const -> bool;\n\n\t/**\n\tChecks and retrieves information about the swap chain capabilities of a physical device.\n\tFills up said information in the SwapChainSupportDetails struct\n\n\t@see SwapChainSupportDetails\n\t@param The physical device to check for swap chain support\n\t@return A SwapChainSupportDetails filled with swap chain support information\n\t*/\n\tauto querySwapChainSupport(\n\t\tconst VkPhysicalDevice& device\n\t) const->SwapChainSupportDetails;\n\n\t/**\n\tChecks and returns the best available surface chain format from the provided ones\n\tprioritizing the ones that fit us best.\n\n\t@param A vector with the surface formats to check\n\t@return The best surface format for our application\n\t*/\n\tauto pickSurfaceChainFormat(\n\t\tconst std::vector<VkSurfaceFormatKHR>& available_formats\n\t) const->VkSurfaceFormatKHR;\n\n\t/**\n\tChecks and returns the best available present mode from the provided ones\n\tprioritizing the ones that fit us best.\n\n\t@param A vector with the present modes to check\n\t@return The best present mode for our application\n\t*/\n\tauto pickSurfacePresentMode(\n\t\tconst std::vector<VkPresentModeKHR>& available_modes\n\t)  const noexcept->VkPresentModeKHR;\n\n\t/**\n\tChecks and returns the best available extent for the images in the\n\tswap chain based on its capabilities.\n\n\t@param The capabilities of the surface\n\t@return The best possible extent (width, height) for our application\n\t*/\n\tauto pickSwapExtent(\n\t\tconst VkSurfaceCapabilitiesKHR& capabilities\n\t)  const noexcept->VkExtent2D;\n\n\t/**\n\tCreates the vulkan swap chain required for rendering.\n\tPrioritizes a triple buffering implementation if possible.\n\n\t@see m_swap_chain\n\t*/\n\tauto createSwapChain() -> void;\n\n\t/**\n\tCreates an image view for each image in the swap chain so\n\twe can use them as color targets later.\n\n\t@see m_swap_chain_image_views\n\t*/\n\tauto createSwapChainImageViews() -> void;\n\n\t/**\n\tCreates the render pass that will be used to then create\n\tthe graphics pipeline.\n\n\t@see m_render_pass\n\t*/\n\tauto createRenderPass() -> void;\n\n\t/**\n\tCreates the descriptor set layout that we will set in\n\tthe pipeline.\n\n\t@see m_descriptor_set_layout;\n\t*/\n\tauto createDescriptorSetLayout() -> void;\n\n\t/**\n\tCreates the graphics pipeline (or pipelines) that will be used to render\n\tour scene.\n\n\t@see m_pipeline_layout\n\t@see m_pipeline\n\t*/\n\tauto createGraphicsPipeline() -> void;\n\n\t/**\n\tCreates a shader module based on the code provided and wraps it up\n\tin the VkShaderModule struct\n\n\t@see VkShaderModule\n\t@param An array of characters with the code for the shader\n\t@return The shader module created based on the shader code\n\t*/\n\tauto createShaderModule(const std::vector<char>& code) const->VkShaderModule;\n\n\t/**\n\tCreates the framebuffersto draw to during render time\n\n\t@see m_swap_chain_framebuffers\n\t*/\n\tauto createFramebuffers() ->  void;\n\n\t/**\n\tCreates the command pool that contains the command buffers to\n\tdraw to during render time.\n\n\t@see m_graphics_command_pool\n\t*/\n\tauto createGraphicsCommandPool() ->  void;\n\n\t/**\n\tCreates the command pool that contains the command buffers to\n\texecute transfer memory commands.\n\n\t@see m_transfer_command_pool\n\t*/\n\tauto createTransferCommandPool() ->  void;\n\n\t/**\n\tHelper function that creates a vulkan image in a general way\n\n\t@param Width of the image\n\t@param Height of the image\n\t@param Vulkan Format of the image\n\t@param Tiling Options for the image\n\t@param Usage flags that the image will need\n\t@param Usage type for allocation\n\t@param Flags necessary for allocation\n\t@param The image to be populated\n\t@param The sharing mode for the image (Concurrent or exclusive)\n\t@param The family indices when sharing mode is concurrent (or nullptr otherwise)\n\t@param The sample count for the image, 1 sample by default (used on images meant for multisampling)\n\t*/\n\tauto createImage(\n\t\tuint width,\n\t\tuint height,\n\t\tVkFormat format,\n\t\tVkImageTiling tiling,\n\t\tVkImageUsageFlags flags,\n\t\tVmaMemoryUsage allocation_usage,\n\t\tVmaAllocationCreateFlags allocation_flags,\n\t\tAllocatedImage& image,\n\t\tVkSharingMode sharing_mode,\n\t\tconst std::vector<uint>* queue_family_indices,\n\t\tshort samples = 1\n\t) -> void;\n\n\t/**\n\tDestroys the image provided and frees its memory\n\n\t@param The image to destroy\n\t*/\n\tauto destroyImage(AllocatedImage& image) noexcept -> void;\n\n\t/**\n\tCreates the necessary resources for the implementation\n\tof a depth buffer\n\n\t@ m_depth_image\n\t@ m_depth_image_view\n\t*/\n\tauto createDepthResources() -> void;\n\n\t/**\n\tCreates a texture image with the data loaded from a file\n\n\t@param the path of th texture\n\t@return The allocated image with the texture\n\t*/\n\tauto createTextureImage(std::string path) -> AllocatedImage;\n\n\t/**\n\tCreates a texture image view into the texture image\n\n\t@param The image to create the view from\n\t@return An image view for the provided image.\n\t*/\n\tauto createTextureImageView(AllocatedImage image) -> VkImageView;\n\n\t/**\n\tLoads the scene with the provided object (.obj) and texture paths\n\n\t@param The path to the .obj model\n\t@param The path to the texture for the model\n\t@see m_scene\n\t*/\n\tauto loadScene(std::string object_path, std::string texture_path) -> void;\n\n\t/**\n\tCreates a sampler to sample the textures\n\tused in the rendering phase.\n\n\t@see m_texture_sampler\n\t*/\n\tauto createTextureSampler() -> void;\n\n\t/**\n\tHelper function that creates a vulkan buffer in a general way.\n\n\t@param The size of the memory to be allocated\n\t@param The usage flags necessary for the memory we are allocating\n\t@param The allocation usage that the buffer will have\n\t@param The flags for the allocator to use during creating of the buffer.\n\t@param The handle to the buffer to create\n\t@param The sharing mode of the buffer (VK_SHARING_MODE_(EXCLUSIVE/CONCURRENT))\n\t@param The family indices of the queues this buffer will be shared between if CONCURRENT, nullptr otherwise\n\t*/\n\tauto createBuffer(\n\t\tVkDeviceSize size,\n\t\tVkBufferUsageFlags usage,\n#ifdef VMA_USE_ALLOCATOR\n\t\tVmaMemoryUsage allocation_usage,\n\t\tVmaAllocationCreateFlags allocation_flags,\n#else\n\t\tVkMemoryPropertyFlags properties,\n#endif\n\t\tAllocatedBuffer& allocated_buffer,\n\t\tVkSharingMode sharing_mode,\n\t\tconst std::vector<uint>* queue_family_indices\n\t) -> void;\n\n\t/**\n\tDestroys the buffer provided and frees its memory\n\n\t@param The Buffer to destroy\n\t*/\n\tauto destroyBuffer(\n\t\tAllocatedBuffer& allocated_buffer\n\t) noexcept -> void;\n\n\t/**\n\tCreates the vertex buffer that will hold the vertices to render.\n\n\t@see m_vertex_buffer\n\t*/\n\tauto createVertexBuffer() -> void;\n\n\t/**\n\tCreates the index buffer that will hold the indexes in order to render.\n\n\t@see m_index_buffer\n\t*/\n\tauto createIndexBuffer() -> void;\n\n\t/**\n\tCreates the uniform buffer that will hold the object data to render.\n\n\t@see m_uniform_buffer\n\t*/\n\tauto createUniformBuffer() -> void;\n\n\t/**\n\tCreates the descriptor pool that will hold the descriptors sets that will\n\tbe used during rendering.\n\n\t@see m_descriptor_pool\n\t*/\n\tauto createDescriptorPool() -> void;\n\n\t/**\n\tCreates the descriptor set that will hold the descriptors\n\tused during rendering.\n\n\t@see m_descriptor_set\n\t*/\n\tauto createDescriptorSet() -> void;\n\n\t/**\n\tHelper function that finds the appropriate format for a depth attachment.\n\n\t@return Format that supports usage as a depth attachment\n\t*/\n\tauto findDepthFormat()->VkFormat;\n\n\t/**\n\tChecks if a given format has a stencil component in it.\n\n\t@param The format to check\n\t@return True if it has a stencil component, false otherwise\n\t*/\n\tauto hasStencilComponent(VkFormat format) const noexcept -> bool;\n\n\t/**\n\tHelper function that finds the post appropriate format for an image given\n\tthe desired features and candidates.\n\n\t@param The possible formats to choose from\n\t@param The tiling options of the image\n\t@param The features desired\n\t@return The most appropriate format\n\t*/\n\tauto findSupportedFormat(\n\t\tconst std::vector<VkFormat>& candidates,\n\t\tVkImageTiling tiling,\n\t\tVkFormatFeatureFlags features\n\t)->VkFormat;\n\n\t/**\n\tHelper function that calculates the required memory types given the input properties.\n\n\t@param Flags that indicate the types of memories that we can consider\n\t@param Properties of the memory we need\n\t@param A reference to a boolean that will indicate if we have found an appropriate type\n\t@return Appropriate flags of the memory we can use.\n\t*/\n\tauto findMemoryType(\n\t\tuint type_filter,\n\t\tVkMemoryPropertyFlags properties,\n\t\tVkBool32 *found = nullptr\n\t)->uint;\n\n\t/**\n\tCopies the contents from one VkBuffer to another.\n\n\t@param The source buffer\n\t@param The destination buffer\n\t@param The size of the memory to be copied\n\t*/\n\tauto copyBuffer(\n\t\tVkBuffer src,\n\t\tVkBuffer dst,\n\t\tVkDeviceSize size\n\t) noexcept -> void;\n\n\t/**\n\tCreates the command buffers that contain the commands to\n\tdraw to during render time.\n\n\t@see m_command_buffers\n\t*/\n\tauto createCommandBuffers() ->  void;\n\n\t/**\n\tCreates the drawing commands into the command buffers\n\n\t@see m_command_buffers\n\t*/\n\tauto recordCommandBuffers() -> void;\n\n\t/**\n\tCreates the semaphores and fences necessary for synchronization of\n\tthe rendering phase.\n\n\t@see m_image_available_semaphores\n\t@see m_render_finished_semaphores\n\t@see m_command_buffer_fences\n\t*/\n\tauto createSemaphoresAndFences() -> void;\n\n\n\t/**\n\tHandles the event of resizing the window to set up the appropriate\n\trendering parameters accordingly.\n\n\t@param Reference to the window that has been resized\n\t@param New width of the window\n\t@param New height of the window\n\t*/\n\tauto static onWindowsResized(\n\t\tGLFWwindow * window,\n\t\tint width,\n\t\tint heigth) -> void;\n\n\t/**\n\tCreates a single use command buffer and starts recording to it\n\n\t@param the type of commands that will be used (graphics also allows transfer)\n\t@return The command buffer we are recording to\n\t*/\n\tauto beginSingleTimeCommands(\n\t\tCommandType command_type = CommandType::graphics\n\t) noexcept->WrappedCommandBuffer;\n\n\t/**\n\tEnd recording to a particulaar command buffer and submits it to the queue\n\n\t@param The command buffer to submit to the queue\n\t*/\n\tauto endSingleTimeCommands(\n\t\tWrappedCommandBuffer& command_buffer\n\t) noexcept ->void;\n\n\t/**\n\tHelper function that changes the image layout to a new one\n\n\t@param The image to change the layout to\n\t@param The format of the image\n\t@param The old layout of the image\n\t@param The new layout for the image\n\t*/\n\tauto changeImageLayout(\n\t\tVkImage& image,\n\t\tVkFormat format,\n\t\tVkImageLayout old_layout,\n\t\tVkImageLayout new_layout)->void;\n\n\t/**\n\tHelper function that copies a buffer with image data into\n\ta vulkan image structure.\n\n\t@param The buffer to read the data from\n\t@param The image to write de data into\n\t@param Width of the image\n\t@param Height of the image\n\t*/\n\tauto copyBufferToImage(\n\t\tVkBuffer buffer,\n\t\tVkImage image,\n\t\tuint width,\n\t\tuint heigth) noexcept -> void;\n\n\t/**\n\tHelped function that creates an image view to the\n\tprovided image.\n\n\t@param The image to create a view from\n\t@param The format of the view\n\t@param The aspect mast to create the image view regarding its use\n\t@return An image view into the provided image\n\t*/\n\tauto createImageView(\n\t\tVkImage image,\n\t\tVkFormat format,\n\t\tVkImageAspectFlags aspect_flags\n\t)->VkImageView;\n\n\t/**\n\tHelper function that calculates the required flags to\n\tset up an especific amount of samples.\n\n\t@param The number of samples required (power of 2 up to 64)\n\t@return The required vulkan flag for the number of samples\n\t*/\n\tauto getSampleBits(short samples)->VkSampleCountFlagBits;\n\n\t/**\n\tCreates a render target for multisampling. This includes, the image,\n\tits memory and a view to it.\n\n\t@param Width of the render target\n\t@param Height of the render target\n\t@param Desired format of the render target\n\t@param The usage flags for the render target\n\t@param The aspect flags for the image view of the render target\n\t@return The render target struct with all the relevant info\n\t*/\n\tauto createMultisampleRenderTarget(\n\t\tuint width,\n\t\tuint height,\n\t\tVkFormat format,\n\t\tVkImageUsageFlags usage,\n\t\tVkImageAspectFlags aspect_mask)->WrappedRenderTarget;\n\n\n\t/* ---------------------------------------------------------------------------------------------- */\n\t/* ---------------------------------------- DATA MEMBERS ---------------------------------------- */\n\t/* ---------------------------------------------------------------------------------------------- */\n\n\tRenderConfiguration config{};\n\n#ifdef VMA_USE_ALLOCATOR\n\tVmaAllocator m_vma_allocator{};\n#endif\n\n\tWindowPtr m_window{};\n\n\tVkInstance m_instance{};\n\n\tVkDebugReportCallbackEXT m_debug_callback{};\n\n\tVkSurfaceKHR m_surface{};\n\n\tQueueFamilyIndices m_queue_family_indices{};\n\n\tVkPhysicalDevice m_physical_device = VK_NULL_HANDLE;\n\n\tVkPhysicalDeviceProperties m_physical_device_properties{};\n\n\tVkPhysicalDeviceFeatures m_physical_device_features{};\n\n\tVkDevice m_device{};\n\n\tVkQueue m_graphics_queue{};\n\n\tVkQueue m_present_queue{};\n\n\tVkQueue m_transfer_queue{};\n\n\tWrappedRenderTarget m_render_target{};\n\n\tWrappedRenderTarget m_depth_target{};\n\n\tVkFormat m_depth_format{};\n\n\tVkSwapchainKHR m_swap_chain{};\n\n\tuint m_current_swapchain_buffer{};\n\n\tstd::vector<VkImage> m_swap_chain_images{};\n\n\tVkFormat m_swap_chain_image_format{};\n\n\tVkExtent2D m_swap_chain_extent{};\n\n\tstd::vector<VkImageView> m_swap_chain_image_views{};\n\n\tVkRenderPass m_render_pass{};\n\n\tVkPipelineLayout m_pipeline_layout{};\n\n\tSimpleObjScene m_scene{};\n\n\tVkDescriptorSetLayout m_descriptor_set_layout{};\n\n\tVkPipeline m_pipeline{};\n\n\tstd::vector<VkFramebuffer> m_swap_chain_framebuffers{};\n\n\tVkCommandPool m_graphics_command_pool{};\n\n\tVkCommandPool m_transfer_command_pool{};\n\n\tAllocatedBuffer m_vertex_buffer{};\n\n\tAllocatedBuffer m_index_buffer{};\n\n\tAllocatedBuffer m_uniform_buffer{};\n\n\tAllocatedImage m_depth_image{};\n\n\tVkImageView m_depth_image_view{};\n\n\tVkSampler m_texture_sampler{};\n\n\tVkDescriptorPool m_descriptor_pool{};\n\n\tVkDescriptorSet m_descriptor_set{};\n\n\tstd::vector<VkCommandBuffer> m_command_buffers{};\n\n\tuint m_current_command_buffer{};\n\n\tstd::vector<bool> m_command_buffer_submitted{};\n\n\tstd::vector<VkSemaphore> m_image_available_semaphores{};\n\n\tstd::vector<VkSemaphore> m_render_finished_semaphores{};\n\n\tstd::vector<VkFence> m_command_buffer_fences{};\n\n};\n\n", "meta": {"hexsha": "ef4e68b0c8d03afce855feb2684c0defdb461364", "size": 23344, "ext": "h", "lang": "C", "max_stars_repo_path": "VR_ButNotReally/src/render/Renderer.h", "max_stars_repo_name": "Jazzzy/VR_ButNotReally", "max_stars_repo_head_hexsha": "82e0335ee86cc9cc32d784c4b1b55ab884ae0414", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "VR_ButNotReally/src/render/Renderer.h", "max_issues_repo_name": "Jazzzy/VR_ButNotReally", "max_issues_repo_head_hexsha": "82e0335ee86cc9cc32d784c4b1b55ab884ae0414", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "VR_ButNotReally/src/render/Renderer.h", "max_forks_repo_name": "Jazzzy/VR_ButNotReally", "max_forks_repo_head_hexsha": "82e0335ee86cc9cc32d784c4b1b55ab884ae0414", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.987283237, "max_line_length": 113, "alphanum_fraction": 0.7294379712, "num_tokens": 5145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07055959618729296, "lm_q2_score": 0.01691491503221905, "lm_q1q2_score": 0.0011935095742157476}}
{"text": "/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */\n#pragma once\n\n#include <mcbp/protocol/status.h>\n#include <stdint.h>\n#include <gsl/gsl>\n\nstruct EngineIface;\n\n/**\n * Callback for any function producing stats.\n *\n * @param key the stat's key\n * @param klen length of the key\n * @param val the stat's value in an ascii form (e.g. text form of a number)\n * @param vlen length of the value\n * @param cookie magic callback cookie\n */\ntypedef void (*ADD_STAT)(const char* key,\n                         const uint16_t klen,\n                         const char* val,\n                         const uint32_t vlen,\n                         gsl::not_null<const void*> cookie);\n\n/**\n * Callback for adding a response backet\n * @param key The key to put in the response\n * @param keylen The length of the key\n * @param ext The data to put in the extended field in the response\n * @param extlen The number of bytes in the ext field\n * @param body The data body\n * @param bodylen The number of bytes in the body\n * @param datatype This is currently not used and should be set to 0\n * @param status The status code of the return packet (see in protocol_binary\n *               for the legal values)\n * @param cas The cas to put in the return packet\n * @param cookie The cookie provided by the frontend\n * @return true if return message was successfully created, false if an\n *              error occured that prevented the message from being sent\n */\ntypedef bool (*ADD_RESPONSE)(const void* key,\n                             uint16_t keylen,\n                             const void* ext,\n                             uint8_t extlen,\n                             const void* body,\n                             uint32_t bodylen,\n                             uint8_t datatype,\n                             cb::mcbp::Status status,\n                             uint64_t cas,\n                             const void* cookie);\n", "meta": {"hexsha": "cf3629d2e3dd2b53a46304dc004e61130d5c3f90", "size": 1934, "ext": "h", "lang": "C", "max_stars_repo_path": "include/memcached/engine_common.h", "max_stars_repo_name": "t3rm1n4l/kv_engine", "max_stars_repo_head_hexsha": "24d4546220f3181678d7eadedc68b4ea088d3538", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/memcached/engine_common.h", "max_issues_repo_name": "t3rm1n4l/kv_engine", "max_issues_repo_head_hexsha": "24d4546220f3181678d7eadedc68b4ea088d3538", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/memcached/engine_common.h", "max_forks_repo_name": "t3rm1n4l/kv_engine", "max_forks_repo_head_hexsha": "24d4546220f3181678d7eadedc68b4ea088d3538", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9215686275, "max_line_length": 77, "alphanum_fraction": 0.5816959669, "num_tokens": 418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07263670636078698, "lm_q2_score": 0.01640303492031256, "lm_q1q2_score": 0.0011914624309324782}}
{"text": "#pragma once\n#include \"halley/support/logger.h\"\n#include \"halley/net/connection/network_message.h\"\n#include <gsl/gsl>\n\nnamespace Halley\n{\n\tclass Serializer;\n\tclass String;\n\tclass MessageQueue;\n\n\tnamespace DevCon\n\t{\n\t\tvoid setupMessageQueue(MessageQueue& queue);\n\n\t\t\n\t\tenum class MessageType\n\t\t{\n\t\t\tLog,\n\t\t\tReloadAssets\n\t\t};\n\n\n\t\tclass DevConMessage : public NetworkMessage\n\t\t{\n\t\tpublic:\n\t\t\tvirtual ~DevConMessage() = default;\n\t\t\tvirtual MessageType getMessageType() const = 0;\n\t\t};\n\n\t\tclass LogMsg : public DevConMessage\n\t\t{\n\t\tpublic:\n\t\t\tLogMsg(gsl::span<const gsl::byte> data);\n\t\t\tLogMsg(LoggerLevel level, const String& msg);\n\n\t\t\tvoid serialize(Serializer& s) const override;\n\n\t\t\tLoggerLevel getLevel() const;\n\t\t\tconst String& getMessage() const;\n\t\t\tMessageType getMessageType() const override;\n\n\t\tprivate:\n\t\t\tLoggerLevel level;\n\t\t\tString msg;\n\t\t};\n\n\t\tclass ReloadAssetsMsg : public DevConMessage\n\t\t{\n\t\tpublic:\n\t\t\tReloadAssetsMsg(gsl::span<const gsl::byte> data);\n\t\t\tReloadAssetsMsg(std::vector<String> ids);\n\n\t\t\tvoid serialize(Serializer& s) const override;\n\n\t\t\tstd::vector<String> getIds() const;\n\n\t\t\tMessageType getMessageType() const override;\n\n\t\tprivate:\n\t\t\tstd::vector<String> ids;\n\t\t};\n\t}\n}\n", "meta": {"hexsha": "5316df2566bc3bf86ac828c1e6e8f38d59abe27e", "size": 1199, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engine/core/include/halley/core/devcon/devcon_messages.h", "max_stars_repo_name": "sunhay/halley", "max_stars_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T20:23:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T20:23:45.000Z", "max_issues_repo_path": "src/engine/core/include/halley/core/devcon/devcon_messages.h", "max_issues_repo_name": "sunhay/halley", "max_issues_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engine/core/include/halley/core/devcon/devcon_messages.h", "max_forks_repo_name": "sunhay/halley", "max_forks_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.4461538462, "max_line_length": 52, "alphanum_fraction": 0.7064220183, "num_tokens": 305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06008665354025421, "lm_q2_score": 0.019719128971477644, "lm_q1q2_score": 0.0011848564706247666}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n *\r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n *\r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n *\r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef utilities_9904f6c1_3075_4335_b065_c7099f52e80b_h\r\n#define utilities_9904f6c1_3075_4335_b065_c7099f52e80b_h\r\n\r\n#include <ariel/type.h>\r\n#include <gslib/std.h>\r\n#include <gslib/string.h>\r\n#include <gslib/file.h>\r\n\r\n__ariel_begin__\r\n\r\n/*\r\n * Text format elements:\r\n *  [section] { ... }\r\n *  [section]:[notation] { ... }\r\n *\r\n * where sections could be nested\r\n */\r\n\r\nextern bool io_bad_eof(const string& src, int32 curr);\r\nextern int32 io_skip_blank_charactors(const string& src, int32 start);\r\nextern int32 io_read_section_name(const string& src, string& name, int32 start);\r\nextern int32 io_read_notation(const string& src, string& notation, int32 start);\r\nextern int32 io_skip_section(const string& src, int32 start);\r\nextern int32 io_enter_section(const string& src, int32 start, gchar st = _t('{'));\r\nextern int32 io_read_line_of_section(const string& src, string& line, int32 start);\r\n\r\n/*\r\n * Binary format elements:\r\n *  #[uint32][string]@[uint32]      section about length(in bytes)\r\n *  $[uint32][string]               notation string(ASCII only)\r\n */\r\n\r\nusing gs::file;\r\n\r\nclass __gs_novtable io_binary_stream abstract\r\n{\r\npublic:\r\n    typedef vector<int32> section_stack;\r\n\r\n    enum control_type\r\n    {\r\n        ctl_unknown,\r\n        ctl_section,\r\n        ctl_notation,\r\n        ctl_counter,\r\n        ctl_byte_stream_field,\r\n        ctl_word_stream_field,\r\n        ctl_dword_stream_field,\r\n        ctl_qword_stream_field,\r\n    };\r\n\r\npublic:\r\n    io_binary_stream(int32 size);\r\n    virtual ~io_binary_stream() {}\r\n    control_type read_control_type();\r\n    bool next_byte_valid() const { return next_n_bytes_valid(1); }\r\n    bool next_word_valid() const { return next_n_bytes_valid(2); }\r\n    bool next_dword_valid() const { return next_n_bytes_valid(4); }\r\n    bool next_qword_valid() const { return next_n_bytes_valid(8); }\r\n    bool next_n_bytes_valid(int32 bytes) const;\r\n    void seek_to(int32 bytes);\r\n    void seek_by(int32 bytes);\r\n    float read_float();\r\n    double read_double();\r\n    int32 read_nstring(string& str);\r\n    int32 read_string(string& str, const string& stopch);\r\n    void enter_section(int32 size) { _section_stack.push_back(size); }\r\n    bool exit_section();\r\n    bool skip_current_section();\r\n    bool skip_next_section();\r\n\r\nprotected:\r\n    int32                   _size;\r\n    int32                   _current;\r\n    section_stack           _section_stack;\r\n\r\npublic:\r\n    virtual byte read_byte() = 0;\r\n    virtual word read_word() = 0;\r\n    virtual dword read_dword() = 0;\r\n    virtual qword read_qword() = 0;\r\n    virtual bool read_field_to_buf(void* ptr, int32 bytes) = 0;\r\n    virtual void rewind_to(int32 bytes) = 0;\r\n    virtual int32 current_dev_pos() const = 0;\r\n\r\nprotected:\r\n    void rewind_by(int32 bytes);\r\n    void take_next_n_bytes(int32 n);\r\n    bool section_stack_valid(int32 bytes) const;\r\n};\r\n\r\nclass io_binary_memory:\r\n    public io_binary_stream\r\n{\r\npublic:\r\n    io_binary_memory(const void* ptr, int32 size);\r\n    virtual byte read_byte() override;\r\n    virtual word read_word() override;\r\n    virtual dword read_dword() override;\r\n    virtual qword read_qword() override;\r\n    virtual bool read_field_to_buf(void* ptr, int32 bytes) override;\r\n    virtual void rewind_to(int32 bytes) override {}\r\n    virtual int32 current_dev_pos() const override { return _current; }\r\n\r\nprotected:\r\n    const byte*             _mem;\r\n};\r\n\r\nclass io_binary_file:\r\n    public io_binary_stream\r\n{\r\npublic:\r\n    io_binary_file(file& pf);\r\n    virtual byte read_byte() override;\r\n    virtual word read_word() override;\r\n    virtual dword read_dword() override;\r\n    virtual qword read_qword() override;\r\n    virtual bool read_field_to_buf(void* ptr, int32 bytes) override;\r\n    virtual void rewind_to(int32 bytes) override { _file.seek(bytes, SEEK_SET); }\r\n    virtual int32 current_dev_pos() const override { return _file.current(); }\r\n\r\nprotected:\r\n    file&                   _file;\r\n};\r\n\r\n__ariel_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "a38a3cfe0ddf5f38e5c4dd8c5432652ee00c9b36", "size": 5227, "ext": "h", "lang": "C", "max_stars_repo_path": "include/ariel/io/utilities.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/ariel/io/utilities.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ariel/io/utilities.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 33.5064102564, "max_line_length": 84, "alphanum_fraction": 0.6946623302, "num_tokens": 1224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.03461883734516869, "lm_q2_score": 0.03410042595771566, "lm_q1q2_score": 0.0011805170996311268}}
{"text": "#ifndef S3D_VIDEO_FILE_PARSER_FFMPEG_SEEKER_H\n#define S3D_VIDEO_FILE_PARSER_FFMPEG_SEEKER_H\n\n#include <chrono>\n\n#include <gsl/gsl>\n\nstruct AVFormatContext;\n\nnamespace s3d {\n\nclass Seeker {\n public:\n  Seeker(gsl::not_null<AVFormatContext*> formatContext, int streamIndex);\n\n  void seekTo(std::chrono::microseconds timestamp);\n\n private:\n  AVFormatContext* formatContext_;\n  int streamIndex_;\n};\n\n}  // namespace s3d\n\n#endif  // S3D_VIDEO_FILE_PARSER_FFMPEG_SEEKER_H\n", "meta": {"hexsha": "96826a11d548a66cbe606a0776def2f9d8d0f711", "size": 465, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/ffmpeg/include/s3d/video/file_parser/ffmpeg/seeker.h", "max_stars_repo_name": "hugbed/OpenS3D", "max_stars_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-16T16:38:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-20T03:23:15.000Z", "max_issues_repo_path": "src/core/ffmpeg/include/s3d/video/file_parser/ffmpeg/seeker.h", "max_issues_repo_name": "hugbed/OpenS3D", "max_issues_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 40.0, "max_issues_repo_issues_event_min_datetime": "2017-04-12T17:24:44.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-21T18:41:23.000Z", "max_forks_repo_path": "src/core/ffmpeg/include/s3d/video/file_parser/ffmpeg/seeker.h", "max_forks_repo_name": "hugbed/OpenS3D", "max_forks_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-07-13T21:51:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-18T16:22:03.000Z", "avg_line_length": 17.8846153846, "max_line_length": 73, "alphanum_fraction": 0.7870967742, "num_tokens": 130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.03514485044314308, "lm_q2_score": 0.03308597934211907, "lm_q1q2_score": 0.0011628017957436964}}
{"text": "#ifndef S3D_VIDEO_STEREO_DEMUXER_STEREO_DEMUXER_H\n#define S3D_VIDEO_STEREO_DEMUXER_STEREO_DEMUXER_H\n\n#include \"s3d/utilities/rule_of_five.h\"\n\n#include \"s3d/video/capture/video_capture_types.h\"\n#include \"s3d/video/video_types.h\"\n\n#include <gsl/gsl>\n\n#include <cstdint>\n#include <vector>\n\nnamespace s3d {\n\nclass StereoDemuxer : public rule_of_five_interface<StereoDemuxer> {\n public:\n  using InputImageData = gsl::span<const uint8_t>;\n  using OutputImageData = std::vector<uint8_t>;\n  virtual void demux(const InputImageData& image,\n                     OutputImageData* leftImage,\n                     OutputImageData* rightImage) = 0;\n  virtual Size demuxedSize() const = 0;\n  virtual Stereo3DFormat getStereoFormat() const = 0;\n  virtual void setSize(Size size) = 0;\n  virtual void setPixelFormat(VideoPixelFormat format) = 0;\n};\n}  // namespace s3d\n\n#endif  // S3D_VIDEO_STEREO_DEMUXER_STEREO_DEMUXER_H\n", "meta": {"hexsha": "dfbda76153bf5fb814c1cb8586f064848b2f6cef", "size": 905, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/s3d/include/s3d/video/stereo_demuxer/stereo_demuxer.h", "max_stars_repo_name": "hugbed/OpenS3D", "max_stars_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-16T16:38:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-20T03:23:15.000Z", "max_issues_repo_path": "src/core/s3d/include/s3d/video/stereo_demuxer/stereo_demuxer.h", "max_issues_repo_name": "hugbed/OpenS3D", "max_issues_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 40.0, "max_issues_repo_issues_event_min_datetime": "2017-04-12T17:24:44.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-21T18:41:23.000Z", "max_forks_repo_path": "src/core/s3d/include/s3d/video/stereo_demuxer/stereo_demuxer.h", "max_forks_repo_name": "hugbed/OpenS3D", "max_forks_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-07-13T21:51:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-18T16:22:03.000Z", "avg_line_length": 29.1935483871, "max_line_length": 68, "alphanum_fraction": 0.7502762431, "num_tokens": 253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.041462267973656895, "lm_q2_score": 0.028007521011643926, "lm_q1q2_score": 0.0011612553414626066}}
{"text": "#pragma once\n#include \"iparam.h\"\n#include \"iparamlist.h\"\n#include \"iflag.h\"\n#include \"iarg.h\"\n#include \"iarglist.h\"\n#include \"icommand.h\"\n#include \"optioninfo.h\"\n#include \"format.h\"\n#include <sfun/string_utils.h>\n#include <cmdlime/usageinfoformat.h>\n#include <gsl/gsl>\n#include <utility>\n#include <vector>\n#include <memory>\n#include <algorithm>\n#include <iomanip>\n\nnamespace cmdlime::detail{\nusing namespace gsl;\nnamespace str = sfun::string_utils;\n\ninline std::string adjustedToLineBreak(std::string line, std::string& text)\n{\n    if (!text.empty() && !isspace(text.front())){\n        auto trimmedLine = str::trimFront(line);\n        if (std::find_if(trimmedLine.begin(), trimmedLine.end(), [](auto ch){return std::isspace(ch);}) == trimmedLine.end())\n            return line;\n        while(!isspace(line.back())){\n            text.insert(text.begin(), 1, line.back());\n            line.pop_back();\n        }\n    }\n    return line;\n}\n\ninline std::string popLine(std::string& text, std::size_t width, bool firstLine = false)\n{\n    auto newLinePos = text.find('\\n');\n    if (newLinePos != std::string::npos && newLinePos <= width){\n        auto line = text.substr(0, newLinePos);\n        text.erase(text.begin(), text.begin() + static_cast<int>(newLinePos + 1));\n        if (!firstLine)\n            line = str::trimFront(line);\n        return line;\n    }\n\n    auto line = text.substr(0, width);\n    if (text.size() < width)\n        text.clear();\n    else\n        text.erase(text.begin(), text.begin() + static_cast<int>(width));\n    if (!firstLine)\n        line = str::trimFront(line);\n    return adjustedToLineBreak(line, text);\n}\n\ntemplate <typename T>\ninline std::vector<not_null<T*>> getParamsByOptionality(const std::vector<not_null<T*>>& params, bool isOptional)\n{\n    auto result = std::vector<not_null<T*>>{};\n    std::copy_if(params.begin(), params.end(), std::back_inserter(result),\n                 [isOptional](auto param){return param->isOptional() == isOptional;});\n    return result;\n}\n\ntemplate <typename T>\nconst std::string& getName(T& option)\n{\n    return option.info().name();\n}\n\ntemplate <typename T>\nconst std::string& getType(T& option)\n{\n    return option.info().type();\n}\n\ntemplate <typename T>\nconst std::string& getDescription(T& option)\n{\n    return option.info().description();\n}\n\ntemplate <FormatType formatType>\nclass UsageInfoCreator{\npublic:\n    UsageInfoCreator(std::string programName,\n                     UsageInfoFormat outputSettings,\n                     const std::vector<not_null<IParam*>>& params,\n                     const std::vector<not_null<IParamList*>>& paramLists,\n                     std::vector<not_null<IFlag*>> flags,\n                     std::vector<not_null<IArg*>> args,\n                     IArgList* argList,\n                     std::vector<not_null<ICommand*>> commands)\n    : programName_(std::move(programName))\n    , params_(getParamsByOptionality(params, false))\n    , optionalParams_(getParamsByOptionality(params, true))\n    , paramLists_(getParamsByOptionality(paramLists, false))\n    , optionalParamLists_(getParamsByOptionality(paramLists, true))\n    , flags_(std::move(flags))\n    , args_(std::move(args))\n    , argList_(argList)\n    , commands_(std::move(commands))\n    , outputSettings_(outputSettings)\n    , maxOptionNameSize_(maxOptionNameLength() + outputSettings.columnsSpacing)\n    {\n    }\n\n    std::string createDetailed()\n    {\n        return minimizedUsageInfo() +\n               argsInfo() +\n               paramsInfo() +               \n               paramListsInfo() +\n               optionsInfo() +\n               optionalParamListsInfo() +\n               flagsInfo() +\n               commandsInfo();\n    }\n\n    std::string create()\n    {\n        return usageInfo();\n    }\n\nprivate:\n    using OutputFormatter = typename Format<formatType>::outputFormatter;\n\n    std::string usageInfo()\n    {\n        auto result = \"Usage: \" + programName_ + \" \";\n        if (!commands_.empty())\n            result += \"[commands] \";\n\n        for (auto arg : args_)\n            result += OutputFormatter::argUsageName(*arg) + \" \";\n\n        for (auto param : params_)\n            result += OutputFormatter::paramUsageName(*param) + \" \";\n        for (auto paramList : paramLists_)\n            result += OutputFormatter::paramListUsageName(*paramList) + \" \";\n        for (auto param : optionalParams_)\n           result += OutputFormatter::paramUsageName(*param) + \" \";\n        for (auto paramList : optionalParamLists_)\n           result += OutputFormatter::paramListUsageName(*paramList) + \" \";\n\n        for (auto flag : flags_)\n            result += OutputFormatter::flagUsageName(*flag) + \" \";\n\n        if (argList_)\n            result += OutputFormatter::argListUsageName(*argList_);\n\n        result += \"\\n\";\n        return result;\n    }\n\n    std::string minimizedUsageInfo()\n    {\n        auto result = \"Usage: \" + programName_ + \" \";\n\n        if (!commands_.empty())\n            result += \"[commands] \";\n\n        for (auto arg : args_)\n            result += OutputFormatter::argUsageName(*arg) + \" \";\n\n        for (auto param : params_)\n            result += OutputFormatter::paramUsageName(*param) + \" \";\n\n        for (auto paramList : paramLists_)\n            result += OutputFormatter::paramListUsageName(*paramList) + \" \";\n\n        if (!optionalParams_.empty() || !optionalParamLists_.empty())\n            result += \"[params] \";\n\n        if (!flags_.empty())\n            result += \"[flags] \";\n\n        if (argList_)\n            result += OutputFormatter::argListUsageName(*argList_);\n\n        result += \"\\n\";\n        return result;\n    }\n\n    std::string paramsInfo()\n    {\n        auto result = std::string{\"Parameters:\\n\"};\n        if (params_.empty())\n            return result;\n        for (const auto& param : params_){\n            const auto name = OutputFormatter::paramDescriptionName(*param, outputSettings_.nameIndentation) + \"\\n\";\n            result += makeConfigFieldInfo(name, getDescription(*param));\n        }\n        return result;\n    }\n\n    std::string paramListsInfo()\n    {\n        auto result = std::string{};\n        if (paramLists_.empty())\n            return result;\n        for (const auto paramList : paramLists_){\n            const auto name = OutputFormatter::paramListDescriptionName(*paramList, outputSettings_.nameIndentation) + \"\\n\";\n            auto description = getDescription(*paramList);\n            if (!description.empty())\n                description += \"\\n(multi-value)\";\n            else\n                description += \"multi-value\";\n            result += makeConfigFieldInfo(name, description);\n        }\n        return result;\n    }\n\n    std::string optionsInfo()\n    {\n        if (optionalParams_.empty())\n            return {};\n        auto result = std::string{};\n        for (const auto option : optionalParams_){\n            auto description = getDescription(*option);\n            if (!description.empty()){\n                if (!option->defaultValue().empty())\n                    description += \"\\n(optional, default: \" + option->defaultValue() + \")\";\n                else\n                    description += \"\\n(optional)\";\n            }\n            else{\n                if (!option->defaultValue().empty())\n                    description += \"optional, default: \" + option->defaultValue();\n                else\n                    description += \"optional\";\n            }\n            result += makeConfigFieldInfo(OutputFormatter::paramDescriptionName(*option, outputSettings_.nameIndentation) + \"\\n\", description);\n        }\n        return result;\n    }\n\n    std::string optionalParamListsInfo()\n    {\n        if (optionalParamLists_.empty())\n            return {};\n        auto result = std::string{};\n        for (const auto option : optionalParamLists_){\n            auto description = getDescription(*option);\n            if (!description.empty()){\n                description += \"\\n(multi-value, \";\n                if (!option->defaultValue().empty())\n                    description += \"optional, default: \" + option->defaultValue() + \")\";\n                else\n                    description += \"optional)\";\n            }\n            else{\n                description += \"multi-value, \";\n                if (!option->defaultValue().empty())\n                    description += \"optional, default: \" + option->defaultValue();\n                else\n                    description += \"optional\";\n            }\n            result += makeConfigFieldInfo(OutputFormatter::paramListDescriptionName(*option, outputSettings_.nameIndentation) + \"\\n\", description);\n        }\n        return result;\n    }\n\n    std::string argsInfo()\n    {\n        if (args_.empty() && !argList_)\n            return {};\n        auto result = std::string{\"Arguments:\\n\"};\n        for (const auto arg : args_)\n            result += makeConfigFieldInfo(OutputFormatter::argDescriptionName(*arg, outputSettings_.nameIndentation) + \"\\n\", getDescription(*arg));\n\n        if (argList_){            \n            auto description = getDescription(*argList_);\n            if (!description.empty()){\n                description += \"\\n(multi-value\";\n                if (argList_->isOptional()){\n                    if (!argList_->defaultValue().empty())\n                        description += \", optional, default: \" + argList_->defaultValue() + \")\";\n                    else\n                        description +=  \", optional)\";\n                }\n                else\n                    description += \")\";\n            }\n            else{\n                description += \"multi-value\";\n                if (argList_->isOptional()){\n                    if (!argList_->defaultValue().empty())\n                        description += \", optional, default: \" + argList_->defaultValue();\n                    else\n                        description +=  \", optional\";\n                }\n            }\n            result += makeConfigFieldInfo(OutputFormatter::argListDescriptionName(*argList_, outputSettings_.nameIndentation) + \"\\n\", description);\n        }\n        return result;\n    }\n\n    std::string flagsInfo()\n    {\n        if (flags_.empty())\n            return {};\n        auto result = std::string{\"Flags:\\n\"};\n        for (const auto flag : flags_)\n            result += makeConfigFieldInfo(OutputFormatter::flagDescriptionName(*flag, outputSettings_.nameIndentation) + \"\\n\", getDescription(*flag));\n        return result;\n    }\n\n    std::string commandsInfo()\n    {\n        if (commands_.empty())\n            return {};\n        auto result = std::string{\"Commands:\\n\"};\n        for (const auto command : commands_){\n            auto nameStream = std::stringstream{};\n            if (outputSettings_.nameIndentation)\n                nameStream << std::setw(outputSettings_.nameIndentation) << \" \";\n            nameStream << getName(*command)\n                       << \" [options]\";\n            result += makeConfigFieldInfo(nameStream.str(), getDescription(*command));\n        }\n        return result;\n    }\n\n    int maxOptionNameLength()\n    {        \n        auto length = 0;\n        auto updateLength = [&length](std::string name)\n        {\n            auto firstLine = true;\n            do {\n               auto nameLine = popLine(name, 100, firstLine);\n               length = std::max(length, static_cast<int>(nameLine.size()));\n               firstLine = false;\n            } while(!name.empty());\n        };\n\n        for (auto param : params_)\n            updateLength(OutputFormatter::paramDescriptionName(*param, outputSettings_.nameIndentation));\n        for (auto option : optionalParams_)\n            updateLength(OutputFormatter::paramDescriptionName(*option, outputSettings_.nameIndentation));\n        for (auto flag : flags_)\n            updateLength(OutputFormatter::flagDescriptionName(*flag, outputSettings_.nameIndentation));\n        for (auto arg : args_)\n            updateLength(OutputFormatter::argDescriptionName(*arg, outputSettings_.nameIndentation));\n        if (argList_)\n            updateLength(OutputFormatter::argListDescriptionName(*argList_, outputSettings_.nameIndentation));\n        return length;\n    }\n\n    std::string makeConfigFieldInfo(std::string name, std::string description)\n    {\n        auto maxNameWidth = std::min(outputSettings_.maxNameColumnWidth, maxOptionNameSize_);\n        const auto columnSeparatorWidth = 1;\n        const auto leftColumnWidth = columnSeparatorWidth + maxNameWidth;\n        const auto rightColumnWidth = static_cast<std::size_t>(outputSettings_.terminalWidth - leftColumnWidth);\n        const auto descriptionWidth = rightColumnWidth - 2;\n        auto stream = std::stringstream{};\n        auto firstLine = true;\n        while (!name.empty()){\n            auto nameLine = popLine(name, static_cast<std::size_t>(maxNameWidth), firstLine);\n            const auto descriptionLine = popLine(description, descriptionWidth, firstLine);\n            if (firstLine)\n                stream << std::setw(maxNameWidth) << std::left << nameLine << \" \" << descriptionLine << std::endl;\n            else\n                stream << std::setw(maxNameWidth) << std::left << nameLine << \"   \" << descriptionLine << std::endl;\n            firstLine = false;\n        }\n        while(!description.empty()){\n            auto descriptionLine = popLine(description, descriptionWidth);\n            stream << std::setw(leftColumnWidth) << \" \" << \"  \" << descriptionLine << std::endl;\n        }\n        return stream.str();\n    }\n\nprivate:    \n    std::string programName_;    \n    std::vector<not_null<IParam*>> params_;\n    std::vector<not_null<IParam*>> optionalParams_;\n    std::vector<not_null<IParamList*>> paramLists_;\n    std::vector<not_null<IParamList*>> optionalParamLists_;\n    std::vector<not_null<IFlag*>> flags_;\n    std::vector<not_null<IArg*>> args_;\n    IArgList* argList_;\n    std::vector<not_null<ICommand*>> commands_;\n    UsageInfoFormat outputSettings_;\n    int maxOptionNameSize_;\n};\n\n}\n", "meta": {"hexsha": "d9c6b6d0a0ef1923fa425eda5cbc14f36cffcb2f", "size": 13953, "ext": "h", "lang": "C", "max_stars_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/usageinfocreator.h", "max_stars_repo_name": "GerHobbelt/hypertextcpp", "max_stars_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_stars_repo_licenses": ["MS-PL"], "max_stars_count": 77.0, "max_stars_repo_stars_event_min_datetime": "2021-05-20T18:05:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T21:37:54.000Z", "max_issues_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/usageinfocreator.h", "max_issues_repo_name": "GerHobbelt/hypertextcpp", "max_issues_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_issues_repo_licenses": ["MS-PL"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2021-05-20T22:04:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-21T08:13:28.000Z", "max_forks_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/usageinfocreator.h", "max_forks_repo_name": "GerHobbelt/hypertextcpp", "max_forks_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_forks_repo_licenses": ["MS-PL"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-22T00:36:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-22T00:36:08.000Z", "avg_line_length": 35.5038167939, "max_line_length": 150, "alphanum_fraction": 0.5743567692, "num_tokens": 2969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06954173679230911, "lm_q2_score": 0.016657040680434793, "lm_q1q2_score": 0.001158359538737582}}
{"text": "//------------------------------------------------------------------------------\n// Util.h\n// Various utility functions and basic types used throughout the library.\n//\n// File is under the MIT license; see LICENSE for details.\n//------------------------------------------------------------------------------\n#pragma once\n\n#include <climits>     // for type size macros\n#include <cstddef>     // for std::byte\n#include <cstdint>     // for sized integer types\n#include <new>         // for placement new\n#include <optional>    // for std::optional\n#include <string_view> // for std::string_view\n#include <utility>     // for many random utility functions\n#include <variant>     // for std::variant\n\nusing std::byte;\nusing std::int16_t;\nusing std::int32_t;\nusing std::int64_t;\nusing std::int8_t;\nusing std::intptr_t;\nusing std::nullptr_t;\nusing std::optional;\nusing std::ptrdiff_t;\nusing std::size_t;\nusing std::string_view;\nusing std::uint16_t;\nusing std::uint32_t;\nusing std::uint64_t;\nusing std::uint8_t;\nusing std::uintptr_t;\n\nusing namespace std::literals;\n\n#if !defined(ASSERT_ENABLED)\n#    if !defined(NDEBUG)\n#        define ASSERT_ENABLED 1\n#    endif\n#endif\n\n#if ASSERT_ENABLED\n#    if defined(__GNUC__) || defined(__clang__)\n#        define ASSERT_FUNCTION __PRETTY_FUNCTION__\n#    elif defined(_MSC_VER)\n#        define ASSERT_FUNCTION __FUNCSIG__\n#    elif defined(__SUNPRO_CC)\n#        define ASSERT_FUNCTION __func__\n#    else\n#        define ASSERT_FUNCTION __FUNCTION__\n#    endif\n#    define ASSERT(cond)                                                                 \\\n        do {                                                                             \\\n            if (!(cond))                                                                 \\\n                slang::assert::assertFailed(#cond, __FILE__, __LINE__, ASSERT_FUNCTION); \\\n        } while (false)\n\n#else\n#    define ASSERT(cond)        \\\n        do {                    \\\n            (void)sizeof(cond); \\\n        } while (false)\n#endif\n\n#define THROW_UNREACHABLE                                                                  \\\n    throw std::logic_error(std::string(__FILE__) + \":\" + std::to_string(__LINE__) + \": \" + \\\n                           \"Default case should be unreachable!\")\n\n#define __ENUM_ELEMENT(x) x,\n#define __ENUM_STRING(x) #x,\n#define ENUM(name, elements)                                          \\\n    enum class name { elements(__ENUM_ELEMENT) };                     \\\n    inline string_view toString(name e) {                             \\\n        static const char* strings[] = { elements(__ENUM_STRING) };   \\\n        return strings[static_cast<std::underlying_type_t<name>>(e)]; \\\n    }                                                                 \\\n    inline std::ostream& operator<<(std::ostream& os, name e) { return os << toString(e); }\n\n#define ENUM_MEMBER(name, elements)                                   \\\n    enum name { elements(__ENUM_ELEMENT) };                           \\\n    friend string_view toString(name e) {                             \\\n        static const char* strings[] = { elements(__ENUM_STRING) };   \\\n        return strings[static_cast<std::underlying_type_t<name>>(e)]; \\\n    }\n\n#include <gsl/gsl>\n\nusing gsl::finally;\nusing gsl::make_span;\nusing gsl::not_null;\nusing gsl::span;\n\n// Compiler-specific macros for warnings and suppressions\n#ifdef __clang__\n#    define NO_SANITIZE(warningName) __attribute__((no_sanitize(warningName)))\n#else\n#    define NO_SANITIZE(warningName)\n#endif\n\n#include <bitmask.hpp>\nusing bitmask_lib::bitmask;\n\n#include <nlohmann/json_fwd.hpp>\nusing json = nlohmann::json;\n\n#define HAS_METHOD_TRAIT(name)                                                               \\\n    template<typename, typename T>                                                           \\\n    struct has_##name {                                                                      \\\n        static_assert(always_false<T>::value,                                                \\\n                      \"Second template parameter needs to be of function type.\");            \\\n    };                                                                                       \\\n    template<typename C, typename Ret, typename... Args>                                     \\\n    struct has_##name<C, Ret(Args...)> {                                                     \\\n    private:                                                                                 \\\n        template<typename T>                                                                 \\\n        static constexpr auto check(T*) ->                                                   \\\n            typename std::is_same<decltype(std::declval<T>().name(std::declval<Args>()...)), \\\n                                  Ret>::type;                                                \\\n        template<typename>                                                                   \\\n        static constexpr std::false_type check(...);                                         \\\n        typedef decltype(check<C>(0)) type;                                                  \\\n                                                                                             \\\n    public:                                                                                  \\\n        static constexpr bool value = type::value;                                           \\\n    };                                                                                       \\\n    template<typename C, typename Ret, typename... Args>                                     \\\n    static constexpr bool has_##name##_v = has_##name<C, Ret(Args...)>::value\n\nnamespace slang {\n\ntemplate<typename T>\nstruct always_false : std::false_type {};\n\n/// Converts a span of characters into a string_view.\ninline string_view to_string_view(span<char> text) {\n    return string_view(text.data(), (size_t)text.size());\n}\n\ninline void hash_combine(size_t&) {\n}\n\n/// Hash combining function, based on the function from Boost.\ntemplate<typename T, typename... Rest>\ninline void hash_combine(size_t& seed, const T& v, Rest... rest) {\n    std::hash<T> hasher;\n    seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n    hash_combine(seed, rest...);\n}\n\nnamespace assert {\n\nclass AssertionException : public std::logic_error {\npublic:\n    AssertionException(const std::string& message) : std::logic_error(message) {}\n};\n\n[[noreturn]] void assertFailed(const char* expr, const char* file, int line, const char* func);\n\n} // namespace assert\n\n} // namespace slang\n\nnamespace detail {\n\ntemplate<typename Tuple, size_t Index = std::tuple_size<Tuple>::value - 1>\nstruct HashValueImpl {\n    static void apply(size_t& seed, const Tuple& tuple) {\n        HashValueImpl<Tuple, Index - 1>::apply(seed, tuple);\n        slang::hash_combine(seed, std::get<Index>(tuple));\n    }\n};\n\ntemplate<typename Tuple>\nstruct HashValueImpl<Tuple, 0> {\n    static void apply(size_t& seed, const Tuple& tuple) {\n        slang::hash_combine(seed, std::get<0>(tuple));\n    }\n};\n\n} // namespace detail\n\nnamespace std {\n\ntemplate<typename... TT>\nstruct hash<std::tuple<TT...>> {\n    size_t operator()(const std::tuple<TT...>& tt) const {\n        size_t seed = 0;\n        ::detail::HashValueImpl<std::tuple<TT...>>::apply(seed, tt);\n        return seed;\n    }\n};\n\n} // namespace std\n", "meta": {"hexsha": "896aa8e9164c79cb4389ae7233f07211760f45a7", "size": 7404, "ext": "h", "lang": "C", "max_stars_repo_path": "include/slang/util/Util.h", "max_stars_repo_name": "jrrk/slang", "max_stars_repo_head_hexsha": "e65f5f68029fadd5986ba453f415f00d6259d9c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/slang/util/Util.h", "max_issues_repo_name": "jrrk/slang", "max_issues_repo_head_hexsha": "e65f5f68029fadd5986ba453f415f00d6259d9c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/slang/util/Util.h", "max_forks_repo_name": "jrrk/slang", "max_forks_repo_head_hexsha": "e65f5f68029fadd5986ba453f415f00d6259d9c5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9692307692, "max_line_length": 95, "alphanum_fraction": 0.4890599676, "num_tokens": 1398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.0715911935020382, "lm_q2_score": 0.016152833460494596, "lm_q1q2_score": 0.0011564006258764658}}
{"text": "\n#pragma once\n\n#include <gsl/gsl>\n\n#include <memory>\n#include <atlcomcli.h>\n\n#include \"textures.h\"\n\nstruct ID3D11Texture2D;\nstruct ID3D11DeviceContext;\nstruct ID3D11RenderTargetView;\nstruct ID3D11ShaderResourceView;\nstruct ID3D11DepthStencilView;\n\nnamespace gfx {\n\n\tenum class BufferFormat;\n\n\tclass DynamicTexture : public Texture {\n\t\tfriend class RenderingDevice;\n\tpublic:\n\t\tDynamicTexture(ID3D11DeviceContext *context,\n\t\t\tID3D11Texture2D *texture,\n\t\t\tID3D11ShaderResourceView *resourceView,\n\t\t\tconst Size &size,\n\t\t\tuint32_t bytesPerPixel);\n\n\t\tint GetId() const override;\n\n\t\tconst std::string& GetName() const;\n\n\t\tconst ContentRect& GetContentRect() const override {\n\t\t\treturn mContentRect;\n\t\t}\n\n\t\tconst Size& GetSize() const override {\n\t\t\treturn mSize;\n\t\t}\n\n\t\tTextureType GetType() const override {\n\t\t\treturn TextureType::Dynamic;\n\t\t}\n\n\t\t// Unloads the device texture (does't prevent it from being loaded again later)\n\t\tvoid FreeDeviceTexture() override;\n\n\t\tID3D11ShaderResourceView* GetResourceView() override {\n\t\t\treturn mResourceView;\n\t\t}\n\n\t\tuint32_t GetBytesPerPixel() const {\n\t\t\treturn mBytesPerPixel;\n\t\t}\n\n\t\ttemplate<typename T>\n\t\tvoid Update(gsl::span<T> data) {\n\t\t\tUpdateRaw(\n\t\t\t\tgsl::span(reinterpret_cast<uint8_t*>(&data[0]), data.size_bytes()), \n\t\t\t\tmSize.width * sizeof(T)\n\t\t\t);\n\t\t}\n\n\tprivate:\n\n\t\tvoid UpdateRaw(gsl::span<uint8_t> data, size_t pitch);\n\n\t\tCComPtr<ID3D11DeviceContext> mContext;\n\t\tCComPtr<ID3D11Texture2D> mTexture;\n\t\tCComPtr<ID3D11ShaderResourceView> mResourceView;\n\t\tSize mSize;\n\t\tsize_t mBytesPerPixel;\n\t\tContentRect mContentRect;\n\n\t};\n\n\tusing DynamicTexturePtr = std::shared_ptr<DynamicTexture>;\n\n\tclass RenderTargetTexture : public Texture {\n\tfriend class RenderingDevice;\n\tpublic:\n\n\t\tRenderTargetTexture(ID3D11Texture2D *texture,\n\t\t\tID3D11RenderTargetView *rtView,\n\t\t\tID3D11Texture2D *resolvedTexture,\n\t\t\tID3D11ShaderResourceView *resourceView,\n\t\t\tconst Size &size,\n\t\t\tbool multiSampled);\n\n\t\tint GetId() const override;\n\n\t\tconst std::string& GetName() const;\n\n\t\tconst ContentRect& GetContentRect() const override {\n\t\t\treturn mContentRect;\n\t\t}\n\n\t\tconst Size& GetSize() const override {\n\t\t\treturn mSize;\n\t\t}\n\n\t\tTextureType GetType() const override {\n\t\t\treturn TextureType::RenderTarget;\n\t\t}\n\n\t\t// Unloads the device texture (does't prevent it from being loaded again later)\n\t\tvoid FreeDeviceTexture() override;\n\n\t\t/**\n\t\t * Only valid for MSAA targets. Will return the texture used to resolve the multisampling\n\t\t * so it can be used as a shader resource.\n\t\t */\n\t\tID3D11Texture2D* GetResolvedTexture() const {\n\t\t\treturn mResolvedTexture;\n\t\t}\n\n\t\t/**\n\t\t * For MSAA targets, this will return the resolvedTexture, while for normal targets,\n\t\t * this will just be the texture itself.\n\t\t */\n\t\tID3D11ShaderResourceView* GetResourceView() override {\n\t\t\treturn mResourceView;\n\t\t}\n\t\t\n\t\tbool IsMultiSampled() const {\n\t\t\treturn mMultiSampled;\n\t\t}\n\n\t\tgfx::BufferFormat GetFormat() const;\n\n\tprivate:\n\t\tCComPtr<ID3D11RenderTargetView> mRtView;\n\t\tCComPtr<ID3D11Texture2D> mTexture;\n\t\tCComPtr<ID3D11Texture2D> mResolvedTexture;\n\t\tCComPtr<ID3D11ShaderResourceView> mResourceView;\n\t\tSize mSize;\n\t\tContentRect mContentRect;\n\t\tbool mMultiSampled;\n\n\t};\n\n\tusing RenderTargetTexturePtr = std::shared_ptr<RenderTargetTexture>;\n\n\tclass RenderTargetDepthStencil {\n\t\tfriend class RenderingDevice;\n\tpublic:\n\n\t\tRenderTargetDepthStencil(ID3D11Texture2D *textureNew,\n\t\t\tID3D11DepthStencilView *dsView,\n\t\t\tconst Size &size);\n\n\t\tconst Size& GetSize() const {\n\t\t\treturn mSize;\n\t\t}\n\n\tprivate:\n\n\t\tCComPtr<ID3D11DepthStencilView> mDsView;\n\t\tCComPtr<ID3D11Texture2D> mTextureNew;\n\t\tSize mSize;\n\n\t};\n\n\tusing RenderTargetDepthStencilPtr = std::shared_ptr<RenderTargetDepthStencil>;\n\n}\n", "meta": {"hexsha": "663755e52fb07f240867ccb699dfe29af15b9722", "size": 3676, "ext": "h", "lang": "C", "max_stars_repo_path": "Infrastructure/include/graphics/dynamictexture.h", "max_stars_repo_name": "edoipi/TemplePlus", "max_stars_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 69.0, "max_stars_repo_stars_event_min_datetime": "2015-05-05T14:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T06:13:04.000Z", "max_issues_repo_path": "Infrastructure/include/graphics/dynamictexture.h", "max_issues_repo_name": "edoipi/TemplePlus", "max_issues_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 457.0, "max_issues_repo_issues_event_min_datetime": "2015-05-01T22:07:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T02:19:10.000Z", "max_forks_repo_path": "Infrastructure/include/graphics/dynamictexture.h", "max_forks_repo_name": "edoipi/TemplePlus", "max_forks_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2016-02-04T21:19:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T23:14:51.000Z", "avg_line_length": 21.880952381, "max_line_length": 91, "alphanum_fraction": 0.7451033732, "num_tokens": 993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07807816514495095, "lm_q2_score": 0.01472861144404275, "lm_q1q2_score": 0.0011499829566837842}}
{"text": "#ifndef cloptions_h\n#define cloptions_h\n\n#include <petsc.h>\n#include \"../include/structs.h\"\n\n// Process general command line options\nPetscErrorCode ProcessCommandLineOptions(MPI_Comm comm, AppCtx app_ctx);\n\n#endif // cloptions_h\n", "meta": {"hexsha": "a905593c2f184a2b7c49afcd0d81a466519d5eda", "size": 229, "ext": "h", "lang": "C", "max_stars_repo_path": "examples/solids/include/cl-options.h", "max_stars_repo_name": "AdelekeBankole/libCEED", "max_stars_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 123.0, "max_stars_repo_stars_event_min_datetime": "2018-01-29T02:04:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T18:13:48.000Z", "max_issues_repo_path": "examples/solids/include/cl-options.h", "max_issues_repo_name": "AdelekeBankole/libCEED", "max_issues_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 781.0, "max_issues_repo_issues_event_min_datetime": "2017-12-22T17:20:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T21:34:34.000Z", "max_forks_repo_path": "examples/solids/include/cl-options.h", "max_forks_repo_name": "AdelekeBankole/libCEED", "max_forks_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2017-12-27T22:35:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:02:07.000Z", "avg_line_length": 20.8181818182, "max_line_length": 72, "alphanum_fraction": 0.7903930131, "num_tokens": 52, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.042722197546490565, "lm_q2_score": 0.026759280954016137, "lm_q1q2_score": 0.00114321528711952}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef typeof_027722a0_eb51_4e04_8f59_b9299ee17be6_h\r\n#define typeof_027722a0_eb51_4e04_8f59_b9299ee17be6_h\r\n\r\n#include <gslib/type.h>\r\n\r\n__gslib_begin__\r\n\r\n#define gs_register_typeof_bs(t) \\\r\n    template<> \\\r\n    struct typeof<t*> { typedef t type; }; \\\r\n    template<> \\\r\n    struct typeof<const t*> { typedef t type; };\r\n\r\n#define gs_register_typeof(q, t) \\\r\n    q t; /* for announcement. */ \\\r\n    gs_register_typeof_bs(t);\r\n\r\n#define gs_register_typeof_ns(ns, q, t) \\\r\n    namespace ns { \\\r\n        q t; /* for announcement. */ \\\r\n    }; \\\r\n    gs_register_typeof_bs(ns::t);\r\n\r\n/* all pointer typeof operator should be registered here. */\r\ngs_register_typeof_bs(int8);\r\ngs_register_typeof_bs(int16);\r\ngs_register_typeof_bs(int);\r\ngs_register_typeof_bs(int64);\r\ngs_register_typeof_bs(wchar);\r\ngs_register_typeof_bs(real32);\r\ngs_register_typeof_bs(real);\r\ngs_register_typeof_bs(byte);\r\ngs_register_typeof_bs(word);\r\ngs_register_typeof_bs(dword);\r\ngs_register_typeof_bs(qword);\r\ngs_register_typeof_ns(rathen, struct, ps_data);\r\ngs_register_typeof_ns(rathen, struct, ps_ref);\r\ngs_register_typeof_ns(rathen, struct, ps_stdata);\r\ngs_register_typeof_ns(rathen, struct, ps_stref);\r\ngs_register_typeof_ns(ariel, class, button);\r\n/* more to come ... */\r\n\r\n__gslib_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "02894a0454a9a38ed9e1206b803ae81167f2c513", "size": 2542, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gslib/typeof.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/gslib/typeof.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gslib/typeof.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 34.8219178082, "max_line_length": 82, "alphanum_fraction": 0.7356412274, "num_tokens": 606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.045352584425245944, "lm_q2_score": 0.025178838820344163, "lm_q1q2_score": 0.0011419254133293187}}
{"text": "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\n#pragma once\n\n#include <gsl/gsl>\n\n#include \"core/optimizer/graph_transformer.h\"\n#include \"core/optimizer/rule_based_graph_transformer.h\"\n#include \"core/optimizer/rewrite_rule.h\"\n\nnamespace onnxruntime {\nstruct FreeDimensionOverride;\n\nnamespace transformer_utils {\n\n/** Generates all predefined rules for this level.\n   If rules_to_enable is not empty, it returns the intersection of predefined rules and rules_to_enable.\n   TODO: This is visible for testing at the moment, but we should rather make it private. */\nstd::vector<std::unique_ptr<RewriteRule>> GenerateRewriteRules(TransformerLevel level,\n                                                               const std::vector<std::string>& rules_to_enable = {});\n\n/** Generates all predefined (both rule-based and non-rule-based) transformers for this level.\n    If transformers_and_rules_to_enable is not empty, it returns the intersection between the predefined transformers/rules \n\tand the transformers_and_rules_to_enable. */\nstd::vector<std::unique_ptr<GraphTransformer>> GenerateTransformers(TransformerLevel level,\n                                                                    gsl::span<const FreeDimensionOverride> free_dimension_overrides,\n                                                                    const std::vector<std::string>& rules_and_transformers_to_enable = {});\n\n/** Given a TransformerLevel, this method generates a name for the rule-based graph transformer of that level. */\nstd::string GenerateRuleBasedTransformerName(TransformerLevel level);\n\n}  // namespace transformer_utils\n}  // namespace onnxruntime\n", "meta": {"hexsha": "d9a0fb369b48ed148e6bc6eac2c3e95ba9b7175f", "size": 1696, "ext": "h", "lang": "C", "max_stars_repo_path": "include/onnxruntime/core/optimizer/graph_transformer_utils.h", "max_stars_repo_name": "csteegz/onnxruntime", "max_stars_repo_head_hexsha": "a36810471b346ec862ac6e4de7f877653f49525e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-07-12T15:23:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-12T15:23:49.000Z", "max_issues_repo_path": "include/onnxruntime/core/optimizer/graph_transformer_utils.h", "max_issues_repo_name": "ajinkya933/onnxruntime", "max_issues_repo_head_hexsha": "0e799a03f2a99da6a1b87a2cd37facb420c482aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/onnxruntime/core/optimizer/graph_transformer_utils.h", "max_forks_repo_name": "ajinkya933/onnxruntime", "max_forks_repo_head_hexsha": "0e799a03f2a99da6a1b87a2cd37facb420c482aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-09T06:55:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-09T06:55:51.000Z", "avg_line_length": 48.4571428571, "max_line_length": 139, "alphanum_fraction": 0.7063679245, "num_tokens": 310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.05500528984257014, "lm_q2_score": 0.020645932998943486, "lm_q1q2_score": 0.0011356355286771698}}
{"text": "#pragma once\n\n#include \"Cesium3DTilesReader/Library.h\"\n\n#include <Cesium3DTiles/Tileset.h>\n#include <CesiumJsonReader/ExtensionReaderContext.h>\n\n#include <gsl/span>\n\n#include <functional>\n#include <memory>\n#include <optional>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\nnamespace Cesium3DTilesReader {\n\n/**\n * @brief The result of reading a tileset with\n * {@link TilesetReader::readTileset}.\n */\nstruct CESIUM3DTILESREADER_API TilesetReaderResult {\n  /**\n   * @brief The read tileset, or std::nullopt if the tileset could not be read.\n   */\n  std::optional<Cesium3DTiles::Tileset> tileset;\n\n  /**\n   * @brief Errors, if any, that occurred during the load process.\n   */\n  std::vector<std::string> errors;\n\n  /**\n   * @brief Warnings, if any, that occurred during the load process.\n   */\n  std::vector<std::string> warnings;\n};\n\n/**\n * @brief Options for how to read a tileset.\n */\nstruct CESIUM3DTILESREADER_API ReadTilesetOptions {};\n\n/**\n * @brief Reads tilesets.\n */\nclass CESIUM3DTILESREADER_API TilesetReader {\npublic:\n  /**\n   * @brief Constructs a new instance.\n   */\n  TilesetReader();\n\n  /**\n   * @brief Gets the context used to control how extensions are loaded from a\n   * tileset.\n   */\n  CesiumJsonReader::ExtensionReaderContext& getExtensions();\n\n  /**\n   * @brief Gets the context used to control how extensions are loaded from a\n   * tileset.\n   */\n  const CesiumJsonReader::ExtensionReaderContext& getExtensions() const;\n\n  /**\n   * @brief Reads a tileset.\n   *\n   * @param data The buffer from which to read the tileset.\n   * @param options Options for how to read the tileset.\n   * @return The result of reading the tileset.\n   */\n  TilesetReaderResult readTileset(\n      const gsl::span<const std::byte>& data,\n      const ReadTilesetOptions& options = ReadTilesetOptions()) const;\n\nprivate:\n  CesiumJsonReader::ExtensionReaderContext _context;\n};\n\n} // namespace Cesium3DTilesReader\n", "meta": {"hexsha": "967fb3b36ddc2f900c3361f4396b2ce781bc4daa", "size": 1923, "ext": "h", "lang": "C", "max_stars_repo_path": "Cesium3DTilesReader/include/Cesium3DTilesReader/TilesetReader.h", "max_stars_repo_name": "137734949/cesium-native", "max_stars_repo_head_hexsha": "7fbccc0ff302f3645dc5829c3a2f3a5bdba83922", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Cesium3DTilesReader/include/Cesium3DTilesReader/TilesetReader.h", "max_issues_repo_name": "137734949/cesium-native", "max_issues_repo_head_hexsha": "7fbccc0ff302f3645dc5829c3a2f3a5bdba83922", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cesium3DTilesReader/include/Cesium3DTilesReader/TilesetReader.h", "max_forks_repo_name": "137734949/cesium-native", "max_forks_repo_head_hexsha": "7fbccc0ff302f3645dc5829c3a2f3a5bdba83922", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1686746988, "max_line_length": 79, "alphanum_fraction": 0.7077483099, "num_tokens": 494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.05500529294080225, "lm_q2_score": 0.020645929760004338, "lm_q1q2_score": 0.0011356354144842658}}
{"text": "#ifndef PARALLEL_PROCESSING_H_2FVRLMCH\n#define PARALLEL_PROCESSING_H_2FVRLMCH\n\n#include <chrono>\n#include <gsl/gsl>\n#include <iomanip>\n#include <ios>\n#include <iostream>\n#include <sens_loc/util/console.h>\n#include <sens_loc/util/progress_bar_observer.h>\n#include <taskflow/taskflow.hpp>\n#include <type_traits>\n\nnamespace sens_loc::apps {\n\n/// Helper function that processes a range of files based on index.\n/// The boolean function \\c f is applied to each function. Error handling\n/// and reporting is done if \\c f returns \\c false.\n///\n/// \\tparam BoolFunction Apply this functor for each index.\n/// \\param start,end inclusive range of integers for the files\n/// \\param f functor that is applied for each index\ntemplate <typename BoolFunction>\nbool parallel_indexed_file_processing(int          start,\n                                      int          end,\n                                      BoolFunction f) noexcept {\n    static_assert(std::is_nothrow_invocable_r_v<bool, BoolFunction, int>,\n                  \"Functor needs to be noexcept callable and return bool!\");\n\n    try {\n        if (start > end)\n            std::swap(start, end);\n\n        int total_tasks = end - start + 1;\n\n        tf::Executor executor;\n        executor.make_observer<util::progress_bar_observer>(total_tasks);\n        tf::Taskflow tf;\n\n        bool batch_success = true;\n        int  fails         = 0;\n\n        tf.parallel_for(\n            start, end + 1, 1, [&batch_success, &fails, &f](int idx) {\n                const bool success = f(idx);\n                if (!success) {\n                    auto s = synced();\n                    fails++;\n                    std::cerr << util::err{};\n                    std::cerr << \"Could not process index \\\"\"\n                              << rang::style::bold << idx << \"\\\"\"\n                              << rang::style::reset << \"!\" << std::endl;\n                    batch_success = false;\n                }\n            });\n\n        const auto before = std::chrono::steady_clock::now();\n        executor.run(tf).wait();\n        const auto after = std::chrono::steady_clock::now();\n        const auto dur_deci_seconds =\n            std::chrono::duration_cast<std::chrono::duration<long, std::centi>>(\n                after - before);\n        std::cout << std::endl;\n\n        Ensures(fails >= 0);\n\n        using namespace std::chrono;\n        {\n            auto s = synced();\n            std::cerr << util::info{};\n            std::cerr << \"Processing \" << rang::style::bold\n                      << std::abs(end - start) + 1 - fails << rang::style::reset\n                      << \" images took \" << rang::style::bold << std::fixed\n                      << std::setprecision(2)\n                      << (dur_deci_seconds.count() / 100.) << rang::style::reset\n                      << \" seconds!\\n\";\n        }\n\n        if (fails > 0) {\n            auto s = synced();\n            std::cerr << util::warn{} << \"Encountered \" << rang::style::bold\n                      << fails << rang::style::reset << \" problematic files!\\n\";\n        }\n\n        return batch_success;\n    } catch (...) {\n        auto s = synced();\n        std::cerr << util::err{} << \"System error in batch processing!\\n\";\n        return false;\n    }\n}\n\n}  // namespace sens_loc::apps\n\n#endif /* end of include guard: PARALLEL_PROCESSING_H_2FVRLMCH */\n", "meta": {"hexsha": "9d1a7f542a87b07250ad71359b9b0d5bacacfabc", "size": 3345, "ext": "h", "lang": "C", "max_stars_repo_path": "src/apps/util/parallel_processing.h", "max_stars_repo_name": "JonasToth/depth-conversions", "max_stars_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-09-30T07:09:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T09:14:35.000Z", "max_issues_repo_path": "src/apps/util/parallel_processing.h", "max_issues_repo_name": "JonasToth/depth-conversions", "max_issues_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/apps/util/parallel_processing.h", "max_forks_repo_name": "JonasToth/depth-conversions", "max_forks_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.84375, "max_line_length": 80, "alphanum_fraction": 0.530941704, "num_tokens": 743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.03410042276746191, "lm_q2_score": 0.033085979938003426, "lm_q1q2_score": 0.00112824590356168}}
{"text": "#ifndef ADD_TO_TASK_INCLUDE\n#define ADD_TO_TASK_INCLUDE\n\n#include <functional>\n#include <initializer_list>\n#include <optional>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include <gsl/pointers>\n\n#include \"base-utils/nonEmptyString.h\"\n#include \"core/task.h\"\n\nnamespace execHelper::test {\nusing AddToTaskFunction = std::function<core::TaskCollection(std::string)>;\n\ninline void addToTask(const std::string& value, gsl::not_null<core::Task*> task,\n                      AddToTaskFunction func) {\n    task->append(func(value));\n}\n\ninline void addToTask(const NonEmptyString& value,\n                      gsl::not_null<core::Task*> task, AddToTaskFunction func) {\n    task->append(func(*value));\n}\n\ninline void addToTask(bool value, gsl::not_null<core::Task*> task,\n                      AddToTaskFunction func) {\n    if(value) {\n        task->append(func(\"true\"));\n    } else {\n        task->append(func(\"false\"));\n    }\n}\n\ninline void addToTask(const std::vector<std::string>& value,\n                      gsl::not_null<core::Task*> task, AddToTaskFunction func) {\n    std::for_each(\n        value.begin(), value.end(),\n        [&task, func](const auto& element) { task->append(func(element)); });\n}\n\ninline void addToTask(const std::pair<std::string, std::string>& value,\n                      gsl::not_null<core::Task*> task, AddToTaskFunction func) {\n    task->append(func(value.first + \"=\" + value.second));\n}\n\ntemplate <typename T>\ninline void addToTask(const std::optional<T>& value,\n                      gsl::not_null<core::Task*> task, AddToTaskFunction func) {\n    if(value) {\n        addToTask(*value, task, func);\n    }\n}\n\ntemplate <typename T>\ninline void addToTask(const std::optional<T>& value,\n                      gsl::not_null<core::Task*> task, AddToTaskFunction func,\n                      const T& defaultValue) {\n    if(value) {\n        addToTask(*value, task, func);\n    } else {\n        addToTask(defaultValue, task, func);\n    }\n}\n} // namespace execHelper::test\n\n#endif /* ADD_TO_TASK_INCLUDE */\n", "meta": {"hexsha": "222a8f05577857ab182afdd43aa8c51672010c77", "size": 2033, "ext": "h", "lang": "C", "max_stars_repo_path": "test/utils/include/utils/addToTask.h", "max_stars_repo_name": "exec-helper/source", "max_stars_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-28T13:24:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-28T13:24:30.000Z", "max_issues_repo_path": "test/utils/include/utils/addToTask.h", "max_issues_repo_name": "exec-helper/source", "max_issues_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/utils/include/utils/addToTask.h", "max_forks_repo_name": "exec-helper/source", "max_forks_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-07-03T11:11:19.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-03T11:11:19.000Z", "avg_line_length": 28.6338028169, "max_line_length": 80, "alphanum_fraction": 0.6286276439, "num_tokens": 476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.0446808702726502, "lm_q2_score": 0.025178841334854832, "lm_q1q2_score": 0.0011250125432982912}}
{"text": "/* vector/gsl_check_range.h\r\n * \r\n * Copyright (C) 2003, 2004, 2007 Brian Gough\r\n * \r\n * This program is free software; you can redistribute it and/or modify\r\n * it under the terms of the GNU General Public License as published by\r\n * the Free Software Foundation; either version 3 of the License, or (at\r\n * your option) any later version.\r\n * \r\n * This program is distributed in the hope that it will be useful, but\r\n * WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n * General Public License for more details.\r\n * \r\n * You should have received a copy of the GNU General Public License\r\n * along with this program; if not, write to the Free Software\r\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r\n */\r\n\r\n#ifndef __GSL_CHECK_RANGE_H__\r\n#define __GSL_CHECK_RANGE_H__\r\n\r\n#if !defined( GSL_FUN )\r\n#  if !defined( GSL_DLL )\r\n#    define GSL_FUN extern\r\n#  elif defined( BUILD_GSL_DLL )\r\n#    define GSL_FUN extern __declspec(dllexport)\r\n#  else\r\n#    define GSL_FUN extern __declspec(dllimport)\r\n#  endif\r\n#endif\r\n\r\n#include <stdlib.h>\r\n#include <gsl/gsl_types.h>\r\n\r\n#undef __BEGIN_DECLS\r\n#undef __END_DECLS\r\n#ifdef __cplusplus\r\n# define __BEGIN_DECLS extern \"C\" {\r\n# define __END_DECLS }\r\n#else\r\n# define __BEGIN_DECLS /* empty */\r\n# define __END_DECLS /* empty */\r\n#endif\r\n\r\n__BEGIN_DECLS\r\n\r\nGSL_VAR int gsl_check_range;\r\n\r\n/* Turn range checking on by default, unless the user defines\r\n   GSL_RANGE_CHECK_OFF, or defines GSL_RANGE_CHECK to 0 explicitly */\r\n\r\n#ifdef GSL_RANGE_CHECK_OFF\r\n# ifndef GSL_RANGE_CHECK\r\n#  define GSL_RANGE_CHECK 0\r\n# else\r\n#  error \"cannot set both GSL_RANGE_CHECK and GSL_RANGE_CHECK_OFF\"\r\n# endif\r\n#else\r\n# ifndef GSL_RANGE_CHECK\r\n#  define GSL_RANGE_CHECK 1\r\n# endif\r\n#endif\r\n\r\n__END_DECLS\r\n\r\n#endif /* __GSL_CHECK_RANGE_H__ */\r\n", "meta": {"hexsha": "5b0a521fa3a00cbdf349aee26979a4e334299afc", "size": 1879, "ext": "h", "lang": "C", "max_stars_repo_path": "deps/include/gsl/gsl_check_range.h", "max_stars_repo_name": "berkus/music-cs", "max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z", "max_issues_repo_path": "deps/include/gsl/gsl_check_range.h", "max_issues_repo_name": "berkus/music-cs", "max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z", "max_forks_repo_path": "deps/include/gsl/gsl_check_range.h", "max_forks_repo_name": "berkus/music-cs", "max_forks_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 27.6323529412, "max_line_length": 82, "alphanum_fraction": 0.7264502395, "num_tokens": 463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.05500528829345414, "lm_q2_score": 0.020332351784377613, "lm_q1q2_score": 0.0011183868715836174}}
{"text": "#pragma once\n#include \"utility/types.h\"\n#include <gsl/gsl>\n#include <memory>\n\nstruct nk_context;\nstruct nk_user_font;\nstruct nk_buffer;\n\n///\nnamespace cws80 {\n\nclass GraphicsDevice;\nstruct FontRequest;\n\n//\nclass NkScreen {\npublic:\n    NkScreen();\n    ~NkScreen();\n\n    void init(GraphicsDevice &gdev, uint w, uint h, gsl::span<const FontRequest> fontreqs);\n    void clear();\n    bool should_render() const;\n    void render(void *draw_context);\n    void update();\n    nk_context *context() const;\n    nk_user_font *font(uint id) const;\n\n    uint width() const;\n    uint height() const;\n\nprivate:\n    struct Impl;\n    std::unique_ptr<Impl> P;\n};\n\n}  // namespace cws80\n", "meta": {"hexsha": "81d0424dbb6533333a4fd8b7d297602a57579fa6", "size": 667, "ext": "h", "lang": "C", "max_stars_repo_path": "sources/ui/cws80_ui_nk.h", "max_stars_repo_name": "jpcima/cws80", "max_stars_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-05-20T19:27:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-03T04:21:53.000Z", "max_issues_repo_path": "sources/ui/cws80_ui_nk.h", "max_issues_repo_name": "jpcima/cws80", "max_issues_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-05-21T12:56:22.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-23T21:33:33.000Z", "max_forks_repo_path": "sources/ui/cws80_ui_nk.h", "max_forks_repo_name": "jpcima/cws80", "max_forks_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.1025641026, "max_line_length": 91, "alphanum_fraction": 0.676161919, "num_tokens": 171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06097517915856705, "lm_q2_score": 0.01826427918682006, "lm_q1q2_score": 0.0011136676956184405}}
{"text": "#pragma once\n\n#include <type_traits>\n#include <gsl/gsl>\n\n#include \"sly/macros.h\"\n#include \"sly/types.h\"\n\ntemplate <class T>\nstruct is_unique_ptr : std::false_type\n{};\n\ntemplate <class T, class D>\nstruct is_unique_ptr<std::unique_ptr<T, D>> : std::true_type\n{};\n\ntemplate <class T>\nstruct unique_ptr_type\n{};\n\ntemplate <class T, class D>\nstruct unique_ptr_type<std::unique_ptr<T, D>>\n{    \n    using type = std::unique_ptr<T, D>;\n    using underlying_type = T;\n    using delete_type = D;\n};\n\ntemplate <class T>\nstruct is_shared_ptr : std::false_type\n{};\n\ntemplate <class T>\nstruct is_shared_ptr<std::shared_ptr<T>> : std::true_type\n{};\n\ntemplate <typename T>\nstruct is_indexable  : std::false_type\n{ };\n\ntemplate <typename T, typename A>\nstruct is_indexable<std::vector<T, A>> : std::true_type\n{ };\n\ntemplate <typename T, std::size_t N>\nstruct is_indexable<std::array<T, N>> : std::true_type\n{ };\n\n\nnamespace sly {\n    typedef s32 StatusCode;\n    typedef const char* ErrorMessage;\n\n\n    static const StatusCode SUCCESS = (StatusCode)0;\n    static const StatusCode UNKNOWN = (StatusCode)-1;\n\n    template <typename T, typename = typename std::is_reference<T>::type>\n    struct retval { };\n\n    template <typename T>\n    struct retval<T, std::false_type> { \n    public:\n    \n        using type = T;\n        using type_pointer = typename std::remove_reference<T>::type*;\n        using type_reference = typename std::remove_reference<T>::type&;\n    \n        //using unique_ptr = typename is_unique_ptr<T>::value;\n\n        retval(T value) : \n            _value(std::move(value)), \n            _statusCode(SUCCESS) {}\n        \n        retval(StatusCode code) : _statusCode(code) {}\n\n        //retval(const retval&) = delete;\n        retval& operator =(const retval&) = delete;\n        ~retval() = default;\n\n        template <class V, typename Y = T, typename std::enable_if_t<is_unique_ptr<Y>::value || is_shared_ptr<Y>::value>* = nullptr>\n        V to() const {\n            return reinterpret_cast<V>(_value.get());\n        }\n\n        template <class V, typename Y = T, typename std::enable_if_t<!is_unique_ptr<Y>::value && !is_shared_ptr<Y>::value>* = nullptr>\n        V to() const {            \n            return reinterpret_cast<V>(_value);\n        }\n\n        template<typename V>\n        operator V() const {\n            return to<V>();\n        }\n\n        type result() { return _value; }         \n        type_reference ref() { return _value; }  \n        \n        template <typename Y = T, typename std::enable_if_t<is_unique_ptr<Y>::value || is_shared_ptr<Y>::value>* = nullptr>  \n        operator type_reference() const { \n            return *_value.get(); \n        }  \n\n        template <typename Y = T, typename std::enable_if_t<is_unique_ptr<Y>::value || is_shared_ptr<Y>::value>* = nullptr>  \n        operator typename unique_ptr_type<Y>::underlying_type&() { \n            return *_value.get(); \n        }  \n\n        template <typename Y = T, typename std::enable_if_t<!is_unique_ptr<Y>::value && !is_shared_ptr<Y>::value>* = nullptr>      \n        operator type() { return result(); }   \n\n        template <typename Y = T, typename std::enable_if_t<std::is_pointer<Y>::value || is_unique_ptr<Y>::value || is_shared_ptr<Y>::value>* = nullptr>\n        type_reference operator->() { return _value; }\n\n        template <typename Y = T, typename std::enable_if_t<!std::is_pointer<Y>::value && !is_unique_ptr<Y>::value && !is_shared_ptr<Y>::value>* = nullptr>\n        type_pointer operator->() { return &_value; }\n\n        //template <typename N, typename Y = T, typename std::enable_if_t<std::is_pointer<Y>::value || is_unique_ptr<Y>::value || is_shared_ptr<Y>::value || is_indexable<Y>::value>* = nullptr>\n        template<typename N>\n        auto operator[](const N index) { return _value[index]; }\n\n        StatusCode statusCode() const { return _statusCode; }\n\n        bool_t succeeded() { return statusCode() == SUCCESS; }\n        bool_t failed() { return statusCode() != SUCCESS; }\n\n        template<typename X>\n        X as() {\n            return (X)result;\n        }\n\n    private:\n        StatusCode _statusCode;\n        T _value;\n    };\n\n    template <typename T>\n    struct retval<T, std::true_type> { \n    public:\n        \n        using type = T;\n        using type_pointer = typename std::remove_reference<T>::type*;\n\n        retval(T value) : \n            _value(std::addressof(value)), \n            _statusCode(SUCCESS) {}\n        \n        retval(StatusCode code) : _statusCode(code), _value(nullptr) {}\n\n        retval(const retval&) = delete;\n        retval& operator =(const retval&) = delete;\n        ~retval() = default;\n\n        T result() { return *_value; }        \n        operator T() { return result(); }\n        type_pointer operator->() { return _value; }\n           \n        StatusCode statusCode() const { return _statusCode; }\n\n        bool_t succeeded() { return statusCode() == SUCCESS; }\n        bool_t failed() { return statusCode() != SUCCESS; }\n\n        template<typename X>\n        X as() {\n            return (X)result();\n        }\n\n    private:\n        StatusCode _statusCode;\n        type_pointer _value;\n    };\n\n\n    template <>\n    struct retval<void, std::false_type> {\n    public:   \n        retval() : _statusCode(SUCCESS) {}\n        retval(StatusCode code) : _statusCode(code) {}\n\n        retval(const retval&) = delete;\n        retval& operator =(const retval&) = delete;\n        ~retval() = default;\n\n        void value() const { }        \n        \n        StatusCode statusCode() const { return _statusCode; }\n\n        bool_t succeeded() { return statusCode() == SUCCESS; }\n        bool_t failed() { return statusCode() != SUCCESS; }\n\n        template<typename X>\n        X as() {\n            return (X)result;\n        }\n\n\n    private:\n        StatusCode _statusCode;\n    };\n\n    template <typename T>\n    retval<T> value(const T& value) {\n        auto result = retval<T> ( std::move(value) ) ;\n        return result;\n    }\n\n    template <typename T>\n    retval<T&> reference(T& value) {\n        return retval<T&> ( value );\n    }\n\n    retval<void> success();\n    retval<void> failed();\n\n    template <typename T>\n    retval<T> failed(StatusCode statusCode, ErrorMessage message) {\n        \n        Expects(statusCode != SUCCESS);\n        return retval<T> { statusCode };\n    }\n\n    template <typename T>\n    retval<T> failed() {        \n        return retval<T> { UNKNOWN };\n    }\n}", "meta": {"hexsha": "31581302f884224fdc5efb9b19a31f86367b93d8", "size": 6434, "ext": "h", "lang": "C", "max_stars_repo_path": "slycore/include/sly/retval.h", "max_stars_repo_name": "Gibbeon/sly", "max_stars_repo_head_hexsha": "9216cf04a78f1d41af01186489ba6680b9641229", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "slycore/include/sly/retval.h", "max_issues_repo_name": "Gibbeon/sly", "max_issues_repo_head_hexsha": "9216cf04a78f1d41af01186489ba6680b9641229", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "slycore/include/sly/retval.h", "max_forks_repo_name": "Gibbeon/sly", "max_forks_repo_head_hexsha": "9216cf04a78f1d41af01186489ba6680b9641229", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4690265487, "max_line_length": 192, "alphanum_fraction": 0.5898352502, "num_tokens": 1511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08269734267503885, "lm_q2_score": 0.013428256296569527, "lm_q1q2_score": 0.0011104811124856583}}
{"text": "#pragma once\n\n#include <memory>\n#include <string>\n#include <unordered_map>\n\n#include <DirectXMath.h>\n#include <gsl/span>\n\nstruct Ray3d;\n\nnamespace gfx {\n\n\tstruct Light3d;\n\tstruct MdfRenderOverrides;\n\tenum class MaterialPlaceholderSlot;\n\n\tstruct AnimatedModelParams;\n\tusing AnimatedModelPtr = std::shared_ptr<class AnimatedModel>;\n\tusing MdfRenderMaterialPtr = std::shared_ptr<class MdfRenderMaterial>;\n\n\tenum class WeaponAnim : int {\n\t\tNone = 0,\n\t\tRightAttack,\n\t\tRightAttack2,\n\t\tRightAttack3,\n\t\tLeftAttack,\n\t\tLeftAttack2,\n\t\tLeftAttack3,\n\t\tWalk,\n\t\tRun,\n\t\tIdle,\n\t\tFrontHit,\n\t\tFrontHit2,\n\t\tFrontHit3,\n\t\tLeftHit,\n\t\tLeftHit2,\n\t\tLeftHit3,\n\t\tRightHit,\n\t\tRightHit2,\n\t\tRightHit3,\n\t\tBackHit,\n\t\tBackHit2,\n\t\tBackHit3,\n\t\tRightCriticalSwing,\n\t\tLeftCriticalSwing,\n\t\tFidget,\n\t\tFidget2,\n\t\tFidget3,\n\t\tSneak,\n\t\tPanic,\n\t\tRightCombatStart,\n\t\tLeftCombatStart,\n\t\tCombatIdle,\n\t\tCombatFidget,\n\t\tSpecial1,\n\t\tSpecial2,\n\t\tSpecial3,\n\t\tFrontDodge,\n\t\tRightDodge,\n\t\tLeftDodge,\n\t\tBackDodge,\n\t\tRightThrow,\n\t\tLeftThrow,\n\t\tLeftSnatch,\n\t\tRightSnatch,\n\t\tLeftTurn,\n\t\tRightTurn\n\t};\n\n\tenum class WeaponAnimType : int {\n\t\tUnarmed = 0,\n\t\tDagger,\n\t\tSword,\n\t\tMace,\n\t\tHammer,\n\t\tAxe,\n\t\tClub,\n\t\tBattleaxe,\n\t\tGreatsword,\n\t\tGreataxe,\n\t\tGreathammer,\n\t\tSpear,\n\t\tStaff,\n\t\tPolearm,\n\t\tBow,\n\t\tCrossbow,\n\t\tSling,\n\t\tShield,\n\t\tFlail,\n\t\tChain,\n\t\tTwoHandedFlail,\n\t\tShuriken,\n\t\tMonk\n\t};\n\n\tenum class BardInstrumentType : int {\n\t\tFlute = 0,\n\t\tDrum,\n\t\tMandolin,\n\t\tTrumpet,\n\t\tHarp,\n\t\tLute,\n\t\tPipers,\n\t\tRecorder\n\t};\n\n\tenum class NormalAnimType : int {\n\t\tFalldown = 0,\n\t\tProneIdle,\n\t\tProneFidget,\n\t\tGetup,\n\t\tMagichands,\n\t\tPicklock,\n\t\tPicklockConcentrated,\n\t\tExamine,\n\t\tThrow,\n\t\tDeath,\n\t\tDeath2,\n\t\tDeath3,\n\t\tDeadIdle,\n\t\tDeadFidget,\n\t\tDeathProneIdle,\n\t\tDeathProneFidget,\n\t\tAbjurationCasting,\n\t\tAbjurationConjuring,\n\t\tConjurationCasting,\n\t\tConjurationConjuring,\n\t\tDivinationCasting,\n\t\tDivinationConjuring,\n\t\tEnchantmentCasting,\n\t\tEnchantmentConjuring,\n\t\tEvocationCasting,\n\t\tEvocationConjuring,\n\t\tIllusionCasting,\n\t\tIllusionConjuring,\n\t\tNecromancyCasting,\n\t\tNecromancyConjuring,\n\t\tTransmutationCasting,\n\t\tTransmutationConjuring,\n\t\tConceal,\n\t\tConcealIdle,\n\t\tUnconceal,\n\t\tItemIdle,\n\t\tItemFidget,\n\t\tOpen,\n\t\tClose,\n\t\tSkillAnimalEmpathy,\n\t\tSkillDisableDevice,\n\t\tSkillHeal,\n\t\tSkillHealConcentrated,\n\t\tSkillHide,\n\t\tSkillHideIdle,\n\t\tSkillHideFidget,\n\t\tSkillUnhide,\n\t\tSkillPickpocket,\n\t\tSkillSearch,\n\t\tSkillSpot,\n\t\tFeatTrack,\n\t\tTrip,\n\t\tBullrush,\n\t\tFlurry,\n\t\tKistrike,\n\t\tTumble,\n\t\tSpecial1,\n\t\tSpecial2,\n\t\tSpecial3,\n\t\tSpecial4,\n\t\tThrow2,\n\t\tWandAbjurationCasting,\n\t\tWandAbjurationConjuring,\n\t\tWandConjurationCasting,\n\t\tWandConjurationConjuring,\n\t\tWandDivinationCasting,\n\t\tWandDivinationConjuring,\n\t\tWandEnchantmentCasting,\n\t\tWandEnchantmentConjuring,\n\t\tWandEvocationCasting,\n\t\tWandEvocationConjuring,\n\t\tWandIllusionCasting,\n\t\tWandIllusionConjuring,\n\t\tWandNecromancyCasting,\n\t\tWandNecromancyConjuring,\n\t\tWandTransmutationCasting,\n\t\tWandTransmutationConjuring,\n\t\tSkillBarbarianRage,\n\t\tOpenIdle\n\t};\n\n\t/*\n\tRepresents an encoded animation id.\n\t*/\n\tclass EncodedAnimId {\n\tpublic:\n\t\texplicit EncodedAnimId(int id) : mId(id) {\n\t\t}\n\n\t\texplicit EncodedAnimId(WeaponAnim anim,\n\t\t                       WeaponAnimType leftHand = WeaponAnimType::Unarmed,\n\t\t                       WeaponAnimType rightHand = WeaponAnimType::Unarmed) : mId(sWeaponAnimFlag) {\n\t\t\tauto animId = (int)anim;\n\t\t\tauto leftHandId = (int)leftHand;\n\t\t\tauto rightHandId = (int)rightHand;\n\n\t\t\tmId |= animId & 0xFFFFF;\n\t\t\tmId |= leftHandId << 20;\n\t\t\tmId |= rightHandId << 25;\n\t\t}\n\n\t\texplicit EncodedAnimId(BardInstrumentType instrumentType) : mId(sBardInstrumentAnimFlag) {\n\t\t\tmId |= (int)instrumentType;\n\t\t}\n\n\t\texplicit EncodedAnimId(NormalAnimType animType) : mId((int) animType) {\n\t\t}\n\n\t\toperator int() const {\n\t\t\treturn mId;\n\t\t}\n\n\t\tbool IsConjuireAnimation() const;\n\n\t\tbool IsSpecialAnim() const {\n\t\t\treturn (mId & (sWeaponAnimFlag | sBardInstrumentAnimFlag)) != 0;\n\t\t}\n\n\t\t// Not for weapon/bard anims\n\t\tNormalAnimType GetNormalAnimType() const {\n\t\t\treturn (NormalAnimType)mId;\n\t\t}\n\n\t\tbool IsWeaponAnim() const {\n\t\t\treturn (mId & sWeaponAnimFlag) != 0;\n\t\t}\n\n\t\t// Only valid for weapon animations\n\t\tWeaponAnimType GetWeaponLeftHand() const {\n\t\t\treturn (WeaponAnimType)((mId >> 20) & 0x1F);\n\t\t}\n\n\t\t// Only valid for weapon animations\n\t\tWeaponAnimType GetWeaponRightHand() const {\n\t\t\treturn (WeaponAnimType)((mId >> 25) & 0x1F);\n\t\t}\n\n\t\t// Only valid for weapon animations\n\t\tWeaponAnim GetWeaponAnim() const {\n\t\t\treturn (WeaponAnim)(mId & 0xFFFFF);\n\t\t}\n\n\t\tbool IsBardInstrumentAnim() const {\n\t\t\treturn (mId & sBardInstrumentAnimFlag) != 0;\n\t\t}\n\n\t\t// Only valid for bard instrument anim\n\t\tBardInstrumentType GetBardInstrumentType() const {\n\t\t\treturn (BardInstrumentType)(mId & 7);\n\t\t}\n\n\t\tstd::string GetName() const;\n\n\t\tbool ToFallback();\n\n\tprivate:\n\t\t// Indicates that an animation id uses the encoded format\n\t\tstatic constexpr int sWeaponAnimFlag = 1 << 30;\n\t\tstatic constexpr int sBardInstrumentAnimFlag = 1 << 31;\n\n\t\tint mId;\n\t};\n\n\t/*\n\t\tRepresents the events that can trigger when the animation\n\t\tof an animated model is advanced.\n\t*/\n\tclass AnimatedModelEvents {\n\tpublic:\n\t\tAnimatedModelEvents(bool isEnd, bool isAction)\n\t\t\t: mIsEnd(isEnd),\n\t\t\t  mIsAction(isAction) {\n\t\t}\n\n\t\tbool IsEnd() const {\n\t\t\treturn mIsEnd;\n\t\t}\n\n\t\tbool IsAction() const {\n\t\t\treturn mIsAction;\n\t\t}\n\n\tprivate:\n\t\tconst bool mIsEnd : 1;\n\t\tconst bool mIsAction : 1;\n\t};\n\n\tclass Submesh {\n\tpublic:\n\t\tvirtual ~Submesh() {\n\t\t}\n\n\t\tvirtual int GetVertexCount() = 0;\n\t\tvirtual int GetPrimitiveCount() = 0;\n\t\tvirtual gsl::span<DirectX::XMFLOAT4> GetPositions() = 0;\n\t\tvirtual gsl::span<DirectX::XMFLOAT4> GetNormals() = 0;\n\t\tvirtual gsl::span<DirectX::XMFLOAT2> GetUV() = 0;\n\t\tvirtual gsl::span<uint16_t> GetIndices() = 0;\n\t};\n\n\tclass IRenderState {\n\tpublic:\n\t\tvirtual ~IRenderState() = default;\n\t};\n\n\tclass AnimatedModel {\n\tpublic:\n\t\tvirtual ~AnimatedModel() {\n\t\t}\n\n\t\tvirtual uint32_t GetHandle() const = 0;\n\n\t\tvirtual bool AddAddMesh(const std::string& filename) = 0;\n\n\t\tvirtual bool ClearAddMeshes() = 0;\n\n\t\tvirtual AnimatedModelEvents Advance(float deltaTime,\n\t\t                                    float deltaDistance,\n\t\t                                    float deltaRotation,\n\t\t                                    const AnimatedModelParams& params) = 0;\n\n\t\tvirtual EncodedAnimId GetAnimId() const = 0;\n\n\t\tvirtual int GetBoneCount() const = 0;\n\n\t\tvirtual std::string GetBoneName(int boneId) = 0;\n\n\t\tvirtual int GetBoneParentId(int boneId) = 0;\n\n\t\tvirtual bool GetBoneWorldMatrixByName(\n\t\t\tconst AnimatedModelParams& params,\n\t\t\tconst std::string& boneName,\n\t\t\tDirectX::XMFLOAT4X4* worldMatrixOut) = 0;\n\n\t\tvirtual bool GetBoneWorldMatrixByNameForChild(const AnimatedModelPtr& child,\n\t\t                                              const AnimatedModelParams& params,\n\t\t                                              const std::string& boneName,\n\t\t\t\tDirectX::XMFLOAT4X4* worldMatrixOut) = 0;\n\n\n\t\tvirtual float GetDistPerSec() const = 0;\n\n\t\tvirtual float GetRotationPerSec() const = 0;\n\n\t\tvirtual bool HasAnim(EncodedAnimId animId) const = 0;\n\n\t\tvirtual void SetTime(const AnimatedModelParams& params, float timeInSecs) = 0;\n\n\t\tvirtual bool HasBone(const std::string& boneName) const = 0;\n\n\t\tvirtual void AddReplacementMaterial(gfx::MaterialPlaceholderSlot slot,\n\t\t\tconst gfx::MdfRenderMaterialPtr &material) = 0;\n\n\t\tvirtual void SetAnimId(EncodedAnimId animId) = 0;\n\n\t\t// This seems to reset cloth simulation state\n\t\tvirtual void SetClothFlag() = 0;\n\n\t\tvirtual std::vector<int> GetSubmeshes() = 0;\n\n\t\tvirtual std::unique_ptr<Submesh> GetSubmesh(const AnimatedModelParams& params, int submeshIdx) = 0;\n\n\t\tvirtual std::unique_ptr<Submesh> GetSubmeshForParticles(const AnimatedModelParams& params, int submeshIdx) = 0;\n\n\t\tbool HitTestRay(const AnimatedModelParams& params, const Ray3d &ray, float &hitDistance);\n\n\t\t/**\n\t\t * Find the closest distance that the given point is away from the surface of this mesh.\n\t\t */\n\t\tfloat GetDistanceToMesh(const AnimatedModelParams &params, DirectX::XMFLOAT3 pos);\n\n\t\t/**\n\t\t\tThis calculates the effective height in world coordinate units of the model in its current\n\t\t\tstate. Scale is the model scale in percent.\n\t\t*/\n\t\tvirtual float GetHeight(int scale = 100) = 0;\n\n\t\t/**\n\t\t\tThis calculates the visible radius of the model in its current state.\n\t\t\tThe radius is the maximum distance of any vertex on the x,z plane from the models origin. \n\t\t\tIf the model has no vertices, 0 is returned.\n\t\t\tScale is model scale in percent.\n\t\t*/\n\t\tvirtual float GetRadius(int scale = 100) = 0;\n\n\t\t/**\n\t\t * Sets a custom render state pointer that will be freed when this model is freed.\n\t\t */\n\t\tvirtual void SetRenderState(std::unique_ptr<IRenderState> renderState) = 0;\n\n\t\t/**\n\t\t * Returns the currently assigned render state or null.\n\t\t */\n\t\tvirtual IRenderState *GetRenderState() const = 0;\n\n\t\ttemplate<typename T>\n\t\tT &GetOrCreateRenderState() {\n\t\t\tauto current = GetRenderState();\n\t\t\tif (!current) {\n\t\t\t\tauto newState = std::make_unique<T>();\n\t\t\t\tcurrent = newState.get();\n\t\t\t\tSetRenderState(std::move(newState));\n\t\t\t}\n\t\t\treturn (T&) *current;\n\t\t}\n\n\t};\n\n\tstruct AnimatedModelParams { // see: objects.GetAnimParams(handle)\n\t\tuint32_t x = 0;\n\t\tuint32_t y = 0;\n\t\tfloat offsetX = 0;\n\t\tfloat offsetY = 0;\n\t\tfloat offsetZ = 0;\n\t\tfloat rotation = 0;\n\t\tfloat scale = 1;\n\t\tfloat rotationRoll = 0;\n\t\tfloat rotationPitch = 0;\n\t\tfloat rotationYaw = 0;\n\t\tAnimatedModelPtr parentAnim;\n\t\tstd::string attachedBoneName;\n\t\tbool rotation3d = false; // Enables use of rotationRoll/rotationPitch/rotationYaw\n\t};\n\n\tclass AnimatedModelFactory {\n\tpublic:\n\t\tvirtual ~AnimatedModelFactory() {\n\t\t}\n\n\t\tvirtual AnimatedModelPtr FromIds(\n\t\t\tint meshId,\n\t\t\tint skeletonId,\n\t\t\tEncodedAnimId idleAnimId,\n\t\t\tconst AnimatedModelParams& params,\n\t\t\tbool borrow = false) = 0;\n\n\t\tvirtual AnimatedModelPtr FromFilenames(\n\t\t\tconst std::string& meshFilename,\n\t\t\tconst std::string& skeletonFilename,\n\t\t\tEncodedAnimId idleAnimId,\n\t\t\tconst AnimatedModelParams& params) = 0;\n\n\t\tvirtual std::unique_ptr<gfx::AnimatedModel> BorrowByHandle(uint32_t handle) = 0;\n\n\t\tvirtual void FreeHandle(uint32_t handle) = 0;\n\n\t\tvirtual void FreeAll() = 0;\n\n\n\t};\n\n\tclass AnimatedModelRenderer {\n\tpublic:\n\t\tvirtual ~AnimatedModelRenderer() {}\n\n\t\tvirtual void Render(AnimatedModel *model,\n\t\t\tconst AnimatedModelParams& params,\n\t\t\tgsl::span<Light3d> lights,\n\t\t\tconst MdfRenderOverrides *materialOverrides = nullptr) = 0;\n\t};\n\n}\n", "meta": {"hexsha": "131db9f30dfa54e41f49d646195d57d45ec35216", "size": 10319, "ext": "h", "lang": "C", "max_stars_repo_path": "Infrastructure/include/infrastructure/meshes.h", "max_stars_repo_name": "edoipi/TemplePlus", "max_stars_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Infrastructure/include/infrastructure/meshes.h", "max_issues_repo_name": "edoipi/TemplePlus", "max_issues_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Infrastructure/include/infrastructure/meshes.h", "max_forks_repo_name": "edoipi/TemplePlus", "max_forks_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.9087048832, "max_line_length": 113, "alphanum_fraction": 0.701327648, "num_tokens": 3094, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10669060246682488, "lm_q2_score": 0.01032815240507123, "lm_q1q2_score": 0.001101916802466236}}
{"text": "#pragma once\n\n#include \"BgfxCallback.h\"\n#include \"FrameBuffer.h\"\n#include \"ShaderCompiler.h\"\n\n#include <Babylon/JsRuntime.h>\n#include <Babylon/JsRuntimeScheduler.h>\n\n#include <GraphicsImpl.h>\n\n#include <napi/napi.h>\n\n#include <bgfx/bgfx.h>\n#include <bgfx/platform.h>\n#include <bimg/bimg.h>\n#include <bx/allocator.h>\n\n#include <gsl/gsl>\n\n#include <assert.h>\n\n#include <arcana/containers/weak_table.h>\n#include <arcana/threading/cancellation.h>\n#include <unordered_map>\n\nnamespace Babylon\n{\n    struct TextureData final\n    {\n        ~TextureData()\n        {\n            if (OwnsHandle && bgfx::isValid(Handle))\n            {\n                bgfx::destroy(Handle);\n            }\n        }\n\n        bgfx::TextureHandle Handle{bgfx::kInvalidHandle};\n        bool OwnsHandle{true};\n        uint32_t Width{0};\n        uint32_t Height{0};\n        uint32_t Flags{0};\n        uint8_t AnisotropicLevel{0};\n    };\n\n    struct UniformInfo final\n    {\n        uint8_t Stage{};\n        bgfx::UniformHandle Handle{bgfx::kInvalidHandle};\n        bool YFlip{false};\n    };\n\n    struct ProgramData final\n    {\n        ProgramData() = default;\n        ProgramData(const ProgramData&) = delete;\n        ProgramData(ProgramData&&) = delete;\n\n        ~ProgramData()\n        {\n            if (bgfx::isValid(Handle))\n            {\n                bgfx::destroy(Handle);\n            }\n        }\n\n        std::unordered_map<std::string, uint32_t> VertexAttributeLocations{};\n        std::unordered_map<std::string, UniformInfo> VertexUniformInfos{};\n        std::unordered_map<std::string, UniformInfo> FragmentUniformInfos{};\n\n        bgfx::ProgramHandle Handle{bgfx::kInvalidHandle};\n\n        struct UniformValue\n        {\n            std::vector<float> Data{};\n            uint16_t ElementLength{};\n            bool YFlip{false};\n        };\n\n        std::unordered_map<uint16_t, UniformValue> Uniforms{};\n\n        void SetUniform(bgfx::UniformHandle handle, gsl::span<const float> data, bool YFlip, size_t elementLength = 1)\n        {\n            UniformValue& value = Uniforms[handle.idx];\n            value.Data.assign(data.begin(), data.end());\n            value.ElementLength = static_cast<uint16_t>(elementLength);\n            value.YFlip = YFlip;\n        }\n    };\n\n    class IndexBufferData;\n    class VertexBufferData;\n\n    struct VertexArray final\n    {\n        ~VertexArray()\n        {\n            for (auto& vertexBufferPair : VertexBuffers)\n            {\n                bgfx::destroy(vertexBufferPair.second.VertexLayoutHandle);\n            }\n        }\n\n        struct IndexBuffer\n        {\n            const IndexBufferData* Data{};\n        };\n\n        IndexBuffer indexBuffer{};\n\n        struct VertexBuffer\n        {\n            const VertexBufferData* Data{};\n            uint32_t StartVertex{};\n            bgfx::VertexLayoutHandle VertexLayoutHandle{};\n        };\n\n        std::unordered_map<uint32_t, VertexBuffer> VertexBuffers;\n    };\n\n    class NativeEngine final : public Napi::ObjectWrap<NativeEngine>\n    {\n        static constexpr auto JS_CLASS_NAME = \"_NativeEngine\";\n        static constexpr auto JS_ENGINE_CONSTRUCTOR_NAME = \"Engine\";\n\n    public:\n        NativeEngine(const Napi::CallbackInfo& info);\n        NativeEngine(const Napi::CallbackInfo& info, JsRuntime& runtime);\n        ~NativeEngine();\n\n        static void Initialize(Napi::Env env);\n\n    private:\n        void Dispose();\n\n        void Dispose(const Napi::CallbackInfo& info);\n        Napi::Value HomogeneousDepth(const Napi::CallbackInfo& info);\n        void RequestAnimationFrame(const Napi::CallbackInfo& info);\n        Napi::Value CreateVertexArray(const Napi::CallbackInfo& info);\n        void DeleteVertexArray(const Napi::CallbackInfo& info);\n        void BindVertexArray(const Napi::CallbackInfo& info);\n        Napi::Value CreateIndexBuffer(const Napi::CallbackInfo& info);\n        void DeleteIndexBuffer(const Napi::CallbackInfo& info);\n        void RecordIndexBuffer(const Napi::CallbackInfo& info);\n        void UpdateDynamicIndexBuffer(const Napi::CallbackInfo& info);\n        Napi::Value CreateVertexBuffer(const Napi::CallbackInfo& info);\n        void DeleteVertexBuffer(const Napi::CallbackInfo& info);\n        void RecordVertexBuffer(const Napi::CallbackInfo& info);\n        void UpdateDynamicVertexBuffer(const Napi::CallbackInfo& info);\n        Napi::Value CreateProgram(const Napi::CallbackInfo& info);\n        Napi::Value GetUniforms(const Napi::CallbackInfo& info);\n        Napi::Value GetAttributes(const Napi::CallbackInfo& info);\n        void SetProgram(const Napi::CallbackInfo& info);\n        void SetState(const Napi::CallbackInfo& info);\n        void SetZOffset(const Napi::CallbackInfo& info);\n        Napi::Value GetZOffset(const Napi::CallbackInfo& info);\n        void SetDepthTest(const Napi::CallbackInfo& info);\n        Napi::Value GetDepthWrite(const Napi::CallbackInfo& info);\n        void SetDepthWrite(const Napi::CallbackInfo& info);\n        void SetColorWrite(const Napi::CallbackInfo& info);\n        void SetBlendMode(const Napi::CallbackInfo& info);\n        void SetMatrix(const Napi::CallbackInfo& info);\n        void SetInt(const Napi::CallbackInfo& info);\n        void SetIntArray(const Napi::CallbackInfo& info);\n        void SetIntArray2(const Napi::CallbackInfo& info);\n        void SetIntArray3(const Napi::CallbackInfo& info);\n        void SetIntArray4(const Napi::CallbackInfo& info);\n        void SetFloatArray(const Napi::CallbackInfo& info);\n        void SetFloatArray2(const Napi::CallbackInfo& info);\n        void SetFloatArray3(const Napi::CallbackInfo& info);\n        void SetFloatArray4(const Napi::CallbackInfo& info);\n        void SetMatrices(const Napi::CallbackInfo& info);\n        void SetMatrix3x3(const Napi::CallbackInfo& info);\n        void SetMatrix2x2(const Napi::CallbackInfo& info);\n        void SetFloat(const Napi::CallbackInfo& info);\n        void SetFloat2(const Napi::CallbackInfo& info);\n        void SetFloat3(const Napi::CallbackInfo& info);\n        void SetFloat4(const Napi::CallbackInfo& info);\n        Napi::Value CreateTexture(const Napi::CallbackInfo& info);\n        void LoadTexture(const Napi::CallbackInfo& info);\n        void LoadRawTexture(const Napi::CallbackInfo& info);\n        void LoadCubeTexture(const Napi::CallbackInfo& info);\n        void LoadCubeTextureWithMips(const Napi::CallbackInfo& info);\n        Napi::Value GetTextureWidth(const Napi::CallbackInfo& info);\n        Napi::Value GetTextureHeight(const Napi::CallbackInfo& info);\n        void SetTextureSampling(const Napi::CallbackInfo& info);\n        void SetTextureWrapMode(const Napi::CallbackInfo& info);\n        void SetTextureAnisotropicLevel(const Napi::CallbackInfo& info);\n        void SetTexture(const Napi::CallbackInfo& info);\n        void DeleteTexture(const Napi::CallbackInfo& info);\n        Napi::Value CreateFrameBuffer(const Napi::CallbackInfo& info);\n        void DeleteFrameBuffer(const Napi::CallbackInfo& info);\n        void BindFrameBuffer(const Napi::CallbackInfo& info);\n        void UnbindFrameBuffer(const Napi::CallbackInfo& info);\n        void DrawIndexed(const Napi::CallbackInfo& info);\n        void Draw(const Napi::CallbackInfo& info);\n        void Clear(const Napi::CallbackInfo& info);\n        Napi::Value GetRenderWidth(const Napi::CallbackInfo& info);\n        Napi::Value GetRenderHeight(const Napi::CallbackInfo& info);\n        void SetViewPort(const Napi::CallbackInfo& info);\n        Napi::Value GetHardwareScalingLevel(const Napi::CallbackInfo& info);\n        void SetHardwareScalingLevel(const Napi::CallbackInfo& info);\n        Napi::Value CreateImageBitmap(const Napi::CallbackInfo& info);\n        Napi::Value ResizeImageBitmap(const Napi::CallbackInfo& info);\n        void GetFrameBufferData(const Napi::CallbackInfo& info);\n\n        void Draw(bgfx::Encoder* encoder, int fillMode);\n\n        GraphicsImpl::UpdateToken& GetUpdateToken();\n\n        std::shared_ptr<arcana::cancellation_source> m_cancellationSource{};\n\n        ShaderCompiler m_shaderCompiler{};\n\n        ProgramData* m_currentProgram{nullptr};\n        arcana::weak_table<std::unique_ptr<ProgramData>> m_programDataCollection{};\n\n        JsRuntime& m_runtime;\n        GraphicsImpl& m_graphicsImpl;\n\n        JsRuntimeScheduler m_runtimeScheduler;\n\n        std::optional<GraphicsImpl::UpdateToken> m_updateToken{};\n\n        void ScheduleRequestAnimationFrameCallbacks();\n        bool m_requestAnimationFrameCallbacksScheduled{};\n\n        bx::DefaultAllocator m_allocator{};\n        uint64_t m_engineState{BGFX_STATE_DEFAULT};\n\n        template<int size, typename arrayType>\n        void SetTypeArrayN(const Napi::CallbackInfo& info);\n\n        template<int size>\n        void SetFloatN(const Napi::CallbackInfo& info);\n\n        template<int size>\n        void SetMatrixN(const Napi::CallbackInfo& info);\n\n        // Scratch vector used for data alignment.\n        std::vector<float> m_scratch{};\n\n        std::vector<Napi::FunctionReference> m_requestAnimationFrameCallbacks{};\n\n        const VertexArray* m_boundVertexArray{};\n        FrameBuffer* m_boundFrameBuffer{};\n    };\n}\n", "meta": {"hexsha": "5c592992d499538c46b314e2ceaf1ce3f0a4b043", "size": 9113, "ext": "h", "lang": "C", "max_stars_repo_path": "Plugins/NativeEngine/Source/NativeEngine.h", "max_stars_repo_name": "lupin4/BabylonNative", "max_stars_repo_head_hexsha": "cfbea50839e10cd53576b4382b191f5213a634f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Plugins/NativeEngine/Source/NativeEngine.h", "max_issues_repo_name": "lupin4/BabylonNative", "max_issues_repo_head_hexsha": "cfbea50839e10cd53576b4382b191f5213a634f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Plugins/NativeEngine/Source/NativeEngine.h", "max_forks_repo_name": "lupin4/BabylonNative", "max_forks_repo_head_hexsha": "cfbea50839e10cd53576b4382b191f5213a634f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.452, "max_line_length": 118, "alphanum_fraction": 0.6628991551, "num_tokens": 2054, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07921032410902436, "lm_q2_score": 0.013848612988287348, "lm_q1q2_score": 0.0010969531232626851}}
{"text": "//          Copyright Jean Pierre Cimalando 2019.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE.md or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n#pragma once\n#include <gsl/gsl>\n\ntemplate <class Ch> bool string_starts_with(gsl::basic_string_span<const Ch> text, gsl::basic_string_span<const Ch> prefix);\ntemplate <class Ch> bool string_ends_with(gsl::basic_string_span<const Ch> text, gsl::basic_string_span<const Ch> suffix);\n\n#include \"strings.tcc\"\n", "meta": {"hexsha": "a797da37f186189a37bbf2174d13dc452406892a", "size": 519, "ext": "h", "lang": "C", "max_stars_repo_path": "sources/utility/strings.h", "max_stars_repo_name": "jpcima/smf-dsp", "max_stars_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2020-07-08T15:23:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T23:08:17.000Z", "max_issues_repo_path": "sources/utility/strings.h", "max_issues_repo_name": "jpcima/smf-dsp", "max_issues_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2020-07-05T23:59:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-16T20:44:07.000Z", "max_forks_repo_path": "sources/utility/strings.h", "max_forks_repo_name": "jpcima/smf-dsp", "max_forks_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-07-10T18:48:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-22T08:05:13.000Z", "avg_line_length": 39.9230769231, "max_line_length": 124, "alphanum_fraction": 0.7418111753, "num_tokens": 128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.037326884131416216, "lm_q2_score": 0.02931222735949175, "lm_q1q2_score": 0.0010941341142814767}}
{"text": "#pragma once\n\n#include <gsl/span>\n#include <rapidjson/fwd.h>\n#include <spdlog/fwd.h>\n\n#include <memory>\n\nnamespace CesiumGltf {\nstruct Model;\n}\n\nnamespace Cesium3DTilesSelection {\n\n/**\n * @brief Parses the provided B3DM batch table and adds an equivalent\n * EXT_feature_metadata extension to the provided glTF.\n *\n * @param pLogger\n * @param gltf\n * @param featureTable\n * @param batchTableJson\n * @param batchTableBinaryData\n */\nvoid upgradeBatchTableToFeatureMetadata(\n    const std::shared_ptr<spdlog::logger>& pLogger,\n    CesiumGltf::Model& gltf,\n    const rapidjson::Document& featureTable,\n    const rapidjson::Document& batchTableJson,\n    const gsl::span<const std::byte>& batchTableBinaryData);\n\n} // namespace Cesium3DTilesSelection\n", "meta": {"hexsha": "d0f0b919fa95362de2c23cbb9f34d0160ccf5869", "size": 744, "ext": "h", "lang": "C", "max_stars_repo_path": "Cesium3DTilesSelection/src/upgradeBatchTableToFeatureMetadata.h", "max_stars_repo_name": "yieryi/cesium-native", "max_stars_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 154.0, "max_stars_repo_stars_event_min_datetime": "2021-03-30T14:08:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T00:01:43.000Z", "max_issues_repo_path": "Cesium3DTilesSelection/src/upgradeBatchTableToFeatureMetadata.h", "max_issues_repo_name": "yieryi/cesium-native", "max_issues_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 256.0, "max_issues_repo_issues_event_min_datetime": "2021-03-30T18:12:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:44:21.000Z", "max_forks_repo_path": "Cesium3DTilesSelection/src/upgradeBatchTableToFeatureMetadata.h", "max_forks_repo_name": "yieryi/cesium-native", "max_forks_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 66.0, "max_forks_repo_forks_event_min_datetime": "2021-03-30T15:14:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T13:38:41.000Z", "avg_line_length": 22.5454545455, "max_line_length": 69, "alphanum_fraction": 0.748655914, "num_tokens": 192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.04742587587030561, "lm_q2_score": 0.0229773676938156, "lm_q1q2_score": 0.001089721788073269}}
{"text": "// MIT License\n//\n// Copyright (c) 2020 SunnyCase\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n#pragma once\n#include <board.h>\n#include <chino/ddk/list.h>\n#include <chino/ddk/object.h>\n#include <chino/threading.h>\n#include <gsl/gsl-lite.hpp>\n\nnamespace chino::threading\n{\nnamespace details\n{\n    struct kthread_checker;\n}\n\nstruct kprocess;\n\nstruct kthread : public ob::object\n{\n    static constexpr ptrdiff_t PROCESS_THREAD_ENTRY_OFFSET = 0;\n    static constexpr ptrdiff_t SCHED_ENTRY_OFFSET = PROCESS_THREAD_ENTRY_OFFSET + VOID_LIST_NODE_SIZE;\n\n    kthread() = default;\n\n    void init_stack(gsl::span<uintptr_t> stack, thread_start_t start, void *arg) noexcept;\n\n    friend struct details::kthread_checker;\n\n    // BEGIN LIST NODES, BE CAREFUL ABOUT THE OFFSETS !!!\n    list_node<kthread, void, PROCESS_THREAD_ENTRY_OFFSET> process_threads_entry_;\n    list_node<kthread, void, SCHED_ENTRY_OFFSET> sched_entry_;\n    // END LIST NODES\n\n    kprocess *owner_ = nullptr;\n    tid_t tid_;\n    thread_priority priority_;\n    std::atomic<uint32_t> exit_code_;\n    gsl::span<uintptr_t> stack_;\n    arch::thread_context_t context_;\n};\n\nnamespace details\n{\n    struct kthread_checker\n    {\n        static_assert(offsetof(kthread, process_threads_entry_) == kthread::PROCESS_THREAD_ENTRY_OFFSET);\n    };\n}\n}\n", "meta": {"hexsha": "aa294b415b0a8fa842201dfc57223b6b7ebdc9fe", "size": 2326, "ext": "h", "lang": "C", "max_stars_repo_path": "src/kernel/include/chino/threading/thread.h", "max_stars_repo_name": "chino-os/chino-os", "max_stars_repo_head_hexsha": "e4b444983a059231636b81dc5f33206e16a859c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2018-04-28T09:50:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T11:42:23.000Z", "max_issues_repo_path": "src/kernel/include/chino/threading/thread.h", "max_issues_repo_name": "dotnetGame/chino-os", "max_issues_repo_head_hexsha": "e4b444983a059231636b81dc5f33206e16a859c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2018-05-15T02:15:33.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-30T14:46:51.000Z", "max_forks_repo_path": "src/kernel/include/chino/threading/thread.h", "max_forks_repo_name": "dotnetGame/chino-os", "max_forks_repo_head_hexsha": "e4b444983a059231636b81dc5f33206e16a859c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2018-05-18T03:54:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T10:14:07.000Z", "avg_line_length": 33.2285714286, "max_line_length": 105, "alphanum_fraction": 0.7502149613, "num_tokens": 530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.05419872982318558, "lm_q2_score": 0.02002344088740789, "lm_q1q2_score": 0.0010852450627871475}}
{"text": "#pragma once\n\n#define STRICT\n#define NOMINMAX\n#include <phnt/phnt_windows.h>\n#include <phnt/phnt.h>\n#pragma comment( lib, \"ntdll.lib\" )\n\n#include <delayimp.h>\n#ifndef _delayimp_h\n#define _delayimp_h\n#endif\n#pragma comment( lib, \"delayimp.lib\" )\n\nEXTERN_C const IMAGE_DOS_HEADER __ImageBase;\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <strsafe.h>\n#include <stdint.h>\n\n#include <string>\n#include <filesystem>\nnamespace fs = std::filesystem;\n\n#include <codecvt>\n#include <gsl/gsl>\n#include <wil/token_helpers.h>\n#include <wil/resource.h>\n\n#define DETOURS_INTERNAL\n#include <detours/detours.h>\n\n#define SPDLOG_ACTIVE_LEVEL SPDLOG_LEVEL_DEBUG\n#define SPDLOG_WCHAR_TO_UTF8_SUPPORT\n#include <spdlog/spdlog.h>\n#include <spdlog/sinks/msvc_sink.h>\n#include <spdlog/fmt/bin_to_hex.h>\n", "meta": {"hexsha": "797cdcb6a5370199ccc922f174f069faad51a6e2", "size": 779, "ext": "h", "lang": "C", "max_stars_repo_path": "src/client/pch.h", "max_stars_repo_name": "LowerCode/bnspatch", "max_stars_repo_head_hexsha": "321608bb86714ee5137823ade21a81f4e0058c09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-11T17:41:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-11T17:41:11.000Z", "max_issues_repo_path": "src/client/pch.h", "max_issues_repo_name": "LowerCode/bnspatch", "max_issues_repo_head_hexsha": "321608bb86714ee5137823ade21a81f4e0058c09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/client/pch.h", "max_forks_repo_name": "LowerCode/bnspatch", "max_forks_repo_head_hexsha": "321608bb86714ee5137823ade21a81f4e0058c09", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-22T00:15:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-22T00:15:04.000Z", "avg_line_length": 19.9743589744, "max_line_length": 46, "alphanum_fraction": 0.7676508344, "num_tokens": 207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.055005291391686174, "lm_q2_score": 0.019719128863461263, "lm_q1q2_score": 0.0010846564291248962}}
{"text": "#pragma once\n\n#include <gsl.h>\n\n#include <boost/optional.hpp>\n\n#include <mitkDataStorage.h>\n#include <mitkNodePredicateBase.h>\n\n#include <mitkOperationActor.h>\n\n#include \"uk_ac_kcl_HierarchyManager_Export.h\"\n\n#define DECLARE_HIERARCHY_MANAGER_NODE_TYPE(nodeTypeName) static const crimson::HierarchyManager::NodeType& nodeTypeName();\n\n#define DEFINE_HIERARCHY_MANAGER_NODE_TYPE(containerClass, nodeTypeName)                                                       \\\n    const crimson::HierarchyManager::NodeType& containerClass::nodeTypeName()                                                  \\\n    {                                                                                                                          \\\n        static const crimson::HierarchyManager::NodeType type = crimson::HierarchyManager::getInstance()->createNodeType();    \\\n        return type;                                                                                                           \\\n    }\n\nnamespace crimson\n{\n\n/*! \\brief   A singleton class for managing the hierarchical relations of CRIMSON data objects. \n *  \n * The hierarchical relations define the dependencies between various data objects.\n * This mostly affects how the nodes are presented to the user in the MITK's Data Manager view.\n * For example, the vessel paths belonging to the same vessel tree must be grouped under the node\n * representing this vessel tree. Thus, deleting the vessel tree node will also delete the vessel \n * paths belonging to it. \n *  \n * Hierarchical grouping also facilitates the discovery of th nodes using the mitk::DataStorage.\n * For example, to find all the contours defining a vessel, it is sufficient to iterate the \n * child nodes of the vessel path and select the nodes containing contours.\n *  \n * HierarchyManager allows adding new node types and relationships between them. The most \n * convenient way to do so is to use the DECLARE_HIERARCHY_MANAGER_NODE_TYPE and  \n * DEFINE_HIERARCHY_MANAGER_NODE_TYPE macro pair. This will correctly register the node types in \n * the hierarchy mananger.\n *     \n * Example usage:\n * \n *     // MyNodeTypes.h\n *     #pragma once  \n *     #include <HierarchyManager.h>  \n *         \n *     struct MyNodeTypes {   \n *         DECLARE_HIERARCHY_MANAGER_NODE_TYPE(MyParentNode)                  \n *         DECLARE_HIERARCHY_MANAGER_NODE_TYPE(MyChildNode)                       \n *     };            \n *     \n *     // MyNodeTypes.cpp\n *     #include \"MyNodeTypes.h\"\n *     \n *     DEFINE_HIERARCHY_MANAGER_NODE_TYPE(MyNodeTypes, MyParentNode)\n *     DEFINE_HIERARCHY_MANAGER_NODE_TYPE(MyNodeTypes, MyChildNode)\n *     \n *     // UsingHierarchyManager.cpp\n *     void initialize()\n *     {\n *          auto hm = crimson::HierarchyManager::getInstance();\n *          hm->addNodeType(MyNodeTypes::MyParentNode(), ParentNodePredicate::New());\n *          hm->addNodeType(MyNodeTypes::MyChildNode(),  ChildNodePredicate::New());\n *          hm->addRelation(MyNodeTypes::MyParentNode(), MyNodeTypes::MyChildNode(), crimson::HierarchyManager::rtOneToMany);\n *     }\n *     \n *     void addNode(mitk::DataNode* parent, mitkDataNode* child)\n *     {\n *          auto hm = crimson::HierarchyManager::getInstance();\n *          hm->addNodeToHierarchy(parent, MyNodeTypes::MyParentNode(), child, MyNodeTypes::MyChildNode());\n *          // ...\n *     }\n */\n\nclass HIERARCHYMANAGER_EXPORT HierarchyManager : public itk::Object, public mitk::OperationActor\n{\npublic:\n    /*! \\name Singleton interface */\n    ///@{ \n    static bool init();\n    static HierarchyManager* getInstance();\n    static void term();\n    ///@} \n\n    using NodeType = int;   \n\n    /*!\n     * \\brief   Creates a unique id for a new node type.\n     */\n    int createNodeType() { return _lastAssignedNodeType++; }\n\n    /*! \\brief   Values that represent relation types between parent and child nodes. */\n    enum RelationType { \n        rtOneToOne = 0, ///< Only one child of a particular type is allowed for the parent\n        rtOneToMany, ///< Multiple children of a particular type are allowed for the parent\n        rtUnknown   ///< No information about the relations between types\n    };\n\n    /*! \\brief   Values that represent node type flags. */\n    enum NodeTypeFlags {\n        ntfNone = 0x00, ///< No flags\n        ntfRecursiveDeletion = 0x01,    ///< Deleting a parent node also deletes all its children\n        ntfUndoableDeletion = 0x02, ///< If the node is deleted, it should be put onto undo stack to allow deletion undo\n        ntfPickable = 0x04  ///< The node should be allowed to be picked with mouse clicks in 3D rendering window\n    };\n\n    ///@{ \n    /*!\n     * \\brief   Adds a new node type.\n     *\n     * \\param   type        The new node type identifier.\n     * \\param   predicate   The predicate defining the node.\n     * \\param   flags       The flags to be applied for nodes of this type.\n     */\n    bool addNodeType(const NodeType& type, const mitk::NodePredicateBase::Pointer& predicate, int flags = ntfNone);\n\n    /*!\n     * \\brief   Adds a relation between the parent and child node types.\n     *\n     * \\param   parentType  Type of the parent.\n     * \\param   childType   Type of the child.\n     * \\param   relation    The type of relation.\n     */\n    bool addRelation(const NodeType& parentType, const NodeType& childType, const RelationType& relation);\n\n    /*!\n     * \\brief   Gets a relation between the parent and child node types.\n     *\n     * \\param   parentNodeType  Type of the parent node.\n     * \\param   childNodeType   Type of the child node.\n     */\n    RelationType getRelation(const NodeType& parentNodeType, const NodeType& childNodeType) const;\n    ///@} \n                     \n\n    /*!\n     * \\brief   Gets data storage that the HierarchyManager operates upon.\n     */\n    mitk::DataStorage::Pointer getDataStorage() const;\n\n    /*!\n     * \\brief   Set the flag whether to start a new undo group when adding nodes to hierarchy.\n     *  \n     *  By default, addNodeToHierarchy() will start a new undo group meaning that undoing the\n     *  addition will remove nodes one by one. However, when multiple nodes are to be added as a\n     *  single unit, set this flag to false (and reset it to true after all nodes are added).\n     */\n    void setStartNewUndoGroup(bool start);\n\n    /*!\n     * \\brief   Determine if a child node of a particular type can be added to the parent node of a different type.\n     *\n     * \\param   parentNode          The desired parent node.\n     * \\param   parentNodeType      Type of the parent node.\n     * \\param   childNodeType       Type of the child node.\n     * \\param   allowReplacement    true if replacing a node is allowed (useful for rtOneToOne relationship).\n     */\n    bool canAddNode(mitk::DataNode* parentNode, const NodeType& parentNodeType, const NodeType& childNodeType,\n                    bool allowReplacement) const;\n\n    /*!\n     * \\brief   Adds a node to hierarchy.\n     *\n     * \\param   parentNode      The parent node.\n     * \\param   parentNodeType  Type of the parent node.\n     * \\param   newNode         The new node.\n     * \\param   newNodeType     Type of the new node.\n     *\n     * \\return  false if the relationship between the node types is unknown.\n     */\n    bool addNodeToHierarchy(const mitk::DataNode* parentNode, const NodeType& parentNodeType, const mitk::DataNode* newNode,\n                            const NodeType& newNodeType);\n\n    /*!\n     * \\brief   Searches for the first node type that the node satisfies.\n     */\n    boost::optional<NodeType> findFittingNodeType(mitk::DataNode* node) const;\n\n    /*!\n     * \\brief   Searches for the potential parents of the node with a particular nodeType.\n     */\n    std::unordered_set<mitk::DataNode*> findPotentialParents(mitk::DataNode* node, NodeType nodeType) const;\n\n    /*!\n     * \\brief   Change the parent of the node.\n     */\n    bool reparentNode(const mitk::DataNode::Pointer& node, const mitk::DataNode::Pointer& newParent);\n\n    /*!\n     * \\brief   Gets a predicate associated with the node type.\n     */\n    mitk::NodePredicateBase::Pointer getPredicate(const NodeType& type) const;\n\n    ///@{ \n    /*!\n     * \\brief   Gets an ancestor of the node of a particular type.\n     *\n     * \\param   node        The child node.\n     * \\param   parentType  Type of the parent.\n     * \\param   directOnly  false to search parents of parents.\n     */\n    mitk::DataNode::Pointer getAncestor(const mitk::DataNode* node, const NodeType& parentType, bool directOnly = false) const;\n\n    /*!\n     * \\brief   Gets the first descendant node of a particular type.\n     *\n     * \\param   node            The parent node.\n     * \\param   descendantType  Type of the descendant.\n     * \\param   directOnly      false to search children of children.\n     */\n    mitk::DataNode::Pointer getFirstDescendant(const mitk::DataNode* node, const NodeType& descendantType,\n                                               bool directOnly = false) const;\n\n    /*!\n     * \\brief   Gets all the descendant nodes of a particular type.\n     *\n     * \\param   node            The parent node.\n     * \\param   descendantsType Type of the descendants.\n     * \\param   directOnly      false to search children of children.\n     */\n    mitk::DataStorage::SetOfObjects::ConstPointer getDescendants(const mitk::DataNode* node, const NodeType& descendantsType,\n                                                                 bool directOnly = false) const;\n\n    ///@} \n     \n    static const char* nodeUIDPropertyName; ///< The name of the DataNode property where the nodeUID is stored\n\n    /*!\n     * \\brief   Searches for the node with a particular UID.\n     */\n    mitk::DataNode::Pointer findNodeByUID(gsl::cstring_span<> nodeUID) const;\n\n    /*!\n     * \\brief   Enables/disables the undo for adding and deleting nodes.\n     */\n    void enableUndo(bool enable);\n\n    /*!\n     * \\brief   Overriden from mitk::Operation for undo/redo support.\n     */\n    void ExecuteOperation(mitk::Operation* operation) override;\n\nprivate:\n    HierarchyManager();\n    ~HierarchyManager();\n\n    HierarchyManager(const HierarchyManager&) = delete;\n    HierarchyManager& operator=(const HierarchyManager&) = delete;\n\n    void _connectDataStorageEvents();\n    void _disconnectDataStorageEvents();\n\n    void nodeAdded(const mitk::DataNode*);\n    void nodeRemoved(const mitk::DataNode*);\n\nprivate:\n    static HierarchyManager* _instance;\n\n    struct HierarchyManagerImpl;\n\n    std::unique_ptr<HierarchyManagerImpl> _impl;\n\n    int _lastAssignedNodeType = 0;\n\n    bool _testFlags(const mitk::DataNode* node, NodeTypeFlags flags) const;\n    std::vector<std::pair<std::vector<const mitk::DataNode*>, mitk::DataNode::ConstPointer>>\n    _getUndoableRemoveNodes(const mitk::DataNode* node) const;\n};\n\n} // namespace crimson", "meta": {"hexsha": "464d4379d51f32bf16ec1b64486fc9a4a1bd2196", "size": 10829, "ext": "h", "lang": "C", "max_stars_repo_path": "Plugins/uk.ac.kcl.HierarchyManager/src/HierarchyManager.h", "max_stars_repo_name": "carthurs/CRIMSONGUI", "max_stars_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-09-17T18:55:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T02:52:38.000Z", "max_issues_repo_path": "Plugins/uk.ac.kcl.HierarchyManager/src/HierarchyManager.h", "max_issues_repo_name": "carthurs/CRIMSONGUI", "max_issues_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Plugins/uk.ac.kcl.HierarchyManager/src/HierarchyManager.h", "max_forks_repo_name": "carthurs/CRIMSONGUI", "max_forks_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-05-19T09:02:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-26T17:39:57.000Z", "avg_line_length": 39.8125, "max_line_length": 128, "alphanum_fraction": 0.63920953, "num_tokens": 2421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08269734945731683, "lm_q2_score": 0.013020488893067478, "lm_q1q2_score": 0.0010767599200951136}}
{"text": "#pragma once\n\n#include \"CesiumGltfWriter/Library.h\"\n\n#include <CesiumJsonWriter/ExtensionWriterContext.h>\n\n#include <gsl/span>\n\n// forward declarations\nnamespace CesiumGltf {\nstruct Model;\n}\n\nnamespace CesiumGltfWriter {\n\n/**\n * @brief The result of writing a glTF with\n * {@link GltfWriter::writeGltf} or {@link GltfWriter::writeGlb}\n */\nstruct CESIUMGLTFWRITER_API GltfWriterResult {\n  /**\n   * @brief The final generated std::vector<std::byte> of the glTF or glb.\n   */\n  std::vector<std::byte> gltfBytes;\n\n  /**\n   * @brief Errors, if any, that occurred during the write process.\n   */\n  std::vector<std::string> errors;\n\n  /**\n   * @brief Warnings, if any, that occurred during the write process.\n   */\n  std::vector<std::string> warnings;\n};\n\n/**\n * @brief Options for how to write a glTF.\n */\nstruct CESIUMGLTFWRITER_API GltfWriterOptions {\n  /**\n   * @brief If the glTF JSON should be pretty printed. Usable with glTF or GLB\n   * (not advised).\n   */\n  bool prettyPrint = false;\n\n  /**\n   * @brief Byte alignment of the GLB binary chunk. When using 64-bit types in\n   * EXT_mesh_features or EXT_feature_metadata this value should be set to 8.\n   */\n  size_t binaryChunkByteAlignment = 4;\n};\n\n/**\n * @brief Writes glTF.\n */\nclass CESIUMGLTFWRITER_API GltfWriter {\npublic:\n  /**\n   * @brief Constructs a new instance.\n   */\n  GltfWriter();\n\n  /**\n   * @brief Gets the context used to control how glTF extensions are written.\n   */\n  CesiumJsonWriter::ExtensionWriterContext& getExtensions();\n\n  /**\n   * @brief Gets the context used to control how glTF extensions are written.\n   */\n  const CesiumJsonWriter::ExtensionWriterContext& getExtensions() const;\n\n  /**\n   * @brief Serializes the provided model into a glTF JSON byte vector.\n   *\n   * @details Ignores internal data such as {@link CesiumGltf::BufferCesium}\n   * and {@link CesiumGltf::ImageCesium} when serializing the glTF. Internal\n   * data must either be converted to data uris or saved as external files. The\n   * buffer.uri and image.uri fields must be set accordingly prior to calling\n   * this function.\n   *\n   * @param model The model.\n   * @param options Options for how to write the glTF.\n   * @return The result of writing the glTF.\n   */\n  GltfWriterResult writeGltf(\n      const CesiumGltf::Model& model,\n      const GltfWriterOptions& options = GltfWriterOptions()) const;\n\n  /**\n   * @brief Serializes the provided model into a glb byte vector.\n   *\n   * @details The first buffer object implicitly refers to the GLB binary chunk\n   * and should not have a uri. Ignores internal data such as\n   * {@link CesiumGltf::BufferCesium} and {@link CesiumGltf::ImageCesium}.\n   *\n   * @param model The model.\n   * @param bufferData The buffer data to store in the GLB binary chunk.\n   * @param options Options for how to write the glb.\n   * @return The result of writing the glb.\n   */\n  GltfWriterResult writeGlb(\n      const CesiumGltf::Model& model,\n      const gsl::span<const std::byte>& bufferData,\n      const GltfWriterOptions& options = GltfWriterOptions()) const;\n\nprivate:\n  CesiumJsonWriter::ExtensionWriterContext _context;\n};\n\n} // namespace CesiumGltfWriter\n", "meta": {"hexsha": "9cedeee58340a0244aaa0b5cab255ed3cac7c918", "size": 3148, "ext": "h", "lang": "C", "max_stars_repo_path": "CesiumGltfWriter/include/CesiumGltfWriter/GltfWriter.h", "max_stars_repo_name": "yieryi/cesium-native", "max_stars_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CesiumGltfWriter/include/CesiumGltfWriter/GltfWriter.h", "max_issues_repo_name": "yieryi/cesium-native", "max_issues_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CesiumGltfWriter/include/CesiumGltfWriter/GltfWriter.h", "max_forks_repo_name": "yieryi/cesium-native", "max_forks_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8584070796, "max_line_length": 79, "alphanum_fraction": 0.7023506989, "num_tokens": 850, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.054198731350889234, "lm_q2_score": 0.01971913001563606, "lm_q1q2_score": 0.001068751830190715}}
{"text": "#pragma once\n\n#include <winrt\\Windows.Foundation.h>\n#include <d3d11.h>\n#include <gsl\\gsl>\n\nnamespace Library\n{\n\tclass BlendStates final\n\t{\n\tpublic:\n\t\tinline static winrt::com_ptr<ID3D11BlendState> AlphaBlending;\n\t\tinline static winrt::com_ptr<ID3D11BlendState> MultiplicativeBlending;\n\n\t\tstatic void Initialize(gsl::not_null<ID3D11Device*> direct3DDevice);\n\t\tstatic void Shutdown();\n\n\t\tBlendStates() = delete;\n\t\tBlendStates(const BlendStates&) = delete;\n\t\tBlendStates& operator=(const BlendStates&) = delete;\n\t\tBlendStates(BlendStates&&) = delete;\n\t\tBlendStates& operator=(BlendStates&&) = delete;\n\t\t~BlendStates() = default;\n\t};\n}", "meta": {"hexsha": "195df2052f0b73e5490ec279be0f79d91baac120", "size": 631, "ext": "h", "lang": "C", "max_stars_repo_path": "source/Library.Shared/BlendStates.h", "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/Library.Shared/BlendStates.h", "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/Library.Shared/BlendStates.h", "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.24, "max_line_length": 72, "alphanum_fraction": 0.7480190174, "num_tokens": 175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.05749328364515302, "lm_q2_score": 0.018546562342199667, "lm_q1q2_score": 0.001066302769382599}}
{"text": "// Copyright (c) 2021 SmartPolarBear\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n//\n// Created by cleve on 9/1/2021.\n//\n#pragma once\n\n#include <base/iterable_stack.h>\n\n#include <interpreter/vm/opcode.h>\n#include <interpreter/vm/chunk.h>\n#include <interpreter/vm/value.h>\n#include <interpreter/vm/exceptions.h>\n\n#include <interpreter/vm/heap.h>\n#include <interpreter/vm/heap_allocator.h>\n#include <interpreter/vm/garbage_collector.h>\n\n\n#include <interpreter/vm/string_object.h>\n#include <interpreter/vm/closure_object.h>\n#include <interpreter/vm/instance_object.h>\n\n#include <memory>\n#include <map>\n#include <ranges>\n\n#include <gsl/gsl>\n#include \"class_object.h\"\n\nnamespace clox::interpreting::vm\n{\n\nenum class virtual_machine_status\n{\n\tOK,\n\tRUNTIME_ERROR,\n};\n\ntemplate<typename F, typename R, class ...Args>\nconcept BinaryOperator=\nrequires(F&& f, Args&& ... args) {\n\t{ std::invoke(std::forward<F>(f), std::forward<Args>(args)...) }->std::same_as<R>;\n};\n\nclass virtual_machine final\n{\npublic:\n\tfriend class garbage_collector;\n\n\tstatic inline constexpr size_t CALL_STACK_RESERVED_SIZE = 64;\n\tstatic inline constexpr size_t STACK_RESERVED_SIZE = 16384;\n\n\tusing value_list_type = std::vector<value>;\n\tusing global_table_type = std::unordered_map<std::string, value>;\n\tusing function_table_type = std::unordered_map<full_opcode_type, value>;\n\tusing ip_type = chunk::iterator_type;\n\n\tusing index_type = gsl::index;\n\n\tclass call_frame final\n\t{\n\tpublic:\n\n\n\tpublic:\n\n\t\texplicit call_frame(closure_object_raw_pointer closure, ip_type ip, size_t offset)\n\t\t\t\t: closure_(closure), ip_(ip), stack_offset_(offset)\n\t\t{\n\t\t}\n\n\t\t[[nodiscard]] size_t stack_offset() const\n\t\t{\n\t\t\treturn stack_offset_;\n\t\t}\n\n\t\t[[nodiscard]] function_object_raw_pointer function() const\n\t\t{\n\t\t\treturn closure_->function();\n\t\t}\n\n\t\t[[nodiscard]] closure_object_raw_pointer closure() const\n\t\t{\n\t\t\treturn closure_;\n\t\t}\n\n\t\t[[nodiscard]] ip_type& ip()\n\t\t{\n\t\t\treturn ip_;\n\t\t}\n\n\n\tprivate:\n\t\tclosure_object_raw_pointer closure_{};\n\t\tip_type ip_{};\n\t\tsize_t stack_offset_{};\n\t};\n\n\tusing call_frame_list_type = std::vector<call_frame>;\n\npublic:\n\tvirtual_machine() = delete;\n\n\t~virtual_machine();\n\n\texplicit virtual_machine(helper::console& cons,\n\t\t\tstd::shared_ptr<object_heap> heap);\n\n\tvirtual_machine_status run(clox::interpreting::vm::closure_object* closure);\n\nprivate:\n\tvirtual_machine_status run();\n\n\t// {return status, exit}\n\tstd::tuple<std::optional<virtual_machine_status>, bool> run_code(chunk::code_type instruction, call_frame& frame);\n\n\ttemplate<class ...TArgs>\n\tvoid runtime_error(std::string_view fmt, const TArgs& ...args)\n\t{\n\n\t\tcons_->error() << std::format(\"[Line {}] in file {}:\",\n\t\t\t\ttop_call_frame().function()->body()->line_of(top_call_frame().ip()),\n\t\t\t\ttop_call_frame().function()->body()->filename()) << std::endl;\n\n\t\tcons_->error() << std::format(fmt, args...) << \"\\n\";\n\n\t\tcons_->error() << \"Call stack:\" << std::endl;\n\t\tfor (auto& frm: call_frames_ | std::ranges::views::reverse)\n\t\t{\n\t\t\tauto func = frm.function();\n\t\t\tauto line = func->body()->line_of(frm.ip() - 1);\n\t\t\tcons_->error() << std::format(\"[Line {}] in \", line);\n\t\t\tif (func->name().empty())\n\t\t\t{\n\t\t\t\tcons_->error() << \"script\" << std::endl;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcons_->error() << func->name() << std::endl;\n\t\t\t}\n\t\t}\n\n\t\treset_stack();\n\t}\n\n\ttemplate<typename TOp>\n\trequires BinaryOperator<TOp, floating_value_type, floating_value_type, floating_value_type>\n\tinline void binary_op(TOp op)\n\t{\n\t\ttry\n\t\t{\n\t\t\tauto l = peek(0), r = peek(1);\n\n\t\t\tauto right = get_number_promoted(l);\n\n\t\t\tauto left = get_number_promoted(r);\n\n\t\t\tauto ret = op(left, right);\n\n\t\t\tif (std::holds_alternative<floating_value_type>(l) ||\n\t\t\t\tstd::holds_alternative<floating_value_type>(r))\n\t\t\t{\n\t\t\t\tpop_two_and_push(ret);\n\t\t\t}\n\t\t\telse if (std::holds_alternative<integer_value_type>(l) ||\n\t\t\t\t\t std::holds_alternative<integer_value_type>(r))\n\t\t\t{\n\t\t\t\tpop_two_and_push(static_cast<integer_value_type>(ret));\n\t\t\t}\n\t\t\telse if (std::holds_alternative<boolean_value_type>(l) ||\n\t\t\t\t\t std::holds_alternative<boolean_value_type>(r))\n\t\t\t{\n\t\t\t\tpop_two_and_push(static_cast<scanning::boolean_literal_type>(ret));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tpop_two_and_push(\n\t\t\t\t\t\tstatic_cast<integer_value_type>(ret)); // cannot combine for the sake of the rules of type promoting\n\t\t\t}\n\t\t}\n\t\tcatch (const std::exception& e)\n\t\t{\n\t\t\tthis->runtime_error(\"Invalid operands for binary operator: {}\", e.what());\n\t\t\tthrow e;\n\t\t}\n\t}\n\n\ttemplate<typename TOp>\n\trequires BinaryOperator<TOp, object_raw_pointer, string_object_raw_pointer, string_object_raw_pointer>\n\tinline void binary_op(TOp op)\n\t{\n\t\ttry\n\t\t{\n\t\t\tauto right = get_string(peek(0));\n\t\t\tauto left = get_string(peek(1));\n\n\t\t\tpop_two_and_push(op(left, right));\n\t\t}\n\t\tcatch (const std::exception& e)\n\t\t{\n\t\t\tthis->runtime_error(\"Invalid operands for binary operator: {}\", e.what());\n\t\t\tthrow e;\n\t\t}\n\t}\n\n\t// for comparing, whose op returns bool value\n\ttemplate<typename TOp>\n\trequires BinaryOperator<TOp, bool, floating_value_type, floating_value_type>\n\tinline void binary_op(TOp op)\n\t{\n\t\ttry\n\t\t{\n\t\t\tauto right = get_number_promoted(peek(0));\n\t\t\tauto left = get_number_promoted(peek(1));\n\n\t\t\tpop_two_and_push(op(left, right));\n\t\t}\n\t\tcatch (const std::exception& e)\n\t\t{\n\t\t\tthis->runtime_error(\"Invalid operands for binary operator: {}\", e.what());\n\t\t\tthrow e;\n\t\t}\n\t}\n\n\ttemplate<typename TOp>\n\trequires BinaryOperator<TOp, bool, string_object_raw_pointer, string_object_raw_pointer>\n\tinline void binary_op(TOp op)\n\t{\n\t\ttry\n\t\t{\n\t\t\tauto right = get_string(peek(0));\n\t\t\tauto left = get_string(peek(1));\n\n\t\t\tpop_two_and_push(op(left, right));\n\t\t}\n\t\tcatch (const std::exception& e)\n\t\t{\n\t\t\tthis->runtime_error(\"Invalid operands for binary operator: {}\", e.what());\n\t\t\tthrow e;\n\t\t}\n\t}\n\n\n\tvoid call_value(const value& val, size_t arg_count);\n\n\tvoid call(closure_object_raw_pointer closure, size_t arg_count);\n\n\tbool is_false(const value& val);\n\n\t[[maybe_unused]] bool is_true(const value& val)\n\t{\n\t\treturn !is_false(val);\n\t}\n\n\t// stack modification\n\tvoid reset_stack();\n\n\n\ttemplate<object_pointer T>\n\tT peek_object(size_t offset = 0)\n\t{\n\t\treturn std::visit([](auto&& val) -> T\n\t\t{\n\t\t\tusing TV = std::decay_t<decltype(val)>;\n\t\t\tif constexpr (std::is_same_v<TV, object_raw_pointer>)\n\t\t\t{\n\t\t\t\tif (auto func = dynamic_cast<T>(val);func)\n\t\t\t\t{\n\t\t\t\t\treturn func;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tthrow invalid_value{ val };\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tthrow invalid_value{ val };\n\t\t\t}\n\t\t}, peek(offset));\n\t}\n\n\tvalue peek(size_t offset = 0);\n\n\tvalue pop();\n\n\tvoid push(const value& val);\n\n\tinline void pop_two_and_push(const value& val);\n\t//\n\n\t// instruction reading\n\tvalue next_constant();\n\n\tstd::string next_variable_name();\n\n\tchunk::code_type next_code();\n\n\tvalue& slot_at(const call_frame& frame, size_t slot);\n\n\tupvalue_object_raw_pointer capture_upvalue(value* val, index_type stack_index);\n\n\tvoid close_upvalues(index_type last);\n\n\t// call frame\n\n\tcall_frame& top_call_frame()\n\t{\n\t\treturn *call_frames_.rbegin();\n\t}\n\n\tvoid push_call_frame(closure_object_raw_pointer closure, chunk::iterator_type ip, size_t stack_offset)\n\t{\n\t\tcall_frames_.emplace_back(closure, ip, stack_offset);\n\t}\n\n\tvoid pop_call_frame()\n\t{\n\t\tcall_frames_.pop_back();\n\t}\n\n\t//\n\n\t// method\n\tbool bind_method(class_object_raw_pointer class_obj, resolving::function_id_type id);\n\n\tbool bind_method(instance_object_raw_pointer class_obj, resolving::function_id_type id);\n\n\tstd::shared_ptr<object_heap> heap_{};\n\n\tvalue_list_type stack_{};\n\n\tglobal_table_type globals_{};\n\n\tfunction_table_type functions_{};\n\n\tcall_frame_list_type call_frames_{};\n\n\tstd::map<index_type, upvalue_object_raw_pointer> open_upvalues_{}; // it should be ordered\n\n\tmutable helper::console* cons_{ nullptr };\n};\n\n\n}\n", "meta": {"hexsha": "1c8d55d1c94d4303f0aa3efe5c3d9a6665c29e27", "size": 8690, "ext": "h", "lang": "C", "max_stars_repo_path": "interpreter/include/interpreter/vm/vm.h", "max_stars_repo_name": "SmartPolarBear/clox", "max_stars_repo_head_hexsha": "e5d4b890f480c7ee6cf2fd74f8167634ea49fa9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2021-07-02T15:49:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T13:06:24.000Z", "max_issues_repo_path": "interpreter/include/interpreter/vm/vm.h", "max_issues_repo_name": "SmartPolarBear/clox", "max_issues_repo_head_hexsha": "e5d4b890f480c7ee6cf2fd74f8167634ea49fa9c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-09T16:21:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-09T16:21:47.000Z", "max_forks_repo_path": "interpreter/include/interpreter/vm/vm.h", "max_forks_repo_name": "SmartPolarBear/clox", "max_forks_repo_head_hexsha": "e5d4b890f480c7ee6cf2fd74f8167634ea49fa9c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-10-15T10:14:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-15T10:14:06.000Z", "avg_line_length": 23.8082191781, "max_line_length": 115, "alphanum_fraction": 0.7075949367, "num_tokens": 2220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06187598572364272, "lm_q2_score": 0.01717671127632688, "lm_q1q2_score": 0.0010628259417131349}}
{"text": "#pragma once\n#include \"utility/types.h\"\n#include \"utility/c++std/optional.h\"\n#include <gsl/gsl>\n#include <vector>\n#include <string>\n\nnamespace cws80 {\n\nenum class FileChooserMode {\n    Open,\n    Save,\n};\n\nstruct FileChooserFilter {\n    const char *name;\n    std::vector<const char *> patterns;\n};\n\nclass NativeUI {\npublic:\n    virtual ~NativeUI() {}\n\n    static NativeUI *create();\n\n    virtual std::string choose_file(gsl::span<const FileChooserFilter> filters, const std::string &directory, const std::string &title, FileChooserMode mode) = 0;\n    virtual cxx::optional<std::string> edit_line(const std::string &title, const std::string &initial_value) = 0;\n    virtual uint select_by_menu(gsl::span<const std::string> choices, uint initial_selection) = 0;\n};\n\n}  // namespace cws80\n", "meta": {"hexsha": "2b714afcea3553b4eb8b877e7c849e7efc375bf8", "size": 785, "ext": "h", "lang": "C", "max_stars_repo_path": "sources/ui/detail/ui_helpers_native.h", "max_stars_repo_name": "jpcima/cws80", "max_stars_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-05-20T19:27:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-03T04:21:53.000Z", "max_issues_repo_path": "sources/ui/detail/ui_helpers_native.h", "max_issues_repo_name": "jpcima/cws80", "max_issues_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-05-21T12:56:22.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-23T21:33:33.000Z", "max_forks_repo_path": "sources/ui/detail/ui_helpers_native.h", "max_forks_repo_name": "jpcima/cws80", "max_forks_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.53125, "max_line_length": 162, "alphanum_fraction": 0.7070063694, "num_tokens": 199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.03846619422289417, "lm_q2_score": 0.027585282226789992, "lm_q1q2_score": 0.0010611008238290544}}
{"text": "#pragma once\n//=============================================================================\n// EXTERNAL DECLARATIONS\n//=============================================================================\n#include \"Core/Components/IComponentInterface.h\"\n#include \"Core/Components/IdType.h\"\n#include <memory>\n#include <gsl/span>\n\nnamespace engine\n{\n\t\n//=============================================================================\n// FORWARD DECLARATIONS\n//=============================================================================\nclass IGameObject;\nusing GameObjectRef = std::shared_ptr<IGameObject>;\nusing GameObjectWeakRef = std::weak_ptr<IGameObject>;\n\n//=============================================================================\n// INTERFACE IComponent\n//=============================================================================\nclass IComponent\n{\npublic:\n\tvirtual ~IComponent() {}\n\npublic:\n\tvirtual gsl::span<IdType> interfaces() = 0;\n\tvirtual void onAttached(const GameObjectRef &iGameObject) = 0;\n\tvirtual void onDetached(const GameObjectRef &iGameObject) = 0;\n};\n\n} // namespace engine\n", "meta": {"hexsha": "4a607d4b5bc5727b10074e047a626e6f4e916e63", "size": 1098, "ext": "h", "lang": "C", "max_stars_repo_path": "Core/Components/IComponent.h", "max_stars_repo_name": "gaspardpetit/INF740-GameEngine", "max_stars_repo_head_hexsha": "075b6563204fb3d1cf7531599f30dd296c2c9239", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Core/Components/IComponent.h", "max_issues_repo_name": "gaspardpetit/INF740-GameEngine", "max_issues_repo_head_hexsha": "075b6563204fb3d1cf7531599f30dd296c2c9239", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Core/Components/IComponent.h", "max_forks_repo_name": "gaspardpetit/INF740-GameEngine", "max_forks_repo_head_hexsha": "075b6563204fb3d1cf7531599f30dd296c2c9239", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-09-25T22:24:16.000Z", "max_forks_repo_forks_event_max_datetime": "2015-09-25T22:24:16.000Z", "avg_line_length": 31.3714285714, "max_line_length": 79, "alphanum_fraction": 0.4307832423, "num_tokens": 165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.03846618981375452, "lm_q2_score": 0.027585284924857807, "lm_q1q2_score": 0.0010611008059860814}}
{"text": "#ifndef PCH_H\n#define PCH_H\n#pragma once\n// add tat ca cac cai thu vien, ham thuong xuyen dung trong suot chuong trinh\n#include <fmt/format.h>\n#include <QtCore/QObject>\n#include <QtSql/QtSql>\n#include <any>\n#include <gsl/gsl>\n#include <memory>\n#include <optional>\n#include \"common.inl\"\n#include \"database.inl\"\n#include \"macros.inl\"\n#endif  // !PCH_H\n", "meta": {"hexsha": "799cd6f05df9c68dd634580dfe2a2b43e832833b", "size": 350, "ext": "h", "lang": "C", "max_stars_repo_path": "electric-bill-management-system/pch.h", "max_stars_repo_name": "philong6297/electric-bill-management-system", "max_stars_repo_head_hexsha": "b82d14dc22b8fd18dda7a79989785bc788f1370b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "electric-bill-management-system/pch.h", "max_issues_repo_name": "philong6297/electric-bill-management-system", "max_issues_repo_head_hexsha": "b82d14dc22b8fd18dda7a79989785bc788f1370b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "electric-bill-management-system/pch.h", "max_forks_repo_name": "philong6297/electric-bill-management-system", "max_forks_repo_head_hexsha": "b82d14dc22b8fd18dda7a79989785bc788f1370b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.875, "max_line_length": 77, "alphanum_fraction": 0.7314285714, "num_tokens": 103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.04742587452393617, "lm_q2_score": 0.022286183022885705, "lm_q1q2_score": 0.001056941719660854}}
{"text": "#pragma once\n\n#include \"halley_gl.h\"\n#include <gsl/gsl>\n\nnamespace Halley\n{\n\tclass GLBuffer\n\t{\n\tpublic:\n\t\tGLBuffer();\n\t\t~GLBuffer();\n\n\t\tvoid bind();\n\t\tvoid bindToTarget(GLuint index);\n\t\tvoid init(GLenum target, GLenum usage = GL_STREAM_DRAW);\n\t\tvoid setData(gsl::span<const gsl::byte> data);\n\t\tsize_t getSize() const;\n\n\tprivate:\n\t\tGLenum target = 0;\n\t\tGLenum usage = 0;\n        GLuint name = 0;\n\t\tsize_t capacity = 0;\n\t\tsize_t size = 0;\n\t};\n}\n", "meta": {"hexsha": "7fdcaefdc7d3b20c4604dd3c3c092f4fba72524f", "size": 443, "ext": "h", "lang": "C", "max_stars_repo_path": "src/plugins/opengl/src/gl_buffer.h", "max_stars_repo_name": "sunhay/halley", "max_stars_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3262.0, "max_stars_repo_stars_event_min_datetime": "2016-04-10T15:24:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:47:08.000Z", "max_issues_repo_path": "src/plugins/opengl/src/gl_buffer.h", "max_issues_repo_name": "sunhay/halley", "max_issues_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 53.0, "max_issues_repo_issues_event_min_datetime": "2016-10-09T16:25:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-10T13:52:37.000Z", "max_forks_repo_path": "src/plugins/opengl/src/gl_buffer.h", "max_forks_repo_name": "sunhay/halley", "max_forks_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 193.0, "max_forks_repo_forks_event_min_datetime": "2017-10-23T06:08:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T12:59:58.000Z", "avg_line_length": 15.8214285714, "max_line_length": 58, "alphanum_fraction": 0.6568848758, "num_tokens": 132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.0488577786221749, "lm_q2_score": 0.02161533154151352, "lm_q1q2_score": 0.001056077083300182}}
{"text": "#pragma once\n\n#include <string_view>\n#include <gsl/span>\n\nnamespace kab_advent {\n\tauto day(gsl::span<std::string_view const> args) -> int;\n}", "meta": {"hexsha": "733c19fe53d22bffa2454a13a5cd861af00ae4c6", "size": 140, "ext": "h", "lang": "C", "max_stars_repo_path": "src/day.h", "max_stars_repo_name": "KABoissonneault/AdventOfCode2017", "max_stars_repo_head_hexsha": "204da8c589ed6290b919cc23d1cfbe083b61bbc4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/day.h", "max_issues_repo_name": "KABoissonneault/AdventOfCode2017", "max_issues_repo_head_hexsha": "204da8c589ed6290b919cc23d1cfbe083b61bbc4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/day.h", "max_forks_repo_name": "KABoissonneault/AdventOfCode2017", "max_forks_repo_head_hexsha": "204da8c589ed6290b919cc23d1cfbe083b61bbc4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.5, "max_line_length": 57, "alphanum_fraction": 0.7214285714, "num_tokens": 37, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.05033062832405111, "lm_q2_score": 0.020964243150176542, "lm_q1q2_score": 0.0010551435300865698}}
{"text": "#pragma once\n\n#include <errno.h>  // errno\n#include <fcntl.h>  // open, write\n#include <unistd.h> // getpid\n#include <sstream>\n#include <boost/filesystem.hpp>\n#include <gsl/gsl_util>\n#include \"do_persistence.h\"\n#include \"error_macros.h\"\n\n// RAII wrapper for creating, writing and deleting the file that will\n// contain the port number for the REST interface.\nclass RestPortAdvertiser\n{\npublic:\n    RestPortAdvertiser(uint16_t port)\n    {\n        // We cannot remove the port file on shutdown because we have already dropped permissions.\n        // Clean it up now when we are still running as root.\n        _DeleteOlderPortFiles();\n\n        std::stringstream ss;\n        ss << docli::GetRuntimeDirectory() << '/' << _restPortFileNamePrefix << '.' << getpid();\n        _outFilePath = ss.str();\n\n        // If file already exists, it is truncated. Probably from an old instance that terminated abnormally.\n        // Allow file to only be read by others.\n        int fd = open(_outFilePath.data(), O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IRGRP | S_IROTH);\n        if (fd == -1)\n        {\n            THROW_HR_MSG(E_FAIL, \"Failed to open file %s, errno: %d\", _outFilePath.data(), errno);\n        }\n\n        try\n        {\n            const auto writeStr = std::to_string(port) + '\\n';\n            const auto cbWrite = gsl::narrow_cast<ssize_t>(writeStr.size() * sizeof(char));\n\n            const ssize_t written = write(fd, writeStr.data(), cbWrite);\n            if (written != cbWrite)\n            {\n                THROW_HR_MSG(E_FAIL, \"Failed to write port, written: %zd, errno: %d\", written, errno);\n            }\n        }\n        catch (...)\n        {\n            (void)close(fd);\n            throw;\n        }\n        (void)close(fd);\n    }\n\n    const std::string& OutFilePath() const { return _outFilePath; }\n\nprivate:\n    void _DeleteOlderPortFiles() try\n    {\n        auto& runtimeDirectory = docli::GetRuntimeDirectory();\n        for (boost::filesystem::directory_iterator itr(runtimeDirectory); itr != boost::filesystem::directory_iterator(); ++itr)\n        {\n            auto& dirEntry = itr->path();\n            if (dirEntry.filename().string().find(_restPortFileNamePrefix) != std::string::npos)\n            {\n                boost::system::error_code ec;\n                boost::filesystem::remove(dirEntry, ec);\n                if (ec)\n                {\n                    DoLogWarning(\"Failed to delete old port file (%d, %s) %s\", ec.value(), ec.message().data(), dirEntry.string().data());\n                }\n            }\n        }\n    } CATCH_LOG()\n\n    std::string _outFilePath;\n    static constexpr const char* const _restPortFileNamePrefix = \"restport\";\n};\n", "meta": {"hexsha": "3767db9ab52f65cb9dd1f683534d25f6e42bd81e", "size": 2677, "ext": "h", "lang": "C", "max_stars_repo_path": "client-lite/src/ipc/rest_port_advertiser.h", "max_stars_repo_name": "QPC-database/do-client", "max_stars_repo_head_hexsha": "8966861204e09961f0db33728e500cd7346cd5dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-06T14:12:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T14:12:34.000Z", "max_issues_repo_path": "client-lite/src/ipc/rest_port_advertiser.h", "max_issues_repo_name": "QPC-database/do-client", "max_issues_repo_head_hexsha": "8966861204e09961f0db33728e500cd7346cd5dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "client-lite/src/ipc/rest_port_advertiser.h", "max_forks_repo_name": "QPC-database/do-client", "max_forks_repo_head_hexsha": "8966861204e09961f0db33728e500cd7346cd5dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3205128205, "max_line_length": 138, "alphanum_fraction": 0.5864774001, "num_tokens": 624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.05419872524007487, "lm_q2_score": 0.019419350097770946, "lm_q1q2_score": 0.0010525040202899085}}
{"text": "/*\n *     Copyright 2021-Present Couchbase, Inc.\n *\n *   Use of this software is governed by the Business Source License included\n *   in the file licenses/BSL-Couchbase.txt.  As of the Change Date specified\n *   in that file, in accordance with the Business Source License, use of this\n *   software will be governed by the Apache License, Version 2.0, included in\n *   the file licenses/APL2.txt.\n */\n#pragma once\n#define MEMCACHED_ENGINE_H\n\n#include <sys/types.h>\n#include <functional>\n#include <memory>\n#include <string_view>\n#include <unordered_set>\n#include <utility>\n\n#include <gsl/gsl>\n#include <optional>\n\n#include <memcached/visibility.h>\n\n#include \"memcached/collections.h\"\n#include \"memcached/engine_common.h\"\n#include \"memcached/thread_pool_config.h\"\n#include \"memcached/types.h\"\n#include \"memcached/vbucket.h\"\n\nnamespace cb::durability {\nclass Requirements;\n} // namespace cb::durability\n\nnamespace cb::mcbp {\nclass Request;\n} // namespace cb::mcbp\n\nnamespace cb::prometheus {\nenum class Cardinality;\n} // namespace cb::prometheus\n\nclass BucketStatCollector;\nclass StatCollector;\n\n/*! \\mainpage memcached public API\n *\n * \\section intro_sec Introduction\n *\n * The memcached project provides an API for providing engines as well\n * as data definitions for those implementing the protocol in C.  This\n * documentation will explain both to you.\n *\n * \\section docs_sec API Documentation\n *\n * Jump right into <a href=\"modules.html\">the modules docs</a> to get started.\n *\n * \\example default_engine.cc\n */\n\n/**\n * \\defgroup Engine Storage Engine API\n * \\defgroup Protex Protocol Extension API\n * \\defgroup Protocol Binary Protocol Structures\n *\n * \\addtogroup Engine\n * @{\n *\n * Most interesting here is to implement engine_interface_v1 for your\n * engine.\n */\n\nstruct DocKey;\nstruct ServerBucketIface;\nstruct ServerCoreIface;\nstruct ServerCallbackIface;\nstruct ServerLogIface;\nstruct ServerCookieIface;\nstruct ServerDocumentIface;\nunion protocol_binary_request_header;\n\nstruct ServerApi {\n    ServerCoreIface* core = nullptr;\n    ServerCallbackIface* callback = nullptr;\n    ServerLogIface* log = nullptr;\n    ServerCookieIface* cookie = nullptr;\n    ServerDocumentIface* document = nullptr;\n    ServerBucketIface* bucket = nullptr;\n};\n\nusing GET_SERVER_API = ServerApi* (*)();\n\nnamespace cb {\nusing EngineErrorItemPair = std::pair<cb::engine_errc, cb::unique_item_ptr>;\n\nusing EngineErrorMetadataPair = std::pair<engine_errc, item_info>;\n\nenum class StoreIfStatus {\n    Continue,\n    Fail,\n    GetItemInfo // please get me the item_info\n};\n\nusing StoreIfPredicate = std::function<StoreIfStatus(\n        const std::optional<item_info>&, cb::vbucket_info)>;\n\nstruct EngineErrorCasPair {\n    engine_errc status;\n    uint64_t cas;\n};\n\n/// Result of getVBucketHlcNow()\nstruct HlcTime {\n    enum class Mode { Real, Logical };\n\n    /// Seconds since Unix epoch.\n    std::chrono::seconds now;\n    Mode mode;\n};\n} // namespace cb\n\n/**\n * The different compression modes that a bucket supports\n */\nenum class BucketCompressionMode : uint8_t {\n    Off,     //Data will be stored as uncompressed\n    Passive, //Data will be stored as provided by the client\n    Active   //Bucket will actively try to compress stored\n             //data\n};\n\n/* The default minimum compression ratio */\nstatic const float default_min_compression_ratio = 1.2f;\n\n/* The default maximum size for a value */\nstatic const size_t default_max_item_size = 20 * 1024 * 1024;\n\nnamespace cb::engine {\n/**\n * Definition of the features that an engine can support\n */\nenum class Feature : uint16_t {\n    Collections = 1,\n};\n\nusing FeatureSet = std::unordered_set<Feature>;\n} // namespace cb::engine\n\nnamespace std {\ntemplate <>\nstruct hash<cb::engine::Feature> {\npublic:\n    size_t operator()(const cb::engine::Feature& f) const {\n        return static_cast<size_t>(f);\n    }\n};\n} // namespace std\n\n/**\n * Definition of the first version of the engine interface\n */\nstruct MEMCACHED_PUBLIC_CLASS EngineIface {\n    virtual ~EngineIface() = default;\n\n    /**\n     * Initialize an engine instance.\n     * This is called *after* creation, but before the engine may be used.\n     *\n     * @param handle the engine handle\n     * @param config_str configuration this engine needs to initialize itself.\n     */\n    virtual cb::engine_errc initialize(const char* config_str) = 0;\n\n    /**\n     * Tear down this engine.\n     *\n     * @param force the flag indicating the force shutdown or not.\n     */\n    virtual void destroy(bool force) = 0;\n\n    /// Callback that a cookie will be disconnected\n    virtual void disconnect(gsl::not_null<const void*> cookie){};\n\n    /**\n     * Initiate the bucket shutdown logic (disconnect clients etc)\n     */\n    virtual void initiate_shutdown() {\n        // empty\n    }\n\n    // Set the number or reader threads\n    virtual void set_num_reader_threads(ThreadPoolConfig::ThreadCount num) {\n        // ignored\n    }\n\n    // Set the number or writer threads\n    virtual void set_num_writer_threads(ThreadPoolConfig::ThreadCount num) {\n        // ignored\n    }\n\n    // Set the number of storage threads\n    virtual void set_num_storage_threads(\n            ThreadPoolConfig::StorageThreadCount num) {\n        // ignored\n    }\n\n    /**\n     * Request the engine to cancel all of the ongoing requests which\n     * may have cookies in an ewouldblock state.\n     *\n     * This method is to removed in CC when we'll tighten the logic for\n     * bucket deletion to use the following logic:\n     *\n     * 1) Stop any new requests into the engine.\n     * 2) Tell the engine to complete (cancel) anything currently in-flight\n     *    (this notification holds a write lock to the engine so it won't\n     *    race with any front end threads)\n     * 3) wait for in-flight ops (i.e. step B) to finish then delete bucket.\n     *\n     * In Mad-Hatter initiate_shutdown may race with all of the frontend\n     * worker threads, and could lead to operations being added after we've\n     * inspected the vbucket. To work around that problem this new method\n     * was introduced and will be called multiple times during bucket\n     * deletion to work around potential race situations.\n     */\n    virtual void cancel_all_operations_in_ewb_state() {\n        // empty\n    }\n\n    /*\n     * Item operations.\n     */\n\n    /**\n     * Allocate an item (extended API)\n     *\n     * @param cookie The cookie provided by the frontend\n     * @param key the item's key\n     * @param nbytes the number of bytes that will make up the\n     *               value of this item.\n     * @param priv_nbytes The number of bytes in nbytes containing\n     *                    system data (and may exceed the item limit).\n     * @param flags the item's flags\n     * @param exptime the maximum lifetime of this item\n     * @param vbucket virtual bucket to request allocation from\n     * @return pair containing the item and the items information\n     * @thows cb::engine_error with:\n     *\n     *   * `cb::engine_errc::no_bucket` The client is bound to the dummy\n     *                                  `no bucket` which don't allow\n     *                                  allocations.\n     *\n     *   * `cb::engine_errc::no_memory` The bucket is full\n     *\n     *   * `cb::engine_errc::too_big` The requested memory exceeds the\n     *                                limit set for items in the bucket.\n     *\n     *   * `cb::engine_errc::disconnect` The client should be disconnected\n     *\n     *   * `cb::engine_errc::not_my_vbucket` The requested vbucket belongs\n     *                                       to someone else\n     *\n     *   * `cb::engine_errc::temporary_failure` Temporary failure, the\n     *                                          _client_ should try again\n     *\n     *   * `cb::engine_errc::too_busy` Too busy to serve the request,\n     *                                 back off and try again.\n     */\n    virtual std::pair<cb::unique_item_ptr, item_info> allocateItem(\n            gsl::not_null<const void*> cookie,\n            const DocKey& key,\n            size_t nbytes,\n            size_t priv_nbytes,\n            int flags,\n            rel_time_t exptime,\n            uint8_t datatype,\n            Vbid vbucket) = 0;\n\n    /**\n     * Remove an item.\n     *\n     * @param cookie The cookie provided by the frontend\n     * @param key the key identifying the item to be removed\n     * @param cas The cas to value to use for delete (or 0 as wildcard)\n     * @param vbucket the virtual bucket id\n     * @param durability the durability specifier for the command\n     * @param mut_info On a successful remove write the mutation details to\n     *                 this address.\n     *\n     * @return cb::engine_errc::success if all goes well\n     */\n    virtual cb::engine_errc remove(\n            gsl::not_null<const void*> cookie,\n            const DocKey& key,\n            uint64_t& cas,\n            Vbid vbucket,\n            const std::optional<cb::durability::Requirements>& durability,\n            mutation_descr_t& mut_info) = 0;\n\n    /**\n     * Indicate that a caller who received an item no longer needs\n     * it.\n     *\n     * @param item the item to be released\n     */\n    virtual void release(gsl::not_null<ItemIface*> item) = 0;\n\n    /**\n     * Retrieve an item.\n     *\n     * @param cookie The cookie provided by the frontend\n     * @param item output variable that will receive the located item\n     * @param key the key to look up\n     * @param vbucket the virtual bucket id\n     * @param documentStateFilter The document to return must be in any of\n     *                            of these states. (If `Alive` is set, return\n     *                            KEY_ENOENT if the document in the engine\n     *                            is in another state)\n     *\n     * @return cb::engine_errc::success if all goes well\n     */\n    virtual cb::EngineErrorItemPair get(gsl::not_null<const void*> cookie,\n                                        const DocKey& key,\n                                        Vbid vbucket,\n                                        DocStateFilter documentStateFilter) = 0;\n\n    /**\n     * Optionally retrieve an item. Only non-deleted items may be fetched\n     * through this interface (Documents in deleted state may be evicted\n     * from memory and we don't want to go to disk in order to fetch these)\n     *\n     * @param cookie The cookie provided by the frontend\n     * @param key the key to look up\n     * @param vbucket the virtual bucket id\n     * @param filter callback filter to see if the item should be returned\n     *               or not. If filter returns false the item should be\n     *               skipped.\n     *               Note: the filter is applied only to the *metadata* of the\n     *               item_info - i.e. the `value` should not be expected to be\n     *               present when filter is invoked.\n     * @return A pair of the error code and (optionally) the item\n     */\n    virtual cb::EngineErrorItemPair get_if(\n            gsl::not_null<const void*> cookie,\n            const DocKey& key,\n            Vbid vbucket,\n            std::function<bool(const item_info&)> filter) = 0;\n\n    /**\n     * Retrieve metadata for a given item.\n     *\n     * @param cookie The cookie provided by the frontend\n     * @param key the key to look up\n     * @param vbucket the virtual bucket id\n     *\n     * @return  Pair (cb::engine_errc::success, Metadata) if all goes well\n     */\n    virtual cb::EngineErrorMetadataPair get_meta(\n            gsl::not_null<const void*> cookie,\n            const DocKey& key,\n            Vbid vbucket) = 0;\n\n    /**\n     * Lock and Retrieve an item.\n     *\n     * @param cookie The cookie provided by the frontend\n     * @param key the key to look up\n     * @param vbucket the virtual bucket id\n     * @param lock_timeout the number of seconds to hold the lock\n     *                     (0 == use the engines default lock time)\n     *\n     * @return A pair of the error code and (optionally) the item\n     */\n    virtual cb::EngineErrorItemPair get_locked(\n            gsl::not_null<const void*> cookie,\n            const DocKey& key,\n            Vbid vbucket,\n            uint32_t lock_timeout) = 0;\n\n    /**\n     * Unlock an item.\n     *\n     * @param cookie The cookie provided by the frontend\n     * @param key the key to look up\n     * @param vbucket the virtual bucket id\n     * @param cas the cas value for the locked item\n     *\n     * @return cb::engine_errc::success if all goes well\n     */\n    virtual cb::engine_errc unlock(gsl::not_null<const void*> cookie,\n                                   const DocKey& key,\n                                   Vbid vbucket,\n                                   uint64_t cas) = 0;\n\n    /**\n     * Get and update the expiry time for the document\n     *\n     * @param cookie The cookie provided by the frontend\n     * @param key the key to look up\n     * @param vbucket the virtual bucket id\n     * @param expirytime the new expiry time for the object\n     * @param durability An optional durability requirement\n     * @return A pair of the error code and (optionally) the item\n     */\n    virtual cb::EngineErrorItemPair get_and_touch(\n            gsl::not_null<const void*> cookie,\n            const DocKey& key,\n            Vbid vbucket,\n            uint32_t expirytime,\n            const std::optional<cb::durability::Requirements>& durability) = 0;\n\n    /**\n     * Store an item into the underlying engine with the given\n     * state. If the DocumentState is set to DocumentState::Deleted\n     * the document shall not be returned unless explicitly asked for\n     * documents in that state, and the underlying engine may choose to\n     * purge it whenever it please.\n     *\n     * @param cookie The cookie provided by the frontend\n     * @param item the item to store\n     * @param cas the CAS value for conditional sets\n     * @param semantics the semantics of the store operation\n     * @param durability An optional durability requirement\n     * @param document_state The state the document should have after\n     *                       the update\n     * @param preserveTtl if set to true the existing documents TTL should\n     *                    be used.\n     *\n     * @return cb::engine_errc::success if all goes well\n     */\n    virtual cb::engine_errc store(\n            gsl::not_null<const void*> cookie,\n            gsl::not_null<ItemIface*> item,\n            uint64_t& cas,\n            StoreSemantics semantics,\n            const std::optional<cb::durability::Requirements>& durability,\n            DocumentState document_state,\n            bool preserveTtl) = 0;\n\n    /**\n     * Store an item into the underlying engine with the given\n     * state only if the predicate argument returns true when called against an\n     * existing item.\n     *\n     * Optional interface; not supported by all engines.\n     *\n     * @param cookie The cookie provided by the frontend\n     * @param item the item to store\n     * @param cas the CAS value for conditional sets\n     * @param semantics the semantics of the store operation\n     * @param predicate a function that will be called from the engine the\n     *                  result of which determines how the store behaves.\n     *                  The function is given any existing item's item_info (as\n     *                  a std::optional) and a cb::vbucket_info object. In the\n     *                  case that the optional item_info is not initialised the\n     *                  function can return cb::StoreIfStatus::GetInfo to\n     *                  request that the engine tries to get the item_info, the\n     *                  engine may ignore this return code if it knows better\n     *                  i.e. a memory only engine and no item_info can be\n     *                  fetched. The function can also return ::Fail if it\n     *                  wishes to fail the store_if (returning predicate_failed)\n     *                  or the predicate can return ::Continue and the rest of\n     *                  the store_if will execute (and possibly fail for other\n     *                  reasons).\n     * @param durability An optional durability requirement\n     * @param document_state The state the document should have after\n     *                       the update\n     * @param preserveTtl if set to true the existing documents TTL should\n     *                    be used.\n     *\n     * @return a std::pair containing the engine_error code and new CAS\n     */\n    virtual cb::EngineErrorCasPair store_if(\n            gsl::not_null<const void*> cookie,\n            gsl::not_null<ItemIface*> item,\n            uint64_t cas,\n            StoreSemantics semantics,\n            const cb::StoreIfPredicate& predicate,\n            const std::optional<cb::durability::Requirements>& durability,\n            DocumentState document_state,\n            bool preserveTtl) {\n        return {cb::engine_errc::not_supported, 0};\n    }\n\n    /**\n     * Flush the cache.\n     *\n     * Optional interface; not supported by all engines.\n     *\n     * @param cookie The cookie provided by the frontend\n     * @return cb::engine_errc::success if all goes well\n     */\n    virtual cb::engine_errc flush(gsl::not_null<const void*> cookie) {\n        return cb::engine_errc::not_supported;\n    }\n\n    /*\n     * Statistics\n     */\n\n    /**\n     * Get statistics from the engine.\n     *\n     * @param cookie The cookie provided by the frontend\n     * @param key optional argument to stats\n     * @param value optional value for the given stat group\n     * @param add_stat callback to feed results to the output\n     *\n     * @return cb::engine_errc::success if all goes well\n     */\n    virtual cb::engine_errc get_stats(gsl::not_null<const void*> cookie,\n                                      std::string_view key,\n                                      std::string_view value,\n                                      const AddStatFn& add_stat) = 0;\n\n    /**\n     * Get statistics for Prometheus exposition from the engine.\n     * Some engines may not support this.\n     *\n     * @param collector where the bucket may register stats\n     *\n     * @return cb::engine_errc::success if all goes well\n     */\n    virtual cb::engine_errc get_prometheus_stats(\n            const BucketStatCollector& collector,\n            cb::prometheus::Cardinality cardinality) {\n        return cb::engine_errc::not_supported;\n    }\n\n    /**\n     * Reset the stats.\n     *\n     * @param cookie The cookie provided by the frontend\n     */\n    virtual void reset_stats(gsl::not_null<const void*> cookie) = 0;\n\n    /**\n     * Any unknown command will be considered engine specific.\n     *\n     * @param cookie The cookie provided by the frontend\n     * @param request The request from the client\n     * @param response function to transmit data\n     *\n     * @return cb::engine_errc::success if all goes well\n     */\n    virtual cb::engine_errc unknown_command(const void* cookie,\n                                            const cb::mcbp::Request& request,\n                                            const AddResponseFn& response) {\n        return cb::engine_errc::not_supported;\n    }\n\n    /**\n     * Set the CAS id on an item.\n     */\n    virtual void item_set_cas(gsl::not_null<ItemIface*> item,\n                              uint64_t cas) = 0;\n\n    /**\n     * Set the data type on an item.\n     */\n    virtual void item_set_datatype(gsl::not_null<ItemIface*> item,\n                                   protocol_binary_datatype_t datatype) = 0;\n\n    /**\n     * Get information about an item.\n     *\n     * The loader of the module may need the pointers to the actual data within\n     * an item. Instead of having to create multiple functions to get each\n     * individual item, this function will get all of them.\n     *\n     * @param item the item to request information about\n     * @param item_info\n     * @return true if successful\n     */\n    virtual bool get_item_info(gsl::not_null<const ItemIface*> item,\n                               gsl::not_null<item_info*> item_info) = 0;\n\n    /**\n     * The set of collections related functions. May be defined optionally by\n     * the engine(s) that support them.\n     */\n    virtual cb::engine_errc set_collection_manifest(\n            gsl::not_null<const void*> cookie, std::string_view json) {\n        return cb::engine_errc::not_supported;\n    }\n\n    /**\n     * Retrieve the last manifest set using set_manifest (a JSON document)\n     */\n    virtual cb::engine_errc get_collection_manifest(\n            gsl::not_null<const void*> cookie, const AddResponseFn& response) {\n        return cb::engine_errc::not_supported;\n    }\n\n    virtual cb::EngineErrorGetCollectionIDResult get_collection_id(\n            gsl::not_null<const void*> cookie, std::string_view path) {\n        return cb::EngineErrorGetCollectionIDResult{\n                cb::engine_errc::not_supported};\n    }\n\n    virtual cb::EngineErrorGetScopeIDResult get_scope_id(\n            gsl::not_null<const void*> cookie, std::string_view path) {\n        return cb::EngineErrorGetScopeIDResult{cb::engine_errc::not_supported};\n    }\n\n    /**\n     * Get the scope for the provided key\n     *\n     * @param cookie cookie object used to identify the request\n     * @param key the key to look up\n     * @return pair with the manifest UID and if found the scope where the key\n     *              belongs.\n     */\n    virtual cb::EngineErrorGetScopeIDResult get_scope_id(\n            gsl::not_null<const void*> cookie,\n            const DocKey& key,\n            std::optional<Vbid> vbid = std::nullopt) const {\n        return cb::EngineErrorGetScopeIDResult(cb::engine_errc::not_supported);\n    }\n\n    /**\n     * Ask the engine what features it supports.\n     */\n    virtual cb::engine::FeatureSet getFeatures() = 0;\n\n    /**\n     * @returns if XATTRs are enabled for this bucket\n     */\n    virtual bool isXattrEnabled() {\n        return false;\n    }\n\n    /**\n     * Get the \"current\" time and mode of the Hybrid Logical Clock for the\n     * specified vBucket.\n     * @returns seconds since unix epoch of the HLC, along with the current\n     * HLC Mode (Real / Logical).\n     */\n    virtual cb::HlcTime getVBucketHlcNow(Vbid vbucket) = 0;\n\n    /**\n     * @returns the compression mode of the bucket\n     */\n    virtual BucketCompressionMode getCompressionMode() {\n        return BucketCompressionMode::Off;\n    }\n\n    /**\n     * @returns the maximum item size supported by the bucket\n     */\n    virtual size_t getMaxItemSize() {\n        return default_max_item_size;\n    };\n\n    /**\n     * @returns the minimum compression ratio defined in the bucket\n     */\n    virtual float getMinCompressionRatio() {\n        return default_min_compression_ratio;\n    }\n\n    /**\n     * Set a configuration parameter in the engine\n     *\n     * @param cookie The cookie identifying the request\n     * @param category The parameter category\n     * @param key The name of the parameter\n     * @param value The value for the parameter\n     * @param vbucket The vbucket specified in the request (only used for\n     *                the vbucket sub group)\n     * @return The standard engine codes\n     */\n    virtual cb::engine_errc setParameter(gsl::not_null<const void*> cookie,\n                                         EngineParamCategory category,\n                                         std::string_view key,\n                                         std::string_view value,\n                                         Vbid vbucket) {\n        return cb::engine_errc::not_supported;\n    }\n\n    /**\n     * Compact a database\n     *\n     * @param cookie The cookie identifying the request\n     * @param vbid The vbucket to compact\n     * @param purge_before_ts The timestamp to purge items before\n     * @param purge_before_seq The sequence number to purge items before\n     * @param drop_deletes Set to true if deletes should be dropped\n     * @return The standard engine codes\n     */\n    virtual cb::engine_errc compactDatabase(gsl::not_null<const void*> cookie,\n                                            Vbid vbid,\n                                            uint64_t purge_before_ts,\n                                            uint64_t purge_before_seq,\n                                            bool drop_deletes) {\n        return cb::engine_errc::not_supported;\n    }\n\n    /**\n     * Get the state of a vbucket\n     *\n     * @param cookie The cookie identifying the request\n     * @param vbid The vbucket to look up\n     * @return A pair where the first entry is one of the standard engine codes\n     *         and the second is the state when the status is success.\n     */\n    virtual std::pair<cb::engine_errc, vbucket_state_t> getVBucket(\n            gsl::not_null<const void*> cookie, Vbid vbid) {\n        return {cb::engine_errc::not_supported, vbucket_state_dead};\n    }\n\n    /**\n     * Set the state of a vbucket\n     *\n     * @param cookie The cookie identifying the request\n     * @param vbid The vbucket to update\n     * @param cas The current value used for CAS swap\n     * @param state The new vbucket state\n     * @param meta The optional meta information for the state (nullptr if\n     *             none is provided)\n     * @return The standard engine codes\n     */\n    virtual cb::engine_errc setVBucket(gsl::not_null<const void*> cookie,\n                                       Vbid vbid,\n                                       uint64_t cas,\n                                       vbucket_state_t state,\n                                       nlohmann::json* meta) {\n        return cb::engine_errc::not_supported;\n    }\n\n    /**\n     * Delete a vbucket\n     *\n     * @param cookie The cookie identifying the request\n     * @param vbid The vbucket to delete\n     * @param sync If the operation should block (return EWB and be signalled\n     *             when the operation is done) or delete in \"fire and forget\"\n     *             mode.\n     * @return The standard engine codes\n     */\n    virtual cb::engine_errc deleteVBucket(gsl::not_null<const void*> cookie,\n                                          Vbid vbid,\n                                          bool sync) {\n        return cb::engine_errc::not_supported;\n    }\n};\n\nnamespace cb {\nclass ItemDeleter {\npublic:\n    ItemDeleter() : handle(nullptr) {}\n\n    /**\n     * Create a new instance of the item deleter.\n     *\n     * @param handle_ the handle to the the engine who owns the item\n     */\n    explicit ItemDeleter(EngineIface* handle_) : handle(handle_) {\n        if (handle == nullptr) {\n            throw std::invalid_argument(\n                \"cb::ItemDeleter: engine handle cannot be nil\");\n        }\n    }\n\n    /**\n     * Create a copy constructor to allow us to use std::move of the item\n     */\n    ItemDeleter(const ItemDeleter& other) = default;\n\n    void operator()(ItemIface* item) {\n        if (handle) {\n            handle->release(item);\n        } else {\n            throw std::invalid_argument(\"cb::ItemDeleter: item attempted to be \"\n                                        \"freed by null engine handle\");\n        }\n    }\n\nprivate:\n    EngineIface* handle;\n};\n\ninline EngineErrorItemPair makeEngineErrorItemPair(cb::engine_errc err) {\n    return {err, unique_item_ptr{nullptr, ItemDeleter{}}};\n}\n\ninline EngineErrorItemPair makeEngineErrorItemPair(cb::engine_errc err,\n                                                   ItemIface* it,\n                                                   EngineIface* handle) {\n    return {err, unique_item_ptr{it, ItemDeleter{handle}}};\n}\n}\n\nstruct EngineDeletor {\n    void operator()(EngineIface* engine) {\n        engine->destroy(force);\n    }\n\n    bool force = false;\n};\n\nusing unique_engine_ptr = std::unique_ptr<EngineIface, EngineDeletor>;\n\n/**\n * @}\n */\n", "meta": {"hexsha": "a263c61ae81223aab6c49dbead144df9e936eff9", "size": 27749, "ext": "h", "lang": "C", "max_stars_repo_path": "include/memcached/engine.h", "max_stars_repo_name": "BenHuddleston/kv_engine", "max_stars_repo_head_hexsha": "78123c9aa2c2feb24b7c31eecc862bf2ed6325e4", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/memcached/engine.h", "max_issues_repo_name": "BenHuddleston/kv_engine", "max_issues_repo_head_hexsha": "78123c9aa2c2feb24b7c31eecc862bf2ed6325e4", "max_issues_repo_licenses": ["MIT", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/memcached/engine.h", "max_forks_repo_name": "BenHuddleston/kv_engine", "max_forks_repo_head_hexsha": "78123c9aa2c2feb24b7c31eecc862bf2ed6325e4", "max_forks_repo_licenses": ["MIT", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.385377943, "max_line_length": 80, "alphanum_fraction": 0.6113013082, "num_tokens": 6193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.037326886273225016, "lm_q2_score": 0.0280075223300253, "lm_q1q2_score": 0.0010454336008076644}}
{"text": "#ifndef __COMPLEARN_REALCOMPRESSOR_H\n#define __COMPLEARN_REALCOMPRESSOR_H\n\n#define COMPLEARN_REAL_COMPRESSOR_TYPE        (real_compressor_get_type ())\n#define COMPLEARN_TYPE_REAL_COMPRESSOR        (real_compressor_get_type ())\n#define COMPLEARN_REAL_COMPRESSOR(obj)        (G_TYPE_CHECK_INSTANCE_CAST ((obj), COMPLEARN_REAL_COMPRESSOR_TYPE, CompLearnRealCompressor))\n#define IS_COMPLEARN_REAL_COMPRESSOR(obj)        (G_TYPE_CHECK_INSTANCE_TYPE ((obj), COMPLEARN_REAL_COMPRESSOR_TYPE))\n#define COMPLEARN_REAL_COMPRESSOR_GET_INTERFACE(inst) (G_TYPE_INSTANCE_GET_INTERFACE((inst), COMPLEARN_REAL_COMPRESSOR_TYPE, CompLearnRealCompressorIface))\n\n#include <glib.h>\n#include <glib-object.h>\n#include <glib/garray.h>\n#include <gsl/gsl_matrix.h>\n\n#define COMPLEARN_ERROR 1\n#define COMPLEARN_ERROR_NO_COMPRESSOR_SET 100\n\ntypedef struct _CompLearnRealCompressor CompLearnRealCompressor;\ntypedef struct _CompLearnRealCompressorIface CompLearnRealCompressorIface;\n\nstruct _CompLearnRealCompressorIface {\n  GTypeInterface parent;\n\n  GString *(*compress)(CompLearnRealCompressor *self, const GString *input);\n  GString *(*decompress)(CompLearnRealCompressor *self, const GString *input);\n  GString *(*blurb)(CompLearnRealCompressor *self);\n  GString *(*canonical_extension)(CompLearnRealCompressor *self);\n  GString *(*name)(CompLearnRealCompressor *self);\n  GString *(*compressor_version)(CompLearnRealCompressor *self);\n  GString *(*binding_version)(CompLearnRealCompressor *self);\n  gboolean (*is_threadsafe)(CompLearnRealCompressor *self);\n  gboolean (*is_compressible)(CompLearnRealCompressor *self, const GString *input);\n  gboolean (*is_decompressible)(CompLearnRealCompressor *self, const GString *input);\n  gboolean (*is_just_size)(CompLearnRealCompressor *self);\n  gboolean (*is_hash_function)(CompLearnRealCompressor *self);\n  GString *(*hash)(CompLearnRealCompressor *self, const GString *input);\n  gboolean (*is_operational)(CompLearnRealCompressor *self);\n  gboolean (*is_private_property)(CompLearnRealCompressor *self, const char *propname);\n  gdouble (*compressed_size)(CompLearnRealCompressor *self, const GString *input);\n  guint64 (*window_size)(CompLearnRealCompressor *self);\n  CompLearnRealCompressor *(*clone)(CompLearnRealCompressor *self);\n};\n\nGType real_compressor_get_type(void);\n\nGString *real_compressor_compress(CompLearnRealCompressor *self,const GString *input);\nGString *real_compressor_hash(CompLearnRealCompressor *self,const GString *input);\nGString *real_compressor_decompress(CompLearnRealCompressor *self,const GString *input);\ngdouble real_compressor_compressed_size(CompLearnRealCompressor *self,const GString *input);\nGString *real_compressor_blurb(CompLearnRealCompressor *self);\nGString *real_compressor_name(CompLearnRealCompressor *self);\nGString *real_compressor_compressor_version(CompLearnRealCompressor *self);\nGString *real_compressor_binding_version(CompLearnRealCompressor *self);\ngboolean real_compressor_is_compressible(CompLearnRealCompressor *self, const GString *input);\ngboolean real_compressor_is_decompressible(CompLearnRealCompressor *self, const GString *input);\ngboolean real_compressor_is_private_property(CompLearnRealCompressor *self, const char *input);\nguint64 real_compressor_window_size(CompLearnRealCompressor *self);\ngboolean real_compressor_is_threadsafe(CompLearnRealCompressor *self);\ngboolean real_compressor_is_just_size(CompLearnRealCompressor *self);\ngboolean real_compressor_is_hash_function(CompLearnRealCompressor *self);\nGString *real_compressor_canonical_extension(CompLearnRealCompressor *rc);\ngboolean real_compressor_is_operational(CompLearnRealCompressor *self);\nCompLearnRealCompressor *real_compressor_clone(CompLearnRealCompressor *self);\n\n#define SET_DEFAULT_PROPS(groupname, clt, mobj) \\\n  do { \\\n  GParamSpec **gps, **cur; \\\n  g_assert(mobj != NULL); \\\n    if (complearn_environment_get_nameable(groupname) == NULL) { \\\n      complearn_environment_register_nameable(groupname, G_OBJECT(mobj)); \\\n      break; \\\n    } \\\n  gps =g_object_class_list_properties(G_OBJECT_CLASS(clt(mobj)), NULL); \\\n  for (cur = gps; *cur; cur += 1) { \\\n    GValue v = {0,}; \\\n    g_value_init(&v, (*cur)->value_type); \\\n    g_param_value_set_default(*cur, &v); \\\n    g_object_set_property(G_OBJECT(mobj), (*cur)->name, &v); \\\n    complearn_environment_register_property(G_OBJECT(mobj), (*cur), &v); \\\n  } } while(0)\n\n#define SET_DEFAULT_COMPRESSOR_PROPS(groupname, clt, mobj) \\\n  do { \\\n      SET_DEFAULT_PROPS(groupname, clt, mobj); \\\n    if (complearn_environment_get_nameable(groupname) == NULL) { \\\n      complearn_environment_register_compressor(mobj); \\\n    } \\\n  } while (0);\n\n#endif\n\n#define G_LOG_LEVEL_NOTICE G_LOG_LEVEL_USER_SHIFT\n#define g_notice(...) g_log(G_LOG_DOMAIN, G_LOG_LEVEL_NOTICE, __VA_ARGS__)\n\nvoid real_compressor_interface_init (gpointer g_iface, gpointer iface_data);\n", "meta": {"hexsha": "9dec49365f4fe600dd497d73b38655bd7e20367e", "size": 4855, "ext": "h", "lang": "C", "max_stars_repo_path": "src/complearn/real-compressor.h", "max_stars_repo_name": "rudi-cilibrasi/classic-complearn", "max_stars_repo_head_hexsha": "c70ac5ad7bcfe3af80a2a8f087ee6f5904820a66", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-03-14T13:52:31.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-08T11:13:03.000Z", "max_issues_repo_path": "src/complearn/real-compressor.h", "max_issues_repo_name": "rudi-cilibrasi/classic-complearn", "max_issues_repo_head_hexsha": "c70ac5ad7bcfe3af80a2a8f087ee6f5904820a66", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2016-05-10T12:56:52.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-15T18:30:04.000Z", "max_forks_repo_path": "src/complearn/real-compressor.h", "max_forks_repo_name": "rudi-cilibrasi/classic-complearn", "max_forks_repo_head_hexsha": "c70ac5ad7bcfe3af80a2a8f087ee6f5904820a66", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.5729166667, "max_line_length": 155, "alphanum_fraction": 0.805561277, "num_tokens": 1241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07585817166422973, "lm_q2_score": 0.013636837962229698, "lm_q1q2_score": 0.001034465595096105}}
{"text": "#ifndef NETWORK_CANUDPRECEIVER_H\n#define NETWORK_CANUDPRECEIVER_H\n\n\n#include <cstdint>\n#include <gsl/gsl>\n#include <QObject>\n\n#include \"tincan/canrawframe.h\"\n#include \"network/udpasyncreceiver.h\"\n\n\nnamespace network {\n\n\nclass Can_udp_receiver final : public QObject, public udp::Async_receiver\n{\n  Q_OBJECT\n\npublic:\n  Can_udp_receiver() = default;\n  Can_udp_receiver(const Can_udp_receiver&) = delete;\n  Can_udp_receiver(Can_udp_receiver&&) = delete;\n  Can_udp_receiver& operator=(const Can_udp_receiver&) = delete;\n  Can_udp_receiver& operator=(Can_udp_receiver&&) = delete;\n\n  void handle_receive(gsl::span<std::uint8_t> buffer) override;\n\nsignals:\n  void received_frame(std::uint64_t, tin::Can_raw_frame);\n};\n\n\n}  // namespace network\n\n\n#endif  // NETWORK_CANUDPRECEIVER_H\n", "meta": {"hexsha": "c8e0455aeb8649a42437bd6005a4fb5ee83ce82a", "size": 776, "ext": "h", "lang": "C", "max_stars_repo_path": "src/network/canudpreceiver.h", "max_stars_repo_name": "mwkpe/tincan", "max_stars_repo_head_hexsha": "7c47ea7fa7f43163f69c94f10dd39b56e4e95256", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2018-06-09T10:22:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T08:03:40.000Z", "max_issues_repo_path": "src/network/canudpreceiver.h", "max_issues_repo_name": "jwkpeter/tincan", "max_issues_repo_head_hexsha": "7c47ea7fa7f43163f69c94f10dd39b56e4e95256", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/network/canudpreceiver.h", "max_forks_repo_name": "jwkpeter/tincan", "max_forks_repo_head_hexsha": "7c47ea7fa7f43163f69c94f10dd39b56e4e95256", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-11-23T11:05:16.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-30T07:57:19.000Z", "avg_line_length": 20.4210526316, "max_line_length": 73, "alphanum_fraction": 0.7680412371, "num_tokens": 197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.04023794032175321, "lm_q2_score": 0.025565211928003716, "lm_q1q2_score": 0.0010286914718719868}}
{"text": "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\n#pragma once\n\n#include \"core/common/inlined_containers.h\"\n#include \"core/codegen/common/common.h\"\n#include \"core/graph/graph.h\"\n#include \"core/providers/nuphar/common/analysis/analysis.h\"\n#include <gsl/gsl>\n\nnamespace onnxruntime {\nnamespace nuphar {\n\nclass OutputAliasAnalysis : public NupharAnalysis {\n public:\n  OutputAliasAnalysis()\n      : NupharAnalysis(\"OutputAliasAnalysis\") {}\n\n  ~OutputAliasAnalysis() = default;\n\n  void Evaluate(const onnxruntime::nuphar::NupharSubgraphUnit& graph) override;\n\n  bool IsOutputNode(const onnxruntime::Node* node) const;\n\n  bool IsOutputAlias(const onnxruntime::Node* node) const;\n\n  const onnxruntime::NodeArg* SourceDefOfOutputAlias(const onnxruntime::NodeArg* node) const;\n\n private:\n  // a set for output nodes\n  std::set<NodeKey> output_nodes_;\n  // a map from an output alias to its input\n  std::map<NodeKey, const onnxruntime::NodeArg*> alias_use_defs_;\n\n  void Traverse(gsl::span<const Node* const> nodes,\n                const InlinedHashSet<std::string_view>& graph_inputs,\n                const InlinedHashSet<std::string_view>& graph_outputs);\n\n private:\n  ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(OutputAliasAnalysis);\n};\n\n}  // namespace nuphar\n}  // namespace onnxruntime\n", "meta": {"hexsha": "31c617011975e910a0f0ef423859ded2ca5c4ec1", "size": 1323, "ext": "h", "lang": "C", "max_stars_repo_path": "onnxruntime/core/providers/nuphar/common/analysis/output_alias_analysis.h", "max_stars_repo_name": "SiriusKY/onnxruntime", "max_stars_repo_head_hexsha": "3c5853dcbc9d5dda2476afa8c6105802d2b8e53d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 669.0, "max_stars_repo_stars_event_min_datetime": "2018-12-03T22:00:31.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-06T19:42:49.000Z", "max_issues_repo_path": "onnxruntime/core/providers/nuphar/common/analysis/output_alias_analysis.h", "max_issues_repo_name": "SiriusKY/onnxruntime", "max_issues_repo_head_hexsha": "3c5853dcbc9d5dda2476afa8c6105802d2b8e53d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 440.0, "max_issues_repo_issues_event_min_datetime": "2018-12-03T21:09:56.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-06T20:47:23.000Z", "max_forks_repo_path": "onnxruntime/core/providers/nuphar/common/analysis/output_alias_analysis.h", "max_forks_repo_name": "SiriusKY/onnxruntime", "max_forks_repo_head_hexsha": "3c5853dcbc9d5dda2476afa8c6105802d2b8e53d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 140.0, "max_forks_repo_forks_event_min_datetime": "2018-12-03T21:15:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-06T18:02:36.000Z", "avg_line_length": 28.7608695652, "max_line_length": 93, "alphanum_fraction": 0.7482993197, "num_tokens": 323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.05582314270540301, "lm_q2_score": 0.018264280789949214, "lm_q1q2_score": 0.0010195695529488858}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef config_27ec2780_3d0a_41f9_8a8b_0099ced77cf1_h\r\n#define config_27ec2780_3d0a_41f9_8a8b_0099ced77cf1_h\r\n\r\n#include <gslib/config.h>\r\n\r\n#define __ariel_begin__     namespace gs { namespace ariel {\r\n#define __ariel_end__       } };\r\n\r\n#if defined(ARIEL_LIB)\r\n#define ariel_export\r\n#elif defined(ARIEL_DLL)\r\n#define ariel_export __declspec(dllexport)\r\n#else\r\n#define ariel_export __declspec(dllimport)\r\n#endif\r\n\r\nenum\r\n{\r\n    render_platform_gl_20,\r\n    render_platform_gl_30,\r\n    render_platform_d3d_9,\r\n    render_platform_d3d_11,\r\n};\r\n\r\n/* select render system here. */\r\n#define select_render_platform  render_platform_d3d_11\r\n\r\n#define use_rendersys_d3d_9     (select_render_platform == render_platform_d3d_9)\r\n#define use_rendersys_d3d_11    (select_render_platform == render_platform_d3d_11)\r\n#define use_rendersys_gl_20     (select_render_platform == render_platform_gl_20)\r\n#define use_rendersys_gl_30     (select_render_platform == render_platform_gl_30)\r\n\r\n#if use_rendersys_d3d_11\r\n#include <d3d11.h>\r\n#include <dxgi.h>\r\n#endif\r\n\r\n__ariel_begin__\r\n\r\ndefine_select_type(render_device);\r\ndefine_select_type(render_context);\r\ndefine_select_type(render_resource);\r\ndefine_select_type(render_swap_chain);\r\ndefine_select_type(render_target_view);\r\ndefine_select_type(shader_resource_view);\r\ndefine_select_type(depth_stencil_view);\r\ndefine_select_type(unordered_access_view);\r\ndefine_select_type(render_blob);\r\ndefine_select_type(vertex_shader);\r\ndefine_select_type(pixel_shader);\r\ndefine_select_type(geometry_shader);\r\ndefine_select_type(compute_shader);\r\ndefine_select_type(hull_shader);\r\ndefine_select_type(domain_shader);\r\ndefine_select_type(render_include);\r\ndefine_select_type(vertex_format);\r\ndefine_select_type(vertex_format_desc);\r\ndefine_select_type(render_vertex_buffer);\r\ndefine_select_type(render_index_buffer);\r\ndefine_select_type(render_constant_buffer);\r\ndefine_select_type(render_texture1d);\r\ndefine_select_type(render_texture2d);\r\ndefine_select_type(render_texture3d);\r\ndefine_select_type(render_sampler_state);\r\ndefine_select_type(render_blend_state);\r\ndefine_select_type(render_raster_state);\r\ndefine_select_type(render_depth_state);\r\n\r\ninstall_select_type(render_platform_d3d_11, render_device, ID3D11Device);\r\ninstall_select_type(render_platform_d3d_11, render_context, ID3D11DeviceContext);\r\ninstall_select_type(render_platform_d3d_11, render_resource, ID3D11Resource);\r\ninstall_select_type(render_platform_d3d_11, render_swap_chain, IDXGISwapChain);\r\ninstall_select_type(render_platform_d3d_11, render_target_view, ID3D11RenderTargetView);\r\ninstall_select_type(render_platform_d3d_11, shader_resource_view, ID3D11ShaderResourceView);\r\ninstall_select_type(render_platform_d3d_11, depth_stencil_view, ID3D11DepthStencilView);\r\ninstall_select_type(render_platform_d3d_11, unordered_access_view, ID3D11UnorderedAccessView);\r\ninstall_select_type(render_platform_d3d_11, render_blob, ID3DBlob);\r\ninstall_select_type(render_platform_d3d_11, vertex_shader, ID3D11VertexShader);\r\ninstall_select_type(render_platform_d3d_11, pixel_shader, ID3D11PixelShader);\r\ninstall_select_type(render_platform_d3d_11, geometry_shader, ID3D11GeometryShader);\r\ninstall_select_type(render_platform_d3d_11, compute_shader, ID3D11ComputeShader);\r\ninstall_select_type(render_platform_d3d_11, hull_shader, ID3D11HullShader);\r\ninstall_select_type(render_platform_d3d_11, domain_shader, ID3D11DomainShader);\r\n\r\ninstall_select_type(render_platform_d3d_11, render_include, ID3DInclude);\r\ninstall_select_type(render_platform_d3d_11, vertex_format, ID3D11InputLayout);\r\ninstall_select_type(render_platform_d3d_11, vertex_format_desc, D3D11_INPUT_ELEMENT_DESC);\r\ninstall_select_type(render_platform_d3d_11, render_vertex_buffer, ID3D11Buffer);\r\ninstall_select_type(render_platform_d3d_11, render_index_buffer, ID3D11Buffer);\r\ninstall_select_type(render_platform_d3d_11, render_constant_buffer, ID3D11Buffer);\r\n\r\ninstall_select_type(render_platform_d3d_11, render_texture1d, ID3D11Texture1D);\r\ninstall_select_type(render_platform_d3d_11, render_texture2d, ID3D11Texture2D);\r\ninstall_select_type(render_platform_d3d_11, render_texture3d, ID3D11Texture3D);\r\ninstall_select_type(render_platform_d3d_11, render_sampler_state, ID3D11SamplerState);\r\ninstall_select_type(render_platform_d3d_11, render_blend_state, ID3D11BlendState);\r\ninstall_select_type(render_platform_d3d_11, render_raster_state, ID3D11RasterizerState);\r\ninstall_select_type(render_platform_d3d_11, render_depth_state, ID3D11DepthStencilState);\r\n\r\nconfig_select_type(select_render_platform, render_device);\r\nconfig_select_type(select_render_platform, render_context);\r\nconfig_select_type(select_render_platform, render_resource);\r\nconfig_select_type(select_render_platform, render_swap_chain);\r\nconfig_select_type(select_render_platform, render_target_view);\r\nconfig_select_type(select_render_platform, shader_resource_view);\r\nconfig_select_type(select_render_platform, depth_stencil_view);\r\nconfig_select_type(select_render_platform, unordered_access_view);\r\nconfig_select_type(select_render_platform, render_blob);\r\nconfig_select_type(select_render_platform, vertex_shader);\r\nconfig_select_type(select_render_platform, pixel_shader);\r\nconfig_select_type(select_render_platform, geometry_shader);\r\nconfig_select_type(select_render_platform, compute_shader);\r\nconfig_select_type(select_render_platform, hull_shader);\r\nconfig_select_type(select_render_platform, domain_shader);\r\nconfig_select_type(select_render_platform, render_include);\r\nconfig_select_type(select_render_platform, vertex_format);\r\nconfig_select_type(select_render_platform, render_vertex_buffer);\r\nconfig_select_type(select_render_platform, render_index_buffer);\r\nconfig_select_type(select_render_platform, render_constant_buffer);\r\nconfig_select_type(select_render_platform, render_texture1d);\r\nconfig_select_type(select_render_platform, render_texture2d);\r\nconfig_select_type(select_render_platform, render_texture3d);\r\nconfig_select_type(select_render_platform, render_sampler_state);\r\nconfig_select_type(select_render_platform, render_blend_state);\r\nconfig_select_type(select_render_platform, render_raster_state);\r\nconfig_select_type(select_render_platform, render_depth_state);\r\n\r\nenum render_option\r\n{\r\n    opt_primitive_topology,\r\n    /* more to come. */\r\n};\r\n\r\n__ariel_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "0875d9cf4bed01f45e241b743ddd16d284f836fc", "size": 7583, "ext": "h", "lang": "C", "max_stars_repo_path": "include/ariel/config.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/ariel/config.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ariel/config.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 46.237804878, "max_line_length": 95, "alphanum_fraction": 0.8418831597, "num_tokens": 1700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.04336579505484044, "lm_q2_score": 0.0233307672805304, "lm_q1q2_score": 0.0010117572723596583}}
{"text": "#pragma once\r\n#include <memory>\r\n#include <gsl/span>\r\n#include \"D3DManager.h\"\r\n\r\nnamespace vrutil\r\n{\r\n\r\nclass OverlayItem\r\n{\r\n    class OverlayItemImpl *m_impl;\r\n    OverlayItem(class OverlayItemImpl *impl);\r\n\r\npublic:\r\n    ~OverlayItem();\r\n    static std::shared_ptr<OverlayItem> Create(uint64_t handle);\r\n    void ProcessEvents();\r\n    void SetTexture(const ComPtr<ID3D11Texture2D> &texture);\r\n    void SetSharedHandle(void *handle);\r\n    void SetOverlayWidthInMeters(float meter);\r\n    void Show();\r\n    void SetMatrix34(const float *matrix34);\r\n};\r\nusing OverlayItemPtr = std::shared_ptr<OverlayItem>;\r\n\r\n} // namespace vrutil\r\n", "meta": {"hexsha": "3aab4be071c3fd1f1f0b0137df46213c5576e0da", "size": 632, "ext": "h", "lang": "C", "max_stars_repo_path": "vrutil/OverlayItem.h", "max_stars_repo_name": "ousttrue/VROverlaySample", "max_stars_repo_head_hexsha": "6116b91403393f2f7747c3da902b29612b0ce20a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vrutil/OverlayItem.h", "max_issues_repo_name": "ousttrue/VROverlaySample", "max_issues_repo_head_hexsha": "6116b91403393f2f7747c3da902b29612b0ce20a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vrutil/OverlayItem.h", "max_forks_repo_name": "ousttrue/VROverlaySample", "max_forks_repo_head_hexsha": "6116b91403393f2f7747c3da902b29612b0ce20a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4074074074, "max_line_length": 65, "alphanum_fraction": 0.7009493671, "num_tokens": 152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07696084416440005, "lm_q2_score": 0.013020492770824853, "lm_q1q2_score": 0.001002068115079149}}
{"text": "#pragma once\n/*\n * (C) Copyright 2020-2021 UCAR\n *\n * This software is licensed under the terms of the Apache Licence Version 2.0\n * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.\n */\n/*! \\defgroup ioda_cxx_variable Variables, Data Access, and Selections\n * \\brief The main data storage methods and objects in IODA.\n * \\ingroup ioda_cxx_api\n *\n * @{\n * \\file Variable.h\n * \\brief @link ioda_cxx_variable Interfaces @endlink for ioda::Variable and related classes.\n */\n#include <cstring>\n#include <gsl/gsl-lite.hpp>\n#include <list>\n#include <map>\n#include <memory>\n#include <string>\n#include <tuple>\n#include <utility>\n#include <vector>\n\n#include \"ioda/Attributes/Has_Attributes.h\"\n#include \"ioda/Exception.h\"\n#include \"ioda/Misc/Eigen_Compat.h\"\n#include \"ioda/Python/Var_ext.h\"\n#include \"ioda/Types/Marshalling.h\"\n#include \"ioda/Types/Type.h\"\n#include \"ioda/Types/Type_Provider.h\"\n#include \"ioda/Variables/Fill.h\"\n#include \"ioda/Variables/Selection.h\"\n#include \"ioda/defs.h\"\n\nnamespace ioda {\nclass Attribute;\nclass Variable;\nstruct VariableCreationParameters;\n\nstruct Named_Variable;\n\nnamespace detail {\nclass Attribute_Backend;\nclass Variable_Backend;\n\n/// \\brief Exists to prevent constructor conflicts when passing a backend into\n///   a frontend object.\n/// \\ingroup ioda_cxx_variable\n/// \\bug Need to add a virtual resize function.\ntemplate <class Variable_Implementation = Variable>\nclass Variable_Base {\nprotected:\n  /// Using an opaque object to implement the backend.\n  std::shared_ptr<Variable_Backend> backend_;\n\n  /// @name General Functions\n  /// @{\n\n  Variable_Base(std::shared_ptr<Variable_Backend>);\n\npublic:\n  virtual ~Variable_Base();\n\n  /// @}\n  /// @name Metadata manipulation\n  /// @{\n\n  /// Attributes\n  Has_Attributes atts;\n\n  /// @}\n\n  /// @name General Functions\n  /// @{\n\n  /// Gets a handle to the underlying object that implements the backend functionality.\n  std::shared_ptr<Variable_Backend> get() const;\n\n  /// @}\n  /// @name Type-querying Functions\n  /// @{\n\n  /// Get type\n  virtual Type getType() const;\n  /// Get type\n  inline Type type() const { return getType(); }\n\n  /// Query the backend and get the type provider.\n  virtual detail::Type_Provider* getTypeProvider() const;\n\n  /// \\brief Convenience function to check a Variable's storage type.\n  /// \\param DataType is the type of the data. I.e. float, int, int32_t, uint16_t, std::string, etc.\n  /// \\returns True if the type matches\n  /// \\returns False (0) if the type does not match\n  /// \\throws ioda::Exception if an error occurred.\n  template <class DataType>\n  bool isA() const {\n    Type templateType = Types::GetType_Wrapper<DataType>::GetType(getTypeProvider());\n\n    return isA(templateType);\n  }\n  /// Hand-off to the backend to check equivalence\n  virtual bool isA(Type lhs) const;\n\n  /// Python compatability function\n  inline bool isA(BasicTypes dataType) const { return isA(Type(dataType, getTypeProvider())); }\n  /// \\internal pybind11\n  inline bool _py_isA2(BasicTypes dataType) { return isA(dataType); }\n  /// Convenience function to query type\n  BasicTypes getBasicType() const;\n\n  /// @}\n  /// @name Querying Functions for Fill Values, Chunking and Compression\n  /// @{\n\n  /// @brief Convenience function to get fill value, attributes,\n  ///   chunk sizes, and compression in a collective call.\n  /// @details This function has better performance on some engines\n  ///   for bulk operations than calling separately.\n  /// @param doAtts includes attributes in the creation parameters.\n  /// @param doDims includes dimension scales in the creation parameters.\n  /// Although dimensions are attributes on some backends, we treat them\n  /// separately in this function.\n  /// @returns the filled-in VariableCreationParameters object\n  virtual VariableCreationParameters getCreationParameters(bool doAtts = true,\n                                                           bool doDims = true) const;\n\n  /// \\brief Check if a variable has a fill value set\n  /// \\returns true if a fill value is set, false otherwise.\n  virtual bool hasFillValue() const;\n\n  /// Remap fill value storage type into this class.\n  typedef detail::FillValueData_t FillValueData_t;\n\n  /// \\brief Retrieve the fill value\n  /// \\returns an object of type FillValueData_t that stores\n  ///   the fill value. If there is no fill value, then\n  ///   FillValueData_t::set_ will equal false. The fill\n  ///   value data will be stored in\n  ///   FillValueData_t::fillValue_ (for simple types), or in\n  ///   FillValueData_t::stringFillValue_ (for strings only).\n  /// \\note Recommend querying isA to make sure that you\n  ///   are reading the fill value as the correct type.\n  virtual FillValueData_t getFillValue() const;\n\n  /// \\brief Retrieve the chunking options for the Variable.\n  /// \\note Not all backends support chunking, but they should\n  ///   all store the desired chunk size information in case the\n  ///   Variable is copied to a new backend.\n  /// \\returns a vector containing the chunk sizes.\n  /// \\returns an empty vector if chunking is not used.\n  virtual std::vector<Dimensions_t> getChunkSizes() const;\n\n  /// \\brief Retrieve the GZIP compression options for the Variable.\n  /// \\note Not all backends support compression (and those that\n  ///   do also require chunking support). They should store this\n  ///   information anyways, in case the Variable is copied to\n  ///   a new backend.\n  /// \\returns a pair indicating 1) whether GZIP is requested and\n  ///   2) the compression level that is desired.\n  virtual std::pair<bool, int> getGZIPCompression() const;\n\n  /// \\brief Retrieve the SZIP compression options for the Variable.\n  /// \\note Not all backends support compression (and those that\n  ///   do also require chunking support). They should store this\n  ///   information anyways, in case the Variable is copied to\n  ///   a new backend.\n  /// \\returns a tuple indicating 1) whether SZIP is requested,\n  ///   2) PixelsPerBlock, and 3) general SZIP filter option flags.\n  virtual std::tuple<bool, unsigned, unsigned> getSZIPCompression() const;\n\n  /// @}\n  /// @name Data Space-Querying Functions\n  /// @{\n\n  // Get dataspace\n  // JEDI_NODISCARD DataSpace getSpace() const;\n\n  /// Get current and maximum dimensions, and number of total points.\n  /// \\note In Python, see the dims property.\n  virtual Dimensions getDimensions() const;\n\n  /// \\brief Resize the variable.\n  /// \\note Not all variables are resizable. This depends\n  ///   on backend support. For HDF5, the variable must be chunked\n  ///   and must not exceed max_dims.\n  /// \\note Bad things may happen if a variable's dimension scales\n  ///   have different lengths than its dimensions. Resize them\n  ///   together, preferably using the ObsSpace resize function.\n  /// \\see ObsSpace::resize\n  /// \\param newDims are the new dimensions.\n  virtual Variable resize(const std::vector<Dimensions_t>& newDims);\n\n  /// Attach a dimension scale to this Variable.\n  virtual Variable attachDimensionScale(unsigned int DimensionNumber, const Variable& scale);\n  /// Detach a dimension scale\n  virtual Variable detachDimensionScale(unsigned int DimensionNumber, const Variable& scale);\n  /// Set dimensions (convenience function to several invocations of attachDimensionScale).\n  Variable setDimScale(const std::vector<Variable>& dims);\n  /// Set dimensions (convenience function to several invocations of attachDimensionScale).\n  Variable setDimScale(const std::vector<Named_Variable>& dims);\n  /// Set dimensions (convenience function to several invocations of attachDimensionScale).\n  Variable setDimScale(const Variable& dims);\n  /// Set dimensions (convenience function to several invocations of attachDimensionScale).\n  Variable setDimScale(const Variable& dim1, const Variable& dim2);\n  /// Set dimensions (convenience function to several invocations of attachDimensionScale).\n  Variable setDimScale(const Variable& dim1, const Variable& dim2, const Variable& dim3);\n\n  /// Is this Variable used as a dimension scale?\n  virtual bool isDimensionScale() const;\n\n  /// Designate this table as a dimension scale\n  virtual Variable setIsDimensionScale(const std::string& dimensionScaleName);\n  /// Get the name of this Variable's defined dimension scale\n  inline std::string getDimensionScaleName() const {\n    std::string r;\n    getDimensionScaleName(r);\n    return r;\n  }\n  virtual Variable getDimensionScaleName(std::string& res) const;\n\n  /// Is a dimension scale attached to this Variable in a certain position?\n  virtual bool isDimensionScaleAttached(unsigned int DimensionNumber, const Variable& scale) const;\n\n  /// \\brief Which dimensions are attached at which positions? This function may offer improved\n  /// performance on some backends compared to serial isDimensionScaleAttached calls.\n  /// \\param scalesToQueryAgainst is a vector containing the scales. You can pass in\n  ///   \"tagged\" strings that map the Variable to a name.\n  ///   If you do not pass in a scale to check against, then this scale will not be checked and\n  ///   will not be present in the function output.\n  /// \\param firstOnly is specified when only one dimension can be attached to each axis (the\n  /// default).\n  /// \\returns a vector with the same length as the variable's dimensionality.\n  ///   Each variable dimension in the vector can have one or more attached scales. These scales are\n  ///   returned as their own, inner, vector of pair<string, Variable>.\n  virtual std::vector<std::vector<Named_Variable>> getDimensionScaleMappings(\n    const std::list<Named_Variable>& scalesToQueryAgainst,\n    bool firstOnly = true) const;\n\n  /// @}\n  /// @name Writing Data\n  /// @{\n\n  /// \\brief The fundamental write function. Backends overload this function to implement\n  ///   all write operations.\n  ///\n  /// \\details This function writes a span of bytes (characters) to the backend attribute\n  ///   storage. No type conversions take place here (see the templated conversion function,\n  ///   below).\n  ///\n  /// \\param data is a span of data.\n  /// \\param in_memory_datatype is an opaque (backend-level) object that describes the\n  ///   placement of the data in memory. Usually ignorable - needed for complex data structures.\n  /// \\param mem_selection is the user's memory layout representing the location where\n  ///   the data is read from.\n  /// \\param file_selection is the backend's memory layout representing the\n  ///   location where the data are written to.\n  /// \\throws ioda::xError if data has the wrong size.\n  /// \\returns The variable (for chaining).\n  virtual Variable write(gsl::span<const char> data, const Type& in_memory_dataType,\n                         const Selection& mem_selection  = Selection::all,\n                         const Selection& file_selection = Selection::all);\n\n  /// \\brief Write the Variable\n  /// \\note Ensure that the correct dimension ordering is preserved.\n  /// \\note With default parameters, the entire Variable is written.\n  /// \\tparam DataType is the type of the data to be written.\n  /// \\tparam Marshaller is a class that serializes / deserializes data.\n  /// \\tparam TypeWrapper translates DataType into a form that the backend understands.\n  /// \\param data is a span of data.\n  /// \\param mem_selection is the user's memory layout representing the location where\n  ///   the data is read from.\n  /// \\param file_selection is the backend's memory layout representing the\n  ///   location where the data are written to.\n  /// \\throws ioda::xError if data has the wrong size.\n  /// \\returns The variable (for chaining).\n  template <class DataType, class Marshaller = Object_Accessor<DataType>,\n            class TypeWrapper = Types::GetType_Wrapper<DataType>>\n  Variable_Implementation write(const gsl::span<DataType> data,\n                                const Selection& mem_selection  = Selection::all,\n                                const Selection& file_selection = Selection::all) {\n    try {\n      Marshaller m;\n      auto d = m.serialize(data);\n      return write(gsl::make_span<const char>(\n                      reinterpret_cast<const char*>(d->DataPointers.data()),\n                     d->DataPointers.size() * Marshaller::bytesPerElement_),\n                   TypeWrapper::GetType(getTypeProvider()), mem_selection, file_selection);\n    } catch (...) {\n      std::throw_with_nested(Exception(ioda_Here()));\n    }\n  }\n\n  /// \\brief Write the Variable\n  /// \\note Ensure that the correct dimension ordering is preserved.\n  /// \\note With default parameters, the entire Variable is written.\n  /// \\tparam DataType is the type of the data to be written.\n  /// \\tparam Marshaller is a class that serializes / deserializes data.\n  /// \\tparam TypeWrapper translates DataType into a form that the backend understands.\n  /// \\param data is a span of data.\n  /// \\param mem_selection is the user's memory layout representing the location where\n  ///   the data is read from.\n  /// \\param file_selection is the backend's memory layout representing the\n  ///   location where the data are written to.\n  /// \\throws ioda::xError if data has the wrong size.\n  /// \\returns The variable (for chaining).\n  template <class DataType, class Marshaller = Object_Accessor<DataType>,\n            class TypeWrapper = Types::GetType_Wrapper<DataType>>\n  Variable_Implementation write(const gsl::span<const DataType> data,\n                                const Selection& mem_selection  = Selection::all,\n                                const Selection& file_selection = Selection::all) {\n    try {\n      Marshaller m;\n      auto d = m.serialize(data);\n      return write(gsl::make_span<const char>(\n                      reinterpret_cast<const char*>(d->DataPointers.data()),\n                     d->DataPointers.size() * Marshaller::bytesPerElement_),\n                   TypeWrapper::GetType(getTypeProvider()), mem_selection, file_selection);\n    } catch (...) {\n      std::throw_with_nested(Exception(ioda_Here()));\n    }\n  }\n\n  /// \\brief Write the variable\n  /// \\tparam DataType is the type of the data to be written.\n  /// \\tparam Marshaller is a class that serializes / deserializes data.\n  /// \\tparam TypeWrapper translates DataType into a form that the backend understands.\n  /// \\param data is a span of data.\n  /// \\param mem_selection is the user's memory layout representing the location where\n  ///   the data is read from.\n  /// \\param file_selection is the backend's memory layout representing the\n  ///   location where the data are written to.\n  /// \\throws ioda::xError if data has the wrong size.\n  /// \\returns The variable (for chaining).\n\n  template <class DataType, class Marshaller = Object_Accessor<DataType>,\n            class TypeWrapper = Types::GetType_Wrapper<DataType>>\n  Variable_Implementation write(const std::vector<DataType>& data,\n                                const Selection& mem_selection  = Selection::all,\n                                const Selection& file_selection = Selection::all) {\n    try {\n      return this->write<DataType, Marshaller, TypeWrapper>(gsl::make_span(data), mem_selection,\n                                                            file_selection);\n    } catch (...) {\n      std::throw_with_nested(Exception(ioda_Here()));\n    }\n  }\n\n  /// \\brief Write an Eigen object (a Matrix, an Array, a Block, a Map).\n  /// \\tparam EigenClass is the type of the Eigen object being written.\n  /// \\param d is the data to be written.\n  /// \\param mem_selection is the user's memory layout representing the location where\n  ///   the data is read from.\n  /// \\param file_selection is the backend's memory layout representing the\n  ///   location where the data are written to.\n  /// \\throws ioda::xError on a dimension mismatch.\n  /// \\returns the variable\n  template <class EigenClass>\n  Variable_Implementation writeWithEigenRegular(const EigenClass& d,\n                                                const Selection& mem_selection  = Selection::all,\n                                                const Selection& file_selection = Selection::all) {\n#if 1  //__has_include(\"Eigen/Dense\")\n    try {\n      typedef typename EigenClass::Scalar ScalarType;\n      // If d is already in Row Major form, then this is optimized out.\n      Eigen::Array<ScalarType, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> dout;\n      dout.resize(d.rows(), d.cols());\n      dout               = d;\n      const auto& dconst = dout;  // To make some compilers happy.\n      auto sp            = gsl::make_span(dconst.data(), static_cast<int>(d.rows() * d.cols()));\n\n      return write<ScalarType>(sp, mem_selection, file_selection);\n    } catch (...) {\n      std::throw_with_nested(Exception(ioda_Here()));\n    }\n#else\n    static_assert(false, \"The Eigen headers cannot be found, so this function cannot be used.\");\n#endif\n  }\n\n  /// \\brief Write an Eigen Tensor-like object\n  /// \\tparam EigenClass is the type of the Eigen object being written.\n  /// \\param d is the data to be written.\n  /// \\param mem_selection is the user's memory layout representing the location where\n  ///   the data is read from.\n  /// \\param file_selection is the backend's memory layout representing the\n  ///   location where the data are written to.\n  /// \\throws ioda::xError on a dimension mismatch.\n  /// \\returns the variable\n  template <class EigenClass>\n  Variable_Implementation writeWithEigenTensor(const EigenClass& d,\n                                               const Selection& mem_selection  = Selection::all,\n                                               const Selection& file_selection = Selection::all) {\n#if 1  //__has_include(\"unsupported/Eigen/CXX11/Tensor\")\n    try {\n      ioda::Dimensions dims = detail::EigenCompat::getTensorDimensions(d);\n\n      auto sp  = (gsl::make_span(d.data(), dims.numElements));\n      auto res = write(sp, mem_selection, file_selection);\n      return res;\n    } catch (...) {\n      std::throw_with_nested(Exception(ioda_Here()));\n    }\n#else\n    static_assert(\n      false, \"The Eigen unsupported/ headers cannot be found, so this function cannot be used.\");\n#endif\n  }\n\n  /// @}\n  /// @name Reading Data\n  /// @{\n\n  /// \\brief Read the Variable - as char array. Ordering is row-major.\n  /// \\details This is the fundamental read function that has to be implemented.\n  /// \\param data is a byte-array that will hold the read data.\n  /// \\param in_memory_dataType describes how ioda should arrange the read data in memory.\n  ///   As floats? As doubles? Strings?\n  /// \\param mem_selection is the user's memory layout representing the location where\n  ///   the data is read from.\n  /// \\param file_selection is the backend's memory layout representing the\n  ///   location where the data are written to.\n  /// \\note Ensure that the correct dimension ordering is preserved\n  /// \\note With default parameters, the entire Variable is read\n  virtual Variable read(gsl::span<char> data, const Type& in_memory_dataType,\n                        const Selection& mem_selection  = Selection::all,\n                        const Selection& file_selection = Selection::all) const;\n\n  /// \\brief Read the variable into a span (range) or memory. Ordering is row-major.\n  /// \\tparam DataType is the type of the data to be written.\n  /// \\tparam Marshaller is a class that serializes / deserializes data.\n  /// \\tparam TypeWrapper translates DataType into a form that the backend understands.\n  /// \\param data is a byte-array that will hold the read data.\n  /// \\param mem_selection is the user's memory layout representing the location where\n  ///   the data is read from.\n  /// \\param file_selection is the backend's memory layout representing the\n  ///   location where the data are written to.\n  /// \\todo Add in the dataspaces!\n  template <class DataType, class Marshaller = ioda::Object_Accessor<DataType>,\n            class TypeWrapper = Types::GetType_Wrapper<DataType>>\n  Variable_Implementation read(gsl::span<DataType> data,\n                               const Selection& mem_selection  = Selection::all,\n                               const Selection& file_selection = Selection::all) const {\n    try {\n      const size_t numObjects = data.size();\n\n      detail::PointerOwner pointerOwner = getTypeProvider()->getReturnedPointerOwner();\n      Marshaller m(pointerOwner);\n      auto p = m.prep_deserialize(numObjects);\n      read(gsl::make_span<char>(\n             reinterpret_cast<char*>(p->DataPointers.data()),\n             // Logic note: sizeof mutable data type. If we are\n             // reading in a string, then mutable data type is char*,\n             // which works because address pointers have the same size.\n             p->DataPointers.size() * Marshaller::bytesPerElement_),\n           TypeWrapper::GetType(getTypeProvider()), mem_selection, file_selection);\n      m.deserialize(p, data);\n\n      return Variable_Implementation{backend_};\n    } catch (...) {\n      std::throw_with_nested(Exception(ioda_Here()));\n    }\n  }\n\n  /// \\brief Read the variable into a vector. Resize if needed. For a non-resizing\n  ///   version, use a gsl::span.\n  /// \\details Ordering is row-major.\n  /// \\tparam DataType is the type of the data to be written.\n  /// \\tparam Marshaller is a class that serializes / deserializes data.\n  /// \\tparam TypeWrapper translates DataType into a form that the backend understands.\n  /// \\param data is a byte-array that will hold the read data.\n  /// \\param mem_selection is the user's memory layout representing the location where\n  ///   the data is read from.\n  /// \\param file_selection is the backend's memory layout representing the\n  ///   location where the data are written to.\n  /// \\bug Resize only if needed, and resize to the proper extent depending on\n  ///   mem_selection and file_selection.\n  template <class DataType, class Marshaller = ioda::Object_Accessor<DataType>,\n            class TypeWrapper = Types::GetType_Wrapper<DataType>>\n  Variable_Implementation read(std::vector<DataType>& data,\n                               const Selection& mem_selection  = Selection::all,\n                               const Selection& file_selection = Selection::all) const {\n    data.resize(getDimensions().numElements); // TODO(Ryan): remove\n    return read<DataType, Marshaller, TypeWrapper>(gsl::make_span(data.data(), data.size()),\n                                                   mem_selection, file_selection);\n  }\n\n  /// \\brief Read the variable into a new vector. Python convenience function.\n  /// \\bug Get correct size based on selection operands.\n  /// \\tparam DataType is the type of the data to be written.\n  /// \\tparam Marshaller is a class that serializes / deserializes data.\n  /// \\tparam TypeWrapper translates DataType into a form that the backend understands.\n  /// \\param mem_selection is the user's memory layout representing the location where\n  ///   the data is read from.\n  /// \\param file_selection is the backend's memory layout representing the\n  ///   location where the data are written to.\n  template <class DataType, class Marshaller = ioda::Object_Accessor<DataType>,\n            class TypeWrapper = Types::GetType_Wrapper<DataType>>\n  std::vector<DataType> readAsVector(const Selection& mem_selection  = Selection::all,\n                                     const Selection& file_selection = Selection::all) const {\n    std::vector<DataType> data(getDimensions().numElements);\n    read<DataType, Marshaller, TypeWrapper>(gsl::make_span(data.data(), data.size()), mem_selection,\n                                            file_selection);\n    return data;\n  }\n\n  /// \\brief Valarray read convenience function. Resize if needed.\n  ///   For a non-resizing version, use a gsl::span.\n  /// \\tparam DataType is the type of the data to be written.\n  /// \\tparam Marshaller is a class that serializes / deserializes data.\n  /// \\tparam TypeWrapper translates DataType into a form that the backend understands.\n  /// \\param data is a valarray acting as a data buffer that is filled with the\n  ///   metadata's contents. It gets resized as needed.\n  /// \\param mem_selection is the user's memory layout representing the location where\n  ///   the data is read from.\n  /// \\param file_selection is the backend's memory layout representing the\n  ///   location where the data are written to.\n  /// \\returns Another instance of this Attribute. Used for operation chaining.\n  /// \\note data will be stored in row-major order.\n  template <class DataType, class Marshaller = ioda::Object_Accessor<DataType>,\n            class TypeWrapper = Types::GetType_Wrapper<DataType>>\n  Variable_Implementation read(std::valarray<DataType>& data,\n                               const Selection& mem_selection  = Selection::all,\n                               const Selection& file_selection = Selection::all) const {\n    /// \\bug Resize only if needed, and resize to the proper extent depending on\n    /// mem_selection and file_selection.\n    data.resize(getDimensions().numElements); // TODO(Ryan): remove\n    return read<DataType, Marshaller, TypeWrapper>(gsl::make_span(std::begin(data), std::end(data)),\n                                                   mem_selection, file_selection);\n  }\n\n  /// \\brief Read data into an Eigen::Array, Eigen::Matrix, Eigen::Map, etc.\n  /// \\tparam EigenClass is a template pointing to the Eigen object.\n  ///   This template must provide the EigenClass::Scalar typedef.\n  /// \\tparam Resize indicates whether the Eigen object should be resized\n  ///   if there is a dimension mismatch. Not all Eigen objects can be resized.\n  /// \\param res is the Eigen object.\n  /// \\param mem_selection is the user's memory layout representing the location where\n  ///   the data is read from.\n  /// \\param file_selection is the backend's memory layout representing the\n  ///   location where the data are written to.\n  /// \\returns Another instance of this Variable. Used for operation chaining.\n  /// \\throws ioda::xError if the variable's dimensionality is\n  ///   too high.\n  /// \\throws ioda::xError if resize = false and there is a dimension mismatch.\n  /// \\note When reading in a 1-D object, the data are read as a column vector.\n  template <class EigenClass, bool Resize = detail::EigenCompat::CanResize<EigenClass>::value>\n  Variable_Implementation readWithEigenRegular(EigenClass& res,\n                                               const Selection& mem_selection = Selection::all,\n                                               const Selection& file_selection\n                                               = Selection::all) const {\n    /// \\bug Resize only if needed, and resize to the proper extent depending on\n    /// mem_selection and file_selection.\n#if 1  //__has_include(\"Eigen/Dense\")\n    try {\n      typedef typename EigenClass::Scalar ScalarType;\n\n      static_assert(\n        !(Resize && !detail::EigenCompat::CanResize<EigenClass>::value),\n        \"This object cannot be resized, but you have specified that a resize is required.\");\n\n      // Check that the dimensionality is 1 or 2.\n      const auto dims = getDimensions();\n      if (dims.dimensionality > 2)\n        throw Exception(\"Dimensionality too high for a regular Eigen read. Use \"\n          \"Eigen::Tensor reads instead.\", ioda_Here());\n\n      int nDims[2] = {1, 1};\n      if (dims.dimsCur.size() >= 1) nDims[0] = gsl::narrow<int>(dims.dimsCur[0]);\n      if (dims.dimsCur.size() >= 2) nDims[1] = gsl::narrow<int>(dims.dimsCur[1]);\n\n      // Resize if needed.\n      if (Resize)\n        detail::EigenCompat::DoEigenResize(res, nDims[0],\n                                           nDims[1]);  // nullop if the size is already correct.\n      else if (dims.numElements != (size_t)(res.rows() * res.cols()))\n        throw Exception(\"Size mismatch\", ioda_Here());\n\n      // Array copy to preserve row vs column major format.\n      // Should be optimized away by the compiler if unneeded.\n      // Note to the reader: We are reading in the data to a temporary object.\n      // We can size _this_ temporary object however we want.\n      // The temporary is used to swap row / column indices if needed.\n      // It should be optimized away if not needed... making sure this happens is a todo.\n      Eigen::Array<ScalarType, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> data_in(res.rows(),\n                                                                                        res.cols());\n\n      auto ret = read<ScalarType>(gsl::span<ScalarType>(data_in.data(), dims.numElements),\n                                  mem_selection, file_selection);\n      res      = data_in;\n      return ret;\n    } catch (...) {\n      std::throw_with_nested(Exception(ioda_Here()));\n    }\n#else\n    static_assert(false, \"The Eigen headers cannot be found, so this function cannot be used.\");\n#endif\n  }\n\n  /// \\brief Read data into an Eigen::Array, Eigen::Matrix, Eigen::Map, etc.\n  /// \\tparam EigenClass is a template pointing to the Eigen object.\n  ///   This template must provide the EigenClass::Scalar typedef.\n  /// \\param res is the Eigen object.\n  /// \\param mem_selection is the user's memory layout representing the location where\n  ///   the data is read from.\n  /// \\param file_selection is the backend's memory layout representing the\n  ///   location where the data are written to.\n  /// \\returns Another instance of this Variable. Used for operation chaining.\n  /// \\throws ioda::Exception if there is a size mismatch.\n  /// \\note When reading in a 1-D object, the data are read as a column vector.\n  template <class EigenClass>\n  Variable_Implementation readWithEigenTensor(EigenClass& res,\n                                              const Selection& mem_selection = Selection::all,\n                                              const Selection& file_selection\n                                              = Selection::all) const {\n#if 1  //__has_include(\"unsupported/Eigen/CXX11/Tensor\")\n    try {\n      // Check dimensionality of source and destination\n      const auto ioda_dims  = getDimensions();\n      const auto eigen_dims = ioda::detail::EigenCompat::getTensorDimensions(res);\n      if (ioda_dims.numElements != eigen_dims.numElements)\n        throw Exception(\"Size mismatch for Eigen Tensor-like read.\", ioda_Here());\n\n      auto sp = (gsl::make_span(res.data(), eigen_dims.numElements));\n      return read(sp, mem_selection, file_selection);\n    } catch (...) {\n      std::throw_with_nested(Exception(ioda_Here()));\n    }\n#else\n    static_assert(\n      false, \"The Eigen unsupported/ headers cannot be found, so this function cannot be used.\");\n#endif\n  }\n\n  /// \\internal Python binding function\n  template <class EigenClass>\n  EigenClass _readWithEigenRegular_python(const Selection& mem_selection  = Selection::all,\n                                          const Selection& file_selection = Selection::all) const {\n    EigenClass data;\n    readWithEigenRegular(data, mem_selection, file_selection);\n    return data;\n  }\n\n  /// @brief Convert a selection into its backend representation\n  /// @param sel is the frontend selection.\n  /// @return The cached backend selection.\n  virtual Selections::SelectionBackend_t instantiateSelection(const Selection& sel) const;\n\n  /// @}\n\nprivate:\n  /// \\brief get the fill value from the netcdf specification (_FillValue attribute)\n  FillValueData_t getNcFillValue() const;\n\n  /// \\brief check if fill data objects match, print warning if they don't match\n  /// \\param hdfFill fill value obtained from the hdf fill value property\n  /// \\param ncFill fill value obtained from the netcdf fill value attribute\n  void checkWarnFillValue(FillValueData_t & hdfFill, FillValueData_t & ncFill) const;\n\n  /// \\brief run an action according to the current variable data type\n  /// \\details this function will call the function passed to it through the action\n  /// parameter, giving this action a typed entity that can be identified by decltype.\n  /// At this point, all of the types supported by Variable_Base::getBasicType() except\n  /// for bool are handled in this function.\n  /// \\param action Function object callable with a single argument which is identifiable\n  /// by decltype\n  // TODO(srh) Additional development is required to properly handle the bool data type.\n  template <typename Action>\n  auto runForVarType(const Action & action) const {\n    if (isA<int>()) {\n      int typeMe;\n      return action(typeMe);\n    } else if (isA<unsigned int>()) {\n      unsigned int typeMe;\n      return action(typeMe);\n    } else if (isA<float>()) {\n      float typeMe;\n      return action(typeMe);\n    } else if (isA<double>()) {\n      double typeMe;\n      return action(typeMe);\n    } else if (isA<std::string>()) {\n      std::string typeMe;\n      return action(typeMe);\n    } else if (isA<long>()) {\n      long typeMe;\n      return action(typeMe);\n    } else if (isA<unsigned long>()) {\n      unsigned long typeMe;\n      return action(typeMe);\n    } else if (isA<short>()) {\n      short typeMe;\n      return action(typeMe);\n    } else if (isA<unsigned short>()) {\n      unsigned short typeMe;\n      return action(typeMe);\n    } else if (isA<long long>()) {\n      long long typeMe;\n      return action(typeMe);\n    } else if (isA<unsigned long long>()) {\n      unsigned long long typeMe;\n      return action(typeMe);\n    } else if (isA<int32_t>()) {\n      int32_t typeMe;\n      return action(typeMe);\n    } else if (isA<uint32_t>()) {\n      uint32_t typeMe;\n      return action(typeMe);\n    } else if (isA<int16_t>()) {\n      int16_t typeMe;\n      return action(typeMe);\n    } else if (isA<uint16_t>()) {\n      uint16_t typeMe;\n      return action(typeMe);\n    } else if (isA<int64_t>()) {\n      int64_t typeMe;\n      return action(typeMe);\n    } else if (isA<uint64_t>()) {\n      uint64_t typeMe;\n      return action(typeMe);\n    } else if (isA<long double>()) {\n      long double typeMe;\n      return action(typeMe);\n    } else if (isA<char>()) {\n      char typeMe;\n      return action(typeMe);\n    } else if (isA<unsigned char>()) {\n      unsigned char typeMe;\n      return action(typeMe);\n    } else {\n      std::throw_with_nested(Exception(\"Unsupported variable data type\", ioda_Here()));\n    }\n  }\n\n};\n// extern template class Variable_Base<Variable>;\n}  // namespace detail\n\n/** \\brief Variables store data!\n * \\ingroup ioda_cxx_variable\n *\n * A variable represents a single field of data. It can be multi-dimensional and\n * usually has one or more attached **dimension scales**.\n *\n * Variables have Metadata, which describe the variable (i.e. valid_range, long_name, units).\n * Variables can have different data types (i.e. int16_t, float, double, string, datetime).\n * Variables can be resized. Depending on the backend, the data in a variable can be stored\n * using chunks, and may also be compressed.\n *\n * The backend manages how variables are stored in memory or on disk. The functions in the\n * Variable class provide methods to query and set data. The goal is to have data transfers\n * involve as few copies as possible.\n *\n * Variable objects themselves are lightweight handles that may be passed across different\n * parts of a program. Variables are always stored somewhere in a Group (or ObsSpace), so you\n * can always re-open a handle.\n *\n * \\note Thread and MPI safety depend on the specific backends used to implement a variable.\n * \\note A variable may be linked to multiple groups and listed under multiple names, so long as\n * the storage backends are all the same.\n **/\nclass IODA_DL Variable : public detail::Variable_Base<Variable> {\npublic:\n  /// @name General Functions\n  /// @{\n\n  Variable();\n  Variable(std::shared_ptr<detail::Variable_Backend> b);\n  Variable(const Variable&);\n  Variable& operator=(const Variable&);\n  virtual ~Variable();\n\n  /// @}\n  /// @name Python compatability objects\n  /// @{\n\n  detail::python_bindings::VariableIsA<Variable> _py_isA;\n\n  detail::python_bindings::VariableReadVector<Variable> _py_readVector;\n  detail::python_bindings::VariableReadNPArray<Variable> _py_readNPArray;\n\n  detail::python_bindings::VariableWriteVector<Variable> _py_writeVector;\n  detail::python_bindings::VariableWriteNPArray<Variable> _py_writeNPArray;\n\n  detail::python_bindings::VariableScales<Variable> _py_scales;\n\n  /// @}\n};\n\nnamespace detail {\n/// \\brief Variable backends inherit from this.\nclass IODA_DL Variable_Backend : public Variable_Base<Variable> {\npublic:\n  virtual ~Variable_Backend();\n\n  /// Default, trivial implementation. Customizable by backends for performance.\n  std::vector<std::vector<Named_Variable>> getDimensionScaleMappings(\n    const std::list<Named_Variable>& scalesToQueryAgainst,\n    bool firstOnly = true) const override;\n\n  /// Default implementation. Customizable by backends for performance.\n  VariableCreationParameters getCreationParameters(bool doAtts = true,\n                                                   bool doDims = true) const override;\n\nprotected:\n  Variable_Backend();\n\n  /// @brief This function de-encapsulates an Attribute's backend storage object.\n  ///   This function is used by Variable_Backend's derivatives when accessing a\n  ///   Variable's Attributes. IODA-internal use only.\n  /// @tparam Attribute_Implementation is a dummy parameter used by Attributes.\n  /// @param base is the Attribute whose backend you want.\n  /// @return The encapsulated backend object.\n  template <class Attribute_Implementation = Attribute>\n  static std::shared_ptr<Attribute_Backend> _getAttributeBackend(\n    const Attribute_Implementation& att) {\n    return att.backend_;\n  }\n\n  /// @brief This function de-encapsulates a Has_Attributes backend storage object.\n  ///   IODA-internal use only.\n  /// @tparam Has_Attributes_Implementation is a dummy parameter for template resolution.\n  /// @param hatts is the Has_Attributes whose backend you want.\n  /// @return The encapsulated backend object.\n  template <class Has_Attributes_Implementation = Has_Attributes>\n  static std::shared_ptr<Has_Attributes_Backend> _getHasAttributesBackend(\n    const Has_Attributes_Implementation& hatts) {\n    return hatts.backend_;\n  }\n};\n}  // namespace detail\n\n/// @brief A named pair of (variable_name, ioda::Variable).\nstruct Named_Variable {\n  std::string name;\n  ioda::Variable var;\n  bool operator<(const Named_Variable& rhs) const { return name < rhs.name; }\n\n  Named_Variable() = default;\n  Named_Variable(const std::string& name, const ioda::Variable& var) : name(name), var(var) {}\n};\n\n}  // namespace ioda\n\n/// @}\n", "meta": {"hexsha": "96fc29c3a43142e4853ba4d98e80ceb76f5be54e", "size": 38402, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engines/ioda/include/ioda/Variables/Variable.h", "max_stars_repo_name": "NOAA-EMC/ioda", "max_stars_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/engines/ioda/include/ioda/Variables/Variable.h", "max_issues_repo_name": "NOAA-EMC/ioda", "max_issues_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engines/ioda/include/ioda/Variables/Variable.h", "max_forks_repo_name": "NOAA-EMC/ioda", "max_forks_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.2853773585, "max_line_length": 100, "alphanum_fraction": 0.6824904953, "num_tokens": 8590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.0408457112396463, "lm_q2_score": 0.024423090320390244, "lm_q1q2_score": 0.0009975784948064606}}
{"text": "#ifndef STDAFX__H\r\n#define STDAFX__H\r\n\r\n#if defined(_WIN32)\r\n\r\n#include <SDKDDKVer.h>\r\n\r\n#if !defined(_STL_EXTRA_DISABLED_WARNINGS)\r\n#define _STL_EXTRA_DISABLED_WARNINGS 4061 4324 4365 4514 4571 4582 4583 4623 4625 4626 4710 4774 4820 4987 5026 5027 5039\r\n#endif\r\n\r\n#if !defined(_SCL_SECURE_NO_WARNINGS)\r\n#define _SCL_SECURE_NO_WARNINGS 1\r\n#endif\r\n\r\n#if !defined(_CRT_SECURE_NO_WARNINGS)\r\n#define _CRT_SECURE_NO_WARNINGS 1\r\n#endif\r\n\r\n#if !defined(_SILENCE_CXX17_ITERATOR_BASE_CLASS_DEPRECATION_WARNING)\r\n#define _SILENCE_CXX17_ITERATOR_BASE_CLASS_DEPRECATION_WARNING 1\r\n#endif\r\n\r\n#if !defined(_SILENCE_CXX17_OLD_ALLOCATOR_MEMBERS_DEPRECATION_WARNING)\r\n#define _SILENCE_CXX17_OLD_ALLOCATOR_MEMBERS_DEPRECATION_WARNING 1\r\n#endif\r\n\r\n#if !defined(_SILENCE_CXX17_CODECVT_HEADER_DEPRECATION_WARNING)\r\n#define _SILENCE_CXX17_CODECVT_HEADER_DEPRECATION_WARNING 1\r\n#endif\r\n\r\n#define STRICT\r\n#define NOMINMAX\r\n\r\n#pragma warning(disable: 4571) // warning C4571: Informational: catch(...) semantics changed since Visual C++ 7.1; structured exceptions (SEH) are no longer caught\r\n#pragma warning(disable: 4668) // warning C4668: '%s' is not defined as a preprocessor macro, replacing with '0' for '#if/#elif'\r\n#pragma warning(disable: 4710) // warning C4710: '%s': function not inlined\r\n#pragma warning(disable: 4711) // warning C4711: function '%s' selected for automatic inline expansion\r\n#pragma warning(disable: 4820) // warning C4820: '%s': '%d' bytes padding added after data member '%s'\r\n#pragma warning(disable: 5045) // warning C5045: Compiler will insert Spectre mitigation for memory load if /Qspectre switch specified\r\n\r\n#include <Windows.h>\r\n\r\n#pragma warning(push)\r\n#pragma warning(disable: 4005) // warning C4005: '%s': macro redefinition\r\n#include <Winternl.h>\r\n#include <ntstatus.h>\r\n#pragma warning(pop)\r\n\r\n#else // defined(_WIN32)\r\n\r\n#include <cpuid.h>\r\n\r\n#endif\r\n\r\n#if defined(_MSC_VER)\r\n\r\n// currently broken (triggers on iterators and other objects that are usually unnamed)\r\n#pragma warning(disable: 26444) // warning C26444: Avoid unnamed objects with custom construction and destruction (es.84: http://go.microsoft.com/fwlink/?linkid=862923).\r\n\r\n// disable for everything\r\n#pragma warning(disable: 4061) // warning C4061: enumerator '%s' in switch of enum '%s' is not explicitly handled by a case label\r\n#pragma warning(disable: 4324) // warning C4234: structure was padded due to alignment specifier\r\n#pragma warning(disable: 4514) // warning C4514: '%s': unreferenced inline function has been removed\r\n#pragma warning(disable: 4623) // warning C4623: '%s': default constructor was implicitly defined as deleted\r\n#pragma warning(disable: 4625) // warning C4625: '%s': copy constructor was implicitly defined as deleted\r\n#pragma warning(disable: 4626) // warning C4626: '%s': assignment operator was implicitly defined as deleted\r\n#pragma warning(disable: 4710) // warning C4710: '%s': function not inlined\r\n#pragma warning(disable: 4820) // warning C4820: '%s': '%d' bytes padding added after data member '%s'\r\n#pragma warning(disable: 5026) // warning C5026: '%s': move constructor was implicitly defined as deleted\r\n#pragma warning(disable: 5027) // warning C5027: '%s': move assignment operator was implicitly defined as deleted\r\n\r\n#pragma warning(disable: 26412) // warning C26412: Do not dereference an invalid pointer (lifetimes rule 1). 'return of %s' was invalidated at line %d by 'no initialization'.\r\n#pragma warning(disable: 26426) // warning C26426: Global initializer calls a non-constexpr function '%s' (i.22: http://go.microsoft.com/fwlink/?linkid=853919).\r\n#pragma warning(disable: 26481) // warning C26481: Don't use pointer arithmetic. Use span instead. (bounds.1: http://go.microsoft.com/fwlink/p/?LinkID=620413)\r\n#pragma warning(disable: 26482) // warning C26482: Only index into arrays using constant expressions (bounds.2: http://go.microsoft.com/fwlink/p/?LinkID=620414).\r\n#pragma warning(disable: 26485) // warning C26485: Expression '%s::`vbtable'': No array to pointer decay. (bounds.3: http://go.microsoft.com/fwlink/p/?LinkID=620415)\r\n#pragma warning(disable: 26490) // warning C26490: Don't use reinterpret_cast. (type.1: http://go.microsoft.com/fwlink/p/?LinkID=620417)\r\n#pragma warning(disable: 26499) // warning C26499: Could not find any lifetime tracking information for '%s'\r\n\r\n// disable for standard headers\r\n#pragma warning(push)\r\n#pragma warning(disable: 26400) // warning C26400: Do not assign the result of an allocation or a function call with an owner<T> return value to a raw pointer, use owner<T> instead. (i.11 http://go.microsoft.com/fwlink/?linkid=845474)\r\n#pragma warning(disable: 26401) // warning C26401: Do not delete a raw pointer that is not an owner<T>. (i.11: http://go.microsoft.com/fwlink/?linkid=845474)\r\n#pragma warning(disable: 26408) // warning C26408: Avoid malloc() and free(), prefer the nothrow version of new with delete. (r.10 http://go.microsoft.com/fwlink/?linkid=845483)\r\n#pragma warning(disable: 26409) // warning C26409: Avoid calling new and delete explicitly, use std::make_unique<T> instead. (r.11 http://go.microsoft.com/fwlink/?linkid=845485)\r\n#pragma warning(disable: 26411) // warning C26411: The parameter '%s' is a reference to unique pointer and it is never reassigned or reset, use T* or T& instead. (r.33 http://go.microsoft.com/fwlink/?linkid=845479)\r\n#pragma warning(disable: 26412) // warning C26412: Do not dereference an invalid pointer (lifetimes rule 1). 'return of %s' was invalidated at line %d by 'end of function scope (local lifetimes end)'.\r\n#pragma warning(disable: 26413) // warning C26413: Do not dereference nullptr (lifetimes rule 2). 'nullptr' was pointed to nullptr at line %d.\r\n#pragma warning(disable: 26423) // warning C26423: The allocation was not directly assigned to an owner.\r\n#pragma warning(disable: 26424) // warning C26424: Failing to delete or assign ownership of allocation at line %d.\r\n#pragma warning(disable: 26425) // warning C26425: Assigning '%s' to a static variable.\r\n#pragma warning(disable: 26444) // warning C26444: Avoid unnamed objects with custom construction and destruction (es.84: http://go.microsoft.com/fwlink/?linkid=862923).\r\n#pragma warning(disable: 26461) // warning C26461: The reference argument '%s' for function %s can be marked as const. (con.3: https://go.microsoft.com/fwlink/p/?LinkID=786684)\r\n#pragma warning(disable: 26471) // warning C26471: Don't use reinterpret_cast. A cast from void* can use static_cast. (type.1: http://go.microsoft.com/fwlink/p/?LinkID=620417).\r\n#pragma warning(disable: 26481) // warning C26481: Don't use pointer arithmetic. Use span instead. (bounds.1: http://go.microsoft.com/fwlink/p/?LinkID=620413)\r\n#pragma warning(disable: 26482) // warning C26482: Only index into arrays using constant expressions. (bounds.2: http://go.microsoft.com/fwlink/p/?LinkID=620414)\r\n#pragma warning(disable: 26490) // warning C26490: Don't use reinterpret_cast. (type.1: http://go.microsoft.com/fwlink/p/?LinkID=620417)\r\n#pragma warning(disable: 26493) // warning C26493: Don't use C-style casts that would perform a static_cast downcast, const_cast, or reinterpret_cast. (type.4: http://go.microsoft.com/fwlink/p/?LinkID=620420)\r\n#pragma warning(disable: 26494) // warning C26494: Variable '%s' is uninitialized. Always initialize an object. (type.5: http://go.microsoft.com/fwlink/p/?LinkID=620421)\r\n#pragma warning(disable: 26495) // warning C26495: Variable '%s' is uninitialized. Always initialize a member variable. (type.6: http://go.microsoft.com/fwlink/p/?LinkID=620422)\r\n#pragma warning(disable: 26496) // warning C26496: Variable '%s' is assigned only once, mark it as const. (con.4: https://go.microsoft.com/fwlink/p/?LinkID=784969)\r\n#pragma warning(disable: 26497) // warning C26497: This function %s could be marked constexpr if compile-time evaluation is desired. (f.4: https://go.microsoft.com/fwlink/p/?LinkID=784970)\r\n\r\n#else\r\n\r\n// linux warnings go here\r\n\r\n#endif\r\n\r\n#include <cstddef>\r\n#include <map>\r\n#include <set>\r\n#include <vector>\r\n#include <string>\r\n#include <algorithm>\r\n#include <iostream>\r\n#include <fstream>\r\n#include <iomanip>\r\n#include <type_traits>\r\n#include <utility>\r\n#include <memory>\r\n#include <tuple>\r\n#include <thread>\r\n#include <cstdlib>\r\n#include <codecvt>\r\n\r\n#if defined(_MSC_VER)\r\n\r\n// disable additionally for third-party libraries\r\n#pragma warning(push)\r\n#pragma warning(disable: 4456) // warning C4456: declaration of '%s' hides previous local declaration\r\n#pragma warning(disable: 4458) // warning C4458: declaration of '%s' hides class member\r\n#pragma warning(disable: 4459) // warning C4459: declaration of '%s' hides global declaration\r\n\r\n#pragma warning(disable: 26429) // warning C26429: Symbol '%s' is never tested for nullness, it can be marked as not_null (f.23: http://go.microsoft.com/fwlink/?linkid=853921).\r\n#pragma warning(disable: 26432) // warning C26432: If you define or delete any default operation in the type '%s', define or delete them all (c.21: http://go.microsoft.com/fwlink/?linkid=853922).\r\n#pragma warning(disable: 26433) // warning C26433: Function '%s' should be marked with 'override' (c.128: http://go.microsoft.com/fwlink/?linkid=853923).\r\n#pragma warning(disable: 26434) // warning C26434: Function '%s' hides a non-virtual function '%s' (c.128: http://go.microsoft.com/fwlink/?linkid=853923).\r\n#pragma warning(disable: 26436) // warning C26436: The type '%s' with a virtual function needs either public, virtual or protected non-virtual destructor (c.35: http://go.microsoft.com/fwlink/?linkid=853924).\r\n#pragma warning(disable: 26439) // warning C26439: This kind of function may not throw. Declare it 'noexcept' (f.6: http://go.microsoft.com/fwlink/?linkid=853927).\r\n#pragma warning(disable: 26440) // warning C26440: Function '%s' can be declared 'noexcept' (f.6: http://go.microsoft.com/fwlink/?linkid=853927).\r\n#pragma warning(disable: 26443) // warning C26443: Overriding destructor should not use explicit 'override' or 'virtual' specifiers (c.128: http://go.microsoft.com/fwlink/?linkid=853923).\r\n#pragma warning(disable: 26462) // warning C26462: The value pointed to by '%s' is assigned only once, mark it as a pointer to const (con.4: https://go.microsoft.com/fwlink/p/?LinkID=784969).\r\n#pragma warning(disable: 26472) // warning C26472: Don't use a static_cast for arithmetic conversions. Use brace initialization, gsl::narrow_cast or gsl::narow (type.1: http://go.microsoft.com/fwlink/p/?LinkID=620417).\r\n#pragma warning(disable: 26474) // warning C26474: Don't cast between pointer types when the conversion could be implicit (type.1: http://go.microsoft.com/fwlink/p/?LinkID=620417).\r\n#pragma warning(disable: 26491) // warning C26491: Don't use static_cast downcasts (type.2: http://go.microsoft.com/fwlink/p/?LinkID=620418).\r\n#pragma warning(disable: 26498) // warning C26498: The function '%s' is constexpr, mark variable '%s' constexpr if compile-time evaluation is desired (con.5: https://go.microsoft.com/fwlink/p/?LinkID=784974).\r\n\r\n#endif\r\n\r\n#ifndef BOOST_CONFIG_SUPPRESS_OUTDATED_MESSAGE\r\n#define BOOST_CONFIG_SUPPRESS_OUTDATED_MESSAGE\r\n#endif\r\n\r\n#include <boost/algorithm/string.hpp>\r\n#include <boost/xpressive/xpressive.hpp>\r\n\r\n#include <gsl/gsl>\r\n\r\n#include <fmt/format.h>\r\n\r\n#if defined(_MSC_VER)\r\n\r\n#pragma warning(pop)\r\n#pragma warning(pop)\r\n\r\n#else\r\n\r\n// linux warning restoration goes here\r\n\r\n#endif\r\n\r\n#endif\r\n\r\n", "meta": {"hexsha": "96cd0edf7421232b3c36892d316e7828e745ec14", "size": 11401, "ext": "h", "lang": "C", "max_stars_repo_path": "examples/cpuid/libcpuid/test/src/cpuid/stdafx.h", "max_stars_repo_name": "DrPizza/jsm", "max_stars_repo_head_hexsha": "d5fc0a6c1e579bbb15c546aa3b76012ad93bc7ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-29T06:46:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-29T06:46:34.000Z", "max_issues_repo_path": "examples/cpuid/libcpuid/test/src/cpuid/stdafx.h", "max_issues_repo_name": "DrPizza/jsm", "max_issues_repo_head_hexsha": "d5fc0a6c1e579bbb15c546aa3b76012ad93bc7ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/cpuid/libcpuid/test/src/cpuid/stdafx.h", "max_forks_repo_name": "DrPizza/jsm", "max_forks_repo_head_hexsha": "d5fc0a6c1e579bbb15c546aa3b76012ad93bc7ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 64.7784090909, "max_line_length": 235, "alphanum_fraction": 0.7501096395, "num_tokens": 3006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.048136776578759734, "lm_q2_score": 0.020645932471674285, "lm_q1q2_score": 0.0009938286386491457}}
{"text": "#pragma once\n\n#define NOMINMAX\n#define NODRAWTEXT\n#define NOGDI\n#define NOBITMAP\n#define NOMCX\n#define NOSERVICE\n#define NOHELP\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <string_view>\n#include <sstream>\n#include <variant>\n#include <codecvt>\n#include <locale>\n#include <filesystem>\n#include <fstream>\n#include <chrono>\n#include <functional>\n#include <numeric>\n\n#ifndef _WIN32\n#include <wsl/winadapter.h>\n#include \"directml_guids.h\"\n#else\n#include <Windows.h>\n#endif\n#include <wil/result.h>\n#include <wrl/client.h>\n#include <gsl/gsl>\n#include <rapidjson/document.h>\n#include <rapidjson/istreamwrapper.h>\n#include <fmt/format.h>\n\n#ifdef _GAMING_XBOX_SCARLETT // Xbox Series X/S - Use GDK\n#include <d3d12_xs.h>\n#include <d3dx12_xs.h>\n#include <d3d12shader_xs.h>\n#include <dxcapi_xs.h>\n#include <pix3.h>\nusing IAdapter = IDXGIAdapter;\n#elif _GAMING_XBOX_XBOXONE // XboxOne - Use GDK\n#include <d3d12_x.h>\n#include <d3dx12_x.h>\n#include <d3d12shader_x.h>\n#include <dxcapi_x.h>\n#include <pix3.h>\nusing IAdapter = IDXGIAdapter;\n#else // Desktop/PC - Use DirectX-Headers\n#include <directx/d3d12.h>\n#include <directx/d3dx12.h>\n#include <directx/dxcore.h>\n#ifndef DXCOMPILER_NONE\n#include <directx/d3d12shader.h>\n#endif\n#include <dxcapi.h>\n#include <WinPixEventRuntime/pix3.h>\n\n#define IGraphicsUnknown IUnknown\n#define IID_GRAPHICS_PPV_ARGS IID_PPV_ARGS\nusing IAdapter = IDXCoreAdapter;\n#endif\n\n#include <DirectML.h>\n#include \"DirectMLX.h\"\n\n#include \"Logging.h\"", "meta": {"hexsha": "28bfeab2cedaf51911a7cb94b472114b5fcdf495", "size": 1474, "ext": "h", "lang": "C", "max_stars_repo_path": "DxDispatch/src/dxdispatch/pch.h", "max_stars_repo_name": "miaobin/DirectML", "max_stars_repo_head_hexsha": "d4657006a60a7b7d9baf17638c42aee27258c836", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2019-05-07T14:41:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-14T07:36:27.000Z", "max_issues_repo_path": "DxDispatch/src/dxdispatch/pch.h", "max_issues_repo_name": "miaobin/DirectML", "max_issues_repo_head_hexsha": "d4657006a60a7b7d9baf17638c42aee27258c836", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2019-05-10T09:12:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-09T01:51:06.000Z", "max_forks_repo_path": "DxDispatch/src/dxdispatch/pch.h", "max_forks_repo_name": "miaobin/DirectML", "max_forks_repo_head_hexsha": "d4657006a60a7b7d9baf17638c42aee27258c836", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2019-05-13T12:56:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-12T15:57:58.000Z", "avg_line_length": 21.0571428571, "max_line_length": 57, "alphanum_fraction": 0.7618724559, "num_tokens": 423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.058345842249068455, "lm_q2_score": 0.016914912864070344, "lm_q1q2_score": 0.000986914837623787}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef scene_048bb735_09b4_43d2_9ff5_5e40441c230b_h\r\n#define scene_048bb735_09b4_43d2_9ff5_5e40441c230b_h\r\n\r\n#include <gslib/std.h>\r\n#include <ariel/config.h>\r\n#include <ariel/rendersys.h>\r\n#include <ariel/framesys.h>\r\n#include <ariel/widget.h>\r\n\r\n__ariel_begin__\r\n\r\nclass rose;\r\nclass stage;\r\ntypedef list<stage*> stages;\r\n\r\nclass __gs_novtable stage abstract:\r\n    public frame_listener\r\n{\r\npublic:\r\n    stage();\r\n    virtual ~stage() {}\r\n    virtual const gchar* get_name() const = 0;\r\n    virtual bool setup() = 0;\r\n    virtual void draw() = 0;\r\n\r\npublic:\r\n    template<class _sty> inline\r\n    _sty* as() { return static_cast<_sty*>(this); }\r\n    template<class _sty> inline\r\n    const _sty* as_const() const { return static_cast<const _sty*>(this); }\r\n\r\nprotected:\r\n    stage*              _prev_presentation_stage;\r\n    stage*              _next_presentation_stage;\r\n    stage*              _prev_notification_stage;\r\n    stage*              _next_notification_stage;\r\n\r\nprotected:\r\n    void on_next_draw();\r\n    void on_next_frame_start();\r\n    void on_next_frame_end();\r\n    bool on_next_event(const frame_event& event);\r\n\r\npublic:\r\n    stage* prev_presentation_stage() const { return _prev_presentation_stage; }\r\n    stage* next_presentation_stage() const { return _next_presentation_stage; }\r\n    stage* prev_notification_stage() const { return _prev_notification_stage; }\r\n    stage* next_notification_stage() const { return _next_notification_stage; }\r\n\r\npublic:\r\n    static void connect_presentation_order(stage* stg1, stage* stg2);\r\n    static void connect_notification_order(stage* stg1, stage* stg2);\r\n    static void connect_presentation_order(stage* stg1, stage* stg2, stage* stg3);\r\n    static void connect_notification_order(stage* stg1, stage* stg2, stage* stg3);\r\n};\r\n\r\nclass ui_stage:\r\n    public stage\r\n{\r\npublic:\r\n    ui_stage(rose* r) { _rose = r; }\r\n    virtual const gchar* get_name() const override { return _t(\"ui\"); }\r\n    virtual bool setup() override;\r\n    virtual void draw() override;\r\n    virtual void on_frame_start() override { on_next_frame_start(); }\r\n    virtual void on_frame_end() override { on_next_frame_end(); }\r\n    virtual bool on_frame_event(const frame_event& event) override;\r\n\r\npublic:\r\n    wsys_manager* get_wsys_manager() { return &_wsys_manager; }\r\n\r\nprotected:\r\n    rose*               _rose;\r\n    wsys_manager        _wsys_manager;\r\n\r\nprivate:\r\n    void setup_draw();\r\n};\r\n\r\nclass scene:\r\n    public frame_listener\r\n{\r\npublic:\r\n    static scene* get_singleton_ptr()\r\n    {\r\n        static scene inst;\r\n        return &inst;\r\n    }\r\n\r\nprivate:\r\n    scene();\r\n\r\npublic:\r\n    ~scene();\r\n    stage* get_stage(const gchar* name);\r\n    wsys_manager* get_ui_system() const { return _uisys; }\r\n    fontsys* get_fontsys() const { return _fontsys; }\r\n    rendersys* get_rendersys() const { return _rendersys; }\r\n    void set_rendersys(rendersys* rsys) { _rendersys = rsys; }\r\n    void set_rose(rose* ptr) { _rose = ptr; }\r\n    void set_fontsys(fontsys* fsys);\r\n    void setup();\r\n    void destroy();\r\n    void destroy_all_stages();\r\n    void add_stage(stage* stg) { _stages.push_back(stg); }\r\n    void set_presentation_before(stage* pos, stage* tar);\r\n    void set_presentation_after(stage* pos, stage* tar);\r\n    void set_notification_before(stage* pos, stage* tar);\r\n    void set_notification_after(stage* pos, stage* tar);\r\n\r\nprotected:\r\n    rendersys*          _rendersys;\r\n    rose*               _rose;\r\n    stages              _stages;\r\n    wsys_manager*       _uisys;\r\n    fontsys*            _fontsys;\r\n    stage*              _notify;\r\n    stage*              _present;\r\n\r\nprotected:\r\n    void draw();\r\n\r\npublic:\r\n    virtual void on_frame_start() override;\r\n    virtual void on_frame_end() override;\r\n    virtual bool on_frame_event(const frame_event& event) override;\r\n};\r\n\r\n__ariel_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "8d4c8c9053e9db1b5d4eff49a8c71b097d54894a", "size": 5124, "ext": "h", "lang": "C", "max_stars_repo_path": "include/ariel/scene.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/ariel/scene.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ariel/scene.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 32.2264150943, "max_line_length": 83, "alphanum_fraction": 0.6799375488, "num_tokens": 1228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.037892424456625315, "lm_q2_score": 0.025957356821042256, "lm_q1q2_score": 0.0009835871824350115}}
{"text": "#ifndef PCH_H\n#define PCH_H\n\n#define ISOLATION_AWARE_ENABLED 1\n\n/*\n    Only put files that never change or are rarely changed in this file.\n    An include graph will be provided for some headers that were not explicit\n    added. VC++ is a requirement.\n\n    We don't care about warnings for library files.\n*/\n#pragma warning(push)\n#pragma warning(disable : 4091 4191 4365 4464 4571 4619 4623 4625 4626 4768 4774 5026 5027 5039 5045)\n/* Windows Stuff */\n#include \"windows_nodefines.h\"\n#include <ShlObj.h> // CommCtrl\n#include <WindowsX.h>\n#include <atlbase.h> // atldef.h (Windows.h), atlcore.h (tchar.h), Shlwapi.h\n#include <direct.h>\n#include <io.h>\n#include <wincodec.h>\n\n#if WIN32_LEAN_AND_MEAN\n#include <CommDlg.h>\n#include <MMSystem.h>\n#include <ShellAPI.h>\n#endif // WIN32_LEAN_AND_MEAN\n\n/*\n    Nuke WinAPI #defines - anything including this file should be using the\n    ra versions.\n*/\n#undef CreateDirectory\n#undef GetMessage\n\n/* C Stuff */\n#include <cctype>\n\n/* STL Stuff */\n#include <array> // algorithm, iterator, tuple\n#include <atomic>\n#include <fstream>\n#include <iomanip>\n#include <map>\n#include <memory>\n#include <mutex> // chrono (time.h), functional, thread, utility\n#include <queue> // deque, vector, algorithm\n#include <set>\n#include <sstream> // string\n#include <stack>\n#include <unordered_map>\n#include <variant>\n\n#pragma warning(push)\n// Look at this file if you want to know what they are and what they mean\n#include \"pch_cppcorecheck_suppressions.h\"\n#include \"pch_microsoft_suppressions.h\"\n\n/* RapidJSON Stuff */\n#define RAPIDJSON_HAS_STDSTRING 1\n#define RAPIDJSON_NOMEMBERITERATORCLASS 1\n#include <rapidjson\\document.h> // has reader.h\n#include <rapidjson\\error\\en.h>\n#include <rapidjson\\istreamwrapper.h>\n#include <rapidjson\\ostreamwrapper.h>\n#include <rapidjson\\writer.h> // has stringbuffer.h\n\n/* gsl stuff */\n#define GSL_THROW_ON_CONTRACT_VIOLATION\n#include <gsl\\gsl>\n\n// the default GSL Expects() macro throws an exception, which we don't try to catch anywhere.\n// replace it with our custom handler, which will log and report the error before throwing it.\n#ifndef RA_UTEST\n #ifdef NDEBUG\n  extern void __gsl_contract_handler(const char* const file, unsigned int line);\n  #undef Expects\n  #define Expects(cond) (GSL_LIKELY(cond) ? static_cast<void>(0) : __gsl_contract_handler(__FILE__, __LINE__))\n #else\n  extern void __gsl_contract_handler(const char* const file, unsigned int line, const char* const error);\n  #undef Expects\n  #define Expects(cond) (GSL_LIKELY(cond) ? static_cast<void>(0) : __gsl_contract_handler(__FILE__, __LINE__, GSL_STRINGIFY(cond)))\n #endif\n#endif\n\n#pragma warning(pop)\n\n#if RA_UTEST\n#include <CodeAnalysis\\Warnings.h>\n#pragma warning(push)\n#pragma warning(disable : ALL_CPPCORECHECK_WARNINGS)\n#include \"CppUnitTest.h\"\n#pragma warning(pop)\n#endif /* RA_UTEST */\n\n/* rcheevos stuff */\n#pragma warning(push)\n#pragma warning(disable : 4201) // nameless struct\n#include <rcheevos.h>\n#pragma warning(pop)\n#pragma warning(pop)\n\n#endif /* !PCH_H */\n", "meta": {"hexsha": "02ed11f3ecaa8f96ed8b43c1127a81003a10a881", "size": 2999, "ext": "h", "lang": "C", "max_stars_repo_path": "src/pch.h", "max_stars_repo_name": "Jamiras/RAIntegration", "max_stars_repo_head_hexsha": "ccf3dea24d81aefdcf51535f073889d03272b259", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 71.0, "max_stars_repo_stars_event_min_datetime": "2018-04-15T13:02:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T11:19:18.000Z", "max_issues_repo_path": "src/pch.h", "max_issues_repo_name": "Jamiras/RAIntegration", "max_issues_repo_head_hexsha": "ccf3dea24d81aefdcf51535f073889d03272b259", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 309.0, "max_issues_repo_issues_event_min_datetime": "2018-04-15T12:10:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-22T20:13:04.000Z", "max_forks_repo_path": "src/pch.h", "max_forks_repo_name": "Jamiras/RAIntegration", "max_forks_repo_head_hexsha": "ccf3dea24d81aefdcf51535f073889d03272b259", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2018-04-17T16:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T08:49:03.000Z", "avg_line_length": 28.5619047619, "max_line_length": 131, "alphanum_fraction": 0.7475825275, "num_tokens": 790, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.0695417406490685, "lm_q2_score": 0.014063627766405478, "lm_q1q2_score": 0.0009780091547164083}}
{"text": "/**\n *  Copyright (C) 2021 FISCO BCOS.\n *  SPDX-License-Identifier: Apache-2.0\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n * @brief tars implementation for Block\n * @file BlockImpl.h\n * @author: ancelmo\n * @date 2021-04-20\n */\n#pragma once\n#include \"BlockHeaderImpl.h\"\n#include \"TransactionImpl.h\"\n#include \"TransactionMetaDataImpl.h\"\n#include \"TransactionReceiptImpl.h\"\n#include \"bcos-tars-protocol/Common.h\"\n#include \"bcos-tars-protocol/tars/Block.h\"\n#include \"interfaces/protocol/Transaction.h\"\n#include <bcos-framework/interfaces/crypto/CryptoSuite.h>\n#include <bcos-framework/interfaces/protocol/Block.h>\n#include <bcos-framework/interfaces/protocol/BlockHeader.h>\n#include <gsl/span>\n#include <memory>\n\nnamespace bcostars\n{\nnamespace protocol\n{\nclass BlockImpl : public bcos::protocol::Block, public std::enable_shared_from_this<BlockImpl>\n{\npublic:\n    BlockImpl(bcos::protocol::TransactionFactory::Ptr _transactionFactory,\n        bcos::protocol::TransactionReceiptFactory::Ptr _receiptFactory)\n      : bcos::protocol::Block(_transactionFactory, _receiptFactory),\n        m_inner(std::make_shared<bcostars::Block>()),\n        x_mutex(std::make_shared<std::mutex>())\n    {}\n\n    ~BlockImpl() override{};\n\n    void decode(bcos::bytesConstRef _data, bool _calculateHash, bool _checkSig) override;\n    void encode(bcos::bytes& _encodeData) const override;\n\n    int32_t version() const override { return m_inner->blockHeader.data.version; }\n    void setVersion(int32_t _version) override { m_inner->blockHeader.data.version = _version; }\n\n    bcos::protocol::BlockType blockType() const override\n    {\n        return (bcos::protocol::BlockType)m_inner->type;\n    }\n    // FIXME: this will cause the same blockHeader calculate hash multiple times\n    bcos::protocol::BlockHeader::Ptr blockHeader() override;\n    bcos::protocol::BlockHeader::ConstPtr blockHeaderConst() const override;\n\n    bcos::protocol::Transaction::ConstPtr transaction(size_t _index) const override;\n    bcos::protocol::TransactionReceipt::ConstPtr receipt(size_t _index) const override;\n\n    // get transaction metaData\n    bcos::protocol::TransactionMetaData::ConstPtr transactionMetaData(size_t _index) const override;\n    void setBlockType(bcos::protocol::BlockType _blockType) override\n    {\n        m_inner->type = (int32_t)_blockType;\n    }\n\n    // set blockHeader\n    void setBlockHeader(bcos::protocol::BlockHeader::Ptr _blockHeader) override;\n\n    void setTransaction(size_t _index, bcos::protocol::Transaction::Ptr _transaction) override\n    {\n        m_inner->transactions[_index] =\n            std::dynamic_pointer_cast<bcostars::protocol::TransactionImpl>(_transaction)->inner();\n    }\n    void appendTransaction(bcos::protocol::Transaction::Ptr _transaction) override\n    {\n        m_inner->transactions.emplace_back(\n            std::dynamic_pointer_cast<bcostars::protocol::TransactionImpl>(_transaction)->inner());\n    }\n\n    void setReceipt(size_t _index, bcos::protocol::TransactionReceipt::Ptr _receipt) override;\n    void appendReceipt(bcos::protocol::TransactionReceipt::Ptr _receipt) override;\n\n    void appendTransactionMetaData(bcos::protocol::TransactionMetaData::Ptr _txMetaData) override;\n\n    // get transactions size\n    size_t transactionsSize() const override { return m_inner->transactions.size(); }\n    size_t transactionsMetaDataSize() const override;\n    // get receipts size\n    size_t receiptsSize() const override { return m_inner->receipts.size(); }\n\n    void setNonceList(bcos::protocol::NonceList const& _nonceList) override;\n    void setNonceList(bcos::protocol::NonceList&& _nonceList) override;\n    bcos::protocol::NonceList const& nonceList() const override;\n\n    const bcostars::Block& inner() const { return *m_inner; }\n    void setInner(const bcostars::Block& inner) { *m_inner = inner; }\n    void setInner(bcostars::Block&& inner) { *m_inner = std::move(inner); }\n\nprivate:\n    std::shared_ptr<bcostars::Block> m_inner;\n    mutable bcos::protocol::NonceList m_nonceList;\n    std::shared_ptr<std::mutex> x_mutex;\n};\n}  // namespace protocol\n}  // namespace bcostars", "meta": {"hexsha": "6ab9dbd5957a443cb41b4652675bb24d93a8e6be", "size": 4609, "ext": "h", "lang": "C", "max_stars_repo_path": "bcos-tars-protocol/protocol/BlockImpl.h", "max_stars_repo_name": "xueying4402/FISCO-BCOS", "max_stars_repo_head_hexsha": "737e08752e8904c7c24e3737f8f46bf5327ef792", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bcos-tars-protocol/protocol/BlockImpl.h", "max_issues_repo_name": "xueying4402/FISCO-BCOS", "max_issues_repo_head_hexsha": "737e08752e8904c7c24e3737f8f46bf5327ef792", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 20.0, "max_issues_repo_issues_event_min_datetime": "2021-09-14T12:23:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-07T14:19:09.000Z", "max_forks_repo_path": "bcos-tars-protocol/protocol/BlockImpl.h", "max_forks_repo_name": "xueying4402/FISCO-BCOS", "max_forks_repo_head_hexsha": "737e08752e8904c7c24e3737f8f46bf5327ef792", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-09-08T02:39:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-06T06:35:57.000Z", "avg_line_length": 40.4298245614, "max_line_length": 100, "alphanum_fraction": 0.7359513994, "num_tokens": 1107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07159119746371433, "lm_q2_score": 0.013636836659411029, "lm_q1q2_score": 0.0009762774660643133}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n//\n// Copyright (c) 2015 Microsoft Corporation. All rights reserved.\n//\n// This code is licensed under the MIT License (MIT).\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef GSL_POINTERS_H\n#define GSL_POINTERS_H\n\n#include <gsl/gsl_assert>  // for Ensures, Expects\n\n#include <algorithm>    // for forward\n#include <iosfwd>       // for ptrdiff_t, nullptr_t, ostream, size_t\n#include <memory>       // for shared_ptr, unique_ptr\n#include <system_error> // for hash\n#include <type_traits>  // for enable_if_t, is_convertible, is_assignable\n\n#if defined(_MSC_VER) && _MSC_VER < 1910\n#pragma push_macro(\"constexpr\")\n#define constexpr /*constexpr*/\n\n#endif                          // defined(_MSC_VER) && _MSC_VER < 1910\n\nnamespace gsl\n{\n\n//\n// GSL.owner: ownership pointers\n//\nusing std::unique_ptr;\nusing std::shared_ptr;\n\n//\n// owner\n//\n// owner<T> is designed as a bridge for code that must deal directly with owning pointers for some reason\n//\n// T must be a pointer type\n// - disallow construction from any type other than pointer type\n//\ntemplate <class T, class = std::enable_if_t<std::is_pointer<T>::value>>\nusing owner = T;\n\n//\n// not_null\n//\n// Restricts a pointer or smart pointer to only hold non-null values.\n//\n// Has zero size overhead over T.\n//\n// If T is a pointer (i.e. T == U*) then\n// - allow construction from U*\n// - disallow construction from nullptr_t\n// - disallow default construction\n// - ensure construction from null U* fails\n// - allow implicit conversion to U*\n//\ntemplate <class T>\nclass not_null\n{\npublic:\n    static_assert(std::is_assignable<T&, std::nullptr_t>::value, \"T cannot be assigned nullptr.\");\n\n    template <typename U, typename = std::enable_if_t<std::is_convertible<U, T>::value>>\n    constexpr explicit not_null(U&& u) : ptr_(std::forward<U>(u))\n    {\n        Expects(ptr_ != nullptr);\n    }\n\n    template <typename = std::enable_if_t<!std::is_same<std::nullptr_t, T>::value>>\n    constexpr explicit not_null(T u) : ptr_(u)\n    {\n        Expects(ptr_ != nullptr);\n    }\n\n    template <typename U, typename = std::enable_if_t<std::is_convertible<U, T>::value>>\n    constexpr not_null(const not_null<U>& other) : not_null(other.get())\n    {\n    }\n\n    not_null(not_null&& other) = default;\n    not_null(const not_null& other) = default;\n    not_null& operator=(const not_null& other) = default;\n\n    constexpr T get() const\n    {\n        Ensures(ptr_ != nullptr);\n        return ptr_;\n    }\n\n    constexpr operator T() const { return get(); }\n    constexpr T operator->() const { return get(); }\n    constexpr decltype(auto) operator*() const { return *get(); } \n\n    // prevents compilation when someone attempts to assign a null pointer constant\n    not_null(std::nullptr_t) = delete;\n    not_null& operator=(std::nullptr_t) = delete;\n\n    // unwanted operators...pointers only point to single objects!\n    not_null& operator++() = delete;\n    not_null& operator--() = delete;\n    not_null operator++(int) = delete;\n    not_null operator--(int) = delete;\n    not_null& operator+=(std::ptrdiff_t) = delete;\n    not_null& operator-=(std::ptrdiff_t) = delete;\n    void operator[](std::ptrdiff_t) const = delete;\n\nprivate:\n    T ptr_;\n};\n\ntemplate <class T>\nauto make_not_null(T&& t) {\n    return gsl::not_null<std::remove_cv_t<std::remove_reference_t<T>>>{std::forward<T>(t)};\n}\n\ntemplate <class T>\nstd::ostream& operator<<(std::ostream& os, const not_null<T>& val)\n{\n    os << val.get();\n    return os;\n}\n\ntemplate <class T, class U>\nauto operator==(const not_null<T>& lhs, const not_null<U>& rhs) -> decltype(lhs.get() == rhs.get())\n{\n    return lhs.get() == rhs.get();\n}\n\ntemplate <class T, class U>\nauto operator!=(const not_null<T>& lhs, const not_null<U>& rhs) -> decltype(lhs.get() != rhs.get())\n{\n    return lhs.get() != rhs.get();\n}\n\ntemplate <class T, class U>\nauto operator<(const not_null<T>& lhs, const not_null<U>& rhs) -> decltype(lhs.get() < rhs.get())\n{\n    return lhs.get() < rhs.get();\n}\n\ntemplate <class T, class U>\nauto operator<=(const not_null<T>& lhs, const not_null<U>& rhs) -> decltype(lhs.get() <= rhs.get())\n{\n    return lhs.get() <= rhs.get();\n}\n\ntemplate <class T, class U>\nauto operator>(const not_null<T>& lhs, const not_null<U>& rhs) -> decltype(lhs.get() > rhs.get())\n{\n    return lhs.get() > rhs.get();\n}\n\ntemplate <class T, class U>\nauto operator>=(const not_null<T>& lhs, const not_null<U>& rhs) -> decltype(lhs.get() >= rhs.get())\n{\n    return lhs.get() >= rhs.get();\n}\n\n// more unwanted operators\ntemplate <class T, class U>\nstd::ptrdiff_t operator-(const not_null<T>&, const not_null<U>&) = delete;\ntemplate <class T>\nnot_null<T> operator-(const not_null<T>&, std::ptrdiff_t) = delete;\ntemplate <class T>\nnot_null<T> operator+(const not_null<T>&, std::ptrdiff_t) = delete;\ntemplate <class T>\nnot_null<T> operator+(std::ptrdiff_t, const not_null<T>&) = delete;\n\n} // namespace gsl\n\nnamespace std\n{\ntemplate <class T>\nstruct hash<gsl::not_null<T>>\n{\n    std::size_t operator()(const gsl::not_null<T>& value) const { return hash<T>{}(value); }\n};\n\n} // namespace std\n\n#if defined(_MSC_VER) && _MSC_VER < 1910\n#undef constexpr\n#pragma pop_macro(\"constexpr\")\n\n#endif // defined(_MSC_VER) && _MSC_VER < 1910\n\n#endif // GSL_POINTERS_H\n", "meta": {"hexsha": "a338856118419e8b1a10648677a8cb392177ef99", "size": 5819, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gsl/pointers.h", "max_stars_repo_name": "Redchards/CVRP", "max_stars_repo_head_hexsha": "f372f2fa06cb374ebdac2f6eee7e6fe297d94103", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-09-01T14:40:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-15T05:01:23.000Z", "max_issues_repo_path": "include/gsl/pointers.h", "max_issues_repo_name": "Redchards/CVRP", "max_issues_repo_head_hexsha": "f372f2fa06cb374ebdac2f6eee7e6fe297d94103", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gsl/pointers.h", "max_forks_repo_name": "Redchards/CVRP", "max_forks_repo_head_hexsha": "f372f2fa06cb374ebdac2f6eee7e6fe297d94103", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-02T17:50:23.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-26T08:25:35.000Z", "avg_line_length": 29.2412060302, "max_line_length": 105, "alphanum_fraction": 0.654236123, "num_tokens": 1455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.04603389847295304, "lm_q2_score": 0.02096424070343657, "lm_q1q2_score": 0.0009650657281045487}}
{"text": "/*\n   Copyright [2017-2020] [IBM Corporation]\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n       http://www.apache.org/licenses/LICENSE-2.0\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n#ifndef __FABRIC_CONNECTION_BASE_H__\n#define __FABRIC_CONNECTION_BASE_H__\n\n#include \"mcas_config.h\"\n\n#include \"buffer_manager.h\" /* Buffer_manager */\n\n#include <api/fabric_itf.h> /* IFabric_memory_region, IFabric_server */\n#include <gsl/pointers>\n#include <algorithm>\n#include <list>\n#include <queue>\n\nnamespace mcas\n{\n\nstruct open_connection_construct_key;\n\nstruct open_connection\n{\nprivate:\n  gsl::not_null<component::IFabric_server_factory *> _factory;\n  gsl::not_null<component::IFabric_server *>         _transport;\npublic:\n  open_connection(\n    gsl::not_null<component::IFabric_server_factory *> factory_\n    , gsl::not_null<component::IFabric_server *> transport_\n    , const open_connection_construct_key &\n    )\n    : _factory(factory_)\n    , _transport(transport_)\n  {}\n\n  open_connection(const open_connection &) = delete;\n  open_connection &operator=(const open_connection &) = delete;\n\n  auto transport() const { return _transport; }\n\n  ~open_connection()\n  {\n    /* close connection */\n    _factory->close_connection(_transport);\n  }\n};\n\nclass Fabric_connection_base : protected common::log_source {\n\n public:\n  friend class Connection;\n  friend class Shard;\n  using memory_region_t = component::IFabric_memory_region *;\n\n protected:\n  using buffer_t = Buffer_manager<component::IFabric_memory_control>::buffer_internal;\n  using pool_t   = component::IKVStore::pool_t;\n\n  enum class action_type {\n        ACTION_NONE = 0, /* unused */\n        ACTION_RELEASE_VALUE_LOCK_SHARED,\n#if 0\n        ACTION_RELEASE_VALUE_LOCK_EXCLUSIVE, /* unused */\n        ACTION_POOL_DELETE, /* unused */\n#endif\n  };\n\n  /* deferred actions */\n  struct action_t {\n    action_type op;\n    void *parm;\n  };\n\n  enum class Completion_state {\n    COMPLETIONS,\n    CLIENT_DISCONNECT,\n    NONE,\n  };\n\n private:\n  std::unique_ptr<component::IFabric_endpoint_unconnected_server> _preconnection;\n  Buffer_manager<component::IFabric_memory_control> _bm;\n\n  /* xx_buffer_outstanding is the signal for completion,\n     xx_buffer is the buffer pointer that needs to be freed (and set to null)\n  */\nprotected:\n  unsigned              _recv_buffer_posted_count;\nprivate:\n  unsigned              _send_buffer_posted_count;\n\nprotected:\n  /* values for two-phase get\n   */\n  unsigned _send_value_posted_count;\nprivate:\n\n  std::list<buffer_t *> _completed_recv_buffers;\n\n  open_connection _oc;\n protected:\n  size_t                             _max_message_size;\n\n  /* Filled by base class     check_for_posted_value_complete\n   * Drained by derived class check_network_completions\n   */\n  std::queue<action_t> _deferred_unlock;\n\n  /**\n   * Ctor\n   *\n   * @param factory\n   * @param fabric_connection\n   */\n  explicit Fabric_connection_base( //\n    unsigned                           debug_level_,\n    gsl::not_null<component::IFabric_server_factory *>factory,\n    std::unique_ptr<component::IFabric_endpoint_unconnected_server> && preconnection);\n\n  Fabric_connection_base(const Fabric_connection_base &) = delete;\n  Fabric_connection_base &operator=(const Fabric_connection_base &) = delete;\n\n  virtual ~Fabric_connection_base();\n\n  static void static_send_callback(void *cnxn, buffer_t *iob) noexcept\n  {\n    static_cast<Fabric_connection_base *>(cnxn)->send_callback(iob);\n  }\n\n  void send_callback(buffer_t *iob) noexcept\n  {\n    --_send_buffer_posted_count;\n    posted_count_log();\n    CPLOG(2, \"Completed send (%p) freeing buffer\", common::p_fmt(iob));\n    free_buffer(iob);\n  }\n\n  static void static_recv_callback(void *cnxn, buffer_t *iob) noexcept\n  {\n    static_cast<Fabric_connection_base *>(cnxn)->recv_callback(iob);\n  }\n\n  void recv_callback(buffer_t *iob) noexcept\n  {\n    --_recv_buffer_posted_count;\n    posted_count_log();\n    _completed_recv_buffers.push_front(iob);\n    CPLOG(2, \"Completed recv (%p) (complete %zu)\", common::p_fmt(iob), _completed_recv_buffers.size());\n  }\n\n  static void completion_callback(void *   context,\n                                  status_t st,\n                                  std::uint64_t,  // completion_flags,\n                                  std::size_t len,\n                                  void *      error_data,\n                                  void *      cnxn) noexcept\n  {\n    if (LIKELY(st == S_OK)) {\n      auto iob = static_cast<buffer_t *>(context);\n      iob->completion_cb(cnxn, iob);\n    }\n    else {\n      PERR(\"Fabric_connection_base: fabric operation failed st != S_OK (st=%d, \"\n           \"context=%p, len=%lu)\",\n           st, context, len);\n      PERR(\"Error: %s\", static_cast<char *>(error_data));\n    }\n  }\n\n  bool check_for_posted_recv_complete()\n  {\n    /* don't free buffer (such as above); it will be used for response */\n    //    return _recv_buffer_posted_outstanding == false;\n    return _completed_recv_buffers.size() > 0;\n  }\n\n  void free_recv_buffer()\n  {\n    for (auto b : _completed_recv_buffers) {      \n      free_buffer(b);\n    }\n  }\n\n  size_t recv_buffer_posted_count() const {\n    return _recv_buffer_posted_count;\n  }\n\n  void post_recv_buffer(buffer_t *buffer)\n  {\n    _preconnection->post_recv(buffer->iov, buffer->iov + 1, buffer->desc, buffer);\n    ++_recv_buffer_posted_count;\n    posted_count_log();\n    CPLOG(2, \"Posted recv (%p) (complete %zu)\", common::p_fmt(buffer), _completed_recv_buffers.size());\n  }\n\n  void post_send_buffer(gsl::not_null<buffer_t *> buffer)\n  {\n    const auto iov = buffer->iov;\n\n    /* if packet is small enough use inject */\n    if (iov->iov_len <= transport()->max_inject_size()) {\n      CPLOG(2, \"Fabric_connection_base: posting send with inject (iob %p %p,len=%lu)\",\n             common::p_fmt(buffer), iov->iov_base, iov->iov_len);\n\n      transport()->inject_send(iov->iov_base, iov->iov_len);\n      CPLOG(2, \"%s: buffer %p\", __func__, common::p_fmt(buffer));\n      free_buffer(buffer); /* buffer is immediately complete fi_inject */\n    }\n    else {\n      CPLOG(2, \"Fabric_connection_base: posting send (%p, %p)\", common::p_fmt(buffer), iov->iov_base);\n\n      transport()->post_send(iov, iov + 1, buffer->desc, buffer);\n      ++_send_buffer_posted_count;\n      posted_count_log();\n      CPLOG(2, \"%s buffer (%p)\", __func__, common::p_fmt(buffer));\n    }\n  }\n\n  void post_send_buffer2(gsl::not_null<buffer_t *> buffer, const ::iovec &val_iov, void *val_desc)\n  {\n    buffer->iov[1] = val_iov;\n    buffer->desc[1] = val_desc;\n\n    ++_send_buffer_posted_count;\n    posted_count_log();\n    CPLOG(2, \"Posted send (%p) ... value (%.*s) (len=%lu,ptr=%p)\", common::p_fmt(buffer),\n         int(val_iov.iov_len), static_cast<char *>(val_iov.iov_base), val_iov.iov_len, val_iov.iov_base);\n\n    transport()->post_send(buffer->iov, buffer->iov + 2, buffer->desc, buffer);\n  }\n\n  buffer_t *posted_recv()\n  {\n    if (_completed_recv_buffers.size() == 0) return nullptr;\n\n    auto iob = _completed_recv_buffers.back();\n    _completed_recv_buffers.pop_back();\n    CPLOG(2, \"Presented recv (%p) (complete %zu)\", common::p_fmt(iob), _completed_recv_buffers.size());\n    return iob;\n  }\n\n  void posted_count_log() const\n  {\n    CPLOG(2, \"POSTs recv %u send %u value %u\", _recv_buffer_posted_count, _send_buffer_posted_count,\n           _send_value_posted_count);\n  }\n\n  Completion_state poll_completions()\n  {\n    if (_recv_buffer_posted_count != 0 || _send_buffer_posted_count != 0 || _send_value_posted_count != 0) {\n#if 0\n      PLOG(\"%s posted_recv %u posted_send %u posted_value %u\", __func__, _recv_buffer_posted_count, _send_buffer_posted_count, _send_value_posted_count);\n#endif\n      try {\n        transport()->poll_completions(&Fabric_connection_base::completion_callback, this);\n        return Completion_state::COMPLETIONS;\n      }\n      catch (const std::logic_error &e) {\n        return Completion_state::CLIENT_DISCONNECT;\n      }\n    }\n    return Completion_state::NONE;\n  }\n\n  /**\n   * Forwarders that allow us to avoid exposing transport() and _bm\n   *\n   */\n public:\n  inline auto register_memory(const void *base, size_t len, std::uint64_t key, std::uint64_t flags)\n  {\n    return transport()->register_memory(base, len, key, flags); /* flags not supported for verbs */\n  }\n\n  inline void deregister_memory(memory_region_t region) { return transport()->deregister_memory(region); }\n\n  inline void *get_memory_descriptor(memory_region_t region) { return transport()->get_memory_descriptor(region); }\n\n  inline uint64_t get_memory_remote_key(memory_region_t region) { return transport()->get_memory_remote_key(region); }\n\n protected:\n  inline auto allocate(buffer_t::completion_t c) { return _bm.allocate(c); }\n\n  inline void free_buffer(buffer_t *buffer) { _bm.free(buffer); }\n\n  inline size_t IO_buffer_size() const { return Buffer_manager<component::IFabric_memory_control>::BUFFER_LEN; }\n\n  gsl::not_null<component::IFabric_server *> transport() const { return _oc.transport(); }\n\n  inline std::string get_local_addr() { return transport()->get_local_addr(); }\n};\n\nstruct open_connection_construct_key\n{\nprivate:\n  open_connection_construct_key() {};\npublic:\n  friend class Fabric_connection_base;\n};\n\n}  // namespace mcas\n\n#endif  // __FABRIC_CONNECTION_BASE_H__\n", "meta": {"hexsha": "b77983ba1712bba0ad70c148e89a3696db8be530", "size": 9672, "ext": "h", "lang": "C", "max_stars_repo_path": "src/server/mcas/src/fabric_connection_base.h", "max_stars_repo_name": "fQuinzan/mcas", "max_stars_repo_head_hexsha": "efaf438eb20cffa18b13f176c74a2b3153f89c07", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/server/mcas/src/fabric_connection_base.h", "max_issues_repo_name": "fQuinzan/mcas", "max_issues_repo_head_hexsha": "efaf438eb20cffa18b13f176c74a2b3153f89c07", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/server/mcas/src/fabric_connection_base.h", "max_forks_repo_name": "fQuinzan/mcas", "max_forks_repo_head_hexsha": "efaf438eb20cffa18b13f176c74a2b3153f89c07", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8025477707, "max_line_length": 153, "alphanum_fraction": 0.6876550868, "num_tokens": 2364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.05184546518477176, "lm_q2_score": 0.018546564478212336, "lm_q1q2_score": 0.0009615552629522822}}
{"text": "\n#if !defined(STRIPWS_H_INCLUDED)\n#define STRIPWS_H_INCLUDED\n\n#include \"FileEnumerator.h\"\n#include \"Utils.h\"\n\n#include <filesystem>\n#include <gsl/gsl>\n#include <iosfwd>\n#include <string>\n\nclass StripWS\n{\npublic:\n\tstatic int usage(::std::ostream& strm, const ::std::string& progName,\n\t\tconst char* pMsg);\n\n\tStripWS(::gsl::span<const char*const> args);\n\tint run() const;\n\n\tStripWS(const StripWS&) = delete;\n\tStripWS& operator=(const StripWS&) = delete;\n\tStripWS(StripWS&&) = delete;\n\tStripWS& operator=(StripWS&&) = delete;\n\nPRIVATE_EXCEPT_IN_TEST:\n\tusing Path = ::std::filesystem::path;\n\n\tvoid queryFile(const Path& p) const;\n\tvoid translateFile(const Path& p) const;\n\n\t/// \\brief Scans the input file, counts the occurrences of white space at\n\t/// the end of a line, and optionally strips them into the provided stream.\n\t///\n\t/// If pOut is null, then the method simply counts the occurrences of white\n\t/// space at the end of a line.\n\t///\n\t/// If pOut is not null, then the method additionally translates the file\n\t/// into *pOut.\n\tstatic void scanFile(::std::istream& in, /* out */ size_t& numLinesAffected,\n\t\t/* out */ size_t& numSpacesStripped, /* out */ size_t& numTabsStripped,\n\t\t::std::ostream* pOut = nullptr);\n\n\tstatic void updateCounts(::std::string const& wsRun,\n\t\t/* in-out */ size_t& numLinesAffected,\n\t\t/* in-out */ size_t& numSpacesStripped,\n\t\t/* in-out */ size_t& numTabsStripped);\n\tstatic void replaceOriginalFileWithTemp(const Path& originalPath,\n\t\tconst Path& tempPath);\n\n\tbool\t\t\t\tm_isInQueryMode;\n\tFileEnumerator\tm_fileEnumerator;\n};\n\n#endif // STRIPWS_H_INCLUDED\n", "meta": {"hexsha": "6e25d82d4bc67212295743681914d1318e1614ae", "size": 1584, "ext": "h", "lang": "C", "max_stars_repo_path": "StripWS.h", "max_stars_repo_name": "IanEmmons/CmdLineUtil", "max_stars_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "StripWS.h", "max_issues_repo_name": "IanEmmons/CmdLineUtil", "max_issues_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "StripWS.h", "max_forks_repo_name": "IanEmmons/CmdLineUtil", "max_forks_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7894736842, "max_line_length": 77, "alphanum_fraction": 0.7140151515, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.05582313485146052, "lm_q2_score": 0.017176710521657357, "lm_q1q2_score": 0.0009588578277549794}}
{"text": "\n#if !defined(ISPLAINASCII_H_INCLUDED)\n#define ISPLAINASCII_H_INCLUDED\n\n#include \"FileEnumerator.h\"\n#include \"Utils.h\"\n\n#include <filesystem>\n#include <gsl/gsl>\n#include <iosfwd>\n#include <string>\n\nclass IsPlainAscii\n{\npublic:\n\tstatic int usage(::std::ostream& strm, const ::std::string& progName,\n\t\tconst char* pMsg);\n\n\tIsPlainAscii(::gsl::span<const char*const> args);\n\tint run() const;\n\n\tIsPlainAscii(const IsPlainAscii&) = delete;\n\tIsPlainAscii& operator=(const IsPlainAscii&) = delete;\n\tIsPlainAscii(IsPlainAscii&&) = delete;\n\tIsPlainAscii& operator=(IsPlainAscii&&) = delete;\n\nPRIVATE_EXCEPT_IN_TEST:\n\tusing Path = ::std::filesystem::path;\n\n\tstatic void scanFile(const Path& filePath);\n\tstatic void scanFile2(const Path& filePath, ::std::istream& in,\n\t\t::std::ostream& out);\n\tstatic void reportNonAsciiRun(const Path& filePath, unsigned long lineNum,\n\t\tunsigned long approxColNum, ::std::string& nonAsciiRun, ::std::ostream& out);\n\n\tFileEnumerator m_fileEnumerator;\n};\n\n#endif // ISPLAINASCII_H_INCLUDED\n", "meta": {"hexsha": "6aac436b4e23e8fb7467ca16705ff079f47f2c62", "size": 1010, "ext": "h", "lang": "C", "max_stars_repo_path": "IsPlainAscii.h", "max_stars_repo_name": "IanEmmons/CmdLineUtil", "max_stars_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "IsPlainAscii.h", "max_issues_repo_name": "IanEmmons/CmdLineUtil", "max_issues_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IsPlainAscii.h", "max_forks_repo_name": "IanEmmons/CmdLineUtil", "max_forks_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.25, "max_line_length": 79, "alphanum_fraction": 0.7465346535, "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06008664344151497, "lm_q2_score": 0.01590639249904534, "lm_q1q2_score": 0.0009557617345309257}}
{"text": "// SPDX-License-Identifier: MIT\n// The MIT License (MIT)\n//\n// Copyright (c) 2014-2018, Institute for Software & Systems Engineering\n// Copyright (c) 2018-2019, Johannes Leupolz\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n#ifndef PEMC_GENERIC_TRAVERSER_PATH_TRACKER_H_\n#define PEMC_GENERIC_TRAVERSER_PATH_TRACKER_H_\n\n#include <vector>\n#include <gsl/span>\n#include <cstdint>\n#include <atomic>\n#include <stack>\n#include <limits>\n\n#include \"pemc/basic/tsc_index.h\"\n#include \"pemc/basic/label.h\"\n#include \"pemc/basic/model_capacity.h\"\n#include \"pemc/basic/raw_memory.h\"\n#include \"pemc/formula/formula.h\"\n\nnamespace pemc {\n  struct PathFrame {\n    // the offset into the states array where the index of the frame's first state is stored.\n    int32_t indexOfFirstStateIndexEntry; //offset\n    // the number of states the frame consists of.\n    int32_t count;\n  };\n\n  ///   When enumerating all states of a model in a depth-first fashion, we have to store the next states (that are computed all\n\t///   at once) somewhere while also being able to generate the counter example. When check a new state, a new frame is allocated\n\t///   on the stack and all unknown successor states are stored in that frame. We then take the topmost state, compute its\n\t///   successor states, and so on. When a formula violation is detected, the counter example consists of the last states of each\n\t///   frame on the stack. When a frame has been fully enumerated without detecting a formula violation, the stack frame is\n\t///   removed, the topmost state of the topmost frame is removed, and the new topmost state is checked.\n  class PathTracker {\n  private:\n      std::vector<PathFrame> pathFrames;\n      std::vector<StateIndex> stateIndexEntries;\n\n      ///   The lowest index of a splittable frame. -1 if no frame is splittable.\n      int32_t lowestSplittableFrame = -1;\n\n      //   Maximal number of stateIndexEntries.\n      int32_t capacity = 1 << 20;\n\n      ///   Finds the next splittable frame, if any.\n      void updateLowestSplittableFrame();\n\n  public:\n      PathTracker(int32_t _capacity);\n\n      ///   Indicates whether the pathFrames can be split.\n      bool canSplit();\n\n      ///   Gets the number of path frames.\n      int32_t getPathFrameCount();\n\n      ///   Clears all pathFrames and its stateIndexEntries.\n      void clear();\n\n      ///   Pushes a new frame onto the pathFrames stack.\n      void pushFrame();\n\n      /// Adds the stateIndex to the current path frame.\n      void pushStateIndex(StateIndex stateIndex);\n\n  \t\t///   Tries to get the topmost stateIndex if there is one.\n      ///   Returns false to indicate that the path tracker was empty and no stateIndex was returned.\n      bool tryGetStateIndex(StateIndex& stateIndex);\n\n      bool splitWork(PathTracker& other);\n\n      ///   Gets the path the path tracker currently represents, i.e.,\n      ///   returns the sequence of topmost states of each frame, starting with\n      ///   the oldest one.\n      std::vector<StateIndex> getCurrentPath();\n  };\n\n}\n\n#endif  // PEMC_GENERIC_TRAVERSER_PATH_TRACKER_H_\n", "meta": {"hexsha": "da7adefc857206612d2597532c8a22aa7cddf030", "size": 4093, "ext": "h", "lang": "C", "max_stars_repo_path": "pemc/generic_traverser/path_tracker.h", "max_stars_repo_name": "joleuger/pemc", "max_stars_repo_head_hexsha": "14deb5b97d4219ba3c92d3834ab71332997e9b13", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pemc/generic_traverser/path_tracker.h", "max_issues_repo_name": "joleuger/pemc", "max_issues_repo_head_hexsha": "14deb5b97d4219ba3c92d3834ab71332997e9b13", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pemc/generic_traverser/path_tracker.h", "max_forks_repo_name": "joleuger/pemc", "max_forks_repo_head_hexsha": "14deb5b97d4219ba3c92d3834ab71332997e9b13", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.1274509804, "max_line_length": 129, "alphanum_fraction": 0.724407525, "num_tokens": 944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06187598399369696, "lm_q2_score": 0.015424552025266512, "lm_q1q2_score": 0.0009544093342253368}}
{"text": "\ufeff#pragma once\n\n#include <string>\n#include <utility>\n#include <vector>\n#include <unordered_map>\n#include <gsl/span>\n\n#include <lmdb.h>\n#include <functional>\n#include \"Transaction.h\"\n#include \"LmdbExceptions.h\"\n\nnamespace DeepestScatter\n{\n    class Dataset\n    {\n    public:\n        struct Settings;\n        class Example;\n\n        explicit Dataset(std::shared_ptr<Settings> settings);\n        ~Dataset();\n\n        template<class T>\n        size_t getRecordsCount();\n\n        template<class T>\n        T getRecord(int32_t recordId);\n\n        template<class T>\n        void dropTable();\n\n        template<class T>\n        void append(const T& example);\n\n        template<class T>\n        void batchAppend(const gsl::span<T>& examples, int32_t startId);\n\n        struct Settings\n        {\n            Settings(std::string path) :\n                path(std::move(path))\n            {}\n\n            std::string path;\n        };\n\n    private:\n        using TableName = std::string;\n\n        template<class T>\n        void tryAppend(const T& example, int entryId);\n\n        template<class T>\n        void tryBatchAppend(const gsl::span<T>& examples, int nextExampleId);\n\n        void increaseSizeIfNeededWhile(const std::function<void(void)>& action);\n        void increaseSize();\n\n        MDB_dbi getTable(const TableName& name);\n        MDB_dbi openTable(const TableName& name);\n        void closeTable(const TableName& name);\n\n        std::unordered_map<TableName, MDB_dbi> openedTables;\n        std::unordered_map<TableName, int32_t> nextIds;\n\n        MDB_env* mdbEnv = nullptr;\n    };\n\n    template <class T>\n    size_t Dataset::getRecordsCount()\n    {\n        const TableName tableName = T::descriptor()->name();\n\n        MDB_dbi dbi = getTable(tableName);\n\n        return Transaction::withTransaction<size_t>(mdbEnv, nullptr, 0, [&](Transaction& transaction)\n        {\n            MDB_stat stats;\n            LmdbExceptions::checkError(mdb_stat(transaction, dbi, &stats));\n            return stats.ms_entries;\n        });\n    }\n\n    template <class T>\n    T Dataset::getRecord(int32_t recordId)\n    {\n        const TableName tableName = T::descriptor()->name();\n        MDB_dbi dbi = getTable(tableName);\n\n        return Transaction::withTransaction<T>(mdbEnv, nullptr, 0, [&](Transaction& transaction)\n        {\n            MDB_val mdbKey\n            {\n                sizeof(int32_t),\n                &recordId\n            };\n\n            MDB_val mdbVal;\n            LmdbExceptions::checkError(mdb_get(transaction, dbi, &mdbKey, &mdbVal));\n\n            T record{};\n            record.ParseFromArray(mdbVal.mv_data, mdbVal.mv_size);\n\n            return record;\n        });\n    }\n\n    template <class T>\n    void Dataset::dropTable()\n    {\n        const TableName tableName = T::descriptor()->name();\n        MDB_dbi dbi = getTable(tableName);\n\n        if (getRecordsCount<T>() == 0)\n        {\n            return;\n        }\n\n        while (true)\n        {\n            std::string tableConfirmation;\n\n            std::cout << \"YOU ARE GOING TO DELETE \" << getRecordsCount<T>() << \" RECORDS!!!\" << std::endl;\n            std::cout << \"Type table name: \\\"\" << T::descriptor()->name() << \"\\\" to drop it\" << std::endl;\n            std::cin >> tableConfirmation;\n\n            if (tableConfirmation == T::descriptor()->name())\n            {\n                break;\n            }\n\n            std::cout << \"Mismatched table name. Try again.\";\n        }\n\n        Transaction::withTransaction<void>(mdbEnv, nullptr, 0, [&](Transaction& transaction)\n        {\n            mdb_drop(transaction, dbi, 0);\n            nextIds[tableName] = 0;\n        });\n    }\n\n    template <class T>\n    void Dataset::append(const T& example)\n    {\n        const TableName tableName = T::descriptor()->name();\n        // Returns zero if not initialized;\n        int entryId = nextIds[tableName];\n\n        increaseSizeIfNeededWhile([&]()\n        {\n            return tryAppend(example, entryId);\n        });\n\n        nextIds[tableName] = entryId + 1;\n    }\n\n    template <class T>\n    void Dataset::batchAppend(const gsl::span<T>& examples, int32_t startId)\n    {\n        const TableName tableName = T::descriptor()->name();\n\n        increaseSizeIfNeededWhile([&]()\n        {\n            return tryBatchAppend(examples, startId);\n        });\n\n        nextIds[tableName] = startId + examples.size();\n    }\n\n\n    template <class T>\n    void Dataset::tryAppend(const T& example, int entryId)\n    {\n        const TableName tableName = T::descriptor()->name();\n        MDB_dbi dbi = getTable(tableName);\n\n        Transaction::withTransaction<void>(mdbEnv, nullptr, 0, [&](Transaction& transaction)\n        {\n\n            MDB_val mdbKey\n            {\n                sizeof(int32_t),\n                &entryId\n            };\n\n            const size_t length = example.ByteSizeLong();\n            std::vector<uint8_t> serialized(length);\n            example.SerializeWithCachedSizesToArray(&serialized[0]);\n\n            MDB_val mdbVal\n            {\n                length * sizeof(uint8_t),\n                static_cast<void*>(&serialized[0])\n            };\n\n            LmdbExceptions::checkError(mdb_put(transaction, dbi, &mdbKey, &mdbVal, 0));\n        });\n    }\n\n    template <class T>\n    void Dataset::tryBatchAppend(const gsl::span<T>& examples, int nextExampleId)\n    {\n        const TableName tableName = T::descriptor()->name();\n        MDB_dbi dbi = getTable(tableName);\n\n        Transaction::withTransaction<void>(mdbEnv, nullptr, 0, [&](Transaction& transaction)\n        {\n            for (const auto& example : examples)\n            {\n                MDB_val mdbKey\n                {\n                    sizeof(int32_t),\n                    &nextExampleId\n                };\n\n                const size_t length = example.ByteSizeLong();\n                std::vector<uint8_t> serialized(length);\n                example.SerializeWithCachedSizesToArray(&serialized[0]);\n\n                MDB_val mdbVal\n                {\n                    length * sizeof(uint8_t),\n                    static_cast<void*>(&serialized[0])\n                };\n\n                LmdbExceptions::checkError(mdb_put(transaction, dbi, &mdbKey, &mdbVal, 0));\n                nextExampleId++;\n            }\n        });\n    }\n}\n", "meta": {"hexsha": "833cb40bcd0d1ae87372f1208896b199b1256320", "size": 6268, "ext": "h", "lang": "C", "max_stars_repo_path": "DeepestScatter_DataGen/DeepestScatter_DataGen/src/Util/Dataset/Dataset.h", "max_stars_repo_name": "marsermd/DeepestScatter", "max_stars_repo_head_hexsha": "eeb490b5e6afd7f05049c8aca90a5c2e6f253726", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2018-09-02T05:39:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T13:15:14.000Z", "max_issues_repo_path": "DeepestScatter_DataGen/DeepestScatter_DataGen/src/Util/Dataset/Dataset.h", "max_issues_repo_name": "marsermd/DeepestScatter", "max_issues_repo_head_hexsha": "eeb490b5e6afd7f05049c8aca90a5c2e6f253726", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18.0, "max_issues_repo_issues_event_min_datetime": "2020-01-28T22:39:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T23:33:13.000Z", "max_forks_repo_path": "DeepestScatter_DataGen/DeepestScatter_DataGen/src/Util/Dataset/Dataset.h", "max_forks_repo_name": "marsermd/DeepestScatter", "max_forks_repo_head_hexsha": "eeb490b5e6afd7f05049c8aca90a5c2e6f253726", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-12-07T01:20:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-17T02:10:36.000Z", "avg_line_length": 26.7863247863, "max_line_length": 106, "alphanum_fraction": 0.5480216975, "num_tokens": 1339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06560484293979194, "lm_q2_score": 0.014503581315397746, "lm_q1q2_score": 0.00095150517426117}}
{"text": "//\n//  Rpc.hpp\n//  PretendToWork\n//\n//  Created by tqtifnypmb on 18/12/2017.\n//  Copyright \u00a9 2017 tqtifnypmb. All rights reserved.\n//\n\n#pragma once\n\n#include <memory>\n#include <vector>\n\n#include <gsl/gsl>\n#include <uv.h>\n\n#include \"Request.h\"\n\nnamespace brick\n{\n    \nclass Rpc {\npublic:\n    using RpcPeer = uv_handle_t;\n    using Callback = std::function<void(RpcPeer*, Request req)>;\n    \n    enum class LoopState: int {\n        looping = 0,\n        closing = 1,\n        closed,\n        ready\n    };\n    \n    Rpc(const char* ip, int port, Callback req_cb);\n    Rpc(const Rpc&) = delete;\n    Rpc& operator=(const Rpc&) = delete;\n    ~Rpc();\n    \n    void send(RpcPeer* peer, const std::string& msg);\n    void loop();\n    void close();\n    void close(RpcPeer* peer);\n    \nprivate:\n    \n    void onNewConnection(uv_tcp_t* client);\n    void onNewMsg(uv_stream_t* client, const std::string& msg);\n    void onHandleClosed(uv_handle_t* handle);\n    \n    static void connection_cb(uv_stream_t* server, int status);\n    static void read_cb(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf);\n    static void close_cb(uv_handle_t*);\n    static void write_cb(uv_write_t* req, int status);\n\n    LoopState state_;\n\n    Callback req_cb_;\n    std::vector<uv_tcp_t*> clients_;\n    gsl::owner<uv_loop_t*> loop_;\n    gsl::owner<uv_tcp_t*> server_;\n};\n    \n}   // namespace brick\n", "meta": {"hexsha": "158a05bf2fe94af741c02f56fcbbdb0afd8de0e5", "size": 1368, "ext": "h", "lang": "C", "max_stars_repo_path": "src/rpc/Rpc.h", "max_stars_repo_name": "tqtifnypmb/brick", "max_stars_repo_head_hexsha": "49398f77113c57d4e256e838a5ad6b9a6381de6a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/rpc/Rpc.h", "max_issues_repo_name": "tqtifnypmb/brick", "max_issues_repo_head_hexsha": "49398f77113c57d4e256e838a5ad6b9a6381de6a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/rpc/Rpc.h", "max_forks_repo_name": "tqtifnypmb/brick", "max_forks_repo_head_hexsha": "49398f77113c57d4e256e838a5ad6b9a6381de6a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.375, "max_line_length": 81, "alphanum_fraction": 0.6388888889, "num_tokens": 379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.046724957298645224, "lm_q2_score": 0.020332352415110444, "lm_q1q2_score": 0.0009500282983770416}}
{"text": "/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */\n/*\n *     Copyright 2017-Present Couchbase, Inc.\n *\n *   Use of this software is governed by the Business Source License included\n *   in the file licenses/BSL-Couchbase.txt.  As of the Change Date specified\n *   in that file, in accordance with the Business Source License, use of this\n *   software will be governed by the Apache License, Version 2.0, included in\n *   the file licenses/APL2.txt.\n */\n#pragma once\n\n#include <gsl/gsl-lite.hpp>\n#include <mcbp/protocol/dcp_stream_end_status.h>\n#include <mcbp/protocol/status.h>\n#include <memcached/dcp_stream_id.h>\n#include <memcached/engine_error.h>\n#include <memcached/types.h>\n#include <memcached/vbucket.h>\n#include <memcached/visibility.h>\n\nclass CookieIface;\nstruct DocKey;\n\nnamespace cb::durability {\nclass Requirements;\nenum class Level : uint8_t;\n} // namespace cb::durability\n\nnamespace cb::mcbp {\nclass Response;\n}\n\nnamespace mcbp::systemevent {\nenum class id : uint32_t;\nenum class version : uint8_t;\n} // namespace mcbp::systemevent\n\nclass DcpConnHandlerIface {\npublic:\n    virtual ~DcpConnHandlerIface() = default;\n};\n\n/**\n * The message producers are used by the engine's DCP producer\n * to add messages into the DCP stream.  Please look at the full\n * DCP documentation to figure out the real meaning for all of the\n * messages.\n */\nstruct DcpMessageProducersIface {\n    virtual ~DcpMessageProducersIface() = default;\n\n    virtual cb::engine_errc get_failover_log(uint32_t opaque, Vbid vbucket) = 0;\n\n    virtual cb::engine_errc stream_req(uint32_t opaque,\n                                       Vbid vbucket,\n                                       uint32_t flags,\n                                       uint64_t start_seqno,\n                                       uint64_t end_seqno,\n                                       uint64_t vbucket_uuid,\n                                       uint64_t snap_start_seqno,\n                                       uint64_t snap_end_seqno,\n                                       const std::string& request_value) = 0;\n\n    virtual cb::engine_errc add_stream_rsp(uint32_t opaque,\n                                           uint32_t stream_opaque,\n                                           cb::mcbp::Status status) = 0;\n\n    virtual cb::engine_errc marker_rsp(uint32_t opaque,\n                                       cb::mcbp::Status status) = 0;\n\n    virtual cb::engine_errc set_vbucket_state_rsp(uint32_t opaque,\n                                                  cb::mcbp::Status status) = 0;\n\n    /**\n     * Send a Stream End message\n     *\n     * @param opaque this is the opaque requested by the consumer\n     *               in the Stream Request message\n     * @param vbucket the vbucket id the message belong to\n     * @param status the reason for the stream end.\n     *              0 = success\n     *              1+ = Something happened on the vbucket causing\n     *                   us to abort it.\n     * @param sid The stream-ID the end applies to (can be 0 for none)\n     *\n     * @return cb::engine_errc::success upon success\n     *         cb::engine_errc::would_block if no data is available\n     *         ENGINE_* for errors\n     */\n    virtual cb::engine_errc stream_end(uint32_t opaque,\n                                       Vbid vbucket,\n                                       cb::mcbp::DcpStreamEndStatus status,\n                                       cb::mcbp::DcpStreamId sid) = 0;\n\n    /**\n     * Send a marker\n     *\n     * @param opaque this is the opaque requested by the consumer\n     *               in the Stream Request message\n     * @param vbucket the vbucket id the message belong to\n     * @param start_seqno start of the snapshot range\n     * @param end_seqno end of the snapshot range\n     * @param flags snapshot marker flags (DISK/MEMORY/CHK/ACK).\n     * @param highCompletedSeqno the SyncRepl high completed seqno\n     * @param maxVisibleSeqno highest committed seqno (ignores prepare/abort)\n     * @param timestamp for the data in the snapshot marker (only valid for\n     *                  disk type and represents the disk commit time)\n     * @param sid The stream-ID the marker applies to (can be 0 for none)\n     *\n     * @return cb::engine_errc::success upon success\n     */\n    virtual cb::engine_errc marker(uint32_t opaque,\n                                   Vbid vbucket,\n                                   uint64_t start_seqno,\n                                   uint64_t end_seqno,\n                                   uint32_t flags,\n                                   std::optional<uint64_t> highCompletedSeqno,\n                                   std::optional<uint64_t> maxVisibleSeqno,\n                                   std::optional<uint64_t> timestamp,\n                                   cb::mcbp::DcpStreamId sid) = 0;\n\n    /**\n     * Send a Mutation\n     *\n     * @param opaque this is the opaque requested by the consumer\n     *               in the Stream Request message\n     * @param itm the item to send.\n     * @param vbucket the vbucket id the message belong to\n     * @param by_seqno\n     * @param rev_seqno\n     * @param lock_time\n     * @param nru the nru field used by ep-engine (may safely be ignored)\n     * @param sid The stream-ID the mutation applies to (can be 0 for none)\n     *\n     * @return cb::engine_errc::success upon success\n     */\n    virtual cb::engine_errc mutation(uint32_t opaque,\n                                     cb::unique_item_ptr itm,\n                                     Vbid vbucket,\n                                     uint64_t by_seqno,\n                                     uint64_t rev_seqno,\n                                     uint32_t lock_time,\n                                     uint8_t nru,\n                                     cb::mcbp::DcpStreamId sid) = 0;\n\n    /**\n     * Send a deletion\n     *\n     * @param opaque this is the opaque requested by the consumer\n     *               in the Stream Request message\n     * @param itm the item to send.\n     * @param by_seqno\n     * @param rev_seqno\n     * @param sid The stream-ID the deletion applies to (can be 0 for none)\n     *\n     * @return cb::engine_errc::success upon success\n     */\n    virtual cb::engine_errc deletion(uint32_t opaque,\n                                     cb::unique_item_ptr itm,\n                                     Vbid vbucket,\n                                     uint64_t by_seqno,\n                                     uint64_t rev_seqno,\n                                     cb::mcbp::DcpStreamId sid) = 0;\n\n    /**\n     * Send a deletion with delete_time or collections (or both)\n     *\n     * @param opaque this is the opaque requested by the consumer\n     *               in the Stream Request message\n     * @param itm the item to send.\n     * @param vbucket the vbucket id the message belong to\n     * @param by_seqno\n     * @param rev_seqno\n     * @param delete_time the time of the deletion (tombstone creation time)\n     * @param sid The stream-ID the deletion applies to (can be 0 for none)\n     *\n     * @return cb::engine_errc::success upon success\n     */\n    virtual cb::engine_errc deletion_v2(uint32_t opaque,\n                                        cb::unique_item_ptr itm,\n                                        Vbid vbucket,\n                                        uint64_t by_seqno,\n                                        uint64_t rev_seqno,\n                                        uint32_t delete_time,\n                                        cb::mcbp::DcpStreamId sid) = 0;\n\n    /**\n     * Send an expiration\n     *\n     * @param opaque this is the opaque requested by the consumer\n     *               in the Stream Request message\n     * @param itm the item to send.\n     * @param by_seqno\n     * @param rev_seqno\n     * @param delete_time the time of the deletion (tombstone creation time)\n     * @param sid The stream-ID the expiration applies to (can be 0 for none)\n     *\n     * @return cb::engine_errc::success upon success\n     */\n    virtual cb::engine_errc expiration(uint32_t opaque,\n                                       cb::unique_item_ptr itm,\n                                       Vbid vbucket,\n                                       uint64_t by_seqno,\n                                       uint64_t rev_seqno,\n                                       uint32_t delete_time,\n                                       cb::mcbp::DcpStreamId sid) = 0;\n\n    /**\n     * Send a state transition for a vbucket\n     *\n     * @param opaque this is the opaque requested by the consumer\n     *               in the Stream Request message\n     * @param vbucket the vbucket id the message belong to\n     * @param state the new state\n     *\n     * @return cb::engine_errc::success upon success\n     */\n    virtual cb::engine_errc set_vbucket_state(uint32_t opaque,\n                                              Vbid vbucket,\n                                              vbucket_state_t state) = 0;\n\n    /**\n     * Send a noop\n     *\n     * @param opaque what to use as the opaque in the buffer\n     *\n     * @return cb::engine_errc::success upon success\n     */\n    virtual cb::engine_errc noop(uint32_t opaque) = 0;\n\n    /**\n     * Send a buffer acknowledgment\n     *\n     * @param opaque this is the opaque requested by the consumer\n     *               in the Stream Request message\n     * @param vbucket the vbucket id the message belong to\n     * @param buffer_bytes the amount of bytes processed\n     *\n     * @return cb::engine_errc::success upon success\n     */\n    virtual cb::engine_errc buffer_acknowledgement(uint32_t opaque,\n                                                   Vbid vbucket,\n                                                   uint32_t buffer_bytes) = 0;\n\n    /**\n     * Send a control message to the other end\n     *\n     * @param opaque what to use as the opaque in the buffer\n     * @param key the identifier for the property to set\n     * @param value The value for the property (the layout of the\n     *              value is defined for the key)\n     *\n     * @return cb::engine_errc::success upon success\n     */\n    virtual cb::engine_errc control(uint32_t opaque,\n                                    std::string_view key,\n                                    std::string_view value) = 0;\n\n    /**\n     * Send a system event message to the other end\n     *\n     * @param cookie passed on the cookie provided by step\n     * @param opaque what to use as the opaque in the buffer\n     * @param vbucket the vbucket the event applies to\n     * @param bySeqno the sequence number of the event\n     * @param version A version value defining the eventData format\n     * @param key the system event's key data\n     * @param eventData the system event's specific data\n     * @param sid The stream-ID the event applies to (can be 0 for none)\n     *\n     * @return cb::engine_errc::success upon success\n     */\n    virtual cb::engine_errc system_event(uint32_t opaque,\n                                         Vbid vbucket,\n                                         mcbp::systemevent::id event,\n                                         uint64_t bySeqno,\n                                         mcbp::systemevent::version version,\n                                         cb::const_byte_buffer key,\n                                         cb::const_byte_buffer eventData,\n                                         cb::mcbp::DcpStreamId sid) = 0;\n\n    /*\n     * Send a GetErrorMap message to the other end\n     *\n     * @param opaque The opaque to send over\n     * @param version The version of the error map\n     *\n     * @return cb::engine_errc::success upon success\n     */\n    virtual cb::engine_errc get_error_map(uint32_t opaque,\n                                          uint16_t version) = 0;\n\n    /**\n     * See mutation for a description of the parameters except for:\n     *\n     * @param deleted Are we storing a deletion operation?\n     * @param durability the durability specification for this item\n     */\n    virtual cb::engine_errc prepare(uint32_t opaque,\n                                    cb::unique_item_ptr itm,\n                                    Vbid vbucket,\n                                    uint64_t by_seqno,\n                                    uint64_t rev_seqno,\n                                    uint32_t lock_time,\n                                    uint8_t nru,\n                                    DocumentState document_state,\n                                    cb::durability::Level level) = 0;\n\n    /**\n     * Send a seqno ack message\n     *\n     * It serves to inform KV-Engine active nodes that the replica has\n     * successfully received and prepared to memory/disk all DCP_PREPARE\n     * messages up to the specified seqno.\n     *\n     * @param opaque identifying stream\n     * @param vbucket the vbucket the seqno ack is for\n     * @param prepared_seqno The seqno the replica has prepared up to.\n     */\n    virtual cb::engine_errc seqno_acknowledged(uint32_t opaque,\n                                               Vbid vbucket,\n                                               uint64_t prepared_seqno) = 0;\n\n    /**\n     * Send a commit message:\n     *\n     * This is sent from the DCP Producer to the DCP Consumer.\n     * It is only sent to DCP replicas, not GSI, FTS etc. It serves to inform\n     * KV-Engine replicas of a committed Sync Write\n     *\n     * @param opaque\n     * @param vbucket the vbucket the event applies to\n     * @param key The key of the committed mutation.\n     * @param prepare_seqno The seqno of the prepare that we are committing.\n     * @param commit_seqno The sequence number to commit this mutation at.\n     * @return\n     */\n    virtual cb::engine_errc commit(uint32_t opaque,\n                                   Vbid vbucket,\n                                   const DocKey& key,\n                                   uint64_t prepare_seqno,\n                                   uint64_t commit_seqno) = 0;\n    /**\n     * Send an abort message:\n     *\n     * This is sent from the DCP Producer to the DCP Consumer.\n     */\n    virtual cb::engine_errc abort(uint32_t opaque,\n                                  Vbid vbucket,\n                                  const DocKey& key,\n                                  uint64_t prepared_seqno,\n                                  uint64_t abort_seqno) = 0;\n    /**\n     * Send an OSO snapshot marker to from server to client\n     */\n    virtual cb::engine_errc oso_snapshot(uint32_t opaque,\n                                         Vbid vbucket,\n                                         uint32_t flags,\n                                         cb::mcbp::DcpStreamId sid) = 0;\n\n    virtual cb::engine_errc seqno_advanced(uint32_t opaque,\n                                           Vbid vbucket,\n                                           uint64_t seqno,\n                                           cb::mcbp::DcpStreamId sid) = 0;\n};\n\nusing dcp_add_failover_log =\n        std::function<cb::engine_errc(const std::vector<vbucket_failover_t>&)>;\n\nstruct MEMCACHED_PUBLIC_CLASS DcpIface {\n    /**\n     * Called from the memcached core for a DCP connection to allow it to\n     * inject new messages on the stream.\n     *\n     * @param cookie a unique handle the engine should pass on to the\n     *               message producers\n     * @param producers functions the client may use to add messages to\n     *                  the DCP stream\n     *\n     * @return The appropriate error code returned from the message\n     *         producerif it failed, or:\n     *         cb::engine_errc::success if the engine don't have more messages\n     *                        to send at this moment\n     */\n    virtual cb::engine_errc step(const CookieIface& cookie,\n                                 DcpMessageProducersIface& producers) = 0;\n\n    /**\n     * Called from the memcached core to open a new DCP connection.\n     *\n     * @param cookie a unique handle the engine should pass on to the\n     *               message producers (typically representing the memcached\n     *               connection).\n     * @param opaque what to use as the opaque for this DCP connection.\n     * @param seqno Unused\n     * @param flags bitfield of flags to specify what to open. See DCP_OPEN_XXX\n     * @param name Identifier for this connection. Note that the name must be\n     *             unique; attempting to (re)connect with a name already in use\n     *             will disconnect the existing connection.\n     * @param value An optional JSON value specifying extra information about\n     *              the connection to be opened.\n     * @return cb::engine_errc::success if the DCP connection was successfully\n     * opened, otherwise error code indicating reason for the failure.\n     */\n    virtual cb::engine_errc open(const CookieIface& cookie,\n                                 uint32_t opaque,\n                                 uint32_t seqno,\n                                 uint32_t flags,\n                                 std::string_view name,\n                                 std::string_view value = {}) = 0;\n\n    /**\n     * Called from the memcached core to add a vBucket stream to the set of\n     * connected streams.\n     *\n     * @param cookie a unique handle the engine should pass on to the\n     *               message producers (typically representing the memcached\n     *               connection).\n     * @param opaque what to use as the opaque for this DCP connection.\n     * @param vbucket The vBucket to stream.\n     * @param flags bitfield of flags to specify what to open. See\n     *              DCP_ADD_STREAM_FLAG_XXX\n     * @return cb::engine_errc::success if the DCP stream was successfully\n     * opened, otherwise error code indicating reason for the failure.\n     */\n    virtual cb::engine_errc add_stream(const CookieIface& cookie,\n                                       uint32_t opaque,\n                                       Vbid vbucket,\n                                       uint32_t flags) = 0;\n\n    /**\n     * Called from the memcached core to close a vBucket stream to the set of\n     * connected streams.\n     *\n     * @param cookie a unique handle the engine should pass on to the\n     *               message producers (typically representing the memcached\n     *               connection).\n     * @param opaque what to use as the opaque for this DCP connection.\n     * @param vbucket The vBucket to close.\n     * @param sid The id of the stream to close (can be 0/none)\n     * @return\n     */\n    virtual cb::engine_errc close_stream(const CookieIface& cookie,\n                                         uint32_t opaque,\n                                         Vbid vbucket,\n                                         cb::mcbp::DcpStreamId sid) = 0;\n\n    /**\n     * Callback to the engine that a Stream Request message was received\n     */\n    virtual cb::engine_errc stream_req(\n            const CookieIface& cookie,\n            uint32_t flags,\n            uint32_t opaque,\n            Vbid vbucket,\n            uint64_t start_seqno,\n            uint64_t end_seqno,\n            uint64_t vbucket_uuid,\n            uint64_t snap_start_seqno,\n            uint64_t snap_end_seqno,\n            uint64_t* rollback_seqno,\n            dcp_add_failover_log callback,\n            std::optional<std::string_view> json) = 0;\n\n    /**\n     * Callback to the engine that a get failover log message was received\n     */\n    virtual cb::engine_errc get_failover_log(const CookieIface& cookie,\n                                             uint32_t opaque,\n                                             Vbid vbucket,\n                                             dcp_add_failover_log callback) = 0;\n\n    /**\n     * Callback to the engine that a stream end message was received\n     */\n    virtual cb::engine_errc stream_end(const CookieIface& cookie,\n                                       uint32_t opaque,\n                                       Vbid vbucket,\n                                       cb::mcbp::DcpStreamEndStatus status) = 0;\n\n    /**\n     * Callback to the engine that a snapshot marker message was received\n     */\n    virtual cb::engine_errc snapshot_marker(\n            const CookieIface& cookie,\n            uint32_t opaque,\n            Vbid vbucket,\n            uint64_t start_seqno,\n            uint64_t end_seqno,\n            uint32_t flags,\n            std::optional<uint64_t> high_completed_seqno,\n            std::optional<uint64_t> max_visible_seqno) = 0;\n\n    /**\n     * Callback to the engine that a mutation message was received\n     *\n     * @param cookie The cookie representing the connection\n     * @param opaque The opaque field in the message (identifying the stream)\n     * @param key The documents key\n     * @param value The value to store\n     * @param priv_bytes The number of bytes in the value which should be\n     *                   allocated from the privileged pool\n     * @param datatype The datatype for the incomming item\n     * @param cas The documents CAS value\n     * @param vbucket The vbucket identifier for the document\n     * @param flags The user specified flags\n     * @param by_seqno The sequence number in the vbucket\n     * @param rev_seqno The revision number for the item\n     * @param expiration When the document expire\n     * @param lock_time The lock time for the document\n     * @param meta The documents meta\n     * @param nru The engine's NRU value\n     * @return Standard engine error code.\n     */\n    virtual cb::engine_errc mutation(const CookieIface& cookie,\n                                     uint32_t opaque,\n                                     const DocKey& key,\n                                     cb::const_byte_buffer value,\n                                     size_t priv_bytes,\n                                     uint8_t datatype,\n                                     uint64_t cas,\n                                     Vbid vbucket,\n                                     uint32_t flags,\n                                     uint64_t by_seqno,\n                                     uint64_t rev_seqno,\n                                     uint32_t expiration,\n                                     uint32_t lock_time,\n                                     cb::const_byte_buffer meta,\n                                     uint8_t nru) = 0;\n\n    /**\n     * Callback to the engine that a deletion message was received\n     *\n     * @param cookie The cookie representing the connection\n     * @param opaque The opaque field in the message (identifying the stream)\n     * @param key The documents key\n     * @param value The value to store\n     * @param priv_bytes The number of bytes in the value which should be\n     *                   allocated from the privileged pool\n     * @param datatype The datatype for the incomming item\n     * @param cas The documents CAS value\n     * @param vbucket The vbucket identifier for the document\n     * @param by_seqno The sequence number in the vbucket\n     * @param rev_seqno The revision number for the item\n     * @param meta The documents meta\n     * @return Standard engine error code.\n     */\n    virtual cb::engine_errc deletion(const CookieIface& cookie,\n                                     uint32_t opaque,\n                                     const DocKey& key,\n                                     cb::const_byte_buffer value,\n                                     size_t priv_bytes,\n                                     uint8_t datatype,\n                                     uint64_t cas,\n                                     Vbid vbucket,\n                                     uint64_t by_seqno,\n                                     uint64_t rev_seqno,\n                                     cb::const_byte_buffer meta) = 0;\n\n    /**\n     * Callback to the engine that a deletion_v2 message was received\n     *\n     * @param cookie The cookie representing the connection\n     * @param opaque The opaque field in the message (identifying the stream)\n     * @param key The documents key\n     * @param value The value to store\n     * @param priv_bytes The number of bytes in the value which should be\n     *                   allocated from the privileged pool\n     * @param datatype The datatype for the incomming item\n     * @param cas The documents CAS value\n     * @param vbucket The vbucket identifier for the document\n     * @param by_seqno The sequence number in the vbucket\n     * @param rev_seqno The revision number for the item\n     * @param delete_time The time of the delete\n     * @return Standard engine error code.\n     */\n    virtual cb::engine_errc deletion_v2(const CookieIface& cookie,\n                                        uint32_t opaque,\n                                        const DocKey& key,\n                                        cb::const_byte_buffer value,\n                                        size_t priv_bytes,\n                                        uint8_t datatype,\n                                        uint64_t cas,\n                                        Vbid vbucket,\n                                        uint64_t by_seqno,\n                                        uint64_t rev_seqno,\n                                        uint32_t delete_time) {\n        return cb::engine_errc::not_supported;\n    }\n\n    /**\n     * Callback to the engine that an expiration message was received\n     *\n     * @param cookie The cookie representing the connection\n     * @param opaque The opaque field in the message (identifying the stream)\n     * @param key The documents key\n     * @param value The value to store\n     * @param priv_bytes The number of bytes in the value which should be\n     *                   allocated from the privileged pool\n     * @param datatype The datatype for the incomming item\n     * @param cas The documents CAS value\n     * @param vbucket The vbucket identifier for the document\n     * @param by_seqno The sequence number in the vbucket\n     * @param rev_seqno The revision number for the item\n     * @param meta The documents meta\n     * @return Standard engine error code.\n     */\n    virtual cb::engine_errc expiration(const CookieIface& cookie,\n                                       uint32_t opaque,\n                                       const DocKey& key,\n                                       cb::const_byte_buffer value,\n                                       size_t priv_bytes,\n                                       uint8_t datatype,\n                                       uint64_t cas,\n                                       Vbid vbucket,\n                                       uint64_t by_seqno,\n                                       uint64_t rev_seqno,\n                                       uint32_t deleteTime) = 0;\n\n    /**\n     * Callback to the engine that a set vbucket state message was received\n     */\n    virtual cb::engine_errc set_vbucket_state(const CookieIface& cookie,\n                                              uint32_t opaque,\n                                              Vbid vbucket,\n                                              vbucket_state_t state) = 0;\n\n    /**\n     * Callback to the engine that a NOOP message was received\n     */\n    virtual cb::engine_errc noop(const CookieIface& cookie,\n                                 uint32_t opaque) = 0;\n\n    /**\n     * Callback to the engine that a buffer_ack message was received\n     */\n    virtual cb::engine_errc buffer_acknowledgement(const CookieIface& cookie,\n                                                   uint32_t opaque,\n                                                   Vbid vbucket,\n                                                   uint32_t buffer_bytes) = 0;\n\n    /**\n     * Callback to the engine that a Control message was received.\n     *\n     * @param cookie The cookie representing the connection\n     * @param opaque The opaque field in the message (identifying the stream)\n     * @param key The control message name\n     * @param value The control message value\n     * @return Standard engine error code.\n     */\n    virtual cb::engine_errc control(const CookieIface& cookie,\n                                    uint32_t opaque,\n                                    std::string_view key,\n                                    std::string_view value) = 0;\n\n    /**\n     * Callback to the engine that a response message has been received.\n     * @param cookie The cookie representing the connection\n     * @param response The response which the server received.\n     * @return Standard engine error code.\n     */\n    virtual cb::engine_errc response_handler(\n            const CookieIface& cookie, const cb::mcbp::Response& response) = 0;\n\n    /**\n     * Callback to the engine that a system event message was received.\n     *\n     * @param cookie The cookie representing the connection\n     * @param opaque The opaque field in the message (identifying the stream)\n     * @param vbucket The vbucket identifier for this event.\n     * @param event The type of system event.\n     * @param bySeqno Sequence number of event.\n     * @param version The version of system event (defines the eventData format)\n     * @param key The event name .\n     * @param eventData The event value.\n     * @return Standard engine error code.\n     */\n    virtual cb::engine_errc system_event(const CookieIface& cookie,\n                                         uint32_t opaque,\n                                         Vbid vbucket,\n                                         mcbp::systemevent::id event,\n                                         uint64_t bySeqno,\n                                         mcbp::systemevent::version version,\n                                         cb::const_byte_buffer key,\n                                         cb::const_byte_buffer eventData) = 0;\n\n    /**\n     * Called by the core when it receives a DCP PREPARE message over the\n     * wire.\n     *\n     * See mutation for a description of the parameters except for:\n     *\n     * @param deleted Are we storing a deletion operation?\n     * @param durability the durability specification for this item\n     */\n    virtual cb::engine_errc prepare(const CookieIface& cookie,\n                                    uint32_t opaque,\n                                    const DocKey& key,\n                                    cb::const_byte_buffer value,\n                                    size_t priv_bytes,\n                                    uint8_t datatype,\n                                    uint64_t cas,\n                                    Vbid vbucket,\n                                    uint32_t flags,\n                                    uint64_t by_seqno,\n                                    uint64_t rev_seqno,\n                                    uint32_t expiration,\n                                    uint32_t lock_time,\n                                    uint8_t nru,\n                                    DocumentState document_state,\n                                    cb::durability::Level level) = 0;\n\n    /**\n     * Called by the core when it receives a DCP SEQNO ACK message over the\n     * wire.\n     *\n     * It serves to inform KV-Engine active nodes that the replica has\n     * successfully received and prepared all DCP_PREPARE messages up to the\n     * specified seqno.\n     *\n     * @param cookie connection to send it over\n     * @param opaque identifying stream\n     * @param vbucket The vbucket which is being acknowledged.\n     * @param prepared_seqno The seqno the replica has prepared up to.\n     */\n    virtual cb::engine_errc seqno_acknowledged(const CookieIface& cookie,\n                                               uint32_t opaque,\n                                               Vbid vbucket,\n                                               uint64_t prepared_seqno) = 0;\n\n    /**\n     * Called by the core when it receives a DCP COMMIT message over the\n     * wire.\n     *\n     * This is sent from the DCP Producer to the DCP Consumer.\n     * It is only sent to DCP replicas, not GSI, FTS etc. It serves to inform\n     * KV-Engine replicas of a committed Sync Write\n     */\n    virtual cb::engine_errc commit(const CookieIface& cookie,\n                                   uint32_t opaque,\n                                   Vbid vbucket,\n                                   const DocKey& key,\n                                   uint64_t prepared_seqno,\n                                   uint64_t commit_seqno) = 0;\n    /**\n     * Called by the core when it receives a DCP ABORT message over the\n     * wire.\n     *\n     * This is sent from the DCP Producer to the DCP Consumer.\n     */\n    virtual cb::engine_errc abort(const CookieIface& cookie,\n                                  uint32_t opaque,\n                                  Vbid vbucket,\n                                  const DocKey& key,\n                                  uint64_t prepared_seqno,\n                                  uint64_t abort_seqno) = 0;\n};\n", "meta": {"hexsha": "5ee52e3a61b763a63a297b8fb672679824db5440", "size": 32978, "ext": "h", "lang": "C", "max_stars_repo_path": "include/memcached/dcp.h", "max_stars_repo_name": "nawazish-couchbase/kv_engine", "max_stars_repo_head_hexsha": "132f1bb04c9212bcac9e401d069aeee5f63ff1cd", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": 104.0, "max_stars_repo_stars_event_min_datetime": "2017-05-22T20:41:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T00:18:34.000Z", "max_issues_repo_path": "include/memcached/dcp.h", "max_issues_repo_name": "nawazish-couchbase/kv_engine", "max_issues_repo_head_hexsha": "132f1bb04c9212bcac9e401d069aeee5f63ff1cd", "max_issues_repo_licenses": ["MIT", "BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-11-14T08:12:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T11:14:17.000Z", "max_forks_repo_path": "include/memcached/dcp.h", "max_forks_repo_name": "nawazish-couchbase/kv_engine", "max_forks_repo_head_hexsha": "132f1bb04c9212bcac9e401d069aeee5f63ff1cd", "max_forks_repo_licenses": ["MIT", "BSD-3-Clause"], "max_forks_count": 71.0, "max_forks_repo_forks_event_min_datetime": "2017-05-22T20:41:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T10:34:32.000Z", "avg_line_length": 43.4492753623, "max_line_length": 80, "alphanum_fraction": 0.5288374068, "num_tokens": 6639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.05582314741776902, "lm_q2_score": 0.016914910355212892, "lm_q1q2_score": 0.000944243534317397}}
{"text": "/* -----------------------------------------------------------------------------\n * Copyright 2021 Jonathan Haigh\n * SPDX-License-Identifier: MIT\n * ---------------------------------------------------------------------------*/\n\n#ifndef SQ_INCLUDE_GUARD_parser_TokenView_h_\n#define SQ_INCLUDE_GUARD_parser_TokenView_h_\n\n#include \"core/Token.h\"\n#include \"core/typeutil.h\"\n\n#include <gsl/gsl>\n#include <optional>\n#include <range/v3/view/facade.hpp>\n#include <string_view>\n\nnamespace sq::parser {\n\n/**\n * A ranges::view of the input query split into tokens.\n */\nclass TokenView : public ranges::view_facade<TokenView> {\npublic:\n  explicit TokenView(std::string_view str) noexcept;\n\n  TokenView() noexcept = default;\n  TokenView(const TokenView &) noexcept = default;\n  TokenView(TokenView &&) noexcept = default;\n  TokenView &operator=(const TokenView &) noexcept = default;\n  TokenView &operator=(TokenView &&) noexcept = default;\n  ~TokenView() noexcept = default;\n\n  // required for ranges::view_facade\n  friend ranges::range_access;\n\n  SQ_ND const Token &read() const;\n  SQ_ND bool equal(ranges::default_sentinel_t other) const noexcept;\n  void next();\n\nprivate:\n  gsl::index whitespace_length() const;\n\n  std::string_view str_;\n  gsl::index pos_ = 0;\n  mutable std::optional<Token> cache_ = std::nullopt;\n};\n\n} // namespace sq::parser\n#endif // SQ_INCLUDE_GUARD_parser_TokenView_h_\n", "meta": {"hexsha": "a66b73db69abe9a6eb41753520bfafcf92a8a9dc", "size": 1383, "ext": "h", "lang": "C", "max_stars_repo_path": "src/parser/include/parser/TokenView.h", "max_stars_repo_name": "jonathanhaigh/sq", "max_stars_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-12T16:21:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-12T16:21:41.000Z", "max_issues_repo_path": "src/parser/include/parser/TokenView.h", "max_issues_repo_name": "jonathanhaigh/sq", "max_issues_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 44.0, "max_issues_repo_issues_event_min_datetime": "2021-02-08T19:17:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-05T18:51:38.000Z", "max_forks_repo_path": "src/parser/include/parser/TokenView.h", "max_forks_repo_name": "jonathanhaigh/sq", "max_forks_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.66, "max_line_length": 80, "alphanum_fraction": 0.6558206797, "num_tokens": 314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.03210070949490524, "lm_q2_score": 0.0288709100797092, "lm_q1q2_score": 0.0009267766973222766}}
{"text": "#pragma once\n\n#include <cassert>\n#include <functional>\n#include <map>\n#include <type_traits>\n#include <vector>\n\n#include <gsl/assert>\n\nnamespace xmol::utils {\n\nclass DeadObserverAccessError : public std::runtime_error {\npublic:\n  using std::runtime_error::runtime_error;\n};\n\ntemplate <typename Observer>\nclass DeadObserverAccessErrorT : public DeadObserverAccessError { /// todo: parametrize on error message instead\npublic:\n  using DeadObserverAccessError::DeadObserverAccessError;\n};\n\nenum class ObserverState { ANY, ACTIVE, INVALID };\n\n/// @brief Implements base primitives for observable entity\ntemplate <typename Observer> class Observable {\n  static_assert(!std::is_reference<Observer>::value);\n  static_assert(!std::is_pointer<Observer>::value);\n\npublic:\n  Observable() = default;\n  Observable(Observable&& rhs) noexcept = default;\n  Observable(const Observable& rhs) = default;\n  Observable& operator=(Observable&& rhs) noexcept = default;\n  Observable& operator=(const Observable& rhs) = default;\n\nprotected:\n  template <ObserverState apply_to = ObserverState::ANY, typename... Args, typename Func = void (Observer::*)(Args...)>\n  void notify(Func func, Args&&... args) const {\n    static_assert(apply_to != ObserverState::INVALID);\n    for (auto& [observer, state] : observers) {\n      if (state == ObserverState::ACTIVE) {\n        std::invoke(func, observer, std::forward<Args>(args)...);\n      } else {\n        if (GSL_UNLIKELY(apply_to == ObserverState::ANY)) {\n          throw DeadObserverAccessErrorT<Observer>(\"\");\n        }\n      }\n    }\n  }\n\n  void add_observer(Observer& ptr) const { observers.emplace(&ptr, ObserverState::ACTIVE); }\n\n  void remove_observer(Observer& ptr) const {\n    auto count = observers.erase(&ptr);\n    static_cast<void>(count);\n    assert(count == 1);\n  }\n\n  void clear_observers() const { observers.clear(); }\n\n  /// @brief marks observer as invalid\n  /// next broadcast notify would fire an exception\n  void invalidate_observer(Observer& ptr) const {\n    auto it = observers.find(&ptr);\n    assert(it != observers.end());\n    it->second = ObserverState::INVALID;\n  }\n\n  void move_observer(Observer& from, Observer& to) const {\n    remove_observer(from);\n    add_observer(to);\n  }\n\npublic:\n\n  void on_move(Observer& from, Observer& to) {\n    remove_observer(from);\n    add_observer(to);\n  }\n\n  void on_delete(Observer& o) { remove_observer(o); }\n  void on_copy(Observer& o) { add_observer(o); }\n\nprotected:\n  mutable std::map<Observer*, ObserverState> observers;\n};\n\n} // namespace xmol\n", "meta": {"hexsha": "01508b77aa2c6cd9517b3a47239f80f66f125a1d", "size": 2530, "ext": "h", "lang": "C", "max_stars_repo_path": "include/xmol/utils/Observable.h", "max_stars_repo_name": "sizmailov/pyxmolpp2", "max_stars_repo_head_hexsha": "9395ba1b1ddc957e0b33dc6decccdb711e720764", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-06-24T11:07:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-15T23:00:30.000Z", "max_issues_repo_path": "include/xmol/utils/Observable.h", "max_issues_repo_name": "sizmailov/pyxmolpp2", "max_issues_repo_head_hexsha": "9395ba1b1ddc957e0b33dc6decccdb711e720764", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 84.0, "max_issues_repo_issues_event_min_datetime": "2018-04-22T12:29:31.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-17T15:03:37.000Z", "max_forks_repo_path": "include/xmol/utils/Observable.h", "max_forks_repo_name": "sizmailov/pyxmolpp2", "max_forks_repo_head_hexsha": "9395ba1b1ddc957e0b33dc6decccdb711e720764", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-06-04T09:16:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T11:05:54.000Z", "avg_line_length": 27.8021978022, "max_line_length": 119, "alphanum_fraction": 0.7, "num_tokens": 586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.04272219510883879, "lm_q2_score": 0.021615331896036323, "lm_q1q2_score": 0.00092345442660477}}
{"text": "/*\n  Copyright [2017-2021] [IBM Corporation]\n  Licensed under the Apache License, Version 2.0 (the \"License\");\n  you may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n  http://www.apache.org/licenses/LICENSE-2.0\n  Unless required by applicable law or agreed to in writing, software\n  distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions and\n  limitations under the License.\n*/\n\n#ifndef _MCAS_POOL_SESSION_H_\n#define _MCAS_POOL_SESSION_H_\n\n#include <gsl/pointers>\n#include <memory>\n\nclass Pool_instance;\n\nstruct pool_session {\n  pool_session(gsl::not_null<std::shared_ptr<Pool_instance>> ph) : pool(ph), canary(0x45450101) {\n  }\n\n  ~pool_session() {\n  }\n\n  bool check() const { return canary == 0x45450101; }\n  gsl::not_null<std::shared_ptr<Pool_instance>> pool;\n  const unsigned canary;\n};\n\n#endif\n", "meta": {"hexsha": "b5cb07faf0df9aee18e0f604641b24cd8d57df20", "size": 1005, "ext": "h", "lang": "C", "max_stars_repo_path": "src/components/store/mapstore/src/pool_session.h", "max_stars_repo_name": "IBM/artemis", "max_stars_repo_head_hexsha": "f655d6e952577de11b52e2f4ab6f48c73ce5dba1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/components/store/mapstore/src/pool_session.h", "max_issues_repo_name": "IBM/artemis", "max_issues_repo_head_hexsha": "f655d6e952577de11b52e2f4ab6f48c73ce5dba1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/components/store/mapstore/src/pool_session.h", "max_forks_repo_name": "IBM/artemis", "max_forks_repo_head_hexsha": "f655d6e952577de11b52e2f4ab6f48c73ce5dba1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7142857143, "max_line_length": 97, "alphanum_fraction": 0.7502487562, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.04885778000710959, "lm_q2_score": 0.018833128031820533, "lm_q1q2_score": 0.0009201448262244164}}
{"text": "#pragma once\n#include <gsl/gsl>\n#include <d3d11.h>\n#undef min\n#undef max\n\nnamespace Halley {\n\tclass DX11Video;\n\n\tclass DX11Buffer {\n    public:\n\t\tenum class Type\n\t\t{\n\t\t\tVertex,\n\t\t\tIndex,\n\t\t\tConstant\n\t\t};\n\n        DX11Buffer(DX11Video& video, Type type, size_t initialSize = 0);\n\t\tDX11Buffer(DX11Buffer&& other) noexcept;\n\t\t~DX11Buffer();\n\n\t\tDX11Buffer(const DX11Buffer& other) = delete;\n\n\t\tDX11Buffer& operator=(const DX11Buffer& other) = delete;\n\t\tDX11Buffer& operator=(DX11Buffer&& other) = delete;\n\n\t\tvoid setData(gsl::span<const gsl::byte> data);\n\t\tID3D11Buffer*& getBuffer();\n\t\tUINT getOffset() const;\n\t\tUINT getLastSize() const;\n\t\tbool canFit(size_t size) const;\n\n\t\tvoid reset();\n\t\tvoid clear();\n\n\tprivate:\n\t\tDX11Video& video;\n\t\tType type;\n\t\tID3D11Buffer* buffer = nullptr;\n\t\tsize_t curSize = 0;\n\t\tsize_t curPos = 0;\n\t\tsize_t lastSize = 0;\n\t\tsize_t lastPos = 0;\n\t\tbool waitingReset = false;\n\n\t\tvoid resize(size_t size);\n\t};\n}\n", "meta": {"hexsha": "bd15739ebe271b43fb20b7178740a4c103fea9bf", "size": 932, "ext": "h", "lang": "C", "max_stars_repo_path": "src/plugins/dx11/src/dx11_buffer.h", "max_stars_repo_name": "sunhay/halley", "max_stars_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3262.0, "max_stars_repo_stars_event_min_datetime": "2016-04-10T15:24:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:47:08.000Z", "max_issues_repo_path": "src/plugins/dx11/src/dx11_buffer.h", "max_issues_repo_name": "sunhay/halley", "max_issues_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 53.0, "max_issues_repo_issues_event_min_datetime": "2016-10-09T16:25:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-10T13:52:37.000Z", "max_forks_repo_path": "src/plugins/dx11/src/dx11_buffer.h", "max_forks_repo_name": "sunhay/halley", "max_forks_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 193.0, "max_forks_repo_forks_event_min_datetime": "2017-10-23T06:08:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T12:59:58.000Z", "avg_line_length": 18.64, "max_line_length": 72, "alphanum_fraction": 0.6791845494, "num_tokens": 291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.05665242690069723, "lm_q2_score": 0.0161528317140353, "lm_q1q2_score": 0.0009150971179186487}}
{"text": "/****************************************************************************\n *                                                                          *\n *  Author : lukasz.iwaszkiewicz@gmail.com                                  *\n *  ~~~~~~~~                                                                *\n *  License : see COPYING file for details.                                 *\n *  ~~~~~~~~~                                                               *\n ****************************************************************************/\n\n#pragma once\n#include <gsl/gsl>\n\nnamespace sd {\n\nvoid init ();\nint lsdir (gsl::czstring path);\n\n} // namespace sd", "meta": {"hexsha": "7960ea31f0387ee64f4ea4d0014944f8f74fd24c", "size": 661, "ext": "h", "lang": "C", "max_stars_repo_path": "src/sdCard.h", "max_stars_repo_name": "iwasz/zephyr-grbl-plotter", "max_stars_repo_head_hexsha": "f7d8dc96ab859903e12c70c4a54cbbf51804e15f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-12-02T17:33:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T07:50:28.000Z", "max_issues_repo_path": "src/sdCard.h", "max_issues_repo_name": "iwasz/zephyr-grbl-plotter", "max_issues_repo_head_hexsha": "f7d8dc96ab859903e12c70c4a54cbbf51804e15f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sdCard.h", "max_forks_repo_name": "iwasz/zephyr-grbl-plotter", "max_forks_repo_head_hexsha": "f7d8dc96ab859903e12c70c4a54cbbf51804e15f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.8823529412, "max_line_length": 78, "alphanum_fraction": 0.2102874433, "num_tokens": 78, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.03410042374907842, "lm_q2_score": 0.02675928182718321, "lm_q1q2_score": 0.0009125028495279609}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef dir_710838b0_50ee_47d4_bb24_95e5ded5be0b_h\r\n#define dir_710838b0_50ee_47d4_bb24_95e5ded5be0b_h\r\n\r\n#include <direct.h>\r\n#include <io.h>\r\n#include <gslib/type.h>\r\n\r\n#ifdef _UNICODE\r\n\r\n#define _gs_getcwd _wgetcwd\r\n#define _gs_chdir _wchdir\r\n#define _gs_mkdir _wmkdir\r\n#define _gs_rmdir _wrmdir\r\n#define _gs_finddata_t _wfinddata_t\r\n#define _gs_findfirst _wfindfirst\r\n#define _gs_findnext _wfindnext\r\n#define _gs_findclose _findclose\r\n\r\n#else\r\n\r\n#define _gs_getcwd _getcwd\r\n#define _gs_chdir _chdir\r\n#define _gs_mkdir _mkdir\r\n#define _gs_rmdir _rmdir\r\n#define _gs_finddata_t _finddata_t\r\n#define _gs_findfirst _findfirst\r\n#define _gs_findnext _findnext\r\n#define _gs_findclose _findclose\r\n\r\n#endif\r\n\r\n#endif\r\n", "meta": {"hexsha": "cb0bd7c34cbd1c96de5da2a3ef86c88e78ab132a", "size": 1976, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gslib/dir.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/gslib/dir.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gslib/dir.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 32.9333333333, "max_line_length": 82, "alphanum_fraction": 0.7641700405, "num_tokens": 503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.03461883485515691, "lm_q2_score": 0.026355354088838354, "lm_q1q2_score": 0.0009123916507506795}}
{"text": "#pragma once\n\n#include <gsl/gsl>\n\n#include <vector>\n#include <memory>\n\nstruct AVCodecContext;\nstruct AVPacket;\nstruct AVFrame;\n\nnamespace video_streamer\n{\n\nclass FrameEncoder\n{\npublic:\n    explicit FrameEncoder(gsl::not_null<AVCodecContext*> codecContext);\n\n    std::vector<unsigned char> encode(gsl::not_null<const AVFrame*> frame);\nprivate:\n    gsl::not_null<AVCodecContext*> m_codecContext;\n    gsl::not_null<AVPacket*> m_packet;\n};\n\nstd::shared_ptr<FrameEncoder> createFrameEncoder(\n    const std::string& encoderName, gsl::not_null<const AVCodecContext*> codecContext);\n\n} // video_streamer\n", "meta": {"hexsha": "d7975efb41d45441467fd1188b4a7f44abe583ea", "size": 596, "ext": "h", "lang": "C", "max_stars_repo_path": "modules/http_streamer/src/FrameEncoder.h", "max_stars_repo_name": "nicledomaS/VideoStream", "max_stars_repo_head_hexsha": "e695e0b544a61bb4e74149005c69723dbbecb952", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/http_streamer/src/FrameEncoder.h", "max_issues_repo_name": "nicledomaS/VideoStream", "max_issues_repo_head_hexsha": "e695e0b544a61bb4e74149005c69723dbbecb952", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-16T07:16:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T07:16:25.000Z", "max_forks_repo_path": "modules/http_streamer/src/FrameEncoder.h", "max_forks_repo_name": "nicledomaS/VideoStream", "max_forks_repo_head_hexsha": "e695e0b544a61bb4e74149005c69723dbbecb952", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.8666666667, "max_line_length": 87, "alphanum_fraction": 0.7567114094, "num_tokens": 148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.0474258704848281, "lm_q2_score": 0.019124036296667982, "lm_q1q2_score": 0.0009069740685529274}}
{"text": "#pragma once\n/*\n * (C) Copyright 2020-2021 UCAR\n *\n * This software is licensed under the terms of the Apache Licence Version 2.0\n * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.\n */\n/*! \\defgroup ioda_cxx_attribute Attributes and Has_Attributes\n * \\brief Ancillary data attached to variables and groups.\n * \\ingroup ioda_cxx_api\n *\n * @{\n * \\file Attribute.h\n * \\brief @link ioda_cxx_attribute Interfaces @endlink for ioda::Attribute and related classes.\n */\n#include <functional>\n#include <gsl/gsl-lite.hpp>\n#include <iostream>\n#include <memory>\n#include <string>\n#include <valarray>\n#include <vector>\n\n#include \"ioda/Exception.h\"\n#include \"ioda/Misc/Dimensions.h\"\n#include \"ioda/Misc/Eigen_Compat.h\"\n#include \"ioda/Python/Att_ext.h\"\n#include \"ioda/Types/Marshalling.h\"\n#include \"ioda/Types/Type.h\"\n#include \"ioda/Types/Type_Provider.h\"\n#include \"ioda/defs.h\"\n\nnamespace ioda {\nclass Attribute;\n\nnamespace detail {\nclass Attribute_Backend;\nclass Variable_Backend;\n\n/// \\brief Base class for Attributes\n/// \\ingroup ioda_cxx_attribute\n///\n/// \\details You might wonder why we have this class\n/// as a template. This is because we are using\n/// a bit of compile-time template polymorphism to return\n/// Attribute objects from base classes before Attribute is fully declared.\n/// This is a variation of the (Curiously Recurring Template\n/// Pattern)[https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern].\ntemplate <class Attribute_Implementation = Attribute>\nclass Attribute_Base {\nprotected:\n  /// Using an opaque object to implement the backend.\n  std::shared_ptr<Attribute_Backend> backend_;\n\n  // Variable_Backend's derived classes do occasionally need access to the Attribute_Backend object.\n  friend class Variable_Backend;\n\n  /// @name General Functions\n  /// @{\n\n  Attribute_Base(std::shared_ptr<Attribute_Backend>);\n\npublic:\n  virtual ~Attribute_Base();\n\n  /// @}\n\n  /// @name Writing Data\n  /// \\note Writing metadata is an all-or-nothing-process, unlike writing\n  /// segments of data to a variable.\n  /// \\note Dimensions are fixed. Attribute are not resizable.\n  /// @{\n  ///\n\n  /// \\brief The fundamental write function. Backends overload this function to implement all write\n  /// operations.\n  ///\n  /// \\details This function writes a span of bytes (characters) to the backend attribute storage.\n  /// No type conversions take place here (see the templated conversion function, below).\n  ///\n  /// \\param data is a span of data.\n  /// \\param in_memory_datatype is an opaque (backend-level) object that describes the placement of\n  ///   the data in memory. Usually ignorable - needed for complex data structures.\n  /// \\throws ioda::Exception if data has the wrong size.\n  /// \\returns The attribute (for chaining).\n  virtual Attribute_Implementation write(gsl::span<const char> data, const Type& type);\n\n  /// \\brief Write data.\n  /// \\tparam DataType is the type of the data. I.e. float, int, int32_t, uint16_t, std::string, etc.\n  /// \\tparam Marshaller is the class that serializes the data type into something that the backend\n  /// library can use.\n  /// \\tparam TypeWrapper is a helper class that creates Type objects for the backend.\n  /// \\param data is a gsl::span (a pointer-length pair) that contains the data to be written.\n  /// \\param in_memory_dataType is the memory layout needed to parse data's type.\n  /// \\returns Another instance of this Attribute. Used for operation chaining.\n  /// \\throws ioda::Exception if data.size() does not match getDimensions().numElements.\n  /// \\see gsl::span for details of how to make a span.\n  /// \\see gsl::make_span\n  template <class DataType, class Marshaller = ioda::Object_Accessor<DataType>,\n            class TypeWrapper = Types::GetType_Wrapper<DataType>>\n  Attribute_Implementation write(gsl::span<const DataType> data) {\n    try {\n      Marshaller m;\n      auto d   = m.serialize(data);\n      auto spn = gsl::make_span<const char>(reinterpret_cast<const char*>(d->DataPointers.data()),\n                                            d->DataPointers.size() * Marshaller::bytesPerElement_);\n      write(spn, TypeWrapper::GetType(getTypeProvider()));\n      return Attribute_Implementation{backend_};\n    } catch (...) {\n      std::throw_with_nested(Exception(ioda_Here()));\n    }\n  }\n\n  /// \\brief Write data\n  /// \\note Normally the gsl::span write is fine. This one exists for easy Python binding.\n  /// \\tparam DataType is the type of the data. I.e. float, int, int32_t, uint16_t, std::string, etc.\n  /// \\tparam Marshaller is the class that serializes the data type into something that the backend\n  /// library can use.\n  /// \\tparam TypeWrapper is a helper class that creates Type objects for the backend.\n  /// \\param data is a std::vector that contains the data to be written.\n  /// \\param in_memory_dataType is the memory layout needed to parse data's type.\n  /// \\returns Another instance of this Attribute. Used for operation chaining.\n  /// \\throws ioda::Exception if data.size() does not match getDimensions().numElements.\n  /// \\see gsl::span for details of how to make a span.\n  /// \\see gsl::make_span for details on how to make a span.\n  template <class DataType, class Marshaller = ioda::Object_Accessor<DataType>,\n            class TypeWrapper = Types::GetType_Wrapper<DataType>>\n  Attribute_Implementation write(const std::vector<DataType>& data) {\n    std::vector<DataType> vd = data;\n    return this->write<DataType, Marshaller, TypeWrapper>(gsl::make_span(vd));\n  }\n\n  /// \\brief Write data.\n  /// \\tparam DataType is the type of the data. I.e. float, int, int32_t, uint16_t, std::string, etc.\n  /// \\param data is an initializer list that contains the data to be written.\n  /// \\param in_memory_dataType is the memory layout needed to parse data's type.\n  /// \\returns Another instance of this Attribute. Used for operation chaining.\n  /// \\throws ioda::Exception if data.size() does not match getDimensions().numElements.\n  /// \\see gsl::span for details of how to make a span.\n  template <class DataType>\n  Attribute_Implementation write(std::initializer_list<DataType> data) {\n    std::vector<DataType> v(data);\n    return this->write<DataType>(gsl::make_span(v));\n  }\n\n  /// \\brief Write a datum.\n  /// \\tparam DataType is the type of the data. I.e. float, int, int32_t, uint16_t, std::string, etc.\n  /// \\param data is the data to be written.\n  /// \\returns Another instance of this Attribute. Used for operation chaining.\n  /// \\throws ioda::Exception if the Attribute dimensions are larger than a single point.\n  template <class DataType>  //, class Marshaller = HH::Types::Object_Accessor<DataType> >\n  Attribute_Implementation write(DataType data) {\n    try {\n      if (getDimensions().numElements != 1)\n        throw Exception(\"Wrong number of elements. Use a different write() method.\", ioda_Here());\n      return write<DataType>(gsl::make_span<DataType>(&data, 1));\n    } catch (...) {\n      std::throw_with_nested(Exception(ioda_Here()));\n    }\n  }\n\n  /// \\brief Write an Eigen object (a Matrix, an Array, a Block, a Map).\n  /// \\tparam EigenClass is the Eigen object to write.\n  /// \\param d is the data to be written.\n  /// \\throws ioda::Exception on a dimension mismatch.\n  /// \\returns the attribute\n  template <class EigenClass>\n  Attribute_Implementation writeWithEigenRegular(const EigenClass& d) {\n#if 1  //__has_include(\"Eigen/Dense\")\n    try {\n      typedef typename EigenClass::Scalar ScalarType;\n      // If d is already in Row Major form, then this is optimized out.\n      Eigen::Array<ScalarType, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> dout;\n      dout.resize(d.rows(), d.cols());\n      dout               = d;\n      const auto& dconst = dout;  // To make some compilers happy.\n      auto sp            = gsl::make_span(dconst.data(), static_cast<int>(d.rows() * d.cols()));\n\n      return write<ScalarType>(sp);\n    } catch (...) {\n      std::throw_with_nested(Exception(ioda_Here()));\n    }\n#else\n    static_assert(false, \"The Eigen headers cannot be found, so this function cannot be used.\");\n#endif\n  }\n\n  /// \\brief Write an Eigen Tensor-like object\n  /// \\tparam EigenClass is the Eigen tensor to write.\n  /// \\param d is the data to be written.\n  /// \\throws ioda::Exception on a dimension mismatch.\n  /// \\returns the attribute\n  template <class EigenClass>\n  Attribute_Implementation writeWithEigenTensor(const EigenClass& d) {\n#if 1  //__has_include(\"unsupported/Eigen/CXX11/Tensor\")\n    try {\n      ioda::Dimensions dims = detail::EigenCompat::getTensorDimensions(d);\n\n      auto sp  = (gsl::make_span(d.data(), dims.numElements));\n      auto res = write(sp);\n      return res;\n    } catch (...) {\n      std::throw_with_nested(Exception(ioda_Here()));\n    }\n#else\n    static_assert(\n      false, \"The Eigen unsupported/ headers cannot be found, so this function cannot be used.\");\n#endif\n  }\n\n  /// @}\n  /// @name Reading Data\n  /// @{\n  ///\n\n  /// \\brief The fundamental read function. Backends overload this function to implement all read\n  /// operations.\n  ///\n  /// \\details This function reads in a span of characters from the backend attribute storage.\n  /// No type conversions take place here (see the templated conversion function, below).\n  ///\n  /// \\param data is a span of data that has length of getStorageSize().\n  /// \\param in_memory_datatype is an opaque (backend-level) object that describes the placement of\n  ///   the data in memory. Usually ignorable - needed for complex data structures.\n  /// \\throws ioda::Exception if data has the wrong size.\n  /// \\returns The attribute (for chaining).\n  virtual Attribute_Implementation read(gsl::span<char> data, const Type& in_memory_dataType) const;\n\n  /// \\brief Read data.\n  ///\n  /// \\details This is a fundamental function that reads a span of characters from backend storage,\n  /// and then performs the appropriate type conversion / deserialization into objects in data.\n  ///\n  /// \\tparam DataType is the type if the data to be read. I.e. float, int, int32_t, uint16_t,\n  /// std::string, etc.\n  /// \\tparam Marshaller is the class that performs the deserialization operation.\n  /// \\tparam TypeWrapper is a helper class that passes Type information to the backend.\n  /// \\param data is a pointer-size pair to the data buffer that is filled with the metadata's\n  /// contents. It should be\n  ///   pre-sized to accomodate all of the matadata. See getDimensions().numElements. data will be\n  ///   filled in row-major order.\n  /// \\param in_memory_datatype is an opaque (backend-level) object that describes the placement of\n  ///   the data in memory. Usually this does not need to be set to anything other than its default\n  ///   value. Kept as a parameter for debugging purposes.\n  /// \\returns Another instance of this Attribute. Used for operation chaining.\n  /// \\throws ioda::Exception if data.size() != getDimensions().numElements.\n  /// \\see getDimensions for buffer size information.\n  template <class DataType, class Marshaller = ioda::Object_Accessor<DataType>,\n            class TypeWrapper = Types::GetType_Wrapper<DataType>>\n  Attribute_Implementation read(gsl::span<DataType> data) const {\n    try {\n      const size_t numObjects = data.size();\n      if (getDimensions().numElements != gsl::narrow<ioda::Dimensions_t>(numObjects))\n        throw Exception(\"Size mismatch between underlying object and user-provided data range.\",\n                        ioda_Here());\n\n      detail::PointerOwner pointerOwner = getTypeProvider()->getReturnedPointerOwner();\n      Marshaller m(pointerOwner);\n      auto p = m.prep_deserialize(numObjects);\n      read(gsl::make_span<char>(reinterpret_cast<char*>(p->DataPointers.data()),\n                                p->DataPointers.size() * Marshaller::bytesPerElement_),\n           TypeWrapper::GetType(getTypeProvider()));\n      m.deserialize(p, data);\n\n      return Attribute_Implementation{backend_};\n    } catch (...) {\n      std::throw_with_nested(Exception(ioda_Here()));\n    }\n  }\n\n  /// \\brief Vector read convenience function.\n  /// \\tparam DataType is the type of the data. I.e. float, int, int32_t, uint16_t, std::string, etc.\n  /// \\param data is a vector acting as a data buffer that is filled with the metadata's contents.\n  ///   It gets resized as needed.\n  /// \\returns Another instance of this Attribute. Used for operation chaining.\n  /// \\note data will be stored in row-major order.\n  template <class DataType>\n  Attribute_Implementation read(std::vector<DataType>& data) const {\n    data.resize(getDimensions().numElements);\n    return read<DataType>(gsl::make_span<DataType>(data.data(), data.size()));\n  }\n\n  /// \\brief Valarray read convenience function.\n  /// \\tparam DataType is the type of the data. I.e. float, int, int32_t, uint16_t, std::string, etc.\n  /// \\param data is a valarray acting as a data buffer that is filled with the metadata's contents.\n  ///   It gets resized as needed.\n  /// \\returns Another instance of this Attribute. Used for operation chaining.\n  /// \\note data will be stored in row-major order.\n  template <class DataType>\n  Attribute_Implementation read(std::valarray<DataType>& data) const {\n    data.resize(getDimensions().numElements);\n    return read<DataType>(gsl::make_span<DataType>(std::begin(data), std::end(data)));\n  }\n\n  /// \\brief Read into a single value (convenience function).\n  /// \\tparam DataType is the type of the data. I.e. float, int, int32_t, uint16_t, std::string, etc.\n  /// \\param data is where the datum is read to.\n  /// \\returns Another instance of this Attribute. Used for operation chaining.\n  /// \\throws ioda::Exception if the underlying data have multiple elements.\n  template <class DataType>\n  Attribute_Implementation read(DataType& data) const {\n    try {\n      if (getDimensions().numElements != 1)\n        throw Exception(\"Wrong number of elements. Use a different read() method.\", ioda_Here());\n      return read<DataType>(gsl::make_span<DataType>(&data, 1));\n    } catch (...) {\n      std::throw_with_nested(Exception(ioda_Here()));\n    }\n  }\n\n  /// \\brief Read a single value (convenience function).\n  /// \\tparam DataType is the type of the data. I.e. float, int, int32_t, uint16_t, std::string, etc.\n  /// \\returns A datum of type DataType.\n  /// \\throws ioda::Exception if the underlying data have size greater than 1.\n  /// \\note The Python function is read_datum_*\n  template <class DataType>\n  DataType read() const {\n    DataType ret;\n    read<DataType>(ret);\n    return ret;\n  }\n\n  /// \\brief Read into a new vector. Python convenience function.\n  /// \\tparam DataType is the type of the data.\n  /// \\note The Python function is read_list_*\n  template <class DataType>\n  std::vector<DataType> readAsVector() const {\n    std::vector<DataType> data(getDimensions().numElements);\n    read<DataType>(gsl::make_span<DataType>(data.data(), data.size()));\n    return data;\n  }\n\n  /// \\brief Read data into an Eigen::Array, Eigen::Matrix, Eigen::Map, etc.\n  /// \\tparam EigenClass is a template pointing to the Eigen object.\n  ///   This template must provide the EigenClass::Scalar typedef.\n  /// \\tparam Resize indicates whether the Eigen object should be resized\n  ///   if there is a dimension mismatch. Not all Eigen objects can be resized.\n  /// \\param res is the Eigen object.\n  /// \\returns Another instance of this Attribute. Used for operation chaining.\n  /// \\throws ioda::Exception if the attribute's dimensionality is\n  ///   too high.\n  /// \\throws ioda::Exception if resize = false and there is a dimension mismatch.\n  /// \\note When reading in a 1-D object, the data are read as a column vector.\n  template <class EigenClass, bool Resize = detail::EigenCompat::CanResize<EigenClass>::value>\n  Attribute_Implementation readWithEigenRegular(EigenClass& res) const {\n#if 1  //__has_include(\"Eigen/Dense\")\n    try {\n      typedef typename EigenClass::Scalar ScalarType;\n\n      static_assert(\n        !(Resize && !detail::EigenCompat::CanResize<EigenClass>::value),\n        \"This object cannot be resized, but you have specified that a resize is required.\");\n\n      // Check that the dimensionality is 1 or 2.\n      const auto dims = getDimensions();\n      if (dims.dimensionality > 2)\n        throw Exception(\n          \"Dimensionality too high for a regular Eigen read. Use \"\n          \"Eigen::Tensor reads instead.\",\n          ioda_Here());\n\n      int nDims[2] = {1, 1};\n      if (dims.dimsCur.size() >= 1) nDims[0] = gsl::narrow<int>(dims.dimsCur[0]);\n      if (dims.dimsCur.size() >= 2) nDims[1] = gsl::narrow<int>(dims.dimsCur[1]);\n\n      // Resize if needed.\n      if (Resize)\n        detail::EigenCompat::DoEigenResize(res, nDims[0],\n                                           nDims[1]);  // nullop if the size is already correct.\n      else if (dims.numElements != (size_t)(res.rows() * res.cols()))\n        throw Exception(\"Size mismatch\", ioda_Here());\n\n      // Array copy to preserve row vs column major format.\n      // Should be optimized away by the compiler if unneeded.\n      // Note to the reader: We are reading in the data to a temporary object.\n      // We can size _this_ temporary object however we want.\n      // The temporary is used to swap row / column indices if needed.\n      // It should be optimized away if not needed... making sure this happens is a todo.\n      Eigen::Array<ScalarType, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> data_in(res.rows(),\n                                                                                        res.cols());\n\n      auto ret = read<ScalarType>(gsl::span<ScalarType>(data_in.data(), dims.numElements));\n      res      = data_in;\n      return ret;\n    } catch (...) {\n      std::throw_with_nested(Exception(ioda_Here()));\n    }\n#else\n    static_assert(false, \"The Eigen headers cannot be found, so this function cannot be used.\");\n#endif\n  }\n\n  /// \\brief Read data into an Eigen::Array, Eigen::Matrix, Eigen::Map, etc.\n  /// \\tparam EigenClass is a template pointing to the Eigen object.\n  ///   This template must provide the EigenClass::Scalar typedef.\n  /// \\param res is the Eigen object.\n  /// \\returns Another instance of this Attribute. Used for operation chaining.\n  /// \\throws ioda::Exception if there is a size mismatch.\n  /// \\note When reading in a 1-D object, the data are read as a column vector.\n  template <class EigenClass>\n  Attribute_Implementation readWithEigenTensor(EigenClass& res) const {\n#if 1  //__has_include(\"unsupported/Eigen/CXX11/Tensor\")\n    try {\n      // Check dimensionality of source and destination\n      const auto ioda_dims  = getDimensions();\n      const auto eigen_dims = ioda::detail::EigenCompat::getTensorDimensions(res);\n      if (ioda_dims.numElements != eigen_dims.numElements)\n        throw Exception(\"Size mismatch for Eigen Tensor-like read.\", ioda_Here());\n\n      auto sp = (gsl::make_span(res.data(), eigen_dims.numElements));\n      return read(sp);\n    } catch (...) {\n      std::throw_with_nested(Exception(ioda_Here()));\n    }\n#else\n    static_assert(\n      false, \"The Eigen unsupported/ headers cannot be found, so this function cannot be used.\");\n#endif\n  }\n\n  /// \\internal Python binding function\n  template <class EigenClass>\n  EigenClass _readWithEigenRegular_python() const {\n    EigenClass data;\n    readWithEigenRegular(data);\n    return data;\n  }\n\n  /// @}\n  /// @name Type-querying Functions\n  /// @{\n\n  /// \\brief Get Attribute type.\n  virtual Type getType() const;\n  /// \\brief Get Attribute type.\n  inline Type type() const { return getType(); }\n\n  /// Query the backend and get the type provider.\n  virtual detail::Type_Provider* getTypeProvider() const;\n\n  /// \\brief Convenience function to check an Attribute's storage type.\n  /// \\tparam DataType is the type of the data. I.e. float, int, int32_t, uint16_t, std::string, etc.\n  /// \\returns True if the type matches\n  /// \\returns False (0) if the type does not match\n  /// \\throws ioda::Exception if an error occurred.\n  template <class DataType>\n  bool isA() const {\n    Type templateType = Types::GetType_Wrapper<DataType>::GetType(getTypeProvider());\n\n    return isA(templateType);\n  }\n  /// Hand-off to the backend to check equivalence\n  virtual bool isA(Type lhs) const;\n\n  /// Python compatability function\n  inline bool isA(BasicTypes dataType) { return isA(Type(dataType, getTypeProvider())); }\n  /// \\internal pybind11\n  inline bool _py_isA2(BasicTypes dataType) { return isA(dataType); }\n\n  /// @}\n  /// @name Data Space-Querying Functions\n  /// @{\n\n  // Get an Attribute's dataspace\n  // virtual Encapsulated_Handle getSpace() const;\n\n  /// \\brief Get Attribute's dimensions.\n  virtual Dimensions getDimensions() const;\n\n  /// @}\n};\n\n// extern template class Attribute_Base<>;\n}  // namespace detail\n\n/** \\brief This class represents attributes, which may be attached to both Variables and Groups.\n *  \\ingroup ioda_cxx_attribute\n *\n * Attributes are used to store small objects that get tagged to a Variable or a\n * Group to provide context to users and other programs. Attributes include\n * descriptions, units, alternate names, dimensions, and similar constructs.\n * Attributes may have different types (ints, floats, datetimes, strings, etc.),\n * and may be 0- or 1-dimensional.\n *\n * We can open an Attribute from a Has_Attribute object, which is a member of Groups and\n * Variables.\n *\n * \\note Multidimensional attributes are supported by some of the underlying backends,\n * like HDF5, but are incompatible with the NetCDF file format.\n * \\see Has_Attribute for the class that can create and open new Attribute objects.\n * \\throws ioda::Exception on all exceptions.\n **/\nclass IODA_DL Attribute : public detail::Attribute_Base<> {\npublic:\n  Attribute();\n  Attribute(std::shared_ptr<detail::Attribute_Backend> b);\n  Attribute(const Attribute&);\n  Attribute& operator=(const Attribute&);\n  virtual ~Attribute();\n\n  /// @name Python compatability objects\n  /// @{\n\n  detail::python_bindings::AttributeIsA<Attribute> _py_isA;\n\n  detail::python_bindings::AttributeReadSingle<Attribute> _py_readSingle;\n  detail::python_bindings::AttributeReadVector<Attribute> _py_readVector;\n  detail::python_bindings::AttributeReadNPArray<Attribute> _py_readNPArray;\n\n  detail::python_bindings::AttributeWriteSingle<Attribute> _py_writeSingle;\n  detail::python_bindings::AttributeWriteVector<Attribute> _py_writeVector;\n  detail::python_bindings::AttributeWriteNPArray<Attribute> _py_writeNPArray;\n\n  /// @}\n};\n\nnamespace detail {\n/// \\brief Attribute backends inherit from this.\nclass IODA_DL Attribute_Backend : public Attribute_Base<> {\npublic:\n  virtual ~Attribute_Backend();\n\nprotected:\n  Attribute_Backend();\n};\n}  // namespace detail\n}  // namespace ioda\n\n/// @} // End Doxygen block\n", "meta": {"hexsha": "da507b2de331c42ac43f37b4cf82fff80445ddb6", "size": 22713, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engines/ioda/include/ioda/Attributes/Attribute.h", "max_stars_repo_name": "NOAA-EMC/ioda", "max_stars_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/engines/ioda/include/ioda/Attributes/Attribute.h", "max_issues_repo_name": "NOAA-EMC/ioda", "max_issues_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engines/ioda/include/ioda/Attributes/Attribute.h", "max_forks_repo_name": "NOAA-EMC/ioda", "max_forks_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.8547169811, "max_line_length": 101, "alphanum_fraction": 0.6960331088, "num_tokens": 5387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.03308597457504463, "lm_q2_score": 0.02716923291416851, "lm_q1q2_score": 0.000898920549421645}}
{"text": "#pragma once\n\n#include <gsl/gsl>\n\nnamespace Halley {\n    // Note: it's important that this class has the same layout and binary structure as a plain pointer\n    template <typename T>\n    class MaybeRef {\n    public:\n        MaybeRef() : pointer(nullptr) {}\n        MaybeRef(T* pointer) : pointer(pointer) {}\n        MaybeRef(T& ref) : pointer(&ref) {}\n\n        bool hasValue() const\n        {\n            return pointer != nullptr;\n        }\n\n        T& get()\n        {\n            Expects(pointer != nullptr);\n            return *pointer;\n        }\n\n        const T& get() const\n        {\n            Expects(pointer != nullptr);\n            return *pointer;\n        }\n\n    \tT* operator->()\n        {\n        \tExpects(pointer != nullptr);\n\t\t\treturn pointer;\n        }\n\n    \tconst T* operator->() const\n        {\n        \tExpects(pointer != nullptr);\n\t\t\treturn pointer;\n        }\n\n    \toperator bool() const\n        {\n            return pointer != nullptr;\n        }\n\n    \tT* tryGet()\n        {\n\t        return pointer;\n        }\n\n    \tconst T* tryGet() const\n        {\n\t        return pointer;\n        }\n\n    private:\n        T* pointer;\n    };\n}\n", "meta": {"hexsha": "a94b7761b05b6c767802f85f40f8fef8e00a5995", "size": 1148, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engine/utils/include/halley/data_structures/maybe_ref.h", "max_stars_repo_name": "code-disaster/halley", "max_stars_repo_head_hexsha": "5c85c889b76c69c6bdef6f4801c6aba282b7af80", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3262.0, "max_stars_repo_stars_event_min_datetime": "2016-04-10T15:24:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:47:08.000Z", "max_issues_repo_path": "src/engine/utils/include/halley/data_structures/maybe_ref.h", "max_issues_repo_name": "code-disaster/halley", "max_issues_repo_head_hexsha": "5c85c889b76c69c6bdef6f4801c6aba282b7af80", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 53.0, "max_issues_repo_issues_event_min_datetime": "2016-10-09T16:25:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-10T13:52:37.000Z", "max_forks_repo_path": "src/engine/utils/include/halley/data_structures/maybe_ref.h", "max_forks_repo_name": "code-disaster/halley", "max_forks_repo_head_hexsha": "5c85c889b76c69c6bdef6f4801c6aba282b7af80", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 193.0, "max_forks_repo_forks_event_min_datetime": "2017-10-23T06:08:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T12:59:58.000Z", "avg_line_length": 18.5161290323, "max_line_length": 103, "alphanum_fraction": 0.4764808362, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.03732688734412946, "lm_q2_score": 0.024053552325993946, "lm_q1q2_score": 0.000897844237898499}}
{"text": "#ifndef SEARCHPATTERNBUILDER_HHHHH\n#define SEARCHPATTERNBUILDER_HHHHH\n\n#include \"detail/SearchPatternBase.h\"\n#include \"SearchPattern.h\"\n\n#include <vector>\n#include <string>\n#include <memory>\n\n#include <gsl/string_span>\n\nnamespace MPSig {\n\n    class SearchPatternBuilder {\n        std::vector<std::unique_ptr<detail::SearchPatternBase>> m_patternSteps;\n    public:\n        SearchPatternBuilder();\n\n        SearchPatternBuilder& HasHexPattern(gsl::cstring_span<-1> pattern);\n        SearchPatternBuilder& ReferencesBSTR(gsl::cwstring_span<-1> bstrText);\n\n        SearchPattern Compile();\n    };\n}\n\n#endif\n", "meta": {"hexsha": "89e99ea04eb71ce6a1526f5a730cf8c4dd96724c", "size": 603, "ext": "h", "lang": "C", "max_stars_repo_path": "src/search/SearchPatternBuilder.h", "max_stars_repo_name": "KevinW1998/MultipassSigScanner", "max_stars_repo_head_hexsha": "13f290ec593ddbeed3c59c7fba642c1704bfd529", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/search/SearchPatternBuilder.h", "max_issues_repo_name": "KevinW1998/MultipassSigScanner", "max_issues_repo_head_hexsha": "13f290ec593ddbeed3c59c7fba642c1704bfd529", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/search/SearchPatternBuilder.h", "max_forks_repo_name": "KevinW1998/MultipassSigScanner", "max_forks_repo_head_hexsha": "13f290ec593ddbeed3c59c7fba642c1704bfd529", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5357142857, "max_line_length": 79, "alphanum_fraction": 0.7296849088, "num_tokens": 139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.045352585715559196, "lm_q2_score": 0.01971912832337935, "lm_q1q2_score": 0.000894313457522173}}
{"text": "#pragma once\n#include \"PreConfig.h\"\n\n#ifdef CRU_PLATFORM_WINDOWS\n#ifdef CRU_BASE_EXPORT_API\n#define CRU_BASE_API __declspec(dllexport)\n#else\n#define CRU_BASE_API __declspec(dllimport)\n#endif\n#else\n#define CRU_BASE_API\n#endif\n\n#include <gsl/gsl>\n\n#define CRU_UNUSED(entity) static_cast<void>(entity);\n\n#define CRU__CONCAT(a, b) a##b\n#define CRU_MAKE_UNICODE_LITERAL(str) CRU__CONCAT(u, #str)\n\n#define CRU_DEFAULT_COPY(classname)      \\\n  classname(const classname&) = default; \\\n  classname& operator=(const classname&) = default;\n\n#define CRU_DEFAULT_MOVE(classname) \\\n  classname(classname&&) = default; \\\n  classname& operator=(classname&&) = default;\n\n#define CRU_DELETE_COPY(classname)      \\\n  classname(const classname&) = delete; \\\n  classname& operator=(const classname&) = delete;\n\n#define CRU_DELETE_MOVE(classname) \\\n  classname(classname&&) = delete; \\\n  classname& operator=(classname&&) = delete;\n\n#define CRU_DEFAULT_DESTRUCTOR(classname) ~classname() = default;\n\n#define CRU_DEFAULT_CONSTRUCTOR_DESTRUCTOR(classname) \\\n  classname() = default;                              \\\n  ~classname() = default;\n\n#define CRU_DEFINE_COMPARE_OPERATORS(classname)                           \\\n  inline bool operator==(const classname& left, const classname& right) { \\\n    return left.Compare(right) == 0;                                      \\\n  }                                                                       \\\n                                                                          \\\n  inline bool operator!=(const classname& left, const classname& right) { \\\n    return left.Compare(right) != 0;                                      \\\n  }                                                                       \\\n                                                                          \\\n  inline bool operator<(const classname& left, const classname& right) {  \\\n    return left.Compare(right) < 0;                                       \\\n  }                                                                       \\\n                                                                          \\\n  inline bool operator<=(const classname& left, const classname& right) { \\\n    return left.Compare(right) <= 0;                                      \\\n  }                                                                       \\\n                                                                          \\\n  inline bool operator>(const classname& left, const classname& right) {  \\\n    return left.Compare(right) > 0;                                       \\\n  }                                                                       \\\n                                                                          \\\n  inline bool operator>=(const classname& left, const classname& right) { \\\n    return left.Compare(right) >= 0;                                      \\\n  }\n\nnamespace cru {\nclass CRU_BASE_API Object {\n public:\n  Object() = default;\n  CRU_DEFAULT_COPY(Object)\n  CRU_DEFAULT_MOVE(Object)\n  virtual ~Object() = default;\n};\n\nstruct CRU_BASE_API Interface {\n  Interface() = default;\n  CRU_DELETE_COPY(Interface)\n  CRU_DELETE_MOVE(Interface)\n  virtual ~Interface() = default;\n};\n\n[[noreturn]] void CRU_BASE_API UnreachableCode();\n\nusing Index = gsl::index;\n\n// https://www.boost.org/doc/libs/1_54_0/doc/html/hash/reference.html#boost.hash_combine\ntemplate <class T>\ninline void hash_combine(std::size_t& s, const T& v) {\n  std::hash<T> h;\n  s ^= h(v) + 0x9e3779b9 + (s << 6) + (s >> 2);\n}\n\n#define CRU_DEFINE_CLASS_LOG_TAG(tag) \\\n private:                             \\\n  constexpr static const char16_t* kLogTag = tag;\n}  // namespace cru\n", "meta": {"hexsha": "899cfc13817d877326143e047989c3b223261be8", "size": 3648, "ext": "h", "lang": "C", "max_stars_repo_path": "include/cru/common/Base.h", "max_stars_repo_name": "crupest/Cru", "max_stars_repo_head_hexsha": "261681705b9a1b8d939d1420c3373c5591316549", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/cru/common/Base.h", "max_issues_repo_name": "crupest/Cru", "max_issues_repo_head_hexsha": "261681705b9a1b8d939d1420c3373c5591316549", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/cru/common/Base.h", "max_forks_repo_name": "crupest/Cru", "max_forks_repo_head_hexsha": "261681705b9a1b8d939d1420c3373c5591316549", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.8484848485, "max_line_length": 88, "alphanum_fraction": 0.5082236842, "num_tokens": 708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.05033063829537844, "lm_q2_score": 0.017712296078414833, "lm_q1q2_score": 0.000891471167303347}}
{"text": "#ifndef DART_CPP14_SHIM_H\n#define DART_CPP14_SHIM_H\n\n// Figure out what compiler we have.\n#if defined(__clang__)\n#define DART_USING_CLANG 1\n#elif defined(__GNUC__) || defined(__GNUG__)\n#define DART_USING_GCC 1\n#elif defined(_MSC_VER)\n#define DART_USING_MSVC 1\n#endif\n\n#ifdef DART_USING_MSVC\n#define _CRT_SECURE_NO_WARNINGS 1\n#endif\n\n#include <ctime>\n#include <cstring>\n\n#if DART_USING_CLANG && __clang_major__ >= 5 && __clang_major__ <= 7\n// Side-step a disagreement between clang (5/6) and GNU std::variant.\n#define DART_USE_MPARK_VARIANT 1\n#elif defined(__APPLE__)\n// Side-step AppleClang misreporting compiler capabilities on macos 10.13 and below.\n#include <availability.h>\n#ifndef __MAC_10_14\n#define DART_USE_MPARK_VARIANT 1\n#endif\n#endif\n\n// MSVC doesn't have a signed size type, obviously\n#if DART_USING_MSVC\n#include <BaseTsd.h>\nusing ssize_t = SSIZE_T;\n#endif\n\n// Make sure we have a fallback for compilers that don't support attributes at all.\n#ifndef __has_cpp_attribute\n#define __has_cpp_attribute(name) 0\n#endif\n\n// Figure out how to declare things [[nodiscard]]\n#if __has_cpp_attribute(gnu::warn_unused_result)\n#define DART_NODISCARD [[gnu::warn_unused_result]]\n#elif __has_cpp_attribute(nodiscard)\n#define DART_NODISCARD [[nodiscard]]\n#else\n#define DART_NODISCARD\n#endif\n\n#define DART_STRINGIFY_IMPL(x) #x\n#define DART_STRINGIFY(x) DART_STRINGIFY_IMPL(x)\n\n#if DART_USING_MSVC\n#define DART_UNLIKELY(x) !!(x)\n#else\n#define DART_UNLIKELY(x) __builtin_expect(!!(x), 0)\n#endif\n\n#ifndef NDEBUG\n\n#if DART_USING_MSVC\n#include <io.h>\n#define DART_WRITE(fd, ptr, bytes) _write(fd, ptr, static_cast<unsigned int>(bytes))\n#define DART_STDERR_FILENO _fileno(stderr)\n#else\n#include <unistd.h>\n#define DART_WRITE(fd, ptr, bytes) write(fd, ptr, bytes)\n#define DART_STDERR_FILENO STDERR_FILENO\n#endif\n\n/**\n *  @brief\n *  Macro customizes functionality usually provided by assert().\n *\n *  @details\n *  Not strictly necessary, but tries to provide a bit more context and\n *  information as to why I just murdered the user's program (in production, no doubt).\n *\n *  @remarks\n *  Don't actually know if Doxygen lets you document macros, guess we'll see.\n */\n#define DART_ASSERT(cond)                                                                                     \\\n  if (DART_UNLIKELY(!(cond))) {                                                                               \\\n    auto& msg = \"dart::packet has detected fatal memory corruption and cannot continue execution.\\n\"          \\\n      \"\\\"\" DART_STRINGIFY(cond) \"\\\" violated.\\nSee \" __FILE__ \":\" DART_STRINGIFY(__LINE__) \"\\n\";              \\\n    int errfd = DART_STDERR_FILENO;                                                                           \\\n    ssize_t spins {0}, written {0}, total {sizeof(msg)};                                                      \\\n    do {                                                                                                      \\\n      ssize_t ret = DART_WRITE(errfd, msg + written, total - written);                                        \\\n      if (ret >= 0) written += ret;                                                                           \\\n    } while (written != total && spins++ < 16);                                                               \\\n    std::abort();                                                                                             \\\n  }\n#else\n#define DART_ASSERT(cond) \n#endif\n\n\n// Conditionally include different implementations of different data structures\n// depending on what standard we have access to.\n#if __cplusplus >= 201703L && !DART_USE_MPARK_VARIANT\n#define DART_HAS_CPP17 1\n#include <variant>\n#include <optional>\n#include <string_view>\n#else\n#define DART_HAS_CPP14 1\n#include \"support/variant.h\"\n#include \"support/optional.h\"\n#include \"support/string_view.h\"\n#endif\n\n// We support two versions of GSL, but unfortunately they don't agree about\n// the template signature of gsl::span (why would we expect two production-ready\n// implementations of the same exact specification to agree about something like\n// that), so we have to declare some of our partial specializations differently\n// depending on what we included.\n#include <gsl/gsl>\n#ifndef gsl_lite_VERSION\n#define DART_USING_GSL\n#else\n#define DART_USING_GSL_LITE\n#endif\n\n// Conditionally pull each of those types into our namespace.\nnamespace dart {\n  namespace shim {\n\n#if DART_USING_MSVC\n    inline int aligned_alloc(void** memptr, size_t alignment, size_t size) {\n      void* ret = _aligned_malloc(size, alignment);\n      if (ret) {\n        *memptr = ret;\n        return 0;\n      } else {\n        return -1;\n      }\n    }\n\n    inline void aligned_free(void* ptr) {\n      _aligned_free(ptr);\n    }\n\n    inline void gmtime(time_t const* src, std::tm* out) {\n      gmtime_s(out, src);\n    }\n\n    inline time_t timegm(std::tm* src) {\n      return _mkgmtime(src);\n    }\n#else\n    inline int aligned_alloc(void** memptr, size_t alignment, size_t size) {\n      return posix_memalign(memptr, alignment, size);\n    }\n\n    inline void aligned_free(void* ptr) {\n      free(ptr);\n    }\n\n    inline void gmtime(time_t const* src, std::tm* out) {\n      gmtime_r(src, out);\n    }\n\n    inline time_t timegm(std::tm* src) {\n      return ::timegm(src);\n    }\n#endif\n\n#ifdef DART_HAS_CPP17\n\n    // Pull in names of types.\n    using std::optional;\n    using std::nullopt_t;\n    using std::variant;\n    using std::monostate;\n    using std::string_view;\n    using std::basic_string_view;\n\n    // Pull in constants.\n    static inline constexpr auto nullopt = std::nullopt;\n\n    // Pull in non-member helpers.\n    using std::get;\n    using std::visit;\n    using std::get_if;\n    using std::launder;\n    using std::holds_alternative;\n    using std::variant_alternative;\n    using std::variant_alternative_t;\n\n    // Define a way to compose lambdas.\n    template <class... Ls>\n    struct compose : Ls... {\n      using Ls::operator ()...;\n    };\n    template <class... Ls>\n    compose(Ls...) -> compose<Ls...>;\n\n    template <class... Ls>\n    auto compose_together(Ls&&... lambdas) {\n      return compose {std::forward<Ls>(lambdas)...};\n    }\n#else\n\n    // Pull in names of types.\n    using dart::optional;\n    using dart::nullopt_t;\n    using dart::string_view;\n    using dart::basic_string_view;\n    using mpark::variant;\n    using mpark::monostate;\n\n    // Pull in non-member helpers.\n    using mpark::get;\n    using mpark::visit;\n    using mpark::get_if;\n    using mpark::holds_alternative;\n    using mpark::variant_alternative;\n    using mpark::variant_alternative_t;\n\n    // Pull in constants.\n    static constexpr auto nullopt = dart::nullopt;\n\n    // Define a way to compose lambdas.\n    template <class... Ls>\n    struct compose;\n    template <class L, class... Ls>\n    struct compose<L, Ls...> : L, compose<Ls...> {\n      compose(L l, Ls... the_rest) : L(std::move(l)), compose<Ls...>(std::move(the_rest)...) {}\n      using L::operator ();\n      using compose<Ls...>::operator ();\n    };\n    template <class L>\n    struct compose<L> : L {\n      compose(L l) : L(std::move(l)) {}\n      using L::operator ();\n    };\n\n    template <class... Ls>\n    auto compose_together(Ls&&... lambdas) {\n      return compose<std::decay_t<Ls>...> {std::forward<Ls>(lambdas)...};\n    }\n#endif\n  }\n}\n\n#endif\n", "meta": {"hexsha": "74236f85a8436bd02b1ec963bf21586dfe81907b", "size": 7298, "ext": "h", "lang": "C", "max_stars_repo_path": "include/dart/shim.h", "max_stars_repo_name": "Cfretz244/libdart", "max_stars_repo_head_hexsha": "987b01aa1f11455ac6aaf89f8e60825e92e6ec25", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2019-05-09T19:12:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-07T16:31:55.000Z", "max_issues_repo_path": "include/dart/shim.h", "max_issues_repo_name": "Cfretz244/libdart", "max_issues_repo_head_hexsha": "987b01aa1f11455ac6aaf89f8e60825e92e6ec25", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2019-05-09T22:37:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-29T03:25:16.000Z", "max_forks_repo_path": "include/dart/shim.h", "max_forks_repo_name": "Cfretz244/libdart", "max_forks_repo_head_hexsha": "987b01aa1f11455ac6aaf89f8e60825e92e6ec25", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-05-11T08:05:10.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-11T11:05:17.000Z", "avg_line_length": 29.3092369478, "max_line_length": 111, "alphanum_fraction": 0.6208550288, "num_tokens": 1792, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.051845466649779834, "lm_q2_score": 0.017176705804973564, "lm_q1q2_score": 0.0008905343279648366}}
{"text": "#pragma once\n#include \"halley/plugin/iasset_importer.h\"\n#include <gsl/gsl>\n\nnamespace Halley\n{\n\tclass Animation;\n\n\tclass AnimationImporter : public IAssetImporter\n\t{\n\tpublic:\n\t\tImportAssetType getType() const override { return ImportAssetType::Animation; }\n\n\t\tvoid import(const ImportingAsset& asset, IAssetCollector& collector) override;\n\n\t\tstatic void parseAnimation(Animation& animation, gsl::span<const gsl::byte> data);\n\t};\n}\n", "meta": {"hexsha": "24b8b0a40e6e2de606ee8376fdb96004a33efaab", "size": 431, "ext": "h", "lang": "C", "max_stars_repo_path": "src/tools/tools/src/assets/importers/animation_importer.h", "max_stars_repo_name": "sunhay/halley", "max_stars_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3262.0, "max_stars_repo_stars_event_min_datetime": "2016-04-10T15:24:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:47:08.000Z", "max_issues_repo_path": "src/tools/tools/src/assets/importers/animation_importer.h", "max_issues_repo_name": "sunhay/halley", "max_issues_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 53.0, "max_issues_repo_issues_event_min_datetime": "2016-10-09T16:25:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-10T13:52:37.000Z", "max_forks_repo_path": "src/tools/tools/src/assets/importers/animation_importer.h", "max_forks_repo_name": "sunhay/halley", "max_forks_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 193.0, "max_forks_repo_forks_event_min_datetime": "2017-10-23T06:08:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T12:59:58.000Z", "avg_line_length": 22.6842105263, "max_line_length": 84, "alphanum_fraction": 0.7679814385, "num_tokens": 101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.0541987267677784, "lm_q2_score": 0.016403030863310474, "lm_q1q2_score": 0.0008890233879240006}}
{"text": "/***\n * Copyright 2019 The Katla Authors\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#ifndef KATLA_SOCKET_H\n#define KATLA_SOCKET_H\n\n#include \"posix-errors.h\"\n\n#include \"katla/core/error.h\"\n#include \"katla/core/core.h\"\n\n#include <gsl/span>\n\n#include <net/ethernet.h>\n\n#include <memory>\n#include <optional>\n#include <system_error>\n\n#include <chrono>\n#include <string>\n\nnamespace outcome = OUTCOME_V2_NAMESPACE;\n\nnamespace katla {\n\nclass PosixSocket {\npublic:\n    enum class ProtocolDomain { Unix, IPv4, IPv6, Packet, Can, Bluetooth, VSock};\n    enum class Type { Stream, Datagram, SequencedPacket, Raw};\n    enum class FrameType : uint16_t { All = ETH_P_ALL, EtherCat = 0x88a4 };\n\n    struct SocketOptions {\n        ProtocolDomain domain {ProtocolDomain::IPv4};\n        Type type {Type::Stream};\n        FrameType frameType {FrameType::All};\n        bool nonBlocking {false};\n        bool reuseAddress {false};\n    };\n\n    static constexpr SocketOptions IPv4SocketOptions {ProtocolDomain::IPv4, Type::Stream, FrameType::All, false, false};\n\n    struct WaitResult {\n        bool dataToRead {0};\n        bool urgentDataToRead {0};\n        bool writingWillNotBlock {0};\n        bool readHangup {0};\n        bool writeHangup {0};\n        bool error {0};      \n        bool invalid {0};\n        bool wakeup {0};\n    };\n\n    PosixSocket();\n    PosixSocket(ProtocolDomain protocolDomain, Type type, FrameType frameType, bool nonBlocking);\n    PosixSocket(const PosixSocket&) = delete;\n    ~PosixSocket();\n\n    static outcome::result<std::array<std::shared_ptr<PosixSocket>, 2>, Error> createUnnamedPair(ProtocolDomain protocolDomain, Type type, FrameType frameType, bool nonBlocking);\n\n    outcome::result<void, Error> bind(std::string url);\n    outcome::result<void, Error> bindIPv4(std::string ip, int port, SocketOptions options = IPv4SocketOptions);\n\n    outcome::result<void, Error> listen();\n    outcome::result<std::unique_ptr<PosixSocket>, Error> accept();\n    std::optional<Error> error();\n\n    outcome::result<void, Error> connect(std::string url, SocketOptions options);\n    outcome::result<void, Error> connectIPv4(std::string ip, int port, SocketOptions options = IPv4SocketOptions);\n\n    // TODO add wakeup to interrupt wait -> multithreading??\n    outcome::result<WaitResult, Error> poll(std::chrono::milliseconds timeout, bool writePending = false);\n\n    outcome::result<ssize_t, Error> read(const gsl::span<std::byte>& buffer);\n    outcome::result<ssize_t, Error> write(const gsl::span<std::byte>& buffer);\n\n    outcome::result<ssize_t, Error> receiveFrom(const gsl::span<std::byte>& buffer);\n    outcome::result<ssize_t, Error> sendTo(std::string url, const gsl::span<std::byte>& buffer);\n\n    outcome::result<void, Error> wakeup();\n\n    outcome::result<void, Error> close();\nprivate:\n    outcome::result<void, Error> create();\n\n    PosixSocket & operator=(const PosixSocket&) = delete;\n\n    PosixSocket(ProtocolDomain protocolDomain, Type type, FrameType frameType, bool nonBlocking, int fd, int wakeupFd);\n\n    static int mapProtocolDomain (ProtocolDomain protocolDomain);\n    static int mapType (Type type);\n\n    int _fd {-1};\n    int _wakeupFd {-1};\n\n    ProtocolDomain _protocolDomain {ProtocolDomain::IPv4};\n    Type _type {Type::Stream};\n    FrameType _frameType {FrameType::All};\n\n    std::string _url;\n\n    bool _nonBlocking {false};\n};\n\n}\n\n#endif // KATLA_SOCKET_H\n", "meta": {"hexsha": "3f37b631039ca9b1ec10068cc0e157a03a7797d2", "size": 3902, "ext": "h", "lang": "C", "max_stars_repo_path": "core/posix-socket.h", "max_stars_repo_name": "plok/katla", "max_stars_repo_head_hexsha": "aaaeb8baf041bba7259275beefc71c8452a16223", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "core/posix-socket.h", "max_issues_repo_name": "plok/katla", "max_issues_repo_head_hexsha": "aaaeb8baf041bba7259275beefc71c8452a16223", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-03-25T14:33:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-16T14:21:56.000Z", "max_forks_repo_path": "core/posix-socket.h", "max_forks_repo_name": "plok/katla", "max_forks_repo_head_hexsha": "aaaeb8baf041bba7259275beefc71c8452a16223", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-26T13:32:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-26T13:32:36.000Z", "avg_line_length": 32.2479338843, "max_line_length": 178, "alphanum_fraction": 0.7029728344, "num_tokens": 951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.05500528364610641, "lm_q2_score": 0.016152838344661417, "lm_q1q2_score": 0.0008884914548378053}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef xsd_284c8467_1f5e_4ae4_b645_077382bf6ab4_h\r\n#define xsd_284c8467_1f5e_4ae4_b645_077382bf6ab4_h\r\n\r\n#include <gslib/config.h>\r\n#include <gslib/xml.h>\r\n#include <gslib/std.h>\r\n#include <gslib/xsdtypes.h>\r\n\r\n__gslib_begin__\r\n\r\n//#define xsd_def_\r\n\r\nclass xsd_schema;\r\nstruct xsd_extern_schema;\r\nclass xsd_node;\r\nclass xsd_element;\r\nclass xsd_attribute;\r\nclass xsd_group;\r\nclass xsd_attribute_group;\r\nclass xsd_simple_type;\r\nclass xsd_complex_type;\r\n\r\ntypedef xml_wrapper xsd_wrapper;\r\ntypedef vector<xsd_wrapper*> xsd_wrappers;\r\ntypedef xmltree::iterator xsd_iterator;\r\ntypedef xmltree::const_iterator xsd_const_iterator;\r\n\r\ntemplate<class _ty>\r\nstruct xsd_schema_ns_hash:\r\n    public std::unary_function<_ty, size_t>\r\n{\r\n    size_t operator()(_ty t) const\r\n    {\r\n        assert(t);\r\n        return string_hash(t->get_namespace());\r\n    }\r\n};\r\n\r\ntemplate<class _ty>\r\nstruct xsd_schema_ns_equalto:\r\n    public std::binary_function<_ty, _ty, bool>\r\n{\r\n    bool operator()(_ty t1, _ty t2) const\r\n    {\r\n        assert(t1 && t2);\r\n        return t1->get_namespace() == t2->get_namespace();\r\n    }\r\n};\r\n\r\ntemplate<class _ty>\r\nstruct xsd_schema_loc_hash:\r\n    public std::unary_function<_ty, size_t>\r\n{\r\n    size_t operator()(_ty t) const\r\n    {\r\n        assert(t);\r\n        return string_hash(t->get_location());\r\n    }\r\n};\r\n\r\ntemplate<class _ty>\r\nstruct xsd_schema_loc_equalto:\r\n    public std::binary_function<_ty, _ty, bool>\r\n{\r\n    bool operator()(_ty t1, _ty t2) const\r\n    {\r\n        assert(t1 && t2);\r\n        return t1->get_location() == t2->get_location();\r\n    }\r\n};\r\n\r\ntemplate<class _ty>\r\nstruct xsd_name_hash:\r\n    public std::unary_function<_ty, size_t>\r\n{\r\n    size_t operator()(_ty t) const\r\n    {\r\n        assert(t);\r\n        return string_hash(t->get_name());\r\n    }\r\n};\r\n\r\ntemplate<class _ty>\r\nstruct xsd_name_equalto:\r\n    public std::binary_function<_ty, _ty, bool>\r\n{\r\n    bool operator()(_ty t1, _ty t2) const\r\n    {\r\n        assert(t1 && t2);\r\n        return t1->get_name() == t2->get_name();\r\n    }\r\n};\r\n\r\ntypedef vector<xsd_schema*> xsd_schemas;\r\ntypedef unordered_multiset<xsd_schema*, xsd_schema_ns_hash<xsd_schema*>, xsd_schema_ns_equalto<xsd_schema*> > xsd_schema_ns_map;\r\ntypedef unordered_set<xsd_schema*, xsd_schema_loc_hash<xsd_schema*>, xsd_schema_loc_equalto<xsd_schema*> > xsd_schema_loc_map;\r\ntypedef list<xsd_extern_schema> xsd_extern_schemas;\r\ntypedef unordered_set<xsd_node*, xsd_name_hash<xsd_node*>, xsd_name_equalto<xsd_node*> > xsd_node_map;\r\ntypedef unordered_multiset<xsd_node*, xsd_name_hash<xsd_node*>, xsd_name_equalto<xsd_node*> > xsd_node_multimap;\r\n\r\nstruct xsd_global\r\n{\r\n    xsd_schemas             packs;\r\n    xsd_schema_ns_map       ns_map;\r\n    xsd_schema_loc_map      loc_map;\r\n\r\npublic:\r\n    ~xsd_global();\r\n\r\n};\r\n\r\nstruct xsd_cg_config {};\r\n\r\nextern xsd_schema* xsd_parse_schema(xsd_global& global, xmltree& dom, const gchar* location);\r\nextern xsd_schema* xsd_parse_schema(xsd_global& global, const gchar* location);\r\nextern void xsd_make_file_name(string& name, const string& str);\r\nextern bool xsd_prepare_name_mangling(xsd_global& global);\r\nextern bool xsd_prepare_translation(xsd_schema* schema, xsd_global& global);\r\nextern bool xsd_translate_declarations(string& output, xsd_schema* schema, xsd_global& global);\r\nextern bool xsd_translate_implementations(string& output, xsd_schema* schema, xsd_global& global);\r\n\r\nenum xsd_extern_schema_type\r\n{\r\n    xest_include,\r\n    xest_import,\r\n};\r\n\r\nenum xsd_node_type\r\n{\r\n    xnt_key,\r\n    xnt_element,\r\n    xnt_attribute,\r\n    xnt_attribute_group,\r\n    xnt_group,\r\n    xnt_simple_type,\r\n    xnt_complex_type,\r\n};\r\n\r\nstruct xsd_extern_schema\r\n{\r\n    xsd_extern_schema_type  type;\r\n    string                  ns;\r\n    xsd_schema*             schema;\r\n\r\npublic:\r\n    xsd_schema* operator->() { return schema; }\r\n    const xsd_schema* operator->() const { return schema; }\r\n};\r\n\r\nclass xsd_schema\r\n{\r\nprotected:\r\n    xsd_wrapper*            _source;\r\n    string                  _namespace;\r\n    string                  _location;\r\n    xsd_extern_schemas      _external;      // include & import\r\n    string                  _xsd_namespace;\r\n    xsd_node_map            _element_map;\r\n    xsd_node_map            _attribute_map;\r\n    xsd_node_map            _attribute_group_map;\r\n    xsd_node_map            _group_map;\r\n    xsd_node_map            _simple_type_map;\r\n    xsd_node_map            _complex_type_map;\r\n\r\npublic:\r\n    xsd_schema();\r\n    ~xsd_schema();\r\n    const string& get_namespace() const { return _namespace; }\r\n    const string& get_location() const { return _location; }\r\n    const string& get_xsd_namespace() const { return _xsd_namespace; }\r\n    void set_namespace(const string& str) { _namespace = str; }\r\n    void set_location(const string& str) { _location = str; }\r\n    void set_xsd_namespace(const string& str) { _xsd_namespace = str; }\r\n    void set_source(xsd_wrapper* s) { _source = s; }\r\n    xsd_extern_schemas& get_extern_schemas() { return _external; }\r\n    xsd_node_map& get_element_map() { return _element_map; }\r\n    xsd_node_map& get_attribute_map() { return _attribute_map; }\r\n    xsd_node_map& get_attribute_group_map() { return _attribute_group_map; }\r\n    xsd_node_map& get_group_map() { return _group_map; }\r\n    xsd_node_map& get_simple_type_map() { return _simple_type_map; }\r\n    xsd_node_map& get_complex_type_map() { return _complex_type_map; }\r\n\r\nprotected:\r\n    static xsd_node* find_node(const xsd_node_map& m, const string& name);\r\n    template<class _node>\r\n    static _node* find_and_verify(const xsd_node_map& m, const string& n, xsd_node_type t)\r\n    {\r\n        xsd_node* r = find_node(m, n);\r\n        if(!r) return 0;\r\n        assert(r->get_type() == t);\r\n        return static_cast<_node*>(r);\r\n    }\r\n\r\npublic:\r\n    xsd_element* find_element_node(const string& name) const { return find_and_verify<xsd_element>(_element_map, name, xnt_element); }\r\n    xsd_attribute* find_attribute_node(const string& name) const { return find_and_verify<xsd_attribute>(_attribute_map, name, xnt_attribute); }\r\n    xsd_group* find_group_node(const string& name) const { return find_and_verify<xsd_group>(_group_map, name, xnt_group); }\r\n    xsd_attribute_group* find_attribute_group_node(const string& name) const { return find_and_verify<xsd_attribute_group>(_attribute_group_map, name, xnt_attribute_group); }\r\n    xsd_simple_type* find_simple_type_node(const string& name) const { return find_and_verify<xsd_simple_type>(_simple_type_map, name, xnt_simple_type); }\r\n    xsd_complex_type* find_complex_type_node(const string& name) const { return find_and_verify<xsd_complex_type>(_complex_type_map, name, xnt_complex_type); }\r\n};\r\n\r\nstruct xsd_ns_key:\r\n    public xsd_schema\r\n{\r\n    xsd_ns_key(const string& str) { _namespace.assign(str); }\r\n    xsd_ns_key(const gchar* str) { _namespace.assign(str); }\r\n    xsd_ns_key(const gchar* str, int len) { _namespace.assign(str, len); }\r\n};\r\n\r\nstruct xsd_loc_key:\r\n    public xsd_schema\r\n{\r\n    xsd_loc_key(const string& str) { _location.assign(str); }\r\n    xsd_loc_key(const gchar* str) { _location.assign(str); }\r\n    xsd_loc_key(const gchar* str, int len) { _location.assign(str, len); }\r\n};\r\n\r\nclass __gs_novtable xsd_node abstract\r\n{\r\npublic:\r\n    xsd_node();\r\n    virtual ~xsd_node() {}\r\n    virtual xsd_node_type get_type() const = 0;\r\n\r\npublic:\r\n    void set_name(const string& str) { _name = str; }\r\n    void set_mangling(const string& str) { _mangling = str; }\r\n    const string& get_name() const { return _name; }\r\n    const string& get_mangling() const { return _mangling; }\r\n    xsd_wrapper* get_source() const { return _source; }\r\n    void set_source(xsd_wrapper* s) { _source = s; }\r\n    void set_translated(bool b) { _translated = b; }\r\n    bool is_translated() const { return _translated; }\r\n\r\nprotected:\r\n    string                  _name;\r\n    string                  _mangling;\r\n    xsd_wrapper*            _source;\r\n    bool                    _translated;\r\n};\r\n\r\nstruct xsd_node_key:\r\n    public xsd_node\r\n{\r\n    xsd_node_key(const string& str) { _name.assign(str); }\r\n    xsd_node_key(const gchar* str) { _name.assign(str); }\r\n    xsd_node_key(const gchar* str, int len) { _name.assign(str, len); }\r\n    xsd_node_type get_type() const override { return xnt_key; }\r\n};\r\n\r\nclass xsd_element:\r\n    public xsd_node\r\n{\r\npublic:\r\n    xsd_element();\r\n    ~xsd_element();\r\n    xsd_node_type get_type() const override { return xnt_element; }\r\n    void set_ref(xsd_element* r) { _ref = r; }\r\n    xsd_element* get_ref() const { return _ref; }\r\n    void set_local_type(xsd_node* n) { _local_type = n; }\r\n    xsd_node* get_local_type() const { return _local_type; }\r\n    string& get_type_name() { return _elem_type_name; }\r\n    string& get_entity_name() { return _elem_entity_name; }\r\n    string& get_verificator() { return _elem_verificator; }\r\n    string& get_assigner() { return _elem_assigner; }\r\n    const string& const_type_name() const { return _elem_type_name; }\r\n    const string& const_entity_name() const { return _elem_entity_name; }\r\n    const string& const_verificator() const { return _elem_verificator; }\r\n    const string& const_assigner() const { return _elem_assigner; }\r\n\r\nprotected:\r\n    xsd_element*            _ref;\r\n    xsd_node*               _local_type;\r\n    string                  _elem_type_name;\r\n    string                  _elem_entity_name;\r\n    string                  _elem_verificator;\r\n    string                  _elem_assigner;\r\n};\r\n\r\nclass xsd_attribute:\r\n    public xsd_node\r\n{\r\npublic:\r\n    xsd_attribute();\r\n    ~xsd_attribute();\r\n    xsd_node_type get_type() const override { return xnt_attribute; }\r\n    void set_ref(xsd_attribute* r) { _ref = 0; }\r\n    xsd_attribute* get_ref() const { return _ref; }\r\n    void set_local_type(xsd_node* n) { _local_type = 0; }\r\n    xsd_node* get_local_type() const { return _local_type; }\r\n    string& get_type_name() { return _attr_type_name; }\r\n    string& get_entity_name() { return _attr_entity_name; }\r\n    string& get_verificator() { return _attr_verificator; }\r\n    string& get_assigner() { return _attr_assigner; }\r\n    const string& const_type_name() const { return _attr_type_name; }\r\n    const string& const_entity_name() const { return _attr_entity_name; }\r\n    const string& const_verificator() const { return _attr_verificator; }\r\n    const string& const_assigner() const { return _attr_assigner; }\r\n\r\nprotected:\r\n    xsd_attribute*          _ref;\r\n    xsd_node*               _local_type;\r\n    string                  _attr_type_name;\r\n    string                  _attr_entity_name;\r\n    string                  _attr_verificator;\r\n    string                  _attr_assigner;\r\n};\r\n\r\nclass xsd_group:\r\n    public xsd_node\r\n{\r\npublic:\r\n    xsd_node_type get_type() const override { return xnt_group; }\r\n\r\nprotected:\r\n};\r\n\r\nclass xsd_attribute_group:\r\n    public xsd_node\r\n{\r\npublic:\r\n    xsd_node_type get_type() const override { return xnt_attribute_group; }\r\n};\r\n\r\nenum xsd_sts_type\r\n{\r\n    xst_restriction,\r\n    xst_union,\r\n    xst_list,\r\n};\r\n\r\nclass __gs_novtable xsd_st_substitution abstract\r\n{\r\npublic:\r\n    virtual ~xsd_st_substitution() {}\r\n    virtual xsd_sts_type get_type() const = 0;\r\n};\r\n\r\nclass xsd_st_restriction:\r\n    public xsd_st_substitution\r\n{\r\npublic:\r\n    xsd_sts_type get_type() const override { return xst_restriction; }\r\n\r\nprotected:\r\n\r\n};\r\n\r\nclass xsd_st_union:\r\n    public xsd_st_substitution\r\n{\r\npublic:\r\n    xsd_sts_type get_type() const override { return xst_union; }\r\n};\r\n\r\nclass xsd_st_list:\r\n    public xsd_st_substitution\r\n{\r\npublic:\r\n    xsd_sts_type get_type() const override { return xst_list; }\r\n};\r\n\r\nclass xsd_simple_type:\r\n    public xsd_node\r\n{\r\npublic:\r\n    xsd_simple_type();\r\n    ~xsd_simple_type();\r\n    xsd_node_type get_type() const override { return xnt_simple_type; }\r\n    void set_ref(xsd_simple_type* r) { _ref = r; }\r\n    xsd_simple_type* get_ref() const { return _ref; }\r\n    void set_substitution(xsd_st_substitution* sub);\r\n    bool build_assigner(string& code, const string& arg, const string& indent);\r\n\r\nprotected:\r\n    xsd_simple_type*        _ref;\r\n    xsd_st_substitution*    _substitution;\r\n};\r\n\r\nclass xsd_complex_type:\r\n    public xsd_node\r\n{\r\npublic:\r\n    xsd_node_type get_type() const override { return xnt_complex_type; }\r\n    bool build_assigner(string& code, const string& arg, const string& indent) { return false; }\r\n};\r\n\r\n__gslib_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "3062295ae545cd86b8d0ba4ed24f68cc1eb63d1d", "size": 13682, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gslib/xsd.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/gslib/xsd.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gslib/xsd.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 32.6539379475, "max_line_length": 175, "alphanum_fraction": 0.6822832919, "num_tokens": 3464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.031618764074832884, "lm_q2_score": 0.028007519186192893, "lm_q1q2_score": 0.0008855631414695886}}
{"text": "/*\n * This file is part of the ProVANT simulator project.\n * Licensed under the terms of the MIT open source license. More details at\n * https://github.com/Guiraffo/ProVANT-Simulator/blob/master/LICENSE.md\n */\n/**\n * @file sdf_parser.h\n * @brief This file contains the declaration of the SDFParser class.\n *\n * @author J\u00fanio Eduardo de Morais Aquino\n */\n\n#ifndef PROVANT_SDF_READER_H\n#define PROVANT_SDF_READER_H\n\n#include <sdf/sdf.hh>\n\n#include <gsl/gsl>\n\n#include \"sdf_status.h\"\n\n/**\n * @brief The SDFParser class is a helper class to read properties from a SDF\n * Element object.\n *\n * This class is specially usefull during the loading of Gazebo plugins where\n * is necessary to read parameters from the plugin SDF description.\n *\n * A SDF (Simulation Description Format) Element, is a specialized XML element\n * that may contain attributes and child elements, as any other XML element\n * can.\n *\n * Gazebo provides a SDF Reader, but many times it has a confusing syntax and\n * very lax documentation, which is very hard to understand and discourages the\n * usage of the SDF class to read its own elements.\n *\n * As there were many instances in the ProVANT Simulator source code that\n * users and developers were using the now depreacted XMLRead class to read the\n * values of SDF elements, this class was designed as a substitution for the\n * XMLRead class, that wraps the methods provided by gazebo into well documented\n * and tested methods.\n *\n * So far, this class provides methods to check the existence, and returns the\n * string values of attributes and elements. In the future, it is very likely\n * that this class will also contain methods to read the values of elements in\n * other types, checking for adequate conversion and validity.\n *\n * @todo It turns out that is really hard to create SDF elements in memory\n * in order to do the testing of this class, so by now THIS CLASS IS UNTESTED!\n * It is imperative that we develop tests for this class. The tests are not\n * hard to create, the problem is that it creating SDF descriptions in memory\n * throws a series of undocumented errors and leads the test executable to a\n * segmentation fault, rendering the test procedure unfeasible.\n */\nclass SDFParser\n{\npublic:\n  /**\n   * @brief Construct a new SDFParser object and initializes the SDF pointer.\n   *\n   * @param sdf SDF element to read data from.\n   */\n  SDFParser(sdf::ElementPtr sdf);\n  /**\n   * @brief Destroy the SDFParser object.\n   * Releases the shared pointer to the SDF element.\n   */\n  virtual ~SDFParser();\n\n  /**\n   * @brief Get the SDF ptr from which this class reads data from.\n   * @return sdf::ElementPtr\n   */\n  virtual sdf::ElementPtr GetElementPtr() const;\n\n  /**\n   * @brief Checks if the SDF contain an attribute with the specified name.\n   *\n   * Attributes are data specific to a element, that are usually strings.\n   * For example, the following XML element:\n   * @code{.xml}\n   * <test type=\"example\">\n   *  <other_data/>\n   * </test>\n   * @endcode\n   *\n   * Contains an attribute named type and with value example.\n   *\n   * Usage example:\n   * Suppose a plugin SDF description as follows:\n   * @code{.xml}\n   * <plugin name=\"example\" filename=\"provant_simulator_step_plugin\">\n   *  <plugin_data/>\n   * </plugin>\n   * @endcode\n   *\n   * Assuming this plugin was read, the following code has res=true, because\n   * the plugin contains an attribute \"name\".\n   * @code{.cpp}\n   * SDFParser reader(_sdf);\n   * bool res = reader.HasAttribute(\"name\");\n   * @endcode\n   *\n   * And the following code results in res=false, because the plugin does not\n   * contain an attribute \"type\".\n   * @code{.cpp}\n   * SDFParser reader(_sdf);\n   * bool res = reader.HasAttribute(\"type\");\n   * @endcode\n   *\n   * @param name\n   * @return true If the SDF element contains an attribute with the specified\n   * name.\n   * @return false Otherwise.\n   */\n  virtual bool HasAttribute(const std::string& name) const;\n  /**\n   * @brief Checks if the SDF has an element with the specified name.\n   *\n   * Usage example:\n   * Suppose a plugin SDF description as follows:\n   * @code{.xml}\n   * <plugin name=\"example\" filename=\"provant_simulator_step_plugin\">\n   *  <plugin_data/>\n   * </plugin>\n   * @endcode\n   *\n   * Assuming this plugin was read, the following code has res=true, because\n   * the plugin contains an element \"plugin_data\".\n   * @code{.cpp}\n   * SDFParser reader(_sdf);\n   * bool res = reader.HasElement(\"plugin_data\");\n   * @endcode\n   *\n   * And the following code results in res=false, because the plugin does not\n   * contain an attribute \"type\".\n   * @code{.cpp}\n   * SDFParser reader(_sdf);\n   * bool res = reader.HasElement(\"type\");\n   * @endcode\n   *\n   * @param name Name of the element to look for.\n   * @return true If the SDF contains an element with the specified name.\n   * @return false Otherwise.\n   */\n  virtual bool HasElement(const std::string& name) const;\n\n  /**\n   * @brief Get an attribute value.\n   *\n   * This checks if an attribute with the specified value exists, and if it\n   * exists, copies its value to the value parameter.\n   *\n   * If the attribute does not exists, or any other occurs, an SDFStatus with an\n   * error and a message describing the problem is returned, and the value is\n   * left emtpy.\n   *\n   * @param name Name of the attribute to return.\n   * @param value Buffer string that will contain the value of the attribute with the specified name.\n   * @return SDFStatus that informs the status of the operation. If the\n   * attribute is found and returned, a OkStatus object is returned, in the case\n   * the attribute does not exist an AttributeNotFoundError object is returned,\n   * containing an error status and a message informing the problem.\n   */\n  virtual SDFStatus GetAttributeValue(const std::string& name, gsl::not_null<std::string*> value) const noexcept;\n  /**\n   * @brief Get an attribute value.\n   *\n   * This method checks if an attribute with the specified name exists, and if\n   * it exists, returns its value.\n   *\n   * @param name Name of the attribute to locate.\n   * @return std::string Value of the attribute.\n   * @throw AttributeNotFoundError If an attribute with the specifed name does\n   * not exist.\n   */\n  virtual std::string GetAttributeValue(const std::string& name) const;\n  /**\n   * @brief Get the text value of a SDF element.\n   *\n   * Check if an element with the specified name exists, and if it exists,\n   * copies its value to the value parameter.\n   *\n   * If an element with the specified name does not exist, or any other\n   * error occurs, the value string is left empty, and a SDFStatus error is\n   * returned with a message identifying the problem.\n   *\n   * @param name Name of the element to read the value.\n   * @param value Buffer string that will contain the value of the element\n   * @return SDFStatus that informs the status of the operation. If at least one\n   * element with the specified name exists, a OkStatus object is returned.\n   * In case an error occurs, an object identifying the problem is returned\n   * with an errors status and a message describing the problem.\n   */\n  virtual SDFStatus GetElementText(const std::string& name, gsl::not_null<std::string*> value) const noexcept;\n  /**\n   * @brief Get the text value of a SDF element.\n   *\n   * Check if an element with the specified name exists, and return is value.\n   *\n   * @sa GetElementText(const std::string& name, std::string* value)\n   *\n   * @param name Name of the element to read the value.\n   * @return std::string Content of the element.\n   * @throw ElementNotFoundError if the element cannot be found as a child of\n   * the SDF element this class reads from.\n   */\n  virtual std::string GetElementText(const std::string& name) const;\n\n  /**\n   * @brief Get the value of a boolean SDF element.\n   *\n   * The valid options are:\n   * For true elements: true in any case combination, or 1.\n   * For false elements: false in any case combinatation, or 0.\n   *\n   * @sa GetElementBool(const std::string&)\n   *\n   * @param name Name of the element to read.\n   * @param value Content of the element.\n   * @return SDFStatus Status of the parse operation. If the element was found\n   * and had a valid value, an OKStatus is returned, otherwise an object\n   * containing and error status and error message is returned.\n   */\n  virtual SDFStatus GetElementBool(const std::string& name, gsl::not_null<bool*> value) const noexcept;\n  /**\n   * @brief Get the value of a boolean SDF element.\n   *\n   * The valid options are:\n   * For true elements: true in any case combination, or 1.\n   * For false elements: false in any case combinatation, or 0.\n   *\n   * @sa GetElementBool(const std::string&, gsl::not_null<int*>)\n   *\n   * @param name Name of the element to read.\n   * @return Value of the element.\n   * @throw SDFStatus exception in case the element is not found or has\n   * invalid content, ie. content that cannot be parsed as a boolean.\n   */\n  virtual bool GetElementBool(const std::string& name) const;\n\n  /**\n   * @brief Get the value of a int SDF element.\n   *\n   * This method can read integer values in the binary (0b), octal (0), decimal\n   * (no prefix), or hexadecimal (0x) formats, identified by their prefixes.\n   * It can also parse signed values with either a - or + signal.\n   *\n   * @sa GetElementInt(const std::string&)\n   *\n   * @param name Name of the element to read.\n   * @param value Value of the element.\n   * @return SDFStatus Status of the parse operation. If the element was found\n   * and had a valid value, an OKStatus is returned, otherwise an object\n   * containing and error status and error message is returned.\n   */\n  virtual SDFStatus GetElementInt(const std::string& name, gsl::not_null<int*> value) const noexcept;\n  /**\n   * @brief Get the value of a int SDF element.\n   *\n   * This method can read integer values in the binary (0b), octal (0), decimal\n   * (no prefix), or hexadecimal (0x) bases, identified by their prefixes.\n   * It can also parse signed values with either a - or + signal.\n   *\n   * @sa GetElementInt(const std::string&, gsl::not_null<int*>)\n   *\n   * @param name Name of the element to read.\n   * @return int Value of the element.\n   * @throw SDFStatus exception in case the element is not found or has\n   * invalid content, ie. content that cannot be parsed as an integer such as\n   * string, or if the value of the element is beyond the current platform limits\n   * for an integer value.\n   */\n  virtual int GetElementInt(const std::string& name) const;\n\n  /**\n   * @brief Get the value of an unsigned int SDF element.\n   *\n   * This method can read unsigned integer values in the binary (0b), octal(0),\n   * decimal (no prefix) or hexadecimal (0x) bases.\n   * In case this methods find a signed integer, it returns an error.\n   *\n   * @sa GetElementUnsignedInt(const std::string&)\n   *\n   * @param name Name of the element to read.\n   * @param value Value of the element.\n   * @return SDFStatus Status of the parse operation. If the element was found\n   * and had a valid value, an OKStatus is returned, otherwise an object\n   * containing and error status and error message is returned.\n   */\n  virtual SDFStatus GetElementUnsignedInt(const std::string& name, gsl::not_null<unsigned int*> value) const noexcept;\n  /**\n   * @brief Get the value of an unsigned int SDF element.\n   *\n   * This method can read unsigned integer values in the binary (0b), octal(0),\n   * decimal (no prefix) or hexadecimal (0x) bases.\n   * In case this methods find a signed integer, it throws an exception.\n   *\n   * @sa GetElementUnsignedInt(const std::string&, gsl::not_null<unsigned int*>)\n   *\n   * @param name Name of the element to read.\n   * @return unsigned int Value of the element.\n   * @throws SDFStatus exception in case the element is not found or has\n   * invalid content, ie. content that cannot be parsed as an integer such as\n   * string, if the value is signed, or if the value is beyond the limits of an\n   * unsigned integer for the current platform.\n   */\n  virtual unsigned int GetElementUnsignedInt(const std::string& name) const;\n\n  /**\n   * @brief Get the value of a single precision (float) SDF Element.\n   *\n   * This method can read real values as single precision floating point values\n   * (float). It is also possible to read floats specified in the hexadecimal\n   * format with the 0x prefix.\n   *\n   * @sa GetElementFloat(const std::string&)\n   *\n   * @param name Name of the element to read.\n   * @param value Value of the element.\n   * @return SDFStatus Status of the parse operation. If the element was found\n   * and had a valid value, an OKStatus is returned, otherwise an object\n   * containing and error status and error message is returned.\n   */\n  virtual SDFStatus GetElementFloat(const std::string& name, gsl::not_null<float*> value) const noexcept;\n  /**\n   * @brief Get the value of a single precision (float) SDF Element.\n   *\n   * This method can read real values as single precision floating point values\n   * (float). It is also possible to read floats specified in the hexadecimal\n   * format with the 0x prefix.\n   *\n   * @sa GetElementFloat(const std::string&, gsl::not_null<float*>)\n   *\n   * @param name Name of the element to read.\n   * @return float Value of the element.\n   * @throws SDFStatus exception in case the element is not found or has\n   * invalid content, ie. content that cannot be parsed as a float or is beyond\n   * the limits of a float for the current platform.\n   */\n  virtual float GetElementFloat(const std::string& name) const;\n\n  /**\n   * @brief Get the value of a double precision floating point (double) SDF Element.\n   *\n   * This method can read real values as double precision floating point values\n   * (double). It is also possible to read doubles specified in the hexadecimal\n   * format with the 0x prefix.\n   *\n   * @sa GetElementDouble(const std::string&)\n   *\n   * @param name Name of the element to read.\n   * @param value Value of the element.\n   * @return SDFStatus Status of the parse operation. If the element was found\n   * and had a valid value, an OKStatus is returned, otherwise an object\n   * containing and error status and error message is returned.\n   */\n  virtual SDFStatus GetElementDouble(const std::string& name, gsl::not_null<double*> value) const noexcept;\n  /**\n   * @brief Get the value of a double precision floating point (double) SDF Element.\n   *\n   * This method can read real values as double precision floating point values\n   * (double). It is also possible to read doubles specified in the hexadecimal\n   * format with the 0x prefix.\n   *\n   * @sa GetElementDouble(const std::string&, gsl::not_null<double*>)\n   *\n   * @param name Name of the element to read.\n   * @return double Value of the element.\n   * @throws SDFStatus exception in case the element is not found or has\n   * invalid content, ie. content that cannot be parsed as a double or is beyond\n   * the limits of a double for the current platform.\n   */\n  virtual double GetElementDouble(const std::string& name) const;\n\nprivate:\n  //! Stores the pointer of the SDF from which this class reads the values of attributes and elements.\n  sdf::ElementPtr _sdf;\n};\n\n#endif  // PROVANT_SDF_READER_H\n", "meta": {"hexsha": "40478c4979082a102eb2e3b4e0ce86b67de5fba0", "size": 15222, "ext": "h", "lang": "C", "max_stars_repo_path": "provant_simulator_utils/provant_simulator_sdf_parser/include/provant_simulator_sdf_parser/sdf_parser.h", "max_stars_repo_name": "Guiraffo/ProVANT_Simulator", "max_stars_repo_head_hexsha": "ef2260204b13f39a9f83ad2ab88a9552a0699bff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "provant_simulator_utils/provant_simulator_sdf_parser/include/provant_simulator_sdf_parser/sdf_parser.h", "max_issues_repo_name": "Guiraffo/ProVANT_Simulator", "max_issues_repo_head_hexsha": "ef2260204b13f39a9f83ad2ab88a9552a0699bff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "provant_simulator_utils/provant_simulator_sdf_parser/include/provant_simulator_sdf_parser/sdf_parser.h", "max_forks_repo_name": "Guiraffo/ProVANT_Simulator", "max_forks_repo_head_hexsha": "ef2260204b13f39a9f83ad2ab88a9552a0699bff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.8481675393, "max_line_length": 118, "alphanum_fraction": 0.7039153856, "num_tokens": 3772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.02096423745386048, "lm_q2_score": 0.042087727615238615, "lm_q1q2_score": 0.0008823371156192635}}
{"text": "#pragma once\n\n#include \"Cesium3DTilesSelection/BoundingVolume.h\"\n#include \"Cesium3DTilesSelection/Library.h\"\n#include \"Cesium3DTilesSelection/Tile.h\"\n#include \"Cesium3DTilesSelection/TileContext.h\"\n#include \"Cesium3DTilesSelection/TileID.h\"\n#include \"Cesium3DTilesSelection/TileRefine.h\"\n#include \"Cesium3DTilesSelection/TilesetOptions.h\"\n\n#include <gsl/span>\n#include <spdlog/fwd.h>\n\n#include <cstddef>\n#include <memory>\n\nnamespace Cesium3DTilesSelection {\n/**\n * @brief The information that is passed to a {@link TileContentLoader} to\n * create a {@link TileContentLoadResult}.\n *\n * For many types of tile content, only the `data` field is required. The other\n * members are used for content that can generate child tiles, like external\n * tilesets or composite tiles. These members are usually initialized from\n * the corresponding members of the {@link Tile} that the content belongs to.\n */\nstruct CESIUM3DTILESSELECTION_API TileContentLoadInput {\n\n  /**\n   * @brief Creates a new, uninitialized instance for the given tile.\n   *\n   * The `data`, `contentType` and `url` will have default values,\n   * and have to be initialized before this instance is passed to\n   * one of the loader functions.\n   *\n   * @param pLogger The logger that will be used\n   * @param tile The {@link Tile} that the content belongs to\n   */\n  TileContentLoadInput(\n      const std::shared_ptr<spdlog::logger> pLogger,\n      const Tile& tile);\n\n  /**\n   * @brief Creates a new instance for the given tile.\n   *\n   * @param pLogger The logger that will be used\n   * @param data The actual data that the tile content will be created from\n   * @param contentType The content type, if the data was received via a\n   * network response\n   * @param url The URL that the data was loaded from\n   * @param tile The {@link Tile} that the content belongs to\n   */\n  TileContentLoadInput(\n      const std::shared_ptr<spdlog::logger> pLogger,\n      const gsl::span<const std::byte>& data,\n      const std::string& contentType,\n      const std::string& url,\n      const Tile& tile);\n\n  /**\n   * @brief Creates a new instance.\n   *\n   * For many types of tile content, only the `data` field is required. The\n   * other parameters are used for content that can generate child tiles, like\n   * external tilesets or composite tiles.\n   *\n   * @param pLogger The logger that will be used\n   * @param data The actual data that the tile content will be created from\n   * @param contentType The content type, if the data was received via a\n   * network response\n   * @param url The URL that the data was loaded from\n   * @param tileID The {@link TileID}\n   * @param tileBoundingVolume The tile {@link BoundingVolume}\n   * @param tileContentBoundingVolume The tile content {@link BoundingVolume}\n   * @param tileRefine The {@link TileRefine} strategy\n   * @param tileGeometricError The geometric error of the tile\n   * @param tileTransform The tile transform\n   */\n  TileContentLoadInput(\n      const std::shared_ptr<spdlog::logger> pLogger,\n      const gsl::span<const std::byte>& data,\n      const std::string& contentType,\n      const std::string& url,\n      const TileID& tileID,\n      const BoundingVolume& tileBoundingVolume,\n      const std::optional<BoundingVolume>& tileContentBoundingVolume,\n      TileRefine tileRefine,\n      double tileGeometricError,\n      const glm::dmat4& tileTransform,\n      const TilesetContentOptions& contentOptions);\n\n  /**\n   * @brief The logger that receives details of loading errors and warnings.\n   */\n  std::shared_ptr<spdlog::logger> pLogger;\n\n  /**\n   * @brief The raw input data.\n   *\n   * The {@link TileContentFactory} will try to determine the type of the\n   * data using the first four bytes (i.e. the \"magic header\"). If this\n   * does not succeed, it will try to determine the type based on the\n   * `contentType` field.\n   */\n  gsl::span<const std::byte> data;\n\n  /**\n   * @brief The content type.\n   *\n   * If the data was obtained via a HTTP response, then this will be\n   * the `Content-Type` of that response. The {@link TileContentFactory}\n   * will try to interpret the data based on this content type.\n   *\n   * If the data was not directly obtained from an HTTP response, then\n   * this may be the empty string.\n   */\n  std::string contentType;\n\n  /**\n   * @brief The source URL.\n   */\n  std::string url;\n\n  /**\n   * @brief The {@link TileID}.\n   */\n  TileID tileID;\n\n  /**\n   * @brief The tile {@link BoundingVolume}.\n   */\n  BoundingVolume tileBoundingVolume;\n\n  /**\n   * @brief Tile content {@link BoundingVolume}.\n   */\n  std::optional<BoundingVolume> tileContentBoundingVolume;\n\n  /**\n   * @brief The {@link TileRefine}.\n   */\n  TileRefine tileRefine;\n\n  /**\n   * @brief The geometric error.\n   */\n  double tileGeometricError;\n\n  /**\n   * @brief The tile transform\n   */\n  glm::dmat4 tileTransform;\n\n  /**\n   * @brief Options for parsing content and creating Gltf models.\n   */\n  TilesetContentOptions contentOptions;\n};\n} // namespace Cesium3DTilesSelection\n", "meta": {"hexsha": "a5ff7f8f2ef7c76616e8e18fc843d1b7022e42d0", "size": 4986, "ext": "h", "lang": "C", "max_stars_repo_path": "Cesium3DTilesSelection/include/Cesium3DTilesSelection/TileContentLoadInput.h", "max_stars_repo_name": "zrkcode/cesium-native", "max_stars_repo_head_hexsha": "5265a65053542fe02928c272762c6b89fa2b29bb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Cesium3DTilesSelection/include/Cesium3DTilesSelection/TileContentLoadInput.h", "max_issues_repo_name": "zrkcode/cesium-native", "max_issues_repo_head_hexsha": "5265a65053542fe02928c272762c6b89fa2b29bb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cesium3DTilesSelection/include/Cesium3DTilesSelection/TileContentLoadInput.h", "max_forks_repo_name": "zrkcode/cesium-native", "max_forks_repo_head_hexsha": "5265a65053542fe02928c272762c6b89fa2b29bb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1625, "max_line_length": 79, "alphanum_fraction": 0.6995587645, "num_tokens": 1247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.04603390632552803, "lm_q2_score": 0.019124037764151, "lm_q1q2_score": 0.0008803541630007875}}
{"text": "#pragma once\n#include <ntdll.h>\n#include <gsl/span>\n#include <gsl/span_ext>\n#include \"module.h\"\n\nnamespace pe\n{\n  class module;\n\n  class segment : public IMAGE_SECTION_HEADER\n  {\n  public:\n    segment() = delete;\n\n    const class module *module() const;\n    class module *module();\n    std::string_view name() const;\n    gsl::span<uint8_t> as_bytes();\n    gsl::span<const uint8_t> as_bytes() const;\n    bool contains_code() const;\n    bool contains_initialized_data() const;\n    bool contains_uninitialized_data() const;\n    uint32_t relocation_count() const;\n    bool discardable() const;\n    bool not_cached() const;\n    bool not_paged() const;\n    bool shared() const;\n    bool executable() const;\n    bool readable() const;\n    bool writable() const;\n  };\n}\n\n#include \"segment.inl\"\n", "meta": {"hexsha": "183e1c83ff5727f20044694505e3942a549371ab", "size": 786, "ext": "h", "lang": "C", "max_stars_repo_path": "include/pe/segment.h", "max_stars_repo_name": "bnsmodpolice/loginhelper", "max_stars_repo_head_hexsha": "7505878b225c7be144ec5e8abf4484133b2cbff9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-12-18T04:53:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-22T20:48:03.000Z", "max_issues_repo_path": "include/pe/segment.h", "max_issues_repo_name": "bnsmodpolice/loginhelper", "max_issues_repo_head_hexsha": "7505878b225c7be144ec5e8abf4484133b2cbff9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/pe/segment.h", "max_forks_repo_name": "bnsmodpolice/loginhelper", "max_forks_repo_head_hexsha": "7505878b225c7be144ec5e8abf4484133b2cbff9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-18T18:03:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-18T18:03:36.000Z", "avg_line_length": 21.8333333333, "max_line_length": 46, "alphanum_fraction": 0.6768447837, "num_tokens": 192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.04742587721667507, "lm_q2_score": 0.018546565224121573, "lm_q1q2_score": 0.0008795871251102455}}
{"text": "#pragma once\n\n#ifndef __linux__\n#error We only support Linux\n#endif\n\n#ifndef _GNU_SOURCE\n#define _GNU_SOURCE\n#endif\n\n#ifdef __FAAS_CPP_WORKER\n#if !defined(__FAAS_USED_IN_BINDING) && !defined(__FAAS_CPP_WORKER_SRC)\n#error Need the source file to have __FAAS_USED_IN_BINDING defined\n#endif\n#endif\n\n#ifdef __FAAS_NODE_ADDON\n#if !defined(__FAAS_USED_IN_BINDING) && !defined(__FAAS_NODE_ADDON_SRC)\n#error Need the source file to have __FAAS_USED_IN_BINDING defined\n#endif\n#define __FAAS_CXX_NO_EXCEPTIONS\n#endif\n\n#ifdef __FAAS_PYTHON_BINDING\n#if !defined(__FAAS_USED_IN_BINDING) && !defined(__FAAS_PYTHON_BINDING_SRC)\n#error Need the source file to have __FAAS_USED_IN_BINDING defined\n#endif\n#include <Python.h>\n#if PY_VERSION_HEX < 0x03070000\n#error FaaS Python binding requires Python 3.7+\n#endif\n#endif\n\n// C includes\n#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <time.h>\n#include <unistd.h>\n\n// C++ includes\n#include <limits>\n#include <atomic>\n#include <memory>\n#include <utility>\n#include <optional>\n#include <sstream>\n#include <string>\n#include <string_view>\n#include <functional>\n#include <algorithm>\n\n// STL containers\n#include <vector>\n#include <queue>\n#include <map>\n#include <set>\n#include <unordered_map>\n#include <unordered_set>\n#ifdef __FAAS_CPP_WORKER\n#include <mutex>\n#endif\n\n// fmtlib\n#define FMT_HEADER_ONLY\n#include <fmt/core.h>\n#include <fmt/format.h>\n\n// Guidelines Support Library (GSL)\n#include <gsl/gsl>\n\n#include \"base/diagnostic.h\"\n\n#ifdef __FAAS_SRC\n#define __FAAS_HAVE_ABSL\n#endif\n\n#if defined(__FAAS_HAVE_ABSL) && !defined(__FAAS_USED_IN_BINDING)\n\n// Will not include common absl headers in source files\n// with __FAAS_USED_IN_BINDING defined\n\n__BEGIN_THIRD_PARTY_HEADERS\n\n#include <absl/base/call_once.h>\n#include <absl/flags/flag.h>\n#include <absl/time/time.h>\n#include <absl/time/clock.h>\n#include <absl/strings/str_cat.h>\n#include <absl/strings/match.h>\n#include <absl/strings/strip.h>\n#include <absl/strings/str_split.h>\n#include <absl/strings/numbers.h>\n#include <absl/strings/ascii.h>\n#include <absl/random/random.h>\n#include <absl/random/distributions.h>\n#include <absl/container/flat_hash_map.h>\n#include <absl/container/flat_hash_set.h>\n#include <absl/container/fixed_array.h>\n#include <absl/container/inlined_vector.h>\n#include <absl/synchronization/mutex.h>\n#include <absl/synchronization/notification.h>\n#include <absl/functional/bind_front.h>\n#include <absl/algorithm/container.h>\n\n__END_THIRD_PARTY_HEADERS\n\n#endif  // defined(__FAAS_HAVE_ABSL) && !defined(__FAAS_USED_IN_BINDING)\n\n#include \"base/macro.h\"\n#include \"base/logging.h\"\n#include \"base/std_span.h\"\n", "meta": {"hexsha": "c163afb3ee34653a6783fde0fddd55e0c58298af", "size": 2641, "ext": "h", "lang": "C", "max_stars_repo_path": "src/base/common.h", "max_stars_repo_name": "jhweintraub/boki", "max_stars_repo_head_hexsha": "65f3c713211c41329878f0057d8659a89243b388", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2021-09-02T13:11:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T09:38:40.000Z", "max_issues_repo_path": "src/base/common.h", "max_issues_repo_name": "jhweintraub/boki", "max_issues_repo_head_hexsha": "65f3c713211c41329878f0057d8659a89243b388", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/base/common.h", "max_forks_repo_name": "jhweintraub/boki", "max_forks_repo_head_hexsha": "65f3c713211c41329878f0057d8659a89243b388", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-09-02T13:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T20:54:11.000Z", "avg_line_length": 23.1666666667, "max_line_length": 75, "alphanum_fraction": 0.7800075729, "num_tokens": 690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.04958902719777796, "lm_q2_score": 0.017712301263593695, "lm_q1q2_score": 0.0008783357890955847}}
{"text": "/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */\n/*\n *     Copyright 2017-Present Couchbase, Inc.\n *\n *   Use of this software is governed by the Business Source License included\n *   in the file licenses/BSL-Couchbase.txt.  As of the Change Date specified\n *   in that file, in accordance with the Business Source License, use of this\n *   software will be governed by the Apache License, Version 2.0, included in\n *   the file licenses/APL2.txt.\n */\n#pragma once\n\n#include <mcbp/protocol/opcode.h>\n#include <mcbp/protocol/request.h>\n#include <mcbp/protocol/response.h>\n#include <mcbp/protocol/status.h>\n\n#include <gsl/gsl-lite.hpp>\n\nnamespace cb::mcbp {\n\n/**\n * FrameBuilder allows you to build up a request / response frame in\n * a provided memory area. It provides helper methods which makes sure\n * that the fields is formatted in the correct byte order etc.\n *\n * The frame looks like:\n *\n *\n *     Byte/     0       |       1       |       2       |       3       |\n *        /              |               |               |               |\n *       |0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|\n *       +---------------+---------------+---------------+---------------+\n *      0| Magic         |               | Framing extras| Key Length    |\n *       +---------------+---------------+---------------+---------------+\n *      4| Extras length |               |                               |\n *       +---------------+---------------+---------------+---------------+\n *      8| Total body length                                             |\n *       +---------------+---------------+---------------+---------------+\n *     12|                                                               |\n *       +---------------+---------------+---------------+---------------+\n *     16|                                                               |\n *       |                                                               |\n *       +---------------+---------------+---------------+---------------+\n *     24| Optional section containing framing extras Max 255 bytes      |\n *       +---------------------------------------------------------------+\n *       | Optional section containing command extras                    |\n *       +---------------------------------------------------------------+\n *       | Optional section containing the key                           |\n *       +---------------------------------------------------------------+\n *       | Optional section containing the value.                        |\n *       | The size of the value is the total body length minus the      |\n *       | size of the optional framing extras, extras and key.          |\n *       +---------------------------------------------------------------+\n *\n */\ntemplate <typename T>\nclass FrameBuilder {\npublic:\n    explicit FrameBuilder(cb::char_buffer backing, bool initialized = false)\n        : FrameBuilder(\n                  {reinterpret_cast<uint8_t*>(backing.data()), backing.size()},\n                  initialized) {\n    }\n\n    explicit FrameBuilder(cb::byte_buffer backing, bool initialized = false)\n        : buffer(backing) {\n        checkSize(sizeof(T));\n        if (!initialized) {\n            std::fill(backing.begin(), backing.begin() + sizeof(T), 0);\n        }\n    }\n\n    T* getFrame() {\n        return reinterpret_cast<T*>(buffer.data());\n    }\n\n    void setMagic(Magic magic) {\n        getFrame()->setMagic(magic);\n    }\n\n    void setOpcode(ClientOpcode opcode) {\n        getFrame()->setOpcode(opcode);\n    }\n\n    void setOpcode(ServerOpcode opcode) {\n        getFrame()->setOpcode(opcode);\n    }\n\n    void setDatatype(Datatype datatype) {\n        getFrame()->setDatatype(datatype);\n    }\n\n    void setVBucket(Vbid value) {\n        getFrame()->setVBucket(value);\n    }\n\n    void setOpaque(uint32_t opaque) {\n        getFrame()->setOpaque(opaque);\n    }\n\n    void setCas(uint64_t val) {\n        getFrame()->setCas(val);\n    }\n\n    /**\n     * Insert/replace the Framing extras section and move the rest of the\n     * sections to their new locations.\n     */\n    void setFramingExtras(cb::const_byte_buffer val) {\n        if (!is_alternative_encoding(getFrame()->getMagic())) {\n            throw std::logic_error(\n                    R\"(setFramingExtras: Magic needs to be one of the alternative packet encodings)\");\n        }\n        auto* req = getFrame();\n        auto existing = req->getFramingExtras();\n        // can we fit the data?\n        checkSize(existing.size(), val.size());\n        moveAndInsert(existing, val, req->getBodylen() - existing.size());\n        req->setFramingExtraslen(gsl::narrow<uint8_t>(val.size()));\n    }\n\n    /**\n     * Insert/replace the Extras section and move the rest of the sections\n     * to their new locations.\n     */\n    void setExtras(cb::const_byte_buffer val) {\n        auto* req = getFrame();\n        auto existing = req->getExtdata();\n        checkSize(existing.size(), val.size());\n        auto move_size = req->getKey().size() + req->getValue().size();\n        moveAndInsert(existing, val, move_size);\n        req->setExtlen(gsl::narrow<uint8_t>(val.size()));\n    }\n    void setExtras(std::string_view val) {\n        setExtras({reinterpret_cast<const uint8_t*>(val.data()), val.size()});\n    }\n\n    /**\n     * Insert/replace the Key section and move the value section to the new\n     * location.\n     */\n    void setKey(cb::const_byte_buffer val) {\n        auto* req = getFrame();\n        auto existing = req->getKey();\n        checkSize(existing.size(), val.size());\n        moveAndInsert(existing, val, req->getValue().size());\n        req->setKeylen(gsl::narrow<uint16_t>(val.size()));\n    }\n\n    void setKey(std::string_view val) {\n        setKey({reinterpret_cast<const uint8_t*>(val.data()), val.size()});\n    }\n\n    /**\n     * Insert/replace the value section.\n     */\n    void setValue(cb::const_byte_buffer val) {\n        auto* req = getFrame();\n        auto existing = req->getValue();\n        checkSize(existing.size(), val.size());\n        moveAndInsert(existing, val, 0);\n    }\n\n    void setValue(std::string_view val) {\n        setValue({reinterpret_cast<const uint8_t*>(val.data()), val.size()});\n    }\n\n    /**\n     * Try to validate the underlying packet\n     */\n    void validate() {\n        getFrame()->isValid();\n    }\n\nprotected:\n    /**\n     * check that the requested size fits into the buffer\n     *\n     * @param size The total requested size (including header)\n     */\n    void checkSize(size_t size) {\n        if (size > buffer.size()) {\n            throw std::logic_error(\n                    \"FrameBuilder::checkSize: too big to fit in buffer\");\n        }\n    }\n\n    /**\n     * check if there is room in the buffer to replace the field with\n     * one with a different size\n     *\n     * @param oldfield\n     * @param newfield\n     */\n    void checkSize(size_t oldfield, size_t newfield) {\n        checkSize(sizeof(T) + getFrame()->getBodylen() - oldfield + newfield);\n    }\n\n    /**\n     * Move the rest of the packet to the new location and insert the\n     * new value\n     */\n    void moveAndInsert(cb::byte_buffer existing,\n                       cb::const_byte_buffer value,\n                       size_t size) {\n        auto* location = existing.data();\n        if (size > 0 && existing.size() != value.size()) {\n            // we need to move the data following this entry to a different\n            // location.\n            memmove(location + value.size(), location + existing.size(), size);\n        }\n        std::copy(value.begin(), value.end(), location);\n        auto* req = getFrame();\n        // Update the total length\n        req->setBodylen(gsl::narrow<uint32_t>(req->getBodylen() -\n                                              existing.size() + value.size()));\n    }\n\n    cb::byte_buffer buffer;\n};\n\n/**\n * Specialized class to build a Request\n */\nclass RequestBuilder : public FrameBuilder<Request> {\npublic:\n    explicit RequestBuilder(cb::char_buffer backing, bool initialized = false)\n        : RequestBuilder(\n                  {reinterpret_cast<uint8_t*>(backing.data()), backing.size()},\n                  initialized) {\n    }\n    explicit RequestBuilder(cb::byte_buffer backing, bool initialized = false)\n        : FrameBuilder<Request>(backing, initialized) {\n    }\n    void setVbucket(Vbid vbucket) {\n        getFrame()->setVBucket(vbucket);\n    }\n};\n\n/**\n * Specialized class to build a response\n */\nclass ResponseBuilder : public FrameBuilder<Response> {\npublic:\n    explicit ResponseBuilder(cb::char_buffer backing, bool initialized = false)\n        : ResponseBuilder(\n                  {reinterpret_cast<uint8_t*>(backing.data()), backing.size()},\n                  initialized) {\n    }\n    explicit ResponseBuilder(cb::byte_buffer backing, bool initialized = false)\n        : FrameBuilder<Response>(backing, initialized) {\n    }\n    void setStatus(Status status) {\n        getFrame()->setStatus(status);\n    }\n};\n\n} // namespace cb::mcbp\n", "meta": {"hexsha": "089bc26994b5256b13ddae5c355145ed0f0e4c29", "size": 9017, "ext": "h", "lang": "C", "max_stars_repo_path": "include/mcbp/protocol/framebuilder.h", "max_stars_repo_name": "nawazish-couchbase/kv_engine", "max_stars_repo_head_hexsha": "132f1bb04c9212bcac9e401d069aeee5f63ff1cd", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": 104.0, "max_stars_repo_stars_event_min_datetime": "2017-05-22T20:41:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T00:18:34.000Z", "max_issues_repo_path": "include/mcbp/protocol/framebuilder.h", "max_issues_repo_name": "nawazish-couchbase/kv_engine", "max_issues_repo_head_hexsha": "132f1bb04c9212bcac9e401d069aeee5f63ff1cd", "max_issues_repo_licenses": ["MIT", "BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-11-14T08:12:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T11:14:17.000Z", "max_forks_repo_path": "include/mcbp/protocol/framebuilder.h", "max_forks_repo_name": "nawazish-couchbase/kv_engine", "max_forks_repo_head_hexsha": "132f1bb04c9212bcac9e401d069aeee5f63ff1cd", "max_forks_repo_licenses": ["MIT", "BSD-3-Clause"], "max_forks_count": 71.0, "max_forks_repo_forks_event_min_datetime": "2017-05-22T20:41:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T10:34:32.000Z", "avg_line_length": 34.6807692308, "max_line_length": 102, "alphanum_fraction": 0.5169124986, "num_tokens": 1964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.060086646807761206, "lm_q2_score": 0.014503578519960881, "lm_q1q2_score": 0.0008714713999775214}}
{"text": "// MIT License\n//\n// Copyright (c) 2020 SunnyCase\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n#pragma once\n#include \"chinodef.h\"\n#include <atomic>\n#include <chino/error.h>\n#include <chino/result.h>\n#include <gsl/gsl-lite.hpp>\n#include <string_view>\n\nnamespace chino::io\n{\nenum class std_handles\n{\n    in,\n    out,\n    err\n};\n\nenum class create_disposition\n{\n    create_always = 2,\n    create_new = 1,\n    open_always = 4,\n    open_existing = 3,\n    truncate_existing = 5\n};\n\nresult<void, error_code> alloc_console() noexcept;\nhandle_t get_std_handle(std_handles type) noexcept;\n\nresult<handle_t, error_code> open(const insert_lookup_object_options &options, create_disposition create_disp = create_disposition::open_existing) noexcept;\nresult<size_t, error_code> read(handle_t file, gsl::span<gsl::byte> buffer) noexcept;\nresult<void, error_code> write(handle_t file, gsl::span<const gsl::byte> buffer) noexcept;\nresult<void, error_code> close(handle_t file) noexcept;\n}\n", "meta": {"hexsha": "a4c2e8130c2ea694462fd0cbf6a1fee2735ac9c9", "size": 2002, "ext": "h", "lang": "C", "max_stars_repo_path": "src/api/include/chino/io.h", "max_stars_repo_name": "chino-os/chino-os", "max_stars_repo_head_hexsha": "e4b444983a059231636b81dc5f33206e16a859c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2018-04-28T09:50:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T11:42:23.000Z", "max_issues_repo_path": "src/api/include/chino/io.h", "max_issues_repo_name": "dotnetGame/chino-os", "max_issues_repo_head_hexsha": "e4b444983a059231636b81dc5f33206e16a859c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2018-05-15T02:15:33.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-30T14:46:51.000Z", "max_forks_repo_path": "src/api/include/chino/io.h", "max_forks_repo_name": "dotnetGame/chino-os", "max_forks_repo_head_hexsha": "e4b444983a059231636b81dc5f33206e16a859c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2018-05-18T03:54:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T10:14:07.000Z", "avg_line_length": 35.75, "max_line_length": 156, "alphanum_fraction": 0.7572427572, "num_tokens": 461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.039048294962802745, "lm_q2_score": 0.022286186026259033, "lm_q1q2_score": 0.0008702375655492555}}
{"text": "// MIT License\n//\n// Copyright (c) 2020 SunnyCase\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n#pragma once\n#include <chino/ddk/kernel.h>\n#include <cstdint>\n#include <gsl/gsl-lite.hpp>\n#include <xmmintrin.h>\n\nnamespace chino::arch\n{\n// No asynchronous interrupt is supported by this target\n// Only save callee saved registers in context\nstruct win32_thread_context\n{\n    uintptr_t rbx;\n    uintptr_t rbp;\n    uintptr_t rdi;\n    uintptr_t rsi;\n    uintptr_t rsp;\n    uintptr_t r12;\n    uintptr_t r13;\n    uintptr_t r14;\n    uintptr_t r15;\n    uintptr_t reserved0;\n\n    __m128 xmm6;\n    __m128 xmm7;\n    __m128 xmm8;\n    __m128 xmm9;\n    __m128 xmm10;\n    __m128 xmm11;\n    __m128 xmm12;\n    __m128 xmm13;\n    __m128 xmm14;\n    __m128 xmm15;\n\n    uintptr_t stack_low;\n    uintptr_t stack_high;\n};\n\nusing thread_context_t = win32_thread_context;\n\nstruct win32_arch\n{\n    static constexpr size_t ALLOCATE_ALIGNMENT = 16;\n\n    static uint32_t current_processor() noexcept { return 0; }\n    static void yield_processor() noexcept;\n\n    static uintptr_t disable_irq() noexcept;\n    static void restore_irq(uintptr_t state) noexcept;\n\n    static void init_thread_context(thread_context_t &context, gsl::span<uintptr_t> stack, kernel::thread_thunk_t start, void *arg0, void *arg1) noexcept;\n    [[noreturn]] static void start_schedule(thread_context_t &context) noexcept;\n    static void yield(thread_context_t &old_context, thread_context_t &new_context) noexcept;\n\n    static void init_stack_check() noexcept;\n};\n\nusing arch_t = win32_arch;\n}\n", "meta": {"hexsha": "39ee7e26d1a444ed0909deb70ed590056d14105c", "size": 2566, "ext": "h", "lang": "C", "max_stars_repo_path": "src/hal/include/chino/arch/win32/arch.h", "max_stars_repo_name": "chino-os/chino-os", "max_stars_repo_head_hexsha": "e4b444983a059231636b81dc5f33206e16a859c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2018-04-28T09:50:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T11:42:23.000Z", "max_issues_repo_path": "src/hal/include/chino/arch/win32/arch.h", "max_issues_repo_name": "dotnetGame/chino-os", "max_issues_repo_head_hexsha": "e4b444983a059231636b81dc5f33206e16a859c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2018-05-15T02:15:33.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-30T14:46:51.000Z", "max_forks_repo_path": "src/hal/include/chino/arch/win32/arch.h", "max_forks_repo_name": "dotnetGame/chino-os", "max_forks_repo_head_hexsha": "e4b444983a059231636b81dc5f33206e16a859c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2018-05-18T03:54:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T10:14:07.000Z", "avg_line_length": 31.6790123457, "max_line_length": 154, "alphanum_fraction": 0.74395947, "num_tokens": 614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.05340332377362639, "lm_q2_score": 0.016152832365257386, "lm_q1q2_score": 0.0008626149366629515}}
{"text": "/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */\n/*\n *     Copyright 2017 Couchbase, Inc.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n */\n#pragma once\n\n#include <mcbp/protocol/dcp_stream_end_status.h>\n#include <mcbp/protocol/status.h>\n#include <memcached/dcp_stream_id.h>\n#include <memcached/engine_error.h>\n#include <memcached/types.h>\n#include <memcached/vbucket.h>\n#include <memcached/visibility.h>\n#include <gsl/gsl>\n\nstruct DocKey;\n\nnamespace cb::durability {\nclass Requirements;\nenum class Level : uint8_t;\n} // namespace cb::durability\n\nnamespace cb::mcbp {\nclass Response;\n}\n\nnamespace mcbp::systemevent {\nenum class id : uint32_t;\nenum class version : uint8_t;\n} // namespace mcbp::systemevent\n\nclass DcpConnHandlerIface {\npublic:\n    virtual ~DcpConnHandlerIface() = default;\n};\n\n/**\n * The message producers are used by the engine's DCP producer\n * to add messages into the DCP stream.  Please look at the full\n * DCP documentation to figure out the real meaning for all of the\n * messages.\n */\nstruct DcpMessageProducersIface {\n    virtual ~DcpMessageProducersIface() = default;\n\n    virtual ENGINE_ERROR_CODE get_failover_log(uint32_t opaque,\n                                               Vbid vbucket) = 0;\n\n    virtual ENGINE_ERROR_CODE stream_req(uint32_t opaque,\n                                         Vbid vbucket,\n                                         uint32_t flags,\n                                         uint64_t start_seqno,\n                                         uint64_t end_seqno,\n                                         uint64_t vbucket_uuid,\n                                         uint64_t snap_start_seqno,\n                                         uint64_t snap_end_seqno,\n                                         const std::string& request_value) = 0;\n\n    virtual ENGINE_ERROR_CODE add_stream_rsp(uint32_t opaque,\n                                             uint32_t stream_opaque,\n                                             cb::mcbp::Status status) = 0;\n\n    virtual ENGINE_ERROR_CODE marker_rsp(uint32_t opaque,\n                                         cb::mcbp::Status status) = 0;\n\n    virtual ENGINE_ERROR_CODE set_vbucket_state_rsp(\n            uint32_t opaque, cb::mcbp::Status status) = 0;\n\n    /**\n     * Send a Stream End message\n     *\n     * @param opaque this is the opaque requested by the consumer\n     *               in the Stream Request message\n     * @param vbucket the vbucket id the message belong to\n     * @param status the reason for the stream end.\n     *              0 = success\n     *              1+ = Something happened on the vbucket causing\n     *                   us to abort it.\n     * @param sid The stream-ID the end applies to (can be 0 for none)\n     *\n     * @return ENGINE_SUCCESS upon success\n     *         ENGINE_EWOULDBLOCK if no data is available\n     *         ENGINE_* for errors\n     */\n    virtual ENGINE_ERROR_CODE stream_end(uint32_t opaque,\n                                         Vbid vbucket,\n                                         cb::mcbp::DcpStreamEndStatus status,\n                                         cb::mcbp::DcpStreamId sid) = 0;\n\n    /**\n     * Send a marker\n     *\n     * @param opaque this is the opaque requested by the consumer\n     *               in the Stream Request message\n     * @param vbucket the vbucket id the message belong to\n     * @param start_seqno start of the snapshot range\n     * @param end_seqno end of the snapshot range\n     * @param flags snapshot marker flags (DISK/MEMORY/CHK/ACK).\n     * @param highCompletedSeqno the SyncRepl high completed seqno\n     * @param maxVisibleSeqno highest committed seqno (ignores prepare/abort)\n     * @param timestamp for the data in the snapshot marker (only valid for\n     *                  disk type and represents the disk commit time)\n     * @param sid The stream-ID the marker applies to (can be 0 for none)\n     *\n     * @return ENGINE_SUCCESS upon success\n     */\n    virtual ENGINE_ERROR_CODE marker(uint32_t opaque,\n                                     Vbid vbucket,\n                                     uint64_t start_seqno,\n                                     uint64_t end_seqno,\n                                     uint32_t flags,\n                                     std::optional<uint64_t> highCompletedSeqno,\n                                     std::optional<uint64_t> maxVisibleSeqno,\n                                     std::optional<uint64_t> timestamp,\n                                     cb::mcbp::DcpStreamId sid) = 0;\n\n    /**\n     * Send a Mutation\n     *\n     * @param opaque this is the opaque requested by the consumer\n     *               in the Stream Request message\n     * @param itm the item to send.\n     * @param vbucket the vbucket id the message belong to\n     * @param by_seqno\n     * @param rev_seqno\n     * @param lock_time\n     * @param nru the nru field used by ep-engine (may safely be ignored)\n     * @param sid The stream-ID the mutation applies to (can be 0 for none)\n     *\n     * @return ENGINE_SUCCESS upon success\n     */\n    virtual ENGINE_ERROR_CODE mutation(uint32_t opaque,\n                                       cb::unique_item_ptr itm,\n                                       Vbid vbucket,\n                                       uint64_t by_seqno,\n                                       uint64_t rev_seqno,\n                                       uint32_t lock_time,\n                                       uint8_t nru,\n                                       cb::mcbp::DcpStreamId sid) = 0;\n\n    /**\n     * Send a deletion\n     *\n     * @param opaque this is the opaque requested by the consumer\n     *               in the Stream Request message\n     * @param itm the item to send.\n     * @param by_seqno\n     * @param rev_seqno\n     * @param sid The stream-ID the deletion applies to (can be 0 for none)\n     *\n     * @return ENGINE_SUCCESS upon success\n     */\n    virtual ENGINE_ERROR_CODE deletion(uint32_t opaque,\n                                       cb::unique_item_ptr itm,\n                                       Vbid vbucket,\n                                       uint64_t by_seqno,\n                                       uint64_t rev_seqno,\n                                       cb::mcbp::DcpStreamId sid) = 0;\n\n    /**\n     * Send a deletion with delete_time or collections (or both)\n     *\n     * @param opaque this is the opaque requested by the consumer\n     *               in the Stream Request message\n     * @param itm the item to send.\n     * @param vbucket the vbucket id the message belong to\n     * @param by_seqno\n     * @param rev_seqno\n     * @param delete_time the time of the deletion (tombstone creation time)\n     * @param sid The stream-ID the deletion applies to (can be 0 for none)\n     *\n     * @return ENGINE_SUCCESS upon success\n     */\n    virtual ENGINE_ERROR_CODE deletion_v2(uint32_t opaque,\n                                          cb::unique_item_ptr itm,\n                                          Vbid vbucket,\n                                          uint64_t by_seqno,\n                                          uint64_t rev_seqno,\n                                          uint32_t delete_time,\n                                          cb::mcbp::DcpStreamId sid) = 0;\n\n    /**\n     * Send an expiration\n     *\n     * @param opaque this is the opaque requested by the consumer\n     *               in the Stream Request message\n     * @param itm the item to send.\n     * @param by_seqno\n     * @param rev_seqno\n     * @param delete_time the time of the deletion (tombstone creation time)\n     * @param sid The stream-ID the expiration applies to (can be 0 for none)\n     *\n     * @return ENGINE_SUCCESS upon success\n     */\n    virtual ENGINE_ERROR_CODE expiration(uint32_t opaque,\n                                         cb::unique_item_ptr itm,\n                                         Vbid vbucket,\n                                         uint64_t by_seqno,\n                                         uint64_t rev_seqno,\n                                         uint32_t delete_time,\n                                         cb::mcbp::DcpStreamId sid) = 0;\n\n    /**\n     * Send a state transition for a vbucket\n     *\n     * @param opaque this is the opaque requested by the consumer\n     *               in the Stream Request message\n     * @param vbucket the vbucket id the message belong to\n     * @param state the new state\n     *\n     * @return ENGINE_SUCCESS upon success\n     */\n    virtual ENGINE_ERROR_CODE set_vbucket_state(uint32_t opaque,\n                                                Vbid vbucket,\n                                                vbucket_state_t state) = 0;\n\n    /**\n     * Send a noop\n     *\n     * @param opaque what to use as the opaque in the buffer\n     *\n     * @return ENGINE_SUCCESS upon success\n     */\n    virtual ENGINE_ERROR_CODE noop(uint32_t opaque) = 0;\n\n    /**\n     * Send a buffer acknowledgment\n     *\n     * @param opaque this is the opaque requested by the consumer\n     *               in the Stream Request message\n     * @param vbucket the vbucket id the message belong to\n     * @param buffer_bytes the amount of bytes processed\n     *\n     * @return ENGINE_SUCCESS upon success\n     */\n    virtual ENGINE_ERROR_CODE buffer_acknowledgement(uint32_t opaque,\n                                                     Vbid vbucket,\n                                                     uint32_t buffer_bytes) = 0;\n\n    /**\n     * Send a control message to the other end\n     *\n     * @param opaque what to use as the opaque in the buffer\n     * @param key the identifier for the property to set\n     * @param value The value for the property (the layout of the\n     *              value is defined for the key)\n     *\n     * @return ENGINE_SUCCESS upon success\n     */\n    virtual ENGINE_ERROR_CODE control(uint32_t opaque,\n                                      std::string_view key,\n                                      std::string_view value) = 0;\n\n    /**\n     * Send a system event message to the other end\n     *\n     * @param cookie passed on the cookie provided by step\n     * @param opaque what to use as the opaque in the buffer\n     * @param vbucket the vbucket the event applies to\n     * @param bySeqno the sequence number of the event\n     * @param version A version value defining the eventData format\n     * @param key the system event's key data\n     * @param eventData the system event's specific data\n     * @param sid The stream-ID the event applies to (can be 0 for none)\n     *\n     * @return ENGINE_SUCCESS upon success\n     */\n    virtual ENGINE_ERROR_CODE system_event(uint32_t opaque,\n                                           Vbid vbucket,\n                                           mcbp::systemevent::id event,\n                                           uint64_t bySeqno,\n                                           mcbp::systemevent::version version,\n                                           cb::const_byte_buffer key,\n                                           cb::const_byte_buffer eventData,\n                                           cb::mcbp::DcpStreamId sid) = 0;\n\n    /*\n     * Send a GetErrorMap message to the other end\n     *\n     * @param opaque The opaque to send over\n     * @param version The version of the error map\n     *\n     * @return ENGINE_SUCCESS upon success\n     */\n    virtual ENGINE_ERROR_CODE get_error_map(uint32_t opaque,\n                                            uint16_t version) = 0;\n\n    /**\n     * See mutation for a description of the parameters except for:\n     *\n     * @param deleted Are we storing a deletion operation?\n     * @param durability the durability specification for this item\n     */\n    virtual ENGINE_ERROR_CODE prepare(uint32_t opaque,\n                                      cb::unique_item_ptr itm,\n                                      Vbid vbucket,\n                                      uint64_t by_seqno,\n                                      uint64_t rev_seqno,\n                                      uint32_t lock_time,\n                                      uint8_t nru,\n                                      DocumentState document_state,\n                                      cb::durability::Level level) = 0;\n\n    /**\n     * Send a seqno ack message\n     *\n     * It serves to inform KV-Engine active nodes that the replica has\n     * successfully received and prepared to memory/disk all DCP_PREPARE\n     * messages up to the specified seqno.\n     *\n     * @param opaque identifying stream\n     * @param vbucket the vbucket the seqno ack is for\n     * @param prepared_seqno The seqno the replica has prepared up to.\n     */\n    virtual ENGINE_ERROR_CODE seqno_acknowledged(uint32_t opaque,\n                                                 Vbid vbucket,\n                                                 uint64_t prepared_seqno) = 0;\n\n    /**\n     * Send a commit message:\n     *\n     * This is sent from the DCP Producer to the DCP Consumer.\n     * It is only sent to DCP replicas, not GSI, FTS etc. It serves to inform\n     * KV-Engine replicas of a committed Sync Write\n     *\n     * @param opaque\n     * @param vbucket the vbucket the event applies to\n     * @param key The key of the committed mutation.\n     * @param prepare_seqno The seqno of the prepare that we are committing.\n     * @param commit_seqno The sequence number to commit this mutation at.\n     * @return\n     */\n    virtual ENGINE_ERROR_CODE commit(uint32_t opaque,\n                                     Vbid vbucket,\n                                     const DocKey& key,\n                                     uint64_t prepare_seqno,\n                                     uint64_t commit_seqno) = 0;\n    /**\n     * Send an abort message:\n     *\n     * This is sent from the DCP Producer to the DCP Consumer.\n     */\n    virtual ENGINE_ERROR_CODE abort(uint32_t opaque,\n                                    Vbid vbucket,\n                                    const DocKey& key,\n                                    uint64_t prepared_seqno,\n                                    uint64_t abort_seqno) = 0;\n    /**\n     * Send an OSO snapshot marker to from server to client\n     */\n    virtual ENGINE_ERROR_CODE oso_snapshot(uint32_t opaque,\n                                           Vbid vbucket,\n                                           uint32_t flags,\n                                           cb::mcbp::DcpStreamId sid) = 0;\n\n    virtual ENGINE_ERROR_CODE seqno_advanced(uint32_t opaque,\n                                             Vbid vbucket,\n                                             uint64_t seqno,\n                                             cb::mcbp::DcpStreamId sid) = 0;\n};\n\nusing dcp_add_failover_log = std::function<ENGINE_ERROR_CODE(\n        const std::vector<vbucket_failover_t>&)>;\n\nstruct MEMCACHED_PUBLIC_CLASS DcpIface {\n    /**\n     * Called from the memcached core for a DCP connection to allow it to\n     * inject new messages on the stream.\n     *\n     * @param cookie a unique handle the engine should pass on to the\n     *               message producers\n     * @param producers functions the client may use to add messages to\n     *                  the DCP stream\n     *\n     * @return The appropriate error code returned from the message\n     *         producerif it failed, or:\n     *         ENGINE_SUCCESS if the engine don't have more messages\n     *                        to send at this moment\n     */\n    virtual ENGINE_ERROR_CODE step(gsl::not_null<const void*> cookie,\n                                   DcpMessageProducersIface& producers) = 0;\n\n    /**\n     * Called from the memcached core to open a new DCP connection.\n     *\n     * @param cookie a unique handle the engine should pass on to the\n     *               message producers (typically representing the memcached\n     *               connection).\n     * @param opaque what to use as the opaque for this DCP connection.\n     * @param seqno Unused\n     * @param flags bitfield of flags to specify what to open. See DCP_OPEN_XXX\n     * @param name Identifier for this connection. Note that the name must be\n     *             unique; attempting to (re)connect with a name already in use\n     *             will disconnect the existing connection.\n     * @param value An optional JSON value specifying extra information about\n     *              the connection to be opened.\n     * @return ENGINE_SUCCESS if the DCP connection was successfully opened,\n     *         otherwise error code indicating reason for the failure.\n     */\n    virtual ENGINE_ERROR_CODE open(gsl::not_null<const void*> cookie,\n                                   uint32_t opaque,\n                                   uint32_t seqno,\n                                   uint32_t flags,\n                                   std::string_view name,\n                                   std::string_view value = {}) = 0;\n\n    /**\n     * Called from the memcached core to add a vBucket stream to the set of\n     * connected streams.\n     *\n     * @param cookie a unique handle the engine should pass on to the\n     *               message producers (typically representing the memcached\n     *               connection).\n     * @param opaque what to use as the opaque for this DCP connection.\n     * @param vbucket The vBucket to stream.\n     * @param flags bitfield of flags to specify what to open. See\n     *              DCP_ADD_STREAM_FLAG_XXX\n     * @return ENGINE_SUCCESS if the DCP stream was successfully opened,\n     *         otherwise error code indicating reason for the failure.\n     */\n    virtual ENGINE_ERROR_CODE add_stream(gsl::not_null<const void*> cookie,\n                                         uint32_t opaque,\n                                         Vbid vbucket,\n                                         uint32_t flags) = 0;\n\n    /**\n     * Called from the memcached core to close a vBucket stream to the set of\n     * connected streams.\n     *\n     * @param cookie a unique handle the engine should pass on to the\n     *               message producers (typically representing the memcached\n     *               connection).\n     * @param opaque what to use as the opaque for this DCP connection.\n     * @param vbucket The vBucket to close.\n     * @param sid The id of the stream to close (can be 0/none)\n     * @return\n     */\n    virtual ENGINE_ERROR_CODE close_stream(gsl::not_null<const void*> cookie,\n                                           uint32_t opaque,\n                                           Vbid vbucket,\n                                           cb::mcbp::DcpStreamId sid) = 0;\n\n    /**\n     * Callback to the engine that a Stream Request message was received\n     */\n    virtual ENGINE_ERROR_CODE stream_req(\n            gsl::not_null<const void*> cookie,\n            uint32_t flags,\n            uint32_t opaque,\n            Vbid vbucket,\n            uint64_t start_seqno,\n            uint64_t end_seqno,\n            uint64_t vbucket_uuid,\n            uint64_t snap_start_seqno,\n            uint64_t snap_end_seqno,\n            uint64_t* rollback_seqno,\n            dcp_add_failover_log callback,\n            std::optional<std::string_view> json) = 0;\n\n    /**\n     * Callback to the engine that a get failover log message was received\n     */\n    virtual ENGINE_ERROR_CODE get_failover_log(\n            gsl::not_null<const void*> cookie,\n            uint32_t opaque,\n            Vbid vbucket,\n            dcp_add_failover_log callback) = 0;\n\n    /**\n     * Callback to the engine that a stream end message was received\n     */\n    virtual ENGINE_ERROR_CODE stream_end(\n            gsl::not_null<const void*> cookie,\n            uint32_t opaque,\n            Vbid vbucket,\n            cb::mcbp::DcpStreamEndStatus status) = 0;\n\n    /**\n     * Callback to the engine that a snapshot marker message was received\n     */\n    virtual ENGINE_ERROR_CODE snapshot_marker(\n            gsl::not_null<const void*> cookie,\n            uint32_t opaque,\n            Vbid vbucket,\n            uint64_t start_seqno,\n            uint64_t end_seqno,\n            uint32_t flags,\n            std::optional<uint64_t> high_completed_seqno,\n            std::optional<uint64_t> max_visible_seqno) = 0;\n\n    /**\n     * Callback to the engine that a mutation message was received\n     *\n     * @param cookie The cookie representing the connection\n     * @param opaque The opaque field in the message (identifying the stream)\n     * @param key The documents key\n     * @param value The value to store\n     * @param priv_bytes The number of bytes in the value which should be\n     *                   allocated from the privileged pool\n     * @param datatype The datatype for the incomming item\n     * @param cas The documents CAS value\n     * @param vbucket The vbucket identifier for the document\n     * @param flags The user specified flags\n     * @param by_seqno The sequence number in the vbucket\n     * @param rev_seqno The revision number for the item\n     * @param expiration When the document expire\n     * @param lock_time The lock time for the document\n     * @param meta The documents meta\n     * @param nru The engine's NRU value\n     * @return Standard engine error code.\n     */\n    virtual ENGINE_ERROR_CODE mutation(gsl::not_null<const void*> cookie,\n                                       uint32_t opaque,\n                                       const DocKey& key,\n                                       cb::const_byte_buffer value,\n                                       size_t priv_bytes,\n                                       uint8_t datatype,\n                                       uint64_t cas,\n                                       Vbid vbucket,\n                                       uint32_t flags,\n                                       uint64_t by_seqno,\n                                       uint64_t rev_seqno,\n                                       uint32_t expiration,\n                                       uint32_t lock_time,\n                                       cb::const_byte_buffer meta,\n                                       uint8_t nru) = 0;\n\n    /**\n     * Callback to the engine that a deletion message was received\n     *\n     * @param cookie The cookie representing the connection\n     * @param opaque The opaque field in the message (identifying the stream)\n     * @param key The documents key\n     * @param value The value to store\n     * @param priv_bytes The number of bytes in the value which should be\n     *                   allocated from the privileged pool\n     * @param datatype The datatype for the incomming item\n     * @param cas The documents CAS value\n     * @param vbucket The vbucket identifier for the document\n     * @param by_seqno The sequence number in the vbucket\n     * @param rev_seqno The revision number for the item\n     * @param meta The documents meta\n     * @return Standard engine error code.\n     */\n    virtual ENGINE_ERROR_CODE deletion(gsl::not_null<const void*> cookie,\n                                       uint32_t opaque,\n                                       const DocKey& key,\n                                       cb::const_byte_buffer value,\n                                       size_t priv_bytes,\n                                       uint8_t datatype,\n                                       uint64_t cas,\n                                       Vbid vbucket,\n                                       uint64_t by_seqno,\n                                       uint64_t rev_seqno,\n                                       cb::const_byte_buffer meta) = 0;\n\n    /**\n     * Callback to the engine that a deletion_v2 message was received\n     *\n     * @param cookie The cookie representing the connection\n     * @param opaque The opaque field in the message (identifying the stream)\n     * @param key The documents key\n     * @param value The value to store\n     * @param priv_bytes The number of bytes in the value which should be\n     *                   allocated from the privileged pool\n     * @param datatype The datatype for the incomming item\n     * @param cas The documents CAS value\n     * @param vbucket The vbucket identifier for the document\n     * @param by_seqno The sequence number in the vbucket\n     * @param rev_seqno The revision number for the item\n     * @param delete_time The time of the delete\n     * @return Standard engine error code.\n     */\n    virtual ENGINE_ERROR_CODE deletion_v2(gsl::not_null<const void*> cookie,\n                                          uint32_t opaque,\n                                          const DocKey& key,\n                                          cb::const_byte_buffer value,\n                                          size_t priv_bytes,\n                                          uint8_t datatype,\n                                          uint64_t cas,\n                                          Vbid vbucket,\n                                          uint64_t by_seqno,\n                                          uint64_t rev_seqno,\n                                          uint32_t delete_time) {\n        return ENGINE_ENOTSUP;\n    }\n\n    /**\n     * Callback to the engine that an expiration message was received\n     *\n     * @param cookie The cookie representing the connection\n     * @param opaque The opaque field in the message (identifying the stream)\n     * @param key The documents key\n     * @param value The value to store\n     * @param priv_bytes The number of bytes in the value which should be\n     *                   allocated from the privileged pool\n     * @param datatype The datatype for the incomming item\n     * @param cas The documents CAS value\n     * @param vbucket The vbucket identifier for the document\n     * @param by_seqno The sequence number in the vbucket\n     * @param rev_seqno The revision number for the item\n     * @param meta The documents meta\n     * @return Standard engine error code.\n     */\n    virtual ENGINE_ERROR_CODE expiration(gsl::not_null<const void*> cookie,\n                                         uint32_t opaque,\n                                         const DocKey& key,\n                                         cb::const_byte_buffer value,\n                                         size_t priv_bytes,\n                                         uint8_t datatype,\n                                         uint64_t cas,\n                                         Vbid vbucket,\n                                         uint64_t by_seqno,\n                                         uint64_t rev_seqno,\n                                         uint32_t deleteTime) = 0;\n\n    /**\n     * Callback to the engine that a set vbucket state message was received\n     */\n    virtual ENGINE_ERROR_CODE set_vbucket_state(\n            gsl::not_null<const void*> cookie,\n            uint32_t opaque,\n            Vbid vbucket,\n            vbucket_state_t state) = 0;\n\n    /**\n     * Callback to the engine that a NOOP message was received\n     */\n    virtual ENGINE_ERROR_CODE noop(gsl::not_null<const void*> cookie,\n                                   uint32_t opaque) = 0;\n\n    /**\n     * Callback to the engine that a buffer_ack message was received\n     */\n    virtual ENGINE_ERROR_CODE buffer_acknowledgement(\n            gsl::not_null<const void*> cookie,\n            uint32_t opaque,\n            Vbid vbucket,\n            uint32_t buffer_bytes) = 0;\n\n    /**\n     * Callback to the engine that a Control message was received.\n     *\n     * @param cookie The cookie representing the connection\n     * @param opaque The opaque field in the message (identifying the stream)\n     * @param key The control message name\n     * @param value The control message value\n     * @return Standard engine error code.\n     */\n    virtual ENGINE_ERROR_CODE control(gsl::not_null<const void*> cookie,\n                                      uint32_t opaque,\n                                      std::string_view key,\n                                      std::string_view value) = 0;\n\n    /**\n     * Callback to the engine that a response message has been received.\n     * @param cookie The cookie representing the connection\n     * @param response The response which the server received.\n     * @return Standard engine error code.\n     */\n    virtual ENGINE_ERROR_CODE response_handler(\n            gsl::not_null<const void*> cookie,\n            const cb::mcbp::Response& response) = 0;\n\n    /**\n     * Callback to the engine that a system event message was received.\n     *\n     * @param cookie The cookie representing the connection\n     * @param opaque The opaque field in the message (identifying the stream)\n     * @param vbucket The vbucket identifier for this event.\n     * @param event The type of system event.\n     * @param bySeqno Sequence number of event.\n     * @param version The version of system event (defines the eventData format)\n     * @param key The event name .\n     * @param eventData The event value.\n     * @return Standard engine error code.\n     */\n    virtual ENGINE_ERROR_CODE system_event(gsl::not_null<const void*> cookie,\n                                           uint32_t opaque,\n                                           Vbid vbucket,\n                                           mcbp::systemevent::id event,\n                                           uint64_t bySeqno,\n                                           mcbp::systemevent::version version,\n                                           cb::const_byte_buffer key,\n                                           cb::const_byte_buffer eventData) = 0;\n\n    /**\n     * Called by the core when it receives a DCP PREPARE message over the\n     * wire.\n     *\n     * See mutation for a description of the parameters except for:\n     *\n     * @param deleted Are we storing a deletion operation?\n     * @param durability the durability specification for this item\n     */\n    virtual ENGINE_ERROR_CODE prepare(gsl::not_null<const void*> cookie,\n                                      uint32_t opaque,\n                                      const DocKey& key,\n                                      cb::const_byte_buffer value,\n                                      size_t priv_bytes,\n                                      uint8_t datatype,\n                                      uint64_t cas,\n                                      Vbid vbucket,\n                                      uint32_t flags,\n                                      uint64_t by_seqno,\n                                      uint64_t rev_seqno,\n                                      uint32_t expiration,\n                                      uint32_t lock_time,\n                                      uint8_t nru,\n                                      DocumentState document_state,\n                                      cb::durability::Level level) = 0;\n\n    /**\n     * Called by the core when it receives a DCP SEQNO ACK message over the\n     * wire.\n     *\n     * It serves to inform KV-Engine active nodes that the replica has\n     * successfully received and prepared all DCP_PREPARE messages up to the\n     * specified seqno.\n     *\n     * @param cookie connection to send it over\n     * @param opaque identifying stream\n     * @param vbucket The vbucket which is being acknowledged.\n     * @param prepared_seqno The seqno the replica has prepared up to.\n     */\n    virtual ENGINE_ERROR_CODE seqno_acknowledged(\n            gsl::not_null<const void*> cookie,\n            uint32_t opaque,\n            Vbid vbucket,\n            uint64_t prepared_seqno) = 0;\n\n    /**\n     * Called by the core when it receives a DCP COMMIT message over the\n     * wire.\n     *\n     * This is sent from the DCP Producer to the DCP Consumer.\n     * It is only sent to DCP replicas, not GSI, FTS etc. It serves to inform\n     * KV-Engine replicas of a committed Sync Write\n     */\n    virtual ENGINE_ERROR_CODE commit(gsl::not_null<const void*> cookie,\n                                     uint32_t opaque,\n                                     Vbid vbucket,\n                                     const DocKey& key,\n                                     uint64_t prepared_seqno,\n                                     uint64_t commit_seqno) = 0;\n    /**\n     * Called by the core when it receives a DCP ABORT message over the\n     * wire.\n     *\n     * This is sent from the DCP Producer to the DCP Consumer.\n     */\n    virtual ENGINE_ERROR_CODE abort(gsl::not_null<const void*> cookie,\n                                    uint32_t opaque,\n                                    Vbid vbucket,\n                                    const DocKey& key,\n                                    uint64_t prepared_seqno,\n                                    uint64_t abort_seqno) = 0;\n};\n", "meta": {"hexsha": "9cc4fe91e506c31b1981ceba4b06b414fb9e7e34", "size": 33212, "ext": "h", "lang": "C", "max_stars_repo_path": "include/memcached/dcp.h", "max_stars_repo_name": "rohansuri/kv_engine", "max_stars_repo_head_hexsha": "6d377448a787ce5dc268c95def2850e36f5f1328", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/memcached/dcp.h", "max_issues_repo_name": "rohansuri/kv_engine", "max_issues_repo_head_hexsha": "6d377448a787ce5dc268c95def2850e36f5f1328", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/memcached/dcp.h", "max_forks_repo_name": "rohansuri/kv_engine", "max_forks_repo_head_hexsha": "6d377448a787ce5dc268c95def2850e36f5f1328", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.0765239948, "max_line_length": 80, "alphanum_fraction": 0.5338732988, "num_tokens": 6571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.054198729823185576, "lm_q2_score": 0.015906394248446885, "lm_q1q2_score": 0.0008621063643326457}}
{"text": "#ifndef FUNCTION_ANY_FUNCTION_H\n#define FUNCTION_ANY_FUNCTION_H\n\n#include \"wasm_base.h\"\n#include \"wasm_value.h\"\n#include \"function/CFunction.h\"\n#include <gsl/gsl>\n\n\nnamespace wasm {\n\nstruct AnyFunction:\n\tprivate std::variant<\n\t\tstd::monostate,\n\t\tgsl::not_null<WasmFunction* const*>,\n\t\tCFunction\n\t>\n{\n\tusing null_function_alt = std::monostate;\n\tusing wasm_function_alt = gsl::not_null<WasmFunction* const*>;\n\tusing c_function_alt = CFunction;\n\tusing variant_type = std::variant<\n\t\tnull_function_alt,\n\t\twasm_function_alt,\n\t\tc_function_alt\n\t>;\n\n\tusing variant_type::variant_type;\n\n\tAnyFunction() = default;\n\n\tAnyFunction(const AnyFunction&) = default;\n\tAnyFunction(AnyFunction&&) = default;\n\n\tAnyFunction& operator=(const AnyFunction&) = default;\n\tAnyFunction& operator=(AnyFunction&&) = default;\n\n\tvoid emplace_wasm_function(gsl::not_null<wasm_function_alt> func)\n\t{ as_variant.emplace<wasm_function_alt>(func); }\n\n\tvoid emplace_c_function(CFunction cfunc)\n\t{ as_variant().emplace<c_function_alt>(std::move(cfunc)); }\n\n\tvoid emplace_null_function()\n\t{ as_variant().emplace<null_function_type>(std::monostate{}); }\n\n\tbool is_wasm_function() const\n\t{ return std::holds_alternative<wasm_function_alt>(as_variant()); }\n\n\tbool is_c_function() const\n\t{ return std::holds_alternative<c_function_alt>(as_variant()); }\n\n\tbool is_null() const\n\t{ return std::holds_alternative<std::monostate>(as_variant()); }\n\n\tconst WasmFunction* get_wasm_function() const\n\t{\n\t\tauto f = std::get<wasm_function_alt>(as_variant());\n\t\treturn *f;\n\t}\n\n\tWasmFunction* get_wasm_function() \n\t{ return const_cast<WasmFunction*>(get_wasm_function()); }\n\n\tc_function_type get_c_function() const\n\t{ return std::get<c_function_alt>(as_variant()); }\n\nprivate:\n\tvariant_type& as_variant()\n\t{ return static_cast<variant_type&>(*this); }\n\n\tconst variant_type& as_variant() const\n\t{ return static_cast<const variant_type&>(*this); }\n\n};\n\n\n} /* namespace wasm */\n\n#endif /* FUNCTION_ANY_FUNCTION_H */\n", "meta": {"hexsha": "c50266ae00178945597876d2f1228da3d9bde4f4", "size": 1954, "ext": "h", "lang": "C", "max_stars_repo_path": "include/function/AnyFunction.h", "max_stars_repo_name": "tvanslyke/wasm-cpp", "max_stars_repo_head_hexsha": "8a56c1706e2723ece36e3642bae9e36792dbd7b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/function/AnyFunction.h", "max_issues_repo_name": "tvanslyke/wasm-cpp", "max_issues_repo_head_hexsha": "8a56c1706e2723ece36e3642bae9e36792dbd7b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/function/AnyFunction.h", "max_forks_repo_name": "tvanslyke/wasm-cpp", "max_forks_repo_head_hexsha": "8a56c1706e2723ece36e3642bae9e36792dbd7b2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1234567901, "max_line_length": 68, "alphanum_fraction": 0.7492323439, "num_tokens": 497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.05665242849342066, "lm_q2_score": 0.015189048139293986, "lm_q1q2_score": 0.0008604964635944767}}
{"text": "#pragma once\n\n#include <gsl/gsl>\n#include \"halley/utils/utils.h\"\n#include \"halley/data_structures/vector.h\"\n#include \"halley/file/path.h\"\n#include \"halley/data_structures/maybe.h\"\n\nnamespace Halley {\n\tclass String;\n\tclass Path;\n\n\tclass FileSystem\n\t{\n\tpublic:\n\t\tstatic bool exists(const Path& p);\n\t\tstatic bool createDir(const Path& p);\n\t\tstatic bool createParentDir(const Path& p);\n\n\t\tstatic int64_t getLastWriteTime(const Path& p);\n\t\tstatic bool isFile(const Path& p);\n\t\tstatic bool isDirectory(const Path& p);\n\n\t\tstatic void copyFile(const Path& src, const Path& dst);\n\t\tstatic bool remove(const Path& path);\n\n\t\tstatic void writeFile(const Path& path, gsl::span<const gsl::byte> data);\n\t\tstatic void writeFile(const Path& path, const Bytes& data);\n\t\tstatic void writeFile(const Path& path, const String& data);\n\t\tstatic Bytes readFile(const Path& path);\n\n\t\tstatic Vector<Path> enumerateDirectory(const Path& path);\n\t\t\n\t\tstatic Path getRelative(const Path& path, const Path& parentPath);\n\t\tstatic Path getAbsolute(const Path& path);\n\n\t\tstatic size_t fileSize(const Path& path);\n\n\t\tstatic Path getTemporaryPath();\n\n\t\tstatic int runCommand(const String& command);\n\t};\n\n\tclass ScopedTemporaryFile final {\n\tpublic:\n\t\tScopedTemporaryFile();\n\t\tScopedTemporaryFile(const String& extension);\n\t\t~ScopedTemporaryFile();\n\n\t\tScopedTemporaryFile(const ScopedTemporaryFile& other) = delete;\n\t\tScopedTemporaryFile(ScopedTemporaryFile&& other) noexcept;\n\t\tScopedTemporaryFile& operator=(const ScopedTemporaryFile& other) = delete;\n\t\tScopedTemporaryFile& operator=(ScopedTemporaryFile&& other) noexcept;\n\n\t\tconst Path& getPath() const;\n\n\tprivate:\n\t\tstd::optional<Path> path;\n\t};\n}\n\n", "meta": {"hexsha": "f9d8dc6c2dee2aa3f762ac3a8a1ac440940b53db", "size": 1666, "ext": "h", "lang": "C", "max_stars_repo_path": "src/tools/tools/include/halley/tools/file/filesystem.h", "max_stars_repo_name": "amrezzd/halley", "max_stars_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tools/tools/include/halley/tools/file/filesystem.h", "max_issues_repo_name": "amrezzd/halley", "max_issues_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tools/tools/include/halley/tools/file/filesystem.h", "max_forks_repo_name": "amrezzd/halley", "max_forks_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8709677419, "max_line_length": 76, "alphanum_fraction": 0.7478991597, "num_tokens": 390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.04401865237117, "lm_q2_score": 0.01941934708291179, "lm_q1q2_score": 0.0008548134885177882}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef error_e0b666c0_4caa_4710_bb62_0f8a9d0e579e_h\r\n#define error_e0b666c0_4caa_4710_bb62_0f8a9d0e579e_h\r\n\r\n#include <gslib/type.h>\r\n\r\n__gslib_begin__\r\n\r\nstruct errinfo\r\n{\r\n    gchar*      desc;\r\n    gchar*      file;\r\n    int         line;\r\n    void*       user;\r\n};\r\n\r\ntypedef void* (*error_dump)(void*);\r\ngs_export extern void* error_dump_callstack(void*);\r\n\r\ngs_export extern void _set_error(const gchar* desc, error_dump dump, void* user, const gchar* file, int line);\r\ngs_export extern void _set_last_error(const gchar* desc, error_dump dump, void* user, const gchar* file, int line);\r\ngs_export extern void pop_error();\r\ngs_export extern errinfo* get_last_error();\r\ngs_export extern void reset_error();\r\n\r\n#ifndef swsc_char\r\n#define swsc_char(x) _t(x)\r\n#endif\r\n\r\n#ifdef set_error\r\n#undef set_error\r\n#endif\r\n#define set_error(desc, ...) do { \\\r\n    assert(!desc); \\\r\n    string str; \\\r\n    str.format(desc, __VA_ARGS__); \\\r\n    _set_error(str.c_str(), 0, 0, swsc_char(__FILE__), __LINE__); \\\r\n} while(0)\r\n\r\n#ifdef set_last_error\r\n#undef set_last_error\r\n#endif\r\n#define set_last_error(desc, ...) do { \\\r\n    assert(!desc); \\\r\n    string str; \\\r\n    str.format(desc, _VA_ARGS__); \\\r\n    _set_last_error(str.c_str(), 0, 0, swsc_char(__FILE__), __LINE__); \\\r\n} while(0)\r\n\r\n//gs_export extern void dumperr_file(void);\r\ngs_export extern void trace_hold(const gchar* fmt, ...);\r\ngs_export extern void _trace_to_clipboard();\r\n\r\n#ifdef _GS_TRACE_TO_CLIPBOARD\r\n#define trace(fmt, ...) do { trace_hold(fmt, __VA_ARGS__); } while(0)\r\n#define trace_to_clipboard _trace_to_clipboard\r\n#elif defined (DEBUG) || defined (_DEBUG)\r\ngs_export extern void trace(const gchar* fmt, ...);\r\ngs_export extern void trace_all(const gchar* str);\r\n#define trace_to_clipboard __noop\r\n#else\r\n#define trace(fmt, ...) __noop\r\n#define trace_all __noop;\r\n#define trace_to_clipboard __noop\r\n#endif\r\n\r\n/* beep an alarm */\r\ngs_export extern void sound_alarm();\r\n\r\n__gslib_end__\r\n\r\n#endif\r\n\r\n", "meta": {"hexsha": "03d84723c2b05fb8bbe367e49d5609d8785e3312", "size": 3224, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gslib/error.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/gslib/error.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gslib/error.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 32.24, "max_line_length": 116, "alphanum_fraction": 0.7174317618, "num_tokens": 791, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.027169233111095294, "lm_q2_score": 0.031143833457347815, "lm_q1q2_score": 0.0008461540711758117}}
{"text": "#include <gmock/gmock.h>\n#include <gtest/gtest.h>\n\n#include \"boost_coroutine/http_client.h\"\n#include \"callback/http_client.h\"\n#include \"coroutine_ts/http_client.h\"\n#include \"sync/http_client.h\"\n#include \"task/http_client.h\"\n#include \"threaded/http_client.h\"\n\n#include \"executor.h\"\n\n#include <boost/algorithm/string.hpp>\n\n#include <gsl/gsl_util>\n\n#if 1\nstatic inline auto log_msg = std::stringstream{};\n#else\nstatic inline auto& log_msg = std::cerr;\n#endif\n\nstatic HttpResponse request_get_impl(std::string_view uri) {\n  if (uri == \"/file1\") {\n    return Redirect{\"/newplaceoffile1\"};\n  }\n  if (uri == \"/newplaceoffile1\") {\n    return Redirect{\"/file2\"};\n  }\n  if (uri == \"/file2\") {\n    return Content{\"content1\"};\n  }\n  if (uri == \"/file3\") {\n    return Content{\"content2\"};\n  }\n  if (boost::algorithm::starts_with(uri, \"/extremeredirect\")) {\n    std::vector<std::string> parts;\n    boost::algorithm::split(parts, uri, [](char c) { return c == '/'; });\n    if (parts.size() == 2) {\n      return Redirect{std::string{uri} + \"/1\"};\n    }\n    if (parts.size() == 3) {\n      auto num = std::stol(parts[2]);\n      if (num < 4) {\n        return Redirect{\"/extremeredirect/\" + std::to_string(num + 1)};\n      }\n    }\n    return Content{\"finally here\"};\n  }\n  return Content{\"\"};\n}\n\nnamespace synchronous {\nclass ConcreteHttpClient : public HttpClient {\npublic:\n  HttpResponse request_get(std::string_view uri) override {\n    log_msg << \"request \" << uri << \"...\" << std::endl;\n    auto out\n      = gsl::finally([&] { log_msg << \"...request \" << uri << std::endl; });\n    return request_get_impl(uri);\n  }\n};\n}\n\nnamespace threaded {\nclass ConcreteHttpClient : public HttpClient {\npublic:\n  HttpResponse request_get(std::string_view uri) override {\n    log_msg << \"request \" << uri << \"...\" << std::endl;\n    auto out\n      = gsl::finally([&] { log_msg << \"...request \" << uri << std::endl; });\n    return request_get_impl(uri);\n  }\n};\n}\n\nnamespace callback {\n\nclass ConcreteHttpClient : public HttpClient {\npublic:\n  void request_get(const std::string&                       uri,\n                   const std::function<void(HttpResponse)>& cb) override {\n    log_msg << \"request \" << uri << \"...\" << std::endl;\n    auto handle = [uri]() -> HttpResponse { return request_get_impl(uri); };\n    get_current_executor().add_work([=] {\n      log_msg << \"...request \" << uri << std::endl;\n      get_current_executor().add_work([=] { cb(handle()); });\n    });\n  }\n};\n}\n\nnamespace task_based {\n\nclass ConcreteHttpClient : public HttpClient {\npublic:\n  task<HttpResponse> request_get(const std::string& uri) override {\n    log_msg << \"request \" << uri << \"...\" << std::endl;\n    const auto handle\n      = [uri]() -> HttpResponse { return request_get_impl(uri); };\n\n    auto fut = make_task<HttpResponse>();\n    get_current_executor().add_work([=] {\n      log_msg << \"...request \" << uri << std::endl;\n\n      fut->set_result(handle());\n    });\n    return fut;\n  }\n};\n}\n\nnamespace boost_coroutine {\n\nclass ConcreteHttpClient : public HttpClient {\npublic:\n  task<HttpResponse> request_get(const std::string& uri) override {\n    log_msg << \"request \" << uri << \"...\" << std::endl;\n    const auto handle = [=]() -> HttpResponse { return request_get_impl(uri); };\n\n    auto fut = make_task<HttpResponse>();\n    get_current_executor().add_work([=] {\n      log_msg << \"...request \" << uri << std::endl;\n      fut->set_result(handle());\n    });\n    return fut;\n  }\n};\n}\n\nnamespace coroutines_ts {\n\nclass ConcreteHttpClient : public HttpClient {\npublic:\n  task<HttpResponse> request_get(const std::string& uri) override {\n    log_msg << \"request \" << uri << \"...\" << std::endl;\n    const auto handle = [=]() -> HttpResponse { return request_get_impl(uri); };\n\n    auto fut = make_task<HttpResponse>();\n    get_current_executor().add_work([=] {\n      log_msg << \"...request \" << uri << std::endl;\n      fut->set_result(handle());\n    });\n    return fut;\n  }\n};\n}\n", "meta": {"hexsha": "48da7f6a63e3ad0a37ad60ebe6395e6996ecc2fc", "size": 3935, "ext": "h", "lang": "C", "max_stars_repo_path": "mixed/src/http_client_implementations.h", "max_stars_repo_name": "adrianimboden/cppusergroup-adynchronous-programming", "max_stars_repo_head_hexsha": "d6fad3ff980be2e7c13ed9e3e05b62e984c9caa4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mixed/src/http_client_implementations.h", "max_issues_repo_name": "adrianimboden/cppusergroup-adynchronous-programming", "max_issues_repo_head_hexsha": "d6fad3ff980be2e7c13ed9e3e05b62e984c9caa4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mixed/src/http_client_implementations.h", "max_forks_repo_name": "adrianimboden/cppusergroup-adynchronous-programming", "max_forks_repo_head_hexsha": "d6fad3ff980be2e7c13ed9e3e05b62e984c9caa4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5878378378, "max_line_length": 80, "alphanum_fraction": 0.6134688691, "num_tokens": 978, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.03904829384451455, "lm_q2_score": 0.021615334850393266, "lm_q1q2_score": 0.0008440419467857323}}
{"text": "#pragma once\n\n#include \"macros.h\"\n\n#include <gsl/span>\n\n#include <array>\n#include <optional>\n#include <string>\n\nnamespace linkollector::win {\n\nenum class activity { url, text };\n\nconstexpr std::string_view activity_delimiter = \"\\uedfd\";\n\nconstexpr std::array<std::byte, activity_delimiter.size()>\n    activity_delimiter_bin = []() {\n        std::array<std::byte, activity_delimiter.size()> delim = {};\n        for (std::size_t i = 0; i < activity_delimiter.size(); ++i) {\n            delim.at(i) = static_cast<std::byte>(activity_delimiter[i]);\n        }\n        return delim;\n    }();\n\n[[nodiscard]] std::string activity_to_string(activity activity_) noexcept;\n\n[[nodiscard]] std::wstring activity_to_wstring(activity activity_) noexcept;\n\n[[nodiscard]] std::optional<activity>\nactivity_from_string(std::string_view activity_) noexcept;\n\nstd::optional<std::pair<activity, std::string>>\ndeserialize(gsl::span<std::byte> msg) noexcept;\n\n} // namespace linkollector::win\n", "meta": {"hexsha": "53a1886c6904543f86f7c97e01a7451d81f2d18c", "size": 969, "ext": "h", "lang": "C", "max_stars_repo_path": "src/activity.h", "max_stars_repo_name": "Longhanks/linkollector-win", "max_stars_repo_head_hexsha": "a76b08fa4f20a3612988a0d84e5b14f7822638ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/activity.h", "max_issues_repo_name": "Longhanks/linkollector-win", "max_issues_repo_head_hexsha": "a76b08fa4f20a3612988a0d84e5b14f7822638ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/activity.h", "max_forks_repo_name": "Longhanks/linkollector-win", "max_forks_repo_head_hexsha": "a76b08fa4f20a3612988a0d84e5b14f7822638ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1891891892, "max_line_length": 76, "alphanum_fraction": 0.6955624355, "num_tokens": 225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.05108273984628585, "lm_q2_score": 0.016403032335851858, "lm_q1q2_score": 0.000837911833502535}}
{"text": "/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */\n/*\n *     Copyright 2018-Present Couchbase, Inc.\n *\n *   Use of this software is governed by the Business Source License included\n *   in the file licenses/BSL-Couchbase.txt.  As of the Change Date specified\n *   in that file, in accordance with the Business Source License, use of this\n *   software will be governed by the Apache License, Version 2.0, included in\n *   the file licenses/APL2.txt.\n */\n#pragma once\n\n#include <gsl/gsl-lite.hpp>\n#include <nlohmann/json.hpp>\n#include <platform/dirutils.h>\n#include <vector>\n\nclass Event;\n\n/**\n * The Module class represents the configuration for a single module.\n * See ../README.md for more information.\n */\nclass Module {\npublic:\n    Module() = delete;\n    Module(const nlohmann::json& json,\n           const std::string& srcRoot,\n           const std::string& objRoot);\n\n    void createHeaderFile();\n\n    /**\n     * The name of the module\n     */\n    std::string name;\n    /**\n     * The lowest identifier for the audit events in this module. All\n     * audit descriptor defined for this module MUST be within the range\n     * [start, start + max_events_per_module]\n     */\n    int64_t start;\n    /**\n     * The name of the file containing the audit descriptors for this\n     * module.\n     */\n    std::string file;\n    /**\n     * The JSON data describing the audit descriptors for this module\n     */\n    nlohmann::json json;\n    /**\n     * Is this module enterprise only?\n     */\n    bool enterprise = false;\n\n    /**\n     * If present this is the name of a C headerfile to generate with\n     * #defines for all audit identifiers for the module.\n     */\n    std::string header;\n\n    /**\n     * A list of all of the events defined for this module\n     */\n    std::vector<std::unique_ptr<Event>> events;\n\nprotected:\n    /**\n     * Add the event to the list of events for the module\n     *\n     * @param event the event to add\n     * @throws std::invalid_argument if the event is outside the legal range\n     *                               for the module\n     */\n    void addEvent(std::unique_ptr<Event> event);\n\n    /// Parse the event descriptor file and add all of the events into\n    /// the list of events\n    void parseEventDescriptorFile();\n};\n", "meta": {"hexsha": "5880af3ba5dcfb112bdbd9bd2b84560edb0f7740", "size": 2283, "ext": "h", "lang": "C", "max_stars_repo_path": "auditd/generator/generator_module.h", "max_stars_repo_name": "BenHuddleston/kv_engine", "max_stars_repo_head_hexsha": "78123c9aa2c2feb24b7c31eecc862bf2ed6325e4", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": 104.0, "max_stars_repo_stars_event_min_datetime": "2017-05-22T20:41:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T00:18:34.000Z", "max_issues_repo_path": "auditd/generator/generator_module.h", "max_issues_repo_name": "BenHuddleston/kv_engine", "max_issues_repo_head_hexsha": "78123c9aa2c2feb24b7c31eecc862bf2ed6325e4", "max_issues_repo_licenses": ["MIT", "BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-11-14T08:12:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T11:14:17.000Z", "max_forks_repo_path": "auditd/generator/generator_module.h", "max_forks_repo_name": "BenHuddleston/kv_engine", "max_forks_repo_head_hexsha": "78123c9aa2c2feb24b7c31eecc862bf2ed6325e4", "max_forks_repo_licenses": ["MIT", "BSD-3-Clause"], "max_forks_count": 71.0, "max_forks_repo_forks_event_min_datetime": "2017-05-22T20:41:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T10:34:32.000Z", "avg_line_length": 27.8414634146, "max_line_length": 79, "alphanum_fraction": 0.6360052562, "num_tokens": 537, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.04401864923589049, "lm_q2_score": 0.018833128031820533, "lm_q1q2_score": 0.0008290088568473246}}
{"text": "/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */\n/*\n *     Copyright 2018 Couchbase, Inc.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n */\n#pragma once\n\n#include <gsl/gsl-lite.hpp>\n#include <nlohmann/json.hpp>\n#include <platform/dirutils.h>\n#include <vector>\n\nclass Event;\n\n/**\n * The Module class represents the configuration for a single module.\n * See ../README.md for more information.\n */\nclass Module {\npublic:\n    Module() = delete;\n    Module(const nlohmann::json& json,\n           const std::string& srcRoot,\n           const std::string& objRoot);\n\n    void createHeaderFile();\n\n    /**\n     * The name of the module\n     */\n    std::string name;\n    /**\n     * The lowest identifier for the audit events in this module. All\n     * audit descriptor defined for this module MUST be within the range\n     * [start, start + max_events_per_module]\n     */\n    int64_t start;\n    /**\n     * The name of the file containing the audit descriptors for this\n     * module.\n     */\n    std::string file;\n    /**\n     * The JSON data describing the audit descriptors for this module\n     */\n    nlohmann::json json;\n    /**\n     * Is this module enterprise only?\n     */\n    bool enterprise = false;\n\n    /**\n     * If present this is the name of a C headerfile to generate with\n     * #defines for all audit identifiers for the module.\n     */\n    std::string header;\n\n    /**\n     * A list of all of the events defined for this module\n     */\n    std::vector<std::unique_ptr<Event>> events;\n\nprotected:\n    /**\n     * Add the event to the list of events for the module\n     *\n     * @param event the event to add\n     * @throws std::invalid_argument if the event is outside the legal range\n     *                               for the module\n     */\n    void addEvent(std::unique_ptr<Event> event);\n\n    /// Parse the event descriptor file and add all of the events into\n    /// the list of events\n    void parseEventDescriptorFile();\n};\n", "meta": {"hexsha": "a0c93137cea69e2c8b1d706fa3fe7cbb462c286c", "size": 2501, "ext": "h", "lang": "C", "max_stars_repo_path": "auditd/generator/generator_module.h", "max_stars_repo_name": "rohansuri/kv_engine", "max_stars_repo_head_hexsha": "6d377448a787ce5dc268c95def2850e36f5f1328", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "auditd/generator/generator_module.h", "max_issues_repo_name": "rohansuri/kv_engine", "max_issues_repo_head_hexsha": "6d377448a787ce5dc268c95def2850e36f5f1328", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "auditd/generator/generator_module.h", "max_forks_repo_name": "rohansuri/kv_engine", "max_forks_repo_head_hexsha": "6d377448a787ce5dc268c95def2850e36f5f1328", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4204545455, "max_line_length": 79, "alphanum_fraction": 0.6405437825, "num_tokens": 577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.04535258055430642, "lm_q2_score": 0.018264278585646665, "lm_q1q2_score": 0.000828332165821834}}
{"text": "/*\n * This module must not depend on any other as it is needed during the startup\n * of pygsl.\n */\n#include <Python.h>\n#include <gsl/gsl_errno.h>\n#include <pygsl/errorno.h>\n\nstatic int \nadd_errno(PyObject * dict, int num, char * name)\n{\n     PyObject * item;\n\n     item = PyInt_FromLong(num);\n     if(item == NULL){\n\t  fprintf(stderr, \"Failed to generate PyInt with value %d for errno %s\\n\",\n\t\t  num, name);\n\t  return -1;\n     }\n     if(PyDict_SetItemString(dict, name, item) == -1){\n\t  fprintf(stderr, \"Failed to add PyInt %p with value %d to dict %p for errno %s\\n\",\n\t\t  (void *) item, num, (void *) dict, name);\n\t  return -1;\n     }\n     return 0;\n}   \n#define ADD_ERRNO(ERRNO, ERRNOSTR) if(add_errno(dict, ERRNO, ERRNOSTR) != 0) goto fail\n\nstatic PyMethodDef errornoMethods[] = {\n     {NULL, NULL, 0, NULL}\n};\n\nDL_EXPORT(void) initerrno(void)\n{\n     PyObject *dict=NULL, *m=NULL;\n     \n     m = Py_InitModule(\"errno\", errornoMethods);\n     assert(m);\n\n     dict = PyModule_GetDict(m);\n     if(!dict)\n\t  goto fail;\n\n     ADD_ERRNO(GSL_SUCCESS , \"GSL_SUCCESS\" );\n     ADD_ERRNO(GSL_FAILURE , \"GSL_FAILURE\" );\n     ADD_ERRNO(GSL_CONTINUE, \"GSL_CONTINUE\");\n     ADD_ERRNO(GSL_EDOM    , \"GSL_EDOM\"    );\n     ADD_ERRNO(GSL_ERANGE  , \"GSL_ERANGE\"  );\n     ADD_ERRNO(GSL_EFAULT  , \"GSL_EFAULT\"  );\n     ADD_ERRNO(GSL_EINVAL  , \"GSL_EINVAL\"  );\n     ADD_ERRNO(GSL_EFAILED , \"GSL_EFAILED\" );\n     ADD_ERRNO(GSL_EFACTOR , \"GSL_EFACTOR\" );\n     ADD_ERRNO(GSL_ESANITY , \"GSL_ESANITY\" );\n     ADD_ERRNO(GSL_ENOMEM  , \"GSL_ENOMEM\"  );\n     ADD_ERRNO(GSL_EBADFUNC, \"GSL_EBADFUNC\");\n     ADD_ERRNO(GSL_ERUNAWAY, \"GSL_ERUNAWAY\");\n     ADD_ERRNO(GSL_EMAXITER, \"GSL_EMAXITER\");\n     ADD_ERRNO(GSL_EZERODIV, \"GSL_EZERODIV\");\n     ADD_ERRNO(GSL_EBADTOL , \"GSL_EBADTOL\" );\n     ADD_ERRNO(GSL_ETOL    , \"GSL_ETOL\"    );\n     ADD_ERRNO(GSL_EUNDRFLW, \"GSL_EUNDRFLW\");\n     ADD_ERRNO(GSL_EOVRFLW , \"GSL_EOVRFLW\" );\n     ADD_ERRNO(GSL_ELOSS   , \"GSL_ELOSS\"   );\n     ADD_ERRNO(GSL_EROUND  , \"GSL_EROUND\"  );\n     ADD_ERRNO(GSL_EBADLEN , \"GSL_EBADLEN\" );\n     ADD_ERRNO(GSL_ENOTSQR , \"GSL_ENOTSQR\" );\n     ADD_ERRNO(GSL_ESING   , \"GSL_ESING\"   );\n     ADD_ERRNO(GSL_EDIVERGE, \"GSL_EDIVERGE\");\n     ADD_ERRNO(GSL_EUNSUP  , \"GSL_EUNSUP\"  );\n     ADD_ERRNO(GSL_EUNIMPL , \"GSL_EUNIMPL\" );\n     ADD_ERRNO(GSL_ECACHE  , \"GSL_ECACHE\"  );\n     ADD_ERRNO(GSL_ETABLE  , \"GSL_ETABLE\"  );\n     ADD_ERRNO(GSL_ENOPROG , \"GSL_ENOPROG\" );\n     ADD_ERRNO(GSL_ENOPROGJ, \"GSL_ENOPROGJ\");\n     ADD_ERRNO(GSL_ETOLF   , \"GSL_ETOLF\"   );\n     ADD_ERRNO(GSL_ETOLX   , \"GSL_ETOLX\"   );\n     ADD_ERRNO(GSL_ETOLG   , \"GSL_ETOLG\"   );\n     ADD_ERRNO(GSL_EOF     , \"GSL_EOF\"     );\n     ADD_ERRNO(PyGSL_ESTRIDE, \"PyGSL_ESTRIDE\");\n     \n\n\n     return;\n fail:\n     fprintf(stderr, \"Initialisation of module errorno failed!\\n\");\n     return;\n}\n", "meta": {"hexsha": "c036a639b1e7384fe2a755d2206ec8b0127d4999", "size": 2788, "ext": "c", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/src/init/errorno.c", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/src/init/errorno.c", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/src/init/errorno.c", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 31.6818181818, "max_line_length": 86, "alphanum_fraction": 0.6391678623, "num_tokens": 979, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.05921025738176787, "lm_q2_score": 0.013848612937411697, "lm_q1q2_score": 0.0008199799364046269}}
{"text": "#pragma once\n#include <autograph/Core/Types.h>\n#include <gsl/span>\n#include <gsl/string_span>\n\nnamespace ag \n{\n\t// until a standard solution appears\n\tusing gsl::span;\n\tusing gsl::string_span;\n}", "meta": {"hexsha": "2db8ff63df5157164debaeeddddc243a293d4a92", "size": 193, "ext": "h", "lang": "C", "max_stars_repo_path": "include/autograph/Core/Support/Span.h", "max_stars_repo_name": "ennis/autograph-pipelines", "max_stars_repo_head_hexsha": "afc66ef60bf99fca26d200bd7739528e1bf3ed8c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-24T12:29:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-24T12:29:42.000Z", "max_issues_repo_path": "include/autograph/Core/Support/Span.h", "max_issues_repo_name": "ennis/autograph-pipelines", "max_issues_repo_head_hexsha": "afc66ef60bf99fca26d200bd7739528e1bf3ed8c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/autograph/Core/Support/Span.h", "max_forks_repo_name": "ennis/autograph-pipelines", "max_forks_repo_head_hexsha": "afc66ef60bf99fca26d200bd7739528e1bf3ed8c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.5454545455, "max_line_length": 37, "alphanum_fraction": 0.7357512953, "num_tokens": 49, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.04146227271140963, "lm_q2_score": 0.019719127423242864, "lm_q1q2_score": 0.0008175998388535318}}
{"text": "#ifndef THREADEDNESS_INCLUDE\n#define THREADEDNESS_INCLUDE\n\n#include <string>\n\n#include <gsl/string_span>\n\n#include \"config/commandLineOptions.h\"\n#include \"config/fleetingOptionsInterface.h\"\n#include \"config/variablesMap.h\"\n#include \"core/task.h\"\n\nnamespace execHelper::plugins {\nusing Jobs = config::Jobs_t;\n\nconst gsl::czstring<> JOBS_KEY = \"jobs\";\n\n/**\n * \\brief Extends the functionality to include the _jobs_ config parameter and processes this parameter, using the --jobs flag\n */\nstruct JobsLong {\n    /**\n     * Adds the variables for this functionality to the given variables map\n     *\n     * @param[in] options       The fleeting options to take into account\n     * @param[out] variables    The variables map to add the variables to\n     */\n    static void\n    getVariables(config::VariablesMap& variables,\n                 const config::FleetingOptionsInterface& options) noexcept;\n\n    /**\n     * Applies the given variables to the task\n     *\n     * @param[in] variables The variables map to use\n     * @param[out] task The task with the given variables map applied to it\n     */\n    inline static void apply(core::Task& task,\n                             const config::VariablesMap& variables) noexcept {\n        task.append(\n            {\"--jobs\", std::to_string(*(variables.get<Jobs>(JOBS_KEY)))});\n    }\n};\n\n/**\n * \\brief Extends the functionality to include the _jobs_ config parameter and processes this parameter, using the -j flag\n */\nstruct JobsShort {\n    /*! @copydoc JobsLong::getVariables(config::VariablesMap&, const config::FleetingOptionsInterface&)\n     */\n    inline static void\n    getVariables(config::VariablesMap& variables,\n                 const config::FleetingOptionsInterface& options) noexcept {\n        JobsLong::getVariables(variables, options);\n    }\n\n    /*! @copydoc JobsLong::apply(core::Task&, const config::VariablesMap&)\n     */\n    inline static void apply(core::Task& task,\n                             const config::VariablesMap& variables) noexcept {\n        task.append({\"-j\", std::to_string(*(variables.get<Jobs>(JOBS_KEY)))});\n    }\n};\n\n} // namespace execHelper::plugins\n\n#endif /* THREADEDNESS_INCLUDE */\n", "meta": {"hexsha": "959118c6e9a9d8f16d62220a1f0978b7008958bb", "size": 2164, "ext": "h", "lang": "C", "max_stars_repo_path": "src/plugins/include/plugins/threadedness.h", "max_stars_repo_name": "exec-helper/source", "max_stars_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-28T13:24:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-28T13:24:30.000Z", "max_issues_repo_path": "src/plugins/include/plugins/threadedness.h", "max_issues_repo_name": "exec-helper/source", "max_issues_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/plugins/include/plugins/threadedness.h", "max_forks_repo_name": "exec-helper/source", "max_forks_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-07-03T11:11:19.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-03T11:11:19.000Z", "avg_line_length": 31.8235294118, "max_line_length": 126, "alphanum_fraction": 0.6695933457, "num_tokens": 477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.03210070393911136, "lm_q2_score": 0.025178840831952678, "lm_q1q2_score": 0.0008082585150765212}}
{"text": "#pragma once\n\n#include <gsl/gsl>\n\n#include <boost/noncopyable.hpp>\n\nnamespace hash_calculator\n{\n\nclass FileMapper : private boost::noncopyable\n{\npublic:\n    FileMapper(int fd, size_t startPosition, size_t maxBufsize);\n    ~FileMapper();\n\n    void* getPtr(size_t currentPosition, size_t offset) const;\n    void mapping();\n    void remapping(size_t startPosition, size_t offset);\n\nprivate:\n    int m_fd;\n    size_t m_startPosition;\n    size_t m_maxBufsize;\n    void* m_ptr;\n};\n\n} // hash_calculator\n", "meta": {"hexsha": "9f295507c5b2392d9d0db753caa75c84d0365e04", "size": 497, "ext": "h", "lang": "C", "max_stars_repo_path": "modules/hash_calculator/src/FileMapper.h", "max_stars_repo_name": "nicledomaS/HashCalculator", "max_stars_repo_head_hexsha": "4708824e2ddde1fc7c330711ae7939c57556cb7d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/hash_calculator/src/FileMapper.h", "max_issues_repo_name": "nicledomaS/HashCalculator", "max_issues_repo_head_hexsha": "4708824e2ddde1fc7c330711ae7939c57556cb7d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/hash_calculator/src/FileMapper.h", "max_forks_repo_name": "nicledomaS/HashCalculator", "max_forks_repo_head_hexsha": "4708824e2ddde1fc7c330711ae7939c57556cb7d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.75, "max_line_length": 64, "alphanum_fraction": 0.7183098592, "num_tokens": 125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.039638842504478966, "lm_q2_score": 0.020332351450460244, "lm_q1q2_score": 0.0008059508768905081}}
{"text": "#pragma once\n/*\n * (C) Copyright 2020 UCAR\n *\n * This software is licensed under the terms of the Apache Licence Version 2.0\n * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.\n */\n/// \\file Copying.h\n/// \\brief Generic copying facility\n/// \\note Feature is under development. This is a placeholder header file.\n\n#include <algorithm>\n#include <gsl/gsl-lite.hpp>\n#include <memory>\n#include <set>\n#include <utility>\n#include <vector>\n\n#include \"ioda/Group.h\"\n#include \"ioda/defs.h\"\n\nnamespace ioda {\nclass Group;\nclass Has_Variables;\n\nclass ObjectSelection;\nstruct ScaleMapping;\n\n/// \\todo This function is not yet complete.\n///   It exists in its present form to provide the guts for\n///   a timing test. Do not use.\n/// \\brief Generic data copying function\n/// \\param from contains the objects that we are copying\n/// \\param to contains the destination(s) of the copy\n/// \\param scale_map contains settings regarding how dimension scales\n///   are propagated\nIODA_DL void copy(const ObjectSelection& from, ObjectSelection& to, const ScaleMapping& scale_map);\n\n/// \\brief Allows you to select objects for a copy operation\nclass IODA_DL ObjectSelection {\n  // friend IODA_DL void copy(const ObjectSelection&, ObjectSelection&, const ScaleMapping&);\npublic:\n  Group g_;\n  bool recurse_ = false;\n\npublic:\n  ~ObjectSelection();\n  ObjectSelection();\n  ObjectSelection(const Group& g, bool recurse = true);\n  /*\n  ObjectSelection(const Variable& v) : ObjectSelection() { insert(v); }\n  ObjectSelection(const std::vector<Variable>& v) : ObjectSelection() { insert(v); }\n  ObjectSelection(const Has_Variables& v) : ObjectSelection() { insert(v); }\n  ObjectSelection(const Group& g, const std::vector<std::string>& v) : ObjectSelection() {\n  insert(g,v); }\n\n  void insert(const ObjectSelection&);\n  void insert(const Variable&);\n  void insert(const std::vector<Variable>&);\n  void insert(const Has_Variables&);\n  void insert(const Group&, const std::vector<std::string>&);\n  void insert(const Group&, bool recurse = true);\n\n  ObjectSelection operator+(const ObjectSelection&) const;\n  ObjectSelection operator+(const Variable&) const;\n  ObjectSelection operator+(const std::vector<Variable>&) const;\n  ObjectSelection operator+(const Has_Variables&) const;\n  // Group insertions need to be wrapped by an ObjectSelection.\n\n  ObjectSelection& operator+=(const ObjectSelection&);\n  ObjectSelection& operator+=(const Variable&);\n  ObjectSelection& operator+=(const std::vector<Variable>&);\n  ObjectSelection& operator+=(const Has_Variables&);\n  */\n};\n\n/// \\brief Settings for how to remap dimension scales\nstruct IODA_DL ScaleMapping {\npublic:\n  ~ScaleMapping();\n\n  std::vector<std::pair<Variable, Variable>> map_from_to;\n  std::vector<Variable> map_new;\n  bool autocreate = false;\n};\n\n}  // namespace ioda\n", "meta": {"hexsha": "8fa6d91bf7340d657c19c72fdad5b2a30e6d8d6c", "size": 2813, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engines/ioda/include/ioda/Copying.h", "max_stars_repo_name": "NOAA-EMC/ioda", "max_stars_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-09T16:11:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-09T16:11:50.000Z", "max_issues_repo_path": "src/engines/ioda/include/ioda/Copying.h", "max_issues_repo_name": "NOAA-EMC/ioda", "max_issues_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engines/ioda/include/ioda/Copying.h", "max_forks_repo_name": "NOAA-EMC/ioda", "max_forks_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-06-09T16:12:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-14T09:19:25.000Z", "avg_line_length": 31.9659090909, "max_line_length": 99, "alphanum_fraction": 0.73302524, "num_tokens": 655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.04885778000710959, "lm_q2_score": 0.016403032215644393, "lm_q1q2_score": 0.0008014157394414851}}
{"text": "/* -----------------------------------------------------------------------------\n * Copyright 2021 Jonathan Haigh\n * SPDX-License-Identifier: MIT\n * ---------------------------------------------------------------------------*/\n\n#ifndef SQ_INCLUDE_GUARD_core_Token_h_\n#define SQ_INCLUDE_GUARD_core_Token_h_\n\n#include \"Token.fwd.h\"\n\n#include \"core/typeutil.h\"\n\n#include <gsl/gsl>\n#include <iosfwd>\n#include <regex>\n#include <string_view>\n#include <vector>\n\nnamespace sq {\n\nenum class TokenKind : int {\n  BoolFalse,\n  BoolTrue,\n  Colon,\n  Comma,\n  Dot,\n  DQString,\n  Eof,\n  Equals,\n  Float,\n  GreaterThan,\n  GreaterThanOrEqualTo,\n  Identifier,\n  Integer,\n  LBrace,\n  LBracket,\n  LessThan,\n  LessThanOrEqualTo,\n  LParen,\n  RBrace,\n  RBracket,\n  RParen\n};\n\nclass Token {\npublic:\n  /**\n   * Create a Token object.\n   *\n   * @param query the full query string in which the token was found.\n   * @param pos the character position within the query at which the token\n   *        was found.\n   * @param len the length, in characters, of the token.\n   * @param kind the kind of the token.\n   */\n  Token(std::string_view query, gsl::index pos, gsl::index len,\n        TokenKind kind) noexcept;\n\n  /**\n   * Get the full query string in which the token was found.\n   */\n  SQ_ND std::string_view query() const noexcept;\n\n  /**\n   * Get the character position within the query at which the token was\n   * found.\n   */\n  SQ_ND gsl::index pos() const noexcept;\n\n  /**\n   * Get the length, in characters, of the token.\n   */\n  SQ_ND gsl::index len() const noexcept;\n\n  /**\n   * Get a std::string_view pointing to the characters of the token.\n   */\n  SQ_ND std::string_view view() const noexcept;\n\n  /**\n   * Get the kind of the token.\n   */\n  SQ_ND TokenKind kind() const noexcept;\n\nprivate:\n  std::string_view query_;\n  gsl::index pos_;\n  gsl::index len_;\n  TokenKind kind_;\n};\n\nstd::ostream &operator<<(std::ostream &os, TokenKind kind);\n\n/**\n * Print information about a token.\n *\n * The text printed includes information about the position of the token in the\n * input query, not just the characters that make up the token.\n */\nstd::ostream &operator<<(std::ostream &os, const Token &token);\n\n} // namespace sq\n\n#endif // SQ_INCLUDE_GUARD_core_Token_h_\n", "meta": {"hexsha": "e0d7b2f7ebefe171ff493c13a1e07212d0056bc2", "size": 2238, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/include/core/Token.h", "max_stars_repo_name": "jonathanhaigh/sq", "max_stars_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-12T16:21:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-12T16:21:41.000Z", "max_issues_repo_path": "src/core/include/core/Token.h", "max_issues_repo_name": "jonathanhaigh/sq", "max_issues_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 44.0, "max_issues_repo_issues_event_min_datetime": "2021-02-08T19:17:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-05T18:51:38.000Z", "max_forks_repo_path": "src/core/include/core/Token.h", "max_forks_repo_name": "jonathanhaigh/sq", "max_forks_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.3142857143, "max_line_length": 80, "alphanum_fraction": 0.6322609473, "num_tokens": 547, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.03210070671700818, "lm_q2_score": 0.024798159519914542, "lm_q1q2_score": 0.0007960384458703611}}
{"text": "\n#if !defined(XEOL_H_INCLUDED)\n#define XEOL_H_INCLUDED\n\n#include \"FileEnumerator.h\"\n#include \"Utils.h\"\n\n#include <filesystem>\n#include <gsl/gsl>\n#include <iosfwd>\n#include <string>\n\nclass Xeol\n{\npublic:\n\tstatic int usage(::std::ostream& strm, const ::std::string& progName,\n\t\tconst char* pMsg);\n\n\tXeol(::gsl::span<const char*const> args);\n\tint run() const;\n\n\tXeol(const Xeol&) = delete;\n\tXeol& operator=(const Xeol&) = delete;\n\tXeol(Xeol&&) = delete;\n\tXeol& operator=(Xeol&&) = delete;\n\nPRIVATE_EXCEPT_IN_TEST:\n\t/// \\brief EolType contains the enum constants that indicate the type of\n\t/// end-of-line for a text file.\n\tenum class EolType\n\t{\n\t\tINDETERMINATE, ///< File contains no ends-of-line\n\t\tMIXED, ///< Inconsistent end-of-line convention, may be binary\n\t\tDOS, ///< End-of-line is \"\\r\\n\"\n\t\tMACINTOSH, ///< End-of-line is \"\\r\" (now archaic)\n\t\tUNIX ///< End-of-line is \"\\n\"\n\t};\n\n\tusing Path = ::std::filesystem::path;\n\n\tvoid queryFile(const Path& p) const;\n\tvoid translateFile(const Path& p) const;\n\tstatic char getIndicatorLetter(EolType eolType);\n\tstatic ::std::string toEolString(EolType eolType);\n\tstatic ::std::string displayPath(const Path& p);\n\n\t/// \\brief Scans the input file, counts the end-of-line types, and\n\t/// optionally translates the ends-of-line into the provided stream.\n\t///\n\t/// If pOut is null, then the method simply counts the end-of-line types and\n\t/// returns the corresponding EolType constant.  In this case, the\n\t/// targetEolType parameter is ignored.\n\t///\n\t/// If pOut is not null, then the method additionally translates the file\n\t/// into *pOut.  In this case, targetEolType must be one of DOS, MACINTOSH,\n\t/// or UNIX.\n\tstatic EolType scanFile(::std::istream& in,\n\t\t/* out */ size_t& numDosEols, /* out */ size_t& numMacEols,\n\t\t/* out */ size_t& numUnixEols, /* out */ size_t& totalEols,\n\t\t::std::ostream* pOut = nullptr, EolType targetEolType = EolType::INDETERMINATE);\n\n\tstatic void replaceOriginalFileWithTemp(const Path& originalPath,\n\t\tconst Path& tempPath);\n\n\tbool\t\t\t\tm_isInQueryMode;\n\tEolType\t\t\tm_targetEolType;\n\tbool\t\t\t\tm_forceTranslation;\n\tFileEnumerator\tm_fileEnumerator;\n};\n\n#endif // XEOL_H_INCLUDED\n", "meta": {"hexsha": "3881718bcc827c6aadfa12e1a725a2a597abf087", "size": 2149, "ext": "h", "lang": "C", "max_stars_repo_path": "Xeol.h", "max_stars_repo_name": "IanEmmons/CmdLineUtil", "max_stars_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Xeol.h", "max_issues_repo_name": "IanEmmons/CmdLineUtil", "max_issues_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Xeol.h", "max_forks_repo_name": "IanEmmons/CmdLineUtil", "max_forks_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8472222222, "max_line_length": 82, "alphanum_fraction": 0.7068403909, "num_tokens": 621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.05419873440629665, "lm_q2_score": 0.014503580356962188, "lm_q1q2_score": 0.0007860756997073747}}
{"text": "/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */\n/*\n *     Copyright 2018-Present Couchbase, Inc.\n *\n *   Use of this software is governed by the Business Source License included\n *   in the file licenses/BSL-Couchbase.txt.  As of the Change Date specified\n *   in that file, in accordance with the Business Source License, use of this\n *   software will be governed by the Apache License, Version 2.0, included in\n *   the file licenses/APL2.txt.\n */\n#pragma once\n\n#include \"dcp/dcp-types.h\"\n#include \"evp_engine_test.h\"\n#include \"evp_store_single_threaded_test.h\"\n#include \"vbucket_fwd.h\"\n#include <memcached/engine_error.h>\n#include <gsl/gsl>\n\nclass Item;\nclass MockDcpProducer;\nclass MockActiveStream;\nstruct DcpMessageProducersIface;\n\n/**\n * Test fixture for unit tests related to DCP.\n */\nclass DCPTest : public EventuallyPersistentEngineTest {\nprotected:\n    void SetUp() override;\n\n    void TearDown() override;\n\n    // Create a DCP producer; initially with no streams associated.\n    void create_dcp_producer(\n            int flags = 0,\n            IncludeValue includeVal = IncludeValue::Yes,\n            IncludeXattrs includeXattrs = IncludeXattrs::Yes,\n            std::vector<std::pair<std::string, std::string>> controls = {});\n\n    // Setup a DCP producer and attach a stream and cursor to it.\n    void setup_dcp_stream(\n            int flags = 0,\n            IncludeValue includeVal = IncludeValue::Yes,\n            IncludeXattrs includeXattrs = IncludeXattrs::Yes,\n            std::vector<std::pair<std::string, std::string>> controls = {});\n\n    cb::engine_errc destroy_dcp_stream();\n\n    struct StreamRequestResult {\n        cb::engine_errc status;\n        uint64_t rollbackSeqno;\n    };\n\n    /**\n     * Helper function to simplify calling producer->streamRequest() - provides\n     * sensible default values for common invocations.\n     */\n    static StreamRequestResult doStreamRequest(DcpProducer& producer,\n                                               uint64_t startSeqno = 0,\n                                               uint64_t endSeqno = ~0,\n                                               uint64_t snapStart = 0,\n                                               uint64_t snapEnd = ~0,\n                                               uint64_t vbUUID = 0);\n\n    /**\n     * Helper function to simplify the process of preparing DCP items to be\n     * fetched from the stream via step().\n     * Should be called once all expected items are present in the vbuckets'\n     * checkpoint, it will then run the correct background tasks to\n     * copy CheckpointManager items to the producers' readyQ.\n     */\n    static void prepareCheckpointItemsForStep(\n            DcpMessageProducersIface& msgProducers,\n            MockDcpProducer& producer,\n            VBucket& vb);\n\n    /*\n     * Creates an item with the key \\\"key\\\", containing json data and xattrs.\n     * @return a unique_ptr to a newly created item.\n     */\n    std::unique_ptr<Item> makeItemWithXattrs();\n\n    /*\n     * Creates an item with the key \\\"key\\\", containing json data and no xattrs.\n     * @return a unique_ptr to a newly created item.\n     */\n    std::unique_ptr<Item> makeItemWithoutXattrs();\n\n    /* Add items onto the vbucket and wait for the checkpoint to be removed */\n    void addItemsAndRemoveCheckpoint(int numItems);\n\n    void removeCheckpoint(int numItems);\n\n    void runCheckpointProcessor(DcpMessageProducersIface& producers);\n\n    std::shared_ptr<MockDcpProducer> producer;\n    std::shared_ptr<MockActiveStream> stream;\n    VBucketPtr vb0;\n\n    /*\n     * Fake callback emulating dcp_add_failover_log\n     */\n    static cb::engine_errc fakeDcpAddFailoverLog(\n            const std::vector<vbucket_failover_t>&) {\n        callbackCount++;\n        return cb::engine_errc::success;\n    }\n\n    // callbackCount needs to be static as its used inside of the static\n    // function fakeDcpAddFailoverLog.\n    static int callbackCount;\n};\n\nclass FlowControlTest : public KVBucketTest,\n                        public ::testing::WithParamInterface<bool> {\nprotected:\n    void SetUp() override;\n\n    bool flowControlEnabled;\n};", "meta": {"hexsha": "4e13611789b8369032653a54a9be5585f8d94562", "size": 4150, "ext": "h", "lang": "C", "max_stars_repo_path": "engines/ep/tests/module_tests/dcp_test.h", "max_stars_repo_name": "BenHuddleston/kv_engine", "max_stars_repo_head_hexsha": "78123c9aa2c2feb24b7c31eecc862bf2ed6325e4", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "engines/ep/tests/module_tests/dcp_test.h", "max_issues_repo_name": "BenHuddleston/kv_engine", "max_issues_repo_head_hexsha": "78123c9aa2c2feb24b7c31eecc862bf2ed6325e4", "max_issues_repo_licenses": ["MIT", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "engines/ep/tests/module_tests/dcp_test.h", "max_forks_repo_name": "BenHuddleston/kv_engine", "max_forks_repo_head_hexsha": "78123c9aa2c2feb24b7c31eecc862bf2ed6325e4", "max_forks_repo_licenses": ["MIT", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2975206612, "max_line_length": 80, "alphanum_fraction": 0.6462650602, "num_tokens": 937, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.03114383143403054, "lm_q2_score": 0.02517884307215325, "lm_q1q2_score": 0.0007841656443430485}}
{"text": "/* Copyright 2019-2020 Canaan Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *     http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n#pragma once\r\n#include <gsl/gsl-lite.hpp>\r\n#include <type_traits>\r\n\r\n#if defined(_MSC_VER)\r\n#ifdef NNCASE_DLL\r\n#define NNCASE_API __declspec(dllexport)\r\n#elif defined(NNCASE_SHARED_LIBS)\r\n#define NNCASE_API __declspec(dllimport)\r\n#else\r\n#define NNCASE_API\r\n#endif\r\n#else\r\n#define NNCASE_API\r\n#endif\r\n\r\n#if defined(_MSC_VER)\r\n#define NNCASE_UNREACHABLE() __assume(0)\r\n#else\r\n#define NNCASE_UNREACHABLE() __builtin_unreachable()\r\n#endif\r\n\r\n#if gsl_CPP17_OR_GREATER\r\n#define NNCASE_INLINE_VAR inline\r\n#define NNCASE_UNUSED [[maybe_unused]]\r\nnamespace nncase\r\n{\r\ntemplate <class Callable, class... Args>\r\nusing invoke_result_t = std::invoke_result_t<Callable, Args...>;\r\n}\r\n#else\r\n#define NNCASE_INLINE_VAR\r\n#if defined(_MSC_VER)\r\n#define NNCASE_UNUSED\r\n#else\r\n#define NNCASE_UNUSED __attribute__((unused))\r\n#endif\r\nnamespace nncase\r\n{\r\ntemplate <class Callable, class... Args>\r\nusing invoke_result_t = std::result_of_t<Callable(Args...)>;\r\n}\r\n#endif\r\n\r\n#define NNCASE_LITTLE_ENDIAN 1\r\n\r\n#define NNCASE_HAVE_STD_BYTE gsl_CPP17_OR_GREATER\r\n#define NNCASE_NODISCARD gsl_NODISCARD\r\n#define NNCASE_NORETURN gsl_NORETURN\r\n\r\n#define BEGIN_NS_NNCASE_RUNTIME \\\r\n    namespace nncase            \\\r\n    {                           \\\r\n        namespace runtime       \\\r\n        {\r\n#define END_NS_NNCASE_RUNTIME \\\r\n    }                         \\\r\n    }\r\n\r\n#define BEGIN_NS_NNCASE_RT_STACKVM \\\r\n    namespace nncase               \\\r\n    {                              \\\r\n        namespace runtime          \\\r\n        {                          \\\r\n            namespace stackvm      \\\r\n            {\r\n#define END_NS_NNCASE_RT_STACKVM \\\r\n    }                            \\\r\n    }                            \\\r\n    }\r\n\r\n#define BEGIN_NS_NNCASE_KERNELS \\\r\n    namespace nncase            \\\r\n    {                           \\\r\n        namespace kernels       \\\r\n        {\r\n\r\n#define END_NS_NNCASE_KERNELS \\\r\n    }                         \\\r\n    }\r\n\r\n#ifndef DEFINE_ENUM_BITMASK_OPERATORS\r\n#define DEFINE_ENUM_BITMASK_OPERATORS(ENUMTYPE) gsl_DEFINE_ENUM_BITMASK_OPERATORS(ENUMTYPE)\r\n#endif\r\n\r\nnamespace nncase\r\n{\r\nstruct default_init_t\r\n{\r\n};\r\n\r\nNNCASE_INLINE_VAR constexpr default_init_t default_init {};\r\n}\r\n", "meta": {"hexsha": "af41d971b190a08c9b46960b5c224837806a6b2f", "size": 2799, "ext": "h", "lang": "C", "max_stars_repo_path": "lib/nncase/v1/include/nncase/runtime/compiler_defs.h", "max_stars_repo_name": "HelloDavid2020/kendryte-standalone-sdk", "max_stars_repo_head_hexsha": "d740f558940aefd2eaa8f358f1a81041f93155dc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-11T08:32:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-11T08:32:10.000Z", "max_issues_repo_path": "lib/nncase/v1/include/nncase/runtime/compiler_defs.h", "max_issues_repo_name": "HelloDavid2020/kendryte-standalone-sdk", "max_issues_repo_head_hexsha": "d740f558940aefd2eaa8f358f1a81041f93155dc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/nncase/v1/include/nncase/runtime/compiler_defs.h", "max_forks_repo_name": "HelloDavid2020/kendryte-standalone-sdk", "max_forks_repo_head_hexsha": "d740f558940aefd2eaa8f358f1a81041f93155dc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9166666667, "max_line_length": 92, "alphanum_fraction": 0.6405859235, "num_tokens": 623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.03732688948593843, "lm_q2_score": 0.020964241812115588, "lm_q1q2_score": 0.0007825299372773281}}
{"text": "#pragma once\n\n#include <gsl/string_span>\n\n#include <fmt/format.h>\n\n#include <string>\n#include <algorithm>\n#include <functional>\n#include <vector>\n#include <sstream>\n#include <cctype>\n#include <iosfwd>\n\n// Thanks Stackoverflow...\n\nstd::string ucs2_to_local(const std::wstring &);\nstd::wstring local_to_ucs2(const std::string &);\nstd::string ucs2_to_utf8(const std::wstring &);\nstd::wstring utf8_to_ucs2(const std::string &);\n\n// trim from start\ninline std::string &ltrim(std::string &s) {\n\ts.erase(s.begin(), find_if(s.begin(), s.end(), [](auto c) { return !std::isspace(c); }));\n\treturn s;\n}\n\n// trim from end\ninline std::string &rtrim(std::string &s) {\n\ts.erase(find_if(s.rbegin(), s.rend(), [](auto c) { return !std::isspace(c); }).base(), s.end());\n\treturn s;\n}\n\n// trim from both ends\ninline std::string &trim(std::string &s) {\n\treturn ltrim(rtrim(s));\n}\n\ninline std::vector<gsl::cstring_span<>>& split(gsl::cstring_span<> s, \n\tchar delim, \n\tstd::vector<gsl::cstring_span<>>& elems, \n\tbool trimItems = false, \n\tbool keepEmpty = false) {\n\n\tint pos = 0;\n\twhile (pos < s.size()) {\n\t\tauto ch = s[pos++];\n\n\t\t// Empty item\n\t\tif (ch == delim) {\n\t\t\tif (keepEmpty) {\n\t\t\t\telems.push_back({});\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (trimItems && isspace(ch)) {\n\t\t\t// Skip all chars that are considered whitespace\n\t\t\tcontinue;\n\t\t}\n\n\t\tauto start = pos - 1; // Start of item\n\t\tsize_t count = 1; // Size of item\n\n\t\t// Seek past all of the item's content\n\t\twhile (pos < s.size()) {\n\t\t\tch = s[pos++];\n\t\t\tif (ch == delim) {\n\t\t\t\tbreak; // reached the end of the item\n\t\t\t}\n\t\t\tcount++;\n\t\t}\n\n\t\t// Trim whitespace at the end of the string\n\t\tif (trimItems) {\n\t\t\twhile (count > 0 && isspace(s[start + count - 1])) {\n\t\t\t\tcount--;\n\t\t\t}\n\t\t}\n\n\t\tif (count != 0) {\n\t\t\telems.push_back(s.subspan(start, count));\n\t\t} else if (keepEmpty) {\n\t\t\telems.push_back({});\n\t\t}\n\n\t}\n\n\treturn elems;\n}\n\ninline std::vector<gsl::cstring_span<>> split(gsl::cstring_span<> s, char delim, bool trim = false, bool keepEmpty = false) {\n\tstd::vector<gsl::cstring_span<>> elems;\n\tsplit(s, delim, elems, trim, keepEmpty);\n\treturn elems;\n}\n\ninline std::vector<std::string>& split(const std::string& s, char delim, std::vector<std::string>& elems, bool trimItems = false, bool keepEmpty = false) {\n\tstd::stringstream ss(s);\n\tstd::string item;\n\twhile (getline(ss, item, delim)) {\n\t\tif (trimItems) {\n\t\t\titem = trim(item);\n\t\t}\n\t\tif (keepEmpty || !item.empty()) {\n\t\t\telems.push_back(item);\n\t\t}\n\t}\n\treturn elems;\n}\n\ninline std::vector<std::string> split(const std::string& s, char delim, bool trim = false, bool keepEmpty = false) {\n\tstd::vector<std::string> elems;\n\tsplit(s, delim, elems, trim, keepEmpty);\n\treturn elems;\n}\n\ninline std::string tolower(const std::string &s) {\n\tauto needsConversion = std::any_of(s.begin(), s.end(), [](char a) {\n\t\treturn std::tolower(a) != a;\n\t});\n\tif (needsConversion) {\n\t\tstd::string result = s;\n\t\tstd::transform(result.begin(), result.end(), result.begin(), [](char ch) { return std::tolower((int)ch); });\n\t\treturn result;\n\t} else {\n\t\treturn s;\n\t}\n}\n\ninline std::string tounderscore(const std::string &s) {\n\tauto needsConversion = std::any_of(s.begin(), s.end(), [](char a) {\n\t\treturn a == ' ';\n\t});\n\tif (needsConversion) {\n\t\tstd::string result = s;\n\t\tstd::transform(result.begin(), result.end(), result.begin(), [](char ch){\n\t\t\tif (ch == ' '){\n\t\t\t\treturn '_';\n\t\t\t}\n\t\t\treturn ch;\n\t\t});\n\t\treturn result;\n\t}\n\telse {\n\t\treturn s;\n\t}\n}\n\ninline std::string toupper(const std::string &s) {\n\tauto needsConversion = std::any_of(s.begin(), s.end(), [](char a) {\n\t\treturn std::toupper(a) != a;\n\t});\n\tif (needsConversion) {\n\t\tstd::string result = s;\n\t\tstd::transform(result.begin(), result.end(), result.begin(), [](char ch) { return std::toupper((int)ch); });\n\t\treturn result;\n\t}\n\telse {\n\t\treturn s;\n\t}\n}\n\n// Nice to have operator for serializing vectors in the logger\nnamespace std {\n\ttemplate<typename T>\n\tvoid format_arg(fmt::BasicFormatter<char> &f, const char *&format_str, const std::vector<T> &v) {\n\t\tusing namespace std;\n\n\t\tf.writer().write(\"[\");\n\t\tfor (size_t i = 0; i < v.size(); ++i) {\n\t\t\tf.writer().write(\"{}\", v[i]);\n\t\t\tif (i != v.size() - 1) {\n\t\t\t\tf.writer().write(\", \");\n\t\t\t}\n\t\t}\n\t\tf.writer().write(\"]\");\n\t}\n}\n\ninline bool endsWith(const std::string &str, const std::string &suffix) {\n\tif (suffix.length() > str.length()) {\n\t\treturn false; // Short-circuit\n\t}\n\n\treturn str.compare(str.length() - suffix.length(), suffix.length(), suffix) == 0;\n}\n", "meta": {"hexsha": "987e0f155cb11fa8cc74e280f461fe915682d330", "size": 4417, "ext": "h", "lang": "C", "max_stars_repo_path": "Infrastructure/include/infrastructure/stringutil.h", "max_stars_repo_name": "edoipi/TemplePlus", "max_stars_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 69.0, "max_stars_repo_stars_event_min_datetime": "2015-05-05T14:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T06:13:04.000Z", "max_issues_repo_path": "Infrastructure/include/infrastructure/stringutil.h", "max_issues_repo_name": "edoipi/TemplePlus", "max_issues_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 457.0, "max_issues_repo_issues_event_min_datetime": "2015-05-01T22:07:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T02:19:10.000Z", "max_forks_repo_path": "Infrastructure/include/infrastructure/stringutil.h", "max_forks_repo_name": "edoipi/TemplePlus", "max_forks_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2016-02-04T21:19:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T23:14:51.000Z", "avg_line_length": 23.4946808511, "max_line_length": 155, "alphanum_fraction": 0.6235001132, "num_tokens": 1275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.038466195325179156, "lm_q2_score": 0.020332354455716784, "lm_q1q2_score": 0.0007821083179143785}}
{"text": "#pragma once\n\n#include <string_view>\n#include <gsl/span>\n#include <spirv_cross.hpp>\n\nnamespace babylon\n{\n    class ShaderCompiler\n    {\n    public:\n        ShaderCompiler();\n        ~ShaderCompiler();\n\n        struct ShaderInfo\n        {\n            std::unique_ptr<const spirv_cross::Compiler> Compiler;\n            gsl::span<uint8_t> Bytes;\n        };\n\n        void Compile(std::string_view vertexSource, std::string_view fragmentSource, std::function<void (ShaderInfo, ShaderInfo)> onCompiled);\n    };\n}\n", "meta": {"hexsha": "cdb8eb013dc3cfcc37e75c40dd132147bd4b168b", "size": 507, "ext": "h", "lang": "C", "max_stars_repo_path": "Library/Source/ShaderCompiler.h", "max_stars_repo_name": "TrevorDev/BabylonNative", "max_stars_repo_head_hexsha": "6d15ec5d418f7f723eba574665233049c785cc72", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-02-18T22:03:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T11:42:08.000Z", "max_issues_repo_path": "Library/Source/ShaderCompiler.h", "max_issues_repo_name": "TrevorDev/BabylonNative", "max_issues_repo_head_hexsha": "6d15ec5d418f7f723eba574665233049c785cc72", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-03T22:56:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-13T00:01:39.000Z", "max_forks_repo_path": "Library/Source/ShaderCompiler.h", "max_forks_repo_name": "ryantrem/BabylonNative", "max_forks_repo_head_hexsha": "548684984126ee6cd242f2d73ecff8c6f5614b02", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.125, "max_line_length": 142, "alphanum_fraction": 0.6351084813, "num_tokens": 112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08151975374329137, "lm_q2_score": 0.009559397883340464, "lm_q1q2_score": 0.0007792797613840554}}
{"text": "#ifndef VolViz_AtomicCache_h\n#define VolViz_AtomicCache_h\n\n#include <gsl/gsl>\n\n#include <atomic>\n\n#pragma clang diagnostic ignored \"-Wpadded\"\n\nnamespace VolViz {\n\n/// Class represening a cached value, that has a very basic thread safety.\n/// The thread saftey is as follows: the cache'd value must not be accessed\n/// from different threads (at least without external synchronization), but\n/// the cache can be marked dirty from any thread.\n/// A typical use case is to cache a derived property that depends on some\n/// shared (beween threads) resources (e.g. AtomicWrapper<> objects) and the\n/// cached value is frequently accessed but the dependent resource does not\n/// change so often.\n///\n/// @tparam T the cached type\ntemplate <class T> class AtomicCache {\npublic:\n  /// Creates a dirty cache with the given fetch operation.\n  /// @tparam FetchOp the fetch operation. It takes no parameter and returns an\n  /// object convertible to T.\n  /// @note At construction no fetch operation is issued.\n  template <class FetchOp>\n  AtomicCache(FetchOp fetchOperation)\n      : fetchOperation_(fetchOperation) {\n    Expects(fetchOperation_);\n    dirtyFlag_.clear();\n  }\n\n  /// Marks the cache as dirty, i.e. a fetch operations must be perfomed on the\n  /// next read.\n  /// @note this method is thread safe.\n  inline void markAsDirty() noexcept { dirtyFlag_.clear(); }\n\n  /// Returns the cached object. If the cache is dirty, a fetch operations is\n  /// performed first.\n  /// @note This method must not be called from more than one thread.\n  inline operator T const &() const noexcept {\n    if (dirtyFlag_.test_and_set()) return value_;\n\n    Expects(fetchOperation_);\n    value_ = std::move(fetchOperation_());\n    return value_;\n  }\n\nprivate:\n  /// The caced value\n  mutable T value_;\n\n  /// The atomic dirty flag\n  mutable std::atomic_flag dirtyFlag_;\n\n  /// The fetch operation\n  std::function<T()> const fetchOperation_;\n};\n\n} // namespace VolViz\n\n#endif // VolViz_AtomicCache_h\n", "meta": {"hexsha": "09d3afdb60cab7659d4260811effd7cc330501b2", "size": 1979, "ext": "h", "lang": "C", "max_stars_repo_path": "include/VolViz/src/AtomicCache.h", "max_stars_repo_name": "ithron/VolViz", "max_stars_repo_head_hexsha": "e79f36563d908d9ba1bd71c3e760792521dd5e7a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/VolViz/src/AtomicCache.h", "max_issues_repo_name": "ithron/VolViz", "max_issues_repo_head_hexsha": "e79f36563d908d9ba1bd71c3e760792521dd5e7a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2016-06-09T07:38:52.000Z", "max_issues_repo_issues_event_max_datetime": "2016-10-28T12:23:59.000Z", "max_forks_repo_path": "include/VolViz/src/AtomicCache.h", "max_forks_repo_name": "ithron/VolViz", "max_forks_repo_head_hexsha": "e79f36563d908d9ba1bd71c3e760792521dd5e7a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4461538462, "max_line_length": 79, "alphanum_fraction": 0.7200606367, "num_tokens": 465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.027169230747973956, "lm_q2_score": 0.028436029957247463, "lm_q1q2_score": 0.0007725850594647564}}
{"text": "//\n// Copyright (C) Microsoft Corporation. All rights reserved.\n//\n\n#pragma once\n\n#include <intsafe.h>\n#include <gsl/gsl>\n\nnamespace arcana\n{\n    void set_thread_name(DWORD threadId, gsl::czstring<> threadName);\n}\n", "meta": {"hexsha": "a7f1bf67394b74eede48e93c888f615b749816e0", "size": 214, "ext": "h", "lang": "C", "max_stars_repo_path": "Source/Windows/arcana/threading/set_thread_name.h", "max_stars_repo_name": "andrei-datcu/arcana.cpp", "max_stars_repo_head_hexsha": "3c4757cbee49b3272130bf8b72094c2c62fd36c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 65.0, "max_stars_repo_stars_event_min_datetime": "2019-05-08T01:53:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T15:05:38.000Z", "max_issues_repo_path": "Source/Windows/arcana/threading/set_thread_name.h", "max_issues_repo_name": "andrei-datcu/arcana.cpp", "max_issues_repo_head_hexsha": "3c4757cbee49b3272130bf8b72094c2c62fd36c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2019-08-13T03:18:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T20:12:24.000Z", "max_forks_repo_path": "Source/Windows/arcana/threading/set_thread_name.h", "max_forks_repo_name": "andrei-datcu/arcana.cpp", "max_forks_repo_head_hexsha": "3c4757cbee49b3272130bf8b72094c2c62fd36c5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2019-05-09T23:07:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-26T14:24:29.000Z", "avg_line_length": 15.2857142857, "max_line_length": 69, "alphanum_fraction": 0.714953271, "num_tokens": 53, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.03567854780163102, "lm_q2_score": 0.0216153329989962, "lm_q1q2_score": 0.0007712036916528584}}
{"text": "#pragma once\n\n#include \"CesiumGltfReader/Library.h\"\n\n#include <CesiumAsync/AsyncSystem.h>\n#include <CesiumAsync/Future.h>\n#include <CesiumAsync/HttpHeaders.h>\n#include <CesiumAsync/IAssetAccessor.h>\n#include <CesiumGltf/Model.h>\n#include <CesiumJsonReader/ExtensionReaderContext.h>\n#include <CesiumJsonReader/IExtensionJsonHandler.h>\n\n#include <gsl/span>\n\n#include <functional>\n#include <memory>\n#include <optional>\n#include <string>\n#include <vector>\n\nnamespace CesiumGltfReader {\n\n/**\n * @brief The result of reading a glTF model with\n * {@link GltfReader::readModel}.\n */\nstruct CESIUMGLTFREADER_API ModelReaderResult {\n  /**\n   * @brief The read model, or std::nullopt if the model could not be read.\n   */\n  std::optional<CesiumGltf::Model> model;\n\n  /**\n   * @brief Errors, if any, that occurred during the load process.\n   */\n  std::vector<std::string> errors;\n\n  /**\n   * @brief Warnings, if any, that occurred during the load process.\n   */\n  std::vector<std::string> warnings;\n};\n\n/**\n * @brief The result of reading an image with\n * {@link GltfReader::readImage}.\n */\nstruct CESIUMGLTFREADER_API ImageReaderResult {\n\n  /**\n   * @brief The {@link ImageCesium} that was read.\n   *\n   * This will be `std::nullopt` if the image could not be read.\n   */\n  std::optional<CesiumGltf::ImageCesium> image;\n\n  /**\n   * @brief Error messages that occurred while trying to read the image.\n   */\n  std::vector<std::string> errors;\n\n  /**\n   * @brief Warning messages that occurred while reading the image.\n   */\n  std::vector<std::string> warnings;\n};\n\n/**\n * @brief Options for how to read a glTF.\n */\nstruct CESIUMGLTFREADER_API ReadModelOptions {\n  /**\n   * @brief Whether data URLs in buffers and images should be automatically\n   * decoded as part of the load process.\n   */\n  bool decodeDataUrls = true;\n\n  /**\n   * @brief Whether data URLs should be cleared after they are successfully\n   * decoded.\n   *\n   * This reduces the memory usage of the model.\n   */\n  bool clearDecodedDataUrls = true;\n\n  /**\n   * @brief Whether embedded images in {@link Model::buffers} should be\n   * automatically decoded as part of the load process.\n   *\n   * The {@link ImageSpec::mimeType} property is ignored, and instead the\n   * [stb_image](https://github.com/nothings/stb) library is used to decode\n   * images in `JPG`, `PNG`, `TGA`, `BMP`, `PSD`, `GIF`, `HDR`, or `PIC` format.\n   */\n  bool decodeEmbeddedImages = true;\n\n  /**\n   * @brief Whether geometry compressed using the `KHR_draco_mesh_compression`\n   * extension should be automatically decoded as part of the load process.\n   */\n  bool decodeDraco = true;\n};\n\n/**\n * @brief Reads glTF models and images.\n */\nclass CESIUMGLTFREADER_API GltfReader {\npublic:\n  /**\n   * @brief Constructs a new instance.\n   */\n  GltfReader();\n\n  /**\n   * @brief Gets the context used to control how extensions are loaded from glTF\n   * files.\n   */\n  CesiumJsonReader::ExtensionReaderContext& getExtensions();\n\n  /**\n   * @brief Gets the context used to control how extensions are loaded from glTF\n   * files.\n   */\n  const CesiumJsonReader::ExtensionReaderContext& getExtensions() const;\n\n  /**\n   * @brief Reads a glTF or binary glTF (GLB) from a buffer.\n   *\n   * @param data The buffer from which to read the glTF.\n   * @param options Options for how to read the glTF.\n   * @return The result of reading the glTF.\n   */\n  ModelReaderResult readModel(\n      const gsl::span<const std::byte>& data,\n      const ReadModelOptions& options = ReadModelOptions()) const;\n\n  /**\n   * @brief Accepts the result of {@link readModel} and resolves any remaining\n   * external buffers and images.\n   *\n   * @param asyncSystem The async system to use for resolving external data.\n   * @param baseUrl The base url that all the external uris are relative to.\n   * @param headers The http headers needed to make any external data requests.\n   * @param pAssetAccessor The asset accessor to use to request the external\n   * buffers and images.\n   * @param result The result of the synchronous readModel invocation.\n   */\n  static CesiumAsync::Future<ModelReaderResult> resolveExternalData(\n      CesiumAsync::AsyncSystem asyncSystem,\n      const std::string& baseUrl,\n      const CesiumAsync::HttpHeaders& headers,\n      std::shared_ptr<CesiumAsync::IAssetAccessor> pAssetAccessor,\n      ModelReaderResult&& result);\n\n  /**\n   * @brief Reads an image from a buffer.\n   *\n   * The [stb_image](https://github.com/nothings/stb) library is used to decode\n   * images in `JPG`, `PNG`, `TGA`, `BMP`, `PSD`, `GIF`, `HDR`, or `PIC` format.\n   *\n   * @param data The buffer from which to read the image.\n   * @return The result of reading the image.\n   */\n  static ImageReaderResult readImage(const gsl::span<const std::byte>& data);\n\nprivate:\n  CesiumJsonReader::ExtensionReaderContext _context;\n};\n\n} // namespace CesiumGltfReader\n", "meta": {"hexsha": "a2ccbdfc5a4e00d3d8546ff97862e55e27cd2a03", "size": 4843, "ext": "h", "lang": "C", "max_stars_repo_path": "CesiumGltfReader/include/CesiumGltfReader/GltfReader.h", "max_stars_repo_name": "137734949/cesium-native", "max_stars_repo_head_hexsha": "7fbccc0ff302f3645dc5829c3a2f3a5bdba83922", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 154.0, "max_stars_repo_stars_event_min_datetime": "2021-03-30T14:08:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T00:01:43.000Z", "max_issues_repo_path": "CesiumGltfReader/include/CesiumGltfReader/GltfReader.h", "max_issues_repo_name": "137734949/cesium-native", "max_issues_repo_head_hexsha": "7fbccc0ff302f3645dc5829c3a2f3a5bdba83922", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 256.0, "max_issues_repo_issues_event_min_datetime": "2021-03-30T18:12:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:44:21.000Z", "max_forks_repo_path": "CesiumGltfReader/include/CesiumGltfReader/GltfReader.h", "max_forks_repo_name": "137734949/cesium-native", "max_forks_repo_head_hexsha": "7fbccc0ff302f3645dc5829c3a2f3a5bdba83922", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 66.0, "max_forks_repo_forks_event_min_datetime": "2021-03-30T15:14:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T13:38:41.000Z", "avg_line_length": 28.4882352941, "max_line_length": 80, "alphanum_fraction": 0.6956431964, "num_tokens": 1248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.04084571999646488, "lm_q2_score": 0.018833130888579408, "lm_q1q2_score": 0.0007692527909316883}}
{"text": "#pragma once\n#include <string>\n#include <ntdll.h>\n#include <gsl/span>\n\nnamespace pe\n{\n  class module : public HINSTANCE__\n  {\n  public:\n    module() = delete;\n    uintptr_t handle() const;\n    template <class T>\n    inline auto rva_to(uint32_t rva)\n    {\n      return reinterpret_cast<T *>(reinterpret_cast<uintptr_t>(this) + rva);\n    }\n    template <class T>\n    inline auto rva_to(uint32_t rva) const\n    {\n      return reinterpret_cast<const T *>(reinterpret_cast<uintptr_t>(this) + rva);\n    }\n    std::wstring base_name() const;\n    std::wstring full_name() const;\n    IMAGE_DOS_HEADER *dos_header();\n    const IMAGE_DOS_HEADER *dos_header() const;\n    IMAGE_NT_HEADERS *nt_header();\n    const IMAGE_NT_HEADERS *nt_header() const;\n    size_t size() const;\n    gsl::span<class segment> segments();\n    gsl::span<const class segment> segments() const;\n    class segment *segment(const char* namename);\n    const class segment *segment(const char* name) const;\n    class export_directory *export_directory();\n    const class export_directory *export_directory() const;\n    void *find_function(const char *name) const;\n    void *find_function(uint32_t num) const;\n  };\n  class module *get_module(const wchar_t *name = nullptr);\n  class module *get_module_from_address(void *pc);\n  const class module *get_module_from_address(const void *pc);\n  class module *instance_module();\n}\n\n#include \"module.inl\"\n", "meta": {"hexsha": "319fea96ab14aa8e939cd1a9d815c92448c0a954", "size": 1404, "ext": "h", "lang": "C", "max_stars_repo_path": "include/pe/module.h", "max_stars_repo_name": "bnsmodpolice/loginhelper", "max_stars_repo_head_hexsha": "7505878b225c7be144ec5e8abf4484133b2cbff9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-12-18T04:53:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-22T20:48:03.000Z", "max_issues_repo_path": "include/pe/module.h", "max_issues_repo_name": "bnsmodpolice/loginhelper", "max_issues_repo_head_hexsha": "7505878b225c7be144ec5e8abf4484133b2cbff9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/pe/module.h", "max_forks_repo_name": "bnsmodpolice/loginhelper", "max_forks_repo_head_hexsha": "7505878b225c7be144ec5e8abf4484133b2cbff9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-18T18:03:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-18T18:03:36.000Z", "avg_line_length": 30.5217391304, "max_line_length": 82, "alphanum_fraction": 0.7008547009, "num_tokens": 341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06371499069622688, "lm_q2_score": 0.012053779627142864, "lm_q1q2_score": 0.0007680064567977767}}
{"text": "#ifndef _UI_HELPERS_H_\n#define _UI_HELPERS_H_\n\n#define OEMRESOURCE\n\n#include <algorithm>\n#include <functional>\n#include <memory>\n#include <optional>\n#include <span>\n#include <string>\n#include <type_traits>\n#include <unordered_map>\n#include <vector>\n\n#include <ppl.h>\n\n#include <gsl/gsl>\n#include <range/v3/all.hpp>\n\n// Included before windows.h, because pfc.h includes winsock2.h\n#include \"../pfc/pfc.h\"\n\n#include <windows.h>\n#include <WindowsX.h>\n#include <SHLWAPI.H>\n#include <vssym32.h>\n#include <uxtheme.h>\n#include <shldisp.h>\n#include <ShlObj.h>\n#include <gdiplus.h>\n#include <Usp10.h>\n#include <CommonControls.h>\n#include <intsafe.h>\n\n#include <wil/resource.h>\n\n#include \"../mmh/stdafx.h\"\n\n#ifndef RECT_CX\n#define RECT_CX(rc) ((rc).right - (rc).left)\n#endif\n\n#ifndef RECT_CY\n#define RECT_CY(rc) ((rc).bottom - (rc).top)\n#endif\n\n#include \"literals.h\"\n\n#include \"handle.h\"\n#include \"win32_helpers.h\"\n#include \"ole.h\"\n\n#include \"dialog.h\"\n#include \"dpi.h\"\n#include \"container_window.h\"\n#include \"message_hook.h\"\n#include \"trackbar.h\"\n#include \"solid_fill.h\"\n#include \"theming.h\"\n\n#include \"gdi.h\"\n#include \"text_drawing.h\"\n#include \"list_view/list_view.h\"\n#include \"drag_image.h\"\n#include \"info_box.h\"\n#include \"menu.h\"\n\n#include \"ole/data_object.h\"\n#include \"ole/enum_format_etc.h\"\n\n#endif\n", "meta": {"hexsha": "1722810d842bc2a46d44ec3b772f72fea536ffb2", "size": 1295, "ext": "h", "lang": "C", "max_stars_repo_path": "stdafx.h", "max_stars_repo_name": "msquared2/ui_helpers", "max_stars_repo_head_hexsha": "2ca7ff26e8f444b7caaf45bd6282c212250e7c41", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stdafx.h", "max_issues_repo_name": "msquared2/ui_helpers", "max_issues_repo_head_hexsha": "2ca7ff26e8f444b7caaf45bd6282c212250e7c41", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stdafx.h", "max_forks_repo_name": "msquared2/ui_helpers", "max_forks_repo_head_hexsha": "2ca7ff26e8f444b7caaf45bd6282c212250e7c41", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.7397260274, "max_line_length": 63, "alphanum_fraction": 0.722007722, "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.05108273117858623, "lm_q2_score": 0.01495708310788378, "lm_q1q2_score": 0.0007640486556158002}}
{"text": "#ifndef PROGRESS_BAR_OBSERVER_H_0L8ZR7QT\n#define PROGRESS_BAR_OBSERVER_H_0L8ZR7QT\n\n#include \"rang.hpp\"\n\n#include <atomic>\n#include <cmath>\n#include <cstdint>\n#include <gsl/gsl>\n#include <iomanip>\n#include <sens_loc/util/console.h>\n#include <taskflow/core/observer.hpp>\n\nnamespace sens_loc::util {\n\nclass progress_bar_observer : public tf::ExecutorObserverInterface {\n  public:\n    constexpr static int max_bars = 50;\n\n    progress_bar_observer(std::int64_t total_tasks)\n        : _total_tasks{total_tasks}\n        , _done{0} {\n        Expects(total_tasks >= 1);\n    }\n\n    progress_bar_observer(const progress_bar_observer&) = delete;\n    progress_bar_observer(progress_bar_observer&&)      = delete;\n    progress_bar_observer& operator=(const progress_bar_observer&) = delete;\n    progress_bar_observer& operator=(progress_bar_observer&&) = delete;\n    ~progress_bar_observer() override                         = default;\n\n    void set_up(unsigned /*num_workers*/) override {}\n    void on_entry(unsigned /*worker_id*/, tf::TaskView /*task_view*/) override;\n    void on_exit(unsigned /*worker_id*/, tf::TaskView /*task_view*/) override;\n\n  private:\n    void print_bar(bool increment) noexcept;\n\n    std::int64_t      _total_tasks;\n    std::int64_t      _done;\n    std::atomic<bool> _inital_output = false;\n};\n}  // namespace sens_loc::util\n\n#endif /* end of include guard: PROGRESS_BAR_OBSERVER_H_0L8ZR7QT */\n", "meta": {"hexsha": "b9db10fe050e876fdc8e978d64cfee4eb5d3ca65", "size": 1409, "ext": "h", "lang": "C", "max_stars_repo_path": "src/include/sens_loc/util/progress_bar_observer.h", "max_stars_repo_name": "JonasToth/depth-conversions", "max_stars_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-09-30T07:09:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T09:14:35.000Z", "max_issues_repo_path": "src/include/sens_loc/util/progress_bar_observer.h", "max_issues_repo_name": "JonasToth/depth-conversions", "max_issues_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/include/sens_loc/util/progress_bar_observer.h", "max_forks_repo_name": "JonasToth/depth-conversions", "max_forks_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6304347826, "max_line_length": 79, "alphanum_fraction": 0.7125621008, "num_tokens": 340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.02064592893143859, "lm_q2_score": 0.03676946845052541, "lm_q1q2_score": 0.000759139832476321}}
{"text": "#pragma once\n#include \"icommand.h\"\n#include \"optioninfo.h\"\n#include \"configaccess.h\"\n#include \"config.h\"\n#include \"format.h\"\n#include \"streamreader.h\"\n#include <gsl/gsl>\n#include <cmdlime/errors.h>\n#include <cmdlime/customnames.h>\n#include <cmdlime/detail/configaccess.h>\n#include <cmdlime/detail/flag.h>\n#include <sstream>\n#include <functional>\n#include <memory>\n\nnamespace cmdlime::detail{\n\ntemplate <typename TConfig>\nclass Command : public ICommand{\npublic:\n    enum class Type{\n        Normal,\n        SubCommand\n    };\n\n    Command(const std::string& name,        \n            std::function<std::optional<TConfig>&()> commandGetter,\n            Type type)\n        : info_(name, {}, {})\n        , commandGetter_(commandGetter)\n        , type_(type)\n    {\n    }\n\n    OptionInfo& info() override\n    {\n        return info_;\n    }\n\n    const OptionInfo& info() const override\n    {\n        return info_;\n    }\n\nprivate:\n    void read(const std::vector<std::string>& commandLine) override\n    {\n        auto& commandCfg = commandGetter_();\n        if (!commandCfg.has_value()){\n            commandCfg.emplace();\n            if (helpFlag_){\n                detail::ConfigAccess<TConfig>(*commandCfg).addFlag(std::move(helpFlag_));\n                detail::ConfigAccess<TConfig>(*commandCfg).addHelpFlagToCommands(programName_);\n            }\n        }\n        commandCfg->read(commandLine);\n    }\n\n    void enableHelpFlag(const std::string& programName) override\n    {        \n        programName_ = programName + \" \" + info_.name();\n        using NameProvider = typename detail::Format<detail::ConfigAccess<TConfig>::format()>::nameProvider;\n        helpFlag_ = std::make_unique<detail::Flag>(NameProvider::name(\"help\"),\n                                                   std::string{},\n                                                   [this]()->bool&{return helpFlagValue_;},\n                                                   detail::Flag::Type::Exit);\n        helpFlag_->info().addDescription(\"show usage info and exit\");\n    }\n\n    bool isHelpFlagSet() const override\n    {\n        return helpFlagValue_;\n    }\n\n    bool isSubCommand() const override\n    {\n        return type_ == Type::SubCommand;\n    }\n\n    std::string usageInfo() const override\n    {\n        auto& commandCfg = commandGetter_();\n        if (!commandCfg.has_value())\n            return {};\n        return commandCfg->usageInfo(programName_);\n    }\n\n    std::string usageInfoDetailed() const override\n    {\n        auto& commandCfg = commandGetter_();\n        if (!commandCfg.has_value())\n            return {};\n        return commandCfg->usageInfoDetailed(programName_);\n    }\n\n    std::vector<not_null<ICommand*>> commandList() override\n    {\n        auto& commandCfg = commandGetter_();\n        if (!commandCfg.has_value())\n            return {};\n        return detail::ConfigAccess<TConfig>(*commandCfg).commandList();\n    }\n\nprivate:\n    OptionInfo info_;\n    std::function<std::optional<TConfig>&()> commandGetter_;\n    Type type_;\n    std::string programName_;\n    std::unique_ptr<IFlag> helpFlag_;\n    bool helpFlagValue_ = false;\n};\n\ntemplate<typename T, typename TConfig>\nclass CommandCreator{\n    using NameProvider = typename Format<ConfigAccess<TConfig>::format()>::nameProvider;\npublic:\n    CommandCreator(TConfig& cfg,\n                   const std::string& varName,\n                   std::function<std::optional<T>&()> commandGetter,\n                   typename Command<T>::Type type = Command<T>::Type::Normal)\n        : cfg_(cfg)\n    {\n        static_assert (std::is_base_of_v<Config<ConfigAccess<TConfig>::format()>, T>,\n                       \"Command's type must be a subclass of Config<FormatType> and have the same format as its parent config.\");\n        Expects(!varName.empty());        \n        command_ = std::make_unique<Command<T>>(NameProvider::fullName(varName), commandGetter, type);\n    }\n\n    CommandCreator<T, TConfig>& operator<<(const std::string& info)\n    {\n        command_->info().addDescription(info);\n        return *this;\n    }\n\n    CommandCreator<T, TConfig>& operator<<(const Name& customName)\n    {\n        command_->info().resetName(customName.value());\n        return *this;\n    }\n\n    operator std::optional<T>()\n    {\n        ConfigAccess<TConfig>{cfg_}.addCommand(std::move(command_));\n        return std::optional<T>{};\n    }\n\nprivate:\n    std::unique_ptr<Command<T>> command_;\n    TConfig& cfg_;\n};\n\ntemplate <typename T, typename TConfig>\nCommandCreator<T, TConfig> makeCommandCreator(TConfig& cfg,\n                                              const std::string& varName,\n                                              std::function<std::optional<T>&()> commandGetter,\n                                              typename Command<T>::Type type = Command<T>::Type::Normal)\n{\n    return CommandCreator<T, TConfig>{cfg, varName, commandGetter, type};\n}\n\n\n}\n", "meta": {"hexsha": "7730e2fcc9ebed7d0e7ecc56ef7f3f2406bbfb02", "size": 4886, "ext": "h", "lang": "C", "max_stars_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/command.h", "max_stars_repo_name": "GerHobbelt/hypertextcpp", "max_stars_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_stars_repo_licenses": ["MS-PL"], "max_stars_count": 77.0, "max_stars_repo_stars_event_min_datetime": "2021-05-20T18:05:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T21:37:54.000Z", "max_issues_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/command.h", "max_issues_repo_name": "GerHobbelt/hypertextcpp", "max_issues_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_issues_repo_licenses": ["MS-PL"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2021-05-20T22:04:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-21T08:13:28.000Z", "max_forks_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/command.h", "max_forks_repo_name": "GerHobbelt/hypertextcpp", "max_forks_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_forks_repo_licenses": ["MS-PL"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-22T00:36:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-22T00:36:08.000Z", "avg_line_length": 29.7926829268, "max_line_length": 129, "alphanum_fraction": 0.5900532133, "num_tokens": 1054, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.0488577786221749, "lm_q2_score": 0.015424550045154767, "lm_q1q2_score": 0.0007536092514528295}}
{"text": "\ufeff// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n#pragma once\n#include <windows.h>\n\n// Include ABI composition headers for interop with DCOMP surface handle from MediaEngine\n#include <windows.ui.composition.h>\n#include <windows.ui.composition.interop.h>\n\n// Include prior to WinRT Headers\n#include <wil/cppwinrt.h> \n\n// WinRT Headers\n#include <winrt/Windows.Foundation.h>\n#include <winrt/Windows.Foundation.Collections.h>\n#include <winrt/Windows.ApplicationModel.Core.h>\n#include <winrt/Windows.UI.Core.h>\n#include <winrt/Windows.UI.Composition.h>\n#include <winrt/Windows.UI.Input.h>\n#include <winrt/Windows.Media.Protection.h>\n#include <winrt/Windows.Storage.h>\n#include <winrt/Windows.Storage.Streams.h>\n#include <winrt/Windows.Web.Http.Headers.h>\n#include <winrt/Windows.Data.Xml.Dom.h>\n#include <winrt/Windows.Security.Cryptography.h>\n#include <winrt/Windows.ApplicationModel.h>\n\n// Direct3D\n#include <d3d11.h>\n\n// Windows Implementation Library\n#include <wil/com.h>\n#include <wil/resource.h>\n#include <wil/result_macros.h>\n\n// MediaFoundation headers\n#include <mfapi.h>\n#include <mferror.h>\n#include <mfmediaengine.h>\n#include <mfidl.h>\n#include <mfcontentdecryptionmodule.h>\n\n// STL headers\n#include <functional>\n#include <memory>\n#include <string>\n#include <vector>\n#include <tuple>\n#include <array>\n\n// GSL (C++ Guidelines Support Library)\n#include <gsl/span>\n", "meta": {"hexsha": "332f8146884f36f730a58435bea2249f24e3fa25", "size": 1396, "ext": "h", "lang": "C", "max_stars_repo_path": "samples/MediaEngineEMEUWPSample/src/pch.h", "max_stars_repo_name": "microsoft/media-foundation", "max_stars_repo_head_hexsha": "f5a0d6133992514733c42ee2f70c869daf5a75e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 62.0, "max_stars_repo_stars_event_min_datetime": "2020-05-09T01:38:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T21:51:19.000Z", "max_issues_repo_path": "samples/MediaEngineEMEUWPSample/src/pch.h", "max_issues_repo_name": "QPC-database/media-foundation", "max_issues_repo_head_hexsha": "dc81175a3e893c7c58fcbf1a943ac342e39f172c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2020-08-06T06:46:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T12:25:39.000Z", "max_forks_repo_path": "samples/MediaEngineEMEUWPSample/src/pch.h", "max_forks_repo_name": "QPC-database/media-foundation", "max_forks_repo_head_hexsha": "dc81175a3e893c7c58fcbf1a943ac342e39f172c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2020-06-08T17:18:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T09:17:10.000Z", "avg_line_length": 25.8518518519, "max_line_length": 89, "alphanum_fraction": 0.7621776504, "num_tokens": 334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.05419873287859291, "lm_q2_score": 0.013848609477867781, "lm_q1q2_score": 0.000750577085830906}}
{"text": "#pragma once\n\n#include <gsl/span>\n\nnamespace std {\nusing gsl::span;\n}  // namespace std\n", "meta": {"hexsha": "017ff56b5374c87a700df055eb9bcdc7583ace4c", "size": 88, "ext": "h", "lang": "C", "max_stars_repo_path": "src/base/std_span_polyfill.h", "max_stars_repo_name": "ut-osa/nightcore", "max_stars_repo_head_hexsha": "f041db04bd369d9bd7a617b48892338fc11c090c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2021-01-18T17:19:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:48:49.000Z", "max_issues_repo_path": "src/base/std_span_polyfill.h", "max_issues_repo_name": "ut-osa/nightcore", "max_issues_repo_head_hexsha": "f041db04bd369d9bd7a617b48892338fc11c090c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2021-04-16T05:08:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-15T17:41:01.000Z", "max_forks_repo_path": "src/base/std_span_polyfill.h", "max_forks_repo_name": "ut-osa/nightcore", "max_forks_repo_head_hexsha": "f041db04bd369d9bd7a617b48892338fc11c090c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2021-01-28T02:16:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-23T00:37:50.000Z", "avg_line_length": 11.0, "max_line_length": 19, "alphanum_fraction": 0.6818181818, "num_tokens": 23, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.03067580082450811, "lm_q2_score": 0.024423090764195313, "lm_q1q2_score": 0.000749197867801339}}
{"text": "/*\n *     Copyright 2021-Present Couchbase, Inc.\n *\n *   Use of this software is governed by the Business Source License included\n *   in the file licenses/BSL-Couchbase.txt.  As of the Change Date specified\n *   in that file, in accordance with the Business Source License, use of this\n *   software will be governed by the Apache License, Version 2.0, included in\n *   the file licenses/APL2.txt.\n */\n\n#pragma once\n\n#include <mcbp/protocol/status.h>\n#include <cstdint>\n#include <functional>\n#include <gsl/gsl>\n\nstruct EngineIface;\n\n/**\n * Callback for any function producing stats.\n *\n * @param key the stat's key\n * @param value the stat's value in an ascii form (e.g. text form of a number)\n * @param cookie magic callback cookie\n */\nusing AddStatFn = std::function<void(std::string_view key,\n                                     std::string_view value,\n                                     gsl::not_null<const void*> cookie)>;\n\n/**\n * Callback for adding a response backet\n * @param key The key to put in the response\n * @param extras The data to put in the extended field in the response\n * @param body The data body\n * @param datatype This is currently not used and should be set to 0\n * @param status The status code of the return packet (see in protocol_binary\n *               for the legal values)\n * @param cas The cas to put in the return packet\n * @param cookie The cookie provided by the frontend\n * @return true if return message was successfully created, false if an\n *              error occured that prevented the message from being sent\n */\nusing AddResponseFn = std::function<bool(std::string_view key,\n                                         std::string_view extras,\n                                         std::string_view body,\n                                         uint8_t datatype,\n                                         cb::mcbp::Status status,\n                                         uint64_t cas,\n                                         const void* cookie)>;\n", "meta": {"hexsha": "de1a2e0a56efe0b43e794f82f853657dfd2fac3b", "size": 1997, "ext": "h", "lang": "C", "max_stars_repo_path": "include/memcached/engine_common.h", "max_stars_repo_name": "BenHuddleston/kv_engine", "max_stars_repo_head_hexsha": "78123c9aa2c2feb24b7c31eecc862bf2ed6325e4", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/memcached/engine_common.h", "max_issues_repo_name": "BenHuddleston/kv_engine", "max_issues_repo_head_hexsha": "78123c9aa2c2feb24b7c31eecc862bf2ed6325e4", "max_issues_repo_licenses": ["MIT", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/memcached/engine_common.h", "max_forks_repo_name": "BenHuddleston/kv_engine", "max_forks_repo_head_hexsha": "78123c9aa2c2feb24b7c31eecc862bf2ed6325e4", "max_forks_repo_licenses": ["MIT", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.1568627451, "max_line_length": 78, "alphanum_fraction": 0.6084126189, "num_tokens": 414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.039638841369975954, "lm_q2_score": 0.018833132024399322, "lm_q1q2_score": 0.0007465235328149788}}
{"text": "#ifndef CONTROLLERS_IMAGEOPERATIONACTIONCONTROLLER_H\n#define CONTROLLERS_IMAGEOPERATIONACTIONCONTROLLER_H\n\n#include <QObject>\n\n#include \"s3d/cv/image_operation/image_operation.h\"\n\n#include <QAction>\n\n#include <gsl/gsl>\n\nclass ImageOperationActionController : public QObject {\n  Q_OBJECT\n\npublic:\n  ImageOperationActionController(gsl::not_null<QAction*> action,\n                                 gsl::not_null<s3d::image_operation::ImageOperation*> imageOperation);\n\n  virtual void onActionTriggered() = 0;\n\nsignals:\n  void imageOperationTriggered();\n\nprotected:\n  QAction* m_action;\n  s3d::image_operation::ImageOperation* m_imageOperation;\n};\n\n#endif //CONTROLLERS_IMAGEOPERATIONACTIONCONTROLLER_H\n", "meta": {"hexsha": "4e067ba15197c51f9b43a224cda047756bc8bf5e", "size": 698, "ext": "h", "lang": "C", "max_stars_repo_path": "src/apps/S3DAnalyzer/controllers/imageoperationactioncontroller.h", "max_stars_repo_name": "hugbed/OpenS3D", "max_stars_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-16T16:38:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-20T03:23:15.000Z", "max_issues_repo_path": "src/apps/S3DAnalyzer/controllers/imageoperationactioncontroller.h", "max_issues_repo_name": "hugbed/OpenS3D", "max_issues_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 40.0, "max_issues_repo_issues_event_min_datetime": "2017-04-12T17:24:44.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-21T18:41:23.000Z", "max_forks_repo_path": "src/apps/S3DAnalyzer/controllers/imageoperationactioncontroller.h", "max_forks_repo_name": "hugbed/OpenS3D", "max_forks_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-07-13T21:51:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-18T16:22:03.000Z", "avg_line_length": 23.2666666667, "max_line_length": 102, "alphanum_fraction": 0.7750716332, "num_tokens": 159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.04535257797368024, "lm_q2_score": 0.016403033808393374, "lm_q1q2_score": 0.0007439198698000737}}
{"text": "/*\n *  Copyright (C) 2021 FISCO BCOS.\n *  SPDX-License-Identifier: Apache-2.0\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n * @brief interface of Table\n * @file Table.h\n * @author: xingqiangbai\n * @date: 2021-04-07\n */\n#pragma once\n\n#include \"Common.h\"\n#include \"StorageInterface.h\"\n#include <future>\n#include <gsl/span>\n\nnamespace bcos\n{\nnamespace storage\n{\nclass Table\n{\npublic:\n    Table(StorageInterface* _db, TableInfo::ConstPtr _tableInfo)\n      : m_storage(_db), m_tableInfo(std::move(_tableInfo))\n    {}\n\n    Table(const Table&) = default;\n    Table(Table&&) = default;\n    Table& operator=(const Table&) = default;\n    Table& operator=(Table&&) = default;\n    ~Table() {}\n\n    std::optional<Entry> getRow(std::string_view _key);\n    std::vector<std::optional<Entry>> getRows(\n        const std::variant<const gsl::span<std::string_view const>,\n            const gsl::span<std::string const>>& _keys);\n    std::vector<std::string> getPrimaryKeys(const std::optional<const Condition>& _condition);\n\n    void setRow(std::string_view _key, Entry _entry);\n\n    void asyncGetPrimaryKeys(std::optional<const Condition> const& _condition,\n        std::function<void(Error::UniquePtr, std::vector<std::string>)> _callback) noexcept;\n\n    void asyncGetRow(std::string_view _key,\n        std::function<void(Error::UniquePtr, std::optional<Entry>)> _callback) noexcept;\n\n    void asyncGetRows(const std::variant<const gsl::span<std::string_view const>,\n                          const gsl::span<std::string const>>& _keys,\n        std::function<void(Error::UniquePtr, std::vector<std::optional<Entry>>)>\n            _callback) noexcept;\n\n    void asyncSetRow(\n        std::string_view key, Entry entry, std::function<void(Error::UniquePtr)> callback) noexcept;\n\n    TableInfo::ConstPtr tableInfo() const { return m_tableInfo; }\n    Entry newEntry() { return Entry(m_tableInfo); }\n    Entry newDeletedEntry()\n    {\n        auto deletedEntry = newEntry();\n        deletedEntry.setStatus(Entry::DELETED);\n        return deletedEntry;\n    }\n\nprotected:\n    StorageInterface* m_storage;\n    TableInfo::ConstPtr m_tableInfo;\n};\n\n}  // namespace storage\n}  // namespace bcos\n", "meta": {"hexsha": "9e066cf6b5634cb08ff26846711c60c2faf7fcfe", "size": 2684, "ext": "h", "lang": "C", "max_stars_repo_path": "bcos-framework/interfaces/storage/Table.h", "max_stars_repo_name": "chuwen95/FISCO-BCOS", "max_stars_repo_head_hexsha": "e9cc29151c90dd1f4634f4d52ba773bb216700ac", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-06T10:46:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T10:46:12.000Z", "max_issues_repo_path": "bcos-framework/interfaces/storage/Table.h", "max_issues_repo_name": "chuwen95/FISCO-BCOS", "max_issues_repo_head_hexsha": "e9cc29151c90dd1f4634f4d52ba773bb216700ac", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bcos-framework/interfaces/storage/Table.h", "max_forks_repo_name": "chuwen95/FISCO-BCOS", "max_forks_repo_head_hexsha": "e9cc29151c90dd1f4634f4d52ba773bb216700ac", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3373493976, "max_line_length": 100, "alphanum_fraction": 0.6859165425, "num_tokens": 656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.048136769751103675, "lm_q2_score": 0.015424551120072542, "lm_q1q2_score": 0.0007424880657810602}}
{"text": "/***\n * Copyright 2019 The Katla Authors\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#ifndef KATLA_PIPE_H\n#define KATLA_PIPE_H\n\n#include \"katla/core/core.h\"\n\n#include <gsl/span>\n\n#include <optional>\n\nnamespace outcome = OUTCOME_V2_NAMESPACE;\n\nnamespace katla {\n\nclass PosixPipe {\npublic:\n    PosixPipe();\n    ~PosixPipe();\n\n    outcome::result<void> open();\n\n    outcome::result<ssize_t> read(gsl::span<std::byte>& buffer);\n    outcome::result<ssize_t> write(gsl::span<std::byte>& buffer);\n\n    outcome::result<void> redirectToRead(int fd_src);\n    outcome::result<void> redirectToWrite(int fd_src);\n\n    outcome::result<void> close();\n    outcome::result<void> closeRead();\n    outcome::result<void> closeWrite();\nprivate:\n    int _fd[2];\n};\n\n}\n\n#endif // KATLA_PIPE_H\n", "meta": {"hexsha": "b6f7d09419aa4d51b1b84da9febf33c60326312b", "size": 1288, "ext": "h", "lang": "C", "max_stars_repo_path": "core/posix-pipe.h", "max_stars_repo_name": "plok/katla", "max_stars_repo_head_hexsha": "aaaeb8baf041bba7259275beefc71c8452a16223", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "core/posix-pipe.h", "max_issues_repo_name": "plok/katla", "max_issues_repo_head_hexsha": "aaaeb8baf041bba7259275beefc71c8452a16223", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-03-25T14:33:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-16T14:21:56.000Z", "max_forks_repo_path": "core/posix-pipe.h", "max_forks_repo_name": "plok/katla", "max_forks_repo_head_hexsha": "aaaeb8baf041bba7259275beefc71c8452a16223", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-26T13:32:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-26T13:32:36.000Z", "avg_line_length": 24.3018867925, "max_line_length": 75, "alphanum_fraction": 0.7104037267, "num_tokens": 313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.025957355690778516, "lm_q2_score": 0.02843603067768865, "lm_q1q2_score": 0.0007381241627346539}}
{"text": "#pragma once\n\n#include <memory>\n#include <gsl\\gsl>\n#include \"RTTI.h\"\n\nnamespace Library\n{\n\tclass Game;\n\n\tclass AbstractContentTypeReader : public RTTI\n\t{\n\t\tRTTI_DECLARATIONS(AbstractContentTypeReader, RTTI)\n\n\tpublic:\t\t\n\t\tAbstractContentTypeReader(const AbstractContentTypeReader&) = default;\n\t\tAbstractContentTypeReader& operator=(const AbstractContentTypeReader&) = default;\n\t\tAbstractContentTypeReader(AbstractContentTypeReader&&) = default;\n\t\tAbstractContentTypeReader& operator=(AbstractContentTypeReader&&) = default;\n\t\tvirtual ~AbstractContentTypeReader() = default;\n\n\t\tstd::uint64_t TargetTypeId() const;\n\t\tvirtual std::shared_ptr<RTTI> Read(const std::wstring& assetName) = 0;\n\n\tprotected:\n\t\tAbstractContentTypeReader(Game& game, const std::uint64_t targetTypeId);\n\n\t\tgsl::not_null<Game*> mGame;\n\t\tconst std::uint64_t mTargetTypeId;\n\t};\n\n\ttemplate <typename T>\n\tclass ContentTypeReader : public AbstractContentTypeReader\n\t{\n\tpublic:\t\t\n\t\tContentTypeReader(const ContentTypeReader&) = default;\n\t\tContentTypeReader& operator=(const ContentTypeReader&) = default;\n\t\tContentTypeReader(ContentTypeReader&&) = default;\n\t\tContentTypeReader& operator=(ContentTypeReader&&) = default;\n\t\tvirtual ~ContentTypeReader() = default;\n\n\t\tvirtual std::shared_ptr<RTTI> Read(const std::wstring& assetName) override;\n\n\tprotected:\n\t\tContentTypeReader(Game& game, const std::uint64_t targetTypeId);\n\n\t\tvirtual std::shared_ptr<T> _Read(const std::wstring& assetName) = 0;\n\t};\n}\n\n#include \"ContentTypeReader.inl\"", "meta": {"hexsha": "83628ddb6bdac6217a24c4911a2e4c66ae12cefe", "size": 1495, "ext": "h", "lang": "C", "max_stars_repo_path": "source/Library.Shared/ContentTypeReader.h", "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/Library.Shared/ContentTypeReader.h", "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/Library.Shared/ContentTypeReader.h", "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3137254902, "max_line_length": 83, "alphanum_fraction": 0.7725752508, "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.048857784161913866, "lm_q2_score": 0.014728610606109385, "lm_q1q2_score": 0.0007196072779981677}}
{"text": "#ifndef NETWORK_UDP_ASYNCRECEIVER_H\n#define NETWORK_UDP_ASYNCRECEIVER_H\n\n\n/* Base class for implementing an asynchronous UDP receiver. A derived class must implement\n   handle_receive which gets passed a view of the received data. The function start() will\n   block and should be called in its own thread. */\n\n\n#include <cstdint>\n#include <array>\n#include <string>\n\n#include <gsl/gsl>\n#include <asio.hpp>\n\n\nnamespace network::udp {\n\n\nclass Async_receiver\n{\npublic:\n  Async_receiver() : socket_{io_service_} {}\n  virtual ~Async_receiver();\n  Async_receiver(const Async_receiver&) = delete;\n  Async_receiver& operator=(const Async_receiver&) = delete;\n\n  void start(const std::string& ip, std::uint16_t port);\n  void stop();\n  bool is_running() const { return socket_.is_open(); }\n\nprotected:\n  virtual void handle_receive(gsl::span<std::uint8_t> buffer) = 0;\n\nprivate:\n  void start_async_receive();\n\n  asio::io_service io_service_;\n  asio::ip::udp::socket socket_;\n  std::array<std::uint8_t, 128> buffer_;\n};\n\n\n}  // namespace network::udp\n\n\n#endif  // NETWORK_UDP_ASYNCRECEIVER_H\n", "meta": {"hexsha": "e28adb21c1274b214e4715e5e3882e1d170537bf", "size": 1080, "ext": "h", "lang": "C", "max_stars_repo_path": "src/network/udpasyncreceiver.h", "max_stars_repo_name": "mwkpe/tincan", "max_stars_repo_head_hexsha": "7c47ea7fa7f43163f69c94f10dd39b56e4e95256", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2018-06-09T10:22:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T08:03:40.000Z", "max_issues_repo_path": "src/network/udpasyncreceiver.h", "max_issues_repo_name": "jwkpeter/tincan", "max_issues_repo_head_hexsha": "7c47ea7fa7f43163f69c94f10dd39b56e4e95256", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/network/udpasyncreceiver.h", "max_forks_repo_name": "jwkpeter/tincan", "max_forks_repo_head_hexsha": "7c47ea7fa7f43163f69c94f10dd39b56e4e95256", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-11-23T11:05:16.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-30T07:57:19.000Z", "avg_line_length": 22.0408163265, "max_line_length": 91, "alphanum_fraction": 0.7388888889, "num_tokens": 269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.02800752141729973, "lm_q2_score": 0.025565214294481865, "lm_q1q2_score": 0.0007160182868905581}}
{"text": "#include \"ui/detail/ui_helpers_native.h\"\n#include <gsl/gsl>\nstruct Tcl_Interp;\n\nnamespace cws80 {\n\nclass TkUI : public NativeUI {\npublic:\n    std::string choose_file(gsl::span<const FileChooserFilter> filters, const std::string &directory, const std::string &title, FileChooserMode mode) override;\n    cxx::optional<std::string> edit_line(const std::string &title, const std::string &initial_value) override;\n    uint select_by_menu(gsl::span<const std::string> choices, uint initial_selection) override;\n\nprivate:\n    static Tcl_Interp *create_tk_interp();\n    static std::string quote(gsl::cstring_span str);\n};\n\n}  // namespace cws80\n", "meta": {"hexsha": "cf622d674424d715a99afab86243632c6eaa4aba", "size": 637, "ext": "h", "lang": "C", "max_stars_repo_path": "sources/ui/detail/ui_helpers_tk.h", "max_stars_repo_name": "jpcima/cws80", "max_stars_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-05-20T19:27:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-03T04:21:53.000Z", "max_issues_repo_path": "sources/ui/detail/ui_helpers_tk.h", "max_issues_repo_name": "jpcima/cws80", "max_issues_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-05-21T12:56:22.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-23T21:33:33.000Z", "max_forks_repo_path": "sources/ui/detail/ui_helpers_tk.h", "max_forks_repo_name": "jpcima/cws80", "max_forks_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5263157895, "max_line_length": 159, "alphanum_fraction": 0.7519623234, "num_tokens": 159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.034100426693928106, "lm_q2_score": 0.020964242385570275, "lm_q1q2_score": 0.0007148896106628797}}
{"text": "/* Copyright 2019-2021 Canaan Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n#pragma once\n#include <gsl/gsl-lite.hpp>\n#include <type_traits>\n\n#if defined(_MSC_VER)\n#ifdef NNCASE_DLL\n#define NNCASE_API __declspec(dllexport)\n#elif defined(NNCASE_SHARED_LIBS)\n#define NNCASE_API __declspec(dllimport)\n#else\n#define NNCASE_API\n#endif\n#else\n#define NNCASE_API\n#endif\n\n#if defined(_MSC_VER)\n#define NNCASE_UNREACHABLE() __assume(0)\n#else\n#define NNCASE_UNREACHABLE() __builtin_unreachable()\n#endif\n\n#if gsl_CPP17_OR_GREATER\n#define NNCASE_INLINE_VAR inline\n#define NNCASE_UNUSED [[maybe_unused]]\nnamespace nncase\n{\ntemplate <class Callable, class... Args>\nusing invoke_result_t = std::invoke_result_t<Callable, Args...>;\n}\n#else\n#define NNCASE_INLINE_VAR\n#if defined(_MSC_VER)\n#define NNCASE_UNUSED\n#else\n#define NNCASE_UNUSED __attribute__((unused))\n#endif\nnamespace nncase\n{\ntemplate <class Callable, class... Args>\nusing invoke_result_t = std::result_of_t<Callable(Args...)>;\n}\n#endif\n\n#define NNCASE_LITTLE_ENDIAN 1\n\n#define NNCASE_HAVE_STD_BYTE gsl_CPP17_OR_GREATER\n#define NNCASE_NODISCARD gsl_NODISCARD\n#define NNCASE_NORETURN gsl_NORETURN\n\n#define BEGIN_NS_NNCASE_RUNTIME \\\n    namespace nncase            \\\n    {                           \\\n        namespace runtime       \\\n        {\n#define END_NS_NNCASE_RUNTIME \\\n    }                         \\\n    }\n\n#define BEGIN_NS_NNCASE_RT_MODULE(MODULE) \\\n    namespace nncase                      \\\n    {                                     \\\n        namespace runtime                 \\\n        {                                 \\\n            namespace MODULE              \\\n            {\n\n#define END_NS_NNCASE_RT_MODULE \\\n    }                           \\\n    }                           \\\n    }\n\n#define BEGIN_NS_NNCASE_KERNELS \\\n    namespace nncase            \\\n    {                           \\\n        namespace kernels       \\\n        {\n\n#define END_NS_NNCASE_KERNELS \\\n    }                         \\\n    }\n\n#ifndef DEFINE_ENUM_BITMASK_OPERATORS\n#define DEFINE_ENUM_BITMASK_OPERATORS(ENUMTYPE) gsl_DEFINE_ENUM_BITMASK_OPERATORS(ENUMTYPE)\n#endif\n\nnamespace nncase\n{\nstruct default_init_t\n{\n};\n\nNNCASE_INLINE_VAR constexpr default_init_t default_init {};\n}\n", "meta": {"hexsha": "ca9339c54871e17a54cf3c9489ce6850b84512bd", "size": 2732, "ext": "h", "lang": "C", "max_stars_repo_path": "include/nncase/runtime/compiler_defs.h", "max_stars_repo_name": "annosoo/nncase", "max_stars_repo_head_hexsha": "898bd4075a0f246bca7b62a912051af3d890aff4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/nncase/runtime/compiler_defs.h", "max_issues_repo_name": "annosoo/nncase", "max_issues_repo_head_hexsha": "898bd4075a0f246bca7b62a912051af3d890aff4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-05-27T06:08:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-02T10:39:35.000Z", "max_forks_repo_path": "include/nncase/runtime/compiler_defs.h", "max_forks_repo_name": "annosoo/nncase", "max_forks_repo_head_hexsha": "898bd4075a0f246bca7b62a912051af3d890aff4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0642201835, "max_line_length": 91, "alphanum_fraction": 0.6573938507, "num_tokens": 622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.03514484741138068, "lm_q2_score": 0.020332354715430333, "lm_q1q2_score": 0.0007145775039878655}}
{"text": "/*\n *     Copyright 2021-Present Couchbase, Inc.\n *\n *   Use of this software is governed by the Business Source License included\n *   in the file licenses/BSL-Couchbase.txt.  As of the Change Date specified\n *   in that file, in accordance with the Business Source License, use of this\n *   software will be governed by the Apache License, Version 2.0, included in\n *   the file licenses/APL2.txt.\n */\n\n#pragma once\n\n#include <gsl/gsl-lite.hpp>\n#include <nlohmann/json.hpp>\n\n// Used by most unit test files.\n#include <folly/portability/GTest.h>\n\n// Used throughout the codebase\n#include <folly/SharedMutex.h>\n#include <folly/Synchronized.h>\n\n// MB-46844:\n// Included by collections/vbucket_manifest.h, which in turn included\n// by 50+ other files.\n// Consider changing collections/vbucket_manifest.h to use pimpl for\n// Manifest::map which would avoid the need to include F14Map.h.\n#include <folly/container/F14Map.h>\n\n#include <map>\n#include <string>\n", "meta": {"hexsha": "274bcb3ddfe9a3e9885191a2169f15516c2f72c2", "size": 953, "ext": "h", "lang": "C", "max_stars_repo_path": "precompiled_headers.h", "max_stars_repo_name": "nawazish-couchbase/kv_engine", "max_stars_repo_head_hexsha": "132f1bb04c9212bcac9e401d069aeee5f63ff1cd", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": 104.0, "max_stars_repo_stars_event_min_datetime": "2017-05-22T20:41:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T00:18:34.000Z", "max_issues_repo_path": "precompiled_headers.h", "max_issues_repo_name": "nawazish-couchbase/kv_engine", "max_issues_repo_head_hexsha": "132f1bb04c9212bcac9e401d069aeee5f63ff1cd", "max_issues_repo_licenses": ["MIT", "BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-11-14T08:12:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T11:14:17.000Z", "max_forks_repo_path": "precompiled_headers.h", "max_forks_repo_name": "nawazish-couchbase/kv_engine", "max_forks_repo_head_hexsha": "132f1bb04c9212bcac9e401d069aeee5f63ff1cd", "max_forks_repo_licenses": ["MIT", "BSD-3-Clause"], "max_forks_count": 71.0, "max_forks_repo_forks_event_min_datetime": "2017-05-22T20:41:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T10:34:32.000Z", "avg_line_length": 29.78125, "max_line_length": 78, "alphanum_fraction": 0.7387198321, "num_tokens": 239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.052618954833365504, "lm_q2_score": 0.013428255877074, "lm_q1q2_score": 0.0007065807894866317}}
{"text": "#pragma once\n\n#include <gsl/gsl>\n#include <Metal/Metal.h>\n\nnamespace Halley {\n\tclass MetalVideo;\n\n\tclass MetalBuffer {\n\tpublic:\n\t\tenum class Type\n\t\t{\n\t\t\tVertex,\n\t\t\tIndex,\n\t\t\tConstant\n\t\t};\n\n\t\tMetalBuffer(MetalVideo& video, Type type, size_t initialSize = 0);\n\t\tMetalBuffer(MetalBuffer&& other) noexcept;\n\t\t~MetalBuffer();\n\n\t\tMetalBuffer(const MetalBuffer& other) = delete;\n\n\t\tMetalBuffer& operator=(const MetalBuffer& other) = delete;\n\t\tMetalBuffer& operator=(MetalBuffer&& other) = delete;\n\n\t\tvoid setData(gsl::span<const gsl::byte> data);\n\t\tvoid bindVertex(id<MTLRenderCommandEncoder> encoder, int bindPoint);\n\t\tvoid bindFragment(id<MTLRenderCommandEncoder> encoder, int bindPoint);\n\t\tid<MTLBuffer> getBuffer();\n\n\tprivate:\n\t\tMetalVideo& video;\n\t\tType type;\n\t\tid<MTLBuffer> buffer = nil;\n\t};\n}\n", "meta": {"hexsha": "7b7383327c5f962084729427b0a08bf89c8131b4", "size": 794, "ext": "h", "lang": "C", "max_stars_repo_path": "src/plugins/metal/src/metal_buffer.h", "max_stars_repo_name": "code-disaster/halley", "max_stars_repo_head_hexsha": "5c85c889b76c69c6bdef6f4801c6aba282b7af80", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3262.0, "max_stars_repo_stars_event_min_datetime": "2016-04-10T15:24:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:47:08.000Z", "max_issues_repo_path": "src/plugins/metal/src/metal_buffer.h", "max_issues_repo_name": "code-disaster/halley", "max_issues_repo_head_hexsha": "5c85c889b76c69c6bdef6f4801c6aba282b7af80", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 53.0, "max_issues_repo_issues_event_min_datetime": "2016-10-09T16:25:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-10T13:52:37.000Z", "max_forks_repo_path": "src/plugins/metal/src/metal_buffer.h", "max_forks_repo_name": "code-disaster/halley", "max_forks_repo_head_hexsha": "5c85c889b76c69c6bdef6f4801c6aba282b7af80", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 193.0, "max_forks_repo_forks_event_min_datetime": "2017-10-23T06:08:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T12:59:58.000Z", "avg_line_length": 20.8947368421, "max_line_length": 72, "alphanum_fraction": 0.717884131, "num_tokens": 224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.05749328203023058, "lm_q2_score": 0.012241273321129092, "lm_q1q2_score": 0.0007037909794608123}}
{"text": "#pragma once\n#include \"Common.h\"\n\n#include <stdexcept>\n#include <gsl/gsl>\n\nnamespace winlogo::utils {\n\n/**\n * This exception is raised when failing to run VirtualProtect.\n */\nclass VirtualProtectFailedError : public std::runtime_error {\npublic:\n    VirtualProtectFailedError() noexcept;\n};\n\n/**\n * This is a RAII class for temporarily changing the protection of a memory region.\n */\nclass MemoryProtectionGuard {\npublic:\n    MemoryProtectionGuard(void* startAddress, size_t size, DWORD protection);\n\n    NO_COPY(MemoryProtectionGuard);\n    NO_MOVE(MemoryProtectionGuard);\n\n    ~MemoryProtectionGuard() noexcept;\n\nprivate:\n    /// The start address of the memory region for which the protection should be changed.\n    void* m_startAddress;\n    /// The size of the memory region for which the protection should be changed.\n    size_t m_size;\n    /// The old protection to be restored in the end.\n    DWORD m_oldProtection;\n\n    /**\n     * Run VirtualProtect for the stored address and store the previous protection in\n     * m_oldProtection.\n     */\n    bool doVirtualProtect(DWORD protection) noexcept;\n};\n\n}  // namespace winlogo::utils\n", "meta": {"hexsha": "39e6ee47a698c2e60514f03f4ffdaabfe23bd9b3", "size": 1137, "ext": "h", "lang": "C", "max_stars_repo_path": "winlogo_core/MemoryProtectionGuard.h", "max_stars_repo_name": "shsh999/WinLogo", "max_stars_repo_head_hexsha": "9ad51469e3ed4bb593303d4d7919c484a3be092e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2021-09-04T22:10:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T07:18:03.000Z", "max_issues_repo_path": "winlogo_core/MemoryProtectionGuard.h", "max_issues_repo_name": "shsh999/WinLogo", "max_issues_repo_head_hexsha": "9ad51469e3ed4bb593303d4d7919c484a3be092e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-23T01:01:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-29T12:13:05.000Z", "max_forks_repo_path": "winlogo_core/MemoryProtectionGuard.h", "max_forks_repo_name": "shsh999/WinLogo", "max_forks_repo_head_hexsha": "9ad51469e3ed4bb593303d4d7919c484a3be092e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-20T12:06:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T12:06:02.000Z", "avg_line_length": 25.2666666667, "max_line_length": 90, "alphanum_fraction": 0.72823219, "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.03622005170359761, "lm_q2_score": 0.019419349494799076, "lm_q1q2_score": 0.0007033698427518545}}
{"text": "#ifndef XYCO_RUNTIME_ASYNC_H_\n#define XYCO_RUNTIME_ASYNC_H_\n\n#include <gsl/pointers>\n\n#include \"future.h\"\n#include \"poll.h\"\n#include \"runtime.h\"\n\nnamespace xyco::runtime {\ntemplate <typename Return>\nclass AsyncFuture : public Future<Return> {\n public:\n  [[nodiscard]] auto poll(Handle<void> self) -> Poll<Return> override {\n    if (!ready_) {\n      ready_ = true;\n      auto res = RuntimeCtx::get_ctx()->blocking_handle()->Register(event_);\n      return Pending();\n    }\n\n    gsl::owner<Return *> ret = gsl::owner<Return *>(\n        std::get<AsyncFutureExtra>(event_.extra_).after_extra_);\n    auto result = std::move(*ret);\n    delete ret;\n\n    return Ready<Return>{std::move(result)};\n  }\n\n  template <typename Fn>\n  explicit AsyncFuture(Fn &&f) requires(std::is_invocable_r_v<Return, Fn>)\n      : Future<Return>(nullptr),\n        f_([&]() {\n          auto extra = AsyncFutureExtra{.after_extra_ = new Return(f())};\n          event_.extra_ = extra;\n        }),\n        ready_(false),\n        event_(xyco::runtime::Event{\n            .future_ = this, .extra_ = AsyncFutureExtra{.before_extra_ = f_}}) {\n  }\n\n  AsyncFuture(const AsyncFuture<Return> &) = delete;\n\n  AsyncFuture(AsyncFuture<Return> &&) = delete;\n\n  auto operator=(const AsyncFuture<Return> &) -> AsyncFuture<Return> & = delete;\n\n  auto operator=(AsyncFuture<Return> &&) -> AsyncFuture<Return> & = delete;\n\n  ~AsyncFuture() = default;\n\n private:\n  bool ready_;\n  std::function<void()> f_;\n  Event event_;\n};\n}  // namespace xyco::runtime\n\n#endif  // XYCO_RUNTIME_ASYNC_H_", "meta": {"hexsha": "492d4925fe29c4582914cf97a162764f8fe845a2", "size": 1535, "ext": "h", "lang": "C", "max_stars_repo_path": "src/runtime/async_future.h", "max_stars_repo_name": "ddxy18/xyco", "max_stars_repo_head_hexsha": "7682652f17b82e2370fa7af17635c5d0c470efe0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/runtime/async_future.h", "max_issues_repo_name": "ddxy18/xyco", "max_issues_repo_head_hexsha": "7682652f17b82e2370fa7af17635c5d0c470efe0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2021-10-30T06:10:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-18T06:16:15.000Z", "max_forks_repo_path": "src/runtime/async_future.h", "max_forks_repo_name": "ddxy18/xyco", "max_forks_repo_head_hexsha": "7682652f17b82e2370fa7af17635c5d0c470efe0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4655172414, "max_line_length": 80, "alphanum_fraction": 0.6488599349, "num_tokens": 399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.03410042178584543, "lm_q2_score": 0.020332354158901302, "lm_q1q2_score": 0.0006933418527177229}}
{"text": "#pragma once\n\n#include <gsl/string_span.h>\n\nusing zstr = gsl::zstring<>;\nusing czstr = gsl::czstring<>;\nusing zwstr = gsl::wzstring<>;\nusing czwstr = gsl::cwzstring<>;\n", "meta": {"hexsha": "a9e9e57120d79bec480f78b42dbcf7e3a351b899", "size": 168, "ext": "h", "lang": "C", "max_stars_repo_path": "StormWebrtc/External/sb/cstr.h", "max_stars_repo_name": "lcmftianci/licodeanalysis", "max_stars_repo_head_hexsha": "62e2722eba1b75ef82f7c1328585873d08bb41cc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-17T14:01:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-24T14:29:45.000Z", "max_issues_repo_path": "StormWebrtc/External/sb/cstr.h", "max_issues_repo_name": "lcmftianci/licodeanalysis", "max_issues_repo_head_hexsha": "62e2722eba1b75ef82f7c1328585873d08bb41cc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "StormWebrtc/External/sb/cstr.h", "max_forks_repo_name": "lcmftianci/licodeanalysis", "max_forks_repo_head_hexsha": "62e2722eba1b75ef82f7c1328585873d08bb41cc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-08-28T14:37:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-17T16:46:32.000Z", "avg_line_length": 18.6666666667, "max_line_length": 32, "alphanum_fraction": 0.6904761905, "num_tokens": 54, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.04146227152697139, "lm_q2_score": 0.016657042083865044, "lm_q1q2_score": 0.0006906388017174018}}
{"text": "#include <gsl/gsl>\n\n#include <functional>\n#include <mutex>\n#include <condition_variable>\n#include <future>\n\n#include <thread>\n\nnamespace lom {\n\nusing executor_t = void (*)(std::function<void()>);\nauto default_executor_impl = [](std::function<void()> f) {\n    std::thread(std::move(f)).detach();\n};\n\nextern executor_t g_default_executor;\n\n//\n//\n/**\n * used to make the library header only. You'll need to add the following in 1 file in an app to use the continuation feature\n * ```\n * #define LOM_FUTURE_IMPLEMENT\n * #include \"lom/future.h\"\n * ```\n */\n#ifdef LOM_FUTURE_IMPLEMENT\nexecutor_t g_default_executor = default_executor_impl;\n#endif\n\ntemplate<class TYPE>\nclass state : public std::enable_shared_from_this<state<TYPE>> {\n    union {\n        TYPE value_;\n        std::exception_ptr exception_;\n    };\n\n    enum {\n        NONE,\n        HAS_VALUE,\n        HAS_EXCEPTION,\n    } status_{NONE};\n\n    mutable std::mutex mutex_;\n    mutable std::condition_variable cv_;\n    std::function<void(std::shared_ptr<state>)> continuation_;\n\n\npublic:\n    void reset() {\n        switch (status_) {\n            case NONE:\n                break;\n            case HAS_VALUE:\n                value_.TYPE::~TYPE();\n                break;\n            case HAS_EXCEPTION:\n                exception_.std::exception_ptr::~exception_ptr();\n                break;\n        }\n\n        status_ = NONE;\n    }\n\n    // for make_ready_future\n    template<class ...ARGS>\n    state(ARGS &&...args) {\n        status_ = HAS_VALUE;\n        new(&value_) TYPE(std::forward<ARGS>(args)...);\n    }\n\n    state() {}\n\n    ~state() {\n        reset();\n    }\n\n    template<class ...ARGS>\n    void set_value(ARGS &&...args) {\n        if (status_ != NONE)\n            throw std::future_error{std::future_errc::promise_already_satisfied};\n\n        {\n            std::lock_guard<std::mutex> lock(mutex_);\n            status_ = HAS_VALUE;\n            new(&value_) TYPE(std::forward<ARGS>(args)...);\n        }\n        cv_.notify_one();\n\n        if (continuation_) {\n            continuation_(this->shared_from_this());\n        }\n    }\n\n    void set_exception(std::exception_ptr p) {\n        if (status_ != NONE)\n            throw std::future_error{std::future_errc::promise_already_satisfied};\n\n        {\n            std::lock_guard<std::mutex> lock(mutex_);\n            status_ = HAS_EXCEPTION;\n            new(&exception_) std::exception_ptr(p);\n        }\n        cv_.notify_one();\n\n        if (continuation_)\n            continuation_(this->shared_from_this());\n    }\n\n    TYPE get() {\n        std::unique_lock<decltype(mutex_)> lock{mutex_};\n\n        cv_.wait(lock, [this]() {\n            return this->status_ != NONE;\n        });\n\n        if (status_ == HAS_EXCEPTION)\n            std::rethrow_exception(exception_);\n\n        return std::move(value_);\n    }\n\n    std::future_status wait() const {\n        std::unique_lock<decltype(mutex_)> lock{mutex_};\n\n        cv_.wait(lock, [this]() {\n            return this->status_ != NONE;\n        });\n\n        return std::future_status::ready;\n    }\n\n    template<class Rep, class Period>\n    std::future_status wait_for(const std::chrono::duration<Rep, Period> &rel_time) const {\n        std::unique_lock<decltype(mutex_)> lock{mutex_};\n\n        bool time_out = cv_.wait_for(lock, rel_time, [this]() {\n            return this->status_ != NONE;\n        });\n\n        if (time_out)\n            return std::future_status::timeout;\n\n        return std::future_status::ready;\n    }\n\n    template<class Clock, class Duration>\n    std::future_status wait_until(const std::chrono::time_point<Clock, Duration> &abs_time) const {\n        std::unique_lock<decltype(mutex_)> lock{mutex_};\n\n        bool time_out = cv_.wait_until(lock, abs_time, [this]() {\n            return this->status_ != NONE;\n        });\n\n        if (time_out)\n            return std::future_status::timeout;\n\n        return std::future_status::ready;\n    }\n\n    void then(std::function<void(std::shared_ptr<state>)> &&func) {\n        {\n            std::lock_guard<std::mutex> lock(mutex_);\n            if (status_ == NONE) {\n                continuation_ = std::move(func);\n                return;\n            }\n        }\n\n        // don't need to lock cause the value is already set and it will through an exception if you try to set it again\n        //\n        func(this->shared_from_this());\n    }\n};\n\ntemplate<class TYPE>\nclass future;\n\ntemplate<class TYPE, class ...ARGS>\nfuture<TYPE> create_ready_future(ARGS &&... args);\n\ntemplate<class future_t>\nclass future {\npublic:\n    using type = future_t;\n\nprivate:\n    template<class ...ARGS>\n    friend future<future_t> create_ready_future(ARGS &&... args);\n\n    std::shared_ptr<state<future_t>> state_;\n\nprivate:\n    template<typename> struct is_future : std::false_type {};\n    template<typename T> struct is_future<future<T>> : std::true_type {};\npublic:\n\n    template<class ...ARGS>\n    future(ARGS &&... args): state_(std::make_shared<future_t>(std::forward<ARGS>(args)...)) {}\n\n    future() {}\n\n    future(const future &) = delete;\n\n    future &operator=(const future &) = default;\n\n    future(future &&p) : state_(std::move(p.state_)) {\n        p.state_ = nullptr;\n    }\n\n    future &operator=(future &&p) {\n        this->state_ = std::move(p.state_);\n        p.state_ = nullptr;\n    }\n\n    future(std::shared_ptr<state<future_t>> state) : state_(std::move(state)) {}\n\n    future_t get() {\n        if (!state_)\n            throw std::future_error{std::future_errc::no_state};\n\n        auto rm_state = gsl::finally([this]() {\n            this->state_->reset();\n            this->state_ = nullptr;\n        });\n\n        return state_->get();\n    }\n\n    std::future_status wait() {\n        if (!state_)\n            throw std::future_error{std::future_errc::no_state};\n\n        return state_->wait();\n    }\n\n    template<class Rep, class Period>\n    std::future_status wait_for(const std::chrono::duration<Rep, Period> &rel_time) const {\n        if (!state_)\n            throw std::future_error{std::future_errc::no_state};\n\n        return state_->wait_for(rel_time);\n    }\n\n    template<class Clock, class Duration>\n    std::future_status wait_until(const std::chrono::time_point<Clock, Duration> &abs_time) const {\n        if (!state_)\n            throw std::future_error{std::future_errc::no_state};\n\n        return state_->wait_until(abs_time);\n    }\n\n    bool valid() {\n        return state_ != nullptr;\n    }\n\n    //function that returns void\n    template <class callback_t,\n            class return_t = typename std::result_of<callback_t(future_t)>::type,\n            typename  = typename std::enable_if<std::is_void<return_t>::value >::type\n    >\n    void then(callback_t cb_function){\n        if (!state_)\n            throw std::future_error{std::future_errc::no_state};\n\n        state_->then([cb_function = std::move(cb_function)](std::shared_ptr<state<future_t>> state) mutable {\n            g_default_executor([cb_function = std::move(cb_function), state = std::move(state)]() mutable {\n                cb_function(future<future_t> {state});\n            });\n        });\n    }\n\n    //function that returns a non future value\n    template <class callback_t,\n            class inner_return_t = typename std::result_of<callback_t(future_t)>::type,\n            class return_t = future<inner_return_t>,\n            typename  = typename std::enable_if<!std::is_void<inner_return_t>::value >::type,\n            typename  = typename std::enable_if<!is_future<inner_return_t>::value>::type\n    >\n    return_t then(callback_t cb_function) {\n        if (!state_)\n            throw std::future_error{std::future_errc::no_state};\n\n        auto ret_state = std::make_shared<state<inner_return_t>>();\n\n        state_->then([cb_function = std::move(cb_function), ret_state](std::shared_ptr<state<future_t>> state) mutable {\n            g_default_executor([cb_function = std::move(cb_function), state = std::move(state), ret_state = std::move(ret_state)]() mutable {\n                ret_state->set_value(cb_function(future<future_t> {state}));\n\n            });\n        });\n\n        return return_t {ret_state};\n    }\n\n    // function that returns a lom::future\n    template <class callback_t,\n            class return_t = typename std::result_of<callback_t(future_t)>::type,\n            class inner_return_t = typename return_t::type,\n            typename  = typename std::enable_if<is_future<return_t>::value>::type\n    >\n    return_t then(callback_t cb_function) {\n        static_assert(std::is_same<return_t, lom::future<double>>::value, \"qwert\");\n        static_assert(std::is_same<inner_return_t,double>::value, \"qewr\");\n\n        if (!state_)\n            throw std::future_error{std::future_errc::no_state};\n\n        auto ret_state = std::make_shared<state<inner_return_t>>();\n\n        state_->then([cb_function = std::move(cb_function), ret_state](std::shared_ptr<state<future_t>> state) mutable {\n            g_default_executor([cb_function = std::move(cb_function), state = std::move(state), ret_state = std::move(ret_state)]() mutable {\n                return_t rt = cb_function(future<future_t> {state});\n                rt.then([ret_state = std::move(ret_state)](return_t r){\n                    ret_state->set_value(r.get());\n                });\n                //ret_state->set_value\n\n            });\n        });\n\n        return return_t {ret_state};\n    }\n};\n\ntemplate<class TYPE, class ...ARGS>\nfuture<TYPE> create_ready_future(ARGS &&... args) {\n    return {std::forward<ARGS>(args)...};\n}\n\n\ntemplate<class TYPE>\nclass promise {\n    std::shared_ptr<state<TYPE>> state_;\n    bool has_future = false;\n\npublic:\n    promise() : state_(std::make_shared<state<TYPE>>()) {}\n\n    promise(const promise &) = delete;\n\n    promise &operator=(const promise &) = delete;\n\n    promise(promise &&p) : state_(std::move(p.state_)) {}\n\n    promise &operator=(promise &&p) noexcept {\n        this->state_ = std::move(p.state_);\n    }\n\n    future<TYPE> get_future() {\n        if(has_future)\n            throw std::future_error{std::future_errc::future_already_retrieved};\n\n        has_future = true;\n\n        return {state_};\n    }\n\n    template<class ...ARGS>\n    void set_value(ARGS &&...args) {\n        if (!state_)\n            throw std::future_error{std::future_errc::no_state};\n\n        state_->set_value(std::forward<ARGS>(args)...);\n    }\n\n    void set_exception(std::exception_ptr p) {\n        if (!state_)\n            throw std::future_error{std::future_errc::no_state};\n\n        state_->set_exception(std::move(p));\n    }\n\n};\n\n/*\ntemplate<class future_t>\ntemplate<class callback_t, class return_t>\nauto future<future_t>::then(callback_t cb_function) -> return_t {\n    static_assert(!std::is_same<return_t, void>::value, \"is null\");\n\n    if (!state_)\n        throw std::future_error{std::future_errc::no_state};\n\n    state_->then([cb_function = std::move(cb_function)](std::shared_ptr<state<future_t>> state) mutable {\n        g_default_executor([cb_function = std::move(cb_function), state = std::move(state)]() mutable {\n            cb_function(future<future_t> {state});\n        });\n    });\n}\n*/\n\n}", "meta": {"hexsha": "e7e3da92a932213cd1fea1697940b81f917fe6e0", "size": 11112, "ext": "h", "lang": "C", "max_stars_repo_path": "include/lom/future.h", "max_stars_repo_name": "liamom/future", "max_stars_repo_head_hexsha": "9d91444fd92868f70fe0eb29ffa16d519ea51974", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/lom/future.h", "max_issues_repo_name": "liamom/future", "max_issues_repo_head_hexsha": "9d91444fd92868f70fe0eb29ffa16d519ea51974", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/lom/future.h", "max_forks_repo_name": "liamom/future", "max_forks_repo_head_hexsha": "9d91444fd92868f70fe0eb29ffa16d519ea51974", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2030456853, "max_line_length": 141, "alphanum_fraction": 0.6005219582, "num_tokens": 2605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.0646534847517276, "lm_q2_score": 0.010652508425177131, "lm_q1q2_score": 0.0006887217910348394}}
{"text": "#pragma once\n#include \"parser.h\"\n#include \"format.h\"\n#include \"nameutils.h\"\n#include \"utils.h\"\n#include <sfun/string_utils.h>\n#include <cmdlime/errors.h>\n#include <gsl/gsl>\n#include <algorithm>\n#include <sstream>\n#include <iomanip>\n#include <functional>\n#include <cassert>\n\nnamespace cmdlime::detail{\nnamespace str = sfun::string_utils;\n\ntemplate <FormatType formatType>\nclass PosixParser : public Parser<formatType>\n{\n    using Parser<formatType>::Parser;\n\n    void processCommand(std::string command)\n    {\n        auto possibleNumberArg = command;\n        command = str::after(command, \"-\");\n        if (isParamOrFlag(command)){            \n            if (this->readMode_ != Parser<formatType>::ReadMode::ExitFlagsAndCommands){\n                if (!foundParam_.empty())\n                    throw ParsingError{\"Parameter '-\" + foundParam_ + \"' value can't be empty\"};\n                if (argumentEncountered_)\n                    throw ParsingError{\"Flags and parameters must precede arguments\"};\n            }\n            parseCommand(command);\n        }\n        else if (isNumber(possibleNumberArg)){\n            this->readArg(possibleNumberArg);\n            argumentEncountered_ = true;\n        }\n        else if (this->readMode_ != Parser<formatType>::ReadMode::ExitFlagsAndCommands)\n            throw ParsingError{\"Encountered unknown parameter or flag '-\" + command + \"'\"};\n    }\n\n    void preProcess() override\n    {\n        checkNames();\n        argumentEncountered_ = false;\n        foundParam_.clear();\n    }\n\n    void process(const std::string& token) override\n    {       \n        if (str::startsWith(token, \"-\") && token.size() > 1)\n           processCommand(token);\n        else if (!foundParam_.empty()){\n            this->readParam(foundParam_, token);\n            foundParam_.clear();\n        }\n        else{\n            this->readArg(token);\n            argumentEncountered_ = true;\n        }\n    }\n\n    void postProcess() override\n    {\n        if (!foundParam_.empty())\n            throw ParsingError{\"Parameter '-\" + foundParam_ + \"' value can't be empty\"};\n    }\n\n    void parseCommand(const std::string& command)\n    {\n        if (command.empty())\n            throw ParsingError{\"Flags and parameters must have a name\"};\n        auto paramValue = std::string{};\n        for(auto ch : command){\n            auto opt = std::string{ch};\n            if (!foundParam_.empty())\n                paramValue += opt;\n            else if (this->findFlag(opt))\n                this->readFlag(opt);\n            else if (this->findParam(opt) || this->findParamList(opt))\n                foundParam_ = opt;\n            else if (this->readMode_ != Parser<formatType>::ReadMode::ExitFlagsAndCommands)\n                throw ParsingError{\"Unknown option '\" + opt + \"' in command '-\" + command + \"'\"};\n        }\n        if (!foundParam_.empty() && !paramValue.empty()){\n            this->readParam(foundParam_, paramValue);\n            foundParam_.clear();\n        }\n    }\n\n    void checkNames()\n    {\n        auto check = [](const OptionInfo& var, const std::string& varType){\n            if (var.name().size() != 1)\n                throw ConfigError{varType + \"'s name '\" + var.name() + \"' can't have more than one symbol\"};\n            if (!std::isalnum(var.name().front()))\n                throw ConfigError{varType + \"'s name '\" + var.name() + \"' must be an alphanumeric character\"};\n        };\n        this->forEachParamInfo([check](const OptionInfo& var){\n            check(var, \"Parameter\");\n        });\n        this->forEachParamListInfo([check](const OptionInfo& var){\n            check(var, \"Parameter\");\n        });\n        this->forEachFlagInfo([check](const OptionInfo& var){\n            check(var, \"Flag\");\n        });\n    }\n\n    bool isParamOrFlag(const std::string& str)\n    {\n        if (str.empty())\n            return false;\n        auto opt = str.substr(0,1);\n        return this->findFlag(opt) ||\n               this->findParam(opt) ||\n               this->findParamList(opt);\n    }\n\nprivate:\n    bool argumentEncountered_ = false;\n    std::string foundParam_;\n};\n\nclass PosixNameProvider{\npublic:\n    static std::string name(const std::string& optionName)\n    {\n        Expects(!optionName.empty());\n        return std::string{static_cast<char>(std::tolower(optionName.front()))};\n    }\n\n    static std::string shortName(const std::string& optionName)\n    {\n        Expects(!optionName.empty());\n        return {};\n    }\n\n    static std::string fullName(const std::string& optionName)\n    {\n        Expects(!optionName.empty());\n        return toKebabCase(optionName);\n    }\n\n    static std::string valueName(const std::string& typeName)\n    {\n        Expects(!typeName.empty());\n        return toCamelCase(templateType(typeNameWithoutNamespace(typeName)));\n    }\n};\n\n\nclass PosixOutputFormatter{\npublic:\n    static std::string paramUsageName(const IParam& param)\n    {\n        auto stream = std::stringstream{};\n        if (param.isOptional())\n            stream << \"[\" << paramPrefix() << param.info().name() << \" <\" << param.info().valueName() << \">]\";\n        else\n            stream << paramPrefix() << param.info().name() << \" <\" << param.info().valueName() << \">\";\n        return stream.str();\n    }\n\n    static std::string paramListUsageName(const IParamList& param)\n    {\n        auto stream = std::stringstream{};\n        if (param.isOptional())\n            stream << \"[\" << paramPrefix() << param.info().name() << \" <\" << param.info().valueName() << \">...]\";\n        else\n            stream << paramPrefix() << param.info().name() << \" <\" << param.info().valueName() << \">...\";\n        return stream.str();\n    }\n\n    static std::string paramDescriptionName(const IParam& param, int indent = 0)\n    {\n        auto stream = std::stringstream{};\n        stream << std::setw(indent) << paramPrefix()\n               << param.info().name() << \" <\" << param.info().valueName() << \">\";\n        return stream.str();\n    }\n\n    static std::string paramListDescriptionName(const IParamList& param, int indent = 0)\n    {\n        auto stream = std::stringstream{};\n        stream << std::setw(indent) << paramPrefix()\n               << param.info().name() << \" <\" << param.info().valueName() << \">\";\n        return stream.str();\n    }\n\n    static std::string paramPrefix()\n    {\n        return \"-\";\n    }\n\n    static std::string flagUsageName(const IFlag& flag)\n    {\n        auto stream = std::stringstream{};\n        stream << \"[\" << flagPrefix() << flag.info().name() << \"]\";\n        return stream.str();\n    }\n\n    static std::string flagDescriptionName(const IFlag& flag, int indent = 0)\n    {\n        auto stream = std::stringstream{};\n        stream << std::setw(indent) << flagPrefix() << flag.info().name();\n        return stream.str();\n    }\n\n    static std::string flagPrefix()\n    {\n        return \"-\";\n    }\n\n    static std::string argUsageName(const IArg& arg)\n    {\n        auto stream = std::stringstream{};\n        stream << \"<\" << arg.info().name() << \">\";\n        return stream.str();\n    }\n\n    static std::string argDescriptionName(const IArg& arg, int indent = 0)\n    {\n        auto stream = std::stringstream{};\n        if (indent)\n            stream << std::setw(indent) << \" \";\n        stream << \"<\" << arg.info().name() << \"> (\" << arg.info().valueName() << \")\";\n        return stream.str();\n    }\n\n    static std::string argListUsageName(const IArgList& argList)\n    {\n        auto stream = std::stringstream{};\n        if (argList.isOptional())\n            stream << \"[\" << argList.info().name() << \"...]\";\n        else\n            stream << \"<\" << argList.info().name() << \"...>\";\n        return stream.str();\n    }\n\n    static std::string argListDescriptionName(const IArgList& argList, int indent = 0)\n    {\n        auto stream = std::stringstream{};\n        if (indent)\n            stream << std::setw(indent) << \" \";\n        stream << \"<\" << argList.info().name() << \"> (\" << argList.info().valueName() << \")\";\n        return stream.str();\n    }\n\n};\n\ntemplate<>\nstruct Format<FormatType::POSIX>\n{\n    using parser = PosixParser<FormatType::POSIX>;\n    using nameProvider = PosixNameProvider;\n    using outputFormatter = PosixOutputFormatter;\n    static constexpr bool shortNamesEnabled = false;\n};\n\n\n}\n", "meta": {"hexsha": "f89d7effefc0691fe20af7307499d5e5032f5db7", "size": 8263, "ext": "h", "lang": "C", "max_stars_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/posixformat.h", "max_stars_repo_name": "GerHobbelt/hypertextcpp", "max_stars_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_stars_repo_licenses": ["MS-PL"], "max_stars_count": 77.0, "max_stars_repo_stars_event_min_datetime": "2021-05-20T18:05:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T21:37:54.000Z", "max_issues_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/posixformat.h", "max_issues_repo_name": "GerHobbelt/hypertextcpp", "max_issues_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_issues_repo_licenses": ["MS-PL"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2021-05-20T22:04:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-21T08:13:28.000Z", "max_forks_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/posixformat.h", "max_forks_repo_name": "GerHobbelt/hypertextcpp", "max_forks_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_forks_repo_licenses": ["MS-PL"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-22T00:36:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-22T00:36:08.000Z", "avg_line_length": 31.1811320755, "max_line_length": 113, "alphanum_fraction": 0.5577877284, "num_tokens": 1885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.03567855190309708, "lm_q2_score": 0.019124038637652847, "lm_q1q2_score": 0.0006823180051303311}}
{"text": "// MIT License Copyright (c) 2020 Jarrett Wendt\n\n#pragma once\n\n#include <gsl/gsl>\n\n#include \"Macros.h\"\n#include \"SharedPtr.h\"\n#include \"Entity.h\"\n\nnamespace Library\n{\t\n\tclass Engine final\n\t{\n\t\tfriend Entity;\n\t\t\n\t\t/** the parentmost Entity */\n\t\tstatic inline SharedPtr<Entity> world{ nullptr };\n\t\t\n\t\tstatic inline std::string programName{};\n\t\tstatic inline std::string pythonSourceDirectory{};\n\t\tstatic inline const std::string initFileName{ \"init.py\" };\n\t\tstatic inline const std::string shutdownFileName{ \"del.py\" };\n\n\t\tstatic inline FILE* initFilePtr{ nullptr };\n\t\t\n\tpublic:\n\t\tSTATIC_CLASS(Engine)\n\t\tusing Args = gsl::span<const char*>;\n\t\t\n\t\t/**\n\t\t * O(1)\n\t\t * \n\t\t * @returns\t\tthe parentmost Entity\n\t\t */\n\t\tstatic Entity& World() noexcept;\n\t\t\n\t\t/**\n\t\t * to be called by WinMain()\n\t\t */\n\t\tstatic void Main(const Args& args);\n\n\t\t/**\n\t\t * setting this to false will terminate the simulation\n\t\t *\n\t\t * @returns\t\twhether or not the simulation is active\n\t\t */\n\t\tstatic bool& IsActive() noexcept;\n\n\t\t/**\n\t\t * runs before the first Update()\n\t\t */\n\t\tstatic void Init();\n\n\t\t/**\n\t\t * the main engine loop\n\t\t */\n\t\tstatic void Update();\n\n\t\t/**\n\t\t * runs after the last Update()\n\t\t */\n\t\tstatic void Terminate();\n\n\tprivate:\n\t\t/**\n\t\t * wraps all of the logic for parsing the command line args.\n\t\t */\n\t\tstatic void ParseArgs(const Args& args);\n\t\t\n\t\t/**\n\t\t * Invoked by WinMain's WndProc.\n\t\t *\n\t\t * @param hWnd\t\tHWND\n\t\t * @param uMsg\t\tUINT\n\t\t * @param wParam\tWPARAM\n\t\t * @param lParam\tLPARAM\n\t\t */\n#ifdef _WIN64\n\t\tstatic long long __stdcall WndProc(void* hWnd, unsigned int uMsg, unsigned long long wParam, long long lParam);\n#else\n\t\tstatic long __stdcall WndProc(void* hWnd, unsigned int uMsg, unsigned wParam, long lParam);\n#endif\n\t};\n}\n", "meta": {"hexsha": "76c7091f1446c4c948ae9e5d2cd58e851f80bb21", "size": 1723, "ext": "h", "lang": "C", "max_stars_repo_path": "source/Library/engine/Engine.h", "max_stars_repo_name": "JarrettWendt/FIEAEngine", "max_stars_repo_head_hexsha": "0bf7e89cd66fec29550f7d7a1a11f5cf398c27e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-05-27T14:01:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T09:11:58.000Z", "max_issues_repo_path": "source/Library/engine/Engine.h", "max_issues_repo_name": "JarrettWendt/FIEAEngine", "max_issues_repo_head_hexsha": "0bf7e89cd66fec29550f7d7a1a11f5cf398c27e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/Library/engine/Engine.h", "max_forks_repo_name": "JarrettWendt/FIEAEngine", "max_forks_repo_head_hexsha": "0bf7e89cd66fec29550f7d7a1a11f5cf398c27e5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0348837209, "max_line_length": 113, "alphanum_fraction": 0.6535113175, "num_tokens": 456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.041462275080286194, "lm_q2_score": 0.016403030773154886, "lm_q1q2_score": 0.0006801069740669474}}
{"text": "/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */\n/*\n *     Copyright 2018 Couchbase, Inc.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n */\n\n#pragma once\n\n#include <nlohmann/json_fwd.hpp>\n#include <gsl/gsl>\n#include <list>\n#include <string>\n\nclass Module;\nclass Event;\n\n/**\n * Is this build for enterprise edition?\n *\n * @return true when building EE, false for CE\n */\nbool is_enterprise_edition();\n\n/**\n * In order to allow making unit tests we want to be able to mock the\n * enterprise edition settings dynamically\n */\nvoid set_enterprise_edition(bool enable);\n\n/**\n * Load the requested file and parse it as JSON\n *\n * @param fname the name of the file\n * @return the json representation of the file\n * @throws std::system_error if we fail to read the file\n *         std::runtime_error if we fail to parse the content of the file\n */\nnlohmann::json load_file(const std::string& fname);\n\n/**\n * Iterate over the module descriptor json and populate each entry\n * in the modules array into the provided modules list.\n *\n * @param ptr The JSON representation of the module description. See\n *            ../README.md for a description of the syntax\n * @param modules Where to store the list of all of the entries found\n * @param srcroot The source root to prepend to all of the paths in the spec\n * @param objroot The object root to prepend to all of the paths in the spec\n * @throws std::invalid_argument if the provided JSON is of an unexpected format\n */\nvoid parse_module_descriptors(const nlohmann::json&,\n                              std::list<std::unique_ptr<Module>>& modules,\n                              const std::string& srcroot,\n                              const std::string& objroot);\n\n/**\n * Build the master event file\n *\n * @param modules The modules to include\n * @param output_file Where to store the result\n * @throws std::system_error if we fail to write the file\n */\nvoid create_master_file(const std::list<std::unique_ptr<Module>>& modules,\n                        const std::string& output_file);\n", "meta": {"hexsha": "b87926b177e497f8ffc9937bf0e219d315dc4cc2", "size": 2586, "ext": "h", "lang": "C", "max_stars_repo_path": "auditd/generator/generator_utilities.h", "max_stars_repo_name": "rohansuri/kv_engine", "max_stars_repo_head_hexsha": "6d377448a787ce5dc268c95def2850e36f5f1328", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-13T07:33:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-13T07:33:09.000Z", "max_issues_repo_path": "auditd/generator/generator_utilities.h", "max_issues_repo_name": "rohansuri/kv_engine", "max_issues_repo_head_hexsha": "6d377448a787ce5dc268c95def2850e36f5f1328", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "auditd/generator/generator_utilities.h", "max_forks_repo_name": "rohansuri/kv_engine", "max_forks_repo_head_hexsha": "6d377448a787ce5dc268c95def2850e36f5f1328", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-10-11T14:00:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-06T09:20:15.000Z", "avg_line_length": 34.0263157895, "max_line_length": 80, "alphanum_fraction": 0.6883217324, "num_tokens": 582, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.03210070764297385, "lm_q2_score": 0.020964240474054714, "lm_q1q2_score": 0.0006729669544146298}}
{"text": "#ifndef ADD_TO_CONFIG_INCLUDE\n#define ADD_TO_CONFIG_INCLUDE\n\n#include <optional>\n#include <stdexcept>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include <gsl/pointers>\n\n#include \"config/variablesMap.h\"\n\n#include \"base-utils/nonEmptyString.h\"\n\nnamespace execHelper::test {\ninline void\naddToConfig(const execHelper::config::SettingsKeys& key,\n            const std::string& value,\n            gsl::not_null<execHelper::config::VariablesMap*> config) {\n    if(!config->add(key, value)) {\n        throw std::runtime_error(\"Failed to add key \" + key.back() +\n                                 \" with value '\" + value + \"' to config\");\n    }\n}\n\ninline void\naddToConfig(const execHelper::config::SettingsKeys& key,\n            const NonEmptyString& value,\n            gsl::not_null<execHelper::config::VariablesMap*> config) {\n    if(!config->add(key, *value)) {\n        throw std::runtime_error(\"Failed to add key \" + key.back() +\n                                 \" with value '\" + *value + \"' to config\");\n    }\n}\n\ntemplate <typename T>\ninline void\naddToConfig(const execHelper::config::SettingsKeys& key,\n            const std::vector<T>& value,\n            gsl::not_null<execHelper::config::VariablesMap*> config) {\n    if(!config->add(key, value)) {\n        throw std::runtime_error(\"Failed to add key \" + key.back() +\n                                 \" with first value '\" + value.front() +\n                                 \"' to config\");\n    }\n}\n\ninline void\naddToConfig(const execHelper::config::SettingsKeys& key, bool value,\n            gsl::not_null<execHelper::config::VariablesMap*> config) {\n    if(value) {\n        if(!config->add(key, \"yes\")) {\n            throw std::runtime_error(\"Failed to add key \" + key.back() +\n                                     \" with value 'true' to config\");\n        }\n    }\n    if(!config->add(key, \"no\")) {\n        throw std::runtime_error(\"Failed to add key \" + key.back() +\n                                 \" with value 'false' to config\");\n    }\n}\n\ninline void\naddToConfig(execHelper::config::SettingsKeys key,\n            const std::pair<std::string, std::string>& value,\n            gsl::not_null<execHelper::config::VariablesMap*> config) {\n    key.push_back(value.first);\n    if(!config->add(key, value.second)) {\n        throw std::runtime_error(\"Failed to add key \" + value.first +\n                                 \" with first value '\" + value.second +\n                                 \"' to config\");\n    }\n}\n\ntemplate <typename T>\ninline void\naddToConfig(const execHelper::config::SettingsKeys& key,\n            const std::optional<T>& value,\n            gsl::not_null<execHelper::config::VariablesMap*> config) {\n    if(value) {\n        addToConfig(key, *value, config);\n    }\n}\n\ntemplate <typename T>\ninline void\naddToConfig(const execHelper::config::SettingsKey& key, const T& value,\n            gsl::not_null<execHelper::config::VariablesMap*> config) {\n    addToConfig(execHelper::config::SettingsKeys({key}), value, config);\n}\n} // namespace execHelper::test\n\n#endif /* ADD_TO_CONFIG_INCLUDE */\n", "meta": {"hexsha": "72fcfc9f89fa18cba403237ea2794c4a28c5f3f2", "size": 3067, "ext": "h", "lang": "C", "max_stars_repo_path": "test/utils/include/utils/addToConfig.h", "max_stars_repo_name": "exec-helper/source", "max_stars_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-28T13:24:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-28T13:24:30.000Z", "max_issues_repo_path": "test/utils/include/utils/addToConfig.h", "max_issues_repo_name": "exec-helper/source", "max_issues_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/utils/include/utils/addToConfig.h", "max_forks_repo_name": "exec-helper/source", "max_forks_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-07-03T11:11:19.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-03T11:11:19.000Z", "avg_line_length": 32.2842105263, "max_line_length": 75, "alphanum_fraction": 0.5891750897, "num_tokens": 693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.03308597648187432, "lm_q2_score": 0.020332351264950595, "lm_q1q2_score": 0.000672715695773363}}
{"text": "#pragma once\n#include \"nkw_common.h\"\n#include \"utility/types.h\"\n#include <gsl/gsl>\n\nnamespace cws80 {\n\nclass NativeUI;\n\n//\nbool im_select(nk_context *ctx, NativeUI &nat,\n               gsl::span<const std::string> choices, uint *value);\n\n}  // namespace cws80\n", "meta": {"hexsha": "0e63185975f55cf40291b98bce7747202436e0fb", "size": 260, "ext": "h", "lang": "C", "max_stars_repo_path": "sources/ui/detail/nkw_select.h", "max_stars_repo_name": "jpcima/cws80", "max_stars_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-05-20T19:27:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-03T04:21:53.000Z", "max_issues_repo_path": "sources/ui/detail/nkw_select.h", "max_issues_repo_name": "jpcima/cws80", "max_issues_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-05-21T12:56:22.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-23T21:33:33.000Z", "max_forks_repo_path": "sources/ui/detail/nkw_select.h", "max_forks_repo_name": "jpcima/cws80", "max_forks_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.3333333333, "max_line_length": 66, "alphanum_fraction": 0.6769230769, "num_tokens": 70, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.03258974382642807, "lm_q2_score": 0.020332353713678093, "lm_q1q2_score": 0.0006626261989170925}}
{"text": "#pragma once\n\n#include <winrt\\Windows.Foundation.h>\n#include <d3d11.h>\n#include <gsl/gsl>\n#include \"RTTI.h\"\n\nnamespace Library\n{\n\tclass Shader : public RTTI\n\t{\n\t\tRTTI_DECLARATIONS(Shader, RTTI)\n\n\tpublic:\t\t\n\t\tShader(const Shader&) = default;\n\t\tShader& operator=(const Shader&) = default;\n\t\tShader(Shader&&) = default;\n\t\tShader& operator=(Shader&&) = default;\n\t\tvirtual ~Shader() = default;\n\n\t\tstatic winrt::com_ptr<ID3D11ClassLinkage> CreateClassLinkage(gsl::not_null<ID3D11Device*> device);\n\n\tprotected:\n\t\tShader() = default;\n\t};\n}", "meta": {"hexsha": "8e9c0a2cb31673e135d894bedec27f9dbb425afd", "size": 531, "ext": "h", "lang": "C", "max_stars_repo_path": "source/Library.Shared/Shader.h", "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/Library.Shared/Shader.h", "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/Library.Shared/Shader.h", "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.4230769231, "max_line_length": 100, "alphanum_fraction": 0.7062146893, "num_tokens": 156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.04023793801989053, "lm_q2_score": 0.016403035942076205, "lm_q1q2_score": 0.000660024343575299}}
{"text": "#ifndef CONTROLLERS_UPDATERECTIFICATIONCONTROLLER_H\n#define CONTROLLERS_UPDATERECTIFICATIONCONTROLLER_H\n\n#include \"imageoperationactioncontroller.h\"\n\n#include \"s3d/cv/image_operation/image_operation.h\"\n\n#include <QAction>\n\n#include <gsl/gsl>\n\nclass ImageOperationTriggerController : public ImageOperationActionController {\nQ_OBJECT\n\npublic:\n  ImageOperationTriggerController(gsl::not_null<QAction*> action,\n                                  gsl::not_null<s3d::image_operation::ImageOperation*> imageOperation);\n\n  void onActionTriggered() override;\n};\n\n#endif //CONTROLLERS_UPDATERECTIFICATIONCONTROLLER_H\n", "meta": {"hexsha": "dae6082e477e814d29bff59565694197d1682014", "size": 606, "ext": "h", "lang": "C", "max_stars_repo_path": "src/apps/S3DAnalyzer/controllers/imageoperationtriggercontroller.h", "max_stars_repo_name": "hugbed/OpenS3D", "max_stars_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-16T16:38:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-20T03:23:15.000Z", "max_issues_repo_path": "src/apps/S3DAnalyzer/controllers/imageoperationtriggercontroller.h", "max_issues_repo_name": "hugbed/OpenS3D", "max_issues_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 40.0, "max_issues_repo_issues_event_min_datetime": "2017-04-12T17:24:44.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-21T18:41:23.000Z", "max_forks_repo_path": "src/apps/S3DAnalyzer/controllers/imageoperationtriggercontroller.h", "max_forks_repo_name": "hugbed/OpenS3D", "max_forks_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-07-13T21:51:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-18T16:22:03.000Z", "avg_line_length": 26.347826087, "max_line_length": 103, "alphanum_fraction": 0.7937293729, "num_tokens": 133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.0446808677284564, "lm_q2_score": 0.014728615120138074, "lm_q1q2_score": 0.0006580873040062322}}
{"text": "#pragma once\n//=============================================================================\n// EXTERNAL DECLARATIONS\n//=============================================================================\n#include \"Core/Game/IManagerComponent.h\"\n#include \"Core/Game/IManager.h\"\n#include \"Core/Game/IGameEngine.h\"\n#include \"Core/Components/ComponentBase.h\"\n#include <gsl/span>\n\nnamespace engine {\n\n//=============================================================================\n// CLASS GameManager\n//=============================================================================\ntemplate<class TDerived>\nclass GameManager\n\t: virtual public IManagerComponent\n\t, virtual public IManager\n{\npublic:\n\tvirtual void onAttached(const GameEngineRef &iGameEngine) override {}\n\tvirtual void onDetached(const GameEngineRef &iGameEngine) override {}\n\n\tvirtual gsl::span<IdType> interfaces() override\n\t{\n\t\treturn TDerived::Interfaces;\n\t}\n};\n} // namespace engine\n", "meta": {"hexsha": "a25a18a23f18a89843fd8c9678b44c4c4fca77b8", "size": 941, "ext": "h", "lang": "C", "max_stars_repo_path": "Engine/Game/GameManager.h", "max_stars_repo_name": "gaspardpetit/INF740-GameEngine", "max_stars_repo_head_hexsha": "075b6563204fb3d1cf7531599f30dd296c2c9239", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Engine/Game/GameManager.h", "max_issues_repo_name": "gaspardpetit/INF740-GameEngine", "max_issues_repo_head_hexsha": "075b6563204fb3d1cf7531599f30dd296c2c9239", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Engine/Game/GameManager.h", "max_forks_repo_name": "gaspardpetit/INF740-GameEngine", "max_forks_repo_head_hexsha": "075b6563204fb3d1cf7531599f30dd296c2c9239", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-09-25T22:24:16.000Z", "max_forks_repo_forks_event_max_datetime": "2015-09-25T22:24:16.000Z", "avg_line_length": 30.3548387097, "max_line_length": 79, "alphanum_fraction": 0.5111583422, "num_tokens": 154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.0255652109535716, "lm_q2_score": 0.02556521345925426, "lm_q1q2_score": 0.0006535800751589231}}
{"text": "#ifndef COMMAND_UTILS_INCLUDE\n#define COMMAND_UTILS_INCLUDE\n\n#include <limits>\n#include <string>\n#include <vector>\n\n#include <gsl/string_span>\n\n#include \"tmpFile.h\"\n\nnamespace execHelper {\nnamespace test {\nnamespace baseUtils {\nusing ConfigFile = TmpFile;\n\nconst gsl::czstring<> EXEC_HELPER_BINARY = \"exec-helper\";\nconst gsl::czstring<> COMMAND_KEY = \"commands\";\nconst gsl::czstring<> COMMAND_LINE_COMMAND_KEY = \"command-line-command\";\nconst gsl::czstring<> COMMAND_LINE_COMMAND_LINE_KEY = \"command-line\";\n\nusing ReturnCode = int32_t;\nstatic const ReturnCode SUCCESS = EXIT_SUCCESS;\nstatic const ReturnCode RUNTIME_ERROR = std::numeric_limits<ReturnCode>::max();\n} // namespace baseUtils\n} // namespace test\n} // namespace execHelper\n\n#endif /* COMMAND_UTILS_INCLUDE */\n", "meta": {"hexsha": "933dd85964978cbca2b985474beb76ee53b07013", "size": 770, "ext": "h", "lang": "C", "max_stars_repo_path": "test/base-utils/include/base-utils/commandUtils.h", "max_stars_repo_name": "exec-helper/source", "max_stars_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-28T13:24:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-28T13:24:30.000Z", "max_issues_repo_path": "test/base-utils/include/base-utils/commandUtils.h", "max_issues_repo_name": "exec-helper/source", "max_issues_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/base-utils/include/base-utils/commandUtils.h", "max_forks_repo_name": "exec-helper/source", "max_forks_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-07-03T11:11:19.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-03T11:11:19.000Z", "avg_line_length": 25.6666666667, "max_line_length": 79, "alphanum_fraction": 0.774025974, "num_tokens": 170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.02758528382564496, "lm_q2_score": 0.02368947366876239, "lm_q1q2_score": 0.0006534808548329533}}
{"text": "/***\n * Copyright 2019 The Katla Authors\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#ifndef KATLA_POSIX_FILE_H\n#define KATLA_POSIX_FILE_H\n\n#include \"katla/core/core.h\"\n\n#include <optional>\n#include <gsl/span>\n\n#include <fcntl.h>\n\nnamespace katla {\n\n    class PosixFile {\n    public:\n        enum class OpenFlags : int {\n            ReadOnly    = O_RDONLY,\n            WriteOnly   = O_WRONLY,\n            ReadWrite   = O_RDWR,\n            Create      = O_CREAT,\n            Exclusive   = O_EXCL,\n            Truncate    = O_TRUNC,\n            Append      = O_APPEND,\n            NonBlocking = O_NONBLOCK,\n            Sync        = O_SYNC,\n            Async       = O_ASYNC,\n\n#if defined(O_TMPFILE)\n            TmpFile     = O_TMPFILE\n#endif\n        };\n\n        PosixFile();\n        ~PosixFile();\n\n        outcome::result<void> create(std::string_view filePath, OpenFlags flags);\n        outcome::result<void> open(std::string_view filePath, OpenFlags flags);\n        outcome::result<void> close();\n\n        outcome::result<ssize_t> read(gsl::span<std::byte> &buffer);\n        outcome::result<ssize_t> write(gsl::span<std::byte> &buffer);\n\n        static outcome::result<std::string> absolutePath(std::string path);\n\n        outcome::result<size_t> size();\n\n    private:\n        int m_fd;\n    };\n\n    inline PosixFile::OpenFlags operator|(PosixFile::OpenFlags lhs, PosixFile::OpenFlags rhs) {\n        using T = std::underlying_type_t<PosixFile::OpenFlags>;\n        return static_cast<PosixFile::OpenFlags>(static_cast<T>(lhs) | static_cast<T>(rhs));\n    }\n\n    inline PosixFile::OpenFlags &operator|=(PosixFile::OpenFlags &lhs, PosixFile::OpenFlags rhs) {\n        lhs = lhs | rhs;\n        return lhs;\n    }\n\n}\n\n#endif // KATLA_POSIX_FILE_H\n", "meta": {"hexsha": "2e730124a33c4055d787c1e497e16ca904b75795", "size": 2257, "ext": "h", "lang": "C", "max_stars_repo_path": "core/posix-file.h", "max_stars_repo_name": "plok/katla", "max_stars_repo_head_hexsha": "aaaeb8baf041bba7259275beefc71c8452a16223", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "core/posix-file.h", "max_issues_repo_name": "plok/katla", "max_issues_repo_head_hexsha": "aaaeb8baf041bba7259275beefc71c8452a16223", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-03-25T14:33:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-16T14:21:56.000Z", "max_forks_repo_path": "core/posix-file.h", "max_forks_repo_name": "plok/katla", "max_forks_repo_head_hexsha": "aaaeb8baf041bba7259275beefc71c8452a16223", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-26T13:32:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-26T13:32:36.000Z", "avg_line_length": 28.5696202532, "max_line_length": 98, "alphanum_fraction": 0.6335844041, "num_tokens": 546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.02333077356210362, "lm_q2_score": 0.02800752151871368, "lm_q1q2_score": 0.0006534371425888534}}
{"text": "#ifndef STDAFX__H\n#define STDAFX__H\n\n#if defined(_WIN32)\n\n#include <SDKDDKVer.h>\n\n#if !defined(_STL_EXTRA_DISABLED_WARNINGS)\n#define _STL_EXTRA_DISABLED_WARNINGS 4061 4324 4365 4514 4571 4582 4583 4623 4625 4626 4710 4774 4800 4820 4987 5026 5027 5039\n#endif\n\n#if !defined(_SCL_SECURE_NO_WARNINGS)\n#define _SCL_SECURE_NO_WARNINGS 1\n#endif\n\n#if !defined(_CRT_SECURE_NO_WARNINGS)\n#define _CRT_SECURE_NO_WARNINGS 1\n#endif\n\n#if !defined(_SILENCE_CXX17_ITERATOR_BASE_CLASS_DEPRECATION_WARNING)\n#define _SILENCE_CXX17_ITERATOR_BASE_CLASS_DEPRECATION_WARNING 1\n#endif\n\n#if !defined(_SILENCE_CXX17_OLD_ALLOCATOR_MEMBERS_DEPRECATION_WARNING)\n#define _SILENCE_CXX17_OLD_ALLOCATOR_MEMBERS_DEPRECATION_WARNING 1\n#endif\n\n#if !defined(_SILENCE_CXX17_CODECVT_HEADER_DEPRECATION_WARNING)\n#define _SILENCE_CXX17_CODECVT_HEADER_DEPRECATION_WARNING 1\n#endif\n\n#define STRICT\n#define NOMINMAX\n\n#pragma warning(disable: 4571) // warning C4571: Informational: catch(...) semantics changed since Visual C++ 7.1; structured exceptions (SEH) are no longer caught\n#pragma warning(disable: 4668) // warning C4668: '%s' is not defined as a preprocessor macro, replacing with '0' for '#if/#elif'\n#pragma warning(disable: 4710) // warning C4710: '%s': function not inlined\n#pragma warning(disable: 4711) // warning C4711: function '%s' selected for automatic inline expansion\n#pragma warning(disable: 4820) // warning C4820: '%s': '%d' bytes padding added after data member '%s'\n#pragma warning(disable: 5045) // warning C5045: Compiler will insert Spectre mitigation for memory load if /Qspectre switch specified\n\n#include <Windows.h>\n\n#pragma warning(push)\n#pragma warning(disable: 4005) // warning C4005: '%s': macro redefinition\n#include <Winternl.h>\n#include <ntstatus.h>\n#pragma warning(pop)\n\n#else // defined(_WIN32)\n\n#include <cpuid.h>\n\n#endif\n\n#if defined(_MSC_VER)\n\n// currently broken (triggers on iterators and other objects that are usually unnamed)\n#pragma warning(disable: 26444) // warning C26444: Avoid unnamed objects with custom construction and destruction (es.84: http://go.microsoft.com/fwlink/?linkid=862923).\n\n// disable for everything\n#pragma warning(disable: 4061) // warning C4061: enumerator '%s' in switch of enum '%s' is not explicitly handled by a case label\n#pragma warning(disable: 4324) // warning C4234: structure was padded due to alignment specifier\n#pragma warning(disable: 4514) // warning C4514: '%s': unreferenced inline function has been removed\n#pragma warning(disable: 4623) // warning C4623: '%s': default constructor was implicitly defined as deleted\n#pragma warning(disable: 4625) // warning C4625: '%s': copy constructor was implicitly defined as deleted\n#pragma warning(disable: 4626) // warning C4626: '%s': assignment operator was implicitly defined as deleted\n#pragma warning(disable: 4710) // warning C4710: '%s': function not inlined\n#pragma warning(disable: 4820) // warning C4820: '%s': '%d' bytes padding added after data member '%s'\n#pragma warning(disable: 5026) // warning C5026: '%s': move constructor was implicitly defined as deleted\n#pragma warning(disable: 5027) // warning C5027: '%s': move assignment operator was implicitly defined as deleted\n\n#pragma warning(disable: 26412) // warning C26412: Do not dereference an invalid pointer (lifetimes rule 1). 'return of %s' was invalidated at line %d by 'no initialization'.\n#pragma warning(disable: 26426) // warning C26426: Global initializer calls a non-constexpr function '%s' (i.22: http://go.microsoft.com/fwlink/?linkid=853919).\n#pragma warning(disable: 26481) // warning C26481: Don't use pointer arithmetic. Use span instead. (bounds.1: http://go.microsoft.com/fwlink/p/?LinkID=620413)\n#pragma warning(disable: 26482) // warning C26482: Only index into arrays using constant expressions (bounds.2: http://go.microsoft.com/fwlink/p/?LinkID=620414).\n#pragma warning(disable: 26485) // warning C26485: Expression '%s::`vbtable'': No array to pointer decay. (bounds.3: http://go.microsoft.com/fwlink/p/?LinkID=620415)\n#pragma warning(disable: 26490) // warning C26490: Don't use reinterpret_cast. (type.1: http://go.microsoft.com/fwlink/p/?LinkID=620417)\n#pragma warning(disable: 26499) // warning C26499: Could not find any lifetime tracking information for '%s'\n\n// disable for standard headers\n#pragma warning(push)\n#pragma warning(disable: 26400) // warning C26400: Do not assign the result of an allocation or a function call with an owner<T> return value to a raw pointer, use owner<T> instead. (i.11 http://go.microsoft.com/fwlink/?linkid=845474)\n#pragma warning(disable: 26401) // warning C26401: Do not delete a raw pointer that is not an owner<T>. (i.11: http://go.microsoft.com/fwlink/?linkid=845474)\n#pragma warning(disable: 26408) // warning C26408: Avoid malloc() and free(), prefer the nothrow version of new with delete. (r.10 http://go.microsoft.com/fwlink/?linkid=845483)\n#pragma warning(disable: 26409) // warning C26409: Avoid calling new and delete explicitly, use std::make_unique<T> instead. (r.11 http://go.microsoft.com/fwlink/?linkid=845485)\n#pragma warning(disable: 26411) // warning C26411: The parameter '%s' is a reference to unique pointer and it is never reassigned or reset, use T* or T& instead. (r.33 http://go.microsoft.com/fwlink/?linkid=845479)\n#pragma warning(disable: 26412) // warning C26412: Do not dereference an invalid pointer (lifetimes rule 1). 'return of %s' was invalidated at line %d by 'end of function scope (local lifetimes end)'.\n#pragma warning(disable: 26413) // warning C26413: Do not dereference nullptr (lifetimes rule 2). 'nullptr' was pointed to nullptr at line %d.\n#pragma warning(disable: 26423) // warning C26423: The allocation was not directly assigned to an owner.\n#pragma warning(disable: 26424) // warning C26424: Failing to delete or assign ownership of allocation at line %d.\n#pragma warning(disable: 26425) // warning C26425: Assigning '%s' to a static variable.\n#pragma warning(disable: 26444) // warning C26444: Avoid unnamed objects with custom construction and destruction (es.84: http://go.microsoft.com/fwlink/?linkid=862923).\n#pragma warning(disable: 26461) // warning C26461: The reference argument '%s' for function %s can be marked as const. (con.3: https://go.microsoft.com/fwlink/p/?LinkID=786684)\n#pragma warning(disable: 26471) // warning C26471: Don't use reinterpret_cast. A cast from void* can use static_cast. (type.1: http://go.microsoft.com/fwlink/p/?LinkID=620417).\n#pragma warning(disable: 26481) // warning C26481: Don't use pointer arithmetic. Use span instead. (bounds.1: http://go.microsoft.com/fwlink/p/?LinkID=620413)\n#pragma warning(disable: 26482) // warning C26482: Only index into arrays using constant expressions. (bounds.2: http://go.microsoft.com/fwlink/p/?LinkID=620414)\n#pragma warning(disable: 26490) // warning C26490: Don't use reinterpret_cast. (type.1: http://go.microsoft.com/fwlink/p/?LinkID=620417)\n#pragma warning(disable: 26493) // warning C26493: Don't use C-style casts that would perform a static_cast downcast, const_cast, or reinterpret_cast. (type.4: http://go.microsoft.com/fwlink/p/?LinkID=620420)\n#pragma warning(disable: 26494) // warning C26494: Variable '%s' is uninitialized. Always initialize an object. (type.5: http://go.microsoft.com/fwlink/p/?LinkID=620421)\n#pragma warning(disable: 26495) // warning C26495: Variable '%s' is uninitialized. Always initialize a member variable. (type.6: http://go.microsoft.com/fwlink/p/?LinkID=620422)\n#pragma warning(disable: 26496) // warning C26496: Variable '%s' is assigned only once, mark it as const. (con.4: https://go.microsoft.com/fwlink/p/?LinkID=784969)\n#pragma warning(disable: 26497) // warning C26497: This function %s could be marked constexpr if compile-time evaluation is desired. (f.4: https://go.microsoft.com/fwlink/p/?LinkID=784970)\n\n#else\n\n// linux warnings go here\n\n#endif\n\n#include <cstddef>\n#include <map>\n#include <set>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <type_traits>\n#include <utility>\n#include <memory>\n#include <tuple>\n#include <thread>\n#include <cstdlib>\n#include <codecvt>\n\n#if defined(_MSC_VER)\n\n// disable additionally for third-party libraries\n#pragma warning(push)\n#pragma warning(disable: 4456) // warning C4456: declaration of '%s' hides previous local declaration\n#pragma warning(disable: 4458) // warning C4458: declaration of '%s' hides class member\n#pragma warning(disable: 4459) // warning C4459: declaration of '%s' hides global declaration\n#pragma warning(disable: 4702) // warning C4702: unreacha3eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeble code\n\n#include <CppCoreCheck\\Warnings.h>\n#pragma warning(disable: ALL_CPPCORECHECK_WARNINGS)\n\n#endif\n\n#ifndef BOOST_CONFIG_SUPPRESS_OUTDATED_MESSAGE\n#define BOOST_CONFIG_SUPPRESS_OUTDATED_MESSAGE\n#endif\n\n#include <boost/algorithm/string.hpp>\n#include <boost/xpressive/xpressive.hpp>\n\n#include <gsl/gsl>\n\n#include <fmt/format.h>\n\n#if defined(_MSC_VER)\n\n#pragma warning(pop)\n#pragma warning(pop)\n\n#else\n\n// linux warning restoration goes here\n\n#endif\n\n#endif\n\n", "meta": {"hexsha": "be0f69a5a8b08f4eefe44903c18d7986446db67a", "size": 9243, "ext": "h", "lang": "C", "max_stars_repo_path": "libcpuid/tests/src/cpuid/stdafx.h", "max_stars_repo_name": "DrPizza/cpuid", "max_stars_repo_head_hexsha": "f8901c5c7b9a4a62f550d835a2a14fc6eec147e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-03-06T08:00:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-29T06:46:39.000Z", "max_issues_repo_path": "libcpuid/tests/src/cpuid/stdafx.h", "max_issues_repo_name": "DrPizza/cpuid", "max_issues_repo_head_hexsha": "f8901c5c7b9a4a62f550d835a2a14fc6eec147e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libcpuid/tests/src/cpuid/stdafx.h", "max_forks_repo_name": "DrPizza/cpuid", "max_forks_repo_head_hexsha": "f8901c5c7b9a4a62f550d835a2a14fc6eec147e5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.6807228916, "max_line_length": 256, "alphanum_fraction": 0.770637239, "num_tokens": 2457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.03410042767554473, "lm_q2_score": 0.019124035213525827, "lm_q1q2_score": 0.000652137779663408}}
{"text": "/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */\n/*\n *     Copyright 2018 Couchbase, Inc.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n */\n\n#pragma once\n\n#include \"engine_error.h\"\n#include \"types.h\"\n\n#include <gsl/gsl>\n\nnamespace cb {\nnamespace audit {\nnamespace document {\nenum class Operation;\n}\n} // namespace audit\n} // namespace cb\n\nstruct ServerDocumentIface {\n    virtual ~ServerDocumentIface() = default;\n\n    /**\n     * This callback is called from the underlying engine right before\n     * it is linked into the list of available documents (it is currently\n     * not visible to anyone). The engine should have validated all\n     * properties set in the document by the client and the core, and\n     * assigned a new CAS number for the document (and sequence number if\n     * the underlying engine use those).\n     *\n     * The callback may at this time do post processing of the document\n     * content (it is allowed to modify the content data, but not\n     * reallocate or change the size of the data in any way).\n     *\n     * Given that the engine MAY HOLD LOCKS when calling this function\n     * the core is *NOT* allowed to acquire *ANY* locks (except for doing\n     * some sort of memory allocation for a temporary buffer).\n     *\n     * @param cookie The cookie provided to the engine for the storage\n     *               command which may (which may hold more context)\n     * @param info the items underlying data\n     * @return ENGINE_SUCCESS means that the underlying engine should\n     *                        proceed to link the item. All other\n     *                        error codes means that the engine should\n     *                        *NOT* link the item\n     */\n    virtual ENGINE_ERROR_CODE pre_link(gsl::not_null<const void*> cookie,\n                                       item_info& info) = 0;\n\n    /**\n     * This callback is called from the underlying engine right before\n     * a particular document expires. The callback is responsible examining\n     * the value and possibly returning a new and modified value.\n     *\n     * @param itm_info info pertaining to the item that is to be expired.\n     * @return std::string empty if the value required no modification, not\n     *         empty then the string contains the modified value. When not empty\n     *         the datatype of the new value is datatype xattr only.\n     *\n     * @throws std::bad_alloc in case of memory allocation failure\n     */\n    virtual std::string pre_expiry(const item_info& itm_info) = 0;\n\n    /**\n     * Add an entry to the audit trail for access to the document specified\n     * in the key for this cookie.\n     *\n     * @param cookie The cookie representing the operation\n     * @param operation The type of access for the operation\n     */\n    virtual void audit_document_access(\n            gsl::not_null<const void*> cookie,\n            cb::audit::document::Operation operation) = 0;\n};\n", "meta": {"hexsha": "d6ea0c7208fa1f3c304a500243ce2b008586588a", "size": 3478, "ext": "h", "lang": "C", "max_stars_repo_path": "include/memcached/server_document_iface.h", "max_stars_repo_name": "hrajput89/kv_engine", "max_stars_repo_head_hexsha": "33fb1ab2c9787f55555e5f7edea38807b3dbc371", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-13T07:33:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-13T07:33:09.000Z", "max_issues_repo_path": "include/memcached/server_document_iface.h", "max_issues_repo_name": "paolococchi/kv_engine", "max_issues_repo_head_hexsha": "40256dca6bf77fb4bcc18e8ef7d9b8f991bf4e45", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/memcached/server_document_iface.h", "max_forks_repo_name": "paolococchi/kv_engine", "max_forks_repo_head_hexsha": "40256dca6bf77fb4bcc18e8ef7d9b8f991bf4e45", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-10-11T14:00:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-06T09:20:15.000Z", "avg_line_length": 39.5227272727, "max_line_length": 80, "alphanum_fraction": 0.6627372053, "num_tokens": 758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.03676946607559874, "lm_q2_score": 0.017712296985821024, "lm_q1q2_score": 0.000651271703141076}}
{"text": "#include \"snd.h\"\n#include \"clm2xen.h\"\n\n/* Snd defines its own exit and delay\n *\n *   In Ruby, rand is kernel_rand.\n *\n *   In Forth, Snd's exit is named snd-exit.\n */\n\n\n/* -------- protect XEN vars from GC -------- */\n\n#if HAVE_SCHEME\n\nint snd_protect(XEN obj) {return(s7_gc_protect(s7, obj));}\nvoid snd_unprotect_at(int loc) {s7_gc_unprotect_at(s7, loc);}\nXEN snd_protected_at(int loc) {return(s7_gc_protected_at(s7, loc));}\n\n#else\nstatic XEN gc_protection;\nstatic int gc_protection_size = 0;\n#define DEFAULT_GC_VALUE XEN_UNDEFINED\nstatic int gc_last_cleared = NOT_A_GC_LOC;\nstatic int gc_last_set = NOT_A_GC_LOC;\n\nint snd_protect(XEN obj)\n{\n  int i, old_size;\n  XEN tmp;\n  \n  if (gc_protection_size == 0)\n    {\n      gc_protection_size = 512;\n      gc_protection = XEN_MAKE_VECTOR(gc_protection_size, DEFAULT_GC_VALUE);\n      XEN_PROTECT_FROM_GC(gc_protection);\n      XEN_VECTOR_SET(gc_protection, 0, obj);\n      gc_last_set = 0;\n    }\n  else\n    {\n      if ((gc_last_cleared >= 0) && \n\t  XEN_EQ_P(XEN_VECTOR_REF(gc_protection, gc_last_cleared), DEFAULT_GC_VALUE))\n\t{\n\t  /* we hit this branch about 2/3 of the time */\n\t  XEN_VECTOR_SET(gc_protection, gc_last_cleared, obj);\n\t  gc_last_set = gc_last_cleared;\n\t  gc_last_cleared = NOT_A_GC_LOC;\n\n\t  return(gc_last_set);\n\t}\n\n      for (i = gc_last_set; i < gc_protection_size; i++)\n\tif (XEN_EQ_P(XEN_VECTOR_REF(gc_protection, i), DEFAULT_GC_VALUE))\n\t  {\n\t    XEN_VECTOR_SET(gc_protection, i, obj);\n\t    gc_last_set = i;\n\t    \n\t    return(gc_last_set);\n\t  }\n\n      for (i = 0; i < gc_last_set; i++)\n\tif (XEN_EQ_P(XEN_VECTOR_REF(gc_protection, i), DEFAULT_GC_VALUE))\n\t  {\n\t    /* here we average 3 checks before a hit, so this isn't as bad as it looks */\n\t    XEN_VECTOR_SET(gc_protection, i, obj);\n\t    gc_last_set = i;\n\n\t    return(gc_last_set);\n\t  }\n\n      tmp = gc_protection;\n      old_size = gc_protection_size;\n      gc_protection_size *= 2;\n      gc_protection = XEN_MAKE_VECTOR(gc_protection_size, DEFAULT_GC_VALUE);\n      XEN_PROTECT_FROM_GC(gc_protection);\n\n      for (i = 0; i < old_size; i++)\n\t{\n\t  XEN_VECTOR_SET(gc_protection, i, XEN_VECTOR_REF(tmp, i));\n\t  XEN_VECTOR_SET(tmp, i, DEFAULT_GC_VALUE);\n\t}\n\n      XEN_VECTOR_SET(gc_protection, old_size, obj);\n\n      /*   in Ruby, I think we can unprotect it */\n#if HAVE_RUBY || HAVE_FORTH\n      XEN_UNPROTECT_FROM_GC(tmp);\n#endif\n      gc_last_set = old_size;\n    }\n  return(gc_last_set);\n}\n\n\nvoid snd_unprotect_at(int loc)\n{\n  if (loc >= 0)\n    {\n      XEN_VECTOR_SET(gc_protection, loc, DEFAULT_GC_VALUE);\n      gc_last_cleared = loc;\n    }\n}\n\n\nXEN snd_protected_at(int loc)\n{\n  if (loc >= 0)\n    return(XEN_VECTOR_REF(gc_protection, loc));\n  return(DEFAULT_GC_VALUE);\n}\n#endif\n\n\n/* -------- error handling -------- */\n\nstatic char *last_file_loaded = NULL;\n\n#if HAVE_SCHEME\nstatic XEN g_snd_s7_error_handler(XEN args)\n{\n  s7_pointer msg;\n  msg = s7_car(args);\n  XEN_ASSERT_TYPE(XEN_STRING_P(msg), msg, XEN_ONLY_ARG, \"_snd_s7_error_handler_\", \"a string\");\n\n#if MUS_DEBUGGING\n  fprintf(stderr, \"error: %s\\n\", s7_object_to_c_string(s7, args));\n#endif\n\n  if (ss->xen_error_handler)\n    (*(ss->xen_error_handler))(s7_string(msg), (void *)any_selected_sound()); /* not NULL! */\n  return(s7_f(s7));\n}\n#endif\n\n\nvoid redirect_xen_error_to(void (*handler)(const char *msg, void *ufd), void *data)\n{\n  ss->xen_error_handler = handler;\n  ss->xen_error_data = data;\n\n#if HAVE_SCHEME\n  if (handler == NULL)\n    s7_eval_c_string(s7, \"(set! (hook-functions *error-hook*) '())\");\n  else s7_eval_c_string(s7, \"(set! (hook-functions *error-hook*) (list               \\n\\\n                               (lambda (tag args)                                    \\n\\\n                                 (_snd_s7_error_handler_                             \\n\\\n                                   (string-append                                    \\n\\\n                                     (if (string? args)                              \\n\\\n                                         args                                        \\n\\\n                                         (if (pair? args)                            \\n\\\n                                             (apply format #f (car args) (cdr args)) \\n\\\n                                             \\\"\\\"))                                  \\n\\\n                                     (if (and (*error-info* 2)                       \\n\\\n                                              (string? (*error-info* 4))             \\n\\\n                                              (number? (*error-info* 3)))            \\n\\\n                                         (format #f \\\"~%~S[~D]: ~A~%\\\"               \\n\\\n                                                 (*error-info* 4)                    \\n\\\n                                                 (*error-info* 3)                    \\n\\\n                                                 (*error-info* 2))                   \\n\\\n                                         \\\"\\\"))))))\");\n#endif\n}\n\n\nvoid redirect_snd_print_to(void (*handler)(const char *msg, void *ufd), void *data)\n{\n  ss->snd_print_handler = handler;\n  ss->snd_print_data = data;\n}\n\n\nvoid redirect_everything_to(void (*handler)(const char *msg, void *ufd), void *data)\n{\n  redirect_snd_error_to(handler, data);\n  redirect_xen_error_to(handler, data);\n  redirect_snd_warning_to(handler, data);\n  redirect_snd_print_to(handler, data);\n}\n\n\nvoid redirect_errors_to(void (*handler)(const char *msg, void *ufd), void *data)\n{\n  redirect_snd_error_to(handler, data);\n  redirect_xen_error_to(handler, data);\n  redirect_snd_warning_to(handler, data);\n}\n\n\nstatic char *gl_print(XEN result);\n\n\n/* ---------------- RUBY error handler ---------------- */\n\n#if HAVE_RUBY\nstatic XEN snd_format_if_needed(XEN args)\n{\n  /* if car has formatting info, use next arg as arg list for it */\n  XEN format_args = XEN_EMPTY_LIST, cur_arg, result;\n  int i, start = 0, num_args, format_info_len, err_size = 8192;\n  bool got_tilde = false, was_formatted = false;\n  char *format_info = NULL, *errmsg = NULL;\n\n  num_args = XEN_LIST_LENGTH(args);\n  if (num_args == 1) return(XEN_CAR(args));\n\n  format_info = mus_strdup(XEN_TO_C_STRING(XEN_CAR(args)));\n  format_info_len = mus_strlen(format_info);\n\n  if (XEN_LIST_P(XEN_CADR(args)))\n    format_args = XEN_COPY_ARG(XEN_CADR(args)); /* protect Ruby case */\n  else format_args = XEN_CADR(args);\n\n  errmsg = (char *)calloc(err_size, sizeof(char));\n\n  for (i = 0; i < format_info_len; i++)\n    {\n      if (format_info[i] == '~')\n\t{\n\t  strncat(errmsg, (char *)(format_info + start), i - start);\n\t  start = i + 2;\n\t  got_tilde = true;\n\t}\n      else\n\t{\n\t  if (got_tilde)\n\t    {\n\t      was_formatted = true;\n\t      got_tilde = false;\n\t      switch (format_info[i])\n\t\t{\n\t\tcase '~': errmsg = mus_strcat(errmsg, \"~\", &err_size); break;\n\t\tcase '%': errmsg = mus_strcat(errmsg, \"\\n\", &err_size); break;\n\t\tcase 'S': \n\t\tcase 'A':\n\t\t  if (XEN_NOT_NULL_P(format_args))\n\t\t    {\n\t\t      cur_arg = XEN_CAR(format_args);\n\t\t      format_args = XEN_CDR(format_args);\n\t\t      if (XEN_VECTOR_P(cur_arg))\n\t\t\t{\n\t\t\t  char *vstr;\n\t\t\t  vstr = gl_print(cur_arg);\n\t\t\t  errmsg = mus_strcat(errmsg, vstr, &err_size);\n\t\t\t  free(vstr);\n\t\t\t}\n\t\t      else\n\t\t\t{\n\t\t\t  char *temp = NULL;\n\t\t\t  errmsg = mus_strcat(errmsg, temp = (char *)XEN_AS_STRING(cur_arg), &err_size);\n\t\t\t}\n\t\t    }\n\t\t  /* else ignore it */\n\t\t  break;\n\t\tdefault: start = i - 1; break;\n\t\t}\n\t    }\n\t}\n    }\n  if (i > start)\n    strncat(errmsg, (char *)(format_info + start), i - start);\n  if (format_info) free(format_info);\n  if (!was_formatted)\n    {\n      char *temp = NULL;\n      errmsg = mus_strcat(errmsg, \" \", &err_size);\n      errmsg = mus_strcat(errmsg, temp = (char *)XEN_AS_STRING(XEN_CADR(args)), &err_size);\n    }\n  if (num_args > 2)\n    {\n      if ((!was_formatted) || (!(XEN_FALSE_P(XEN_CADDR(args))))) start = 2; else start = 3;\n      for (i = start; i < num_args; i++)\n\t{\n\t  char *temp = NULL;\n\t  errmsg = mus_strcat(errmsg, \" \", &err_size);\n\t  errmsg = mus_strcat(errmsg, temp = (char *)XEN_AS_STRING(XEN_LIST_REF(args, i)), &err_size);\n\t}\n    }\n  result = C_TO_XEN_STRING(errmsg);\n  free(errmsg);\n  return(result);\n}\n\n\nvoid snd_rb_raise(XEN tag, XEN throw_args)\n{\n  static char *msg = NULL;\n  XEN err = rb_eStandardError, bt;\n  bool need_comma = false;\n  int size = 2048;\n\n  if (strcmp(rb_id2name(tag), \"Out_of_range\") == 0) \n    err = rb_eRangeError;\n  else\n    if (strcmp(rb_id2name(tag), \"Wrong_type_arg\") == 0) \n      err = rb_eTypeError;\n\n  if (msg) free(msg);\n  msg = (char *)calloc(size, sizeof(char));\n\n  if ((XEN_LIST_P(throw_args)) && \n      (XEN_LIST_LENGTH(throw_args) > 0))\n    {\n      /* normally car is string name of calling func */\n      if (XEN_NOT_FALSE_P(XEN_CAR(throw_args)))\n\t{\n\t  snprintf(msg, size, \"%s: %s\", \n\t\t   XEN_AS_STRING(XEN_CAR(throw_args)), \n\t\t   rb_id2name(tag));\n\t  need_comma = true;\n\t}\n\n      if (XEN_LIST_LENGTH(throw_args) > 1)\n\t{\n\t  /* here XEN_CADR can contain formatting info and XEN_CADDR is a list of args to fit in */\n\t  /* or it may be a list of info vars etc */\n\n\t  if (need_comma) \n\t    msg = mus_strcat(msg, \": \", &size); /* new size, if realloc, reported through size arg */\n\n\t  if (XEN_STRING_P(XEN_CADR(throw_args)))\n\t    msg = mus_strcat(msg, XEN_TO_C_STRING(snd_format_if_needed(XEN_CDR(throw_args))), &size);\n\t  else msg = mus_strcat(msg, XEN_AS_STRING(XEN_CDR(throw_args)), &size);\n\t}\n    }\n\n  bt = rb_funcall(err, rb_intern(\"caller\"), 0); \n\n  if (XEN_VECTOR_P(bt) && XEN_VECTOR_LENGTH(bt) > 0) \n    {\n      int i; \n      msg = mus_strcat(msg, \"\\n\", &size); \n      for (i = 0; i < XEN_VECTOR_LENGTH(bt); i++) \n\t{ \n\t  msg = mus_strcat(msg, XEN_TO_C_STRING(XEN_VECTOR_REF(bt, i)), &size); \n\t  msg = mus_strcat(msg, \"\\n\", &size); \n\t} \n    }\n\n  if (strcmp(rb_id2name(tag), \"Snd_error\") != 0)\n    {\n      if (!(run_snd_error_hook(msg)))\n\t{\n\t  if (ss->xen_error_handler)\n\t    {\n\t      /* make sure it doesn't call itself recursively */\n\t      void (*old_xen_error_handler)(const char *msg, void *data);\n\t      void *old_xen_error_data;\n\t      old_xen_error_handler = ss->xen_error_handler;\n\t      old_xen_error_data = ss->xen_error_data;\n\t      ss->xen_error_handler = NULL;\n\t      ss->xen_error_data = NULL;\n\t      (*(old_xen_error_handler))(msg, old_xen_error_data);\n\t      ss->xen_error_handler = old_xen_error_handler;\n\t      ss->xen_error_data = old_xen_error_data;\n\t    }\n\t}\n    }\n\n  rb_raise(err, msg);\n}\n#endif\n/* end HAVE_RUBY */\n\n\n\n#if HAVE_EXTENSION_LANGUAGE\n\nXEN snd_catch_any(XEN_CATCH_BODY_TYPE body, void *body_data, const char *caller)\n{\n  return((*body)(body_data));\n}\n\n#else\n\n/* no extension language but user managed to try to evaluate something -- one way is to\n *   activate the minibuffer (via click) and type an expression into it\n */\nXEN snd_catch_any(XEN_CATCH_BODY_TYPE body, void *body_data, const char *caller)\n{\n  snd_error(\"This version of Snd has no extension language, so there's no way for %s to evaluate anything\", caller);\n  return(XEN_FALSE);\n}\n#endif\n\n\nbool procedure_arity_ok(XEN proc, int args)\n{\n  XEN arity;\n  int rargs;\n  arity = XEN_ARITY(proc);\n\n#if HAVE_RUBY\n  rargs = XEN_TO_C_INT(arity);\n  return(xen_rb_arity_ok(rargs, args));\n#endif\n\n#if HAVE_FORTH\n  rargs = XEN_TO_C_INT(arity);\n  if (rargs != args)\n    return(false);\n#endif\n\n#if HAVE_SCHEME\n  {\n    int oargs, restargs, gc_loc;\n\n    gc_loc = s7_gc_protect(s7, arity);\n    rargs = XEN_TO_C_INT(XEN_CAR(arity));\n    oargs = XEN_TO_C_INT(XEN_CADR(arity));\n    restargs = ((XEN_TRUE_P(XEN_CADDR(arity))) ? 1 : 0);\n    s7_gc_unprotect_at(s7, gc_loc);\n\n    if (rargs > args) return(false);\n    if ((restargs == 0) && ((rargs + oargs) < args)) return(false);\n  }\n#endif\n\n  return(true);\n}\n\n\nchar *procedure_ok(XEN proc, int args, const char *caller, const char *arg_name, int argn)\n{\n  /* if string returned, needs to be freed */\n  /* 0 args is special => \"thunk\" meaning in this case that optional args are not ok (applies to as-one-edit and two menu callbacks) */\n  XEN arity;\n  int rargs;\n\n  if (!(XEN_PROCEDURE_P(proc)))\n    {\n      if (XEN_NOT_FALSE_P(proc)) /* #f as explicit arg to clear */\n\t{\n\t  char *temp = NULL, *str;\n\t  str = mus_format(\"%s: %s (%s arg %d) is not a procedure!\", \n\t\t\t   temp = (char *)XEN_AS_STRING(proc),\n\t\t\t   arg_name, caller, argn);\n#if HAVE_SCHEME\n\t  if (temp) free(temp);\n#endif\n\t  return(str);\n\t}\n    }\n  else\n    {\n      arity = XEN_ARITY(proc);\n\n#if HAVE_RUBY\n      rargs = XEN_TO_C_INT(arity);\n      if (!xen_rb_arity_ok(rargs, args))\n \treturn(mus_format(\"%s function (%s arg %d) should take %d args, not %d\",\n \t\t\t  arg_name, caller, argn, args, (rargs < 0) ? (-rargs) : rargs));\n#endif\n\n#if HAVE_SCHEME\n      {\n\tint oargs, restargs;\n\tint loc;\n\n\tloc = snd_protect(arity);\n\trargs = XEN_TO_C_INT(XEN_CAR(arity));\n\toargs = XEN_TO_C_INT(XEN_CADR(arity));\n\trestargs = ((XEN_TRUE_P(XEN_CADDR(arity))) ? 1 : 0);\n\tsnd_unprotect_at(loc);\n\n\tif (rargs > args)\n\t  return(mus_format(\"%s function (%s arg %d) should take %d argument%s, but instead requires %d\",\n\t\t\t    arg_name, caller, argn, args, (args != 1) ? \"s\" : \"\", rargs));\n\n\tif ((restargs == 0) && ((rargs + oargs) < args))\n\t  return(mus_format(\"%s function (%s arg %d) should accept at least %d argument%s, but instead accepts only %d\",\n\t\t\t    arg_name, caller, argn, args, (args != 1) ? \"s\" : \"\", rargs + oargs));\n\n\tif ((args == 0) &&\n\t    ((rargs != 0) || (oargs != 0) || (restargs != 0)))\n\t  return(mus_format(\"%s function (%s arg %d) should take no args, not %d\", \n\t\t\t    arg_name, caller, argn, rargs + oargs + restargs));\n      }\n#endif\n\n#if HAVE_FORTH\n      rargs = XEN_TO_C_INT(arity);\n      if (rargs != args)\n\treturn(mus_format(\"%s function (%s arg %d) should take %d args, not %d\",\n\t\t\t  arg_name, caller, argn, args, rargs));\n#endif\n    }\n  return(NULL);\n}\n\n\nXEN snd_no_such_file_error(const char *caller, XEN filename)\n{\n  XEN_ERROR(NO_SUCH_FILE,\n\t    XEN_LIST_4(C_TO_XEN_STRING(\"no-such-file: ~A ~S: ~A\"),\n\t\t       C_TO_XEN_STRING(caller),\n\t\t       filename,\n\t\t       C_TO_XEN_STRING(snd_open_strerror())));\n  return(XEN_FALSE);\n}\n\n\nXEN snd_no_such_channel_error(const char *caller, XEN snd, XEN chn)\n{\n  int index = NOT_A_SOUND;\n  snd_info *sp;\n\n  if (XEN_INTEGER_P(snd))\n    index = XEN_TO_C_INT(snd);\n  else\n    {\n      if (XEN_SOUND_P(snd))\n\tindex = XEN_SOUND_TO_C_INT(snd);\n    }\n\n  if ((index >= 0) &&\n      (index < ss->max_sounds) && \n      (snd_ok(ss->sounds[index]))) /* good grief... */\n    {\n      sp = ss->sounds[index];\n      XEN_ERROR(NO_SUCH_CHANNEL,\n\t\tXEN_LIST_6(C_TO_XEN_STRING(\"no-such-channel: (~A: sound: ~A, chan: ~A) (~S, chans: ~A))\"),\n\t\t\t   C_TO_XEN_STRING(caller),\n\t\t\t   snd, \n\t\t\t   chn, \n\t\t\t   C_TO_XEN_STRING(sp->short_filename), \n\t\t\t   C_TO_XEN_INT(sp->nchans)));\n    }\n  XEN_ERROR(NO_SUCH_CHANNEL,\n\t    XEN_LIST_4(C_TO_XEN_STRING(\"no-such-channel: (~A: sound: ~A, chan: ~A)\"),\n\t\t       C_TO_XEN_STRING(caller),\n\t\t       snd,\n\t\t       chn));\n  return(XEN_FALSE);\n}\n\n\nXEN snd_no_active_selection_error(const char *caller)\n{\n  XEN_ERROR(XEN_ERROR_TYPE(\"no-active-selection\"),\n\t    XEN_LIST_2(C_TO_XEN_STRING(\"~A: no active selection\"),\n\t\t       C_TO_XEN_STRING(caller)));\n  return(XEN_FALSE);\n}\n\n\nXEN snd_bad_arity_error(const char *caller, XEN errstr, XEN proc)\n{\n  XEN_ERROR(XEN_ERROR_TYPE(\"bad-arity\"),\n            XEN_LIST_3(C_TO_XEN_STRING(\"~A,~A\"),\n\t\t       C_TO_XEN_STRING(caller),\n                       errstr));\n  return(XEN_FALSE);\n}\n\n\n\n/* -------- various evaluators (within our error handler) -------- */\n\nXEN eval_str_wrapper(void *data)\n{\n  return(XEN_EVAL_C_STRING((char *)data));\n}\n\n\n#if (!HAVE_SCHEME)\nXEN eval_form_wrapper(void *data)\n{\n  return(XEN_EVAL_FORM((XEN)data));\n}\n#else\nXEN eval_form_wrapper(void *data)\n{\n  return(XEN_FALSE);\n}\n#endif\n\n\nstatic XEN string_to_form_1(void *data)\n{\n  return(C_STRING_TO_XEN_FORM((char *)data));\n}\n\n\nXEN string_to_form(const char *str)\n{\n  return(snd_catch_any(string_to_form_1, (void *)str, str));  /* catch needed else #< in input (or incomplete form) exits Snd! */\n}\n\n\nstatic XEN eval_file_wrapper(void *data)\n{\n  XEN error;\n  last_file_loaded = (char *)data;\n  error = XEN_LOAD_FILE((char *)data); /* error only meaningful in Ruby */\n  last_file_loaded = NULL;\n  return(error);\n}\n\n\nstatic char *g_print_1(XEN obj) /* free return val */\n{\n#if HAVE_SCHEME\n  return(XEN_AS_STRING(obj)); \n#endif\n\n#if HAVE_FORTH || HAVE_RUBY\n  return(mus_strdup(XEN_AS_STRING(obj))); \n#endif\n\n#if (!HAVE_EXTENSION_LANGUAGE)\n  return(NULL);\n#endif\n}\n\n\nstatic char *gl_print(XEN result)\n{\n  char *newbuf = NULL, *str = NULL;\n  int i, ilen, savelen;\n\n#if HAVE_SCHEME\n  /* expand \\t first (neither gtk nor motif handles this automatically)\n   *   but... \"#\\\\t\" is the character t not a tab indication!\n   *   (object->string #\\t)\n   */\n  #define TAB_SPACES 4\n  int tabs = 0, len, j = 0;\n\n  newbuf = g_print_1(result);\n  len = mus_strlen(newbuf);\n\n  for (i = 0; i < len - 1; i++)\n    if (((i == 0) || (newbuf[i - 1] != '\\\\')) && \n\t(newbuf[i] == '\\\\') && \n\t(newbuf[i + 1] == 't'))\n      tabs++;\n\n  if (tabs == 0)\n    return(newbuf);\n\n  ilen = len + tabs * TAB_SPACES;\n  str = (char *)calloc(ilen, sizeof(char));\n\n  for (i = 0; i < len - 1; i++)\n    {\n      if (((i == 0) || (newbuf[i - 1] != '\\\\')) && \n\t  (newbuf[i] == '\\\\') && \n\t  (newbuf[i + 1] == 't'))\n\t{\n\t  int k;\n\t  for (k = 0; k < TAB_SPACES; k++)\n\t    str[j + k] = ' ';\n\t  j += TAB_SPACES;\n\t  i++;\n\t}\n      else str[j++] = newbuf[i];\n    }\n  str[j] = newbuf[len - 1];\n\n  free(newbuf);\n  return(str);\n#endif\n\n  /* specialize vectors which can be enormous in this context */\n  if ((!(XEN_VECTOR_P(result))) || \n      ((int)(XEN_VECTOR_LENGTH(result)) <= print_length(ss)))\n    return(g_print_1(result));\n\n  ilen = print_length(ss); \n  newbuf = (char *)calloc(128, sizeof(char));\n  savelen = 128;\n\n#if HAVE_FORTH\n  sprintf(newbuf, \"#(\"); \n#endif\n\n#if HAVE_RUBY\n  sprintf(newbuf, \"[\");\n#endif\n\n  for (i = 0; i < ilen; i++)\n    {\n      str = g_print_1(XEN_VECTOR_REF(result, i));\n      if ((str) && (*str)) \n\t{\n\t  if (i != 0) \n\t    {\n#if HAVE_RUBY\n\t      newbuf = mus_strcat(newbuf, \",\", &savelen);\n#endif\n\t      newbuf = mus_strcat(newbuf, \" \", &savelen); \n\t    }\n\t  newbuf = mus_strcat(newbuf, str, &savelen);\n\t  free(str);\n\t}\n    }\n\n#if HAVE_FORTH\n  newbuf = mus_strcat(newbuf, \" ...)\", &savelen);\n#endif\n\n#if HAVE_RUBY\n  newbuf = mus_strcat(newbuf, \" ...]\", &savelen);\n#endif\n\n  return(newbuf);\n}\n\n\nvoid snd_display_result(const char *str, const char *endstr)\n{\n  if (ss->snd_print_handler)\n    {\n      /* make sure it doesn't call itself recursively */\n      void (*old_snd_print_handler)(const char *msg, void *data);\n      void *old_snd_print_data;\n      old_snd_print_handler = ss->snd_print_handler;\n      old_snd_print_data = ss->snd_print_data;\n      ss->snd_print_handler = NULL;\n      ss->snd_print_data = NULL;\n      (*(old_snd_print_handler))(str, old_snd_print_data);\n      ss->snd_print_handler = old_snd_print_handler;\n      ss->snd_print_data = old_snd_print_data;\n    }\n  else\n    {\n      if (endstr) listener_append(endstr);\n      listener_append_and_prompt(str);\n    }\n}\n\n\nvoid snd_report_result(XEN result, const char *buf)\n{\n  char *str = NULL;\n  str = gl_print(result);\n  snd_display_result(str, buf);\n  if (str) free(str);\n}\n\n\nvoid snd_report_listener_result(XEN form)\n{\n  snd_report_result(form, \"\\n\");\n}\n\n\nstatic char *stdin_str = NULL;\n\nvoid clear_stdin(void)\n{\n  if (stdin_str) free(stdin_str);\n  stdin_str = NULL;\n}\n\n\nstatic char *stdin_check_for_full_expression(const char *newstr)\n{\n#if HAVE_SCHEME\n  int end_of_text;\n#endif\n  if (stdin_str)\n    {\n      char *str;\n      str = stdin_str;\n      stdin_str = (char *)calloc(mus_strlen(str) + mus_strlen(newstr) + 2, sizeof(char));\n      strcat(stdin_str, str);\n      strcat(stdin_str, newstr);\n      free(str);\n    }\n  else stdin_str = mus_strdup(newstr);\n#if HAVE_SCHEME\n  end_of_text = check_balance(stdin_str, 0, mus_strlen(stdin_str), false); /* last-arg->not in listener */\n  if (end_of_text > 0)\n    {\n      if (end_of_text + 1 < mus_strlen(stdin_str))\n\tstdin_str[end_of_text + 1] = 0;\n      return(stdin_str);\n    }\n  return(NULL);\n#endif\n  return(stdin_str);\n}\n\n\nstatic void string_to_stdout(const char *msg, void *ignored)\n{\n  fprintf(stdout, \"%s\\n\", msg);\n}\n\n\nvoid snd_eval_stdin_str(const char *buf)\n{\n  /* we may get incomplete expressions here */\n  /*   (Ilisp always sends a complete expression, but it may be broken into two or more pieces from read's point of view) */\n\n  char *str = NULL;\n  if (mus_strlen(buf) == 0) return;\n\n  str = stdin_check_for_full_expression(buf);\n  if (str)\n    {\n      XEN result;\n      int loc;\n\n      redirect_everything_to(string_to_stdout, NULL);\n      result = snd_catch_any(eval_str_wrapper, (void *)str, str);\n      redirect_everything_to(NULL, NULL);\n\n      loc = snd_protect(result);\n      if (stdin_str) free(stdin_str);\n      /* same as str here */\n      stdin_str = NULL;\n      str = gl_print(result);\n      string_to_stdout(str, NULL);\n\n      if (str) free(str);\n      snd_unprotect_at(loc);\n    }\n}\n\n\nstatic void string_to_stderr_and_listener(const char *msg, void *ignore)\n{\n  fprintf(stderr, \"%s\\n\", msg);\n  if (listener_exists()) /* the idea here is to save startup errors until we can post them */\n    {\n      listener_append((char *)msg);\n      listener_append(\"\\n\");\n    }\n  else \n    {\n      if (ss->startup_errors)\n\t{\n\t  char *temp;\n\t  temp = ss->startup_errors;\n\t  ss->startup_errors = mus_format(\"%s\\n%s %s\\n\", ss->startup_errors, listener_prompt(ss), msg);\n\t  free(temp);\n\t}\n      else ss->startup_errors = mus_strdup(msg); /* initial prompt is already there */\n    }\n}\n\n\nstatic bool snd_load_init_file_1(const char *filename)\n{\n  char *expr, *fullname;\n  bool happy = false;\n  fullname = mus_expand_filename(filename);\n  if (mus_file_probe(fullname))\n    {\n      happy = true;\n#if HAVE_SCHEME\n      expr = mus_format(\"(load %s)\", fullname);\n#endif\n\n#if HAVE_RUBY || HAVE_FORTH\n      expr = mus_format(\"load(%s)\", fullname);\n#endif\n      snd_catch_any(eval_file_wrapper, (void *)fullname, expr);\n      free(expr);\n    }\n\n  if (fullname) free(fullname);\n  return(happy);\n}\n\n\nvoid snd_load_init_file(bool no_global, bool no_init)\n{\n  /* look for \".snd\" on the home directory; return true if an error occurred (to try to get that info to the user's attention) */\n  /* called only in snd-g|xmain.c at initialization time */\n\n  /* changed Oct-05 because the Scheme/Ruby/Forth choices are becoming a hassle --\n   *   now save-options has its own file ~/.snd_prefs_ruby|forth|s7 which is loaded first, if present\n   *     then ~/.snd_ruby|forth|s7, if present\n   *     then ~/.snd for backwards compatibility\n   * snd_options does not write ~/.snd anymore, but overwrites the .snd_prefs_* file\n   * use set init files only change the ~/.snd choice\n   *\n   * there are parallel choices for the global configuration file: /etc/snd_ruby|forth|s7.conf\n   */\n\n#if HAVE_EXTENSION_LANGUAGE\n#if HAVE_RUBY\n  #define SND_EXT_CONF \"/etc/snd_ruby.conf\"\n  #define SND_PREFS \"~/.snd_prefs_ruby\"\n  #define SND_INIT \"~/.snd_ruby\"\n#endif\n\n#if HAVE_FORTH\n  #define SND_EXT_CONF \"/etc/snd_forth.conf\"\n  #define SND_PREFS \"~/.snd_prefs_forth\"\n  #define SND_INIT \"~/.snd_forth\"\n#endif\n\n#if HAVE_SCHEME\n  #define SND_EXT_CONF \"/etc/snd_s7.conf\"\n  #define SND_PREFS \"~/.snd_prefs_s7\"\n  #define SND_INIT \"~/.snd_s7\"\n#endif\n\n#define SND_INIT_FILE_ENVIRONMENT_NAME \"SND_INIT_FILE\"\n#if (!HAVE_WINDOZE)\n  #define INIT_FILE_NAME \"~/.snd\"\n#else\n  #define INIT_FILE_NAME \"snd-init\"\n#endif\n\n  #define SND_CONF \"/etc/snd.conf\"\n  redirect_snd_print_to(string_to_stdout, NULL);\n  redirect_errors_to(string_to_stderr_and_listener, NULL);\n\n  /* check for global configuration files (/etc/snd*) */\n  if (!no_global)\n    {\n      snd_load_init_file_1(SND_EXT_CONF);\n      snd_load_init_file_1(SND_CONF);\n    }\n\n  /* now load local init file(s) */\n  if (!no_init)\n    {\n      char *temp;\n      snd_load_init_file_1(SND_PREFS);  /* check for possible prefs dialog output */\n      snd_load_init_file_1(SND_INIT);\n      temp = getenv(SND_INIT_FILE_ENVIRONMENT_NAME);\n      if (temp)\n\tsnd_load_init_file_1(temp);\n      else snd_load_init_file_1(INIT_FILE_NAME);\n    }\n\n  redirect_everything_to(NULL, NULL);\n#endif\n}\n\n\nstatic char *find_source_file(const char *orig);\n\nvoid snd_load_file(const char *filename)\n{\n  char *str = NULL, *str2 = NULL;\n\n  str = mus_expand_filename(filename);\n  if (!(mus_file_probe(str)))\n    {\n      char *temp;\n      temp = find_source_file(str); \n      free(str);\n      str = temp;\n    }\n  if (!str)\n    {\n      snd_error(\"can't load %s: %s\", filename, snd_open_strerror());\n      return;\n    }\n\n  str2 = mus_format(\"(load \\\"%s\\\")\", filename);   /* currently unused in Forth and Ruby */\n  snd_catch_any(eval_file_wrapper, (void *)str, str2);\n  if (str) free(str);\n  if (str2) free(str2);\n}\n\n\nstatic XEN g_snd_print(XEN msg)\n{\n  #define H_snd_print \"(\" S_snd_print \" str): display str in the listener window\"\n  char *str = NULL;\n  if (XEN_STRING_P(msg))\n    str = mus_strdup(XEN_TO_C_STRING(msg));\n  else\n    {\n      if (XEN_CHAR_P(msg))\n\t{\n\t  str = (char *)calloc(2, sizeof(char));\n\t  str[0] = XEN_TO_C_CHAR(msg);\n\t}\n      else str = gl_print(msg);\n    }\n\n  if (str)\n    {\n      listener_append(str);\n      free(str);\n    }\n  /* used to check for event in Motif case, but that is very dangerous -- check for infinite loop C-c needs to be somewhere else */\n  return(msg);\n}\n\n\nstatic XEN print_hook;\n\nbool listener_print_p(const char *msg)\n{\n  static int print_depth = 0;\n  XEN res = XEN_FALSE;\n  if ((msg) && (print_depth == 0) && (mus_strlen(msg) > 0) && (XEN_HOOKED(print_hook)))\n    {\n      print_depth++;\n      res = run_or_hook(print_hook, \n\t\t\tXEN_LIST_1(C_TO_XEN_STRING(msg)),\n\t\t\tS_print_hook);\n      print_depth--;\n    }\n return(XEN_FALSE_P(res));\n}\n\n\nvoid check_features_list(const char *features)\n{\n  /* check for list of features, report any missing, exit (for compsnd) */\n  /*  this can't be in snd.c because we haven't fully initialized the extension language and so on at that point */\n  if (!features) return;\n\n#if HAVE_SCHEME\n  XEN_EVAL_C_STRING(mus_format(\"(for-each \\\n                                  (lambda (f)\t\\\n                                    (if (not (provided? f)) \\\n                                        (display (format #f \\\"~%%no ~A!~%%~%%\\\" f)))) \\\n                                  (list %s))\", features));\n#endif\n\n#if HAVE_RUBY\n  /* provided? is defined in examp.rb */\n  XEN_EVAL_C_STRING(mus_format(\"[%s].each do |f|\\n\\\n                                  unless $LOADED_FEATURES.map do |ff| File.basename(ff) end.member?(f.to_s.tr(\\\"_\\\", \\\"-\\\"))\\n\\\n                                    $stderr.printf(\\\"~\\\\nno %%s!\\\\n\\\\n\\\", f.id2name)\\n\\\n                                  end\\n\\\n                                end\\n\", features));\n#endif\n\n#if HAVE_FORTH\n  XEN_EVAL_C_STRING(mus_format(\"'( %s ) [each] dup \\\n                                          provided? [if] \\\n                                            drop \\\n                                          [else] \\\n                                            1 >list \\\"\\\\nno %%s!\\\\n\\\\n\\\" swap format .stderr \\\n                                          [then] \\\n                                        [end-each]\\n\", \n\t\t\t       features)); \n#endif\n  snd_exit(0);\n}\n\n\nmus_float_t string_to_mus_float_t(const char *str, mus_float_t lo, const char *field_name)\n{\n#if HAVE_EXTENSION_LANGUAGE\n  XEN res;\n  mus_float_t f;\n  res = snd_catch_any(eval_str_wrapper, (void *)str, \"string->float\");\n  if (XEN_NUMBER_P(res))\n    {\n      f = XEN_TO_C_DOUBLE(res);\n      if (f < lo)\n\tsnd_error(\"%s: %.3f is invalid\", field_name, f);\n      else return(f);\n    }\n  else snd_error(\"%s is not a number\", str);\n  return(0.0);\n#else\n  mus_float_t res = 0.0;\n  if (str) \n    {\n      if (!(sscanf(str, \"%f\", &res)))\n\tsnd_error(\"%s is not a number\", str);\n      else\n\t{\n\t  if (res < lo)\n\t    snd_error(\"%s: %.3f is invalid\", field_name, res);\n\t}\n    }\n  return(res);\n#endif\n}\n\n\nint string_to_int(const char *str, int lo, const char *field_name) \n{\n#if HAVE_EXTENSION_LANGUAGE\n  XEN res;\n  res = snd_catch_any(eval_str_wrapper, (void *)str, \"string->int\");\n  if (XEN_NUMBER_P(res))\n    {\n      int val;\n      val = XEN_TO_C_INT(res);\n      if (val < lo)\n\tsnd_error(\"%s: %d is invalid\", field_name, val);\n      else return(val);\n    }\n  else snd_error(\"%s: %s is not a number\", field_name, str);\n  return(0);\n#else\n  int res = 0;\n  if (str) \n    {\n      if (!(sscanf(str, \"%d\", &res)))\n\tsnd_error(\"%s: %s is not a number\", field_name, str);\n      else\n\t{\n\t  if (res < lo)\n\t    snd_error(\"%s: %d is invalid\", field_name, res);\n\t}\n    }\n  return(res);\n#endif\n}\n\n\nmus_long_t string_to_mus_long_t(const char *str, mus_long_t lo, const char *field_name)\n{\n#if HAVE_EXTENSION_LANGUAGE\n  XEN res;\n\n  res = snd_catch_any(eval_str_wrapper, (void *)str, \"string->mus_long_t\");\n  if (XEN_NUMBER_P(res))\n    {\n      mus_long_t val;\n      val = XEN_TO_C_INT64_T(res);\n      if (val < lo)\n\tsnd_error(\"%s: \" MUS_LD \" is invalid\", field_name, val);\n      else return(val);\n    }\n  else snd_error(\"%s: %s is not a number\", field_name, str);\n  return(0);\n#else\n  mus_long_t res = 0;\n  if (str) \n    {\n      if (!(sscanf(str, MUS_LD , &res)))\n\tsnd_error(\"%s: %s is not a number\", field_name, str);\n      else\n\t{\n\t  if (res < lo)\n\t    snd_error(\"%s: \" MUS_LD \" is invalid\", field_name, res);\n\t}\n    }\n  return(res);\n#endif\n}\n\n\nXEN run_progn_hook(XEN hook, XEN args, const char *caller)\n{\n#if HAVE_SCHEME\n  int gc_loc;\n#endif\n  XEN result = XEN_FALSE;\n  XEN procs = XEN_HOOK_PROCEDURES(hook);\n\n#if HAVE_SCHEME\n  gc_loc = s7_gc_protect(s7, args);\n  /* this gc protection is needed in s7 because the args are not s7 eval-assembled;\n   *   they are cons'd up in our C code, and applied here via s7_call, so between\n   *   s7_call's, they are not otherwise protected.  In normal function calls, the\n   *   args are on the sc->args list in the evaluator, and therefore protected.\n   */\n#endif\n\n  while (XEN_NOT_NULL_P(procs))\n    {\n      result = XEN_APPLY(XEN_CAR(procs), args, caller);\n      procs = XEN_CDR(procs);\n    }\n\n#if HAVE_SCHEME\n  s7_gc_unprotect_at(s7, gc_loc);\n#endif\n\n  return(result);\n}\n\n\nXEN run_hook(XEN hook, XEN args, const char *caller)\n{\n#if HAVE_SCHEME\n  int gc_loc;\n#endif\n  XEN procs = XEN_HOOK_PROCEDURES(hook);\n\n#if HAVE_SCHEME\n  gc_loc = s7_gc_protect(s7, args);\n#endif\n\n  while (XEN_NOT_NULL_P(procs))\n    {\n      if (!(XEN_EQ_P(args, XEN_EMPTY_LIST)))\n\tXEN_APPLY(XEN_CAR(procs), args, caller);\n      else XEN_CALL_0(XEN_CAR(procs), caller);\n      procs = XEN_CDR (procs);\n    }\n\n#if HAVE_SCHEME\n  s7_gc_unprotect_at(s7, gc_loc);\n#endif\n\n  return(XEN_FALSE);\n}\n\n\nXEN run_or_hook(XEN hook, XEN args, const char *caller)\n{\n#if HAVE_SCHEME\n  int gc_loc;\n#endif\n  XEN result = XEN_FALSE; /* (or): #f */\n  XEN hook_result = XEN_FALSE;\n  XEN procs = XEN_HOOK_PROCEDURES(hook);\n\n#if HAVE_SCHEME\n  gc_loc = s7_gc_protect(s7, args);\n#endif\n\n  while (XEN_NOT_NULL_P(procs))\n    {\n      if (!(XEN_EQ_P(args, XEN_EMPTY_LIST)))\n\tresult = XEN_APPLY(XEN_CAR(procs), args, caller);\n      else result = XEN_CALL_0(XEN_CAR(procs), caller);\n      if (XEN_NOT_FALSE_P(result)) \n        hook_result = result;\n      procs = XEN_CDR (procs);\n    }\n\n#if HAVE_SCHEME\n  s7_gc_unprotect_at(s7, gc_loc);\n#endif\n\n  return(hook_result);\n}\n\n\n\n#if HAVE_SCHEME && HAVE_DLFCN_H\n#include <dlfcn.h>\n/* these are included because libtool's dlopen is incredibly stupid */\n\nstatic XEN g_dlopen(XEN name)\n{\n  #define H_dlopen \"(dlopen lib) loads the dynamic library 'lib' and returns a handle for it (for dlinit and dlclose)\"\n  void *handle;\n  const char *cname;\n  XEN_ASSERT_TYPE(XEN_STRING_P(name), name, XEN_ONLY_ARG, \"dlopen\", \"a string (filename)\");\n  cname = XEN_TO_C_STRING(name);\n  if (cname)\n    {\n      handle = dlopen(cname, RTLD_LAZY);\n      if (handle == NULL)\n\t{\n\t  char *longname;\n\t  longname = mus_expand_filename(cname);\n\t  handle = dlopen(longname, RTLD_LAZY);\n\t  free(longname);\n\t  if (handle == NULL)\n\t    {\n\t      char *err;\n\t      err = (char *)dlerror();\n\t      if ((err) && (*err))\n\t\treturn(C_TO_XEN_STRING(err));\n\t      return(XEN_FALSE);\n\t    }\n\t}\n      return(XEN_WRAP_C_POINTER(handle));\n    }\n  return(XEN_FALSE);\n}\n\n\nstatic XEN g_dlclose(XEN handle)\n{\n  #define H_dlclose \"(dlclose handle) may close the library referred to by 'handle'.\"\n  XEN_ASSERT_TYPE(XEN_WRAPPED_C_POINTER_P(handle), handle, XEN_ONLY_ARG, \"dlclose\", \"a library handle\");\n  return(C_TO_XEN_INT(dlclose((void *)(XEN_UNWRAP_C_POINTER(handle)))));\n}\n\n\nstatic XEN g_dlerror(void)\n{\n  #define H_dlerror \"(dlerror) returns a string describing the last dlopen/dlinit/dlclose error\"\n  return(C_TO_XEN_STRING(dlerror()));\n}\n\n\nstatic XEN g_dlinit(XEN handle, XEN func)\n{\n  #define H_dlinit \"(dlinit handle func) calls 'func' from the library referred to by 'handle'.\"\n  typedef void *(*snd_dl_func)(void);\n  void *proc;\n\n  XEN_ASSERT_TYPE(XEN_WRAPPED_C_POINTER_P(handle), handle, XEN_ARG_1, \"dlinit\", \"a library handle\");\n  XEN_ASSERT_TYPE(XEN_STRING_P(func), func, XEN_ARG_2, \"dlinit\", \"a string (init func name)\");\n\n  proc = dlsym((void *)(XEN_UNWRAP_C_POINTER(handle)), XEN_TO_C_STRING(func));\n  if (proc == NULL) return(C_TO_XEN_STRING(dlerror()));\n  ((snd_dl_func)proc)();\n  return(XEN_TRUE);\n}\n\n#if 0\nstatic XEN g_dlinit(XEN handle, XEN func)\n{\n  /* 'man dlopen' suggests: double (*cosine)(double); *(void **) (&cosine) = dlsym(handle, \"cos\"); printf(\"%f\\n\", (*cosine)(2.0)); */\n  void (*proc)(void);\n  /* typedef void *(*snd_dl_func)(void); */\n  /* void *proc; */\n  (*(void **)(&proc)) = dlsym((void *)(XEN_UNWRAP_C_POINTER(handle)), XEN_TO_C_STRING(func));\n  /* but this line triggers warnings from gcc */\n  if (proc == NULL) return(C_TO_XEN_STRING(dlerror()));\n  /* ((snd_dl_func)proc)(); */\n  (*proc)();\n  return(XEN_TRUE);\n}\n#endif\n#endif\n\n\nstatic XEN g_little_endian(void)\n{\n#if MUS_LITTLE_ENDIAN\n  return(XEN_TRUE);\n#else\n  return(XEN_FALSE);\n#endif\n}\n\n\nstatic XEN g_snd_global_state(void)\n{\n  return(XEN_WRAP_C_POINTER(ss));\n}\n\n\n#if MUS_DEBUGGING\nstatic XEN g_snd_sound_pointer(XEN snd)\n{\n  /* (XtCallCallbacks (cadr (sound-widgets 0)) XmNactivateCallback (snd-sound-pointer 0)) */\n  int s;\n  s = XEN_TO_C_INT(snd);\n  if ((s < ss->max_sounds) && (s >= 0) && (ss->sounds[s]))\n    return(XEN_WRAP_C_POINTER(ss->sounds[s]));\n  return(XEN_FALSE);\n}\n#endif\n\n\n#if (!HAVE_SCHEME)\n/* fmod is the same as modulo in s7:\n   (do ((i 0 (+ i 1))) \n       ((= i 100)) \n     (let ((val1 (- (random 1.0) 2.0)) \n           (val2 (- (random 1.0) 2.0)))\n       (let ((f (fmod val1 val2)) \n             (m (modulo val1 val2))) \n         (if (> (abs (- f m)) 1e-9) \n             (format *stderr* \"~A ~A -> ~A ~A~%\" val1 val2 f m)))))\n*/\n\nstatic XEN g_fmod(XEN a, XEN b)\n{\n  double val, x, y;\n  XEN_ASSERT_TYPE(XEN_NUMBER_P(a), a, XEN_ARG_1, \"fmod\", \" a number\");\n  XEN_ASSERT_TYPE(XEN_NUMBER_P(b), b, XEN_ARG_2, \"fmod\", \" a number\");\n  x = XEN_TO_C_DOUBLE(a);\n  y = XEN_TO_C_DOUBLE(b);\n  val = fmod(x, y);\n  if (((y > 0.0) && (val < 0.0)) ||\n      ((y < 0.0) && (val > 0.0)))\n    return(C_TO_XEN_DOUBLE(val + y));\n  return(C_TO_XEN_DOUBLE(val));\n}\n#endif\n\n\n#if HAVE_SPECIAL_FUNCTIONS || HAVE_GSL\n#define S_bes_j0 \"bes-j0\"\n#define S_bes_j1 \"bes-j1\"\n#define S_bes_jn \"bes-jn\"\n#define S_bes_y0 \"bes-y0\"\n#define S_bes_y1 \"bes-y1\"\n#define S_bes_yn \"bes-yn\"\n#endif\n\n\n/* ---------------------------------------- use libm ---------------------------------------- */\n\n#if HAVE_SCHEME && WITH_GMP && HAVE_SPECIAL_FUNCTIONS\n\n#include <gmp.h>\n#include <mpfr.h>\n#include <mpc.h>\n\nstatic XEN big_math_1(XEN x, \n\t\t      int (*mpfr_math)(mpfr_ptr, mpfr_srcptr, mpfr_rnd_t))\n{\n  s7_pointer val;\n  mpfr_t y;\n  mpfr_init_set(y, *s7_big_real(x), GMP_RNDN);\n  mpfr_math(y, y, GMP_RNDN);\n  val = s7_make_big_real(s7, &y);\n  mpfr_clear(y);\n  return(val);\n}\n\n\nstatic XEN big_j0(XEN x) {return(big_math_1(x, mpfr_j0));}\nstatic XEN big_j1(XEN x) {return(big_math_1(x, mpfr_j1));}\nstatic XEN big_y0(XEN x) {return(big_math_1(x, mpfr_y0));}\nstatic XEN big_y1(XEN x) {return(big_math_1(x, mpfr_y1));}\n\nstatic XEN big_erf(XEN x) {return(big_math_1(x, mpfr_erf));}\nstatic XEN big_erfc(XEN x) {return(big_math_1(x, mpfr_erfc));}\n\n\nstatic XEN big_math_2(XEN n, XEN x, \n\t\t      int (*mpfr_math)(mpfr_ptr, long, mpfr_srcptr, mpfr_rnd_t))\n{\n  s7_pointer val;\n  mpfr_t y;\n  mpfr_init_set(y, *s7_big_real(x), GMP_RNDN);\n  mpfr_math(y, XEN_TO_C_INT(n), y, GMP_RNDN);\n  val = s7_make_big_real(s7, &y);\n  mpfr_clear(y);\n  return(val);\n}\n\n\nstatic XEN big_jn(XEN n, XEN x) {return(big_math_2(n, x, mpfr_jn));}\nstatic XEN big_yn(XEN n, XEN x) {return(big_math_2(n, x, mpfr_yn));}\n\n\n/* bes-i0 from G&R 8.447, 8.451, A&S 9.6.12, 9.7.1, arprec bessel.cpp */\n\nstatic XEN big_i0(XEN ux)\n{\n  int k;\n  mpfr_t sum, x, x1, x2, eps;\n  mpfr_init_set_ui(sum, 0, GMP_RNDN);\n  mpfr_init_set(x, *s7_big_real(ux), GMP_RNDN);\n  mpfr_init_set_ui(sum, 1, GMP_RNDN);\n  mpfr_init_set_ui(x1, 1, GMP_RNDN);\n  mpfr_init_set_ui(eps, 2, GMP_RNDN);\n  mpfr_pow_si(eps, eps, -mpfr_get_default_prec(), GMP_RNDN);\n  mpfr_init_set_ui(x2, mpfr_get_default_prec(), GMP_RNDN);\n  mpfr_div_ui(x2, x2, 2, GMP_RNDN);\n  if (mpfr_cmpabs(x, x2) < 0)\n    {\n      mpfr_mul(x, x, x, GMP_RNDN);           /* x = ux^2 */\n      for (k = 1; k < 10000; k++)\n\t{\n\t  mpfr_set_ui(x2, k, GMP_RNDN);      /* x2 = k */\n\t  mpfr_mul(x2, x2, x2, GMP_RNDN);    /* x2 = k^2 */\n\t  mpfr_div(x1, x1, x2, GMP_RNDN);    /* x1 = x1/x2 */\n\t  mpfr_mul(x1, x1, x, GMP_RNDN);     /* x1 = x1*x */\n\t  mpfr_div_ui(x1, x1, 4, GMP_RNDN);  /* x1 = x1/4 */\n\t  if (mpfr_cmp(x1, eps) < 0)\n\t    break;\n\t  mpfr_add(sum, sum, x1, GMP_RNDN);  /* sum += x1 */\n\t}\n      /* takes usually ca 10 to 40 iterations */\n    }\n  else\n    {\n      mpfr_t den, num;\n      mpfr_init(den);\n      mpfr_init(num);\n      mpfr_abs(x, x, GMP_RNDN);\n      for (k = 1; k < 10000; k++)\n\t{\n\t  mpfr_set(x2, x1, GMP_RNDN);\n\t  mpfr_set_ui(den, k, GMP_RNDN);\n\t  mpfr_mul_ui(den, den, 8, GMP_RNDN);\n\t  mpfr_mul(den, den, x, GMP_RNDN);\n\t  mpfr_set_ui(num, k, GMP_RNDN);\n\t  mpfr_mul_ui(num, num, 2, GMP_RNDN);\n\t  mpfr_sub_ui(num, num, 1, GMP_RNDN);\n\t  mpfr_mul(num, num, num, GMP_RNDN);\n\t  mpfr_div(num, num, den, GMP_RNDN);\n\t  mpfr_mul(x1, x1, num, GMP_RNDN);\n\t  mpfr_add(sum, sum, x1, GMP_RNDN);  \n\t  if (mpfr_cmp(x1, eps) < 0)\n\t    {\n\t      mpfr_const_pi(x2, GMP_RNDN);\n\t      mpfr_mul_ui(x2, x2, 2, GMP_RNDN);\n\t      mpfr_mul(x2, x2, x, GMP_RNDN);\n\t      mpfr_sqrt(x2, x2, GMP_RNDN);           /* sqrt(2*pi*x) */\n\t      mpfr_div(sum, sum, x2, GMP_RNDN);\n\t      mpfr_exp(x1, x, GMP_RNDN);\n\t      mpfr_mul(sum, sum, x1, GMP_RNDN);      /* sum * e^x / sqrt(2*pi*x) */\n\t      break;\n\t    }\n\t  if (mpfr_cmp(x1, x2) > 0)\n\t    {\n\t      fprintf(stderr, \"bes-i0 has screwed up\");\n\t      break;\n\t    }\n\t}\n      mpfr_clear(den);\n      mpfr_clear(num);\n    }\n  mpfr_clear(x1);\n  mpfr_clear(x2);\n  mpfr_clear(x);\n  mpfr_clear(eps);\n  return(s7_make_big_real(s7, &sum));\n}\n\n\n/* fft\n *     (define hi (make-vector 8))\n *     (define ho (make-vector 8))\n *     (do ((i 0 (+ i 1))) ((= i 8)) (vector-set! hi i (bignum \"0.0\")) (vector-set! ho i (bignum \"0.0\")))\n *     (vector-set! ho 1 (bignum \"-1.0\"))\n *     (vector-set! ho 1 (bignum \"-1.0\"))\n *     (bignum-fft hi ho 8)\n *\n * this is tricky -- perhaps a bad idea.  vector elements are changed in place which means\n *   they better be unique!  and there are no checks that each element actually is a bignum\n *   which means we'll segfault if a normal real leaks through.\n *\n * bignum_fft is say 200 times slower than the same size fftw call, and takes more space than\n *   I can account for: 2^20 29 secs ~.5 Gb, 2^24 11 mins ~5Gb.  I think there should be\n *   the vector element (8), the mpfr_t space (16 or 32), the s7_cell (28 or 32), and the value pointer (8),\n *   and the heap pointer loc (8) so 2^24 should be (* 2 (expt 2 24) (+ 8 8 8 8 32 32)) = 3 Gb, not 5.  2^25 25 min 10.6?\n *   I think the extra is in the free space in the heap -- it can be adding 1/4 of the total.\n */\n\nstatic s7_pointer bignum_fft(s7_scheme *sc, s7_pointer args)\n{\n  #define H_bignum_fft \"(bignum-fft rl im n (sign 1)) performs a multiprecision fft on the vectors of bigfloats rl and im\"\n\n  int n, sign = 1;\n  s7_pointer *rl, *im;\n\n  int m, j, mh, ldm, lg, i, i2, j2, imh;\n  mpfr_t ur, ui, u, vr, vi, angle, c, s, temp;\n\n  #define big_rl(n) (*(s7_big_real(rl[n])))\n  #define big_im(n) (*(s7_big_real(im[n])))\n\n  n = s7_integer(s7_list_ref(sc, args, 2));\n  if (s7_list_length(sc, args) > 3)\n    sign = s7_integer(s7_list_ref(sc, args, 3));\n\n  rl = s7_vector_elements(s7_list_ref(sc, args, 0));\n  im = s7_vector_elements(s7_list_ref(sc, args, 1));\n\n  /* scramble(rl, im, n); */\n  {\n    int i, m, j;\n    s7_pointer vr, vi;\n    j = 0;\n    for (i = 0; i < n; i++)\n      {\n\tif (j > i)\n\t  {\n\t    vr = rl[j];\n\t    vi = im[j];\n\t    rl[j] = rl[i];\n\t    im[j] = im[i];\n\t    rl[i] = vr;\n\t    im[i] = vi;\n\t  }\n\tm = n >> 1;\n\twhile ((m >= 2) && (j >= m))\n\t  {\n\t    j -= m;\n\t    m = m >> 1;\n\t  }\n\tj += m;\n      }\n  }\n\n  imh = (int)(log(n + 1) / log(2.0));\n  m = 2;\n  ldm = 1;\n  mh = n >> 1;\n\n  mpfr_init(angle);                        /* angle = (M_PI * sign) */\n  mpfr_const_pi(angle, GMP_RNDN);\n  if (sign == -1)\n    mpfr_neg(angle, angle, GMP_RNDN);\n\n  mpfr_init(c);\n  mpfr_init(s);\n  mpfr_init(ur);\n  mpfr_init(ui);\n  mpfr_init(u);\n  mpfr_init(vr);\n  mpfr_init(vi);\n  mpfr_init(temp);\n\n  for (lg = 0; lg < imh; lg++)\n    {\n      mpfr_cos(c, angle, GMP_RNDN);         /* c = cos(angle) */\n      mpfr_sin(s, angle, GMP_RNDN);         /* s = sin(angle) */\n      mpfr_set_ui(ur, 1, GMP_RNDN);         /* ur = 1.0 */\n      mpfr_set_ui(ui, 0, GMP_RNDN);         /* ui = 0.0 */\n      for (i2 = 0; i2 < ldm; i2++)\n\t{\n\t  i = i2;\n\t  j = i2 + ldm;\n\t  for (j2 = 0; j2 < mh; j2++)\n\t    {\n\t      mpfr_set(temp, big_im(j), GMP_RNDN);          /* vr = ur * rl[j] - ui * im[j] */\n\t      mpfr_mul(temp, temp, ui, GMP_RNDN);\n\t      mpfr_set(vr, big_rl(j), GMP_RNDN);\n\t      mpfr_mul(vr, vr, ur, GMP_RNDN);\n\t      mpfr_sub(vr, vr, temp, GMP_RNDN);\n\t      \n\t      mpfr_set(temp, big_rl(j), GMP_RNDN);          /* vi = ur * im[j] + ui * rl[j] */\n\t      mpfr_mul(temp, temp, ui, GMP_RNDN);\n\t      mpfr_set(vi, big_im(j), GMP_RNDN);\n\t      mpfr_mul(vi, vi, ur, GMP_RNDN);\n\t      mpfr_add(vi, vi, temp, GMP_RNDN);\n\t      \n\t      mpfr_set(big_rl(j), big_rl(i), GMP_RNDN);     /* rl[j] = rl[i] - vr */\n\t      mpfr_sub(big_rl(j), big_rl(j), vr, GMP_RNDN);\n\n\t      mpfr_set(big_im(j), big_im(i), GMP_RNDN);     /* im[j] = im[i] - vi */\n\t      mpfr_sub(big_im(j), big_im(j), vi, GMP_RNDN);\n\t      \n\t      mpfr_add(big_rl(i), big_rl(i), vr, GMP_RNDN); /* rl[i] += vr */\n\t      mpfr_add(big_im(i), big_im(i), vi, GMP_RNDN); /* im[i] += vi */\n\t      \n\t      i += m;\n\t      j += m;\n\t    }\n\n\t  mpfr_set(u, ur, GMP_RNDN);             /* u = ur */\n\t  mpfr_set(temp, ui, GMP_RNDN);          /* ur = (ur * c) - (ui * s) */\n\t  mpfr_mul(temp, temp, s, GMP_RNDN);\n\t  mpfr_mul(ur, ur, c, GMP_RNDN);\n\t  mpfr_sub(ur, ur, temp, GMP_RNDN);\n\t  \n\t  mpfr_set(temp, u, GMP_RNDN);           /* ui = (ui * c) + (u * s) */\n\t  mpfr_mul(temp, temp, s, GMP_RNDN);\n\t  mpfr_mul(ui, ui, c, GMP_RNDN);\n\t  mpfr_add(ui, ui, temp, GMP_RNDN);\n\t}\n      mh >>= 1;\n      ldm = m;\n\n      mpfr_div_ui(angle, angle, 2, GMP_RNDN);   /* angle *= 0.5 */\n      m <<= 1;\n    }\n  return(s7_f(sc));\n}\n\n#endif\n\n\n#if HAVE_SPECIAL_FUNCTIONS && (!HAVE_GSL)\nstatic XEN g_j0(XEN x)\n{\n  #define H_j0 \"(\" S_bes_j0 \" x): returns the regular cylindrical bessel function value J0(x)\"\n  XEN_ASSERT_TYPE(XEN_NUMBER_P(x), x, XEN_ONLY_ARG, S_bes_j0, \" a number\");\n\n#if HAVE_SCHEME && WITH_GMP\n  if ((s7_is_bignum(x)) &&\n      (s7_is_real(x)) &&\n      (!(s7_is_rational(x))))\n    return(big_j0(x));\n#endif\n  return(C_TO_XEN_DOUBLE(j0(XEN_TO_C_DOUBLE(x))));\n}\n\n\nstatic XEN g_j1(XEN x)\n{\n  #define H_j1 \"(\" S_bes_j1 \" x): returns the regular cylindrical bessel function value J1(x)\"\n  XEN_ASSERT_TYPE(XEN_NUMBER_P(x), x, XEN_ONLY_ARG, S_bes_j1, \" a number\");\n\n#if HAVE_SCHEME && WITH_GMP\n  if ((s7_is_bignum(x)) &&\n      (s7_is_real(x)) &&\n      (!(s7_is_rational(x))))\n    return(big_j1(x));\n#endif\n  return(C_TO_XEN_DOUBLE(j1(XEN_TO_C_DOUBLE(x))));\n}\n\n\nstatic XEN g_jn(XEN order, XEN x)\n{\n  #define H_jn \"(\" S_bes_jn \" n x): returns the regular cylindrical bessel function value Jn(x)\"\n  XEN_ASSERT_TYPE(XEN_INTEGER_P(order), x, XEN_ARG_1, S_bes_jn, \" an int\");\n  XEN_ASSERT_TYPE(XEN_NUMBER_P(x), x, XEN_ARG_2, S_bes_jn, \" a number\");\n\n#if HAVE_SCHEME && WITH_GMP\n  if ((s7_is_bignum(x)) &&\n      (s7_is_real(x)) &&\n      (!(s7_is_rational(x))))\n    return(big_jn(order, x));\n#endif\n  return(C_TO_XEN_DOUBLE(jn(XEN_TO_C_INT(order), XEN_TO_C_DOUBLE(x))));\n}\n\n\nstatic XEN g_y0(XEN x)\n{\n  #define H_y0 \"(\" S_bes_y0 \" x): returns the irregular cylindrical bessel function value Y0(x)\"\n  XEN_ASSERT_TYPE(XEN_NUMBER_P(x), x, XEN_ONLY_ARG, S_bes_y0, \" a number\");\n#if HAVE_SCHEME && WITH_GMP\n  if ((s7_is_bignum(x)) &&\n      (s7_is_real(x)) &&\n      (!(s7_is_rational(x))))\n    return(big_y0(x));\n#endif\n  return(C_TO_XEN_DOUBLE(y0(XEN_TO_C_DOUBLE(x))));\n}\n\n\nstatic XEN g_y1(XEN x)\n{\n  #define H_y1 \"(\" S_bes_y1 \" x): returns the irregular cylindrical bessel function value Y1(x)\"\n  XEN_ASSERT_TYPE(XEN_NUMBER_P(x), x, XEN_ONLY_ARG, S_bes_y1, \" a number\");\n#if HAVE_SCHEME && WITH_GMP\n  if ((s7_is_bignum(x)) &&\n      (s7_is_real(x)) &&\n      (!(s7_is_rational(x))))\n    return(big_y1(x));\n#endif\n  return(C_TO_XEN_DOUBLE(y1(XEN_TO_C_DOUBLE(x))));\n}\n\n\nstatic XEN g_yn(XEN order, XEN x)\n{\n  #define H_yn \"(\" S_bes_yn \" n x): returns the irregular cylindrical bessel function value Yn(x)\"\n  XEN_ASSERT_TYPE(XEN_INTEGER_P(order), x, XEN_ARG_1, S_bes_yn, \" an int\");\n  XEN_ASSERT_TYPE(XEN_NUMBER_P(x), x, XEN_ARG_2, S_bes_yn, \" a number\");\n#if HAVE_SCHEME && WITH_GMP\n  if ((s7_is_bignum(x)) &&\n      (s7_is_real(x)) &&\n      (!(s7_is_rational(x))))\n    return(big_yn(order, x));\n#endif\n  return(C_TO_XEN_DOUBLE(yn(XEN_TO_C_INT(order), XEN_TO_C_DOUBLE(x))));\n}\n\n\nstatic XEN g_erf(XEN x)\n{\n  #define H_erf \"(erf x): returns the error function erf(x)\"\n  XEN_ASSERT_TYPE(XEN_NUMBER_P(x), x, XEN_ONLY_ARG, \"erf\", \" a number\");\n#if HAVE_SCHEME && WITH_GMP\n  if ((s7_is_bignum(x)) &&\n      (s7_is_real(x)) &&\n      (!(s7_is_rational(x))))\n    return(big_erf(x));\n#endif\n  return(C_TO_XEN_DOUBLE(erf(XEN_TO_C_DOUBLE(x))));\n}\n\n\nstatic XEN g_erfc(XEN x)\n{\n  #define H_erfc \"(erfc x): returns the complementary error function erfc(x)\"\n  XEN_ASSERT_TYPE(XEN_NUMBER_P(x), x, XEN_ONLY_ARG, \"erfc\", \" a number\");\n#if HAVE_SCHEME && WITH_GMP\n  if ((s7_is_bignum(x)) &&\n      (s7_is_real(x)) &&\n      (!(s7_is_rational(x))))\n    return(big_erfc(x));\n#endif\n  return(C_TO_XEN_DOUBLE(erfc(XEN_TO_C_DOUBLE(x))));\n}\n\n\nstatic XEN g_lgamma(XEN x)\n{\n  #define H_lgamma \"(lgamma x): returns the log of the gamma function at x\"\n  XEN_ASSERT_TYPE(XEN_NUMBER_P(x), x, XEN_ONLY_ARG, \"lgamma\", \" a number\");\n  return(C_TO_XEN_DOUBLE(lgamma(XEN_TO_C_DOUBLE(x))));\n}\n#endif\n\n\n#define S_bes_i0 \"bes-i0\"\n\nstatic XEN g_i0(XEN x)\n{\n  #define H_i0 \"(\" S_bes_i0 \" x): returns the modified cylindrical bessel function value I0(x)\"\n  XEN_ASSERT_TYPE(XEN_NUMBER_P(x), x, XEN_ONLY_ARG, S_bes_i0, \" a number\");\n#if HAVE_SCHEME && WITH_GMP\n  if ((s7_is_bignum(x)) &&\n      (s7_is_real(x)) &&\n      (!(s7_is_rational(x))))\n    return(big_i0(x));\n#endif\n  return(C_TO_XEN_DOUBLE(mus_bessi0(XEN_TO_C_DOUBLE(x)))); /* uses GSL if possible */\n}\n\n\n/* ---------------------------------------- use GSL ---------------------------------------- */\n#if HAVE_GSL\n\n/* include all the bessel functions, etc */\n#include <gsl/gsl_sf_bessel.h>\n\nstatic XEN g_j0(XEN x)\n{\n  #define H_j0 \"(\" S_bes_j0 \" x): returns the regular cylindrical bessel function value J0(x)\"\n  XEN_ASSERT_TYPE(XEN_NUMBER_P(x), x, XEN_ONLY_ARG, S_bes_j0, \" a number\");\n\n#if HAVE_SCHEME && WITH_GMP\n  if ((s7_is_bignum(x)) &&\n      (s7_is_real(x)) &&\n      (!(s7_is_rational(x))))\n    return(big_j0(x));\n#endif\n  return(C_TO_XEN_DOUBLE(gsl_sf_bessel_J0(XEN_TO_C_DOUBLE(x))));\n}\n\n\nstatic XEN g_j1(XEN x)\n{\n  #define H_j1 \"(\" S_bes_j1 \" x): returns the regular cylindrical bessel function value J1(x)\"\n  XEN_ASSERT_TYPE(XEN_NUMBER_P(x), x, XEN_ONLY_ARG, S_bes_j1, \" a number\");\n\n#if HAVE_SCHEME && WITH_GMP\n  if ((s7_is_bignum(x)) &&\n      (s7_is_real(x)) &&\n      (!(s7_is_rational(x))))\n    return(big_j1(x));\n#endif\n  return(C_TO_XEN_DOUBLE(gsl_sf_bessel_J1(XEN_TO_C_DOUBLE(x))));\n}\n\n\nstatic XEN g_jn(XEN order, XEN x)\n{\n  #define H_jn \"(\" S_bes_jn \" n x): returns the regular cylindrical bessel function value Jn(x)\"\n  XEN_ASSERT_TYPE(XEN_INTEGER_P(order), x, XEN_ARG_1, S_bes_jn, \" an int\");\n  XEN_ASSERT_TYPE(XEN_NUMBER_P(x), x, XEN_ARG_2, S_bes_jn, \" a number\");\n\n#if HAVE_SCHEME && WITH_GMP\n  if ((s7_is_bignum(x)) &&\n      (s7_is_real(x)) &&\n      (!(s7_is_rational(x))))\n    return(big_jn(order, x));\n#endif\n  return(C_TO_XEN_DOUBLE(gsl_sf_bessel_Jn(XEN_TO_C_INT(order), XEN_TO_C_DOUBLE(x))));\n}\n\n\nstatic XEN g_y0(XEN x)\n{\n  #define H_y0 \"(\" S_bes_y0 \" x): returns the irregular cylindrical bessel function value Y0(x)\"\n  XEN_ASSERT_TYPE(XEN_NUMBER_P(x), x, XEN_ONLY_ARG, S_bes_y0, \" a number\");\n#if HAVE_SCHEME && WITH_GMP\n  if ((s7_is_bignum(x)) &&\n      (s7_is_real(x)) &&\n      (!(s7_is_rational(x))))\n    return(big_y0(x));\n#endif\n  return(C_TO_XEN_DOUBLE(gsl_sf_bessel_Y0(XEN_TO_C_DOUBLE(x))));\n}\n\n\nstatic XEN g_y1(XEN x)\n{\n  #define H_y1 \"(\" S_bes_y1 \" x): returns the irregular cylindrical bessel function value Y1(x)\"\n  XEN_ASSERT_TYPE(XEN_NUMBER_P(x), x, XEN_ONLY_ARG, S_bes_y1, \" a number\");\n#if HAVE_SCHEME && WITH_GMP\n  if ((s7_is_bignum(x)) &&\n      (s7_is_real(x)) &&\n      (!(s7_is_rational(x))))\n    return(big_y1(x));\n#endif\n  return(C_TO_XEN_DOUBLE(gsl_sf_bessel_Y1(XEN_TO_C_DOUBLE(x))));\n}\n\n\nstatic XEN g_yn(XEN order, XEN x)\n{\n  #define H_yn \"(\" S_bes_yn \" n x): returns the irregular cylindrical bessel function value Yn(x)\"\n  XEN_ASSERT_TYPE(XEN_INTEGER_P(order), x, XEN_ARG_1, S_bes_yn, \" an int\");\n  XEN_ASSERT_TYPE(XEN_NUMBER_P(x), x, XEN_ARG_2, S_bes_yn, \" a number\");\n#if HAVE_SCHEME && WITH_GMP\n  if ((s7_is_bignum(x)) &&\n      (s7_is_real(x)) &&\n      (!(s7_is_rational(x))))\n    return(big_yn(order, x));\n#endif\n  return(C_TO_XEN_DOUBLE(gsl_sf_bessel_Yn(XEN_TO_C_INT(order), XEN_TO_C_DOUBLE(x))));\n}\n\n#define S_bes_i1 \"bes-i1\"\n#define S_bes_in \"bes-in\"\n#define S_bes_k0 \"bes-k0\"\n#define S_bes_k1 \"bes-k1\"\n#define S_bes_kn \"bes-kn\"\n\nstatic XEN g_i1(XEN x)\n{\n  #define H_i1 \"(\" S_bes_i1 \" x): returns the regular cylindrical bessel function value I1(x)\"\n  XEN_ASSERT_TYPE(XEN_NUMBER_P(x), x, XEN_ONLY_ARG, S_bes_i1, \" a number\");\n  return(C_TO_XEN_DOUBLE(gsl_sf_bessel_I1(XEN_TO_C_DOUBLE(x))));\n}\n\n\nstatic XEN g_in(XEN order, XEN x)\n{\n  #define H_in \"(\" S_bes_in \" n x): returns the regular cylindrical bessel function value In(x)\"\n  XEN_ASSERT_TYPE(XEN_INTEGER_P(order), x, XEN_ARG_1, S_bes_in, \" an int\");\n  XEN_ASSERT_TYPE(XEN_NUMBER_P(x), x, XEN_ARG_2, S_bes_in, \" a number\");\n  return(C_TO_XEN_DOUBLE(gsl_sf_bessel_In(XEN_TO_C_INT(order), XEN_TO_C_DOUBLE(x))));\n}\n\n\nstatic XEN g_k0(XEN x)\n{\n  #define H_k0 \"(\" S_bes_k0 \" x): returns the irregular cylindrical bessel function value K0(x)\"\n  XEN_ASSERT_TYPE(XEN_NUMBER_P(x), x, XEN_ONLY_ARG, S_bes_k0, \" a number\");\n  return(C_TO_XEN_DOUBLE(gsl_sf_bessel_K0(XEN_TO_C_DOUBLE(x))));\n}\n\n\nstatic XEN g_k1(XEN x)\n{\n  #define H_k1 \"(\" S_bes_k1 \" x): returns the irregular cylindrical bessel function value K1(x)\"\n  XEN_ASSERT_TYPE(XEN_NUMBER_P(x), x, XEN_ONLY_ARG, S_bes_k1, \" a number\");\n  return(C_TO_XEN_DOUBLE(gsl_sf_bessel_K1(XEN_TO_C_DOUBLE(x))));\n}\n\n\nstatic XEN g_kn(XEN order, XEN x)\n{\n  #define H_kn \"(\" S_bes_kn \" n x): returns the irregular cylindrical bessel function value Kn(x)\"\n  XEN_ASSERT_TYPE(XEN_INTEGER_P(order), x, XEN_ARG_1, S_bes_kn, \" an int\");\n  XEN_ASSERT_TYPE(XEN_NUMBER_P(x), x, XEN_ARG_2, S_bes_kn, \" a number\");\n  return(C_TO_XEN_DOUBLE(gsl_sf_bessel_Kn(XEN_TO_C_INT(order), XEN_TO_C_DOUBLE(x))));\n}\n\n\n#include <gsl/gsl_sf_erf.h>\nstatic XEN g_erf(XEN x)\n{\n  #define H_erf \"(erf x): returns the error function erf(x)\"\n  XEN_ASSERT_TYPE(XEN_NUMBER_P(x), x, XEN_ONLY_ARG, \"erf\", \" a number\");\n#if HAVE_SCHEME && WITH_GMP\n  if ((s7_is_bignum(x)) &&\n      (s7_is_real(x)) &&\n      (!(s7_is_rational(x))))\n    return(big_erf(x));\n#endif\n  return(C_TO_XEN_DOUBLE(gsl_sf_erf(XEN_TO_C_DOUBLE(x))));\n}\n\n\nstatic XEN g_erfc(XEN x)\n{\n  #define H_erfc \"(erfc x): returns the complementary error function value erfc(x)\"\n  XEN_ASSERT_TYPE(XEN_NUMBER_P(x), x, XEN_ONLY_ARG, \"erfc\", \" a number\");\n#if HAVE_SCHEME && WITH_GMP\n  if ((s7_is_bignum(x)) &&\n      (s7_is_real(x)) &&\n      (!(s7_is_rational(x))))\n    return(big_erfc(x));\n#endif\n  return(C_TO_XEN_DOUBLE(gsl_sf_erfc(XEN_TO_C_DOUBLE(x))));\n}\n\n\n#include <gsl/gsl_sf_gamma.h>\nstatic XEN g_lgamma(XEN x)\n{\n  #define H_lgamma \"(lgamma x): returns the log of the gamma function at x\"\n  XEN_ASSERT_TYPE(XEN_NUMBER_P(x), x, XEN_ONLY_ARG, \"lgamma\", \" a number\");\n  return(C_TO_XEN_DOUBLE(gsl_sf_lngamma(XEN_TO_C_DOUBLE(x))));\n}\n\n\n\n#include <gsl/gsl_sf_ellint.h>\nstatic XEN g_gsl_ellipk(XEN k)\n{\n  double f;\n  #define H_gsl_ellipk \"(gsl-ellipk k): returns the complete elliptic integral k\"\n  XEN_ASSERT_TYPE(XEN_NUMBER_P(k), k, XEN_ONLY_ARG, \"gsl-ellipk\", \"a number\");\n  f = XEN_TO_C_DOUBLE(k);\n  XEN_ASSERT_TYPE(f >= 0.0, k, XEN_ONLY_ARG, \"gsl-ellipk\", \"a non-negative number\");\n  return(C_TO_XEN_DOUBLE(gsl_sf_ellint_Kcomp(sqrt(XEN_TO_C_DOUBLE(k)), GSL_PREC_APPROX)));\n}\n\n\n#include <gsl/gsl_sf_elljac.h>\nstatic XEN g_gsl_ellipj(XEN u, XEN m)\n{\n  #define H_gsl_ellipj \"(gsl-ellipj u m): returns the Jacobian elliptic functions sn, cn, and dn of u and m\"\n  double sn = 0.0, cn = 0.0, dn = 0.0;\n  XEN_ASSERT_TYPE(XEN_NUMBER_P(u), u, XEN_ARG_1, \"gsl-ellipj\", \"a number\");\n  XEN_ASSERT_TYPE(XEN_NUMBER_P(m), m, XEN_ARG_2, \"gsl-ellipj\", \"a number\");\n  gsl_sf_elljac_e(XEN_TO_C_DOUBLE(u),\n\t\t  XEN_TO_C_DOUBLE(m),\n\t\t  &sn, &cn, &dn);\n  return(XEN_LIST_3(C_TO_XEN_DOUBLE(sn),\n\t\t    C_TO_XEN_DOUBLE(cn),\n\t\t    C_TO_XEN_DOUBLE(dn)));\n}\n\n\n#if MUS_DEBUGGING && HAVE_SCHEME\n/* use gsl gegenbauer to check our function */\n\n#include <gsl/gsl_sf_gegenbauer.h>\n\nstatic XEN g_gsl_gegenbauer(XEN n, XEN lambda, XEN x)\n{\n  gsl_sf_result val;\n  gsl_sf_gegenpoly_n_e(XEN_TO_C_INT(n), XEN_TO_C_DOUBLE(lambda), XEN_TO_C_DOUBLE(x), &val);\n  return(C_TO_XEN_DOUBLE(val.val));\n}\n\n#ifdef XEN_ARGIFY_1\n  XEN_NARGIFY_3(g_gsl_gegenbauer_w, g_gsl_gegenbauer)\n#else\n  #define g_gsl_gegenbauer_w g_gsl_gegenbauer\n#endif\n#endif\n\n\n#include <gsl/gsl_dht.h>\n\nstatic XEN g_gsl_dht(XEN size, XEN data, XEN nu, XEN xmax)\n{\n  #define H_gsl_dht \"(gsl-dht size data nu xmax): Hankel transform of data (a vct)\"\n  int n;\n\n  XEN_ASSERT_TYPE(XEN_INTEGER_P(size), size, XEN_ARG_1, \"gsl-dht\", \"an integer\");\n  XEN_ASSERT_TYPE(MUS_VCT_P(data), data, XEN_ARG_2, \"gsl-dht\", \"a vct\");\n  XEN_ASSERT_TYPE(XEN_NUMBER_P(nu), nu, XEN_ARG_3, \"gsl-dht\", \"a number\");\n  XEN_ASSERT_TYPE(XEN_NUMBER_P(xmax), xmax, XEN_ARG_4, \"gsl-dht\", \"a number\");\n\n  n = XEN_TO_C_INT(size);\n  if (n <= 0)\n    XEN_OUT_OF_RANGE_ERROR(\"gsl-dht\", XEN_ARG_1, size, \"must be > 0\");\n  else\n    {\n      double *indata, *outdata;\n      int i;\n      vct *v;\n\n      gsl_dht *t = gsl_dht_new(n, XEN_TO_C_DOUBLE(nu), XEN_TO_C_DOUBLE(xmax));\n\n      indata = (double *)calloc(n, sizeof(double));\n      outdata = (double *)calloc(n, sizeof(double));\n\n      v = XEN_TO_VCT(data);\n      for (i = 0; i < n; i++)\n\tindata[i] = v->data[i];\n\n      gsl_dht_apply(t, indata, outdata);\n\n      for (i = 0; i < n; i++)\n\tv->data[i] = outdata[i];\n\n      gsl_dht_free(t);\n\n      free(indata);\n      free(outdata);\n    }\n  return(data);\n}\n\n\n#if HAVE_GSL_EIGEN_NONSYMMV_WORKSPACE\n\n/* eignevector/values, from gsl/doc/examples/eigen_nonsymm.c */\n\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_eigen.h>\n\nstatic XEN g_gsl_eigenvectors(XEN matrix)\n{\n  double *data;\n  mus_any *u1;\n  mus_float_t *vals;\n  int i, j, len;\n  XEN values = XEN_FALSE, vectors = XEN_FALSE;\n\n  XEN_ASSERT_TYPE(mus_xen_p(matrix), matrix, XEN_ONLY_ARG, \"gsl-eigenvectors\", \"a mixer (matrix)\");\n  u1 = XEN_TO_MUS_ANY(matrix);\n  if (!mus_mixer_p(u1)) return(XEN_FALSE);\n  vals = mus_data(u1);\n  len = mus_length(u1);\n  data = (double *)calloc(len * len, sizeof(double));\n  for (i = 0; i < len; i++)\n    for (j = 0; j < len; j++)\n      data[i * len + j] = mus_mixer_ref(u1, i, j);\n\n  {\n    gsl_matrix_view m = gsl_matrix_view_array(data, len, len);\n    gsl_vector_complex *eval = gsl_vector_complex_alloc(len);\n    gsl_matrix_complex *evec = gsl_matrix_complex_alloc(len, len);\n    gsl_eigen_nonsymmv_workspace *w = gsl_eigen_nonsymmv_alloc(len);\n    gsl_eigen_nonsymmv(&m.matrix, eval, evec, w);\n    gsl_eigen_nonsymmv_free(w);\n    gsl_eigen_nonsymmv_sort(eval, evec, GSL_EIGEN_SORT_ABS_DESC);\n  \n    {\n      int values_loc, vectors_loc;\n\n      values = XEN_MAKE_VECTOR(len, XEN_ZERO);\n      values_loc = snd_protect(values);\n      vectors = XEN_MAKE_VECTOR(len, XEN_FALSE);\n      vectors_loc = snd_protect(vectors);\n\n      for (i = 0; i < len; i++)\n\t{\n\t  XEN vect;\n\t  gsl_complex eval_i = gsl_vector_complex_get(eval, i);\n\t  gsl_vector_complex_view evec_i = gsl_matrix_complex_column(evec, i);\n\t  XEN_VECTOR_SET(values, i, C_TO_XEN_DOUBLE(GSL_REAL(eval_i)));\n\t\n\t  vect = XEN_MAKE_VECTOR(len, XEN_ZERO);\n\t  XEN_VECTOR_SET(vectors, i, vect);\n\n\t  for (j = 0; j < len; j++)\n\t    {\n\t      gsl_complex z = gsl_vector_complex_get(&evec_i.vector, j);\n\t      XEN_VECTOR_SET(vect, j, C_TO_XEN_DOUBLE(GSL_REAL(z)));\n\t    }\n\t}\n      snd_unprotect_at(values_loc);\n      snd_unprotect_at(vectors_loc);\n    }\n\n    gsl_vector_complex_free(eval);\n    gsl_matrix_complex_free(evec);\n  }\n\n  free(data);\n  return(XEN_LIST_2(values, vectors));\n}\n#endif\n\n\n#if HAVE_COMPLEX_TRIG && XEN_HAVE_COMPLEX_NUMBERS\n#include <gsl/gsl_poly.h>\n#include <complex.h>\n\nstatic XEN g_gsl_roots(XEN poly)\n{\n  #define H_gsl_roots \"(gsl-roots poly): roots of poly\"\n  int i, n, loc;\n  double *p;\n  double complex *z;\n  gsl_poly_complex_workspace *w;\n  XEN result;\n\n  XEN_ASSERT_TYPE(XEN_VECTOR_P(poly), poly, XEN_ONLY_ARG, \"gsl-roots\", \"a vector\");\n\n  n = XEN_VECTOR_LENGTH(poly);\n  w = gsl_poly_complex_workspace_alloc(n);\n  z = (double complex *)calloc(n, sizeof(double complex));\n  p = (double *)calloc(n, sizeof(double));\n\n  for (i = 0; i < n; i++)\n    p[i] = XEN_TO_C_DOUBLE(XEN_VECTOR_REF(poly, i));\n\n  gsl_poly_complex_solve(p, n, w, (gsl_complex_packed_ptr)z);\n  gsl_poly_complex_workspace_free (w);\n\n  result = XEN_MAKE_VECTOR(n - 1, XEN_ZERO);\n  loc = snd_protect(result);\n  for (i = 0; i < n - 1; i++)\n    if (__imag__(z[i]) != 0.0)\n      XEN_VECTOR_SET(result, i, C_TO_XEN_COMPLEX(z[i]));\n    else XEN_VECTOR_SET(result, i, C_TO_XEN_DOUBLE(__real__(z[i])));\n\n  free(z);\n  free(p);\n  snd_unprotect_at(loc);\n  return(result);\n}\n#endif\n#endif\n\n\n\n/* -------- source file extensions list -------- */\n\nstatic char **source_file_extensions = NULL;\nstatic int source_file_extensions_size = 0;\nstatic int source_file_extensions_end = 0;\nstatic int default_source_file_extensions = 0;\n\nstatic void add_source_file_extension(const char *ext)\n{\n  int i;\n  for (i = 0; i < source_file_extensions_end; i++)\n    if (mus_strcmp(ext, source_file_extensions[i]))\n      return;\n  if (source_file_extensions_end == source_file_extensions_size)\n    {\n      source_file_extensions_size += 8;\n      if (source_file_extensions == NULL)\n\tsource_file_extensions = (char **)calloc(source_file_extensions_size, sizeof(char *));\n      else source_file_extensions = (char **)realloc(source_file_extensions, source_file_extensions_size * sizeof(char *));\n    }\n  source_file_extensions[source_file_extensions_end] = mus_strdup(ext);\n  source_file_extensions_end++;\n}\n\n\nbool source_file_p(const char *name)\n{\n  int i, dot_loc = -1, len;\n\n  if (!name) return(false);\n\n  if (source_file_extensions)\n    {\n      len = strlen(name);\n\n      for (i = 0; i < len; i++)\n\tif (name[i] == '.')\n\t  dot_loc = i;\n      /* dot_loc is last dot in the name */\n\n      if ((dot_loc > 0) &&\n\t  (dot_loc < len - 1))\n\t{\n\t  const char *ext;\n\n\t  ext = (const char *)(name + dot_loc + 1);\n\t  for (i = 0; i < source_file_extensions_end; i++)\n\t    if (mus_strcmp(ext, source_file_extensions[i]))\n\t      return(true);\n\t}\n    }\n  return(false);\n}\n\n\nvoid save_added_source_file_extensions(FILE *fd)\n{\n  int i;\n\n  if (source_file_extensions_end > default_source_file_extensions)\n    for (i = default_source_file_extensions; i < source_file_extensions_end; i++)\n      {\n#if HAVE_SCHEME\n\tfprintf(fd, \"(%s \\\"%s\\\")\\n\", S_add_source_file_extension, source_file_extensions[i]);\n#endif\n\n#if HAVE_RUBY\n\tfprintf(fd, \"%s(\\\"%s\\\")\\n\", TO_PROC_NAME(S_add_source_file_extension), source_file_extensions[i]);\n#endif\n\n#if HAVE_FORTH\n\tfprintf(fd, \"\\\"%s\\\" %s drop\\n\", source_file_extensions[i], S_add_source_file_extension);\n#endif\n      }\n}\n\n\nstatic XEN g_add_source_file_extension(XEN ext)\n{\n  #define H_add_source_file_extension \"(\" S_add_source_file_extension \" ext):  add the file extension 'ext' to the list of source file extensions\"\n  XEN_ASSERT_TYPE(XEN_STRING_P(ext), ext, XEN_ONLY_ARG, S_add_source_file_extension, \"a string\");\n  add_source_file_extension(XEN_TO_C_STRING(ext));\n  return(ext);\n}\n\n\nstatic char *find_source_file(const char *orig)\n{\n  int i;\n  char *str;\n  for (i = 0; i < source_file_extensions_end; i++)\n    {\n      str = mus_format(\"%s.%s\", orig, source_file_extensions[i]);\n      if (mus_file_probe(str))\n\treturn(str);\n      free(str);\n    }\n  return(NULL);\n}\n\n\n#if HAVE_SCHEME\n\nstatic s7_pointer g_char_position(s7_scheme *sc, s7_pointer args)\n{\n  #define H_char_position \"(char-position char str (start 0)) returns the position of the first occurrence of char in str, or #f\"\n  const char *porig, *p;\n  char c;\n  int start = 0;\n\n  if (!s7_is_character(s7_car(args)))\n    return(s7_wrong_type_arg_error(sc, \"char-position\", 1, s7_car(args), \"a character\"));\n  if (!s7_is_string(s7_car(s7_cdr(args))))\n    return(s7_wrong_type_arg_error(sc, \"char-position\", 2, s7_car(s7_cdr(args)), \"a string\"));\n\n  if (s7_is_pair(s7_cdr(s7_cdr(args))))\n    {\n      s7_pointer arg;\n      arg = s7_car(s7_cdr(s7_cdr(args)));\n      if (!s7_is_integer(arg))\n\treturn(s7_wrong_type_arg_error(sc, \"char-position\", 3, arg, \"an integer\"));\n\n      start = s7_integer(arg);\n      if (start < 0)\n\treturn(s7_wrong_type_arg_error(sc, \"char-position\", 3, arg, \"a non-negative integer\"));\n    }\n\n  c = s7_character(s7_car(args));\n  porig = s7_string(s7_car(s7_cdr(args)));\n\n  if ((!porig) || (start >= mus_strlen(porig)))\n    return(s7_f(sc));\n\n  for (p = (const char *)(porig + start); (*p); p++)\n    if ((*p) == c)\n      return(s7_make_integer(sc, p - porig));\n  return(s7_f(sc));\n}\n\n\nstatic s7_pointer g_string_position_1(s7_scheme *sc, s7_pointer args, bool ci, const char *name)\n{\n  const char *s1, *s2, *p1, *p2;\n  int start = 0;\n\n  if (!s7_is_string(s7_car(args)))\n    return(s7_wrong_type_arg_error(sc, name, 1, s7_car(args), \"a string\"));\n  if (!s7_is_string(s7_car(s7_cdr(args))))\n    return(s7_wrong_type_arg_error(sc, name, 2, s7_car(s7_cdr(args)), \"a string\"));\n\n  if (s7_is_pair(s7_cdr(s7_cdr(args))))\n    {\n      s7_pointer arg;\n      arg = s7_car(s7_cdr(s7_cdr(args)));\n      if (!s7_is_integer(arg))\n\treturn(s7_wrong_type_arg_error(sc, name, 3, arg, \"an integer\"));\n\n      start = s7_integer(arg);\n      if (start < 0)\n\treturn(s7_wrong_type_arg_error(sc, name, 3, arg, \"a non-negative integer\"));\n    }\n  \n  s1 = s7_string(s7_car(args));\n  s2 = s7_string(s7_car(s7_cdr(args)));\n  if (start >= mus_strlen(s2))\n    return(s7_f(sc));\n\n  if (!ci)\n    {\n      for (p2 = (const char *)(s2 + start); (*p2); p2++)\n\t{\n\t  const char *ptemp;\n\t  for (p1 = s1, ptemp = p2; (*p1) && (*ptemp) && ((*p1) == (*ptemp)); p1++, ptemp++);\n\t  if (!(*p1))\n\t    return(s7_make_integer(sc, p2 - s2));\n\t}\n    }\n  else\n    {\n      for (p2 = (const char *)(s2 + start); (*p2); p2++)\n\t{\n\t  const char *ptemp;\n\t  for (p1 = s1, ptemp = p2; (*p1) && (*ptemp) && (toupper((int)(*p1)) == toupper((int)(*ptemp))); p1++, ptemp++);\n\t  if (!(*p1))\n\t    return(s7_make_integer(sc, p2 - s2));\n\t}\n    }\n\n  return(s7_f(sc));\n}\n\n\nstatic s7_pointer g_string_position(s7_scheme *sc, s7_pointer args)\n{\n  #define H_string_position \"(string-position str1 str2 (start 0)) returns the starting position of str1 in str2 or #f\"\n  return(g_string_position_1(sc, args, false, \"string-position\"));\n}\n\n\nstatic s7_pointer g_string_ci_position(s7_scheme *sc, s7_pointer args)\n{\n  #define H_string_ci_position \"(string-ci-position str1 str2 (start 0)) returns the starting position of str1 in str2 ignoring case, or #f\"\n  return(g_string_position_1(sc, args, true, \"string-ci-position\"));\n}\n\n\nstatic s7_pointer g_string_vector_position(s7_scheme *sc, s7_pointer args)\n{\n  #define H_string_vector_position \"(string-vector-position str vect (start 0)) returns the position of the first occurrence of str in vect starting from start, or #f\"\n  const char *s1;\n  s7_pointer *strs;\n  int i, len, start = 0;\n\n  if (!s7_is_string(s7_car(args)))\n    return(s7_wrong_type_arg_error(sc, \"string-vector-position\", 1, s7_car(args), \"a string\"));\n  if (!s7_is_vector(s7_car(s7_cdr(args))))\n    return(s7_wrong_type_arg_error(sc, \"string-vector-position\", 2, s7_car(s7_cdr(args)), \"a vector\"));\n\n  if (s7_is_pair(s7_cdr(s7_cdr(args))))\n    {\n      s7_pointer arg;\n      arg = s7_car(s7_cdr(s7_cdr(args)));\n      if (!s7_is_integer(arg))\n\treturn(s7_wrong_type_arg_error(sc, \"string-vector-position\", 3, arg, \"an integer\"));\n\n      start = s7_integer(arg);\n      if (start < 0)\n\treturn(s7_wrong_type_arg_error(sc, \"string-vector-position\", 3, arg, \"a non-negative integer\"));\n    }\n  \n  s1 = s7_string(s7_car(args));\n  strs = s7_vector_elements(s7_car(s7_cdr(args)));\n  len = s7_vector_length(s7_car(s7_cdr(args)));\n\n  for (i = start; i < len; i++)\n    if ((s7_is_string(strs[i])) &&\n\t(mus_strcmp(s1, s7_string(strs[i]))))\n      return(s7_make_integer(sc, i));\n  \n  return(s7_f(sc));\n}\n\n\nstatic s7_pointer g_string_list_position_1(s7_scheme *sc, s7_pointer args, bool ci, const char *name)\n{\n  const char *s1;\n  s7_pointer p;\n  int i, start = 0;\n\n  if (!s7_is_string(s7_car(args)))\n    return(s7_wrong_type_arg_error(sc, name, 1, s7_car(args), \"a string\"));\n\n  p = s7_car(s7_cdr(args));\n  if (p == s7_nil(sc))\n    return(s7_f(sc));\n  if (!s7_is_pair(p))\n    return(s7_wrong_type_arg_error(sc, name, 2, p, \"a list\"));\n\n  if (s7_is_pair(s7_cdr(s7_cdr(args))))\n    {\n      s7_pointer arg;\n      arg = s7_car(s7_cdr(s7_cdr(args)));\n      if (!s7_is_integer(arg))\n\treturn(s7_wrong_type_arg_error(sc, \"string-list-position\", 3, arg, \"an integer\"));\n\n      start = s7_integer(arg);\n      if (start < 0)\n\treturn(s7_wrong_type_arg_error(sc, \"string-list-position\", 3, arg, \"a non-negative integer\"));\n    }\n  \n  s1 = s7_string(s7_car(args));\n\n  if (!ci)\n    {\n      for (i = 0; s7_is_pair(p); p = s7_cdr(p), i++)\n\tif ((i >= start) &&\n\t    (s7_is_string(s7_car(p))) &&\n\t    (mus_strcmp(s1, s7_string(s7_car(p)))))\n\t  return(s7_make_integer(sc, i));\n    }\n  else\n    {\n      for (i = 0; s7_is_pair(p); p = s7_cdr(p), i++)\n\tif ((i >= start) &&\n\t    (s7_is_string(s7_car(p))) &&\n\t    (strcasecmp(s1, s7_string(s7_car(p))) == 0))\n\t  return(s7_make_integer(sc, i));\n    }\n  return(s7_f(sc));\n}\n\n\nstatic s7_pointer g_string_list_position(s7_scheme *sc, s7_pointer args)\n{\n  #define H_string_list_position \"(string-list-position str lst (start 0)) returns the position of the first occurrence of str in lst starting from start, or #f\"\n  return(g_string_list_position_1(sc, args, false, \"string-list-position\"));\n}\n\n\nstatic s7_pointer g_string_ci_list_position(s7_scheme *sc, s7_pointer args)\n{\n  #define H_string_ci_list_position \"(string-ci-list-position str lst (start 0)) returns the position of the first occurrence of str in lst starting from start, or #f\"\n  return(g_string_list_position_1(sc, args, true, \"string-ci-list-position\"));\n}\n\n\n/* list-in-vector|list, vector-in-list|vector, cobj-in-vector|list obj-in-cobj\n *   string-ci-in-vector? hash-table cases?\n *   most of this could be done via for-each\n */\n\n#endif\n\n\n#ifdef XEN_ARGIFY_1\n#if HAVE_SCHEME && HAVE_DLFCN_H\n  XEN_NARGIFY_1(g_dlopen_w, g_dlopen)\n  XEN_NARGIFY_1(g_dlclose_w, g_dlclose)\n  XEN_NARGIFY_0(g_dlerror_w, g_dlerror)\n  XEN_NARGIFY_2(g_dlinit_w, g_dlinit)\n#endif\n#if HAVE_SCHEME\n  XEN_VARGIFY(g_snd_s7_error_handler_w, g_snd_s7_error_handler);\n#endif\n\nXEN_NARGIFY_1(g_snd_print_w, g_snd_print)\nXEN_NARGIFY_0(g_little_endian_w, g_little_endian)\nXEN_NARGIFY_0(g_snd_global_state_w, g_snd_global_state)\nXEN_NARGIFY_1(g_add_source_file_extension_w, g_add_source_file_extension)\n\n#if MUS_DEBUGGING\n  XEN_NARGIFY_1(g_snd_sound_pointer_w, g_snd_sound_pointer)\n#endif\n\n#if (!HAVE_SCHEME)\nXEN_NARGIFY_2(g_fmod_w, g_fmod)\n#endif\n\n#if HAVE_SPECIAL_FUNCTIONS || HAVE_GSL\n  XEN_NARGIFY_1(g_j0_w, g_j0)\n  XEN_NARGIFY_1(g_j1_w, g_j1)\n  XEN_NARGIFY_2(g_jn_w, g_jn)\n  XEN_NARGIFY_1(g_y0_w, g_y0)\n  XEN_NARGIFY_1(g_y1_w, g_y1)\n  XEN_NARGIFY_2(g_yn_w, g_yn)\n  XEN_NARGIFY_1(g_erf_w, g_erf)\n  XEN_NARGIFY_1(g_erfc_w, g_erfc)\n  XEN_NARGIFY_1(g_lgamma_w, g_lgamma)\n#endif\n\nXEN_NARGIFY_1(g_i0_w, g_i0)\n\n#if HAVE_GSL\n  XEN_NARGIFY_1(g_i1_w, g_i1)\n  XEN_NARGIFY_2(g_in_w, g_in)\n  XEN_NARGIFY_1(g_k0_w, g_k0)\n  XEN_NARGIFY_1(g_k1_w, g_k1)\n  XEN_NARGIFY_2(g_kn_w, g_kn)\n\n  XEN_NARGIFY_1(g_gsl_ellipk_w, g_gsl_ellipk)\n  XEN_NARGIFY_2(g_gsl_ellipj_w, g_gsl_ellipj)\n  XEN_NARGIFY_4(g_gsl_dht_w, g_gsl_dht)\n#if HAVE_GSL_EIGEN_NONSYMMV_WORKSPACE\n  XEN_NARGIFY_1(g_gsl_eigenvectors_w, g_gsl_eigenvectors)\n#endif\n\n  #if HAVE_COMPLEX_TRIG && XEN_HAVE_COMPLEX_NUMBERS\n    XEN_NARGIFY_1(g_gsl_roots_w, g_gsl_roots)\n  #endif\n#endif\n\n#else\n/* not argify */\n\n#if HAVE_SCHEME && HAVE_DLFCN_H\n  #define g_dlopen_w g_dlopen\n  #define g_dlclose_w g_dlclose\n  #define g_dlerror_w g_dlerror\n  #define g_dlinit_w g_dlinit\n#endif\n#if HAVE_SCHEME\n  #define g_snd_s7_error_handler_w g_snd_s7_error_handler\n#endif\n\n#define g_snd_print_w g_snd_print\n#define g_little_endian_w g_little_endian\n#define g_snd_global_state_w g_snd_global_state\n#define g_add_source_file_extension_w g_add_source_file_extension\n#if MUS_DEBUGGING\n  #define g_snd_sound_pointer_w g_snd_sound_pointer\n#endif\n\n#if (!HAVE_SCHEME)\n#define g_fmod_w g_fmod\n#endif\n\n#if HAVE_SPECIAL_FUNCTIONS || HAVE_GSL\n  #define g_j0_w g_j0\n  #define g_j1_w g_j1\n  #define g_jn_w g_jn\n  #define g_y0_w g_y0\n  #define g_y1_w g_y1\n  #define g_yn_w g_yn\n  #define g_erf_w g_erf\n  #define g_erfc_w g_erfc\n  #define g_lgamma_w g_lgamma\n#endif\n\n#define g_i0_w g_i0\n\n#if HAVE_GSL\n  #define g_i1_w g_i1\n  #define g_in_w g_in\n  #define g_k0_w g_k0\n  #define g_k1_w g_k1\n  #define g_kn_w g_kn\n  #define g_gsl_ellipk_w g_gsl_ellipk\n  #define g_gsl_ellipj_w g_gsl_ellipj\n  #define g_gsl_dht_w g_gsl_dht\n  #if HAVE_GSL_EIGEN_NONSYMMV_WORKSPACE\n    #define g_gsl_eigenvectors_w g_gsl_eigenvectors\n  #endif\n  #if HAVE_COMPLEX_TRIG && XEN_HAVE_COMPLEX_NUMBERS\n    #define g_gsl_roots_w g_gsl_roots\n  #endif\n#endif\n#endif\n\n\n#if HAVE_STATIC_XM\n  #if USE_MOTIF\n    void Init_libxm(void);\n  #else\n    void Init_libxg(void);\n  #endif\n#endif\n\n\n#if HAVE_GL && (!JUST_GL)\n void Init_libgl(void);\n#endif\n\n\nstatic char *legalize_path(const char *in_str)\n{ \n  int inlen;\n  char *out_str;\n  int inpos, outpos = 0; \n\n  inlen = mus_strlen(in_str); \n  out_str = (char *)calloc(inlen * 2, sizeof(char)); \n\n  for (inpos = 0; inpos < inlen; inpos++)\n    { \n      if (in_str[inpos] == '\\\\')\n\tout_str[outpos++] = '\\\\';\n      out_str[outpos++] = in_str[inpos]; \n    } \n\n  return(out_str); \n} \n\n\n#if HAVE_GL\nstatic XEN g_snd_glx_context(void)\n{\n  return(XEN_LIST_2(C_STRING_TO_XEN_SYMBOL(\"GLXContext\"), \n\t\t    XEN_WRAP_C_POINTER(ss->cx)));\n} \n\n\n#ifdef XEN_ARGIFY_1\nXEN_NARGIFY_0(g_snd_glx_context_w, g_snd_glx_context)\n#else\n#define g_snd_glx_context_w g_snd_glx_context\n#endif\n#endif\n\n\n\n/* -------------------------------------------------------------------------------- */\n\nvoid g_xen_initialize(void)\n{\n  add_source_file_extension(XEN_FILE_EXTENSION);\n#if HAVE_SCHEME\n  add_source_file_extension(\"cl\");\n  add_source_file_extension(\"lisp\");\n  add_source_file_extension(\"init\");  /* for slib */\n#endif\n#if HAVE_FORTH\n  add_source_file_extension(\"fth\");\n  add_source_file_extension(\"fsm\");\n#endif\n  add_source_file_extension(\"marks\"); /* from save-marks */\n  default_source_file_extensions = source_file_extensions_end;\n\n  XEN_DEFINE_PROCEDURE(\"snd-global-state\", g_snd_global_state_w, 0, 0, 0, \"internal testing function\");\n  XEN_DEFINE_PROCEDURE(S_add_source_file_extension, g_add_source_file_extension_w, 1, 0, 0, H_add_source_file_extension);\n\n  ss->snd_open_file_hook = XEN_DEFINE_SIMPLE_HOOK(1);\n  ss->snd_selection_hook = XEN_DEFINE_SIMPLE_HOOK(1);\n\n  XEN_PROTECT_FROM_GC(ss->snd_open_file_hook);\n  XEN_PROTECT_FROM_GC(ss->snd_selection_hook);\n\n  ss->effects_hook = XEN_DEFINE_HOOK(S_effects_hook, 0, \"called when something changes that the effects dialogs care about\");\n\n#if MUS_DEBUGGING\n  XEN_DEFINE_PROCEDURE(\"snd-sound-pointer\", g_snd_sound_pointer_w, 1, 0, 0, \"internal testing function\");\n#endif\n\n  Init_sndlib();\n\n#if HAVE_FORTH\n  fth_add_loaded_files(\"sndlib.so\");\n#endif\n\n#if (!HAVE_SCHEME)\n  gc_protection = XEN_FALSE;\n#endif\n\n  XEN_DEFINE_SAFE_PROCEDURE(S_snd_print,      g_snd_print_w,     1, 0, 0, H_snd_print);\n  XEN_DEFINE_SAFE_PROCEDURE(\"little-endian?\", g_little_endian_w, 0, 0, 0, \"return \" PROC_TRUE \" if host is little endian\");\n\n#if HAVE_SCHEME\n  XEN_EVAL_C_STRING(\"(define fmod modulo)\");\n#else\n  XEN_DEFINE_PROCEDURE(\"fmod\",           g_fmod_w,          2, 0, 0, \"C's fmod\");\n#endif\n\n#if HAVE_SPECIAL_FUNCTIONS || HAVE_GSL\n  XEN_DEFINE_SAFE_PROCEDURE(S_bes_j0, g_j0_w,     1, 0, 0, H_j0);\n  XEN_DEFINE_SAFE_PROCEDURE(S_bes_j1, g_j1_w,     1, 0, 0, H_j1);\n  XEN_DEFINE_SAFE_PROCEDURE(S_bes_jn, g_jn_w,     2, 0, 0, H_jn);\n  XEN_DEFINE_SAFE_PROCEDURE(S_bes_y0, g_y0_w,     1, 0, 0, H_y0);\n  XEN_DEFINE_SAFE_PROCEDURE(S_bes_y1, g_y1_w,     1, 0, 0, H_y1);\n  XEN_DEFINE_SAFE_PROCEDURE(S_bes_yn, g_yn_w,     2, 0, 0, H_yn);\n  XEN_DEFINE_SAFE_PROCEDURE(\"erf\",    g_erf_w,    1, 0, 0, H_erf);\n  XEN_DEFINE_SAFE_PROCEDURE(\"erfc\",   g_erfc_w,   1, 0, 0, H_erfc);\n  XEN_DEFINE_SAFE_PROCEDURE(\"lgamma\", g_lgamma_w, 1, 0, 0, H_lgamma);\n#endif\n\n  XEN_DEFINE_PROCEDURE(S_bes_i0, g_i0_w,     1, 0, 0, H_i0);\n\n#if HAVE_GSL\n  XEN_DEFINE_SAFE_PROCEDURE(S_bes_i1, g_i1_w,     1, 0, 0, H_i1);\n  XEN_DEFINE_SAFE_PROCEDURE(S_bes_in, g_in_w,     2, 0, 0, H_in);\n  XEN_DEFINE_SAFE_PROCEDURE(S_bes_k0, g_k0_w,     1, 0, 0, H_k0);\n  XEN_DEFINE_SAFE_PROCEDURE(S_bes_k1, g_k1_w,     1, 0, 0, H_k1);\n  XEN_DEFINE_SAFE_PROCEDURE(S_bes_kn, g_kn_w,     2, 0, 0, H_kn);\n\n  XEN_DEFINE_PROCEDURE(\"gsl-ellipk\", g_gsl_ellipk_w, 1, 0, 0, H_gsl_ellipk);\n  XEN_DEFINE_PROCEDURE(\"gsl-ellipj\", g_gsl_ellipj_w, 2, 0, 0, H_gsl_ellipj);\n  XEN_DEFINE_PROCEDURE(\"gsl-dht\",    g_gsl_dht_w,    4, 0, 0, H_gsl_dht);\n#if HAVE_GSL_EIGEN_NONSYMMV_WORKSPACE\n  XEN_DEFINE_PROCEDURE(\"gsl-eigenvectors\", g_gsl_eigenvectors_w, 1, 0, 0, \"returns eigenvalues and eigenvectors\");\n#endif\n\n#if MUS_DEBUGGING && HAVE_SCHEME\n  XEN_DEFINE_PROCEDURE(\"gsl-gegenbauer\",  g_gsl_gegenbauer_w,  3, 0, 0, \"internal test func\");\n#endif\n\n#if HAVE_COMPLEX_TRIG && XEN_HAVE_COMPLEX_NUMBERS\n  XEN_DEFINE_PROCEDURE(\"gsl-roots\",  g_gsl_roots_w,  1, 0, 0, H_gsl_roots);\n#endif\n\n#endif\n\n#if HAVE_SCHEME && WITH_GMP\n  s7_define_function(s7, \"bignum-fft\", bignum_fft, 3, 1, false, H_bignum_fft);\n#endif\n\n#if HAVE_SCHEME\n  s7_define_safe_function(s7, \"char-position\", g_char_position, 2, 1, false, H_char_position);\n  s7_define_safe_function(s7, \"string-position\", g_string_position, 2, 1, false, H_string_position);\n  s7_define_safe_function(s7, \"string-ci-position\", g_string_ci_position, 2, 1, false, H_string_ci_position);\n  s7_define_safe_function(s7, \"string-vector-position\", g_string_vector_position, 2, 1, false, H_string_vector_position);\n  s7_define_safe_function(s7, \"string-list-position\", g_string_list_position, 2, 1, false, H_string_list_position);\n  s7_define_safe_function(s7, \"string-ci-list-position\", g_string_ci_list_position, 2, 1, false, H_string_ci_list_position);\n\n  #define H_print_hook S_print_hook \" (text): called each time some Snd-generated response (text) is about to be appended to the listener. \\\nIf it returns some non-\" PROC_FALSE \" result, Snd assumes you've sent the text out yourself, as well as any needed prompt. \\n\\\n  (add-hook! \" S_print_hook \"\\n\\\n    (lambda (msg) \\n\\\n      (\" S_snd_print \"\\n\\\n        (format #f \\\"~A~%[~A]~%~A\\\" \\n\\\n                msg \\n\\\n                (strftime \\\"%d-%b %H:%M %Z\\\" \\n\\\n                           (localtime (current-time))) \\n\\\n                (\" S_listener_prompt \")))))\"\n#endif\n\n#if HAVE_RUBY\n  #define H_print_hook S_print_hook \" (text): called each time some Snd-generated response (text) is about to be appended to the listener. \\\nIf it returns some non-false result, Snd assumes you've sent the text out yourself, as well as any needed prompt. \\n\\\n  $print_hook.add-hook!(\\\"localtime\\\") do |msg|\\n\\\n    $stdout.print msg\\n\\\n  false\\n\\\n  end\"\n#endif\n\n#if HAVE_FORTH\n  #define H_print_hook S_print_hook \" (text): called each time some Snd-generated response (text) is about to be appended to the listener. \\\nIf it returns some non-#f result, Snd assumes you've sent the text out yourself, as well as any needed prompt. \\n\\\n\" S_print_hook \" lambda: <{ msg }>\\n\\\n  \\\"%s\\n[%s]\\n%s\\\" '( msg date \" S_listener_prompt \" ) format \" S_snd_print \"\\n\\\n; add-hook!\"\n#endif\n\n  print_hook = XEN_DEFINE_HOOK(S_print_hook, 1, H_print_hook);          /* arg = text */\n\n  g_init_base();\n  g_init_utils();\n  g_init_marks();\n  g_init_regions();\n  g_init_selection();\n  g_init_mix();\n  g_init_chn();\n  g_init_kbd();\n  g_init_sig();\n  g_init_print();\n  g_init_errors();\n  g_init_fft();\n  g_init_edits();\n  g_init_listener();\n  g_init_help();\n  g_init_menu();\n  g_init_main();\n  g_init_snd();\n  g_init_dac(); /* needs to follow snd and mix */\n  g_init_file();\n  g_init_data();\n  g_init_env();\n  g_init_find();\n#if (!USE_NO_GUI)\n  g_init_gxcolormaps();\n  g_init_gxfile();\n  g_init_gxdraw();\n  g_init_gxenv();\n  g_init_gxmenu();\n  g_init_axis();\n  g_init_gxlistener();\n  g_init_gxchn();\n  g_init_draw();\n  g_init_gxdrop();\n  g_init_gxregion();\n  g_init_gxsnd();\n  g_init_gxfind();\n#endif\n\n#if (!WITH_SHARED_SNDLIB)\n  mus_init_run(); /* this needs to be called after Snd's run-optimizable functions are defined (sampler_p for example) */\n#endif\n\n#if HAVE_SCHEME && HAVE_DLFCN_H\n  XEN_DEFINE_PROCEDURE(\"dlopen\",  g_dlopen_w,  1, 0 ,0, H_dlopen);\n  XEN_DEFINE_PROCEDURE(\"dlclose\", g_dlclose_w, 1, 0 ,0, H_dlclose);\n  XEN_DEFINE_PROCEDURE(\"dlerror\", g_dlerror_w, 0, 0 ,0, H_dlerror);\n  XEN_DEFINE_PROCEDURE(\"dlinit\",  g_dlinit_w,  2, 0 ,0, H_dlinit);\n#endif\n\n#if HAVE_LADSPA && HAVE_EXTENSION_LANGUAGE && HAVE_DLFCN_H && HAVE_DIRENT_H\n  g_ladspa_to_snd();\n#endif\n\n#ifdef SCRIPTS_DIR\n  XEN_ADD_TO_LOAD_PATH((char *)SCRIPTS_DIR);\n#endif\n\n  { \n    char *pwd, *legal_pwd; \n    pwd = mus_getcwd(); \n    legal_pwd = legalize_path(pwd);\n    XEN_ADD_TO_LOAD_PATH(legal_pwd); \n    free(pwd); \n    free(legal_pwd); \n  } \n\n#if HAVE_SCHEME\n  XEN_DEFINE_PROCEDURE(\"_snd_s7_error_handler_\", g_snd_s7_error_handler_w,  0, 0, 1, \"internal error redirection for snd/s7\");\n\n  XEN_EVAL_C_STRING(\"(define redo-edit redo)\");        /* consistency with Ruby */\n  XEN_EVAL_C_STRING(\"(define undo-edit undo)\");\n  \n  XEN_EVAL_C_STRING(\"(define (procedure-name proc) (if (procedure? proc) (format #f \\\"~A\\\" proc) #f))\");\n  /* needed in snd-test.scm and hooks.scm */\n\n  XEN_EVAL_C_STRING(\"\\\n        (define* (apropos name port)\\\n          (define (substring? subs s)\\\n            (let* ((start 0)\\\n\t           (ls (string-length s))\\\n\t           (lu (string-length subs))\\\n\t           (limit (- ls lu)))\\\n              (let loop ((i start))\\\n\t        (cond ((> i limit) #f)\\\n\t              ((do ((j i (+ j 1))\\\n\t        \t    (k 0 (+ k 1)))\\\n\t        \t   ((or (= k lu)\\\n\t        \t\t(not (char=? (string-ref subs k) (string-ref s j))))\\\n\t        \t    (= k lu))) i)\\\n\t              (else (loop (+ i 1)))))))\\\n          (define (apropos-1 e)\\\n            (for-each\\\n             (lambda (binding)\\\n               (if (and (pair? binding)\\\n                        (substring? name (symbol->string (car binding))))\\\n                   (let ((str (format #f \\\"~%~A: ~A\\\" \\\n\t        \t              (car binding) \\\n\t        \t              (if (procedure? (cdr binding))\\\n\t        \t                  (procedure-documentation (cdr binding))\\\n\t        \t                  (cdr binding)))))\\\n                     (if (not port)\\\n                         (snd-print str)\\\n\t                 (display str port)))))\\\n             e))\\\n          (if (or (not (string? name))\\\n                  (= (length name) 0))\\\n              (error 'wrong-type-arg \\\"apropos argument should be a non-nil string\\\")\\\n              (begin \\\n                 (if (not (eq? (current-environment) (global-environment)))\\\n                     (for-each apropos-1 (environment->list (current-environment)))) \\\n                 (apropos-1 (global-environment)))))\");\n\n  XEN_EVAL_C_STRING(\"\\\n(define break-ok #f)\\\n(define break-exit #f)  ; a kludge to get 2 funcs to share a local variable\\n\\\n(define break-enter #f)\\\n\\\n(let ((saved-listener-prompt (listener-prompt)))\\\n  (set! break-exit (lambda ()\\\n\t\t     (reset-hook! read-hook)\\\n\t\t     (set! (listener-prompt) saved-listener-prompt)\\\n\t\t     #f))\\\n  (set! break-enter (lambda ()\\\n\t\t      (set! saved-listener-prompt (listener-prompt)))))\\\n\\\n(define-macro (break)\\\n  `(let ((__break__ (current-environment)))\\\n     (break-enter)\\\n     (set! (listener-prompt) (format #f \\\"~A>\\\" (if (defined? __func__) __func__ 'break)))\\\n     (call/cc\\\n      (lambda (return)\\\n\t(set! break-ok return)      ; save current program loc so (break-ok) continues from the break\\n\\\n\t(add-hook! read-hook        ; anything typed in the listener is evaluated in the environment of the break call\\n\\\n\t\t   (lambda (str)\\\n\t\t     (eval-string str __break__)))\\\n\t(error 'snd-top-level)))    ; jump back to the top level\\n\\\n     (break-exit)))                 ; we get here if break-ok is called\\n\\\n\");\n\n#endif\n\n#if HAVE_SCHEME && USE_GTK && (!HAVE_GTK_ADJUSTMENT_GET_UPPER)\n  /* Gtk 3 is removing direct struct accesses (which they should have done years ago), so we need compatibility functions: */\n  XEN_EVAL_C_STRING(\"(define (gtk_widget_get_window w) (.window w))\");\n  XEN_EVAL_C_STRING(\"(define (gtk_font_selection_dialog_get_ok_button w) (.ok_button w))\");\n  XEN_EVAL_C_STRING(\"(define (gtk_font_selection_dialog_get_apply_button w) (.apply_button w))\");\n  XEN_EVAL_C_STRING(\"(define (gtk_font_selection_dialog_get_cancel_button w) (.cancel_button w))\");\n  XEN_EVAL_C_STRING(\"(define (gtk_color_selection_dialog_get_color_selection w) (.colorsel w))\");\n  XEN_EVAL_C_STRING(\"(define (gtk_dialog_get_action_area w) (.action_area w))\");\n  XEN_EVAL_C_STRING(\"(define (gtk_dialog_get_content_area w) (.vbox w))\");\n  /* also gtk_adjustment fields, but I think they are not in use in Snd's gtk code */\n#endif\n\n#if HAVE_FORTH\n  XEN_EVAL_C_STRING(\"<'> redo alias redo-edit\");        /* consistency with Ruby */ \n  XEN_EVAL_C_STRING(\"<'> undo alias undo-edit\"); \n  XEN_EVAL_C_STRING(\": clm-print ( fmt :optional args -- ) fth-format snd-print drop ;\"); \n#endif\n\n#if HAVE_RUBY\n  XEN_EVAL_C_STRING(\"def clm_print(str, *args)\\n\\\n                      snd_print format(str, *args)\\n\\\n                      end\");\n#endif\n\n#if HAVE_SCHEME\n  XEN_EVAL_C_STRING(\"(define (clm-print . args) \\\"(clm-print . args) applies format to args and prints the result via snd-print\\\" \\\n                       (snd-print (apply format #f args)))\");\n#endif\n\n#if HAVE_GL\n  XEN_DEFINE_PROCEDURE(\"snd-glx-context\", g_snd_glx_context_w, 0, 0, 0, \"OpenGL GLXContext\");\n#endif\n\n#if HAVE_STATIC_XM\n  #if USE_MOTIF\n    Init_libxm();\n    #if HAVE_FORTH\n      fth_add_loaded_files(\"libxm.so\");\n    #endif\n  #else\n    Init_libxg();\n    #if HAVE_FORTH\n      fth_add_loaded_files(\"libxg.so\");\n    #endif\n  #endif\n#endif\n\n#if (HAVE_GL) && (!JUST_GL)\n  Init_libgl();\n#endif\n\n#if MUS_DEBUGGING\n  XEN_YES_WE_HAVE(\"snd-debug\");\n#endif\n\n#if HAVE_ALSA\n  XEN_YES_WE_HAVE(\"alsa\");\n#endif\n\n#if HAVE_OSS\n  XEN_YES_WE_HAVE(\"oss\");\n#endif\n\n#if MUS_ESD\n  XEN_YES_WE_HAVE(\"esd\");\n#endif\n\n#if MUS_PULSEAUDIO\n  XEN_YES_WE_HAVE(\"pulse-audio\");\n#endif\n\n#if MUS_JACK\n  XEN_YES_WE_HAVE(\"jack\");\n#endif\n\n#if HAVE_GSL\n  XEN_YES_WE_HAVE(\"gsl\");\n#endif\n\n#if USE_MOTIF\n  XEN_YES_WE_HAVE(\"snd-motif\");\n#endif\n\n#if USE_GTK\n  XEN_YES_WE_HAVE(\"snd-gtk\");\n#if HAVE_GTK_3\n  XEN_YES_WE_HAVE(\"gtk3\");\n#else\n  XEN_YES_WE_HAVE(\"gtk2\");\n#endif\n#endif\n\n#if USE_NO_GUI\n  XEN_YES_WE_HAVE(\"snd-nogui\");\n#endif\n\n#if HAVE_FORTH\n  XEN_YES_WE_HAVE(\"snd-forth\");\n#endif\n\n#if HAVE_SCHEME\n  XEN_YES_WE_HAVE(\"snd-s7\");\n#endif\n\n#if HAVE_RUBY\n  XEN_YES_WE_HAVE(\"snd-ruby\");\n  /* we need to set up the search path so that load and require will work as in the program irb */\n  #ifdef RUBY_SEARCH_PATH\n    {\n      /* this code stolen from ruby.c */\n      char *str, *buf;\n      int i, j = 0, len;\n      str = (char *)(RUBY_SEARCH_PATH);\n      len = mus_strlen(str);\n      buf = (char *)calloc(len + 1, sizeof(char));\n      for (i = 0; i < len; i++)\n\tif (str[i] == ':')\n\t  {\n\t    buf[j] = 0;\n\t    if (j > 0)\n\t      {\n\t\tXEN_ADD_TO_LOAD_PATH(buf);\n\t      }\n\t    j = 0;\n\t  }\n\telse buf[j++] = str[i];\n      if (j > 0)\n\t{\n\t  buf[j] = 0;\n\t  XEN_ADD_TO_LOAD_PATH(buf);\n\t}\n      free(buf);\n    }\n  #endif\n#endif\n\n  XEN_YES_WE_HAVE(\"snd\");\n  XEN_YES_WE_HAVE(\"snd\" SND_MAJOR_VERSION);\n  XEN_YES_WE_HAVE(\"snd-\" SND_MAJOR_VERSION \".\" SND_MINOR_VERSION);\n}\n", "meta": {"hexsha": "f7ba880841f2fb61c224fa0f875c16170137ec17", "size": 85111, "ext": "c", "lang": "C", "max_stars_repo_path": "sources/snd-xen.c", "max_stars_repo_name": "OS2World/MM-SOUND-Snd", "max_stars_repo_head_hexsha": "b633660e5945a6a6b095cd9aa3178deab56b354f", "max_stars_repo_licenses": ["Ruby"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-08-27T17:57:08.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-27T17:57:08.000Z", "max_issues_repo_path": "sources/snd-xen.c", "max_issues_repo_name": "OS2World/MM-SOUND-Snd", "max_issues_repo_head_hexsha": "b633660e5945a6a6b095cd9aa3178deab56b354f", "max_issues_repo_licenses": ["Ruby"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sources/snd-xen.c", "max_forks_repo_name": "OS2World/MM-SOUND-Snd", "max_forks_repo_head_hexsha": "b633660e5945a6a6b095cd9aa3178deab56b354f", "max_forks_repo_licenses": ["Ruby"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6603834904, "max_line_length": 167, "alphanum_fraction": 0.6401757705, "num_tokens": 26738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.04468087408894116, "lm_q2_score": 0.014503580756310332, "lm_q1q2_score": 0.000648032665611492}}
{"text": "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\n#pragma once\n\n#include <gsl/gsl>\n\n#include \"core/optimizer/graph_transformer.h\"\n#include \"orttraining/core/optimizer/graph_transformer_config.h\"\n#include \"orttraining/core/session/training_session.h\"\n\nnamespace onnxruntime {\nstruct FreeDimensionOverride;\n\nnamespace training {\nnamespace transformer_utils {\n\n/** Generates all pre-training transformers for this level. */\nstd::vector<std::unique_ptr<GraphTransformer>> GeneratePreTrainingTransformers(\n    TransformerLevel level,\n    const std::unordered_set<std::string>& weights_to_train,\n    const TrainingGraphTransformerConfiguration& config,\n    const IExecutionProvider& execution_provider,  // required for constant folding\n    const std::unordered_set<std::string>& rules_and_transformers_to_disable = {});\n\n/** Generates all predefined (both rule-based and non-rule-based) transformers for this level.\n    If transformers_and_rules_to_enable is not empty, it returns the intersection between the predefined transformers/rules \n    and the transformers_and_rules_to_enable. */\nInlinedVector<std::unique_ptr<GraphTransformer>> GenerateTransformers(\n    TransformerLevel level,\n    const std::unordered_set<std::string>& weights_to_train,\n    gsl::span<const FreeDimensionOverride> free_dimension_overrides,\n    const InlinedHashSet<std::string>& rules_and_transformers_to_disable = {});\n\n}  // namespace transformer_utils\n}  // namespace training\n}  // namespace onnxruntime\n", "meta": {"hexsha": "d0bba49746315c08117874959f7658c0e4009664", "size": 1529, "ext": "h", "lang": "C", "max_stars_repo_path": "orttraining/orttraining/core/optimizer/graph_transformer_utils.h", "max_stars_repo_name": "SiriusKY/onnxruntime", "max_stars_repo_head_hexsha": "3c5853dcbc9d5dda2476afa8c6105802d2b8e53d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 669.0, "max_stars_repo_stars_event_min_datetime": "2018-12-03T22:00:31.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-06T19:42:49.000Z", "max_issues_repo_path": "orttraining/orttraining/core/optimizer/graph_transformer_utils.h", "max_issues_repo_name": "SiriusKY/onnxruntime", "max_issues_repo_head_hexsha": "3c5853dcbc9d5dda2476afa8c6105802d2b8e53d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 440.0, "max_issues_repo_issues_event_min_datetime": "2018-12-03T21:09:56.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-06T20:47:23.000Z", "max_forks_repo_path": "orttraining/orttraining/core/optimizer/graph_transformer_utils.h", "max_forks_repo_name": "SiriusKY/onnxruntime", "max_forks_repo_head_hexsha": "3c5853dcbc9d5dda2476afa8c6105802d2b8e53d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 140.0, "max_forks_repo_forks_event_min_datetime": "2018-12-03T21:15:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-06T18:02:36.000Z", "avg_line_length": 40.2368421053, "max_line_length": 124, "alphanum_fraction": 0.7939829954, "num_tokens": 305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.050330632597476874, "lm_q2_score": 0.012821211413997247, "lm_q1q2_score": 0.0006452996811324724}}
{"text": "#pragma once\n/*\n * (C) Copyright 2021 UCAR\n *\n * This software is licensed under the terms of the Apache Licence Version 2.0\n * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.\n */\n/*! \\addtogroup ioda_internals_engines_hh\n *\n * @{\n * \\file HH-util.h\n * \\brief Utility functions for HDF5.\n */\n\n#include <string>\n#include <utility>\n#include <vector>\n\n#include <hdf5.h>\n#include <gsl/gsl-lite.hpp>\n\n#include \"./Handles.h\"\n#include \"ioda/defs.h\"\n#include \"ioda/Exception.h\"\n#include \"ioda/Types/Marshalling.h\"\n\nnamespace ioda {\nnamespace detail {\nnamespace Engines {\nnamespace HH {\nclass HH_Attribute;\nclass HH_Variable;\n\n//#if H5_VERSION_GE(1, 12, 0)\n//typedef H5R_ref_t ref_t;\n//#else\ntypedef hobj_ref_t ref_t;\n//#endif\n\n// brief Conveys information that a variable (or scale) is attached along a specified axis.\n//typedef std::pair<ref_t, unsigned> ref_axis_t;\n\n/// @brief Duplicate the HDF5 dataset list structure for REFERENCE_LISTs.\nstruct ds_list_t {\n  hobj_ref_t ref;       /* object reference  */\n  unsigned int dim_idx; /* dimension index of the dataset */\n};\n\n/// Data to pass to/from iterator classes.\nstruct IODA_HIDDEN Iterator_find_attr_data_t {\n  std::string search_for;\n  hsize_t idx  = 0;\n  bool success = false;\n};\n\n/// Callback function for H5Aiterate / H5Aiterate2 / H5Aiterate1.\n#if H5_VERSION_GE(1, 8, 0)\nIODA_HIDDEN herr_t iterate_find_attr(hid_t loc_id, const char* name, const H5A_info_t* info,\n                                     void* op_data);\n#else\nIODA_HIDDEN herr_t iterate_find_attr(hid_t loc_id, const char* name, void* op_data);\n#endif\n\n/*! @brief Determine attribute creation order for a dataset.\n *  @param obj is the dataset being queried\n *  @param objType is the type of object (Dataset or Group).\n *  @return H5_INDEX_CRT_ORDER if creation order is tracked.\n *  @return H5_INDEX_NAME if creation order is not tracked.\n *  @details Check if the variable has attribute creation order stored and/or indexed.\n * This is not the default, but it can speed up object list accesses considerably.\n */\nIODA_HIDDEN H5_index_t getAttrCreationOrder(hid_t obj, H5O_type_t objType);\n\n/// @brief Linear search to find an attribute.\n/// @param baseObject is the object that could contain the attribute.\n/// @param attname is the name of the attribute.\n/// @param iteration_type is the type of iteration for the search. See getAttrCreationOrder.\n/// @return A pair of (success_flag, index).\nIODA_HIDDEN std::pair<bool, hsize_t> iterativeAttributeSearch(hid_t baseObject,\n                                                              const char* attname,\n                                                              H5_index_t iteration_type);\n\n/// @brief Linear search to find and open an attribute, if it exists.\n/// @param baseObject is the object that could contain the attribute.\n/// @param objType is the type of object (Dataset or Group).\n/// @param attname is the name of the attribute.\n/// @return An open handle to the attribute, if it exists.\n/// @return An invalid handle if the attribute does not exist or upon general failure.\n/// @details This function is useful because it is faster than the regular attribute\n///   open by name routine, which does not take advantage of attribute creation order\n///   indexing. Performance is particularly good when there are few attributes attached\n///   to the base object.\nIODA_HIDDEN HH_Attribute iterativeAttributeSearchAndOpen(hid_t baseObject, H5O_type_t objType,\n                                                         const char* attname);\n\n/*! @brief Attribute DIMENSION_LIST update function\n* \n* @details This function exists to update DIMENSION_LISTs without updating the\n* mirrored REFERENCE_LIST entry in the variable's scales. This is done for\n* performance reasons, as attaching dimension scales for hundreds of\n* variables sequentially is very slow.\n*\n* NOTE: This code does not use the regular atts.open(...) call\n* for performance reasons when we have to repeat this call for hundreds or\n* thousands of variables. We instead do a creation-order-preferred search.\n*\n* @param var is the variable of interest.\n* @param new_dim_list is the mapping of dimensions that should be added to the variable.\n*/\nIODA_HIDDEN void attr_update_dimension_list(HH_Variable* var,\n                                            const std::vector<std::vector<ref_t>>& new_dim_list);\n\n/*! @brief Attribute REFERENCE_LIST update function\n* \n* @details This function exists to update REFERENCE_LISTs without updating the\n* mirrored DIMENSION_LIST entry. This is done for\n* performance reasons, as attaching dimension scales for hundreds of\n* variables sequentially is very slow.\n*\n* NOTE: This code does not use the regular atts.open(...) call\n* for performance reasons when we have to repeat this call for hundreds or\n* thousands of variables. We instead do a creation-order-preferred search.\n*\n* @param scale is the scale of interest.\n* @param ref_var_axis_list is the mapping of variables-dimension numbers that\n*   should be added to the scale's REFERENCE_LIST attribute.\n*/\nIODA_HIDDEN void attr_update_reference_list(HH_Variable* scale,\n                                            const std::vector<ds_list_t>& ref_var_axis);\n\n\n\n/// @brief A \"view\" of hvl_t objects. Adds C++ conveniences to an otherwise troublesome class.\n/// @tparam Inner is the datatype that we are really manipulating.\ntemplate <class Inner>\nstruct IODA_HIDDEN View_hvl_t {\n  hvl_t &obj;\n  View_hvl_t(hvl_t& obj) : obj{obj} {}\n  size_t size() const { return obj.len; }\n  void resize(size_t newlen) {\n    if (newlen) {\n      obj.p = (obj.p) ? H5resize_memory(obj.p, newlen * sizeof(Inner))\n        : H5allocate_memory(newlen * sizeof(Inner), false);\n      if (!obj.p) throw Exception(\"Failed to allocate memory\", ioda_Here());\n    }\n    else {\n      if (obj.p)\n        if (H5free_memory(obj.p) < 0) throw Exception(\"Failed to free memory\", ioda_Here());\n      obj.p = nullptr;\n    }\n    obj.len = newlen;\n  }\n  void clear() { resize(0); }\n  Inner* at(size_t i) {\n    if (i >= obj.len) throw Exception(\"Out-of-bounds access\", ioda_Here())\n      .add(\"i\", i).add(\"obj.len\", obj.len);\n    return operator[](i);\n  }\n  Inner* operator[](size_t i) {\n    return &(static_cast<Inner*>(obj.p)[i]);\n  }\n};\n\n/*! Internal structure to encapsulate resources and prevent leaks.\n* \n* When reading dimension scales, calls to H5Aread return variable-length arrays\n* that must be reclaimed. We use a custom object to encapsulate this.\n*/\nstruct IODA_HIDDEN Vlen_data {\n  std::unique_ptr<hvl_t[]> buf;  // NOLINT: C array and visibility warnings.\n  HH_hid_t typ, space;           // NOLINT: C visibility warnings.\n  size_t sz;\n  Vlen_data(size_t sz, HH_hid_t typ, HH_hid_t space)\n      : buf(new hvl_t[sz]), typ{typ}, space{space}, sz{sz} {\n    if (!buf) throw Exception(\"Failed to allocate buf\", ioda_Here());\n    for (size_t i = 0; i < sz; i++) {\n      buf[i].len = 0;\n      buf[i].p   = nullptr;\n    }\n  }\n  ~Vlen_data() {\n    if (buf) {\n      /*\n      for (size_t i = 0; i < sz; i++) {\n        if (buf[i].p) delete[] buf[i].p;\n        buf[i].len = 0;\n        buf[i].p   = nullptr;\n      }\n      */\n\n      H5Dvlen_reclaim(typ.get(), space.get(), H5P_DEFAULT, reinterpret_cast<void*>(buf.get()));\n    }\n  }\n  Vlen_data(const Vlen_data&) = delete;\n  Vlen_data(Vlen_data&&)      = delete;\n  Vlen_data operator=(const Vlen_data&) = delete;\n  Vlen_data operator=(Vlen_data&&) = delete;\n\n  hvl_t& operator[](size_t idx) { return (buf).get()[idx]; }\n};\n\n/// @brief Gets a variable / group / link name from an id. Useful for debugging.\n/// @param obj_id is the object.\n/// @return One of the possible object names.\n/// @throws ioda::Exception if obj_id is invalid.\nIODA_HIDDEN std::string getNameFromIdentifier(hid_t obj_id);\n\n/// @brief Convert from variable-length data to fixed-length data.\n/// @param in_buf is the input buffer. Buffer has a sequence of pointers, serialized as chars.\n/// @param unitLength is the length of each fixed-length element.\n/// @param lengthsAreExact signifies that padding is not needed between elements. Each\n///   variable-length string is already of length unitLength. If false, then strlen\n///   is calculated for each element (which finds the first null byte).\n/// @returns the output buffer.\nIODA_HIDDEN std::vector<char> convertVariableLengthToFixedLength(\n  gsl::span<const char> in_buf, size_t unitLength, bool lengthsAreExact);\n\n/// @brief Convert from fixed-length data to variable-length data.\n/// @param in_buf is the input buffer. Buffer is a sequence of fixed-length elements (*not* pointers).\n/// @param unitLength is the length of each fixed-length element.\n/// @returns the converted buffer.\nIODA_HIDDEN Marshalled_Data<char*, char*, true> convertFixedLengthToVariableLength(\n  gsl::span<const char> in_buf, size_t unitLength);\n\n}  // namespace HH\n}  // namespace Engines\n}  // namespace detail\n}  // namespace ioda\n", "meta": {"hexsha": "7afe00133aa3b688dbf20a2e0cf03bb7e0054bb8", "size": 8903, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engines/ioda/src/ioda/Engines/HH/HH/HH-util.h", "max_stars_repo_name": "NOAA-EMC/ioda", "max_stars_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/engines/ioda/src/ioda/Engines/HH/HH/HH-util.h", "max_issues_repo_name": "NOAA-EMC/ioda", "max_issues_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engines/ioda/src/ioda/Engines/HH/HH/HH-util.h", "max_forks_repo_name": "NOAA-EMC/ioda", "max_forks_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.8777292576, "max_line_length": 102, "alphanum_fraction": 0.6971807256, "num_tokens": 2189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.0440186461006112, "lm_q2_score": 0.01450358075631033, "lm_q1q2_score": 0.0006384279885036594}}
{"text": "#pragma once\n\n#include \"options.h\"\n#include <cstdio>\n#include <fmt/color.h>\n#include <fmt/printf.h>\n#include <gsl/gsl-lite.hpp>\n\nnamespace angonoka::cli {\n/**\n    Print text to stdout if not in quiet mode.\n\n    @param options CLI options\n*/\ntemplate <typename... T>\nvoid print(\n    const Options& options,\n    fmt::format_string<T...> fmt,\n    T&&... args)\n{\n    if (options.quiet) return;\n    fmt::print(fmt, std::forward<T>(args)...);\n}\n\n/**\n    Prints red text.\n\n    Conditionally disables the color depending on\n    CLI options.\n\n    @param options CLI options\n*/\ntemplate <typename... T>\nvoid print_error(\n    const Options& options,\n    std::FILE* output,\n    fmt::format_string<T...> fmt,\n    T&&... args)\n{\n    if (options.color) {\n        fmt::print(\n            output,\n            fg(fmt::terminal_color::red),\n            fmt::string_view{fmt},\n            std::forward<T>(args)...);\n    } else {\n        fmt::print(output, fmt, std::forward<T>(args)...);\n    }\n}\n\n/**\n    Critical error message.\n\n    Used for progress messages with ellipsis like\n\n    Progress message... <die()>Error\n    An error has occured.\n\n    @param options CLI options\n*/\ntemplate <typename... T>\nvoid die(\n    const Options& options,\n    fmt::format_string<T...> fmt,\n    T&&... args)\n{\n\n    if (!options.quiet) print_error(options, stdout, \"Error\\n\");\n    print_error(options, stderr, fmt, std::forward<T>(args)...);\n}\n} // namespace angonoka::cli\n", "meta": {"hexsha": "c9eea6fe2582875dbe0e6b7105b93d0947ef6599", "size": 1437, "ext": "h", "lang": "C", "max_stars_repo_path": "src/cli/utils.h", "max_stars_repo_name": "coffee-lord/angonoka", "max_stars_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-10-23T18:05:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T21:53:24.000Z", "max_issues_repo_path": "src/cli/utils.h", "max_issues_repo_name": "coffee-lord/angonoka", "max_issues_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2022-02-12T19:52:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-12T19:55:52.000Z", "max_forks_repo_path": "src/cli/utils.h", "max_forks_repo_name": "coffee-lord/angonoka", "max_forks_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.9583333333, "max_line_length": 64, "alphanum_fraction": 0.6047320807, "num_tokens": 363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.02479816379916523, "lm_q2_score": 0.025178841426291586, "lm_q1q2_score": 0.0006243890339623858}}
{"text": "//--------------------------------------------------------------------------------------------------\n// \n//\tWIN-BLUETOOTH\n//\n//--------------------------------------------------------------------------------------------------\n//\n// The MIT License (MIT)\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of this software \n// and associated documentation files (the \"Software\"), to deal in the Software without \n// restriction, including without limitation the rights to use, copy, modify, merge, publish, \n// distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the \n// Software is furnished to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in all copies or \n// substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING \n// BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND \n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, \n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING \n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n//--------------------------------------------------------------------------------------------------\n//\n// Copyright (c) 2018 Nic Holthaus\n// \n//--------------------------------------------------------------------------------------------------\n//\n// ATTRIBUTION:\n// https://github.com/martinmoene/gsl-lite/releases\n//\n//--------------------------------------------------------------------------------------------------\n//\n/// @file\tobexResponse.h\n/// @brief\tOBEX server response classes\n//\n//--------------------------------------------------------------------------------------------------\n\n#pragma once\n#ifndef obexResponse_h__\n#define obexResponse_h__\n\n//-------------------------\n//\tINCLUDES\n//-------------------------\n\n#include <QObject>\n#include <gsl-lite.h> \n#include <obexHeader.h>\n\n//-------------------------\n//\tFORWARD DECLARATIONS\n//-------------------------\n\nclass QDataStream;\n\n//--------------------------------------------------------------------------------------------------\n//\tOBEXResponse\n//--------------------------------------------------------------------------------------------------\nclass OBEXResponse\n{\n\tQ_GADGET\n\npublic:\n\n\tfriend QDataStream& operator>>(QDataStream& in, OBEXResponse& response);\n\n\t// OBEX operation response codes. See OBEX standard chapter 3.2.1\n\tclass Code\n\t{\n\tpublic:\n\n\t\tenum class Enum : quint8\n\t\t{\n\t\t\tINVALID\t\t\t\t\t= 0x00,\n\t\t\tCONTINUE\t\t\t\t= 0x90,\n\t\t\tSUCCESS\t\t\t\t\t= 0xA0,\n\t\t\tSERVICEUNAVAILABLE\t\t= 0xD3,\n\t\t};\n\n\t\tCode(quint8 value);\n\t\toperator quint8() const;\n\t\tbool isFinal() const;\n\t\tbool operator==(const Code& other) const;\n\t\tbool operator!=(const Code& other) const;\n\n\tprivate:\n\n\t\tCode::Enum\tm_code;\n\t\tbool\t\tm_isFinal = false;\n\t};\t\n\npublic:\n\n\tOBEXResponse() = default;\n\tvirtual ~OBEXResponse() = default;\n\tvirtual gsl::string_span data() = 0;\t// returns a span representing the response-specific data storage\n\tvirtual quint16 packetLength() = 0;\t\t// packet length value from the response data\n\tvirtual bool validateAndFixup() = 0;\t// called at the end of operator>>. Used to validate code fields, and convert\n\t\t\t\t\t\t\t\t\t\t\t// large types from big to little endian. Returns true on success.\n\tbool isValid() const;\n\nprotected:\n\n\tbool m_valid = false;\n\tstd::vector<OBEXHeader>\tm_optionalHeaders;\n};\n\nQDataStream& operator>>(QDataStream& in, OBEXResponse& response);\n\n//--------------------------------------------------------------------------------------------------\n//\tOBEXConnectResponse\n//--------------------------------------------------------------------------------------------------\n\nclass OBEXConnectResponse : public OBEXResponse\n{\npublic:\n\n\tOBEXConnectResponse() = default;\n\tvirtual ~OBEXConnectResponse() = default;\n\tvirtual gsl::string_span data() override;\n\tvirtual quint16 packetLength() override;\t// the return value will generally not be valid until after data has been streamed into the class.\n\tvirtual bool validateAndFixup() override;\n\tquint16 maxPacketLength() const;\n\nprivate:\n\n#pragma pack(push, 1)\n\tstruct Data\n\t{\n\t\tOBEXResponse::Code::Enum    code\t\t\t= Code::Enum::INVALID;\n\t\tquint16\t\t\t\t\t\tlength\t\t\t= 0;\n\t\tquint8\t\t\t\t\t\tversion\t\t\t= 0;\n\t\tquint8\t\t\t\t\t\tflags\t\t\t= 0;\n\t\tquint16\t\t\t\t\t\tmaxPacketLength = 0;\n\t} m_data;\n#pragma pack(pop)\n};\n\n//--------------------------------------------------------------------------------------------------\n//\tOBEXDisconnectResponse\n//--------------------------------------------------------------------------------------------------\n\nclass OBEXDisconnectResponse : public OBEXResponse\n{\npublic:\n\n\tOBEXDisconnectResponse() = default;\n\tvirtual ~OBEXDisconnectResponse() = default;\n\t\n\tvirtual gsl::string_span data() override;\n\tvirtual quint16 packetLength() override;\n\tvirtual bool validateAndFixup() override;\n\n#pragma pack(push, 1)\n\tstruct Data\n\t{\n\t\tOBEXResponse::Code::Enum    code = Code::Enum::SUCCESS;\n\t\tquint16\t\t\t\t\t\tlength = 0;\n\t} m_data;\n#pragma pack(pop)\n};\n\n//--------------------------------------------------------------------------------------------------\n//\tOBEXPutResponse\n//--------------------------------------------------------------------------------------------------\n\nclass OBEXPutResponse : public OBEXResponse\n{\npublic:\n\n\tOBEXPutResponse() = default;\n\tvirtual ~OBEXPutResponse() = default;\n\t\n\tvirtual gsl::string_span data() override;\n\tvirtual quint16 packetLength() override;\n\tvirtual bool validateAndFixup() override;\n\tbool continueSending() const;\n\nprotected:\n\n#pragma pack(push, 1)\n\tstruct Data\n\t{\n\t\tOBEXResponse::Code::Enum    code = Code::Enum::CONTINUE;\t// assume success until proven otherwise\n\t\tquint16\t\t\t\t\t\tlength = 0;\n\t} m_data;\n#pragma pack(pop)\n\n};\n#endif // obexResponse_h__\n", "meta": {"hexsha": "5cc1a8798b14c9a597244f84098e88bc3ebcb19e", "size": 5936, "ext": "h", "lang": "C", "max_stars_repo_path": "include/obexResponse.h", "max_stars_repo_name": "nholthaus/win-bluetooth", "max_stars_repo_head_hexsha": "f0b7f961e3e1d8dd00f5536a203f94e8316c1c17", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-07-18T01:31:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-17T09:43:30.000Z", "max_issues_repo_path": "include/obexResponse.h", "max_issues_repo_name": "nholthaus/win-bluetooth", "max_issues_repo_head_hexsha": "f0b7f961e3e1d8dd00f5536a203f94e8316c1c17", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-08-19T11:18:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-28T21:16:07.000Z", "max_forks_repo_path": "include/obexResponse.h", "max_forks_repo_name": "nholthaus/win-bluetooth", "max_forks_repo_head_hexsha": "f0b7f961e3e1d8dd00f5536a203f94e8316c1c17", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-07-17T12:06:28.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-30T08:41:16.000Z", "avg_line_length": 30.7564766839, "max_line_length": 140, "alphanum_fraction": 0.5380727763, "num_tokens": 1171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.03732688680867723, "lm_q2_score": 0.016657037049822285, "lm_q1q2_score": 0.0006217553365266594}}
{"text": "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\n#pragma once\n\n#include <memory>\n#include <numeric>\n#include <algorithm>\n#include <vector>\n#include <string>\n#include <limits>\n#include <memory>\n#include <optional>\n#include <list>\n#include <map>\n#include <deque>\n#include <chrono>\n#include <variant>\n#include <cassert>\n\n#include <wrl/client.h>\n#include <wrl/implements.h>\n\n#include <wil/wrl.h>\n#include <wil/result.h>\n\n#include <gsl/gsl>\n\n#include <d3d12.h>\n#include <d3d12sdklayers.h>\n#include \"External/D3DX12/d3dx12.h\"\n\n#include <DirectML.h>\n#include \"core/common/common.h\"\n#include \"ErrorHandling.h\"\n\n// DirectML helper libraries\n#include \"External/DirectMLHelpers/ApiTraits.h\"\n#include \"External/DirectMLHelpers/ApiHelpers.h\"\n#include \"External/DirectMLHelpers/DirectMLSchema.h\"\n#include \"External/DirectMLHelpers/AbstractOperatorDesc.h\"\n#include \"External/DirectMLHelpers/GeneratedSchemaTypes.h\"\n#include \"External/DirectMLHelpers/SchemaHelpers.h\"\n#include \"External/DirectMLHelpers/GeneratedSchemaHelpers.h\"\n\nusing Microsoft::WRL::ComPtr;\n\n// Windows pollutes the macro space, causing a build break in schema.h.\n#undef OPTIONAL\n\n#include \"core/providers/dml/DmlExecutionProvider/inc/DmlExecutionProvider.h\"\n#include \"core/providers/dml/OperatorAuthorHelper/MLOperatorAuthorHelper.h\"\n#include \"core/providers/dml/OperatorAuthorHelper/Common.h\"\n\n#include \"DmlCommon.h\"\n#include \"TensorDesc.h\"\n#include \"DescriptorPool.h\"\n#include \"IExecutionProvider.h\"\n", "meta": {"hexsha": "d057c944359c4e124c200522e1000a537b07b872", "size": 1504, "ext": "h", "lang": "C", "max_stars_repo_path": "onnxruntime/core/providers/dml/DmlExecutionProvider/src/precomp.h", "max_stars_repo_name": "lchang20/onnxruntime", "max_stars_repo_head_hexsha": "97b8f6f394ae02c73ed775f456fd85639c91ced1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2019-05-28T09:07:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T21:24:29.000Z", "max_issues_repo_path": "onnxruntime/core/providers/dml/DmlExecutionProvider/src/precomp.h", "max_issues_repo_name": "lchang20/onnxruntime", "max_issues_repo_head_hexsha": "97b8f6f394ae02c73ed775f456fd85639c91ced1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 82.0, "max_issues_repo_issues_event_min_datetime": "2019-06-21T20:03:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T07:33:51.000Z", "max_forks_repo_path": "onnxruntime/core/providers/dml/DmlExecutionProvider/src/precomp.h", "max_forks_repo_name": "lchang20/onnxruntime", "max_forks_repo_head_hexsha": "97b8f6f394ae02c73ed775f456fd85639c91ced1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2019-06-08T15:50:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T21:24:29.000Z", "avg_line_length": 25.4915254237, "max_line_length": 77, "alphanum_fraction": 0.7832446809, "num_tokens": 358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06187599264342621, "lm_q2_score": 0.010013570549313303, "lm_q1q2_score": 0.0006195996176437393}}
{"text": "/* -----------------------------------------------------------------------------\n * Copyright 2021 Jonathan Haigh\n * SPDX-License-Identifier: MIT\n * ---------------------------------------------------------------------------*/\n\n#ifndef SQ_INCLUDE_GUARD_system_linux_SqTypeSchemaImpl_h_\n#define SQ_INCLUDE_GUARD_system_linux_SqTypeSchemaImpl_h_\n\n#include \"core/typeutil.h\"\n#include \"system/SqTypeSchema.gen.h\"\n\n#include \"system/schema.h\"\n\n#include <gsl/gsl>\n\nnamespace sq::system::linux {\n\nclass SqTypeSchemaImpl : public SqTypeSchema<SqTypeSchemaImpl> {\npublic:\n  explicit SqTypeSchemaImpl(const TypeSchema &type_schema);\n\n  SQ_ND Result get_name() const;\n  SQ_ND Result get_doc() const;\n  SQ_ND Result get_fields() const;\n\n  SQ_ND Primitive to_primitive() const override;\n\nprivate:\n  gsl::not_null<const TypeSchema *> type_schema_;\n};\n\n} // namespace sq::system::linux\n\n#endif // SQ_INCLUDE_GUARD_system_linux_SqTypeSchemaImpl_h_\n", "meta": {"hexsha": "147a8e30af53480d9993ac88954e89af2a02783f", "size": 931, "ext": "h", "lang": "C", "max_stars_repo_path": "src/system/include/system/linux/SqTypeSchemaImpl.h", "max_stars_repo_name": "jonathanhaigh/sq", "max_stars_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-12T16:21:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-12T16:21:41.000Z", "max_issues_repo_path": "src/system/include/system/linux/SqTypeSchemaImpl.h", "max_issues_repo_name": "jonathanhaigh/sq", "max_issues_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 44.0, "max_issues_repo_issues_event_min_datetime": "2021-02-08T19:17:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-05T18:51:38.000Z", "max_forks_repo_path": "src/system/include/system/linux/SqTypeSchemaImpl.h", "max_forks_repo_name": "jonathanhaigh/sq", "max_forks_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6, "max_line_length": 80, "alphanum_fraction": 0.6530612245, "num_tokens": 199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.03904829048965015, "lm_q2_score": 0.015424553298195622, "lm_q1q2_score": 0.000602302437861034}}
{"text": "/* -----------------------------------------------------------------------------\n * Copyright 2021 Jonathan Haigh\n * SPDX-License-Identifier: MIT\n * ---------------------------------------------------------------------------*/\n\n#ifndef SQ_INCLUDE_GUARD_system_linux_SqParamSchemaImpl_h_\n#define SQ_INCLUDE_GUARD_system_linux_SqParamSchemaImpl_h_\n\n#include \"core/typeutil.h\"\n#include \"system/SqParamSchema.gen.h\"\n#include \"system/schema.h\"\n\n#include <gsl/gsl>\n\nnamespace sq::system::linux {\n\nclass SqParamSchemaImpl : public SqParamSchema<SqParamSchemaImpl> {\npublic:\n  explicit SqParamSchemaImpl(const ParamSchema &param_schema);\n\n  SQ_ND Result get_name() const;\n  SQ_ND Result get_doc() const;\n  SQ_ND Result get_index() const;\n  SQ_ND Result get_type() const;\n  SQ_ND Result get_required() const;\n  SQ_ND Result get_default_value() const;\n  SQ_ND Result get_default_value_doc() const;\n\n  SQ_ND Primitive to_primitive() const override;\n\nprivate:\n  gsl::not_null<const ParamSchema *> param_schema_;\n};\n\n} // namespace sq::system::linux\n\n#endif // SQ_INCLUDE_GUARD_system_linux_SqParamSchemaImpl_h_\n", "meta": {"hexsha": "43b7658b55b04afd61c11363cf78f80f17a4ac1b", "size": 1099, "ext": "h", "lang": "C", "max_stars_repo_path": "src/system/include/system/linux/SqParamSchemaImpl.h", "max_stars_repo_name": "jonathanhaigh/sq", "max_stars_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-12T16:21:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-12T16:21:41.000Z", "max_issues_repo_path": "src/system/include/system/linux/SqParamSchemaImpl.h", "max_issues_repo_name": "jonathanhaigh/sq", "max_issues_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 44.0, "max_issues_repo_issues_event_min_datetime": "2021-02-08T19:17:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-05T18:51:38.000Z", "max_forks_repo_path": "src/system/include/system/linux/SqParamSchemaImpl.h", "max_forks_repo_name": "jonathanhaigh/sq", "max_forks_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9210526316, "max_line_length": 80, "alphanum_fraction": 0.6742493176, "num_tokens": 242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.03358950468268333, "lm_q2_score": 0.01771229494415716, "lm_q1q2_score": 0.0005949472139678352}}
{"text": "#ifndef VMICORE_VMIINITDATA_H\n#define VMICORE_VMIINITDATA_H\n\n#include <filesystem>\n#include <gsl/pointers>\n#include <libvmi/libvmi.h>\n\nclass VmiInitData\n{\n  public:\n    gsl::owner<vmi_init_data_t*> data{};\n\n    explicit VmiInitData(const std::filesystem::path& socketPath);\n\n    ~VmiInitData();\n};\n\n#endif // VMICORE_VMIINITDATA_H\n", "meta": {"hexsha": "a5e95e7f24513586fc8b061b1829452edb4da46a", "size": 331, "ext": "h", "lang": "C", "max_stars_repo_path": "vmicore/src/vmi/VmiInitData.h", "max_stars_repo_name": "GDATASoftwareAG/smartvmi", "max_stars_repo_head_hexsha": "68c9d9791c3b291ec2b49ffd8191c9cdf335baf3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2022-02-17T23:35:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T12:36:45.000Z", "max_issues_repo_path": "vmicore/src/vmi/VmiInitData.h", "max_issues_repo_name": "GDATASoftwareAG/smartvmi", "max_issues_repo_head_hexsha": "68c9d9791c3b291ec2b49ffd8191c9cdf335baf3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vmicore/src/vmi/VmiInitData.h", "max_forks_repo_name": "GDATASoftwareAG/smartvmi", "max_forks_repo_head_hexsha": "68c9d9791c3b291ec2b49ffd8191c9cdf335baf3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.4210526316, "max_line_length": 66, "alphanum_fraction": 0.7432024169, "num_tokens": 101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.022629197396471325, "lm_q2_score": 0.025565216336149464, "lm_q1q2_score": 0.0005785203269542197}}
{"text": "#pragma once\n\n#include \"HttpHeaders.h\"\n#include \"Library.h\"\n\n#include <gsl/span>\n\n#include <cstddef>\n#include <map>\n#include <string>\n\nnamespace CesiumAsync {\n\n/**\n * @brief A completed response for a 3D Tiles asset.\n */\nclass CESIUMASYNC_API IAssetResponse {\npublic:\n  /**\n   * @brief Default destructor\n   */\n  virtual ~IAssetResponse() = default;\n\n  /**\n   * @brief Returns the HTTP response code.\n   */\n  virtual uint16_t statusCode() const = 0;\n\n  /**\n   * @brief Returns the HTTP content type\n   */\n  virtual std::string contentType() const = 0;\n\n  /**\n   * @brief Returns the HTTP headers of the response\n   */\n  virtual const HttpHeaders& headers() const = 0;\n\n  /**\n   * @brief Returns the data of this response\n   */\n  virtual gsl::span<const std::byte> data() const = 0;\n};\n\n} // namespace CesiumAsync\n", "meta": {"hexsha": "10519057806beb521d144c174ffdb21144ae2c85", "size": 813, "ext": "h", "lang": "C", "max_stars_repo_path": "CesiumAsync/include/CesiumAsync/IAssetResponse.h", "max_stars_repo_name": "yieryi/cesium-native", "max_stars_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 154.0, "max_stars_repo_stars_event_min_datetime": "2021-03-30T14:08:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T00:01:43.000Z", "max_issues_repo_path": "CesiumAsync/include/CesiumAsync/IAssetResponse.h", "max_issues_repo_name": "yieryi/cesium-native", "max_issues_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 256.0, "max_issues_repo_issues_event_min_datetime": "2021-03-30T18:12:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:44:21.000Z", "max_forks_repo_path": "CesiumAsync/include/CesiumAsync/IAssetResponse.h", "max_forks_repo_name": "yieryi/cesium-native", "max_forks_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 66.0, "max_forks_repo_forks_event_min_datetime": "2021-03-30T15:14:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T13:38:41.000Z", "avg_line_length": 17.6739130435, "max_line_length": 54, "alphanum_fraction": 0.655596556, "num_tokens": 208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.02800752303992299, "lm_q2_score": 0.020645928893776512, "lm_q1q2_score": 0.0005782413291730575}}
{"text": "#pragma once\n/*\n * (C) Copyright 2020-2021 UCAR\n *\n * This software is licensed under the terms of the Apache Licence Version 2.0\n * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.\n */\n/*! \\defgroup ioda_cxx_layout Groups and Data Layout\n * \\brief Public API for ioda::Group, ioda::ObsGroup, and data layout policies.\n * \\ingroup ioda_cxx_api\n *\n * @{\n * \\file Group.h\n * \\brief Interfaces for ioda::Group and related classes.\n */\n\n#include <gsl/gsl-lite.hpp>\n#include <map>\n#include <memory>\n#include <string>\n#include <vector>\n\n#include \"ioda/Attributes/Has_Attributes.h\"\n#include \"ioda/Types/Has_Types.h\"\n#include \"ioda/Variables/FillPolicy.h\"\n#include \"ioda/Variables/Has_Variables.h\"\n#include \"ioda/defs.h\"\n\nnamespace ioda {\nclass Group;\n\nnamespace Engines {\nstruct Capabilities;\n}  // namespace Engines\n\nnamespace detail {\nclass Group_Base;\nclass Group_Backend;\n\n/// \\brief Hidden base class to prevent constructor confusion.\n/// \\ingroup ioda_cxx_layout\n/// \\note enable_shared_from_this is a hint to pybind11.\nclass IODA_DL Group_Base {\n  std::shared_ptr<Group_Backend> backend_;\n\nprotected:\n  Group_Base(std::shared_ptr<Group_Backend>);\n\npublic:\n  virtual ~Group_Base();\n\n  std::shared_ptr<Group_Backend> getBackend() const { return backend_; }\n\n  /// Get capabilities of the Engine backing this Group\n  virtual ::ioda::Engines::Capabilities getCapabilities() const;\n\n  /// \\brief Get the fill value policy used for Variables within this Group\n  /// \\details The backend has to be consulted for this operation. Storage of this policy is\n  ///   backend-dependent.\n  virtual FillValuePolicy getFillValuePolicy() const;\n\n  /// \\brief List all one-level child groups in this group\n  /// \\details This function exists to provide the same calling semantics as\n  ///   vars.list() and atts.list(). It is useful for human exploration of the contents\n  ///   of a Group.\n  /// \\returns A vector of strings listing the child groups. The strings are unordered.\n  /// \\see listObjects if you need to enumerate both Groups and Variables, or\n  ///   if you want to do a recursive search. This function is more sophisticated, and\n  ///   depending on the backend it may be faster than recursive calls to\n  ///   list() and vars.list().\n  std::vector<std::string> list() const;\n  /// Same as list(). Uniform semantics with atts() and vars().\n  inline std::vector<std::string> groups() const { return list(); }\n\n  /// \\brief List all objects (groups + variables) within this group\n  /// \\param recurse indicates whether the search should be one-level or recursive. If\n  ///   multiple possible paths exist for an object, only one is actually returned.\n  /// \\param filter allows you to search for only a certain type of object, such as a\n  ///   Group or Variable.\n  /// \\returns a map of ObjectTypes. Each mapping contains a vector of strings indicating\n  ///   object names. If a filter is provided, then this map only contains the filtered\n  ///   object type. Otherwise, the map always has vectors for each element of ObjectType\n  ///   (Group, Variable, etc.), although these vectors may be empty if no object of a\n  ///   certain type is found.\n  /// \\todo This function should list all *distinct* objects. In the future, this will mean\n  ///   that 1) hard-linked duplicate objects will only be listed once, 2) soft\n  ///   links pointing to the same object will only be traversed once, and\n  ///   3) multiple external links to the same object will only be traversed once.\n  ///   If you would want to list *indistinct* objects, then there will be a\n  ///   listLinks function.\n  /// \\todo Once links are implemented, add an option to auto-resolve\n  ///   soft and external links.\n  virtual std::map<ObjectType, std::vector<std::string>> listObjects(ObjectType filter\n                                                                     = ObjectType::Ignored,\n                                                                     bool recurse = false) const;\n\n  template <ObjectType objectClass>\n  std::vector<std::string> listObjects(bool recurse = false) const {\n    return listObjects(objectClass, recurse)[objectClass];\n  }\n\n  /// Does a group exist at the specified path?\n  /// \\param name is the group name.\n  /// \\returns true if a group does exist.\n  /// \\return false if a group does not exist.\n  virtual bool exists(const std::string& name) const;\n\n  /// \\brief Create a group\n  /// \\param name is the group name.\n  /// \\returns an invalid handle on failure. (i.e. return.isGroup() == false).\n  /// \\returns a scoped handle to the group on success.\n  virtual Group create(const std::string& name);\n\n  /// \\brief Open a group\n  /// \\returns an invalid handle if an error occurred. (i.e. return.isGroup() == false).\n  /// \\returns a scoped handle to the group upon success.\n  /// \\note It is possible to have multiple handles opened for the group\n  /// simultaneously.\n  /// \\param name is the name of the child group to open.\n  virtual Group open(const std::string& name) const;\n\n  /// Use this to access the metadata for the group / ObsSpace.\n  Has_Attributes atts;\n\n  /// Use this to access named data types.\n  Has_Types types;\n\n  /// Use this to access variables\n  Has_Variables vars;\n};\n\nclass IODA_DL Group_Backend : public Group_Base {\npublic:\n  virtual ~Group_Backend();\n  /// Default fill value policy is NETCDF4. Overridable on a per-backend basis.\n  FillValuePolicy getFillValuePolicy() const override;\n\n  /// @}\n\nprotected:\n  Group_Backend();\n};\n\n}  // namespace detail\n\n/** \\brief Groups are a new implementation of ObsSpaces.\n * \\ingroup ioda_cxx_layout\n *\n * \\see \\ref Groups for a examples.\n *\n * A group can be thought of as a folder that contains Variables and Metadata.\n * A group can also contain child groups, allowing for our ObsSpaces to exist in a\n * nested tree-like structure, which removes the need for having an ObsSpaceContainer.\n *\n * Groups are implemented in several backends, such as the in-memory IODA store, the HDF5 disk\n * backend, the HDF5 in-memory backend, the ATLAS backend, et cetera. The root Group is mounted\n * using one of these backends (probably as a File object, which is a special type of Group),\n * and additional backends may be mounted into the tree structure.\n *\n * \\throws std::logic_error if the backend handle points to something other than a group.\n * \\throws std::logic_error if the backend handle is invalid.\n * \\throws std::logic_error if any error has occurred.\n * \\author Ryan Honeyager (honeyage@ucar.edu)\n **/\nclass IODA_DL Group : public detail::Group_Base {\npublic:\n  Group();\n  Group(std::shared_ptr<detail::Group_Backend>);\n  virtual ~Group();\n};\n\n}  // namespace ioda\n\n/// @}\n", "meta": {"hexsha": "e93aec95a372e6208f3101e321ff85c7f1b396ad", "size": 6675, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engines/ioda/include/ioda/Group.h", "max_stars_repo_name": "NOAA-EMC/ioda", "max_stars_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/engines/ioda/include/ioda/Group.h", "max_issues_repo_name": "NOAA-EMC/ioda", "max_issues_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engines/ioda/include/ioda/Group.h", "max_forks_repo_name": "NOAA-EMC/ioda", "max_forks_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.1428571429, "max_line_length": 97, "alphanum_fraction": 0.7047191011, "num_tokens": 1586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.03210070625402536, "lm_q2_score": 0.01798621318622854, "lm_q1q2_score": 0.0005773701461133999}}
{"text": "#ifndef VKST_PLAT_FS_NOTIFY_WIN32_H\n#define VKST_PLAT_FS_NOTIFY_WIN32_H\n\n#ifndef VKST_PLAT_FS_NOTIFY_H\n#error \"Include fs_notify.h only\"\n#endif\n\n#include \"fs_notify.h\"\n#include <gsl.h>\n#include <vector>\n\nnamespace plat {\n\nclass fs_notify final : public impl::fs_notify<fs_notify> {\npublic:\n  class watch {\n  public:\n    OVERLAPPED overlapped{};\n    plat::filesystem::path path{};\n    notify_delegate delegate{};\n    bool recursive{false};\n    HANDLE handle{INVALID_HANDLE_VALUE};\n    std::array<BYTE, 32 * 1024> buffer{};\n    watch_id id{UINT32_MAX};\n    bool stop{false};\n\n    bool refresh(bool clear = false) noexcept;\n    void notify(plat::filesystem::path changed_path, DWORD action) noexcept;\n\n    watch(plat::filesystem::path p, notify_delegate d, bool r) noexcept\n    : path{std::move(p)}, delegate{std::move(d)}, recursive{r} {}\n\n    watch() = default;\n    watch(watch const&) = delete;\n    watch& operator=(watch const&) = delete;\n    ~watch() noexcept;\n  }; // struct watch\n\nprivate:\n  std::vector<gsl::unique_ptr<watch>> _watches;\n\n  watch_id do_add(plat::filesystem::path path,\n                  impl::fs_notify<fs_notify>::notify_delegate delegate,\n                  bool recursive, std::error_code& ec) noexcept;\n\n  void do_remove(watch_id id) noexcept;\n\n  void do_tick() noexcept;\n\n  friend class impl::fs_notify<fs_notify>;\n}; // class fs_notify\n\n} // namespace plat\n\n#endif // VKST_PLAT_FS_NOTIFY_WIN32_H", "meta": {"hexsha": "f690e3026d9f20bc06868c41cc1603254f213d12", "size": 1421, "ext": "h", "lang": "C", "max_stars_repo_path": "src/plat/fs_notify_win32.h", "max_stars_repo_name": "wesleygriffin/vkst", "max_stars_repo_head_hexsha": "5f1210ef8aeecdd2bbc3904b0cc4dd09892f239c", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/plat/fs_notify_win32.h", "max_issues_repo_name": "wesleygriffin/vkst", "max_issues_repo_head_hexsha": "5f1210ef8aeecdd2bbc3904b0cc4dd09892f239c", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/plat/fs_notify_win32.h", "max_forks_repo_name": "wesleygriffin/vkst", "max_forks_repo_head_hexsha": "5f1210ef8aeecdd2bbc3904b0cc4dd09892f239c", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8363636364, "max_line_length": 76, "alphanum_fraction": 0.6959887403, "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.035144844379618526, "lm_q2_score": 0.016403032756577993, "lm_q1q2_score": 0.0005764820335837186}}
{"text": "#ifndef COMMAND_LINE_INCLUDE\n#define COMMAND_LINE_INCLUDE\n\n#include <string>\n#include <vector>\n\n#include <gsl/string_span>\n\n#include \"config/fleetingOptionsInterface.h\"\n#include \"config/variablesMap.h\"\n#include \"core/task.h\"\n\nnamespace execHelper {\nnamespace plugins {\nusing CommandLineArg = std::string;\nusing CommandLineArgs = std::vector<CommandLineArg>;\n\nstatic const gsl::czstring<> COMMAND_LINE_KEY = \"command-line\";\n\n/**\n * \\brief Extends the functionality to include the _command-line_ config parameter and processes this parameter\n */\nstruct CommandLine {\n    /*! @copydoc AddEnvironment::getVariables(config::VariablesMap&, const config::FleetingOptionsInterface&)\n     */\n    static void\n    getVariables(config::VariablesMap& variables,\n                 const config::FleetingOptionsInterface& options) noexcept;\n\n    /*! @copydoc JobsLong::apply(core::Task&, const config::VariablesMap&)\n     */\n    inline static void apply(core::Task& task,\n                             const config::VariablesMap& variables) noexcept {\n        task.append(*(variables.get<CommandLineArgs>(COMMAND_LINE_KEY)));\n    }\n};\n\n} // namespace plugins\n} // namespace execHelper\n\n#endif /* COMMAND_LINE_INCLUDE */\n", "meta": {"hexsha": "4f5aee25c3bf723e5f9f6fe658b127664a7d0109", "size": 1203, "ext": "h", "lang": "C", "max_stars_repo_path": "src/plugins/include/plugins/commandLine.h", "max_stars_repo_name": "exec-helper/source", "max_stars_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-28T13:24:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-28T13:24:30.000Z", "max_issues_repo_path": "src/plugins/include/plugins/commandLine.h", "max_issues_repo_name": "exec-helper/source", "max_issues_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/plugins/include/plugins/commandLine.h", "max_forks_repo_name": "exec-helper/source", "max_forks_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-07-03T11:11:19.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-03T11:11:19.000Z", "avg_line_length": 28.6428571429, "max_line_length": 111, "alphanum_fraction": 0.7198669992, "num_tokens": 247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.024053549396381886, "lm_q2_score": 0.023689470610097973, "lm_q1q2_score": 0.0005698158514941286}}
{"text": "#include <stdlib.h>\n#include <gsl/gsl_vector.h>\n#include \"../include/type.h\"\n#include \"../include/global.h\"\n#include \"../include/cthreadpool.h\"\n\n\nvoid *pool_thread(void *arg) {\n    threadpool_t *pool = (threadpool_t*)arg;\n    task_t task;\n    int head;\n\n    while(1) {\n        pthread_mutex_lock(&(pool->pool_lock));\n\n        while(pool->task_count == 0 && pool->flag != POOL_RECLAIM) {\n            pthread_cond_wait(&(pool->notify), &(pool->pool_lock));\n        }\n\n        if (pool->task_count == 0 && pool->flag == POOL_RECLAIM) {\n            break;\n        }\n\n        head = pool->task_head;\n        task.func = pool->tasks[head].func;\n        task.arg = pool->tasks[head].arg;\n        pool->task_head++;\n        pool->task_count--;\n\n        pthread_mutex_unlock(&(pool->pool_lock));\n\n        *(pool->tasks[head].ret) = (task.func)(task.arg);\n    }\n\n    pthread_mutex_unlock(&(pool->pool_lock));\n\n    return NULL;\n}\n\n\nthreadpool_t* threadpool_create(const int nthread, const int queue_size) {\n    int i = 0;\n    threadpool_t *pool = NULL;\n\n    if ((pool = (threadpool_t *)malloc(sizeof(threadpool_t))) == NULL) {\n        return NULL;\n    }\n\n    pool->nthread = nthread;\n    pool->queue_size = queue_size;\n    pool->task_head = 0;\n    pool->task_tail = -1;\n    pool->task_count = 0;\n\n    pthread_mutex_init(&pool->pool_lock, NULL);\n    pthread_cond_init(&pool->notify, NULL);\n\n    pool->working = (int*)malloc(sizeof(int)*nthread);\n    pool->threads = (pthread_t*)malloc(sizeof(pthread_t)*nthread);\n    pool->tasks = (task_t*)malloc(sizeof(task_t)*queue_size);\n    for (i = 0; i < nthread; ++i) {\n        pool->working[i] = IDLE;\n    }\n\n    for(i = 0; i < nthread; i++) {\n        if(pthread_create(&(pool->threads[i]), NULL, pool_thread, (void*)pool) != 0) {\n            threadpool_reclaim(pool);\n            return NULL;\n        }\n        pool->working[i] = INCOMPLETED;\n    }\n\n    return pool;\n}\n\n\nint threadpool_add(threadpool_t *pool, void* (*func)(void *), void *arg, void **ret) {\n    int tail;\n\n    if (pool == NULL || func == NULL) {\n        return POOL_ADD_ERR;\n    }\n\n    if(pthread_mutex_lock(&(pool->pool_lock)) != 0) {\n        return POOL_LOCK_FAILURE;\n    }\n\n    tail = pool->task_tail + 1;\n    tail = tail == pool->queue_size? 0:tail;\n    if (pool->task_count == pool->queue_size) {\n        // TODO erroneous.\n        if ((realloc(pool->tasks, 2 * pool->queue_size)) != 0) {\n            return POOL_ADD_ERR;\n        }\n        tail = pool->queue_size;\n        pool->queue_size *= 2;\n    }\n\n    pool->tasks[tail].func = func;\n    pool->tasks[tail].arg = arg;\n    pool->tasks[tail].ret = ret;\n    pool->task_tail = tail;\n    pool->task_count++;\n\n    if(pthread_cond_signal(&(pool->notify)) != 0 ||\n       pthread_mutex_unlock(&pool->pool_lock) != 0) {\n        return POOL_LOCK_FAILURE;\n    }\n\n    return 0;\n}\n\n\nint threadpool_reclaim(threadpool_t *pool) {\n    int i = 0;\n\n    if(pthread_mutex_lock(&(pool->pool_lock)) != 0) {\n        return POOL_LOCK_FAILURE;\n    }\n\n    pool->flag = POOL_RECLAIM;\n    pthread_mutex_unlock(&(pool->pool_lock));\n\n    for (i = 0; i < pool->nthread; ++i) {\n        if (pool->working[i] != IDLE) {\n            pthread_join(pool->threads[i], NULL);\n        }\n    }\n\n    free(pool->threads);\n    free(pool->tasks);\n    free(pool);\n\n    return 0;\n}\n", "meta": {"hexsha": "a353e244066136bc1c4eae91d66645d6e9b38e26", "size": 3289, "ext": "c", "lang": "C", "max_stars_repo_path": "rMATS_C/src/cthreadpool.c", "max_stars_repo_name": "chunjie-sam-liu/rmats-turbo", "max_stars_repo_head_hexsha": "8a2ad659717a1ccd6dbecd593dc1370ba7c30621", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 88.0, "max_stars_repo_stars_event_min_datetime": "2020-06-01T20:20:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T17:34:39.000Z", "max_issues_repo_path": "rMATS_C/src/cthreadpool.c", "max_issues_repo_name": "chunjie-sam-liu/rmats-turbo", "max_issues_repo_head_hexsha": "8a2ad659717a1ccd6dbecd593dc1370ba7c30621", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 163.0, "max_issues_repo_issues_event_min_datetime": "2020-06-03T06:54:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:39:30.000Z", "max_forks_repo_path": "rMATS_C/src/cthreadpool.c", "max_forks_repo_name": "chunjie-sam-liu/rmats-turbo", "max_forks_repo_head_hexsha": "8a2ad659717a1ccd6dbecd593dc1370ba7c30621", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 39.0, "max_forks_repo_forks_event_min_datetime": "2020-06-01T20:25:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T09:14:46.000Z", "avg_line_length": 24.1838235294, "max_line_length": 86, "alphanum_fraction": 0.574034661, "num_tokens": 906, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.028436031398129842, "lm_q2_score": 0.019719128899466722, "lm_q1q2_score": 0.0005607337685290053}}
{"text": "#pragma once\n\n#include \"JsonHandler.h\"\n#include \"Library.h\"\n\n#include <gsl/span>\n\n#include <cstddef>\n#include <optional>\n#include <string>\n#include <vector>\n\nnamespace rapidjson {\nstruct MemoryStream;\n}\n\nnamespace CesiumJsonReader {\n\n/**\n * @brief The result of {@link Reader::readJson}.\n */\ntemplate <typename T> struct ReadJsonResult {\n  /**\n   * @brief The value read from the JSON, or `std::nullopt` on error.\n   */\n  std::optional<T> value;\n\n  /**\n   * @brief Errors that occurred while reading.\n   */\n  std::vector<std::string> errors;\n\n  /**\n   * @brief Warnings that occurred while reading.\n   */\n  std::vector<std::string> warnings;\n};\n\n/**\n * @brief Reads JSON.\n */\nclass CESIUMJSONREADER_API JsonReader {\npublic:\n  /**\n   * @brief Reads JSON from a byte buffer.\n   *\n   * @param data The buffer from which to read JSON.\n   * @param handler The handler to receive the top-level JSON object.\n   * @return The result of reading the JSON.\n   */\n  template <typename T>\n  static ReadJsonResult<typename T::ValueType>\n  readJson(const gsl::span<const std::byte>& data, T& handler) {\n    ReadJsonResult<typename T::ValueType> result;\n\n    result.value.emplace();\n\n    FinalJsonHandler finalHandler(result.warnings);\n    handler.reset(&finalHandler, &result.value.value());\n\n    JsonReader::internalRead(\n        data,\n        handler,\n        finalHandler,\n        result.errors,\n        result.warnings);\n\n    if (!result.errors.empty()) {\n      result.value.reset();\n    }\n\n    return result;\n  }\n\nprivate:\n  class FinalJsonHandler : public JsonHandler {\n  public:\n    FinalJsonHandler(std::vector<std::string>& warnings);\n    virtual void reportWarning(\n        const std::string& warning,\n        std::vector<std::string>&& context) override;\n    void setInputStream(rapidjson::MemoryStream* pInputStream) noexcept;\n\n  private:\n    std::vector<std::string>& _warnings;\n    rapidjson::MemoryStream* _pInputStream;\n  };\n\n  static void internalRead(\n      const gsl::span<const std::byte>& data,\n      IJsonHandler& handler,\n      FinalJsonHandler& finalHandler,\n      std::vector<std::string>& errors,\n      std::vector<std::string>& warnings);\n};\n\n} // namespace CesiumJsonReader\n", "meta": {"hexsha": "3680acaa0166d19ddf6a8c651687bde1f3dd1cca", "size": 2187, "ext": "h", "lang": "C", "max_stars_repo_path": "CesiumJsonReader/include/CesiumJsonReader/JsonReader.h", "max_stars_repo_name": "yieryi/cesium-native", "max_stars_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 154.0, "max_stars_repo_stars_event_min_datetime": "2021-03-30T14:08:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T00:01:43.000Z", "max_issues_repo_path": "CesiumJsonReader/include/CesiumJsonReader/JsonReader.h", "max_issues_repo_name": "yieryi/cesium-native", "max_issues_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 256.0, "max_issues_repo_issues_event_min_datetime": "2021-03-30T18:12:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:44:21.000Z", "max_forks_repo_path": "CesiumJsonReader/include/CesiumJsonReader/JsonReader.h", "max_forks_repo_name": "yieryi/cesium-native", "max_forks_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 66.0, "max_forks_repo_forks_event_min_datetime": "2021-03-30T15:14:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T13:38:41.000Z", "avg_line_length": 22.3163265306, "max_line_length": 72, "alphanum_fraction": 0.6675811614, "num_tokens": 517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.03210070764297384, "lm_q2_score": 0.01744248425736833, "lm_q1q2_score": 0.0005599160877129545}}
{"text": "#pragma once\n\n#include <list>\n#include <vector>\n#include <optional>\n#include <memory>\n#include <functional>\n\n#include <gsl/gsl-lite.hpp>\n\n#include \"UtilMacros.Namespace.h\"\n#include \"util.std_aliases.h\"\n#include \"zstring_view.h\"\n\nNAMESPACE_BEGIN( cpp )\n\nusing vlr::string;\nusing vlr::wstring;\nusing vlr::tstring;\nusing vlr::zstring_view;\nusing vlr::wzstring_view;\nusing vlr::tzstring_view;\n\nusing std::shared_ptr;\nusing std::weak_ptr;\nusing std::make_shared;\n\nusing std::function;\n\nusing gsl::span;\n\nNAMESPACE_END //( cpp )\n", "meta": {"hexsha": "33e48bd391399197aa1ca96027d0f659a4347f9f", "size": 523, "ext": "h", "lang": "C", "max_stars_repo_path": "vlr-util/cpp_namespace.h", "max_stars_repo_name": "nick42/vlr-util", "max_stars_repo_head_hexsha": "937f53dd4d3e15b23d615b085f5bf4a8e6b9cd91", "max_stars_repo_licenses": ["Artistic-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vlr-util/cpp_namespace.h", "max_issues_repo_name": "nick42/vlr-util", "max_issues_repo_head_hexsha": "937f53dd4d3e15b23d615b085f5bf4a8e6b9cd91", "max_issues_repo_licenses": ["Artistic-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vlr-util/cpp_namespace.h", "max_forks_repo_name": "nick42/vlr-util", "max_forks_repo_head_hexsha": "937f53dd4d3e15b23d615b085f5bf4a8e6b9cd91", "max_forks_repo_licenses": ["Artistic-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.8484848485, "max_line_length": 33, "alphanum_fraction": 0.7456978967, "num_tokens": 136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.026355351316620014, "lm_q2_score": 0.020964240856357813, "lm_q1q2_score": 0.000552519932855549}}
{"text": "#pragma once\n\n#include <CesiumAsync/IAssetResponse.h>\n\n#include <gsl/span>\n\n#include <string>\n#include <vector>\n\nnamespace CesiumCpp {\n\nnamespace CesiumNativeImpl {\n/**\n * @brief Implementation of an IAssetResponse for data from a file.\n */\nclass FileAssetResponse : public CesiumAsync::IAssetResponse {\npublic:\n  /**\n   * @brief Creates a new instance.\n   *\n   * @param fileName The file name.\n   * @param statusCode The HTTP status code\n   * @param contentType The content type.\n   * @param fileData The file data.\n   */\n  FileAssetResponse(const std::string &fileName, uint16_t statusCode,\n                    const std::string &contentType,\n                    const CesiumAsync::HttpHeaders &headers,\n                    const std::vector<std::byte> &fileData);\n\n  uint16_t statusCode() const noexcept override;\n\n  virtual const CesiumAsync::HttpHeaders &headers() const override {\n    return this->_headers;\n  }\n\n  std::string contentType() const noexcept override;\n\n  gsl::span<const std::byte> data() const noexcept override;\n\nprivate:\n  std::string _fileName;\n  uint16_t _statusCode;\n  std::string _contentType;\n  CesiumAsync::HttpHeaders _headers;\n\n  std::vector<std::byte> _fileData;\n};\n} // namespace CesiumNativeImpl\n} // namespace CesiumCpp\n", "meta": {"hexsha": "f4a005fb82587b553a2afa1d44914b701c4184d4", "size": 1255, "ext": "h", "lang": "C", "max_stars_repo_path": "Source/include/CesiumNativeImpl/FileAssetResponse.h", "max_stars_repo_name": "javagl/cesium-cpp", "max_stars_repo_head_hexsha": "fe05a5e49cc53ac9c8821335168975fa232dd2f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2022-01-04T12:40:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:34:35.000Z", "max_issues_repo_path": "Source/include/CesiumNativeImpl/FileAssetResponse.h", "max_issues_repo_name": "javagl/cesium-cpp", "max_issues_repo_head_hexsha": "fe05a5e49cc53ac9c8821335168975fa232dd2f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/include/CesiumNativeImpl/FileAssetResponse.h", "max_forks_repo_name": "javagl/cesium-cpp", "max_forks_repo_head_hexsha": "fe05a5e49cc53ac9c8821335168975fa232dd2f8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6078431373, "max_line_length": 69, "alphanum_fraction": 0.6980079681, "num_tokens": 291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.028007519794676562, "lm_q2_score": 0.019719127495253782, "lm_q1q2_score": 0.0005522838536570711}}
{"text": "/// @file Error.h\n/// @author Braxton Salyer <braxtonsalyer@gmail.com>\n/// @brief Basic high-level types for communicating recoverable errors\n/// @version 0.1\n/// @date 2021-11-03\n///\n/// MIT License\n/// @copyright Copyright (c) 2021 Braxton Salyer <braxtonsalyer@gmail.com>\n///\n/// Permission is hereby granted, free of charge, to any person obtaining a copy\n/// of this software and associated documentation files (the \"Software\"), to\n/// deal in the Software without restriction, including without limitation the\n/// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n/// sell copies of the Software, and to permit persons to whom the Software is\n/// furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in\n/// all copies or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n/// IN THE SOFTWARE.\n#pragma once\n\n#include <Hyperion/BasicTypes.h>\n#include <Hyperion/HyperionDef.h>\n#include <Hyperion/Ignore.h>\n#include <Hyperion/Memory.h>\n#include <Hyperion/error/SystemDomain.h>\n#include <cstring>\n#include <gsl/gsl>\n#include <memory>\n#include <string>\n#include <system_error>\n#include <type_traits>\n\n///\t@defgroup error Error\n/// The Error module provides various error-handling facilities and types for\n/// communicating and handling recoverable errors and for aborting on\n/// irrecoverable errors in a communicable way\n/// @headerfile \"Hyperion/Error.h\"\n\nnamespace hyperion::error {\n\tusing namespace std::literals::string_literals;\n\n\t/// @brief Basic interface for recoverable errors. Error types may provide\n\t/// additional functionality beyond this, but this much is required.\n\t/// @ingroup error\n\t/// @headerfile \"Hyperion/Error.h\"\n\tIGNORE_WEAK_VTABLES_START\n\n\tclass [[nodiscard]] ErrorBase {\n\t  public:\n\t\tconstexpr ErrorBase() noexcept = default;\n\n\t\tconstexpr ErrorBase(const ErrorBase&) noexcept = default;\n\n\t\tconstexpr ErrorBase(ErrorBase&&) noexcept = default;\n\n\t\tconstexpr virtual ~ErrorBase() noexcept = default;\n\n\t\t/// @brief Returns the value of the associated error code as an `i64`\n\t\t/// @return The value of the associated error code\n\t\t/// @ingroup error\n\t\t[[nodiscard]] virtual constexpr auto value() const noexcept -> i64 = 0;\n\n\t\t/// @brief Returns the message associated with the error as a `std::string`\n\t\t/// @return The message associated with the error\n\t\t/// @ingroup error\n\t\t[[nodiscard]] virtual auto message() const noexcept -> std::string = 0;\n\n\t\t/// @brief Converts this error into a `std::string`\n\t\t/// @return This error as a `std::string`\n\t\t/// @ingroup error\n\t\t[[nodiscard]] virtual auto to_string() const noexcept -> std::string = 0;\n\n\t\tconstexpr auto operator=(const ErrorBase&) noexcept -> ErrorBase& = default;\n\n\t\tconstexpr auto operator=(ErrorBase&&) noexcept -> ErrorBase& = default;\n\t};\n\n\tIGNORE_WEAK_VTABLES_STOP\n\n\t// class [[nodiscard]] AnyError;\n\n\t/// @brief General purpose type for communicating recoverable errors.\n\t///\n\t/// Wraps an `error::ErrorCode<Domain>` in a type-safe manner.\n\t/// Usually makes up the `E` variant of a `Result<T, E>`\n\t///\n\t/// @tparam Domain - The `StatusCodeDomain` associated with the this error\n\t/// @ingroup error\n\ttemplate<StatusCodeDomain Domain = SystemDomain>\n\tclass [[nodiscard]] Error final : public ErrorBase {\n\t  public:\n\t\t/// @brief The type used to represent the error (an enum, integer error code,\n\t\t/// etc)\n\t\t/// @ingroup error\n\t\tusing value_type = typename ErrorCode<Domain>::value_type;\n\n\t\tfriend class AnyError;\n\n\t\t/// @brief Constructs a default `Error` with an error code representing an\n\t\t/// unknown error\n\t\t/// @ingroup error\n\t\tconstexpr Error() noexcept {\n\n\t\t\tif constexpr(StatusCodeEnum<value_type>) {\n\t\t\t\tm_error_code = make_error_code(static_cast<value_type>(-1));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tm_error_code = make_error_code<Domain>(static_cast<value_type>(-1));\n\t\t\t}\n\t\t}\n\n\t\t/// @brief Constructs an `Error` from the given `ErrorCode<Domain>`\n\t\t///\n\t\t/// @param code - The error code\n\t\t/// @ingroup error\n\t\tconstexpr Error(const ErrorCode<Domain>& code) noexcept // NOLINT\n\t\t\t: m_error_code(code) {\n\t\t}\n\n\t\t/// @brief Constructs an `Error` from the given `ErrorCode<Domain>`\n\t\t///\n\t\t/// @param code - The error code\n\t\t/// @ingroup error\n\t\tconstexpr Error(ErrorCode<Domain>&& code) noexcept // NOLINT\n\t\t\t: m_error_code(std::move(code)) {\n\t\t}\n\n\t\t/// @brief Constructs an `Error` from the given error code\n\t\t///\n\t\t/// @param code - The error code\n\t\t/// @ingroup error\n\t\tconstexpr Error(const value_type& code) noexcept // NOLINT\n\t\t\trequires(!StatusCodeEnum<value_type>)\n\t\t\t: m_error_code(make_error_code<Domain>(code)) {\n\t\t}\n\n\t\t/// @brief Constructs an `Error` from the given error code\n\t\t///\n\t\t/// @param code - The error code\n\t\t/// @ingroup error\n\t\tconstexpr Error(const value_type& code) noexcept // NOLINT\n\t\t\trequires StatusCodeEnum<value_type> : m_error_code(make_error_code(code)) {\n\t\t}\n\n\t\t/// @brief Copy-constructs an `Error`\n\t\t/// @ingroup error\n\t\tconstexpr Error(const Error& error) = default;\n\n\t\t/// @brief Move-constructs an `Error`\n\t\t/// @ingroup error\n\t\tconstexpr Error(Error&& error) noexcept = default;\n\n\t\t/// @brief Destroys this `Error`\n\t\t/// @ingroup error\n\t\tconstexpr ~Error() noexcept final = default;\n\n\t\t/// @brief Returns the `i64` value of the error code associated with this\n\t\t/// `Error`\n\t\t///\n\t\t/// @return The associated error code as an `i64`\n\t\t/// @ingroup error\n\t\t[[nodiscard]] auto value() const noexcept -> i64 final {\n\n\t\t\treturn m_error_code.value();\n\t\t}\n\n\t\t/// @brief Returns the `ErrorCode` associated with this `Error`\n\t\t///\n\t\t/// @return The associated `ErrorCode`\n\t\t/// @ingroup error\n\t\t[[nodiscard]] auto code() const noexcept -> const ErrorCode<Domain>& {\n\n\t\t\treturn m_error_code;\n\t\t}\n\n\t\t/// @brief Returns the error message associated with this `Error`\n\t\t///\n\t\t/// @return The error message\n\t\t/// @ingroup error\n\t\t[[nodiscard]] inline auto message() const noexcept -> std::string final {\n\n\t\t\tif constexpr(concepts::Same<error_code_message_type, std::string>) {\n\t\t\t\treturn m_error_code.message();\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn std::string(m_error_code.message());\n\t\t\t}\n\t\t}\n\n\t\t/// @brief Returns the error message associated with this `Error`, as a cstring\n\t\t///\n\t\t/// @return The error message\n\t\t/// @ingroup error\n\t\t[[nodiscard]] auto message_as_cstr() const noexcept -> const char* {\n\n\t\t\treturn m_error_code.message().c_str();\n\t\t}\n\n\t\t/// @brief Gets the `std::string` representation of this `Error`\n\t\t///\n\t\t/// @return this `Error` formatted as a `std::string`\n\t\t/// @ingroup error\n\t\t[[nodiscard]] auto to_string() const noexcept -> std::string final {\n\n\t\t\treturn fmt::format(\"Error: {}\", m_error_code.message());\n\t\t}\n\n\t\t/// @brief Converts this `Error` into its underlying `ErrorCode<Domain>`\n\t\t/// @ingroup error\n\t\tconstexpr operator ErrorCode<Domain>() const noexcept { // NOLINT\n\t\t\treturn m_error_code;\n\t\t}\n\n\t\t/// @brief Converts this `Error` into its underlying `value_type`\n\t\t/// @ingroup error\n\t\tconstexpr operator value_type() const noexcept { // NOLINT\n\t\t\treturn static_cast<value_type>(m_error_code);\n\t\t}\n\n\t\t/// @brief Equality comparison operator with another `Error` from a possibly different\n\t\t/// `StatusCodeDomain`\n\t\t/// @tparam Domain2 - The `StatusCodeDomain` of `error`\n\t\t/// @ingroup error\n\t\ttemplate<StatusCodeDomain Domain2>\n\t\tconstexpr auto operator==(const Error<Domain2>& error) const noexcept -> bool {\n\t\t\treturn m_error_code == error.m_error_code;\n\t\t}\n\n\t\t/// @brief Inequality comparison operator with another `Error` from a possibly different\n\t\t/// `StatusCodeDomain`\n\t\t/// @tparam Domain2 - The `StatusCodeDomain` of `error`\n\t\t/// @ingroup error\n\t\ttemplate<StatusCodeDomain Domain2>\n\t\tconstexpr auto operator!=(const Error<Domain2>& error) const noexcept -> bool {\n\t\t\treturn m_error_code != error.m_error_code;\n\t\t}\n\n\t\t/// @brief Equality comparison operator with an `ErrorCode` from a possibly different\n\t\t/// `StatusCodeDomain`\n\t\t/// @tparam Domain2 - The `StatusCodeDomain` of `code`\n\t\t/// @ingroup error\n\t\ttemplate<StatusCodeDomain Domain2>\n\t\tconstexpr auto operator==(const ErrorCode<Domain2>& code) const noexcept -> bool {\n\t\t\treturn m_error_code == code;\n\t\t}\n\n\t\t/// @brief Inequality comparison operator with an `ErrorCode` from a possibly different\n\t\t/// `StatusCodeDomain`\n\t\t/// @tparam Domain2 - The `StatusCodeDomain` of `code`\n\t\t/// @ingroup error\n\t\ttemplate<StatusCodeDomain Domain2>\n\t\tconstexpr auto operator!=(const ErrorCode<Domain2>& code) const noexcept -> bool {\n\t\t\treturn m_error_code != code;\n\t\t}\n\n\t\t/// @brief Copy-assigns the given `error` to this `Error`\n\t\t/// @ingroup error\n\t\tconstexpr auto operator=(const Error& error) noexcept -> Error& = default;\n\n\t\t/// @brief Move-assigns the given `error` to this `Error`\n\t\t/// @ingroup error\n\t\tconstexpr auto operator=(Error&& error) noexcept -> Error& = default;\n\n\t\t/// @brief Copy-assigns the given `ErrorCode<Domain>` to this `Error`\n\t\t/// @ingroup error\n\t\tconstexpr auto operator=(const ErrorCode<Domain>& code) noexcept -> Error& {\n\n\t\t\tm_error_code = code;\n\n\t\t\treturn *this;\n\t\t}\n\n\t\t/// @brief Move-assigns the given `ErrorCode<Domain>` to this `Error`\n\t\t/// @ingroup error\n\t\tconstexpr auto operator=(ErrorCode<Domain>&& code) noexcept -> Error& {\n\n\t\t\tm_error_code = std::move(code);\n\n\t\t\treturn *this;\n\t\t}\n\n\t\t/// @brief Provides `std::tuple`-like structured binding support.\n\t\t///\n\t\t/// `Index == 0` returns the error code value.\n\t\t/// `Index == 1` returns the error message.\n\t\t/// Other `Index` values ar invalid\n\t\t///\n\t\t/// @return The error code value (`Index == 0`), or the error message (`Index\n\t\t/// == 1`)\n\t\t/// @ingroup error\n\t\ttemplate<usize Index>\n\t\tauto get() const&& noexcept {\n\n\t\t\treturn get_impl<Index>(*this);\n\t\t}\n\n\t\t/// @brief Provides `std::tuple`-like structured binding support.\n\t\t///\n\t\t/// `Index == 0` returns the error code value.\n\t\t/// `Index == 1` returns the error message.\n\t\t/// Other `Index` values ar invalid\n\t\t///\n\t\t/// @return The error code value (`Index == 0`), or the error message (`Index\n\t\t/// == 1`)\n\t\t/// @ingroup error\n\t\ttemplate<usize Index>\n\t\tauto get() const& noexcept {\n\n\t\t\treturn get_impl<Index>(*this);\n\t\t}\n\n\t  private:\n\t\ttemplate<usize Index, typename T>\n\t\tauto get_impl(T&& t) const noexcept {\n\n\t\t\tstatic_assert(Index < 2, \"Index out of bounds for hyperion::error::Error::get\");\n\t\t\tif constexpr(Index == 0) {\n\t\t\t\treturn std::forward<T>(t).m_error_code.value();\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn std::forward<T>(t).m_error_code.message();\n\t\t\t}\n\t\t}\n\n\t\t/// error code\n\t\tErrorCode<Domain> m_error_code;\n\n\t\tusing error_code_message_type = decltype(m_error_code.message());\n\t};\n} // namespace hyperion::error\n\n/// @brief Specialize `std::tuple_size` for `error::Error<Domain>`\n/// @ingroup error\ntemplate<hyperion::error::StatusCodeDomain Domain>\nstruct std::tuple_size<hyperion::error::Error<Domain>> {\n\tstatic constexpr hyperion::usize value = 2;\n};\n\n/// @brief Specialize `std::tuple_element<0, T>` for `error::Error<Domain>`\n/// @ingroup error\ntemplate<hyperion::error::StatusCodeDomain Domain>\nstruct std::tuple_element<0, hyperion::error::Error<Domain>> {\n\tusing type = typename hyperion::error::Error<Domain>::value_type;\n};\n\n/// @brief Specialize `std::tuple_element<1, T>` for `error::Error<Domain>`\n/// @ingroup error\ntemplate<hyperion::error::StatusCodeDomain Domain>\nstruct std::tuple_element<1, hyperion::error::Error<Domain>> {\n\tusing type = std::string;\n};\n\nnamespace hyperion::error {\n\n\t/// @brief `SystemError` is an error representing the default platform/OS level\n\t/// errors (eg POSIX or WIN32 error codes)\n\t///\n\t/// In practice, this will usually be an alias for one of `PosixError`,\n\t/// `Win32Error`, or `NTError`, depending on platform and configuration\n\t/// @ingroup error\n\tusing SystemError = Error<SystemDomain>;\n\t/// @brief `PosixError` is an error representing a platform's implementation of\n\t/// POSIX error codes (it includes support for additional platform specific\n\t/// codes not required by POSIX)\n\t/// @ingroup error\n\tusing PosixError = Error<PosixDomain>;\n\t/// @brief `GenericError` represents the strict set of POSIX required error\n\t/// codes.\n\t///\n\t/// In Hyperion's error system, `GenericError` fills a role similar to a\n\t/// `std::error_code` of `std::generic_category`\n\t/// @ingroup error\n\tusing GenericError = Error<GenericDomain>;\n\n#if HYPERION_PLATFORM_WINDOWS\n\t/// @brief `Win32Error` is an error representing the Win32 error codes\n\t/// @ingroup error\n\tusing Win32Error = Error<Win32Domain>;\n\t/// @brief `NTError` is an error representing the Windows NT error codes\n\t/// @ingroup error\n\tusing NTError = Error<NTDomain>;\n#endif // HYPERION_PLATFORM_WINDOWS\n\n\t/// @brief Concept specifying the requirements of a type necessary to be\n\t/// guaranteed compatible with Hyperion's error system.\n\t///\n\t/// Users are encouraged to fulfill this concept for their own error types,\n\t/// particularly when using them with Hyperion's higher-level error-handling\n\t/// facilities like `Result<T, E>`\n\t/// @ingroup error\n\ttemplate<typename E>\n\tconcept ErrorType = std::derived_from<E, ErrorBase>;\n\n\t/// @brief Concept useful for shorthanding `!ErrorType<E>`\n\t/// @note Removes the need for extra parentheses and enables cleaner\n\t/// auto-formatting (eg `SomeConcept &&(!ErrorType<E>)` vs `SomeConcept &&\n\t/// NotErrorType<E>`)\n\t/// @ingroup error\n\ttemplate<typename E>\n\tconcept NotErrorType = !ErrorType<E>;\n\n\t/// @brief `AnyError` represents a type erased error from any\n\t/// `error::StatusCodeDomain`\n\t/// @ingroup error\n\tclass [[nodiscard]] AnyError final : public ErrorBase {\n\t  public:\n\t\t/// @brief Constructs an `AnyError` as an unknown error\n\t\t/// @ingroup error\n\t\tHYPERION_CONSTEXPR_STRINGS AnyError() noexcept = default;\n\n\t\t/// @brief Constructs an `AnyError` from the given `error::ErrorCode<Domain>`\n\t\t///\n\t\t/// @tparam Domain - The `error::StatusCodeDomain` of the error\n\t\t///\n\t\t/// @param code - The error code this `AnyError` should represent\n\t\t/// @ingroup error\n\t\ttemplate<StatusCodeDomain Domain>\n\t\tHYPERION_CONSTEXPR_STRINGS AnyError(const ErrorCode<Domain>& code) noexcept // NOLINT\n\t\t\t: m_error_code(code.value()), m_message(code.message()) {\n\t\t}\n\n\t\t/// @brief Constructs an `AnyError` from the given `error::ErrorCode<Domain>`\n\t\t///\n\t\t/// @tparam Domain - The `error::StatusCodeDomain` of the error\n\t\t///\n\t\t/// @param code - The error code this `AnyError` should represent\n\t\t/// @ingroup error\n\t\ttemplate<StatusCodeDomain Domain>\n\t\tHYPERION_CONSTEXPR_STRINGS AnyError(ErrorCode<Domain>&& code) noexcept // NOLINT\n\t\t\t: m_error_code(code.value()), m_message(code.message()) {\n\t\t}\n\n\t\t/// @brief Constructs an `AnyError` from the given `error::Error<Domain>`\n\t\t///\n\t\t/// @tparam Domain - The `error::StatusCodeDomain` of the error\n\t\t///\n\t\t/// @param error - The error this `AnyError` should represent\n\t\t/// @ingroup error\n\t\ttemplate<StatusCodeDomain Domain>\n\t\tHYPERION_CONSTEXPR_STRINGS AnyError(const Error<Domain>& error) noexcept // NOLINT\n\t\t\t: m_error_code(error.code().value()), m_message(error.message()) {\n\t\t}\n\n\t\t/// @brief Constructs an `AnyError` from the given `error::Error<Domain>`\n\t\t///\n\t\t/// @tparam Domain - The `error::StatusCodeDomain` of the error\n\t\t///\n\t\t/// @param error - The error this `AnyError` should represent\n\t\t/// @ingroup error\n\t\ttemplate<StatusCodeDomain Domain>\n\t\tHYPERION_CONSTEXPR_STRINGS AnyError(Error<Domain>&& error) noexcept // NOLINT\n\t\t\t: m_error_code(error.code().value()), m_message(error.message()) {\n\t\t}\n\t\t/// @brief Copy-constructs an `AnyError` from the given one\n\t\t/// @ingroup error\n\t\tHYPERION_CONSTEXPR_STRINGS AnyError(const AnyError&) noexcept = default;\n\t\t/// @brief Move-constructs an `AnyError` from the given one\n\t\t/// @ingroup error\n\t\tHYPERION_CONSTEXPR_STRINGS AnyError(AnyError&&) noexcept = default;\n\t\t/// @brief Destroys this `AnyError`\n\t\t/// @ingroup error\n\t\tHYPERION_CONSTEXPR_STRINGS ~AnyError() noexcept final = default;\n\n\t\t/// @brief Returns the `i64` value corresponding with the error code this\n\t\t/// represents\n\t\t/// @return The error code as an `i64`\n\t\t/// @ingroup error\n\t\t[[nodiscard]] constexpr auto value() const noexcept -> i64 final {\n\n\t\t\treturn m_error_code;\n\t\t}\n\n\t\t/// @brief Returns the error message associated with the error code this\n\t\t/// represents\n\t\t/// @return The error code message\n\t\t/// @ingroup error\n\t\t[[nodiscard]] auto message() const noexcept -> std::string final {\n\n\t\t\treturn m_message;\n\t\t}\n\n\t\t/// @brief Returns the string representation of this `AnyError`\n\t\t/// @return this `AnyError` as a `std::string`\n\t\t/// @ingroup error\n\t\t[[nodiscard]] HYPERION_CONSTEXPR_STRINGS auto\n\t\tto_string() const noexcept -> std::string final {\n\n\t\t\treturn \"Error: \"s + m_message + \"\\n\"s;\n\t\t}\n\n\t\t/// @brief Copy-assigns the given `AnyError` to this one\n\t\t/// @ingroup error\n\t\tHYPERION_CONSTEXPR_STRINGS auto operator=(const AnyError&) noexcept -> AnyError& = default;\n\t\t/// @brief Move-assigns the given `AnyError` to this one\n\t\t/// @ingroup error\n\t\tHYPERION_CONSTEXPR_STRINGS auto operator=(AnyError&&) noexcept -> AnyError& = default;\n\n\t\t/// @brief Copy-assigns this `AnyError` with the given\n\t\t/// `error::ErrorCode<Domain>`\n\t\t///\n\t\t/// @tparam Domain - The `error::StatusCodeDomain` of the error code\n\t\t///\n\t\t/// @param code - The error code to assign to this\n\t\t/// @ingroup error\n\t\ttemplate<StatusCodeDomain Domain>\n\t\tHYPERION_CONSTEXPR_STRINGS auto\n\t\toperator=(const ErrorCode<Domain>& code) noexcept -> AnyError& {\n\n\t\t\tm_error_code = code.value();\n\t\t\tm_message = code.message();\n\n\t\t\treturn *this;\n\t\t}\n\n\t\t/// @brief Move-assigns this `AnyError` with the given\n\t\t/// `error::ErrorCode<Domain>`\n\t\t///\n\t\t/// @tparam Domain - The `error::StatusCodeDomain` of the error code\n\t\t///\n\t\t/// @param code - The error code to assign to this\n\t\t/// @ingroup error\n\t\ttemplate<StatusCodeDomain Domain>\n\t\tHYPERION_CONSTEXPR_STRINGS auto operator=(ErrorCode<Domain>&& code) noexcept -> AnyError& {\n\n\t\t\tm_error_code = code.value();\n\t\t\tm_message = code.message();\n\n\t\t\treturn *this;\n\t\t}\n\n\t\t/// @brief Copy-assigns this `AnyError` with the given `error::Error<Domain>`\n\t\t///\n\t\t/// @tparam Domain - The `error::StatusCodeDomain` of the error\n\t\t///\n\t\t/// @param error - The error to assign to this\n\t\t/// @ingroup error\n\t\ttemplate<StatusCodeDomain Domain>\n\t\tHYPERION_CONSTEXPR_STRINGS auto\n\t\toperator=(const Error<Domain>& error) noexcept -> AnyError& {\n\n\t\t\tm_error_code = error.value();\n\t\t\tm_message = error.message();\n\n\t\t\treturn *this;\n\t\t}\n\n\t\t/// @brief Move-assigns this `AnyError` with the given `error::Error<Domain>`\n\t\t///\n\t\t/// @tparam Domain - The `error::StatusCodeDomain` of the error\n\t\t///\n\t\t/// @param error - The error to assign to this\n\t\t/// @ingroup error\n\t\ttemplate<StatusCodeDomain Domain>\n\t\tHYPERION_CONSTEXPR_STRINGS auto operator=(Error<Domain>&& error) noexcept -> AnyError& {\n\n\t\t\tm_error_code = error.value();\n\t\t\tm_message = error.message();\n\n\t\t\treturn *this;\n\t\t}\n\n\t\t/// @brief Provides `std::tuple`-like structured binding support.\n\t\t///\n\t\t/// `Index == 0` returns the error code value.\n\t\t/// `Index == 1` returns the error message.\n\t\t/// Other `Index` values ar invalid\n\t\t///\n\t\t/// @return The error code value (`Index == 0`), or the error message (`Index\n\t\t/// == 1`)\n\t\t/// @ingroup error\n\t\ttemplate<usize Index>\n\t\tauto get() const&& noexcept {\n\n\t\t\treturn get_impl<Index>(*this);\n\t\t}\n\n\t\t/// @brief Provides `std::tuple`-like structured binding support.\n\t\t///\n\t\t/// `Index == 0` returns the error code value.\n\t\t/// `Index == 1` returns the error message.\n\t\t/// Other `Index` values ar invalid\n\t\t///\n\t\t/// @return The error code value (`Index == 0`), or the error message (`Index\n\t\t/// == 1`)\n\t\t/// @ingroup error\n\t\ttemplate<usize Index>\n\t\tauto get() const& noexcept {\n\n\t\t\treturn get_impl<Index>(*this);\n\t\t}\n\n\t  private:\n\t\ttemplate<usize Index, typename T>\n\t\tauto get_impl(T&& t) const noexcept {\n\n\t\t\tstatic_assert(Index < 2, \"Index out of bounds for hyperion::error::AnyError::get\");\n\t\t\tif constexpr(Index == 0) {\n\t\t\t\treturn std::forward<T>(t).m_error_code;\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn std::forward<T>(t).m_message;\n\t\t\t}\n\t\t}\n\n\t\ti64 m_error_code = -1;\n\n\t\tstd::string m_message;\n\t};\n} // namespace hyperion::error\n\n/// @brief Specialize `std::tuple_size` for `error::AnyError`\n/// @ingroup error\ntemplate<>\nstruct std::tuple_size<hyperion::error::AnyError> {\n\tstatic constexpr hyperion::usize value = 2;\n};\n\n/// @brief Specialize `std::tuple_element<0, T>` for `error::AnyError`\n/// @ingroup error\ntemplate<>\nstruct std::tuple_element<0, hyperion::error::AnyError> {\n\tusing type = hyperion::i64;\n};\n\n/// @brief Specialize `std::tuple_element<1, T>` for `error::AnyError`\n/// @ingroup error\ntemplate<>\nstruct std::tuple_element<1, hyperion::error::AnyError> {\n\tusing type = std::string;\n};\n", "meta": {"hexsha": "fce65b7998e6640713833dc7d48761411181d892", "size": 21034, "ext": "h", "lang": "C", "max_stars_repo_path": "include/Hyperion/Error.h", "max_stars_repo_name": "braxtons12/Hyperion-Utils", "max_stars_repo_head_hexsha": "3873a116e2ea76fc74c9c056925f3740eee6dcd8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/Hyperion/Error.h", "max_issues_repo_name": "braxtons12/Hyperion-Utils", "max_issues_repo_head_hexsha": "3873a116e2ea76fc74c9c056925f3740eee6dcd8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/Hyperion/Error.h", "max_forks_repo_name": "braxtons12/Hyperion-Utils", "max_forks_repo_head_hexsha": "3873a116e2ea76fc74c9c056925f3740eee6dcd8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.917057903, "max_line_length": 93, "alphanum_fraction": 0.6919273557, "num_tokens": 5577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.020023442459047608, "lm_q2_score": 0.027169228483316193, "lm_q1q2_score": 0.0005440214831923991}}
{"text": "#ifdef _MSC_VER\n#if _MSC_VER >= 1910\n#include <CppCoreCheck/warnings.h>\n#pragma warning(disable: ALL_CPPCORECHECK_WARNINGS)\n#endif // _MSC_VER >= 1910\n#endif // _MSC_VER\n\n\n#include <gsl/gsl>\n\n\n#ifdef _MSC_VER\n#if _MSC_VER >= 1910\n#pragma warning(default: ALL_CPPCORECHECK_WARNINGS)\n#endif // _MSC_VER >= 1910\n#endif // _MSC_VER\n", "meta": {"hexsha": "38084f0b3cbda1ae74d314e773eba027cb502215", "size": 328, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gsl_wrapper.h", "max_stars_repo_name": "TomoyukiAota/CoreCheckerAndGsl", "max_stars_repo_head_hexsha": "e3ed0472f3ca449c3082cae5b5d9629e2e8e1699", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/gsl_wrapper.h", "max_issues_repo_name": "TomoyukiAota/CoreCheckerAndGsl", "max_issues_repo_head_hexsha": "e3ed0472f3ca449c3082cae5b5d9629e2e8e1699", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gsl_wrapper.h", "max_forks_repo_name": "TomoyukiAota/CoreCheckerAndGsl", "max_forks_repo_head_hexsha": "e3ed0472f3ca449c3082cae5b5d9629e2e8e1699", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.2941176471, "max_line_length": 51, "alphanum_fraction": 0.7469512195, "num_tokens": 97, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.03308597552845946, "lm_q2_score": 0.016403036032231824, "lm_q1q2_score": 0.0005427104487548609}}
{"text": "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\n#pragma once\n\n#include <gsl/gsl>\n\nnamespace _winml {\n\nvoid LoadSpanFromDisjointBuffers(\n    size_t num_buffers,\n    std::function<gsl::span<byte>(size_t)> get_buffer,\n    gsl::span<byte>& buffer_span);\n\nvoid StoreSpanIntoDisjointBuffers(\n    size_t num_buffers,\n    std::function<gsl::span<byte>(size_t)> get_buffer,\n    gsl::span<byte>& buffer_span);\n\n} // namespace _winml", "meta": {"hexsha": "9e6c354e4332657d9339484f437440765320649c", "size": 471, "ext": "h", "lang": "C", "max_stars_repo_path": "winml/lib/Api.Image/inc/DisjointBufferHelpers.h", "max_stars_repo_name": "dennyac/onnxruntime", "max_stars_repo_head_hexsha": "d5175795d2b7f2db18b0390f394a49238f814668", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6036.0, "max_stars_repo_stars_event_min_datetime": "2019-05-07T06:03:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:59:54.000Z", "max_issues_repo_path": "winml/lib/Api.Image/inc/DisjointBufferHelpers.h", "max_issues_repo_name": "dennyac/onnxruntime", "max_issues_repo_head_hexsha": "d5175795d2b7f2db18b0390f394a49238f814668", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5730.0, "max_issues_repo_issues_event_min_datetime": "2019-05-06T23:04:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:55:56.000Z", "max_forks_repo_path": "winml/lib/Api.Image/inc/DisjointBufferHelpers.h", "max_forks_repo_name": "dennyac/onnxruntime", "max_forks_repo_head_hexsha": "d5175795d2b7f2db18b0390f394a49238f814668", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1566.0, "max_forks_repo_forks_event_min_datetime": "2019-05-07T01:30:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T17:06:50.000Z", "avg_line_length": 23.55, "max_line_length": 60, "alphanum_fraction": 0.7282377919, "num_tokens": 118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.03461883485515691, "lm_q2_score": 0.015663647821384945, "lm_q1q2_score": 0.0005422572371578638}}
{"text": "#ifndef VERBOSITY_INCLUDE\n#define VERBOSITY_INCLUDE\n\n#include <iostream>\n\n#include <gsl/string_span>\n\n#include \"config/fleetingOptionsInterface.h\"\n#include \"config/variablesMap.h\"\n#include \"core/task.h\"\n\nnamespace execHelper {\nnamespace plugins {\nusing Verbosity = bool;\n\nconst gsl::czstring<> VERBOSITY_KEY = \"verbose\";\n\n/**\n * \\brief Extends the functionality to include the _verbose_ config parameter and processes this parameter, using the --verbose flag\n */\nstruct VerbosityLong {\n    /*! @copydoc JobsLong::getVariables(config::VariablesMap&, const config::FleetingOptionsInterface&)\n     */\n    static void\n    getVariables(config::VariablesMap& variables,\n                 const config::FleetingOptionsInterface& options) noexcept;\n\n    /*! @copydoc JobsLong::apply(core::Task&, const config::VariablesMap&)\n     */\n    inline static void apply(core::Task& task,\n                             const config::VariablesMap& variables) noexcept {\n        if(*(variables.get<Verbosity>(VERBOSITY_KEY))) {\n            task.append(\"--verbose\");\n        }\n    }\n};\n\n/**\n * \\brief Extends the functionality to include the _verbose_ config parameter and processes this parameter, using the --debug flag\n */\nstruct VerbosityDebug {\n    /*! @copydoc JobsLong::getVariables(config::VariablesMap&, const config::FleetingOptionsInterface&)\n     */\n    inline static void\n    getVariables(config::VariablesMap& variables,\n                 const config::FleetingOptionsInterface& options) noexcept {\n        VerbosityLong::getVariables(variables, options);\n    }\n\n    /*! @copydoc JobsLong::apply(core::Task&, const config::VariablesMap&)\n     */\n    inline static void apply(core::Task& task,\n                             const config::VariablesMap& variables) noexcept {\n        if(*(variables.get<Verbosity>(VERBOSITY_KEY))) {\n            task.append(\"--debug\");\n        }\n    }\n};\n\n/**\n * \\brief Extends the functionality to include the _verbose_ config parameter and processes this parameter, using the -v flag\n */\nstruct VerbosityShort {\n    /*! @copydoc JobsLong::getVariables(config::VariablesMap&, const config::FleetingOptionsInterface&)\n     */\n    inline static void\n    getVariables(config::VariablesMap& variables,\n                 const config::FleetingOptionsInterface& options) noexcept {\n        VerbosityLong::getVariables(variables, options);\n    }\n\n    /*! @copydoc JobsLong::apply(core::Task&, const config::VariablesMap&)\n     */\n    inline static void apply(core::Task& task,\n                             const config::VariablesMap& variables) noexcept {\n        if(*(variables.get<Verbosity>(VERBOSITY_KEY))) {\n            task.append(\"-v\");\n        }\n    }\n};\n} // namespace plugins\n} // namespace execHelper\n\n#endif /* VERBOSITY_INCLUDE */\n", "meta": {"hexsha": "b23ccf417796905976493fdd81f3a250e8c273ec", "size": 2757, "ext": "h", "lang": "C", "max_stars_repo_path": "src/plugins/include/plugins/verbosity.h", "max_stars_repo_name": "exec-helper/source", "max_stars_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-28T13:24:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-28T13:24:30.000Z", "max_issues_repo_path": "src/plugins/include/plugins/verbosity.h", "max_issues_repo_name": "exec-helper/source", "max_issues_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/plugins/include/plugins/verbosity.h", "max_forks_repo_name": "exec-helper/source", "max_forks_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-07-03T11:11:19.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-03T11:11:19.000Z", "avg_line_length": 32.4352941176, "max_line_length": 132, "alphanum_fraction": 0.6663039536, "num_tokens": 597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.020964244488237582, "lm_q2_score": 0.025565214944103357, "lm_q1q2_score": 0.0005359554164825279}}
{"text": "#ifndef config_e9763ac5_66db_439d_99b9_4c84c1b41e14_h\r\n#define config_e9763ac5_66db_439d_99b9_4c84c1b41e14_h\r\n\r\n#include <gslib\\config.h>\r\n\r\n#ifdef __cplusplus\r\n\r\n#define __rathen_begin__    namespace gs { namespace rathen {\r\n#define __rathen_end__      }; };\r\n\r\n#endif\r\n\r\n/* rathen source postfix & binary postfix */\r\n#define rathen_spf  _t(\".rs\")\r\n#define rathen_bpf  _t(\".rb\")\r\n\r\n#endif", "meta": {"hexsha": "f10af7b559cdc2109807b981686a3c249b6991da", "size": 389, "ext": "h", "lang": "C", "max_stars_repo_path": "include/rathen/config.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/rathen/config.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/rathen/config.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 22.8823529412, "max_line_length": 62, "alphanum_fraction": 0.7377892031, "num_tokens": 133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.027585275831371006, "lm_q2_score": 0.01941934757947679, "lm_q1q2_score": 0.0005356880594451341}}
{"text": "// Copyright 2021 atframework\n// Created by owent on 2016-05-21\n\n#pragma once\n\n#include <string>\n\n#include <gsl/select-gsl.h>\n#include <log/log_wrapper.h>\n\n#include \"atframe/atapp_config.h\"\n\nnamespace atapp {\nnamespace protocol {\nclass atapp_log;\nclass atapp_log_category;\nclass atapp_log_sink;\n}  // namespace protocol\n}  // namespace atapp\n\nnamespace atapp {\nclass log_sink_maker {\n public:\n  using log_reg_t = std::function<util::log::log_wrapper::log_handler_t(\n      util::log::log_wrapper &, int32_t, const ::atapp::protocol::atapp_log &,\n      const ::atapp::protocol::atapp_log_category &, const ::atapp::protocol::atapp_log_sink &)>;\n\n private:\n  log_sink_maker();\n  ~log_sink_maker();\n\n public:\n  static LIBATAPP_MACRO_API gsl::string_view get_file_sink_name();\n\n  static LIBATAPP_MACRO_API log_reg_t get_file_sink_reg();\n\n  static LIBATAPP_MACRO_API gsl::string_view get_stdout_sink_name();\n\n  static LIBATAPP_MACRO_API log_reg_t get_stdout_sink_reg();\n\n  static LIBATAPP_MACRO_API gsl::string_view get_stderr_sink_name();\n\n  static LIBATAPP_MACRO_API log_reg_t get_stderr_sink_reg();\n\n  static LIBATAPP_MACRO_API gsl::string_view get_syslog_sink_name();\n\n  static LIBATAPP_MACRO_API log_reg_t get_syslog_sink_reg();\n};\n}  // namespace atapp\n", "meta": {"hexsha": "f3a3046d3dbbc8dae428d8474c6ded55f8438203", "size": 1253, "ext": "h", "lang": "C", "max_stars_repo_path": "include/atframe/atapp_log_sink_maker.h", "max_stars_repo_name": "atframework/libatapp", "max_stars_repo_head_hexsha": "54aae9e0972eb94c33a7c109bdd099ff3a89ee80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2018-06-23T04:38:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T01:22:54.000Z", "max_issues_repo_path": "include/atframe/atapp_log_sink_maker.h", "max_issues_repo_name": "atframework/libatapp", "max_issues_repo_head_hexsha": "54aae9e0972eb94c33a7c109bdd099ff3a89ee80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/atframe/atapp_log_sink_maker.h", "max_forks_repo_name": "atframework/libatapp", "max_forks_repo_head_hexsha": "54aae9e0972eb94c33a7c109bdd099ff3a89ee80", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-08-04T06:14:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-19T10:06:06.000Z", "avg_line_length": 25.06, "max_line_length": 97, "alphanum_fraction": 0.7693535515, "num_tokens": 323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.02800751979467656, "lm_q2_score": 0.01912403668100876, "lm_q1q2_score": 0.0005356168358974735}}
{"text": "#pragma once\n\n#include <gsl/gsl>\n#include \"halley/utils/utils.h\"\n#include <vector>\n\nnamespace Halley {\n\tclass String;\n\tclass Path;\n\n\tclass FileSystem\n\t{\n\tpublic:\n\t\tstatic bool exists(const Path& p);\n\t\tstatic bool createDir(const Path& p);\n\t\tstatic bool createParentDir(const Path& p);\n\n\t\tstatic int64_t getLastWriteTime(const Path& p);\n\t\tstatic bool isFile(const Path& p);\n\t\tstatic bool isDirectory(const Path& p);\n\n\t\tstatic void copyFile(const Path& src, const Path& dst);\n\t\tstatic bool remove(const Path& path);\n\n\t\tstatic void writeFile(const Path& path, gsl::span<const gsl::byte> data);\n\t\tstatic void writeFile(const Path& path, const Bytes& data);\n\t\tstatic Bytes readFile(const Path& path);\n\n\t\tstatic std::vector<Path> enumerateDirectory(const Path& path);\n\t\t\n\t\tstatic Path getRelative(const Path& path, const Path& parentPath);\n\t\tstatic Path getAbsolute(const Path& path);\n\n\t\tstatic size_t fileSize(const Path& path);\n\n\t\tstatic Path getTemporaryPath();\n\n\t\tstatic int runCommand(const String& command);\n\t};\n}\n\n", "meta": {"hexsha": "8fda1ad4abf1a0a63637573ca4966a21557668c0", "size": 1015, "ext": "h", "lang": "C", "max_stars_repo_path": "src/tools/tools/include/halley/tools/file/filesystem.h", "max_stars_repo_name": "Healthire/halley", "max_stars_repo_head_hexsha": "aa58e1abe22cda9e80637922721c03574779cd81", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tools/tools/include/halley/tools/file/filesystem.h", "max_issues_repo_name": "Healthire/halley", "max_issues_repo_head_hexsha": "aa58e1abe22cda9e80637922721c03574779cd81", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tools/tools/include/halley/tools/file/filesystem.h", "max_forks_repo_name": "Healthire/halley", "max_forks_repo_head_hexsha": "aa58e1abe22cda9e80637922721c03574779cd81", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1666666667, "max_line_length": 75, "alphanum_fraction": 0.7280788177, "num_tokens": 239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.033589505650103976, "lm_q2_score": 0.01590639369446971, "lm_q1q2_score": 0.0005342879008731685}}
{"text": "/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */\n/*\n *     Copyright 2017 Couchbase, Inc.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n */\n\n#pragma once\n\n#include <cJSON.h>\n#include <memcached/mcd_util-visibility.h>\n\n#include <gsl/gsl>\n#include <string>\n\nnamespace cb {\nnamespace breakpad {\n/**\n * What information should breakpad minidumps contain?\n */\nenum class Content {\n    /**\n     * Default content (threads+stack+env+arguments)\n     */\n    Default\n};\n\n/**\n * Settings for Breakpad crash catcher.\n */\nstruct MCD_UTIL_PUBLIC_API Settings {\n    /**\n     * Default constructor initialize the object to be in a disabled state\n     */\n    Settings() = default;\n\n    /**\n     * Initialize the Breakpad object from the specified JSON structure\n     * which looks like:\n     *\n     *     {\n     *         \"enabled\" : true,\n     *         \"minidump_dir\" : \"/var/crash\",\n     *         \"content\" : \"default\"\n     *     }\n     *\n     * @param json The json to parse\n     * @throws std::invalid_argument if the json dosn't look as expected\n     */\n    explicit Settings(gsl::not_null<const cJSON*> json);\n\n    bool enabled{false};\n    std::string minidump_dir;\n    Content content{Content::Default};\n};\n\n} // namespace breakpad\n} // namespace cb\n\nMCD_UTIL_PUBLIC_API\nstd::string to_string(cb::breakpad::Content content);\n", "meta": {"hexsha": "26c4bf6fa67ec45482202900f09418a24ca83c45", "size": 1878, "ext": "h", "lang": "C", "max_stars_repo_path": "utilities/breakpad_settings.h", "max_stars_repo_name": "t3rm1n4l/kv_engine", "max_stars_repo_head_hexsha": "24d4546220f3181678d7eadedc68b4ea088d3538", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utilities/breakpad_settings.h", "max_issues_repo_name": "t3rm1n4l/kv_engine", "max_issues_repo_head_hexsha": "24d4546220f3181678d7eadedc68b4ea088d3538", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utilities/breakpad_settings.h", "max_forks_repo_name": "t3rm1n4l/kv_engine", "max_forks_repo_head_hexsha": "24d4546220f3181678d7eadedc68b4ea088d3538", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0833333333, "max_line_length": 79, "alphanum_fraction": 0.6522896699, "num_tokens": 450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.028436032221491242, "lm_q2_score": 0.018546562410009584, "lm_q1q2_score": 0.0005273906462889308}}
{"text": "/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */\n/*\n *     Copyright 2018-Present Couchbase, Inc.\n *\n *   Use of this software is governed by the Business Source License included\n *   in the file licenses/BSL-Couchbase.txt.  As of the Change Date specified\n *   in that file, in accordance with the Business Source License, use of this\n *   software will be governed by the Apache License, Version 2.0, included in\n *   the file licenses/APL2.txt.\n */\n\n#pragma once\n\n#include <gsl/gsl-lite.hpp>\n#include <nlohmann/json_fwd.hpp>\n#include <cstdint>\n#include <string>\n\n/**\n * The Event class represents the information needed for a single\n * audit event entry.\n */\nclass Event {\npublic:\n    Event() = delete;\n\n    /**\n     * Construct and initialize a new Event structure based off the\n     * provided JSON. See ../README.md for information about the\n     * layout of the JSON element.\n     *\n     * @param entry\n     * @throws std::runtime_error for errors accessing the expected\n     *                            elements\n     */\n    explicit Event(const nlohmann::json& json);\n\n    /// The identifier for this entry\n    uint32_t id;\n    /// The name of the entry\n    std::string name;\n    /// The full description of the entry\n    std::string description;\n    /// Set to true if this entry should be handled synchronously\n    bool sync;\n    /// Set to true if this entry is enabled (or should be dropped)\n    bool enabled;\n    /// Set to true if the user may enable filtering for the enry\n    bool filtering_permitted;\n    /// The textual representation of the JSON describing mandatory\n    /// fields in the event (NOTE: this is currently not enforced\n    /// by the audit daemon)\n    std::string mandatory_fields;\n    /// The textual representation of the JSON describing the optional\n    /// fields in the event (NOTE: this is currently not enforced\n    /// by the audit daemon)\n    std::string optional_fields;\n};\n", "meta": {"hexsha": "930c81359783f88129d98a173d2008d0ba36a8be", "size": 1949, "ext": "h", "lang": "C", "max_stars_repo_path": "auditd/generator/generator_event.h", "max_stars_repo_name": "BenHuddleston/kv_engine", "max_stars_repo_head_hexsha": "78123c9aa2c2feb24b7c31eecc862bf2ed6325e4", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": 104.0, "max_stars_repo_stars_event_min_datetime": "2017-05-22T20:41:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T00:18:34.000Z", "max_issues_repo_path": "auditd/generator/generator_event.h", "max_issues_repo_name": "BenHuddleston/kv_engine", "max_issues_repo_head_hexsha": "78123c9aa2c2feb24b7c31eecc862bf2ed6325e4", "max_issues_repo_licenses": ["MIT", "BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-11-14T08:12:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T11:14:17.000Z", "max_forks_repo_path": "auditd/generator/generator_event.h", "max_forks_repo_name": "BenHuddleston/kv_engine", "max_forks_repo_head_hexsha": "78123c9aa2c2feb24b7c31eecc862bf2ed6325e4", "max_forks_repo_licenses": ["MIT", "BSD-3-Clause"], "max_forks_count": 71.0, "max_forks_repo_forks_event_min_datetime": "2017-05-22T20:41:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T10:34:32.000Z", "avg_line_length": 33.0338983051, "max_line_length": 79, "alphanum_fraction": 0.6711133915, "num_tokens": 449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.02931223414322127, "lm_q2_score": 0.017986214074511276, "lm_q1q2_score": 0.0005272161183021764}}
{"text": "#ifndef EXECUTION_HANDLER_INCLUDE\n#define EXECUTION_HANDLER_INCLUDE\n\n#include <map>\n\n#include <gsl/gsl>\n\n#include \"executionContent.h\"\n\nnamespace execHelper {\nnamespace test {\nnamespace baseUtils {\nclass ExecutionHandler {\n  public:\n    void add(const std::string& key, ExecutionContent&& content) noexcept;\n\n    const ExecutionContent& at(const std::string& key) const noexcept;\n\n  private:\n    using ExecutionContentCollection = std::map<std::string, ExecutionContent>;\n\n    /**\n     * \\brief   Used for handling an execution iteration\n     */\n    class ExecutionHandlerIterationRAII {\n      public:\n        explicit ExecutionHandlerIterationRAII(\n            gsl::not_null<ExecutionContentCollection*> outputs);\n        ~ExecutionHandlerIterationRAII();\n\n        ExecutionHandlerIterationRAII(\n            const ExecutionHandlerIterationRAII& other) = default;\n        ExecutionHandlerIterationRAII(ExecutionHandlerIterationRAII&& other) =\n            default;\n\n        ExecutionHandlerIterationRAII&\n        operator=(const ExecutionHandlerIterationRAII& other) = default;\n        ExecutionHandlerIterationRAII&\n        operator=(ExecutionHandlerIterationRAII&& other) noexcept =\n            default; // NOLINT(misc-noexcept-move-constructor)\n\n        const ExecutionContent& at(const std::string& key) const noexcept;\n\n      private:\n        gsl::not_null<ExecutionContentCollection*> m_outputs;\n    };\n\n    ExecutionContentCollection m_outputs;\n\n  public:\n    ExecutionHandlerIterationRAII startIteration() noexcept;\n};\n} // namespace baseUtils\n} // namespace test\n} // namespace execHelper\n\n#endif /* EXECUTION_HANDLER_INCLUDE */\n", "meta": {"hexsha": "d5a1b09da561ffdfad0621d18b7f00aaa35bd5b2", "size": 1637, "ext": "h", "lang": "C", "max_stars_repo_path": "test/base-utils/include/base-utils/executionHandler.h", "max_stars_repo_name": "exec-helper/source", "max_stars_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-28T13:24:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-28T13:24:30.000Z", "max_issues_repo_path": "test/base-utils/include/base-utils/executionHandler.h", "max_issues_repo_name": "exec-helper/source", "max_issues_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/base-utils/include/base-utils/executionHandler.h", "max_forks_repo_name": "exec-helper/source", "max_forks_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-07-03T11:11:19.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-03T11:11:19.000Z", "avg_line_length": 28.224137931, "max_line_length": 79, "alphanum_fraction": 0.7196090409, "num_tokens": 330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.03358950274784212, "lm_q2_score": 0.01566364948707647, "lm_q1q2_score": 0.000526134197487391}}
{"text": "/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */\n/*\n *     Copyright 2018 Couchbase, Inc.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n */\n\n#pragma once\n\n#include <gsl.h>\n#include <nlohmann/json_fwd.hpp>\n#include <cstdint>\n#include <string>\n\n/**\n * The Event class represents the information needed for a single\n * audit event entry.\n */\nclass Event {\npublic:\n    Event() = delete;\n\n    /**\n     * Construct and initialize a new Event structure based off the\n     * provided JSON. See ../README.md for information about the\n     * layout of the JSON element.\n     *\n     * @param entry\n     * @throws std::runtime_error for errors accessing the expected\n     *                            elements\n     */\n    explicit Event(const nlohmann::json& json);\n\n    /// The identifier for this entry\n    uint32_t id;\n    /// The name of the entry\n    std::string name;\n    /// The full description of the entry\n    std::string description;\n    /// Set to true if this entry should be handled synchronously\n    bool sync;\n    /// Set to true if this entry is enabled (or should be dropped)\n    bool enabled;\n    /// Set to true if the user may enable filtering for the enry\n    bool filtering_permitted;\n    /// The textual representation of the JSON describing mandatory\n    /// fields in the event (NOTE: this is currently not enforced\n    /// by the audit daemon)\n    std::string mandatory_fields;\n    /// The textual representation of the JSON describing the optional\n    /// fields in the event (NOTE: this is currently not enforced\n    /// by the audit daemon)\n    std::string optional_fields;\n};\n", "meta": {"hexsha": "94285d535ceddd528877f487da5b098e150b40f5", "size": 2156, "ext": "h", "lang": "C", "max_stars_repo_path": "auditd/generator/generator_event.h", "max_stars_repo_name": "hrajput89/kv_engine", "max_stars_repo_head_hexsha": "33fb1ab2c9787f55555e5f7edea38807b3dbc371", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-13T07:33:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-13T07:33:09.000Z", "max_issues_repo_path": "auditd/generator/generator_event.h", "max_issues_repo_name": "paolococchi/kv_engine", "max_issues_repo_head_hexsha": "40256dca6bf77fb4bcc18e8ef7d9b8f991bf4e45", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "auditd/generator/generator_event.h", "max_forks_repo_name": "paolococchi/kv_engine", "max_forks_repo_head_hexsha": "40256dca6bf77fb4bcc18e8ef7d9b8f991bf4e45", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-10-11T14:00:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-06T09:20:15.000Z", "avg_line_length": 33.1692307692, "max_line_length": 79, "alphanum_fraction": 0.6720779221, "num_tokens": 486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.025565215408118718, "lm_q2_score": 0.020332355346163247, "lm_q1q2_score": 0.0005198010441790777}}
{"text": "/* -----------------------------------------------------------------------------\n * Copyright 2021 Jonathan Haigh\n * SPDX-License-Identifier: MIT\n * ---------------------------------------------------------------------------*/\n\n#ifndef SQ_INCLUDE_GUARD_system_linux_udev_inl_h_\n#define SQ_INCLUDE_GUARD_system_linux_udev_inl_h_\n\n#include \"core/errors.h\"\n#include \"core/typeutil.h\"\n\n#include <fmt/format.h>\n#include <gsl/gsl>\n\nnamespace sq::system::linux {\n\ntemplate <typename T> UdevPtr<T>::UdevPtr(SQ_MU std::nullptr_t np) noexcept {}\n\ntemplate <typename T>\nUdevPtr<T>::UdevPtr(const UdevPtr &other) noexcept : t_{other.t_.p_} {\n  if (t_.p_ != nullptr) {\n    t_.add_ref();\n  }\n}\n\ntemplate <typename T>\nUdevPtr<T>::UdevPtr(UdevPtr &&other) noexcept : t_{other.t_.p_} {\n  other.t_.p_ = nullptr;\n}\n\n// When a raw pointer is first obtained from libudev it already has a reference\n// count of 1 so we don't need to adjust it here.\ntemplate <typename T> UdevPtr<T>::UdevPtr(RawPtr p) noexcept : t_{p} {\n  Expects(p != nullptr);\n  Ensures(t_.p_ != nullptr);\n}\n\ntemplate <typename T>\nUdevPtr<T> &UdevPtr<T>::operator=(const UdevPtr &other) noexcept {\n  // Note: must call add_ref before remove_ref to deal with the case where\n  // *this == other\n  if (other.t_.p_ != nullptr) {\n    other.t_.add_ref();\n  }\n  if (t_.p_ != nullptr) {\n    t_.remove_ref();\n  }\n  t_.p_ = other.t_.p_;\n  return *this;\n}\n\ntemplate <typename T> UdevPtr<T>::~UdevPtr() noexcept {\n  if (t_.p_ != nullptr) {\n    t_.remove_ref();\n  }\n}\n\ntemplate <typename T>\nUdevPtr<T> &UdevPtr<T>::operator=(UdevPtr &&other) noexcept {\n  std::swap(t_.p_, other.t_.p_);\n  return *this;\n}\n\ntemplate <typename T> void UdevPtr<T>::reset() noexcept {\n  UdevPtr<T>{}.swap(*this);\n}\n\ntemplate <typename T> void UdevPtr<T>::swap(UdevPtr &other) noexcept {\n  std::swap(t_.p_, other.t_.p_);\n}\n\ntemplate <typename T> T *UdevPtr<T>::get() const noexcept {\n  if (t_.p_ == nullptr) {\n    return nullptr;\n  }\n  return &t_;\n}\n\ntemplate <typename T> T &UdevPtr<T>::operator*() const noexcept {\n  Expects(t_.p_ != nullptr);\n  return t_;\n}\n\ntemplate <typename T> T *UdevPtr<T>::operator->() const noexcept {\n  return get();\n}\n\ntemplate <typename T> UdevPtr<T>::operator bool() const noexcept {\n  return t_.p_ != nullptr;\n}\n\ntemplate <typename T>\nauto UdevPtr<T>::operator<=>(const UdevPtr<T> &other) const noexcept {\n  return std::compare_three_way{}(t_.p_, other.t_.p_);\n}\n\ntemplate <typename T>\nbool UdevPtr<T>::operator==(const UdevPtr<T> &other) const noexcept {\n  return t_.p_ == other.t_.p_;\n}\n\ntemplate <typename T>\nauto UdevPtr<T>::operator<=>(std::nullptr_t np) const noexcept {\n  return std::compare_three_way{}(t_.p_, static_cast<decltype(t_.p_)>(np));\n}\n\ntemplate <typename T>\nbool UdevPtr<T>::operator==(std::nullptr_t np) const noexcept {\n  return t_.p_ == static_cast<decltype(t_.p_)>(np);\n}\n\ntemplate <typename U, typename... Args> UdevPtr<U> make_udev(Args &&...args) {\n  auto *const p = U::create_new(SQ_FWD(args)...);\n  if (p == nullptr) {\n    throw UdevError{fmt::format(\"Failed to create new {}\", base_type_name(p))};\n  }\n  return UdevPtr<U>{p};\n}\n\n} // namespace sq::system::linux\n\n#endif // SQ_INCLUDE_GUARD_system_linux_udev_inl_h_\n", "meta": {"hexsha": "7190706ef86f451d5f0de4052ee838596e642b57", "size": 3187, "ext": "h", "lang": "C", "max_stars_repo_path": "src/system/include/system/linux/udev.inl.h", "max_stars_repo_name": "jonathanhaigh/sq", "max_stars_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-12T16:21:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-12T16:21:41.000Z", "max_issues_repo_path": "src/system/include/system/linux/udev.inl.h", "max_issues_repo_name": "jonathanhaigh/sq", "max_issues_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 44.0, "max_issues_repo_issues_event_min_datetime": "2021-02-08T19:17:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-05T18:51:38.000Z", "max_forks_repo_path": "src/system/include/system/linux/udev.inl.h", "max_forks_repo_name": "jonathanhaigh/sq", "max_forks_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9105691057, "max_line_length": 80, "alphanum_fraction": 0.6457483527, "num_tokens": 922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.02758528062793511, "lm_q2_score": 0.018833130854160624, "lm_q1q2_score": 0.0005195171997146441}}
{"text": "#pragma once\n#include \"errors.h\"\n#include \"usageinfoformat.h\"\n#include \"detail/config.h\"\n#include \"detail/configmacro.h\"\n#include \"detail/configaccess.h\"\n#include \"detail/flag.h\"\n#include <gsl/gsl>\n#include <iostream>\n#include <ostream>\n#include <optional>\n#include <map>\n#include <utility>\n\nnamespace cmdlime{\n\nenum class ErrorOutputMode{\n    STDOUT,\n    STDERR\n};\n\ntemplate<typename TConfig>\nclass ConfigReader{\n    struct CommandHelpFlag{\n        bool value = false;\n        std::string usageInfo;\n    };\n\npublic:\n    ConfigReader(TConfig& cfg,\n                 std::string programName,\n                 const UsageInfoFormat& usageInfoFormat = {},\n                 ErrorOutputMode errorOutputMode = ErrorOutputMode::STDERR)\n        : cfg_(cfg)\n        , programName_(std::move(programName))\n        , usageInfoFormat_(usageInfoFormat)\n        , errorOutput_(errorOutputMode == ErrorOutputMode::STDERR ? std::cerr : std::cout)\n    {}\n\n    int exitCode() const\n    {\n        return exitCode_;\n    }\n\n    bool read(const std::vector<std::string>& cmdLine)\n    {\n        addExitFlags();\n        if(!processCommandLine(cmdLine))\n            return exitOnError(-1);\n\n        if (processFlagsAndExit())\n            return exitOnFlag();\n\n        return success();\n    }\n\n    bool readCommandLine(int argc, char** argv)\n    {\n        auto cmdLine = std::vector<std::string>(argv + 1, argv + argc);\n        return read(cmdLine);\n    }\n\nprivate:\n    void addExitFlags()\n    {\n        using NameProvider = typename detail::Format<detail::ConfigAccess<TConfig>::format()>::nameProvider;\n        auto helpFlag = std::make_unique<detail::Flag>(NameProvider::name(\"help\"),\n                                                       std::string{},\n                                                       [this]()->bool&{return help_;},\n                                                       detail::Flag::Type::Exit);\n        helpFlag->info().addDescription(\"show usage info and exit\");\n        detail::ConfigAccess<TConfig>{cfg_}.addFlag(std::move(helpFlag));\n\n        if (!cfg_.versionInfo().empty()){\n            auto versionFlag = std::make_unique<detail::Flag>(NameProvider::name(\"version\"),\n                                                           std::string{},\n                                                           [this]()->bool&{return version_;},\n                                                           detail::Flag::Type::Exit);\n            versionFlag->info().addDescription(\"show version info and exit\");\n            detail::ConfigAccess<TConfig>{cfg_}.addFlag(std::move(versionFlag));\n        }\n\n        detail::ConfigAccess<TConfig>(cfg_).addHelpFlagToCommands(programName_);\n    }\n\n    bool processCommandLine(const std::vector<std::string>& cmdLine)\n    {\n        try{\n            cfg_.read(cmdLine);\n        }\n        catch(const CommandError& e){\n            errorOutput_ << \"Command '\" + e.commandName() + \"' error: \" << e.what() << \"\\n\";\n            std::cout << e.commandUsageInfo() << std::endl;\n            return false;\n        }\n        catch(const Error& e){\n            errorOutput_ << e.what() << \"\\n\";\n            std::cout << cfg_.usageInfo(programName_) << std::endl;\n            return false;\n        }\n        return true;\n    }\n\n    bool processFlagsAndExit()\n    {\n        if (help_){\n            std::cout << cfg_.usageInfoDetailed(programName_, usageInfoFormat_) << std::endl;\n            return true;\n        }\n        if (version_){\n            std::cout << cfg_.versionInfo() << std::endl;\n            return true;\n        }\n\n        for (auto command :  detail::ConfigAccess<TConfig>{cfg_}.commandList())\n            if (checkCommandHelpFlag(command))\n                return true;\n\n        return false;\n    }\n\n    bool checkCommandHelpFlag(gsl::not_null<detail::ICommand*> command)\n    {\n        if (command->isHelpFlagSet()){\n            std::cout << command->usageInfoDetailed() << std::endl;\n            return true;\n        }\n\n        for (auto childCommand : command->commandList())\n            if (checkCommandHelpFlag(childCommand))\n                return true;\n\n        return false;\n    }\n\n    bool exitOnFlag()\n    {\n        exitCode_ = 0;\n        return false;\n    }\n\n    bool exitOnError(int errorCode)\n    {\n        exitCode_ = errorCode;\n        return false;\n    }\n\n    bool success()\n    {\n        exitCode_ = 0;\n        return true;\n    }\n\nprivate:\n    TConfig& cfg_;\n    std::string programName_;\n    UsageInfoFormat usageInfoFormat_;\n    std::map<int, CommandHelpFlag> commandHelpFlags_;\n    std::ostream& errorOutput_;\n    int exitCode_ = 0;\n    bool help_ = false;\n    bool version_ = false;\n}\n;\n}\n", "meta": {"hexsha": "2a3cdd02716a3f57b512f3f02bdd121ea34ec15c", "size": 4655, "ext": "h", "lang": "C", "max_stars_repo_path": "thirdparty/cmdlime/include/cmdlime/configreader.h", "max_stars_repo_name": "GerHobbelt/hypertextcpp", "max_stars_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_stars_repo_licenses": ["MS-PL"], "max_stars_count": 77.0, "max_stars_repo_stars_event_min_datetime": "2021-05-20T18:05:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T21:37:54.000Z", "max_issues_repo_path": "thirdparty/cmdlime/include/cmdlime/configreader.h", "max_issues_repo_name": "GerHobbelt/hypertextcpp", "max_issues_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_issues_repo_licenses": ["MS-PL"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2021-05-20T22:04:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-21T08:13:28.000Z", "max_forks_repo_path": "thirdparty/cmdlime/include/cmdlime/configreader.h", "max_forks_repo_name": "GerHobbelt/hypertextcpp", "max_forks_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_forks_repo_licenses": ["MS-PL"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-22T00:36:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-22T00:36:08.000Z", "avg_line_length": 28.0421686747, "max_line_length": 108, "alphanum_fraction": 0.5458646617, "num_tokens": 1015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.033085982202364056, "lm_q2_score": 0.01566365201433291, "lm_q1q2_score": 0.0005182473117702425}}
{"text": "#pragma once\r\n#include <wrl/client.h>\r\n#include <d3d11.h>\r\n#include <gsl/span>\r\n\r\nnamespace vrutil\r\n{\r\ntemplate <typename T> using ComPtr = Microsoft::WRL::ComPtr<T>;\r\nusing SharedTexture = std::pair<ComPtr<ID3D11Texture2D>, HANDLE>;\r\n\r\nclass D3DManager\r\n{\r\n    class D3D11ManagerImpl *m_impl;\r\n\r\npublic:\r\n    D3DManager();\r\n    ~D3DManager();\r\n    bool Initialize();\r\n    ComPtr<ID3D11Texture2D> CreateStaticTexture(int w, int h, const gsl::span<uint8_t> &bytes);\r\n    SharedTexture CreateSharedStaticTexture(int w, int h, const gsl::span<uint8_t> &bytes);\r\n    void Copy(const ComPtr<ID3D11Texture2D> &src, const ComPtr<ID3D11Texture2D> &dst);\r\n};\r\n\r\n} // namespace vrutil", "meta": {"hexsha": "559b53fdd76b4417b04d55a77a597d84d568e282", "size": 674, "ext": "h", "lang": "C", "max_stars_repo_path": "vrutil/D3DManager.h", "max_stars_repo_name": "ousttrue/VROverlaySample", "max_stars_repo_head_hexsha": "6116b91403393f2f7747c3da902b29612b0ce20a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vrutil/D3DManager.h", "max_issues_repo_name": "ousttrue/VROverlaySample", "max_issues_repo_head_hexsha": "6116b91403393f2f7747c3da902b29612b0ce20a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vrutil/D3DManager.h", "max_forks_repo_name": "ousttrue/VROverlaySample", "max_forks_repo_head_hexsha": "6116b91403393f2f7747c3da902b29612b0ce20a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0833333333, "max_line_length": 96, "alphanum_fraction": 0.7017804154, "num_tokens": 198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.04208773272170267, "lm_q2_score": 0.012241274548579966, "lm_q1q2_score": 0.0005152074913736151}}
{"text": "/**\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n#ifndef LIBMINIFI_INCLUDE_UTILS_GSL_H_\n#define LIBMINIFI_INCLUDE_UTILS_GSL_H_\n\n#include <type_traits>\n\n#include <gsl-lite/gsl-lite.hpp>\n\nnamespace org {\nnamespace apache {\nnamespace nifi {\nnamespace minifi {\n\nnamespace gsl = ::gsl_lite;\n\nnamespace utils {\nnamespace detail {\ntemplate<typename T>\nusing remove_cvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type;\n}  // namespace detail\n\ntemplate<typename Container, typename T>\nContainer span_to(gsl::span<T> span) {\n  static_assert(std::is_constructible<Container, typename gsl::span<T>::iterator, typename gsl::span<T>::iterator>::value,\n      \"The destination container must have an iterator (pointer) range constructor\");\n  return Container(std::begin(span), std::end(span));\n}\ntemplate<template<typename...> class Container, typename T>\nContainer<detail::remove_cvref_t<T>> span_to(gsl::span<T> span) {\n  static_assert(std::is_constructible<Container<detail::remove_cvref_t<T>>, typename gsl::span<T>::iterator, typename gsl::span<T>::iterator>::value,\n      \"The destination container must have an iterator (pointer) range constructor\");\n  return span_to<Container<detail::remove_cvref_t<T>>>(span);\n}\n}  // namespace utils\n\n}  // namespace minifi\n}  // namespace nifi\n}  // namespace apache\n}  // namespace org\n\n#endif  // LIBMINIFI_INCLUDE_UTILS_GSL_H_\n", "meta": {"hexsha": "9bd4f09e57313ea3c1f69eb4ae72170d5934342c", "size": 2142, "ext": "h", "lang": "C", "max_stars_repo_path": "libminifi/include/utils/gsl.h", "max_stars_repo_name": "dtrodrigues/nifi-minifi-cpp", "max_stars_repo_head_hexsha": "87147e2dffcda6cc6e4e0510a57cc88011fda37f", "max_stars_repo_licenses": ["Apache-2.0", "OpenSSL"], "max_stars_count": 113.0, "max_stars_repo_stars_event_min_datetime": "2016-04-30T15:00:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T20:42:58.000Z", "max_issues_repo_path": "libminifi/include/utils/gsl.h", "max_issues_repo_name": "dtrodrigues/nifi-minifi-cpp", "max_issues_repo_head_hexsha": "87147e2dffcda6cc6e4e0510a57cc88011fda37f", "max_issues_repo_licenses": ["Apache-2.0", "OpenSSL"], "max_issues_count": 688.0, "max_issues_repo_issues_event_min_datetime": "2016-04-28T17:52:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T07:58:05.000Z", "max_forks_repo_path": "libminifi/include/utils/gsl.h", "max_forks_repo_name": "dtrodrigues/nifi-minifi-cpp", "max_forks_repo_head_hexsha": "87147e2dffcda6cc6e4e0510a57cc88011fda37f", "max_forks_repo_licenses": ["Apache-2.0", "OpenSSL"], "max_forks_count": 104.0, "max_forks_repo_forks_event_min_datetime": "2016-04-28T15:20:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:39:20.000Z", "avg_line_length": 37.5789473684, "max_line_length": 149, "alphanum_fraction": 0.753968254, "num_tokens": 487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.021615332762647658, "lm_q2_score": 0.02368947297948587, "lm_q1q2_score": 0.0005120558414233373}}
{"text": "#ifndef XYWEBSERVER_TEST_UTILS_H_\n#define XYWEBSERVER_TEST_UTILS_H_\n\n#include <gtest/gtest.h>\n\n#include <gsl/pointers>\n\n#include \"runtime/runtime.h\"\n\n#define CO_ASSERT_EQ(val1, val2)               \\\n  ({                                           \\\n    auto f = [&]() { ASSERT_EQ(val1, val2); }; \\\n    f();                                       \\\n  })\n\nconstexpr std::chrono::milliseconds time_deviation(7);\n\nclass TestRuntimeCtxGuard {\n public:\n  TestRuntimeCtxGuard(\n      gsl::owner<std::function<xyco::runtime::Future<void>()> *> co_wrapper,\n      bool in_runtime);\n\n  TestRuntimeCtxGuard(const TestRuntimeCtxGuard &guard) = delete;\n\n  TestRuntimeCtxGuard(TestRuntimeCtxGuard &&guard) = delete;\n\n  auto operator=(const TestRuntimeCtxGuard &guard)\n      -> TestRuntimeCtxGuard & = delete;\n\n  auto operator=(TestRuntimeCtxGuard &&guard) -> TestRuntimeCtxGuard & = delete;\n\n  ~TestRuntimeCtxGuard();\n\n private:\n  gsl::owner<std::function<xyco::runtime::Future<void>()> *> co_wrapper_;\n};\n\nclass TestRuntimeCtx {\n public:\n  // run until co finished\n  template <typename Fn>\n  static auto co_run(Fn &&co)\n      -> void requires(std::is_invocable_r_v<xyco::runtime::Future<void>, Fn>) {\n    // co_outer's lifetime is managed by the caller to avoid being destroyed\n    // automatically before resumed.\n\n    std::mutex mutex;\n    std::unique_lock<std::mutex> lock_guard(mutex);\n    std::condition_variable cv;\n\n    auto co_outer = [&]() -> xyco::runtime::Future<void> {\n      try {\n        co_await co();\n        cv.notify_one();\n      } catch (std::exception e) {\n        auto f = [&]() { ASSERT_NO_THROW(throw e); };\n        f();\n        cv.notify_one();\n      }\n    };\n    runtime_->spawn(co_outer());\n    cv.wait(lock_guard);\n  }\n\n  template <typename Fn>\n  static auto co_run_no_wait(Fn &&co) -> TestRuntimeCtxGuard\n      requires(std::is_invocable_r_v<xyco::runtime::Future<void>, Fn>) {\n    auto *co_outer = gsl::owner<std::function<xyco::runtime::Future<void>()> *>(\n        new std::function<xyco::runtime::Future<void>()>(\n            [=]() -> xyco::runtime::Future<void> { co_await co(); }));\n\n    return {co_outer, true};\n  }\n\n  template <typename Fn>\n  static auto co_run_without_runtime(Fn &&co) -> TestRuntimeCtxGuard\n      requires(std::is_invocable_r_v<xyco::runtime::Future<void>, Fn>) {\n    auto *co_outer = gsl::owner<std::function<xyco::runtime::Future<void>()> *>(\n        new std::function<xyco::runtime::Future<void>()>(\n            [=]() -> xyco::runtime::Future<void> { co_await co(); }));\n\n    return {co_outer, false};\n  }\n\n private : static std::unique_ptr<xyco::runtime::Runtime> runtime_;\n};\n\n#endif  // XYWEBSERVER_TEST_UTILS_H_", "meta": {"hexsha": "72ba8d9bb15639cf0fcff2c0e0e62e8fa71b0702", "size": 2655, "ext": "h", "lang": "C", "max_stars_repo_path": "tests/utils.h", "max_stars_repo_name": "ddxy18/xyco", "max_stars_repo_head_hexsha": "7682652f17b82e2370fa7af17635c5d0c470efe0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/utils.h", "max_issues_repo_name": "ddxy18/xyco", "max_issues_repo_head_hexsha": "7682652f17b82e2370fa7af17635c5d0c470efe0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2021-10-30T06:10:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-18T06:16:15.000Z", "max_forks_repo_path": "tests/utils.h", "max_forks_repo_name": "ddxy18/xyco", "max_forks_repo_head_hexsha": "7682652f17b82e2370fa7af17635c5d0c470efe0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8314606742, "max_line_length": 80, "alphanum_fraction": 0.6293785311, "num_tokens": 676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.030214586630765133, "lm_q2_score": 0.016914915001245496, "lm_q1q2_score": 0.0005110771646571607}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef gsm_129e9ac0_6a88_49a3_8bf1_a95a8edf7da8_h\r\n#define gsm_129e9ac0_6a88_49a3_8bf1_a95a8edf7da8_h\r\n\r\n#include <gslib/xml.h>\r\n#include <gslib/json.h>\r\n#include <gslib/uuid.h>\r\n#include <gslib/vdir.h>\r\n\r\n/*\r\n * Make tool introductions.\r\n * see gsm_help();\r\n */\r\n\r\n__gslib_begin__\r\n\r\nenum gsm_project_type\r\n{\r\n    gpt_executable,\r\n    gpt_static_library,\r\n    gpt_dynamic_library,\r\n};\r\n\r\nstruct gsm_project;\r\ntypedef list<string> gsm_str_list;\r\ntypedef list<gsm_project> gsm_proj_list;\r\n\r\nstruct gsm_config\r\n{\r\n    string              source_dir;\r\n    string              target_dir;\r\n    string              spec_compiler;\r\n    bool                is_debug;\r\n};\r\n\r\nstruct gsm_globals\r\n{\r\n    string              compiler;           /* $compiler */\r\n    string              os_name;            /* $os */\r\n    string              os_version;         /* $os_ver */\r\n    string              source_dir;         /* $src_dir */\r\n    string              target_dir;         /* $tar_dir */\r\n    string              target_name;        /* $tar_name */\r\n    bool                is_debug;           /* $debug */\r\n};\r\n\r\nstruct gsm_project\r\n{\r\n    string              name;\r\n    uuid                project_id;\r\n    string              output_name;\r\n    gsm_project_type    project_type;\r\n    gsm_str_list        definitions;\r\n    gsm_str_list        libraries;\r\n    string              project_dir;\r\n    string              intermediate_dir;\r\n    string              output_dir;\r\n    gsm_str_list        include_dirs;\r\n    gsm_str_list        library_dirs;\r\n    gsm_str_list        sources;\r\n    json_node_table     ext_sheet;\r\n};\r\n\r\nextern void gsm_help(string& str);\r\nextern void gsm_syntax_help(string& str);\r\nextern bool gsm_setup_globals(gsm_globals& globals, const gsm_config& cfgs);\r\nextern bool gsm_prepare_projects(gsm_proj_list& proj_list, vdir& vd, const gsm_globals& globals);\r\nextern bool gsm_generate_projects(vdir& vd, const gsm_globals& globals);\r\nextern bool gsm_finalize_projects(vdir& vd, const gsm_proj_list& projects, const gsm_globals& globals);\r\n\r\n__gslib_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "c329f28a6bd5492e8a4a8bc27e52582214997d03", "size": 3351, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gslib/gsm.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/gslib/gsm.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gslib/gsm.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 33.51, "max_line_length": 104, "alphanum_fraction": 0.6523425843, "num_tokens": 771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.025565214665694145, "lm_q2_score": 0.019719129151504953, "lm_q1q2_score": 0.0005041237697787713}}
{"text": "// MIT License\n//\n// Copyright (c) 2020 SunnyCase\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n#pragma once\n#include \"object.h\"\n#include \"utility.h\"\n#include <chino/io.h>\n#include <chino/threading.h>\n#include <gsl/gsl-lite.hpp>\n\nnamespace chino::io\n{\n#if defined(_MSC_VER)\n#pragma section(\".CHDRV$A\", long, read) // Begin drivers\n#pragma section(\".CHDRV$C\", long, read) // Drivers\n#pragma section(\".CHDRV$Z\", long, read) // End drivers\n#define EXPORT_DRIVER(x) __declspec(allocate(\".CHDRV$C\")) const ::chino::io::driver *CHINO_CONCAT(_drv_, __COUNTER__) = &x\n\n#pragma section(\".CHHDR$A\", long, read) // Begin hardware device registrations\n#pragma section(\".CHHDR$C\", long, read) // Hardware device registrations\n#pragma section(\".CHHDR$Z\", long, read) // End hardware device registrations\n#define EXPORT_HARDWARE(x) __declspec(allocate(\".CHHDR$C\")) const ::chino::io::hardware_device_registration *CHINO_CONCAT(_hdr_, __COUNTER__) = &x\n#elif defined(__GNUC__)\n#define EXPORT_DRIVER(x) __attribute__((unused, section(\".chdrv\"))) const ::chino::io::driver *CHINO_CONCAT(_drv_, __COUNTER__) = &x\n#define EXPORT_HARDWARE(x) __attribute__((unused, section(\".chhdr\"))) const ::chino::io::hardware_device_registration *CHINO_CONCAT(_hdr_, __COUNTER__) = &x\n#else\n#error \"Unsupported compiler\"\n#endif\n\nstruct driver;\nstruct device;\nstruct file;\n\n#define DEFINE_DEV_TYPE(x, v) x = v,\nenum class device_type\n{\n#include \"device_types.def\"\n    COUNT\n};\n#undef DEFINE_DEV_TYPE\n\nenum class driver_type\n{\n    hardware,\n    console\n};\n\nstruct hardware_device_registration\n{\n    const driver &drv;\n};\n\ntypedef result<void, error_code> (*driver_add_device_t)(const driver &drv, const hardware_device_registration &hdr);\ntypedef result<void, error_code> (*driver_attach_device_t)(const driver &drv, device &bottom_dev, std::string_view args);\ntypedef result<file *, error_code> (*driver_open_device_t)(device &dev, std::string_view filename, create_disposition create_disp);\ntypedef result<void, error_code> (*driver_close_device_t)(file &file);\ntypedef result<size_t, error_code> (*driver_read_device_t)(file &file, gsl::span<gsl::byte> buffer);\ntypedef result<void, error_code> (*driver_write_device_t)(file &file, gsl::span<const gsl::byte> buffer);\n\nstruct driver_operations\n{\n    driver_add_device_t add_device;\n    driver_attach_device_t attach_device;\n    driver_open_device_t open_device;\n    driver_close_device_t close_device;\n    driver_read_device_t read_device;\n    driver_write_device_t write_device;\n};\n\nstruct driver\n{\n    driver_type type = driver_type::hardware;\n    std::string_view name;\n    driver_operations ops;\n};\n\nstruct device : ob::object\n{\n    const driver &drv;\n    device_type type;\n    threading::sched_spinlock syncroot;\n\n    template <class T = uint8_t>\n    T &extension() noexcept { return *reinterpret_cast<T *>(reinterpret_cast<uint8_t *>(this) + sizeof(device)); }\n};\n\nstruct device_extension\n{\n    device &dev() noexcept { return *reinterpret_cast<device *>(reinterpret_cast<uint8_t *>(this) - sizeof(device)); }\n};\n\nstruct file : ob::object\n{\n    device &dev;\n    size_t offset;\n    threading::sched_spinlock syncroot;\n\n    template <class T = uint8_t>\n    T &extension() noexcept { return *reinterpret_cast<T *>(reinterpret_cast<uint8_t *>(this) + sizeof(file)); }\n};\n\nstruct file_extension\n{\n    io::file &file() noexcept { return *reinterpret_cast<io::file *>(reinterpret_cast<uint8_t *>(this) - sizeof(device)); }\n};\n\nresult<device *, error_code> create_device(const driver &drv, device_type type, size_t extension_size) noexcept;\nresult<device *, error_code> create_device(std::string_view name, const driver &drv, device_type type, size_t extension_size) noexcept;\nresult<file *, error_code> create_file(device &dev, size_t extension_size) noexcept;\n\nresult<file *, error_code> open_file(device &dev, access_mask access, std::string_view filename, create_disposition create_disp = create_disposition::open_existing) noexcept;\nresult<size_t, error_code> read_file(file &file, gsl::span<gsl::byte> buffer) noexcept;\nresult<void, error_code> write_file(file &file, gsl::span<const gsl::byte> buffer) noexcept;\nresult<void, error_code> close_file(file &file) noexcept;\n}\n", "meta": {"hexsha": "4e99c1b29d58c90cdfd41db515ee7da7dd343649", "size": 5223, "ext": "h", "lang": "C", "max_stars_repo_path": "src/ddk/include/chino/ddk/io.h", "max_stars_repo_name": "chino-os/chino-os", "max_stars_repo_head_hexsha": "e4b444983a059231636b81dc5f33206e16a859c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2018-04-28T09:50:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T11:42:23.000Z", "max_issues_repo_path": "src/ddk/include/chino/ddk/io.h", "max_issues_repo_name": "dotnetGame/chino-os", "max_issues_repo_head_hexsha": "e4b444983a059231636b81dc5f33206e16a859c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2018-05-15T02:15:33.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-30T14:46:51.000Z", "max_forks_repo_path": "src/ddk/include/chino/ddk/io.h", "max_forks_repo_name": "dotnetGame/chino-os", "max_forks_repo_head_hexsha": "e4b444983a059231636b81dc5f33206e16a859c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2018-05-18T03:54:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T10:14:07.000Z", "avg_line_length": 38.9776119403, "max_line_length": 174, "alphanum_fraction": 0.7520582041, "num_tokens": 1244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.03210070856893953, "lm_q2_score": 0.015663652387677647, "lm_q1q2_score": 0.000502814340422014}}
{"text": "#ifndef LIC_METADATA_DEFINITION\n#define LIC_METADATA_DEFINITION\n\n#include <gsl/gsl>\n\n#include \"format/ClrMetadataFormat.h\"\n\nnamespace lic\n{\n\nclass Assembly;\n\nclass Metadata\n{\npublic:\n    Metadata(Assembly& assembly, MetadataTable table, size_t rid, gsl::byte* row);\n    ~Metadata();\n\nprotected:\n    Assembly& assembly;\n    MetadataTable table;\n    size_t rid;\n    gsl::byte* row;\n};\n\n}\n\n#endif // !LIC_METADATA_DEFINITION\n", "meta": {"hexsha": "18839c216e253c73ba1f7ee3281fec6bade3fa17", "size": 422, "ext": "h", "lang": "C", "max_stars_repo_path": "src/loader/Metadata.h", "max_stars_repo_name": "roberthusak/lic", "max_stars_repo_head_hexsha": "5ad4a7014673bb60b748390856e0c7cb11eaca09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-05-18T11:44:16.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-18T11:44:16.000Z", "max_issues_repo_path": "src/loader/Metadata.h", "max_issues_repo_name": "roberthusak/lic", "max_issues_repo_head_hexsha": "5ad4a7014673bb60b748390856e0c7cb11eaca09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/loader/Metadata.h", "max_forks_repo_name": "roberthusak/lic", "max_forks_repo_head_hexsha": "5ad4a7014673bb60b748390856e0c7cb11eaca09", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.5517241379, "max_line_length": 82, "alphanum_fraction": 0.7227488152, "num_tokens": 98, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.023689474745756993, "lm_q2_score": 0.02064593186908094, "lm_q1q2_score": 0.0004890912816152124}}
{"text": "#ifndef ENVIRONMENT_INCLUDE\n#define ENVIRONMENT_INCLUDE\n\n#include <map>\n#include <string>\n#include <vector>\n\n#include <gsl/string_span>\n\nnamespace execHelper {\nnamespace config {\nusing EnvArg = std::string;\nusing EnvArgs = std::vector<EnvArg>;\n\nusing EnvironmentCollection = std::map<std::string, EnvArg>;\nusing EnvironmentValue = std::pair<std::string, EnvArg>;\n\nstatic const gsl::czstring<> ENVIRONMENT_KEY = \"environment\";\n\n} // namespace config\n} // namespace execHelper\n\n#endif /* ENVIRONMENT_INCLUDE */\n", "meta": {"hexsha": "2e0889770fc3fdca636f3b72a790eb13811f04dc", "size": 509, "ext": "h", "lang": "C", "max_stars_repo_path": "src/config/include/config/environment.h", "max_stars_repo_name": "exec-helper/source", "max_stars_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-28T13:24:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-28T13:24:30.000Z", "max_issues_repo_path": "src/config/include/config/environment.h", "max_issues_repo_name": "exec-helper/source", "max_issues_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/config/include/config/environment.h", "max_forks_repo_name": "exec-helper/source", "max_forks_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-07-03T11:11:19.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-03T11:11:19.000Z", "avg_line_length": 21.2083333333, "max_line_length": 61, "alphanum_fraction": 0.7544204322, "num_tokens": 114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.01971912810734659, "lm_q2_score": 0.024423087790701507, "lm_q1q2_score": 0.0004816019969218154}}
{"text": "#ifndef STATEMENT_INCLUDE\n#define STATEMENT_INCLUDE\n\n#include <string>\n\n#include <gsl/gsl>\n\n#include \"executionContent.h\"\n#include \"yaml.h\"\n\nnamespace execHelper {\nnamespace test {\nnamespace baseUtils {\nusing StatementKey = std::string;\nusing StatementCollection = ExecutionContent::ConfigCommand;\n\nclass Statement {\n  public:\n    virtual ~Statement() = default;\n\n    virtual StatementKey getKey() const noexcept = 0;\n    virtual void write(gsl::not_null<YamlWriter*> yaml,\n                       const std::string& command) const noexcept = 0;\n\n    virtual inline unsigned int getNumberOfExecutions() const noexcept {\n        return m_execution.getNumberOfExecutions();\n    }\n\n    virtual inline void resetExecutions() noexcept { m_execution.clear(); }\n\n  protected:\n    Statement(ReturnCode returnCode) noexcept : m_execution(returnCode) {}\n\n    ExecutionContent m_execution;\n};\n} // namespace baseUtils\n} // namespace test\n} // namespace execHelper\n\n#endif /* STATEMENT_INCLUDE */\n", "meta": {"hexsha": "4a01ca7037b4ed8248ba6aae98bdbe30676f84c2", "size": 984, "ext": "h", "lang": "C", "max_stars_repo_path": "test/base-utils/include/base-utils/statement.h", "max_stars_repo_name": "exec-helper/source", "max_stars_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-28T13:24:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-28T13:24:30.000Z", "max_issues_repo_path": "test/base-utils/include/base-utils/statement.h", "max_issues_repo_name": "exec-helper/source", "max_issues_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/base-utils/include/base-utils/statement.h", "max_forks_repo_name": "exec-helper/source", "max_forks_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-07-03T11:11:19.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-03T11:11:19.000Z", "avg_line_length": 24.0, "max_line_length": 75, "alphanum_fraction": 0.7245934959, "num_tokens": 204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.018833132093236893, "lm_q2_score": 0.025565213088042, "lm_q1q2_score": 0.00048147303507884364}}
{"text": "#pragma once\n\n#include <gsl/gsl>\n\n#include <vector>\n#include <memory>\n#include <mutex>\n\nstruct AVFrame;\n\nnamespace video_streamer\n{\n\nclass StreamSession;\nclass FrameEncoder;\n\nclass GroupStreamSession\n{\npublic:\n    explicit GroupStreamSession(std::shared_ptr<FrameEncoder> frameEncoder);\n\n    void addStream(std::unique_ptr<StreamSession> streamSession);\n    void pushFrame(gsl::not_null<const AVFrame*> frame);\n\nprivate:\n    std::shared_ptr<FrameEncoder> m_frameEncoder;\n    std::vector<std::unique_ptr<StreamSession>> m_streamSession;\n    mutable std::mutex m_mtx;\n};\n\n} // video_streamer", "meta": {"hexsha": "156240c7821fe8f43d7db97da6d1d3c40b246e30", "size": 589, "ext": "h", "lang": "C", "max_stars_repo_path": "modules/http_streamer/src/GroupStreamSession.h", "max_stars_repo_name": "nicledomaS/VideoStream", "max_stars_repo_head_hexsha": "e695e0b544a61bb4e74149005c69723dbbecb952", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/http_streamer/src/GroupStreamSession.h", "max_issues_repo_name": "nicledomaS/VideoStream", "max_issues_repo_head_hexsha": "e695e0b544a61bb4e74149005c69723dbbecb952", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-16T07:16:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T07:16:25.000Z", "max_forks_repo_path": "modules/http_streamer/src/GroupStreamSession.h", "max_forks_repo_name": "nicledomaS/VideoStream", "max_forks_repo_head_hexsha": "e695e0b544a61bb4e74149005c69723dbbecb952", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.0, "max_line_length": 76, "alphanum_fraction": 0.7589134126, "num_tokens": 139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.03461884182719031, "lm_q2_score": 0.013848607341091087, "lm_q1q2_score": 0.00047942274706809886}}
{"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n *\r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n *\r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n *\r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef applicationwin32_3971e4cb_1be6_4066_b7ea_da679d40c987_h\r\n#define applicationwin32_3971e4cb_1be6_4066_b7ea_da679d40c987_h\r\n\r\n#include <gslib/string.h>\r\n#include <gslib/std.h>\r\n#include <ariel/application.h>\r\n#include <windows.h>\r\n\r\n#undef min\r\n#undef max\r\n\r\n__ariel_begin__\r\n\r\ntypedef LRESULT(__stdcall *fnwndproc)(HWND, UINT, WPARAM, LPARAM);\r\ntypedef list<string> arg_list;\r\n\r\nextern void set_execute_path_as_directory();\r\nextern void init_application_environment(app_env& env);\r\nextern void init_application_environment(app_env& env, HINSTANCE hinst, HINSTANCE hprevinst, const gchar* argv[], int argc);\r\n\r\nstruct app_data\r\n{\r\n    HINSTANCE           hinst = nullptr;\r\n    HWND                hwnd = nullptr;\r\n    fnwndproc           wndproc = nullptr;\r\n    arg_list            arglist;\r\n\r\npublic:\r\n    bool install(const app_config& cfg, const app_env& env);\r\n    int run();\r\n};\r\n\r\nstruct app_env\r\n{\r\n    HINSTANCE           hinst = nullptr;\r\n    HINSTANCE           hprevinst = nullptr;\r\n    arg_list            arglist;\r\n\r\npublic:\r\n    void init(HINSTANCE hinst, HINSTANCE hprevinst, const gchar* argv[], int argc) { init_application_environment(*this, hinst, hprevinst, argv, argc); }\r\n};\r\n\r\n__ariel_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "39cf3e5e09d220bfcebba24042f8da32ff22fdca", "size": 2492, "ext": "h", "lang": "C", "max_stars_repo_path": "include/ariel/applicationwin32.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/ariel/applicationwin32.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ariel/applicationwin32.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 34.1369863014, "max_line_length": 154, "alphanum_fraction": 0.7158908507, "num_tokens": 576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.02002344304384381, "lm_q2_score": 0.023689472850246522, "lm_q1q2_score": 0.0004743448103555955}}
{"text": "#ifndef VKST_PLAT_LOG_H\n#define VKST_PLAT_LOG_H\n\n#include <plat/core.h>\n#include <plat/filesystem.h>\n#include <gsl.h>\n#include <string>\n\nnamespace plat {\n\n// Initialize logging with output to a given path.\n// Must be called before logging output will occur.\nvoid init_logging(plat::filesystem::path logfile, std::error_code& ec) noexcept;\n\nenum class log_severities : uint8_t {\n  trace = 1,\n  debug,\n  info,\n  warn,\n  error,\n  fatal,\n  none\n};\n\ninline constexpr gsl::czstring to_string(log_severities severity) noexcept {\n  switch(severity) {\n  case log_severities::trace: return \"TRACE\";\n  case log_severities::debug: return \"DEBUG\";\n  case log_severities::info: return \"INFO\";\n  case log_severities::warn: return \"WARN\";\n  case log_severities::error: return \"ERROR\";\n  case log_severities::fatal: return \"FATAL\";\n  case log_severities::none: return \"NONE\";\n  }\n  PLAT_MARK_UNREACHABLE;\n}\n\nvoid log(log_severities severity, gsl::czstring fmt, ...) noexcept;\n\n#define LOG_TRACE(...) ::plat::log(::plat::log_severities::trace, __VA_ARGS__)\n#define LOG_DEBUG(...) ::plat::log(::plat::log_severities::debug, __VA_ARGS__)\n#define LOG_INFO(...) ::plat::log(::plat::log_severities::info, __VA_ARGS__)\n#define LOG_WARN(...) ::plat::log(::plat::log_severities::warn, __VA_ARGS__)\n#define LOG_ERROR(...) ::plat::log(::plat::log_severities::error, __VA_ARGS__)\n#define LOG_FATAL(...) ::plat::log(::plat::log_severities::fatal, __VA_ARGS__)\n\n#define LOG_ENTER                                                              \\\n  ::plat::log(::plat::log_severities::trace, \"enter: %s (%s:%d)\", __func__,    \\\n              __FILE__, __LINE__)\n#define LOG_LEAVE                                                              \\\n  ::plat::log(::plat::log_severities::trace, \"leave: %s (%s:%d)\", __func__,    \\\n              __FILE__, __LINE__)\n\n} // namespace plat\n\n#endif // VKST_PLAT_LOG_H", "meta": {"hexsha": "5ffaad508acac09cd545da44433f286acfe8c509", "size": 1870, "ext": "h", "lang": "C", "max_stars_repo_path": "src/plat/log.h", "max_stars_repo_name": "wesleygriffin/vkst", "max_stars_repo_head_hexsha": "5f1210ef8aeecdd2bbc3904b0cc4dd09892f239c", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/plat/log.h", "max_issues_repo_name": "wesleygriffin/vkst", "max_issues_repo_head_hexsha": "5f1210ef8aeecdd2bbc3904b0cc4dd09892f239c", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/plat/log.h", "max_forks_repo_name": "wesleygriffin/vkst", "max_forks_repo_head_hexsha": "5f1210ef8aeecdd2bbc3904b0cc4dd09892f239c", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3928571429, "max_line_length": 80, "alphanum_fraction": 0.6550802139, "num_tokens": 490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.020023445383028797, "lm_q2_score": 0.02368946992082154, "lm_q1q2_score": 0.0004743448071124736}}
{"text": "#ifndef LIC_TYPE_DEFINITION\n#define LIC_TYPE_DEFINITION\n\n#include <gsl/gsl>\n\n#include \"Metadata.h\"\n\nnamespace lic\n{\n\nclass MethodDefinition;\n\nclass TypeDefinition : Metadata\n{\npublic:\n    TypeDefinition(Assembly& assembly, MetadataTable table, size_t rid, gsl::byte* row);\n    ~TypeDefinition();\n\n    const char* Name() const;\n    const char* Namespace() const;\n    const gsl::span<MethodDefinition> Methods();\n\nprivate:\n    size_t FirstMethodRid();\n};\n\n}\n\n#endif // !LIC_TYPE_DEFINITION\n", "meta": {"hexsha": "a80d199beac4d5f9b586e435767870b4df451078", "size": 488, "ext": "h", "lang": "C", "max_stars_repo_path": "src/loader/TypeDefinition.h", "max_stars_repo_name": "roberthusak/lic", "max_stars_repo_head_hexsha": "5ad4a7014673bb60b748390856e0c7cb11eaca09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-05-18T11:44:16.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-18T11:44:16.000Z", "max_issues_repo_path": "src/loader/TypeDefinition.h", "max_issues_repo_name": "roberthusak/lic", "max_issues_repo_head_hexsha": "5ad4a7014673bb60b748390856e0c7cb11eaca09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/loader/TypeDefinition.h", "max_forks_repo_name": "roberthusak/lic", "max_forks_repo_head_hexsha": "5ad4a7014673bb60b748390856e0c7cb11eaca09", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.2666666667, "max_line_length": 88, "alphanum_fraction": 0.7233606557, "num_tokens": 113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.024053548696773095, "lm_q2_score": 0.019124038742473072, "lm_q1q2_score": 0.00046000099717105137}}
{"text": "#pragma once\n\n#include \"Cesium3DTiles/Library.h\"\n#include \"Cesium3DTiles/RasterOverlay.h\"\n#include \"Cesium3DTiles/RasterOverlayTileProvider.h\"\n#include <gsl/span>\n#include <memory>\n#include <vector>\n\nnamespace Cesium3DTiles {\n\nclass Tileset;\n\n/**\n * @brief A collection of {@link RasterOverlay} instances that are associated\n * with a {@link Tileset}.\n *\n * The raster overlay instances may be added to the raster overlay collection\n * of a tileset that is returned with {@link Tileset::getOverlays}. When the\n * tileset is loaded, one {@link RasterOverlayTileProvider} will be created\n * for each raster overlay that had been added. The raster overlay tile provider\n * instances will be passed to the {@link RasterOverlayTile} instances that\n * they create when the tiles are updated.\n */\nclass CESIUM3DTILES_API RasterOverlayCollection final {\npublic:\n  /**\n   * @brief Creates a new instance.\n   *\n   * @param tileset The tileset to which this instance belongs\n   */\n  RasterOverlayCollection(Tileset& tileset) noexcept;\n\n  ~RasterOverlayCollection();\n\n  /**\n   * @brief Adds the given {@link RasterOverlay} to this collection.\n   *\n   * @param pOverlay The pointer to the overlay. This may not be `nullptr`.\n   */\n  void add(std::unique_ptr<RasterOverlay>&& pOverlay);\n\n  /**\n   * @brief Remove the given {@link RasterOverlay} from this collection.\n   */\n  void remove(RasterOverlay* pOverlay) noexcept;\n\n  /**\n   * @brief A constant iterator for {@link RasterOverlay} instances.\n   */\n  typedef std::vector<std::unique_ptr<RasterOverlay>>::const_iterator\n      const_iterator;\n\n  /**\n   * @brief Returns an iterator at the beginning of this collection.\n   */\n  const_iterator begin() const noexcept { return this->_overlays.begin(); }\n\n  /**\n   * @brief Returns an iterator at the end of this collection.\n   */\n  const_iterator end() const noexcept { return this->_overlays.end(); }\n\n  /**\n   * @brief Gets the number of overlays in the collection.\n   */\n  size_t size() const noexcept { return this->_overlays.size(); }\n\nprivate:\n  Tileset* _pTileset;\n  std::vector<std::unique_ptr<RasterOverlay>> _overlays;\n};\n\n} // namespace Cesium3DTiles\n", "meta": {"hexsha": "6a55d2da06de2a50bde943ba75062858e15b233f", "size": 2148, "ext": "h", "lang": "C", "max_stars_repo_path": "Cesium3DTiles/include/Cesium3DTiles/RasterOverlayCollection.h", "max_stars_repo_name": "zy6p/cesium-native", "max_stars_repo_head_hexsha": "d7b02d0c229e54e626e313bf2cfab31ed6e8ac3b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-27T04:47:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-27T04:47:23.000Z", "max_issues_repo_path": "Cesium3DTiles/include/Cesium3DTiles/RasterOverlayCollection.h", "max_issues_repo_name": "zy6p/cesium-native", "max_issues_repo_head_hexsha": "d7b02d0c229e54e626e313bf2cfab31ed6e8ac3b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cesium3DTiles/include/Cesium3DTiles/RasterOverlayCollection.h", "max_forks_repo_name": "zy6p/cesium-native", "max_forks_repo_head_hexsha": "d7b02d0c229e54e626e313bf2cfab31ed6e8ac3b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.64, "max_line_length": 80, "alphanum_fraction": 0.7188081937, "num_tokens": 521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.03021458532087864, "lm_q2_score": 0.01495708500145351, "lm_q1q2_score": 0.00045192212092805126}}
{"text": "/// @file UniquePtr.h\n/// @author Braxton Salyer <braxtonsalyer@gmail.com>\n/// @brief This includes Hyperion's `constexpr` equivalents and extensions to the C++ standard\n/// library's `std::unique_ptr<T, Deleter>`\n/// @version 0.1\n/// @date 2021-11-05\n///\n/// MIT License\n/// @copyright Copyright (c) 2021 Braxton Salyer <braxtonsalyer@gmail.com>\n///\n/// Permission is hereby granted, free of charge, to any person obtaining a copy\n/// of this software and associated documentation files (the \"Software\"), to deal\n/// in the Software without restriction, including without limitation the rights\n/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n/// copies of the Software, and to permit persons to whom the Software is\n/// furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in all\n/// copies or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n/// SOFTWARE.\n#pragma once\n\n#include <Hyperion/Concepts.h>\n#include <Hyperion/HyperionDef.h>\n#include <Hyperion/memory/CompressedPair.h>\n#include <gsl/gsl>\n\n/// @ingroup memory\n/// @{\n///\t@defgroup UniquePtr UniquePtr\n/// Hyperion provides a `constexpr` equivalent to the C++ standard library's\n/// `std::unique_ptr<T, Deleter>` in our `UniquePtr`, with additional functionality like allocator\n/// aware factory functions (`allocate_unique`).\n///\n/// Example:\n///\n/// auto ptr = hyperion::make_unique<i32>(42);\n/// ptr.reset(24);\n///\n/// auto ptr2 = hyperion::allocate_unique<i32>(std::allocator<i32>(), 42);\n/// ptr2.reset(24);\n/// @headerfile \"Hyperion/memory/UniquePtr.h\"\n/// @}\n\nnamespace hyperion {\n\n\t/// @brief Default Deleter type for Hyperion smart pointers\n\t/// This is the default deleter type used by Hyperion smart pointers\n\t/// such as `hyperion::UniquePtr<T, Deleter>`\n\t///\n\t/// @tparam T The type to handle deletion for (eg, `i32`, `std::string`)\n\t///\n\t/// # Requirements\n\t/// - `concepts::Deletable<T>`: T must be a deletable type\n\t/// - `concepts::NotFunction<T>`: T must NOT be a function type\n\t/// @ingroup memory\n\t/// @headerfile \"Hyperion/memory/UniquePtr.h\"\n\ttemplate<typename T>\n\trequires concepts::Deletable<T> && concepts::NotFunction<T>\n\tstruct DefaultDeleter {\n\n\t\t/// @brief Default constructs a `DefaultDeleter`\n\t\t/// @ingroup memory\n\t\tconstexpr DefaultDeleter() noexcept = default;\n\t\t/// @brief Copy-constructs a `DefaultDeleter` from the given one\n\t\t/// @ingroup memory\n\t\tconstexpr DefaultDeleter(const DefaultDeleter&) noexcept = default;\n\t\t/// @brief Move-constructs a `DefaultDeleter` from the given one\n\t\t/// @ingroup memory\n\t\tconstexpr DefaultDeleter(DefaultDeleter&&) noexcept = default;\n\t\t/// @brief Destructs a `DefaultDeleter`\n\t\t/// @ingroup memory\n\t\tconstexpr ~DefaultDeleter() noexcept = default;\n\t\t/// @brief Constructs a `DefaultDeleter<T>` from a `DefaultDeleter<U>`\n\t\t///\n\t\t/// @tparam U - The type managed by the given deleter\n\t\t///\n\t\t/// @param deleter - The deleter to construct this from\n\t\t///\n\t\t/// # Requirements\n\t\t/// - `concepts::Convertible<U*, T*>`: The pointer type of `deleter` must be convertible two\n\t\t/// the pointer type of `DefaultDeleter<T>` in order to construct a `DefaultDeleter` from it\n\t\t/// @ingroup memory\n\t\ttemplate<typename U>\n\t\trequires concepts::Convertible<U*, T*>\n\t\texplicit DefaultDeleter([[maybe_unused]] const DefaultDeleter<U>& deleter) noexcept {\n\t\t}\n\n\t\t/// @brief Deletes the data at the given pointer\n\t\t///\n\t\t/// @param ptr - The pointer to the data to delete\n\t\t/// @ingroup memory\n\t\tconstexpr auto\n\t\toperator()(gsl::owner<T*> ptr) const noexcept(concepts::NoexceptDeletable<T>) {\n\t\t\tdelete ptr;\n\t\t}\n\n\t\t/// @brief Copy-assigns this `DefaultDeleter` from the given one\n\t\t/// @ingroup memory\n\t\tconstexpr auto operator=(const DefaultDeleter&) noexcept -> DefaultDeleter& = default;\n\t\t/// @brief Move-assigns this `DefaultDeleter` from the given one\n\t\t/// @ingroup memory\n\t\tconstexpr auto operator=(DefaultDeleter&&) noexcept -> DefaultDeleter& = default;\n\t};\n\n\ttemplate<typename T>\n\trequires concepts::Deletable<T[]> && concepts::NotFunction<T>\n\tstruct DefaultDeleter<T[]> { // NOLINT\n\t\tconstexpr DefaultDeleter() noexcept = default;\n\t\tconstexpr DefaultDeleter(const DefaultDeleter&) noexcept = default;\n\t\tconstexpr DefaultDeleter(DefaultDeleter&&) noexcept = default;\n\t\tconstexpr ~DefaultDeleter() noexcept = default;\n\t\ttemplate<typename U>\n\t\trequires concepts::Convertible<U (*)[], T (*)[]>\t\t\t\t\t\t\t // NOLINT\n\t\texplicit DefaultDeleter([[maybe_unused]] const DefaultDeleter<U[]>& deleter) // NOLINT\n\t\t\tnoexcept {\n\t\t}\n\n\t\tconstexpr auto\n\t\toperator()(gsl::owner<T*> ptr) const noexcept(concepts::NoexceptDeletable<T[]>) // NOLINT\n\t\t{\n\t\t\tdelete[] ptr;\n\t\t}\n\n\t\tconstexpr auto operator=(const DefaultDeleter&) noexcept -> DefaultDeleter& = default;\n\t\tconstexpr auto operator=(DefaultDeleter&&) noexcept -> DefaultDeleter& = default;\n\t};\n\n\t/// @brief `UniquePtr<T, Deleter>` is Hyperion's `constexpr` equivalent to the standard\n\t/// library's `std::unique_ptr<T, Deleter>`\n\t///\n\t/// `UniquePtr<T, Deleter>` is a `constexpr` implementation of a unique owning pointer, with\n\t/// almost complete semantic equivalence with `std::unique_ptr<T, Deleter>`.\n\t/// It is a drop-in replacement in almost all situations(1).\n\t/// Hyperion also provides extended functionality for `UniquePtr<T, Deleter>`\n\t/// over `std::unique_ptr<T, Deleter>`, eg: an allocator-aware factory function set in\n\t/// `allocate_unique`\n\t///\n\t/// @tparam T - The type to store in the `UniquePtr`\n\t/// @tparam Deleter - The deleter type to handle deletion of the stored `T`, by default, this is\n\t/// `hyperion::DefaultDeleter<T>`. This type only needs to be explicitly provided when custom\n\t/// deletion or resource-freeing strategies are required.\n\t///\n\t/// # Requirements\n\t/// - `!std::is_rvalue_reference_v<Deleter>`: `Deleter` cannot be an r-value reference type\n\t///\n\t/// @note(1): The exception is in situations where destructor ordering is required and code was\n\t/// compiled with Clang. `UniquePtr<T, Deleter>` makes use of Clang's `trivial_abi` attribute,\n\t/// which allows `UniquePtr<T, Deleter>` to be passed via register in function calls\n\t/// (and thus removes its overhead compared to a raw pointer), but moves the call to its\n\t/// destructor from the calling code to the callee. The result is that the destructor for\n\t/// `UniquePtr<T, Deleter>` will not nest in the same way as `std::unique_ptr<T, Deleter>`, and\n\t/// code relying on that behavior may experience issues. This is identical behavior to\n\t/// `std::unique_ptr<T, Deleter>` when `_LIBCPP_ABI_ENABLE_UNIQUE_PTR_TRIVIAL_ABI` is defined\n\t/// @ingroup UniquePtr\n\t/// @headerfile \"Hyperion/memory/UniquePtr.h\"\n\ttemplate<typename T, typename Deleter = DefaultDeleter<T>>\n\trequires concepts::NotRValueReference<Deleter>\n\tclass HYPERION_TRIVIAL_ABI UniquePtr {\n\t  public:\n\t\t/// @brief The element type allocated in the `UniquePtr`\n\t\t/// @ingroup UniquePtr\n\t\tusing element_type = T;\n\t\t/// @brief The deleter type used by the `UniquePtr`\n\t\t/// @ingroup UniquePtr\n\t\tusing deleter_type = Deleter;\n\t\t/// @brief The pointer type stored in the `UniquePtr`\n\t\t/// @ingroup UniquePtr\n\t\tusing pointer = T*;\n\t\t/// @brief The pointer type stored in the `UniquePtr`, as a pointer to const\n\t\t/// @ingroup UniquePtr\n\t\tusing pointer_to_const = const T*;\n\n\t\t/// @brief Constructs a default `UniquePtr<T, Deleter>`, managing no pointer\n\t\t///\n\t\t/// # Requirements\n\t\t/// - `concepts::NoexceptDefaultConstructible<deleter_type>`: `deleter_type` must be\n\t\t/// noexcept default constructible in order to default construct a `UniquePtr`\n\t\t/// - `concepts::NotPointer<deleter_type>`: `deleter_type` must not be a pointer\n\t\t/// in order to default construct a `UniquePtr`\n\t\t/// @ingroup UniquePtr\n\t\tconstexpr UniquePtr() noexcept requires concepts::NoexceptDefaultConstructible<\n\t\t\tdeleter_type> && concepts::NotPointer<deleter_type>\n\t\t\t: m_ptr(pointer(), DefaultInitTag<deleter_type>()) {\n\t\t}\n\t\t/// @brief Constructs a `UniquePtr<T, Deleter>` managing no pointer\n\t\t///\n\t\t/// @param ptr - The `nullptr` signaling this `UniquePtr` should manage no pointer\n\t\t///\n\t\t/// # Requirements\n\t\t/// - `concepts::NoexceptDefaultConstructible<deleter_type>`: `deleter_type` must be\n\t\t/// noexcept default constructible in order to construct a `UniquePtr` from only a `nullptr`\n\t\t/// - `concepts::NotPointer<deleter_type>`: `deleter_type` must not be a pointer\n\t\t/// in order to construct a `UniquePtr` from only a `nullptr`\n\t\t/// @ingroup UniquePtr\n\t\tconstexpr UniquePtr(std::nullptr_t ptr) noexcept // NOLINT\n\t\t\trequires concepts::NoexceptDefaultConstructible<deleter_type> && concepts::NotPointer<\n\t\t\t\tdeleter_type> : m_ptr(ptr, DefaultInitTag<deleter_type>()) {\n\t\t}\n\t\t/// @brief Constructs a `UniquePtr<T, Deleter>` managing the given pointer\n\t\t///\n\t\t/// @param ptr - The pointer to manage with this `UniquePtr`\n\t\t///\n\t\t/// # Requirements\n\t\t/// - `concepts::NoexceptDefaultConstructible<deleter_type>`: `deleter_type` must be\n\t\t/// noexcept default constructible in order to construct a `UniquePtr` from only a `pointer`\n\t\t/// - `concepts::NotPointer<deleter_type>`: `deleter_type` must not be a pointer\n\t\t/// in order to construct a `UniquePtr` from only a `pointer`\n\t\t/// @ingroup UniquePtr\n\t\texplicit constexpr UniquePtr(pointer ptr) noexcept requires concepts::\n\t\t\tNoexceptDefaultConstructible<deleter_type> && concepts::NotPointer<deleter_type>\n\t\t\t: m_ptr(ptr, DefaultInitTag<deleter_type>()) {\n\t\t}\n\t\t/// @brief Constructs a `UniquePtr<T, Deleter>` managing the given pointer\n\t\t///\n\t\t/// @tparam U - The type of the pointer to manage in this `UniquePtr`\n\t\t///\n\t\t/// @param ptr - The pointer to manage with this `UniquePtr`\n\t\t///\n\t\t/// # Requirements\n\t\t/// - `concepts::Convertible<U, pointer>`: `U` must be convertible to `pointer` to construct\n\t\t/// a `UniquePtr` from it\n\t\t/// - `concepts::NoexceptDefaultConstructible<deleter_type>`: `deleter_type` must be\n\t\t/// noexcept default constructible in order to construct a `UniquePtr` from only a `pointer`\n\t\t/// - `concepts::NotPointer<deleter_type>`: `deleter_type` must not be a pointer\n\t\t/// in order to construct a `UniquePtr` from only a `pointer`\n\t\t/// @ingroup UniquePtr\n\t\ttemplate<typename U>\n\t\trequires concepts::Convertible<U, pointer> && concepts::NoexceptDefaultConstructible<\n\t\t\tdeleter_type> && concepts::NotPointer<deleter_type>\n\t\texplicit constexpr UniquePtr(U ptr) noexcept : m_ptr(ptr, DefaultInitTag<deleter_type>()) {\n\t\t}\n\t\t/// @brief Constructs a `UniquePtr<T, Deleter>` managing the given pointer\n\t\t///\n\t\t/// @param ptr - The pointer to manage with this `UniquePtr`\n\t\t/// @param deleter - The deleter to delete `ptr` with when the destructor of this\n\t\t/// `UniquePtr` is called\n\t\t///\n\t\t/// @ingroup UniquePtr\n\t\tconstexpr UniquePtr(pointer ptr, const Deleter& deleter) noexcept requires\n\t\t\tconcepts::NoexceptCopyConstructible<Deleter> : m_ptr(ptr, deleter) {\n\t\t}\n\t\t/// @brief Constructs a `UniquePtr<T, Deleter>` managing the given pointer\n\t\t///\n\t\t/// @param ptr - The pointer to manage with this `UniquePtr`\n\t\t/// @param deleter - The deleter to delete `ptr` with when the destructor of this\n\t\t/// `UniquePtr` is called\n\t\t///\n\t\t/// @ingroup UniquePtr\n\t\tconstexpr UniquePtr(pointer ptr, Deleter&& deleter) noexcept requires\n\t\t\tconcepts::NoexceptMoveConstructible<Deleter> && concepts::NotRValueReference<Deleter>\n\t\t\t: m_ptr(ptr, std::move(deleter)) {\n\t\t}\n\t\t/// @brief Constructs a `UniquePtr<T, Deleter>` managing the given pointer\n\t\t///\n\t\t/// @tparam U - The type of the pointer to manage in this `UniquePtr`\n\t\t///\n\t\t/// @param ptr - The pointer to manage with this `UniquePtr`\n\t\t/// @param deleter - The deleter to delete `ptr` with when the destructor of this\n\t\t/// `UniquePtr` is called\n\t\t///\n\t\t/// # Requirements\n\t\t/// - `concepts::Convertible<U, pointer>`: `U` must be convertible to `pointer` to construct\n\t\t/// a `UniquePtr` from it\n\t\t/// @ingroup UniquePtr\n\t\ttemplate<typename U>\n\t\trequires concepts::Convertible<U, pointer> && concepts::NotSame<U, pointer> && concepts::\n\t\t\tNoexceptCopyConstructible<Deleter>\n\t\tconstexpr UniquePtr(U ptr, const Deleter& deleter) noexcept : m_ptr(ptr, deleter) {\n\t\t}\n\t\t/// @brief Constructs a `UniquePtr<T, Deleter>` managing the given pointer\n\t\t///\n\t\t/// @tparam U - The type of the pointer to manage in this `UniquePtr`\n\t\t///\n\t\t/// @param ptr - The pointer to manage with this `UniquePtr`\n\t\t/// @param deleter - The deleter to delete `ptr` with when the destructor of this\n\t\t/// `UniquePtr` is called\n\t\t///\n\t\t/// # Requirements\n\t\t/// - `concepts::Convertible<U, pointer>`: `U` must be convertible to `pointer` to construct\n\t\t/// a `UniquePtr` from it\n\t\t/// @ingroup UniquePtr\n\t\ttemplate<typename U>\n\t\trequires concepts::Convertible<U, pointer> && concepts::NotSame<U, pointer> && concepts::\n\t\t\tNoexceptMoveConstructible<Deleter> && concepts::NotRValueReference<Deleter>\n\t\tconstexpr UniquePtr(U ptr, Deleter&& deleter) noexcept : m_ptr(ptr, std::move(deleter)) {\n\t\t}\n\t\t/// @brief Constructs a `UniquePtr<T, Deleter>` managing no pointer\n\t\t///\n\t\t/// @param ptr - The `nullptr` signaling this `UniquePtr` should manage no pointer\n\t\t/// @param deleter - The deleter to delete a managed pointer with when the destructor of\n\t\t/// this `UniquePtr` is called\n\t\t///\n\t\t/// @ingroup UniquePtr\n\t\tconstexpr UniquePtr(std::nullptr_t ptr, const Deleter& deleter) noexcept requires\n\t\t\tconcepts::NoexceptCopyConstructible<Deleter> : m_ptr(ptr, deleter) {\n\t\t}\n\t\t/// @brief Constructs a `UniquePtr<T, Deleter>` managing no pointer\n\t\t///\n\t\t/// @param ptr - The `nullptr` signaling this `UniquePtr` should manage no pointer\n\t\t/// @param deleter - The deleter to delete a managed pointer with when the destructor of\n\t\t/// this `UniquePtr` is called\n\t\t///\n\t\t/// @ingroup UniquePtr\n\t\tconstexpr UniquePtr(std::nullptr_t ptr, Deleter&& deleter) noexcept requires\n\t\t\tconcepts::NoexceptMoveConstructible<Deleter> && concepts::NotRValueReference<Deleter>\n\t\t\t: m_ptr(ptr, std::move(deleter)) {\n\t\t}\n\t\t/// @brief Constructs a `UniquePtr<T, Deleter>` from the given moved `UniquePtr<U, D>`\n\t\t///\n\t\t/// @param ptr - The `UniquePtr` to construct this one from\n\t\t///\n\t\t/// # Requirements\n\t\t/// - `concepts::NoexceptConstructibleFrom<deleter_type,\n\t\t/// decltype((std::forward<D>(ptr.get_deleter())))`: `deleter_type` must be noexcept\n\t\t/// constructible from the deleter type returned by `ptr.get_deleter()`\n\t\t/// - `concepts::Convertible<typename UniquePtr<U, D>::pointer, pointer>`: The pointer type\n\t\t/// of `UniquePtr<U, D>` must be convertible to `pointer`\n\t\t/// - `concepts::Convertible<typename UniquePtr<U, D>::deleter_type, deleter_type>`: The\n\t\t/// deleter type of `UniquePtr<U, D>` must be convertible to `deleter_type`\n\t\t/// @ingroup UniquePtr\n\t\ttemplate<typename U, typename D>\n\t\texplicit constexpr UniquePtr(UniquePtr<U, D>&& ptr) noexcept requires concepts::\n\t\t\tNoexceptConstructibleFrom<deleter_type,\n\t\t\t\t\t\t\t\t\t  decltype((std::forward<D>(ptr.get_deleter())))> && concepts::\n\t\t\t\tConvertible<typename UniquePtr<U, D>::pointer, pointer> && concepts::\n\t\t\t\t\tConvertible<typename UniquePtr<U, D>::deleter_type, deleter_type>\n\t\t\t: m_ptr(ptr.release(), std::forward<D>(ptr.get_deleter())) {\n\t\t}\n\t\t/// @brief `UniquePtr` cannot be copied\n\t\t/// @ingroup UniquePtr\n\t\tUniquePtr(const UniquePtr&) = delete;\n\t\t/// @brief Move Constructs a `UniquePtr` from the given one\n\t\t///\n\t\t/// @param ptr - The `UniquePtr` to move\n\t\t///\n\t\t/// # Requirements\n\t\t/// - `concepts::NoexceptMoveConstructible<deleter_type>`: `deleter_type` must be noexcept\n\t\t/// move constructible in order to move construct a `UniquePtr`\n\t\t/// @ingroup UniquePtr\n\t\tconstexpr UniquePtr(\n\t\t\tUniquePtr&& ptr) noexcept requires concepts::NoexceptMoveConstructible<deleter_type>\n\t\t\t: m_ptr(ptr.release(), std::forward<deleter_type>(ptr.get_deleter())) {\n\t\t}\n\t\t/// @brief `UniquePtr` destructor\n\t\t///\n\t\t/// # Requirements\n\t\t/// - `noexcept(std::declval<deleter_type>()(std::declval<pointer>()))`: Deleting the\n\t\t/// managed pointer via the associated `deleter_type`'s call operator must be noexcept\n\t\t/// @ingroup UniquePtr\n\t\tconstexpr ~UniquePtr() noexcept\n\t\t\trequires(noexcept(std::declval<deleter_type>()(std::declval<pointer>()))) // NOLINT\n\t\t{\n\t\t\treset();\n\t\t}\n\n\t\t/// @brief Releases ownership of the managed pointer and returns it\n\t\t///\n\t\t/// @return The managed pointer\n\t\t/// @ingroup UniquePtr\n\t\t[[nodiscard]] inline constexpr auto release() noexcept -> pointer {\n\t\t\tauto* ptr = m_ptr.first();\n\t\t\tm_ptr.first() = pointer();\n\t\t\treturn ptr;\n\t\t}\n\n\t\t/// @brief Deletes the currently managed pointer, if any, and begins managing the given one\n\t\t///\n\t\t/// @param ptr - The new pointer to manage with this `UniquePtr`\n\t\t///\n\t\t/// # Requirements\n\t\t/// - `noexcept(std::declval<deleter_type>()(std::declval<pointer>()))`: Deleting the\n\t\t/// managed pointer via the associated `deleter_type`'s call operator must be noexcept\n\t\tinline constexpr auto reset(pointer ptr = pointer()) noexcept -> void requires(\n\t\t\tnoexcept(std::declval<deleter_type>()(std::declval<pointer>()))) // NOLINT\n\t\t{\n\t\t\tgsl::owner<pointer> tmp = m_ptr.first(); // NOLINT\n\t\t\tm_ptr.first() = ptr;\n\t\t\tm_ptr.second()(tmp);\n\t\t}\n\n\t\t/// @brief Deletes the currently managed pointer, if any, and begins managing the given one\n\t\t///\n\t\t/// @tparam U - The type of the new pointer to manage\n\t\t///\n\t\t/// @param ptr - The new pointer to manage with this `UniquePtr`\n\t\t///\n\t\t/// # Requirements\n\t\t/// - `concepts::Convertible<U, pointer>`: `U` must be convertible to `pointer` in order for\n\t\t/// this `UniquePtr` to manage a `U`\n\t\t/// - `noexcept(std::declval<deleter_type>()(std::declval<pointer>()))`: Deleting the\n\t\t/// managed pointer via the associated `deleter_type`'s call operator must be noexcept\n\t\t/// @ingroup UniquePtr\n\t\ttemplate<typename U>\n\t\trequires concepts::Convertible<U, pointer>\n\t\tinline constexpr auto reset(U ptr) noexcept -> void requires(\n\t\t\tnoexcept(std::declval<deleter_type>()(std::declval<pointer>()))) // NOLINT\n\t\t{\n\t\t\tgsl::owner<pointer> tmp = m_ptr.first(); // NOLINT\n\t\t\tm_ptr.first() = ptr;\n\t\t\tm_ptr.second()(tmp);\n\t\t}\n\n\t\t/// @brief Swaps the managed pointer and deleter of this `UniquePtr` with the given one\n\t\t///\n\t\t/// @param ptr - The `UniquePtr` to swap with\n\t\t///\n\t\t/// # Requirements\n\t\t/// - `std::is_nothrow_swappable_v<CompressedPair<pointer, deleter_type>>`:\n\t\t/// `CompressedPair<pointer, deleter_type> must be noexcept swappable in order to\n\t\t/// swap two `UniquePtr`s. (`CompressedPair` is used internally to store the managed pointer\n\t\t/// and deleter, to allow for\n\t\t/// [Empty Base Class Optimization](https://en.cppreference.com/w/cpp/language/ebo) )\n\t\t/// @ingroup UniquePtr\n\t\tinline constexpr auto swap(UniquePtr& ptr) noexcept\n\t\t\t-> void requires concepts::NoexceptSwappable<CompressedPair<pointer, deleter_type>> {\n\t\t\tm_ptr.swap(ptr.m_ptr);\n\t\t}\n\n\t\t/// @brief Returns the managed pointer\n\t\t///\n\t\t/// Returns the managed pointer. This does not release ownership of the pointer, it only\n\t\t/// provides unmanaged access to it. Use of the returned pointer after the lifetime of this\n\t\t/// `UniquePtr` has ended results in undefined behavior.\n\t\t///\n\t\t/// @return The managed pointer\n\t\t/// @ingroup UniquePtr\n\t\t[[nodiscard]] inline constexpr auto get() noexcept -> pointer {\n\t\t\treturn m_ptr.first();\n\t\t}\n\n\t\t/// @brief Returns the managed pointer\n\t\t///\n\t\t/// Returns the managed pointer. This does not release ownership of the pointer, it only\n\t\t/// provides unmanaged access to it. Use of the returned pointer after the lifetime of this\n\t\t/// `UniquePtr` has ended results in undefined behavior.\n\t\t///\n\t\t/// @return The managed pointer\n\t\t/// @ingroup UniquePtr\n\t\t[[nodiscard]] inline constexpr auto get() const noexcept -> pointer_to_const {\n\t\t\treturn m_ptr.first();\n\t\t}\n\n\t\t/// @brief Returns the associated deleter\n\t\t///\n\t\t/// @return The associated deleter\n\t\t/// @ingroup UniquePtr\n\t\t[[nodiscard]] inline constexpr auto get_deleter() const noexcept -> const deleter_type& {\n\t\t\treturn m_ptr.second();\n\t\t}\n\n\t\t/// @brief Returns the associated deleter\n\t\t///\n\t\t/// @return The associated deleter\n\t\t/// @ingroup UniquePtr\n\t\t[[nodiscard]] inline constexpr auto get_deleter() noexcept -> deleter_type& {\n\t\t\treturn m_ptr.second();\n\t\t}\n\n\t\t/// @brief Converts this `UniquePtr` to a `bool`\n\t\t///\n\t\t/// Returns `true` if the managed pointer is not null, `false` otherwise.\n\t\t/// @return this, as a `bool`\n\t\t/// @ingroup UniquePtr\n\t\texplicit constexpr operator bool() const noexcept {\n\t\t\treturn m_ptr.first() != nullptr;\n\t\t}\n\n\t\tconstexpr auto operator*() const -> typename std::add_lvalue_reference_t<T> {\n\t\t\treturn *(m_ptr.first());\n\t\t}\n\n\t\tconstexpr auto operator->() const noexcept -> pointer {\n\t\t\treturn m_ptr.first();\n\t\t}\n\n\t\tinline constexpr auto operator==(const UniquePtr& ptr) const noexcept -> bool {\n\t\t\treturn m_ptr.first() == ptr.first();\n\t\t}\n\n\t\tinline constexpr auto operator==(std::nullptr_t) const noexcept -> bool {\n\t\t\treturn m_ptr.first() == nullptr;\n\t\t}\n\n\t\tauto operator=(const UniquePtr&) -> UniquePtr& = delete;\n\t\t/// @brief Move-assigns this `UniquePtr` from the given one\n\t\t///\n\t\t/// @param ptr - The `UniquePtr` to move into this one\n\t\t///\n\t\t/// # Requirements\n\t\t/// - `concepts::NoexceptMoveAssignable<deleter_type>`: `deleter_type` must be noexcept move\n\t\t/// assignable in order to move assign a `UniquePtr`\n\t\t/// - `noexcept(std::declval<deleter_type>()(std::declval<pointer>()))`: Deleting the\n\t\t/// managed pointer via the associated `deleter_type`'s call operator must be noexcept\n\t\t///\n\t\t/// @return this\n\t\t/// @ingroup UniquePtr\n\t\tconstexpr auto operator=(UniquePtr&& ptr) noexcept\n\t\t\t-> UniquePtr& requires concepts::NoexceptMoveAssignable<deleter_type> &&(\n\t\t\t\tnoexcept(std::declval<deleter_type>()(std::declval<pointer>()))) // NOLINT\n\t\t{\n\t\t\tif(this == &ptr) {\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\treset(ptr.release());\n\t\t\tm_ptr.second() = std::forward<deleter_type>(ptr.get_deleter());\n\n\t\t\treturn *this;\n\t\t}\n\n\t\t/// @brief Move-assigns this `UniquePtr` from the given one\n\t\t///\n\t\t/// @tparam U - The managed type of the given `UniquePtr`\n\t\t/// @tparam D - The deleter type of the given `UniquePtr`\n\t\t///\n\t\t/// @param ptr - The `UniquePtr<U, D>` to move into this one\n\t\t///\n\t\t/// # Requirements\n\t\t/// - `concepts::NoexceptAssignable<deleter_type,\n\t\t/// decltype(std::forward<D>(ptr.get_deleter()))>`: `deleter_type` must be assignable with\n\t\t/// the deleter type returned by `ptr`'s `get_deleter()` member function\n\t\t/// - `concepts::Convertible<typename UniquePtr<U, D>::pointer, pointer>`: The pointer type\n\t\t/// of `ptr` must be convertible to the pointer type of `this` in order to assign from\n\t\t/// it\n\t\t/// - `concepts::Convertible<typename UniquePtr<U, D>::deleter_type, deleter_type>`:\n\t\t/// The deleter type of `ptr` must be convertible to the pointer type of `this` in order to\n\t\t/// assign from it\n\t\t/// - `noexcept(std::declval<deleter_type>()(std::declval<pointer>()))`: Deleting the\n\t\t/// managed pointer via the associated `deleter_type`'s call operator must be noexcept\n\t\t///\n\t\t/// @return this\n\t\t/// @ingroup UniquePtr\n\t\ttemplate<typename U, typename D>\n\t\tconstexpr auto operator=(UniquePtr<U, D>&& ptr) noexcept -> UniquePtr& requires\n\t\t\tconcepts::NoexceptAssignable<deleter_type,\n\t\t\t\t\t\t\t\t\t\t decltype(std::forward<D>(ptr.get_deleter()))> && concepts::\n\t\t\t\tConvertible<typename UniquePtr<U, D>::pointer, pointer> && concepts::\n\t\t\t\t\tConvertible<typename UniquePtr<U, D>::deleter_type, deleter_type> &&(\n\t\t\t\t\t\tnoexcept(std::declval<deleter_type>()(std::declval<pointer>()))) // NOLINT\n\t\t{\n\t\t\treset(ptr.release());\n\t\t\tm_ptr.second() = std::forward<D>(ptr.get_deleter());\n\t\t\treturn *this;\n\t\t}\n\n\t\t/// @brief Assigns this `UniquePtr` with `nullptr`\n\t\t///\n\t\t/// Calls the deleter on the managed pointer and replaces it with `nullptr`\n\t\t///\n\t\t/// # Requirements\n\t\t/// - `noexcept(std::declval<deleter_type>()(std::declval<pointer>()))`: Deleting the\n\t\t/// managed pointer via the associated `deleter_type`'s call operator must be noexcept\n\t\t///\n\t\t/// @return this\n\t\t/// @ingroup UniquePtr\n\t\tconstexpr auto operator=(std::nullptr_t) noexcept -> UniquePtr& requires(\n\t\t\tnoexcept(std::declval<deleter_type>()(std::declval<pointer>()))) // NOLINT\n\t\t{\n\t\t\treset();\n\t\t\treturn *this;\n\t\t}\n\n\t\t/// @brief Assigns this `UniquePtr` with `ptr`\n\t\t///\n\t\t/// Calls the deleter on the managed pointer and replaces it with `ptr`\n\t\t///\n\t\t/// # Requirements\n\t\t/// - `noexcept(std::declval<deleter_type>()(std::declval<pointer>()))`: Deleting the\n\t\t/// managed pointer via the associated `deleter_type`'s call operator must be noexcept\n\t\t///\n\t\t/// @return this\n\t\t/// @ingroup UniquePtr\n\t\tconstexpr auto operator=(pointer ptr) noexcept -> UniquePtr& requires(\n\t\t\tnoexcept(std::declval<deleter_type>()(std::declval<pointer>()))) // NOLINT\n\t\t{\n\t\t\treset(ptr);\n\t\t\treturn *this;\n\t\t}\n\n\t\t// clang-format off\n\t  private:\n\t\ttemplate<typename T_, typename Deleter_>\n\t\tusing CompressedPair = CompressedPair<T_, Deleter_>;\n\t\ttemplate<typename T_>\n\t\tusing DefaultInitTag = DefaultInitTag<T_>;\n\n\t\tCompressedPair<pointer, deleter_type> m_ptr;\n\t\t// clang-format on\n\t};\n\n\ttemplate<typename T, typename Deleter>\n\trequires concepts::NotRValueReference<Deleter>\n\tclass HYPERION_TRIVIAL_ABI UniquePtr<T[], Deleter> { // NOLINT\n\t  public:\n\t\tusing element_type = T;\n\t\tusing deleter_type = Deleter;\n\t\tusing pointer = std::add_pointer_t<element_type>;\n\t\tusing pointer_to_const = std::add_pointer_t<std::add_const_t<element_type>>;\n\n\t\tconstexpr UniquePtr() noexcept requires concepts::NoexceptDefaultConstructible<\n\t\t\tdeleter_type> && concepts::NotPointer<deleter_type>\n\t\t\t: m_ptr(pointer(), DefaultInitTag<deleter_type>()) {\n\t\t}\n\n\t\tconstexpr UniquePtr(std::nullptr_t ptr) noexcept // NOLINT\n\t\t\trequires concepts::NoexceptDefaultConstructible<deleter_type> && concepts::NotPointer<\n\t\t\t\tdeleter_type> : m_ptr(ptr, DefaultInitTag<deleter_type>()) {\n\t\t}\n\t\texplicit constexpr UniquePtr(pointer ptr) noexcept requires concepts::\n\t\t\tNoexceptDefaultConstructible<deleter_type> && concepts::NotPointer<deleter_type>\n\t\t\t: m_ptr(ptr, DefaultInitTag<deleter_type>()) {\n\t\t}\n\t\ttemplate<typename U>\n\t\trequires concepts::Convertible<U, pointer> && concepts::NoexceptDefaultConstructible<\n\t\t\tdeleter_type> && concepts::NotPointer<deleter_type> && concepts::NotSame<U, pointer>\n\t\texplicit constexpr UniquePtr(U ptr) noexcept : m_ptr(ptr, DefaultInitTag<deleter_type>()) {\n\t\t}\n\t\tconstexpr UniquePtr(pointer ptr, const Deleter& deleter) noexcept requires\n\t\t\tconcepts::NoexceptCopyConstructible<Deleter> : m_ptr(ptr, deleter) {\n\t\t}\n\t\tconstexpr UniquePtr(pointer ptr, Deleter&& deleter) noexcept requires\n\t\t\tconcepts::NoexceptMoveConstructible<Deleter> && concepts::NotRValueReference<Deleter>\n\t\t\t: m_ptr(ptr, std::move(deleter)) {\n\t\t}\n\t\ttemplate<typename U>\n\t\trequires concepts::Convertible<U, pointer> && concepts::NotSame<U, pointer> && concepts::\n\t\t\tNoexceptCopyConstructible<Deleter>\n\t\tconstexpr UniquePtr(U ptr, const Deleter& deleter) noexcept : m_ptr(ptr, deleter) {\n\t\t}\n\t\ttemplate<typename U>\n\t\trequires concepts::Convertible<U, pointer> && concepts::NotSame<U, pointer> && concepts::\n\t\t\tNoexceptMoveConstructible<Deleter> && concepts::NotRValueReference<Deleter>\n\t\tconstexpr UniquePtr(U ptr, Deleter&& deleter) noexcept : m_ptr(ptr, std::move(deleter)) {\n\t\t}\n\t\tconstexpr UniquePtr(std::nullptr_t ptr, const Deleter& deleter) noexcept requires\n\t\t\tconcepts::NoexceptCopyConstructible<Deleter> : m_ptr(ptr, deleter) {\n\t\t}\n\t\tconstexpr UniquePtr(std::nullptr_t ptr, Deleter&& deleter) noexcept requires\n\t\t\tconcepts::NoexceptMoveConstructible<Deleter> && concepts::NotRValueReference<Deleter>\n\t\t\t: m_ptr(ptr, std::move(deleter)) {\n\t\t}\n\t\t// clang-format off\n\t\ttemplate<typename U, typename D>\n\t\trequires std::is_array_v<U>\n\t\texplicit constexpr UniquePtr(UniquePtr<U, D>&& ptr)\n\t\t\tnoexcept(concepts::NoexceptConstructibleFrom<deleter_type,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t decltype((std::forward<D>(ptr.get_deleter())))>)\n\t\t\trequires concepts::Convertible<typename UniquePtr<U, D>::element_type(*)[], // NOLINT\n\t\t\t\t\t\t\t\t\t\t   element_type (*)[] > \t\t\t\t\t\t// NOLINT\n\t\t\t\t\t && concepts::Convertible<typename UniquePtr<U, D>::deleter_type, deleter_type>\n\t\t\t: m_ptr(ptr.release(), std::forward<D>(ptr.get_deleter())) {\n\t\t}\n\t\t// clang-format on\n\t\tUniquePtr(const UniquePtr&) = delete;\n\t\tconstexpr UniquePtr(\n\t\t\tUniquePtr&& ptr) noexcept requires concepts::NoexceptMoveConstructible<deleter_type>\n\t\t\t: m_ptr(ptr.release(), std::forward<deleter_type>(ptr.get_deleter())) {\n\t\t}\n\t\tconstexpr ~UniquePtr() noexcept\n\t\t\trequires(noexcept(std::declval<deleter_type>()(std::declval<pointer>()))) // NOLINT\n\t\t{\n\t\t\treset();\n\t\t}\n\n\t\t[[nodiscard]] inline constexpr auto release() noexcept -> pointer {\n\t\t\tauto* ptr = m_ptr.first();\n\t\t\tm_ptr.first() = pointer();\n\t\t\treturn ptr;\n\t\t}\n\n\t\tinline constexpr auto reset(pointer ptr = pointer()) noexcept -> void requires(\n\t\t\tnoexcept(std::declval<deleter_type>()(std::declval<pointer>()))) // NOLINT\n\t\t{\n\t\t\tgsl::owner<pointer> tmp = m_ptr.first(); // NOLINT\n\t\t\tm_ptr.first() = ptr;\n\t\t\tm_ptr.second()(tmp);\n\t\t}\n\n\t\ttemplate<typename U>\n\t\trequires concepts::Convertible<U, pointer>\n\t\tinline constexpr auto reset(U ptr) noexcept -> void requires(\n\t\t\tnoexcept(std::declval<deleter_type>()(std::declval<pointer>()))) // NOLINT\n\t\t{\n\t\t\tgsl::owner<pointer> tmp = m_ptr.first(); // NOLINT\n\t\t\tm_ptr.first() = ptr;\n\t\t\tm_ptr.second()(tmp);\n\t\t}\n\n\t\tinline constexpr auto swap(UniquePtr& ptr) noexcept\n\t\t\t-> void requires concepts::NoexceptSwappable<CompressedPair<pointer, deleter_type>> {\n\t\t\tm_ptr.swap(ptr.m_ptr);\n\t\t}\n\n\t\t[[nodiscard]] inline constexpr auto get() noexcept -> pointer {\n\t\t\treturn m_ptr.first();\n\t\t}\n\n\t\t[[nodiscard]] inline constexpr auto get() const noexcept -> pointer_to_const {\n\t\t\treturn m_ptr.first();\n\t\t}\n\n\t\t[[nodiscard]] inline constexpr auto get_deleter() const noexcept -> const deleter_type& {\n\t\t\treturn m_ptr.second();\n\t\t}\n\n\t\t[[nodiscard]] inline constexpr auto get_deleter() noexcept -> deleter_type& {\n\t\t\treturn m_ptr.second();\n\t\t}\n\n\t\texplicit constexpr operator bool() const noexcept {\n\t\t\treturn m_ptr.first() != nullptr;\n\t\t}\n\n\t\tinline constexpr auto operator==(const UniquePtr& ptr) const noexcept -> bool {\n\t\t\treturn m_ptr.first() == ptr.first();\n\t\t}\n\n\t\tinline constexpr auto operator==(std::nullptr_t) const noexcept -> bool {\n\t\t\treturn m_ptr.first() == nullptr;\n\t\t}\n\n\t\t// constexpr inline auto operator[](concepts::Integral auto i) const\n\t\t//\tnoexcept -> std::add_const_t<std::add_lvalue_reference_t<element_type>> {\n\t\t//\treturn m_ptr.first()[i];\n\t\t// }\n\n\t\tinline constexpr auto operator[](concepts::Integral auto index) const noexcept\n\t\t\t-> std::add_lvalue_reference_t<element_type> {\n\t\t\treturn m_ptr.first()[index];\n\t\t}\n\n\t\tauto operator=(const UniquePtr&) -> UniquePtr& = delete;\n\t\tconstexpr auto operator=(UniquePtr&& ptr) noexcept\n\t\t\t-> UniquePtr& requires concepts::NoexceptMoveAssignable<deleter_type> &&(\n\t\t\t\tnoexcept(std::declval<deleter_type>()(std::declval<pointer>()))) // NOLINT\n\t\t{\n\t\t\tif(this == &ptr) {\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\treset(ptr.release());\n\t\t\tm_ptr.second() = std::forward<deleter_type>(ptr.get_deleter());\n\n\t\t\treturn *this;\n\t\t}\n\t\t// clang-format off\n\n\t\ttemplate<typename U, typename D>\n\t\trequires std::is_array_v<U>\n\t\tconstexpr auto operator=(UniquePtr<U, D>&& ptr) noexcept -> UniquePtr&\n\t\t\trequires concepts::NoexceptAssignable<deleter_type,\n\t\t\t\t\t\t\t\t\t\t\t\t  decltype(std::forward<D>(ptr.get_deleter()))>\n\t\t\t\t\t && concepts::Convertible<typename UniquePtr<U, D>::element_type(*)\t[], // NOLINT\n\t\t\t\t\t\t\t\t\t\t   \t  element_type(*)[]> \t\t\t\t\t\t\t// NOLINT\n\t\t\t\t\t && concepts::Convertible<typename UniquePtr<U, D>::deleter_type, deleter_type>\n\t\t\t\t\t && (noexcept(std::declval<deleter_type>()(std::declval<pointer>()))) // NOLINT\n\t\t{\n\t\t\treset(ptr.release());\n\t\t\tm_ptr.second() = std::forward<D>(ptr.get_deleter());\n\t\t\treturn *this;\n\t\t}\n\t\t// clang-format on\n\n\t\tconstexpr auto operator=(std::nullptr_t) noexcept -> UniquePtr& requires(\n\t\t\tnoexcept(std::declval<deleter_type>()(std::declval<pointer>()))) // NOLINT\n\t\t{\n\t\t\treset();\n\t\t\treturn *this;\n\t\t}\n\n\t\tconstexpr auto operator=(pointer ptr) noexcept -> UniquePtr& requires(\n\t\t\tnoexcept(std::declval<deleter_type>()(std::declval<pointer>()))) // NOLINT\n\t\t{\n\t\t\treset(ptr);\n\t\t\treturn *this;\n\t\t}\n\n\t\t// clang-format off\n\t  private:\n\t\ttemplate<typename T_, typename Deleter_>\n\t\tusing CompressedPair = CompressedPair<T_, Deleter_>;\n\t\ttemplate<typename T_>\n\t\tusing DefaultInitTag = DefaultInitTag<T_>;\n\n\t\tCompressedPair<pointer, deleter_type> m_ptr;\n\t\t// clang-format on\n\t};\n\ttemplate<typename T, typename Deleter>\n\tUniquePtr(T*, Deleter) -> UniquePtr<T, Deleter>;\n\n\t/// @brief Swaps the managed pointer and deleter of the two `UniquePtr`s\n\t///\n\t/// @tparam T - The type held by the `UniquePtr`s\n\t/// @tparam Deleter - The deleter type used by the `UniquePtr`s\n\t///\n\t/// @param first - The `UniquePtr` to swap to\n\t/// @param second - The `UniquePtr` to swap from\n\t/// @ingroup UniquePtr\n\ttemplate<typename T, typename Deleter>\n\trequires concepts::Swappable<Deleter>\n\tinline constexpr auto\n\tswap(UniquePtr<T, Deleter>& first, UniquePtr<T, Deleter>& second) noexcept -> void {\n\t\tfirst.swap(second);\n\t}\n\t// clang-format off\n\n\tIGNORE_UNUSED_TEMPLATES_START\n\n\t/// @brief Constructs a `UniquePtr<T, Deleter>` from the given arguments\n\t///\n\t/// Constructs a `UniquePtr<T, Deleter>` from the given arguments, passing them directly\n\t/// to `T`'s constructor\n\t///\n\t/// @tparam T - The type to hold in the `UniquePtr`\n\t/// @tparam Deleter - The deleter type to free the resources associated with `T`\n\t/// @tparam Args - The types of the arguments to pass to `T`'s constructor\n\t///\n\t/// @param args - The arguments to pass to `T`'s constructor\n\t///\n\t/// # Requirements\n\t/// - `concepts::ConstructibleFrom<T, Args...>`: `T` must be constructible from the given\n\t/// arguments in order to make a `UniquePtr` from them\n\t/// - `!std::is_array_v<T>`: Cannot make a `UniquePtr` holding an array type from a set of\n\t/// constructor arguments. Use the overload for arrays to make a `UniquePtr<T[]>`.\n\t///\n\t/// @return a `UniquePtr<T, Deleter>` with the `T` constructed from the given arguments\n\t/// @ingroup UniquePtr\n\ttemplate<typename T, typename Deleter = DefaultDeleter<T>, typename... Args>\n\trequires concepts::ConstructibleFrom<T, Args...> && (!std::is_unbounded_array_v<T>)\n\tinline static constexpr auto make_unique(Args&&... args)\n\t\tnoexcept(concepts::NoexceptConstructibleFrom<T, Args...>)\n\t\t-> UniquePtr<T, Deleter>\n\t{\n\t\t// NOLINTNEXTLINE(modernize-use-auto,hicpp-use-auto,bugprone-unhandled-exception-at-new)\n\t\tgsl::owner<T*> ptr = new T(std::forward<Args>(args)...);\n\t\t// NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks)\n\t\treturn UniquePtr<T, Deleter>(ptr);\n\t}\n\t// clang-format on\n\n\t/// @brief Constructs a `UniquePtr` holding array type `T` of size `N`\n\t///\n\t/// Constructs a `UniquePtr<T, Deleter>`, where `T` is an unbounded array type with initial\n\t/// size of `N`.\n\t///\n\t/// @tparam T - The array type to hold in the `UniquePtr`\n\t/// @tparam Deleter - The deleter type to free the resources associated with `T`\n\t/// @tparam ElementType - The element type of the array\n\t///\n\t/// @param N - The initial size of the array managed by the `UniquePtr`\n\t///\n\t/// # Requirements\n\t/// - `std::is_unbounded_array_v<T>`: `T` must be an unbounded array type to make a `UniquePtr`\n\t/// managing an array.\n\t///\n\t/// @return a `UniquePtr<T, Deleter>` managing an array of `N` `ElementType`s\n\t/// @note The array managed by the returned `UniquePtr` will be uninitialized, and thus each\n\t/// element must be appropriately initialized before use. Otherwise, the result is undefined\n\t/// behavior.\n\t/// @ingroup UniquePtr\n\ttemplate<typename T,\n\t\t\t typename Deleter = DefaultDeleter<T>,\n\t\t\t typename ElementType = std::remove_extent_t<T>> // NOLINT\n\trequires std::is_unbounded_array_v<T>\n\tinline static constexpr auto make_unique(usize N) noexcept -> UniquePtr<T, Deleter> {\n\t\t// NOLINTNEXTLINE(modernize-use-auto,hicpp-use-auto,bugprone-unhandled-exception-at-new)\n\t\tgsl::owner<ElementType*> ptr = new ElementType[N];\n\t\t// NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks)\n\t\treturn UniquePtr<T, Deleter>(ptr);\n\t}\n\tIGNORE_UNUSED_TEMPLATES_STOP\n\n\tIGNORE_PADDING_START\n\t/// @brief An allocator-aware deleter type for Hyperion smart pointers\n\t///\n\t/// `AllocatorAwareDeleter` is useful for using smart pointers in situations that require custom\n\t/// allocation strategies. It allows use of smart pointers in an allocator-aware fashion.\n\t///\n\t/// @tparam T - The type to manage deletion for\n\t/// @tparam Allocator - The allocator type allocation was performed with\n\t/// @tparam ElementType - The element type of the managed deletion, in the case that `T` is an\n\t/// array\n\t///\n\t/// # Requirements\n\t/// - `concepts::Allocatable<ElementType, Allocator>`: `AllocatorAwareDeleter` can't be\n\t/// instantiated for an `ElementType`-`Allocator` pair where the element type `ElementType`\n\t/// isn't allocatable by the associated allocator type, `Allocator`\n\t/// @note In the case that `T` is an array type, `AllocatorAwareDeleter` requires that the\n\t/// managed array is fully-initialized and the same size as when the `AllocatorAwareDeleter`\n\t/// was constructed with it (by a call to one of the factory functions, `allocate_unique`, or\n\t/// `allocate_shared`) when its call operator is used to free the resources associated with the\n\t/// array.\n\t/// @note If `T` is an array type and the array is resized, the deleter associated with it in\n\t/// the owning smart pointer must be set to a new one to match the changed state.\n\t/// @note If `T` is an array type and the members of the array are not all initialized when the\n\t/// call operator of this deleter is used to free the resources associated with it, the result\n\t/// is undefined behavior.\n\t/// @ingroup memory\n\ttemplate<typename T,\n\t\t\t typename Allocator = std::allocator<T>,\n\t\t\t typename ElementType = std::remove_cv_t<std::remove_all_extents_t<T>>>\n\trequires concepts::Allocatable<ElementType, Allocator>\n\tclass AllocatorAwareDeleter {\n\t  public:\n\t\t/// @brief The rebound allocator type for this deleter\n\t\t/// @ingroup memory\n\t\tusing Alloc = typename std::allocator_traits<Allocator>::template rebind_alloc<ElementType>;\n\t\t/// @brief The `std::allocator_traits` type for this deleter\n\t\t/// @ingroup memory\n\t\tusing Traits = std::allocator_traits<Alloc>;\n\t\t/// @brief The pointer type for the associated allocator traits for this deleter\n\t\t/// @ingroup memory\n\t\tusing pointer = typename Traits::pointer;\n\n\t\t/// @brief Default-Constructs an `AllocatorAwareDeleter`\n\t\t///\n\t\t/// # Requirements\n\t\t/// - `concepts::NoexceptDefaultConstructible<Alloc>`: The associated allocator type must be\n\t\t/// noexcept default constructible in order to construct an `AllocatorAwareDeleter` with one\n\t\t/// @ingroup memory\n\t\tconstexpr AllocatorAwareDeleter() noexcept requires\n\t\t\tconcepts::NoexceptDefaultConstructible<Alloc> : m_allocator() {\n\t\t}\n\t\t/// @brief Constructs an `AllocatorAwareDeleter` from the given allocator\n\t\t///\n\t\t/// @param alloc - The allocator to construct the allocator associated with this from\n\t\t///\n\t\t/// # Requirements\n\t\t/// - `concepts::NoexceptConstructibleFrom<Alloc, decltype(alloc)>`: The associated\n\t\t/// allocator type must be noexcept constructible from the given allocator in order to\n\t\t/// construct an `AllocatorAwareDeleter` from it\n\t\t/// @ingroup memory\n\t\texplicit constexpr AllocatorAwareDeleter(const Allocator& alloc) noexcept requires\n\t\t\tconcepts::NoexceptConstructibleFrom<Alloc, decltype(alloc)> : m_allocator(alloc) {\n\t\t}\n\t\t/// @brief Copy-Constructs an `AllocatorAwareDeleter` from the given one\n\t\t///\n\t\t/// # Requirements\n\t\t/// - `concepts::NoexceptCopyConstructible<Alloc>`: The associated allocator type must be\n\t\t/// noexcept copy constructible in order to copy construct an `AllocatorAwareDeleter`\n\t\t/// @ingroup memory\n\t\tconstexpr AllocatorAwareDeleter(const AllocatorAwareDeleter&) noexcept requires\n\t\t\tconcepts::NoexceptCopyConstructible<Alloc>\n\t\t= default;\n\t\t/// @brief Move-Constructs an `AllocatorAwareDeleter` from the given one\n\t\t///\n\t\t/// # Requirements\n\t\t/// - `concepts::NoexceptMoveConstructible<Alloc>`: The associated allocator type must be\n\t\t/// noexcept move constructible in order to copy construct an `AllocatorAwareDeleter`\n\t\t/// @ingroup memory\n\t\tconstexpr AllocatorAwareDeleter(\n\t\t\tAllocatorAwareDeleter&&) noexcept requires concepts::NoexceptMoveConstructible<Alloc>\n\t\t= default;\n\n\t\t/// @brief Destructs this `AllocatorAwareDeleter`\n\t\t/// @ingroup memory\n\t\tconstexpr ~AllocatorAwareDeleter() noexcept = default;\n\n\t\t/// @brief Frees the resources associated with the pointed-to object\n\t\t///\n\t\t/// @param p - Pointer to the object to free associated resources of\n\t\t/// @ingroup memory\n\t\tinline constexpr auto operator()(pointer p) const noexcept {\n\t\t\tAlloc allocator = m_allocator;\n\n\t\t\tTraits::destroy(allocator, std::addressof(*p));\n\n\t\t\tTraits::deallocate(allocator, p, 1);\n\t\t}\n\n\t\t/// @brief Copy-Assigns this `AllocatorAwareDeleter` from the given one\n\t\t///\n\t\t/// # Requirements\n\t\t/// - `concepts::NoexceptCopyAssignable<Alloc>`: The associated allocator type must be\n\t\t/// noexcept copy assignable in order to copy assign this `AllocatorAwareDeleter`\n\t\t/// @ingroup memory\n\t\tconstexpr auto operator=(const AllocatorAwareDeleter&) noexcept\n\t\t\t-> AllocatorAwareDeleter& requires concepts::NoexceptCopyAssignable<Alloc>\n\t\t= default;\n\t\t/// @brief Move-Assigns this `AllocatorAwareDeleter` from the given one\n\t\t///\n\t\t/// # Requirements\n\t\t/// - `concepts::NoexceptMoveAssignable<Alloc>`: The associated allocator type must be\n\t\t/// noexcept move assignable in order to move assign this `AllocatorAwareDeleter`\n\t\t/// @ingroup memory\n\t\tconstexpr auto operator=(AllocatorAwareDeleter&&) noexcept\n\t\t\t-> AllocatorAwareDeleter& requires concepts::NoexceptMoveAssignable<Alloc>\n\t\t= default;\n\n\t  private:\n\t\tAlloc m_allocator;\n\t};\n\n\ttemplate<typename T, typename Allocator, typename ElementType>\n\trequires concepts::Allocatable<ElementType, Allocator>\n\tclass AllocatorAwareDeleter<T[], Allocator, ElementType> { // NOLINT\n\t  public:\n\t\tusing Alloc = typename std::allocator_traits<Allocator>::template rebind_alloc<ElementType>;\n\t\tusing Traits = std::allocator_traits<Alloc>;\n\t\tusing pointer = typename Traits::pointer;\n\n\t\tconstexpr AllocatorAwareDeleter() noexcept requires\n\t\t\tconcepts::NoexceptDefaultConstructible<Alloc> : m_allocator() {\n\t\t}\n\t\texplicit constexpr AllocatorAwareDeleter(const Allocator& alloc,\n\t\t\t\t\t\t\t\t\t\t\t\t usize num_elements) noexcept requires\n\t\t\tconcepts::NoexceptConstructibleFrom<Alloc, decltype(alloc)>\n\t\t\t: m_allocator(alloc),\n\t\t\t  m_num_elements(num_elements) {\n\t\t}\n\t\tconstexpr AllocatorAwareDeleter(const AllocatorAwareDeleter&) noexcept requires\n\t\t\tconcepts::NoexceptCopyConstructible<Alloc>\n\t\t= default;\n\t\tconstexpr AllocatorAwareDeleter(\n\t\t\tAllocatorAwareDeleter&&) noexcept requires concepts::NoexceptMoveConstructible<Alloc>\n\t\t= default;\n\t\tconstexpr ~AllocatorAwareDeleter() noexcept = default;\n\n\t\tinline constexpr auto operator()(pointer p) const noexcept {\n\t\t\tAlloc allocator = m_allocator;\n\n\t\t\tauto i = m_num_elements >= 1_usize ? m_num_elements - 1_usize : 0_usize;\n\t\t\t// we need to use do-while to ensure we destroy the 0th element\n\t\t\t// in a 1 element array\n\t\t\tdo {\n\t\t\t\tTraits::destroy(allocator, std::addressof(*p) + i); // NOLINT\n\t\t\t\t--i;\n\t\t\t} while(i != 0_usize);\n\n\t\t\tTraits::deallocate(allocator, p, m_num_elements);\n\t\t}\n\n\t\tconstexpr auto operator=(const AllocatorAwareDeleter&) noexcept\n\t\t\t-> AllocatorAwareDeleter& requires concepts::NoexceptCopyAssignable<Alloc>\n\t\t= default;\n\t\tconstexpr auto operator=(AllocatorAwareDeleter&&) noexcept\n\t\t\t-> AllocatorAwareDeleter& requires concepts::NoexceptMoveAssignable<Alloc>\n\t\t= default;\n\n\t  private:\n\t\tAlloc m_allocator;\n\t\tusize m_num_elements = 1_usize;\n\t};\n\tIGNORE_PADDING_STOP\n\n\t/// @brief Constructs an allocator-aware `UniquePtr`\n\t///\n\t/// Constructs a `UniquePtr<T, AllocatorAwareDeleter<T, Alloc>>`. The managed `T` will be\n\t/// constructed from the given arguments, `args`, passing them directly to `T`'s constructor.\n\t/// Allocation of the managed `T` will be performed by the given allocator.\n\t///\n\t/// @tparam T - The type to manage in the `UniquePtr`\n\t/// @tparam Allocator - The type of the allocator to use for allocation and deletion of the `T`\n\t/// @tparam ElementType - The element type of the array, in the case that `T` is an unbounded\n\t/// array type\n\t/// @tparam Alloc - The allocator type `Allocator` rebound to the element type, `ElementType`\n\t///\n\t/// @param alloc - The allocator to perform allocation and deallocation with\n\t/// @param args - The arguments to pass to `T`'s constructor\n\t///\n\t/// # Requirements\n\t/// - `concepts::NoexceptConstructibleFrom<ElementType, Args...>`: `ElementType` must be\n\t/// noexcept constructible from `args` in order to make a `UniquePtr` from them\n\t/// - `concepts::Allocatable<ElementType, Alloc>`: `AllocatorAwareDeleter` can't be\n\t/// instantiated for an `ElementType`-`Alloc` pair where the element type `ElementType`\n\t/// isn't allocatable by the associated allocator type, `Alloc`\n\t/// - `!std::is_array_v<T>`: Cannot make a `UniquePtr` holding an array type from a set of\n\t/// constructor arguments. Use the overload for arrays to make a `UniquePtr<T[]>`.\n\t/// - `concepts::NoexceptConstructibleFrom<Alloc, decltype(alloc)>`: The associated allocator\n\t/// type, `Alloc`, must be noexcept constructible from the given allocator in order to create\n\t/// a `UniquePtr` using it\n\t/// @ingroup UniquePtr\n\ttemplate<typename T,\n\t\t\t typename Allocator = std::allocator<T>,\n\t\t\t typename ElementType = std::remove_cv_t<std::remove_all_extents_t<T>>,\n\t\t\t typename Alloc =\n\t\t\t\t typename std::allocator_traits<Allocator>::template rebind_alloc<ElementType>,\n\t\t\t typename... Args>\n\trequires concepts::NoexceptConstructibleFrom<ElementType, Args...> && concepts::\n\t\tAllocatable<ElementType, Alloc> &&(!std::is_unbounded_array_v<T>)\n\t\t\t[[nodiscard]] inline constexpr auto allocate_unique(const Allocator& alloc,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tArgs&&... args) noexcept\n\t\t-> UniquePtr<T, AllocatorAwareDeleter<T, Alloc>>\n\trequires concepts::NoexceptConstructibleFrom<Alloc, decltype(alloc)> {\n\t\tusing Traits = std::allocator_traits<Alloc>;\n\t\tusing Deleter = AllocatorAwareDeleter<T, Alloc>;\n\n\t\tAlloc allocator(alloc);\n\t\tauto* p = Traits::allocate(allocator, 1);\n\t\tTraits::construct(allocator, std::addressof(*p), std::forward<Args>(args)...);\n\n\t\t// NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks)\n\t\treturn UniquePtr<T, Deleter>(p, Deleter(allocator));\n\t}\n\n\t/// @brief Constructs an allocator-aware `UniquePtr`\n\t///\n\t/// Constructs a `UniquePtr<T, AllocatorAwareDeleter<T, Alloc>>`, where `T` is an unbounded\n\t/// array type. The managed array will have its elements default constructed in place.\n\t/// Allocation of the managed array will be performed by the given allocator.\n\t///\n\t/// @tparam T - The type to manage in the `UniquePtr`\n\t/// @tparam Allocator - The type of the allocator to use for allocation and deletion of the `T`\n\t/// @tparam ElementType - The element type of the array, in the case that `T` is an unbounded\n\t/// array type\n\t/// @tparam Alloc - The allocator type `Allocator` rebound to the element type, `ElementType`\n\t///\n\t/// @param alloc - The allocator to perform allocation and deallocation with\n\t/// @param N - The number of elements to allocate in the array\n\t///\n\t/// # Requirements\n\t/// - `concepts::NoexceptDefaultConstructible<ElementType>`: `ElementType` must be\n\t/// noexcept default-constructible in order to make a `UniquePtr` managing an array of them\n\t/// - `concepts::Allocatable<ElementType, Alloc>`: `AllocatorAwareDeleter` can't be\n\t/// instantiated for an `ElementType`-`Alloc` pair where the element type `ElementType`\n\t/// isn't allocatable by the associated allocator type, `Alloc`\n\t/// - `std::is_unbounded_array_v<T>`: `T` must be an unbounded array type to make a `UniquePtr`\n\t/// managing an array.\n\t/// - `concepts::NoexceptConstructibleFrom<Alloc, decltype(alloc)>`: The associated allocator\n\t/// type, `Alloc`, must be noexcept constructible from the given allocator in order to create\n\t/// a `UniquePtr` using it\n\t/// @ingroup UniquePtr\n\ttemplate<typename T,\n\t\t\t typename Allocator = std::allocator<T>,\n\t\t\t typename ElementType = std::remove_cv_t<std::remove_all_extents_t<T>>,\n\t\t\t typename Alloc =\n\t\t\t\t typename std::allocator_traits<Allocator>::template rebind_alloc<ElementType>>\n\trequires concepts::NoexceptDefaultConstructible<\n\t\tElementType> && concepts::Allocatable<ElementType, Alloc> && std::is_unbounded_array_v<T>\n\t[[nodiscard]] inline constexpr auto allocate_unique(const Allocator& alloc, usize N) noexcept\n\t\t-> UniquePtr<T, AllocatorAwareDeleter<T, Alloc>>\n\trequires concepts::NoexceptConstructibleFrom<Alloc, decltype(alloc)> {\n\t\tusing Traits = std::allocator_traits<Alloc>;\n\t\tusing Deleter = AllocatorAwareDeleter<ElementType[], Alloc>; // NOLINT (c arrays)\n\n\t\tAlloc allocator(alloc);\n\t\tauto* p = Traits::allocate(allocator, N);\n\t\t// we need to use do-while to make sure we construct the 0th element in a one element array\n\t\tauto i = 0_usize;\n\t\tdo {\n\t\t\tTraits::construct(allocator, std::addressof(*p) + i); // NOLINT\n\t\t\t++i;\n\t\t} while(i < N);\n\n\t\t// NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks)\n\t\treturn UniquePtr<ElementType[], Deleter>(p, Deleter(allocator, N)); // NOLINT ( c arrays)\n\t}\n\n\t/// @brief Constructs an allocator-aware `UniquePtr`\n\t///\n\t/// Constructs a `UniquePtr<T, AllocatorAwareDeleter<T, Alloc>>`, where `T` is an unbounded\n\t/// array type. The managed array will have its elements default constructed in place.\n\t/// Allocation of the managed array will be performed by the given allocator.\n\t///\n\t/// @tparam T - The type to manage in the `UniquePtr`\n\t/// @tparam Allocator - The type of the allocator to use for allocation and deletion of the `T`\n\t/// @tparam ElementType - The element type of the array, in the case that `T` is an unbounded\n\t/// array type\n\t/// @tparam Alloc - The allocator type `Allocator` rebound to the element type, `ElementType`\n\t/// @tparam Args - The types of the arguments to use to default-construct the elements of the\n\t/// array\n\t///\n\t/// @param alloc - The allocator to perform allocation and deallocation with\n\t/// @param N - The number of elements to allocate in the array\n\t///\n\t/// # Requirements\n\t/// - `concepts::NoexceptDefaultConstructible<ElementType>`: `ElementType` must be\n\t/// noexcept default-constructible in order to make a `UniquePtr` managing an array of them\n\t/// - `concepts::Allocatable<ElementType, Alloc>`: `AllocatorAwareDeleter` can't be\n\t/// instantiated for an `ElementType`-`Alloc` pair where the element type `ElementType`\n\t/// isn't allocatable by the associated allocator type, `Alloc`\n\t/// - `std::is_unbounded_array_v<T>`: `T` must be an unbounded array type to make a `UniquePtr`\n\t/// managing an array.\n\t/// - `concepts::NoexceptConstructibleFrom<Alloc, decltype(alloc)>`: The associated allocator\n\t/// type, `Alloc`, must be noexcept constructible from the given allocator in order to create\n\t/// a `UniquePtr` using it\n\t/// @ingroup UniquePtr\n\ttemplate<typename T,\n\t\t\t typename Allocator = std::allocator<T>,\n\t\t\t typename ElementType = std::remove_cv_t<std::remove_all_extents_t<T>>,\n\t\t\t typename Alloc =\n\t\t\t\t typename std::allocator_traits<Allocator>::template rebind_alloc<ElementType>,\n\t\t\t typename... Args>\n\trequires concepts::NoexceptConstructibleFrom<ElementType, Args...> && mpl::for_all_types_v<\n\t\tstd::is_nothrow_copy_constructible,\n\t\tstd::true_type,\n\t\tmpl::list<Args...>> && concepts::Allocatable<ElementType,\n\t\t\t\t\t\t\t\t\t\t\t\t\t Alloc> && std::is_unbounded_array_v<T>\n\t[[nodiscard]] inline constexpr auto\n\tallocate_unique(const Allocator& alloc, usize N, Args&&... args) noexcept\n\t\t-> UniquePtr<T, AllocatorAwareDeleter<T, Alloc>>\n\trequires concepts::NoexceptConstructibleFrom<Alloc, decltype(alloc)> {\n\t\tusing Traits = std::allocator_traits<Alloc>;\n\t\tusing Deleter = AllocatorAwareDeleter<ElementType[], Alloc>; // NOLINT (c arrays)\n\n\t\tAlloc allocator(alloc);\n\t\tauto* p = Traits::allocate(allocator, N);\n\t\tauto tuple = std::make_tuple(std::forward<Args>(args)...);\n\t\t// we need to use do-while to make sure we construct the 0th element in a one element array\n\t\tauto i = 0_usize;\n\t\tdo {\n\t\t\tauto t = std::tuple(tuple);\n\t\t\tTraits::construct(allocator,\n\t\t\t\t\t\t\t  std::addressof(*p) + i,\n\t\t\t\t\t\t\t  std::make_from_tuple<ElementType>(std::move(t))); // NOLINT\n\t\t\t++i;\n\t\t} while(i < N);\n\n\t\treturn UniquePtr<ElementType[], Deleter>(p, Deleter(allocator, N)); // NOLINT (c arrays)\n\t}\n\n#if HYPERION_DEFINE_TESTS\n\n\t// NOLINTNEXTLINE(modernize-use-trailing-return-type)\n\tTEST_SUITE(\"UniquePtr\") {\n\t\tTEST_CASE(\"Constructor\") {\n\t\t\tauto ptr1 = UniquePtr<i32>();\n\t\t\t// NOLINTNEXTLINE\n\t\t\tauto ptr2 = UniquePtr<i32>(new i32(3_i32));\n\t\t\tauto ptr3 = hyperion::make_unique<i32>(2_i32);\n\n\t\t\tCHECK_EQ(ptr1, nullptr);\n\t\t\tCHECK_NE(ptr2, nullptr);\n\t\t\tCHECK_NE(ptr3, nullptr);\n\t\t\tCHECK_EQ(*ptr2, 3_i32);\n\t\t\tCHECK_EQ(*ptr3, 2_i32);\n\n\t\t\tSUBCASE(\"move\") {\n\t\t\t\tauto ptr4 = std::move(ptr3);\n\t\t\t\t// NOLINTNEXTLINE(bugprone-use-after-move,hicpp-invalid-access-moved)\n\t\t\t\tCHECK_EQ(ptr3, nullptr);\n\t\t\t\tCHECK_NE(ptr4, nullptr);\n\t\t\t\tCHECK_EQ(*ptr4, 2_i32);\n\t\t\t}\n\n\t\t\tSUBCASE(\"accessors_and_modifiers\") {\n\t\t\t\tCHECK(ptr3);\n\t\t\t\tCHECK(static_cast<bool>(ptr3));\n\t\t\t\tCHECK_NE(ptr3.get(), nullptr);\n\t\t\t\tCHECK_EQ(*(ptr3.get()), 2_i32);\n\n\t\t\t\tauto* ptr4 = ptr3.release();\n\t\t\t\tCHECK_EQ(ptr3, nullptr);\n\t\t\t\tCHECK_NE(ptr4, nullptr);\n\t\t\t\tCHECK_EQ(*ptr4, 2_i32);\n\n\t\t\t\t*ptr4 = 4_i32;\n\t\t\t\tptr3.reset(ptr4);\n\t\t\t\tCHECK_NE(ptr3, nullptr);\n\t\t\t\tCHECK(ptr3);\n\t\t\t\tCHECK_EQ(*ptr3, 4_i32);\n\t\t\t\tCHECK_EQ(*(ptr3.get()), 4_i32);\n\t\t\t}\n\t\t}\n\t}\n#endif // HYPERION_DEFINE_TESTS\n} // namespace hyperion\n", "meta": {"hexsha": "48789ec95ea449c192aada384a86c91d318179b9", "size": 53858, "ext": "h", "lang": "C", "max_stars_repo_path": "include/Hyperion/memory/UniquePtr.h", "max_stars_repo_name": "braxtons12/Hyperion-Utils", "max_stars_repo_head_hexsha": "3873a116e2ea76fc74c9c056925f3740eee6dcd8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/Hyperion/memory/UniquePtr.h", "max_issues_repo_name": "braxtons12/Hyperion-Utils", "max_issues_repo_head_hexsha": "3873a116e2ea76fc74c9c056925f3740eee6dcd8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/Hyperion/memory/UniquePtr.h", "max_forks_repo_name": "braxtons12/Hyperion-Utils", "max_forks_repo_head_hexsha": "3873a116e2ea76fc74c9c056925f3740eee6dcd8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.541864139, "max_line_length": 98, "alphanum_fraction": 0.7077128746, "num_tokens": 14724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.021287353966627617, "lm_q2_score": 0.02096424074166688, "lm_q1q2_score": 0.0004462732133094587}}
{"text": "#ifndef LOGGER_INCLUDE\n#define LOGGER_INCLUDE\n\n#include <gsl/string_span>\n\n#include \"log/log.h\"\nBOOST_LOG_GLOBAL_LOGGER(exec_helper_test_logger, execHelper::log::LoggerType);\n\nstatic const gsl::czstring<> LOG_CHANNEL = \"test\";\n#define LOG(x)                                                                 \\\n    BOOST_LOG_STREAM_CHANNEL_SEV(exec_helper_test_logger::get(), LOG_CHANNEL,  \\\n                                 execHelper::log::x)                           \\\n        << boost::log::add_value(fileLog, __FILE__)                            \\\n        << boost::log::add_value(lineLog, __LINE__)\n\n#endif /* LOGGER_INCLUDE */\n", "meta": {"hexsha": "1a698dc7e9e84db43661b08a202e017f66e26444", "size": 632, "ext": "h", "lang": "C", "max_stars_repo_path": "test/catch/include/unittest/logger.h", "max_stars_repo_name": "exec-helper/source", "max_stars_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-28T13:24:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-28T13:24:30.000Z", "max_issues_repo_path": "test/catch/include/unittest/logger.h", "max_issues_repo_name": "exec-helper/source", "max_issues_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/catch/include/unittest/logger.h", "max_forks_repo_name": "exec-helper/source", "max_forks_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-07-03T11:11:19.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-03T11:11:19.000Z", "avg_line_length": 37.1764705882, "max_line_length": 80, "alphanum_fraction": 0.5585443038, "num_tokens": 121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.022977373924293353, "lm_q2_score": 0.019419348679013636, "lm_q1q2_score": 0.00044620563596392847}}
{"text": "//          Copyright Jean Pierre Cimalando 2019.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE.md or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n#pragma once\n#include <SimpleIni.h>\n#include <gsl/gsl>\n#include <string>\n#include <memory>\n\nconst std::string &get_configuration_dir();\nstd::string get_configuration_file(gsl::cstring_span name);\n\nstd::unique_ptr<CSimpleIniA> create_configuration();\nstd::unique_ptr<CSimpleIniA> load_configuration(gsl::cstring_span name);\nbool save_configuration(gsl::cstring_span name, const CSimpleIniA &ini);\n\nstd::unique_ptr<CSimpleIniA> load_global_configuration();\nbool save_global_configuration(const CSimpleIniA &ini);\n", "meta": {"hexsha": "0f0bbe191b872a5688209e9e64efd5a6a34b3bae", "size": 725, "ext": "h", "lang": "C", "max_stars_repo_path": "sources/configuration.h", "max_stars_repo_name": "jpcima/smf-dsp", "max_stars_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2020-07-08T15:23:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T23:08:17.000Z", "max_issues_repo_path": "sources/configuration.h", "max_issues_repo_name": "jpcima/smf-dsp", "max_issues_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2020-07-05T23:59:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-16T20:44:07.000Z", "max_forks_repo_path": "sources/configuration.h", "max_forks_repo_name": "jpcima/smf-dsp", "max_forks_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-07-10T18:48:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-22T08:05:13.000Z", "avg_line_length": 34.5238095238, "max_line_length": 72, "alphanum_fraction": 0.7696551724, "num_tokens": 174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.025565214665694145, "lm_q2_score": 0.01744248323584941, "lm_q1q2_score": 0.0004459208282272616}}
{"text": "/** GSLDAPCom.h - <title>GSLDAP: Common</title>\n\n   Copyright (C) 2002-2003 Free Software Foundation, Inc.\n   \n   Written by:\tManuel Guesdon <mguesdon@orange-concept.com>\n   Date: \tSep 2002\n   \n   $Revision$\n   $Date$\n   $Id$\n\n   This file is part of the GNUstep LDAP Library.\n   \n   <license>\n   This library is free software; you can redistribute it and/or\n   modify it under the terms of the GNU Library General Public\n   License as published by the Free Software Foundation; either\n   version 2 of the License, or (at your option) any later version.\n   \n   This library is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n   Library General Public License for more details.\n   \n   You should have received a copy of the GNU Library General Public\n   License along with this library; if not, write to the Free\n   Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n   </license>\n**/\n\n#ifndef _GSLDAPCom_h__ \n#define _GSLDAPCom_h__ \n\n#include <stdio.h>\n#include <string.h>\n#include <ldap.h>\n#include <lber.h>\n#include <sys/time.h>\n#include <Foundation/NSObject.h>\n#include <Foundation/NSString.h>\n#include <Foundation/NSArray.h>\n#include <Foundation/NSData.h>\n#include <Foundation/NSDictionary.h>\n#include <Foundation/NSDebug.h>\n#include <Foundation/NSScanner.h>\n#include <Foundation/NSCalendarDate.h>\n#include <Foundation/NSException.h>\n#include <GNUstepBase/GSCategories.h>\n#include <gsldap/GSLDAPUtils.h>\n#include <gsldap/GSLDAPConnection.h>\n#include <gsldap/GSLDAPEntry.h>\n#include <gsldap/GSLDAPAttribute.h>\n#include <gsldap/GSLDAPObjectClass.h>\n#include <gsldap/GSLDAPSyntax.h>\n#include <gsldap/GSLDAPMatchingRule.h>\n#include <gsldap/GSLDAPSchema.h>\n\n#endif //_GSLDAPCom_h__ \n\n\n", "meta": {"hexsha": "8f4bf7444c1b821bc91485480e8635c16ea95fe3", "size": 1835, "ext": "h", "lang": "C", "max_stars_repo_path": "GSLDAPCom.h", "max_stars_repo_name": "gnustep/gsldap", "max_stars_repo_head_hexsha": "da29870c44780c3101d5a90ac9380d9b8c404593", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GSLDAPCom.h", "max_issues_repo_name": "gnustep/gsldap", "max_issues_repo_head_hexsha": "da29870c44780c3101d5a90ac9380d9b8c404593", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GSLDAPCom.h", "max_forks_repo_name": "gnustep/gsldap", "max_forks_repo_head_hexsha": "da29870c44780c3101d5a90ac9380d9b8c404593", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0819672131, "max_line_length": 69, "alphanum_fraction": 0.7455040872, "num_tokens": 484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.0284360338682141, "lm_q2_score": 0.01566364561003612, "lm_q1q2_score": 0.0004454119570666902}}
{"text": "/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */\n/*\n *     Copyright 2018 Couchbase, Inc\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n */\n#pragma once\n\n#include \"dcp/dcp-types.h\"\n#include \"evp_engine_test.h\"\n#include \"evp_store_single_threaded_test.h\"\n#include \"vbucket_fwd.h\"\n#include <memcached/engine_error.h>\n#include <gsl/gsl>\n\nclass Item;\nclass MockDcpProducer;\nclass MockActiveStream;\nstruct dcp_message_producers;\n\n/**\n * Test fixture for unit tests related to DCP.\n */\nclass DCPTest : public EventuallyPersistentEngineTest {\nprotected:\n    void SetUp() override;\n\n    void TearDown() override;\n\n    // Create a DCP producer; initially with no streams associated.\n    void create_dcp_producer(\n            int flags = 0,\n            IncludeValue includeVal = IncludeValue::Yes,\n            IncludeXattrs includeXattrs = IncludeXattrs::Yes,\n            std::vector<std::pair<std::string, std::string>> controls = {});\n\n    // Setup a DCP producer and attach a stream and cursor to it.\n    void setup_dcp_stream(\n            int flags = 0,\n            IncludeValue includeVal = IncludeValue::Yes,\n            IncludeXattrs includeXattrs = IncludeXattrs::Yes,\n            std::vector<std::pair<std::string, std::string>> controls = {});\n\n    void destroy_dcp_stream();\n\n    struct StreamRequestResult {\n        ENGINE_ERROR_CODE status;\n        uint64_t rollbackSeqno;\n    };\n\n    /**\n     * Helper function to simplify calling producer->streamRequest() - provides\n     * sensible default values for common invocations.\n     */\n    static StreamRequestResult doStreamRequest(DcpProducer& producer,\n                                               uint64_t startSeqno = 0,\n                                               uint64_t endSeqno = ~0,\n                                               uint64_t snapStart = 0,\n                                               uint64_t snapEnd = ~0,\n                                               uint64_t vbUUID = 0);\n\n    /**\n     * Helper function to simplify the process of preparing DCP items to be\n     * fetched from the stream via step().\n     * Should be called once all expected items are present in the vbuckets'\n     * checkpoint, it will then run the correct background tasks to\n     * copy CheckpointManager items to the producers' readyQ.\n     */\n    static void prepareCheckpointItemsForStep(\n            dcp_message_producers& msgProducers,\n            MockDcpProducer& producer,\n            VBucket& vb);\n\n    /*\n     * Creates an item with the key \\\"key\\\", containing json data and xattrs.\n     * @return a unique_ptr to a newly created item.\n     */\n    std::unique_ptr<Item> makeItemWithXattrs();\n\n    /*\n     * Creates an item with the key \\\"key\\\", containing json data and no xattrs.\n     * @return a unique_ptr to a newly created item.\n     */\n    std::unique_ptr<Item> makeItemWithoutXattrs();\n\n    /* Add items onto the vbucket and wait for the checkpoint to be removed */\n    void addItemsAndRemoveCheckpoint(int numItems);\n\n    void removeCheckpoint(int numItems);\n\n    void runCheckpointProcessor(dcp_message_producers& producers);\n\n    std::shared_ptr<MockDcpProducer> producer;\n    std::shared_ptr<MockActiveStream> stream;\n    VBucketPtr vb0;\n\n    /*\n     * Fake callback emulating dcp_add_failover_log\n     */\n    static ENGINE_ERROR_CODE fakeDcpAddFailoverLog(\n            vbucket_failover_t* entry,\n            size_t nentries,\n            gsl::not_null<const void*> cookie) {\n        callbackCount++;\n        return ENGINE_SUCCESS;\n    }\n\n    // callbackCount needs to be static as its used inside of the static\n    // function fakeDcpAddFailoverLog.\n    static int callbackCount;\n};\n", "meta": {"hexsha": "f01c97774b63c3b7efde1738190dcde15eca9cf2", "size": 4219, "ext": "h", "lang": "C", "max_stars_repo_path": "engines/ep/tests/module_tests/dcp_test.h", "max_stars_repo_name": "hrajput89/kv_engine", "max_stars_repo_head_hexsha": "33fb1ab2c9787f55555e5f7edea38807b3dbc371", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "engines/ep/tests/module_tests/dcp_test.h", "max_issues_repo_name": "hrajput89/kv_engine", "max_issues_repo_head_hexsha": "33fb1ab2c9787f55555e5f7edea38807b3dbc371", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "engines/ep/tests/module_tests/dcp_test.h", "max_forks_repo_name": "hrajput89/kv_engine", "max_forks_repo_head_hexsha": "33fb1ab2c9787f55555e5f7edea38807b3dbc371", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-01-15T16:52:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-15T16:52:37.000Z", "avg_line_length": 34.5819672131, "max_line_length": 80, "alphanum_fraction": 0.6461246741, "num_tokens": 935, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.027169230747973956, "lm_q2_score": 0.015424555476319006, "lm_q1q2_score": 0.00041907330692103644}}
{"text": "#pragma once\n\n#include \"poll_event.h\"\n#include \"poll_response.h\"\n#include \"poll_target.h\"\n\n#include <gsl/span>\n\n#include <optional>\n#include <vector>\n\nnamespace wrappers::zmq {\n\n[[nodiscard]] std::optional<std::vector<poll_response>>\nblocking_poll(gsl::span<poll_target> targets) noexcept;\n\n} // namespace wrappers::zmq\n", "meta": {"hexsha": "25e035d3f8dd80cdfc1647d2dcf20a809620f201", "size": 320, "ext": "h", "lang": "C", "max_stars_repo_path": "src/wrappers/zmq/poll.h", "max_stars_repo_name": "Longhanks/linkollector-win", "max_stars_repo_head_hexsha": "a76b08fa4f20a3612988a0d84e5b14f7822638ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/wrappers/zmq/poll.h", "max_issues_repo_name": "Longhanks/linkollector-win", "max_issues_repo_head_hexsha": "a76b08fa4f20a3612988a0d84e5b14f7822638ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/wrappers/zmq/poll.h", "max_forks_repo_name": "Longhanks/linkollector-win", "max_forks_repo_head_hexsha": "a76b08fa4f20a3612988a0d84e5b14f7822638ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.7777777778, "max_line_length": 55, "alphanum_fraction": 0.74375, "num_tokens": 76, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.023330771524836445, "lm_q2_score": 0.017712301296001067, "lm_q1q2_score": 0.0004132416547160654}}
{"text": "/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*/\n// Portions Copyright (c) Microsoft Corporation\n\n#pragma once\n\n#include <functional>\n#include <memory>\n#include <string>\n#include <unordered_map>\n#include <vector>\n#include <gsl/gsl>\n\n#include \"core/common/common.h\"\n#include \"core/common/path_string.h\"\n#include \"core/framework/callback.h\"\n#include \"core/platform/env_time.h\"\n#include \"core/platform/telemetry.h\"\n\n#ifndef _WIN32\n#include <sys/types.h>\n#include <unistd.h>\n#endif\nnamespace Eigen {\nclass ThreadPoolInterface;\n}\nnamespace onnxruntime {\n\n#ifdef _WIN32\nusing PIDType = unsigned long;\nusing FileOffsetType = int64_t;\n#else\nusing PIDType = pid_t;\nusing FileOffsetType = off_t;\n#endif\n\nclass EnvThread {\n public:\n  virtual void OnCancel() = 0;\n  virtual ~EnvThread() = default;\n};\n\n// Parameters that are required to create a set of threads for a thread pool\nstruct ThreadOptions {\n  // Stack size for a new thread. If it is 0, the operating system uses the same value as the stack that's specified for\n  // the main thread, which is usually set in the main executable(not controlled by onnxruntime.dll).\n  unsigned int stack_size = 0;\n\n  // Thread affinity means a thread can only run on the logical processors that the thread is allowed to run on.\n  // If the vector is not empty, set the affinity of each thread to just one CPU.\n  // Index is thread index, value is CPU ID, starting from zero. For example, the first thread in the pool will be bound\n  // to the logical processor with id of affinity[0]. If the vector is empty, the thread can run on all the processors\n  // its process can run on. NOTE: When hyperthreading is enabled, for example, on a 4 cores 8 physical threads CPU,\n  // processor group [0,1,2,3] may only contain half of the physical cores.\n  std::vector<size_t> affinity;\n\n  // Set or unset denormal as zero.\n  bool set_denormal_as_zero = false;\n};\n/// \\brief An interface used by the onnxruntime implementation to\n/// access operating system functionality like the filesystem etc.\n///\n/// Callers may wish to provide a custom Env object to get fine grain\n/// control.\n///\n/// All Env implementations are safe for concurrent access from\n/// multiple threads without any external synchronization.\nclass Env {\n public:\n  using EnvThread = onnxruntime::EnvThread;\n  virtual ~Env() = default;\n  // clang-format off\n  /**\n   * Start a new thread for a thread pool\n   * \\param name_prefix A human-readable string for debugging purpose, can be NULL\n   * \\param index The index value of the thread, for each thread pool instance, the index should start from 0 and be continuous.\n   * \\param start_address The entry point of thread\n   * \\param threadpool The thread pool that the new thread belongs to\n   * \\param thread_options options to create the thread\n   *\n   * Caller is responsible for deleting the returned value\n   */\n  // clang-format on\n  virtual EnvThread* CreateThread(_In_opt_z_ const ORTCHAR_T* name_prefix, int index,\n                                  _In_ unsigned (*start_address)(int id, Eigen::ThreadPoolInterface* param),\n                                  Eigen::ThreadPoolInterface* threadpool, const ThreadOptions& thread_options) = 0;\n\n  /// \\brief Returns a default environment suitable for the current operating\n  /// system.\n  ///\n  /// Sophisticated users may wish to provide their own Env\n  /// implementation instead of relying on this default environment.\n  ///\n  /// The result of Default() belongs to this library and must never be deleted.\n  static Env& Default();\n\n  virtual int GetNumCpuCores() const = 0;\n\n  // This function doesn't support systems with more than 64 logical processors\n  virtual std::vector<size_t> GetThreadAffinityMasks() const = 0;\n\n  /// \\brief Returns the number of micro-seconds since the Unix epoch.\n  virtual uint64_t NowMicros() const {\n    return env_time_->NowMicros();\n  }\n\n  /// \\brief Returns the number of seconds since the Unix epoch.\n  virtual uint64_t NowSeconds() const {\n    return env_time_->NowSeconds();\n  }\n\n  /// Sleeps/delays the thread for the prescribed number of micro-seconds.\n  /// On Windows, it's the min time to sleep, not the actual one.\n  virtual void SleepForMicroseconds(int64_t micros) const = 0;\n\n  /**\n   * Gets the length of the specified file.\n   */\n  virtual common::Status GetFileLength(_In_z_ const ORTCHAR_T* file_path, size_t& length) const = 0;\n  virtual common::Status GetFileLength(int fd, /*out*/ size_t& file_size) const = 0;\n\n  /**\n   * Copies the content of the file into the provided buffer.\n   * @param file_path The path to the file.\n   * @param offset The file offset from which to start reading.\n   * @param length The length in bytes to read.\n   * @param buffer The buffer in which to write.\n   */\n  virtual common::Status ReadFileIntoBuffer(_In_z_ const ORTCHAR_T* file_path, FileOffsetType offset, size_t length,\n                                            gsl::span<char> buffer) const = 0;\n\n  using MappedMemoryPtr = std::unique_ptr<char[], OrtCallbackInvoker>;\n\n  /**\n   * Maps the content of the file into memory.\n   * This is a copy-on-write mapping, so any changes are not written to the\n   * actual file.\n   * @param file_path The path to the file.\n   * @param offset The file offset from which to start the mapping.\n   * @param length The length in bytes of the mapping.\n   * @param[out] mapped_memory A smart pointer to the mapped memory which\n   *             unmaps the memory (unless release()'d) when destroyed.\n   */\n  virtual common::Status MapFileIntoMemory(_In_z_ const ORTCHAR_T* file_path, FileOffsetType offset, size_t length,\n                                           MappedMemoryPtr& mapped_memory) const = 0;\n\n#ifdef _WIN32\n  /// \\brief Returns true if the directory exists.\n  virtual bool FolderExists(const std::wstring& path) const = 0;\n  /// \\brief Recursively creates the directory, if it doesn't exist.\n  virtual common::Status CreateFolder(const std::wstring& path) const = 0;\n  // Mainly for use with protobuf library\n  virtual common::Status FileOpenRd(const std::wstring& path, /*out*/ int& fd) const = 0;\n  // Mainly for use with protobuf library\n  virtual common::Status FileOpenWr(const std::wstring& path, /*out*/ int& fd) const = 0;\n#endif\n  /// \\brief Returns true if the directory exists.\n  virtual bool FolderExists(const std::string& path) const = 0;\n  /// \\brief Recursively creates the directory, if it doesn't exist.\n  virtual common::Status CreateFolder(const std::string& path) const = 0;\n  // Recursively deletes the directory and its contents.\n  // Note: This function is not thread safe!\n  virtual common::Status DeleteFolder(const PathString& path) const = 0;\n  // Mainly for use with protobuf library\n  virtual common::Status FileOpenRd(const std::string& path, /*out*/ int& fd) const = 0;\n  // Mainly for use with protobuf library\n  virtual common::Status FileOpenWr(const std::string& path, /*out*/ int& fd) const = 0;\n  // Mainly for use with protobuf library\n  virtual common::Status FileClose(int fd) const = 0;\n\n  /** Gets the canonical form of a file path (symlinks resolved). */\n  virtual common::Status GetCanonicalPath(\n      const PathString& path,\n      PathString& canonical_path) const = 0;\n\n  // This functions is always successful. It can't fail.\n  virtual PIDType GetSelfPid() const = 0;\n\n  // \\brief Load a dynamic library.\n  //\n  // Pass \"library_filename\" to a platform-specific mechanism for dynamically\n  // loading a library.  The rules for determining the exact location of the\n  // library are platform-specific and are not documented here.\n  //\n  // On success, returns a handle to the library in \"*handle\" and returns\n  // OK from the function.\n  // Otherwise returns nullptr in \"*handle\" and an error status from the\n  // function.\n  virtual common::Status LoadDynamicLibrary(const std::string& library_filename, void** handle) const = 0;\n\n  virtual common::Status UnloadDynamicLibrary(void* handle) const = 0;\n\n  // \\brief Gets the file path of the onnx runtime code\n  //\n  // Used to help load other shared libraries that live in the same folder as the core code, for example\n  // The DNNL provider shared library. Without this path, the module won't be found on windows in all cases.\n  virtual std::string GetRuntimePath() const { return \"\"; }\n\n  // \\brief Get a pointer to a symbol from a dynamic library.\n  //\n  // \"handle\" should be a pointer returned from a previous call to LoadDynamicLibrary.\n  // On success, store a pointer to the located symbol in \"*symbol\" and return\n  // OK from the function. Otherwise, returns nullptr in \"*symbol\" and an error\n  // status from the function.\n  virtual common::Status GetSymbolFromLibrary(void* handle, const std::string& symbol_name, void** symbol) const = 0;\n\n  // \\brief build the name of dynamic library.\n  //\n  // \"name\" should be name of the library.\n  // \"version\" should be the version of the library or NULL\n  // returns the name that LoadDynamicLibrary() can use\n  virtual std::string FormatLibraryFileName(const std::string& name, const std::string& version) const = 0;\n\n  // \\brief returns a provider that will handle telemetry on the current platform\n  virtual const Telemetry& GetTelemetryProvider() const = 0;\n\n  // \\brief returns a value for the queried variable name (var_name)\n  //\n  // Returns the corresponding value stored in the environment variable if available\n  // Returns empty string if there is no such environment variable available\n  virtual std::string GetEnvironmentVar(const std::string& var_name) const = 0;\n\n protected:\n  Env();\n\n private:\n  ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(Env);\n  EnvTime* env_time_ = EnvTime::Default();\n};\n\n}  // namespace onnxruntime\n", "meta": {"hexsha": "268f729acf811a4de7512ee055e79d3e29095e7c", "size": 10288, "ext": "h", "lang": "C", "max_stars_repo_path": "onnxruntime/core/platform/env.h", "max_stars_repo_name": "dennyac/onnxruntime", "max_stars_repo_head_hexsha": "d5175795d2b7f2db18b0390f394a49238f814668", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-02-20T04:53:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-09T19:29:27.000Z", "max_issues_repo_path": "onnxruntime/core/platform/env.h", "max_issues_repo_name": "dennyac/onnxruntime", "max_issues_repo_head_hexsha": "d5175795d2b7f2db18b0390f394a49238f814668", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2021-03-01T21:35:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T05:38:38.000Z", "max_forks_repo_path": "onnxruntime/core/platform/env.h", "max_forks_repo_name": "dennyac/onnxruntime", "max_forks_repo_head_hexsha": "d5175795d2b7f2db18b0390f394a49238f814668", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-02-20T12:10:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-09T19:15:20.000Z", "avg_line_length": 42.1639344262, "max_line_length": 128, "alphanum_fraction": 0.7176321928, "num_tokens": 2421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.025565213552057323, "lm_q2_score": 0.015906388387952466, "lm_q1q2_score": 0.00040665021597996963}}
{"text": "#pragma once\n\n#include <memory>\n#include <string>\n#include <vector>\n\n#include <gsl/span>\n\nstruct VfsSearchResult {\n\tstd::string filename;\n\tbool dir;\n\tsize_t sizeInBytes;\n\tuint32_t lastModified;\n};\n\nenum class SeekDir {\n\tStart = 0,\n\tCurrent = 1,\n\tEnd = 2\n};\n\n/*\n\tAbstractions for accessing files in the virtual file system.\n\tThe virtual file system is backed by TIO in a normal game,\n\twhich means that the files are scattered across the .dat files\n\tand data directories.\n*/\nclass Vfs {\npublic:\n\tvirtual ~Vfs() {\n\t};\n\n\tstatic Vfs* CreateStdIoVfs();\n\n\t/*\n\t\tReads a file fully into a string.\n\t*/\n\tstd::string ReadAsString(std::string_view filename);\n\n\t/*\n\tReads a binary file fully into a vector of uint8_t.\n\t*/\n\tstd::vector<uint8_t> ReadAsBinary(std::string_view filename);\n\n\t/**\n\t * Does the file exist?\n\t */\n\tvirtual bool FileExists(std::string_view path) = 0;\n\n\t/**\n\t * Does the directory exist?\n\t */\n\tvirtual bool DirExists(std::string_view path) = 0;\n\n\t/**\n\t * Creates a directory.\n\t */\n\tvirtual bool MkDir(std::string_view path) = 0;\n\n\t/**\n\t * Will return all files and directories that match the given glob pattern, which\n\t * is not recursive.\n\t * Example: mes\\*.mes will return the names of all files in mes (not full paths) that\n\t            end with .mes.\n\t */\n\tvirtual std::vector<VfsSearchResult> Search(std::string_view globPattern) = 0;\n\n\t/**\n\t * Removes an empty directory.\n\t */\n\tvirtual bool RemoveDir(std::string_view path) = 0;\n\n\t/**\n\t * Removes a file (no directories).\n\t */\n\tvirtual bool RemoveFile(std::string_view path) = 0;\n\n\t/**\n\t* Deletes all files and dirctories within the given directory.\n\t*/\n\tbool CleanDir(std::string_view path);\n\n\t/**\n\t * Returns true if the given directory does not contain anything.\n\t */\n\tbool IsDirEmpty(std::string_view path);\n\n\t/**\n\t * Writes binary data to a file.\n\t */\n\tvoid WriteBinaryFile(std::string_view path, gsl::span<uint8_t> data);\n\n\tusing FileHandle = void*;\n\tvirtual FileHandle Open(std::string_view name, std::string_view mode) = 0;\n\tvirtual size_t Read(void* buffer, size_t size, FileHandle handle) = 0;\n\tvirtual size_t Write(const void* buffer, size_t size, FileHandle handle) = 0;\n\tvirtual size_t Length(FileHandle handle) = 0;\n\tvirtual size_t Tell(FileHandle handle) = 0;\n\tvirtual void Seek(FileHandle handle, int position, SeekDir dir = SeekDir::Start) = 0;\n\tvirtual void Close(FileHandle handle) = 0;\n\t\n};\n\nclass VfsPath {\npublic:\n\tVfsPath() = delete;\n\n\tstatic bool IsFileSystem(std::string_view path);\n\tstatic std::string Concat(std::string_view a, std::string_view b);\n};\n\nextern std::unique_ptr<Vfs> vfs;\n", "meta": {"hexsha": "f31d57c71ff736fee435bcd9300c4ffadc1073a8", "size": 2577, "ext": "h", "lang": "C", "max_stars_repo_path": "Infrastructure/include/infrastructure/vfs.h", "max_stars_repo_name": "edoipi/TemplePlus", "max_stars_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 69.0, "max_stars_repo_stars_event_min_datetime": "2015-05-05T14:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T06:13:04.000Z", "max_issues_repo_path": "Infrastructure/include/infrastructure/vfs.h", "max_issues_repo_name": "edoipi/TemplePlus", "max_issues_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 457.0, "max_issues_repo_issues_event_min_datetime": "2015-05-01T22:07:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T02:19:10.000Z", "max_forks_repo_path": "Infrastructure/include/infrastructure/vfs.h", "max_forks_repo_name": "edoipi/TemplePlus", "max_forks_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2016-02-04T21:19:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T23:14:51.000Z", "avg_line_length": 22.8053097345, "max_line_length": 86, "alphanum_fraction": 0.7023670935, "num_tokens": 669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.03514484336903119, "lm_q2_score": 0.0115081505157441, "lm_q1q2_score": 0.00040445214734306193}}
{"text": "// Copyright 2021 atframework\n// Created by owent\n\n#pragma once\n\n#include <config/atframe_utils_build_feature.h>\n#include <config/compiler_features.h>\n\n#include <design_pattern/nomovable.h>\n#include <design_pattern/noncopyable.h>\n\n#include <time/time_utility.h>\n\n#include <gsl/select-gsl.h>\n\n#include <list>\n#include <vector>\n\n#if defined(LIBATFRAME_UTILS_ENABLE_UNORDERED_MAP_SET) && LIBATFRAME_UTILS_ENABLE_UNORDERED_MAP_SET\n#  include <unordered_map>\n#  include <unordered_set>\n#else\n#  include <map>\n#  include <set>\n#endif\n\n#include \"atframe/atapp_conf.h\"\n#include \"atframe/etcdcli/etcd_discovery.h\"\n\nnamespace atapp {\nclass app;\nclass atapp_connection_handle;\nclass atapp_endpoint;\nclass atapp_connector_impl;\n\nstruct atapp_endpoint_bind_helper {\n  // This API is used by inner system and will not be exported, do not call it directly\n  static LIBATAPP_MACRO_API_SYMBOL_HIDDEN void unbind(atapp_connection_handle &handle, atapp_endpoint &connect);\n  // This API is used by inner system and will not be exported, do not call it directly\n  static LIBATAPP_MACRO_API_SYMBOL_HIDDEN void bind(atapp_connection_handle &handle, atapp_endpoint &connect);\n};\n\nclass atapp_endpoint {\n public:\n  using handle_set_t = std::unordered_set<atapp_connection_handle *>;\n  using handle_set_iterator = handle_set_t::iterator;\n  using handle_set_const_iterator = handle_set_t::const_iterator;\n  using ptr_t = std::shared_ptr<atapp_endpoint>;\n  using weak_ptr_t = std::weak_ptr<atapp_endpoint>;\n\n  struct pending_message_t {\n    util::time::time_utility::raw_time_t expired_timepoint;\n    int32_t type;\n    uint64_t message_sequence;\n    std::vector<unsigned char> data;\n    std::unique_ptr<atapp::protocol::atapp_metadata> metadata;\n  };\n\n  UTIL_DESIGN_PATTERN_NOCOPYABLE(atapp_endpoint)\n  UTIL_DESIGN_PATTERN_NOMOVABLE(atapp_endpoint)\n\n private:\n  struct construct_helper_t {};\n\n public:\n  LIBATAPP_MACRO_API atapp_endpoint(app &owner, construct_helper_t &helper);\n  static LIBATAPP_MACRO_API ptr_t create(app &owner);\n  LIBATAPP_MACRO_API ~atapp_endpoint();\n\n  LIBATAPP_MACRO_API uint64_t get_id() const noexcept;\n  LIBATAPP_MACRO_API gsl::string_view get_name() const noexcept;\n\n  UTIL_FORCEINLINE bool has_connection_handle() const noexcept { return !refer_connections_.empty(); }\n  LIBATAPP_MACRO_API const etcd_discovery_node::ptr_t &get_discovery() const noexcept;\n  LIBATAPP_MACRO_API void update_discovery(const etcd_discovery_node::ptr_t &discovery) noexcept;\n\n  LIBATAPP_MACRO_API void add_connection_handle(atapp_connection_handle &handle);\n  LIBATAPP_MACRO_API void remove_connection_handle(atapp_connection_handle &handle);\n  LIBATAPP_MACRO_API atapp_connection_handle *get_ready_connection_handle() const noexcept;\n\n  LIBATAPP_MACRO_API int32_t push_forward_message(int32_t type, uint64_t &msg_sequence, const void *data,\n                                                  size_t data_size, const atapp::protocol::atapp_metadata *metadata);\n\n  LIBATAPP_MACRO_API int32_t retry_pending_messages(const util::time::time_utility::raw_time_t &tick_time,\n                                                    int32_t max_count = 0);\n  LIBATAPP_MACRO_API void add_waker(util::time::time_utility::raw_time_t wakeup_time);\n\n  UTIL_FORCEINLINE app *get_owner() const noexcept { return owner_; }\n\n  LIBATAPP_MACRO_API size_t get_pending_message_count() const noexcept;\n  LIBATAPP_MACRO_API size_t get_pending_message_size() const noexcept;\n\n private:\n  void reset();\n  void cancel_pending_messages();\n\n  void trigger_on_receive_forward_response(atapp_connector_impl *connector, atapp_connection_handle *handle,\n                                           int32_t type, uint64_t sequence, int32_t error_code, const void *data,\n                                           size_t data_size, const atapp::protocol::atapp_metadata *metadata);\n\n private:\n  bool closing_;\n  app *owner_;\n  util::time::time_utility::raw_time_t nearest_waker_;\n  weak_ptr_t watcher_;\n  handle_set_t refer_connections_;\n  etcd_discovery_node::ptr_t discovery_;\n\n  std::list<pending_message_t> pending_message_;\n  size_t pending_message_size_;\n#if defined(LIBATAPP_ENABLE_CUSTOM_COUNT_FOR_STD_LIST) && LIBATAPP_ENABLE_CUSTOM_COUNT_FOR_STD_LIST\n  size_t pending_message_count_;\n#endif\n\n  friend struct atapp_endpoint_bind_helper;\n};\n}  // namespace atapp\n", "meta": {"hexsha": "6147e48b35453820eb9f63b599c5c9065a5cd0ce", "size": 4312, "ext": "h", "lang": "C", "max_stars_repo_path": "include/atframe/connectors/atapp_endpoint.h", "max_stars_repo_name": "atframework/libatapp", "max_stars_repo_head_hexsha": "54aae9e0972eb94c33a7c109bdd099ff3a89ee80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2018-06-23T04:38:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T01:22:54.000Z", "max_issues_repo_path": "include/atframe/connectors/atapp_endpoint.h", "max_issues_repo_name": "atframework/libatapp", "max_issues_repo_head_hexsha": "54aae9e0972eb94c33a7c109bdd099ff3a89ee80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/atframe/connectors/atapp_endpoint.h", "max_forks_repo_name": "atframework/libatapp", "max_forks_repo_head_hexsha": "54aae9e0972eb94c33a7c109bdd099ff3a89ee80", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-08-04T06:14:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-19T10:06:06.000Z", "avg_line_length": 36.5423728814, "max_line_length": 117, "alphanum_fraction": 0.7738868275, "num_tokens": 1004, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.03514484640079326, "lm_q2_score": 0.011508148725280784, "lm_q1q2_score": 0.00040445211930747793}}
{"text": "#ifndef LIC_METHOD_DEFINITION\n#define LIC_METHOD_DEFINITION\n\n#include <gsl/gsl>\n\n#include \"Metadata.h\"\n\nnamespace lic\n{\n\nclass MethodDefinition : Metadata\n{\npublic:\n    MethodDefinition(Assembly& assembly, MetadataTable table, size_t rid, gsl::byte* row);\n    ~MethodDefinition();\n\n    const char* Name() const;\n    const gsl::byte* Code() const;\n};\n\n}\n\n#endif // !LIC_METHOD_DEFINITION\n", "meta": {"hexsha": "f7fa2907dd7cc81d5681ce656d1d51895326c56f", "size": 387, "ext": "h", "lang": "C", "max_stars_repo_path": "src/loader/MethodDefinition.h", "max_stars_repo_name": "roberthusak/lic", "max_stars_repo_head_hexsha": "5ad4a7014673bb60b748390856e0c7cb11eaca09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-05-18T11:44:16.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-18T11:44:16.000Z", "max_issues_repo_path": "src/loader/MethodDefinition.h", "max_issues_repo_name": "roberthusak/lic", "max_issues_repo_head_hexsha": "5ad4a7014673bb60b748390856e0c7cb11eaca09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/loader/MethodDefinition.h", "max_forks_repo_name": "roberthusak/lic", "max_forks_repo_head_hexsha": "5ad4a7014673bb60b748390856e0c7cb11eaca09", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.125, "max_line_length": 90, "alphanum_fraction": 0.7235142119, "num_tokens": 90, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.019419345912437175, "lm_q2_score": 0.02033235397339163, "lm_q1q2_score": 0.0003948410150234085}}
{"text": "#ifndef TEST_COMMAND_INCLUDE\n#define TEST_COMMAND_INCLUDE\n\n#include <memory>\n#include <string>\n#include <vector>\n\n#include <gsl/gsl>\n\n#include \"statement.h\"\n#include \"yaml.h\"\n\nnamespace execHelper {\nnamespace test {\nnamespace baseUtils {\nusing CommandKey = std::string;\nusing CommandKeys = std::vector<CommandKey>;\nusing Statements = std::vector<std::shared_ptr<Statement>>;\n\nclass TestCommand {\n  public:\n    TestCommand(CommandKey commandKey,\n                Statements initialStatements = {}) noexcept;\n\n    std::shared_ptr<Statement> operator[](size_t index) const noexcept;\n\n    Statements::const_iterator begin() const noexcept;\n    Statements::const_iterator end() const noexcept;\n\n    size_t size() const noexcept;\n    std::string get() const noexcept;\n    unsigned int getNbOfStatements() const noexcept;\n    unsigned int getNumberOfStatementExecutions()\n        const noexcept; // Returns the sum of executions of all statements\n    void add(std::shared_ptr<Statement> statement) noexcept;\n    void resetExecutions() noexcept;\n\n    void write(gsl::not_null<YamlWriter*> yaml) const noexcept;\n\n  private:\n    std::string m_command;\n    Statements m_statements;\n};\nusing Commands = std::vector<TestCommand>;\n\ntemplate <typename T, typename... Args>\ninline std::shared_ptr<Statement> createStatement(Args... args) noexcept {\n    return std::static_pointer_cast<Statement>(std::make_shared<T>(args...));\n}\n} // namespace baseUtils\n} // namespace test\n} // namespace execHelper\n\n#endif /* TEST_COMMAND_INCLUDE */\n", "meta": {"hexsha": "9a66d64882016e7c9aca631b2c47496cd1071a4f", "size": 1518, "ext": "h", "lang": "C", "max_stars_repo_path": "test/base-utils/include/base-utils/testCommand.h", "max_stars_repo_name": "exec-helper/source", "max_stars_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-28T13:24:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-28T13:24:30.000Z", "max_issues_repo_path": "test/base-utils/include/base-utils/testCommand.h", "max_issues_repo_name": "exec-helper/source", "max_issues_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/base-utils/include/base-utils/testCommand.h", "max_forks_repo_name": "exec-helper/source", "max_forks_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-07-03T11:11:19.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-03T11:11:19.000Z", "avg_line_length": 27.6, "max_line_length": 77, "alphanum_fraction": 0.7338603426, "num_tokens": 329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.02442309360454794, "lm_q2_score": 0.015906392936395713, "lm_q1q2_score": 0.00038848332359631263}}
{"text": "#pragma once\n\n#include <gsl/gsl>\n\n", "meta": {"hexsha": "5246ae4c8d35bb690b270bf2151fdd92f5bbfffd", "size": 34, "ext": "h", "lang": "C", "max_stars_repo_path": "build/Test/pch.h", "max_stars_repo_name": "DakkyDaWolf/OpenGL", "max_stars_repo_head_hexsha": "628e9aed116022175cc0c59c88ace7688309628c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "build/Test/pch.h", "max_issues_repo_name": "DakkyDaWolf/OpenGL", "max_issues_repo_head_hexsha": "628e9aed116022175cc0c59c88ace7688309628c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "build/Test/pch.h", "max_forks_repo_name": "DakkyDaWolf/OpenGL", "max_forks_repo_head_hexsha": "628e9aed116022175cc0c59c88ace7688309628c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 6.8, "max_line_length": 18, "alphanum_fraction": 0.6764705882, "num_tokens": 10, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.01542454936625937, "lm_q2_score": 0.025178843117871635, "lm_q1q2_score": 0.000388372308656911}}
{"text": "#ifndef CONTROLLERS_IMAGEOPERATIONTOGGLECONTROLLER_H\n#define CONTROLLERS_IMAGEOPERATIONTOGGLECONTROLLER_H\n\n#include \"imageoperationactioncontroller.h\"\n\n#include \"s3d/cv/image_operation/image_operation.h\"\n\n#include <QAction>\n\n#include <gsl/gsl>\n\nclass ImageOperationToggleController : public ImageOperationActionController {\n  Q_OBJECT\n\npublic:\n  ImageOperationToggleController(gsl::not_null<QAction*> action,\n                                 gsl::not_null<s3d::image_operation::ImageOperation*> imageOperation);\n\n  void onActionTriggered() override;\n};\n\n#endif //CONTROLLERS_IMAGEOPERATIONTOGGLECONTROLLER_H\n", "meta": {"hexsha": "4bdbe13ac04c507a2596c026eea936f500f2896f", "size": 608, "ext": "h", "lang": "C", "max_stars_repo_path": "src/apps/S3DAnalyzer/controllers/imageoperationtogglecontroller.h", "max_stars_repo_name": "hugbed/OpenS3D", "max_stars_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-16T16:38:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-20T03:23:15.000Z", "max_issues_repo_path": "src/apps/S3DAnalyzer/controllers/imageoperationtogglecontroller.h", "max_issues_repo_name": "hugbed/OpenS3D", "max_issues_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 40.0, "max_issues_repo_issues_event_min_datetime": "2017-04-12T17:24:44.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-21T18:41:23.000Z", "max_forks_repo_path": "src/apps/S3DAnalyzer/controllers/imageoperationtogglecontroller.h", "max_forks_repo_name": "hugbed/OpenS3D", "max_forks_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-07-13T21:51:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-18T16:22:03.000Z", "avg_line_length": 26.4347826087, "max_line_length": 102, "alphanum_fraction": 0.7927631579, "num_tokens": 134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.02758527902908032, "lm_q2_score": 0.01406362763726976, "lm_q1q2_score": 0.0003879490925351719}}
{"text": "/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */\n/*\n *     Copyright 2018 Couchbase, Inc.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n */\n\n#pragma once\n\n#include \"engine_error.h\"\n#include \"types.h\"\n\n#include <gsl/gsl>\n\nstruct ServerDocumentIface {\n    virtual ~ServerDocumentIface() = default;\n\n    /**\n     * This callback is called from the underlying engine right before\n     * it is linked into the list of available documents (it is currently\n     * not visible to anyone). The engine should have validated all\n     * properties set in the document by the client and the core, and\n     * assigned a new CAS number for the document (and sequence number if\n     * the underlying engine use those).\n     *\n     * The callback may at this time do post processing of the document\n     * content (it is allowed to modify the content data, but not\n     * reallocate or change the size of the data in any way).\n     *\n     * Given that the engine MAY HOLD LOCKS when calling this function\n     * the core is *NOT* allowed to acquire *ANY* locks (except for doing\n     * some sort of memory allocation for a temporary buffer).\n     *\n     * @param cookie The cookie provided to the engine for the storage\n     *               command which may (which may hold more context)\n     * @param info the items underlying data\n     * @return ENGINE_SUCCESS means that the underlying engine should\n     *                        proceed to link the item. All other\n     *                        error codes means that the engine should\n     *                        *NOT* link the item\n     */\n    virtual ENGINE_ERROR_CODE pre_link(gsl::not_null<const void*> cookie,\n                                       item_info& info) = 0;\n\n    /**\n     * This callback is called from the underlying engine right before\n     * a particular document expires. The callback is responsible for\n     * modifying the contents of the itm_info passed in. The updated\n     * total size is available in itm_info.nbytes.\n     *\n     * @param itm_info info pertaining to the item that is to be expired.\n     * @return true indicating that the info has been modified in itm_info.\n     *         false indicating that there is no data available in itm_info.\n     * @throws std::bad_alloc in case of memory allocation failure\n     * @throws std::logic_error if the data has grown\n     */\n    virtual bool pre_expiry(item_info& itm_info) = 0;\n};\n", "meta": {"hexsha": "7e4ef62f72016d896f7af47675991f906b2d5d96", "size": 2968, "ext": "h", "lang": "C", "max_stars_repo_path": "include/memcached/server_document_iface.h", "max_stars_repo_name": "gsauere/kv_engine", "max_stars_repo_head_hexsha": "233945fe4ddb033c2292e51f5845ab630c33276f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/memcached/server_document_iface.h", "max_issues_repo_name": "gsauere/kv_engine", "max_issues_repo_head_hexsha": "233945fe4ddb033c2292e51f5845ab630c33276f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/memcached/server_document_iface.h", "max_forks_repo_name": "gsauere/kv_engine", "max_forks_repo_head_hexsha": "233945fe4ddb033c2292e51f5845ab630c33276f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.0144927536, "max_line_length": 79, "alphanum_fraction": 0.6664420485, "num_tokens": 654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.030214586630765136, "lm_q2_score": 0.012624948689482097, "lm_q1q2_score": 0.0003814576058873216}}
{"text": "#pragma once\n\n#include \"CesiumGltf/IExtensionJsonHandler.h\"\n#include \"CesiumGltf/Model.h\"\n#include \"CesiumGltf/ReaderLibrary.h\"\n#include <functional>\n#include <gsl/span>\n#include <map>\n#include <memory>\n#include <optional>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\nnamespace CesiumGltf {\n\nstruct ReaderContext;\n\n/**\n * @brief The result of reading a glTF model with\n * {@link GltfReader::readModel}.\n */\nstruct CESIUMGLTFREADER_API ModelReaderResult {\n  /**\n   * @brief The read model, or std::nullopt if the model could not be read.\n   */\n  std::optional<Model> model;\n\n  /**\n   * @brief Errors, if any, that occurred during the load process.\n   */\n  std::vector<std::string> errors;\n\n  /**\n   * @brief Warnings, if any, that occurred during the load process.\n   */\n  std::vector<std::string> warnings;\n};\n\n/**\n * @brief The result of reading an image with\n * {@link GltfReader::readImage}.\n */\nstruct CESIUMGLTFREADER_API ImageReaderResult {\n\n  /**\n   * @brief The {@link ImageCesium} that was read.\n   *\n   * This will be `std::nullopt` if the image could not be read.\n   */\n  std::optional<ImageCesium> image;\n\n  /**\n   * @brief Error messages that occurred while trying to read the image.\n   */\n  std::vector<std::string> errors;\n\n  /**\n   * @brief Warning messages that occurred while reading the image.\n   */\n  std::vector<std::string> warnings;\n};\n\n/**\n * @brief The state of a glTF extension.\n */\nenum class ExtensionState {\n  /**\n   * @brief The extension is enabled.\n   *\n   * If a statically-typed class is available for the extension, it will be\n   * used. Otherwise the extension will be represented as a\n   * {@link CesiumUtility::JsonValue}.\n   */\n  Enabled,\n\n  /**\n   * @brief The extension is enabled but will always be deserialized as a\n   * {@link CesiumUtility::JsonValue}.\n   *\n   * Even if a statically-typed class is available for the extension, it will\n   * not be used.\n   */\n  JsonOnly,\n\n  /**\n   * @brief The extension is disabled.\n   *\n   * It will not be represented in the loaded model at all.\n   */\n  Disabled\n};\n\n/**\n * @brief Options for how to read a glTF.\n */\nstruct CESIUMGLTFREADER_API ReadModelOptions {\n  /**\n   * @brief Whether data URLs in buffers and images should be automatically\n   * decoded as part of the load process.\n   */\n  bool decodeDataUrls = true;\n\n  /**\n   * @brief Whether data URLs should be cleared after they are successfully\n   * decoded.\n   *\n   * This reduces the memory usage of the model.\n   */\n  bool clearDecodedDataUrls = true;\n\n  /**\n   * @brief Whether embedded images in {@link Model::buffers} should be\n   * automatically decoded as part of the load process.\n   *\n   * The {@link ImageSpec::mimeType} property is ignored, and instead the\n   * [stb_image](https://github.com/nothings/stb) library is used to decode\n   * images in `JPG`, `PNG`, `TGA`, `BMP`, `PSD`, `GIF`, `HDR`, or `PIC` format.\n   */\n  bool decodeEmbeddedImages = true;\n\n  /**\n   * @brief Whether geometry compressed using the `KHR_draco_mesh_compression`\n   * extension should be automatically decoded as part of the load process.\n   */\n  bool decodeDraco = true;\n};\n\n/**\n * @brief Reads glTF models and images.\n */\nclass CESIUMGLTFREADER_API GltfReader {\npublic:\n  /**\n   * @brief Constructs a new instance.\n   */\n  GltfReader();\n\n  /**\n   * @brief Registers an extension for a glTF object.\n   *\n   * @tparam TExtended The glTF object to extend.\n   * @tparam TExtensionHandler The extension's\n   * {@link CesiumJsonReader::JsonHandler}.\n   * @param extensionName The name of the extension.\n   */\n  template <typename TExtended, typename TExtensionHandler>\n  void registerExtension(const std::string& extensionName) {\n    auto it =\n        this->_extensions.emplace(extensionName, ObjectTypeToHandler()).first;\n    it->second.insert_or_assign(\n        TExtended::TypeName,\n        ExtensionReaderFactory([](const ReaderContext& context) {\n          return std::make_unique<TExtensionHandler>(context);\n        }));\n  }\n\n  /**\n   * @brief Registers an extension for a glTF object.\n   *\n   * The extension name is obtained from `TExtensionHandler::ExtensionName`.\n   *\n   * @tparam TExtended The glTF object to extend.\n   * @tparam TExtensionHandler The extension's\n   * {@link CesiumJsonReader::JsonHandler}.\n   */\n  template <typename TExtended, typename TExtensionHandler>\n  void registerExtension() {\n    auto it =\n        this->_extensions\n            .emplace(TExtensionHandler::ExtensionName, ObjectTypeToHandler())\n            .first;\n    it->second.insert_or_assign(\n        TExtended::TypeName,\n        ExtensionHandlerFactory([](const ReaderContext& context) {\n          return std::make_unique<TExtensionHandler>(context);\n        }));\n  }\n\n  /**\n   * @brief Enables or disables a glTF extension.\n   *\n   * By default, all extensions are enabled. When an enabled extension is\n   * encountered in the source glTF, it is read into a statically-typed\n   * extension class, if one is registered, or into a\n   * {@link CesiumUtility::JsonValue} if not.\n   *\n   * When a disabled extension is encountered in the source glTF, it is ignored\n   * completely.\n   *\n   * An extension may also be set to `ExtensionState::JsonOnly`, in which case\n   * it will be read into a {@link CesiumUtility::JsonValue} even if a\n   * statically-typed extension class is registered.\n   *\n   * @param extensionName The name of the extension to be enabled or disabled.\n   * @param newState The new state for the extension.\n   */\n  void\n  setExtensionState(const std::string& extensionName, ExtensionState newState);\n\n  /**\n   * @brief Reads a glTF or binary glTF (GLB) from a buffer.\n   *\n   * @param data The buffer from which to read the glTF.\n   * @param options Options for how to read the glTF.\n   * @return The result of reading the glTF.\n   */\n  ModelReaderResult readModel(\n      const gsl::span<const std::byte>& data,\n      const ReadModelOptions& options = ReadModelOptions()) const;\n\n  /**\n   * @brief Reads an image from a buffer.\n   *\n   * The [stb_image](https://github.com/nothings/stb) library is used to decode\n   * images in `JPG`, `PNG`, `TGA`, `BMP`, `PSD`, `GIF`, `HDR`, or `PIC` format.\n   *\n   * @param data The buffer from which to read the image.\n   * @return The result of reading the image.\n   */\n  ImageReaderResult readImage(const gsl::span<const std::byte>& data) const;\n\n  std::unique_ptr<IExtensionJsonHandler> createExtensionHandler(\n      const ReaderContext& context,\n      const std::string_view& extensionName,\n      const std::string& extendedObjectType) const;\n\nprivate:\n  using ExtensionHandlerFactory =\n      std::function<std::unique_ptr<IExtensionJsonHandler>(\n          const ReaderContext&)>;\n  using ObjectTypeToHandler = std::map<std::string, ExtensionHandlerFactory>;\n  using ExtensionNameMap = std::map<std::string, ObjectTypeToHandler>;\n\n  ExtensionNameMap _extensions;\n  std::unordered_map<std::string, ExtensionState> _extensionStates;\n};\n\n} // namespace CesiumGltf\n", "meta": {"hexsha": "fa2a2bfd812ca0814069c97be685f8b6096d2582", "size": 6962, "ext": "h", "lang": "C", "max_stars_repo_path": "CesiumGltfReader/include/CesiumGltf/GltfReader.h", "max_stars_repo_name": "zrkcode/cesium-native", "max_stars_repo_head_hexsha": "5265a65053542fe02928c272762c6b89fa2b29bb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CesiumGltfReader/include/CesiumGltf/GltfReader.h", "max_issues_repo_name": "zrkcode/cesium-native", "max_issues_repo_head_hexsha": "5265a65053542fe02928c272762c6b89fa2b29bb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CesiumGltfReader/include/CesiumGltf/GltfReader.h", "max_forks_repo_name": "zrkcode/cesium-native", "max_forks_repo_head_hexsha": "5265a65053542fe02928c272762c6b89fa2b29bb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0083333333, "max_line_length": 80, "alphanum_fraction": 0.6847170353, "num_tokens": 1733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.024798161637017424, "lm_q2_score": 0.015189045241637812, "lm_q1q2_score": 0.00037666039901410487}}
{"text": "#ifndef CONSUMER_H\n#define CONSUMER_H\n\n#include <gsl/gsl>\n#include <producer.h>\n\nclass consumer\n{\npublic:\n\n    \n    explicit consumer(gsl::not_null<producer *> p)\n    { p->print_msg(); }\n\n    ~consumer() = default;\n\npublic:\n\n    consumer(consumer &&) noexcept = default;               \n    consumer &operator=(consumer &&) noexcept = default;    \n\n    consumer(const consumer &) = delete;                    \n    consumer &operator=(const consumer &) = delete;         \n};\n\n#endif\n", "meta": {"hexsha": "1222e53dd636c6cc1fc59019a68c2ed0303215d4", "size": 481, "ext": "h", "lang": "C", "max_stars_repo_path": "include/consumer.h", "max_stars_repo_name": "rutujar/ci_helloworld", "max_stars_repo_head_hexsha": "719d990d75f208aeee69be71fa5a6285cef69fb2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/consumer.h", "max_issues_repo_name": "rutujar/ci_helloworld", "max_issues_repo_head_hexsha": "719d990d75f208aeee69be71fa5a6285cef69fb2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/consumer.h", "max_forks_repo_name": "rutujar/ci_helloworld", "max_forks_repo_head_hexsha": "719d990d75f208aeee69be71fa5a6285cef69fb2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.8148148148, "max_line_length": 60, "alphanum_fraction": 0.5904365904, "num_tokens": 107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.01717671102477037, "lm_q2_score": 0.02161533473221898, "lm_q1q2_score": 0.00037128035839900767}}
{"text": "#ifndef EXECUTE_INCLUDE\n#define EXECUTE_INCLUDE\n\n#include <filesystem>\n#include <string>\n#include <vector>\n\n#include <gsl/string_span>\n\n#include \"path.h\"\n\nnamespace execHelper {\nnamespace test {\nnamespace baseUtils {\nnamespace execution {\nusing CommandLine = std::vector<std::string>;\n\nint execute(const CommandLine& commandLine,\n            const Path& workingDir = std::filesystem::current_path()) noexcept;\n} // namespace execution\n} // namespace baseUtils\n} // namespace test\n} // namespace execHelper\n\n#endif /* EXECUTE_INCLUDE */\n", "meta": {"hexsha": "082cf590706c0c409b2cbe60e74541265cd7aca1", "size": 536, "ext": "h", "lang": "C", "max_stars_repo_path": "test/base-utils/include/base-utils/execution.h", "max_stars_repo_name": "exec-helper/source", "max_stars_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-28T13:24:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-28T13:24:30.000Z", "max_issues_repo_path": "test/base-utils/include/base-utils/execution.h", "max_issues_repo_name": "exec-helper/source", "max_issues_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/base-utils/include/base-utils/execution.h", "max_forks_repo_name": "exec-helper/source", "max_forks_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-07-03T11:11:19.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-03T11:11:19.000Z", "avg_line_length": 20.6153846154, "max_line_length": 79, "alphanum_fraction": 0.7406716418, "num_tokens": 110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.0147286121197955, "lm_q2_score": 0.025178838957499283, "lm_q1q2_score": 0.000370849352631803}}
{"text": "#pragma once\n//#include <gsl/string_span>\nnamespace Util {\n\t//static gsl::string_span<> toLower(gsl::string_span<> const&);\n}; // namespace util\n", "meta": {"hexsha": "6bb4743b08bdc06b784e3d6aff7d1830981dc1d8", "size": 145, "ext": "h", "lang": "C", "max_stars_repo_path": "jni/mcpe/util.h", "max_stars_repo_name": "ProtectorYT364/BlockLauncher", "max_stars_repo_head_hexsha": "146a78743f851728a803468083dbd2a68304f923", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 796.0, "max_stars_repo_stars_event_min_datetime": "2015-01-03T04:33:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T10:49:17.000Z", "max_issues_repo_path": "jni/mcpe/util.h", "max_issues_repo_name": "TimScriptov/MCPELauncher", "max_issues_repo_head_hexsha": "75dccc348ef7a136e916a8231f266c62fb71ca96", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1334.0, "max_issues_repo_issues_event_min_datetime": "2015-01-01T07:40:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-18T14:39:44.000Z", "max_forks_repo_path": "jni/mcpe/util.h", "max_forks_repo_name": "TimScriptov/MCPELauncher", "max_forks_repo_head_hexsha": "75dccc348ef7a136e916a8231f266c62fb71ca96", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 233.0, "max_forks_repo_forks_event_min_datetime": "2015-01-11T03:03:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T23:12:33.000Z", "avg_line_length": 24.1666666667, "max_line_length": 64, "alphanum_fraction": 0.7103448276, "num_tokens": 37, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.028007519794676555, "lm_q2_score": 0.013222820075346206, "lm_q1q2_score": 0.0003703383950017054}}
{"text": "#pragma once\n\n#include \"rev/gl/Context.h\"\n#include \"rev/gl/Resource.h\"\n\n#include <gsl/span>\n\nnamespace rev {\n\nusing Buffer = Resource<singleCreate<gl::genBuffers>, singleDestroy<gl::deleteBuffers>>;\n\n} // namespace rev\n", "meta": {"hexsha": "f4fd4547f95588980fc0a1429eea81c639d76b65", "size": 219, "ext": "h", "lang": "C", "max_stars_repo_path": "engine/include/rev/gl/Buffer.h", "max_stars_repo_name": "eyebrowsoffire/rev", "max_stars_repo_head_hexsha": "d8abdf0a0016e309942932c9af9df1f8a2b02448", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "engine/include/rev/gl/Buffer.h", "max_issues_repo_name": "eyebrowsoffire/rev", "max_issues_repo_head_hexsha": "d8abdf0a0016e309942932c9af9df1f8a2b02448", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-01-27T16:52:41.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-27T16:52:41.000Z", "max_forks_repo_path": "engine/include/rev/gl/Buffer.h", "max_forks_repo_name": "eyebrowsoffire/rev", "max_forks_repo_head_hexsha": "d8abdf0a0016e309942932c9af9df1f8a2b02448", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.8461538462, "max_line_length": 88, "alphanum_fraction": 0.7305936073, "num_tokens": 55, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.023330772883014543, "lm_q2_score": 0.015663650865579932, "lm_q1q2_score": 0.00036544508086367957}}
{"text": "#pragma once\n\n#include \"Cesium3DTilesReader/Library.h\"\n\n#include <Cesium3DTiles/Subtree.h>\n#include <CesiumJsonReader/ExtensionReaderContext.h>\n\n#include <gsl/span>\n\n#include <functional>\n#include <memory>\n#include <optional>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\nnamespace Cesium3DTilesReader {\n\n/**\n * @brief The result of reading a subtree with\n * {@link SubtreeReader::readSubtree}.\n */\nstruct CESIUM3DTILESREADER_API SubtreeReaderResult {\n  /**\n   * @brief The read subtree, or std::nullopt if the subtree could not be read.\n   */\n  std::optional<Cesium3DTiles::Subtree> subtree;\n\n  /**\n   * @brief Errors, if any, that occurred during the load process.\n   */\n  std::vector<std::string> errors;\n\n  /**\n   * @brief Warnings, if any, that occurred during the load process.\n   */\n  std::vector<std::string> warnings;\n};\n\n/**\n * @brief Reads subtrees.\n */\nclass CESIUM3DTILESREADER_API SubtreeReader {\npublic:\n  /**\n   * @brief Constructs a new instance.\n   */\n  SubtreeReader();\n\n  /**\n   * @brief Gets the context used to control how extensions are loaded from a\n   * subtree.\n   */\n  CesiumJsonReader::ExtensionReaderContext& getExtensions();\n\n  /**\n   * @brief Gets the context used to control how extensions are loaded from a\n   * subtree.\n   */\n  const CesiumJsonReader::ExtensionReaderContext& getExtensions() const;\n\n  /**\n   * @brief Reads a subtree.\n   *\n   * @param data The buffer from which to read the subtree.\n   * @param options Options for how to read the subtree.\n   * @return The result of reading the subtree.\n   */\n  SubtreeReaderResult readSubtree(const gsl::span<const std::byte>& data) const;\n\nprivate:\n  CesiumJsonReader::ExtensionReaderContext _context;\n};\n\n} // namespace Cesium3DTilesReader\n", "meta": {"hexsha": "1f1d2f64aea0e4ca0464560e43e9fd5fccedd0bb", "size": 1744, "ext": "h", "lang": "C", "max_stars_repo_path": "Cesium3DTilesReader/include/Cesium3DTilesReader/SubtreeReader.h", "max_stars_repo_name": "yieryi/cesium-native", "max_stars_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Cesium3DTilesReader/include/Cesium3DTilesReader/SubtreeReader.h", "max_issues_repo_name": "yieryi/cesium-native", "max_issues_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cesium3DTilesReader/include/Cesium3DTilesReader/SubtreeReader.h", "max_forks_repo_name": "yieryi/cesium-native", "max_forks_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9473684211, "max_line_length": 80, "alphanum_fraction": 0.7075688073, "num_tokens": 438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.029312233295254998, "lm_q2_score": 0.012431653402955802, "lm_q1q2_score": 0.0003643995247931911}}
{"text": "#pragma once\n\n#include \"iobserver.h\"\n#include \"irequest.h\"\n#include <gsl/pointers>\n#include <atomic>\n#include <vector>\n#include <Windows.h>\n\nnamespace died\n{\n\tnamespace observer \n\t{\n\t\tnamespace callback\n\t\t{\n\t\t\tunsigned WINAPI start_thread_proc(LPVOID);\n\t\t\tVOID CALLBACK terminate_proc(__in ULONG_PTR);\n\t\t\tVOID CALLBACK add_directory_proc(__in ULONG_PTR);\n\t\t}\n\t}\n\n\tclass observer_impl final : public iobserver\n\t{\n\tpublic:\n\t\tobserver_impl(idirectory_watcher*);\n\n\t\t// diable copy\n\t\tobserver_impl(observer_impl const&) = delete;\n\t\tobserver_impl& operator=(observer_impl const&) = delete;\n\n\t\t// interface\n\tprivate:\n\t\tunsigned int do_inc_request() final;\n\t\tunsigned int do_dec_request() final;\n\t\tidirectory_watcher* do_get_watcher() const final;\n\n\tprivate:\n\t\tvoid run();\n\t\tbool terminated() const;\n\t\tbool empty_request() const;\n\t\tbool add_directory(irequest* pBlock);\n\t\tvoid request_termination();\n\n\t\tfriend unsigned WINAPI observer::callback::start_thread_proc(LPVOID);\n\t\tfriend VOID CALLBACK observer::callback::terminate_proc(__in ULONG_PTR);\n\t\tfriend VOID CALLBACK observer::callback::add_directory_proc(__in ULONG_PTR);\n\n\tprivate:\n\t\tgsl::not_null<idirectory_watcher*> mDirWatcher;\n\t\tstd::atomic_bool mTerminated{};\n\t\tstd::atomic_uint mOutstandingRequests{};\n\t\tstd::vector<gsl::not_null<irequest*>> mBlocks;\n\t};\n}", "meta": {"hexsha": "bbf72f12d2c2a63b8f03ea23237d0d358318af30", "size": 1311, "ext": "h", "lang": "C", "max_stars_repo_path": "FileWatcherDemo/file_activity/observer_impl.h", "max_stars_repo_name": "pvthuyet/file-watcher-demo", "max_stars_repo_head_hexsha": "37fb2022fb27952db294b253fe2817d4548817bc", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FileWatcherDemo/file_activity/observer_impl.h", "max_issues_repo_name": "pvthuyet/file-watcher-demo", "max_issues_repo_head_hexsha": "37fb2022fb27952db294b253fe2817d4548817bc", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FileWatcherDemo/file_activity/observer_impl.h", "max_forks_repo_name": "pvthuyet/file-watcher-demo", "max_forks_repo_head_hexsha": "37fb2022fb27952db294b253fe2817d4548817bc", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.2777777778, "max_line_length": 78, "alphanum_fraction": 0.7536231884, "num_tokens": 320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.028436030574768477, "lm_q2_score": 0.012624947389222997, "lm_q1q2_score": 0.0003590033899647886}}
{"text": "#ifndef _AVA_COMMON_SUPPORT_STD_SPAN_H_\n#define _AVA_COMMON_SUPPORT_STD_SPAN_H_\n#pragma once\n\n#include <gsl/span>\n#include <gsl/span_ext>\n\nnamespace std {\nusing gsl::span;\n}  // namespace std\n\n#define EMPTY_CHAR_SPAN std::span<const char>()\n\n#define STRING_AS_SPAN(STR_VAR) std::span<const char>((STR_VAR).data(), (STR_VAR).length())\n\n#define VECTOR_AS_SPAN(VEC_VAR) std::span<const decltype(VEC_VAR)::value_type>((VEC_VAR).data(), (VEC_VAR).size())\n\n#define VECTOR_AS_CHAR_SPAN(VEC_VAR)                                      \\\n  std::span<const char>(reinterpret_cast<const char *>((VEC_VAR).data()), \\\n                        sizeof(decltype(VEC_VAR)::value_type) * (VEC_VAR).size())\n\n#endif  // _AVA_COMMON_SUPPORT_STD_SPAN_H_\n", "meta": {"hexsha": "b8866689a561b1bd664830566ae5eb361449b5be", "size": 729, "ext": "h", "lang": "C", "max_stars_repo_path": "common/support/std_span.h", "max_stars_repo_name": "anjuna-security/ava", "max_stars_repo_head_hexsha": "9187a05e99dfadf9711a890a9b0e2760e6e58c66", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2020-01-31T21:25:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-03T23:48:14.000Z", "max_issues_repo_path": "common/support/std_span.h", "max_issues_repo_name": "anjuna-security/ava", "max_issues_repo_head_hexsha": "9187a05e99dfadf9711a890a9b0e2760e6e58c66", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 81.0, "max_issues_repo_issues_event_min_datetime": "2020-03-16T02:47:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-14T12:22:47.000Z", "max_forks_repo_path": "common/support/std_span.h", "max_forks_repo_name": "anjuna-security/ava", "max_forks_repo_head_hexsha": "9187a05e99dfadf9711a890a9b0e2760e6e58c66", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2020-01-31T21:25:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-18T03:35:13.000Z", "avg_line_length": 31.6956521739, "max_line_length": 114, "alphanum_fraction": 0.6913580247, "num_tokens": 180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.02262920069217879, "lm_q2_score": 0.01566364512181629, "lm_q1q2_score": 0.0003544557690326481}}
{"text": "/* GStreamer\n * Copyright (C) <2005> Thomas Vander Stichele <thomas at apestaart dot org>\n * Copyright (C) <2006> Tim-Philipp M\u00fcller <tim centricular net>\n *\n * gstutils.c: Unit test for functions in gstutils\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n */\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include <gst/check/gstcheck.h>\n\n#define SPECIAL_POINTER(x) ((void*)(19283847+(x)))\n\nstatic int n_data_probes = 0;\nstatic int n_buffer_probes = 0;\nstatic int n_event_probes = 0;\n\nstatic GstPadProbeReturn\nprobe_do_nothing (GstPad * pad, GstPadProbeInfo * info, gpointer data)\n{\n  GstMiniObject *obj = GST_PAD_PROBE_INFO_DATA (info);\n  GST_DEBUG_OBJECT (pad, \"is buffer:%d\", GST_IS_BUFFER (obj));\n  return GST_PAD_PROBE_OK;\n}\n\nstatic GstPadProbeReturn\ndata_probe (GstPad * pad, GstPadProbeInfo * info, gpointer data)\n{\n  GstMiniObject *obj = GST_PAD_PROBE_INFO_DATA (info);\n  n_data_probes++;\n  GST_DEBUG_OBJECT (pad, \"data probe %d\", n_data_probes);\n  g_assert (GST_IS_BUFFER (obj) || GST_IS_EVENT (obj));\n  g_assert (data == SPECIAL_POINTER (0));\n  return GST_PAD_PROBE_OK;\n}\n\nstatic GstPadProbeReturn\nbuffer_probe (GstPad * pad, GstPadProbeInfo * info, gpointer data)\n{\n  GstBuffer *obj = GST_PAD_PROBE_INFO_BUFFER (info);\n  n_buffer_probes++;\n  GST_DEBUG_OBJECT (pad, \"buffer probe %d\", n_buffer_probes);\n  g_assert (GST_IS_BUFFER (obj));\n  g_assert (data == SPECIAL_POINTER (1));\n  return GST_PAD_PROBE_OK;\n}\n\nstatic GstPadProbeReturn\nevent_probe (GstPad * pad, GstPadProbeInfo * info, gpointer data)\n{\n  GstEvent *obj = GST_PAD_PROBE_INFO_EVENT (info);\n  n_event_probes++;\n  GST_DEBUG_OBJECT (pad, \"event probe %d [%s]\",\n      n_event_probes, GST_EVENT_TYPE_NAME (obj));\n  g_assert (GST_IS_EVENT (obj));\n  g_assert (data == SPECIAL_POINTER (2));\n  return GST_PAD_PROBE_OK;\n}\n\nGST_START_TEST (test_buffer_probe_n_times)\n{\n  GstElement *pipeline, *fakesrc, *fakesink;\n  GstBus *bus;\n  GstMessage *message;\n  GstPad *pad;\n\n  pipeline = gst_element_factory_make (\"pipeline\", NULL);\n  fakesrc = gst_element_factory_make (\"fakesrc\", NULL);\n  fakesink = gst_element_factory_make (\"fakesink\", NULL);\n\n  g_object_set (fakesrc, \"num-buffers\", (int) 10, NULL);\n\n  gst_bin_add_many (GST_BIN (pipeline), fakesrc, fakesink, NULL);\n  gst_element_link (fakesrc, fakesink);\n\n  pad = gst_element_get_static_pad (fakesink, \"sink\");\n\n  /* add the probes we need for the test */\n  gst_pad_add_probe (pad, GST_PAD_PROBE_TYPE_DATA_BOTH, data_probe,\n      SPECIAL_POINTER (0), NULL);\n  gst_pad_add_probe (pad, GST_PAD_PROBE_TYPE_BUFFER, buffer_probe,\n      SPECIAL_POINTER (1), NULL);\n  gst_pad_add_probe (pad, GST_PAD_PROBE_TYPE_EVENT_BOTH, event_probe,\n      SPECIAL_POINTER (2), NULL);\n\n  /* add some string probes just to test that the data is free'd\n   * properly as it should be */\n  gst_pad_add_probe (pad, GST_PAD_PROBE_TYPE_DATA_BOTH, probe_do_nothing,\n      g_strdup (\"data probe string\"), (GDestroyNotify) g_free);\n  gst_pad_add_probe (pad, GST_PAD_PROBE_TYPE_BUFFER, probe_do_nothing,\n      g_strdup (\"buffer probe string\"), (GDestroyNotify) g_free);\n  gst_pad_add_probe (pad, GST_PAD_PROBE_TYPE_EVENT_BOTH, probe_do_nothing,\n      g_strdup (\"event probe string\"), (GDestroyNotify) g_free);\n\n  gst_object_unref (pad);\n\n  gst_element_set_state (pipeline, GST_STATE_PLAYING);\n\n  bus = gst_element_get_bus (pipeline);\n  message = gst_bus_poll (bus, GST_MESSAGE_EOS, -1);\n  gst_message_unref (message);\n  gst_object_unref (bus);\n\n  g_assert (n_buffer_probes == 10);     /* one for every buffer */\n  g_assert (n_event_probes == 4);       /* stream-start, new segment, latency and eos */\n  g_assert (n_data_probes == 14);       /* duh */\n\n  gst_element_set_state (pipeline, GST_STATE_NULL);\n  gst_object_unref (pipeline);\n\n  /* make sure nothing was sent in addition to the above when shutting down */\n  g_assert (n_buffer_probes == 10);     /* one for every buffer */\n  g_assert (n_event_probes == 4);       /* stream-start, new segment, latency and eos */\n  g_assert (n_data_probes == 14);       /* duh */\n} GST_END_TEST;\n\nstatic int n_data_probes_once = 0;\nstatic int n_buffer_probes_once = 0;\nstatic int n_event_probes_once = 0;\n\nstatic GstPadProbeReturn\ndata_probe_once (GstPad * pad, GstPadProbeInfo * info, guint * data)\n{\n  GstMiniObject *obj = GST_PAD_PROBE_INFO_DATA (info);\n\n  n_data_probes_once++;\n  g_assert (GST_IS_BUFFER (obj) || GST_IS_EVENT (obj));\n\n  gst_pad_remove_probe (pad, *data);\n\n  return GST_PAD_PROBE_OK;\n}\n\nstatic GstPadProbeReturn\nbuffer_probe_once (GstPad * pad, GstPadProbeInfo * info, guint * data)\n{\n  GstBuffer *obj = GST_PAD_PROBE_INFO_BUFFER (info);\n\n  n_buffer_probes_once++;\n  g_assert (GST_IS_BUFFER (obj));\n\n  gst_pad_remove_probe (pad, *data);\n\n  return GST_PAD_PROBE_OK;\n}\n\nstatic GstPadProbeReturn\nevent_probe_once (GstPad * pad, GstPadProbeInfo * info, guint * data)\n{\n  GstEvent *obj = GST_PAD_PROBE_INFO_EVENT (info);\n\n  n_event_probes_once++;\n  g_assert (GST_IS_EVENT (obj));\n\n  gst_pad_remove_probe (pad, *data);\n\n  return GST_PAD_PROBE_OK;\n}\n\nGST_START_TEST (test_buffer_probe_once)\n{\n  GstElement *pipeline, *fakesrc, *fakesink;\n  GstBus *bus;\n  GstMessage *message;\n  GstPad *pad;\n  guint id1, id2, id3;\n\n  pipeline = gst_element_factory_make (\"pipeline\", NULL);\n  fakesrc = gst_element_factory_make (\"fakesrc\", NULL);\n  fakesink = gst_element_factory_make (\"fakesink\", NULL);\n\n  g_object_set (fakesrc, \"num-buffers\", (int) 10, NULL);\n\n  gst_bin_add_many (GST_BIN (pipeline), fakesrc, fakesink, NULL);\n  gst_element_link (fakesrc, fakesink);\n\n  pad = gst_element_get_static_pad (fakesink, \"sink\");\n  id1 =\n      gst_pad_add_probe (pad, GST_PAD_PROBE_TYPE_DATA_BOTH,\n      (GstPadProbeCallback) data_probe_once, &id1, NULL);\n  id2 =\n      gst_pad_add_probe (pad, GST_PAD_PROBE_TYPE_BUFFER,\n      (GstPadProbeCallback) buffer_probe_once, &id2, NULL);\n  id3 =\n      gst_pad_add_probe (pad, GST_PAD_PROBE_TYPE_EVENT_BOTH,\n      (GstPadProbeCallback) event_probe_once, &id3, NULL);\n  gst_object_unref (pad);\n\n  gst_element_set_state (pipeline, GST_STATE_PLAYING);\n\n  bus = gst_element_get_bus (pipeline);\n  message = gst_bus_poll (bus, GST_MESSAGE_EOS, -1);\n  gst_message_unref (message);\n  gst_object_unref (bus);\n\n  gst_element_set_state (pipeline, GST_STATE_NULL);\n  gst_object_unref (pipeline);\n\n  g_assert (n_buffer_probes_once == 1); /* can we hit it and quit? */\n  g_assert (n_event_probes_once == 1);  /* i said, can we hit it and quit? */\n  g_assert (n_data_probes_once == 1);   /* let's hit it and quit!!! */\n} GST_END_TEST;\n\nGST_START_TEST (test_math_scale)\n{\n  fail_if (gst_util_uint64_scale_int (1, 1, 1) != 1);\n\n  fail_if (gst_util_uint64_scale_int (10, 10, 1) != 100);\n  fail_if (gst_util_uint64_scale_int (10, 10, 2) != 50);\n\n  fail_if (gst_util_uint64_scale_int (0, 10, 2) != 0);\n  fail_if (gst_util_uint64_scale_int (0, 0, 2) != 0);\n\n  fail_if (gst_util_uint64_scale_int (G_MAXUINT32, 5, 1) != G_MAXUINT32 * 5LL);\n  fail_if (gst_util_uint64_scale_int (G_MAXUINT32, 10, 2) != G_MAXUINT32 * 5LL);\n\n  fail_if (gst_util_uint64_scale_int (G_MAXUINT32, 1, 5) != G_MAXUINT32 / 5LL);\n  fail_if (gst_util_uint64_scale_int (G_MAXUINT32, 2, 10) != G_MAXUINT32 / 5LL);\n\n  /* not quite overflow */\n  fail_if (gst_util_uint64_scale_int (G_MAXUINT64 - 1, 10,\n          10) != G_MAXUINT64 - 1);\n  fail_if (gst_util_uint64_scale_int (G_MAXUINT64 - 1, G_MAXINT32,\n          G_MAXINT32) != G_MAXUINT64 - 1);\n  fail_if (gst_util_uint64_scale_int (G_MAXUINT64 - 100, G_MAXINT32,\n          G_MAXINT32) != G_MAXUINT64 - 100);\n\n  /* overflow */\n  fail_if (gst_util_uint64_scale_int (G_MAXUINT64 - 1, 10, 1) != G_MAXUINT64);\n  fail_if (gst_util_uint64_scale_int (G_MAXUINT64 - 1, G_MAXINT32,\n          1) != G_MAXUINT64);\n\n} GST_END_TEST;\n\nGST_START_TEST (test_math_scale_round)\n{\n  fail_if (gst_util_uint64_scale_int_round (2, 1, 2) != 1);\n  fail_if (gst_util_uint64_scale_int_round (3, 1, 2) != 2);\n  fail_if (gst_util_uint64_scale_int_round (4, 1, 2) != 2);\n\n  fail_if (gst_util_uint64_scale_int_round (200, 100, 20000) != 1);\n  fail_if (gst_util_uint64_scale_int_round (299, 100, 20000) != 1);\n  fail_if (gst_util_uint64_scale_int_round (300, 100, 20000) != 2);\n  fail_if (gst_util_uint64_scale_int_round (301, 100, 20000) != 2);\n  fail_if (gst_util_uint64_scale_int_round (400, 100, 20000) != 2);\n} GST_END_TEST;\n\nGST_START_TEST (test_math_scale_ceil)\n{\n  fail_if (gst_util_uint64_scale_int_ceil (2, 1, 2) != 1);\n  fail_if (gst_util_uint64_scale_int_ceil (3, 1, 2) != 2);\n  fail_if (gst_util_uint64_scale_int_ceil (4, 1, 2) != 2);\n\n  fail_if (gst_util_uint64_scale_int_ceil (200, 100, 20000) != 1);\n  fail_if (gst_util_uint64_scale_int_ceil (299, 100, 20000) != 2);\n  fail_if (gst_util_uint64_scale_int_ceil (300, 100, 20000) != 2);\n  fail_if (gst_util_uint64_scale_int_ceil (301, 100, 20000) != 2);\n  fail_if (gst_util_uint64_scale_int_ceil (400, 100, 20000) != 2);\n} GST_END_TEST;\n\nGST_START_TEST (test_math_scale_uint64)\n{\n  fail_if (gst_util_uint64_scale (1, 1, 1) != 1);\n\n  fail_if (gst_util_uint64_scale (10, 10, 1) != 100);\n  fail_if (gst_util_uint64_scale (10, 10, 2) != 50);\n\n  fail_if (gst_util_uint64_scale (0, 10, 2) != 0);\n  fail_if (gst_util_uint64_scale (0, 0, 2) != 0);\n\n  fail_if (gst_util_uint64_scale (G_MAXUINT32, 5, 1) != G_MAXUINT32 * 5LL);\n  fail_if (gst_util_uint64_scale (G_MAXUINT32, 10, 2) != G_MAXUINT32 * 5LL);\n\n  fail_if (gst_util_uint64_scale (G_MAXUINT32, 1, 5) != G_MAXUINT32 / 5LL);\n  fail_if (gst_util_uint64_scale (G_MAXUINT32, 2, 10) != G_MAXUINT32 / 5LL);\n\n  /* not quite overflow */\n  fail_if (gst_util_uint64_scale (G_MAXUINT64 - 1, 10, 10) != G_MAXUINT64 - 1);\n  fail_if (gst_util_uint64_scale (G_MAXUINT64 - 1, G_MAXUINT32,\n          G_MAXUINT32) != G_MAXUINT64 - 1);\n  fail_if (gst_util_uint64_scale (G_MAXUINT64 - 100, G_MAXUINT32,\n          G_MAXUINT32) != G_MAXUINT64 - 100);\n\n  fail_if (gst_util_uint64_scale (G_MAXUINT64 - 1, 10, 10) != G_MAXUINT64 - 1);\n  fail_if (gst_util_uint64_scale (G_MAXUINT64 - 1, G_MAXUINT64,\n          G_MAXUINT64) != G_MAXUINT64 - 1);\n  fail_if (gst_util_uint64_scale (G_MAXUINT64 - 100, G_MAXUINT64,\n          G_MAXUINT64) != G_MAXUINT64 - 100);\n\n  /* overflow */\n  fail_if (gst_util_uint64_scale (G_MAXUINT64 - 1, 10, 1) != G_MAXUINT64);\n  fail_if (gst_util_uint64_scale (G_MAXUINT64 - 1, G_MAXUINT64,\n          1) != G_MAXUINT64);\n\n} GST_END_TEST;\n\nGST_START_TEST (test_math_scale_random)\n{\n  guint64 val, num, denom, res;\n  GRand *rand;\n  gint i;\n\n  rand = g_rand_new ();\n\n  i = 100000;\n  while (i--) {\n    guint64 check, diff;\n\n    val = ((guint64) g_rand_int (rand)) << 32 | g_rand_int (rand);\n    num = ((guint64) g_rand_int (rand)) << 32 | g_rand_int (rand);\n    denom = ((guint64) g_rand_int (rand)) << 32 | g_rand_int (rand);\n\n    res = gst_util_uint64_scale (val, num, denom);\n    check = gst_gdouble_to_guint64 (gst_guint64_to_gdouble (val) *\n        gst_guint64_to_gdouble (num) / gst_guint64_to_gdouble (denom));\n\n    if (res < G_MAXUINT64 && check < G_MAXUINT64) {\n      if (res > check)\n        diff = res - check;\n      else\n        diff = check - res;\n\n      /* some arbitrary value, really.. someone do the proper math to get\n       * the upper bound */\n      if (diff > 20000)\n        fail_if (diff > 20000);\n    }\n  }\n  g_rand_free (rand);\n\n}\n\nGST_END_TEST;\n\nGST_START_TEST (test_guint64_to_gdouble)\n{\n  guint64 from[] = { 0, 1, 100, 10000, (guint64) (1) << 63,\n    ((guint64) (1) << 63) + 1,\n    ((guint64) (1) << 63) + (G_GINT64_CONSTANT (1) << 62)\n  };\n  gdouble to[] = { 0., 1., 100., 10000., 9223372036854775808.,\n    9223372036854775809., 13835058055282163712.\n  };\n  gdouble tolerance[] = { 0., 0., 0., 0., 0., 1., 1. };\n  gint i;\n  gdouble result;\n  gdouble delta;\n\n  for (i = 0; i < G_N_ELEMENTS (from); ++i) {\n    result = gst_util_guint64_to_gdouble (from[i]);\n    delta = ABS (to[i] - result);\n    fail_unless (delta <= tolerance[i],\n        \"Could not convert %d: %\" G_GUINT64_FORMAT\n        \" -> %f, got %f instead, delta of %e with tolerance of %e\",\n        i, from[i], to[i], result, delta, tolerance[i]);\n  }\n}\n\nGST_END_TEST;\n\nGST_START_TEST (test_gdouble_to_guint64)\n{\n  gdouble from[] = { 0., 1., 100., 10000., 9223372036854775808.,\n    9223372036854775809., 13835058055282163712.\n  };\n  guint64 to[] = { 0, 1, 100, 10000, (guint64) (1) << 63,\n    ((guint64) (1) << 63) + 1,\n    ((guint64) (1) << 63) + (G_GINT64_CONSTANT (1) << 62)\n  };\n  guint64 tolerance[] = { 0, 0, 0, 0, 0, 1, 1 };\n  gint i;\n  gdouble result;\n  guint64 delta;\n\n  for (i = 0; i < G_N_ELEMENTS (from); ++i) {\n    result = gst_util_gdouble_to_guint64 (from[i]);\n    delta = ABS (to[i] - result);\n    fail_unless (delta <= tolerance[i],\n        \"Could not convert %f: %\" G_GUINT64_FORMAT\n        \" -> %d, got %d instead, delta of %e with tolerance of %e\",\n        i, from[i], to[i], result, delta, tolerance[i]);\n  }\n}\n\nGST_END_TEST;\n\n#ifndef GST_DISABLE_PARSE\nGST_START_TEST (test_parse_bin_from_description)\n{\n  struct\n  {\n    const gchar *bin_desc;\n    const gchar *pad_names;\n  } bin_tests[] = {\n    {\n    \"identity\", \"identity0/sink,identity0/src\"}, {\n    \"identity ! identity ! identity\", \"identity1/sink,identity3/src\"}, {\n    \"identity ! fakesink\", \"identity4/sink\"}, {\n    \"fakesrc ! identity\", \"identity5/src\"}, {\n    \"fakesrc ! fakesink\", \"\"}\n  };\n  gint i;\n\n  for (i = 0; i < G_N_ELEMENTS (bin_tests); ++i) {\n    GstElement *bin, *parent;\n    GString *s;\n    GstPad *ghost_pad, *target_pad;\n    GError *err = NULL;\n\n    bin = gst_parse_bin_from_description (bin_tests[i].bin_desc, TRUE, &err);\n    if (err) {\n      g_error (\"ERROR in gst_parse_bin_from_description (%s): %s\",\n          bin_tests[i].bin_desc, err->message);\n    }\n    g_assert (bin != NULL);\n\n    s = g_string_new (\"\");\n    if ((ghost_pad = gst_element_get_static_pad (bin, \"sink\"))) {\n      g_assert (GST_IS_GHOST_PAD (ghost_pad));\n\n      target_pad = gst_ghost_pad_get_target (GST_GHOST_PAD (ghost_pad));\n      g_assert (target_pad != NULL);\n      g_assert (GST_IS_PAD (target_pad));\n\n      parent = gst_pad_get_parent_element (target_pad);\n      g_assert (parent != NULL);\n\n      g_string_append_printf (s, \"%s/sink\", GST_ELEMENT_NAME (parent));\n\n      gst_object_unref (parent);\n      gst_object_unref (target_pad);\n      gst_object_unref (ghost_pad);\n    }\n\n    if ((ghost_pad = gst_element_get_static_pad (bin, \"src\"))) {\n      g_assert (GST_IS_GHOST_PAD (ghost_pad));\n\n      target_pad = gst_ghost_pad_get_target (GST_GHOST_PAD (ghost_pad));\n      g_assert (target_pad != NULL);\n      g_assert (GST_IS_PAD (target_pad));\n\n      parent = gst_pad_get_parent_element (target_pad);\n      g_assert (parent != NULL);\n\n      if (s->len > 0) {\n        g_string_append (s, \",\");\n      }\n\n      g_string_append_printf (s, \"%s/src\", GST_ELEMENT_NAME (parent));\n\n      gst_object_unref (parent);\n      gst_object_unref (target_pad);\n      gst_object_unref (ghost_pad);\n    }\n\n    if (strcmp (s->str, bin_tests[i].pad_names) != 0) {\n      g_error (\"FAILED: expected '%s', got '%s' for bin '%s'\",\n          bin_tests[i].pad_names, s->str, bin_tests[i].bin_desc);\n    }\n    g_string_free (s, TRUE);\n\n    gst_object_unref (bin);\n  }\n}\n\nGST_END_TEST;\n#endif\n\nGST_START_TEST (test_element_found_tags)\n{\n  GstElement *pipeline, *fakesrc, *fakesink;\n  GstTagList *list;\n  GstBus *bus;\n  GstMessage *message;\n  GstPad *srcpad;\n\n  pipeline = gst_element_factory_make (\"pipeline\", NULL);\n  fakesrc = gst_element_factory_make (\"fakesrc\", NULL);\n  fakesink = gst_element_factory_make (\"fakesink\", NULL);\n  list = gst_tag_list_new_empty ();\n\n  g_object_set (fakesrc, \"num-buffers\", (int) 10, NULL);\n\n  gst_bin_add_many (GST_BIN (pipeline), fakesrc, fakesink, NULL);\n  gst_element_link (fakesrc, fakesink);\n\n  gst_element_set_state (pipeline, GST_STATE_PLAYING);\n\n  srcpad = gst_element_get_static_pad (fakesrc, \"src\");\n  gst_pad_push_event (srcpad, gst_event_new_tag (list));\n  gst_object_unref (srcpad);\n\n  bus = gst_element_get_bus (pipeline);\n  message = gst_bus_poll (bus, GST_MESSAGE_EOS, -1);\n  gst_message_unref (message);\n  gst_object_unref (bus);\n\n  /* FIXME: maybe also check if the fakesink receives the message */\n\n  gst_element_set_state (pipeline, GST_STATE_NULL);\n  gst_object_unref (pipeline);\n}\n\nGST_END_TEST;\n\nGST_START_TEST (test_element_unlink)\n{\n  GstElement *src, *sink;\n\n  src = gst_element_factory_make (\"fakesrc\", NULL);\n  sink = gst_element_factory_make (\"fakesink\", NULL);\n  fail_unless (gst_element_link (src, sink) != FALSE);\n  gst_element_unlink (src, sink);\n  gst_object_unref (src);\n  gst_object_unref (sink);\n}\n\nGST_END_TEST;\n\nGST_START_TEST (test_set_value_from_string)\n{\n  GValue val = { 0, };\n\n  /* g_return_if_fail */\n  ASSERT_CRITICAL (gst_util_set_value_from_string (NULL, \"xyz\"));\n\n  g_value_init (&val, G_TYPE_STRING);\n  ASSERT_CRITICAL (gst_util_set_value_from_string (&val, NULL));\n  g_value_unset (&val);\n\n  /* string => string */\n  g_value_init (&val, G_TYPE_STRING);\n  gst_util_set_value_from_string (&val, \"Y00\");\n  fail_unless (g_value_get_string (&val) != NULL);\n  fail_unless_equals_string (g_value_get_string (&val), \"Y00\");\n  g_value_unset (&val);\n\n  /* string => int */\n  g_value_init (&val, G_TYPE_INT);\n  gst_util_set_value_from_string (&val, \"987654321\");\n  fail_unless (g_value_get_int (&val) == 987654321);\n  g_value_unset (&val);\n\n  g_value_init (&val, G_TYPE_INT);\n  ASSERT_CRITICAL (gst_util_set_value_from_string (&val, \"xyz\"));\n  g_value_unset (&val);\n\n  /* string => uint */\n  g_value_init (&val, G_TYPE_UINT);\n  gst_util_set_value_from_string (&val, \"987654321\");\n  fail_unless (g_value_get_uint (&val) == 987654321);\n  g_value_unset (&val);\n\n  /* CHECKME: is this really desired behaviour? (tpm) */\n  g_value_init (&val, G_TYPE_UINT);\n  gst_util_set_value_from_string (&val, \"-999\");\n  fail_unless (g_value_get_uint (&val) == ((guint) 0 - (guint) 999));\n  g_value_unset (&val);\n\n  g_value_init (&val, G_TYPE_UINT);\n  ASSERT_CRITICAL (gst_util_set_value_from_string (&val, \"xyz\"));\n  g_value_unset (&val);\n\n  /* string => long */\n  g_value_init (&val, G_TYPE_LONG);\n  gst_util_set_value_from_string (&val, \"987654321\");\n  fail_unless (g_value_get_long (&val) == 987654321);\n  g_value_unset (&val);\n\n  g_value_init (&val, G_TYPE_LONG);\n  ASSERT_CRITICAL (gst_util_set_value_from_string (&val, \"xyz\"));\n  g_value_unset (&val);\n\n  /* string => ulong */\n  g_value_init (&val, G_TYPE_ULONG);\n  gst_util_set_value_from_string (&val, \"987654321\");\n  fail_unless (g_value_get_ulong (&val) == 987654321);\n  g_value_unset (&val);\n\n  /* CHECKME: is this really desired behaviour? (tpm) */\n  g_value_init (&val, G_TYPE_ULONG);\n  gst_util_set_value_from_string (&val, \"-999\");\n  fail_unless (g_value_get_ulong (&val) == ((gulong) 0 - (gulong) 999));\n  g_value_unset (&val);\n\n  g_value_init (&val, G_TYPE_ULONG);\n  ASSERT_CRITICAL (gst_util_set_value_from_string (&val, \"xyz\"));\n  g_value_unset (&val);\n\n  /* string => boolean */\n  g_value_init (&val, G_TYPE_BOOLEAN);\n  gst_util_set_value_from_string (&val, \"true\");\n  fail_unless_equals_int (g_value_get_boolean (&val), TRUE);\n  g_value_unset (&val);\n\n  g_value_init (&val, G_TYPE_BOOLEAN);\n  gst_util_set_value_from_string (&val, \"TRUE\");\n  fail_unless_equals_int (g_value_get_boolean (&val), TRUE);\n  g_value_unset (&val);\n\n  g_value_init (&val, G_TYPE_BOOLEAN);\n  gst_util_set_value_from_string (&val, \"false\");\n  fail_unless_equals_int (g_value_get_boolean (&val), FALSE);\n  g_value_unset (&val);\n\n  g_value_init (&val, G_TYPE_BOOLEAN);\n  gst_util_set_value_from_string (&val, \"FALSE\");\n  fail_unless_equals_int (g_value_get_boolean (&val), FALSE);\n  g_value_unset (&val);\n\n  g_value_init (&val, G_TYPE_BOOLEAN);\n  gst_util_set_value_from_string (&val, \"bleh\");\n  fail_unless_equals_int (g_value_get_boolean (&val), FALSE);\n  g_value_unset (&val);\n\n#if 0\n  /* string => float (yay, localisation issues involved) */\n  g_value_init (&val, G_TYPE_FLOAT);\n  gst_util_set_value_from_string (&val, \"987.654\");\n  fail_unless (g_value_get_float (&val) >= 987.653 &&\n      g_value_get_float (&val) <= 987.655);\n  g_value_unset (&val);\n\n  g_value_init (&val, G_TYPE_FLOAT);\n  gst_util_set_value_from_string (&val, \"987,654\");\n  fail_unless (g_value_get_float (&val) >= 987.653 &&\n      g_value_get_float (&val) <= 987.655);\n  g_value_unset (&val);\n\n  /* string => double (yay, localisation issues involved) */\n  g_value_init (&val, G_TYPE_DOUBLE);\n  gst_util_set_value_from_string (&val, \"987.654\");\n  fail_unless (g_value_get_double (&val) >= 987.653 &&\n      g_value_get_double (&val) <= 987.655);\n  g_value_unset (&val);\n\n  g_value_init (&val, G_TYPE_DOUBLE);\n  gst_util_set_value_from_string (&val, \"987,654\");\n  fail_unless (g_value_get_double (&val) >= 987.653 &&\n      g_value_get_double (&val) <= 987.655);\n  g_value_unset (&val);\n#endif\n}\n\nGST_END_TEST;\n\nstatic gint\n_binary_search_compare (guint32 * a, guint32 * b)\n{\n  return *a - *b;\n}\n\nGST_START_TEST (test_binary_search)\n{\n  guint32 data[257];\n  guint32 *match;\n  guint32 search_element = 121 * 2;\n  guint i;\n\n  for (i = 0; i < 257; i++)\n    data[i] = (i + 1) * 2;\n\n  match =\n      (guint32 *) gst_util_array_binary_search (data, 257, sizeof (guint32),\n      (GCompareDataFunc) _binary_search_compare, GST_SEARCH_MODE_EXACT,\n      &search_element, NULL);\n  fail_unless (match != NULL);\n  fail_unless_equals_int (match - data, 120);\n\n  match =\n      (guint32 *) gst_util_array_binary_search (data, 257, sizeof (guint32),\n      (GCompareDataFunc) _binary_search_compare, GST_SEARCH_MODE_BEFORE,\n      &search_element, NULL);\n  fail_unless (match != NULL);\n  fail_unless_equals_int (match - data, 120);\n\n  match =\n      (guint32 *) gst_util_array_binary_search (data, 257, sizeof (guint32),\n      (GCompareDataFunc) _binary_search_compare, GST_SEARCH_MODE_AFTER,\n      &search_element, NULL);\n  fail_unless (match != NULL);\n  fail_unless_equals_int (match - data, 120);\n\n  search_element = 0;\n  match =\n      (guint32 *) gst_util_array_binary_search (data, 257, sizeof (guint32),\n      (GCompareDataFunc) _binary_search_compare, GST_SEARCH_MODE_EXACT,\n      &search_element, NULL);\n  fail_unless (match == NULL);\n\n  match =\n      (guint32 *) gst_util_array_binary_search (data, 257, sizeof (guint32),\n      (GCompareDataFunc) _binary_search_compare, GST_SEARCH_MODE_AFTER,\n      &search_element, NULL);\n  fail_unless (match != NULL);\n  fail_unless_equals_int (match - data, 0);\n\n  match =\n      (guint32 *) gst_util_array_binary_search (data, 257, sizeof (guint32),\n      (GCompareDataFunc) _binary_search_compare, GST_SEARCH_MODE_BEFORE,\n      &search_element, NULL);\n  fail_unless (match == NULL);\n\n  search_element = 1000;\n  match =\n      (guint32 *) gst_util_array_binary_search (data, 257, sizeof (guint32),\n      (GCompareDataFunc) _binary_search_compare, GST_SEARCH_MODE_EXACT,\n      &search_element, NULL);\n  fail_unless (match == NULL);\n\n  match =\n      (guint32 *) gst_util_array_binary_search (data, 257, sizeof (guint32),\n      (GCompareDataFunc) _binary_search_compare, GST_SEARCH_MODE_AFTER,\n      &search_element, NULL);\n  fail_unless (match == NULL);\n\n  match =\n      (guint32 *) gst_util_array_binary_search (data, 257, sizeof (guint32),\n      (GCompareDataFunc) _binary_search_compare, GST_SEARCH_MODE_BEFORE,\n      &search_element, NULL);\n  fail_unless (match != NULL);\n  fail_unless_equals_int (match - data, 256);\n\n  search_element = 121 * 2 - 1;\n  match =\n      (guint32 *) gst_util_array_binary_search (data, 257, sizeof (guint32),\n      (GCompareDataFunc) _binary_search_compare, GST_SEARCH_MODE_EXACT,\n      &search_element, NULL);\n  fail_unless (match == NULL);\n\n  match =\n      (guint32 *) gst_util_array_binary_search (data, 257, sizeof (guint32),\n      (GCompareDataFunc) _binary_search_compare, GST_SEARCH_MODE_AFTER,\n      &search_element, NULL);\n  fail_unless (match != NULL);\n  fail_unless_equals_int (match - data, 120);\n\n  match =\n      (guint32 *) gst_util_array_binary_search (data, 257, sizeof (guint32),\n      (GCompareDataFunc) _binary_search_compare, GST_SEARCH_MODE_BEFORE,\n      &search_element, NULL);\n  fail_unless (match != NULL);\n  fail_unless_equals_int (match - data, 119);\n\n}\n\nGST_END_TEST;\n\n#ifdef HAVE_GSL\n#ifdef HAVE_GMP\n\n#include <gsl/gsl_rng.h>\n#include <gmp.h>\n\nstatic guint64\nrandguint64 (gsl_rng * rng, guint64 n)\n{\n  union\n  {\n    guint64 x;\n    struct\n    {\n      guint16 a, b, c, d;\n    } parts;\n  } x;\n  x.parts.a = gsl_rng_uniform_int (rng, 1 << 16);\n  x.parts.b = gsl_rng_uniform_int (rng, 1 << 16);\n  x.parts.c = gsl_rng_uniform_int (rng, 1 << 16);\n  x.parts.d = gsl_rng_uniform_int (rng, 1 << 16);\n  return x.x % n;\n}\n\n\nenum round_t\n{\n  ROUND_TONEAREST = 0,\n  ROUND_UP,\n  ROUND_DOWN\n};\n\nstatic void\ngmp_set_uint64 (mpz_t mp, guint64 x)\n{\n  mpz_t two_32, tmp;\n\n  mpz_init (two_32);\n  mpz_init (tmp);\n\n  mpz_ui_pow_ui (two_32, 2, 32);\n  mpz_set_ui (mp, (unsigned long) ((x >> 32) & G_MAXUINT32));\n  mpz_mul (tmp, mp, two_32);\n  mpz_add_ui (mp, tmp, (unsigned long) (x & G_MAXUINT32));\n  mpz_clear (two_32);\n  mpz_clear (tmp);\n}\n\nstatic guint64\ngmp_get_uint64 (mpz_t mp)\n{\n  mpz_t two_64, two_32, tmp;\n  guint64 ret;\n\n  mpz_init (two_64);\n  mpz_init (two_32);\n  mpz_init (tmp);\n\n  mpz_ui_pow_ui (two_64, 2, 64);\n  mpz_ui_pow_ui (two_32, 2, 32);\n  if (mpz_cmp (tmp, two_64) >= 0)\n    return G_MAXUINT64;\n  mpz_clear (two_64);\n\n  mpz_tdiv_q (tmp, mp, two_32);\n  ret = mpz_get_ui (tmp);\n  ret <<= 32;\n  ret |= mpz_get_ui (mp);\n  mpz_clear (two_32);\n  mpz_clear (tmp);\n\n  return ret;\n}\n\nstatic guint64\ngmp_scale (guint64 x, guint64 a, guint64 b, enum round_t mode)\n{\n  mpz_t mp1, mp2, mp3;\n  if (!b)\n    /* overflow */\n    return G_MAXUINT64;\n  mpz_init (mp1);\n  mpz_init (mp2);\n  mpz_init (mp3);\n\n  gmp_set_uint64 (mp1, x);\n  gmp_set_uint64 (mp3, a);\n  mpz_mul (mp2, mp1, mp3);\n  switch (mode) {\n    case ROUND_TONEAREST:\n      gmp_set_uint64 (mp1, b);\n      mpz_tdiv_q_ui (mp3, mp1, 2);\n      mpz_add (mp1, mp2, mp3);\n      mpz_set (mp2, mp1);\n      break;\n    case ROUND_UP:\n      gmp_set_uint64 (mp1, b);\n      mpz_sub_ui (mp3, mp1, 1);\n      mpz_add (mp1, mp2, mp3);\n      mpz_set (mp2, mp1);\n      break;\n    case ROUND_DOWN:\n      break;\n  }\n  gmp_set_uint64 (mp3, b);\n  mpz_tdiv_q (mp1, mp2, mp3);\n  x = gmp_get_uint64 (mp1);\n  mpz_clear (mp1);\n  mpz_clear (mp2);\n  mpz_clear (mp3);\n  return x;\n}\n\nstatic void\n_gmp_test_scale (gsl_rng * rng)\n{\n  guint64 bygst, bygmp;\n  guint64 a = randguint64 (rng, gsl_rng_uniform_int (rng,\n          2) ? G_MAXUINT64 : G_MAXUINT32);\n  guint64 b = randguint64 (rng, gsl_rng_uniform_int (rng, 2) ? G_MAXUINT64 - 1 : G_MAXUINT32 - 1) + 1;  /* 0 not allowed */\n  guint64 val = randguint64 (rng, gmp_scale (G_MAXUINT64, b, a, ROUND_DOWN));\n  enum round_t mode = gsl_rng_uniform_int (rng, 3);\n  const char *func;\n\n  bygmp = gmp_scale (val, a, b, mode);\n  switch (mode) {\n    case ROUND_TONEAREST:\n      bygst = gst_util_uint64_scale_round (val, a, b);\n      func = \"gst_util_uint64_scale_round\";\n      break;\n    case ROUND_UP:\n      bygst = gst_util_uint64_scale_ceil (val, a, b);\n      func = \"gst_util_uint64_scale_ceil\";\n      break;\n    case ROUND_DOWN:\n      bygst = gst_util_uint64_scale (val, a, b);\n      func = \"gst_util_uint64_scale\";\n      break;\n    default:\n      g_assert_not_reached ();\n      break;\n  }\n  fail_unless (bygst == bygmp,\n      \"error: %s(): %\" G_GUINT64_FORMAT \" * %\" G_GUINT64_FORMAT \" / %\"\n      G_GUINT64_FORMAT \" = %\" G_GUINT64_FORMAT \", correct = %\" G_GUINT64_FORMAT\n      \"\\n\", func, val, a, b, bygst, bygmp);\n}\n\nstatic void\n_gmp_test_scale_int (gsl_rng * rng)\n{\n  guint64 bygst, bygmp;\n  gint32 a = randguint64 (rng, G_MAXINT32);\n  gint32 b = randguint64 (rng, G_MAXINT32 - 1) + 1;     /* 0 not allowed */\n  guint64 val = randguint64 (rng, gmp_scale (G_MAXUINT64, b, a, ROUND_DOWN));\n  enum round_t mode = gsl_rng_uniform_int (rng, 3);\n  const char *func;\n\n  bygmp = gmp_scale (val, a, b, mode);\n  switch (mode) {\n    case ROUND_TONEAREST:\n      bygst = gst_util_uint64_scale_int_round (val, a, b);\n      func = \"gst_util_uint64_scale_int_round\";\n      break;\n    case ROUND_UP:\n      bygst = gst_util_uint64_scale_int_ceil (val, a, b);\n      func = \"gst_util_uint64_scale_int_ceil\";\n      break;\n    case ROUND_DOWN:\n      bygst = gst_util_uint64_scale_int (val, a, b);\n      func = \"gst_util_uint64_scale_int\";\n      break;\n    default:\n      g_assert_not_reached ();\n      break;\n  }\n  fail_unless (bygst == bygmp,\n      \"error: %s(): %\" G_GUINT64_FORMAT \" * %d / %d = %\" G_GUINT64_FORMAT\n      \", correct = %\" G_GUINT64_FORMAT \"\\n\", func, val, a, b, bygst, bygmp);\n}\n\n#define GMP_TEST_RUNS 100000\n\nGST_START_TEST (test_math_scale_gmp)\n{\n  gsl_rng *rng = gsl_rng_alloc (gsl_rng_mt19937);\n  gint n;\n\n  for (n = 0; n < GMP_TEST_RUNS; n++)\n    _gmp_test_scale (rng);\n\n  gsl_rng_free (rng);\n}\n\nGST_END_TEST;\n\nGST_START_TEST (test_math_scale_gmp_int)\n{\n  gsl_rng *rng = gsl_rng_alloc (gsl_rng_mt19937);\n  gint n;\n\n  for (n = 0; n < GMP_TEST_RUNS; n++)\n    _gmp_test_scale_int (rng);\n\n  gsl_rng_free (rng);\n}\n\nGST_END_TEST;\n\n#endif\n#endif\n\nGST_START_TEST (test_pad_proxy_query_caps_aggregation)\n{\n  GstElement *tee, *sink1, *sink2;\n  GstCaps *caps;\n  GstPad *tee_src1, *tee_src2, *tee_sink, *sink1_sink, *sink2_sink;\n\n  tee = gst_element_factory_make (\"tee\", \"tee\");\n\n  sink1 = gst_element_factory_make (\"fakesink\", \"sink1\");\n  tee_src1 = gst_element_get_request_pad (tee, \"src_%u\");\n  sink1_sink = gst_element_get_static_pad (sink1, \"sink\");\n  fail_unless_equals_int (gst_pad_link (tee_src1, sink1_sink), GST_PAD_LINK_OK);\n\n  sink2 = gst_element_factory_make (\"fakesink\", \"sink2\");\n  tee_src2 = gst_element_get_request_pad (tee, \"src_%u\");\n  sink2_sink = gst_element_get_static_pad (sink2, \"sink\");\n  fail_unless_equals_int (gst_pad_link (tee_src2, sink2_sink), GST_PAD_LINK_OK);\n\n  tee_sink = gst_element_get_static_pad (tee, \"sink\");\n\n  gst_element_set_state (sink1, GST_STATE_PAUSED);\n  gst_element_set_state (sink2, GST_STATE_PAUSED);\n  gst_element_set_state (tee, GST_STATE_PAUSED);\n\n  /* by default, ANY caps should intersect to ANY */\n  caps = gst_pad_query_caps (tee_sink, NULL);\n  GST_INFO (\"got caps: %\" GST_PTR_FORMAT, caps);\n  fail_unless (caps != NULL);\n  fail_unless (gst_caps_is_any (caps));\n  gst_caps_unref (caps);\n\n  /* these don't intersect we should get empty caps */\n  caps = gst_caps_new_empty_simple (\"foo/bar\");\n  fail_unless (gst_pad_set_caps (sink1_sink, caps));\n  gst_pad_use_fixed_caps (sink1_sink);\n  gst_caps_unref (caps);\n\n  caps = gst_caps_new_empty_simple (\"bar/ter\");\n  fail_unless (gst_pad_set_caps (sink2_sink, caps));\n  gst_pad_use_fixed_caps (sink2_sink);\n  gst_caps_unref (caps);\n\n  caps = gst_pad_query_caps (tee_sink, NULL);\n  GST_INFO (\"got caps: %\" GST_PTR_FORMAT, caps);\n  fail_unless (caps != NULL);\n  fail_unless (gst_caps_is_empty (caps));\n  gst_caps_unref (caps);\n\n  /* test intersection */\n  caps = gst_caps_new_simple (\"foo/bar\", \"barversion\", G_TYPE_INT, 1, NULL);\n  GST_OBJECT_FLAG_UNSET (sink2_sink, GST_PAD_FLAG_FIXED_CAPS);\n  fail_unless (gst_pad_set_caps (sink2_sink, caps));\n  gst_pad_use_fixed_caps (sink2_sink);\n  gst_caps_unref (caps);\n\n  caps = gst_pad_query_caps (tee_sink, NULL);\n  GST_INFO (\"got caps: %\" GST_PTR_FORMAT, caps);\n  fail_unless (caps != NULL);\n  fail_if (gst_caps_is_empty (caps));\n  {\n    GstStructure *s = gst_caps_get_structure (caps, 0);\n\n    fail_unless_equals_string (gst_structure_get_name (s), \"foo/bar\");\n    fail_unless (gst_structure_has_field_typed (s, \"barversion\", G_TYPE_INT));\n  }\n  gst_caps_unref (caps);\n\n  gst_element_set_state (sink1, GST_STATE_NULL);\n  gst_element_set_state (sink2, GST_STATE_NULL);\n  gst_element_set_state (tee, GST_STATE_NULL);\n\n  /* clean up */\n  gst_element_release_request_pad (tee, tee_src1);\n  gst_object_unref (tee_src1);\n  gst_element_release_request_pad (tee, tee_src2);\n  gst_object_unref (tee_src2);\n  gst_object_unref (tee_sink);\n  gst_object_unref (tee);\n  gst_object_unref (sink1_sink);\n  gst_object_unref (sink1);\n  gst_object_unref (sink2_sink);\n  gst_object_unref (sink2);\n}\n\nGST_END_TEST;\n\nGST_START_TEST (test_greatest_common_divisor)\n{\n  fail_if (gst_util_greatest_common_divisor (1, 1) != 1);\n  fail_if (gst_util_greatest_common_divisor (2, 3) != 1);\n  fail_if (gst_util_greatest_common_divisor (3, 5) != 1);\n  fail_if (gst_util_greatest_common_divisor (-1, 1) != 1);\n  fail_if (gst_util_greatest_common_divisor (-2, 3) != 1);\n  fail_if (gst_util_greatest_common_divisor (-3, 5) != 1);\n  fail_if (gst_util_greatest_common_divisor (-1, -1) != 1);\n  fail_if (gst_util_greatest_common_divisor (-2, -3) != 1);\n  fail_if (gst_util_greatest_common_divisor (-3, -5) != 1);\n  fail_if (gst_util_greatest_common_divisor (1, -1) != 1);\n  fail_if (gst_util_greatest_common_divisor (2, -3) != 1);\n  fail_if (gst_util_greatest_common_divisor (3, -5) != 1);\n  fail_if (gst_util_greatest_common_divisor (2, 2) != 2);\n  fail_if (gst_util_greatest_common_divisor (2, 4) != 2);\n  fail_if (gst_util_greatest_common_divisor (1001, 11) != 11);\n\n}\n\nGST_END_TEST;\n\nGST_START_TEST (test_read_macros)\n{\n  guint8 carray[] = \"ABCDEFGH\"; /* 0x41 ... 0x48 */\n  guint32 uarray[2];\n  guint8 *cpointer;\n\n  memcpy (uarray, carray, 8);\n  cpointer = carray;\n\n  /* 16 bit */\n  /* First try the standard pointer variants */\n  fail_unless_equals_int_hex (GST_READ_UINT16_BE (cpointer), 0x4142);\n  fail_unless_equals_int_hex (GST_READ_UINT16_BE (cpointer + 1), 0x4243);\n  fail_unless_equals_int_hex (GST_READ_UINT16_BE (cpointer + 2), 0x4344);\n  fail_unless_equals_int_hex (GST_READ_UINT16_BE (cpointer + 3), 0x4445);\n  fail_unless_equals_int_hex (GST_READ_UINT16_BE (cpointer + 4), 0x4546);\n  fail_unless_equals_int_hex (GST_READ_UINT16_BE (cpointer + 5), 0x4647);\n  fail_unless_equals_int_hex (GST_READ_UINT16_BE (cpointer + 6), 0x4748);\n\n  fail_unless_equals_int_hex (GST_READ_UINT16_LE (cpointer), 0x4241);\n  fail_unless_equals_int_hex (GST_READ_UINT16_LE (cpointer + 1), 0x4342);\n  fail_unless_equals_int_hex (GST_READ_UINT16_LE (cpointer + 2), 0x4443);\n  fail_unless_equals_int_hex (GST_READ_UINT16_LE (cpointer + 3), 0x4544);\n  fail_unless_equals_int_hex (GST_READ_UINT16_LE (cpointer + 4), 0x4645);\n  fail_unless_equals_int_hex (GST_READ_UINT16_LE (cpointer + 5), 0x4746);\n  fail_unless_equals_int_hex (GST_READ_UINT16_LE (cpointer + 6), 0x4847);\n\n  /* On an array of guint8 */\n  fail_unless_equals_int_hex (GST_READ_UINT16_BE (carray), 0x4142);\n  fail_unless_equals_int_hex (GST_READ_UINT16_BE (carray + 1), 0x4243);\n  fail_unless_equals_int_hex (GST_READ_UINT16_BE (carray + 2), 0x4344);\n  fail_unless_equals_int_hex (GST_READ_UINT16_BE (carray + 3), 0x4445);\n  fail_unless_equals_int_hex (GST_READ_UINT16_BE (carray + 4), 0x4546);\n  fail_unless_equals_int_hex (GST_READ_UINT16_BE (carray + 5), 0x4647);\n  fail_unless_equals_int_hex (GST_READ_UINT16_BE (carray + 6), 0x4748);\n\n  fail_unless_equals_int_hex (GST_READ_UINT16_LE (carray), 0x4241);\n  fail_unless_equals_int_hex (GST_READ_UINT16_LE (carray + 1), 0x4342);\n  fail_unless_equals_int_hex (GST_READ_UINT16_LE (carray + 2), 0x4443);\n  fail_unless_equals_int_hex (GST_READ_UINT16_LE (carray + 3), 0x4544);\n  fail_unless_equals_int_hex (GST_READ_UINT16_LE (carray + 4), 0x4645);\n  fail_unless_equals_int_hex (GST_READ_UINT16_LE (carray + 5), 0x4746);\n  fail_unless_equals_int_hex (GST_READ_UINT16_LE (carray + 6), 0x4847);\n\n  /* On an array of guint32 */\n  fail_unless_equals_int_hex (GST_READ_UINT16_BE (uarray), 0x4142);\n  fail_unless_equals_int_hex (GST_READ_UINT16_BE (uarray + 1), 0x4546);\n\n  fail_unless_equals_int_hex (GST_READ_UINT16_LE (uarray), 0x4241);\n  fail_unless_equals_int_hex (GST_READ_UINT16_LE (uarray + 1), 0x4645);\n\n\n  /* 24bit */\n  /* First try the standard pointer variants */\n  fail_unless_equals_int_hex (GST_READ_UINT24_BE (cpointer), 0x414243);\n  fail_unless_equals_int_hex (GST_READ_UINT24_BE (cpointer + 1), 0x424344);\n  fail_unless_equals_int_hex (GST_READ_UINT24_BE (cpointer + 2), 0x434445);\n  fail_unless_equals_int_hex (GST_READ_UINT24_BE (cpointer + 3), 0x444546);\n  fail_unless_equals_int_hex (GST_READ_UINT24_BE (cpointer + 4), 0x454647);\n  fail_unless_equals_int_hex (GST_READ_UINT24_BE (cpointer + 5), 0x464748);\n\n  fail_unless_equals_int_hex (GST_READ_UINT24_LE (cpointer), 0x434241);\n  fail_unless_equals_int_hex (GST_READ_UINT24_LE (cpointer + 1), 0x444342);\n  fail_unless_equals_int_hex (GST_READ_UINT24_LE (cpointer + 2), 0x454443);\n  fail_unless_equals_int_hex (GST_READ_UINT24_LE (cpointer + 3), 0x464544);\n  fail_unless_equals_int_hex (GST_READ_UINT24_LE (cpointer + 4), 0x474645);\n  fail_unless_equals_int_hex (GST_READ_UINT24_LE (cpointer + 5), 0x484746);\n\n  /* On an array of guint8 */\n  fail_unless_equals_int_hex (GST_READ_UINT24_BE (carray), 0x414243);\n  fail_unless_equals_int_hex (GST_READ_UINT24_BE (carray + 1), 0x424344);\n  fail_unless_equals_int_hex (GST_READ_UINT24_BE (carray + 2), 0x434445);\n  fail_unless_equals_int_hex (GST_READ_UINT24_BE (carray + 3), 0x444546);\n  fail_unless_equals_int_hex (GST_READ_UINT24_BE (carray + 4), 0x454647);\n  fail_unless_equals_int_hex (GST_READ_UINT24_BE (carray + 5), 0x464748);\n\n  fail_unless_equals_int_hex (GST_READ_UINT24_LE (carray), 0x434241);\n  fail_unless_equals_int_hex (GST_READ_UINT24_LE (carray + 1), 0x444342);\n  fail_unless_equals_int_hex (GST_READ_UINT24_LE (carray + 2), 0x454443);\n  fail_unless_equals_int_hex (GST_READ_UINT24_LE (carray + 3), 0x464544);\n  fail_unless_equals_int_hex (GST_READ_UINT24_LE (carray + 4), 0x474645);\n  fail_unless_equals_int_hex (GST_READ_UINT24_LE (carray + 5), 0x484746);\n\n  /* On an array of guint32 */\n  fail_unless_equals_int_hex (GST_READ_UINT24_BE (uarray), 0x414243);\n  fail_unless_equals_int_hex (GST_READ_UINT24_BE (uarray + 1), 0x454647);\n\n  fail_unless_equals_int_hex (GST_READ_UINT24_LE (uarray), 0x434241);\n  fail_unless_equals_int_hex (GST_READ_UINT24_LE (uarray + 1), 0x474645);\n\n\n  /* 32bit */\n  /* First try the standard pointer variants */\n  fail_unless_equals_int_hex (GST_READ_UINT32_BE (cpointer), 0x41424344);\n  fail_unless_equals_int_hex (GST_READ_UINT32_BE (cpointer + 1), 0x42434445);\n  fail_unless_equals_int_hex (GST_READ_UINT32_BE (cpointer + 2), 0x43444546);\n  fail_unless_equals_int_hex (GST_READ_UINT32_BE (cpointer + 3), 0x44454647);\n  fail_unless_equals_int_hex (GST_READ_UINT32_BE (cpointer + 4), 0x45464748);\n\n  fail_unless_equals_int_hex (GST_READ_UINT32_LE (cpointer), 0x44434241);\n  fail_unless_equals_int_hex (GST_READ_UINT32_LE (cpointer + 1), 0x45444342);\n  fail_unless_equals_int_hex (GST_READ_UINT32_LE (cpointer + 2), 0x46454443);\n  fail_unless_equals_int_hex (GST_READ_UINT32_LE (cpointer + 3), 0x47464544);\n  fail_unless_equals_int_hex (GST_READ_UINT32_LE (cpointer + 4), 0x48474645);\n\n  /* On an array of guint8 */\n  fail_unless_equals_int_hex (GST_READ_UINT32_BE (carray), 0x41424344);\n  fail_unless_equals_int_hex (GST_READ_UINT32_BE (carray + 1), 0x42434445);\n  fail_unless_equals_int_hex (GST_READ_UINT32_BE (carray + 2), 0x43444546);\n  fail_unless_equals_int_hex (GST_READ_UINT32_BE (carray + 3), 0x44454647);\n  fail_unless_equals_int_hex (GST_READ_UINT32_BE (carray + 4), 0x45464748);\n\n  fail_unless_equals_int_hex (GST_READ_UINT32_LE (carray), 0x44434241);\n  fail_unless_equals_int_hex (GST_READ_UINT32_LE (carray + 1), 0x45444342);\n  fail_unless_equals_int_hex (GST_READ_UINT32_LE (carray + 2), 0x46454443);\n  fail_unless_equals_int_hex (GST_READ_UINT32_LE (carray + 3), 0x47464544);\n  fail_unless_equals_int_hex (GST_READ_UINT32_LE (carray + 4), 0x48474645);\n\n  /* On an array of guint32 */\n  fail_unless_equals_int_hex (GST_READ_UINT32_BE (uarray), 0x41424344);\n  fail_unless_equals_int_hex (GST_READ_UINT32_BE (uarray + 1), 0x45464748);\n\n  fail_unless_equals_int_hex (GST_READ_UINT32_LE (uarray), 0x44434241);\n  fail_unless_equals_int_hex (GST_READ_UINT32_LE (uarray + 1), 0x48474645);\n\n\n  /* 64bit */\n  fail_unless_equals_int64_hex (GST_READ_UINT64_BE (cpointer),\n      0x4142434445464748);\n  fail_unless_equals_int64_hex (GST_READ_UINT64_LE (cpointer),\n      0x4847464544434241);\n\n  fail_unless_equals_int64_hex (GST_READ_UINT64_BE (carray),\n      0x4142434445464748);\n  fail_unless_equals_int64_hex (GST_READ_UINT64_LE (carray),\n      0x4847464544434241);\n\n  fail_unless_equals_int64_hex (GST_READ_UINT64_BE (uarray),\n      0x4142434445464748);\n  fail_unless_equals_int64_hex (GST_READ_UINT64_LE (uarray),\n      0x4847464544434241);\n\n  /* make sure the data argument is not duplicated inside the macro\n   * with possibly unexpected side-effects */\n  cpointer = carray;\n  fail_unless_equals_int (GST_READ_UINT8 (cpointer++), 'A');\n  fail_unless (cpointer == carray + 1);\n\n  cpointer = carray;\n  fail_unless_equals_int_hex (GST_READ_UINT16_BE (cpointer++), 0x4142);\n  fail_unless (cpointer == carray + 1);\n\n  cpointer = carray;\n  fail_unless_equals_int_hex (GST_READ_UINT32_BE (cpointer++), 0x41424344);\n  fail_unless (cpointer == carray + 1);\n\n  cpointer = carray;\n  fail_unless_equals_int64_hex (GST_READ_UINT64_BE (cpointer++),\n      0x4142434445464748);\n  fail_unless (cpointer == carray + 1);\n}\n\nGST_END_TEST;\n\nGST_START_TEST (test_write_macros)\n{\n  guint8 carray[8];\n  guint8 *cpointer;\n\n  /* make sure the data argument is not duplicated inside the macro\n   * with possibly unexpected side-effects */\n  memset (carray, 0, sizeof (carray));\n  cpointer = carray;\n  GST_WRITE_UINT8 (cpointer++, 'A');\n  fail_unless_equals_pointer (cpointer, carray + 1);\n  fail_unless_equals_int (carray[0], 'A');\n\n  memset (carray, 0, sizeof (carray));\n  cpointer = carray;\n  GST_WRITE_UINT16_BE (cpointer++, 0x4142);\n  fail_unless_equals_pointer (cpointer, carray + 1);\n  fail_unless_equals_int (carray[0], 'A');\n  fail_unless_equals_int (carray[1], 'B');\n\n  memset (carray, 0, sizeof (carray));\n  cpointer = carray;\n  GST_WRITE_UINT32_BE (cpointer++, 0x41424344);\n  fail_unless_equals_pointer (cpointer, carray + 1);\n  fail_unless_equals_int (carray[0], 'A');\n  fail_unless_equals_int (carray[3], 'D');\n\n  memset (carray, 0, sizeof (carray));\n  cpointer = carray;\n  GST_WRITE_UINT64_BE (cpointer++, 0x4142434445464748);\n  fail_unless_equals_pointer (cpointer, carray + 1);\n  fail_unless_equals_int (carray[0], 'A');\n  fail_unless_equals_int (carray[7], 'H');\n\n  memset (carray, 0, sizeof (carray));\n  cpointer = carray;\n  GST_WRITE_UINT16_LE (cpointer++, 0x4142);\n  fail_unless_equals_pointer (cpointer, carray + 1);\n  fail_unless_equals_int (carray[0], 'B');\n  fail_unless_equals_int (carray[1], 'A');\n\n  memset (carray, 0, sizeof (carray));\n  cpointer = carray;\n  GST_WRITE_UINT32_LE (cpointer++, 0x41424344);\n  fail_unless_equals_pointer (cpointer, carray + 1);\n  fail_unless_equals_int (carray[0], 'D');\n  fail_unless_equals_int (carray[3], 'A');\n\n  memset (carray, 0, sizeof (carray));\n  cpointer = carray;\n  GST_WRITE_UINT64_LE (cpointer++, 0x4142434445464748);\n  fail_unless_equals_pointer (cpointer, carray + 1);\n  fail_unless_equals_int (carray[0], 'H');\n  fail_unless_equals_int (carray[7], 'A');\n}\n\nGST_END_TEST;\n\nstatic void\ncount_request_pad (const GValue * item, gpointer user_data)\n{\n  GstPad *pad = GST_PAD (g_value_get_object (item));\n  guint *count = (guint *) user_data;\n\n  if (GST_PAD_TEMPLATE_PRESENCE (GST_PAD_PAD_TEMPLATE (pad)) == GST_PAD_REQUEST)\n    (*count)++;\n}\n\nstatic guint\nrequest_pads (GstElement * element)\n{\n  GstIterator *iter;\n  guint pads = 0;\n\n  iter = gst_element_iterate_pads (element);\n  fail_unless (gst_iterator_foreach (iter, count_request_pad, &pads) ==\n      GST_ITERATOR_DONE);\n  gst_iterator_free (iter);\n\n  return pads;\n}\n\nstatic GstPadLinkReturn\nrefuse_to_link (GstPad * pad, GstObject * parent, GstPad * peer)\n{\n  return GST_PAD_LINK_REFUSED;\n}\n\ntypedef struct _GstFakeReqSink GstFakeReqSink;\ntypedef struct _GstFakeReqSinkClass GstFakeReqSinkClass;\n\nstruct _GstFakeReqSink\n{\n  GstElement element;\n};\n\nstruct _GstFakeReqSinkClass\n{\n  GstElementClass parent_class;\n};\n\nG_GNUC_INTERNAL GType gst_fakereqsink_get_type (void);\n\nstatic GstStaticPadTemplate fakereqsink_sink_template =\nGST_STATIC_PAD_TEMPLATE (\"sink_%u\",\n    GST_PAD_SINK,\n    GST_PAD_REQUEST,\n    GST_STATIC_CAPS_ANY);\n\nG_DEFINE_TYPE (GstFakeReqSink, gst_fakereqsink, GST_TYPE_ELEMENT);\n\nstatic GstPad *\ngst_fakereqsink_request_new_pad (GstElement * element, GstPadTemplate * templ,\n    const gchar * name, const GstCaps * caps)\n{\n  GstPad *pad;\n  pad = gst_pad_new_from_static_template (&fakereqsink_sink_template, name);\n  gst_pad_set_link_function (pad, refuse_to_link);\n  gst_element_add_pad (GST_ELEMENT_CAST (element), pad);\n  return pad;\n}\n\nstatic void\ngst_fakereqsink_release_pad (GstElement * element, GstPad * pad)\n{\n  gst_pad_set_active (pad, FALSE);\n  gst_element_remove_pad (element, pad);\n}\n\nstatic void\ngst_fakereqsink_class_init (GstFakeReqSinkClass * klass)\n{\n  GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);\n\n  gst_element_class_set_static_metadata (gstelement_class,\n      \"Fake Request Sink\", \"Sink\", \"Fake sink with request pads\",\n      \"Sebastian Rasmussen <sebras@hotmail.com>\");\n\n  gst_element_class_add_static_pad_template (gstelement_class,\n      &fakereqsink_sink_template);\n\n  gstelement_class->request_new_pad = gst_fakereqsink_request_new_pad;\n  gstelement_class->release_pad = gst_fakereqsink_release_pad;\n}\n\nstatic void\ngst_fakereqsink_init (GstFakeReqSink * fakereqsink)\n{\n}\n\nstatic void\ntest_link (const gchar * expectation, const gchar * srcname,\n    const gchar * srcpad, const gchar * srcstate, const gchar * sinkname,\n    const gchar * sinkpad, const gchar * sinkstate)\n{\n  GstElement *src, *sink, *othersrc, *othersink;\n  guint src_pads, sink_pads;\n\n  if (g_strcmp0 (srcname, \"requestsrc\") == 0)\n    src = gst_element_factory_make (\"tee\", NULL);\n  else if (g_strcmp0 (srcname, \"requestsink\") == 0)\n    src = gst_element_factory_make (\"funnel\", NULL);\n  else if (g_strcmp0 (srcname, \"staticsrc\") == 0)\n    src = gst_element_factory_make (\"fakesrc\", NULL);\n  else if (g_strcmp0 (srcname, \"staticsink\") == 0)\n    src = gst_element_factory_make (\"fakesink\", NULL);\n  else\n    g_assert_not_reached ();\n\n  if (g_strcmp0 (sinkname, \"requestsink\") == 0)\n    sink = gst_element_factory_make (\"funnel\", NULL);\n  else if (g_strcmp0 (sinkname, \"requestsrc\") == 0)\n    sink = gst_element_factory_make (\"tee\", NULL);\n  else if (g_strcmp0 (sinkname, \"staticsink\") == 0)\n    sink = gst_element_factory_make (\"fakesink\", NULL);\n  else if (g_strcmp0 (sinkname, \"staticsrc\") == 0)\n    sink = gst_element_factory_make (\"fakesrc\", NULL);\n  else if (g_strcmp0 (sinkname, \"fakerequestsink\") == 0)\n    sink = gst_element_factory_make (\"fakereqsink\", NULL);\n  else\n    g_assert_not_reached ();\n\n  othersrc = gst_element_factory_make (\"fakesrc\", NULL);\n  othersink = gst_element_factory_make (\"fakesink\", NULL);\n\n  if (g_strcmp0 (srcstate, \"linked\") == 0)\n    fail_unless (gst_element_link_pads (src, srcpad, othersink, NULL));\n  if (g_strcmp0 (sinkstate, \"linked\") == 0)\n    fail_unless (gst_element_link_pads (othersrc, NULL, sink, sinkpad));\n  if (g_strcmp0 (srcstate, \"unlinkable\") == 0) {\n    GstPad *pad = gst_element_get_static_pad (src, srcpad ? srcpad : \"src\");\n    gst_pad_set_link_function (pad, refuse_to_link);\n    gst_object_unref (pad);\n  }\n  if (g_strcmp0 (sinkstate, \"unlinkable\") == 0) {\n    GstPad *pad = gst_element_get_static_pad (sink, sinkpad ? sinkpad : \"sink\");\n    gst_pad_set_link_function (pad, refuse_to_link);\n    gst_object_unref (pad);\n  }\n\n  src_pads = request_pads (src);\n  sink_pads = request_pads (sink);\n  if (g_strcmp0 (expectation, \"OK\") == 0) {\n    fail_unless (gst_element_link_pads (src, srcpad, sink, sinkpad));\n    if (g_str_has_prefix (srcname, \"request\")) {\n      fail_unless_equals_int (request_pads (src), src_pads + 1);\n    } else {\n      fail_unless_equals_int (request_pads (src), src_pads);\n    }\n    if (g_str_has_prefix (sinkname, \"request\")) {\n      fail_unless_equals_int (request_pads (sink), sink_pads + 1);\n    } else {\n      fail_unless_equals_int (request_pads (sink), sink_pads);\n    }\n  } else {\n    fail_if (gst_element_link_pads (src, srcpad, sink, sinkpad));\n    fail_unless_equals_int (request_pads (src), src_pads);\n    fail_unless_equals_int (request_pads (sink), sink_pads);\n  }\n\n  gst_object_unref (othersrc);\n  gst_object_unref (othersink);\n\n  gst_object_unref (src);\n  gst_object_unref (sink);\n}\n\nGST_START_TEST (test_element_link)\n{\n  /* Successful cases */\n\n  gst_element_register (NULL, \"fakereqsink\", GST_RANK_NONE,\n      gst_fakereqsink_get_type ());\n\n  test_link (\"OK\", \"staticsrc\", \"src\", \"\", \"staticsink\", \"sink\", \"\");\n  test_link (\"OK\", \"staticsrc\", \"src\", \"\", \"requestsink\", \"sink_0\", \"\");\n  test_link (\"OK\", \"staticsrc\", \"src\", \"\", \"staticsink\", NULL, \"\");\n  test_link (\"OK\", \"staticsrc\", \"src\", \"\", \"requestsink\", NULL, \"\");\n  test_link (\"OK\", \"requestsrc\", \"src_0\", \"\", \"staticsink\", \"sink\", \"\");\n  test_link (\"OK\", \"requestsrc\", \"src_0\", \"\", \"requestsink\", \"sink_0\", \"\");\n  test_link (\"OK\", \"requestsrc\", \"src_0\", \"\", \"staticsink\", NULL, \"\");\n  test_link (\"OK\", \"requestsrc\", \"src_0\", \"\", \"requestsink\", NULL, \"\");\n  test_link (\"OK\", \"staticsrc\", NULL, \"\", \"staticsink\", \"sink\", \"\");\n  test_link (\"OK\", \"staticsrc\", NULL, \"\", \"requestsink\", \"sink_0\", \"\");\n  test_link (\"OK\", \"staticsrc\", NULL, \"\", \"staticsink\", NULL, \"\");\n  test_link (\"OK\", \"staticsrc\", NULL, \"\", \"requestsink\", NULL, \"\");\n  test_link (\"OK\", \"requestsrc\", NULL, \"\", \"staticsink\", \"sink\", \"\");\n  test_link (\"OK\", \"requestsrc\", NULL, \"\", \"requestsink\", \"sink_0\", \"\");\n  test_link (\"OK\", \"requestsrc\", NULL, \"\", \"staticsink\", NULL, \"\");\n  test_link (\"OK\", \"requestsrc\", NULL, \"\", \"requestsink\", NULL, \"\");\n\n  /* Failure cases */\n\n  test_link (\"NOK\", \"staticsrc\", \"missing\", \"\", \"staticsink\", \"sink\", \"\");\n  test_link (\"NOK\", \"staticsink\", \"sink\", \"\", \"staticsink\", \"sink\", \"\");\n  test_link (\"NOK\", \"staticsrc\", \"src\", \"linked\", \"staticsink\", \"sink\", \"\");\n  test_link (\"NOK\", \"staticsrc\", \"src\", \"\", \"staticsink\", \"missing\", \"\");\n  test_link (\"NOK\", \"staticsrc\", \"src\", \"\", \"staticsrc\", \"src\", \"\");\n  test_link (\"NOK\", \"staticsrc\", \"src\", \"\", \"staticsink\", \"sink\", \"linked\");\n  test_link (\"NOK\", \"staticsrc\", \"src\", \"\", \"staticsink\", \"sink\", \"unlinkable\");\n  test_link (\"NOK\", \"staticsrc\", NULL, \"\", \"staticsink\", \"sink\", \"unlinkable\");\n  test_link (\"NOK\", \"staticsrc\", NULL, \"\", \"staticsink\", NULL, \"unlinkable\");\n  test_link (\"NOK\", \"requestsrc\", \"missing\", \"\", \"staticsink\", \"sink\", \"\");\n  test_link (\"NOK\", \"requestsink\", \"sink_0\", \"\", \"staticsink\", \"sink\", \"\");\n  test_link (\"NOK\", \"requestsrc\", \"src_0\", \"linked\", \"staticsink\", \"sink\", \"\");\n  test_link (\"NOK\", \"requestsrc\", \"src_0\", \"\", \"staticsink\", \"missing\", \"\");\n  test_link (\"NOK\", \"requestsrc\", \"src_0\", \"\", \"staticsrc\", \"src\", \"\");\n  test_link (\"NOK\", \"requestsrc\", \"src_0\", \"\", \"staticsink\", \"sink\", \"linked\");\n  test_link (\"NOK\", \"requestsrc\", \"src_0\", \"\", \"staticsink\", \"sink\",\n      \"unlinkable\");\n  test_link (\"NOK\", \"requestsrc\", NULL, \"\", \"staticsink\", \"sink\", \"unlinkable\");\n  test_link (\"NOK\", \"requestsrc\", NULL, \"\", \"staticsink\", NULL, \"unlinkable\");\n  test_link (\"NOK\", \"staticsrc\", \"missing\", \"\", \"requestsink\", \"sink_0\", \"\");\n  test_link (\"NOK\", \"staticsink\", \"sink\", \"\", \"requestsink\", \"sink_0\", \"\");\n  test_link (\"NOK\", \"staticsrc\", \"src\", \"linked\", \"requestsink\", \"sink_0\", \"\");\n  test_link (\"NOK\", \"staticsrc\", \"src\", \"\", \"requestsink\", \"missing\", \"\");\n  test_link (\"NOK\", \"staticsrc\", \"src\", \"\", \"requestsrc\", \"src_0\", \"\");\n  test_link (\"NOK\", \"staticsrc\", \"src\", \"\", \"requestsink\", \"sink_0\", \"linked\");\n  test_link (\"NOK\", \"staticsrc\", \"src\", \"unlinkable\", \"requestsink\",\n      \"sink_0\", \"\");\n  test_link (\"NOK\", \"staticsrc\", NULL, \"unlinkable\", \"requestsink\",\n      \"sink_0\", \"\");\n  test_link (\"NOK\", \"staticsrc\", NULL, \"unlinkable\", \"requestsink\", NULL, \"\");\n  test_link (\"NOK\", \"requestsrc\", \"src_0\", \"\", \"staticsink\", NULL,\n      \"unlinkable\");\n  test_link (\"NOK\", \"requestsrc\", NULL, \"\", \"fakerequestsink\", NULL, \"\");\n}\n\nGST_END_TEST;\n\ntypedef struct _GstTestPadReqSink GstTestPadReqSink;\ntypedef struct _GstTestPadReqSinkClass GstTestPadReqSinkClass;\n\nstruct _GstTestPadReqSink\n{\n  GstElement element;\n};\n\nstruct _GstTestPadReqSinkClass\n{\n  GstElementClass parent_class;\n};\n\nG_GNUC_INTERNAL GType gst_testpadreqsink_get_type (void);\n\nstatic GstStaticPadTemplate testpadreqsink_video_template =\nGST_STATIC_PAD_TEMPLATE (\"video_%u\",\n    GST_PAD_SINK,\n    GST_PAD_REQUEST,\n    GST_STATIC_CAPS (\"video/x-raw\"));\n\nstatic GstStaticPadTemplate testpadreqsink_audio_template =\nGST_STATIC_PAD_TEMPLATE (\"audio_%u\",\n    GST_PAD_SINK,\n    GST_PAD_REQUEST,\n    GST_STATIC_CAPS (\"audio/x-raw\"));\n\nG_DEFINE_TYPE (GstTestPadReqSink, gst_testpadreqsink, GST_TYPE_ELEMENT);\n\nstatic GstPad *\ngst_testpadreqsink_request_new_pad (GstElement * element,\n    GstPadTemplate * templ, const gchar * name, const GstCaps * caps)\n{\n  GstPad *pad;\n  pad = gst_pad_new_from_template (templ, name);\n  gst_pad_set_active (pad, TRUE);\n  gst_element_add_pad (GST_ELEMENT_CAST (element), pad);\n  return pad;\n}\n\nstatic void\ngst_testpadreqsink_release_pad (GstElement * element, GstPad * pad)\n{\n  gst_pad_set_active (pad, FALSE);\n  gst_element_remove_pad (element, pad);\n}\n\nstatic void\ngst_testpadreqsink_class_init (GstTestPadReqSinkClass * klass)\n{\n  GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);\n\n  gst_element_class_set_static_metadata (gstelement_class,\n      \"Test Pad Request Sink\", \"Sink\", \"Sink for unit tests with request pads\",\n      \"Thiago Santos <thiagoss@osg.samsung.com>\");\n\n  gst_element_class_add_static_pad_template (gstelement_class,\n      &testpadreqsink_video_template);\n  gst_element_class_add_static_pad_template (gstelement_class,\n      &testpadreqsink_audio_template);\n\n  gstelement_class->request_new_pad = gst_testpadreqsink_request_new_pad;\n  gstelement_class->release_pad = gst_testpadreqsink_release_pad;\n}\n\nstatic void\ngst_testpadreqsink_init (GstTestPadReqSink * testpadeqsink)\n{\n}\n\nstatic GstCaps *padreqsink_query_caps = NULL;\n\nstatic gboolean\ntestpadreqsink_peer_query (GstPad * pad, GstObject * parent, GstQuery * query)\n{\n  gboolean res;\n\n  switch (GST_QUERY_TYPE (query)) {\n    case GST_QUERY_CAPS:\n      if (padreqsink_query_caps) {\n        gst_query_set_caps_result (query, padreqsink_query_caps);\n        res = TRUE;\n        break;\n      }\n    default:\n      res = gst_pad_query_default (pad, parent, query);\n      break;\n  }\n\n  return res;\n}\n\nstatic void\ncheck_get_compatible_pad_request (GstElement * element, GstCaps * peer_caps,\n    GstCaps * filter, gboolean should_get_pad, const gchar * pad_tmpl_name)\n{\n  GstPad *peer, *requested;\n  GstPadTemplate *tmpl;\n\n  gst_caps_replace (&padreqsink_query_caps, peer_caps);\n  peer = gst_pad_new (\"src\", GST_PAD_SRC);\n  gst_pad_set_query_function (peer, testpadreqsink_peer_query);\n  requested = gst_element_get_compatible_pad (element, peer, filter);\n\n  if (should_get_pad) {\n    fail_unless (requested != NULL);\n    if (pad_tmpl_name) {\n      tmpl = gst_pad_get_pad_template (requested);\n      fail_unless (strcmp (GST_PAD_TEMPLATE_NAME_TEMPLATE (tmpl),\n              pad_tmpl_name) == 0);\n      gst_object_unref (tmpl);\n    }\n    gst_element_release_request_pad (element, requested);\n    gst_object_unref (requested);\n  } else {\n    fail_unless (requested == NULL);\n  }\n\n  if (peer_caps)\n    gst_caps_unref (peer_caps);\n  if (filter)\n    gst_caps_unref (filter);\n  gst_object_unref (peer);\n}\n\nGST_START_TEST (test_element_get_compatible_pad_request)\n{\n  GstElement *element;\n\n  gst_element_register (NULL, \"testpadreqsink\", GST_RANK_NONE,\n      gst_testpadreqsink_get_type ());\n\n  element = gst_element_factory_make (\"testpadreqsink\", NULL);\n\n  /* Try with a peer pad with any caps and no filter,\n   * returning any pad is ok */\n  check_get_compatible_pad_request (element, NULL, NULL, TRUE, NULL);\n  /* Try with a peer pad with any caps and video as filter */\n  check_get_compatible_pad_request (element, NULL,\n      gst_caps_from_string (\"video/x-raw\"), TRUE, \"video_%u\");\n  /* Try with a peer pad with any caps and audio as filter */\n  check_get_compatible_pad_request (element, NULL,\n      gst_caps_from_string (\"audio/x-raw\"), TRUE, \"audio_%u\");\n  /* Try with a peer pad with any caps and fake caps as filter */\n  check_get_compatible_pad_request (element, NULL,\n      gst_caps_from_string (\"foo/bar\"), FALSE, NULL);\n\n  /* Try with a peer pad with video caps and no caps as filter */\n  check_get_compatible_pad_request (element,\n      gst_caps_from_string (\"video/x-raw\"), NULL, TRUE, \"video_%u\");\n  /* Try with a peer pad with audio caps and no caps as filter */\n  check_get_compatible_pad_request (element,\n      gst_caps_from_string (\"audio/x-raw\"), NULL, TRUE, \"audio_%u\");\n  /* Try with a peer pad with video caps and foo caps as filter */\n  check_get_compatible_pad_request (element,\n      gst_caps_from_string (\"video/x-raw\"), gst_caps_from_string (\"foo/bar\"),\n      FALSE, NULL);\n\n  gst_caps_replace (&padreqsink_query_caps, NULL);\n  gst_object_unref (element);\n}\n\nGST_END_TEST;\n\nGST_START_TEST (test_element_link_with_ghost_pads)\n{\n  GstElement *sink_bin, *sink2_bin, *pipeline;\n  GstElement *src, *tee, *queue, *queue2, *sink, *sink2;\n  GstMessage *message;\n  GstBus *bus;\n\n  fail_unless (pipeline = gst_pipeline_new (NULL));\n  fail_unless (sink_bin = gst_bin_new (NULL));\n  fail_unless (sink2_bin = gst_bin_new (NULL));\n  fail_unless (src = gst_element_factory_make (\"fakesrc\", NULL));\n  fail_unless (tee = gst_element_factory_make (\"tee\", NULL));\n  fail_unless (queue = gst_element_factory_make (\"queue\", NULL));\n  fail_unless (sink = gst_element_factory_make (\"fakesink\", NULL));\n  fail_unless (queue2 = gst_element_factory_make (\"queue\", NULL));\n  fail_unless (sink2 = gst_element_factory_make (\"fakesink\", NULL));\n\n  gst_bin_add_many (GST_BIN (pipeline), src, tee, queue, sink, sink2_bin, NULL);\n  fail_unless (gst_element_link_many (src, tee, queue, sink, NULL));\n  fail_unless (gst_element_set_state (pipeline,\n          GST_STATE_PLAYING) == GST_STATE_CHANGE_ASYNC);\n\n  /* wait for a buffer to arrive at the sink */\n  bus = gst_element_get_bus (pipeline);\n  message = gst_bus_poll (bus, GST_MESSAGE_ASYNC_DONE, -1);\n  gst_message_unref (message);\n  gst_object_unref (bus);\n\n  gst_bin_add_many (GST_BIN (sink_bin), queue2, sink2, NULL);\n  fail_unless (gst_element_link (queue2, sink2));\n\n  gst_bin_add (GST_BIN (sink2_bin), sink_bin);\n  /* The two levels of bins with the outer bin in the running state is\n   * important, when the second ghost pad is created (from this\n   * gst_element_link()) in the running bin, we need to activate the\n   * created ghost pad */\n  fail_unless (gst_element_link (tee, queue2));\n\n  fail_unless (gst_element_set_state (pipeline,\n          GST_STATE_NULL) == GST_STATE_CHANGE_SUCCESS);\n\n  gst_object_unref (pipeline);\n}\n\nGST_END_TEST;\n\nstatic const GstClockTime times1[] = {\n  257116899087539, 120632754291904,\n  257117935914250, 120633825367344,\n  257119448289434, 120635306141271,\n  257120493671524, 120636384357825,\n  257121550784861, 120637417438878,\n  257123042669403, 120638895344150,\n  257124089184865, 120639971729651,\n  257125545836474, 120641406788243,\n  257127030618490, 120642885914220,\n  257128033712770, 120643888843907,\n  257129081768074, 120644981892002,\n  257130145383845, 120646016376867,\n  257131532530200, 120647389850987,\n  257132578136034, 120648472767247,\n  257134102475722, 120649953785315,\n  257135142994788, 120651028858556,\n  257136585079868, 120652441303624,\n  257137618260656, 120653491627112,\n  257139108694546, 120654963978184,\n  257140644022048, 120656500233068,\n  257141685671825, 120657578510655,\n  257142741238288, 120658610889805,\n  257144243633074, 120660093098060,\n  257145287962271, 120661172901525,\n  257146740596716, 120662591572179,\n  257147757607150, 120663622822179,\n  257149263992401, 120665135578527,\n  257150303719290, 120666176166905,\n  257151355569906, 120667217304601,\n  257152430578406, 120668326099768,\n  257153490501095, 120669360554111,\n  257154512360784, 120670365497960,\n  257155530610577, 120671399006259,\n  257156562091659, 120672432728185,\n  257157945388742, 120673800312414,\n  257159287547073, 120675142444983,\n  257160324912880, 120676215076817,\n  257345408328042, 120861261738196,\n  257346412270919, 120862265613926,\n  257347420532284, 120863278644933,\n  257348431187638, 120864284412754,\n  257349439018028, 120865293110265,\n  257351796217938, 120867651111973,\n  257352803038092, 120868659107578,\n  257354152688899, 120870008594883,\n  257355157088906, 120871011097327,\n  257356162439182, 120872016346348,\n  257357167872040, 120873021656407,\n  257358182440058, 120874048633945,\n  257359198881356, 120875052265538,\n  257100756525466, 120616619282139,\n  257101789337770, 120617655475988,\n  257102816323472, 120618674000157,\n  257103822485250, 120619679005039,\n  257104840760423, 120620710743321,\n  257105859459496, 120621715351476,\n  257106886662470, 120622764942539,\n  257108387497864, 120624244221106,\n  257109428859191, 120625321461096,\n  257110485892785, 120626356892003,\n  257111869872141, 120627726459874,\n  257112915903774, 120628813190830,\n  257114329982208, 120630187061682,\n  257115376666026, 120631271992101\n};\n\n\nstatic const GstClockTime times2[] = {\n  291678579009762, 162107345029507,\n  291679770464405, 162108597684538,\n  291680972924370, 162109745816863,\n  291682278949629, 162111000577605,\n  291683590706117, 162112357724822,\n  291684792322541, 162113613156950,\n  291685931362506, 162114760556854,\n  291687132156589, 162115909238493,\n  291688265012060, 162117120603240,\n  291689372183047, 162118126279508,\n  291705506022294, 162134329373992,\n  291667914301004, 162096795553658,\n  291668119537668, 162096949051905,\n  291668274671455, 162097049238371,\n  291668429435600, 162097256356719,\n  291668586128535, 162097355689763,\n  291668741306233, 162097565678460,\n  291668893789203, 162097661044916,\n  291669100256555, 162097865694145,\n  291669216417563, 162098069214693,\n  291669836394620, 162098677275530,\n  291669990447821, 162098792601263,\n  291670149426086, 162098916899184,\n  291670300232152, 162099114225621,\n  291670411261917, 162099236784112,\n  291670598483507, 162099402158751,\n  291671716582687, 162100558744122,\n  291672600759788, 162101499326359,\n  291673919988307, 162102751981384,\n  291675174441643, 162104005551939,\n  291676271562197, 162105105252898,\n  291677376345374, 162106195737516\n};\n\nstatic const GstClockTime times3[] = {\n  291881924291688, 162223997578228,\n  291883318122262, 162224167198360,\n  291884786394838, 162224335172501,\n  291886004374386, 162224503695531,\n  291887224353285, 162224673560021,\n  291888472403367, 162224843760361,\n  291889727977561, 162225014479362,\n  291890989982306, 162225174554558,\n  291892247875763, 162225339753039,\n  291893502163547, 162225673230987,\n  291894711382216, 162225829494101,\n  291895961021506, 162225964530832,\n  291897251690854, 162226127287981,\n  291898508630785, 162226303710406,\n  291899740172868, 162226472478047,\n  291900998878873, 162226637402085,\n  291902334919875, 162226797873245,\n  291903572196610, 162226964352963,\n  291904727342699, 162227125312525,\n  291906071189108, 162228361337153,\n  291907308146005, 162229560625638,\n  291908351925126, 162230604986650,\n  291909396411423, 162231653690543,\n  291910453965348, 162232698550995,\n  291912096870744, 162233475264947,\n  291913234148395, 162233606516855,\n  291915448096576, 162233921145559,\n  291916707748827, 162234047154298,\n  291918737451070, 162234370837425,\n  291919896016205, 162234705504337,\n  291921098663980, 162234872320397,\n  291922315691409, 162235031023366\n};\n\nstatic const GstClockTime times4[] = {\n  10, 0,\n  20, 20,\n  30, 40,\n  40, 60,\n  50, 80,\n  60, 100\n};\n\nstruct test_entry\n{\n  gint n;\n  const GstClockTime *v;\n  GstClockTime expect_internal;\n  GstClockTime expect_external;\n  guint64 expect_num;\n  guint64 expect_denom;\n} times[] = {\n  {\n  32, times1, 257154512360784, 120670380469753, 4052622913376634109,\n        4052799313904261962}, {\n  64, times1, 257359198881356, 120875054227405, 2011895759027682422,\n        2012014931360215503}, {\n  32, times2, 291705506022294, 162134297192792, 2319535707505209857,\n        2321009753483354451}, {\n  32, times3, 291922315691409, 162234934150296, 1370930728180888261,\n        4392719527011673456}, {\n  6, times4, 60, 100, 2, 1}\n};\n\nGST_START_TEST (test_regression)\n{\n  GstClockTime m_num, m_den, internal, external;\n  gdouble r_squared, rate, expect_rate;\n  gint i;\n\n  for (i = 0; i < G_N_ELEMENTS (times); i++) {\n    fail_unless (gst_calculate_linear_regression (times[i].v, NULL, times[i].n,\n            &m_num, &m_den, &external, &internal, &r_squared));\n\n    GST_LOG (\"xbase %\" G_GUINT64_FORMAT \" ybase %\" G_GUINT64_FORMAT \" rate = %\"\n        G_GUINT64_FORMAT \" / %\" G_GUINT64_FORMAT \" = %.10f r_squared %f\\n\",\n        internal, external, m_num, m_den, (gdouble) (m_num) / (m_den),\n        r_squared);\n\n    /* Require high correlation */\n    fail_unless (r_squared >= 0.9);\n\n    fail_unless (internal == times[i].expect_internal,\n        \"Regression params %d fail. internal %\" G_GUINT64_FORMAT\n        \" != expected %\" G_GUINT64_FORMAT, i, internal,\n        times[i].expect_internal);\n    /* Rate must be within 1% tolerance */\n    expect_rate = ((gdouble) (times[i].expect_num) / times[i].expect_denom);\n    rate = ((gdouble) (m_num) / m_den);\n    fail_unless ((expect_rate - rate) >= -0.1 && (expect_rate - rate) <= 0.1,\n        \"Regression params %d fail. Rate out of range. Expected %f, got %f\",\n        i, expect_rate, rate);\n    fail_unless (external >= times[i].expect_external * 0.99 &&\n        external <= times[i].expect_external * 1.01,\n        \"Regression params %d fail. external %\" G_GUINT64_FORMAT\n        \" != expected %\" G_GUINT64_FORMAT, i, external,\n        times[i].expect_external);\n  }\n}\n\nGST_END_TEST;\n\nstatic Suite *\ngst_utils_suite (void)\n{\n  Suite *s = suite_create (\"GstUtils\");\n  TCase *tc_chain = tcase_create (\"general\");\n\n  suite_add_tcase (s, tc_chain);\n  tcase_add_test (tc_chain, test_buffer_probe_n_times);\n  tcase_add_test (tc_chain, test_buffer_probe_once);\n  tcase_add_test (tc_chain, test_math_scale);\n  tcase_add_test (tc_chain, test_math_scale_round);\n  tcase_add_test (tc_chain, test_math_scale_ceil);\n  tcase_add_test (tc_chain, test_math_scale_uint64);\n  tcase_add_test (tc_chain, test_math_scale_random);\n#ifdef HAVE_GSL\n#ifdef HAVE_GMP\n  tcase_add_test (tc_chain, test_math_scale_gmp);\n  tcase_add_test (tc_chain, test_math_scale_gmp_int);\n#endif\n#endif\n\n  tcase_add_test (tc_chain, test_guint64_to_gdouble);\n  tcase_add_test (tc_chain, test_gdouble_to_guint64);\n#ifndef GST_DISABLE_PARSE\n  tcase_add_test (tc_chain, test_parse_bin_from_description);\n#endif\n  tcase_add_test (tc_chain, test_element_found_tags);\n  tcase_add_test (tc_chain, test_element_link);\n  tcase_add_test (tc_chain, test_element_link_with_ghost_pads);\n  tcase_add_test (tc_chain, test_element_unlink);\n  tcase_add_test (tc_chain, test_element_get_compatible_pad_request);\n  tcase_add_test (tc_chain, test_set_value_from_string);\n  tcase_add_test (tc_chain, test_binary_search);\n\n  tcase_add_test (tc_chain, test_pad_proxy_query_caps_aggregation);\n  tcase_add_test (tc_chain, test_greatest_common_divisor);\n\n  tcase_add_test (tc_chain, test_read_macros);\n  tcase_add_test (tc_chain, test_write_macros);\n  tcase_add_test (tc_chain, test_regression);\n\n  return s;\n}\n\nGST_CHECK_MAIN (gst_utils);\n", "meta": {"hexsha": "18ba199b98dc6926def327925da14cbc18b194ab", "size": 67607, "ext": "c", "lang": "C", "max_stars_repo_path": "third_party/gstreamer/tests/check/gst/gstutils.c", "max_stars_repo_name": "isabella232/aistreams", "max_stars_repo_head_hexsha": "209f4385425405676a581a749bb915e257dbc1c1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-09-22T18:07:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-21T01:34:04.000Z", "max_issues_repo_path": "third_party/gstreamer/tests/check/gst/gstutils.c", "max_issues_repo_name": "isabella232/aistreams", "max_issues_repo_head_hexsha": "209f4385425405676a581a749bb915e257dbc1c1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-11-10T13:17:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T11:22:14.000Z", "max_forks_repo_path": "third_party/gstreamer/tests/check/gst/gstutils.c", "max_forks_repo_name": "isabella232/aistreams", "max_forks_repo_head_hexsha": "209f4385425405676a581a749bb915e257dbc1c1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-09-26T08:40:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-21T01:33:56.000Z", "avg_line_length": 33.7866066967, "max_line_length": 123, "alphanum_fraction": 0.7175292499, "num_tokens": 21204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.028007520605988132, "lm_q2_score": 0.012624951568627715, "lm_q1q2_score": 0.0003535935912079429}}
{"text": "#include \"sly/defines.h\"\n\n#include <gsl/gsl>\n#include <memory.h>\n#include <optional>\n#include <stdio.h>\n\n\n#ifdef _WIN32\n    #include <windows.h>\n#endif\n\n#include \"sly/debug/logger.h\"\n#include \"sly/enum.h\"\n#include \"sly/errors.h\"\n#include \"sly/macros.h\"\n#include \"sly/retval.h\"\n#include \"sly/types.h\"\n\n", "meta": {"hexsha": "bc735191cbcc3edff39d7af3b7a3729842ee9119", "size": 301, "ext": "h", "lang": "C", "max_stars_repo_path": "slycore/include/sly/global.h", "max_stars_repo_name": "Gibbeon/sly", "max_stars_repo_head_hexsha": "9216cf04a78f1d41af01186489ba6680b9641229", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "slycore/include/sly/global.h", "max_issues_repo_name": "Gibbeon/sly", "max_issues_repo_head_hexsha": "9216cf04a78f1d41af01186489ba6680b9641229", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "slycore/include/sly/global.h", "max_forks_repo_name": "Gibbeon/sly", "max_forks_repo_head_hexsha": "9216cf04a78f1d41af01186489ba6680b9641229", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.05, "max_line_length": 29, "alphanum_fraction": 0.6910299003, "num_tokens": 89, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.028436034691575563, "lm_q2_score": 0.012431649904168424, "lm_q1q2_score": 0.0003535068279484553}}
{"text": "#pragma once\n\n#include \"Cesium3DTiles/BoundingVolume.h\"\n#include \"Cesium3DTiles/Library.h\"\n#include \"Cesium3DTiles/TileContentLoadInput.h\"\n#include \"Cesium3DTiles/TileContentLoadResult.h\"\n#include \"Cesium3DTiles/TileContentLoader.h\"\n#include \"Cesium3DTiles/TileID.h\"\n#include \"Cesium3DTiles/TileRefine.h\"\n\n#include <gsl/span>\n#include <spdlog/fwd.h>\n\n#include <cstddef>\n#include <functional>\n#include <memory>\n#include <optional>\n#include <unordered_map>\n\nnamespace Cesium3DTiles {\nclass TileContent;\nclass Tileset;\n\n/**\n * @brief Creates {@link TileContentLoadResult} objects from a {@link\n * TileContentLoadInput}.\n *\n * The class offers a lookup functionality for registering {@link\n * TileContentLoader} instances that can create {@link TileContentLoadResult}\n * instances from a {@link TileContentLoadInput}.\n *\n * The loaders are registered based on the magic header or the content type\n * of the input data. The raw data (i.e. the `data` of the {@link\n * TileContentLoadInput}) is usually received as a response to a  network\n * request, and the first four bytes of the raw data form the magic header.\n * Based on this header or the content type of the network response, the loader\n * that will be used for processing the input can be looked up.\n */\nclass CESIUM3DTILES_API TileContentFactory final {\npublic:\n  TileContentFactory() = delete;\n\n  /**\n   * @brief Register the given function for the given magic header.\n   *\n   * The given magic header is a 4-character string. It will be compared\n   * to the first 4 bytes of the raw input data, to decide whether the\n   * given factory function should be used to create the\n   * {@link TileContentLoadResult} from the input data.\n   *\n   * @param magic The string describing the magic header.\n   * @param pLoader The loader that will be used to create the tile content.\n   */\n  static void registerMagic(\n      const std::string& magic,\n      const std::shared_ptr<TileContentLoader>& pLoader);\n\n  /**\n   * @brief Register the given function for the given content type.\n   *\n   * The given string describes the content type of a network response.\n   * It is used for deciding whether the given loader should be\n   * used to create the {@link TileContentLoadResult} from a\n   * {@link TileContentLoadInput} with the same `contentType`.\n   *\n   * @param contentType The string describing the content type.\n   * @param pLoader The loader that will be used to create the tile content\n   */\n  static void registerContentType(\n      const std::string& contentType,\n      const std::shared_ptr<TileContentLoader>& pLoader);\n\n  /**\n   * @brief Creates the {@link TileContentLoadResult} from the given {@link\n   * TileContentLoadInput}.\n   *\n   * This will look up the {@link TileContentLoader} that can be used to\n   * process the given input data, based on all loaders that\n   * have been registered with {@link TileContentFactory::registerMagic}\n   * or {@link TileContentFactory::registerContentType}.\n   *\n   * It will first try to find a loader based on the magic header\n   * of the `data` in the given input. If no matching loader is found, then\n   * it will look up a loader based on the `contentType` of the given input.\n   * (This will ignore any parameters that may appear after a `;` in the\n   * `contentType` string).\n   *\n   * If no such loader is found then `nullptr` is returned.\n   *\n   * If a matching loader is found, it will be applied to the given\n   * input, and the result will be returned.\n   *\n   * @param input The {@link TileContentLoadInput}.\n   * @return The {@link TileContentLoadResult}, or `nullptr` if there is\n   * no loader registered for the magic header of the given\n   * input, and no loader for the content type of the input.\n   */\n  static std::unique_ptr<TileContentLoadResult>\n  createContent(const TileContentLoadInput& input);\n\nprivate:\n  static std::optional<std::string>\n  getMagic(const gsl::span<const std::byte>& data);\n\n  static std::unordered_map<std::string, std::shared_ptr<TileContentLoader>>\n      _loadersByMagic;\n  static std::unordered_map<std::string, std::shared_ptr<TileContentLoader>>\n      _loadersByContentType;\n};\n\n} // namespace Cesium3DTiles\n", "meta": {"hexsha": "b31547acd92529f04d3f0eced7efb0ca9eac9598", "size": 4156, "ext": "h", "lang": "C", "max_stars_repo_path": "Cesium3DTiles/include/Cesium3DTiles/TileContentFactory.h", "max_stars_repo_name": "TJKoury/cesium-native", "max_stars_repo_head_hexsha": "b824699d3dd9503a5943007247f683b6adc132d4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-27T04:47:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-27T04:47:23.000Z", "max_issues_repo_path": "Cesium3DTiles/include/Cesium3DTiles/TileContentFactory.h", "max_issues_repo_name": "MAPSWorks/cesium-native", "max_issues_repo_head_hexsha": "18a295f47b3118cc2edfc22354d93b938a68069c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cesium3DTiles/include/Cesium3DTiles/TileContentFactory.h", "max_forks_repo_name": "MAPSWorks/cesium-native", "max_forks_repo_head_hexsha": "18a295f47b3118cc2edfc22354d93b938a68069c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1071428571, "max_line_length": 79, "alphanum_fraction": 0.7317131858, "num_tokens": 1011, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.020645931944405106, "lm_q2_score": 0.016657037415934436, "lm_q1q2_score": 0.00034390006088479185}}
{"text": "\ufeff#pragma once\n#define NOMINMAX\n#define WEBRTC_WIN\n#define ABSL_USES_STD_STRING_VIEW\n\n#include <unknwn.h>\n#include <ppltasks.h>\n#include <pplawait.h>\n#include <gsl/gsl>\n#include <winrt/Windows.Foundation.h>\n#include <winrt/Windows.Foundation.Diagnostics.h>\n#include <winrt/Windows.Foundation.Collections.h>\n#include <winrt/Windows.Data.Json.h>\n#include <winrt/Windows.Networking.Sockets.h>\n#include <winrt/Windows.System.Threading.h>\n#include <winrt/Windows.Storage.Streams.h>\n#include <wrl/client.h>\n", "meta": {"hexsha": "4706f5bd31c981fc1641a8ac449a82bcee1ae7ea", "size": 500, "ext": "h", "lang": "C", "max_stars_repo_path": "Unicord.Universal.Voice/pch.h", "max_stars_repo_name": "WamWooWam/Unicord", "max_stars_repo_head_hexsha": "47c74e665ebb2bff3ef93b068357d3bf2f912e17", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 106.0, "max_stars_repo_stars_event_min_datetime": "2019-05-10T18:08:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-29T23:40:01.000Z", "max_issues_repo_path": "Unicord.Universal.Voice/pch.h", "max_issues_repo_name": "UnicordDev/Unicord.Universal.Voice", "max_issues_repo_head_hexsha": "3fd70f650ffdc4521795b2bd3c74d901a04312bd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57.0, "max_issues_repo_issues_event_min_datetime": "2019-06-07T12:53:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-30T17:34:08.000Z", "max_forks_repo_path": "Unicord.Universal.Voice/pch.h", "max_forks_repo_name": "UnicordDev/Unicord.Universal.Voice", "max_forks_repo_head_hexsha": "3fd70f650ffdc4521795b2bd3c74d901a04312bd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2019-08-19T12:02:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-16T18:09:59.000Z", "avg_line_length": 27.7777777778, "max_line_length": 49, "alphanum_fraction": 0.786, "num_tokens": 128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.03514484437961852, "lm_q2_score": 0.009708476463566183, "lm_q1q2_score": 0.0003412028944752226}}
{"text": "#ifndef __EXECUTE_PLUGIN_H__\n#define __EXECUTE_PLUGIN_H__\n\n#include <memory>\n#include <optional>\n#include <stdexcept>\n#include <string>\n#include <vector>\n\n#include <gsl/gsl>\n\n#include \"config/commandLineOptions.h\"\n#include \"config/fleetingOptionsInterface.h\"\n#include \"config/pattern.h\"\n#include \"config/patternsHandler.h\"\n#include \"config/settingsNode.h\"\n\n#include \"plugin.h\"\n\nnamespace execHelper::plugins {\nusing Plugins = std::map<std::string, std::shared_ptr<const Plugin>>;\n\n/**\n * \\brief Exception thrown when the requested plugin is invalid\n *\n * Exception thrown when the requested plugin is invalid e.g. due to the fact that it can not be found\n */\nstruct InvalidPlugin : public std::runtime_error {\n  public:\n    /**\n     * Create an invalid plugin\n     *\n     * \\param[in] msg   A message detailing the specifics of the exception\n     */\n    inline explicit InvalidPlugin(const std::string& msg)\n        : std::runtime_error(msg) {}\n\n    /*! @copydoc InvalidPlugin(const std::string&)\n     */\n    inline explicit InvalidPlugin(const char* msg) : std::runtime_error(msg) {}\n};\n\n/**\n * \\brief Plugin for executing arbitrary configured commands and/or plugins\n *\n * The ExecutePlugin handles the context of and calls all plugins. It uses the prototype pattern for retrieving a map of plugins it can call.\n */\nclass ExecutePlugin : public Plugin {\n  public:\n    /**\n     * Create an executePlugin instance\n     *\n     * \\param[in] commandsToExecute  The commands to execute with this plugin\n     * instance\n     */\n    explicit ExecutePlugin(\n        const config::CommandCollection& commandsToExecute) noexcept;\n\n    /**\n     * \\param[in] commandsToExecute The commands to execute\n     * \\param[in] initialCommand    The initial command that is being executed\n     */\n    ExecutePlugin(const config::CommandCollection& commandsToExecute,\n                  const config::Command& initialCommand) noexcept;\n\n    config::VariablesMap\n    getVariablesMap(const config::FleetingOptionsInterface& fleetingOptions)\n        const noexcept override;\n    bool apply(core::Task task, const config::VariablesMap& variables,\n               const config::Patterns& patterns) const noexcept override;\n\n    std::string summary() const noexcept override;\n\n    /**\n     * Returns a list with the names of all known plugins\n     *\n     * @returns A list of plugin names\n     */\n    static auto getPluginNames() noexcept -> std::vector<std::string>;\n\n    /**\n     * Returns an instance of the plugin associated with the given name\n     *\n     * \\param[in] pluginName    The plugin to get the associated instance from\n     * \\returns A pointer to the new instance\n     * \\throws  InvalidPlugin   When no plugin associated with the given pluginName is found\n     */\n    static std::shared_ptr<const Plugin>\n    getPlugin(const std::string& pluginName);\n\n    /**\n     * Push the given fleeting options on the stack\n     *\n     * \\param[in] fleetingOptions   The fleeting options to use. The last option\n     * on the stack will be used for calling the commands. \\returns True    if\n     * the options were successfully pushed False   otherwise\n     */\n    static bool push(gsl::not_null<const config::FleetingOptionsInterface*>\n                         fleetingOptions) noexcept;\n\n    /**\n     * Push the given settings node on the stack\n     *\n     * \\param[in] settings   The settings node to use. The last settings node on\n     * the stack will be used for calling the commands. \\returns True    if the\n     * settings node was successfully pushed False   otherwise\n     */\n    static bool push(config::SettingsNode&& settings) noexcept;\n\n    /**\n     * Push the given patterns on the stack\n     *\n     * \\param[in] patterns   The patterns to use. The last patterns on the stack\n     * will be used for calling the commands.\n     * \\returns True    if the patterns were successfully pushed\n     *          False   otherwise\n     */\n    static bool push(config::Patterns&& patterns) noexcept;\n\n    /**\n     * Push the plugin prototypes to the stack\n     *\n     * \\param[in] plugins   Mapping of discovered plugin prototypes\n     */\n    static void push(Plugins&& plugins) noexcept;\n\n    /**\n     * Pop the last fleeting options from the stack\n     *\n     */\n    static void popFleetingOptions() noexcept;\n\n    /**\n     * Pop the last settings node from the stack\n     */\n    static void popSettingsNode() noexcept;\n\n    /**\n     * Pop the last patterns from the stack\n     */\n    static void popPatterns() noexcept;\n\n    /**\n     * Pop the last plugin prototypes from the stack\n     */\n    static void popPlugins() noexcept;\n\n  private:\n    static auto getNextStep(const config::Command& command,\n                            const config::Command& originalCommand) noexcept\n        -> std::shared_ptr<const Plugin>;\n    static bool\n    getVariablesMap(config::VariablesMap* variables,\n                    const std::vector<config::SettingsKeys>& keys,\n                    const config::SettingsNode& rootSettings) noexcept;\n    static void index(config::VariablesMap* variables,\n                      const config::SettingsNode& settings,\n                      const config::SettingsKeys& key) noexcept;\n\n    const config::CommandCollection m_commands;\n    const config::CommandCollection m_initialCommands;\n\n    static std::vector<gsl::not_null<const config::FleetingOptionsInterface*>>\n        m_fleeting;\n    static std::vector<config::SettingsNode> m_settings;\n    static std::vector<config::PatternsHandler> m_patterns;\n    static std::vector<Plugins> m_plugins;\n};\n} // namespace execHelper::plugins\n\n#endif /* __EXECUTE_PLUGIN_H__ */\n", "meta": {"hexsha": "b3f1ce5dcdb075c1b381919a06ac2d9a35d15a89", "size": 5629, "ext": "h", "lang": "C", "max_stars_repo_path": "src/plugins/include/plugins/executePlugin.h", "max_stars_repo_name": "exec-helper/source", "max_stars_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-28T13:24:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-28T13:24:30.000Z", "max_issues_repo_path": "src/plugins/include/plugins/executePlugin.h", "max_issues_repo_name": "exec-helper/source", "max_issues_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/plugins/include/plugins/executePlugin.h", "max_forks_repo_name": "exec-helper/source", "max_forks_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-07-03T11:11:19.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-03T11:11:19.000Z", "avg_line_length": 32.726744186, "max_line_length": 141, "alphanum_fraction": 0.6736542903, "num_tokens": 1207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.02479816019558565, "lm_q2_score": 0.013222822918885406, "lm_q1q2_score": 0.00032790168098038175}}
{"text": "#ifndef LOGGER_INCLUDE\n#define LOGGER_INCLUDE\n\n#include <gsl/string_span>\n\n#include \"log/log.h\"\nBOOST_LOG_GLOBAL_LOGGER(exec_helper_core_logger, execHelper::log::LoggerType);\n\nstatic const gsl::czstring<> LOG_CHANNEL = \"core\";\n#define LOG(x)                                                                 \\\n    BOOST_LOG_STREAM_CHANNEL_SEV(exec_helper_core_logger::get(), LOG_CHANNEL,  \\\n                                 execHelper::log::x)                           \\\n        << boost::log::add_value(fileLog, __FILE__)                            \\\n        << boost::log::add_value(lineLog, __LINE__)\n\n#endif /* LOGGER_INCLUDE */\n", "meta": {"hexsha": "759bdfc9006344971208530ea022ebba3c1b3acc", "size": 632, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/include/core/logger.h", "max_stars_repo_name": "exec-helper/source", "max_stars_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-28T13:24:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-28T13:24:30.000Z", "max_issues_repo_path": "src/core/include/core/logger.h", "max_issues_repo_name": "exec-helper/source", "max_issues_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/include/core/logger.h", "max_forks_repo_name": "exec-helper/source", "max_forks_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-07-03T11:11:19.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-03T11:11:19.000Z", "avg_line_length": 37.1764705882, "max_line_length": 80, "alphanum_fraction": 0.5585443038, "num_tokens": 121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.017712296629340017, "lm_q2_score": 0.01798621344942342, "lm_q1q2_score": 0.0003185771478548125}}
{"text": "#pragma once\n\n// std\n#include <optional>\n\n// GSL\n#include <gsl/gsl_assert>\n\n// EnTT\n#include <entt/entt.hpp>\n\n// Qt\n#include <QtWidgets>", "meta": {"hexsha": "884d94e5d48a1680b1d6fdf282df072c9bf1e996", "size": 136, "ext": "h", "lang": "C", "max_stars_repo_path": "PolyDock/PolyDock/src/pd/pch/PCH.h", "max_stars_repo_name": "Qt-Widgets/PolyDock", "max_stars_repo_head_hexsha": "f32def214753ca0f6bab9968bc2bb5e451cb6e4f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-10T06:43:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-10T06:43:03.000Z", "max_issues_repo_path": "PolyDock/PolyDock/src/pd/pch/PCH.h", "max_issues_repo_name": "Qt-Widgets/PolyDock", "max_issues_repo_head_hexsha": "f32def214753ca0f6bab9968bc2bb5e451cb6e4f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PolyDock/PolyDock/src/pd/pch/PCH.h", "max_forks_repo_name": "Qt-Widgets/PolyDock", "max_forks_repo_head_hexsha": "f32def214753ca0f6bab9968bc2bb5e451cb6e4f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 10.4615384615, "max_line_length": 25, "alphanum_fraction": 0.6691176471, "num_tokens": 42, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.022629197396471318, "lm_q2_score": 0.01282121273420735, "lm_q1q2_score": 0.00029013375382452985}}
{"text": "\n#if !defined(XFORMCVSSTATUS_H_INCLUDED)\n#define XFORMCVSSTATUS_H_INCLUDED\n\n#include <filesystem>\n#include <gsl/gsl>\n#include <iosfwd>\n#include <map>\n#include <string>\n\nclass XformCvsStatus\n{\npublic:\n\tstatic int usage(::std::ostream& strm, const ::std::string& progName,\n\t\tconst char* pMsg);\n\n\tXformCvsStatus(::gsl::span<const char*const> args);\n\tint run();\n\n\tXformCvsStatus(const XformCvsStatus&) = delete;\n\tXformCvsStatus& operator=(const XformCvsStatus&) = delete;\n\tXformCvsStatus(XformCvsStatus&&) = delete;\n\tXformCvsStatus& operator=(XformCvsStatus&&) = delete;\n\nprivate:\n\tusing Path = ::std::filesystem::path;\n\tusing FileToStatusMap = ::std::map<Path, ::std::string>;\n\n\tvoid insertInMap(const ::std::string& file, const ::std::string& status);\n\tPath buildPath(const ::std::string& file) const;\n\tstatic ::std::string xlateStatus(const ::std::string& status);\n\tstatic ::std::string pathStringToConsoleString(const Path::string_type& str);\n\n\tbool\t\t\t\t\tm_suppressNew;\n\tbool\t\t\t\t\tm_suppressUpToDate;\n\tbool\t\t\t\t\tm_suppressLocal;\n\tPath\t\t\t\t\tm_lastWorkingDir;\n\tFileToStatusMap\t\tm_map;\n};\n\n#endif // XFORMCVSSTATUS_H_INCLUDED\n", "meta": {"hexsha": "0099e68f8e0f1b187e0020a0bc5508ee1131ec15", "size": 1119, "ext": "h", "lang": "C", "max_stars_repo_path": "XformCvsStatus.h", "max_stars_repo_name": "IanEmmons/CmdLineUtil", "max_stars_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "XformCvsStatus.h", "max_issues_repo_name": "IanEmmons/CmdLineUtil", "max_issues_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "XformCvsStatus.h", "max_forks_repo_name": "IanEmmons/CmdLineUtil", "max_forks_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6428571429, "max_line_length": 78, "alphanum_fraction": 0.7363717605, "num_tokens": 312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.025565211695996064, "lm_q2_score": 0.011331754835602531, "lm_q1q2_score": 0.00028969871125930576}}
{"text": "#pragma once\n\n#define OEMRESOURCE\n\n#include <atomic>\n#include <concepts>\n\n#include <ppl.h>\n\n#include <gsl/gsl>\n\n// Included before windows.h, because pfc.h includes winsock2.h\n#include \"../pfc/pfc.h\"\n\n#include <windows.h>\n#include <SHLWAPI.H>\n\n#include \"../foobar2000/SDK/foobar2000.h\"\n\n#include \"../mmh/stdafx.h\"\n#include \"../ui_helpers/stdafx.h\"\n\n#include \"config_var.h\"\n#include \"config_object.h\"\n#include \"console.h\"\n#include \"fcl.h\"\n#include \"info_box.h\"\n#include \"initquit.h\"\n#include \"library.h\"\n#include \"low_level_hook.h\"\n#include \"main_thread_callback.h\"\n#include \"sort.h\"\n#include \"stream.h\"\n", "meta": {"hexsha": "abffa3466220cecfdbc1f9902e18d72181e42072", "size": 603, "ext": "h", "lang": "C", "max_stars_repo_path": "stdafx.h", "max_stars_repo_name": "reupen/fbh", "max_stars_repo_head_hexsha": "d065acb4ceaf829292613f8ce9f4aa373b187ad7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stdafx.h", "max_issues_repo_name": "reupen/fbh", "max_issues_repo_head_hexsha": "d065acb4ceaf829292613f8ce9f4aa373b187ad7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stdafx.h", "max_forks_repo_name": "reupen/fbh", "max_forks_repo_head_hexsha": "d065acb4ceaf829292613f8ce9f4aa373b187ad7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.7352941176, "max_line_length": 63, "alphanum_fraction": 0.7180762852, "num_tokens": 159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.02843603551493705, "lm_q2_score": 0.009559401313456267, "lm_q1q2_score": 0.00027183147525097827}}
{"text": "/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*/\n// Portions Copyright (c) Microsoft Corporation\n\n#pragma once\n\n#include <functional>\n#include <memory>\n#include <string>\n#include <unordered_map>\n#include <vector>\n#include <gsl/gsl>\n\n#include \"core/common/common.h\"\n#include \"core/framework/callback.h\"\n#include \"core/platform/env_time.h\"\n#include \"core/platform/telemetry.h\"\n#include \"core/session/onnxruntime_c_api.h\"  // for ORTCHAR_T\n\n#ifndef _WIN32\n#include <sys/types.h>\n#include <unistd.h>\n#endif\n\nnamespace onnxruntime {\n\n#ifdef _WIN32\nusing PIDType = unsigned long;\nusing FileOffsetType = int64_t;\n#else\nusing PIDType = pid_t;\nusing FileOffsetType = off_t;\n#endif\n\n/// \\brief An interface used by the onnxruntime implementation to\n/// access operating system functionality like the filesystem etc.\n///\n/// Callers may wish to provide a custom Env object to get fine grain\n/// control.\n///\n/// All Env implementations are safe for concurrent access from\n/// multiple threads without any external synchronization.\nclass Env {\n public:\n  virtual ~Env() = default;\n\n  /// \\brief Returns a default environment suitable for the current operating\n  /// system.\n  ///\n  /// Sophisticated users may wish to provide their own Env\n  /// implementation instead of relying on this default environment.\n  ///\n  /// The result of Default() belongs to this library and must never be deleted.\n  static const Env& Default();\n\n  virtual int GetNumCpuCores() const = 0;\n\n  /// \\brief Returns the number of micro-seconds since the Unix epoch.\n  virtual uint64_t NowMicros() const { return env_time_->NowMicros(); }\n\n  /// \\brief Returns the number of seconds since the Unix epoch.\n  virtual uint64_t NowSeconds() const { return env_time_->NowSeconds(); }\n\n  /// Sleeps/delays the thread for the prescribed number of micro-seconds.\n  /// On Windows, it's the min time to sleep, not the actual one.\n  virtual void SleepForMicroseconds(int64_t micros) const = 0;\n\n  /**\n   * Gets the length of the specified file.\n   */\n  virtual common::Status GetFileLength(\n      const ORTCHAR_T* file_path, size_t& length) const = 0;\n\n  /**\n   * Copies the content of the file into the provided buffer.\n   * @param file_path The path to the file.\n   * @param offset The file offset from which to start reading.\n   * @param length The length in bytes to read.\n   * @param buffer The buffer in which to write.\n   */\n  virtual common::Status ReadFileIntoBuffer(\n      const ORTCHAR_T* file_path, FileOffsetType offset, size_t length,\n      gsl::span<char> buffer) const = 0;\n\n  using MappedMemoryPtr = std::unique_ptr<char[], OrtCallbackInvoker>;\n\n  /**\n   * Maps the content of the file into memory.\n   * This is a copy-on-write mapping, so any changes are not written to the\n   * actual file.\n   * @param file_path The path to the file.\n   * @param offset The file offset from which to start the mapping.\n   * @param length The length in bytes of the mapping.\n   * @param[out] mapped_memory A smart pointer to the mapped memory which\n   *             unmaps the memory (unless release()'d) when destroyed.\n   */\n  virtual common::Status MapFileIntoMemory(\n      const ORTCHAR_T* file_path, FileOffsetType offset, size_t length,\n      MappedMemoryPtr& mapped_memory) const = 0;\n\n#ifdef _WIN32\n  //Mainly for use with protobuf library\n  virtual common::Status FileOpenRd(const std::wstring& path, /*out*/ int& fd) const = 0;\n  //Mainly for use with protobuf library\n  virtual common::Status FileOpenWr(const std::wstring& path, /*out*/ int& fd) const = 0;\n#endif\n  //Mainly for use with protobuf library\n  virtual common::Status FileOpenRd(const std::string& path, /*out*/ int& fd) const = 0;\n  //Mainly for use with protobuf library\n  virtual common::Status FileOpenWr(const std::string& path, /*out*/ int& fd) const = 0;\n  //Mainly for use with protobuf library\n  virtual common::Status FileClose(int fd) const = 0;\n  //This functions is always successful. It can't fail.\n  virtual PIDType GetSelfPid() const = 0;\n\n  // \\brief Load a dynamic library.\n  //\n  // Pass \"library_filename\" to a platform-specific mechanism for dynamically\n  // loading a library.  The rules for determining the exact location of the\n  // library are platform-specific and are not documented here.\n  //\n  // On success, returns a handle to the library in \"*handle\" and returns\n  // OK from the function.\n  // Otherwise returns nullptr in \"*handle\" and an error status from the\n  // function.\n  virtual common::Status LoadDynamicLibrary(const std::string& library_filename, void** handle) const = 0;\n\n  virtual common::Status UnloadDynamicLibrary(void* handle) const = 0;\n\n  // \\brief Get a pointer to a symbol from a dynamic library.\n  //\n  // \"handle\" should be a pointer returned from a previous call to LoadDynamicLibrary.\n  // On success, store a pointer to the located symbol in \"*symbol\" and return\n  // OK from the function. Otherwise, returns nullptr in \"*symbol\" and an error\n  // status from the function.\n  virtual common::Status GetSymbolFromLibrary(void* handle, const std::string& symbol_name, void** symbol) const = 0;\n\n  // \\brief build the name of dynamic library.\n  //\n  // \"name\" should be name of the library.\n  // \"version\" should be the version of the library or NULL\n  // returns the name that LoadDynamicLibrary() can use\n  virtual std::string FormatLibraryFileName(const std::string& name, const std::string& version) const = 0;\n\n  // \\brief returns a provider that will handle telemetry on the current platform\n  virtual const Telemetry& GetTelemetryProvider() const = 0;\n\n protected:\n  Env();\n\n private:\n  ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(Env);\n  EnvTime* env_time_ = EnvTime::Default();\n};\n\n}  // namespace onnxruntime\n", "meta": {"hexsha": "d6b20e00d44b5e52e68bf9290d1c75c8568ae712", "size": 6319, "ext": "h", "lang": "C", "max_stars_repo_path": "onnxruntime/core/platform/env.h", "max_stars_repo_name": "nrandell/onnxruntime", "max_stars_repo_head_hexsha": "4d32050f784fc73d065bb030e937bd45ac86ff32", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-11-25T10:26:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-14T08:11:29.000Z", "max_issues_repo_path": "onnxruntime/core/platform/env.h", "max_issues_repo_name": "nrandell/onnxruntime", "max_issues_repo_head_hexsha": "4d32050f784fc73d065bb030e937bd45ac86ff32", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "onnxruntime/core/platform/env.h", "max_forks_repo_name": "nrandell/onnxruntime", "max_forks_repo_head_hexsha": "4d32050f784fc73d065bb030e937bd45ac86ff32", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3905325444, "max_line_length": 117, "alphanum_fraction": 0.7197341351, "num_tokens": 1504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.016914913514514927, "lm_q2_score": 0.01590639480242408, "lm_q1q2_score": 0.0002690552924107331}}
{"text": "#pragma once\n#include <gsl/span>\n\n/**\n * \\brief Class for managing Bluetooth state.\n */\nclass Bluetooth\n{\npublic:\n\t/**\n\t * \\brief Disconnects a device with matching MAC address from\n\t * the first Bluetooth radio it is connected to.\n\t * \\param macAddress The MAC address to search for.\n\t * \\return \\c true on success.\n\t */\n\tstatic bool disconnectDevice(const gsl::span<uint8_t>& macAddress);\n};\n", "meta": {"hexsha": "ecdeacd520a0d31ee08aecfc0223570228cc45aa", "size": 394, "ext": "h", "lang": "C", "max_stars_repo_path": "ds4wizard-cpp/Bluetooth.h", "max_stars_repo_name": "SonicFreak94/ds4wizard", "max_stars_repo_head_hexsha": "4d2ddc15b7db7cc5618c8676c91cf81614921c3c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T19:23:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-13T08:35:31.000Z", "max_issues_repo_path": "ds4wizard-cpp/Bluetooth.h", "max_issues_repo_name": "SonicFreak94/ds4wizard", "max_issues_repo_head_hexsha": "4d2ddc15b7db7cc5618c8676c91cf81614921c3c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-01-29T20:34:26.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-30T04:00:38.000Z", "max_forks_repo_path": "ds4wizard-cpp/Bluetooth.h", "max_forks_repo_name": "SonicFreak94/ds4wizard", "max_forks_repo_head_hexsha": "4d2ddc15b7db7cc5618c8676c91cf81614921c3c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.8888888889, "max_line_length": 68, "alphanum_fraction": 0.7081218274, "num_tokens": 94, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.02128735303526621, "lm_q2_score": 0.012624946437247667, "lm_q1q2_score": 0.00026875169186101744}}
{"text": "#ifndef EXECUTION_CONTENT_INCLUDE\n#define EXECUTION_CONTENT_INCLUDE\n\n#include <atomic>\n#include <map>\n#include <string>\n#include <thread>\n#include <vector>\n\n#include <boost/asio.hpp>\n#include <boost/serialization/map.hpp>\n#include <boost/serialization/vector.hpp>\n#include <gsl/gsl>\n\n#include \"base-utils/commandUtils.h\"\n#include \"base-utils/execution.h\"\n#include \"base-utils/tmpFile.h\"\n\nnamespace execHelper {\nnamespace test {\nnamespace baseUtils {\nclass IoService {\n  public:\n    IoService() = default;\n    IoService(const IoService& other) = delete;\n    IoService(IoService&& other) = delete;\n    ~IoService() noexcept;\n\n    IoService& operator=(const IoService& other) = delete;\n    IoService& operator=(IoService&& other) = delete;\n\n    void start() noexcept;\n    void stop() noexcept;\n    void run() noexcept;\n\n    boost::asio::io_service& get() noexcept;\n\n  private:\n    boost::asio::io_context m_service;\n    std::atomic<bool> m_isRunning = {false};\n    std::thread m_thread;\n};\n\nstruct ExecutionContentData {\n    std::vector<std::string> args;\n    std::map<std::string, std::string> env;\n\n    template <typename Archive>\n    void serialize(Archive& ar, const unsigned int /*version*/) {\n        ar& args& env;\n    }\n};\n\nstruct ExecutionContentDataReply {\n    ReturnCode returnCode;\n\n    ExecutionContentDataReply(ReturnCode returnCode) noexcept\n        : returnCode(returnCode) {\n        ;\n    }\n};\n\nclass ExecutionContentServer {\n  public:\n    using ConfigCommand = std::vector<std::string>;\n\n    ExecutionContentServer(ReturnCode returnCode) noexcept;\n    ~ExecutionContentServer() noexcept;\n\n    ExecutionContentServer(const ExecutionContentServer& other) = delete;\n    ExecutionContentServer(ExecutionContentServer&& other) noexcept;\n\n    ExecutionContentServer&\n    operator=(const ExecutionContentServer& other) = delete;\n    ExecutionContentServer& operator=(ExecutionContentServer&& other) noexcept;\n\n    void swap(ExecutionContentServer& other) noexcept;\n\n    ConfigCommand getConfigCommand() const noexcept;\n    unsigned int getNumberOfExecutions() const noexcept;\n    const std::vector<ExecutionContentData>& getReceivedData() const noexcept;\n\n    void clear() noexcept;\n\n    static void registerIoService(gsl::not_null<IoService*> ioService) noexcept;\n\n  private:\n    /**\n     * Opens the acceptor explicitly rather than using the appropriate constructor for it. This is to work around\n     * the fact that the appropriate constructor will throw, causing an exception to leak out of the interface\n     *\n     * \\throws boost::system::system_error  If the acceptor can not be opened\n     */\n    void openAcceptor();\n    void init() noexcept;\n    void accept() noexcept;\n    ExecutionContentDataReply addData(ExecutionContentData data) noexcept;\n\n    std::vector<ExecutionContentData> m_receivedData;\n    uint32_t m_numberOfExecutions = {0};\n    ReturnCode m_returnCode = {SUCCESS};\n    TmpFile m_file;\n    boost::asio::local::stream_protocol::endpoint m_endpoint;\n    boost::asio::local::stream_protocol::socket m_socket;\n    boost::asio::local::stream_protocol::acceptor m_acceptor;\n\n    static IoService* m_ioService;\n};\nusing ExecutionContent = ExecutionContentServer;\n\nclass ExecutionContentClient {\n  public:\n    ExecutionContentClient(const Path& file);\n\n    ReturnCode addExecution(const ExecutionContentData& data);\n\n  private:\n    boost::asio::local::stream_protocol::endpoint m_endpoint;\n};\n} // namespace baseUtils\n} // namespace test\n} // namespace execHelper\n\n#endif /* EXECUTION_CONTENT_INCLUDE */\n", "meta": {"hexsha": "b1b13f07632ffda0542dea89e372d4a5688e68bc", "size": 3532, "ext": "h", "lang": "C", "max_stars_repo_path": "test/base-utils/include/base-utils/executionContent.h", "max_stars_repo_name": "exec-helper/source", "max_stars_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-28T13:24:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-28T13:24:30.000Z", "max_issues_repo_path": "test/base-utils/include/base-utils/executionContent.h", "max_issues_repo_name": "exec-helper/source", "max_issues_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/base-utils/include/base-utils/executionContent.h", "max_forks_repo_name": "exec-helper/source", "max_forks_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-07-03T11:11:19.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-03T11:11:19.000Z", "avg_line_length": 28.256, "max_line_length": 113, "alphanum_fraction": 0.729614949, "num_tokens": 787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.021287354897989066, "lm_q2_score": 0.012053782222353336, "lm_q1q2_score": 0.00025659314003030685}}
{"text": "//\n//  Author  : github.com/luncliff (luncliff@gmail.com)\n//  License : CC BY 4.0\n//\n//  Note\n//      Test framework adapter\n//\n#pragma once\n\n#include <gsl/gsl>\n\nvoid _require_(bool expr);\nvoid _require_(bool expr, gsl::czstring<> file, size_t line);\nvoid _println_(gsl::czstring<> message);\n\nvoid _fail_now_(gsl::czstring<> message, //\n                gsl::czstring<> file = __FILE__, size_t line = __LINE__);\n", "meta": {"hexsha": "7fa3cbb660e56f7baa3f0ac7ac9fdab8d6b7de87", "size": 411, "ext": "h", "lang": "C", "max_stars_repo_path": "test/test.h", "max_stars_repo_name": "Farwaykorse/coroutine", "max_stars_repo_head_hexsha": "cfe7f0ca5ab4670e539a9f4d6c69d85ba4cb18f7", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test.h", "max_issues_repo_name": "Farwaykorse/coroutine", "max_issues_repo_head_hexsha": "cfe7f0ca5ab4670e539a9f4d6c69d85ba4cb18f7", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test.h", "max_forks_repo_name": "Farwaykorse/coroutine", "max_forks_repo_head_hexsha": "cfe7f0ca5ab4670e539a9f4d6c69d85ba4cb18f7", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8333333333, "max_line_length": 73, "alphanum_fraction": 0.6569343066, "num_tokens": 122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.017176705993640892, "lm_q2_score": 0.014281935786890628, "lm_q1q2_score": 0.0002453166120314786}}
{"text": "/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */\n/*\n *     Copyright 2018 Couchbase, Inc.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n */\n\n#pragma once\n\n#include \"engine_error.h\"\n#include \"protocol_binary.h\"\n#include \"rbac.h\"\n#include \"types.h\"\n\n#include <mcbp/protocol/opcode.h>\n#include <nlohmann/json_fwd.hpp>\n#include <gsl/gsl>\n#include <string>\n\n/**\n * Commands to operate on a specific cookie.\n */\nstruct ServerCookieIface {\n    virtual ~ServerCookieIface() = default;\n\n    /**\n     * Store engine-specific session data on the given cookie.\n     *\n     * The engine interface allows for a single item to be\n     * attached to the connection that it can use to track\n     * connection-specific data throughout duration of the\n     * connection.\n     *\n     * @param cookie The cookie provided by the frontend\n     * @param engine_data pointer to opaque data\n     */\n    virtual void store_engine_specific(gsl::not_null<const void*> cookie,\n                                       void* engine_data) = 0;\n\n    /**\n     * Retrieve engine-specific session data for the given cookie.\n     *\n     * @param cookie The cookie provided by the frontend\n     *\n     * @return the data provied by store_engine_specific or NULL\n     *         if none was provided\n     */\n    virtual void* get_engine_specific(gsl::not_null<const void*> cookie) = 0;\n\n    /**\n     * Check if datatype is supported by the connection.\n     *\n     * @param cookie The cookie provided by the frontend\n     * @param datatype The datatype to test\n     *\n     * @return true if connection supports the datatype or else false.\n     */\n    virtual bool is_datatype_supported(gsl::not_null<const void*> cookie,\n                                       protocol_binary_datatype_t datatype) = 0;\n\n    /**\n     * Check if mutation extras is supported by the connection.\n     *\n     * @param cookie The cookie provided by the frontend\n     *\n     * @return true if supported or else false.\n     */\n    virtual bool is_mutation_extras_supported(\n            gsl::not_null<const void*> cookie) = 0;\n\n    /**\n     * Check if collections are supported by the connection.\n     *\n     * @param cookie The cookie provided by the frontend\n     *\n     * @return true if supported or else false.\n     */\n    virtual bool is_collections_supported(\n            gsl::not_null<const void*> cookie) = 0;\n\n    /**\n     * Retrieve the opcode of the connection, if\n     * ewouldblock flag is set. Please note that the ewouldblock\n     * flag for a connection is cleared before calling into\n     * the engine interface, so this method only works in the\n     * notify hooks.\n     *\n     * @param cookie The cookie provided by the frontend\n     *\n     * @return the opcode from the binary_header saved in the\n     * connection.\n     */\n    virtual cb::mcbp::ClientOpcode get_opcode_if_ewouldblock_set(\n            gsl::not_null<const void*> cookie) = 0;\n\n    /**\n     * Validate given ns_server's session cas token against\n     * saved token in memached, and if so incrment the session\n     * counter.\n     *\n     * @param cas The cas token from the request\n     *\n     * @return true if session cas matches the one saved in\n     * memcached\n     */\n    virtual bool validate_session_cas(uint64_t cas) = 0;\n\n    /**\n     * Decrement session_cas's counter everytime a control\n     * command completes execution.\n     */\n    virtual void decrement_session_ctr() = 0;\n\n    /**\n     * Let a connection know that IO has completed.\n     * @param cookie cookie representing the connection\n     * @param status the status for the io operation\n     */\n    virtual void notify_io_complete(gsl::not_null<const void*> cookie,\n                                    ENGINE_ERROR_CODE status) = 0;\n\n    /**\n     * Notify the core that we're holding on to this cookie for\n     * future use. (The core guarantees it will not invalidate the\n     * memory until the cookie is invalidated by calling release())\n     */\n    virtual ENGINE_ERROR_CODE reserve(gsl::not_null<const void*> cookie) = 0;\n\n    /**\n     * Notify the core that we're releasing the reference to the\n     * The engine is not allowed to use the cookie (the core may invalidate\n     * the memory)\n     */\n    virtual ENGINE_ERROR_CODE release(gsl::not_null<const void*> cookie) = 0;\n\n    /**\n     * Set the priority for this connection\n     */\n    virtual void set_priority(gsl::not_null<const void*> cookie,\n                              CONN_PRIORITY priority) = 0;\n\n    /**\n     * Get the priority for this connection\n     */\n    virtual CONN_PRIORITY get_priority(gsl::not_null<const void*> cookie) = 0;\n\n    /**\n     * Get the bucket the connection is bound to\n     *\n     * @cookie The connection object\n     * @return the bucket identifier for a cookie\n     */\n    virtual bucket_id_t get_bucket_id(gsl::not_null<const void*> cookie) = 0;\n\n    /**\n     * Get connection id\n     *\n     * @param cookie the cookie sent to the engine for an operation\n     * @return a unique identifier for a connection\n     */\n    virtual uint64_t get_connection_id(gsl::not_null<const void*> cookie) = 0;\n\n    /**\n     * Check if the cookie have the specified privilege in it's\n     * active set.\n     *\n     * @todo We should probably add the key we want to access as part\n     *       of the API. We're going to need that when we're adding\n     *       support for collections. For now let's assume that it\n     *       won't be a big problem to fix that later on.\n     * @param cookie the cookie sent to the engine for an operation\n     * @param privilege the privilege to check for\n     * @return true if the cookie have the privilege in its active set,\n     *         false otherwise\n     */\n    virtual cb::rbac::PrivilegeAccess check_privilege(\n            gsl::not_null<const void*> cookie,\n            cb::rbac::Privilege privilege) = 0;\n\n    /**\n     * Method to map an engine error code to the appropriate mcbp response\n     * code (the client may not support all error codes so we may have\n     * to remap some).\n     *\n     * @param cookie the client cookie (to look up the client connection)\n     * @param code the engine error code to get the mcbp response code.\n     * @return the mcbp response status to use\n     * @throws std::engine_error if the error code results in being\n     *                           ENGINE_DISCONNECT after remapping\n     *         std::logic_error if the error code doesn't make sense\n     *         std::invalid_argument if the code doesn't exist\n     */\n    virtual cb::mcbp::Status engine_error2mcbp(\n            gsl::not_null<const void*> cookie, ENGINE_ERROR_CODE code) = 0;\n\n    /**\n     * Get the log information to be used for a log entry.\n     *\n     * The typical log entry from the core is:\n     *\n     *  `id> message` - Data read from ta client\n     *  `id: message` - Status messages for this client\n     *  `id< message` - Data sent back to the client\n     *\n     * If the caller wants to dump more information about the connection\n     * (like socket name, peer name, user name) the pair returns this\n     * info as the second field. The info may be invalidated by the core\n     * at any time (but not while the engine is operating in a single call\n     * from the core) so it should _not_ be cached.\n     */\n    virtual std::pair<uint32_t, std::string> get_log_info(\n            gsl::not_null<const void*> cookie) = 0;\n\n    virtual std::string get_authenticated_user(\n            gsl::not_null<const void*> cookie) = 0;\n\n    virtual in_port_t get_connected_port(gsl::not_null<const void*> cookie) = 0;\n\n    /**\n     * Set the error context string to be sent in response. This should not\n     * contain security sensitive information. If sensitive information needs to\n     * be preserved, log it with a UUID and send the UUID.\n     *\n     * Note this has no affect for the following response codes.\n     *   cb::mcbp::Status::Success\n     *   cb::mcbp::Status::SubdocSuccessDeleted\n     *   cb::mcbp::Status::SubdocMultiPathFailure\n     *   cb::mcbp::Status::Rollback\n     *   cb::mcbp::Status::NotMyVbucket\n     *\n     * @param cookie the client cookie (to look up client connection)\n     * @param message the message string to be set as the error context\n     */\n    virtual void set_error_context(gsl::not_null<void*> cookie,\n                                   cb::const_char_buffer message) = 0;\n\n    /**\n     * Set a JSON object to be included in an error response (along side\n     * anything set by set_error_context).\n     *\n     * The json object cannot include \"error\" as a top-level key\n     *\n     * Note this has no affect for the following response codes.\n     *   cb::mcbp::Status::Success\n     *   cb::mcbp::Status::SubdocSuccessDeleted\n     *   cb::mcbp::Status::SubdocMultiPathFailure\n     *   cb::mcbp::Status::Rollback\n     *   cb::mcbp::Status::NotMyVbucket\n     *\n     * @param cookie the client cookie (to look up client connection)\n     * @param json extra json object to include in a error response.\n     */\n    virtual void set_error_json_extras(gsl::not_null<void*> cookie,\n                                       const nlohmann::json& json) = 0;\n};\n", "meta": {"hexsha": "c10951d9ed684f594a8fd3584729747c5fe01a21", "size": 9673, "ext": "h", "lang": "C", "max_stars_repo_path": "include/memcached/server_cookie_iface.h", "max_stars_repo_name": "scwright027/kv_engine", "max_stars_repo_head_hexsha": "6fc9dc957844f077d44dc6992794ffe35e91e1f7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-13T07:33:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-13T07:33:09.000Z", "max_issues_repo_path": "include/memcached/server_cookie_iface.h", "max_issues_repo_name": "paolococchi/kv_engine", "max_issues_repo_head_hexsha": "40256dca6bf77fb4bcc18e8ef7d9b8f991bf4e45", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/memcached/server_cookie_iface.h", "max_forks_repo_name": "paolococchi/kv_engine", "max_forks_repo_head_hexsha": "40256dca6bf77fb4bcc18e8ef7d9b8f991bf4e45", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-01-15T16:52:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-15T16:52:37.000Z", "avg_line_length": 36.3646616541, "max_line_length": 80, "alphanum_fraction": 0.642199938, "num_tokens": 2283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.02595735644428767, "lm_q2_score": 0.009268011251587797, "lm_q1q2_score": 0.00024057307158713314}}
{"text": "/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*/\n// Portions Copyright (c) Microsoft Corporation\n\n#pragma once\n\n#include <functional>\n#include <memory>\n#include <string>\n#include <unordered_map>\n#include <vector>\n#include <gsl/pointers>\n\n#include \"core/common/common.h\"\n#include \"core/common/callback.h\"\n#include \"core/platform/env_time.h\"\n\n#ifndef _WIN32\n#include <sys/types.h>\n#include <unistd.h>\n#endif\n\nnamespace onnxruntime {\n\n#ifdef _WIN32\nusing PIDType = unsigned long;\n#else\nusing PIDType = pid_t;\n#endif\n\n/// \\brief An interface used by the onnxruntime implementation to\n/// access operating system functionality like the filesystem etc.\n///\n/// Callers may wish to provide a custom Env object to get fine grain\n/// control.\n///\n/// All Env implementations are safe for concurrent access from\n/// multiple threads without any external synchronization.\nclass Env {\n public:\n  virtual ~Env() = default;\n\n  /// \\brief Returns a default environment suitable for the current operating\n  /// system.\n  ///\n  /// Sophisticated users may wish to provide their own Env\n  /// implementation instead of relying on this default environment.\n  ///\n  /// The result of Default() belongs to this library and must never be deleted.\n  static const Env& Default();\n\n  virtual int GetNumCpuCores() const = 0;\n\n  /// \\brief Returns the number of micro-seconds since the Unix epoch.\n  virtual uint64_t NowMicros() const { return env_time_->NowMicros(); }\n\n  /// \\brief Returns the number of seconds since the Unix epoch.\n  virtual uint64_t NowSeconds() const { return env_time_->NowSeconds(); }\n\n  /// Sleeps/delays the thread for the prescribed number of micro-seconds.\n  /// On Windows, it's the min time to sleep, not the actual one.\n  virtual void SleepForMicroseconds(int64_t micros) const = 0;\n\n#ifndef _WIN32\n  /**\n   *\n   * \\param file_path file_path must point to a regular file, which can't be a pipe/socket/...\n   * \\param[out] p  allocated buffer with the file data\n   * \\param[in] offset file offset. If offset>0, then len must also be >0.\n   * \\param[in, out] len length to read(or has read). If len==0, read the whole file.\n   * @return\n   */\n  virtual common::Status ReadFileAsString(const char* file_path, off_t offset, void*& p, size_t& len,\n      OrtCallback& deleter) const = 0;\n#else\n  virtual common::Status ReadFileAsString(const wchar_t* file_path, int64_t offset, void*& p, size_t& len,\n                                          OrtCallback& deleter) const = 0;\n#endif\n\n#ifdef _WIN32\n  //Mainly for use with protobuf library\n  virtual common::Status FileOpenRd(const std::wstring& path, /*out*/ int& fd) const = 0;\n  //Mainly for use with protobuf library\n  virtual common::Status FileOpenWr(const std::wstring& path, /*out*/ int& fd) const = 0;\n#endif\n  //Mainly for use with protobuf library\n  virtual common::Status FileOpenRd(const std::string& path, /*out*/ int& fd) const = 0;\n  //Mainly for use with protobuf library\n  virtual common::Status FileOpenWr(const std::string& path, /*out*/ int& fd) const = 0;\n  //Mainly for use with protobuf library\n  virtual common::Status FileClose(int fd) const = 0;\n  //This functions is always successful. It can't fail.\n  virtual PIDType GetSelfPid() const = 0;\n\n  // \\brief Load a dynamic library.\n  //\n  // Pass \"library_filename\" to a platform-specific mechanism for dynamically\n  // loading a library.  The rules for determining the exact location of the\n  // library are platform-specific and are not documented here.\n  //\n  // On success, returns a handle to the library in \"*handle\" and returns\n  // OK from the function.\n  // Otherwise returns nullptr in \"*handle\" and an error status from the\n  // function.\n  virtual common::Status LoadDynamicLibrary(const std::string& library_filename, void** handle) const = 0;\n\n  virtual common::Status UnloadDynamicLibrary(void* handle) const = 0;\n\n  // \\brief Get a pointer to a symbol from a dynamic library.\n  //\n  // \"handle\" should be a pointer returned from a previous call to LoadDynamicLibrary.\n  // On success, store a pointer to the located symbol in \"*symbol\" and return\n  // OK from the function. Otherwise, returns nullptr in \"*symbol\" and an error\n  // status from the function.\n  virtual common::Status GetSymbolFromLibrary(void* handle, const std::string& symbol_name, void** symbol) const = 0;\n\n  // \\brief build the name of dynamic library.\n  //\n  // \"name\" should be name of the library.\n  // \"version\" should be the version of the library or NULL\n  // returns the name that LoadDynamicLibrary() can use\n  virtual std::string FormatLibraryFileName(const std::string& name, const std::string& version) const = 0;\n\n protected:\n  Env();\n\n private:\n  ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(Env);\n  EnvTime* env_time_ = EnvTime::Default();\n};\n\n}  // namespace onnxruntime\n", "meta": {"hexsha": "d27cdbaae68332b88f3c475fd128327ff8782b78", "size": 5410, "ext": "h", "lang": "C", "max_stars_repo_path": "onnxruntime/core/platform/env.h", "max_stars_repo_name": "dahburj/onnxruntime", "max_stars_repo_head_hexsha": "cd5f74be6250a5a672decc1fd234e200dac36878", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-07-12T16:33:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-12T16:33:33.000Z", "max_issues_repo_path": "onnxruntime/core/platform/env.h", "max_issues_repo_name": "dahburj/onnxruntime", "max_issues_repo_head_hexsha": "cd5f74be6250a5a672decc1fd234e200dac36878", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-10-08T14:20:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-19T16:56:52.000Z", "max_forks_repo_path": "onnxruntime/core/platform/env.h", "max_forks_repo_name": "dahburj/onnxruntime", "max_forks_repo_head_hexsha": "cd5f74be6250a5a672decc1fd234e200dac36878", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:23:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-13T12:00:20.000Z", "avg_line_length": 37.3103448276, "max_line_length": 117, "alphanum_fraction": 0.7129390018, "num_tokens": 1292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.01262494909581309, "lm_q2_score": 0.018546564478212332, "lm_q1q2_score": 0.00023414943243964595}}
{"text": "#ifndef LOGGER_INCLUDE\n#define LOGGER_INCLUDE\n\n#include <gsl/string_span>\n\n#include \"log.h\"\nBOOST_LOG_GLOBAL_LOGGER(\n    exec_helper_log_logger,\n    execHelper::log::LoggerType); // NOLINT(modernize-use-using)\n\nstatic const gsl::czstring<> LOG_CHANNEL = \"log\";\n#define LOG(x)                                                                 \\\n    BOOST_LOG_STREAM_CHANNEL_SEV(exec_helper_log_logger::get(), LOG_CHANNEL,   \\\n                                 x)                                            \\\n        << boost::log::add_value(fileLog, __FILE__)                            \\\n        << boost::log::add_value(lineLog, __LINE__)\n\n#endif /* LOGGER_INCLUDE */\n", "meta": {"hexsha": "edd5ed8a5a95fbf2c183eae122622efb06f0a496", "size": 666, "ext": "h", "lang": "C", "max_stars_repo_path": "src/log/include/log/logger.h", "max_stars_repo_name": "exec-helper/source", "max_stars_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-28T13:24:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-28T13:24:30.000Z", "max_issues_repo_path": "src/log/include/log/logger.h", "max_issues_repo_name": "exec-helper/source", "max_issues_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/log/include/log/logger.h", "max_forks_repo_name": "exec-helper/source", "max_forks_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-07-03T11:11:19.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-03T11:11:19.000Z", "avg_line_length": 35.0526315789, "max_line_length": 80, "alphanum_fraction": 0.536036036, "num_tokens": 128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.014728610822350248, "lm_q2_score": 0.015663647074695697, "lm_q1q2_score": 0.00023070376182183784}}
{"text": "//\n// CI Hello World\n//\n// Copyright (C) 2017 Assured Information Security, Inc.\n// Author: Rian Quinn        <quinnr@ainfosec.com>\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#ifndef CONSUMER_H\n#define CONSUMER_H\n\n#include <gsl/gsl>\n#include <producer.h>\n\n/// Consumer\n///\n/// A simple example of a consumer that is capable of accepting the real\n/// producer, or a mocked version for unit testing.\n///\nclass consumer\n{\npublic:\n\n    /// Default Constructor\n    ///\n    /// @param p the producer that this consumer will use.\n    ///\n    explicit consumer(gsl::not_null<producer *> p)\n    { p->print_msg(); }\n\n    /// Default Destructor\n    ///\n    ~consumer() = default;\n\npublic:\n\n    // We define the copy and move constructors / operators because Clang Tidy\n    // (legitimately) complains about the definition of a destructor without\n    // defining the copy and move semantics for this class. In general a class\n    // should always be marked non-copyable unless such functionality is\n    // specifically desired.\n\n    consumer(consumer &&) noexcept = default;               ///< Default move construction\n    consumer &operator=(consumer &&) noexcept = default;    ///< Default move operator\n\n    consumer(const consumer &) = delete;                    ///< Deleted copy construction\n    consumer &operator=(const consumer &) = delete;         ///< Deleted copy operator\n};\n\n#endif", "meta": {"hexsha": "a120441f65363c4dfb1258e11bb04fc3a77664a2", "size": 2417, "ext": "h", "lang": "C", "max_stars_repo_path": "include/consumer.h", "max_stars_repo_name": "lopezfjose/GPP", "max_stars_repo_head_hexsha": "88291129c30fff188d6fa8137dec8900ac3dd5ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/consumer.h", "max_issues_repo_name": "lopezfjose/GPP", "max_issues_repo_head_hexsha": "88291129c30fff188d6fa8137dec8900ac3dd5ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-01-31T04:26:44.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-31T04:34:58.000Z", "max_forks_repo_path": "include/consumer.h", "max_forks_repo_name": "lopezfjose/GPP", "max_forks_repo_head_hexsha": "88291129c30fff188d6fa8137dec8900ac3dd5ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6212121212, "max_line_length": 90, "alphanum_fraction": 0.7070748862, "num_tokens": 513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.016914916240187736, "lm_q2_score": 0.013636835356592481, "lm_q1q2_score": 0.0002306659278379925}}
{"text": "#pragma once\n\n#include \"poll_event.h\"\n#include \"poll_response.h\"\n#include \"poll_target.h\"\n\n#include <cstddef>\n#include <optional>\n#include <string>\n#include <vector>\n\n#include <gsl/span>\n\nnamespace wrappers::zmq {\n\nclass context;\n\nclass socket final {\n\npublic:\n    enum class type {\n        pair,\n        pub,\n        sub,\n        req,\n        rep,\n        dealer,\n        router,\n        pull,\n        push,\n        xpub,\n        xsub,\n        stream,\n    };\n\n    explicit socket(context &ctx, type socket_type) noexcept;\n    socket(const socket &other) = delete;\n    socket &operator=(const socket &other) = delete;\n    socket(socket &&other) noexcept;\n    socket &operator=(socket &&other) noexcept;\n    ~socket() noexcept;\n\n    [[nodiscard]] bool bind(const std::string &endpoint) noexcept;\n\n    [[nodiscard]] bool connect(const std::string &endpoint) noexcept;\n\n    [[nodiscard]] bool blocking_send() noexcept;\n    [[nodiscard]] bool blocking_send(gsl::span<std::byte> message) noexcept;\n\n    [[nodiscard]] std::optional<std::vector<std::byte>>\n    blocking_receive() noexcept;\n\n    [[nodiscard]] bool\n    async_receive(void *data,\n                  void (*callback)(void *, gsl::span<std::byte>)) noexcept;\n\n    friend std::optional<std::vector<poll_response>>\n    blocking_poll(gsl::span<poll_target> targets) noexcept;\n\nprivate:\n    void *m_socket = nullptr;\n};\n\n} // namespace wrappers::zmq\n", "meta": {"hexsha": "f7b41233c09db224b291b007d63906e9dc56e837", "size": 1400, "ext": "h", "lang": "C", "max_stars_repo_path": "src/wrappers/zmq/socket.h", "max_stars_repo_name": "Longhanks/linkollector-win", "max_stars_repo_head_hexsha": "a76b08fa4f20a3612988a0d84e5b14f7822638ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/wrappers/zmq/socket.h", "max_issues_repo_name": "Longhanks/linkollector-win", "max_issues_repo_head_hexsha": "a76b08fa4f20a3612988a0d84e5b14f7822638ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/wrappers/zmq/socket.h", "max_forks_repo_name": "Longhanks/linkollector-win", "max_forks_repo_head_hexsha": "a76b08fa4f20a3612988a0d84e5b14f7822638ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5384615385, "max_line_length": 76, "alphanum_fraction": 0.6328571429, "num_tokens": 320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.017442488822281704, "lm_q2_score": 0.013020490281400236, "lm_q1q2_score": 0.00022710975619395115}}
{"text": "/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */\n/*\n *     Copyright 2018-Present Couchbase, Inc.\n *\n *   Use of this software is governed by the Business Source License included\n *   in the file licenses/BSL-Couchbase.txt.  As of the Change Date specified\n *   in that file, in accordance with the Business Source License, use of this\n *   software will be governed by the Apache License, Version 2.0, included in\n *   the file licenses/APL2.txt.\n */\n\n#pragma once\n\n#include <mcbp/protocol/response.h>\n#include <mcbp/protocol/status.h>\n#include <nlohmann/json_fwd.hpp>\n#include <platform/thread.h>\n#include <chrono>\n#include <gsl/gsl>\n#include <mutex>\n#include <queue>\n#include <unordered_map>\n#include <vector>\n\nclass Connection;\nclass AuthnAuthzServiceTask;\n\n/**\n * The ExternalAuthManagerThread class takes care of the scheduling between\n * the authentication requests and the responses received.\n *\n * One of the problems is that we try to communicate between multiple\n * frontend threads, which could cause deadlocks. To avoid locking\n * problems we're using a dedicated thread to communicate with the\n * other threads.\n */\nclass ExternalAuthManagerThread : public Couchbase::Thread {\npublic:\n    ExternalAuthManagerThread() : Couchbase::Thread(\"mcd:ext_auth\") {\n    }\n    ExternalAuthManagerThread(const ExternalAuthManagerThread&) = delete;\n\n    /**\n     * The named (external) user logged on to the system\n     */\n    void login(const std::string& user);\n\n    /**\n     * The named (external) user logged off the system\n     */\n    void logoff(const std::string& user);\n\n    /**\n     * Get the list of active users defined in the system\n     */\n    nlohmann::json getActiveUsers() const;\n\n    /**\n     * Add the provided connection to the list of available authentication\n     * providers\n     */\n    void add(Connection& connection);\n\n    /**\n     * Remove the connection from the list of available providers (the\n     * connection may not be registered)\n     */\n    void remove(Connection& connection);\n\n    /**\n     * Enqueue a SASL request to the list of requests to send to the\n     * RBAC provider. NOTE: This method must _NOT_ be called from the\n     * worker threads as that may result in a deadlock (should be\n     * called from the tasks execute() method when running on the\n     * executor threads)\n     *\n     * @param request the task to notify when the result comes back\n     */\n    void enqueueRequest(AuthnAuthzServiceTask& request);\n\n    /**\n     * Received an authentication response on the provided connection\n     *\n     * @param connection the connection the message was received on\n     * @param response\n     */\n    void responseReceived(const cb::mcbp::Response& response);\n\n    /**\n     * Request the authentication daemon to stop\n     */\n    void shutdown();\n\n    void setPushActiveUsersInterval(std::chrono::microseconds interval) {\n        activeUsersPushInterval.store(interval);\n        condition_variable.notify_one();\n    }\n\n    void setRbacCacheEpoch(std::chrono::steady_clock::time_point tp);\n\n    /// Check to see if we've got an up to date RBAC entry for the user\n    bool haveRbacEntryForUser(const std::string& user) const;\n\nprotected:\n    /// The main loop of the thread\n    void run() override;\n\n    /**\n     * Process all of the requests added by the various SaslTasks by putting\n     * them into the queue of messages to send to the Authentication Provider.\n     */\n    void processRequestQueue();\n    /**\n     * Process all of the response messages enqueued and notify the SaslTask\n     */\n    void processResponseQueue();\n\n    /**\n     * Iterate over all of the connections marked as closed. Generate\n     * error responses for all outstanding requests; decrement the reference\n     * count and tell the thread to complete its shutdown logic.\n     */\n    void purgePendingDeadConnections();\n\n    /// Push the list of active users to the authentication provider\n    void pushActiveUsers();\n\n    /// Let the daemon thread run as long as this member is set to true\n    bool running = true;\n\n    /// The next value to use in the opaque field\n    uint32_t next = 0;\n\n    /// The map between the opaque field being used and the SaslAuthTask\n    /// requested the operation\n    /// Second should be a std pair of a connection and a task, so that\n    /// when we remove a connection we can iterate over the entire\n    /// map and create aborts for the one we don't have anymore (or\n    /// we could redistribute them O:)\n    std::unordered_map<uint32_t, std::pair<Connection*, AuthnAuthzServiceTask*>>\n            requestMap;\n\n    /// The mutex variable used to protect access to _all_ the internal\n    /// members\n    std::mutex mutex;\n    /// The daemon thread will block and wait on this variable when there\n    /// isn't any work to do\n    std::condition_variable condition_variable;\n\n    /// A list of available connections to use as authentication providers\n    std::vector<Connection*> connections;\n\n    /**\n     * All of the various tasks enqueue their SASL request in this queue\n     * to allow the authentication provider thread to inject them into\n     * the worker thread (to avoid a possible deadlock)\n     */\n    std::queue<AuthnAuthzServiceTask*> incomingRequests;\n\n    /**\n     * We need to pass the response information from one of the frontend\n     * thread back to the sasl task, and we'd like to use the same\n     * logic when we're terminating the connections.\n     */\n    struct AuthResponse {\n        AuthResponse(uint32_t opaque, std::string payload)\n            : opaque(opaque),\n              status(cb::mcbp::Status::Etmpfail),\n              payload(std::move(payload)) {\n        }\n        AuthResponse(uint32_t opaque,\n                     cb::mcbp::Status status,\n                     cb::const_byte_buffer value)\n            : opaque(opaque),\n              status(status),\n              payload(reinterpret_cast<const char*>(value.data()),\n                      value.size()) {\n        }\n        uint32_t opaque;\n        cb::mcbp::Status status;\n        std::string payload;\n    };\n\n    /**\n     * All of the various responses is stored within this queue to\n     * be handled by the daemon thread\n     */\n    std::queue<std::unique_ptr<AuthResponse>> incommingResponse;\n\n    std::vector<Connection*> pendingRemoveConnection;\n\n    class ActiveUsers {\n    public:\n        void login(const std::string& user);\n\n        void logoff(const std::string& user);\n\n        nlohmann::json to_json() const;\n\n    private:\n        mutable std::mutex mutex;\n        std::unordered_map<std::string, uint32_t> users;\n    } activeUsers;\n\n    /**\n     * The interval we'll push the current active users to the external\n     * authentication service.\n     *\n     * The list can't be considered as \"absolute\" as memcached is a\n     * highly multithreaded application and we may have disconnects\n     * happening in multiple threads at the same time and we might\n     * have login messages waiting to acquire the lock for the map.\n     * The intention with the list is that we'll poll the users from\n     * LDAP to check if the group membership has changed since the last\n     * time we checked. Given that LDAP is an external system and it\n     * can't push change notifications to our system our guarantee\n     * is that the change is reflected in memcached at within 2 times\n     * of the interval we push these users.\n     *\n     * We don't need microseconds resolution \"in production\", but\n     * we don't want to have our unit tests wait multiple seconds\n     * for this message to be sent\n     */\n    std::atomic<std::chrono::microseconds> activeUsersPushInterval{\n            std::chrono::minutes(5)};\n\n    /**\n     * The time point we last sent the list of active users to the auth\n     * provider\n     */\n    std::chrono::steady_clock::time_point activeUsersLastSent;\n\n    /**\n     * It should be possible for the authentication provider to\n     * invalidate the entire cache, but we can't simply drop the\n     * current cache as that would cause all of the connected clients\n     * to be disconnected. Instead the authentication provider may\n     * tell us to start requesting a new RBAC entry if the cached\n     * one is older than a given time point. Combined with the logic\n     * that we'll push all of the connected users the authentication\n     * provider can make sure that all of the connections use the\n     * correct RBAC definition. Ideally we would have stored this\n     * as a std::chrono::steady_clock::TimePoint, but that don't\n     * play well with std::atomic, so we're storing the raw\n     * number of seconds instead.\n     */\n    std::atomic<uint64_t> rbacCacheEpoch{{}};\n};\n\nextern std::unique_ptr<ExternalAuthManagerThread> externalAuthManager;\n", "meta": {"hexsha": "d25291d0131ee00c896b1c54444ce26b3e124f12", "size": 8760, "ext": "h", "lang": "C", "max_stars_repo_path": "daemon/external_auth_manager_thread.h", "max_stars_repo_name": "vpn03/kv_engine", "max_stars_repo_head_hexsha": "a3131a099154c39a0f7b0458bf0cc4ea38363a64", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "daemon/external_auth_manager_thread.h", "max_issues_repo_name": "vpn03/kv_engine", "max_issues_repo_head_hexsha": "a3131a099154c39a0f7b0458bf0cc4ea38363a64", "max_issues_repo_licenses": ["MIT", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "daemon/external_auth_manager_thread.h", "max_forks_repo_name": "vpn03/kv_engine", "max_forks_repo_head_hexsha": "a3131a099154c39a0f7b0458bf0cc4ea38363a64", "max_forks_repo_licenses": ["MIT", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9003984064, "max_line_length": 80, "alphanum_fraction": 0.6753424658, "num_tokens": 1959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.02128734868891348, "lm_q2_score": 0.009859856621902897, "lm_q1q2_score": 0.00020989020593313953}}
{"text": "#pragma once\n\n#include \"AsyncSystem.h\"\n#include \"IAssetRequest.h\"\n#include \"Library.h\"\n\n#include <gsl/span>\n\n#include <cstddef>\n#include <memory>\n#include <string>\n#include <vector>\n\nnamespace CesiumAsync {\nclass AsyncSystem;\n\n/**\n * @brief Provides asynchronous access to assets, usually files downloaded via\n * HTTP.\n */\nclass CESIUMASYNC_API IAssetAccessor {\npublic:\n  /**\n   * @brief An HTTP header represented as a key/value pair.\n   */\n  typedef std::pair<std::string, std::string> THeader;\n\n  virtual ~IAssetAccessor() = default;\n\n  /**\n   * @brief Starts a new request for the asset with the given URL.\n   * The request proceeds asynchronously without blocking the calling thread.\n   *\n   * @param asyncSystem The async system used to do work in threads.\n   * @param url The URL of the asset.\n   * @param headers The headers to include in the request.\n   * @return The in-progress asset request.\n   */\n  virtual CesiumAsync::Future<std::shared_ptr<IAssetRequest>> requestAsset(\n      const AsyncSystem& asyncSystem,\n      const std::string& url,\n      const std::vector<THeader>& headers = {}) = 0;\n\n  /**\n   * @brief Starts a new POST request to the given URL.\n   *\n   * The request proceeds asynchronously without blocking the calling thread.\n   *\n   * @param asyncSystem The async system used to do work in threads.\n   * @param url The URL of the asset.\n   * @param headers The headers to include in the request.\n   * @param contentPayload The payload data of the POST.\n   * @return The in-progress asset request.\n   */\n  virtual CesiumAsync::Future<std::shared_ptr<IAssetRequest>> post(\n      const AsyncSystem& asyncSystem,\n      const std::string& url,\n      const std::vector<THeader>& headers = std::vector<THeader>(),\n      const gsl::span<const std::byte>& contentPayload = {}) = 0;\n\n  /**\n   * @brief Ticks the asset accessor system while the main thread is blocked.\n   *\n   * If the asset accessor is not dependent on the main thread to\n   * dispatch requests, this method does not need to do anything.\n   */\n  virtual void tick() noexcept = 0;\n};\n\n} // namespace CesiumAsync\n", "meta": {"hexsha": "e13f4b68b7d55bd046db3a102864cd6ef8194733", "size": 2096, "ext": "h", "lang": "C", "max_stars_repo_path": "CesiumAsync/include/CesiumAsync/IAssetAccessor.h", "max_stars_repo_name": "JiangMuWen/cesium-native", "max_stars_repo_head_hexsha": "1d9912307336c833b74b7e9b7bc715d0a4e6c7ec", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 154.0, "max_stars_repo_stars_event_min_datetime": "2021-03-30T14:08:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T00:01:43.000Z", "max_issues_repo_path": "CesiumAsync/include/CesiumAsync/IAssetAccessor.h", "max_issues_repo_name": "JiangMuWen/cesium-native", "max_issues_repo_head_hexsha": "1d9912307336c833b74b7e9b7bc715d0a4e6c7ec", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 256.0, "max_issues_repo_issues_event_min_datetime": "2021-03-30T18:12:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:44:21.000Z", "max_forks_repo_path": "CesiumAsync/include/CesiumAsync/IAssetAccessor.h", "max_forks_repo_name": "JiangMuWen/cesium-native", "max_forks_repo_head_hexsha": "1d9912307336c833b74b7e9b7bc715d0a4e6c7ec", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 66.0, "max_forks_repo_forks_event_min_datetime": "2021-03-30T15:14:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T13:38:41.000Z", "avg_line_length": 29.5211267606, "max_line_length": 78, "alphanum_fraction": 0.6946564885, "num_tokens": 496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.01566364917116944, "lm_q2_score": 0.013020488797320396, "lm_q1q2_score": 0.0002039483685583686}}
{"text": "#ifndef STDAFX__H\n#define STDAFX__H\n\n#include <SDKDDKVer.h>\n\n#if !defined(_STL_EXTRA_DISABLED_WARNINGS)\n#define _STL_EXTRA_DISABLED_WARNINGS 4061 4324 4365 4514 4571 4582 4583 4623 4625 4626 4710 4774 4820 4987 5026 5027 5039\n#endif\n\n#if !defined(_SCL_SECURE_NO_WARNINGS)\n#define _SCL_SECURE_NO_WARNINGS 1\n#endif\n\n#if !defined(_CRT_SECURE_NO_WARNINGS)\n#define _CRT_SECURE_NO_WARNINGS 1\n#endif\n\n#if !defined(_SILENCE_CXX17_ITERATOR_BASE_CLASS_DEPRECATION_WARNING)\n#define _SILENCE_CXX17_ITERATOR_BASE_CLASS_DEPRECATION_WARNING 1\n#endif\n\n#define STRICT\n#define NOMINMAX\n\n#pragma warning(disable: 4668) // warning C4668: '%s' is not defined as a preprocessor macro, replacing with '0' for '#if/#elif'\n#pragma warning(disable: 4710) // warning C4710: '%s': function not inlined\n#pragma warning(disable: 4711) // warning C4711: function '%s' selected for automatic inline expansion\n#pragma warning(disable: 4820) // warning C4820: '%s': '%d' bytes padding added after data member '%s'\n\n#pragma warning(push)\n#pragma warning(disable: 5039) // warning C5039: '%s': pointer or reference to potentially throwing function passed to extern C function under -EHc. Undefined behavior may occur if this function throws an exception.\n#include <Windows.h>\n#pragma warning(pop)\n\n#pragma warning(push)\n#pragma warning(disable: 4005) // warning C4005: '%s': macro redefinition\n#include <Winternl.h>\n#include <ntstatus.h>\n#pragma warning(pop)\n\n// disable for everything\n#pragma warning(disable: 4061) // warning C4061: enumerator '%s' in switch of enum '%s' is not explicitly handled by a case label\n#pragma warning(disable: 4324) // warning C4234: structure was padded due to alignment specifier\n#pragma warning(disable: 4514) // warning C4514: '%s': unreferenced inline function has been removed\n#pragma warning(disable: 4623) // warning C4623: '%s': default constructor was implicitly defined as deleted\n#pragma warning(disable: 4625) // warning C4625: '%s': copy constructor was implicitly defined as deleted\n#pragma warning(disable: 4626) // warning C4626: '%s': assignment operator was implicitly defined as deleted\n#pragma warning(disable: 4710) // warning C4710: '%s': function not inlined\n#pragma warning(disable: 4820) // warning C4820: '%s': '%d' bytes padding added after data member '%s'\n#pragma warning(disable: 5026) // warning C5026: '%s': move constructor was implicitly defined as deleted\n#pragma warning(disable: 5027) // warning C5027: '%s': move assignment operator was implicitly defined as deleted\n\n#pragma warning(disable: 26412) // warning C26412: Do not dereference an invalid pointer (lifetimes rule 1). 'return of %s' was invalidated at line %d by 'no initialization'.\n#pragma warning(disable: 26426) // warning C26426: Global initializer calls a non-constexpr function '%s' (i.22: http://go.microsoft.com/fwlink/?linkid=853919).\n#pragma warning(disable: 26481) // warning C26481: Don't use pointer arithmetic. Use span instead. (bounds.1: http://go.microsoft.com/fwlink/p/?LinkID=620413)\n#pragma warning(disable: 26482) // warning C26482: Only index into arrays using constant expressions (bounds.2: http://go.microsoft.com/fwlink/p/?LinkID=620414).\n#pragma warning(disable: 26485) // warning C26485: Expression '%s::`vbtable'': No array to pointer decay. (bounds.3: http://go.microsoft.com/fwlink/p/?LinkID=620415)\n#pragma warning(disable: 26490) // warning C26490: Don't use reinterpret_cast. (type.1: http://go.microsoft.com/fwlink/p/?LinkID=620417)\n#pragma warning(disable: 26499) // warning C26499: Could not find any lifetime tracking information for '%s'\n\n// disable for standard headers\n#pragma warning(push)\n#pragma warning(disable: 5039) // warning C5039: '%s': pointer or reference to potentially throwing function passed to extern C function under -EHc. Undefined behavior may occur if this function throws an exception.\n\n#pragma warning(disable: 26400) // warning C26400: Do not assign the result of an allocation or a function call with an owner<T> return value to a raw pointer, use owner<T> instead. (i.11 http://go.microsoft.com/fwlink/?linkid=845474)\n#pragma warning(disable: 26401) // warning C26401: Do not delete a raw pointer that is not an owner<T>. (i.11: http://go.microsoft.com/fwlink/?linkid=845474)\n#pragma warning(disable: 26408) // warning C26408: Avoid malloc() and free(), prefer the nothrow version of new with delete. (r.10 http://go.microsoft.com/fwlink/?linkid=845483)\n#pragma warning(disable: 26409) // warning C26409: Avoid calling new and delete explicitly, use std::make_unique<T> instead. (r.11 http://go.microsoft.com/fwlink/?linkid=845485)\n#pragma warning(disable: 26411) // warning C26411: The parameter '%s' is a reference to unique pointer and it is never reassigned or reset, use T* or T& instead. (r.33 http://go.microsoft.com/fwlink/?linkid=845479)\n#pragma warning(disable: 26412) // warning C26412: Do not dereference an invalid pointer (lifetimes rule 1). 'return of %s' was invalidated at line %d by 'end of function scope (local lifetimes end)'.\n#pragma warning(disable: 26413) // warning C26413: Do not dereference nullptr (lifetimes rule 2). 'nullptr' was pointed to nullptr at line %d.\n#pragma warning(disable: 26423) // warning C26423: The allocation was not directly assigned to an owner.\n#pragma warning(disable: 26424) // warning C26424: Failing to delete or assign ownership of allocation at line %d.\n#pragma warning(disable: 26425) // warning C26425: Assigning '%s' to a static variable.\n#pragma warning(disable: 26461) // warning C26461: The reference argument '%s' for function %s can be marked as const. (con.3: https://go.microsoft.com/fwlink/p/?LinkID=786684)\n#pragma warning(disable: 26471) // warning C26471: Don't use reinterpret_cast. A cast from void* can use static_cast. (type.1: http://go.microsoft.com/fwlink/p/?LinkID=620417).\n#pragma warning(disable: 26481) // warning C26481: Don't use pointer arithmetic. Use span instead. (bounds.1: http://go.microsoft.com/fwlink/p/?LinkID=620413)\n#pragma warning(disable: 26482) // warning C26482: Only index into arrays using constant expressions. (bounds.2: http://go.microsoft.com/fwlink/p/?LinkID=620414)\n#pragma warning(disable: 26490) // warning C26490: Don't use reinterpret_cast. (type.1: http://go.microsoft.com/fwlink/p/?LinkID=620417)\n#pragma warning(disable: 26493) // warning C26493: Don't use C-style casts that would perform a static_cast downcast, const_cast, or reinterpret_cast. (type.4: http://go.microsoft.com/fwlink/p/?LinkID=620420)\n#pragma warning(disable: 26494) // warning C26494: Variable '%s' is uninitialized. Always initialize an object. (type.5: http://go.microsoft.com/fwlink/p/?LinkID=620421)\n#pragma warning(disable: 26495) // warning C26495: Variable '%s' is uninitialized. Always initialize a member variable. (type.6: http://go.microsoft.com/fwlink/p/?LinkID=620422)\n#pragma warning(disable: 26496) // warning C26496: Variable '%s' is assigned only once, mark it as const. (con.4: https://go.microsoft.com/fwlink/p/?LinkID=784969)\n#pragma warning(disable: 26497) // warning C26497: This function %s could be marked constexpr if compile-time evaluation is desired. (f.4: https://go.microsoft.com/fwlink/p/?LinkID=784970)\n\n#include <cstddef>\n#include <map>\n#include <set>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <iostream>\n#include <iomanip>\n#include <type_traits>\n#include <utility>\n#include <memory>\n#include <tuple>\n#include <thread>\n#include <cstdlib>\n\n// disable additionally for third-party libraries\n#pragma warning(push)\n#pragma warning(disable: 4365) // warning C4365: '%s': conversion from '%s' to '%s', signed/unsigned mismatch\n#pragma warning(disable: 4371) // warning C4371: '%s': layout of class may have changed from a previous version of the compiler due to better packing of member '%s'\n#pragma warning(disable: 4619) // warning C4619: #pragma warning: there is no warning number '%d'\n#pragma warning(disable: 5031) // warning C5031: #pragma warning(pop): likely mismatch, popping warning state pushed in different file\n#pragma warning(disable: 26429) // warning C26429: Symbol '%s' is never tested for nullness, it can be marked as not_null (f.23: http://go.microsoft.com/fwlink/?linkid=853921).\n#pragma warning(disable: 26432) // warning C26432: If you define or delete any default operation in the type '%s', define or delete them all (c.21: http://go.microsoft.com/fwlink/?linkid=853922).\n#pragma warning(disable: 26434) // warning C26434: Function '%s' hides a non-virtual function '%s' (c.128: http://go.microsoft.com/fwlink/?linkid=853923).\n#pragma warning(disable: 26439) // warning C26439: This kind of function may not throw. Declare it 'noexcept' (f.6: http://go.microsoft.com/fwlink/?linkid=853927).\n#pragma warning(disable: 26440) // warning C26440: Function '%s' can be declared 'noexcept' (f.6: http://go.microsoft.com/fwlink/?linkid=853927).\n#pragma warning(disable: 26472) // warning C26472: Don't use a static_cast for arithmetic conversions. Use brace initialization, gsl::narrow_cast or gsl::narow (type.1: http://go.microsoft.com/fwlink/p/?LinkID=620417).\n\n#ifndef BOOST_CONFIG_SUPPRESS_OUTDATED_MESSAGE\n#define BOOST_CONFIG_SUPPRESS_OUTDATED_MESSAGE\n#endif\n\n#include <gsl/gsl>\n\n#include <fmt/format.h>\n\n#pragma warning(pop)\n\n#pragma warning(pop)\n\n#endif\n", "meta": {"hexsha": "eb79b46a24443d028f08b39261d4bc4eae5d947e", "size": 9278, "ext": "h", "lang": "C", "max_stars_repo_path": "cpuid/include/stdafx.h", "max_stars_repo_name": "DrPizza/benchmarking-tools", "max_stars_repo_head_hexsha": "9dadec0b10ec032a31fd68e6614d94be13b66722", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-06-01T06:47:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-29T06:46:52.000Z", "max_issues_repo_path": "cpuid/include/stdafx.h", "max_issues_repo_name": "DrPizza/benchmarking-tools", "max_issues_repo_head_hexsha": "9dadec0b10ec032a31fd68e6614d94be13b66722", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpuid/include/stdafx.h", "max_forks_repo_name": "DrPizza/benchmarking-tools", "max_forks_repo_head_hexsha": "9dadec0b10ec032a31fd68e6614d94be13b66722", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 73.0551181102, "max_line_length": 234, "alphanum_fraction": 0.7588920026, "num_tokens": 2475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.014957087032238704, "lm_q2_score": 0.013428252570462646, "lm_q1q2_score": 0.00020084754238729289}}
{"text": "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\n#pragma once\n\n#include <limits>\n#include <cassert>\n#include <chrono>\n#include <vector>\n#include <map>\n#include <set>\n#include <numeric>\n\n#include <wrl/client.h>\n#include <wrl/implements.h>\n\n#include <wil/wrl.h>\n#include <wil/result.h>\n\n#include <gsl/gsl>\n", "meta": {"hexsha": "6c47e60e63b8de102427d54a5a37a8ff982939d5", "size": 352, "ext": "h", "lang": "C", "max_stars_repo_path": "onnxruntime/core/providers/dml/OperatorAuthorHelper/precomp.h", "max_stars_repo_name": "dennyac/onnxruntime", "max_stars_repo_head_hexsha": "d5175795d2b7f2db18b0390f394a49238f814668", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6036.0, "max_stars_repo_stars_event_min_datetime": "2019-05-07T06:03:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:59:54.000Z", "max_issues_repo_path": "onnxruntime/core/providers/dml/OperatorAuthorHelper/precomp.h", "max_issues_repo_name": "dennyac/onnxruntime", "max_issues_repo_head_hexsha": "d5175795d2b7f2db18b0390f394a49238f814668", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5730.0, "max_issues_repo_issues_event_min_datetime": "2019-05-06T23:04:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:55:56.000Z", "max_forks_repo_path": "onnxruntime/core/providers/dml/OperatorAuthorHelper/precomp.h", "max_forks_repo_name": "dennyac/onnxruntime", "max_forks_repo_head_hexsha": "d5175795d2b7f2db18b0390f394a49238f814668", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1566.0, "max_forks_repo_forks_event_min_datetime": "2019-05-07T01:30:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T17:06:50.000Z", "avg_line_length": 16.7619047619, "max_line_length": 60, "alphanum_fraction": 0.7159090909, "num_tokens": 85, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.016657040985528313, "lm_q2_score": 0.011869121734474592, "lm_q1q2_score": 0.00019770444719336818}}
{"text": "#pragma once\n\n#include <Runtime/Runtime.h>\n#include <napi/napi.h>\n#include <memory>\n#include <gsl/gsl>\n\nnamespace babylon\n{\n    class ScriptHost final\n    {\n    public:\n        explicit ScriptHost(RuntimeImpl&);\n        ScriptHost(const ScriptHost&) = delete;\n        ~ScriptHost();\n\n        void RunScript(gsl::czstring<> script, gsl::czstring<> url);\n\n        Napi::Env& Env();\n\n    private:\n        class Impl;\n        std::unique_ptr<Impl> m_impl;\n    };\n}\n", "meta": {"hexsha": "d2c32c51b9792abfdfcd25c710f5eedcd1dfa528", "size": 461, "ext": "h", "lang": "C", "max_stars_repo_path": "Library/Source/ScriptHost.h", "max_stars_repo_name": "TrevorDev/BabylonNative", "max_stars_repo_head_hexsha": "6d15ec5d418f7f723eba574665233049c785cc72", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Library/Source/ScriptHost.h", "max_issues_repo_name": "TrevorDev/BabylonNative", "max_issues_repo_head_hexsha": "6d15ec5d418f7f723eba574665233049c785cc72", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Library/Source/ScriptHost.h", "max_forks_repo_name": "TrevorDev/BabylonNative", "max_forks_repo_head_hexsha": "6d15ec5d418f7f723eba574665233049c785cc72", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.7307692308, "max_line_length": 68, "alphanum_fraction": 0.6052060738, "num_tokens": 114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.014957087032238702, "lm_q2_score": 0.007937993661358403, "lm_q1q2_score": 0.00011872926205429678}}
